Merge branch 'perfcounters-fixes-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/linux-2.6-tip

* 'perfcounters-fixes-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/linux-2.6-tip: (49 commits)
  perfcounter: Handle some IO return values
  perf_counter: Push perf_sample_data through the swcounter code
  perf_counter tools: Define and use our own u64, s64 etc. definitions
  perf_counter: Close race in perf_lock_task_context()
  perf_counter, x86: Improve interactions with fast-gup
  perf_counter: Simplify and fix task migration counting
  perf_counter tools: Add a data file header
  perf_counter: Update userspace callchain sampling uses
  perf_counter: Make callchain samples extensible
  perf report: Filter to parent set by default
  perf_counter tools: Handle lost events
  perf_counter: Add event overlow handling
  fs: Provide empty .set_page_dirty() aop for anon inodes
  perf_counter: tools: Makefile tweaks for 64-bit powerpc
  perf_counter: powerpc: Add processor back-end for MPC7450 family
  perf_counter: powerpc: Make powerpc perf_counter code safe for 32-bit kernels
  perf_counter: powerpc: Change how processor-specific back-ends get selected
  perf_counter: powerpc: Use unsigned long for register and constraint values
  perf_counter: powerpc: Enable use of software counters on 32-bit powerpc
  perf_counter tools: Add and use isprint()
  ...
diff --git a/Documentation/ABI/testing/sysfs-fs-ext4 b/Documentation/ABI/testing/sysfs-fs-ext4
index 4e79074..5fb7099 100644
--- a/Documentation/ABI/testing/sysfs-fs-ext4
+++ b/Documentation/ABI/testing/sysfs-fs-ext4
@@ -79,3 +79,13 @@
 		This file is read-only and shows the number of
 		kilobytes of data that have been written to this
 		filesystem since it was mounted.
+
+What:		/sys/fs/ext4/<disk>/inode_goal
+Date:		June 2008
+Contact:	"Theodore Ts'o" <tytso@mit.edu>
+Description:
+		Tuning parameter which (if non-zero) controls the goal
+		inode used by the inode allocator in p0reference to
+		all other allocation hueristics.  This is intended for
+		debugging use only, and should be 0 on production
+		systems.
diff --git a/Documentation/ABI/testing/sysfs-pps b/Documentation/ABI/testing/sysfs-pps
new file mode 100644
index 0000000..25028c7
--- /dev/null
+++ b/Documentation/ABI/testing/sysfs-pps
@@ -0,0 +1,73 @@
+What:		/sys/class/pps/
+Date:		February 2008
+Contact:	Rodolfo Giometti <giometti@linux.it>
+Description:
+		The /sys/class/pps/ directory will contain files and
+		directories that will provide a unified interface to
+		the PPS sources.
+
+What:		/sys/class/pps/ppsX/
+Date:		February 2008
+Contact:	Rodolfo Giometti <giometti@linux.it>
+Description:
+		The /sys/class/pps/ppsX/ directory is related to X-th
+		PPS source into the system. Each directory will
+		contain files to manage and control its PPS source.
+
+What:		/sys/class/pps/ppsX/assert
+Date:		February 2008
+Contact:	Rodolfo Giometti <giometti@linux.it>
+Description:
+		The /sys/class/pps/ppsX/assert file reports the assert events
+		and the assert sequence number of the X-th source in the form:
+
+			<secs>.<nsec>#<sequence>
+
+		If the source has no assert events the content of this file
+		is empty.
+
+What:		/sys/class/pps/ppsX/clear
+Date:		February 2008
+Contact:	Rodolfo Giometti <giometti@linux.it>
+Description:
+		The /sys/class/pps/ppsX/clear file reports the clear events
+		and the clear sequence number of the X-th source in the form:
+
+			<secs>.<nsec>#<sequence>
+
+		If the source has no clear events the content of this file
+		is empty.
+
+What:		/sys/class/pps/ppsX/mode
+Date:		February 2008
+Contact:	Rodolfo Giometti <giometti@linux.it>
+Description:
+		The /sys/class/pps/ppsX/mode file reports the functioning
+		mode of the X-th source in hexadecimal encoding.
+
+		Please, refer to linux/include/linux/pps.h for further
+		info.
+
+What:		/sys/class/pps/ppsX/echo
+Date:		February 2008
+Contact:	Rodolfo Giometti <giometti@linux.it>
+Description:
+		The /sys/class/pps/ppsX/echo file reports if the X-th does
+		or does not support an "echo" function.
+
+What:		/sys/class/pps/ppsX/name
+Date:		February 2008
+Contact:	Rodolfo Giometti <giometti@linux.it>
+Description:
+		The /sys/class/pps/ppsX/name file reports the name of the
+		X-th source.
+
+What:		/sys/class/pps/ppsX/path
+Date:		February 2008
+Contact:	Rodolfo Giometti <giometti@linux.it>
+Description:
+		The /sys/class/pps/ppsX/path file reports the path name of
+		the device connected with the X-th source.
+
+		If the source is not connected with any device the content
+		of this file is empty.
diff --git a/Documentation/Changes b/Documentation/Changes
index 6643924..6d0f1ef 100644
--- a/Documentation/Changes
+++ b/Documentation/Changes
@@ -72,6 +72,13 @@
 your kernel.  This change does, however, mean that you need a recent
 release of binutils.
 
+Perl
+----
+
+You will need perl 5 and the following modules: Getopt::Long, Getopt::Std,
+File::Basename, and File::Find to build the kernel.
+
+
 System utilities
 ================
 
diff --git a/Documentation/SubmitChecklist b/Documentation/SubmitChecklist
index ac5e0b2..78a9168 100644
--- a/Documentation/SubmitChecklist
+++ b/Documentation/SubmitChecklist
@@ -54,7 +54,7 @@
     CONFIG_PREEMPT.
 
 14: If the patch affects IO/Disk, etc: has been tested with and without
-    CONFIG_LBD.
+    CONFIG_LBDAF.
 
 15: All codepaths have been exercised with all lockdep features enabled.
 
diff --git a/Documentation/cgroups/memory.txt b/Documentation/cgroups/memory.txt
index 1a60887..23d1262 100644
--- a/Documentation/cgroups/memory.txt
+++ b/Documentation/cgroups/memory.txt
@@ -152,14 +152,19 @@
 
 usage of mem+swap is limited by memsw.limit_in_bytes.
 
-Note: why 'mem+swap' rather than swap.
+* why 'mem+swap' rather than swap.
 The global LRU(kswapd) can swap out arbitrary pages. Swap-out means
 to move account from memory to swap...there is no change in usage of
-mem+swap.
+mem+swap. In other words, when we want to limit the usage of swap without
+affecting global LRU, mem+swap limit is better than just limiting swap from
+OS point of view.
 
-In other words, when we want to limit the usage of swap without affecting
-global LRU, mem+swap limit is better than just limiting swap from OS point
-of view.
+* What happens when a cgroup hits memory.memsw.limit_in_bytes
+When a cgroup his memory.memsw.limit_in_bytes, it's useless to do swap-out
+in this cgroup. Then, swap-out will not be done by cgroup routine and file
+caches are dropped. But as mentioned above, global LRU can do swapout memory
+from it for sanity of the system's memory management state. You can't forbid
+it by cgroup.
 
 2.5 Reclaim
 
@@ -204,6 +209,7 @@
 
 NOTE: We can use a suffix (k, K, m, M, g or G) to indicate values in kilo,
 mega or gigabytes.
+NOTE: We can write "-1" to reset the *.limit_in_bytes(unlimited).
 
 # cat /cgroups/0/memory.limit_in_bytes
 4194304
diff --git a/Documentation/connector/cn_test.c b/Documentation/connector/cn_test.c
index 6977c17..f688eba 100644
--- a/Documentation/connector/cn_test.c
+++ b/Documentation/connector/cn_test.c
@@ -41,6 +41,12 @@
 	       msg->seq, msg->ack, msg->len, (char *)msg->data);
 }
 
+/*
+ * Do not remove this function even if no one is using it as
+ * this is an example of how to get notifications about new
+ * connector user registration
+ */
+#if 0
 static int cn_test_want_notify(void)
 {
 	struct cn_ctl_msg *ctl;
@@ -117,6 +123,7 @@
 	kfree_skb(skb);
 	return -EINVAL;
 }
+#endif
 
 static u32 cn_test_timer_counter;
 static void cn_test_timer_func(unsigned long __data)
diff --git a/Documentation/cpu-freq/cpu-drivers.txt b/Documentation/cpu-freq/cpu-drivers.txt
index 43c7439..75a58d1 100644
--- a/Documentation/cpu-freq/cpu-drivers.txt
+++ b/Documentation/cpu-freq/cpu-drivers.txt
@@ -155,7 +155,7 @@
 - if relation==CPUFREQ_REL_H, try to select a new_freq lower than or equal
   target_freq. ("H for highest, but no higher than")
 
-Here again the frequency table helper might assist you - see section 3
+Here again the frequency table helper might assist you - see section 2
 for details.
 
 
diff --git a/Documentation/cpu-freq/governors.txt b/Documentation/cpu-freq/governors.txt
index ce73f3eb..aed082f 100644
--- a/Documentation/cpu-freq/governors.txt
+++ b/Documentation/cpu-freq/governors.txt
@@ -119,10 +119,6 @@
 what to do about the frequency.  Typically this is set to values of
 around '10000' or more. It's default value is (cmp. with users-guide.txt):
 transition_latency * 1000
-The lowest value you can set is:
-transition_latency * 100 or it may get restricted to a value where it
-makes not sense for the kernel anymore to poll that often which depends
-on your HZ config variable (HZ=1000: max=20000us, HZ=250: max=5000).
 Be aware that transition latency is in ns and sampling_rate is in us, so you
 get the same sysfs value by default.
 Sampling rate should always get adjusted considering the transition latency
@@ -131,14 +127,20 @@
 echo `$(($(cat cpuinfo_transition_latency) * 750 / 1000)) \
     >ondemand/sampling_rate
 
-show_sampling_rate_(min|max): THIS INTERFACE IS DEPRECATED, DON'T USE IT.
-You can use wider ranges now and the general
-cpuinfo_transition_latency variable (cmp. with user-guide.txt) can be
-used to obtain exactly the same info:
-show_sampling_rate_min = transtition_latency * 500    / 1000
-show_sampling_rate_max = transtition_latency * 500000 / 1000
-(divided by 1000 is to illustrate that sampling rate is in us and
-transition latency is exported ns).
+show_sampling_rate_min:
+The sampling rate is limited by the HW transition latency:
+transition_latency * 100
+Or by kernel restrictions:
+If CONFIG_NO_HZ is set, the limit is 10ms fixed.
+If CONFIG_NO_HZ is not set or no_hz=off boot parameter is used, the
+limits depend on the CONFIG_HZ option:
+HZ=1000: min=20000us  (20ms)
+HZ=250:  min=80000us  (80ms)
+HZ=100:  min=200000us (200ms)
+The highest value of kernel and HW latency restrictions is shown and
+used as the minimum sampling rate.
+
+show_sampling_rate_max: THIS INTERFACE IS DEPRECATED, DON'T USE IT.
 
 up_threshold: defines what the average CPU usage between the samplings
 of 'sampling_rate' needs to be for the kernel to make a decision on
diff --git a/Documentation/cpu-freq/user-guide.txt b/Documentation/cpu-freq/user-guide.txt
index 75f4119..5d5f5fa 100644
--- a/Documentation/cpu-freq/user-guide.txt
+++ b/Documentation/cpu-freq/user-guide.txt
@@ -31,7 +31,6 @@
 
 3. How to change the CPU cpufreq policy and/or speed
 3.1 Preferred interface: sysfs
-3.2 Deprecated interfaces
 
 
 
diff --git a/Documentation/feature-removal-schedule.txt b/Documentation/feature-removal-schedule.txt
index 7129846a..f8cd450 100644
--- a/Documentation/feature-removal-schedule.txt
+++ b/Documentation/feature-removal-schedule.txt
@@ -6,6 +6,20 @@
 
 ---------------------------
 
+What:	IRQF_SAMPLE_RANDOM
+Check:	IRQF_SAMPLE_RANDOM
+When:	July 2009
+
+Why:	Many of IRQF_SAMPLE_RANDOM users are technically bogus as entropy
+	sources in the kernel's current entropy model. To resolve this, every
+	input point to the kernel's entropy pool needs to better document the
+	type of entropy source it actually is. This will be replaced with
+	additional add_*_randomness functions in drivers/char/random.c
+
+Who:	Robin Getz <rgetz@blackfin.uclinux.org> & Matt Mackall <mpm@selenic.com>
+
+---------------------------
+
 What:	The ieee80211_regdom module parameter
 When:	March 2010 / desktop catchup
 
@@ -354,16 +368,6 @@
 
 ---------------------------
 
-What:	i2c_attach_client(), i2c_detach_client(), i2c_driver->detach_client(),
-	i2c_adapter->client_register(), i2c_adapter->client_unregister
-When:	2.6.30
-Check:	i2c_attach_client i2c_detach_client
-Why:	Deprecated by the new (standard) device driver binding model. Use
-	i2c_driver->probe() and ->remove() instead.
-Who:	Jean Delvare <khali@linux-fr.org>
-
----------------------------
-
 What:	fscher and fscpos drivers
 When:	June 2009
 Why:	Deprecated by the new fschmd driver.
diff --git a/Documentation/filesystems/Locking b/Documentation/filesystems/Locking
index 3120f8d..229d7b7 100644
--- a/Documentation/filesystems/Locking
+++ b/Documentation/filesystems/Locking
@@ -187,7 +187,7 @@
 write_begin:		no	locks the page		yes
 write_end:		no	yes, unlocks		yes
 perform_write:		no	n/a			yes
-bmap:			yes
+bmap:			no
 invalidatepage:		no	yes
 releasepage:		no	yes
 direct_IO:		no
diff --git a/Documentation/filesystems/ext2.txt b/Documentation/filesystems/ext2.txt
index e055acb..67639f9 100644
--- a/Documentation/filesystems/ext2.txt
+++ b/Documentation/filesystems/ext2.txt
@@ -322,7 +322,7 @@
 so 8kB blocks are only allowed on Alpha systems (and other architectures
 which support larger pages).
 
-There is an upper limit of 32768 subdirectories in a single directory.
+There is an upper limit of 32000 subdirectories in a single directory.
 
 There is a "soft" upper limit of about 10-15k files in a single directory
 with the current linear linked-list directory implementation.  This limit
diff --git a/Documentation/filesystems/ext4.txt b/Documentation/filesystems/ext4.txt
index 608fdba..7be02ac 100644
--- a/Documentation/filesystems/ext4.txt
+++ b/Documentation/filesystems/ext4.txt
@@ -235,6 +235,10 @@
 
 debug			Extra debugging information is sent to syslog.
 
+abort			Simulate the effects of calling ext4_abort() for
+			debugging purposes.  This is normally used while
+			remounting a filesystem which is already mounted.
+
 errors=remount-ro	Remount the filesystem read-only on an error.
 errors=continue		Keep going on a filesystem error.
 errors=panic		Panic and halt the machine if an error occurs.
diff --git a/Documentation/filesystems/isofs.txt b/Documentation/filesystems/isofs.txt
index 6973b98..3c367c3 100644
--- a/Documentation/filesystems/isofs.txt
+++ b/Documentation/filesystems/isofs.txt
@@ -23,8 +23,13 @@
   map=off       Do not map non-Rock Ridge filenames to lower case
   map=normal    Map non-Rock Ridge filenames to lower case
   map=acorn     As map=normal but also apply Acorn extensions if present
-  mode=xxx      Sets the permissions on files to xxx
-  dmode=xxx     Sets the permissions on directories to xxx
+  mode=xxx      Sets the permissions on files to xxx unless Rock Ridge
+		extensions set the permissions otherwise
+  dmode=xxx     Sets the permissions on directories to xxx unless Rock Ridge
+		extensions set the permissions otherwise
+  overriderockperm Set permissions on files and directories according to
+		'mode' and 'dmode' even though Rock Ridge extensions are
+		present.
   nojoliet      Ignore Joliet extensions if they are present.
   norock        Ignore Rock Ridge extensions if they are present.
   hide		Completely strip hidden files from the file system.
diff --git a/Documentation/filesystems/proc.txt b/Documentation/filesystems/proc.txt
index ebff3c1..fad18f9 100644
--- a/Documentation/filesystems/proc.txt
+++ b/Documentation/filesystems/proc.txt
@@ -5,11 +5,12 @@
                   Bodo Bauer <bb@ricochet.net>
 
 2.4.x update	  Jorge Nerin <comandante@zaralinux.com>      November 14 2000
-move /proc/sys	  Shen Feng <shen@cn.fujitsu.com>		    April 1 2009
+move /proc/sys	  Shen Feng <shen@cn.fujitsu.com>		  April 1 2009
 ------------------------------------------------------------------------------
 Version 1.3                                              Kernel version 2.2.12
 					      Kernel version 2.4.0-test11-pre4
 ------------------------------------------------------------------------------
+fixes/update part 1.1  Stefani Seibold <stefani@seibold.net>       June 9 2009
 
 Table of Contents
 -----------------
@@ -116,7 +117,7 @@
 subdirectory has the entries listed in Table 1-1.
 
 
-Table 1-1: Process specific entries in /proc 
+Table 1-1: Process specific entries in /proc
 ..............................................................................
  File		Content
  clear_refs	Clears page referenced bits shown in smaps output
@@ -134,46 +135,103 @@
  status		Process status in human readable form
  wchan		If CONFIG_KALLSYMS is set, a pre-decoded wchan
  stack		Report full stack trace, enable via CONFIG_STACKTRACE
- smaps		Extension based on maps, the rss size for each mapped file
+ smaps		a extension based on maps, showing the memory consumption of
+		each mapping
 ..............................................................................
 
 For example, to get the status information of a process, all you have to do is
 read the file /proc/PID/status:
 
-  >cat /proc/self/status 
-  Name:   cat 
-  State:  R (running) 
-  Pid:    5452 
-  PPid:   743 
+  >cat /proc/self/status
+  Name:   cat
+  State:  R (running)
+  Tgid:   5452
+  Pid:    5452
+  PPid:   743
   TracerPid:      0						(2.4)
-  Uid:    501     501     501     501 
-  Gid:    100     100     100     100 
-  Groups: 100 14 16 
-  VmSize:     1112 kB 
-  VmLck:         0 kB 
-  VmRSS:       348 kB 
-  VmData:       24 kB 
-  VmStk:        12 kB 
-  VmExe:         8 kB 
-  VmLib:      1044 kB 
-  SigPnd: 0000000000000000 
-  SigBlk: 0000000000000000 
-  SigIgn: 0000000000000000 
-  SigCgt: 0000000000000000 
-  CapInh: 00000000fffffeff 
-  CapPrm: 0000000000000000 
-  CapEff: 0000000000000000 
-
+  Uid:    501     501     501     501
+  Gid:    100     100     100     100
+  FDSize: 256
+  Groups: 100 14 16
+  VmPeak:     5004 kB
+  VmSize:     5004 kB
+  VmLck:         0 kB
+  VmHWM:       476 kB
+  VmRSS:       476 kB
+  VmData:      156 kB
+  VmStk:        88 kB
+  VmExe:        68 kB
+  VmLib:      1412 kB
+  VmPTE:        20 kb
+  Threads:        1
+  SigQ:   0/28578
+  SigPnd: 0000000000000000
+  ShdPnd: 0000000000000000
+  SigBlk: 0000000000000000
+  SigIgn: 0000000000000000
+  SigCgt: 0000000000000000
+  CapInh: 00000000fffffeff
+  CapPrm: 0000000000000000
+  CapEff: 0000000000000000
+  CapBnd: ffffffffffffffff
+  voluntary_ctxt_switches:        0
+  nonvoluntary_ctxt_switches:     1
 
 This shows you nearly the same information you would get if you viewed it with
 the ps  command.  In  fact,  ps  uses  the  proc  file  system  to  obtain its
-information. The  statm  file  contains  more  detailed  information about the
-process memory usage. Its seven fields are explained in Table 1-2.  The stat
-file contains details information about the process itself.  Its fields are
-explained in Table 1-3.
+information.  But you get a more detailed  view of the  process by reading the
+file /proc/PID/status. It fields are described in table 1-2.
 
+The  statm  file  contains  more  detailed  information about the process
+memory usage. Its seven fields are explained in Table 1-3.  The stat file
+contains details information about the process itself.  Its fields are
+explained in Table 1-4.
 
-Table 1-2: Contents of the statm files (as of 2.6.8-rc3)
+Table 1-2: Contents of the statm files (as of 2.6.30-rc7)
+..............................................................................
+ Field                       Content
+ Name                        filename of the executable
+ State                       state (R is running, S is sleeping, D is sleeping
+                             in an uninterruptible wait, Z is zombie,
+			     T is traced or stopped)
+ Tgid                        thread group ID
+ Pid                         process id
+ PPid                        process id of the parent process
+ TracerPid                   PID of process tracing this process (0 if not)
+ Uid                         Real, effective, saved set, and  file system UIDs
+ Gid                         Real, effective, saved set, and  file system GIDs
+ FDSize                      number of file descriptor slots currently allocated
+ Groups                      supplementary group list
+ VmPeak                      peak virtual memory size
+ VmSize                      total program size
+ VmLck                       locked memory size
+ VmHWM                       peak resident set size ("high water mark")
+ VmRSS                       size of memory portions
+ VmData                      size of data, stack, and text segments
+ VmStk                       size of data, stack, and text segments
+ VmExe                       size of text segment
+ VmLib                       size of shared library code
+ VmPTE                       size of page table entries
+ Threads                     number of threads
+ SigQ                        number of signals queued/max. number for queue
+ SigPnd                      bitmap of pending signals for the thread
+ ShdPnd                      bitmap of shared pending signals for the process
+ SigBlk                      bitmap of blocked signals
+ SigIgn                      bitmap of ignored signals
+ SigCgt                      bitmap of catched signals
+ CapInh                      bitmap of inheritable capabilities
+ CapPrm                      bitmap of permitted capabilities
+ CapEff                      bitmap of effective capabilities
+ CapBnd                      bitmap of capabilities bounding set
+ Cpus_allowed                mask of CPUs on which this process may run
+ Cpus_allowed_list           Same as previous, but in "list format"
+ Mems_allowed                mask of memory nodes allowed to this process
+ Mems_allowed_list           Same as previous, but in "list format"
+ voluntary_ctxt_switches     number of voluntary context switches
+ nonvoluntary_ctxt_switches  number of non voluntary context switches
+..............................................................................
+
+Table 1-3: Contents of the statm files (as of 2.6.8-rc3)
 ..............................................................................
  Field    Content
  size     total program size (pages)		(same as VmSize in status)
@@ -188,7 +246,7 @@
 ..............................................................................
 
 
-Table 1-3: Contents of the stat files (as of 2.6.22-rc3)
+Table 1-4: Contents of the stat files (as of 2.6.30-rc7)
 ..............................................................................
  Field          Content
   pid           process id
@@ -222,10 +280,10 @@
   start_stack   address of the start of the stack
   esp           current value of ESP
   eip           current value of EIP
-  pending       bitmap of pending signals (obsolete)
-  blocked       bitmap of blocked signals (obsolete)
-  sigign        bitmap of ignored signals (obsolete)
-  sigcatch      bitmap of catched signals (obsolete)
+  pending       bitmap of pending signals
+  blocked       bitmap of blocked signals
+  sigign        bitmap of ignored signals
+  sigcatch      bitmap of catched signals
   wchan         address where process went to sleep
   0             (place holder)
   0             (place holder)
@@ -234,19 +292,99 @@
   rt_priority   realtime priority
   policy        scheduling policy (man sched_setscheduler)
   blkio_ticks   time spent waiting for block IO
+  gtime         guest time of the task in jiffies
+  cgtime        guest time of the task children in jiffies
 ..............................................................................
 
+The /proc/PID/map file containing the currently mapped memory regions and
+their access permissions.
+
+The format is:
+
+address           perms offset  dev   inode      pathname
+
+08048000-08049000 r-xp 00000000 03:00 8312       /opt/test
+08049000-0804a000 rw-p 00001000 03:00 8312       /opt/test
+0804a000-0806b000 rw-p 00000000 00:00 0          [heap]
+a7cb1000-a7cb2000 ---p 00000000 00:00 0
+a7cb2000-a7eb2000 rw-p 00000000 00:00 0
+a7eb2000-a7eb3000 ---p 00000000 00:00 0
+a7eb3000-a7ed5000 rw-p 00000000 00:00 0
+a7ed5000-a8008000 r-xp 00000000 03:00 4222       /lib/libc.so.6
+a8008000-a800a000 r--p 00133000 03:00 4222       /lib/libc.so.6
+a800a000-a800b000 rw-p 00135000 03:00 4222       /lib/libc.so.6
+a800b000-a800e000 rw-p 00000000 00:00 0
+a800e000-a8022000 r-xp 00000000 03:00 14462      /lib/libpthread.so.0
+a8022000-a8023000 r--p 00013000 03:00 14462      /lib/libpthread.so.0
+a8023000-a8024000 rw-p 00014000 03:00 14462      /lib/libpthread.so.0
+a8024000-a8027000 rw-p 00000000 00:00 0
+a8027000-a8043000 r-xp 00000000 03:00 8317       /lib/ld-linux.so.2
+a8043000-a8044000 r--p 0001b000 03:00 8317       /lib/ld-linux.so.2
+a8044000-a8045000 rw-p 0001c000 03:00 8317       /lib/ld-linux.so.2
+aff35000-aff4a000 rw-p 00000000 00:00 0          [stack]
+ffffe000-fffff000 r-xp 00000000 00:00 0          [vdso]
+
+where "address" is the address space in the process that it occupies, "perms"
+is a set of permissions:
+
+ r = read
+ w = write
+ x = execute
+ s = shared
+ p = private (copy on write)
+
+"offset" is the offset into the mapping, "dev" is the device (major:minor), and
+"inode" is the inode  on that device.  0 indicates that  no inode is associated
+with the memory region, as the case would be with BSS (uninitialized data).
+The "pathname" shows the name associated file for this mapping.  If the mapping
+is not associated with a file:
+
+ [heap]                   = the heap of the program
+ [stack]                  = the stack of the main process
+ [vdso]                   = the "virtual dynamic shared object",
+                            the kernel system call handler
+
+ or if empty, the mapping is anonymous.
+
+
+The /proc/PID/smaps is an extension based on maps, showing the memory
+consumption for each of the process's mappings. For each of mappings there
+is a series of lines such as the following:
+
+08048000-080bc000 r-xp 00000000 03:02 13130      /bin/bash
+Size:               1084 kB
+Rss:                 892 kB
+Pss:                 374 kB
+Shared_Clean:        892 kB
+Shared_Dirty:          0 kB
+Private_Clean:         0 kB
+Private_Dirty:         0 kB
+Referenced:          892 kB
+Swap:                  0 kB
+KernelPageSize:        4 kB
+MMUPageSize:           4 kB
+
+The first  of these lines shows  the same information  as is displayed for the
+mapping in /proc/PID/maps.  The remaining lines show  the size of the mapping,
+the amount of the mapping that is currently resident in RAM, the "proportional
+set size” (divide each shared page by the number of processes sharing it), the
+number of clean and dirty shared pages in the mapping, and the number of clean
+and dirty private pages in the mapping.  The "Referenced" indicates the amount
+of memory currently marked as referenced or accessed.
+
+This file is only present if the CONFIG_MMU kernel configuration option is
+enabled.
 
 1.2 Kernel data
 ---------------
 
 Similar to  the  process entries, the kernel data files give information about
 the running kernel. The files used to obtain this information are contained in
-/proc and  are  listed  in Table 1-4. Not all of these will be present in your
+/proc and  are  listed  in Table 1-5. Not all of these will be present in your
 system. It  depends  on the kernel configuration and the loaded modules, which
 files are there, and which are missing.
 
-Table 1-4: Kernel info in /proc
+Table 1-5: Kernel info in /proc
 ..............................................................................
  File        Content                                           
  apm         Advanced power management info                    
@@ -283,6 +421,7 @@
  rtc         Real time clock                                   
  scsi        SCSI info (see text)                              
  slabinfo    Slab pool info                                    
+ softirqs    softirq usage
  stat        Overall statistics                                
  swaps       Swap space utilization                            
  sys         See chapter 2                                     
@@ -597,6 +736,25 @@
 0xffffffffa0017000-0xffffffffa0022000   45056 sys_init_module+0xc27/0x1d00 ...
    pages=10 vmalloc N0=10
 
+..............................................................................
+
+softirqs:
+
+Provides counts of softirq handlers serviced since boot time, for each cpu.
+
+> cat /proc/softirqs
+                CPU0       CPU1       CPU2       CPU3
+      HI:          0          0          0          0
+   TIMER:      27166      27120      27097      27034
+  NET_TX:          0          0          0         17
+  NET_RX:         42          0          0         39
+   BLOCK:          0          0        107       1121
+ TASKLET:          0          0          0        290
+   SCHED:      27035      26983      26971      26746
+ HRTIMER:          0          0          0          0
+     RCU:       1678       1769       2178       2250
+
+
 1.3 IDE devices in /proc/ide
 ----------------------------
 
@@ -614,10 +772,10 @@
 
 More detailed  information  can  be  found  in  the  controller  specific
 subdirectories. These  are  named  ide0,  ide1  and  so  on.  Each  of  these
-directories contains the files shown in table 1-5.
+directories contains the files shown in table 1-6.
 
 
-Table 1-5: IDE controller info in  /proc/ide/ide?
+Table 1-6: IDE controller info in  /proc/ide/ide?
 ..............................................................................
  File    Content                                 
  channel IDE channel (0 or 1)                    
@@ -627,11 +785,11 @@
 ..............................................................................
 
 Each device  connected  to  a  controller  has  a separate subdirectory in the
-controllers directory.  The  files  listed in table 1-6 are contained in these
+controllers directory.  The  files  listed in table 1-7 are contained in these
 directories.
 
 
-Table 1-6: IDE device information
+Table 1-7: IDE device information
 ..............................................................................
  File             Content                                    
  cache            The cache                                  
@@ -673,12 +831,12 @@
 1.4 Networking info in /proc/net
 --------------------------------
 
-The subdirectory  /proc/net  follows  the  usual  pattern. Table 1-6 shows the
+The subdirectory  /proc/net  follows  the  usual  pattern. Table 1-8 shows the
 additional values  you  get  for  IP  version 6 if you configure the kernel to
-support this. Table 1-7 lists the files and their meaning.
+support this. Table 1-9 lists the files and their meaning.
 
 
-Table 1-6: IPv6 info in /proc/net 
+Table 1-8: IPv6 info in /proc/net
 ..............................................................................
  File       Content                                               
  udp6       UDP sockets (IPv6)                                    
@@ -693,7 +851,7 @@
 ..............................................................................
 
 
-Table 1-7: Network info in /proc/net 
+Table 1-9: Network info in /proc/net
 ..............................................................................
  File          Content                                                         
  arp           Kernel  ARP table                                               
@@ -817,10 +975,10 @@
 your system.  It  has  one  subdirectory  for  each port, named after the port
 number (0,1,2,...).
 
-These directories contain the four files shown in Table 1-8.
+These directories contain the four files shown in Table 1-10.
 
 
-Table 1-8: Files in /proc/parport 
+Table 1-10: Files in /proc/parport
 ..............................................................................
  File      Content                                                             
  autoprobe Any IEEE-1284 device ID information that has been acquired.         
@@ -838,10 +996,10 @@
 
 Information about  the  available  and actually used tty's can be found in the
 directory /proc/tty.You'll  find  entries  for drivers and line disciplines in
-this directory, as shown in Table 1-9.
+this directory, as shown in Table 1-11.
 
 
-Table 1-9: Files in /proc/tty 
+Table 1-11: Files in /proc/tty
 ..............................................................................
  File          Content                                        
  drivers       list of drivers and their usage                
@@ -883,6 +1041,7 @@
   processes 2915
   procs_running 1
   procs_blocked 0
+  softirq 183433 0 21755 12 39 1137 231 21459 2263
 
 The very first  "cpu" line aggregates the  numbers in all  of the other "cpuN"
 lines.  These numbers identify the amount of time the CPU has spent performing
@@ -918,6 +1077,11 @@
 The   "procs_blocked" line gives  the  number of  processes currently blocked,
 waiting for I/O to complete.
 
+The "softirq" line gives counts of softirqs serviced since boot time, for each
+of the possible system softirqs. The first column is the total of all
+softirqs serviced; each subsequent column is the total for that particular
+softirq.
+
 
 1.9 Ext4 file system parameters
 ------------------------------
@@ -926,9 +1090,9 @@
 /proc/fs/ext4.  Each mounted filesystem will have a directory in
 /proc/fs/ext4 based on its device name (i.e., /proc/fs/ext4/hdc or
 /proc/fs/ext4/dm-0).   The files in each per-device directory are shown
-in Table 1-10, below.
+in Table 1-12, below.
 
-Table 1-10: Files in /proc/fs/ext4/<devname>
+Table 1-12: Files in /proc/fs/ext4/<devname>
 ..............................................................................
  File            Content                                        
  mb_groups       details of multiblock allocator buddy cache of free blocks
diff --git a/Documentation/gcov.txt b/Documentation/gcov.txt
new file mode 100644
index 0000000..e716aad
--- /dev/null
+++ b/Documentation/gcov.txt
@@ -0,0 +1,246 @@
+Using gcov with the Linux kernel
+================================
+
+1. Introduction
+2. Preparation
+3. Customization
+4. Files
+5. Modules
+6. Separated build and test machines
+7. Troubleshooting
+Appendix A: sample script: gather_on_build.sh
+Appendix B: sample script: gather_on_test.sh
+
+
+1. Introduction
+===============
+
+gcov profiling kernel support enables the use of GCC's coverage testing
+tool gcov [1] with the Linux kernel. Coverage data of a running kernel
+is exported in gcov-compatible format via the "gcov" debugfs directory.
+To get coverage data for a specific file, change to the kernel build
+directory and use gcov with the -o option as follows (requires root):
+
+# cd /tmp/linux-out
+# gcov -o /sys/kernel/debug/gcov/tmp/linux-out/kernel spinlock.c
+
+This will create source code files annotated with execution counts
+in the current directory. In addition, graphical gcov front-ends such
+as lcov [2] can be used to automate the process of collecting data
+for the entire kernel and provide coverage overviews in HTML format.
+
+Possible uses:
+
+* debugging (has this line been reached at all?)
+* test improvement (how do I change my test to cover these lines?)
+* minimizing kernel configurations (do I need this option if the
+  associated code is never run?)
+
+--
+
+[1] http://gcc.gnu.org/onlinedocs/gcc/Gcov.html
+[2] http://ltp.sourceforge.net/coverage/lcov.php
+
+
+2. Preparation
+==============
+
+Configure the kernel with:
+
+        CONFIG_DEBUGFS=y
+        CONFIG_GCOV_KERNEL=y
+
+and to get coverage data for the entire kernel:
+
+        CONFIG_GCOV_PROFILE_ALL=y
+
+Note that kernels compiled with profiling flags will be significantly
+larger and run slower. Also CONFIG_GCOV_PROFILE_ALL may not be supported
+on all architectures.
+
+Profiling data will only become accessible once debugfs has been
+mounted:
+
+        mount -t debugfs none /sys/kernel/debug
+
+
+3. Customization
+================
+
+To enable profiling for specific files or directories, add a line
+similar to the following to the respective kernel Makefile:
+
+        For a single file (e.g. main.o):
+                GCOV_PROFILE_main.o := y
+
+        For all files in one directory:
+                GCOV_PROFILE := y
+
+To exclude files from being profiled even when CONFIG_GCOV_PROFILE_ALL
+is specified, use:
+
+                GCOV_PROFILE_main.o := n
+        and:
+                GCOV_PROFILE := n
+
+Only files which are linked to the main kernel image or are compiled as
+kernel modules are supported by this mechanism.
+
+
+4. Files
+========
+
+The gcov kernel support creates the following files in debugfs:
+
+        /sys/kernel/debug/gcov
+                Parent directory for all gcov-related files.
+
+        /sys/kernel/debug/gcov/reset
+                Global reset file: resets all coverage data to zero when
+                written to.
+
+        /sys/kernel/debug/gcov/path/to/compile/dir/file.gcda
+                The actual gcov data file as understood by the gcov
+                tool. Resets file coverage data to zero when written to.
+
+        /sys/kernel/debug/gcov/path/to/compile/dir/file.gcno
+                Symbolic link to a static data file required by the gcov
+                tool. This file is generated by gcc when compiling with
+                option -ftest-coverage.
+
+
+5. Modules
+==========
+
+Kernel modules may contain cleanup code which is only run during
+module unload time. The gcov mechanism provides a means to collect
+coverage data for such code by keeping a copy of the data associated
+with the unloaded module. This data remains available through debugfs.
+Once the module is loaded again, the associated coverage counters are
+initialized with the data from its previous instantiation.
+
+This behavior can be deactivated by specifying the gcov_persist kernel
+parameter:
+
+        gcov_persist=0
+
+At run-time, a user can also choose to discard data for an unloaded
+module by writing to its data file or the global reset file.
+
+
+6. Separated build and test machines
+====================================
+
+The gcov kernel profiling infrastructure is designed to work out-of-the
+box for setups where kernels are built and run on the same machine. In
+cases where the kernel runs on a separate machine, special preparations
+must be made, depending on where the gcov tool is used:
+
+a) gcov is run on the TEST machine
+
+The gcov tool version on the test machine must be compatible with the
+gcc version used for kernel build. Also the following files need to be
+copied from build to test machine:
+
+from the source tree:
+  - all C source files + headers
+
+from the build tree:
+  - all C source files + headers
+  - all .gcda and .gcno files
+  - all links to directories
+
+It is important to note that these files need to be placed into the
+exact same file system location on the test machine as on the build
+machine. If any of the path components is symbolic link, the actual
+directory needs to be used instead (due to make's CURDIR handling).
+
+b) gcov is run on the BUILD machine
+
+The following files need to be copied after each test case from test
+to build machine:
+
+from the gcov directory in sysfs:
+  - all .gcda files
+  - all links to .gcno files
+
+These files can be copied to any location on the build machine. gcov
+must then be called with the -o option pointing to that directory.
+
+Example directory setup on the build machine:
+
+  /tmp/linux:    kernel source tree
+  /tmp/out:      kernel build directory as specified by make O=
+  /tmp/coverage: location of the files copied from the test machine
+
+  [user@build] cd /tmp/out
+  [user@build] gcov -o /tmp/coverage/tmp/out/init main.c
+
+
+7. Troubleshooting
+==================
+
+Problem:  Compilation aborts during linker step.
+Cause:    Profiling flags are specified for source files which are not
+          linked to the main kernel or which are linked by a custom
+          linker procedure.
+Solution: Exclude affected source files from profiling by specifying
+          GCOV_PROFILE := n or GCOV_PROFILE_basename.o := n in the
+          corresponding Makefile.
+
+
+Appendix A: gather_on_build.sh
+==============================
+
+Sample script to gather coverage meta files on the build machine
+(see 6a):
+
+#!/bin/bash
+
+KSRC=$1
+KOBJ=$2
+DEST=$3
+
+if [ -z "$KSRC" ] || [ -z "$KOBJ" ] || [ -z "$DEST" ]; then
+  echo "Usage: $0 <ksrc directory> <kobj directory> <output.tar.gz>" >&2
+  exit 1
+fi
+
+KSRC=$(cd $KSRC; printf "all:\n\t@echo \${CURDIR}\n" | make -f -)
+KOBJ=$(cd $KOBJ; printf "all:\n\t@echo \${CURDIR}\n" | make -f -)
+
+find $KSRC $KOBJ \( -name '*.gcno' -o -name '*.[ch]' -o -type l \) -a \
+                 -perm /u+r,g+r | tar cfz $DEST -P -T -
+
+if [ $? -eq 0 ] ; then
+  echo "$DEST successfully created, copy to test system and unpack with:"
+  echo "  tar xfz $DEST -P"
+else
+  echo "Could not create file $DEST"
+fi
+
+
+Appendix B: gather_on_test.sh
+=============================
+
+Sample script to gather coverage data files on the test machine
+(see 6b):
+
+#!/bin/bash
+
+DEST=$1
+GCDA=/sys/kernel/debug/gcov
+
+if [ -z "$DEST" ] ; then
+  echo "Usage: $0 <output.tar.gz>" >&2
+  exit 1
+fi
+
+find $GCDA -name '*.gcno' -o -name '*.gcda' | tar cfz $DEST -T -
+
+if [ $? -eq 0 ] ; then
+  echo "$DEST successfully created, copy to build system and unpack with:"
+  echo "  tar xfz $DEST"
+else
+  echo "Could not create file $DEST"
+fi
diff --git a/Documentation/i2c/instantiating-devices b/Documentation/i2c/instantiating-devices
index b55ce57..c740b7b 100644
--- a/Documentation/i2c/instantiating-devices
+++ b/Documentation/i2c/instantiating-devices
@@ -165,3 +165,47 @@
 Once again, method 3 should be avoided wherever possible. Explicit device
 instantiation (methods 1 and 2) is much preferred for it is safer and
 faster.
+
+
+Method 4: Instantiate from user-space
+-------------------------------------
+
+In general, the kernel should know which I2C devices are connected and
+what addresses they live at. However, in certain cases, it does not, so a
+sysfs interface was added to let the user provide the information. This
+interface is made of 2 attribute files which are created in every I2C bus
+directory: new_device and delete_device. Both files are write only and you
+must write the right parameters to them in order to properly instantiate,
+respectively delete, an I2C device.
+
+File new_device takes 2 parameters: the name of the I2C device (a string)
+and the address of the I2C device (a number, typically expressed in
+hexadecimal starting with 0x, but can also be expressed in decimal.)
+
+File delete_device takes a single parameter: the address of the I2C
+device. As no two devices can live at the same address on a given I2C
+segment, the address is sufficient to uniquely identify the device to be
+deleted.
+
+Example:
+# echo eeprom 0x50 > /sys/class/i2c-adapter/i2c-3/new_device
+
+While this interface should only be used when in-kernel device declaration
+can't be done, there is a variety of cases where it can be helpful:
+* The I2C driver usually detects devices (method 3 above) but the bus
+  segment your device lives on doesn't have the proper class bit set and
+  thus detection doesn't trigger.
+* The I2C driver usually detects devices, but your device lives at an
+  unexpected address.
+* The I2C driver usually detects devices, but your device is not detected,
+  either because the detection routine is too strict, or because your
+  device is not officially supported yet but you know it is compatible.
+* You are developing a driver on a test board, where you soldered the I2C
+  device yourself.
+
+This interface is a replacement for the force_* module parameters some I2C
+drivers implement. Being implemented in i2c-core rather than in each
+device driver individually, it is much more efficient, and also has the
+advantage that you do not have to reload the driver to change a setting.
+You can also instantiate the device before the driver is loaded or even
+available, and you don't need to know what driver the device needs.
diff --git a/Documentation/i2c/writing-clients b/Documentation/i2c/writing-clients
index c1a06f9..7860aaf 100644
--- a/Documentation/i2c/writing-clients
+++ b/Documentation/i2c/writing-clients
@@ -126,19 +126,9 @@
 that can't be distinguished by protocol probing, or which need some board
 specific information to operate correctly.
 
-Accordingly, the I2C stack now has two models for associating I2C devices
-with their drivers:  the original "legacy" model, and a newer one that's
-fully compatible with the Linux 2.6 driver model.  These models do not mix,
-since the "legacy" model requires drivers to create "i2c_client" device
-objects after SMBus style probing, while the Linux driver model expects
-drivers to be given such device objects in their probe() routines.
 
-The legacy model is deprecated now and will soon be removed, so we no
-longer document it here.
-
-
-Standard Driver Model Binding ("New Style")
--------------------------------------------
+Device/Driver Binding
+---------------------
 
 System infrastructure, typically board-specific initialization code or
 boot firmware, reports what I2C devices exist.  For example, there may be
@@ -201,7 +191,7 @@
 devices on a PC's SMBus.  In that case, you may want to let your driver
 detect supported devices automatically.  This is how the legacy model
 was working, and is now available as an extension to the standard
-driver model (so that we can finally get rid of the legacy model.)
+driver model.
 
 You simply have to define a detect callback which will attempt to
 identify supported devices (returning 0 for supported ones and -ENODEV
diff --git a/Documentation/input/input.txt b/Documentation/input/input.txt
index 686ee99..b93c084 100644
--- a/Documentation/input/input.txt
+++ b/Documentation/input/input.txt
@@ -278,7 +278,7 @@
 };
 
   'time' is the timestamp, it returns the time at which the event happened.
-Type is for example EV_REL for relative moment, REL_KEY for a keypress or
+Type is for example EV_REL for relative moment, EV_KEY for a keypress or
 release. More types are defined in include/linux/input.h.
 
   'code' is event code, for example REL_X or KEY_BACKSPACE, again a complete
diff --git a/Documentation/input/rotary-encoder.txt b/Documentation/input/rotary-encoder.txt
index 435102a..3a6aec4 100644
--- a/Documentation/input/rotary-encoder.txt
+++ b/Documentation/input/rotary-encoder.txt
@@ -67,7 +67,12 @@
 struct rotary_encoder_platform_data is declared in
 include/linux/rotary-encoder.h and needs to be filled with the number of
 steps the encoder has and can carry information about externally inverted
-signals (because of used invertig buffer or other reasons).
+signals (because of an inverting buffer or other reasons). The encoder
+can be set up to deliver input information as either an absolute or relative
+axes. For relative axes the input event returns +/-1 for each step. For
+absolute axes the position of the encoder can either roll over between zero
+and the number of steps or will clamp at the maximum and zero depending on
+the configuration.
 
 Because GPIO to IRQ mapping is platform specific, this information must
 be given in seperately to the driver. See the example below.
@@ -85,6 +90,8 @@
 static struct rotary_encoder_platform_data my_rotary_encoder_info = {
 	.steps		= 24,
 	.axis		= ABS_X,
+	.relative_axis	= false,
+	.rollover	= false,
 	.gpio_a		= GPIO_ROTARY_A,
 	.gpio_b		= GPIO_ROTARY_B,
 	.inverted_a	= 0,
diff --git a/Documentation/ioctl/ioctl-number.txt b/Documentation/ioctl/ioctl-number.txt
index 1f779a2..7bb0d93 100644
--- a/Documentation/ioctl/ioctl-number.txt
+++ b/Documentation/ioctl/ioctl-number.txt
@@ -149,6 +149,8 @@
 'p'	40-7F	linux/nvram.h
 'p'	80-9F				user-space parport
 					<mailto:tim@cyberelk.net>
+'p'	a1-a4	linux/pps.h		LinuxPPS
+					<mailto:giometti@linux.it>
 'q'	00-1F	linux/serio.h
 'q'	80-FF				Internet PhoneJACK, Internet LineJACK
 					<http://www.quicknet.net>
diff --git a/Documentation/ja_JP/SubmitChecklist b/Documentation/ja_JP/SubmitChecklist
index 6c42e07..2df4576 100644
--- a/Documentation/ja_JP/SubmitChecklist
+++ b/Documentation/ja_JP/SubmitChecklist
@@ -75,7 +75,7 @@
     ビルドした上、動作確認を行ってください。
 
 14: もしパッチがディスクのI/O性能などに影響を与えるようであれば、
-    'CONFIG_LBD'オプションを有効にした場合と無効にした場合の両方で
+    'CONFIG_LBDAF'オプションを有効にした場合と無効にした場合の両方で
     テストを実施してみてください。
 
 15: lockdepの機能を全て有効にした上で、全てのコードパスを評価してください。
diff --git a/Documentation/kernel-parameters.txt b/Documentation/kernel-parameters.txt
index 5578248..08def8d 100644
--- a/Documentation/kernel-parameters.txt
+++ b/Documentation/kernel-parameters.txt
@@ -48,6 +48,7 @@
 	EFI	EFI Partitioning (GPT) is enabled
 	EIDE	EIDE/ATAPI support is enabled.
 	FB	The frame buffer device is enabled.
+	GCOV	GCOV profiling is enabled.
 	HW	Appropriate hardware is enabled.
 	IA-64	IA-64 architecture is enabled.
 	IMA     Integrity measurement architecture is enabled.
@@ -796,6 +797,12 @@
 			Format: off | on
 			default: on
 
+	gcov_persist=	[GCOV] When non-zero (default), profiling data for
+			kernel modules is saved and remains accessible via
+			debugfs, even when the module is unloaded/reloaded.
+			When zero, profiling data is discarded and associated
+			debugfs files are removed at module unload time.
+
 	gdth=		[HW,SCSI]
 			See header of drivers/scsi/gdth.c.
 
diff --git a/Documentation/pps/pps.txt b/Documentation/pps/pps.txt
new file mode 100644
index 0000000..125f4ab
--- /dev/null
+++ b/Documentation/pps/pps.txt
@@ -0,0 +1,172 @@
+
+			PPS - Pulse Per Second
+			----------------------
+
+(C) Copyright 2007 Rodolfo Giometti <giometti@enneenne.com>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+
+
+Overview
+--------
+
+LinuxPPS provides a programming interface (API) to define in the
+system several PPS sources.
+
+PPS means "pulse per second" and a PPS source is just a device which
+provides a high precision signal each second so that an application
+can use it to adjust system clock time.
+
+A PPS source can be connected to a serial port (usually to the Data
+Carrier Detect pin) or to a parallel port (ACK-pin) or to a special
+CPU's GPIOs (this is the common case in embedded systems) but in each
+case when a new pulse arrives the system must apply to it a timestamp
+and record it for userland.
+
+Common use is the combination of the NTPD as userland program, with a
+GPS receiver as PPS source, to obtain a wallclock-time with
+sub-millisecond synchronisation to UTC.
+
+
+RFC considerations
+------------------
+
+While implementing a PPS API as RFC 2783 defines and using an embedded
+CPU GPIO-Pin as physical link to the signal, I encountered a deeper
+problem:
+
+   At startup it needs a file descriptor as argument for the function
+   time_pps_create().
+
+This implies that the source has a /dev/... entry. This assumption is
+ok for the serial and parallel port, where you can do something
+useful besides(!) the gathering of timestamps as it is the central
+task for a PPS-API. But this assumption does not work for a single
+purpose GPIO line. In this case even basic file-related functionality
+(like read() and write()) makes no sense at all and should not be a
+precondition for the use of a PPS-API.
+
+The problem can be simply solved if you consider that a PPS source is
+not always connected with a GPS data source.
+
+So your programs should check if the GPS data source (the serial port
+for instance) is a PPS source too, and if not they should provide the
+possibility to open another device as PPS source.
+
+In LinuxPPS the PPS sources are simply char devices usually mapped
+into files /dev/pps0, /dev/pps1, etc..
+
+
+Coding example
+--------------
+
+To register a PPS source into the kernel you should define a struct
+pps_source_info_s as follows:
+
+    static struct pps_source_info pps_ktimer_info = {
+	    .name         = "ktimer",
+	    .path         = "",
+	    .mode         = PPS_CAPTUREASSERT | PPS_OFFSETASSERT | \
+			    PPS_ECHOASSERT | \
+			    PPS_CANWAIT | PPS_TSFMT_TSPEC,
+	    .echo         = pps_ktimer_echo,
+	    .owner        = THIS_MODULE,
+    };
+
+and then calling the function pps_register_source() in your
+intialization routine as follows:
+
+    source = pps_register_source(&pps_ktimer_info,
+			PPS_CAPTUREASSERT | PPS_OFFSETASSERT);
+
+The pps_register_source() prototype is:
+
+  int pps_register_source(struct pps_source_info_s *info, int default_params)
+
+where "info" is a pointer to a structure that describes a particular
+PPS source, "default_params" tells the system what the initial default
+parameters for the device should be (it is obvious that these parameters
+must be a subset of ones defined in the struct
+pps_source_info_s which describe the capabilities of the driver).
+
+Once you have registered a new PPS source into the system you can
+signal an assert event (for example in the interrupt handler routine)
+just using:
+
+    pps_event(source, &ts, PPS_CAPTUREASSERT, ptr)
+
+where "ts" is the event's timestamp.
+
+The same function may also run the defined echo function
+(pps_ktimer_echo(), passing to it the "ptr" pointer) if the user
+asked for that... etc..
+
+Please see the file drivers/pps/clients/ktimer.c for example code.
+
+
+SYSFS support
+-------------
+
+If the SYSFS filesystem is enabled in the kernel it provides a new class:
+
+   $ ls /sys/class/pps/
+   pps0/  pps1/  pps2/
+
+Every directory is the ID of a PPS sources defined in the system and
+inside you find several files:
+
+   $ ls /sys/class/pps/pps0/
+   assert	clear  echo  mode  name  path  subsystem@  uevent
+
+Inside each "assert" and "clear" file you can find the timestamp and a
+sequence number:
+
+   $ cat /sys/class/pps/pps0/assert
+   1170026870.983207967#8
+
+Where before the "#" is the timestamp in seconds; after it is the
+sequence number. Other files are:
+
+* echo: reports if the PPS source has an echo function or not;
+
+* mode: reports available PPS functioning modes;
+
+* name: reports the PPS source's name;
+
+* path: reports the PPS source's device path, that is the device the
+  PPS source is connected to (if it exists).
+
+
+Testing the PPS support
+-----------------------
+
+In order to test the PPS support even without specific hardware you can use
+the ktimer driver (see the client subsection in the PPS configuration menu)
+and the userland tools provided into Documentaion/pps/ directory.
+
+Once you have enabled the compilation of ktimer just modprobe it (if
+not statically compiled):
+
+   # modprobe ktimer
+
+and the run ppstest as follow:
+
+   $ ./ppstest /dev/pps0
+   trying PPS source "/dev/pps1"
+   found PPS source "/dev/pps1"
+   ok, found 1 source(s), now start fetching data...
+   source 0 - assert 1186592699.388832443, sequence: 364 - clear  0.000000000, sequence: 0
+   source 0 - assert 1186592700.388931295, sequence: 365 - clear  0.000000000, sequence: 0
+   source 0 - assert 1186592701.389032765, sequence: 366 - clear  0.000000000, sequence: 0
+
+Please, note that to compile userland programs you need the file timepps.h
+(see Documentation/pps/).
diff --git a/Documentation/rfkill.txt b/Documentation/rfkill.txt
index 1b74b5f..c8acd86 100644
--- a/Documentation/rfkill.txt
+++ b/Documentation/rfkill.txt
@@ -3,9 +3,8 @@
 
 1. Introduction
 2. Implementation details
-3. Kernel driver guidelines
-4. Kernel API
-5. Userspace support
+3. Kernel API
+4. Userspace support
 
 
 1. Introduction
@@ -19,82 +18,62 @@
 situations where transmitters need to be turned off, for example on
 aircraft.
 
+The rfkill subsystem has a concept of "hard" and "soft" block, which
+differ little in their meaning (block == transmitters off) but rather in
+whether they can be changed or not:
+ - hard block: read-only radio block that cannot be overriden by software
+ - soft block: writable radio block (need not be readable) that is set by
+               the system software.
 
 
 2. Implementation details
 
-The rfkill subsystem is composed of various components: the rfkill class, the
-rfkill-input module (an input layer handler), and some specific input layer
-events.
+The rfkill subsystem is composed of three main components:
+ * the rfkill core,
+ * the deprecated rfkill-input module (an input layer handler, being
+   replaced by userspace policy code) and
+ * the rfkill drivers.
 
-The rfkill class is provided for kernel drivers to register their radio
-transmitter with the kernel, provide methods for turning it on and off and,
-optionally, letting the system know about hardware-disabled states that may
-be implemented on the device. This code is enabled with the CONFIG_RFKILL
-Kconfig option, which drivers can "select".
+The rfkill core provides API for kernel drivers to register their radio
+transmitter with the kernel, methods for turning it on and off and, letting
+the system know about hardware-disabled states that may be implemented on
+the device.
 
-The rfkill class code also notifies userspace of state changes, this is
-achieved via uevents. It also provides some sysfs files for userspace to
-check the status of radio transmitters. See the "Userspace support" section
-below.
-
-
-The rfkill-input code implements a basic response to rfkill buttons -- it
-implements turning on/off all devices of a certain class (or all).
+The rfkill core code also notifies userspace of state changes, and provides
+ways for userspace to query the current states. See the "Userspace support"
+section below.
 
 When the device is hard-blocked (either by a call to rfkill_set_hw_state()
-or from query_hw_block) set_block() will be invoked but drivers can well
-ignore the method call since they can use the return value of the function
-rfkill_set_hw_state() to sync the software state instead of keeping track
-of calls to set_block().
+or from query_hw_block) set_block() will be invoked for additional software
+block, but drivers can ignore the method call since they can use the return
+value of the function rfkill_set_hw_state() to sync the software state
+instead of keeping track of calls to set_block(). In fact, drivers should
+use the return value of rfkill_set_hw_state() unless the hardware actually
+keeps track of soft and hard block separately.
 
 
-The entire functionality is spread over more than one subsystem:
-
- * The kernel input layer generates KEY_WWAN, KEY_WLAN etc. and
-   SW_RFKILL_ALL -- when the user presses a button. Drivers for radio
-   transmitters generally do not register to the input layer, unless the
-   device really provides an input device (i.e. a button that has no
-   effect other than generating a button press event)
-
- * The rfkill-input code hooks up to these events and switches the soft-block
-   of the various radio transmitters, depending on the button type.
-
- * The rfkill drivers turn off/on their transmitters as requested.
-
- * The rfkill class will generate userspace notifications (uevents) to tell
-   userspace what the current state is.
+3. Kernel API
 
 
-
-3. Kernel driver guidelines
-
-
-Drivers for radio transmitters normally implement only the rfkill class.
-These drivers may not unblock the transmitter based on own decisions, they
-should act on information provided by the rfkill class only.
+Drivers for radio transmitters normally implement an rfkill driver.
 
 Platform drivers might implement input devices if the rfkill button is just
 that, a button. If that button influences the hardware then you need to
-implement an rfkill class instead. This also applies if the platform provides
+implement an rfkill driver instead. This also applies if the platform provides
 a way to turn on/off the transmitter(s).
 
-During suspend/hibernation, transmitters should only be left enabled when
-wake-on wlan or similar functionality requires it and the device wasn't
-blocked before suspend/hibernate. Note that it may be necessary to update
-the rfkill subsystem's idea of what the current state is at resume time if
-the state may have changed over suspend.
+For some platforms, it is possible that the hardware state changes during
+suspend/hibernation, in which case it will be necessary to update the rfkill
+core with the current state is at resume time.
 
+To create an rfkill driver, driver's Kconfig needs to have
 
+	depends on RFKILL || !RFKILL
 
-4. Kernel API
-
-To build a driver with rfkill subsystem support, the driver should depend on
-(or select) the Kconfig symbol RFKILL.
-
-The hardware the driver talks to may be write-only (where the current state
-of the hardware is unknown), or read-write (where the hardware can be queried
-about its current state).
+to ensure the driver cannot be built-in when rfkill is modular. The !RFKILL
+case allows the driver to be built when rfkill is not configured, which which
+case all rfkill API can still be used but will be provided by static inlines
+which compile to almost nothing.
 
 Calling rfkill_set_hw_state() when a state change happens is required from
 rfkill drivers that control devices that can be hard-blocked unless they also
@@ -105,10 +84,33 @@
 
 5. Userspace support
 
-The following sysfs entries exist for every rfkill device:
+The recommended userspace interface to use is /dev/rfkill, which is a misc
+character device that allows userspace to obtain and set the state of rfkill
+devices and sets of devices. It also notifies userspace about device addition
+and removal. The API is a simple read/write API that is defined in
+linux/rfkill.h, with one ioctl that allows turning off the deprecated input
+handler in the kernel for the transition period.
+
+Except for the one ioctl, communication with the kernel is done via read()
+and write() of instances of 'struct rfkill_event'. In this structure, the
+soft and hard block are properly separated (unlike sysfs, see below) and
+userspace is able to get a consistent snapshot of all rfkill devices in the
+system. Also, it is possible to switch all rfkill drivers (or all drivers of
+a specified type) into a state which also updates the default state for
+hotplugged devices.
+
+After an application opens /dev/rfkill, it can read the current state of
+all devices, and afterwards can poll the descriptor for hotplug or state
+change events.
+
+Applications must ignore operations (the "op" field) they do not handle,
+this allows the API to be extended in the future.
+
+Additionally, each rfkill device is registered in sysfs and there has the
+following attributes:
 
 	name: Name assigned by driver to this key (interface or driver name).
-	type: Name of the key type ("wlan", "bluetooth", etc).
+	type: Driver type string ("wlan", "bluetooth", etc).
 	state: Current state of the transmitter
 		0: RFKILL_STATE_SOFT_BLOCKED
 			transmitter is turned off by software
@@ -117,7 +119,12 @@
 		2: RFKILL_STATE_HARD_BLOCKED
 			transmitter is forced off by something outside of
 			the driver's control.
-	claim: 0: Kernel handles events (currently always reads that value)
+	       This file is deprecated because it can only properly show
+	       three of the four possible states, soft-and-hard-blocked is
+	       missing.
+	claim: 0: Kernel handles events
+	       This file is deprecated because there no longer is a way to
+	       claim just control over a single rfkill instance.
 
 rfkill devices also issue uevents (with an action of "change"), with the
 following environment variables set:
@@ -128,9 +135,3 @@
 
 The contents of these variables corresponds to the "name", "state" and
 "type" sysfs files explained above.
-
-An alternative userspace interface exists as a misc device /dev/rfkill,
-which allows userspace to obtain and set the state of rfkill devices and
-sets of devices. It also notifies userspace about device addition and
-removal. The API is a simple read/write API that is defined in
-linux/rfkill.h.
diff --git a/Documentation/robust-futex-ABI.txt b/Documentation/robust-futex-ABI.txt
index 535f69f..fd1cd8a 100644
--- a/Documentation/robust-futex-ABI.txt
+++ b/Documentation/robust-futex-ABI.txt
@@ -135,7 +135,7 @@
 protocol on 'lock entry' insertion and removal:
 
 On insertion:
- 1) set the 'list_op_pending' word to the address of the 'lock word'
+ 1) set the 'list_op_pending' word to the address of the 'lock entry'
     to be inserted,
  2) acquire the futex lock,
  3) add the lock entry, with its thread id (TID) in the bottom 29 bits
@@ -143,7 +143,7 @@
  4) clear the 'list_op_pending' word.
 
 On removal:
- 1) set the 'list_op_pending' word to the address of the 'lock word'
+ 1) set the 'list_op_pending' word to the address of the 'lock entry'
     to be removed,
  2) remove the lock entry for this lock from the 'head' list,
  2) release the futex lock, and
diff --git a/Documentation/scsi/scsi_fc_transport.txt b/Documentation/scsi/scsi_fc_transport.txt
index e5b071d..d7f1817 100644
--- a/Documentation/scsi/scsi_fc_transport.txt
+++ b/Documentation/scsi/scsi_fc_transport.txt
@@ -1,10 +1,11 @@
                              SCSI FC Tansport
                  =============================================
 
-Date:  4/12/2007
+Date:  11/18/2008
 Kernel Revisions for features:
   rports : <<TBS>>
-  vports : 2.6.22 (? TBD)
+  vports : 2.6.22
+  bsg support : 2.6.30 (?TBD?)
 
 
 Introduction
@@ -15,6 +16,7 @@
   drivers/scsi/scsi_transport_fc.c
   include/scsi/scsi_transport_fc.h
   include/scsi/scsi_netlink_fc.h
+  include/scsi/scsi_bsg_fc.h
 
 This file is found at Documentation/scsi/scsi_fc_transport.txt
 
@@ -472,6 +474,14 @@
 fc_vport_terminate(struct fc_vport *vport)
 
 
+FC BSG support (CT & ELS passthru, and more)
+========================================================================
+<< To Be Supplied >>
+
+
+
+
+
 Credits
 =======
 The following people have contributed to this document:
diff --git a/Documentation/scsi/scsi_mid_low_api.txt b/Documentation/scsi/scsi_mid_low_api.txt
index a6d5354..de67229 100644
--- a/Documentation/scsi/scsi_mid_low_api.txt
+++ b/Documentation/scsi/scsi_mid_low_api.txt
@@ -1271,6 +1271,11 @@
     hostdata[0]  - area reserved for LLD at end of struct Scsi_Host. Size
                    is set by the second argument (named 'xtr_bytes') to
                    scsi_host_alloc() or scsi_register().
+    vendor_id    - a unique value that identifies the vendor supplying
+                   the LLD for the Scsi_Host.  Used most often in validating
+                   vendor-specific message requests.  Value consists of an
+                   identifier type and a vendor-specific value.
+                   See scsi_netlink.h for a description of valid formats.
 
 The scsi_host structure is defined in include/scsi/scsi_host.h
 
diff --git a/Documentation/vm/Makefile b/Documentation/vm/Makefile
index 27479d4..5bd269b 100644
--- a/Documentation/vm/Makefile
+++ b/Documentation/vm/Makefile
@@ -2,7 +2,7 @@
 obj- := dummy.o
 
 # List of programs to build
-hostprogs-y := slabinfo slqbinfo page-types
+hostprogs-y := slabinfo page-types
 
 # Tell kbuild to always build the programs
 always := $(hostprogs-y)
diff --git a/Documentation/watchdog/hpwdt.txt b/Documentation/watchdog/hpwdt.txt
new file mode 100644
index 0000000..127839e
--- /dev/null
+++ b/Documentation/watchdog/hpwdt.txt
@@ -0,0 +1,84 @@
+Last reviewed: 06/02/2009
+
+                     HP iLO2 NMI Watchdog Driver
+              NMI sourcing for iLO2 based ProLiant Servers
+                     Documentation and Driver by
+              Thomas Mingarelli <thomas.mingarelli@hp.com>
+
+ The HP iLO2 NMI Watchdog driver is a kernel module that provides basic
+ watchdog functionality and the added benefit of NMI sourcing. Both the
+ watchdog functionality and the NMI sourcing capability need to be enabled
+ by the user. Remember that the two modes are not dependant on one another.
+ A user can have the NMI sourcing without the watchdog timer and vice-versa.
+
+ Watchdog functionality is enabled like any other common watchdog driver. That
+ is, an application needs to be started that kicks off the watchdog timer. A
+ basic application exists in the Documentation/watchdog/src directory called
+ watchdog-test.c. Simply compile the C file and kick it off. If the system
+ gets into a bad state and hangs, the HP ProLiant iLO 2 timer register will
+ not be updated in a timely fashion and a hardware system reset (also known as
+ an Automatic Server Recovery (ASR)) event will occur.
+
+ The hpwdt driver also has three (3) module parameters. They are the following:
+
+ soft_margin - allows the user to set the watchdog timer value
+ allow_kdump - allows the user to save off a kernel dump image after an NMI
+ nowayout    - basic watchdog parameter that does not allow the timer to
+               be restarted or an impending ASR to be escaped.
+
+ NOTE: More information about watchdog drivers in general, including the ioctl
+       interface to /dev/watchdog can be found in
+       Documentation/watchdog/watchdog-api.txt and Documentation/IPMI.txt.
+
+ The NMI sourcing capability is disabled when the driver discovers that the
+ nmi_watchdog is turned on (nmi_watchdog = 1). This is due to the inability to
+ distinguish between "NMI Watchdog Ticks" and "HW generated NMI events" in the
+ Linux kernel. What this means is that the hpwdt nmi handler code is called
+ each time the NMI signal fires off. This could amount to several thousands of
+ NMIs in a matter of seconds. If a user sees the Linux kernel's "dazed and
+ confused" message in the logs or if the system gets into a hung state, then
+ the user should reboot with nmi_watchdog=0.
+
+ 1. If the kernel has not been booted with nmi_watchdog turned off then
+    edit /boot/grub/menu.lst and place the nmi_watchdog=0 at the end of the
+    currently booting kernel line.
+ 2. reboot the sever
+
+ Now, the hpwdt can successfully receive and source the NMI and provide a log
+ message that details the reason for the NMI (as determined by the HP BIOS).
+
+ Below is a list of NMIs the HP BIOS understands along with the associated
+ code (reason):
+
+	No source found                00h
+
+	Uncorrectable Memory Error     01h
+
+	ASR NMI                        1Bh
+
+	PCI Parity Error               20h
+
+	NMI Button Press               27h
+
+	SB_BUS_NMI                     28h
+
+	ILO Doorbell NMI               29h
+
+	ILO IOP NMI                    2Ah
+
+	ILO Watchdog NMI               2Bh
+
+	Proc Throt NMI                 2Ch
+
+	Front Side Bus NMI             2Dh
+
+	PCI Express Error              2Fh
+
+	DMA controller NMI             30h
+
+	Hypertransport/CSI Error       31h
+
+
+
+ -- Tom Mingarelli
+    (thomas.mingarelli@hp.com)
diff --git a/MAINTAINERS b/MAINTAINERS
index fb94add..dc226e7 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -946,7 +946,7 @@
 L:	linux-wireless@vger.kernel.org
 L:	ath5k-devel@lists.ath5k.org
 S:	Maintained
-F:	drivers/net/wireless/ath5k/
+F:	drivers/net/wireless/ath/ath5k/
 
 ATHEROS ATH9K WIRELESS DRIVER
 P:	Luis R. Rodriguez
@@ -962,7 +962,7 @@
 L:	linux-wireless@vger.kernel.org
 L:	ath9k-devel@lists.ath9k.org
 S:	Supported
-F:	drivers/net/wireless/ath9k/
+F:	drivers/net/wireless/ath/ath9k/
 
 ATHEROS AR9170 WIRELESS DRIVER
 P:	Christian Lamparter
@@ -970,7 +970,7 @@
 L:	linux-wireless@vger.kernel.org
 W:	http://wireless.kernel.org/en/users/Drivers/ar9170
 S:	Maintained
-F:	drivers/net/wireless/ar9170/
+F:	drivers/net/wireless/ath/ar9170/
 
 ATI_REMOTE2 DRIVER
 P:	Ville Syrjala
@@ -1544,6 +1544,7 @@
 S:	Maintained
 F:	include/linux/cgroup*
 F:	kernel/cgroup*
+F:	mm/*cgroup*
 
 CORETEMP HARDWARE MONITORING DRIVER
 P:	Rudolf Marek
@@ -2052,8 +2053,8 @@
 
 EDAC-I82975X
 P:	Ranganathan Desikan
-P:	Arvind R.
 M:	rdesikan@jetzbroadband.com
+P:	Arvind R.
 M:	arvind@acarlab.com
 L:	bluesmoke-devel@lists.sourceforge.net (moderated for non-subscribers)
 W:	bluesmoke.sourceforge.net
@@ -2274,11 +2275,9 @@
 F:	drivers/net/wan/sdla.c
 
 FRAMEBUFFER LAYER
-P:	Antonino Daplas
-M:	adaplas@gmail.com
 L:	linux-fbdev-devel@lists.sourceforge.net (moderated for non-subscribers)
 W:	http://linux-fbdev.sourceforge.net/
-S:	Maintained
+S:	Orphan
 F:	Documentation/fb/
 F:	drivers/video/fb*
 F:	include/linux/fb.h
@@ -2391,7 +2390,7 @@
 P:	Steven Rostedt
 M:	rostedt@goodmis.org
 S:	Maintained
-F:	Documentation/ftrace.txt
+F:	Documentation/trace/ftrace.txt
 F:	arch/*/*/*/ftrace.h
 F:	arch/*/kernel/ftrace.c
 F:	include/*/ftrace.h
@@ -2850,7 +2849,7 @@
 T:	git git://git.kernel.org/pub/scm/linux/kernel/git/lumag/lowpan.git
 S:	Maintained
 F:	net/ieee802154/
-F:	drivers/ieee801254/
+F:	drivers/ieee802154/
 
 INTEGRITY MEASUREMENT ARCHITECTURE (IMA)
 P:	Mimi Zohar
@@ -3407,7 +3406,7 @@
 M:	eduard.munteanu@linux360.ro
 S:	Maintained
 F:	Documentation/trace/kmemtrace.txt
-F:	include/trace/kmemtrace.h
+F:	include/linux/kmemtrace.h
 F:	kernel/trace/kmemtrace.c
 
 KPROBES
@@ -4084,7 +4083,7 @@
 S:	Maintained
 F:	net/wireless/
 F:	include/net/ieee80211*
-F:	include/net/wireless.h
+F:	include/linux/wireless.h
 
 NETWORKING DRIVERS
 L:	netdev@vger.kernel.org
@@ -4578,6 +4577,13 @@
 F:	drivers/net/pppol2tp.c
 F:	include/linux/if_pppol2tp.h
 
+PPS SUPPORT
+P:	Rodolfo Giometti
+M:	giometti@enneenne.com
+W:	http://wiki.enneenne.com/index.php/LinuxPPS_support
+L:	linuxpps@ml.enneenne.com (subscribers-only)
+S:	Maintained
+
 PREEMPTIBLE KERNEL
 P:	Robert Love
 M:	rml@tech9.net
@@ -5473,6 +5479,7 @@
 P:	Greg Kroah-Hartman
 M:	gregkh@suse.de
 T:	quilt kernel.org/pub/linux/kernel/people/gregkh/gregkh-2.6/
+L:	devel@driverdev.osuosl.org
 S:	Maintained
 F:	drivers/staging/
 
diff --git a/Makefile b/Makefile
index ea63667..46e1c9d 100644
--- a/Makefile
+++ b/Makefile
@@ -330,6 +330,7 @@
 LDFLAGS_MODULE  =
 CFLAGS_KERNEL	=
 AFLAGS_KERNEL	=
+CFLAGS_GCOV	= -fprofile-arcs -ftest-coverage
 
 
 # Use LINUXINCLUDE when you must reference the include/ directory.
@@ -356,7 +357,7 @@
 export HOSTCXX HOSTCXXFLAGS LDFLAGS_MODULE CHECK CHECKFLAGS
 
 export KBUILD_CPPFLAGS NOSTDINC_FLAGS LINUXINCLUDE OBJCOPYFLAGS LDFLAGS
-export KBUILD_CFLAGS CFLAGS_KERNEL CFLAGS_MODULE
+export KBUILD_CFLAGS CFLAGS_KERNEL CFLAGS_MODULE CFLAGS_GCOV
 export KBUILD_AFLAGS AFLAGS_KERNEL AFLAGS_MODULE
 
 # When compiling out-of-tree modules, put MODVERDIR in the module
@@ -1216,8 +1217,8 @@
 		\( -name '*.[oas]' -o -name '*.ko' -o -name '.*.cmd' \
 		-o -name '.*.d' -o -name '.*.tmp' -o -name '*.mod.c' \
 		-o -name '*.symtypes' -o -name 'modules.order' \
-		-o -name 'Module.markers' -o -name '.tmp_*.o.*' \) \
-		-type f -print | xargs rm -f
+		-o -name 'Module.markers' -o -name '.tmp_*.o.*' \
+		-o -name '*.gcno' \) -type f -print | xargs rm -f
 
 # mrproper - Delete all generated files, including .config
 #
@@ -1421,8 +1422,8 @@
 	$(call cmd,rmfiles)
 	@find $(KBUILD_EXTMOD) $(RCS_FIND_IGNORE) \
 		\( -name '*.[oas]' -o -name '*.ko' -o -name '.*.cmd' \
-		-o -name '.*.d' -o -name '.*.tmp' -o -name '*.mod.c' \) \
-		-type f -print | xargs rm -f
+		-o -name '.*.d' -o -name '.*.tmp' -o -name '*.mod.c' \
+		-o -name '*.gcno' \) -type f -print | xargs rm -f
 
 help:
 	@echo  '  Building external modules.'
diff --git a/arch/Kconfig b/arch/Kconfig
index 78a35e9..99193b1 100644
--- a/arch/Kconfig
+++ b/arch/Kconfig
@@ -112,3 +112,5 @@
 
 config HAVE_DEFAULT_NO_SPIN_MUTEXES
 	bool
+
+source "kernel/gcov/Kconfig"
diff --git a/arch/alpha/include/asm/pci.h b/arch/alpha/include/asm/pci.h
index cb04eaa..d22ace9 100644
--- a/arch/alpha/include/asm/pci.h
+++ b/arch/alpha/include/asm/pci.h
@@ -237,19 +237,6 @@
 extern void pcibios_bus_to_resource(struct pci_dev *dev, struct resource *res,
 				    struct pci_bus_region *region);
 
-static inline struct resource *
-pcibios_select_root(struct pci_dev *pdev, struct resource *res)
-{
-	struct resource *root = NULL;
-
-	if (res->flags & IORESOURCE_IO)
-		root = &ioport_resource;
-	if (res->flags & IORESOURCE_MEM)
-		root = &iomem_resource;
-
-	return root;
-}
-
 #define pci_domain_nr(bus) ((struct pci_controller *)(bus)->sysdata)->index
 
 static inline int pci_proc_domain(struct pci_bus *bus)
diff --git a/arch/arm/include/asm/pci.h b/arch/arm/include/asm/pci.h
index 918d0cb..0abf386 100644
--- a/arch/arm/include/asm/pci.h
+++ b/arch/arm/include/asm/pci.h
@@ -65,19 +65,6 @@
 pcibios_bus_to_resource(struct pci_dev *dev, struct resource *res,
 			struct pci_bus_region *region);
 
-static inline struct resource *
-pcibios_select_root(struct pci_dev *pdev, struct resource *res)
-{
-	struct resource *root = NULL;
-
-	if (res->flags & IORESOURCE_IO)
-		root = &ioport_resource;
-	if (res->flags & IORESOURCE_MEM)
-		root = &iomem_resource;
-
-	return root;
-}
-
 /*
  * Dummy implementation; always return 0.
  */
diff --git a/arch/arm/mach-ep93xx/include/mach/ep93xx_keypad.h b/arch/arm/mach-ep93xx/include/mach/ep93xx_keypad.h
new file mode 100644
index 0000000..83f31cd
--- /dev/null
+++ b/arch/arm/mach-ep93xx/include/mach/ep93xx_keypad.h
@@ -0,0 +1,42 @@
+/*
+ * arch/arm/mach-ep93xx/include/mach/ep93xx_keypad.h
+ */
+
+#ifndef __ASM_ARCH_EP93XX_KEYPAD_H
+#define __ASM_ARCH_EP93XX_KEYPAD_H
+
+#define MAX_MATRIX_KEY_ROWS		(8)
+#define MAX_MATRIX_KEY_COLS		(8)
+
+/* flags for the ep93xx_keypad driver */
+#define EP93XX_KEYPAD_DISABLE_3_KEY	(1<<0)	/* disable 3-key reset */
+#define EP93XX_KEYPAD_DIAG_MODE		(1<<1)	/* diagnostic mode */
+#define EP93XX_KEYPAD_BACK_DRIVE	(1<<2)	/* back driving mode */
+#define EP93XX_KEYPAD_TEST_MODE		(1<<3)	/* scan only column 0 */
+#define EP93XX_KEYPAD_KDIV		(1<<4)	/* 1/4 clock or 1/16 clock */
+#define EP93XX_KEYPAD_AUTOREPEAT	(1<<5)	/* enable key autorepeat */
+
+/**
+ * struct ep93xx_keypad_platform_data - platform specific device structure
+ * @matrix_key_rows:		number of rows in the keypad matrix
+ * @matrix_key_cols:		number of columns in the keypad matrix
+ * @matrix_key_map:		array of keycodes defining the keypad matrix
+ * @matrix_key_map_size:	ARRAY_SIZE(matrix_key_map)
+ * @debounce:			debounce start count; terminal count is 0xff
+ * @prescale:			row/column counter pre-scaler load value
+ * @flags:			see above
+ */
+struct ep93xx_keypad_platform_data {
+	unsigned int	matrix_key_rows;
+	unsigned int	matrix_key_cols;
+	unsigned int	*matrix_key_map;
+	int		matrix_key_map_size;
+	unsigned int	debounce;
+	unsigned int	prescale;
+	unsigned int	flags;
+};
+
+/* macro for creating the matrix_key_map table */
+#define KEY(row, col, val)	(((row) << 28) | ((col) << 24) | (val))
+
+#endif	/* __ASM_ARCH_EP93XX_KEYPAD_H */
diff --git a/arch/avr32/kernel/process.c b/arch/avr32/kernel/process.c
index 1bbe1da..93c0342 100644
--- a/arch/avr32/kernel/process.c
+++ b/arch/avr32/kernel/process.c
@@ -394,8 +394,6 @@
 		goto out;
 
 	error = do_execve(filename, uargv, uenvp, regs);
-	if (error == 0)
-		current->ptrace &= ~PT_DTRACE;
 	putname(filename);
 
 out:
diff --git a/arch/blackfin/include/asm/atomic.h b/arch/blackfin/include/asm/atomic.h
index b1d92f1..88f36d5 100644
--- a/arch/blackfin/include/asm/atomic.h
+++ b/arch/blackfin/include/asm/atomic.h
@@ -1,24 +1,21 @@
 #ifndef __ARCH_BLACKFIN_ATOMIC__
 #define __ARCH_BLACKFIN_ATOMIC__
 
+#ifndef CONFIG_SMP
+# include <asm-generic/atomic.h>
+#else
+
 #include <linux/types.h>
 #include <asm/system.h>	/* local_irq_XXX() */
 
 /*
  * Atomic operations that C can't guarantee us.  Useful for
  * resource counting etc..
- *
- * Generally we do not concern about SMP BFIN systems, so we don't have
- * to deal with that.
- *
- * Tony Kou (tonyko@lineo.ca)   Lineo Inc.   2001
  */
 
 #define ATOMIC_INIT(i)	{ (i) }
 #define atomic_set(v, i)	(((v)->counter) = i)
 
-#ifdef CONFIG_SMP
-
 #define atomic_read(v)	__raw_uncached_fetch_asm(&(v)->counter)
 
 asmlinkage int __raw_uncached_fetch_asm(const volatile int *ptr);
@@ -84,100 +81,6 @@
 #define smp_mb__before_atomic_inc()    barrier()
 #define smp_mb__after_atomic_inc() barrier()
 
-#else /* !CONFIG_SMP */
-
-#define atomic_read(v)	((v)->counter)
-
-static inline void atomic_add(int i, atomic_t *v)
-{
-	unsigned long flags;
-
-	local_irq_save_hw(flags);
-	v->counter += i;
-	local_irq_restore_hw(flags);
-}
-
-static inline void atomic_sub(int i, atomic_t *v)
-{
-	unsigned long flags;
-
-	local_irq_save_hw(flags);
-	v->counter -= i;
-	local_irq_restore_hw(flags);
-
-}
-
-static inline int atomic_add_return(int i, atomic_t *v)
-{
-	int __temp = 0;
-	unsigned long flags;
-
-	local_irq_save_hw(flags);
-	v->counter += i;
-	__temp = v->counter;
-	local_irq_restore_hw(flags);
-
-
-	return __temp;
-}
-
-static inline int atomic_sub_return(int i, atomic_t *v)
-{
-	int __temp = 0;
-	unsigned long flags;
-
-	local_irq_save_hw(flags);
-	v->counter -= i;
-	__temp = v->counter;
-	local_irq_restore_hw(flags);
-
-	return __temp;
-}
-
-static inline void atomic_inc(volatile atomic_t *v)
-{
-	unsigned long flags;
-
-	local_irq_save_hw(flags);
-	v->counter++;
-	local_irq_restore_hw(flags);
-}
-
-static inline void atomic_dec(volatile atomic_t *v)
-{
-	unsigned long flags;
-
-	local_irq_save_hw(flags);
-	v->counter--;
-	local_irq_restore_hw(flags);
-}
-
-static inline void atomic_clear_mask(unsigned int mask, atomic_t *v)
-{
-	unsigned long flags;
-
-	local_irq_save_hw(flags);
-	v->counter &= ~mask;
-	local_irq_restore_hw(flags);
-}
-
-static inline void atomic_set_mask(unsigned int mask, atomic_t *v)
-{
-	unsigned long flags;
-
-	local_irq_save_hw(flags);
-	v->counter |= mask;
-	local_irq_restore_hw(flags);
-}
-
-/* Atomic operations are already serializing */
-#define smp_mb__before_atomic_dec()    barrier()
-#define smp_mb__after_atomic_dec() barrier()
-#define smp_mb__before_atomic_inc()    barrier()
-#define smp_mb__after_atomic_inc() barrier()
-
-#endif /* !CONFIG_SMP */
-
 #define atomic_add_negative(a, v)	(atomic_add_return((a), (v)) < 0)
 #define atomic_dec_return(v) atomic_sub_return(1,(v))
 #define atomic_inc_return(v) atomic_add_return(1,(v))
@@ -210,4 +113,6 @@
 
 #include <asm-generic/atomic-long.h>
 
-#endif				/* __ARCH_BLACKFIN_ATOMIC __ */
+#endif
+
+#endif
diff --git a/arch/blackfin/include/asm/auxvec.h b/arch/blackfin/include/asm/auxvec.h
index 215506c..41fa68b 100644
--- a/arch/blackfin/include/asm/auxvec.h
+++ b/arch/blackfin/include/asm/auxvec.h
@@ -1,4 +1 @@
-#ifndef __ASMBFIN_AUXVEC_H
-#define __ASMBFIN_AUXVEC_H
-
-#endif
+#include <asm-generic/auxvec.h>
diff --git a/arch/blackfin/include/asm/bitops.h b/arch/blackfin/include/asm/bitops.h
index 75fee2f..daffa71 100644
--- a/arch/blackfin/include/asm/bitops.h
+++ b/arch/blackfin/include/asm/bitops.h
@@ -1,26 +1,22 @@
 #ifndef _BLACKFIN_BITOPS_H
 #define _BLACKFIN_BITOPS_H
 
-/*
- * Copyright 1992, Linus Torvalds.
- */
-
-#include <linux/compiler.h>
-#include <asm/byteorder.h>	/* swab32 */
-
-#ifdef __KERNEL__
+#ifndef CONFIG_SMP
+# include <asm-generic/bitops.h>
+#else
 
 #ifndef _LINUX_BITOPS_H
 #error only <linux/bitops.h> can be included directly
 #endif
 
+#include <linux/compiler.h>
+#include <asm/byteorder.h>	/* swab32 */
+
 #include <asm-generic/bitops/ffs.h>
 #include <asm-generic/bitops/__ffs.h>
 #include <asm-generic/bitops/sched.h>
 #include <asm-generic/bitops/ffz.h>
 
-#ifdef CONFIG_SMP
-
 #include <linux/linkage.h>
 
 asmlinkage int __raw_bit_set_asm(volatile unsigned long *addr, int nr);
@@ -79,189 +75,13 @@
 	return __raw_bit_test_toggle_asm(a, nr & 0x1f);
 }
 
-#else /* !CONFIG_SMP */
-
-#include <asm/system.h>		/* save_flags */
-
-static inline void set_bit(int nr, volatile unsigned long *addr)
-{
-	int *a = (int *)addr;
-	int mask;
-	unsigned long flags;
-	a += nr >> 5;
-	mask = 1 << (nr & 0x1f);
-	local_irq_save_hw(flags);
-	*a |= mask;
-	local_irq_restore_hw(flags);
-}
-
-static inline void clear_bit(int nr, volatile unsigned long *addr)
-{
-	int *a = (int *)addr;
-	int mask;
-	unsigned long flags;
-	a += nr >> 5;
-	mask = 1 << (nr & 0x1f);
-	local_irq_save_hw(flags);
-	*a &= ~mask;
-	local_irq_restore_hw(flags);
-}
-
-static inline void change_bit(int nr, volatile unsigned long *addr)
-{
-	int mask;
-	unsigned long flags;
-	unsigned long *ADDR = (unsigned long *)addr;
-
-	ADDR += nr >> 5;
-	mask = 1 << (nr & 31);
-	local_irq_save_hw(flags);
-	*ADDR ^= mask;
-	local_irq_restore_hw(flags);
-}
-
-static inline int test_and_set_bit(int nr, volatile unsigned long *addr)
-{
-	int mask, retval;
-	volatile unsigned int *a = (volatile unsigned int *)addr;
-	unsigned long flags;
-
-	a += nr >> 5;
-	mask = 1 << (nr & 0x1f);
-	local_irq_save_hw(flags);
-	retval = (mask & *a) != 0;
-	*a |= mask;
-	local_irq_restore_hw(flags);
-
-	return retval;
-}
-
-static inline int test_and_clear_bit(int nr, volatile unsigned long *addr)
-{
-	int mask, retval;
-	volatile unsigned int *a = (volatile unsigned int *)addr;
-	unsigned long flags;
-
-	a += nr >> 5;
-	mask = 1 << (nr & 0x1f);
-	local_irq_save_hw(flags);
-	retval = (mask & *a) != 0;
-	*a &= ~mask;
-	local_irq_restore_hw(flags);
-
-	return retval;
-}
-
-static inline int test_and_change_bit(int nr, volatile unsigned long *addr)
-{
-	int mask, retval;
-	volatile unsigned int *a = (volatile unsigned int *)addr;
-	unsigned long flags;
-
-	a += nr >> 5;
-	mask = 1 << (nr & 0x1f);
-	local_irq_save_hw(flags);
-	retval = (mask & *a) != 0;
-	*a ^= mask;
-	local_irq_restore_hw(flags);
-	return retval;
-}
-
-#endif /* CONFIG_SMP */
-
 /*
  * clear_bit() doesn't provide any barrier for the compiler.
  */
 #define smp_mb__before_clear_bit()	barrier()
 #define smp_mb__after_clear_bit()	barrier()
 
-static inline void __set_bit(int nr, volatile unsigned long *addr)
-{
-	int *a = (int *)addr;
-	int mask;
-
-	a += nr >> 5;
-	mask = 1 << (nr & 0x1f);
-	*a |= mask;
-}
-
-static inline void __clear_bit(int nr, volatile unsigned long *addr)
-{
-	int *a = (int *)addr;
-	int mask;
-
-	a += nr >> 5;
-	mask = 1 << (nr & 0x1f);
-	*a &= ~mask;
-}
-
-static inline void __change_bit(int nr, volatile unsigned long *addr)
-{
-	int mask;
-	unsigned long *ADDR = (unsigned long *)addr;
-
-	ADDR += nr >> 5;
-	mask = 1 << (nr & 31);
-	*ADDR ^= mask;
-}
-
-static inline int __test_and_set_bit(int nr, volatile unsigned long *addr)
-{
-	int mask, retval;
-	volatile unsigned int *a = (volatile unsigned int *)addr;
-
-	a += nr >> 5;
-	mask = 1 << (nr & 0x1f);
-	retval = (mask & *a) != 0;
-	*a |= mask;
-	return retval;
-}
-
-static inline int __test_and_clear_bit(int nr, volatile unsigned long *addr)
-{
-	int mask, retval;
-	volatile unsigned int *a = (volatile unsigned int *)addr;
-
-	a += nr >> 5;
-	mask = 1 << (nr & 0x1f);
-	retval = (mask & *a) != 0;
-	*a &= ~mask;
-	return retval;
-}
-
-static inline int __test_and_change_bit(int nr,
-					    volatile unsigned long *addr)
-{
-	int mask, retval;
-	volatile unsigned int *a = (volatile unsigned int *)addr;
-
-	a += nr >> 5;
-	mask = 1 << (nr & 0x1f);
-	retval = (mask & *a) != 0;
-	*a ^= mask;
-	return retval;
-}
-
-static inline int __test_bit(int nr, const void *addr)
-{
-	int *a = (int *)addr;
-	int mask;
-
-	a += nr >> 5;
-	mask = 1 << (nr & 0x1f);
-	return ((mask & *a) != 0);
-}
-
-#ifndef CONFIG_SMP
-/*
- * This routine doesn't need irq save and restore ops in UP
- * context.
- */
-static inline int test_bit(int nr, const void *addr)
-{
-	return __test_bit(nr, addr);
-}
-#endif
+#include <asm-generic/bitops/non-atomic.h>
 
 #include <asm-generic/bitops/find.h>
 #include <asm-generic/bitops/hweight.h>
@@ -272,10 +92,10 @@
 
 #include <asm-generic/bitops/minix.h>
 
-#endif				/* __KERNEL__ */
-
 #include <asm-generic/bitops/fls.h>
 #include <asm-generic/bitops/__fls.h>
 #include <asm-generic/bitops/fls64.h>
 
+#endif /* CONFIG_SMP */
+
 #endif				/* _BLACKFIN_BITOPS_H */
diff --git a/arch/blackfin/include/asm/bugs.h b/arch/blackfin/include/asm/bugs.h
index 9093c9c..61791e1 100644
--- a/arch/blackfin/include/asm/bugs.h
+++ b/arch/blackfin/include/asm/bugs.h
@@ -1,16 +1 @@
-/*
- *  include/asm-blackfin/bugs.h
- *
- *  Copyright (C) 1994  Linus Torvalds
- */
-
-/*
- * This is included by init/main.c to check for architecture-dependent bugs.
- *
- * Needs:
- *	void check_bugs(void);
- */
-
-static void check_bugs(void)
-{
-}
+#include <asm-generic/bugs.h>
diff --git a/arch/blackfin/include/asm/cputime.h b/arch/blackfin/include/asm/cputime.h
index 2b19705..6d68ad7 100644
--- a/arch/blackfin/include/asm/cputime.h
+++ b/arch/blackfin/include/asm/cputime.h
@@ -1,6 +1 @@
-#ifndef __BLACKFIN_CPUTIME_H
-#define __BLACKFIN_CPUTIME_H
-
 #include <asm-generic/cputime.h>
-
-#endif				/* __BLACKFIN_CPUTIME_H */
diff --git a/arch/blackfin/include/asm/current.h b/arch/blackfin/include/asm/current.h
index 31918d2..4c51401 100644
--- a/arch/blackfin/include/asm/current.h
+++ b/arch/blackfin/include/asm/current.h
@@ -1,23 +1 @@
-#ifndef _BLACKFIN_CURRENT_H
-#define _BLACKFIN_CURRENT_H
-/*
- *	current.h
- *	(C) Copyright 2000, Lineo, David McCullough <davidm@lineo.com>
- *
- *	rather than dedicate a register (as the m68k source does), we
- *	just keep a global,  we should probably just change it all to be
- *	current and lose _current_task.
- */
-#include <linux/thread_info.h>
-
-struct task_struct;
-
-static inline struct task_struct *get_current(void) __attribute__ ((__const__));
-static inline struct task_struct *get_current(void)
-{
-	return (current_thread_info()->task);
-}
-
-#define	current	(get_current())
-
-#endif				/* _BLACKFIN_CURRENT_H */
+#include <asm-generic/current.h>
diff --git a/arch/blackfin/include/asm/device.h b/arch/blackfin/include/asm/device.h
index d8f9872..f0a4c25 100644
--- a/arch/blackfin/include/asm/device.h
+++ b/arch/blackfin/include/asm/device.h
@@ -1,7 +1 @@
-/*
- * Arch specific extensions to struct device
- *
- * This file is released under the GPLv2
- */
 #include <asm-generic/device.h>
-
diff --git a/arch/blackfin/include/asm/elf.h b/arch/blackfin/include/asm/elf.h
index 230e160..5a87baf 100644
--- a/arch/blackfin/include/asm/elf.h
+++ b/arch/blackfin/include/asm/elf.h
@@ -20,7 +20,7 @@
 
 typedef unsigned long elf_greg_t;
 
-#define ELF_NGREG (sizeof(struct user_regs_struct) / sizeof(elf_greg_t))
+#define ELF_NGREG 40 /* (sizeof(struct user_regs_struct) / sizeof(elf_greg_t)) */
 typedef elf_greg_t elf_gregset_t[ELF_NGREG];
 
 typedef struct user_bfinfp_struct elf_fpregset_t;
diff --git a/arch/blackfin/include/asm/emergency-restart.h b/arch/blackfin/include/asm/emergency-restart.h
index 27f6c78..3711bd9 100644
--- a/arch/blackfin/include/asm/emergency-restart.h
+++ b/arch/blackfin/include/asm/emergency-restart.h
@@ -1,6 +1 @@
-#ifndef _ASM_EMERGENCY_RESTART_H
-#define _ASM_EMERGENCY_RESTART_H
-
 #include <asm-generic/emergency-restart.h>
-
-#endif				/* _ASM_EMERGENCY_RESTART_H */
diff --git a/arch/blackfin/include/asm/errno.h b/arch/blackfin/include/asm/errno.h
index 164e4f3..4c82b50 100644
--- a/arch/blackfin/include/asm/errno.h
+++ b/arch/blackfin/include/asm/errno.h
@@ -1,6 +1 @@
-#ifndef _BFIN_ERRNO_H
-#define _BFIN_ERRNO_H
-
-#include<asm-generic/errno.h>
-
-#endif				/* _BFIN_ERRNO_H */
+#include <asm-generic/errno.h>
diff --git a/arch/blackfin/include/asm/fb.h b/arch/blackfin/include/asm/fb.h
index c7df380..3a4988e 100644
--- a/arch/blackfin/include/asm/fb.h
+++ b/arch/blackfin/include/asm/fb.h
@@ -1,12 +1 @@
-#ifndef _ASM_FB_H_
-#define _ASM_FB_H_
-#include <linux/fb.h>
-
-#define fb_pgprotect(...) do {} while (0)
-
-static inline int fb_is_primary_device(struct fb_info *info)
-{
-	return 0;
-}
-
-#endif /* _ASM_FB_H_ */
+#include <asm-generic/fb.h>
diff --git a/arch/blackfin/include/asm/futex.h b/arch/blackfin/include/asm/futex.h
index 6a332a9..0b74582 100644
--- a/arch/blackfin/include/asm/futex.h
+++ b/arch/blackfin/include/asm/futex.h
@@ -1,6 +1 @@
-#ifndef _ASM_FUTEX_H
-#define _ASM_FUTEX_H
-
 #include <asm-generic/futex.h>
-
-#endif
diff --git a/arch/blackfin/include/asm/hardirq.h b/arch/blackfin/include/asm/hardirq.h
index 717181a..cbd52f8 100644
--- a/arch/blackfin/include/asm/hardirq.h
+++ b/arch/blackfin/include/asm/hardirq.h
@@ -1,47 +1,11 @@
 #ifndef __BFIN_HARDIRQ_H
 #define __BFIN_HARDIRQ_H
 
-#include <linux/cache.h>
-#include <linux/threads.h>
-#include <asm/irq.h>
-
-typedef struct {
-	unsigned int __softirq_pending;
-	unsigned int __syscall_count;
-	struct task_struct *__ksoftirqd_task;
-} ____cacheline_aligned irq_cpustat_t;
-
-#include <linux/irq_cpustat.h>	/* Standard mappings for irq_cpustat_t above */
-
-/*
- * We put the hardirq and softirq counter into the preemption
- * counter. The bitmask has the following meaning:
- *
- * - bits 0-7 are the preemption count (max preemption depth: 256)
- * - bits 8-15 are the softirq count (max # of softirqs: 256)
- * - bits 16-23 are the hardirq count (max # of hardirqs: 256)
- *
- * - ( bit 26 is the PREEMPT_ACTIVE flag. )
- *
- * PREEMPT_MASK: 0x000000ff
- * HARDIRQ_MASK: 0x0000ff00
- * SOFTIRQ_MASK: 0x00ff0000
- */
-
-#if NR_IRQS > 256
-#define HARDIRQ_BITS	9
-#else
-#define HARDIRQ_BITS	8
-#endif
-
-#ifdef NR_IRQS
-# if (1 << HARDIRQ_BITS) < NR_IRQS
-# error HARDIRQ_BITS is too low!
-# endif
-#endif
-
 #define __ARCH_IRQ_EXIT_IRQS_DISABLED	1
 
 extern void ack_bad_irq(unsigned int irq);
+#define ack_bad_irq ack_bad_irq
+
+#include <asm-generic/hardirq.h>
 
 #endif
diff --git a/arch/blackfin/include/asm/hw_irq.h b/arch/blackfin/include/asm/hw_irq.h
index 5b51eae..1f5ef7d 100644
--- a/arch/blackfin/include/asm/hw_irq.h
+++ b/arch/blackfin/include/asm/hw_irq.h
@@ -1,6 +1 @@
-#ifndef __ASM_BFIN_HW_IRQ_H
-#define __ASM_BFIN_HW_IRQ_H
-
-/* Dummy include. */
-
-#endif
+#include <asm-generic/hw_irq.h>
diff --git a/arch/blackfin/include/asm/io.h b/arch/blackfin/include/asm/io.h
index 3022b5c..37053ec 100644
--- a/arch/blackfin/include/asm/io.h
+++ b/arch/blackfin/include/asm/io.h
@@ -222,7 +222,6 @@
 #define	ioport_unmap(addr)
 
 /* Pages to physical address... */
-#define page_to_phys(page)      ((page - mem_map) << PAGE_SHIFT)
 #define page_to_bus(page)       ((page - mem_map) << PAGE_SHIFT)
 
 #define phys_to_virt(vaddr)	((void *) (vaddr))
diff --git a/arch/blackfin/include/asm/ioctls.h b/arch/blackfin/include/asm/ioctls.h
index 895e317..eca8d75 100644
--- a/arch/blackfin/include/asm/ioctls.h
+++ b/arch/blackfin/include/asm/ioctls.h
@@ -1,87 +1,7 @@
 #ifndef __ARCH_BFIN_IOCTLS_H__
 #define __ARCH_BFIN_IOCTLS_H__
 
-#include <asm/ioctl.h>
-
-/* 0x54 is just a magic number to make these relatively unique ('T') */
-
-#define TCGETS		0x5401
-#define TCSETS		0x5402
-#define TCSETSW		0x5403
-#define TCSETSF		0x5404
-#define TCGETA		0x5405
-#define TCSETA		0x5406
-#define TCSETAW		0x5407
-#define TCSETAF		0x5408
-#define TCSBRK		0x5409
-#define TCXONC		0x540A
-#define TCFLSH		0x540B
-#define TIOCEXCL	0x540C
-#define TIOCNXCL	0x540D
-#define TIOCSCTTY	0x540E
-#define TIOCGPGRP	0x540F
-#define TIOCSPGRP	0x5410
-#define TIOCOUTQ	0x5411
-#define TIOCSTI		0x5412
-#define TIOCGWINSZ	0x5413
-#define TIOCSWINSZ	0x5414
-#define TIOCMGET	0x5415
-#define TIOCMBIS	0x5416
-#define TIOCMBIC	0x5417
-#define TIOCMSET	0x5418
-#define TIOCGSOFTCAR	0x5419
-#define TIOCSSOFTCAR	0x541A
-#define FIONREAD	0x541B
-#define TIOCINQ		FIONREAD
-#define TIOCLINUX	0x541C
-#define TIOCCONS	0x541D
-#define TIOCGSERIAL	0x541E
-#define TIOCSSERIAL	0x541F
-#define TIOCPKT		0x5420
-#define FIONBIO		0x5421
-#define TIOCNOTTY	0x5422
-#define TIOCSETD	0x5423
-#define TIOCGETD	0x5424
-#define TCSBRKP		0x5425	/* Needed for POSIX tcsendbreak() */
-#define TIOCTTYGSTRUCT	0x5426	/* For debugging only */
-#define TIOCSBRK	0x5427	/* BSD compatibility */
-#define TIOCCBRK	0x5428	/* BSD compatibility */
-#define TIOCGSID	0x5429	/* Return the session ID of FD */
-#define TCGETS2		_IOR('T', 0x2A, struct termios2)
-#define TCSETS2		_IOW('T', 0x2B, struct termios2)
-#define TCSETSW2	_IOW('T', 0x2C, struct termios2)
-#define TCSETSF2	_IOW('T', 0x2D, struct termios2)
-/* Get Pty Number (of pty-mux device) */
-#define TIOCGPTN	_IOR('T', 0x30, unsigned int)
-#define TIOCSPTLCK	_IOW('T', 0x31, int)	/* Lock/unlock Pty */
-
-#define FIONCLEX	0x5450	/* these numbers need to be adjusted. */
-#define FIOCLEX		0x5451
-#define FIOASYNC	0x5452
-#define TIOCSERCONFIG	0x5453
-#define TIOCSERGWILD	0x5454
-#define TIOCSERSWILD	0x5455
-#define TIOCGLCKTRMIOS	0x5456
-#define TIOCSLCKTRMIOS	0x5457
-#define TIOCSERGSTRUCT	0x5458	/* For debugging only */
-#define TIOCSERGETLSR   0x5459	/* Get line status register */
-#define TIOCSERGETMULTI 0x545A	/* Get multiport config  */
-#define TIOCSERSETMULTI 0x545B	/* Set multiport config */
-
-#define TIOCMIWAIT	0x545C	/* wait for a change on serial input line(s) */
-#define TIOCGICOUNT	0x545D	/* read serial port inline interrupt counts */
-
 #define FIOQSIZE	0x545E
+#include <asm-generic/ioctls.h>
 
-/* Used for packet mode */
-#define TIOCPKT_DATA		 0
-#define TIOCPKT_FLUSHREAD	 1
-#define TIOCPKT_FLUSHWRITE	 2
-#define TIOCPKT_STOP		 4
-#define TIOCPKT_START		 8
-#define TIOCPKT_NOSTOP		16
-#define TIOCPKT_DOSTOP		32
-
-#define TIOCSER_TEMT    0x01	/* Transmitter physically empty */
-
-#endif				/* __ARCH_BFIN_IOCTLS_H__ */
+#endif
diff --git a/arch/blackfin/include/asm/ipcbuf.h b/arch/blackfin/include/asm/ipcbuf.h
index 8f0899c..84c7e51 100644
--- a/arch/blackfin/include/asm/ipcbuf.h
+++ b/arch/blackfin/include/asm/ipcbuf.h
@@ -1,30 +1 @@
-/* Changes origined from m68k version.    Lineo Inc.  May 2001   */
-
-#ifndef __BFIN_IPCBUF_H__
-#define __BFIN_IPCBUF_H__
-
-/*
- * The user_ipc_perm structure for m68k architecture.
- * Note extra padding because this structure is passed back and forth
- * between kernel and user space.
- *
- * Pad space is left for:
- * - 32-bit mode_t and seq
- * - 2 miscellaneous 32-bit values
- */
-
-struct ipc64_perm {
-	__kernel_key_t key;
-	__kernel_uid32_t uid;
-	__kernel_gid32_t gid;
-	__kernel_uid32_t cuid;
-	__kernel_gid32_t cgid;
-	__kernel_mode_t mode;
-	unsigned short __pad1;
-	unsigned short seq;
-	unsigned short __pad2;
-	unsigned long __unused1;
-	unsigned long __unused2;
-};
-
-#endif				/* __BFIN_IPCBUF_H__ */
+#include <asm-generic/ipcbuf.h>
diff --git a/arch/blackfin/include/asm/irq.h b/arch/blackfin/include/asm/irq.h
index 400bdd5..9a7f63a 100644
--- a/arch/blackfin/include/asm/irq.h
+++ b/arch/blackfin/include/asm/irq.h
@@ -45,9 +45,6 @@
 		: "d" (bfin_irq_flags) \
 	)
 
-static inline int irq_canonicalize(int irq)
-{
-	return irq;
-}
+#include <asm-generic/irq.h>
 
 #endif				/* _BFIN_IRQ_H_ */
diff --git a/arch/blackfin/include/asm/kmap_types.h b/arch/blackfin/include/asm/kmap_types.h
index 0a88622..3575c64 100644
--- a/arch/blackfin/include/asm/kmap_types.h
+++ b/arch/blackfin/include/asm/kmap_types.h
@@ -1,6 +1 @@
-#ifndef _ASM_KMAP_TYPES_H
-#define _ASM_KMAP_TYPES_H
-
 #include <asm-generic/kmap_types.h>
-
-#endif
diff --git a/arch/blackfin/include/asm/local.h b/arch/blackfin/include/asm/local.h
index 75afffb..c11c530 100644
--- a/arch/blackfin/include/asm/local.h
+++ b/arch/blackfin/include/asm/local.h
@@ -1,6 +1 @@
-#ifndef __BLACKFIN_LOCAL_H
-#define __BLACKFIN_LOCAL_H
-
 #include <asm-generic/local.h>
-
-#endif				/* __BLACKFIN_LOCAL_H */
diff --git a/arch/blackfin/include/asm/mman.h b/arch/blackfin/include/asm/mman.h
index b58f5ad..8eebf89f5 100644
--- a/arch/blackfin/include/asm/mman.h
+++ b/arch/blackfin/include/asm/mman.h
@@ -1,43 +1 @@
-#ifndef __BFIN_MMAN_H__
-#define __BFIN_MMAN_H__
-
-#define PROT_READ	0x1	/* page can be read */
-#define PROT_WRITE	0x2	/* page can be written */
-#define PROT_EXEC	0x4	/* page can be executed */
-#define PROT_SEM	0x8	/* page may be used for atomic ops */
-#define PROT_NONE	0x0	/* page can not be accessed */
-#define PROT_GROWSDOWN	0x01000000	/* mprotect flag: extend change to start of growsdown vma */
-#define PROT_GROWSUP	0x02000000	/* mprotect flag: extend change to end of growsup vma */
-
-#define MAP_SHARED	0x01	/* Share changes */
-#define MAP_PRIVATE	0x02	/* Changes are private */
-#define MAP_TYPE	0x0f	/* Mask for type of mapping */
-#define MAP_FIXED	0x10	/* Interpret addr exactly */
-#define MAP_ANONYMOUS	0x20	/* don't use a file */
-
-#define MAP_GROWSDOWN	0x0100	/* stack-like segment */
-#define MAP_DENYWRITE	0x0800	/* ETXTBSY */
-#define MAP_EXECUTABLE	0x1000	/* mark it as an executable */
-#define MAP_LOCKED	0x2000	/* pages are locked */
-#define MAP_NORESERVE	0x4000	/* don't check for reservations */
-#define MAP_POPULATE	0x8000	/* populate (prefault) pagetables */
-#define MAP_NONBLOCK	0x10000	/* do not block on IO */
-
-#define MS_ASYNC	1	/* sync memory asynchronously */
-#define MS_INVALIDATE	2	/* invalidate the caches */
-#define MS_SYNC		4	/* synchronous memory sync */
-
-#define MCL_CURRENT	1	/* lock all current mappings */
-#define MCL_FUTURE	2	/* lock all future mappings */
-
-#define MADV_NORMAL	0x0	/* default page-in behavior */
-#define MADV_RANDOM	0x1	/* page-in minimum required */
-#define MADV_SEQUENTIAL	0x2	/* read-ahead aggressively */
-#define MADV_WILLNEED	0x3	/* pre-fault pages */
-#define MADV_DONTNEED	0x4	/* discard these pages */
-
-/* compatibility flags */
-#define MAP_ANON	MAP_ANONYMOUS
-#define MAP_FILE	0
-
-#endif				/* __BFIN_MMAN_H__ */
+#include <asm-generic/mman.h>
diff --git a/arch/blackfin/include/asm/msgbuf.h b/arch/blackfin/include/asm/msgbuf.h
index 6fcbe8c..809134c 100644
--- a/arch/blackfin/include/asm/msgbuf.h
+++ b/arch/blackfin/include/asm/msgbuf.h
@@ -1,31 +1 @@
-#ifndef _BFIN_MSGBUF_H
-#define _BFIN_MSGBUF_H
-
-/*
- * The msqid64_ds structure for bfin architecture.
- * Note extra padding because this structure is passed back and forth
- * between kernel and user space.
- *
- * Pad space is left for:
- * - 64-bit time_t to solve y2038 problem
- * - 2 miscellaneous 32-bit values
- */
-
-struct msqid64_ds {
-	struct ipc64_perm msg_perm;
-	__kernel_time_t msg_stime;	/* last msgsnd time */
-	unsigned long __unused1;
-	__kernel_time_t msg_rtime;	/* last msgrcv time */
-	unsigned long __unused2;
-	__kernel_time_t msg_ctime;	/* last change time */
-	unsigned long __unused3;
-	unsigned long msg_cbytes;	/* current number of bytes on queue */
-	unsigned long msg_qnum;	/* number of messages in queue */
-	unsigned long msg_qbytes;	/* max number of bytes on queue */
-	__kernel_pid_t msg_lspid;	/* pid of last msgsnd */
-	__kernel_pid_t msg_lrpid;	/* last receive pid */
-	unsigned long __unused4;
-	unsigned long __unused5;
-};
-
-#endif				/* _BFIN_MSGBUF_H */
+#include <asm-generic/msgbuf.h>
diff --git a/arch/blackfin/include/asm/mutex.h b/arch/blackfin/include/asm/mutex.h
index 5d39925..5cc641c 100644
--- a/arch/blackfin/include/asm/mutex.h
+++ b/arch/blackfin/include/asm/mutex.h
@@ -10,7 +10,7 @@
 #define _ASM_MUTEX_H
 
 #ifndef CONFIG_SMP
-#include <asm-generic/mutex-dec.h>
+#include <asm-generic/mutex.h>
 #else
 
 static inline void
diff --git a/arch/blackfin/include/asm/page.h b/arch/blackfin/include/asm/page.h
index 3ea2016..29dcf75 100644
--- a/arch/blackfin/include/asm/page.h
+++ b/arch/blackfin/include/asm/page.h
@@ -1,88 +1,7 @@
 #ifndef _BLACKFIN_PAGE_H
 #define _BLACKFIN_PAGE_H
 
-/* PAGE_SHIFT determines the page size */
+#include <asm-generic/page.h>
+#define MAP_NR(addr) (((unsigned long)(addr)-PAGE_OFFSET) >> PAGE_SHIFT)
 
-#define PAGE_SHIFT	12
-#ifdef __ASSEMBLY__
-#define PAGE_SIZE	(1 << PAGE_SHIFT)
-#else
-#define PAGE_SIZE	(1UL << PAGE_SHIFT)
 #endif
-#define PAGE_MASK	(~(PAGE_SIZE-1))
-
-#include <asm/setup.h>
-
-#ifndef __ASSEMBLY__
-
-#define get_user_page(vaddr)		__get_free_page(GFP_KERNEL)
-#define free_user_page(page, addr)	free_page(addr)
-
-#define clear_page(page)	memset((page), 0, PAGE_SIZE)
-#define copy_page(to,from)	memcpy((to), (from), PAGE_SIZE)
-
-#define clear_user_page(page, vaddr,pg)	clear_page(page)
-#define copy_user_page(to, from, vaddr,pg)	copy_page(to, from)
-
-/*
- * These are used to make use of C type-checking..
- */
-typedef struct {
-	unsigned long pte;
-} pte_t;
-typedef struct {
-	unsigned long pmd[16];
-} pmd_t;
-typedef struct {
-	unsigned long pgd;
-} pgd_t;
-typedef struct {
-	unsigned long pgprot;
-} pgprot_t;
-typedef struct page *pgtable_t;
-
-#define pte_val(x)	((x).pte)
-#define pmd_val(x)	((&x)->pmd[0])
-#define pgd_val(x)	((x).pgd)
-#define pgprot_val(x)	((x).pgprot)
-
-#define __pte(x)	((pte_t) { (x) } )
-#define __pmd(x)	((pmd_t) { (x) } )
-#define __pgd(x)	((pgd_t) { (x) } )
-#define __pgprot(x)	((pgprot_t) { (x) } )
-
-extern unsigned long memory_start;
-extern unsigned long memory_end;
-
-#endif				/* !__ASSEMBLY__ */
-
-#include <asm/page_offset.h>
-#include <asm/io.h>
-
-#define PAGE_OFFSET		(PAGE_OFFSET_RAW)
-
-#ifndef __ASSEMBLY__
-
-#define __pa(vaddr)		virt_to_phys((void *)(vaddr))
-#define __va(paddr)		phys_to_virt((unsigned long)(paddr))
-
-#define MAP_NR(addr)		(((unsigned long)(addr)-PAGE_OFFSET) >> PAGE_SHIFT)
-
-#define virt_to_pfn(kaddr)	(__pa(kaddr) >> PAGE_SHIFT)
-#define pfn_to_virt(pfn)	__va((pfn) << PAGE_SHIFT)
-#define virt_to_page(addr)	(mem_map + (((unsigned long)(addr)-PAGE_OFFSET) >> PAGE_SHIFT))
-#define page_to_virt(page)	((((page) - mem_map) << PAGE_SHIFT) + PAGE_OFFSET)
-#define VALID_PAGE(page)	((page - mem_map) < max_mapnr)
-
-#define pfn_to_page(pfn)	virt_to_page(pfn_to_virt(pfn))
-#define page_to_pfn(page)	virt_to_pfn(page_to_virt(page))
-#define pfn_valid(pfn)	        ((pfn) < max_mapnr)
-
-#define	virt_addr_valid(kaddr)	(((void *)(kaddr) >= (void *)PAGE_OFFSET) && \
-				((void *)(kaddr) < (void *)memory_end))
-
-#include <asm-generic/getorder.h>
-
-#endif				/* __ASSEMBLY__ */
-
-#endif				/* _BLACKFIN_PAGE_H */
diff --git a/arch/blackfin/include/asm/param.h b/arch/blackfin/include/asm/param.h
index 41564a6..965d454 100644
--- a/arch/blackfin/include/asm/param.h
+++ b/arch/blackfin/include/asm/param.h
@@ -1,22 +1 @@
-#ifndef _BLACKFIN_PARAM_H
-#define _BLACKFIN_PARAM_H
-
-#ifdef __KERNEL__
-#define HZ 		CONFIG_HZ
-#define	USER_HZ		100
-#define	CLOCKS_PER_SEC	(USER_HZ)
-#endif
-
-#ifndef HZ
-#define HZ 100
-#endif
-
-#define EXEC_PAGESIZE	4096
-
-#ifndef NOGROUP
-#define NOGROUP		(-1)
-#endif
-
-#define MAXHOSTNAMELEN	64	/* max length of hostname */
-
-#endif				/* _BLACKFIN_PARAM_H */
+#include <asm-generic/param.h>
diff --git a/arch/blackfin/include/asm/percpu.h b/arch/blackfin/include/asm/percpu.h
index c94c7bc..06a959d 100644
--- a/arch/blackfin/include/asm/percpu.h
+++ b/arch/blackfin/include/asm/percpu.h
@@ -1,6 +1 @@
-#ifndef __ARCH_BLACKFIN_PERCPU__
-#define __ARCH_BLACKFIN_PERCPU__
-
 #include <asm-generic/percpu.h>
-
-#endif	/* __ARCH_BLACKFIN_PERCPU__ */
diff --git a/arch/blackfin/include/asm/pgalloc.h b/arch/blackfin/include/asm/pgalloc.h
index c686e05..f261cb7 100644
--- a/arch/blackfin/include/asm/pgalloc.h
+++ b/arch/blackfin/include/asm/pgalloc.h
@@ -1,8 +1 @@
-#ifndef _BLACKFIN_PGALLOC_H
-#define _BLACKFIN_PGALLOC_H
-
-#include <asm/setup.h>
-
-#define check_pgt_cache()	do { } while (0)
-
-#endif				/* _BLACKFIN_PGALLOC_H */
+#include <asm-generic/pgalloc.h>
diff --git a/arch/blackfin/include/asm/poll.h b/arch/blackfin/include/asm/poll.h
index 94cc263..a055667 100644
--- a/arch/blackfin/include/asm/poll.h
+++ b/arch/blackfin/include/asm/poll.h
@@ -1,24 +1,9 @@
 #ifndef __BFIN_POLL_H
 #define __BFIN_POLL_H
 
-#define POLLIN		  1
-#define POLLPRI		  2
-#define POLLOUT		  4
-#define POLLERR		  8
-#define POLLHUP		 16
-#define POLLNVAL	 32
-#define POLLRDNORM	 64
-#define POLLWRNORM	POLLOUT
-#define POLLRDBAND	128
+#define POLLWRNORM	4 /* POLLOUT */
 #define POLLWRBAND	256
-#define POLLMSG		0x0400
-#define POLLREMOVE	0x1000
-#define POLLRDHUP       0x2000
 
-struct pollfd {
-	int fd;
-	short events;
-	short revents;
-};
+#include <asm-generic/poll.h>
 
-#endif				/* __BFIN_POLL_H */
+#endif
diff --git a/arch/blackfin/include/asm/posix_types.h b/arch/blackfin/include/asm/posix_types.h
index 23aa1f8..80c9d64 100644
--- a/arch/blackfin/include/asm/posix_types.h
+++ b/arch/blackfin/include/asm/posix_types.h
@@ -1,61 +1,27 @@
 #ifndef __ARCH_BFIN_POSIX_TYPES_H
 #define __ARCH_BFIN_POSIX_TYPES_H
 
-/*
- * This file is generally used by user-level software, so you need to
- * be a little careful about namespace pollution etc.  Also, we cannot
- * assume GCC is being used.
- */
-
-typedef unsigned long __kernel_ino_t;
 typedef unsigned short __kernel_mode_t;
+#define __kernel_mode_t __kernel_mode_t
+
 typedef unsigned short __kernel_nlink_t;
-typedef long __kernel_off_t;
-typedef int __kernel_pid_t;
+#define __kernel_nlink_t __kernel_nlink_t
+
 typedef unsigned int __kernel_ipc_pid_t;
-typedef unsigned int __kernel_uid_t;
-typedef unsigned int __kernel_gid_t;
+#define __kernel_ipc_pid_t __kernel_ipc_pid_t
+
 typedef unsigned long __kernel_size_t;
 typedef long __kernel_ssize_t;
 typedef int __kernel_ptrdiff_t;
-typedef long __kernel_time_t;
-typedef long __kernel_suseconds_t;
-typedef long __kernel_clock_t;
-typedef int __kernel_timer_t;
-typedef int __kernel_clockid_t;
-typedef int __kernel_daddr_t;
-typedef char *__kernel_caddr_t;
-typedef unsigned short __kernel_uid16_t;
-typedef unsigned short __kernel_gid16_t;
-typedef unsigned int __kernel_uid32_t;
-typedef unsigned int __kernel_gid32_t;
+#define __kernel_size_t __kernel_size_t
 
 typedef unsigned short __kernel_old_uid_t;
 typedef unsigned short __kernel_old_gid_t;
+#define __kernel_old_uid_t __kernel_old_uid_t
+
 typedef unsigned short __kernel_old_dev_t;
+#define __kernel_old_dev_t __kernel_old_dev_t
 
-#ifdef __GNUC__
-typedef long long __kernel_loff_t;
-#endif
-
-typedef struct {
-	int val[2];
-} __kernel_fsid_t;
-
-#if defined(__KERNEL__)
-
-#undef	__FD_SET
-#define	__FD_SET(d, set)	((set)->fds_bits[__FDELT(d)] |= __FDMASK(d))
-
-#undef	__FD_CLR
-#define	__FD_CLR(d, set)	((set)->fds_bits[__FDELT(d)] &= ~__FDMASK(d))
-
-#undef	__FD_ISSET
-#define	__FD_ISSET(d, set)	((set)->fds_bits[__FDELT(d)] & __FDMASK(d))
-
-#undef	__FD_ZERO
-#define __FD_ZERO(fdsetp) (memset (fdsetp, 0, sizeof(*(fd_set *)fdsetp)))
-
-#endif				/* defined(__KERNEL__) */
+#include <asm-generic/posix_types.h>
 
 #endif
diff --git a/arch/blackfin/include/asm/processor.h b/arch/blackfin/include/asm/processor.h
index 3040415..d0be99b 100644
--- a/arch/blackfin/include/asm/processor.h
+++ b/arch/blackfin/include/asm/processor.h
@@ -7,9 +7,8 @@
  */
 #define current_text_addr() ({ __label__ _l; _l: &&_l;})
 
+#include <asm/ptrace.h>
 #include <asm/blackfin.h>
-#include <asm/segment.h>
-#include <linux/compiler.h>
 
 static inline unsigned long rdusp(void)
 {
@@ -59,36 +58,8 @@
 	PS_S, 0, 0						\
 }
 
-/*
- * Do necessary setup to start up a newly executed thread.
- *
- * pass the data segment into user programs if it exists,
- * it can't hurt anything as far as I can tell
- */
-#ifndef CONFIG_SMP
-#define start_thread(_regs, _pc, _usp)					\
-do {									\
-	set_fs(USER_DS);						\
-	(_regs)->pc = (_pc);						\
-	if (current->mm)						\
-		(_regs)->p5 = current->mm->start_data;			\
-	task_thread_info(current)->l1_task_info.stack_start		\
-		= (void *)current->mm->context.stack_start;		\
-	task_thread_info(current)->l1_task_info.lowest_sp = (void *)(_usp); \
-	memcpy(L1_SCRATCH_TASK_INFO, &task_thread_info(current)->l1_task_info, \
-		sizeof(*L1_SCRATCH_TASK_INFO));				\
-	wrusp(_usp);							\
-} while(0)
-#else
-#define start_thread(_regs, _pc, _usp)					\
-do {									\
-	set_fs(USER_DS);						\
-	(_regs)->pc = (_pc);						\
-	if (current->mm)						\
-		(_regs)->p5 = current->mm->start_data;			\
-	wrusp(_usp);							\
-} while (0)
-#endif
+extern void start_thread(struct pt_regs *regs, unsigned long new_ip,
+					       unsigned long new_sp);
 
 /* Forward declaration, a strange C thing */
 struct task_struct;
diff --git a/arch/blackfin/include/asm/resource.h b/arch/blackfin/include/asm/resource.h
index 091355a..04bc4db 100644
--- a/arch/blackfin/include/asm/resource.h
+++ b/arch/blackfin/include/asm/resource.h
@@ -1,6 +1 @@
-#ifndef _BFIN_RESOURCE_H
-#define _BFIN_RESOURCE_H
-
 #include <asm-generic/resource.h>
-
-#endif				/* _BFIN_RESOURCE_H */
diff --git a/arch/blackfin/include/asm/sembuf.h b/arch/blackfin/include/asm/sembuf.h
index 18deb5c..7673b83 100644
--- a/arch/blackfin/include/asm/sembuf.h
+++ b/arch/blackfin/include/asm/sembuf.h
@@ -1,25 +1 @@
-#ifndef _BFIN_SEMBUF_H
-#define _BFIN_SEMBUF_H
-
-/*
- * The semid64_ds structure for bfin architecture.
- * Note extra padding because this structure is passed back and forth
- * between kernel and user space.
- *
- * Pad space is left for:
- * - 64-bit time_t to solve y2038 problem
- * - 2 miscellaneous 32-bit values
- */
-
-struct semid64_ds {
-	struct ipc64_perm sem_perm;	/* permissions .. see ipc.h */
-	__kernel_time_t sem_otime;	/* last semop time */
-	unsigned long __unused1;
-	__kernel_time_t sem_ctime;	/* last change time */
-	unsigned long __unused2;
-	unsigned long sem_nsems;	/* no. of semaphores in array */
-	unsigned long __unused3;
-	unsigned long __unused4;
-};
-
-#endif				/* _BFIN_SEMBUF_H */
+#include <asm-generic/sembuf.h>
diff --git a/arch/blackfin/include/asm/serial.h b/arch/blackfin/include/asm/serial.h
index 3a47606..94a4a12 100644
--- a/arch/blackfin/include/asm/serial.h
+++ b/arch/blackfin/include/asm/serial.h
@@ -1,6 +1,2 @@
-/*
- * include/asm-blackfin/serial.h
- */
-
+#include <asm-generic/serial.h>
 #define SERIAL_EXTRA_IRQ_FLAGS IRQF_TRIGGER_HIGH
-#define BASE_BAUD (1843200 / 16)
diff --git a/arch/blackfin/include/asm/setup.h b/arch/blackfin/include/asm/setup.h
index 01c8c6c..552df83 100644
--- a/arch/blackfin/include/asm/setup.h
+++ b/arch/blackfin/include/asm/setup.h
@@ -1,17 +1 @@
-/*
-** asm/setup.h -- Definition of the Linux/bfin setup information
-**
-** This file is subject to the terms and conditions of the GNU General Public
-** License.  See the file COPYING in the main directory of this archive
-** for more details.
-**
-** Copyright Lineo, Inc 2001          Tony Kou
-**
-*/
-
-#ifndef _BFIN_SETUP_H
-#define _BFIN_SETUP_H
-
-#define COMMAND_LINE_SIZE	512
-
-#endif				/* _BFIN_SETUP_H */
+#include <asm-generic/setup.h>
diff --git a/arch/blackfin/include/asm/shmbuf.h b/arch/blackfin/include/asm/shmbuf.h
index 6124363..83c05fc 100644
--- a/arch/blackfin/include/asm/shmbuf.h
+++ b/arch/blackfin/include/asm/shmbuf.h
@@ -1,42 +1 @@
-#ifndef _BFIN_SHMBUF_H
-#define _BFIN_SHMBUF_H
-
-/*
- * The shmid64_ds structure for bfin architecture.
- * Note extra padding because this structure is passed back and forth
- * between kernel and user space.
- *
- * Pad space is left for:
- * - 64-bit time_t to solve y2038 problem
- * - 2 miscellaneous 32-bit values
- */
-
-struct shmid64_ds {
-	struct ipc64_perm shm_perm;	/* operation perms */
-	size_t shm_segsz;	/* size of segment (bytes) */
-	__kernel_time_t shm_atime;	/* last attach time */
-	unsigned long __unused1;
-	__kernel_time_t shm_dtime;	/* last detach time */
-	unsigned long __unused2;
-	__kernel_time_t shm_ctime;	/* last change time */
-	unsigned long __unused3;
-	__kernel_pid_t shm_cpid;	/* pid of creator */
-	__kernel_pid_t shm_lpid;	/* pid of last operator */
-	unsigned long shm_nattch;	/* no. of current attaches */
-	unsigned long __unused4;
-	unsigned long __unused5;
-};
-
-struct shminfo64 {
-	unsigned long shmmax;
-	unsigned long shmmin;
-	unsigned long shmmni;
-	unsigned long shmseg;
-	unsigned long shmall;
-	unsigned long __unused1;
-	unsigned long __unused2;
-	unsigned long __unused3;
-	unsigned long __unused4;
-};
-
-#endif				/* _BFIN_SHMBUF_H */
+#include <asm-generic/shmbuf.h>
diff --git a/arch/blackfin/include/asm/shmparam.h b/arch/blackfin/include/asm/shmparam.h
index 3c03906..93f30de 100644
--- a/arch/blackfin/include/asm/shmparam.h
+++ b/arch/blackfin/include/asm/shmparam.h
@@ -1,6 +1 @@
-#ifndef _BFIN_SHMPARAM_H
-#define _BFIN_SHMPARAM_H
-
-#define	SHMLBA PAGE_SIZE	/* attach addr a multiple of this */
-
-#endif				/* _BFIN_SHMPARAM_H */
+#include <asm-generic/shmparam.h>
diff --git a/arch/blackfin/include/asm/signal.h b/arch/blackfin/include/asm/signal.h
index 2eea907..77a3bf3 100644
--- a/arch/blackfin/include/asm/signal.h
+++ b/arch/blackfin/include/asm/signal.h
@@ -1,160 +1,7 @@
 #ifndef _BLACKFIN_SIGNAL_H
 #define _BLACKFIN_SIGNAL_H
 
-#include <linux/types.h>
+#define SA_RESTORER 0x04000000
+#include <asm-generic/signal.h>
 
-/* Avoid too many header ordering problems.  */
-struct siginfo;
-
-#ifdef __KERNEL__
-/* Most things should be clean enough to redefine this at will, if care
-   is taken to make libc match.  */
-
-#define _NSIG		64
-#define _NSIG_BPW	32
-#define _NSIG_WORDS	(_NSIG / _NSIG_BPW)
-
-typedef unsigned long old_sigset_t;	/* at least 32 bits */
-
-typedef struct {
-	unsigned long sig[_NSIG_WORDS];
-} sigset_t;
-
-#else
-/* Here we must cater to libcs that poke about in kernel headers.  */
-
-#define NSIG		32
-typedef unsigned long sigset_t;
-
-#endif				/* __KERNEL__ */
-
-#define SIGHUP		 1
-#define SIGINT		 2
-#define SIGQUIT		 3
-#define SIGILL		 4
-#define SIGTRAP		 5
-#define SIGABRT		 6
-#define SIGIOT		 6
-#define SIGBUS		 7
-#define SIGFPE		 8
-#define SIGKILL		 9
-#define SIGUSR1		10
-#define SIGSEGV		11
-#define SIGUSR2		12
-#define SIGPIPE		13
-#define SIGALRM		14
-#define SIGTERM		15
-#define SIGSTKFLT	16
-#define SIGCHLD		17
-#define SIGCONT		18
-#define SIGSTOP		19
-#define SIGTSTP		20
-#define SIGTTIN		21
-#define SIGTTOU		22
-#define SIGURG		23
-#define SIGXCPU		24
-#define SIGXFSZ		25
-#define SIGVTALRM	26
-#define SIGPROF		27
-#define SIGWINCH	28
-#define SIGIO		29
-#define SIGPOLL		SIGIO
-/*
-#define SIGLOST		29
-*/
-#define SIGPWR		30
-#define SIGSYS		31
-#define	SIGUNUSED	31
-
-/* These should not be considered constants from userland.  */
-#define SIGRTMIN	32
-#define SIGRTMAX	_NSIG
-
-/*
- * SA_FLAGS values:
- *
- * SA_ONSTACK indicates that a registered stack_t will be used.
- * SA_INTERRUPT is a no-op, but left due to historical reasons. Use the
- * SA_RESTART flag to get restarting signals (which were the default long ago)
- * SA_NOCLDSTOP flag to turn off SIGCHLD when children stop.
- * SA_RESETHAND clears the handler when the signal is delivered.
- * SA_NOCLDWAIT flag on SIGCHLD to inhibit zombies.
- * SA_NODEFER prevents the current signal from being masked in the handler.
- *
- * SA_ONESHOT and SA_NOMASK are the historical Linux names for the Single
- * Unix names RESETHAND and NODEFER respectively.
- */
-#define SA_NOCLDSTOP	0x00000001
-#define SA_NOCLDWAIT	0x00000002	/* not supported yet */
-#define SA_SIGINFO	0x00000004
-#define SA_ONSTACK	0x08000000
-#define SA_RESTART	0x10000000
-#define SA_NODEFER	0x40000000
-#define SA_RESETHAND	0x80000000
-
-#define SA_NOMASK	SA_NODEFER
-#define SA_ONESHOT	SA_RESETHAND
-
-/*
- * sigaltstack controls
- */
-#define SS_ONSTACK	1
-#define SS_DISABLE	2
-
-#define MINSIGSTKSZ	2048
-#define SIGSTKSZ	8192
-
-#include <asm-generic/signal-defs.h>
-
-#ifdef __KERNEL__
-struct old_sigaction {
-	__sighandler_t sa_handler;
-	old_sigset_t sa_mask;
-	unsigned long sa_flags;
-	void (*sa_restorer) (void);
-};
-
-struct sigaction {
-	__sighandler_t sa_handler;
-	unsigned long sa_flags;
-	void (*sa_restorer) (void);
-	sigset_t sa_mask;	/* mask last for extensibility */
-};
-
-struct k_sigaction {
-	struct sigaction sa;
-};
-#else
-/* Here we must cater to libcs that poke about in kernel headers.  */
-
-struct sigaction {
-	union {
-		__sighandler_t _sa_handler;
-		void (*_sa_sigaction) (int, struct siginfo *, void *);
-	} _u;
-	sigset_t sa_mask;
-	unsigned long sa_flags;
-	void (*sa_restorer) (void);
-};
-
-#define sa_handler	_u._sa_handler
-#define sa_sigaction	_u._sa_sigaction
-
-#endif				/* __KERNEL__ */
-
-typedef struct sigaltstack {
-	void __user *ss_sp;
-	int ss_flags;
-	size_t ss_size;
-} stack_t;
-
-#ifdef __KERNEL__
-
-#include <asm/sigcontext.h>
-#undef __HAVE_ARCH_SIG_BITOPS
-
-#define ptrace_signal_deliver(regs, cookie) do { } while (0)
-
-#endif				/* __KERNEL__ */
-
-#endif				/* _BLACKFIN_SIGNAL_H */
+#endif
diff --git a/arch/blackfin/include/asm/socket.h b/arch/blackfin/include/asm/socket.h
index fac7fe9..6b71384 100644
--- a/arch/blackfin/include/asm/socket.h
+++ b/arch/blackfin/include/asm/socket.h
@@ -1,59 +1 @@
-#ifndef _ASM_SOCKET_H
-#define _ASM_SOCKET_H
-
-#include <asm/sockios.h>
-
-/* For setsockoptions(2) */
-#define SOL_SOCKET	1
-
-#define SO_DEBUG	1
-#define SO_REUSEADDR	2
-#define SO_TYPE		3
-#define SO_ERROR	4
-#define SO_DONTROUTE	5
-#define SO_BROADCAST	6
-#define SO_SNDBUF	7
-#define SO_RCVBUF	8
-#define SO_SNDBUFFORCE	32
-#define SO_RCVBUFFORCE	33
-#define SO_KEEPALIVE	9
-#define SO_OOBINLINE	10
-#define SO_NO_CHECK	11
-#define SO_PRIORITY	12
-#define SO_LINGER	13
-#define SO_BSDCOMPAT	14
-/* To add :#define SO_REUSEPORT 15 */
-#define SO_PASSCRED	16
-#define SO_PEERCRED	17
-#define SO_RCVLOWAT	18
-#define SO_SNDLOWAT	19
-#define SO_RCVTIMEO	20
-#define SO_SNDTIMEO	21
-
-/* Security levels - as per NRL IPv6 - don't actually do anything */
-#define SO_SECURITY_AUTHENTICATION		22
-#define SO_SECURITY_ENCRYPTION_TRANSPORT	23
-#define SO_SECURITY_ENCRYPTION_NETWORK		24
-
-#define SO_BINDTODEVICE	25
-
-/* Socket filtering */
-#define SO_ATTACH_FILTER	26
-#define SO_DETACH_FILTER	27
-
-#define SO_PEERNAME		28
-#define SO_TIMESTAMP		29
-#define SCM_TIMESTAMP		SO_TIMESTAMP
-
-#define SO_ACCEPTCONN		30
-#define SO_PEERSEC		31
-#define SO_PASSSEC		34
-#define SO_TIMESTAMPNS		35
-#define SCM_TIMESTAMPNS		SO_TIMESTAMPNS
-
-#define SO_MARK			36
-
-#define SO_TIMESTAMPING		37
-#define SCM_TIMESTAMPING	SO_TIMESTAMPING
-
-#endif				/* _ASM_SOCKET_H */
+#include <asm-generic/socket.h>
diff --git a/arch/blackfin/include/asm/sockios.h b/arch/blackfin/include/asm/sockios.h
index 426b89b..def6d47 100644
--- a/arch/blackfin/include/asm/sockios.h
+++ b/arch/blackfin/include/asm/sockios.h
@@ -1,13 +1 @@
-#ifndef __ARCH_BFIN_SOCKIOS__
-#define __ARCH_BFIN_SOCKIOS__
-
-/* Socket-level I/O control calls. */
-#define FIOSETOWN 	0x8901
-#define SIOCSPGRP	0x8902
-#define FIOGETOWN	0x8903
-#define SIOCGPGRP	0x8904
-#define SIOCATMARK	0x8905
-#define SIOCGSTAMP	0x8906	/* Get stamp (timeval) */
-#define SIOCGSTAMPNS	0x8907	/* Get stamp (timespec) */
-
-#endif				/* __ARCH_BFIN_SOCKIOS__ */
+#include <asm-generic/sockios.h>
diff --git a/arch/blackfin/include/asm/spinlock.h b/arch/blackfin/include/asm/spinlock.h
index 0249ac3..d6ff4b5 100644
--- a/arch/blackfin/include/asm/spinlock.h
+++ b/arch/blackfin/include/asm/spinlock.h
@@ -1,6 +1,10 @@
 #ifndef __BFIN_SPINLOCK_H
 #define __BFIN_SPINLOCK_H
 
+#ifndef CONFIG_SMP
+# include <asm-generic/spinlock.h>
+#else
+
 #include <asm/atomic.h>
 
 asmlinkage int __raw_spin_is_locked_asm(volatile int *ptr);
@@ -86,4 +90,6 @@
 #define _raw_read_relax(lock)	cpu_relax()
 #define _raw_write_relax(lock)	cpu_relax()
 
+#endif
+
 #endif /*  !__BFIN_SPINLOCK_H */
diff --git a/arch/blackfin/include/asm/statfs.h b/arch/blackfin/include/asm/statfs.h
index 3506720..0b91fe1 100644
--- a/arch/blackfin/include/asm/statfs.h
+++ b/arch/blackfin/include/asm/statfs.h
@@ -1,6 +1 @@
-#ifndef _BFIN_STATFS_H
-#define _BFIN_STATFS_H
-
 #include <asm-generic/statfs.h>
-
-#endif				/* _BFIN_STATFS_H */
diff --git a/arch/blackfin/include/asm/swab.h b/arch/blackfin/include/asm/swab.h
index 6403ad2..d442113 100644
--- a/arch/blackfin/include/asm/swab.h
+++ b/arch/blackfin/include/asm/swab.h
@@ -2,11 +2,7 @@
 #define _BLACKFIN_SWAB_H
 
 #include <linux/types.h>
-#include <linux/compiler.h>
-
-#if defined(__GNUC__) && !defined(__STRICT_ANSI__) || defined(__KERNEL__)
-#  define __SWAB_64_THRU_32__
-#endif
+#include <asm-generic/swab.h>
 
 #ifdef __GNUC__
 
diff --git a/arch/blackfin/include/asm/termbits.h b/arch/blackfin/include/asm/termbits.h
index f37feb7..3935b10 100644
--- a/arch/blackfin/include/asm/termbits.h
+++ b/arch/blackfin/include/asm/termbits.h
@@ -1,198 +1 @@
-#ifndef __ARCH_BFIN_TERMBITS_H__
-#define __ARCH_BFIN_TERMBITS_H__
-
-#include <linux/posix_types.h>
-
-typedef unsigned char cc_t;
-typedef unsigned int speed_t;
-typedef unsigned int tcflag_t;
-
-#define NCCS 19
-struct termios {
-	tcflag_t c_iflag;	/* input mode flags */
-	tcflag_t c_oflag;	/* output mode flags */
-	tcflag_t c_cflag;	/* control mode flags */
-	tcflag_t c_lflag;	/* local mode flags */
-	cc_t c_line;		/* line discipline */
-	cc_t c_cc[NCCS];	/* control characters */
-};
-
-struct termios2 {
-	tcflag_t c_iflag;               /* input mode flags */
-	tcflag_t c_oflag;               /* output mode flags */
-	tcflag_t c_cflag;               /* control mode flags */
-	tcflag_t c_lflag;               /* local mode flags */
-	cc_t c_line;                    /* line discipline */
-	cc_t c_cc[NCCS];                /* control characters */
-	speed_t c_ispeed;               /* input speed */
-	speed_t c_ospeed;               /* output speed */
-};
-
-struct ktermios {
-	tcflag_t c_iflag;               /* input mode flags */
-	tcflag_t c_oflag;               /* output mode flags */
-	tcflag_t c_cflag;               /* control mode flags */
-	tcflag_t c_lflag;               /* local mode flags */
-	cc_t c_line;                    /* line discipline */
-	cc_t c_cc[NCCS];                /* control characters */
-	speed_t c_ispeed;               /* input speed */
-	speed_t c_ospeed;               /* output speed */
-};
-
-/* c_cc characters */
-#define VINTR 0
-#define VQUIT 1
-#define VERASE 2
-#define VKILL 3
-#define VEOF 4
-#define VTIME 5
-#define VMIN 6
-#define VSWTC 7
-#define VSTART 8
-#define VSTOP 9
-#define VSUSP 10
-#define VEOL 11
-#define VREPRINT 12
-#define VDISCARD 13
-#define VWERASE 14
-#define VLNEXT 15
-#define VEOL2 16
-
-/* c_iflag bits */
-#define IGNBRK	0000001
-#define BRKINT	0000002
-#define IGNPAR	0000004
-#define PARMRK	0000010
-#define INPCK	0000020
-#define ISTRIP	0000040
-#define INLCR	0000100
-#define IGNCR	0000200
-#define ICRNL	0000400
-#define IUCLC	0001000
-#define IXON	0002000
-#define IXANY	0004000
-#define IXOFF	0010000
-#define IMAXBEL	0020000
-#define IUTF8	0040000
-
-/* c_oflag bits */
-#define OPOST	0000001
-#define OLCUC	0000002
-#define ONLCR	0000004
-#define OCRNL	0000010
-#define ONOCR	0000020
-#define ONLRET	0000040
-#define OFILL	0000100
-#define OFDEL	0000200
-#define NLDLY	0000400
-#define   NL0	0000000
-#define   NL1	0000400
-#define CRDLY	0003000
-#define   CR0	0000000
-#define   CR1	0001000
-#define   CR2	0002000
-#define   CR3	0003000
-#define TABDLY	0014000
-#define   TAB0	0000000
-#define   TAB1	0004000
-#define   TAB2	0010000
-#define   TAB3	0014000
-#define   XTABS	0014000
-#define BSDLY	0020000
-#define   BS0	0000000
-#define   BS1	0020000
-#define VTDLY	0040000
-#define   VT0	0000000
-#define   VT1	0040000
-#define FFDLY	0100000
-#define   FF0	0000000
-#define   FF1	0100000
-
-/* c_cflag bit meaning */
-#define CBAUD	0010017
-#define  B0	0000000		/* hang up */
-#define  B50	0000001
-#define  B75	0000002
-#define  B110	0000003
-#define  B134	0000004
-#define  B150	0000005
-#define  B200	0000006
-#define  B300	0000007
-#define  B600	0000010
-#define  B1200	0000011
-#define  B1800	0000012
-#define  B2400	0000013
-#define  B4800	0000014
-#define  B9600	0000015
-#define  B19200	0000016
-#define  B38400	0000017
-#define EXTA B19200
-#define EXTB B38400
-#define CSIZE	0000060
-#define   CS5	0000000
-#define   CS6	0000020
-#define   CS7	0000040
-#define   CS8	0000060
-#define CSTOPB	0000100
-#define CREAD	0000200
-#define PARENB	0000400
-#define PARODD	0001000
-#define HUPCL	0002000
-#define CLOCAL	0004000
-#define CBAUDEX 0010000
-#define BOTHER	0010000
-#define    B57600 0010001
-#define   B115200 0010002
-#define   B230400 0010003
-#define   B460800 0010004
-#define   B500000 0010005
-#define   B576000 0010006
-#define   B921600 0010007
-#define  B1000000 0010010
-#define  B1152000 0010011
-#define  B1500000 0010012
-#define  B2000000 0010013
-#define  B2500000 0010014
-#define  B3000000 0010015
-#define  B3500000 0010016
-#define  B4000000 0010017
-#define CIBAUD	  002003600000	/* input baud rate */
-#define CMSPAR	  010000000000	/* mark or space (stick) parity */
-#define CRTSCTS	  020000000000	/* flow control */
-
-#define IBSHIFT	16	/* Shift from CBAUD to CIBAUD */
-
-/* c_lflag bits */
-#define ISIG	0000001
-#define ICANON	0000002
-#define XCASE	0000004
-#define ECHO	0000010
-#define ECHOE	0000020
-#define ECHOK	0000040
-#define ECHONL	0000100
-#define NOFLSH	0000200
-#define TOSTOP	0000400
-#define ECHOCTL	0001000
-#define ECHOPRT	0002000
-#define ECHOKE	0004000
-#define FLUSHO	0010000
-#define PENDIN	0040000
-#define IEXTEN	0100000
-
-/* tcflow() and TCXONC use these */
-#define	TCOOFF		0
-#define	TCOON		1
-#define	TCIOFF		2
-#define	TCION		3
-
-/* tcflush() and TCFLSH use these */
-#define	TCIFLUSH	0
-#define	TCOFLUSH	1
-#define	TCIOFLUSH	2
-
-/* tcsetattr uses these */
-#define	TCSANOW		0
-#define	TCSADRAIN	1
-#define	TCSAFLUSH	2
-
-#endif				/* __ARCH_BFIN_TERMBITS_H__ */
+#include <asm-generic/termbits.h>
diff --git a/arch/blackfin/include/asm/termios.h b/arch/blackfin/include/asm/termios.h
index d50d063..280d78a 100644
--- a/arch/blackfin/include/asm/termios.h
+++ b/arch/blackfin/include/asm/termios.h
@@ -1,94 +1 @@
-#ifndef __BFIN_TERMIOS_H__
-#define __BFIN_TERMIOS_H__
-
-#include <asm/termbits.h>
-#include <asm/ioctls.h>
-
-struct winsize {
-	unsigned short ws_row;
-	unsigned short ws_col;
-	unsigned short ws_xpixel;
-	unsigned short ws_ypixel;
-};
-
-#define NCC 8
-struct termio {
-	unsigned short c_iflag;	/* input mode flags */
-	unsigned short c_oflag;	/* output mode flags */
-	unsigned short c_cflag;	/* control mode flags */
-	unsigned short c_lflag;	/* local mode flags */
-	unsigned char c_line;	/* line discipline */
-	unsigned char c_cc[NCC];	/* control characters */
-};
-
-/* modem lines */
-#define TIOCM_LE	0x001
-#define TIOCM_DTR	0x002
-#define TIOCM_RTS	0x004
-#define TIOCM_ST	0x008
-#define TIOCM_SR	0x010
-#define TIOCM_CTS	0x020
-#define TIOCM_CAR	0x040
-#define TIOCM_RNG	0x080
-#define TIOCM_DSR	0x100
-#define TIOCM_CD	TIOCM_CAR
-#define TIOCM_RI	TIOCM_RNG
-#define TIOCM_OUT1	0x2000
-#define TIOCM_OUT2	0x4000
-#define TIOCM_LOOP	0x8000
-
-/* ioctl (fd, TIOCSERGETLSR, &result) where result may be as below */
-
-#ifdef __KERNEL__
-
-/*	intr=^C		quit=^\		erase=del	kill=^U
-	eof=^D		vtime=\0	vmin=\1		sxtc=\0
-	start=^Q	stop=^S		susp=^Z		eol=\0
-	reprint=^R	discard=^U	werase=^W	lnext=^V
-	eol2=\0
-*/
-#define INIT_C_CC "\003\034\177\025\004\0\1\0\021\023\032\0\022\017\027\026\0"
-
-/*
- * Translate a "termio" structure into a "termios". Ugh.
- */
-#define SET_LOW_TERMIOS_BITS(termios, termio, x) { \
-	unsigned short __tmp; \
-	get_user(__tmp,&(termio)->x); \
-	*(unsigned short *) &(termios)->x = __tmp; \
-}
-
-#define user_termio_to_kernel_termios(termios, termio) \
-({ \
-	SET_LOW_TERMIOS_BITS(termios, termio, c_iflag); \
-	SET_LOW_TERMIOS_BITS(termios, termio, c_oflag); \
-	SET_LOW_TERMIOS_BITS(termios, termio, c_cflag); \
-	SET_LOW_TERMIOS_BITS(termios, termio, c_lflag); \
-	copy_from_user((termios)->c_cc, (termio)->c_cc, NCC); \
-})
-
-/*
- * Translate a "termios" structure into a "termio". Ugh.
- */
-#define kernel_termios_to_user_termio(termio, termios) \
-({ \
-	put_user((termios)->c_iflag, &(termio)->c_iflag); \
-	put_user((termios)->c_oflag, &(termio)->c_oflag); \
-	put_user((termios)->c_cflag, &(termio)->c_cflag); \
-	put_user((termios)->c_lflag, &(termio)->c_lflag); \
-	put_user((termios)->c_line,  &(termio)->c_line); \
-	copy_to_user((termio)->c_cc, (termios)->c_cc, NCC); \
-})
-
-#define user_termios_to_kernel_termios(k, u) \
-	copy_from_user(k, u, sizeof(struct termios2))
-#define kernel_termios_to_user_termios(u, k) \
-	copy_to_user(u, k, sizeof(struct termios2))
-#define user_termios_to_kernel_termios_1(k, u) \
-	copy_from_user(k, u, sizeof(struct termios))
-#define kernel_termios_to_user_termios_1(u, k) \
-	copy_to_user(u, k, sizeof(struct termios))
-
-#endif				/* __KERNEL__ */
-
-#endif				/* __BFIN_TERMIOS_H__ */
+#include <asm-generic/termios.h>
diff --git a/arch/blackfin/include/asm/tlbflush.h b/arch/blackfin/include/asm/tlbflush.h
index 277b400..f1a06c0 100644
--- a/arch/blackfin/include/asm/tlbflush.h
+++ b/arch/blackfin/include/asm/tlbflush.h
@@ -1,56 +1 @@
-#ifndef _BLACKFIN_TLBFLUSH_H
-#define _BLACKFIN_TLBFLUSH_H
-
-/*
- * Copyright (C) 2000 Lineo, David McCullough <davidm@uclinux.org>
- * Copyright (C) 2000-2002, Greg Ungerer <gerg@snapgear.com>
- */
-
-#include <asm/setup.h>
-
-/*
- * flush all user-space atc entries.
- */
-static inline void __flush_tlb(void)
-{
-	BUG();
-}
-
-static inline void __flush_tlb_one(unsigned long addr)
-{
-	BUG();
-}
-
-#define flush_tlb() __flush_tlb()
-
-/*
- * flush all atc entries (both kernel and user-space entries).
- */
-static inline void flush_tlb_all(void)
-{
-	BUG();
-}
-
-static inline void flush_tlb_mm(struct mm_struct *mm)
-{
-	BUG();
-}
-
-static inline void flush_tlb_page(struct vm_area_struct *vma,
-				  unsigned long addr)
-{
-	BUG();
-}
-
-static inline void flush_tlb_range(struct mm_struct *mm,
-				   unsigned long start, unsigned long end)
-{
-	BUG();
-}
-
-static inline void flush_tlb_kernel_page(unsigned long addr)
-{
-	BUG();
-}
-
-#endif
+#include <asm-generic/tlbflush.h>
diff --git a/arch/blackfin/include/asm/topology.h b/arch/blackfin/include/asm/topology.h
index acee239..5428f33 100644
--- a/arch/blackfin/include/asm/topology.h
+++ b/arch/blackfin/include/asm/topology.h
@@ -1,6 +1 @@
-#ifndef _ASM_BLACKFIN_TOPOLOGY_H
-#define _ASM_BLACKFIN_TOPOLOGY_H
-
 #include <asm-generic/topology.h>
-
-#endif				/* _ASM_BLACKFIN_TOPOLOGY_H */
diff --git a/arch/blackfin/include/asm/types.h b/arch/blackfin/include/asm/types.h
index 8441cbc..b9e79bc 100644
--- a/arch/blackfin/include/asm/types.h
+++ b/arch/blackfin/include/asm/types.h
@@ -1,36 +1 @@
-#ifndef _BFIN_TYPES_H
-#define _BFIN_TYPES_H
-
-/*
- * This file is never included by application software unless
- * explicitly requested (e.g., via linux/types.h) in which case the
- * application is Linux specific so (user-) name space pollution is
- * not a major issue.  However, for interoperability, libraries still
- * need to be careful to avoid a name clashes.
- */
-#include <asm-generic/int-ll64.h>
-
-#ifndef __ASSEMBLY__
-
-typedef unsigned short umode_t;
-
-#endif				/* __ASSEMBLY__ */
-/*
- * These aren't exported outside the kernel to avoid name space clashes
- */
-#ifdef __KERNEL__
-
-#define BITS_PER_LONG 32
-
-#ifndef __ASSEMBLY__
-
-/* Dma addresses are 32-bits wide.  */
-
-typedef u32 dma_addr_t;
-typedef u64 dma64_addr_t;
-
-#endif				/* __ASSEMBLY__ */
-
-#endif				/* __KERNEL__ */
-
-#endif				/* _BFIN_TYPES_H */
+#include <asm-generic/types.h>
diff --git a/arch/blackfin/include/asm/ucontext.h b/arch/blackfin/include/asm/ucontext.h
index 4a4e385..9bc07b9 100644
--- a/arch/blackfin/include/asm/ucontext.h
+++ b/arch/blackfin/include/asm/ucontext.h
@@ -1,17 +1 @@
-/** Changes made by Tony Kou   Lineo Inc.    May 2001
- *
- *  Based on: include/m68knommu/ucontext.h
- */
-
-#ifndef _BLACKFIN_UCONTEXT_H
-#define _BLACKFIN_UCONTEXT_H
-
-struct ucontext {
-	unsigned long uc_flags;	/* the others are necessary */
-	struct ucontext *uc_link;
-	stack_t uc_stack;
-	struct sigcontext uc_mcontext;
-	sigset_t uc_sigmask;	/* mask last for extensibility */
-};
-
-#endif				/* _BLACKFIN_UCONTEXT_H */
+#include <asm-generic/ucontext.h>
diff --git a/arch/blackfin/include/asm/unaligned.h b/arch/blackfin/include/asm/unaligned.h
index fd8a1d6..6cecbbb 100644
--- a/arch/blackfin/include/asm/unaligned.h
+++ b/arch/blackfin/include/asm/unaligned.h
@@ -1,11 +1 @@
-#ifndef _ASM_BLACKFIN_UNALIGNED_H
-#define _ASM_BLACKFIN_UNALIGNED_H
-
-#include <linux/unaligned/le_struct.h>
-#include <linux/unaligned/be_byteshift.h>
-#include <linux/unaligned/generic.h>
-
-#define get_unaligned	__get_unaligned_le
-#define put_unaligned	__put_unaligned_le
-
-#endif /* _ASM_BLACKFIN_UNALIGNED_H */
+#include <asm-generic/unaligned.h>
diff --git a/arch/blackfin/include/asm/user.h b/arch/blackfin/include/asm/user.h
index afe6a0e..4792a60 100644
--- a/arch/blackfin/include/asm/user.h
+++ b/arch/blackfin/include/asm/user.h
@@ -1,89 +1 @@
-#ifndef _BFIN_USER_H
-#define _BFIN_USER_H
-
-/* Changes by Tony Kou   Lineo, Inc.  July, 2001
- *
- * Based include/asm-m68knommu/user.h
- *
- */
-
-/* Core file format: The core file is written in such a way that gdb
-   can understand it and provide useful information to the user (under
-   linux we use the 'trad-core' bfd).  There are quite a number of
-   obstacles to being able to view the contents of the floating point
-   registers, and until these are solved you will not be able to view the
-   contents of them.  Actually, you can read in the core file and look at
-   the contents of the user struct to find out what the floating point
-   registers contain.
-   The actual file contents are as follows:
-   UPAGE: 1 page consisting of a user struct that tells gdb what is present
-   in the file.  Directly after this is a copy of the task_struct, which
-   is currently not used by gdb, but it may come in useful at some point.
-   All of the registers are stored as part of the upage.  The upage should
-   always be only one page.
-   DATA: The data area is stored.  We use current->end_text to
-   current->brk to pick up all of the user variables, plus any memory
-   that may have been malloced.  No attempt is made to determine if a page
-   is demand-zero or if a page is totally unused, we just cover the entire
-   range.  All of the addresses are rounded in such a way that an integral
-   number of pages is written.
-   STACK: We need the stack information in order to get a meaningful
-   backtrace.  We need to write the data from (esp) to
-   current->start_stack, so we round each of these off in order to be able
-   to write an integer number of pages.
-   The minimum core file size is 3 pages, or 12288 bytes.
-*/
-struct user_bfinfp_struct {
-};
-
-/* This is the old layout of "struct pt_regs" as of Linux 1.x, and
-   is still the layout used by user (the new pt_regs doesn't have
-   all registers). */
-struct user_regs_struct {
-	long r0, r1, r2, r3, r4, r5, r6, r7;
-	long p0, p1, p2, p3, p4, p5, usp, fp;
-	long i0, i1, i2, i3;
-	long l0, l1, l2, l3;
-	long b0, b1, b2, b3;
-	long m0, m1, m2, m3;
-	long a0w, a1w;
-	long a0x, a1x;
-	unsigned long rets;
-	unsigned long astat;
-	unsigned long pc;
-	unsigned long orig_p0;
-};
-
-/* When the kernel dumps core, it starts by dumping the user struct -
-   this will be used by gdb to figure out where the data and stack segments
-   are within the file, and what virtual addresses to use. */
-
-struct user {
-/* We start with the registers, to mimic the way that "memory" is returned
-   from the ptrace(3,...) function.  */
-
-	struct user_regs_struct regs;	/* Where the registers are actually stored */
-
-/* The rest of this junk is to help gdb figure out what goes where */
-	unsigned long int u_tsize;	/* Text segment size (pages). */
-	unsigned long int u_dsize;	/* Data segment size (pages). */
-	unsigned long int u_ssize;	/* Stack segment size (pages). */
-	unsigned long start_code;	/* Starting virtual address of text. */
-	unsigned long start_stack;	/* Starting virtual address of stack area.
-					   This is actually the bottom of the stack,
-					   the top of the stack is always found in the
-					   esp register.  */
-	long int signal;	/* Signal that caused the core dump. */
-	int reserved;		/* No longer used */
-	unsigned long u_ar0;
-	/* Used by gdb to help find the values for */
-	/* the registers. */
-	unsigned long magic;	/* To uniquely identify a core file */
-	char u_comm[32];	/* User command that was responsible */
-};
-#define NBPG PAGE_SIZE
-#define UPAGES 1
-#define HOST_TEXT_START_ADDR (u.start_code)
-#define HOST_STACK_END_ADDR (u.start_stack + u.u_ssize * NBPG)
-
-#endif
+#include <asm-generic/user.h>
diff --git a/arch/blackfin/kernel/bfin_ksyms.c b/arch/blackfin/kernel/bfin_ksyms.c
index aa05e63..ed8392c 100644
--- a/arch/blackfin/kernel/bfin_ksyms.c
+++ b/arch/blackfin/kernel/bfin_ksyms.c
@@ -10,6 +10,7 @@
 #include <linux/uaccess.h>
 
 #include <asm/cacheflush.h>
+#include <asm/io.h>
 
 /* Allow people to have their own Blackfin exception handler in a module */
 EXPORT_SYMBOL(bfin_return_from_exception);
diff --git a/arch/blackfin/kernel/process.c b/arch/blackfin/kernel/process.c
index 30d0843..3e1d86e 100644
--- a/arch/blackfin/kernel/process.c
+++ b/arch/blackfin/kernel/process.c
@@ -160,6 +160,29 @@
 }
 EXPORT_SYMBOL(kernel_thread);
 
+/*
+ * Do necessary setup to start up a newly executed thread.
+ *
+ * pass the data segment into user programs if it exists,
+ * it can't hurt anything as far as I can tell
+ */
+void start_thread(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp)
+{
+	set_fs(USER_DS);
+	regs->pc = new_ip;
+	if (current->mm)
+		regs->p5 = current->mm->start_data;
+#ifdef CONFIG_SMP
+	task_thread_info(current)->l1_task_info.stack_start =
+		(void *)current->mm->context.stack_start;
+	task_thread_info(current)->l1_task_info.lowest_sp = (void *)new_sp;
+	memcpy(L1_SCRATCH_TASK_INFO, &task_thread_info(current)->l1_task_info,
+	       sizeof(*L1_SCRATCH_TASK_INFO));
+#endif
+	wrusp(new_sp);
+}
+EXPORT_SYMBOL_GPL(start_thread);
+
 void flush_thread(void)
 {
 }
diff --git a/arch/blackfin/mach-common/Makefile b/arch/blackfin/mach-common/Makefile
index 1f3228e..dd8b2dc 100644
--- a/arch/blackfin/mach-common/Makefile
+++ b/arch/blackfin/mach-common/Makefile
@@ -4,7 +4,7 @@
 
 obj-y := \
 	cache.o cache-c.o entry.o head.o \
-	interrupt.o irqpanic.o arch_checks.o ints-priority.o
+	interrupt.o arch_checks.o ints-priority.o
 
 obj-$(CONFIG_BFIN_ICACHE_LOCK) += lock.o
 obj-$(CONFIG_PM)          += pm.o dpmc_modes.o
@@ -12,3 +12,4 @@
 obj-$(CONFIG_CPU_VOLTAGE) += dpmc.o
 obj-$(CONFIG_SMP)         += smp.o
 obj-$(CONFIG_BFIN_KERNEL_CLOCK) += clocks-init.o
+obj-$(CONFIG_DEBUG_ICACHE_CHECK) += irqpanic.o
diff --git a/arch/blackfin/mach-common/ints-priority.c b/arch/blackfin/mach-common/ints-priority.c
index 351afd0..af70f09 100644
--- a/arch/blackfin/mach-common/ints-priority.c
+++ b/arch/blackfin/mach-common/ints-priority.c
@@ -472,7 +472,7 @@
 
 	if (type == IRQ_TYPE_PROBE) {
 		/* only probe unenabled GPIO interrupt lines */
-		if (__test_bit(gpionr, gpio_enabled))
+		if (test_bit(gpionr, gpio_enabled))
 			return 0;
 		type = IRQ_TYPE_EDGE_RISING | IRQ_TYPE_EDGE_FALLING;
 	}
@@ -782,7 +782,7 @@
 
 	if (type == IRQ_TYPE_PROBE) {
 		/* only probe unenabled GPIO interrupt lines */
-		if (__test_bit(gpionr, gpio_enabled))
+		if (test_bit(gpionr, gpio_enabled))
 			return 0;
 		type = IRQ_TYPE_EDGE_RISING | IRQ_TYPE_EDGE_FALLING;
 	}
diff --git a/arch/blackfin/mach-common/irqpanic.c b/arch/blackfin/mach-common/irqpanic.c
index 05004df..883e324 100644
--- a/arch/blackfin/mach-common/irqpanic.c
+++ b/arch/blackfin/mach-common/irqpanic.c
@@ -30,21 +30,17 @@
 #include <linux/module.h>
 #include <linux/kernel_stat.h>
 #include <linux/sched.h>
-#include <asm/traps.h>
 #include <asm/blackfin.h>
 
-#ifdef CONFIG_DEBUG_ICACHE_CHECK
 #define L1_ICACHE_START 0xffa10000
 #define L1_ICACHE_END   0xffa13fff
-void irq_panic(int reason, struct pt_regs *regs) __attribute__ ((l1_text));
-#endif
 
 /*
  * irq_panic - calls panic with string setup
  */
+__attribute__ ((l1_text))
 asmlinkage void irq_panic(int reason, struct pt_regs *regs)
 {
-#ifdef CONFIG_DEBUG_ICACHE_CHECK
 	unsigned int cmd, tag, ca, cache_hi, cache_lo, *pa;
 	unsigned short i, j, die;
 	unsigned int bad[10][6];
@@ -126,9 +122,6 @@
 			     bad[j][3], bad[j][4], bad[j][5]);
 		}
 		panic("icache coherency error");
-	} else {
+	} else
 		printk(KERN_EMERG "icache checked, and OK\n");
-	}
-#endif
-
 }
diff --git a/arch/h8300/kernel/asm-offsets.c b/arch/h8300/kernel/asm-offsets.c
index 2042552..fd961e0 100644
--- a/arch/h8300/kernel/asm-offsets.c
+++ b/arch/h8300/kernel/asm-offsets.c
@@ -55,7 +55,6 @@
 	DEFINE(LRET,  offsetof(struct pt_regs, pc)       - sizeof(long));
 
 	DEFINE(PT_PTRACED, PT_PTRACED);
-	DEFINE(PT_DTRACE, PT_DTRACE);
 
 	return 0;
 }
diff --git a/arch/ia64/Kconfig b/arch/ia64/Kconfig
index 294a3b1..170042b 100644
--- a/arch/ia64/Kconfig
+++ b/arch/ia64/Kconfig
@@ -28,6 +28,7 @@
 	select HAVE_DMA_ATTRS
 	select HAVE_KVM
 	select HAVE_ARCH_TRACEHOOK
+	select HAVE_DMA_API_DEBUG
 	default y
 	help
 	  The Itanium Processor Family is Intel's 64-bit successor to
diff --git a/arch/ia64/hp/common/sba_iommu.c b/arch/ia64/hp/common/sba_iommu.c
index fe63b2dc9..8cfb001 100644
--- a/arch/ia64/hp/common/sba_iommu.c
+++ b/arch/ia64/hp/common/sba_iommu.c
@@ -1787,7 +1787,7 @@
 };
 
 static struct ioc * __init
-ioc_init(u64 hpa, void *handle)
+ioc_init(unsigned long hpa, void *handle)
 {
 	struct ioc *ioc;
 	struct ioc_iommu *info;
diff --git a/arch/ia64/hp/sim/hpsim_irq.c b/arch/ia64/hp/sim/hpsim_irq.c
index acb5047..b272261 100644
--- a/arch/ia64/hp/sim/hpsim_irq.c
+++ b/arch/ia64/hp/sim/hpsim_irq.c
@@ -27,7 +27,7 @@
 	return 0;
 }
 
-static struct hw_interrupt_type irq_type_hp_sim = {
+static struct irq_chip irq_type_hp_sim = {
 	.name =		"hpsim",
 	.startup =	hpsim_irq_startup,
 	.shutdown =	hpsim_irq_noop,
@@ -41,12 +41,12 @@
 void __init
 hpsim_irq_init (void)
 {
-	irq_desc_t *idesc;
+	struct irq_desc *idesc;
 	int i;
 
 	for (i = 0; i < NR_IRQS; ++i) {
 		idesc = irq_desc + i;
-		if (idesc->chip == &no_irq_type)
+		if (idesc->chip == &no_irq_chip)
 			idesc->chip = &irq_type_hp_sim;
 	}
 }
diff --git a/arch/ia64/include/asm/Kbuild b/arch/ia64/include/asm/Kbuild
index ccbe8ae..c7d0a71 100644
--- a/arch/ia64/include/asm/Kbuild
+++ b/arch/ia64/include/asm/Kbuild
@@ -2,7 +2,6 @@
 
 header-y += break.h
 header-y += fpu.h
-header-y += fpswa.h
 header-y += ia64regs.h
 header-y += intel_intrin.h
 header-y += perfmon_default_smpl.h
diff --git a/arch/ia64/include/asm/dma-mapping.h b/arch/ia64/include/asm/dma-mapping.h
index 36c0009..5a61b5c 100644
--- a/arch/ia64/include/asm/dma-mapping.h
+++ b/arch/ia64/include/asm/dma-mapping.h
@@ -8,6 +8,7 @@
 #include <asm/machvec.h>
 #include <linux/scatterlist.h>
 #include <asm/swiotlb.h>
+#include <linux/dma-debug.h>
 
 #define ARCH_HAS_DMA_GET_REQUIRED_MASK
 
@@ -24,95 +25,28 @@
 				       dma_addr_t *daddr, gfp_t gfp)
 {
 	struct dma_map_ops *ops = platform_dma_get_ops(dev);
-	return ops->alloc_coherent(dev, size, daddr, gfp);
+	void *caddr;
+
+	caddr = ops->alloc_coherent(dev, size, daddr, gfp);
+	debug_dma_alloc_coherent(dev, size, *daddr, caddr);
+	return caddr;
 }
 
 static inline void dma_free_coherent(struct device *dev, size_t size,
 				     void *caddr, dma_addr_t daddr)
 {
 	struct dma_map_ops *ops = platform_dma_get_ops(dev);
+	debug_dma_free_coherent(dev, size, caddr, daddr);
 	ops->free_coherent(dev, size, caddr, daddr);
 }
 
 #define dma_alloc_noncoherent(d, s, h, f) dma_alloc_coherent(d, s, h, f)
 #define dma_free_noncoherent(d, s, v, h) dma_free_coherent(d, s, v, h)
 
-static inline dma_addr_t dma_map_single_attrs(struct device *dev,
-					      void *caddr, size_t size,
-					      enum dma_data_direction dir,
-					      struct dma_attrs *attrs)
-{
-	struct dma_map_ops *ops = platform_dma_get_ops(dev);
-	return ops->map_page(dev, virt_to_page(caddr),
-			     (unsigned long)caddr & ~PAGE_MASK, size,
-			     dir, attrs);
-}
+#define get_dma_ops(dev) platform_dma_get_ops(dev)
+#define flush_write_buffers()
 
-static inline void dma_unmap_single_attrs(struct device *dev, dma_addr_t daddr,
-					  size_t size,
-					  enum dma_data_direction dir,
-					  struct dma_attrs *attrs)
-{
-	struct dma_map_ops *ops = platform_dma_get_ops(dev);
-	ops->unmap_page(dev, daddr, size, dir, attrs);
-}
-
-#define dma_map_single(d, a, s, r) dma_map_single_attrs(d, a, s, r, NULL)
-#define dma_unmap_single(d, a, s, r) dma_unmap_single_attrs(d, a, s, r, NULL)
-
-static inline int dma_map_sg_attrs(struct device *dev, struct scatterlist *sgl,
-				   int nents, enum dma_data_direction dir,
-				   struct dma_attrs *attrs)
-{
-	struct dma_map_ops *ops = platform_dma_get_ops(dev);
-	return ops->map_sg(dev, sgl, nents, dir, attrs);
-}
-
-static inline void dma_unmap_sg_attrs(struct device *dev,
-				      struct scatterlist *sgl, int nents,
-				      enum dma_data_direction dir,
-				      struct dma_attrs *attrs)
-{
-	struct dma_map_ops *ops = platform_dma_get_ops(dev);
-	ops->unmap_sg(dev, sgl, nents, dir, attrs);
-}
-
-#define dma_map_sg(d, s, n, r) dma_map_sg_attrs(d, s, n, r, NULL)
-#define dma_unmap_sg(d, s, n, r) dma_unmap_sg_attrs(d, s, n, r, NULL)
-
-static inline void dma_sync_single_for_cpu(struct device *dev, dma_addr_t daddr,
-					   size_t size,
-					   enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = platform_dma_get_ops(dev);
-	ops->sync_single_for_cpu(dev, daddr, size, dir);
-}
-
-static inline void dma_sync_sg_for_cpu(struct device *dev,
-				       struct scatterlist *sgl,
-				       int nents, enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = platform_dma_get_ops(dev);
-	ops->sync_sg_for_cpu(dev, sgl, nents, dir);
-}
-
-static inline void dma_sync_single_for_device(struct device *dev,
-					      dma_addr_t daddr,
-					      size_t size,
-					      enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = platform_dma_get_ops(dev);
-	ops->sync_single_for_device(dev, daddr, size, dir);
-}
-
-static inline void dma_sync_sg_for_device(struct device *dev,
-					  struct scatterlist *sgl,
-					  int nents,
-					  enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = platform_dma_get_ops(dev);
-	ops->sync_sg_for_device(dev, sgl, nents, dir);
-}
+#include <asm-generic/dma-mapping-common.h>
 
 static inline int dma_mapping_error(struct device *dev, dma_addr_t daddr)
 {
@@ -120,30 +54,6 @@
 	return ops->mapping_error(dev, daddr);
 }
 
-static inline dma_addr_t dma_map_page(struct device *dev, struct page *page,
-				      size_t offset, size_t size,
-				      enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = platform_dma_get_ops(dev);
-	return ops->map_page(dev, page, offset, size, dir, NULL);
-}
-
-static inline void dma_unmap_page(struct device *dev, dma_addr_t addr,
-				  size_t size, enum dma_data_direction dir)
-{
-	dma_unmap_single(dev, addr, size, dir);
-}
-
-/*
- * Rest of this file is part of the "Advanced DMA API".  Use at your own risk.
- * See Documentation/DMA-API.txt for details.
- */
-
-#define dma_sync_single_range_for_cpu(dev, dma_handle, offset, size, dir)	\
-	dma_sync_single_for_cpu(dev, dma_handle, size, dir)
-#define dma_sync_single_range_for_device(dev, dma_handle, offset, size, dir)	\
-	dma_sync_single_for_device(dev, dma_handle, size, dir)
-
 static inline int dma_supported(struct device *dev, u64 mask)
 {
 	struct dma_map_ops *ops = platform_dma_get_ops(dev);
diff --git a/arch/ia64/include/asm/gcc_intrin.h b/arch/ia64/include/asm/gcc_intrin.h
index c2c5fd8..21ddee5 100644
--- a/arch/ia64/include/asm/gcc_intrin.h
+++ b/arch/ia64/include/asm/gcc_intrin.h
@@ -388,7 +388,7 @@
 
 #define ia64_native_thash(addr)							\
 ({										\
-	__u64 ia64_intri_res;							\
+	unsigned long ia64_intri_res;						\
 	asm volatile ("thash %0=%1" : "=r"(ia64_intri_res) : "r" (addr));	\
 	ia64_intri_res;								\
 })
@@ -419,7 +419,7 @@
 
 #define ia64_tpa(addr)								\
 ({										\
-	__u64 ia64_pa;								\
+	unsigned long ia64_pa;							\
 	asm volatile ("tpa %0 = %1" : "=r"(ia64_pa) : "r"(addr) : "memory");	\
 	ia64_pa;								\
 })
@@ -444,35 +444,35 @@
 
 #define ia64_native_get_cpuid(index)							\
 ({											\
-	__u64 ia64_intri_res;								\
+	unsigned long ia64_intri_res;							\
 	asm volatile ("mov %0=cpuid[%r1]" : "=r"(ia64_intri_res) : "rO"(index));	\
 	ia64_intri_res;									\
 })
 
 #define __ia64_get_dbr(index)							\
 ({										\
-	__u64 ia64_intri_res;							\
+	unsigned long ia64_intri_res;						\
 	asm volatile ("mov %0=dbr[%1]" : "=r"(ia64_intri_res) : "r"(index));	\
 	ia64_intri_res;								\
 })
 
 #define ia64_get_ibr(index)							\
 ({										\
-	__u64 ia64_intri_res;							\
+	unsigned long ia64_intri_res;						\
 	asm volatile ("mov %0=ibr[%1]" : "=r"(ia64_intri_res) : "r"(index));	\
 	ia64_intri_res;								\
 })
 
 #define ia64_get_pkr(index)							\
 ({										\
-	__u64 ia64_intri_res;							\
+	unsigned long ia64_intri_res;						\
 	asm volatile ("mov %0=pkr[%1]" : "=r"(ia64_intri_res) : "r"(index));	\
 	ia64_intri_res;								\
 })
 
 #define ia64_get_pmc(index)							\
 ({										\
-	__u64 ia64_intri_res;							\
+	unsigned long ia64_intri_res;						\
 	asm volatile ("mov %0=pmc[%1]" : "=r"(ia64_intri_res) : "r"(index));	\
 	ia64_intri_res;								\
 })
@@ -480,14 +480,14 @@
 
 #define ia64_native_get_pmd(index)						\
 ({										\
-	__u64 ia64_intri_res;							\
+	unsigned long ia64_intri_res;						\
 	asm volatile ("mov %0=pmd[%1]" : "=r"(ia64_intri_res) : "r"(index));	\
 	ia64_intri_res;								\
 })
 
 #define ia64_native_get_rr(index)						\
 ({										\
-	__u64 ia64_intri_res;							\
+	unsigned long ia64_intri_res;						\
 	asm volatile ("mov %0=rr[%1]" : "=r"(ia64_intri_res) : "r" (index));	\
 	ia64_intri_res;								\
 })
diff --git a/arch/ia64/include/asm/hw_irq.h b/arch/ia64/include/asm/hw_irq.h
index 5c99cbc..91619b3 100644
--- a/arch/ia64/include/asm/hw_irq.h
+++ b/arch/ia64/include/asm/hw_irq.h
@@ -106,7 +106,7 @@
 #define irq_to_domain(x)	irq_cfg[(x)].domain
 DECLARE_PER_CPU(int[IA64_NUM_VECTORS], vector_irq);
 
-extern struct hw_interrupt_type irq_type_ia64_lsapic;	/* CPU-internal interrupt controller */
+extern struct irq_chip irq_type_ia64_lsapic;	/* CPU-internal interrupt controller */
 
 #ifdef CONFIG_PARAVIRT_GUEST
 #include <asm/paravirt.h>
@@ -146,7 +146,7 @@
  * Default implementations for the irq-descriptor API:
  */
 
-extern irq_desc_t irq_desc[NR_IRQS];
+extern struct irq_desc irq_desc[NR_IRQS];
 
 #ifndef CONFIG_IA64_GENERIC
 static inline ia64_vector __ia64_irq_to_vector(int irq)
diff --git a/arch/ia64/include/asm/mca.h b/arch/ia64/include/asm/mca.h
index 18a4321..44a0b53 100644
--- a/arch/ia64/include/asm/mca.h
+++ b/arch/ia64/include/asm/mca.h
@@ -72,39 +72,39 @@
 struct ia64_sal_os_state {
 
 	/* SAL to OS */
-	u64			os_gp;			/* GP of the os registered with the SAL, physical */
-	u64			pal_proc;		/* PAL_PROC entry point, physical */
-	u64			sal_proc;		/* SAL_PROC entry point, physical */
-	u64			rv_rc;			/* MCA - Rendezvous state, INIT - reason code */
-	u64			proc_state_param;	/* from R18 */
-	u64			monarch;		/* 1 for a monarch event, 0 for a slave */
+	unsigned long		os_gp;			/* GP of the os registered with the SAL, physical */
+	unsigned long		pal_proc;		/* PAL_PROC entry point, physical */
+	unsigned long		sal_proc;		/* SAL_PROC entry point, physical */
+	unsigned long		rv_rc;			/* MCA - Rendezvous state, INIT - reason code */
+	unsigned long		proc_state_param;	/* from R18 */
+	unsigned long		monarch;		/* 1 for a monarch event, 0 for a slave */
 
 	/* common */
-	u64			sal_ra;			/* Return address in SAL, physical */
-	u64			sal_gp;			/* GP of the SAL - physical */
+	unsigned long		sal_ra;			/* Return address in SAL, physical */
+	unsigned long		sal_gp;			/* GP of the SAL - physical */
 	pal_min_state_area_t	*pal_min_state;		/* from R17.  physical in asm, virtual in C */
 	/* Previous values of IA64_KR(CURRENT) and IA64_KR(CURRENT_STACK).
 	 * Note: if the MCA/INIT recovery code wants to resume to a new context
 	 * then it must change these values to reflect the new kernel stack.
 	 */
-	u64			prev_IA64_KR_CURRENT;	/* previous value of IA64_KR(CURRENT) */
-	u64			prev_IA64_KR_CURRENT_STACK;
+	unsigned long		prev_IA64_KR_CURRENT;	/* previous value of IA64_KR(CURRENT) */
+	unsigned long		prev_IA64_KR_CURRENT_STACK;
 	struct task_struct	*prev_task;		/* previous task, NULL if it is not useful */
 	/* Some interrupt registers are not saved in minstate, pt_regs or
 	 * switch_stack.  Because MCA/INIT can occur when interrupts are
 	 * disabled, we need to save the additional interrupt registers over
 	 * MCA/INIT and resume.
 	 */
-	u64			isr;
-	u64			ifa;
-	u64			itir;
-	u64			iipa;
-	u64			iim;
-	u64			iha;
+	unsigned long		isr;
+	unsigned long		ifa;
+	unsigned long		itir;
+	unsigned long		iipa;
+	unsigned long		iim;
+	unsigned long		iha;
 
 	/* OS to SAL */
-	u64			os_status;		/* OS status to SAL, enum below */
-	u64			context;		/* 0 if return to same context
+	unsigned long		os_status;		/* OS status to SAL, enum below */
+	unsigned long		context;		/* 0 if return to same context
 							   1 if return to new context */
 };
 
@@ -150,7 +150,7 @@
 extern void ia64_mca_cmc_vector_setup(void);
 extern int  ia64_reg_MCA_extension(int (*fn)(void *, struct ia64_sal_os_state *));
 extern void ia64_unreg_MCA_extension(void);
-extern u64 ia64_get_rnat(u64 *);
+extern unsigned long ia64_get_rnat(unsigned long *);
 extern void ia64_mca_printk(const char * fmt, ...)
 	 __attribute__ ((format (printf, 1, 2)));
 
diff --git a/arch/ia64/include/asm/meminit.h b/arch/ia64/include/asm/meminit.h
index c0cea37..688a812 100644
--- a/arch/ia64/include/asm/meminit.h
+++ b/arch/ia64/include/asm/meminit.h
@@ -25,8 +25,8 @@
 #define IA64_MAX_RSVD_REGIONS 9
 
 struct rsvd_region {
-	unsigned long start;	/* virtual address of beginning of element */
-	unsigned long end;	/* virtual address of end of element + 1 */
+	u64 start;	/* virtual address of beginning of element */
+	u64 end;	/* virtual address of end of element + 1 */
 };
 
 extern struct rsvd_region rsvd_region[IA64_MAX_RSVD_REGIONS + 1];
@@ -35,13 +35,13 @@
 extern void find_memory (void);
 extern void reserve_memory (void);
 extern void find_initrd (void);
-extern int filter_rsvd_memory (unsigned long start, unsigned long end, void *arg);
-extern int filter_memory (unsigned long start, unsigned long end, void *arg);
-extern unsigned long efi_memmap_init(unsigned long *s, unsigned long *e);
-extern int find_max_min_low_pfn (unsigned long , unsigned long, void *);
+extern int filter_rsvd_memory (u64 start, u64 end, void *arg);
+extern int filter_memory (u64 start, u64 end, void *arg);
+extern unsigned long efi_memmap_init(u64 *s, u64 *e);
+extern int find_max_min_low_pfn (u64, u64, void *);
 
 extern unsigned long vmcore_find_descriptor_size(unsigned long address);
-extern int reserve_elfcorehdr(unsigned long *start, unsigned long *end);
+extern int reserve_elfcorehdr(u64 *start, u64 *end);
 
 /*
  * For rounding an address to the next IA64_GRANULE_SIZE or order
@@ -63,8 +63,8 @@
 # define LARGE_GAP	0x40000000 /* Use virtual mem map if hole is > than this */
   extern unsigned long vmalloc_end;
   extern struct page *vmem_map;
-  extern int find_largest_hole (u64 start, u64 end, void *arg);
-  extern int create_mem_map_page_table (u64 start, u64 end, void *arg);
+  extern int find_largest_hole(u64 start, u64 end, void *arg);
+  extern int create_mem_map_page_table(u64 start, u64 end, void *arg);
   extern int vmemmap_find_next_valid_pfn(int, int);
 #else
 static inline int vmemmap_find_next_valid_pfn(int node, int i)
diff --git a/arch/ia64/include/asm/pal.h b/arch/ia64/include/asm/pal.h
index 67b0290..6a29250 100644
--- a/arch/ia64/include/asm/pal.h
+++ b/arch/ia64/include/asm/pal.h
@@ -989,8 +989,8 @@
 }
 
 /* Return summary information about the hierarchy of caches controlled by the processor */
-static inline s64
-ia64_pal_cache_summary (u64 *cache_levels, u64 *unique_caches)
+static inline long ia64_pal_cache_summary(unsigned long *cache_levels,
+						unsigned long *unique_caches)
 {
 	struct ia64_pal_retval iprv;
 	PAL_CALL(iprv, PAL_CACHE_SUMMARY, 0, 0, 0);
@@ -1038,8 +1038,8 @@
 }
 
 /* Return the number of instruction and data debug register pairs */
-static inline s64
-ia64_pal_debug_info (u64 *inst_regs,  u64 *data_regs)
+static inline long ia64_pal_debug_info(unsigned long *inst_regs,
+						unsigned long *data_regs)
 {
 	struct ia64_pal_retval iprv;
 	PAL_CALL(iprv, PAL_DEBUG_INFO, 0, 0, 0);
@@ -1074,8 +1074,7 @@
 }
 
 /* Get base frequency of the platform if generated by the processor */
-static inline s64
-ia64_pal_freq_base (u64 *platform_base_freq)
+static inline long ia64_pal_freq_base(unsigned long *platform_base_freq)
 {
 	struct ia64_pal_retval iprv;
 	PAL_CALL(iprv, PAL_FREQ_BASE, 0, 0, 0);
@@ -1437,7 +1436,7 @@
  * possible.
  */
 typedef struct ia64_ptce_info_s {
-	u64		base;
+	unsigned long	base;
 	u32		count[2];
 	u32		stride[2];
 } ia64_ptce_info_t;
@@ -1478,9 +1477,9 @@
 }
 
 typedef union pal_hints_u {
-	u64			ph_data;
+	unsigned long		ph_data;
 	struct {
-	       u64		si		: 1,
+	       unsigned long	si		: 1,
 				li		: 1,
 				reserved	: 62;
 	} pal_hints_s;
@@ -1489,8 +1488,8 @@
 /* Return information about the register stack and RSE for this processor
  * implementation.
  */
-static inline s64
-ia64_pal_rse_info (u64 *num_phys_stacked, pal_hints_u_t *hints)
+static inline long ia64_pal_rse_info(unsigned long *num_phys_stacked,
+							pal_hints_u_t *hints)
 {
 	struct ia64_pal_retval iprv;
 	PAL_CALL(iprv, PAL_RSE_INFO, 0, 0, 0);
@@ -1608,8 +1607,7 @@
 /* Get page size information about the virtual memory characteristics of the processor
  * implementation.
  */
-static inline s64
-ia64_pal_vm_page_size (u64 *tr_pages, u64 *vw_pages)
+static inline s64 ia64_pal_vm_page_size(u64 *tr_pages, u64 *vw_pages)
 {
 	struct ia64_pal_retval iprv;
 	PAL_CALL(iprv, PAL_VM_PAGE_SIZE, 0, 0, 0);
diff --git a/arch/ia64/include/asm/pci.h b/arch/ia64/include/asm/pci.h
index 1d660d8..fcfca56 100644
--- a/arch/ia64/include/asm/pci.h
+++ b/arch/ia64/include/asm/pci.h
@@ -135,19 +135,6 @@
 extern void pcibios_bus_to_resource(struct pci_dev *dev,
 		struct resource *res, struct pci_bus_region *region);
 
-static inline struct resource *
-pcibios_select_root(struct pci_dev *pdev, struct resource *res)
-{
-	struct resource *root = NULL;
-
-	if (res->flags & IORESOURCE_IO)
-		root = &ioport_resource;
-	if (res->flags & IORESOURCE_MEM)
-		root = &iomem_resource;
-
-	return root;
-}
-
 #define pcibios_scan_all_fns(a, b)	0
 
 #define HAVE_ARCH_PCI_GET_LEGACY_IDE_IRQ
diff --git a/arch/ia64/include/asm/processor.h b/arch/ia64/include/asm/processor.h
index f88fa05..3eaeedf1 100644
--- a/arch/ia64/include/asm/processor.h
+++ b/arch/ia64/include/asm/processor.h
@@ -187,40 +187,40 @@
  * state comes earlier:
  */
 struct cpuinfo_ia64 {
-	__u32 softirq_pending;
-	__u64 itm_delta;	/* # of clock cycles between clock ticks */
-	__u64 itm_next;		/* interval timer mask value to use for next clock tick */
-	__u64 nsec_per_cyc;	/* (1000000000<<IA64_NSEC_PER_CYC_SHIFT)/itc_freq */
-	__u64 unimpl_va_mask;	/* mask of unimplemented virtual address bits (from PAL) */
-	__u64 unimpl_pa_mask;	/* mask of unimplemented physical address bits (from PAL) */
-	__u64 itc_freq;		/* frequency of ITC counter */
-	__u64 proc_freq;	/* frequency of processor */
-	__u64 cyc_per_usec;	/* itc_freq/1000000 */
-	__u64 ptce_base;
-	__u32 ptce_count[2];
-	__u32 ptce_stride[2];
+	unsigned int softirq_pending;
+	unsigned long itm_delta;	/* # of clock cycles between clock ticks */
+	unsigned long itm_next;		/* interval timer mask value to use for next clock tick */
+	unsigned long nsec_per_cyc;	/* (1000000000<<IA64_NSEC_PER_CYC_SHIFT)/itc_freq */
+	unsigned long unimpl_va_mask;	/* mask of unimplemented virtual address bits (from PAL) */
+	unsigned long unimpl_pa_mask;	/* mask of unimplemented physical address bits (from PAL) */
+	unsigned long itc_freq;		/* frequency of ITC counter */
+	unsigned long proc_freq;	/* frequency of processor */
+	unsigned long cyc_per_usec;	/* itc_freq/1000000 */
+	unsigned long ptce_base;
+	unsigned int ptce_count[2];
+	unsigned int ptce_stride[2];
 	struct task_struct *ksoftirqd;	/* kernel softirq daemon for this CPU */
 
 #ifdef CONFIG_SMP
-	__u64 loops_per_jiffy;
+	unsigned long loops_per_jiffy;
 	int cpu;
-	__u32 socket_id;	/* physical processor socket id */
-	__u16 core_id;		/* core id */
-	__u16 thread_id;	/* thread id */
-	__u16 num_log;		/* Total number of logical processors on
+	unsigned int socket_id;	/* physical processor socket id */
+	unsigned short core_id;	/* core id */
+	unsigned short thread_id; /* thread id */
+	unsigned short num_log;	/* Total number of logical processors on
 				 * this socket that were successfully booted */
-	__u8  cores_per_socket;	/* Cores per processor socket */
-	__u8  threads_per_core;	/* Threads per core */
+	unsigned char cores_per_socket;	/* Cores per processor socket */
+	unsigned char threads_per_core;	/* Threads per core */
 #endif
 
 	/* CPUID-derived information: */
-	__u64 ppn;
-	__u64 features;
-	__u8 number;
-	__u8 revision;
-	__u8 model;
-	__u8 family;
-	__u8 archrev;
+	unsigned long ppn;
+	unsigned long features;
+	unsigned char number;
+	unsigned char revision;
+	unsigned char model;
+	unsigned char family;
+	unsigned char archrev;
 	char vendor[16];
 	char *model_name;
 
@@ -329,8 +329,8 @@
 #else
 # define INIT_THREAD_PM
 #endif
-	__u64 dbr[IA64_NUM_DBG_REGS];
-	__u64 ibr[IA64_NUM_DBG_REGS];
+	unsigned long dbr[IA64_NUM_DBG_REGS];
+	unsigned long ibr[IA64_NUM_DBG_REGS];
 	struct ia64_fpreg fph[96];	/* saved/loaded on demand */
 };
 
diff --git a/arch/ia64/include/asm/sal.h b/arch/ia64/include/asm/sal.h
index 966797a..d19ddba 100644
--- a/arch/ia64/include/asm/sal.h
+++ b/arch/ia64/include/asm/sal.h
@@ -106,10 +106,10 @@
 	 * informational value should be printed (e.g., "reboot for
 	 * change to take effect").
 	 */
-	s64 status;
-	u64 v0;
-	u64 v1;
-	u64 v2;
+	long status;
+	unsigned long v0;
+	unsigned long v1;
+	unsigned long v2;
 };
 
 typedef struct ia64_sal_retval (*ia64_sal_handler) (u64, ...);
diff --git a/arch/ia64/include/asm/sn/sn_sal.h b/arch/ia64/include/asm/sn/sn_sal.h
index e310fc0..1f5ff47 100644
--- a/arch/ia64/include/asm/sn/sn_sal.h
+++ b/arch/ia64/include/asm/sn/sn_sal.h
@@ -929,7 +929,7 @@
 /*
  * Get the associated ioboard type for a given nasid.
  */
-static inline s64
+static inline long
 ia64_sn_sysctl_ioboard_get(nasid_t nasid, u16 *ioboard)
 {
 	struct ia64_sal_retval isrv;
diff --git a/arch/ia64/include/asm/types.h b/arch/ia64/include/asm/types.h
index fbf1ed3..bcd260e 100644
--- a/arch/ia64/include/asm/types.h
+++ b/arch/ia64/include/asm/types.h
@@ -2,10 +2,11 @@
 #define _ASM_IA64_TYPES_H
 
 /*
- * This file is never included by application software unless explicitly requested (e.g.,
- * via linux/types.h) in which case the application is Linux specific so (user-) name
- * space pollution is not a major issue.  However, for interoperability, libraries still
- * need to be careful to avoid a name clashes.
+ * This file is never included by application software unless explicitly
+ * requested (e.g., via linux/types.h) in which case the application is
+ * Linux specific so (user-) name space pollution is not a major issue.
+ * However, for interoperability, libraries still need to be careful to
+ * avoid naming clashes.
  *
  * Based on <asm-alpha/types.h>.
  *
@@ -13,7 +14,11 @@
  *	David Mosberger-Tang <davidm@hpl.hp.com>, Hewlett-Packard Co
  */
 
+#ifdef __KERNEL__
+#include <asm-generic/int-ll64.h>
+#else
 #include <asm-generic/int-l64.h>
+#endif
 
 #ifdef __ASSEMBLY__
 # define __IA64_UL(x)		(x)
diff --git a/arch/ia64/include/asm/unistd.h b/arch/ia64/include/asm/unistd.h
index 10a9eb0..5a5347f 100644
--- a/arch/ia64/include/asm/unistd.h
+++ b/arch/ia64/include/asm/unistd.h
@@ -310,11 +310,12 @@
 #define __NR_inotify_init1		1318
 #define __NR_preadv			1319
 #define __NR_pwritev			1320
+#define __NR_rt_tgsigqueueinfo		1321
 
 #ifdef __KERNEL__
 
 
-#define NR_syscalls			297 /* length of syscall table */
+#define NR_syscalls			298 /* length of syscall table */
 
 /*
  * The following defines stop scripts/checksyscalls.sh from complaining about
@@ -328,6 +329,7 @@
 #define __IGNORE_utime		/* utimes() */
 #define __IGNORE_getpgrp	/* getpgid() */
 #define __IGNORE_vfork		/* clone() */
+#define __IGNORE_umount2	/* umount() */
 
 #define __ARCH_WANT_SYS_RT_SIGACTION
 #define __ARCH_WANT_SYS_RT_SIGSUSPEND
diff --git a/arch/ia64/kernel/efi.c b/arch/ia64/kernel/efi.c
index 7ef80e8..c745d0a 100644
--- a/arch/ia64/kernel/efi.c
+++ b/arch/ia64/kernel/efi.c
@@ -46,7 +46,7 @@
 struct efi efi;
 EXPORT_SYMBOL(efi);
 static efi_runtime_services_t *runtime;
-static unsigned long mem_limit = ~0UL, max_addr = ~0UL, min_addr = 0UL;
+static u64 mem_limit = ~0UL, max_addr = ~0UL, min_addr = 0UL;
 
 #define efi_call_virt(f, args...)	(*(f))(args)
 
@@ -356,7 +356,7 @@
 
 		if (++pal_code_count > 1) {
 			printk(KERN_ERR "Too many EFI Pal Code memory ranges, "
-			       "dropped @ %lx\n", md->phys_addr);
+			       "dropped @ %llx\n", md->phys_addr);
 			continue;
 		}
 		/*
@@ -490,10 +490,10 @@
 		}
 	}
 	if (min_addr != 0UL)
-		printk(KERN_INFO "Ignoring memory below %luMB\n",
+		printk(KERN_INFO "Ignoring memory below %lluMB\n",
 		       min_addr >> 20);
 	if (max_addr != ~0UL)
-		printk(KERN_INFO "Ignoring memory above %luMB\n",
+		printk(KERN_INFO "Ignoring memory above %lluMB\n",
 		       max_addr >> 20);
 
 	efi.systab = __va(ia64_boot_param->efi_systab);
@@ -1066,7 +1066,7 @@
  * parts exist, and are WB.
  */
 unsigned long
-efi_memmap_init(unsigned long *s, unsigned long *e)
+efi_memmap_init(u64 *s, u64 *e)
 {
 	struct kern_memdesc *k, *prev = NULL;
 	u64	contig_low=0, contig_high=0;
diff --git a/arch/ia64/kernel/entry.S b/arch/ia64/kernel/entry.S
index 7bebac0..d0e7d37 100644
--- a/arch/ia64/kernel/entry.S
+++ b/arch/ia64/kernel/entry.S
@@ -1805,6 +1805,7 @@
 	data8 sys_inotify_init1
 	data8 sys_preadv
 	data8 sys_pwritev			// 1320
+	data8 sys_rt_tgsigqueueinfo
 
 	.org sys_call_table + 8*NR_syscalls	// guard against failures to increase NR_syscalls
 #endif /* __IA64_ASM_PARAVIRTUALIZED_NATIVE */
diff --git a/arch/ia64/kernel/iosapic.c b/arch/ia64/kernel/iosapic.c
index f92cef4..c48b03f 100644
--- a/arch/ia64/kernel/iosapic.c
+++ b/arch/ia64/kernel/iosapic.c
@@ -451,7 +451,7 @@
 static void
 iosapic_ack_edge_irq (unsigned int irq)
 {
-	irq_desc_t *idesc = irq_desc + irq;
+	struct irq_desc *idesc = irq_desc + irq;
 
 	irq_complete_move(irq);
 	move_native_irq(irq);
@@ -600,8 +600,8 @@
 register_intr (unsigned int gsi, int irq, unsigned char delivery,
 	       unsigned long polarity, unsigned long trigger)
 {
-	irq_desc_t *idesc;
-	struct hw_interrupt_type *irq_type;
+	struct irq_desc *idesc;
+	struct irq_chip *irq_type;
 	int index;
 	struct iosapic_rte_info *rte;
 
@@ -650,7 +650,7 @@
 
 	idesc = irq_desc + irq;
 	if (irq_type != NULL && idesc->chip != irq_type) {
-		if (idesc->chip != &no_irq_type)
+		if (idesc->chip != &no_irq_chip)
 			printk(KERN_WARNING
 			       "%s: changing vector %d from %s to %s\n",
 			       __func__, irq_to_vector(irq),
@@ -828,7 +828,7 @@
 {
 	unsigned long flags;
 	int irq, index;
-	irq_desc_t *idesc;
+	struct irq_desc *idesc;
 	u32 low32;
 	unsigned long trigger, polarity;
 	unsigned int dest;
diff --git a/arch/ia64/kernel/irq.c b/arch/ia64/kernel/irq.c
index 7429752..7d89512 100644
--- a/arch/ia64/kernel/irq.c
+++ b/arch/ia64/kernel/irq.c
@@ -130,7 +130,7 @@
  */
 static void migrate_irqs(void)
 {
-	irq_desc_t *desc;
+	struct irq_desc *desc;
 	int 		irq, new_cpu;
 
 	for (irq=0; irq < NR_IRQS; irq++) {
diff --git a/arch/ia64/kernel/irq_ia64.c b/arch/ia64/kernel/irq_ia64.c
index b448197..dd9d7b5 100644
--- a/arch/ia64/kernel/irq_ia64.c
+++ b/arch/ia64/kernel/irq_ia64.c
@@ -630,7 +630,7 @@
 void
 ia64_native_register_percpu_irq (ia64_vector vec, struct irqaction *action)
 {
-	irq_desc_t *desc;
+	struct irq_desc *desc;
 	unsigned int irq;
 
 	irq = vec;
diff --git a/arch/ia64/kernel/irq_lsapic.c b/arch/ia64/kernel/irq_lsapic.c
index e56a7a3..fc1549d 100644
--- a/arch/ia64/kernel/irq_lsapic.c
+++ b/arch/ia64/kernel/irq_lsapic.c
@@ -33,7 +33,7 @@
 	return 1;
 }
 
-struct hw_interrupt_type irq_type_ia64_lsapic = {
+struct irq_chip irq_type_ia64_lsapic = {
 	.name =		"LSAPIC",
 	.startup =	lsapic_noop_startup,
 	.shutdown =	lsapic_noop,
diff --git a/arch/ia64/kernel/mca.c b/arch/ia64/kernel/mca.c
index 5b17bd4..7b30d21 100644
--- a/arch/ia64/kernel/mca.c
+++ b/arch/ia64/kernel/mca.c
@@ -850,7 +850,7 @@
 
 
 static inline void
-copy_reg(const u64 *fr, u64 fnat, u64 *tr, u64 *tnat)
+copy_reg(const u64 *fr, u64 fnat, unsigned long *tr, unsigned long *tnat)
 {
 	u64 fslot, tslot, nat;
 	*tr = *fr;
@@ -914,9 +914,9 @@
 	struct switch_stack *old_sw;
 	unsigned size = sizeof(struct pt_regs) +
 			sizeof(struct switch_stack) + 16;
-	u64 *old_bspstore, *old_bsp;
-	u64 *new_bspstore, *new_bsp;
-	u64 old_unat, old_rnat, new_rnat, nat;
+	unsigned long *old_bspstore, *old_bsp;
+	unsigned long *new_bspstore, *new_bsp;
+	unsigned long old_unat, old_rnat, new_rnat, nat;
 	u64 slots, loadrs = regs->loadrs;
 	u64 r12 = ms->pmsa_gr[12-1], r13 = ms->pmsa_gr[13-1];
 	u64 ar_bspstore = regs->ar_bspstore;
@@ -968,10 +968,10 @@
 	 * loadrs for the new stack and save it in the new pt_regs, where
 	 * ia64_old_stack() can get it.
 	 */
-	old_bspstore = (u64 *)ar_bspstore;
-	old_bsp = (u64 *)ar_bsp;
+	old_bspstore = (unsigned long *)ar_bspstore;
+	old_bsp = (unsigned long *)ar_bsp;
 	slots = ia64_rse_num_regs(old_bspstore, old_bsp);
-	new_bspstore = (u64 *)((u64)current + IA64_RBS_OFFSET);
+	new_bspstore = (unsigned long *)((u64)current + IA64_RBS_OFFSET);
 	new_bsp = ia64_rse_skip_regs(new_bspstore, slots);
 	regs->loadrs = (new_bsp - new_bspstore) * 8 << 16;
 
@@ -1917,9 +1917,9 @@
 	ia64_fptr_t *init_hldlr_ptr_slave = (ia64_fptr_t *)ia64_os_init_dispatch_slave;
 	ia64_fptr_t *mca_hldlr_ptr = (ia64_fptr_t *)ia64_os_mca_dispatch;
 	int i;
-	s64 rc;
+	long rc;
 	struct ia64_sal_retval isrv;
-	u64 timeout = IA64_MCA_RENDEZ_TIMEOUT;	/* platform specific */
+	unsigned long timeout = IA64_MCA_RENDEZ_TIMEOUT; /* platform specific */
 	static struct notifier_block default_init_monarch_nb = {
 		.notifier_call = default_monarch_init_process,
 		.priority = 0/* we need to notified last */
@@ -2092,7 +2092,7 @@
 	cpe_poll_timer.function = ia64_mca_cpe_poll;
 
 	{
-		irq_desc_t *desc;
+		struct irq_desc *desc;
 		unsigned int irq;
 
 		if (cpe_vector >= 0) {
diff --git a/arch/ia64/kernel/module.c b/arch/ia64/kernel/module.c
index da3b0cf..1481b0a 100644
--- a/arch/ia64/kernel/module.c
+++ b/arch/ia64/kernel/module.c
@@ -171,7 +171,8 @@
 		return 0;
 	}
 	if (val + ((uint64_t) 1 << 59) >= (1UL << 60)) {
-		printk(KERN_ERR "%s: value %ld out of IMM60 range\n", mod->name, (int64_t) val);
+		printk(KERN_ERR "%s: value %ld out of IMM60 range\n",
+			mod->name, (long) val);
 		return 0;
 	}
 	ia64_patch_imm60((u64) insn, val);
@@ -182,7 +183,8 @@
 apply_imm22 (struct module *mod, struct insn *insn, uint64_t val)
 {
 	if (val + (1 << 21) >= (1 << 22)) {
-		printk(KERN_ERR "%s: value %li out of IMM22 range\n", mod->name, (int64_t)val);
+		printk(KERN_ERR "%s: value %li out of IMM22 range\n",
+			mod->name, (long)val);
 		return 0;
 	}
 	ia64_patch((u64) insn, 0x01fffcfe000UL, (  ((val & 0x200000UL) << 15) /* bit 21 -> 36 */
@@ -196,7 +198,8 @@
 apply_imm21b (struct module *mod, struct insn *insn, uint64_t val)
 {
 	if (val + (1 << 20) >= (1 << 21)) {
-		printk(KERN_ERR "%s: value %li out of IMM21b range\n", mod->name, (int64_t)val);
+		printk(KERN_ERR "%s: value %li out of IMM21b range\n",
+			mod->name, (long)val);
 		return 0;
 	}
 	ia64_patch((u64) insn, 0x11ffffe000UL, (  ((val & 0x100000UL) << 16) /* bit 20 -> 36 */
@@ -701,8 +704,9 @@
 	      case RV_PCREL2:
 		if (r_type == R_IA64_PCREL21BI) {
 			if (!is_internal(mod, val)) {
-				printk(KERN_ERR "%s: %s reloc against non-local symbol (%lx)\n",
-				       __func__, reloc_name[r_type], val);
+				printk(KERN_ERR "%s: %s reloc against "
+					"non-local symbol (%lx)\n", __func__,
+					reloc_name[r_type], (unsigned long)val);
 				return -ENOEXEC;
 			}
 			format = RF_INSN21B;
diff --git a/arch/ia64/kernel/msi_ia64.c b/arch/ia64/kernel/msi_ia64.c
index 0f8ade9..6c89228 100644
--- a/arch/ia64/kernel/msi_ia64.c
+++ b/arch/ia64/kernel/msi_ia64.c
@@ -158,7 +158,7 @@
 }
 #endif /* CONFIG_SMP */
 
-struct irq_chip dmar_msi_type = {
+static struct irq_chip dmar_msi_type = {
 	.name = "DMAR_MSI",
 	.unmask = dmar_msi_unmask,
 	.mask = dmar_msi_mask,
diff --git a/arch/ia64/kernel/palinfo.c b/arch/ia64/kernel/palinfo.c
index a4f19c7..fdf6f9d 100644
--- a/arch/ia64/kernel/palinfo.c
+++ b/arch/ia64/kernel/palinfo.c
@@ -218,10 +218,10 @@
 cache_info(char *page)
 {
 	char *p = page;
-	u64 i, levels, unique_caches;
+	unsigned long i, levels, unique_caches;
 	pal_cache_config_info_t cci;
 	int j, k;
-	s64 status;
+	long status;
 
 	if ((status = ia64_pal_cache_summary(&levels, &unique_caches)) != 0) {
 		printk(KERN_ERR "ia64_pal_cache_summary=%ld\n", status);
@@ -303,7 +303,7 @@
 	ia64_ptce_info_t ptce;
 	const char *sep;
 	int i, j;
-	s64 status;
+	long status;
 
 	if ((status = ia64_pal_vm_summary(&vm_info_1, &vm_info_2)) !=0) {
 		printk(KERN_ERR "ia64_pal_vm_summary=%ld\n", status);
@@ -431,9 +431,9 @@
 	char *p = page;
 	u64 reg_info[2];
 	u64 info;
-	u64 phys_stacked;
+	unsigned long phys_stacked;
 	pal_hints_u_t hints;
-	u64 iregs, dregs;
+	unsigned long iregs, dregs;
 	char *info_type[]={
 		"Implemented AR(s)",
 		"AR(s) with read side-effects",
@@ -530,8 +530,8 @@
 	NULL, NULL, NULL, NULL,
 };
 
-static char *
-feature_set_info(char *page, u64 avail, u64 status, u64 control, u64 set)
+static char * feature_set_info(char *page, u64 avail, u64 status, u64 control,
+							unsigned long set)
 {
 	char *p = page;
 	char **vf, **v;
@@ -714,7 +714,7 @@
 {
 	char *p = page;
 	struct pal_freq_ratio proc, itc, bus;
-	u64 base;
+	unsigned long base;
 
 	if (ia64_pal_freq_base(&base) == -1)
 		p += sprintf(p, "Output clock            : not implemented\n");
@@ -736,43 +736,43 @@
 tr_info(char *page)
 {
 	char *p = page;
-	s64 status;
+	long status;
 	pal_tr_valid_u_t tr_valid;
 	u64 tr_buffer[4];
 	pal_vm_info_1_u_t vm_info_1;
 	pal_vm_info_2_u_t vm_info_2;
-	u64 i, j;
-	u64 max[3], pgm;
+	unsigned long i, j;
+	unsigned long max[3], pgm;
 	struct ifa_reg {
-		u64 valid:1;
-		u64 ig:11;
-		u64 vpn:52;
+		unsigned long valid:1;
+		unsigned long ig:11;
+		unsigned long vpn:52;
 	} *ifa_reg;
 	struct itir_reg {
-		u64 rv1:2;
-		u64 ps:6;
-		u64 key:24;
-		u64 rv2:32;
+		unsigned long rv1:2;
+		unsigned long ps:6;
+		unsigned long key:24;
+		unsigned long rv2:32;
 	} *itir_reg;
 	struct gr_reg {
-		u64 p:1;
-		u64 rv1:1;
-		u64 ma:3;
-		u64 a:1;
-		u64 d:1;
-		u64 pl:2;
-		u64 ar:3;
-		u64 ppn:38;
-		u64 rv2:2;
-		u64 ed:1;
-		u64 ig:11;
+		unsigned long p:1;
+		unsigned long rv1:1;
+		unsigned long ma:3;
+		unsigned long a:1;
+		unsigned long d:1;
+		unsigned long pl:2;
+		unsigned long ar:3;
+		unsigned long ppn:38;
+		unsigned long rv2:2;
+		unsigned long ed:1;
+		unsigned long ig:11;
 	} *gr_reg;
 	struct rid_reg {
-		u64 ig1:1;
-		u64 rv1:1;
-		u64 ig2:6;
-		u64 rid:24;
-		u64 rv2:32;
+		unsigned long ig1:1;
+		unsigned long rv1:1;
+		unsigned long ig2:6;
+		unsigned long rid:24;
+		unsigned long rv2:32;
 	} *rid_reg;
 
 	if ((status = ia64_pal_vm_summary(&vm_info_1, &vm_info_2)) !=0) {
diff --git a/arch/ia64/kernel/paravirt_patchlist.c b/arch/ia64/kernel/paravirt_patchlist.c
index b28082a..0a70720 100644
--- a/arch/ia64/kernel/paravirt_patchlist.c
+++ b/arch/ia64/kernel/paravirt_patchlist.c
@@ -19,6 +19,8 @@
  */
 
 #include <linux/bug.h>
+#include <linux/init.h>
+#include <linux/kernel.h>
 #include <asm/paravirt.h>
 
 #define DECLARE(name)						\
diff --git a/arch/ia64/kernel/pci-dma.c b/arch/ia64/kernel/pci-dma.c
index eb98738..1376da4 100644
--- a/arch/ia64/kernel/pci-dma.c
+++ b/arch/ia64/kernel/pci-dma.c
@@ -91,7 +91,7 @@
 	   type. Normally this doesn't make any difference, but gives
 	   more gentle handling of IOMMU overflow. */
 	if (iommu_sac_force && (mask >= DMA_BIT_MASK(40))) {
-		dev_info(dev, "Force SAC with mask %lx\n", mask);
+		dev_info(dev, "Force SAC with mask %llx\n", mask);
 		return 0;
 	}
 
diff --git a/arch/ia64/kernel/perfmon.c b/arch/ia64/kernel/perfmon.c
index bdc176c..abce246 100644
--- a/arch/ia64/kernel/perfmon.c
+++ b/arch/ia64/kernel/perfmon.c
@@ -312,7 +312,7 @@
 	unsigned long		th_pmcs[PFM_NUM_PMC_REGS];	/* PMC thread save state */
 	unsigned long		th_pmds[PFM_NUM_PMD_REGS];	/* PMD thread save state */
 
-	u64			ctx_saved_psr_up;	/* only contains psr.up value */
+	unsigned long		ctx_saved_psr_up;	/* only contains psr.up value */
 
 	unsigned long		ctx_last_activation;	/* context last activation number for last_cpu */
 	unsigned int		ctx_last_cpu;		/* CPU id of current or last CPU used (SMP only) */
@@ -5213,8 +5213,8 @@
  * main overflow processing routine.
  * it can be called from the interrupt path or explicitly during the context switch code
  */
-static void
-pfm_overflow_handler(struct task_struct *task, pfm_context_t *ctx, u64 pmc0, struct pt_regs *regs)
+static void pfm_overflow_handler(struct task_struct *task, pfm_context_t *ctx,
+				unsigned long pmc0, struct pt_regs *regs)
 {
 	pfm_ovfl_arg_t *ovfl_arg;
 	unsigned long mask;
diff --git a/arch/ia64/kernel/setup.c b/arch/ia64/kernel/setup.c
index 714066a..1b23ec12 100644
--- a/arch/ia64/kernel/setup.c
+++ b/arch/ia64/kernel/setup.c
@@ -151,9 +151,9 @@
  * This routine does not assume the incoming segments are sorted.
  */
 int __init
-filter_rsvd_memory (unsigned long start, unsigned long end, void *arg)
+filter_rsvd_memory (u64 start, u64 end, void *arg)
 {
-	unsigned long range_start, range_end, prev_start;
+	u64 range_start, range_end, prev_start;
 	void (*func)(unsigned long, unsigned long, int);
 	int i;
 
@@ -191,7 +191,7 @@
  * are not filtered out.
  */
 int __init
-filter_memory(unsigned long start, unsigned long end, void *arg)
+filter_memory(u64 start, u64 end, void *arg)
 {
 	void (*func)(unsigned long, unsigned long, int);
 
@@ -397,7 +397,7 @@
 		initrd_start = (unsigned long)__va(ia64_boot_param->initrd_start);
 		initrd_end   = initrd_start+ia64_boot_param->initrd_size;
 
-		printk(KERN_INFO "Initial ramdisk at: 0x%lx (%lu bytes)\n",
+		printk(KERN_INFO "Initial ramdisk at: 0x%lx (%llu bytes)\n",
 		       initrd_start, ia64_boot_param->initrd_size);
 	}
 #endif
@@ -505,9 +505,9 @@
 }
 early_param("elfcorehdr", parse_elfcorehdr);
 
-int __init reserve_elfcorehdr(unsigned long *start, unsigned long *end)
+int __init reserve_elfcorehdr(u64 *start, u64 *end)
 {
-	unsigned long length;
+	u64 length;
 
 	/* We get the address using the kernel command line,
 	 * but the size is extracted from the EFI tables.
@@ -588,7 +588,7 @@
 	ia64_patch_rse((u64) __start___rse_patchlist, (u64) __end___rse_patchlist);
 #else
 	{
-		u64 num_phys_stacked;
+		unsigned long num_phys_stacked;
 
 		if (ia64_pal_rse_info(&num_phys_stacked, 0) == 0 && num_phys_stacked > 96)
 			ia64_patch_rse((u64) __start___rse_patchlist, (u64) __end___rse_patchlist);
@@ -872,9 +872,9 @@
 get_cache_info(void)
 {
 	unsigned long line_size, max = 1;
-	u64 l, levels, unique_caches;
-        pal_cache_config_info_t cci;
-        s64 status;
+	unsigned long l, levels, unique_caches;
+	pal_cache_config_info_t cci;
+	long status;
 
         status = ia64_pal_cache_summary(&levels, &unique_caches);
         if (status != 0) {
@@ -892,9 +892,9 @@
 		/* cache_type (data_or_unified)=2 */
 		status = ia64_pal_cache_config_info(l, 2, &cci);
 		if (status != 0) {
-			printk(KERN_ERR
-			       "%s: ia64_pal_cache_config_info(l=%lu, 2) failed (status=%ld)\n",
-			       __func__, l, status);
+			printk(KERN_ERR "%s: ia64_pal_cache_config_info"
+				"(l=%lu, 2) failed (status=%ld)\n",
+				__func__, l, status);
 			max = SMP_CACHE_BYTES;
 			/* The safest setup for "flush_icache_range()" */
 			cci.pcci_stride = I_CACHE_STRIDE_SHIFT;
@@ -914,10 +914,10 @@
 			/* cache_type (instruction)=1*/
 			status = ia64_pal_cache_config_info(l, 1, &cci);
 			if (status != 0) {
-				printk(KERN_ERR
-				"%s: ia64_pal_cache_config_info(l=%lu, 1) failed (status=%ld)\n",
+				printk(KERN_ERR "%s: ia64_pal_cache_config_info"
+					"(l=%lu, 1) failed (status=%ld)\n",
 					__func__, l, status);
-				/* The safest setup for "flush_icache_range()" */
+				/* The safest setup for flush_icache_range() */
 				cci.pcci_stride = I_CACHE_STRIDE_SHIFT;
 			}
 		}
diff --git a/arch/ia64/kernel/smp.c b/arch/ia64/kernel/smp.c
index 5230eaa..f0c521b 100644
--- a/arch/ia64/kernel/smp.c
+++ b/arch/ia64/kernel/smp.c
@@ -66,7 +66,7 @@
 #define IPI_KDUMP_CPU_STOP	3
 
 /* This needs to be cacheline aligned because it is written to by *other* CPUs.  */
-static DEFINE_PER_CPU_SHARED_ALIGNED(u64, ipi_operation);
+static DEFINE_PER_CPU_SHARED_ALIGNED(unsigned long, ipi_operation);
 
 extern void cpu_halt (void);
 
diff --git a/arch/ia64/kernel/smpboot.c b/arch/ia64/kernel/smpboot.c
index 7700e23..de100aa 100644
--- a/arch/ia64/kernel/smpboot.c
+++ b/arch/ia64/kernel/smpboot.c
@@ -678,7 +678,7 @@
 int migrate_platform_irqs(unsigned int cpu)
 {
 	int new_cpei_cpu;
-	irq_desc_t *desc = NULL;
+	struct irq_desc *desc = NULL;
 	const struct cpumask *mask;
 	int 		retval = 0;
 
@@ -865,7 +865,7 @@
 void __devinit
 identify_siblings(struct cpuinfo_ia64 *c)
 {
-	s64 status;
+	long status;
 	u16 pltid;
 	pal_logical_to_physical_t info;
 
diff --git a/arch/ia64/kernel/time.c b/arch/ia64/kernel/time.c
index 604c1a3..4990495 100644
--- a/arch/ia64/kernel/time.c
+++ b/arch/ia64/kernel/time.c
@@ -385,7 +385,7 @@
 
 static cycle_t itc_get_cycles(struct clocksource *cs)
 {
-	u64 lcycle, now, ret;
+	unsigned long lcycle, now, ret;
 
 	if (!itc_jitter_data.itc_jitter)
 		return get_cycles();
diff --git a/arch/ia64/kernel/topology.c b/arch/ia64/kernel/topology.c
index a8d61a3..bc80dff 100644
--- a/arch/ia64/kernel/topology.c
+++ b/arch/ia64/kernel/topology.c
@@ -306,10 +306,10 @@
 
 static int __cpuinit cpu_cache_sysfs_init(unsigned int cpu)
 {
-	u64 i, levels, unique_caches;
+	unsigned long i, levels, unique_caches;
 	pal_cache_config_info_t cci;
 	int j;
-	s64 status;
+	long status;
 	struct cache_info *this_cache;
 	int num_cache_leaves = 0;
 
diff --git a/arch/ia64/kernel/uncached.c b/arch/ia64/kernel/uncached.c
index 6ba72ab..a595823 100644
--- a/arch/ia64/kernel/uncached.c
+++ b/arch/ia64/kernel/uncached.c
@@ -250,8 +250,7 @@
  * Called at boot time to build a map of pages that can be used for
  * memory special operations.
  */
-static int __init uncached_build_memmap(unsigned long uc_start,
-					unsigned long uc_end, void *arg)
+static int __init uncached_build_memmap(u64 uc_start, u64 uc_end, void *arg)
 {
 	int nid = paddr_to_nid(uc_start - __IA64_UNCACHED_OFFSET);
 	struct gen_pool *pool = uncached_pools[nid].pool;
diff --git a/arch/ia64/mm/contig.c b/arch/ia64/mm/contig.c
index 0ee085e..2f724d2 100644
--- a/arch/ia64/mm/contig.c
+++ b/arch/ia64/mm/contig.c
@@ -107,10 +107,10 @@
  * bootmap_start.  This address must be page-aligned.
  */
 static int __init
-find_bootmap_location (unsigned long start, unsigned long end, void *arg)
+find_bootmap_location (u64 start, u64 end, void *arg)
 {
-	unsigned long needed = *(unsigned long *)arg;
-	unsigned long range_start, range_end, free_start;
+	u64 needed = *(unsigned long *)arg;
+	u64 range_start, range_end, free_start;
 	int i;
 
 #if IGNORE_PFN0
@@ -229,8 +229,7 @@
 	alloc_per_cpu_data();
 }
 
-static int
-count_pages (u64 start, u64 end, void *arg)
+static int count_pages(u64 start, u64 end, void *arg)
 {
 	unsigned long *count = arg;
 
diff --git a/arch/ia64/mm/init.c b/arch/ia64/mm/init.c
index c0f3bee..b115b3b 100644
--- a/arch/ia64/mm/init.c
+++ b/arch/ia64/mm/init.c
@@ -422,8 +422,7 @@
 	return hole_next_pfn - pgdat->node_start_pfn;
 }
 
-int __init
-create_mem_map_page_table (u64 start, u64 end, void *arg)
+int __init create_mem_map_page_table(u64 start, u64 end, void *arg)
 {
 	unsigned long address, start_page, end_page;
 	struct page *map_start, *map_end;
@@ -469,7 +468,7 @@
 };
 
 static int __meminit
-virtual_memmap_init (u64 start, u64 end, void *arg)
+virtual_memmap_init(u64 start, u64 end, void *arg)
 {
 	struct memmap_init_callback_data *args;
 	struct page *map_start, *map_end;
@@ -531,8 +530,7 @@
 }
 EXPORT_SYMBOL(ia64_pfn_valid);
 
-int __init
-find_largest_hole (u64 start, u64 end, void *arg)
+int __init find_largest_hole(u64 start, u64 end, void *arg)
 {
 	u64 *max_gap = arg;
 
@@ -548,8 +546,7 @@
 
 #endif /* CONFIG_VIRTUAL_MEM_MAP */
 
-int __init
-register_active_ranges(u64 start, u64 len, int nid)
+int __init register_active_ranges(u64 start, u64 len, int nid)
 {
 	u64 end = start + len;
 
@@ -567,7 +564,7 @@
 }
 
 static int __init
-count_reserved_pages (u64 start, u64 end, void *arg)
+count_reserved_pages(u64 start, u64 end, void *arg)
 {
 	unsigned long num_reserved = 0;
 	unsigned long *count = arg;
@@ -580,7 +577,7 @@
 }
 
 int
-find_max_min_low_pfn (unsigned long start, unsigned long end, void *arg)
+find_max_min_low_pfn (u64 start, u64 end, void *arg)
 {
 	unsigned long pfn_start, pfn_end;
 #ifdef CONFIG_FLATMEM
diff --git a/arch/ia64/mm/tlb.c b/arch/ia64/mm/tlb.c
index b9f3d7b..f426dc7 100644
--- a/arch/ia64/mm/tlb.c
+++ b/arch/ia64/mm/tlb.c
@@ -34,7 +34,7 @@
 #include <asm/tlb.h>
 
 static struct {
-	unsigned long mask;	/* mask of supported purge page-sizes */
+	u64 mask;		/* mask of supported purge page-sizes */
 	unsigned long max_bits;	/* log2 of largest supported purge page-size */
 } purge;
 
@@ -328,7 +328,7 @@
 ia64_tlb_init (void)
 {
 	ia64_ptce_info_t uninitialized_var(ptce_info); /* GCC be quiet */
-	unsigned long tr_pgbits;
+	u64 tr_pgbits;
 	long status;
 	pal_vm_info_1_u_t vm_info_1;
 	pal_vm_info_2_u_t vm_info_2;
diff --git a/arch/ia64/pci/pci.c b/arch/ia64/pci/pci.c
index 61f1af5..729298f 100644
--- a/arch/ia64/pci/pci.c
+++ b/arch/ia64/pci/pci.c
@@ -163,7 +163,7 @@
 {
 	struct resource *resource;
 	char *name;
-	u64 base, min, max, base_port;
+	unsigned long base, min, max, base_port;
 	unsigned int sparse = 0, space_nr, len;
 
 	resource = kzalloc(sizeof(*resource), GFP_KERNEL);
@@ -292,7 +292,7 @@
 	window->offset = offset;
 
 	if (insert_resource(root, &window->resource)) {
-		printk(KERN_ERR "alloc 0x%lx-0x%lx from %s for %s failed\n",
+		printk(KERN_ERR "alloc 0x%llx-0x%llx from %s for %s failed\n",
 			window->resource.start, window->resource.end,
 			root->name, info->name);
 	}
@@ -314,8 +314,8 @@
 		    (res->end - res->start < 16))
 			continue;
 		if (j >= PCI_BUS_NUM_RESOURCES) {
-			printk("Ignoring range [%lx-%lx] (%lx)\n", res->start,
-					res->end, res->flags);
+			printk("Ignoring range [%#llx-%#llx] (%lx)\n",
+					res->start, res->end, res->flags);
 			continue;
 		}
 		bus->resource[j++] = res;
@@ -371,8 +371,6 @@
 	 * such quirk. So we just ignore the case now.
 	 */
 	pbus = pci_scan_bus_parented(NULL, bus, &pci_root_ops, controller);
-	if (pbus)
-		pcibios_setup_root_windows(pbus, controller);
 
 	return pbus;
 
@@ -490,6 +488,8 @@
 	if (b->self) {
 		pci_read_bridge_bases(b);
 		pcibios_fixup_bridge_resources(b->self);
+	} else {
+		pcibios_setup_root_windows(b, b->sysdata);
 	}
 	list_for_each_entry(dev, &b->devices, bus_list)
 		pcibios_fixup_device_resources(dev);
@@ -728,8 +728,8 @@
  */
 static void __init set_pci_cacheline_size(void)
 {
-	u64 levels, unique_caches;
-	s64 status;
+	unsigned long levels, unique_caches;
+	long status;
 	pal_cache_config_info_t cci;
 
 	status = ia64_pal_cache_summary(&levels, &unique_caches);
diff --git a/arch/ia64/sn/kernel/io_acpi_init.c b/arch/ia64/sn/kernel/io_acpi_init.c
index d0223ab..fd50ff9 100644
--- a/arch/ia64/sn/kernel/io_acpi_init.c
+++ b/arch/ia64/sn/kernel/io_acpi_init.c
@@ -40,7 +40,7 @@
 /*
  * Perform the early IO init in PROM.
  */
-static s64
+static long
 sal_ioif_init(u64 *result)
 {
 	struct ia64_sal_retval isrv = {0,0,0,0};
@@ -492,7 +492,7 @@
 sn_io_acpi_init(void)
 {
 	u64 result;
-	s64 status;
+	long status;
 
 	/* SN Altix does not follow the IOSAPIC IRQ routing model */
 	acpi_irq_model = ACPI_IRQ_MODEL_PLATFORM;
diff --git a/arch/ia64/sn/kernel/io_common.c b/arch/ia64/sn/kernel/io_common.c
index 57f280d..76645cf 100644
--- a/arch/ia64/sn/kernel/io_common.c
+++ b/arch/ia64/sn/kernel/io_common.c
@@ -342,7 +342,7 @@
 		struct pcibus_bussoft *b = SN_PCIBUS_BUSSOFT(bus);
 
 		printk(KERN_WARNING "Device ASIC=%u XID=%u PBUSNUM=%u "
-		       "L_IO=%lx L_MEM=%lx BASE=%lx\n",
+		       "L_IO=%llx L_MEM=%llx BASE=%llx\n",
 		       b->bs_asic_type, b->bs_xid, b->bs_persist_busnum,
 		       b->bs_legacy_io, b->bs_legacy_mem, b->bs_base);
 		printk(KERN_WARNING "on node %d but only %d nodes online."
diff --git a/arch/ia64/sn/kernel/irq.c b/arch/ia64/sn/kernel/irq.c
index 764f26a..40d6eed 100644
--- a/arch/ia64/sn/kernel/irq.c
+++ b/arch/ia64/sn/kernel/irq.c
@@ -295,13 +295,13 @@
 void sn_irq_init(void)
 {
 	int i;
-	irq_desc_t *base_desc = irq_desc;
+	struct irq_desc *base_desc = irq_desc;
 
 	ia64_first_device_vector = IA64_SN2_FIRST_DEVICE_VECTOR;
 	ia64_last_device_vector = IA64_SN2_LAST_DEVICE_VECTOR;
 
 	for (i = 0; i < NR_IRQS; i++) {
-		if (base_desc[i].chip == &no_irq_type) {
+		if (base_desc[i].chip == &no_irq_chip) {
 			base_desc[i].chip = &irq_type_sn;
 		}
 	}
@@ -377,7 +377,7 @@
 	int cpu = nasid_slice_to_cpuid(nasid, slice);
 #ifdef CONFIG_SMP
 	int cpuphys;
-	irq_desc_t *desc;
+	struct irq_desc *desc;
 #endif
 
 	pci_dev_get(pci_dev);
diff --git a/arch/ia64/sn/kernel/sn2/sn_hwperf.c b/arch/ia64/sn/kernel/sn2/sn_hwperf.c
index 9e6491c..4c7e747 100644
--- a/arch/ia64/sn/kernel/sn2/sn_hwperf.c
+++ b/arch/ia64/sn/kernel/sn2/sn_hwperf.c
@@ -414,7 +414,7 @@
 		}
 		seq_printf(s, "partition %u %s local "
 			"shubtype %s, "
-			"nasid_mask 0x%016lx, "
+			"nasid_mask 0x%016llx, "
 			"nasid_bits %d:%d, "
 			"system_size %d, "
 			"sharing_size %d, "
@@ -683,7 +683,7 @@
  * ioctl for "sn_hwperf" misc device
  */
 static int
-sn_hwperf_ioctl(struct inode *in, struct file *fp, u32 op, u64 arg)
+sn_hwperf_ioctl(struct inode *in, struct file *fp, u32 op, unsigned long arg)
 {
 	struct sn_hwperf_ioctl_args a;
 	struct cpuinfo_ia64 *cdata;
diff --git a/arch/ia64/sn/kernel/sn2/sn_proc_fs.c b/arch/ia64/sn/kernel/sn2/sn_proc_fs.c
index 2526e5c..c76d8dc 100644
--- a/arch/ia64/sn/kernel/sn2/sn_proc_fs.c
+++ b/arch/ia64/sn/kernel/sn2/sn_proc_fs.c
@@ -36,7 +36,7 @@
 
 static int licenseID_show(struct seq_file *s, void *p)
 {
-	seq_printf(s, "0x%lx\n", sn_partition_serial_number_val());
+	seq_printf(s, "0x%llx\n", sn_partition_serial_number_val());
 	return 0;
 }
 
diff --git a/arch/ia64/sn/kernel/tiocx.c b/arch/ia64/sn/kernel/tiocx.c
index 3f86423..c1bd1cf 100644
--- a/arch/ia64/sn/kernel/tiocx.c
+++ b/arch/ia64/sn/kernel/tiocx.c
@@ -368,7 +368,7 @@
 static int is_fpga_tio(int nasid, int *bt)
 {
 	u16 uninitialized_var(ioboard_type);	/* GCC be quiet */
-	s64 rc;
+	long rc;
 
 	rc = ia64_sn_sysctl_ioboard_get(nasid, &ioboard_type);
 	if (rc) {
diff --git a/arch/ia64/sn/pci/pcibr/pcibr_provider.c b/arch/ia64/sn/pci/pcibr/pcibr_provider.c
index 2c676cc..d13e5a2 100644
--- a/arch/ia64/sn/pci/pcibr/pcibr_provider.c
+++ b/arch/ia64/sn/pci/pcibr/pcibr_provider.c
@@ -79,7 +79,7 @@
 
 u16 sn_ioboard_to_pci_bus(struct pci_bus *pci_bus)
 {
-	s64 rc;
+	long rc;
 	u16 uninitialized_var(ioboard);		/* GCC be quiet */
 	nasid_t nasid = NASID_GET(SN_PCIBUS_BUSSOFT(pci_bus)->bs_base);
 
diff --git a/arch/ia64/sn/pci/tioca_provider.c b/arch/ia64/sn/pci/tioca_provider.c
index 79165122..35b2a27 100644
--- a/arch/ia64/sn/pci/tioca_provider.c
+++ b/arch/ia64/sn/pci/tioca_provider.c
@@ -123,7 +123,7 @@
 
 	if (!tmp) {
 		printk(KERN_ERR "%s:  Could not allocate "
-		       "%lu bytes (order %d) for GART\n",
+		       "%llu bytes (order %d) for GART\n",
 		       __func__,
 		       tioca_kern->ca_gart_size,
 		       get_order(tioca_kern->ca_gart_size));
@@ -348,7 +348,7 @@
 	agp_dma_extn = __sn_readq_relaxed(&ca_base->ca_agp_dma_addr_extn);
 	if (node_upper != (agp_dma_extn >> CA_AGP_DMA_NODE_ID_SHFT)) {
 		printk(KERN_ERR "%s:  coretalk upper node (%u) "
-		       "mismatch with ca_agp_dma_addr_extn (%lu)\n",
+		       "mismatch with ca_agp_dma_addr_extn (%llu)\n",
 		       __func__,
 		       node_upper, (agp_dma_extn >> CA_AGP_DMA_NODE_ID_SHFT));
 		return 0;
@@ -367,7 +367,7 @@
  * dma_addr_t is guaranteed to be contiguous in CA bus space.
  */
 static dma_addr_t
-tioca_dma_mapped(struct pci_dev *pdev, u64 paddr, size_t req_size)
+tioca_dma_mapped(struct pci_dev *pdev, unsigned long paddr, size_t req_size)
 {
 	int i, ps, ps_shift, entry, entries, mapsize, last_entry;
 	u64 xio_addr, end_xio_addr;
diff --git a/arch/ia64/sn/pci/tioce_provider.c b/arch/ia64/sn/pci/tioce_provider.c
index 94e5845..012f3b8 100644
--- a/arch/ia64/sn/pci/tioce_provider.c
+++ b/arch/ia64/sn/pci/tioce_provider.c
@@ -493,7 +493,7 @@
 
 		if (&map->ce_dmamap_list == &ce_kern->ce_dmamap_list) {
 			printk(KERN_WARNING
-			       "%s:  %s - no map found for bus_addr 0x%lx\n",
+			       "%s:  %s - no map found for bus_addr 0x%llx\n",
 			       __func__, pci_name(pdev), bus_addr);
 		} else if (--map->refcnt == 0) {
 			for (i = 0; i < map->ate_count; i++) {
@@ -642,7 +642,7 @@
  * in the address.
  */
 static u64
-tioce_dma(struct pci_dev *pdev, u64 paddr, size_t byte_count, int dma_flags)
+tioce_dma(struct pci_dev *pdev, unsigned long  paddr, size_t byte_count, int dma_flags)
 {
 	return tioce_do_dma_map(pdev, paddr, byte_count, 0, dma_flags);
 }
@@ -657,7 +657,7 @@
  * in the address.
  */
 static u64
-tioce_dma_consistent(struct pci_dev *pdev, u64 paddr, size_t byte_count, int dma_flags)
+tioce_dma_consistent(struct pci_dev *pdev, unsigned long  paddr, size_t byte_count, int dma_flags)
 {
 	return tioce_do_dma_map(pdev, paddr, byte_count, 1, dma_flags);
 }
diff --git a/arch/ia64/xen/irq_xen.c b/arch/ia64/xen/irq_xen.c
index af93aad..f042e19 100644
--- a/arch/ia64/xen/irq_xen.c
+++ b/arch/ia64/xen/irq_xen.c
@@ -138,7 +138,7 @@
 __xen_register_percpu_irq(unsigned int cpu, unsigned int vec,
 			struct irqaction *action, int save)
 {
-	irq_desc_t *desc;
+	struct irq_desc *desc;
 	int irq = 0;
 
 	if (xen_slab_ready) {
diff --git a/arch/m32r/kernel/process.c b/arch/m32r/kernel/process.c
index 3e876f0..67a01e1 100644
--- a/arch/m32r/kernel/process.c
+++ b/arch/m32r/kernel/process.c
@@ -302,11 +302,6 @@
 		goto out;
 
 	error = do_execve(filename, uargv, uenvp, &regs);
-	if (error == 0) {
-		task_lock(current);
-		current->ptrace &= ~PT_DTRACE;
-		task_unlock(current);
-	}
 	putname(filename);
 out:
 	return error;
diff --git a/arch/m32r/kernel/ptrace.c b/arch/m32r/kernel/ptrace.c
index 9aa615d..bf0abe9 100644
--- a/arch/m32r/kernel/ptrace.c
+++ b/arch/m32r/kernel/ptrace.c
@@ -676,10 +676,6 @@
 		if (!valid_signal(data))
 			break;
 		clear_tsk_thread_flag(child, TIF_SYSCALL_TRACE);
-		if ((child->ptrace & PT_DTRACE) == 0) {
-			/* Spurious delayed TF traps may occur */
-			child->ptrace |= PT_DTRACE;
-		}
 
 		/* Compute next pc.  */
 		pc = get_stack_long(child, PT_BPC);
diff --git a/arch/m68k/kernel/traps.c b/arch/m68k/kernel/traps.c
index 184acc9..aacd6d1 100644
--- a/arch/m68k/kernel/traps.c
+++ b/arch/m68k/kernel/traps.c
@@ -1057,7 +1057,6 @@
 	if (fp->ptregs.sr & PS_S) {
 		if ((fp->ptregs.vector >> 2) == VEC_TRACE) {
 			/* traced a trapping instruction */
-			current->ptrace |= PT_DTRACE;
 		} else
 			bad_super_trap(fp);
 		return;
diff --git a/arch/m68knommu/kernel/asm-offsets.c b/arch/m68knommu/kernel/asm-offsets.c
index f500dd6..594ee0e 100644
--- a/arch/m68knommu/kernel/asm-offsets.c
+++ b/arch/m68knommu/kernel/asm-offsets.c
@@ -73,7 +73,6 @@
 	DEFINE(TRAP_TRACE, TRAP_TRACE);
 
 	DEFINE(PT_PTRACED, PT_PTRACED);
-	DEFINE(PT_DTRACE, PT_DTRACE);
 
 	DEFINE(THREAD_SIZE, THREAD_SIZE);
 
diff --git a/arch/m68knommu/kernel/traps.c b/arch/m68knommu/kernel/traps.c
index 5d5d56b..51d3253 100644
--- a/arch/m68knommu/kernel/traps.c
+++ b/arch/m68knommu/kernel/traps.c
@@ -200,7 +200,6 @@
 	if (fp->ptregs.sr & PS_S) {
 		if ((fp->ptregs.vector >> 2) == VEC_TRACE) {
 			/* traced a trapping instruction */
-			current->ptrace |= PT_DTRACE;
 		} else
 			bad_super_trap(fp);
 		return;
diff --git a/arch/microblaze/kernel/init_task.c b/arch/microblaze/kernel/init_task.c
index 48eb9fb..67da225 100644
--- a/arch/microblaze/kernel/init_task.c
+++ b/arch/microblaze/kernel/init_task.c
@@ -18,8 +18,6 @@
 
 static struct signal_struct init_signals = INIT_SIGNALS(init_signals);
 static struct sighand_struct init_sighand = INIT_SIGHAND(init_sighand);
-struct mm_struct init_mm = INIT_MM(init_mm);
-EXPORT_SYMBOL(init_mm);
 
 union thread_union init_thread_union
 	__attribute__((__section__(".data.init_task"))) =
diff --git a/arch/microblaze/kernel/vmlinux.lds.S b/arch/microblaze/kernel/vmlinux.lds.S
index 8ae807a..d34d38d 100644
--- a/arch/microblaze/kernel/vmlinux.lds.S
+++ b/arch/microblaze/kernel/vmlinux.lds.S
@@ -62,7 +62,8 @@
 
 	_sdata = . ;
 	.data ALIGN (4096) : { /* page aligned when MMU used - origin 0x4 */
-		*(.data)
+		DATA_DATA
+		CONSTRUCTORS
 	}
 	. = ALIGN(32);
 	.data.cacheline_aligned : { *(.data.cacheline_aligned) }
@@ -98,13 +99,13 @@
 	. = ALIGN(4096);
 	.init.text : {
 		_sinittext = . ;
-		*(.init.text)
-		*(.exit.text)
-		*(.exit.data)
+		INIT_TEXT
 		_einittext = .;
 	}
 
-	.init.data : { *(.init.data) }
+	.init.data : {
+		INIT_DATA
+	}
 
 	. = ALIGN(4);
 	.init.ivt : {
diff --git a/arch/mips/Kconfig b/arch/mips/Kconfig
index 25f3b0a..b29f028 100644
--- a/arch/mips/Kconfig
+++ b/arch/mips/Kconfig
@@ -618,6 +618,8 @@
 	select SYS_HAS_EARLY_PRINTK
 	select SYS_HAS_CPU_CAVIUM_OCTEON
 	select SWAP_IO_SPACE
+	select HW_HAS_PCI
+	select ARCH_SUPPORTS_MSI
 	help
 	  This option supports all of the Octeon reference boards from Cavium
 	  Networks. It builds a kernel that dynamically determines the Octeon
@@ -851,6 +853,11 @@
 config SYS_SUPPORTS_LITTLE_ENDIAN
 	bool
 
+config SYS_SUPPORTS_HUGETLBFS
+	bool
+	depends on CPU_SUPPORTS_HUGEPAGES && 64BIT
+	default y
+
 config IRQ_CPU
 	bool
 
@@ -1055,6 +1062,7 @@
 	select CPU_SUPPORTS_32BIT_KERNEL
 	select CPU_SUPPORTS_64BIT_KERNEL
 	select CPU_SUPPORTS_HIGHMEM
+	select CPU_SUPPORTS_HUGEPAGES
 	help
 	  Choose this option to build a kernel for release 1 or later of the
 	  MIPS64 architecture.  Many modern embedded systems with a 64-bit
@@ -1074,6 +1082,7 @@
 	select CPU_SUPPORTS_32BIT_KERNEL
 	select CPU_SUPPORTS_64BIT_KERNEL
 	select CPU_SUPPORTS_HIGHMEM
+	select CPU_SUPPORTS_HUGEPAGES
 	help
 	  Choose this option to build a kernel for release 2 or later of the
 	  MIPS64 architecture.  Many modern embedded systems with a 64-bit
@@ -1160,6 +1169,7 @@
 	select CPU_HAS_LLSC
 	select CPU_SUPPORTS_32BIT_KERNEL
 	select CPU_SUPPORTS_64BIT_KERNEL
+	select CPU_SUPPORTS_HUGEPAGES
 	help
 	  NEC VR5500 and VR5500A series processors implement 64-bit MIPS IV
 	  instruction set.
@@ -1245,6 +1255,7 @@
 	select WEAK_ORDERING
 	select WEAK_REORDERING_BEYOND_LLSC
 	select CPU_SUPPORTS_HIGHMEM
+	select CPU_SUPPORTS_HUGEPAGES
 	help
 	  The Cavium Octeon processor is a highly integrated chip containing
 	  many ethernet hardware widgets for networking tasks. The processor
@@ -1364,6 +1375,8 @@
 	bool
 config CPU_SUPPORTS_64BIT_KERNEL
 	bool
+config CPU_SUPPORTS_HUGEPAGES
+	bool
 
 #
 # Set to y for ptrace access to watch registers.
@@ -2121,6 +2134,10 @@
 
 menu "Power management options"
 
+config ARCH_HIBERNATION_POSSIBLE
+	def_bool y
+	depends on !SMP
+
 config ARCH_SUSPEND_POSSIBLE
 	def_bool y
 	depends on !SMP
diff --git a/arch/mips/Makefile b/arch/mips/Makefile
index c4cae9e..807572a 100644
--- a/arch/mips/Makefile
+++ b/arch/mips/Makefile
@@ -167,7 +167,6 @@
 libs-$(CONFIG_CFE)		+= arch/mips/fw/cfe/
 libs-$(CONFIG_SNIPROM)		+= arch/mips/fw/sni/
 libs-y				+= arch/mips/fw/lib/
-libs-$(CONFIG_SIBYTE_CFE)	+= arch/mips/sibyte/cfe/
 
 #
 # Board-dependent options and extra files
@@ -184,7 +183,6 @@
 # Common Alchemy Au1x00 stuff
 #
 core-$(CONFIG_SOC_AU1X00)	+= arch/mips/alchemy/common/
-cflags-$(CONFIG_SOC_AU1X00)	+= -I$(srctree)/arch/mips/include/asm/mach-au1x00
 
 #
 # AMD Alchemy Pb1000 eval board
@@ -282,6 +280,10 @@
 libs-$(CONFIG_MIPS_XXS1500)	+= arch/mips/alchemy/xxs1500/
 load-$(CONFIG_MIPS_XXS1500)	+= 0xffffffff80100000
 
+# must be last for Alchemy systems for GPIO to work properly
+cflags-$(CONFIG_SOC_AU1X00)	+= -I$(srctree)/arch/mips/include/asm/mach-au1x00
+
+
 #
 # Cobalt Server
 #
@@ -675,6 +677,9 @@
 
 drivers-$(CONFIG_OPROFILE)	+= arch/mips/oprofile/
 
+# suspend and hibernation support
+drivers-$(CONFIG_PM)	+= arch/mips/power/
+
 ifdef CONFIG_LASAT
 rom.bin rom.sw: vmlinux
 	$(Q)$(MAKE) $(build)=arch/mips/lasat/image $@
diff --git a/arch/mips/alchemy/Kconfig b/arch/mips/alchemy/Kconfig
index 8128aeb..00b498e 100644
--- a/arch/mips/alchemy/Kconfig
+++ b/arch/mips/alchemy/Kconfig
@@ -1,3 +1,14 @@
+# au1000-style gpio
+config ALCHEMY_GPIO_AU1000
+	bool
+
+# select this in your board config if you don't want to use the gpio
+# namespace as documented in the manuals.  In this case however you need
+# to create the necessary gpio_* functions in your board code/headers!
+# see arch/mips/include/asm/mach-au1x00/gpio.h   for more information.
+config ALCHEMY_GPIO_INDIRECT
+	def_bool n
+
 choice
 	prompt "Machine type"
 	depends on MACH_ALCHEMY
@@ -108,22 +119,27 @@
 config SOC_AU1000
 	bool
 	select SOC_AU1X00
+	select ALCHEMY_GPIO_AU1000
 
 config SOC_AU1100
 	bool
 	select SOC_AU1X00
+	select ALCHEMY_GPIO_AU1000
 
 config SOC_AU1500
 	bool
 	select SOC_AU1X00
+	select ALCHEMY_GPIO_AU1000
 
 config SOC_AU1550
 	bool
 	select SOC_AU1X00
+	select ALCHEMY_GPIO_AU1000
 
 config SOC_AU1200
 	bool
 	select SOC_AU1X00
+	select ALCHEMY_GPIO_AU1000
 
 config SOC_AU1X00
 	bool
@@ -134,4 +150,5 @@
 	select SYS_HAS_CPU_MIPS32_R1
 	select SYS_SUPPORTS_32BIT_KERNEL
 	select SYS_SUPPORTS_APM_EMULATION
-	select ARCH_REQUIRE_GPIOLIB
+	select GENERIC_GPIO
+	select ARCH_WANT_OPTIONAL_GPIOLIB
diff --git a/arch/mips/alchemy/common/Makefile b/arch/mips/alchemy/common/Makefile
index d50d476..b67fb51 100644
--- a/arch/mips/alchemy/common/Makefile
+++ b/arch/mips/alchemy/common/Makefile
@@ -7,7 +7,14 @@
 
 obj-y += prom.o irq.o puts.o time.o reset.o \
 	clocks.o platform.o power.o setup.o \
-	sleeper.o dma.o dbdma.o gpio.o
+	sleeper.o dma.o dbdma.o
+
+# optional gpiolib support
+ifeq ($(CONFIG_ALCHEMY_GPIO_INDIRECT),)
+ ifeq ($(CONFIG_GPIOLIB),y)
+  obj-$(CONFIG_ALCHEMY_GPIO_AU1000) += gpiolib-au1000.o
+ endif
+endif
 
 obj-$(CONFIG_PCI)		+= pci.o
 
diff --git a/arch/mips/alchemy/common/gpio.c b/arch/mips/alchemy/common/gpio.c
deleted file mode 100644
index 91a9c44..0000000
--- a/arch/mips/alchemy/common/gpio.c
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- *  Copyright (C) 2007-2009, OpenWrt.org, Florian Fainelli <florian@openwrt.org>
- *  	Architecture specific GPIO support
- *
- *  This program is free software; you can redistribute	 it and/or modify it
- *  under  the terms of	 the GNU General  Public License as published by the
- *  Free Software Foundation;  either version 2 of the	License, or (at your
- *  option) any later version.
- *
- *  THIS  SOFTWARE  IS PROVIDED	  ``AS	IS'' AND   ANY	EXPRESS OR IMPLIED
- *  WARRANTIES,	  INCLUDING, BUT NOT  LIMITED  TO, THE IMPLIED WARRANTIES OF
- *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
- *  NO	EVENT  SHALL   THE AUTHOR  BE	 LIABLE FOR ANY	  DIRECT, INDIRECT,
- *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- *  NOT LIMITED	  TO, PROCUREMENT OF  SUBSTITUTE GOODS	OR SERVICES; LOSS OF
- *  USE, DATA,	OR PROFITS; OR	BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- *  ANY THEORY OF LIABILITY, WHETHER IN	 CONTRACT, STRICT LIABILITY, OR TORT
- *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- *  You should have received a copy of the  GNU General Public License along
- *  with this program; if not, write  to the Free Software Foundation, Inc.,
- *  675 Mass Ave, Cambridge, MA 02139, USA.
- *
- *  Notes :
- * 	au1000 SoC have only one GPIO line : GPIO1
- * 	others have a second one : GPIO2
- */
-
-#include <linux/kernel.h>
-#include <linux/module.h>
-#include <linux/types.h>
-#include <linux/platform_device.h>
-#include <linux/gpio.h>
-
-#include <asm/mach-au1x00/au1000.h>
-#include <asm/gpio.h>
-
-struct au1000_gpio_chip {
-	struct gpio_chip	chip;
-	void __iomem		*regbase;
-};
-
-#if !defined(CONFIG_SOC_AU1000)
-static int au1000_gpio2_get(struct gpio_chip *chip, unsigned offset)
-{
-	u32 mask = 1 << offset;
-	struct au1000_gpio_chip *gpch;
-
-	gpch = container_of(chip, struct au1000_gpio_chip, chip);
-	return readl(gpch->regbase + AU1000_GPIO2_ST) & mask;
-}
-
-static void au1000_gpio2_set(struct gpio_chip *chip,
-				unsigned offset, int value)
-{
-	u32 mask = ((GPIO2_OUT_EN_MASK << offset) | (!!value << offset));
-	struct au1000_gpio_chip *gpch;
-	unsigned long flags;
-
-	gpch = container_of(chip, struct au1000_gpio_chip, chip);
-
-	local_irq_save(flags);
-	writel(mask, gpch->regbase + AU1000_GPIO2_OUT);
-	local_irq_restore(flags);
-}
-
-static int au1000_gpio2_direction_input(struct gpio_chip *chip, unsigned offset)
-{
-	u32 mask = 1 << offset;
-	u32 tmp;
-	struct au1000_gpio_chip *gpch;
-	unsigned long flags;
-
-	gpch = container_of(chip, struct au1000_gpio_chip, chip);
-
-	local_irq_save(flags);
-	tmp = readl(gpch->regbase + AU1000_GPIO2_DIR);
-	tmp &= ~mask;
-	writel(tmp, gpch->regbase + AU1000_GPIO2_DIR);
-	local_irq_restore(flags);
-
-	return 0;
-}
-
-static int au1000_gpio2_direction_output(struct gpio_chip *chip,
-					unsigned offset, int value)
-{
-	u32 mask = 1 << offset;
-	u32 out_mask = ((GPIO2_OUT_EN_MASK << offset) | (!!value << offset));
-	u32 tmp;
-	struct au1000_gpio_chip *gpch;
-	unsigned long flags;
-
-	gpch = container_of(chip, struct au1000_gpio_chip, chip);
-
-	local_irq_save(flags);
-	tmp = readl(gpch->regbase + AU1000_GPIO2_DIR);
-	tmp |= mask;
-	writel(tmp, gpch->regbase + AU1000_GPIO2_DIR);
-	writel(out_mask, gpch->regbase + AU1000_GPIO2_OUT);
-	local_irq_restore(flags);
-
-	return 0;
-}
-#endif /* !defined(CONFIG_SOC_AU1000) */
-
-static int au1000_gpio1_get(struct gpio_chip *chip, unsigned offset)
-{
-	u32 mask = 1 << offset;
-	struct au1000_gpio_chip *gpch;
-
-	gpch = container_of(chip, struct au1000_gpio_chip, chip);
-	return readl(gpch->regbase + AU1000_GPIO1_ST) & mask;
-}
-
-static void au1000_gpio1_set(struct gpio_chip *chip,
-				unsigned offset, int value)
-{
-	u32 mask = 1 << offset;
-	u32 reg_offset;
-	struct au1000_gpio_chip *gpch;
-	unsigned long flags;
-
-	gpch = container_of(chip, struct au1000_gpio_chip, chip);
-
-	if (value)
-		reg_offset = AU1000_GPIO1_OUT;
-	else
-		reg_offset = AU1000_GPIO1_CLR;
-
-	local_irq_save(flags);
-	writel(mask, gpch->regbase + reg_offset);
-	local_irq_restore(flags);
-}
-
-static int au1000_gpio1_direction_input(struct gpio_chip *chip, unsigned offset)
-{
-	u32 mask = 1 << offset;
-	struct au1000_gpio_chip *gpch;
-
-	gpch = container_of(chip, struct au1000_gpio_chip, chip);
-	writel(mask, gpch->regbase + AU1000_GPIO1_ST);
-
-	return 0;
-}
-
-static int au1000_gpio1_direction_output(struct gpio_chip *chip,
-					unsigned offset, int value)
-{
-	u32 mask = 1 << offset;
-	struct au1000_gpio_chip *gpch;
-
-	gpch = container_of(chip, struct au1000_gpio_chip, chip);
-
-	writel(mask, gpch->regbase + AU1000_GPIO1_TRI_OUT);
-	au1000_gpio1_set(chip, offset, value);
-
-	return 0;
-}
-
-struct au1000_gpio_chip au1000_gpio_chip[] = {
-	[0] = {
-		.regbase			= (void __iomem *)SYS_BASE,
-		.chip = {
-			.label			= "au1000-gpio1",
-			.direction_input	= au1000_gpio1_direction_input,
-			.direction_output	= au1000_gpio1_direction_output,
-			.get			= au1000_gpio1_get,
-			.set			= au1000_gpio1_set,
-			.base			= 0,
-			.ngpio			= 32,
-		},
-	},
-#if !defined(CONFIG_SOC_AU1000)
-	[1] = {
-		.regbase                        = (void __iomem *)GPIO2_BASE,
-		.chip = {
-			.label                  = "au1000-gpio2",
-			.direction_input        = au1000_gpio2_direction_input,
-			.direction_output       = au1000_gpio2_direction_output,
-			.get                    = au1000_gpio2_get,
-			.set                    = au1000_gpio2_set,
-			.base                   = AU1XXX_GPIO_BASE,
-			.ngpio                  = 32,
-		},
-	},
-#endif
-};
-
-static int __init au1000_gpio_init(void)
-{
-	gpiochip_add(&au1000_gpio_chip[0].chip);
-#if !defined(CONFIG_SOC_AU1000)
-	gpiochip_add(&au1000_gpio_chip[1].chip);
-#endif
-
-	return 0;
-}
-arch_initcall(au1000_gpio_init);
-
diff --git a/arch/mips/alchemy/common/gpiolib-au1000.c b/arch/mips/alchemy/common/gpiolib-au1000.c
new file mode 100644
index 0000000..1bfa91f
--- /dev/null
+++ b/arch/mips/alchemy/common/gpiolib-au1000.c
@@ -0,0 +1,130 @@
+/*
+ *  Copyright (C) 2007-2009, OpenWrt.org, Florian Fainelli <florian@openwrt.org>
+ *  	GPIOLIB support for Au1000, Au1500, Au1100, Au1550 and Au12x0.
+ *
+ *  This program is free software; you can redistribute	 it and/or modify it
+ *  under  the terms of	 the GNU General  Public License as published by the
+ *  Free Software Foundation;  either version 2 of the	License, or (at your
+ *  option) any later version.
+ *
+ *  THIS  SOFTWARE  IS PROVIDED	  ``AS	IS'' AND   ANY	EXPRESS OR IMPLIED
+ *  WARRANTIES,	  INCLUDING, BUT NOT  LIMITED  TO, THE IMPLIED WARRANTIES OF
+ *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
+ *  NO	EVENT  SHALL   THE AUTHOR  BE	 LIABLE FOR ANY	  DIRECT, INDIRECT,
+ *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ *  NOT LIMITED	  TO, PROCUREMENT OF  SUBSTITUTE GOODS	OR SERVICES; LOSS OF
+ *  USE, DATA,	OR PROFITS; OR	BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ *  ANY THEORY OF LIABILITY, WHETHER IN	 CONTRACT, STRICT LIABILITY, OR TORT
+ *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ *  You should have received a copy of the  GNU General Public License along
+ *  with this program; if not, write  to the Free Software Foundation, Inc.,
+ *  675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ *  Notes :
+ * 	au1000 SoC have only one GPIO block : GPIO1
+ * 	Au1100, Au15x0, Au12x0 have a second one : GPIO2
+ */
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/types.h>
+#include <linux/platform_device.h>
+#include <linux/gpio.h>
+
+#include <asm/mach-au1x00/au1000.h>
+#include <asm/mach-au1x00/gpio.h>
+
+#if !defined(CONFIG_SOC_AU1000)
+static int gpio2_get(struct gpio_chip *chip, unsigned offset)
+{
+	return alchemy_gpio2_get_value(offset + ALCHEMY_GPIO2_BASE);
+}
+
+static void gpio2_set(struct gpio_chip *chip, unsigned offset, int value)
+{
+	alchemy_gpio2_set_value(offset + ALCHEMY_GPIO2_BASE, value);
+}
+
+static int gpio2_direction_input(struct gpio_chip *chip, unsigned offset)
+{
+	return alchemy_gpio2_direction_input(offset + ALCHEMY_GPIO2_BASE);
+}
+
+static int gpio2_direction_output(struct gpio_chip *chip, unsigned offset,
+				  int value)
+{
+	return alchemy_gpio2_direction_output(offset + ALCHEMY_GPIO2_BASE,
+						value);
+}
+
+static int gpio2_to_irq(struct gpio_chip *chip, unsigned offset)
+{
+	return alchemy_gpio2_to_irq(offset + ALCHEMY_GPIO2_BASE);
+}
+#endif /* !defined(CONFIG_SOC_AU1000) */
+
+static int gpio1_get(struct gpio_chip *chip, unsigned offset)
+{
+	return alchemy_gpio1_get_value(offset + ALCHEMY_GPIO1_BASE);
+}
+
+static void gpio1_set(struct gpio_chip *chip,
+				unsigned offset, int value)
+{
+	alchemy_gpio1_set_value(offset + ALCHEMY_GPIO1_BASE, value);
+}
+
+static int gpio1_direction_input(struct gpio_chip *chip, unsigned offset)
+{
+	return alchemy_gpio1_direction_input(offset + ALCHEMY_GPIO1_BASE);
+}
+
+static int gpio1_direction_output(struct gpio_chip *chip,
+					unsigned offset, int value)
+{
+	return alchemy_gpio1_direction_output(offset + ALCHEMY_GPIO1_BASE,
+					     value);
+}
+
+static int gpio1_to_irq(struct gpio_chip *chip, unsigned offset)
+{
+	return alchemy_gpio1_to_irq(offset + ALCHEMY_GPIO1_BASE);
+}
+
+struct gpio_chip alchemy_gpio_chip[] = {
+	[0] = {
+		.label			= "alchemy-gpio1",
+		.direction_input	= gpio1_direction_input,
+		.direction_output	= gpio1_direction_output,
+		.get			= gpio1_get,
+		.set			= gpio1_set,
+		.to_irq			= gpio1_to_irq,
+		.base			= ALCHEMY_GPIO1_BASE,
+		.ngpio			= ALCHEMY_GPIO1_NUM,
+	},
+#if !defined(CONFIG_SOC_AU1000)
+	[1] = {
+		.label                  = "alchemy-gpio2",
+		.direction_input        = gpio2_direction_input,
+		.direction_output       = gpio2_direction_output,
+		.get                    = gpio2_get,
+		.set                    = gpio2_set,
+		.to_irq			= gpio2_to_irq,
+		.base                   = ALCHEMY_GPIO2_BASE,
+		.ngpio                  = ALCHEMY_GPIO2_NUM,
+	},
+#endif
+};
+
+static int __init alchemy_gpiolib_init(void)
+{
+	gpiochip_add(&alchemy_gpio_chip[0]);
+#if !defined(CONFIG_SOC_AU1000)
+	gpiochip_add(&alchemy_gpio_chip[1]);
+#endif
+
+	return 0;
+}
+arch_initcall(alchemy_gpiolib_init);
diff --git a/arch/mips/alchemy/common/reset.c b/arch/mips/alchemy/common/reset.c
index 0191c93..4791011 100644
--- a/arch/mips/alchemy/common/reset.c
+++ b/arch/mips/alchemy/common/reset.c
@@ -27,8 +27,9 @@
  *  675 Mass Ave, Cambridge, MA 02139, USA.
  */
 
-#include <asm/cacheflush.h>
+#include <linux/gpio.h>
 
+#include <asm/cacheflush.h>
 #include <asm/mach-au1x00/au1000.h>
 
 void au1000_restart(char *command)
@@ -161,7 +162,7 @@
 #else
 	printk(KERN_NOTICE "\n** You can safely turn off the power\n");
 #ifdef CONFIG_MIPS_MIRAGE
-	au_writel((1 << 26) | (1 << 10), GPIO2_OUTPUT);
+	gpio_direction_output(210, 1);
 #endif
 #ifdef CONFIG_MIPS_DB1200
 	au_writew(au_readw(0xB980001C) | (1 << 14), 0xB980001C);
diff --git a/arch/mips/alchemy/devboards/db1x00/board_setup.c b/arch/mips/alchemy/devboards/db1x00/board_setup.c
index a75ffbf..de30d8e 100644
--- a/arch/mips/alchemy/devboards/db1x00/board_setup.c
+++ b/arch/mips/alchemy/devboards/db1x00/board_setup.c
@@ -27,6 +27,7 @@
  *  675 Mass Ave, Cambridge, MA 02139, USA.
  */
 
+#include <linux/gpio.h>
 #include <linux/init.h>
 
 #include <asm/mach-au1x00/au1000.h>
@@ -94,12 +95,12 @@
 #endif
 	bcsr->pcmcia = 0x0000; /* turn off PCMCIA power */
 
-#ifdef CONFIG_MIPS_MIRAGE
 	/* Enable GPIO[31:0] inputs */
-	au_writel(0, SYS_PININPUTEN);
+	alchemy_gpio1_input_enable();
 
-	/* GPIO[20] is output, tristate the other input primary GPIOs */
-	au_writel(~(1 << 20), SYS_TRIOUTCLR);
+#ifdef CONFIG_MIPS_MIRAGE
+	/* GPIO[20] is output */
+	alchemy_gpio_direction_output(20, 0);
 
 	/* Set GPIO[210:208] instead of SSI_0 */
 	pin_func = au_readl(SYS_PINFUNC) | SYS_PF_S0;
@@ -118,8 +119,7 @@
 	 * Enable speaker amplifier.  This should
 	 * be part of the audio driver.
 	 */
-	au_writel(au_readl(GPIO2_DIR) | 0x200, GPIO2_DIR);
-	au_writel(0x02000200, GPIO2_OUTPUT);
+	alchemy_gpio_direction_output(209, 1);
 #endif
 
 	au_sync();
diff --git a/arch/mips/alchemy/devboards/pb1000/board_setup.c b/arch/mips/alchemy/devboards/pb1000/board_setup.c
index aed2fde..cd27354 100644
--- a/arch/mips/alchemy/devboards/pb1000/board_setup.c
+++ b/arch/mips/alchemy/devboards/pb1000/board_setup.c
@@ -24,6 +24,7 @@
  */
 
 #include <linux/delay.h>
+#include <linux/gpio.h>
 #include <linux/init.h>
 #include <linux/interrupt.h>
 #include <asm/mach-au1x00/au1000.h>
@@ -130,8 +131,11 @@
 	pin_func |= SYS_PF_USB;
 
 	au_writel(pin_func, SYS_PINFUNC);
-	au_writel(0x2800, SYS_TRIOUTCLR);
-	au_writel(0x0030, SYS_OUTPUTCLR);
+
+	alchemy_gpio_direction_input(11);
+	alchemy_gpio_direction_input(13);
+	alchemy_gpio_direction_output(4, 0);
+	alchemy_gpio_direction_output(5, 0);
 #endif /* defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE) */
 
 	/* Make GPIO 15 an input (for interrupt line) */
@@ -140,7 +144,7 @@
 	pin_func |= SYS_PF_I2S;
 	au_writel(pin_func, SYS_PINFUNC);
 
-	au_writel(0x8000, SYS_TRIOUTCLR);
+	alchemy_gpio_direction_input(15);
 
 	static_cfg0 = au_readl(MEM_STCFG0) & ~0xc00;
 	au_writel(static_cfg0, MEM_STCFG0);
diff --git a/arch/mips/alchemy/devboards/pb1100/board_setup.c b/arch/mips/alchemy/devboards/pb1100/board_setup.c
index 4df57fa..6126308 100644
--- a/arch/mips/alchemy/devboards/pb1100/board_setup.c
+++ b/arch/mips/alchemy/devboards/pb1100/board_setup.c
@@ -23,6 +23,7 @@
  *  675 Mass Ave, Cambridge, MA 02139, USA.
  */
 
+#include <linux/gpio.h>
 #include <linux/init.h>
 #include <linux/delay.h>
 #include <linux/interrupt.h>
@@ -88,7 +89,7 @@
 
 	/* Set AUX clock to 12 MHz * 8 = 96 MHz */
 	au_writel(8, SYS_AUXPLL);
-	au_writel(0, SYS_PININPUTEN);
+	alchemy_gpio1_input_enable();
 	udelay(100);
 
 #if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
diff --git a/arch/mips/alchemy/devboards/pb1500/board_setup.c b/arch/mips/alchemy/devboards/pb1500/board_setup.c
index fed3b09..d7a5656 100644
--- a/arch/mips/alchemy/devboards/pb1500/board_setup.c
+++ b/arch/mips/alchemy/devboards/pb1500/board_setup.c
@@ -23,8 +23,9 @@
  *  675 Mass Ave, Cambridge, MA 02139, USA.
  */
 
-#include <linux/init.h>
 #include <linux/delay.h>
+#include <linux/gpio.h>
+#include <linux/init.h>
 #include <linux/interrupt.h>
 
 #include <asm/mach-au1x00/au1000.h>
@@ -90,11 +91,12 @@
 	au_writel(0, SYS_PINSTATERD);
 	udelay(100);
 
-#if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
-
 	/* GPIO201 is input for PCMCIA card detect */
 	/* GPIO203 is input for PCMCIA interrupt request */
-	au_writel(au_readl(GPIO2_DIR) & ~((1 << 1) | (1 << 3)), GPIO2_DIR);
+	alchemy_gpio_direction_input(201);
+	alchemy_gpio_direction_input(203);
+
+#if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
 
 	/* Zero and disable FREQ2 */
 	sys_freqctrl = au_readl(SYS_FREQCTRL0);
diff --git a/arch/mips/alchemy/devboards/pm.c b/arch/mips/alchemy/devboards/pm.c
index d5eb9c3..632f986 100644
--- a/arch/mips/alchemy/devboards/pm.c
+++ b/arch/mips/alchemy/devboards/pm.c
@@ -9,6 +9,7 @@
 #include <linux/suspend.h>
 #include <linux/sysfs.h>
 #include <asm/mach-au1x00/au1000.h>
+#include <asm/mach-au1x00/gpio.h>
 
 /*
  * Generic suspend userspace interface for Alchemy development boards.
@@ -26,7 +27,7 @@
 static int db1x_pm_enter(suspend_state_t state)
 {
 	/* enable GPIO based wakeup */
-	au_writel(1, SYS_PININPUTEN);
+	alchemy_gpio1_input_enable();
 
 	/* clear and setup wake cause and source */
 	au_writel(0, SYS_WAKEMSK);
diff --git a/arch/mips/alchemy/mtx-1/board_setup.c b/arch/mips/alchemy/mtx-1/board_setup.c
index 8ed1ae1..cc32c69 100644
--- a/arch/mips/alchemy/mtx-1/board_setup.c
+++ b/arch/mips/alchemy/mtx-1/board_setup.c
@@ -28,6 +28,7 @@
  *  675 Mass Ave, Cambridge, MA 02139, USA.
  */
 
+#include <linux/gpio.h>
 #include <linux/init.h>
 
 #include <asm/mach-au1x00/au1000.h>
@@ -55,10 +56,11 @@
 	}
 #endif
 
+	alchemy_gpio2_enable();
+
 #if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
 	/* Enable USB power switch */
-	au_writel(au_readl(GPIO2_DIR) | 0x10, GPIO2_DIR);
-	au_writel(0x100000, GPIO2_OUTPUT);
+	alchemy_gpio_direction_output(204, 0);
 #endif /* defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE) */
 
 #ifdef CONFIG_PCI
@@ -74,14 +76,14 @@
 
 	/* Initialize GPIO */
 	au_writel(0xFFFFFFFF, SYS_TRIOUTCLR);
-	au_writel(0x00000001, SYS_OUTPUTCLR); /* set M66EN (PCI 66MHz) to OFF */
-	au_writel(0x00000008, SYS_OUTPUTSET); /* set PCI CLKRUN# to OFF */
-	au_writel(0x00000002, SYS_OUTPUTSET); /* set EXT_IO3 ON */
-	au_writel(0x00000020, SYS_OUTPUTCLR); /* set eth PHY TX_ER to OFF */
+	alchemy_gpio_direction_output(0, 0);	/* Disable M66EN (PCI 66MHz) */
+	alchemy_gpio_direction_output(3, 1);	/* Disable PCI CLKRUN# */
+	alchemy_gpio_direction_output(1, 1);	/* Enable EXT_IO3 */
+	alchemy_gpio_direction_output(5, 0);	/* Disable eth PHY TX_ER */
 
 	/* Enable LED and set it to green */
-	au_writel(au_readl(GPIO2_DIR) | 0x1800, GPIO2_DIR);
-	au_writel(0x18000800, GPIO2_OUTPUT);
+	alchemy_gpio_direction_output(211, 1);	/* green on */
+	alchemy_gpio_direction_output(212, 0);	/* red off */
 
 	board_pci_idsel = mtx1_pci_idsel;
 
@@ -101,10 +103,10 @@
 
 	if (assert && devsel != 0)
 		/* Suppress signal to Cardbus */
-		au_writel(0x00000002, SYS_OUTPUTCLR); /* set EXT_IO3 OFF */
+		gpio_set_value(1, 0);	/* set EXT_IO3 OFF */
 	else
-		au_writel(0x00000002, SYS_OUTPUTSET); /* set EXT_IO3 ON */
+		gpio_set_value(1, 1);	/* set EXT_IO3 ON */
+
 	au_sync_udelay(1);
 	return 1;
 }
-
diff --git a/arch/mips/alchemy/xxs1500/board_setup.c b/arch/mips/alchemy/xxs1500/board_setup.c
index a2634fa..4de2d48 100644
--- a/arch/mips/alchemy/xxs1500/board_setup.c
+++ b/arch/mips/alchemy/xxs1500/board_setup.c
@@ -23,6 +23,7 @@
  *  675 Mass Ave, Cambridge, MA 02139, USA.
  */
 
+#include <linux/gpio.h>
 #include <linux/init.h>
 #include <linux/delay.h>
 
@@ -50,6 +51,9 @@
 	}
 #endif
 
+	alchemy_gpio1_input_enable();
+	alchemy_gpio2_enable();
+
 	/* Set multiple use pins (UART3/GPIO) to UART (it's used as UART too) */
 	pin_func  = au_readl(SYS_PINFUNC) & ~SYS_PF_UR3;
 	pin_func |= SYS_PF_UR3;
@@ -65,20 +69,19 @@
 	au_writel(0x01, UART3_ADDR + UART_MCR); /* UART_MCR_DTR is 0x01??? */
 
 #ifdef CONFIG_PCMCIA_XXS1500
-	/* Setup PCMCIA signals */
-	au_writel(0, SYS_PININPUTEN);
-
 	/* GPIO 0, 1, and 4 are inputs */
-	au_writel(1 | (1 << 1) | (1 << 4), SYS_TRIOUTCLR);
+	alchemy_gpio_direction_input(0);
+	alchemy_gpio_direction_input(1);
+	alchemy_gpio_direction_input(4);
 
-	/* Enable GPIO2 if not already enabled */
-	au_writel(1, GPIO2_ENABLE);
 	/* GPIO2 208/9/10/11 are inputs */
-	au_writel((1 << 8) | (1 << 9) | (1 << 10) | (1 << 11), GPIO2_DIR);
+	alchemy_gpio_direction_input(208);
+	alchemy_gpio_direction_input(209);
+	alchemy_gpio_direction_input(210);
+	alchemy_gpio_direction_input(211);
 
 	/* Turn off power */
-	au_writel((au_readl(GPIO2_PINSTATE) & ~(1 << 14)) | (1 << 30),
-		  GPIO2_OUTPUT);
+	alchemy_gpio_direction_output(214, 0);
 #endif
 
 #ifdef CONFIG_PCI
diff --git a/arch/mips/cavium-octeon/Makefile b/arch/mips/cavium-octeon/Makefile
index d6903c3..7c0528b 100644
--- a/arch/mips/cavium-octeon/Makefile
+++ b/arch/mips/cavium-octeon/Makefile
@@ -14,5 +14,9 @@
 obj-y += octeon-memcpy.o
 
 obj-$(CONFIG_SMP)                     += smp.o
+obj-$(CONFIG_PCI)                     += pci-common.o
+obj-$(CONFIG_PCI)                     += pci.o
+obj-$(CONFIG_PCI)                     += pcie.o
+obj-$(CONFIG_PCI_MSI)                 += msi.o
 
 EXTRA_CFLAGS += -Werror
diff --git a/arch/mips/cavium-octeon/dma-octeon.c b/arch/mips/cavium-octeon/dma-octeon.c
index 01b1ef9..627c162 100644
--- a/arch/mips/cavium-octeon/dma-octeon.c
+++ b/arch/mips/cavium-octeon/dma-octeon.c
@@ -13,20 +13,327 @@
  */
 #include <linux/types.h>
 #include <linux/mm.h>
+#include <linux/module.h>
+#include <linux/string.h>
+#include <linux/dma-mapping.h>
+#include <linux/platform_device.h>
+#include <linux/scatterlist.h>
+
+#include <linux/cache.h>
+#include <linux/io.h>
+
+#include <asm/octeon/octeon.h>
+#include <asm/octeon/cvmx-npi-defs.h>
+#include <asm/octeon/cvmx-pci-defs.h>
 
 #include <dma-coherence.h>
 
+#ifdef CONFIG_PCI
+#include "pci-common.h"
+#endif
+
+#define BAR2_PCI_ADDRESS 0x8000000000ul
+
+struct bar1_index_state {
+	int16_t ref_count;	/* Number of PCI mappings using this index */
+	uint16_t address_bits;	/* Upper bits of physical address. This is
+				   shifted 22 bits */
+};
+
+#ifdef CONFIG_PCI
+static DEFINE_SPINLOCK(bar1_lock);
+static struct bar1_index_state bar1_state[32];
+#endif
+
 dma_addr_t octeon_map_dma_mem(struct device *dev, void *ptr, size_t size)
 {
+#ifndef CONFIG_PCI
 	/* Without PCI/PCIe this function can be called for Octeon internal
 	   devices such as USB. These devices all support 64bit addressing */
 	mb();
 	return virt_to_phys(ptr);
+#else
+	unsigned long flags;
+	uint64_t dma_mask;
+	int64_t start_index;
+	dma_addr_t result = -1;
+	uint64_t physical = virt_to_phys(ptr);
+	int64_t index;
+
+	mb();
+	/*
+	 * Use the DMA masks to determine the allowed memory
+	 * region. For us it doesn't limit the actual memory, just the
+	 * address visible over PCI.  Devices with limits need to use
+	 * lower indexed Bar1 entries.
+	 */
+	if (dev) {
+		dma_mask = dev->coherent_dma_mask;
+		if (dev->dma_mask)
+			dma_mask = *dev->dma_mask;
+	} else {
+		dma_mask = 0xfffffffful;
+	}
+
+	/*
+	 * Platform devices, such as the internal USB, skip all
+	 * translation and use Octeon physical addresses directly.
+	 */
+	if (!dev || dev->bus == &platform_bus_type)
+		return physical;
+
+	switch (octeon_dma_bar_type) {
+	case OCTEON_DMA_BAR_TYPE_PCIE:
+		if (unlikely(physical < (16ul << 10)))
+			panic("dma_map_single: Not allowed to map first 16KB."
+			      " It interferes with BAR0 special area\n");
+		else if ((physical + size >= (256ul << 20)) &&
+			 (physical < (512ul << 20)))
+			panic("dma_map_single: Not allowed to map bootbus\n");
+		else if ((physical + size >= 0x400000000ull) &&
+			 physical < 0x410000000ull)
+			panic("dma_map_single: "
+			      "Attempt to map illegal memory address 0x%llx\n",
+			      physical);
+		else if (physical >= 0x420000000ull)
+			panic("dma_map_single: "
+			      "Attempt to map illegal memory address 0x%llx\n",
+			      physical);
+		else if ((physical + size >=
+			  (4ull<<30) - (OCTEON_PCI_BAR1_HOLE_SIZE<<20))
+			 && physical < (4ull<<30))
+			pr_warning("dma_map_single: Warning: "
+				   "Mapping memory address that might "
+				   "conflict with devices 0x%llx-0x%llx\n",
+				   physical, physical+size-1);
+		/* The 2nd 256MB is mapped at 256<<20 instead of 0x410000000 */
+		if ((physical >= 0x410000000ull) && physical < 0x420000000ull)
+			result = physical - 0x400000000ull;
+		else
+			result = physical;
+		if (((result+size-1) & dma_mask) != result+size-1)
+			panic("dma_map_single: Attempt to map address "
+			      "0x%llx-0x%llx, which can't be accessed "
+			      "according to the dma mask 0x%llx\n",
+			      physical, physical+size-1, dma_mask);
+		goto done;
+
+	case OCTEON_DMA_BAR_TYPE_BIG:
+#ifdef CONFIG_64BIT
+		/* If the device supports 64bit addressing, then use BAR2 */
+		if (dma_mask > BAR2_PCI_ADDRESS) {
+			result = physical + BAR2_PCI_ADDRESS;
+			goto done;
+		}
+#endif
+		if (unlikely(physical < (4ul << 10))) {
+			panic("dma_map_single: Not allowed to map first 4KB. "
+			      "It interferes with BAR0 special area\n");
+		} else if (physical < (256ul << 20)) {
+			if (unlikely(physical + size > (256ul << 20)))
+				panic("dma_map_single: Requested memory spans "
+				      "Bar0 0:256MB and bootbus\n");
+			result = physical;
+			goto done;
+		} else if (unlikely(physical < (512ul << 20))) {
+			panic("dma_map_single: Not allowed to map bootbus\n");
+		} else if (physical < (2ul << 30)) {
+			if (unlikely(physical + size > (2ul << 30)))
+				panic("dma_map_single: Requested memory spans "
+				      "Bar0 512MB:2GB and BAR1\n");
+			result = physical;
+			goto done;
+		} else if (physical < (2ul << 30) + (128 << 20)) {
+			/* Fall through */
+		} else if (physical <
+			   (4ul << 30) - (OCTEON_PCI_BAR1_HOLE_SIZE << 20)) {
+			if (unlikely
+			    (physical + size >
+			     (4ul << 30) - (OCTEON_PCI_BAR1_HOLE_SIZE << 20)))
+				panic("dma_map_single: Requested memory "
+				      "extends past Bar1 (4GB-%luMB)\n",
+				      OCTEON_PCI_BAR1_HOLE_SIZE);
+			result = physical;
+			goto done;
+		} else if ((physical >= 0x410000000ull) &&
+			   (physical < 0x420000000ull)) {
+			if (unlikely(physical + size > 0x420000000ull))
+				panic("dma_map_single: Requested memory spans "
+				      "non existant memory\n");
+			/* BAR0 fixed mapping 256MB:512MB ->
+			 * 16GB+256MB:16GB+512MB */
+			result = physical - 0x400000000ull;
+			goto done;
+		} else {
+			/* Continued below switch statement */
+		}
+		break;
+
+	case OCTEON_DMA_BAR_TYPE_SMALL:
+#ifdef CONFIG_64BIT
+		/* If the device supports 64bit addressing, then use BAR2 */
+		if (dma_mask > BAR2_PCI_ADDRESS) {
+			result = physical + BAR2_PCI_ADDRESS;
+			goto done;
+		}
+#endif
+		/* Continued below switch statement */
+		break;
+
+	default:
+		panic("dma_map_single: Invalid octeon_dma_bar_type\n");
+	}
+
+	/* Don't allow mapping to span multiple Bar entries. The hardware guys
+	   won't guarantee that DMA across boards work */
+	if (unlikely((physical >> 22) != ((physical + size - 1) >> 22)))
+		panic("dma_map_single: "
+		      "Requested memory spans more than one Bar1 entry\n");
+
+	if (octeon_dma_bar_type == OCTEON_DMA_BAR_TYPE_BIG)
+		start_index = 31;
+	else if (unlikely(dma_mask < (1ul << 27)))
+		start_index = (dma_mask >> 22);
+	else
+		start_index = 31;
+
+	/* Only one processor can access the Bar register at once */
+	spin_lock_irqsave(&bar1_lock, flags);
+
+	/* Look through Bar1 for existing mapping that will work */
+	for (index = start_index; index >= 0; index--) {
+		if ((bar1_state[index].address_bits == physical >> 22) &&
+		    (bar1_state[index].ref_count)) {
+			/* An existing mapping will work, use it */
+			bar1_state[index].ref_count++;
+			if (unlikely(bar1_state[index].ref_count < 0))
+				panic("dma_map_single: "
+				      "Bar1[%d] reference count overflowed\n",
+				      (int) index);
+			result = (index << 22) | (physical & ((1 << 22) - 1));
+			/* Large BAR1 is offset at 2GB */
+			if (octeon_dma_bar_type == OCTEON_DMA_BAR_TYPE_BIG)
+				result += 2ul << 30;
+			goto done_unlock;
+		}
+	}
+
+	/* No existing mappings, look for a free entry */
+	for (index = start_index; index >= 0; index--) {
+		if (unlikely(bar1_state[index].ref_count == 0)) {
+			union cvmx_pci_bar1_indexx bar1_index;
+			/* We have a free entry, use it */
+			bar1_state[index].ref_count = 1;
+			bar1_state[index].address_bits = physical >> 22;
+			bar1_index.u32 = 0;
+			/* Address bits[35:22] sent to L2C */
+			bar1_index.s.addr_idx = physical >> 22;
+			/* Don't put PCI accesses in L2. */
+			bar1_index.s.ca = 1;
+			/* Endian Swap Mode */
+			bar1_index.s.end_swp = 1;
+			/* Set '1' when the selected address range is valid. */
+			bar1_index.s.addr_v = 1;
+			octeon_npi_write32(CVMX_NPI_PCI_BAR1_INDEXX(index),
+					   bar1_index.u32);
+			/* An existing mapping will work, use it */
+			result = (index << 22) | (physical & ((1 << 22) - 1));
+			/* Large BAR1 is offset at 2GB */
+			if (octeon_dma_bar_type == OCTEON_DMA_BAR_TYPE_BIG)
+				result += 2ul << 30;
+			goto done_unlock;
+		}
+	}
+
+	pr_err("dma_map_single: "
+	       "Can't find empty BAR1 index for physical mapping 0x%llx\n",
+	       (unsigned long long) physical);
+
+done_unlock:
+	spin_unlock_irqrestore(&bar1_lock, flags);
+done:
+	pr_debug("dma_map_single 0x%llx->0x%llx\n", physical, result);
+	return result;
+#endif
 }
 
 void octeon_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr)
 {
-	/* Without PCI/PCIe this function can be called for Octeon internal
-	 * devices such as USB. These devices all support 64bit addressing */
+#ifndef CONFIG_PCI
+	/*
+	 * Without PCI/PCIe this function can be called for Octeon internal
+	 * devices such as USB. These devices all support 64bit addressing.
+	 */
 	return;
+#else
+	unsigned long flags;
+	uint64_t index;
+
+	/*
+	 * Platform devices, such as the internal USB, skip all
+	 * translation and use Octeon physical addresses directly.
+	 */
+	if (dev->bus == &platform_bus_type)
+		return;
+
+	switch (octeon_dma_bar_type) {
+	case OCTEON_DMA_BAR_TYPE_PCIE:
+		/* Nothing to do, all mappings are static */
+		goto done;
+
+	case OCTEON_DMA_BAR_TYPE_BIG:
+#ifdef CONFIG_64BIT
+		/* Nothing to do for addresses using BAR2 */
+		if (dma_addr >= BAR2_PCI_ADDRESS)
+			goto done;
+#endif
+		if (unlikely(dma_addr < (4ul << 10)))
+			panic("dma_unmap_single: Unexpect DMA address 0x%llx\n",
+			      dma_addr);
+		else if (dma_addr < (2ul << 30))
+			/* Nothing to do for addresses using BAR0 */
+			goto done;
+		else if (dma_addr < (2ul << 30) + (128ul << 20))
+			/* Need to unmap, fall through */
+			index = (dma_addr - (2ul << 30)) >> 22;
+		else if (dma_addr <
+			 (4ul << 30) - (OCTEON_PCI_BAR1_HOLE_SIZE << 20))
+			goto done;	/* Nothing to do for the rest of BAR1 */
+		else
+			panic("dma_unmap_single: Unexpect DMA address 0x%llx\n",
+			      dma_addr);
+		/* Continued below switch statement */
+		break;
+
+	case OCTEON_DMA_BAR_TYPE_SMALL:
+#ifdef CONFIG_64BIT
+		/* Nothing to do for addresses using BAR2 */
+		if (dma_addr >= BAR2_PCI_ADDRESS)
+			goto done;
+#endif
+		index = dma_addr >> 22;
+		/* Continued below switch statement */
+		break;
+
+	default:
+		panic("dma_unmap_single: Invalid octeon_dma_bar_type\n");
+	}
+
+	if (unlikely(index > 31))
+		panic("dma_unmap_single: "
+		      "Attempt to unmap an invalid address (0x%llx)\n",
+		      dma_addr);
+
+	spin_lock_irqsave(&bar1_lock, flags);
+	bar1_state[index].ref_count--;
+	if (bar1_state[index].ref_count == 0)
+		octeon_npi_write32(CVMX_NPI_PCI_BAR1_INDEXX(index), 0);
+	else if (unlikely(bar1_state[index].ref_count < 0))
+		panic("dma_unmap_single: Bar1[%u] reference count < 0\n",
+		      (int) index);
+	spin_unlock_irqrestore(&bar1_lock, flags);
+done:
+	pr_debug("dma_unmap_single 0x%llx\n", dma_addr);
+	return;
+#endif
 }
diff --git a/arch/mips/cavium-octeon/executive/Makefile b/arch/mips/cavium-octeon/executive/Makefile
index 80d6cb2..2fd66db 100644
--- a/arch/mips/cavium-octeon/executive/Makefile
+++ b/arch/mips/cavium-octeon/executive/Makefile
@@ -11,3 +11,4 @@
 
 obj-y += cvmx-bootmem.o cvmx-l2c.o cvmx-sysinfo.o octeon-model.o
 
+obj-$(CONFIG_PCI) += cvmx-helper-errata.o cvmx-helper-jtag.o
diff --git a/arch/mips/cavium-octeon/executive/cvmx-bootmem.c b/arch/mips/cavium-octeon/executive/cvmx-bootmem.c
index 4f5a08b..25666da 100644
--- a/arch/mips/cavium-octeon/executive/cvmx-bootmem.c
+++ b/arch/mips/cavium-octeon/executive/cvmx-bootmem.c
@@ -31,6 +31,7 @@
  */
 
 #include <linux/kernel.h>
+#include <linux/module.h>
 
 #include <asm/octeon/cvmx.h>
 #include <asm/octeon/cvmx-spinlock.h>
@@ -97,6 +98,33 @@
 	return cvmx_bootmem_alloc_range(size, alignment, 0, 0);
 }
 
+void *cvmx_bootmem_alloc_named_range(uint64_t size, uint64_t min_addr,
+				     uint64_t max_addr, uint64_t align,
+				     char *name)
+{
+	int64_t addr;
+
+	addr = cvmx_bootmem_phy_named_block_alloc(size, min_addr, max_addr,
+						  align, name, 0);
+	if (addr >= 0)
+		return cvmx_phys_to_ptr(addr);
+	else
+		return NULL;
+}
+
+void *cvmx_bootmem_alloc_named_address(uint64_t size, uint64_t address,
+				       char *name)
+{
+    return cvmx_bootmem_alloc_named_range(size, address, address + size,
+					  0, name);
+}
+
+void *cvmx_bootmem_alloc_named(uint64_t size, uint64_t alignment, char *name)
+{
+    return cvmx_bootmem_alloc_named_range(size, 0, 0, alignment, name);
+}
+EXPORT_SYMBOL(cvmx_bootmem_alloc_named);
+
 int cvmx_bootmem_free_named(char *name)
 {
 	return cvmx_bootmem_phy_named_block_free(name, 0);
@@ -106,6 +134,7 @@
 {
 	return cvmx_bootmem_phy_named_block_find(name, 0);
 }
+EXPORT_SYMBOL(cvmx_bootmem_find_named_block);
 
 void cvmx_bootmem_lock(void)
 {
@@ -584,3 +613,78 @@
 	cvmx_bootmem_unlock();
 	return named_block_ptr != NULL;	/* 0 on failure, 1 on success */
 }
+
+int64_t cvmx_bootmem_phy_named_block_alloc(uint64_t size, uint64_t min_addr,
+					   uint64_t max_addr,
+					   uint64_t alignment,
+					   char *name,
+					   uint32_t flags)
+{
+	int64_t addr_allocated;
+	struct cvmx_bootmem_named_block_desc *named_block_desc_ptr;
+
+#ifdef DEBUG
+	cvmx_dprintf("cvmx_bootmem_phy_named_block_alloc: size: 0x%llx, min: "
+		     "0x%llx, max: 0x%llx, align: 0x%llx, name: %s\n",
+		     (unsigned long long)size,
+		     (unsigned long long)min_addr,
+		     (unsigned long long)max_addr,
+		     (unsigned long long)alignment,
+		     name);
+#endif
+	if (cvmx_bootmem_desc->major_version != 3) {
+		cvmx_dprintf("ERROR: Incompatible bootmem descriptor version: "
+			     "%d.%d at addr: %p\n",
+			     (int)cvmx_bootmem_desc->major_version,
+			     (int)cvmx_bootmem_desc->minor_version,
+			     cvmx_bootmem_desc);
+		return -1;
+	}
+
+	/*
+	 * Take lock here, as name lookup/block alloc/name add need to
+	 * be atomic.
+	 */
+	if (!(flags & CVMX_BOOTMEM_FLAG_NO_LOCKING))
+		cvmx_spinlock_lock((cvmx_spinlock_t *)&(cvmx_bootmem_desc->lock));
+
+	/* Get pointer to first available named block descriptor */
+	named_block_desc_ptr =
+		cvmx_bootmem_phy_named_block_find(NULL,
+						  flags | CVMX_BOOTMEM_FLAG_NO_LOCKING);
+
+	/*
+	 * Check to see if name already in use, return error if name
+	 * not available or no more room for blocks.
+	 */
+	if (cvmx_bootmem_phy_named_block_find(name,
+					      flags | CVMX_BOOTMEM_FLAG_NO_LOCKING) || !named_block_desc_ptr) {
+		if (!(flags & CVMX_BOOTMEM_FLAG_NO_LOCKING))
+			cvmx_spinlock_unlock((cvmx_spinlock_t *)&(cvmx_bootmem_desc->lock));
+		return -1;
+	}
+
+
+	/*
+	 * Round size up to mult of minimum alignment bytes We need
+	 * the actual size allocated to allow for blocks to be
+	 * coallesced when they are freed.  The alloc routine does the
+	 * same rounding up on all allocations.
+	 */
+	size = __ALIGN_MASK(size, (CVMX_BOOTMEM_ALIGNMENT_SIZE - 1));
+
+	addr_allocated = cvmx_bootmem_phy_alloc(size, min_addr, max_addr,
+						alignment,
+						flags | CVMX_BOOTMEM_FLAG_NO_LOCKING);
+	if (addr_allocated >= 0) {
+		named_block_desc_ptr->base_addr = addr_allocated;
+		named_block_desc_ptr->size = size;
+		strncpy(named_block_desc_ptr->name, name,
+			cvmx_bootmem_desc->named_block_name_len);
+		named_block_desc_ptr->name[cvmx_bootmem_desc->named_block_name_len - 1] = 0;
+	}
+
+	if (!(flags & CVMX_BOOTMEM_FLAG_NO_LOCKING))
+		cvmx_spinlock_unlock((cvmx_spinlock_t *)&(cvmx_bootmem_desc->lock));
+	return addr_allocated;
+}
diff --git a/arch/mips/cavium-octeon/executive/cvmx-helper-errata.c b/arch/mips/cavium-octeon/executive/cvmx-helper-errata.c
new file mode 100644
index 0000000..868659e
--- /dev/null
+++ b/arch/mips/cavium-octeon/executive/cvmx-helper-errata.c
@@ -0,0 +1,73 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ *
+ * Fixes and workaround for Octeon chip errata. This file
+ * contains functions called by cvmx-helper to workaround known
+ * chip errata. For the most part, code doesn't need to call
+ * these functions directly.
+ *
+ */
+#include <linux/module.h>
+
+#include <asm/octeon/octeon.h>
+
+#include <asm/octeon/cvmx-helper-jtag.h>
+
+/**
+ * Due to errata G-720, the 2nd order CDR circuit on CN52XX pass
+ * 1 doesn't work properly. The following code disables 2nd order
+ * CDR for the specified QLM.
+ *
+ * @qlm:    QLM to disable 2nd order CDR for.
+ */
+void __cvmx_helper_errata_qlm_disable_2nd_order_cdr(int qlm)
+{
+	int lane;
+	cvmx_helper_qlm_jtag_init();
+	/* We need to load all four lanes of the QLM, a total of 1072 bits */
+	for (lane = 0; lane < 4; lane++) {
+		/*
+		 * Each lane has 268 bits. We need to set
+		 * cfg_cdr_incx<67:64> = 3 and cfg_cdr_secord<77> =
+		 * 1. All other bits are zero. Bits go in LSB first,
+		 * so start off with the zeros for bits <63:0>.
+		 */
+		cvmx_helper_qlm_jtag_shift_zeros(qlm, 63 - 0 + 1);
+		/* cfg_cdr_incx<67:64>=3 */
+		cvmx_helper_qlm_jtag_shift(qlm, 67 - 64 + 1, 3);
+		/* Zeros for bits <76:68> */
+		cvmx_helper_qlm_jtag_shift_zeros(qlm, 76 - 68 + 1);
+		/* cfg_cdr_secord<77>=1 */
+		cvmx_helper_qlm_jtag_shift(qlm, 77 - 77 + 1, 1);
+		/* Zeros for bits <267:78> */
+		cvmx_helper_qlm_jtag_shift_zeros(qlm, 267 - 78 + 1);
+	}
+	cvmx_helper_qlm_jtag_update(qlm);
+}
+EXPORT_SYMBOL(__cvmx_helper_errata_qlm_disable_2nd_order_cdr);
diff --git a/arch/mips/cavium-octeon/executive/cvmx-helper-jtag.c b/arch/mips/cavium-octeon/executive/cvmx-helper-jtag.c
new file mode 100644
index 0000000..c1c5489
--- /dev/null
+++ b/arch/mips/cavium-octeon/executive/cvmx-helper-jtag.c
@@ -0,0 +1,144 @@
+
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ *
+ * Helper utilities for qlm_jtag.
+ *
+ */
+
+#include <asm/octeon/octeon.h>
+#include <asm/octeon/cvmx-helper-jtag.h>
+
+
+/**
+ * Initialize the internal QLM JTAG logic to allow programming
+ * of the JTAG chain by the cvmx_helper_qlm_jtag_*() functions.
+ * These functions should only be used at the direction of Cavium
+ * Networks. Programming incorrect values into the JTAG chain
+ * can cause chip damage.
+ */
+void cvmx_helper_qlm_jtag_init(void)
+{
+	union cvmx_ciu_qlm_jtgc jtgc;
+	uint32_t clock_div = 0;
+	uint32_t divisor = cvmx_sysinfo_get()->cpu_clock_hz / (25 * 1000000);
+	divisor = (divisor - 1) >> 2;
+	/* Convert the divisor into a power of 2 shift */
+	while (divisor) {
+		clock_div++;
+		divisor = divisor >> 1;
+	}
+
+	/*
+	 * Clock divider for QLM JTAG operations.  eclk is divided by
+	 * 2^(CLK_DIV + 2)
+	 */
+	jtgc.u64 = 0;
+	jtgc.s.clk_div = clock_div;
+	jtgc.s.mux_sel = 0;
+	if (OCTEON_IS_MODEL(OCTEON_CN52XX))
+		jtgc.s.bypass = 0x3;
+	else
+		jtgc.s.bypass = 0xf;
+	cvmx_write_csr(CVMX_CIU_QLM_JTGC, jtgc.u64);
+	cvmx_read_csr(CVMX_CIU_QLM_JTGC);
+}
+
+/**
+ * Write up to 32bits into the QLM jtag chain. Bits are shifted
+ * into the MSB and out the LSB, so you should shift in the low
+ * order bits followed by the high order bits. The JTAG chain is
+ * 4 * 268 bits long, or 1072.
+ *
+ * @qlm:    QLM to shift value into
+ * @bits:   Number of bits to shift in (1-32).
+ * @data:   Data to shift in. Bit 0 enters the chain first, followed by
+ *               bit 1, etc.
+ *
+ * Returns The low order bits of the JTAG chain that shifted out of the
+ *         circle.
+ */
+uint32_t cvmx_helper_qlm_jtag_shift(int qlm, int bits, uint32_t data)
+{
+	union cvmx_ciu_qlm_jtgd jtgd;
+	jtgd.u64 = 0;
+	jtgd.s.shift = 1;
+	jtgd.s.shft_cnt = bits - 1;
+	jtgd.s.shft_reg = data;
+	if (!OCTEON_IS_MODEL(OCTEON_CN56XX_PASS1_X))
+		jtgd.s.select = 1 << qlm;
+	cvmx_write_csr(CVMX_CIU_QLM_JTGD, jtgd.u64);
+	do {
+		jtgd.u64 = cvmx_read_csr(CVMX_CIU_QLM_JTGD);
+	} while (jtgd.s.shift);
+	return jtgd.s.shft_reg >> (32 - bits);
+}
+
+/**
+ * Shift long sequences of zeros into the QLM JTAG chain. It is
+ * common to need to shift more than 32 bits of zeros into the
+ * chain. This function is a convience wrapper around
+ * cvmx_helper_qlm_jtag_shift() to shift more than 32 bits of
+ * zeros at a time.
+ *
+ * @qlm:    QLM to shift zeros into
+ * @bits:
+ */
+void cvmx_helper_qlm_jtag_shift_zeros(int qlm, int bits)
+{
+	while (bits > 0) {
+		int n = bits;
+		if (n > 32)
+			n = 32;
+		cvmx_helper_qlm_jtag_shift(qlm, n, 0);
+		bits -= n;
+	}
+}
+
+/**
+ * Program the QLM JTAG chain into all lanes of the QLM. You must
+ * have already shifted in 268*4, or 1072 bits into the JTAG
+ * chain. Updating invalid values can possibly cause chip damage.
+ *
+ * @qlm:    QLM to program
+ */
+void cvmx_helper_qlm_jtag_update(int qlm)
+{
+	union cvmx_ciu_qlm_jtgd jtgd;
+
+	/* Update the new data */
+	jtgd.u64 = 0;
+	jtgd.s.update = 1;
+	if (!OCTEON_IS_MODEL(OCTEON_CN56XX_PASS1_X))
+		jtgd.s.select = 1 << qlm;
+	cvmx_write_csr(CVMX_CIU_QLM_JTGD, jtgd.u64);
+	do {
+		jtgd.u64 = cvmx_read_csr(CVMX_CIU_QLM_JTGD);
+	} while (jtgd.s.update);
+}
diff --git a/arch/mips/cavium-octeon/executive/cvmx-sysinfo.c b/arch/mips/cavium-octeon/executive/cvmx-sysinfo.c
index 48123707..e583889 100644
--- a/arch/mips/cavium-octeon/executive/cvmx-sysinfo.c
+++ b/arch/mips/cavium-octeon/executive/cvmx-sysinfo.c
@@ -29,6 +29,7 @@
  * This module provides system/board/application information obtained
  * by the bootloader.
  */
+#include <linux/module.h>
 
 #include <asm/octeon/cvmx.h>
 #include <asm/octeon/cvmx-spinlock.h>
@@ -69,6 +70,7 @@
 {
 	return &(state.sysinfo);
 }
+EXPORT_SYMBOL(cvmx_sysinfo_get);
 
 /**
  * This function is used in non-simple executive environments (such as
diff --git a/arch/mips/cavium-octeon/msi.c b/arch/mips/cavium-octeon/msi.c
new file mode 100644
index 0000000..964b03b
--- /dev/null
+++ b/arch/mips/cavium-octeon/msi.c
@@ -0,0 +1,288 @@
+/*
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 2005-2007 Cavium Networks
+ */
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/msi.h>
+#include <linux/spinlock.h>
+#include <linux/interrupt.h>
+
+#include <asm/octeon/octeon.h>
+#include <asm/octeon/cvmx-npi-defs.h>
+#include <asm/octeon/cvmx-pci-defs.h>
+#include <asm/octeon/cvmx-npei-defs.h>
+#include <asm/octeon/cvmx-pexp-defs.h>
+
+#include "pci-common.h"
+
+/*
+ * Each bit in msi_free_irq_bitmask represents a MSI interrupt that is
+ * in use.
+ */
+static uint64_t msi_free_irq_bitmask;
+
+/*
+ * Each bit in msi_multiple_irq_bitmask tells that the device using
+ * this bit in msi_free_irq_bitmask is also using the next bit. This
+ * is used so we can disable all of the MSI interrupts when a device
+ * uses multiple.
+ */
+static uint64_t msi_multiple_irq_bitmask;
+
+/*
+ * This lock controls updates to msi_free_irq_bitmask and
+ * msi_multiple_irq_bitmask.
+ */
+static DEFINE_SPINLOCK(msi_free_irq_bitmask_lock);
+
+
+/**
+ * Called when a driver request MSI interrupts instead of the
+ * legacy INT A-D. This routine will allocate multiple interrupts
+ * for MSI devices that support them. A device can override this by
+ * programming the MSI control bits [6:4] before calling
+ * pci_enable_msi().
+ *
+ * @param dev    Device requesting MSI interrupts
+ * @param desc   MSI descriptor
+ *
+ * Returns 0 on success.
+ */
+int arch_setup_msi_irq(struct pci_dev *dev, struct msi_desc *desc)
+{
+	struct msi_msg msg;
+	uint16_t control;
+	int configured_private_bits;
+	int request_private_bits;
+	int irq;
+	int irq_step;
+	uint64_t search_mask;
+
+	/*
+	 * Read the MSI config to figure out how many IRQs this device
+	 * wants.  Most devices only want 1, which will give
+	 * configured_private_bits and request_private_bits equal 0.
+	 */
+	pci_read_config_word(dev, desc->msi_attrib.pos + PCI_MSI_FLAGS,
+			     &control);
+
+	/*
+	 * If the number of private bits has been configured then use
+	 * that value instead of the requested number. This gives the
+	 * driver the chance to override the number of interrupts
+	 * before calling pci_enable_msi().
+	 */
+	configured_private_bits = (control & PCI_MSI_FLAGS_QSIZE) >> 4;
+	if (configured_private_bits == 0) {
+		/* Nothing is configured, so use the hardware requested size */
+		request_private_bits = (control & PCI_MSI_FLAGS_QMASK) >> 1;
+	} else {
+		/*
+		 * Use the number of configured bits, assuming the
+		 * driver wanted to override the hardware request
+		 * value.
+		 */
+		request_private_bits = configured_private_bits;
+	}
+
+	/*
+	 * The PCI 2.3 spec mandates that there are at most 32
+	 * interrupts. If this device asks for more, only give it one.
+	 */
+	if (request_private_bits > 5)
+		request_private_bits = 0;
+
+try_only_one:
+	/*
+	 * The IRQs have to be aligned on a power of two based on the
+	 * number being requested.
+	 */
+	irq_step = 1 << request_private_bits;
+
+	/* Mask with one bit for each IRQ */
+	search_mask = (1 << irq_step) - 1;
+
+	/*
+	 * We're going to search msi_free_irq_bitmask_lock for zero
+	 * bits. This represents an MSI interrupt number that isn't in
+	 * use.
+	 */
+	spin_lock(&msi_free_irq_bitmask_lock);
+	for (irq = 0; irq < 64; irq += irq_step) {
+		if ((msi_free_irq_bitmask & (search_mask << irq)) == 0) {
+			msi_free_irq_bitmask |= search_mask << irq;
+			msi_multiple_irq_bitmask |= (search_mask >> 1) << irq;
+			break;
+		}
+	}
+	spin_unlock(&msi_free_irq_bitmask_lock);
+
+	/* Make sure the search for available interrupts didn't fail */
+	if (irq >= 64) {
+		if (request_private_bits) {
+			pr_err("arch_setup_msi_irq: Unable to find %d free "
+			       "interrupts, trying just one",
+			       1 << request_private_bits);
+			request_private_bits = 0;
+			goto try_only_one;
+		} else
+			panic("arch_setup_msi_irq: Unable to find a free MSI "
+			      "interrupt");
+	}
+
+	/* MSI interrupts start at logical IRQ OCTEON_IRQ_MSI_BIT0 */
+	irq += OCTEON_IRQ_MSI_BIT0;
+
+	switch (octeon_dma_bar_type) {
+	case OCTEON_DMA_BAR_TYPE_SMALL:
+		/* When not using big bar, Bar 0 is based at 128MB */
+		msg.address_lo =
+			((128ul << 20) + CVMX_PCI_MSI_RCV) & 0xffffffff;
+		msg.address_hi = ((128ul << 20) + CVMX_PCI_MSI_RCV) >> 32;
+	case OCTEON_DMA_BAR_TYPE_BIG:
+		/* When using big bar, Bar 0 is based at 0 */
+		msg.address_lo = (0 + CVMX_PCI_MSI_RCV) & 0xffffffff;
+		msg.address_hi = (0 + CVMX_PCI_MSI_RCV) >> 32;
+		break;
+	case OCTEON_DMA_BAR_TYPE_PCIE:
+		/* When using PCIe, Bar 0 is based at 0 */
+		/* FIXME CVMX_NPEI_MSI_RCV* other than 0? */
+		msg.address_lo = (0 + CVMX_NPEI_PCIE_MSI_RCV) & 0xffffffff;
+		msg.address_hi = (0 + CVMX_NPEI_PCIE_MSI_RCV) >> 32;
+		break;
+	default:
+		panic("arch_setup_msi_irq: Invalid octeon_dma_bar_type\n");
+	}
+	msg.data = irq - OCTEON_IRQ_MSI_BIT0;
+
+	/* Update the number of IRQs the device has available to it */
+	control &= ~PCI_MSI_FLAGS_QSIZE;
+	control |= request_private_bits << 4;
+	pci_write_config_word(dev, desc->msi_attrib.pos + PCI_MSI_FLAGS,
+			      control);
+
+	set_irq_msi(irq, desc);
+	write_msi_msg(irq, &msg);
+	return 0;
+}
+
+
+/**
+ * Called when a device no longer needs its MSI interrupts. All
+ * MSI interrupts for the device are freed.
+ *
+ * @irq:    The devices first irq number. There may be multple in sequence.
+ */
+void arch_teardown_msi_irq(unsigned int irq)
+{
+	int number_irqs;
+	uint64_t bitmask;
+
+	if ((irq < OCTEON_IRQ_MSI_BIT0) || (irq > OCTEON_IRQ_MSI_BIT63))
+		panic("arch_teardown_msi_irq: Attempted to teardown illegal "
+		      "MSI interrupt (%d)", irq);
+	irq -= OCTEON_IRQ_MSI_BIT0;
+
+	/*
+	 * Count the number of IRQs we need to free by looking at the
+	 * msi_multiple_irq_bitmask. Each bit set means that the next
+	 * IRQ is also owned by this device.
+	 */
+	number_irqs = 0;
+	while ((irq+number_irqs < 64) &&
+	       (msi_multiple_irq_bitmask & (1ull << (irq + number_irqs))))
+		number_irqs++;
+	number_irqs++;
+	/* Mask with one bit for each IRQ */
+	bitmask = (1 << number_irqs) - 1;
+	/* Shift the mask to the correct bit location */
+	bitmask <<= irq;
+	if ((msi_free_irq_bitmask & bitmask) != bitmask)
+		panic("arch_teardown_msi_irq: Attempted to teardown MSI "
+		      "interrupt (%d) not in use", irq);
+
+	/* Checks are done, update the in use bitmask */
+	spin_lock(&msi_free_irq_bitmask_lock);
+	msi_free_irq_bitmask &= ~bitmask;
+	msi_multiple_irq_bitmask &= ~bitmask;
+	spin_unlock(&msi_free_irq_bitmask_lock);
+}
+
+
+/**
+ * Called by the interrupt handling code when an MSI interrupt
+ * occurs.
+ *
+ * @param cpl
+ * @param dev_id
+ *
+ * @return
+ */
+static irqreturn_t octeon_msi_interrupt(int cpl, void *dev_id)
+{
+	uint64_t msi_bits;
+	int irq;
+
+	if (octeon_dma_bar_type == OCTEON_DMA_BAR_TYPE_PCIE)
+		msi_bits = cvmx_read_csr(CVMX_PEXP_NPEI_MSI_RCV0);
+	else
+		msi_bits = cvmx_read_csr(CVMX_NPI_NPI_MSI_RCV);
+	irq = fls64(msi_bits);
+	if (irq) {
+		irq += OCTEON_IRQ_MSI_BIT0 - 1;
+		if (irq_desc[irq].action) {
+			do_IRQ(irq);
+			return IRQ_HANDLED;
+		} else {
+			pr_err("Spurious MSI interrupt %d\n", irq);
+			if (octeon_has_feature(OCTEON_FEATURE_PCIE)) {
+				/* These chips have PCIe */
+				cvmx_write_csr(CVMX_PEXP_NPEI_MSI_RCV0,
+					       1ull << (irq -
+							OCTEON_IRQ_MSI_BIT0));
+			} else {
+				/* These chips have PCI */
+				cvmx_write_csr(CVMX_NPI_NPI_MSI_RCV,
+					       1ull << (irq -
+							OCTEON_IRQ_MSI_BIT0));
+			}
+		}
+	}
+	return IRQ_NONE;
+}
+
+
+/**
+ * Initializes the MSI interrupt handling code
+ *
+ * @return
+ */
+int octeon_msi_initialize(void)
+{
+	int r;
+	if (octeon_has_feature(OCTEON_FEATURE_PCIE)) {
+		r = request_irq(OCTEON_IRQ_PCI_MSI0, octeon_msi_interrupt,
+				IRQF_SHARED,
+				"MSI[0:63]", octeon_msi_interrupt);
+	} else if (octeon_is_pci_host()) {
+		r = request_irq(OCTEON_IRQ_PCI_MSI0, octeon_msi_interrupt,
+				IRQF_SHARED,
+				"MSI[0:15]", octeon_msi_interrupt);
+		r += request_irq(OCTEON_IRQ_PCI_MSI1, octeon_msi_interrupt,
+				 IRQF_SHARED,
+				 "MSI[16:31]", octeon_msi_interrupt);
+		r += request_irq(OCTEON_IRQ_PCI_MSI2, octeon_msi_interrupt,
+				 IRQF_SHARED,
+				 "MSI[32:47]", octeon_msi_interrupt);
+		r += request_irq(OCTEON_IRQ_PCI_MSI3, octeon_msi_interrupt,
+				 IRQF_SHARED,
+				 "MSI[48:63]", octeon_msi_interrupt);
+	}
+	return 0;
+}
+
+subsys_initcall(octeon_msi_initialize);
diff --git a/arch/mips/cavium-octeon/octeon-irq.c b/arch/mips/cavium-octeon/octeon-irq.c
index d3a0c81..8dfa009 100644
--- a/arch/mips/cavium-octeon/octeon-irq.c
+++ b/arch/mips/cavium-octeon/octeon-irq.c
@@ -10,6 +10,8 @@
 #include <linux/hardirq.h>
 
 #include <asm/octeon/octeon.h>
+#include <asm/octeon/cvmx-pexp-defs.h>
+#include <asm/octeon/cvmx-npi-defs.h>
 
 DEFINE_RWLOCK(octeon_irq_ciu0_rwlock);
 DEFINE_RWLOCK(octeon_irq_ciu1_rwlock);
diff --git a/arch/mips/cavium-octeon/pci-common.c b/arch/mips/cavium-octeon/pci-common.c
new file mode 100644
index 0000000..cd029f8
--- /dev/null
+++ b/arch/mips/cavium-octeon/pci-common.c
@@ -0,0 +1,137 @@
+/*
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 2005-2007 Cavium Networks
+ */
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/pci.h>
+#include <linux/interrupt.h>
+#include <linux/time.h>
+#include <linux/delay.h>
+#include "pci-common.h"
+
+typeof(pcibios_map_irq) *octeon_pcibios_map_irq;
+enum octeon_dma_bar_type octeon_dma_bar_type = OCTEON_DMA_BAR_TYPE_INVALID;
+
+/**
+ * Map a PCI device to the appropriate interrupt line
+ *
+ * @param dev    The Linux PCI device structure for the device to map
+ * @param slot   The slot number for this device on __BUS 0__. Linux
+ *               enumerates through all the bridges and figures out the
+ *               slot on Bus 0 where this device eventually hooks to.
+ * @param pin    The PCI interrupt pin read from the device, then swizzled
+ *               as it goes through each bridge.
+ * @return Interrupt number for the device
+ */
+int __init pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
+{
+	if (octeon_pcibios_map_irq)
+		return octeon_pcibios_map_irq(dev, slot, pin);
+	else
+		panic("octeon_pcibios_map_irq doesn't point to a "
+		      "pcibios_map_irq() function");
+}
+
+
+/**
+ * Called to perform platform specific PCI setup
+ *
+ * @param dev
+ * @return
+ */
+int pcibios_plat_dev_init(struct pci_dev *dev)
+{
+	uint16_t config;
+	uint32_t dconfig;
+	int pos;
+	/*
+	 * Force the Cache line setting to 64 bytes. The standard
+	 * Linux bus scan doesn't seem to set it. Octeon really has
+	 * 128 byte lines, but Intel bridges get really upset if you
+	 * try and set values above 64 bytes. Value is specified in
+	 * 32bit words.
+	 */
+	pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, 64 / 4);
+	/* Set latency timers for all devices */
+	pci_write_config_byte(dev, PCI_LATENCY_TIMER, 48);
+
+	/* Enable reporting System errors and parity errors on all devices */
+	/* Enable parity checking and error reporting */
+	pci_read_config_word(dev, PCI_COMMAND, &config);
+	config |= PCI_COMMAND_PARITY | PCI_COMMAND_SERR;
+	pci_write_config_word(dev, PCI_COMMAND, config);
+
+	if (dev->subordinate) {
+		/* Set latency timers on sub bridges */
+		pci_write_config_byte(dev, PCI_SEC_LATENCY_TIMER, 48);
+		/* More bridge error detection */
+		pci_read_config_word(dev, PCI_BRIDGE_CONTROL, &config);
+		config |= PCI_BRIDGE_CTL_PARITY | PCI_BRIDGE_CTL_SERR;
+		pci_write_config_word(dev, PCI_BRIDGE_CONTROL, config);
+	}
+
+	/* Enable the PCIe normal error reporting */
+	pos = pci_find_capability(dev, PCI_CAP_ID_EXP);
+	if (pos) {
+		/* Update Device Control */
+		pci_read_config_word(dev, pos + PCI_EXP_DEVCTL, &config);
+		/* Correctable Error Reporting */
+		config |= PCI_EXP_DEVCTL_CERE;
+		/* Non-Fatal Error Reporting */
+		config |= PCI_EXP_DEVCTL_NFERE;
+		/* Fatal Error Reporting */
+		config |= PCI_EXP_DEVCTL_FERE;
+		/* Unsupported Request */
+		config |= PCI_EXP_DEVCTL_URRE;
+		pci_write_config_word(dev, pos + PCI_EXP_DEVCTL, config);
+	}
+
+	/* Find the Advanced Error Reporting capability */
+	pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ERR);
+	if (pos) {
+		/* Clear Uncorrectable Error Status */
+		pci_read_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS,
+				      &dconfig);
+		pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_STATUS,
+				       dconfig);
+		/* Enable reporting of all uncorrectable errors */
+		/* Uncorrectable Error Mask - turned on bits disable errors */
+		pci_write_config_dword(dev, pos + PCI_ERR_UNCOR_MASK, 0);
+		/*
+		 * Leave severity at HW default. This only controls if
+		 * errors are reported as uncorrectable or
+		 * correctable, not if the error is reported.
+		 */
+		/* PCI_ERR_UNCOR_SEVER - Uncorrectable Error Severity */
+		/* Clear Correctable Error Status */
+		pci_read_config_dword(dev, pos + PCI_ERR_COR_STATUS, &dconfig);
+		pci_write_config_dword(dev, pos + PCI_ERR_COR_STATUS, dconfig);
+		/* Enable reporting of all correctable errors */
+		/* Correctable Error Mask - turned on bits disable errors */
+		pci_write_config_dword(dev, pos + PCI_ERR_COR_MASK, 0);
+		/* Advanced Error Capabilities */
+		pci_read_config_dword(dev, pos + PCI_ERR_CAP, &dconfig);
+		/* ECRC Generation Enable */
+		if (config & PCI_ERR_CAP_ECRC_GENC)
+			config |= PCI_ERR_CAP_ECRC_GENE;
+		/* ECRC Check Enable */
+		if (config & PCI_ERR_CAP_ECRC_CHKC)
+			config |= PCI_ERR_CAP_ECRC_CHKE;
+		pci_write_config_dword(dev, pos + PCI_ERR_CAP, dconfig);
+		/* PCI_ERR_HEADER_LOG - Header Log Register (16 bytes) */
+		/* Report all errors to the root complex */
+		pci_write_config_dword(dev, pos + PCI_ERR_ROOT_COMMAND,
+				       PCI_ERR_ROOT_CMD_COR_EN |
+				       PCI_ERR_ROOT_CMD_NONFATAL_EN |
+				       PCI_ERR_ROOT_CMD_FATAL_EN);
+		/* Clear the Root status register */
+		pci_read_config_dword(dev, pos + PCI_ERR_ROOT_STATUS, &dconfig);
+		pci_write_config_dword(dev, pos + PCI_ERR_ROOT_STATUS, dconfig);
+	}
+
+	return 0;
+}
diff --git a/arch/mips/cavium-octeon/pci-common.h b/arch/mips/cavium-octeon/pci-common.h
new file mode 100644
index 0000000..74ae799
--- /dev/null
+++ b/arch/mips/cavium-octeon/pci-common.h
@@ -0,0 +1,39 @@
+/*
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 2005-2007 Cavium Networks
+ */
+#ifndef __OCTEON_PCI_COMMON_H__
+#define __OCTEON_PCI_COMMON_H__
+
+#include <linux/pci.h>
+
+/* Some PCI cards require delays when accessing config space. */
+#define PCI_CONFIG_SPACE_DELAY 10000
+
+/* pcibios_map_irq() is defined inside pci-common.c. All it does is call the
+   Octeon specific version pointed to by this variable. This function needs to
+   change for PCI or PCIe based hosts */
+extern typeof(pcibios_map_irq) *octeon_pcibios_map_irq;
+
+/* The following defines are only used when octeon_dma_bar_type =
+   OCTEON_DMA_BAR_TYPE_BIG */
+#define OCTEON_PCI_BAR1_HOLE_BITS 5
+#define OCTEON_PCI_BAR1_HOLE_SIZE (1ul<<(OCTEON_PCI_BAR1_HOLE_BITS+3))
+
+enum octeon_dma_bar_type {
+	OCTEON_DMA_BAR_TYPE_INVALID,
+	OCTEON_DMA_BAR_TYPE_SMALL,
+	OCTEON_DMA_BAR_TYPE_BIG,
+	OCTEON_DMA_BAR_TYPE_PCIE
+};
+
+/**
+ * This is a variable to tell the DMA mapping system in dma-octeon.c
+ * how to map PCI DMA addresses.
+ */
+extern enum octeon_dma_bar_type octeon_dma_bar_type;
+
+#endif
diff --git a/arch/mips/cavium-octeon/pci.c b/arch/mips/cavium-octeon/pci.c
new file mode 100644
index 0000000..67c0ff5
--- /dev/null
+++ b/arch/mips/cavium-octeon/pci.c
@@ -0,0 +1,568 @@
+/*
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 2005-2007 Cavium Networks
+ */
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/pci.h>
+#include <linux/interrupt.h>
+#include <linux/time.h>
+#include <linux/delay.h>
+
+#include <asm/time.h>
+
+#include <asm/octeon/octeon.h>
+#include <asm/octeon/cvmx-npi-defs.h>
+#include <asm/octeon/cvmx-pci-defs.h>
+
+#include "pci-common.h"
+
+#define USE_OCTEON_INTERNAL_ARBITER
+
+/*
+ * Octeon's PCI controller uses did=3, subdid=2 for PCI IO
+ * addresses. Use PCI endian swapping 1 so no address swapping is
+ * necessary. The Linux io routines will endian swap the data.
+ */
+#define OCTEON_PCI_IOSPACE_BASE     0x80011a0400000000ull
+#define OCTEON_PCI_IOSPACE_SIZE     (1ull<<32)
+
+/* Octeon't PCI controller uses did=3, subdid=3 for PCI memory. */
+#define OCTEON_PCI_MEMSPACE_OFFSET  (0x00011b0000000000ull)
+
+/**
+ * This is the bit decoding used for the Octeon PCI controller addresses
+ */
+union octeon_pci_address {
+	uint64_t u64;
+	struct {
+		uint64_t upper:2;
+		uint64_t reserved:13;
+		uint64_t io:1;
+		uint64_t did:5;
+		uint64_t subdid:3;
+		uint64_t reserved2:4;
+		uint64_t endian_swap:2;
+		uint64_t reserved3:10;
+		uint64_t bus:8;
+		uint64_t dev:5;
+		uint64_t func:3;
+		uint64_t reg:8;
+	} s;
+};
+
+/**
+ * Return the mapping of PCI device number to IRQ line. Each
+ * character in the return string represents the interrupt
+ * line for the device at that position. Device 1 maps to the
+ * first character, etc. The characters A-D are used for PCI
+ * interrupts.
+ *
+ * Returns PCI interrupt mapping
+ */
+const char *octeon_get_pci_interrupts(void)
+{
+	/*
+	 * Returning an empty string causes the interrupts to be
+	 * routed based on the PCI specification. From the PCI spec:
+	 *
+	 * INTA# of Device Number 0 is connected to IRQW on the system
+	 * board.  (Device Number has no significance regarding being
+	 * located on the system board or in a connector.) INTA# of
+	 * Device Number 1 is connected to IRQX on the system
+	 * board. INTA# of Device Number 2 is connected to IRQY on the
+	 * system board. INTA# of Device Number 3 is connected to IRQZ
+	 * on the system board. The table below describes how each
+	 * agent's INTx# lines are connected to the system board
+	 * interrupt lines. The following equation can be used to
+	 * determine to which INTx# signal on the system board a given
+	 * device's INTx# line(s) is connected.
+	 *
+	 * MB = (D + I) MOD 4 MB = System board Interrupt (IRQW = 0,
+	 * IRQX = 1, IRQY = 2, and IRQZ = 3) D = Device Number I =
+	 * Interrupt Number (INTA# = 0, INTB# = 1, INTC# = 2, and
+	 * INTD# = 3)
+	 */
+	switch (octeon_bootinfo->board_type) {
+	case CVMX_BOARD_TYPE_NAO38:
+		/* This is really the NAC38 */
+		return "AAAAADABAAAAAAAAAAAAAAAAAAAAAAAA";
+	case CVMX_BOARD_TYPE_THUNDER:
+		return "";
+	case CVMX_BOARD_TYPE_EBH3000:
+		return "";
+	case CVMX_BOARD_TYPE_EBH3100:
+	case CVMX_BOARD_TYPE_CN3010_EVB_HS5:
+	case CVMX_BOARD_TYPE_CN3005_EVB_HS5:
+		return "AAABAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
+	case CVMX_BOARD_TYPE_BBGW_REF:
+		return "AABCD";
+	default:
+		return "";
+	}
+}
+
+/**
+ * Map a PCI device to the appropriate interrupt line
+ *
+ * @dev:    The Linux PCI device structure for the device to map
+ * @slot:   The slot number for this device on __BUS 0__. Linux
+ *               enumerates through all the bridges and figures out the
+ *               slot on Bus 0 where this device eventually hooks to.
+ * @pin:    The PCI interrupt pin read from the device, then swizzled
+ *               as it goes through each bridge.
+ * Returns Interrupt number for the device
+ */
+int __init octeon_pci_pcibios_map_irq(const struct pci_dev *dev,
+				      u8 slot, u8 pin)
+{
+	int irq_num;
+	const char *interrupts;
+	int dev_num;
+
+	/* Get the board specific interrupt mapping */
+	interrupts = octeon_get_pci_interrupts();
+
+	dev_num = dev->devfn >> 3;
+	if (dev_num < strlen(interrupts))
+		irq_num = ((interrupts[dev_num] - 'A' + pin - 1) & 3) +
+			OCTEON_IRQ_PCI_INT0;
+	else
+		irq_num = ((slot + pin - 3) & 3) + OCTEON_IRQ_PCI_INT0;
+	return irq_num;
+}
+
+
+/**
+ * Read a value from configuration space
+ *
+ */
+static int octeon_read_config(struct pci_bus *bus, unsigned int devfn,
+			      int reg, int size, u32 *val)
+{
+	union octeon_pci_address pci_addr;
+
+	pci_addr.u64 = 0;
+	pci_addr.s.upper = 2;
+	pci_addr.s.io = 1;
+	pci_addr.s.did = 3;
+	pci_addr.s.subdid = 1;
+	pci_addr.s.endian_swap = 1;
+	pci_addr.s.bus = bus->number;
+	pci_addr.s.dev = devfn >> 3;
+	pci_addr.s.func = devfn & 0x7;
+	pci_addr.s.reg = reg;
+
+#if PCI_CONFIG_SPACE_DELAY
+	udelay(PCI_CONFIG_SPACE_DELAY);
+#endif
+	switch (size) {
+	case 4:
+		*val = le32_to_cpu(cvmx_read64_uint32(pci_addr.u64));
+		return PCIBIOS_SUCCESSFUL;
+	case 2:
+		*val = le16_to_cpu(cvmx_read64_uint16(pci_addr.u64));
+		return PCIBIOS_SUCCESSFUL;
+	case 1:
+		*val = cvmx_read64_uint8(pci_addr.u64);
+		return PCIBIOS_SUCCESSFUL;
+	}
+	return PCIBIOS_FUNC_NOT_SUPPORTED;
+}
+
+
+/**
+ * Write a value to PCI configuration space
+ *
+ * @bus:
+ * @devfn:
+ * @reg:
+ * @size:
+ * @val:
+ * Returns
+ */
+static int octeon_write_config(struct pci_bus *bus, unsigned int devfn,
+			       int reg, int size, u32 val)
+{
+	union octeon_pci_address pci_addr;
+
+	pci_addr.u64 = 0;
+	pci_addr.s.upper = 2;
+	pci_addr.s.io = 1;
+	pci_addr.s.did = 3;
+	pci_addr.s.subdid = 1;
+	pci_addr.s.endian_swap = 1;
+	pci_addr.s.bus = bus->number;
+	pci_addr.s.dev = devfn >> 3;
+	pci_addr.s.func = devfn & 0x7;
+	pci_addr.s.reg = reg;
+
+#if PCI_CONFIG_SPACE_DELAY
+	udelay(PCI_CONFIG_SPACE_DELAY);
+#endif
+	switch (size) {
+	case 4:
+		cvmx_write64_uint32(pci_addr.u64, cpu_to_le32(val));
+		return PCIBIOS_SUCCESSFUL;
+	case 2:
+		cvmx_write64_uint16(pci_addr.u64, cpu_to_le16(val));
+		return PCIBIOS_SUCCESSFUL;
+	case 1:
+		cvmx_write64_uint8(pci_addr.u64, val);
+		return PCIBIOS_SUCCESSFUL;
+	}
+	return PCIBIOS_FUNC_NOT_SUPPORTED;
+}
+
+
+static struct pci_ops octeon_pci_ops = {
+	octeon_read_config,
+	octeon_write_config,
+};
+
+static struct resource octeon_pci_mem_resource = {
+	.start = 0,
+	.end = 0,
+	.name = "Octeon PCI MEM",
+	.flags = IORESOURCE_MEM,
+};
+
+/*
+ * PCI ports must be above 16KB so the ISA bus filtering in the PCI-X to PCI
+ * bridge
+ */
+static struct resource octeon_pci_io_resource = {
+	.start = 0x4000,
+	.end = OCTEON_PCI_IOSPACE_SIZE - 1,
+	.name = "Octeon PCI IO",
+	.flags = IORESOURCE_IO,
+};
+
+static struct pci_controller octeon_pci_controller = {
+	.pci_ops = &octeon_pci_ops,
+	.mem_resource = &octeon_pci_mem_resource,
+	.mem_offset = OCTEON_PCI_MEMSPACE_OFFSET,
+	.io_resource = &octeon_pci_io_resource,
+	.io_offset = 0,
+	.io_map_base = OCTEON_PCI_IOSPACE_BASE,
+};
+
+
+/**
+ * Low level initialize the Octeon PCI controller
+ *
+ * Returns
+ */
+static void octeon_pci_initialize(void)
+{
+	union cvmx_pci_cfg01 cfg01;
+	union cvmx_npi_ctl_status ctl_status;
+	union cvmx_pci_ctl_status_2 ctl_status_2;
+	union cvmx_pci_cfg19 cfg19;
+	union cvmx_pci_cfg16 cfg16;
+	union cvmx_pci_cfg22 cfg22;
+	union cvmx_pci_cfg56 cfg56;
+
+	/* Reset the PCI Bus */
+	cvmx_write_csr(CVMX_CIU_SOFT_PRST, 0x1);
+	cvmx_read_csr(CVMX_CIU_SOFT_PRST);
+
+	udelay(2000);		/* Hold PCI reset for 2 ms */
+
+	ctl_status.u64 = 0;	/* cvmx_read_csr(CVMX_NPI_CTL_STATUS); */
+	ctl_status.s.max_word = 1;
+	ctl_status.s.timer = 1;
+	cvmx_write_csr(CVMX_NPI_CTL_STATUS, ctl_status.u64);
+
+	/* Deassert PCI reset and advertize PCX Host Mode Device Capability
+	   (64b) */
+	cvmx_write_csr(CVMX_CIU_SOFT_PRST, 0x4);
+	cvmx_read_csr(CVMX_CIU_SOFT_PRST);
+
+	udelay(2000);		/* Wait 2 ms after deasserting PCI reset */
+
+	ctl_status_2.u32 = 0;
+	ctl_status_2.s.tsr_hwm = 1;	/* Initializes to 0.  Must be set
+					   before any PCI reads. */
+	ctl_status_2.s.bar2pres = 1;	/* Enable BAR2 */
+	ctl_status_2.s.bar2_enb = 1;
+	ctl_status_2.s.bar2_cax = 1;	/* Don't use L2 */
+	ctl_status_2.s.bar2_esx = 1;
+	ctl_status_2.s.pmo_amod = 1;	/* Round robin priority */
+	if (octeon_dma_bar_type == OCTEON_DMA_BAR_TYPE_BIG) {
+		/* BAR1 hole */
+		ctl_status_2.s.bb1_hole = OCTEON_PCI_BAR1_HOLE_BITS;
+		ctl_status_2.s.bb1_siz = 1;  /* BAR1 is 2GB */
+		ctl_status_2.s.bb_ca = 1;    /* Don't use L2 with big bars */
+		ctl_status_2.s.bb_es = 1;    /* Big bar in byte swap mode */
+		ctl_status_2.s.bb1 = 1;      /* BAR1 is big */
+		ctl_status_2.s.bb0 = 1;      /* BAR0 is big */
+	}
+
+	octeon_npi_write32(CVMX_NPI_PCI_CTL_STATUS_2, ctl_status_2.u32);
+	udelay(2000);		/* Wait 2 ms before doing PCI reads */
+
+	ctl_status_2.u32 = octeon_npi_read32(CVMX_NPI_PCI_CTL_STATUS_2);
+	pr_notice("PCI Status: %s %s-bit\n",
+		  ctl_status_2.s.ap_pcix ? "PCI-X" : "PCI",
+		  ctl_status_2.s.ap_64ad ? "64" : "32");
+
+	if (OCTEON_IS_MODEL(OCTEON_CN58XX) || OCTEON_IS_MODEL(OCTEON_CN50XX)) {
+		union cvmx_pci_cnt_reg cnt_reg_start;
+		union cvmx_pci_cnt_reg cnt_reg_end;
+		unsigned long cycles, pci_clock;
+
+		cnt_reg_start.u64 = cvmx_read_csr(CVMX_NPI_PCI_CNT_REG);
+		cycles = read_c0_cvmcount();
+		udelay(1000);
+		cnt_reg_end.u64 = cvmx_read_csr(CVMX_NPI_PCI_CNT_REG);
+		cycles = read_c0_cvmcount() - cycles;
+		pci_clock = (cnt_reg_end.s.pcicnt - cnt_reg_start.s.pcicnt) /
+			    (cycles / (mips_hpt_frequency / 1000000));
+		pr_notice("PCI Clock: %lu MHz\n", pci_clock);
+	}
+
+	/*
+	 * TDOMC must be set to one in PCI mode. TDOMC should be set to 4
+	 * in PCI-X mode to allow four oustanding splits. Otherwise,
+	 * should not change from its reset value. Don't write PCI_CFG19
+	 * in PCI mode (0x82000001 reset value), write it to 0x82000004
+	 * after PCI-X mode is known. MRBCI,MDWE,MDRE -> must be zero.
+	 * MRBCM -> must be one.
+	 */
+	if (ctl_status_2.s.ap_pcix) {
+		cfg19.u32 = 0;
+		/*
+		 * Target Delayed/Split request outstanding maximum
+		 * count. [1..31] and 0=32.  NOTE: If the user
+		 * programs these bits beyond the Designed Maximum
+		 * outstanding count, then the designed maximum table
+		 * depth will be used instead.  No additional
+		 * Deferred/Split transactions will be accepted if
+		 * this outstanding maximum count is
+		 * reached. Furthermore, no additional deferred/split
+		 * transactions will be accepted if the I/O delay/ I/O
+		 * Split Request outstanding maximum is reached.
+		 */
+		cfg19.s.tdomc = 4;
+		/*
+		 * Master Deferred Read Request Outstanding Max Count
+		 * (PCI only).  CR4C[26:24] Max SAC cycles MAX DAC
+		 * cycles 000 8 4 001 1 0 010 2 1 011 3 1 100 4 2 101
+		 * 5 2 110 6 3 111 7 3 For example, if these bits are
+		 * programmed to 100, the core can support 2 DAC
+		 * cycles, 4 SAC cycles or a combination of 1 DAC and
+		 * 2 SAC cycles. NOTE: For the PCI-X maximum
+		 * outstanding split transactions, refer to
+		 * CRE0[22:20].
+		 */
+		cfg19.s.mdrrmc = 2;
+		/*
+		 * Master Request (Memory Read) Byte Count/Byte Enable
+		 * select. 0 = Byte Enables valid. In PCI mode, a
+		 * burst transaction cannot be performed using Memory
+		 * Read command=4?h6. 1 = DWORD Byte Count valid
+		 * (default). In PCI Mode, the memory read byte
+		 * enables are automatically generated by the
+		 * core. Note: N3 Master Request transaction sizes are
+		 * always determined through the
+		 * am_attr[<35:32>|<7:0>] field.
+		 */
+		cfg19.s.mrbcm = 1;
+		octeon_npi_write32(CVMX_NPI_PCI_CFG19, cfg19.u32);
+	}
+
+
+	cfg01.u32 = 0;
+	cfg01.s.msae = 1;	/* Memory Space Access Enable */
+	cfg01.s.me = 1;		/* Master Enable */
+	cfg01.s.pee = 1;	/* PERR# Enable */
+	cfg01.s.see = 1;	/* System Error Enable */
+	cfg01.s.fbbe = 1;	/* Fast Back to Back Transaction Enable */
+
+	octeon_npi_write32(CVMX_NPI_PCI_CFG01, cfg01.u32);
+
+#ifdef USE_OCTEON_INTERNAL_ARBITER
+	/*
+	 * When OCTEON is a PCI host, most systems will use OCTEON's
+	 * internal arbiter, so must enable it before any PCI/PCI-X
+	 * traffic can occur.
+	 */
+	{
+		union cvmx_npi_pci_int_arb_cfg pci_int_arb_cfg;
+
+		pci_int_arb_cfg.u64 = 0;
+		pci_int_arb_cfg.s.en = 1;	/* Internal arbiter enable */
+		cvmx_write_csr(CVMX_NPI_PCI_INT_ARB_CFG, pci_int_arb_cfg.u64);
+	}
+#endif				/* USE_OCTEON_INTERNAL_ARBITER */
+
+	/*
+	 * Preferrably written to 1 to set MLTD. [RDSATI,TRTAE,
+	 * TWTAE,TMAE,DPPMR -> must be zero. TILT -> must not be set to
+	 * 1..7.
+	 */
+	cfg16.u32 = 0;
+	cfg16.s.mltd = 1;	/* Master Latency Timer Disable */
+	octeon_npi_write32(CVMX_NPI_PCI_CFG16, cfg16.u32);
+
+	/*
+	 * Should be written to 0x4ff00. MTTV -> must be zero.
+	 * FLUSH -> must be 1. MRV -> should be 0xFF.
+	 */
+	cfg22.u32 = 0;
+	/* Master Retry Value [1..255] and 0=infinite */
+	cfg22.s.mrv = 0xff;
+	/*
+	 * AM_DO_FLUSH_I control NOTE: This bit MUST BE ONE for proper
+	 * N3K operation.
+	 */
+	cfg22.s.flush = 1;
+	octeon_npi_write32(CVMX_NPI_PCI_CFG22, cfg22.u32);
+
+	/*
+	 * MOST Indicates the maximum number of outstanding splits (in -1
+	 * notation) when OCTEON is in PCI-X mode.  PCI-X performance is
+	 * affected by the MOST selection.  Should generally be written
+	 * with one of 0x3be807, 0x2be807, 0x1be807, or 0x0be807,
+	 * depending on the desired MOST of 3, 2, 1, or 0, respectively.
+	 */
+	cfg56.u32 = 0;
+	cfg56.s.pxcid = 7;	/* RO - PCI-X Capability ID */
+	cfg56.s.ncp = 0xe8;	/* RO - Next Capability Pointer */
+	cfg56.s.dpere = 1;	/* Data Parity Error Recovery Enable */
+	cfg56.s.roe = 1;	/* Relaxed Ordering Enable */
+	cfg56.s.mmbc = 1;	/* Maximum Memory Byte Count
+				   [0=512B,1=1024B,2=2048B,3=4096B] */
+	cfg56.s.most = 3;	/* Maximum outstanding Split transactions [0=1
+				   .. 7=32] */
+
+	octeon_npi_write32(CVMX_NPI_PCI_CFG56, cfg56.u32);
+
+	/*
+	 * Affects PCI performance when OCTEON services reads to its
+	 * BAR1/BAR2. Refer to Section 10.6.1.  The recommended values are
+	 * 0x22, 0x33, and 0x33 for PCI_READ_CMD_6, PCI_READ_CMD_C, and
+	 * PCI_READ_CMD_E, respectively. Unfortunately due to errata DDR-700,
+	 * these values need to be changed so they won't possibly prefetch off
+	 * of the end of memory if PCI is DMAing a buffer at the end of
+	 * memory. Note that these values differ from their reset values.
+	 */
+	octeon_npi_write32(CVMX_NPI_PCI_READ_CMD_6, 0x21);
+	octeon_npi_write32(CVMX_NPI_PCI_READ_CMD_C, 0x31);
+	octeon_npi_write32(CVMX_NPI_PCI_READ_CMD_E, 0x31);
+}
+
+
+/**
+ * Initialize the Octeon PCI controller
+ *
+ * Returns
+ */
+static int __init octeon_pci_setup(void)
+{
+	union cvmx_npi_mem_access_subidx mem_access;
+	int index;
+
+	/* Only these chips have PCI */
+	if (octeon_has_feature(OCTEON_FEATURE_PCIE))
+		return 0;
+
+	/* Point pcibios_map_irq() to the PCI version of it */
+	octeon_pcibios_map_irq = octeon_pci_pcibios_map_irq;
+
+	/* Only use the big bars on chips that support it */
+	if (OCTEON_IS_MODEL(OCTEON_CN31XX) ||
+	    OCTEON_IS_MODEL(OCTEON_CN38XX_PASS2) ||
+	    OCTEON_IS_MODEL(OCTEON_CN38XX_PASS1))
+		octeon_dma_bar_type = OCTEON_DMA_BAR_TYPE_SMALL;
+	else
+		octeon_dma_bar_type = OCTEON_DMA_BAR_TYPE_BIG;
+
+	/* PCI I/O and PCI MEM values */
+	set_io_port_base(OCTEON_PCI_IOSPACE_BASE);
+	ioport_resource.start = 0;
+	ioport_resource.end = OCTEON_PCI_IOSPACE_SIZE - 1;
+	if (!octeon_is_pci_host()) {
+		pr_notice("Not in host mode, PCI Controller not initialized\n");
+		return 0;
+	}
+
+	pr_notice("%s Octeon big bar support\n",
+		  (octeon_dma_bar_type ==
+		  OCTEON_DMA_BAR_TYPE_BIG) ? "Enabling" : "Disabling");
+
+	octeon_pci_initialize();
+
+	mem_access.u64 = 0;
+	mem_access.s.esr = 1;	/* Endian-Swap on read. */
+	mem_access.s.esw = 1;	/* Endian-Swap on write. */
+	mem_access.s.nsr = 0;	/* No-Snoop on read. */
+	mem_access.s.nsw = 0;	/* No-Snoop on write. */
+	mem_access.s.ror = 0;	/* Relax Read on read. */
+	mem_access.s.row = 0;	/* Relax Order on write. */
+	mem_access.s.ba = 0;	/* PCI Address bits [63:36]. */
+	cvmx_write_csr(CVMX_NPI_MEM_ACCESS_SUBID3, mem_access.u64);
+
+	/*
+	 * Remap the Octeon BAR 2 above all 32 bit devices
+	 * (0x8000000000ul).  This is done here so it is remapped
+	 * before the readl()'s below. We don't want BAR2 overlapping
+	 * with BAR0/BAR1 during these reads.
+	 */
+	octeon_npi_write32(CVMX_NPI_PCI_CFG08, 0);
+	octeon_npi_write32(CVMX_NPI_PCI_CFG09, 0x80);
+
+	/* Disable the BAR1 movable mappings */
+	for (index = 0; index < 32; index++)
+		octeon_npi_write32(CVMX_NPI_PCI_BAR1_INDEXX(index), 0);
+
+	if (octeon_dma_bar_type == OCTEON_DMA_BAR_TYPE_BIG) {
+		/* Remap the Octeon BAR 0 to 0-2GB */
+		octeon_npi_write32(CVMX_NPI_PCI_CFG04, 0);
+		octeon_npi_write32(CVMX_NPI_PCI_CFG05, 0);
+
+		/*
+		 * Remap the Octeon BAR 1 to map 2GB-4GB (minus the
+		 * BAR 1 hole).
+		 */
+		octeon_npi_write32(CVMX_NPI_PCI_CFG06, 2ul << 30);
+		octeon_npi_write32(CVMX_NPI_PCI_CFG07, 0);
+
+		/* Devices go after BAR1 */
+		octeon_pci_mem_resource.start =
+			OCTEON_PCI_MEMSPACE_OFFSET + (4ul << 30) -
+			(OCTEON_PCI_BAR1_HOLE_SIZE << 20);
+		octeon_pci_mem_resource.end =
+			octeon_pci_mem_resource.start + (1ul << 30);
+	} else {
+		/* Remap the Octeon BAR 0 to map 128MB-(128MB+4KB) */
+		octeon_npi_write32(CVMX_NPI_PCI_CFG04, 128ul << 20);
+		octeon_npi_write32(CVMX_NPI_PCI_CFG05, 0);
+
+		/* Remap the Octeon BAR 1 to map 0-128MB */
+		octeon_npi_write32(CVMX_NPI_PCI_CFG06, 0);
+		octeon_npi_write32(CVMX_NPI_PCI_CFG07, 0);
+
+		/* Devices go after BAR0 */
+		octeon_pci_mem_resource.start =
+			OCTEON_PCI_MEMSPACE_OFFSET + (128ul << 20) +
+			(4ul << 10);
+		octeon_pci_mem_resource.end =
+			octeon_pci_mem_resource.start + (1ul << 30);
+	}
+
+	register_pci_controller(&octeon_pci_controller);
+
+	/*
+	 * Clear any errors that might be pending from before the bus
+	 * was setup properly.
+	 */
+	cvmx_write_csr(CVMX_NPI_PCI_INT_SUM2, -1);
+	return 0;
+}
+
+arch_initcall(octeon_pci_setup);
diff --git a/arch/mips/cavium-octeon/pcie.c b/arch/mips/cavium-octeon/pcie.c
new file mode 100644
index 0000000..49d1408
--- /dev/null
+++ b/arch/mips/cavium-octeon/pcie.c
@@ -0,0 +1,1370 @@
+/*
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 2007, 2008 Cavium Networks
+ */
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/pci.h>
+#include <linux/interrupt.h>
+#include <linux/time.h>
+#include <linux/delay.h>
+
+#include <asm/octeon/octeon.h>
+#include <asm/octeon/cvmx-npei-defs.h>
+#include <asm/octeon/cvmx-pciercx-defs.h>
+#include <asm/octeon/cvmx-pescx-defs.h>
+#include <asm/octeon/cvmx-pexp-defs.h>
+#include <asm/octeon/cvmx-helper-errata.h>
+
+#include "pci-common.h"
+
+union cvmx_pcie_address {
+	uint64_t u64;
+	struct {
+		uint64_t upper:2;	/* Normally 2 for XKPHYS */
+		uint64_t reserved_49_61:13;	/* Must be zero */
+		uint64_t io:1;	/* 1 for IO space access */
+		uint64_t did:5;	/* PCIe DID = 3 */
+		uint64_t subdid:3;	/* PCIe SubDID = 1 */
+		uint64_t reserved_36_39:4;	/* Must be zero */
+		uint64_t es:2;	/* Endian swap = 1 */
+		uint64_t port:2;	/* PCIe port 0,1 */
+		uint64_t reserved_29_31:3;	/* Must be zero */
+		/*
+		 * Selects the type of the configuration request (0 = type 0,
+		 * 1 = type 1).
+		 */
+		uint64_t ty:1;
+		/* Target bus number sent in the ID in the request. */
+		uint64_t bus:8;
+		/*
+		 * Target device number sent in the ID in the
+		 * request. Note that Dev must be zero for type 0
+		 * configuration requests.
+		 */
+		uint64_t dev:5;
+		/* Target function number sent in the ID in the request. */
+		uint64_t func:3;
+		/*
+		 * Selects a register in the configuration space of
+		 * the target.
+		 */
+		uint64_t reg:12;
+	} config;
+	struct {
+		uint64_t upper:2;	/* Normally 2 for XKPHYS */
+		uint64_t reserved_49_61:13;	/* Must be zero */
+		uint64_t io:1;	/* 1 for IO space access */
+		uint64_t did:5;	/* PCIe DID = 3 */
+		uint64_t subdid:3;	/* PCIe SubDID = 2 */
+		uint64_t reserved_36_39:4;	/* Must be zero */
+		uint64_t es:2;	/* Endian swap = 1 */
+		uint64_t port:2;	/* PCIe port 0,1 */
+		uint64_t address:32;	/* PCIe IO address */
+	} io;
+	struct {
+		uint64_t upper:2;	/* Normally 2 for XKPHYS */
+		uint64_t reserved_49_61:13;	/* Must be zero */
+		uint64_t io:1;	/* 1 for IO space access */
+		uint64_t did:5;	/* PCIe DID = 3 */
+		uint64_t subdid:3;	/* PCIe SubDID = 3-6 */
+		uint64_t reserved_36_39:4;	/* Must be zero */
+		uint64_t address:36;	/* PCIe Mem address */
+	} mem;
+};
+
+/**
+ * Return the Core virtual base address for PCIe IO access. IOs are
+ * read/written as an offset from this address.
+ *
+ * @pcie_port: PCIe port the IO is for
+ *
+ * Returns 64bit Octeon IO base address for read/write
+ */
+static inline uint64_t cvmx_pcie_get_io_base_address(int pcie_port)
+{
+	union cvmx_pcie_address pcie_addr;
+	pcie_addr.u64 = 0;
+	pcie_addr.io.upper = 0;
+	pcie_addr.io.io = 1;
+	pcie_addr.io.did = 3;
+	pcie_addr.io.subdid = 2;
+	pcie_addr.io.es = 1;
+	pcie_addr.io.port = pcie_port;
+	return pcie_addr.u64;
+}
+
+/**
+ * Size of the IO address region returned at address
+ * cvmx_pcie_get_io_base_address()
+ *
+ * @pcie_port: PCIe port the IO is for
+ *
+ * Returns Size of the IO window
+ */
+static inline uint64_t cvmx_pcie_get_io_size(int pcie_port)
+{
+	return 1ull << 32;
+}
+
+/**
+ * Return the Core virtual base address for PCIe MEM access. Memory is
+ * read/written as an offset from this address.
+ *
+ * @pcie_port: PCIe port the IO is for
+ *
+ * Returns 64bit Octeon IO base address for read/write
+ */
+static inline uint64_t cvmx_pcie_get_mem_base_address(int pcie_port)
+{
+	union cvmx_pcie_address pcie_addr;
+	pcie_addr.u64 = 0;
+	pcie_addr.mem.upper = 0;
+	pcie_addr.mem.io = 1;
+	pcie_addr.mem.did = 3;
+	pcie_addr.mem.subdid = 3 + pcie_port;
+	return pcie_addr.u64;
+}
+
+/**
+ * Size of the Mem address region returned at address
+ * cvmx_pcie_get_mem_base_address()
+ *
+ * @pcie_port: PCIe port the IO is for
+ *
+ * Returns Size of the Mem window
+ */
+static inline uint64_t cvmx_pcie_get_mem_size(int pcie_port)
+{
+	return 1ull << 36;
+}
+
+/**
+ * Read a PCIe config space register indirectly. This is used for
+ * registers of the form PCIEEP_CFG??? and PCIERC?_CFG???.
+ *
+ * @pcie_port:  PCIe port to read from
+ * @cfg_offset: Address to read
+ *
+ * Returns Value read
+ */
+static uint32_t cvmx_pcie_cfgx_read(int pcie_port, uint32_t cfg_offset)
+{
+	union cvmx_pescx_cfg_rd pescx_cfg_rd;
+	pescx_cfg_rd.u64 = 0;
+	pescx_cfg_rd.s.addr = cfg_offset;
+	cvmx_write_csr(CVMX_PESCX_CFG_RD(pcie_port), pescx_cfg_rd.u64);
+	pescx_cfg_rd.u64 = cvmx_read_csr(CVMX_PESCX_CFG_RD(pcie_port));
+	return pescx_cfg_rd.s.data;
+}
+
+/**
+ * Write a PCIe config space register indirectly. This is used for
+ * registers of the form PCIEEP_CFG??? and PCIERC?_CFG???.
+ *
+ * @pcie_port:  PCIe port to write to
+ * @cfg_offset: Address to write
+ * @val:        Value to write
+ */
+static void cvmx_pcie_cfgx_write(int pcie_port, uint32_t cfg_offset,
+				 uint32_t val)
+{
+	union cvmx_pescx_cfg_wr pescx_cfg_wr;
+	pescx_cfg_wr.u64 = 0;
+	pescx_cfg_wr.s.addr = cfg_offset;
+	pescx_cfg_wr.s.data = val;
+	cvmx_write_csr(CVMX_PESCX_CFG_WR(pcie_port), pescx_cfg_wr.u64);
+}
+
+/**
+ * Build a PCIe config space request address for a device
+ *
+ * @pcie_port: PCIe port to access
+ * @bus:       Sub bus
+ * @dev:       Device ID
+ * @fn:        Device sub function
+ * @reg:       Register to access
+ *
+ * Returns 64bit Octeon IO address
+ */
+static inline uint64_t __cvmx_pcie_build_config_addr(int pcie_port, int bus,
+						     int dev, int fn, int reg)
+{
+	union cvmx_pcie_address pcie_addr;
+	union cvmx_pciercx_cfg006 pciercx_cfg006;
+
+	pciercx_cfg006.u32 =
+	    cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG006(pcie_port));
+	if ((bus <= pciercx_cfg006.s.pbnum) && (dev != 0))
+		return 0;
+
+	pcie_addr.u64 = 0;
+	pcie_addr.config.upper = 2;
+	pcie_addr.config.io = 1;
+	pcie_addr.config.did = 3;
+	pcie_addr.config.subdid = 1;
+	pcie_addr.config.es = 1;
+	pcie_addr.config.port = pcie_port;
+	pcie_addr.config.ty = (bus > pciercx_cfg006.s.pbnum);
+	pcie_addr.config.bus = bus;
+	pcie_addr.config.dev = dev;
+	pcie_addr.config.func = fn;
+	pcie_addr.config.reg = reg;
+	return pcie_addr.u64;
+}
+
+/**
+ * Read 8bits from a Device's config space
+ *
+ * @pcie_port: PCIe port the device is on
+ * @bus:       Sub bus
+ * @dev:       Device ID
+ * @fn:        Device sub function
+ * @reg:       Register to access
+ *
+ * Returns Result of the read
+ */
+static uint8_t cvmx_pcie_config_read8(int pcie_port, int bus, int dev,
+				      int fn, int reg)
+{
+	uint64_t address =
+	    __cvmx_pcie_build_config_addr(pcie_port, bus, dev, fn, reg);
+	if (address)
+		return cvmx_read64_uint8(address);
+	else
+		return 0xff;
+}
+
+/**
+ * Read 16bits from a Device's config space
+ *
+ * @pcie_port: PCIe port the device is on
+ * @bus:       Sub bus
+ * @dev:       Device ID
+ * @fn:        Device sub function
+ * @reg:       Register to access
+ *
+ * Returns Result of the read
+ */
+static uint16_t cvmx_pcie_config_read16(int pcie_port, int bus, int dev,
+					int fn, int reg)
+{
+	uint64_t address =
+	    __cvmx_pcie_build_config_addr(pcie_port, bus, dev, fn, reg);
+	if (address)
+		return le16_to_cpu(cvmx_read64_uint16(address));
+	else
+		return 0xffff;
+}
+
+/**
+ * Read 32bits from a Device's config space
+ *
+ * @pcie_port: PCIe port the device is on
+ * @bus:       Sub bus
+ * @dev:       Device ID
+ * @fn:        Device sub function
+ * @reg:       Register to access
+ *
+ * Returns Result of the read
+ */
+static uint32_t cvmx_pcie_config_read32(int pcie_port, int bus, int dev,
+					int fn, int reg)
+{
+	uint64_t address =
+	    __cvmx_pcie_build_config_addr(pcie_port, bus, dev, fn, reg);
+	if (address)
+		return le32_to_cpu(cvmx_read64_uint32(address));
+	else
+		return 0xffffffff;
+}
+
+/**
+ * Write 8bits to a Device's config space
+ *
+ * @pcie_port: PCIe port the device is on
+ * @bus:       Sub bus
+ * @dev:       Device ID
+ * @fn:        Device sub function
+ * @reg:       Register to access
+ * @val:       Value to write
+ */
+static void cvmx_pcie_config_write8(int pcie_port, int bus, int dev, int fn,
+				    int reg, uint8_t val)
+{
+	uint64_t address =
+	    __cvmx_pcie_build_config_addr(pcie_port, bus, dev, fn, reg);
+	if (address)
+		cvmx_write64_uint8(address, val);
+}
+
+/**
+ * Write 16bits to a Device's config space
+ *
+ * @pcie_port: PCIe port the device is on
+ * @bus:       Sub bus
+ * @dev:       Device ID
+ * @fn:        Device sub function
+ * @reg:       Register to access
+ * @val:       Value to write
+ */
+static void cvmx_pcie_config_write16(int pcie_port, int bus, int dev, int fn,
+				     int reg, uint16_t val)
+{
+	uint64_t address =
+	    __cvmx_pcie_build_config_addr(pcie_port, bus, dev, fn, reg);
+	if (address)
+		cvmx_write64_uint16(address, cpu_to_le16(val));
+}
+
+/**
+ * Write 32bits to a Device's config space
+ *
+ * @pcie_port: PCIe port the device is on
+ * @bus:       Sub bus
+ * @dev:       Device ID
+ * @fn:        Device sub function
+ * @reg:       Register to access
+ * @val:       Value to write
+ */
+static void cvmx_pcie_config_write32(int pcie_port, int bus, int dev, int fn,
+				     int reg, uint32_t val)
+{
+	uint64_t address =
+	    __cvmx_pcie_build_config_addr(pcie_port, bus, dev, fn, reg);
+	if (address)
+		cvmx_write64_uint32(address, cpu_to_le32(val));
+}
+
+/**
+ * Initialize the RC config space CSRs
+ *
+ * @pcie_port: PCIe port to initialize
+ */
+static void __cvmx_pcie_rc_initialize_config_space(int pcie_port)
+{
+	union cvmx_pciercx_cfg030 pciercx_cfg030;
+	union cvmx_npei_ctl_status2 npei_ctl_status2;
+	union cvmx_pciercx_cfg070 pciercx_cfg070;
+	union cvmx_pciercx_cfg001 pciercx_cfg001;
+	union cvmx_pciercx_cfg032 pciercx_cfg032;
+	union cvmx_pciercx_cfg006 pciercx_cfg006;
+	union cvmx_pciercx_cfg008 pciercx_cfg008;
+	union cvmx_pciercx_cfg009 pciercx_cfg009;
+	union cvmx_pciercx_cfg010 pciercx_cfg010;
+	union cvmx_pciercx_cfg011 pciercx_cfg011;
+	union cvmx_pciercx_cfg035 pciercx_cfg035;
+	union cvmx_pciercx_cfg075 pciercx_cfg075;
+	union cvmx_pciercx_cfg034 pciercx_cfg034;
+
+	/* Max Payload Size (PCIE*_CFG030[MPS]) */
+	/* Max Read Request Size (PCIE*_CFG030[MRRS]) */
+	/* Relaxed-order, no-snoop enables (PCIE*_CFG030[RO_EN,NS_EN] */
+	/* Error Message Enables (PCIE*_CFG030[CE_EN,NFE_EN,FE_EN,UR_EN]) */
+	pciercx_cfg030.u32 =
+		cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG030(pcie_port));
+	/*
+	 * Max payload size = 128 bytes for best Octeon DMA
+	 * performance.
+	 */
+	pciercx_cfg030.s.mps = 0;
+	/*
+	 * Max read request size = 128 bytes for best Octeon DMA
+	 * performance.
+	 */
+	pciercx_cfg030.s.mrrs = 0;
+	/* Enable relaxed ordering. */
+	pciercx_cfg030.s.ro_en = 1;
+	/* Enable no snoop. */
+	pciercx_cfg030.s.ns_en = 1;
+	/* Correctable error reporting enable. */
+	pciercx_cfg030.s.ce_en = 1;
+	/* Non-fatal error reporting enable. */
+	pciercx_cfg030.s.nfe_en = 1;
+	/* Fatal error reporting enable. */
+	pciercx_cfg030.s.fe_en = 1;
+	/* Unsupported request reporting enable. */
+	pciercx_cfg030.s.ur_en = 1;
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG030(pcie_port),
+			     pciercx_cfg030.u32);
+
+	/*
+	 * Max Payload Size (NPEI_CTL_STATUS2[MPS]) must match
+	 * PCIE*_CFG030[MPS]
+	 *
+	 * Max Read Request Size (NPEI_CTL_STATUS2[MRRS]) must not
+	 * exceed PCIE*_CFG030[MRRS].
+	 */
+	npei_ctl_status2.u64 = cvmx_read_csr(CVMX_PEXP_NPEI_CTL_STATUS2);
+	/* Max payload size = 128 bytes for best Octeon DMA performance */
+	npei_ctl_status2.s.mps = 0;
+	/* Max read request size = 128 bytes for best Octeon DMA performance */
+	npei_ctl_status2.s.mrrs = 0;
+	cvmx_write_csr(CVMX_PEXP_NPEI_CTL_STATUS2, npei_ctl_status2.u64);
+
+	/* ECRC Generation (PCIE*_CFG070[GE,CE]) */
+	pciercx_cfg070.u32 =
+		cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG070(pcie_port));
+	pciercx_cfg070.s.ge = 1;	/* ECRC generation enable. */
+	pciercx_cfg070.s.ce = 1;	/* ECRC check enable. */
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG070(pcie_port),
+			     pciercx_cfg070.u32);
+
+	/*
+	 * Access Enables (PCIE*_CFG001[MSAE,ME]) ME and MSAE should
+	 * always be set.
+	 *
+	 * Interrupt Disable (PCIE*_CFG001[I_DIS]) System Error
+	 * Message Enable (PCIE*_CFG001[SEE])
+	 */
+	pciercx_cfg001.u32 =
+		cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG001(pcie_port));
+	pciercx_cfg001.s.msae = 1;	/* Memory space enable. */
+	pciercx_cfg001.s.me = 1;	/* Bus master enable. */
+	pciercx_cfg001.s.i_dis = 1;	/* INTx assertion disable. */
+	pciercx_cfg001.s.see = 1;	/* SERR# enable */
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG001(pcie_port),
+			pciercx_cfg001.u32);
+
+	/* Advanced Error Recovery Message Enables */
+	/* (PCIE*_CFG066,PCIE*_CFG067,PCIE*_CFG069) */
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG066(pcie_port), 0);
+	/* Use CVMX_PCIERCX_CFG067 hardware default */
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG069(pcie_port), 0);
+
+	/* Active State Power Management (PCIE*_CFG032[ASLPC]) */
+	pciercx_cfg032.u32 =
+		cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG032(pcie_port));
+	pciercx_cfg032.s.aslpc = 0;	/* Active state Link PM control. */
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG032(pcie_port),
+			     pciercx_cfg032.u32);
+
+	/* Entrance Latencies (PCIE*_CFG451[L0EL,L1EL]) */
+
+	/*
+	 * Link Width Mode (PCIERCn_CFG452[LME]) - Set during
+	 * cvmx_pcie_rc_initialize_link()
+	 *
+	 * Primary Bus Number (PCIERCn_CFG006[PBNUM])
+	 *
+	 * We set the primary bus number to 1 so IDT bridges are
+	 * happy. They don't like zero.
+	 */
+	pciercx_cfg006.u32 = 0;
+	pciercx_cfg006.s.pbnum = 1;
+	pciercx_cfg006.s.sbnum = 1;
+	pciercx_cfg006.s.subbnum = 1;
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG006(pcie_port),
+			     pciercx_cfg006.u32);
+
+	/*
+	 * Memory-mapped I/O BAR (PCIERCn_CFG008)
+	 * Most applications should disable the memory-mapped I/O BAR by
+	 * setting PCIERCn_CFG008[ML_ADDR] < PCIERCn_CFG008[MB_ADDR]
+	 */
+	pciercx_cfg008.u32 = 0;
+	pciercx_cfg008.s.mb_addr = 0x100;
+	pciercx_cfg008.s.ml_addr = 0;
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG008(pcie_port),
+			     pciercx_cfg008.u32);
+
+	/*
+	 * Prefetchable BAR (PCIERCn_CFG009,PCIERCn_CFG010,PCIERCn_CFG011)
+	 * Most applications should disable the prefetchable BAR by setting
+	 * PCIERCn_CFG011[UMEM_LIMIT],PCIERCn_CFG009[LMEM_LIMIT] <
+	 * PCIERCn_CFG010[UMEM_BASE],PCIERCn_CFG009[LMEM_BASE]
+	 */
+	pciercx_cfg009.u32 =
+		cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG009(pcie_port));
+	pciercx_cfg010.u32 =
+		cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG010(pcie_port));
+	pciercx_cfg011.u32 =
+		cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG011(pcie_port));
+	pciercx_cfg009.s.lmem_base = 0x100;
+	pciercx_cfg009.s.lmem_limit = 0;
+	pciercx_cfg010.s.umem_base = 0x100;
+	pciercx_cfg011.s.umem_limit = 0;
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG009(pcie_port),
+			     pciercx_cfg009.u32);
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG010(pcie_port),
+			     pciercx_cfg010.u32);
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG011(pcie_port),
+			     pciercx_cfg011.u32);
+
+	/*
+	 * System Error Interrupt Enables (PCIERCn_CFG035[SECEE,SEFEE,SENFEE])
+	 * PME Interrupt Enables (PCIERCn_CFG035[PMEIE])
+	 */
+	pciercx_cfg035.u32 =
+		cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG035(pcie_port));
+	/* System error on correctable error enable. */
+	pciercx_cfg035.s.secee = 1;
+	/* System error on fatal error enable. */
+	pciercx_cfg035.s.sefee = 1;
+	/* System error on non-fatal error enable. */
+	pciercx_cfg035.s.senfee = 1;
+	/* PME interrupt enable. */
+	pciercx_cfg035.s.pmeie = 1;
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG035(pcie_port),
+			     pciercx_cfg035.u32);
+
+	/*
+	 * Advanced Error Recovery Interrupt Enables
+	 * (PCIERCn_CFG075[CERE,NFERE,FERE])
+	 */
+	pciercx_cfg075.u32 =
+		cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG075(pcie_port));
+	/* Correctable error reporting enable. */
+	pciercx_cfg075.s.cere = 1;
+	/* Non-fatal error reporting enable. */
+	pciercx_cfg075.s.nfere = 1;
+	/* Fatal error reporting enable. */
+	pciercx_cfg075.s.fere = 1;
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG075(pcie_port),
+			     pciercx_cfg075.u32);
+
+	/* HP Interrupt Enables (PCIERCn_CFG034[HPINT_EN],
+	 * PCIERCn_CFG034[DLLS_EN,CCINT_EN])
+	 */
+	pciercx_cfg034.u32 =
+		cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG034(pcie_port));
+	/* Hot-plug interrupt enable. */
+	pciercx_cfg034.s.hpint_en = 1;
+	/* Data Link Layer state changed enable */
+	pciercx_cfg034.s.dlls_en = 1;
+	/* Command completed interrupt enable. */
+	pciercx_cfg034.s.ccint_en = 1;
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG034(pcie_port),
+			     pciercx_cfg034.u32);
+}
+
+/**
+ * Initialize a host mode PCIe link. This function takes a PCIe
+ * port from reset to a link up state. Software can then begin
+ * configuring the rest of the link.
+ *
+ * @pcie_port: PCIe port to initialize
+ *
+ * Returns Zero on success
+ */
+static int __cvmx_pcie_rc_initialize_link(int pcie_port)
+{
+	uint64_t start_cycle;
+	union cvmx_pescx_ctl_status pescx_ctl_status;
+	union cvmx_pciercx_cfg452 pciercx_cfg452;
+	union cvmx_pciercx_cfg032 pciercx_cfg032;
+	union cvmx_pciercx_cfg448 pciercx_cfg448;
+
+	/* Set the lane width */
+	pciercx_cfg452.u32 =
+	    cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG452(pcie_port));
+	pescx_ctl_status.u64 = cvmx_read_csr(CVMX_PESCX_CTL_STATUS(pcie_port));
+	if (pescx_ctl_status.s.qlm_cfg == 0) {
+		/* We're in 8 lane (56XX) or 4 lane (54XX) mode */
+		pciercx_cfg452.s.lme = 0xf;
+	} else {
+		/* We're in 4 lane (56XX) or 2 lane (52XX) mode */
+		pciercx_cfg452.s.lme = 0x7;
+	}
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG452(pcie_port),
+			     pciercx_cfg452.u32);
+
+	/*
+	 * CN52XX pass 1.x has an errata where length mismatches on UR
+	 * responses can cause bus errors on 64bit memory
+	 * reads. Turning off length error checking fixes this.
+	 */
+	if (OCTEON_IS_MODEL(OCTEON_CN52XX_PASS1_X)) {
+		union cvmx_pciercx_cfg455 pciercx_cfg455;
+		pciercx_cfg455.u32 =
+		    cvmx_pcie_cfgx_read(pcie_port,
+					CVMX_PCIERCX_CFG455(pcie_port));
+		pciercx_cfg455.s.m_cpl_len_err = 1;
+		cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG455(pcie_port),
+				     pciercx_cfg455.u32);
+	}
+
+	/* Lane swap needs to be manually enabled for CN52XX */
+	if (OCTEON_IS_MODEL(OCTEON_CN52XX) && (pcie_port == 1)) {
+		pescx_ctl_status.s.lane_swp = 1;
+		cvmx_write_csr(CVMX_PESCX_CTL_STATUS(pcie_port),
+			       pescx_ctl_status.u64);
+	}
+
+	/* Bring up the link */
+	pescx_ctl_status.u64 = cvmx_read_csr(CVMX_PESCX_CTL_STATUS(pcie_port));
+	pescx_ctl_status.s.lnk_enb = 1;
+	cvmx_write_csr(CVMX_PESCX_CTL_STATUS(pcie_port), pescx_ctl_status.u64);
+
+	/*
+	 * CN52XX pass 1.0: Due to a bug in 2nd order CDR, it needs to
+	 * be disabled.
+	 */
+	if (OCTEON_IS_MODEL(OCTEON_CN52XX_PASS1_0))
+		__cvmx_helper_errata_qlm_disable_2nd_order_cdr(0);
+
+	/* Wait for the link to come up */
+	cvmx_dprintf("PCIe: Waiting for port %d link\n", pcie_port);
+	start_cycle = cvmx_get_cycle();
+	do {
+		if (cvmx_get_cycle() - start_cycle >
+		    2 * cvmx_sysinfo_get()->cpu_clock_hz) {
+			cvmx_dprintf("PCIe: Port %d link timeout\n",
+				     pcie_port);
+			return -1;
+		}
+		cvmx_wait(10000);
+		pciercx_cfg032.u32 =
+		    cvmx_pcie_cfgx_read(pcie_port,
+					CVMX_PCIERCX_CFG032(pcie_port));
+	} while (pciercx_cfg032.s.dlla == 0);
+
+	/* Display the link status */
+	cvmx_dprintf("PCIe: Port %d link active, %d lanes\n", pcie_port,
+		     pciercx_cfg032.s.nlw);
+
+	/*
+	 * Update the Replay Time Limit. Empirically, some PCIe
+	 * devices take a little longer to respond than expected under
+	 * load. As a workaround for this we configure the Replay Time
+	 * Limit to the value expected for a 512 byte MPS instead of
+	 * our actual 256 byte MPS. The numbers below are directly
+	 * from the PCIe spec table 3-4.
+	 */
+	pciercx_cfg448.u32 =
+	    cvmx_pcie_cfgx_read(pcie_port, CVMX_PCIERCX_CFG448(pcie_port));
+	switch (pciercx_cfg032.s.nlw) {
+	case 1:		/* 1 lane */
+		pciercx_cfg448.s.rtl = 1677;
+		break;
+	case 2:		/* 2 lanes */
+		pciercx_cfg448.s.rtl = 867;
+		break;
+	case 4:		/* 4 lanes */
+		pciercx_cfg448.s.rtl = 462;
+		break;
+	case 8:		/* 8 lanes */
+		pciercx_cfg448.s.rtl = 258;
+		break;
+	}
+	cvmx_pcie_cfgx_write(pcie_port, CVMX_PCIERCX_CFG448(pcie_port),
+			     pciercx_cfg448.u32);
+
+	return 0;
+}
+
+/**
+ * Initialize a PCIe port for use in host(RC) mode. It doesn't
+ * enumerate the bus.
+ *
+ * @pcie_port: PCIe port to initialize
+ *
+ * Returns Zero on success
+ */
+static int cvmx_pcie_rc_initialize(int pcie_port)
+{
+	int i;
+	union cvmx_ciu_soft_prst ciu_soft_prst;
+	union cvmx_pescx_bist_status pescx_bist_status;
+	union cvmx_pescx_bist_status2 pescx_bist_status2;
+	union cvmx_npei_ctl_status npei_ctl_status;
+	union cvmx_npei_mem_access_ctl npei_mem_access_ctl;
+	union cvmx_npei_mem_access_subidx mem_access_subid;
+	union cvmx_npei_dbg_data npei_dbg_data;
+	union cvmx_pescx_ctl_status2 pescx_ctl_status2;
+
+	/*
+	 * Make sure we aren't trying to setup a target mode interface
+	 * in host mode.
+	 */
+	npei_ctl_status.u64 = cvmx_read_csr(CVMX_PEXP_NPEI_CTL_STATUS);
+	if ((pcie_port == 0) && !npei_ctl_status.s.host_mode) {
+		cvmx_dprintf("PCIe: ERROR: cvmx_pcie_rc_initialize() called "
+			     "on port0, but port0 is not in host mode\n");
+		return -1;
+	}
+
+	/*
+	 * Make sure a CN52XX isn't trying to bring up port 1 when it
+	 * is disabled.
+	 */
+	if (OCTEON_IS_MODEL(OCTEON_CN52XX)) {
+		npei_dbg_data.u64 = cvmx_read_csr(CVMX_PEXP_NPEI_DBG_DATA);
+		if ((pcie_port == 1) && npei_dbg_data.cn52xx.qlm0_link_width) {
+			cvmx_dprintf("PCIe: ERROR: cvmx_pcie_rc_initialize() "
+				     "called on port1, but port1 is "
+				     "disabled\n");
+			return -1;
+		}
+	}
+
+	/*
+	 * PCIe switch arbitration mode. '0' == fixed priority NPEI,
+	 * PCIe0, then PCIe1. '1' == round robin.
+	 */
+	npei_ctl_status.s.arb = 1;
+	/* Allow up to 0x20 config retries */
+	npei_ctl_status.s.cfg_rtry = 0x20;
+	/*
+	 * CN52XX pass1.x has an errata where P0_NTAGS and P1_NTAGS
+	 * don't reset.
+	 */
+	if (OCTEON_IS_MODEL(OCTEON_CN52XX_PASS1_X)) {
+		npei_ctl_status.s.p0_ntags = 0x20;
+		npei_ctl_status.s.p1_ntags = 0x20;
+	}
+	cvmx_write_csr(CVMX_PEXP_NPEI_CTL_STATUS, npei_ctl_status.u64);
+
+	/* Bring the PCIe out of reset */
+	if (cvmx_sysinfo_get()->board_type == CVMX_BOARD_TYPE_EBH5200) {
+		/*
+		 * The EBH5200 board swapped the PCIe reset lines on
+		 * the board. As a workaround for this bug, we bring
+		 * both PCIe ports out of reset at the same time
+		 * instead of on separate calls. So for port 0, we
+		 * bring both out of reset and do nothing on port 1.
+		 */
+		if (pcie_port == 0) {
+			ciu_soft_prst.u64 = cvmx_read_csr(CVMX_CIU_SOFT_PRST);
+			/*
+			 * After a chip reset the PCIe will also be in
+			 * reset. If it isn't, most likely someone is
+			 * trying to init it again without a proper
+			 * PCIe reset.
+			 */
+			if (ciu_soft_prst.s.soft_prst == 0) {
+				/* Reset the ports */
+				ciu_soft_prst.s.soft_prst = 1;
+				cvmx_write_csr(CVMX_CIU_SOFT_PRST,
+					       ciu_soft_prst.u64);
+				ciu_soft_prst.u64 =
+				    cvmx_read_csr(CVMX_CIU_SOFT_PRST1);
+				ciu_soft_prst.s.soft_prst = 1;
+				cvmx_write_csr(CVMX_CIU_SOFT_PRST1,
+					       ciu_soft_prst.u64);
+				/* Wait until pcie resets the ports. */
+				udelay(2000);
+			}
+			ciu_soft_prst.u64 = cvmx_read_csr(CVMX_CIU_SOFT_PRST1);
+			ciu_soft_prst.s.soft_prst = 0;
+			cvmx_write_csr(CVMX_CIU_SOFT_PRST1, ciu_soft_prst.u64);
+			ciu_soft_prst.u64 = cvmx_read_csr(CVMX_CIU_SOFT_PRST);
+			ciu_soft_prst.s.soft_prst = 0;
+			cvmx_write_csr(CVMX_CIU_SOFT_PRST, ciu_soft_prst.u64);
+		}
+	} else {
+		/*
+		 * The normal case: The PCIe ports are completely
+		 * separate and can be brought out of reset
+		 * independently.
+		 */
+		if (pcie_port)
+			ciu_soft_prst.u64 = cvmx_read_csr(CVMX_CIU_SOFT_PRST1);
+		else
+			ciu_soft_prst.u64 = cvmx_read_csr(CVMX_CIU_SOFT_PRST);
+		/*
+		 * After a chip reset the PCIe will also be in
+		 * reset. If it isn't, most likely someone is trying
+		 * to init it again without a proper PCIe reset.
+		 */
+		if (ciu_soft_prst.s.soft_prst == 0) {
+			/* Reset the port */
+			ciu_soft_prst.s.soft_prst = 1;
+			if (pcie_port)
+				cvmx_write_csr(CVMX_CIU_SOFT_PRST1,
+					       ciu_soft_prst.u64);
+			else
+				cvmx_write_csr(CVMX_CIU_SOFT_PRST,
+					       ciu_soft_prst.u64);
+			/* Wait until pcie resets the ports. */
+			udelay(2000);
+		}
+		if (pcie_port) {
+			ciu_soft_prst.u64 = cvmx_read_csr(CVMX_CIU_SOFT_PRST1);
+			ciu_soft_prst.s.soft_prst = 0;
+			cvmx_write_csr(CVMX_CIU_SOFT_PRST1, ciu_soft_prst.u64);
+		} else {
+			ciu_soft_prst.u64 = cvmx_read_csr(CVMX_CIU_SOFT_PRST);
+			ciu_soft_prst.s.soft_prst = 0;
+			cvmx_write_csr(CVMX_CIU_SOFT_PRST, ciu_soft_prst.u64);
+		}
+	}
+
+	/*
+	 * Wait for PCIe reset to complete. Due to errata PCIE-700, we
+	 * don't poll PESCX_CTL_STATUS2[PCIERST], but simply wait a
+	 * fixed number of cycles.
+	 */
+	cvmx_wait(400000);
+
+	/* PESCX_BIST_STATUS2[PCLK_RUN] was missing on pass 1 of CN56XX and
+	   CN52XX, so we only probe it on newer chips */
+	if (!OCTEON_IS_MODEL(OCTEON_CN56XX_PASS1_X)
+	    && !OCTEON_IS_MODEL(OCTEON_CN52XX_PASS1_X)) {
+		/* Clear PCLK_RUN so we can check if the clock is running */
+		pescx_ctl_status2.u64 =
+		    cvmx_read_csr(CVMX_PESCX_CTL_STATUS2(pcie_port));
+		pescx_ctl_status2.s.pclk_run = 1;
+		cvmx_write_csr(CVMX_PESCX_CTL_STATUS2(pcie_port),
+			       pescx_ctl_status2.u64);
+		/*
+		 * Now that we cleared PCLK_RUN, wait for it to be set
+		 * again telling us the clock is running.
+		 */
+		if (CVMX_WAIT_FOR_FIELD64(CVMX_PESCX_CTL_STATUS2(pcie_port),
+					  union cvmx_pescx_ctl_status2,
+					  pclk_run, ==, 1, 10000)) {
+			cvmx_dprintf("PCIe: Port %d isn't clocked, skipping.\n",
+				     pcie_port);
+			return -1;
+		}
+	}
+
+	/*
+	 * Check and make sure PCIe came out of reset. If it doesn't
+	 * the board probably hasn't wired the clocks up and the
+	 * interface should be skipped.
+	 */
+	pescx_ctl_status2.u64 =
+	    cvmx_read_csr(CVMX_PESCX_CTL_STATUS2(pcie_port));
+	if (pescx_ctl_status2.s.pcierst) {
+		cvmx_dprintf("PCIe: Port %d stuck in reset, skipping.\n",
+			     pcie_port);
+		return -1;
+	}
+
+	/*
+	 * Check BIST2 status. If any bits are set skip this interface. This
+	 * is an attempt to catch PCIE-813 on pass 1 parts.
+	 */
+	pescx_bist_status2.u64 =
+	    cvmx_read_csr(CVMX_PESCX_BIST_STATUS2(pcie_port));
+	if (pescx_bist_status2.u64) {
+		cvmx_dprintf("PCIe: Port %d BIST2 failed. Most likely this "
+			     "port isn't hooked up, skipping.\n",
+			     pcie_port);
+		return -1;
+	}
+
+	/* Check BIST status */
+	pescx_bist_status.u64 =
+	    cvmx_read_csr(CVMX_PESCX_BIST_STATUS(pcie_port));
+	if (pescx_bist_status.u64)
+		cvmx_dprintf("PCIe: BIST FAILED for port %d (0x%016llx)\n",
+			     pcie_port, CAST64(pescx_bist_status.u64));
+
+	/* Initialize the config space CSRs */
+	__cvmx_pcie_rc_initialize_config_space(pcie_port);
+
+	/* Bring the link up */
+	if (__cvmx_pcie_rc_initialize_link(pcie_port)) {
+		cvmx_dprintf
+		    ("PCIe: ERROR: cvmx_pcie_rc_initialize_link() failed\n");
+		return -1;
+	}
+
+	/* Store merge control (NPEI_MEM_ACCESS_CTL[TIMER,MAX_WORD]) */
+	npei_mem_access_ctl.u64 = cvmx_read_csr(CVMX_PEXP_NPEI_MEM_ACCESS_CTL);
+	/* Allow 16 words to combine */
+	npei_mem_access_ctl.s.max_word = 0;
+	/* Wait up to 127 cycles for more data */
+	npei_mem_access_ctl.s.timer = 127;
+	cvmx_write_csr(CVMX_PEXP_NPEI_MEM_ACCESS_CTL, npei_mem_access_ctl.u64);
+
+	/* Setup Mem access SubDIDs */
+	mem_access_subid.u64 = 0;
+	/* Port the request is sent to. */
+	mem_access_subid.s.port = pcie_port;
+	/* Due to an errata on pass 1 chips, no merging is allowed. */
+	mem_access_subid.s.nmerge = 1;
+	/* Endian-swap for Reads. */
+	mem_access_subid.s.esr = 1;
+	/* Endian-swap for Writes. */
+	mem_access_subid.s.esw = 1;
+	/* No Snoop for Reads. */
+	mem_access_subid.s.nsr = 1;
+	/* No Snoop for Writes. */
+	mem_access_subid.s.nsw = 1;
+	/* Disable Relaxed Ordering for Reads. */
+	mem_access_subid.s.ror = 0;
+	/* Disable Relaxed Ordering for Writes. */
+	mem_access_subid.s.row = 0;
+	/* PCIe Adddress Bits <63:34>. */
+	mem_access_subid.s.ba = 0;
+
+	/*
+	 * Setup mem access 12-15 for port 0, 16-19 for port 1,
+	 * supplying 36 bits of address space.
+	 */
+	for (i = 12 + pcie_port * 4; i < 16 + pcie_port * 4; i++) {
+		cvmx_write_csr(CVMX_PEXP_NPEI_MEM_ACCESS_SUBIDX(i),
+			       mem_access_subid.u64);
+		/* Set each SUBID to extend the addressable range */
+		mem_access_subid.s.ba += 1;
+	}
+
+	/*
+	 * Disable the peer to peer forwarding register. This must be
+	 * setup by the OS after it enumerates the bus and assigns
+	 * addresses to the PCIe busses.
+	 */
+	for (i = 0; i < 4; i++) {
+		cvmx_write_csr(CVMX_PESCX_P2P_BARX_START(i, pcie_port), -1);
+		cvmx_write_csr(CVMX_PESCX_P2P_BARX_END(i, pcie_port), -1);
+	}
+
+	/* Set Octeon's BAR0 to decode 0-16KB. It overlaps with Bar2 */
+	cvmx_write_csr(CVMX_PESCX_P2N_BAR0_START(pcie_port), 0);
+
+	/*
+	 * Disable Octeon's BAR1. It isn't needed in RC mode since
+	 * BAR2 maps all of memory. BAR2 also maps 256MB-512MB into
+	 * the 2nd 256MB of memory.
+	 */
+	cvmx_write_csr(CVMX_PESCX_P2N_BAR1_START(pcie_port), -1);
+
+	/*
+	 * Set Octeon's BAR2 to decode 0-2^39. Bar0 and Bar1 take
+	 * precedence where they overlap. It also overlaps with the
+	 * device addresses, so make sure the peer to peer forwarding
+	 * is set right.
+	 */
+	cvmx_write_csr(CVMX_PESCX_P2N_BAR2_START(pcie_port), 0);
+
+	/*
+	 * Setup BAR2 attributes
+	 *
+	 * Relaxed Ordering (NPEI_CTL_PORTn[PTLP_RO,CTLP_RO, WAIT_COM])
+	 * - PTLP_RO,CTLP_RO should normally be set (except for debug).
+	 * - WAIT_COM=0 will likely work for all applications.
+	 *
+	 * Load completion relaxed ordering (NPEI_CTL_PORTn[WAITL_COM]).
+	 */
+	if (pcie_port) {
+		union cvmx_npei_ctl_port1 npei_ctl_port;
+		npei_ctl_port.u64 = cvmx_read_csr(CVMX_PEXP_NPEI_CTL_PORT1);
+		npei_ctl_port.s.bar2_enb = 1;
+		npei_ctl_port.s.bar2_esx = 1;
+		npei_ctl_port.s.bar2_cax = 0;
+		npei_ctl_port.s.ptlp_ro = 1;
+		npei_ctl_port.s.ctlp_ro = 1;
+		npei_ctl_port.s.wait_com = 0;
+		npei_ctl_port.s.waitl_com = 0;
+		cvmx_write_csr(CVMX_PEXP_NPEI_CTL_PORT1, npei_ctl_port.u64);
+	} else {
+		union cvmx_npei_ctl_port0 npei_ctl_port;
+		npei_ctl_port.u64 = cvmx_read_csr(CVMX_PEXP_NPEI_CTL_PORT0);
+		npei_ctl_port.s.bar2_enb = 1;
+		npei_ctl_port.s.bar2_esx = 1;
+		npei_ctl_port.s.bar2_cax = 0;
+		npei_ctl_port.s.ptlp_ro = 1;
+		npei_ctl_port.s.ctlp_ro = 1;
+		npei_ctl_port.s.wait_com = 0;
+		npei_ctl_port.s.waitl_com = 0;
+		cvmx_write_csr(CVMX_PEXP_NPEI_CTL_PORT0, npei_ctl_port.u64);
+	}
+	return 0;
+}
+
+
+/* Above was cvmx-pcie.c, below original pcie.c */
+
+
+/**
+ * Map a PCI device to the appropriate interrupt line
+ *
+ * @param dev    The Linux PCI device structure for the device to map
+ * @param slot   The slot number for this device on __BUS 0__. Linux
+ *               enumerates through all the bridges and figures out the
+ *               slot on Bus 0 where this device eventually hooks to.
+ * @param pin    The PCI interrupt pin read from the device, then swizzled
+ *               as it goes through each bridge.
+ * @return Interrupt number for the device
+ */
+int __init octeon_pcie_pcibios_map_irq(const struct pci_dev *dev,
+				       u8 slot, u8 pin)
+{
+	/*
+	 * The EBH5600 board with the PCI to PCIe bridge mistakenly
+	 * wires the first slot for both device id 2 and interrupt
+	 * A. According to the PCI spec, device id 2 should be C. The
+	 * following kludge attempts to fix this.
+	 */
+	if (strstr(octeon_board_type_string(), "EBH5600") &&
+	    dev->bus && dev->bus->parent) {
+		/*
+		 * Iterate all the way up the device chain and find
+		 * the root bus.
+		 */
+		while (dev->bus && dev->bus->parent)
+			dev = to_pci_dev(dev->bus->bridge);
+		/* If the root bus is number 0 and the PEX 8114 is the
+		 * root, assume we are behind the miswired bus. We
+		 * need to correct the swizzle level by two. Yuck.
+		 */
+		if ((dev->bus->number == 0) &&
+		    (dev->vendor == 0x10b5) && (dev->device == 0x8114)) {
+			/*
+			 * The pin field is one based, not zero. We
+			 * need to swizzle it by minus two.
+			 */
+			pin = ((pin - 3) & 3) + 1;
+		}
+	}
+	/*
+	 * The -1 is because pin starts with one, not zero. It might
+	 * be that this equation needs to include the slot number, but
+	 * I don't have hardware to check that against.
+	 */
+	return pin - 1 + OCTEON_IRQ_PCI_INT0;
+}
+
+/**
+ * Read a value from configuration space
+ *
+ * @param bus
+ * @param devfn
+ * @param reg
+ * @param size
+ * @param val
+ * @return
+ */
+static inline int octeon_pcie_read_config(int pcie_port, struct pci_bus *bus,
+					  unsigned int devfn, int reg, int size,
+					  u32 *val)
+{
+	union octeon_cvmemctl cvmmemctl;
+	union octeon_cvmemctl cvmmemctl_save;
+	int bus_number = bus->number;
+
+	/*
+	 * We need to force the bus number to be zero on the root
+	 * bus. Linux numbers the 2nd root bus to start after all
+	 * buses on root 0.
+	 */
+	if (bus->parent == NULL)
+		bus_number = 0;
+
+	/*
+	 * PCIe only has a single device connected to Octeon. It is
+	 * always device ID 0. Don't bother doing reads for other
+	 * device IDs on the first segment.
+	 */
+	if ((bus_number == 0) && (devfn >> 3 != 0))
+		return PCIBIOS_FUNC_NOT_SUPPORTED;
+
+	/*
+	 * The following is a workaround for the CN57XX, CN56XX,
+	 * CN55XX, and CN54XX errata with PCIe config reads from non
+	 * existent devices.  These chips will hang the PCIe link if a
+	 * config read is performed that causes a UR response.
+	 */
+	if (OCTEON_IS_MODEL(OCTEON_CN56XX_PASS1) ||
+	    OCTEON_IS_MODEL(OCTEON_CN56XX_PASS1_1)) {
+		/*
+		 * For our EBH5600 board, port 0 has a bridge with two
+		 * PCI-X slots. We need a new special checks to make
+		 * sure we only probe valid stuff.  The PCIe->PCI-X
+		 * bridge only respondes to device ID 0, function
+		 * 0-1
+		 */
+		if ((bus_number == 0) && (devfn >= 2))
+			return PCIBIOS_FUNC_NOT_SUPPORTED;
+		/*
+		 * The PCI-X slots are device ID 2,3. Choose one of
+		 * the below "if" blocks based on what is plugged into
+		 * the board.
+		 */
+#if 1
+		/* Use this option if you aren't using either slot */
+		if (bus_number == 1)
+			return PCIBIOS_FUNC_NOT_SUPPORTED;
+#elif 0
+		/*
+		 * Use this option if you are using the first slot but
+		 * not the second.
+		 */
+		if ((bus_number == 1) && (devfn >> 3 != 2))
+			return PCIBIOS_FUNC_NOT_SUPPORTED;
+#elif 0
+		/*
+		 * Use this option if you are using the second slot
+		 * but not the first.
+		 */
+		if ((bus_number == 1) && (devfn >> 3 != 3))
+			return PCIBIOS_FUNC_NOT_SUPPORTED;
+#elif 0
+		/* Use this opion if you are using both slots */
+		if ((bus_number == 1) &&
+		    !((devfn == (2 << 3)) || (devfn == (3 << 3))))
+			return PCIBIOS_FUNC_NOT_SUPPORTED;
+#endif
+
+		/*
+		 * Shorten the DID timeout so bus errors for PCIe
+		 * config reads from non existent devices happen
+		 * faster. This allows us to continue booting even if
+		 * the above "if" checks are wrong.  Once one of these
+		 * errors happens, the PCIe port is dead.
+		 */
+		cvmmemctl_save.u64 = __read_64bit_c0_register($11, 7);
+		cvmmemctl.u64 = cvmmemctl_save.u64;
+		cvmmemctl.s.didtto = 2;
+		__write_64bit_c0_register($11, 7, cvmmemctl.u64);
+	}
+
+	switch (size) {
+	case 4:
+		*val = cvmx_pcie_config_read32(pcie_port, bus_number,
+					       devfn >> 3, devfn & 0x7, reg);
+		break;
+	case 2:
+		*val = cvmx_pcie_config_read16(pcie_port, bus_number,
+					       devfn >> 3, devfn & 0x7, reg);
+		break;
+	case 1:
+		*val = cvmx_pcie_config_read8(pcie_port, bus_number, devfn >> 3,
+					      devfn & 0x7, reg);
+		break;
+	default:
+		return PCIBIOS_FUNC_NOT_SUPPORTED;
+	}
+
+	if (OCTEON_IS_MODEL(OCTEON_CN56XX_PASS1) ||
+	    OCTEON_IS_MODEL(OCTEON_CN56XX_PASS1_1))
+		__write_64bit_c0_register($11, 7, cvmmemctl_save.u64);
+	return PCIBIOS_SUCCESSFUL;
+}
+
+static int octeon_pcie0_read_config(struct pci_bus *bus, unsigned int devfn,
+				    int reg, int size, u32 *val)
+{
+	return octeon_pcie_read_config(0, bus, devfn, reg, size, val);
+}
+
+static int octeon_pcie1_read_config(struct pci_bus *bus, unsigned int devfn,
+				    int reg, int size, u32 *val)
+{
+	return octeon_pcie_read_config(1, bus, devfn, reg, size, val);
+}
+
+
+
+/**
+ * Write a value to PCI configuration space
+ *
+ * @param bus
+ * @param devfn
+ * @param reg
+ * @param size
+ * @param val
+ * @return
+ */
+static inline int octeon_pcie_write_config(int pcie_port, struct pci_bus *bus,
+					   unsigned int devfn, int reg,
+					   int size, u32 val)
+{
+	int bus_number = bus->number;
+	/*
+	 * We need to force the bus number to be zero on the root
+	 * bus. Linux numbers the 2nd root bus to start after all
+	 * busses on root 0.
+	 */
+	if (bus->parent == NULL)
+		bus_number = 0;
+
+	switch (size) {
+	case 4:
+		cvmx_pcie_config_write32(pcie_port, bus_number, devfn >> 3,
+					 devfn & 0x7, reg, val);
+		return PCIBIOS_SUCCESSFUL;
+	case 2:
+		cvmx_pcie_config_write16(pcie_port, bus_number, devfn >> 3,
+					 devfn & 0x7, reg, val);
+		return PCIBIOS_SUCCESSFUL;
+	case 1:
+		cvmx_pcie_config_write8(pcie_port, bus_number, devfn >> 3,
+					devfn & 0x7, reg, val);
+		return PCIBIOS_SUCCESSFUL;
+	}
+#if PCI_CONFIG_SPACE_DELAY
+	udelay(PCI_CONFIG_SPACE_DELAY);
+#endif
+	return PCIBIOS_FUNC_NOT_SUPPORTED;
+}
+
+static int octeon_pcie0_write_config(struct pci_bus *bus, unsigned int devfn,
+				     int reg, int size, u32 val)
+{
+	return octeon_pcie_write_config(0, bus, devfn, reg, size, val);
+}
+
+static int octeon_pcie1_write_config(struct pci_bus *bus, unsigned int devfn,
+				     int reg, int size, u32 val)
+{
+	return octeon_pcie_write_config(1, bus, devfn, reg, size, val);
+}
+
+static struct pci_ops octeon_pcie0_ops = {
+	octeon_pcie0_read_config,
+	octeon_pcie0_write_config,
+};
+
+static struct resource octeon_pcie0_mem_resource = {
+	.name = "Octeon PCIe0 MEM",
+	.flags = IORESOURCE_MEM,
+};
+
+static struct resource octeon_pcie0_io_resource = {
+	.name = "Octeon PCIe0 IO",
+	.flags = IORESOURCE_IO,
+};
+
+static struct pci_controller octeon_pcie0_controller = {
+	.pci_ops = &octeon_pcie0_ops,
+	.mem_resource = &octeon_pcie0_mem_resource,
+	.io_resource = &octeon_pcie0_io_resource,
+};
+
+static struct pci_ops octeon_pcie1_ops = {
+	octeon_pcie1_read_config,
+	octeon_pcie1_write_config,
+};
+
+static struct resource octeon_pcie1_mem_resource = {
+	.name = "Octeon PCIe1 MEM",
+	.flags = IORESOURCE_MEM,
+};
+
+static struct resource octeon_pcie1_io_resource = {
+	.name = "Octeon PCIe1 IO",
+	.flags = IORESOURCE_IO,
+};
+
+static struct pci_controller octeon_pcie1_controller = {
+	.pci_ops = &octeon_pcie1_ops,
+	.mem_resource = &octeon_pcie1_mem_resource,
+	.io_resource = &octeon_pcie1_io_resource,
+};
+
+
+/**
+ * Initialize the Octeon PCIe controllers
+ *
+ * @return
+ */
+static int __init octeon_pcie_setup(void)
+{
+	union cvmx_npei_ctl_status npei_ctl_status;
+	int result;
+
+	/* These chips don't have PCIe */
+	if (!octeon_has_feature(OCTEON_FEATURE_PCIE))
+		return 0;
+
+	/* Point pcibios_map_irq() to the PCIe version of it */
+	octeon_pcibios_map_irq = octeon_pcie_pcibios_map_irq;
+
+	/* Use the PCIe based DMA mappings */
+	octeon_dma_bar_type = OCTEON_DMA_BAR_TYPE_PCIE;
+
+	/*
+	 * PCIe I/O range. It is based on port 0 but includes up until
+	 * port 1's end.
+	 */
+	set_io_port_base(CVMX_ADD_IO_SEG(cvmx_pcie_get_io_base_address(0)));
+	ioport_resource.start = 0;
+	ioport_resource.end =
+		cvmx_pcie_get_io_base_address(1) -
+		cvmx_pcie_get_io_base_address(0) + cvmx_pcie_get_io_size(1) - 1;
+
+	npei_ctl_status.u64 = cvmx_read_csr(CVMX_PEXP_NPEI_CTL_STATUS);
+	if (npei_ctl_status.s.host_mode) {
+		pr_notice("PCIe: Initializing port 0\n");
+		result = cvmx_pcie_rc_initialize(0);
+		if (result == 0) {
+			/* Memory offsets are physical addresses */
+			octeon_pcie0_controller.mem_offset =
+				cvmx_pcie_get_mem_base_address(0);
+			/* IO offsets are Mips virtual addresses */
+			octeon_pcie0_controller.io_map_base =
+				CVMX_ADD_IO_SEG(cvmx_pcie_get_io_base_address
+						(0));
+			octeon_pcie0_controller.io_offset = 0;
+			/*
+			 * To keep things similar to PCI, we start
+			 * device addresses at the same place as PCI
+			 * uisng big bar support. This normally
+			 * translates to 4GB-256MB, which is the same
+			 * as most x86 PCs.
+			 */
+			octeon_pcie0_controller.mem_resource->start =
+				cvmx_pcie_get_mem_base_address(0) +
+				(4ul << 30) - (OCTEON_PCI_BAR1_HOLE_SIZE << 20);
+			octeon_pcie0_controller.mem_resource->end =
+				cvmx_pcie_get_mem_base_address(0) +
+				cvmx_pcie_get_mem_size(0) - 1;
+			/*
+			 * Ports must be above 16KB for the ISA bus
+			 * filtering in the PCI-X to PCI bridge.
+			 */
+			octeon_pcie0_controller.io_resource->start = 4 << 10;
+			octeon_pcie0_controller.io_resource->end =
+				cvmx_pcie_get_io_size(0) - 1;
+			register_pci_controller(&octeon_pcie0_controller);
+		}
+	} else {
+		pr_notice("PCIe: Port 0 in endpoint mode, skipping.\n");
+	}
+
+	/* Skip the 2nd port on CN52XX if port 0 is in 4 lane mode */
+	if (OCTEON_IS_MODEL(OCTEON_CN52XX)) {
+		union cvmx_npei_dbg_data npei_dbg_data;
+		npei_dbg_data.u64 = cvmx_read_csr(CVMX_PEXP_NPEI_DBG_DATA);
+		if (npei_dbg_data.cn52xx.qlm0_link_width)
+			return 0;
+	}
+
+	pr_notice("PCIe: Initializing port 1\n");
+	result = cvmx_pcie_rc_initialize(1);
+	if (result == 0) {
+		/* Memory offsets are physical addresses */
+		octeon_pcie1_controller.mem_offset =
+			cvmx_pcie_get_mem_base_address(1);
+		/* IO offsets are Mips virtual addresses */
+		octeon_pcie1_controller.io_map_base =
+			CVMX_ADD_IO_SEG(cvmx_pcie_get_io_base_address(1));
+		octeon_pcie1_controller.io_offset =
+			cvmx_pcie_get_io_base_address(1) -
+			cvmx_pcie_get_io_base_address(0);
+		/*
+		 * To keep things similar to PCI, we start device
+		 * addresses at the same place as PCI uisng big bar
+		 * support. This normally translates to 4GB-256MB,
+		 * which is the same as most x86 PCs.
+		 */
+		octeon_pcie1_controller.mem_resource->start =
+			cvmx_pcie_get_mem_base_address(1) + (4ul << 30) -
+			(OCTEON_PCI_BAR1_HOLE_SIZE << 20);
+		octeon_pcie1_controller.mem_resource->end =
+			cvmx_pcie_get_mem_base_address(1) +
+			cvmx_pcie_get_mem_size(1) - 1;
+		/*
+		 * Ports must be above 16KB for the ISA bus filtering
+		 * in the PCI-X to PCI bridge.
+		 */
+		octeon_pcie1_controller.io_resource->start =
+			cvmx_pcie_get_io_base_address(1) -
+			cvmx_pcie_get_io_base_address(0);
+		octeon_pcie1_controller.io_resource->end =
+			octeon_pcie1_controller.io_resource->start +
+			cvmx_pcie_get_io_size(1) - 1;
+		register_pci_controller(&octeon_pcie1_controller);
+	}
+	return 0;
+}
+
+arch_initcall(octeon_pcie_setup);
diff --git a/arch/mips/include/asm/cpu-features.h b/arch/mips/include/asm/cpu-features.h
index c0047f8..8ab1d12 100644
--- a/arch/mips/include/asm/cpu-features.h
+++ b/arch/mips/include/asm/cpu-features.h
@@ -147,6 +147,10 @@
 #define cpu_has_mips_r	(cpu_has_mips32r1 | cpu_has_mips32r2 | \
 			 cpu_has_mips64r1 | cpu_has_mips64r2)
 
+#ifndef cpu_has_mips_r2_exec_hazard
+#define cpu_has_mips_r2_exec_hazard cpu_has_mips_r2
+#endif
+
 /*
  * MIPS32, MIPS64, VR5500, IDT32332, IDT32334 and maybe a few other
  * pre-MIPS32/MIPS53 processors have CLO, CLZ.  For 64-bit kernels
@@ -230,4 +234,8 @@
 #define cpu_scache_line_size()	cpu_data[0].scache.linesz
 #endif
 
+#ifndef cpu_hwrena_impl_bits
+#define cpu_hwrena_impl_bits		0
+#endif
+
 #endif /* __ASM_CPU_FEATURES_H */
diff --git a/arch/mips/include/asm/delay.h b/arch/mips/include/asm/delay.h
index a07e51b..d2d8949 100644
--- a/arch/mips/include/asm/delay.h
+++ b/arch/mips/include/asm/delay.h
@@ -15,7 +15,7 @@
 extern void __ndelay(unsigned int ns);
 extern void __udelay(unsigned int us);
 
-#define ndelay(ns) __udelay(ns)
+#define ndelay(ns) __ndelay(ns)
 #define udelay(us) __udelay(us)
 
 /* make sure "usecs *= ..." in udelay do not overflow. */
diff --git a/arch/mips/include/asm/hugetlb.h b/arch/mips/include/asm/hugetlb.h
new file mode 100644
index 0000000..f5e85601
--- /dev/null
+++ b/arch/mips/include/asm/hugetlb.h
@@ -0,0 +1,114 @@
+/*
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 2008, 2009 Cavium Networks, Inc.
+ */
+
+#ifndef __ASM_HUGETLB_H
+#define __ASM_HUGETLB_H
+
+#include <asm/page.h>
+
+
+static inline int is_hugepage_only_range(struct mm_struct *mm,
+					 unsigned long addr,
+					 unsigned long len)
+{
+	return 0;
+}
+
+static inline int prepare_hugepage_range(struct file *file,
+					 unsigned long addr,
+					 unsigned long len)
+{
+	unsigned long task_size = STACK_TOP;
+	struct hstate *h = hstate_file(file);
+
+	if (len & ~huge_page_mask(h))
+		return -EINVAL;
+	if (addr & ~huge_page_mask(h))
+		return -EINVAL;
+	if (len > task_size)
+		return -ENOMEM;
+	if (task_size - len < addr)
+		return -EINVAL;
+	return 0;
+}
+
+static inline void hugetlb_prefault_arch_hook(struct mm_struct *mm)
+{
+}
+
+static inline void hugetlb_free_pgd_range(struct mmu_gather *tlb,
+					  unsigned long addr,
+					  unsigned long end,
+					  unsigned long floor,
+					  unsigned long ceiling)
+{
+	free_pgd_range(tlb, addr, end, floor, ceiling);
+}
+
+static inline void set_huge_pte_at(struct mm_struct *mm, unsigned long addr,
+				   pte_t *ptep, pte_t pte)
+{
+	set_pte_at(mm, addr, ptep, pte);
+}
+
+static inline pte_t huge_ptep_get_and_clear(struct mm_struct *mm,
+					    unsigned long addr, pte_t *ptep)
+{
+	pte_t clear;
+	pte_t pte = *ptep;
+
+	pte_val(clear) = (unsigned long)invalid_pte_table;
+	set_pte_at(mm, addr, ptep, clear);
+	return pte;
+}
+
+static inline void huge_ptep_clear_flush(struct vm_area_struct *vma,
+					 unsigned long addr, pte_t *ptep)
+{
+}
+
+static inline int huge_pte_none(pte_t pte)
+{
+	unsigned long val = pte_val(pte) & ~_PAGE_GLOBAL;
+	return !val || (val == (unsigned long)invalid_pte_table);
+}
+
+static inline pte_t huge_pte_wrprotect(pte_t pte)
+{
+	return pte_wrprotect(pte);
+}
+
+static inline void huge_ptep_set_wrprotect(struct mm_struct *mm,
+					   unsigned long addr, pte_t *ptep)
+{
+	ptep_set_wrprotect(mm, addr, ptep);
+}
+
+static inline int huge_ptep_set_access_flags(struct vm_area_struct *vma,
+					     unsigned long addr,
+					     pte_t *ptep, pte_t pte,
+					     int dirty)
+{
+	return ptep_set_access_flags(vma, addr, ptep, pte, dirty);
+}
+
+static inline pte_t huge_ptep_get(pte_t *ptep)
+{
+	return *ptep;
+}
+
+static inline int arch_prepare_hugepage(struct page *page)
+{
+	return 0;
+}
+
+static inline void arch_release_hugepage(struct page *page)
+{
+}
+
+#endif /* __ASM_HUGETLB_H */
diff --git a/arch/mips/include/asm/ioctl.h b/arch/mips/include/asm/ioctl.h
index 9161634..c515a1a 100644
--- a/arch/mips/include/asm/ioctl.h
+++ b/arch/mips/include/asm/ioctl.h
@@ -3,40 +3,16 @@
  * License.  See the file "COPYING" in the main directory of this archive
  * for more details.
  *
- * Copyright (C) 1995, 96, 99, 2001 Ralf Baechle
+ * Copyright (C) 1995, 96, 99, 2001 Ralf Baechle <ralf@linux-mips.org>
+ * Copyright (C) 2009 Wind River Systems
+ * Written by Ralf Baechle <ralf@linux-mips.org>
  */
-#ifndef _ASM_IOCTL_H
-#define _ASM_IOCTL_H
+#ifndef __ASM_IOCTL_H
+#define __ASM_IOCTL_H
 
-/*
- * The original linux ioctl numbering scheme was just a general
- * "anything goes" setup, where more or less random numbers were
- * assigned.  Sorry, I was clueless when I started out on this.
- *
- * On the alpha, we'll try to clean it up a bit, using a more sane
- * ioctl numbering, and also trying to be compatible with OSF/1 in
- * the process. I'd like to clean it up for the i386 as well, but
- * it's so painful recognizing both the new and the old numbers..
- *
- * The same applies for for the MIPS ABI; in fact even the macros
- * from Linux/Alpha fit almost perfectly.
- */
-
-#define _IOC_NRBITS	8
-#define _IOC_TYPEBITS	8
 #define _IOC_SIZEBITS	13
 #define _IOC_DIRBITS	3
 
-#define _IOC_NRMASK	((1 << _IOC_NRBITS)-1)
-#define _IOC_TYPEMASK	((1 << _IOC_TYPEBITS)-1)
-#define _IOC_SIZEMASK	((1 << _IOC_SIZEBITS)-1)
-#define _IOC_DIRMASK	((1 << _IOC_DIRBITS)-1)
-
-#define _IOC_NRSHIFT	0
-#define _IOC_TYPESHIFT	(_IOC_NRSHIFT+_IOC_NRBITS)
-#define _IOC_SIZESHIFT	(_IOC_TYPESHIFT+_IOC_TYPEBITS)
-#define _IOC_DIRSHIFT	(_IOC_SIZESHIFT+_IOC_SIZEBITS)
-
 /*
  * Direction bits _IOC_NONE could be 0, but OSF/1 gives it a bit.
  * And this turns out useful to catch old ioctl numbers in header
@@ -46,53 +22,6 @@
 #define _IOC_READ	2U
 #define _IOC_WRITE	4U
 
-/*
- * The following are included for compatibility
- */
-#define _IOC_VOID	0x20000000
-#define _IOC_OUT	0x40000000
-#define _IOC_IN		0x80000000
-#define _IOC_INOUT	(IOC_IN|IOC_OUT)
+#include <asm-generic/ioctl.h>
 
-#define _IOC(dir, type, nr, size) \
-	(((dir)  << _IOC_DIRSHIFT) | \
-	 ((type) << _IOC_TYPESHIFT) | \
-	 ((nr)   << _IOC_NRSHIFT) | \
-	 ((size) << _IOC_SIZESHIFT))
-
-#ifdef __KERNEL__
-/* provoke compile error for invalid uses of size argument */
-extern unsigned int __invalid_size_argument_for_IOC;
-#define _IOC_TYPECHECK(t) \
-	((sizeof(t) == sizeof(t[1]) && \
-	  sizeof(t) < (1 << _IOC_SIZEBITS)) ? \
-	  sizeof(t) : __invalid_size_argument_for_IOC)
-#else
-#define _IOC_TYPECHECK(t)	(sizeof(t))
-#endif
-
-/* used to create numbers */
-#define _IO(type, nr)		_IOC(_IOC_NONE, (type), (nr), 0)
-#define _IOR(type, nr, size)	_IOC(_IOC_READ, (type), (nr), (_IOC_TYPECHECK(size)))
-#define _IOW(type, nr, size)	_IOC(_IOC_WRITE, (type), (nr), (_IOC_TYPECHECK(size)))
-#define _IOWR(type, nr, size)	_IOC(_IOC_READ|_IOC_WRITE, (type), (nr), (_IOC_TYPECHECK(size)))
-#define _IOR_BAD(type, nr, size)	_IOC(_IOC_READ, (type), (nr), sizeof(size))
-#define _IOW_BAD(type, nr, size)	_IOC(_IOC_WRITE, (type), (nr), sizeof(size))
-#define _IOWR_BAD(type, nr, size)	_IOC(_IOC_READ|_IOC_WRITE, (type), (nr), sizeof(size))
-
-
-/* used to decode them.. */
-#define _IOC_DIR(nr)		(((nr) >> _IOC_DIRSHIFT) & _IOC_DIRMASK)
-#define _IOC_TYPE(nr)		(((nr) >> _IOC_TYPESHIFT) & _IOC_TYPEMASK)
-#define _IOC_NR(nr)		(((nr) >> _IOC_NRSHIFT) & _IOC_NRMASK)
-#define _IOC_SIZE(nr)		(((nr) >> _IOC_SIZESHIFT) & _IOC_SIZEMASK)
-
-/* ...and for the drivers/sound files... */
-
-#define IOC_IN		(_IOC_WRITE << _IOC_DIRSHIFT)
-#define IOC_OUT		(_IOC_READ << _IOC_DIRSHIFT)
-#define IOC_INOUT	((_IOC_WRITE|_IOC_READ) << _IOC_DIRSHIFT)
-#define IOCSIZE_MASK	(_IOC_SIZEMASK << _IOC_SIZESHIFT)
-#define IOCSIZE_SHIFT	(_IOC_SIZESHIFT)
-
-#endif /* _ASM_IOCTL_H */
+#endif /* __ASM_IOCTL_H */
diff --git a/arch/mips/include/asm/mach-au1x00/au1000_gpio.h b/arch/mips/include/asm/mach-au1x00/au1000_gpio.h
deleted file mode 100644
index d8c96fd..0000000
--- a/arch/mips/include/asm/mach-au1x00/au1000_gpio.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * FILE NAME au1000_gpio.h
- *
- * BRIEF MODULE DESCRIPTION
- *	API to Alchemy Au1xx0 GPIO device.
- *
- *  Author: MontaVista Software, Inc.  <source@mvista.com>
- *          Steve Longerbeam
- *
- * Copyright 2001, 2008 MontaVista Software Inc.
- *
- *  This program is free software; you can redistribute  it and/or modify it
- *  under  the terms of  the GNU General  Public License as published by the
- *  Free Software Foundation;  either version 2 of the  License, or (at your
- *  option) any later version.
- *
- *  THIS  SOFTWARE  IS PROVIDED   ``AS  IS'' AND   ANY  EXPRESS OR IMPLIED
- *  WARRANTIES,   INCLUDING, BUT NOT  LIMITED  TO, THE IMPLIED WARRANTIES OF
- *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
- *  NO  EVENT  SHALL   THE AUTHOR  BE    LIABLE FOR ANY   DIRECT, INDIRECT,
- *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- *  NOT LIMITED   TO, PROCUREMENT OF  SUBSTITUTE GOODS  OR SERVICES; LOSS OF
- *  USE, DATA,  OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- *  ANY THEORY OF LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT
- *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- *  You should have received a copy of the  GNU General Public License along
- *  with this program; if not, write  to the Free Software Foundation, Inc.,
- *  675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#ifndef __AU1000_GPIO_H
-#define __AU1000_GPIO_H
-
-#include <linux/ioctl.h>
-
-#define AU1000GPIO_IOC_MAGIC 'A'
-
-#define AU1000GPIO_IN		_IOR(AU1000GPIO_IOC_MAGIC, 0, int)
-#define AU1000GPIO_SET		_IOW(AU1000GPIO_IOC_MAGIC, 1, int)
-#define AU1000GPIO_CLEAR	_IOW(AU1000GPIO_IOC_MAGIC, 2, int)
-#define AU1000GPIO_OUT		_IOW(AU1000GPIO_IOC_MAGIC, 3, int)
-#define AU1000GPIO_TRISTATE	_IOW(AU1000GPIO_IOC_MAGIC, 4, int)
-#define AU1000GPIO_AVAIL_MASK	_IOR(AU1000GPIO_IOC_MAGIC, 5, int)
-
-#ifdef __KERNEL__
-extern u32 get_au1000_avail_gpio_mask(void);
-extern int au1000gpio_tristate(u32 data);
-extern int au1000gpio_in(u32 *data);
-extern int au1000gpio_set(u32 data);
-extern int au1000gpio_clear(u32 data);
-extern int au1000gpio_out(u32 data);
-#endif
-
-#endif
diff --git a/arch/mips/include/asm/mach-au1x00/gpio-au1000.h b/arch/mips/include/asm/mach-au1x00/gpio-au1000.h
new file mode 100644
index 0000000..127d4ed
--- /dev/null
+++ b/arch/mips/include/asm/mach-au1x00/gpio-au1000.h
@@ -0,0 +1,604 @@
+/*
+ * GPIO functions for Au1000, Au1500, Au1100, Au1550, Au1200
+ *
+ * Copyright (c) 2009 Manuel Lauss.
+ *
+ * Licensed under the terms outlined in the file COPYING.
+ */
+
+#ifndef _ALCHEMY_GPIO_AU1000_H_
+#define _ALCHEMY_GPIO_AU1000_H_
+
+#include <asm/mach-au1x00/au1000.h>
+
+/* The default GPIO numberspace as documented in the Alchemy manuals.
+ * GPIO0-31 from GPIO1 block,   GPIO200-215 from GPIO2 block.
+ */
+#define ALCHEMY_GPIO1_BASE	0
+#define ALCHEMY_GPIO2_BASE	200
+
+#define ALCHEMY_GPIO1_NUM	32
+#define ALCHEMY_GPIO2_NUM	16
+#define ALCHEMY_GPIO1_MAX 	(ALCHEMY_GPIO1_BASE + ALCHEMY_GPIO1_NUM - 1)
+#define ALCHEMY_GPIO2_MAX	(ALCHEMY_GPIO2_BASE + ALCHEMY_GPIO2_NUM - 1)
+
+#define MAKE_IRQ(intc, off)	(AU1000_INTC##intc##_INT_BASE + (off))
+
+
+static inline int au1000_gpio1_to_irq(int gpio)
+{
+	return MAKE_IRQ(1, gpio - ALCHEMY_GPIO1_BASE);
+}
+
+static inline int au1000_gpio2_to_irq(int gpio)
+{
+	return -ENXIO;
+}
+
+#ifdef CONFIG_SOC_AU1000
+static inline int au1000_irq_to_gpio(int irq)
+{
+	if ((irq >= AU1000_GPIO_0) && (irq <= AU1000_GPIO_31))
+		return ALCHEMY_GPIO1_BASE + (irq - AU1000_GPIO_0) + 0;
+
+	return -ENXIO;
+}
+#endif
+
+static inline int au1500_gpio1_to_irq(int gpio)
+{
+	gpio -= ALCHEMY_GPIO1_BASE;
+
+	switch (gpio) {
+	case 0 ... 15:
+	case 20:
+	case 23 ... 28:	return MAKE_IRQ(1, gpio);
+	}
+
+	return -ENXIO;
+}
+
+static inline int au1500_gpio2_to_irq(int gpio)
+{
+	gpio -= ALCHEMY_GPIO2_BASE;
+
+	switch (gpio) {
+	case 0 ... 3:	return MAKE_IRQ(1, 16 + gpio - 0);
+	case 4 ... 5:	return MAKE_IRQ(1, 21 + gpio - 4);
+	case 6 ... 7:	return MAKE_IRQ(1, 29 + gpio - 6);
+	}
+
+	return -ENXIO;
+}
+
+#ifdef CONFIG_SOC_AU1500
+static inline int au1500_irq_to_gpio(int irq)
+{
+	switch (irq) {
+	case AU1000_GPIO_0 ... AU1000_GPIO_15:
+	case AU1500_GPIO_20:
+	case AU1500_GPIO_23 ... AU1500_GPIO_28:
+		return ALCHEMY_GPIO1_BASE + (irq - AU1000_GPIO_0) + 0;
+	case AU1500_GPIO_200 ... AU1500_GPIO_203:
+		return ALCHEMY_GPIO2_BASE + (irq - AU1500_GPIO_200) + 0;
+	case AU1500_GPIO_204 ... AU1500_GPIO_205:
+		return ALCHEMY_GPIO2_BASE + (irq - AU1500_GPIO_204) + 4;
+	case AU1500_GPIO_206 ... AU1500_GPIO_207:
+		return ALCHEMY_GPIO2_BASE + (irq - AU1500_GPIO_206) + 6;
+	case AU1500_GPIO_208_215:
+		return ALCHEMY_GPIO2_BASE + 8;
+	}
+
+	return -ENXIO;
+}
+#endif
+
+static inline int au1100_gpio1_to_irq(int gpio)
+{
+	return MAKE_IRQ(1, gpio - ALCHEMY_GPIO1_BASE);
+}
+
+static inline int au1100_gpio2_to_irq(int gpio)
+{
+	gpio -= ALCHEMY_GPIO2_BASE;
+
+	if ((gpio >= 8) && (gpio <= 15))
+		return MAKE_IRQ(0, 29);		/* shared GPIO208_215 */
+}
+
+#ifdef CONFIG_SOC_AU1100
+static inline int au1100_irq_to_gpio(int irq)
+{
+	switch (irq) {
+	case AU1000_GPIO_0 ... AU1000_GPIO_31:
+		return ALCHEMY_GPIO1_BASE + (irq - AU1000_GPIO_0) + 0;
+	case AU1100_GPIO_208_215:
+		return ALCHEMY_GPIO2_BASE + 8;
+	}
+
+	return -ENXIO;
+}
+#endif
+
+static inline int au1550_gpio1_to_irq(int gpio)
+{
+	gpio -= ALCHEMY_GPIO1_BASE;
+
+	switch (gpio) {
+	case 0 ... 15:
+	case 20 ... 28:	return MAKE_IRQ(1, gpio);
+	case 16 ... 17:	return MAKE_IRQ(1, 18 + gpio - 16);
+	}
+
+	return -ENXIO;
+}
+
+static inline int au1550_gpio2_to_irq(int gpio)
+{
+	gpio -= ALCHEMY_GPIO2_BASE;
+
+	switch (gpio) {
+	case 0:		return MAKE_IRQ(1, 16);
+	case 1 ... 5:	return MAKE_IRQ(1, 17);	/* shared GPIO201_205 */
+	case 6 ... 7:	return MAKE_IRQ(1, 29 + gpio - 6);
+	case 8 ... 15:	return MAKE_IRQ(1, 31);	/* shared GPIO208_215 */
+	}
+
+	return -ENXIO;
+}
+
+#ifdef CONFIG_SOC_AU1550
+static inline int au1550_irq_to_gpio(int irq)
+{
+	switch (irq) {
+	case AU1000_GPIO_0 ... AU1000_GPIO_15:
+		return ALCHEMY_GPIO1_BASE + (irq - AU1000_GPIO_0) + 0;
+	case AU1550_GPIO_200:
+	case AU1500_GPIO_201_205:
+		return ALCHEMY_GPIO2_BASE + (irq - AU1550_GPIO_200) + 0;
+	case AU1500_GPIO_16 ... AU1500_GPIO_28:
+		return ALCHEMY_GPIO1_BASE + (irq - AU1500_GPIO_16) + 16;
+	case AU1500_GPIO_206 ... AU1500_GPIO_208_218:
+		return ALCHEMY_GPIO2_BASE + (irq - AU1500_GPIO_206) + 6;
+	}
+
+	return -ENXIO;
+}
+#endif
+
+static inline int au1200_gpio1_to_irq(int gpio)
+{
+	return MAKE_IRQ(1, gpio - ALCHEMY_GPIO1_BASE);
+}
+
+static inline int au1200_gpio2_to_irq(int gpio)
+{
+	gpio -= ALCHEMY_GPIO2_BASE;
+
+	switch (gpio) {
+	case 0 ... 2:	return MAKE_IRQ(0, 5 + gpio - 0);
+	case 3:		return MAKE_IRQ(0, 22);
+	case 4 ... 7:	return MAKE_IRQ(0, 24 + gpio - 4);
+	case 8 ... 15:	return MAKE_IRQ(0, 28);	/* shared GPIO208_215 */
+	}
+
+	return -ENXIO;
+}
+
+#ifdef CONFIG_SOC_AU1200
+static inline int au1200_irq_to_gpio(int irq)
+{
+	switch (irq) {
+	case AU1000_GPIO_0 ... AU1000_GPIO_31:
+		return ALCHEMY_GPIO1_BASE + (irq - AU1000_GPIO_0) + 0;
+	case AU1200_GPIO_200 ... AU1200_GPIO_202:
+		return ALCHEMY_GPIO2_BASE + (irq - AU1200_GPIO_200) + 0;
+	case AU1200_GPIO_203:
+		return ALCHEMY_GPIO2_BASE + 3;
+	case AU1200_GPIO_204 ... AU1200_GPIO_208_215:
+		return ALCHEMY_GPIO2_BASE + (irq - AU1200_GPIO_204) + 4;
+	}
+
+	return -ENXIO;
+}
+#endif
+
+/*
+ * GPIO1 block macros for common linux gpio functions.
+ */
+static inline void alchemy_gpio1_set_value(int gpio, int v)
+{
+	unsigned long mask = 1 << (gpio - ALCHEMY_GPIO1_BASE);
+	unsigned long r = v ? SYS_OUTPUTSET : SYS_OUTPUTCLR;
+	au_writel(mask, r);
+	au_sync();
+}
+
+static inline int alchemy_gpio1_get_value(int gpio)
+{
+	unsigned long mask = 1 << (gpio - ALCHEMY_GPIO1_BASE);
+	return au_readl(SYS_PINSTATERD) & mask;
+}
+
+static inline int alchemy_gpio1_direction_input(int gpio)
+{
+	unsigned long mask = 1 << (gpio - ALCHEMY_GPIO1_BASE);
+	au_writel(mask, SYS_TRIOUTCLR);
+	au_sync();
+	return 0;
+}
+
+static inline int alchemy_gpio1_direction_output(int gpio, int v)
+{
+	/* hardware switches to "output" mode when one of the two
+	 * "set_value" registers is accessed.
+	 */
+	alchemy_gpio1_set_value(gpio, v);
+	return 0;
+}
+
+static inline int alchemy_gpio1_is_valid(int gpio)
+{
+	return ((gpio >= ALCHEMY_GPIO1_BASE) && (gpio <= ALCHEMY_GPIO1_MAX));
+}
+
+static inline int alchemy_gpio1_to_irq(int gpio)
+{
+#if defined(CONFIG_SOC_AU1000)
+	return au1000_gpio1_to_irq(gpio);
+#elif defined(CONFIG_SOC_AU1100)
+	return au1100_gpio1_to_irq(gpio);
+#elif defined(CONFIG_SOC_AU1500)
+	return au1500_gpio1_to_irq(gpio);
+#elif defined(CONFIG_SOC_AU1550)
+	return au1550_gpio1_to_irq(gpio);
+#elif defined(CONFIG_SOC_AU1200)
+	return au1200_gpio1_to_irq(gpio);
+#else
+	return -ENXIO;
+#endif
+}
+
+/*
+ * GPIO2 block macros for common linux GPIO functions. The 'gpio'
+ * parameter must be in range of ALCHEMY_GPIO2_BASE..ALCHEMY_GPIO2_MAX.
+ */
+static inline void __alchemy_gpio2_mod_dir(int gpio, int to_out)
+{
+	unsigned long mask = 1 << (gpio - ALCHEMY_GPIO2_BASE);
+	unsigned long d = au_readl(GPIO2_DIR);
+	if (to_out)
+		d |= mask;
+	else
+		d &= ~mask;
+	au_writel(d, GPIO2_DIR);
+	au_sync();
+}
+
+static inline void alchemy_gpio2_set_value(int gpio, int v)
+{
+	unsigned long mask;
+	mask = ((v) ? 0x00010001 : 0x00010000) << (gpio - ALCHEMY_GPIO2_BASE);
+	au_writel(mask, GPIO2_OUTPUT);
+	au_sync();
+}
+
+static inline int alchemy_gpio2_get_value(int gpio)
+{
+	return au_readl(GPIO2_PINSTATE) & (1 << (gpio - ALCHEMY_GPIO2_BASE));
+}
+
+static inline int alchemy_gpio2_direction_input(int gpio)
+{
+	unsigned long flags;
+	local_irq_save(flags);
+	__alchemy_gpio2_mod_dir(gpio, 0);
+	local_irq_restore(flags);
+	return 0;
+}
+
+static inline int alchemy_gpio2_direction_output(int gpio, int v)
+{
+	unsigned long flags;
+	alchemy_gpio2_set_value(gpio, v);
+	local_irq_save(flags);
+	__alchemy_gpio2_mod_dir(gpio, 1);
+	local_irq_restore(flags);
+	return 0;
+}
+
+static inline int alchemy_gpio2_is_valid(int gpio)
+{
+	return ((gpio >= ALCHEMY_GPIO2_BASE) && (gpio <= ALCHEMY_GPIO2_MAX));
+}
+
+static inline int alchemy_gpio2_to_irq(int gpio)
+{
+#if defined(CONFIG_SOC_AU1000)
+	return au1000_gpio2_to_irq(gpio);
+#elif defined(CONFIG_SOC_AU1100)
+	return au1100_gpio2_to_irq(gpio);
+#elif defined(CONFIG_SOC_AU1500)
+	return au1500_gpio2_to_irq(gpio);
+#elif defined(CONFIG_SOC_AU1550)
+	return au1550_gpio2_to_irq(gpio);
+#elif defined(CONFIG_SOC_AU1200)
+	return au1200_gpio2_to_irq(gpio);
+#else
+	return -ENXIO;
+#endif
+}
+
+/**********************************************************************/
+
+/* On Au1000, Au1500 and Au1100 GPIOs won't work as inputs before
+ * SYS_PININPUTEN is written to at least once.  On Au1550/Au1200 this
+ * register enables use of GPIOs as wake source.
+ */
+static inline void alchemy_gpio1_input_enable(void)
+{
+	au_writel(0, SYS_PININPUTEN);	/* the write op is key */
+	au_sync();
+}
+
+/* GPIO2 shared interrupts and control */
+
+static inline void __alchemy_gpio2_mod_int(int gpio2, int en)
+{
+	unsigned long r = au_readl(GPIO2_INTENABLE);
+	if (en)
+		r |= 1 << gpio2;
+	else
+		r &= ~(1 << gpio2);
+	au_writel(r, GPIO2_INTENABLE);
+	au_sync();
+}
+
+/**
+ * alchemy_gpio2_enable_int - Enable a GPIO2 pins' shared irq contribution.
+ * @gpio2:	The GPIO2 pin to activate (200...215).
+ *
+ * GPIO208-215 have one shared interrupt line to the INTC.  They are
+ * and'ed with a per-pin enable bit and finally or'ed together to form
+ * a single irq request (useful for active-high sources).
+ * With this function, a pins' individual contribution to the int request
+ * can be enabled.  As with all other GPIO-based interrupts, the INTC
+ * must be programmed to accept the GPIO208_215 interrupt as well.
+ *
+ * NOTE: Calling this macro is only necessary for GPIO208-215; all other
+ * GPIO2-based interrupts have their own request to the INTC.  Please
+ * consult your Alchemy databook for more information!
+ *
+ * NOTE: On the Au1550, GPIOs 201-205 also have a shared interrupt request
+ * line to the INTC, GPIO201_205.  This function can be used for those
+ * as well.
+ *
+ * NOTE: 'gpio2' parameter must be in range of the GPIO2 numberspace
+ * (200-215 by default). No sanity checks are made,
+ */
+static inline void alchemy_gpio2_enable_int(int gpio2)
+{
+	unsigned long flags;
+
+	gpio2 -= ALCHEMY_GPIO2_BASE;
+
+#if defined(CONFIG_SOC_AU1100) || defined(CONFIG_SOC_AU1500)
+	/* Au1100/Au1500 have GPIO208-215 enable bits at 0..7 */
+	gpio2 -= 8;
+#endif
+	local_irq_save(flags);
+	__alchemy_gpio2_mod_int(gpio2, 1);
+	local_irq_restore(flags);
+}
+
+/**
+ * alchemy_gpio2_disable_int - Disable a GPIO2 pins' shared irq contribution.
+ * @gpio2:	The GPIO2 pin to activate (200...215).
+ *
+ * see function alchemy_gpio2_enable_int() for more information.
+ */
+static inline void alchemy_gpio2_disable_int(int gpio2)
+{
+	unsigned long flags;
+
+	gpio2 -= ALCHEMY_GPIO2_BASE;
+
+#if defined(CONFIG_SOC_AU1100) || defined(CONFIG_SOC_AU1500)
+	/* Au1100/Au1500 have GPIO208-215 enable bits at 0..7 */
+	gpio2 -= 8;
+#endif
+	local_irq_save(flags);
+	__alchemy_gpio2_mod_int(gpio2, 0);
+	local_irq_restore(flags);
+}
+
+/**
+ * alchemy_gpio2_enable -  Activate GPIO2 block.
+ *
+ * The GPIO2 block must be enabled excplicitly to work.  On systems
+ * where this isn't done by the bootloader, this macro can be used.
+ */
+static inline void alchemy_gpio2_enable(void)
+{
+	au_writel(3, GPIO2_ENABLE);	/* reset, clock enabled */
+	au_sync();
+	au_writel(1, GPIO2_ENABLE);	/* clock enabled */
+	au_sync();
+}
+
+/**
+ * alchemy_gpio2_disable - disable GPIO2 block.
+ *
+ * Disable and put GPIO2 block in low-power mode.
+ */
+static inline void alchemy_gpio2_disable(void)
+{
+	au_writel(2, GPIO2_ENABLE);	/* reset, clock disabled */
+	au_sync();
+}
+
+/**********************************************************************/
+
+/* wrappers for on-chip gpios; can be used before gpio chips have been
+ * registered with gpiolib.
+ */
+static inline int alchemy_gpio_direction_input(int gpio)
+{
+	return (gpio >= ALCHEMY_GPIO2_BASE) ?
+		alchemy_gpio2_direction_input(gpio) :
+		alchemy_gpio1_direction_input(gpio);
+}
+
+static inline int alchemy_gpio_direction_output(int gpio, int v)
+{
+	return (gpio >= ALCHEMY_GPIO2_BASE) ?
+		alchemy_gpio2_direction_output(gpio, v) :
+		alchemy_gpio1_direction_output(gpio, v);
+}
+
+static inline int alchemy_gpio_get_value(int gpio)
+{
+	return (gpio >= ALCHEMY_GPIO2_BASE) ?
+		alchemy_gpio2_get_value(gpio) :
+		alchemy_gpio1_get_value(gpio);
+}
+
+static inline void alchemy_gpio_set_value(int gpio, int v)
+{
+	if (gpio >= ALCHEMY_GPIO2_BASE)
+		alchemy_gpio2_set_value(gpio, v);
+	else
+		alchemy_gpio1_set_value(gpio, v);
+}
+
+static inline int alchemy_gpio_is_valid(int gpio)
+{
+	return (gpio >= ALCHEMY_GPIO2_BASE) ?
+		alchemy_gpio2_is_valid(gpio) :
+		alchemy_gpio1_is_valid(gpio);
+}
+
+static inline int alchemy_gpio_cansleep(int gpio)
+{
+	return 0;	/* Alchemy never gets tired */
+}
+
+static inline int alchemy_gpio_to_irq(int gpio)
+{
+	return (gpio >= ALCHEMY_GPIO2_BASE) ?
+		alchemy_gpio2_to_irq(gpio) :
+		alchemy_gpio1_to_irq(gpio);
+}
+
+static inline int alchemy_irq_to_gpio(int irq)
+{
+#if defined(CONFIG_SOC_AU1000)
+	return au1000_irq_to_gpio(irq);
+#elif defined(CONFIG_SOC_AU1100)
+	return au1100_irq_to_gpio(irq);
+#elif defined(CONFIG_SOC_AU1500)
+	return au1500_irq_to_gpio(irq);
+#elif defined(CONFIG_SOC_AU1550)
+	return au1550_irq_to_gpio(irq);
+#elif defined(CONFIG_SOC_AU1200)
+	return au1200_irq_to_gpio(irq);
+#else
+	return -ENXIO;
+#endif
+}
+
+/**********************************************************************/
+
+/* Linux gpio framework integration.
+ *
+ * 4 use cases of Au1000-Au1200 GPIOS:
+ *(1) GPIOLIB=y, ALCHEMY_GPIO_INDIRECT=y:
+ *	Board must register gpiochips.
+ *(2) GPIOLIB=y, ALCHEMY_GPIO_INDIRECT=n:
+ *	2 (1 for Au1000) gpio_chips are registered.
+ *
+ *(3) GPIOLIB=n, ALCHEMY_GPIO_INDIRECT=y:
+ *	the boards' gpio.h must provide	the linux gpio wrapper functions,
+ *
+ *(4) GPIOLIB=n, ALCHEMY_GPIO_INDIRECT=n:
+ *	inlinable gpio functions are provided which enable access to the
+ *	Au1000 gpios only by using the numbers straight out of the data-
+ *	sheets.
+
+ * Cases 1 and 3 are intended for boards which want to provide their own
+ * GPIO namespace and -operations (i.e. for example you have 8 GPIOs
+ * which are in part provided by spare Au1000 GPIO pins and in part by
+ * an external FPGA but you still want them to be accssible in linux
+ * as gpio0-7. The board can of course use the alchemy_gpioX_* functions
+ * as required).
+ */
+
+#ifndef CONFIG_GPIOLIB
+
+
+#ifndef CONFIG_ALCHEMY_GPIO_INDIRECT	/* case (4) */
+
+static inline int gpio_direction_input(int gpio)
+{
+	return alchemy_gpio_direction_input(gpio);
+}
+
+static inline int gpio_direction_output(int gpio, int v)
+{
+	return alchemy_gpio_direction_output(gpio, v);
+}
+
+static inline int gpio_get_value(int gpio)
+{
+	return alchemy_gpio_get_value(gpio);
+}
+
+static inline void gpio_set_value(int gpio, int v)
+{
+	alchemy_gpio_set_value(gpio, v);
+}
+
+static inline int gpio_is_valid(int gpio)
+{
+	return alchemy_gpio_is_valid(gpio);
+}
+
+static inline int gpio_cansleep(int gpio)
+{
+	return alchemy_gpio_cansleep(gpio);
+}
+
+static inline int gpio_to_irq(int gpio)
+{
+	return alchemy_gpio_to_irq(gpio);
+}
+
+static inline int irq_to_gpio(int irq)
+{
+	return alchemy_irq_to_gpio(irq);
+}
+
+#endif	/* !CONFIG_ALCHEMY_GPIO_INDIRECT */
+
+
+#else	/* CONFIG GPIOLIB */
+
+
+ /* using gpiolib to provide up to 2 gpio_chips for on-chip gpios */
+#ifndef CONFIG_ALCHEMY_GPIO_INDIRECT	/* case (2) */
+
+/* get everything through gpiolib */
+#define gpio_to_irq	__gpio_to_irq
+#define gpio_get_value	__gpio_get_value
+#define gpio_set_value	__gpio_set_value
+#define gpio_cansleep	__gpio_cansleep
+#define irq_to_gpio	alchemy_irq_to_gpio
+
+#include <asm-generic/gpio.h>
+
+#endif	/* !CONFIG_ALCHEMY_GPIO_INDIRECT */
+
+
+#endif	/* !CONFIG_GPIOLIB */
+
+#endif /* _ALCHEMY_GPIO_AU1000_H_ */
diff --git a/arch/mips/include/asm/mach-au1x00/gpio.h b/arch/mips/include/asm/mach-au1x00/gpio.h
index 34d9b72..f9b7d41 100644
--- a/arch/mips/include/asm/mach-au1x00/gpio.h
+++ b/arch/mips/include/asm/mach-au1x00/gpio.h
@@ -1,33 +1,10 @@
-#ifndef _AU1XXX_GPIO_H_
-#define _AU1XXX_GPIO_H_
+#ifndef _ALCHEMY_GPIO_H_
+#define _ALCHEMY_GPIO_H_
 
-#include <linux/types.h>
+#if defined(CONFIG_ALCHEMY_GPIO_AU1000)
 
-#define AU1XXX_GPIO_BASE	200
+#include <asm/mach-au1x00/gpio-au1000.h>
 
-/* GPIO bank 1 offsets */
-#define AU1000_GPIO1_TRI_OUT	0x0100
-#define AU1000_GPIO1_OUT	0x0108
-#define AU1000_GPIO1_ST		0x0110
-#define AU1000_GPIO1_CLR	0x010C
+#endif
 
-/* GPIO bank 2 offsets */
-#define AU1000_GPIO2_DIR	0x00
-#define AU1000_GPIO2_RSVD	0x04
-#define AU1000_GPIO2_OUT	0x08
-#define AU1000_GPIO2_ST		0x0C
-#define AU1000_GPIO2_INT	0x10
-#define AU1000_GPIO2_EN		0x14
-
-#define GPIO2_OUT_EN_MASK	0x00010000
-
-#define gpio_to_irq(gpio)	NULL
-
-#define gpio_get_value __gpio_get_value
-#define gpio_set_value __gpio_set_value
-
-#define gpio_cansleep __gpio_cansleep
-
-#include <asm-generic/gpio.h>
-
-#endif /* _AU1XXX_GPIO_H_ */
+#endif	/* _ALCHEMY_GPIO_H_ */
diff --git a/arch/mips/include/asm/mach-bcm47xx/gpio.h b/arch/mips/include/asm/mach-bcm47xx/gpio.h
index 1784fde..9850414 100644
--- a/arch/mips/include/asm/mach-bcm47xx/gpio.h
+++ b/arch/mips/include/asm/mach-bcm47xx/gpio.h
@@ -37,6 +37,9 @@
 
 static inline int gpio_direction_output(unsigned gpio, int value)
 {
+	/* first set the gpio out value */
+	ssb_gpio_out(&ssb_bcm47xx, 1 << gpio, value ? 1 << gpio : 0);
+	/* then set the gpio mode */
 	ssb_gpio_outen(&ssb_bcm47xx, 1 << gpio, 1 << gpio);
 	return 0;
 }
diff --git a/arch/mips/include/asm/mach-cavium-octeon/cpu-feature-overrides.h b/arch/mips/include/asm/mach-cavium-octeon/cpu-feature-overrides.h
index 04ce6e6..3d830756 100644
--- a/arch/mips/include/asm/mach-cavium-octeon/cpu-feature-overrides.h
+++ b/arch/mips/include/asm/mach-cavium-octeon/cpu-feature-overrides.h
@@ -47,11 +47,13 @@
 #define cpu_has_mips32r2	0
 #define cpu_has_mips64r1	0
 #define cpu_has_mips64r2	1
+#define cpu_has_mips_r2_exec_hazard 0
 #define cpu_has_dsp		0
 #define cpu_has_mipsmt		0
 #define cpu_has_userlocal	0
 #define cpu_has_vint		0
 #define cpu_has_veic		0
+#define cpu_hwrena_impl_bits	0xc0000000
 #define ARCH_HAS_READ_CURRENT_TIMER 1
 #define ARCH_HAS_IRQ_PER_CPU	1
 #define ARCH_HAS_SPINLOCK_PREFETCH 1
diff --git a/arch/mips/include/asm/mach-cavium-octeon/dma-coherence.h b/arch/mips/include/asm/mach-cavium-octeon/dma-coherence.h
index f30fce9..17d5794 100644
--- a/arch/mips/include/asm/mach-cavium-octeon/dma-coherence.h
+++ b/arch/mips/include/asm/mach-cavium-octeon/dma-coherence.h
@@ -30,12 +30,14 @@
 	return octeon_map_dma_mem(dev, page_address(page), PAGE_SIZE);
 }
 
-static inline unsigned long plat_dma_addr_to_phys(dma_addr_t dma_addr)
+static inline unsigned long plat_dma_addr_to_phys(struct device *dev,
+	dma_addr_t dma_addr)
 {
 	return dma_addr;
 }
 
-static inline void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr)
+static inline void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr,
+	size_t size, enum dma_data_direction direction)
 {
 	octeon_unmap_dma_mem(dev, dma_addr);
 }
diff --git a/arch/mips/include/asm/mach-generic/dma-coherence.h b/arch/mips/include/asm/mach-generic/dma-coherence.h
index 36c611b..8da9807 100644
--- a/arch/mips/include/asm/mach-generic/dma-coherence.h
+++ b/arch/mips/include/asm/mach-generic/dma-coherence.h
@@ -23,12 +23,14 @@
 	return page_to_phys(page);
 }
 
-static inline unsigned long plat_dma_addr_to_phys(dma_addr_t dma_addr)
+static inline unsigned long plat_dma_addr_to_phys(struct device *dev,
+	dma_addr_t dma_addr)
 {
 	return dma_addr;
 }
 
-static inline void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr)
+static inline void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr,
+	size_t size, enum dma_data_direction direction)
 {
 }
 
diff --git a/arch/mips/include/asm/mach-ip27/dma-coherence.h b/arch/mips/include/asm/mach-ip27/dma-coherence.h
index 4c21bfc..d3d0401 100644
--- a/arch/mips/include/asm/mach-ip27/dma-coherence.h
+++ b/arch/mips/include/asm/mach-ip27/dma-coherence.h
@@ -33,12 +33,14 @@
 	return pa;
 }
 
-static unsigned long plat_dma_addr_to_phys(dma_addr_t dma_addr)
+static unsigned long plat_dma_addr_to_phys(struct device *dev,
+	dma_addr_t dma_addr)
 {
 	return dma_addr & ~(0xffUL << 56);
 }
 
-static inline void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr)
+static inline void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr,
+	size_t size, enum dma_data_direction direction)
 {
 }
 
diff --git a/arch/mips/include/asm/mach-ip32/dma-coherence.h b/arch/mips/include/asm/mach-ip32/dma-coherence.h
index 7ae40f4..3785595 100644
--- a/arch/mips/include/asm/mach-ip32/dma-coherence.h
+++ b/arch/mips/include/asm/mach-ip32/dma-coherence.h
@@ -50,7 +50,8 @@
 }
 
 /* This is almost certainly wrong but it's what dma-ip32.c used to use  */
-static unsigned long plat_dma_addr_to_phys(dma_addr_t dma_addr)
+static unsigned long plat_dma_addr_to_phys(struct device *dev,
+	dma_addr_t dma_addr)
 {
 	unsigned long addr = dma_addr & RAM_OFFSET_MASK;
 
@@ -60,7 +61,8 @@
 	return addr;
 }
 
-static inline void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr)
+static inline void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr,
+	size_t size, enum dma_data_direction direction)
 {
 }
 
diff --git a/arch/mips/include/asm/mach-jazz/dma-coherence.h b/arch/mips/include/asm/mach-jazz/dma-coherence.h
index 1c7cd27..f93aee5 100644
--- a/arch/mips/include/asm/mach-jazz/dma-coherence.h
+++ b/arch/mips/include/asm/mach-jazz/dma-coherence.h
@@ -22,12 +22,14 @@
 	return vdma_alloc(page_to_phys(page), PAGE_SIZE);
 }
 
-static unsigned long plat_dma_addr_to_phys(dma_addr_t dma_addr)
+static unsigned long plat_dma_addr_to_phys(struct device *dev,
+	dma_addr_t dma_addr)
 {
 	return vdma_log2phys(dma_addr);
 }
 
-static void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr)
+static void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr,
+	size_t size, enum dma_data_direction direction)
 {
 	vdma_free(dma_addr);
 }
diff --git a/arch/mips/include/asm/mach-lemote/dma-coherence.h b/arch/mips/include/asm/mach-lemote/dma-coherence.h
index 38fad7d..c8de5e7 100644
--- a/arch/mips/include/asm/mach-lemote/dma-coherence.h
+++ b/arch/mips/include/asm/mach-lemote/dma-coherence.h
@@ -25,12 +25,14 @@
 	return page_to_phys(page) | 0x80000000;
 }
 
-static inline unsigned long plat_dma_addr_to_phys(dma_addr_t dma_addr)
+static inline unsigned long plat_dma_addr_to_phys(struct device *dev,
+	dma_addr_t dma_addr)
 {
 	return dma_addr & 0x7fffffff;
 }
 
-static inline void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr)
+static inline void plat_unmap_dma_mem(struct device *dev, dma_addr_t dma_addr,
+	size_t size, enum dma_data_direction direction)
 {
 }
 
diff --git a/arch/mips/include/asm/mach-rc32434/cpu-feature-overrides.h b/arch/mips/include/asm/mach-rc32434/cpu-feature-overrides.h
index f3bc7ef..c3e4d3a 100644
--- a/arch/mips/include/asm/mach-rc32434/cpu-feature-overrides.h
+++ b/arch/mips/include/asm/mach-rc32434/cpu-feature-overrides.h
@@ -53,11 +53,6 @@
 #define cpu_has_smartmips		0
 
 #define cpu_has_vtag_icache		0
-/* #define cpu_has_dc_aliases		? */
-/* #define cpu_has_ic_fills_f_dc	? */
-/* #define cpu_has_pindexed_dcache	? */
-
-/* #define cpu_icache_snoops_remote_store	? */
 
 #define cpu_has_mips32r1		1
 #define cpu_has_mips32r2		0
diff --git a/arch/mips/include/asm/mipsregs.h b/arch/mips/include/asm/mipsregs.h
index 32ef8be..a581d60 100644
--- a/arch/mips/include/asm/mipsregs.h
+++ b/arch/mips/include/asm/mipsregs.h
@@ -220,6 +220,22 @@
 #error Bad page size configuration!
 #endif
 
+/*
+ * Default huge tlb size for a given kernel configuration
+ */
+#ifdef CONFIG_PAGE_SIZE_4KB
+#define PM_HUGE_MASK	PM_1M
+#elif defined(CONFIG_PAGE_SIZE_8KB)
+#define PM_HUGE_MASK	PM_4M
+#elif defined(CONFIG_PAGE_SIZE_16KB)
+#define PM_HUGE_MASK	PM_16M
+#elif defined(CONFIG_PAGE_SIZE_32KB)
+#define PM_HUGE_MASK	PM_64M
+#elif defined(CONFIG_PAGE_SIZE_64KB)
+#define PM_HUGE_MASK	PM_256M
+#elif defined(CONFIG_HUGETLB_PAGE)
+#error Bad page size configuration for hugetlbfs!
+#endif
 
 /*
  * Values used for computation of new tlb entries
diff --git a/arch/mips/include/asm/octeon/cvmx-bootinfo.h b/arch/mips/include/asm/octeon/cvmx-bootinfo.h
index 692989a..f3c23a4 100644
--- a/arch/mips/include/asm/octeon/cvmx-bootinfo.h
+++ b/arch/mips/include/asm/octeon/cvmx-bootinfo.h
@@ -157,6 +157,13 @@
 	CVMX_BOARD_TYPE_NIC_XLE_4G = 21,
 	CVMX_BOARD_TYPE_EBT5600 = 22,
 	CVMX_BOARD_TYPE_EBH5201 = 23,
+	CVMX_BOARD_TYPE_EBT5200 = 24,
+	CVMX_BOARD_TYPE_CB5600  = 25,
+	CVMX_BOARD_TYPE_CB5601  = 26,
+	CVMX_BOARD_TYPE_CB5200  = 27,
+	/* Special 'generic' board type, supports many boards */
+	CVMX_BOARD_TYPE_GENERIC = 28,
+	CVMX_BOARD_TYPE_EBH5610 = 29,
 	CVMX_BOARD_TYPE_MAX,
 
 	/*
@@ -228,6 +235,12 @@
 		ENUM_BRD_TYPE_CASE(CVMX_BOARD_TYPE_NIC_XLE_4G)
 		ENUM_BRD_TYPE_CASE(CVMX_BOARD_TYPE_EBT5600)
 		ENUM_BRD_TYPE_CASE(CVMX_BOARD_TYPE_EBH5201)
+		ENUM_BRD_TYPE_CASE(CVMX_BOARD_TYPE_EBT5200)
+		ENUM_BRD_TYPE_CASE(CVMX_BOARD_TYPE_CB5600)
+		ENUM_BRD_TYPE_CASE(CVMX_BOARD_TYPE_CB5601)
+		ENUM_BRD_TYPE_CASE(CVMX_BOARD_TYPE_CB5200)
+		ENUM_BRD_TYPE_CASE(CVMX_BOARD_TYPE_GENERIC)
+		ENUM_BRD_TYPE_CASE(CVMX_BOARD_TYPE_EBH5610)
 		ENUM_BRD_TYPE_CASE(CVMX_BOARD_TYPE_MAX)
 
 			/* Customer boards listed here */
diff --git a/arch/mips/include/asm/octeon/cvmx-bootmem.h b/arch/mips/include/asm/octeon/cvmx-bootmem.h
index 1cbe4b5..8e708bd 100644
--- a/arch/mips/include/asm/octeon/cvmx-bootmem.h
+++ b/arch/mips/include/asm/octeon/cvmx-bootmem.h
@@ -183,6 +183,64 @@
  * Returns 0 on failure,
  *         !0 on success
  */
+
+
+/**
+ * Allocate a block of memory from the free list that was passed
+ * to the application by the bootloader, and assign it a name in the
+ * global named block table.  (part of the cvmx_bootmem_descriptor_t structure)
+ * Named blocks can later be freed.
+ *
+ * @size:      Size in bytes of block to allocate
+ * @alignment: Alignment required - must be power of 2
+ * @name:      name of block - must be less than CVMX_BOOTMEM_NAME_LEN bytes
+ *
+ * Returns a pointer to block of memory, NULL on error
+ */
+extern void *cvmx_bootmem_alloc_named(uint64_t size, uint64_t alignment,
+				      char *name);
+
+
+
+/**
+ * Allocate a block of memory from the free list that was passed
+ * to the application by the bootloader, and assign it a name in the
+ * global named block table.  (part of the cvmx_bootmem_descriptor_t structure)
+ * Named blocks can later be freed.
+ *
+ * @size:     Size in bytes of block to allocate
+ * @address:  Physical address to allocate memory at.  If this
+ *            memory is not available, the allocation fails.
+ * @name:     name of block - must be less than CVMX_BOOTMEM_NAME_LEN
+ *            bytes
+ *
+ * Returns a pointer to block of memory, NULL on error
+ */
+extern void *cvmx_bootmem_alloc_named_address(uint64_t size, uint64_t address,
+					      char *name);
+
+
+
+/**
+ * Allocate a block of memory from a specific range of the free list
+ * that was passed to the application by the bootloader, and assign it
+ * a name in the global named block table.  (part of the
+ * cvmx_bootmem_descriptor_t structure) Named blocks can later be
+ * freed.  If request cannot be satisfied within the address range
+ * specified, NULL is returned
+ *
+ * @size:      Size in bytes of block to allocate
+ * @min_addr:  minimum address of range
+ * @max_addr:  maximum address of range
+ * @align:     Alignment of memory to be allocated. (must be a power of 2)
+ * @name:      name of block - must be less than CVMX_BOOTMEM_NAME_LEN bytes
+ *
+ * Returns a pointer to block of memory, NULL on error
+ */
+extern void *cvmx_bootmem_alloc_named_range(uint64_t size, uint64_t min_addr,
+					    uint64_t max_addr, uint64_t align,
+					    char *name);
+
 extern int cvmx_bootmem_free_named(char *name);
 
 /**
@@ -224,6 +282,33 @@
 			       uint32_t flags);
 
 /**
+ * Allocates a named block of physical memory from the free list, at
+ * (optional) requested address and alignment.
+ *
+ * @param size      size of region to allocate.  All requests are rounded
+ *                  up to be a multiple CVMX_BOOTMEM_ALIGNMENT_SIZE
+ *                  bytes size
+ * @param min_addr Minimum address that block can occupy.
+ * @param max_addr  Specifies the maximum address_min (inclusive) that
+ *                  the allocation can use.
+ * @param alignment Requested alignment of the block.  If this
+ *                  alignment cannot be met, the allocation fails.
+ *                  This must be a power of 2.  (Note: Alignment of
+ *                  CVMX_BOOTMEM_ALIGNMENT_SIZE bytes is required, and
+ *                  internally enforced.  Requested alignments of less
+ *                  than CVMX_BOOTMEM_ALIGNMENT_SIZE are set to
+ *                  CVMX_BOOTMEM_ALIGNMENT_SIZE.)
+ * @param name      name to assign to named block
+ * @param flags     Flags to control options for the allocation.
+ *
+ * @return physical address of block allocated, or -1 on failure
+ */
+int64_t cvmx_bootmem_phy_named_block_alloc(uint64_t size, uint64_t min_addr,
+					   uint64_t max_addr,
+					   uint64_t alignment,
+					   char *name, uint32_t flags);
+
+/**
  * Finds a named memory block by name.
  * Also used for finding an unused entry in the named block table.
  *
diff --git a/arch/mips/include/asm/octeon/cvmx-helper-errata.h b/arch/mips/include/asm/octeon/cvmx-helper-errata.h
new file mode 100644
index 0000000..5fc9918
--- /dev/null
+++ b/arch/mips/include/asm/octeon/cvmx-helper-errata.h
@@ -0,0 +1,33 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_HELPER_ERRATA_H__
+#define __CVMX_HELPER_ERRATA_H__
+
+extern void __cvmx_helper_errata_qlm_disable_2nd_order_cdr(int qlm);
+
+#endif
diff --git a/arch/mips/include/asm/octeon/cvmx-helper-jtag.h b/arch/mips/include/asm/octeon/cvmx-helper-jtag.h
new file mode 100644
index 0000000..29f016d
--- /dev/null
+++ b/arch/mips/include/asm/octeon/cvmx-helper-jtag.h
@@ -0,0 +1,43 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * @file
+ *
+ *  Helper utilities for qlm_jtag.
+ *
+ */
+
+#ifndef __CVMX_HELPER_JTAG_H__
+#define __CVMX_HELPER_JTAG_H__
+
+extern void cvmx_helper_qlm_jtag_init(void);
+extern uint32_t cvmx_helper_qlm_jtag_shift(int qlm, int bits, uint32_t data);
+extern void cvmx_helper_qlm_jtag_shift_zeros(int qlm, int bits);
+extern void cvmx_helper_qlm_jtag_update(int qlm);
+
+#endif /* __CVMX_HELPER_JTAG_H__ */
diff --git a/arch/mips/include/asm/octeon/cvmx-npei-defs.h b/arch/mips/include/asm/octeon/cvmx-npei-defs.h
new file mode 100644
index 0000000..4b347bb
--- /dev/null
+++ b/arch/mips/include/asm/octeon/cvmx-npei-defs.h
@@ -0,0 +1,2560 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_NPEI_DEFS_H__
+#define __CVMX_NPEI_DEFS_H__
+
+#define CVMX_NPEI_BAR1_INDEXX(offset) \
+	 (0x0000000000000000ull + (((offset) & 31) * 16))
+#define CVMX_NPEI_BIST_STATUS \
+	 (0x0000000000000580ull)
+#define CVMX_NPEI_BIST_STATUS2 \
+	 (0x0000000000000680ull)
+#define CVMX_NPEI_CTL_PORT0 \
+	 (0x0000000000000250ull)
+#define CVMX_NPEI_CTL_PORT1 \
+	 (0x0000000000000260ull)
+#define CVMX_NPEI_CTL_STATUS \
+	 (0x0000000000000570ull)
+#define CVMX_NPEI_CTL_STATUS2 \
+	 (0x0000000000003C00ull)
+#define CVMX_NPEI_DATA_OUT_CNT \
+	 (0x00000000000005F0ull)
+#define CVMX_NPEI_DBG_DATA \
+	 (0x0000000000000510ull)
+#define CVMX_NPEI_DBG_SELECT \
+	 (0x0000000000000500ull)
+#define CVMX_NPEI_DMA0_INT_LEVEL \
+	 (0x00000000000005C0ull)
+#define CVMX_NPEI_DMA1_INT_LEVEL \
+	 (0x00000000000005D0ull)
+#define CVMX_NPEI_DMAX_COUNTS(offset) \
+	 (0x0000000000000450ull + (((offset) & 7) * 16))
+#define CVMX_NPEI_DMAX_DBELL(offset) \
+	 (0x00000000000003B0ull + (((offset) & 7) * 16))
+#define CVMX_NPEI_DMAX_IBUFF_SADDR(offset) \
+	 (0x0000000000000400ull + (((offset) & 7) * 16))
+#define CVMX_NPEI_DMAX_NADDR(offset) \
+	 (0x00000000000004A0ull + (((offset) & 7) * 16))
+#define CVMX_NPEI_DMA_CNTS \
+	 (0x00000000000005E0ull)
+#define CVMX_NPEI_DMA_CONTROL \
+	 (0x00000000000003A0ull)
+#define CVMX_NPEI_INT_A_ENB \
+	 (0x0000000000000560ull)
+#define CVMX_NPEI_INT_A_ENB2 \
+	 (0x0000000000003CE0ull)
+#define CVMX_NPEI_INT_A_SUM \
+	 (0x0000000000000550ull)
+#define CVMX_NPEI_INT_ENB \
+	 (0x0000000000000540ull)
+#define CVMX_NPEI_INT_ENB2 \
+	 (0x0000000000003CD0ull)
+#define CVMX_NPEI_INT_INFO \
+	 (0x0000000000000590ull)
+#define CVMX_NPEI_INT_SUM \
+	 (0x0000000000000530ull)
+#define CVMX_NPEI_INT_SUM2 \
+	 (0x0000000000003CC0ull)
+#define CVMX_NPEI_LAST_WIN_RDATA0 \
+	 (0x0000000000000600ull)
+#define CVMX_NPEI_LAST_WIN_RDATA1 \
+	 (0x0000000000000610ull)
+#define CVMX_NPEI_MEM_ACCESS_CTL \
+	 (0x00000000000004F0ull)
+#define CVMX_NPEI_MEM_ACCESS_SUBIDX(offset) \
+	 (0x0000000000000340ull + (((offset) & 31) * 16) - 16 * 12)
+#define CVMX_NPEI_MSI_ENB0 \
+	 (0x0000000000003C50ull)
+#define CVMX_NPEI_MSI_ENB1 \
+	 (0x0000000000003C60ull)
+#define CVMX_NPEI_MSI_ENB2 \
+	 (0x0000000000003C70ull)
+#define CVMX_NPEI_MSI_ENB3 \
+	 (0x0000000000003C80ull)
+#define CVMX_NPEI_MSI_RCV0 \
+	 (0x0000000000003C10ull)
+#define CVMX_NPEI_MSI_RCV1 \
+	 (0x0000000000003C20ull)
+#define CVMX_NPEI_MSI_RCV2 \
+	 (0x0000000000003C30ull)
+#define CVMX_NPEI_MSI_RCV3 \
+	 (0x0000000000003C40ull)
+#define CVMX_NPEI_MSI_RD_MAP \
+	 (0x0000000000003CA0ull)
+#define CVMX_NPEI_MSI_W1C_ENB0 \
+	 (0x0000000000003CF0ull)
+#define CVMX_NPEI_MSI_W1C_ENB1 \
+	 (0x0000000000003D00ull)
+#define CVMX_NPEI_MSI_W1C_ENB2 \
+	 (0x0000000000003D10ull)
+#define CVMX_NPEI_MSI_W1C_ENB3 \
+	 (0x0000000000003D20ull)
+#define CVMX_NPEI_MSI_W1S_ENB0 \
+	 (0x0000000000003D30ull)
+#define CVMX_NPEI_MSI_W1S_ENB1 \
+	 (0x0000000000003D40ull)
+#define CVMX_NPEI_MSI_W1S_ENB2 \
+	 (0x0000000000003D50ull)
+#define CVMX_NPEI_MSI_W1S_ENB3 \
+	 (0x0000000000003D60ull)
+#define CVMX_NPEI_MSI_WR_MAP \
+	 (0x0000000000003C90ull)
+#define CVMX_NPEI_PCIE_CREDIT_CNT \
+	 (0x0000000000003D70ull)
+#define CVMX_NPEI_PCIE_MSI_RCV \
+	 (0x0000000000003CB0ull)
+#define CVMX_NPEI_PCIE_MSI_RCV_B1 \
+	 (0x0000000000000650ull)
+#define CVMX_NPEI_PCIE_MSI_RCV_B2 \
+	 (0x0000000000000660ull)
+#define CVMX_NPEI_PCIE_MSI_RCV_B3 \
+	 (0x0000000000000670ull)
+#define CVMX_NPEI_PKTX_CNTS(offset) \
+	 (0x0000000000002400ull + (((offset) & 31) * 16))
+#define CVMX_NPEI_PKTX_INSTR_BADDR(offset) \
+	 (0x0000000000002800ull + (((offset) & 31) * 16))
+#define CVMX_NPEI_PKTX_INSTR_BAOFF_DBELL(offset) \
+	 (0x0000000000002C00ull + (((offset) & 31) * 16))
+#define CVMX_NPEI_PKTX_INSTR_FIFO_RSIZE(offset) \
+	 (0x0000000000003000ull + (((offset) & 31) * 16))
+#define CVMX_NPEI_PKTX_INSTR_HEADER(offset) \
+	 (0x0000000000003400ull + (((offset) & 31) * 16))
+#define CVMX_NPEI_PKTX_IN_BP(offset) \
+	 (0x0000000000003800ull + (((offset) & 31) * 16))
+#define CVMX_NPEI_PKTX_SLIST_BADDR(offset) \
+	 (0x0000000000001400ull + (((offset) & 31) * 16))
+#define CVMX_NPEI_PKTX_SLIST_BAOFF_DBELL(offset) \
+	 (0x0000000000001800ull + (((offset) & 31) * 16))
+#define CVMX_NPEI_PKTX_SLIST_FIFO_RSIZE(offset) \
+	 (0x0000000000001C00ull + (((offset) & 31) * 16))
+#define CVMX_NPEI_PKT_CNT_INT \
+	 (0x0000000000001110ull)
+#define CVMX_NPEI_PKT_CNT_INT_ENB \
+	 (0x0000000000001130ull)
+#define CVMX_NPEI_PKT_DATA_OUT_ES \
+	 (0x00000000000010B0ull)
+#define CVMX_NPEI_PKT_DATA_OUT_NS \
+	 (0x00000000000010A0ull)
+#define CVMX_NPEI_PKT_DATA_OUT_ROR \
+	 (0x0000000000001090ull)
+#define CVMX_NPEI_PKT_DPADDR \
+	 (0x0000000000001080ull)
+#define CVMX_NPEI_PKT_INPUT_CONTROL \
+	 (0x0000000000001150ull)
+#define CVMX_NPEI_PKT_INSTR_ENB \
+	 (0x0000000000001000ull)
+#define CVMX_NPEI_PKT_INSTR_RD_SIZE \
+	 (0x0000000000001190ull)
+#define CVMX_NPEI_PKT_INSTR_SIZE \
+	 (0x0000000000001020ull)
+#define CVMX_NPEI_PKT_INT_LEVELS \
+	 (0x0000000000001100ull)
+#define CVMX_NPEI_PKT_IN_BP \
+	 (0x00000000000006B0ull)
+#define CVMX_NPEI_PKT_IN_DONEX_CNTS(offset) \
+	 (0x0000000000002000ull + (((offset) & 31) * 16))
+#define CVMX_NPEI_PKT_IN_INSTR_COUNTS \
+	 (0x00000000000006A0ull)
+#define CVMX_NPEI_PKT_IN_PCIE_PORT \
+	 (0x00000000000011A0ull)
+#define CVMX_NPEI_PKT_IPTR \
+	 (0x0000000000001070ull)
+#define CVMX_NPEI_PKT_OUTPUT_WMARK \
+	 (0x0000000000001160ull)
+#define CVMX_NPEI_PKT_OUT_BMODE \
+	 (0x00000000000010D0ull)
+#define CVMX_NPEI_PKT_OUT_ENB \
+	 (0x0000000000001010ull)
+#define CVMX_NPEI_PKT_PCIE_PORT \
+	 (0x00000000000010E0ull)
+#define CVMX_NPEI_PKT_PORT_IN_RST \
+	 (0x0000000000000690ull)
+#define CVMX_NPEI_PKT_SLIST_ES \
+	 (0x0000000000001050ull)
+#define CVMX_NPEI_PKT_SLIST_ID_SIZE \
+	 (0x0000000000001180ull)
+#define CVMX_NPEI_PKT_SLIST_NS \
+	 (0x0000000000001040ull)
+#define CVMX_NPEI_PKT_SLIST_ROR \
+	 (0x0000000000001030ull)
+#define CVMX_NPEI_PKT_TIME_INT \
+	 (0x0000000000001120ull)
+#define CVMX_NPEI_PKT_TIME_INT_ENB \
+	 (0x0000000000001140ull)
+#define CVMX_NPEI_RSL_INT_BLOCKS \
+	 (0x0000000000000520ull)
+#define CVMX_NPEI_SCRATCH_1 \
+	 (0x0000000000000270ull)
+#define CVMX_NPEI_STATE1 \
+	 (0x0000000000000620ull)
+#define CVMX_NPEI_STATE2 \
+	 (0x0000000000000630ull)
+#define CVMX_NPEI_STATE3 \
+	 (0x0000000000000640ull)
+#define CVMX_NPEI_WINDOW_CTL \
+	 (0x0000000000000380ull)
+#define CVMX_NPEI_WIN_RD_ADDR \
+	 (0x0000000000000210ull)
+#define CVMX_NPEI_WIN_RD_DATA \
+	 (0x0000000000000240ull)
+#define CVMX_NPEI_WIN_WR_ADDR \
+	 (0x0000000000000200ull)
+#define CVMX_NPEI_WIN_WR_DATA \
+	 (0x0000000000000220ull)
+#define CVMX_NPEI_WIN_WR_MASK \
+	 (0x0000000000000230ull)
+
+union cvmx_npei_bar1_indexx {
+	uint32_t u32;
+	struct cvmx_npei_bar1_indexx_s {
+		uint32_t reserved_18_31:14;
+		uint32_t addr_idx:14;
+		uint32_t ca:1;
+		uint32_t end_swp:2;
+		uint32_t addr_v:1;
+	} s;
+	struct cvmx_npei_bar1_indexx_s cn52xx;
+	struct cvmx_npei_bar1_indexx_s cn52xxp1;
+	struct cvmx_npei_bar1_indexx_s cn56xx;
+	struct cvmx_npei_bar1_indexx_s cn56xxp1;
+};
+
+union cvmx_npei_bist_status {
+	uint64_t u64;
+	struct cvmx_npei_bist_status_s {
+		uint64_t pkt_rdf:1;
+		uint64_t pkt_pmem:1;
+		uint64_t pkt_p1:1;
+		uint64_t reserved_60_60:1;
+		uint64_t pcr_gim:1;
+		uint64_t pkt_pif:1;
+		uint64_t pcsr_int:1;
+		uint64_t pcsr_im:1;
+		uint64_t pcsr_cnt:1;
+		uint64_t pcsr_id:1;
+		uint64_t pcsr_sl:1;
+		uint64_t reserved_50_52:3;
+		uint64_t pkt_ind:1;
+		uint64_t pkt_slm:1;
+		uint64_t reserved_36_47:12;
+		uint64_t d0_pst:1;
+		uint64_t d1_pst:1;
+		uint64_t d2_pst:1;
+		uint64_t d3_pst:1;
+		uint64_t reserved_31_31:1;
+		uint64_t n2p0_c:1;
+		uint64_t n2p0_o:1;
+		uint64_t n2p1_c:1;
+		uint64_t n2p1_o:1;
+		uint64_t cpl_p0:1;
+		uint64_t cpl_p1:1;
+		uint64_t p2n1_po:1;
+		uint64_t p2n1_no:1;
+		uint64_t p2n1_co:1;
+		uint64_t p2n0_po:1;
+		uint64_t p2n0_no:1;
+		uint64_t p2n0_co:1;
+		uint64_t p2n0_c0:1;
+		uint64_t p2n0_c1:1;
+		uint64_t p2n0_n:1;
+		uint64_t p2n0_p0:1;
+		uint64_t p2n0_p1:1;
+		uint64_t p2n1_c0:1;
+		uint64_t p2n1_c1:1;
+		uint64_t p2n1_n:1;
+		uint64_t p2n1_p0:1;
+		uint64_t p2n1_p1:1;
+		uint64_t csm0:1;
+		uint64_t csm1:1;
+		uint64_t dif0:1;
+		uint64_t dif1:1;
+		uint64_t dif2:1;
+		uint64_t dif3:1;
+		uint64_t reserved_2_2:1;
+		uint64_t msi:1;
+		uint64_t ncb_cmd:1;
+	} s;
+	struct cvmx_npei_bist_status_cn52xx {
+		uint64_t pkt_rdf:1;
+		uint64_t pkt_pmem:1;
+		uint64_t pkt_p1:1;
+		uint64_t reserved_60_60:1;
+		uint64_t pcr_gim:1;
+		uint64_t pkt_pif:1;
+		uint64_t pcsr_int:1;
+		uint64_t pcsr_im:1;
+		uint64_t pcsr_cnt:1;
+		uint64_t pcsr_id:1;
+		uint64_t pcsr_sl:1;
+		uint64_t pkt_imem:1;
+		uint64_t pkt_pfm:1;
+		uint64_t pkt_pof:1;
+		uint64_t reserved_48_49:2;
+		uint64_t pkt_pop0:1;
+		uint64_t pkt_pop1:1;
+		uint64_t d0_mem:1;
+		uint64_t d1_mem:1;
+		uint64_t d2_mem:1;
+		uint64_t d3_mem:1;
+		uint64_t d4_mem:1;
+		uint64_t ds_mem:1;
+		uint64_t reserved_36_39:4;
+		uint64_t d0_pst:1;
+		uint64_t d1_pst:1;
+		uint64_t d2_pst:1;
+		uint64_t d3_pst:1;
+		uint64_t d4_pst:1;
+		uint64_t n2p0_c:1;
+		uint64_t n2p0_o:1;
+		uint64_t n2p1_c:1;
+		uint64_t n2p1_o:1;
+		uint64_t cpl_p0:1;
+		uint64_t cpl_p1:1;
+		uint64_t p2n1_po:1;
+		uint64_t p2n1_no:1;
+		uint64_t p2n1_co:1;
+		uint64_t p2n0_po:1;
+		uint64_t p2n0_no:1;
+		uint64_t p2n0_co:1;
+		uint64_t p2n0_c0:1;
+		uint64_t p2n0_c1:1;
+		uint64_t p2n0_n:1;
+		uint64_t p2n0_p0:1;
+		uint64_t p2n0_p1:1;
+		uint64_t p2n1_c0:1;
+		uint64_t p2n1_c1:1;
+		uint64_t p2n1_n:1;
+		uint64_t p2n1_p0:1;
+		uint64_t p2n1_p1:1;
+		uint64_t csm0:1;
+		uint64_t csm1:1;
+		uint64_t dif0:1;
+		uint64_t dif1:1;
+		uint64_t dif2:1;
+		uint64_t dif3:1;
+		uint64_t dif4:1;
+		uint64_t msi:1;
+		uint64_t ncb_cmd:1;
+	} cn52xx;
+	struct cvmx_npei_bist_status_cn52xxp1 {
+		uint64_t reserved_46_63:18;
+		uint64_t d0_mem0:1;
+		uint64_t d1_mem1:1;
+		uint64_t d2_mem2:1;
+		uint64_t d3_mem3:1;
+		uint64_t dr0_mem:1;
+		uint64_t d0_mem:1;
+		uint64_t d1_mem:1;
+		uint64_t d2_mem:1;
+		uint64_t d3_mem:1;
+		uint64_t dr1_mem:1;
+		uint64_t d0_pst:1;
+		uint64_t d1_pst:1;
+		uint64_t d2_pst:1;
+		uint64_t d3_pst:1;
+		uint64_t dr2_mem:1;
+		uint64_t n2p0_c:1;
+		uint64_t n2p0_o:1;
+		uint64_t n2p1_c:1;
+		uint64_t n2p1_o:1;
+		uint64_t cpl_p0:1;
+		uint64_t cpl_p1:1;
+		uint64_t p2n1_po:1;
+		uint64_t p2n1_no:1;
+		uint64_t p2n1_co:1;
+		uint64_t p2n0_po:1;
+		uint64_t p2n0_no:1;
+		uint64_t p2n0_co:1;
+		uint64_t p2n0_c0:1;
+		uint64_t p2n0_c1:1;
+		uint64_t p2n0_n:1;
+		uint64_t p2n0_p0:1;
+		uint64_t p2n0_p1:1;
+		uint64_t p2n1_c0:1;
+		uint64_t p2n1_c1:1;
+		uint64_t p2n1_n:1;
+		uint64_t p2n1_p0:1;
+		uint64_t p2n1_p1:1;
+		uint64_t csm0:1;
+		uint64_t csm1:1;
+		uint64_t dif0:1;
+		uint64_t dif1:1;
+		uint64_t dif2:1;
+		uint64_t dif3:1;
+		uint64_t dr3_mem:1;
+		uint64_t msi:1;
+		uint64_t ncb_cmd:1;
+	} cn52xxp1;
+	struct cvmx_npei_bist_status_cn56xx {
+		uint64_t pkt_rdf:1;
+		uint64_t reserved_60_62:3;
+		uint64_t pcr_gim:1;
+		uint64_t pkt_pif:1;
+		uint64_t pcsr_int:1;
+		uint64_t pcsr_im:1;
+		uint64_t pcsr_cnt:1;
+		uint64_t pcsr_id:1;
+		uint64_t pcsr_sl:1;
+		uint64_t pkt_imem:1;
+		uint64_t pkt_pfm:1;
+		uint64_t pkt_pof:1;
+		uint64_t reserved_48_49:2;
+		uint64_t pkt_pop0:1;
+		uint64_t pkt_pop1:1;
+		uint64_t d0_mem:1;
+		uint64_t d1_mem:1;
+		uint64_t d2_mem:1;
+		uint64_t d3_mem:1;
+		uint64_t d4_mem:1;
+		uint64_t ds_mem:1;
+		uint64_t reserved_36_39:4;
+		uint64_t d0_pst:1;
+		uint64_t d1_pst:1;
+		uint64_t d2_pst:1;
+		uint64_t d3_pst:1;
+		uint64_t d4_pst:1;
+		uint64_t n2p0_c:1;
+		uint64_t n2p0_o:1;
+		uint64_t n2p1_c:1;
+		uint64_t n2p1_o:1;
+		uint64_t cpl_p0:1;
+		uint64_t cpl_p1:1;
+		uint64_t p2n1_po:1;
+		uint64_t p2n1_no:1;
+		uint64_t p2n1_co:1;
+		uint64_t p2n0_po:1;
+		uint64_t p2n0_no:1;
+		uint64_t p2n0_co:1;
+		uint64_t p2n0_c0:1;
+		uint64_t p2n0_c1:1;
+		uint64_t p2n0_n:1;
+		uint64_t p2n0_p0:1;
+		uint64_t p2n0_p1:1;
+		uint64_t p2n1_c0:1;
+		uint64_t p2n1_c1:1;
+		uint64_t p2n1_n:1;
+		uint64_t p2n1_p0:1;
+		uint64_t p2n1_p1:1;
+		uint64_t csm0:1;
+		uint64_t csm1:1;
+		uint64_t dif0:1;
+		uint64_t dif1:1;
+		uint64_t dif2:1;
+		uint64_t dif3:1;
+		uint64_t dif4:1;
+		uint64_t msi:1;
+		uint64_t ncb_cmd:1;
+	} cn56xx;
+	struct cvmx_npei_bist_status_cn56xxp1 {
+		uint64_t reserved_58_63:6;
+		uint64_t pcsr_int:1;
+		uint64_t pcsr_im:1;
+		uint64_t pcsr_cnt:1;
+		uint64_t pcsr_id:1;
+		uint64_t pcsr_sl:1;
+		uint64_t pkt_pout:1;
+		uint64_t pkt_imem:1;
+		uint64_t pkt_cntm:1;
+		uint64_t pkt_ind:1;
+		uint64_t pkt_slm:1;
+		uint64_t pkt_odf:1;
+		uint64_t pkt_oif:1;
+		uint64_t pkt_out:1;
+		uint64_t pkt_i0:1;
+		uint64_t pkt_i1:1;
+		uint64_t pkt_s0:1;
+		uint64_t pkt_s1:1;
+		uint64_t d0_mem:1;
+		uint64_t d1_mem:1;
+		uint64_t d2_mem:1;
+		uint64_t d3_mem:1;
+		uint64_t d4_mem:1;
+		uint64_t d0_pst:1;
+		uint64_t d1_pst:1;
+		uint64_t d2_pst:1;
+		uint64_t d3_pst:1;
+		uint64_t d4_pst:1;
+		uint64_t n2p0_c:1;
+		uint64_t n2p0_o:1;
+		uint64_t n2p1_c:1;
+		uint64_t n2p1_o:1;
+		uint64_t cpl_p0:1;
+		uint64_t cpl_p1:1;
+		uint64_t p2n1_po:1;
+		uint64_t p2n1_no:1;
+		uint64_t p2n1_co:1;
+		uint64_t p2n0_po:1;
+		uint64_t p2n0_no:1;
+		uint64_t p2n0_co:1;
+		uint64_t p2n0_c0:1;
+		uint64_t p2n0_c1:1;
+		uint64_t p2n0_n:1;
+		uint64_t p2n0_p0:1;
+		uint64_t p2n0_p1:1;
+		uint64_t p2n1_c0:1;
+		uint64_t p2n1_c1:1;
+		uint64_t p2n1_n:1;
+		uint64_t p2n1_p0:1;
+		uint64_t p2n1_p1:1;
+		uint64_t csm0:1;
+		uint64_t csm1:1;
+		uint64_t dif0:1;
+		uint64_t dif1:1;
+		uint64_t dif2:1;
+		uint64_t dif3:1;
+		uint64_t dif4:1;
+		uint64_t msi:1;
+		uint64_t ncb_cmd:1;
+	} cn56xxp1;
+};
+
+union cvmx_npei_bist_status2 {
+	uint64_t u64;
+	struct cvmx_npei_bist_status2_s {
+		uint64_t reserved_5_63:59;
+		uint64_t psc_p0:1;
+		uint64_t psc_p1:1;
+		uint64_t pkt_gd:1;
+		uint64_t pkt_gl:1;
+		uint64_t pkt_blk:1;
+	} s;
+	struct cvmx_npei_bist_status2_s cn52xx;
+	struct cvmx_npei_bist_status2_s cn56xx;
+};
+
+union cvmx_npei_ctl_port0 {
+	uint64_t u64;
+	struct cvmx_npei_ctl_port0_s {
+		uint64_t reserved_21_63:43;
+		uint64_t waitl_com:1;
+		uint64_t intd:1;
+		uint64_t intc:1;
+		uint64_t intb:1;
+		uint64_t inta:1;
+		uint64_t intd_map:2;
+		uint64_t intc_map:2;
+		uint64_t intb_map:2;
+		uint64_t inta_map:2;
+		uint64_t ctlp_ro:1;
+		uint64_t reserved_6_6:1;
+		uint64_t ptlp_ro:1;
+		uint64_t bar2_enb:1;
+		uint64_t bar2_esx:2;
+		uint64_t bar2_cax:1;
+		uint64_t wait_com:1;
+	} s;
+	struct cvmx_npei_ctl_port0_s cn52xx;
+	struct cvmx_npei_ctl_port0_s cn52xxp1;
+	struct cvmx_npei_ctl_port0_s cn56xx;
+	struct cvmx_npei_ctl_port0_s cn56xxp1;
+};
+
+union cvmx_npei_ctl_port1 {
+	uint64_t u64;
+	struct cvmx_npei_ctl_port1_s {
+		uint64_t reserved_21_63:43;
+		uint64_t waitl_com:1;
+		uint64_t intd:1;
+		uint64_t intc:1;
+		uint64_t intb:1;
+		uint64_t inta:1;
+		uint64_t intd_map:2;
+		uint64_t intc_map:2;
+		uint64_t intb_map:2;
+		uint64_t inta_map:2;
+		uint64_t ctlp_ro:1;
+		uint64_t reserved_6_6:1;
+		uint64_t ptlp_ro:1;
+		uint64_t bar2_enb:1;
+		uint64_t bar2_esx:2;
+		uint64_t bar2_cax:1;
+		uint64_t wait_com:1;
+	} s;
+	struct cvmx_npei_ctl_port1_s cn52xx;
+	struct cvmx_npei_ctl_port1_s cn52xxp1;
+	struct cvmx_npei_ctl_port1_s cn56xx;
+	struct cvmx_npei_ctl_port1_s cn56xxp1;
+};
+
+union cvmx_npei_ctl_status {
+	uint64_t u64;
+	struct cvmx_npei_ctl_status_s {
+		uint64_t reserved_44_63:20;
+		uint64_t p1_ntags:6;
+		uint64_t p0_ntags:6;
+		uint64_t cfg_rtry:16;
+		uint64_t ring_en:1;
+		uint64_t lnk_rst:1;
+		uint64_t arb:1;
+		uint64_t pkt_bp:4;
+		uint64_t host_mode:1;
+		uint64_t chip_rev:8;
+	} s;
+	struct cvmx_npei_ctl_status_s cn52xx;
+	struct cvmx_npei_ctl_status_cn52xxp1 {
+		uint64_t reserved_44_63:20;
+		uint64_t p1_ntags:6;
+		uint64_t p0_ntags:6;
+		uint64_t cfg_rtry:16;
+		uint64_t reserved_15_15:1;
+		uint64_t lnk_rst:1;
+		uint64_t arb:1;
+		uint64_t reserved_9_12:4;
+		uint64_t host_mode:1;
+		uint64_t chip_rev:8;
+	} cn52xxp1;
+	struct cvmx_npei_ctl_status_s cn56xx;
+	struct cvmx_npei_ctl_status_cn56xxp1 {
+		uint64_t reserved_16_63:48;
+		uint64_t ring_en:1;
+		uint64_t lnk_rst:1;
+		uint64_t arb:1;
+		uint64_t pkt_bp:4;
+		uint64_t host_mode:1;
+		uint64_t chip_rev:8;
+	} cn56xxp1;
+};
+
+union cvmx_npei_ctl_status2 {
+	uint64_t u64;
+	struct cvmx_npei_ctl_status2_s {
+		uint64_t reserved_16_63:48;
+		uint64_t mps:1;
+		uint64_t mrrs:3;
+		uint64_t c1_w_flt:1;
+		uint64_t c0_w_flt:1;
+		uint64_t c1_b1_s:3;
+		uint64_t c0_b1_s:3;
+		uint64_t c1_wi_d:1;
+		uint64_t c1_b0_d:1;
+		uint64_t c0_wi_d:1;
+		uint64_t c0_b0_d:1;
+	} s;
+	struct cvmx_npei_ctl_status2_s cn52xx;
+	struct cvmx_npei_ctl_status2_s cn52xxp1;
+	struct cvmx_npei_ctl_status2_s cn56xx;
+	struct cvmx_npei_ctl_status2_s cn56xxp1;
+};
+
+union cvmx_npei_data_out_cnt {
+	uint64_t u64;
+	struct cvmx_npei_data_out_cnt_s {
+		uint64_t reserved_44_63:20;
+		uint64_t p1_ucnt:16;
+		uint64_t p1_fcnt:6;
+		uint64_t p0_ucnt:16;
+		uint64_t p0_fcnt:6;
+	} s;
+	struct cvmx_npei_data_out_cnt_s cn52xx;
+	struct cvmx_npei_data_out_cnt_s cn52xxp1;
+	struct cvmx_npei_data_out_cnt_s cn56xx;
+	struct cvmx_npei_data_out_cnt_s cn56xxp1;
+};
+
+union cvmx_npei_dbg_data {
+	uint64_t u64;
+	struct cvmx_npei_dbg_data_s {
+		uint64_t reserved_28_63:36;
+		uint64_t qlm0_rev_lanes:1;
+		uint64_t reserved_25_26:2;
+		uint64_t qlm1_spd:2;
+		uint64_t c_mul:5;
+		uint64_t dsel_ext:1;
+		uint64_t data:17;
+	} s;
+	struct cvmx_npei_dbg_data_cn52xx {
+		uint64_t reserved_29_63:35;
+		uint64_t qlm0_link_width:1;
+		uint64_t qlm0_rev_lanes:1;
+		uint64_t qlm1_mode:2;
+		uint64_t qlm1_spd:2;
+		uint64_t c_mul:5;
+		uint64_t dsel_ext:1;
+		uint64_t data:17;
+	} cn52xx;
+	struct cvmx_npei_dbg_data_cn52xx cn52xxp1;
+	struct cvmx_npei_dbg_data_cn56xx {
+		uint64_t reserved_29_63:35;
+		uint64_t qlm2_rev_lanes:1;
+		uint64_t qlm0_rev_lanes:1;
+		uint64_t qlm3_spd:2;
+		uint64_t qlm1_spd:2;
+		uint64_t c_mul:5;
+		uint64_t dsel_ext:1;
+		uint64_t data:17;
+	} cn56xx;
+	struct cvmx_npei_dbg_data_cn56xx cn56xxp1;
+};
+
+union cvmx_npei_dbg_select {
+	uint64_t u64;
+	struct cvmx_npei_dbg_select_s {
+		uint64_t reserved_16_63:48;
+		uint64_t dbg_sel:16;
+	} s;
+	struct cvmx_npei_dbg_select_s cn52xx;
+	struct cvmx_npei_dbg_select_s cn52xxp1;
+	struct cvmx_npei_dbg_select_s cn56xx;
+	struct cvmx_npei_dbg_select_s cn56xxp1;
+};
+
+union cvmx_npei_dmax_counts {
+	uint64_t u64;
+	struct cvmx_npei_dmax_counts_s {
+		uint64_t reserved_39_63:25;
+		uint64_t fcnt:7;
+		uint64_t dbell:32;
+	} s;
+	struct cvmx_npei_dmax_counts_s cn52xx;
+	struct cvmx_npei_dmax_counts_s cn52xxp1;
+	struct cvmx_npei_dmax_counts_s cn56xx;
+	struct cvmx_npei_dmax_counts_s cn56xxp1;
+};
+
+union cvmx_npei_dmax_dbell {
+	uint32_t u32;
+	struct cvmx_npei_dmax_dbell_s {
+		uint32_t reserved_16_31:16;
+		uint32_t dbell:16;
+	} s;
+	struct cvmx_npei_dmax_dbell_s cn52xx;
+	struct cvmx_npei_dmax_dbell_s cn52xxp1;
+	struct cvmx_npei_dmax_dbell_s cn56xx;
+	struct cvmx_npei_dmax_dbell_s cn56xxp1;
+};
+
+union cvmx_npei_dmax_ibuff_saddr {
+	uint64_t u64;
+	struct cvmx_npei_dmax_ibuff_saddr_s {
+		uint64_t reserved_37_63:27;
+		uint64_t idle:1;
+		uint64_t saddr:29;
+		uint64_t reserved_0_6:7;
+	} s;
+	struct cvmx_npei_dmax_ibuff_saddr_cn52xx {
+		uint64_t reserved_36_63:28;
+		uint64_t saddr:29;
+		uint64_t reserved_0_6:7;
+	} cn52xx;
+	struct cvmx_npei_dmax_ibuff_saddr_cn52xx cn52xxp1;
+	struct cvmx_npei_dmax_ibuff_saddr_s cn56xx;
+	struct cvmx_npei_dmax_ibuff_saddr_cn52xx cn56xxp1;
+};
+
+union cvmx_npei_dmax_naddr {
+	uint64_t u64;
+	struct cvmx_npei_dmax_naddr_s {
+		uint64_t reserved_36_63:28;
+		uint64_t addr:36;
+	} s;
+	struct cvmx_npei_dmax_naddr_s cn52xx;
+	struct cvmx_npei_dmax_naddr_s cn52xxp1;
+	struct cvmx_npei_dmax_naddr_s cn56xx;
+	struct cvmx_npei_dmax_naddr_s cn56xxp1;
+};
+
+union cvmx_npei_dma0_int_level {
+	uint64_t u64;
+	struct cvmx_npei_dma0_int_level_s {
+		uint64_t time:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_npei_dma0_int_level_s cn52xx;
+	struct cvmx_npei_dma0_int_level_s cn52xxp1;
+	struct cvmx_npei_dma0_int_level_s cn56xx;
+	struct cvmx_npei_dma0_int_level_s cn56xxp1;
+};
+
+union cvmx_npei_dma1_int_level {
+	uint64_t u64;
+	struct cvmx_npei_dma1_int_level_s {
+		uint64_t time:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_npei_dma1_int_level_s cn52xx;
+	struct cvmx_npei_dma1_int_level_s cn52xxp1;
+	struct cvmx_npei_dma1_int_level_s cn56xx;
+	struct cvmx_npei_dma1_int_level_s cn56xxp1;
+};
+
+union cvmx_npei_dma_cnts {
+	uint64_t u64;
+	struct cvmx_npei_dma_cnts_s {
+		uint64_t dma1:32;
+		uint64_t dma0:32;
+	} s;
+	struct cvmx_npei_dma_cnts_s cn52xx;
+	struct cvmx_npei_dma_cnts_s cn52xxp1;
+	struct cvmx_npei_dma_cnts_s cn56xx;
+	struct cvmx_npei_dma_cnts_s cn56xxp1;
+};
+
+union cvmx_npei_dma_control {
+	uint64_t u64;
+	struct cvmx_npei_dma_control_s {
+		uint64_t reserved_39_63:25;
+		uint64_t dma4_enb:1;
+		uint64_t dma3_enb:1;
+		uint64_t dma2_enb:1;
+		uint64_t dma1_enb:1;
+		uint64_t dma0_enb:1;
+		uint64_t b0_lend:1;
+		uint64_t dwb_denb:1;
+		uint64_t dwb_ichk:9;
+		uint64_t fpa_que:3;
+		uint64_t o_add1:1;
+		uint64_t o_ro:1;
+		uint64_t o_ns:1;
+		uint64_t o_es:2;
+		uint64_t o_mode:1;
+		uint64_t csize:14;
+	} s;
+	struct cvmx_npei_dma_control_s cn52xx;
+	struct cvmx_npei_dma_control_cn52xxp1 {
+		uint64_t reserved_38_63:26;
+		uint64_t dma3_enb:1;
+		uint64_t dma2_enb:1;
+		uint64_t dma1_enb:1;
+		uint64_t dma0_enb:1;
+		uint64_t b0_lend:1;
+		uint64_t dwb_denb:1;
+		uint64_t dwb_ichk:9;
+		uint64_t fpa_que:3;
+		uint64_t o_add1:1;
+		uint64_t o_ro:1;
+		uint64_t o_ns:1;
+		uint64_t o_es:2;
+		uint64_t o_mode:1;
+		uint64_t csize:14;
+	} cn52xxp1;
+	struct cvmx_npei_dma_control_s cn56xx;
+	struct cvmx_npei_dma_control_s cn56xxp1;
+};
+
+union cvmx_npei_int_a_enb {
+	uint64_t u64;
+	struct cvmx_npei_int_a_enb_s {
+		uint64_t reserved_10_63:54;
+		uint64_t pout_err:1;
+		uint64_t pin_bp:1;
+		uint64_t p1_rdlk:1;
+		uint64_t p0_rdlk:1;
+		uint64_t pgl_err:1;
+		uint64_t pdi_err:1;
+		uint64_t pop_err:1;
+		uint64_t pins_err:1;
+		uint64_t dma1_cpl:1;
+		uint64_t dma0_cpl:1;
+	} s;
+	struct cvmx_npei_int_a_enb_cn52xx {
+		uint64_t reserved_8_63:56;
+		uint64_t p1_rdlk:1;
+		uint64_t p0_rdlk:1;
+		uint64_t pgl_err:1;
+		uint64_t pdi_err:1;
+		uint64_t pop_err:1;
+		uint64_t pins_err:1;
+		uint64_t dma1_cpl:1;
+		uint64_t dma0_cpl:1;
+	} cn52xx;
+	struct cvmx_npei_int_a_enb_cn52xxp1 {
+		uint64_t reserved_2_63:62;
+		uint64_t dma1_cpl:1;
+		uint64_t dma0_cpl:1;
+	} cn52xxp1;
+	struct cvmx_npei_int_a_enb_s cn56xx;
+};
+
+union cvmx_npei_int_a_enb2 {
+	uint64_t u64;
+	struct cvmx_npei_int_a_enb2_s {
+		uint64_t reserved_10_63:54;
+		uint64_t pout_err:1;
+		uint64_t pin_bp:1;
+		uint64_t p1_rdlk:1;
+		uint64_t p0_rdlk:1;
+		uint64_t pgl_err:1;
+		uint64_t pdi_err:1;
+		uint64_t pop_err:1;
+		uint64_t pins_err:1;
+		uint64_t dma1_cpl:1;
+		uint64_t dma0_cpl:1;
+	} s;
+	struct cvmx_npei_int_a_enb2_cn52xx {
+		uint64_t reserved_8_63:56;
+		uint64_t p1_rdlk:1;
+		uint64_t p0_rdlk:1;
+		uint64_t pgl_err:1;
+		uint64_t pdi_err:1;
+		uint64_t pop_err:1;
+		uint64_t pins_err:1;
+		uint64_t reserved_0_1:2;
+	} cn52xx;
+	struct cvmx_npei_int_a_enb2_cn52xxp1 {
+		uint64_t reserved_2_63:62;
+		uint64_t dma1_cpl:1;
+		uint64_t dma0_cpl:1;
+	} cn52xxp1;
+	struct cvmx_npei_int_a_enb2_s cn56xx;
+};
+
+union cvmx_npei_int_a_sum {
+	uint64_t u64;
+	struct cvmx_npei_int_a_sum_s {
+		uint64_t reserved_10_63:54;
+		uint64_t pout_err:1;
+		uint64_t pin_bp:1;
+		uint64_t p1_rdlk:1;
+		uint64_t p0_rdlk:1;
+		uint64_t pgl_err:1;
+		uint64_t pdi_err:1;
+		uint64_t pop_err:1;
+		uint64_t pins_err:1;
+		uint64_t dma1_cpl:1;
+		uint64_t dma0_cpl:1;
+	} s;
+	struct cvmx_npei_int_a_sum_cn52xx {
+		uint64_t reserved_8_63:56;
+		uint64_t p1_rdlk:1;
+		uint64_t p0_rdlk:1;
+		uint64_t pgl_err:1;
+		uint64_t pdi_err:1;
+		uint64_t pop_err:1;
+		uint64_t pins_err:1;
+		uint64_t dma1_cpl:1;
+		uint64_t dma0_cpl:1;
+	} cn52xx;
+	struct cvmx_npei_int_a_sum_cn52xxp1 {
+		uint64_t reserved_2_63:62;
+		uint64_t dma1_cpl:1;
+		uint64_t dma0_cpl:1;
+	} cn52xxp1;
+	struct cvmx_npei_int_a_sum_s cn56xx;
+};
+
+union cvmx_npei_int_enb {
+	uint64_t u64;
+	struct cvmx_npei_int_enb_s {
+		uint64_t mio_inta:1;
+		uint64_t reserved_62_62:1;
+		uint64_t int_a:1;
+		uint64_t c1_ldwn:1;
+		uint64_t c0_ldwn:1;
+		uint64_t c1_exc:1;
+		uint64_t c0_exc:1;
+		uint64_t c1_up_wf:1;
+		uint64_t c0_up_wf:1;
+		uint64_t c1_un_wf:1;
+		uint64_t c0_un_wf:1;
+		uint64_t c1_un_bx:1;
+		uint64_t c1_un_wi:1;
+		uint64_t c1_un_b2:1;
+		uint64_t c1_un_b1:1;
+		uint64_t c1_un_b0:1;
+		uint64_t c1_up_bx:1;
+		uint64_t c1_up_wi:1;
+		uint64_t c1_up_b2:1;
+		uint64_t c1_up_b1:1;
+		uint64_t c1_up_b0:1;
+		uint64_t c0_un_bx:1;
+		uint64_t c0_un_wi:1;
+		uint64_t c0_un_b2:1;
+		uint64_t c0_un_b1:1;
+		uint64_t c0_un_b0:1;
+		uint64_t c0_up_bx:1;
+		uint64_t c0_up_wi:1;
+		uint64_t c0_up_b2:1;
+		uint64_t c0_up_b1:1;
+		uint64_t c0_up_b0:1;
+		uint64_t c1_hpint:1;
+		uint64_t c1_pmei:1;
+		uint64_t c1_wake:1;
+		uint64_t crs1_dr:1;
+		uint64_t c1_se:1;
+		uint64_t crs1_er:1;
+		uint64_t c1_aeri:1;
+		uint64_t c0_hpint:1;
+		uint64_t c0_pmei:1;
+		uint64_t c0_wake:1;
+		uint64_t crs0_dr:1;
+		uint64_t c0_se:1;
+		uint64_t crs0_er:1;
+		uint64_t c0_aeri:1;
+		uint64_t ptime:1;
+		uint64_t pcnt:1;
+		uint64_t pidbof:1;
+		uint64_t psldbof:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t dma1fi:1;
+		uint64_t dma0fi:1;
+		uint64_t dma4dbo:1;
+		uint64_t dma3dbo:1;
+		uint64_t dma2dbo:1;
+		uint64_t dma1dbo:1;
+		uint64_t dma0dbo:1;
+		uint64_t iob2big:1;
+		uint64_t bar0_to:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} s;
+	struct cvmx_npei_int_enb_s cn52xx;
+	struct cvmx_npei_int_enb_cn52xxp1 {
+		uint64_t mio_inta:1;
+		uint64_t reserved_62_62:1;
+		uint64_t int_a:1;
+		uint64_t c1_ldwn:1;
+		uint64_t c0_ldwn:1;
+		uint64_t c1_exc:1;
+		uint64_t c0_exc:1;
+		uint64_t c1_up_wf:1;
+		uint64_t c0_up_wf:1;
+		uint64_t c1_un_wf:1;
+		uint64_t c0_un_wf:1;
+		uint64_t c1_un_bx:1;
+		uint64_t c1_un_wi:1;
+		uint64_t c1_un_b2:1;
+		uint64_t c1_un_b1:1;
+		uint64_t c1_un_b0:1;
+		uint64_t c1_up_bx:1;
+		uint64_t c1_up_wi:1;
+		uint64_t c1_up_b2:1;
+		uint64_t c1_up_b1:1;
+		uint64_t c1_up_b0:1;
+		uint64_t c0_un_bx:1;
+		uint64_t c0_un_wi:1;
+		uint64_t c0_un_b2:1;
+		uint64_t c0_un_b1:1;
+		uint64_t c0_un_b0:1;
+		uint64_t c0_up_bx:1;
+		uint64_t c0_up_wi:1;
+		uint64_t c0_up_b2:1;
+		uint64_t c0_up_b1:1;
+		uint64_t c0_up_b0:1;
+		uint64_t c1_hpint:1;
+		uint64_t c1_pmei:1;
+		uint64_t c1_wake:1;
+		uint64_t crs1_dr:1;
+		uint64_t c1_se:1;
+		uint64_t crs1_er:1;
+		uint64_t c1_aeri:1;
+		uint64_t c0_hpint:1;
+		uint64_t c0_pmei:1;
+		uint64_t c0_wake:1;
+		uint64_t crs0_dr:1;
+		uint64_t c0_se:1;
+		uint64_t crs0_er:1;
+		uint64_t c0_aeri:1;
+		uint64_t ptime:1;
+		uint64_t pcnt:1;
+		uint64_t pidbof:1;
+		uint64_t psldbof:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t dma1fi:1;
+		uint64_t dma0fi:1;
+		uint64_t reserved_8_8:1;
+		uint64_t dma3dbo:1;
+		uint64_t dma2dbo:1;
+		uint64_t dma1dbo:1;
+		uint64_t dma0dbo:1;
+		uint64_t iob2big:1;
+		uint64_t bar0_to:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn52xxp1;
+	struct cvmx_npei_int_enb_s cn56xx;
+	struct cvmx_npei_int_enb_cn56xxp1 {
+		uint64_t mio_inta:1;
+		uint64_t reserved_61_62:2;
+		uint64_t c1_ldwn:1;
+		uint64_t c0_ldwn:1;
+		uint64_t c1_exc:1;
+		uint64_t c0_exc:1;
+		uint64_t c1_up_wf:1;
+		uint64_t c0_up_wf:1;
+		uint64_t c1_un_wf:1;
+		uint64_t c0_un_wf:1;
+		uint64_t c1_un_bx:1;
+		uint64_t c1_un_wi:1;
+		uint64_t c1_un_b2:1;
+		uint64_t c1_un_b1:1;
+		uint64_t c1_un_b0:1;
+		uint64_t c1_up_bx:1;
+		uint64_t c1_up_wi:1;
+		uint64_t c1_up_b2:1;
+		uint64_t c1_up_b1:1;
+		uint64_t c1_up_b0:1;
+		uint64_t c0_un_bx:1;
+		uint64_t c0_un_wi:1;
+		uint64_t c0_un_b2:1;
+		uint64_t c0_un_b1:1;
+		uint64_t c0_un_b0:1;
+		uint64_t c0_up_bx:1;
+		uint64_t c0_up_wi:1;
+		uint64_t c0_up_b2:1;
+		uint64_t c0_up_b1:1;
+		uint64_t c0_up_b0:1;
+		uint64_t c1_hpint:1;
+		uint64_t c1_pmei:1;
+		uint64_t c1_wake:1;
+		uint64_t reserved_29_29:1;
+		uint64_t c1_se:1;
+		uint64_t reserved_27_27:1;
+		uint64_t c1_aeri:1;
+		uint64_t c0_hpint:1;
+		uint64_t c0_pmei:1;
+		uint64_t c0_wake:1;
+		uint64_t reserved_22_22:1;
+		uint64_t c0_se:1;
+		uint64_t reserved_20_20:1;
+		uint64_t c0_aeri:1;
+		uint64_t ptime:1;
+		uint64_t pcnt:1;
+		uint64_t pidbof:1;
+		uint64_t psldbof:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t dma1fi:1;
+		uint64_t dma0fi:1;
+		uint64_t dma4dbo:1;
+		uint64_t dma3dbo:1;
+		uint64_t dma2dbo:1;
+		uint64_t dma1dbo:1;
+		uint64_t dma0dbo:1;
+		uint64_t iob2big:1;
+		uint64_t bar0_to:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn56xxp1;
+};
+
+union cvmx_npei_int_enb2 {
+	uint64_t u64;
+	struct cvmx_npei_int_enb2_s {
+		uint64_t reserved_62_63:2;
+		uint64_t int_a:1;
+		uint64_t c1_ldwn:1;
+		uint64_t c0_ldwn:1;
+		uint64_t c1_exc:1;
+		uint64_t c0_exc:1;
+		uint64_t c1_up_wf:1;
+		uint64_t c0_up_wf:1;
+		uint64_t c1_un_wf:1;
+		uint64_t c0_un_wf:1;
+		uint64_t c1_un_bx:1;
+		uint64_t c1_un_wi:1;
+		uint64_t c1_un_b2:1;
+		uint64_t c1_un_b1:1;
+		uint64_t c1_un_b0:1;
+		uint64_t c1_up_bx:1;
+		uint64_t c1_up_wi:1;
+		uint64_t c1_up_b2:1;
+		uint64_t c1_up_b1:1;
+		uint64_t c1_up_b0:1;
+		uint64_t c0_un_bx:1;
+		uint64_t c0_un_wi:1;
+		uint64_t c0_un_b2:1;
+		uint64_t c0_un_b1:1;
+		uint64_t c0_un_b0:1;
+		uint64_t c0_up_bx:1;
+		uint64_t c0_up_wi:1;
+		uint64_t c0_up_b2:1;
+		uint64_t c0_up_b1:1;
+		uint64_t c0_up_b0:1;
+		uint64_t c1_hpint:1;
+		uint64_t c1_pmei:1;
+		uint64_t c1_wake:1;
+		uint64_t crs1_dr:1;
+		uint64_t c1_se:1;
+		uint64_t crs1_er:1;
+		uint64_t c1_aeri:1;
+		uint64_t c0_hpint:1;
+		uint64_t c0_pmei:1;
+		uint64_t c0_wake:1;
+		uint64_t crs0_dr:1;
+		uint64_t c0_se:1;
+		uint64_t crs0_er:1;
+		uint64_t c0_aeri:1;
+		uint64_t ptime:1;
+		uint64_t pcnt:1;
+		uint64_t pidbof:1;
+		uint64_t psldbof:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t dma1fi:1;
+		uint64_t dma0fi:1;
+		uint64_t dma4dbo:1;
+		uint64_t dma3dbo:1;
+		uint64_t dma2dbo:1;
+		uint64_t dma1dbo:1;
+		uint64_t dma0dbo:1;
+		uint64_t iob2big:1;
+		uint64_t bar0_to:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} s;
+	struct cvmx_npei_int_enb2_s cn52xx;
+	struct cvmx_npei_int_enb2_cn52xxp1 {
+		uint64_t reserved_62_63:2;
+		uint64_t int_a:1;
+		uint64_t c1_ldwn:1;
+		uint64_t c0_ldwn:1;
+		uint64_t c1_exc:1;
+		uint64_t c0_exc:1;
+		uint64_t c1_up_wf:1;
+		uint64_t c0_up_wf:1;
+		uint64_t c1_un_wf:1;
+		uint64_t c0_un_wf:1;
+		uint64_t c1_un_bx:1;
+		uint64_t c1_un_wi:1;
+		uint64_t c1_un_b2:1;
+		uint64_t c1_un_b1:1;
+		uint64_t c1_un_b0:1;
+		uint64_t c1_up_bx:1;
+		uint64_t c1_up_wi:1;
+		uint64_t c1_up_b2:1;
+		uint64_t c1_up_b1:1;
+		uint64_t c1_up_b0:1;
+		uint64_t c0_un_bx:1;
+		uint64_t c0_un_wi:1;
+		uint64_t c0_un_b2:1;
+		uint64_t c0_un_b1:1;
+		uint64_t c0_un_b0:1;
+		uint64_t c0_up_bx:1;
+		uint64_t c0_up_wi:1;
+		uint64_t c0_up_b2:1;
+		uint64_t c0_up_b1:1;
+		uint64_t c0_up_b0:1;
+		uint64_t c1_hpint:1;
+		uint64_t c1_pmei:1;
+		uint64_t c1_wake:1;
+		uint64_t crs1_dr:1;
+		uint64_t c1_se:1;
+		uint64_t crs1_er:1;
+		uint64_t c1_aeri:1;
+		uint64_t c0_hpint:1;
+		uint64_t c0_pmei:1;
+		uint64_t c0_wake:1;
+		uint64_t crs0_dr:1;
+		uint64_t c0_se:1;
+		uint64_t crs0_er:1;
+		uint64_t c0_aeri:1;
+		uint64_t ptime:1;
+		uint64_t pcnt:1;
+		uint64_t pidbof:1;
+		uint64_t psldbof:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t dma1fi:1;
+		uint64_t dma0fi:1;
+		uint64_t reserved_8_8:1;
+		uint64_t dma3dbo:1;
+		uint64_t dma2dbo:1;
+		uint64_t dma1dbo:1;
+		uint64_t dma0dbo:1;
+		uint64_t iob2big:1;
+		uint64_t bar0_to:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn52xxp1;
+	struct cvmx_npei_int_enb2_s cn56xx;
+	struct cvmx_npei_int_enb2_cn56xxp1 {
+		uint64_t reserved_61_63:3;
+		uint64_t c1_ldwn:1;
+		uint64_t c0_ldwn:1;
+		uint64_t c1_exc:1;
+		uint64_t c0_exc:1;
+		uint64_t c1_up_wf:1;
+		uint64_t c0_up_wf:1;
+		uint64_t c1_un_wf:1;
+		uint64_t c0_un_wf:1;
+		uint64_t c1_un_bx:1;
+		uint64_t c1_un_wi:1;
+		uint64_t c1_un_b2:1;
+		uint64_t c1_un_b1:1;
+		uint64_t c1_un_b0:1;
+		uint64_t c1_up_bx:1;
+		uint64_t c1_up_wi:1;
+		uint64_t c1_up_b2:1;
+		uint64_t c1_up_b1:1;
+		uint64_t c1_up_b0:1;
+		uint64_t c0_un_bx:1;
+		uint64_t c0_un_wi:1;
+		uint64_t c0_un_b2:1;
+		uint64_t c0_un_b1:1;
+		uint64_t c0_un_b0:1;
+		uint64_t c0_up_bx:1;
+		uint64_t c0_up_wi:1;
+		uint64_t c0_up_b2:1;
+		uint64_t c0_up_b1:1;
+		uint64_t c0_up_b0:1;
+		uint64_t c1_hpint:1;
+		uint64_t c1_pmei:1;
+		uint64_t c1_wake:1;
+		uint64_t reserved_29_29:1;
+		uint64_t c1_se:1;
+		uint64_t reserved_27_27:1;
+		uint64_t c1_aeri:1;
+		uint64_t c0_hpint:1;
+		uint64_t c0_pmei:1;
+		uint64_t c0_wake:1;
+		uint64_t reserved_22_22:1;
+		uint64_t c0_se:1;
+		uint64_t reserved_20_20:1;
+		uint64_t c0_aeri:1;
+		uint64_t ptime:1;
+		uint64_t pcnt:1;
+		uint64_t pidbof:1;
+		uint64_t psldbof:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t dma1fi:1;
+		uint64_t dma0fi:1;
+		uint64_t dma4dbo:1;
+		uint64_t dma3dbo:1;
+		uint64_t dma2dbo:1;
+		uint64_t dma1dbo:1;
+		uint64_t dma0dbo:1;
+		uint64_t iob2big:1;
+		uint64_t bar0_to:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn56xxp1;
+};
+
+union cvmx_npei_int_info {
+	uint64_t u64;
+	struct cvmx_npei_int_info_s {
+		uint64_t reserved_12_63:52;
+		uint64_t pidbof:6;
+		uint64_t psldbof:6;
+	} s;
+	struct cvmx_npei_int_info_s cn52xx;
+	struct cvmx_npei_int_info_s cn56xx;
+	struct cvmx_npei_int_info_s cn56xxp1;
+};
+
+union cvmx_npei_int_sum {
+	uint64_t u64;
+	struct cvmx_npei_int_sum_s {
+		uint64_t mio_inta:1;
+		uint64_t reserved_62_62:1;
+		uint64_t int_a:1;
+		uint64_t c1_ldwn:1;
+		uint64_t c0_ldwn:1;
+		uint64_t c1_exc:1;
+		uint64_t c0_exc:1;
+		uint64_t c1_up_wf:1;
+		uint64_t c0_up_wf:1;
+		uint64_t c1_un_wf:1;
+		uint64_t c0_un_wf:1;
+		uint64_t c1_un_bx:1;
+		uint64_t c1_un_wi:1;
+		uint64_t c1_un_b2:1;
+		uint64_t c1_un_b1:1;
+		uint64_t c1_un_b0:1;
+		uint64_t c1_up_bx:1;
+		uint64_t c1_up_wi:1;
+		uint64_t c1_up_b2:1;
+		uint64_t c1_up_b1:1;
+		uint64_t c1_up_b0:1;
+		uint64_t c0_un_bx:1;
+		uint64_t c0_un_wi:1;
+		uint64_t c0_un_b2:1;
+		uint64_t c0_un_b1:1;
+		uint64_t c0_un_b0:1;
+		uint64_t c0_up_bx:1;
+		uint64_t c0_up_wi:1;
+		uint64_t c0_up_b2:1;
+		uint64_t c0_up_b1:1;
+		uint64_t c0_up_b0:1;
+		uint64_t c1_hpint:1;
+		uint64_t c1_pmei:1;
+		uint64_t c1_wake:1;
+		uint64_t crs1_dr:1;
+		uint64_t c1_se:1;
+		uint64_t crs1_er:1;
+		uint64_t c1_aeri:1;
+		uint64_t c0_hpint:1;
+		uint64_t c0_pmei:1;
+		uint64_t c0_wake:1;
+		uint64_t crs0_dr:1;
+		uint64_t c0_se:1;
+		uint64_t crs0_er:1;
+		uint64_t c0_aeri:1;
+		uint64_t ptime:1;
+		uint64_t pcnt:1;
+		uint64_t pidbof:1;
+		uint64_t psldbof:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t dma1fi:1;
+		uint64_t dma0fi:1;
+		uint64_t dma4dbo:1;
+		uint64_t dma3dbo:1;
+		uint64_t dma2dbo:1;
+		uint64_t dma1dbo:1;
+		uint64_t dma0dbo:1;
+		uint64_t iob2big:1;
+		uint64_t bar0_to:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} s;
+	struct cvmx_npei_int_sum_s cn52xx;
+	struct cvmx_npei_int_sum_cn52xxp1 {
+		uint64_t mio_inta:1;
+		uint64_t reserved_62_62:1;
+		uint64_t int_a:1;
+		uint64_t c1_ldwn:1;
+		uint64_t c0_ldwn:1;
+		uint64_t c1_exc:1;
+		uint64_t c0_exc:1;
+		uint64_t c1_up_wf:1;
+		uint64_t c0_up_wf:1;
+		uint64_t c1_un_wf:1;
+		uint64_t c0_un_wf:1;
+		uint64_t c1_un_bx:1;
+		uint64_t c1_un_wi:1;
+		uint64_t c1_un_b2:1;
+		uint64_t c1_un_b1:1;
+		uint64_t c1_un_b0:1;
+		uint64_t c1_up_bx:1;
+		uint64_t c1_up_wi:1;
+		uint64_t c1_up_b2:1;
+		uint64_t c1_up_b1:1;
+		uint64_t c1_up_b0:1;
+		uint64_t c0_un_bx:1;
+		uint64_t c0_un_wi:1;
+		uint64_t c0_un_b2:1;
+		uint64_t c0_un_b1:1;
+		uint64_t c0_un_b0:1;
+		uint64_t c0_up_bx:1;
+		uint64_t c0_up_wi:1;
+		uint64_t c0_up_b2:1;
+		uint64_t c0_up_b1:1;
+		uint64_t c0_up_b0:1;
+		uint64_t c1_hpint:1;
+		uint64_t c1_pmei:1;
+		uint64_t c1_wake:1;
+		uint64_t crs1_dr:1;
+		uint64_t c1_se:1;
+		uint64_t crs1_er:1;
+		uint64_t c1_aeri:1;
+		uint64_t c0_hpint:1;
+		uint64_t c0_pmei:1;
+		uint64_t c0_wake:1;
+		uint64_t crs0_dr:1;
+		uint64_t c0_se:1;
+		uint64_t crs0_er:1;
+		uint64_t c0_aeri:1;
+		uint64_t reserved_15_18:4;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t dma1fi:1;
+		uint64_t dma0fi:1;
+		uint64_t reserved_8_8:1;
+		uint64_t dma3dbo:1;
+		uint64_t dma2dbo:1;
+		uint64_t dma1dbo:1;
+		uint64_t dma0dbo:1;
+		uint64_t iob2big:1;
+		uint64_t bar0_to:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn52xxp1;
+	struct cvmx_npei_int_sum_s cn56xx;
+	struct cvmx_npei_int_sum_cn56xxp1 {
+		uint64_t mio_inta:1;
+		uint64_t reserved_61_62:2;
+		uint64_t c1_ldwn:1;
+		uint64_t c0_ldwn:1;
+		uint64_t c1_exc:1;
+		uint64_t c0_exc:1;
+		uint64_t c1_up_wf:1;
+		uint64_t c0_up_wf:1;
+		uint64_t c1_un_wf:1;
+		uint64_t c0_un_wf:1;
+		uint64_t c1_un_bx:1;
+		uint64_t c1_un_wi:1;
+		uint64_t c1_un_b2:1;
+		uint64_t c1_un_b1:1;
+		uint64_t c1_un_b0:1;
+		uint64_t c1_up_bx:1;
+		uint64_t c1_up_wi:1;
+		uint64_t c1_up_b2:1;
+		uint64_t c1_up_b1:1;
+		uint64_t c1_up_b0:1;
+		uint64_t c0_un_bx:1;
+		uint64_t c0_un_wi:1;
+		uint64_t c0_un_b2:1;
+		uint64_t c0_un_b1:1;
+		uint64_t c0_un_b0:1;
+		uint64_t c0_up_bx:1;
+		uint64_t c0_up_wi:1;
+		uint64_t c0_up_b2:1;
+		uint64_t c0_up_b1:1;
+		uint64_t c0_up_b0:1;
+		uint64_t c1_hpint:1;
+		uint64_t c1_pmei:1;
+		uint64_t c1_wake:1;
+		uint64_t reserved_29_29:1;
+		uint64_t c1_se:1;
+		uint64_t reserved_27_27:1;
+		uint64_t c1_aeri:1;
+		uint64_t c0_hpint:1;
+		uint64_t c0_pmei:1;
+		uint64_t c0_wake:1;
+		uint64_t reserved_22_22:1;
+		uint64_t c0_se:1;
+		uint64_t reserved_20_20:1;
+		uint64_t c0_aeri:1;
+		uint64_t ptime:1;
+		uint64_t pcnt:1;
+		uint64_t pidbof:1;
+		uint64_t psldbof:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t dma1fi:1;
+		uint64_t dma0fi:1;
+		uint64_t dma4dbo:1;
+		uint64_t dma3dbo:1;
+		uint64_t dma2dbo:1;
+		uint64_t dma1dbo:1;
+		uint64_t dma0dbo:1;
+		uint64_t iob2big:1;
+		uint64_t bar0_to:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn56xxp1;
+};
+
+union cvmx_npei_int_sum2 {
+	uint64_t u64;
+	struct cvmx_npei_int_sum2_s {
+		uint64_t mio_inta:1;
+		uint64_t reserved_62_62:1;
+		uint64_t int_a:1;
+		uint64_t c1_ldwn:1;
+		uint64_t c0_ldwn:1;
+		uint64_t c1_exc:1;
+		uint64_t c0_exc:1;
+		uint64_t c1_up_wf:1;
+		uint64_t c0_up_wf:1;
+		uint64_t c1_un_wf:1;
+		uint64_t c0_un_wf:1;
+		uint64_t c1_un_bx:1;
+		uint64_t c1_un_wi:1;
+		uint64_t c1_un_b2:1;
+		uint64_t c1_un_b1:1;
+		uint64_t c1_un_b0:1;
+		uint64_t c1_up_bx:1;
+		uint64_t c1_up_wi:1;
+		uint64_t c1_up_b2:1;
+		uint64_t c1_up_b1:1;
+		uint64_t c1_up_b0:1;
+		uint64_t c0_un_bx:1;
+		uint64_t c0_un_wi:1;
+		uint64_t c0_un_b2:1;
+		uint64_t c0_un_b1:1;
+		uint64_t c0_un_b0:1;
+		uint64_t c0_up_bx:1;
+		uint64_t c0_up_wi:1;
+		uint64_t c0_up_b2:1;
+		uint64_t c0_up_b1:1;
+		uint64_t c0_up_b0:1;
+		uint64_t c1_hpint:1;
+		uint64_t c1_pmei:1;
+		uint64_t c1_wake:1;
+		uint64_t crs1_dr:1;
+		uint64_t c1_se:1;
+		uint64_t crs1_er:1;
+		uint64_t c1_aeri:1;
+		uint64_t c0_hpint:1;
+		uint64_t c0_pmei:1;
+		uint64_t c0_wake:1;
+		uint64_t crs0_dr:1;
+		uint64_t c0_se:1;
+		uint64_t crs0_er:1;
+		uint64_t c0_aeri:1;
+		uint64_t reserved_15_18:4;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t dma1fi:1;
+		uint64_t dma0fi:1;
+		uint64_t reserved_8_8:1;
+		uint64_t dma3dbo:1;
+		uint64_t dma2dbo:1;
+		uint64_t dma1dbo:1;
+		uint64_t dma0dbo:1;
+		uint64_t iob2big:1;
+		uint64_t bar0_to:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} s;
+	struct cvmx_npei_int_sum2_s cn52xx;
+	struct cvmx_npei_int_sum2_s cn52xxp1;
+	struct cvmx_npei_int_sum2_s cn56xx;
+};
+
+union cvmx_npei_last_win_rdata0 {
+	uint64_t u64;
+	struct cvmx_npei_last_win_rdata0_s {
+		uint64_t data:64;
+	} s;
+	struct cvmx_npei_last_win_rdata0_s cn52xx;
+	struct cvmx_npei_last_win_rdata0_s cn52xxp1;
+	struct cvmx_npei_last_win_rdata0_s cn56xx;
+	struct cvmx_npei_last_win_rdata0_s cn56xxp1;
+};
+
+union cvmx_npei_last_win_rdata1 {
+	uint64_t u64;
+	struct cvmx_npei_last_win_rdata1_s {
+		uint64_t data:64;
+	} s;
+	struct cvmx_npei_last_win_rdata1_s cn52xx;
+	struct cvmx_npei_last_win_rdata1_s cn52xxp1;
+	struct cvmx_npei_last_win_rdata1_s cn56xx;
+	struct cvmx_npei_last_win_rdata1_s cn56xxp1;
+};
+
+union cvmx_npei_mem_access_ctl {
+	uint64_t u64;
+	struct cvmx_npei_mem_access_ctl_s {
+		uint64_t reserved_14_63:50;
+		uint64_t max_word:4;
+		uint64_t timer:10;
+	} s;
+	struct cvmx_npei_mem_access_ctl_s cn52xx;
+	struct cvmx_npei_mem_access_ctl_s cn52xxp1;
+	struct cvmx_npei_mem_access_ctl_s cn56xx;
+	struct cvmx_npei_mem_access_ctl_s cn56xxp1;
+};
+
+union cvmx_npei_mem_access_subidx {
+	uint64_t u64;
+	struct cvmx_npei_mem_access_subidx_s {
+		uint64_t reserved_42_63:22;
+		uint64_t zero:1;
+		uint64_t port:2;
+		uint64_t nmerge:1;
+		uint64_t esr:2;
+		uint64_t esw:2;
+		uint64_t nsr:1;
+		uint64_t nsw:1;
+		uint64_t ror:1;
+		uint64_t row:1;
+		uint64_t ba:30;
+	} s;
+	struct cvmx_npei_mem_access_subidx_s cn52xx;
+	struct cvmx_npei_mem_access_subidx_s cn52xxp1;
+	struct cvmx_npei_mem_access_subidx_s cn56xx;
+	struct cvmx_npei_mem_access_subidx_s cn56xxp1;
+};
+
+union cvmx_npei_msi_enb0 {
+	uint64_t u64;
+	struct cvmx_npei_msi_enb0_s {
+		uint64_t enb:64;
+	} s;
+	struct cvmx_npei_msi_enb0_s cn52xx;
+	struct cvmx_npei_msi_enb0_s cn52xxp1;
+	struct cvmx_npei_msi_enb0_s cn56xx;
+	struct cvmx_npei_msi_enb0_s cn56xxp1;
+};
+
+union cvmx_npei_msi_enb1 {
+	uint64_t u64;
+	struct cvmx_npei_msi_enb1_s {
+		uint64_t enb:64;
+	} s;
+	struct cvmx_npei_msi_enb1_s cn52xx;
+	struct cvmx_npei_msi_enb1_s cn52xxp1;
+	struct cvmx_npei_msi_enb1_s cn56xx;
+	struct cvmx_npei_msi_enb1_s cn56xxp1;
+};
+
+union cvmx_npei_msi_enb2 {
+	uint64_t u64;
+	struct cvmx_npei_msi_enb2_s {
+		uint64_t enb:64;
+	} s;
+	struct cvmx_npei_msi_enb2_s cn52xx;
+	struct cvmx_npei_msi_enb2_s cn52xxp1;
+	struct cvmx_npei_msi_enb2_s cn56xx;
+	struct cvmx_npei_msi_enb2_s cn56xxp1;
+};
+
+union cvmx_npei_msi_enb3 {
+	uint64_t u64;
+	struct cvmx_npei_msi_enb3_s {
+		uint64_t enb:64;
+	} s;
+	struct cvmx_npei_msi_enb3_s cn52xx;
+	struct cvmx_npei_msi_enb3_s cn52xxp1;
+	struct cvmx_npei_msi_enb3_s cn56xx;
+	struct cvmx_npei_msi_enb3_s cn56xxp1;
+};
+
+union cvmx_npei_msi_rcv0 {
+	uint64_t u64;
+	struct cvmx_npei_msi_rcv0_s {
+		uint64_t intr:64;
+	} s;
+	struct cvmx_npei_msi_rcv0_s cn52xx;
+	struct cvmx_npei_msi_rcv0_s cn52xxp1;
+	struct cvmx_npei_msi_rcv0_s cn56xx;
+	struct cvmx_npei_msi_rcv0_s cn56xxp1;
+};
+
+union cvmx_npei_msi_rcv1 {
+	uint64_t u64;
+	struct cvmx_npei_msi_rcv1_s {
+		uint64_t intr:64;
+	} s;
+	struct cvmx_npei_msi_rcv1_s cn52xx;
+	struct cvmx_npei_msi_rcv1_s cn52xxp1;
+	struct cvmx_npei_msi_rcv1_s cn56xx;
+	struct cvmx_npei_msi_rcv1_s cn56xxp1;
+};
+
+union cvmx_npei_msi_rcv2 {
+	uint64_t u64;
+	struct cvmx_npei_msi_rcv2_s {
+		uint64_t intr:64;
+	} s;
+	struct cvmx_npei_msi_rcv2_s cn52xx;
+	struct cvmx_npei_msi_rcv2_s cn52xxp1;
+	struct cvmx_npei_msi_rcv2_s cn56xx;
+	struct cvmx_npei_msi_rcv2_s cn56xxp1;
+};
+
+union cvmx_npei_msi_rcv3 {
+	uint64_t u64;
+	struct cvmx_npei_msi_rcv3_s {
+		uint64_t intr:64;
+	} s;
+	struct cvmx_npei_msi_rcv3_s cn52xx;
+	struct cvmx_npei_msi_rcv3_s cn52xxp1;
+	struct cvmx_npei_msi_rcv3_s cn56xx;
+	struct cvmx_npei_msi_rcv3_s cn56xxp1;
+};
+
+union cvmx_npei_msi_rd_map {
+	uint64_t u64;
+	struct cvmx_npei_msi_rd_map_s {
+		uint64_t reserved_16_63:48;
+		uint64_t rd_int:8;
+		uint64_t msi_int:8;
+	} s;
+	struct cvmx_npei_msi_rd_map_s cn52xx;
+	struct cvmx_npei_msi_rd_map_s cn52xxp1;
+	struct cvmx_npei_msi_rd_map_s cn56xx;
+	struct cvmx_npei_msi_rd_map_s cn56xxp1;
+};
+
+union cvmx_npei_msi_w1c_enb0 {
+	uint64_t u64;
+	struct cvmx_npei_msi_w1c_enb0_s {
+		uint64_t clr:64;
+	} s;
+	struct cvmx_npei_msi_w1c_enb0_s cn52xx;
+	struct cvmx_npei_msi_w1c_enb0_s cn56xx;
+};
+
+union cvmx_npei_msi_w1c_enb1 {
+	uint64_t u64;
+	struct cvmx_npei_msi_w1c_enb1_s {
+		uint64_t clr:64;
+	} s;
+	struct cvmx_npei_msi_w1c_enb1_s cn52xx;
+	struct cvmx_npei_msi_w1c_enb1_s cn56xx;
+};
+
+union cvmx_npei_msi_w1c_enb2 {
+	uint64_t u64;
+	struct cvmx_npei_msi_w1c_enb2_s {
+		uint64_t clr:64;
+	} s;
+	struct cvmx_npei_msi_w1c_enb2_s cn52xx;
+	struct cvmx_npei_msi_w1c_enb2_s cn56xx;
+};
+
+union cvmx_npei_msi_w1c_enb3 {
+	uint64_t u64;
+	struct cvmx_npei_msi_w1c_enb3_s {
+		uint64_t clr:64;
+	} s;
+	struct cvmx_npei_msi_w1c_enb3_s cn52xx;
+	struct cvmx_npei_msi_w1c_enb3_s cn56xx;
+};
+
+union cvmx_npei_msi_w1s_enb0 {
+	uint64_t u64;
+	struct cvmx_npei_msi_w1s_enb0_s {
+		uint64_t set:64;
+	} s;
+	struct cvmx_npei_msi_w1s_enb0_s cn52xx;
+	struct cvmx_npei_msi_w1s_enb0_s cn56xx;
+};
+
+union cvmx_npei_msi_w1s_enb1 {
+	uint64_t u64;
+	struct cvmx_npei_msi_w1s_enb1_s {
+		uint64_t set:64;
+	} s;
+	struct cvmx_npei_msi_w1s_enb1_s cn52xx;
+	struct cvmx_npei_msi_w1s_enb1_s cn56xx;
+};
+
+union cvmx_npei_msi_w1s_enb2 {
+	uint64_t u64;
+	struct cvmx_npei_msi_w1s_enb2_s {
+		uint64_t set:64;
+	} s;
+	struct cvmx_npei_msi_w1s_enb2_s cn52xx;
+	struct cvmx_npei_msi_w1s_enb2_s cn56xx;
+};
+
+union cvmx_npei_msi_w1s_enb3 {
+	uint64_t u64;
+	struct cvmx_npei_msi_w1s_enb3_s {
+		uint64_t set:64;
+	} s;
+	struct cvmx_npei_msi_w1s_enb3_s cn52xx;
+	struct cvmx_npei_msi_w1s_enb3_s cn56xx;
+};
+
+union cvmx_npei_msi_wr_map {
+	uint64_t u64;
+	struct cvmx_npei_msi_wr_map_s {
+		uint64_t reserved_16_63:48;
+		uint64_t ciu_int:8;
+		uint64_t msi_int:8;
+	} s;
+	struct cvmx_npei_msi_wr_map_s cn52xx;
+	struct cvmx_npei_msi_wr_map_s cn52xxp1;
+	struct cvmx_npei_msi_wr_map_s cn56xx;
+	struct cvmx_npei_msi_wr_map_s cn56xxp1;
+};
+
+union cvmx_npei_pcie_credit_cnt {
+	uint64_t u64;
+	struct cvmx_npei_pcie_credit_cnt_s {
+		uint64_t reserved_48_63:16;
+		uint64_t p1_ccnt:8;
+		uint64_t p1_ncnt:8;
+		uint64_t p1_pcnt:8;
+		uint64_t p0_ccnt:8;
+		uint64_t p0_ncnt:8;
+		uint64_t p0_pcnt:8;
+	} s;
+	struct cvmx_npei_pcie_credit_cnt_s cn52xx;
+	struct cvmx_npei_pcie_credit_cnt_s cn56xx;
+};
+
+union cvmx_npei_pcie_msi_rcv {
+	uint64_t u64;
+	struct cvmx_npei_pcie_msi_rcv_s {
+		uint64_t reserved_8_63:56;
+		uint64_t intr:8;
+	} s;
+	struct cvmx_npei_pcie_msi_rcv_s cn52xx;
+	struct cvmx_npei_pcie_msi_rcv_s cn52xxp1;
+	struct cvmx_npei_pcie_msi_rcv_s cn56xx;
+	struct cvmx_npei_pcie_msi_rcv_s cn56xxp1;
+};
+
+union cvmx_npei_pcie_msi_rcv_b1 {
+	uint64_t u64;
+	struct cvmx_npei_pcie_msi_rcv_b1_s {
+		uint64_t reserved_16_63:48;
+		uint64_t intr:8;
+		uint64_t reserved_0_7:8;
+	} s;
+	struct cvmx_npei_pcie_msi_rcv_b1_s cn52xx;
+	struct cvmx_npei_pcie_msi_rcv_b1_s cn52xxp1;
+	struct cvmx_npei_pcie_msi_rcv_b1_s cn56xx;
+	struct cvmx_npei_pcie_msi_rcv_b1_s cn56xxp1;
+};
+
+union cvmx_npei_pcie_msi_rcv_b2 {
+	uint64_t u64;
+	struct cvmx_npei_pcie_msi_rcv_b2_s {
+		uint64_t reserved_24_63:40;
+		uint64_t intr:8;
+		uint64_t reserved_0_15:16;
+	} s;
+	struct cvmx_npei_pcie_msi_rcv_b2_s cn52xx;
+	struct cvmx_npei_pcie_msi_rcv_b2_s cn52xxp1;
+	struct cvmx_npei_pcie_msi_rcv_b2_s cn56xx;
+	struct cvmx_npei_pcie_msi_rcv_b2_s cn56xxp1;
+};
+
+union cvmx_npei_pcie_msi_rcv_b3 {
+	uint64_t u64;
+	struct cvmx_npei_pcie_msi_rcv_b3_s {
+		uint64_t reserved_32_63:32;
+		uint64_t intr:8;
+		uint64_t reserved_0_23:24;
+	} s;
+	struct cvmx_npei_pcie_msi_rcv_b3_s cn52xx;
+	struct cvmx_npei_pcie_msi_rcv_b3_s cn52xxp1;
+	struct cvmx_npei_pcie_msi_rcv_b3_s cn56xx;
+	struct cvmx_npei_pcie_msi_rcv_b3_s cn56xxp1;
+};
+
+union cvmx_npei_pktx_cnts {
+	uint64_t u64;
+	struct cvmx_npei_pktx_cnts_s {
+		uint64_t reserved_54_63:10;
+		uint64_t timer:22;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_npei_pktx_cnts_s cn52xx;
+	struct cvmx_npei_pktx_cnts_s cn56xx;
+	struct cvmx_npei_pktx_cnts_s cn56xxp1;
+};
+
+union cvmx_npei_pktx_in_bp {
+	uint64_t u64;
+	struct cvmx_npei_pktx_in_bp_s {
+		uint64_t wmark:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_npei_pktx_in_bp_s cn52xx;
+	struct cvmx_npei_pktx_in_bp_s cn56xx;
+	struct cvmx_npei_pktx_in_bp_s cn56xxp1;
+};
+
+union cvmx_npei_pktx_instr_baddr {
+	uint64_t u64;
+	struct cvmx_npei_pktx_instr_baddr_s {
+		uint64_t addr:61;
+		uint64_t reserved_0_2:3;
+	} s;
+	struct cvmx_npei_pktx_instr_baddr_s cn52xx;
+	struct cvmx_npei_pktx_instr_baddr_s cn56xx;
+	struct cvmx_npei_pktx_instr_baddr_s cn56xxp1;
+};
+
+union cvmx_npei_pktx_instr_baoff_dbell {
+	uint64_t u64;
+	struct cvmx_npei_pktx_instr_baoff_dbell_s {
+		uint64_t aoff:32;
+		uint64_t dbell:32;
+	} s;
+	struct cvmx_npei_pktx_instr_baoff_dbell_s cn52xx;
+	struct cvmx_npei_pktx_instr_baoff_dbell_s cn56xx;
+	struct cvmx_npei_pktx_instr_baoff_dbell_s cn56xxp1;
+};
+
+union cvmx_npei_pktx_instr_fifo_rsize {
+	uint64_t u64;
+	struct cvmx_npei_pktx_instr_fifo_rsize_s {
+		uint64_t max:9;
+		uint64_t rrp:9;
+		uint64_t wrp:9;
+		uint64_t fcnt:5;
+		uint64_t rsize:32;
+	} s;
+	struct cvmx_npei_pktx_instr_fifo_rsize_s cn52xx;
+	struct cvmx_npei_pktx_instr_fifo_rsize_s cn56xx;
+	struct cvmx_npei_pktx_instr_fifo_rsize_s cn56xxp1;
+};
+
+union cvmx_npei_pktx_instr_header {
+	uint64_t u64;
+	struct cvmx_npei_pktx_instr_header_s {
+		uint64_t reserved_44_63:20;
+		uint64_t pbp:1;
+		uint64_t rsv_f:5;
+		uint64_t rparmode:2;
+		uint64_t rsv_e:1;
+		uint64_t rskp_len:7;
+		uint64_t rsv_d:6;
+		uint64_t use_ihdr:1;
+		uint64_t rsv_c:5;
+		uint64_t par_mode:2;
+		uint64_t rsv_b:1;
+		uint64_t skp_len:7;
+		uint64_t rsv_a:6;
+	} s;
+	struct cvmx_npei_pktx_instr_header_s cn52xx;
+	struct cvmx_npei_pktx_instr_header_s cn56xx;
+	struct cvmx_npei_pktx_instr_header_s cn56xxp1;
+};
+
+union cvmx_npei_pktx_slist_baddr {
+	uint64_t u64;
+	struct cvmx_npei_pktx_slist_baddr_s {
+		uint64_t addr:60;
+		uint64_t reserved_0_3:4;
+	} s;
+	struct cvmx_npei_pktx_slist_baddr_s cn52xx;
+	struct cvmx_npei_pktx_slist_baddr_s cn56xx;
+	struct cvmx_npei_pktx_slist_baddr_s cn56xxp1;
+};
+
+union cvmx_npei_pktx_slist_baoff_dbell {
+	uint64_t u64;
+	struct cvmx_npei_pktx_slist_baoff_dbell_s {
+		uint64_t aoff:32;
+		uint64_t dbell:32;
+	} s;
+	struct cvmx_npei_pktx_slist_baoff_dbell_s cn52xx;
+	struct cvmx_npei_pktx_slist_baoff_dbell_s cn56xx;
+	struct cvmx_npei_pktx_slist_baoff_dbell_s cn56xxp1;
+};
+
+union cvmx_npei_pktx_slist_fifo_rsize {
+	uint64_t u64;
+	struct cvmx_npei_pktx_slist_fifo_rsize_s {
+		uint64_t reserved_32_63:32;
+		uint64_t rsize:32;
+	} s;
+	struct cvmx_npei_pktx_slist_fifo_rsize_s cn52xx;
+	struct cvmx_npei_pktx_slist_fifo_rsize_s cn56xx;
+	struct cvmx_npei_pktx_slist_fifo_rsize_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_cnt_int {
+	uint64_t u64;
+	struct cvmx_npei_pkt_cnt_int_s {
+		uint64_t reserved_32_63:32;
+		uint64_t port:32;
+	} s;
+	struct cvmx_npei_pkt_cnt_int_s cn52xx;
+	struct cvmx_npei_pkt_cnt_int_s cn56xx;
+	struct cvmx_npei_pkt_cnt_int_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_cnt_int_enb {
+	uint64_t u64;
+	struct cvmx_npei_pkt_cnt_int_enb_s {
+		uint64_t reserved_32_63:32;
+		uint64_t port:32;
+	} s;
+	struct cvmx_npei_pkt_cnt_int_enb_s cn52xx;
+	struct cvmx_npei_pkt_cnt_int_enb_s cn56xx;
+	struct cvmx_npei_pkt_cnt_int_enb_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_data_out_es {
+	uint64_t u64;
+	struct cvmx_npei_pkt_data_out_es_s {
+		uint64_t es:64;
+	} s;
+	struct cvmx_npei_pkt_data_out_es_s cn52xx;
+	struct cvmx_npei_pkt_data_out_es_s cn56xx;
+	struct cvmx_npei_pkt_data_out_es_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_data_out_ns {
+	uint64_t u64;
+	struct cvmx_npei_pkt_data_out_ns_s {
+		uint64_t reserved_32_63:32;
+		uint64_t nsr:32;
+	} s;
+	struct cvmx_npei_pkt_data_out_ns_s cn52xx;
+	struct cvmx_npei_pkt_data_out_ns_s cn56xx;
+	struct cvmx_npei_pkt_data_out_ns_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_data_out_ror {
+	uint64_t u64;
+	struct cvmx_npei_pkt_data_out_ror_s {
+		uint64_t reserved_32_63:32;
+		uint64_t ror:32;
+	} s;
+	struct cvmx_npei_pkt_data_out_ror_s cn52xx;
+	struct cvmx_npei_pkt_data_out_ror_s cn56xx;
+	struct cvmx_npei_pkt_data_out_ror_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_dpaddr {
+	uint64_t u64;
+	struct cvmx_npei_pkt_dpaddr_s {
+		uint64_t reserved_32_63:32;
+		uint64_t dptr:32;
+	} s;
+	struct cvmx_npei_pkt_dpaddr_s cn52xx;
+	struct cvmx_npei_pkt_dpaddr_s cn56xx;
+	struct cvmx_npei_pkt_dpaddr_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_in_bp {
+	uint64_t u64;
+	struct cvmx_npei_pkt_in_bp_s {
+		uint64_t reserved_32_63:32;
+		uint64_t bp:32;
+	} s;
+	struct cvmx_npei_pkt_in_bp_s cn56xx;
+};
+
+union cvmx_npei_pkt_in_donex_cnts {
+	uint64_t u64;
+	struct cvmx_npei_pkt_in_donex_cnts_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_npei_pkt_in_donex_cnts_s cn52xx;
+	struct cvmx_npei_pkt_in_donex_cnts_s cn56xx;
+	struct cvmx_npei_pkt_in_donex_cnts_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_in_instr_counts {
+	uint64_t u64;
+	struct cvmx_npei_pkt_in_instr_counts_s {
+		uint64_t wr_cnt:32;
+		uint64_t rd_cnt:32;
+	} s;
+	struct cvmx_npei_pkt_in_instr_counts_s cn52xx;
+	struct cvmx_npei_pkt_in_instr_counts_s cn56xx;
+};
+
+union cvmx_npei_pkt_in_pcie_port {
+	uint64_t u64;
+	struct cvmx_npei_pkt_in_pcie_port_s {
+		uint64_t pp:64;
+	} s;
+	struct cvmx_npei_pkt_in_pcie_port_s cn52xx;
+	struct cvmx_npei_pkt_in_pcie_port_s cn56xx;
+};
+
+union cvmx_npei_pkt_input_control {
+	uint64_t u64;
+	struct cvmx_npei_pkt_input_control_s {
+		uint64_t reserved_23_63:41;
+		uint64_t pkt_rr:1;
+		uint64_t pbp_dhi:13;
+		uint64_t d_nsr:1;
+		uint64_t d_esr:2;
+		uint64_t d_ror:1;
+		uint64_t use_csr:1;
+		uint64_t nsr:1;
+		uint64_t esr:2;
+		uint64_t ror:1;
+	} s;
+	struct cvmx_npei_pkt_input_control_s cn52xx;
+	struct cvmx_npei_pkt_input_control_s cn56xx;
+	struct cvmx_npei_pkt_input_control_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_instr_enb {
+	uint64_t u64;
+	struct cvmx_npei_pkt_instr_enb_s {
+		uint64_t reserved_32_63:32;
+		uint64_t enb:32;
+	} s;
+	struct cvmx_npei_pkt_instr_enb_s cn52xx;
+	struct cvmx_npei_pkt_instr_enb_s cn56xx;
+	struct cvmx_npei_pkt_instr_enb_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_instr_rd_size {
+	uint64_t u64;
+	struct cvmx_npei_pkt_instr_rd_size_s {
+		uint64_t rdsize:64;
+	} s;
+	struct cvmx_npei_pkt_instr_rd_size_s cn52xx;
+	struct cvmx_npei_pkt_instr_rd_size_s cn56xx;
+};
+
+union cvmx_npei_pkt_instr_size {
+	uint64_t u64;
+	struct cvmx_npei_pkt_instr_size_s {
+		uint64_t reserved_32_63:32;
+		uint64_t is_64b:32;
+	} s;
+	struct cvmx_npei_pkt_instr_size_s cn52xx;
+	struct cvmx_npei_pkt_instr_size_s cn56xx;
+	struct cvmx_npei_pkt_instr_size_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_int_levels {
+	uint64_t u64;
+	struct cvmx_npei_pkt_int_levels_s {
+		uint64_t reserved_54_63:10;
+		uint64_t time:22;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_npei_pkt_int_levels_s cn52xx;
+	struct cvmx_npei_pkt_int_levels_s cn56xx;
+	struct cvmx_npei_pkt_int_levels_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_iptr {
+	uint64_t u64;
+	struct cvmx_npei_pkt_iptr_s {
+		uint64_t reserved_32_63:32;
+		uint64_t iptr:32;
+	} s;
+	struct cvmx_npei_pkt_iptr_s cn52xx;
+	struct cvmx_npei_pkt_iptr_s cn56xx;
+	struct cvmx_npei_pkt_iptr_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_out_bmode {
+	uint64_t u64;
+	struct cvmx_npei_pkt_out_bmode_s {
+		uint64_t reserved_32_63:32;
+		uint64_t bmode:32;
+	} s;
+	struct cvmx_npei_pkt_out_bmode_s cn52xx;
+	struct cvmx_npei_pkt_out_bmode_s cn56xx;
+	struct cvmx_npei_pkt_out_bmode_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_out_enb {
+	uint64_t u64;
+	struct cvmx_npei_pkt_out_enb_s {
+		uint64_t reserved_32_63:32;
+		uint64_t enb:32;
+	} s;
+	struct cvmx_npei_pkt_out_enb_s cn52xx;
+	struct cvmx_npei_pkt_out_enb_s cn56xx;
+	struct cvmx_npei_pkt_out_enb_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_output_wmark {
+	uint64_t u64;
+	struct cvmx_npei_pkt_output_wmark_s {
+		uint64_t reserved_32_63:32;
+		uint64_t wmark:32;
+	} s;
+	struct cvmx_npei_pkt_output_wmark_s cn52xx;
+	struct cvmx_npei_pkt_output_wmark_s cn56xx;
+};
+
+union cvmx_npei_pkt_pcie_port {
+	uint64_t u64;
+	struct cvmx_npei_pkt_pcie_port_s {
+		uint64_t pp:64;
+	} s;
+	struct cvmx_npei_pkt_pcie_port_s cn52xx;
+	struct cvmx_npei_pkt_pcie_port_s cn56xx;
+	struct cvmx_npei_pkt_pcie_port_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_port_in_rst {
+	uint64_t u64;
+	struct cvmx_npei_pkt_port_in_rst_s {
+		uint64_t in_rst:32;
+		uint64_t out_rst:32;
+	} s;
+	struct cvmx_npei_pkt_port_in_rst_s cn52xx;
+	struct cvmx_npei_pkt_port_in_rst_s cn56xx;
+};
+
+union cvmx_npei_pkt_slist_es {
+	uint64_t u64;
+	struct cvmx_npei_pkt_slist_es_s {
+		uint64_t es:64;
+	} s;
+	struct cvmx_npei_pkt_slist_es_s cn52xx;
+	struct cvmx_npei_pkt_slist_es_s cn56xx;
+	struct cvmx_npei_pkt_slist_es_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_slist_id_size {
+	uint64_t u64;
+	struct cvmx_npei_pkt_slist_id_size_s {
+		uint64_t reserved_23_63:41;
+		uint64_t isize:7;
+		uint64_t bsize:16;
+	} s;
+	struct cvmx_npei_pkt_slist_id_size_s cn52xx;
+	struct cvmx_npei_pkt_slist_id_size_s cn56xx;
+	struct cvmx_npei_pkt_slist_id_size_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_slist_ns {
+	uint64_t u64;
+	struct cvmx_npei_pkt_slist_ns_s {
+		uint64_t reserved_32_63:32;
+		uint64_t nsr:32;
+	} s;
+	struct cvmx_npei_pkt_slist_ns_s cn52xx;
+	struct cvmx_npei_pkt_slist_ns_s cn56xx;
+	struct cvmx_npei_pkt_slist_ns_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_slist_ror {
+	uint64_t u64;
+	struct cvmx_npei_pkt_slist_ror_s {
+		uint64_t reserved_32_63:32;
+		uint64_t ror:32;
+	} s;
+	struct cvmx_npei_pkt_slist_ror_s cn52xx;
+	struct cvmx_npei_pkt_slist_ror_s cn56xx;
+	struct cvmx_npei_pkt_slist_ror_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_time_int {
+	uint64_t u64;
+	struct cvmx_npei_pkt_time_int_s {
+		uint64_t reserved_32_63:32;
+		uint64_t port:32;
+	} s;
+	struct cvmx_npei_pkt_time_int_s cn52xx;
+	struct cvmx_npei_pkt_time_int_s cn56xx;
+	struct cvmx_npei_pkt_time_int_s cn56xxp1;
+};
+
+union cvmx_npei_pkt_time_int_enb {
+	uint64_t u64;
+	struct cvmx_npei_pkt_time_int_enb_s {
+		uint64_t reserved_32_63:32;
+		uint64_t port:32;
+	} s;
+	struct cvmx_npei_pkt_time_int_enb_s cn52xx;
+	struct cvmx_npei_pkt_time_int_enb_s cn56xx;
+	struct cvmx_npei_pkt_time_int_enb_s cn56xxp1;
+};
+
+union cvmx_npei_rsl_int_blocks {
+	uint64_t u64;
+	struct cvmx_npei_rsl_int_blocks_s {
+		uint64_t reserved_31_63:33;
+		uint64_t iob:1;
+		uint64_t lmc1:1;
+		uint64_t agl:1;
+		uint64_t reserved_24_27:4;
+		uint64_t asxpcs1:1;
+		uint64_t asxpcs0:1;
+		uint64_t reserved_21_21:1;
+		uint64_t pip:1;
+		uint64_t reserved_18_19:2;
+		uint64_t lmc0:1;
+		uint64_t l2c:1;
+		uint64_t usb1:1;
+		uint64_t rad:1;
+		uint64_t usb:1;
+		uint64_t pow:1;
+		uint64_t tim:1;
+		uint64_t pko:1;
+		uint64_t ipd:1;
+		uint64_t reserved_8_8:1;
+		uint64_t zip:1;
+		uint64_t reserved_6_6:1;
+		uint64_t fpa:1;
+		uint64_t key:1;
+		uint64_t npei:1;
+		uint64_t gmx1:1;
+		uint64_t gmx0:1;
+		uint64_t mio:1;
+	} s;
+	struct cvmx_npei_rsl_int_blocks_s cn52xx;
+	struct cvmx_npei_rsl_int_blocks_s cn52xxp1;
+	struct cvmx_npei_rsl_int_blocks_cn56xx {
+		uint64_t reserved_31_63:33;
+		uint64_t iob:1;
+		uint64_t lmc1:1;
+		uint64_t agl:1;
+		uint64_t reserved_24_27:4;
+		uint64_t asxpcs1:1;
+		uint64_t asxpcs0:1;
+		uint64_t reserved_21_21:1;
+		uint64_t pip:1;
+		uint64_t reserved_18_19:2;
+		uint64_t lmc0:1;
+		uint64_t l2c:1;
+		uint64_t reserved_15_15:1;
+		uint64_t rad:1;
+		uint64_t usb:1;
+		uint64_t pow:1;
+		uint64_t tim:1;
+		uint64_t pko:1;
+		uint64_t ipd:1;
+		uint64_t reserved_8_8:1;
+		uint64_t zip:1;
+		uint64_t reserved_6_6:1;
+		uint64_t fpa:1;
+		uint64_t key:1;
+		uint64_t npei:1;
+		uint64_t gmx1:1;
+		uint64_t gmx0:1;
+		uint64_t mio:1;
+	} cn56xx;
+	struct cvmx_npei_rsl_int_blocks_cn56xx cn56xxp1;
+};
+
+union cvmx_npei_scratch_1 {
+	uint64_t u64;
+	struct cvmx_npei_scratch_1_s {
+		uint64_t data:64;
+	} s;
+	struct cvmx_npei_scratch_1_s cn52xx;
+	struct cvmx_npei_scratch_1_s cn52xxp1;
+	struct cvmx_npei_scratch_1_s cn56xx;
+	struct cvmx_npei_scratch_1_s cn56xxp1;
+};
+
+union cvmx_npei_state1 {
+	uint64_t u64;
+	struct cvmx_npei_state1_s {
+		uint64_t cpl1:12;
+		uint64_t cpl0:12;
+		uint64_t arb:1;
+		uint64_t csr:39;
+	} s;
+	struct cvmx_npei_state1_s cn52xx;
+	struct cvmx_npei_state1_s cn52xxp1;
+	struct cvmx_npei_state1_s cn56xx;
+	struct cvmx_npei_state1_s cn56xxp1;
+};
+
+union cvmx_npei_state2 {
+	uint64_t u64;
+	struct cvmx_npei_state2_s {
+		uint64_t reserved_48_63:16;
+		uint64_t npei:1;
+		uint64_t rac:1;
+		uint64_t csm1:15;
+		uint64_t csm0:15;
+		uint64_t nnp0:8;
+		uint64_t nnd:8;
+	} s;
+	struct cvmx_npei_state2_s cn52xx;
+	struct cvmx_npei_state2_s cn52xxp1;
+	struct cvmx_npei_state2_s cn56xx;
+	struct cvmx_npei_state2_s cn56xxp1;
+};
+
+union cvmx_npei_state3 {
+	uint64_t u64;
+	struct cvmx_npei_state3_s {
+		uint64_t reserved_56_63:8;
+		uint64_t psm1:15;
+		uint64_t psm0:15;
+		uint64_t nsm1:13;
+		uint64_t nsm0:13;
+	} s;
+	struct cvmx_npei_state3_s cn52xx;
+	struct cvmx_npei_state3_s cn52xxp1;
+	struct cvmx_npei_state3_s cn56xx;
+	struct cvmx_npei_state3_s cn56xxp1;
+};
+
+union cvmx_npei_win_rd_addr {
+	uint64_t u64;
+	struct cvmx_npei_win_rd_addr_s {
+		uint64_t reserved_51_63:13;
+		uint64_t ld_cmd:2;
+		uint64_t iobit:1;
+		uint64_t rd_addr:48;
+	} s;
+	struct cvmx_npei_win_rd_addr_s cn52xx;
+	struct cvmx_npei_win_rd_addr_s cn52xxp1;
+	struct cvmx_npei_win_rd_addr_s cn56xx;
+	struct cvmx_npei_win_rd_addr_s cn56xxp1;
+};
+
+union cvmx_npei_win_rd_data {
+	uint64_t u64;
+	struct cvmx_npei_win_rd_data_s {
+		uint64_t rd_data:64;
+	} s;
+	struct cvmx_npei_win_rd_data_s cn52xx;
+	struct cvmx_npei_win_rd_data_s cn52xxp1;
+	struct cvmx_npei_win_rd_data_s cn56xx;
+	struct cvmx_npei_win_rd_data_s cn56xxp1;
+};
+
+union cvmx_npei_win_wr_addr {
+	uint64_t u64;
+	struct cvmx_npei_win_wr_addr_s {
+		uint64_t reserved_49_63:15;
+		uint64_t iobit:1;
+		uint64_t wr_addr:46;
+		uint64_t reserved_0_1:2;
+	} s;
+	struct cvmx_npei_win_wr_addr_s cn52xx;
+	struct cvmx_npei_win_wr_addr_s cn52xxp1;
+	struct cvmx_npei_win_wr_addr_s cn56xx;
+	struct cvmx_npei_win_wr_addr_s cn56xxp1;
+};
+
+union cvmx_npei_win_wr_data {
+	uint64_t u64;
+	struct cvmx_npei_win_wr_data_s {
+		uint64_t wr_data:64;
+	} s;
+	struct cvmx_npei_win_wr_data_s cn52xx;
+	struct cvmx_npei_win_wr_data_s cn52xxp1;
+	struct cvmx_npei_win_wr_data_s cn56xx;
+	struct cvmx_npei_win_wr_data_s cn56xxp1;
+};
+
+union cvmx_npei_win_wr_mask {
+	uint64_t u64;
+	struct cvmx_npei_win_wr_mask_s {
+		uint64_t reserved_8_63:56;
+		uint64_t wr_mask:8;
+	} s;
+	struct cvmx_npei_win_wr_mask_s cn52xx;
+	struct cvmx_npei_win_wr_mask_s cn52xxp1;
+	struct cvmx_npei_win_wr_mask_s cn56xx;
+	struct cvmx_npei_win_wr_mask_s cn56xxp1;
+};
+
+union cvmx_npei_window_ctl {
+	uint64_t u64;
+	struct cvmx_npei_window_ctl_s {
+		uint64_t reserved_32_63:32;
+		uint64_t time:32;
+	} s;
+	struct cvmx_npei_window_ctl_s cn52xx;
+	struct cvmx_npei_window_ctl_s cn52xxp1;
+	struct cvmx_npei_window_ctl_s cn56xx;
+	struct cvmx_npei_window_ctl_s cn56xxp1;
+};
+
+#endif
diff --git a/arch/mips/include/asm/octeon/cvmx-npi-defs.h b/arch/mips/include/asm/octeon/cvmx-npi-defs.h
new file mode 100644
index 0000000..4e03cd8
--- /dev/null
+++ b/arch/mips/include/asm/octeon/cvmx-npi-defs.h
@@ -0,0 +1,1735 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_NPI_DEFS_H__
+#define __CVMX_NPI_DEFS_H__
+
+#define CVMX_NPI_BASE_ADDR_INPUT0 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000070ull)
+#define CVMX_NPI_BASE_ADDR_INPUT1 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000080ull)
+#define CVMX_NPI_BASE_ADDR_INPUT2 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000090ull)
+#define CVMX_NPI_BASE_ADDR_INPUT3 \
+	 CVMX_ADD_IO_SEG(0x00011F00000000A0ull)
+#define CVMX_NPI_BASE_ADDR_INPUTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000000070ull + (((offset) & 3) * 16))
+#define CVMX_NPI_BASE_ADDR_OUTPUT0 \
+	 CVMX_ADD_IO_SEG(0x00011F00000000B8ull)
+#define CVMX_NPI_BASE_ADDR_OUTPUT1 \
+	 CVMX_ADD_IO_SEG(0x00011F00000000C0ull)
+#define CVMX_NPI_BASE_ADDR_OUTPUT2 \
+	 CVMX_ADD_IO_SEG(0x00011F00000000C8ull)
+#define CVMX_NPI_BASE_ADDR_OUTPUT3 \
+	 CVMX_ADD_IO_SEG(0x00011F00000000D0ull)
+#define CVMX_NPI_BASE_ADDR_OUTPUTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F00000000B8ull + (((offset) & 3) * 8))
+#define CVMX_NPI_BIST_STATUS \
+	 CVMX_ADD_IO_SEG(0x00011F00000003F8ull)
+#define CVMX_NPI_BUFF_SIZE_OUTPUT0 \
+	 CVMX_ADD_IO_SEG(0x00011F00000000E0ull)
+#define CVMX_NPI_BUFF_SIZE_OUTPUT1 \
+	 CVMX_ADD_IO_SEG(0x00011F00000000E8ull)
+#define CVMX_NPI_BUFF_SIZE_OUTPUT2 \
+	 CVMX_ADD_IO_SEG(0x00011F00000000F0ull)
+#define CVMX_NPI_BUFF_SIZE_OUTPUT3 \
+	 CVMX_ADD_IO_SEG(0x00011F00000000F8ull)
+#define CVMX_NPI_BUFF_SIZE_OUTPUTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F00000000E0ull + (((offset) & 3) * 8))
+#define CVMX_NPI_COMP_CTL \
+	 CVMX_ADD_IO_SEG(0x00011F0000000218ull)
+#define CVMX_NPI_CTL_STATUS \
+	 CVMX_ADD_IO_SEG(0x00011F0000000010ull)
+#define CVMX_NPI_DBG_SELECT \
+	 CVMX_ADD_IO_SEG(0x00011F0000000008ull)
+#define CVMX_NPI_DMA_CONTROL \
+	 CVMX_ADD_IO_SEG(0x00011F0000000128ull)
+#define CVMX_NPI_DMA_HIGHP_COUNTS \
+	 CVMX_ADD_IO_SEG(0x00011F0000000148ull)
+#define CVMX_NPI_DMA_HIGHP_NADDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000000158ull)
+#define CVMX_NPI_DMA_LOWP_COUNTS \
+	 CVMX_ADD_IO_SEG(0x00011F0000000140ull)
+#define CVMX_NPI_DMA_LOWP_NADDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000000150ull)
+#define CVMX_NPI_HIGHP_DBELL \
+	 CVMX_ADD_IO_SEG(0x00011F0000000120ull)
+#define CVMX_NPI_HIGHP_IBUFF_SADDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000000110ull)
+#define CVMX_NPI_INPUT_CONTROL \
+	 CVMX_ADD_IO_SEG(0x00011F0000000138ull)
+#define CVMX_NPI_INT_ENB \
+	 CVMX_ADD_IO_SEG(0x00011F0000000020ull)
+#define CVMX_NPI_INT_SUM \
+	 CVMX_ADD_IO_SEG(0x00011F0000000018ull)
+#define CVMX_NPI_LOWP_DBELL \
+	 CVMX_ADD_IO_SEG(0x00011F0000000118ull)
+#define CVMX_NPI_LOWP_IBUFF_SADDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000000108ull)
+#define CVMX_NPI_MEM_ACCESS_SUBID3 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000028ull)
+#define CVMX_NPI_MEM_ACCESS_SUBID4 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000030ull)
+#define CVMX_NPI_MEM_ACCESS_SUBID5 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000038ull)
+#define CVMX_NPI_MEM_ACCESS_SUBID6 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000040ull)
+#define CVMX_NPI_MEM_ACCESS_SUBIDX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000000028ull + (((offset) & 7) * 8) - 8 * 3)
+#define CVMX_NPI_MSI_RCV \
+	 (0x0000000000000190ull)
+#define CVMX_NPI_NPI_MSI_RCV \
+	 CVMX_ADD_IO_SEG(0x00011F0000001190ull)
+#define CVMX_NPI_NUM_DESC_OUTPUT0 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000050ull)
+#define CVMX_NPI_NUM_DESC_OUTPUT1 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000058ull)
+#define CVMX_NPI_NUM_DESC_OUTPUT2 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000060ull)
+#define CVMX_NPI_NUM_DESC_OUTPUT3 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000068ull)
+#define CVMX_NPI_NUM_DESC_OUTPUTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000000050ull + (((offset) & 3) * 8))
+#define CVMX_NPI_OUTPUT_CONTROL \
+	 CVMX_ADD_IO_SEG(0x00011F0000000100ull)
+#define CVMX_NPI_P0_DBPAIR_ADDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000000180ull)
+#define CVMX_NPI_P0_INSTR_ADDR \
+	 CVMX_ADD_IO_SEG(0x00011F00000001C0ull)
+#define CVMX_NPI_P0_INSTR_CNTS \
+	 CVMX_ADD_IO_SEG(0x00011F00000001A0ull)
+#define CVMX_NPI_P0_PAIR_CNTS \
+	 CVMX_ADD_IO_SEG(0x00011F0000000160ull)
+#define CVMX_NPI_P1_DBPAIR_ADDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000000188ull)
+#define CVMX_NPI_P1_INSTR_ADDR \
+	 CVMX_ADD_IO_SEG(0x00011F00000001C8ull)
+#define CVMX_NPI_P1_INSTR_CNTS \
+	 CVMX_ADD_IO_SEG(0x00011F00000001A8ull)
+#define CVMX_NPI_P1_PAIR_CNTS \
+	 CVMX_ADD_IO_SEG(0x00011F0000000168ull)
+#define CVMX_NPI_P2_DBPAIR_ADDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000000190ull)
+#define CVMX_NPI_P2_INSTR_ADDR \
+	 CVMX_ADD_IO_SEG(0x00011F00000001D0ull)
+#define CVMX_NPI_P2_INSTR_CNTS \
+	 CVMX_ADD_IO_SEG(0x00011F00000001B0ull)
+#define CVMX_NPI_P2_PAIR_CNTS \
+	 CVMX_ADD_IO_SEG(0x00011F0000000170ull)
+#define CVMX_NPI_P3_DBPAIR_ADDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000000198ull)
+#define CVMX_NPI_P3_INSTR_ADDR \
+	 CVMX_ADD_IO_SEG(0x00011F00000001D8ull)
+#define CVMX_NPI_P3_INSTR_CNTS \
+	 CVMX_ADD_IO_SEG(0x00011F00000001B8ull)
+#define CVMX_NPI_P3_PAIR_CNTS \
+	 CVMX_ADD_IO_SEG(0x00011F0000000178ull)
+#define CVMX_NPI_PCI_BAR1_INDEXX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000001100ull + (((offset) & 31) * 4))
+#define CVMX_NPI_PCI_BIST_REG \
+	 CVMX_ADD_IO_SEG(0x00011F00000011C0ull)
+#define CVMX_NPI_PCI_BURST_SIZE \
+	 CVMX_ADD_IO_SEG(0x00011F00000000D8ull)
+#define CVMX_NPI_PCI_CFG00 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001800ull)
+#define CVMX_NPI_PCI_CFG01 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001804ull)
+#define CVMX_NPI_PCI_CFG02 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001808ull)
+#define CVMX_NPI_PCI_CFG03 \
+	 CVMX_ADD_IO_SEG(0x00011F000000180Cull)
+#define CVMX_NPI_PCI_CFG04 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001810ull)
+#define CVMX_NPI_PCI_CFG05 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001814ull)
+#define CVMX_NPI_PCI_CFG06 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001818ull)
+#define CVMX_NPI_PCI_CFG07 \
+	 CVMX_ADD_IO_SEG(0x00011F000000181Cull)
+#define CVMX_NPI_PCI_CFG08 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001820ull)
+#define CVMX_NPI_PCI_CFG09 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001824ull)
+#define CVMX_NPI_PCI_CFG10 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001828ull)
+#define CVMX_NPI_PCI_CFG11 \
+	 CVMX_ADD_IO_SEG(0x00011F000000182Cull)
+#define CVMX_NPI_PCI_CFG12 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001830ull)
+#define CVMX_NPI_PCI_CFG13 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001834ull)
+#define CVMX_NPI_PCI_CFG15 \
+	 CVMX_ADD_IO_SEG(0x00011F000000183Cull)
+#define CVMX_NPI_PCI_CFG16 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001840ull)
+#define CVMX_NPI_PCI_CFG17 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001844ull)
+#define CVMX_NPI_PCI_CFG18 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001848ull)
+#define CVMX_NPI_PCI_CFG19 \
+	 CVMX_ADD_IO_SEG(0x00011F000000184Cull)
+#define CVMX_NPI_PCI_CFG20 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001850ull)
+#define CVMX_NPI_PCI_CFG21 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001854ull)
+#define CVMX_NPI_PCI_CFG22 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001858ull)
+#define CVMX_NPI_PCI_CFG56 \
+	 CVMX_ADD_IO_SEG(0x00011F00000018E0ull)
+#define CVMX_NPI_PCI_CFG57 \
+	 CVMX_ADD_IO_SEG(0x00011F00000018E4ull)
+#define CVMX_NPI_PCI_CFG58 \
+	 CVMX_ADD_IO_SEG(0x00011F00000018E8ull)
+#define CVMX_NPI_PCI_CFG59 \
+	 CVMX_ADD_IO_SEG(0x00011F00000018ECull)
+#define CVMX_NPI_PCI_CFG60 \
+	 CVMX_ADD_IO_SEG(0x00011F00000018F0ull)
+#define CVMX_NPI_PCI_CFG61 \
+	 CVMX_ADD_IO_SEG(0x00011F00000018F4ull)
+#define CVMX_NPI_PCI_CFG62 \
+	 CVMX_ADD_IO_SEG(0x00011F00000018F8ull)
+#define CVMX_NPI_PCI_CFG63 \
+	 CVMX_ADD_IO_SEG(0x00011F00000018FCull)
+#define CVMX_NPI_PCI_CNT_REG \
+	 CVMX_ADD_IO_SEG(0x00011F00000011B8ull)
+#define CVMX_NPI_PCI_CTL_STATUS_2 \
+	 CVMX_ADD_IO_SEG(0x00011F000000118Cull)
+#define CVMX_NPI_PCI_INT_ARB_CFG \
+	 CVMX_ADD_IO_SEG(0x00011F0000000130ull)
+#define CVMX_NPI_PCI_INT_ENB2 \
+	 CVMX_ADD_IO_SEG(0x00011F00000011A0ull)
+#define CVMX_NPI_PCI_INT_SUM2 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001198ull)
+#define CVMX_NPI_PCI_READ_CMD \
+	 CVMX_ADD_IO_SEG(0x00011F0000000048ull)
+#define CVMX_NPI_PCI_READ_CMD_6 \
+	 CVMX_ADD_IO_SEG(0x00011F0000001180ull)
+#define CVMX_NPI_PCI_READ_CMD_C \
+	 CVMX_ADD_IO_SEG(0x00011F0000001184ull)
+#define CVMX_NPI_PCI_READ_CMD_E \
+	 CVMX_ADD_IO_SEG(0x00011F0000001188ull)
+#define CVMX_NPI_PCI_SCM_REG \
+	 CVMX_ADD_IO_SEG(0x00011F00000011A8ull)
+#define CVMX_NPI_PCI_TSR_REG \
+	 CVMX_ADD_IO_SEG(0x00011F00000011B0ull)
+#define CVMX_NPI_PORT32_INSTR_HDR \
+	 CVMX_ADD_IO_SEG(0x00011F00000001F8ull)
+#define CVMX_NPI_PORT33_INSTR_HDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000000200ull)
+#define CVMX_NPI_PORT34_INSTR_HDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000000208ull)
+#define CVMX_NPI_PORT35_INSTR_HDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000000210ull)
+#define CVMX_NPI_PORT_BP_CONTROL \
+	 CVMX_ADD_IO_SEG(0x00011F00000001F0ull)
+#define CVMX_NPI_PX_DBPAIR_ADDR(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000000180ull + (((offset) & 3) * 8))
+#define CVMX_NPI_PX_INSTR_ADDR(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F00000001C0ull + (((offset) & 3) * 8))
+#define CVMX_NPI_PX_INSTR_CNTS(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F00000001A0ull + (((offset) & 3) * 8))
+#define CVMX_NPI_PX_PAIR_CNTS(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000000160ull + (((offset) & 3) * 8))
+#define CVMX_NPI_RSL_INT_BLOCKS \
+	 CVMX_ADD_IO_SEG(0x00011F0000000000ull)
+#define CVMX_NPI_SIZE_INPUT0 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000078ull)
+#define CVMX_NPI_SIZE_INPUT1 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000088ull)
+#define CVMX_NPI_SIZE_INPUT2 \
+	 CVMX_ADD_IO_SEG(0x00011F0000000098ull)
+#define CVMX_NPI_SIZE_INPUT3 \
+	 CVMX_ADD_IO_SEG(0x00011F00000000A8ull)
+#define CVMX_NPI_SIZE_INPUTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000000078ull + (((offset) & 3) * 16))
+#define CVMX_NPI_WIN_READ_TO \
+	 CVMX_ADD_IO_SEG(0x00011F00000001E0ull)
+
+union cvmx_npi_base_addr_inputx {
+	uint64_t u64;
+	struct cvmx_npi_base_addr_inputx_s {
+		uint64_t baddr:61;
+		uint64_t reserved_0_2:3;
+	} s;
+	struct cvmx_npi_base_addr_inputx_s cn30xx;
+	struct cvmx_npi_base_addr_inputx_s cn31xx;
+	struct cvmx_npi_base_addr_inputx_s cn38xx;
+	struct cvmx_npi_base_addr_inputx_s cn38xxp2;
+	struct cvmx_npi_base_addr_inputx_s cn50xx;
+	struct cvmx_npi_base_addr_inputx_s cn58xx;
+	struct cvmx_npi_base_addr_inputx_s cn58xxp1;
+};
+
+union cvmx_npi_base_addr_outputx {
+	uint64_t u64;
+	struct cvmx_npi_base_addr_outputx_s {
+		uint64_t baddr:61;
+		uint64_t reserved_0_2:3;
+	} s;
+	struct cvmx_npi_base_addr_outputx_s cn30xx;
+	struct cvmx_npi_base_addr_outputx_s cn31xx;
+	struct cvmx_npi_base_addr_outputx_s cn38xx;
+	struct cvmx_npi_base_addr_outputx_s cn38xxp2;
+	struct cvmx_npi_base_addr_outputx_s cn50xx;
+	struct cvmx_npi_base_addr_outputx_s cn58xx;
+	struct cvmx_npi_base_addr_outputx_s cn58xxp1;
+};
+
+union cvmx_npi_bist_status {
+	uint64_t u64;
+	struct cvmx_npi_bist_status_s {
+		uint64_t reserved_20_63:44;
+		uint64_t csr_bs:1;
+		uint64_t dif_bs:1;
+		uint64_t rdp_bs:1;
+		uint64_t pcnc_bs:1;
+		uint64_t pcn_bs:1;
+		uint64_t rdn_bs:1;
+		uint64_t pcac_bs:1;
+		uint64_t pcad_bs:1;
+		uint64_t rdnl_bs:1;
+		uint64_t pgf_bs:1;
+		uint64_t pig_bs:1;
+		uint64_t pof0_bs:1;
+		uint64_t pof1_bs:1;
+		uint64_t pof2_bs:1;
+		uint64_t pof3_bs:1;
+		uint64_t pos_bs:1;
+		uint64_t nus_bs:1;
+		uint64_t dob_bs:1;
+		uint64_t pdf_bs:1;
+		uint64_t dpi_bs:1;
+	} s;
+	struct cvmx_npi_bist_status_cn30xx {
+		uint64_t reserved_20_63:44;
+		uint64_t csr_bs:1;
+		uint64_t dif_bs:1;
+		uint64_t rdp_bs:1;
+		uint64_t pcnc_bs:1;
+		uint64_t pcn_bs:1;
+		uint64_t rdn_bs:1;
+		uint64_t pcac_bs:1;
+		uint64_t pcad_bs:1;
+		uint64_t rdnl_bs:1;
+		uint64_t pgf_bs:1;
+		uint64_t pig_bs:1;
+		uint64_t pof0_bs:1;
+		uint64_t reserved_5_7:3;
+		uint64_t pos_bs:1;
+		uint64_t nus_bs:1;
+		uint64_t dob_bs:1;
+		uint64_t pdf_bs:1;
+		uint64_t dpi_bs:1;
+	} cn30xx;
+	struct cvmx_npi_bist_status_s cn31xx;
+	struct cvmx_npi_bist_status_s cn38xx;
+	struct cvmx_npi_bist_status_s cn38xxp2;
+	struct cvmx_npi_bist_status_cn50xx {
+		uint64_t reserved_20_63:44;
+		uint64_t csr_bs:1;
+		uint64_t dif_bs:1;
+		uint64_t rdp_bs:1;
+		uint64_t pcnc_bs:1;
+		uint64_t pcn_bs:1;
+		uint64_t rdn_bs:1;
+		uint64_t pcac_bs:1;
+		uint64_t pcad_bs:1;
+		uint64_t rdnl_bs:1;
+		uint64_t pgf_bs:1;
+		uint64_t pig_bs:1;
+		uint64_t pof0_bs:1;
+		uint64_t pof1_bs:1;
+		uint64_t reserved_5_6:2;
+		uint64_t pos_bs:1;
+		uint64_t nus_bs:1;
+		uint64_t dob_bs:1;
+		uint64_t pdf_bs:1;
+		uint64_t dpi_bs:1;
+	} cn50xx;
+	struct cvmx_npi_bist_status_s cn58xx;
+	struct cvmx_npi_bist_status_s cn58xxp1;
+};
+
+union cvmx_npi_buff_size_outputx {
+	uint64_t u64;
+	struct cvmx_npi_buff_size_outputx_s {
+		uint64_t reserved_23_63:41;
+		uint64_t isize:7;
+		uint64_t bsize:16;
+	} s;
+	struct cvmx_npi_buff_size_outputx_s cn30xx;
+	struct cvmx_npi_buff_size_outputx_s cn31xx;
+	struct cvmx_npi_buff_size_outputx_s cn38xx;
+	struct cvmx_npi_buff_size_outputx_s cn38xxp2;
+	struct cvmx_npi_buff_size_outputx_s cn50xx;
+	struct cvmx_npi_buff_size_outputx_s cn58xx;
+	struct cvmx_npi_buff_size_outputx_s cn58xxp1;
+};
+
+union cvmx_npi_comp_ctl {
+	uint64_t u64;
+	struct cvmx_npi_comp_ctl_s {
+		uint64_t reserved_10_63:54;
+		uint64_t pctl:5;
+		uint64_t nctl:5;
+	} s;
+	struct cvmx_npi_comp_ctl_s cn50xx;
+	struct cvmx_npi_comp_ctl_s cn58xx;
+	struct cvmx_npi_comp_ctl_s cn58xxp1;
+};
+
+union cvmx_npi_ctl_status {
+	uint64_t u64;
+	struct cvmx_npi_ctl_status_s {
+		uint64_t reserved_63_63:1;
+		uint64_t chip_rev:8;
+		uint64_t dis_pniw:1;
+		uint64_t out3_enb:1;
+		uint64_t out2_enb:1;
+		uint64_t out1_enb:1;
+		uint64_t out0_enb:1;
+		uint64_t ins3_enb:1;
+		uint64_t ins2_enb:1;
+		uint64_t ins1_enb:1;
+		uint64_t ins0_enb:1;
+		uint64_t ins3_64b:1;
+		uint64_t ins2_64b:1;
+		uint64_t ins1_64b:1;
+		uint64_t ins0_64b:1;
+		uint64_t pci_wdis:1;
+		uint64_t wait_com:1;
+		uint64_t reserved_37_39:3;
+		uint64_t max_word:5;
+		uint64_t reserved_10_31:22;
+		uint64_t timer:10;
+	} s;
+	struct cvmx_npi_ctl_status_cn30xx {
+		uint64_t reserved_63_63:1;
+		uint64_t chip_rev:8;
+		uint64_t dis_pniw:1;
+		uint64_t reserved_51_53:3;
+		uint64_t out0_enb:1;
+		uint64_t reserved_47_49:3;
+		uint64_t ins0_enb:1;
+		uint64_t reserved_43_45:3;
+		uint64_t ins0_64b:1;
+		uint64_t pci_wdis:1;
+		uint64_t wait_com:1;
+		uint64_t reserved_37_39:3;
+		uint64_t max_word:5;
+		uint64_t reserved_10_31:22;
+		uint64_t timer:10;
+	} cn30xx;
+	struct cvmx_npi_ctl_status_cn31xx {
+		uint64_t reserved_63_63:1;
+		uint64_t chip_rev:8;
+		uint64_t dis_pniw:1;
+		uint64_t reserved_52_53:2;
+		uint64_t out1_enb:1;
+		uint64_t out0_enb:1;
+		uint64_t reserved_48_49:2;
+		uint64_t ins1_enb:1;
+		uint64_t ins0_enb:1;
+		uint64_t reserved_44_45:2;
+		uint64_t ins1_64b:1;
+		uint64_t ins0_64b:1;
+		uint64_t pci_wdis:1;
+		uint64_t wait_com:1;
+		uint64_t reserved_37_39:3;
+		uint64_t max_word:5;
+		uint64_t reserved_10_31:22;
+		uint64_t timer:10;
+	} cn31xx;
+	struct cvmx_npi_ctl_status_s cn38xx;
+	struct cvmx_npi_ctl_status_s cn38xxp2;
+	struct cvmx_npi_ctl_status_cn31xx cn50xx;
+	struct cvmx_npi_ctl_status_s cn58xx;
+	struct cvmx_npi_ctl_status_s cn58xxp1;
+};
+
+union cvmx_npi_dbg_select {
+	uint64_t u64;
+	struct cvmx_npi_dbg_select_s {
+		uint64_t reserved_16_63:48;
+		uint64_t dbg_sel:16;
+	} s;
+	struct cvmx_npi_dbg_select_s cn30xx;
+	struct cvmx_npi_dbg_select_s cn31xx;
+	struct cvmx_npi_dbg_select_s cn38xx;
+	struct cvmx_npi_dbg_select_s cn38xxp2;
+	struct cvmx_npi_dbg_select_s cn50xx;
+	struct cvmx_npi_dbg_select_s cn58xx;
+	struct cvmx_npi_dbg_select_s cn58xxp1;
+};
+
+union cvmx_npi_dma_control {
+	uint64_t u64;
+	struct cvmx_npi_dma_control_s {
+		uint64_t reserved_36_63:28;
+		uint64_t b0_lend:1;
+		uint64_t dwb_denb:1;
+		uint64_t dwb_ichk:9;
+		uint64_t fpa_que:3;
+		uint64_t o_add1:1;
+		uint64_t o_ro:1;
+		uint64_t o_ns:1;
+		uint64_t o_es:2;
+		uint64_t o_mode:1;
+		uint64_t hp_enb:1;
+		uint64_t lp_enb:1;
+		uint64_t csize:14;
+	} s;
+	struct cvmx_npi_dma_control_s cn30xx;
+	struct cvmx_npi_dma_control_s cn31xx;
+	struct cvmx_npi_dma_control_s cn38xx;
+	struct cvmx_npi_dma_control_s cn38xxp2;
+	struct cvmx_npi_dma_control_s cn50xx;
+	struct cvmx_npi_dma_control_s cn58xx;
+	struct cvmx_npi_dma_control_s cn58xxp1;
+};
+
+union cvmx_npi_dma_highp_counts {
+	uint64_t u64;
+	struct cvmx_npi_dma_highp_counts_s {
+		uint64_t reserved_39_63:25;
+		uint64_t fcnt:7;
+		uint64_t dbell:32;
+	} s;
+	struct cvmx_npi_dma_highp_counts_s cn30xx;
+	struct cvmx_npi_dma_highp_counts_s cn31xx;
+	struct cvmx_npi_dma_highp_counts_s cn38xx;
+	struct cvmx_npi_dma_highp_counts_s cn38xxp2;
+	struct cvmx_npi_dma_highp_counts_s cn50xx;
+	struct cvmx_npi_dma_highp_counts_s cn58xx;
+	struct cvmx_npi_dma_highp_counts_s cn58xxp1;
+};
+
+union cvmx_npi_dma_highp_naddr {
+	uint64_t u64;
+	struct cvmx_npi_dma_highp_naddr_s {
+		uint64_t reserved_40_63:24;
+		uint64_t state:4;
+		uint64_t addr:36;
+	} s;
+	struct cvmx_npi_dma_highp_naddr_s cn30xx;
+	struct cvmx_npi_dma_highp_naddr_s cn31xx;
+	struct cvmx_npi_dma_highp_naddr_s cn38xx;
+	struct cvmx_npi_dma_highp_naddr_s cn38xxp2;
+	struct cvmx_npi_dma_highp_naddr_s cn50xx;
+	struct cvmx_npi_dma_highp_naddr_s cn58xx;
+	struct cvmx_npi_dma_highp_naddr_s cn58xxp1;
+};
+
+union cvmx_npi_dma_lowp_counts {
+	uint64_t u64;
+	struct cvmx_npi_dma_lowp_counts_s {
+		uint64_t reserved_39_63:25;
+		uint64_t fcnt:7;
+		uint64_t dbell:32;
+	} s;
+	struct cvmx_npi_dma_lowp_counts_s cn30xx;
+	struct cvmx_npi_dma_lowp_counts_s cn31xx;
+	struct cvmx_npi_dma_lowp_counts_s cn38xx;
+	struct cvmx_npi_dma_lowp_counts_s cn38xxp2;
+	struct cvmx_npi_dma_lowp_counts_s cn50xx;
+	struct cvmx_npi_dma_lowp_counts_s cn58xx;
+	struct cvmx_npi_dma_lowp_counts_s cn58xxp1;
+};
+
+union cvmx_npi_dma_lowp_naddr {
+	uint64_t u64;
+	struct cvmx_npi_dma_lowp_naddr_s {
+		uint64_t reserved_40_63:24;
+		uint64_t state:4;
+		uint64_t addr:36;
+	} s;
+	struct cvmx_npi_dma_lowp_naddr_s cn30xx;
+	struct cvmx_npi_dma_lowp_naddr_s cn31xx;
+	struct cvmx_npi_dma_lowp_naddr_s cn38xx;
+	struct cvmx_npi_dma_lowp_naddr_s cn38xxp2;
+	struct cvmx_npi_dma_lowp_naddr_s cn50xx;
+	struct cvmx_npi_dma_lowp_naddr_s cn58xx;
+	struct cvmx_npi_dma_lowp_naddr_s cn58xxp1;
+};
+
+union cvmx_npi_highp_dbell {
+	uint64_t u64;
+	struct cvmx_npi_highp_dbell_s {
+		uint64_t reserved_16_63:48;
+		uint64_t dbell:16;
+	} s;
+	struct cvmx_npi_highp_dbell_s cn30xx;
+	struct cvmx_npi_highp_dbell_s cn31xx;
+	struct cvmx_npi_highp_dbell_s cn38xx;
+	struct cvmx_npi_highp_dbell_s cn38xxp2;
+	struct cvmx_npi_highp_dbell_s cn50xx;
+	struct cvmx_npi_highp_dbell_s cn58xx;
+	struct cvmx_npi_highp_dbell_s cn58xxp1;
+};
+
+union cvmx_npi_highp_ibuff_saddr {
+	uint64_t u64;
+	struct cvmx_npi_highp_ibuff_saddr_s {
+		uint64_t reserved_36_63:28;
+		uint64_t saddr:36;
+	} s;
+	struct cvmx_npi_highp_ibuff_saddr_s cn30xx;
+	struct cvmx_npi_highp_ibuff_saddr_s cn31xx;
+	struct cvmx_npi_highp_ibuff_saddr_s cn38xx;
+	struct cvmx_npi_highp_ibuff_saddr_s cn38xxp2;
+	struct cvmx_npi_highp_ibuff_saddr_s cn50xx;
+	struct cvmx_npi_highp_ibuff_saddr_s cn58xx;
+	struct cvmx_npi_highp_ibuff_saddr_s cn58xxp1;
+};
+
+union cvmx_npi_input_control {
+	uint64_t u64;
+	struct cvmx_npi_input_control_s {
+		uint64_t reserved_23_63:41;
+		uint64_t pkt_rr:1;
+		uint64_t pbp_dhi:13;
+		uint64_t d_nsr:1;
+		uint64_t d_esr:2;
+		uint64_t d_ror:1;
+		uint64_t use_csr:1;
+		uint64_t nsr:1;
+		uint64_t esr:2;
+		uint64_t ror:1;
+	} s;
+	struct cvmx_npi_input_control_cn30xx {
+		uint64_t reserved_22_63:42;
+		uint64_t pbp_dhi:13;
+		uint64_t d_nsr:1;
+		uint64_t d_esr:2;
+		uint64_t d_ror:1;
+		uint64_t use_csr:1;
+		uint64_t nsr:1;
+		uint64_t esr:2;
+		uint64_t ror:1;
+	} cn30xx;
+	struct cvmx_npi_input_control_cn30xx cn31xx;
+	struct cvmx_npi_input_control_s cn38xx;
+	struct cvmx_npi_input_control_cn30xx cn38xxp2;
+	struct cvmx_npi_input_control_s cn50xx;
+	struct cvmx_npi_input_control_s cn58xx;
+	struct cvmx_npi_input_control_s cn58xxp1;
+};
+
+union cvmx_npi_int_enb {
+	uint64_t u64;
+	struct cvmx_npi_int_enb_s {
+		uint64_t reserved_62_63:2;
+		uint64_t q1_a_f:1;
+		uint64_t q1_s_e:1;
+		uint64_t pdf_p_f:1;
+		uint64_t pdf_p_e:1;
+		uint64_t pcf_p_f:1;
+		uint64_t pcf_p_e:1;
+		uint64_t rdx_s_e:1;
+		uint64_t rwx_s_e:1;
+		uint64_t pnc_a_f:1;
+		uint64_t pnc_s_e:1;
+		uint64_t com_a_f:1;
+		uint64_t com_s_e:1;
+		uint64_t q3_a_f:1;
+		uint64_t q3_s_e:1;
+		uint64_t q2_a_f:1;
+		uint64_t q2_s_e:1;
+		uint64_t pcr_a_f:1;
+		uint64_t pcr_s_e:1;
+		uint64_t fcr_a_f:1;
+		uint64_t fcr_s_e:1;
+		uint64_t iobdma:1;
+		uint64_t p_dperr:1;
+		uint64_t win_rto:1;
+		uint64_t i3_pperr:1;
+		uint64_t i2_pperr:1;
+		uint64_t i1_pperr:1;
+		uint64_t i0_pperr:1;
+		uint64_t p3_ptout:1;
+		uint64_t p2_ptout:1;
+		uint64_t p1_ptout:1;
+		uint64_t p0_ptout:1;
+		uint64_t p3_pperr:1;
+		uint64_t p2_pperr:1;
+		uint64_t p1_pperr:1;
+		uint64_t p0_pperr:1;
+		uint64_t g3_rtout:1;
+		uint64_t g2_rtout:1;
+		uint64_t g1_rtout:1;
+		uint64_t g0_rtout:1;
+		uint64_t p3_perr:1;
+		uint64_t p2_perr:1;
+		uint64_t p1_perr:1;
+		uint64_t p0_perr:1;
+		uint64_t p3_rtout:1;
+		uint64_t p2_rtout:1;
+		uint64_t p1_rtout:1;
+		uint64_t p0_rtout:1;
+		uint64_t i3_overf:1;
+		uint64_t i2_overf:1;
+		uint64_t i1_overf:1;
+		uint64_t i0_overf:1;
+		uint64_t i3_rtout:1;
+		uint64_t i2_rtout:1;
+		uint64_t i1_rtout:1;
+		uint64_t i0_rtout:1;
+		uint64_t po3_2sml:1;
+		uint64_t po2_2sml:1;
+		uint64_t po1_2sml:1;
+		uint64_t po0_2sml:1;
+		uint64_t pci_rsl:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} s;
+	struct cvmx_npi_int_enb_cn30xx {
+		uint64_t reserved_62_63:2;
+		uint64_t q1_a_f:1;
+		uint64_t q1_s_e:1;
+		uint64_t pdf_p_f:1;
+		uint64_t pdf_p_e:1;
+		uint64_t pcf_p_f:1;
+		uint64_t pcf_p_e:1;
+		uint64_t rdx_s_e:1;
+		uint64_t rwx_s_e:1;
+		uint64_t pnc_a_f:1;
+		uint64_t pnc_s_e:1;
+		uint64_t com_a_f:1;
+		uint64_t com_s_e:1;
+		uint64_t q3_a_f:1;
+		uint64_t q3_s_e:1;
+		uint64_t q2_a_f:1;
+		uint64_t q2_s_e:1;
+		uint64_t pcr_a_f:1;
+		uint64_t pcr_s_e:1;
+		uint64_t fcr_a_f:1;
+		uint64_t fcr_s_e:1;
+		uint64_t iobdma:1;
+		uint64_t p_dperr:1;
+		uint64_t win_rto:1;
+		uint64_t reserved_36_38:3;
+		uint64_t i0_pperr:1;
+		uint64_t reserved_32_34:3;
+		uint64_t p0_ptout:1;
+		uint64_t reserved_28_30:3;
+		uint64_t p0_pperr:1;
+		uint64_t reserved_24_26:3;
+		uint64_t g0_rtout:1;
+		uint64_t reserved_20_22:3;
+		uint64_t p0_perr:1;
+		uint64_t reserved_16_18:3;
+		uint64_t p0_rtout:1;
+		uint64_t reserved_12_14:3;
+		uint64_t i0_overf:1;
+		uint64_t reserved_8_10:3;
+		uint64_t i0_rtout:1;
+		uint64_t reserved_4_6:3;
+		uint64_t po0_2sml:1;
+		uint64_t pci_rsl:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn30xx;
+	struct cvmx_npi_int_enb_cn31xx {
+		uint64_t reserved_62_63:2;
+		uint64_t q1_a_f:1;
+		uint64_t q1_s_e:1;
+		uint64_t pdf_p_f:1;
+		uint64_t pdf_p_e:1;
+		uint64_t pcf_p_f:1;
+		uint64_t pcf_p_e:1;
+		uint64_t rdx_s_e:1;
+		uint64_t rwx_s_e:1;
+		uint64_t pnc_a_f:1;
+		uint64_t pnc_s_e:1;
+		uint64_t com_a_f:1;
+		uint64_t com_s_e:1;
+		uint64_t q3_a_f:1;
+		uint64_t q3_s_e:1;
+		uint64_t q2_a_f:1;
+		uint64_t q2_s_e:1;
+		uint64_t pcr_a_f:1;
+		uint64_t pcr_s_e:1;
+		uint64_t fcr_a_f:1;
+		uint64_t fcr_s_e:1;
+		uint64_t iobdma:1;
+		uint64_t p_dperr:1;
+		uint64_t win_rto:1;
+		uint64_t reserved_37_38:2;
+		uint64_t i1_pperr:1;
+		uint64_t i0_pperr:1;
+		uint64_t reserved_33_34:2;
+		uint64_t p1_ptout:1;
+		uint64_t p0_ptout:1;
+		uint64_t reserved_29_30:2;
+		uint64_t p1_pperr:1;
+		uint64_t p0_pperr:1;
+		uint64_t reserved_25_26:2;
+		uint64_t g1_rtout:1;
+		uint64_t g0_rtout:1;
+		uint64_t reserved_21_22:2;
+		uint64_t p1_perr:1;
+		uint64_t p0_perr:1;
+		uint64_t reserved_17_18:2;
+		uint64_t p1_rtout:1;
+		uint64_t p0_rtout:1;
+		uint64_t reserved_13_14:2;
+		uint64_t i1_overf:1;
+		uint64_t i0_overf:1;
+		uint64_t reserved_9_10:2;
+		uint64_t i1_rtout:1;
+		uint64_t i0_rtout:1;
+		uint64_t reserved_5_6:2;
+		uint64_t po1_2sml:1;
+		uint64_t po0_2sml:1;
+		uint64_t pci_rsl:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn31xx;
+	struct cvmx_npi_int_enb_s cn38xx;
+	struct cvmx_npi_int_enb_cn38xxp2 {
+		uint64_t reserved_42_63:22;
+		uint64_t iobdma:1;
+		uint64_t p_dperr:1;
+		uint64_t win_rto:1;
+		uint64_t i3_pperr:1;
+		uint64_t i2_pperr:1;
+		uint64_t i1_pperr:1;
+		uint64_t i0_pperr:1;
+		uint64_t p3_ptout:1;
+		uint64_t p2_ptout:1;
+		uint64_t p1_ptout:1;
+		uint64_t p0_ptout:1;
+		uint64_t p3_pperr:1;
+		uint64_t p2_pperr:1;
+		uint64_t p1_pperr:1;
+		uint64_t p0_pperr:1;
+		uint64_t g3_rtout:1;
+		uint64_t g2_rtout:1;
+		uint64_t g1_rtout:1;
+		uint64_t g0_rtout:1;
+		uint64_t p3_perr:1;
+		uint64_t p2_perr:1;
+		uint64_t p1_perr:1;
+		uint64_t p0_perr:1;
+		uint64_t p3_rtout:1;
+		uint64_t p2_rtout:1;
+		uint64_t p1_rtout:1;
+		uint64_t p0_rtout:1;
+		uint64_t i3_overf:1;
+		uint64_t i2_overf:1;
+		uint64_t i1_overf:1;
+		uint64_t i0_overf:1;
+		uint64_t i3_rtout:1;
+		uint64_t i2_rtout:1;
+		uint64_t i1_rtout:1;
+		uint64_t i0_rtout:1;
+		uint64_t po3_2sml:1;
+		uint64_t po2_2sml:1;
+		uint64_t po1_2sml:1;
+		uint64_t po0_2sml:1;
+		uint64_t pci_rsl:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn38xxp2;
+	struct cvmx_npi_int_enb_cn31xx cn50xx;
+	struct cvmx_npi_int_enb_s cn58xx;
+	struct cvmx_npi_int_enb_s cn58xxp1;
+};
+
+union cvmx_npi_int_sum {
+	uint64_t u64;
+	struct cvmx_npi_int_sum_s {
+		uint64_t reserved_62_63:2;
+		uint64_t q1_a_f:1;
+		uint64_t q1_s_e:1;
+		uint64_t pdf_p_f:1;
+		uint64_t pdf_p_e:1;
+		uint64_t pcf_p_f:1;
+		uint64_t pcf_p_e:1;
+		uint64_t rdx_s_e:1;
+		uint64_t rwx_s_e:1;
+		uint64_t pnc_a_f:1;
+		uint64_t pnc_s_e:1;
+		uint64_t com_a_f:1;
+		uint64_t com_s_e:1;
+		uint64_t q3_a_f:1;
+		uint64_t q3_s_e:1;
+		uint64_t q2_a_f:1;
+		uint64_t q2_s_e:1;
+		uint64_t pcr_a_f:1;
+		uint64_t pcr_s_e:1;
+		uint64_t fcr_a_f:1;
+		uint64_t fcr_s_e:1;
+		uint64_t iobdma:1;
+		uint64_t p_dperr:1;
+		uint64_t win_rto:1;
+		uint64_t i3_pperr:1;
+		uint64_t i2_pperr:1;
+		uint64_t i1_pperr:1;
+		uint64_t i0_pperr:1;
+		uint64_t p3_ptout:1;
+		uint64_t p2_ptout:1;
+		uint64_t p1_ptout:1;
+		uint64_t p0_ptout:1;
+		uint64_t p3_pperr:1;
+		uint64_t p2_pperr:1;
+		uint64_t p1_pperr:1;
+		uint64_t p0_pperr:1;
+		uint64_t g3_rtout:1;
+		uint64_t g2_rtout:1;
+		uint64_t g1_rtout:1;
+		uint64_t g0_rtout:1;
+		uint64_t p3_perr:1;
+		uint64_t p2_perr:1;
+		uint64_t p1_perr:1;
+		uint64_t p0_perr:1;
+		uint64_t p3_rtout:1;
+		uint64_t p2_rtout:1;
+		uint64_t p1_rtout:1;
+		uint64_t p0_rtout:1;
+		uint64_t i3_overf:1;
+		uint64_t i2_overf:1;
+		uint64_t i1_overf:1;
+		uint64_t i0_overf:1;
+		uint64_t i3_rtout:1;
+		uint64_t i2_rtout:1;
+		uint64_t i1_rtout:1;
+		uint64_t i0_rtout:1;
+		uint64_t po3_2sml:1;
+		uint64_t po2_2sml:1;
+		uint64_t po1_2sml:1;
+		uint64_t po0_2sml:1;
+		uint64_t pci_rsl:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} s;
+	struct cvmx_npi_int_sum_cn30xx {
+		uint64_t reserved_62_63:2;
+		uint64_t q1_a_f:1;
+		uint64_t q1_s_e:1;
+		uint64_t pdf_p_f:1;
+		uint64_t pdf_p_e:1;
+		uint64_t pcf_p_f:1;
+		uint64_t pcf_p_e:1;
+		uint64_t rdx_s_e:1;
+		uint64_t rwx_s_e:1;
+		uint64_t pnc_a_f:1;
+		uint64_t pnc_s_e:1;
+		uint64_t com_a_f:1;
+		uint64_t com_s_e:1;
+		uint64_t q3_a_f:1;
+		uint64_t q3_s_e:1;
+		uint64_t q2_a_f:1;
+		uint64_t q2_s_e:1;
+		uint64_t pcr_a_f:1;
+		uint64_t pcr_s_e:1;
+		uint64_t fcr_a_f:1;
+		uint64_t fcr_s_e:1;
+		uint64_t iobdma:1;
+		uint64_t p_dperr:1;
+		uint64_t win_rto:1;
+		uint64_t reserved_36_38:3;
+		uint64_t i0_pperr:1;
+		uint64_t reserved_32_34:3;
+		uint64_t p0_ptout:1;
+		uint64_t reserved_28_30:3;
+		uint64_t p0_pperr:1;
+		uint64_t reserved_24_26:3;
+		uint64_t g0_rtout:1;
+		uint64_t reserved_20_22:3;
+		uint64_t p0_perr:1;
+		uint64_t reserved_16_18:3;
+		uint64_t p0_rtout:1;
+		uint64_t reserved_12_14:3;
+		uint64_t i0_overf:1;
+		uint64_t reserved_8_10:3;
+		uint64_t i0_rtout:1;
+		uint64_t reserved_4_6:3;
+		uint64_t po0_2sml:1;
+		uint64_t pci_rsl:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn30xx;
+	struct cvmx_npi_int_sum_cn31xx {
+		uint64_t reserved_62_63:2;
+		uint64_t q1_a_f:1;
+		uint64_t q1_s_e:1;
+		uint64_t pdf_p_f:1;
+		uint64_t pdf_p_e:1;
+		uint64_t pcf_p_f:1;
+		uint64_t pcf_p_e:1;
+		uint64_t rdx_s_e:1;
+		uint64_t rwx_s_e:1;
+		uint64_t pnc_a_f:1;
+		uint64_t pnc_s_e:1;
+		uint64_t com_a_f:1;
+		uint64_t com_s_e:1;
+		uint64_t q3_a_f:1;
+		uint64_t q3_s_e:1;
+		uint64_t q2_a_f:1;
+		uint64_t q2_s_e:1;
+		uint64_t pcr_a_f:1;
+		uint64_t pcr_s_e:1;
+		uint64_t fcr_a_f:1;
+		uint64_t fcr_s_e:1;
+		uint64_t iobdma:1;
+		uint64_t p_dperr:1;
+		uint64_t win_rto:1;
+		uint64_t reserved_37_38:2;
+		uint64_t i1_pperr:1;
+		uint64_t i0_pperr:1;
+		uint64_t reserved_33_34:2;
+		uint64_t p1_ptout:1;
+		uint64_t p0_ptout:1;
+		uint64_t reserved_29_30:2;
+		uint64_t p1_pperr:1;
+		uint64_t p0_pperr:1;
+		uint64_t reserved_25_26:2;
+		uint64_t g1_rtout:1;
+		uint64_t g0_rtout:1;
+		uint64_t reserved_21_22:2;
+		uint64_t p1_perr:1;
+		uint64_t p0_perr:1;
+		uint64_t reserved_17_18:2;
+		uint64_t p1_rtout:1;
+		uint64_t p0_rtout:1;
+		uint64_t reserved_13_14:2;
+		uint64_t i1_overf:1;
+		uint64_t i0_overf:1;
+		uint64_t reserved_9_10:2;
+		uint64_t i1_rtout:1;
+		uint64_t i0_rtout:1;
+		uint64_t reserved_5_6:2;
+		uint64_t po1_2sml:1;
+		uint64_t po0_2sml:1;
+		uint64_t pci_rsl:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn31xx;
+	struct cvmx_npi_int_sum_s cn38xx;
+	struct cvmx_npi_int_sum_cn38xxp2 {
+		uint64_t reserved_42_63:22;
+		uint64_t iobdma:1;
+		uint64_t p_dperr:1;
+		uint64_t win_rto:1;
+		uint64_t i3_pperr:1;
+		uint64_t i2_pperr:1;
+		uint64_t i1_pperr:1;
+		uint64_t i0_pperr:1;
+		uint64_t p3_ptout:1;
+		uint64_t p2_ptout:1;
+		uint64_t p1_ptout:1;
+		uint64_t p0_ptout:1;
+		uint64_t p3_pperr:1;
+		uint64_t p2_pperr:1;
+		uint64_t p1_pperr:1;
+		uint64_t p0_pperr:1;
+		uint64_t g3_rtout:1;
+		uint64_t g2_rtout:1;
+		uint64_t g1_rtout:1;
+		uint64_t g0_rtout:1;
+		uint64_t p3_perr:1;
+		uint64_t p2_perr:1;
+		uint64_t p1_perr:1;
+		uint64_t p0_perr:1;
+		uint64_t p3_rtout:1;
+		uint64_t p2_rtout:1;
+		uint64_t p1_rtout:1;
+		uint64_t p0_rtout:1;
+		uint64_t i3_overf:1;
+		uint64_t i2_overf:1;
+		uint64_t i1_overf:1;
+		uint64_t i0_overf:1;
+		uint64_t i3_rtout:1;
+		uint64_t i2_rtout:1;
+		uint64_t i1_rtout:1;
+		uint64_t i0_rtout:1;
+		uint64_t po3_2sml:1;
+		uint64_t po2_2sml:1;
+		uint64_t po1_2sml:1;
+		uint64_t po0_2sml:1;
+		uint64_t pci_rsl:1;
+		uint64_t rml_wto:1;
+		uint64_t rml_rto:1;
+	} cn38xxp2;
+	struct cvmx_npi_int_sum_cn31xx cn50xx;
+	struct cvmx_npi_int_sum_s cn58xx;
+	struct cvmx_npi_int_sum_s cn58xxp1;
+};
+
+union cvmx_npi_lowp_dbell {
+	uint64_t u64;
+	struct cvmx_npi_lowp_dbell_s {
+		uint64_t reserved_16_63:48;
+		uint64_t dbell:16;
+	} s;
+	struct cvmx_npi_lowp_dbell_s cn30xx;
+	struct cvmx_npi_lowp_dbell_s cn31xx;
+	struct cvmx_npi_lowp_dbell_s cn38xx;
+	struct cvmx_npi_lowp_dbell_s cn38xxp2;
+	struct cvmx_npi_lowp_dbell_s cn50xx;
+	struct cvmx_npi_lowp_dbell_s cn58xx;
+	struct cvmx_npi_lowp_dbell_s cn58xxp1;
+};
+
+union cvmx_npi_lowp_ibuff_saddr {
+	uint64_t u64;
+	struct cvmx_npi_lowp_ibuff_saddr_s {
+		uint64_t reserved_36_63:28;
+		uint64_t saddr:36;
+	} s;
+	struct cvmx_npi_lowp_ibuff_saddr_s cn30xx;
+	struct cvmx_npi_lowp_ibuff_saddr_s cn31xx;
+	struct cvmx_npi_lowp_ibuff_saddr_s cn38xx;
+	struct cvmx_npi_lowp_ibuff_saddr_s cn38xxp2;
+	struct cvmx_npi_lowp_ibuff_saddr_s cn50xx;
+	struct cvmx_npi_lowp_ibuff_saddr_s cn58xx;
+	struct cvmx_npi_lowp_ibuff_saddr_s cn58xxp1;
+};
+
+union cvmx_npi_mem_access_subidx {
+	uint64_t u64;
+	struct cvmx_npi_mem_access_subidx_s {
+		uint64_t reserved_38_63:26;
+		uint64_t shortl:1;
+		uint64_t nmerge:1;
+		uint64_t esr:2;
+		uint64_t esw:2;
+		uint64_t nsr:1;
+		uint64_t nsw:1;
+		uint64_t ror:1;
+		uint64_t row:1;
+		uint64_t ba:28;
+	} s;
+	struct cvmx_npi_mem_access_subidx_s cn30xx;
+	struct cvmx_npi_mem_access_subidx_cn31xx {
+		uint64_t reserved_36_63:28;
+		uint64_t esr:2;
+		uint64_t esw:2;
+		uint64_t nsr:1;
+		uint64_t nsw:1;
+		uint64_t ror:1;
+		uint64_t row:1;
+		uint64_t ba:28;
+	} cn31xx;
+	struct cvmx_npi_mem_access_subidx_s cn38xx;
+	struct cvmx_npi_mem_access_subidx_cn31xx cn38xxp2;
+	struct cvmx_npi_mem_access_subidx_s cn50xx;
+	struct cvmx_npi_mem_access_subidx_s cn58xx;
+	struct cvmx_npi_mem_access_subidx_s cn58xxp1;
+};
+
+union cvmx_npi_msi_rcv {
+	uint64_t u64;
+	struct cvmx_npi_msi_rcv_s {
+		uint64_t int_vec:64;
+	} s;
+	struct cvmx_npi_msi_rcv_s cn30xx;
+	struct cvmx_npi_msi_rcv_s cn31xx;
+	struct cvmx_npi_msi_rcv_s cn38xx;
+	struct cvmx_npi_msi_rcv_s cn38xxp2;
+	struct cvmx_npi_msi_rcv_s cn50xx;
+	struct cvmx_npi_msi_rcv_s cn58xx;
+	struct cvmx_npi_msi_rcv_s cn58xxp1;
+};
+
+union cvmx_npi_num_desc_outputx {
+	uint64_t u64;
+	struct cvmx_npi_num_desc_outputx_s {
+		uint64_t reserved_32_63:32;
+		uint64_t size:32;
+	} s;
+	struct cvmx_npi_num_desc_outputx_s cn30xx;
+	struct cvmx_npi_num_desc_outputx_s cn31xx;
+	struct cvmx_npi_num_desc_outputx_s cn38xx;
+	struct cvmx_npi_num_desc_outputx_s cn38xxp2;
+	struct cvmx_npi_num_desc_outputx_s cn50xx;
+	struct cvmx_npi_num_desc_outputx_s cn58xx;
+	struct cvmx_npi_num_desc_outputx_s cn58xxp1;
+};
+
+union cvmx_npi_output_control {
+	uint64_t u64;
+	struct cvmx_npi_output_control_s {
+		uint64_t reserved_49_63:15;
+		uint64_t pkt_rr:1;
+		uint64_t p3_bmode:1;
+		uint64_t p2_bmode:1;
+		uint64_t p1_bmode:1;
+		uint64_t p0_bmode:1;
+		uint64_t o3_es:2;
+		uint64_t o3_ns:1;
+		uint64_t o3_ro:1;
+		uint64_t o2_es:2;
+		uint64_t o2_ns:1;
+		uint64_t o2_ro:1;
+		uint64_t o1_es:2;
+		uint64_t o1_ns:1;
+		uint64_t o1_ro:1;
+		uint64_t o0_es:2;
+		uint64_t o0_ns:1;
+		uint64_t o0_ro:1;
+		uint64_t o3_csrm:1;
+		uint64_t o2_csrm:1;
+		uint64_t o1_csrm:1;
+		uint64_t o0_csrm:1;
+		uint64_t reserved_20_23:4;
+		uint64_t iptr_o3:1;
+		uint64_t iptr_o2:1;
+		uint64_t iptr_o1:1;
+		uint64_t iptr_o0:1;
+		uint64_t esr_sl3:2;
+		uint64_t nsr_sl3:1;
+		uint64_t ror_sl3:1;
+		uint64_t esr_sl2:2;
+		uint64_t nsr_sl2:1;
+		uint64_t ror_sl2:1;
+		uint64_t esr_sl1:2;
+		uint64_t nsr_sl1:1;
+		uint64_t ror_sl1:1;
+		uint64_t esr_sl0:2;
+		uint64_t nsr_sl0:1;
+		uint64_t ror_sl0:1;
+	} s;
+	struct cvmx_npi_output_control_cn30xx {
+		uint64_t reserved_45_63:19;
+		uint64_t p0_bmode:1;
+		uint64_t reserved_32_43:12;
+		uint64_t o0_es:2;
+		uint64_t o0_ns:1;
+		uint64_t o0_ro:1;
+		uint64_t reserved_25_27:3;
+		uint64_t o0_csrm:1;
+		uint64_t reserved_17_23:7;
+		uint64_t iptr_o0:1;
+		uint64_t reserved_4_15:12;
+		uint64_t esr_sl0:2;
+		uint64_t nsr_sl0:1;
+		uint64_t ror_sl0:1;
+	} cn30xx;
+	struct cvmx_npi_output_control_cn31xx {
+		uint64_t reserved_46_63:18;
+		uint64_t p1_bmode:1;
+		uint64_t p0_bmode:1;
+		uint64_t reserved_36_43:8;
+		uint64_t o1_es:2;
+		uint64_t o1_ns:1;
+		uint64_t o1_ro:1;
+		uint64_t o0_es:2;
+		uint64_t o0_ns:1;
+		uint64_t o0_ro:1;
+		uint64_t reserved_26_27:2;
+		uint64_t o1_csrm:1;
+		uint64_t o0_csrm:1;
+		uint64_t reserved_18_23:6;
+		uint64_t iptr_o1:1;
+		uint64_t iptr_o0:1;
+		uint64_t reserved_8_15:8;
+		uint64_t esr_sl1:2;
+		uint64_t nsr_sl1:1;
+		uint64_t ror_sl1:1;
+		uint64_t esr_sl0:2;
+		uint64_t nsr_sl0:1;
+		uint64_t ror_sl0:1;
+	} cn31xx;
+	struct cvmx_npi_output_control_s cn38xx;
+	struct cvmx_npi_output_control_cn38xxp2 {
+		uint64_t reserved_48_63:16;
+		uint64_t p3_bmode:1;
+		uint64_t p2_bmode:1;
+		uint64_t p1_bmode:1;
+		uint64_t p0_bmode:1;
+		uint64_t o3_es:2;
+		uint64_t o3_ns:1;
+		uint64_t o3_ro:1;
+		uint64_t o2_es:2;
+		uint64_t o2_ns:1;
+		uint64_t o2_ro:1;
+		uint64_t o1_es:2;
+		uint64_t o1_ns:1;
+		uint64_t o1_ro:1;
+		uint64_t o0_es:2;
+		uint64_t o0_ns:1;
+		uint64_t o0_ro:1;
+		uint64_t o3_csrm:1;
+		uint64_t o2_csrm:1;
+		uint64_t o1_csrm:1;
+		uint64_t o0_csrm:1;
+		uint64_t reserved_20_23:4;
+		uint64_t iptr_o3:1;
+		uint64_t iptr_o2:1;
+		uint64_t iptr_o1:1;
+		uint64_t iptr_o0:1;
+		uint64_t esr_sl3:2;
+		uint64_t nsr_sl3:1;
+		uint64_t ror_sl3:1;
+		uint64_t esr_sl2:2;
+		uint64_t nsr_sl2:1;
+		uint64_t ror_sl2:1;
+		uint64_t esr_sl1:2;
+		uint64_t nsr_sl1:1;
+		uint64_t ror_sl1:1;
+		uint64_t esr_sl0:2;
+		uint64_t nsr_sl0:1;
+		uint64_t ror_sl0:1;
+	} cn38xxp2;
+	struct cvmx_npi_output_control_cn50xx {
+		uint64_t reserved_49_63:15;
+		uint64_t pkt_rr:1;
+		uint64_t reserved_46_47:2;
+		uint64_t p1_bmode:1;
+		uint64_t p0_bmode:1;
+		uint64_t reserved_36_43:8;
+		uint64_t o1_es:2;
+		uint64_t o1_ns:1;
+		uint64_t o1_ro:1;
+		uint64_t o0_es:2;
+		uint64_t o0_ns:1;
+		uint64_t o0_ro:1;
+		uint64_t reserved_26_27:2;
+		uint64_t o1_csrm:1;
+		uint64_t o0_csrm:1;
+		uint64_t reserved_18_23:6;
+		uint64_t iptr_o1:1;
+		uint64_t iptr_o0:1;
+		uint64_t reserved_8_15:8;
+		uint64_t esr_sl1:2;
+		uint64_t nsr_sl1:1;
+		uint64_t ror_sl1:1;
+		uint64_t esr_sl0:2;
+		uint64_t nsr_sl0:1;
+		uint64_t ror_sl0:1;
+	} cn50xx;
+	struct cvmx_npi_output_control_s cn58xx;
+	struct cvmx_npi_output_control_s cn58xxp1;
+};
+
+union cvmx_npi_px_dbpair_addr {
+	uint64_t u64;
+	struct cvmx_npi_px_dbpair_addr_s {
+		uint64_t reserved_63_63:1;
+		uint64_t state:2;
+		uint64_t naddr:61;
+	} s;
+	struct cvmx_npi_px_dbpair_addr_s cn30xx;
+	struct cvmx_npi_px_dbpair_addr_s cn31xx;
+	struct cvmx_npi_px_dbpair_addr_s cn38xx;
+	struct cvmx_npi_px_dbpair_addr_s cn38xxp2;
+	struct cvmx_npi_px_dbpair_addr_s cn50xx;
+	struct cvmx_npi_px_dbpair_addr_s cn58xx;
+	struct cvmx_npi_px_dbpair_addr_s cn58xxp1;
+};
+
+union cvmx_npi_px_instr_addr {
+	uint64_t u64;
+	struct cvmx_npi_px_instr_addr_s {
+		uint64_t state:3;
+		uint64_t naddr:61;
+	} s;
+	struct cvmx_npi_px_instr_addr_s cn30xx;
+	struct cvmx_npi_px_instr_addr_s cn31xx;
+	struct cvmx_npi_px_instr_addr_s cn38xx;
+	struct cvmx_npi_px_instr_addr_s cn38xxp2;
+	struct cvmx_npi_px_instr_addr_s cn50xx;
+	struct cvmx_npi_px_instr_addr_s cn58xx;
+	struct cvmx_npi_px_instr_addr_s cn58xxp1;
+};
+
+union cvmx_npi_px_instr_cnts {
+	uint64_t u64;
+	struct cvmx_npi_px_instr_cnts_s {
+		uint64_t reserved_38_63:26;
+		uint64_t fcnt:6;
+		uint64_t avail:32;
+	} s;
+	struct cvmx_npi_px_instr_cnts_s cn30xx;
+	struct cvmx_npi_px_instr_cnts_s cn31xx;
+	struct cvmx_npi_px_instr_cnts_s cn38xx;
+	struct cvmx_npi_px_instr_cnts_s cn38xxp2;
+	struct cvmx_npi_px_instr_cnts_s cn50xx;
+	struct cvmx_npi_px_instr_cnts_s cn58xx;
+	struct cvmx_npi_px_instr_cnts_s cn58xxp1;
+};
+
+union cvmx_npi_px_pair_cnts {
+	uint64_t u64;
+	struct cvmx_npi_px_pair_cnts_s {
+		uint64_t reserved_37_63:27;
+		uint64_t fcnt:5;
+		uint64_t avail:32;
+	} s;
+	struct cvmx_npi_px_pair_cnts_s cn30xx;
+	struct cvmx_npi_px_pair_cnts_s cn31xx;
+	struct cvmx_npi_px_pair_cnts_s cn38xx;
+	struct cvmx_npi_px_pair_cnts_s cn38xxp2;
+	struct cvmx_npi_px_pair_cnts_s cn50xx;
+	struct cvmx_npi_px_pair_cnts_s cn58xx;
+	struct cvmx_npi_px_pair_cnts_s cn58xxp1;
+};
+
+union cvmx_npi_pci_burst_size {
+	uint64_t u64;
+	struct cvmx_npi_pci_burst_size_s {
+		uint64_t reserved_14_63:50;
+		uint64_t wr_brst:7;
+		uint64_t rd_brst:7;
+	} s;
+	struct cvmx_npi_pci_burst_size_s cn30xx;
+	struct cvmx_npi_pci_burst_size_s cn31xx;
+	struct cvmx_npi_pci_burst_size_s cn38xx;
+	struct cvmx_npi_pci_burst_size_s cn38xxp2;
+	struct cvmx_npi_pci_burst_size_s cn50xx;
+	struct cvmx_npi_pci_burst_size_s cn58xx;
+	struct cvmx_npi_pci_burst_size_s cn58xxp1;
+};
+
+union cvmx_npi_pci_int_arb_cfg {
+	uint64_t u64;
+	struct cvmx_npi_pci_int_arb_cfg_s {
+		uint64_t reserved_13_63:51;
+		uint64_t hostmode:1;
+		uint64_t pci_ovr:4;
+		uint64_t reserved_5_7:3;
+		uint64_t en:1;
+		uint64_t park_mod:1;
+		uint64_t park_dev:3;
+	} s;
+	struct cvmx_npi_pci_int_arb_cfg_cn30xx {
+		uint64_t reserved_5_63:59;
+		uint64_t en:1;
+		uint64_t park_mod:1;
+		uint64_t park_dev:3;
+	} cn30xx;
+	struct cvmx_npi_pci_int_arb_cfg_cn30xx cn31xx;
+	struct cvmx_npi_pci_int_arb_cfg_cn30xx cn38xx;
+	struct cvmx_npi_pci_int_arb_cfg_cn30xx cn38xxp2;
+	struct cvmx_npi_pci_int_arb_cfg_s cn50xx;
+	struct cvmx_npi_pci_int_arb_cfg_s cn58xx;
+	struct cvmx_npi_pci_int_arb_cfg_s cn58xxp1;
+};
+
+union cvmx_npi_pci_read_cmd {
+	uint64_t u64;
+	struct cvmx_npi_pci_read_cmd_s {
+		uint64_t reserved_11_63:53;
+		uint64_t cmd_size:11;
+	} s;
+	struct cvmx_npi_pci_read_cmd_s cn30xx;
+	struct cvmx_npi_pci_read_cmd_s cn31xx;
+	struct cvmx_npi_pci_read_cmd_s cn38xx;
+	struct cvmx_npi_pci_read_cmd_s cn38xxp2;
+	struct cvmx_npi_pci_read_cmd_s cn50xx;
+	struct cvmx_npi_pci_read_cmd_s cn58xx;
+	struct cvmx_npi_pci_read_cmd_s cn58xxp1;
+};
+
+union cvmx_npi_port32_instr_hdr {
+	uint64_t u64;
+	struct cvmx_npi_port32_instr_hdr_s {
+		uint64_t reserved_44_63:20;
+		uint64_t pbp:1;
+		uint64_t rsv_f:5;
+		uint64_t rparmode:2;
+		uint64_t rsv_e:1;
+		uint64_t rskp_len:7;
+		uint64_t rsv_d:6;
+		uint64_t use_ihdr:1;
+		uint64_t rsv_c:5;
+		uint64_t par_mode:2;
+		uint64_t rsv_b:1;
+		uint64_t skp_len:7;
+		uint64_t rsv_a:6;
+	} s;
+	struct cvmx_npi_port32_instr_hdr_s cn30xx;
+	struct cvmx_npi_port32_instr_hdr_s cn31xx;
+	struct cvmx_npi_port32_instr_hdr_s cn38xx;
+	struct cvmx_npi_port32_instr_hdr_s cn38xxp2;
+	struct cvmx_npi_port32_instr_hdr_s cn50xx;
+	struct cvmx_npi_port32_instr_hdr_s cn58xx;
+	struct cvmx_npi_port32_instr_hdr_s cn58xxp1;
+};
+
+union cvmx_npi_port33_instr_hdr {
+	uint64_t u64;
+	struct cvmx_npi_port33_instr_hdr_s {
+		uint64_t reserved_44_63:20;
+		uint64_t pbp:1;
+		uint64_t rsv_f:5;
+		uint64_t rparmode:2;
+		uint64_t rsv_e:1;
+		uint64_t rskp_len:7;
+		uint64_t rsv_d:6;
+		uint64_t use_ihdr:1;
+		uint64_t rsv_c:5;
+		uint64_t par_mode:2;
+		uint64_t rsv_b:1;
+		uint64_t skp_len:7;
+		uint64_t rsv_a:6;
+	} s;
+	struct cvmx_npi_port33_instr_hdr_s cn31xx;
+	struct cvmx_npi_port33_instr_hdr_s cn38xx;
+	struct cvmx_npi_port33_instr_hdr_s cn38xxp2;
+	struct cvmx_npi_port33_instr_hdr_s cn50xx;
+	struct cvmx_npi_port33_instr_hdr_s cn58xx;
+	struct cvmx_npi_port33_instr_hdr_s cn58xxp1;
+};
+
+union cvmx_npi_port34_instr_hdr {
+	uint64_t u64;
+	struct cvmx_npi_port34_instr_hdr_s {
+		uint64_t reserved_44_63:20;
+		uint64_t pbp:1;
+		uint64_t rsv_f:5;
+		uint64_t rparmode:2;
+		uint64_t rsv_e:1;
+		uint64_t rskp_len:7;
+		uint64_t rsv_d:6;
+		uint64_t use_ihdr:1;
+		uint64_t rsv_c:5;
+		uint64_t par_mode:2;
+		uint64_t rsv_b:1;
+		uint64_t skp_len:7;
+		uint64_t rsv_a:6;
+	} s;
+	struct cvmx_npi_port34_instr_hdr_s cn38xx;
+	struct cvmx_npi_port34_instr_hdr_s cn38xxp2;
+	struct cvmx_npi_port34_instr_hdr_s cn58xx;
+	struct cvmx_npi_port34_instr_hdr_s cn58xxp1;
+};
+
+union cvmx_npi_port35_instr_hdr {
+	uint64_t u64;
+	struct cvmx_npi_port35_instr_hdr_s {
+		uint64_t reserved_44_63:20;
+		uint64_t pbp:1;
+		uint64_t rsv_f:5;
+		uint64_t rparmode:2;
+		uint64_t rsv_e:1;
+		uint64_t rskp_len:7;
+		uint64_t rsv_d:6;
+		uint64_t use_ihdr:1;
+		uint64_t rsv_c:5;
+		uint64_t par_mode:2;
+		uint64_t rsv_b:1;
+		uint64_t skp_len:7;
+		uint64_t rsv_a:6;
+	} s;
+	struct cvmx_npi_port35_instr_hdr_s cn38xx;
+	struct cvmx_npi_port35_instr_hdr_s cn38xxp2;
+	struct cvmx_npi_port35_instr_hdr_s cn58xx;
+	struct cvmx_npi_port35_instr_hdr_s cn58xxp1;
+};
+
+union cvmx_npi_port_bp_control {
+	uint64_t u64;
+	struct cvmx_npi_port_bp_control_s {
+		uint64_t reserved_8_63:56;
+		uint64_t bp_on:4;
+		uint64_t enb:4;
+	} s;
+	struct cvmx_npi_port_bp_control_s cn30xx;
+	struct cvmx_npi_port_bp_control_s cn31xx;
+	struct cvmx_npi_port_bp_control_s cn38xx;
+	struct cvmx_npi_port_bp_control_s cn38xxp2;
+	struct cvmx_npi_port_bp_control_s cn50xx;
+	struct cvmx_npi_port_bp_control_s cn58xx;
+	struct cvmx_npi_port_bp_control_s cn58xxp1;
+};
+
+union cvmx_npi_rsl_int_blocks {
+	uint64_t u64;
+	struct cvmx_npi_rsl_int_blocks_s {
+		uint64_t reserved_32_63:32;
+		uint64_t rint_31:1;
+		uint64_t iob:1;
+		uint64_t reserved_28_29:2;
+		uint64_t rint_27:1;
+		uint64_t rint_26:1;
+		uint64_t rint_25:1;
+		uint64_t rint_24:1;
+		uint64_t asx1:1;
+		uint64_t asx0:1;
+		uint64_t rint_21:1;
+		uint64_t pip:1;
+		uint64_t spx1:1;
+		uint64_t spx0:1;
+		uint64_t lmc:1;
+		uint64_t l2c:1;
+		uint64_t rint_15:1;
+		uint64_t reserved_13_14:2;
+		uint64_t pow:1;
+		uint64_t tim:1;
+		uint64_t pko:1;
+		uint64_t ipd:1;
+		uint64_t rint_8:1;
+		uint64_t zip:1;
+		uint64_t dfa:1;
+		uint64_t fpa:1;
+		uint64_t key:1;
+		uint64_t npi:1;
+		uint64_t gmx1:1;
+		uint64_t gmx0:1;
+		uint64_t mio:1;
+	} s;
+	struct cvmx_npi_rsl_int_blocks_cn30xx {
+		uint64_t reserved_32_63:32;
+		uint64_t rint_31:1;
+		uint64_t iob:1;
+		uint64_t rint_29:1;
+		uint64_t rint_28:1;
+		uint64_t rint_27:1;
+		uint64_t rint_26:1;
+		uint64_t rint_25:1;
+		uint64_t rint_24:1;
+		uint64_t asx1:1;
+		uint64_t asx0:1;
+		uint64_t rint_21:1;
+		uint64_t pip:1;
+		uint64_t spx1:1;
+		uint64_t spx0:1;
+		uint64_t lmc:1;
+		uint64_t l2c:1;
+		uint64_t rint_15:1;
+		uint64_t rint_14:1;
+		uint64_t usb:1;
+		uint64_t pow:1;
+		uint64_t tim:1;
+		uint64_t pko:1;
+		uint64_t ipd:1;
+		uint64_t rint_8:1;
+		uint64_t zip:1;
+		uint64_t dfa:1;
+		uint64_t fpa:1;
+		uint64_t key:1;
+		uint64_t npi:1;
+		uint64_t gmx1:1;
+		uint64_t gmx0:1;
+		uint64_t mio:1;
+	} cn30xx;
+	struct cvmx_npi_rsl_int_blocks_cn30xx cn31xx;
+	struct cvmx_npi_rsl_int_blocks_cn38xx {
+		uint64_t reserved_32_63:32;
+		uint64_t rint_31:1;
+		uint64_t iob:1;
+		uint64_t rint_29:1;
+		uint64_t rint_28:1;
+		uint64_t rint_27:1;
+		uint64_t rint_26:1;
+		uint64_t rint_25:1;
+		uint64_t rint_24:1;
+		uint64_t asx1:1;
+		uint64_t asx0:1;
+		uint64_t rint_21:1;
+		uint64_t pip:1;
+		uint64_t spx1:1;
+		uint64_t spx0:1;
+		uint64_t lmc:1;
+		uint64_t l2c:1;
+		uint64_t rint_15:1;
+		uint64_t rint_14:1;
+		uint64_t rint_13:1;
+		uint64_t pow:1;
+		uint64_t tim:1;
+		uint64_t pko:1;
+		uint64_t ipd:1;
+		uint64_t rint_8:1;
+		uint64_t zip:1;
+		uint64_t dfa:1;
+		uint64_t fpa:1;
+		uint64_t key:1;
+		uint64_t npi:1;
+		uint64_t gmx1:1;
+		uint64_t gmx0:1;
+		uint64_t mio:1;
+	} cn38xx;
+	struct cvmx_npi_rsl_int_blocks_cn38xx cn38xxp2;
+	struct cvmx_npi_rsl_int_blocks_cn50xx {
+		uint64_t reserved_31_63:33;
+		uint64_t iob:1;
+		uint64_t lmc1:1;
+		uint64_t agl:1;
+		uint64_t reserved_24_27:4;
+		uint64_t asx1:1;
+		uint64_t asx0:1;
+		uint64_t reserved_21_21:1;
+		uint64_t pip:1;
+		uint64_t spx1:1;
+		uint64_t spx0:1;
+		uint64_t lmc:1;
+		uint64_t l2c:1;
+		uint64_t reserved_15_15:1;
+		uint64_t rad:1;
+		uint64_t usb:1;
+		uint64_t pow:1;
+		uint64_t tim:1;
+		uint64_t pko:1;
+		uint64_t ipd:1;
+		uint64_t reserved_8_8:1;
+		uint64_t zip:1;
+		uint64_t dfa:1;
+		uint64_t fpa:1;
+		uint64_t key:1;
+		uint64_t npi:1;
+		uint64_t gmx1:1;
+		uint64_t gmx0:1;
+		uint64_t mio:1;
+	} cn50xx;
+	struct cvmx_npi_rsl_int_blocks_cn38xx cn58xx;
+	struct cvmx_npi_rsl_int_blocks_cn38xx cn58xxp1;
+};
+
+union cvmx_npi_size_inputx {
+	uint64_t u64;
+	struct cvmx_npi_size_inputx_s {
+		uint64_t reserved_32_63:32;
+		uint64_t size:32;
+	} s;
+	struct cvmx_npi_size_inputx_s cn30xx;
+	struct cvmx_npi_size_inputx_s cn31xx;
+	struct cvmx_npi_size_inputx_s cn38xx;
+	struct cvmx_npi_size_inputx_s cn38xxp2;
+	struct cvmx_npi_size_inputx_s cn50xx;
+	struct cvmx_npi_size_inputx_s cn58xx;
+	struct cvmx_npi_size_inputx_s cn58xxp1;
+};
+
+union cvmx_npi_win_read_to {
+	uint64_t u64;
+	struct cvmx_npi_win_read_to_s {
+		uint64_t reserved_32_63:32;
+		uint64_t time:32;
+	} s;
+	struct cvmx_npi_win_read_to_s cn30xx;
+	struct cvmx_npi_win_read_to_s cn31xx;
+	struct cvmx_npi_win_read_to_s cn38xx;
+	struct cvmx_npi_win_read_to_s cn38xxp2;
+	struct cvmx_npi_win_read_to_s cn50xx;
+	struct cvmx_npi_win_read_to_s cn58xx;
+	struct cvmx_npi_win_read_to_s cn58xxp1;
+};
+
+#endif
diff --git a/arch/mips/include/asm/octeon/cvmx-pci-defs.h b/arch/mips/include/asm/octeon/cvmx-pci-defs.h
new file mode 100644
index 0000000..90f8d65
--- /dev/null
+++ b/arch/mips/include/asm/octeon/cvmx-pci-defs.h
@@ -0,0 +1,1645 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_PCI_DEFS_H__
+#define __CVMX_PCI_DEFS_H__
+
+#define CVMX_PCI_BAR1_INDEXX(offset) \
+	 (0x0000000000000100ull + (((offset) & 31) * 4))
+#define CVMX_PCI_BIST_REG \
+	 (0x00000000000001C0ull)
+#define CVMX_PCI_CFG00 \
+	 (0x0000000000000000ull)
+#define CVMX_PCI_CFG01 \
+	 (0x0000000000000004ull)
+#define CVMX_PCI_CFG02 \
+	 (0x0000000000000008ull)
+#define CVMX_PCI_CFG03 \
+	 (0x000000000000000Cull)
+#define CVMX_PCI_CFG04 \
+	 (0x0000000000000010ull)
+#define CVMX_PCI_CFG05 \
+	 (0x0000000000000014ull)
+#define CVMX_PCI_CFG06 \
+	 (0x0000000000000018ull)
+#define CVMX_PCI_CFG07 \
+	 (0x000000000000001Cull)
+#define CVMX_PCI_CFG08 \
+	 (0x0000000000000020ull)
+#define CVMX_PCI_CFG09 \
+	 (0x0000000000000024ull)
+#define CVMX_PCI_CFG10 \
+	 (0x0000000000000028ull)
+#define CVMX_PCI_CFG11 \
+	 (0x000000000000002Cull)
+#define CVMX_PCI_CFG12 \
+	 (0x0000000000000030ull)
+#define CVMX_PCI_CFG13 \
+	 (0x0000000000000034ull)
+#define CVMX_PCI_CFG15 \
+	 (0x000000000000003Cull)
+#define CVMX_PCI_CFG16 \
+	 (0x0000000000000040ull)
+#define CVMX_PCI_CFG17 \
+	 (0x0000000000000044ull)
+#define CVMX_PCI_CFG18 \
+	 (0x0000000000000048ull)
+#define CVMX_PCI_CFG19 \
+	 (0x000000000000004Cull)
+#define CVMX_PCI_CFG20 \
+	 (0x0000000000000050ull)
+#define CVMX_PCI_CFG21 \
+	 (0x0000000000000054ull)
+#define CVMX_PCI_CFG22 \
+	 (0x0000000000000058ull)
+#define CVMX_PCI_CFG56 \
+	 (0x00000000000000E0ull)
+#define CVMX_PCI_CFG57 \
+	 (0x00000000000000E4ull)
+#define CVMX_PCI_CFG58 \
+	 (0x00000000000000E8ull)
+#define CVMX_PCI_CFG59 \
+	 (0x00000000000000ECull)
+#define CVMX_PCI_CFG60 \
+	 (0x00000000000000F0ull)
+#define CVMX_PCI_CFG61 \
+	 (0x00000000000000F4ull)
+#define CVMX_PCI_CFG62 \
+	 (0x00000000000000F8ull)
+#define CVMX_PCI_CFG63 \
+	 (0x00000000000000FCull)
+#define CVMX_PCI_CNT_REG \
+	 (0x00000000000001B8ull)
+#define CVMX_PCI_CTL_STATUS_2 \
+	 (0x000000000000018Cull)
+#define CVMX_PCI_DBELL_0 \
+	 (0x0000000000000080ull)
+#define CVMX_PCI_DBELL_1 \
+	 (0x0000000000000088ull)
+#define CVMX_PCI_DBELL_2 \
+	 (0x0000000000000090ull)
+#define CVMX_PCI_DBELL_3 \
+	 (0x0000000000000098ull)
+#define CVMX_PCI_DBELL_X(offset) \
+	 (0x0000000000000080ull + (((offset) & 3) * 8))
+#define CVMX_PCI_DMA_CNT0 \
+	 (0x00000000000000A0ull)
+#define CVMX_PCI_DMA_CNT1 \
+	 (0x00000000000000A8ull)
+#define CVMX_PCI_DMA_CNTX(offset) \
+	 (0x00000000000000A0ull + (((offset) & 1) * 8))
+#define CVMX_PCI_DMA_INT_LEV0 \
+	 (0x00000000000000A4ull)
+#define CVMX_PCI_DMA_INT_LEV1 \
+	 (0x00000000000000ACull)
+#define CVMX_PCI_DMA_INT_LEVX(offset) \
+	 (0x00000000000000A4ull + (((offset) & 1) * 8))
+#define CVMX_PCI_DMA_TIME0 \
+	 (0x00000000000000B0ull)
+#define CVMX_PCI_DMA_TIME1 \
+	 (0x00000000000000B4ull)
+#define CVMX_PCI_DMA_TIMEX(offset) \
+	 (0x00000000000000B0ull + (((offset) & 1) * 4))
+#define CVMX_PCI_INSTR_COUNT0 \
+	 (0x0000000000000084ull)
+#define CVMX_PCI_INSTR_COUNT1 \
+	 (0x000000000000008Cull)
+#define CVMX_PCI_INSTR_COUNT2 \
+	 (0x0000000000000094ull)
+#define CVMX_PCI_INSTR_COUNT3 \
+	 (0x000000000000009Cull)
+#define CVMX_PCI_INSTR_COUNTX(offset) \
+	 (0x0000000000000084ull + (((offset) & 3) * 8))
+#define CVMX_PCI_INT_ENB \
+	 (0x0000000000000038ull)
+#define CVMX_PCI_INT_ENB2 \
+	 (0x00000000000001A0ull)
+#define CVMX_PCI_INT_SUM \
+	 (0x0000000000000030ull)
+#define CVMX_PCI_INT_SUM2 \
+	 (0x0000000000000198ull)
+#define CVMX_PCI_MSI_RCV \
+	 (0x00000000000000F0ull)
+#define CVMX_PCI_PKTS_SENT0 \
+	 (0x0000000000000040ull)
+#define CVMX_PCI_PKTS_SENT1 \
+	 (0x0000000000000050ull)
+#define CVMX_PCI_PKTS_SENT2 \
+	 (0x0000000000000060ull)
+#define CVMX_PCI_PKTS_SENT3 \
+	 (0x0000000000000070ull)
+#define CVMX_PCI_PKTS_SENTX(offset) \
+	 (0x0000000000000040ull + (((offset) & 3) * 16))
+#define CVMX_PCI_PKTS_SENT_INT_LEV0 \
+	 (0x0000000000000048ull)
+#define CVMX_PCI_PKTS_SENT_INT_LEV1 \
+	 (0x0000000000000058ull)
+#define CVMX_PCI_PKTS_SENT_INT_LEV2 \
+	 (0x0000000000000068ull)
+#define CVMX_PCI_PKTS_SENT_INT_LEV3 \
+	 (0x0000000000000078ull)
+#define CVMX_PCI_PKTS_SENT_INT_LEVX(offset) \
+	 (0x0000000000000048ull + (((offset) & 3) * 16))
+#define CVMX_PCI_PKTS_SENT_TIME0 \
+	 (0x000000000000004Cull)
+#define CVMX_PCI_PKTS_SENT_TIME1 \
+	 (0x000000000000005Cull)
+#define CVMX_PCI_PKTS_SENT_TIME2 \
+	 (0x000000000000006Cull)
+#define CVMX_PCI_PKTS_SENT_TIME3 \
+	 (0x000000000000007Cull)
+#define CVMX_PCI_PKTS_SENT_TIMEX(offset) \
+	 (0x000000000000004Cull + (((offset) & 3) * 16))
+#define CVMX_PCI_PKT_CREDITS0 \
+	 (0x0000000000000044ull)
+#define CVMX_PCI_PKT_CREDITS1 \
+	 (0x0000000000000054ull)
+#define CVMX_PCI_PKT_CREDITS2 \
+	 (0x0000000000000064ull)
+#define CVMX_PCI_PKT_CREDITS3 \
+	 (0x0000000000000074ull)
+#define CVMX_PCI_PKT_CREDITSX(offset) \
+	 (0x0000000000000044ull + (((offset) & 3) * 16))
+#define CVMX_PCI_READ_CMD_6 \
+	 (0x0000000000000180ull)
+#define CVMX_PCI_READ_CMD_C \
+	 (0x0000000000000184ull)
+#define CVMX_PCI_READ_CMD_E \
+	 (0x0000000000000188ull)
+#define CVMX_PCI_READ_TIMEOUT \
+	 CVMX_ADD_IO_SEG(0x00011F00000000B0ull)
+#define CVMX_PCI_SCM_REG \
+	 (0x00000000000001A8ull)
+#define CVMX_PCI_TSR_REG \
+	 (0x00000000000001B0ull)
+#define CVMX_PCI_WIN_RD_ADDR \
+	 (0x0000000000000008ull)
+#define CVMX_PCI_WIN_RD_DATA \
+	 (0x0000000000000020ull)
+#define CVMX_PCI_WIN_WR_ADDR \
+	 (0x0000000000000000ull)
+#define CVMX_PCI_WIN_WR_DATA \
+	 (0x0000000000000010ull)
+#define CVMX_PCI_WIN_WR_MASK \
+	 (0x0000000000000018ull)
+
+union cvmx_pci_bar1_indexx {
+	uint32_t u32;
+	struct cvmx_pci_bar1_indexx_s {
+		uint32_t reserved_18_31:14;
+		uint32_t addr_idx:14;
+		uint32_t ca:1;
+		uint32_t end_swp:2;
+		uint32_t addr_v:1;
+	} s;
+	struct cvmx_pci_bar1_indexx_s cn30xx;
+	struct cvmx_pci_bar1_indexx_s cn31xx;
+	struct cvmx_pci_bar1_indexx_s cn38xx;
+	struct cvmx_pci_bar1_indexx_s cn38xxp2;
+	struct cvmx_pci_bar1_indexx_s cn50xx;
+	struct cvmx_pci_bar1_indexx_s cn58xx;
+	struct cvmx_pci_bar1_indexx_s cn58xxp1;
+};
+
+union cvmx_pci_bist_reg {
+	uint64_t u64;
+	struct cvmx_pci_bist_reg_s {
+		uint64_t reserved_10_63:54;
+		uint64_t rsp_bs:1;
+		uint64_t dma0_bs:1;
+		uint64_t cmd0_bs:1;
+		uint64_t cmd_bs:1;
+		uint64_t csr2p_bs:1;
+		uint64_t csrr_bs:1;
+		uint64_t rsp2p_bs:1;
+		uint64_t csr2n_bs:1;
+		uint64_t dat2n_bs:1;
+		uint64_t dbg2n_bs:1;
+	} s;
+	struct cvmx_pci_bist_reg_s cn50xx;
+};
+
+union cvmx_pci_cfg00 {
+	uint32_t u32;
+	struct cvmx_pci_cfg00_s {
+		uint32_t devid:16;
+		uint32_t vendid:16;
+	} s;
+	struct cvmx_pci_cfg00_s cn30xx;
+	struct cvmx_pci_cfg00_s cn31xx;
+	struct cvmx_pci_cfg00_s cn38xx;
+	struct cvmx_pci_cfg00_s cn38xxp2;
+	struct cvmx_pci_cfg00_s cn50xx;
+	struct cvmx_pci_cfg00_s cn58xx;
+	struct cvmx_pci_cfg00_s cn58xxp1;
+};
+
+union cvmx_pci_cfg01 {
+	uint32_t u32;
+	struct cvmx_pci_cfg01_s {
+		uint32_t dpe:1;
+		uint32_t sse:1;
+		uint32_t rma:1;
+		uint32_t rta:1;
+		uint32_t sta:1;
+		uint32_t devt:2;
+		uint32_t mdpe:1;
+		uint32_t fbb:1;
+		uint32_t reserved_22_22:1;
+		uint32_t m66:1;
+		uint32_t cle:1;
+		uint32_t i_stat:1;
+		uint32_t reserved_11_18:8;
+		uint32_t i_dis:1;
+		uint32_t fbbe:1;
+		uint32_t see:1;
+		uint32_t ads:1;
+		uint32_t pee:1;
+		uint32_t vps:1;
+		uint32_t mwice:1;
+		uint32_t scse:1;
+		uint32_t me:1;
+		uint32_t msae:1;
+		uint32_t isae:1;
+	} s;
+	struct cvmx_pci_cfg01_s cn30xx;
+	struct cvmx_pci_cfg01_s cn31xx;
+	struct cvmx_pci_cfg01_s cn38xx;
+	struct cvmx_pci_cfg01_s cn38xxp2;
+	struct cvmx_pci_cfg01_s cn50xx;
+	struct cvmx_pci_cfg01_s cn58xx;
+	struct cvmx_pci_cfg01_s cn58xxp1;
+};
+
+union cvmx_pci_cfg02 {
+	uint32_t u32;
+	struct cvmx_pci_cfg02_s {
+		uint32_t cc:24;
+		uint32_t rid:8;
+	} s;
+	struct cvmx_pci_cfg02_s cn30xx;
+	struct cvmx_pci_cfg02_s cn31xx;
+	struct cvmx_pci_cfg02_s cn38xx;
+	struct cvmx_pci_cfg02_s cn38xxp2;
+	struct cvmx_pci_cfg02_s cn50xx;
+	struct cvmx_pci_cfg02_s cn58xx;
+	struct cvmx_pci_cfg02_s cn58xxp1;
+};
+
+union cvmx_pci_cfg03 {
+	uint32_t u32;
+	struct cvmx_pci_cfg03_s {
+		uint32_t bcap:1;
+		uint32_t brb:1;
+		uint32_t reserved_28_29:2;
+		uint32_t bcod:4;
+		uint32_t ht:8;
+		uint32_t lt:8;
+		uint32_t cls:8;
+	} s;
+	struct cvmx_pci_cfg03_s cn30xx;
+	struct cvmx_pci_cfg03_s cn31xx;
+	struct cvmx_pci_cfg03_s cn38xx;
+	struct cvmx_pci_cfg03_s cn38xxp2;
+	struct cvmx_pci_cfg03_s cn50xx;
+	struct cvmx_pci_cfg03_s cn58xx;
+	struct cvmx_pci_cfg03_s cn58xxp1;
+};
+
+union cvmx_pci_cfg04 {
+	uint32_t u32;
+	struct cvmx_pci_cfg04_s {
+		uint32_t lbase:20;
+		uint32_t lbasez:8;
+		uint32_t pf:1;
+		uint32_t typ:2;
+		uint32_t mspc:1;
+	} s;
+	struct cvmx_pci_cfg04_s cn30xx;
+	struct cvmx_pci_cfg04_s cn31xx;
+	struct cvmx_pci_cfg04_s cn38xx;
+	struct cvmx_pci_cfg04_s cn38xxp2;
+	struct cvmx_pci_cfg04_s cn50xx;
+	struct cvmx_pci_cfg04_s cn58xx;
+	struct cvmx_pci_cfg04_s cn58xxp1;
+};
+
+union cvmx_pci_cfg05 {
+	uint32_t u32;
+	struct cvmx_pci_cfg05_s {
+		uint32_t hbase:32;
+	} s;
+	struct cvmx_pci_cfg05_s cn30xx;
+	struct cvmx_pci_cfg05_s cn31xx;
+	struct cvmx_pci_cfg05_s cn38xx;
+	struct cvmx_pci_cfg05_s cn38xxp2;
+	struct cvmx_pci_cfg05_s cn50xx;
+	struct cvmx_pci_cfg05_s cn58xx;
+	struct cvmx_pci_cfg05_s cn58xxp1;
+};
+
+union cvmx_pci_cfg06 {
+	uint32_t u32;
+	struct cvmx_pci_cfg06_s {
+		uint32_t lbase:5;
+		uint32_t lbasez:23;
+		uint32_t pf:1;
+		uint32_t typ:2;
+		uint32_t mspc:1;
+	} s;
+	struct cvmx_pci_cfg06_s cn30xx;
+	struct cvmx_pci_cfg06_s cn31xx;
+	struct cvmx_pci_cfg06_s cn38xx;
+	struct cvmx_pci_cfg06_s cn38xxp2;
+	struct cvmx_pci_cfg06_s cn50xx;
+	struct cvmx_pci_cfg06_s cn58xx;
+	struct cvmx_pci_cfg06_s cn58xxp1;
+};
+
+union cvmx_pci_cfg07 {
+	uint32_t u32;
+	struct cvmx_pci_cfg07_s {
+		uint32_t hbase:32;
+	} s;
+	struct cvmx_pci_cfg07_s cn30xx;
+	struct cvmx_pci_cfg07_s cn31xx;
+	struct cvmx_pci_cfg07_s cn38xx;
+	struct cvmx_pci_cfg07_s cn38xxp2;
+	struct cvmx_pci_cfg07_s cn50xx;
+	struct cvmx_pci_cfg07_s cn58xx;
+	struct cvmx_pci_cfg07_s cn58xxp1;
+};
+
+union cvmx_pci_cfg08 {
+	uint32_t u32;
+	struct cvmx_pci_cfg08_s {
+		uint32_t lbasez:28;
+		uint32_t pf:1;
+		uint32_t typ:2;
+		uint32_t mspc:1;
+	} s;
+	struct cvmx_pci_cfg08_s cn30xx;
+	struct cvmx_pci_cfg08_s cn31xx;
+	struct cvmx_pci_cfg08_s cn38xx;
+	struct cvmx_pci_cfg08_s cn38xxp2;
+	struct cvmx_pci_cfg08_s cn50xx;
+	struct cvmx_pci_cfg08_s cn58xx;
+	struct cvmx_pci_cfg08_s cn58xxp1;
+};
+
+union cvmx_pci_cfg09 {
+	uint32_t u32;
+	struct cvmx_pci_cfg09_s {
+		uint32_t hbase:25;
+		uint32_t hbasez:7;
+	} s;
+	struct cvmx_pci_cfg09_s cn30xx;
+	struct cvmx_pci_cfg09_s cn31xx;
+	struct cvmx_pci_cfg09_s cn38xx;
+	struct cvmx_pci_cfg09_s cn38xxp2;
+	struct cvmx_pci_cfg09_s cn50xx;
+	struct cvmx_pci_cfg09_s cn58xx;
+	struct cvmx_pci_cfg09_s cn58xxp1;
+};
+
+union cvmx_pci_cfg10 {
+	uint32_t u32;
+	struct cvmx_pci_cfg10_s {
+		uint32_t cisp:32;
+	} s;
+	struct cvmx_pci_cfg10_s cn30xx;
+	struct cvmx_pci_cfg10_s cn31xx;
+	struct cvmx_pci_cfg10_s cn38xx;
+	struct cvmx_pci_cfg10_s cn38xxp2;
+	struct cvmx_pci_cfg10_s cn50xx;
+	struct cvmx_pci_cfg10_s cn58xx;
+	struct cvmx_pci_cfg10_s cn58xxp1;
+};
+
+union cvmx_pci_cfg11 {
+	uint32_t u32;
+	struct cvmx_pci_cfg11_s {
+		uint32_t ssid:16;
+		uint32_t ssvid:16;
+	} s;
+	struct cvmx_pci_cfg11_s cn30xx;
+	struct cvmx_pci_cfg11_s cn31xx;
+	struct cvmx_pci_cfg11_s cn38xx;
+	struct cvmx_pci_cfg11_s cn38xxp2;
+	struct cvmx_pci_cfg11_s cn50xx;
+	struct cvmx_pci_cfg11_s cn58xx;
+	struct cvmx_pci_cfg11_s cn58xxp1;
+};
+
+union cvmx_pci_cfg12 {
+	uint32_t u32;
+	struct cvmx_pci_cfg12_s {
+		uint32_t erbar:16;
+		uint32_t erbarz:5;
+		uint32_t reserved_1_10:10;
+		uint32_t erbar_en:1;
+	} s;
+	struct cvmx_pci_cfg12_s cn30xx;
+	struct cvmx_pci_cfg12_s cn31xx;
+	struct cvmx_pci_cfg12_s cn38xx;
+	struct cvmx_pci_cfg12_s cn38xxp2;
+	struct cvmx_pci_cfg12_s cn50xx;
+	struct cvmx_pci_cfg12_s cn58xx;
+	struct cvmx_pci_cfg12_s cn58xxp1;
+};
+
+union cvmx_pci_cfg13 {
+	uint32_t u32;
+	struct cvmx_pci_cfg13_s {
+		uint32_t reserved_8_31:24;
+		uint32_t cp:8;
+	} s;
+	struct cvmx_pci_cfg13_s cn30xx;
+	struct cvmx_pci_cfg13_s cn31xx;
+	struct cvmx_pci_cfg13_s cn38xx;
+	struct cvmx_pci_cfg13_s cn38xxp2;
+	struct cvmx_pci_cfg13_s cn50xx;
+	struct cvmx_pci_cfg13_s cn58xx;
+	struct cvmx_pci_cfg13_s cn58xxp1;
+};
+
+union cvmx_pci_cfg15 {
+	uint32_t u32;
+	struct cvmx_pci_cfg15_s {
+		uint32_t ml:8;
+		uint32_t mg:8;
+		uint32_t inta:8;
+		uint32_t il:8;
+	} s;
+	struct cvmx_pci_cfg15_s cn30xx;
+	struct cvmx_pci_cfg15_s cn31xx;
+	struct cvmx_pci_cfg15_s cn38xx;
+	struct cvmx_pci_cfg15_s cn38xxp2;
+	struct cvmx_pci_cfg15_s cn50xx;
+	struct cvmx_pci_cfg15_s cn58xx;
+	struct cvmx_pci_cfg15_s cn58xxp1;
+};
+
+union cvmx_pci_cfg16 {
+	uint32_t u32;
+	struct cvmx_pci_cfg16_s {
+		uint32_t trdnpr:1;
+		uint32_t trdard:1;
+		uint32_t rdsati:1;
+		uint32_t trdrs:1;
+		uint32_t trtae:1;
+		uint32_t twsei:1;
+		uint32_t twsen:1;
+		uint32_t twtae:1;
+		uint32_t tmae:1;
+		uint32_t tslte:3;
+		uint32_t tilt:4;
+		uint32_t pbe:12;
+		uint32_t dppmr:1;
+		uint32_t reserved_2_2:1;
+		uint32_t tswc:1;
+		uint32_t mltd:1;
+	} s;
+	struct cvmx_pci_cfg16_s cn30xx;
+	struct cvmx_pci_cfg16_s cn31xx;
+	struct cvmx_pci_cfg16_s cn38xx;
+	struct cvmx_pci_cfg16_s cn38xxp2;
+	struct cvmx_pci_cfg16_s cn50xx;
+	struct cvmx_pci_cfg16_s cn58xx;
+	struct cvmx_pci_cfg16_s cn58xxp1;
+};
+
+union cvmx_pci_cfg17 {
+	uint32_t u32;
+	struct cvmx_pci_cfg17_s {
+		uint32_t tscme:32;
+	} s;
+	struct cvmx_pci_cfg17_s cn30xx;
+	struct cvmx_pci_cfg17_s cn31xx;
+	struct cvmx_pci_cfg17_s cn38xx;
+	struct cvmx_pci_cfg17_s cn38xxp2;
+	struct cvmx_pci_cfg17_s cn50xx;
+	struct cvmx_pci_cfg17_s cn58xx;
+	struct cvmx_pci_cfg17_s cn58xxp1;
+};
+
+union cvmx_pci_cfg18 {
+	uint32_t u32;
+	struct cvmx_pci_cfg18_s {
+		uint32_t tdsrps:32;
+	} s;
+	struct cvmx_pci_cfg18_s cn30xx;
+	struct cvmx_pci_cfg18_s cn31xx;
+	struct cvmx_pci_cfg18_s cn38xx;
+	struct cvmx_pci_cfg18_s cn38xxp2;
+	struct cvmx_pci_cfg18_s cn50xx;
+	struct cvmx_pci_cfg18_s cn58xx;
+	struct cvmx_pci_cfg18_s cn58xxp1;
+};
+
+union cvmx_pci_cfg19 {
+	uint32_t u32;
+	struct cvmx_pci_cfg19_s {
+		uint32_t mrbcm:1;
+		uint32_t mrbci:1;
+		uint32_t mdwe:1;
+		uint32_t mdre:1;
+		uint32_t mdrimc:1;
+		uint32_t mdrrmc:3;
+		uint32_t tmes:8;
+		uint32_t teci:1;
+		uint32_t tmei:1;
+		uint32_t tmse:1;
+		uint32_t tmdpes:1;
+		uint32_t tmapes:1;
+		uint32_t reserved_9_10:2;
+		uint32_t tibcd:1;
+		uint32_t tibde:1;
+		uint32_t reserved_6_6:1;
+		uint32_t tidomc:1;
+		uint32_t tdomc:5;
+	} s;
+	struct cvmx_pci_cfg19_s cn30xx;
+	struct cvmx_pci_cfg19_s cn31xx;
+	struct cvmx_pci_cfg19_s cn38xx;
+	struct cvmx_pci_cfg19_s cn38xxp2;
+	struct cvmx_pci_cfg19_s cn50xx;
+	struct cvmx_pci_cfg19_s cn58xx;
+	struct cvmx_pci_cfg19_s cn58xxp1;
+};
+
+union cvmx_pci_cfg20 {
+	uint32_t u32;
+	struct cvmx_pci_cfg20_s {
+		uint32_t mdsp:32;
+	} s;
+	struct cvmx_pci_cfg20_s cn30xx;
+	struct cvmx_pci_cfg20_s cn31xx;
+	struct cvmx_pci_cfg20_s cn38xx;
+	struct cvmx_pci_cfg20_s cn38xxp2;
+	struct cvmx_pci_cfg20_s cn50xx;
+	struct cvmx_pci_cfg20_s cn58xx;
+	struct cvmx_pci_cfg20_s cn58xxp1;
+};
+
+union cvmx_pci_cfg21 {
+	uint32_t u32;
+	struct cvmx_pci_cfg21_s {
+		uint32_t scmre:32;
+	} s;
+	struct cvmx_pci_cfg21_s cn30xx;
+	struct cvmx_pci_cfg21_s cn31xx;
+	struct cvmx_pci_cfg21_s cn38xx;
+	struct cvmx_pci_cfg21_s cn38xxp2;
+	struct cvmx_pci_cfg21_s cn50xx;
+	struct cvmx_pci_cfg21_s cn58xx;
+	struct cvmx_pci_cfg21_s cn58xxp1;
+};
+
+union cvmx_pci_cfg22 {
+	uint32_t u32;
+	struct cvmx_pci_cfg22_s {
+		uint32_t mac:7;
+		uint32_t reserved_19_24:6;
+		uint32_t flush:1;
+		uint32_t mra:1;
+		uint32_t mtta:1;
+		uint32_t mrv:8;
+		uint32_t mttv:8;
+	} s;
+	struct cvmx_pci_cfg22_s cn30xx;
+	struct cvmx_pci_cfg22_s cn31xx;
+	struct cvmx_pci_cfg22_s cn38xx;
+	struct cvmx_pci_cfg22_s cn38xxp2;
+	struct cvmx_pci_cfg22_s cn50xx;
+	struct cvmx_pci_cfg22_s cn58xx;
+	struct cvmx_pci_cfg22_s cn58xxp1;
+};
+
+union cvmx_pci_cfg56 {
+	uint32_t u32;
+	struct cvmx_pci_cfg56_s {
+		uint32_t reserved_23_31:9;
+		uint32_t most:3;
+		uint32_t mmbc:2;
+		uint32_t roe:1;
+		uint32_t dpere:1;
+		uint32_t ncp:8;
+		uint32_t pxcid:8;
+	} s;
+	struct cvmx_pci_cfg56_s cn30xx;
+	struct cvmx_pci_cfg56_s cn31xx;
+	struct cvmx_pci_cfg56_s cn38xx;
+	struct cvmx_pci_cfg56_s cn38xxp2;
+	struct cvmx_pci_cfg56_s cn50xx;
+	struct cvmx_pci_cfg56_s cn58xx;
+	struct cvmx_pci_cfg56_s cn58xxp1;
+};
+
+union cvmx_pci_cfg57 {
+	uint32_t u32;
+	struct cvmx_pci_cfg57_s {
+		uint32_t reserved_30_31:2;
+		uint32_t scemr:1;
+		uint32_t mcrsd:3;
+		uint32_t mostd:3;
+		uint32_t mmrbcd:2;
+		uint32_t dc:1;
+		uint32_t usc:1;
+		uint32_t scd:1;
+		uint32_t m133:1;
+		uint32_t w64:1;
+		uint32_t bn:8;
+		uint32_t dn:5;
+		uint32_t fn:3;
+	} s;
+	struct cvmx_pci_cfg57_s cn30xx;
+	struct cvmx_pci_cfg57_s cn31xx;
+	struct cvmx_pci_cfg57_s cn38xx;
+	struct cvmx_pci_cfg57_s cn38xxp2;
+	struct cvmx_pci_cfg57_s cn50xx;
+	struct cvmx_pci_cfg57_s cn58xx;
+	struct cvmx_pci_cfg57_s cn58xxp1;
+};
+
+union cvmx_pci_cfg58 {
+	uint32_t u32;
+	struct cvmx_pci_cfg58_s {
+		uint32_t pmes:5;
+		uint32_t d2s:1;
+		uint32_t d1s:1;
+		uint32_t auxc:3;
+		uint32_t dsi:1;
+		uint32_t reserved_20_20:1;
+		uint32_t pmec:1;
+		uint32_t pcimiv:3;
+		uint32_t ncp:8;
+		uint32_t pmcid:8;
+	} s;
+	struct cvmx_pci_cfg58_s cn30xx;
+	struct cvmx_pci_cfg58_s cn31xx;
+	struct cvmx_pci_cfg58_s cn38xx;
+	struct cvmx_pci_cfg58_s cn38xxp2;
+	struct cvmx_pci_cfg58_s cn50xx;
+	struct cvmx_pci_cfg58_s cn58xx;
+	struct cvmx_pci_cfg58_s cn58xxp1;
+};
+
+union cvmx_pci_cfg59 {
+	uint32_t u32;
+	struct cvmx_pci_cfg59_s {
+		uint32_t pmdia:8;
+		uint32_t bpccen:1;
+		uint32_t bd3h:1;
+		uint32_t reserved_16_21:6;
+		uint32_t pmess:1;
+		uint32_t pmedsia:2;
+		uint32_t pmds:4;
+		uint32_t pmeens:1;
+		uint32_t reserved_2_7:6;
+		uint32_t ps:2;
+	} s;
+	struct cvmx_pci_cfg59_s cn30xx;
+	struct cvmx_pci_cfg59_s cn31xx;
+	struct cvmx_pci_cfg59_s cn38xx;
+	struct cvmx_pci_cfg59_s cn38xxp2;
+	struct cvmx_pci_cfg59_s cn50xx;
+	struct cvmx_pci_cfg59_s cn58xx;
+	struct cvmx_pci_cfg59_s cn58xxp1;
+};
+
+union cvmx_pci_cfg60 {
+	uint32_t u32;
+	struct cvmx_pci_cfg60_s {
+		uint32_t reserved_24_31:8;
+		uint32_t m64:1;
+		uint32_t mme:3;
+		uint32_t mmc:3;
+		uint32_t msien:1;
+		uint32_t ncp:8;
+		uint32_t msicid:8;
+	} s;
+	struct cvmx_pci_cfg60_s cn30xx;
+	struct cvmx_pci_cfg60_s cn31xx;
+	struct cvmx_pci_cfg60_s cn38xx;
+	struct cvmx_pci_cfg60_s cn38xxp2;
+	struct cvmx_pci_cfg60_s cn50xx;
+	struct cvmx_pci_cfg60_s cn58xx;
+	struct cvmx_pci_cfg60_s cn58xxp1;
+};
+
+union cvmx_pci_cfg61 {
+	uint32_t u32;
+	struct cvmx_pci_cfg61_s {
+		uint32_t msi31t2:30;
+		uint32_t reserved_0_1:2;
+	} s;
+	struct cvmx_pci_cfg61_s cn30xx;
+	struct cvmx_pci_cfg61_s cn31xx;
+	struct cvmx_pci_cfg61_s cn38xx;
+	struct cvmx_pci_cfg61_s cn38xxp2;
+	struct cvmx_pci_cfg61_s cn50xx;
+	struct cvmx_pci_cfg61_s cn58xx;
+	struct cvmx_pci_cfg61_s cn58xxp1;
+};
+
+union cvmx_pci_cfg62 {
+	uint32_t u32;
+	struct cvmx_pci_cfg62_s {
+		uint32_t msi:32;
+	} s;
+	struct cvmx_pci_cfg62_s cn30xx;
+	struct cvmx_pci_cfg62_s cn31xx;
+	struct cvmx_pci_cfg62_s cn38xx;
+	struct cvmx_pci_cfg62_s cn38xxp2;
+	struct cvmx_pci_cfg62_s cn50xx;
+	struct cvmx_pci_cfg62_s cn58xx;
+	struct cvmx_pci_cfg62_s cn58xxp1;
+};
+
+union cvmx_pci_cfg63 {
+	uint32_t u32;
+	struct cvmx_pci_cfg63_s {
+		uint32_t reserved_16_31:16;
+		uint32_t msimd:16;
+	} s;
+	struct cvmx_pci_cfg63_s cn30xx;
+	struct cvmx_pci_cfg63_s cn31xx;
+	struct cvmx_pci_cfg63_s cn38xx;
+	struct cvmx_pci_cfg63_s cn38xxp2;
+	struct cvmx_pci_cfg63_s cn50xx;
+	struct cvmx_pci_cfg63_s cn58xx;
+	struct cvmx_pci_cfg63_s cn58xxp1;
+};
+
+union cvmx_pci_cnt_reg {
+	uint64_t u64;
+	struct cvmx_pci_cnt_reg_s {
+		uint64_t reserved_38_63:26;
+		uint64_t hm_pcix:1;
+		uint64_t hm_speed:2;
+		uint64_t ap_pcix:1;
+		uint64_t ap_speed:2;
+		uint64_t pcicnt:32;
+	} s;
+	struct cvmx_pci_cnt_reg_s cn50xx;
+	struct cvmx_pci_cnt_reg_s cn58xx;
+	struct cvmx_pci_cnt_reg_s cn58xxp1;
+};
+
+union cvmx_pci_ctl_status_2 {
+	uint32_t u32;
+	struct cvmx_pci_ctl_status_2_s {
+		uint32_t reserved_29_31:3;
+		uint32_t bb1_hole:3;
+		uint32_t bb1_siz:1;
+		uint32_t bb_ca:1;
+		uint32_t bb_es:2;
+		uint32_t bb1:1;
+		uint32_t bb0:1;
+		uint32_t erst_n:1;
+		uint32_t bar2pres:1;
+		uint32_t scmtyp:1;
+		uint32_t scm:1;
+		uint32_t en_wfilt:1;
+		uint32_t reserved_14_14:1;
+		uint32_t ap_pcix:1;
+		uint32_t ap_64ad:1;
+		uint32_t b12_bist:1;
+		uint32_t pmo_amod:1;
+		uint32_t pmo_fpc:3;
+		uint32_t tsr_hwm:3;
+		uint32_t bar2_enb:1;
+		uint32_t bar2_esx:2;
+		uint32_t bar2_cax:1;
+	} s;
+	struct cvmx_pci_ctl_status_2_s cn30xx;
+	struct cvmx_pci_ctl_status_2_cn31xx {
+		uint32_t reserved_20_31:12;
+		uint32_t erst_n:1;
+		uint32_t bar2pres:1;
+		uint32_t scmtyp:1;
+		uint32_t scm:1;
+		uint32_t en_wfilt:1;
+		uint32_t reserved_14_14:1;
+		uint32_t ap_pcix:1;
+		uint32_t ap_64ad:1;
+		uint32_t b12_bist:1;
+		uint32_t pmo_amod:1;
+		uint32_t pmo_fpc:3;
+		uint32_t tsr_hwm:3;
+		uint32_t bar2_enb:1;
+		uint32_t bar2_esx:2;
+		uint32_t bar2_cax:1;
+	} cn31xx;
+	struct cvmx_pci_ctl_status_2_s cn38xx;
+	struct cvmx_pci_ctl_status_2_cn31xx cn38xxp2;
+	struct cvmx_pci_ctl_status_2_s cn50xx;
+	struct cvmx_pci_ctl_status_2_s cn58xx;
+	struct cvmx_pci_ctl_status_2_s cn58xxp1;
+};
+
+union cvmx_pci_dbellx {
+	uint32_t u32;
+	struct cvmx_pci_dbellx_s {
+		uint32_t reserved_16_31:16;
+		uint32_t inc_val:16;
+	} s;
+	struct cvmx_pci_dbellx_s cn30xx;
+	struct cvmx_pci_dbellx_s cn31xx;
+	struct cvmx_pci_dbellx_s cn38xx;
+	struct cvmx_pci_dbellx_s cn38xxp2;
+	struct cvmx_pci_dbellx_s cn50xx;
+	struct cvmx_pci_dbellx_s cn58xx;
+	struct cvmx_pci_dbellx_s cn58xxp1;
+};
+
+union cvmx_pci_dma_cntx {
+	uint32_t u32;
+	struct cvmx_pci_dma_cntx_s {
+		uint32_t dma_cnt:32;
+	} s;
+	struct cvmx_pci_dma_cntx_s cn30xx;
+	struct cvmx_pci_dma_cntx_s cn31xx;
+	struct cvmx_pci_dma_cntx_s cn38xx;
+	struct cvmx_pci_dma_cntx_s cn38xxp2;
+	struct cvmx_pci_dma_cntx_s cn50xx;
+	struct cvmx_pci_dma_cntx_s cn58xx;
+	struct cvmx_pci_dma_cntx_s cn58xxp1;
+};
+
+union cvmx_pci_dma_int_levx {
+	uint32_t u32;
+	struct cvmx_pci_dma_int_levx_s {
+		uint32_t pkt_cnt:32;
+	} s;
+	struct cvmx_pci_dma_int_levx_s cn30xx;
+	struct cvmx_pci_dma_int_levx_s cn31xx;
+	struct cvmx_pci_dma_int_levx_s cn38xx;
+	struct cvmx_pci_dma_int_levx_s cn38xxp2;
+	struct cvmx_pci_dma_int_levx_s cn50xx;
+	struct cvmx_pci_dma_int_levx_s cn58xx;
+	struct cvmx_pci_dma_int_levx_s cn58xxp1;
+};
+
+union cvmx_pci_dma_timex {
+	uint32_t u32;
+	struct cvmx_pci_dma_timex_s {
+		uint32_t dma_time:32;
+	} s;
+	struct cvmx_pci_dma_timex_s cn30xx;
+	struct cvmx_pci_dma_timex_s cn31xx;
+	struct cvmx_pci_dma_timex_s cn38xx;
+	struct cvmx_pci_dma_timex_s cn38xxp2;
+	struct cvmx_pci_dma_timex_s cn50xx;
+	struct cvmx_pci_dma_timex_s cn58xx;
+	struct cvmx_pci_dma_timex_s cn58xxp1;
+};
+
+union cvmx_pci_instr_countx {
+	uint32_t u32;
+	struct cvmx_pci_instr_countx_s {
+		uint32_t icnt:32;
+	} s;
+	struct cvmx_pci_instr_countx_s cn30xx;
+	struct cvmx_pci_instr_countx_s cn31xx;
+	struct cvmx_pci_instr_countx_s cn38xx;
+	struct cvmx_pci_instr_countx_s cn38xxp2;
+	struct cvmx_pci_instr_countx_s cn50xx;
+	struct cvmx_pci_instr_countx_s cn58xx;
+	struct cvmx_pci_instr_countx_s cn58xxp1;
+};
+
+union cvmx_pci_int_enb {
+	uint64_t u64;
+	struct cvmx_pci_int_enb_s {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t idtime1:1;
+		uint64_t idtime0:1;
+		uint64_t idcnt1:1;
+		uint64_t idcnt0:1;
+		uint64_t iptime3:1;
+		uint64_t iptime2:1;
+		uint64_t iptime1:1;
+		uint64_t iptime0:1;
+		uint64_t ipcnt3:1;
+		uint64_t ipcnt2:1;
+		uint64_t ipcnt1:1;
+		uint64_t ipcnt0:1;
+		uint64_t irsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t idperr:1;
+		uint64_t iaperr:1;
+		uint64_t iserr:1;
+		uint64_t itsr_abt:1;
+		uint64_t imsc_msg:1;
+		uint64_t imsi_mabt:1;
+		uint64_t imsi_tabt:1;
+		uint64_t imsi_per:1;
+		uint64_t imr_tto:1;
+		uint64_t imr_abt:1;
+		uint64_t itr_abt:1;
+		uint64_t imr_wtto:1;
+		uint64_t imr_wabt:1;
+		uint64_t itr_wabt:1;
+	} s;
+	struct cvmx_pci_int_enb_cn30xx {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t idtime1:1;
+		uint64_t idtime0:1;
+		uint64_t idcnt1:1;
+		uint64_t idcnt0:1;
+		uint64_t reserved_22_24:3;
+		uint64_t iptime0:1;
+		uint64_t reserved_18_20:3;
+		uint64_t ipcnt0:1;
+		uint64_t irsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t idperr:1;
+		uint64_t iaperr:1;
+		uint64_t iserr:1;
+		uint64_t itsr_abt:1;
+		uint64_t imsc_msg:1;
+		uint64_t imsi_mabt:1;
+		uint64_t imsi_tabt:1;
+		uint64_t imsi_per:1;
+		uint64_t imr_tto:1;
+		uint64_t imr_abt:1;
+		uint64_t itr_abt:1;
+		uint64_t imr_wtto:1;
+		uint64_t imr_wabt:1;
+		uint64_t itr_wabt:1;
+	} cn30xx;
+	struct cvmx_pci_int_enb_cn31xx {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t idtime1:1;
+		uint64_t idtime0:1;
+		uint64_t idcnt1:1;
+		uint64_t idcnt0:1;
+		uint64_t reserved_23_24:2;
+		uint64_t iptime1:1;
+		uint64_t iptime0:1;
+		uint64_t reserved_19_20:2;
+		uint64_t ipcnt1:1;
+		uint64_t ipcnt0:1;
+		uint64_t irsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t idperr:1;
+		uint64_t iaperr:1;
+		uint64_t iserr:1;
+		uint64_t itsr_abt:1;
+		uint64_t imsc_msg:1;
+		uint64_t imsi_mabt:1;
+		uint64_t imsi_tabt:1;
+		uint64_t imsi_per:1;
+		uint64_t imr_tto:1;
+		uint64_t imr_abt:1;
+		uint64_t itr_abt:1;
+		uint64_t imr_wtto:1;
+		uint64_t imr_wabt:1;
+		uint64_t itr_wabt:1;
+	} cn31xx;
+	struct cvmx_pci_int_enb_s cn38xx;
+	struct cvmx_pci_int_enb_s cn38xxp2;
+	struct cvmx_pci_int_enb_cn31xx cn50xx;
+	struct cvmx_pci_int_enb_s cn58xx;
+	struct cvmx_pci_int_enb_s cn58xxp1;
+};
+
+union cvmx_pci_int_enb2 {
+	uint64_t u64;
+	struct cvmx_pci_int_enb2_s {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t rdtime1:1;
+		uint64_t rdtime0:1;
+		uint64_t rdcnt1:1;
+		uint64_t rdcnt0:1;
+		uint64_t rptime3:1;
+		uint64_t rptime2:1;
+		uint64_t rptime1:1;
+		uint64_t rptime0:1;
+		uint64_t rpcnt3:1;
+		uint64_t rpcnt2:1;
+		uint64_t rpcnt1:1;
+		uint64_t rpcnt0:1;
+		uint64_t rrsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t rdperr:1;
+		uint64_t raperr:1;
+		uint64_t rserr:1;
+		uint64_t rtsr_abt:1;
+		uint64_t rmsc_msg:1;
+		uint64_t rmsi_mabt:1;
+		uint64_t rmsi_tabt:1;
+		uint64_t rmsi_per:1;
+		uint64_t rmr_tto:1;
+		uint64_t rmr_abt:1;
+		uint64_t rtr_abt:1;
+		uint64_t rmr_wtto:1;
+		uint64_t rmr_wabt:1;
+		uint64_t rtr_wabt:1;
+	} s;
+	struct cvmx_pci_int_enb2_cn30xx {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t rdtime1:1;
+		uint64_t rdtime0:1;
+		uint64_t rdcnt1:1;
+		uint64_t rdcnt0:1;
+		uint64_t reserved_22_24:3;
+		uint64_t rptime0:1;
+		uint64_t reserved_18_20:3;
+		uint64_t rpcnt0:1;
+		uint64_t rrsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t rdperr:1;
+		uint64_t raperr:1;
+		uint64_t rserr:1;
+		uint64_t rtsr_abt:1;
+		uint64_t rmsc_msg:1;
+		uint64_t rmsi_mabt:1;
+		uint64_t rmsi_tabt:1;
+		uint64_t rmsi_per:1;
+		uint64_t rmr_tto:1;
+		uint64_t rmr_abt:1;
+		uint64_t rtr_abt:1;
+		uint64_t rmr_wtto:1;
+		uint64_t rmr_wabt:1;
+		uint64_t rtr_wabt:1;
+	} cn30xx;
+	struct cvmx_pci_int_enb2_cn31xx {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t rdtime1:1;
+		uint64_t rdtime0:1;
+		uint64_t rdcnt1:1;
+		uint64_t rdcnt0:1;
+		uint64_t reserved_23_24:2;
+		uint64_t rptime1:1;
+		uint64_t rptime0:1;
+		uint64_t reserved_19_20:2;
+		uint64_t rpcnt1:1;
+		uint64_t rpcnt0:1;
+		uint64_t rrsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t rdperr:1;
+		uint64_t raperr:1;
+		uint64_t rserr:1;
+		uint64_t rtsr_abt:1;
+		uint64_t rmsc_msg:1;
+		uint64_t rmsi_mabt:1;
+		uint64_t rmsi_tabt:1;
+		uint64_t rmsi_per:1;
+		uint64_t rmr_tto:1;
+		uint64_t rmr_abt:1;
+		uint64_t rtr_abt:1;
+		uint64_t rmr_wtto:1;
+		uint64_t rmr_wabt:1;
+		uint64_t rtr_wabt:1;
+	} cn31xx;
+	struct cvmx_pci_int_enb2_s cn38xx;
+	struct cvmx_pci_int_enb2_s cn38xxp2;
+	struct cvmx_pci_int_enb2_cn31xx cn50xx;
+	struct cvmx_pci_int_enb2_s cn58xx;
+	struct cvmx_pci_int_enb2_s cn58xxp1;
+};
+
+union cvmx_pci_int_sum {
+	uint64_t u64;
+	struct cvmx_pci_int_sum_s {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t ptime3:1;
+		uint64_t ptime2:1;
+		uint64_t ptime1:1;
+		uint64_t ptime0:1;
+		uint64_t pcnt3:1;
+		uint64_t pcnt2:1;
+		uint64_t pcnt1:1;
+		uint64_t pcnt0:1;
+		uint64_t rsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t dperr:1;
+		uint64_t aperr:1;
+		uint64_t serr:1;
+		uint64_t tsr_abt:1;
+		uint64_t msc_msg:1;
+		uint64_t msi_mabt:1;
+		uint64_t msi_tabt:1;
+		uint64_t msi_per:1;
+		uint64_t mr_tto:1;
+		uint64_t mr_abt:1;
+		uint64_t tr_abt:1;
+		uint64_t mr_wtto:1;
+		uint64_t mr_wabt:1;
+		uint64_t tr_wabt:1;
+	} s;
+	struct cvmx_pci_int_sum_cn30xx {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t reserved_22_24:3;
+		uint64_t ptime0:1;
+		uint64_t reserved_18_20:3;
+		uint64_t pcnt0:1;
+		uint64_t rsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t dperr:1;
+		uint64_t aperr:1;
+		uint64_t serr:1;
+		uint64_t tsr_abt:1;
+		uint64_t msc_msg:1;
+		uint64_t msi_mabt:1;
+		uint64_t msi_tabt:1;
+		uint64_t msi_per:1;
+		uint64_t mr_tto:1;
+		uint64_t mr_abt:1;
+		uint64_t tr_abt:1;
+		uint64_t mr_wtto:1;
+		uint64_t mr_wabt:1;
+		uint64_t tr_wabt:1;
+	} cn30xx;
+	struct cvmx_pci_int_sum_cn31xx {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t reserved_23_24:2;
+		uint64_t ptime1:1;
+		uint64_t ptime0:1;
+		uint64_t reserved_19_20:2;
+		uint64_t pcnt1:1;
+		uint64_t pcnt0:1;
+		uint64_t rsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t dperr:1;
+		uint64_t aperr:1;
+		uint64_t serr:1;
+		uint64_t tsr_abt:1;
+		uint64_t msc_msg:1;
+		uint64_t msi_mabt:1;
+		uint64_t msi_tabt:1;
+		uint64_t msi_per:1;
+		uint64_t mr_tto:1;
+		uint64_t mr_abt:1;
+		uint64_t tr_abt:1;
+		uint64_t mr_wtto:1;
+		uint64_t mr_wabt:1;
+		uint64_t tr_wabt:1;
+	} cn31xx;
+	struct cvmx_pci_int_sum_s cn38xx;
+	struct cvmx_pci_int_sum_s cn38xxp2;
+	struct cvmx_pci_int_sum_cn31xx cn50xx;
+	struct cvmx_pci_int_sum_s cn58xx;
+	struct cvmx_pci_int_sum_s cn58xxp1;
+};
+
+union cvmx_pci_int_sum2 {
+	uint64_t u64;
+	struct cvmx_pci_int_sum2_s {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t ptime3:1;
+		uint64_t ptime2:1;
+		uint64_t ptime1:1;
+		uint64_t ptime0:1;
+		uint64_t pcnt3:1;
+		uint64_t pcnt2:1;
+		uint64_t pcnt1:1;
+		uint64_t pcnt0:1;
+		uint64_t rsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t dperr:1;
+		uint64_t aperr:1;
+		uint64_t serr:1;
+		uint64_t tsr_abt:1;
+		uint64_t msc_msg:1;
+		uint64_t msi_mabt:1;
+		uint64_t msi_tabt:1;
+		uint64_t msi_per:1;
+		uint64_t mr_tto:1;
+		uint64_t mr_abt:1;
+		uint64_t tr_abt:1;
+		uint64_t mr_wtto:1;
+		uint64_t mr_wabt:1;
+		uint64_t tr_wabt:1;
+	} s;
+	struct cvmx_pci_int_sum2_cn30xx {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t reserved_22_24:3;
+		uint64_t ptime0:1;
+		uint64_t reserved_18_20:3;
+		uint64_t pcnt0:1;
+		uint64_t rsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t dperr:1;
+		uint64_t aperr:1;
+		uint64_t serr:1;
+		uint64_t tsr_abt:1;
+		uint64_t msc_msg:1;
+		uint64_t msi_mabt:1;
+		uint64_t msi_tabt:1;
+		uint64_t msi_per:1;
+		uint64_t mr_tto:1;
+		uint64_t mr_abt:1;
+		uint64_t tr_abt:1;
+		uint64_t mr_wtto:1;
+		uint64_t mr_wabt:1;
+		uint64_t tr_wabt:1;
+	} cn30xx;
+	struct cvmx_pci_int_sum2_cn31xx {
+		uint64_t reserved_34_63:30;
+		uint64_t ill_rd:1;
+		uint64_t ill_wr:1;
+		uint64_t win_wr:1;
+		uint64_t dma1_fi:1;
+		uint64_t dma0_fi:1;
+		uint64_t dtime1:1;
+		uint64_t dtime0:1;
+		uint64_t dcnt1:1;
+		uint64_t dcnt0:1;
+		uint64_t reserved_23_24:2;
+		uint64_t ptime1:1;
+		uint64_t ptime0:1;
+		uint64_t reserved_19_20:2;
+		uint64_t pcnt1:1;
+		uint64_t pcnt0:1;
+		uint64_t rsl_int:1;
+		uint64_t ill_rrd:1;
+		uint64_t ill_rwr:1;
+		uint64_t dperr:1;
+		uint64_t aperr:1;
+		uint64_t serr:1;
+		uint64_t tsr_abt:1;
+		uint64_t msc_msg:1;
+		uint64_t msi_mabt:1;
+		uint64_t msi_tabt:1;
+		uint64_t msi_per:1;
+		uint64_t mr_tto:1;
+		uint64_t mr_abt:1;
+		uint64_t tr_abt:1;
+		uint64_t mr_wtto:1;
+		uint64_t mr_wabt:1;
+		uint64_t tr_wabt:1;
+	} cn31xx;
+	struct cvmx_pci_int_sum2_s cn38xx;
+	struct cvmx_pci_int_sum2_s cn38xxp2;
+	struct cvmx_pci_int_sum2_cn31xx cn50xx;
+	struct cvmx_pci_int_sum2_s cn58xx;
+	struct cvmx_pci_int_sum2_s cn58xxp1;
+};
+
+union cvmx_pci_msi_rcv {
+	uint32_t u32;
+	struct cvmx_pci_msi_rcv_s {
+		uint32_t reserved_6_31:26;
+		uint32_t intr:6;
+	} s;
+	struct cvmx_pci_msi_rcv_s cn30xx;
+	struct cvmx_pci_msi_rcv_s cn31xx;
+	struct cvmx_pci_msi_rcv_s cn38xx;
+	struct cvmx_pci_msi_rcv_s cn38xxp2;
+	struct cvmx_pci_msi_rcv_s cn50xx;
+	struct cvmx_pci_msi_rcv_s cn58xx;
+	struct cvmx_pci_msi_rcv_s cn58xxp1;
+};
+
+union cvmx_pci_pkt_creditsx {
+	uint32_t u32;
+	struct cvmx_pci_pkt_creditsx_s {
+		uint32_t pkt_cnt:16;
+		uint32_t ptr_cnt:16;
+	} s;
+	struct cvmx_pci_pkt_creditsx_s cn30xx;
+	struct cvmx_pci_pkt_creditsx_s cn31xx;
+	struct cvmx_pci_pkt_creditsx_s cn38xx;
+	struct cvmx_pci_pkt_creditsx_s cn38xxp2;
+	struct cvmx_pci_pkt_creditsx_s cn50xx;
+	struct cvmx_pci_pkt_creditsx_s cn58xx;
+	struct cvmx_pci_pkt_creditsx_s cn58xxp1;
+};
+
+union cvmx_pci_pkts_sentx {
+	uint32_t u32;
+	struct cvmx_pci_pkts_sentx_s {
+		uint32_t pkt_cnt:32;
+	} s;
+	struct cvmx_pci_pkts_sentx_s cn30xx;
+	struct cvmx_pci_pkts_sentx_s cn31xx;
+	struct cvmx_pci_pkts_sentx_s cn38xx;
+	struct cvmx_pci_pkts_sentx_s cn38xxp2;
+	struct cvmx_pci_pkts_sentx_s cn50xx;
+	struct cvmx_pci_pkts_sentx_s cn58xx;
+	struct cvmx_pci_pkts_sentx_s cn58xxp1;
+};
+
+union cvmx_pci_pkts_sent_int_levx {
+	uint32_t u32;
+	struct cvmx_pci_pkts_sent_int_levx_s {
+		uint32_t pkt_cnt:32;
+	} s;
+	struct cvmx_pci_pkts_sent_int_levx_s cn30xx;
+	struct cvmx_pci_pkts_sent_int_levx_s cn31xx;
+	struct cvmx_pci_pkts_sent_int_levx_s cn38xx;
+	struct cvmx_pci_pkts_sent_int_levx_s cn38xxp2;
+	struct cvmx_pci_pkts_sent_int_levx_s cn50xx;
+	struct cvmx_pci_pkts_sent_int_levx_s cn58xx;
+	struct cvmx_pci_pkts_sent_int_levx_s cn58xxp1;
+};
+
+union cvmx_pci_pkts_sent_timex {
+	uint32_t u32;
+	struct cvmx_pci_pkts_sent_timex_s {
+		uint32_t pkt_time:32;
+	} s;
+	struct cvmx_pci_pkts_sent_timex_s cn30xx;
+	struct cvmx_pci_pkts_sent_timex_s cn31xx;
+	struct cvmx_pci_pkts_sent_timex_s cn38xx;
+	struct cvmx_pci_pkts_sent_timex_s cn38xxp2;
+	struct cvmx_pci_pkts_sent_timex_s cn50xx;
+	struct cvmx_pci_pkts_sent_timex_s cn58xx;
+	struct cvmx_pci_pkts_sent_timex_s cn58xxp1;
+};
+
+union cvmx_pci_read_cmd_6 {
+	uint32_t u32;
+	struct cvmx_pci_read_cmd_6_s {
+		uint32_t reserved_9_31:23;
+		uint32_t min_data:6;
+		uint32_t prefetch:3;
+	} s;
+	struct cvmx_pci_read_cmd_6_s cn30xx;
+	struct cvmx_pci_read_cmd_6_s cn31xx;
+	struct cvmx_pci_read_cmd_6_s cn38xx;
+	struct cvmx_pci_read_cmd_6_s cn38xxp2;
+	struct cvmx_pci_read_cmd_6_s cn50xx;
+	struct cvmx_pci_read_cmd_6_s cn58xx;
+	struct cvmx_pci_read_cmd_6_s cn58xxp1;
+};
+
+union cvmx_pci_read_cmd_c {
+	uint32_t u32;
+	struct cvmx_pci_read_cmd_c_s {
+		uint32_t reserved_9_31:23;
+		uint32_t min_data:6;
+		uint32_t prefetch:3;
+	} s;
+	struct cvmx_pci_read_cmd_c_s cn30xx;
+	struct cvmx_pci_read_cmd_c_s cn31xx;
+	struct cvmx_pci_read_cmd_c_s cn38xx;
+	struct cvmx_pci_read_cmd_c_s cn38xxp2;
+	struct cvmx_pci_read_cmd_c_s cn50xx;
+	struct cvmx_pci_read_cmd_c_s cn58xx;
+	struct cvmx_pci_read_cmd_c_s cn58xxp1;
+};
+
+union cvmx_pci_read_cmd_e {
+	uint32_t u32;
+	struct cvmx_pci_read_cmd_e_s {
+		uint32_t reserved_9_31:23;
+		uint32_t min_data:6;
+		uint32_t prefetch:3;
+	} s;
+	struct cvmx_pci_read_cmd_e_s cn30xx;
+	struct cvmx_pci_read_cmd_e_s cn31xx;
+	struct cvmx_pci_read_cmd_e_s cn38xx;
+	struct cvmx_pci_read_cmd_e_s cn38xxp2;
+	struct cvmx_pci_read_cmd_e_s cn50xx;
+	struct cvmx_pci_read_cmd_e_s cn58xx;
+	struct cvmx_pci_read_cmd_e_s cn58xxp1;
+};
+
+union cvmx_pci_read_timeout {
+	uint64_t u64;
+	struct cvmx_pci_read_timeout_s {
+		uint64_t reserved_32_63:32;
+		uint64_t enb:1;
+		uint64_t cnt:31;
+	} s;
+	struct cvmx_pci_read_timeout_s cn30xx;
+	struct cvmx_pci_read_timeout_s cn31xx;
+	struct cvmx_pci_read_timeout_s cn38xx;
+	struct cvmx_pci_read_timeout_s cn38xxp2;
+	struct cvmx_pci_read_timeout_s cn50xx;
+	struct cvmx_pci_read_timeout_s cn58xx;
+	struct cvmx_pci_read_timeout_s cn58xxp1;
+};
+
+union cvmx_pci_scm_reg {
+	uint64_t u64;
+	struct cvmx_pci_scm_reg_s {
+		uint64_t reserved_32_63:32;
+		uint64_t scm:32;
+	} s;
+	struct cvmx_pci_scm_reg_s cn30xx;
+	struct cvmx_pci_scm_reg_s cn31xx;
+	struct cvmx_pci_scm_reg_s cn38xx;
+	struct cvmx_pci_scm_reg_s cn38xxp2;
+	struct cvmx_pci_scm_reg_s cn50xx;
+	struct cvmx_pci_scm_reg_s cn58xx;
+	struct cvmx_pci_scm_reg_s cn58xxp1;
+};
+
+union cvmx_pci_tsr_reg {
+	uint64_t u64;
+	struct cvmx_pci_tsr_reg_s {
+		uint64_t reserved_36_63:28;
+		uint64_t tsr:36;
+	} s;
+	struct cvmx_pci_tsr_reg_s cn30xx;
+	struct cvmx_pci_tsr_reg_s cn31xx;
+	struct cvmx_pci_tsr_reg_s cn38xx;
+	struct cvmx_pci_tsr_reg_s cn38xxp2;
+	struct cvmx_pci_tsr_reg_s cn50xx;
+	struct cvmx_pci_tsr_reg_s cn58xx;
+	struct cvmx_pci_tsr_reg_s cn58xxp1;
+};
+
+union cvmx_pci_win_rd_addr {
+	uint64_t u64;
+	struct cvmx_pci_win_rd_addr_s {
+		uint64_t reserved_49_63:15;
+		uint64_t iobit:1;
+		uint64_t reserved_0_47:48;
+	} s;
+	struct cvmx_pci_win_rd_addr_cn30xx {
+		uint64_t reserved_49_63:15;
+		uint64_t iobit:1;
+		uint64_t rd_addr:46;
+		uint64_t reserved_0_1:2;
+	} cn30xx;
+	struct cvmx_pci_win_rd_addr_cn30xx cn31xx;
+	struct cvmx_pci_win_rd_addr_cn38xx {
+		uint64_t reserved_49_63:15;
+		uint64_t iobit:1;
+		uint64_t rd_addr:45;
+		uint64_t reserved_0_2:3;
+	} cn38xx;
+	struct cvmx_pci_win_rd_addr_cn38xx cn38xxp2;
+	struct cvmx_pci_win_rd_addr_cn30xx cn50xx;
+	struct cvmx_pci_win_rd_addr_cn38xx cn58xx;
+	struct cvmx_pci_win_rd_addr_cn38xx cn58xxp1;
+};
+
+union cvmx_pci_win_rd_data {
+	uint64_t u64;
+	struct cvmx_pci_win_rd_data_s {
+		uint64_t rd_data:64;
+	} s;
+	struct cvmx_pci_win_rd_data_s cn30xx;
+	struct cvmx_pci_win_rd_data_s cn31xx;
+	struct cvmx_pci_win_rd_data_s cn38xx;
+	struct cvmx_pci_win_rd_data_s cn38xxp2;
+	struct cvmx_pci_win_rd_data_s cn50xx;
+	struct cvmx_pci_win_rd_data_s cn58xx;
+	struct cvmx_pci_win_rd_data_s cn58xxp1;
+};
+
+union cvmx_pci_win_wr_addr {
+	uint64_t u64;
+	struct cvmx_pci_win_wr_addr_s {
+		uint64_t reserved_49_63:15;
+		uint64_t iobit:1;
+		uint64_t wr_addr:45;
+		uint64_t reserved_0_2:3;
+	} s;
+	struct cvmx_pci_win_wr_addr_s cn30xx;
+	struct cvmx_pci_win_wr_addr_s cn31xx;
+	struct cvmx_pci_win_wr_addr_s cn38xx;
+	struct cvmx_pci_win_wr_addr_s cn38xxp2;
+	struct cvmx_pci_win_wr_addr_s cn50xx;
+	struct cvmx_pci_win_wr_addr_s cn58xx;
+	struct cvmx_pci_win_wr_addr_s cn58xxp1;
+};
+
+union cvmx_pci_win_wr_data {
+	uint64_t u64;
+	struct cvmx_pci_win_wr_data_s {
+		uint64_t wr_data:64;
+	} s;
+	struct cvmx_pci_win_wr_data_s cn30xx;
+	struct cvmx_pci_win_wr_data_s cn31xx;
+	struct cvmx_pci_win_wr_data_s cn38xx;
+	struct cvmx_pci_win_wr_data_s cn38xxp2;
+	struct cvmx_pci_win_wr_data_s cn50xx;
+	struct cvmx_pci_win_wr_data_s cn58xx;
+	struct cvmx_pci_win_wr_data_s cn58xxp1;
+};
+
+union cvmx_pci_win_wr_mask {
+	uint64_t u64;
+	struct cvmx_pci_win_wr_mask_s {
+		uint64_t reserved_8_63:56;
+		uint64_t wr_mask:8;
+	} s;
+	struct cvmx_pci_win_wr_mask_s cn30xx;
+	struct cvmx_pci_win_wr_mask_s cn31xx;
+	struct cvmx_pci_win_wr_mask_s cn38xx;
+	struct cvmx_pci_win_wr_mask_s cn38xxp2;
+	struct cvmx_pci_win_wr_mask_s cn50xx;
+	struct cvmx_pci_win_wr_mask_s cn58xx;
+	struct cvmx_pci_win_wr_mask_s cn58xxp1;
+};
+
+#endif
diff --git a/arch/mips/include/asm/octeon/cvmx-pcieep-defs.h b/arch/mips/include/asm/octeon/cvmx-pcieep-defs.h
new file mode 100644
index 0000000..d553f8e
--- /dev/null
+++ b/arch/mips/include/asm/octeon/cvmx-pcieep-defs.h
@@ -0,0 +1,1365 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_PCIEEP_DEFS_H__
+#define __CVMX_PCIEEP_DEFS_H__
+
+#define CVMX_PCIEEP_CFG000 \
+	 (0x0000000000000000ull)
+#define CVMX_PCIEEP_CFG001 \
+	 (0x0000000000000004ull)
+#define CVMX_PCIEEP_CFG002 \
+	 (0x0000000000000008ull)
+#define CVMX_PCIEEP_CFG003 \
+	 (0x000000000000000Cull)
+#define CVMX_PCIEEP_CFG004 \
+	 (0x0000000000000010ull)
+#define CVMX_PCIEEP_CFG004_MASK \
+	 (0x0000000080000010ull)
+#define CVMX_PCIEEP_CFG005 \
+	 (0x0000000000000014ull)
+#define CVMX_PCIEEP_CFG005_MASK \
+	 (0x0000000080000014ull)
+#define CVMX_PCIEEP_CFG006 \
+	 (0x0000000000000018ull)
+#define CVMX_PCIEEP_CFG006_MASK \
+	 (0x0000000080000018ull)
+#define CVMX_PCIEEP_CFG007 \
+	 (0x000000000000001Cull)
+#define CVMX_PCIEEP_CFG007_MASK \
+	 (0x000000008000001Cull)
+#define CVMX_PCIEEP_CFG008 \
+	 (0x0000000000000020ull)
+#define CVMX_PCIEEP_CFG008_MASK \
+	 (0x0000000080000020ull)
+#define CVMX_PCIEEP_CFG009 \
+	 (0x0000000000000024ull)
+#define CVMX_PCIEEP_CFG009_MASK \
+	 (0x0000000080000024ull)
+#define CVMX_PCIEEP_CFG010 \
+	 (0x0000000000000028ull)
+#define CVMX_PCIEEP_CFG011 \
+	 (0x000000000000002Cull)
+#define CVMX_PCIEEP_CFG012 \
+	 (0x0000000000000030ull)
+#define CVMX_PCIEEP_CFG012_MASK \
+	 (0x0000000080000030ull)
+#define CVMX_PCIEEP_CFG013 \
+	 (0x0000000000000034ull)
+#define CVMX_PCIEEP_CFG015 \
+	 (0x000000000000003Cull)
+#define CVMX_PCIEEP_CFG016 \
+	 (0x0000000000000040ull)
+#define CVMX_PCIEEP_CFG017 \
+	 (0x0000000000000044ull)
+#define CVMX_PCIEEP_CFG020 \
+	 (0x0000000000000050ull)
+#define CVMX_PCIEEP_CFG021 \
+	 (0x0000000000000054ull)
+#define CVMX_PCIEEP_CFG022 \
+	 (0x0000000000000058ull)
+#define CVMX_PCIEEP_CFG023 \
+	 (0x000000000000005Cull)
+#define CVMX_PCIEEP_CFG028 \
+	 (0x0000000000000070ull)
+#define CVMX_PCIEEP_CFG029 \
+	 (0x0000000000000074ull)
+#define CVMX_PCIEEP_CFG030 \
+	 (0x0000000000000078ull)
+#define CVMX_PCIEEP_CFG031 \
+	 (0x000000000000007Cull)
+#define CVMX_PCIEEP_CFG032 \
+	 (0x0000000000000080ull)
+#define CVMX_PCIEEP_CFG033 \
+	 (0x0000000000000084ull)
+#define CVMX_PCIEEP_CFG034 \
+	 (0x0000000000000088ull)
+#define CVMX_PCIEEP_CFG037 \
+	 (0x0000000000000094ull)
+#define CVMX_PCIEEP_CFG038 \
+	 (0x0000000000000098ull)
+#define CVMX_PCIEEP_CFG039 \
+	 (0x000000000000009Cull)
+#define CVMX_PCIEEP_CFG040 \
+	 (0x00000000000000A0ull)
+#define CVMX_PCIEEP_CFG041 \
+	 (0x00000000000000A4ull)
+#define CVMX_PCIEEP_CFG042 \
+	 (0x00000000000000A8ull)
+#define CVMX_PCIEEP_CFG064 \
+	 (0x0000000000000100ull)
+#define CVMX_PCIEEP_CFG065 \
+	 (0x0000000000000104ull)
+#define CVMX_PCIEEP_CFG066 \
+	 (0x0000000000000108ull)
+#define CVMX_PCIEEP_CFG067 \
+	 (0x000000000000010Cull)
+#define CVMX_PCIEEP_CFG068 \
+	 (0x0000000000000110ull)
+#define CVMX_PCIEEP_CFG069 \
+	 (0x0000000000000114ull)
+#define CVMX_PCIEEP_CFG070 \
+	 (0x0000000000000118ull)
+#define CVMX_PCIEEP_CFG071 \
+	 (0x000000000000011Cull)
+#define CVMX_PCIEEP_CFG072 \
+	 (0x0000000000000120ull)
+#define CVMX_PCIEEP_CFG073 \
+	 (0x0000000000000124ull)
+#define CVMX_PCIEEP_CFG074 \
+	 (0x0000000000000128ull)
+#define CVMX_PCIEEP_CFG448 \
+	 (0x0000000000000700ull)
+#define CVMX_PCIEEP_CFG449 \
+	 (0x0000000000000704ull)
+#define CVMX_PCIEEP_CFG450 \
+	 (0x0000000000000708ull)
+#define CVMX_PCIEEP_CFG451 \
+	 (0x000000000000070Cull)
+#define CVMX_PCIEEP_CFG452 \
+	 (0x0000000000000710ull)
+#define CVMX_PCIEEP_CFG453 \
+	 (0x0000000000000714ull)
+#define CVMX_PCIEEP_CFG454 \
+	 (0x0000000000000718ull)
+#define CVMX_PCIEEP_CFG455 \
+	 (0x000000000000071Cull)
+#define CVMX_PCIEEP_CFG456 \
+	 (0x0000000000000720ull)
+#define CVMX_PCIEEP_CFG458 \
+	 (0x0000000000000728ull)
+#define CVMX_PCIEEP_CFG459 \
+	 (0x000000000000072Cull)
+#define CVMX_PCIEEP_CFG460 \
+	 (0x0000000000000730ull)
+#define CVMX_PCIEEP_CFG461 \
+	 (0x0000000000000734ull)
+#define CVMX_PCIEEP_CFG462 \
+	 (0x0000000000000738ull)
+#define CVMX_PCIEEP_CFG463 \
+	 (0x000000000000073Cull)
+#define CVMX_PCIEEP_CFG464 \
+	 (0x0000000000000740ull)
+#define CVMX_PCIEEP_CFG465 \
+	 (0x0000000000000744ull)
+#define CVMX_PCIEEP_CFG466 \
+	 (0x0000000000000748ull)
+#define CVMX_PCIEEP_CFG467 \
+	 (0x000000000000074Cull)
+#define CVMX_PCIEEP_CFG468 \
+	 (0x0000000000000750ull)
+#define CVMX_PCIEEP_CFG490 \
+	 (0x00000000000007A8ull)
+#define CVMX_PCIEEP_CFG491 \
+	 (0x00000000000007ACull)
+#define CVMX_PCIEEP_CFG492 \
+	 (0x00000000000007B0ull)
+#define CVMX_PCIEEP_CFG516 \
+	 (0x0000000000000810ull)
+#define CVMX_PCIEEP_CFG517 \
+	 (0x0000000000000814ull)
+
+union cvmx_pcieep_cfg000 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg000_s {
+		uint32_t devid:16;
+		uint32_t vendid:16;
+	} s;
+	struct cvmx_pcieep_cfg000_s cn52xx;
+	struct cvmx_pcieep_cfg000_s cn52xxp1;
+	struct cvmx_pcieep_cfg000_s cn56xx;
+	struct cvmx_pcieep_cfg000_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg001 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg001_s {
+		uint32_t dpe:1;
+		uint32_t sse:1;
+		uint32_t rma:1;
+		uint32_t rta:1;
+		uint32_t sta:1;
+		uint32_t devt:2;
+		uint32_t mdpe:1;
+		uint32_t fbb:1;
+		uint32_t reserved_22_22:1;
+		uint32_t m66:1;
+		uint32_t cl:1;
+		uint32_t i_stat:1;
+		uint32_t reserved_11_18:8;
+		uint32_t i_dis:1;
+		uint32_t fbbe:1;
+		uint32_t see:1;
+		uint32_t ids_wcc:1;
+		uint32_t per:1;
+		uint32_t vps:1;
+		uint32_t mwice:1;
+		uint32_t scse:1;
+		uint32_t me:1;
+		uint32_t msae:1;
+		uint32_t isae:1;
+	} s;
+	struct cvmx_pcieep_cfg001_s cn52xx;
+	struct cvmx_pcieep_cfg001_s cn52xxp1;
+	struct cvmx_pcieep_cfg001_s cn56xx;
+	struct cvmx_pcieep_cfg001_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg002 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg002_s {
+		uint32_t bcc:8;
+		uint32_t sc:8;
+		uint32_t pi:8;
+		uint32_t rid:8;
+	} s;
+	struct cvmx_pcieep_cfg002_s cn52xx;
+	struct cvmx_pcieep_cfg002_s cn52xxp1;
+	struct cvmx_pcieep_cfg002_s cn56xx;
+	struct cvmx_pcieep_cfg002_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg003 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg003_s {
+		uint32_t bist:8;
+		uint32_t mfd:1;
+		uint32_t chf:7;
+		uint32_t lt:8;
+		uint32_t cls:8;
+	} s;
+	struct cvmx_pcieep_cfg003_s cn52xx;
+	struct cvmx_pcieep_cfg003_s cn52xxp1;
+	struct cvmx_pcieep_cfg003_s cn56xx;
+	struct cvmx_pcieep_cfg003_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg004 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg004_s {
+		uint32_t lbab:18;
+		uint32_t reserved_4_13:10;
+		uint32_t pf:1;
+		uint32_t typ:2;
+		uint32_t mspc:1;
+	} s;
+	struct cvmx_pcieep_cfg004_s cn52xx;
+	struct cvmx_pcieep_cfg004_s cn52xxp1;
+	struct cvmx_pcieep_cfg004_s cn56xx;
+	struct cvmx_pcieep_cfg004_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg004_mask {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg004_mask_s {
+		uint32_t lmask:31;
+		uint32_t enb:1;
+	} s;
+	struct cvmx_pcieep_cfg004_mask_s cn52xx;
+	struct cvmx_pcieep_cfg004_mask_s cn52xxp1;
+	struct cvmx_pcieep_cfg004_mask_s cn56xx;
+	struct cvmx_pcieep_cfg004_mask_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg005 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg005_s {
+		uint32_t ubab:32;
+	} s;
+	struct cvmx_pcieep_cfg005_s cn52xx;
+	struct cvmx_pcieep_cfg005_s cn52xxp1;
+	struct cvmx_pcieep_cfg005_s cn56xx;
+	struct cvmx_pcieep_cfg005_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg005_mask {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg005_mask_s {
+		uint32_t umask:32;
+	} s;
+	struct cvmx_pcieep_cfg005_mask_s cn52xx;
+	struct cvmx_pcieep_cfg005_mask_s cn52xxp1;
+	struct cvmx_pcieep_cfg005_mask_s cn56xx;
+	struct cvmx_pcieep_cfg005_mask_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg006 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg006_s {
+		uint32_t lbab:6;
+		uint32_t reserved_4_25:22;
+		uint32_t pf:1;
+		uint32_t typ:2;
+		uint32_t mspc:1;
+	} s;
+	struct cvmx_pcieep_cfg006_s cn52xx;
+	struct cvmx_pcieep_cfg006_s cn52xxp1;
+	struct cvmx_pcieep_cfg006_s cn56xx;
+	struct cvmx_pcieep_cfg006_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg006_mask {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg006_mask_s {
+		uint32_t lmask:31;
+		uint32_t enb:1;
+	} s;
+	struct cvmx_pcieep_cfg006_mask_s cn52xx;
+	struct cvmx_pcieep_cfg006_mask_s cn52xxp1;
+	struct cvmx_pcieep_cfg006_mask_s cn56xx;
+	struct cvmx_pcieep_cfg006_mask_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg007 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg007_s {
+		uint32_t ubab:32;
+	} s;
+	struct cvmx_pcieep_cfg007_s cn52xx;
+	struct cvmx_pcieep_cfg007_s cn52xxp1;
+	struct cvmx_pcieep_cfg007_s cn56xx;
+	struct cvmx_pcieep_cfg007_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg007_mask {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg007_mask_s {
+		uint32_t umask:32;
+	} s;
+	struct cvmx_pcieep_cfg007_mask_s cn52xx;
+	struct cvmx_pcieep_cfg007_mask_s cn52xxp1;
+	struct cvmx_pcieep_cfg007_mask_s cn56xx;
+	struct cvmx_pcieep_cfg007_mask_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg008 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg008_s {
+		uint32_t reserved_4_31:28;
+		uint32_t pf:1;
+		uint32_t typ:2;
+		uint32_t mspc:1;
+	} s;
+	struct cvmx_pcieep_cfg008_s cn52xx;
+	struct cvmx_pcieep_cfg008_s cn52xxp1;
+	struct cvmx_pcieep_cfg008_s cn56xx;
+	struct cvmx_pcieep_cfg008_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg008_mask {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg008_mask_s {
+		uint32_t lmask:31;
+		uint32_t enb:1;
+	} s;
+	struct cvmx_pcieep_cfg008_mask_s cn52xx;
+	struct cvmx_pcieep_cfg008_mask_s cn52xxp1;
+	struct cvmx_pcieep_cfg008_mask_s cn56xx;
+	struct cvmx_pcieep_cfg008_mask_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg009 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg009_s {
+		uint32_t ubab:25;
+		uint32_t reserved_0_6:7;
+	} s;
+	struct cvmx_pcieep_cfg009_s cn52xx;
+	struct cvmx_pcieep_cfg009_s cn52xxp1;
+	struct cvmx_pcieep_cfg009_s cn56xx;
+	struct cvmx_pcieep_cfg009_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg009_mask {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg009_mask_s {
+		uint32_t umask:32;
+	} s;
+	struct cvmx_pcieep_cfg009_mask_s cn52xx;
+	struct cvmx_pcieep_cfg009_mask_s cn52xxp1;
+	struct cvmx_pcieep_cfg009_mask_s cn56xx;
+	struct cvmx_pcieep_cfg009_mask_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg010 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg010_s {
+		uint32_t cisp:32;
+	} s;
+	struct cvmx_pcieep_cfg010_s cn52xx;
+	struct cvmx_pcieep_cfg010_s cn52xxp1;
+	struct cvmx_pcieep_cfg010_s cn56xx;
+	struct cvmx_pcieep_cfg010_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg011 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg011_s {
+		uint32_t ssid:16;
+		uint32_t ssvid:16;
+	} s;
+	struct cvmx_pcieep_cfg011_s cn52xx;
+	struct cvmx_pcieep_cfg011_s cn52xxp1;
+	struct cvmx_pcieep_cfg011_s cn56xx;
+	struct cvmx_pcieep_cfg011_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg012 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg012_s {
+		uint32_t eraddr:16;
+		uint32_t reserved_1_15:15;
+		uint32_t er_en:1;
+	} s;
+	struct cvmx_pcieep_cfg012_s cn52xx;
+	struct cvmx_pcieep_cfg012_s cn52xxp1;
+	struct cvmx_pcieep_cfg012_s cn56xx;
+	struct cvmx_pcieep_cfg012_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg012_mask {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg012_mask_s {
+		uint32_t mask:31;
+		uint32_t enb:1;
+	} s;
+	struct cvmx_pcieep_cfg012_mask_s cn52xx;
+	struct cvmx_pcieep_cfg012_mask_s cn52xxp1;
+	struct cvmx_pcieep_cfg012_mask_s cn56xx;
+	struct cvmx_pcieep_cfg012_mask_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg013 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg013_s {
+		uint32_t reserved_8_31:24;
+		uint32_t cp:8;
+	} s;
+	struct cvmx_pcieep_cfg013_s cn52xx;
+	struct cvmx_pcieep_cfg013_s cn52xxp1;
+	struct cvmx_pcieep_cfg013_s cn56xx;
+	struct cvmx_pcieep_cfg013_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg015 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg015_s {
+		uint32_t ml:8;
+		uint32_t mg:8;
+		uint32_t inta:8;
+		uint32_t il:8;
+	} s;
+	struct cvmx_pcieep_cfg015_s cn52xx;
+	struct cvmx_pcieep_cfg015_s cn52xxp1;
+	struct cvmx_pcieep_cfg015_s cn56xx;
+	struct cvmx_pcieep_cfg015_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg016 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg016_s {
+		uint32_t pmes:5;
+		uint32_t d2s:1;
+		uint32_t d1s:1;
+		uint32_t auxc:3;
+		uint32_t dsi:1;
+		uint32_t reserved_20_20:1;
+		uint32_t pme_clock:1;
+		uint32_t pmsv:3;
+		uint32_t ncp:8;
+		uint32_t pmcid:8;
+	} s;
+	struct cvmx_pcieep_cfg016_s cn52xx;
+	struct cvmx_pcieep_cfg016_s cn52xxp1;
+	struct cvmx_pcieep_cfg016_s cn56xx;
+	struct cvmx_pcieep_cfg016_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg017 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg017_s {
+		uint32_t pmdia:8;
+		uint32_t bpccee:1;
+		uint32_t bd3h:1;
+		uint32_t reserved_16_21:6;
+		uint32_t pmess:1;
+		uint32_t pmedsia:2;
+		uint32_t pmds:4;
+		uint32_t pmeens:1;
+		uint32_t reserved_4_7:4;
+		uint32_t nsr:1;
+		uint32_t reserved_2_2:1;
+		uint32_t ps:2;
+	} s;
+	struct cvmx_pcieep_cfg017_s cn52xx;
+	struct cvmx_pcieep_cfg017_s cn52xxp1;
+	struct cvmx_pcieep_cfg017_s cn56xx;
+	struct cvmx_pcieep_cfg017_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg020 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg020_s {
+		uint32_t reserved_24_31:8;
+		uint32_t m64:1;
+		uint32_t mme:3;
+		uint32_t mmc:3;
+		uint32_t msien:1;
+		uint32_t ncp:8;
+		uint32_t msicid:8;
+	} s;
+	struct cvmx_pcieep_cfg020_s cn52xx;
+	struct cvmx_pcieep_cfg020_s cn52xxp1;
+	struct cvmx_pcieep_cfg020_s cn56xx;
+	struct cvmx_pcieep_cfg020_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg021 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg021_s {
+		uint32_t lmsi:30;
+		uint32_t reserved_0_1:2;
+	} s;
+	struct cvmx_pcieep_cfg021_s cn52xx;
+	struct cvmx_pcieep_cfg021_s cn52xxp1;
+	struct cvmx_pcieep_cfg021_s cn56xx;
+	struct cvmx_pcieep_cfg021_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg022 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg022_s {
+		uint32_t umsi:32;
+	} s;
+	struct cvmx_pcieep_cfg022_s cn52xx;
+	struct cvmx_pcieep_cfg022_s cn52xxp1;
+	struct cvmx_pcieep_cfg022_s cn56xx;
+	struct cvmx_pcieep_cfg022_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg023 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg023_s {
+		uint32_t reserved_16_31:16;
+		uint32_t msimd:16;
+	} s;
+	struct cvmx_pcieep_cfg023_s cn52xx;
+	struct cvmx_pcieep_cfg023_s cn52xxp1;
+	struct cvmx_pcieep_cfg023_s cn56xx;
+	struct cvmx_pcieep_cfg023_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg028 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg028_s {
+		uint32_t reserved_30_31:2;
+		uint32_t imn:5;
+		uint32_t si:1;
+		uint32_t dpt:4;
+		uint32_t pciecv:4;
+		uint32_t ncp:8;
+		uint32_t pcieid:8;
+	} s;
+	struct cvmx_pcieep_cfg028_s cn52xx;
+	struct cvmx_pcieep_cfg028_s cn52xxp1;
+	struct cvmx_pcieep_cfg028_s cn56xx;
+	struct cvmx_pcieep_cfg028_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg029 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg029_s {
+		uint32_t reserved_28_31:4;
+		uint32_t cspls:2;
+		uint32_t csplv:8;
+		uint32_t reserved_16_17:2;
+		uint32_t rber:1;
+		uint32_t reserved_12_14:3;
+		uint32_t el1al:3;
+		uint32_t el0al:3;
+		uint32_t etfs:1;
+		uint32_t pfs:2;
+		uint32_t mpss:3;
+	} s;
+	struct cvmx_pcieep_cfg029_s cn52xx;
+	struct cvmx_pcieep_cfg029_s cn52xxp1;
+	struct cvmx_pcieep_cfg029_s cn56xx;
+	struct cvmx_pcieep_cfg029_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg030 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg030_s {
+		uint32_t reserved_22_31:10;
+		uint32_t tp:1;
+		uint32_t ap_d:1;
+		uint32_t ur_d:1;
+		uint32_t fe_d:1;
+		uint32_t nfe_d:1;
+		uint32_t ce_d:1;
+		uint32_t reserved_15_15:1;
+		uint32_t mrrs:3;
+		uint32_t ns_en:1;
+		uint32_t ap_en:1;
+		uint32_t pf_en:1;
+		uint32_t etf_en:1;
+		uint32_t mps:3;
+		uint32_t ro_en:1;
+		uint32_t ur_en:1;
+		uint32_t fe_en:1;
+		uint32_t nfe_en:1;
+		uint32_t ce_en:1;
+	} s;
+	struct cvmx_pcieep_cfg030_s cn52xx;
+	struct cvmx_pcieep_cfg030_s cn52xxp1;
+	struct cvmx_pcieep_cfg030_s cn56xx;
+	struct cvmx_pcieep_cfg030_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg031 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg031_s {
+		uint32_t pnum:8;
+		uint32_t reserved_22_23:2;
+		uint32_t lbnc:1;
+		uint32_t dllarc:1;
+		uint32_t sderc:1;
+		uint32_t cpm:1;
+		uint32_t l1el:3;
+		uint32_t l0el:3;
+		uint32_t aslpms:2;
+		uint32_t mlw:6;
+		uint32_t mls:4;
+	} s;
+	struct cvmx_pcieep_cfg031_s cn52xx;
+	struct cvmx_pcieep_cfg031_s cn52xxp1;
+	struct cvmx_pcieep_cfg031_s cn56xx;
+	struct cvmx_pcieep_cfg031_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg032 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg032_s {
+		uint32_t reserved_30_31:2;
+		uint32_t dlla:1;
+		uint32_t scc:1;
+		uint32_t lt:1;
+		uint32_t reserved_26_26:1;
+		uint32_t nlw:6;
+		uint32_t ls:4;
+		uint32_t reserved_10_15:6;
+		uint32_t hawd:1;
+		uint32_t ecpm:1;
+		uint32_t es:1;
+		uint32_t ccc:1;
+		uint32_t rl:1;
+		uint32_t ld:1;
+		uint32_t rcb:1;
+		uint32_t reserved_2_2:1;
+		uint32_t aslpc:2;
+	} s;
+	struct cvmx_pcieep_cfg032_s cn52xx;
+	struct cvmx_pcieep_cfg032_s cn52xxp1;
+	struct cvmx_pcieep_cfg032_s cn56xx;
+	struct cvmx_pcieep_cfg032_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg033 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg033_s {
+		uint32_t ps_num:13;
+		uint32_t nccs:1;
+		uint32_t emip:1;
+		uint32_t sp_ls:2;
+		uint32_t sp_lv:8;
+		uint32_t hp_c:1;
+		uint32_t hp_s:1;
+		uint32_t pip:1;
+		uint32_t aip:1;
+		uint32_t mrlsp:1;
+		uint32_t pcp:1;
+		uint32_t abp:1;
+	} s;
+	struct cvmx_pcieep_cfg033_s cn52xx;
+	struct cvmx_pcieep_cfg033_s cn52xxp1;
+	struct cvmx_pcieep_cfg033_s cn56xx;
+	struct cvmx_pcieep_cfg033_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg034 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg034_s {
+		uint32_t reserved_25_31:7;
+		uint32_t dlls_c:1;
+		uint32_t emis:1;
+		uint32_t pds:1;
+		uint32_t mrlss:1;
+		uint32_t ccint_d:1;
+		uint32_t pd_c:1;
+		uint32_t mrls_c:1;
+		uint32_t pf_d:1;
+		uint32_t abp_d:1;
+		uint32_t reserved_13_15:3;
+		uint32_t dlls_en:1;
+		uint32_t emic:1;
+		uint32_t pcc:1;
+		uint32_t pic:2;
+		uint32_t aic:2;
+		uint32_t hpint_en:1;
+		uint32_t ccint_en:1;
+		uint32_t pd_en:1;
+		uint32_t mrls_en:1;
+		uint32_t pf_en:1;
+		uint32_t abp_en:1;
+	} s;
+	struct cvmx_pcieep_cfg034_s cn52xx;
+	struct cvmx_pcieep_cfg034_s cn52xxp1;
+	struct cvmx_pcieep_cfg034_s cn56xx;
+	struct cvmx_pcieep_cfg034_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg037 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg037_s {
+		uint32_t reserved_5_31:27;
+		uint32_t ctds:1;
+		uint32_t ctrs:4;
+	} s;
+	struct cvmx_pcieep_cfg037_s cn52xx;
+	struct cvmx_pcieep_cfg037_s cn52xxp1;
+	struct cvmx_pcieep_cfg037_s cn56xx;
+	struct cvmx_pcieep_cfg037_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg038 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg038_s {
+		uint32_t reserved_5_31:27;
+		uint32_t ctd:1;
+		uint32_t ctv:4;
+	} s;
+	struct cvmx_pcieep_cfg038_s cn52xx;
+	struct cvmx_pcieep_cfg038_s cn52xxp1;
+	struct cvmx_pcieep_cfg038_s cn56xx;
+	struct cvmx_pcieep_cfg038_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg039 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg039_s {
+		uint32_t reserved_0_31:32;
+	} s;
+	struct cvmx_pcieep_cfg039_s cn52xx;
+	struct cvmx_pcieep_cfg039_s cn52xxp1;
+	struct cvmx_pcieep_cfg039_s cn56xx;
+	struct cvmx_pcieep_cfg039_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg040 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg040_s {
+		uint32_t reserved_0_31:32;
+	} s;
+	struct cvmx_pcieep_cfg040_s cn52xx;
+	struct cvmx_pcieep_cfg040_s cn52xxp1;
+	struct cvmx_pcieep_cfg040_s cn56xx;
+	struct cvmx_pcieep_cfg040_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg041 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg041_s {
+		uint32_t reserved_0_31:32;
+	} s;
+	struct cvmx_pcieep_cfg041_s cn52xx;
+	struct cvmx_pcieep_cfg041_s cn52xxp1;
+	struct cvmx_pcieep_cfg041_s cn56xx;
+	struct cvmx_pcieep_cfg041_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg042 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg042_s {
+		uint32_t reserved_0_31:32;
+	} s;
+	struct cvmx_pcieep_cfg042_s cn52xx;
+	struct cvmx_pcieep_cfg042_s cn52xxp1;
+	struct cvmx_pcieep_cfg042_s cn56xx;
+	struct cvmx_pcieep_cfg042_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg064 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg064_s {
+		uint32_t nco:12;
+		uint32_t cv:4;
+		uint32_t pcieec:16;
+	} s;
+	struct cvmx_pcieep_cfg064_s cn52xx;
+	struct cvmx_pcieep_cfg064_s cn52xxp1;
+	struct cvmx_pcieep_cfg064_s cn56xx;
+	struct cvmx_pcieep_cfg064_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg065 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg065_s {
+		uint32_t reserved_21_31:11;
+		uint32_t ures:1;
+		uint32_t ecrces:1;
+		uint32_t mtlps:1;
+		uint32_t ros:1;
+		uint32_t ucs:1;
+		uint32_t cas:1;
+		uint32_t cts:1;
+		uint32_t fcpes:1;
+		uint32_t ptlps:1;
+		uint32_t reserved_6_11:6;
+		uint32_t sdes:1;
+		uint32_t dlpes:1;
+		uint32_t reserved_0_3:4;
+	} s;
+	struct cvmx_pcieep_cfg065_s cn52xx;
+	struct cvmx_pcieep_cfg065_s cn52xxp1;
+	struct cvmx_pcieep_cfg065_s cn56xx;
+	struct cvmx_pcieep_cfg065_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg066 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg066_s {
+		uint32_t reserved_21_31:11;
+		uint32_t urem:1;
+		uint32_t ecrcem:1;
+		uint32_t mtlpm:1;
+		uint32_t rom:1;
+		uint32_t ucm:1;
+		uint32_t cam:1;
+		uint32_t ctm:1;
+		uint32_t fcpem:1;
+		uint32_t ptlpm:1;
+		uint32_t reserved_6_11:6;
+		uint32_t sdem:1;
+		uint32_t dlpem:1;
+		uint32_t reserved_0_3:4;
+	} s;
+	struct cvmx_pcieep_cfg066_s cn52xx;
+	struct cvmx_pcieep_cfg066_s cn52xxp1;
+	struct cvmx_pcieep_cfg066_s cn56xx;
+	struct cvmx_pcieep_cfg066_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg067 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg067_s {
+		uint32_t reserved_21_31:11;
+		uint32_t ures:1;
+		uint32_t ecrces:1;
+		uint32_t mtlps:1;
+		uint32_t ros:1;
+		uint32_t ucs:1;
+		uint32_t cas:1;
+		uint32_t cts:1;
+		uint32_t fcpes:1;
+		uint32_t ptlps:1;
+		uint32_t reserved_6_11:6;
+		uint32_t sdes:1;
+		uint32_t dlpes:1;
+		uint32_t reserved_0_3:4;
+	} s;
+	struct cvmx_pcieep_cfg067_s cn52xx;
+	struct cvmx_pcieep_cfg067_s cn52xxp1;
+	struct cvmx_pcieep_cfg067_s cn56xx;
+	struct cvmx_pcieep_cfg067_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg068 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg068_s {
+		uint32_t reserved_14_31:18;
+		uint32_t anfes:1;
+		uint32_t rtts:1;
+		uint32_t reserved_9_11:3;
+		uint32_t rnrs:1;
+		uint32_t bdllps:1;
+		uint32_t btlps:1;
+		uint32_t reserved_1_5:5;
+		uint32_t res:1;
+	} s;
+	struct cvmx_pcieep_cfg068_s cn52xx;
+	struct cvmx_pcieep_cfg068_s cn52xxp1;
+	struct cvmx_pcieep_cfg068_s cn56xx;
+	struct cvmx_pcieep_cfg068_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg069 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg069_s {
+		uint32_t reserved_14_31:18;
+		uint32_t anfem:1;
+		uint32_t rttm:1;
+		uint32_t reserved_9_11:3;
+		uint32_t rnrm:1;
+		uint32_t bdllpm:1;
+		uint32_t btlpm:1;
+		uint32_t reserved_1_5:5;
+		uint32_t rem:1;
+	} s;
+	struct cvmx_pcieep_cfg069_s cn52xx;
+	struct cvmx_pcieep_cfg069_s cn52xxp1;
+	struct cvmx_pcieep_cfg069_s cn56xx;
+	struct cvmx_pcieep_cfg069_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg070 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg070_s {
+		uint32_t reserved_9_31:23;
+		uint32_t ce:1;
+		uint32_t cc:1;
+		uint32_t ge:1;
+		uint32_t gc:1;
+		uint32_t fep:5;
+	} s;
+	struct cvmx_pcieep_cfg070_s cn52xx;
+	struct cvmx_pcieep_cfg070_s cn52xxp1;
+	struct cvmx_pcieep_cfg070_s cn56xx;
+	struct cvmx_pcieep_cfg070_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg071 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg071_s {
+		uint32_t dword1:32;
+	} s;
+	struct cvmx_pcieep_cfg071_s cn52xx;
+	struct cvmx_pcieep_cfg071_s cn52xxp1;
+	struct cvmx_pcieep_cfg071_s cn56xx;
+	struct cvmx_pcieep_cfg071_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg072 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg072_s {
+		uint32_t dword2:32;
+	} s;
+	struct cvmx_pcieep_cfg072_s cn52xx;
+	struct cvmx_pcieep_cfg072_s cn52xxp1;
+	struct cvmx_pcieep_cfg072_s cn56xx;
+	struct cvmx_pcieep_cfg072_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg073 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg073_s {
+		uint32_t dword3:32;
+	} s;
+	struct cvmx_pcieep_cfg073_s cn52xx;
+	struct cvmx_pcieep_cfg073_s cn52xxp1;
+	struct cvmx_pcieep_cfg073_s cn56xx;
+	struct cvmx_pcieep_cfg073_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg074 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg074_s {
+		uint32_t dword4:32;
+	} s;
+	struct cvmx_pcieep_cfg074_s cn52xx;
+	struct cvmx_pcieep_cfg074_s cn52xxp1;
+	struct cvmx_pcieep_cfg074_s cn56xx;
+	struct cvmx_pcieep_cfg074_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg448 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg448_s {
+		uint32_t rtl:16;
+		uint32_t rtltl:16;
+	} s;
+	struct cvmx_pcieep_cfg448_s cn52xx;
+	struct cvmx_pcieep_cfg448_s cn52xxp1;
+	struct cvmx_pcieep_cfg448_s cn56xx;
+	struct cvmx_pcieep_cfg448_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg449 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg449_s {
+		uint32_t omr:32;
+	} s;
+	struct cvmx_pcieep_cfg449_s cn52xx;
+	struct cvmx_pcieep_cfg449_s cn52xxp1;
+	struct cvmx_pcieep_cfg449_s cn56xx;
+	struct cvmx_pcieep_cfg449_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg450 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg450_s {
+		uint32_t lpec:8;
+		uint32_t reserved_22_23:2;
+		uint32_t link_state:6;
+		uint32_t force_link:1;
+		uint32_t reserved_8_14:7;
+		uint32_t link_num:8;
+	} s;
+	struct cvmx_pcieep_cfg450_s cn52xx;
+	struct cvmx_pcieep_cfg450_s cn52xxp1;
+	struct cvmx_pcieep_cfg450_s cn56xx;
+	struct cvmx_pcieep_cfg450_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg451 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg451_s {
+		uint32_t reserved_30_31:2;
+		uint32_t l1el:3;
+		uint32_t l0el:3;
+		uint32_t n_fts_cc:8;
+		uint32_t n_fts:8;
+		uint32_t ack_freq:8;
+	} s;
+	struct cvmx_pcieep_cfg451_s cn52xx;
+	struct cvmx_pcieep_cfg451_s cn52xxp1;
+	struct cvmx_pcieep_cfg451_s cn56xx;
+	struct cvmx_pcieep_cfg451_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg452 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg452_s {
+		uint32_t reserved_26_31:6;
+		uint32_t eccrc:1;
+		uint32_t reserved_22_24:3;
+		uint32_t lme:6;
+		uint32_t reserved_8_15:8;
+		uint32_t flm:1;
+		uint32_t reserved_6_6:1;
+		uint32_t dllle:1;
+		uint32_t reserved_4_4:1;
+		uint32_t ra:1;
+		uint32_t le:1;
+		uint32_t sd:1;
+		uint32_t omr:1;
+	} s;
+	struct cvmx_pcieep_cfg452_s cn52xx;
+	struct cvmx_pcieep_cfg452_s cn52xxp1;
+	struct cvmx_pcieep_cfg452_s cn56xx;
+	struct cvmx_pcieep_cfg452_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg453 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg453_s {
+		uint32_t dlld:1;
+		uint32_t reserved_26_30:5;
+		uint32_t ack_nak:1;
+		uint32_t fcd:1;
+		uint32_t ilst:24;
+	} s;
+	struct cvmx_pcieep_cfg453_s cn52xx;
+	struct cvmx_pcieep_cfg453_s cn52xxp1;
+	struct cvmx_pcieep_cfg453_s cn56xx;
+	struct cvmx_pcieep_cfg453_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg454 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg454_s {
+		uint32_t reserved_29_31:3;
+		uint32_t tmfcwt:5;
+		uint32_t tmanlt:5;
+		uint32_t tmrt:5;
+		uint32_t reserved_11_13:3;
+		uint32_t nskps:3;
+		uint32_t reserved_4_7:4;
+		uint32_t ntss:4;
+	} s;
+	struct cvmx_pcieep_cfg454_s cn52xx;
+	struct cvmx_pcieep_cfg454_s cn52xxp1;
+	struct cvmx_pcieep_cfg454_s cn56xx;
+	struct cvmx_pcieep_cfg454_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg455 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg455_s {
+		uint32_t m_cfg0_filt:1;
+		uint32_t m_io_filt:1;
+		uint32_t msg_ctrl:1;
+		uint32_t m_cpl_ecrc_filt:1;
+		uint32_t m_ecrc_filt:1;
+		uint32_t m_cpl_len_err:1;
+		uint32_t m_cpl_attr_err:1;
+		uint32_t m_cpl_tc_err:1;
+		uint32_t m_cpl_fun_err:1;
+		uint32_t m_cpl_rid_err:1;
+		uint32_t m_cpl_tag_err:1;
+		uint32_t m_lk_filt:1;
+		uint32_t m_cfg1_filt:1;
+		uint32_t m_bar_match:1;
+		uint32_t m_pois_filt:1;
+		uint32_t m_fun:1;
+		uint32_t dfcwt:1;
+		uint32_t reserved_11_14:4;
+		uint32_t skpiv:11;
+	} s;
+	struct cvmx_pcieep_cfg455_s cn52xx;
+	struct cvmx_pcieep_cfg455_s cn52xxp1;
+	struct cvmx_pcieep_cfg455_s cn56xx;
+	struct cvmx_pcieep_cfg455_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg456 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg456_s {
+		uint32_t reserved_2_31:30;
+		uint32_t m_vend1_drp:1;
+		uint32_t m_vend0_drp:1;
+	} s;
+	struct cvmx_pcieep_cfg456_s cn52xx;
+	struct cvmx_pcieep_cfg456_s cn52xxp1;
+	struct cvmx_pcieep_cfg456_s cn56xx;
+	struct cvmx_pcieep_cfg456_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg458 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg458_s {
+		uint32_t dbg_info_l32:32;
+	} s;
+	struct cvmx_pcieep_cfg458_s cn52xx;
+	struct cvmx_pcieep_cfg458_s cn52xxp1;
+	struct cvmx_pcieep_cfg458_s cn56xx;
+	struct cvmx_pcieep_cfg458_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg459 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg459_s {
+		uint32_t dbg_info_u32:32;
+	} s;
+	struct cvmx_pcieep_cfg459_s cn52xx;
+	struct cvmx_pcieep_cfg459_s cn52xxp1;
+	struct cvmx_pcieep_cfg459_s cn56xx;
+	struct cvmx_pcieep_cfg459_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg460 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg460_s {
+		uint32_t reserved_20_31:12;
+		uint32_t tphfcc:8;
+		uint32_t tpdfcc:12;
+	} s;
+	struct cvmx_pcieep_cfg460_s cn52xx;
+	struct cvmx_pcieep_cfg460_s cn52xxp1;
+	struct cvmx_pcieep_cfg460_s cn56xx;
+	struct cvmx_pcieep_cfg460_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg461 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg461_s {
+		uint32_t reserved_20_31:12;
+		uint32_t tchfcc:8;
+		uint32_t tcdfcc:12;
+	} s;
+	struct cvmx_pcieep_cfg461_s cn52xx;
+	struct cvmx_pcieep_cfg461_s cn52xxp1;
+	struct cvmx_pcieep_cfg461_s cn56xx;
+	struct cvmx_pcieep_cfg461_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg462 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg462_s {
+		uint32_t reserved_20_31:12;
+		uint32_t tchfcc:8;
+		uint32_t tcdfcc:12;
+	} s;
+	struct cvmx_pcieep_cfg462_s cn52xx;
+	struct cvmx_pcieep_cfg462_s cn52xxp1;
+	struct cvmx_pcieep_cfg462_s cn56xx;
+	struct cvmx_pcieep_cfg462_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg463 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg463_s {
+		uint32_t reserved_3_31:29;
+		uint32_t rqne:1;
+		uint32_t trbne:1;
+		uint32_t rtlpfccnr:1;
+	} s;
+	struct cvmx_pcieep_cfg463_s cn52xx;
+	struct cvmx_pcieep_cfg463_s cn52xxp1;
+	struct cvmx_pcieep_cfg463_s cn56xx;
+	struct cvmx_pcieep_cfg463_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg464 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg464_s {
+		uint32_t wrr_vc3:8;
+		uint32_t wrr_vc2:8;
+		uint32_t wrr_vc1:8;
+		uint32_t wrr_vc0:8;
+	} s;
+	struct cvmx_pcieep_cfg464_s cn52xx;
+	struct cvmx_pcieep_cfg464_s cn52xxp1;
+	struct cvmx_pcieep_cfg464_s cn56xx;
+	struct cvmx_pcieep_cfg464_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg465 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg465_s {
+		uint32_t wrr_vc7:8;
+		uint32_t wrr_vc6:8;
+		uint32_t wrr_vc5:8;
+		uint32_t wrr_vc4:8;
+	} s;
+	struct cvmx_pcieep_cfg465_s cn52xx;
+	struct cvmx_pcieep_cfg465_s cn52xxp1;
+	struct cvmx_pcieep_cfg465_s cn56xx;
+	struct cvmx_pcieep_cfg465_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg466 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg466_s {
+		uint32_t rx_queue_order:1;
+		uint32_t type_ordering:1;
+		uint32_t reserved_24_29:6;
+		uint32_t queue_mode:3;
+		uint32_t reserved_20_20:1;
+		uint32_t header_credits:8;
+		uint32_t data_credits:12;
+	} s;
+	struct cvmx_pcieep_cfg466_s cn52xx;
+	struct cvmx_pcieep_cfg466_s cn52xxp1;
+	struct cvmx_pcieep_cfg466_s cn56xx;
+	struct cvmx_pcieep_cfg466_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg467 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg467_s {
+		uint32_t reserved_24_31:8;
+		uint32_t queue_mode:3;
+		uint32_t reserved_20_20:1;
+		uint32_t header_credits:8;
+		uint32_t data_credits:12;
+	} s;
+	struct cvmx_pcieep_cfg467_s cn52xx;
+	struct cvmx_pcieep_cfg467_s cn52xxp1;
+	struct cvmx_pcieep_cfg467_s cn56xx;
+	struct cvmx_pcieep_cfg467_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg468 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg468_s {
+		uint32_t reserved_24_31:8;
+		uint32_t queue_mode:3;
+		uint32_t reserved_20_20:1;
+		uint32_t header_credits:8;
+		uint32_t data_credits:12;
+	} s;
+	struct cvmx_pcieep_cfg468_s cn52xx;
+	struct cvmx_pcieep_cfg468_s cn52xxp1;
+	struct cvmx_pcieep_cfg468_s cn56xx;
+	struct cvmx_pcieep_cfg468_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg490 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg490_s {
+		uint32_t reserved_26_31:6;
+		uint32_t header_depth:10;
+		uint32_t reserved_14_15:2;
+		uint32_t data_depth:14;
+	} s;
+	struct cvmx_pcieep_cfg490_s cn52xx;
+	struct cvmx_pcieep_cfg490_s cn52xxp1;
+	struct cvmx_pcieep_cfg490_s cn56xx;
+	struct cvmx_pcieep_cfg490_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg491 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg491_s {
+		uint32_t reserved_26_31:6;
+		uint32_t header_depth:10;
+		uint32_t reserved_14_15:2;
+		uint32_t data_depth:14;
+	} s;
+	struct cvmx_pcieep_cfg491_s cn52xx;
+	struct cvmx_pcieep_cfg491_s cn52xxp1;
+	struct cvmx_pcieep_cfg491_s cn56xx;
+	struct cvmx_pcieep_cfg491_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg492 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg492_s {
+		uint32_t reserved_26_31:6;
+		uint32_t header_depth:10;
+		uint32_t reserved_14_15:2;
+		uint32_t data_depth:14;
+	} s;
+	struct cvmx_pcieep_cfg492_s cn52xx;
+	struct cvmx_pcieep_cfg492_s cn52xxp1;
+	struct cvmx_pcieep_cfg492_s cn56xx;
+	struct cvmx_pcieep_cfg492_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg516 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg516_s {
+		uint32_t phy_stat:32;
+	} s;
+	struct cvmx_pcieep_cfg516_s cn52xx;
+	struct cvmx_pcieep_cfg516_s cn52xxp1;
+	struct cvmx_pcieep_cfg516_s cn56xx;
+	struct cvmx_pcieep_cfg516_s cn56xxp1;
+};
+
+union cvmx_pcieep_cfg517 {
+	uint32_t u32;
+	struct cvmx_pcieep_cfg517_s {
+		uint32_t phy_ctrl:32;
+	} s;
+	struct cvmx_pcieep_cfg517_s cn52xx;
+	struct cvmx_pcieep_cfg517_s cn52xxp1;
+	struct cvmx_pcieep_cfg517_s cn56xx;
+	struct cvmx_pcieep_cfg517_s cn56xxp1;
+};
+
+#endif
diff --git a/arch/mips/include/asm/octeon/cvmx-pciercx-defs.h b/arch/mips/include/asm/octeon/cvmx-pciercx-defs.h
new file mode 100644
index 0000000..75574c9
--- /dev/null
+++ b/arch/mips/include/asm/octeon/cvmx-pciercx-defs.h
@@ -0,0 +1,1397 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_PCIERCX_DEFS_H__
+#define __CVMX_PCIERCX_DEFS_H__
+
+#define CVMX_PCIERCX_CFG000(offset) \
+	 (0x0000000000000000ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG001(offset) \
+	 (0x0000000000000004ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG002(offset) \
+	 (0x0000000000000008ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG003(offset) \
+	 (0x000000000000000Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG004(offset) \
+	 (0x0000000000000010ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG005(offset) \
+	 (0x0000000000000014ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG006(offset) \
+	 (0x0000000000000018ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG007(offset) \
+	 (0x000000000000001Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG008(offset) \
+	 (0x0000000000000020ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG009(offset) \
+	 (0x0000000000000024ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG010(offset) \
+	 (0x0000000000000028ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG011(offset) \
+	 (0x000000000000002Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG012(offset) \
+	 (0x0000000000000030ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG013(offset) \
+	 (0x0000000000000034ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG014(offset) \
+	 (0x0000000000000038ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG015(offset) \
+	 (0x000000000000003Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG016(offset) \
+	 (0x0000000000000040ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG017(offset) \
+	 (0x0000000000000044ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG020(offset) \
+	 (0x0000000000000050ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG021(offset) \
+	 (0x0000000000000054ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG022(offset) \
+	 (0x0000000000000058ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG023(offset) \
+	 (0x000000000000005Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG028(offset) \
+	 (0x0000000000000070ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG029(offset) \
+	 (0x0000000000000074ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG030(offset) \
+	 (0x0000000000000078ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG031(offset) \
+	 (0x000000000000007Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG032(offset) \
+	 (0x0000000000000080ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG033(offset) \
+	 (0x0000000000000084ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG034(offset) \
+	 (0x0000000000000088ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG035(offset) \
+	 (0x000000000000008Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG036(offset) \
+	 (0x0000000000000090ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG037(offset) \
+	 (0x0000000000000094ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG038(offset) \
+	 (0x0000000000000098ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG039(offset) \
+	 (0x000000000000009Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG040(offset) \
+	 (0x00000000000000A0ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG041(offset) \
+	 (0x00000000000000A4ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG042(offset) \
+	 (0x00000000000000A8ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG064(offset) \
+	 (0x0000000000000100ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG065(offset) \
+	 (0x0000000000000104ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG066(offset) \
+	 (0x0000000000000108ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG067(offset) \
+	 (0x000000000000010Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG068(offset) \
+	 (0x0000000000000110ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG069(offset) \
+	 (0x0000000000000114ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG070(offset) \
+	 (0x0000000000000118ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG071(offset) \
+	 (0x000000000000011Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG072(offset) \
+	 (0x0000000000000120ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG073(offset) \
+	 (0x0000000000000124ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG074(offset) \
+	 (0x0000000000000128ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG075(offset) \
+	 (0x000000000000012Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG076(offset) \
+	 (0x0000000000000130ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG077(offset) \
+	 (0x0000000000000134ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG448(offset) \
+	 (0x0000000000000700ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG449(offset) \
+	 (0x0000000000000704ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG450(offset) \
+	 (0x0000000000000708ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG451(offset) \
+	 (0x000000000000070Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG452(offset) \
+	 (0x0000000000000710ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG453(offset) \
+	 (0x0000000000000714ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG454(offset) \
+	 (0x0000000000000718ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG455(offset) \
+	 (0x000000000000071Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG456(offset) \
+	 (0x0000000000000720ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG458(offset) \
+	 (0x0000000000000728ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG459(offset) \
+	 (0x000000000000072Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG460(offset) \
+	 (0x0000000000000730ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG461(offset) \
+	 (0x0000000000000734ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG462(offset) \
+	 (0x0000000000000738ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG463(offset) \
+	 (0x000000000000073Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG464(offset) \
+	 (0x0000000000000740ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG465(offset) \
+	 (0x0000000000000744ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG466(offset) \
+	 (0x0000000000000748ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG467(offset) \
+	 (0x000000000000074Cull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG468(offset) \
+	 (0x0000000000000750ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG490(offset) \
+	 (0x00000000000007A8ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG491(offset) \
+	 (0x00000000000007ACull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG492(offset) \
+	 (0x00000000000007B0ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG516(offset) \
+	 (0x0000000000000810ull + (((offset) & 1) * 0))
+#define CVMX_PCIERCX_CFG517(offset) \
+	 (0x0000000000000814ull + (((offset) & 1) * 0))
+
+union cvmx_pciercx_cfg000 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg000_s {
+		uint32_t devid:16;
+		uint32_t vendid:16;
+	} s;
+	struct cvmx_pciercx_cfg000_s cn52xx;
+	struct cvmx_pciercx_cfg000_s cn52xxp1;
+	struct cvmx_pciercx_cfg000_s cn56xx;
+	struct cvmx_pciercx_cfg000_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg001 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg001_s {
+		uint32_t dpe:1;
+		uint32_t sse:1;
+		uint32_t rma:1;
+		uint32_t rta:1;
+		uint32_t sta:1;
+		uint32_t devt:2;
+		uint32_t mdpe:1;
+		uint32_t fbb:1;
+		uint32_t reserved_22_22:1;
+		uint32_t m66:1;
+		uint32_t cl:1;
+		uint32_t i_stat:1;
+		uint32_t reserved_11_18:8;
+		uint32_t i_dis:1;
+		uint32_t fbbe:1;
+		uint32_t see:1;
+		uint32_t ids_wcc:1;
+		uint32_t per:1;
+		uint32_t vps:1;
+		uint32_t mwice:1;
+		uint32_t scse:1;
+		uint32_t me:1;
+		uint32_t msae:1;
+		uint32_t isae:1;
+	} s;
+	struct cvmx_pciercx_cfg001_s cn52xx;
+	struct cvmx_pciercx_cfg001_s cn52xxp1;
+	struct cvmx_pciercx_cfg001_s cn56xx;
+	struct cvmx_pciercx_cfg001_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg002 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg002_s {
+		uint32_t bcc:8;
+		uint32_t sc:8;
+		uint32_t pi:8;
+		uint32_t rid:8;
+	} s;
+	struct cvmx_pciercx_cfg002_s cn52xx;
+	struct cvmx_pciercx_cfg002_s cn52xxp1;
+	struct cvmx_pciercx_cfg002_s cn56xx;
+	struct cvmx_pciercx_cfg002_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg003 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg003_s {
+		uint32_t bist:8;
+		uint32_t mfd:1;
+		uint32_t chf:7;
+		uint32_t lt:8;
+		uint32_t cls:8;
+	} s;
+	struct cvmx_pciercx_cfg003_s cn52xx;
+	struct cvmx_pciercx_cfg003_s cn52xxp1;
+	struct cvmx_pciercx_cfg003_s cn56xx;
+	struct cvmx_pciercx_cfg003_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg004 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg004_s {
+		uint32_t reserved_0_31:32;
+	} s;
+	struct cvmx_pciercx_cfg004_s cn52xx;
+	struct cvmx_pciercx_cfg004_s cn52xxp1;
+	struct cvmx_pciercx_cfg004_s cn56xx;
+	struct cvmx_pciercx_cfg004_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg005 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg005_s {
+		uint32_t reserved_0_31:32;
+	} s;
+	struct cvmx_pciercx_cfg005_s cn52xx;
+	struct cvmx_pciercx_cfg005_s cn52xxp1;
+	struct cvmx_pciercx_cfg005_s cn56xx;
+	struct cvmx_pciercx_cfg005_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg006 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg006_s {
+		uint32_t slt:8;
+		uint32_t subbnum:8;
+		uint32_t sbnum:8;
+		uint32_t pbnum:8;
+	} s;
+	struct cvmx_pciercx_cfg006_s cn52xx;
+	struct cvmx_pciercx_cfg006_s cn52xxp1;
+	struct cvmx_pciercx_cfg006_s cn56xx;
+	struct cvmx_pciercx_cfg006_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg007 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg007_s {
+		uint32_t dpe:1;
+		uint32_t sse:1;
+		uint32_t rma:1;
+		uint32_t rta:1;
+		uint32_t sta:1;
+		uint32_t devt:2;
+		uint32_t mdpe:1;
+		uint32_t fbb:1;
+		uint32_t reserved_22_22:1;
+		uint32_t m66:1;
+		uint32_t reserved_16_20:5;
+		uint32_t lio_limi:4;
+		uint32_t reserved_9_11:3;
+		uint32_t io32b:1;
+		uint32_t lio_base:4;
+		uint32_t reserved_1_3:3;
+		uint32_t io32a:1;
+	} s;
+	struct cvmx_pciercx_cfg007_s cn52xx;
+	struct cvmx_pciercx_cfg007_s cn52xxp1;
+	struct cvmx_pciercx_cfg007_s cn56xx;
+	struct cvmx_pciercx_cfg007_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg008 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg008_s {
+		uint32_t ml_addr:12;
+		uint32_t reserved_16_19:4;
+		uint32_t mb_addr:12;
+		uint32_t reserved_0_3:4;
+	} s;
+	struct cvmx_pciercx_cfg008_s cn52xx;
+	struct cvmx_pciercx_cfg008_s cn52xxp1;
+	struct cvmx_pciercx_cfg008_s cn56xx;
+	struct cvmx_pciercx_cfg008_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg009 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg009_s {
+		uint32_t lmem_limit:12;
+		uint32_t reserved_17_19:3;
+		uint32_t mem64b:1;
+		uint32_t lmem_base:12;
+		uint32_t reserved_1_3:3;
+		uint32_t mem64a:1;
+	} s;
+	struct cvmx_pciercx_cfg009_s cn52xx;
+	struct cvmx_pciercx_cfg009_s cn52xxp1;
+	struct cvmx_pciercx_cfg009_s cn56xx;
+	struct cvmx_pciercx_cfg009_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg010 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg010_s {
+		uint32_t umem_base:32;
+	} s;
+	struct cvmx_pciercx_cfg010_s cn52xx;
+	struct cvmx_pciercx_cfg010_s cn52xxp1;
+	struct cvmx_pciercx_cfg010_s cn56xx;
+	struct cvmx_pciercx_cfg010_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg011 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg011_s {
+		uint32_t umem_limit:32;
+	} s;
+	struct cvmx_pciercx_cfg011_s cn52xx;
+	struct cvmx_pciercx_cfg011_s cn52xxp1;
+	struct cvmx_pciercx_cfg011_s cn56xx;
+	struct cvmx_pciercx_cfg011_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg012 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg012_s {
+		uint32_t uio_limit:16;
+		uint32_t uio_base:16;
+	} s;
+	struct cvmx_pciercx_cfg012_s cn52xx;
+	struct cvmx_pciercx_cfg012_s cn52xxp1;
+	struct cvmx_pciercx_cfg012_s cn56xx;
+	struct cvmx_pciercx_cfg012_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg013 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg013_s {
+		uint32_t reserved_8_31:24;
+		uint32_t cp:8;
+	} s;
+	struct cvmx_pciercx_cfg013_s cn52xx;
+	struct cvmx_pciercx_cfg013_s cn52xxp1;
+	struct cvmx_pciercx_cfg013_s cn56xx;
+	struct cvmx_pciercx_cfg013_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg014 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg014_s {
+		uint32_t reserved_0_31:32;
+	} s;
+	struct cvmx_pciercx_cfg014_s cn52xx;
+	struct cvmx_pciercx_cfg014_s cn52xxp1;
+	struct cvmx_pciercx_cfg014_s cn56xx;
+	struct cvmx_pciercx_cfg014_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg015 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg015_s {
+		uint32_t reserved_28_31:4;
+		uint32_t dtsees:1;
+		uint32_t dts:1;
+		uint32_t sdt:1;
+		uint32_t pdt:1;
+		uint32_t fbbe:1;
+		uint32_t sbrst:1;
+		uint32_t mam:1;
+		uint32_t vga16d:1;
+		uint32_t vgae:1;
+		uint32_t isae:1;
+		uint32_t see:1;
+		uint32_t pere:1;
+		uint32_t inta:8;
+		uint32_t il:8;
+	} s;
+	struct cvmx_pciercx_cfg015_s cn52xx;
+	struct cvmx_pciercx_cfg015_s cn52xxp1;
+	struct cvmx_pciercx_cfg015_s cn56xx;
+	struct cvmx_pciercx_cfg015_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg016 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg016_s {
+		uint32_t pmes:5;
+		uint32_t d2s:1;
+		uint32_t d1s:1;
+		uint32_t auxc:3;
+		uint32_t dsi:1;
+		uint32_t reserved_20_20:1;
+		uint32_t pme_clock:1;
+		uint32_t pmsv:3;
+		uint32_t ncp:8;
+		uint32_t pmcid:8;
+	} s;
+	struct cvmx_pciercx_cfg016_s cn52xx;
+	struct cvmx_pciercx_cfg016_s cn52xxp1;
+	struct cvmx_pciercx_cfg016_s cn56xx;
+	struct cvmx_pciercx_cfg016_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg017 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg017_s {
+		uint32_t pmdia:8;
+		uint32_t bpccee:1;
+		uint32_t bd3h:1;
+		uint32_t reserved_16_21:6;
+		uint32_t pmess:1;
+		uint32_t pmedsia:2;
+		uint32_t pmds:4;
+		uint32_t pmeens:1;
+		uint32_t reserved_4_7:4;
+		uint32_t nsr:1;
+		uint32_t reserved_2_2:1;
+		uint32_t ps:2;
+	} s;
+	struct cvmx_pciercx_cfg017_s cn52xx;
+	struct cvmx_pciercx_cfg017_s cn52xxp1;
+	struct cvmx_pciercx_cfg017_s cn56xx;
+	struct cvmx_pciercx_cfg017_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg020 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg020_s {
+		uint32_t reserved_24_31:8;
+		uint32_t m64:1;
+		uint32_t mme:3;
+		uint32_t mmc:3;
+		uint32_t msien:1;
+		uint32_t ncp:8;
+		uint32_t msicid:8;
+	} s;
+	struct cvmx_pciercx_cfg020_s cn52xx;
+	struct cvmx_pciercx_cfg020_s cn52xxp1;
+	struct cvmx_pciercx_cfg020_s cn56xx;
+	struct cvmx_pciercx_cfg020_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg021 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg021_s {
+		uint32_t lmsi:30;
+		uint32_t reserved_0_1:2;
+	} s;
+	struct cvmx_pciercx_cfg021_s cn52xx;
+	struct cvmx_pciercx_cfg021_s cn52xxp1;
+	struct cvmx_pciercx_cfg021_s cn56xx;
+	struct cvmx_pciercx_cfg021_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg022 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg022_s {
+		uint32_t umsi:32;
+	} s;
+	struct cvmx_pciercx_cfg022_s cn52xx;
+	struct cvmx_pciercx_cfg022_s cn52xxp1;
+	struct cvmx_pciercx_cfg022_s cn56xx;
+	struct cvmx_pciercx_cfg022_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg023 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg023_s {
+		uint32_t reserved_16_31:16;
+		uint32_t msimd:16;
+	} s;
+	struct cvmx_pciercx_cfg023_s cn52xx;
+	struct cvmx_pciercx_cfg023_s cn52xxp1;
+	struct cvmx_pciercx_cfg023_s cn56xx;
+	struct cvmx_pciercx_cfg023_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg028 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg028_s {
+		uint32_t reserved_30_31:2;
+		uint32_t imn:5;
+		uint32_t si:1;
+		uint32_t dpt:4;
+		uint32_t pciecv:4;
+		uint32_t ncp:8;
+		uint32_t pcieid:8;
+	} s;
+	struct cvmx_pciercx_cfg028_s cn52xx;
+	struct cvmx_pciercx_cfg028_s cn52xxp1;
+	struct cvmx_pciercx_cfg028_s cn56xx;
+	struct cvmx_pciercx_cfg028_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg029 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg029_s {
+		uint32_t reserved_28_31:4;
+		uint32_t cspls:2;
+		uint32_t csplv:8;
+		uint32_t reserved_16_17:2;
+		uint32_t rber:1;
+		uint32_t reserved_12_14:3;
+		uint32_t el1al:3;
+		uint32_t el0al:3;
+		uint32_t etfs:1;
+		uint32_t pfs:2;
+		uint32_t mpss:3;
+	} s;
+	struct cvmx_pciercx_cfg029_s cn52xx;
+	struct cvmx_pciercx_cfg029_s cn52xxp1;
+	struct cvmx_pciercx_cfg029_s cn56xx;
+	struct cvmx_pciercx_cfg029_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg030 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg030_s {
+		uint32_t reserved_22_31:10;
+		uint32_t tp:1;
+		uint32_t ap_d:1;
+		uint32_t ur_d:1;
+		uint32_t fe_d:1;
+		uint32_t nfe_d:1;
+		uint32_t ce_d:1;
+		uint32_t reserved_15_15:1;
+		uint32_t mrrs:3;
+		uint32_t ns_en:1;
+		uint32_t ap_en:1;
+		uint32_t pf_en:1;
+		uint32_t etf_en:1;
+		uint32_t mps:3;
+		uint32_t ro_en:1;
+		uint32_t ur_en:1;
+		uint32_t fe_en:1;
+		uint32_t nfe_en:1;
+		uint32_t ce_en:1;
+	} s;
+	struct cvmx_pciercx_cfg030_s cn52xx;
+	struct cvmx_pciercx_cfg030_s cn52xxp1;
+	struct cvmx_pciercx_cfg030_s cn56xx;
+	struct cvmx_pciercx_cfg030_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg031 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg031_s {
+		uint32_t pnum:8;
+		uint32_t reserved_22_23:2;
+		uint32_t lbnc:1;
+		uint32_t dllarc:1;
+		uint32_t sderc:1;
+		uint32_t cpm:1;
+		uint32_t l1el:3;
+		uint32_t l0el:3;
+		uint32_t aslpms:2;
+		uint32_t mlw:6;
+		uint32_t mls:4;
+	} s;
+	struct cvmx_pciercx_cfg031_s cn52xx;
+	struct cvmx_pciercx_cfg031_s cn52xxp1;
+	struct cvmx_pciercx_cfg031_s cn56xx;
+	struct cvmx_pciercx_cfg031_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg032 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg032_s {
+		uint32_t lab:1;
+		uint32_t lbm:1;
+		uint32_t dlla:1;
+		uint32_t scc:1;
+		uint32_t lt:1;
+		uint32_t reserved_26_26:1;
+		uint32_t nlw:6;
+		uint32_t ls:4;
+		uint32_t reserved_12_15:4;
+		uint32_t lab_int_enb:1;
+		uint32_t lbm_int_enb:1;
+		uint32_t hawd:1;
+		uint32_t ecpm:1;
+		uint32_t es:1;
+		uint32_t ccc:1;
+		uint32_t rl:1;
+		uint32_t ld:1;
+		uint32_t rcb:1;
+		uint32_t reserved_2_2:1;
+		uint32_t aslpc:2;
+	} s;
+	struct cvmx_pciercx_cfg032_s cn52xx;
+	struct cvmx_pciercx_cfg032_s cn52xxp1;
+	struct cvmx_pciercx_cfg032_s cn56xx;
+	struct cvmx_pciercx_cfg032_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg033 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg033_s {
+		uint32_t ps_num:13;
+		uint32_t nccs:1;
+		uint32_t emip:1;
+		uint32_t sp_ls:2;
+		uint32_t sp_lv:8;
+		uint32_t hp_c:1;
+		uint32_t hp_s:1;
+		uint32_t pip:1;
+		uint32_t aip:1;
+		uint32_t mrlsp:1;
+		uint32_t pcp:1;
+		uint32_t abp:1;
+	} s;
+	struct cvmx_pciercx_cfg033_s cn52xx;
+	struct cvmx_pciercx_cfg033_s cn52xxp1;
+	struct cvmx_pciercx_cfg033_s cn56xx;
+	struct cvmx_pciercx_cfg033_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg034 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg034_s {
+		uint32_t reserved_25_31:7;
+		uint32_t dlls_c:1;
+		uint32_t emis:1;
+		uint32_t pds:1;
+		uint32_t mrlss:1;
+		uint32_t ccint_d:1;
+		uint32_t pd_c:1;
+		uint32_t mrls_c:1;
+		uint32_t pf_d:1;
+		uint32_t abp_d:1;
+		uint32_t reserved_13_15:3;
+		uint32_t dlls_en:1;
+		uint32_t emic:1;
+		uint32_t pcc:1;
+		uint32_t pic:2;
+		uint32_t aic:2;
+		uint32_t hpint_en:1;
+		uint32_t ccint_en:1;
+		uint32_t pd_en:1;
+		uint32_t mrls_en:1;
+		uint32_t pf_en:1;
+		uint32_t abp_en:1;
+	} s;
+	struct cvmx_pciercx_cfg034_s cn52xx;
+	struct cvmx_pciercx_cfg034_s cn52xxp1;
+	struct cvmx_pciercx_cfg034_s cn56xx;
+	struct cvmx_pciercx_cfg034_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg035 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg035_s {
+		uint32_t reserved_17_31:15;
+		uint32_t crssv:1;
+		uint32_t reserved_5_15:11;
+		uint32_t crssve:1;
+		uint32_t pmeie:1;
+		uint32_t sefee:1;
+		uint32_t senfee:1;
+		uint32_t secee:1;
+	} s;
+	struct cvmx_pciercx_cfg035_s cn52xx;
+	struct cvmx_pciercx_cfg035_s cn52xxp1;
+	struct cvmx_pciercx_cfg035_s cn56xx;
+	struct cvmx_pciercx_cfg035_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg036 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg036_s {
+		uint32_t reserved_18_31:14;
+		uint32_t pme_pend:1;
+		uint32_t pme_stat:1;
+		uint32_t pme_rid:16;
+	} s;
+	struct cvmx_pciercx_cfg036_s cn52xx;
+	struct cvmx_pciercx_cfg036_s cn52xxp1;
+	struct cvmx_pciercx_cfg036_s cn56xx;
+	struct cvmx_pciercx_cfg036_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg037 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg037_s {
+		uint32_t reserved_5_31:27;
+		uint32_t ctds:1;
+		uint32_t ctrs:4;
+	} s;
+	struct cvmx_pciercx_cfg037_s cn52xx;
+	struct cvmx_pciercx_cfg037_s cn52xxp1;
+	struct cvmx_pciercx_cfg037_s cn56xx;
+	struct cvmx_pciercx_cfg037_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg038 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg038_s {
+		uint32_t reserved_5_31:27;
+		uint32_t ctd:1;
+		uint32_t ctv:4;
+	} s;
+	struct cvmx_pciercx_cfg038_s cn52xx;
+	struct cvmx_pciercx_cfg038_s cn52xxp1;
+	struct cvmx_pciercx_cfg038_s cn56xx;
+	struct cvmx_pciercx_cfg038_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg039 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg039_s {
+		uint32_t reserved_0_31:32;
+	} s;
+	struct cvmx_pciercx_cfg039_s cn52xx;
+	struct cvmx_pciercx_cfg039_s cn52xxp1;
+	struct cvmx_pciercx_cfg039_s cn56xx;
+	struct cvmx_pciercx_cfg039_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg040 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg040_s {
+		uint32_t reserved_0_31:32;
+	} s;
+	struct cvmx_pciercx_cfg040_s cn52xx;
+	struct cvmx_pciercx_cfg040_s cn52xxp1;
+	struct cvmx_pciercx_cfg040_s cn56xx;
+	struct cvmx_pciercx_cfg040_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg041 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg041_s {
+		uint32_t reserved_0_31:32;
+	} s;
+	struct cvmx_pciercx_cfg041_s cn52xx;
+	struct cvmx_pciercx_cfg041_s cn52xxp1;
+	struct cvmx_pciercx_cfg041_s cn56xx;
+	struct cvmx_pciercx_cfg041_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg042 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg042_s {
+		uint32_t reserved_0_31:32;
+	} s;
+	struct cvmx_pciercx_cfg042_s cn52xx;
+	struct cvmx_pciercx_cfg042_s cn52xxp1;
+	struct cvmx_pciercx_cfg042_s cn56xx;
+	struct cvmx_pciercx_cfg042_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg064 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg064_s {
+		uint32_t nco:12;
+		uint32_t cv:4;
+		uint32_t pcieec:16;
+	} s;
+	struct cvmx_pciercx_cfg064_s cn52xx;
+	struct cvmx_pciercx_cfg064_s cn52xxp1;
+	struct cvmx_pciercx_cfg064_s cn56xx;
+	struct cvmx_pciercx_cfg064_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg065 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg065_s {
+		uint32_t reserved_21_31:11;
+		uint32_t ures:1;
+		uint32_t ecrces:1;
+		uint32_t mtlps:1;
+		uint32_t ros:1;
+		uint32_t ucs:1;
+		uint32_t cas:1;
+		uint32_t cts:1;
+		uint32_t fcpes:1;
+		uint32_t ptlps:1;
+		uint32_t reserved_6_11:6;
+		uint32_t sdes:1;
+		uint32_t dlpes:1;
+		uint32_t reserved_0_3:4;
+	} s;
+	struct cvmx_pciercx_cfg065_s cn52xx;
+	struct cvmx_pciercx_cfg065_s cn52xxp1;
+	struct cvmx_pciercx_cfg065_s cn56xx;
+	struct cvmx_pciercx_cfg065_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg066 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg066_s {
+		uint32_t reserved_21_31:11;
+		uint32_t urem:1;
+		uint32_t ecrcem:1;
+		uint32_t mtlpm:1;
+		uint32_t rom:1;
+		uint32_t ucm:1;
+		uint32_t cam:1;
+		uint32_t ctm:1;
+		uint32_t fcpem:1;
+		uint32_t ptlpm:1;
+		uint32_t reserved_6_11:6;
+		uint32_t sdem:1;
+		uint32_t dlpem:1;
+		uint32_t reserved_0_3:4;
+	} s;
+	struct cvmx_pciercx_cfg066_s cn52xx;
+	struct cvmx_pciercx_cfg066_s cn52xxp1;
+	struct cvmx_pciercx_cfg066_s cn56xx;
+	struct cvmx_pciercx_cfg066_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg067 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg067_s {
+		uint32_t reserved_21_31:11;
+		uint32_t ures:1;
+		uint32_t ecrces:1;
+		uint32_t mtlps:1;
+		uint32_t ros:1;
+		uint32_t ucs:1;
+		uint32_t cas:1;
+		uint32_t cts:1;
+		uint32_t fcpes:1;
+		uint32_t ptlps:1;
+		uint32_t reserved_6_11:6;
+		uint32_t sdes:1;
+		uint32_t dlpes:1;
+		uint32_t reserved_0_3:4;
+	} s;
+	struct cvmx_pciercx_cfg067_s cn52xx;
+	struct cvmx_pciercx_cfg067_s cn52xxp1;
+	struct cvmx_pciercx_cfg067_s cn56xx;
+	struct cvmx_pciercx_cfg067_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg068 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg068_s {
+		uint32_t reserved_14_31:18;
+		uint32_t anfes:1;
+		uint32_t rtts:1;
+		uint32_t reserved_9_11:3;
+		uint32_t rnrs:1;
+		uint32_t bdllps:1;
+		uint32_t btlps:1;
+		uint32_t reserved_1_5:5;
+		uint32_t res:1;
+	} s;
+	struct cvmx_pciercx_cfg068_s cn52xx;
+	struct cvmx_pciercx_cfg068_s cn52xxp1;
+	struct cvmx_pciercx_cfg068_s cn56xx;
+	struct cvmx_pciercx_cfg068_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg069 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg069_s {
+		uint32_t reserved_14_31:18;
+		uint32_t anfem:1;
+		uint32_t rttm:1;
+		uint32_t reserved_9_11:3;
+		uint32_t rnrm:1;
+		uint32_t bdllpm:1;
+		uint32_t btlpm:1;
+		uint32_t reserved_1_5:5;
+		uint32_t rem:1;
+	} s;
+	struct cvmx_pciercx_cfg069_s cn52xx;
+	struct cvmx_pciercx_cfg069_s cn52xxp1;
+	struct cvmx_pciercx_cfg069_s cn56xx;
+	struct cvmx_pciercx_cfg069_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg070 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg070_s {
+		uint32_t reserved_9_31:23;
+		uint32_t ce:1;
+		uint32_t cc:1;
+		uint32_t ge:1;
+		uint32_t gc:1;
+		uint32_t fep:5;
+	} s;
+	struct cvmx_pciercx_cfg070_s cn52xx;
+	struct cvmx_pciercx_cfg070_s cn52xxp1;
+	struct cvmx_pciercx_cfg070_s cn56xx;
+	struct cvmx_pciercx_cfg070_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg071 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg071_s {
+		uint32_t dword1:32;
+	} s;
+	struct cvmx_pciercx_cfg071_s cn52xx;
+	struct cvmx_pciercx_cfg071_s cn52xxp1;
+	struct cvmx_pciercx_cfg071_s cn56xx;
+	struct cvmx_pciercx_cfg071_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg072 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg072_s {
+		uint32_t dword2:32;
+	} s;
+	struct cvmx_pciercx_cfg072_s cn52xx;
+	struct cvmx_pciercx_cfg072_s cn52xxp1;
+	struct cvmx_pciercx_cfg072_s cn56xx;
+	struct cvmx_pciercx_cfg072_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg073 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg073_s {
+		uint32_t dword3:32;
+	} s;
+	struct cvmx_pciercx_cfg073_s cn52xx;
+	struct cvmx_pciercx_cfg073_s cn52xxp1;
+	struct cvmx_pciercx_cfg073_s cn56xx;
+	struct cvmx_pciercx_cfg073_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg074 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg074_s {
+		uint32_t dword4:32;
+	} s;
+	struct cvmx_pciercx_cfg074_s cn52xx;
+	struct cvmx_pciercx_cfg074_s cn52xxp1;
+	struct cvmx_pciercx_cfg074_s cn56xx;
+	struct cvmx_pciercx_cfg074_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg075 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg075_s {
+		uint32_t reserved_3_31:29;
+		uint32_t fere:1;
+		uint32_t nfere:1;
+		uint32_t cere:1;
+	} s;
+	struct cvmx_pciercx_cfg075_s cn52xx;
+	struct cvmx_pciercx_cfg075_s cn52xxp1;
+	struct cvmx_pciercx_cfg075_s cn56xx;
+	struct cvmx_pciercx_cfg075_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg076 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg076_s {
+		uint32_t aeimn:5;
+		uint32_t reserved_7_26:20;
+		uint32_t femr:1;
+		uint32_t nfemr:1;
+		uint32_t fuf:1;
+		uint32_t multi_efnfr:1;
+		uint32_t efnfr:1;
+		uint32_t multi_ecr:1;
+		uint32_t ecr:1;
+	} s;
+	struct cvmx_pciercx_cfg076_s cn52xx;
+	struct cvmx_pciercx_cfg076_s cn52xxp1;
+	struct cvmx_pciercx_cfg076_s cn56xx;
+	struct cvmx_pciercx_cfg076_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg077 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg077_s {
+		uint32_t efnfsi:16;
+		uint32_t ecsi:16;
+	} s;
+	struct cvmx_pciercx_cfg077_s cn52xx;
+	struct cvmx_pciercx_cfg077_s cn52xxp1;
+	struct cvmx_pciercx_cfg077_s cn56xx;
+	struct cvmx_pciercx_cfg077_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg448 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg448_s {
+		uint32_t rtl:16;
+		uint32_t rtltl:16;
+	} s;
+	struct cvmx_pciercx_cfg448_s cn52xx;
+	struct cvmx_pciercx_cfg448_s cn52xxp1;
+	struct cvmx_pciercx_cfg448_s cn56xx;
+	struct cvmx_pciercx_cfg448_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg449 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg449_s {
+		uint32_t omr:32;
+	} s;
+	struct cvmx_pciercx_cfg449_s cn52xx;
+	struct cvmx_pciercx_cfg449_s cn52xxp1;
+	struct cvmx_pciercx_cfg449_s cn56xx;
+	struct cvmx_pciercx_cfg449_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg450 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg450_s {
+		uint32_t lpec:8;
+		uint32_t reserved_22_23:2;
+		uint32_t link_state:6;
+		uint32_t force_link:1;
+		uint32_t reserved_8_14:7;
+		uint32_t link_num:8;
+	} s;
+	struct cvmx_pciercx_cfg450_s cn52xx;
+	struct cvmx_pciercx_cfg450_s cn52xxp1;
+	struct cvmx_pciercx_cfg450_s cn56xx;
+	struct cvmx_pciercx_cfg450_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg451 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg451_s {
+		uint32_t reserved_30_31:2;
+		uint32_t l1el:3;
+		uint32_t l0el:3;
+		uint32_t n_fts_cc:8;
+		uint32_t n_fts:8;
+		uint32_t ack_freq:8;
+	} s;
+	struct cvmx_pciercx_cfg451_s cn52xx;
+	struct cvmx_pciercx_cfg451_s cn52xxp1;
+	struct cvmx_pciercx_cfg451_s cn56xx;
+	struct cvmx_pciercx_cfg451_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg452 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg452_s {
+		uint32_t reserved_26_31:6;
+		uint32_t eccrc:1;
+		uint32_t reserved_22_24:3;
+		uint32_t lme:6;
+		uint32_t reserved_8_15:8;
+		uint32_t flm:1;
+		uint32_t reserved_6_6:1;
+		uint32_t dllle:1;
+		uint32_t reserved_4_4:1;
+		uint32_t ra:1;
+		uint32_t le:1;
+		uint32_t sd:1;
+		uint32_t omr:1;
+	} s;
+	struct cvmx_pciercx_cfg452_s cn52xx;
+	struct cvmx_pciercx_cfg452_s cn52xxp1;
+	struct cvmx_pciercx_cfg452_s cn56xx;
+	struct cvmx_pciercx_cfg452_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg453 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg453_s {
+		uint32_t dlld:1;
+		uint32_t reserved_26_30:5;
+		uint32_t ack_nak:1;
+		uint32_t fcd:1;
+		uint32_t ilst:24;
+	} s;
+	struct cvmx_pciercx_cfg453_s cn52xx;
+	struct cvmx_pciercx_cfg453_s cn52xxp1;
+	struct cvmx_pciercx_cfg453_s cn56xx;
+	struct cvmx_pciercx_cfg453_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg454 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg454_s {
+		uint32_t reserved_29_31:3;
+		uint32_t tmfcwt:5;
+		uint32_t tmanlt:5;
+		uint32_t tmrt:5;
+		uint32_t reserved_11_13:3;
+		uint32_t nskps:3;
+		uint32_t reserved_4_7:4;
+		uint32_t ntss:4;
+	} s;
+	struct cvmx_pciercx_cfg454_s cn52xx;
+	struct cvmx_pciercx_cfg454_s cn52xxp1;
+	struct cvmx_pciercx_cfg454_s cn56xx;
+	struct cvmx_pciercx_cfg454_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg455 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg455_s {
+		uint32_t m_cfg0_filt:1;
+		uint32_t m_io_filt:1;
+		uint32_t msg_ctrl:1;
+		uint32_t m_cpl_ecrc_filt:1;
+		uint32_t m_ecrc_filt:1;
+		uint32_t m_cpl_len_err:1;
+		uint32_t m_cpl_attr_err:1;
+		uint32_t m_cpl_tc_err:1;
+		uint32_t m_cpl_fun_err:1;
+		uint32_t m_cpl_rid_err:1;
+		uint32_t m_cpl_tag_err:1;
+		uint32_t m_lk_filt:1;
+		uint32_t m_cfg1_filt:1;
+		uint32_t m_bar_match:1;
+		uint32_t m_pois_filt:1;
+		uint32_t m_fun:1;
+		uint32_t dfcwt:1;
+		uint32_t reserved_11_14:4;
+		uint32_t skpiv:11;
+	} s;
+	struct cvmx_pciercx_cfg455_s cn52xx;
+	struct cvmx_pciercx_cfg455_s cn52xxp1;
+	struct cvmx_pciercx_cfg455_s cn56xx;
+	struct cvmx_pciercx_cfg455_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg456 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg456_s {
+		uint32_t reserved_2_31:30;
+		uint32_t m_vend1_drp:1;
+		uint32_t m_vend0_drp:1;
+	} s;
+	struct cvmx_pciercx_cfg456_s cn52xx;
+	struct cvmx_pciercx_cfg456_s cn52xxp1;
+	struct cvmx_pciercx_cfg456_s cn56xx;
+	struct cvmx_pciercx_cfg456_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg458 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg458_s {
+		uint32_t dbg_info_l32:32;
+	} s;
+	struct cvmx_pciercx_cfg458_s cn52xx;
+	struct cvmx_pciercx_cfg458_s cn52xxp1;
+	struct cvmx_pciercx_cfg458_s cn56xx;
+	struct cvmx_pciercx_cfg458_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg459 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg459_s {
+		uint32_t dbg_info_u32:32;
+	} s;
+	struct cvmx_pciercx_cfg459_s cn52xx;
+	struct cvmx_pciercx_cfg459_s cn52xxp1;
+	struct cvmx_pciercx_cfg459_s cn56xx;
+	struct cvmx_pciercx_cfg459_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg460 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg460_s {
+		uint32_t reserved_20_31:12;
+		uint32_t tphfcc:8;
+		uint32_t tpdfcc:12;
+	} s;
+	struct cvmx_pciercx_cfg460_s cn52xx;
+	struct cvmx_pciercx_cfg460_s cn52xxp1;
+	struct cvmx_pciercx_cfg460_s cn56xx;
+	struct cvmx_pciercx_cfg460_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg461 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg461_s {
+		uint32_t reserved_20_31:12;
+		uint32_t tchfcc:8;
+		uint32_t tcdfcc:12;
+	} s;
+	struct cvmx_pciercx_cfg461_s cn52xx;
+	struct cvmx_pciercx_cfg461_s cn52xxp1;
+	struct cvmx_pciercx_cfg461_s cn56xx;
+	struct cvmx_pciercx_cfg461_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg462 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg462_s {
+		uint32_t reserved_20_31:12;
+		uint32_t tchfcc:8;
+		uint32_t tcdfcc:12;
+	} s;
+	struct cvmx_pciercx_cfg462_s cn52xx;
+	struct cvmx_pciercx_cfg462_s cn52xxp1;
+	struct cvmx_pciercx_cfg462_s cn56xx;
+	struct cvmx_pciercx_cfg462_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg463 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg463_s {
+		uint32_t reserved_3_31:29;
+		uint32_t rqne:1;
+		uint32_t trbne:1;
+		uint32_t rtlpfccnr:1;
+	} s;
+	struct cvmx_pciercx_cfg463_s cn52xx;
+	struct cvmx_pciercx_cfg463_s cn52xxp1;
+	struct cvmx_pciercx_cfg463_s cn56xx;
+	struct cvmx_pciercx_cfg463_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg464 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg464_s {
+		uint32_t wrr_vc3:8;
+		uint32_t wrr_vc2:8;
+		uint32_t wrr_vc1:8;
+		uint32_t wrr_vc0:8;
+	} s;
+	struct cvmx_pciercx_cfg464_s cn52xx;
+	struct cvmx_pciercx_cfg464_s cn52xxp1;
+	struct cvmx_pciercx_cfg464_s cn56xx;
+	struct cvmx_pciercx_cfg464_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg465 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg465_s {
+		uint32_t wrr_vc7:8;
+		uint32_t wrr_vc6:8;
+		uint32_t wrr_vc5:8;
+		uint32_t wrr_vc4:8;
+	} s;
+	struct cvmx_pciercx_cfg465_s cn52xx;
+	struct cvmx_pciercx_cfg465_s cn52xxp1;
+	struct cvmx_pciercx_cfg465_s cn56xx;
+	struct cvmx_pciercx_cfg465_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg466 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg466_s {
+		uint32_t rx_queue_order:1;
+		uint32_t type_ordering:1;
+		uint32_t reserved_24_29:6;
+		uint32_t queue_mode:3;
+		uint32_t reserved_20_20:1;
+		uint32_t header_credits:8;
+		uint32_t data_credits:12;
+	} s;
+	struct cvmx_pciercx_cfg466_s cn52xx;
+	struct cvmx_pciercx_cfg466_s cn52xxp1;
+	struct cvmx_pciercx_cfg466_s cn56xx;
+	struct cvmx_pciercx_cfg466_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg467 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg467_s {
+		uint32_t reserved_24_31:8;
+		uint32_t queue_mode:3;
+		uint32_t reserved_20_20:1;
+		uint32_t header_credits:8;
+		uint32_t data_credits:12;
+	} s;
+	struct cvmx_pciercx_cfg467_s cn52xx;
+	struct cvmx_pciercx_cfg467_s cn52xxp1;
+	struct cvmx_pciercx_cfg467_s cn56xx;
+	struct cvmx_pciercx_cfg467_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg468 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg468_s {
+		uint32_t reserved_24_31:8;
+		uint32_t queue_mode:3;
+		uint32_t reserved_20_20:1;
+		uint32_t header_credits:8;
+		uint32_t data_credits:12;
+	} s;
+	struct cvmx_pciercx_cfg468_s cn52xx;
+	struct cvmx_pciercx_cfg468_s cn52xxp1;
+	struct cvmx_pciercx_cfg468_s cn56xx;
+	struct cvmx_pciercx_cfg468_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg490 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg490_s {
+		uint32_t reserved_26_31:6;
+		uint32_t header_depth:10;
+		uint32_t reserved_14_15:2;
+		uint32_t data_depth:14;
+	} s;
+	struct cvmx_pciercx_cfg490_s cn52xx;
+	struct cvmx_pciercx_cfg490_s cn52xxp1;
+	struct cvmx_pciercx_cfg490_s cn56xx;
+	struct cvmx_pciercx_cfg490_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg491 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg491_s {
+		uint32_t reserved_26_31:6;
+		uint32_t header_depth:10;
+		uint32_t reserved_14_15:2;
+		uint32_t data_depth:14;
+	} s;
+	struct cvmx_pciercx_cfg491_s cn52xx;
+	struct cvmx_pciercx_cfg491_s cn52xxp1;
+	struct cvmx_pciercx_cfg491_s cn56xx;
+	struct cvmx_pciercx_cfg491_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg492 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg492_s {
+		uint32_t reserved_26_31:6;
+		uint32_t header_depth:10;
+		uint32_t reserved_14_15:2;
+		uint32_t data_depth:14;
+	} s;
+	struct cvmx_pciercx_cfg492_s cn52xx;
+	struct cvmx_pciercx_cfg492_s cn52xxp1;
+	struct cvmx_pciercx_cfg492_s cn56xx;
+	struct cvmx_pciercx_cfg492_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg516 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg516_s {
+		uint32_t phy_stat:32;
+	} s;
+	struct cvmx_pciercx_cfg516_s cn52xx;
+	struct cvmx_pciercx_cfg516_s cn52xxp1;
+	struct cvmx_pciercx_cfg516_s cn56xx;
+	struct cvmx_pciercx_cfg516_s cn56xxp1;
+};
+
+union cvmx_pciercx_cfg517 {
+	uint32_t u32;
+	struct cvmx_pciercx_cfg517_s {
+		uint32_t phy_ctrl:32;
+	} s;
+	struct cvmx_pciercx_cfg517_s cn52xx;
+	struct cvmx_pciercx_cfg517_s cn52xxp1;
+	struct cvmx_pciercx_cfg517_s cn56xx;
+	struct cvmx_pciercx_cfg517_s cn56xxp1;
+};
+
+#endif
diff --git a/arch/mips/include/asm/octeon/cvmx-pescx-defs.h b/arch/mips/include/asm/octeon/cvmx-pescx-defs.h
new file mode 100644
index 0000000..f40cfaf
--- /dev/null
+++ b/arch/mips/include/asm/octeon/cvmx-pescx-defs.h
@@ -0,0 +1,410 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_PESCX_DEFS_H__
+#define __CVMX_PESCX_DEFS_H__
+
+#define CVMX_PESCX_BIST_STATUS(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000018ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_BIST_STATUS2(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000418ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_CFG_RD(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000030ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_CFG_WR(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000028ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_CPL_LUT_VALID(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000098ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_CTL_STATUS(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000000ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_CTL_STATUS2(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000400ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_DBG_INFO(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000008ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_DBG_INFO_EN(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C80000A0ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_DIAG_STATUS(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000020ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_P2N_BAR0_START(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000080ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_P2N_BAR1_START(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000088ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_P2N_BAR2_START(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000090ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_P2P_BARX_END(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000048ull + (((offset) & 3) * 16) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_P2P_BARX_START(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000040ull + (((offset) & 3) * 16) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PESCX_TLP_CREDITS(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800C8000038ull + (((block_id) & 1) * 0x8000000ull))
+
+union cvmx_pescx_bist_status {
+	uint64_t u64;
+	struct cvmx_pescx_bist_status_s {
+		uint64_t reserved_13_63:51;
+		uint64_t rqdata5:1;
+		uint64_t ctlp_or:1;
+		uint64_t ntlp_or:1;
+		uint64_t ptlp_or:1;
+		uint64_t retry:1;
+		uint64_t rqdata0:1;
+		uint64_t rqdata1:1;
+		uint64_t rqdata2:1;
+		uint64_t rqdata3:1;
+		uint64_t rqdata4:1;
+		uint64_t rqhdr1:1;
+		uint64_t rqhdr0:1;
+		uint64_t sot:1;
+	} s;
+	struct cvmx_pescx_bist_status_s cn52xx;
+	struct cvmx_pescx_bist_status_cn52xxp1 {
+		uint64_t reserved_12_63:52;
+		uint64_t ctlp_or:1;
+		uint64_t ntlp_or:1;
+		uint64_t ptlp_or:1;
+		uint64_t retry:1;
+		uint64_t rqdata0:1;
+		uint64_t rqdata1:1;
+		uint64_t rqdata2:1;
+		uint64_t rqdata3:1;
+		uint64_t rqdata4:1;
+		uint64_t rqhdr1:1;
+		uint64_t rqhdr0:1;
+		uint64_t sot:1;
+	} cn52xxp1;
+	struct cvmx_pescx_bist_status_s cn56xx;
+	struct cvmx_pescx_bist_status_cn52xxp1 cn56xxp1;
+};
+
+union cvmx_pescx_bist_status2 {
+	uint64_t u64;
+	struct cvmx_pescx_bist_status2_s {
+		uint64_t reserved_14_63:50;
+		uint64_t cto_p2e:1;
+		uint64_t e2p_cpl:1;
+		uint64_t e2p_n:1;
+		uint64_t e2p_p:1;
+		uint64_t e2p_rsl:1;
+		uint64_t dbg_p2e:1;
+		uint64_t peai_p2e:1;
+		uint64_t rsl_p2e:1;
+		uint64_t pef_tpf1:1;
+		uint64_t pef_tpf0:1;
+		uint64_t pef_tnf:1;
+		uint64_t pef_tcf1:1;
+		uint64_t pef_tc0:1;
+		uint64_t ppf:1;
+	} s;
+	struct cvmx_pescx_bist_status2_s cn52xx;
+	struct cvmx_pescx_bist_status2_s cn52xxp1;
+	struct cvmx_pescx_bist_status2_s cn56xx;
+	struct cvmx_pescx_bist_status2_s cn56xxp1;
+};
+
+union cvmx_pescx_cfg_rd {
+	uint64_t u64;
+	struct cvmx_pescx_cfg_rd_s {
+		uint64_t data:32;
+		uint64_t addr:32;
+	} s;
+	struct cvmx_pescx_cfg_rd_s cn52xx;
+	struct cvmx_pescx_cfg_rd_s cn52xxp1;
+	struct cvmx_pescx_cfg_rd_s cn56xx;
+	struct cvmx_pescx_cfg_rd_s cn56xxp1;
+};
+
+union cvmx_pescx_cfg_wr {
+	uint64_t u64;
+	struct cvmx_pescx_cfg_wr_s {
+		uint64_t data:32;
+		uint64_t addr:32;
+	} s;
+	struct cvmx_pescx_cfg_wr_s cn52xx;
+	struct cvmx_pescx_cfg_wr_s cn52xxp1;
+	struct cvmx_pescx_cfg_wr_s cn56xx;
+	struct cvmx_pescx_cfg_wr_s cn56xxp1;
+};
+
+union cvmx_pescx_cpl_lut_valid {
+	uint64_t u64;
+	struct cvmx_pescx_cpl_lut_valid_s {
+		uint64_t reserved_32_63:32;
+		uint64_t tag:32;
+	} s;
+	struct cvmx_pescx_cpl_lut_valid_s cn52xx;
+	struct cvmx_pescx_cpl_lut_valid_s cn52xxp1;
+	struct cvmx_pescx_cpl_lut_valid_s cn56xx;
+	struct cvmx_pescx_cpl_lut_valid_s cn56xxp1;
+};
+
+union cvmx_pescx_ctl_status {
+	uint64_t u64;
+	struct cvmx_pescx_ctl_status_s {
+		uint64_t reserved_28_63:36;
+		uint64_t dnum:5;
+		uint64_t pbus:8;
+		uint64_t qlm_cfg:2;
+		uint64_t lane_swp:1;
+		uint64_t pm_xtoff:1;
+		uint64_t pm_xpme:1;
+		uint64_t ob_p_cmd:1;
+		uint64_t reserved_7_8:2;
+		uint64_t nf_ecrc:1;
+		uint64_t dly_one:1;
+		uint64_t lnk_enb:1;
+		uint64_t ro_ctlp:1;
+		uint64_t reserved_2_2:1;
+		uint64_t inv_ecrc:1;
+		uint64_t inv_lcrc:1;
+	} s;
+	struct cvmx_pescx_ctl_status_s cn52xx;
+	struct cvmx_pescx_ctl_status_s cn52xxp1;
+	struct cvmx_pescx_ctl_status_cn56xx {
+		uint64_t reserved_28_63:36;
+		uint64_t dnum:5;
+		uint64_t pbus:8;
+		uint64_t qlm_cfg:2;
+		uint64_t reserved_12_12:1;
+		uint64_t pm_xtoff:1;
+		uint64_t pm_xpme:1;
+		uint64_t ob_p_cmd:1;
+		uint64_t reserved_7_8:2;
+		uint64_t nf_ecrc:1;
+		uint64_t dly_one:1;
+		uint64_t lnk_enb:1;
+		uint64_t ro_ctlp:1;
+		uint64_t reserved_2_2:1;
+		uint64_t inv_ecrc:1;
+		uint64_t inv_lcrc:1;
+	} cn56xx;
+	struct cvmx_pescx_ctl_status_cn56xx cn56xxp1;
+};
+
+union cvmx_pescx_ctl_status2 {
+	uint64_t u64;
+	struct cvmx_pescx_ctl_status2_s {
+		uint64_t reserved_2_63:62;
+		uint64_t pclk_run:1;
+		uint64_t pcierst:1;
+	} s;
+	struct cvmx_pescx_ctl_status2_s cn52xx;
+	struct cvmx_pescx_ctl_status2_cn52xxp1 {
+		uint64_t reserved_1_63:63;
+		uint64_t pcierst:1;
+	} cn52xxp1;
+	struct cvmx_pescx_ctl_status2_s cn56xx;
+	struct cvmx_pescx_ctl_status2_cn52xxp1 cn56xxp1;
+};
+
+union cvmx_pescx_dbg_info {
+	uint64_t u64;
+	struct cvmx_pescx_dbg_info_s {
+		uint64_t reserved_31_63:33;
+		uint64_t ecrc_e:1;
+		uint64_t rawwpp:1;
+		uint64_t racpp:1;
+		uint64_t ramtlp:1;
+		uint64_t rarwdns:1;
+		uint64_t caar:1;
+		uint64_t racca:1;
+		uint64_t racur:1;
+		uint64_t rauc:1;
+		uint64_t rqo:1;
+		uint64_t fcuv:1;
+		uint64_t rpe:1;
+		uint64_t fcpvwt:1;
+		uint64_t dpeoosd:1;
+		uint64_t rtwdle:1;
+		uint64_t rdwdle:1;
+		uint64_t mre:1;
+		uint64_t rte:1;
+		uint64_t acto:1;
+		uint64_t rvdm:1;
+		uint64_t rumep:1;
+		uint64_t rptamrc:1;
+		uint64_t rpmerc:1;
+		uint64_t rfemrc:1;
+		uint64_t rnfemrc:1;
+		uint64_t rcemrc:1;
+		uint64_t rpoison:1;
+		uint64_t recrce:1;
+		uint64_t rtlplle:1;
+		uint64_t rtlpmal:1;
+		uint64_t spoison:1;
+	} s;
+	struct cvmx_pescx_dbg_info_s cn52xx;
+	struct cvmx_pescx_dbg_info_s cn52xxp1;
+	struct cvmx_pescx_dbg_info_s cn56xx;
+	struct cvmx_pescx_dbg_info_s cn56xxp1;
+};
+
+union cvmx_pescx_dbg_info_en {
+	uint64_t u64;
+	struct cvmx_pescx_dbg_info_en_s {
+		uint64_t reserved_31_63:33;
+		uint64_t ecrc_e:1;
+		uint64_t rawwpp:1;
+		uint64_t racpp:1;
+		uint64_t ramtlp:1;
+		uint64_t rarwdns:1;
+		uint64_t caar:1;
+		uint64_t racca:1;
+		uint64_t racur:1;
+		uint64_t rauc:1;
+		uint64_t rqo:1;
+		uint64_t fcuv:1;
+		uint64_t rpe:1;
+		uint64_t fcpvwt:1;
+		uint64_t dpeoosd:1;
+		uint64_t rtwdle:1;
+		uint64_t rdwdle:1;
+		uint64_t mre:1;
+		uint64_t rte:1;
+		uint64_t acto:1;
+		uint64_t rvdm:1;
+		uint64_t rumep:1;
+		uint64_t rptamrc:1;
+		uint64_t rpmerc:1;
+		uint64_t rfemrc:1;
+		uint64_t rnfemrc:1;
+		uint64_t rcemrc:1;
+		uint64_t rpoison:1;
+		uint64_t recrce:1;
+		uint64_t rtlplle:1;
+		uint64_t rtlpmal:1;
+		uint64_t spoison:1;
+	} s;
+	struct cvmx_pescx_dbg_info_en_s cn52xx;
+	struct cvmx_pescx_dbg_info_en_s cn52xxp1;
+	struct cvmx_pescx_dbg_info_en_s cn56xx;
+	struct cvmx_pescx_dbg_info_en_s cn56xxp1;
+};
+
+union cvmx_pescx_diag_status {
+	uint64_t u64;
+	struct cvmx_pescx_diag_status_s {
+		uint64_t reserved_4_63:60;
+		uint64_t pm_dst:1;
+		uint64_t pm_stat:1;
+		uint64_t pm_en:1;
+		uint64_t aux_en:1;
+	} s;
+	struct cvmx_pescx_diag_status_s cn52xx;
+	struct cvmx_pescx_diag_status_s cn52xxp1;
+	struct cvmx_pescx_diag_status_s cn56xx;
+	struct cvmx_pescx_diag_status_s cn56xxp1;
+};
+
+union cvmx_pescx_p2n_bar0_start {
+	uint64_t u64;
+	struct cvmx_pescx_p2n_bar0_start_s {
+		uint64_t addr:50;
+		uint64_t reserved_0_13:14;
+	} s;
+	struct cvmx_pescx_p2n_bar0_start_s cn52xx;
+	struct cvmx_pescx_p2n_bar0_start_s cn52xxp1;
+	struct cvmx_pescx_p2n_bar0_start_s cn56xx;
+	struct cvmx_pescx_p2n_bar0_start_s cn56xxp1;
+};
+
+union cvmx_pescx_p2n_bar1_start {
+	uint64_t u64;
+	struct cvmx_pescx_p2n_bar1_start_s {
+		uint64_t addr:38;
+		uint64_t reserved_0_25:26;
+	} s;
+	struct cvmx_pescx_p2n_bar1_start_s cn52xx;
+	struct cvmx_pescx_p2n_bar1_start_s cn52xxp1;
+	struct cvmx_pescx_p2n_bar1_start_s cn56xx;
+	struct cvmx_pescx_p2n_bar1_start_s cn56xxp1;
+};
+
+union cvmx_pescx_p2n_bar2_start {
+	uint64_t u64;
+	struct cvmx_pescx_p2n_bar2_start_s {
+		uint64_t addr:25;
+		uint64_t reserved_0_38:39;
+	} s;
+	struct cvmx_pescx_p2n_bar2_start_s cn52xx;
+	struct cvmx_pescx_p2n_bar2_start_s cn52xxp1;
+	struct cvmx_pescx_p2n_bar2_start_s cn56xx;
+	struct cvmx_pescx_p2n_bar2_start_s cn56xxp1;
+};
+
+union cvmx_pescx_p2p_barx_end {
+	uint64_t u64;
+	struct cvmx_pescx_p2p_barx_end_s {
+		uint64_t addr:52;
+		uint64_t reserved_0_11:12;
+	} s;
+	struct cvmx_pescx_p2p_barx_end_s cn52xx;
+	struct cvmx_pescx_p2p_barx_end_s cn52xxp1;
+	struct cvmx_pescx_p2p_barx_end_s cn56xx;
+	struct cvmx_pescx_p2p_barx_end_s cn56xxp1;
+};
+
+union cvmx_pescx_p2p_barx_start {
+	uint64_t u64;
+	struct cvmx_pescx_p2p_barx_start_s {
+		uint64_t addr:52;
+		uint64_t reserved_0_11:12;
+	} s;
+	struct cvmx_pescx_p2p_barx_start_s cn52xx;
+	struct cvmx_pescx_p2p_barx_start_s cn52xxp1;
+	struct cvmx_pescx_p2p_barx_start_s cn56xx;
+	struct cvmx_pescx_p2p_barx_start_s cn56xxp1;
+};
+
+union cvmx_pescx_tlp_credits {
+	uint64_t u64;
+	struct cvmx_pescx_tlp_credits_s {
+		uint64_t reserved_0_63:64;
+	} s;
+	struct cvmx_pescx_tlp_credits_cn52xx {
+		uint64_t reserved_56_63:8;
+		uint64_t peai_ppf:8;
+		uint64_t pesc_cpl:8;
+		uint64_t pesc_np:8;
+		uint64_t pesc_p:8;
+		uint64_t npei_cpl:8;
+		uint64_t npei_np:8;
+		uint64_t npei_p:8;
+	} cn52xx;
+	struct cvmx_pescx_tlp_credits_cn52xxp1 {
+		uint64_t reserved_38_63:26;
+		uint64_t peai_ppf:8;
+		uint64_t pesc_cpl:5;
+		uint64_t pesc_np:5;
+		uint64_t pesc_p:5;
+		uint64_t npei_cpl:5;
+		uint64_t npei_np:5;
+		uint64_t npei_p:5;
+	} cn52xxp1;
+	struct cvmx_pescx_tlp_credits_cn52xx cn56xx;
+	struct cvmx_pescx_tlp_credits_cn52xxp1 cn56xxp1;
+};
+
+#endif
diff --git a/arch/mips/include/asm/octeon/cvmx-pexp-defs.h b/arch/mips/include/asm/octeon/cvmx-pexp-defs.h
new file mode 100644
index 0000000..5ea5dc5
--- /dev/null
+++ b/arch/mips/include/asm/octeon/cvmx-pexp-defs.h
@@ -0,0 +1,229 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * cvmx-pexp-defs.h
+ *
+ * Configuration and status register (CSR) definitions for
+ * OCTEON PEXP.
+ *
+ */
+#ifndef __CVMX_PEXP_DEFS_H__
+#define __CVMX_PEXP_DEFS_H__
+
+#define CVMX_PEXP_NPEI_BAR1_INDEXX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000008000ull + (((offset) & 31) * 16))
+#define CVMX_PEXP_NPEI_BIST_STATUS \
+	 CVMX_ADD_IO_SEG(0x00011F0000008580ull)
+#define CVMX_PEXP_NPEI_BIST_STATUS2 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008680ull)
+#define CVMX_PEXP_NPEI_CTL_PORT0 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008250ull)
+#define CVMX_PEXP_NPEI_CTL_PORT1 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008260ull)
+#define CVMX_PEXP_NPEI_CTL_STATUS \
+	 CVMX_ADD_IO_SEG(0x00011F0000008570ull)
+#define CVMX_PEXP_NPEI_CTL_STATUS2 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BC00ull)
+#define CVMX_PEXP_NPEI_DATA_OUT_CNT \
+	 CVMX_ADD_IO_SEG(0x00011F00000085F0ull)
+#define CVMX_PEXP_NPEI_DBG_DATA \
+	 CVMX_ADD_IO_SEG(0x00011F0000008510ull)
+#define CVMX_PEXP_NPEI_DBG_SELECT \
+	 CVMX_ADD_IO_SEG(0x00011F0000008500ull)
+#define CVMX_PEXP_NPEI_DMA0_INT_LEVEL \
+	 CVMX_ADD_IO_SEG(0x00011F00000085C0ull)
+#define CVMX_PEXP_NPEI_DMA1_INT_LEVEL \
+	 CVMX_ADD_IO_SEG(0x00011F00000085D0ull)
+#define CVMX_PEXP_NPEI_DMAX_COUNTS(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000008450ull + (((offset) & 7) * 16))
+#define CVMX_PEXP_NPEI_DMAX_DBELL(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F00000083B0ull + (((offset) & 7) * 16))
+#define CVMX_PEXP_NPEI_DMAX_IBUFF_SADDR(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000008400ull + (((offset) & 7) * 16))
+#define CVMX_PEXP_NPEI_DMAX_NADDR(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F00000084A0ull + (((offset) & 7) * 16))
+#define CVMX_PEXP_NPEI_DMA_CNTS \
+	 CVMX_ADD_IO_SEG(0x00011F00000085E0ull)
+#define CVMX_PEXP_NPEI_DMA_CONTROL \
+	 CVMX_ADD_IO_SEG(0x00011F00000083A0ull)
+#define CVMX_PEXP_NPEI_INT_A_ENB \
+	 CVMX_ADD_IO_SEG(0x00011F0000008560ull)
+#define CVMX_PEXP_NPEI_INT_A_ENB2 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BCE0ull)
+#define CVMX_PEXP_NPEI_INT_A_SUM \
+	 CVMX_ADD_IO_SEG(0x00011F0000008550ull)
+#define CVMX_PEXP_NPEI_INT_ENB \
+	 CVMX_ADD_IO_SEG(0x00011F0000008540ull)
+#define CVMX_PEXP_NPEI_INT_ENB2 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BCD0ull)
+#define CVMX_PEXP_NPEI_INT_INFO \
+	 CVMX_ADD_IO_SEG(0x00011F0000008590ull)
+#define CVMX_PEXP_NPEI_INT_SUM \
+	 CVMX_ADD_IO_SEG(0x00011F0000008530ull)
+#define CVMX_PEXP_NPEI_INT_SUM2 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BCC0ull)
+#define CVMX_PEXP_NPEI_LAST_WIN_RDATA0 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008600ull)
+#define CVMX_PEXP_NPEI_LAST_WIN_RDATA1 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008610ull)
+#define CVMX_PEXP_NPEI_MEM_ACCESS_CTL \
+	 CVMX_ADD_IO_SEG(0x00011F00000084F0ull)
+#define CVMX_PEXP_NPEI_MEM_ACCESS_SUBIDX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000008280ull + (((offset) & 31) * 16) - 16 * 12)
+#define CVMX_PEXP_NPEI_MSI_ENB0 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BC50ull)
+#define CVMX_PEXP_NPEI_MSI_ENB1 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BC60ull)
+#define CVMX_PEXP_NPEI_MSI_ENB2 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BC70ull)
+#define CVMX_PEXP_NPEI_MSI_ENB3 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BC80ull)
+#define CVMX_PEXP_NPEI_MSI_RCV0 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BC10ull)
+#define CVMX_PEXP_NPEI_MSI_RCV1 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BC20ull)
+#define CVMX_PEXP_NPEI_MSI_RCV2 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BC30ull)
+#define CVMX_PEXP_NPEI_MSI_RCV3 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BC40ull)
+#define CVMX_PEXP_NPEI_MSI_RD_MAP \
+	 CVMX_ADD_IO_SEG(0x00011F000000BCA0ull)
+#define CVMX_PEXP_NPEI_MSI_W1C_ENB0 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BCF0ull)
+#define CVMX_PEXP_NPEI_MSI_W1C_ENB1 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BD00ull)
+#define CVMX_PEXP_NPEI_MSI_W1C_ENB2 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BD10ull)
+#define CVMX_PEXP_NPEI_MSI_W1C_ENB3 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BD20ull)
+#define CVMX_PEXP_NPEI_MSI_W1S_ENB0 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BD30ull)
+#define CVMX_PEXP_NPEI_MSI_W1S_ENB1 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BD40ull)
+#define CVMX_PEXP_NPEI_MSI_W1S_ENB2 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BD50ull)
+#define CVMX_PEXP_NPEI_MSI_W1S_ENB3 \
+	 CVMX_ADD_IO_SEG(0x00011F000000BD60ull)
+#define CVMX_PEXP_NPEI_MSI_WR_MAP \
+	 CVMX_ADD_IO_SEG(0x00011F000000BC90ull)
+#define CVMX_PEXP_NPEI_PCIE_CREDIT_CNT \
+	 CVMX_ADD_IO_SEG(0x00011F000000BD70ull)
+#define CVMX_PEXP_NPEI_PCIE_MSI_RCV \
+	 CVMX_ADD_IO_SEG(0x00011F000000BCB0ull)
+#define CVMX_PEXP_NPEI_PCIE_MSI_RCV_B1 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008650ull)
+#define CVMX_PEXP_NPEI_PCIE_MSI_RCV_B2 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008660ull)
+#define CVMX_PEXP_NPEI_PCIE_MSI_RCV_B3 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008670ull)
+#define CVMX_PEXP_NPEI_PKTX_CNTS(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F000000A400ull + (((offset) & 31) * 16))
+#define CVMX_PEXP_NPEI_PKTX_INSTR_BADDR(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F000000A800ull + (((offset) & 31) * 16))
+#define CVMX_PEXP_NPEI_PKTX_INSTR_BAOFF_DBELL(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F000000AC00ull + (((offset) & 31) * 16))
+#define CVMX_PEXP_NPEI_PKTX_INSTR_FIFO_RSIZE(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F000000B000ull + (((offset) & 31) * 16))
+#define CVMX_PEXP_NPEI_PKTX_INSTR_HEADER(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F000000B400ull + (((offset) & 31) * 16))
+#define CVMX_PEXP_NPEI_PKTX_IN_BP(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F000000B800ull + (((offset) & 31) * 16))
+#define CVMX_PEXP_NPEI_PKTX_SLIST_BADDR(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000009400ull + (((offset) & 31) * 16))
+#define CVMX_PEXP_NPEI_PKTX_SLIST_BAOFF_DBELL(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000009800ull + (((offset) & 31) * 16))
+#define CVMX_PEXP_NPEI_PKTX_SLIST_FIFO_RSIZE(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F0000009C00ull + (((offset) & 31) * 16))
+#define CVMX_PEXP_NPEI_PKT_CNT_INT \
+	 CVMX_ADD_IO_SEG(0x00011F0000009110ull)
+#define CVMX_PEXP_NPEI_PKT_CNT_INT_ENB \
+	 CVMX_ADD_IO_SEG(0x00011F0000009130ull)
+#define CVMX_PEXP_NPEI_PKT_DATA_OUT_ES \
+	 CVMX_ADD_IO_SEG(0x00011F00000090B0ull)
+#define CVMX_PEXP_NPEI_PKT_DATA_OUT_NS \
+	 CVMX_ADD_IO_SEG(0x00011F00000090A0ull)
+#define CVMX_PEXP_NPEI_PKT_DATA_OUT_ROR \
+	 CVMX_ADD_IO_SEG(0x00011F0000009090ull)
+#define CVMX_PEXP_NPEI_PKT_DPADDR \
+	 CVMX_ADD_IO_SEG(0x00011F0000009080ull)
+#define CVMX_PEXP_NPEI_PKT_INPUT_CONTROL \
+	 CVMX_ADD_IO_SEG(0x00011F0000009150ull)
+#define CVMX_PEXP_NPEI_PKT_INSTR_ENB \
+	 CVMX_ADD_IO_SEG(0x00011F0000009000ull)
+#define CVMX_PEXP_NPEI_PKT_INSTR_RD_SIZE \
+	 CVMX_ADD_IO_SEG(0x00011F0000009190ull)
+#define CVMX_PEXP_NPEI_PKT_INSTR_SIZE \
+	 CVMX_ADD_IO_SEG(0x00011F0000009020ull)
+#define CVMX_PEXP_NPEI_PKT_INT_LEVELS \
+	 CVMX_ADD_IO_SEG(0x00011F0000009100ull)
+#define CVMX_PEXP_NPEI_PKT_IN_BP \
+	 CVMX_ADD_IO_SEG(0x00011F00000086B0ull)
+#define CVMX_PEXP_NPEI_PKT_IN_DONEX_CNTS(offset) \
+	 CVMX_ADD_IO_SEG(0x00011F000000A000ull + (((offset) & 31) * 16))
+#define CVMX_PEXP_NPEI_PKT_IN_INSTR_COUNTS \
+	 CVMX_ADD_IO_SEG(0x00011F00000086A0ull)
+#define CVMX_PEXP_NPEI_PKT_IN_PCIE_PORT \
+	 CVMX_ADD_IO_SEG(0x00011F00000091A0ull)
+#define CVMX_PEXP_NPEI_PKT_IPTR \
+	 CVMX_ADD_IO_SEG(0x00011F0000009070ull)
+#define CVMX_PEXP_NPEI_PKT_OUTPUT_WMARK \
+	 CVMX_ADD_IO_SEG(0x00011F0000009160ull)
+#define CVMX_PEXP_NPEI_PKT_OUT_BMODE \
+	 CVMX_ADD_IO_SEG(0x00011F00000090D0ull)
+#define CVMX_PEXP_NPEI_PKT_OUT_ENB \
+	 CVMX_ADD_IO_SEG(0x00011F0000009010ull)
+#define CVMX_PEXP_NPEI_PKT_PCIE_PORT \
+	 CVMX_ADD_IO_SEG(0x00011F00000090E0ull)
+#define CVMX_PEXP_NPEI_PKT_PORT_IN_RST \
+	 CVMX_ADD_IO_SEG(0x00011F0000008690ull)
+#define CVMX_PEXP_NPEI_PKT_SLIST_ES \
+	 CVMX_ADD_IO_SEG(0x00011F0000009050ull)
+#define CVMX_PEXP_NPEI_PKT_SLIST_ID_SIZE \
+	 CVMX_ADD_IO_SEG(0x00011F0000009180ull)
+#define CVMX_PEXP_NPEI_PKT_SLIST_NS \
+	 CVMX_ADD_IO_SEG(0x00011F0000009040ull)
+#define CVMX_PEXP_NPEI_PKT_SLIST_ROR \
+	 CVMX_ADD_IO_SEG(0x00011F0000009030ull)
+#define CVMX_PEXP_NPEI_PKT_TIME_INT \
+	 CVMX_ADD_IO_SEG(0x00011F0000009120ull)
+#define CVMX_PEXP_NPEI_PKT_TIME_INT_ENB \
+	 CVMX_ADD_IO_SEG(0x00011F0000009140ull)
+#define CVMX_PEXP_NPEI_RSL_INT_BLOCKS \
+	 CVMX_ADD_IO_SEG(0x00011F0000008520ull)
+#define CVMX_PEXP_NPEI_SCRATCH_1 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008270ull)
+#define CVMX_PEXP_NPEI_STATE1 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008620ull)
+#define CVMX_PEXP_NPEI_STATE2 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008630ull)
+#define CVMX_PEXP_NPEI_STATE3 \
+	 CVMX_ADD_IO_SEG(0x00011F0000008640ull)
+#define CVMX_PEXP_NPEI_WINDOW_CTL \
+	 CVMX_ADD_IO_SEG(0x00011F0000008380ull)
+
+#endif
diff --git a/arch/mips/include/asm/octeon/cvmx.h b/arch/mips/include/asm/octeon/cvmx.h
index 03fddfa..e31e3fe 100644
--- a/arch/mips/include/asm/octeon/cvmx.h
+++ b/arch/mips/include/asm/octeon/cvmx.h
@@ -376,6 +376,18 @@
 }
 
 /**
+ * Wait for the specified number of cycle
+ *
+ */
+static inline void cvmx_wait(uint64_t cycles)
+{
+	uint64_t done = cvmx_get_cycle() + cycles;
+
+	while (cvmx_get_cycle() < done)
+		; /* Spin */
+}
+
+/**
  * Reads a chip global cycle counter.  This counts CPU cycles since
  * chip reset.  The counter is 64 bit.
  * This register does not exist on CN38XX pass 1 silicion
diff --git a/arch/mips/include/asm/octeon/octeon-feature.h b/arch/mips/include/asm/octeon/octeon-feature.h
index 04fac68..ef24a7b 100644
--- a/arch/mips/include/asm/octeon/octeon-feature.h
+++ b/arch/mips/include/asm/octeon/octeon-feature.h
@@ -57,6 +57,13 @@
 	OCTEON_FEATURE_RAID,
 	/* Octeon has a builtin USB */
 	OCTEON_FEATURE_USB,
+	/* Octeon IPD can run without using work queue entries */
+	OCTEON_FEATURE_NO_WPTR,
+	/* Octeon has DFA state machines */
+	OCTEON_FEATURE_DFA,
+	/* Octeon MDIO block supports clause 45 transactions for 10
+	 * Gig support */
+	OCTEON_FEATURE_MDIO_CLAUSE_45,
 };
 
 static inline int cvmx_fuse_read(int fuse);
@@ -112,6 +119,26 @@
 	case OCTEON_FEATURE_USB:
 		return !(OCTEON_IS_MODEL(OCTEON_CN38XX)
 			 || OCTEON_IS_MODEL(OCTEON_CN58XX));
+	case OCTEON_FEATURE_NO_WPTR:
+		return (OCTEON_IS_MODEL(OCTEON_CN56XX)
+			 || OCTEON_IS_MODEL(OCTEON_CN52XX))
+			&& !OCTEON_IS_MODEL(OCTEON_CN56XX_PASS1_X)
+			&& !OCTEON_IS_MODEL(OCTEON_CN52XX_PASS1_X);
+	case OCTEON_FEATURE_DFA:
+		if (!OCTEON_IS_MODEL(OCTEON_CN38XX)
+		    && !OCTEON_IS_MODEL(OCTEON_CN31XX)
+		    && !OCTEON_IS_MODEL(OCTEON_CN58XX))
+			return 0;
+		else if (OCTEON_IS_MODEL(OCTEON_CN3020))
+			return 0;
+		else if (OCTEON_IS_MODEL(OCTEON_CN38XX_PASS1))
+			return 1;
+		else
+			return !cvmx_fuse_read(120);
+	case OCTEON_FEATURE_MDIO_CLAUSE_45:
+		return !(OCTEON_IS_MODEL(OCTEON_CN3XXX)
+			 || OCTEON_IS_MODEL(OCTEON_CN58XX)
+			 || OCTEON_IS_MODEL(OCTEON_CN50XX));
 	}
 	return 0;
 }
diff --git a/arch/mips/include/asm/octeon/octeon.h b/arch/mips/include/asm/octeon/octeon.h
index edc6760..cac9b1a 100644
--- a/arch/mips/include/asm/octeon/octeon.h
+++ b/arch/mips/include/asm/octeon/octeon.h
@@ -245,4 +245,6 @@
 	return cvmx_read64_uint32(address ^ 4);
 }
 
+extern struct cvmx_bootinfo *octeon_bootinfo;
+
 #endif /* __ASM_OCTEON_OCTEON_H */
diff --git a/arch/mips/include/asm/page.h b/arch/mips/include/asm/page.h
index 72c80d2..dc0eaa7 100644
--- a/arch/mips/include/asm/page.h
+++ b/arch/mips/include/asm/page.h
@@ -32,6 +32,11 @@
 #define PAGE_SIZE	(1UL << PAGE_SHIFT)
 #define PAGE_MASK       (~((1 << PAGE_SHIFT) - 1))
 
+#define HPAGE_SHIFT	(PAGE_SHIFT + PAGE_SHIFT - 3)
+#define HPAGE_SIZE	((1UL) << HPAGE_SHIFT)
+#define HPAGE_MASK	(~(HPAGE_SIZE - 1))
+#define HUGETLB_PAGE_ORDER	(HPAGE_SHIFT - PAGE_SHIFT)
+
 #ifndef __ASSEMBLY__
 
 #include <linux/pfn.h>
diff --git a/arch/mips/include/asm/pci.h b/arch/mips/include/asm/pci.h
index 053e463..a68d111 100644
--- a/arch/mips/include/asm/pci.h
+++ b/arch/mips/include/asm/pci.h
@@ -142,19 +142,6 @@
 extern void pcibios_bus_to_resource(struct pci_dev *dev, struct resource *res,
 				    struct pci_bus_region *region);
 
-static inline struct resource *
-pcibios_select_root(struct pci_dev *pdev, struct resource *res)
-{
-	struct resource *root = NULL;
-
-	if (res->flags & IORESOURCE_IO)
-		root = &ioport_resource;
-	if (res->flags & IORESOURCE_MEM)
-		root = &iomem_resource;
-
-	return root;
-}
-
 #define pci_domain_nr(bus) ((struct pci_controller *)(bus)->sysdata)->index
 
 static inline int pci_proc_domain(struct pci_bus *bus)
diff --git a/arch/mips/include/asm/pgtable-bits.h b/arch/mips/include/asm/pgtable-bits.h
index 51b34a4..1073e6d 100644
--- a/arch/mips/include/asm/pgtable-bits.h
+++ b/arch/mips/include/asm/pgtable-bits.h
@@ -72,6 +72,7 @@
 #else
 
 #define _PAGE_R4KBUG                (1<<5)  /* workaround for r4k bug  */
+#define _PAGE_HUGE                  (1<<5)  /* huge tlb page */
 #define _PAGE_GLOBAL                (1<<6)
 #define _PAGE_VALID                 (1<<7)
 #define _PAGE_SILENT_READ           (1<<7)  /* synonym                 */
diff --git a/arch/mips/include/asm/pgtable.h b/arch/mips/include/asm/pgtable.h
index 6a0edf7..1a9f9b2 100644
--- a/arch/mips/include/asm/pgtable.h
+++ b/arch/mips/include/asm/pgtable.h
@@ -292,6 +292,16 @@
 		pte_val(pte) |= _PAGE_SILENT_READ;
 	return pte;
 }
+
+#ifdef _PAGE_HUGE
+static inline int pte_huge(pte_t pte)	{ return pte_val(pte) & _PAGE_HUGE; }
+
+static inline pte_t pte_mkhuge(pte_t pte)
+{
+	pte_val(pte) |= _PAGE_HUGE;
+	return pte;
+}
+#endif /* _PAGE_HUGE */
 #endif
 static inline int pte_special(pte_t pte)	{ return 0; }
 static inline pte_t pte_mkspecial(pte_t pte)	{ return pte; }
diff --git a/arch/mips/include/asm/r4kcache.h b/arch/mips/include/asm/r4kcache.h
index 4c140db..387bf59 100644
--- a/arch/mips/include/asm/r4kcache.h
+++ b/arch/mips/include/asm/r4kcache.h
@@ -399,6 +399,7 @@
 __BUILD_BLAST_CACHE(d, dcache, Index_Writeback_Inv_D, Hit_Writeback_Inv_D, 32)
 __BUILD_BLAST_CACHE(i, icache, Index_Invalidate_I, Hit_Invalidate_I, 32)
 __BUILD_BLAST_CACHE(s, scache, Index_Writeback_Inv_SD, Hit_Writeback_Inv_SD, 32)
+__BUILD_BLAST_CACHE(d, dcache, Index_Writeback_Inv_D, Hit_Writeback_Inv_D, 64)
 __BUILD_BLAST_CACHE(i, icache, Index_Invalidate_I, Hit_Invalidate_I, 64)
 __BUILD_BLAST_CACHE(s, scache, Index_Writeback_Inv_SD, Hit_Writeback_Inv_SD, 64)
 __BUILD_BLAST_CACHE(s, scache, Index_Writeback_Inv_SD, Hit_Writeback_Inv_SD, 128)
diff --git a/arch/mips/include/asm/suspend.h b/arch/mips/include/asm/suspend.h
new file mode 100644
index 0000000..294cdb6
--- /dev/null
+++ b/arch/mips/include/asm/suspend.h
@@ -0,0 +1,9 @@
+#ifndef __ASM_SUSPEND_H
+#define __ASM_SUSPEND_H
+
+static inline int arch_prepare_suspend(void) { return 0; }
+
+/* References to section boundaries */
+extern const void __nosave_begin, __nosave_end;
+
+#endif /* __ASM_SUSPEND_H */
diff --git a/arch/mips/include/asm/txx9/dmac.h b/arch/mips/include/asm/txx9/dmac.h
new file mode 100644
index 0000000..5e9151f
--- /dev/null
+++ b/arch/mips/include/asm/txx9/dmac.h
@@ -0,0 +1,51 @@
+/*
+ * TXx9 SoC DMA Controller
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+
+#ifndef __ASM_TXX9_DMAC_H
+#define __ASM_TXX9_DMAC_H
+
+#include <linux/dmaengine.h>
+
+#define TXX9_DMA_MAX_NR_CHANNELS	4
+
+/**
+ * struct txx9dmac_platform_data - Controller configuration parameters
+ * @memcpy_chan: Channel used for DMA_MEMCPY
+ * @have_64bit_regs: DMAC have 64 bit registers
+ */
+struct txx9dmac_platform_data {
+	int	memcpy_chan;
+	bool	have_64bit_regs;
+};
+
+/**
+ * struct txx9dmac_chan_platform_data - Channel configuration parameters
+ * @dmac_dev: A platform device for DMAC
+ */
+struct txx9dmac_chan_platform_data {
+	struct platform_device *dmac_dev;
+};
+
+/**
+ * struct txx9dmac_slave - Controller-specific information about a slave
+ * @tx_reg: physical address of data register used for
+ *	memory-to-peripheral transfers
+ * @rx_reg: physical address of data register used for
+ *	peripheral-to-memory transfers
+ * @reg_width: peripheral register width
+ */
+struct txx9dmac_slave {
+	u64		tx_reg;
+	u64		rx_reg;
+	unsigned int	reg_width;
+};
+
+void txx9_dmac_init(int id, unsigned long baseaddr, int irq,
+		    const struct txx9dmac_platform_data *pdata);
+
+#endif /* __ASM_TXX9_DMAC_H */
diff --git a/arch/mips/include/asm/txx9/generic.h b/arch/mips/include/asm/txx9/generic.h
index 9cde009..827dc22 100644
--- a/arch/mips/include/asm/txx9/generic.h
+++ b/arch/mips/include/asm/txx9/generic.h
@@ -91,4 +91,10 @@
 		       void (*putc)(unsigned int pos, unsigned char val));
 int txx9_7segled_putc(unsigned int pos, char c);
 
+void __init txx9_aclc_init(unsigned long baseaddr, int irq,
+			   unsigned int dmac_id,
+			   unsigned int dma_chan_out,
+			   unsigned int dma_chan_in);
+void __init txx9_sramc_init(struct resource *r);
+
 #endif /* __ASM_TXX9_GENERIC_H */
diff --git a/arch/mips/include/asm/txx9/tx4927.h b/arch/mips/include/asm/txx9/tx4927.h
index 7d813f1..18c98c5 100644
--- a/arch/mips/include/asm/txx9/tx4927.h
+++ b/arch/mips/include/asm/txx9/tx4927.h
@@ -41,6 +41,7 @@
 
 #define TX4927_SDRAMC_REG	(TX4927_REG_BASE + 0x8000)
 #define TX4927_EBUSC_REG	(TX4927_REG_BASE + 0x9000)
+#define TX4927_DMA_REG		(TX4927_REG_BASE + 0xb000)
 #define TX4927_PCIC_REG		(TX4927_REG_BASE + 0xd000)
 #define TX4927_CCFG_REG		(TX4927_REG_BASE + 0xe000)
 #define TX4927_IRC_REG		(TX4927_REG_BASE + 0xf600)
@@ -49,6 +50,7 @@
 #define TX4927_NR_SIO	2
 #define TX4927_SIO_REG(ch)	(TX4927_REG_BASE + 0xf300 + (ch) * 0x100)
 #define TX4927_PIO_REG		(TX4927_REG_BASE + 0xf500)
+#define TX4927_ACLC_REG		(TX4927_REG_BASE + 0xf700)
 
 #define TX4927_IR_ECCERR	0
 #define TX4927_IR_WTOERR	1
@@ -265,5 +267,7 @@
 void tx4927_setup_pcierr_irq(void);
 void tx4927_irq_init(void);
 void tx4927_mtd_init(int ch);
+void tx4927_dmac_init(int memcpy_chan);
+void tx4927_aclc_init(unsigned int dma_chan_out, unsigned int dma_chan_in);
 
 #endif /* __ASM_TXX9_TX4927_H */
diff --git a/arch/mips/include/asm/txx9/tx4938.h b/arch/mips/include/asm/txx9/tx4938.h
index cd8bc20..8a178f1 100644
--- a/arch/mips/include/asm/txx9/tx4938.h
+++ b/arch/mips/include/asm/txx9/tx4938.h
@@ -305,5 +305,8 @@
 };
 
 void tx4938_ata_init(unsigned int irq, unsigned int shift, int tune);
+void tx4938_dmac_init(int memcpy_chan0, int memcpy_chan1);
+void tx4938_aclc_init(void);
+void tx4938_sramc_init(void);
 
 #endif
diff --git a/arch/mips/include/asm/txx9/tx4939.h b/arch/mips/include/asm/txx9/tx4939.h
index f02c50b..d4f342c 100644
--- a/arch/mips/include/asm/txx9/tx4939.h
+++ b/arch/mips/include/asm/txx9/tx4939.h
@@ -45,6 +45,8 @@
 #define TX4939_RTC_REG		(TX4939_REG_BASE + 0xfb00)
 #define TX4939_CIR_REG		(TX4939_REG_BASE + 0xfc00)
 
+#define TX4939_RNG_REG		(TX4939_CRYPTO_REG + 0xb0)
+
 struct tx4939_le_reg {
 	__u32 r;
 	__u32 unused;
@@ -544,5 +546,9 @@
 void tx4939_rtc_init(void);
 void tx4939_ndfmc_init(unsigned int hold, unsigned int spw,
 		       unsigned char ch_mask, unsigned char wide_mask);
+void tx4939_dmac_init(int memcpy_chan0, int memcpy_chan1);
+void tx4939_aclc_init(void);
+void tx4939_sramc_init(void);
+void tx4939_rng_init(void);
 
 #endif /* __ASM_TXX9_TX4939_H */
diff --git a/arch/mips/kernel/asm-offsets.c b/arch/mips/kernel/asm-offsets.c
index c901c22..8d006ec 100644
--- a/arch/mips/kernel/asm-offsets.c
+++ b/arch/mips/kernel/asm-offsets.c
@@ -14,6 +14,7 @@
 #include <linux/mm.h>
 #include <linux/interrupt.h>
 #include <linux/kbuild.h>
+#include <linux/suspend.h>
 #include <asm/ptrace.h>
 #include <asm/processor.h>
 
@@ -326,3 +327,15 @@
 	BLANK();
 }
 #endif
+
+#ifdef CONFIG_HIBERNATION
+void output_pbe_defines(void)
+{
+	COMMENT(" Linux struct pbe offsets. ");
+	OFFSET(PBE_ADDRESS, pbe, address);
+	OFFSET(PBE_ORIG_ADDRESS, pbe, orig_address);
+	OFFSET(PBE_NEXT, pbe, next);
+	DEFINE(PBE_SIZE, sizeof(struct pbe));
+	BLANK();
+}
+#endif
diff --git a/arch/mips/kernel/cevt-txx9.c b/arch/mips/kernel/cevt-txx9.c
index 2e911e3..0037f21 100644
--- a/arch/mips/kernel/cevt-txx9.c
+++ b/arch/mips/kernel/cevt-txx9.c
@@ -20,22 +20,29 @@
 #define TIMER_CCD	0	/* 1/2 */
 #define TIMER_CLK(imclk)	((imclk) / (2 << TIMER_CCD))
 
-static struct txx9_tmr_reg __iomem *txx9_cs_tmrptr;
+struct txx9_clocksource {
+	struct clocksource cs;
+	struct txx9_tmr_reg __iomem *tmrptr;
+};
 
 static cycle_t txx9_cs_read(struct clocksource *cs)
 {
-	return __raw_readl(&txx9_cs_tmrptr->trr);
+	struct txx9_clocksource *txx9_cs =
+		container_of(cs, struct txx9_clocksource, cs);
+	return __raw_readl(&txx9_cs->tmrptr->trr);
 }
 
 /* Use 1 bit smaller width to use full bits in that width */
 #define TXX9_CLOCKSOURCE_BITS (TXX9_TIMER_BITS - 1)
 
-static struct clocksource txx9_clocksource = {
-	.name		= "TXx9",
-	.rating		= 200,
-	.read		= txx9_cs_read,
-	.mask		= CLOCKSOURCE_MASK(TXX9_CLOCKSOURCE_BITS),
-	.flags		= CLOCK_SOURCE_IS_CONTINUOUS,
+static struct txx9_clocksource txx9_clocksource = {
+	.cs = {
+		.name		= "TXx9",
+		.rating		= 200,
+		.read		= txx9_cs_read,
+		.mask		= CLOCKSOURCE_MASK(TXX9_CLOCKSOURCE_BITS),
+		.flags		= CLOCK_SOURCE_IS_CONTINUOUS,
+	},
 };
 
 void __init txx9_clocksource_init(unsigned long baseaddr,
@@ -43,8 +50,8 @@
 {
 	struct txx9_tmr_reg __iomem *tmrptr;
 
-	clocksource_set_clock(&txx9_clocksource, TIMER_CLK(imbusclk));
-	clocksource_register(&txx9_clocksource);
+	clocksource_set_clock(&txx9_clocksource.cs, TIMER_CLK(imbusclk));
+	clocksource_register(&txx9_clocksource.cs);
 
 	tmrptr = ioremap(baseaddr, sizeof(struct txx9_tmr_reg));
 	__raw_writel(TCR_BASE, &tmrptr->tcr);
@@ -53,10 +60,13 @@
 	__raw_writel(TXx9_TMITMR_TZCE, &tmrptr->itmr);
 	__raw_writel(1 << TXX9_CLOCKSOURCE_BITS, &tmrptr->cpra);
 	__raw_writel(TCR_BASE | TXx9_TMTCR_TCE, &tmrptr->tcr);
-	txx9_cs_tmrptr = tmrptr;
+	txx9_clocksource.tmrptr = tmrptr;
 }
 
-static struct txx9_tmr_reg __iomem *txx9_tmrptr;
+struct txx9_clock_event_device {
+	struct clock_event_device cd;
+	struct txx9_tmr_reg __iomem *tmrptr;
+};
 
 static void txx9tmr_stop_and_clear(struct txx9_tmr_reg __iomem *tmrptr)
 {
@@ -69,7 +79,9 @@
 static void txx9tmr_set_mode(enum clock_event_mode mode,
 			     struct clock_event_device *evt)
 {
-	struct txx9_tmr_reg __iomem *tmrptr = txx9_tmrptr;
+	struct txx9_clock_event_device *txx9_cd =
+		container_of(evt, struct txx9_clock_event_device, cd);
+	struct txx9_tmr_reg __iomem *tmrptr = txx9_cd->tmrptr;
 
 	txx9tmr_stop_and_clear(tmrptr);
 	switch (mode) {
@@ -99,7 +111,9 @@
 static int txx9tmr_set_next_event(unsigned long delta,
 				  struct clock_event_device *evt)
 {
-	struct txx9_tmr_reg __iomem *tmrptr = txx9_tmrptr;
+	struct txx9_clock_event_device *txx9_cd =
+		container_of(evt, struct txx9_clock_event_device, cd);
+	struct txx9_tmr_reg __iomem *tmrptr = txx9_cd->tmrptr;
 
 	txx9tmr_stop_and_clear(tmrptr);
 	/* start timer */
@@ -108,18 +122,22 @@
 	return 0;
 }
 
-static struct clock_event_device txx9tmr_clock_event_device = {
-	.name		= "TXx9",
-	.features	= CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT,
-	.rating		= 200,
-	.set_mode	= txx9tmr_set_mode,
-	.set_next_event	= txx9tmr_set_next_event,
+static struct txx9_clock_event_device txx9_clock_event_device = {
+	.cd = {
+		.name		= "TXx9",
+		.features	= CLOCK_EVT_FEAT_PERIODIC |
+				  CLOCK_EVT_FEAT_ONESHOT,
+		.rating		= 200,
+		.set_mode	= txx9tmr_set_mode,
+		.set_next_event	= txx9tmr_set_next_event,
+	},
 };
 
 static irqreturn_t txx9tmr_interrupt(int irq, void *dev_id)
 {
-	struct clock_event_device *cd = &txx9tmr_clock_event_device;
-	struct txx9_tmr_reg __iomem *tmrptr = txx9_tmrptr;
+	struct txx9_clock_event_device *txx9_cd = dev_id;
+	struct clock_event_device *cd = &txx9_cd->cd;
+	struct txx9_tmr_reg __iomem *tmrptr = txx9_cd->tmrptr;
 
 	__raw_writel(0, &tmrptr->tisr);	/* ack interrupt */
 	cd->event_handler(cd);
@@ -130,19 +148,20 @@
 	.handler	= txx9tmr_interrupt,
 	.flags		= IRQF_DISABLED | IRQF_PERCPU,
 	.name		= "txx9tmr",
+	.dev_id		= &txx9_clock_event_device,
 };
 
 void __init txx9_clockevent_init(unsigned long baseaddr, int irq,
 				 unsigned int imbusclk)
 {
-	struct clock_event_device *cd = &txx9tmr_clock_event_device;
+	struct clock_event_device *cd = &txx9_clock_event_device.cd;
 	struct txx9_tmr_reg __iomem *tmrptr;
 
 	tmrptr = ioremap(baseaddr, sizeof(struct txx9_tmr_reg));
 	txx9tmr_stop_and_clear(tmrptr);
 	__raw_writel(TIMER_CCD, &tmrptr->ccdr);
 	__raw_writel(0, &tmrptr->itmr);
-	txx9_tmrptr = tmrptr;
+	txx9_clock_event_device.tmrptr = tmrptr;
 
 	clockevent_set_clock(cd, TIMER_CLK(imbusclk));
 	cd->max_delta_ns =
diff --git a/arch/mips/kernel/smtc.c b/arch/mips/kernel/smtc.c
index 5f5af7d..37d51cd 100644
--- a/arch/mips/kernel/smtc.c
+++ b/arch/mips/kernel/smtc.c
@@ -924,6 +924,7 @@
 	int irq = MIPS_CPU_IRQ_BASE + 1;
 
 	smtc_ipi_nq(&freeIPIq, pipi);
+
 	switch (type_copy) {
 	case SMTC_CLOCK_TICK:
 		irq_enter();
diff --git a/arch/mips/kernel/traps.c b/arch/mips/kernel/traps.c
index e83da17..08f1edf 100644
--- a/arch/mips/kernel/traps.c
+++ b/arch/mips/kernel/traps.c
@@ -1502,7 +1502,7 @@
 			 status_set);
 
 	if (cpu_has_mips_r2) {
-		unsigned int enable = 0x0000000f;
+		unsigned int enable = 0x0000000f | cpu_hwrena_impl_bits;
 
 		if (!noulri && cpu_has_userlocal)
 			enable |= (1 << 29);
@@ -1510,10 +1510,6 @@
 		write_c0_hwrena(enable);
 	}
 
-#ifdef CONFIG_CPU_CAVIUM_OCTEON
-	write_c0_hwrena(0xc000000f); /* Octeon has register 30 and 31 */
-#endif
-
 #ifdef CONFIG_MIPS_MT_SMTC
 	if (!secondaryTC) {
 #endif /* CONFIG_MIPS_MT_SMTC */
diff --git a/arch/mips/lib/delay.c b/arch/mips/lib/delay.c
index f69c6b5..6b3b1de9 100644
--- a/arch/mips/lib/delay.c
+++ b/arch/mips/lib/delay.c
@@ -43,7 +43,7 @@
 {
 	unsigned int lpj = current_cpu_data.udelay_val;
 
-	__delay((us * 0x000010c7 * HZ * lpj) >> 32);
+	__delay((us * 0x000010c7ull * HZ * lpj) >> 32);
 }
 EXPORT_SYMBOL(__udelay);
 
@@ -51,6 +51,6 @@
 {
 	unsigned int lpj = current_cpu_data.udelay_val;
 
-	__delay((us * 0x00000005 * HZ * lpj) >> 32);
+	__delay((ns * 0x00000005ull * HZ * lpj) >> 32);
 }
 EXPORT_SYMBOL(__ndelay);
diff --git a/arch/mips/mm/Makefile b/arch/mips/mm/Makefile
index d7ec955..f0e4355 100644
--- a/arch/mips/mm/Makefile
+++ b/arch/mips/mm/Makefile
@@ -8,6 +8,7 @@
 obj-$(CONFIG_32BIT)		+= ioremap.o pgtable-32.o
 obj-$(CONFIG_64BIT)		+= pgtable-64.o
 obj-$(CONFIG_HIGHMEM)		+= highmem.o
+obj-$(CONFIG_HUGETLB_PAGE)	+= hugetlbpage.o
 
 obj-$(CONFIG_CPU_LOONGSON2)	+= c-r4k.o cex-gen.o tlb-r4k.o
 obj-$(CONFIG_CPU_MIPS32)	+= c-r4k.o cex-gen.o tlb-r4k.o
diff --git a/arch/mips/mm/c-r4k.c b/arch/mips/mm/c-r4k.c
index 171951d..71fe4cb 100644
--- a/arch/mips/mm/c-r4k.c
+++ b/arch/mips/mm/c-r4k.c
@@ -100,6 +100,12 @@
 	blast_dcache32_page(addr);
 }
 
+static inline void r4k_blast_dcache_page_dc64(unsigned long addr)
+{
+	R4600_HIT_CACHEOP_WAR_IMPL;
+	blast_dcache64_page(addr);
+}
+
 static void __cpuinit r4k_blast_dcache_page_setup(void)
 {
 	unsigned long  dc_lsize = cpu_dcache_line_size();
@@ -110,6 +116,8 @@
 		r4k_blast_dcache_page = blast_dcache16_page;
 	else if (dc_lsize == 32)
 		r4k_blast_dcache_page = r4k_blast_dcache_page_dc32;
+	else if (dc_lsize == 64)
+		r4k_blast_dcache_page = r4k_blast_dcache_page_dc64;
 }
 
 static void (* r4k_blast_dcache_page_indexed)(unsigned long addr);
@@ -124,6 +132,8 @@
 		r4k_blast_dcache_page_indexed = blast_dcache16_page_indexed;
 	else if (dc_lsize == 32)
 		r4k_blast_dcache_page_indexed = blast_dcache32_page_indexed;
+	else if (dc_lsize == 64)
+		r4k_blast_dcache_page_indexed = blast_dcache64_page_indexed;
 }
 
 static void (* r4k_blast_dcache)(void);
@@ -138,6 +148,8 @@
 		r4k_blast_dcache = blast_dcache16;
 	else if (dc_lsize == 32)
 		r4k_blast_dcache = blast_dcache32;
+	else if (dc_lsize == 64)
+		r4k_blast_dcache = blast_dcache64;
 }
 
 /* force code alignment (used for TX49XX_ICACHE_INDEX_INV_WAR) */
diff --git a/arch/mips/mm/dma-default.c b/arch/mips/mm/dma-default.c
index 4fdb7f5..7e48e76 100644
--- a/arch/mips/mm/dma-default.c
+++ b/arch/mips/mm/dma-default.c
@@ -20,9 +20,10 @@
 
 #include <dma-coherence.h>
 
-static inline unsigned long dma_addr_to_virt(dma_addr_t dma_addr)
+static inline unsigned long dma_addr_to_virt(struct device *dev,
+	dma_addr_t dma_addr)
 {
-	unsigned long addr = plat_dma_addr_to_phys(dma_addr);
+	unsigned long addr = plat_dma_addr_to_phys(dev, dma_addr);
 
 	return (unsigned long)phys_to_virt(addr);
 }
@@ -111,7 +112,7 @@
 void dma_free_noncoherent(struct device *dev, size_t size, void *vaddr,
 	dma_addr_t dma_handle)
 {
-	plat_unmap_dma_mem(dev, dma_handle);
+	plat_unmap_dma_mem(dev, dma_handle, size, DMA_BIDIRECTIONAL);
 	free_pages((unsigned long) vaddr, get_order(size));
 }
 
@@ -122,7 +123,7 @@
 {
 	unsigned long addr = (unsigned long) vaddr;
 
-	plat_unmap_dma_mem(dev, dma_handle);
+	plat_unmap_dma_mem(dev, dma_handle, size, DMA_BIDIRECTIONAL);
 
 	if (!plat_device_is_coherent(dev))
 		addr = CAC_ADDR(addr);
@@ -170,10 +171,10 @@
 	enum dma_data_direction direction)
 {
 	if (cpu_is_noncoherent_r10000(dev))
-		__dma_sync(dma_addr_to_virt(dma_addr), size,
+		__dma_sync(dma_addr_to_virt(dev, dma_addr), size,
 		           direction);
 
-	plat_unmap_dma_mem(dev, dma_addr);
+	plat_unmap_dma_mem(dev, dma_addr, size, direction);
 }
 
 EXPORT_SYMBOL(dma_unmap_single);
@@ -232,7 +233,7 @@
 			if (addr)
 				__dma_sync(addr, sg->length, direction);
 		}
-		plat_unmap_dma_mem(dev, sg->dma_address);
+		plat_unmap_dma_mem(dev, sg->dma_address, sg->length, direction);
 	}
 }
 
@@ -246,7 +247,7 @@
 	if (cpu_is_noncoherent_r10000(dev)) {
 		unsigned long addr;
 
-		addr = dma_addr_to_virt(dma_handle);
+		addr = dma_addr_to_virt(dev, dma_handle);
 		__dma_sync(addr, size, direction);
 	}
 }
@@ -262,7 +263,7 @@
 	if (!plat_device_is_coherent(dev)) {
 		unsigned long addr;
 
-		addr = dma_addr_to_virt(dma_handle);
+		addr = dma_addr_to_virt(dev, dma_handle);
 		__dma_sync(addr, size, direction);
 	}
 }
@@ -277,7 +278,7 @@
 	if (cpu_is_noncoherent_r10000(dev)) {
 		unsigned long addr;
 
-		addr = dma_addr_to_virt(dma_handle);
+		addr = dma_addr_to_virt(dev, dma_handle);
 		__dma_sync(addr + offset, size, direction);
 	}
 }
@@ -293,7 +294,7 @@
 	if (!plat_device_is_coherent(dev)) {
 		unsigned long addr;
 
-		addr = dma_addr_to_virt(dma_handle);
+		addr = dma_addr_to_virt(dev, dma_handle);
 		__dma_sync(addr + offset, size, direction);
 	}
 }
diff --git a/arch/mips/mm/hugetlbpage.c b/arch/mips/mm/hugetlbpage.c
new file mode 100644
index 0000000..471c09a
--- /dev/null
+++ b/arch/mips/mm/hugetlbpage.c
@@ -0,0 +1,101 @@
+/*
+ * MIPS Huge TLB Page Support for Kernel.
+ *
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 2002, Rohit Seth <rohit.seth@intel.com>
+ * Copyright 2005, Embedded Alley Solutions, Inc.
+ * Matt Porter <mporter@embeddedalley.com>
+ * Copyright (C) 2008, 2009 Cavium Networks, Inc.
+ */
+
+#include <linux/init.h>
+#include <linux/fs.h>
+#include <linux/mm.h>
+#include <linux/hugetlb.h>
+#include <linux/pagemap.h>
+#include <linux/smp_lock.h>
+#include <linux/slab.h>
+#include <linux/err.h>
+#include <linux/sysctl.h>
+#include <asm/mman.h>
+#include <asm/tlb.h>
+#include <asm/tlbflush.h>
+
+pte_t *huge_pte_alloc(struct mm_struct *mm, unsigned long addr,
+		      unsigned long sz)
+{
+	pgd_t *pgd;
+	pud_t *pud;
+	pte_t *pte = NULL;
+
+	pgd = pgd_offset(mm, addr);
+	pud = pud_alloc(mm, pgd, addr);
+	if (pud)
+		pte = (pte_t *)pmd_alloc(mm, pud, addr);
+
+	return pte;
+}
+
+pte_t *huge_pte_offset(struct mm_struct *mm, unsigned long addr)
+{
+	pgd_t *pgd;
+	pud_t *pud;
+	pmd_t *pmd = NULL;
+
+	pgd = pgd_offset(mm, addr);
+	if (pgd_present(*pgd)) {
+		pud = pud_offset(pgd, addr);
+		if (pud_present(*pud))
+			pmd = pmd_offset(pud, addr);
+	}
+	return (pte_t *) pmd;
+}
+
+int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep)
+{
+	return 0;
+}
+
+/*
+ * This function checks for proper alignment of input addr and len parameters.
+ */
+int is_aligned_hugepage_range(unsigned long addr, unsigned long len)
+{
+	if (len & ~HPAGE_MASK)
+		return -EINVAL;
+	if (addr & ~HPAGE_MASK)
+		return -EINVAL;
+	return 0;
+}
+
+struct page *
+follow_huge_addr(struct mm_struct *mm, unsigned long address, int write)
+{
+	return ERR_PTR(-EINVAL);
+}
+
+int pmd_huge(pmd_t pmd)
+{
+	return (pmd_val(pmd) & _PAGE_HUGE) != 0;
+}
+
+int pud_huge(pud_t pud)
+{
+	return (pud_val(pud) & _PAGE_HUGE) != 0;
+}
+
+struct page *
+follow_huge_pmd(struct mm_struct *mm, unsigned long address,
+		pmd_t *pmd, int write)
+{
+	struct page *page;
+
+	page = pte_page(*(pte_t *)pmd);
+	if (page)
+		page += ((address & ~HPAGE_MASK) >> PAGE_SHIFT);
+	return page;
+}
+
diff --git a/arch/mips/mm/tlb-r4k.c b/arch/mips/mm/tlb-r4k.c
index 892be42..f60fe51 100644
--- a/arch/mips/mm/tlb-r4k.c
+++ b/arch/mips/mm/tlb-r4k.c
@@ -11,6 +11,7 @@
 #include <linux/init.h>
 #include <linux/sched.h>
 #include <linux/mm.h>
+#include <linux/hugetlb.h>
 
 #include <asm/cpu.h>
 #include <asm/bootinfo.h>
@@ -295,21 +296,41 @@
 	pudp = pud_offset(pgdp, address);
 	pmdp = pmd_offset(pudp, address);
 	idx = read_c0_index();
-	ptep = pte_offset_map(pmdp, address);
+#ifdef CONFIG_HUGETLB_PAGE
+	/* this could be a huge page  */
+	if (pmd_huge(*pmdp)) {
+		unsigned long lo;
+		write_c0_pagemask(PM_HUGE_MASK);
+		ptep = (pte_t *)pmdp;
+		lo = pte_val(*ptep) >> 6;
+		write_c0_entrylo0(lo);
+		write_c0_entrylo1(lo + (HPAGE_SIZE >> 7));
+
+		mtc0_tlbw_hazard();
+		if (idx < 0)
+			tlb_write_random();
+		else
+			tlb_write_indexed();
+		write_c0_pagemask(PM_DEFAULT_MASK);
+	} else
+#endif
+	{
+		ptep = pte_offset_map(pmdp, address);
 
 #if defined(CONFIG_64BIT_PHYS_ADDR) && defined(CONFIG_CPU_MIPS32)
-	write_c0_entrylo0(ptep->pte_high);
-	ptep++;
-	write_c0_entrylo1(ptep->pte_high);
+		write_c0_entrylo0(ptep->pte_high);
+		ptep++;
+		write_c0_entrylo1(ptep->pte_high);
 #else
-	write_c0_entrylo0(pte_val(*ptep++) >> 6);
-	write_c0_entrylo1(pte_val(*ptep) >> 6);
+		write_c0_entrylo0(pte_val(*ptep++) >> 6);
+		write_c0_entrylo1(pte_val(*ptep) >> 6);
 #endif
-	mtc0_tlbw_hazard();
-	if (idx < 0)
-		tlb_write_random();
-	else
-		tlb_write_indexed();
+		mtc0_tlbw_hazard();
+		if (idx < 0)
+			tlb_write_random();
+		else
+			tlb_write_indexed();
+	}
 	tlbw_use_hazard();
 	FLUSH_ITLB_VM(vma);
 	EXIT_CRITICAL(flags);
diff --git a/arch/mips/mm/tlbex.c b/arch/mips/mm/tlbex.c
index 0615b62..8f606ea 100644
--- a/arch/mips/mm/tlbex.c
+++ b/arch/mips/mm/tlbex.c
@@ -6,8 +6,9 @@
  * Synthesize TLB refill handlers at runtime.
  *
  * Copyright (C) 2004, 2005, 2006, 2008  Thiemo Seufer
- * Copyright (C) 2005, 2007  Maciej W. Rozycki
+ * Copyright (C) 2005, 2007, 2008, 2009  Maciej W. Rozycki
  * Copyright (C) 2006  Ralf Baechle (ralf@linux-mips.org)
+ * Copyright (C) 2008, 2009 Cavium Networks, Inc.
  *
  * ... and the days got worse and worse and now you see
  * I've gone completly out of my mind.
@@ -19,6 +20,7 @@
  * (Condolences to Napoleon XIV)
  */
 
+#include <linux/bug.h>
 #include <linux/kernel.h>
 #include <linux/types.h>
 #include <linux/string.h>
@@ -82,6 +84,9 @@
 	label_nopage_tlbm,
 	label_smp_pgtable_change,
 	label_r3000_write_probe_fail,
+#ifdef CONFIG_HUGETLB_PAGE
+	label_tlb_huge_update,
+#endif
 };
 
 UASM_L_LA(_second_part)
@@ -98,6 +103,9 @@
 UASM_L_LA(_nopage_tlbm)
 UASM_L_LA(_smp_pgtable_change)
 UASM_L_LA(_r3000_write_probe_fail)
+#ifdef CONFIG_HUGETLB_PAGE
+UASM_L_LA(_tlb_huge_update)
+#endif
 
 /*
  * For debug purposes.
@@ -125,6 +133,7 @@
 #define C0_TCBIND	2, 2
 #define C0_ENTRYLO1	3, 0
 #define C0_CONTEXT	4, 0
+#define C0_PAGEMASK	5, 0
 #define C0_BADVADDR	8, 0
 #define C0_ENTRYHI	10, 0
 #define C0_EPC		14, 0
@@ -258,7 +267,8 @@
 	}
 
 	if (cpu_has_mips_r2) {
-		uasm_i_ehb(p);
+		if (cpu_has_mips_r2_exec_hazard)
+			uasm_i_ehb(p);
 		tlbw(p);
 		return;
 	}
@@ -310,7 +320,6 @@
 	case CPU_BCM3302:
 	case CPU_BCM4710:
 	case CPU_LOONGSON2:
-	case CPU_CAVIUM_OCTEON:
 	case CPU_R5500:
 		if (m4kc_tlbp_war())
 			uasm_i_nop(p);
@@ -382,6 +391,98 @@
 	}
 }
 
+#ifdef CONFIG_HUGETLB_PAGE
+static __cpuinit void build_huge_tlb_write_entry(u32 **p,
+						 struct uasm_label **l,
+						 struct uasm_reloc **r,
+						 unsigned int tmp,
+						 enum tlb_write_entry wmode)
+{
+	/* Set huge page tlb entry size */
+	uasm_i_lui(p, tmp, PM_HUGE_MASK >> 16);
+	uasm_i_ori(p, tmp, tmp, PM_HUGE_MASK & 0xffff);
+	uasm_i_mtc0(p, tmp, C0_PAGEMASK);
+
+	build_tlb_write_entry(p, l, r, wmode);
+
+	/* Reset default page size */
+	if (PM_DEFAULT_MASK >> 16) {
+		uasm_i_lui(p, tmp, PM_DEFAULT_MASK >> 16);
+		uasm_i_ori(p, tmp, tmp, PM_DEFAULT_MASK & 0xffff);
+		uasm_il_b(p, r, label_leave);
+		uasm_i_mtc0(p, tmp, C0_PAGEMASK);
+	} else if (PM_DEFAULT_MASK) {
+		uasm_i_ori(p, tmp, 0, PM_DEFAULT_MASK);
+		uasm_il_b(p, r, label_leave);
+		uasm_i_mtc0(p, tmp, C0_PAGEMASK);
+	} else {
+		uasm_il_b(p, r, label_leave);
+		uasm_i_mtc0(p, 0, C0_PAGEMASK);
+	}
+}
+
+/*
+ * Check if Huge PTE is present, if so then jump to LABEL.
+ */
+static void __cpuinit
+build_is_huge_pte(u32 **p, struct uasm_reloc **r, unsigned int tmp,
+		unsigned int pmd, int lid)
+{
+	UASM_i_LW(p, tmp, 0, pmd);
+	uasm_i_andi(p, tmp, tmp, _PAGE_HUGE);
+	uasm_il_bnez(p, r, tmp, lid);
+}
+
+static __cpuinit void build_huge_update_entries(u32 **p,
+						unsigned int pte,
+						unsigned int tmp)
+{
+	int small_sequence;
+
+	/*
+	 * A huge PTE describes an area the size of the
+	 * configured huge page size. This is twice the
+	 * of the large TLB entry size we intend to use.
+	 * A TLB entry half the size of the configured
+	 * huge page size is configured into entrylo0
+	 * and entrylo1 to cover the contiguous huge PTE
+	 * address space.
+	 */
+	small_sequence = (HPAGE_SIZE >> 7) < 0x10000;
+
+	/* We can clobber tmp.  It isn't used after this.*/
+	if (!small_sequence)
+		uasm_i_lui(p, tmp, HPAGE_SIZE >> (7 + 16));
+
+	UASM_i_SRL(p, pte, pte, 6); /* convert to entrylo */
+	uasm_i_mtc0(p, pte, C0_ENTRYLO0); /* load it */
+	/* convert to entrylo1 */
+	if (small_sequence)
+		UASM_i_ADDIU(p, pte, pte, HPAGE_SIZE >> 7);
+	else
+		UASM_i_ADDU(p, pte, pte, tmp);
+
+	uasm_i_mtc0(p, pte, C0_ENTRYLO1); /* load it */
+}
+
+static __cpuinit void build_huge_handler_tail(u32 **p,
+					      struct uasm_reloc **r,
+					      struct uasm_label **l,
+					      unsigned int pte,
+					      unsigned int ptr)
+{
+#ifdef CONFIG_SMP
+	UASM_i_SC(p, pte, 0, ptr);
+	uasm_il_beqz(p, r, pte, label_tlb_huge_update);
+	UASM_i_LW(p, pte, 0, ptr); /* Needed because SC killed our PTE */
+#else
+	UASM_i_SW(p, pte, 0, ptr);
+#endif
+	build_huge_update_entries(p, pte, ptr);
+	build_huge_tlb_write_entry(p, l, r, pte, tlb_indexed);
+}
+#endif /* CONFIG_HUGETLB_PAGE */
+
 #ifdef CONFIG_64BIT
 /*
  * TMP and PTR are scratch.
@@ -649,6 +750,14 @@
 #endif
 }
 
+/*
+ * For a 64-bit kernel, we are using the 64-bit XTLB refill exception
+ * because EXL == 0.  If we wrap, we can also use the 32 instruction
+ * slots before the XTLB refill exception handler which belong to the
+ * unused TLB refill exception.
+ */
+#define MIPS64_REFILL_INSNS 32
+
 static void __cpuinit build_r4000_tlb_refill_handler(void)
 {
 	u32 *p = tlb_handler;
@@ -680,12 +789,23 @@
 	build_get_pgde32(&p, K0, K1); /* get pgd in K1 */
 #endif
 
+#ifdef CONFIG_HUGETLB_PAGE
+	build_is_huge_pte(&p, &r, K0, K1, label_tlb_huge_update);
+#endif
+
 	build_get_ptep(&p, K0, K1);
 	build_update_entries(&p, K0, K1);
 	build_tlb_write_entry(&p, &l, &r, tlb_random);
 	uasm_l_leave(&l, p);
 	uasm_i_eret(&p); /* return from trap */
 
+#ifdef CONFIG_HUGETLB_PAGE
+	uasm_l_tlb_huge_update(&l, p);
+	UASM_i_LW(&p, K0, 0, K1);
+	build_huge_update_entries(&p, K0, K1);
+	build_huge_tlb_write_entry(&p, &l, &r, K0, tlb_random);
+#endif
+
 #ifdef CONFIG_64BIT
 	build_get_pgd_vmalloc64(&p, &l, &r, K0, K1);
 #endif
@@ -702,9 +822,10 @@
 	if ((p - tlb_handler) > 64)
 		panic("TLB refill handler space exceeded");
 #else
-	if (((p - tlb_handler) > 63)
-	    || (((p - tlb_handler) > 61)
-		&& uasm_insn_has_bdelay(relocs, tlb_handler + 29)))
+	if (((p - tlb_handler) > (MIPS64_REFILL_INSNS * 2) - 1)
+	    || (((p - tlb_handler) > (MIPS64_REFILL_INSNS * 2) - 3)
+		&& uasm_insn_has_bdelay(relocs,
+					tlb_handler + MIPS64_REFILL_INSNS - 3)))
 		panic("TLB refill handler space exceeded");
 #endif
 
@@ -717,39 +838,74 @@
 	uasm_copy_handler(relocs, labels, tlb_handler, p, f);
 	final_len = p - tlb_handler;
 #else /* CONFIG_64BIT */
-	f = final_handler + 32;
-	if ((p - tlb_handler) <= 32) {
+	f = final_handler + MIPS64_REFILL_INSNS;
+	if ((p - tlb_handler) <= MIPS64_REFILL_INSNS) {
 		/* Just copy the handler. */
 		uasm_copy_handler(relocs, labels, tlb_handler, p, f);
 		final_len = p - tlb_handler;
 	} else {
-		u32 *split = tlb_handler + 30;
+#if defined(CONFIG_HUGETLB_PAGE)
+		const enum label_id ls = label_tlb_huge_update;
+#elif defined(MODULE_START)
+		const enum label_id ls = label_module_alloc;
+#else
+		const enum label_id ls = label_vmalloc;
+#endif
+		u32 *split;
+		int ov = 0;
+		int i;
+
+		for (i = 0; i < ARRAY_SIZE(labels) && labels[i].lab != ls; i++)
+			;
+		BUG_ON(i == ARRAY_SIZE(labels));
+		split = labels[i].addr;
 
 		/*
-		 * Find the split point.
+		 * See if we have overflown one way or the other.
 		 */
-		if (uasm_insn_has_bdelay(relocs, split - 1))
-			split--;
+		if (split > tlb_handler + MIPS64_REFILL_INSNS ||
+		    split < p - MIPS64_REFILL_INSNS)
+			ov = 1;
 
+		if (ov) {
+			/*
+			 * Split two instructions before the end.  One
+			 * for the branch and one for the instruction
+			 * in the delay slot.
+			 */
+			split = tlb_handler + MIPS64_REFILL_INSNS - 2;
+
+			/*
+			 * If the branch would fall in a delay slot,
+			 * we must back up an additional instruction
+			 * so that it is no longer in a delay slot.
+			 */
+			if (uasm_insn_has_bdelay(relocs, split - 1))
+				split--;
+		}
 		/* Copy first part of the handler. */
 		uasm_copy_handler(relocs, labels, tlb_handler, split, f);
 		f += split - tlb_handler;
 
-		/* Insert branch. */
-		uasm_l_split(&l, final_handler);
-		uasm_il_b(&f, &r, label_split);
-		if (uasm_insn_has_bdelay(relocs, split))
-			uasm_i_nop(&f);
-		else {
-			uasm_copy_handler(relocs, labels, split, split + 1, f);
-			uasm_move_labels(labels, f, f + 1, -1);
-			f++;
-			split++;
+		if (ov) {
+			/* Insert branch. */
+			uasm_l_split(&l, final_handler);
+			uasm_il_b(&f, &r, label_split);
+			if (uasm_insn_has_bdelay(relocs, split))
+				uasm_i_nop(&f);
+			else {
+				uasm_copy_handler(relocs, labels,
+						  split, split + 1, f);
+				uasm_move_labels(labels, f, f + 1, -1);
+				f++;
+				split++;
+			}
 		}
 
 		/* Copy the rest of the handler. */
 		uasm_copy_handler(relocs, labels, split, p, final_handler);
-		final_len = (f - (final_handler + 32)) + (p - split);
+		final_len = (f - (final_handler + MIPS64_REFILL_INSNS)) +
+			    (p - split);
 	}
 #endif /* CONFIG_64BIT */
 
@@ -782,7 +938,7 @@
 u32 handle_tlbm[FASTPATH_SIZE] __cacheline_aligned;
 
 static void __cpuinit
-iPTE_LW(u32 **p, struct uasm_label **l, unsigned int pte, unsigned int ptr)
+iPTE_LW(u32 **p, unsigned int pte, unsigned int ptr)
 {
 #ifdef CONFIG_SMP
 # ifdef CONFIG_64BIT_PHYS_ADDR
@@ -862,13 +1018,13 @@
  * with it's original value.
  */
 static void __cpuinit
-build_pte_present(u32 **p, struct uasm_label **l, struct uasm_reloc **r,
+build_pte_present(u32 **p, struct uasm_reloc **r,
 		  unsigned int pte, unsigned int ptr, enum label_id lid)
 {
 	uasm_i_andi(p, pte, pte, _PAGE_PRESENT | _PAGE_READ);
 	uasm_i_xori(p, pte, pte, _PAGE_PRESENT | _PAGE_READ);
 	uasm_il_bnez(p, r, pte, lid);
-	iPTE_LW(p, l, pte, ptr);
+	iPTE_LW(p, pte, ptr);
 }
 
 /* Make PTE valid, store result in PTR. */
@@ -886,13 +1042,13 @@
  * restore PTE with value from PTR when done.
  */
 static void __cpuinit
-build_pte_writable(u32 **p, struct uasm_label **l, struct uasm_reloc **r,
+build_pte_writable(u32 **p, struct uasm_reloc **r,
 		   unsigned int pte, unsigned int ptr, enum label_id lid)
 {
 	uasm_i_andi(p, pte, pte, _PAGE_PRESENT | _PAGE_WRITE);
 	uasm_i_xori(p, pte, pte, _PAGE_PRESENT | _PAGE_WRITE);
 	uasm_il_bnez(p, r, pte, lid);
-	iPTE_LW(p, l, pte, ptr);
+	iPTE_LW(p, pte, ptr);
 }
 
 /* Make PTE writable, update software status bits as well, then store
@@ -913,12 +1069,12 @@
  * restore PTE with value from PTR when done.
  */
 static void __cpuinit
-build_pte_modifiable(u32 **p, struct uasm_label **l, struct uasm_reloc **r,
+build_pte_modifiable(u32 **p, struct uasm_reloc **r,
 		     unsigned int pte, unsigned int ptr, enum label_id lid)
 {
 	uasm_i_andi(p, pte, pte, _PAGE_WRITE);
 	uasm_il_beqz(p, r, pte, lid);
-	iPTE_LW(p, l, pte, ptr);
+	iPTE_LW(p, pte, ptr);
 }
 
 /*
@@ -994,7 +1150,7 @@
 	memset(relocs, 0, sizeof(relocs));
 
 	build_r3000_tlbchange_handler_head(&p, K0, K1);
-	build_pte_present(&p, &l, &r, K0, K1, label_nopage_tlbl);
+	build_pte_present(&p, &r, K0, K1, label_nopage_tlbl);
 	uasm_i_nop(&p); /* load delay */
 	build_make_valid(&p, &r, K0, K1);
 	build_r3000_tlb_reload_write(&p, &l, &r, K0, K1);
@@ -1024,7 +1180,7 @@
 	memset(relocs, 0, sizeof(relocs));
 
 	build_r3000_tlbchange_handler_head(&p, K0, K1);
-	build_pte_writable(&p, &l, &r, K0, K1, label_nopage_tlbs);
+	build_pte_writable(&p, &r, K0, K1, label_nopage_tlbs);
 	uasm_i_nop(&p); /* load delay */
 	build_make_write(&p, &r, K0, K1);
 	build_r3000_tlb_reload_write(&p, &l, &r, K0, K1);
@@ -1054,7 +1210,7 @@
 	memset(relocs, 0, sizeof(relocs));
 
 	build_r3000_tlbchange_handler_head(&p, K0, K1);
-	build_pte_modifiable(&p, &l, &r, K0, K1, label_nopage_tlbm);
+	build_pte_modifiable(&p, &r, K0, K1, label_nopage_tlbm);
 	uasm_i_nop(&p); /* load delay */
 	build_make_write(&p, &r, K0, K1);
 	build_r3000_pte_reload_tlbwi(&p, K0, K1);
@@ -1087,6 +1243,15 @@
 	build_get_pgde32(p, pte, ptr); /* get pgd in ptr */
 #endif
 
+#ifdef CONFIG_HUGETLB_PAGE
+	/*
+	 * For huge tlb entries, pmd doesn't contain an address but
+	 * instead contains the tlb pte. Check the PAGE_HUGE bit and
+	 * see if we need to jump to huge tlb processing.
+	 */
+	build_is_huge_pte(p, r, pte, ptr, label_tlb_huge_update);
+#endif
+
 	UASM_i_MFC0(p, pte, C0_BADVADDR);
 	UASM_i_LW(p, ptr, 0, ptr);
 	UASM_i_SRL(p, pte, pte, PAGE_SHIFT + PTE_ORDER - PTE_T_LOG2);
@@ -1096,7 +1261,7 @@
 #ifdef CONFIG_SMP
 	uasm_l_smp_pgtable_change(l, *p);
 #endif
-	iPTE_LW(p, l, pte, ptr); /* get even pte */
+	iPTE_LW(p, pte, ptr); /* get even pte */
 	if (!m4kc_tlbp_war())
 		build_tlb_probe_entry(p);
 }
@@ -1138,12 +1303,25 @@
 	}
 
 	build_r4000_tlbchange_handler_head(&p, &l, &r, K0, K1);
-	build_pte_present(&p, &l, &r, K0, K1, label_nopage_tlbl);
+	build_pte_present(&p, &r, K0, K1, label_nopage_tlbl);
 	if (m4kc_tlbp_war())
 		build_tlb_probe_entry(&p);
 	build_make_valid(&p, &r, K0, K1);
 	build_r4000_tlbchange_handler_tail(&p, &l, &r, K0, K1);
 
+#ifdef CONFIG_HUGETLB_PAGE
+	/*
+	 * This is the entry point when build_r4000_tlbchange_handler_head
+	 * spots a huge page.
+	 */
+	uasm_l_tlb_huge_update(&l, p);
+	iPTE_LW(&p, K0, K1);
+	build_pte_present(&p, &r, K0, K1, label_nopage_tlbl);
+	build_tlb_probe_entry(&p);
+	uasm_i_ori(&p, K0, K0, (_PAGE_ACCESSED | _PAGE_VALID));
+	build_huge_handler_tail(&p, &r, &l, K0, K1);
+#endif
+
 	uasm_l_nopage_tlbl(&l, p);
 	uasm_i_j(&p, (unsigned long)tlb_do_page_fault_0 & 0x0fffffff);
 	uasm_i_nop(&p);
@@ -1169,12 +1347,26 @@
 	memset(relocs, 0, sizeof(relocs));
 
 	build_r4000_tlbchange_handler_head(&p, &l, &r, K0, K1);
-	build_pte_writable(&p, &l, &r, K0, K1, label_nopage_tlbs);
+	build_pte_writable(&p, &r, K0, K1, label_nopage_tlbs);
 	if (m4kc_tlbp_war())
 		build_tlb_probe_entry(&p);
 	build_make_write(&p, &r, K0, K1);
 	build_r4000_tlbchange_handler_tail(&p, &l, &r, K0, K1);
 
+#ifdef CONFIG_HUGETLB_PAGE
+	/*
+	 * This is the entry point when
+	 * build_r4000_tlbchange_handler_head spots a huge page.
+	 */
+	uasm_l_tlb_huge_update(&l, p);
+	iPTE_LW(&p, K0, K1);
+	build_pte_writable(&p, &r, K0, K1, label_nopage_tlbs);
+	build_tlb_probe_entry(&p);
+	uasm_i_ori(&p, K0, K0,
+		   _PAGE_ACCESSED | _PAGE_MODIFIED | _PAGE_VALID | _PAGE_DIRTY);
+	build_huge_handler_tail(&p, &r, &l, K0, K1);
+#endif
+
 	uasm_l_nopage_tlbs(&l, p);
 	uasm_i_j(&p, (unsigned long)tlb_do_page_fault_1 & 0x0fffffff);
 	uasm_i_nop(&p);
@@ -1200,13 +1392,27 @@
 	memset(relocs, 0, sizeof(relocs));
 
 	build_r4000_tlbchange_handler_head(&p, &l, &r, K0, K1);
-	build_pte_modifiable(&p, &l, &r, K0, K1, label_nopage_tlbm);
+	build_pte_modifiable(&p, &r, K0, K1, label_nopage_tlbm);
 	if (m4kc_tlbp_war())
 		build_tlb_probe_entry(&p);
 	/* Present and writable bits set, set accessed and dirty bits. */
 	build_make_write(&p, &r, K0, K1);
 	build_r4000_tlbchange_handler_tail(&p, &l, &r, K0, K1);
 
+#ifdef CONFIG_HUGETLB_PAGE
+	/*
+	 * This is the entry point when
+	 * build_r4000_tlbchange_handler_head spots a huge page.
+	 */
+	uasm_l_tlb_huge_update(&l, p);
+	iPTE_LW(&p, K0, K1);
+	build_pte_modifiable(&p, &r, K0, K1, label_nopage_tlbm);
+	build_tlb_probe_entry(&p);
+	uasm_i_ori(&p, K0, K0,
+		   _PAGE_ACCESSED | _PAGE_MODIFIED | _PAGE_VALID | _PAGE_DIRTY);
+	build_huge_handler_tail(&p, &r, &l, K0, K1);
+#endif
+
 	uasm_l_nopage_tlbm(&l, p);
 	uasm_i_j(&p, (unsigned long)tlb_do_page_fault_1 & 0x0fffffff);
 	uasm_i_nop(&p);
diff --git a/arch/mips/power/Makefile b/arch/mips/power/Makefile
new file mode 100644
index 0000000..73d56b8
--- /dev/null
+++ b/arch/mips/power/Makefile
@@ -0,0 +1 @@
+obj-$(CONFIG_HIBERNATION) += cpu.o hibernate.o
diff --git a/arch/mips/power/cpu.c b/arch/mips/power/cpu.c
new file mode 100644
index 0000000..7995df4
--- /dev/null
+++ b/arch/mips/power/cpu.c
@@ -0,0 +1,43 @@
+/*
+ * Suspend support specific for mips.
+ *
+ * Licensed under the GPLv2
+ *
+ * Copyright (C) 2009 Lemote Inc. & Insititute of Computing Technology
+ * Author: Hu Hongbing <huhb@lemote.com>
+ *         Wu Zhangjin <wuzj@lemote.com>
+ */
+#include <asm/suspend.h>
+#include <asm/fpu.h>
+#include <asm/dsp.h>
+
+static u32 saved_status;
+struct pt_regs saved_regs;
+
+void save_processor_state(void)
+{
+	saved_status = read_c0_status();
+
+	if (is_fpu_owner())
+		save_fp(current);
+	if (cpu_has_dsp)
+		save_dsp(current);
+}
+
+void restore_processor_state(void)
+{
+	write_c0_status(saved_status);
+
+	if (is_fpu_owner())
+		restore_fp(current);
+	if (cpu_has_dsp)
+		restore_dsp(current);
+}
+
+int pfn_is_nosave(unsigned long pfn)
+{
+	unsigned long nosave_begin_pfn = PFN_DOWN(__pa(&__nosave_begin));
+	unsigned long nosave_end_pfn = PFN_UP(__pa(&__nosave_end));
+
+	return	(pfn >= nosave_begin_pfn) && (pfn < nosave_end_pfn);
+}
diff --git a/arch/mips/power/hibernate.S b/arch/mips/power/hibernate.S
new file mode 100644
index 0000000..486bd3f
--- /dev/null
+++ b/arch/mips/power/hibernate.S
@@ -0,0 +1,70 @@
+/*
+ * Hibernation support specific for mips - temporary page tables
+ *
+ * Licensed under the GPLv2
+ *
+ * Copyright (C) 2009 Lemote Inc. & Insititute of Computing Technology
+ * Author: Hu Hongbing <huhb@lemote.com>
+ *         Wu Zhangjin <wuzj@lemote.com>
+ */
+#include <asm/asm-offsets.h>
+#include <asm/regdef.h>
+#include <asm/asm.h>
+
+.text
+LEAF(swsusp_arch_suspend)
+	PTR_LA t0, saved_regs
+	PTR_S ra, PT_R31(t0)
+	PTR_S sp, PT_R29(t0)
+	PTR_S fp, PT_R30(t0)
+	PTR_S gp, PT_R28(t0)
+	PTR_S s0, PT_R16(t0)
+	PTR_S s1, PT_R17(t0)
+	PTR_S s2, PT_R18(t0)
+	PTR_S s3, PT_R19(t0)
+	PTR_S s4, PT_R20(t0)
+	PTR_S s5, PT_R21(t0)
+	PTR_S s6, PT_R22(t0)
+	PTR_S s7, PT_R23(t0)
+	j swsusp_save
+END(swsusp_arch_suspend)
+
+LEAF(swsusp_arch_resume)
+	PTR_L t0, restore_pblist
+0:
+	PTR_L t1, PBE_ADDRESS(t0)   /* source */
+	PTR_L t2, PBE_ORIG_ADDRESS(t0) /* destination */
+	PTR_ADDIU t3, t1, _PAGE_SIZE
+1:
+	REG_L t8, (t1)
+	REG_S t8, (t2)
+	PTR_ADDIU t1, t1, SZREG
+	PTR_ADDIU t2, t2, SZREG
+	bne t1, t3, 1b
+	PTR_L t0, PBE_NEXT(t0)
+	bnez t0, 0b
+	/* flush caches to make sure context is in memory */
+	PTR_L t0, __flush_cache_all
+	jalr t0
+	/* flush tlb entries */
+#ifdef CONFIG_SMP
+	jal	flush_tlb_all
+#else
+	jal	local_flush_tlb_all
+#endif
+	PTR_LA t0, saved_regs
+	PTR_L ra, PT_R31(t0)
+	PTR_L sp, PT_R29(t0)
+	PTR_L fp, PT_R30(t0)
+	PTR_L gp, PT_R28(t0)
+	PTR_L s0, PT_R16(t0)
+	PTR_L s1, PT_R17(t0)
+	PTR_L s2, PT_R18(t0)
+	PTR_L s3, PT_R19(t0)
+	PTR_L s4, PT_R20(t0)
+	PTR_L s5, PT_R21(t0)
+	PTR_L s6, PT_R22(t0)
+	PTR_L s7, PT_R23(t0)
+	PTR_LI v0, 0x0
+	jr ra
+END(swsusp_arch_resume)
diff --git a/arch/mips/rb532/irq.c b/arch/mips/rb532/irq.c
index 53eeb5e..f078820 100644
--- a/arch/mips/rb532/irq.c
+++ b/arch/mips/rb532/irq.c
@@ -151,7 +151,8 @@
 		mask |= intr_bit;
 		WRITE_MASK(addr, mask);
 
-		if (group == GPIO_MAPPED_IRQ_GROUP)
+		/* There is a maximum of 14 GPIO interrupts */
+		if (group == GPIO_MAPPED_IRQ_GROUP && irq_nr <= (GROUP4_IRQ_BASE + 13))
 			rb532_gpio_set_istat(0, irq_nr - GPIO_MAPPED_IRQ_BASE);
 
 		/*
@@ -174,7 +175,7 @@
 	int gpio = irq_nr - GPIO_MAPPED_IRQ_BASE;
 	int group = irq_to_group(irq_nr);
 
-	if (group != GPIO_MAPPED_IRQ_GROUP)
+	if (group != GPIO_MAPPED_IRQ_GROUP || irq_nr > (GROUP4_IRQ_BASE + 13))
 		return (type == IRQ_TYPE_LEVEL_HIGH) ? 0 : -EINVAL;
 
 	switch (type) {
diff --git a/arch/mips/sibyte/Kconfig b/arch/mips/sibyte/Kconfig
index 366b19d..3e639bd 100644
--- a/arch/mips/sibyte/Kconfig
+++ b/arch/mips/sibyte/Kconfig
@@ -75,6 +75,8 @@
 	select SWAP_IO_SPACE
 	select SYS_SUPPORTS_32BIT_KERNEL
 	select SYS_SUPPORTS_64BIT_KERNEL
+	select CFE
+	select SYS_HAS_EARLY_PRINTK
 
 choice
 	prompt "SiByte SOC Stepping"
@@ -128,13 +130,6 @@
 	bool
 	select SIBYTE_HAS_LDT if PCI
 
-config SIMULATION
-	bool "Running under simulation"
-	depends on SIBYTE_SB1xxx_SOC
-	help
-	  Build a kernel suitable for running under the GDB simulator.
-	  Primarily adjusts the kernel's notion of time.
-
 config SB1_CEX_ALWAYS_FATAL
 	bool "All cache exceptions considered fatal (no recovery attempted)"
 	depends on SIBYTE_SB1xxx_SOC
@@ -143,34 +138,14 @@
 	bool "Stall (rather than panic) on fatal cache error"
 	depends on SIBYTE_SB1xxx_SOC
 
-config SIBYTE_CFE
-	bool "Booting from CFE"
-	depends on SIBYTE_SB1xxx_SOC
-	select CFE
-	select SYS_HAS_EARLY_PRINTK
-	help
-	  Make use of the CFE API for enumerating available memory,
-	  controlling secondary CPUs, and possibly console output.
-
 config SIBYTE_CFE_CONSOLE
 	bool "Use firmware console"
-	depends on SIBYTE_CFE
+	depends on SIBYTE_SB1xxx_SOC
 	help
 	  Use the CFE API's console write routines during boot.  Other console
 	  options (VT console, sb1250 duart console, etc.) should not be
 	  configured.
 
-config SIBYTE_STANDALONE
-	bool
-	depends on SIBYTE_SB1xxx_SOC && !SIBYTE_CFE
-	select SYS_HAS_EARLY_PRINTK
-	default y
-
-config SIBYTE_STANDALONE_RAM_SIZE
-	int "Memory size (in megabytes)"
-	depends on SIBYTE_STANDALONE
-	default "32"
-
 config SIBYTE_BUS_WATCHER
 	bool "Support for Bus Watcher statistics"
 	depends on SIBYTE_SB1xxx_SOC
diff --git a/arch/mips/sibyte/cfe/Makefile b/arch/mips/sibyte/cfe/Makefile
deleted file mode 100644
index 02b32e1..0000000
--- a/arch/mips/sibyte/cfe/Makefile
+++ /dev/null
@@ -1,2 +0,0 @@
-lib-y					= setup.o
-lib-$(CONFIG_SIBYTE_CFE_CONSOLE)	+= console.o
diff --git a/arch/mips/sibyte/common/Makefile b/arch/mips/sibyte/common/Makefile
index 48a91b9..4f65983 100644
--- a/arch/mips/sibyte/common/Makefile
+++ b/arch/mips/sibyte/common/Makefile
@@ -1,5 +1,5 @@
-obj-y :=
-
+obj-y := cfe.o
+obj-$(CONFIG_SIBYTE_CFE_CONSOLE)	+= cfe_console.o
 obj-$(CONFIG_SIBYTE_TBPROF)		+= sb_tbprof.o
 
 EXTRA_CFLAGS += -Werror
diff --git a/arch/mips/sibyte/cfe/setup.c b/arch/mips/sibyte/common/cfe.c
similarity index 100%
rename from arch/mips/sibyte/cfe/setup.c
rename to arch/mips/sibyte/common/cfe.c
diff --git a/arch/mips/sibyte/cfe/console.c b/arch/mips/sibyte/common/cfe_console.c
similarity index 100%
rename from arch/mips/sibyte/cfe/console.c
rename to arch/mips/sibyte/common/cfe_console.c
diff --git a/arch/mips/sibyte/sb1250/Makefile b/arch/mips/sibyte/sb1250/Makefile
index 6977937..1896f4e 100644
--- a/arch/mips/sibyte/sb1250/Makefile
+++ b/arch/mips/sibyte/sb1250/Makefile
@@ -1,7 +1,6 @@
 obj-y := setup.o irq.o time.o
 
 obj-$(CONFIG_SMP)			+= smp.o
-obj-$(CONFIG_SIBYTE_STANDALONE)		+= prom.o
 obj-$(CONFIG_SIBYTE_BUS_WATCHER)	+= bus_watcher.o
 
 EXTRA_CFLAGS += -Werror
diff --git a/arch/mips/sibyte/sb1250/irq.c b/arch/mips/sibyte/sb1250/irq.c
index 409dec7..5e7f201 100644
--- a/arch/mips/sibyte/sb1250/irq.c
+++ b/arch/mips/sibyte/sb1250/irq.c
@@ -111,11 +111,6 @@
 
 	i = cpumask_first(mask);
 
-	if (cpumask_weight(mask) > 1) {
-		printk("attempted to set irq affinity for irq %d to multiple CPUs\n", irq);
-		return -1;
-	}
-
 	/* Convert logical CPU to physical CPU */
 	cpu = cpu_logical_map(i);
 
diff --git a/arch/mips/sibyte/sb1250/prom.c b/arch/mips/sibyte/sb1250/prom.c
deleted file mode 100644
index 65b1af6..0000000
--- a/arch/mips/sibyte/sb1250/prom.c
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2000, 2001 Broadcom Corporation
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
- */
-
-#include <linux/init.h>
-#include <linux/kernel.h>
-#include <linux/mm.h>
-#include <linux/blkdev.h>
-#include <linux/bootmem.h>
-#include <linux/smp.h>
-#include <linux/initrd.h>
-#include <linux/pm.h>
-
-#include <asm/bootinfo.h>
-#include <asm/reboot.h>
-
-#define MAX_RAM_SIZE ((CONFIG_SIBYTE_STANDALONE_RAM_SIZE * 1024 * 1024) - 1)
-
-static __init void prom_meminit(void)
-{
-#ifdef CONFIG_BLK_DEV_INITRD
-	unsigned long initrd_pstart;
-	unsigned long initrd_pend;
-
-	initrd_pstart = __pa(initrd_start);
-	initrd_pend = __pa(initrd_end);
-	if (initrd_start &&
-	    ((initrd_pstart > MAX_RAM_SIZE)
-	     || (initrd_pend > MAX_RAM_SIZE))) {
-		panic("initrd out of addressable memory");
-	}
-
-	add_memory_region(0, initrd_pstart,
-			  BOOT_MEM_RAM);
-	add_memory_region(initrd_pstart, initrd_pend - initrd_pstart,
-			  BOOT_MEM_RESERVED);
-	add_memory_region(initrd_pend,
-			  (CONFIG_SIBYTE_STANDALONE_RAM_SIZE * 1024 * 1024) - initrd_pend,
-			  BOOT_MEM_RAM);
-#else
-	add_memory_region(0, CONFIG_SIBYTE_STANDALONE_RAM_SIZE * 1024 * 1024,
-			  BOOT_MEM_RAM);
-#endif
-}
-
-void prom_cpu0_exit(void *unused)
-{
-        while (1) ;
-}
-
-static void prom_linux_exit(void)
-{
-#ifdef CONFIG_SMP
-	if (smp_processor_id()) {
-		smp_call_function(prom_cpu0_exit, NULL, 1);
-	}
-#endif
-	while(1);
-}
-
-/*
- * prom_init is called just after the cpu type is determined, from setup_arch()
- */
-void __init prom_init(void)
-{
-	_machine_restart   = (void (*)(char *))prom_linux_exit;
-	_machine_halt      = prom_linux_exit;
-	pm_power_off = prom_linux_exit;
-
-	strcpy(arcs_cmdline, "root=/dev/ram0 ");
-
-	prom_meminit();
-}
-
-void __init prom_free_prom_memory(void)
-{
-	/* Not sure what I'm supposed to do here.  Nothing, I think */
-}
-
-void prom_putchar(char c)
-{
-}
diff --git a/arch/mips/sibyte/swarm/setup.c b/arch/mips/sibyte/swarm/setup.c
index 080c966..672e45d 100644
--- a/arch/mips/sibyte/swarm/setup.c
+++ b/arch/mips/sibyte/swarm/setup.c
@@ -136,20 +136,6 @@
 	if (m41t81_probe())
 		swarm_rtc_type = RTC_M4LT81;
 
-	printk("This kernel optimized for "
-#ifdef CONFIG_SIMULATION
-	       "simulation"
-#else
-	       "board"
-#endif
-	       " runs "
-#ifdef CONFIG_SIBYTE_CFE
-	       "with"
-#else
-	       "without"
-#endif
-	       " CFE\n");
-
 #ifdef CONFIG_VT
 	screen_info = (struct screen_info) {
 		0, 0,           /* orig-x, orig-y */
diff --git a/arch/mips/txx9/Kconfig b/arch/mips/txx9/Kconfig
index 0db7cf3..852ae4b 100644
--- a/arch/mips/txx9/Kconfig
+++ b/arch/mips/txx9/Kconfig
@@ -69,6 +69,7 @@
 	select IRQ_TXX9
 	select PCI_TX4927
 	select GPIO_TXX9
+	select HAS_TXX9_ACLC
 
 config SOC_TX4938
 	bool
@@ -78,6 +79,7 @@
 	select IRQ_TXX9
 	select PCI_TX4927
 	select GPIO_TXX9
+	select HAS_TXX9_ACLC
 
 config SOC_TX4939
 	bool
@@ -85,6 +87,7 @@
 	select HAS_TXX9_SERIAL
 	select HW_HAS_PCI
 	select PCI_TX4927
+	select HAS_TXX9_ACLC
 
 config TXX9_7SEGLED
 	bool
diff --git a/arch/mips/txx9/generic/setup.c b/arch/mips/txx9/generic/setup.c
index 8a266c6..3b7d77d 100644
--- a/arch/mips/txx9/generic/setup.c
+++ b/arch/mips/txx9/generic/setup.c
@@ -24,6 +24,7 @@
 #include <linux/serial_core.h>
 #include <linux/mtd/physmap.h>
 #include <linux/leds.h>
+#include <linux/sysdev.h>
 #include <asm/bootinfo.h>
 #include <asm/time.h>
 #include <asm/reboot.h>
@@ -33,6 +34,7 @@
 #include <asm/txx9/pci.h>
 #include <asm/txx9tmr.h>
 #include <asm/txx9/ndfmc.h>
+#include <asm/txx9/dmac.h>
 #ifdef CONFIG_CPU_TX49XX
 #include <asm/txx9/tx4938.h>
 #endif
@@ -821,3 +823,176 @@
 {
 }
 #endif /* CONFIG_LEDS_GPIO */
+
+void __init txx9_dmac_init(int id, unsigned long baseaddr, int irq,
+			   const struct txx9dmac_platform_data *pdata)
+{
+#if defined(CONFIG_TXX9_DMAC) || defined(CONFIG_TXX9_DMAC_MODULE)
+	struct resource res[] = {
+		{
+			.start = baseaddr,
+			.end = baseaddr + 0x800 - 1,
+			.flags = IORESOURCE_MEM,
+#ifndef CONFIG_MACH_TX49XX
+		}, {
+			.start = irq,
+			.flags = IORESOURCE_IRQ,
+#endif
+		}
+	};
+#ifdef CONFIG_MACH_TX49XX
+	struct resource chan_res[] = {
+		{
+			.flags = IORESOURCE_IRQ,
+		}
+	};
+#endif
+	struct platform_device *pdev = platform_device_alloc("txx9dmac", id);
+	struct txx9dmac_chan_platform_data cpdata;
+	int i;
+
+	if (!pdev ||
+	    platform_device_add_resources(pdev, res, ARRAY_SIZE(res)) ||
+	    platform_device_add_data(pdev, pdata, sizeof(*pdata)) ||
+	    platform_device_add(pdev)) {
+		platform_device_put(pdev);
+		return;
+	}
+	memset(&cpdata, 0, sizeof(cpdata));
+	cpdata.dmac_dev = pdev;
+	for (i = 0; i < TXX9_DMA_MAX_NR_CHANNELS; i++) {
+#ifdef CONFIG_MACH_TX49XX
+		chan_res[0].start = irq + i;
+#endif
+		pdev = platform_device_alloc("txx9dmac-chan",
+					     id * TXX9_DMA_MAX_NR_CHANNELS + i);
+		if (!pdev ||
+#ifdef CONFIG_MACH_TX49XX
+		    platform_device_add_resources(pdev, chan_res,
+						  ARRAY_SIZE(chan_res)) ||
+#endif
+		    platform_device_add_data(pdev, &cpdata, sizeof(cpdata)) ||
+		    platform_device_add(pdev))
+			platform_device_put(pdev);
+	}
+#endif
+}
+
+void __init txx9_aclc_init(unsigned long baseaddr, int irq,
+			   unsigned int dmac_id,
+			   unsigned int dma_chan_out,
+			   unsigned int dma_chan_in)
+{
+#if defined(CONFIG_SND_SOC_TXX9ACLC) || \
+	defined(CONFIG_SND_SOC_TXX9ACLC_MODULE)
+	unsigned int dma_base = dmac_id * TXX9_DMA_MAX_NR_CHANNELS;
+	struct resource res[] = {
+		{
+			.start = baseaddr,
+			.end = baseaddr + 0x100 - 1,
+			.flags = IORESOURCE_MEM,
+		}, {
+			.start = irq,
+			.flags = IORESOURCE_IRQ,
+		}, {
+			.name = "txx9dmac-chan",
+			.start = dma_base + dma_chan_out,
+			.flags = IORESOURCE_DMA,
+		}, {
+			.name = "txx9dmac-chan",
+			.start = dma_base + dma_chan_in,
+			.flags = IORESOURCE_DMA,
+		}
+	};
+	struct platform_device *pdev =
+		platform_device_alloc("txx9aclc-ac97", -1);
+
+	if (!pdev ||
+	    platform_device_add_resources(pdev, res, ARRAY_SIZE(res)) ||
+	    platform_device_add(pdev))
+		platform_device_put(pdev);
+#endif
+}
+
+static struct sysdev_class txx9_sramc_sysdev_class;
+
+struct txx9_sramc_sysdev {
+	struct sys_device dev;
+	struct bin_attribute bindata_attr;
+	void __iomem *base;
+};
+
+static ssize_t txx9_sram_read(struct kobject *kobj,
+			      struct bin_attribute *bin_attr,
+			      char *buf, loff_t pos, size_t size)
+{
+	struct txx9_sramc_sysdev *dev = bin_attr->private;
+	size_t ramsize = bin_attr->size;
+
+	if (pos >= ramsize)
+		return 0;
+	if (pos + size > ramsize)
+		size = ramsize - pos;
+	memcpy_fromio(buf, dev->base + pos, size);
+	return size;
+}
+
+static ssize_t txx9_sram_write(struct kobject *kobj,
+			       struct bin_attribute *bin_attr,
+			       char *buf, loff_t pos, size_t size)
+{
+	struct txx9_sramc_sysdev *dev = bin_attr->private;
+	size_t ramsize = bin_attr->size;
+
+	if (pos >= ramsize)
+		return 0;
+	if (pos + size > ramsize)
+		size = ramsize - pos;
+	memcpy_toio(dev->base + pos, buf, size);
+	return size;
+}
+
+void __init txx9_sramc_init(struct resource *r)
+{
+	struct txx9_sramc_sysdev *dev;
+	size_t size;
+	int err;
+
+	if (!txx9_sramc_sysdev_class.name) {
+		txx9_sramc_sysdev_class.name = "txx9_sram";
+		err = sysdev_class_register(&txx9_sramc_sysdev_class);
+		if (err) {
+			txx9_sramc_sysdev_class.name = NULL;
+			return;
+		}
+	}
+	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
+	if (!dev)
+		return;
+	size = resource_size(r);
+	dev->base = ioremap(r->start, size);
+	if (!dev->base)
+		goto exit;
+	dev->dev.cls = &txx9_sramc_sysdev_class;
+	dev->bindata_attr.attr.name = "bindata";
+	dev->bindata_attr.attr.mode = S_IRUSR | S_IWUSR;
+	dev->bindata_attr.read = txx9_sram_read;
+	dev->bindata_attr.write = txx9_sram_write;
+	dev->bindata_attr.size = size;
+	dev->bindata_attr.private = dev;
+	err = sysdev_register(&dev->dev);
+	if (err)
+		goto exit;
+	err = sysfs_create_bin_file(&dev->dev.kobj, &dev->bindata_attr);
+	if (err) {
+		sysdev_unregister(&dev->dev);
+		goto exit;
+	}
+	return;
+exit:
+	if (dev) {
+		if (dev->base)
+			iounmap(dev->base);
+		kfree(dev);
+	}
+}
diff --git a/arch/mips/txx9/generic/setup_tx4927.c b/arch/mips/txx9/generic/setup_tx4927.c
index 1093549..3418b2a 100644
--- a/arch/mips/txx9/generic/setup_tx4927.c
+++ b/arch/mips/txx9/generic/setup_tx4927.c
@@ -22,6 +22,7 @@
 #include <asm/txx9tmr.h>
 #include <asm/txx9pio.h>
 #include <asm/txx9/generic.h>
+#include <asm/txx9/dmac.h>
 #include <asm/txx9/tx4927.h>
 
 static void __init tx4927_wdr_init(void)
@@ -253,6 +254,60 @@
 	txx9_physmap_flash_init(ch, start, size, &pdata);
 }
 
+void __init tx4927_dmac_init(int memcpy_chan)
+{
+	struct txx9dmac_platform_data plat_data = {
+		.memcpy_chan = memcpy_chan,
+		.have_64bit_regs = true,
+	};
+
+	txx9_dmac_init(0, TX4927_DMA_REG & 0xfffffffffULL,
+		       TXX9_IRQ_BASE + TX4927_IR_DMA(0), &plat_data);
+}
+
+void __init tx4927_aclc_init(unsigned int dma_chan_out,
+			     unsigned int dma_chan_in)
+{
+	u64 pcfg = __raw_readq(&tx4927_ccfgptr->pcfg);
+	__u64 dmasel_mask = 0, dmasel = 0;
+	unsigned long flags;
+
+	if (!(pcfg & TX4927_PCFG_SEL2))
+		return;
+	/* setup DMASEL (playback:ACLC ch0, capture:ACLC ch1) */
+	switch (dma_chan_out) {
+	case 0:
+		dmasel_mask |= TX4927_PCFG_DMASEL0_MASK;
+		dmasel |= TX4927_PCFG_DMASEL0_ACL0;
+		break;
+	case 2:
+		dmasel_mask |= TX4927_PCFG_DMASEL2_MASK;
+		dmasel |= TX4927_PCFG_DMASEL2_ACL0;
+		break;
+	default:
+		return;
+	}
+	switch (dma_chan_in) {
+	case 1:
+		dmasel_mask |= TX4927_PCFG_DMASEL1_MASK;
+		dmasel |= TX4927_PCFG_DMASEL1_ACL1;
+		break;
+	case 3:
+		dmasel_mask |= TX4927_PCFG_DMASEL3_MASK;
+		dmasel |= TX4927_PCFG_DMASEL3_ACL1;
+		break;
+	default:
+		return;
+	}
+	local_irq_save(flags);
+	txx9_clear64(&tx4927_ccfgptr->pcfg, dmasel_mask);
+	txx9_set64(&tx4927_ccfgptr->pcfg, dmasel);
+	local_irq_restore(flags);
+	txx9_aclc_init(TX4927_ACLC_REG & 0xfffffffffULL,
+		       TXX9_IRQ_BASE + TX4927_IR_ACLC,
+		       0, dma_chan_out, dma_chan_in);
+}
+
 static void __init tx4927_stop_unused_modules(void)
 {
 	__u64 pcfg, rst = 0, ckd = 0;
diff --git a/arch/mips/txx9/generic/setup_tx4938.c b/arch/mips/txx9/generic/setup_tx4938.c
index 3925219..eb20801 100644
--- a/arch/mips/txx9/generic/setup_tx4938.c
+++ b/arch/mips/txx9/generic/setup_tx4938.c
@@ -24,6 +24,7 @@
 #include <asm/txx9pio.h>
 #include <asm/txx9/generic.h>
 #include <asm/txx9/ndfmc.h>
+#include <asm/txx9/dmac.h>
 #include <asm/txx9/tx4938.h>
 
 static void __init tx4938_wdr_init(void)
@@ -239,11 +240,6 @@
 	for (i = 0; i < TX4938_NR_TMR; i++)
 		txx9_tmr_init(TX4938_TMR_REG(i) & 0xfffffffffULL);
 
-	/* DMA */
-	for (i = 0; i < 2; i++)
-		____raw_writeq(TX4938_DMA_MCR_MSTEN,
-			       (void __iomem *)(TX4938_DMA_REG(i) + 0x50));
-
 	/* PIO */
 	txx9_gpio_init(TX4938_PIO_REG & 0xfffffffffULL, 0, TX4938_NUM_PIO);
 	__raw_writel(0, &tx4938_pioptr->maskcpu);
@@ -403,6 +399,38 @@
 		txx9_ndfmc_init(baseaddr, &plat_data);
 }
 
+void __init tx4938_dmac_init(int memcpy_chan0, int memcpy_chan1)
+{
+	struct txx9dmac_platform_data plat_data = {
+		.have_64bit_regs = true,
+	};
+	int i;
+
+	for (i = 0; i < 2; i++) {
+		plat_data.memcpy_chan = i ? memcpy_chan1 : memcpy_chan0;
+		txx9_dmac_init(i, TX4938_DMA_REG(i) & 0xfffffffffULL,
+			       TXX9_IRQ_BASE + TX4938_IR_DMA(i, 0),
+			       &plat_data);
+	}
+}
+
+void __init tx4938_aclc_init(void)
+{
+	u64 pcfg = __raw_readq(&tx4938_ccfgptr->pcfg);
+
+	if ((pcfg & TX4938_PCFG_SEL2) &&
+	    !(pcfg & TX4938_PCFG_ETH0_SEL))
+		txx9_aclc_init(TX4938_ACLC_REG & 0xfffffffffULL,
+			       TXX9_IRQ_BASE + TX4938_IR_ACLC,
+			       1, 0, 1);
+}
+
+void __init tx4938_sramc_init(void)
+{
+	if (tx4938_sram_resource.start)
+		txx9_sramc_init(&tx4938_sram_resource);
+}
+
 static void __init tx4938_stop_unused_modules(void)
 {
 	__u64 pcfg, rst = 0, ckd = 0;
diff --git a/arch/mips/txx9/generic/setup_tx4939.c b/arch/mips/txx9/generic/setup_tx4939.c
index c2bf150..3dc19f4 100644
--- a/arch/mips/txx9/generic/setup_tx4939.c
+++ b/arch/mips/txx9/generic/setup_tx4939.c
@@ -28,6 +28,7 @@
 #include <asm/txx9tmr.h>
 #include <asm/txx9/generic.h>
 #include <asm/txx9/ndfmc.h>
+#include <asm/txx9/dmac.h>
 #include <asm/txx9/tx4939.h>
 
 static void __init tx4939_wdr_init(void)
@@ -259,11 +260,6 @@
 	for (i = 0; i < TX4939_NR_TMR; i++)
 		txx9_tmr_init(TX4939_TMR_REG(i) & 0xfffffffffULL);
 
-	/* DMA */
-	for (i = 0; i < 2; i++)
-		____raw_writeq(TX4938_DMA_MCR_MSTEN,
-			       (void __iomem *)(TX4939_DMA_REG(i) + 0x50));
-
 	/* set PCIC1 reset (required to prevent hangup on BIST) */
 	txx9_set64(&tx4939_ccfgptr->clkctr, TX4939_CLKCTR_PCI1RST);
 	pcfg = ____raw_readq(&tx4939_ccfgptr->pcfg);
@@ -474,6 +470,53 @@
 	txx9_ndfmc_init(TX4939_NDFMC_REG & 0xfffffffffULL, &plat_data);
 }
 
+void __init tx4939_dmac_init(int memcpy_chan0, int memcpy_chan1)
+{
+	struct txx9dmac_platform_data plat_data = {
+		.have_64bit_regs = true,
+	};
+	int i;
+
+	for (i = 0; i < 2; i++) {
+		plat_data.memcpy_chan = i ? memcpy_chan1 : memcpy_chan0;
+		txx9_dmac_init(i, TX4939_DMA_REG(i) & 0xfffffffffULL,
+			       TXX9_IRQ_BASE + TX4939_IR_DMA(i, 0),
+			       &plat_data);
+	}
+}
+
+void __init tx4939_aclc_init(void)
+{
+	u64 pcfg = __raw_readq(&tx4939_ccfgptr->pcfg);
+
+	if ((pcfg & TX4939_PCFG_I2SMODE_MASK) == TX4939_PCFG_I2SMODE_ACLC)
+		txx9_aclc_init(TX4939_ACLC_REG & 0xfffffffffULL,
+			       TXX9_IRQ_BASE + TX4939_IR_ACLC, 1, 0, 1);
+}
+
+void __init tx4939_sramc_init(void)
+{
+	if (tx4939_sram_resource.start)
+		txx9_sramc_init(&tx4939_sram_resource);
+}
+
+void __init tx4939_rng_init(void)
+{
+	static struct resource res = {
+		.start = TX4939_RNG_REG & 0xfffffffffULL,
+		.end = (TX4939_RNG_REG & 0xfffffffffULL) + 0x30 - 1,
+		.flags = IORESOURCE_MEM,
+	};
+	static struct platform_device pdev = {
+		.name = "tx4939-rng",
+		.id = -1,
+		.num_resources = 1,
+		.resource = &res,
+	};
+
+	platform_device_register(&pdev);
+}
+
 static void __init tx4939_stop_unused_modules(void)
 {
 	__u64 pcfg, rst = 0, ckd = 0;
diff --git a/arch/mips/txx9/rbtx4927/setup.c b/arch/mips/txx9/rbtx4927/setup.c
index 01129a9..ee468ea 100644
--- a/arch/mips/txx9/rbtx4927/setup.c
+++ b/arch/mips/txx9/rbtx4927/setup.c
@@ -337,6 +337,14 @@
 	rbtx4927_ne_init();
 	tx4927_wdt_init();
 	rbtx4927_mtd_init();
+	if (TX4927_REV_PCODE() == 0x4927) {
+		tx4927_dmac_init(2);
+		tx4927_aclc_init(0, 1);
+	} else {
+		tx4938_dmac_init(0, 2);
+		tx4938_aclc_init();
+	}
+	platform_device_register_simple("txx9aclc-generic", -1, NULL, 0);
 	txx9_iocled_init(RBTX4927_LED_ADDR - IO_BASE, -1, 3, 1, "green", NULL);
 	rbtx4927_gpioled_init();
 }
diff --git a/arch/mips/txx9/rbtx4938/setup.c b/arch/mips/txx9/rbtx4938/setup.c
index 65d13df..d66509b 100644
--- a/arch/mips/txx9/rbtx4938/setup.c
+++ b/arch/mips/txx9/rbtx4938/setup.c
@@ -355,6 +355,10 @@
 	/* TC58DVM82A1FT: tDH=10ns, tWP=tRP=tREADID=35ns */
 	tx4938_ndfmc_init(10, 35);
 	tx4938_ata_init(RBTX4938_IRQ_IOC_ATA, 0, 1);
+	tx4938_dmac_init(0, 2);
+	tx4938_aclc_init();
+	platform_device_register_simple("txx9aclc-generic", -1, NULL, 0);
+	tx4938_sramc_init();
 	txx9_iocled_init(RBTX4938_LED_ADDR - IO_BASE, -1, 8, 1, "green", NULL);
 }
 
diff --git a/arch/mips/txx9/rbtx4939/setup.c b/arch/mips/txx9/rbtx4939/setup.c
index 4199c6f..c033ffe 100644
--- a/arch/mips/txx9/rbtx4939/setup.c
+++ b/arch/mips/txx9/rbtx4939/setup.c
@@ -498,6 +498,11 @@
 	tx4939_wdt_init();
 	tx4939_ata_init();
 	tx4939_rtc_init();
+	tx4939_dmac_init(0, 2);
+	tx4939_aclc_init();
+	platform_device_register_simple("txx9aclc-generic", -1, NULL, 0);
+	tx4939_sramc_init();
+	tx4939_rng_init();
 }
 
 static void __init rbtx4939_setup(void)
diff --git a/arch/mn10300/include/asm/elf.h b/arch/mn10300/include/asm/elf.h
index 4910546..75a70aa 100644
--- a/arch/mn10300/include/asm/elf.h
+++ b/arch/mn10300/include/asm/elf.h
@@ -28,6 +28,8 @@
 #define R_MN10300_PCREL8	6	/* PC-relative 8-bit signed.  */
 #define R_MN10300_24		9	/* Direct 24 bit.  */
 #define R_MN10300_RELATIVE	23	/* Adjust by program base.  */
+#define R_MN10300_SYM_DIFF	33	/* Adjustment when relaxing. */
+#define R_MN10300_ALIGN 	34	/* Alignment requirement. */
 
 /*
  * ELF register definitions..
diff --git a/arch/mn10300/include/asm/pci.h b/arch/mn10300/include/asm/pci.h
index 0517b45..e58b9a4 100644
--- a/arch/mn10300/include/asm/pci.h
+++ b/arch/mn10300/include/asm/pci.h
@@ -106,19 +106,6 @@
 				    struct resource *res,
 				    struct pci_bus_region *region);
 
-static inline struct resource *
-pcibios_select_root(struct pci_dev *pdev, struct resource *res)
-{
-	struct resource *root = NULL;
-
-	if (res->flags & IORESOURCE_IO)
-		root = &ioport_resource;
-	if (res->flags & IORESOURCE_MEM)
-		root = &iomem_resource;
-
-	return root;
-}
-
 #define pcibios_scan_all_fns(a, b)	0
 
 static inline int pci_get_legacy_ide_irq(struct pci_dev *dev, int channel)
diff --git a/arch/mn10300/kernel/module.c b/arch/mn10300/kernel/module.c
index 4fa0e36..6aea7fd 100644
--- a/arch/mn10300/kernel/module.c
+++ b/arch/mn10300/kernel/module.c
@@ -1,6 +1,6 @@
 /* MN10300 Kernel module helper routines
  *
- * Copyright (C) 2007, 2008 Red Hat, Inc. All Rights Reserved.
+ * Copyright (C) 2007, 2008, 2009 Red Hat, Inc. All Rights Reserved.
  * Written by Mark Salter (msalter@redhat.com)
  * - Derived from arch/i386/kernel/module.c
  *
@@ -103,10 +103,10 @@
 		       unsigned int relsec,
 		       struct module *me)
 {
-	unsigned int i;
+	unsigned int i, sym_diff_seen = 0;
 	Elf32_Rela *rel = (void *)sechdrs[relsec].sh_addr;
 	Elf32_Sym *sym;
-	Elf32_Addr relocation;
+	Elf32_Addr relocation, sym_diff_val = 0;
 	uint8_t *location;
 	uint32_t value;
 
@@ -126,6 +126,22 @@
 		/* this is the adjustment to be made */
 		relocation = sym->st_value + rel[i].r_addend;
 
+		if (sym_diff_seen) {
+			switch (ELF32_R_TYPE(rel[i].r_info)) {
+			case R_MN10300_32:
+			case R_MN10300_24:
+			case R_MN10300_16:
+			case R_MN10300_8:
+				relocation -= sym_diff_val;
+				sym_diff_seen = 0;
+				break;
+			default:
+				printk(KERN_ERR "module %s: Unexpected SYM_DIFF relocation: %u\n",
+				       me->name, ELF32_R_TYPE(rel[i].r_info));
+				return -ENOEXEC;
+			}
+		}
+
 		switch (ELF32_R_TYPE(rel[i].r_info)) {
 			/* for the first four relocation types, we simply
 			 * store the adjustment at the location given */
@@ -157,12 +173,29 @@
 			*location = relocation - (uint32_t) location;
 			break;
 
+		case R_MN10300_SYM_DIFF:
+			/* This is used to adjust the next reloc as required
+			 * by relaxation. */
+			sym_diff_seen = 1;
+			sym_diff_val = sym->st_value;
+			break;
+
+		case R_MN10300_ALIGN:
+			/* Just ignore the ALIGN relocs.
+			 * Only interesting if kernel performed relaxation. */
+			continue;
+
 		default:
 			printk(KERN_ERR "module %s: Unknown relocation: %u\n",
 			       me->name, ELF32_R_TYPE(rel[i].r_info));
 			return -ENOEXEC;
 		}
 	}
+	if (sym_diff_seen) {
+		printk(KERN_ERR "module %s: Nothing follows SYM_DIFF relocation: %u\n",
+				       me->name, ELF32_R_TYPE(rel[i].r_info));
+		return -ENOEXEC;
+	}
 	return 0;
 }
 
diff --git a/arch/mn10300/kernel/process.c b/arch/mn10300/kernel/process.c
index 234cf34..892cce8 100644
--- a/arch/mn10300/kernel/process.c
+++ b/arch/mn10300/kernel/process.c
@@ -281,9 +281,6 @@
 	error = PTR_ERR(filename);
 	if (!IS_ERR(filename)) {
 		error = do_execve(filename, argv, envp, __frame);
-		if (error == 0)
-			current->ptrace &= ~PT_DTRACE;
-
 		putname(filename);
 	}
 
diff --git a/arch/parisc/hpux/fs.c b/arch/parisc/hpux/fs.c
index 5cbe9f9..5407536 100644
--- a/arch/parisc/hpux/fs.c
+++ b/arch/parisc/hpux/fs.c
@@ -44,11 +44,6 @@
 	error = do_execve(filename, (char __user * __user *) regs->gr[25],
 		(char __user * __user *) regs->gr[24], regs);
 
-	if (error == 0) {
-		task_lock(current);
-		current->ptrace &= ~PT_DTRACE;
-		task_unlock(current);
-	}
 	putname(filename);
 
 out:
diff --git a/arch/parisc/include/asm/pci.h b/arch/parisc/include/asm/pci.h
index 4ba868f..7d842d6 100644
--- a/arch/parisc/include/asm/pci.h
+++ b/arch/parisc/include/asm/pci.h
@@ -268,19 +268,6 @@
 pcibios_bus_to_resource(struct pci_dev *dev, struct resource *res,
 			struct pci_bus_region *region);
 
-static inline struct resource *
-pcibios_select_root(struct pci_dev *pdev, struct resource *res)
-{
-	struct resource *root = NULL;
-
-	if (res->flags & IORESOURCE_IO)
-		root = &ioport_resource;
-	if (res->flags & IORESOURCE_MEM)
-		root = &iomem_resource;
-
-	return root;
-}
-
 static inline void pcibios_penalize_isa_irq(int irq, int active)
 {
 	/* We don't need to penalize isa irq's */
diff --git a/arch/parisc/kernel/process.c b/arch/parisc/kernel/process.c
index 6f69101..61c0707 100644
--- a/arch/parisc/kernel/process.c
+++ b/arch/parisc/kernel/process.c
@@ -349,11 +349,6 @@
 		goto out;
 	error = do_execve(filename, (char __user * __user *) regs->gr[25],
 		(char __user * __user *) regs->gr[24], regs);
-	if (error == 0) {
-		task_lock(current);
-		current->ptrace &= ~PT_DTRACE;
-		task_unlock(current);
-	}
 	putname(filename);
 out:
 
diff --git a/arch/parisc/kernel/sys_parisc32.c b/arch/parisc/kernel/sys_parisc32.c
index 0838155..1adb40c 100644
--- a/arch/parisc/kernel/sys_parisc32.c
+++ b/arch/parisc/kernel/sys_parisc32.c
@@ -77,11 +77,6 @@
 		goto out;
 	error = compat_do_execve(filename, compat_ptr(regs->gr[25]),
 				 compat_ptr(regs->gr[24]), regs);
-	if (error == 0) {
-		task_lock(current);
-		current->ptrace &= ~PT_DTRACE;
-		task_unlock(current);
-	}
 	putname(filename);
 out:
 
diff --git a/arch/powerpc/Kconfig.debug b/arch/powerpc/Kconfig.debug
index d79a902..3b10051 100644
--- a/arch/powerpc/Kconfig.debug
+++ b/arch/powerpc/Kconfig.debug
@@ -2,6 +2,23 @@
 
 source "lib/Kconfig.debug"
 
+config PPC_DISABLE_WERROR
+	bool "Don't build arch/powerpc code with -Werror"
+	default n
+	help
+	  This option tells the compiler NOT to build the code under
+	  arch/powerpc with the -Werror flag (which means warnings
+	  are treated as errors).
+
+	  Only enable this if you are hitting a build failure in the
+	  arch/powerpc code caused by a warning, and you don't feel
+	  inclined to fix it.
+
+config PPC_WERROR
+	bool
+	depends on !PPC_DISABLE_WERROR
+	default y
+
 config PRINT_STACK_DEPTH
 	int "Stack depth to print" if DEBUG_KERNEL
 	default 64
diff --git a/arch/powerpc/boot/cuboot-85xx.c b/arch/powerpc/boot/cuboot-85xx.c
index 6776a1a..277ba4a 100644
--- a/arch/powerpc/boot/cuboot-85xx.c
+++ b/arch/powerpc/boot/cuboot-85xx.c
@@ -15,6 +15,7 @@
 #include "cuboot.h"
 
 #define TARGET_85xx
+#define TARGET_HAS_ETH3
 #include "ppcboot.h"
 
 static bd_t bd;
@@ -27,6 +28,7 @@
 	dt_fixup_mac_address_by_alias("ethernet0", bd.bi_enetaddr);
 	dt_fixup_mac_address_by_alias("ethernet1", bd.bi_enet1addr);
 	dt_fixup_mac_address_by_alias("ethernet2", bd.bi_enet2addr);
+	dt_fixup_mac_address_by_alias("ethernet3", bd.bi_enet3addr);
 	dt_fixup_cpu_clocks(bd.bi_intfreq, bd.bi_busfreq / 8, bd.bi_busfreq);
 
 	/* Unfortunately, the specific model number is encoded in the
diff --git a/arch/powerpc/boot/dts/asp834x-redboot.dts b/arch/powerpc/boot/dts/asp834x-redboot.dts
index 7da84fd..261d10c 100644
--- a/arch/powerpc/boot/dts/asp834x-redboot.dts
+++ b/arch/powerpc/boot/dts/asp834x-redboot.dts
@@ -167,7 +167,7 @@
 			interrupt-parent = <&ipic>;
 			interrupts = <39 0x8>;
 			phy_type = "ulpi";
-			port1;
+			port0;
 		};
 		/* phy type (ULPI, UTMI, UTMI_WIDE, SERIAL) */
 		usb@23000 {
diff --git a/arch/powerpc/boot/dts/gef_sbc610.dts b/arch/powerpc/boot/dts/gef_sbc610.dts
index 217f8aa..35a6318 100644
--- a/arch/powerpc/boot/dts/gef_sbc610.dts
+++ b/arch/powerpc/boot/dts/gef_sbc610.dts
@@ -152,6 +152,16 @@
 			interrupt-parent = <&mpic>;
 			dfsrr;
 
+			hwmon@48 {
+				compatible = "national,lm92";
+				reg = <0x48>;
+			};
+
+			hwmon@4c {
+				compatible = "adi,adt7461";
+				reg = <0x4c>;
+			};
+
 			rtc@51 {
 				compatible = "epson,rx8581";
 				reg = <0x00000051>;
diff --git a/arch/powerpc/boot/dts/kmeter1.dts b/arch/powerpc/boot/dts/kmeter1.dts
new file mode 100644
index 0000000..167044f
--- /dev/null
+++ b/arch/powerpc/boot/dts/kmeter1.dts
@@ -0,0 +1,520 @@
+/*
+ * Keymile KMETER1 Device Tree Source
+ *
+ * 2008 DENX Software Engineering GmbH
+ *
+ * This program is free software; you can redistribute  it and/or modify it
+ * under  the terms of  the GNU General  Public License as published by the
+ * Free Software Foundation;  either version 2 of the  License, or (at your
+ * option) any later version.
+ */
+
+/dts-v1/;
+
+/ {
+	model = "KMETER1";
+	compatible = "keymile,KMETER1";
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	aliases {
+		ethernet0 = &enet_piggy2;
+		ethernet1 = &enet_estar1;
+		ethernet2 = &enet_estar2;
+		ethernet3 = &enet_eth1;
+		ethernet4 = &enet_eth2;
+		ethernet5 = &enet_eth3;
+		ethernet6 = &enet_eth4;
+		serial0 = &serial0;
+	};
+
+	cpus {
+		#address-cells = <1>;
+		#size-cells = <0>;
+
+		PowerPC,8360@0 {
+			device_type = "cpu";
+			reg = <0x0>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <32768>;		// L1, 32K
+			i-cache-size = <32768>;		// L1, 32K
+			timebase-frequency = <0>;	/* Filled in by U-Boot */
+			bus-frequency = <0>;	/* Filled in by U-Boot */
+			clock-frequency = <0>;	/* Filled in by U-Boot */
+		};
+	};
+
+	memory {
+		device_type = "memory";
+		reg = <0 0>;	/* Filled in by U-Boot */
+	};
+
+	soc8360@e0000000 {
+		#address-cells = <1>;
+		#size-cells = <1>;
+		device_type = "soc";
+		compatible = "fsl,mpc8360-immr", "simple-bus";
+		ranges = <0x0 0xe0000000 0x00200000>;
+		reg = <0xe0000000 0x00000200>;
+		bus-frequency = <0>;	/* Filled in by U-Boot */
+
+		i2c@3000 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <0>;
+			compatible = "fsl-i2c";
+			reg = <0x3000 0x100>;
+			interrupts = <14 0x8>;
+			interrupt-parent = <&ipic>;
+			dfsrr;
+		};
+
+		serial0: serial@4500 {
+			cell-index = <0>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4500 0x100>;
+			clock-frequency = <264000000>;
+			interrupts = <9 0x8>;
+			interrupt-parent = <&ipic>;
+		};
+
+		dma@82a8 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,mpc8360-dma", "fsl,elo-dma";
+			reg = <0x82a8 4>;
+			ranges = <0 0x8100 0x1a8>;
+			interrupt-parent = <&ipic>;
+			interrupts = <71 8>;
+			cell-index = <0>;
+			dma-channel@0 {
+				compatible = "fsl,mpc8360-dma-channel", "fsl,elo-dma-channel";
+				reg = <0 0x80>;
+				interrupt-parent = <&ipic>;
+				interrupts = <71 8>;
+			};
+			dma-channel@80 {
+				compatible = "fsl,mpc8360-dma-channel", "fsl,elo-dma-channel";
+				reg = <0x80 0x80>;
+				interrupt-parent = <&ipic>;
+				interrupts = <71 8>;
+			};
+			dma-channel@100 {
+				compatible = "fsl,mpc8360-dma-channel", "fsl,elo-dma-channel";
+				reg = <0x100 0x80>;
+				interrupt-parent = <&ipic>;
+				interrupts = <71 8>;
+			};
+			dma-channel@180 {
+				compatible = "fsl,mpc8360-dma-channel", "fsl,elo-dma-channel";
+				reg = <0x180 0x28>;
+				interrupt-parent = <&ipic>;
+				interrupts = <71 8>;
+			};
+		};
+
+		ipic: pic@700 {
+			#address-cells = <0>;
+			#interrupt-cells = <2>;
+			compatible = "fsl,pq2pro-pic", "fsl,ipic";
+			interrupt-controller;
+			reg = <0x700 0x100>;
+		};
+
+		par_io@1400 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			reg = <0x1400 0x100>;
+			compatible = "fsl,mpc8360-par_io";
+			num-ports = <7>;
+
+			pio_ucc1: ucc_pin@0 {
+				reg = <0>;
+
+				pio-map = <
+					/* port pin dir open_drain assignment has_irq */
+					0   1  3  0  2  0	/* MDIO   */
+					0   2  1  0  1  0	/* MDC    */
+
+					0   3  1  0  1  0	/* TxD0   */
+					0   4  1  0  1  0	/* TxD1   */
+					0   5  1  0  1  0	/* TxD2   */
+					0   6  1  0  1  0	/* TxD3   */
+					0   9  2  0  1  0	/* RxD0   */
+					0  10  2  0  1  0	/* RxD1   */
+					0  11  2  0  1  0	/* RxD2   */
+					0  12  2  0  1  0	/* RxD3   */
+					0   7  1  0  1  0	/* TX_EN  */
+					0   8  1  0  1  0	/* TX_ER  */
+					0  15  2  0  1  0	/* RX_DV  */
+					0  16  2  0  1  0	/* RX_ER  */
+					0   0  2  0  1  0	/* RX_CLK */
+					2   9  1  0  3  0	/* GTX_CLK - CLK10 */
+					2   8  2  0  1  0	/* GTX125  - CLK9  */
+				>;
+			};
+
+			pio_ucc2: ucc_pin@1 {
+				reg = <1>;
+
+				pio-map = <
+					/* port pin dir open_drain assignment has_irq */
+					0   1  3  0  2  0	/* MDIO   */
+					0   2  1  0  1  0	/* MDC    */
+
+					0  17  1  0  1  0	/* TxD0   */
+					0  18  1  0  1  0	/* TxD1   */
+					0  19  1  0  1  0	/* TxD2   */
+					0  20  1  0  1  0	/* TxD3   */
+					0  23  2  0  1  0	/* RxD0   */
+					0  24  2  0  1  0	/* RxD1   */
+					0  25  2  0  1  0	/* RxD2   */
+					0  26  2  0  1  0	/* RxD3   */
+					0  21  1  0  1  0	/* TX_EN  */
+					0  22  1  0  1  0	/* TX_ER  */
+					0  29  2  0  1  0	/* RX_DV  */
+					0  30  2  0  1  0	/* RX_ER  */
+					0  31  2  0  1  0	/* RX_CLK */
+					2  2   1  0  2  0	/* GTX_CLK - CLK3  */
+					2  3   2  0  1  0	/* GTX125  - CLK4  */
+				>;
+			};
+
+			pio_ucc4: ucc_pin@3 {
+				reg = <3>;
+
+				pio-map = <
+					/* port pin dir open_drain assignment has_irq */
+					0   1  3  0  2  0	/* MDIO */
+					0   2  1  0  1  0	/* MDC  */
+
+					1  14  1  0  1  0	/* TxD0   (PB14, out, f1) */
+					1  15  1  0  1  0	/* TxD1   (PB15, out, f1) */
+					1  20  2  0  1  0	/* RxD0   (PB20, in,  f1) */
+					1  21  2  0  1  0	/* RxD1   (PB21, in,  f1) */
+					1  18  1  0  1  0	/* TX_EN  (PB18, out, f1) */
+					1  26  2  0  1  0	/* RX_DV  (PB26, in,  f1) */
+					1  27  2  0  1  0	/* RX_ER  (PB27, in,  f1) */
+
+					2  16  2  0  1  0	/* UCC4_RMII_CLK (CLK17) */
+				>;
+			};
+
+			pio_ucc5: ucc_pin@4 {
+				reg = <4>;
+
+				pio-map = <
+					/* port pin dir open_drain assignment has_irq */
+					0   1  3  0  2  0	/* MDIO */
+					0   2  1  0  1  0	/* MDC  */
+
+					3   0  1  0  1  0	/* TxD0  (PD0,  out, f1) */
+					3   1  1  0  1  0	/* TxD1  (PD1,  out, f1) */
+					3   6  2  0  1  0	/* RxD0  (PD6,   in, f1) */
+					3   7  2  0  1  0	/* RxD1  (PD7,   in, f1) */
+					3   4  1  0  1  0	/* TX_EN (PD4,  out, f1) */
+					3  12  2  0  1  0	/* RX_DV (PD12,  in, f1) */
+					3  13  2  0  1  0	/* RX_ER (PD13,  in, f1) */
+				>;
+			};
+
+			pio_ucc6: ucc_pin@5 {
+				reg = <5>;
+
+				pio-map = <
+					/* port pin dir open_drain assignment has_irq */
+					0   1  3  0  2  0	/* MDIO */
+					0   2  1  0  1  0	/* MDC  */
+
+					3  14  1  0  1  0	/* TxD0   (PD14, out, f1) */
+					3  15  1  0  1  0	/* TxD1   (PD15, out, f1) */
+					3  20  2  0  1  0	/* RxD0   (PD20, in,  f1) */
+					3  21  2  0  1  0	/* RxD1   (PD21, in,  f1) */
+					3  18  1  0  1  0	/* TX_EN  (PD18, out, f1) */
+					3  26  2  0  1  0	/* RX_DV  (PD26, in,  f1) */
+					3  27  2  0  1  0	/* RX_ER  (PD27, in,  f1) */
+				>;
+			};
+
+			pio_ucc7: ucc_pin@6 {
+				reg = <6>;
+
+				pio-map = <
+					/* port pin dir open_drain assignment has_irq */
+					0   1  3  0  2  0	/* MDIO */
+					0   2  1  0  1  0	/* MDC  */
+
+					4   0  1  0  1  0	/* TxD0   (PE0,  out, f1) */
+					4   1  1  0  1  0	/* TxD1   (PE1,  out, f1) */
+					4   6  2  0  1  0	/* RxD0   (PE6,   in, f1) */
+					4   7  2  0  1  0	/* RxD1   (PE7,   in, f1) */
+					4   4  1  0  1  0	/* TX_EN  (PE4,  out, f1) */
+					4  12  2  0  1  0	/* RX_DV  (PE12,  in, f1) */
+					4  13  2  0  1  0	/* RX_ER  (PE13,  in, f1) */
+				>;
+			};
+
+			pio_ucc8: ucc_pin@7 {
+				reg = <7>;
+
+				pio-map = <
+					/* port pin dir open_drain assignment has_irq */
+					0   1  3  0  2  0	/* MDIO */
+					0   2  1  0  1  0	/* MDC  */
+
+					4  14  1  0  2  0	/* TxD0   (PE14, out, f2) */
+					4  15  1  0  1  0	/* TxD1   (PE15, out, f1) */
+					4  20  2  0  1  0	/* RxD0   (PE20, in,  f1) */
+					4  21  2  0  1  0	/* RxD1   (PE21, in,  f1) */
+					4  18  1  0  1  0	/* TX_EN  (PE18, out, f1) */
+					4  26  2  0  1  0	/* RX_DV  (PE26, in,  f1) */
+					4  27  2  0  1  0	/* RX_ER  (PE27, in,  f1) */
+
+					2  15  2  0  1  0	/* UCCx_RMII_CLK (CLK16) */
+				>;
+			};
+
+		};
+
+		qe@100000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,qe";
+			ranges = <0x0 0x100000 0x100000>;
+			reg = <0x100000 0x480>;
+			clock-frequency = <0>;	/* Filled in by U-Boot */
+			brg-frequency = <0>;	/* Filled in by U-Boot */
+			bus-frequency = <0>;	/* Filled in by U-Boot */
+
+			muram@10000 {
+				#address-cells = <1>;
+				#size-cells = <1>;
+				compatible = "fsl,qe-muram", "fsl,cpm-muram";
+				ranges = <0x0 0x00010000 0x0000c000>;
+
+				data-only@0 {
+					compatible = "fsl,qe-muram-data",
+						     "fsl,cpm-muram-data";
+					reg = <0x0 0xc000>;
+				};
+			};
+
+			/* ESTAR-1 (UCC1, MDIO 0x10, RGMII) */
+			enet_estar1: ucc@2000 {
+				device_type = "network";
+				compatible = "ucc_geth";
+				cell-index = <1>;
+				reg = <0x2000 0x200>;
+				interrupts = <32>;
+				interrupt-parent = <&qeic>;
+				local-mac-address = [ 00 00 00 00 00 00 ];
+				rx-clock-name = "none";
+				tx-clock-name = "clk9";
+				phy-handle = <&phy_estar1>;
+				phy-connection-type = "rgmii-id";
+				pio-handle = <&pio_ucc1>;
+			};
+
+			/* ESTAR-2 (UCC2, MDIO 0x11, RGMII) */
+			enet_estar2: ucc@3000 {
+				device_type = "network";
+				compatible = "ucc_geth";
+				cell-index = <2>;
+				reg = <0x3000 0x200>;
+				interrupts = <33>;
+				interrupt-parent = <&qeic>;
+				local-mac-address = [ 00 00 00 00 00 00 ];
+				rx-clock-name = "none";
+				tx-clock-name = "clk4";
+				phy-handle = <&phy_estar2>;
+				phy-connection-type = "rgmii-id";
+				pio-handle = <&pio_ucc2>;
+			};
+
+			/* Piggy2 (UCC4, MDIO 0x00, RMII) */
+			enet_piggy2: ucc@3200 {
+				device_type = "network";
+				compatible = "ucc_geth";
+				cell-index = <4>;
+				reg = <0x3200 0x200>;
+				interrupts = <35>;
+				interrupt-parent = <&qeic>;
+				local-mac-address = [ 00 00 00 00 00 00 ];
+				rx-clock-name = "none";
+				tx-clock-name = "clk17";
+				phy-handle = <&phy_piggy2>;
+				phy-connection-type = "rmii";
+				pio-handle = <&pio_ucc4>;
+			};
+
+			/* Eth-1 (UCC5, MDIO 0x08, RMII) */
+			enet_eth1: ucc@2400 {
+				device_type = "network";
+				compatible = "ucc_geth";
+				cell-index = <5>;
+				reg = <0x2400 0x200>;
+				interrupts = <40>;
+				interrupt-parent = <&qeic>;
+				local-mac-address = [ 00 00 00 00 00 00 ];
+				rx-clock-name = "none";
+				tx-clock-name = "clk16";
+				phy-handle = <&phy_eth1>;
+				phy-connection-type = "rmii";
+				pio-handle = <&pio_ucc5>;
+			};
+
+			/* Eth-2 (UCC6, MDIO 0x09, RMII) */
+			enet_eth2: ucc@3400 {
+				device_type = "network";
+				compatible = "ucc_geth";
+				cell-index = <6>;
+				reg = <0x3400 0x200>;
+				interrupts = <41>;
+				interrupt-parent = <&qeic>;
+				local-mac-address = [ 00 00 00 00 00 00 ];
+				rx-clock-name = "none";
+				tx-clock-name = "clk16";
+				phy-handle = <&phy_eth2>;
+				phy-connection-type = "rmii";
+				pio-handle = <&pio_ucc6>;
+			};
+
+			/* Eth-3 (UCC7, MDIO 0x0a, RMII) */
+			enet_eth3: ucc@2600 {
+				device_type = "network";
+				compatible = "ucc_geth";
+				cell-index = <7>;
+				reg = <0x2600 0x200>;
+				interrupts = <42>;
+				interrupt-parent = <&qeic>;
+				local-mac-address = [ 00 00 00 00 00 00 ];
+				rx-clock-name = "none";
+				tx-clock-name = "clk16";
+				phy-handle = <&phy_eth3>;
+				phy-connection-type = "rmii";
+				pio-handle = <&pio_ucc7>;
+			};
+
+			/* Eth-4 (UCC8, MDIO 0x0b, RMII) */
+			enet_eth4: ucc@3600 {
+				device_type = "network";
+				compatible = "ucc_geth";
+				cell-index = <8>;
+				reg = <0x3600 0x200>;
+				interrupts = <43>;
+				interrupt-parent = <&qeic>;
+				local-mac-address = [ 00 00 00 00 00 00 ];
+				rx-clock-name = "none";
+				tx-clock-name = "clk16";
+				phy-handle = <&phy_eth4>;
+				phy-connection-type = "rmii";
+				pio-handle = <&pio_ucc8>;
+			};
+
+			mdio@3320 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				reg = <0x3320 0x18>;
+				compatible = "fsl,ucc-mdio";
+
+				/* Piggy2 (UCC4, MDIO 0x00, RMII) */
+				phy_piggy2: ethernet-phy@00 {
+					reg = <0x0>;
+				};
+
+				/* Eth-1 (UCC5, MDIO 0x08, RMII) */
+				phy_eth1: ethernet-phy@08 {
+					reg = <0x08>;
+				};
+
+				/* Eth-2 (UCC6, MDIO 0x09, RMII) */
+				phy_eth2: ethernet-phy@09 {
+					reg = <0x09>;
+				};
+
+				/* Eth-3 (UCC7, MDIO 0x0a, RMII) */
+				phy_eth3: ethernet-phy@0a {
+					reg = <0x0a>;
+				};
+
+				/* Eth-4 (UCC8, MDIO 0x0b, RMII) */
+				phy_eth4: ethernet-phy@0b {
+					reg = <0x0b>;
+				};
+
+				/* ESTAR-1 (UCC1, MDIO 0x10, RGMII) */
+				phy_estar1: ethernet-phy@10 {
+					interrupt-parent = <&ipic>;
+					interrupts = <17 0x8>;
+					reg = <0x10>;
+				};
+
+				/* ESTAR-2 (UCC2, MDIO 0x11, RGMII) */
+				phy_estar2: ethernet-phy@11 {
+					interrupt-parent = <&ipic>;
+					interrupts = <18 0x8>;
+					reg = <0x11>;
+				};
+			};
+
+			qeic: interrupt-controller@80 {
+				interrupt-controller;
+				compatible = "fsl,qe-ic";
+				#address-cells = <0>;
+				#interrupt-cells = <1>;
+				reg = <0x80 0x80>;
+				interrupts = <32 8 33 8>;
+				interrupt-parent = <&ipic>;
+			};
+		};
+	};
+
+	localbus@e0005000 {
+		#address-cells = <2>;
+		#size-cells = <1>;
+		compatible = "fsl,mpc8360-localbus", "fsl,pq2pro-localbus",
+			     "simple-bus";
+		reg = <0xe0005000 0xd8>;
+		ranges = <0 0 0xf0000000 0x04000000>;	/* Filled in by U-Boot */
+
+		flash@f0000000,0 {
+			compatible = "cfi-flash";
+			/*
+			 * The Intel P30 chip has 2 non-identical chips on
+			 * one die, so we need to define 2 seperate regions
+			 * that are scanned by physmap_of independantly.
+			 */
+			reg = <0 0x00000000 0x02000000
+			       0 0x02000000 0x02000000>;	/* Filled in by U-Boot */
+			bank-width = <2>;
+			#address-cells = <1>;
+			#size-cells = <1>;
+			partition@0 {
+				label = "u-boot";
+				reg = <0 0x40000>;
+			};
+			partition@40000 {
+				label = "env";
+				reg = <0x40000 0x40000>;
+			};
+			partition@80000 {
+				label = "dtb";
+				reg = <0x80000 0x20000>;
+			};
+			partition@a0000 {
+				label = "kernel";
+				reg = <0xa0000 0x300000>;
+			};
+			partition@3a0000 {
+				label = "ramdisk";
+				reg = <0x3a0000 0x800000>;
+			};
+			partition@ba0000 {
+				label = "user";
+				reg = <0xba0000 0x3460000>;
+			};
+		};
+	};
+};
diff --git a/arch/powerpc/boot/dts/mpc8272ads.dts b/arch/powerpc/boot/dts/mpc8272ads.dts
index 2a1929a..60f3327 100644
--- a/arch/powerpc/boot/dts/mpc8272ads.dts
+++ b/arch/powerpc/boot/dts/mpc8272ads.dts
@@ -17,6 +17,13 @@
 	#address-cells = <1>;
 	#size-cells = <1>;
 
+	aliases {
+		ethernet0 = &eth0;
+		ethernet1 = &eth1;
+		serial0 = &scc1;
+		serial1 = &scc4;
+	};
+
 	cpus {
 		#address-cells = <1>;
 		#size-cells = <0>;
@@ -46,13 +53,13 @@
 		#size-cells = <1>;
 		reg = <0xf0010100 0x40>;
 
-		ranges = <0x0 0x0 0xfe000000 0x2000000
+		ranges = <0x0 0x0 0xff800000 0x00800000
 		          0x1 0x0 0xf4500000 0x8000
 		          0x3 0x0 0xf8200000 0x8000>;
 
 		flash@0,0 {
 			compatible = "jedec-flash";
-			reg = <0x0 0x0 0x2000000>;
+			reg = <0x0 0x0 0x00800000>;
 			bank-width = <4>;
 			device-width = <1>;
 		};
@@ -144,7 +151,7 @@
 				reg = <0x119f0 0x10 0x115f0 0x10>;
 			};
 
-			serial@11a00 {
+			scc1: serial@11a00 {
 				device_type = "serial";
 				compatible = "fsl,mpc8272-scc-uart",
 				             "fsl,cpm2-scc-uart";
@@ -155,7 +162,7 @@
 				fsl,cpm-command = <0x800000>;
 			};
 
-			serial@11a60 {
+			scc4: serial@11a60 {
 				device_type = "serial";
 				compatible = "fsl,mpc8272-scc-uart",
 				             "fsl,cpm2-scc-uart";
@@ -192,7 +199,7 @@
 				};
 			};
 
-			ethernet@11300 {
+			eth0: ethernet@11300 {
 				device_type = "network";
 				compatible = "fsl,mpc8272-fcc-enet",
 				             "fsl,cpm2-fcc-enet";
@@ -205,7 +212,7 @@
 				fsl,cpm-command = <0x12000300>;
 			};
 
-			ethernet@11320 {
+			eth1: ethernet@11320 {
 				device_type = "network";
 				compatible = "fsl,mpc8272-fcc-enet",
 				             "fsl,cpm2-fcc-enet";
diff --git a/arch/powerpc/boot/dts/mpc8315erdb.dts b/arch/powerpc/boot/dts/mpc8315erdb.dts
index 3f4c5fb..32e10f5 100644
--- a/arch/powerpc/boot/dts/mpc8315erdb.dts
+++ b/arch/powerpc/boot/dts/mpc8315erdb.dts
@@ -322,6 +322,21 @@
 			reg = <0x700 0x100>;
 			device_type = "ipic";
 		};
+
+		ipic-msi@7c0 {
+			compatible = "fsl,ipic-msi";
+			reg = <0x7c0 0x40>;
+			msi-available-ranges = <0 0x100>;
+			interrupts = <0x43 0x8
+				      0x4  0x8
+				      0x51 0x8
+				      0x52 0x8
+				      0x56 0x8
+				      0x57 0x8
+				      0x58 0x8
+				      0x59 0x8>;
+			interrupt-parent = < &ipic >;
+		};
 	};
 
 	pci0: pci@e0008500 {
diff --git a/arch/powerpc/boot/dts/mpc8349emitx.dts b/arch/powerpc/boot/dts/mpc8349emitx.dts
index e3eeaed..feeeb7f 100644
--- a/arch/powerpc/boot/dts/mpc8349emitx.dts
+++ b/arch/powerpc/boot/dts/mpc8349emitx.dts
@@ -156,7 +156,7 @@
 			interrupt-parent = <&ipic>;
 			interrupts = <39 0x8>;
 			phy_type = "ulpi";
-			port1;
+			port0;
 		};
 
 		usb@23000 {
diff --git a/arch/powerpc/boot/dts/mpc834x_mds.dts b/arch/powerpc/boot/dts/mpc834x_mds.dts
index a2553a6..230febb 100644
--- a/arch/powerpc/boot/dts/mpc834x_mds.dts
+++ b/arch/powerpc/boot/dts/mpc834x_mds.dts
@@ -153,7 +153,7 @@
 			interrupt-parent = <&ipic>;
 			interrupts = <39 0x8>;
 			phy_type = "ulpi";
-			port1;
+			port0;
 		};
 		/* phy type (ULPI, UTMI, UTMI_WIDE, SERIAL) */
 		usb@23000 {
diff --git a/arch/powerpc/boot/dts/mpc8377_mds.dts b/arch/powerpc/boot/dts/mpc8377_mds.dts
index 67bb372..f32c281 100644
--- a/arch/powerpc/boot/dts/mpc8377_mds.dts
+++ b/arch/powerpc/boot/dts/mpc8377_mds.dts
@@ -155,7 +155,7 @@
 			};
 
 			sdhci@2e000 {
-				compatible = "fsl,mpc8377-esdhc", "fsl,mpc8379-esdhc";
+				compatible = "fsl,mpc8377-esdhc", "fsl,esdhc";
 				reg = <0x2e000 0x1000>;
 				interrupts = <42 0x8>;
 				interrupt-parent = <&ipic>;
diff --git a/arch/powerpc/boot/dts/mpc8377_rdb.dts b/arch/powerpc/boot/dts/mpc8377_rdb.dts
index 0533393..224b4f0 100644
--- a/arch/powerpc/boot/dts/mpc8377_rdb.dts
+++ b/arch/powerpc/boot/dts/mpc8377_rdb.dts
@@ -169,7 +169,7 @@
 			};
 
 			sdhci@2e000 {
-				compatible = "fsl,mpc8377-esdhc", "fsl,mpc8379-esdhc";
+				compatible = "fsl,mpc8377-esdhc", "fsl,esdhc";
 				reg = <0x2e000 0x1000>;
 				interrupts = <42 0x8>;
 				interrupt-parent = <&ipic>;
diff --git a/arch/powerpc/boot/dts/mpc8378_mds.dts b/arch/powerpc/boot/dts/mpc8378_mds.dts
index a955a57..f720ab9 100644
--- a/arch/powerpc/boot/dts/mpc8378_mds.dts
+++ b/arch/powerpc/boot/dts/mpc8378_mds.dts
@@ -155,7 +155,7 @@
 			};
 
 			sdhci@2e000 {
-				compatible = "fsl,mpc8378-esdhc", "fsl,mpc8379-esdhc";
+				compatible = "fsl,mpc8378-esdhc", "fsl,esdhc";
 				reg = <0x2e000 0x1000>;
 				interrupts = <42 0x8>;
 				interrupt-parent = <&ipic>;
diff --git a/arch/powerpc/boot/dts/mpc8378_rdb.dts b/arch/powerpc/boot/dts/mpc8378_rdb.dts
index 5d90e85..474ea2f 100644
--- a/arch/powerpc/boot/dts/mpc8378_rdb.dts
+++ b/arch/powerpc/boot/dts/mpc8378_rdb.dts
@@ -169,7 +169,7 @@
 			};
 
 			sdhci@2e000 {
-				compatible = "fsl,mpc8378-esdhc", "fsl,mpc8379-esdhc";
+				compatible = "fsl,mpc8378-esdhc", "fsl,esdhc";
 				reg = <0x2e000 0x1000>;
 				interrupts = <42 0x8>;
 				interrupt-parent = <&ipic>;
diff --git a/arch/powerpc/boot/dts/mpc8379_mds.dts b/arch/powerpc/boot/dts/mpc8379_mds.dts
index d266ddb..4fa221f 100644
--- a/arch/powerpc/boot/dts/mpc8379_mds.dts
+++ b/arch/powerpc/boot/dts/mpc8379_mds.dts
@@ -153,7 +153,7 @@
 			};
 
 			sdhci@2e000 {
-				compatible = "fsl,mpc8379-esdhc";
+				compatible = "fsl,mpc8379-esdhc", "fsl,esdhc";
 				reg = <0x2e000 0x1000>;
 				interrupts = <42 0x8>;
 				interrupt-parent = <&ipic>;
diff --git a/arch/powerpc/boot/dts/mpc8379_rdb.dts b/arch/powerpc/boot/dts/mpc8379_rdb.dts
index 98ae95b..d4838af 100644
--- a/arch/powerpc/boot/dts/mpc8379_rdb.dts
+++ b/arch/powerpc/boot/dts/mpc8379_rdb.dts
@@ -167,7 +167,7 @@
 			};
 
 			sdhci@2e000 {
-				compatible = "fsl,mpc8379-esdhc";
+				compatible = "fsl,mpc8379-esdhc", "fsl,esdhc";
 				reg = <0x2e000 0x1000>;
 				interrupts = <42 0x8>;
 				interrupt-parent = <&ipic>;
diff --git a/arch/powerpc/boot/dts/mpc8569mds.dts b/arch/powerpc/boot/dts/mpc8569mds.dts
index 39c2927..a8dcb01 100644
--- a/arch/powerpc/boot/dts/mpc8569mds.dts
+++ b/arch/powerpc/boot/dts/mpc8569mds.dts
@@ -24,6 +24,8 @@
 		ethernet1 = &enet1;
 		ethernet2 = &enet2;
 		ethernet3 = &enet3;
+		ethernet5 = &enet5;
+		ethernet7 = &enet7;
 		pci1 = &pci1;
 		rapidio0 = &rio0;
 	};
@@ -70,8 +72,30 @@
 			#size-cells = <1>;
 			compatible = "cfi-flash";
 			reg = <0x0 0x0 0x02000000>;
-			bank-width = <2>;
+			bank-width = <1>;
 			device-width = <1>;
+			partition@0 {
+				label = "ramdisk";
+				reg = <0x00000000 0x01c00000>;
+			};
+			partition@1c00000 {
+				label = "kernel";
+				reg = <0x01c00000 0x002e0000>;
+			};
+			partiton@1ee0000 {
+				label = "dtb";
+				reg = <0x01ee0000 0x00020000>;
+			};
+			partition@1f00000 {
+				label = "firmware";
+				reg = <0x01f00000 0x00080000>;
+				read-only;
+			};
+			partition@1f80000 {
+				label = "u-boot";
+				reg = <0x01f80000 0x00080000>;
+				read-only;
+			};
 		};
 
 		bcsr@1,0 {
@@ -466,6 +490,37 @@
 				reg = <0x3>;
 				device_type = "ethernet-phy";
 			};
+			qe_phy5: ethernet-phy@04 {
+				interrupt-parent = <&mpic>;
+				reg = <0x04>;
+				device_type = "ethernet-phy";
+			};
+			qe_phy7: ethernet-phy@06 {
+				interrupt-parent = <&mpic>;
+				reg = <0x6>;
+				device_type = "ethernet-phy";
+			};
+		};
+		mdio@3520 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			reg = <0x3520 0x18>;
+			compatible = "fsl,ucc-mdio";
+
+			tbi0: tbi-phy@15 {
+			reg = <0x15>;
+			device_type = "tbi-phy";
+			};
+		};
+		mdio@3720 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			reg = <0x3720 0x38>;
+			compatible = "fsl,ucc-mdio";
+			tbi1: tbi-phy@17 {
+				reg = <0x17>;
+				device_type = "tbi-phy";
+			};
 		};
 
 		enet2: ucc@2200 {
@@ -513,6 +568,36 @@
 			phy-connection-type = "rgmii-id";
 		};
 
+		enet5: ucc@3400 {
+			device_type = "network";
+			compatible = "ucc_geth";
+			cell-index = <6>;
+			reg = <0x3400 0x200>;
+			interrupts = <41>;
+			interrupt-parent = <&qeic>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			rx-clock-name = "none";
+			tx-clock-name = "none";
+			tbi-handle = <&tbi0>;
+			phy-handle = <&qe_phy5>;
+			phy-connection-type = "sgmii";
+		};
+
+		enet7: ucc@3600 {
+			device_type = "network";
+			compatible = "ucc_geth";
+			cell-index = <8>;
+			reg = <0x3600 0x200>;
+			interrupts = <43>;
+			interrupt-parent = <&qeic>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			rx-clock-name = "none";
+			tx-clock-name = "none";
+			tbi-handle = <&tbi1>;
+			phy-handle = <&qe_phy7>;
+			phy-connection-type = "sgmii";
+		};
+
 		muram@10000 {
 			#address-cells = <1>;
 			#size-cells = <1>;
diff --git a/arch/powerpc/boot/dts/mpc8610_hpcd.dts b/arch/powerpc/boot/dts/mpc8610_hpcd.dts
index cfc2c60..f468d21 100644
--- a/arch/powerpc/boot/dts/mpc8610_hpcd.dts
+++ b/arch/powerpc/boot/dts/mpc8610_hpcd.dts
@@ -100,8 +100,18 @@
 		};
 
 		board-control@3,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
 			compatible = "fsl,fpga-pixis";
 			reg = <3 0 0x20>;
+			ranges = <0 3 0 0x20>;
+
+			sdcsr_pio: gpio-controller@a {
+				#gpio-cells = <2>;
+				compatible = "fsl,fpga-pixis-gpio-bank";
+				reg = <0xa 1>;
+				gpio-controller;
+			};
 		};
 	};
 
@@ -176,6 +186,28 @@
 			interrupt-parent = <&mpic>;
 		};
 
+		spi@7000 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			compatible = "fsl,mpc8610-spi", "fsl,spi";
+			reg = <0x7000 0x40>;
+			cell-index = <0>;
+			interrupts = <59 2>;
+			interrupt-parent = <&mpic>;
+			mode = "cpu";
+			gpios = <&sdcsr_pio 7 0>;
+
+			mmc-slot@0 {
+				compatible = "fsl,mpc8610hpcd-mmc-slot",
+					     "mmc-spi-slot";
+				reg = <0>;
+				gpios = <&sdcsr_pio 0 1   /* nCD */
+					 &sdcsr_pio 1 0>; /*  WP */
+				voltage-ranges = <3300 3300>;
+				spi-max-frequency = <50000000>;
+			};
+		};
+
 		display@2c000 {
 			compatible = "fsl,diu";
 			reg = <0x2c000 100>;
diff --git a/arch/powerpc/boot/dts/pcm030.dts b/arch/powerpc/boot/dts/pcm030.dts
index 8958347..30bfdc0 100644
--- a/arch/powerpc/boot/dts/pcm030.dts
+++ b/arch/powerpc/boot/dts/pcm030.dts
@@ -258,34 +258,16 @@
 				compatible = "nxp,pcf8563";
 				reg = <0x51>;
 			};
-			/* FIXME: EEPROM */
+			eeprom@52 {
+				compatible = "catalyst,24c32";
+				reg = <0x52>;
+			};
 		};
 
 		sram@8000 {
 			compatible = "fsl,mpc5200b-sram","fsl,mpc5200-sram";
 			reg = <0x8000 0x4000>;
 		};
-
-		/* This is only an example device to show the usage of gpios. It maps all available
-		 * gpios to the "gpio-provider" device.
-		 */
-		gpio {
-			compatible = "gpio-provider";
-
-						    /* mpc52xx		exp.con		patchfield */
-			gpios = <&gpio_wkup	0 0 /* GPIO_WKUP_7	11d		jp13-3     */
-				 &gpio_wkup	1 0 /* GPIO_WKUP_6	14c			   */
-				 &gpio_wkup	6 0 /* PSC2_4		43c		x5-11	   */
-				 &gpio_simple	2 0 /* IRDA_1		24c		x7-6	set GPS_PORT_CONFIG[IRDA] = 0 */
-				 &gpio_simple	3 0 /* IRDA_0				x8-5	set GPS_PORT_CONFIG[IRDA] = 0 */
-				 &gpt2		0 0 /* timer2		12d		x4-4	   */
-				 &gpt3		0 0 /* timer3		13d		x6-4	   */
-				 &gpt4		0 0 /* timer4		61c		x2-16	   */
-				 &gpt5		0 0 /* timer5		44c		x7-11	   */
-				 &gpt6		0 0 /* timer6		60c		x8-15	   */
-				 &gpt7		0 0 /* timer7		36a		x17-9	   */
-				 >;
-		};
 	};
 
 	pci@f0000d00 {
diff --git a/arch/powerpc/boot/dts/sbc8349.dts b/arch/powerpc/boot/dts/sbc8349.dts
index 5fb6f66..2d9fa68 100644
--- a/arch/powerpc/boot/dts/sbc8349.dts
+++ b/arch/powerpc/boot/dts/sbc8349.dts
@@ -144,7 +144,7 @@
 			interrupt-parent = <&ipic>;
 			interrupts = <39 0x8>;
 			phy_type = "ulpi";
-			port1;
+			port0;
 		};
 		/* phy type (ULPI, UTMI, UTMI_WIDE, SERIAL) */
 		usb@23000 {
diff --git a/arch/powerpc/boot/dts/xcalibur1501.dts b/arch/powerpc/boot/dts/xcalibur1501.dts
new file mode 100644
index 0000000..ac0a617
--- /dev/null
+++ b/arch/powerpc/boot/dts/xcalibur1501.dts
@@ -0,0 +1,696 @@
+/*
+ * Copyright (C) 2008 Extreme Engineering Solutions, Inc.
+ * Based on MPC8572DS device tree from Freescale Semiconductor, Inc.
+ *
+ * XCalibur1501 6U CompactPCI single-board computer based on MPC8572E
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+
+/dts-v1/;
+/ {
+	model = "xes,xcalibur1501";
+	compatible = "xes,xcalibur1501", "xes,MPC8572";
+	#address-cells = <2>;
+	#size-cells = <2>;
+
+	aliases {
+		ethernet0 = &enet0;
+		ethernet1 = &enet1;
+		ethernet2 = &enet2;
+		ethernet3 = &enet3;
+		serial0 = &serial0;
+		serial1 = &serial1;
+		pci2 = &pci2;
+	};
+
+	cpus {
+		#address-cells = <1>;
+		#size-cells = <0>;
+
+		PowerPC,8572@0 {
+			device_type = "cpu";
+			reg = <0x0>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <0x8000>;		// L1, 32K
+			i-cache-size = <0x8000>;		// L1, 32K
+			timebase-frequency = <0>;
+			bus-frequency = <0>;
+			clock-frequency = <0>;
+			next-level-cache = <&L2>;
+		};
+
+		PowerPC,8572@1 {
+			device_type = "cpu";
+			reg = <0x1>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <0x8000>;		// L1, 32K
+			i-cache-size = <0x8000>;		// L1, 32K
+			timebase-frequency = <0>;
+			bus-frequency = <0>;
+			clock-frequency = <0>;
+			next-level-cache = <&L2>;
+		};
+	};
+
+	memory {
+		device_type = "memory";
+		reg = <0x0 0x0 0x0 0x0>;	// Filled in by U-Boot
+	};
+
+	localbus@ef005000 {
+		#address-cells = <2>;
+		#size-cells = <1>;
+		compatible = "fsl,mpc8572-elbc", "fsl,elbc", "simple-bus";
+		reg = <0 0xef005000 0 0x1000>;
+		interrupts = <19 2>;
+		interrupt-parent = <&mpic>;
+		/* Local bus region mappings */
+		ranges = <0 0 0 0xf8000000 0x8000000  /* CS0: Flash 1 */
+			  1 0 0 0xf0000000 0x8000000  /* CS1: Flash 2 */
+			  2 0 0 0xef800000 0x40000    /* CS2: NAND CE1 */
+			  3 0 0 0xef840000 0x40000    /* CS3: NAND CE2 */
+			  4 0 0 0xe9000000 0x100000>; /* CS4: USB */
+
+		nor-boot@0,0 {
+			compatible = "amd,s29gl01gp", "cfi-flash";
+			bank-width = <2>;
+			reg = <0 0 0x8000000>; /* 128MB */
+			#address-cells = <1>;
+			#size-cells = <1>;
+			partition@0 {
+				label = "Primary user space";
+				reg = <0x00000000 0x6f00000>; /* 111 MB */
+			};
+			partition@6f00000 {
+				label = "Primary kernel";
+				reg = <0x6f00000 0x1000000>; /* 16 MB */
+			};
+			partition@7f00000 {
+				label = "Primary DTB";
+				reg = <0x7f00000 0x40000>; /* 256 KB */
+			};
+			partition@7f40000 {
+				label = "Primary U-Boot environment";
+				reg = <0x7f40000 0x40000>; /* 256 KB */
+			};
+			partition@7f80000 {
+				label = "Primary U-Boot";
+				reg = <0x7f80000 0x80000>; /* 512 KB */
+				read-only;
+			};
+		};
+
+		nor-alternate@1,0 {
+			compatible = "amd,s29gl01gp", "cfi-flash";
+			bank-width = <2>;
+			//reg = <0xf0000000 0x08000000>; /* 128MB */
+			reg = <1 0 0x8000000>; /* 128MB */
+			#address-cells = <1>;
+			#size-cells = <1>;
+			partition@0 {
+				label = "Secondary user space";
+				reg = <0x00000000 0x6f00000>; /* 111 MB */
+			};
+			partition@6f00000 {
+				label = "Secondary kernel";
+				reg = <0x6f00000 0x1000000>; /* 16 MB */
+			};
+			partition@7f00000 {
+				label = "Secondary DTB";
+				reg = <0x7f00000 0x40000>; /* 256 KB */
+			};
+			partition@7f40000 {
+				label = "Secondary U-Boot environment";
+				reg = <0x7f40000 0x40000>; /* 256 KB */
+			};
+			partition@7f80000 {
+				label = "Secondary U-Boot";
+				reg = <0x7f80000 0x80000>; /* 512 KB */
+				read-only;
+			};
+		};
+
+		nand@2,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			/*
+			 * Actual part could be ST Micro NAND08GW3B2A (1 GB),
+			 * Micron MT29F8G08DAA (2x 512 MB), or Micron
+			 * MT29F16G08FAA (2x 1 GB), depending on the build
+			 * configuration
+			 */
+			compatible = "fsl,mpc8572-fcm-nand",
+				     "fsl,elbc-fcm-nand";
+			reg = <2 0 0x40000>;
+			/* U-Boot should fix this up if chip size > 1 GB */
+			partition@0 {
+				label = "NAND Filesystem";
+				reg = <0 0x40000000>;
+			};
+		};
+
+		usb@4,0 {
+			compatible = "nxp,usb-isp1761";
+			reg = <4 0 0x100000>;
+			bus-width = <32>;
+			interrupt-parent = <&mpic>;
+			interrupts = <10 1>;
+		};
+	};
+
+	soc8572@ef000000 {
+		#address-cells = <1>;
+		#size-cells = <1>;
+		device_type = "soc";
+		compatible = "fsl,mpc8572-immr", "simple-bus";
+		ranges = <0x0 0 0xef000000 0x100000>;
+		bus-frequency = <0>;		// Filled out by uboot.
+
+		ecm-law@0 {
+			compatible = "fsl,ecm-law";
+			reg = <0x0 0x1000>;
+			fsl,num-laws = <12>;
+		};
+
+		ecm@1000 {
+			compatible = "fsl,mpc8572-ecm", "fsl,ecm";
+			reg = <0x1000 0x1000>;
+			interrupts = <17 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		memory-controller@2000 {
+			compatible = "fsl,mpc8572-memory-controller";
+			reg = <0x2000 0x1000>;
+			interrupt-parent = <&mpic>;
+			interrupts = <18 2>;
+		};
+
+		memory-controller@6000 {
+			compatible = "fsl,mpc8572-memory-controller";
+			reg = <0x6000 0x1000>;
+			interrupt-parent = <&mpic>;
+			interrupts = <18 2>;
+		};
+
+		L2: l2-cache-controller@20000 {
+			compatible = "fsl,mpc8572-l2-cache-controller";
+			reg = <0x20000 0x1000>;
+			cache-line-size = <32>;	// 32 bytes
+			cache-size = <0x100000>; // L2, 1M
+			interrupt-parent = <&mpic>;
+			interrupts = <16 2>;
+		};
+
+		i2c@3000 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <0>;
+			compatible = "fsl-i2c";
+			reg = <0x3000 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+
+			temp-sensor@48 {
+				compatible = "dallas,ds1631", "dallas,ds1621";
+				reg = <0x48>;
+			};
+
+			temp-sensor@4c {
+				compatible = "adi,adt7461";
+				reg = <0x4c>;
+			};
+
+			cpu-supervisor@51 {
+				compatible = "dallas,ds4510";
+				reg = <0x51>;
+			};
+
+			eeprom@54 {
+				compatible = "atmel,at24c128b";
+				reg = <0x54>;
+			};
+
+			rtc@68 {
+				compatible = "stm,m41t00",
+				             "dallas,ds1338";
+				reg = <0x68>;
+			};
+
+			pcie-switch@6a {
+				compatible = "plx,pex8648";
+				reg = <0x6a>;
+			};
+
+			/* On-board signals for VID, flash, serial */
+			gpio1: gpio@18 {
+				compatible = "nxp,pca9557";
+				reg = <0x18>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			/* PMC0/XMC0 signals */
+			gpio2: gpio@1c {
+				compatible = "nxp,pca9557";
+				reg = <0x1c>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			/* PMC1/XMC1 signals */
+			gpio3: gpio@1d {
+				compatible = "nxp,pca9557";
+				reg = <0x1d>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			/* CompactPCI signals (sysen, GA[4:0]) */
+			gpio4: gpio@1e {
+				compatible = "nxp,pca9557";
+				reg = <0x1e>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			/* CompactPCI J5 GPIO and FAL/DEG/PRST */
+			gpio5: gpio@1f {
+				compatible = "nxp,pca9557";
+				reg = <0x1f>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+		};
+
+		i2c@3100 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <1>;
+			compatible = "fsl-i2c";
+			reg = <0x3100 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+		};
+
+		dma@c300 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,mpc8572-dma", "fsl,eloplus-dma";
+			reg = <0xc300 0x4>;
+			ranges = <0x0 0xc100 0x200>;
+			cell-index = <1>;
+			dma-channel@0 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x0 0x80>;
+				cell-index = <0>;
+				interrupt-parent = <&mpic>;
+				interrupts = <76 2>;
+			};
+			dma-channel@80 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x80 0x80>;
+				cell-index = <1>;
+				interrupt-parent = <&mpic>;
+				interrupts = <77 2>;
+			};
+			dma-channel@100 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x100 0x80>;
+				cell-index = <2>;
+				interrupt-parent = <&mpic>;
+				interrupts = <78 2>;
+			};
+			dma-channel@180 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x180 0x80>;
+				cell-index = <3>;
+				interrupt-parent = <&mpic>;
+				interrupts = <79 2>;
+			};
+		};
+
+		dma@21300 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,mpc8572-dma", "fsl,eloplus-dma";
+			reg = <0x21300 0x4>;
+			ranges = <0x0 0x21100 0x200>;
+			cell-index = <0>;
+			dma-channel@0 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x0 0x80>;
+				cell-index = <0>;
+				interrupt-parent = <&mpic>;
+				interrupts = <20 2>;
+			};
+			dma-channel@80 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x80 0x80>;
+				cell-index = <1>;
+				interrupt-parent = <&mpic>;
+				interrupts = <21 2>;
+			};
+			dma-channel@100 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x100 0x80>;
+				cell-index = <2>;
+				interrupt-parent = <&mpic>;
+				interrupts = <22 2>;
+			};
+			dma-channel@180 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x180 0x80>;
+				cell-index = <3>;
+				interrupt-parent = <&mpic>;
+				interrupts = <23 2>;
+			};
+		};
+
+		/* eTSEC 1 front panel 0 */
+		enet0: ethernet@24000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <0>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x24000 0x1000>;
+			ranges = <0x0 0x24000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <29 2 30 2 34 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi0>;
+			phy-handle = <&phy0>;
+			phy-connection-type = "sgmii";
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-mdio";
+				reg = <0x520 0x20>;
+
+				phy0: ethernet-phy@1 {
+					interrupt-parent = <&mpic>;
+					interrupts = <4 1>;
+					reg = <0x1>;
+				};
+				phy1: ethernet-phy@2 {
+					interrupt-parent = <&mpic>;
+					interrupts = <4 1>;
+					reg = <0x2>;
+				};
+				phy2: ethernet-phy@3 {
+					interrupt-parent = <&mpic>;
+					interrupts = <5 1>;
+					reg = <0x3>;
+				};
+				phy3: ethernet-phy@4 {
+					interrupt-parent = <&mpic>;
+					interrupts = <5 1>;
+					reg = <0x4>;
+				};
+				tbi0: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC 2 front panel 1 */
+		enet1: ethernet@25000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <1>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x25000 0x1000>;
+			ranges = <0x0 0x25000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <35 2 36 2 40 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi1>;
+			phy-handle = <&phy1>;
+			phy-connection-type = "sgmii";
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi1: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC 3 PICMG2.16 backplane port 0 */
+		enet2: ethernet@26000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <2>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x26000 0x1000>;
+			ranges = <0x0 0x26000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <31 2 32 2 33 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi2>;
+			phy-handle = <&phy2>;
+			phy-connection-type = "sgmii";
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi2: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC 4 PICMG2.16 backplane port 1 */
+		enet3: ethernet@27000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <3>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x27000 0x1000>;
+			ranges = <0x0 0x27000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <37 2 38 2 39 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi3>;
+			phy-handle = <&phy3>;
+			phy-connection-type = "sgmii";
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi3: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* UART0 */
+		serial0: serial@4500 {
+			cell-index = <0>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4500 0x100>;
+			clock-frequency = <0>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		/* UART1 */
+		serial1: serial@4600 {
+			cell-index = <1>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4600 0x100>;
+			clock-frequency = <0>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		global-utilities@e0000 {	//global utilities block
+			compatible = "fsl,mpc8572-guts";
+			reg = <0xe0000 0x1000>;
+			fsl,has-rstcr;
+		};
+
+		msi@41600 {
+			compatible = "fsl,mpc8572-msi", "fsl,mpic-msi";
+			reg = <0x41600 0x80>;
+			msi-available-ranges = <0 0x100>;
+			interrupts = <
+				0xe0 0
+				0xe1 0
+				0xe2 0
+				0xe3 0
+				0xe4 0
+				0xe5 0
+				0xe6 0
+				0xe7 0>;
+			interrupt-parent = <&mpic>;
+		};
+
+		crypto@30000 {
+			compatible = "fsl,sec3.0", "fsl,sec2.4", "fsl,sec2.2",
+				     "fsl,sec2.1", "fsl,sec2.0";
+			reg = <0x30000 0x10000>;
+			interrupts = <45 2 58 2>;
+			interrupt-parent = <&mpic>;
+			fsl,num-channels = <4>;
+			fsl,channel-fifo-len = <24>;
+			fsl,exec-units-mask = <0x9fe>;
+			fsl,descriptor-types-mask = <0x3ab0ebf>;
+		};
+
+		mpic: pic@40000 {
+			interrupt-controller;
+			#address-cells = <0>;
+			#interrupt-cells = <2>;
+			reg = <0x40000 0x40000>;
+			compatible = "chrp,open-pic";
+			device_type = "open-pic";
+		};
+
+		gpio0: gpio@f000 {
+			compatible = "fsl,mpc8572-gpio";
+			reg = <0xf000 0x1000>;
+			interrupts = <47 2>;
+			interrupt-parent = <&mpic>;
+			#gpio-cells = <2>;
+			gpio-controller;
+		};
+
+		gpio-leds {
+			compatible = "gpio-leds";
+
+			heartbeat {
+				label = "Heartbeat";
+				gpios = <&gpio0 4 1>;
+				linux,default-trigger = "heartbeat";
+			};
+
+			yellow {
+				label = "Yellow";
+				gpios = <&gpio0 5 1>;
+			};
+
+			red {
+				label = "Red";
+				gpios = <&gpio0 6 1>;
+			};
+
+			green {
+				label = "Green";
+				gpios = <&gpio0 7 1>;
+			};
+		};
+
+		/* PME (pattern-matcher) */
+		pme@10000 {
+			compatible = "fsl,mpc8572-pme", "pme8572";
+			reg = <0x10000 0x5000>;
+			interrupts = <57 2 64 2 65 2 66 2 67 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		tlu@2f000 {
+			compatible = "fsl,mpc8572-tlu", "fsl_tlu";
+			reg = <0x2f000 0x1000>;
+			interupts = <61 2 >;
+			interrupt-parent = <&mpic>;
+		};
+
+		tlu@15000 {
+			compatible = "fsl,mpc8572-tlu", "fsl_tlu";
+			reg = <0x15000 0x1000>;
+			interupts = <75 2>;
+			interrupt-parent = <&mpic>;
+		};
+	};
+
+	/*
+	 * PCI Express controller 3 @ ef008000 is not used.
+	 * This would have been pci0 on other mpc85xx platforms.
+	 *
+	 * PCI Express controller 2 @ ef009000 is not used.
+	 * This would have been pci1 on other mpc85xx platforms.
+	 */
+
+	/* PCI Express controller 1, wired to PEX8648 PCIe switch */
+	pci2: pcie@ef00a000 {
+		compatible = "fsl,mpc8548-pcie";
+		device_type = "pci";
+		#interrupt-cells = <1>;
+		#size-cells = <2>;
+		#address-cells = <3>;
+		reg = <0 0xef00a000 0 0x1000>;
+		bus-range = <0 255>;
+		ranges = <0x2000000 0x0 0x80000000 0 0x80000000 0x0 0x40000000
+			  0x1000000 0x0 0x00000000 0 0xe8000000 0x0 0x10000>;
+		clock-frequency = <33333333>;
+		interrupt-parent = <&mpic>;
+		interrupts = <26 2>;
+		interrupt-map-mask = <0xf800 0x0 0x0 0x7>;
+		interrupt-map = <
+			/* IDSEL 0x0 */
+			0x0 0x0 0x0 0x1 &mpic 0x0 0x1
+			0x0 0x0 0x0 0x2 &mpic 0x1 0x1
+			0x0 0x0 0x0 0x3 &mpic 0x2 0x1
+			0x0 0x0 0x0 0x4 &mpic 0x3 0x1
+			>;
+		pcie@0 {
+			reg = <0x0 0x0 0x0 0x0 0x0>;
+			#size-cells = <2>;
+			#address-cells = <3>;
+			device_type = "pci";
+			ranges = <0x2000000 0x0 0x80000000
+				  0x2000000 0x0 0x80000000
+				  0x0 0x40000000
+
+				  0x1000000 0x0 0x0
+				  0x1000000 0x0 0x0
+				  0x0 0x100000>;
+		};
+	};
+};
diff --git a/arch/powerpc/boot/dts/xpedite5200.dts b/arch/powerpc/boot/dts/xpedite5200.dts
new file mode 100644
index 0000000..a0cf53f
--- /dev/null
+++ b/arch/powerpc/boot/dts/xpedite5200.dts
@@ -0,0 +1,466 @@
+/*
+ * Copyright (C) 2009 Extreme Engineering Solutions, Inc.
+ * Based on TQM8548 device tree
+ *
+ * XPedite5200 PrPMC/XMC module based on MPC8548E
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+
+/dts-v1/;
+
+/ {
+	model = "xes,xpedite5200";
+	compatible = "xes,xpedite5200", "xes,MPC8548";
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	aliases {
+		ethernet0 = &enet0;
+		ethernet1 = &enet1;
+		ethernet2 = &enet2;
+		ethernet3 = &enet3;
+
+		serial0 = &serial0;
+		serial1 = &serial1;
+		pci0 = &pci0;
+	};
+
+	cpus {
+		#address-cells = <1>;
+		#size-cells = <0>;
+
+		PowerPC,8548@0 {
+			device_type = "cpu";
+			reg = <0>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <0x8000>;	// L1, 32K
+			i-cache-size = <0x8000>;	// L1, 32K
+			next-level-cache = <&L2>;
+		};
+	};
+
+	memory {
+		device_type = "memory";
+		reg = <0x0 0x0>;	// Filled in by U-Boot
+	};
+
+	soc@ef000000 {
+		#address-cells = <1>;
+		#size-cells = <1>;
+		device_type = "soc";
+		ranges = <0x0 0xef000000 0x100000>;
+		bus-frequency = <0>;
+		compatible = "fsl,mpc8548-immr", "simple-bus";
+
+		ecm-law@0 {
+			compatible = "fsl,ecm-law";
+			reg = <0x0 0x1000>;
+			fsl,num-laws = <12>;
+		};
+
+		ecm@1000 {
+			compatible = "fsl,mpc8548-ecm", "fsl,ecm";
+			reg = <0x1000 0x1000>;
+			interrupts = <17 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		memory-controller@2000 {
+			compatible = "fsl,mpc8548-memory-controller";
+			reg = <0x2000 0x1000>;
+			interrupt-parent = <&mpic>;
+			interrupts = <18 2>;
+		};
+
+		L2: l2-cache-controller@20000 {
+			compatible = "fsl,mpc8548-l2-cache-controller";
+			reg = <0x20000 0x1000>;
+			cache-line-size = <32>;	// 32 bytes
+			cache-size = <0x80000>;	// L2, 512K
+			interrupt-parent = <&mpic>;
+			interrupts = <16 2>;
+		};
+
+		/* On-card I2C */
+		i2c@3000 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <0>;
+			compatible = "fsl-i2c";
+			reg = <0x3000 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+
+			/*
+			 * Board GPIO:
+			 * 	0: BRD_CFG0 (1: P14 IO present)
+			 * 	1: BRD_CFG1 (1: FP ethernet present)
+			 * 	2: BRD_CFG2 (1: XMC IO present)
+			 * 	3: XMC root complex indicator
+			 * 	4: Flash boot device indicator
+			 * 	5: Flash write protect enable
+			 * 	6: PMC monarch indicator
+			 * 	7: PMC EREADY
+			 */
+			gpio1: gpio@18 {
+				compatible = "nxp,pca9556";
+				reg = <0x18>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			/* P14 GPIO */
+			gpio2: gpio@19 {
+				compatible = "nxp,pca9556";
+				reg = <0x19>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			eeprom@50 {
+				compatible = "atmel,at24c16";
+				reg = <0x50>;
+			};
+
+			rtc@68 {
+				compatible = "stm,m41t00",
+					     "dallas,ds1338";
+				reg = <0x68>;
+			};
+
+			dtt@48 {
+				compatible = "maxim,max1237";
+				reg = <0x34>;
+			};
+		};
+
+		/* Off-card I2C */
+		i2c@3100 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <1>;
+			compatible = "fsl-i2c";
+			reg = <0x3100 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+		};
+
+		dma@21300 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,mpc8548-dma", "fsl,eloplus-dma";
+			reg = <0x21300 0x4>;
+			ranges = <0x0 0x21100 0x200>;
+			cell-index = <0>;
+			dma-channel@0 {
+				compatible = "fsl,mpc8548-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x0 0x80>;
+				cell-index = <0>;
+				interrupt-parent = <&mpic>;
+				interrupts = <20 2>;
+			};
+			dma-channel@80 {
+				compatible = "fsl,mpc8548-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x80 0x80>;
+				cell-index = <1>;
+				interrupt-parent = <&mpic>;
+				interrupts = <21 2>;
+			};
+			dma-channel@100 {
+				compatible = "fsl,mpc8548-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x100 0x80>;
+				cell-index = <2>;
+				interrupt-parent = <&mpic>;
+				interrupts = <22 2>;
+			};
+			dma-channel@180 {
+				compatible = "fsl,mpc8548-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x180 0x80>;
+				cell-index = <3>;
+				interrupt-parent = <&mpic>;
+				interrupts = <23 2>;
+			};
+		};
+
+		/* eTSEC1: Front panel port 0 */
+		enet0: ethernet@24000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <0>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x24000 0x1000>;
+			ranges = <0x0 0x24000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <29 2 30 2 34 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi0>;
+			phy-handle = <&phy0>;
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-mdio";
+				reg = <0x520 0x20>;
+
+				phy0: ethernet-phy@1 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x1>;
+				};
+				phy1: ethernet-phy@2 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x2>;
+				};
+				phy2: ethernet-phy@3 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x3>;
+				};
+				phy3: ethernet-phy@4 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x4>;
+				};
+				tbi0: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC2: Front panel port 1 */
+		enet1: ethernet@25000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <1>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x25000 0x1000>;
+			ranges = <0x0 0x25000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <35 2 36 2 40 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi1>;
+			phy-handle = <&phy1>;
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi1: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC3: Rear panel port 2 */
+		enet2: ethernet@26000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <2>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x26000 0x1000>;
+			ranges = <0x0 0x26000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <31 2 32 2 33 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi2>;
+			phy-handle = <&phy2>;
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi2: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC4: Rear panel port 3 */
+		enet3: ethernet@27000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <3>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x27000 0x1000>;
+			ranges = <0x0 0x27000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <37 2 38 2 39 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi3>;
+			phy-handle = <&phy3>;
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi3: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		serial0: serial@4500 {
+			cell-index = <0>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4500 0x100>;
+			clock-frequency = <0>;
+			current-speed = <115200>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		serial1: serial@4600 {
+			cell-index = <1>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4600 0x100>;
+			clock-frequency = <0>;
+			current-speed = <115200>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		global-utilities@e0000 {	// global utilities reg
+			compatible = "fsl,mpc8548-guts";
+			reg = <0xe0000 0x1000>;
+			fsl,has-rstcr;
+		};
+
+		mpic: pic@40000 {
+			interrupt-controller;
+			#address-cells = <0>;
+			#interrupt-cells = <2>;
+			reg = <0x40000 0x40000>;
+			compatible = "chrp,open-pic";
+			device_type = "open-pic";
+		};
+	};
+
+	localbus@ef005000 {
+		compatible = "fsl,mpc8548-localbus", "fsl,pq3-localbus",
+			     "simple-bus";
+		#address-cells = <2>;
+		#size-cells = <1>;
+		reg = <0xef005000 0x100>;	// BRx, ORx, etc.
+
+		ranges = <
+			0 0x0 0xfc000000 0x04000000	// NOR boot flash
+			1 0x0 0xf8000000 0x04000000	// NOR expansion flash
+			2 0x0 0xef800000 0x00010000	// NAND CE1
+			3 0x0 0xef840000 0x00010000	// NAND CE2
+		>;
+
+		nor-boot@0,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "cfi-flash";
+			reg = <0 0x0 0x4000000>;
+			bank-width = <2>;
+
+			partition@0 {
+				label = "Primary OS";
+				reg = <0x00000000 0x180000>;
+			};
+			partition@180000 {
+				label = "Secondary OS";
+				reg = <0x00180000 0x180000>;
+			};
+			partition@300000 {
+				label = "User";
+				reg = <0x00300000 0x3c80000>;
+			};
+			partition@3f80000 {
+				label = "Boot firmware";
+				reg = <0x03f80000 0x80000>;
+			};
+		};
+
+		nor-alternate@1,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "cfi-flash";
+			reg = <1 0x0 0x4000000>;
+			bank-width = <2>;
+
+			partition@0 {
+				label = "Filesystem";
+				reg = <0x00000000 0x3f80000>;
+			};
+			partition@3f80000 {
+				label = "Alternate boot firmware";
+				reg = <0x03f80000 0x80000>;
+			};
+		};
+
+		nand@2,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "xes,address-ctl-nand";
+			reg = <2 0x0 0x10000>;
+			cle-line = <0x8>;	/* CLE tied to A3 */
+			ale-line = <0x10>;	/* ALE tied to A4 */
+
+			/* U-Boot should fix this up */
+			partition@0 {
+				label = "NAND Filesystem";
+				reg = <0 0x40000000>;
+			};
+		};
+	};
+
+	/* PMC interface */
+	pci0: pci@ef008000 {
+		#interrupt-cells = <1>;
+		#size-cells = <2>;
+		#address-cells = <3>;
+		compatible = "fsl,mpc8540-pcix", "fsl,mpc8540-pci";
+		device_type = "pci";
+		reg = <0xef008000 0x1000>;
+		clock-frequency = <33333333>;
+		interrupt-map-mask = <0xf800 0x0 0x0 0x7>;
+		interrupt-map = <
+				/* IDSEL */
+				 0xe000 0 0 1 &mpic 2 1
+				 0xe000 0 0 2 &mpic 3 1>;
+
+		interrupt-parent = <&mpic>;
+		interrupts = <24 2>;
+		bus-range = <0 0>;
+		ranges = <0x02000000 0 0x80000000 0x80000000 0 0x40000000
+			  0x01000000 0 0x00000000 0xe8000000 0 0x00800000>;
+	};
+
+	/* XMC PCIe is not yet enabled in U-Boot on XPedite5200 */
+};
diff --git a/arch/powerpc/boot/dts/xpedite5200_xmon.dts b/arch/powerpc/boot/dts/xpedite5200_xmon.dts
new file mode 100644
index 0000000..c5b2975
--- /dev/null
+++ b/arch/powerpc/boot/dts/xpedite5200_xmon.dts
@@ -0,0 +1,506 @@
+/*
+ * Copyright (C) 2009 Extreme Engineering Solutions, Inc.
+ * Based on TQM8548 device tree
+ *
+ * XPedite5200 PrPMC/XMC module based on MPC8548E.  This dts is for the
+ * xMon boot loader memory map which differs from U-Boot's.
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+
+/dts-v1/;
+
+/ {
+	model = "xes,xpedite5200";
+	compatible = "xes,xpedite5200", "xes,MPC8548";
+	#address-cells = <1>;
+	#size-cells = <1>;
+	form-factor = "PMC/XMC";
+	boot-bank = <0x0>;
+
+	aliases {
+		ethernet0 = &enet0;
+		ethernet1 = &enet1;
+		ethernet2 = &enet2;
+		ethernet3 = &enet3;
+
+		serial0 = &serial0;
+		serial1 = &serial1;
+		pci0 = &pci0;
+		pci1 = &pci1;
+	};
+
+	cpus {
+		#address-cells = <1>;
+		#size-cells = <0>;
+
+		PowerPC,8548@0 {
+			device_type = "cpu";
+			reg = <0>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <0x8000>;	// L1, 32K
+			i-cache-size = <0x8000>;	// L1, 32K
+			next-level-cache = <&L2>;
+		};
+	};
+
+	memory {
+		device_type = "memory";
+		reg = <0x0 0x0>;	// Filled in by boot loader
+	};
+
+	soc@ef000000 {
+		#address-cells = <1>;
+		#size-cells = <1>;
+		device_type = "soc";
+		ranges = <0x0 0xef000000 0x100000>;
+		bus-frequency = <0>;
+		compatible = "fsl,mpc8548-immr", "simple-bus";
+
+		ecm-law@0 {
+			compatible = "fsl,ecm-law";
+			reg = <0x0 0x1000>;
+			fsl,num-laws = <12>;
+		};
+
+		ecm@1000 {
+			compatible = "fsl,mpc8548-ecm", "fsl,ecm";
+			reg = <0x1000 0x1000>;
+			interrupts = <17 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		memory-controller@2000 {
+			compatible = "fsl,mpc8548-memory-controller";
+			reg = <0x2000 0x1000>;
+			interrupt-parent = <&mpic>;
+			interrupts = <18 2>;
+		};
+
+		L2: l2-cache-controller@20000 {
+			compatible = "fsl,mpc8548-l2-cache-controller";
+			reg = <0x20000 0x1000>;
+			cache-line-size = <32>;	// 32 bytes
+			cache-size = <0x80000>;	// L2, 512K
+			interrupt-parent = <&mpic>;
+			interrupts = <16 2>;
+		};
+
+		/* On-card I2C */
+		i2c@3000 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <0>;
+			compatible = "fsl-i2c";
+			reg = <0x3000 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+
+			/*
+			 * Board GPIO:
+			 * 	0: BRD_CFG0 (1: P14 IO present)
+			 * 	1: BRD_CFG1 (1: FP ethernet present)
+			 * 	2: BRD_CFG2 (1: XMC IO present)
+			 * 	3: XMC root complex indicator
+			 * 	4: Flash boot device indicator
+			 * 	5: Flash write protect enable
+			 * 	6: PMC monarch indicator
+			 * 	7: PMC EREADY
+			 */
+			gpio1: gpio@18 {
+				compatible = "nxp,pca9556";
+				reg = <0x18>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			/* P14 GPIO */
+			gpio2: gpio@19 {
+				compatible = "nxp,pca9556";
+				reg = <0x19>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			eeprom@50 {
+				compatible = "atmel,at24c16";
+				reg = <0x50>;
+			};
+
+			rtc@68 {
+				compatible = "stm,m41t00",
+					     "dallas,ds1338";
+				reg = <0x68>;
+			};
+
+			dtt@48 {
+				compatible = "maxim,max1237";
+				reg = <0x34>;
+			};
+		};
+
+		/* Off-card I2C */
+		i2c@3100 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <1>;
+			compatible = "fsl-i2c";
+			reg = <0x3100 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+		};
+
+		dma@21300 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,mpc8548-dma", "fsl,eloplus-dma";
+			reg = <0x21300 0x4>;
+			ranges = <0x0 0x21100 0x200>;
+			cell-index = <0>;
+			dma-channel@0 {
+				compatible = "fsl,mpc8548-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x0 0x80>;
+				cell-index = <0>;
+				interrupt-parent = <&mpic>;
+				interrupts = <20 2>;
+			};
+			dma-channel@80 {
+				compatible = "fsl,mpc8548-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x80 0x80>;
+				cell-index = <1>;
+				interrupt-parent = <&mpic>;
+				interrupts = <21 2>;
+			};
+			dma-channel@100 {
+				compatible = "fsl,mpc8548-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x100 0x80>;
+				cell-index = <2>;
+				interrupt-parent = <&mpic>;
+				interrupts = <22 2>;
+			};
+			dma-channel@180 {
+				compatible = "fsl,mpc8548-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x180 0x80>;
+				cell-index = <3>;
+				interrupt-parent = <&mpic>;
+				interrupts = <23 2>;
+			};
+		};
+
+		/* eTSEC1: Front panel port 0 */
+		enet0: ethernet@24000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <0>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x24000 0x1000>;
+			ranges = <0x0 0x24000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <29 2 30 2 34 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi0>;
+			phy-handle = <&phy0>;
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-mdio";
+				reg = <0x520 0x20>;
+
+				phy0: ethernet-phy@1 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x1>;
+				};
+				phy1: ethernet-phy@2 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x2>;
+				};
+				phy2: ethernet-phy@3 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x3>;
+				};
+				phy3: ethernet-phy@4 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x4>;
+				};
+				tbi0: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC2: Front panel port 1 */
+		enet1: ethernet@25000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <1>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x25000 0x1000>;
+			ranges = <0x0 0x25000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <35 2 36 2 40 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi1>;
+			phy-handle = <&phy1>;
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi1: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC3: Rear panel port 2 */
+		enet2: ethernet@26000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <2>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x26000 0x1000>;
+			ranges = <0x0 0x26000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <31 2 32 2 33 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi2>;
+			phy-handle = <&phy2>;
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi2: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC4: Rear panel port 3 */
+		enet3: ethernet@27000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <3>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x27000 0x1000>;
+			ranges = <0x0 0x27000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <37 2 38 2 39 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi3>;
+			phy-handle = <&phy3>;
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi3: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		serial0: serial@4500 {
+			cell-index = <0>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4500 0x100>;
+			clock-frequency = <0>;
+			current-speed = <9600>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		serial1: serial@4600 {
+			cell-index = <1>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4600 0x100>;
+			clock-frequency = <0>;
+			current-speed = <9600>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		global-utilities@e0000 {	// global utilities reg
+			compatible = "fsl,mpc8548-guts";
+			reg = <0xe0000 0x1000>;
+			fsl,has-rstcr;
+		};
+
+		mpic: pic@40000 {
+			interrupt-controller;
+			#address-cells = <0>;
+			#interrupt-cells = <2>;
+			reg = <0x40000 0x40000>;
+			compatible = "chrp,open-pic";
+			device_type = "open-pic";
+		};
+	};
+
+	localbus@ef005000 {
+		compatible = "fsl,mpc8548-localbus", "fsl,pq3-localbus",
+			     "simple-bus";
+		#address-cells = <2>;
+		#size-cells = <1>;
+		reg = <0xef005000 0x100>;	// BRx, ORx, etc.
+
+		ranges = <
+			0 0x0 0xf8000000 0x08000000	// NOR boot flash
+			1 0x0 0xf0000000 0x08000000	// NOR expansion flash
+			2 0x0 0xe8000000 0x00010000	// NAND CE1
+			3 0x0 0xe8010000 0x00010000	// NAND CE2
+		>;
+
+		nor-boot@0,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "cfi-flash";
+			reg = <0 0x0 0x4000000>;
+			bank-width = <2>;
+
+			partition@0 {
+				label = "Primary OS";
+				reg = <0x00000000 0x180000>;
+			};
+			partition@180000 {
+				label = "Secondary OS";
+				reg = <0x00180000 0x180000>;
+			};
+			partition@300000 {
+				label = "User";
+				reg = <0x00300000 0x3c80000>;
+			};
+			partition@3f80000 {
+				label = "Boot firmware";
+				reg = <0x03f80000 0x80000>;
+			};
+		};
+
+		nor-alternate@1,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "cfi-flash";
+			reg = <1 0x0 0x4000000>;
+			bank-width = <2>;
+
+			partition@0 {
+				label = "Filesystem";
+				reg = <0x00000000 0x3f80000>;
+			};
+			partition@3f80000 {
+				label = "Alternate boot firmware";
+				reg = <0x03f80000 0x80000>;
+			};
+		};
+
+		nand@2,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "xes,address-ctl-nand";
+			reg = <2 0x0 0x10000>;
+			cle-line = <0x8>;	/* CLE tied to A3 */
+			ale-line = <0x10>;	/* ALE tied to A4 */
+
+			partition@0 {
+				label = "NAND Filesystem";
+				reg = <0 0x40000000>;
+			};
+		};
+	};
+
+	/* PMC interface */
+	pci0: pci@ef008000 {
+		#interrupt-cells = <1>;
+		#size-cells = <2>;
+		#address-cells = <3>;
+		compatible = "fsl,mpc8540-pcix", "fsl,mpc8540-pci";
+		device_type = "pci";
+		reg = <0xef008000 0x1000>;
+		clock-frequency = <33333333>;
+		interrupt-map-mask = <0xf800 0x0 0x0 0x7>;
+		interrupt-map = <
+				/* IDSEL */
+				 0xe000 0 0 1 &mpic 2 1
+				 0xe000 0 0 2 &mpic 3 1>;
+
+		interrupt-parent = <&mpic>;
+		interrupts = <24 2>;
+		bus-range = <0 0>;
+		ranges = <0x02000000 0 0x80000000 0x80000000 0 0x20000000
+			  0x01000000 0 0x00000000 0xd0000000 0 0x01000000>;
+	};
+
+	/* XMC PCIe */
+	pci1: pcie@ef00a000 {
+		interrupt-map-mask = <0xf800 0x0 0x0 0x7>;
+		interrupt-map = <
+			/* IDSEL 0x0 */
+			0x00000 0 0 1 &mpic 0 1
+			0x00000 0 0 2 &mpic 1 1
+			0x00000 0 0 3 &mpic 2 1
+			0x00000 0 0 4 &mpic 3 1>;
+
+		interrupt-parent = <&mpic>;
+		interrupts = <26 2>;
+		bus-range = <0 0xff>;
+		ranges = <0x02000000 0 0xa0000000 0xa0000000 0 0x20000000
+			  0x01000000 0 0x00000000 0xd1000000 0 0x01000000>;
+		clock-frequency = <33333333>;
+		#interrupt-cells = <1>;
+		#size-cells = <2>;
+		#address-cells = <3>;
+		reg = <0xef00a000 0x1000>;
+		compatible = "fsl,mpc8548-pcie";
+		device_type = "pci";
+		pcie@0 {
+			reg = <0 0 0 0 0>;
+			#size-cells = <2>;
+			#address-cells = <3>;
+			device_type = "pci";
+			ranges = <0x02000000 0 0xc0000000 0x02000000 0
+			          0xc0000000 0 0x20000000
+				  0x01000000 0 0x00000000 0x01000000 0
+				  0x00000000 0 0x08000000>;
+		};
+	};
+
+	/* Needed for dtbImage boot wrapper compatibility */
+	chosen {
+		linux,stdout-path = &serial0;
+	};
+};
diff --git a/arch/powerpc/boot/dts/xpedite5301.dts b/arch/powerpc/boot/dts/xpedite5301.dts
new file mode 100644
index 0000000..db7faf5
--- /dev/null
+++ b/arch/powerpc/boot/dts/xpedite5301.dts
@@ -0,0 +1,640 @@
+/*
+ * Copyright (C) 2008 Extreme Engineering Solutions, Inc.
+ * Based on MPC8572DS device tree from Freescale Semiconductor, Inc.
+ *
+ * XPedite5301 PMC/XMC module based on MPC8572E
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+
+/dts-v1/;
+/ {
+	model = "xes,xpedite5301";
+	compatible = "xes,xpedite5301", "xes,MPC8572";
+	#address-cells = <2>;
+	#size-cells = <2>;
+	form-factor = "PMC/XMC";
+	boot-bank = <0x0>;	/* 0: Primary flash, 1: Secondary flash */
+
+	aliases {
+		ethernet0 = &enet0;
+		ethernet1 = &enet1;
+		serial0 = &serial0;
+		serial1 = &serial1;
+		pci1 = &pci1;
+		pci2 = &pci2;
+	};
+
+	cpus {
+		#address-cells = <1>;
+		#size-cells = <0>;
+
+		PowerPC,8572@0 {
+			device_type = "cpu";
+			reg = <0x0>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <0x8000>;		// L1, 32K
+			i-cache-size = <0x8000>;		// L1, 32K
+			timebase-frequency = <0>;
+			bus-frequency = <0>;
+			clock-frequency = <0>;
+			next-level-cache = <&L2>;
+		};
+
+		PowerPC,8572@1 {
+			device_type = "cpu";
+			reg = <0x1>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <0x8000>;		// L1, 32K
+			i-cache-size = <0x8000>;		// L1, 32K
+			timebase-frequency = <0>;
+			bus-frequency = <0>;
+			clock-frequency = <0>;
+			next-level-cache = <&L2>;
+		};
+	};
+
+	memory {
+		device_type = "memory";
+		reg = <0x0 0x0 0x0 0x0>;	// Filled in by U-Boot
+	};
+
+	localbus@ef005000 {
+		#address-cells = <2>;
+		#size-cells = <1>;
+		compatible = "fsl,mpc8572-elbc", "fsl,elbc", "simple-bus";
+		reg = <0 0xef005000 0 0x1000>;
+		interrupts = <19 2>;
+		interrupt-parent = <&mpic>;
+		/* Local bus region mappings */
+		ranges = <0 0 0 0xf8000000 0x8000000 /* CS0: Boot flash */
+			  1 0 0 0xf0000000 0x8000000 /* CS1: Alternate flash */
+			  2 0 0 0xef800000 0x40000   /* CS2: NAND CE1 */
+			  3 0 0 0xef840000 0x40000>; /* CS3: NAND CE2 */
+
+		nor-boot@0,0 {
+			compatible = "amd,s29gl01gp", "cfi-flash";
+			bank-width = <2>;
+			reg = <0 0 0x8000000>; /* 128MB */
+			#address-cells = <1>;
+			#size-cells = <1>;
+			partition@0 {
+				label = "Primary user space";
+				reg = <0x00000000 0x6f00000>; /* 111 MB */
+			};
+			partition@6f00000 {
+				label = "Primary kernel";
+				reg = <0x6f00000 0x1000000>; /* 16 MB */
+			};
+			partition@7f00000 {
+				label = "Primary DTB";
+				reg = <0x7f00000 0x40000>; /* 256 KB */
+			};
+			partition@7f40000 {
+				label = "Primary U-Boot environment";
+				reg = <0x7f40000 0x40000>; /* 256 KB */
+			};
+			partition@7f80000 {
+				label = "Primary U-Boot";
+				reg = <0x7f80000 0x80000>; /* 512 KB */
+				read-only;
+			};
+		};
+
+		nor-alternate@1,0 {
+			compatible = "amd,s29gl01gp", "cfi-flash";
+			bank-width = <2>;
+			//reg = <0xf0000000 0x08000000>; /* 128MB */
+			reg = <1 0 0x8000000>; /* 128MB */
+			#address-cells = <1>;
+			#size-cells = <1>;
+			partition@0 {
+				label = "Secondary user space";
+				reg = <0x00000000 0x6f00000>; /* 111 MB */
+			};
+			partition@6f00000 {
+				label = "Secondary kernel";
+				reg = <0x6f00000 0x1000000>; /* 16 MB */
+			};
+			partition@7f00000 {
+				label = "Secondary DTB";
+				reg = <0x7f00000 0x40000>; /* 256 KB */
+			};
+			partition@7f40000 {
+				label = "Secondary U-Boot environment";
+				reg = <0x7f40000 0x40000>; /* 256 KB */
+			};
+			partition@7f80000 {
+				label = "Secondary U-Boot";
+				reg = <0x7f80000 0x80000>; /* 512 KB */
+				read-only;
+			};
+		};
+
+		nand@2,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			/*
+			 * Actual part could be ST Micro NAND08GW3B2A (1 GB),
+			 * Micron MT29F8G08DAA (2x 512 MB), or Micron
+			 * MT29F16G08FAA (2x 1 GB), depending on the build
+			 * configuration
+			 */
+			compatible = "fsl,mpc8572-fcm-nand",
+				     "fsl,elbc-fcm-nand";
+			reg = <2 0 0x40000>;
+			/* U-Boot should fix this up if chip size > 1 GB */
+			partition@0 {
+				label = "NAND Filesystem";
+				reg = <0 0x40000000>;
+			};
+		};
+
+	};
+
+	soc8572@ef000000 {
+		#address-cells = <1>;
+		#size-cells = <1>;
+		device_type = "soc";
+		compatible = "fsl,mpc8572-immr", "simple-bus";
+		ranges = <0x0 0 0xef000000 0x100000>;
+		bus-frequency = <0>;		// Filled out by uboot.
+
+		ecm-law@0 {
+			compatible = "fsl,ecm-law";
+			reg = <0x0 0x1000>;
+			fsl,num-laws = <12>;
+		};
+
+		ecm@1000 {
+			compatible = "fsl,mpc8572-ecm", "fsl,ecm";
+			reg = <0x1000 0x1000>;
+			interrupts = <17 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		memory-controller@2000 {
+			compatible = "fsl,mpc8572-memory-controller";
+			reg = <0x2000 0x1000>;
+			interrupt-parent = <&mpic>;
+			interrupts = <18 2>;
+		};
+
+		memory-controller@6000 {
+			compatible = "fsl,mpc8572-memory-controller";
+			reg = <0x6000 0x1000>;
+			interrupt-parent = <&mpic>;
+			interrupts = <18 2>;
+		};
+
+		L2: l2-cache-controller@20000 {
+			compatible = "fsl,mpc8572-l2-cache-controller";
+			reg = <0x20000 0x1000>;
+			cache-line-size = <32>;	// 32 bytes
+			cache-size = <0x100000>; // L2, 1M
+			interrupt-parent = <&mpic>;
+			interrupts = <16 2>;
+		};
+
+		i2c@3000 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <0>;
+			compatible = "fsl-i2c";
+			reg = <0x3000 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+
+			temp-sensor@48 {
+				compatible = "dallas,ds1631", "dallas,ds1621";
+				reg = <0x48>;
+			};
+
+			temp-sensor@4c {
+				compatible = "adi,adt7461";
+				reg = <0x4c>;
+			};
+
+			cpu-supervisor@51 {
+				compatible = "dallas,ds4510";
+				reg = <0x51>;
+			};
+
+			eeprom@54 {
+				compatible = "atmel,at24c128b";
+				reg = <0x54>;
+			};
+
+			rtc@68 {
+				compatible = "stm,m41t00",
+				             "dallas,ds1338";
+				reg = <0x68>;
+			};
+
+			pcie-switch@70 {
+				compatible = "plx,pex8518";
+				reg = <0x70>;
+			};
+
+			gpio1: gpio@18 {
+				compatible = "nxp,pca9557";
+				reg = <0x18>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			gpio2: gpio@1c {
+				compatible = "nxp,pca9557";
+				reg = <0x1c>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			gpio3: gpio@1e {
+				compatible = "nxp,pca9557";
+				reg = <0x1e>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			gpio4: gpio@1f {
+				compatible = "nxp,pca9557";
+				reg = <0x1f>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+		};
+
+		i2c@3100 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <1>;
+			compatible = "fsl-i2c";
+			reg = <0x3100 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+		};
+
+		dma@c300 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,mpc8572-dma", "fsl,eloplus-dma";
+			reg = <0xc300 0x4>;
+			ranges = <0x0 0xc100 0x200>;
+			cell-index = <1>;
+			dma-channel@0 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x0 0x80>;
+				cell-index = <0>;
+				interrupt-parent = <&mpic>;
+				interrupts = <76 2>;
+			};
+			dma-channel@80 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x80 0x80>;
+				cell-index = <1>;
+				interrupt-parent = <&mpic>;
+				interrupts = <77 2>;
+			};
+			dma-channel@100 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x100 0x80>;
+				cell-index = <2>;
+				interrupt-parent = <&mpic>;
+				interrupts = <78 2>;
+			};
+			dma-channel@180 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x180 0x80>;
+				cell-index = <3>;
+				interrupt-parent = <&mpic>;
+				interrupts = <79 2>;
+			};
+		};
+
+		dma@21300 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,mpc8572-dma", "fsl,eloplus-dma";
+			reg = <0x21300 0x4>;
+			ranges = <0x0 0x21100 0x200>;
+			cell-index = <0>;
+			dma-channel@0 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x0 0x80>;
+				cell-index = <0>;
+				interrupt-parent = <&mpic>;
+				interrupts = <20 2>;
+			};
+			dma-channel@80 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x80 0x80>;
+				cell-index = <1>;
+				interrupt-parent = <&mpic>;
+				interrupts = <21 2>;
+			};
+			dma-channel@100 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x100 0x80>;
+				cell-index = <2>;
+				interrupt-parent = <&mpic>;
+				interrupts = <22 2>;
+			};
+			dma-channel@180 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x180 0x80>;
+				cell-index = <3>;
+				interrupt-parent = <&mpic>;
+				interrupts = <23 2>;
+			};
+		};
+
+		/* eTSEC 1 */
+		enet0: ethernet@24000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <0>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x24000 0x1000>;
+			ranges = <0x0 0x24000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <29 2 30 2 34 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi0>;
+			phy-handle = <&phy0>;
+			phy-connection-type = "sgmii";
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-mdio";
+				reg = <0x520 0x20>;
+
+				phy0: ethernet-phy@1 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x1>;
+				};
+				phy1: ethernet-phy@2 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x2>;
+				};
+				tbi0: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC 2 */
+		enet1: ethernet@25000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <1>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x25000 0x1000>;
+			ranges = <0x0 0x25000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <35 2 36 2 40 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi1>;
+			phy-handle = <&phy1>;
+			phy-connection-type = "sgmii";
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi1: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* UART0 */
+		serial0: serial@4500 {
+			cell-index = <0>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4500 0x100>;
+			clock-frequency = <0>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		/* UART1 */
+		serial1: serial@4600 {
+			cell-index = <1>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4600 0x100>;
+			clock-frequency = <0>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		global-utilities@e0000 {	//global utilities block
+			compatible = "fsl,mpc8572-guts";
+			reg = <0xe0000 0x1000>;
+			fsl,has-rstcr;
+		};
+
+		msi@41600 {
+			compatible = "fsl,mpc8572-msi", "fsl,mpic-msi";
+			reg = <0x41600 0x80>;
+			msi-available-ranges = <0 0x100>;
+			interrupts = <
+				0xe0 0
+				0xe1 0
+				0xe2 0
+				0xe3 0
+				0xe4 0
+				0xe5 0
+				0xe6 0
+				0xe7 0>;
+			interrupt-parent = <&mpic>;
+		};
+
+		crypto@30000 {
+			compatible = "fsl,sec3.0", "fsl,sec2.4", "fsl,sec2.2",
+				     "fsl,sec2.1", "fsl,sec2.0";
+			reg = <0x30000 0x10000>;
+			interrupts = <45 2 58 2>;
+			interrupt-parent = <&mpic>;
+			fsl,num-channels = <4>;
+			fsl,channel-fifo-len = <24>;
+			fsl,exec-units-mask = <0x9fe>;
+			fsl,descriptor-types-mask = <0x3ab0ebf>;
+		};
+
+		mpic: pic@40000 {
+			interrupt-controller;
+			#address-cells = <0>;
+			#interrupt-cells = <2>;
+			reg = <0x40000 0x40000>;
+			compatible = "chrp,open-pic";
+			device_type = "open-pic";
+		};
+
+		gpio0: gpio@f000 {
+			compatible = "fsl,mpc8572-gpio";
+			reg = <0xf000 0x1000>;
+			interrupts = <47 2>;
+			interrupt-parent = <&mpic>;
+			#gpio-cells = <2>;
+			gpio-controller;
+		};
+
+		gpio-leds {
+			compatible = "gpio-leds";
+
+			heartbeat {
+				label = "Heartbeat";
+				gpios = <&gpio0 4 1>;
+				linux,default-trigger = "heartbeat";
+			};
+
+			yellow {
+				label = "Yellow";
+				gpios = <&gpio0 5 1>;
+			};
+
+			red {
+				label = "Red";
+				gpios = <&gpio0 6 1>;
+			};
+
+			green {
+				label = "Green";
+				gpios = <&gpio0 7 1>;
+			};
+		};
+
+		/* PME (pattern-matcher) */
+		pme@10000 {
+			compatible = "fsl,mpc8572-pme", "pme8572";
+			reg = <0x10000 0x5000>;
+			interrupts = <57 2 64 2 65 2 66 2 67 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		tlu@2f000 {
+			compatible = "fsl,mpc8572-tlu", "fsl_tlu";
+			reg = <0x2f000 0x1000>;
+			interupts = <61 2 >;
+			interrupt-parent = <&mpic>;
+		};
+
+		tlu@15000 {
+			compatible = "fsl,mpc8572-tlu", "fsl_tlu";
+			reg = <0x15000 0x1000>;
+			interupts = <75 2>;
+			interrupt-parent = <&mpic>;
+		};
+	};
+
+	/*
+	 * PCI Express controller 3 @ ef008000 is not used.
+	 * This would have been pci0 on other mpc85xx platforms.
+	 */
+
+	/* PCI Express controller 2, wired to XMC P15 connector */
+	pci1: pcie@ef009000 {
+		compatible = "fsl,mpc8548-pcie";
+		device_type = "pci";
+		#interrupt-cells = <1>;
+		#size-cells = <2>;
+		#address-cells = <3>;
+		reg = <0 0xef009000 0 0x1000>;
+		bus-range = <0 255>;
+		ranges = <0x2000000 0x0 0xc0000000 0 0xc0000000 0x0 0x10000000
+			  0x1000000 0x0 0x00000000 0 0xe8800000 0x0 0x00010000>;
+		clock-frequency = <33333333>;
+		interrupt-parent = <&mpic>;
+		interrupts = <25 2>;
+		interrupt-map-mask = <0xf800 0x0 0x0 0x7>;
+		interrupt-map = <
+			/* IDSEL 0x0 */
+			0x0 0x0 0x0 0x1 &mpic 0x4 0x1
+			0x0 0x0 0x0 0x2 &mpic 0x5 0x1
+			0x0 0x0 0x0 0x3 &mpic 0x6 0x1
+			0x0 0x0 0x0 0x4 &mpic 0x7 0x1
+			>;
+		pcie@0 {
+			reg = <0x00000000 0x00000000 0x00000000 0x00000000 0x00000000>;
+			#size-cells = <2>;
+			#address-cells = <3>;
+			device_type = "pci";
+			ranges = <0x2000000 0x0 0xc0000000
+				  0x2000000 0x0 0xc0000000
+				  0x0 0x10000000
+
+				  0x1000000 0x0 0x0
+				  0x1000000 0x0 0x0
+				  0x0 0x100000>;
+		};
+	};
+
+	/* PCI Express controller 1, wired to PEX8112 for PMC interface */
+	pci2: pcie@ef00a000 {
+		compatible = "fsl,mpc8548-pcie";
+		device_type = "pci";
+		#interrupt-cells = <1>;
+		#size-cells = <2>;
+		#address-cells = <3>;
+		reg = <0 0xef00a000 0 0x1000>;
+		bus-range = <0 255>;
+		ranges = <0x2000000 0x0 0x80000000 0 0x80000000 0x0 0x40000000
+			  0x1000000 0x0 0x00000000 0 0xe8000000 0x0 0x10000>;
+		clock-frequency = <33333333>;
+		interrupt-parent = <&mpic>;
+		interrupts = <26 2>;
+		interrupt-map-mask = <0xf800 0x0 0x0 0x7>;
+		interrupt-map = <
+			/* IDSEL 0x0 */
+			0x0 0x0 0x0 0x1 &mpic 0x0 0x1
+			0x0 0x0 0x0 0x2 &mpic 0x1 0x1
+			0x0 0x0 0x0 0x3 &mpic 0x2 0x1
+			0x0 0x0 0x0 0x4 &mpic 0x3 0x1
+			>;
+		pcie@0 {
+			reg = <0x0 0x0 0x0 0x0 0x0>;
+			#size-cells = <2>;
+			#address-cells = <3>;
+			device_type = "pci";
+			ranges = <0x2000000 0x0 0x80000000
+				  0x2000000 0x0 0x80000000
+				  0x0 0x40000000
+
+				  0x1000000 0x0 0x0
+				  0x1000000 0x0 0x0
+				  0x0 0x100000>;
+		};
+	};
+};
diff --git a/arch/powerpc/boot/dts/xpedite5330.dts b/arch/powerpc/boot/dts/xpedite5330.dts
new file mode 100644
index 0000000..c364ca6
--- /dev/null
+++ b/arch/powerpc/boot/dts/xpedite5330.dts
@@ -0,0 +1,707 @@
+/*
+ * Copyright (C) 2008 Extreme Engineering Solutions, Inc.
+ * Based on MPC8572DS device tree from Freescale Semiconductor, Inc.
+ *
+ * XPedite5330 3U CompactPCI module based on MPC8572E
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+
+/dts-v1/;
+/ {
+	model = "xes,xpedite5330";
+	compatible = "xes,xpedite5330", "xes,MPC8572";
+	#address-cells = <2>;
+	#size-cells = <2>;
+	form-factor = "3U CompactPCI";
+	boot-bank = <0x0>;	/* 0: Primary flash, 1: Secondary flash */
+
+	aliases {
+		ethernet0 = &enet0;
+		ethernet1 = &enet1;
+		serial0 = &serial0;
+		serial1 = &serial1;
+		pci0 = &pci0;
+		pci1 = &pci1;
+		pci2 = &pci2;
+	};
+
+	pmcslots {
+		#address-cells = <1>;
+		#size-cells = <0>;
+
+		pmcslot@0 {
+			cell-index = <0>;
+			/*
+			 * boolean properties (true if defined):
+			 *     monarch;
+			 *     module-present;
+			 */
+		};
+	};
+
+	xmcslots {
+		#address-cells = <1>;
+		#size-cells = <0>;
+
+		xmcslot@0 {
+			cell-index = <0>;
+			/*
+			 * boolean properties (true if defined):
+			 *     module-present;
+			 */
+		};
+	};
+
+	cpci {
+		/*
+		 * boolean properties (true if defined):
+		 *     system-controller;
+		 */
+		system-controller;
+	};
+
+	cpus {
+		#address-cells = <1>;
+		#size-cells = <0>;
+
+		PowerPC,8572@0 {
+			device_type = "cpu";
+			reg = <0x0>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <0x8000>;		// L1, 32K
+			i-cache-size = <0x8000>;		// L1, 32K
+			timebase-frequency = <0>;
+			bus-frequency = <0>;
+			clock-frequency = <0>;
+			next-level-cache = <&L2>;
+		};
+
+		PowerPC,8572@1 {
+			device_type = "cpu";
+			reg = <0x1>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <0x8000>;		// L1, 32K
+			i-cache-size = <0x8000>;		// L1, 32K
+			timebase-frequency = <0>;
+			bus-frequency = <0>;
+			clock-frequency = <0>;
+			next-level-cache = <&L2>;
+		};
+	};
+
+	memory {
+		device_type = "memory";
+		reg = <0x0 0x0 0x0 0x0>;	// Filled in by U-Boot
+	};
+
+	localbus@ef005000 {
+		#address-cells = <2>;
+		#size-cells = <1>;
+		compatible = "fsl,mpc8572-elbc", "fsl,elbc", "simple-bus";
+		reg = <0 0xef005000 0 0x1000>;
+		interrupts = <19 2>;
+		interrupt-parent = <&mpic>;
+		/* Local bus region mappings */
+		ranges = <0 0 0 0xf8000000 0x8000000 /* CS0: Boot flash */
+			  1 0 0 0xf0000000 0x8000000 /* CS1: Alternate flash */
+			  2 0 0 0xef800000 0x40000   /* CS2: NAND CE1 */
+			  3 0 0 0xef840000 0x40000>; /* CS3: NAND CE2 */
+
+		nor-boot@0,0 {
+			compatible = "amd,s29gl01gp", "cfi-flash";
+			bank-width = <2>;
+			reg = <0 0 0x8000000>; /* 128MB */
+			#address-cells = <1>;
+			#size-cells = <1>;
+			partition@0 {
+				label = "Primary user space";
+				reg = <0x00000000 0x6f00000>; /* 111 MB */
+			};
+			partition@6f00000 {
+				label = "Primary kernel";
+				reg = <0x6f00000 0x1000000>; /* 16 MB */
+			};
+			partition@7f00000 {
+				label = "Primary DTB";
+				reg = <0x7f00000 0x40000>; /* 256 KB */
+			};
+			partition@7f40000 {
+				label = "Primary U-Boot environment";
+				reg = <0x7f40000 0x40000>; /* 256 KB */
+			};
+			partition@7f80000 {
+				label = "Primary U-Boot";
+				reg = <0x7f80000 0x80000>; /* 512 KB */
+				read-only;
+			};
+		};
+
+		nor-alternate@1,0 {
+			compatible = "amd,s29gl01gp", "cfi-flash";
+			bank-width = <2>;
+			//reg = <0xf0000000 0x08000000>; /* 128MB */
+			reg = <1 0 0x8000000>; /* 128MB */
+			#address-cells = <1>;
+			#size-cells = <1>;
+			partition@0 {
+				label = "Secondary user space";
+				reg = <0x00000000 0x6f00000>; /* 111 MB */
+			};
+			partition@6f00000 {
+				label = "Secondary kernel";
+				reg = <0x6f00000 0x1000000>; /* 16 MB */
+			};
+			partition@7f00000 {
+				label = "Secondary DTB";
+				reg = <0x7f00000 0x40000>; /* 256 KB */
+			};
+			partition@7f40000 {
+				label = "Secondary U-Boot environment";
+				reg = <0x7f40000 0x40000>; /* 256 KB */
+			};
+			partition@7f80000 {
+				label = "Secondary U-Boot";
+				reg = <0x7f80000 0x80000>; /* 512 KB */
+				read-only;
+			};
+		};
+
+		nand@2,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			/*
+			 * Actual part could be ST Micro NAND08GW3B2A (1 GB),
+			 * Micron MT29F8G08DAA (2x 512 MB), or Micron
+			 * MT29F16G08FAA (2x 1 GB), depending on the build
+			 * configuration
+			 */
+			compatible = "fsl,mpc8572-fcm-nand",
+				     "fsl,elbc-fcm-nand";
+			reg = <2 0 0x40000>;
+			/* U-Boot should fix this up if chip size > 1 GB */
+			partition@0 {
+				label = "NAND Filesystem";
+				reg = <0 0x40000000>;
+			};
+		};
+
+	};
+
+	soc8572@ef000000 {
+		#address-cells = <1>;
+		#size-cells = <1>;
+		device_type = "soc";
+		compatible = "fsl,mpc8572-immr", "simple-bus";
+		ranges = <0x0 0 0xef000000 0x100000>;
+		bus-frequency = <0>;		// Filled out by uboot.
+
+		ecm-law@0 {
+			compatible = "fsl,ecm-law";
+			reg = <0x0 0x1000>;
+			fsl,num-laws = <12>;
+		};
+
+		ecm@1000 {
+			compatible = "fsl,mpc8572-ecm", "fsl,ecm";
+			reg = <0x1000 0x1000>;
+			interrupts = <17 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		memory-controller@2000 {
+			compatible = "fsl,mpc8572-memory-controller";
+			reg = <0x2000 0x1000>;
+			interrupt-parent = <&mpic>;
+			interrupts = <18 2>;
+		};
+
+		memory-controller@6000 {
+			compatible = "fsl,mpc8572-memory-controller";
+			reg = <0x6000 0x1000>;
+			interrupt-parent = <&mpic>;
+			interrupts = <18 2>;
+		};
+
+		L2: l2-cache-controller@20000 {
+			compatible = "fsl,mpc8572-l2-cache-controller";
+			reg = <0x20000 0x1000>;
+			cache-line-size = <32>;	// 32 bytes
+			cache-size = <0x100000>; // L2, 1M
+			interrupt-parent = <&mpic>;
+			interrupts = <16 2>;
+		};
+
+		i2c@3000 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <0>;
+			compatible = "fsl-i2c";
+			reg = <0x3000 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+
+			temp-sensor@48 {
+				compatible = "dallas,ds1631", "dallas,ds1621";
+				reg = <0x48>;
+			};
+
+			temp-sensor@4c {
+				compatible = "adi,adt7461";
+				reg = <0x4c>;
+			};
+
+			cpu-supervisor@51 {
+				compatible = "dallas,ds4510";
+				reg = <0x51>;
+			};
+
+			eeprom@54 {
+				compatible = "atmel,at24c128b";
+				reg = <0x54>;
+			};
+
+			rtc@68 {
+				compatible = "stm,m41t00",
+				             "dallas,ds1338";
+				reg = <0x68>;
+			};
+
+			pcie-switch@70 {
+				compatible = "plx,pex8518";
+				reg = <0x70>;
+			};
+
+			gpio1: gpio@18 {
+				compatible = "nxp,pca9557";
+				reg = <0x18>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			gpio2: gpio@1c {
+				compatible = "nxp,pca9557";
+				reg = <0x1c>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			gpio3: gpio@1e {
+				compatible = "nxp,pca9557";
+				reg = <0x1e>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			gpio4: gpio@1f {
+				compatible = "nxp,pca9557";
+				reg = <0x1f>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+		};
+
+		i2c@3100 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <1>;
+			compatible = "fsl-i2c";
+			reg = <0x3100 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+		};
+
+		dma@c300 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,mpc8572-dma", "fsl,eloplus-dma";
+			reg = <0xc300 0x4>;
+			ranges = <0x0 0xc100 0x200>;
+			cell-index = <1>;
+			dma-channel@0 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x0 0x80>;
+				cell-index = <0>;
+				interrupt-parent = <&mpic>;
+				interrupts = <76 2>;
+			};
+			dma-channel@80 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x80 0x80>;
+				cell-index = <1>;
+				interrupt-parent = <&mpic>;
+				interrupts = <77 2>;
+			};
+			dma-channel@100 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x100 0x80>;
+				cell-index = <2>;
+				interrupt-parent = <&mpic>;
+				interrupts = <78 2>;
+			};
+			dma-channel@180 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x180 0x80>;
+				cell-index = <3>;
+				interrupt-parent = <&mpic>;
+				interrupts = <79 2>;
+			};
+		};
+
+		dma@21300 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,mpc8572-dma", "fsl,eloplus-dma";
+			reg = <0x21300 0x4>;
+			ranges = <0x0 0x21100 0x200>;
+			cell-index = <0>;
+			dma-channel@0 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x0 0x80>;
+				cell-index = <0>;
+				interrupt-parent = <&mpic>;
+				interrupts = <20 2>;
+			};
+			dma-channel@80 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x80 0x80>;
+				cell-index = <1>;
+				interrupt-parent = <&mpic>;
+				interrupts = <21 2>;
+			};
+			dma-channel@100 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x100 0x80>;
+				cell-index = <2>;
+				interrupt-parent = <&mpic>;
+				interrupts = <22 2>;
+			};
+			dma-channel@180 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x180 0x80>;
+				cell-index = <3>;
+				interrupt-parent = <&mpic>;
+				interrupts = <23 2>;
+			};
+		};
+
+		/* eTSEC 1 */
+		enet0: ethernet@24000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <0>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x24000 0x1000>;
+			ranges = <0x0 0x24000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <29 2 30 2 34 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi0>;
+			phy-handle = <&phy0>;
+			phy-connection-type = "sgmii";
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-mdio";
+				reg = <0x520 0x20>;
+
+				phy0: ethernet-phy@1 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x1>;
+				};
+				phy1: ethernet-phy@2 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x2>;
+				};
+				tbi0: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC 2 */
+		enet1: ethernet@25000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <1>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x25000 0x1000>;
+			ranges = <0x0 0x25000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <35 2 36 2 40 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi1>;
+			phy-handle = <&phy1>;
+			phy-connection-type = "sgmii";
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi1: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* UART0 */
+		serial0: serial@4500 {
+			cell-index = <0>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4500 0x100>;
+			clock-frequency = <0>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		/* UART1 */
+		serial1: serial@4600 {
+			cell-index = <1>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4600 0x100>;
+			clock-frequency = <0>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		global-utilities@e0000 {	//global utilities block
+			compatible = "fsl,mpc8572-guts";
+			reg = <0xe0000 0x1000>;
+			fsl,has-rstcr;
+		};
+
+		msi@41600 {
+			compatible = "fsl,mpc8572-msi", "fsl,mpic-msi";
+			reg = <0x41600 0x80>;
+			msi-available-ranges = <0 0x100>;
+			interrupts = <
+				0xe0 0
+				0xe1 0
+				0xe2 0
+				0xe3 0
+				0xe4 0
+				0xe5 0
+				0xe6 0
+				0xe7 0>;
+			interrupt-parent = <&mpic>;
+		};
+
+		crypto@30000 {
+			compatible = "fsl,sec3.0", "fsl,sec2.4", "fsl,sec2.2",
+				     "fsl,sec2.1", "fsl,sec2.0";
+			reg = <0x30000 0x10000>;
+			interrupts = <45 2 58 2>;
+			interrupt-parent = <&mpic>;
+			fsl,num-channels = <4>;
+			fsl,channel-fifo-len = <24>;
+			fsl,exec-units-mask = <0x9fe>;
+			fsl,descriptor-types-mask = <0x3ab0ebf>;
+		};
+
+		mpic: pic@40000 {
+			interrupt-controller;
+			#address-cells = <0>;
+			#interrupt-cells = <2>;
+			reg = <0x40000 0x40000>;
+			compatible = "chrp,open-pic";
+			device_type = "open-pic";
+		};
+
+		gpio0: gpio@f000 {
+			compatible = "fsl,mpc8572-gpio";
+			reg = <0xf000 0x1000>;
+			interrupts = <47 2>;
+			interrupt-parent = <&mpic>;
+			#gpio-cells = <2>;
+			gpio-controller;
+		};
+
+		gpio-leds {
+			compatible = "gpio-leds";
+
+			heartbeat {
+				label = "Heartbeat";
+				gpios = <&gpio0 4 1>;
+				linux,default-trigger = "heartbeat";
+			};
+
+			yellow {
+				label = "Yellow";
+				gpios = <&gpio0 5 1>;
+			};
+
+			red {
+				label = "Red";
+				gpios = <&gpio0 6 1>;
+			};
+
+			green {
+				label = "Green";
+				gpios = <&gpio0 7 1>;
+			};
+		};
+
+		/* PME (pattern-matcher) */
+		pme@10000 {
+			compatible = "fsl,mpc8572-pme", "pme8572";
+			reg = <0x10000 0x5000>;
+			interrupts = <57 2 64 2 65 2 66 2 67 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		tlu@2f000 {
+			compatible = "fsl,mpc8572-tlu", "fsl_tlu";
+			reg = <0x2f000 0x1000>;
+			interupts = <61 2 >;
+			interrupt-parent = <&mpic>;
+		};
+
+		tlu@15000 {
+			compatible = "fsl,mpc8572-tlu", "fsl_tlu";
+			reg = <0x15000 0x1000>;
+			interupts = <75 2>;
+			interrupt-parent = <&mpic>;
+		};
+	};
+
+	/* PCI Express controller 3 - CompactPCI bus via PEX8112 bridge */
+	pci0: pcie@ef008000 {
+		compatible = "fsl,mpc8548-pcie";
+		device_type = "pci";
+		#interrupt-cells = <1>;
+		#size-cells = <2>;
+		#address-cells = <3>;
+		reg = <0 0xef008000 0 0x1000>;
+		bus-range = <0 255>;
+		ranges = <0x2000000 0x0 0xe0000000 0 0xe0000000 0x0 0x10000000
+			  0x1000000 0x0 0x00000000 0 0xe9000000 0x0 0x10000>;
+		clock-frequency = <33333333>;
+		interrupt-parent = <&mpic>;
+		interrupts = <24 2>;
+		interrupt-map-mask = <0xff00 0x0 0x0 0x7>;
+		interrupt-map = <
+			0x0 0x0 0x0 0x1 &mpic 0x0 0x1
+			0x0 0x0 0x0 0x2 &mpic 0x1 0x1
+			0x0 0x0 0x0 0x3 &mpic 0x2 0x1
+			0x0 0x0 0x0 0x4 &mpic 0x3 0x1
+			>;
+		pcie@0 {
+			reg = <0x0 0x0 0x0 0x0 0x0>;
+			#size-cells = <2>;
+			#address-cells = <3>;
+			device_type = "pci";
+			ranges = <0x02000000 0x0 0xe0000000
+				  0x02000000 0x0 0xe0000000
+				  0x0 0x10000000
+
+				  0x01000000 0x0 0x0
+				  0x01000000 0x0 0x0
+				  0x0 0x100000>;
+		};
+	};
+
+	/* PCI Express controller 2, PMC module via PEX8112 bridge */
+	pci1: pcie@ef009000 {
+		compatible = "fsl,mpc8548-pcie";
+		device_type = "pci";
+		#interrupt-cells = <1>;
+		#size-cells = <2>;
+		#address-cells = <3>;
+		reg = <0 0xef009000 0 0x1000>;
+		bus-range = <0 255>;
+		ranges = <0x2000000 0x0 0xc0000000 0 0xc0000000 0x0 0x10000000
+			  0x1000000 0x0 0x00000000 0 0xe8800000 0x0 0x10000>;
+		clock-frequency = <33333333>;
+		interrupt-parent = <&mpic>;
+		interrupts = <25 2>;
+		interrupt-map-mask = <0xf800 0x0 0x0 0x7>;
+		interrupt-map = <
+			/* IDSEL 0x0 */
+			0x0 0x0 0x0 0x1 &mpic 0x4 0x1
+			0x0 0x0 0x0 0x2 &mpic 0x5 0x1
+			0x0 0x0 0x0 0x3 &mpic 0x6 0x1
+			0x0 0x0 0x0 0x4 &mpic 0x7 0x1
+			>;
+		pcie@0 {
+			reg = <0x0 0x0 0x0 0x0 0x0>;
+			#size-cells = <2>;
+			#address-cells = <3>;
+			device_type = "pci";
+			ranges = <0x2000000 0x0 0xc0000000
+				  0x2000000 0x0 0xc0000000
+				  0x0 0x10000000
+
+				  0x1000000 0x0 0x0
+				  0x1000000 0x0 0x0
+				  0x0 0x100000>;
+		};
+	};
+
+	/* PCI Express controller 1, XMC P15 */
+	pci2: pcie@ef00a000 {
+		compatible = "fsl,mpc8548-pcie";
+		device_type = "pci";
+		#interrupt-cells = <1>;
+		#size-cells = <2>;
+		#address-cells = <3>;
+		reg = <0 0xef00a000 0 0x1000>;
+		bus-range = <0 255>;
+		ranges = <0x2000000 0x0 0x80000000 0 0x80000000 0x0 0x40000000
+			  0x1000000 0x0 0x00000000 0 0xe8000000 0x0 0x10000>;
+		clock-frequency = <33333333>;
+		interrupt-parent = <&mpic>;
+		interrupts = <26 2>;
+		interrupt-map-mask = <0xf800 0x0 0x0 0x7>;
+		interrupt-map = <
+			/* IDSEL 0x0 */
+			0x0 0x0 0x0 0x1 &mpic 0x0 0x1
+			0x0 0x0 0x0 0x2 &mpic 0x1 0x1
+			0x0 0x0 0x0 0x3 &mpic 0x2 0x1
+			0x0 0x0 0x0 0x4 &mpic 0x3 0x1
+			>;
+		pcie@0 {
+			reg = <0x0 0x0 0x0 0x0 0x0>;
+			#size-cells = <2>;
+			#address-cells = <3>;
+			device_type = "pci";
+			ranges = <0x2000000 0x0 0x80000000
+				  0x2000000 0x0 0x80000000
+				  0x0 0x40000000
+
+				  0x1000000 0x0 0x0
+				  0x1000000 0x0 0x0
+				  0x0 0x100000>;
+		};
+	};
+};
diff --git a/arch/powerpc/boot/dts/xpedite5370.dts b/arch/powerpc/boot/dts/xpedite5370.dts
new file mode 100644
index 0000000..7a8a4afd
--- /dev/null
+++ b/arch/powerpc/boot/dts/xpedite5370.dts
@@ -0,0 +1,638 @@
+/*
+ * Copyright (C) 2008 Extreme Engineering Solutions, Inc.
+ * Based on MPC8572DS device tree from Freescale Semiconductor, Inc.
+ *
+ * XPedite5370 3U VPX single-board computer based on MPC8572E
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+
+/dts-v1/;
+/ {
+	model = "xes,xpedite5370";
+	compatible = "xes,xpedite5370", "xes,MPC8572";
+	#address-cells = <2>;
+	#size-cells = <2>;
+
+	aliases {
+		ethernet0 = &enet0;
+		ethernet1 = &enet1;
+		serial0 = &serial0;
+		serial1 = &serial1;
+		pci1 = &pci1;
+		pci2 = &pci2;
+	};
+
+	cpus {
+		#address-cells = <1>;
+		#size-cells = <0>;
+
+		PowerPC,8572@0 {
+			device_type = "cpu";
+			reg = <0x0>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <0x8000>;		// L1, 32K
+			i-cache-size = <0x8000>;		// L1, 32K
+			timebase-frequency = <0>;
+			bus-frequency = <0>;
+			clock-frequency = <0>;
+			next-level-cache = <&L2>;
+		};
+
+		PowerPC,8572@1 {
+			device_type = "cpu";
+			reg = <0x1>;
+			d-cache-line-size = <32>;	// 32 bytes
+			i-cache-line-size = <32>;	// 32 bytes
+			d-cache-size = <0x8000>;		// L1, 32K
+			i-cache-size = <0x8000>;		// L1, 32K
+			timebase-frequency = <0>;
+			bus-frequency = <0>;
+			clock-frequency = <0>;
+			next-level-cache = <&L2>;
+		};
+	};
+
+	memory {
+		device_type = "memory";
+		reg = <0x0 0x0 0x0 0x0>;	// Filled in by U-Boot
+	};
+
+	localbus@ef005000 {
+		#address-cells = <2>;
+		#size-cells = <1>;
+		compatible = "fsl,mpc8572-elbc", "fsl,elbc", "simple-bus";
+		reg = <0 0xef005000 0 0x1000>;
+		interrupts = <19 2>;
+		interrupt-parent = <&mpic>;
+		/* Local bus region mappings */
+		ranges = <0 0 0 0xf8000000 0x8000000 /* CS0: Boot flash */
+			  1 0 0 0xf0000000 0x8000000 /* CS1: Alternate flash */
+			  2 0 0 0xef800000 0x40000   /* CS2: NAND CE1 */
+			  3 0 0 0xef840000 0x40000>; /* CS3: NAND CE2 */
+
+		nor-boot@0,0 {
+			compatible = "amd,s29gl01gp", "cfi-flash";
+			bank-width = <2>;
+			reg = <0 0 0x8000000>; /* 128MB */
+			#address-cells = <1>;
+			#size-cells = <1>;
+			partition@0 {
+				label = "Primary user space";
+				reg = <0x00000000 0x6f00000>; /* 111 MB */
+			};
+			partition@6f00000 {
+				label = "Primary kernel";
+				reg = <0x6f00000 0x1000000>; /* 16 MB */
+			};
+			partition@7f00000 {
+				label = "Primary DTB";
+				reg = <0x7f00000 0x40000>; /* 256 KB */
+			};
+			partition@7f40000 {
+				label = "Primary U-Boot environment";
+				reg = <0x7f40000 0x40000>; /* 256 KB */
+			};
+			partition@7f80000 {
+				label = "Primary U-Boot";
+				reg = <0x7f80000 0x80000>; /* 512 KB */
+				read-only;
+			};
+		};
+
+		nor-alternate@1,0 {
+			compatible = "amd,s29gl01gp", "cfi-flash";
+			bank-width = <2>;
+			//reg = <0xf0000000 0x08000000>; /* 128MB */
+			reg = <1 0 0x8000000>; /* 128MB */
+			#address-cells = <1>;
+			#size-cells = <1>;
+			partition@0 {
+				label = "Secondary user space";
+				reg = <0x00000000 0x6f00000>; /* 111 MB */
+			};
+			partition@6f00000 {
+				label = "Secondary kernel";
+				reg = <0x6f00000 0x1000000>; /* 16 MB */
+			};
+			partition@7f00000 {
+				label = "Secondary DTB";
+				reg = <0x7f00000 0x40000>; /* 256 KB */
+			};
+			partition@7f40000 {
+				label = "Secondary U-Boot environment";
+				reg = <0x7f40000 0x40000>; /* 256 KB */
+			};
+			partition@7f80000 {
+				label = "Secondary U-Boot";
+				reg = <0x7f80000 0x80000>; /* 512 KB */
+				read-only;
+			};
+		};
+
+		nand@2,0 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			/*
+			 * Actual part could be ST Micro NAND08GW3B2A (1 GB),
+			 * Micron MT29F8G08DAA (2x 512 MB), or Micron
+			 * MT29F16G08FAA (2x 1 GB), depending on the build
+			 * configuration
+			 */
+			compatible = "fsl,mpc8572-fcm-nand",
+				     "fsl,elbc-fcm-nand";
+			reg = <2 0 0x40000>;
+			/* U-Boot should fix this up if chip size > 1 GB */
+			partition@0 {
+				label = "NAND Filesystem";
+				reg = <0 0x40000000>;
+			};
+		};
+
+	};
+
+	soc8572@ef000000 {
+		#address-cells = <1>;
+		#size-cells = <1>;
+		device_type = "soc";
+		compatible = "fsl,mpc8572-immr", "simple-bus";
+		ranges = <0x0 0 0xef000000 0x100000>;
+		bus-frequency = <0>;		// Filled out by uboot.
+
+		ecm-law@0 {
+			compatible = "fsl,ecm-law";
+			reg = <0x0 0x1000>;
+			fsl,num-laws = <12>;
+		};
+
+		ecm@1000 {
+			compatible = "fsl,mpc8572-ecm", "fsl,ecm";
+			reg = <0x1000 0x1000>;
+			interrupts = <17 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		memory-controller@2000 {
+			compatible = "fsl,mpc8572-memory-controller";
+			reg = <0x2000 0x1000>;
+			interrupt-parent = <&mpic>;
+			interrupts = <18 2>;
+		};
+
+		memory-controller@6000 {
+			compatible = "fsl,mpc8572-memory-controller";
+			reg = <0x6000 0x1000>;
+			interrupt-parent = <&mpic>;
+			interrupts = <18 2>;
+		};
+
+		L2: l2-cache-controller@20000 {
+			compatible = "fsl,mpc8572-l2-cache-controller";
+			reg = <0x20000 0x1000>;
+			cache-line-size = <32>;	// 32 bytes
+			cache-size = <0x100000>; // L2, 1M
+			interrupt-parent = <&mpic>;
+			interrupts = <16 2>;
+		};
+
+		i2c@3000 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <0>;
+			compatible = "fsl-i2c";
+			reg = <0x3000 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+
+			temp-sensor@48 {
+				compatible = "dallas,ds1631", "dallas,ds1621";
+				reg = <0x48>;
+			};
+
+			temp-sensor@4c {
+				compatible = "adi,adt7461";
+				reg = <0x4c>;
+			};
+
+			cpu-supervisor@51 {
+				compatible = "dallas,ds4510";
+				reg = <0x51>;
+			};
+
+			eeprom@54 {
+				compatible = "atmel,at24c128b";
+				reg = <0x54>;
+			};
+
+			rtc@68 {
+				compatible = "stm,m41t00",
+				             "dallas,ds1338";
+				reg = <0x68>;
+			};
+
+			pcie-switch@70 {
+				compatible = "plx,pex8518";
+				reg = <0x70>;
+			};
+
+			gpio1: gpio@18 {
+				compatible = "nxp,pca9557";
+				reg = <0x18>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			gpio2: gpio@1c {
+				compatible = "nxp,pca9557";
+				reg = <0x1c>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			gpio3: gpio@1e {
+				compatible = "nxp,pca9557";
+				reg = <0x1e>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+
+			gpio4: gpio@1f {
+				compatible = "nxp,pca9557";
+				reg = <0x1f>;
+				#gpio-cells = <2>;
+				gpio-controller;
+				polarity = <0x00>;
+			};
+		};
+
+		i2c@3100 {
+			#address-cells = <1>;
+			#size-cells = <0>;
+			cell-index = <1>;
+			compatible = "fsl-i2c";
+			reg = <0x3100 0x100>;
+			interrupts = <43 2>;
+			interrupt-parent = <&mpic>;
+			dfsrr;
+		};
+
+		dma@c300 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,mpc8572-dma", "fsl,eloplus-dma";
+			reg = <0xc300 0x4>;
+			ranges = <0x0 0xc100 0x200>;
+			cell-index = <1>;
+			dma-channel@0 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x0 0x80>;
+				cell-index = <0>;
+				interrupt-parent = <&mpic>;
+				interrupts = <76 2>;
+			};
+			dma-channel@80 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x80 0x80>;
+				cell-index = <1>;
+				interrupt-parent = <&mpic>;
+				interrupts = <77 2>;
+			};
+			dma-channel@100 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x100 0x80>;
+				cell-index = <2>;
+				interrupt-parent = <&mpic>;
+				interrupts = <78 2>;
+			};
+			dma-channel@180 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x180 0x80>;
+				cell-index = <3>;
+				interrupt-parent = <&mpic>;
+				interrupts = <79 2>;
+			};
+		};
+
+		dma@21300 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			compatible = "fsl,mpc8572-dma", "fsl,eloplus-dma";
+			reg = <0x21300 0x4>;
+			ranges = <0x0 0x21100 0x200>;
+			cell-index = <0>;
+			dma-channel@0 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x0 0x80>;
+				cell-index = <0>;
+				interrupt-parent = <&mpic>;
+				interrupts = <20 2>;
+			};
+			dma-channel@80 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x80 0x80>;
+				cell-index = <1>;
+				interrupt-parent = <&mpic>;
+				interrupts = <21 2>;
+			};
+			dma-channel@100 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x100 0x80>;
+				cell-index = <2>;
+				interrupt-parent = <&mpic>;
+				interrupts = <22 2>;
+			};
+			dma-channel@180 {
+				compatible = "fsl,mpc8572-dma-channel",
+						"fsl,eloplus-dma-channel";
+				reg = <0x180 0x80>;
+				cell-index = <3>;
+				interrupt-parent = <&mpic>;
+				interrupts = <23 2>;
+			};
+		};
+
+		/* eTSEC 1 */
+		enet0: ethernet@24000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <0>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x24000 0x1000>;
+			ranges = <0x0 0x24000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <29 2 30 2 34 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi0>;
+			phy-handle = <&phy0>;
+			phy-connection-type = "sgmii";
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-mdio";
+				reg = <0x520 0x20>;
+
+				phy0: ethernet-phy@1 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x1>;
+				};
+				phy1: ethernet-phy@2 {
+					interrupt-parent = <&mpic>;
+					interrupts = <8 1>;
+					reg = <0x2>;
+				};
+				tbi0: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* eTSEC 2 */
+		enet1: ethernet@25000 {
+			#address-cells = <1>;
+			#size-cells = <1>;
+			cell-index = <1>;
+			device_type = "network";
+			model = "eTSEC";
+			compatible = "gianfar";
+			reg = <0x25000 0x1000>;
+			ranges = <0x0 0x25000 0x1000>;
+			local-mac-address = [ 00 00 00 00 00 00 ];
+			interrupts = <35 2 36 2 40 2>;
+			interrupt-parent = <&mpic>;
+			tbi-handle = <&tbi1>;
+			phy-handle = <&phy1>;
+			phy-connection-type = "sgmii";
+
+			mdio@520 {
+				#address-cells = <1>;
+				#size-cells = <0>;
+				compatible = "fsl,gianfar-tbi";
+				reg = <0x520 0x20>;
+
+				tbi1: tbi-phy@11 {
+					reg = <0x11>;
+					device_type = "tbi-phy";
+				};
+			};
+		};
+
+		/* UART0 */
+		serial0: serial@4500 {
+			cell-index = <0>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4500 0x100>;
+			clock-frequency = <0>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		/* UART1 */
+		serial1: serial@4600 {
+			cell-index = <1>;
+			device_type = "serial";
+			compatible = "ns16550";
+			reg = <0x4600 0x100>;
+			clock-frequency = <0>;
+			interrupts = <42 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		global-utilities@e0000 {	//global utilities block
+			compatible = "fsl,mpc8572-guts";
+			reg = <0xe0000 0x1000>;
+			fsl,has-rstcr;
+		};
+
+		msi@41600 {
+			compatible = "fsl,mpc8572-msi", "fsl,mpic-msi";
+			reg = <0x41600 0x80>;
+			msi-available-ranges = <0 0x100>;
+			interrupts = <
+				0xe0 0
+				0xe1 0
+				0xe2 0
+				0xe3 0
+				0xe4 0
+				0xe5 0
+				0xe6 0
+				0xe7 0>;
+			interrupt-parent = <&mpic>;
+		};
+
+		crypto@30000 {
+			compatible = "fsl,sec3.0", "fsl,sec2.4", "fsl,sec2.2",
+				     "fsl,sec2.1", "fsl,sec2.0";
+			reg = <0x30000 0x10000>;
+			interrupts = <45 2 58 2>;
+			interrupt-parent = <&mpic>;
+			fsl,num-channels = <4>;
+			fsl,channel-fifo-len = <24>;
+			fsl,exec-units-mask = <0x9fe>;
+			fsl,descriptor-types-mask = <0x3ab0ebf>;
+		};
+
+		mpic: pic@40000 {
+			interrupt-controller;
+			#address-cells = <0>;
+			#interrupt-cells = <2>;
+			reg = <0x40000 0x40000>;
+			compatible = "chrp,open-pic";
+			device_type = "open-pic";
+		};
+
+		gpio0: gpio@f000 {
+			compatible = "fsl,mpc8572-gpio";
+			reg = <0xf000 0x1000>;
+			interrupts = <47 2>;
+			interrupt-parent = <&mpic>;
+			#gpio-cells = <2>;
+			gpio-controller;
+		};
+
+		gpio-leds {
+			compatible = "gpio-leds";
+
+			heartbeat {
+				label = "Heartbeat";
+				gpios = <&gpio0 4 1>;
+				linux,default-trigger = "heartbeat";
+			};
+
+			yellow {
+				label = "Yellow";
+				gpios = <&gpio0 5 1>;
+			};
+
+			red {
+				label = "Red";
+				gpios = <&gpio0 6 1>;
+			};
+
+			green {
+				label = "Green";
+				gpios = <&gpio0 7 1>;
+			};
+		};
+
+		/* PME (pattern-matcher) */
+		pme@10000 {
+			compatible = "fsl,mpc8572-pme", "pme8572";
+			reg = <0x10000 0x5000>;
+			interrupts = <57 2 64 2 65 2 66 2 67 2>;
+			interrupt-parent = <&mpic>;
+		};
+
+		tlu@2f000 {
+			compatible = "fsl,mpc8572-tlu", "fsl_tlu";
+			reg = <0x2f000 0x1000>;
+			interupts = <61 2 >;
+			interrupt-parent = <&mpic>;
+		};
+
+		tlu@15000 {
+			compatible = "fsl,mpc8572-tlu", "fsl_tlu";
+			reg = <0x15000 0x1000>;
+			interupts = <75 2>;
+			interrupt-parent = <&mpic>;
+		};
+	};
+
+	/*
+	 * PCI Express controller 3 @ ef008000 is not used.
+	 * This would have been pci0 on other mpc85xx platforms.
+	 */
+
+	/* PCI Express controller 2, wired to VPX P1,P2 backplane */
+	pci1: pcie@ef009000 {
+		compatible = "fsl,mpc8548-pcie";
+		device_type = "pci";
+		#interrupt-cells = <1>;
+		#size-cells = <2>;
+		#address-cells = <3>;
+		reg = <0 0xef009000 0 0x1000>;
+		bus-range = <0 255>;
+		ranges = <0x2000000 0x0 0xc0000000 0 0xc0000000 0x0 0x10000000
+			  0x1000000 0x0 0x00000000 0 0xe8800000 0x0 0x00010000>;
+		clock-frequency = <33333333>;
+		interrupt-parent = <&mpic>;
+		interrupts = <25 2>;
+		interrupt-map-mask = <0xf800 0x0 0x0 0x7>;
+		interrupt-map = <
+			/* IDSEL 0x0 */
+			0x0 0x0 0x0 0x1 &mpic 0x4 0x1
+			0x0 0x0 0x0 0x2 &mpic 0x5 0x1
+			0x0 0x0 0x0 0x3 &mpic 0x6 0x1
+			0x0 0x0 0x0 0x4 &mpic 0x7 0x1
+			>;
+		pcie@0 {
+			reg = <0x00000000 0x00000000 0x00000000 0x00000000 0x00000000>;
+			#size-cells = <2>;
+			#address-cells = <3>;
+			device_type = "pci";
+			ranges = <0x2000000 0x0 0xc0000000
+				  0x2000000 0x0 0xc0000000
+				  0x0 0x10000000
+
+				  0x1000000 0x0 0x0
+				  0x1000000 0x0 0x0
+				  0x0 0x100000>;
+		};
+	};
+
+	/* PCI Express controller 1, wired to PEX8518 PCIe switch */
+	pci2: pcie@ef00a000 {
+		compatible = "fsl,mpc8548-pcie";
+		device_type = "pci";
+		#interrupt-cells = <1>;
+		#size-cells = <2>;
+		#address-cells = <3>;
+		reg = <0 0xef00a000 0 0x1000>;
+		bus-range = <0 255>;
+		ranges = <0x2000000 0x0 0x80000000 0 0x80000000 0x0 0x40000000
+			  0x1000000 0x0 0x00000000 0 0xe8000000 0x0 0x10000>;
+		clock-frequency = <33333333>;
+		interrupt-parent = <&mpic>;
+		interrupts = <26 2>;
+		interrupt-map-mask = <0xf800 0x0 0x0 0x7>;
+		interrupt-map = <
+			/* IDSEL 0x0 */
+			0x0 0x0 0x0 0x1 &mpic 0x0 0x1
+			0x0 0x0 0x0 0x2 &mpic 0x1 0x1
+			0x0 0x0 0x0 0x3 &mpic 0x2 0x1
+			0x0 0x0 0x0 0x4 &mpic 0x3 0x1
+			>;
+		pcie@0 {
+			reg = <0x0 0x0 0x0 0x0 0x0>;
+			#size-cells = <2>;
+			#address-cells = <3>;
+			device_type = "pci";
+			ranges = <0x2000000 0x0 0x80000000
+				  0x2000000 0x0 0x80000000
+				  0x0 0x40000000
+
+				  0x1000000 0x0 0x0
+				  0x1000000 0x0 0x0
+				  0x0 0x100000>;
+		};
+	};
+};
diff --git a/arch/powerpc/boot/wrapper b/arch/powerpc/boot/wrapper
index 3ac75ae..4db487d 100755
--- a/arch/powerpc/boot/wrapper
+++ b/arch/powerpc/boot/wrapper
@@ -225,6 +225,10 @@
     platformo="$object/fixed-head.o $object/redboot-83xx.o"
     binary=y
     ;;
+xpedite52*)
+    link_address='0x1400000'
+    platformo=$object/cuboot-85xx.o
+    ;;
 esac
 
 vmz="$tmpdir/`basename \"$kernel\"`.$ext"
diff --git a/arch/powerpc/configs/83xx/kmeter1_defconfig b/arch/powerpc/configs/83xx/kmeter1_defconfig
new file mode 100644
index 0000000..bf0853f
--- /dev/null
+++ b/arch/powerpc/configs/83xx/kmeter1_defconfig
@@ -0,0 +1,908 @@
+#
+# Automatically generated make config: don't edit
+# Linux kernel version: 2.6.28
+# Fri Apr  3 10:34:33 2009
+#
+# CONFIG_PPC64 is not set
+
+#
+# Processor support
+#
+CONFIG_6xx=y
+# CONFIG_PPC_85xx is not set
+# CONFIG_PPC_8xx is not set
+# CONFIG_40x is not set
+# CONFIG_44x is not set
+# CONFIG_E200 is not set
+CONFIG_PPC_FPU=y
+# CONFIG_FSL_EMB_PERFMON is not set
+# CONFIG_ALTIVEC is not set
+CONFIG_PPC_STD_MMU=y
+CONFIG_PPC_STD_MMU_32=y
+# CONFIG_PPC_MM_SLICES is not set
+# CONFIG_SMP is not set
+CONFIG_PPC32=y
+CONFIG_WORD_SIZE=32
+# CONFIG_ARCH_PHYS_ADDR_T_64BIT is not set
+CONFIG_MMU=y
+CONFIG_GENERIC_CMOS_UPDATE=y
+CONFIG_GENERIC_TIME=y
+CONFIG_GENERIC_TIME_VSYSCALL=y
+CONFIG_GENERIC_CLOCKEVENTS=y
+CONFIG_GENERIC_HARDIRQS=y
+# CONFIG_HAVE_SETUP_PER_CPU_AREA is not set
+CONFIG_IRQ_PER_CPU=y
+CONFIG_STACKTRACE_SUPPORT=y
+CONFIG_HAVE_LATENCYTOP_SUPPORT=y
+CONFIG_LOCKDEP_SUPPORT=y
+CONFIG_RWSEM_XCHGADD_ALGORITHM=y
+CONFIG_ARCH_HAS_ILOG2_U32=y
+CONFIG_GENERIC_HWEIGHT=y
+CONFIG_GENERIC_CALIBRATE_DELAY=y
+CONFIG_GENERIC_FIND_NEXT_BIT=y
+# CONFIG_ARCH_NO_VIRT_TO_BUS is not set
+CONFIG_PPC=y
+CONFIG_EARLY_PRINTK=y
+CONFIG_GENERIC_NVRAM=y
+CONFIG_SCHED_NO_NO_OMIT_FRAME_POINTER=y
+CONFIG_ARCH_MAY_HAVE_PC_FDC=y
+CONFIG_PPC_OF=y
+CONFIG_OF=y
+CONFIG_PPC_UDBG_16550=y
+# CONFIG_GENERIC_TBSYNC is not set
+CONFIG_AUDIT_ARCH=y
+CONFIG_GENERIC_BUG=y
+CONFIG_DEFAULT_UIMAGE=y
+CONFIG_ARCH_SUSPEND_POSSIBLE=y
+# CONFIG_PPC_DCR_NATIVE is not set
+# CONFIG_PPC_DCR_MMIO is not set
+CONFIG_DEFCONFIG_LIST="/lib/modules/$UNAME_RELEASE/.config"
+
+#
+# General setup
+#
+CONFIG_EXPERIMENTAL=y
+CONFIG_BROKEN_ON_SMP=y
+CONFIG_LOCK_KERNEL=y
+CONFIG_INIT_ENV_ARG_LIMIT=32
+CONFIG_LOCALVERSION=""
+CONFIG_LOCALVERSION_AUTO=y
+# CONFIG_SWAP is not set
+CONFIG_SYSVIPC=y
+CONFIG_SYSVIPC_SYSCTL=y
+CONFIG_POSIX_MQUEUE=y
+# CONFIG_BSD_PROCESS_ACCT is not set
+# CONFIG_TASKSTATS is not set
+# CONFIG_AUDIT is not set
+# CONFIG_IKCONFIG is not set
+CONFIG_LOG_BUF_SHIFT=14
+# CONFIG_CGROUPS is not set
+# CONFIG_GROUP_SCHED is not set
+# CONFIG_SYSFS_DEPRECATED_V2 is not set
+# CONFIG_RELAY is not set
+# CONFIG_NAMESPACES is not set
+# CONFIG_BLK_DEV_INITRD is not set
+CONFIG_CC_OPTIMIZE_FOR_SIZE=y
+CONFIG_SYSCTL=y
+CONFIG_EMBEDDED=y
+CONFIG_SYSCTL_SYSCALL=y
+CONFIG_KALLSYMS=y
+CONFIG_KALLSYMS_ALL=y
+# CONFIG_KALLSYMS_EXTRA_PASS is not set
+# CONFIG_HOTPLUG is not set
+CONFIG_PRINTK=y
+CONFIG_BUG=y
+CONFIG_ELF_CORE=y
+CONFIG_COMPAT_BRK=y
+CONFIG_BASE_FULL=y
+CONFIG_FUTEX=y
+CONFIG_ANON_INODES=y
+CONFIG_EPOLL=y
+CONFIG_SIGNALFD=y
+CONFIG_TIMERFD=y
+CONFIG_EVENTFD=y
+CONFIG_SHMEM=y
+CONFIG_AIO=y
+CONFIG_VM_EVENT_COUNTERS=y
+CONFIG_SLAB=y
+# CONFIG_SLUB is not set
+# CONFIG_SLOB is not set
+# CONFIG_PROFILING is not set
+# CONFIG_MARKERS is not set
+CONFIG_HAVE_OPROFILE=y
+# CONFIG_KPROBES is not set
+CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS=y
+CONFIG_HAVE_IOREMAP_PROT=y
+CONFIG_HAVE_KPROBES=y
+CONFIG_HAVE_KRETPROBES=y
+CONFIG_HAVE_ARCH_TRACEHOOK=y
+# CONFIG_HAVE_GENERIC_DMA_COHERENT is not set
+CONFIG_SLABINFO=y
+CONFIG_RT_MUTEXES=y
+# CONFIG_TINY_SHMEM is not set
+CONFIG_BASE_SMALL=0
+CONFIG_MODULES=y
+# CONFIG_MODULE_FORCE_LOAD is not set
+CONFIG_MODULE_UNLOAD=y
+# CONFIG_MODULE_FORCE_UNLOAD is not set
+# CONFIG_MODVERSIONS is not set
+# CONFIG_MODULE_SRCVERSION_ALL is not set
+CONFIG_KMOD=y
+CONFIG_BLOCK=y
+# CONFIG_LBD is not set
+# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_LSF is not set
+# CONFIG_BLK_DEV_BSG is not set
+# CONFIG_BLK_DEV_INTEGRITY is not set
+
+#
+# IO Schedulers
+#
+CONFIG_IOSCHED_NOOP=y
+# CONFIG_IOSCHED_AS is not set
+# CONFIG_IOSCHED_DEADLINE is not set
+# CONFIG_IOSCHED_CFQ is not set
+# CONFIG_DEFAULT_AS is not set
+# CONFIG_DEFAULT_DEADLINE is not set
+# CONFIG_DEFAULT_CFQ is not set
+CONFIG_DEFAULT_NOOP=y
+CONFIG_DEFAULT_IOSCHED="noop"
+CONFIG_CLASSIC_RCU=y
+# CONFIG_FREEZER is not set
+
+#
+# Platform support
+#
+CONFIG_PPC_MULTIPLATFORM=y
+CONFIG_CLASSIC32=y
+# CONFIG_PPC_CHRP is not set
+# CONFIG_MPC5121_ADS is not set
+# CONFIG_MPC5121_GENERIC is not set
+# CONFIG_PPC_MPC52xx is not set
+# CONFIG_PPC_PMAC is not set
+# CONFIG_PPC_CELL is not set
+# CONFIG_PPC_CELL_NATIVE is not set
+# CONFIG_PPC_82xx is not set
+# CONFIG_PQ2ADS is not set
+CONFIG_PPC_83xx=y
+# CONFIG_MPC831x_RDB is not set
+# CONFIG_MPC832x_MDS is not set
+# CONFIG_MPC832x_RDB is not set
+# CONFIG_MPC834x_MDS is not set
+# CONFIG_MPC834x_ITX is not set
+# CONFIG_MPC836x_MDS is not set
+# CONFIG_MPC836x_RDK is not set
+# CONFIG_MPC837x_MDS is not set
+# CONFIG_MPC837x_RDB is not set
+# CONFIG_SBC834x is not set
+# CONFIG_ASP834x is not set
+CONFIG_KMETER1=y
+# CONFIG_PPC_86xx is not set
+# CONFIG_EMBEDDED6xx is not set
+CONFIG_IPIC=y
+# CONFIG_MPIC is not set
+# CONFIG_MPIC_WEIRD is not set
+# CONFIG_PPC_I8259 is not set
+# CONFIG_PPC_RTAS is not set
+# CONFIG_MMIO_NVRAM is not set
+# CONFIG_PPC_MPC106 is not set
+# CONFIG_PPC_970_NAP is not set
+# CONFIG_PPC_INDIRECT_IO is not set
+# CONFIG_GENERIC_IOMAP is not set
+# CONFIG_CPU_FREQ is not set
+# CONFIG_TAU is not set
+CONFIG_QUICC_ENGINE=y
+# CONFIG_QE_GPIO is not set
+# CONFIG_FSL_ULI1575 is not set
+
+#
+# Kernel options
+#
+# CONFIG_HIGHMEM is not set
+CONFIG_TICK_ONESHOT=y
+CONFIG_NO_HZ=y
+CONFIG_HIGH_RES_TIMERS=y
+CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
+# CONFIG_HZ_100 is not set
+CONFIG_HZ_250=y
+# CONFIG_HZ_300 is not set
+# CONFIG_HZ_1000 is not set
+CONFIG_HZ=250
+CONFIG_SCHED_HRTICK=y
+# CONFIG_PREEMPT_NONE is not set
+# CONFIG_PREEMPT_VOLUNTARY is not set
+CONFIG_PREEMPT=y
+# CONFIG_PREEMPT_RCU is not set
+CONFIG_BINFMT_ELF=y
+# CONFIG_CORE_DUMP_DEFAULT_ELF_HEADERS is not set
+# CONFIG_HAVE_AOUT is not set
+# CONFIG_BINFMT_MISC is not set
+# CONFIG_IOMMU_HELPER is not set
+CONFIG_ARCH_ENABLE_MEMORY_HOTPLUG=y
+CONFIG_ARCH_HAS_WALK_MEMORY=y
+CONFIG_ARCH_ENABLE_MEMORY_HOTREMOVE=y
+# CONFIG_KEXEC is not set
+CONFIG_ARCH_FLATMEM_ENABLE=y
+CONFIG_ARCH_POPULATES_NODE_MAP=y
+CONFIG_SELECT_MEMORY_MODEL=y
+CONFIG_FLATMEM_MANUAL=y
+# CONFIG_DISCONTIGMEM_MANUAL is not set
+# CONFIG_SPARSEMEM_MANUAL is not set
+CONFIG_FLATMEM=y
+CONFIG_FLAT_NODE_MEM_MAP=y
+CONFIG_PAGEFLAGS_EXTENDED=y
+CONFIG_SPLIT_PTLOCK_CPUS=4
+CONFIG_MIGRATION=y
+# CONFIG_RESOURCES_64BIT is not set
+# CONFIG_PHYS_ADDR_T_64BIT is not set
+CONFIG_ZONE_DMA_FLAG=1
+CONFIG_BOUNCE=y
+CONFIG_VIRT_TO_BUS=y
+CONFIG_UNEVICTABLE_LRU=y
+CONFIG_FORCE_MAX_ZONEORDER=11
+CONFIG_PROC_DEVICETREE=y
+# CONFIG_CMDLINE_BOOL is not set
+CONFIG_EXTRA_TARGETS=""
+# CONFIG_PM is not set
+# CONFIG_SECCOMP is not set
+CONFIG_ISA_DMA_API=y
+
+#
+# Bus options
+#
+CONFIG_ZONE_DMA=y
+CONFIG_GENERIC_ISA_DMA=y
+CONFIG_FSL_SOC=y
+CONFIG_PPC_PCI_CHOICE=y
+# CONFIG_PCI is not set
+# CONFIG_PCI_DOMAINS is not set
+# CONFIG_PCI_SYSCALL is not set
+# CONFIG_ARCH_SUPPORTS_MSI is not set
+# CONFIG_HAS_RAPIDIO is not set
+
+#
+# Advanced setup
+#
+# CONFIG_ADVANCED_OPTIONS is not set
+
+#
+# Default settings for advanced configuration options are used
+#
+CONFIG_LOWMEM_SIZE=0x30000000
+CONFIG_PAGE_OFFSET=0xc0000000
+CONFIG_KERNEL_START=0xc0000000
+CONFIG_PHYSICAL_START=0x00000000
+CONFIG_TASK_SIZE=0xc0000000
+CONFIG_NET=y
+
+#
+# Networking options
+#
+CONFIG_PACKET=y
+# CONFIG_PACKET_MMAP is not set
+CONFIG_UNIX=y
+# CONFIG_NET_KEY is not set
+CONFIG_INET=y
+CONFIG_IP_MULTICAST=y
+# CONFIG_IP_ADVANCED_ROUTER is not set
+CONFIG_IP_FIB_HASH=y
+CONFIG_IP_PNP=y
+# CONFIG_IP_PNP_DHCP is not set
+# CONFIG_IP_PNP_BOOTP is not set
+# CONFIG_IP_PNP_RARP is not set
+# CONFIG_NET_IPIP is not set
+# CONFIG_NET_IPGRE is not set
+# CONFIG_IP_MROUTE is not set
+# CONFIG_ARPD is not set
+# CONFIG_SYN_COOKIES is not set
+# CONFIG_INET_AH is not set
+# CONFIG_INET_ESP is not set
+# CONFIG_INET_IPCOMP is not set
+# CONFIG_INET_XFRM_TUNNEL is not set
+# CONFIG_INET_TUNNEL is not set
+# CONFIG_INET_XFRM_MODE_TRANSPORT is not set
+# CONFIG_INET_XFRM_MODE_TUNNEL is not set
+# CONFIG_INET_XFRM_MODE_BEET is not set
+# CONFIG_INET_LRO is not set
+CONFIG_INET_DIAG=y
+CONFIG_INET_TCP_DIAG=y
+# CONFIG_TCP_CONG_ADVANCED is not set
+CONFIG_TCP_CONG_CUBIC=y
+CONFIG_DEFAULT_TCP_CONG="cubic"
+# CONFIG_TCP_MD5SIG is not set
+# CONFIG_IPV6 is not set
+# CONFIG_NETWORK_SECMARK is not set
+# CONFIG_NETFILTER is not set
+# CONFIG_IP_DCCP is not set
+# CONFIG_IP_SCTP is not set
+# CONFIG_TIPC is not set
+# CONFIG_ATM is not set
+CONFIG_STP=m
+CONFIG_BRIDGE=m
+# CONFIG_NET_DSA is not set
+CONFIG_VLAN_8021Q=y
+# CONFIG_VLAN_8021Q_GVRP is not set
+# CONFIG_DECNET is not set
+CONFIG_LLC=m
+# CONFIG_LLC2 is not set
+# CONFIG_IPX is not set
+# CONFIG_ATALK is not set
+# CONFIG_X25 is not set
+# CONFIG_LAPB is not set
+# CONFIG_ECONET is not set
+# CONFIG_WAN_ROUTER is not set
+# CONFIG_NET_SCHED is not set
+
+#
+# Network testing
+#
+# CONFIG_NET_PKTGEN is not set
+# CONFIG_HAMRADIO is not set
+# CONFIG_CAN is not set
+# CONFIG_IRDA is not set
+# CONFIG_BT is not set
+# CONFIG_AF_RXRPC is not set
+# CONFIG_PHONET is not set
+# CONFIG_WIRELESS is not set
+# CONFIG_RFKILL is not set
+# CONFIG_NET_9P is not set
+
+#
+# Device Drivers
+#
+
+#
+# Generic Driver Options
+#
+CONFIG_STANDALONE=y
+CONFIG_PREVENT_FIRMWARE_BUILD=y
+# CONFIG_SYS_HYPERVISOR is not set
+# CONFIG_CONNECTOR is not set
+CONFIG_MTD=y
+# CONFIG_MTD_DEBUG is not set
+CONFIG_MTD_CONCAT=y
+CONFIG_MTD_PARTITIONS=y
+# CONFIG_MTD_REDBOOT_PARTS is not set
+CONFIG_MTD_CMDLINE_PARTS=y
+CONFIG_MTD_OF_PARTS=y
+# CONFIG_MTD_AR7_PARTS is not set
+
+#
+# User Modules And Translation Layers
+#
+CONFIG_MTD_CHAR=y
+CONFIG_MTD_BLKDEVS=y
+CONFIG_MTD_BLOCK=y
+# CONFIG_FTL is not set
+# CONFIG_NFTL is not set
+# CONFIG_INFTL is not set
+# CONFIG_RFD_FTL is not set
+# CONFIG_SSFDC is not set
+# CONFIG_MTD_OOPS is not set
+
+#
+# RAM/ROM/Flash chip drivers
+#
+CONFIG_MTD_CFI=y
+# CONFIG_MTD_JEDECPROBE is not set
+CONFIG_MTD_GEN_PROBE=y
+# CONFIG_MTD_CFI_ADV_OPTIONS is not set
+CONFIG_MTD_MAP_BANK_WIDTH_1=y
+CONFIG_MTD_MAP_BANK_WIDTH_2=y
+CONFIG_MTD_MAP_BANK_WIDTH_4=y
+# CONFIG_MTD_MAP_BANK_WIDTH_8 is not set
+# CONFIG_MTD_MAP_BANK_WIDTH_16 is not set
+# CONFIG_MTD_MAP_BANK_WIDTH_32 is not set
+CONFIG_MTD_CFI_I1=y
+CONFIG_MTD_CFI_I2=y
+# CONFIG_MTD_CFI_I4 is not set
+# CONFIG_MTD_CFI_I8 is not set
+CONFIG_MTD_CFI_INTELEXT=y
+CONFIG_MTD_CFI_AMDSTD=y
+# CONFIG_MTD_CFI_STAA is not set
+CONFIG_MTD_CFI_UTIL=y
+# CONFIG_MTD_RAM is not set
+# CONFIG_MTD_ROM is not set
+# CONFIG_MTD_ABSENT is not set
+
+#
+# Mapping drivers for chip access
+#
+# CONFIG_MTD_COMPLEX_MAPPINGS is not set
+# CONFIG_MTD_PHYSMAP is not set
+CONFIG_MTD_PHYSMAP_OF=y
+# CONFIG_MTD_PLATRAM is not set
+
+#
+# Self-contained MTD device drivers
+#
+# CONFIG_MTD_SLRAM is not set
+CONFIG_MTD_PHRAM=y
+# CONFIG_MTD_MTDRAM is not set
+# CONFIG_MTD_BLOCK2MTD is not set
+
+#
+# Disk-On-Chip Device Drivers
+#
+# CONFIG_MTD_DOC2000 is not set
+# CONFIG_MTD_DOC2001 is not set
+# CONFIG_MTD_DOC2001PLUS is not set
+# CONFIG_MTD_NAND is not set
+# CONFIG_MTD_ONENAND is not set
+
+#
+# UBI - Unsorted block images
+#
+CONFIG_MTD_UBI=y
+CONFIG_MTD_UBI_WL_THRESHOLD=4096
+CONFIG_MTD_UBI_BEB_RESERVE=1
+CONFIG_MTD_UBI_GLUEBI=y
+
+#
+# UBI debugging options
+#
+CONFIG_MTD_UBI_DEBUG=y
+# CONFIG_MTD_UBI_DEBUG_MSG is not set
+# CONFIG_MTD_UBI_DEBUG_PARANOID is not set
+# CONFIG_MTD_UBI_DEBUG_DISABLE_BGT is not set
+# CONFIG_MTD_UBI_DEBUG_USERSPACE_IO is not set
+# CONFIG_MTD_UBI_DEBUG_EMULATE_BITFLIPS is not set
+# CONFIG_MTD_UBI_DEBUG_EMULATE_WRITE_FAILURES is not set
+# CONFIG_MTD_UBI_DEBUG_EMULATE_ERASE_FAILURES is not set
+
+#
+# Additional UBI debugging messages
+#
+# CONFIG_MTD_UBI_DEBUG_MSG_BLD is not set
+# CONFIG_MTD_UBI_DEBUG_MSG_EBA is not set
+# CONFIG_MTD_UBI_DEBUG_MSG_WL is not set
+# CONFIG_MTD_UBI_DEBUG_MSG_IO is not set
+CONFIG_OF_DEVICE=y
+CONFIG_OF_I2C=y
+# CONFIG_PARPORT is not set
+CONFIG_BLK_DEV=y
+# CONFIG_BLK_DEV_FD is not set
+# CONFIG_BLK_DEV_COW_COMMON is not set
+# CONFIG_BLK_DEV_LOOP is not set
+# CONFIG_BLK_DEV_NBD is not set
+# CONFIG_BLK_DEV_RAM is not set
+# CONFIG_CDROM_PKTCDVD is not set
+# CONFIG_ATA_OVER_ETH is not set
+# CONFIG_BLK_DEV_HD is not set
+# CONFIG_MISC_DEVICES is not set
+CONFIG_HAVE_IDE=y
+# CONFIG_IDE is not set
+
+#
+# SCSI device support
+#
+# CONFIG_RAID_ATTRS is not set
+# CONFIG_SCSI is not set
+# CONFIG_SCSI_DMA is not set
+# CONFIG_SCSI_NETLINK is not set
+# CONFIG_ATA is not set
+# CONFIG_MD is not set
+# CONFIG_MACINTOSH_DRIVERS is not set
+CONFIG_NETDEVICES=y
+CONFIG_DUMMY=y
+# CONFIG_BONDING is not set
+# CONFIG_MACVLAN is not set
+# CONFIG_EQUALIZER is not set
+CONFIG_TUN=y
+# CONFIG_VETH is not set
+CONFIG_PHYLIB=y
+
+#
+# MII PHY device drivers
+#
+CONFIG_MARVELL_PHY=y
+# CONFIG_DAVICOM_PHY is not set
+# CONFIG_QSEMI_PHY is not set
+# CONFIG_LXT_PHY is not set
+# CONFIG_CICADA_PHY is not set
+# CONFIG_VITESSE_PHY is not set
+# CONFIG_SMSC_PHY is not set
+# CONFIG_BROADCOM_PHY is not set
+# CONFIG_ICPLUS_PHY is not set
+# CONFIG_REALTEK_PHY is not set
+# CONFIG_FIXED_PHY is not set
+# CONFIG_MDIO_BITBANG is not set
+CONFIG_NET_ETHERNET=y
+CONFIG_MII=y
+# CONFIG_IBM_NEW_EMAC_ZMII is not set
+# CONFIG_IBM_NEW_EMAC_RGMII is not set
+# CONFIG_IBM_NEW_EMAC_TAH is not set
+# CONFIG_IBM_NEW_EMAC_EMAC4 is not set
+# CONFIG_IBM_NEW_EMAC_NO_FLOW_CTRL is not set
+# CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
+# CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
+# CONFIG_B44 is not set
+CONFIG_NETDEV_1000=y
+# CONFIG_GIANFAR is not set
+CONFIG_UCC_GETH=y
+# CONFIG_UGETH_MAGIC_PACKET is not set
+# CONFIG_UGETH_FILTERING is not set
+# CONFIG_UGETH_TX_ON_DEMAND is not set
+# CONFIG_MV643XX_ETH is not set
+# CONFIG_NETDEV_10000 is not set
+
+#
+# Wireless LAN
+#
+# CONFIG_WLAN_PRE80211 is not set
+# CONFIG_WLAN_80211 is not set
+# CONFIG_IWLWIFI_LEDS is not set
+CONFIG_WAN=y
+CONFIG_HDLC=y
+# CONFIG_HDLC_RAW is not set
+# CONFIG_HDLC_RAW_ETH is not set
+# CONFIG_HDLC_CISCO is not set
+# CONFIG_HDLC_FR is not set
+# CONFIG_HDLC_PPP is not set
+
+#
+# X.25/LAPB support is disabled
+#
+CONFIG_HDLC_KM=y
+CONFIG_FS_UCC_HDLC=y
+# CONFIG_DLCI is not set
+CONFIG_PPP=y
+CONFIG_PPP_MULTILINK=y
+# CONFIG_PPP_FILTER is not set
+# CONFIG_PPP_ASYNC is not set
+# CONFIG_PPP_SYNC_TTY is not set
+# CONFIG_PPP_DEFLATE is not set
+# CONFIG_PPP_BSDCOMP is not set
+# CONFIG_PPP_MPPE is not set
+CONFIG_PPPOE=y
+# CONFIG_PPPOL2TP is not set
+# CONFIG_SLIP is not set
+CONFIG_SLHC=y
+# CONFIG_NETCONSOLE is not set
+# CONFIG_NETPOLL is not set
+# CONFIG_NET_POLL_CONTROLLER is not set
+# CONFIG_ISDN is not set
+# CONFIG_PHONE is not set
+
+#
+# Input device support
+#
+# CONFIG_INPUT is not set
+
+#
+# Hardware I/O ports
+#
+# CONFIG_SERIO is not set
+# CONFIG_GAMEPORT is not set
+
+#
+# Character devices
+#
+# CONFIG_VT is not set
+# CONFIG_DEVKMEM is not set
+# CONFIG_SERIAL_NONSTANDARD is not set
+
+#
+# Serial drivers
+#
+CONFIG_SERIAL_8250=y
+CONFIG_SERIAL_8250_CONSOLE=y
+CONFIG_SERIAL_8250_NR_UARTS=4
+CONFIG_SERIAL_8250_RUNTIME_UARTS=4
+# CONFIG_SERIAL_8250_EXTENDED is not set
+
+#
+# Non-8250 serial port support
+#
+# CONFIG_SERIAL_UARTLITE is not set
+CONFIG_SERIAL_CORE=y
+CONFIG_SERIAL_CORE_CONSOLE=y
+# CONFIG_SERIAL_OF_PLATFORM is not set
+# CONFIG_SERIAL_QE is not set
+CONFIG_UNIX98_PTYS=y
+CONFIG_LEGACY_PTYS=y
+CONFIG_LEGACY_PTY_COUNT=256
+# CONFIG_IPMI_HANDLER is not set
+CONFIG_HW_RANDOM=y
+# CONFIG_NVRAM is not set
+# CONFIG_GEN_RTC is not set
+# CONFIG_R3964 is not set
+# CONFIG_RAW_DRIVER is not set
+# CONFIG_TCG_TPM is not set
+CONFIG_BOOTCOUNT=y
+CONFIG_I2C=y
+CONFIG_I2C_BOARDINFO=y
+CONFIG_I2C_CHARDEV=y
+CONFIG_I2C_HELPER_AUTO=y
+
+#
+# I2C Hardware Bus support
+#
+
+#
+# I2C system bus drivers (mostly embedded / system-on-chip)
+#
+CONFIG_I2C_MPC=y
+# CONFIG_I2C_OCORES is not set
+# CONFIG_I2C_SIMTEC is not set
+
+#
+# External I2C/SMBus adapter drivers
+#
+# CONFIG_I2C_PARPORT_LIGHT is not set
+# CONFIG_I2C_TAOS_EVM is not set
+
+#
+# Other I2C/SMBus bus drivers
+#
+# CONFIG_I2C_PCA_PLATFORM is not set
+# CONFIG_I2C_STUB is not set
+
+#
+# Miscellaneous I2C Chip support
+#
+# CONFIG_DS1682 is not set
+# CONFIG_AT24 is not set
+# CONFIG_SENSORS_EEPROM is not set
+# CONFIG_SENSORS_PCF8574 is not set
+# CONFIG_PCF8575 is not set
+# CONFIG_SENSORS_PCA9539 is not set
+# CONFIG_SENSORS_PCF8591 is not set
+# CONFIG_SENSORS_MAX6875 is not set
+# CONFIG_SENSORS_TSL2550 is not set
+# CONFIG_MCU_MPC8349EMITX is not set
+# CONFIG_I2C_DEBUG_CORE is not set
+# CONFIG_I2C_DEBUG_ALGO is not set
+# CONFIG_I2C_DEBUG_BUS is not set
+# CONFIG_I2C_DEBUG_CHIP is not set
+# CONFIG_SPI is not set
+CONFIG_ARCH_WANT_OPTIONAL_GPIOLIB=y
+# CONFIG_GPIOLIB is not set
+# CONFIG_W1 is not set
+# CONFIG_POWER_SUPPLY is not set
+# CONFIG_HWMON is not set
+# CONFIG_THERMAL is not set
+# CONFIG_THERMAL_HWMON is not set
+# CONFIG_WATCHDOG is not set
+CONFIG_SSB_POSSIBLE=y
+
+#
+# Sonics Silicon Backplane
+#
+# CONFIG_SSB is not set
+
+#
+# Multifunction device drivers
+#
+# CONFIG_MFD_CORE is not set
+# CONFIG_MFD_SM501 is not set
+# CONFIG_HTC_PASIC3 is not set
+# CONFIG_MFD_TMIO is not set
+# CONFIG_PMIC_DA903X is not set
+# CONFIG_MFD_WM8400 is not set
+# CONFIG_MFD_WM8350_I2C is not set
+# CONFIG_REGULATOR is not set
+
+#
+# Multimedia devices
+#
+
+#
+# Multimedia core support
+#
+# CONFIG_VIDEO_DEV is not set
+# CONFIG_DVB_CORE is not set
+# CONFIG_VIDEO_MEDIA is not set
+
+#
+# Multimedia drivers
+#
+# CONFIG_DAB is not set
+
+#
+# Graphics support
+#
+# CONFIG_VGASTATE is not set
+# CONFIG_VIDEO_OUTPUT_CONTROL is not set
+# CONFIG_FB is not set
+# CONFIG_BACKLIGHT_LCD_SUPPORT is not set
+
+#
+# Display device support
+#
+# CONFIG_DISPLAY_SUPPORT is not set
+# CONFIG_SOUND is not set
+# CONFIG_USB_SUPPORT is not set
+# CONFIG_MMC is not set
+# CONFIG_MEMSTICK is not set
+# CONFIG_NEW_LEDS is not set
+# CONFIG_ACCESSIBILITY is not set
+# CONFIG_EDAC is not set
+# CONFIG_RTC_CLASS is not set
+# CONFIG_DMADEVICES is not set
+CONFIG_UIO=y
+# CONFIG_UIO_PDRV is not set
+# CONFIG_UIO_PDRV_GENIRQ is not set
+# CONFIG_UIO_SMX is not set
+# CONFIG_UIO_SERCOS3 is not set
+# CONFIG_STAGING is not set
+
+#
+# File systems
+#
+# CONFIG_EXT2_FS is not set
+# CONFIG_EXT3_FS is not set
+# CONFIG_EXT4_FS is not set
+# CONFIG_REISERFS_FS is not set
+# CONFIG_JFS_FS is not set
+# CONFIG_FS_POSIX_ACL is not set
+CONFIG_FILE_LOCKING=y
+# CONFIG_XFS_FS is not set
+# CONFIG_OCFS2_FS is not set
+# CONFIG_DNOTIFY is not set
+CONFIG_INOTIFY=y
+CONFIG_INOTIFY_USER=y
+# CONFIG_QUOTA is not set
+# CONFIG_AUTOFS_FS is not set
+# CONFIG_AUTOFS4_FS is not set
+# CONFIG_FUSE_FS is not set
+
+#
+# CD-ROM/DVD Filesystems
+#
+# CONFIG_ISO9660_FS is not set
+# CONFIG_UDF_FS is not set
+
+#
+# DOS/FAT/NT Filesystems
+#
+# CONFIG_MSDOS_FS is not set
+# CONFIG_VFAT_FS is not set
+# CONFIG_NTFS_FS is not set
+
+#
+# Pseudo filesystems
+#
+CONFIG_PROC_FS=y
+# CONFIG_PROC_KCORE is not set
+CONFIG_PROC_SYSCTL=y
+CONFIG_PROC_PAGE_MONITOR=y
+CONFIG_SYSFS=y
+CONFIG_TMPFS=y
+# CONFIG_TMPFS_POSIX_ACL is not set
+# CONFIG_HUGETLB_PAGE is not set
+# CONFIG_CONFIGFS_FS is not set
+
+#
+# Miscellaneous filesystems
+#
+# CONFIG_ADFS_FS is not set
+# CONFIG_AFFS_FS is not set
+# CONFIG_HFS_FS is not set
+# CONFIG_HFSPLUS_FS is not set
+# CONFIG_BEFS_FS is not set
+# CONFIG_BFS_FS is not set
+# CONFIG_EFS_FS is not set
+CONFIG_JFFS2_FS=y
+CONFIG_JFFS2_FS_DEBUG=0
+CONFIG_JFFS2_FS_WRITEBUFFER=y
+# CONFIG_JFFS2_FS_WBUF_VERIFY is not set
+# CONFIG_JFFS2_SUMMARY is not set
+# CONFIG_JFFS2_FS_XATTR is not set
+# CONFIG_JFFS2_COMPRESSION_OPTIONS is not set
+CONFIG_JFFS2_ZLIB=y
+# CONFIG_JFFS2_LZO is not set
+CONFIG_JFFS2_RTIME=y
+# CONFIG_JFFS2_RUBIN is not set
+# CONFIG_UBIFS_FS is not set
+# CONFIG_CRAMFS is not set
+# CONFIG_VXFS_FS is not set
+# CONFIG_MINIX_FS is not set
+# CONFIG_OMFS_FS is not set
+# CONFIG_HPFS_FS is not set
+# CONFIG_QNX4FS_FS is not set
+# CONFIG_ROMFS_FS is not set
+# CONFIG_SYSV_FS is not set
+# CONFIG_UFS_FS is not set
+CONFIG_NETWORK_FILESYSTEMS=y
+CONFIG_NFS_FS=y
+CONFIG_NFS_V3=y
+# CONFIG_NFS_V3_ACL is not set
+# CONFIG_NFS_V4 is not set
+CONFIG_ROOT_NFS=y
+# CONFIG_NFSD is not set
+CONFIG_LOCKD=y
+CONFIG_LOCKD_V4=y
+CONFIG_NFS_COMMON=y
+CONFIG_SUNRPC=y
+# CONFIG_SUNRPC_REGISTER_V4 is not set
+# CONFIG_RPCSEC_GSS_KRB5 is not set
+# CONFIG_RPCSEC_GSS_SPKM3 is not set
+# CONFIG_SMB_FS is not set
+# CONFIG_CIFS is not set
+# CONFIG_NCP_FS is not set
+# CONFIG_CODA_FS is not set
+# CONFIG_AFS_FS is not set
+
+#
+# Partition Types
+#
+CONFIG_PARTITION_ADVANCED=y
+# CONFIG_ACORN_PARTITION is not set
+# CONFIG_OSF_PARTITION is not set
+# CONFIG_AMIGA_PARTITION is not set
+# CONFIG_ATARI_PARTITION is not set
+# CONFIG_MAC_PARTITION is not set
+# CONFIG_MSDOS_PARTITION is not set
+# CONFIG_LDM_PARTITION is not set
+# CONFIG_SGI_PARTITION is not set
+# CONFIG_ULTRIX_PARTITION is not set
+# CONFIG_SUN_PARTITION is not set
+# CONFIG_KARMA_PARTITION is not set
+# CONFIG_EFI_PARTITION is not set
+# CONFIG_SYSV68_PARTITION is not set
+# CONFIG_NLS is not set
+# CONFIG_DLM is not set
+CONFIG_UCC_FAST=y
+CONFIG_UCC=y
+
+#
+# Library routines
+#
+CONFIG_BITREVERSE=y
+# CONFIG_CRC_CCITT is not set
+# CONFIG_CRC16 is not set
+# CONFIG_CRC_T10DIF is not set
+# CONFIG_CRC_ITU_T is not set
+CONFIG_CRC32=y
+# CONFIG_CRC7 is not set
+# CONFIG_LIBCRC32C is not set
+CONFIG_ZLIB_INFLATE=y
+CONFIG_ZLIB_DEFLATE=y
+CONFIG_PLIST=y
+CONFIG_HAS_IOMEM=y
+CONFIG_HAS_IOPORT=y
+CONFIG_HAS_DMA=y
+CONFIG_HAVE_LMB=y
+
+#
+# Kernel hacking
+#
+# CONFIG_PRINTK_TIME is not set
+CONFIG_ENABLE_WARN_DEPRECATED=y
+CONFIG_ENABLE_MUST_CHECK=y
+CONFIG_FRAME_WARN=1024
+# CONFIG_MAGIC_SYSRQ is not set
+# CONFIG_UNUSED_SYMBOLS is not set
+CONFIG_DEBUG_FS=y
+# CONFIG_HEADERS_CHECK is not set
+# CONFIG_DEBUG_KERNEL is not set
+# CONFIG_DEBUG_BUGVERBOSE is not set
+# CONFIG_DEBUG_MEMORY_INIT is not set
+# CONFIG_RCU_CPU_STALL_DETECTOR is not set
+# CONFIG_LATENCYTOP is not set
+CONFIG_SYSCTL_SYSCALL_CHECK=y
+CONFIG_HAVE_FUNCTION_TRACER=y
+
+#
+# Tracers
+#
+# CONFIG_DYNAMIC_PRINTK_DEBUG is not set
+# CONFIG_SAMPLES is not set
+CONFIG_HAVE_ARCH_KGDB=y
+# CONFIG_IRQSTACKS is not set
+# CONFIG_VIRQ_DEBUG is not set
+# CONFIG_BOOTX_TEXT is not set
+# CONFIG_PPC_EARLY_DEBUG is not set
+
+#
+# Security options
+#
+# CONFIG_KEYS is not set
+# CONFIG_SECURITY is not set
+# CONFIG_SECURITYFS is not set
+# CONFIG_SECURITY_FILE_CAPABILITIES is not set
+# CONFIG_CRYPTO is not set
+# CONFIG_PPC_CLOCK is not set
+CONFIG_PPC_LIB_RHEAP=y
+# CONFIG_VIRTUALIZATION is not set
diff --git a/arch/powerpc/configs/85xx/xes_mpc85xx_defconfig b/arch/powerpc/configs/85xx/xes_mpc85xx_defconfig
new file mode 100644
index 0000000..2552cbe
--- /dev/null
+++ b/arch/powerpc/configs/85xx/xes_mpc85xx_defconfig
@@ -0,0 +1,1821 @@
+#
+# Automatically generated make config: don't edit
+# Linux kernel version: 2.6.30-rc6
+# Thu Jun 11 11:25:17 2009
+#
+# CONFIG_PPC64 is not set
+
+#
+# Processor support
+#
+# CONFIG_6xx is not set
+CONFIG_PPC_85xx=y
+# CONFIG_PPC_8xx is not set
+# CONFIG_40x is not set
+# CONFIG_44x is not set
+# CONFIG_E200 is not set
+CONFIG_E500=y
+# CONFIG_PPC_E500MC is not set
+CONFIG_BOOKE=y
+CONFIG_FSL_BOOKE=y
+CONFIG_FSL_EMB_PERFMON=y
+# CONFIG_PHYS_64BIT is not set
+CONFIG_SPE=y
+CONFIG_PPC_MMU_NOHASH=y
+CONFIG_PPC_BOOK3E_MMU=y
+# CONFIG_PPC_MM_SLICES is not set
+CONFIG_SMP=y
+CONFIG_NR_CPUS=2
+CONFIG_PPC32=y
+CONFIG_WORD_SIZE=32
+# CONFIG_ARCH_PHYS_ADDR_T_64BIT is not set
+CONFIG_MMU=y
+CONFIG_GENERIC_CMOS_UPDATE=y
+CONFIG_GENERIC_TIME=y
+CONFIG_GENERIC_TIME_VSYSCALL=y
+CONFIG_GENERIC_CLOCKEVENTS=y
+CONFIG_GENERIC_HARDIRQS=y
+# CONFIG_HAVE_SETUP_PER_CPU_AREA is not set
+CONFIG_IRQ_PER_CPU=y
+CONFIG_STACKTRACE_SUPPORT=y
+CONFIG_HAVE_LATENCYTOP_SUPPORT=y
+CONFIG_LOCKDEP_SUPPORT=y
+CONFIG_RWSEM_XCHGADD_ALGORITHM=y
+CONFIG_ARCH_HAS_ILOG2_U32=y
+CONFIG_GENERIC_HWEIGHT=y
+CONFIG_GENERIC_CALIBRATE_DELAY=y
+CONFIG_GENERIC_FIND_NEXT_BIT=y
+CONFIG_GENERIC_GPIO=y
+# CONFIG_ARCH_NO_VIRT_TO_BUS is not set
+CONFIG_PPC=y
+CONFIG_EARLY_PRINTK=y
+CONFIG_GENERIC_NVRAM=y
+CONFIG_SCHED_OMIT_FRAME_POINTER=y
+CONFIG_ARCH_MAY_HAVE_PC_FDC=y
+CONFIG_PPC_OF=y
+CONFIG_OF=y
+CONFIG_PPC_UDBG_16550=y
+CONFIG_GENERIC_TBSYNC=y
+CONFIG_AUDIT_ARCH=y
+CONFIG_GENERIC_BUG=y
+CONFIG_DTC=y
+CONFIG_DEFAULT_UIMAGE=y
+# CONFIG_PPC_DCR_NATIVE is not set
+# CONFIG_PPC_DCR_MMIO is not set
+CONFIG_ARCH_SUPPORTS_DEBUG_PAGEALLOC=y
+CONFIG_DEFCONFIG_LIST="/lib/modules/$UNAME_RELEASE/.config"
+
+#
+# General setup
+#
+CONFIG_EXPERIMENTAL=y
+CONFIG_LOCK_KERNEL=y
+CONFIG_INIT_ENV_ARG_LIMIT=32
+CONFIG_LOCALVERSION=""
+CONFIG_LOCALVERSION_AUTO=y
+CONFIG_SWAP=y
+CONFIG_SYSVIPC=y
+CONFIG_SYSVIPC_SYSCTL=y
+CONFIG_POSIX_MQUEUE=y
+CONFIG_POSIX_MQUEUE_SYSCTL=y
+CONFIG_BSD_PROCESS_ACCT=y
+# CONFIG_BSD_PROCESS_ACCT_V3 is not set
+# CONFIG_TASKSTATS is not set
+CONFIG_AUDIT=y
+# CONFIG_AUDITSYSCALL is not set
+
+#
+# RCU Subsystem
+#
+CONFIG_CLASSIC_RCU=y
+# CONFIG_TREE_RCU is not set
+# CONFIG_PREEMPT_RCU is not set
+# CONFIG_TREE_RCU_TRACE is not set
+# CONFIG_PREEMPT_RCU_TRACE is not set
+CONFIG_IKCONFIG=y
+CONFIG_IKCONFIG_PROC=y
+CONFIG_LOG_BUF_SHIFT=14
+# CONFIG_GROUP_SCHED is not set
+# CONFIG_CGROUPS is not set
+CONFIG_SYSFS_DEPRECATED=y
+CONFIG_SYSFS_DEPRECATED_V2=y
+# CONFIG_RELAY is not set
+# CONFIG_NAMESPACES is not set
+CONFIG_BLK_DEV_INITRD=y
+CONFIG_INITRAMFS_SOURCE=""
+CONFIG_RD_GZIP=y
+# CONFIG_RD_BZIP2 is not set
+# CONFIG_RD_LZMA is not set
+# CONFIG_CC_OPTIMIZE_FOR_SIZE is not set
+CONFIG_SYSCTL=y
+CONFIG_ANON_INODES=y
+CONFIG_EMBEDDED=y
+CONFIG_SYSCTL_SYSCALL=y
+CONFIG_KALLSYMS=y
+CONFIG_KALLSYMS_ALL=y
+CONFIG_KALLSYMS_EXTRA_PASS=y
+# CONFIG_STRIP_ASM_SYMS is not set
+CONFIG_HOTPLUG=y
+CONFIG_PRINTK=y
+CONFIG_BUG=y
+CONFIG_ELF_CORE=y
+CONFIG_BASE_FULL=y
+CONFIG_FUTEX=y
+CONFIG_EPOLL=y
+CONFIG_SIGNALFD=y
+CONFIG_TIMERFD=y
+CONFIG_EVENTFD=y
+CONFIG_SHMEM=y
+CONFIG_AIO=y
+CONFIG_VM_EVENT_COUNTERS=y
+CONFIG_PCI_QUIRKS=y
+CONFIG_SLUB_DEBUG=y
+CONFIG_COMPAT_BRK=y
+# CONFIG_SLAB is not set
+CONFIG_SLUB=y
+# CONFIG_SLOB is not set
+# CONFIG_PROFILING is not set
+# CONFIG_MARKERS is not set
+CONFIG_HAVE_OPROFILE=y
+# CONFIG_KPROBES is not set
+CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS=y
+CONFIG_HAVE_IOREMAP_PROT=y
+CONFIG_HAVE_KPROBES=y
+CONFIG_HAVE_KRETPROBES=y
+CONFIG_HAVE_ARCH_TRACEHOOK=y
+CONFIG_USE_GENERIC_SMP_HELPERS=y
+# CONFIG_SLOW_WORK is not set
+# CONFIG_HAVE_GENERIC_DMA_COHERENT is not set
+CONFIG_SLABINFO=y
+CONFIG_RT_MUTEXES=y
+CONFIG_BASE_SMALL=0
+CONFIG_MODULES=y
+# CONFIG_MODULE_FORCE_LOAD is not set
+CONFIG_MODULE_UNLOAD=y
+CONFIG_MODULE_FORCE_UNLOAD=y
+CONFIG_MODVERSIONS=y
+# CONFIG_MODULE_SRCVERSION_ALL is not set
+CONFIG_STOP_MACHINE=y
+CONFIG_BLOCK=y
+CONFIG_LBD=y
+# CONFIG_BLK_DEV_BSG is not set
+# CONFIG_BLK_DEV_INTEGRITY is not set
+
+#
+# IO Schedulers
+#
+CONFIG_IOSCHED_NOOP=y
+CONFIG_IOSCHED_AS=y
+CONFIG_IOSCHED_DEADLINE=y
+CONFIG_IOSCHED_CFQ=y
+# CONFIG_DEFAULT_AS is not set
+# CONFIG_DEFAULT_DEADLINE is not set
+CONFIG_DEFAULT_CFQ=y
+# CONFIG_DEFAULT_NOOP is not set
+CONFIG_DEFAULT_IOSCHED="cfq"
+# CONFIG_FREEZER is not set
+CONFIG_PPC_MSI_BITMAP=y
+
+#
+# Platform support
+#
+# CONFIG_PPC_CELL is not set
+# CONFIG_PPC_CELL_NATIVE is not set
+# CONFIG_PQ2ADS is not set
+CONFIG_MPC85xx=y
+# CONFIG_MPC8540_ADS is not set
+# CONFIG_MPC8560_ADS is not set
+# CONFIG_MPC85xx_CDS is not set
+# CONFIG_MPC85xx_MDS is not set
+# CONFIG_MPC8536_DS is not set
+# CONFIG_MPC85xx_DS is not set
+# CONFIG_SOCRATES is not set
+# CONFIG_KSI8560 is not set
+CONFIG_XES_MPC85xx=y
+# CONFIG_STX_GP3 is not set
+# CONFIG_TQM8540 is not set
+# CONFIG_TQM8541 is not set
+# CONFIG_TQM8548 is not set
+# CONFIG_TQM8555 is not set
+# CONFIG_TQM8560 is not set
+# CONFIG_SBC8548 is not set
+# CONFIG_SBC8560 is not set
+# CONFIG_IPIC is not set
+CONFIG_MPIC=y
+# CONFIG_MPIC_WEIRD is not set
+# CONFIG_PPC_I8259 is not set
+# CONFIG_PPC_RTAS is not set
+# CONFIG_MMIO_NVRAM is not set
+# CONFIG_PPC_MPC106 is not set
+# CONFIG_PPC_970_NAP is not set
+# CONFIG_PPC_INDIRECT_IO is not set
+# CONFIG_GENERIC_IOMAP is not set
+# CONFIG_CPU_FREQ is not set
+# CONFIG_QUICC_ENGINE is not set
+# CONFIG_CPM2 is not set
+# CONFIG_FSL_ULI1575 is not set
+CONFIG_MPC8xxx_GPIO=y
+# CONFIG_SIMPLE_GPIO is not set
+
+#
+# Kernel options
+#
+CONFIG_HIGHMEM=y
+# CONFIG_NO_HZ is not set
+# CONFIG_HIGH_RES_TIMERS is not set
+CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
+# CONFIG_HZ_100 is not set
+CONFIG_HZ_250=y
+# CONFIG_HZ_300 is not set
+# CONFIG_HZ_1000 is not set
+CONFIG_HZ=250
+# CONFIG_SCHED_HRTICK is not set
+CONFIG_PREEMPT_NONE=y
+# CONFIG_PREEMPT_VOLUNTARY is not set
+# CONFIG_PREEMPT is not set
+CONFIG_BINFMT_ELF=y
+# CONFIG_CORE_DUMP_DEFAULT_ELF_HEADERS is not set
+# CONFIG_HAVE_AOUT is not set
+# CONFIG_BINFMT_MISC is not set
+CONFIG_MATH_EMULATION=y
+# CONFIG_IOMMU_HELPER is not set
+CONFIG_ARCH_ENABLE_MEMORY_HOTPLUG=y
+CONFIG_ARCH_HAS_WALK_MEMORY=y
+CONFIG_ARCH_ENABLE_MEMORY_HOTREMOVE=y
+# CONFIG_IRQ_ALL_CPUS is not set
+CONFIG_ARCH_FLATMEM_ENABLE=y
+CONFIG_ARCH_POPULATES_NODE_MAP=y
+CONFIG_SELECT_MEMORY_MODEL=y
+CONFIG_FLATMEM_MANUAL=y
+# CONFIG_DISCONTIGMEM_MANUAL is not set
+# CONFIG_SPARSEMEM_MANUAL is not set
+CONFIG_FLATMEM=y
+CONFIG_FLAT_NODE_MEM_MAP=y
+CONFIG_PAGEFLAGS_EXTENDED=y
+CONFIG_SPLIT_PTLOCK_CPUS=4
+CONFIG_MIGRATION=y
+# CONFIG_PHYS_ADDR_T_64BIT is not set
+CONFIG_ZONE_DMA_FLAG=1
+CONFIG_BOUNCE=y
+CONFIG_VIRT_TO_BUS=y
+CONFIG_UNEVICTABLE_LRU=y
+CONFIG_HAVE_MLOCK=y
+CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_PPC_4K_PAGES=y
+# CONFIG_PPC_16K_PAGES is not set
+# CONFIG_PPC_64K_PAGES is not set
+# CONFIG_PPC_256K_PAGES is not set
+CONFIG_FORCE_MAX_ZONEORDER=11
+CONFIG_PROC_DEVICETREE=y
+# CONFIG_CMDLINE_BOOL is not set
+CONFIG_EXTRA_TARGETS=""
+# CONFIG_PM is not set
+CONFIG_SECCOMP=y
+CONFIG_ISA_DMA_API=y
+
+#
+# Bus options
+#
+CONFIG_ZONE_DMA=y
+CONFIG_PPC_INDIRECT_PCI=y
+CONFIG_FSL_SOC=y
+CONFIG_FSL_PCI=y
+CONFIG_FSL_LBC=y
+CONFIG_PPC_PCI_CHOICE=y
+CONFIG_PCI=y
+CONFIG_PCI_DOMAINS=y
+CONFIG_PCI_SYSCALL=y
+CONFIG_PCIEPORTBUS=y
+CONFIG_PCIEAER=y
+# CONFIG_PCIEASPM is not set
+CONFIG_ARCH_SUPPORTS_MSI=y
+CONFIG_PCI_MSI=y
+CONFIG_PCI_LEGACY=y
+# CONFIG_PCI_DEBUG is not set
+# CONFIG_PCI_STUB is not set
+# CONFIG_PCI_IOV is not set
+# CONFIG_PCCARD is not set
+# CONFIG_HOTPLUG_PCI is not set
+# CONFIG_HAS_RAPIDIO is not set
+
+#
+# Advanced setup
+#
+CONFIG_ADVANCED_OPTIONS=y
+CONFIG_LOWMEM_SIZE_BOOL=y
+CONFIG_LOWMEM_SIZE=0x40000000
+# CONFIG_LOWMEM_CAM_NUM_BOOL is not set
+CONFIG_LOWMEM_CAM_NUM=3
+# CONFIG_RELOCATABLE is not set
+CONFIG_PAGE_OFFSET_BOOL=y
+CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_KERNEL_START_BOOL=y
+CONFIG_KERNEL_START=0x80000000
+# CONFIG_PHYSICAL_START_BOOL is not set
+CONFIG_PHYSICAL_START=0x00000000
+CONFIG_PHYSICAL_ALIGN=0x04000000
+CONFIG_TASK_SIZE_BOOL=y
+CONFIG_TASK_SIZE=0x80000000
+CONFIG_NET=y
+
+#
+# Networking options
+#
+CONFIG_PACKET=y
+# CONFIG_PACKET_MMAP is not set
+CONFIG_UNIX=y
+CONFIG_XFRM=y
+CONFIG_XFRM_USER=y
+# CONFIG_XFRM_SUB_POLICY is not set
+# CONFIG_XFRM_MIGRATE is not set
+# CONFIG_XFRM_STATISTICS is not set
+CONFIG_NET_KEY=y
+# CONFIG_NET_KEY_MIGRATE is not set
+CONFIG_INET=y
+CONFIG_IP_MULTICAST=y
+CONFIG_IP_ADVANCED_ROUTER=y
+CONFIG_ASK_IP_FIB_HASH=y
+# CONFIG_IP_FIB_TRIE is not set
+CONFIG_IP_FIB_HASH=y
+CONFIG_IP_MULTIPLE_TABLES=y
+CONFIG_IP_ROUTE_MULTIPATH=y
+CONFIG_IP_ROUTE_VERBOSE=y
+CONFIG_IP_PNP=y
+CONFIG_IP_PNP_DHCP=y
+CONFIG_IP_PNP_BOOTP=y
+CONFIG_IP_PNP_RARP=y
+CONFIG_NET_IPIP=y
+CONFIG_NET_IPGRE=y
+CONFIG_NET_IPGRE_BROADCAST=y
+CONFIG_IP_MROUTE=y
+CONFIG_IP_PIMSM_V1=y
+CONFIG_IP_PIMSM_V2=y
+CONFIG_ARPD=y
+# CONFIG_SYN_COOKIES is not set
+# CONFIG_INET_AH is not set
+# CONFIG_INET_ESP is not set
+# CONFIG_INET_IPCOMP is not set
+# CONFIG_INET_XFRM_TUNNEL is not set
+CONFIG_INET_TUNNEL=y
+# CONFIG_INET_XFRM_MODE_TRANSPORT is not set
+# CONFIG_INET_XFRM_MODE_TUNNEL is not set
+# CONFIG_INET_XFRM_MODE_BEET is not set
+# CONFIG_INET_LRO is not set
+CONFIG_INET_DIAG=y
+CONFIG_INET_TCP_DIAG=y
+# CONFIG_TCP_CONG_ADVANCED is not set
+CONFIG_TCP_CONG_CUBIC=y
+CONFIG_DEFAULT_TCP_CONG="cubic"
+# CONFIG_TCP_MD5SIG is not set
+CONFIG_IPV6=y
+# CONFIG_IPV6_PRIVACY is not set
+# CONFIG_IPV6_ROUTER_PREF is not set
+# CONFIG_IPV6_OPTIMISTIC_DAD is not set
+# CONFIG_INET6_AH is not set
+# CONFIG_INET6_ESP is not set
+# CONFIG_INET6_IPCOMP is not set
+# CONFIG_IPV6_MIP6 is not set
+# CONFIG_INET6_XFRM_TUNNEL is not set
+# CONFIG_INET6_TUNNEL is not set
+CONFIG_INET6_XFRM_MODE_TRANSPORT=y
+CONFIG_INET6_XFRM_MODE_TUNNEL=y
+CONFIG_INET6_XFRM_MODE_BEET=y
+# CONFIG_INET6_XFRM_MODE_ROUTEOPTIMIZATION is not set
+CONFIG_IPV6_SIT=y
+CONFIG_IPV6_NDISC_NODETYPE=y
+# CONFIG_IPV6_TUNNEL is not set
+# CONFIG_IPV6_MULTIPLE_TABLES is not set
+# CONFIG_IPV6_MROUTE is not set
+# CONFIG_NETWORK_SECMARK is not set
+# CONFIG_NETFILTER is not set
+# CONFIG_IP_DCCP is not set
+# CONFIG_IP_SCTP is not set
+# CONFIG_TIPC is not set
+# CONFIG_ATM is not set
+# CONFIG_BRIDGE is not set
+# CONFIG_NET_DSA is not set
+# CONFIG_VLAN_8021Q is not set
+# CONFIG_DECNET is not set
+# CONFIG_LLC2 is not set
+# CONFIG_IPX is not set
+# CONFIG_ATALK is not set
+# CONFIG_X25 is not set
+# CONFIG_LAPB is not set
+# CONFIG_ECONET is not set
+# CONFIG_WAN_ROUTER is not set
+# CONFIG_PHONET is not set
+# CONFIG_NET_SCHED is not set
+# CONFIG_DCB is not set
+
+#
+# Network testing
+#
+# CONFIG_NET_PKTGEN is not set
+# CONFIG_HAMRADIO is not set
+# CONFIG_CAN is not set
+# CONFIG_IRDA is not set
+# CONFIG_BT is not set
+# CONFIG_AF_RXRPC is not set
+CONFIG_FIB_RULES=y
+# CONFIG_WIRELESS is not set
+# CONFIG_WIMAX is not set
+# CONFIG_RFKILL is not set
+# CONFIG_NET_9P is not set
+
+#
+# Device Drivers
+#
+
+#
+# Generic Driver Options
+#
+CONFIG_UEVENT_HELPER_PATH="/sbin/hotplug"
+CONFIG_STANDALONE=y
+CONFIG_PREVENT_FIRMWARE_BUILD=y
+CONFIG_FW_LOADER=y
+CONFIG_FIRMWARE_IN_KERNEL=y
+CONFIG_EXTRA_FIRMWARE=""
+# CONFIG_DEBUG_DRIVER is not set
+# CONFIG_DEBUG_DEVRES is not set
+# CONFIG_SYS_HYPERVISOR is not set
+# CONFIG_CONNECTOR is not set
+CONFIG_MTD=y
+# CONFIG_MTD_DEBUG is not set
+# CONFIG_MTD_CONCAT is not set
+CONFIG_MTD_PARTITIONS=y
+# CONFIG_MTD_TESTS is not set
+CONFIG_MTD_REDBOOT_PARTS=y
+CONFIG_MTD_REDBOOT_DIRECTORY_BLOCK=-1
+# CONFIG_MTD_REDBOOT_PARTS_UNALLOCATED is not set
+# CONFIG_MTD_REDBOOT_PARTS_READONLY is not set
+CONFIG_MTD_CMDLINE_PARTS=y
+CONFIG_MTD_OF_PARTS=y
+# CONFIG_MTD_AR7_PARTS is not set
+
+#
+# User Modules And Translation Layers
+#
+CONFIG_MTD_CHAR=y
+CONFIG_MTD_BLKDEVS=y
+CONFIG_MTD_BLOCK=y
+# CONFIG_FTL is not set
+# CONFIG_NFTL is not set
+# CONFIG_INFTL is not set
+# CONFIG_RFD_FTL is not set
+# CONFIG_SSFDC is not set
+# CONFIG_MTD_OOPS is not set
+
+#
+# RAM/ROM/Flash chip drivers
+#
+CONFIG_MTD_CFI=y
+CONFIG_MTD_JEDECPROBE=y
+CONFIG_MTD_GEN_PROBE=y
+# CONFIG_MTD_CFI_ADV_OPTIONS is not set
+CONFIG_MTD_MAP_BANK_WIDTH_1=y
+CONFIG_MTD_MAP_BANK_WIDTH_2=y
+CONFIG_MTD_MAP_BANK_WIDTH_4=y
+# CONFIG_MTD_MAP_BANK_WIDTH_8 is not set
+# CONFIG_MTD_MAP_BANK_WIDTH_16 is not set
+# CONFIG_MTD_MAP_BANK_WIDTH_32 is not set
+CONFIG_MTD_CFI_I1=y
+CONFIG_MTD_CFI_I2=y
+# CONFIG_MTD_CFI_I4 is not set
+# CONFIG_MTD_CFI_I8 is not set
+CONFIG_MTD_CFI_INTELEXT=y
+CONFIG_MTD_CFI_AMDSTD=y
+CONFIG_MTD_CFI_STAA=y
+CONFIG_MTD_CFI_UTIL=y
+# CONFIG_MTD_RAM is not set
+# CONFIG_MTD_ROM is not set
+# CONFIG_MTD_ABSENT is not set
+
+#
+# Mapping drivers for chip access
+#
+# CONFIG_MTD_COMPLEX_MAPPINGS is not set
+# CONFIG_MTD_PHYSMAP is not set
+CONFIG_MTD_PHYSMAP_OF=y
+# CONFIG_MTD_INTEL_VR_NOR is not set
+# CONFIG_MTD_PLATRAM is not set
+
+#
+# Self-contained MTD device drivers
+#
+# CONFIG_MTD_PMC551 is not set
+# CONFIG_MTD_SLRAM is not set
+# CONFIG_MTD_PHRAM is not set
+# CONFIG_MTD_MTDRAM is not set
+# CONFIG_MTD_BLOCK2MTD is not set
+
+#
+# Disk-On-Chip Device Drivers
+#
+# CONFIG_MTD_DOC2000 is not set
+# CONFIG_MTD_DOC2001 is not set
+# CONFIG_MTD_DOC2001PLUS is not set
+CONFIG_MTD_NAND=y
+# CONFIG_MTD_NAND_VERIFY_WRITE is not set
+# CONFIG_MTD_NAND_ECC_SMC is not set
+# CONFIG_MTD_NAND_MUSEUM_IDS is not set
+CONFIG_MTD_NAND_IDS=y
+# CONFIG_MTD_NAND_DISKONCHIP is not set
+# CONFIG_MTD_NAND_CAFE is not set
+# CONFIG_MTD_NAND_NANDSIM is not set
+# CONFIG_MTD_NAND_PLATFORM is not set
+# CONFIG_MTD_ALAUDA is not set
+CONFIG_MTD_NAND_FSL_ELBC=y
+CONFIG_MTD_NAND_FSL_UPM=y
+# CONFIG_MTD_ONENAND is not set
+
+#
+# LPDDR flash memory drivers
+#
+# CONFIG_MTD_LPDDR is not set
+
+#
+# UBI - Unsorted block images
+#
+# CONFIG_MTD_UBI is not set
+CONFIG_OF_DEVICE=y
+CONFIG_OF_GPIO=y
+CONFIG_OF_I2C=y
+# CONFIG_PARPORT is not set
+CONFIG_BLK_DEV=y
+# CONFIG_BLK_DEV_FD is not set
+# CONFIG_BLK_CPQ_DA is not set
+# CONFIG_BLK_CPQ_CISS_DA is not set
+# CONFIG_BLK_DEV_DAC960 is not set
+# CONFIG_BLK_DEV_UMEM is not set
+# CONFIG_BLK_DEV_COW_COMMON is not set
+CONFIG_BLK_DEV_LOOP=y
+# CONFIG_BLK_DEV_CRYPTOLOOP is not set
+CONFIG_BLK_DEV_NBD=y
+# CONFIG_BLK_DEV_SX8 is not set
+# CONFIG_BLK_DEV_UB is not set
+CONFIG_BLK_DEV_RAM=y
+CONFIG_BLK_DEV_RAM_COUNT=16
+CONFIG_BLK_DEV_RAM_SIZE=131072
+# CONFIG_BLK_DEV_XIP is not set
+# CONFIG_CDROM_PKTCDVD is not set
+# CONFIG_ATA_OVER_ETH is not set
+# CONFIG_BLK_DEV_HD is not set
+CONFIG_MISC_DEVICES=y
+# CONFIG_PHANTOM is not set
+# CONFIG_SGI_IOC4 is not set
+# CONFIG_TIFM_CORE is not set
+# CONFIG_ICS932S401 is not set
+# CONFIG_ENCLOSURE_SERVICES is not set
+# CONFIG_HP_ILO is not set
+# CONFIG_ISL29003 is not set
+# CONFIG_C2PORT is not set
+
+#
+# EEPROM support
+#
+# CONFIG_EEPROM_AT24 is not set
+# CONFIG_EEPROM_LEGACY is not set
+# CONFIG_EEPROM_93CX6 is not set
+CONFIG_HAVE_IDE=y
+# CONFIG_IDE is not set
+
+#
+# SCSI device support
+#
+# CONFIG_RAID_ATTRS is not set
+CONFIG_SCSI=y
+CONFIG_SCSI_DMA=y
+# CONFIG_SCSI_TGT is not set
+# CONFIG_SCSI_NETLINK is not set
+CONFIG_SCSI_PROC_FS=y
+
+#
+# SCSI support type (disk, tape, CD-ROM)
+#
+CONFIG_BLK_DEV_SD=y
+CONFIG_CHR_DEV_ST=y
+# CONFIG_CHR_DEV_OSST is not set
+CONFIG_BLK_DEV_SR=y
+# CONFIG_BLK_DEV_SR_VENDOR is not set
+CONFIG_CHR_DEV_SG=y
+# CONFIG_CHR_DEV_SCH is not set
+
+#
+# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
+#
+CONFIG_SCSI_MULTI_LUN=y
+# CONFIG_SCSI_CONSTANTS is not set
+CONFIG_SCSI_LOGGING=y
+# CONFIG_SCSI_SCAN_ASYNC is not set
+CONFIG_SCSI_WAIT_SCAN=m
+
+#
+# SCSI Transports
+#
+# CONFIG_SCSI_SPI_ATTRS is not set
+# CONFIG_SCSI_FC_ATTRS is not set
+# CONFIG_SCSI_ISCSI_ATTRS is not set
+# CONFIG_SCSI_SAS_LIBSAS is not set
+# CONFIG_SCSI_SRP_ATTRS is not set
+CONFIG_SCSI_LOWLEVEL=y
+# CONFIG_ISCSI_TCP is not set
+# CONFIG_BLK_DEV_3W_XXXX_RAID is not set
+# CONFIG_SCSI_3W_9XXX is not set
+# CONFIG_SCSI_ACARD is not set
+# CONFIG_SCSI_AACRAID is not set
+# CONFIG_SCSI_AIC7XXX is not set
+# CONFIG_SCSI_AIC7XXX_OLD is not set
+# CONFIG_SCSI_AIC79XX is not set
+# CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_DPT_I2O is not set
+# CONFIG_SCSI_ADVANSYS is not set
+# CONFIG_SCSI_ARCMSR is not set
+# CONFIG_MEGARAID_NEWGEN is not set
+# CONFIG_MEGARAID_LEGACY is not set
+# CONFIG_MEGARAID_SAS is not set
+# CONFIG_SCSI_MPT2SAS is not set
+# CONFIG_SCSI_HPTIOP is not set
+# CONFIG_SCSI_BUSLOGIC is not set
+# CONFIG_LIBFC is not set
+# CONFIG_LIBFCOE is not set
+# CONFIG_FCOE is not set
+# CONFIG_SCSI_DMX3191D is not set
+# CONFIG_SCSI_EATA is not set
+# CONFIG_SCSI_FUTURE_DOMAIN is not set
+# CONFIG_SCSI_GDTH is not set
+# CONFIG_SCSI_IPS is not set
+# CONFIG_SCSI_INITIO is not set
+# CONFIG_SCSI_INIA100 is not set
+# CONFIG_SCSI_MVSAS is not set
+# CONFIG_SCSI_STEX is not set
+# CONFIG_SCSI_SYM53C8XX_2 is not set
+# CONFIG_SCSI_IPR is not set
+# CONFIG_SCSI_QLOGIC_1280 is not set
+# CONFIG_SCSI_QLA_FC is not set
+# CONFIG_SCSI_QLA_ISCSI is not set
+# CONFIG_SCSI_LPFC is not set
+# CONFIG_SCSI_DC395x is not set
+# CONFIG_SCSI_DC390T is not set
+# CONFIG_SCSI_NSP32 is not set
+# CONFIG_SCSI_DEBUG is not set
+# CONFIG_SCSI_SRP is not set
+# CONFIG_SCSI_DH is not set
+# CONFIG_SCSI_OSD_INITIATOR is not set
+CONFIG_ATA=y
+# CONFIG_ATA_NONSTANDARD is not set
+CONFIG_SATA_PMP=y
+CONFIG_SATA_AHCI=y
+# CONFIG_SATA_SIL24 is not set
+# CONFIG_SATA_FSL is not set
+CONFIG_ATA_SFF=y
+# CONFIG_SATA_SVW is not set
+# CONFIG_ATA_PIIX is not set
+# CONFIG_SATA_MV is not set
+# CONFIG_SATA_NV is not set
+# CONFIG_PDC_ADMA is not set
+# CONFIG_SATA_QSTOR is not set
+# CONFIG_SATA_PROMISE is not set
+# CONFIG_SATA_SX4 is not set
+# CONFIG_SATA_SIL is not set
+# CONFIG_SATA_SIS is not set
+# CONFIG_SATA_ULI is not set
+# CONFIG_SATA_VIA is not set
+# CONFIG_SATA_VITESSE is not set
+# CONFIG_SATA_INIC162X is not set
+CONFIG_PATA_ALI=y
+# CONFIG_PATA_AMD is not set
+# CONFIG_PATA_ARTOP is not set
+# CONFIG_PATA_ATIIXP is not set
+# CONFIG_PATA_CMD640_PCI is not set
+# CONFIG_PATA_CMD64X is not set
+# CONFIG_PATA_CS5520 is not set
+# CONFIG_PATA_CS5530 is not set
+# CONFIG_PATA_CYPRESS is not set
+# CONFIG_PATA_EFAR is not set
+# CONFIG_ATA_GENERIC is not set
+# CONFIG_PATA_HPT366 is not set
+# CONFIG_PATA_HPT37X is not set
+# CONFIG_PATA_HPT3X2N is not set
+# CONFIG_PATA_HPT3X3 is not set
+# CONFIG_PATA_IT821X is not set
+# CONFIG_PATA_IT8213 is not set
+# CONFIG_PATA_JMICRON is not set
+# CONFIG_PATA_TRIFLEX is not set
+# CONFIG_PATA_MARVELL is not set
+# CONFIG_PATA_MPIIX is not set
+# CONFIG_PATA_OLDPIIX is not set
+# CONFIG_PATA_NETCELL is not set
+# CONFIG_PATA_NINJA32 is not set
+# CONFIG_PATA_NS87410 is not set
+# CONFIG_PATA_NS87415 is not set
+# CONFIG_PATA_OPTI is not set
+# CONFIG_PATA_OPTIDMA is not set
+# CONFIG_PATA_PDC_OLD is not set
+# CONFIG_PATA_RADISYS is not set
+# CONFIG_PATA_RZ1000 is not set
+# CONFIG_PATA_SC1200 is not set
+# CONFIG_PATA_SERVERWORKS is not set
+# CONFIG_PATA_PDC2027X is not set
+# CONFIG_PATA_SIL680 is not set
+# CONFIG_PATA_SIS is not set
+# CONFIG_PATA_VIA is not set
+# CONFIG_PATA_WINBOND is not set
+# CONFIG_PATA_PLATFORM is not set
+# CONFIG_PATA_SCH is not set
+# CONFIG_MD is not set
+# CONFIG_FUSION is not set
+
+#
+# IEEE 1394 (FireWire) support
+#
+
+#
+# Enable only one of the two stacks, unless you know what you are doing
+#
+# CONFIG_FIREWIRE is not set
+# CONFIG_IEEE1394 is not set
+# CONFIG_I2O is not set
+# CONFIG_MACINTOSH_DRIVERS is not set
+CONFIG_NETDEVICES=y
+CONFIG_COMPAT_NET_DEV_OPS=y
+CONFIG_DUMMY=y
+# CONFIG_BONDING is not set
+# CONFIG_MACVLAN is not set
+# CONFIG_EQUALIZER is not set
+# CONFIG_TUN is not set
+# CONFIG_VETH is not set
+# CONFIG_ARCNET is not set
+CONFIG_PHYLIB=y
+
+#
+# MII PHY device drivers
+#
+# CONFIG_MARVELL_PHY is not set
+# CONFIG_DAVICOM_PHY is not set
+# CONFIG_QSEMI_PHY is not set
+# CONFIG_LXT_PHY is not set
+# CONFIG_CICADA_PHY is not set
+# CONFIG_VITESSE_PHY is not set
+# CONFIG_SMSC_PHY is not set
+CONFIG_BROADCOM_PHY=y
+# CONFIG_ICPLUS_PHY is not set
+# CONFIG_REALTEK_PHY is not set
+# CONFIG_NATIONAL_PHY is not set
+# CONFIG_STE10XP is not set
+# CONFIG_LSI_ET1011C_PHY is not set
+# CONFIG_FIXED_PHY is not set
+# CONFIG_MDIO_BITBANG is not set
+CONFIG_NET_ETHERNET=y
+CONFIG_MII=y
+# CONFIG_HAPPYMEAL is not set
+# CONFIG_SUNGEM is not set
+# CONFIG_CASSINI is not set
+# CONFIG_NET_VENDOR_3COM is not set
+# CONFIG_ETHOC is not set
+# CONFIG_DNET is not set
+# CONFIG_NET_TULIP is not set
+# CONFIG_HP100 is not set
+# CONFIG_IBM_NEW_EMAC_ZMII is not set
+# CONFIG_IBM_NEW_EMAC_RGMII is not set
+# CONFIG_IBM_NEW_EMAC_TAH is not set
+# CONFIG_IBM_NEW_EMAC_EMAC4 is not set
+# CONFIG_IBM_NEW_EMAC_NO_FLOW_CTRL is not set
+# CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
+# CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
+# CONFIG_NET_PCI is not set
+# CONFIG_B44 is not set
+# CONFIG_ATL2 is not set
+CONFIG_NETDEV_1000=y
+# CONFIG_ACENIC is not set
+# CONFIG_DL2K is not set
+CONFIG_E1000=y
+# CONFIG_E1000E is not set
+# CONFIG_IP1000 is not set
+# CONFIG_IGB is not set
+# CONFIG_IGBVF is not set
+# CONFIG_NS83820 is not set
+# CONFIG_HAMACHI is not set
+# CONFIG_YELLOWFIN is not set
+# CONFIG_R8169 is not set
+# CONFIG_SIS190 is not set
+# CONFIG_SKGE is not set
+# CONFIG_SKY2 is not set
+# CONFIG_VIA_VELOCITY is not set
+# CONFIG_TIGON3 is not set
+# CONFIG_BNX2 is not set
+CONFIG_FSL_PQ_MDIO=y
+CONFIG_GIANFAR=y
+# CONFIG_QLA3XXX is not set
+# CONFIG_ATL1 is not set
+# CONFIG_ATL1E is not set
+# CONFIG_ATL1C is not set
+# CONFIG_JME is not set
+# CONFIG_NETDEV_10000 is not set
+# CONFIG_TR is not set
+
+#
+# Wireless LAN
+#
+# CONFIG_WLAN_PRE80211 is not set
+# CONFIG_WLAN_80211 is not set
+
+#
+# Enable WiMAX (Networking options) to see the WiMAX drivers
+#
+
+#
+# USB Network Adapters
+#
+# CONFIG_USB_CATC is not set
+# CONFIG_USB_KAWETH is not set
+# CONFIG_USB_PEGASUS is not set
+# CONFIG_USB_RTL8150 is not set
+# CONFIG_USB_USBNET is not set
+# CONFIG_WAN is not set
+# CONFIG_FDDI is not set
+# CONFIG_HIPPI is not set
+# CONFIG_PPP is not set
+# CONFIG_SLIP is not set
+# CONFIG_NET_FC is not set
+# CONFIG_NETCONSOLE is not set
+# CONFIG_NETPOLL is not set
+# CONFIG_NET_POLL_CONTROLLER is not set
+# CONFIG_ISDN is not set
+# CONFIG_PHONE is not set
+
+#
+# Input device support
+#
+CONFIG_INPUT=y
+# CONFIG_INPUT_FF_MEMLESS is not set
+# CONFIG_INPUT_POLLDEV is not set
+
+#
+# Userland interfaces
+#
+# CONFIG_INPUT_MOUSEDEV is not set
+# CONFIG_INPUT_JOYDEV is not set
+# CONFIG_INPUT_EVDEV is not set
+# CONFIG_INPUT_EVBUG is not set
+
+#
+# Input Device Drivers
+#
+# CONFIG_INPUT_KEYBOARD is not set
+# CONFIG_INPUT_MOUSE is not set
+# CONFIG_INPUT_JOYSTICK is not set
+# CONFIG_INPUT_TABLET is not set
+# CONFIG_INPUT_TOUCHSCREEN is not set
+# CONFIG_INPUT_MISC is not set
+
+#
+# Hardware I/O ports
+#
+CONFIG_SERIO=y
+CONFIG_SERIO_I8042=y
+CONFIG_SERIO_SERPORT=y
+# CONFIG_SERIO_PCIPS2 is not set
+CONFIG_SERIO_LIBPS2=y
+# CONFIG_SERIO_RAW is not set
+# CONFIG_SERIO_XILINX_XPS_PS2 is not set
+# CONFIG_GAMEPORT is not set
+
+#
+# Character devices
+#
+CONFIG_VT=y
+CONFIG_CONSOLE_TRANSLATIONS=y
+CONFIG_VT_CONSOLE=y
+CONFIG_HW_CONSOLE=y
+# CONFIG_VT_HW_CONSOLE_BINDING is not set
+CONFIG_DEVKMEM=y
+# CONFIG_SERIAL_NONSTANDARD is not set
+# CONFIG_NOZOMI is not set
+
+#
+# Serial drivers
+#
+CONFIG_SERIAL_8250=y
+CONFIG_SERIAL_8250_CONSOLE=y
+CONFIG_SERIAL_8250_PCI=y
+CONFIG_SERIAL_8250_NR_UARTS=2
+CONFIG_SERIAL_8250_RUNTIME_UARTS=2
+CONFIG_SERIAL_8250_EXTENDED=y
+CONFIG_SERIAL_8250_MANY_PORTS=y
+CONFIG_SERIAL_8250_SHARE_IRQ=y
+CONFIG_SERIAL_8250_DETECT_IRQ=y
+CONFIG_SERIAL_8250_RSA=y
+
+#
+# Non-8250 serial port support
+#
+# CONFIG_SERIAL_UARTLITE is not set
+CONFIG_SERIAL_CORE=y
+CONFIG_SERIAL_CORE_CONSOLE=y
+# CONFIG_SERIAL_JSM is not set
+# CONFIG_SERIAL_OF_PLATFORM is not set
+CONFIG_UNIX98_PTYS=y
+# CONFIG_DEVPTS_MULTIPLE_INSTANCES is not set
+CONFIG_LEGACY_PTYS=y
+CONFIG_LEGACY_PTY_COUNT=256
+# CONFIG_HVC_UDBG is not set
+# CONFIG_IPMI_HANDLER is not set
+# CONFIG_HW_RANDOM is not set
+CONFIG_NVRAM=y
+# CONFIG_R3964 is not set
+# CONFIG_APPLICOM is not set
+# CONFIG_RAW_DRIVER is not set
+# CONFIG_TCG_TPM is not set
+CONFIG_DEVPORT=y
+CONFIG_I2C=y
+CONFIG_I2C_BOARDINFO=y
+CONFIG_I2C_CHARDEV=y
+CONFIG_I2C_HELPER_AUTO=y
+
+#
+# I2C Hardware Bus support
+#
+
+#
+# PC SMBus host controller drivers
+#
+# CONFIG_I2C_ALI1535 is not set
+# CONFIG_I2C_ALI1563 is not set
+# CONFIG_I2C_ALI15X3 is not set
+# CONFIG_I2C_AMD756 is not set
+# CONFIG_I2C_AMD8111 is not set
+# CONFIG_I2C_I801 is not set
+# CONFIG_I2C_ISCH is not set
+# CONFIG_I2C_PIIX4 is not set
+# CONFIG_I2C_NFORCE2 is not set
+# CONFIG_I2C_SIS5595 is not set
+# CONFIG_I2C_SIS630 is not set
+# CONFIG_I2C_SIS96X is not set
+# CONFIG_I2C_VIA is not set
+# CONFIG_I2C_VIAPRO is not set
+
+#
+# I2C system bus drivers (mostly embedded / system-on-chip)
+#
+# CONFIG_I2C_GPIO is not set
+CONFIG_I2C_MPC=y
+# CONFIG_I2C_OCORES is not set
+# CONFIG_I2C_SIMTEC is not set
+
+#
+# External I2C/SMBus adapter drivers
+#
+# CONFIG_I2C_PARPORT_LIGHT is not set
+# CONFIG_I2C_TAOS_EVM is not set
+# CONFIG_I2C_TINY_USB is not set
+
+#
+# Graphics adapter I2C/DDC channel drivers
+#
+# CONFIG_I2C_VOODOO3 is not set
+
+#
+# Other I2C/SMBus bus drivers
+#
+# CONFIG_I2C_PCA_PLATFORM is not set
+# CONFIG_I2C_STUB is not set
+
+#
+# Miscellaneous I2C Chip support
+#
+# CONFIG_DS1682 is not set
+# CONFIG_SENSORS_PCF8574 is not set
+# CONFIG_PCF8575 is not set
+# CONFIG_SENSORS_MAX6875 is not set
+# CONFIG_SENSORS_TSL2550 is not set
+# CONFIG_I2C_DEBUG_CORE is not set
+# CONFIG_I2C_DEBUG_ALGO is not set
+# CONFIG_I2C_DEBUG_BUS is not set
+# CONFIG_I2C_DEBUG_CHIP is not set
+# CONFIG_SPI is not set
+CONFIG_ARCH_WANT_OPTIONAL_GPIOLIB=y
+CONFIG_ARCH_REQUIRE_GPIOLIB=y
+CONFIG_GPIOLIB=y
+# CONFIG_DEBUG_GPIO is not set
+CONFIG_GPIO_SYSFS=y
+
+#
+# Memory mapped GPIO expanders:
+#
+# CONFIG_GPIO_XILINX is not set
+
+#
+# I2C GPIO expanders:
+#
+# CONFIG_GPIO_MAX732X is not set
+CONFIG_GPIO_PCA953X=y
+# CONFIG_GPIO_PCF857X is not set
+
+#
+# PCI GPIO expanders:
+#
+# CONFIG_GPIO_BT8XX is not set
+
+#
+# SPI GPIO expanders:
+#
+# CONFIG_W1 is not set
+# CONFIG_POWER_SUPPLY is not set
+CONFIG_HWMON=y
+# CONFIG_HWMON_VID is not set
+# CONFIG_SENSORS_AD7414 is not set
+# CONFIG_SENSORS_AD7418 is not set
+# CONFIG_SENSORS_ADM1021 is not set
+# CONFIG_SENSORS_ADM1025 is not set
+# CONFIG_SENSORS_ADM1026 is not set
+# CONFIG_SENSORS_ADM1029 is not set
+# CONFIG_SENSORS_ADM1031 is not set
+# CONFIG_SENSORS_ADM9240 is not set
+# CONFIG_SENSORS_ADT7462 is not set
+# CONFIG_SENSORS_ADT7470 is not set
+# CONFIG_SENSORS_ADT7473 is not set
+# CONFIG_SENSORS_ADT7475 is not set
+# CONFIG_SENSORS_ATXP1 is not set
+CONFIG_SENSORS_DS1621=y
+# CONFIG_SENSORS_I5K_AMB is not set
+# CONFIG_SENSORS_F71805F is not set
+# CONFIG_SENSORS_F71882FG is not set
+# CONFIG_SENSORS_F75375S is not set
+# CONFIG_SENSORS_G760A is not set
+# CONFIG_SENSORS_GL518SM is not set
+# CONFIG_SENSORS_GL520SM is not set
+# CONFIG_SENSORS_IT87 is not set
+# CONFIG_SENSORS_LM63 is not set
+# CONFIG_SENSORS_LM75 is not set
+# CONFIG_SENSORS_LM77 is not set
+# CONFIG_SENSORS_LM78 is not set
+# CONFIG_SENSORS_LM80 is not set
+# CONFIG_SENSORS_LM83 is not set
+# CONFIG_SENSORS_LM85 is not set
+# CONFIG_SENSORS_LM87 is not set
+CONFIG_SENSORS_LM90=y
+# CONFIG_SENSORS_LM92 is not set
+# CONFIG_SENSORS_LM93 is not set
+# CONFIG_SENSORS_LTC4215 is not set
+# CONFIG_SENSORS_LTC4245 is not set
+# CONFIG_SENSORS_LM95241 is not set
+# CONFIG_SENSORS_MAX1619 is not set
+# CONFIG_SENSORS_MAX6650 is not set
+# CONFIG_SENSORS_PC87360 is not set
+# CONFIG_SENSORS_PC87427 is not set
+# CONFIG_SENSORS_PCF8591 is not set
+# CONFIG_SENSORS_SHT15 is not set
+# CONFIG_SENSORS_SIS5595 is not set
+# CONFIG_SENSORS_DME1737 is not set
+# CONFIG_SENSORS_SMSC47M1 is not set
+# CONFIG_SENSORS_SMSC47M192 is not set
+# CONFIG_SENSORS_SMSC47B397 is not set
+# CONFIG_SENSORS_ADS7828 is not set
+# CONFIG_SENSORS_THMC50 is not set
+# CONFIG_SENSORS_VIA686A is not set
+# CONFIG_SENSORS_VT1211 is not set
+# CONFIG_SENSORS_VT8231 is not set
+# CONFIG_SENSORS_W83781D is not set
+# CONFIG_SENSORS_W83791D is not set
+# CONFIG_SENSORS_W83792D is not set
+# CONFIG_SENSORS_W83793 is not set
+# CONFIG_SENSORS_W83L785TS is not set
+# CONFIG_SENSORS_W83L786NG is not set
+# CONFIG_SENSORS_W83627HF is not set
+# CONFIG_SENSORS_W83627EHF is not set
+# CONFIG_HWMON_DEBUG_CHIP is not set
+# CONFIG_THERMAL is not set
+# CONFIG_THERMAL_HWMON is not set
+CONFIG_WATCHDOG=y
+# CONFIG_WATCHDOG_NOWAYOUT is not set
+
+#
+# Watchdog Device Drivers
+#
+# CONFIG_SOFT_WATCHDOG is not set
+# CONFIG_ALIM7101_WDT is not set
+# CONFIG_BOOKE_WDT is not set
+
+#
+# PCI-based Watchdog Cards
+#
+# CONFIG_PCIPCWATCHDOG is not set
+# CONFIG_WDTPCI is not set
+
+#
+# USB-based Watchdog Cards
+#
+# CONFIG_USBPCWATCHDOG is not set
+CONFIG_SSB_POSSIBLE=y
+
+#
+# Sonics Silicon Backplane
+#
+# CONFIG_SSB is not set
+
+#
+# Multifunction device drivers
+#
+# CONFIG_MFD_CORE is not set
+# CONFIG_MFD_SM501 is not set
+# CONFIG_HTC_PASIC3 is not set
+# CONFIG_TPS65010 is not set
+# CONFIG_TWL4030_CORE is not set
+# CONFIG_MFD_TMIO is not set
+# CONFIG_PMIC_DA903X is not set
+# CONFIG_MFD_WM8400 is not set
+# CONFIG_MFD_WM8350_I2C is not set
+# CONFIG_MFD_PCF50633 is not set
+# CONFIG_REGULATOR is not set
+
+#
+# Multimedia devices
+#
+
+#
+# Multimedia core support
+#
+# CONFIG_VIDEO_DEV is not set
+# CONFIG_DVB_CORE is not set
+# CONFIG_VIDEO_MEDIA is not set
+
+#
+# Multimedia drivers
+#
+# CONFIG_DAB is not set
+
+#
+# Graphics support
+#
+# CONFIG_AGP is not set
+# CONFIG_DRM is not set
+# CONFIG_VGASTATE is not set
+CONFIG_VIDEO_OUTPUT_CONTROL=y
+# CONFIG_FB is not set
+# CONFIG_BACKLIGHT_LCD_SUPPORT is not set
+
+#
+# Display device support
+#
+# CONFIG_DISPLAY_SUPPORT is not set
+
+#
+# Console display driver support
+#
+CONFIG_VGA_CONSOLE=y
+# CONFIG_VGACON_SOFT_SCROLLBACK is not set
+CONFIG_DUMMY_CONSOLE=y
+# CONFIG_SOUND is not set
+CONFIG_HID_SUPPORT=y
+CONFIG_HID=y
+# CONFIG_HID_DEBUG is not set
+# CONFIG_HIDRAW is not set
+
+#
+# USB Input Devices
+#
+CONFIG_USB_HID=y
+# CONFIG_HID_PID is not set
+# CONFIG_USB_HIDDEV is not set
+
+#
+# Special HID drivers
+#
+# CONFIG_HID_A4TECH is not set
+# CONFIG_HID_APPLE is not set
+# CONFIG_HID_BELKIN is not set
+# CONFIG_HID_CHERRY is not set
+# CONFIG_HID_CHICONY is not set
+# CONFIG_HID_CYPRESS is not set
+# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_EZKEY is not set
+# CONFIG_HID_KYE is not set
+# CONFIG_HID_GYRATION is not set
+# CONFIG_HID_KENSINGTON is not set
+# CONFIG_HID_LOGITECH is not set
+# CONFIG_HID_MICROSOFT is not set
+# CONFIG_HID_MONTEREY is not set
+# CONFIG_HID_NTRIG is not set
+# CONFIG_HID_PANTHERLORD is not set
+# CONFIG_HID_PETALYNX is not set
+# CONFIG_HID_SAMSUNG is not set
+# CONFIG_HID_SONY is not set
+# CONFIG_HID_SUNPLUS is not set
+# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_TOPSEED is not set
+# CONFIG_THRUSTMASTER_FF is not set
+# CONFIG_ZEROPLUS_FF is not set
+CONFIG_USB_SUPPORT=y
+CONFIG_USB_ARCH_HAS_HCD=y
+CONFIG_USB_ARCH_HAS_OHCI=y
+CONFIG_USB_ARCH_HAS_EHCI=y
+CONFIG_USB=y
+# CONFIG_USB_DEBUG is not set
+# CONFIG_USB_ANNOUNCE_NEW_DEVICES is not set
+
+#
+# Miscellaneous USB options
+#
+CONFIG_USB_DEVICEFS=y
+# CONFIG_USB_DEVICE_CLASS is not set
+# CONFIG_USB_DYNAMIC_MINORS is not set
+# CONFIG_USB_OTG is not set
+# CONFIG_USB_OTG_WHITELIST is not set
+# CONFIG_USB_OTG_BLACKLIST_HUB is not set
+CONFIG_USB_MON=y
+# CONFIG_USB_WUSB is not set
+# CONFIG_USB_WUSB_CBAF is not set
+
+#
+# USB Host Controller Drivers
+#
+# CONFIG_USB_C67X00_HCD is not set
+# CONFIG_USB_EHCI_HCD is not set
+# CONFIG_USB_OXU210HP_HCD is not set
+# CONFIG_USB_ISP116X_HCD is not set
+CONFIG_USB_ISP1760_HCD=y
+# CONFIG_USB_OHCI_HCD is not set
+# CONFIG_USB_UHCI_HCD is not set
+# CONFIG_USB_SL811_HCD is not set
+# CONFIG_USB_R8A66597_HCD is not set
+# CONFIG_USB_WHCI_HCD is not set
+# CONFIG_USB_HWA_HCD is not set
+
+#
+# USB Device Class drivers
+#
+# CONFIG_USB_ACM is not set
+# CONFIG_USB_PRINTER is not set
+# CONFIG_USB_WDM is not set
+# CONFIG_USB_TMC is not set
+
+#
+# NOTE: USB_STORAGE depends on SCSI but BLK_DEV_SD may
+#
+
+#
+# also be needed; see USB_STORAGE Help for more info
+#
+CONFIG_USB_STORAGE=y
+# CONFIG_USB_STORAGE_DEBUG is not set
+# CONFIG_USB_STORAGE_DATAFAB is not set
+# CONFIG_USB_STORAGE_FREECOM is not set
+# CONFIG_USB_STORAGE_ISD200 is not set
+# CONFIG_USB_STORAGE_USBAT is not set
+# CONFIG_USB_STORAGE_SDDR09 is not set
+# CONFIG_USB_STORAGE_SDDR55 is not set
+# CONFIG_USB_STORAGE_JUMPSHOT is not set
+# CONFIG_USB_STORAGE_ALAUDA is not set
+# CONFIG_USB_STORAGE_ONETOUCH is not set
+# CONFIG_USB_STORAGE_KARMA is not set
+# CONFIG_USB_STORAGE_CYPRESS_ATACB is not set
+# CONFIG_USB_LIBUSUAL is not set
+
+#
+# USB Imaging devices
+#
+# CONFIG_USB_MDC800 is not set
+# CONFIG_USB_MICROTEK is not set
+
+#
+# USB port drivers
+#
+# CONFIG_USB_SERIAL is not set
+
+#
+# USB Miscellaneous drivers
+#
+# CONFIG_USB_EMI62 is not set
+# CONFIG_USB_EMI26 is not set
+# CONFIG_USB_ADUTUX is not set
+# CONFIG_USB_SEVSEG is not set
+# CONFIG_USB_RIO500 is not set
+# CONFIG_USB_LEGOTOWER is not set
+# CONFIG_USB_LCD is not set
+# CONFIG_USB_BERRY_CHARGE is not set
+# CONFIG_USB_LED is not set
+# CONFIG_USB_CYPRESS_CY7C63 is not set
+# CONFIG_USB_CYTHERM is not set
+# CONFIG_USB_IDMOUSE is not set
+# CONFIG_USB_FTDI_ELAN is not set
+# CONFIG_USB_APPLEDISPLAY is not set
+# CONFIG_USB_LD is not set
+# CONFIG_USB_TRANCEVIBRATOR is not set
+# CONFIG_USB_IOWARRIOR is not set
+# CONFIG_USB_TEST is not set
+# CONFIG_USB_ISIGHTFW is not set
+# CONFIG_USB_VST is not set
+# CONFIG_USB_GADGET is not set
+
+#
+# OTG and related infrastructure
+#
+# CONFIG_USB_GPIO_VBUS is not set
+# CONFIG_NOP_USB_XCEIV is not set
+# CONFIG_UWB is not set
+# CONFIG_MMC is not set
+# CONFIG_MEMSTICK is not set
+CONFIG_NEW_LEDS=y
+CONFIG_LEDS_CLASS=y
+
+#
+# LED drivers
+#
+# CONFIG_LEDS_PCA9532 is not set
+CONFIG_LEDS_GPIO=y
+CONFIG_LEDS_GPIO_PLATFORM=y
+CONFIG_LEDS_GPIO_OF=y
+# CONFIG_LEDS_LP5521 is not set
+CONFIG_LEDS_PCA955X=y
+# CONFIG_LEDS_BD2802 is not set
+
+#
+# LED Triggers
+#
+CONFIG_LEDS_TRIGGERS=y
+CONFIG_LEDS_TRIGGER_TIMER=y
+CONFIG_LEDS_TRIGGER_HEARTBEAT=y
+# CONFIG_LEDS_TRIGGER_BACKLIGHT is not set
+CONFIG_LEDS_TRIGGER_GPIO=y
+# CONFIG_LEDS_TRIGGER_DEFAULT_ON is not set
+
+#
+# iptables trigger is under Netfilter config (LED target)
+#
+# CONFIG_ACCESSIBILITY is not set
+# CONFIG_INFINIBAND is not set
+CONFIG_EDAC=y
+
+#
+# Reporting subsystems
+#
+# CONFIG_EDAC_DEBUG is not set
+CONFIG_EDAC_MM_EDAC=y
+CONFIG_EDAC_MPC85XX=y
+# CONFIG_EDAC_AMD8131 is not set
+# CONFIG_EDAC_AMD8111 is not set
+CONFIG_RTC_LIB=y
+CONFIG_RTC_CLASS=y
+CONFIG_RTC_HCTOSYS=y
+CONFIG_RTC_HCTOSYS_DEVICE="rtc0"
+# CONFIG_RTC_DEBUG is not set
+
+#
+# RTC interfaces
+#
+CONFIG_RTC_INTF_SYSFS=y
+CONFIG_RTC_INTF_PROC=y
+CONFIG_RTC_INTF_DEV=y
+# CONFIG_RTC_INTF_DEV_UIE_EMUL is not set
+# CONFIG_RTC_DRV_TEST is not set
+
+#
+# I2C RTC drivers
+#
+CONFIG_RTC_DRV_DS1307=y
+# CONFIG_RTC_DRV_DS1374 is not set
+# CONFIG_RTC_DRV_DS1672 is not set
+# CONFIG_RTC_DRV_MAX6900 is not set
+# CONFIG_RTC_DRV_RS5C372 is not set
+# CONFIG_RTC_DRV_ISL1208 is not set
+# CONFIG_RTC_DRV_X1205 is not set
+# CONFIG_RTC_DRV_PCF8563 is not set
+# CONFIG_RTC_DRV_PCF8583 is not set
+# CONFIG_RTC_DRV_M41T80 is not set
+# CONFIG_RTC_DRV_S35390A is not set
+# CONFIG_RTC_DRV_FM3130 is not set
+# CONFIG_RTC_DRV_RX8581 is not set
+
+#
+# SPI RTC drivers
+#
+
+#
+# Platform RTC drivers
+#
+CONFIG_RTC_DRV_CMOS=y
+# CONFIG_RTC_DRV_DS1286 is not set
+# CONFIG_RTC_DRV_DS1511 is not set
+# CONFIG_RTC_DRV_DS1553 is not set
+# CONFIG_RTC_DRV_DS1742 is not set
+# CONFIG_RTC_DRV_STK17TA8 is not set
+# CONFIG_RTC_DRV_M48T86 is not set
+# CONFIG_RTC_DRV_M48T35 is not set
+# CONFIG_RTC_DRV_M48T59 is not set
+# CONFIG_RTC_DRV_BQ4802 is not set
+# CONFIG_RTC_DRV_V3020 is not set
+
+#
+# on-CPU RTC drivers
+#
+# CONFIG_RTC_DRV_GENERIC is not set
+CONFIG_DMADEVICES=y
+
+#
+# DMA Devices
+#
+CONFIG_FSL_DMA=y
+CONFIG_DMA_ENGINE=y
+
+#
+# DMA Clients
+#
+CONFIG_NET_DMA=y
+# CONFIG_ASYNC_TX_DMA is not set
+# CONFIG_DMATEST is not set
+# CONFIG_AUXDISPLAY is not set
+# CONFIG_UIO is not set
+# CONFIG_STAGING is not set
+
+#
+# File systems
+#
+CONFIG_EXT2_FS=y
+# CONFIG_EXT2_FS_XATTR is not set
+# CONFIG_EXT2_FS_XIP is not set
+CONFIG_EXT3_FS=y
+# CONFIG_EXT3_DEFAULTS_TO_ORDERED is not set
+CONFIG_EXT3_FS_XATTR=y
+# CONFIG_EXT3_FS_POSIX_ACL is not set
+# CONFIG_EXT3_FS_SECURITY is not set
+# CONFIG_EXT4_FS is not set
+CONFIG_JBD=y
+CONFIG_FS_MBCACHE=y
+# CONFIG_REISERFS_FS is not set
+# CONFIG_JFS_FS is not set
+# CONFIG_FS_POSIX_ACL is not set
+CONFIG_FILE_LOCKING=y
+# CONFIG_XFS_FS is not set
+# CONFIG_GFS2_FS is not set
+# CONFIG_OCFS2_FS is not set
+# CONFIG_BTRFS_FS is not set
+CONFIG_DNOTIFY=y
+CONFIG_INOTIFY=y
+CONFIG_INOTIFY_USER=y
+# CONFIG_QUOTA is not set
+# CONFIG_AUTOFS_FS is not set
+# CONFIG_AUTOFS4_FS is not set
+# CONFIG_FUSE_FS is not set
+
+#
+# Caches
+#
+# CONFIG_FSCACHE is not set
+
+#
+# CD-ROM/DVD Filesystems
+#
+CONFIG_ISO9660_FS=y
+CONFIG_JOLIET=y
+CONFIG_ZISOFS=y
+CONFIG_UDF_FS=y
+CONFIG_UDF_NLS=y
+
+#
+# DOS/FAT/NT Filesystems
+#
+CONFIG_FAT_FS=y
+CONFIG_MSDOS_FS=y
+CONFIG_VFAT_FS=y
+CONFIG_FAT_DEFAULT_CODEPAGE=437
+CONFIG_FAT_DEFAULT_IOCHARSET="iso8859-1"
+# CONFIG_NTFS_FS is not set
+
+#
+# Pseudo filesystems
+#
+CONFIG_PROC_FS=y
+CONFIG_PROC_KCORE=y
+CONFIG_PROC_SYSCTL=y
+CONFIG_PROC_PAGE_MONITOR=y
+CONFIG_SYSFS=y
+CONFIG_TMPFS=y
+# CONFIG_TMPFS_POSIX_ACL is not set
+# CONFIG_HUGETLB_PAGE is not set
+# CONFIG_CONFIGFS_FS is not set
+CONFIG_MISC_FILESYSTEMS=y
+# CONFIG_ADFS_FS is not set
+# CONFIG_AFFS_FS is not set
+# CONFIG_HFS_FS is not set
+# CONFIG_HFSPLUS_FS is not set
+# CONFIG_BEFS_FS is not set
+# CONFIG_BFS_FS is not set
+# CONFIG_EFS_FS is not set
+CONFIG_JFFS2_FS=y
+CONFIG_JFFS2_FS_DEBUG=0
+CONFIG_JFFS2_FS_WRITEBUFFER=y
+# CONFIG_JFFS2_FS_WBUF_VERIFY is not set
+CONFIG_JFFS2_SUMMARY=y
+# CONFIG_JFFS2_FS_XATTR is not set
+# CONFIG_JFFS2_COMPRESSION_OPTIONS is not set
+CONFIG_JFFS2_ZLIB=y
+# CONFIG_JFFS2_LZO is not set
+CONFIG_JFFS2_RTIME=y
+# CONFIG_JFFS2_RUBIN is not set
+# CONFIG_CRAMFS is not set
+# CONFIG_SQUASHFS is not set
+# CONFIG_VXFS_FS is not set
+# CONFIG_MINIX_FS is not set
+# CONFIG_OMFS_FS is not set
+# CONFIG_HPFS_FS is not set
+# CONFIG_QNX4FS_FS is not set
+# CONFIG_ROMFS_FS is not set
+# CONFIG_SYSV_FS is not set
+# CONFIG_UFS_FS is not set
+# CONFIG_NILFS2_FS is not set
+CONFIG_NETWORK_FILESYSTEMS=y
+CONFIG_NFS_FS=y
+CONFIG_NFS_V3=y
+# CONFIG_NFS_V3_ACL is not set
+# CONFIG_NFS_V4 is not set
+CONFIG_ROOT_NFS=y
+CONFIG_NFSD=y
+# CONFIG_NFSD_V3 is not set
+# CONFIG_NFSD_V4 is not set
+CONFIG_LOCKD=y
+CONFIG_LOCKD_V4=y
+CONFIG_EXPORTFS=y
+CONFIG_NFS_COMMON=y
+CONFIG_SUNRPC=y
+# CONFIG_RPCSEC_GSS_KRB5 is not set
+# CONFIG_RPCSEC_GSS_SPKM3 is not set
+# CONFIG_SMB_FS is not set
+# CONFIG_CIFS is not set
+# CONFIG_NCP_FS is not set
+# CONFIG_CODA_FS is not set
+# CONFIG_AFS_FS is not set
+
+#
+# Partition Types
+#
+CONFIG_PARTITION_ADVANCED=y
+# CONFIG_ACORN_PARTITION is not set
+# CONFIG_OSF_PARTITION is not set
+# CONFIG_AMIGA_PARTITION is not set
+# CONFIG_ATARI_PARTITION is not set
+# CONFIG_MAC_PARTITION is not set
+CONFIG_MSDOS_PARTITION=y
+# CONFIG_BSD_DISKLABEL is not set
+# CONFIG_MINIX_SUBPARTITION is not set
+# CONFIG_SOLARIS_X86_PARTITION is not set
+# CONFIG_UNIXWARE_DISKLABEL is not set
+# CONFIG_LDM_PARTITION is not set
+# CONFIG_SGI_PARTITION is not set
+# CONFIG_ULTRIX_PARTITION is not set
+# CONFIG_SUN_PARTITION is not set
+# CONFIG_KARMA_PARTITION is not set
+# CONFIG_EFI_PARTITION is not set
+# CONFIG_SYSV68_PARTITION is not set
+CONFIG_NLS=y
+CONFIG_NLS_DEFAULT="iso8859-1"
+CONFIG_NLS_CODEPAGE_437=y
+# CONFIG_NLS_CODEPAGE_737 is not set
+# CONFIG_NLS_CODEPAGE_775 is not set
+# CONFIG_NLS_CODEPAGE_850 is not set
+# CONFIG_NLS_CODEPAGE_852 is not set
+# CONFIG_NLS_CODEPAGE_855 is not set
+# CONFIG_NLS_CODEPAGE_857 is not set
+# CONFIG_NLS_CODEPAGE_860 is not set
+# CONFIG_NLS_CODEPAGE_861 is not set
+# CONFIG_NLS_CODEPAGE_862 is not set
+# CONFIG_NLS_CODEPAGE_863 is not set
+# CONFIG_NLS_CODEPAGE_864 is not set
+# CONFIG_NLS_CODEPAGE_865 is not set
+# CONFIG_NLS_CODEPAGE_866 is not set
+# CONFIG_NLS_CODEPAGE_869 is not set
+# CONFIG_NLS_CODEPAGE_936 is not set
+# CONFIG_NLS_CODEPAGE_950 is not set
+# CONFIG_NLS_CODEPAGE_932 is not set
+# CONFIG_NLS_CODEPAGE_949 is not set
+# CONFIG_NLS_CODEPAGE_874 is not set
+# CONFIG_NLS_ISO8859_8 is not set
+# CONFIG_NLS_CODEPAGE_1250 is not set
+# CONFIG_NLS_CODEPAGE_1251 is not set
+# CONFIG_NLS_ASCII is not set
+CONFIG_NLS_ISO8859_1=y
+# CONFIG_NLS_ISO8859_2 is not set
+# CONFIG_NLS_ISO8859_3 is not set
+# CONFIG_NLS_ISO8859_4 is not set
+# CONFIG_NLS_ISO8859_5 is not set
+# CONFIG_NLS_ISO8859_6 is not set
+# CONFIG_NLS_ISO8859_7 is not set
+# CONFIG_NLS_ISO8859_9 is not set
+# CONFIG_NLS_ISO8859_13 is not set
+# CONFIG_NLS_ISO8859_14 is not set
+# CONFIG_NLS_ISO8859_15 is not set
+# CONFIG_NLS_KOI8_R is not set
+# CONFIG_NLS_KOI8_U is not set
+# CONFIG_NLS_UTF8 is not set
+# CONFIG_DLM is not set
+# CONFIG_BINARY_PRINTF is not set
+
+#
+# Library routines
+#
+CONFIG_BITREVERSE=y
+CONFIG_GENERIC_FIND_LAST_BIT=y
+# CONFIG_CRC_CCITT is not set
+# CONFIG_CRC16 is not set
+CONFIG_CRC_T10DIF=y
+CONFIG_CRC_ITU_T=y
+CONFIG_CRC32=y
+# CONFIG_CRC7 is not set
+# CONFIG_LIBCRC32C is not set
+CONFIG_ZLIB_INFLATE=y
+CONFIG_ZLIB_DEFLATE=y
+CONFIG_DECOMPRESS_GZIP=y
+CONFIG_HAS_IOMEM=y
+CONFIG_HAS_IOPORT=y
+CONFIG_HAS_DMA=y
+CONFIG_HAVE_LMB=y
+CONFIG_NLATTR=y
+
+#
+# Kernel hacking
+#
+# CONFIG_PRINTK_TIME is not set
+CONFIG_ENABLE_WARN_DEPRECATED=y
+CONFIG_ENABLE_MUST_CHECK=y
+CONFIG_FRAME_WARN=1024
+# CONFIG_MAGIC_SYSRQ is not set
+# CONFIG_UNUSED_SYMBOLS is not set
+# CONFIG_DEBUG_FS is not set
+# CONFIG_HEADERS_CHECK is not set
+CONFIG_DEBUG_KERNEL=y
+# CONFIG_DEBUG_SHIRQ is not set
+CONFIG_DETECT_SOFTLOCKUP=y
+# CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC is not set
+CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC_VALUE=0
+CONFIG_DETECT_HUNG_TASK=y
+# CONFIG_BOOTPARAM_HUNG_TASK_PANIC is not set
+CONFIG_BOOTPARAM_HUNG_TASK_PANIC_VALUE=0
+CONFIG_SCHED_DEBUG=y
+# CONFIG_SCHEDSTATS is not set
+# CONFIG_TIMER_STATS is not set
+# CONFIG_DEBUG_OBJECTS is not set
+# CONFIG_SLUB_DEBUG_ON is not set
+# CONFIG_SLUB_STATS is not set
+# CONFIG_DEBUG_RT_MUTEXES is not set
+# CONFIG_RT_MUTEX_TESTER is not set
+# CONFIG_DEBUG_SPINLOCK is not set
+# CONFIG_DEBUG_MUTEXES is not set
+# CONFIG_DEBUG_SPINLOCK_SLEEP is not set
+# CONFIG_DEBUG_LOCKING_API_SELFTESTS is not set
+# CONFIG_DEBUG_KOBJECT is not set
+# CONFIG_DEBUG_HIGHMEM is not set
+# CONFIG_DEBUG_BUGVERBOSE is not set
+# CONFIG_DEBUG_INFO is not set
+# CONFIG_DEBUG_VM is not set
+# CONFIG_DEBUG_WRITECOUNT is not set
+# CONFIG_DEBUG_MEMORY_INIT is not set
+# CONFIG_DEBUG_LIST is not set
+# CONFIG_DEBUG_SG is not set
+# CONFIG_DEBUG_NOTIFIERS is not set
+# CONFIG_BOOT_PRINTK_DELAY is not set
+# CONFIG_RCU_TORTURE_TEST is not set
+# CONFIG_RCU_CPU_STALL_DETECTOR is not set
+# CONFIG_BACKTRACE_SELF_TEST is not set
+# CONFIG_DEBUG_BLOCK_EXT_DEVT is not set
+# CONFIG_FAULT_INJECTION is not set
+# CONFIG_LATENCYTOP is not set
+# CONFIG_SYSCTL_SYSCALL_CHECK is not set
+# CONFIG_DEBUG_PAGEALLOC is not set
+CONFIG_HAVE_FUNCTION_TRACER=y
+CONFIG_HAVE_FUNCTION_GRAPH_TRACER=y
+CONFIG_HAVE_DYNAMIC_FTRACE=y
+CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
+CONFIG_TRACING_SUPPORT=y
+
+#
+# Tracers
+#
+# CONFIG_FUNCTION_TRACER is not set
+# CONFIG_SCHED_TRACER is not set
+# CONFIG_CONTEXT_SWITCH_TRACER is not set
+# CONFIG_EVENT_TRACER is not set
+# CONFIG_BOOT_TRACER is not set
+# CONFIG_TRACE_BRANCH_PROFILING is not set
+# CONFIG_STACK_TRACER is not set
+# CONFIG_KMEMTRACE is not set
+# CONFIG_WORKQUEUE_TRACER is not set
+# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_SAMPLES is not set
+CONFIG_HAVE_ARCH_KGDB=y
+# CONFIG_KGDB is not set
+CONFIG_PRINT_STACK_DEPTH=64
+# CONFIG_DEBUG_STACKOVERFLOW is not set
+# CONFIG_DEBUG_STACK_USAGE is not set
+# CONFIG_CODE_PATCHING_SELFTEST is not set
+# CONFIG_FTR_FIXUP_SELFTEST is not set
+# CONFIG_MSI_BITMAP_SELFTEST is not set
+# CONFIG_XMON is not set
+# CONFIG_IRQSTACKS is not set
+# CONFIG_BDI_SWITCH is not set
+# CONFIG_PPC_EARLY_DEBUG is not set
+
+#
+# Security options
+#
+# CONFIG_KEYS is not set
+# CONFIG_SECURITY is not set
+# CONFIG_SECURITYFS is not set
+# CONFIG_SECURITY_FILE_CAPABILITIES is not set
+CONFIG_CRYPTO=y
+
+#
+# Crypto core or helper
+#
+# CONFIG_CRYPTO_FIPS is not set
+CONFIG_CRYPTO_ALGAPI=y
+CONFIG_CRYPTO_ALGAPI2=y
+CONFIG_CRYPTO_AEAD2=y
+CONFIG_CRYPTO_BLKCIPHER2=y
+CONFIG_CRYPTO_HASH=y
+CONFIG_CRYPTO_HASH2=y
+CONFIG_CRYPTO_RNG2=y
+CONFIG_CRYPTO_PCOMP=y
+CONFIG_CRYPTO_MANAGER=y
+CONFIG_CRYPTO_MANAGER2=y
+# CONFIG_CRYPTO_GF128MUL is not set
+# CONFIG_CRYPTO_NULL is not set
+CONFIG_CRYPTO_WORKQUEUE=y
+# CONFIG_CRYPTO_CRYPTD is not set
+# CONFIG_CRYPTO_AUTHENC is not set
+# CONFIG_CRYPTO_TEST is not set
+
+#
+# Authenticated Encryption with Associated Data
+#
+# CONFIG_CRYPTO_CCM is not set
+# CONFIG_CRYPTO_GCM is not set
+# CONFIG_CRYPTO_SEQIV is not set
+
+#
+# Block modes
+#
+# CONFIG_CRYPTO_CBC is not set
+# CONFIG_CRYPTO_CTR is not set
+# CONFIG_CRYPTO_CTS is not set
+# CONFIG_CRYPTO_ECB is not set
+# CONFIG_CRYPTO_LRW is not set
+# CONFIG_CRYPTO_PCBC is not set
+# CONFIG_CRYPTO_XTS is not set
+
+#
+# Hash modes
+#
+CONFIG_CRYPTO_HMAC=y
+# CONFIG_CRYPTO_XCBC is not set
+
+#
+# Digest
+#
+# CONFIG_CRYPTO_CRC32C is not set
+# CONFIG_CRYPTO_MD4 is not set
+CONFIG_CRYPTO_MD5=y
+# CONFIG_CRYPTO_MICHAEL_MIC is not set
+# CONFIG_CRYPTO_RMD128 is not set
+# CONFIG_CRYPTO_RMD160 is not set
+# CONFIG_CRYPTO_RMD256 is not set
+# CONFIG_CRYPTO_RMD320 is not set
+# CONFIG_CRYPTO_SHA1 is not set
+# CONFIG_CRYPTO_SHA256 is not set
+# CONFIG_CRYPTO_SHA512 is not set
+# CONFIG_CRYPTO_TGR192 is not set
+# CONFIG_CRYPTO_WP512 is not set
+
+#
+# Ciphers
+#
+# CONFIG_CRYPTO_AES is not set
+# CONFIG_CRYPTO_ANUBIS is not set
+# CONFIG_CRYPTO_ARC4 is not set
+# CONFIG_CRYPTO_BLOWFISH is not set
+# CONFIG_CRYPTO_CAMELLIA is not set
+# CONFIG_CRYPTO_CAST5 is not set
+# CONFIG_CRYPTO_CAST6 is not set
+# CONFIG_CRYPTO_DES is not set
+# CONFIG_CRYPTO_FCRYPT is not set
+# CONFIG_CRYPTO_KHAZAD is not set
+# CONFIG_CRYPTO_SALSA20 is not set
+# CONFIG_CRYPTO_SEED is not set
+# CONFIG_CRYPTO_SERPENT is not set
+# CONFIG_CRYPTO_TEA is not set
+# CONFIG_CRYPTO_TWOFISH is not set
+
+#
+# Compression
+#
+# CONFIG_CRYPTO_DEFLATE is not set
+# CONFIG_CRYPTO_ZLIB is not set
+# CONFIG_CRYPTO_LZO is not set
+
+#
+# Random Number Generation
+#
+# CONFIG_CRYPTO_ANSI_CPRNG is not set
+CONFIG_CRYPTO_HW=y
+# CONFIG_CRYPTO_DEV_HIFN_795X is not set
+# CONFIG_CRYPTO_DEV_TALITOS is not set
+# CONFIG_PPC_CLOCK is not set
+# CONFIG_VIRTUALIZATION is not set
diff --git a/arch/powerpc/include/asm/delay.h b/arch/powerpc/include/asm/delay.h
index f9200a6..1e2eb41 100644
--- a/arch/powerpc/include/asm/delay.h
+++ b/arch/powerpc/include/asm/delay.h
@@ -2,8 +2,11 @@
 #define _ASM_POWERPC_DELAY_H
 #ifdef __KERNEL__
 
+#include <asm/time.h>
+
 /*
  * Copyright 1996, Paul Mackerras.
+ * Copyright (C) 2009 Freescale Semiconductor, Inc. All rights reserved.
  *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
@@ -30,5 +33,38 @@
 #define mdelay(n)	udelay((n) * 1000)
 #endif
 
+/**
+ * spin_event_timeout - spin until a condition gets true or a timeout elapses
+ * @condition: a C expression to evalate
+ * @timeout: timeout, in microseconds
+ * @delay: the number of microseconds to delay between each evaluation of
+ *         @condition
+ *
+ * The process spins until the condition evaluates to true (non-zero) or the
+ * timeout elapses.  The return value of this macro is the value of
+ * @condition when the loop terminates. This allows you to determine the cause
+ * of the loop terminates.  If the return value is zero, then you know a
+ * timeout has occurred.
+ *
+ * This primary purpose of this macro is to poll on a hardware register
+ * until a status bit changes.  The timeout ensures that the loop still
+ * terminates even if the bit never changes.  The delay is for devices that
+ * need a delay in between successive reads.
+ *
+ * gcc will optimize out the if-statement if @delay is a constant.
+ */
+#define spin_event_timeout(condition, timeout, delay)                          \
+({                                                                             \
+	typeof(condition) __ret;                                               \
+	unsigned long __loops = tb_ticks_per_usec * timeout;                   \
+	unsigned long __start = get_tbl();                                     \
+	while (!(__ret = (condition)) && (tb_ticks_since(__start) <= __loops)) \
+		if (delay)                                                     \
+			udelay(delay);                                         \
+		else                                                           \
+			cpu_relax();                                           \
+	__ret;		                                                       \
+})
+
 #endif /* __KERNEL__ */
 #endif /* _ASM_POWERPC_DELAY_H */
diff --git a/arch/powerpc/include/asm/fsl_lbc.h b/arch/powerpc/include/asm/fsl_lbc.h
index 63a4f77..1b5a210 100644
--- a/arch/powerpc/include/asm/fsl_lbc.h
+++ b/arch/powerpc/include/asm/fsl_lbc.h
@@ -95,8 +95,8 @@
 };
 
 struct fsl_lbc_regs {
-	struct fsl_lbc_bank bank[8];
-	u8 res0[0x28];
+	struct fsl_lbc_bank bank[12];
+	u8 res0[0x8];
 	__be32 mar;             /**< UPM Address Register */
 	u8 res1[0x4];
 	__be32 mamr;            /**< UPMA Mode Register */
diff --git a/arch/powerpc/include/asm/mpc52xx.h b/arch/powerpc/include/asm/mpc52xx.h
index 52e049c..1b4f697 100644
--- a/arch/powerpc/include/asm/mpc52xx.h
+++ b/arch/powerpc/include/asm/mpc52xx.h
@@ -16,6 +16,7 @@
 #ifndef __ASSEMBLY__
 #include <asm/types.h>
 #include <asm/prom.h>
+#include <asm/mpc5xxx.h>
 #endif /* __ASSEMBLY__ */
 
 #include <linux/suspend.h>
@@ -268,7 +269,6 @@
 #ifndef __ASSEMBLY__
 
 /* mpc52xx_common.c */
-extern unsigned int mpc52xx_find_ipb_freq(struct device_node *node);
 extern void mpc5200_setup_xlb_arbiter(void);
 extern void mpc52xx_declare_of_platform_devices(void);
 extern void mpc52xx_map_common_devices(void);
diff --git a/arch/powerpc/include/asm/mpc512x.h b/arch/powerpc/include/asm/mpc5xxx.h
similarity index 65%
rename from arch/powerpc/include/asm/mpc512x.h
rename to arch/powerpc/include/asm/mpc5xxx.h
index c48a165..5ce9c5f 100644
--- a/arch/powerpc/include/asm/mpc512x.h
+++ b/arch/powerpc/include/asm/mpc5xxx.h
@@ -4,7 +4,7 @@
  * Author: John Rigby, <jrigby@freescale.com>, Friday Apr 13 2007
  *
  * Description:
- * MPC5121 Prototypes and definitions
+ * MPC5xxx Prototypes and definitions
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by
@@ -13,10 +13,10 @@
  *
  */
 
-#ifndef __ASM_POWERPC_MPC512x_H__
-#define __ASM_POWERPC_MPC512x_H__
+#ifndef __ASM_POWERPC_MPC5xxx_H__
+#define __ASM_POWERPC_MPC5xxx_H__
 
-extern unsigned long mpc512x_find_ips_freq(struct device_node *node);
+extern unsigned long mpc5xxx_get_bus_frequency(struct device_node *node);
 
-#endif /* __ASM_POWERPC_MPC512x_H__ */
+#endif /* __ASM_POWERPC_MPC5xxx_H__ */
 
diff --git a/arch/powerpc/include/asm/pci.h b/arch/powerpc/include/asm/pci.h
index ba17d5d..d9483c5 100644
--- a/arch/powerpc/include/asm/pci.h
+++ b/arch/powerpc/include/asm/pci.h
@@ -195,19 +195,6 @@
 			struct resource *res,
 			struct pci_bus_region *region);
 
-static inline struct resource *pcibios_select_root(struct pci_dev *pdev,
-			struct resource *res)
-{
-	struct resource *root = NULL;
-
-	if (res->flags & IORESOURCE_IO)
-		root = &ioport_resource;
-	if (res->flags & IORESOURCE_MEM)
-		root = &iomem_resource;
-
-	return root;
-}
-
 extern void pcibios_claim_one_bus(struct pci_bus *b);
 
 extern void pcibios_finish_adding_to_bus(struct pci_bus *bus);
diff --git a/arch/powerpc/include/asm/reg.h b/arch/powerpc/include/asm/reg.h
index a3c28e4..1170267 100644
--- a/arch/powerpc/include/asm/reg.h
+++ b/arch/powerpc/include/asm/reg.h
@@ -755,7 +755,8 @@
 #define mfspr(rn)	({unsigned long rval; \
 			asm volatile("mfspr %0," __stringify(rn) \
 				: "=r" (rval)); rval;})
-#define mtspr(rn, v)	asm volatile("mtspr " __stringify(rn) ",%0" : : "r" (v))
+#define mtspr(rn, v)	asm volatile("mtspr " __stringify(rn) ",%0" : : "r" (v)\
+				     : "memory")
 
 #ifdef __powerpc64__
 #ifdef CONFIG_PPC_CELL
diff --git a/arch/powerpc/include/asm/reg_booke.h b/arch/powerpc/include/asm/reg_booke.h
index 601ddbc..6bcf364 100644
--- a/arch/powerpc/include/asm/reg_booke.h
+++ b/arch/powerpc/include/asm/reg_booke.h
@@ -389,12 +389,14 @@
 #define ICCR_CACHE	1		/* Cacheable */
 
 /* Bit definitions for L1CSR0. */
+#define L1CSR0_CPE	0x00010000	/* Data Cache Parity Enable */
 #define L1CSR0_CLFC	0x00000100	/* Cache Lock Bits Flash Clear */
 #define L1CSR0_DCFI	0x00000002	/* Data Cache Flash Invalidate */
 #define L1CSR0_CFI	0x00000002	/* Cache Flash Invalidate */
 #define L1CSR0_DCE	0x00000001	/* Data Cache Enable */
 
 /* Bit definitions for L1CSR1. */
+#define L1CSR1_CPE	0x00010000	/* Instruction Cache Parity Enable */
 #define L1CSR1_ICLFR	0x00000100	/* Instr Cache Lock Bits Flash Reset */
 #define L1CSR1_ICFI	0x00000002	/* Instr Cache Flash Invalidate */
 #define L1CSR1_ICE	0x00000001	/* Instr Cache Enable */
diff --git a/arch/powerpc/kernel/Makefile b/arch/powerpc/kernel/Makefile
index a9f8829..b73396b 100644
--- a/arch/powerpc/kernel/Makefile
+++ b/arch/powerpc/kernel/Makefile
@@ -4,6 +4,8 @@
 
 CFLAGS_ptrace.o		+= -DUTS_MACHINE='"$(UTS_MACHINE)"'
 
+subdir-ccflags-$(CONFIG_PPC_WERROR) := -Werror
+
 ifeq ($(CONFIG_PPC64),y)
 CFLAGS_prom_init.o	+= -mno-minimal-toc
 endif
diff --git a/arch/powerpc/kernel/cpu_setup_6xx.S b/arch/powerpc/kernel/cpu_setup_6xx.S
index 54f767e..1e9949e 100644
--- a/arch/powerpc/kernel/cpu_setup_6xx.S
+++ b/arch/powerpc/kernel/cpu_setup_6xx.S
@@ -239,6 +239,9 @@
 	ori	r11,r11,HID0_SGE | HID0_FOLD | HID0_BHTE
 	ori	r11,r11,HID0_LRSTK | HID0_BTIC
 	oris	r11,r11,HID0_DPM@h
+BEGIN_MMU_FTR_SECTION
+	oris	r11,r11,HID0_HIGH_BAT@h
+END_MMU_FTR_SECTION_IFSET(MMU_FTR_USE_HIGH_BATS)
 BEGIN_FTR_SECTION
 	xori	r11,r11,HID0_BTIC
 END_FTR_SECTION_IFSET(CPU_FTR_NO_BTIC)
diff --git a/arch/powerpc/kernel/cpu_setup_fsl_booke.S b/arch/powerpc/kernel/cpu_setup_fsl_booke.S
index eb4b9ad..0adb50a 100644
--- a/arch/powerpc/kernel/cpu_setup_fsl_booke.S
+++ b/arch/powerpc/kernel/cpu_setup_fsl_booke.S
@@ -17,6 +17,40 @@
 #include <asm/cputable.h>
 #include <asm/ppc_asm.h>
 
+_GLOBAL(__e500_icache_setup)
+	mfspr	r0, SPRN_L1CSR1
+	andi.	r3, r0, L1CSR1_ICE
+	bnelr				/* Already enabled */
+	oris	r0, r0, L1CSR1_CPE@h
+	ori	r0, r0, (L1CSR1_ICFI | L1CSR1_ICLFR |  L1CSR1_ICE)
+	mtspr	SPRN_L1CSR1, r0		/* Enable I-Cache */
+	isync
+	blr
+
+_GLOBAL(__e500_dcache_setup)
+	mfspr	r0, SPRN_L1CSR0
+	andi.	r3, r0, L1CSR0_DCE
+	bnelr				/* Already enabled */
+	msync
+	isync
+	li	r0, 0
+	mtspr	SPRN_L1CSR0, r0		/* Disable */
+	msync
+	isync
+	li	r0, (L1CSR0_DCFI | L1CSR0_CLFC)
+	mtspr	SPRN_L1CSR0, r0		/* Invalidate */
+	isync
+1:	mfspr	r0, SPRN_L1CSR0
+	andi.	r3, r0, L1CSR0_CLFC
+	bne+	1b			/* Wait for lock bits reset */
+	oris	r0, r0, L1CSR0_CPE@h
+	ori	r0, r0, L1CSR0_DCE
+	msync
+	isync
+	mtspr	SPRN_L1CSR0, r0		/* Enable */
+	isync
+	blr
+
 _GLOBAL(__setup_cpu_e200)
 	/* enable dedicated debug exception handling resources (Debug APU) */
 	mfspr	r3,SPRN_HID0
@@ -25,7 +59,16 @@
 	b	__setup_e200_ivors
 _GLOBAL(__setup_cpu_e500v1)
 _GLOBAL(__setup_cpu_e500v2)
-	b	__setup_e500_ivors
+	mflr	r4
+	bl	__e500_icache_setup
+	bl	__e500_dcache_setup
+	bl	__setup_e500_ivors
+	mtlr	r4
+	blr
 _GLOBAL(__setup_cpu_e500mc)
-	b	__setup_e500mc_ivors
-
+	mflr	r4
+	bl	__e500_icache_setup
+	bl	__e500_dcache_setup
+	bl	__setup_e500mc_ivors
+	mtlr	r4
+	blr
diff --git a/arch/powerpc/kernel/ftrace.c b/arch/powerpc/kernel/ftrace.c
index 1b12696..ce1f3e44 100644
--- a/arch/powerpc/kernel/ftrace.c
+++ b/arch/powerpc/kernel/ftrace.c
@@ -586,7 +586,7 @@
 		return;
 	}
 
-	if (ftrace_push_return_trace(old, self_addr, &trace.depth) == -EBUSY) {
+	if (ftrace_push_return_trace(old, self_addr, &trace.depth, 0) == -EBUSY) {
 		*parent = old;
 		return;
 	}
diff --git a/arch/powerpc/kernel/prom_init.c b/arch/powerpc/kernel/prom_init.c
index ef6f649..a538824 100644
--- a/arch/powerpc/kernel/prom_init.c
+++ b/arch/powerpc/kernel/prom_init.c
@@ -1947,8 +1947,47 @@
 	prom_setprop(isa, name, "ranges",
 			isa_ranges, sizeof(isa_ranges));
 }
+
+#define CPC925_MC_START		0xf8000000
+#define CPC925_MC_LENGTH	0x1000000
+/* The values for memory-controller don't have right number of cells */
+static void __init fixup_device_tree_maple_memory_controller(void)
+{
+	phandle mc;
+	u32 mc_reg[4];
+	char *name = "/hostbridge@f8000000";
+	struct prom_t *_prom = &RELOC(prom);
+	u32 ac, sc;
+
+	mc = call_prom("finddevice", 1, 1, ADDR(name));
+	if (!PHANDLE_VALID(mc))
+		return;
+
+	if (prom_getproplen(mc, "reg") != 8)
+		return;
+
+	prom_getprop(_prom->root, "#address-cells", &ac, sizeof(ac));
+	prom_getprop(_prom->root, "#size-cells", &sc, sizeof(sc));
+	if ((ac != 2) || (sc != 2))
+		return;
+
+	if (prom_getprop(mc, "reg", mc_reg, sizeof(mc_reg)) == PROM_ERROR)
+		return;
+
+	if (mc_reg[0] != CPC925_MC_START || mc_reg[1] != CPC925_MC_LENGTH)
+		return;
+
+	prom_printf("Fixing up bogus hostbridge on Maple...\n");
+
+	mc_reg[0] = 0x0;
+	mc_reg[1] = CPC925_MC_START;
+	mc_reg[2] = 0x0;
+	mc_reg[3] = CPC925_MC_LENGTH;
+	prom_setprop(mc, name, "reg", mc_reg, sizeof(mc_reg));
+}
 #else
 #define fixup_device_tree_maple()
+#define fixup_device_tree_maple_memory_controller()
 #endif
 
 #ifdef CONFIG_PPC_CHRP
@@ -2189,6 +2228,7 @@
 static void __init fixup_device_tree(void)
 {
 	fixup_device_tree_maple();
+	fixup_device_tree_maple_memory_controller();
 	fixup_device_tree_chrp();
 	fixup_device_tree_pmac();
 	fixup_device_tree_efika();
diff --git a/arch/powerpc/kvm/Makefile b/arch/powerpc/kvm/Makefile
index 4b2df66..459c7ee 100644
--- a/arch/powerpc/kvm/Makefile
+++ b/arch/powerpc/kvm/Makefile
@@ -2,6 +2,8 @@
 # Makefile for Kernel-based Virtual Machine module
 #
 
+subdir-ccflags-$(CONFIG_PPC_WERROR) := -Werror
+
 EXTRA_CFLAGS += -Ivirt/kvm -Iarch/powerpc/kvm
 
 common-objs-y = $(addprefix ../../../virt/kvm/, kvm_main.o coalesced_mmio.o)
diff --git a/arch/powerpc/lib/Makefile b/arch/powerpc/lib/Makefile
index 29b742b..3040dac 100644
--- a/arch/powerpc/lib/Makefile
+++ b/arch/powerpc/lib/Makefile
@@ -2,6 +2,8 @@
 # Makefile for ppc-specific library files..
 #
 
+subdir-ccflags-$(CONFIG_PPC_WERROR) := -Werror
+
 ifeq ($(CONFIG_PPC64),y)
 EXTRA_CFLAGS		+= -mno-minimal-toc
 endif
diff --git a/arch/powerpc/mm/Makefile b/arch/powerpc/mm/Makefile
index c4bcf07..2d2192e 100644
--- a/arch/powerpc/mm/Makefile
+++ b/arch/powerpc/mm/Makefile
@@ -2,6 +2,8 @@
 # Makefile for the linux ppc-specific parts of the memory manager.
 #
 
+subdir-ccflags-$(CONFIG_PPC_WERROR) := -Werror
+
 ifeq ($(CONFIG_PPC64),y)
 EXTRA_CFLAGS	+= -mno-minimal-toc
 endif
diff --git a/arch/powerpc/oprofile/Makefile b/arch/powerpc/oprofile/Makefile
index 2ef6b0d..73e1c2c 100644
--- a/arch/powerpc/oprofile/Makefile
+++ b/arch/powerpc/oprofile/Makefile
@@ -1,3 +1,5 @@
+subdir-ccflags-$(CONFIG_PPC_WERROR) := -Werror
+
 ifeq ($(CONFIG_PPC64),y)
 EXTRA_CFLAGS	+= -mno-minimal-toc
 endif
diff --git a/arch/powerpc/platforms/44x/warp.c b/arch/powerpc/platforms/44x/warp.c
index c511880..42e09a9 100644
--- a/arch/powerpc/platforms/44x/warp.c
+++ b/arch/powerpc/platforms/44x/warp.c
@@ -43,7 +43,13 @@
 {
 	unsigned long root = of_get_flat_dt_root();
 
-	return of_flat_dt_is_compatible(root, "pika,warp");
+	if (!of_flat_dt_is_compatible(root, "pika,warp"))
+		return 0;
+
+	/* For __dma_alloc_coherent */
+	ISA_DMA_THRESHOLD = ~0L;
+
+	return 1;
 }
 
 define_machine(warp) {
diff --git a/arch/powerpc/platforms/512x/clock.c b/arch/powerpc/platforms/512x/clock.c
index 1bcff94..84544d0 100644
--- a/arch/powerpc/platforms/512x/clock.c
+++ b/arch/powerpc/platforms/512x/clock.c
@@ -24,7 +24,7 @@
 #include <linux/io.h>
 
 #include <linux/of_platform.h>
-#include <asm/mpc512x.h>
+#include <asm/mpc5xxx.h>
 #include <asm/clk_interface.h>
 
 #undef CLK_DEBUG
@@ -83,13 +83,13 @@
 	mutex_lock(&clocks_mutex);
 	printk(KERN_INFO "CLOCKS:\n");
 	list_for_each_entry(p, &clocks, node) {
-		printk(KERN_INFO "  %s %ld", p->name, p->rate);
+		pr_info("  %s=%ld", p->name, p->rate);
 		if (p->parent)
-			printk(KERN_INFO " %s %ld", p->parent->name,
+			pr_cont(" %s=%ld", p->parent->name,
 			       p->parent->rate);
 		if (p->flags & CLK_HAS_CTRL)
-			printk(KERN_INFO " reg/bit %d/%d", p->reg, p->bit);
-		printk("\n");
+			pr_cont(" reg/bit=%d/%d", p->reg, p->bit);
+		pr_cont("\n");
 	}
 	mutex_unlock(&clocks_mutex);
 }
diff --git a/arch/powerpc/platforms/512x/mpc512x.h b/arch/powerpc/platforms/512x/mpc512x.h
index 9c03693..22a5352 100644
--- a/arch/powerpc/platforms/512x/mpc512x.h
+++ b/arch/powerpc/platforms/512x/mpc512x.h
@@ -11,7 +11,6 @@
 
 #ifndef __MPC512X_H__
 #define __MPC512X_H__
-extern unsigned long mpc512x_find_ips_freq(struct device_node *node);
 extern void __init mpc512x_init_IRQ(void);
 void __init mpc512x_declare_of_platform_devices(void);
 #endif				/* __MPC512X_H__ */
diff --git a/arch/powerpc/platforms/512x/mpc512x_shared.c b/arch/powerpc/platforms/512x/mpc512x_shared.c
index d8cd579..434d683 100644
--- a/arch/powerpc/platforms/512x/mpc512x_shared.c
+++ b/arch/powerpc/platforms/512x/mpc512x_shared.c
@@ -24,29 +24,6 @@
 
 #include "mpc512x.h"
 
-unsigned long
-mpc512x_find_ips_freq(struct device_node *node)
-{
-	struct device_node *np;
-	const unsigned int *p_ips_freq = NULL;
-
-	of_node_get(node);
-	while (node) {
-		p_ips_freq = of_get_property(node, "bus-frequency", NULL);
-		if (p_ips_freq)
-			break;
-
-		np = of_get_parent(node);
-		of_node_put(node);
-		node = np;
-	}
-	if (node)
-		of_node_put(node);
-
-	return p_ips_freq ? *p_ips_freq : 0;
-}
-EXPORT_SYMBOL(mpc512x_find_ips_freq);
-
 void __init mpc512x_init_IRQ(void)
 {
 	struct device_node *np;
diff --git a/arch/powerpc/platforms/52xx/mpc52xx_common.c b/arch/powerpc/platforms/52xx/mpc52xx_common.c
index 8e3dd5a..a46bad0 100644
--- a/arch/powerpc/platforms/52xx/mpc52xx_common.c
+++ b/arch/powerpc/platforms/52xx/mpc52xx_common.c
@@ -47,36 +47,6 @@
 static struct mpc52xx_gpt __iomem *mpc52xx_wdt;
 static struct mpc52xx_cdm __iomem *mpc52xx_cdm;
 
-/**
- * 	mpc52xx_find_ipb_freq - Find the IPB bus frequency for a device
- * 	@node:	device node
- *
- * 	Returns IPB bus frequency, or 0 if the bus frequency cannot be found.
- */
-unsigned int
-mpc52xx_find_ipb_freq(struct device_node *node)
-{
-	struct device_node *np;
-	const unsigned int *p_ipb_freq = NULL;
-
-	of_node_get(node);
-	while (node) {
-		p_ipb_freq = of_get_property(node, "bus-frequency", NULL);
-		if (p_ipb_freq)
-			break;
-
-		np = of_get_parent(node);
-		of_node_put(node);
-		node = np;
-	}
-	if (node)
-		of_node_put(node);
-
-	return p_ipb_freq ? *p_ipb_freq : 0;
-}
-EXPORT_SYMBOL(mpc52xx_find_ipb_freq);
-
-
 /*
  * Configure the XLB arbiter settings to match what Linux expects.
  */
@@ -221,7 +191,7 @@
 	if (!mpc52xx_cdm)
 		return 0;
 
-	freq = mpc52xx_find_ipb_freq(node);
+	freq = mpc5xxx_get_bus_frequency(node);
 	if (!freq)
 		return 0;
 
diff --git a/arch/powerpc/platforms/83xx/Kconfig b/arch/powerpc/platforms/83xx/Kconfig
index 437d29a..083ebee 100644
--- a/arch/powerpc/platforms/83xx/Kconfig
+++ b/arch/powerpc/platforms/83xx/Kconfig
@@ -96,6 +96,13 @@
 	  This enables support for the Analogue & Micro ASP 83xx
 	  board.
 
+config KMETER1
+	bool "Keymile KMETER1"
+	select DEFAULT_UIMAGE
+	select QUICC_ENGINE
+	help
+	  This enables support for the Keymile KMETER1 board.
+
 
 endif
 
diff --git a/arch/powerpc/platforms/83xx/Makefile b/arch/powerpc/platforms/83xx/Makefile
index 051777c..e139c36 100644
--- a/arch/powerpc/platforms/83xx/Makefile
+++ b/arch/powerpc/platforms/83xx/Makefile
@@ -15,3 +15,4 @@
 obj-$(CONFIG_SBC834x)		+= sbc834x.o
 obj-$(CONFIG_MPC837x_RDB)	+= mpc837x_rdb.o
 obj-$(CONFIG_ASP834x)		+= asp834x.o
+obj-$(CONFIG_KMETER1)		+= kmeter1.o
diff --git a/arch/powerpc/platforms/83xx/kmeter1.c b/arch/powerpc/platforms/83xx/kmeter1.c
new file mode 100644
index 0000000..903acfd
--- /dev/null
+++ b/arch/powerpc/platforms/83xx/kmeter1.c
@@ -0,0 +1,191 @@
+/*
+ * Copyright 2008 DENX Software Engineering GmbH
+ * Author: Heiko Schocher <hs@denx.de>
+ *
+ * Description:
+ * Keymile KMETER1 board specific routines.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under  the terms of  the GNU General  Public License as published by the
+ * Free Software Foundation;  either version 2 of the  License, or (at your
+ * option) any later version.
+ */
+
+#include <linux/stddef.h>
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/errno.h>
+#include <linux/reboot.h>
+#include <linux/pci.h>
+#include <linux/kdev_t.h>
+#include <linux/major.h>
+#include <linux/console.h>
+#include <linux/delay.h>
+#include <linux/seq_file.h>
+#include <linux/root_dev.h>
+#include <linux/initrd.h>
+#include <linux/of_platform.h>
+#include <linux/of_device.h>
+
+#include <asm/system.h>
+#include <asm/atomic.h>
+#include <asm/time.h>
+#include <asm/io.h>
+#include <asm/machdep.h>
+#include <asm/ipic.h>
+#include <asm/irq.h>
+#include <asm/prom.h>
+#include <asm/udbg.h>
+#include <sysdev/fsl_soc.h>
+#include <sysdev/fsl_pci.h>
+#include <asm/qe.h>
+#include <asm/qe_ic.h>
+
+#include "mpc83xx.h"
+
+#define SVR_REV(svr)    (((svr) >>  0) & 0xFFFF) /* Revision field */
+/* ************************************************************************
+ *
+ * Setup the architecture
+ *
+ */
+static void __init kmeter1_setup_arch(void)
+{
+	struct device_node *np;
+
+	if (ppc_md.progress)
+		ppc_md.progress("kmeter1_setup_arch()", 0);
+
+#ifdef CONFIG_PCI
+	for_each_compatible_node(np, "pci", "fsl,mpc8349-pci")
+		mpc83xx_add_bridge(np);
+#endif
+
+#ifdef CONFIG_QUICC_ENGINE
+	qe_reset();
+
+	np = of_find_node_by_name(NULL, "par_io");
+	if (np != NULL) {
+		par_io_init(np);
+		of_node_put(np);
+
+		for (np = NULL; (np = of_find_node_by_name(np, "ucc")) != NULL;)
+			par_io_of_config(np);
+	}
+
+	np = of_find_compatible_node(NULL, "network", "ucc_geth");
+	if (np != NULL) {
+		uint svid;
+
+		/* handle mpc8360ea rev.2.1 erratum 2: RGMII Timing */
+		svid = mfspr(SPRN_SVR);
+		if (SVR_REV(svid) == 0x0021) {
+			struct	device_node *np_par;
+			struct	resource res;
+			void	__iomem *base;
+			int	ret;
+
+			np_par = of_find_node_by_name(NULL, "par_io");
+			if (np_par == NULL) {
+				printk(KERN_WARNING "%s couldn;t find par_io node\n",
+					__func__);
+				return;
+			}
+			/* Map Parallel I/O ports registers */
+			ret = of_address_to_resource(np_par, 0, &res);
+			if (ret) {
+				printk(KERN_WARNING "%s couldn;t map par_io registers\n",
+					__func__);
+				return;
+			}
+			base = ioremap(res.start, res.end - res.start + 1);
+
+			/*
+			 * IMMR + 0x14A8[4:5] = 11 (clk delay for UCC 2)
+			 * IMMR + 0x14A8[18:19] = 11 (clk delay for UCC 1)
+			 */
+			setbits32((base + 0xa8), 0x0c003000);
+
+			/*
+			 * IMMR + 0x14AC[20:27] = 10101010
+			 * (data delay for both UCC's)
+			 */
+			clrsetbits_be32((base + 0xac), 0xff0, 0xaa0);
+			iounmap(base);
+			of_node_put(np_par);
+		}
+		of_node_put(np);
+	}
+#endif				/* CONFIG_QUICC_ENGINE */
+}
+
+static struct of_device_id kmeter_ids[] = {
+	{ .type = "soc", },
+	{ .compatible = "soc", },
+	{ .compatible = "simple-bus", },
+	{ .type = "qe", },
+	{ .compatible = "fsl,qe", },
+	{},
+};
+
+static int __init kmeter_declare_of_platform_devices(void)
+{
+	/* Publish the QE devices */
+	of_platform_bus_probe(NULL, kmeter_ids, NULL);
+
+	return 0;
+}
+machine_device_initcall(kmeter1, kmeter_declare_of_platform_devices);
+
+static void __init kmeter1_init_IRQ(void)
+{
+	struct device_node *np;
+
+	np = of_find_compatible_node(NULL, NULL, "fsl,pq2pro-pic");
+	if (!np) {
+		np = of_find_node_by_type(NULL, "ipic");
+		if (!np)
+			return;
+	}
+
+	ipic_init(np, 0);
+
+	/* Initialize the default interrupt mapping priorities,
+	 * in case the boot rom changed something on us.
+	 */
+	ipic_set_default_priority();
+	of_node_put(np);
+
+#ifdef CONFIG_QUICC_ENGINE
+	np = of_find_compatible_node(NULL, NULL, "fsl,qe-ic");
+	if (!np) {
+		np = of_find_node_by_type(NULL, "qeic");
+		if (!np)
+			return;
+	}
+	qe_ic_init(np, 0, qe_ic_cascade_low_ipic, qe_ic_cascade_high_ipic);
+	of_node_put(np);
+#endif				/* CONFIG_QUICC_ENGINE */
+}
+
+/*
+ * Called very early, MMU is off, device-tree isn't unflattened
+ */
+static int __init kmeter1_probe(void)
+{
+	unsigned long root = of_get_flat_dt_root();
+
+	return of_flat_dt_is_compatible(root, "keymile,KMETER1");
+}
+
+define_machine(kmeter1) {
+	.name		= "KMETER1",
+	.probe		= kmeter1_probe,
+	.setup_arch	= kmeter1_setup_arch,
+	.init_IRQ	= kmeter1_init_IRQ,
+	.get_irq	= ipic_get_irq,
+	.restart	= mpc83xx_restart,
+	.time_init	= mpc83xx_time_init,
+	.calibrate_decr	= generic_calibrate_decr,
+	.progress	= udbg_progress,
+};
diff --git a/arch/powerpc/platforms/83xx/mpc83xx.h b/arch/powerpc/platforms/83xx/mpc83xx.h
index 83cfe51..d1dc5b0 100644
--- a/arch/powerpc/platforms/83xx/mpc83xx.h
+++ b/arch/powerpc/platforms/83xx/mpc83xx.h
@@ -22,8 +22,8 @@
 /* system i/o configuration register low */
 #define MPC83XX_SICRL_OFFS         0x114
 #define MPC834X_SICRL_USB_MASK     0x60000000
-#define MPC834X_SICRL_USB0         0x40000000
-#define MPC834X_SICRL_USB1         0x20000000
+#define MPC834X_SICRL_USB0         0x20000000
+#define MPC834X_SICRL_USB1         0x40000000
 #define MPC831X_SICRL_USB_MASK     0x00000c00
 #define MPC831X_SICRL_USB_ULPI     0x00000800
 #define MPC8315_SICRL_USB_MASK     0x000000fc
diff --git a/arch/powerpc/platforms/83xx/usb.c b/arch/powerpc/platforms/83xx/usb.c
index 11e1fac..3ba4bb7 100644
--- a/arch/powerpc/platforms/83xx/usb.c
+++ b/arch/powerpc/platforms/83xx/usb.c
@@ -47,25 +47,25 @@
 		sccr |= MPC83XX_SCCR_USB_DRCM_11;  /* 1:3 */
 
 		prop = of_get_property(np, "phy_type", NULL);
+		port1_is_dr = 1;
 		if (prop && (!strcmp(prop, "utmi") ||
 					!strcmp(prop, "utmi_wide"))) {
 			sicrl |= MPC834X_SICRL_USB0 | MPC834X_SICRL_USB1;
 			sicrh |= MPC834X_SICRH_USB_UTMI;
-			port1_is_dr = 1;
+			port0_is_dr = 1;
 		} else if (prop && !strcmp(prop, "serial")) {
 			dr_mode = of_get_property(np, "dr_mode", NULL);
 			if (dr_mode && !strcmp(dr_mode, "otg")) {
 				sicrl |= MPC834X_SICRL_USB0 | MPC834X_SICRL_USB1;
-				port1_is_dr = 1;
+				port0_is_dr = 1;
 			} else {
-				sicrl |= MPC834X_SICRL_USB0;
+				sicrl |= MPC834X_SICRL_USB1;
 			}
 		} else if (prop && !strcmp(prop, "ulpi")) {
-			sicrl |= MPC834X_SICRL_USB0;
+			sicrl |= MPC834X_SICRL_USB1;
 		} else {
 			printk(KERN_WARNING "834x USB PHY type not supported\n");
 		}
-		port0_is_dr = 1;
 		of_node_put(np);
 	}
 	np = of_find_compatible_node(NULL, NULL, "fsl-usb2-mph");
diff --git a/arch/powerpc/platforms/85xx/Kconfig b/arch/powerpc/platforms/85xx/Kconfig
index 43d385c..a9b4166 100644
--- a/arch/powerpc/platforms/85xx/Kconfig
+++ b/arch/powerpc/platforms/85xx/Kconfig
@@ -35,12 +35,14 @@
 	select DEFAULT_UIMAGE
 	select PHYLIB
 	select HAS_RAPIDIO
+	select SWIOTLB
 	help
 	  This option enables support for the MPC85xx MDS board
 
 config MPC8536_DS
 	bool "Freescale MPC8536 DS"
 	select DEFAULT_UIMAGE
+	select SWIOTLB
 	help
 	  This option enables support for the MPC8536 DS board
 
@@ -49,6 +51,7 @@
 	select PPC_I8259
 	select DEFAULT_UIMAGE
 	select FSL_ULI1575
+	select SWIOTLB
 	help
 	  This option enables support for the MPC85xx DS (MPC8544 DS) board
 
@@ -64,6 +67,16 @@
         help
           This option enables support for the Emerson KSI8560 board
 
+config XES_MPC85xx
+	bool "X-ES single-board computer"
+	select DEFAULT_UIMAGE
+	help
+	  This option enables support for the various single-board
+	  computers from Extreme Engineering Solutions (X-ES) based on
+	  Freescale MPC85xx processors.
+	  Manufacturer: Extreme Engineering Solutions, Inc.
+	  URL: <http://www.xes-inc.com/>
+
 config STX_GP3
 	bool "Silicon Turnkey Express GP3"
 	help
diff --git a/arch/powerpc/platforms/85xx/Makefile b/arch/powerpc/platforms/85xx/Makefile
index a857b35..835733f 100644
--- a/arch/powerpc/platforms/85xx/Makefile
+++ b/arch/powerpc/platforms/85xx/Makefile
@@ -15,3 +15,4 @@
 obj-$(CONFIG_SBC8548)     += sbc8548.o
 obj-$(CONFIG_SOCRATES)    += socrates.o socrates_fpga_pic.o
 obj-$(CONFIG_KSI8560)	  += ksi8560.o
+obj-$(CONFIG_XES_MPC85xx) += xes_mpc85xx.o
\ No newline at end of file
diff --git a/arch/powerpc/platforms/85xx/mpc8536_ds.c b/arch/powerpc/platforms/85xx/mpc8536_ds.c
index 63efca2..055ff41 100644
--- a/arch/powerpc/platforms/85xx/mpc8536_ds.c
+++ b/arch/powerpc/platforms/85xx/mpc8536_ds.c
@@ -17,6 +17,7 @@
 #include <linux/seq_file.h>
 #include <linux/interrupt.h>
 #include <linux/of_platform.h>
+#include <linux/lmb.h>
 
 #include <asm/system.h>
 #include <asm/time.h>
@@ -26,6 +27,7 @@
 #include <asm/prom.h>
 #include <asm/udbg.h>
 #include <asm/mpic.h>
+#include <asm/swiotlb.h>
 
 #include <sysdev/fsl_soc.h>
 #include <sysdev/fsl_pci.h>
@@ -65,7 +67,9 @@
 {
 #ifdef CONFIG_PCI
 	struct device_node *np;
+	struct pci_controller *hose;
 #endif
+	dma_addr_t max = 0xffffffff;
 
 	if (ppc_md.progress)
 		ppc_md.progress("mpc8536_ds_setup_arch()", 0);
@@ -80,11 +84,22 @@
 				fsl_add_bridge(np, 1);
 			else
 				fsl_add_bridge(np, 0);
+
+			hose = pci_find_hose_for_OF_device(np);
+			max = min(max, hose->dma_window_base_cur +
+					hose->dma_window_size);
 		}
 	}
 
 #endif
 
+#ifdef CONFIG_SWIOTLB
+	if (lmb_end_of_DRAM() > max) {
+		ppc_swiotlb_enable = 1;
+		set_pci_dma_ops(&swiotlb_pci_dma_ops);
+	}
+#endif
+
 	printk("MPC8536 DS board from Freescale Semiconductor\n");
 }
 
@@ -102,6 +117,8 @@
 }
 machine_device_initcall(mpc8536_ds, mpc8536_ds_publish_devices);
 
+machine_arch_initcall(mpc8536_ds, swiotlb_setup_bus_notifier);
+
 /*
  * Called very early, device-tree isn't unflattened
  */
diff --git a/arch/powerpc/platforms/85xx/mpc85xx_ds.c b/arch/powerpc/platforms/85xx/mpc85xx_ds.c
index 53d5851..849c0ac 100644
--- a/arch/powerpc/platforms/85xx/mpc85xx_ds.c
+++ b/arch/powerpc/platforms/85xx/mpc85xx_ds.c
@@ -20,6 +20,7 @@
 #include <linux/seq_file.h>
 #include <linux/interrupt.h>
 #include <linux/of_platform.h>
+#include <linux/lmb.h>
 
 #include <asm/system.h>
 #include <asm/time.h>
@@ -30,6 +31,7 @@
 #include <asm/udbg.h>
 #include <asm/mpic.h>
 #include <asm/i8259.h>
+#include <asm/swiotlb.h>
 
 #include <sysdev/fsl_soc.h>
 #include <sysdev/fsl_pci.h>
@@ -155,7 +157,9 @@
 {
 #ifdef CONFIG_PCI
 	struct device_node *np;
+	struct pci_controller *hose;
 #endif
+	dma_addr_t max = 0xffffffff;
 
 	if (ppc_md.progress)
 		ppc_md.progress("mpc85xx_ds_setup_arch()", 0);
@@ -171,6 +175,10 @@
 				fsl_add_bridge(np, 1);
 			else
 				fsl_add_bridge(np, 0);
+
+			hose = pci_find_hose_for_OF_device(np);
+			max = min(max, hose->dma_window_base_cur +
+					hose->dma_window_size);
 		}
 	}
 
@@ -181,6 +189,13 @@
 	mpc85xx_smp_init();
 #endif
 
+#ifdef CONFIG_SWIOTLB
+	if (lmb_end_of_DRAM() > max) {
+		ppc_swiotlb_enable = 1;
+		set_pci_dma_ops(&swiotlb_pci_dma_ops);
+	}
+#endif
+
 	printk("MPC85xx DS board from Freescale Semiconductor\n");
 }
 
@@ -217,6 +232,10 @@
 machine_device_initcall(mpc8572_ds, mpc85xxds_publish_devices);
 machine_device_initcall(p2020_ds, mpc85xxds_publish_devices);
 
+machine_arch_initcall(mpc8544_ds, swiotlb_setup_bus_notifier);
+machine_arch_initcall(mpc8572_ds, swiotlb_setup_bus_notifier);
+machine_arch_initcall(p2020_ds, swiotlb_setup_bus_notifier);
+
 /*
  * Called very early, device-tree isn't unflattened
  */
diff --git a/arch/powerpc/platforms/85xx/mpc85xx_mds.c b/arch/powerpc/platforms/85xx/mpc85xx_mds.c
index b2c0a43..77f90b3 100644
--- a/arch/powerpc/platforms/85xx/mpc85xx_mds.c
+++ b/arch/powerpc/platforms/85xx/mpc85xx_mds.c
@@ -33,6 +33,7 @@
 #include <linux/of_platform.h>
 #include <linux/of_device.h>
 #include <linux/phy.h>
+#include <linux/lmb.h>
 
 #include <asm/system.h>
 #include <asm/atomic.h>
@@ -49,6 +50,7 @@
 #include <asm/qe.h>
 #include <asm/qe_ic.h>
 #include <asm/mpic.h>
+#include <asm/swiotlb.h>
 
 #undef DEBUG
 #ifdef DEBUG
@@ -155,6 +157,10 @@
 {
 	struct device_node *np;
 	static u8 __iomem *bcsr_regs = NULL;
+#ifdef CONFIG_PCI
+	struct pci_controller *hose;
+#endif
+	dma_addr_t max = 0xffffffff;
 
 	if (ppc_md.progress)
 		ppc_md.progress("mpc85xx_mds_setup_arch()", 0);
@@ -179,6 +185,10 @@
 				fsl_add_bridge(np, 1);
 			else
 				fsl_add_bridge(np, 0);
+
+			hose = pci_find_hose_for_OF_device(np);
+			max = min(max, hose->dma_window_base_cur +
+					hose->dma_window_size);
 		}
 	}
 #endif
@@ -227,6 +237,13 @@
 		iounmap(bcsr_regs);
 	}
 #endif	/* CONFIG_QUICC_ENGINE */
+
+#ifdef CONFIG_SWIOTLB
+	if (lmb_end_of_DRAM() > max) {
+		ppc_swiotlb_enable = 1;
+		set_pci_dma_ops(&swiotlb_pci_dma_ops);
+	}
+#endif
 }
 
 
@@ -281,6 +298,9 @@
 machine_device_initcall(mpc8568_mds, mpc85xx_publish_devices);
 machine_device_initcall(mpc8569_mds, mpc85xx_publish_devices);
 
+machine_arch_initcall(mpc8568_mds, swiotlb_setup_bus_notifier);
+machine_arch_initcall(mpc8569_mds, swiotlb_setup_bus_notifier);
+
 static void __init mpc85xx_mds_pic_init(void)
 {
 	struct mpic *mpic;
diff --git a/arch/powerpc/platforms/85xx/xes_mpc85xx.c b/arch/powerpc/platforms/85xx/xes_mpc85xx.c
new file mode 100644
index 0000000..ee01532
--- /dev/null
+++ b/arch/powerpc/platforms/85xx/xes_mpc85xx.c
@@ -0,0 +1,282 @@
+/*
+ * Copyright (C) 2009 Extreme Engineering Solutions, Inc.
+ *
+ * X-ES board-specific functionality
+ *
+ * Based on mpc85xx_ds code from Freescale Semiconductor, Inc.
+ *
+ * Author: Nate Case <ncase@xes-inc.com>
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+
+#include <linux/stddef.h>
+#include <linux/kernel.h>
+#include <linux/pci.h>
+#include <linux/kdev_t.h>
+#include <linux/delay.h>
+#include <linux/seq_file.h>
+#include <linux/interrupt.h>
+#include <linux/of_platform.h>
+
+#include <asm/system.h>
+#include <asm/time.h>
+#include <asm/machdep.h>
+#include <asm/pci-bridge.h>
+#include <mm/mmu_decl.h>
+#include <asm/prom.h>
+#include <asm/udbg.h>
+#include <asm/mpic.h>
+
+#include <sysdev/fsl_soc.h>
+#include <sysdev/fsl_pci.h>
+#include <linux/of_platform.h>
+
+/* A few bit definitions needed for fixups on some boards */
+#define MPC85xx_L2CTL_L2E		0x80000000 /* L2 enable */
+#define MPC85xx_L2CTL_L2I		0x40000000 /* L2 flash invalidate */
+#define MPC85xx_L2CTL_L2SIZ_MASK	0x30000000 /* L2 SRAM size (R/O) */
+
+void __init xes_mpc85xx_pic_init(void)
+{
+	struct mpic *mpic;
+	struct resource r;
+	struct device_node *np;
+
+	np = of_find_node_by_type(NULL, "open-pic");
+	if (np == NULL) {
+		printk(KERN_ERR "Could not find open-pic node\n");
+		return;
+	}
+
+	if (of_address_to_resource(np, 0, &r)) {
+		printk(KERN_ERR "Failed to map mpic register space\n");
+		of_node_put(np);
+		return;
+	}
+
+	mpic = mpic_alloc(np, r.start,
+			  MPIC_PRIMARY | MPIC_WANTS_RESET |
+			  MPIC_BIG_ENDIAN | MPIC_BROKEN_FRR_NIRQS,
+			0, 256, " OpenPIC  ");
+	BUG_ON(mpic == NULL);
+	of_node_put(np);
+
+	mpic_init(mpic);
+}
+
+static void xes_mpc85xx_configure_l2(void __iomem *l2_base)
+{
+	volatile uint32_t ctl, tmp;
+
+	asm volatile("msync; isync");
+	tmp = in_be32(l2_base);
+
+	/*
+	 * xMon may have enabled part of L2 as SRAM, so we need to set it
+	 * up for all cache mode just to be safe.
+	 */
+	printk(KERN_INFO "xes_mpc85xx: Enabling L2 as cache\n");
+
+	ctl = MPC85xx_L2CTL_L2E | MPC85xx_L2CTL_L2I;
+	if (machine_is_compatible("MPC8540") ||
+	    machine_is_compatible("MPC8560"))
+		/*
+		 * Assume L2 SRAM is used fully for cache, so set
+		 * L2BLKSZ (bits 4:5) to match L2SIZ (bits 2:3).
+		 */
+		ctl |= (tmp & MPC85xx_L2CTL_L2SIZ_MASK) >> 2;
+
+	asm volatile("msync; isync");
+	out_be32(l2_base, ctl);
+	asm volatile("msync; isync");
+}
+
+static void xes_mpc85xx_fixups(void)
+{
+	struct device_node *np;
+	int err;
+
+	/*
+	 * Legacy xMon firmware on some X-ES boards does not enable L2
+	 * as cache.  We must ensure that they get enabled here.
+	 */
+	for_each_node_by_name(np, "l2-cache-controller") {
+		struct resource r[2];
+		void __iomem *l2_base;
+
+		/* Only MPC8548, MPC8540, and MPC8560 boards are affected */
+		if (!of_device_is_compatible(np,
+				    "fsl,mpc8548-l2-cache-controller") &&
+		    !of_device_is_compatible(np,
+				    "fsl,mpc8540-l2-cache-controller") &&
+		    !of_device_is_compatible(np,
+				    "fsl,mpc8560-l2-cache-controller"))
+			continue;
+
+		err = of_address_to_resource(np, 0, &r[0]);
+		if (err) {
+			printk(KERN_WARNING "xes_mpc85xx: Could not get "
+			       "resource for device tree node '%s'",
+			       np->full_name);
+			continue;
+		}
+
+		l2_base = ioremap(r[0].start, r[0].end - r[0].start + 1);
+
+		xes_mpc85xx_configure_l2(l2_base);
+	}
+}
+
+#ifdef CONFIG_PCI
+static int primary_phb_addr;
+#endif
+
+/*
+ * Setup the architecture
+ */
+#ifdef CONFIG_SMP
+extern void __init mpc85xx_smp_init(void);
+#endif
+static void __init xes_mpc85xx_setup_arch(void)
+{
+#ifdef CONFIG_PCI
+	struct device_node *np;
+#endif
+	struct device_node *root;
+	const char *model = "Unknown";
+
+	root = of_find_node_by_path("/");
+	if (root == NULL)
+		return;
+
+	model = of_get_property(root, "model", NULL);
+
+	printk(KERN_INFO "X-ES MPC85xx-based single-board computer: %s\n",
+	       model + strlen("xes,"));
+
+	xes_mpc85xx_fixups();
+
+#ifdef CONFIG_PCI
+	for_each_node_by_type(np, "pci") {
+		if (of_device_is_compatible(np, "fsl,mpc8540-pci") ||
+		    of_device_is_compatible(np, "fsl,mpc8548-pcie")) {
+			struct resource rsrc;
+			of_address_to_resource(np, 0, &rsrc);
+			if ((rsrc.start & 0xfffff) == primary_phb_addr)
+				fsl_add_bridge(np, 1);
+			else
+				fsl_add_bridge(np, 0);
+		}
+	}
+#endif
+
+#ifdef CONFIG_SMP
+	mpc85xx_smp_init();
+#endif
+}
+
+static struct of_device_id __initdata xes_mpc85xx_ids[] = {
+	{ .type = "soc", },
+	{ .compatible = "soc", },
+	{ .compatible = "simple-bus", },
+	{ .compatible = "gianfar", },
+	{},
+};
+
+static int __init xes_mpc85xx_publish_devices(void)
+{
+	return of_platform_bus_probe(NULL, xes_mpc85xx_ids, NULL);
+}
+machine_device_initcall(xes_mpc8572, xes_mpc85xx_publish_devices);
+machine_device_initcall(xes_mpc8548, xes_mpc85xx_publish_devices);
+machine_device_initcall(xes_mpc8540, xes_mpc85xx_publish_devices);
+
+/*
+ * Called very early, device-tree isn't unflattened
+ */
+static int __init xes_mpc8572_probe(void)
+{
+	unsigned long root = of_get_flat_dt_root();
+
+	if (of_flat_dt_is_compatible(root, "xes,MPC8572")) {
+#ifdef CONFIG_PCI
+		primary_phb_addr = 0x8000;
+#endif
+		return 1;
+	} else {
+		return 0;
+	}
+}
+
+static int __init xes_mpc8548_probe(void)
+{
+	unsigned long root = of_get_flat_dt_root();
+
+	if (of_flat_dt_is_compatible(root, "xes,MPC8548")) {
+#ifdef CONFIG_PCI
+		primary_phb_addr = 0xb000;
+#endif
+		return 1;
+	} else {
+		return 0;
+	}
+}
+
+static int __init xes_mpc8540_probe(void)
+{
+	unsigned long root = of_get_flat_dt_root();
+
+	if (of_flat_dt_is_compatible(root, "xes,MPC8540")) {
+#ifdef CONFIG_PCI
+		primary_phb_addr = 0xb000;
+#endif
+		return 1;
+	} else {
+		return 0;
+	}
+}
+
+define_machine(xes_mpc8572) {
+	.name			= "X-ES MPC8572",
+	.probe			= xes_mpc8572_probe,
+	.setup_arch		= xes_mpc85xx_setup_arch,
+	.init_IRQ		= xes_mpc85xx_pic_init,
+#ifdef CONFIG_PCI
+	.pcibios_fixup_bus	= fsl_pcibios_fixup_bus,
+#endif
+	.get_irq		= mpic_get_irq,
+	.restart		= fsl_rstcr_restart,
+	.calibrate_decr		= generic_calibrate_decr,
+	.progress		= udbg_progress,
+};
+
+define_machine(xes_mpc8548) {
+	.name			= "X-ES MPC8548",
+	.probe			= xes_mpc8548_probe,
+	.setup_arch		= xes_mpc85xx_setup_arch,
+	.init_IRQ		= xes_mpc85xx_pic_init,
+#ifdef CONFIG_PCI
+	.pcibios_fixup_bus	= fsl_pcibios_fixup_bus,
+#endif
+	.get_irq		= mpic_get_irq,
+	.restart		= fsl_rstcr_restart,
+	.calibrate_decr		= generic_calibrate_decr,
+	.progress		= udbg_progress,
+};
+
+define_machine(xes_mpc8540) {
+	.name			= "X-ES MPC8540",
+	.probe			= xes_mpc8540_probe,
+	.setup_arch		= xes_mpc85xx_setup_arch,
+	.init_IRQ		= xes_mpc85xx_pic_init,
+#ifdef CONFIG_PCI
+	.pcibios_fixup_bus	= fsl_pcibios_fixup_bus,
+#endif
+	.get_irq		= mpic_get_irq,
+	.restart		= fsl_rstcr_restart,
+	.calibrate_decr		= generic_calibrate_decr,
+	.progress		= udbg_progress,
+};
diff --git a/arch/powerpc/platforms/86xx/Kconfig b/arch/powerpc/platforms/86xx/Kconfig
index fdaf4dd..9c7b64a 100644
--- a/arch/powerpc/platforms/86xx/Kconfig
+++ b/arch/powerpc/platforms/86xx/Kconfig
@@ -15,6 +15,7 @@
 	select DEFAULT_UIMAGE
 	select FSL_ULI1575
 	select HAS_RAPIDIO
+	select SWIOTLB
 	help
 	  This option enables support for the MPC8641 HPCN board.
 
diff --git a/arch/powerpc/platforms/86xx/mpc8610_hpcd.c b/arch/powerpc/platforms/86xx/mpc8610_hpcd.c
index 51eec0c..627908a 100644
--- a/arch/powerpc/platforms/86xx/mpc8610_hpcd.c
+++ b/arch/powerpc/platforms/86xx/mpc8610_hpcd.c
@@ -37,6 +37,7 @@
 #include <linux/of_platform.h>
 #include <sysdev/fsl_pci.h>
 #include <sysdev/fsl_soc.h>
+#include <sysdev/simple_gpio.h>
 
 #include "mpc86xx.h"
 
@@ -51,6 +52,9 @@
 
 static int __init mpc8610_declare_of_platform_devices(void)
 {
+	/* Firstly, register PIXIS GPIOs. */
+	simple_gpiochip_init("fsl,fpga-pixis-gpio-bank");
+
 	/* Without this call, the SSI device driver won't get probed. */
 	of_platform_bus_probe(NULL, mpc8610_ids, NULL);
 
diff --git a/arch/powerpc/platforms/86xx/mpc86xx_hpcn.c b/arch/powerpc/platforms/86xx/mpc86xx_hpcn.c
index 7e9e83c..6632702 100644
--- a/arch/powerpc/platforms/86xx/mpc86xx_hpcn.c
+++ b/arch/powerpc/platforms/86xx/mpc86xx_hpcn.c
@@ -19,6 +19,7 @@
 #include <linux/delay.h>
 #include <linux/seq_file.h>
 #include <linux/of_platform.h>
+#include <linux/lmb.h>
 
 #include <asm/system.h>
 #include <asm/time.h>
@@ -27,6 +28,7 @@
 #include <asm/prom.h>
 #include <mm/mmu_decl.h>
 #include <asm/udbg.h>
+#include <asm/swiotlb.h>
 
 #include <asm/mpic.h>
 
@@ -70,7 +72,9 @@
 {
 #ifdef CONFIG_PCI
 	struct device_node *np;
+	struct pci_controller *hose;
 #endif
+	dma_addr_t max = 0xffffffff;
 
 	if (ppc_md.progress)
 		ppc_md.progress("mpc86xx_hpcn_setup_arch()", 0);
@@ -83,6 +87,9 @@
 			fsl_add_bridge(np, 1);
 		else
 			fsl_add_bridge(np, 0);
+		hose = pci_find_hose_for_OF_device(np);
+		max = min(max, hose->dma_window_base_cur +
+			  hose->dma_window_size);
 	}
 
 	ppc_md.pci_exclude_device = mpc86xx_exclude_device;
@@ -94,6 +101,13 @@
 #ifdef CONFIG_SMP
 	mpc86xx_smp_init();
 #endif
+
+#ifdef CONFIG_SWIOTLB
+	if (lmb_end_of_DRAM() > max) {
+		ppc_swiotlb_enable = 1;
+		set_pci_dma_ops(&swiotlb_pci_dma_ops);
+	}
+#endif
 }
 
 
@@ -158,6 +172,7 @@
 	return 0;
 }
 machine_device_initcall(mpc86xx_hpcn, declare_of_platform_devices);
+machine_arch_initcall(mpc86xx_hpcn, swiotlb_setup_bus_notifier);
 
 define_machine(mpc86xx_hpcn) {
 	.name			= "MPC86xx HPCN",
diff --git a/arch/powerpc/platforms/Kconfig.cputype b/arch/powerpc/platforms/Kconfig.cputype
index 8485c8c..61187be 100644
--- a/arch/powerpc/platforms/Kconfig.cputype
+++ b/arch/powerpc/platforms/Kconfig.cputype
@@ -21,7 +21,7 @@
 
 	  If unsure, select 52xx/6xx/7xx/74xx/82xx/83xx/86xx.
 
-config PPC_BOOK3S
+config PPC_BOOK3S_32
 	bool "512x/52xx/6xx/7xx/74xx/82xx/83xx/86xx"
 	select PPC_FPU
 
@@ -57,11 +57,14 @@
 
 endchoice
 
-config PPC_BOOK3S
-	default y
+config PPC_BOOK3S_64
+	def_bool y
 	depends on PPC64
 	select PPC_FPU
 
+config PPC_BOOK3S
+	def_bool y
+	depends on PPC_BOOK3S_32 || PPC_BOOK3S_64
 
 config POWER4_ONLY
 	bool "Optimize for POWER4"
diff --git a/arch/powerpc/platforms/Makefile b/arch/powerpc/platforms/Makefile
index f741919..a6812ee 100644
--- a/arch/powerpc/platforms/Makefile
+++ b/arch/powerpc/platforms/Makefile
@@ -1,4 +1,6 @@
 
+subdir-ccflags-$(CONFIG_PPC_WERROR) := -Werror
+
 obj-$(CONFIG_FSL_ULI1575)	+= fsl_uli1575.o
 
 obj-$(CONFIG_PPC_PMAC)		+= powermac/
diff --git a/arch/powerpc/platforms/maple/setup.c b/arch/powerpc/platforms/maple/setup.c
index bfd60e4..0636a3d 100644
--- a/arch/powerpc/platforms/maple/setup.c
+++ b/arch/powerpc/platforms/maple/setup.c
@@ -335,3 +335,62 @@
 	.progress		= maple_progress,
 	.power_save		= power4_idle,
 };
+
+#ifdef CONFIG_EDAC
+/*
+ * Register a platform device for CPC925 memory controller on
+ * Motorola ATCA-6101 blade.
+ */
+#define MAPLE_CPC925_MODEL	"Motorola,ATCA-6101"
+static int __init maple_cpc925_edac_setup(void)
+{
+	struct platform_device *pdev;
+	struct device_node *np = NULL;
+	struct resource r;
+	const unsigned char *model;
+	int ret;
+
+	np = of_find_node_by_path("/");
+	if (!np) {
+		printk(KERN_ERR "%s: Unable to get root node\n", __func__);
+		return -ENODEV;
+	}
+
+	model = (const unsigned char *)of_get_property(np, "model", NULL);
+	if (!model) {
+		printk(KERN_ERR "%s: Unabel to get model info\n", __func__);
+		return -ENODEV;
+	}
+
+	ret = strcmp(model, MAPLE_CPC925_MODEL);
+	of_node_put(np);
+
+	if (ret != 0)
+		return 0;
+
+	np = of_find_node_by_type(NULL, "memory-controller");
+	if (!np) {
+		printk(KERN_ERR "%s: Unable to find memory-controller node\n",
+			__func__);
+		return -ENODEV;
+	}
+
+	ret = of_address_to_resource(np, 0, &r);
+	of_node_put(np);
+
+	if (ret < 0) {
+		printk(KERN_ERR "%s: Unable to get memory-controller reg\n",
+			__func__);
+		return -ENODEV;
+	}
+
+	pdev = platform_device_register_simple("cpc925_edac", 0, &r, 1);
+	if (IS_ERR(pdev))
+		return PTR_ERR(pdev);
+
+	printk(KERN_INFO "%s: CPC925 platform device created\n", __func__);
+
+	return 0;
+}
+machine_device_initcall(maple, maple_cpc925_edac_setup);
+#endif
diff --git a/arch/powerpc/sysdev/Makefile b/arch/powerpc/sysdev/Makefile
index 2d1c87d..9d4b174 100644
--- a/arch/powerpc/sysdev/Makefile
+++ b/arch/powerpc/sysdev/Makefile
@@ -1,3 +1,5 @@
+subdir-ccflags-$(CONFIG_PPC_WERROR) := -Werror
+
 ifeq ($(CONFIG_PPC64),y)
 EXTRA_CFLAGS			+= -mno-minimal-toc
 endif
@@ -48,6 +50,9 @@
 obj-$(CONFIG_8xx)		+= mpc8xx_pic.o cpm1.o
 obj-$(CONFIG_UCODE_PATCH)	+= micropatch.o
 
+obj-$(CONFIG_PPC_MPC512x)	+= mpc5xxx_clocks.o
+obj-$(CONFIG_PPC_MPC52xx)	+= mpc5xxx_clocks.o
+
 ifeq ($(CONFIG_SUSPEND),y)
 obj-$(CONFIG_6xx)		+= 6xx-suspend.o
 endif
diff --git a/arch/powerpc/sysdev/mpc5xxx_clocks.c b/arch/powerpc/sysdev/mpc5xxx_clocks.c
new file mode 100644
index 0000000..34e12f9
--- /dev/null
+++ b/arch/powerpc/sysdev/mpc5xxx_clocks.c
@@ -0,0 +1,33 @@
+/**
+ * 	mpc5xxx_get_bus_frequency - Find the bus frequency for a device
+ * 	@node:	device node
+ *
+ * 	Returns bus frequency (IPS on MPC512x, IPB on MPC52xx),
+ * 	or 0 if the bus frequency cannot be found.
+ */
+
+#include <linux/kernel.h>
+#include <linux/of_platform.h>
+
+unsigned int
+mpc5xxx_get_bus_frequency(struct device_node *node)
+{
+	struct device_node *np;
+	const unsigned int *p_bus_freq = NULL;
+
+	of_node_get(node);
+	while (node) {
+		p_bus_freq = of_get_property(node, "bus-frequency", NULL);
+		if (p_bus_freq)
+			break;
+
+		np = of_get_parent(node);
+		of_node_put(node);
+		node = np;
+	}
+	if (node)
+		of_node_put(node);
+
+	return p_bus_freq ? *p_bus_freq : 0;
+}
+EXPORT_SYMBOL(mpc5xxx_get_bus_frequency);
diff --git a/arch/powerpc/xmon/Makefile b/arch/powerpc/xmon/Makefile
index 9cb03b7..85ab97a 100644
--- a/arch/powerpc/xmon/Makefile
+++ b/arch/powerpc/xmon/Makefile
@@ -1,5 +1,7 @@
 # Makefile for xmon
 
+subdir-ccflags-$(CONFIG_PPC_WERROR) := -Werror
+
 ifdef CONFIG_PPC64
 EXTRA_CFLAGS += -mno-minimal-toc
 endif
diff --git a/arch/s390/kernel/compat_linux.c b/arch/s390/kernel/compat_linux.c
index 002c70d..9ab188d 100644
--- a/arch/s390/kernel/compat_linux.c
+++ b/arch/s390/kernel/compat_linux.c
@@ -461,9 +461,6 @@
 		result = rc;
 		goto out_putname;
 	}
-	task_lock(current);
-	current->ptrace &= ~PT_DTRACE;
-	task_unlock(current);
 	current->thread.fp_regs.fpc=0;
 	asm volatile("sfpc %0,0" : : "d" (0));
 	result = regs->gprs[2];
diff --git a/arch/s390/kernel/ftrace.c b/arch/s390/kernel/ftrace.c
index 82ddfd3..3e298e6 100644
--- a/arch/s390/kernel/ftrace.c
+++ b/arch/s390/kernel/ftrace.c
@@ -190,7 +190,7 @@
 		goto out;
 	if (unlikely(atomic_read(&current->tracing_graph_pause)))
 		goto out;
-	if (ftrace_push_return_trace(parent, ip, &trace.depth) == -EBUSY)
+	if (ftrace_push_return_trace(parent, ip, &trace.depth, 0) == -EBUSY)
 		goto out;
 	trace.func = ftrace_mcount_call_adjust(ip) & PSW_ADDR_INSN;
 	/* Only trace if the calling function expects to. */
diff --git a/arch/s390/kernel/process.c b/arch/s390/kernel/process.c
index 355f7a3..5a43f27 100644
--- a/arch/s390/kernel/process.c
+++ b/arch/s390/kernel/process.c
@@ -266,9 +266,6 @@
 
 asmlinkage void execve_tail(void)
 {
-	task_lock(current);
-	current->ptrace &= ~PT_DTRACE;
-	task_unlock(current);
 	current->thread.fp_regs.fpc = 0;
 	if (MACHINE_HAS_IEEE)
 		asm volatile("sfpc %0,%0" : : "d" (0));
diff --git a/arch/sh/Kconfig b/arch/sh/Kconfig
index 586cd04..ac1c620 100644
--- a/arch/sh/Kconfig
+++ b/arch/sh/Kconfig
@@ -15,7 +15,9 @@
 	select HAVE_IOREMAP_PROT if MMU
 	select HAVE_ARCH_TRACEHOOK
 	select HAVE_DMA_API_DEBUG
+	select HAVE_PERF_COUNTER
 	select RTC_LIB
+	select GENERIC_ATOMIC64
 	help
 	  The SuperH is a RISC processor targeted for use in embedded systems
 	  and consumer electronics; it was also used in the Sega Dreamcast
@@ -50,6 +52,10 @@
 	def_bool y
 	depends on BUG && SUPERH32
 
+config GENERIC_CSUM
+	def_bool y
+	depends on SUPERH64
+
 config GENERIC_FIND_NEXT_BIT
 	def_bool y
 
diff --git a/arch/sh/Kconfig.debug b/arch/sh/Kconfig.debug
index 8179cc9..8ece0b5 100644
--- a/arch/sh/Kconfig.debug
+++ b/arch/sh/Kconfig.debug
@@ -39,6 +39,7 @@
 				CPU_SUBTYPE_SH7722 || CPU_SUBTYPE_SH7366 || \
 				CPU_SUBTYPE_SH7343
 	default "0xffea0000" if CPU_SUBTYPE_SH7785
+	default "0xffeb0000" if CPU_SUBTYPE_SH7786
 	default "0xfffe8000" if CPU_SUBTYPE_SH7203
 	default "0xfffe9800" if CPU_SUBTYPE_SH7206 || CPU_SUBTYPE_SH7263
 	default "0xffe80000" if CPU_SH4
diff --git a/arch/sh/boards/Kconfig b/arch/sh/boards/Kconfig
index 1c91b1f..2b1af0e 100644
--- a/arch/sh/boards/Kconfig
+++ b/arch/sh/boards/Kconfig
@@ -175,6 +175,7 @@
 	bool "Urquell"
 	depends on CPU_SUBTYPE_SH7786
 	select ARCH_REQUIRE_GPIOLIB
+	select SYS_SUPPORTS_PCI
 
 config SH_MIGOR
 	bool "Migo-R"
diff --git a/arch/sh/boards/board-ap325rxa.c b/arch/sh/boards/board-ap325rxa.c
index 1c4d83e..7ffd1b43 100644
--- a/arch/sh/boards/board-ap325rxa.c
+++ b/arch/sh/boards/board-ap325rxa.c
@@ -349,15 +349,6 @@
 	return 0;
 }
 
-static struct ov772x_camera_info ov7725_info = {
-	.buswidth  = SOCAM_DATAWIDTH_8,
-	.flags = OV772X_FLAG_VFLIP | OV772X_FLAG_HFLIP,
-	.edgectrl = OV772X_AUTO_EDGECTRL(0xf, 0),
-	.link = {
-		.power  = ov7725_power,
-	},
-};
-
 static struct sh_mobile_ceu_info sh_mobile_ceu_info = {
 	.flags = SH_CEU_FLAG_USE_8BIT_BUS,
 };
@@ -402,6 +393,38 @@
 	},
 };
 
+static struct i2c_board_info __initdata ap325rxa_i2c_devices[] = {
+	{
+		I2C_BOARD_INFO("pcf8563", 0x51),
+	},
+};
+
+static struct i2c_board_info ap325rxa_i2c_camera[] = {
+	{
+		I2C_BOARD_INFO("ov772x", 0x21),
+	},
+};
+
+static struct ov772x_camera_info ov7725_info = {
+	.buswidth	= SOCAM_DATAWIDTH_8,
+	.flags		= OV772X_FLAG_VFLIP | OV772X_FLAG_HFLIP,
+	.edgectrl	= OV772X_AUTO_EDGECTRL(0xf, 0),
+	.link = {
+		.power		= ov7725_power,
+		.board_info	= &ap325rxa_i2c_camera[0],
+		.i2c_adapter_id	= 0,
+		.module_name	= "ov772x",
+	},
+};
+
+static struct platform_device ap325rxa_camera = {
+	.name	= "soc-camera-pdrv",
+	.id	= 0,
+	.dev	= {
+		.platform_data = &ov7725_info.link,
+	},
+};
+
 static struct platform_device *ap325rxa_devices[] __initdata = {
 	&smsc9118_device,
 	&ap325rxa_nor_flash_device,
@@ -409,16 +432,7 @@
 	&ceu_device,
 	&nand_flash_device,
 	&sdcard_cn3_device,
-};
-
-static struct i2c_board_info __initdata ap325rxa_i2c_devices[] = {
-	{
-		I2C_BOARD_INFO("pcf8563", 0x51),
-	},
-	{
-		I2C_BOARD_INFO("ov772x", 0x21),
-		.platform_data = &ov7725_info,
-	},
+	&ap325rxa_camera,
 };
 
 static struct spi_board_info ap325rxa_spi_devices[] = {
diff --git a/arch/sh/boards/board-sh7785lcr.c b/arch/sh/boards/board-sh7785lcr.c
index 7be56fb..42410a1 100644
--- a/arch/sh/boards/board-sh7785lcr.c
+++ b/arch/sh/boards/board-sh7785lcr.c
@@ -15,16 +15,18 @@
 #include <linux/fb.h>
 #include <linux/mtd/physmap.h>
 #include <linux/delay.h>
+#include <linux/interrupt.h>
 #include <linux/i2c.h>
 #include <linux/i2c-pca-platform.h>
 #include <linux/i2c-algo-pca.h>
+#include <linux/usb/r8a66597.h>
 #include <linux/irq.h>
 #include <linux/clk.h>
 #include <linux/errno.h>
 #include <mach/sh7785lcr.h>
+#include <cpu/sh7785.h>
 #include <asm/heartbeat.h>
 #include <asm/clock.h>
-#include <cpu/sh7785.h>
 
 /*
  * NOTE: This board has 2 physical memory maps.
@@ -98,18 +100,21 @@
 	.resource	= nor_flash_resources,
 };
 
+static struct r8a66597_platdata r8a66597_data = {
+	.xtal = R8A66597_PLATDATA_XTAL_12MHZ,
+	.vif = 1,
+};
+
 static struct resource r8a66597_usb_host_resources[] = {
 	[0] = {
-		.name	= "r8a66597_hcd",
 		.start	= R8A66597_ADDR,
 		.end	= R8A66597_ADDR + R8A66597_SIZE - 1,
 		.flags	= IORESOURCE_MEM,
 	},
 	[1] = {
-		.name	= "r8a66597_hcd",
 		.start	= 2,
 		.end	= 2,
-		.flags	= IORESOURCE_IRQ,
+		.flags	= IORESOURCE_IRQ | IRQF_TRIGGER_LOW,
 	},
 };
 
@@ -119,6 +124,7 @@
 	.dev = {
 		.dma_mask		= NULL,
 		.coherent_dma_mask	= 0xffffffff,
+		.platform_data		= &r8a66597_data,
 	},
 	.num_resources	= ARRAY_SIZE(r8a66597_usb_host_resources),
 	.resource	= r8a66597_usb_host_resources,
diff --git a/arch/sh/boards/board-urquell.c b/arch/sh/boards/board-urquell.c
index beb88c4..36b8bac 100644
--- a/arch/sh/boards/board-urquell.c
+++ b/arch/sh/boards/board-urquell.c
@@ -2,6 +2,7 @@
  * Renesas Technology Corp. SH7786 Urquell Support.
  *
  * Copyright (C) 2008  Kuninori Morimoto <morimoto.kuninori@renesas.com>
+ * Copyright (C) 2009  Paul Mundt
  *
  * Based on board-sh7785lcr.c
  * Copyright (C) 2008  Yoshihiro Shimoda
@@ -178,6 +179,11 @@
 	plat_irq_setup_pins(IRQ_MODE_IRL3210_MASK);
 }
 
+static int urquell_mode_pins(void)
+{
+	return __raw_readw(UBOARDREG(MDSWMR));
+}
+
 /* Initialize the board */
 static void __init urquell_setup(char **cmdline_p)
 {
@@ -193,4 +199,5 @@
 	.mv_name	= "Urquell",
 	.mv_setup	= urquell_setup,
 	.mv_init_irq	= urquell_init_irq,
+	.mv_mode_pins	= urquell_mode_pins,
 };
diff --git a/arch/sh/boards/mach-highlander/setup.c b/arch/sh/boards/mach-highlander/setup.c
index 20fe72c..1639f89 100644
--- a/arch/sh/boards/mach-highlander/setup.c
+++ b/arch/sh/boards/mach-highlander/setup.c
@@ -17,8 +17,11 @@
 #include <linux/platform_device.h>
 #include <linux/ata_platform.h>
 #include <linux/types.h>
+#include <linux/mtd/physmap.h>
 #include <linux/i2c.h>
 #include <linux/irq.h>
+#include <linux/interrupt.h>
+#include <linux/usb/r8a66597.h>
 #include <net/ax88796.h>
 #include <asm/machvec.h>
 #include <mach/highlander.h>
@@ -27,18 +30,21 @@
 #include <asm/io.h>
 #include <asm/io_trapped.h>
 
+static struct r8a66597_platdata r8a66597_data = {
+	.xtal = R8A66597_PLATDATA_XTAL_12MHZ,
+	.vif = 1,
+};
+
 static struct resource r8a66597_usb_host_resources[] = {
 	[0] = {
-		.name	= "r8a66597_hcd",
 		.start	= 0xA4200000,
 		.end	= 0xA42000FF,
 		.flags	= IORESOURCE_MEM,
 	},
 	[1] = {
-		.name	= "r8a66597_hcd",
 		.start	= IRQ_EXT1,		/* irq number */
 		.end	= IRQ_EXT1,
-		.flags	= IORESOURCE_IRQ,
+		.flags	= IORESOURCE_IRQ | IRQF_TRIGGER_LOW,
 	},
 };
 
@@ -48,6 +54,7 @@
 	.dev = {
 		.dma_mask		= NULL,		/* don't use dma */
 		.coherent_dma_mask	= 0xffffffff,
+		.platform_data		= &r8a66597_data,
 	},
 	.num_resources	= ARRAY_SIZE(r8a66597_usb_host_resources),
 	.resource	= r8a66597_usb_host_resources,
@@ -178,6 +185,53 @@
 	.resource       = ax88796_resources,
 };
 
+static struct mtd_partition nor_flash_partitions[] = {
+	{
+		.name		= "loader",
+		.offset		= 0x00000000,
+		.size		= 512 * 1024,
+	},
+	{
+		.name		= "bootenv",
+		.offset		= MTDPART_OFS_APPEND,
+		.size		= 512 * 1024,
+	},
+	{
+		.name		= "kernel",
+		.offset		= MTDPART_OFS_APPEND,
+		.size		= 4 * 1024 * 1024,
+	},
+	{
+		.name		= "data",
+		.offset		= MTDPART_OFS_APPEND,
+		.size		= MTDPART_SIZ_FULL,
+	},
+};
+
+static struct physmap_flash_data nor_flash_data = {
+	.width		= 4,
+	.parts		= nor_flash_partitions,
+	.nr_parts	= ARRAY_SIZE(nor_flash_partitions),
+};
+
+/* This config is flash board for mass production. */
+static struct resource nor_flash_resources[] = {
+	[0]	= {
+		.start	= PA_NORFLASH_ADDR,
+		.end	= PA_NORFLASH_ADDR + PA_NORFLASH_SIZE - 1,
+		.flags	= IORESOURCE_MEM,
+	}
+};
+
+static struct platform_device nor_flash_device = {
+	.name		= "physmap-flash",
+	.dev		= {
+		.platform_data	= &nor_flash_data,
+	},
+	.num_resources	= ARRAY_SIZE(nor_flash_resources),
+	.resource	= nor_flash_resources,
+};
+
 static struct resource smbus_resources[] = {
 	[0] = {
 		.start	= PA_SMCR,
@@ -209,6 +263,7 @@
 	&m66592_usb_peripheral_device,
 	&heartbeat_device,
 	&smbus_device,
+	&nor_flash_device,
 #ifndef CONFIG_SH_R7780RP
 	&ax88796_device,
 #endif
@@ -247,9 +302,10 @@
 /*
  * Platform specific clocks
  */
-static void ivdr_clk_enable(struct clk *clk)
+static int ivdr_clk_enable(struct clk *clk)
 {
 	ctrl_outw(ctrl_inw(PA_IVDRCTL) | (1 << IVDR_CK_ON), PA_IVDRCTL);
+	return 0;
 }
 
 static void ivdr_clk_disable(struct clk *clk)
diff --git a/arch/sh/boards/mach-migor/setup.c b/arch/sh/boards/mach-migor/setup.c
index 6ed401c..f70f4644 100644
--- a/arch/sh/boards/mach-migor/setup.c
+++ b/arch/sh/boards/mach-migor/setup.c
@@ -381,21 +381,6 @@
 	},
 };
 
-static struct ov772x_camera_info ov7725_info = {
-	.buswidth  = SOCAM_DATAWIDTH_8,
-	.link = {
-		.power  = ov7725_power,
-	},
-};
-
-static struct tw9910_video_info tw9910_info = {
-	.buswidth = SOCAM_DATAWIDTH_8,
-	.mpout    = TW9910_MPO_FIELD,
-	.link = {
-		.power  = tw9910_power,
-	}
-};
-
 struct spi_gpio_platform_data sdcard_cn9_platform_data = {
 	.sck = GPIO_PTD0,
 	.mosi = GPIO_PTD1,
@@ -410,16 +395,6 @@
 	},
 };
 
-static struct platform_device *migor_devices[] __initdata = {
-	&smc91x_eth_device,
-	&sh_keysc_device,
-	&migor_lcdc_device,
-	&migor_ceu_device,
-	&migor_nor_flash_device,
-	&migor_nand_flash_device,
-	&sdcard_cn9_device,
-};
-
 static struct i2c_board_info migor_i2c_devices[] = {
 	{
 		I2C_BOARD_INFO("rs5c372b", 0x32),
@@ -428,16 +403,66 @@
 		I2C_BOARD_INFO("migor_ts", 0x51),
 		.irq = 38, /* IRQ6 */
 	},
+};
+
+static struct i2c_board_info migor_i2c_camera[] = {
 	{
 		I2C_BOARD_INFO("ov772x", 0x21),
-		.platform_data = &ov7725_info,
 	},
 	{
 		I2C_BOARD_INFO("tw9910", 0x45),
-		.platform_data = &tw9910_info,
 	},
 };
 
+static struct ov772x_camera_info ov7725_info = {
+	.buswidth	= SOCAM_DATAWIDTH_8,
+	.link = {
+		.power		= ov7725_power,
+		.board_info	= &migor_i2c_camera[0],
+		.i2c_adapter_id	= 0,
+		.module_name	= "ov772x",
+	},
+};
+
+static struct tw9910_video_info tw9910_info = {
+	.buswidth	= SOCAM_DATAWIDTH_8,
+	.mpout		= TW9910_MPO_FIELD,
+	.link = {
+		.power		= tw9910_power,
+		.board_info	= &migor_i2c_camera[1],
+		.i2c_adapter_id	= 0,
+		.module_name	= "tw9910",
+	}
+};
+
+static struct platform_device migor_camera[] = {
+	{
+		.name	= "soc-camera-pdrv",
+		.id	= 0,
+		.dev	= {
+			.platform_data = &ov7725_info.link,
+		},
+	}, {
+		.name	= "soc-camera-pdrv",
+		.id	= 1,
+		.dev	= {
+			.platform_data = &tw9910_info.link,
+		},
+	},
+};
+
+static struct platform_device *migor_devices[] __initdata = {
+	&smc91x_eth_device,
+	&sh_keysc_device,
+	&migor_lcdc_device,
+	&migor_ceu_device,
+	&migor_nor_flash_device,
+	&migor_nand_flash_device,
+	&sdcard_cn9_device,
+	&migor_camera[0],
+	&migor_camera[1],
+};
+
 static struct spi_board_info migor_spi_devices[] = {
 	{
 		.modalias = "mmc_spi",
diff --git a/arch/sh/boards/mach-rsk/devices-rsk7203.c b/arch/sh/boards/mach-rsk/devices-rsk7203.c
index d8a65ea..4af3a77 100644
--- a/arch/sh/boards/mach-rsk/devices-rsk7203.c
+++ b/arch/sh/boards/mach-rsk/devices-rsk7203.c
@@ -26,13 +26,13 @@
 	.phy_interface	= PHY_INTERFACE_MODE_MII,
 	.irq_polarity	= SMSC911X_IRQ_POLARITY_ACTIVE_LOW,
 	.irq_type	= SMSC911X_IRQ_TYPE_OPEN_DRAIN,
-	.flags		= SMSC911X_USE_16BIT,
+	.flags		= SMSC911X_USE_32BIT | SMSC911X_SWAP_FIFO,
 };
 
 static struct resource smsc911x_resources[] = {
 	[0] = {
 		.start		= 0x24000000,
-		.end		= 0x24000000 + 0x100,
+		.end		= 0x240000ff,
 		.flags		= IORESOURCE_MEM,
 	},
 	[1] = {
@@ -99,6 +99,10 @@
 	gpio_request(GPIO_FN_TXD0, NULL);
 	gpio_request(GPIO_FN_RXD0, NULL);
 
+	/* Setup LAN9118: CS1 in 16-bit Big Endian Mode, IRQ0 at Port B */
+	ctrl_outl(0x36db0400, 0xfffc0008); /* CS1BCR */
+	gpio_request(GPIO_FN_IRQ0_PB, NULL);
+
 	return platform_add_devices(rsk7203_devices,
 				    ARRAY_SIZE(rsk7203_devices));
 }
diff --git a/arch/sh/boards/mach-se/7780/irq.c b/arch/sh/boards/mach-se/7780/irq.c
index b8d43b6..121744c 100644
--- a/arch/sh/boards/mach-se/7780/irq.c
+++ b/arch/sh/boards/mach-se/7780/irq.c
@@ -12,7 +12,6 @@
 #include <linux/init.h>
 #include <linux/irq.h>
 #include <linux/interrupt.h>
-#include <linux/irq.h>
 #include <linux/io.h>
 #include <mach-se/mach/se7780.h>
 
diff --git a/arch/sh/boards/mach-x3proto/setup.c b/arch/sh/boards/mach-x3proto/setup.c
index a340492..8913ae3 100644
--- a/arch/sh/boards/mach-x3proto/setup.c
+++ b/arch/sh/boards/mach-x3proto/setup.c
@@ -15,6 +15,8 @@
 #include <linux/io.h>
 #include <linux/smc91x.h>
 #include <linux/irq.h>
+#include <linux/interrupt.h>
+#include <linux/usb/r8a66597.h>
 #include <asm/ilsel.h>
 
 static struct resource heartbeat_resources[] = {
@@ -58,17 +60,20 @@
 	},
 };
 
+static struct r8a66597_platdata r8a66597_data = {
+	.xtal = R8A66597_PLATDATA_XTAL_12MHZ,
+	.vif = 1,
+};
+
 static struct resource r8a66597_usb_host_resources[] = {
 	[0] = {
-		.name	= "r8a66597_hcd",
 		.start	= 0x18040000,
 		.end	= 0x18080000 - 1,
 		.flags	= IORESOURCE_MEM,
 	},
 	[1] = {
-		.name	= "r8a66597_hcd",
 		/* Filled in by ilsel */
-		.flags	= IORESOURCE_IRQ,
+		.flags	= IORESOURCE_IRQ | IRQF_TRIGGER_LOW,
 	},
 };
 
@@ -78,6 +83,7 @@
 	.dev = {
 		.dma_mask		= NULL,		/* don't use dma */
 		.coherent_dma_mask	= 0xffffffff,
+		.platform_data		= &r8a66597_data,
 	},
 	.num_resources	= ARRAY_SIZE(r8a66597_usb_host_resources),
 	.resource	= r8a66597_usb_host_resources,
diff --git a/arch/sh/configs/ap325rxa_defconfig b/arch/sh/configs/ap325rxa_defconfig
index 022f70e..6c38a43 100644
--- a/arch/sh/configs/ap325rxa_defconfig
+++ b/arch/sh/configs/ap325rxa_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:42:06 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 16:04:11 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 CONFIG_ARCH_SUSPEND_POSSIBLE=y
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_CMT=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -75,7 +76,6 @@
 CONFIG_UID16=y
 CONFIG_SYSCTL_SYSCALL=y
 # CONFIG_KALLSYMS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -88,7 +88,12 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -180,6 +185,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x08000000
 CONFIG_29BIT=y
@@ -195,7 +201,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -208,9 +213,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -228,7 +233,6 @@
 # CONFIG_SH_STORE_QUEUES is not set
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -239,10 +243,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
+CONFIG_SH_TIMER_TMU=y
 # CONFIG_SH_TIMER_CMT is not set
-CONFIG_SH_TIMER_IRQ=16
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
 CONFIG_TICK_ONESHOT=y
 # CONFIG_NO_HZ is not set
 CONFIG_HIGH_RES_TIMERS=y
@@ -284,12 +288,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=tty1 console=ttySC5,38400 root=/dev/nfs ip=dhcp"
 
@@ -372,6 +378,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -389,7 +396,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -532,6 +543,7 @@
 # CONFIG_EEPROM_AT24 is not set
 # CONFIG_EEPROM_AT25 is not set
 # CONFIG_EEPROM_LEGACY is not set
+# CONFIG_EEPROM_MAX6875 is not set
 # CONFIG_EEPROM_93CX6 is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
@@ -555,10 +567,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -575,6 +583,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_LIBFC is not set
 # CONFIG_LIBFCOE is not set
 # CONFIG_SCSI_DEBUG is not set
@@ -583,7 +592,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -628,6 +636,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -751,7 +760,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -823,10 +831,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
+CONFIG_MEDIA_SUPPORT=y
 
 #
 # Multimedia core support
@@ -1017,6 +1022,7 @@
 # on-CPU RTC drivers
 #
 # CONFIG_RTC_DRV_SH is not set
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 CONFIG_UIO=y
@@ -1024,6 +1030,10 @@
 CONFIG_UIO_PDRV_GENIRQ=y
 # CONFIG_UIO_SMX is not set
 # CONFIG_UIO_SERCOS3 is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1045,10 +1055,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1204,28 +1215,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_PREEMPT_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1347,3 +1342,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/cayman_defconfig b/arch/sh/configs/cayman_defconfig
index 40301f8..6b863cb 100644
--- a/arch/sh/configs/cayman_defconfig
+++ b/arch/sh/configs/cayman_defconfig
@@ -1,24 +1,26 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:42:53 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:21:54 2009
 #
 CONFIG_SUPERH=y
 # CONFIG_SUPERH32 is not set
 CONFIG_SUPERH64=y
 CONFIG_ARCH_DEFCONFIG="arch/sh/configs/cayman_defconfig"
 CONFIG_RWSEM_GENERIC_SPINLOCK=y
+CONFIG_GENERIC_CSUM=y
 CONFIG_GENERIC_FIND_NEXT_BIT=y
 CONFIG_GENERIC_HWEIGHT=y
 CONFIG_GENERIC_HARDIRQS=y
 CONFIG_GENERIC_HARDIRQS_NO__DO_IRQ=y
 CONFIG_GENERIC_IRQ_PROBE=y
 # CONFIG_GENERIC_GPIO is not set
-# CONFIG_GENERIC_TIME is not set
-# CONFIG_GENERIC_CLOCKEVENTS is not set
+CONFIG_GENERIC_TIME=y
+CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 # CONFIG_ARCH_HIBERNATION_POSSIBLE is not set
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -71,7 +73,6 @@
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_ALL is not set
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -84,8 +85,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -140,6 +146,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x20000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x80000000
 CONFIG_MEMORY_SIZE=0x00400000
 CONFIG_32BIT=y
@@ -153,7 +160,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_HUGETLB_PAGE_SIZE_64K=y
 # CONFIG_HUGETLB_PAGE_SIZE_256K is not set
 # CONFIG_HUGETLB_PAGE_SIZE_1MB is not set
@@ -172,9 +178,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -190,7 +196,6 @@
 # CONFIG_CPU_BIG_ENDIAN is not set
 CONFIG_SH_FPU=y
 # CONFIG_SH64_FPU_DENORM_FLUSH is not set
-CONFIG_SH64_USER_MISALIGNED_FIXUP=y
 CONFIG_SH64_ID2815_WORKAROUND=y
 CONFIG_CPU_HAS_FPU=y
 
@@ -202,8 +207,13 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=50000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
+# CONFIG_NO_HZ is not set
+# CONFIG_HIGH_RES_TIMERS is not set
+CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
 
 #
 # CPU Frequency scaling
@@ -237,12 +247,14 @@
 # CONFIG_PREEMPT_NONE is not set
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
-CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_BOOT_LINK_OFFSET=0x00400000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_CMDLINE_BOOL is not set
 
 #
@@ -332,6 +344,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -349,7 +362,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -402,7 +419,9 @@
 #
 # CONFIG_EEPROM_AT24 is not set
 # CONFIG_EEPROM_LEGACY is not set
+# CONFIG_EEPROM_MAX6875 is not set
 # CONFIG_EEPROM_93CX6 is not set
+# CONFIG_CB710_CORE is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
 
@@ -425,10 +444,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 CONFIG_SCSI_MULTI_LUN=y
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -446,6 +461,7 @@
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
 # CONFIG_SCSI_CXGB3_ISCSI is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_BLK_DEV_3W_XXXX_RAID is not set
 # CONFIG_SCSI_3W_9XXX is not set
 # CONFIG_SCSI_ACARD is not set
@@ -454,6 +470,7 @@
 # CONFIG_SCSI_AIC7XXX_OLD is not set
 # CONFIG_SCSI_AIC79XX is not set
 # CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_ARCMSR is not set
 # CONFIG_MEGARAID_NEWGEN is not set
 # CONFIG_MEGARAID_LEGACY is not set
@@ -468,7 +485,6 @@
 # CONFIG_SCSI_IPS is not set
 # CONFIG_SCSI_INITIO is not set
 # CONFIG_SCSI_INIA100 is not set
-# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_STEX is not set
 # CONFIG_SCSI_SYM53C8XX_2 is not set
 # CONFIG_SCSI_QLOGIC_1280 is not set
@@ -497,7 +513,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -530,6 +545,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_NET_PCI is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_ATL2 is not set
 CONFIG_NETDEV_1000=y
 # CONFIG_ACENIC is not set
@@ -722,7 +738,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -781,6 +796,7 @@
 # CONFIG_SENSORS_SMSC47B397 is not set
 # CONFIG_SENSORS_ADS7828 is not set
 # CONFIG_SENSORS_THMC50 is not set
+# CONFIG_SENSORS_TMP401 is not set
 # CONFIG_SENSORS_VIA686A is not set
 # CONFIG_SENSORS_VT1211 is not set
 # CONFIG_SENSORS_VT8231 is not set
@@ -827,92 +843,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-CONFIG_VIDEO_DEV=m
-CONFIG_VIDEO_V4L2_COMMON=m
-CONFIG_VIDEO_ALLOW_V4L1=y
-CONFIG_VIDEO_V4L1_COMPAT=y
-CONFIG_DVB_CORE=y
-CONFIG_VIDEO_MEDIA=m
-
-#
-# Multimedia drivers
-#
-# CONFIG_MEDIA_ATTACH is not set
-CONFIG_MEDIA_TUNER=m
-# CONFIG_MEDIA_TUNER_CUSTOMISE is not set
-CONFIG_MEDIA_TUNER_SIMPLE=m
-CONFIG_MEDIA_TUNER_TDA8290=m
-CONFIG_MEDIA_TUNER_TDA9887=m
-CONFIG_MEDIA_TUNER_TEA5761=m
-CONFIG_MEDIA_TUNER_TEA5767=m
-CONFIG_MEDIA_TUNER_MT20XX=m
-CONFIG_MEDIA_TUNER_XC2028=m
-CONFIG_MEDIA_TUNER_XC5000=m
-CONFIG_MEDIA_TUNER_MC44S803=m
-CONFIG_VIDEO_V4L2=m
-CONFIG_VIDEO_V4L1=m
-CONFIG_VIDEO_CAPTURE_DRIVERS=y
-# CONFIG_VIDEO_ADV_DEBUG is not set
-# CONFIG_VIDEO_FIXED_MINOR_RANGES is not set
-CONFIG_VIDEO_HELPER_CHIPS_AUTO=y
-# CONFIG_VIDEO_VIVI is not set
-# CONFIG_VIDEO_BT848 is not set
-# CONFIG_VIDEO_CPIA is not set
-# CONFIG_VIDEO_SAA5246A is not set
-# CONFIG_VIDEO_SAA5249 is not set
-# CONFIG_VIDEO_SAA7134 is not set
-# CONFIG_VIDEO_MXB is not set
-# CONFIG_VIDEO_HEXIUM_ORION is not set
-# CONFIG_VIDEO_HEXIUM_GEMINI is not set
-# CONFIG_VIDEO_CX88 is not set
-# CONFIG_VIDEO_CX23885 is not set
-# CONFIG_VIDEO_IVTV is not set
-# CONFIG_VIDEO_CX18 is not set
-# CONFIG_VIDEO_CAFE_CCIC is not set
-# CONFIG_SOC_CAMERA is not set
-# CONFIG_RADIO_ADAPTERS is not set
-# CONFIG_DVB_DYNAMIC_MINORS is not set
-CONFIG_DVB_CAPTURE_DRIVERS=y
-
-#
-# Supported SAA7146 based PCI Adapters
-#
-# CONFIG_TTPCI_EEPROM is not set
-# CONFIG_DVB_AV7110 is not set
-# CONFIG_DVB_BUDGET_CORE is not set
-
-#
-# Supported FlexCopII (B2C2) Adapters
-#
-# CONFIG_DVB_B2C2_FLEXCOP is not set
-
-#
-# Supported BT878 Adapters
-#
-
-#
-# Supported Pluto2 Adapters
-#
-# CONFIG_DVB_PLUTO2 is not set
-
-#
-# Supported SDMC DM1105 Adapters
-#
-# CONFIG_DVB_DM1105 is not set
-
-#
-# Supported DVB Frontends
-#
-# CONFIG_DVB_FE_CUSTOMISE is not set
-CONFIG_DAB=y
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -1041,10 +972,15 @@
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
 # CONFIG_INFINIBAND is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1065,10 +1001,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1228,29 +1165,28 @@
 # CONFIG_SYSCTL_SYSCALL_CHECK is not set
 # CONFIG_PAGE_POISONING is not set
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
+# CONFIG_IRQSOFF_TRACER is not set
+# CONFIG_PREEMPT_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
 # CONFIG_BLK_DEV_IO_TRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
+# CONFIG_KMEMCHECK is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
 # CONFIG_DEBUG_BOOTMEM is not set
 # CONFIG_DEBUG_STACK_USAGE is not set
 # CONFIG_4KSTACKS is not set
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 CONFIG_SH64_SR_WATCH=y
-# CONFIG_POOR_MANS_STRACE is not set
 
 #
 # Security options
@@ -1364,3 +1300,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/dreamcast_defconfig b/arch/sh/configs/dreamcast_defconfig
index 1f3cc98..95717a0 100644
--- a/arch/sh/configs/dreamcast_defconfig
+++ b/arch/sh/configs/dreamcast_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:44:27 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:24:48 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -17,9 +17,11 @@
 # CONFIG_GENERIC_GPIO is not set
 CONFIG_GENERIC_TIME=y
 CONFIG_GENERIC_CLOCKEVENTS=y
+CONFIG_GENERIC_CMOS_UPDATE=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -72,7 +74,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -85,8 +86,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -177,6 +183,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x01000000
 CONFIG_29BIT=y
@@ -191,7 +198,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_HUGETLB_PAGE_SIZE_64K=y
 # CONFIG_HUGETLB_PAGE_SIZE_256K is not set
 # CONFIG_HUGETLB_PAGE_SIZE_1MB is not set
@@ -210,9 +216,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -230,7 +236,6 @@
 CONFIG_SH_STORE_QUEUES=y
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -241,9 +246,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=49876504
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -307,12 +313,14 @@
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC1,115200 panic=3"
@@ -401,6 +409,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -418,7 +427,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -463,6 +476,7 @@
 # EEPROM support
 #
 # CONFIG_EEPROM_93CX6 is not set
+# CONFIG_CB710_CORE is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
 
@@ -488,7 +502,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -541,6 +554,7 @@
 # CONFIG_SMSC9420 is not set
 # CONFIG_SUNDANCE is not set
 # CONFIG_TLAN is not set
+# CONFIG_KS8842 is not set
 # CONFIG_VIA_RHINE is not set
 # CONFIG_SC92031 is not set
 # CONFIG_ATL2 is not set
@@ -697,22 +711,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -841,10 +840,15 @@
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
 # CONFIG_INFINIBAND is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -856,10 +860,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -956,28 +961,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_PREEMPT_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1091,3 +1080,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/edosk7705_defconfig b/arch/sh/configs/edosk7705_defconfig
index d709245..497414c 100644
--- a/arch/sh/configs/edosk7705_defconfig
+++ b/arch/sh/configs/edosk7705_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:45:04 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:25:35 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -18,6 +18,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -57,7 +58,6 @@
 # CONFIG_UID16 is not set
 # CONFIG_SYSCTL_SYSCALL is not set
 # CONFIG_KALLSYMS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_HOTPLUG is not set
 # CONFIG_PRINTK is not set
 # CONFIG_BUG is not set
@@ -70,7 +70,12 @@
 # CONFIG_EVENTFD is not set
 CONFIG_SHMEM=y
 # CONFIG_AIO is not set
+
+#
+# Performance Counters
+#
 # CONFIG_VM_EVENT_COUNTERS is not set
+# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_COMPAT_BRK is not set
 # CONFIG_SLAB is not set
 CONFIG_SLUB=y
@@ -136,6 +141,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -152,7 +158,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 # CONFIG_FLATMEM_MANUAL is not set
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -166,9 +171,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -196,9 +201,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=31250000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -243,6 +249,7 @@
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_CMDLINE_BOOL is not set
 
 #
@@ -335,21 +342,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -369,17 +362,25 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
 # File systems
 #
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -418,26 +419,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -462,3 +449,4 @@
 CONFIG_HAS_IOMEM=y
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/edosk7760_defconfig b/arch/sh/configs/edosk7760_defconfig
index a822b1d..77684ed 100644
--- a/arch/sh/configs/edosk7760_defconfig
+++ b/arch/sh/configs/edosk7760_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:45:25 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:25:55 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -19,6 +19,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -78,7 +79,6 @@
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_ALL=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -91,8 +91,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_SLUB_DEBUG=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 # CONFIG_SLAB is not set
 CONFIG_SLUB=y
@@ -182,6 +187,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -196,7 +202,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -209,9 +214,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -229,7 +234,6 @@
 CONFIG_SH_STORE_QUEUES=y
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -240,9 +244,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 CONFIG_TICK_ONESHOT=y
 # CONFIG_NO_HZ is not set
 CONFIG_HIGH_RES_TIMERS=y
@@ -258,6 +263,7 @@
 #
 CONFIG_SH_DMA_API=y
 CONFIG_SH_DMA=y
+CONFIG_SH_DMA_IRQ_MULTI=y
 CONFIG_NR_ONCHIP_DMA_CHANNELS=8
 # CONFIG_NR_DMA_CHANNELS_BOOL is not set
 # CONFIG_SH_DMABRG is not set
@@ -289,12 +295,14 @@
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x02000000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="mem=64M console=ttySC2,115200 root=/dev/nfs rw nfsroot=192.168.0.3:/scripts/filesys ip=192.168.0.4"
@@ -373,6 +381,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -390,7 +399,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -523,7 +536,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -548,6 +560,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -670,7 +683,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 CONFIG_I2C_DEBUG_CORE=y
 CONFIG_I2C_DEBUG_ALGO=y
@@ -703,22 +715,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -783,6 +780,11 @@
 # CONFIG_SND_VERBOSE_PROCFS is not set
 CONFIG_SND_VERBOSE_PRINTK=y
 # CONFIG_SND_DEBUG is not set
+# CONFIG_SND_RAWMIDI_SEQ is not set
+# CONFIG_SND_OPL3_LIB_SEQ is not set
+# CONFIG_SND_OPL4_LIB_SEQ is not set
+# CONFIG_SND_SBAWE_SEQ is not set
+# CONFIG_SND_EMU10K1_SEQ is not set
 CONFIG_SND_DRIVERS=y
 # CONFIG_SND_DUMMY is not set
 # CONFIG_SND_MTPAV is not set
@@ -803,10 +805,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -829,10 +836,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1015,18 +1023,16 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_PREEMPT_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
@@ -1043,10 +1049,8 @@
 CONFIG_DEBUG_STACKOVERFLOW=y
 # CONFIG_DEBUG_STACK_USAGE is not set
 # CONFIG_4KSTACKS is not set
-# CONFIG_IRQSTACKS is not set
 CONFIG_DUMP_CODE=y
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1165,3 +1169,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/espt_defconfig b/arch/sh/configs/espt_defconfig
index c5b5007..881128e 100644
--- a/arch/sh/configs/espt_defconfig
+++ b/arch/sh/configs/espt_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:46:26 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:27:21 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -19,6 +19,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -79,7 +80,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -92,14 +92,19 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
 # CONFIG_SLOB is not set
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 # CONFIG_KPROBES is not set
@@ -184,6 +189,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -200,7 +206,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 # CONFIG_FLATMEM_MANUAL is not set
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -215,9 +220,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -246,9 +251,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=28
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=66666666
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -289,12 +295,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200 root=/dev/nfs ip=bootp"
 
@@ -377,6 +385,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -529,10 +538,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -549,6 +554,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_LIBFC is not set
 # CONFIG_LIBFCOE is not set
 # CONFIG_SCSI_DEBUG is not set
@@ -557,7 +563,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -602,6 +607,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -720,22 +726,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -909,10 +900,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -933,10 +929,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1088,31 +1085,17 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1226,3 +1209,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/hp6xx_defconfig b/arch/sh/configs/hp6xx_defconfig
index 8e13027..3249d46 100644
--- a/arch/sh/configs/hp6xx_defconfig
+++ b/arch/sh/configs/hp6xx_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:47:15 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:28:12 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 CONFIG_ARCH_SUSPEND_POSSIBLE=y
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_APM_EMULATION=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -68,7 +69,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -81,7 +81,12 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -165,6 +170,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0d000000
 CONFIG_MEMORY_SIZE=0x00400000
 CONFIG_29BIT=y
@@ -179,7 +185,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -192,9 +197,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -223,9 +228,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=22110000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -249,7 +255,6 @@
 CONFIG_HD6446X_SERIES=y
 CONFIG_HD64461=y
 CONFIG_HD64461_IRQ=36
-CONFIG_HD64461_IOBASE=0xb0000000
 CONFIG_HD64461_ENABLER=y
 
 #
@@ -275,12 +280,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_CMDLINE_BOOL is not set
 
 #
@@ -370,10 +377,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -387,6 +390,7 @@
 # CONFIG_SCSI_SAS_LIBSAS is not set
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_LIBFC is not set
 # CONFIG_LIBFCOE is not set
 # CONFIG_SCSI_DEBUG is not set
@@ -524,21 +528,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -651,9 +641,14 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -667,9 +662,10 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -798,27 +794,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -939,3 +920,4 @@
 CONFIG_HAS_IOMEM=y
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/landisk_defconfig b/arch/sh/configs/landisk_defconfig
index 7f549ae..ba05739 100644
--- a/arch/sh/configs/landisk_defconfig
+++ b/arch/sh/configs/landisk_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:47:48 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:28:45 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -70,7 +71,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_EXTRA_PASS=y
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -83,8 +83,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -174,6 +179,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -188,7 +194,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -201,9 +206,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -221,7 +226,6 @@
 # CONFIG_SH_STORE_QUEUES is not set
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -237,9 +241,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -281,12 +286,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 # CONFIG_CMDLINE_BOOL is not set
 
@@ -420,6 +427,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -437,7 +445,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -488,6 +500,7 @@
 # EEPROM support
 #
 # CONFIG_EEPROM_93CX6 is not set
+# CONFIG_CB710_CORE is not set
 CONFIG_HAVE_IDE=y
 CONFIG_IDE=y
 
@@ -567,10 +580,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 CONFIG_SCSI_MULTI_LUN=y
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -588,6 +597,7 @@
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
 # CONFIG_SCSI_CXGB3_ISCSI is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_BLK_DEV_3W_XXXX_RAID is not set
 # CONFIG_SCSI_3W_9XXX is not set
 # CONFIG_SCSI_ACARD is not set
@@ -596,6 +606,7 @@
 # CONFIG_SCSI_AIC7XXX_OLD is not set
 # CONFIG_SCSI_AIC79XX is not set
 # CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_ARCMSR is not set
 # CONFIG_MEGARAID_NEWGEN is not set
 # CONFIG_MEGARAID_LEGACY is not set
@@ -610,7 +621,6 @@
 # CONFIG_SCSI_IPS is not set
 # CONFIG_SCSI_INITIO is not set
 # CONFIG_SCSI_INIA100 is not set
-# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_STEX is not set
 # CONFIG_SCSI_SYM53C8XX_2 is not set
 # CONFIG_SCSI_QLOGIC_1280 is not set
@@ -649,7 +659,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -698,6 +707,7 @@
 # CONFIG_SMSC9420 is not set
 # CONFIG_SUNDANCE is not set
 # CONFIG_TLAN is not set
+# CONFIG_KS8842 is not set
 # CONFIG_VIA_RHINE is not set
 # CONFIG_SC92031 is not set
 # CONFIG_ATL2 is not set
@@ -895,65 +905,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-CONFIG_VIDEO_DEV=m
-CONFIG_VIDEO_V4L2_COMMON=m
-CONFIG_VIDEO_ALLOW_V4L1=y
-CONFIG_VIDEO_V4L1_COMPAT=y
-# CONFIG_DVB_CORE is not set
-CONFIG_VIDEO_MEDIA=m
-
-#
-# Multimedia drivers
-#
-# CONFIG_MEDIA_ATTACH is not set
-CONFIG_VIDEO_V4L2=m
-CONFIG_VIDEO_V4L1=m
-CONFIG_VIDEO_CAPTURE_DRIVERS=y
-# CONFIG_VIDEO_ADV_DEBUG is not set
-# CONFIG_VIDEO_FIXED_MINOR_RANGES is not set
-CONFIG_VIDEO_HELPER_CHIPS_AUTO=y
-# CONFIG_VIDEO_VIVI is not set
-# CONFIG_VIDEO_CPIA is not set
-# CONFIG_VIDEO_CPIA2 is not set
-# CONFIG_SOC_CAMERA is not set
-CONFIG_V4L_USB_DRIVERS=y
-# CONFIG_USB_VIDEO_CLASS is not set
-CONFIG_USB_VIDEO_CLASS_INPUT_EVDEV=y
-# CONFIG_USB_GSPCA is not set
-# CONFIG_VIDEO_HDPVR is not set
-CONFIG_VIDEO_USBVIDEO=m
-CONFIG_USB_VICAM=m
-CONFIG_USB_IBMCAM=m
-CONFIG_USB_KONICAWC=m
-# CONFIG_USB_QUICKCAM_MESSENGER is not set
-# CONFIG_USB_ET61X251 is not set
-CONFIG_USB_OV511=m
-CONFIG_USB_SE401=m
-CONFIG_USB_SN9C102=m
-CONFIG_USB_STV680=m
-# CONFIG_USB_ZC0301 is not set
-CONFIG_USB_PWC=m
-# CONFIG_USB_PWC_DEBUG is not set
-CONFIG_USB_PWC_INPUT_EVDEV=y
-# CONFIG_USB_ZR364XX is not set
-# CONFIG_USB_STKWEBCAM is not set
-# CONFIG_USB_S2255 is not set
-CONFIG_RADIO_ADAPTERS=y
-# CONFIG_RADIO_GEMTEK_PCI is not set
-# CONFIG_RADIO_MAXIRADIO is not set
-# CONFIG_RADIO_MAESTRO is not set
-CONFIG_USB_DSBR=m
-# CONFIG_USB_SI470X is not set
-# CONFIG_USB_MR800 is not set
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -1005,7 +957,7 @@
 CONFIG_HID_CHERRY=m
 CONFIG_HID_CHICONY=m
 CONFIG_HID_CYPRESS=m
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 CONFIG_HID_EZKEY=m
 # CONFIG_HID_KYE is not set
 CONFIG_HID_GYRATION=m
@@ -1022,10 +974,11 @@
 CONFIG_HID_SAMSUNG=m
 CONFIG_HID_SONY=m
 CONFIG_HID_SUNPLUS=m
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-CONFIG_THRUSTMASTER_FF=m
-CONFIG_ZEROPLUS_FF=m
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 CONFIG_USB_ARCH_HAS_OHCI=y
@@ -1051,6 +1004,7 @@
 # USB Host Controller Drivers
 #
 # CONFIG_USB_C67X00_HCD is not set
+# CONFIG_USB_XHCI_HCD is not set
 CONFIG_USB_EHCI_HCD=y
 # CONFIG_USB_EHCI_ROOT_HUB_TT is not set
 # CONFIG_USB_EHCI_TT_NEWSCHED is not set
@@ -1191,10 +1145,15 @@
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
 # CONFIG_INFINIBAND is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1217,10 +1176,11 @@
 # CONFIG_REISERFS_FS_XATTR is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1383,28 +1343,13 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 CONFIG_SH_STANDARD_BIOS=y
 # CONFIG_EARLY_SCIF_CONSOLE is not set
 # CONFIG_EARLY_PRINTK is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1518,3 +1463,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/lboxre2_defconfig b/arch/sh/configs/lboxre2_defconfig
index a7db539..c0bc2fd 100644
--- a/arch/sh/configs/lboxre2_defconfig
+++ b/arch/sh/configs/lboxre2_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:48:54 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:29:50 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -70,7 +71,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_EXTRA_PASS=y
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -83,8 +83,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -174,6 +179,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -188,7 +194,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -201,9 +206,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -221,7 +226,6 @@
 # CONFIG_SH_STORE_QUEUES is not set
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -237,9 +241,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=40000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -281,12 +286,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC1,115200 root=/dev/sda1"
@@ -418,6 +425,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -435,7 +443,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -485,6 +497,7 @@
 # EEPROM support
 #
 # CONFIG_EEPROM_93CX6 is not set
+# CONFIG_CB710_CORE is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
 
@@ -507,10 +520,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -528,6 +537,7 @@
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
 # CONFIG_SCSI_CXGB3_ISCSI is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_BLK_DEV_3W_XXXX_RAID is not set
 # CONFIG_SCSI_3W_9XXX is not set
 # CONFIG_SCSI_ACARD is not set
@@ -536,6 +546,7 @@
 # CONFIG_SCSI_AIC7XXX_OLD is not set
 # CONFIG_SCSI_AIC79XX is not set
 # CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_ARCMSR is not set
 # CONFIG_MEGARAID_NEWGEN is not set
 # CONFIG_MEGARAID_LEGACY is not set
@@ -550,7 +561,6 @@
 # CONFIG_SCSI_IPS is not set
 # CONFIG_SCSI_INITIO is not set
 # CONFIG_SCSI_INIA100 is not set
-# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_STEX is not set
 # CONFIG_SCSI_SYM53C8XX_2 is not set
 # CONFIG_SCSI_IPR is not set
@@ -641,7 +651,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -694,6 +703,7 @@
 # CONFIG_SMSC9420 is not set
 # CONFIG_SUNDANCE is not set
 # CONFIG_TLAN is not set
+# CONFIG_KS8842 is not set
 # CONFIG_VIA_RHINE is not set
 # CONFIG_SC92031 is not set
 # CONFIG_ATL2 is not set
@@ -890,22 +900,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -998,9 +993,14 @@
 # on-CPU RTC drivers
 #
 # CONFIG_RTC_DRV_SH is not set
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1020,10 +1020,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1166,28 +1167,13 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 CONFIG_SH_STANDARD_BIOS=y
 # CONFIG_EARLY_SCIF_CONSOLE is not set
 # CONFIG_EARLY_PRINTK is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1301,3 +1287,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/magicpanelr2_defconfig b/arch/sh/configs/magicpanelr2_defconfig
index 58bec61..c5859e8 100644
--- a/arch/sh/configs/magicpanelr2_defconfig
+++ b/arch/sh/configs/magicpanelr2_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:49:32 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:30:31 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -19,6 +19,8 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_CMT=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -77,7 +79,6 @@
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_ALL=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -90,7 +91,12 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -180,6 +186,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0C000000
 CONFIG_MEMORY_SIZE=0x03F00000
 CONFIG_29BIT=y
@@ -194,7 +201,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -207,9 +213,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -243,9 +249,11 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
+CONFIG_SH_TIMER_CMT=y
 CONFIG_SH_PCLK_FREQ=24000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -290,12 +298,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_CMDLINE_BOOL is not set
 
 #
@@ -372,6 +382,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -389,7 +400,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -528,7 +543,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -572,6 +586,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -727,22 +742,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-CONFIG_DAB=y
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -804,9 +804,14 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -823,12 +828,14 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -1012,17 +1019,15 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
@@ -1031,6 +1036,7 @@
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_KGDB is not set
+# CONFIG_KMEMCHECK is not set
 # CONFIG_SH_STANDARD_BIOS is not set
 CONFIG_EARLY_SCIF_CONSOLE=y
 CONFIG_EARLY_SCIF_CONSOLE_PORT=0xa4430000
@@ -1039,10 +1045,8 @@
 # CONFIG_DEBUG_STACKOVERFLOW is not set
 # CONFIG_DEBUG_STACK_USAGE is not set
 # CONFIG_4KSTACKS is not set
-# CONFIG_IRQSTACKS is not set
 CONFIG_DUMP_CODE=y
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1074,3 +1078,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/microdev_defconfig b/arch/sh/configs/microdev_defconfig
index 2886fc8..e5a21e1 100644
--- a/arch/sh/configs/microdev_defconfig
+++ b/arch/sh/configs/microdev_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:50:51 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:31:56 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -19,6 +19,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -74,7 +75,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -87,7 +87,12 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -171,6 +176,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -185,7 +191,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_HUGETLB_PAGE_SIZE_64K=y
 # CONFIG_HUGETLB_PAGE_SIZE_256K is not set
 # CONFIG_HUGETLB_PAGE_SIZE_1MB is not set
@@ -204,9 +209,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -224,7 +229,6 @@
 # CONFIG_SH_STORE_QUEUES is not set
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -235,9 +239,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=66000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -282,12 +287,14 @@
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200 root=/dev/hda1"
@@ -371,6 +378,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -388,7 +396,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -460,7 +472,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -485,6 +496,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 CONFIG_NETDEV_1000=y
 CONFIG_NETDEV_10000=y
 
@@ -582,22 +594,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -636,10 +633,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -659,10 +661,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -812,28 +815,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_PREEMPT_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -957,3 +944,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/migor_defconfig b/arch/sh/configs/migor_defconfig
index 8ecceb4..da627d2 100644
--- a/arch/sh/configs/migor_defconfig
+++ b/arch/sh/configs/migor_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:51:34 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 16:06:48 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -21,6 +21,7 @@
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_NUMA=y
 CONFIG_SYS_SUPPORTS_CMT=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -76,7 +77,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -89,14 +89,19 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
 # CONFIG_SLOB is not set
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 # CONFIG_KPROBES is not set
@@ -184,6 +189,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -202,7 +208,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 # CONFIG_FLATMEM_MANUAL is not set
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -217,9 +222,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -238,7 +243,6 @@
 # CONFIG_SH_STORE_QUEUES is not set
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_DSP=y
 
 #
@@ -252,10 +256,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
+CONFIG_SH_TIMER_TMU=y
 # CONFIG_SH_TIMER_CMT is not set
-CONFIG_SH_TIMER_IRQ=16
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -296,12 +300,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200 earlyprintk=serial ip=on root=/dev/nfs ip=dhcp"
 
@@ -384,6 +390,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -403,7 +410,11 @@
 CONFIG_WIRELESS_EXT=y
 CONFIG_WIRELESS_EXT_SYSFS=y
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -534,6 +545,7 @@
 #
 # CONFIG_EEPROM_AT24 is not set
 # CONFIG_EEPROM_LEGACY is not set
+# CONFIG_EEPROM_MAX6875 is not set
 # CONFIG_EEPROM_93CX6 is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
@@ -557,10 +569,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -577,6 +585,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_LIBFC is not set
 # CONFIG_LIBFCOE is not set
 # CONFIG_SCSI_DEBUG is not set
@@ -585,7 +594,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -610,6 +618,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -740,7 +749,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -796,10 +804,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
+CONFIG_MEDIA_SUPPORT=y
 
 #
 # Multimedia core support
@@ -899,6 +904,7 @@
 # CONFIG_USB_GADGET_OMAP is not set
 # CONFIG_USB_GADGET_PXA25X is not set
 # CONFIG_USB_GADGET_PXA27X is not set
+# CONFIG_USB_GADGET_S3C_HSOTG is not set
 # CONFIG_USB_GADGET_S3C2410 is not set
 # CONFIG_USB_GADGET_IMX is not set
 CONFIG_USB_GADGET_M66592=y
@@ -909,9 +915,11 @@
 # CONFIG_USB_GADGET_CI13XXX is not set
 # CONFIG_USB_GADGET_NET2280 is not set
 # CONFIG_USB_GADGET_GOKU is not set
+# CONFIG_USB_GADGET_LANGWELL is not set
 # CONFIG_USB_GADGET_DUMMY_HCD is not set
 CONFIG_USB_GADGET_DUALSPEED=y
 # CONFIG_USB_ZERO is not set
+# CONFIG_USB_AUDIO is not set
 # CONFIG_USB_ETH is not set
 # CONFIG_USB_GADGETFS is not set
 # CONFIG_USB_FILE_STORAGE is not set
@@ -983,6 +991,7 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 CONFIG_UIO=y
@@ -990,6 +999,10 @@
 CONFIG_UIO_PDRV_GENIRQ=y
 # CONFIG_UIO_SMX is not set
 # CONFIG_UIO_SERCOS3 is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1001,12 +1014,14 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -1111,24 +1126,11 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
@@ -1137,7 +1139,6 @@
 CONFIG_EARLY_SCIF_CONSOLE=y
 CONFIG_EARLY_SCIF_CONSOLE_PORT=0xffe00000
 CONFIG_EARLY_PRINTK=y
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1259,3 +1260,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/polaris_defconfig b/arch/sh/configs/polaris_defconfig
index 2b95072..67edd3f 100644
--- a/arch/sh/configs/polaris_defconfig
+++ b/arch/sh/configs/polaris_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:52:19 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:33:28 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -19,6 +19,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -78,7 +79,6 @@
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_ALL=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -91,7 +91,12 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -181,6 +186,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0C000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -195,7 +201,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -208,9 +213,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -240,9 +245,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=33000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 CONFIG_TICK_ONESHOT=y
 CONFIG_NO_HZ=y
 CONFIG_HIGH_RES_TIMERS=y
@@ -288,12 +294,14 @@
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC1,115200 root=/dev/mtdblock2 rootfstype=jffs2 mem=63M mtdparts=physmap-flash.0:0x00100000(bootloader)ro,0x00500000(Kernel)ro,0x00A00000(Filesystem)"
 
@@ -369,6 +377,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -522,7 +531,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -566,6 +574,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -678,22 +687,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -756,9 +750,14 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -770,12 +769,14 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -928,18 +929,16 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_PREEMPT_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
@@ -948,6 +947,7 @@
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_KGDB is not set
+# CONFIG_KMEMCHECK is not set
 # CONFIG_SH_STANDARD_BIOS is not set
 CONFIG_EARLY_SCIF_CONSOLE=y
 CONFIG_EARLY_SCIF_CONSOLE_PORT=0x00000000
@@ -956,10 +956,8 @@
 # CONFIG_DEBUG_STACKOVERFLOW is not set
 # CONFIG_DEBUG_STACK_USAGE is not set
 # CONFIG_4KSTACKS is not set
-# CONFIG_IRQSTACKS is not set
 CONFIG_DUMP_CODE=y
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -990,3 +988,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/r7780mp_defconfig b/arch/sh/configs/r7780mp_defconfig
index 943da63..107a8e3 100644
--- a/arch/sh/configs/r7780mp_defconfig
+++ b/arch/sh/configs/r7780mp_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:53:28 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:34:44 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -79,7 +80,6 @@
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_ALL is not set
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -92,15 +92,20 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
 # CONFIG_SLOB is not set
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=m
 CONFIG_HAVE_OPROFILE=y
 # CONFIG_KPROBES is not set
@@ -185,6 +190,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x08000000
 # CONFIG_29BIT is not set
@@ -203,7 +209,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_HUGETLB_PAGE_SIZE_64K=y
 # CONFIG_HUGETLB_PAGE_SIZE_256K is not set
 # CONFIG_HUGETLB_PAGE_SIZE_1MB is not set
@@ -222,9 +227,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -258,9 +263,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=28
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -301,12 +307,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200 root=/dev/sda1"
 
@@ -404,6 +412,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -423,7 +432,11 @@
 CONFIG_WIRELESS_EXT=y
 CONFIG_WIRELESS_EXT_SYSFS=y
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -445,7 +458,91 @@
 # CONFIG_DEBUG_DEVRES is not set
 # CONFIG_SYS_HYPERVISOR is not set
 # CONFIG_CONNECTOR is not set
-# CONFIG_MTD is not set
+CONFIG_MTD=y
+# CONFIG_MTD_DEBUG is not set
+# CONFIG_MTD_CONCAT is not set
+CONFIG_MTD_PARTITIONS=y
+# CONFIG_MTD_TESTS is not set
+# CONFIG_MTD_REDBOOT_PARTS is not set
+# CONFIG_MTD_CMDLINE_PARTS is not set
+# CONFIG_MTD_AR7_PARTS is not set
+
+#
+# User Modules And Translation Layers
+#
+# CONFIG_MTD_CHAR is not set
+# CONFIG_MTD_BLKDEVS is not set
+# CONFIG_MTD_BLOCK is not set
+# CONFIG_MTD_BLOCK_RO is not set
+# CONFIG_FTL is not set
+# CONFIG_NFTL is not set
+# CONFIG_INFTL is not set
+# CONFIG_RFD_FTL is not set
+# CONFIG_SSFDC is not set
+# CONFIG_MTD_OOPS is not set
+
+#
+# RAM/ROM/Flash chip drivers
+#
+CONFIG_MTD_CFI=y
+# CONFIG_MTD_JEDECPROBE is not set
+CONFIG_MTD_GEN_PROBE=y
+# CONFIG_MTD_CFI_ADV_OPTIONS is not set
+CONFIG_MTD_MAP_BANK_WIDTH_1=y
+CONFIG_MTD_MAP_BANK_WIDTH_2=y
+CONFIG_MTD_MAP_BANK_WIDTH_4=y
+# CONFIG_MTD_MAP_BANK_WIDTH_8 is not set
+# CONFIG_MTD_MAP_BANK_WIDTH_16 is not set
+# CONFIG_MTD_MAP_BANK_WIDTH_32 is not set
+CONFIG_MTD_CFI_I1=y
+CONFIG_MTD_CFI_I2=y
+# CONFIG_MTD_CFI_I4 is not set
+# CONFIG_MTD_CFI_I8 is not set
+# CONFIG_MTD_CFI_INTELEXT is not set
+CONFIG_MTD_CFI_AMDSTD=y
+# CONFIG_MTD_CFI_STAA is not set
+CONFIG_MTD_CFI_UTIL=y
+# CONFIG_MTD_RAM is not set
+# CONFIG_MTD_ROM is not set
+# CONFIG_MTD_ABSENT is not set
+
+#
+# Mapping drivers for chip access
+#
+CONFIG_MTD_COMPLEX_MAPPINGS=y
+CONFIG_MTD_PHYSMAP=y
+# CONFIG_MTD_PHYSMAP_COMPAT is not set
+# CONFIG_MTD_PCI is not set
+# CONFIG_MTD_INTEL_VR_NOR is not set
+# CONFIG_MTD_PLATRAM is not set
+
+#
+# Self-contained MTD device drivers
+#
+# CONFIG_MTD_PMC551 is not set
+# CONFIG_MTD_SLRAM is not set
+# CONFIG_MTD_PHRAM is not set
+# CONFIG_MTD_MTDRAM is not set
+# CONFIG_MTD_BLOCK2MTD is not set
+
+#
+# Disk-On-Chip Device Drivers
+#
+# CONFIG_MTD_DOC2000 is not set
+# CONFIG_MTD_DOC2001 is not set
+# CONFIG_MTD_DOC2001PLUS is not set
+# CONFIG_MTD_NAND is not set
+# CONFIG_MTD_ONENAND is not set
+
+#
+# LPDDR flash memory drivers
+#
+# CONFIG_MTD_LPDDR is not set
+
+#
+# UBI - Unsorted block images
+#
+# CONFIG_MTD_UBI is not set
 # CONFIG_PARPORT is not set
 CONFIG_BLK_DEV=y
 # CONFIG_BLK_CPQ_CISS_DA is not set
@@ -477,7 +574,9 @@
 #
 # CONFIG_EEPROM_AT24 is not set
 # CONFIG_EEPROM_LEGACY is not set
+# CONFIG_EEPROM_MAX6875 is not set
 CONFIG_EEPROM_93CX6=y
+# CONFIG_CB710_CORE is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
 
@@ -500,10 +599,6 @@
 # CONFIG_BLK_DEV_SR is not set
 CONFIG_CHR_DEV_SG=m
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -521,6 +616,7 @@
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
 # CONFIG_SCSI_CXGB3_ISCSI is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_BLK_DEV_3W_XXXX_RAID is not set
 # CONFIG_SCSI_3W_9XXX is not set
 # CONFIG_SCSI_ACARD is not set
@@ -529,6 +625,7 @@
 # CONFIG_SCSI_AIC7XXX_OLD is not set
 # CONFIG_SCSI_AIC79XX is not set
 # CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_ARCMSR is not set
 # CONFIG_MEGARAID_NEWGEN is not set
 # CONFIG_MEGARAID_LEGACY is not set
@@ -543,7 +640,6 @@
 # CONFIG_SCSI_IPS is not set
 # CONFIG_SCSI_INITIO is not set
 # CONFIG_SCSI_INIA100 is not set
-# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_STEX is not set
 # CONFIG_SCSI_SYM53C8XX_2 is not set
 # CONFIG_SCSI_IPR is not set
@@ -632,7 +728,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -686,6 +781,7 @@
 # CONFIG_SMSC9420 is not set
 # CONFIG_SUNDANCE is not set
 # CONFIG_TLAN is not set
+# CONFIG_KS8842 is not set
 CONFIG_VIA_RHINE=m
 CONFIG_VIA_RHINE_MMIO=y
 # CONFIG_SC92031 is not set
@@ -894,7 +990,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -953,6 +1048,7 @@
 # CONFIG_SENSORS_SMSC47B397 is not set
 # CONFIG_SENSORS_ADS7828 is not set
 # CONFIG_SENSORS_THMC50 is not set
+# CONFIG_SENSORS_TMP401 is not set
 # CONFIG_SENSORS_VIA686A is not set
 # CONFIG_SENSORS_VT1211 is not set
 # CONFIG_SENSORS_VT8231 is not set
@@ -988,22 +1084,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-CONFIG_DAB=y
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -1111,9 +1192,14 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1134,10 +1220,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1145,6 +1232,7 @@
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
 CONFIG_FUSE_FS=m
+# CONFIG_CUSE is not set
 
 #
 # Caches
@@ -1190,6 +1278,7 @@
 # CONFIG_BEFS_FS is not set
 # CONFIG_BFS_FS is not set
 # CONFIG_EFS_FS is not set
+# CONFIG_JFFS2_FS is not set
 # CONFIG_CRAMFS is not set
 # CONFIG_SQUASHFS is not set
 # CONFIG_VXFS_FS is not set
@@ -1328,41 +1417,40 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_PREEMPT_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
 # CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_RING_BUFFER_BENCHMARK is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_KGDB is not set
-CONFIG_SH_STANDARD_BIOS=y
-# CONFIG_EARLY_SCIF_CONSOLE is not set
-CONFIG_EARLY_PRINTK=y
+# CONFIG_SH_STANDARD_BIOS is not set
+CONFIG_EARLY_SCIF_CONSOLE=y
+CONFIG_EARLY_SCIF_CONSOLE_PORT=0xffe00000
+# CONFIG_EARLY_PRINTK is not set
 # CONFIG_DEBUG_BOOTMEM is not set
 CONFIG_DEBUG_STACKOVERFLOW=y
 # CONFIG_DEBUG_STACK_USAGE is not set
 # CONFIG_4KSTACKS is not set
-# CONFIG_IRQSTACKS is not set
 CONFIG_DUMP_CODE=y
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1486,3 +1574,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/r7785rp_defconfig b/arch/sh/configs/r7785rp_defconfig
index 82658f6..8a3dc30 100644
--- a/arch/sh/configs/r7785rp_defconfig
+++ b/arch/sh/configs/r7785rp_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:55:10 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:37:20 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -21,6 +21,7 @@
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_NUMA=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -80,7 +81,6 @@
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_ALL=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -93,15 +93,20 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
 # CONFIG_SLOB is not set
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 CONFIG_KPROBES=y
@@ -189,6 +194,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x08000000
 # CONFIG_29BIT is not set
@@ -211,7 +217,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_HUGETLB_PAGE_SIZE_64K is not set
 # CONFIG_HUGETLB_PAGE_SIZE_256K is not set
 CONFIG_HUGETLB_PAGE_SIZE_1MB=y
@@ -232,9 +237,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -252,7 +257,6 @@
 CONFIG_SH_STORE_QUEUES=y
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -267,9 +271,9 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=28
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
 CONFIG_TICK_ONESHOT=y
 CONFIG_NO_HZ=y
 CONFIG_HIGH_RES_TIMERS=y
@@ -326,12 +330,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200 root=/dev/sda1"
 
@@ -429,6 +435,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -449,7 +456,11 @@
 CONFIG_WIRELESS_EXT=y
 CONFIG_WIRELESS_EXT_SYSFS=y
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -503,7 +514,9 @@
 #
 # CONFIG_EEPROM_AT24 is not set
 # CONFIG_EEPROM_LEGACY is not set
+# CONFIG_EEPROM_MAX6875 is not set
 CONFIG_EEPROM_93CX6=y
+# CONFIG_CB710_CORE is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
 
@@ -526,10 +539,6 @@
 # CONFIG_BLK_DEV_SR is not set
 CONFIG_CHR_DEV_SG=m
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -547,6 +556,7 @@
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
 # CONFIG_SCSI_CXGB3_ISCSI is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_BLK_DEV_3W_XXXX_RAID is not set
 # CONFIG_SCSI_3W_9XXX is not set
 # CONFIG_SCSI_ACARD is not set
@@ -555,6 +565,7 @@
 # CONFIG_SCSI_AIC7XXX_OLD is not set
 # CONFIG_SCSI_AIC79XX is not set
 # CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_ARCMSR is not set
 # CONFIG_MEGARAID_NEWGEN is not set
 # CONFIG_MEGARAID_LEGACY is not set
@@ -569,7 +580,6 @@
 # CONFIG_SCSI_IPS is not set
 # CONFIG_SCSI_INITIO is not set
 # CONFIG_SCSI_INIA100 is not set
-# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_STEX is not set
 # CONFIG_SCSI_SYM53C8XX_2 is not set
 # CONFIG_SCSI_IPR is not set
@@ -658,7 +668,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -692,6 +701,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_NET_PCI is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_ATL2 is not set
 CONFIG_NETDEV_1000=y
 # CONFIG_ACENIC is not set
@@ -899,7 +909,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -983,6 +992,7 @@
 # CONFIG_SENSORS_SMSC47B397 is not set
 # CONFIG_SENSORS_ADS7828 is not set
 # CONFIG_SENSORS_THMC50 is not set
+# CONFIG_SENSORS_TMP401 is not set
 # CONFIG_SENSORS_VIA686A is not set
 # CONFIG_SENSORS_VT1211 is not set
 # CONFIG_SENSORS_VT8231 is not set
@@ -1019,22 +1029,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -1195,9 +1190,14 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1218,10 +1218,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1229,6 +1230,7 @@
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
 CONFIG_FUSE_FS=m
+# CONFIG_CUSE is not set
 
 #
 # Caches
@@ -1413,25 +1415,25 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_PREEMPT_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
 # CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_RING_BUFFER_BENCHMARK is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
@@ -1444,10 +1446,8 @@
 CONFIG_DEBUG_STACKOVERFLOW=y
 CONFIG_DEBUG_STACK_USAGE=y
 CONFIG_4KSTACKS=y
-# CONFIG_IRQSTACKS is not set
 CONFIG_DUMP_CODE=y
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1572,3 +1572,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/rsk7201_defconfig b/arch/sh/configs/rsk7201_defconfig
index fa43957..55c3656 100644
--- a/arch/sh/configs/rsk7201_defconfig
+++ b/arch/sh/configs/rsk7201_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:56:29 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:39:54 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -15,10 +15,11 @@
 CONFIG_GENERIC_HARDIRQS_NO__DO_IRQ=y
 CONFIG_GENERIC_IRQ_PROBE=y
 # CONFIG_GENERIC_GPIO is not set
-# CONFIG_GENERIC_TIME is not set
-# CONFIG_GENERIC_CLOCKEVENTS is not set
+CONFIG_GENERIC_TIME=y
+CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 # CONFIG_ARCH_HIBERNATION_POSSIBLE is not set
+CONFIG_SYS_SUPPORTS_MTU2=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -74,7 +75,6 @@
 CONFIG_SYSCTL_SYSCALL=y
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -86,14 +86,19 @@
 CONFIG_TIMERFD=y
 CONFIG_EVENTFD=y
 # CONFIG_AIO is not set
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 # CONFIG_SLAB is not set
 # CONFIG_SLUB is not set
 CONFIG_SLOB=y
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 # CONFIG_KPROBES is not set
@@ -175,6 +180,7 @@
 #
 CONFIG_QUICKLIST=y
 CONFIG_PAGE_OFFSET=0x00000000
+CONFIG_FORCE_MAX_ZONEORDER=14
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x01000000
 CONFIG_29BIT=y
@@ -188,7 +194,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -201,7 +206,8 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
+CONFIG_NOMMU_INITIAL_TRIM_EXCESS=1
 
 #
 # Cache configuration
@@ -228,10 +234,14 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_MTU2=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_MTU2=y
 CONFIG_SH_PCLK_FREQ=40000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 CONFIG_SH_CLK_MD=0
+# CONFIG_NO_HZ is not set
+# CONFIG_HIGH_RES_TIMERS is not set
+CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
 
 #
 # CPU Frequency scaling
@@ -267,12 +277,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200 earlyprintk=serial ignore_loglevel"
 
@@ -506,21 +518,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-CONFIG_DAB=y
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -578,9 +576,14 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -593,11 +596,13 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-# CONFIG_FILE_LOCKING is not set
 # CONFIG_XFS_FS is not set
 # CONFIG_BTRFS_FS is not set
+# CONFIG_FILE_LOCKING is not set
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -696,30 +701,17 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -749,3 +741,4 @@
 CONFIG_HAS_IOMEM=y
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/rsk7203_defconfig b/arch/sh/configs/rsk7203_defconfig
index e3a65f8..69e6199 100644
--- a/arch/sh/configs/rsk7203_defconfig
+++ b/arch/sh/configs/rsk7203_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:57:06 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:40:44 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -15,11 +15,12 @@
 CONFIG_GENERIC_HARDIRQS_NO__DO_IRQ=y
 CONFIG_GENERIC_IRQ_PROBE=y
 CONFIG_GENERIC_GPIO=y
-# CONFIG_GENERIC_TIME is not set
-# CONFIG_GENERIC_CLOCKEVENTS is not set
+CONFIG_GENERIC_TIME=y
+CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 # CONFIG_ARCH_HIBERNATION_POSSIBLE is not set
 CONFIG_SYS_SUPPORTS_CMT=y
+CONFIG_SYS_SUPPORTS_MTU2=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -81,7 +82,6 @@
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_ALL=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -93,14 +93,19 @@
 CONFIG_TIMERFD=y
 CONFIG_EVENTFD=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 # CONFIG_SLAB is not set
 # CONFIG_SLUB is not set
 CONFIG_SLOB=y
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 # CONFIG_KPROBES is not set
@@ -182,6 +187,7 @@
 #
 CONFIG_QUICKLIST=y
 CONFIG_PAGE_OFFSET=0x00000000
+CONFIG_FORCE_MAX_ZONEORDER=14
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x01000000
 CONFIG_29BIT=y
@@ -195,7 +201,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -208,7 +213,8 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
+CONFIG_NOMMU_INITIAL_TRIM_EXCESS=1
 
 #
 # Cache configuration
@@ -235,11 +241,15 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_CMT=y
-# CONFIG_SH_MTU2 is not set
-CONFIG_SH_TIMER_IRQ=142
+CONFIG_SH_TIMER_CMT=y
+CONFIG_SH_TIMER_MTU2=y
 CONFIG_SH_PCLK_FREQ=16670800
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 CONFIG_SH_CLK_MD=0
+# CONFIG_NO_HZ is not set
+# CONFIG_HIGH_RES_TIMERS is not set
+CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
 
 #
 # CPU Frequency scaling
@@ -290,12 +300,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200 earlyprintk=serial ignore_loglevel"
 
@@ -375,6 +387,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -393,7 +406,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -528,7 +545,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -572,6 +588,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -705,24 +722,9 @@
 # CONFIG_REGULATOR_DEBUG is not set
 # CONFIG_REGULATOR_FIXED_VOLTAGE is not set
 # CONFIG_REGULATOR_VIRTUAL_CONSUMER is not set
+# CONFIG_REGULATOR_USERSPACE_CONSUMER is not set
 # CONFIG_REGULATOR_BQ24022 is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-CONFIG_DAB=y
-# CONFIG_USB_DABUSB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -758,7 +760,7 @@
 CONFIG_HID_CHERRY=y
 CONFIG_HID_CHICONY=y
 CONFIG_HID_CYPRESS=y
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 CONFIG_HID_EZKEY=y
 # CONFIG_HID_KYE is not set
 CONFIG_HID_GYRATION=y
@@ -775,10 +777,11 @@
 CONFIG_HID_SAMSUNG=y
 CONFIG_HID_SONY=y
 CONFIG_HID_SUNPLUS=y
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-CONFIG_THRUSTMASTER_FF=m
-CONFIG_ZEROPLUS_FF=m
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 # CONFIG_USB_ARCH_HAS_OHCI is not set
@@ -931,9 +934,14 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -945,12 +953,14 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -1029,7 +1039,46 @@
 #
 # CONFIG_PARTITION_ADVANCED is not set
 CONFIG_MSDOS_PARTITION=y
-# CONFIG_NLS is not set
+CONFIG_NLS=y
+CONFIG_NLS_DEFAULT="iso8859-1"
+# CONFIG_NLS_CODEPAGE_437 is not set
+# CONFIG_NLS_CODEPAGE_737 is not set
+# CONFIG_NLS_CODEPAGE_775 is not set
+# CONFIG_NLS_CODEPAGE_850 is not set
+# CONFIG_NLS_CODEPAGE_852 is not set
+# CONFIG_NLS_CODEPAGE_855 is not set
+# CONFIG_NLS_CODEPAGE_857 is not set
+# CONFIG_NLS_CODEPAGE_860 is not set
+# CONFIG_NLS_CODEPAGE_861 is not set
+# CONFIG_NLS_CODEPAGE_862 is not set
+# CONFIG_NLS_CODEPAGE_863 is not set
+# CONFIG_NLS_CODEPAGE_864 is not set
+# CONFIG_NLS_CODEPAGE_865 is not set
+# CONFIG_NLS_CODEPAGE_866 is not set
+# CONFIG_NLS_CODEPAGE_869 is not set
+# CONFIG_NLS_CODEPAGE_936 is not set
+# CONFIG_NLS_CODEPAGE_950 is not set
+# CONFIG_NLS_CODEPAGE_932 is not set
+# CONFIG_NLS_CODEPAGE_949 is not set
+# CONFIG_NLS_CODEPAGE_874 is not set
+# CONFIG_NLS_ISO8859_8 is not set
+# CONFIG_NLS_CODEPAGE_1250 is not set
+# CONFIG_NLS_CODEPAGE_1251 is not set
+# CONFIG_NLS_ASCII is not set
+# CONFIG_NLS_ISO8859_1 is not set
+# CONFIG_NLS_ISO8859_2 is not set
+# CONFIG_NLS_ISO8859_3 is not set
+# CONFIG_NLS_ISO8859_4 is not set
+# CONFIG_NLS_ISO8859_5 is not set
+# CONFIG_NLS_ISO8859_6 is not set
+# CONFIG_NLS_ISO8859_7 is not set
+# CONFIG_NLS_ISO8859_9 is not set
+# CONFIG_NLS_ISO8859_13 is not set
+# CONFIG_NLS_ISO8859_14 is not set
+# CONFIG_NLS_ISO8859_15 is not set
+# CONFIG_NLS_KOI8_R is not set
+# CONFIG_NLS_KOI8_U is not set
+# CONFIG_NLS_UTF8 is not set
 # CONFIG_DLM is not set
 
 #
@@ -1094,23 +1143,24 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
+# CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
 # CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_RING_BUFFER_BENCHMARK is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
@@ -1123,10 +1173,8 @@
 CONFIG_DEBUG_BOOTMEM=y
 CONFIG_DEBUG_STACKOVERFLOW=y
 CONFIG_DEBUG_STACK_USAGE=y
-# CONFIG_IRQSTACKS is not set
 CONFIG_DUMP_CODE=y
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1156,3 +1204,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/rts7751r2d1_defconfig b/arch/sh/configs/rts7751r2d1_defconfig
index a4a59f6..c6e9b1c 100644
--- a/arch/sh/configs/rts7751r2d1_defconfig
+++ b/arch/sh/configs/rts7751r2d1_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:58:13 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:42:26 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -71,7 +72,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -84,15 +84,20 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
 # CONFIG_SLOB is not set
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 # CONFIG_KPROBES is not set
@@ -176,6 +181,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -190,7 +196,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -203,9 +208,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -223,7 +228,6 @@
 # CONFIG_SH_STORE_QUEUES is not set
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -245,9 +249,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=60000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -289,12 +294,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00010000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=tty0 console=ttySC0,115200 root=/dev/sda1 earlyprintk=serial"
@@ -385,6 +392,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -404,7 +412,11 @@
 CONFIG_WIRELESS_EXT=y
 CONFIG_WIRELESS_EXT_SYSFS=y
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -455,6 +467,7 @@
 #
 # CONFIG_EEPROM_AT25 is not set
 # CONFIG_EEPROM_93CX6 is not set
+# CONFIG_CB710_CORE is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
 
@@ -477,10 +490,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -498,6 +507,7 @@
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
 # CONFIG_SCSI_CXGB3_ISCSI is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_BLK_DEV_3W_XXXX_RAID is not set
 # CONFIG_SCSI_3W_9XXX is not set
 # CONFIG_SCSI_ACARD is not set
@@ -506,6 +516,7 @@
 # CONFIG_SCSI_AIC7XXX_OLD is not set
 # CONFIG_SCSI_AIC79XX is not set
 # CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_ARCMSR is not set
 # CONFIG_MEGARAID_NEWGEN is not set
 # CONFIG_MEGARAID_LEGACY is not set
@@ -520,7 +531,6 @@
 # CONFIG_SCSI_IPS is not set
 # CONFIG_SCSI_INITIO is not set
 # CONFIG_SCSI_INIA100 is not set
-# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_STEX is not set
 # CONFIG_SCSI_SYM53C8XX_2 is not set
 # CONFIG_SCSI_IPR is not set
@@ -609,7 +619,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -663,6 +672,7 @@
 # CONFIG_SMSC9420 is not set
 # CONFIG_SUNDANCE is not set
 # CONFIG_TLAN is not set
+# CONFIG_KS8842 is not set
 # CONFIG_VIA_RHINE is not set
 # CONFIG_SC92031 is not set
 # CONFIG_ATL2 is not set
@@ -871,23 +881,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-CONFIG_DAB=y
-# CONFIG_USB_DABUSB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -989,6 +983,11 @@
 # CONFIG_SND_VERBOSE_PRINTK is not set
 # CONFIG_SND_DEBUG is not set
 CONFIG_SND_VMASTER=y
+# CONFIG_SND_RAWMIDI_SEQ is not set
+# CONFIG_SND_OPL3_LIB_SEQ is not set
+# CONFIG_SND_OPL4_LIB_SEQ is not set
+# CONFIG_SND_SBAWE_SEQ is not set
+# CONFIG_SND_EMU10K1_SEQ is not set
 CONFIG_SND_MPU401_UART=m
 CONFIG_SND_OPL3_LIB=m
 CONFIG_SND_AC97_CODEC=m
@@ -1015,6 +1014,7 @@
 # CONFIG_SND_OXYGEN is not set
 # CONFIG_SND_CS4281 is not set
 # CONFIG_SND_CS46XX is not set
+# CONFIG_SND_CTXFI is not set
 # CONFIG_SND_DARLA20 is not set
 # CONFIG_SND_GINA20 is not set
 # CONFIG_SND_LAYLA20 is not set
@@ -1045,6 +1045,7 @@
 # CONFIG_SND_INTEL8X0 is not set
 # CONFIG_SND_INTEL8X0M is not set
 # CONFIG_SND_KORG1212 is not set
+# CONFIG_SND_LX6464ES is not set
 # CONFIG_SND_MAESTRO3 is not set
 # CONFIG_SND_MIXART is not set
 # CONFIG_SND_NM256 is not set
@@ -1089,7 +1090,7 @@
 CONFIG_HID_CHERRY=y
 CONFIG_HID_CHICONY=y
 CONFIG_HID_CYPRESS=y
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 CONFIG_HID_EZKEY=y
 # CONFIG_HID_KYE is not set
 CONFIG_HID_GYRATION=y
@@ -1106,10 +1107,11 @@
 CONFIG_HID_SAMSUNG=y
 CONFIG_HID_SONY=y
 CONFIG_HID_SUNPLUS=y
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-CONFIG_THRUSTMASTER_FF=m
-CONFIG_ZEROPLUS_FF=m
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 CONFIG_USB_ARCH_HAS_OHCI=y
@@ -1135,6 +1137,7 @@
 # USB Host Controller Drivers
 #
 # CONFIG_USB_C67X00_HCD is not set
+# CONFIG_USB_XHCI_HCD is not set
 # CONFIG_USB_EHCI_HCD is not set
 # CONFIG_USB_OXU210HP_HCD is not set
 # CONFIG_USB_ISP116X_HCD is not set
@@ -1268,9 +1271,14 @@
 # on-CPU RTC drivers
 #
 # CONFIG_RTC_DRV_SH is not set
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1284,10 +1292,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1428,24 +1437,11 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
@@ -1454,7 +1450,6 @@
 CONFIG_EARLY_SCIF_CONSOLE=y
 CONFIG_EARLY_SCIF_CONSOLE_PORT=0xffe80000
 CONFIG_EARLY_PRINTK=y
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1568,3 +1563,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/rts7751r2dplus_defconfig b/arch/sh/configs/rts7751r2dplus_defconfig
index a860435..bc10469 100644
--- a/arch/sh/configs/rts7751r2dplus_defconfig
+++ b/arch/sh/configs/rts7751r2dplus_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:59:01 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:43:19 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -71,7 +72,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -84,15 +84,20 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
 # CONFIG_SLOB is not set
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 # CONFIG_KPROBES is not set
@@ -176,6 +181,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -190,7 +196,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -203,9 +208,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -223,7 +228,6 @@
 # CONFIG_SH_STORE_QUEUES is not set
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -245,9 +249,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=60000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -289,12 +294,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00010000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=tty0 console=ttySC0,115200 root=/dev/sda1 earlyprintk=serial"
@@ -385,6 +392,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -404,7 +412,11 @@
 CONFIG_WIRELESS_EXT=y
 CONFIG_WIRELESS_EXT_SYSFS=y
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -540,6 +552,7 @@
 #
 # CONFIG_EEPROM_AT25 is not set
 # CONFIG_EEPROM_93CX6 is not set
+# CONFIG_CB710_CORE is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
 
@@ -562,10 +575,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -583,6 +592,7 @@
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
 # CONFIG_SCSI_CXGB3_ISCSI is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_BLK_DEV_3W_XXXX_RAID is not set
 # CONFIG_SCSI_3W_9XXX is not set
 # CONFIG_SCSI_ACARD is not set
@@ -591,6 +601,7 @@
 # CONFIG_SCSI_AIC7XXX_OLD is not set
 # CONFIG_SCSI_AIC79XX is not set
 # CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_ARCMSR is not set
 # CONFIG_MEGARAID_NEWGEN is not set
 # CONFIG_MEGARAID_LEGACY is not set
@@ -605,7 +616,6 @@
 # CONFIG_SCSI_IPS is not set
 # CONFIG_SCSI_INITIO is not set
 # CONFIG_SCSI_INIA100 is not set
-# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_STEX is not set
 # CONFIG_SCSI_SYM53C8XX_2 is not set
 # CONFIG_SCSI_IPR is not set
@@ -694,7 +704,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -748,6 +757,7 @@
 # CONFIG_SMSC9420 is not set
 # CONFIG_SUNDANCE is not set
 # CONFIG_TLAN is not set
+# CONFIG_KS8842 is not set
 # CONFIG_VIA_RHINE is not set
 # CONFIG_SC92031 is not set
 # CONFIG_ATL2 is not set
@@ -956,23 +966,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-CONFIG_DAB=y
-# CONFIG_USB_DABUSB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -1074,6 +1068,11 @@
 # CONFIG_SND_VERBOSE_PRINTK is not set
 # CONFIG_SND_DEBUG is not set
 CONFIG_SND_VMASTER=y
+# CONFIG_SND_RAWMIDI_SEQ is not set
+# CONFIG_SND_OPL3_LIB_SEQ is not set
+# CONFIG_SND_OPL4_LIB_SEQ is not set
+# CONFIG_SND_SBAWE_SEQ is not set
+# CONFIG_SND_EMU10K1_SEQ is not set
 CONFIG_SND_MPU401_UART=m
 CONFIG_SND_OPL3_LIB=m
 CONFIG_SND_AC97_CODEC=m
@@ -1100,6 +1099,7 @@
 # CONFIG_SND_OXYGEN is not set
 # CONFIG_SND_CS4281 is not set
 # CONFIG_SND_CS46XX is not set
+# CONFIG_SND_CTXFI is not set
 # CONFIG_SND_DARLA20 is not set
 # CONFIG_SND_GINA20 is not set
 # CONFIG_SND_LAYLA20 is not set
@@ -1130,6 +1130,7 @@
 # CONFIG_SND_INTEL8X0 is not set
 # CONFIG_SND_INTEL8X0M is not set
 # CONFIG_SND_KORG1212 is not set
+# CONFIG_SND_LX6464ES is not set
 # CONFIG_SND_MAESTRO3 is not set
 # CONFIG_SND_MIXART is not set
 # CONFIG_SND_NM256 is not set
@@ -1174,7 +1175,7 @@
 CONFIG_HID_CHERRY=y
 CONFIG_HID_CHICONY=y
 CONFIG_HID_CYPRESS=y
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 CONFIG_HID_EZKEY=y
 # CONFIG_HID_KYE is not set
 CONFIG_HID_GYRATION=y
@@ -1191,10 +1192,11 @@
 CONFIG_HID_SAMSUNG=y
 CONFIG_HID_SONY=y
 CONFIG_HID_SUNPLUS=y
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-CONFIG_THRUSTMASTER_FF=m
-CONFIG_ZEROPLUS_FF=m
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 CONFIG_USB_ARCH_HAS_OHCI=y
@@ -1220,6 +1222,7 @@
 # USB Host Controller Drivers
 #
 # CONFIG_USB_C67X00_HCD is not set
+# CONFIG_USB_XHCI_HCD is not set
 # CONFIG_USB_EHCI_HCD is not set
 # CONFIG_USB_OXU210HP_HCD is not set
 # CONFIG_USB_ISP116X_HCD is not set
@@ -1353,9 +1356,14 @@
 # on-CPU RTC drivers
 #
 # CONFIG_RTC_DRV_SH is not set
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1369,10 +1377,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1423,6 +1432,7 @@
 # CONFIG_BEFS_FS is not set
 # CONFIG_BFS_FS is not set
 # CONFIG_EFS_FS is not set
+# CONFIG_JFFS2_FS is not set
 # CONFIG_CRAMFS is not set
 # CONFIG_SQUASHFS is not set
 # CONFIG_VXFS_FS is not set
@@ -1513,24 +1523,11 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
@@ -1539,7 +1536,6 @@
 CONFIG_EARLY_SCIF_CONSOLE=y
 CONFIG_EARLY_SCIF_CONSOLE_PORT=0xffe80000
 CONFIG_EARLY_PRINTK=y
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1653,3 +1649,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/sdk7780_defconfig b/arch/sh/configs/sdk7780_defconfig
index a629b79..753fb27 100644
--- a/arch/sh/configs/sdk7780_defconfig
+++ b/arch/sh/configs/sdk7780_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 12:59:32 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:43:54 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -75,7 +76,6 @@
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_ALL=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -88,9 +88,14 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
 CONFIG_SLUB_DEBUG=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 # CONFIG_SLAB is not set
 CONFIG_SLUB=y
@@ -181,6 +186,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x08000000
 # CONFIG_29BIT is not set
@@ -199,7 +205,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_HUGETLB_PAGE_SIZE_64K=y
 # CONFIG_HUGETLB_PAGE_SIZE_256K is not set
 # CONFIG_HUGETLB_PAGE_SIZE_1MB is not set
@@ -218,9 +223,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -252,9 +257,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=28
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 CONFIG_TICK_ONESHOT=y
 # CONFIG_NO_HZ is not set
 CONFIG_HIGH_RES_TIMERS=y
@@ -300,12 +306,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x01800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="mem=128M console=tty0 console=ttySC0,115200 ip=bootp root=/dev/nfs nfsroot=192.168.0.1:/home/rootfs"
 
@@ -441,6 +449,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 CONFIG_NET_SCHED=y
 
 #
@@ -490,7 +499,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -613,10 +626,6 @@
 # CONFIG_BLK_DEV_SR_VENDOR is not set
 CONFIG_CHR_DEV_SG=y
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -633,6 +642,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_BLK_DEV_3W_XXXX_RAID is not set
 # CONFIG_SCSI_3W_9XXX is not set
 # CONFIG_SCSI_ACARD is not set
@@ -641,6 +651,7 @@
 # CONFIG_SCSI_AIC7XXX_OLD is not set
 # CONFIG_SCSI_AIC79XX is not set
 # CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_ARCMSR is not set
 # CONFIG_MEGARAID_NEWGEN is not set
 # CONFIG_MEGARAID_LEGACY is not set
@@ -655,7 +666,6 @@
 # CONFIG_SCSI_IPS is not set
 # CONFIG_SCSI_INITIO is not set
 # CONFIG_SCSI_INIA100 is not set
-# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_STEX is not set
 # CONFIG_SCSI_SYM53C8XX_2 is not set
 # CONFIG_SCSI_IPR is not set
@@ -756,7 +766,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -789,6 +798,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_NET_PCI is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NET_POCKET is not set
 # CONFIG_ATL2 is not set
 # CONFIG_NETDEV_1000 is not set
@@ -971,22 +981,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -1100,7 +1095,7 @@
 CONFIG_HID_CHERRY=y
 CONFIG_HID_CHICONY=y
 CONFIG_HID_CYPRESS=y
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 CONFIG_HID_EZKEY=y
 # CONFIG_HID_KYE is not set
 CONFIG_HID_GYRATION=y
@@ -1117,10 +1112,11 @@
 CONFIG_HID_SAMSUNG=y
 CONFIG_HID_SONY=y
 CONFIG_HID_SUNPLUS=y
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-CONFIG_THRUSTMASTER_FF=m
-CONFIG_ZEROPLUS_FF=m
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 CONFIG_USB_ARCH_HAS_OHCI=y
@@ -1146,6 +1142,7 @@
 # USB Host Controller Drivers
 #
 # CONFIG_USB_C67X00_HCD is not set
+# CONFIG_USB_XHCI_HCD is not set
 CONFIG_USB_EHCI_HCD=y
 # CONFIG_USB_EHCI_ROOT_HUB_TT is not set
 # CONFIG_USB_EHCI_TT_NEWSCHED is not set
@@ -1247,10 +1244,15 @@
 # CONFIG_LEDS_TRIGGERS is not set
 # CONFIG_ACCESSIBILITY is not set
 # CONFIG_INFINIBAND is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1272,11 +1274,12 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_GFS2_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1471,18 +1474,16 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_PREEMPT_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
@@ -1498,10 +1499,8 @@
 CONFIG_DEBUG_STACKOVERFLOW=y
 # CONFIG_DEBUG_STACK_USAGE is not set
 # CONFIG_4KSTACKS is not set
-# CONFIG_IRQSTACKS is not set
 CONFIG_DUMP_CODE=y
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1619,3 +1618,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/se7206_defconfig b/arch/sh/configs/se7206_defconfig
index 5caf85a..8dd2f13 100644
--- a/arch/sh/configs/se7206_defconfig
+++ b/arch/sh/configs/se7206_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:01:02 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:46:15 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -15,11 +15,12 @@
 CONFIG_GENERIC_HARDIRQS_NO__DO_IRQ=y
 CONFIG_GENERIC_IRQ_PROBE=y
 # CONFIG_GENERIC_GPIO is not set
-# CONFIG_GENERIC_TIME is not set
-# CONFIG_GENERIC_CLOCKEVENTS is not set
+CONFIG_GENERIC_TIME=y
+CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 # CONFIG_ARCH_HIBERNATION_POSSIBLE is not set
 CONFIG_SYS_SUPPORTS_CMT=y
+CONFIG_SYS_SUPPORTS_MTU2=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -47,6 +48,7 @@
 # CONFIG_TASKSTATS is not set
 CONFIG_AUDIT=y
 CONFIG_AUDITSYSCALL=y
+CONFIG_AUDIT_TREE=y
 
 #
 # RCU Subsystem
@@ -92,7 +94,6 @@
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_ALL=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -104,14 +105,19 @@
 CONFIG_TIMERFD=y
 CONFIG_EVENTFD=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_COMPAT_BRK is not set
 # CONFIG_SLAB is not set
 # CONFIG_SLUB is not set
 CONFIG_SLOB=y
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 # CONFIG_KPROBES is not set
@@ -194,6 +200,7 @@
 #
 CONFIG_QUICKLIST=y
 CONFIG_PAGE_OFFSET=0x00000000
+CONFIG_FORCE_MAX_ZONEORDER=14
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -207,7 +214,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -220,7 +226,8 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
+CONFIG_NOMMU_INITIAL_TRIM_EXCESS=1
 
 #
 # Cache configuration
@@ -245,11 +252,15 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_CMT=y
-# CONFIG_SH_MTU2 is not set
-CONFIG_SH_TIMER_IRQ=140
+CONFIG_SH_TIMER_CMT=y
+CONFIG_SH_TIMER_MTU2=y
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 CONFIG_SH_CLK_MD=6
+# CONFIG_NO_HZ is not set
+# CONFIG_HIGH_RES_TIMERS is not set
+CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
 
 #
 # CPU Frequency scaling
@@ -300,12 +311,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC3,115200 ignore_loglevel earlyprintk=serial"
 
@@ -390,6 +403,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -408,7 +422,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -543,7 +561,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -568,6 +585,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -650,22 +668,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -722,9 +725,14 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -737,12 +745,14 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
-# CONFIG_INOTIFY is not set
+CONFIG_INOTIFY=y
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -884,23 +894,25 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
+# CONFIG_IRQSOFF_TRACER is not set
+# CONFIG_PREEMPT_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
 # CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_RING_BUFFER_BENCHMARK is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
@@ -911,10 +923,8 @@
 # CONFIG_DEBUG_BOOTMEM is not set
 CONFIG_DEBUG_STACKOVERFLOW=y
 CONFIG_DEBUG_STACK_USAGE=y
-# CONFIG_IRQSTACKS is not set
 CONFIG_DUMP_CODE=y
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1037,3 +1047,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/se7343_defconfig b/arch/sh/configs/se7343_defconfig
index 004d531..18f46de 100644
--- a/arch/sh/configs/se7343_defconfig
+++ b/arch/sh/configs/se7343_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:01:44 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:47:07 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 CONFIG_ARCH_SUSPEND_POSSIBLE=y
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_CMT=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -75,7 +76,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -88,7 +88,12 @@
 CONFIG_EVENTFD=y
 # CONFIG_SHMEM is not set
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -180,6 +185,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x01000000
 CONFIG_29BIT=y
@@ -194,7 +200,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -207,9 +212,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -239,10 +244,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
+CONFIG_SH_TIMER_TMU=y
 # CONFIG_SH_TIMER_CMT is not set
-CONFIG_SH_TIMER_IRQ=16
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -283,12 +288,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200"
 
@@ -367,6 +374,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -384,7 +392,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -518,10 +530,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 CONFIG_SCSI_MULTI_LUN=y
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -542,7 +550,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -574,6 +581,7 @@
 CONFIG_USB_USBNET=y
 # CONFIG_USB_NET_AX8817X is not set
 CONFIG_USB_NET_CDCETHER=y
+# CONFIG_USB_NET_CDC_EEM is not set
 CONFIG_USB_NET_DM9601=y
 # CONFIG_USB_NET_SMSC95XX is not set
 # CONFIG_USB_NET_GL620A is not set
@@ -583,6 +591,7 @@
 # CONFIG_USB_NET_RNDIS_HOST is not set
 # CONFIG_USB_NET_CDC_SUBSET is not set
 # CONFIG_USB_NET_ZAURUS is not set
+# CONFIG_USB_NET_INT51X1 is not set
 # CONFIG_WAN is not set
 # CONFIG_PPP is not set
 # CONFIG_SLIP is not set
@@ -696,7 +705,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -729,106 +737,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-CONFIG_VIDEO_DEV=y
-CONFIG_VIDEO_V4L2_COMMON=y
-CONFIG_VIDEO_ALLOW_V4L1=y
-CONFIG_VIDEO_V4L1_COMPAT=y
-# CONFIG_DVB_CORE is not set
-CONFIG_VIDEO_MEDIA=y
-
-#
-# Multimedia drivers
-#
-# CONFIG_MEDIA_ATTACH is not set
-CONFIG_MEDIA_TUNER=y
-# CONFIG_MEDIA_TUNER_CUSTOMISE is not set
-CONFIG_MEDIA_TUNER_SIMPLE=y
-CONFIG_MEDIA_TUNER_TDA8290=y
-CONFIG_MEDIA_TUNER_TDA9887=y
-CONFIG_MEDIA_TUNER_TEA5761=y
-CONFIG_MEDIA_TUNER_TEA5767=y
-CONFIG_MEDIA_TUNER_MT20XX=y
-CONFIG_MEDIA_TUNER_XC2028=y
-CONFIG_MEDIA_TUNER_XC5000=y
-CONFIG_MEDIA_TUNER_MC44S803=y
-CONFIG_VIDEO_V4L2=y
-CONFIG_VIDEO_V4L1=y
-CONFIG_VIDEO_CAPTURE_DRIVERS=y
-# CONFIG_VIDEO_ADV_DEBUG is not set
-# CONFIG_VIDEO_FIXED_MINOR_RANGES is not set
-CONFIG_VIDEO_HELPER_CHIPS_AUTO=y
-# CONFIG_VIDEO_VIVI is not set
-# CONFIG_VIDEO_CPIA is not set
-# CONFIG_VIDEO_CPIA2 is not set
-# CONFIG_VIDEO_SAA5246A is not set
-# CONFIG_VIDEO_SAA5249 is not set
-# CONFIG_SOC_CAMERA is not set
-CONFIG_V4L_USB_DRIVERS=y
-# CONFIG_USB_VIDEO_CLASS is not set
-CONFIG_USB_VIDEO_CLASS_INPUT_EVDEV=y
-CONFIG_USB_GSPCA=m
-# CONFIG_USB_M5602 is not set
-# CONFIG_USB_STV06XX is not set
-# CONFIG_USB_GSPCA_CONEX is not set
-# CONFIG_USB_GSPCA_ETOMS is not set
-# CONFIG_USB_GSPCA_FINEPIX is not set
-# CONFIG_USB_GSPCA_MARS is not set
-# CONFIG_USB_GSPCA_MR97310A is not set
-# CONFIG_USB_GSPCA_OV519 is not set
-# CONFIG_USB_GSPCA_OV534 is not set
-# CONFIG_USB_GSPCA_PAC207 is not set
-# CONFIG_USB_GSPCA_PAC7311 is not set
-# CONFIG_USB_GSPCA_SONIXB is not set
-# CONFIG_USB_GSPCA_SONIXJ is not set
-# CONFIG_USB_GSPCA_SPCA500 is not set
-# CONFIG_USB_GSPCA_SPCA501 is not set
-# CONFIG_USB_GSPCA_SPCA505 is not set
-# CONFIG_USB_GSPCA_SPCA506 is not set
-# CONFIG_USB_GSPCA_SPCA508 is not set
-# CONFIG_USB_GSPCA_SPCA561 is not set
-# CONFIG_USB_GSPCA_SQ905 is not set
-# CONFIG_USB_GSPCA_SQ905C is not set
-# CONFIG_USB_GSPCA_STK014 is not set
-# CONFIG_USB_GSPCA_SUNPLUS is not set
-# CONFIG_USB_GSPCA_T613 is not set
-# CONFIG_USB_GSPCA_TV8532 is not set
-# CONFIG_USB_GSPCA_VC032X is not set
-# CONFIG_USB_GSPCA_ZC3XX is not set
-# CONFIG_VIDEO_PVRUSB2 is not set
-# CONFIG_VIDEO_HDPVR is not set
-# CONFIG_VIDEO_EM28XX is not set
-# CONFIG_VIDEO_CX231XX is not set
-# CONFIG_VIDEO_USBVISION is not set
-# CONFIG_USB_VICAM is not set
-# CONFIG_USB_IBMCAM is not set
-# CONFIG_USB_KONICAWC is not set
-# CONFIG_USB_QUICKCAM_MESSENGER is not set
-# CONFIG_USB_ET61X251 is not set
-# CONFIG_VIDEO_OVCAMCHIP is not set
-# CONFIG_USB_OV511 is not set
-# CONFIG_USB_SE401 is not set
-# CONFIG_USB_SN9C102 is not set
-# CONFIG_USB_STV680 is not set
-# CONFIG_USB_ZC0301 is not set
-# CONFIG_USB_PWC is not set
-CONFIG_USB_PWC_INPUT_EVDEV=y
-# CONFIG_USB_ZR364XX is not set
-# CONFIG_USB_STKWEBCAM is not set
-# CONFIG_USB_S2255 is not set
-CONFIG_RADIO_ADAPTERS=y
-# CONFIG_USB_DSBR is not set
-# CONFIG_USB_SI470X is not set
-# CONFIG_USB_MR800 is not set
-# CONFIG_RADIO_TEA5764 is not set
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -894,6 +803,11 @@
 CONFIG_SND_VERBOSE_PROCFS=y
 # CONFIG_SND_VERBOSE_PRINTK is not set
 # CONFIG_SND_DEBUG is not set
+# CONFIG_SND_RAWMIDI_SEQ is not set
+# CONFIG_SND_OPL3_LIB_SEQ is not set
+# CONFIG_SND_OPL4_LIB_SEQ is not set
+# CONFIG_SND_SBAWE_SEQ is not set
+# CONFIG_SND_EMU10K1_SEQ is not set
 CONFIG_SND_DRIVERS=y
 # CONFIG_SND_DUMMY is not set
 # CONFIG_SND_VIRMIDI is not set
@@ -927,7 +841,7 @@
 CONFIG_HID_CHERRY=y
 CONFIG_HID_CHICONY=y
 CONFIG_HID_CYPRESS=y
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 CONFIG_HID_EZKEY=y
 # CONFIG_HID_KYE is not set
 CONFIG_HID_GYRATION=y
@@ -944,10 +858,11 @@
 CONFIG_HID_SAMSUNG=y
 CONFIG_HID_SONY=y
 CONFIG_HID_SUNPLUS=y
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-# CONFIG_THRUSTMASTER_FF is not set
-# CONFIG_ZEROPLUS_FF is not set
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 # CONFIG_USB_ARCH_HAS_OHCI is not set
@@ -1042,6 +957,7 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
@@ -1050,6 +966,10 @@
 # CONFIG_UIO_PDRV_GENIRQ is not set
 # CONFIG_UIO_SMX is not set
 # CONFIG_UIO_SERCOS3 is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1069,12 +989,14 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -1167,7 +1089,46 @@
 #
 # CONFIG_PARTITION_ADVANCED is not set
 CONFIG_MSDOS_PARTITION=y
-# CONFIG_NLS is not set
+CONFIG_NLS=y
+CONFIG_NLS_DEFAULT="iso8859-1"
+# CONFIG_NLS_CODEPAGE_437 is not set
+# CONFIG_NLS_CODEPAGE_737 is not set
+# CONFIG_NLS_CODEPAGE_775 is not set
+# CONFIG_NLS_CODEPAGE_850 is not set
+# CONFIG_NLS_CODEPAGE_852 is not set
+# CONFIG_NLS_CODEPAGE_855 is not set
+# CONFIG_NLS_CODEPAGE_857 is not set
+# CONFIG_NLS_CODEPAGE_860 is not set
+# CONFIG_NLS_CODEPAGE_861 is not set
+# CONFIG_NLS_CODEPAGE_862 is not set
+# CONFIG_NLS_CODEPAGE_863 is not set
+# CONFIG_NLS_CODEPAGE_864 is not set
+# CONFIG_NLS_CODEPAGE_865 is not set
+# CONFIG_NLS_CODEPAGE_866 is not set
+# CONFIG_NLS_CODEPAGE_869 is not set
+# CONFIG_NLS_CODEPAGE_936 is not set
+# CONFIG_NLS_CODEPAGE_950 is not set
+# CONFIG_NLS_CODEPAGE_932 is not set
+# CONFIG_NLS_CODEPAGE_949 is not set
+# CONFIG_NLS_CODEPAGE_874 is not set
+# CONFIG_NLS_ISO8859_8 is not set
+# CONFIG_NLS_CODEPAGE_1250 is not set
+# CONFIG_NLS_CODEPAGE_1251 is not set
+# CONFIG_NLS_ASCII is not set
+# CONFIG_NLS_ISO8859_1 is not set
+# CONFIG_NLS_ISO8859_2 is not set
+# CONFIG_NLS_ISO8859_3 is not set
+# CONFIG_NLS_ISO8859_4 is not set
+# CONFIG_NLS_ISO8859_5 is not set
+# CONFIG_NLS_ISO8859_6 is not set
+# CONFIG_NLS_ISO8859_7 is not set
+# CONFIG_NLS_ISO8859_9 is not set
+# CONFIG_NLS_ISO8859_13 is not set
+# CONFIG_NLS_ISO8859_14 is not set
+# CONFIG_NLS_ISO8859_15 is not set
+# CONFIG_NLS_KOI8_R is not set
+# CONFIG_NLS_KOI8_U is not set
+# CONFIG_NLS_UTF8 is not set
 # CONFIG_DLM is not set
 
 #
@@ -1191,21 +1152,7 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
@@ -1213,7 +1160,6 @@
 CONFIG_EARLY_SCIF_CONSOLE=y
 CONFIG_EARLY_SCIF_CONSOLE_PORT=0xffe00000
 CONFIG_EARLY_PRINTK=y
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1328,3 +1274,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/se7619_defconfig b/arch/sh/configs/se7619_defconfig
index edbece5..724bb77 100644
--- a/arch/sh/configs/se7619_defconfig
+++ b/arch/sh/configs/se7619_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:02:32 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:47:56 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -15,8 +15,8 @@
 CONFIG_GENERIC_HARDIRQS_NO__DO_IRQ=y
 CONFIG_GENERIC_IRQ_PROBE=y
 # CONFIG_GENERIC_GPIO is not set
-# CONFIG_GENERIC_TIME is not set
-# CONFIG_GENERIC_CLOCKEVENTS is not set
+CONFIG_GENERIC_TIME=y
+CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 # CONFIG_ARCH_HIBERNATION_POSSIBLE is not set
 CONFIG_SYS_SUPPORTS_CMT=y
@@ -62,7 +62,6 @@
 # CONFIG_UID16 is not set
 # CONFIG_SYSCTL_SYSCALL is not set
 # CONFIG_KALLSYMS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_HOTPLUG is not set
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -74,7 +73,12 @@
 CONFIG_TIMERFD=y
 CONFIG_EVENTFD=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 # CONFIG_VM_EVENT_COUNTERS is not set
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -155,6 +159,7 @@
 #
 CONFIG_QUICKLIST=y
 CONFIG_PAGE_OFFSET=0x00000000
+CONFIG_FORCE_MAX_ZONEORDER=14
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -168,7 +173,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -181,7 +185,8 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
+CONFIG_NOMMU_INITIAL_TRIM_EXCESS=1
 
 #
 # Cache configuration
@@ -206,10 +211,14 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_CMT=y
-CONFIG_SH_TIMER_IRQ=86
+CONFIG_SH_TIMER_CMT=y
 CONFIG_SH_PCLK_FREQ=31250000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 CONFIG_SH_CLK_MD=5
+# CONFIG_NO_HZ is not set
+# CONFIG_HIGH_RES_TIMERS is not set
+CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
 
 #
 # CPU Frequency scaling
@@ -245,12 +254,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_CMDLINE_BOOL is not set
 
 #
@@ -479,21 +490,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-CONFIG_DAB=y
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -541,10 +538,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -556,11 +558,13 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -644,25 +648,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -689,3 +680,4 @@
 CONFIG_HAS_IOMEM=y
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/se7705_defconfig b/arch/sh/configs/se7705_defconfig
index bae161c..6ca6a2f 100644
--- a/arch/sh/configs/se7705_defconfig
+++ b/arch/sh/configs/se7705_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:02:52 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:48:18 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -19,6 +19,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -70,7 +71,6 @@
 CONFIG_UID16=y
 # CONFIG_SYSCTL_SYSCALL is not set
 # CONFIG_KALLSYMS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_HOTPLUG is not set
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -83,7 +83,12 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -171,6 +176,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x02000000
 CONFIG_29BIT=y
@@ -185,7 +191,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -198,9 +203,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -231,9 +236,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -275,12 +281,14 @@
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_CMDLINE_BOOL is not set
 
 #
@@ -361,6 +369,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -378,7 +387,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -507,7 +520,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -532,6 +544,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 CONFIG_NETDEV_1000=y
 CONFIG_NETDEV_10000=y
 
@@ -662,22 +675,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -725,10 +723,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -742,9 +745,10 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -856,27 +860,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_PREEMPT_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -991,3 +980,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/se7712_defconfig b/arch/sh/configs/se7712_defconfig
index 330043f..b8aae11 100644
--- a/arch/sh/configs/se7712_defconfig
+++ b/arch/sh/configs/se7712_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:03:27 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:49:00 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -18,6 +18,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -71,7 +72,6 @@
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_ALL=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 # CONFIG_BUG is not set
@@ -84,7 +84,12 @@
 CONFIG_EVENTFD=y
 # CONFIG_SHMEM is not set
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -173,6 +178,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x02000000
 CONFIG_29BIT=y
@@ -187,7 +193,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -200,9 +205,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -233,9 +238,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=66666666
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -277,12 +283,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200 root=/dev/sda1"
 
@@ -374,6 +382,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 CONFIG_NET_SCHED=y
 
 #
@@ -427,7 +436,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -568,10 +581,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -588,6 +597,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_LIBFC is not set
 # CONFIG_LIBFCOE is not set
 # CONFIG_SCSI_DEBUG is not set
@@ -601,7 +611,6 @@
 CONFIG_PATA_PLATFORM=y
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -646,6 +655,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 CONFIG_NETDEV_1000=y
 CONFIG_NETDEV_10000=y
 
@@ -730,22 +740,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -802,10 +797,15 @@
 # iptables trigger is under Netfilter config (LED target)
 #
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -827,12 +827,14 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -975,17 +977,15 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
@@ -994,16 +994,15 @@
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_KGDB is not set
+# CONFIG_KMEMCHECK is not set
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
 # CONFIG_DEBUG_BOOTMEM is not set
 # CONFIG_DEBUG_STACKOVERFLOW is not set
 # CONFIG_DEBUG_STACK_USAGE is not set
 # CONFIG_4KSTACKS is not set
-# CONFIG_IRQSTACKS is not set
 # CONFIG_DUMP_CODE is not set
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1129,3 +1128,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/se7721_defconfig b/arch/sh/configs/se7721_defconfig
index 5647891..306e21c 100644
--- a/arch/sh/configs/se7721_defconfig
+++ b/arch/sh/configs/se7721_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:04:19 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:50:49 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -18,6 +18,8 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_CMT=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -75,7 +77,6 @@
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_ALL=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 # CONFIG_BUG is not set
@@ -88,7 +89,12 @@
 CONFIG_EVENTFD=y
 # CONFIG_SHMEM is not set
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -177,6 +183,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x02000000
 CONFIG_29BIT=y
@@ -191,7 +198,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -204,9 +210,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -236,9 +242,11 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
+CONFIG_SH_TIMER_CMT=y
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -280,12 +288,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200 root=/dev/sda2"
 
@@ -377,6 +387,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 CONFIG_NET_SCHED=y
 
 #
@@ -430,7 +441,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -572,10 +587,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 CONFIG_SCSI_MULTI_LUN=y
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -601,7 +612,6 @@
 CONFIG_PATA_PLATFORM=y
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -735,22 +745,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -786,7 +781,7 @@
 CONFIG_HID_CHERRY=y
 CONFIG_HID_CHICONY=y
 CONFIG_HID_CYPRESS=y
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 CONFIG_HID_EZKEY=y
 # CONFIG_HID_KYE is not set
 CONFIG_HID_GYRATION=y
@@ -803,10 +798,11 @@
 CONFIG_HID_SAMSUNG=y
 CONFIG_HID_SONY=y
 CONFIG_HID_SUNPLUS=y
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-CONFIG_THRUSTMASTER_FF=m
-CONFIG_ZEROPLUS_FF=m
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 CONFIG_USB_ARCH_HAS_OHCI=y
@@ -934,10 +930,15 @@
 # iptables trigger is under Netfilter config (LED target)
 #
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -959,12 +960,14 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -1134,17 +1137,15 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
@@ -1153,16 +1154,15 @@
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_KGDB is not set
+# CONFIG_KMEMCHECK is not set
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
 # CONFIG_DEBUG_BOOTMEM is not set
 # CONFIG_DEBUG_STACKOVERFLOW is not set
 # CONFIG_DEBUG_STACK_USAGE is not set
 # CONFIG_4KSTACKS is not set
-# CONFIG_IRQSTACKS is not set
 # CONFIG_DUMP_CODE is not set
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1288,3 +1288,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/se7722_defconfig b/arch/sh/configs/se7722_defconfig
index 726fdbd..6194382 100644
--- a/arch/sh/configs/se7722_defconfig
+++ b/arch/sh/configs/se7722_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:05:29 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 12:54:24 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -21,6 +21,7 @@
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_NUMA=y
 CONFIG_SYS_SUPPORTS_CMT=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -78,7 +79,6 @@
 CONFIG_SYSCTL_SYSCALL=y
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -91,8 +91,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_SLUB_DEBUG=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 # CONFIG_SLAB is not set
 CONFIG_SLUB=y
@@ -187,6 +192,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -205,7 +211,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_HUGETLB_PAGE_SIZE_64K=y
 # CONFIG_HUGETLB_PAGE_SIZE_256K is not set
 # CONFIG_HUGETLB_PAGE_SIZE_1MB is not set
@@ -226,9 +231,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -247,7 +252,6 @@
 CONFIG_SH_STORE_QUEUES=y
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_DSP=y
 
 #
@@ -260,10 +264,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
+CONFIG_SH_TIMER_TMU=y
 # CONFIG_SH_TIMER_CMT is not set
-CONFIG_SH_TIMER_IRQ=16
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
 CONFIG_TICK_ONESHOT=y
 CONFIG_NO_HZ=y
 CONFIG_HIGH_RES_TIMERS=y
@@ -305,12 +309,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_CMDLINE_BOOL is not set
 
 #
@@ -389,6 +395,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -406,7 +413,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -467,10 +478,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -487,6 +494,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_LIBFC is not set
 # CONFIG_LIBFCOE is not set
 # CONFIG_SCSI_DEBUG is not set
@@ -500,7 +508,6 @@
 CONFIG_PATA_PLATFORM=y
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -525,6 +532,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 CONFIG_NETDEV_1000=y
 CONFIG_NETDEV_10000=y
 
@@ -656,22 +664,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-CONFIG_DAB=y
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -756,9 +749,14 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -779,10 +777,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -882,22 +881,7 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_PREEMPT_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
@@ -905,7 +889,6 @@
 CONFIG_SH_STANDARD_BIOS=y
 # CONFIG_EARLY_SCIF_CONSOLE is not set
 # CONFIG_EARLY_PRINTK is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1020,3 +1003,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/se7724_defconfig b/arch/sh/configs/se7724_defconfig
index 96d2587..3840270 100644
--- a/arch/sh/configs/se7724_defconfig
+++ b/arch/sh/configs/se7724_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc6
-# Tue May 26 13:18:09 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 16:09:05 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -76,7 +76,6 @@
 CONFIG_UID16=y
 CONFIG_SYSCTL_SYSCALL=y
 # CONFIG_KALLSYMS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -89,7 +88,12 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -209,9 +213,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -229,7 +233,6 @@
 # CONFIG_SH_STORE_QUEUES is not set
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -244,6 +247,7 @@
 CONFIG_SH_TIMER_TMU=y
 # CONFIG_SH_TIMER_CMT is not set
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -284,6 +288,7 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
@@ -373,6 +378,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -390,7 +396,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -534,6 +544,7 @@
 # CONFIG_EEPROM_AT24 is not set
 # CONFIG_EEPROM_AT25 is not set
 # CONFIG_EEPROM_LEGACY is not set
+# CONFIG_EEPROM_MAX6875 is not set
 # CONFIG_EEPROM_93CX6 is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
@@ -557,10 +568,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -577,6 +584,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_LIBFC is not set
 # CONFIG_LIBFCOE is not set
 # CONFIG_SCSI_DEBUG is not set
@@ -585,7 +593,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -617,6 +624,7 @@
 CONFIG_MII=y
 # CONFIG_AX88796 is not set
 # CONFIG_STNIC is not set
+# CONFIG_SH_ETH is not set
 CONFIG_SMC91X=y
 # CONFIG_ENC28J60 is not set
 # CONFIG_ETHOC is not set
@@ -631,6 +639,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -772,7 +781,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -844,10 +852,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
+CONFIG_MEDIA_SUPPORT=y
 
 #
 # Multimedia core support
@@ -1019,7 +1024,7 @@
 # CONFIG_HID_CHERRY is not set
 # CONFIG_HID_CHICONY is not set
 # CONFIG_HID_CYPRESS is not set
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 # CONFIG_HID_EZKEY is not set
 # CONFIG_HID_KYE is not set
 # CONFIG_HID_GYRATION is not set
@@ -1033,10 +1038,11 @@
 # CONFIG_HID_SAMSUNG is not set
 # CONFIG_HID_SONY is not set
 # CONFIG_HID_SUNPLUS is not set
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-# CONFIG_THRUSTMASTER_FF is not set
-# CONFIG_ZEROPLUS_FF is not set
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 # CONFIG_USB_ARCH_HAS_OHCI is not set
@@ -1228,6 +1234,10 @@
 CONFIG_UIO_PDRV_GENIRQ=y
 # CONFIG_UIO_SMX is not set
 # CONFIG_UIO_SERCOS3 is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1249,10 +1259,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1408,22 +1419,7 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_PREEMPT_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
@@ -1550,3 +1546,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/se7750_defconfig b/arch/sh/configs/se7750_defconfig
index ed1a123..564bf7b 100644
--- a/arch/sh/configs/se7750_defconfig
+++ b/arch/sh/configs/se7750_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:06:02 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:00:01 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -19,6 +19,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -71,7 +72,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_HOTPLUG is not set
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -84,7 +84,12 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -173,6 +178,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x02000000
 CONFIG_29BIT=y
@@ -187,7 +193,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -200,9 +205,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -221,7 +226,6 @@
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_IPR_IRQ=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -233,9 +237,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -277,12 +282,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 # CONFIG_CMDLINE_BOOL is not set
 
@@ -365,6 +372,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -382,7 +390,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -535,10 +547,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -555,6 +563,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_LIBFC is not set
 # CONFIG_LIBFCOE is not set
 # CONFIG_SCSI_DEBUG is not set
@@ -563,7 +572,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -588,6 +596,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 CONFIG_NETDEV_1000=y
 CONFIG_NETDEV_10000=y
 
@@ -697,22 +706,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -751,10 +745,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -766,10 +765,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -897,27 +897,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1032,3 +1017,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/se7751_defconfig b/arch/sh/configs/se7751_defconfig
index 55f3b78..eb431c4 100644
--- a/arch/sh/configs/se7751_defconfig
+++ b/arch/sh/configs/se7751_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:06:44 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:02:26 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -19,6 +19,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -74,7 +75,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_HOTPLUG is not set
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -87,7 +87,12 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -176,6 +181,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -190,7 +196,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -203,9 +208,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -224,7 +229,6 @@
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_IPR_IRQ=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -237,9 +241,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=60000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -281,12 +286,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00010000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC1,38400"
@@ -389,6 +396,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -406,7 +414,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -535,7 +547,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -560,6 +571,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 CONFIG_NETDEV_1000=y
 CONFIG_NETDEV_10000=y
 
@@ -660,22 +672,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -714,10 +711,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -731,10 +733,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -842,27 +845,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -978,3 +966,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/se7780_defconfig b/arch/sh/configs/se7780_defconfig
index c4f0af3..756beec 100644
--- a/arch/sh/configs/se7780_defconfig
+++ b/arch/sh/configs/se7780_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:07:14 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:03:56 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -68,7 +69,6 @@
 CONFIG_UID16=y
 CONFIG_SYSCTL_SYSCALL=y
 # CONFIG_KALLSYMS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_HOTPLUG is not set
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -81,8 +81,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -170,6 +175,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x08000000
 CONFIG_29BIT=y
@@ -186,7 +192,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 # CONFIG_FLATMEM_MANUAL is not set
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -200,9 +205,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -233,9 +238,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=28
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -280,6 +286,7 @@
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00810000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0.115200 root=/dev/sda1"
 
@@ -323,6 +330,7 @@
 # CONFIG_NET_IPIP is not set
 # CONFIG_NET_IPGRE is not set
 # CONFIG_IP_MROUTE is not set
+# CONFIG_ARPD is not set
 # CONFIG_SYN_COOKIES is not set
 # CONFIG_INET_AH is not set
 # CONFIG_INET_ESP is not set
@@ -377,7 +385,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 
@@ -503,6 +515,7 @@
 # EEPROM support
 #
 # CONFIG_EEPROM_93CX6 is not set
+# CONFIG_CB710_CORE is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
 
@@ -524,10 +537,6 @@
 # CONFIG_BLK_DEV_SR is not set
 CONFIG_CHR_DEV_SG=y
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -544,6 +553,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_BLK_DEV_3W_XXXX_RAID is not set
 # CONFIG_SCSI_3W_9XXX is not set
 # CONFIG_SCSI_ACARD is not set
@@ -552,6 +562,7 @@
 # CONFIG_SCSI_AIC7XXX_OLD is not set
 # CONFIG_SCSI_AIC79XX is not set
 # CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_ARCMSR is not set
 # CONFIG_MEGARAID_NEWGEN is not set
 # CONFIG_MEGARAID_LEGACY is not set
@@ -566,7 +577,6 @@
 # CONFIG_SCSI_IPS is not set
 # CONFIG_SCSI_INITIO is not set
 # CONFIG_SCSI_INIA100 is not set
-# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_STEX is not set
 # CONFIG_SCSI_SYM53C8XX_2 is not set
 # CONFIG_SCSI_IPR is not set
@@ -643,7 +653,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_EQUALIZER is not set
@@ -709,6 +718,7 @@
 # CONFIG_SMSC9420 is not set
 # CONFIG_SUNDANCE is not set
 # CONFIG_TLAN is not set
+# CONFIG_KS8842 is not set
 # CONFIG_VIA_RHINE is not set
 # CONFIG_ATL2 is not set
 # CONFIG_NETDEV_1000 is not set
@@ -842,22 +852,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -965,7 +960,7 @@
 CONFIG_HID_CHERRY=y
 CONFIG_HID_CHICONY=y
 CONFIG_HID_CYPRESS=y
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 CONFIG_HID_EZKEY=y
 # CONFIG_HID_KYE is not set
 CONFIG_HID_GYRATION=y
@@ -982,10 +977,11 @@
 CONFIG_HID_SAMSUNG=y
 CONFIG_HID_SONY=y
 CONFIG_HID_SUNPLUS=y
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-CONFIG_THRUSTMASTER_FF=m
-CONFIG_ZEROPLUS_FF=m
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 CONFIG_USB_ARCH_HAS_OHCI=y
@@ -1097,10 +1093,15 @@
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
 # CONFIG_INFINIBAND is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1114,9 +1115,10 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1254,28 +1256,13 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1385,3 +1372,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/sh03_defconfig b/arch/sh/configs/sh03_defconfig
index f9c6e51..7fedaae 100644
--- a/arch/sh/configs/sh03_defconfig
+++ b/arch/sh/configs/sh03_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:07:56 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:04:41 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -17,9 +17,11 @@
 # CONFIG_GENERIC_GPIO is not set
 CONFIG_GENERIC_TIME=y
 CONFIG_GENERIC_CLOCKEVENTS=y
+CONFIG_GENERIC_CMOS_UPDATE=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -77,7 +79,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -90,15 +91,20 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
 # CONFIG_SLOB is not set
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=m
 CONFIG_HAVE_OPROFILE=y
 # CONFIG_KPROBES is not set
@@ -183,6 +189,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x08000000
 CONFIG_29BIT=y
@@ -197,7 +204,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -210,9 +216,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -231,7 +237,6 @@
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_IPR_IRQ=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -243,9 +248,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=60000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -287,12 +293,14 @@
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00004000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC1,115200 mem=64M root=/dev/nfs"
@@ -388,6 +396,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -406,7 +415,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -454,6 +467,7 @@
 # EEPROM support
 #
 # CONFIG_EEPROM_93CX6 is not set
+# CONFIG_CB710_CORE is not set
 CONFIG_HAVE_IDE=y
 CONFIG_IDE=y
 
@@ -526,10 +540,6 @@
 CONFIG_BLK_DEV_SR_VENDOR=y
 CONFIG_CHR_DEV_SG=m
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -547,6 +557,7 @@
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
 # CONFIG_SCSI_CXGB3_ISCSI is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_BLK_DEV_3W_XXXX_RAID is not set
 # CONFIG_SCSI_3W_9XXX is not set
 # CONFIG_SCSI_ACARD is not set
@@ -555,6 +566,7 @@
 # CONFIG_SCSI_AIC7XXX_OLD is not set
 # CONFIG_SCSI_AIC79XX is not set
 # CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_ARCMSR is not set
 # CONFIG_MEGARAID_NEWGEN is not set
 # CONFIG_MEGARAID_LEGACY is not set
@@ -569,7 +581,6 @@
 # CONFIG_SCSI_IPS is not set
 # CONFIG_SCSI_INITIO is not set
 # CONFIG_SCSI_INIA100 is not set
-# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_STEX is not set
 # CONFIG_SCSI_SYM53C8XX_2 is not set
 # CONFIG_SCSI_QLOGIC_1280 is not set
@@ -598,7 +609,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -647,6 +657,7 @@
 # CONFIG_SMSC9420 is not set
 # CONFIG_SUNDANCE is not set
 # CONFIG_TLAN is not set
+# CONFIG_KS8842 is not set
 # CONFIG_VIA_RHINE is not set
 # CONFIG_SC92031 is not set
 # CONFIG_ATL2 is not set
@@ -845,22 +856,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -916,10 +912,15 @@
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
 # CONFIG_INFINIBAND is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -942,10 +943,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1120,25 +1122,11 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_PREEMPT_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
@@ -1146,7 +1134,6 @@
 CONFIG_SH_STANDARD_BIOS=y
 # CONFIG_EARLY_SCIF_CONSOLE is not set
 # CONFIG_EARLY_PRINTK is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1273,3 +1260,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/sh7710voipgw_defconfig b/arch/sh/configs/sh7710voipgw_defconfig
index 48b5809..c296ca5 100644
--- a/arch/sh/configs/sh7710voipgw_defconfig
+++ b/arch/sh/configs/sh7710voipgw_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:09:16 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:06:13 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -19,6 +19,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -74,7 +75,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -87,7 +87,12 @@
 CONFIG_EVENTFD=y
 # CONFIG_SHMEM is not set
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -176,6 +181,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x00800000
 CONFIG_29BIT=y
@@ -190,7 +196,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -203,9 +208,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -234,9 +239,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=32768000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -278,12 +284,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_CMDLINE_BOOL is not set
 
 #
@@ -380,6 +388,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 CONFIG_NET_SCHED=y
 
 #
@@ -434,7 +443,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -564,7 +577,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -590,6 +602,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 CONFIG_NETDEV_1000=y
 CONFIG_NETDEV_10000=y
 
@@ -693,22 +706,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -756,10 +754,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -771,12 +774,14 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -881,28 +886,13 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1017,3 +1007,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/sh7724_generic_defconfig b/arch/sh/configs/sh7724_generic_defconfig
index ec8f18c..ba26be1 100644
--- a/arch/sh/configs/sh7724_generic_defconfig
+++ b/arch/sh/configs/sh7724_generic_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:09:47 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:06:48 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 CONFIG_ARCH_SUSPEND_POSSIBLE=y
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_CMT=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -79,7 +80,6 @@
 CONFIG_SYSCTL_SYSCALL=y
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -92,14 +92,19 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_COMPAT_BRK is not set
 # CONFIG_SLAB is not set
 CONFIG_SLUB=y
 # CONFIG_SLOB is not set
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 CONFIG_HAVE_IOREMAP_PROT=y
@@ -180,6 +185,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -197,7 +203,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 # CONFIG_FLATMEM_MANUAL is not set
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -215,9 +220,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -235,20 +240,20 @@
 # CONFIG_SH_STORE_QUEUES is not set
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
 # Board support
 #
+# CONFIG_SH_7724_SOLUTION_ENGINE is not set
 
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_TIMER_CMT=y
-CONFIG_SH_TIMER_IRQ=16
 CONFIG_SH_PCLK_FREQ=41666666
+CONFIG_SH_CLK_CPG=y
 CONFIG_TICK_ONESHOT=y
 CONFIG_NO_HZ=y
 CONFIG_HIGH_RES_TIMERS=y
@@ -305,12 +310,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_CMDLINE_BOOL is not set
 
 #
@@ -335,6 +342,7 @@
 CONFIG_PM_SLEEP=y
 CONFIG_SUSPEND=y
 CONFIG_SUSPEND_FREEZER=y
+CONFIG_HIBERNATION_NVS=y
 CONFIG_HIBERNATION=y
 CONFIG_PM_STD_PARTITION=""
 CONFIG_CPU_IDLE=y
@@ -451,7 +459,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -484,21 +491,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -570,6 +563,7 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 CONFIG_UIO=y
@@ -577,6 +571,10 @@
 CONFIG_UIO_PDRV_GENIRQ=y
 # CONFIG_UIO_SMX is not set
 # CONFIG_UIO_SERCOS3 is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -588,11 +586,13 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -657,30 +657,17 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -705,3 +692,4 @@
 CONFIG_HAS_IOMEM=y
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/sh7763rdp_defconfig b/arch/sh/configs/sh7763rdp_defconfig
index f77bc79..b1d9b23 100644
--- a/arch/sh/configs/sh7763rdp_defconfig
+++ b/arch/sh/configs/sh7763rdp_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:10:12 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:07:15 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -19,6 +19,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -79,7 +80,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -92,14 +92,19 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
 # CONFIG_SLOB is not set
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 # CONFIG_KPROBES is not set
@@ -184,6 +189,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -200,7 +206,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 # CONFIG_FLATMEM_MANUAL is not set
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -215,9 +220,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -246,9 +251,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=28
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=66666666
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -289,12 +295,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC2,115200 root=/dev/sda1 rootdelay=10"
 
@@ -377,6 +385,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -396,7 +405,11 @@
 CONFIG_WIRELESS_EXT=y
 CONFIG_WIRELESS_EXT_SYSFS=y
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -536,10 +549,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -556,6 +565,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_LIBFC is not set
 # CONFIG_LIBFCOE is not set
 # CONFIG_SCSI_DEBUG is not set
@@ -564,7 +574,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -609,6 +618,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -727,22 +737,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -931,10 +926,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -955,10 +955,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1109,31 +1110,17 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1246,3 +1233,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/sh7770_generic_defconfig b/arch/sh/configs/sh7770_generic_defconfig
index d6489b4..426a88f 100644
--- a/arch/sh/configs/sh7770_generic_defconfig
+++ b/arch/sh/configs/sh7770_generic_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc4
-# Tue May 12 14:48:21 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:08:05 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -79,7 +79,6 @@
 CONFIG_SYSCTL_SYSCALL=y
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -92,14 +91,19 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_COMPAT_BRK is not set
 # CONFIG_SLAB is not set
 CONFIG_SLUB=y
 # CONFIG_SLOB is not set
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 CONFIG_HAVE_IOREMAP_PROT=y
@@ -178,6 +182,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -211,9 +216,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -240,9 +245,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=41666666
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 CONFIG_TICK_ONESHOT=y
 CONFIG_NO_HZ=y
 CONFIG_HIGH_RES_TIMERS=y
@@ -299,6 +305,7 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
@@ -328,6 +335,7 @@
 CONFIG_PM=y
 # CONFIG_PM_DEBUG is not set
 CONFIG_PM_SLEEP=y
+CONFIG_HIBERNATION_NVS=y
 CONFIG_HIBERNATION=y
 CONFIG_PM_STD_PARTITION=""
 CONFIG_CPU_IDLE=y
@@ -444,7 +452,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -477,21 +484,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -571,6 +564,10 @@
 CONFIG_UIO_PDRV_GENIRQ=y
 # CONFIG_UIO_SMX is not set
 # CONFIG_UIO_SERCOS3 is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -582,11 +579,13 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -651,23 +650,11 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
@@ -698,3 +685,4 @@
 CONFIG_HAS_IOMEM=y
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/sh7785lcr_32bit_defconfig b/arch/sh/configs/sh7785lcr_32bit_defconfig
index 1c55b80..ed316f6 100644
--- a/arch/sh/configs/sh7785lcr_32bit_defconfig
+++ b/arch/sh/configs/sh7785lcr_32bit_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:10:53 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:08:29 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -21,6 +21,7 @@
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_NUMA=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -80,7 +81,6 @@
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_ALL is not set
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -93,8 +93,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -187,6 +192,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x40000000
 CONFIG_MEMORY_SIZE=0x20000000
 # CONFIG_29BIT is not set
@@ -209,7 +215,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 # CONFIG_FLATMEM_MANUAL is not set
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -224,9 +229,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -244,7 +249,6 @@
 CONFIG_SH_STORE_QUEUES=y
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -256,9 +260,9 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=28
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=50000000
+CONFIG_SH_CLK_CPG=y
 CONFIG_TICK_ONESHOT=y
 # CONFIG_NO_HZ is not set
 CONFIG_HIGH_RES_TIMERS=y
@@ -300,12 +304,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_CMDLINE_BOOL is not set
 
 #
@@ -400,6 +406,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -418,7 +425,11 @@
 CONFIG_WIRELESS_EXT=y
 CONFIG_WIRELESS_EXT_SYSFS=y
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -561,10 +572,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -656,7 +663,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -861,7 +867,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -894,22 +899,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -1017,7 +1007,7 @@
 CONFIG_HID_CHERRY=y
 CONFIG_HID_CHICONY=y
 CONFIG_HID_CYPRESS=y
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 CONFIG_HID_EZKEY=y
 # CONFIG_HID_KYE is not set
 CONFIG_HID_GYRATION=y
@@ -1034,10 +1024,11 @@
 CONFIG_HID_SAMSUNG=y
 CONFIG_HID_SONY=y
 CONFIG_HID_SUNPLUS=y
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-CONFIG_THRUSTMASTER_FF=m
-CONFIG_ZEROPLUS_FF=m
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 CONFIG_USB_ARCH_HAS_OHCI=y
@@ -1063,6 +1054,7 @@
 # USB Host Controller Drivers
 #
 # CONFIG_USB_C67X00_HCD is not set
+# CONFIG_USB_XHCI_HCD is not set
 CONFIG_USB_EHCI_HCD=m
 # CONFIG_USB_EHCI_ROOT_HUB_TT is not set
 # CONFIG_USB_EHCI_TT_NEWSCHED is not set
@@ -1210,9 +1202,14 @@
 # on-CPU RTC drivers
 #
 # CONFIG_RTC_DRV_SH is not set
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1232,10 +1229,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1428,18 +1426,16 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_PREEMPT_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
@@ -1454,10 +1450,8 @@
 # CONFIG_DEBUG_STACKOVERFLOW is not set
 # CONFIG_DEBUG_STACK_USAGE is not set
 # CONFIG_4KSTACKS is not set
-# CONFIG_IRQSTACKS is not set
 # CONFIG_DUMP_CODE is not set
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1580,3 +1574,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/sh7785lcr_defconfig b/arch/sh/configs/sh7785lcr_defconfig
index 4385fe9..004e6f5 100644
--- a/arch/sh/configs/sh7785lcr_defconfig
+++ b/arch/sh/configs/sh7785lcr_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:11:48 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:09:34 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -21,6 +21,7 @@
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_NUMA=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -80,7 +81,6 @@
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_ALL is not set
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -93,8 +93,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -187,6 +192,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x08000000
 CONFIG_29BIT=y
@@ -204,7 +210,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -217,9 +222,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -237,7 +242,6 @@
 CONFIG_SH_STORE_QUEUES=y
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -250,9 +254,9 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=28
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=50000000
+CONFIG_SH_CLK_CPG=y
 CONFIG_TICK_ONESHOT=y
 # CONFIG_NO_HZ is not set
 CONFIG_HIGH_RES_TIMERS=y
@@ -294,12 +298,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_CMDLINE_BOOL is not set
 
 #
@@ -394,6 +400,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -412,7 +419,11 @@
 CONFIG_WIRELESS_EXT=y
 CONFIG_WIRELESS_EXT_SYSFS=y
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -555,10 +566,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -650,7 +657,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -855,7 +861,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -888,22 +893,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -1011,7 +1001,7 @@
 CONFIG_HID_CHERRY=y
 CONFIG_HID_CHICONY=y
 CONFIG_HID_CYPRESS=y
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 CONFIG_HID_EZKEY=y
 # CONFIG_HID_KYE is not set
 CONFIG_HID_GYRATION=y
@@ -1028,10 +1018,11 @@
 CONFIG_HID_SAMSUNG=y
 CONFIG_HID_SONY=y
 CONFIG_HID_SUNPLUS=y
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-CONFIG_THRUSTMASTER_FF=m
-CONFIG_ZEROPLUS_FF=m
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 CONFIG_USB_ARCH_HAS_OHCI=y
@@ -1057,6 +1048,7 @@
 # USB Host Controller Drivers
 #
 # CONFIG_USB_C67X00_HCD is not set
+# CONFIG_USB_XHCI_HCD is not set
 CONFIG_USB_EHCI_HCD=m
 # CONFIG_USB_EHCI_ROOT_HUB_TT is not set
 # CONFIG_USB_EHCI_TT_NEWSCHED is not set
@@ -1204,9 +1196,14 @@
 # on-CPU RTC drivers
 #
 # CONFIG_RTC_DRV_SH is not set
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1226,10 +1223,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1422,18 +1420,16 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_PREEMPT_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
@@ -1448,10 +1444,8 @@
 # CONFIG_DEBUG_STACKOVERFLOW is not set
 # CONFIG_DEBUG_STACK_USAGE is not set
 # CONFIG_4KSTACKS is not set
-# CONFIG_IRQSTACKS is not set
 # CONFIG_DUMP_CODE is not set
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1574,3 +1568,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/shmin_defconfig b/arch/sh/configs/shmin_defconfig
index 4e12025..ad7d609 100644
--- a/arch/sh/configs/shmin_defconfig
+++ b/arch/sh/configs/shmin_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:12:41 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:10:33 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -18,6 +18,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -64,7 +65,6 @@
 # CONFIG_UID16 is not set
 # CONFIG_SYSCTL_SYSCALL is not set
 # CONFIG_KALLSYMS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_HOTPLUG is not set
 CONFIG_PRINTK=y
 # CONFIG_BUG is not set
@@ -77,7 +77,12 @@
 CONFIG_EVENTFD=y
 # CONFIG_SHMEM is not set
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 # CONFIG_SLAB is not set
 # CONFIG_SLUB is not set
@@ -159,6 +164,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x00800000
 CONFIG_29BIT=y
@@ -173,7 +179,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -186,9 +191,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -216,9 +221,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=32000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -260,12 +266,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00210000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC1,115200 root=1f01 mtdparts=phys_mapped_flash:64k(firm)ro,-(sys) netdev=34,0x300,eth0 "
 
@@ -345,6 +353,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -362,7 +371,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -489,7 +502,6 @@
 # CONFIG_ATA is not set
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -514,6 +526,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 CONFIG_NETDEV_1000=y
 CONFIG_NETDEV_10000=y
 
@@ -599,22 +612,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -653,10 +651,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -668,11 +671,13 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -773,27 +778,13 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 CONFIG_SH_STANDARD_BIOS=y
 # CONFIG_EARLY_SCIF_CONSOLE is not set
 CONFIG_EARLY_PRINTK=y
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -905,3 +896,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/shx3_defconfig b/arch/sh/configs/shx3_defconfig
index c088144..207b0c9 100644
--- a/arch/sh/configs/shx3_defconfig
+++ b/arch/sh/configs/shx3_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:13:12 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:11:03 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -23,6 +23,7 @@
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_SMP=y
 CONFIG_SYS_SUPPORTS_NUMA=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 # CONFIG_ARCH_HAS_ILOG2_U32 is not set
@@ -98,7 +99,6 @@
 CONFIG_KALLSYMS=y
 CONFIG_KALLSYMS_ALL=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -111,14 +111,19 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 # CONFIG_SLAB is not set
 # CONFIG_SLUB is not set
 CONFIG_SLOB=y
 CONFIG_PROFILING=y
 CONFIG_TRACEPOINTS=y
-# CONFIG_MARKERS is not set
+CONFIG_MARKERS=y
 CONFIG_OPROFILE=y
 CONFIG_HAVE_OPROFILE=y
 CONFIG_KPROBES=y
@@ -207,6 +212,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=7
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x04000000
 CONFIG_29BIT=y
@@ -226,7 +232,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 CONFIG_PAGE_SIZE_64KB=y
-CONFIG_ENTRY_OFFSET=0x00010000
 # CONFIG_HUGETLB_PAGE_SIZE_64K is not set
 # CONFIG_HUGETLB_PAGE_SIZE_256K is not set
 CONFIG_HUGETLB_PAGE_SIZE_1MB=y
@@ -249,9 +254,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -279,9 +284,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=50000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 CONFIG_TICK_ONESHOT=y
 CONFIG_NO_HZ=y
 CONFIG_HIGH_RES_TIMERS=y
@@ -339,12 +345,14 @@
 # CONFIG_PREEMPT_NONE is not set
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
-CONFIG_ZERO_PAGE_OFFSET=0x00001000
+CONFIG_ZERO_PAGE_OFFSET=0x00010000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00010000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200 earlyprintk=bios ignore_loglevel"
 
@@ -444,6 +452,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -462,6 +471,7 @@
 # CAN Device Drivers
 #
 CONFIG_CAN_VCAN=m
+# CONFIG_CAN_DEV is not set
 # CONFIG_CAN_DEBUG_DEVICES is not set
 # CONFIG_IRDA is not set
 # CONFIG_BT is not set
@@ -512,6 +522,7 @@
 # CONFIG_EEPROM_AT24 is not set
 # CONFIG_EEPROM_AT25 is not set
 # CONFIG_EEPROM_LEGACY is not set
+# CONFIG_EEPROM_MAX6875 is not set
 # CONFIG_EEPROM_93CX6 is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
@@ -535,10 +546,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -555,6 +562,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_LIBFC is not set
 # CONFIG_LIBFCOE is not set
 # CONFIG_SCSI_DEBUG is not set
@@ -568,7 +576,6 @@
 CONFIG_PATA_PLATFORM=y
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -594,6 +601,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -701,7 +709,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -758,22 +765,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -885,6 +877,7 @@
 # CONFIG_USB_GADGET_OMAP is not set
 # CONFIG_USB_GADGET_PXA25X is not set
 # CONFIG_USB_GADGET_PXA27X is not set
+# CONFIG_USB_GADGET_S3C_HSOTG is not set
 # CONFIG_USB_GADGET_S3C2410 is not set
 # CONFIG_USB_GADGET_IMX is not set
 CONFIG_USB_GADGET_M66592=y
@@ -894,9 +887,11 @@
 # CONFIG_USB_GADGET_CI13XXX is not set
 # CONFIG_USB_GADGET_NET2280 is not set
 # CONFIG_USB_GADGET_GOKU is not set
+# CONFIG_USB_GADGET_LANGWELL is not set
 # CONFIG_USB_GADGET_DUMMY_HCD is not set
 CONFIG_USB_GADGET_DUALSPEED=y
 # CONFIG_USB_ZERO is not set
+# CONFIG_USB_AUDIO is not set
 # CONFIG_USB_ETH is not set
 # CONFIG_USB_GADGETFS is not set
 # CONFIG_USB_FILE_STORAGE is not set
@@ -974,6 +969,7 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=y
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 CONFIG_UIO=m
@@ -981,6 +977,10 @@
 # CONFIG_UIO_PDRV_GENIRQ is not set
 # CONFIG_UIO_SMX is not set
 # CONFIG_UIO_SERCOS3 is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1001,10 +1001,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1077,7 +1078,46 @@
 #
 # CONFIG_PARTITION_ADVANCED is not set
 CONFIG_MSDOS_PARTITION=y
-# CONFIG_NLS is not set
+CONFIG_NLS=y
+CONFIG_NLS_DEFAULT="iso8859-1"
+# CONFIG_NLS_CODEPAGE_437 is not set
+# CONFIG_NLS_CODEPAGE_737 is not set
+# CONFIG_NLS_CODEPAGE_775 is not set
+# CONFIG_NLS_CODEPAGE_850 is not set
+# CONFIG_NLS_CODEPAGE_852 is not set
+# CONFIG_NLS_CODEPAGE_855 is not set
+# CONFIG_NLS_CODEPAGE_857 is not set
+# CONFIG_NLS_CODEPAGE_860 is not set
+# CONFIG_NLS_CODEPAGE_861 is not set
+# CONFIG_NLS_CODEPAGE_862 is not set
+# CONFIG_NLS_CODEPAGE_863 is not set
+# CONFIG_NLS_CODEPAGE_864 is not set
+# CONFIG_NLS_CODEPAGE_865 is not set
+# CONFIG_NLS_CODEPAGE_866 is not set
+# CONFIG_NLS_CODEPAGE_869 is not set
+# CONFIG_NLS_CODEPAGE_936 is not set
+# CONFIG_NLS_CODEPAGE_950 is not set
+# CONFIG_NLS_CODEPAGE_932 is not set
+# CONFIG_NLS_CODEPAGE_949 is not set
+# CONFIG_NLS_CODEPAGE_874 is not set
+# CONFIG_NLS_ISO8859_8 is not set
+# CONFIG_NLS_CODEPAGE_1250 is not set
+# CONFIG_NLS_CODEPAGE_1251 is not set
+# CONFIG_NLS_ASCII is not set
+# CONFIG_NLS_ISO8859_1 is not set
+# CONFIG_NLS_ISO8859_2 is not set
+# CONFIG_NLS_ISO8859_3 is not set
+# CONFIG_NLS_ISO8859_4 is not set
+# CONFIG_NLS_ISO8859_5 is not set
+# CONFIG_NLS_ISO8859_6 is not set
+# CONFIG_NLS_ISO8859_7 is not set
+# CONFIG_NLS_ISO8859_9 is not set
+# CONFIG_NLS_ISO8859_13 is not set
+# CONFIG_NLS_ISO8859_14 is not set
+# CONFIG_NLS_ISO8859_15 is not set
+# CONFIG_NLS_KOI8_R is not set
+# CONFIG_NLS_KOI8_U is not set
+# CONFIG_NLS_UTF8 is not set
 # CONFIG_DLM is not set
 
 #
@@ -1138,25 +1178,25 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_RING_BUFFER=y
+CONFIG_EVENT_TRACING=y
+CONFIG_CONTEXT_SWITCH_TRACER=y
 CONFIG_TRACING=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_PREEMPT_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
 # CONFIG_BLK_DEV_IO_TRACE is not set
-# CONFIG_FTRACE_STARTUP_TEST is not set
+# CONFIG_RING_BUFFER_BENCHMARK is not set
 # CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
@@ -1168,10 +1208,8 @@
 # CONFIG_DEBUG_BOOTMEM is not set
 CONFIG_DEBUG_STACKOVERFLOW=y
 CONFIG_DEBUG_STACK_USAGE=y
-# CONFIG_IRQSTACKS is not set
 CONFIG_DUMP_CODE=y
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1285,3 +1323,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/snapgear_defconfig b/arch/sh/configs/snapgear_defconfig
index 54a7a3c..ca3c88a 100644
--- a/arch/sh/configs/snapgear_defconfig
+++ b/arch/sh/configs/snapgear_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:14:00 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:11:58 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -73,7 +74,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_HOTPLUG is not set
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -86,8 +86,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -171,6 +176,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x01000000
 CONFIG_29BIT=y
@@ -185,7 +191,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -198,9 +203,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -219,7 +224,6 @@
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_IPR_IRQ=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -235,9 +239,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=60000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -283,12 +288,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 # CONFIG_CMDLINE_BOOL is not set
 
@@ -366,6 +373,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -383,7 +391,11 @@
 # CONFIG_WIRELESS_OLD_REGULATORY is not set
 # CONFIG_WIRELESS_EXT is not set
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -528,7 +540,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -581,6 +592,7 @@
 # CONFIG_SMSC9420 is not set
 # CONFIG_SUNDANCE is not set
 # CONFIG_TLAN is not set
+# CONFIG_KS8842 is not set
 # CONFIG_VIA_RHINE is not set
 # CONFIG_SC92031 is not set
 # CONFIG_ATL2 is not set
@@ -695,22 +707,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -734,10 +731,15 @@
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
 # CONFIG_INFINIBAND is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -751,12 +753,14 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 # CONFIG_DNOTIFY is not set
 # CONFIG_INOTIFY is not set
+CONFIG_INOTIFY_USER=y
 # CONFIG_QUOTA is not set
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
@@ -855,27 +859,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -905,3 +894,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/systemh_defconfig b/arch/sh/configs/systemh_defconfig
index dbe7e54..5d97026 100644
--- a/arch/sh/configs/systemh_defconfig
+++ b/arch/sh/configs/systemh_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:14:33 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:12:28 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -19,6 +19,7 @@
 CONFIG_GENERIC_CLOCKEVENTS=y
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -70,7 +71,6 @@
 # CONFIG_SYSCTL_SYSCALL is not set
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 # CONFIG_HOTPLUG is not set
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -83,7 +83,12 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -173,6 +178,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x0c000000
 CONFIG_MEMORY_SIZE=0x00400000
 CONFIG_29BIT=y
@@ -187,7 +193,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -200,9 +205,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -220,7 +225,6 @@
 # CONFIG_SH_STORE_QUEUES is not set
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -236,9 +240,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=60000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -280,12 +285,14 @@
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 # CONFIG_CMDLINE_BOOL is not set
 
@@ -428,21 +435,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -481,10 +474,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -496,9 +494,10 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -590,28 +589,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_PREEMPT_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -640,3 +623,4 @@
 CONFIG_HAS_IOMEM=y
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/titan_defconfig b/arch/sh/configs/titan_defconfig
index 8ca94ef..7ad080e 100644
--- a/arch/sh/configs/titan_defconfig
+++ b/arch/sh/configs/titan_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:14:55 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:12:54 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,7 @@
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -77,7 +78,6 @@
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_ALL is not set
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -90,8 +90,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
@@ -181,6 +186,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08030000
 CONFIG_MEMORY_SIZE=0x7fd0000
 CONFIG_29BIT=y
@@ -195,7 +201,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_SELECT_MEMORY_MODEL=y
 CONFIG_FLATMEM_MANUAL=y
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -208,9 +213,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -229,7 +234,6 @@
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_IPR_IRQ=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_FPU=y
 
 #
@@ -245,9 +249,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=30000000
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 # CONFIG_NO_HZ is not set
 # CONFIG_HIGH_RES_TIMERS is not set
 CONFIG_GENERIC_CLOCKEVENTS_BUILD=y
@@ -293,12 +298,14 @@
 # CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
 # CONFIG_GUSA_RB is not set
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x009e0000
+CONFIG_ENTRY_OFFSET=0x00001000
 # CONFIG_UBC_WAKEUP is not set
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC1,38400N81 root=/dev/nfs ip=:::::eth1:autoconf rw"
@@ -417,6 +424,7 @@
 CONFIG_NETFILTER_NETLINK_QUEUE=m
 CONFIG_NETFILTER_NETLINK_LOG=m
 # CONFIG_NF_CONNTRACK is not set
+# CONFIG_NETFILTER_TPROXY is not set
 CONFIG_NETFILTER_XTABLES=m
 CONFIG_NETFILTER_XT_TARGET_CLASSIFY=m
 # CONFIG_NETFILTER_XT_TARGET_DSCP is not set
@@ -454,6 +462,7 @@
 CONFIG_NETFILTER_XT_MATCH_TCPMSS=m
 # CONFIG_NETFILTER_XT_MATCH_TIME is not set
 # CONFIG_NETFILTER_XT_MATCH_U32 is not set
+# CONFIG_NETFILTER_XT_MATCH_OSF is not set
 # CONFIG_IP_VS is not set
 
 #
@@ -517,6 +526,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 CONFIG_NET_SCHED=y
 
 #
@@ -589,7 +599,11 @@
 CONFIG_WIRELESS_EXT=y
 CONFIG_WIRELESS_EXT_SYSFS=y
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -731,6 +745,7 @@
 # EEPROM support
 #
 # CONFIG_EEPROM_93CX6 is not set
+# CONFIG_CB710_CORE is not set
 CONFIG_HAVE_IDE=y
 # CONFIG_IDE is not set
 
@@ -754,10 +769,6 @@
 # CONFIG_BLK_DEV_SR_VENDOR is not set
 CONFIG_CHR_DEV_SG=m
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -775,6 +786,7 @@
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
 # CONFIG_SCSI_CXGB3_ISCSI is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_BLK_DEV_3W_XXXX_RAID is not set
 # CONFIG_SCSI_3W_9XXX is not set
 # CONFIG_SCSI_ACARD is not set
@@ -783,6 +795,7 @@
 # CONFIG_SCSI_AIC7XXX_OLD is not set
 # CONFIG_SCSI_AIC79XX is not set
 # CONFIG_SCSI_AIC94XX is not set
+# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_ARCMSR is not set
 # CONFIG_MEGARAID_NEWGEN is not set
 # CONFIG_MEGARAID_LEGACY is not set
@@ -797,7 +810,6 @@
 # CONFIG_SCSI_IPS is not set
 # CONFIG_SCSI_INITIO is not set
 # CONFIG_SCSI_INIA100 is not set
-# CONFIG_SCSI_MVSAS is not set
 # CONFIG_SCSI_STEX is not set
 # CONFIG_SCSI_SYM53C8XX_2 is not set
 # CONFIG_SCSI_QLOGIC_1280 is not set
@@ -826,7 +838,6 @@
 # CONFIG_IEEE1394 is not set
 # CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_IFB is not set
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
@@ -898,6 +909,7 @@
 # CONFIG_SMSC9420 is not set
 # CONFIG_SUNDANCE is not set
 # CONFIG_TLAN is not set
+# CONFIG_KS8842 is not set
 # CONFIG_VIA_RHINE is not set
 # CONFIG_SC92031 is not set
 # CONFIG_ATL2 is not set
@@ -965,6 +977,7 @@
 CONFIG_USB_USBNET=m
 CONFIG_USB_NET_AX8817X=m
 CONFIG_USB_NET_CDCETHER=m
+# CONFIG_USB_NET_CDC_EEM is not set
 # CONFIG_USB_NET_DM9601 is not set
 # CONFIG_USB_NET_SMSC95XX is not set
 # CONFIG_USB_NET_GL620A is not set
@@ -974,6 +987,7 @@
 # CONFIG_USB_NET_RNDIS_HOST is not set
 # CONFIG_USB_NET_CDC_SUBSET is not set
 CONFIG_USB_NET_ZAURUS=m
+# CONFIG_USB_NET_INT51X1 is not set
 # CONFIG_WAN is not set
 # CONFIG_FDDI is not set
 # CONFIG_HIPPI is not set
@@ -1130,22 +1144,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -1211,6 +1210,7 @@
 # USB Host Controller Drivers
 #
 # CONFIG_USB_C67X00_HCD is not set
+# CONFIG_USB_XHCI_HCD is not set
 CONFIG_USB_EHCI_HCD=y
 CONFIG_USB_EHCI_ROOT_HUB_TT=y
 CONFIG_USB_EHCI_TT_NEWSCHED=y
@@ -1350,7 +1350,7 @@
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
 # CONFIG_INFINIBAND is not set
-CONFIG_RTC_LIB=m
+CONFIG_RTC_LIB=y
 CONFIG_RTC_CLASS=m
 
 #
@@ -1384,9 +1384,14 @@
 # on-CPU RTC drivers
 #
 CONFIG_RTC_DRV_SH=m
+# CONFIG_RTC_DRV_GENERIC is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1406,7 +1411,6 @@
 # CONFIG_REISERFS_FS_XATTR is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 CONFIG_XFS_FS=m
 # CONFIG_XFS_QUOTA is not set
 # CONFIG_XFS_POSIX_ACL is not set
@@ -1414,6 +1418,8 @@
 # CONFIG_XFS_DEBUG is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1421,6 +1427,7 @@
 # CONFIG_AUTOFS_FS is not set
 # CONFIG_AUTOFS4_FS is not set
 CONFIG_FUSE_FS=m
+# CONFIG_CUSE is not set
 
 #
 # Caches
@@ -1533,7 +1540,7 @@
 # CONFIG_KARMA_PARTITION is not set
 # CONFIG_EFI_PARTITION is not set
 # CONFIG_SYSV68_PARTITION is not set
-CONFIG_NLS=m
+CONFIG_NLS=y
 CONFIG_NLS_DEFAULT="iso8859-1"
 CONFIG_NLS_CODEPAGE_437=m
 # CONFIG_NLS_CODEPAGE_737 is not set
@@ -1626,17 +1633,15 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
+CONFIG_FTRACE=y
 # CONFIG_FUNCTION_TRACER is not set
 # CONFIG_IRQSOFF_TRACER is not set
 # CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
+# CONFIG_ENABLE_DEFAULT_TRACERS is not set
 # CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
+CONFIG_BRANCH_PROFILE_NONE=y
+# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set
+# CONFIG_PROFILE_ALL_BRANCHES is not set
 # CONFIG_STACK_TRACER is not set
 # CONFIG_KMEMTRACE is not set
 # CONFIG_WORKQUEUE_TRACER is not set
@@ -1645,16 +1650,15 @@
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_KGDB is not set
+# CONFIG_KMEMCHECK is not set
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
 # CONFIG_DEBUG_BOOTMEM is not set
 # CONFIG_DEBUG_STACKOVERFLOW is not set
 # CONFIG_DEBUG_STACK_USAGE is not set
 # CONFIG_4KSTACKS is not set
-# CONFIG_IRQSTACKS is not set
 # CONFIG_DUMP_CODE is not set
 # CONFIG_SH_NO_BSS_INIT is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1787,3 +1791,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/ul2_defconfig b/arch/sh/configs/ul2_defconfig
index bfb4d98..608fe56 100644
--- a/arch/sh/configs/ul2_defconfig
+++ b/arch/sh/configs/ul2_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 13:17:05 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:14:36 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -21,6 +21,7 @@
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_NUMA=y
 CONFIG_SYS_SUPPORTS_CMT=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -78,7 +79,6 @@
 CONFIG_SYSCTL_SYSCALL=y
 CONFIG_KALLSYMS=y
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -91,8 +91,13 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
 CONFIG_SLUB_DEBUG=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 # CONFIG_SLAB is not set
 CONFIG_SLUB=y
@@ -187,6 +192,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x01f00000
 CONFIG_29BIT=y
@@ -205,7 +211,6 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_HUGETLB_PAGE_SIZE_64K=y
 # CONFIG_HUGETLB_PAGE_SIZE_256K is not set
 # CONFIG_HUGETLB_PAGE_SIZE_1MB is not set
@@ -226,9 +231,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -247,7 +252,6 @@
 # CONFIG_SH_STORE_QUEUES is not set
 CONFIG_CPU_HAS_INTEVT=y
 CONFIG_CPU_HAS_SR_RB=y
-CONFIG_CPU_HAS_PTEA=y
 CONFIG_CPU_HAS_DSP=y
 
 #
@@ -257,10 +261,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
+CONFIG_SH_TIMER_TMU=y
 # CONFIG_SH_TIMER_CMT is not set
-CONFIG_SH_TIMER_IRQ=16
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
 CONFIG_TICK_ONESHOT=y
 # CONFIG_NO_HZ is not set
 CONFIG_HIGH_RES_TIMERS=y
@@ -302,12 +306,14 @@
 # CONFIG_PREEMPT_VOLUNTARY is not set
 CONFIG_PREEMPT=y
 CONFIG_GUSA=y
+# CONFIG_SPARSE_IRQ is not set
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
+CONFIG_ENTRY_OFFSET=0x00001000
 CONFIG_CMDLINE_BOOL=y
 CONFIG_CMDLINE="console=ttySC0,115200 root=/dev/nfs ip=dhcp"
 
@@ -390,6 +396,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -411,6 +418,8 @@
 CONFIG_LIB80211=m
 # CONFIG_LIB80211_DEBUG is not set
 CONFIG_MAC80211=y
+CONFIG_MAC80211_DEFAULT_PS=y
+CONFIG_MAC80211_DEFAULT_PS_VALUE=1
 
 #
 # Rate control algorithm selection
@@ -565,10 +574,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -585,6 +590,7 @@
 # CONFIG_SCSI_SRP_ATTRS is not set
 CONFIG_SCSI_LOWLEVEL=y
 # CONFIG_ISCSI_TCP is not set
+# CONFIG_SCSI_BNX2_ISCSI is not set
 # CONFIG_LIBFC is not set
 # CONFIG_LIBFCOE is not set
 # CONFIG_SCSI_DEBUG is not set
@@ -598,7 +604,6 @@
 CONFIG_PATA_PLATFORM=y
 # CONFIG_MD is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
@@ -623,6 +628,7 @@
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
 # CONFIG_B44 is not set
+# CONFIG_KS8842 is not set
 # CONFIG_NETDEV_1000 is not set
 # CONFIG_NETDEV_10000 is not set
 
@@ -648,6 +654,7 @@
 # CONFIG_B43LEGACY is not set
 # CONFIG_ZD1211RW is not set
 # CONFIG_RT2X00 is not set
+# CONFIG_IWM is not set
 
 #
 # Enable WiMAX (Networking options) to see the WiMAX drivers
@@ -663,6 +670,7 @@
 CONFIG_USB_USBNET=y
 CONFIG_USB_NET_AX8817X=y
 CONFIG_USB_NET_CDCETHER=y
+# CONFIG_USB_NET_CDC_EEM is not set
 # CONFIG_USB_NET_DM9601 is not set
 # CONFIG_USB_NET_SMSC95XX is not set
 # CONFIG_USB_NET_GL620A is not set
@@ -672,6 +680,7 @@
 # CONFIG_USB_NET_RNDIS_HOST is not set
 # CONFIG_USB_NET_CDC_SUBSET is not set
 # CONFIG_USB_NET_ZAURUS is not set
+# CONFIG_USB_NET_INT51X1 is not set
 # CONFIG_WAN is not set
 # CONFIG_PPP is not set
 # CONFIG_SLIP is not set
@@ -774,22 +783,7 @@
 # CONFIG_HTC_PASIC3 is not set
 # CONFIG_MFD_TMIO is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
-
-#
-# Multimedia core support
-#
-# CONFIG_VIDEO_DEV is not set
-# CONFIG_DVB_CORE is not set
-# CONFIG_VIDEO_MEDIA is not set
-
-#
-# Multimedia drivers
-#
-# CONFIG_DAB is not set
+# CONFIG_MEDIA_SUPPORT is not set
 
 #
 # Graphics support
@@ -926,10 +920,15 @@
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
+CONFIG_RTC_LIB=y
 # CONFIG_RTC_CLASS is not set
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -949,10 +948,11 @@
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
 # CONFIG_FS_POSIX_ACL is not set
-CONFIG_FILE_LOCKING=y
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
 # CONFIG_BTRFS_FS is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1106,28 +1106,12 @@
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_PREEMPT_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
 # CONFIG_SH_STANDARD_BIOS is not set
 # CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
 
 #
 # Security options
@@ -1252,3 +1236,4 @@
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/configs/urquell_defconfig b/arch/sh/configs/urquell_defconfig
index 512664f..ee1987e 100644
--- a/arch/sh/configs/urquell_defconfig
+++ b/arch/sh/configs/urquell_defconfig
@@ -1,7 +1,7 @@
 #
 # Automatically generated make config: don't edit
-# Linux kernel version: 2.6.30-rc3
-# Mon Apr 27 14:02:55 2009
+# Linux kernel version: 2.6.30
+# Thu Jun 18 13:15:28 2009
 #
 CONFIG_SUPERH=y
 CONFIG_SUPERH32=y
@@ -20,6 +20,8 @@
 # CONFIG_ARCH_SUSPEND_POSSIBLE is not set
 CONFIG_ARCH_HIBERNATION_POSSIBLE=y
 CONFIG_SYS_SUPPORTS_NUMA=y
+CONFIG_SYS_SUPPORTS_PCI=y
+CONFIG_SYS_SUPPORTS_TMU=y
 CONFIG_STACKTRACE_SUPPORT=y
 CONFIG_LOCKDEP_SUPPORT=y
 CONFIG_HAVE_LATENCYTOP_SUPPORT=y
@@ -34,25 +36,30 @@
 #
 CONFIG_EXPERIMENTAL=y
 CONFIG_BROKEN_ON_SMP=y
-CONFIG_LOCK_KERNEL=y
 CONFIG_INIT_ENV_ARG_LIMIT=32
 CONFIG_LOCALVERSION=""
 CONFIG_LOCALVERSION_AUTO=y
 CONFIG_SWAP=y
 CONFIG_SYSVIPC=y
 CONFIG_SYSVIPC_SYSCTL=y
-# CONFIG_POSIX_MQUEUE is not set
+CONFIG_POSIX_MQUEUE=y
+CONFIG_POSIX_MQUEUE_SYSCTL=y
 CONFIG_BSD_PROCESS_ACCT=y
 # CONFIG_BSD_PROCESS_ACCT_V3 is not set
 # CONFIG_TASKSTATS is not set
-# CONFIG_AUDIT is not set
+CONFIG_AUDIT=y
+CONFIG_AUDITSYSCALL=y
+CONFIG_AUDIT_TREE=y
 
 #
 # RCU Subsystem
 #
-CONFIG_CLASSIC_RCU=y
-# CONFIG_TREE_RCU is not set
+# CONFIG_CLASSIC_RCU is not set
+CONFIG_TREE_RCU=y
 # CONFIG_PREEMPT_RCU is not set
+# CONFIG_RCU_TRACE is not set
+CONFIG_RCU_FANOUT=32
+# CONFIG_RCU_FANOUT_EXACT is not set
 # CONFIG_TREE_RCU_TRACE is not set
 # CONFIG_PREEMPT_RCU_TRACE is not set
 CONFIG_IKCONFIG=y
@@ -60,15 +67,29 @@
 CONFIG_LOG_BUF_SHIFT=14
 CONFIG_GROUP_SCHED=y
 CONFIG_FAIR_GROUP_SCHED=y
-# CONFIG_RT_GROUP_SCHED is not set
-CONFIG_USER_SCHED=y
-# CONFIG_CGROUP_SCHED is not set
-# CONFIG_CGROUPS is not set
-CONFIG_SYSFS_DEPRECATED=y
-CONFIG_SYSFS_DEPRECATED_V2=y
+CONFIG_RT_GROUP_SCHED=y
+# CONFIG_USER_SCHED is not set
+CONFIG_CGROUP_SCHED=y
+CONFIG_CGROUPS=y
+CONFIG_CGROUP_DEBUG=y
+CONFIG_CGROUP_NS=y
+CONFIG_CGROUP_FREEZER=y
+CONFIG_CGROUP_DEVICE=y
+CONFIG_CPUSETS=y
+# CONFIG_PROC_PID_CPUSET is not set
+CONFIG_CGROUP_CPUACCT=y
+CONFIG_RESOURCE_COUNTERS=y
+CONFIG_CGROUP_MEM_RES_CTLR=y
+CONFIG_CGROUP_MEM_RES_CTLR_SWAP=y
+CONFIG_MM_OWNER=y
+# CONFIG_SYSFS_DEPRECATED_V2 is not set
 # CONFIG_RELAY is not set
 # CONFIG_NAMESPACES is not set
-# CONFIG_BLK_DEV_INITRD is not set
+CONFIG_BLK_DEV_INITRD=y
+CONFIG_INITRAMFS_SOURCE=""
+CONFIG_RD_GZIP=y
+# CONFIG_RD_BZIP2 is not set
+# CONFIG_RD_LZMA is not set
 CONFIG_CC_OPTIMIZE_FOR_SIZE=y
 CONFIG_SYSCTL=y
 CONFIG_ANON_INODES=y
@@ -76,8 +97,8 @@
 CONFIG_UID16=y
 CONFIG_SYSCTL_SYSCALL=y
 CONFIG_KALLSYMS=y
+# CONFIG_KALLSYMS_ALL is not set
 # CONFIG_KALLSYMS_EXTRA_PASS is not set
-# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_HOTPLUG=y
 CONFIG_PRINTK=y
 CONFIG_BUG=y
@@ -90,13 +111,20 @@
 CONFIG_EVENTFD=y
 CONFIG_SHMEM=y
 CONFIG_AIO=y
+
+#
+# Performance Counters
+#
 CONFIG_VM_EVENT_COUNTERS=y
+CONFIG_PCI_QUIRKS=y
+# CONFIG_STRIP_ASM_SYMS is not set
 CONFIG_COMPAT_BRK=y
 CONFIG_SLAB=y
 # CONFIG_SLUB is not set
 # CONFIG_SLOB is not set
 CONFIG_PROFILING=y
-# CONFIG_MARKERS is not set
+CONFIG_TRACEPOINTS=y
+CONFIG_MARKERS=y
 # CONFIG_OPROFILE is not set
 CONFIG_HAVE_OPROFILE=y
 # CONFIG_KPROBES is not set
@@ -129,12 +157,12 @@
 CONFIG_IOSCHED_AS=y
 CONFIG_IOSCHED_DEADLINE=y
 CONFIG_IOSCHED_CFQ=y
-# CONFIG_DEFAULT_AS is not set
+CONFIG_DEFAULT_AS=y
 # CONFIG_DEFAULT_DEADLINE is not set
-CONFIG_DEFAULT_CFQ=y
+# CONFIG_DEFAULT_CFQ is not set
 # CONFIG_DEFAULT_NOOP is not set
-CONFIG_DEFAULT_IOSCHED="cfq"
-# CONFIG_FREEZER is not set
+CONFIG_DEFAULT_IOSCHED="anticipatory"
+CONFIG_FREEZER=y
 
 #
 # System type
@@ -183,6 +211,7 @@
 CONFIG_QUICKLIST=y
 CONFIG_MMU=y
 CONFIG_PAGE_OFFSET=0x80000000
+CONFIG_FORCE_MAX_ZONEORDER=11
 CONFIG_MEMORY_START=0x08000000
 CONFIG_MEMORY_SIZE=0x08000000
 CONFIG_29BIT=y
@@ -201,7 +230,12 @@
 # CONFIG_PAGE_SIZE_8KB is not set
 # CONFIG_PAGE_SIZE_16KB is not set
 # CONFIG_PAGE_SIZE_64KB is not set
-CONFIG_ENTRY_OFFSET=0x00001000
+CONFIG_HUGETLB_PAGE_SIZE_64K=y
+# CONFIG_HUGETLB_PAGE_SIZE_256K is not set
+# CONFIG_HUGETLB_PAGE_SIZE_1MB is not set
+# CONFIG_HUGETLB_PAGE_SIZE_4MB is not set
+# CONFIG_HUGETLB_PAGE_SIZE_64MB is not set
+# CONFIG_HUGETLB_PAGE_SIZE_512MB is not set
 CONFIG_SELECT_MEMORY_MODEL=y
 # CONFIG_FLATMEM_MANUAL is not set
 # CONFIG_DISCONTIGMEM_MANUAL is not set
@@ -216,9 +250,9 @@
 # CONFIG_PHYS_ADDR_T_64BIT is not set
 CONFIG_ZONE_DMA_FLAG=0
 CONFIG_NR_QUICK=2
-CONFIG_UNEVICTABLE_LRU=y
 CONFIG_HAVE_MLOCK=y
 CONFIG_HAVE_MLOCKED_PAGE_BIT=y
+CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
 
 #
 # Cache configuration
@@ -247,9 +281,10 @@
 #
 # Timer and clock configuration
 #
-CONFIG_SH_TMU=y
-CONFIG_SH_TIMER_IRQ=16
+CONFIG_SH_TIMER_TMU=y
 CONFIG_SH_PCLK_FREQ=33333333
+CONFIG_SH_CLK_CPG=y
+CONFIG_SH_CLK_CPG_LEGACY=y
 CONFIG_TICK_ONESHOT=y
 # CONFIG_NO_HZ is not set
 CONFIG_HIGH_RES_TIMERS=y
@@ -286,25 +321,37 @@
 CONFIG_SCHED_HRTICK=y
 CONFIG_KEXEC=y
 # CONFIG_CRASH_DUMP is not set
-# CONFIG_SECCOMP is not set
-# CONFIG_PREEMPT_NONE is not set
+CONFIG_SECCOMP=y
+CONFIG_PREEMPT_NONE=y
 # CONFIG_PREEMPT_VOLUNTARY is not set
-CONFIG_PREEMPT=y
+# CONFIG_PREEMPT is not set
 CONFIG_GUSA=y
+CONFIG_SPARSE_IRQ=y
 
 #
 # Boot options
 #
 CONFIG_ZERO_PAGE_OFFSET=0x00001000
 CONFIG_BOOT_LINK_OFFSET=0x00800000
-CONFIG_CMDLINE_BOOL=y
-CONFIG_CMDLINE="console=ttySC1, 38400 earlyprintk=serial ip=on ignore_loglevel root=/dev/nfs ip=dhcp memchunk.vpu=4m"
+CONFIG_ENTRY_OFFSET=0x00001000
+# CONFIG_CMDLINE_BOOL is not set
 
 #
 # Bus options
 #
+CONFIG_PCI=y
+# CONFIG_SH_PCIDMA_NONCOHERENT is not set
+CONFIG_PCIEPORTBUS=y
+CONFIG_PCIEAER=y
+CONFIG_PCIEASPM=y
+CONFIG_PCIEASPM_DEBUG=y
 # CONFIG_ARCH_SUPPORTS_MSI is not set
+# CONFIG_PCI_LEGACY is not set
+CONFIG_PCI_DEBUG=y
+# CONFIG_PCI_STUB is not set
+# CONFIG_PCI_IOV is not set
 # CONFIG_PCCARD is not set
+# CONFIG_HOTPLUG_PCI is not set
 
 #
 # Executable file formats
@@ -312,13 +359,16 @@
 CONFIG_BINFMT_ELF=y
 # CONFIG_CORE_DUMP_DEFAULT_ELF_HEADERS is not set
 # CONFIG_HAVE_AOUT is not set
-# CONFIG_BINFMT_MISC is not set
+CONFIG_BINFMT_MISC=y
 
 #
 # Power management options (EXPERIMENTAL)
 #
-# CONFIG_PM is not set
-# CONFIG_CPU_IDLE is not set
+CONFIG_PM=y
+# CONFIG_PM_DEBUG is not set
+# CONFIG_HIBERNATION is not set
+CONFIG_CPU_IDLE=y
+CONFIG_CPU_IDLE_GOV_LADDER=y
 CONFIG_NET=y
 
 #
@@ -384,6 +434,7 @@
 # CONFIG_ECONET is not set
 # CONFIG_WAN_ROUTER is not set
 # CONFIG_PHONET is not set
+# CONFIG_IEEE802154 is not set
 # CONFIG_NET_SCHED is not set
 # CONFIG_DCB is not set
 
@@ -391,6 +442,7 @@
 # Network testing
 #
 # CONFIG_NET_PKTGEN is not set
+# CONFIG_NET_DROP_MONITOR is not set
 # CONFIG_HAMRADIO is not set
 # CONFIG_CAN is not set
 # CONFIG_IRDA is not set
@@ -402,7 +454,11 @@
 CONFIG_WIRELESS_EXT=y
 CONFIG_WIRELESS_EXT_SYSFS=y
 # CONFIG_LIB80211 is not set
-# CONFIG_MAC80211 is not set
+
+#
+# CFG80211 needs to be enabled for MAC80211
+#
+CONFIG_MAC80211_DEFAULT_PS_VALUE=0
 # CONFIG_WIMAX is not set
 # CONFIG_RFKILL is not set
 # CONFIG_NET_9P is not set
@@ -418,6 +474,8 @@
 CONFIG_STANDALONE=y
 CONFIG_PREVENT_FIRMWARE_BUILD=y
 # CONFIG_FW_LOADER is not set
+# CONFIG_DEBUG_DRIVER is not set
+# CONFIG_DEBUG_DEVRES is not set
 # CONFIG_SYS_HYPERVISOR is not set
 # CONFIG_CONNECTOR is not set
 CONFIG_MTD=y
@@ -473,11 +531,13 @@
 # CONFIG_MTD_COMPLEX_MAPPINGS is not set
 CONFIG_MTD_PHYSMAP=y
 # CONFIG_MTD_PHYSMAP_COMPAT is not set
+# CONFIG_MTD_INTEL_VR_NOR is not set
 # CONFIG_MTD_PLATRAM is not set
 
 #
 # Self-contained MTD device drivers
 #
+# CONFIG_MTD_PMC551 is not set
 # CONFIG_MTD_SLRAM is not set
 # CONFIG_MTD_PHRAM is not set
 # CONFIG_MTD_MTDRAM is not set
@@ -503,9 +563,13 @@
 # CONFIG_MTD_UBI is not set
 # CONFIG_PARPORT is not set
 CONFIG_BLK_DEV=y
+# CONFIG_BLK_CPQ_CISS_DA is not set
+# CONFIG_BLK_DEV_DAC960 is not set
+# CONFIG_BLK_DEV_UMEM is not set
 # CONFIG_BLK_DEV_COW_COMMON is not set
 # CONFIG_BLK_DEV_LOOP is not set
 # CONFIG_BLK_DEV_NBD is not set
+# CONFIG_BLK_DEV_SX8 is not set
 # CONFIG_BLK_DEV_UB is not set
 CONFIG_BLK_DEV_RAM=y
 CONFIG_BLK_DEV_RAM_COUNT=16
@@ -537,10 +601,6 @@
 # CONFIG_BLK_DEV_SR is not set
 # CONFIG_CHR_DEV_SG is not set
 # CONFIG_CHR_DEV_SCH is not set
-
-#
-# Some SCSI devices (e.g. CD jukebox) support multiple LUNs
-#
 # CONFIG_SCSI_MULTI_LUN is not set
 # CONFIG_SCSI_CONSTANTS is not set
 # CONFIG_SCSI_LOGGING is not set
@@ -561,24 +621,90 @@
 CONFIG_ATA=y
 # CONFIG_ATA_NONSTANDARD is not set
 CONFIG_SATA_PMP=y
+# CONFIG_SATA_AHCI is not set
+CONFIG_SATA_SIL24=y
 CONFIG_ATA_SFF=y
+# CONFIG_SATA_SVW is not set
+# CONFIG_ATA_PIIX is not set
 # CONFIG_SATA_MV is not set
+# CONFIG_SATA_NV is not set
+# CONFIG_PDC_ADMA is not set
+# CONFIG_SATA_QSTOR is not set
+# CONFIG_SATA_PROMISE is not set
+# CONFIG_SATA_SX4 is not set
+# CONFIG_SATA_SIL is not set
+# CONFIG_SATA_SIS is not set
+# CONFIG_SATA_ULI is not set
+# CONFIG_SATA_VIA is not set
+# CONFIG_SATA_VITESSE is not set
+# CONFIG_SATA_INIC162X is not set
+# CONFIG_PATA_ALI is not set
+# CONFIG_PATA_AMD is not set
+# CONFIG_PATA_ARTOP is not set
+# CONFIG_PATA_ATIIXP is not set
+# CONFIG_PATA_CMD640_PCI is not set
+# CONFIG_PATA_CMD64X is not set
+# CONFIG_PATA_CS5520 is not set
+# CONFIG_PATA_CS5530 is not set
+# CONFIG_PATA_CYPRESS is not set
+# CONFIG_PATA_EFAR is not set
+# CONFIG_ATA_GENERIC is not set
+# CONFIG_PATA_HPT366 is not set
+# CONFIG_PATA_HPT37X is not set
+# CONFIG_PATA_HPT3X2N is not set
+# CONFIG_PATA_HPT3X3 is not set
+# CONFIG_PATA_IT821X is not set
+# CONFIG_PATA_IT8213 is not set
+# CONFIG_PATA_JMICRON is not set
+# CONFIG_PATA_TRIFLEX is not set
+# CONFIG_PATA_MARVELL is not set
+# CONFIG_PATA_MPIIX is not set
+# CONFIG_PATA_OLDPIIX is not set
+# CONFIG_PATA_NETCELL is not set
+# CONFIG_PATA_NINJA32 is not set
+# CONFIG_PATA_NS87410 is not set
+# CONFIG_PATA_NS87415 is not set
+# CONFIG_PATA_OPTI is not set
+# CONFIG_PATA_OPTIDMA is not set
+# CONFIG_PATA_PDC_OLD is not set
+# CONFIG_PATA_RADISYS is not set
+# CONFIG_PATA_RZ1000 is not set
+# CONFIG_PATA_SC1200 is not set
+# CONFIG_PATA_SERVERWORKS is not set
+# CONFIG_PATA_PDC2027X is not set
+# CONFIG_PATA_SIL680 is not set
+# CONFIG_PATA_SIS is not set
+# CONFIG_PATA_VIA is not set
+# CONFIG_PATA_WINBOND is not set
 # CONFIG_PATA_PLATFORM is not set
+# CONFIG_PATA_SCH is not set
 # CONFIG_MD is not set
+# CONFIG_FUSION is not set
+
+#
+# IEEE 1394 (FireWire) support
+#
+
+#
+# Enable only one of the two stacks, unless you know what you are doing
+#
+# CONFIG_FIREWIRE is not set
+# CONFIG_IEEE1394 is not set
+# CONFIG_I2O is not set
 CONFIG_NETDEVICES=y
-CONFIG_COMPAT_NET_DEV_OPS=y
 # CONFIG_DUMMY is not set
 # CONFIG_BONDING is not set
 # CONFIG_MACVLAN is not set
 # CONFIG_EQUALIZER is not set
 # CONFIG_TUN is not set
 # CONFIG_VETH is not set
+# CONFIG_ARCNET is not set
 CONFIG_PHYLIB=y
 
 #
 # MII PHY device drivers
 #
-# CONFIG_MARVELL_PHY is not set
+CONFIG_MARVELL_PHY=y
 # CONFIG_DAVICOM_PHY is not set
 # CONFIG_QSEMI_PHY is not set
 # CONFIG_LXT_PHY is not set
@@ -597,11 +723,17 @@
 CONFIG_MII=y
 # CONFIG_AX88796 is not set
 # CONFIG_STNIC is not set
+# CONFIG_HAPPYMEAL is not set
+# CONFIG_SUNGEM is not set
+# CONFIG_CASSINI is not set
+# CONFIG_NET_VENDOR_3COM is not set
 CONFIG_SMC91X=y
 # CONFIG_ETHOC is not set
 # CONFIG_SMC911X is not set
 # CONFIG_SMSC911X is not set
 # CONFIG_DNET is not set
+# CONFIG_NET_TULIP is not set
+# CONFIG_HP100 is not set
 # CONFIG_IBM_NEW_EMAC_ZMII is not set
 # CONFIG_IBM_NEW_EMAC_RGMII is not set
 # CONFIG_IBM_NEW_EMAC_TAH is not set
@@ -609,9 +741,54 @@
 # CONFIG_IBM_NEW_EMAC_NO_FLOW_CTRL is not set
 # CONFIG_IBM_NEW_EMAC_MAL_CLR_ICINTSTAT is not set
 # CONFIG_IBM_NEW_EMAC_MAL_COMMON_ERR is not set
+CONFIG_NET_PCI=y
+# CONFIG_PCNET32 is not set
+# CONFIG_AMD8111_ETH is not set
+# CONFIG_ADAPTEC_STARFIRE is not set
 # CONFIG_B44 is not set
-# CONFIG_NETDEV_1000 is not set
+# CONFIG_FORCEDETH is not set
+# CONFIG_E100 is not set
+# CONFIG_FEALNX is not set
+# CONFIG_NATSEMI is not set
+# CONFIG_NE2K_PCI is not set
+CONFIG_8139CP=y
+# CONFIG_8139TOO is not set
+# CONFIG_R6040 is not set
+# CONFIG_SIS900 is not set
+# CONFIG_EPIC100 is not set
+# CONFIG_SMSC9420 is not set
+# CONFIG_SUNDANCE is not set
+# CONFIG_TLAN is not set
+# CONFIG_KS8842 is not set
+# CONFIG_VIA_RHINE is not set
+# CONFIG_SC92031 is not set
+# CONFIG_ATL2 is not set
+CONFIG_NETDEV_1000=y
+# CONFIG_ACENIC is not set
+# CONFIG_DL2K is not set
+# CONFIG_E1000 is not set
+# CONFIG_E1000E is not set
+# CONFIG_IP1000 is not set
+# CONFIG_IGB is not set
+# CONFIG_IGBVF is not set
+# CONFIG_NS83820 is not set
+# CONFIG_HAMACHI is not set
+# CONFIG_YELLOWFIN is not set
+# CONFIG_R8169 is not set
+# CONFIG_SIS190 is not set
+# CONFIG_SKGE is not set
+CONFIG_SKY2=y
+CONFIG_SKY2_DEBUG=y
+# CONFIG_VIA_VELOCITY is not set
+# CONFIG_TIGON3 is not set
+# CONFIG_BNX2 is not set
+# CONFIG_QLA3XXX is not set
+# CONFIG_ATL1 is not set
+# CONFIG_ATL1E is not set
+# CONFIG_ATL1C is not set
+# CONFIG_JME is not set
 # CONFIG_NETDEV_10000 is not set
+# CONFIG_TR is not set
 
 #
 # Wireless LAN
@@ -632,8 +809,11 @@
 # CONFIG_USB_RTL8150 is not set
 # CONFIG_USB_USBNET is not set
 # CONFIG_WAN is not set
+# CONFIG_FDDI is not set
+# CONFIG_HIPPI is not set
 # CONFIG_PPP is not set
 # CONFIG_SLIP is not set
+# CONFIG_NET_FC is not set
 # CONFIG_NETCONSOLE is not set
 # CONFIG_NETPOLL is not set
 # CONFIG_NET_POLL_CONTROLLER is not set
@@ -692,6 +872,7 @@
 CONFIG_VT_HW_CONSOLE_BINDING=y
 CONFIG_DEVKMEM=y
 # CONFIG_SERIAL_NONSTANDARD is not set
+# CONFIG_NOZOMI is not set
 
 #
 # Serial drivers
@@ -706,6 +887,7 @@
 CONFIG_SERIAL_SH_SCI_CONSOLE=y
 CONFIG_SERIAL_CORE=y
 CONFIG_SERIAL_CORE_CONSOLE=y
+# CONFIG_SERIAL_JSM is not set
 CONFIG_UNIX98_PTYS=y
 # CONFIG_DEVPTS_MULTIPLE_INSTANCES is not set
 CONFIG_LEGACY_PTYS=y
@@ -714,8 +896,10 @@
 CONFIG_HW_RANDOM=y
 # CONFIG_HW_RANDOM_TIMERIOMEM is not set
 # CONFIG_R3964 is not set
+# CONFIG_APPLICOM is not set
 # CONFIG_RAW_DRIVER is not set
 # CONFIG_TCG_TPM is not set
+CONFIG_DEVPORT=y
 CONFIG_I2C=y
 CONFIG_I2C_BOARDINFO=y
 # CONFIG_I2C_CHARDEV is not set
@@ -727,6 +911,24 @@
 #
 
 #
+# PC SMBus host controller drivers
+#
+# CONFIG_I2C_ALI1535 is not set
+# CONFIG_I2C_ALI1563 is not set
+# CONFIG_I2C_ALI15X3 is not set
+# CONFIG_I2C_AMD756 is not set
+# CONFIG_I2C_AMD8111 is not set
+# CONFIG_I2C_I801 is not set
+# CONFIG_I2C_ISCH is not set
+# CONFIG_I2C_PIIX4 is not set
+# CONFIG_I2C_NFORCE2 is not set
+# CONFIG_I2C_SIS5595 is not set
+# CONFIG_I2C_SIS630 is not set
+# CONFIG_I2C_SIS96X is not set
+# CONFIG_I2C_VIA is not set
+# CONFIG_I2C_VIAPRO is not set
+
+#
 # I2C system bus drivers (mostly embedded / system-on-chip)
 #
 # CONFIG_I2C_GPIO is not set
@@ -742,6 +944,11 @@
 # CONFIG_I2C_TINY_USB is not set
 
 #
+# Graphics adapter I2C/DDC channel drivers
+#
+# CONFIG_I2C_VOODOO3 is not set
+
+#
 # Other I2C/SMBus bus drivers
 #
 CONFIG_I2C_PCA_PLATFORM=y
@@ -754,7 +961,6 @@
 # CONFIG_SENSORS_PCF8574 is not set
 # CONFIG_PCF8575 is not set
 # CONFIG_SENSORS_PCA9539 is not set
-# CONFIG_SENSORS_MAX6875 is not set
 # CONFIG_SENSORS_TSL2550 is not set
 # CONFIG_I2C_DEBUG_CORE is not set
 # CONFIG_I2C_DEBUG_ALGO is not set
@@ -763,6 +969,7 @@
 # CONFIG_SPI is not set
 CONFIG_ARCH_REQUIRE_GPIOLIB=y
 CONFIG_GPIOLIB=y
+# CONFIG_DEBUG_GPIO is not set
 # CONFIG_GPIO_SYSFS is not set
 
 #
@@ -779,15 +986,79 @@
 #
 # PCI GPIO expanders:
 #
+# CONFIG_GPIO_BT8XX is not set
 
 #
 # SPI GPIO expanders:
 #
 # CONFIG_W1 is not set
 # CONFIG_POWER_SUPPLY is not set
-# CONFIG_HWMON is not set
+CONFIG_HWMON=y
+# CONFIG_HWMON_VID is not set
+# CONFIG_SENSORS_AD7414 is not set
+# CONFIG_SENSORS_AD7418 is not set
+# CONFIG_SENSORS_ADM1021 is not set
+# CONFIG_SENSORS_ADM1025 is not set
+# CONFIG_SENSORS_ADM1026 is not set
+# CONFIG_SENSORS_ADM1029 is not set
+# CONFIG_SENSORS_ADM1031 is not set
+# CONFIG_SENSORS_ADM9240 is not set
+# CONFIG_SENSORS_ADT7462 is not set
+# CONFIG_SENSORS_ADT7470 is not set
+# CONFIG_SENSORS_ADT7473 is not set
+# CONFIG_SENSORS_ADT7475 is not set
+# CONFIG_SENSORS_ATXP1 is not set
+# CONFIG_SENSORS_DS1621 is not set
+# CONFIG_SENSORS_I5K_AMB is not set
+# CONFIG_SENSORS_F71805F is not set
+# CONFIG_SENSORS_F71882FG is not set
+# CONFIG_SENSORS_F75375S is not set
+# CONFIG_SENSORS_G760A is not set
+# CONFIG_SENSORS_GL518SM is not set
+# CONFIG_SENSORS_GL520SM is not set
+# CONFIG_SENSORS_IT87 is not set
+# CONFIG_SENSORS_LM63 is not set
+# CONFIG_SENSORS_LM75 is not set
+# CONFIG_SENSORS_LM77 is not set
+# CONFIG_SENSORS_LM78 is not set
+# CONFIG_SENSORS_LM80 is not set
+# CONFIG_SENSORS_LM83 is not set
+# CONFIG_SENSORS_LM85 is not set
+# CONFIG_SENSORS_LM87 is not set
+# CONFIG_SENSORS_LM90 is not set
+# CONFIG_SENSORS_LM92 is not set
+# CONFIG_SENSORS_LM93 is not set
+# CONFIG_SENSORS_LTC4215 is not set
+# CONFIG_SENSORS_LTC4245 is not set
+# CONFIG_SENSORS_LM95241 is not set
+# CONFIG_SENSORS_MAX1619 is not set
+# CONFIG_SENSORS_MAX6650 is not set
+# CONFIG_SENSORS_PC87360 is not set
+# CONFIG_SENSORS_PC87427 is not set
+# CONFIG_SENSORS_PCF8591 is not set
+# CONFIG_SENSORS_SHT15 is not set
+# CONFIG_SENSORS_SIS5595 is not set
+# CONFIG_SENSORS_DME1737 is not set
+# CONFIG_SENSORS_SMSC47M1 is not set
+# CONFIG_SENSORS_SMSC47M192 is not set
+# CONFIG_SENSORS_SMSC47B397 is not set
+# CONFIG_SENSORS_ADS7828 is not set
+# CONFIG_SENSORS_THMC50 is not set
+# CONFIG_SENSORS_TMP401 is not set
+# CONFIG_SENSORS_VIA686A is not set
+# CONFIG_SENSORS_VT1211 is not set
+# CONFIG_SENSORS_VT8231 is not set
+# CONFIG_SENSORS_W83781D is not set
+# CONFIG_SENSORS_W83791D is not set
+# CONFIG_SENSORS_W83792D is not set
+# CONFIG_SENSORS_W83793 is not set
+# CONFIG_SENSORS_W83L785TS is not set
+# CONFIG_SENSORS_W83L786NG is not set
+# CONFIG_SENSORS_W83627HF is not set
+# CONFIG_SENSORS_W83627EHF is not set
+# CONFIG_HWMON_DEBUG_CHIP is not set
 # CONFIG_THERMAL is not set
-# CONFIG_THERMAL_HWMON is not set
+CONFIG_THERMAL_HWMON=y
 # CONFIG_WATCHDOG is not set
 CONFIG_SSB_POSSIBLE=y
 
@@ -811,10 +1082,7 @@
 # CONFIG_MFD_WM8350_I2C is not set
 # CONFIG_MFD_PCF50633 is not set
 # CONFIG_REGULATOR is not set
-
-#
-# Multimedia devices
-#
+CONFIG_MEDIA_SUPPORT=y
 
 #
 # Multimedia core support
@@ -831,6 +1099,7 @@
 #
 # Graphics support
 #
+# CONFIG_DRM is not set
 # CONFIG_VGASTATE is not set
 # CONFIG_VIDEO_OUTPUT_CONTROL is not set
 CONFIG_FB=y
@@ -856,7 +1125,31 @@
 #
 # Frame buffer hardware drivers
 #
+# CONFIG_FB_CIRRUS is not set
+# CONFIG_FB_PM2 is not set
+# CONFIG_FB_CYBER2000 is not set
+# CONFIG_FB_ASILIANT is not set
+# CONFIG_FB_IMSTT is not set
 # CONFIG_FB_S1D13XXX is not set
+# CONFIG_FB_NVIDIA is not set
+# CONFIG_FB_RIVA is not set
+# CONFIG_FB_MATROX is not set
+# CONFIG_FB_RADEON is not set
+# CONFIG_FB_ATY128 is not set
+# CONFIG_FB_ATY is not set
+# CONFIG_FB_S3 is not set
+# CONFIG_FB_SAVAGE is not set
+# CONFIG_FB_SIS is not set
+# CONFIG_FB_VIA is not set
+# CONFIG_FB_NEOMAGIC is not set
+# CONFIG_FB_KYRO is not set
+# CONFIG_FB_3DFX is not set
+# CONFIG_FB_VOODOO1 is not set
+# CONFIG_FB_VT8623 is not set
+# CONFIG_FB_TRIDENT is not set
+# CONFIG_FB_ARK is not set
+# CONFIG_FB_PM3 is not set
+# CONFIG_FB_CARMINE is not set
 CONFIG_FB_SH_MOBILE_LCDC=m
 CONFIG_FB_SM501=y
 # CONFIG_FB_VIRTUAL is not set
@@ -909,7 +1202,7 @@
 CONFIG_HID_CHERRY=y
 CONFIG_HID_CHICONY=y
 CONFIG_HID_CYPRESS=y
-# CONFIG_DRAGONRISE_FF is not set
+# CONFIG_HID_DRAGONRISE is not set
 CONFIG_HID_EZKEY=y
 # CONFIG_HID_KYE is not set
 CONFIG_HID_GYRATION=y
@@ -926,14 +1219,15 @@
 CONFIG_HID_SAMSUNG=y
 CONFIG_HID_SONY=y
 CONFIG_HID_SUNPLUS=y
-# CONFIG_GREENASIA_FF is not set
+# CONFIG_HID_GREENASIA is not set
+# CONFIG_HID_SMARTJOYPLUS is not set
 # CONFIG_HID_TOPSEED is not set
-CONFIG_THRUSTMASTER_FF=m
-CONFIG_ZEROPLUS_FF=m
+# CONFIG_HID_THRUSTMASTER is not set
+# CONFIG_HID_ZEROPLUS is not set
 CONFIG_USB_SUPPORT=y
 CONFIG_USB_ARCH_HAS_HCD=y
 CONFIG_USB_ARCH_HAS_OHCI=y
-# CONFIG_USB_ARCH_HAS_EHCI is not set
+CONFIG_USB_ARCH_HAS_EHCI=y
 CONFIG_USB=y
 # CONFIG_USB_DEBUG is not set
 CONFIG_USB_ANNOUNCE_NEW_DEVICES=y
@@ -944,6 +1238,7 @@
 CONFIG_USB_DEVICEFS=y
 CONFIG_USB_DEVICE_CLASS=y
 # CONFIG_USB_DYNAMIC_MINORS is not set
+# CONFIG_USB_SUSPEND is not set
 # CONFIG_USB_OTG is not set
 # CONFIG_USB_OTG_WHITELIST is not set
 # CONFIG_USB_OTG_BLACKLIST_HUB is not set
@@ -955,12 +1250,19 @@
 # USB Host Controller Drivers
 #
 # CONFIG_USB_C67X00_HCD is not set
+# CONFIG_USB_XHCI_HCD is not set
+# CONFIG_USB_EHCI_HCD is not set
 # CONFIG_USB_OXU210HP_HCD is not set
 # CONFIG_USB_ISP116X_HCD is not set
 # CONFIG_USB_ISP1760_HCD is not set
-# CONFIG_USB_OHCI_HCD is not set
+CONFIG_USB_OHCI_HCD=y
+# CONFIG_USB_OHCI_BIG_ENDIAN_DESC is not set
+# CONFIG_USB_OHCI_BIG_ENDIAN_MMIO is not set
+CONFIG_USB_OHCI_LITTLE_ENDIAN=y
+# CONFIG_USB_UHCI_HCD is not set
 # CONFIG_USB_SL811_HCD is not set
 # CONFIG_USB_R8A66597_HCD is not set
+# CONFIG_USB_WHCI_HCD is not set
 # CONFIG_USB_HWA_HCD is not set
 
 #
@@ -1034,14 +1336,74 @@
 #
 # CONFIG_USB_GPIO_VBUS is not set
 # CONFIG_NOP_USB_XCEIV is not set
+# CONFIG_UWB is not set
 # CONFIG_MMC is not set
 # CONFIG_MEMSTICK is not set
 # CONFIG_NEW_LEDS is not set
 # CONFIG_ACCESSIBILITY is not set
-# CONFIG_RTC_CLASS is not set
+# CONFIG_INFINIBAND is not set
+CONFIG_RTC_LIB=y
+CONFIG_RTC_CLASS=y
+CONFIG_RTC_HCTOSYS=y
+CONFIG_RTC_HCTOSYS_DEVICE="rtc0"
+# CONFIG_RTC_DEBUG is not set
+
+#
+# RTC interfaces
+#
+CONFIG_RTC_INTF_SYSFS=y
+CONFIG_RTC_INTF_PROC=y
+CONFIG_RTC_INTF_DEV=y
+# CONFIG_RTC_INTF_DEV_UIE_EMUL is not set
+# CONFIG_RTC_DRV_TEST is not set
+
+#
+# I2C RTC drivers
+#
+# CONFIG_RTC_DRV_DS1307 is not set
+# CONFIG_RTC_DRV_DS1374 is not set
+# CONFIG_RTC_DRV_DS1672 is not set
+# CONFIG_RTC_DRV_MAX6900 is not set
+# CONFIG_RTC_DRV_RS5C372 is not set
+# CONFIG_RTC_DRV_ISL1208 is not set
+# CONFIG_RTC_DRV_X1205 is not set
+# CONFIG_RTC_DRV_PCF8563 is not set
+# CONFIG_RTC_DRV_PCF8583 is not set
+# CONFIG_RTC_DRV_M41T80 is not set
+# CONFIG_RTC_DRV_S35390A is not set
+# CONFIG_RTC_DRV_FM3130 is not set
+# CONFIG_RTC_DRV_RX8581 is not set
+
+#
+# SPI RTC drivers
+#
+
+#
+# Platform RTC drivers
+#
+# CONFIG_RTC_DRV_DS1286 is not set
+# CONFIG_RTC_DRV_DS1511 is not set
+# CONFIG_RTC_DRV_DS1553 is not set
+# CONFIG_RTC_DRV_DS1742 is not set
+# CONFIG_RTC_DRV_STK17TA8 is not set
+# CONFIG_RTC_DRV_M48T86 is not set
+# CONFIG_RTC_DRV_M48T35 is not set
+# CONFIG_RTC_DRV_M48T59 is not set
+# CONFIG_RTC_DRV_BQ4802 is not set
+# CONFIG_RTC_DRV_V3020 is not set
+
+#
+# on-CPU RTC drivers
+#
+CONFIG_RTC_DRV_SH=y
+CONFIG_RTC_DRV_GENERIC=y
 # CONFIG_DMADEVICES is not set
 # CONFIG_AUXDISPLAY is not set
 # CONFIG_UIO is not set
+
+#
+# TI VLYNQ
+#
 # CONFIG_STAGING is not set
 
 #
@@ -1055,16 +1417,25 @@
 CONFIG_EXT3_FS_XATTR=y
 # CONFIG_EXT3_FS_POSIX_ACL is not set
 # CONFIG_EXT3_FS_SECURITY is not set
-# CONFIG_EXT4_FS is not set
+CONFIG_EXT4_FS=y
+# CONFIG_EXT4DEV_COMPAT is not set
+CONFIG_EXT4_FS_XATTR=y
+# CONFIG_EXT4_FS_POSIX_ACL is not set
+# CONFIG_EXT4_FS_SECURITY is not set
 CONFIG_JBD=y
+# CONFIG_JBD_DEBUG is not set
+CONFIG_JBD2=y
+# CONFIG_JBD2_DEBUG is not set
 CONFIG_FS_MBCACHE=y
 # CONFIG_REISERFS_FS is not set
 # CONFIG_JFS_FS is not set
-CONFIG_FS_POSIX_ACL=y
-CONFIG_FILE_LOCKING=y
+# CONFIG_FS_POSIX_ACL is not set
 # CONFIG_XFS_FS is not set
 # CONFIG_OCFS2_FS is not set
-# CONFIG_BTRFS_FS is not set
+CONFIG_BTRFS_FS=y
+# CONFIG_BTRFS_FS_POSIX_ACL is not set
+CONFIG_FILE_LOCKING=y
+CONFIG_FSNOTIFY=y
 CONFIG_DNOTIFY=y
 CONFIG_INOTIFY=y
 CONFIG_INOTIFY_USER=y
@@ -1106,9 +1477,9 @@
 CONFIG_SYSFS=y
 CONFIG_TMPFS=y
 # CONFIG_TMPFS_POSIX_ACL is not set
-# CONFIG_HUGETLBFS is not set
-# CONFIG_HUGETLB_PAGE is not set
-# CONFIG_CONFIGFS_FS is not set
+CONFIG_HUGETLBFS=y
+CONFIG_HUGETLB_PAGE=y
+CONFIG_CONFIGFS_FS=y
 CONFIG_MISC_FILESYSTEMS=y
 # CONFIG_ADFS_FS is not set
 # CONFIG_AFFS_FS is not set
@@ -1121,7 +1492,7 @@
 # CONFIG_CRAMFS is not set
 # CONFIG_SQUASHFS is not set
 # CONFIG_VXFS_FS is not set
-CONFIG_MINIX_FS=y
+# CONFIG_MINIX_FS is not set
 # CONFIG_OMFS_FS is not set
 # CONFIG_HPFS_FS is not set
 # CONFIG_QNX4FS_FS is not set
@@ -1135,13 +1506,9 @@
 # CONFIG_NFS_V3_ACL is not set
 CONFIG_NFS_V4=y
 CONFIG_ROOT_NFS=y
-CONFIG_NFSD=y
-CONFIG_NFSD_V3=y
-# CONFIG_NFSD_V3_ACL is not set
-CONFIG_NFSD_V4=y
+# CONFIG_NFSD is not set
 CONFIG_LOCKD=y
 CONFIG_LOCKD_V4=y
-CONFIG_EXPORTFS=y
 CONFIG_NFS_COMMON=y
 CONFIG_SUNRPC=y
 CONFIG_SUNRPC_GSS=y
@@ -1204,46 +1571,74 @@
 # Kernel hacking
 #
 CONFIG_TRACE_IRQFLAGS_SUPPORT=y
-# CONFIG_PRINTK_TIME is not set
+CONFIG_PRINTK_TIME=y
 # CONFIG_ENABLE_WARN_DEPRECATED is not set
 # CONFIG_ENABLE_MUST_CHECK is not set
 CONFIG_FRAME_WARN=1024
 # CONFIG_MAGIC_SYSRQ is not set
 # CONFIG_UNUSED_SYMBOLS is not set
-# CONFIG_DEBUG_FS is not set
+CONFIG_DEBUG_FS=y
 # CONFIG_HEADERS_CHECK is not set
-# CONFIG_DEBUG_KERNEL is not set
-# CONFIG_DEBUG_BUGVERBOSE is not set
+CONFIG_DEBUG_KERNEL=y
+# CONFIG_DEBUG_SHIRQ is not set
+CONFIG_DETECT_SOFTLOCKUP=y
+# CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC is not set
+CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC_VALUE=0
+CONFIG_DETECT_HUNG_TASK=y
+# CONFIG_BOOTPARAM_HUNG_TASK_PANIC is not set
+CONFIG_BOOTPARAM_HUNG_TASK_PANIC_VALUE=0
+CONFIG_SCHED_DEBUG=y
+# CONFIG_SCHEDSTATS is not set
+# CONFIG_TIMER_STATS is not set
+# CONFIG_DEBUG_OBJECTS is not set
+# CONFIG_DEBUG_SLAB is not set
+# CONFIG_DEBUG_RT_MUTEXES is not set
+# CONFIG_RT_MUTEX_TESTER is not set
+# CONFIG_DEBUG_SPINLOCK is not set
+# CONFIG_DEBUG_MUTEXES is not set
+# CONFIG_DEBUG_LOCK_ALLOC is not set
+# CONFIG_PROVE_LOCKING is not set
+# CONFIG_LOCK_STAT is not set
+# CONFIG_DEBUG_SPINLOCK_SLEEP is not set
+# CONFIG_DEBUG_LOCKING_API_SELFTESTS is not set
+# CONFIG_DEBUG_KOBJECT is not set
+CONFIG_DEBUG_BUGVERBOSE=y
+CONFIG_DEBUG_INFO=y
+# CONFIG_DEBUG_VM is not set
+# CONFIG_DEBUG_WRITECOUNT is not set
 # CONFIG_DEBUG_MEMORY_INIT is not set
+# CONFIG_DEBUG_LIST is not set
+# CONFIG_DEBUG_SG is not set
+# CONFIG_DEBUG_NOTIFIERS is not set
+CONFIG_FRAME_POINTER=y
+# CONFIG_RCU_TORTURE_TEST is not set
 # CONFIG_RCU_CPU_STALL_DETECTOR is not set
+# CONFIG_BACKTRACE_SELF_TEST is not set
+# CONFIG_DEBUG_BLOCK_EXT_DEVT is not set
+# CONFIG_FAULT_INJECTION is not set
 # CONFIG_LATENCYTOP is not set
 CONFIG_SYSCTL_SYSCALL_CHECK=y
+# CONFIG_PAGE_POISONING is not set
 CONFIG_HAVE_FUNCTION_TRACER=y
 CONFIG_HAVE_DYNAMIC_FTRACE=y
 CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
 CONFIG_TRACING_SUPPORT=y
-
-#
-# Tracers
-#
-# CONFIG_FUNCTION_TRACER is not set
-# CONFIG_IRQSOFF_TRACER is not set
-# CONFIG_PREEMPT_TRACER is not set
-# CONFIG_SCHED_TRACER is not set
-# CONFIG_CONTEXT_SWITCH_TRACER is not set
-# CONFIG_EVENT_TRACER is not set
-# CONFIG_BOOT_TRACER is not set
-# CONFIG_TRACE_BRANCH_PROFILING is not set
-# CONFIG_STACK_TRACER is not set
-# CONFIG_KMEMTRACE is not set
-# CONFIG_WORKQUEUE_TRACER is not set
-# CONFIG_BLK_DEV_IO_TRACE is not set
+# CONFIG_FTRACE is not set
+# CONFIG_DYNAMIC_DEBUG is not set
 # CONFIG_DMA_API_DEBUG is not set
 # CONFIG_SAMPLES is not set
 CONFIG_HAVE_ARCH_KGDB=y
+# CONFIG_KGDB is not set
 # CONFIG_SH_STANDARD_BIOS is not set
-# CONFIG_EARLY_SCIF_CONSOLE is not set
-# CONFIG_MORE_COMPILE_OPTIONS is not set
+CONFIG_EARLY_SCIF_CONSOLE=y
+CONFIG_EARLY_SCIF_CONSOLE_PORT=0xffeb0000
+CONFIG_EARLY_PRINTK=y
+# CONFIG_DEBUG_BOOTMEM is not set
+# CONFIG_DEBUG_STACKOVERFLOW is not set
+# CONFIG_DEBUG_STACK_USAGE is not set
+# CONFIG_4KSTACKS is not set
+# CONFIG_DUMP_CODE is not set
+# CONFIG_SH_NO_BSS_INIT is not set
 
 #
 # Security options
@@ -1303,7 +1698,7 @@
 #
 # Digest
 #
-# CONFIG_CRYPTO_CRC32C is not set
+CONFIG_CRYPTO_CRC32C=y
 # CONFIG_CRYPTO_MD4 is not set
 CONFIG_CRYPTO_MD5=y
 # CONFIG_CRYPTO_MICHAEL_MIC is not set
@@ -1356,13 +1751,18 @@
 CONFIG_BITREVERSE=y
 CONFIG_GENERIC_FIND_LAST_BIT=y
 # CONFIG_CRC_CCITT is not set
-# CONFIG_CRC16 is not set
+CONFIG_CRC16=y
 # CONFIG_CRC_T10DIF is not set
 # CONFIG_CRC_ITU_T is not set
 CONFIG_CRC32=y
 # CONFIG_CRC7 is not set
-# CONFIG_LIBCRC32C is not set
+CONFIG_LIBCRC32C=y
+CONFIG_AUDIT_GENERIC=y
+CONFIG_ZLIB_INFLATE=y
+CONFIG_ZLIB_DEFLATE=y
+CONFIG_DECOMPRESS_GZIP=y
 CONFIG_HAS_IOMEM=y
 CONFIG_HAS_IOPORT=y
 CONFIG_HAS_DMA=y
 CONFIG_NLATTR=y
+CONFIG_GENERIC_ATOMIC64=y
diff --git a/arch/sh/drivers/pci/Makefile b/arch/sh/drivers/pci/Makefile
index d2ffc47..08af1f4 100644
--- a/arch/sh/drivers/pci/Makefile
+++ b/arch/sh/drivers/pci/Makefile
@@ -8,6 +8,7 @@
 obj-$(CONFIG_CPU_SUBTYPE_SH7763)	+= pci-sh7780.o ops-sh4.o
 obj-$(CONFIG_CPU_SUBTYPE_SH7780)	+= pci-sh7780.o ops-sh4.o
 obj-$(CONFIG_CPU_SUBTYPE_SH7785)	+= pci-sh7780.o ops-sh4.o
+obj-$(CONFIG_CPU_SUBTYPE_SH7786)	+= ops-sh7786.o
 obj-$(CONFIG_CPU_SH5)			+= pci-sh5.o ops-sh5.o
 
 obj-$(CONFIG_SH_DREAMCAST)		+= ops-dreamcast.o fixups-dreamcast.o \
@@ -24,3 +25,4 @@
 obj-$(CONFIG_SH_LANDISK)		+= fixups-landisk.o
 obj-$(CONFIG_SH_LBOX_RE2)		+= fixups-rts7751r2d.o
 obj-$(CONFIG_SH_CAYMAN)			+= fixups-cayman.o
+obj-$(CONFIG_SH_URQUELL)		+= pcie-sh7786.o
diff --git a/arch/sh/drivers/pci/ops-dreamcast.c b/arch/sh/drivers/pci/ops-dreamcast.c
index e83d0d3..16e0a1b 100644
--- a/arch/sh/drivers/pci/ops-dreamcast.c
+++ b/arch/sh/drivers/pci/ops-dreamcast.c
@@ -18,7 +18,6 @@
 #include <linux/pci.h>
 #include <linux/module.h>
 #include <linux/io.h>
-#include <linux/irq.h>
 #include <mach/pci.h>
 
 /*
diff --git a/arch/sh/drivers/pci/ops-sh7786.c b/arch/sh/drivers/pci/ops-sh7786.c
new file mode 100644
index 0000000..48f594b9
--- /dev/null
+++ b/arch/sh/drivers/pci/ops-sh7786.c
@@ -0,0 +1,134 @@
+/*
+ * Generic SH7786 PCI-Express operations.
+ *
+ *  Copyright (C) 2009  Paul Mundt
+ *
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License v2. See the file "COPYING" in the main directory of this archive
+ * for more details.
+ */
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/pci.h>
+#include <linux/io.h>
+#include <linux/spinlock.h>
+#include "pcie-sh7786.h"
+
+enum {
+	PCI_ACCESS_READ,
+	PCI_ACCESS_WRITE,
+};
+
+static DEFINE_SPINLOCK(sh7786_pcie_lock);
+
+static int sh7786_pcie_config_access(unsigned char access_type,
+		struct pci_bus *bus, unsigned int devfn, int where, u32 *data)
+{
+	struct pci_channel *chan = bus->sysdata;
+	int dev, func;
+
+	dev = PCI_SLOT(devfn);
+	func = PCI_FUNC(devfn);
+
+	if (bus->number > 255 || dev > 31 || func > 7)
+		return PCIBIOS_FUNC_NOT_SUPPORTED;
+	if (devfn)
+		return PCIBIOS_DEVICE_NOT_FOUND;
+
+	/* Set the PIO address */
+	pci_write_reg(chan, (bus->number << 24) | (dev << 19) |
+				(func << 16) | (where & ~3), SH4A_PCIEPAR);
+
+	/* Enable the configuration access */
+	pci_write_reg(chan, (1 << 31), SH4A_PCIEPCTLR);
+
+	if (access_type == PCI_ACCESS_READ)
+		*data = pci_read_reg(chan, SH4A_PCIEPDR);
+	else
+		pci_write_reg(chan, *data, SH4A_PCIEPDR);
+
+	/* Check for master and target aborts */
+	if (pci_read_reg(chan, SH4A_PCIEPCICONF1) & ((1 << 29) | (1 << 28)))
+		return PCIBIOS_DEVICE_NOT_FOUND;
+
+	return PCIBIOS_SUCCESSFUL;
+}
+
+static int sh7786_pcie_read(struct pci_bus *bus, unsigned int devfn,
+			    int where, int size, u32 *val)
+{
+	unsigned long flags;
+	int ret;
+	u32 data;
+
+        if ((size == 2) && (where & 1))
+		return PCIBIOS_BAD_REGISTER_NUMBER;
+	else if ((size == 4) && (where & 3))
+		return PCIBIOS_BAD_REGISTER_NUMBER;
+
+	spin_lock_irqsave(&sh7786_pcie_lock, flags);
+	ret = sh7786_pcie_config_access(PCI_ACCESS_READ, bus,
+					devfn, where, &data);
+	if (ret != PCIBIOS_SUCCESSFUL)
+		goto out;
+
+	if (size == 1)
+		*val = (data >> ((where & 3) << 3)) & 0xff;
+	else if (size == 2)
+		*val = (data >> ((where & 2) << 3)) & 0xffff;
+	else
+		*val = data;
+
+	dev_dbg(&bus->dev, "pcie-config-read: bus=%3d devfn=0x%04x "
+		"where=0x%04x size=%d val=0x%08lx\n", bus->number,
+		devfn, where, size, (unsigned long)*val);
+
+out:
+	spin_unlock_irqrestore(&sh7786_pcie_lock, flags);
+	return ret;
+}
+
+static int sh7786_pcie_write(struct pci_bus *bus, unsigned int devfn,
+			     int where, int size, u32 val)
+{
+	unsigned long flags;
+	int shift, ret;
+	u32 data;
+
+        if ((size == 2) && (where & 1))
+		return PCIBIOS_BAD_REGISTER_NUMBER;
+	else if ((size == 4) && (where & 3))
+		return PCIBIOS_BAD_REGISTER_NUMBER;
+
+	spin_lock_irqsave(&sh7786_pcie_lock, flags);
+	ret = sh7786_pcie_config_access(PCI_ACCESS_READ, bus,
+					devfn, where, &data);
+	if (ret != PCIBIOS_SUCCESSFUL)
+		goto out;
+
+	dev_dbg(&bus->dev, "pcie-config-write: bus=%3d devfn=0x%04x "
+		"where=0x%04x size=%d val=%08lx\n", bus->number,
+		devfn, where, size, (unsigned long)val);
+
+	if (size == 1) {
+		shift = (where & 3) << 3;
+		data &= ~(0xff << shift);
+		data |= ((val & 0xff) << shift);
+	} else if (size == 2) {
+		shift = (where & 2) << 3;
+		data &= ~(0xffff << shift);
+		data |= ((val & 0xffff) << shift);
+	} else
+		data = val;
+
+	ret = sh7786_pcie_config_access(PCI_ACCESS_WRITE, bus,
+					devfn, where, &data);
+out:
+	spin_unlock_irqrestore(&sh7786_pcie_lock, flags);
+	return ret;
+}
+
+struct pci_ops sh7786_pci_ops = {
+	.read	= sh7786_pcie_read,
+	.write	= sh7786_pcie_write,
+};
diff --git a/arch/sh/drivers/pci/pci.c b/arch/sh/drivers/pci/pci.c
index 54d77cb..9a1c423 100644
--- a/arch/sh/drivers/pci/pci.c
+++ b/arch/sh/drivers/pci/pci.c
@@ -53,12 +53,8 @@
 
 void __devinit register_pci_controller(struct pci_channel *hose)
 {
-	if (request_resource(&iomem_resource, hose->mem_resource) < 0)
-		goto out;
-	if (request_resource(&ioport_resource, hose->io_resource) < 0) {
-		release_resource(hose->mem_resource);
-		goto out;
-	}
+	request_resource(&iomem_resource, hose->mem_resource);
+	request_resource(&ioport_resource, hose->io_resource);
 
 	*hose_tail = hose;
 	hose_tail = &hose->next;
@@ -80,12 +76,6 @@
 		pcibios_scanbus(hose);
 		mutex_unlock(&pci_scan_mutex);
 	}
-
-	return;
-
-out:
-	printk(KERN_WARNING
-	       "Skipping PCI bus scan due to resource conflict\n");
 }
 
 static int __init pcibios_init(void)
diff --git a/arch/sh/drivers/pci/pcie-sh7786.c b/arch/sh/drivers/pci/pcie-sh7786.c
new file mode 100644
index 0000000..ac37ee8
--- /dev/null
+++ b/arch/sh/drivers/pci/pcie-sh7786.c
@@ -0,0 +1,355 @@
+/*
+ * Low-Level PCI Express Support for the SH7786
+ *
+ *  Copyright (C) 2009  Paul Mundt
+ *
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ */
+#include <linux/pci.h>
+#include <linux/init.h>
+#include <linux/kernel.h>
+#include <linux/io.h>
+#include <linux/delay.h>
+#include "pcie-sh7786.h"
+#include <asm/sizes.h>
+
+struct sh7786_pcie_port {
+	struct pci_channel	*hose;
+	unsigned int		index;
+	int			endpoint;
+	int			link;
+};
+
+static struct sh7786_pcie_port *sh7786_pcie_ports;
+static unsigned int nr_ports;
+
+static struct sh7786_pcie_hwops {
+	int (*core_init)(void);
+	int (*port_init_hw)(struct sh7786_pcie_port *port);
+} *sh7786_pcie_hwops;
+
+static struct resource sh7786_pci_32bit_mem_resources[] = {
+	{
+		.name	= "pci0_mem",
+		.start	= SH4A_PCIMEM_BASEA,
+		.end	= SH4A_PCIMEM_BASEA + SZ_64M - 1,
+		.flags	= IORESOURCE_MEM,
+	}, {
+		.name	= "pci1_mem",
+		.start	= SH4A_PCIMEM_BASEA1,
+		.end	= SH4A_PCIMEM_BASEA1 + SZ_64M - 1,
+		.flags	= IORESOURCE_MEM,
+	}, {
+		.name	= "pci2_mem",
+		.start	= SH4A_PCIMEM_BASEA2,
+		.end	= SH4A_PCIMEM_BASEA2 + SZ_64M - 1,
+		.flags	= IORESOURCE_MEM,
+	},
+};
+
+static struct resource sh7786_pci_29bit_mem_resource = {
+	.start	= SH4A_PCIMEM_BASE,
+	.end	= SH4A_PCIMEM_BASE + SZ_64M - 1,
+	.flags	= IORESOURCE_MEM,
+};
+
+static struct resource sh7786_pci_io_resources[] = {
+	{
+		.name	= "pci0_io",
+		.start	= SH4A_PCIIO_BASE,
+		.end	= SH4A_PCIIO_BASE + SZ_8M - 1,
+		.flags	= IORESOURCE_IO,
+	}, {
+		.name	= "pci1_io",
+		.start	= SH4A_PCIIO_BASE1,
+		.end	= SH4A_PCIIO_BASE1 + SZ_8M - 1,
+		.flags	= IORESOURCE_IO,
+	}, {
+		.name	= "pci2_io",
+		.start	= SH4A_PCIIO_BASE2,
+		.end	= SH4A_PCIIO_BASE2 + SZ_4M - 1,
+		.flags	= IORESOURCE_IO,
+	},
+};
+
+extern struct pci_ops sh7786_pci_ops;
+
+#define DEFINE_CONTROLLER(start, idx)				\
+{								\
+	.pci_ops	= &sh7786_pci_ops,			\
+	.reg_base	= start,				\
+	/* mem_resource filled in at probe time */		\
+	.mem_offset	= 0,					\
+	.io_resource	= &sh7786_pci_io_resources[idx],	\
+	.io_offset	= 0,					\
+}
+
+static struct pci_channel sh7786_pci_channels[] = {
+	DEFINE_CONTROLLER(0xfe000000, 0),
+	DEFINE_CONTROLLER(0xfe200000, 1),
+	DEFINE_CONTROLLER(0xfcc00000, 2),
+};
+
+static int phy_wait_for_ack(struct pci_channel *chan)
+{
+	unsigned int timeout = 100;
+
+	while (timeout--) {
+		if (pci_read_reg(chan, SH4A_PCIEPHYADRR) & (1 << BITS_ACK))
+			return 0;
+
+		udelay(100);
+	}
+
+	return -ETIMEDOUT;
+}
+
+static int pci_wait_for_irq(struct pci_channel *chan, unsigned int mask)
+{
+	unsigned int timeout = 100;
+
+	while (timeout--) {
+		if ((pci_read_reg(chan, SH4A_PCIEINTR) & mask) == mask)
+			return 0;
+
+		udelay(100);
+	}
+
+	return -ETIMEDOUT;
+}
+
+static void phy_write_reg(struct pci_channel *chan, unsigned int addr,
+			  unsigned int lane, unsigned int data)
+{
+	unsigned long phyaddr, ctrl;
+
+	phyaddr = (1 << BITS_CMD) + ((lane & 0xf) << BITS_LANE) +
+			((addr & 0xff) << BITS_ADR);
+
+	/* Enable clock */
+	ctrl = pci_read_reg(chan, SH4A_PCIEPHYCTLR);
+	ctrl |= (1 << BITS_CKE);
+	pci_write_reg(chan, ctrl, SH4A_PCIEPHYCTLR);
+
+	/* Set write data */
+	pci_write_reg(chan, data, SH4A_PCIEPHYDOUTR);
+	pci_write_reg(chan, phyaddr, SH4A_PCIEPHYADRR);
+
+	phy_wait_for_ack(chan);
+
+	/* Clear command */
+	pci_write_reg(chan, 0, SH4A_PCIEPHYADRR);
+
+	phy_wait_for_ack(chan);
+
+	/* Disable clock */
+	ctrl = pci_read_reg(chan, SH4A_PCIEPHYCTLR);
+	ctrl &= ~(1 << BITS_CKE);
+	pci_write_reg(chan, ctrl, SH4A_PCIEPHYCTLR);
+}
+
+static int phy_init(struct pci_channel *chan)
+{
+	unsigned int timeout = 100;
+
+	/* Initialize the phy */
+	phy_write_reg(chan, 0x60, 0xf, 0x004b008b);
+	phy_write_reg(chan, 0x61, 0xf, 0x00007b41);
+	phy_write_reg(chan, 0x64, 0xf, 0x00ff4f00);
+	phy_write_reg(chan, 0x65, 0xf, 0x09070907);
+	phy_write_reg(chan, 0x66, 0xf, 0x00000010);
+	phy_write_reg(chan, 0x74, 0xf, 0x0007001c);
+	phy_write_reg(chan, 0x79, 0xf, 0x01fc000d);
+
+	/* Deassert Standby */
+	phy_write_reg(chan, 0x67, 0xf, 0x00000400);
+
+	while (timeout--) {
+		if (pci_read_reg(chan, SH4A_PCIEPHYSR))
+			return 0;
+
+		udelay(100);
+	}
+
+	return -ETIMEDOUT;
+}
+
+static int pcie_init(struct sh7786_pcie_port *port)
+{
+	struct pci_channel *chan = port->hose;
+	unsigned int data;
+	int ret;
+
+	/* Begin initialization */
+	pci_write_reg(chan, 0, SH4A_PCIETCTLR);
+
+	/* Initialize as type1. */
+	data = pci_read_reg(chan, SH4A_PCIEPCICONF3);
+	data &= ~(0x7f << 16);
+	data |= PCI_HEADER_TYPE_BRIDGE << 16;
+	pci_write_reg(chan, data, SH4A_PCIEPCICONF3);
+
+	/* Initialize default capabilities. */
+	data = pci_read_reg(chan, SH4A_PCIEEXPCAP0);
+	data &= ~(PCI_EXP_FLAGS_TYPE << 16);
+
+	if (port->endpoint)
+		data |= PCI_EXP_TYPE_ENDPOINT << 20;
+	else
+		data |= PCI_EXP_TYPE_ROOT_PORT << 20;
+
+	data |= PCI_CAP_ID_EXP;
+	pci_write_reg(chan, data, SH4A_PCIEEXPCAP0);
+
+	/* Enable x4 link width and extended sync. */
+	data = pci_read_reg(chan, SH4A_PCIEEXPCAP4);
+	data &= ~(PCI_EXP_LNKSTA_NLW << 16);
+	data |= (1 << 22) | PCI_EXP_LNKCTL_ES;
+	pci_write_reg(chan, data, SH4A_PCIEEXPCAP4);
+
+	/* Set the completion timer timeout to the maximum 32ms. */
+	data = pci_read_reg(chan, SH4A_PCIETLCTLR);
+	data &= ~0xffff;
+	data |= 0x32 << 8;
+	pci_write_reg(chan, data, SH4A_PCIETLCTLR);
+
+	/*
+	 * Set fast training sequences to the maximum 255,
+	 * and enable MAC data scrambling.
+	 */
+	data = pci_read_reg(chan, SH4A_PCIEMACCTLR);
+	data &= ~PCIEMACCTLR_SCR_DIS;
+	data |= (0xff << 16);
+	pci_write_reg(chan, data, SH4A_PCIEMACCTLR);
+
+	/* Finish initialization */
+	data = pci_read_reg(chan, SH4A_PCIETCTLR);
+	data |= 0x1;
+	pci_write_reg(chan, data, SH4A_PCIETCTLR);
+
+	/* Enable DL_Active Interrupt generation */
+	data = pci_read_reg(chan, SH4A_PCIEDLINTENR);
+	data |= PCIEDLINTENR_DLL_ACT_ENABLE;
+	pci_write_reg(chan, data, SH4A_PCIEDLINTENR);
+
+	/* Disable MAC data scrambling. */
+	data = pci_read_reg(chan, SH4A_PCIEMACCTLR);
+	data |= PCIEMACCTLR_SCR_DIS | (0xff << 16);
+	pci_write_reg(chan, data, SH4A_PCIEMACCTLR);
+
+	ret = pci_wait_for_irq(chan, MASK_INT_TX_CTRL);
+	if (unlikely(ret != 0))
+		return -ENODEV;
+
+	pci_write_reg(chan, 0x00100007, SH4A_PCIEPCICONF1);
+	pci_write_reg(chan, 0x80888000, SH4A_PCIETXVC0DCTLR);
+	pci_write_reg(chan, 0x00222000, SH4A_PCIERXVC0DCTLR);
+	pci_write_reg(chan, 0x000050A0, SH4A_PCIEEXPCAP2);
+
+	wmb();
+
+	data = pci_read_reg(chan, SH4A_PCIEMACSR);
+	printk(KERN_NOTICE "PCI: PCIe#%d link width %d\n",
+	       port->index, (data >> 20) & 0x3f);
+
+	pci_write_reg(chan, 0x007c0000, SH4A_PCIEPAMR0);
+	pci_write_reg(chan, 0x00000000, SH4A_PCIEPARH0);
+	pci_write_reg(chan, 0x00000000, SH4A_PCIEPARL0);
+	pci_write_reg(chan, 0x80000100, SH4A_PCIEPTCTLR0);
+
+	pci_write_reg(chan, 0x03fc0000, SH4A_PCIEPAMR2);
+	pci_write_reg(chan, 0x00000000, SH4A_PCIEPARH2);
+	pci_write_reg(chan, 0x00000000, SH4A_PCIEPARL2);
+	pci_write_reg(chan, 0x80000000, SH4A_PCIEPTCTLR2);
+
+	return 0;
+}
+
+int __init pcibios_map_platform_irq(struct pci_dev *pdev, u8 slot, u8 pin)
+{
+        return 71;
+}
+
+static int sh7786_pcie_core_init(void)
+{
+	/* Return the number of ports */
+	return test_mode_pin(MODE_PIN12) ? 3 : 2;
+}
+
+static int __devinit sh7786_pcie_init_hw(struct sh7786_pcie_port *port)
+{
+	int ret;
+
+	ret = phy_init(port->hose);
+	if (unlikely(ret < 0))
+		return ret;
+
+	/*
+	 * Check if we are configured in endpoint or root complex mode,
+	 * this is a fixed pin setting that applies to all PCIe ports.
+	 */
+	port->endpoint = test_mode_pin(MODE_PIN11);
+
+	ret = pcie_init(port);
+	if (unlikely(ret < 0))
+		return ret;
+
+	register_pci_controller(port->hose);
+
+	return 0;
+}
+
+static struct sh7786_pcie_hwops sh7786_65nm_pcie_hwops __initdata = {
+	.core_init	= sh7786_pcie_core_init,
+	.port_init_hw	= sh7786_pcie_init_hw,
+};
+
+static int __init sh7786_pcie_init(void)
+{
+	int ret = 0, i;
+
+	printk(KERN_NOTICE "PCI: Starting intialization.\n");
+
+	sh7786_pcie_hwops = &sh7786_65nm_pcie_hwops;
+
+	nr_ports = sh7786_pcie_hwops->core_init();
+	BUG_ON(nr_ports > ARRAY_SIZE(sh7786_pci_channels));
+
+	if (unlikely(nr_ports == 0))
+		return -ENODEV;
+
+	sh7786_pcie_ports = kzalloc(nr_ports * sizeof(struct sh7786_pcie_port),
+				    GFP_KERNEL);
+	if (unlikely(!sh7786_pcie_ports))
+		return -ENOMEM;
+
+	printk(KERN_NOTICE "PCI: probing %d ports.\n", nr_ports);
+
+	for (i = 0; i < nr_ports; i++) {
+		struct sh7786_pcie_port *port = sh7786_pcie_ports + i;
+
+		port->index		= i;
+		port->hose		= sh7786_pci_channels + i;
+		port->hose->io_map_base	= port->hose->io_resource->start;
+
+		/*
+		 * Check if we are booting in 29 or 32-bit mode
+		 *
+		 * 32-bit mode provides each controller with its own
+		 * memory window, while 29-bit mode uses a shared one.
+		 */
+		port->hose->mem_resource = test_mode_pin(MODE_PIN10) ?
+			&sh7786_pci_32bit_mem_resources[i] :
+			&sh7786_pci_29bit_mem_resource;
+
+		ret |= sh7786_pcie_hwops->port_init_hw(port);
+	}
+
+	if (unlikely(ret))
+		return ret;
+
+	return 0;
+}
+arch_initcall(sh7786_pcie_init);
diff --git a/arch/sh/drivers/pci/pcie-sh7786.h b/arch/sh/drivers/pci/pcie-sh7786.h
new file mode 100644
index 0000000..c655290
--- /dev/null
+++ b/arch/sh/drivers/pci/pcie-sh7786.h
@@ -0,0 +1,589 @@
+/*
+ * SH7786 PCI-Express controller definitions.
+ *
+ * Copyright (C) 2008, 2009 Renesas Technology Corp.
+ * All rights reserved.
+ *
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ */
+#ifndef __PCI_SH7786_H
+#define __PCI_SH7786_H
+
+/* PCIe bus-0(x4) on SH7786 */			// Rev1.171
+#define SH4A_PCIE_SPW_BASE	0xFE000000	/* spw config address for controller 0 */
+#define SH4A_PCIE_SPW_BASE1	0xFE200000	/* spw config address for controller 1 (Rev1.14)*/
+#define SH4A_PCIE_SPW_BASE2	0xFCC00000	/* spw config address for controller 2 (Rev1.171)*/
+#define SH4A_PCIE_SPW_BASE_LEN	0x00080000
+
+#define SH4A_PCI_CNFG_BASE	0xFE040000	/* pci config address for controller 0 */
+#define SH4A_PCI_CNFG_BASE1	0xFE240000	/* pci config address for controller 1 (Rev1.14)*/
+#define SH4A_PCI_CNFG_BASE2	0xFCC40000	/* pci config address for controller 2 (Rev1.171)*/
+#define SH4A_PCI_CNFG_BASE_LEN	0x00040000
+
+#define SH4A_PCIPIO_ADDR_OFFSET	0x000001c0	/* offset to pci config_address */
+#define SH4A_PCIPIO_DATA_OFFSET	0x00000220	/* offset to pci config_data */
+
+/*
+ * for PEX8111(Max Payload Size=128B,PCIIO_SIZE=64K),
+ * for other(Max Payload Size=4096B,PCIIO_SIZE=8M)
+ */
+
+/* PCI0-0: PCI I/O space */
+#define SH4A_PCIIO_BASE		0xFD000000	/* PCI I/O for controller 0 */
+#define SH4A_PCIIO_BASE1	0xFD800000	/* PCI I/O for controller 1 (Rev1.14)*/
+#define SH4A_PCIIO_BASE2	0xFC800000	/* PCI I/O for controller 2 (Rev1.171)*/
+
+#define SH4A_PCIIO_SIZE64	0x00010000	/* PLX allows only 64K */
+#define SH4A_PCIIO_SIZE		0x00800000	/* 8M */
+#define SH4A_PCIIO_SIZE2	0x00400000	/* 4M (Rev1.171)*/
+
+/* PCI0-1: PCI memory space 29-bit address */
+#define SH4A_PCIMEM_BASE	0x10000000
+#define SH4A_PCIMEM_SIZE	0x04000000	/* 64M */
+
+/* PCI0-2: PCI memory space 32-bit address */
+#define SH4A_PCIMEM_BASEA	0xC0000000	/*  for controller 0 */
+#define SH4A_PCIMEM_BASEA1	0xA0000000	/*  for controller 1 (Rev1.14)*/
+#define SH4A_PCIMEM_BASEA2	0x80000000	/*  for controller 2 (Rev1.171)*/
+#define SH4A_PCIMEM_SIZEA	0x20000000	/* 512M */
+
+/* PCI0: PCI memory target transfer 32-bit address translation value(Rev1.11T)*/
+#define SH4A_PCIBMSTR_TRANSLATION	0x20000000
+
+#define SH4A_PCI_DEVICE_ID		0x0002
+#define SH4A_PCI_VENDOR_ID		0x1912
+
+// PCI compatible 000-03f
+#define PCI_CMD		0x004
+#define PCI_RID		0x008
+#define PCI_IBAR	0x010
+#define PCI_MBAR0	0x014
+#define PCI_MBAR1	0x018
+
+/* PCI power management/MSI/capablity 040-0ff */
+/* PCIE extended 100-fff */
+
+/* SH7786 device identification */	// Rev1.171
+#define SH4A_PVR		(0xFF000030)
+#define SH4A_PVR_SHX3		(0x10400000)
+#define SH4A_PRR		(0xFF000044)
+#define SH4A_PRR_SH7786		(0x00000400)	// Rev1.171
+
+/*	SPVCR0		*/
+#define	SH4A_PCIEVCR0		(0x000000)	/* R - 0x0000 0000 32 */
+#define		BITS_TOP_MB	(24)
+#define		MASK_TOP_MB	(0xff<<BITS_TOP_MB)
+#define		BITS_BOT_MB	(16)
+#define		MASK_BOT_MB	(0xff<<BITS_BOT_MB)
+#define		BITS_VC_ID	(0)
+#define		MASK_VC_ID	(0xffff<<BITS_VC_ID)
+
+/*	SPVCR1		*/
+#define	SH4A_PCIEVCR1		(0x000004)	/* R - 0x0000 0000 32*/
+#define		BITS_BADOPC	(5)		/* 5 BADOPC 0 R/W */
+#define		MASK_BADOPC	(1<<BITS_BADOPC)
+#define		BITS_BADDEST	(4)		/*4 BADDEST 0 R/W  */
+#define		MASK_BADDEST	(1<<BITS_BADDEST)
+#define		BITS_UNSOLRESP	(3)		/* 3 UNSOLRESP 0 R/W  */
+#define		MASK_UNSOLRESP	(1<<BITS_UNSOLRESP)
+#define		BITS_ERRSNT	(1)		/* 1 ERRSNT 0 */
+#define		MASK_ERRSNT	(1<<BITS_ERRSNT)
+#define		BITS_ERRRCV	(0)		/* 0 ERRRCV 0 */
+#define		MASK_ERRRCV	(1<<BITS_ERRRCV)
+
+/*	PCIEECR		*/
+#define	SH4A_PCIEECR		(0x000008)	/* R/W - 0x0000 0000 32 */
+#define		BITS_ENBL	(0)	/* 0 ENBL 0 R/W */
+#define		MASK_ENBL	(1<<BITS_ENBL)
+
+/*	PCIEPAR		*/
+#define	SH4A_PCIEPAR		(0x000010)	/* R/W - 0x0000 0000 32 */
+#define		BITS_BN		(24)
+#define		MASK_BN		(0xff<<BITS_BN)
+#define		BITS_DN		(19)
+#define		MASK_DN		(0x1f<<BITS_DN)
+#define		BITS_FN		(16)
+#define		MASK_FN		(0x7<<BITS_FN)
+#define		BITS_EREGNO	(8)
+#define		MASK_EREGNO	(0xff<<BITS_EREGNO)
+#define		BITS_REGNO	(2)
+#define		MASK_REGNO	(0x3f<<BITS_REGNO)
+
+/*	PCIEPCTLR	*/
+#define	SH4A_PCIEPCTLR		(0x000018)	/* R/W - 0x0000 0000 32 */
+#define		BITS_CCIE	(31)	/*  31 CCIE */
+#define		MASK_CCIE	(1<<BITS_CCIE)
+#define		BITS_TYPE	(8)
+#define		MASK_TYPE	(1<<BITS_TYPE)
+#define		BITS_C_VC	(0)
+#define		MASK_C_VC	(1<<BITS_C_VC)
+
+/*	PCIEPDR		*/
+#define	SH4A_PCIEPDR		(0x000020)	/* R/W - 0x0000 0000 32 */
+#define		BITS_PDR	(0)
+#define		MASK_PDR	(0xffffffff<<BITS_PDR)
+
+/*	PCIEMSGALR	*/
+#define	SH4A_PCIEMSGALR		(0x000030)	/* R/W - 0x0000 0000 32 */
+#define		BITS_MSGADRL	(0)
+#define		MASK_MSGADRL	(0xffffffff<<BITS_MSGADRL)
+
+/*	PCIEMSGAHR	*/
+#define	SH4A_PCIEMSGAHR		(0x000034)	/* R/W - 0x0000 0000 32 */
+#define		BITS_MSGADRH	(0)
+#define		MASK_MSGADRH	(0xffffffff<<BITS_MSGADRH)
+
+/*	PCIEMSGCTLR	*/
+#define	SH4A_PCIEMSGCTLR	(0x000038)	/* R/W - 0x0000 0000 32 */
+#define		BITS_MSGIE	(31)
+#define		MASK_MSGIE	(1<<BITS_MSGIE)
+#define		BITS_MROUTE	(16)
+#define		MASK_MROUTE	(0x7<<BITS_MROUTE)
+#define		BITS_MCODE	(8)
+#define		MASK_MCODE	(0xff<<BITS_MCODE)
+#define		BITS_M_VC	(0)
+#define		MASK_M_VC	(1<<BITS_M_VC)
+
+/*	PCIEMSG		*/
+#define	SH4A_PCIEMSG		(0x000040)	/* W - - 32	*/
+#define		BITS_MDATA	(0)
+#define		MASK_MDATA	(0xffffffff<<BITS_MDATA)
+
+/*	PCIEPHYCTLR	*/
+#define	SH4A_PCIEPHYCTLR	(0x010000)	/* R/W - 0x0000 0000 32 */
+#define		BITS_CKE	(0)
+#define		MASK_CKE	(1<<BITS_CKE)
+
+/*	PCIERMSGIER	*/
+#define	SH4A_PCIERMSGIER	(0x004040)	/* R/W - 0x0000 0000 32 */
+
+/*	PCIEPHYADRR	*/
+#define	SH4A_PCIEPHYADRR	(0x010004)	/* R/W - 0x0000 0000 32 */
+#define		BITS_ACK	(24)			// Rev1.171
+#define		MASK_ACK	(1<<BITS_ACK)		// Rev1.171
+#define		BITS_CMD	(16)			// Rev1.171
+#define		MASK_CMD	(0x03<<BITS_CMD)	// Rev1.171
+#define		BITS_LANE	(8)
+#define		MASK_LANE	(0x0f<<BITS_LANE)
+#define		BITS_ADR	(0)
+#define		MASK_ADR	(0xff<<BITS_ADR)
+
+/*	PCIEPHYDINR	*/							// Rev1.171 start.
+#define	SH4A_PCIEPHYDINR	(0x010008)	/* R/W - 0x0000 0000 32 */
+
+/*	PCIEPHYDOUTR	*/
+#define	SH4A_PCIEPHYDOUTR	(0x01000C)	/* R/W - 0x0000 0000 32 */
+
+/*	PCIEPHYSR	*/
+#define	SH4A_PCIEPHYSR		(0x010010)	/* R/W - 0x0000 0000 32 */	// Rev1.171 end.
+
+/*	PCIEPHYDATAR	*/
+#define	SH4A_PCIEPHYDATAR	(0x00008)	/* R/W - 0xxxxx xxxx 32 */
+#define		BITS_DATA	(0)
+#define		MASK_DATA	(0xffffffff<<BITS_DATA)
+
+/*	PCIETCTLR	*/
+#define	SH4A_PCIETCTLR		(0x020000)	/* R/W R/W 0x0000 0000 32 */
+#define		BITS_CFINT	(0)
+#define		MASK_CFINT	(1<<BITS_CFINT)
+
+/*	PCIETSTR	*/
+#define	SH4A_PCIETSTR		(0x020004)	/* R/W R/W 0x0000 0000 32  */
+
+/*	PCIEINTR	*/
+#define	SH4A_PCIEINTR		(0x020008)	/* R/W R/W 0x0000 0000 32  */
+#define		BITS_INT_RX_ERP			(31)
+#define		MASK_INT_RX_ERP			(1<<BITS_INT_RX_ERP)
+#define		BITS_INT_RX_VCX_Posted		(30)
+#define		MASK_INT_RX_VCX_Posted		(1<<BITS_INT_RX_VCX_Posted)
+#define		BITS_INT_RX_VCX_NonPosted	(29)
+#define		MASK_INT_RX_VCX_NonPosted	(1<<BITS_INT_RX_VCX_NonPosted)
+#define		BITS_INT_RX_VCX_CPL		(28)
+#define		MASK_INT_RX_VCX_CPL		(1<<BITS_INT_RX_VCX_CPL)
+#define		BITS_INT_TX_VCX_Posted		(26)
+#define		MASK_INT_TX_VCX_Posted		(1<<BITS_INT_TX_VCX_Posted)
+#define		BITS_INT_TX_VCX_NonPosted	(25)
+#define		MASK_INT_TX_VCX_NonPosted	(1<<BITS_INT_TX_VCX_NonPosted)
+#define		BITS_INT_TX_VCX_CPL		(24)
+#define		MASK_INT_TX_VCX_CPL		(1<<BITS_INT_TX_VCX_CPL)
+#define		BITS_INT_RX_VC0_Posted		(22)
+#define		MASK_INT_RX_VC0_Posted		(1<<BITS_INT_RX_VC0_Posted)
+#define		BITS_INT_RX_VC0_NonPosted	(21)
+#define		MASK_INT_RX_VC0_NonPosted	(1<<BITS_INT_RX_VC0_NonPosted)
+#define		BITS_INT_RX_VC0_CPL		(20)
+#define		MASK_INT_RX_VC0_CPL		(1<<BITS_INT_RX_VC0_CPL)
+#define		BITS_INT_TX_VC0_Posted		(18)
+#define		MASK_INT_TX_VC0_Posted		(1<<BITS_INT_TX_VC0_Posted)
+#define		BITS_INT_TX_VC0_NonPosted	(17)
+#define		MASK_INT_TX_VC0_NonPosted	(1<<BITS_INT_TX_VC0_NonPosted)
+#define		BITS_INT_TX_VC0_CPL		(16)
+#define		MASK_INT_TX_VC0_CPL		(1<<BITS_INT_TX_VC0_CPL)
+#define		BITS_INT_RX_CTRL		(15)
+#define		MASK_INT_RX_CTRL		(1<<BITS_INT_RX_CTRL)
+#define		BITS_INT_TX_CTRL		(14)
+#define		MASK_INT_TX_CTRL		(1<<BITS_INT_TX_CTRL)
+#define		BITS_INTTL			(11)
+#define		MASK_INTTL			(1<<BITS_INTTL)
+#define		BITS_INTDL			(10)
+#define		MASK_INTDL			(1<<BITS_INTDL)
+#define		BITS_INTMAC			(9)
+#define		MASK_INTMAC			(1<<BITS_INTMAC)
+#define		BITS_INTPM			(8)
+#define		MASK_INTPM			(1<<BITS_INTPM)
+
+/*	PCIEINTER	*/
+#define	SH4A_PCIEINTER		(0x02000C)	/* R/W R/W 0x0000 0000 32 */
+#define		BITS_INT_RX_ERP			(31)
+#define		MASK_INT_RX_ERP			(1<<BITS_INT_RX_ERP)
+#define		BITS_INT_RX_VCX_Posted		(30)
+#define		MASK_INT_RX_VCX_Posted		(1<<BITS_INT_RX_VCX_Posted)
+#define		BITS_INT_RX_VCX_NonPosted	(29)
+#define		MASK_INT_RX_VCX_NonPosted	(1<<BITS_INT_RX_VCX_NonPosted)
+#define		BITS_INT_RX_VCX_CPL		(28)
+#define		MASK_INT_RX_VCX_CPL		(1<<BITS_INT_RX_VCX_CPL)
+#define		BITS_INT_TX_VCX_Posted		(26)
+#define		MASK_INT_TX_VCX_Posted		(1<<BITS_INT_TX_VCX_Posted)
+#define		BITS_INT_TX_VCX_NonPosted	(25)
+#define		MASK_INT_TX_VCX_NonPosted	(1<<BITS_INT_TX_VCX_NonPosted)
+#define		BITS_INT_TX_VCX_CPL		(24)
+#define		MASK_INT_TX_VCX_CPL		(1<<BITS_INT_TX_VCX_CPL)
+#define		BITS_INT_RX_VC0_Posted		(22)
+#define		MASK_INT_RX_VC0_Posted		(1<<BITS_INT_RX_VC0_Posted)
+#define		BITS_INT_RX_VC0_NonPosted	(21)
+#define		MASK_INT_RX_VC0_NonPosted	(1<<BITS_INT_RX_VC0_NonPosted)
+#define		BITS_INT_RX_VC0_CPL		(20)
+#define		MASK_INT_RX_VC0_CPL		(1<<BITS_INT_RX_VC0_CPL)
+#define		BITS_INT_TX_VC0_Posted		(18)
+#define		MASK_INT_TX_VC0_Posted		(1<<BITS_INT_TX_VC0_Posted)
+#define		BITS_INT_TX_VC0_NonPosted	(17)
+#define		MASK_INT_TX_VC0_NonPosted	(1<<BITS_INT_TX_VC0_NonPosted)
+#define		BITS_INT_TX_VC0_CPL		(16)
+#define		MASK_INT_TX_VC0_CPL		(1<<BITS_INT_TX_VC0_CPL)
+#define		BITS_INT_RX_CTRL		(15)
+#define		MASK_INT_RX_CTRL		(1<<BITS_INT_RX_CTRL)
+#define		BITS_INT_TX_CTRL		(14)
+#define		MASK_INT_TX_CTRL		(1<<BITS_INT_TX_CTRL)
+#define		BITS_INTTL			(11)
+#define		MASK_INTTL			(1<<BITS_INTTL)
+#define		BITS_INTDL			(10)
+#define		MASK_INTDL			(1<<BITS_INTDL)
+#define		BITS_INTMAC			(9)
+#define		MASK_INTMAC			(1<<BITS_INTMAC)
+#define		BITS_INTPM			(8)
+#define		MASK_INTPM			(1<<BITS_INTPM)
+
+/*	PCIEAIR	 */
+#define	SH4A_PCIEAIR		(SH4A_PCIE_BASE + 0x020010)	/* R/W R/W 0xxxxx xxxx 32 */
+
+/*	 PCIECIR	 */
+#define	SH4A_PCIECIR		(SH4A_PCIE_BASE)	/* R/W R/W 0xxxxx xxxx 32 */
+
+/*	 PCIEERRFR	 */								// Rev1.18
+#define	SH4A_PCIEERRFR		(0x020020)		/* R/W R/W 0xxxxx xxxx 32 */	// Rev1.18
+											// Rev1.18
+/*	PCIELAR0	*/
+#define	SH4A_PCIELAR0		(0x020200)	/* R/W R/W 0x0000 0000 32 */
+#define		BITS_LARn	(20)
+#define		MASK_LARn	(0xfff<<BITS_LARn)
+
+#define	SH4A_PCIE_020204	(0x020204)	/* R/W R/W 0x0000 0000 32 */
+
+/*	PCIELAMR0	*/
+#define	SH4A_PCIELAMR0		(0x020208)	/* R/W R/W 0x0000 0000 32 */
+#define		BITS_LAMRn	(20)
+#define		MASK_LAMRn	(0x1ff<<BITS_LAMRn)
+#define		BITS_LAREn	(0)
+#define		MASK_LAREn	(0x1<<BITS_LAREn)
+
+/*	PCIECSCR0	*/
+#define	SH4A_PCIECSCR0		(0x020210)	/* R/W R/W 0x0000 0000 32 */
+#define		BITS_RANGE	(2)
+#define		MASK_RANGE	(0x7<<BITS_RANGE)
+#define		BITS_SNPMD	(0)
+#define		MASK_SNPMD	(0x3<<BITS_SNPMD)
+
+/*	PCIECSAR0	*/
+#define	SH4A_PCIECSAR0		(0x020214)	/* R/W R/W 0x0000 0000 32 */
+#define		BITS_CSADR	(0)
+#define		MASK_CSADR	(0xffffffff<<BITS_CSADR)
+
+/*	PCIESTCTLR0	*/
+#define	SH4A_PCIESTCTLR0	(0x020218)	/* R/W R/W 0x0000 0000 32 */
+#define		BITS_SHPRI	(8)
+#define		MASK_SHPRI	(0x0f<<BITS_SHPRI)
+
+#define	SH4A_PCIE_020224	(0x020224)	/* R/W R/W 0x0000 0000 32 */
+
+#define	SH4A_PCIELAR1		(0x020220)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIELAMR1		(0x020228)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIECSCR1		(0x020230)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIECSAR1		(0x020234)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIESTCTLR1	(0x020238)	/* R/W R/W 0x0000 0000 32 */
+
+#define	SH4A_PCIELAR2		(0x020240)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIE_020244	(0x020244)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIELAMR2		(0x020248)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIECSCR2		(0x020250)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIECSAR2		(0x020254)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIESTCTLR2	(0x020258)	/* R/W R/W 0x0000 0000 32 */
+
+#define	SH4A_PCIELAR3		(0x020260)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIE_020264	(0x020264)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIELAMR3		(0x020268)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIECSCR3		(0x020270)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIECSAR3		(0x020274)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIESTCTLR3	(0x020278)	/* R/W R/W 0x0000 0000 32 */
+
+#define	SH4A_PCIELAR4		(0x020280)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIE_020284	(0x020284)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIELAMR4		(0x020288)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIECSCR4		(0x020290)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIECSAR4		(0x020294)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIESTCTLR4	(0x020298)	/* R/W R/W 0x0000 0000 32 */
+
+#define	SH4A_PCIELAR5		(0x0202A0)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIE_0202A4	(0x0202A4)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIELAMR5		(0x0202A8)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIECSCR5		(0x0202B0)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIECSAR5		(0x0202B4)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIESTCTLR5	(0x0202B8)	/* R/W R/W 0x0000 0000 32 */
+
+/*	PCIEPARL0	*/
+#define	SH4A_PCIEPARL0		(0x020400)	/* R/W R/W 0x0000 0000 32 */
+#define		BITS_PAL	(18)
+#define		MASK_PAL	(0x3fff<<BITS_PAL)
+
+/*	PCIEPARH0	*/
+#define	SH4A_PCIEPARH0		(0x020404)	/* R/W R/W 0x0000 0000 32 */
+#define		BITS_PAH	(0)
+#define		MASK_PAH	(0xffffffff<<BITS_PAH)
+
+/*	PCIEPAMR0	 */
+#define	SH4A_PCIEPAMR0		(0x020408)	/* R/W R/W 0x0000 0000 32 */
+#define		BITS_PAM	(18)
+#define		MASK_PAM	(0x3fff<<BITS_PAM)
+
+/*	PCIEPTCTLR0	*/
+#define	SH4A_PCIEPTCTLR0	(0x02040C)	/* R/W R/W 0x0000 0000 32 */
+#define		BITS_PARE	(31)
+#define		MASK_PARE	(0x1<<BITS_PARE)
+#define		BITS_TC		(20)
+#define		MASK_TC		(0x7<<BITS_TC)
+#define		BITS_T_VC	(16)
+#define		MASK_T_VC	(0x1<<BITS_T_VC)
+#define		BITS_LOCK	(12)
+#define		MASK_LOCK	(0x1<<BITS_LOCK)
+#define		BITS_SPC	(8)
+#define		MASK_SPC	(0x1<<BITS_SPC)
+
+#define	SH4A_PCIEPARL1		(0x020420)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPARH1		(0x020424)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPAMR1		(0x020428)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPTCTLR1	(0x02042C)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPARL2		(0x020440)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPARH2		(0x020444)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPAMR2		(0x020448)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPTCTLR2	(0x02044C)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPARL3		(0x020460)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPARH3		(0x020464)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPAMR3		(0x020468)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPTCTLR3	(0x02046C)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPARL4		(0x020480)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPARH4		(0x020484)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPAMR4		(0x020488)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPTCTLR4	(0x02048C)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPARL5		(0x0204A0)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPARH5		(0x0204A4)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPAMR5		(0x0204A8)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPTCTLR5	(0x0204AC)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMAOR		(0x021000)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSAR0		(0x021100)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSAHR0	(0x021104)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMDAR0		(0x021108)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMDAHR0	(0x02110C)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMBCNTR0	(0x021110)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSBCNTR0	(0x021114)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSTRR0	(0x021118)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCCAR0	(0x02111C)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCCR0		(0x021120)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCC2R0	(0x021124)	/* R/W R/W 0x0000 0000 - */
+#define	SH4A_PCIEDMCCCR0	(0x021128)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSAR1		(0x021140)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSAHR1	(0x021144)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMDAR1		(0x021148)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMDAHR1	(0x02114C)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMBCNTR1	(0x021150)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSBCNTR1	(0x021154)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSTRR1	(0x021158)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCCAR1	(0x02115C)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCCR1		(0x021160)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCC2R1	(0x021164)	/* R/W R/W 0x0000 0000 - */
+#define	SH4A_PCIEDMCCCR1	(0x021168)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSAR2		(0x021180)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSAHR2	(0x021184)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMDAR2		(0x021188)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMDAHR2	(0x02118C)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMBCNTR2	(0x021190)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSBCNTR2	(0x021194)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSTRR2	(0x021198)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCCAR2	(0x02119C)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCCR2		(0x0211A0)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCC2R2	(0x0211A4)	/* R/W R/W 0x0000 0000 -  */
+#define	SH4A_PCIEDMCCCR2	(0x0211A8)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSAR3		(0x0211C0)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSAHR3	(0x0211C4)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMDAR3		(0x0211C8)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMDAHR3	(0x0211CC)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMBCNTR3	(0x0211D0)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSBCNTR3	(0x0211D4)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMSTRR3	(0x0211D8)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCCAR3	(0x0211DC)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCCR3		(0x0211E0)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEDMCC2R3	(0x0211E4)	/* R/W R/W 0x0000 0000 -  */
+#define	SH4A_PCIEDMCCCR3	(0x0211E8)	/* R/W R/W 0x0000 0000 32 */
+#define	SH4A_PCIEPCICONF0	(0x040000)	/* R R - 8/16/32 */
+#define	SH4A_PCIEPCICONF1	(0x040004)	/* R/W R/W 0x0008 0000 8/16/32 */
+#define	SH4A_PCIEPCICONF2	(0x040008)	/* R/W R/W 0xFF00 0000 8/16/32 */
+#define	SH4A_PCIEPCICONF3	(0x04000C)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEPCICONF4	(0x040010)	/* - R/W - 8/16/32 */
+#define	SH4A_PCIEPCICONF5	(0x040014)	/* - R/W - 8/16/32 */
+#define	SH4A_PCIEPCICONF6	(0x040018)	/* - R/W - 8/16/32 */
+#define	SH4A_PCIEPCICONF7	(0x04001C)	/* - R/W - 8/16/32 */
+#define	SH4A_PCIEPCICONF8	(0x040020)	/* - R/W - 8/16/32 */
+#define	SH4A_PCIEPCICONF9	(0x040024)	/* - R/W - 8/16/32 */
+#define	SH4A_PCIEPCICONF10	(0x040028)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEPCICONF11	(0x04002C)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEPCICONF12	(0x040030)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEPCICONF13	(0x040034)	/* R/W R/W 0x0000 0040 8/16/32 */
+#define	SH4A_PCIEPCICONF14	(0x040038)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEPCICONF15	(0x04003C)	/* R/W R/W 0x0000 00FF 8/16/32 */
+#define	SH4A_PCIEPMCAP0		(0x040040)	/* R/W R 0x0003 5001 8/16/32 */
+#define	SH4A_PCIEPMCAP1		(0x040044)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEMSICAP0	(0x040050)	/* R/W R/W 0x0180 7005 8/16/32 */
+#define	SH4A_PCIEMSICAP1	(0x040054)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEMSICAP2	(0x040058)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEMSICAP3	(0x04005C)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEMSICAP4	(0x040060)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEMSICAP5	(0x040064)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEEXPCAP0	(0x040070)	/* R/W R/W 0x0001 0010 8/16/32 */
+#define	SH4A_PCIEEXPCAP1	(0x040074)	/* R/W R 0x0000 0005 8/16/32 */
+#define	SH4A_PCIEEXPCAP2	(0x040078)	/* R/W R/W 0x0000 0801 8/16/32 */
+#define	SH4A_PCIEEXPCAP3	(0x04007C)	/* R/W R 0x0003 F421 8/16/32 */
+#define	SH4A_PCIEEXPCAP4	(0x040080)	/* R/W R/W 0x0041 0000 8/16/32 */
+#define	SH4A_PCIEEXPCAP5	(0x040084)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEEXPCAP6	(0x040088)	/* R/W R/W 0x0000 03C0 8/16/32 */
+#define	SH4A_PCIEEXPCAP7	(0x04008C)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEEXPCAP8	(0x040090)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEVCCAP0		(0x040100)	/* R/W R 0x1B01 0002 8/16/32 */
+#define	SH4A_PCIEVCCAP1		(0x040104)	/* R R 0x0000 0001 8/16/32 */
+#define	SH4A_PCIEVCCAP2		(0x040108)	/* R R 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEVCCAP3		(0x04010C)	/* R R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEVCCAP4		(0x040110)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEVCCAP5		(0x040114)	/* R/W R/W 0x8000 00FF 8/16/32 */
+#define	SH4A_PCIEVCCAP6		(0x040118)	/* R/W R 0x0002 0000 8/16/32 */
+#define	SH4A_PCIEVCCAP7		(0x04011C)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEVCCAP8		(0x040120)	/* R/W R/W 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEVCCAP9		(0x040124)	/* R/W R 0x0002 0000 8/16/32 */
+#define	SH4A_PCIENUMCAP0	(0x0001B0)	/* RW R 0x0001 0003 8/16/32 */
+#define	SH4A_PCIENUMCAP1	(0x0001B4)	/* R R 0x0000 0000 8/16/32 */
+#define	SH4A_PCIENUMCAP2	(0x0001B8)	/* R R 0x0000 0000 8/16/32 */
+#define	SH4A_PCIEIDSETR0	(0x041000)	/* R/W R 0x0000 FFFF 16/32 */
+#define	SH4A_PCIEIDSETR1	(0x041004)	/* R/W R 0xFF00 0000 16/32 */
+#define	SH4A_PCIEBAR0SETR	(0x041008)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEBAR1SETR	(0x04100C)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEBAR2SETR	(0x041010)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEBAR3SETR	(0x041014)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEBAR4SETR	(0x041018)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEBAR5SETR	(0x04101C)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIECISSETR	(0x041020)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEIDSETR2	(0x041024)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEEROMSETR	(0x041028)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEDSERSETR0	(0x04102C)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEDSERSETR1	(0x041030)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIECTLR		(0x041040)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIETLSR		(0x041044)	/* R/W1C R 0x0000 0000 16/32 */
+#define	SH4A_PCIETLCTLR		(0x041048)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEDLSR		(0x04104C)	/* R/W1C R 0x4003 0000 16/32 */
+#define	SH4A_PCIEDLCTLR		(0x041050)	/* R R 0x0000 0000 16/32 */
+#define	SH4A_PCIEMACSR		(0x041054)	/* R/W1C R 0x0041 0000 16/32 */
+#define	SH4A_PCIEMACCTLR	(0x041058)	/* R/W R 0x0000 0000 16/32 */
+#define		PCIEMACCTLR_SCR_DIS	(1 << 27)	/* scramble disable */
+#define	SH4A_PCIEPMSTR		(0x04105C)	/* R/W1C R 0x0000 0000 16/32 */
+#define	SH4A_PCIEPMCTLR		(0x041060)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIETLINTENR	(0x041064)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEDLINTENR	(0x041068)	/* R/W R 0x0000 0000 16/32 */
+#define		PCIEDLINTENR_DLL_ACT_ENABLE	(1 << 31) /* DL active irq */
+#define	SH4A_PCIEMACINTENR	(0x04106C)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIEPMINTENR	(0x041070)	/* R/W R 0x0000 0000 16/32 */
+#define	SH4A_PCIETXDCTLR	(0x044000)	/* R/W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIETXCTLR		(0x044020)	/* R/W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIETXSR		(0x044028)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIETXVC0DCTLR	(0x044100)	/* R/W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIETXVC0SR	(0x044108)	/* R/W - H'00888000_00000000 32/64 */
+#define	SH4A_PCIEVC0PDTXR	(0x044110)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0PHTXR	(0x044118)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0NPDTXR	(0x044120)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0NPHTXR	(0x044128)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0CDTXR	(0x044130)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0CHTXR	(0x044138)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIETXVCXDCTLR	(0x044200)	/* R/W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIETXVCXSR	(0x044208)	/* R/W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXPDTXR	(0x044210)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXPHTXR	(0x044218)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXNPDTXR	(0x044220)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXNPHTXR	(0x044228)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXCDTXR	(0x044230)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXCHTXR	(0x044238)	/* W - H'00000000_00000000 32/64 */
+#define	SH4A_PCIERDCTLR		(0x046000)	/* RW - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEERPCTLR	(0x046008)	/* RW - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEERPHR		(0x046010)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEERPERR		(0x046018)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIERXVC0DCTLR	(0x046100)	/* RW - H'00000000_00000000 32/64 */
+#define	SH4A_PCIERXVC0SR	(0x046108)	/* RW - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0PDRXR	(0x046140)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0PHRXR	(0x046148)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0PERR	(0x046150)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0NPDRXR	(0x046158)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0NPHRXR	(0x046160)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0NPERR	(0x046168)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0CDRXR	(0x046170)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0CHRXR	(0x046178)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVC0CERR	(0x046180)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIERXVCXDCTLR	(0x046200)	/* RW - H'00000000_00000000 32/64 */
+#define	SH4A_PCIERXVCXSR	(0x046208)	/* RW - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXPDRXR	(0x046240)	/* R - H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXPHRXR	(0x046248)	/* R H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXPERR	(0x046250)	/* R H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXNPDRXR	(0x046258)	/* R H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXNPHRXR	(0x046260)	/* R H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXNPERR	(0x046268)	/* R H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXCDRXR	(0x046270)	/* R H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXCHRXR	(0x046278)	/* R H'00000000_00000000 32/64 */
+#define	SH4A_PCIEVCXCERR	(0x046280)	/* R H'00000000_00000000 32/64 */
+
+/* SSI Register Definition for MSI WORK AROUND --hamada */
+#define SH4A_PCI_SSI_BASE	0xFFE00000	/* spw config address	*/
+#define SH4A_PCI_SSI_BASE_LEN	0x00100000	/* 1MB			*/
+
+#define	SH4A_SSICR0		(0x000000)
+#define	SH4A_SSICR1		(0x010000)
+#define	SH4A_SSICR2		(0x020000)
+#define	SH4A_SSICR3		(0x030000)
+
+#define PCI_REG(x)		((x) + 0x40000)
+
+static inline void
+pci_write_reg(struct pci_channel *chan, unsigned long val, unsigned long reg)
+{
+	__raw_writel(val, chan->reg_base + reg);
+}
+
+static inline unsigned long
+pci_read_reg(struct pci_channel *chan, unsigned long reg)
+{
+	return __raw_readl(chan->reg_base + reg);
+}
+
+#endif /* __PCI_SH7786_H */
diff --git a/arch/sh/include/asm/atomic-irq.h b/arch/sh/include/asm/atomic-irq.h
index a0b3480..467d941 100644
--- a/arch/sh/include/asm/atomic-irq.h
+++ b/arch/sh/include/asm/atomic-irq.h
@@ -10,29 +10,29 @@
 {
 	unsigned long flags;
 
-	local_irq_save(flags);
+	raw_local_irq_save(flags);
 	v->counter += i;
-	local_irq_restore(flags);
+	raw_local_irq_restore(flags);
 }
 
 static inline void atomic_sub(int i, atomic_t *v)
 {
 	unsigned long flags;
 
-	local_irq_save(flags);
+	raw_local_irq_save(flags);
 	v->counter -= i;
-	local_irq_restore(flags);
+	raw_local_irq_restore(flags);
 }
 
 static inline int atomic_add_return(int i, atomic_t *v)
 {
 	unsigned long temp, flags;
 
-	local_irq_save(flags);
+	raw_local_irq_save(flags);
 	temp = v->counter;
 	temp += i;
 	v->counter = temp;
-	local_irq_restore(flags);
+	raw_local_irq_restore(flags);
 
 	return temp;
 }
@@ -41,11 +41,11 @@
 {
 	unsigned long temp, flags;
 
-	local_irq_save(flags);
+	raw_local_irq_save(flags);
 	temp = v->counter;
 	temp -= i;
 	v->counter = temp;
-	local_irq_restore(flags);
+	raw_local_irq_restore(flags);
 
 	return temp;
 }
@@ -54,18 +54,18 @@
 {
 	unsigned long flags;
 
-	local_irq_save(flags);
+	raw_local_irq_save(flags);
 	v->counter &= ~mask;
-	local_irq_restore(flags);
+	raw_local_irq_restore(flags);
 }
 
 static inline void atomic_set_mask(unsigned int mask, atomic_t *v)
 {
 	unsigned long flags;
 
-	local_irq_save(flags);
+	raw_local_irq_save(flags);
 	v->counter |= mask;
-	local_irq_restore(flags);
+	raw_local_irq_restore(flags);
 }
 
 #endif /* __ASM_SH_ATOMIC_IRQ_H */
diff --git a/arch/sh/include/asm/atomic.h b/arch/sh/include/asm/atomic.h
index 157c320..e8e7813 100644
--- a/arch/sh/include/asm/atomic.h
+++ b/arch/sh/include/asm/atomic.h
@@ -85,4 +85,6 @@
 #define smp_mb__after_atomic_inc()	barrier()
 
 #include <asm-generic/atomic-long.h>
+#include <asm-generic/atomic64.h>
+
 #endif /* __ASM_SH_ATOMIC_H */
diff --git a/arch/sh/include/asm/checksum.h b/arch/sh/include/asm/checksum.h
index 67496ab..fc26d1f 100644
--- a/arch/sh/include/asm/checksum.h
+++ b/arch/sh/include/asm/checksum.h
@@ -1,5 +1,5 @@
 #ifdef CONFIG_SUPERH32
 # include "checksum_32.h"
 #else
-# include "checksum_64.h"
+# include <asm-generic/checksum.h>
 #endif
diff --git a/arch/sh/include/asm/checksum_64.h b/arch/sh/include/asm/checksum_64.h
deleted file mode 100644
index 9c62a03..0000000
--- a/arch/sh/include/asm/checksum_64.h
+++ /dev/null
@@ -1,78 +0,0 @@
-#ifndef __ASM_SH_CHECKSUM_64_H
-#define __ASM_SH_CHECKSUM_64_H
-
-/*
- * include/asm-sh/checksum_64.h
- *
- * Copyright (C) 2000, 2001  Paolo Alberelli
- *
- * This file is subject to the terms and conditions of the GNU General Public
- * License.  See the file "COPYING" in the main directory of this archive
- * for more details.
- */
-
-/*
- * computes the checksum of a memory block at buff, length len,
- * and adds in "sum" (32-bit)
- *
- * returns a 32-bit number suitable for feeding into itself
- * or csum_tcpudp_magic
- *
- * this function must be called with even lengths, except
- * for the last fragment, which may be odd
- *
- * it's best to have buff aligned on a 32-bit boundary
- */
-asmlinkage __wsum csum_partial(const void *buff, int len, __wsum sum);
-
-/*
- *	Note: when you get a NULL pointer exception here this means someone
- *	passed in an incorrect kernel address to one of these functions.
- *
- *	If you use these functions directly please don't forget the
- *	access_ok().
- */
-
-
-__wsum csum_partial_copy_nocheck(const void *src, void *dst, int len,
-				       __wsum sum);
-
-__wsum csum_partial_copy_from_user(const void __user *src, void *dst,
-					 int len, __wsum sum, int *err_ptr);
-
-static inline __sum16 csum_fold(__wsum csum)
-{
-	u32 sum = (__force u32)csum;
-        sum = (sum & 0xffff) + (sum >> 16);
-        sum = (sum & 0xffff) + (sum >> 16);
-        return (__force __sum16)~sum;
-}
-
-__sum16 ip_fast_csum(const void *iph, unsigned int ihl);
-
-__wsum csum_tcpudp_nofold(__be32 saddr, __be32 daddr,
-				 unsigned short len, unsigned short proto,
-				 __wsum sum);
-
-/*
- * computes the checksum of the TCP/UDP pseudo-header
- * returns a 16-bit checksum, already complemented
- */
-static inline __sum16 csum_tcpudp_magic(__be32 saddr, __be32 daddr,
-						   unsigned short len,
-						   unsigned short proto,
-						   __wsum sum)
-{
-	return csum_fold(csum_tcpudp_nofold(saddr,daddr,len,proto,sum));
-}
-
-/*
- * this routine is used for miscellaneous IP-like checksums, mainly
- * in icmp.c
- */
-static inline __sum16 ip_compute_csum(const void *buff, int len)
-{
-	return csum_fold(csum_partial(buff, len, 0));
-}
-
-#endif /* __ASM_SH_CHECKSUM_64_H */
diff --git a/arch/sh/include/asm/current.h b/arch/sh/include/asm/current.h
index 62b6388..4c51401 100644
--- a/arch/sh/include/asm/current.h
+++ b/arch/sh/include/asm/current.h
@@ -1,20 +1 @@
-#ifndef __ASM_SH_CURRENT_H
-#define __ASM_SH_CURRENT_H
-
-/*
- * Copyright (C) 1999 Niibe Yutaka
- *
- */
-
-#include <linux/thread_info.h>
-
-struct task_struct;
-
-static __inline__ struct task_struct * get_current(void)
-{
-	return current_thread_info()->task;
-}
-
-#define current get_current()
-
-#endif /* __ASM_SH_CURRENT_H */
+#include <asm-generic/current.h>
diff --git a/arch/sh/include/asm/dma.h b/arch/sh/include/asm/dma.h
index 6bd1784..04ad0e1 100644
--- a/arch/sh/include/asm/dma.h
+++ b/arch/sh/include/asm/dma.h
@@ -16,13 +16,7 @@
 #include <linux/sched.h>
 #include <linux/sysdev.h>
 #include <cpu/dma.h>
-
-/* The maximum address that we can perform a DMA transfer to on this platform */
-/* Don't define MAX_DMA_ADDRESS; it's useless on the SuperH and any
-   occurrence should be flagged as an error.  */
-/* But... */
-/* XXX: This is not applicable to SuperH, just needed for alloc_bootmem */
-#define MAX_DMA_ADDRESS		(PAGE_OFFSET+0x10000000)
+#include <asm-generic/dma.h>
 
 #ifdef CONFIG_NR_DMA_CHANNELS
 #  define MAX_DMA_CHANNELS   (CONFIG_NR_DMA_CHANNELS)
@@ -137,8 +131,6 @@
 
 extern int request_dma_bycap(const char **dmac, const char **caps,
 			     const char *dev_id);
-extern int request_dma(unsigned int chan, const char *dev_id);
-extern void free_dma(unsigned int chan);
 extern int get_dma_residue(unsigned int chan);
 extern struct dma_info *get_dma_info(unsigned int chan);
 extern struct dma_channel *get_dma_channel(unsigned int chan);
diff --git a/arch/sh/include/asm/ipcbuf.h b/arch/sh/include/asm/ipcbuf.h
index 5ffc997..84c7e51 100644
--- a/arch/sh/include/asm/ipcbuf.h
+++ b/arch/sh/include/asm/ipcbuf.h
@@ -1,29 +1 @@
-#ifndef __ASM_SH_IPCBUF_H__
-#define __ASM_SH_IPCBUF_H__
-
-/*
- * The ipc64_perm structure for i386 architecture.
- * Note extra padding because this structure is passed back and forth
- * between kernel and user space.
- *
- * Pad space is left for:
- * - 32-bit mode_t and seq
- * - 2 miscellaneous 32-bit values
- */
-
-struct ipc64_perm
-{
-	__kernel_key_t		key;
-	__kernel_uid32_t	uid;
-	__kernel_gid32_t	gid;
-	__kernel_uid32_t	cuid;
-	__kernel_gid32_t	cgid;
-	__kernel_mode_t		mode;
-	unsigned short		__pad1;
-	unsigned short		seq;
-	unsigned short		__pad2;
-	unsigned long		__unused1;
-	unsigned long		__unused2;
-};
-
-#endif /* __ASM_SH_IPCBUF_H__ */
+#include <asm-generic/ipcbuf.h>
diff --git a/arch/sh/include/asm/irq.h b/arch/sh/include/asm/irq.h
index a2b8c99..df8e150 100644
--- a/arch/sh/include/asm/irq.h
+++ b/arch/sh/include/asm/irq.h
@@ -39,7 +39,6 @@
 	return irq;
 }
 
-#define irq_canonicalize(irq)	(irq)
 #define irq_demux(irq)		sh_mv.mv_irq_demux(irq)
 
 void init_IRQ(void);
@@ -54,6 +53,7 @@
 # define irq_ctx_exit(cpu) do { } while (0)
 #endif
 
+#include <asm-generic/irq.h>
 #ifdef CONFIG_CPU_SH5
 #include <cpu/irq.h>
 #endif
diff --git a/arch/sh/include/asm/mman.h b/arch/sh/include/asm/mman.h
index 7d8b72c..8eebf89f5 100644
--- a/arch/sh/include/asm/mman.h
+++ b/arch/sh/include/asm/mman.h
@@ -1,17 +1 @@
-#ifndef __ASM_SH_MMAN_H
-#define __ASM_SH_MMAN_H
-
-#include <asm-generic/mman-common.h>
-
-#define MAP_GROWSDOWN	0x0100		/* stack-like segment */
-#define MAP_DENYWRITE	0x0800		/* ETXTBSY */
-#define MAP_EXECUTABLE	0x1000		/* mark it as an executable */
-#define MAP_LOCKED	0x2000		/* pages are locked */
-#define MAP_NORESERVE	0x4000		/* don't check for reservations */
-#define MAP_POPULATE	0x8000		/* populate (prefault) page tables */
-#define MAP_NONBLOCK	0x10000		/* do not block on IO */
-
-#define MCL_CURRENT	1		/* lock all current mappings */
-#define MCL_FUTURE	2		/* lock all future mappings */
-
-#endif /* __ASM_SH_MMAN_H */
+#include <asm-generic/mman.h>
diff --git a/arch/sh/include/asm/mmu_context.h b/arch/sh/include/asm/mmu_context.h
index 2a9c55f..67d8946 100644
--- a/arch/sh/include/asm/mmu_context.h
+++ b/arch/sh/include/asm/mmu_context.h
@@ -122,30 +122,30 @@
 	unsigned int cpu = smp_processor_id();
 
 	if (likely(prev != next)) {
-		cpu_set(cpu, next->cpu_vm_mask);
+		cpumask_set_cpu(cpu, mm_cpumask(next));
 		set_TTB(next->pgd);
 		activate_context(next, cpu);
 	} else
-		if (!cpu_test_and_set(cpu, next->cpu_vm_mask))
+		if (!cpumask_test_and_set_cpu(cpu, mm_cpumask(next)))
 			activate_context(next, cpu);
 }
+
+#define activate_mm(prev, next)		switch_mm((prev),(next),NULL)
+#define deactivate_mm(tsk,mm)		do { } while (0)
+#define enter_lazy_tlb(mm,tsk)		do { } while (0)
+
 #else
-#define get_mmu_context(mm)		do { } while (0)
-#define init_new_context(tsk,mm)	(0)
-#define destroy_context(mm)		do { } while (0)
+
 #define set_asid(asid)			do { } while (0)
 #define get_asid()			(0)
 #define cpu_asid(cpu, mm)		({ (void)cpu; NO_CONTEXT; })
 #define switch_and_save_asid(asid)	(0)
 #define set_TTB(pgd)			do { } while (0)
 #define get_TTB()			(0)
-#define activate_context(mm,cpu)	do { } while (0)
-#define switch_mm(prev,next,tsk)	do { } while (0)
-#endif /* CONFIG_MMU */
 
-#define activate_mm(prev, next)		switch_mm((prev),(next),NULL)
-#define deactivate_mm(tsk,mm)		do { } while (0)
-#define enter_lazy_tlb(mm,tsk)		do { } while (0)
+#include <asm-generic/mmu_context.h>
+
+#endif /* CONFIG_MMU */
 
 #if defined(CONFIG_CPU_SH3) || defined(CONFIG_CPU_SH4)
 /*
diff --git a/arch/sh/include/asm/module.h b/arch/sh/include/asm/module.h
index 46eccd3..068bf16 100644
--- a/arch/sh/include/asm/module.h
+++ b/arch/sh/include/asm/module.h
@@ -1,17 +1,7 @@
 #ifndef _ASM_SH_MODULE_H
 #define _ASM_SH_MODULE_H
 
-/*
- * This file contains the SH architecture specific module code.
- */
-
-struct mod_arch_specific {
-	/* Nothing to see here .. */
-};
-
-#define Elf_Shdr		Elf32_Shdr
-#define Elf_Sym			Elf32_Sym
-#define Elf_Ehdr		Elf32_Ehdr
+#include <asm-generic/module.h>
 
 #ifdef CONFIG_CPU_LITTLE_ENDIAN
 # ifdef CONFIG_CPU_SH2
diff --git a/arch/sh/include/asm/msgbuf.h b/arch/sh/include/asm/msgbuf.h
index 5174323..809134c 100644
--- a/arch/sh/include/asm/msgbuf.h
+++ b/arch/sh/include/asm/msgbuf.h
@@ -1,31 +1 @@
-#ifndef __ASM_SH_MSGBUF_H
-#define __ASM_SH_MSGBUF_H
-
-/* 
- * The msqid64_ds structure for i386 architecture.
- * Note extra padding because this structure is passed back and forth
- * between kernel and user space.
- *
- * Pad space is left for:
- * - 64-bit time_t to solve y2038 problem
- * - 2 miscellaneous 32-bit values
- */
-
-struct msqid64_ds {
-	struct ipc64_perm msg_perm;
-	__kernel_time_t msg_stime;	/* last msgsnd time */
-	unsigned long	__unused1;
-	__kernel_time_t msg_rtime;	/* last msgrcv time */
-	unsigned long	__unused2;
-	__kernel_time_t msg_ctime;	/* last change time */
-	unsigned long	__unused3;
-	unsigned long  msg_cbytes;	/* current number of bytes on queue */
-	unsigned long  msg_qnum;	/* number of messages in queue */
-	unsigned long  msg_qbytes;	/* max number of bytes on queue */
-	__kernel_pid_t msg_lspid;	/* pid of last msgsnd */
-	__kernel_pid_t msg_lrpid;	/* last receive pid */
-	unsigned long  __unused4;
-	unsigned long  __unused5;
-};
-
-#endif /* __ASM_SH_MSGBUF_H */
+#include <asm-generic/msgbuf.h>
diff --git a/arch/sh/include/asm/param.h b/arch/sh/include/asm/param.h
index ae245af..965d454 100644
--- a/arch/sh/include/asm/param.h
+++ b/arch/sh/include/asm/param.h
@@ -1,22 +1 @@
-#ifndef __ASM_SH_PARAM_H
-#define __ASM_SH_PARAM_H
-
-#ifdef __KERNEL__
-# define HZ		CONFIG_HZ
-# define USER_HZ	100		/* User interfaces are in "ticks" */
-# define CLOCKS_PER_SEC	(USER_HZ)	/* frequency at which times() counts */
-#endif
-
-#ifndef HZ
-#define HZ 100
-#endif
-
-#define EXEC_PAGESIZE	4096
-
-#ifndef NOGROUP
-#define NOGROUP		(-1)
-#endif
-
-#define MAXHOSTNAMELEN	64	/* max length of hostname */
-
-#endif /* __ASM_SH_PARAM_H */
+#include <asm-generic/param.h>
diff --git a/arch/sh/include/asm/parport.h b/arch/sh/include/asm/parport.h
index f67ba60..cf252af 100644
--- a/arch/sh/include/asm/parport.h
+++ b/arch/sh/include/asm/parport.h
@@ -1,16 +1 @@
-/*
- * Copyright (C) 1999, 2000  Tim Waugh <tim@cyberelk.demon.co.uk>
- *
- * This file should only be included by drivers/parport/parport_pc.c.
- */
-#ifndef __ASM_SH_PARPORT_H
-#define __ASM_SH_PARPORT_H
-
-static int __devinit parport_pc_find_isa_ports(int autoirq, int autodma);
-
-static int __devinit parport_pc_find_nonpci_ports(int autoirq, int autodma)
-{
-	return parport_pc_find_isa_ports(autoirq, autodma);
-}
-
-#endif /* __ASM_SH_PARPORT_H */
+#include <asm-generic/parport.h>
diff --git a/arch/sh/include/asm/pci.h b/arch/sh/include/asm/pci.h
index ae0da6f..d3633f5 100644
--- a/arch/sh/include/asm/pci.h
+++ b/arch/sh/include/asm/pci.h
@@ -137,19 +137,6 @@
 extern void pcibios_bus_to_resource(struct pci_dev *dev, struct resource *res,
 				    struct pci_bus_region *region);
 
-static inline struct resource *
-pcibios_select_root(struct pci_dev *pdev, struct resource *res)
-{
-	struct resource *root = NULL;
-
-	if (res->flags & IORESOURCE_IO)
-		root = &ioport_resource;
-	if (res->flags & IORESOURCE_MEM)
-		root = &iomem_resource;
-
-	return root;
-}
-
 /* Chances are this interrupt is wired PC-style ...  */
 static inline int pci_get_legacy_ide_irq(struct pci_dev *dev, int channel)
 {
diff --git a/arch/sh/include/asm/perf_counter.h b/arch/sh/include/asm/perf_counter.h
new file mode 100644
index 0000000..a8153c2
--- /dev/null
+++ b/arch/sh/include/asm/perf_counter.h
@@ -0,0 +1,7 @@
+#ifndef __ASM_SH_PERF_COUNTER_H
+#define __ASM_SH_PERF_COUNTER_H
+
+/* SH only supports software counters through this interface. */
+#define set_perf_counter_pending()	do { } while (0)
+
+#endif /* __ASM_SH_PERF_COUNTER_H */
diff --git a/arch/sh/include/asm/posix_types_32.h b/arch/sh/include/asm/posix_types_32.h
index 2172732..6a9ceaa 100644
--- a/arch/sh/include/asm/posix_types_32.h
+++ b/arch/sh/include/asm/posix_types_32.h
@@ -1,118 +1,29 @@
-#ifndef __ASM_SH_POSIX_TYPES_H
-#define __ASM_SH_POSIX_TYPES_H
+#ifndef __ASM_SH_POSIX_TYPES_32_H
+#define __ASM_SH_POSIX_TYPES_32_H
 
-/*
- * This file is generally used by user-level software, so you need to
- * be a little careful about namespace pollution etc.  Also, we cannot
- * assume GCC is being used.
- */
-
-typedef unsigned long	__kernel_ino_t;
 typedef unsigned short	__kernel_mode_t;
+#define __kernel_mode_t __kernel_mode_t
 typedef unsigned short	__kernel_nlink_t;
-typedef long		__kernel_off_t;
-typedef int		__kernel_pid_t;
+#define __kernel_nlink_t __kernel_nlink_t
 typedef unsigned short	__kernel_ipc_pid_t;
+#define __kernel_ipc_pid_t __kernel_ipc_pid_t
 typedef unsigned short	__kernel_uid_t;
+#define __kernel_uid_t __kernel_uid_t
 typedef unsigned short	__kernel_gid_t;
-typedef unsigned int	__kernel_size_t;
-typedef int		__kernel_ssize_t;
-typedef int		__kernel_ptrdiff_t;
-typedef long		__kernel_time_t;
-typedef long		__kernel_suseconds_t;
-typedef long		__kernel_clock_t;
-typedef int		__kernel_timer_t;
-typedef int		__kernel_clockid_t;
-typedef int		__kernel_daddr_t;
-typedef char *		__kernel_caddr_t;
-typedef unsigned short	__kernel_uid16_t;
-typedef unsigned short	__kernel_gid16_t;
+#define __kernel_gid_t __kernel_gid_t
+
 typedef unsigned int	__kernel_uid32_t;
+#define __kernel_uid32_t __kernel_uid32_t
 typedef unsigned int	__kernel_gid32_t;
+#define __kernel_gid32_t __kernel_gid32_t
 
 typedef unsigned short	__kernel_old_uid_t;
+#define __kernel_old_uid_t __kernel_old_uid_t
 typedef unsigned short	__kernel_old_gid_t;
+#define __kernel_old_gid_t __kernel_old_gid_t
 typedef unsigned short	__kernel_old_dev_t;
+#define __kernel_old_dev_t __kernel_old_dev_t
 
-#ifdef __GNUC__
-typedef long long	__kernel_loff_t;
-#endif
+#include <asm-generic/posix_types.h>
 
-typedef struct {
-	int	val[2];
-} __kernel_fsid_t;
-
-#if defined(__KERNEL__)
-
-#undef	__FD_SET
-static __inline__ void __FD_SET(unsigned long __fd, __kernel_fd_set *__fdsetp)
-{
-	unsigned long __tmp = __fd / __NFDBITS;
-	unsigned long __rem = __fd % __NFDBITS;
-	__fdsetp->fds_bits[__tmp] |= (1UL<<__rem);
-}
-
-#undef	__FD_CLR
-static __inline__ void __FD_CLR(unsigned long __fd, __kernel_fd_set *__fdsetp)
-{
-	unsigned long __tmp = __fd / __NFDBITS;
-	unsigned long __rem = __fd % __NFDBITS;
-	__fdsetp->fds_bits[__tmp] &= ~(1UL<<__rem);
-}
-
-
-#undef	__FD_ISSET
-static __inline__ int __FD_ISSET(unsigned long __fd, const __kernel_fd_set *__p)
-{ 
-	unsigned long __tmp = __fd / __NFDBITS;
-	unsigned long __rem = __fd % __NFDBITS;
-	return (__p->fds_bits[__tmp] & (1UL<<__rem)) != 0;
-}
-
-/*
- * This will unroll the loop for the normal constant case (8 ints,
- * for a 256-bit fd_set)
- */
-#undef	__FD_ZERO
-static __inline__ void __FD_ZERO(__kernel_fd_set *__p)
-{
-	unsigned long *__tmp = __p->fds_bits;
-	int __i;
-
-	if (__builtin_constant_p(__FDSET_LONGS)) {
-		switch (__FDSET_LONGS) {
-		case 16:
-			__tmp[ 0] = 0; __tmp[ 1] = 0;
-			__tmp[ 2] = 0; __tmp[ 3] = 0;
-			__tmp[ 4] = 0; __tmp[ 5] = 0;
-			__tmp[ 6] = 0; __tmp[ 7] = 0;
-			__tmp[ 8] = 0; __tmp[ 9] = 0;
-			__tmp[10] = 0; __tmp[11] = 0;
-			__tmp[12] = 0; __tmp[13] = 0;
-			__tmp[14] = 0; __tmp[15] = 0;
-			return;
-
-		case 8:
-			__tmp[ 0] = 0; __tmp[ 1] = 0;
-			__tmp[ 2] = 0; __tmp[ 3] = 0;
-			__tmp[ 4] = 0; __tmp[ 5] = 0;
-			__tmp[ 6] = 0; __tmp[ 7] = 0;
-			return;
-
-		case 4:
-			__tmp[ 0] = 0; __tmp[ 1] = 0;
-			__tmp[ 2] = 0; __tmp[ 3] = 0;
-			return;
-		}
-	}
-	__i = __FDSET_LONGS;
-	while (__i) {
-		__i--;
-		*__tmp = 0;
-		__tmp++;
-	}
-}
-
-#endif /* defined(__KERNEL__) */
-
-#endif /* __ASM_SH_POSIX_TYPES_H */
+#endif /* __ASM_SH_POSIX_TYPES_32_H */
diff --git a/arch/sh/include/asm/posix_types_64.h b/arch/sh/include/asm/posix_types_64.h
index f83e9bd..8cd1148 100644
--- a/arch/sh/include/asm/posix_types_64.h
+++ b/arch/sh/include/asm/posix_types_64.h
@@ -1,127 +1,34 @@
-#ifndef __ASM_SH64_POSIX_TYPES_H
-#define __ASM_SH64_POSIX_TYPES_H
+#ifndef __ASM_SH_POSIX_TYPES_64_H
+#define __ASM_SH_POSIX_TYPES_64_H
 
-/*
- * This file is subject to the terms and conditions of the GNU General Public
- * License.  See the file "COPYING" in the main directory of this archive
- * for more details.
- *
- * include/asm-sh64/posix_types.h
- *
- * Copyright (C) 2000, 2001  Paolo Alberelli
- * Copyright (C) 2003  Paul Mundt
- *
- * This file is generally used by user-level software, so you need to
- * be a little careful about namespace pollution etc.  Also, we cannot
- * assume GCC is being used.
- */
-
-typedef unsigned long	__kernel_ino_t;
 typedef unsigned short	__kernel_mode_t;
+#define __kernel_mode_t __kernel_mode_t
 typedef unsigned short	__kernel_nlink_t;
-typedef long		__kernel_off_t;
-typedef int		__kernel_pid_t;
+#define __kernel_nlink_t __kernel_nlink_t
 typedef unsigned short	__kernel_ipc_pid_t;
+#define __kernel_ipc_pid_t __kernel_ipc_pid_t
 typedef unsigned short	__kernel_uid_t;
+#define __kernel_uid_t __kernel_uid_t
 typedef unsigned short	__kernel_gid_t;
+#define __kernel_gid_t __kernel_gid_t
 typedef long unsigned int	__kernel_size_t;
+#define __kernel_size_t __kernel_size_t
 typedef int		__kernel_ssize_t;
+#define __kernel_ssize_t __kernel_ssize_t
 typedef int		__kernel_ptrdiff_t;
-typedef long		__kernel_time_t;
-typedef long		__kernel_suseconds_t;
-typedef long		__kernel_clock_t;
-typedef int		__kernel_timer_t;
-typedef int		__kernel_clockid_t;
-typedef int		__kernel_daddr_t;
-typedef char *		__kernel_caddr_t;
-typedef unsigned short	__kernel_uid16_t;
-typedef unsigned short	__kernel_gid16_t;
+#define __kernel_ptrdiff_t __kernel_ptrdiff_t
 typedef unsigned int	__kernel_uid32_t;
+#define __kernel_uid32_t __kernel_uid32_t
 typedef unsigned int	__kernel_gid32_t;
+#define __kernel_gid32_t __kernel_gid32_t
 
 typedef unsigned short	__kernel_old_uid_t;
+#define __kernel_old_uid_t __kernel_old_uid_t
 typedef unsigned short	__kernel_old_gid_t;
+#define __kernel_old_gid_t __kernel_old_gid_t
 typedef unsigned short	__kernel_old_dev_t;
+#define __kernel_old_dev_t __kernel_old_dev_t
 
-#ifdef __GNUC__
-typedef long long	__kernel_loff_t;
-#endif
+#include <asm-generic/posix_types.h>
 
-typedef struct {
-	int	val[2];
-} __kernel_fsid_t;
-
-#if defined(__KERNEL__)
-
-#undef	__FD_SET
-static __inline__ void __FD_SET(unsigned long __fd, __kernel_fd_set *__fdsetp)
-{
-	unsigned long __tmp = __fd / __NFDBITS;
-	unsigned long __rem = __fd % __NFDBITS;
-	__fdsetp->fds_bits[__tmp] |= (1UL<<__rem);
-}
-
-#undef	__FD_CLR
-static __inline__ void __FD_CLR(unsigned long __fd, __kernel_fd_set *__fdsetp)
-{
-	unsigned long __tmp = __fd / __NFDBITS;
-	unsigned long __rem = __fd % __NFDBITS;
-	__fdsetp->fds_bits[__tmp] &= ~(1UL<<__rem);
-}
-
-
-#undef	__FD_ISSET
-static __inline__ int __FD_ISSET(unsigned long __fd, const __kernel_fd_set *__p)
-{
-	unsigned long __tmp = __fd / __NFDBITS;
-	unsigned long __rem = __fd % __NFDBITS;
-	return (__p->fds_bits[__tmp] & (1UL<<__rem)) != 0;
-}
-
-/*
- * This will unroll the loop for the normal constant case (8 ints,
- * for a 256-bit fd_set)
- */
-#undef	__FD_ZERO
-static __inline__ void __FD_ZERO(__kernel_fd_set *__p)
-{
-	unsigned long *__tmp = __p->fds_bits;
-	int __i;
-
-	if (__builtin_constant_p(__FDSET_LONGS)) {
-		switch (__FDSET_LONGS) {
-		case 16:
-			__tmp[ 0] = 0; __tmp[ 1] = 0;
-			__tmp[ 2] = 0; __tmp[ 3] = 0;
-			__tmp[ 4] = 0; __tmp[ 5] = 0;
-			__tmp[ 6] = 0; __tmp[ 7] = 0;
-			__tmp[ 8] = 0; __tmp[ 9] = 0;
-			__tmp[10] = 0; __tmp[11] = 0;
-			__tmp[12] = 0; __tmp[13] = 0;
-			__tmp[14] = 0; __tmp[15] = 0;
-			return;
-
-		case 8:
-			__tmp[ 0] = 0; __tmp[ 1] = 0;
-			__tmp[ 2] = 0; __tmp[ 3] = 0;
-			__tmp[ 4] = 0; __tmp[ 5] = 0;
-			__tmp[ 6] = 0; __tmp[ 7] = 0;
-			return;
-
-		case 4:
-			__tmp[ 0] = 0; __tmp[ 1] = 0;
-			__tmp[ 2] = 0; __tmp[ 3] = 0;
-			return;
-		}
-	}
-	__i = __FDSET_LONGS;
-	while (__i) {
-		__i--;
-		*__tmp = 0;
-		__tmp++;
-	}
-}
-
-#endif /* defined(__KERNEL__) */
-
-#endif /* __ASM_SH64_POSIX_TYPES_H */
+#endif /* __ASM_SH_POSIX_TYPES_64_H */
diff --git a/arch/sh/include/asm/scatterlist.h b/arch/sh/include/asm/scatterlist.h
index c693d26..327cc2e 100644
--- a/arch/sh/include/asm/scatterlist.h
+++ b/arch/sh/include/asm/scatterlist.h
@@ -1,28 +1,8 @@
 #ifndef __ASM_SH_SCATTERLIST_H
 #define __ASM_SH_SCATTERLIST_H
 
-#include <asm/types.h>
-
-struct scatterlist {
-#ifdef CONFIG_DEBUG_SG
-	unsigned long	sg_magic;
-#endif
-	unsigned long	page_link;
-	unsigned int	offset;		/* for highmem, page offset */
-	unsigned int	length;
-	dma_addr_t	dma_address;
-	unsigned int	dma_length;
-};
-
 #define ISA_DMA_THRESHOLD	PHYS_ADDR_MASK
 
-/* These macros should be used after a pci_map_sg call has been done
- * to get bus addresses of each of the SG entries and their lengths.
- * You should only work with the number of sg entries pci_map_sg
- * returns, or alternatively stop on the first sg_dma_len(sg) which
- * is 0.
- */
-#define sg_dma_address(sg)	((sg)->dma_address)
-#define sg_dma_len(sg)		((sg)->length)
+#include <asm-generic/scatterlist.h>
 
-#endif /* !(__ASM_SH_SCATTERLIST_H) */
+#endif /* __ASM_SH_SCATTERLIST_H */
diff --git a/arch/sh/include/asm/sembuf.h b/arch/sh/include/asm/sembuf.h
index d79f3bd..7673b83 100644
--- a/arch/sh/include/asm/sembuf.h
+++ b/arch/sh/include/asm/sembuf.h
@@ -1,25 +1 @@
-#ifndef __ASM_SH_SEMBUF_H
-#define __ASM_SH_SEMBUF_H
-
-/* 
- * The semid64_ds structure for i386 architecture.
- * Note extra padding because this structure is passed back and forth
- * between kernel and user space.
- *
- * Pad space is left for:
- * - 64-bit time_t to solve y2038 problem
- * - 2 miscellaneous 32-bit values
- */
-
-struct semid64_ds {
-	struct ipc64_perm sem_perm;		/* permissions .. see ipc.h */
-	__kernel_time_t	sem_otime;		/* last semop time */
-	unsigned long	__unused1;
-	__kernel_time_t	sem_ctime;		/* last change time */
-	unsigned long	__unused2;
-	unsigned long	sem_nsems;		/* no. of semaphores in array */
-	unsigned long	__unused3;
-	unsigned long	__unused4;
-};
-
-#endif /* __ASM_SH_SEMBUF_H */
+#include <asm-generic/sembuf.h>
diff --git a/arch/sh/include/asm/serial.h b/arch/sh/include/asm/serial.h
index 11f854d..a0cb0caf 100644
--- a/arch/sh/include/asm/serial.h
+++ b/arch/sh/include/asm/serial.h
@@ -1,19 +1 @@
-/*
- * include/asm-sh/serial.h
- *
- * Configuration details for 8250, 16450, 16550, etc. serial ports
- */
-
-#ifndef _ASM_SERIAL_H
-#define _ASM_SERIAL_H
-
-/*
- * This assumes you have a 1.8432 MHz clock for your UART.
- *
- * It'd be nice if someone built a serial card with a 24.576 MHz
- * clock, since the 16550A is capable of handling a top speed of 1.5
- * megabits/second; but this requires the faster clock.
- */
-#define BASE_BAUD ( 1843200 / 16 )
-
-#endif /* _ASM_SERIAL_H */
+#include <asm-generic/serial.h>
diff --git a/arch/sh/include/asm/setup.h b/arch/sh/include/asm/setup.h
index d450bcf..ce37435 100644
--- a/arch/sh/include/asm/setup.h
+++ b/arch/sh/include/asm/setup.h
@@ -1,7 +1,7 @@
 #ifndef _SH_SETUP_H
 #define _SH_SETUP_H
 
-#define COMMAND_LINE_SIZE 256
+#include <asm-generic/setup.h>
 
 #ifdef __KERNEL__
 /*
diff --git a/arch/sh/include/asm/shmbuf.h b/arch/sh/include/asm/shmbuf.h
index b2101f4..83c05fc 100644
--- a/arch/sh/include/asm/shmbuf.h
+++ b/arch/sh/include/asm/shmbuf.h
@@ -1,42 +1 @@
-#ifndef __ASM_SH_SHMBUF_H
-#define __ASM_SH_SHMBUF_H
-
-/* 
- * The shmid64_ds structure for i386 architecture.
- * Note extra padding because this structure is passed back and forth
- * between kernel and user space.
- *
- * Pad space is left for:
- * - 64-bit time_t to solve y2038 problem
- * - 2 miscellaneous 32-bit values
- */
-
-struct shmid64_ds {
-	struct ipc64_perm	shm_perm;	/* operation perms */
-	size_t			shm_segsz;	/* size of segment (bytes) */
-	__kernel_time_t		shm_atime;	/* last attach time */
-	unsigned long		__unused1;
-	__kernel_time_t		shm_dtime;	/* last detach time */
-	unsigned long		__unused2;
-	__kernel_time_t		shm_ctime;	/* last change time */
-	unsigned long		__unused3;
-	__kernel_pid_t		shm_cpid;	/* pid of creator */
-	__kernel_pid_t		shm_lpid;	/* pid of last operator */
-	unsigned long		shm_nattch;	/* no. of current attaches */
-	unsigned long		__unused4;
-	unsigned long		__unused5;
-};
-
-struct shminfo64 {
-	unsigned long	shmmax;
-	unsigned long	shmmin;
-	unsigned long	shmmni;
-	unsigned long	shmseg;
-	unsigned long	shmall;
-	unsigned long	__unused1;
-	unsigned long	__unused2;
-	unsigned long	__unused3;
-	unsigned long	__unused4;
-};
-
-#endif /* __ASM_SH_SHMBUF_H */
+#include <asm-generic/shmbuf.h>
diff --git a/arch/sh/include/asm/signal.h b/arch/sh/include/asm/signal.h
index 9cc5f01..9ac530a 100644
--- a/arch/sh/include/asm/signal.h
+++ b/arch/sh/include/asm/signal.h
@@ -1,114 +1,10 @@
 #ifndef __ASM_SH_SIGNAL_H
 #define __ASM_SH_SIGNAL_H
 
-#include <linux/types.h>
-
-/* Avoid too many header ordering problems.  */
-struct pt_regs;
-struct siginfo;
-
-#ifdef __KERNEL__
-/* Most things should be clean enough to redefine this at will, if care
-   is taken to make libc match.  */
-
-#define _NSIG		64
-#define _NSIG_BPW	32
-#define _NSIG_WORDS	(_NSIG / _NSIG_BPW)
-
-typedef unsigned long old_sigset_t;		/* at least 32 bits */
-
-typedef struct {
-	unsigned long sig[_NSIG_WORDS];
-} sigset_t;
-
-#else
-/* Here we must cater to libcs that poke about in kernel headers.  */
-
-#define NSIG		32
-typedef unsigned long sigset_t;
-
-#endif /* __KERNEL__ */
-
-#define SIGHUP		 1
-#define SIGINT		 2
-#define SIGQUIT		 3
-#define SIGILL		 4
-#define SIGTRAP		 5
-#define SIGABRT		 6
-#define SIGIOT		 6
-#define SIGBUS		 7
-#define SIGFPE		 8
-#define SIGKILL		 9
-#define SIGUSR1		10
-#define SIGSEGV		11
-#define SIGUSR2		12
-#define SIGPIPE		13
-#define SIGALRM		14
-#define SIGTERM		15
-#define SIGSTKFLT	16
-#define SIGCHLD		17
-#define SIGCONT		18
-#define SIGSTOP		19
-#define SIGTSTP		20
-#define SIGTTIN		21
-#define SIGTTOU		22
-#define SIGURG		23
-#define SIGXCPU		24
-#define SIGXFSZ		25
-#define SIGVTALRM	26
-#define SIGPROF		27
-#define SIGWINCH	28
-#define SIGIO		29
-#define SIGPOLL		SIGIO
-/*
-#define SIGLOST		29
-*/
-#define SIGPWR		30
-#define SIGSYS		31
-#define	SIGUNUSED	31
-
-/* These should not be considered constants from userland.  */
-#define SIGRTMIN	32
-#define SIGRTMAX	_NSIG
-
-/*
- * SA_FLAGS values:
- *
- * SA_ONSTACK indicates that a registered stack_t will be used.
- * SA_RESTART flag to get restarting signals (which were the default long ago)
- * SA_NOCLDSTOP flag to turn off SIGCHLD when children stop.
- * SA_RESETHAND clears the handler when the signal is delivered.
- * SA_NOCLDWAIT flag on SIGCHLD to inhibit zombies.
- * SA_NODEFER prevents the current signal from being masked in the handler.
- *
- * SA_ONESHOT and SA_NOMASK are the historical Linux names for the Single
- * Unix names RESETHAND and NODEFER respectively.
- */
-#define SA_NOCLDSTOP	0x00000001
-#define SA_NOCLDWAIT	0x00000002
-#define SA_SIGINFO	0x00000004
-#define SA_ONSTACK	0x08000000
-#define SA_RESTART	0x10000000
-#define SA_NODEFER	0x40000000
-#define SA_RESETHAND	0x80000000
-
-#define SA_NOMASK	SA_NODEFER
-#define SA_ONESHOT	SA_RESETHAND
-
 #define SA_RESTORER	0x04000000
 
-/* 
- * sigaltstack controls
- */
-#define SS_ONSTACK	1
-#define SS_DISABLE	2
+#include <asm-generic/signal.h>
 
-#define MINSIGSTKSZ	2048
-#define SIGSTKSZ	8192
-
-#include <asm-generic/signal-defs.h>
-
-#ifdef __KERNEL__
 struct old_sigaction {
 	__sighandler_t sa_handler;
 	old_sigset_t sa_mask;
@@ -116,45 +12,4 @@
 	void (*sa_restorer)(void);
 };
 
-struct sigaction {
-	__sighandler_t sa_handler;
-	unsigned long sa_flags;
-	void (*sa_restorer)(void);
-	sigset_t sa_mask;		/* mask last for extensibility */
-};
-
-struct k_sigaction {
-	struct sigaction sa;
-};
-#else
-/* Here we must cater to libcs that poke about in kernel headers.  */
-
-struct sigaction {
-	union {
-	  __sighandler_t _sa_handler;
-	  void (*_sa_sigaction)(int, struct siginfo *, void *);
-	} _u;
-	sigset_t sa_mask;
-	unsigned long sa_flags;
-	void (*sa_restorer)(void);
-};
-
-#define sa_handler	_u._sa_handler
-#define sa_sigaction	_u._sa_sigaction
-
-#endif /* __KERNEL__ */
-
-typedef struct sigaltstack {
-	void *ss_sp;
-	int ss_flags;
-	size_t ss_size;
-} stack_t;
-
-#ifdef __KERNEL__
-#include <asm/sigcontext.h>
-
-#define ptrace_signal_deliver(regs, cookie) do { } while (0)
-
-#endif /* __KERNEL__ */
-
 #endif /* __ASM_SH_SIGNAL_H */
diff --git a/arch/sh/include/asm/smp.h b/arch/sh/include/asm/smp.h
index c24e9c6..ca64f43 100644
--- a/arch/sh/include/asm/smp.h
+++ b/arch/sh/include/asm/smp.h
@@ -43,7 +43,8 @@
 void plat_send_ipi(unsigned int cpu, unsigned int message);
 
 void arch_send_call_function_single_ipi(int cpu);
-void arch_send_call_function_ipi(cpumask_t mask);
+extern void arch_send_call_function_ipi_mask(const struct cpumask *mask);
+#define arch_send_call_function_ipi_mask arch_send_call_function_ipi_mask
 
 #else
 
diff --git a/arch/sh/include/asm/socket.h b/arch/sh/include/asm/socket.h
index 345653b..6b71384 100644
--- a/arch/sh/include/asm/socket.h
+++ b/arch/sh/include/asm/socket.h
@@ -1,60 +1 @@
-#ifndef __ASM_SH_SOCKET_H
-#define __ASM_SH_SOCKET_H
-
-#include <asm/sockios.h>
-
-/* For setsockopt(2) */
-#define SOL_SOCKET	1
-
-#define SO_DEBUG	1
-#define SO_REUSEADDR	2
-#define SO_TYPE		3
-#define SO_ERROR	4
-#define SO_DONTROUTE	5
-#define SO_BROADCAST	6
-#define SO_SNDBUF	7
-#define SO_RCVBUF	8
-#define SO_RCVBUFFORCE	32
-#define SO_SNDBUFFORCE	33
-#define SO_KEEPALIVE	9
-#define SO_OOBINLINE	10
-#define SO_NO_CHECK	11
-#define SO_PRIORITY	12
-#define SO_LINGER	13
-#define SO_BSDCOMPAT	14
-/* To add :#define SO_REUSEPORT 15 */
-#define SO_PASSCRED	16
-#define SO_PEERCRED	17
-#define SO_RCVLOWAT	18
-#define SO_SNDLOWAT	19
-#define SO_RCVTIMEO	20
-#define SO_SNDTIMEO	21
-
-/* Security levels - as per NRL IPv6 - don't actually do anything */
-#define SO_SECURITY_AUTHENTICATION		22
-#define SO_SECURITY_ENCRYPTION_TRANSPORT	23
-#define SO_SECURITY_ENCRYPTION_NETWORK		24
-
-#define SO_BINDTODEVICE	25
-
-/* Socket filtering */
-#define SO_ATTACH_FILTER        26
-#define SO_DETACH_FILTER        27
-
-#define SO_PEERNAME             28
-#define SO_TIMESTAMP		29
-#define SCM_TIMESTAMP		SO_TIMESTAMP
-
-#define SO_ACCEPTCONN		30
-
-#define SO_PEERSEC		31
-#define SO_PASSSEC		34
-#define SO_TIMESTAMPNS		35
-#define SCM_TIMESTAMPNS		SO_TIMESTAMPNS
-
-#define SO_MARK			36
-
-#define SO_TIMESTAMPING		37
-#define SCM_TIMESTAMPING	SO_TIMESTAMPING
-
-#endif /* __ASM_SH_SOCKET_H */
+#include <asm-generic/socket.h>
diff --git a/arch/sh/include/asm/swab.h b/arch/sh/include/asm/swab.h
index 0e08fe5..1cd0976 100644
--- a/arch/sh/include/asm/swab.h
+++ b/arch/sh/include/asm/swab.h
@@ -7,8 +7,7 @@
  */
 #include <linux/compiler.h>
 #include <linux/types.h>
-
-#define __SWAB_64_THRU_32__
+#include <asm-generic/swab.h>
 
 static inline __attribute_const__ __u32 __arch_swab32(__u32 x)
 {
diff --git a/arch/sh/include/asm/termbits.h b/arch/sh/include/asm/termbits.h
index 77db116..3935b10 100644
--- a/arch/sh/include/asm/termbits.h
+++ b/arch/sh/include/asm/termbits.h
@@ -1,198 +1 @@
-#ifndef __ASM_SH_TERMBITS_H
-#define __ASM_SH_TERMBITS_H
-
-#include <linux/posix_types.h>
-
-typedef unsigned char	cc_t;
-typedef unsigned int	speed_t;
-typedef unsigned int	tcflag_t;
-
-#define NCCS 19
-struct termios {
-	tcflag_t c_iflag;		/* input mode flags */
-	tcflag_t c_oflag;		/* output mode flags */
-	tcflag_t c_cflag;		/* control mode flags */
-	tcflag_t c_lflag;		/* local mode flags */
-	cc_t c_line;			/* line discipline */
-	cc_t c_cc[NCCS];		/* control characters */
-};
-
-struct termios2 {
-	tcflag_t c_iflag;		/* input mode flags */
-	tcflag_t c_oflag;		/* output mode flags */
-	tcflag_t c_cflag;		/* control mode flags */
-	tcflag_t c_lflag;		/* local mode flags */
-	cc_t c_line;			/* line discipline */
-	cc_t c_cc[NCCS];		/* control characters */
-	speed_t c_ispeed;		/* input speed */
-	speed_t c_ospeed;		/* output speed */
-};
-
-struct ktermios {
-	tcflag_t c_iflag;		/* input mode flags */
-	tcflag_t c_oflag;		/* output mode flags */
-	tcflag_t c_cflag;		/* control mode flags */
-	tcflag_t c_lflag;		/* local mode flags */
-	cc_t c_line;			/* line discipline */
-	cc_t c_cc[NCCS];		/* control characters */
-	speed_t c_ispeed;		/* input speed */
-	speed_t c_ospeed;		/* output speed */
-};
-
-/* c_cc characters */
-#define VINTR 0
-#define VQUIT 1
-#define VERASE 2
-#define VKILL 3
-#define VEOF 4
-#define VTIME 5
-#define VMIN 6
-#define VSWTC 7
-#define VSTART 8
-#define VSTOP 9
-#define VSUSP 10
-#define VEOL 11
-#define VREPRINT 12
-#define VDISCARD 13
-#define VWERASE 14
-#define VLNEXT 15
-#define VEOL2 16
-
-/* c_iflag bits */
-#define IGNBRK	0000001
-#define BRKINT	0000002
-#define IGNPAR	0000004
-#define PARMRK	0000010
-#define INPCK	0000020
-#define ISTRIP	0000040
-#define INLCR	0000100
-#define IGNCR	0000200
-#define ICRNL	0000400
-#define IUCLC	0001000
-#define IXON	0002000
-#define IXANY	0004000
-#define IXOFF	0010000
-#define IMAXBEL	0020000
-#define IUTF8	0040000
-
-/* c_oflag bits */
-#define OPOST	0000001
-#define OLCUC	0000002
-#define ONLCR	0000004
-#define OCRNL	0000010
-#define ONOCR	0000020
-#define ONLRET	0000040
-#define OFILL	0000100
-#define OFDEL	0000200
-#define NLDLY	0000400
-#define   NL0	0000000
-#define   NL1	0000400
-#define CRDLY	0003000
-#define   CR0	0000000
-#define   CR1	0001000
-#define   CR2	0002000
-#define   CR3	0003000
-#define TABDLY	0014000
-#define   TAB0	0000000
-#define   TAB1	0004000
-#define   TAB2	0010000
-#define   TAB3	0014000
-#define   XTABS	0014000
-#define BSDLY	0020000
-#define   BS0	0000000
-#define   BS1	0020000
-#define VTDLY	0040000
-#define   VT0	0000000
-#define   VT1	0040000
-#define FFDLY	0100000
-#define   FF0	0000000
-#define   FF1	0100000
-
-/* c_cflag bit meaning */
-#define CBAUD	0010017
-#define  B0	0000000		/* hang up */
-#define  B50	0000001
-#define  B75	0000002
-#define  B110	0000003
-#define  B134	0000004
-#define  B150	0000005
-#define  B200	0000006
-#define  B300	0000007
-#define  B600	0000010
-#define  B1200	0000011
-#define  B1800	0000012
-#define  B2400	0000013
-#define  B4800	0000014
-#define  B9600	0000015
-#define  B19200	0000016
-#define  B38400	0000017
-#define EXTA B19200
-#define EXTB B38400
-#define CSIZE	0000060
-#define   CS5	0000000
-#define   CS6	0000020
-#define   CS7	0000040
-#define   CS8	0000060
-#define CSTOPB	0000100
-#define CREAD	0000200
-#define PARENB	0000400
-#define PARODD	0001000
-#define HUPCL	0002000
-#define CLOCAL	0004000
-#define CBAUDEX 0010000
-#define	   BOTHER 0010000
-#define    B57600 0010001
-#define   B115200 0010002
-#define   B230400 0010003
-#define   B460800 0010004
-#define   B500000 0010005
-#define   B576000 0010006
-#define   B921600 0010007
-#define  B1000000 0010010
-#define  B1152000 0010011
-#define  B1500000 0010012
-#define  B2000000 0010013
-#define  B2500000 0010014
-#define  B3000000 0010015
-#define  B3500000 0010016
-#define  B4000000 0010017
-#define CIBAUD	  002003600000		/* input baud rate */
-#define CMSPAR	  010000000000		/* mark or space (stick) parity */
-#define CRTSCTS	  020000000000		/* flow control */
-
-#define IBSHIFT	16		/* Shift from CBAUD to CIBAUD */
-
-/* c_lflag bits */
-#define ISIG	0000001
-#define ICANON	0000002
-#define XCASE	0000004
-#define ECHO	0000010
-#define ECHOE	0000020
-#define ECHOK	0000040
-#define ECHONL	0000100
-#define NOFLSH	0000200
-#define TOSTOP	0000400
-#define ECHOCTL	0001000
-#define ECHOPRT	0002000
-#define ECHOKE	0004000
-#define FLUSHO	0010000
-#define PENDIN	0040000
-#define IEXTEN	0100000
-
-/* tcflow() and TCXONC use these */
-#define	TCOOFF		0
-#define	TCOON		1
-#define	TCIOFF		2
-#define	TCION		3
-
-/* tcflush() and TCFLSH use these */
-#define	TCIFLUSH	0
-#define	TCOFLUSH	1
-#define	TCIOFLUSH	2
-
-/* tcsetattr uses these */
-#define	TCSANOW		0
-#define	TCSADRAIN	1
-#define	TCSAFLUSH	2
-
-#endif /* __ASM_SH_TERMBITS_H */
+#include <asm-generic/termbits.h>
diff --git a/arch/sh/include/asm/termios.h b/arch/sh/include/asm/termios.h
index 0a8c793..280d78a 100644
--- a/arch/sh/include/asm/termios.h
+++ b/arch/sh/include/asm/termios.h
@@ -1,90 +1 @@
-#ifndef __ASM_SH_TERMIOS_H
-#define __ASM_SH_TERMIOS_H
-
-#include <asm/termbits.h>
-#include <asm/ioctls.h>
-
-struct winsize {
-	unsigned short ws_row;
-	unsigned short ws_col;
-	unsigned short ws_xpixel;
-	unsigned short ws_ypixel;
-};
-
-#define NCC 8
-struct termio {
-	unsigned short c_iflag;		/* input mode flags */
-	unsigned short c_oflag;		/* output mode flags */
-	unsigned short c_cflag;		/* control mode flags */
-	unsigned short c_lflag;		/* local mode flags */
-	unsigned char c_line;		/* line discipline */
-	unsigned char c_cc[NCC];	/* control characters */
-};
-
-/* modem lines */
-#define TIOCM_LE	0x001
-#define TIOCM_DTR	0x002
-#define TIOCM_RTS	0x004
-#define TIOCM_ST	0x008
-#define TIOCM_SR	0x010
-#define TIOCM_CTS	0x020
-#define TIOCM_CAR	0x040
-#define TIOCM_RNG	0x080
-#define TIOCM_DSR	0x100
-#define TIOCM_CD	TIOCM_CAR
-#define TIOCM_RI	TIOCM_RNG
-#define TIOCM_OUT1	0x2000
-#define TIOCM_OUT2	0x4000
-#define TIOCM_LOOP	0x8000
-
-/* ioctl (fd, TIOCSERGETLSR, &result) where result may be as below */
-
-#ifdef __KERNEL__
-
-/*	intr=^C		quit=^\		erase=del	kill=^U
-	eof=^D		vtime=\0	vmin=\1		sxtc=\0
-	start=^Q	stop=^S		susp=^Z		eol=\0
-	reprint=^R	discard=^U	werase=^W	lnext=^V
-	eol2=\0
-*/
-#define INIT_C_CC "\003\034\177\025\004\0\1\0\021\023\032\0\022\017\027\026\0"
-
-/*
- * Translate a "termio" structure into a "termios". Ugh.
- */
-#define SET_LOW_TERMIOS_BITS(termios, termio, x) { \
-	unsigned short __tmp; \
-	get_user(__tmp,&(termio)->x); \
-	*(unsigned short *) &(termios)->x = __tmp; \
-}
-
-#define user_termio_to_kernel_termios(termios, termio) \
-({ \
-	SET_LOW_TERMIOS_BITS(termios, termio, c_iflag); \
-	SET_LOW_TERMIOS_BITS(termios, termio, c_oflag); \
-	SET_LOW_TERMIOS_BITS(termios, termio, c_cflag); \
-	SET_LOW_TERMIOS_BITS(termios, termio, c_lflag); \
-	copy_from_user((termios)->c_cc, (termio)->c_cc, NCC); \
-})
-
-/*
- * Translate a "termios" structure into a "termio". Ugh.
- */
-#define kernel_termios_to_user_termio(termio, termios) \
-({ \
-	put_user((termios)->c_iflag, &(termio)->c_iflag); \
-	put_user((termios)->c_oflag, &(termio)->c_oflag); \
-	put_user((termios)->c_cflag, &(termio)->c_cflag); \
-	put_user((termios)->c_lflag, &(termio)->c_lflag); \
-	put_user((termios)->c_line,  &(termio)->c_line); \
-	copy_to_user((termio)->c_cc, (termios)->c_cc, NCC); \
-})
-
-#define user_termios_to_kernel_termios(k, u) copy_from_user(k, u, sizeof(struct termios2))
-#define kernel_termios_to_user_termios(u, k) copy_to_user(u, k, sizeof(struct termios2))
-#define user_termios_to_kernel_termios_1(k, u) copy_from_user(k, u, sizeof(struct termios))
-#define kernel_termios_to_user_termios_1(u, k) copy_to_user(u, k, sizeof(struct termios))
-
-#endif	/* __KERNEL__ */
-
-#endif	/* __ASM_SH_TERMIOS_H */
+#include <asm-generic/termios.h>
diff --git a/arch/sh/include/asm/timex.h b/arch/sh/include/asm/timex.h
index a873e24..b556d49 100644
--- a/arch/sh/include/asm/timex.h
+++ b/arch/sh/include/asm/timex.h
@@ -8,11 +8,6 @@
 
 #define CLOCK_TICK_RATE		(CONFIG_SH_PCLK_FREQ / 4) /* Underlying HZ */
 
-typedef unsigned long long cycles_t;
-
-static __inline__ cycles_t get_cycles (void)
-{
-	return 0;
-}
+#include <asm-generic/timex.h>
 
 #endif /* __ASM_SH_TIMEX_H */
diff --git a/arch/sh/include/asm/topology.h b/arch/sh/include/asm/topology.h
index 8489a09..b69ee85 100644
--- a/arch/sh/include/asm/topology.h
+++ b/arch/sh/include/asm/topology.h
@@ -35,9 +35,6 @@
 #define cpumask_of_node(node)	((void)node, cpu_online_mask)
 
 #define pcibus_to_node(bus)	((void)(bus), -1)
-#define pcibus_to_cpumask(bus)	(pcibus_to_node(bus) == -1 ? \
-					CPU_MASK_ALL : \
-					node_to_cpumask(pcibus_to_node(bus)))
 #define cpumask_of_pcibus(bus)	(pcibus_to_node(bus) == -1 ? \
 					CPU_MASK_ALL_PTR : \
 					cpumask_of_node(pcibus_to_node(bus)))
diff --git a/arch/sh/include/asm/types.h b/arch/sh/include/asm/types.h
index b13caca..c7f3c94 100644
--- a/arch/sh/include/asm/types.h
+++ b/arch/sh/include/asm/types.h
@@ -1,27 +1,14 @@
 #ifndef __ASM_SH_TYPES_H
 #define __ASM_SH_TYPES_H
 
-#include <asm-generic/int-ll64.h>
-
-#ifndef __ASSEMBLY__
-
-typedef unsigned short umode_t;
-
-#endif /* __ASSEMBLY__ */
+#include <asm-generic/types.h>
 
 /*
  * These aren't exported outside the kernel to avoid name space clashes
  */
 #ifdef __KERNEL__
-
-#define BITS_PER_LONG 32
-
 #ifndef __ASSEMBLY__
 
-/* Dma addresses are 32-bits wide.  */
-
-typedef u32 dma_addr_t;
-
 #ifdef CONFIG_SUPERH32
 typedef u16 insn_size_t;
 #else
@@ -29,7 +16,6 @@
 #endif
 
 #endif /* __ASSEMBLY__ */
-
 #endif /* __KERNEL__ */
 
 #endif /* __ASM_SH_TYPES_H */
diff --git a/arch/sh/include/asm/ucontext.h b/arch/sh/include/asm/ucontext.h
index 202ef1d..9bc07b9 100644
--- a/arch/sh/include/asm/ucontext.h
+++ b/arch/sh/include/asm/ucontext.h
@@ -1,12 +1 @@
-#ifndef __ASM_SH_UCONTEXT_H
-#define __ASM_SH_UCONTEXT_H
-
-struct ucontext {
-	unsigned long	  uc_flags;
-	struct ucontext  *uc_link;
-	stack_t		  uc_stack;
-	struct sigcontext uc_mcontext;
-	sigset_t	  uc_sigmask;	/* mask last for extensibility */
-};
-
-#endif /* __ASM_SH_UCONTEXT_H */
+#include <asm-generic/ucontext.h>
diff --git a/arch/sh/include/asm/unaligned.h b/arch/sh/include/asm/unaligned.h
index 8c0ad5e..7d14e06 100644
--- a/arch/sh/include/asm/unaligned.h
+++ b/arch/sh/include/asm/unaligned.h
@@ -6,19 +6,7 @@
 #include <asm/unaligned-sh4a.h>
 #else
 /* Otherwise, SH can't handle unaligned accesses. */
-#ifdef __LITTLE_ENDIAN__
-# include <linux/unaligned/le_struct.h>
-# include <linux/unaligned/be_byteshift.h>
-# include <linux/unaligned/generic.h>
-# define get_unaligned	__get_unaligned_le
-# define put_unaligned	__put_unaligned_le
-#else
-# include <linux/unaligned/be_struct.h>
-# include <linux/unaligned/le_byteshift.h>
-# include <linux/unaligned/generic.h>
-# define get_unaligned	__get_unaligned_be
-# define put_unaligned	__put_unaligned_be
-#endif
+#include <asm-generic/unaligned.h>
 #endif
 
 #endif /* _ASM_SH_UNALIGNED_H */
diff --git a/arch/sh/include/asm/unistd_32.h b/arch/sh/include/asm/unistd_32.h
index 6519708..61d6ad9 100644
--- a/arch/sh/include/asm/unistd_32.h
+++ b/arch/sh/include/asm/unistd_32.h
@@ -344,8 +344,9 @@
 #define __NR_preadv		333
 #define __NR_pwritev		334
 #define __NR_rt_tgsigqueueinfo	335
+#define __NR_perf_counter_open	336
 
-#define NR_syscalls 336
+#define NR_syscalls 337
 
 #ifdef __KERNEL__
 
diff --git a/arch/sh/include/asm/unistd_64.h b/arch/sh/include/asm/unistd_64.h
index 8014aea..a751699 100644
--- a/arch/sh/include/asm/unistd_64.h
+++ b/arch/sh/include/asm/unistd_64.h
@@ -384,10 +384,11 @@
 #define __NR_preadv		361
 #define __NR_pwritev		362
 #define __NR_rt_tgsigqueueinfo	363
+#define __NR_perf_counter_open	364
 
 #ifdef __KERNEL__
 
-#define NR_syscalls 364
+#define NR_syscalls 365
 
 #define __ARCH_WANT_IPC_PARSE_VERSION
 #define __ARCH_WANT_OLD_READDIR
diff --git a/arch/sh/include/mach-common/mach/highlander.h b/arch/sh/include/mach-common/mach/highlander.h
index bd26a84..5d9d4d5 100644
--- a/arch/sh/include/mach-common/mach/highlander.h
+++ b/arch/sh/include/mach-common/mach/highlander.h
@@ -2,6 +2,9 @@
 #define __ASM_SH_RENESAS_R7780RP_H
 
 /* Box specific addresses.  */
+#define PA_NORFLASH_ADDR	0x00000000
+#define PA_NORFLASH_SIZE	0x04000000
+
 #if defined(CONFIG_SH_R7780MP)
 #define PA_BCR          0xa4000000      /* FPGA */
 #define PA_SDPOW	(-1)
diff --git a/arch/sh/kernel/cpu/clock-cpg.c b/arch/sh/kernel/cpu/clock-cpg.c
index 275942e..6dfe2cc 100644
--- a/arch/sh/kernel/cpu/clock-cpg.c
+++ b/arch/sh/kernel/cpu/clock-cpg.c
@@ -1,6 +1,6 @@
 #include <linux/clk.h>
 #include <linux/compiler.h>
-#include <linux/bootmem.h>
+#include <linux/slab.h>
 #include <linux/io.h>
 #include <asm/clock.h>
 
@@ -127,10 +127,11 @@
 	int k;
 
 	freq_table_size *= (nr_divs + 1);
-
-	freq_table = alloc_bootmem(freq_table_size * nr);
-	if (!freq_table)
+	freq_table = kzalloc(freq_table_size * nr, GFP_KERNEL);
+	if (!freq_table) {
+		pr_err("sh_clk_div6_register: unable to alloc memory\n");
 		return -ENOMEM;
+	}
 
 	for (k = 0; !ret && (k < nr); k++) {
 		clkp = clks + k;
@@ -175,10 +176,11 @@
 	int k;
 
 	freq_table_size *= (nr_divs + 1);
-
-	freq_table = alloc_bootmem(freq_table_size * nr);
-	if (!freq_table)
+	freq_table = kzalloc(freq_table_size * nr, GFP_KERNEL);
+	if (!freq_table) {
+		pr_err("sh_clk_div4_register: unable to alloc memory\n");
 		return -ENOMEM;
+	}
 
 	for (k = 0; !ret && (k < nr); k++) {
 		clkp = clks + k;
diff --git a/arch/sh/kernel/cpu/sh4a/setup-sh7366.c b/arch/sh/kernel/cpu/sh4a/setup-sh7366.c
index 318516f..c18f7d0 100644
--- a/arch/sh/kernel/cpu/sh4a/setup-sh7366.c
+++ b/arch/sh/kernel/cpu/sh4a/setup-sh7366.c
@@ -15,6 +15,7 @@
 #include <linux/serial_sci.h>
 #include <linux/uio_driver.h>
 #include <linux/sh_timer.h>
+#include <linux/usb/r8a66597.h>
 #include <asm/clock.h>
 
 static struct resource iic_resources[] = {
@@ -38,18 +39,20 @@
 	.resource       = iic_resources,
 };
 
+static struct r8a66597_platdata r8a66597_data = {
+	/* This set zero to all members */
+};
+
 static struct resource usb_host_resources[] = {
 	[0] = {
-		.name   = "r8a66597_hcd",
 		.start  = 0xa4d80000,
 		.end    = 0xa4d800ff,
 		.flags  = IORESOURCE_MEM,
 	},
 	[1] = {
-		.name   = "r8a66597_hcd",
 		.start  = 65,
 		.end    = 65,
-		.flags  = IORESOURCE_IRQ,
+		.flags	= IORESOURCE_IRQ | IRQF_TRIGGER_LOW,
 	},
 };
 
@@ -59,6 +62,7 @@
 	.dev = {
 		.dma_mask		= NULL,
 		.coherent_dma_mask	= 0xffffffff,
+		.platform_data		= &r8a66597_data,
 	},
 	.num_resources	= ARRAY_SIZE(usb_host_resources),
 	.resource	= usb_host_resources,
diff --git a/arch/sh/kernel/cpu/sh4a/setup-sh7723.c b/arch/sh/kernel/cpu/sh4a/setup-sh7723.c
index d8f4a13..e1bb80b 100644
--- a/arch/sh/kernel/cpu/sh4a/setup-sh7723.c
+++ b/arch/sh/kernel/cpu/sh4a/setup-sh7723.c
@@ -13,6 +13,7 @@
 #include <linux/mm.h>
 #include <linux/serial_sci.h>
 #include <linux/uio_driver.h>
+#include <linux/usb/r8a66597.h>
 #include <linux/sh_timer.h>
 #include <linux/io.h>
 #include <asm/clock.h>
@@ -396,9 +397,12 @@
 	.resource	= rtc_resources,
 };
 
+static struct r8a66597_platdata r8a66597_data = {
+	/* This set zero to all members */
+};
+
 static struct resource sh7723_usb_host_resources[] = {
 	[0] = {
-		.name	= "r8a66597_hcd",
 		.start	= 0xa4d80000,
 		.end	= 0xa4d800ff,
 		.flags	= IORESOURCE_MEM,
@@ -406,7 +410,7 @@
 	[1] = {
 		.start	= 65,
 		.end	= 65,
-		.flags	= IORESOURCE_IRQ,
+		.flags	= IORESOURCE_IRQ | IRQF_TRIGGER_LOW,
 	},
 };
 
@@ -416,6 +420,7 @@
 	.dev = {
 		.dma_mask		= NULL,         /*  not use dma */
 		.coherent_dma_mask	= 0xffffffff,
+		.platform_data		= &r8a66597_data,
 	},
 	.num_resources	= ARRAY_SIZE(sh7723_usb_host_resources),
 	.resource	= sh7723_usb_host_resources,
diff --git a/arch/sh/kernel/cpu/sh4a/smp-shx3.c b/arch/sh/kernel/cpu/sh4a/smp-shx3.c
index b8869aa..2b6b0d5 100644
--- a/arch/sh/kernel/cpu/sh4a/smp-shx3.c
+++ b/arch/sh/kernel/cpu/sh4a/smp-shx3.c
@@ -35,8 +35,7 @@
 	unsigned int cpu = 0;
 	int i, num;
 
-	cpus_clear(cpu_possible_map);
-	cpu_set(cpu, cpu_possible_map);
+	init_cpu_possible(cpumask_of(cpu));
 
 	__cpu_number_map[0] = 0;
 	__cpu_logical_map[0] = 0;
@@ -46,7 +45,7 @@
 	 * for the total number of cores.
 	 */
 	for (i = 1, num = 0; i < NR_CPUS; i++) {
-		cpu_set(i, cpu_possible_map);
+		set_cpu_possible(i, true);
 		__cpu_number_map[i] = ++num;
 		__cpu_logical_map[num] = i;
 	}
diff --git a/arch/sh/kernel/ftrace.c b/arch/sh/kernel/ftrace.c
index 4c32474..066f37d 100644
--- a/arch/sh/kernel/ftrace.c
+++ b/arch/sh/kernel/ftrace.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 Matt Fleming <mjf@gentoo.org>
+ * Copyright (C) 2008 Matt Fleming <matt@console-pimps.org>
  * Copyright (C) 2008 Paul Mundt <lethal@linux-sh.org>
  *
  * Code for replacing ftrace calls with jumps.
@@ -19,30 +19,37 @@
 #include <asm/ftrace.h>
 #include <asm/cacheflush.h>
 
-static unsigned char ftrace_nop[] = {
-	0x09, 0x00,		/* nop */
-	0x09, 0x00,		/* nop */
-};
-
 static unsigned char ftrace_replaced_code[MCOUNT_INSN_SIZE];
 
-unsigned char *ftrace_nop_replace(void)
+static unsigned char ftrace_nop[4];
+/*
+ * If we're trying to nop out a call to a function, we instead
+ * place a call to the address after the memory table.
+ *
+ * 8c011060 <a>:
+ * 8c011060:       02 d1           mov.l   8c01106c <a+0xc>,r1
+ * 8c011062:       22 4f           sts.l   pr,@-r15
+ * 8c011064:       02 c7           mova    8c011070 <a+0x10>,r0
+ * 8c011066:       2b 41           jmp     @r1
+ * 8c011068:       2a 40           lds     r0,pr
+ * 8c01106a:       09 00           nop
+ * 8c01106c:       68 24           .word 0x2468     <--- ip
+ * 8c01106e:       1d 8c           .word 0x8c1d
+ * 8c011070:       26 4f           lds.l   @r15+,pr <--- ip + MCOUNT_INSN_SIZE
+ *
+ * We write 0x8c011070 to 0x8c01106c so that on entry to a() we branch
+ * past the _mcount call and continue executing code like normal.
+ */
+static unsigned char *ftrace_nop_replace(unsigned long ip)
 {
+	__raw_writel(ip + MCOUNT_INSN_SIZE, ftrace_nop);
 	return ftrace_nop;
 }
 
-static int is_sh_nop(unsigned char *ip)
-{
-	return strncmp(ip, ftrace_nop, sizeof(ftrace_nop));
-}
-
-unsigned char *ftrace_call_replace(unsigned long ip, unsigned long addr)
+static unsigned char *ftrace_call_replace(unsigned long ip, unsigned long addr)
 {
 	/* Place the address in the memory table. */
-	if (addr == CALLER_ADDR)
-		__raw_writel(addr + MCOUNT_INSN_OFFSET, ftrace_replaced_code);
-	else
-		__raw_writel(addr, ftrace_replaced_code);
+	__raw_writel(addr, ftrace_replaced_code);
 
 	/*
 	 * No locking needed, this must be called via kstop_machine
@@ -51,7 +58,7 @@
 	return ftrace_replaced_code;
 }
 
-int ftrace_modify_code(unsigned long ip, unsigned char *old_code,
+static int ftrace_modify_code(unsigned long ip, unsigned char *old_code,
 		       unsigned char *new_code)
 {
 	unsigned char replaced[MCOUNT_INSN_SIZE];
@@ -66,13 +73,6 @@
 	 * kstop_machine, or before SMP starts.
 	 */
 
-	/*
-	 * If we're trying to nop out a call to a function, we instead
-	 * place a call to the address after the memory table.
-	 */
-	if (is_sh_nop(new_code) == 0)
-		__raw_writel(ip + MCOUNT_INSN_SIZE, (unsigned long)new_code);
-
 	/* read the text we want to modify */
 	if (probe_kernel_read(replaced, (void *)ip, MCOUNT_INSN_SIZE))
 		return -EFAULT;
@@ -92,13 +92,13 @@
 
 int ftrace_update_ftrace_func(ftrace_func_t func)
 {
-	unsigned long ip = (unsigned long)(&ftrace_call);
+	unsigned long ip = (unsigned long)(&ftrace_call) + MCOUNT_INSN_OFFSET;
 	unsigned char old[MCOUNT_INSN_SIZE], *new;
 
-	memcpy(old, (unsigned char *)(ip + MCOUNT_INSN_OFFSET), MCOUNT_INSN_SIZE);
+	memcpy(old, (unsigned char *)ip, MCOUNT_INSN_SIZE);
 	new = ftrace_call_replace(ip, (unsigned long)func);
 
-	return ftrace_modify_code(ip + MCOUNT_INSN_OFFSET, old, new);
+	return ftrace_modify_code(ip, old, new);
 }
 
 int ftrace_make_nop(struct module *mod,
@@ -108,7 +108,7 @@
 	unsigned long ip = rec->ip;
 
 	old = ftrace_call_replace(ip, addr);
-	new = ftrace_nop_replace();
+	new = ftrace_nop_replace(ip);
 
 	return ftrace_modify_code(rec->ip, old, new);
 }
@@ -118,7 +118,7 @@
 	unsigned char *new, *old;
 	unsigned long ip = rec->ip;
 
-	old = ftrace_nop_replace();
+	old = ftrace_nop_replace(ip);
 	new = ftrace_call_replace(ip, addr);
 
 	return ftrace_modify_code(rec->ip, old, new);
diff --git a/arch/sh/kernel/process_32.c b/arch/sh/kernel/process_32.c
index 9289ede..92d7740 100644
--- a/arch/sh/kernel/process_32.c
+++ b/arch/sh/kernel/process_32.c
@@ -119,8 +119,6 @@
 	pid = do_fork(flags | CLONE_VM | CLONE_UNTRACED, 0,
 		      &regs, 0, NULL, NULL);
 
-	trace_mark(kernel_arch_kthread_create, "pid %d fn %p", pid, fn);
-
 	return pid;
 }
 
@@ -367,11 +365,6 @@
 		goto out;
 
 	error = do_execve(filename, uargv, uenvp, regs);
-	if (error == 0) {
-		task_lock(current);
-		current->ptrace &= ~PT_DTRACE;
-		task_unlock(current);
-	}
 	putname(filename);
 out:
 	return error;
diff --git a/arch/sh/kernel/process_64.c b/arch/sh/kernel/process_64.c
index 96be839..24de742 100644
--- a/arch/sh/kernel/process_64.c
+++ b/arch/sh/kernel/process_64.c
@@ -323,7 +323,6 @@
 int kernel_thread(int (*fn)(void *), void * arg, unsigned long flags)
 {
 	struct pt_regs regs;
-	int pid;
 
 	memset(&regs, 0, sizeof(regs));
 	regs.regs[2] = (unsigned long)arg;
@@ -333,12 +332,8 @@
 	regs.sr = (1 << 30);
 
 	/* Ok, create the new process.. */
-	pid = do_fork(flags | CLONE_VM | CLONE_UNTRACED, 0,
+	return do_fork(flags | CLONE_VM | CLONE_UNTRACED, 0,
 		      &regs, 0, NULL, NULL);
-
-	trace_mark(kernel_arch_kthread_create, "pid %d fn %p", pid, fn);
-
-	return pid;
 }
 
 /*
@@ -529,11 +524,6 @@
 			  (char __user * __user *)uargv,
 			  (char __user * __user *)uenvp,
 			  pregs);
-	if (error == 0) {
-		task_lock(current);
-		current->ptrace &= ~PT_DTRACE;
-		task_unlock(current);
-	}
 	putname(filename);
 out:
 	return error;
diff --git a/arch/sh/kernel/sh_ksyms_64.c b/arch/sh/kernel/sh_ksyms_64.c
index 8f54ef0..f5bd156 100644
--- a/arch/sh/kernel/sh_ksyms_64.c
+++ b/arch/sh/kernel/sh_ksyms_64.c
@@ -38,13 +38,6 @@
 EXPORT_SYMBOL(flush_dcache_page);
 #endif
 
-/* Networking helper routines. */
-EXPORT_SYMBOL(csum_partial);
-EXPORT_SYMBOL(csum_partial_copy_nocheck);
-#ifdef CONFIG_IPV6
-EXPORT_SYMBOL(csum_ipv6_magic);
-#endif
-
 #ifdef CONFIG_VT
 EXPORT_SYMBOL(screen_info);
 #endif
diff --git a/arch/sh/kernel/signal_32.c b/arch/sh/kernel/signal_32.c
index 17784e1..b5afbec 100644
--- a/arch/sh/kernel/signal_32.c
+++ b/arch/sh/kernel/signal_32.c
@@ -332,8 +332,8 @@
 
 /* These symbols are defined with the addresses in the vsyscall page.
    See vsyscall-trapa.S.  */
-extern void __user __kernel_sigreturn;
-extern void __user __kernel_rt_sigreturn;
+extern void __kernel_sigreturn(void);
+extern void __kernel_rt_sigreturn(void);
 
 static int setup_frame(int sig, struct k_sigaction *ka,
 			sigset_t *set, struct pt_regs *regs)
diff --git a/arch/sh/kernel/smp.c b/arch/sh/kernel/smp.c
index 8f40274..442d8d4 100644
--- a/arch/sh/kernel/smp.c
+++ b/arch/sh/kernel/smp.c
@@ -47,7 +47,7 @@
 	plat_prepare_cpus(max_cpus);
 
 #ifndef CONFIG_HOTPLUG_CPU
-	cpu_present_map = cpu_possible_map;
+	init_cpu_present(&cpu_possible_map);
 #endif
 }
 
@@ -58,8 +58,8 @@
 	__cpu_number_map[0] = cpu;
 	__cpu_logical_map[0] = cpu;
 
-	cpu_set(cpu, cpu_online_map);
-	cpu_set(cpu, cpu_possible_map);
+	set_cpu_online(cpu, true);
+	set_cpu_possible(cpu, true);
 }
 
 asmlinkage void __cpuinit start_secondary(void)
@@ -171,11 +171,11 @@
 	smp_call_function(stop_this_cpu, 0, 0);
 }
 
-void arch_send_call_function_ipi(cpumask_t mask)
+void arch_send_call_function_ipi_mask(const struct cpumask *mask)
 {
 	int cpu;
 
-	for_each_cpu_mask(cpu, mask)
+	for_each_cpu(cpu, mask)
 		plat_send_ipi(cpu, SMP_MSG_FUNCTION);
 }
 
diff --git a/arch/sh/kernel/sys_sh.c b/arch/sh/kernel/sys_sh.c
index e3a7e36..90d00e4 100644
--- a/arch/sh/kernel/sys_sh.c
+++ b/arch/sh/kernel/sys_sh.c
@@ -88,8 +88,6 @@
 	version = call >> 16; /* hack for backward compatibility */
 	call &= 0xffff;
 
-	trace_mark(kernel_arch_ipc_call, "call %u first %d", call, first);
-
 	if (call <= SEMTIMEDOP)
 		switch (call) {
 		case SEMOP:
diff --git a/arch/sh/kernel/syscalls_32.S b/arch/sh/kernel/syscalls_32.S
index a9fff9f..f9e21fa 100644
--- a/arch/sh/kernel/syscalls_32.S
+++ b/arch/sh/kernel/syscalls_32.S
@@ -352,3 +352,4 @@
 	.long sys_preadv
 	.long sys_pwritev
 	.long sys_rt_tgsigqueueinfo	/* 335 */
+	.long sys_perf_counter_open
diff --git a/arch/sh/kernel/syscalls_64.S b/arch/sh/kernel/syscalls_64.S
index 75c1889..bf420b6 100644
--- a/arch/sh/kernel/syscalls_64.S
+++ b/arch/sh/kernel/syscalls_64.S
@@ -390,3 +390,4 @@
 	.long sys_preadv
 	.long sys_pwritev
 	.long sys_rt_tgsigqueueinfo
+	.long sys_perf_counter_open
diff --git a/arch/sh/kernel/time.c b/arch/sh/kernel/time.c
index 2edde32..9b352a1 100644
--- a/arch/sh/kernel/time.c
+++ b/arch/sh/kernel/time.c
@@ -91,21 +91,6 @@
 
 void (*board_time_init)(void);
 
-unsigned long long sched_clock(void)
-{
-	return (jiffies_64 - INITIAL_JIFFIES) * (NSEC_PER_SEC / HZ);
-}
-
-static void __init sh_late_time_init(void)
-{
-	/*
-	 * Make sure all compiled-in early timers register themselves.
-	 * Run probe() for one "earlytimer" device.
-	 */
-	early_platform_driver_register_all("earlytimer");
-	early_platform_driver_probe("earlytimer", 1, 0);
-}
-
 void __init time_init(void)
 {
 	if (board_time_init)
@@ -121,5 +106,15 @@
 	local_timer_setup(smp_processor_id());
 #endif
 
-	late_time_init = sh_late_time_init;
+	/*
+	 * Make sure all compiled-in early timers register themselves.
+	 *
+	 * Run probe() for two "earlytimer" devices, these will be the
+	 * clockevents and clocksource devices respectively. In the event
+	 * that only a clockevents device is available, we -ENODEV on the
+	 * clocksource and the jiffies clocksource is used transparently
+	 * instead. No error handling is necessary here.
+	 */
+	early_platform_driver_register_all("earlytimer");
+	early_platform_driver_probe("earlytimer", 2, 0);
 }
diff --git a/arch/sh/kernel/traps.c b/arch/sh/kernel/traps.c
index 46348ed0..b3e0067 100644
--- a/arch/sh/kernel/traps.c
+++ b/arch/sh/kernel/traps.c
@@ -69,6 +69,7 @@
 		insn_size_t insn = *(insn_size_t *)instruction_pointer(regs);
 		if (insn == TRAPA_BUG_OPCODE)
 			handle_BUG(regs);
+		return;
 	}
 #endif
 
diff --git a/arch/sh/lib64/Makefile b/arch/sh/lib64/Makefile
index 4bacb9e..334bb2d 100644
--- a/arch/sh/lib64/Makefile
+++ b/arch/sh/lib64/Makefile
@@ -10,7 +10,7 @@
 #
 
 # Panic should really be compiled as PIC
-lib-y  := udelay.o c-checksum.o dbg.o panic.o memcpy.o memset.o \
+lib-y  := udelay.o dbg.o panic.o memcpy.o memset.o \
 	  copy_user_memcpy.o copy_page.o clear_page.o strcpy.o strlen.o
 
 # Extracted from libgcc
diff --git a/arch/sh/lib64/c-checksum.c b/arch/sh/lib64/c-checksum.c
deleted file mode 100644
index 73c0877..0000000
--- a/arch/sh/lib64/c-checksum.c
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * arch/sh/lib64/c-checksum.c
- *
- * This file contains network checksum routines that are better done
- * in an architecture-specific manner due to speed..
- */
-#include <linux/string.h>
-#include <linux/errno.h>
-#include <linux/kernel.h>
-#include <linux/module.h>
-#include <asm/byteorder.h>
-#include <asm/uaccess.h>
-
-static inline unsigned short from64to16(unsigned long long x)
-{
-	/* add up 32-bit words for 33 bits */
-	x = (x & 0xffffffff) + (x >> 32);
-	/* add up 16-bit and 17-bit words for 17+c bits */
-	x = (x & 0xffff) + (x >> 16);
-	/* add up 16-bit and 2-bit for 16+c bit */
-	x = (x & 0xffff) + (x >> 16);
-	/* add up carry.. */
-	x = (x & 0xffff) + (x >> 16);
-	return x;
-}
-
-static inline unsigned short foldto16(unsigned long x)
-{
-	/* add up 16-bit for 17 bits */
-	x = (x & 0xffff) + (x >> 16);
-	/* add up carry.. */
-	x = (x & 0xffff) + (x >> 16);
-	return x;
-}
-
-static inline unsigned short myfoldto16(unsigned long long x)
-{
-	/* Fold down to 32-bits so we don't lose in the typedef-less
-	   network stack.  */
-	/* 64 to 33 */
-	x = (x & 0xffffffff) + (x >> 32);
-	/* 33 to 32 */
-	x = (x & 0xffffffff) + (x >> 32);
-
-	/* add up 16-bit for 17 bits */
-	x = (x & 0xffff) + (x >> 16);
-	/* add up carry.. */
-	x = (x & 0xffff) + (x >> 16);
-	return x;
-}
-
-#define odd(x) ((x)&1)
-#define U16(x) ntohs(x)
-
-static unsigned long do_csum(const unsigned char *buff, int len)
-{
-	int odd, count;
-	unsigned long result = 0;
-
-	pr_debug("do_csum buff %p, len %d (0x%x)\n", buff, len, len);
-#ifdef DEBUG
-	for (i = 0; i < len; i++) {
-		if ((i % 26) == 0)
-			printk("\n");
-		printk("%02X ", buff[i]);
-	}
-#endif
-
-	if (len <= 0)
-		goto out;
-
-	odd = 1 & (unsigned long) buff;
-	if (odd) {
-		result = *buff << 8;
-		len--;
-		buff++;
-	}
-	count = len >> 1;	/* nr of 16-bit words.. */
-	if (count) {
-		if (2 & (unsigned long) buff) {
-			result += *(unsigned short *) buff;
-			count--;
-			len -= 2;
-			buff += 2;
-		}
-		count >>= 1;	/* nr of 32-bit words.. */
-		if (count) {
-			unsigned long carry = 0;
-			do {
-				unsigned long w = *(unsigned long *) buff;
-				buff += 4;
-				count--;
-				result += carry;
-				result += w;
-				carry = (w > result);
-			} while (count);
-			result += carry;
-			result = (result & 0xffff) + (result >> 16);
-		}
-		if (len & 2) {
-			result += *(unsigned short *) buff;
-			buff += 2;
-		}
-	}
-	if (len & 1)
-		result += *buff;
-	result = foldto16(result);
-	if (odd)
-		result = ((result >> 8) & 0xff) | ((result & 0xff) << 8);
-
-	pr_debug("\nCHECKSUM is 0x%lx\n", result);
-
-      out:
-	return result;
-}
-
-/* computes the checksum of a memory block at buff, length len,
-   and adds in "sum" (32-bit)  */
-__wsum csum_partial(const void *buff, int len, __wsum sum)
-{
-	unsigned long long result = do_csum(buff, len);
-
-	/* add in old sum, and carry.. */
-	result += (__force u32)sum;
-	/* 32+c bits -> 32 bits */
-	result = (result & 0xffffffff) + (result >> 32);
-
-	pr_debug("csum_partial, buff %p len %d sum 0x%x result=0x%016Lx\n",
-		buff, len, sum, result);
-
-	return (__force __wsum)result;
-}
-
-/* Copy while checksumming, otherwise like csum_partial.  */
-__wsum
-csum_partial_copy_nocheck(const void *src, void *dst, int len, __wsum sum)
-{
-	sum = csum_partial(src, len, sum);
-	memcpy(dst, src, len);
-
-	return sum;
-}
-
-/* Copy from userspace and compute checksum.  If we catch an exception
-   then zero the rest of the buffer.  */
-__wsum
-csum_partial_copy_from_user(const void __user *src, void *dst, int len,
-			    __wsum sum, int *err_ptr)
-{
-	int missing;
-
-	pr_debug
-	    ("csum_partial_copy_from_user src %p, dest %p, len %d, sum %08x, err_ptr %p\n",
-	     src, dst, len, sum, err_ptr);
-	missing = copy_from_user(dst, src, len);
-	pr_debug("  access_ok %d\n", __access_ok((unsigned long) src, len));
-	pr_debug("  missing %d\n", missing);
-	if (missing) {
-		memset(dst + len - missing, 0, missing);
-		*err_ptr = -EFAULT;
-	}
-
-	return csum_partial(dst, len, sum);
-}
-
-/* Copy to userspace and compute checksum.  */
-__wsum
-csum_partial_copy_to_user(const unsigned char *src, unsigned char *dst, int len,
-			  __wsum sum, int *err_ptr)
-{
-	sum = csum_partial(src, len, sum);
-
-	if (copy_to_user(dst, src, len))
-		*err_ptr = -EFAULT;
-
-	return sum;
-}
-
-/*
- *	This is a version of ip_compute_csum() optimized for IP headers,
- *	which always checksum on 4 octet boundaries.
- */
-__sum16 ip_fast_csum(const void *iph, unsigned int ihl)
-{
-	pr_debug("ip_fast_csum %p,%d\n", iph, ihl);
-
-	return (__force __sum16)~do_csum(iph, ihl * 4);
-}
-
-__wsum csum_tcpudp_nofold(__be32 saddr, __be32 daddr,
-				unsigned short len,
-				unsigned short proto, __wsum sum)
-{
-	unsigned long long result;
-
-	pr_debug("ntohs(0x%x)=0x%x\n", 0xdead, ntohs(0xdead));
-	pr_debug("htons(0x%x)=0x%x\n", 0xdead, htons(0xdead));
-
-	result = (__force u64) saddr + (__force u64) daddr +
-		 (__force u64) sum + ((len + proto) << 8);
-
-	/* Fold down to 32-bits so we don't lose in the typedef-less
-	   network stack.  */
-	/* 64 to 33 */
-	result = (result & 0xffffffff) + (result >> 32);
-	/* 33 to 32 */
-	result = (result & 0xffffffff) + (result >> 32);
-
-	pr_debug("%s saddr %x daddr %x len %x proto %x sum %x result %08Lx\n",
-		__func__, saddr, daddr, len, proto, sum, result);
-
-	return (__wsum)result;
-}
-EXPORT_SYMBOL(csum_tcpudp_nofold);
diff --git a/arch/sh/mm/fault_32.c b/arch/sh/mm/fault_32.c
index 31a33eb..2c50f80 100644
--- a/arch/sh/mm/fault_32.c
+++ b/arch/sh/mm/fault_32.c
@@ -249,9 +249,6 @@
 {
 	int ret = 0;
 
-	trace_mark(kernel_arch_trap_entry, "trap_id %d ip #p%ld",
-		   trap >> 5, instruction_pointer(regs));
-
 #ifdef CONFIG_KPROBES
 	if (!user_mode(regs)) {
 		preempt_disable();
@@ -327,6 +324,5 @@
 
 	ret = 0;
 out:
-	trace_mark(kernel_arch_trap_exit, MARK_NOARGS);
 	return ret;
 }
diff --git a/arch/sparc/include/asm/pci_64.h b/arch/sparc/include/asm/pci_64.h
index 4f79a54..7a1e356 100644
--- a/arch/sparc/include/asm/pci_64.h
+++ b/arch/sparc/include/asm/pci_64.h
@@ -191,8 +191,6 @@
 pcibios_bus_to_resource(struct pci_dev *dev, struct resource *res,
 			struct pci_bus_region *region);
 
-extern struct resource *pcibios_select_root(struct pci_dev *, struct resource *);
-
 static inline int pci_get_legacy_ide_irq(struct pci_dev *dev, int channel)
 {
 	return PCI_IRQ_NONE;
diff --git a/arch/sparc/kernel/pci.c b/arch/sparc/kernel/pci.c
index 4638fba..57859ad 100644
--- a/arch/sparc/kernel/pci.c
+++ b/arch/sparc/kernel/pci.c
@@ -711,19 +711,6 @@
 	pbus->resource[1] = &pbm->mem_space;
 }
 
-struct resource *pcibios_select_root(struct pci_dev *pdev, struct resource *r)
-{
-	struct pci_pbm_info *pbm = pdev->bus->sysdata;
-	struct resource *root = NULL;
-
-	if (r->flags & IORESOURCE_IO)
-		root = &pbm->io_space;
-	if (r->flags & IORESOURCE_MEM)
-		root = &pbm->mem_space;
-
-	return root;
-}
-
 void pcibios_update_irq(struct pci_dev *pdev, int irq)
 {
 }
diff --git a/arch/sparc/mm/init_64.c b/arch/sparc/mm/init_64.c
index ca92e2f..ed6be6b 100644
--- a/arch/sparc/mm/init_64.c
+++ b/arch/sparc/mm/init_64.c
@@ -1796,10 +1796,16 @@
 
 	prom_build_devicetree();
 	of_populate_present_mask();
+#ifndef CONFIG_SMP
+	of_fill_in_cpu_data();
+#endif
 
 	if (tlb_type == hypervisor) {
 		sun4v_mdesc_init();
 		mdesc_populate_present_mask(cpu_all_mask);
+#ifndef CONFIG_SMP
+		mdesc_fill_in_cpu_data(cpu_all_mask);
+#endif
 	}
 
 	/* Once the OF device tree and MDESC have been setup, we know
diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index cf42fc3..d1430ef 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -28,11 +28,13 @@
 	select HAVE_KPROBES
 	select ARCH_WANT_OPTIONAL_GPIOLIB
 	select ARCH_WANT_FRAME_POINTERS
+	select HAVE_DMA_ATTRS
 	select HAVE_KRETPROBES
 	select HAVE_FTRACE_MCOUNT_RECORD
 	select HAVE_DYNAMIC_FTRACE
 	select HAVE_FUNCTION_TRACER
 	select HAVE_FUNCTION_GRAPH_TRACER
+	select HAVE_FUNCTION_GRAPH_FP_TEST
 	select HAVE_FUNCTION_TRACE_MCOUNT_TEST
 	select HAVE_FTRACE_NMI_ENTER if DYNAMIC_FTRACE
 	select HAVE_FTRACE_SYSCALLS
diff --git a/arch/x86/boot/Makefile b/arch/x86/boot/Makefile
index 8d16ada..ec749c2 100644
--- a/arch/x86/boot/Makefile
+++ b/arch/x86/boot/Makefile
@@ -70,6 +70,7 @@
 		   $(call cc-option, -mpreferred-stack-boundary=2)
 KBUILD_CFLAGS	+= $(call cc-option, -m32)
 KBUILD_AFLAGS	:= $(KBUILD_CFLAGS) -D__ASSEMBLY__
+GCOV_PROFILE := n
 
 $(obj)/bzImage: asflags-y  := $(SVGA_MODE)
 
diff --git a/arch/x86/boot/bioscall.S b/arch/x86/boot/bioscall.S
index 5077937..1dfbf64 100644
--- a/arch/x86/boot/bioscall.S
+++ b/arch/x86/boot/bioscall.S
@@ -13,7 +13,7 @@
  * touching registers they shouldn't be.
  */
 
-	.code16
+	.code16gcc
 	.text
 	.globl	intcall
 	.type	intcall, @function
diff --git a/arch/x86/boot/compressed/Makefile b/arch/x86/boot/compressed/Makefile
index 49c8a4c..e2ff504 100644
--- a/arch/x86/boot/compressed/Makefile
+++ b/arch/x86/boot/compressed/Makefile
@@ -15,6 +15,7 @@
 KBUILD_CFLAGS += $(call cc-option,-fno-stack-protector)
 
 KBUILD_AFLAGS  := $(KBUILD_CFLAGS) -D__ASSEMBLY__
+GCOV_PROFILE := n
 
 LDFLAGS := -m elf_$(UTS_MACHINE)
 LDFLAGS_vmlinux := -T
diff --git a/arch/x86/include/asm/amd_iommu.h b/arch/x86/include/asm/amd_iommu.h
index 262e028..bdf96f1 100644
--- a/arch/x86/include/asm/amd_iommu.h
+++ b/arch/x86/include/asm/amd_iommu.h
@@ -29,9 +29,11 @@
 extern irqreturn_t amd_iommu_int_handler(int irq, void *data);
 extern void amd_iommu_flush_all_domains(void);
 extern void amd_iommu_flush_all_devices(void);
+extern void amd_iommu_shutdown(void);
 #else
 static inline int amd_iommu_init(void) { return -ENODEV; }
 static inline void amd_iommu_detect(void) { }
+static inline void amd_iommu_shutdown(void) { }
 #endif
 
 #endif /* _ASM_X86_AMD_IOMMU_H */
diff --git a/arch/x86/include/asm/atomic_32.h b/arch/x86/include/asm/atomic_32.h
index 8cb9c81..2503d4e 100644
--- a/arch/x86/include/asm/atomic_32.h
+++ b/arch/x86/include/asm/atomic_32.h
@@ -257,7 +257,7 @@
 
 /**
  * atomic64_read - read atomic64 variable
- * @v: pointer of type atomic64_t
+ * @ptr: pointer of type atomic64_t
  *
  * Atomically reads the value of @v.
  * Doesn't imply a read memory barrier.
@@ -294,7 +294,6 @@
  * atomic64_xchg - xchg atomic64 variable
  * @ptr:      pointer to type atomic64_t
  * @new_val:  value to assign
- * @old_val:  old value that was there
  *
  * Atomically xchgs the value of @ptr to @new_val and returns
  * the old value.
diff --git a/arch/x86/include/asm/desc.h b/arch/x86/include/asm/desc.h
index c45f415..c993e9e 100644
--- a/arch/x86/include/asm/desc.h
+++ b/arch/x86/include/asm/desc.h
@@ -1,7 +1,6 @@
 #ifndef _ASM_X86_DESC_H
 #define _ASM_X86_DESC_H
 
-#ifndef __ASSEMBLY__
 #include <asm/desc_defs.h>
 #include <asm/ldt.h>
 #include <asm/mmu.h>
@@ -380,29 +379,4 @@
 	_set_gate(n, GATE_INTERRUPT, addr, 0x3, ist, __KERNEL_CS);
 }
 
-#else
-/*
- * GET_DESC_BASE reads the descriptor base of the specified segment.
- *
- * Args:
- *    idx - descriptor index
- *    gdt - GDT pointer
- *    base - 32bit register to which the base will be written
- *    lo_w - lo word of the "base" register
- *    lo_b - lo byte of the "base" register
- *    hi_b - hi byte of the low word of the "base" register
- *
- * Example:
- *    GET_DESC_BASE(GDT_ENTRY_ESPFIX_SS, %ebx, %eax, %ax, %al, %ah)
- *    Will read the base address of GDT_ENTRY_ESPFIX_SS and put it into %eax.
- */
-#define GET_DESC_BASE(idx, gdt, base, lo_w, lo_b, hi_b) \
-	movb idx * 8 + 4(gdt), lo_b;			\
-	movb idx * 8 + 7(gdt), hi_b;			\
-	shll $16, base;					\
-	movw idx * 8 + 2(gdt), lo_w;
-
-
-#endif /* __ASSEMBLY__ */
-
 #endif /* _ASM_X86_DESC_H */
diff --git a/arch/x86/include/asm/dma-mapping.h b/arch/x86/include/asm/dma-mapping.h
index b93405b..1c3f943 100644
--- a/arch/x86/include/asm/dma-mapping.h
+++ b/arch/x86/include/asm/dma-mapping.h
@@ -33,6 +33,8 @@
 #endif
 }
 
+#include <asm-generic/dma-mapping-common.h>
+
 /* Make sure we keep the same behaviour */
 static inline int dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
 {
@@ -53,177 +55,6 @@
 extern void *dma_generic_alloc_coherent(struct device *dev, size_t size,
 					dma_addr_t *dma_addr, gfp_t flag);
 
-static inline dma_addr_t
-dma_map_single(struct device *hwdev, void *ptr, size_t size,
-	       enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(hwdev);
-	dma_addr_t addr;
-
-	BUG_ON(!valid_dma_direction(dir));
-	kmemcheck_mark_initialized(ptr, size);
-	addr = ops->map_page(hwdev, virt_to_page(ptr),
-			     (unsigned long)ptr & ~PAGE_MASK, size,
-			     dir, NULL);
-	debug_dma_map_page(hwdev, virt_to_page(ptr),
-			   (unsigned long)ptr & ~PAGE_MASK, size,
-			   dir, addr, true);
-	return addr;
-}
-
-static inline void
-dma_unmap_single(struct device *dev, dma_addr_t addr, size_t size,
-		 enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(dev);
-
-	BUG_ON(!valid_dma_direction(dir));
-	if (ops->unmap_page)
-		ops->unmap_page(dev, addr, size, dir, NULL);
-	debug_dma_unmap_page(dev, addr, size, dir, true);
-}
-
-static inline int
-dma_map_sg(struct device *hwdev, struct scatterlist *sg,
-	   int nents, enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(hwdev);
-	int ents;
-	struct scatterlist *s;
-	int i;
-
-	BUG_ON(!valid_dma_direction(dir));
-	for_each_sg(sg, s, nents, i)
-		kmemcheck_mark_initialized(sg_virt(s), s->length);
-	ents = ops->map_sg(hwdev, sg, nents, dir, NULL);
-	debug_dma_map_sg(hwdev, sg, nents, ents, dir);
-
-	return ents;
-}
-
-static inline void
-dma_unmap_sg(struct device *hwdev, struct scatterlist *sg, int nents,
-	     enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(hwdev);
-
-	BUG_ON(!valid_dma_direction(dir));
-	debug_dma_unmap_sg(hwdev, sg, nents, dir);
-	if (ops->unmap_sg)
-		ops->unmap_sg(hwdev, sg, nents, dir, NULL);
-}
-
-static inline void
-dma_sync_single_for_cpu(struct device *hwdev, dma_addr_t dma_handle,
-			size_t size, enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(hwdev);
-
-	BUG_ON(!valid_dma_direction(dir));
-	if (ops->sync_single_for_cpu)
-		ops->sync_single_for_cpu(hwdev, dma_handle, size, dir);
-	debug_dma_sync_single_for_cpu(hwdev, dma_handle, size, dir);
-	flush_write_buffers();
-}
-
-static inline void
-dma_sync_single_for_device(struct device *hwdev, dma_addr_t dma_handle,
-			   size_t size, enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(hwdev);
-
-	BUG_ON(!valid_dma_direction(dir));
-	if (ops->sync_single_for_device)
-		ops->sync_single_for_device(hwdev, dma_handle, size, dir);
-	debug_dma_sync_single_for_device(hwdev, dma_handle, size, dir);
-	flush_write_buffers();
-}
-
-static inline void
-dma_sync_single_range_for_cpu(struct device *hwdev, dma_addr_t dma_handle,
-			      unsigned long offset, size_t size,
-			      enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(hwdev);
-
-	BUG_ON(!valid_dma_direction(dir));
-	if (ops->sync_single_range_for_cpu)
-		ops->sync_single_range_for_cpu(hwdev, dma_handle, offset,
-					       size, dir);
-	debug_dma_sync_single_range_for_cpu(hwdev, dma_handle,
-					    offset, size, dir);
-	flush_write_buffers();
-}
-
-static inline void
-dma_sync_single_range_for_device(struct device *hwdev, dma_addr_t dma_handle,
-				 unsigned long offset, size_t size,
-				 enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(hwdev);
-
-	BUG_ON(!valid_dma_direction(dir));
-	if (ops->sync_single_range_for_device)
-		ops->sync_single_range_for_device(hwdev, dma_handle,
-						  offset, size, dir);
-	debug_dma_sync_single_range_for_device(hwdev, dma_handle,
-					       offset, size, dir);
-	flush_write_buffers();
-}
-
-static inline void
-dma_sync_sg_for_cpu(struct device *hwdev, struct scatterlist *sg,
-		    int nelems, enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(hwdev);
-
-	BUG_ON(!valid_dma_direction(dir));
-	if (ops->sync_sg_for_cpu)
-		ops->sync_sg_for_cpu(hwdev, sg, nelems, dir);
-	debug_dma_sync_sg_for_cpu(hwdev, sg, nelems, dir);
-	flush_write_buffers();
-}
-
-static inline void
-dma_sync_sg_for_device(struct device *hwdev, struct scatterlist *sg,
-		       int nelems, enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(hwdev);
-
-	BUG_ON(!valid_dma_direction(dir));
-	if (ops->sync_sg_for_device)
-		ops->sync_sg_for_device(hwdev, sg, nelems, dir);
-	debug_dma_sync_sg_for_device(hwdev, sg, nelems, dir);
-
-	flush_write_buffers();
-}
-
-static inline dma_addr_t dma_map_page(struct device *dev, struct page *page,
-				      size_t offset, size_t size,
-				      enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(dev);
-	dma_addr_t addr;
-
-	BUG_ON(!valid_dma_direction(dir));
-	kmemcheck_mark_initialized(page_address(page) + offset, size);
-	addr = ops->map_page(dev, page, offset, size, dir, NULL);
-	debug_dma_map_page(dev, page, offset, size, dir, addr, false);
-
-	return addr;
-}
-
-static inline void dma_unmap_page(struct device *dev, dma_addr_t addr,
-				  size_t size, enum dma_data_direction dir)
-{
-	struct dma_map_ops *ops = get_dma_ops(dev);
-
-	BUG_ON(!valid_dma_direction(dir));
-	if (ops->unmap_page)
-		ops->unmap_page(dev, addr, size, dir, NULL);
-	debug_dma_unmap_page(dev, addr, size, dir, false);
-}
-
 static inline void
 dma_cache_sync(struct device *dev, void *vaddr, size_t size,
 	enum dma_data_direction dir)
diff --git a/arch/x86/include/asm/mce.h b/arch/x86/include/asm/mce.h
index 540a466..5cdd8d1 100644
--- a/arch/x86/include/asm/mce.h
+++ b/arch/x86/include/asm/mce.h
@@ -102,15 +102,39 @@
 
 #ifdef __KERNEL__
 
-extern int mce_disabled;
-
-#include <asm/atomic.h>
 #include <linux/percpu.h>
+#include <linux/init.h>
+#include <asm/atomic.h>
+
+extern int mce_disabled;
+extern int mce_p5_enabled;
+
+#ifdef CONFIG_X86_MCE
+void mcheck_init(struct cpuinfo_x86 *c);
+#else
+static inline void mcheck_init(struct cpuinfo_x86 *c) {}
+#endif
+
+#ifdef CONFIG_X86_OLD_MCE
+extern int nr_mce_banks;
+void amd_mcheck_init(struct cpuinfo_x86 *c);
+void intel_p4_mcheck_init(struct cpuinfo_x86 *c);
+void intel_p6_mcheck_init(struct cpuinfo_x86 *c);
+#endif
+
+#ifdef CONFIG_X86_ANCIENT_MCE
+void intel_p5_mcheck_init(struct cpuinfo_x86 *c);
+void winchip_mcheck_init(struct cpuinfo_x86 *c);
+static inline void enable_p5_mce(void) { mce_p5_enabled = 1; }
+#else
+static inline void intel_p5_mcheck_init(struct cpuinfo_x86 *c) {}
+static inline void winchip_mcheck_init(struct cpuinfo_x86 *c) {}
+static inline void enable_p5_mce(void) {}
+#endif
 
 void mce_setup(struct mce *m);
 void mce_log(struct mce *m);
 DECLARE_PER_CPU(struct sys_device, mce_dev);
-extern void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
 
 /*
  * To support more than 128 would need to escape the predefined
@@ -145,12 +169,8 @@
 DECLARE_PER_CPU(unsigned, mce_exception_count);
 DECLARE_PER_CPU(unsigned, mce_poll_count);
 
-void mce_log_therm_throt_event(__u64 status);
-
 extern atomic_t mce_entry;
 
-void do_machine_check(struct pt_regs *, long);
-
 typedef DECLARE_BITMAP(mce_banks_t, MAX_NR_BANKS);
 DECLARE_PER_CPU(mce_banks_t, mce_poll_banks);
 
@@ -167,13 +187,32 @@
 DECLARE_PER_CPU(struct mce, injectm);
 extern struct file_operations mce_chrdev_ops;
 
-#ifdef CONFIG_X86_MCE
-void mcheck_init(struct cpuinfo_x86 *c);
-#else
-#define mcheck_init(c) do { } while (0)
-#endif
+/*
+ * Exception handler
+ */
+
+/* Call the installed machine check handler for this CPU setup. */
+extern void (*machine_check_vector)(struct pt_regs *, long error_code);
+void do_machine_check(struct pt_regs *, long);
+
+/*
+ * Threshold handler
+ */
 
 extern void (*mce_threshold_vector)(void);
+extern void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
+
+/*
+ * Thermal handler
+ */
+
+void intel_init_thermal(struct cpuinfo_x86 *c);
+
+#ifdef CONFIG_X86_NEW_MCE
+void mce_log_therm_throt_event(__u64 status);
+#else
+static inline void mce_log_therm_throt_event(__u64 status) {}
+#endif
 
 #endif /* __KERNEL__ */
 #endif /* _ASM_X86_MCE_H */
diff --git a/arch/x86/include/asm/msr.h b/arch/x86/include/asm/msr.h
index 2260376..48ad9d2 100644
--- a/arch/x86/include/asm/msr.h
+++ b/arch/x86/include/asm/msr.h
@@ -3,13 +3,10 @@
 
 #include <asm/msr-index.h>
 
-#ifndef __ASSEMBLY__
-# include <linux/types.h>
-#endif
-
 #ifdef __KERNEL__
 #ifndef __ASSEMBLY__
 
+#include <linux/types.h>
 #include <asm/asm.h>
 #include <asm/errno.h>
 #include <asm/cpumask.h>
@@ -264,6 +261,4 @@
 #endif  /* CONFIG_SMP */
 #endif /* __ASSEMBLY__ */
 #endif /* __KERNEL__ */
-
-
 #endif /* _ASM_X86_MSR_H */
diff --git a/arch/x86/include/asm/therm_throt.h b/arch/x86/include/asm/therm_throt.h
deleted file mode 100644
index c62349e..0000000
--- a/arch/x86/include/asm/therm_throt.h
+++ /dev/null
@@ -1,9 +0,0 @@
-#ifndef _ASM_X86_THERM_THROT_H
-#define _ASM_X86_THERM_THROT_H
-
-#include <asm/atomic.h>
-
-extern atomic_t therm_throt_en;
-int therm_throt_process(int curr);
-
-#endif /* _ASM_X86_THERM_THROT_H */
diff --git a/arch/x86/include/asm/timer.h b/arch/x86/include/asm/timer.h
index bd37ed4..20ca9c4 100644
--- a/arch/x86/include/asm/timer.h
+++ b/arch/x86/include/asm/timer.h
@@ -45,12 +45,16 @@
  */
 
 DECLARE_PER_CPU(unsigned long, cyc2ns);
+DECLARE_PER_CPU(unsigned long long, cyc2ns_offset);
 
 #define CYC2NS_SCALE_FACTOR 10 /* 2^10, carefully chosen */
 
 static inline unsigned long long __cycles_2_ns(unsigned long long cyc)
 {
-	return cyc * per_cpu(cyc2ns, smp_processor_id()) >> CYC2NS_SCALE_FACTOR;
+	int cpu = smp_processor_id();
+	unsigned long long ns = per_cpu(cyc2ns_offset, cpu);
+	ns += cyc * per_cpu(cyc2ns, cpu) >> CYC2NS_SCALE_FACTOR;
+	return ns;
 }
 
 static inline unsigned long long cycles_2_ns(unsigned long long cyc)
diff --git a/arch/x86/kernel/Makefile b/arch/x86/kernel/Makefile
index f3477bb..6c327b8 100644
--- a/arch/x86/kernel/Makefile
+++ b/arch/x86/kernel/Makefile
@@ -24,6 +24,8 @@
 CFLAGS_hpet.o		:= $(nostackp)
 CFLAGS_tsc.o		:= $(nostackp)
 CFLAGS_paravirt.o	:= $(nostackp)
+GCOV_PROFILE_vsyscall_64.o	:= n
+GCOV_PROFILE_hpet.o		:= n
 
 obj-y			:= process_$(BITS).o signal.o entry_$(BITS).o
 obj-y			+= traps.o irq.o irq_$(BITS).o dumpstack_$(BITS).o
diff --git a/arch/x86/kernel/acpi/realmode/Makefile b/arch/x86/kernel/acpi/realmode/Makefile
index 167bc16..6a564ac 100644
--- a/arch/x86/kernel/acpi/realmode/Makefile
+++ b/arch/x86/kernel/acpi/realmode/Makefile
@@ -42,6 +42,7 @@
 		   $(call cc-option, -mpreferred-stack-boundary=2)
 KBUILD_CFLAGS	+= $(call cc-option, -m32)
 KBUILD_AFLAGS	:= $(KBUILD_CFLAGS) -D__ASSEMBLY__
+GCOV_PROFILE := n
 
 WAKEUP_OBJS = $(addprefix $(obj)/,$(wakeup-y))
 
diff --git a/arch/x86/kernel/amd_iommu.c b/arch/x86/kernel/amd_iommu.c
index 1c60554..9372f04 100644
--- a/arch/x86/kernel/amd_iommu.c
+++ b/arch/x86/kernel/amd_iommu.c
@@ -434,6 +434,16 @@
 	iommu_queue_inv_iommu_pages(iommu, address, domid, 0, 1);
 }
 
+/* Flush the whole IO/TLB for a given protection domain - including PDE */
+static void iommu_flush_tlb_pde(struct amd_iommu *iommu, u16 domid)
+{
+       u64 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
+
+       INC_STATS_COUNTER(domain_flush_single);
+
+       iommu_queue_inv_iommu_pages(iommu, address, domid, 1, 1);
+}
+
 /*
  * This function is used to flush the IO/TLB for a given protection domain
  * on every IOMMU in the system
@@ -1078,7 +1088,13 @@
 	amd_iommu_pd_table[devid] = domain;
 	write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
 
+       /*
+        * We might boot into a crash-kernel here. The crashed kernel
+        * left the caches in the IOMMU dirty. So we have to flush
+        * here to evict all dirty stuff.
+        */
 	iommu_queue_inv_dev_entry(iommu, devid);
+	iommu_flush_tlb_pde(iommu, domain->id);
 }
 
 /*
diff --git a/arch/x86/kernel/amd_iommu_init.c b/arch/x86/kernel/amd_iommu_init.c
index 238989e..10b2acc 100644
--- a/arch/x86/kernel/amd_iommu_init.c
+++ b/arch/x86/kernel/amd_iommu_init.c
@@ -260,6 +260,14 @@
 
 static void iommu_disable(struct amd_iommu *iommu)
 {
+	/* Disable command buffer */
+	iommu_feature_disable(iommu, CONTROL_CMDBUF_EN);
+
+	/* Disable event logging and event interrupts */
+	iommu_feature_disable(iommu, CONTROL_EVT_INT_EN);
+	iommu_feature_disable(iommu, CONTROL_EVT_LOG_EN);
+
+	/* Disable IOMMU hardware itself */
 	iommu_feature_disable(iommu, CONTROL_IOMMU_EN);
 }
 
@@ -478,6 +486,10 @@
 	memcpy_toio(iommu->mmio_base + MMIO_EVT_BUF_OFFSET,
 		    &entry, sizeof(entry));
 
+	/* set head and tail to zero manually */
+	writel(0x00, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
+	writel(0x00, iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
+
 	iommu_feature_enable(iommu, CONTROL_EVT_LOG_EN);
 }
 
@@ -1042,6 +1054,7 @@
 	struct amd_iommu *iommu;
 
 	for_each_iommu(iommu) {
+		iommu_disable(iommu);
 		iommu_set_device_table(iommu);
 		iommu_enable_command_buffer(iommu);
 		iommu_enable_event_buffer(iommu);
@@ -1066,12 +1079,6 @@
 
 static int amd_iommu_resume(struct sys_device *dev)
 {
-	/*
-	 * Disable IOMMUs before reprogramming the hardware registers.
-	 * IOMMU is still enabled from the resume kernel.
-	 */
-	disable_iommus();
-
 	/* re-load the hardware */
 	enable_iommus();
 
@@ -1079,8 +1086,8 @@
 	 * we have to flush after the IOMMUs are enabled because a
 	 * disabled IOMMU will never execute the commands we send
 	 */
-	amd_iommu_flush_all_domains();
 	amd_iommu_flush_all_devices();
+	amd_iommu_flush_all_domains();
 
 	return 0;
 }
@@ -1273,6 +1280,11 @@
 	goto out;
 }
 
+void amd_iommu_shutdown(void)
+{
+	disable_iommus();
+}
+
 /****************************************************************************
  *
  * Early detect code. This code runs at IOMMU detection time in the DMA
diff --git a/arch/x86/kernel/apic/io_apic.c b/arch/x86/kernel/apic/io_apic.c
index ef8d929..b7a7920 100644
--- a/arch/x86/kernel/apic/io_apic.c
+++ b/arch/x86/kernel/apic/io_apic.c
@@ -462,7 +462,8 @@
 static void
 __ioapic_write_entry(int apic, int pin, struct IO_APIC_route_entry e)
 {
-	union entry_union eu;
+	union entry_union eu = {{0, 0}};
+
 	eu.entry = e;
 	io_apic_write(apic, 0x11 + 2*pin, eu.w2);
 	io_apic_write(apic, 0x10 + 2*pin, eu.w1);
@@ -2003,7 +2004,9 @@
 	/*
 	 * Use virtual wire A mode when interrupt remapping is enabled.
 	 */
-	disconnect_bsp_APIC(!intr_remapping_enabled && ioapic_i8259.pin != -1);
+	if (cpu_has_apic)
+		disconnect_bsp_APIC(!intr_remapping_enabled &&
+				ioapic_i8259.pin != -1);
 }
 
 #ifdef CONFIG_X86_32
@@ -3567,7 +3570,7 @@
 
 #endif /* CONFIG_SMP */
 
-struct irq_chip dmar_msi_type = {
+static struct irq_chip dmar_msi_type = {
 	.name = "DMAR_MSI",
 	.unmask = dmar_msi_unmask,
 	.mask = dmar_msi_mask,
diff --git a/arch/x86/kernel/apic/probe_32.c b/arch/x86/kernel/apic/probe_32.c
index 440a8bc..0c0182c 100644
--- a/arch/x86/kernel/apic/probe_32.c
+++ b/arch/x86/kernel/apic/probe_32.c
@@ -20,23 +20,12 @@
 #include <asm/apic.h>
 #include <asm/setup.h>
 
-#include <linux/threads.h>
-#include <linux/cpumask.h>
-#include <asm/mpspec.h>
-#include <asm/fixmap.h>
-#include <asm/apicdef.h>
-#include <linux/kernel.h>
-#include <linux/string.h>
 #include <linux/smp.h>
-#include <linux/init.h>
 #include <asm/ipi.h>
 
-#include <linux/smp.h>
-#include <linux/init.h>
 #include <linux/interrupt.h>
 #include <asm/acpi.h>
 #include <asm/e820.h>
-#include <asm/setup.h>
 
 #ifdef CONFIG_HOTPLUG_CPU
 #define DEFAULT_SEND_IPI	(1)
diff --git a/arch/x86/kernel/apic/summit_32.c b/arch/x86/kernel/apic/summit_32.c
index 344eee4..eafdfbd1 100644
--- a/arch/x86/kernel/apic/summit_32.c
+++ b/arch/x86/kernel/apic/summit_32.c
@@ -44,7 +44,6 @@
 #include <asm/ipi.h>
 #include <linux/kernel.h>
 #include <linux/string.h>
-#include <linux/init.h>
 #include <linux/gfp.h>
 #include <linux/smp.h>
 
diff --git a/arch/x86/kernel/cpu/common.c b/arch/x86/kernel/cpu/common.c
index 9fa3388..6b26d4d 100644
--- a/arch/x86/kernel/cpu/common.c
+++ b/arch/x86/kernel/cpu/common.c
@@ -108,7 +108,7 @@
 	/* data */
 	[GDT_ENTRY_APMBIOS_BASE+2]	= { { { 0x0000ffff, 0x00409200 } } },
 
-	[GDT_ENTRY_ESPFIX_SS]		= { { { 0x00000000, 0x00c09200 } } },
+	[GDT_ENTRY_ESPFIX_SS]		= { { { 0x0000ffff, 0x00cf9200 } } },
 	[GDT_ENTRY_PERCPU]		= { { { 0x0000ffff, 0x00cf9200 } } },
 	GDT_STACK_CANARY_INIT
 #endif
@@ -848,6 +848,9 @@
 #if defined(CONFIG_NUMA) && defined(CONFIG_X86_64)
 	numa_add_cpu(smp_processor_id());
 #endif
+
+	/* Cap the iomem address space to what is addressable on all CPUs */
+	iomem_resource.end &= (1ULL << c->x86_phys_bits) - 1;
 }
 
 #ifdef CONFIG_X86_64
diff --git a/arch/x86/kernel/cpu/cpufreq/powernow-k8.c b/arch/x86/kernel/cpu/cpufreq/powernow-k8.c
index cf52215..81cbe64 100644
--- a/arch/x86/kernel/cpu/cpufreq/powernow-k8.c
+++ b/arch/x86/kernel/cpu/cpufreq/powernow-k8.c
@@ -1,3 +1,4 @@
+
 /*
  *   (c) 2003-2006 Advanced Micro Devices, Inc.
  *  Your use of this code is subject to the terms and conditions of the
@@ -117,20 +118,17 @@
 	u32 i = 0;
 
 	if (cpu_family == CPU_HW_PSTATE) {
-		if (data->currpstate == HW_PSTATE_INVALID) {
-			/* read (initial) hw pstate if not yet set */
-			rdmsr(MSR_PSTATE_STATUS, lo, hi);
-			i = lo & HW_PSTATE_MASK;
+		rdmsr(MSR_PSTATE_STATUS, lo, hi);
+		i = lo & HW_PSTATE_MASK;
+		data->currpstate = i;
 
-			/*
-			 * a workaround for family 11h erratum 311 might cause
-			 * an "out-of-range Pstate if the core is in Pstate-0
-			 */
-			if (i >= data->numps)
-				data->currpstate = HW_PSTATE_0;
-			else
-				data->currpstate = i;
-		}
+		/*
+		 * a workaround for family 11h erratum 311 might cause
+		 * an "out-of-range Pstate if the core is in Pstate-0
+		 */
+		if ((boot_cpu_data.x86 == 0x11) && (i >= data->numps))
+			data->currpstate = HW_PSTATE_0;
+
 		return 0;
 	}
 	do {
@@ -510,41 +508,34 @@
 	return 0;
 }
 
-static int check_supported_cpu(unsigned int cpu)
+static void check_supported_cpu(void *_rc)
 {
-	cpumask_t oldmask;
 	u32 eax, ebx, ecx, edx;
-	unsigned int rc = 0;
+	int *rc = _rc;
 
-	oldmask = current->cpus_allowed;
-	set_cpus_allowed_ptr(current, &cpumask_of_cpu(cpu));
-
-	if (smp_processor_id() != cpu) {
-		printk(KERN_ERR PFX "limiting to cpu %u failed\n", cpu);
-		goto out;
-	}
+	*rc = -ENODEV;
 
 	if (current_cpu_data.x86_vendor != X86_VENDOR_AMD)
-		goto out;
+		return;
 
 	eax = cpuid_eax(CPUID_PROCESSOR_SIGNATURE);
 	if (((eax & CPUID_XFAM) != CPUID_XFAM_K8) &&
 	    ((eax & CPUID_XFAM) < CPUID_XFAM_10H))
-		goto out;
+		return;
 
 	if ((eax & CPUID_XFAM) == CPUID_XFAM_K8) {
 		if (((eax & CPUID_USE_XFAM_XMOD) != CPUID_USE_XFAM_XMOD) ||
 		    ((eax & CPUID_XMOD) > CPUID_XMOD_REV_MASK)) {
 			printk(KERN_INFO PFX
 				"Processor cpuid %x not supported\n", eax);
-			goto out;
+			return;
 		}
 
 		eax = cpuid_eax(CPUID_GET_MAX_CAPABILITIES);
 		if (eax < CPUID_FREQ_VOLT_CAPABILITIES) {
 			printk(KERN_INFO PFX
 			       "No frequency change capabilities detected\n");
-			goto out;
+			return;
 		}
 
 		cpuid(CPUID_FREQ_VOLT_CAPABILITIES, &eax, &ebx, &ecx, &edx);
@@ -552,21 +543,17 @@
 			!= P_STATE_TRANSITION_CAPABLE) {
 			printk(KERN_INFO PFX
 				"Power state transitions not supported\n");
-			goto out;
+			return;
 		}
 	} else { /* must be a HW Pstate capable processor */
 		cpuid(CPUID_FREQ_VOLT_CAPABILITIES, &eax, &ebx, &ecx, &edx);
 		if ((edx & USE_HW_PSTATE) == USE_HW_PSTATE)
 			cpu_family = CPU_HW_PSTATE;
 		else
-			goto out;
+			return;
 	}
 
-	rc = 1;
-
-out:
-	set_cpus_allowed_ptr(current, &oldmask);
-	return rc;
+	*rc = 0;
 }
 
 static int check_pst_table(struct powernow_k8_data *data, struct pst_s *pst,
@@ -823,13 +810,14 @@
 	if (!data->acpi_data.state_count || (cpu_family == CPU_HW_PSTATE))
 		return;
 
-	control = data->acpi_data.states[index].control; data->irt = (control
-			>> IRT_SHIFT) & IRT_MASK; data->rvo = (control >>
-				RVO_SHIFT) & RVO_MASK; data->exttype = (control
-					>> EXT_TYPE_SHIFT) & EXT_TYPE_MASK;
-	data->plllock = (control >> PLL_L_SHIFT) & PLL_L_MASK; data->vidmvs = 1
-		<< ((control >> MVS_SHIFT) & MVS_MASK); data->vstable =
-		(control >> VST_SHIFT) & VST_MASK; }
+	control = data->acpi_data.states[index].control;
+	data->irt = (control >> IRT_SHIFT) & IRT_MASK;
+	data->rvo = (control >> RVO_SHIFT) & RVO_MASK;
+	data->exttype = (control >> EXT_TYPE_SHIFT) & EXT_TYPE_MASK;
+	data->plllock = (control >> PLL_L_SHIFT) & PLL_L_MASK;
+	data->vidmvs = 1 << ((control >> MVS_SHIFT) & MVS_MASK);
+	data->vstable = (control >> VST_SHIFT) & VST_MASK;
+}
 
 static int powernow_k8_cpu_init_acpi(struct powernow_k8_data *data)
 {
@@ -1046,6 +1034,19 @@
 		if (cur_latency > max_latency)
 			max_latency = cur_latency;
 	}
+	if (max_latency == 0) {
+		/*
+		 * Fam 11h always returns 0 as transition latency.
+		 * This is intended and means "very fast". While cpufreq core
+		 * and governors currently can handle that gracefully, better
+		 * set it to 1 to avoid problems in the future.
+		 * For all others it's a BIOS bug.
+		 */
+		if (!boot_cpu_data.x86 == 0x11)
+			printk(KERN_ERR FW_WARN PFX "Invalid zero transition "
+				"latency\n");
+		max_latency = 1;
+	}
 	/* value in usecs, needs to be in nanoseconds */
 	return 1000 * max_latency;
 }
@@ -1093,7 +1094,7 @@
 	freqs.old = find_khz_freq_from_fid(data->currfid);
 	freqs.new = find_khz_freq_from_fid(fid);
 
-	for_each_cpu_mask_nr(i, *(data->available_cores)) {
+	for_each_cpu(i, data->available_cores) {
 		freqs.cpu = i;
 		cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
 	}
@@ -1101,7 +1102,7 @@
 	res = transition_fid_vid(data, fid, vid);
 	freqs.new = find_khz_freq_from_fid(data->currfid);
 
-	for_each_cpu_mask_nr(i, *(data->available_cores)) {
+	for_each_cpu(i, data->available_cores) {
 		freqs.cpu = i;
 		cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
 	}
@@ -1126,7 +1127,7 @@
 			data->currpstate);
 	freqs.new = find_khz_freq_from_pstate(data->powernow_table, pstate);
 
-	for_each_cpu_mask_nr(i, *(data->available_cores)) {
+	for_each_cpu(i, data->available_cores) {
 		freqs.cpu = i;
 		cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
 	}
@@ -1134,7 +1135,7 @@
 	res = transition_pstate(data, pstate);
 	freqs.new = find_khz_freq_from_pstate(data->powernow_table, pstate);
 
-	for_each_cpu_mask_nr(i, *(data->available_cores)) {
+	for_each_cpu(i, data->available_cores) {
 		freqs.cpu = i;
 		cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
 	}
@@ -1235,21 +1236,47 @@
 	return cpufreq_frequency_table_verify(pol, data->powernow_table);
 }
 
-static const char ACPI_PSS_BIOS_BUG_MSG[] =
-	KERN_ERR FW_BUG PFX "No compatible ACPI _PSS objects found.\n"
-	KERN_ERR FW_BUG PFX "Try again with latest BIOS.\n";
+struct init_on_cpu {
+	struct powernow_k8_data *data;
+	int rc;
+};
+
+static void __cpuinit powernowk8_cpu_init_on_cpu(void *_init_on_cpu)
+{
+	struct init_on_cpu *init_on_cpu = _init_on_cpu;
+
+	if (pending_bit_stuck()) {
+		printk(KERN_ERR PFX "failing init, change pending bit set\n");
+		init_on_cpu->rc = -ENODEV;
+		return;
+	}
+
+	if (query_current_values_with_pending_wait(init_on_cpu->data)) {
+		init_on_cpu->rc = -ENODEV;
+		return;
+	}
+
+	if (cpu_family == CPU_OPTERON)
+		fidvid_msr_init();
+
+	init_on_cpu->rc = 0;
+}
 
 /* per CPU init entry point to the driver */
 static int __cpuinit powernowk8_cpu_init(struct cpufreq_policy *pol)
 {
+	static const char ACPI_PSS_BIOS_BUG_MSG[] =
+		KERN_ERR FW_BUG PFX "No compatible ACPI _PSS objects found.\n"
+		KERN_ERR FW_BUG PFX "Try again with latest BIOS.\n";
 	struct powernow_k8_data *data;
-	cpumask_t oldmask;
+	struct init_on_cpu init_on_cpu;
 	int rc;
 
 	if (!cpu_online(pol->cpu))
 		return -ENODEV;
 
-	if (!check_supported_cpu(pol->cpu))
+	smp_call_function_single(pol->cpu, check_supported_cpu, &rc, 1);
+	if (rc)
 		return -ENODEV;
 
 	data = kzalloc(sizeof(struct powernow_k8_data), GFP_KERNEL);
@@ -1289,27 +1316,12 @@
 		pol->cpuinfo.transition_latency = get_transition_latency(data);
 
 	/* only run on specific CPU from here on */
-	oldmask = current->cpus_allowed;
-	set_cpus_allowed_ptr(current, &cpumask_of_cpu(pol->cpu));
-
-	if (smp_processor_id() != pol->cpu) {
-		printk(KERN_ERR PFX "limiting to cpu %u failed\n", pol->cpu);
-		goto err_out_unmask;
-	}
-
-	if (pending_bit_stuck()) {
-		printk(KERN_ERR PFX "failing init, change pending bit set\n");
-		goto err_out_unmask;
-	}
-
-	if (query_current_values_with_pending_wait(data))
-		goto err_out_unmask;
-
-	if (cpu_family == CPU_OPTERON)
-		fidvid_msr_init();
-
-	/* run on any CPU again */
-	set_cpus_allowed_ptr(current, &oldmask);
+	init_on_cpu.data = data;
+	smp_call_function_single(data->cpu, powernowk8_cpu_init_on_cpu,
+				 &init_on_cpu, 1);
+	rc = init_on_cpu.rc;
+	if (rc != 0)
+		goto err_out_exit_acpi;
 
 	if (cpu_family == CPU_HW_PSTATE)
 		cpumask_copy(pol->cpus, cpumask_of(pol->cpu));
@@ -1346,8 +1358,7 @@
 
 	return 0;
 
-err_out_unmask:
-	set_cpus_allowed_ptr(current, &oldmask);
+err_out_exit_acpi:
 	powernow_k8_cpu_exit_acpi(data);
 
 err_out:
@@ -1372,28 +1383,25 @@
 	return 0;
 }
 
+static void query_values_on_cpu(void *_err)
+{
+	int *err = _err;
+	struct powernow_k8_data *data = __get_cpu_var(powernow_data);
+
+	*err = query_current_values_with_pending_wait(data);
+}
+
 static unsigned int powernowk8_get(unsigned int cpu)
 {
-	struct powernow_k8_data *data;
-	cpumask_t oldmask = current->cpus_allowed;
+	struct powernow_k8_data *data = per_cpu(powernow_data, cpu);
 	unsigned int khz = 0;
-	unsigned int first;
-
-	first = cpumask_first(cpu_core_mask(cpu));
-	data = per_cpu(powernow_data, first);
+	int err;
 
 	if (!data)
 		return -EINVAL;
 
-	set_cpus_allowed_ptr(current, &cpumask_of_cpu(cpu));
-	if (smp_processor_id() != cpu) {
-		printk(KERN_ERR PFX
-			"limiting to CPU %d failed in powernowk8_get\n", cpu);
-		set_cpus_allowed_ptr(current, &oldmask);
-		return 0;
-	}
-
-	if (query_current_values_with_pending_wait(data))
+	smp_call_function_single(cpu, query_values_on_cpu, &err, true);
+	if (err)
 		goto out;
 
 	if (cpu_family == CPU_HW_PSTATE)
@@ -1404,7 +1412,6 @@
 
 
 out:
-	set_cpus_allowed_ptr(current, &oldmask);
 	return khz;
 }
 
@@ -1430,7 +1437,9 @@
 	unsigned int i, supported_cpus = 0;
 
 	for_each_online_cpu(i) {
-		if (check_supported_cpu(i))
+		int rc;
+		smp_call_function_single(i, check_supported_cpu, &rc, 1);
+		if (rc == 0)
 			supported_cpus++;
 	}
 
diff --git a/arch/x86/kernel/cpu/cpufreq/powernow-k8.h b/arch/x86/kernel/cpu/cpufreq/powernow-k8.h
index 6c6698f..c9c1190 100644
--- a/arch/x86/kernel/cpu/cpufreq/powernow-k8.h
+++ b/arch/x86/kernel/cpu/cpufreq/powernow-k8.h
@@ -223,14 +223,3 @@
 
 static int fill_powernow_table_pstate(struct powernow_k8_data *data, struct cpufreq_frequency_table *powernow_table);
 static int fill_powernow_table_fidvid(struct powernow_k8_data *data, struct cpufreq_frequency_table *powernow_table);
-
-#ifdef CONFIG_SMP
-static inline void define_siblings(int cpu, cpumask_t cpu_sharedcore_mask[])
-{
-}
-#else
-static inline void define_siblings(int cpu, cpumask_t cpu_sharedcore_mask[])
-{
-	cpu_set(0, cpu_sharedcore_mask[0]);
-}
-#endif
diff --git a/arch/x86/kernel/cpu/cpufreq/speedstep-centrino.c b/arch/x86/kernel/cpu/cpufreq/speedstep-centrino.c
index 55c831e..8d672ef 100644
--- a/arch/x86/kernel/cpu/cpufreq/speedstep-centrino.c
+++ b/arch/x86/kernel/cpu/cpufreq/speedstep-centrino.c
@@ -323,14 +323,8 @@
 {
 	unsigned l, h;
 	unsigned clock_freq;
-	cpumask_t saved_mask;
 
-	saved_mask = current->cpus_allowed;
-	set_cpus_allowed_ptr(current, &cpumask_of_cpu(cpu));
-	if (smp_processor_id() != cpu)
-		return 0;
-
-	rdmsr(MSR_IA32_PERF_STATUS, l, h);
+	rdmsr_on_cpu(cpu, MSR_IA32_PERF_STATUS, &l, &h);
 	clock_freq = extract_clock(l, cpu, 0);
 
 	if (unlikely(clock_freq == 0)) {
@@ -340,11 +334,9 @@
 		 * P-state transition (like TM2). Get the last freq set 
 		 * in PERF_CTL.
 		 */
-		rdmsr(MSR_IA32_PERF_CTL, l, h);
+		rdmsr_on_cpu(cpu, MSR_IA32_PERF_CTL, &l, &h);
 		clock_freq = extract_clock(l, cpu, 1);
 	}
-
-	set_cpus_allowed_ptr(current, &saved_mask);
 	return clock_freq;
 }
 
@@ -467,15 +459,10 @@
 	struct cpufreq_freqs	freqs;
 	int			retval = 0;
 	unsigned int		j, k, first_cpu, tmp;
-	cpumask_var_t saved_mask, covered_cpus;
+	cpumask_var_t covered_cpus;
 
-	if (unlikely(!alloc_cpumask_var(&saved_mask, GFP_KERNEL)))
+	if (unlikely(!zalloc_cpumask_var(&covered_cpus, GFP_KERNEL)))
 		return -ENOMEM;
-	if (unlikely(!zalloc_cpumask_var(&covered_cpus, GFP_KERNEL))) {
-		free_cpumask_var(saved_mask);
-		return -ENOMEM;
-	}
-	cpumask_copy(saved_mask, &current->cpus_allowed);
 
 	if (unlikely(per_cpu(centrino_model, cpu) == NULL)) {
 		retval = -ENODEV;
@@ -493,7 +480,7 @@
 
 	first_cpu = 1;
 	for_each_cpu(j, policy->cpus) {
-		const struct cpumask *mask;
+		int good_cpu;
 
 		/* cpufreq holds the hotplug lock, so we are safe here */
 		if (!cpu_online(j))
@@ -504,32 +491,30 @@
 		 * Make sure we are running on CPU that wants to change freq
 		 */
 		if (policy->shared_type == CPUFREQ_SHARED_TYPE_ANY)
-			mask = policy->cpus;
+			good_cpu = cpumask_any_and(policy->cpus,
+						   cpu_online_mask);
 		else
-			mask = cpumask_of(j);
+			good_cpu = j;
 
-		set_cpus_allowed_ptr(current, mask);
-		preempt_disable();
-		if (unlikely(!cpu_isset(smp_processor_id(), *mask))) {
+		if (good_cpu >= nr_cpu_ids) {
 			dprintk("couldn't limit to CPUs in this domain\n");
 			retval = -EAGAIN;
 			if (first_cpu) {
 				/* We haven't started the transition yet. */
-				goto migrate_end;
+				goto out;
 			}
-			preempt_enable();
 			break;
 		}
 
 		msr = per_cpu(centrino_model, cpu)->op_points[newstate].index;
 
 		if (first_cpu) {
-			rdmsr(MSR_IA32_PERF_CTL, oldmsr, h);
+			rdmsr_on_cpu(good_cpu, MSR_IA32_PERF_CTL, &oldmsr, &h);
 			if (msr == (oldmsr & 0xffff)) {
 				dprintk("no change needed - msr was and needs "
 					"to be %x\n", oldmsr);
 				retval = 0;
-				goto migrate_end;
+				goto out;
 			}
 
 			freqs.old = extract_clock(oldmsr, cpu, 0);
@@ -553,14 +538,11 @@
 			oldmsr |= msr;
 		}
 
-		wrmsr(MSR_IA32_PERF_CTL, oldmsr, h);
-		if (policy->shared_type == CPUFREQ_SHARED_TYPE_ANY) {
-			preempt_enable();
+		wrmsr_on_cpu(good_cpu, MSR_IA32_PERF_CTL, oldmsr, h);
+		if (policy->shared_type == CPUFREQ_SHARED_TYPE_ANY)
 			break;
-		}
 
-		cpu_set(j, *covered_cpus);
-		preempt_enable();
+		cpumask_set_cpu(j, covered_cpus);
 	}
 
 	for_each_cpu(k, policy->cpus) {
@@ -578,10 +560,8 @@
 		 * Best effort undo..
 		 */
 
-		for_each_cpu_mask_nr(j, *covered_cpus) {
-			set_cpus_allowed_ptr(current, &cpumask_of_cpu(j));
-			wrmsr(MSR_IA32_PERF_CTL, oldmsr, h);
-		}
+		for_each_cpu(j, covered_cpus)
+			wrmsr_on_cpu(j, MSR_IA32_PERF_CTL, oldmsr, h);
 
 		tmp = freqs.new;
 		freqs.new = freqs.old;
@@ -593,15 +573,9 @@
 			cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
 		}
 	}
-	set_cpus_allowed_ptr(current, saved_mask);
 	retval = 0;
-	goto out;
 
-migrate_end:
-	preempt_enable();
-	set_cpus_allowed_ptr(current, saved_mask);
 out:
-	free_cpumask_var(saved_mask);
 	free_cpumask_var(covered_cpus);
 	return retval;
 }
diff --git a/arch/x86/kernel/cpu/cpufreq/speedstep-ich.c b/arch/x86/kernel/cpu/cpufreq/speedstep-ich.c
index 016c1a4..6911e91 100644
--- a/arch/x86/kernel/cpu/cpufreq/speedstep-ich.c
+++ b/arch/x86/kernel/cpu/cpufreq/speedstep-ich.c
@@ -89,7 +89,8 @@
  * speedstep_set_state - set the SpeedStep state
  * @state: new processor frequency state (SPEEDSTEP_LOW or SPEEDSTEP_HIGH)
  *
- *   Tries to change the SpeedStep state.
+ *   Tries to change the SpeedStep state.  Can be called from
+ *   smp_call_function_single.
  */
 static void speedstep_set_state(unsigned int state)
 {
@@ -143,6 +144,11 @@
 	return;
 }
 
+/* Wrapper for smp_call_function_single. */
+static void _speedstep_set_state(void *_state)
+{
+	speedstep_set_state(*(unsigned int *)_state);
+}
 
 /**
  * speedstep_activate - activate SpeedStep control in the chipset
@@ -226,22 +232,28 @@
 	return 0;
 }
 
-static unsigned int _speedstep_get(const struct cpumask *cpus)
-{
+struct get_freq_data {
 	unsigned int speed;
-	cpumask_t cpus_allowed;
+	unsigned int processor;
+};
 
-	cpus_allowed = current->cpus_allowed;
-	set_cpus_allowed_ptr(current, cpus);
-	speed = speedstep_get_frequency(speedstep_processor);
-	set_cpus_allowed_ptr(current, &cpus_allowed);
-	dprintk("detected %u kHz as current frequency\n", speed);
-	return speed;
+static void get_freq_data(void *_data)
+{
+	struct get_freq_data *data = _data;
+
+	data->speed = speedstep_get_frequency(data->processor);
 }
 
 static unsigned int speedstep_get(unsigned int cpu)
 {
-	return _speedstep_get(cpumask_of(cpu));
+	struct get_freq_data data = { .processor = cpu };
+
+	/* You're supposed to ensure CPU is online. */
+	if (smp_call_function_single(cpu, get_freq_data, &data, 1) != 0)
+		BUG();
+
+	dprintk("detected %u kHz as current frequency\n", data.speed);
+	return data.speed;
 }
 
 /**
@@ -257,16 +269,16 @@
 			     unsigned int target_freq,
 			     unsigned int relation)
 {
-	unsigned int newstate = 0;
+	unsigned int newstate = 0, policy_cpu;
 	struct cpufreq_freqs freqs;
-	cpumask_t cpus_allowed;
 	int i;
 
 	if (cpufreq_frequency_table_target(policy, &speedstep_freqs[0],
 				target_freq, relation, &newstate))
 		return -EINVAL;
 
-	freqs.old = _speedstep_get(policy->cpus);
+	policy_cpu = cpumask_any_and(policy->cpus, cpu_online_mask);
+	freqs.old = speedstep_get(policy_cpu);
 	freqs.new = speedstep_freqs[newstate].frequency;
 	freqs.cpu = policy->cpu;
 
@@ -276,20 +288,13 @@
 	if (freqs.old == freqs.new)
 		return 0;
 
-	cpus_allowed = current->cpus_allowed;
-
 	for_each_cpu(i, policy->cpus) {
 		freqs.cpu = i;
 		cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
 	}
 
-	/* switch to physical CPU where state is to be changed */
-	set_cpus_allowed_ptr(current, policy->cpus);
-
-	speedstep_set_state(newstate);
-
-	/* allow to be run on all CPUs */
-	set_cpus_allowed_ptr(current, &cpus_allowed);
+	smp_call_function_single(policy_cpu, _speedstep_set_state, &newstate,
+				 true);
 
 	for_each_cpu(i, policy->cpus) {
 		freqs.cpu = i;
@@ -312,33 +317,43 @@
 	return cpufreq_frequency_table_verify(policy, &speedstep_freqs[0]);
 }
 
+struct get_freqs {
+	struct cpufreq_policy *policy;
+	int ret;
+};
+
+static void get_freqs_on_cpu(void *_get_freqs)
+{
+	struct get_freqs *get_freqs = _get_freqs;
+
+	get_freqs->ret =
+		speedstep_get_freqs(speedstep_processor,
+			    &speedstep_freqs[SPEEDSTEP_LOW].frequency,
+			    &speedstep_freqs[SPEEDSTEP_HIGH].frequency,
+			    &get_freqs->policy->cpuinfo.transition_latency,
+			    &speedstep_set_state);
+}
 
 static int speedstep_cpu_init(struct cpufreq_policy *policy)
 {
-	int result = 0;
-	unsigned int speed;
-	cpumask_t cpus_allowed;
+	int result;
+	unsigned int policy_cpu, speed;
+	struct get_freqs gf;
 
 	/* only run on CPU to be set, or on its sibling */
 #ifdef CONFIG_SMP
 	cpumask_copy(policy->cpus, cpu_sibling_mask(policy->cpu));
 #endif
-
-	cpus_allowed = current->cpus_allowed;
-	set_cpus_allowed_ptr(current, policy->cpus);
+	policy_cpu = cpumask_any_and(policy->cpus, cpu_online_mask);
 
 	/* detect low and high frequency and transition latency */
-	result = speedstep_get_freqs(speedstep_processor,
-				     &speedstep_freqs[SPEEDSTEP_LOW].frequency,
-				     &speedstep_freqs[SPEEDSTEP_HIGH].frequency,
-				     &policy->cpuinfo.transition_latency,
-				     &speedstep_set_state);
-	set_cpus_allowed_ptr(current, &cpus_allowed);
-	if (result)
-		return result;
+	gf.policy = policy;
+	smp_call_function_single(policy_cpu, get_freqs_on_cpu, &gf, 1);
+	if (gf.ret)
+		return gf.ret;
 
 	/* get current speed setting */
-	speed = _speedstep_get(policy->cpus);
+	speed = speedstep_get(policy_cpu);
 	if (!speed)
 		return -EIO;
 
diff --git a/arch/x86/kernel/cpu/cpufreq/speedstep-lib.c b/arch/x86/kernel/cpu/cpufreq/speedstep-lib.c
index 2e3c686..f4c290b 100644
--- a/arch/x86/kernel/cpu/cpufreq/speedstep-lib.c
+++ b/arch/x86/kernel/cpu/cpufreq/speedstep-lib.c
@@ -226,6 +226,7 @@
 }
 
 
+/* Warning: may get called from smp_call_function_single. */
 unsigned int speedstep_get_frequency(unsigned int processor)
 {
 	switch (processor) {
diff --git a/arch/x86/kernel/cpu/mcheck/Makefile b/arch/x86/kernel/cpu/mcheck/Makefile
index 45004fa..188a1ca 100644
--- a/arch/x86/kernel/cpu/mcheck/Makefile
+++ b/arch/x86/kernel/cpu/mcheck/Makefile
@@ -1,11 +1,12 @@
-obj-y				=  mce.o therm_throt.o
+obj-y				=  mce.o
 
 obj-$(CONFIG_X86_NEW_MCE)	+= mce-severity.o
 obj-$(CONFIG_X86_OLD_MCE)	+= k7.o p4.o p6.o
 obj-$(CONFIG_X86_ANCIENT_MCE)	+= winchip.o p5.o
-obj-$(CONFIG_X86_MCE_P4THERMAL)	+= mce_intel.o
-obj-$(CONFIG_X86_MCE_INTEL)	+= mce_intel_64.o mce_intel.o
-obj-$(CONFIG_X86_MCE_AMD)	+= mce_amd_64.o
+obj-$(CONFIG_X86_MCE_INTEL)	+= mce_intel.o
+obj-$(CONFIG_X86_MCE_AMD)	+= mce_amd.o
 obj-$(CONFIG_X86_MCE_NONFATAL)	+= non-fatal.o
 obj-$(CONFIG_X86_MCE_THRESHOLD) += threshold.o
 obj-$(CONFIG_X86_MCE_INJECT)	+= mce-inject.o
+
+obj-$(CONFIG_X86_THERMAL_VECTOR) += therm_throt.o
diff --git a/arch/x86/kernel/cpu/mcheck/k7.c b/arch/x86/kernel/cpu/mcheck/k7.c
index 89e5104..b945d5d 100644
--- a/arch/x86/kernel/cpu/mcheck/k7.c
+++ b/arch/x86/kernel/cpu/mcheck/k7.c
@@ -10,10 +10,9 @@
 
 #include <asm/processor.h>
 #include <asm/system.h>
+#include <asm/mce.h>
 #include <asm/msr.h>
 
-#include "mce.h"
-
 /* Machine Check Handler For AMD Athlon/Duron: */
 static void k7_machine_check(struct pt_regs *regs, long error_code)
 {
diff --git a/arch/x86/kernel/cpu/mcheck/mce.c b/arch/x86/kernel/cpu/mcheck/mce.c
index fabba15..284d1de 100644
--- a/arch/x86/kernel/cpu/mcheck/mce.c
+++ b/arch/x86/kernel/cpu/mcheck/mce.c
@@ -44,7 +44,6 @@
 #include <asm/msr.h>
 
 #include "mce-internal.h"
-#include "mce.h"
 
 /* Handle unconfigured int18 (should never happen) */
 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
@@ -57,7 +56,7 @@
 void (*machine_check_vector)(struct pt_regs *, long error_code) =
 						unexpected_machine_check;
 
-int				mce_disabled;
+int mce_disabled __read_mostly;
 
 #ifdef CONFIG_X86_NEW_MCE
 
@@ -76,21 +75,22 @@
  *   2: SIGBUS or log uncorrected errors (if possible), log corrected errors
  *   3: never panic or SIGBUS, log all errors (for testing only)
  */
-static int			tolerant = 1;
-static int			banks;
-static u64			*bank;
-static unsigned long		notify_user;
-static int			rip_msr;
-static int			mce_bootlog = -1;
-static int			monarch_timeout = -1;
-static int			mce_panic_timeout;
-static int			mce_dont_log_ce;
-int				mce_cmci_disabled;
-int				mce_ignore_ce;
-int				mce_ser;
+static int			tolerant		__read_mostly = 1;
+static int			banks			__read_mostly;
+static u64			*bank			__read_mostly;
+static int			rip_msr			__read_mostly;
+static int			mce_bootlog		__read_mostly = -1;
+static int			monarch_timeout		__read_mostly = -1;
+static int			mce_panic_timeout	__read_mostly;
+static int			mce_dont_log_ce		__read_mostly;
+int				mce_cmci_disabled	__read_mostly;
+int				mce_ignore_ce		__read_mostly;
+int				mce_ser			__read_mostly;
 
-static char			trigger[128];
-static char			*trigger_argv[2] = { trigger, NULL };
+/* User mode helper program triggered by machine check event */
+static unsigned long		mce_need_notify;
+static char			mce_helper[128];
+static char			*mce_helper_argv[2] = { mce_helper, NULL };
 
 static unsigned long		dont_init_banks;
 
@@ -180,7 +180,7 @@
 	wmb();
 
 	mce->finished = 1;
-	set_bit(0, &notify_user);
+	set_bit(0, &mce_need_notify);
 }
 
 static void print_mce(struct mce *m)
@@ -691,18 +691,21 @@
  * in the entry order.
  * TBD double check parallel CPU hotunplug
  */
-static int mce_start(int no_way_out, int *order)
+static int mce_start(int *no_way_out)
 {
-	int nwo;
+	int order;
 	int cpus = num_online_cpus();
 	u64 timeout = (u64)monarch_timeout * NSEC_PER_USEC;
 
-	if (!timeout) {
-		*order = -1;
-		return no_way_out;
-	}
+	if (!timeout)
+		return -1;
 
-	atomic_add(no_way_out, &global_nwo);
+	atomic_add(*no_way_out, &global_nwo);
+	/*
+	 * global_nwo should be updated before mce_callin
+	 */
+	smp_wmb();
+	order = atomic_add_return(1, &mce_callin);
 
 	/*
 	 * Wait for everyone.
@@ -710,40 +713,43 @@
 	while (atomic_read(&mce_callin) != cpus) {
 		if (mce_timed_out(&timeout)) {
 			atomic_set(&global_nwo, 0);
-			*order = -1;
-			return no_way_out;
+			return -1;
 		}
 		ndelay(SPINUNIT);
 	}
 
 	/*
+	 * mce_callin should be read before global_nwo
+	 */
+	smp_rmb();
+
+	if (order == 1) {
+		/*
+		 * Monarch: Starts executing now, the others wait.
+		 */
+		atomic_set(&mce_executing, 1);
+	} else {
+		/*
+		 * Subject: Now start the scanning loop one by one in
+		 * the original callin order.
+		 * This way when there are any shared banks it will be
+		 * only seen by one CPU before cleared, avoiding duplicates.
+		 */
+		while (atomic_read(&mce_executing) < order) {
+			if (mce_timed_out(&timeout)) {
+				atomic_set(&global_nwo, 0);
+				return -1;
+			}
+			ndelay(SPINUNIT);
+		}
+	}
+
+	/*
 	 * Cache the global no_way_out state.
 	 */
-	nwo = atomic_read(&global_nwo);
+	*no_way_out = atomic_read(&global_nwo);
 
-	/*
-	 * Monarch starts executing now, the others wait.
-	 */
-	if (*order == 1) {
-		atomic_set(&mce_executing, 1);
-		return nwo;
-	}
-
-	/*
-	 * Now start the scanning loop one by one
-	 * in the original callin order.
-	 * This way when there are any shared banks it will
-	 * be only seen by one CPU before cleared, avoiding duplicates.
-	 */
-	while (atomic_read(&mce_executing) < *order) {
-		if (mce_timed_out(&timeout)) {
-			atomic_set(&global_nwo, 0);
-			*order = -1;
-			return no_way_out;
-		}
-		ndelay(SPINUNIT);
-	}
-	return nwo;
+	return order;
 }
 
 /*
@@ -863,7 +869,6 @@
 	 * check handler.
 	 */
 	int order;
-
 	/*
 	 * If no_way_out gets set, there is no safe way to recover from this
 	 * MCE.  If tolerant is cranked up, we'll try anyway.
@@ -887,7 +892,6 @@
 	if (!banks)
 		goto out;
 
-	order = atomic_add_return(1, &mce_callin);
 	mce_setup(&m);
 
 	m.mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
@@ -909,7 +913,7 @@
 	 * This way we don't report duplicated events on shared banks
 	 * because the first one to see it will clear it.
 	 */
-	no_way_out = mce_start(no_way_out, &order);
+	order = mce_start(&no_way_out);
 	for (i = 0; i < banks; i++) {
 		__clear_bit(i, toclear);
 		if (!bank[i])
@@ -1118,7 +1122,7 @@
 
 static void mce_do_trigger(struct work_struct *work)
 {
-	call_usermodehelper(trigger, trigger_argv, NULL, UMH_NO_WAIT);
+	call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
 }
 
 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
@@ -1135,7 +1139,7 @@
 
 	clear_thread_flag(TIF_MCE_NOTIFY);
 
-	if (test_and_clear_bit(0, &notify_user)) {
+	if (test_and_clear_bit(0, &mce_need_notify)) {
 		wake_up_interruptible(&mce_wait);
 
 		/*
@@ -1143,7 +1147,7 @@
 		 * work_pending is always cleared before the function is
 		 * executed.
 		 */
-		if (trigger[0] && !work_pending(&mce_trigger_work))
+		if (mce_helper[0] && !work_pending(&mce_trigger_work))
 			schedule_work(&mce_trigger_work);
 
 		if (__ratelimit(&ratelimit))
@@ -1245,7 +1249,7 @@
 		 * Various K7s with broken bank 0 around. Always disable
 		 * by default.
 		 */
-		 if (c->x86 == 6)
+		 if (c->x86 == 6 && banks > 0)
 			bank[0] = 0;
 	}
 
@@ -1282,8 +1286,7 @@
 		return;
 	switch (c->x86_vendor) {
 	case X86_VENDOR_INTEL:
-		if (mce_p5_enabled())
-			intel_p5_mcheck_init(c);
+		intel_p5_mcheck_init(c);
 		break;
 	case X86_VENDOR_CENTAUR:
 		winchip_mcheck_init(c);
@@ -1609,8 +1612,9 @@
 static void mce_cpu_restart(void *data)
 {
 	del_timer_sync(&__get_cpu_var(mce_timer));
-	if (mce_available(&current_cpu_data))
-		mce_init();
+	if (!mce_available(&current_cpu_data))
+		return;
+	mce_init();
 	mce_init_timer();
 }
 
@@ -1620,6 +1624,26 @@
 	on_each_cpu(mce_cpu_restart, NULL, 1);
 }
 
+/* Toggle features for corrected errors */
+static void mce_disable_ce(void *all)
+{
+	if (!mce_available(&current_cpu_data))
+		return;
+	if (all)
+		del_timer_sync(&__get_cpu_var(mce_timer));
+	cmci_clear();
+}
+
+static void mce_enable_ce(void *all)
+{
+	if (!mce_available(&current_cpu_data))
+		return;
+	cmci_reenable();
+	cmci_recheck();
+	if (all)
+		mce_init_timer();
+}
+
 static struct sysdev_class mce_sysclass = {
 	.suspend	= mce_suspend,
 	.shutdown	= mce_shutdown,
@@ -1659,9 +1683,9 @@
 static ssize_t
 show_trigger(struct sys_device *s, struct sysdev_attribute *attr, char *buf)
 {
-	strcpy(buf, trigger);
+	strcpy(buf, mce_helper);
 	strcat(buf, "\n");
-	return strlen(trigger) + 1;
+	return strlen(mce_helper) + 1;
 }
 
 static ssize_t set_trigger(struct sys_device *s, struct sysdev_attribute *attr,
@@ -1670,10 +1694,10 @@
 	char *p;
 	int len;
 
-	strncpy(trigger, buf, sizeof(trigger));
-	trigger[sizeof(trigger)-1] = 0;
-	len = strlen(trigger);
-	p = strchr(trigger, '\n');
+	strncpy(mce_helper, buf, sizeof(mce_helper));
+	mce_helper[sizeof(mce_helper)-1] = 0;
+	len = strlen(mce_helper);
+	p = strchr(mce_helper, '\n');
 
 	if (*p)
 		*p = 0;
@@ -1681,6 +1705,52 @@
 	return len;
 }
 
+static ssize_t set_ignore_ce(struct sys_device *s,
+			     struct sysdev_attribute *attr,
+			     const char *buf, size_t size)
+{
+	u64 new;
+
+	if (strict_strtoull(buf, 0, &new) < 0)
+		return -EINVAL;
+
+	if (mce_ignore_ce ^ !!new) {
+		if (new) {
+			/* disable ce features */
+			on_each_cpu(mce_disable_ce, (void *)1, 1);
+			mce_ignore_ce = 1;
+		} else {
+			/* enable ce features */
+			mce_ignore_ce = 0;
+			on_each_cpu(mce_enable_ce, (void *)1, 1);
+		}
+	}
+	return size;
+}
+
+static ssize_t set_cmci_disabled(struct sys_device *s,
+				 struct sysdev_attribute *attr,
+				 const char *buf, size_t size)
+{
+	u64 new;
+
+	if (strict_strtoull(buf, 0, &new) < 0)
+		return -EINVAL;
+
+	if (mce_cmci_disabled ^ !!new) {
+		if (new) {
+			/* disable cmci */
+			on_each_cpu(mce_disable_ce, NULL, 1);
+			mce_cmci_disabled = 1;
+		} else {
+			/* enable cmci */
+			mce_cmci_disabled = 0;
+			on_each_cpu(mce_enable_ce, NULL, 1);
+		}
+	}
+	return size;
+}
+
 static ssize_t store_int_with_restart(struct sys_device *s,
 				      struct sysdev_attribute *attr,
 				      const char *buf, size_t size)
@@ -1693,6 +1763,7 @@
 static SYSDEV_ATTR(trigger, 0644, show_trigger, set_trigger);
 static SYSDEV_INT_ATTR(tolerant, 0644, tolerant);
 static SYSDEV_INT_ATTR(monarch_timeout, 0644, monarch_timeout);
+static SYSDEV_INT_ATTR(dont_log_ce, 0644, mce_dont_log_ce);
 
 static struct sysdev_ext_attribute attr_check_interval = {
 	_SYSDEV_ATTR(check_interval, 0644, sysdev_show_int,
@@ -1700,9 +1771,24 @@
 	&check_interval
 };
 
+static struct sysdev_ext_attribute attr_ignore_ce = {
+	_SYSDEV_ATTR(ignore_ce, 0644, sysdev_show_int, set_ignore_ce),
+	&mce_ignore_ce
+};
+
+static struct sysdev_ext_attribute attr_cmci_disabled = {
+	_SYSDEV_ATTR(cmci_disabled, 0644, sysdev_show_int, set_cmci_disabled),
+	&mce_cmci_disabled
+};
+
 static struct sysdev_attribute *mce_attrs[] = {
-	&attr_tolerant.attr, &attr_check_interval.attr, &attr_trigger,
+	&attr_tolerant.attr,
+	&attr_check_interval.attr,
+	&attr_trigger,
 	&attr_monarch_timeout.attr,
+	&attr_dont_log_ce.attr,
+	&attr_ignore_ce.attr,
+	&attr_cmci_disabled.attr,
 	NULL
 };
 
@@ -1712,7 +1798,7 @@
 static __cpuinit int mce_create_device(unsigned int cpu)
 {
 	int err;
-	int i;
+	int i, j;
 
 	if (!mce_available(&boot_cpu_data))
 		return -EIO;
@@ -1730,9 +1816,9 @@
 		if (err)
 			goto error;
 	}
-	for (i = 0; i < banks; i++) {
+	for (j = 0; j < banks; j++) {
 		err = sysdev_create_file(&per_cpu(mce_dev, cpu),
-					&bank_attrs[i]);
+					&bank_attrs[j]);
 		if (err)
 			goto error2;
 	}
@@ -1740,8 +1826,8 @@
 
 	return 0;
 error2:
-	while (--i >= 0)
-		sysdev_remove_file(&per_cpu(mce_dev, cpu), &bank_attrs[i]);
+	while (--j >= 0)
+		sysdev_remove_file(&per_cpu(mce_dev, cpu), &bank_attrs[j]);
 error:
 	while (--i >= 0)
 		sysdev_remove_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
@@ -1883,7 +1969,7 @@
 	if (!mce_available(&boot_cpu_data))
 		return -EIO;
 
-	alloc_cpumask_var(&mce_dev_initialized, GFP_KERNEL);
+	zalloc_cpumask_var(&mce_dev_initialized, GFP_KERNEL);
 
 	err = mce_init_banks();
 	if (err)
@@ -1915,7 +2001,7 @@
 /* This has to be run for each processor */
 void mcheck_init(struct cpuinfo_x86 *c)
 {
-	if (mce_disabled == 1)
+	if (mce_disabled)
 		return;
 
 	switch (c->x86_vendor) {
@@ -1945,10 +2031,9 @@
 
 static int __init mcheck_enable(char *str)
 {
-	mce_disabled = -1;
+	mce_p5_enabled = 1;
 	return 1;
 }
-
 __setup("mce", mcheck_enable);
 
 #endif /* CONFIG_X86_OLD_MCE */
diff --git a/arch/x86/kernel/cpu/mcheck/mce.h b/arch/x86/kernel/cpu/mcheck/mce.h
deleted file mode 100644
index 84a552b..0000000
--- a/arch/x86/kernel/cpu/mcheck/mce.h
+++ /dev/null
@@ -1,38 +0,0 @@
-#include <linux/init.h>
-#include <asm/mce.h>
-
-#ifdef CONFIG_X86_OLD_MCE
-void amd_mcheck_init(struct cpuinfo_x86 *c);
-void intel_p4_mcheck_init(struct cpuinfo_x86 *c);
-void intel_p6_mcheck_init(struct cpuinfo_x86 *c);
-#endif
-
-#ifdef CONFIG_X86_ANCIENT_MCE
-void intel_p5_mcheck_init(struct cpuinfo_x86 *c);
-void winchip_mcheck_init(struct cpuinfo_x86 *c);
-extern int mce_p5_enable;
-static inline int mce_p5_enabled(void) { return mce_p5_enable; }
-static inline void enable_p5_mce(void) { mce_p5_enable = 1; }
-#else
-static inline void intel_p5_mcheck_init(struct cpuinfo_x86 *c) {}
-static inline void winchip_mcheck_init(struct cpuinfo_x86 *c) {}
-static inline int mce_p5_enabled(void) { return 0; }
-static inline void enable_p5_mce(void) { }
-#endif
-
-/* Call the installed machine check handler for this CPU setup. */
-extern void (*machine_check_vector)(struct pt_regs *, long error_code);
-
-#ifdef CONFIG_X86_OLD_MCE
-
-extern int nr_mce_banks;
-
-void intel_set_thermal_handler(void);
-
-#else
-
-static inline void intel_set_thermal_handler(void) { }
-
-#endif
-
-void intel_init_thermal(struct cpuinfo_x86 *c);
diff --git a/arch/x86/kernel/cpu/mcheck/mce_amd_64.c b/arch/x86/kernel/cpu/mcheck/mce_amd.c
similarity index 100%
rename from arch/x86/kernel/cpu/mcheck/mce_amd_64.c
rename to arch/x86/kernel/cpu/mcheck/mce_amd.c
diff --git a/arch/x86/kernel/cpu/mcheck/mce_intel.c b/arch/x86/kernel/cpu/mcheck/mce_intel.c
index 2b011d2..e1acec0f 100644
--- a/arch/x86/kernel/cpu/mcheck/mce_intel.c
+++ b/arch/x86/kernel/cpu/mcheck/mce_intel.c
@@ -1,74 +1,226 @@
 /*
- * Common code for Intel machine checks
+ * Intel specific MCE features.
+ * Copyright 2004 Zwane Mwaikambo <zwane@linuxpower.ca>
+ * Copyright (C) 2008, 2009 Intel Corporation
+ * Author: Andi Kleen
  */
-#include <linux/interrupt.h>
-#include <linux/kernel.h>
-#include <linux/types.h>
+
 #include <linux/init.h>
-#include <linux/smp.h>
-
-#include <asm/therm_throt.h>
-#include <asm/processor.h>
-#include <asm/system.h>
+#include <linux/interrupt.h>
+#include <linux/percpu.h>
 #include <asm/apic.h>
+#include <asm/processor.h>
 #include <asm/msr.h>
+#include <asm/mce.h>
 
-#include "mce.h"
+/*
+ * Support for Intel Correct Machine Check Interrupts. This allows
+ * the CPU to raise an interrupt when a corrected machine check happened.
+ * Normally we pick those up using a regular polling timer.
+ * Also supports reliable discovery of shared banks.
+ */
 
-void intel_init_thermal(struct cpuinfo_x86 *c)
+static DEFINE_PER_CPU(mce_banks_t, mce_banks_owned);
+
+/*
+ * cmci_discover_lock protects against parallel discovery attempts
+ * which could race against each other.
+ */
+static DEFINE_SPINLOCK(cmci_discover_lock);
+
+#define CMCI_THRESHOLD 1
+
+static int cmci_supported(int *banks)
 {
-	unsigned int cpu = smp_processor_id();
-	int tm2 = 0;
-	u32 l, h;
+	u64 cap;
 
-	/* Thermal monitoring depends on ACPI and clock modulation*/
-	if (!cpu_has(c, X86_FEATURE_ACPI) || !cpu_has(c, X86_FEATURE_ACC))
-		return;
+	if (mce_cmci_disabled || mce_ignore_ce)
+		return 0;
 
 	/*
-	 * First check if its enabled already, in which case there might
-	 * be some SMM goo which handles it, so we can't even put a handler
-	 * since it might be delivered via SMI already:
+	 * Vendor check is not strictly needed, but the initial
+	 * initialization is vendor keyed and this
+	 * makes sure none of the backdoors are entered otherwise.
 	 */
-	rdmsr(MSR_IA32_MISC_ENABLE, l, h);
-	h = apic_read(APIC_LVTTHMR);
-	if ((l & MSR_IA32_MISC_ENABLE_TM1) && (h & APIC_DM_SMI)) {
-		printk(KERN_DEBUG
-		       "CPU%d: Thermal monitoring handled by SMI\n", cpu);
+	if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
+		return 0;
+	if (!cpu_has_apic || lapic_get_maxlvt() < 6)
+		return 0;
+	rdmsrl(MSR_IA32_MCG_CAP, cap);
+	*banks = min_t(unsigned, MAX_NR_BANKS, cap & 0xff);
+	return !!(cap & MCG_CMCI_P);
+}
+
+/*
+ * The interrupt handler. This is called on every event.
+ * Just call the poller directly to log any events.
+ * This could in theory increase the threshold under high load,
+ * but doesn't for now.
+ */
+static void intel_threshold_interrupt(void)
+{
+	machine_check_poll(MCP_TIMESTAMP, &__get_cpu_var(mce_banks_owned));
+	mce_notify_irq();
+}
+
+static void print_update(char *type, int *hdr, int num)
+{
+	if (*hdr == 0)
+		printk(KERN_INFO "CPU %d MCA banks", smp_processor_id());
+	*hdr = 1;
+	printk(KERN_CONT " %s:%d", type, num);
+}
+
+/*
+ * Enable CMCI (Corrected Machine Check Interrupt) for available MCE banks
+ * on this CPU. Use the algorithm recommended in the SDM to discover shared
+ * banks.
+ */
+static void cmci_discover(int banks, int boot)
+{
+	unsigned long *owned = (void *)&__get_cpu_var(mce_banks_owned);
+	unsigned long flags;
+	int hdr = 0;
+	int i;
+
+	spin_lock_irqsave(&cmci_discover_lock, flags);
+	for (i = 0; i < banks; i++) {
+		u64 val;
+
+		if (test_bit(i, owned))
+			continue;
+
+		rdmsrl(MSR_IA32_MC0_CTL2 + i, val);
+
+		/* Already owned by someone else? */
+		if (val & CMCI_EN) {
+			if (test_and_clear_bit(i, owned) || boot)
+				print_update("SHD", &hdr, i);
+			__clear_bit(i, __get_cpu_var(mce_poll_banks));
+			continue;
+		}
+
+		val |= CMCI_EN | CMCI_THRESHOLD;
+		wrmsrl(MSR_IA32_MC0_CTL2 + i, val);
+		rdmsrl(MSR_IA32_MC0_CTL2 + i, val);
+
+		/* Did the enable bit stick? -- the bank supports CMCI */
+		if (val & CMCI_EN) {
+			if (!test_and_set_bit(i, owned) || boot)
+				print_update("CMCI", &hdr, i);
+			__clear_bit(i, __get_cpu_var(mce_poll_banks));
+		} else {
+			WARN_ON(!test_bit(i, __get_cpu_var(mce_poll_banks)));
+		}
+	}
+	spin_unlock_irqrestore(&cmci_discover_lock, flags);
+	if (hdr)
+		printk(KERN_CONT "\n");
+}
+
+/*
+ * Just in case we missed an event during initialization check
+ * all the CMCI owned banks.
+ */
+void cmci_recheck(void)
+{
+	unsigned long flags;
+	int banks;
+
+	if (!mce_available(&current_cpu_data) || !cmci_supported(&banks))
 		return;
+	local_irq_save(flags);
+	machine_check_poll(MCP_TIMESTAMP, &__get_cpu_var(mce_banks_owned));
+	local_irq_restore(flags);
+}
+
+/*
+ * Disable CMCI on this CPU for all banks it owns when it goes down.
+ * This allows other CPUs to claim the banks on rediscovery.
+ */
+void cmci_clear(void)
+{
+	unsigned long flags;
+	int i;
+	int banks;
+	u64 val;
+
+	if (!cmci_supported(&banks))
+		return;
+	spin_lock_irqsave(&cmci_discover_lock, flags);
+	for (i = 0; i < banks; i++) {
+		if (!test_bit(i, __get_cpu_var(mce_banks_owned)))
+			continue;
+		/* Disable CMCI */
+		rdmsrl(MSR_IA32_MC0_CTL2 + i, val);
+		val &= ~(CMCI_EN|CMCI_THRESHOLD_MASK);
+		wrmsrl(MSR_IA32_MC0_CTL2 + i, val);
+		__clear_bit(i, __get_cpu_var(mce_banks_owned));
+	}
+	spin_unlock_irqrestore(&cmci_discover_lock, flags);
+}
+
+/*
+ * After a CPU went down cycle through all the others and rediscover
+ * Must run in process context.
+ */
+void cmci_rediscover(int dying)
+{
+	int banks;
+	int cpu;
+	cpumask_var_t old;
+
+	if (!cmci_supported(&banks))
+		return;
+	if (!alloc_cpumask_var(&old, GFP_KERNEL))
+		return;
+	cpumask_copy(old, &current->cpus_allowed);
+
+	for_each_online_cpu(cpu) {
+		if (cpu == dying)
+			continue;
+		if (set_cpus_allowed_ptr(current, cpumask_of(cpu)))
+			continue;
+		/* Recheck banks in case CPUs don't all have the same */
+		if (cmci_supported(&banks))
+			cmci_discover(banks, 0);
 	}
 
-	if (cpu_has(c, X86_FEATURE_TM2) && (l & MSR_IA32_MISC_ENABLE_TM2))
-		tm2 = 1;
+	set_cpus_allowed_ptr(current, old);
+	free_cpumask_var(old);
+}
 
-	/* Check whether a vector already exists */
-	if (h & APIC_VECTOR_MASK) {
-		printk(KERN_DEBUG
-		       "CPU%d: Thermal LVT vector (%#x) already installed\n",
-		       cpu, (h & APIC_VECTOR_MASK));
+/*
+ * Reenable CMCI on this CPU in case a CPU down failed.
+ */
+void cmci_reenable(void)
+{
+	int banks;
+	if (cmci_supported(&banks))
+		cmci_discover(banks, 0);
+}
+
+static void intel_init_cmci(void)
+{
+	int banks;
+
+	if (!cmci_supported(&banks))
 		return;
-	}
 
-	/* We'll mask the thermal vector in the lapic till we're ready: */
-	h = THERMAL_APIC_VECTOR | APIC_DM_FIXED | APIC_LVT_MASKED;
-	apic_write(APIC_LVTTHMR, h);
+	mce_threshold_vector = intel_threshold_interrupt;
+	cmci_discover(banks, 1);
+	/*
+	 * For CPU #0 this runs with still disabled APIC, but that's
+	 * ok because only the vector is set up. We still do another
+	 * check for the banks later for CPU #0 just to make sure
+	 * to not miss any events.
+	 */
+	apic_write(APIC_LVTCMCI, THRESHOLD_APIC_VECTOR|APIC_DM_FIXED);
+	cmci_recheck();
+}
 
-	rdmsr(MSR_IA32_THERM_INTERRUPT, l, h);
-	wrmsr(MSR_IA32_THERM_INTERRUPT,
-		l | (THERM_INT_LOW_ENABLE | THERM_INT_HIGH_ENABLE), h);
-
-	intel_set_thermal_handler();
-
-	rdmsr(MSR_IA32_MISC_ENABLE, l, h);
-	wrmsr(MSR_IA32_MISC_ENABLE, l | MSR_IA32_MISC_ENABLE_TM1, h);
-
-	/* Unmask the thermal vector: */
-	l = apic_read(APIC_LVTTHMR);
-	apic_write(APIC_LVTTHMR, l & ~APIC_LVT_MASKED);
-
-	printk(KERN_INFO "CPU%d: Thermal monitoring enabled (%s)\n",
-	       cpu, tm2 ? "TM2" : "TM1");
-
-	/* enable thermal throttle processing */
-	atomic_set(&therm_throt_en, 1);
+void mce_intel_feature_init(struct cpuinfo_x86 *c)
+{
+	intel_init_thermal(c);
+	intel_init_cmci();
 }
diff --git a/arch/x86/kernel/cpu/mcheck/mce_intel_64.c b/arch/x86/kernel/cpu/mcheck/mce_intel_64.c
deleted file mode 100644
index f2ef695..0000000
--- a/arch/x86/kernel/cpu/mcheck/mce_intel_64.c
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- * Intel specific MCE features.
- * Copyright 2004 Zwane Mwaikambo <zwane@linuxpower.ca>
- * Copyright (C) 2008, 2009 Intel Corporation
- * Author: Andi Kleen
- */
-
-#include <linux/init.h>
-#include <linux/interrupt.h>
-#include <linux/percpu.h>
-#include <asm/processor.h>
-#include <asm/apic.h>
-#include <asm/msr.h>
-#include <asm/mce.h>
-#include <asm/hw_irq.h>
-#include <asm/idle.h>
-#include <asm/therm_throt.h>
-
-#include "mce.h"
-
-asmlinkage void smp_thermal_interrupt(void)
-{
-	__u64 msr_val;
-
-	ack_APIC_irq();
-
-	exit_idle();
-	irq_enter();
-
-	rdmsrl(MSR_IA32_THERM_STATUS, msr_val);
-	if (therm_throt_process(msr_val & THERM_STATUS_PROCHOT))
-		mce_log_therm_throt_event(msr_val);
-
-	inc_irq_stat(irq_thermal_count);
-	irq_exit();
-}
-
-/*
- * Support for Intel Correct Machine Check Interrupts. This allows
- * the CPU to raise an interrupt when a corrected machine check happened.
- * Normally we pick those up using a regular polling timer.
- * Also supports reliable discovery of shared banks.
- */
-
-static DEFINE_PER_CPU(mce_banks_t, mce_banks_owned);
-
-/*
- * cmci_discover_lock protects against parallel discovery attempts
- * which could race against each other.
- */
-static DEFINE_SPINLOCK(cmci_discover_lock);
-
-#define CMCI_THRESHOLD 1
-
-static int cmci_supported(int *banks)
-{
-	u64 cap;
-
-	if (mce_cmci_disabled || mce_ignore_ce)
-		return 0;
-
-	/*
-	 * Vendor check is not strictly needed, but the initial
-	 * initialization is vendor keyed and this
-	 * makes sure none of the backdoors are entered otherwise.
-	 */
-	if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
-		return 0;
-	if (!cpu_has_apic || lapic_get_maxlvt() < 6)
-		return 0;
-	rdmsrl(MSR_IA32_MCG_CAP, cap);
-	*banks = min_t(unsigned, MAX_NR_BANKS, cap & 0xff);
-	return !!(cap & MCG_CMCI_P);
-}
-
-/*
- * The interrupt handler. This is called on every event.
- * Just call the poller directly to log any events.
- * This could in theory increase the threshold under high load,
- * but doesn't for now.
- */
-static void intel_threshold_interrupt(void)
-{
-	machine_check_poll(MCP_TIMESTAMP, &__get_cpu_var(mce_banks_owned));
-	mce_notify_irq();
-}
-
-static void print_update(char *type, int *hdr, int num)
-{
-	if (*hdr == 0)
-		printk(KERN_INFO "CPU %d MCA banks", smp_processor_id());
-	*hdr = 1;
-	printk(KERN_CONT " %s:%d", type, num);
-}
-
-/*
- * Enable CMCI (Corrected Machine Check Interrupt) for available MCE banks
- * on this CPU. Use the algorithm recommended in the SDM to discover shared
- * banks.
- */
-static void cmci_discover(int banks, int boot)
-{
-	unsigned long *owned = (void *)&__get_cpu_var(mce_banks_owned);
-	unsigned long flags;
-	int hdr = 0;
-	int i;
-
-	spin_lock_irqsave(&cmci_discover_lock, flags);
-	for (i = 0; i < banks; i++) {
-		u64 val;
-
-		if (test_bit(i, owned))
-			continue;
-
-		rdmsrl(MSR_IA32_MC0_CTL2 + i, val);
-
-		/* Already owned by someone else? */
-		if (val & CMCI_EN) {
-			if (test_and_clear_bit(i, owned) || boot)
-				print_update("SHD", &hdr, i);
-			__clear_bit(i, __get_cpu_var(mce_poll_banks));
-			continue;
-		}
-
-		val |= CMCI_EN | CMCI_THRESHOLD;
-		wrmsrl(MSR_IA32_MC0_CTL2 + i, val);
-		rdmsrl(MSR_IA32_MC0_CTL2 + i, val);
-
-		/* Did the enable bit stick? -- the bank supports CMCI */
-		if (val & CMCI_EN) {
-			if (!test_and_set_bit(i, owned) || boot)
-				print_update("CMCI", &hdr, i);
-			__clear_bit(i, __get_cpu_var(mce_poll_banks));
-		} else {
-			WARN_ON(!test_bit(i, __get_cpu_var(mce_poll_banks)));
-		}
-	}
-	spin_unlock_irqrestore(&cmci_discover_lock, flags);
-	if (hdr)
-		printk(KERN_CONT "\n");
-}
-
-/*
- * Just in case we missed an event during initialization check
- * all the CMCI owned banks.
- */
-void cmci_recheck(void)
-{
-	unsigned long flags;
-	int banks;
-
-	if (!mce_available(&current_cpu_data) || !cmci_supported(&banks))
-		return;
-	local_irq_save(flags);
-	machine_check_poll(MCP_TIMESTAMP, &__get_cpu_var(mce_banks_owned));
-	local_irq_restore(flags);
-}
-
-/*
- * Disable CMCI on this CPU for all banks it owns when it goes down.
- * This allows other CPUs to claim the banks on rediscovery.
- */
-void cmci_clear(void)
-{
-	unsigned long flags;
-	int i;
-	int banks;
-	u64 val;
-
-	if (!cmci_supported(&banks))
-		return;
-	spin_lock_irqsave(&cmci_discover_lock, flags);
-	for (i = 0; i < banks; i++) {
-		if (!test_bit(i, __get_cpu_var(mce_banks_owned)))
-			continue;
-		/* Disable CMCI */
-		rdmsrl(MSR_IA32_MC0_CTL2 + i, val);
-		val &= ~(CMCI_EN|CMCI_THRESHOLD_MASK);
-		wrmsrl(MSR_IA32_MC0_CTL2 + i, val);
-		__clear_bit(i, __get_cpu_var(mce_banks_owned));
-	}
-	spin_unlock_irqrestore(&cmci_discover_lock, flags);
-}
-
-/*
- * After a CPU went down cycle through all the others and rediscover
- * Must run in process context.
- */
-void cmci_rediscover(int dying)
-{
-	int banks;
-	int cpu;
-	cpumask_var_t old;
-
-	if (!cmci_supported(&banks))
-		return;
-	if (!alloc_cpumask_var(&old, GFP_KERNEL))
-		return;
-	cpumask_copy(old, &current->cpus_allowed);
-
-	for_each_online_cpu(cpu) {
-		if (cpu == dying)
-			continue;
-		if (set_cpus_allowed_ptr(current, cpumask_of(cpu)))
-			continue;
-		/* Recheck banks in case CPUs don't all have the same */
-		if (cmci_supported(&banks))
-			cmci_discover(banks, 0);
-	}
-
-	set_cpus_allowed_ptr(current, old);
-	free_cpumask_var(old);
-}
-
-/*
- * Reenable CMCI on this CPU in case a CPU down failed.
- */
-void cmci_reenable(void)
-{
-	int banks;
-	if (cmci_supported(&banks))
-		cmci_discover(banks, 0);
-}
-
-static void intel_init_cmci(void)
-{
-	int banks;
-
-	if (!cmci_supported(&banks))
-		return;
-
-	mce_threshold_vector = intel_threshold_interrupt;
-	cmci_discover(banks, 1);
-	/*
-	 * For CPU #0 this runs with still disabled APIC, but that's
-	 * ok because only the vector is set up. We still do another
-	 * check for the banks later for CPU #0 just to make sure
-	 * to not miss any events.
-	 */
-	apic_write(APIC_LVTCMCI, THRESHOLD_APIC_VECTOR|APIC_DM_FIXED);
-	cmci_recheck();
-}
-
-void mce_intel_feature_init(struct cpuinfo_x86 *c)
-{
-	intel_init_thermal(c);
-	intel_init_cmci();
-}
diff --git a/arch/x86/kernel/cpu/mcheck/non-fatal.c b/arch/x86/kernel/cpu/mcheck/non-fatal.c
index 70b7104..f5f2d6f 100644
--- a/arch/x86/kernel/cpu/mcheck/non-fatal.c
+++ b/arch/x86/kernel/cpu/mcheck/non-fatal.c
@@ -17,10 +17,9 @@
 
 #include <asm/processor.h>
 #include <asm/system.h>
+#include <asm/mce.h>
 #include <asm/msr.h>
 
-#include "mce.h"
-
 static int		firstbank;
 
 #define MCE_RATE	(15*HZ)	/* timer rate is 15s */
diff --git a/arch/x86/kernel/cpu/mcheck/p4.c b/arch/x86/kernel/cpu/mcheck/p4.c
index 82cee10..4482aea 100644
--- a/arch/x86/kernel/cpu/mcheck/p4.c
+++ b/arch/x86/kernel/cpu/mcheck/p4.c
@@ -1,21 +1,15 @@
 /*
  * P4 specific Machine Check Exception Reporting
  */
-
-#include <linux/interrupt.h>
 #include <linux/kernel.h>
 #include <linux/types.h>
 #include <linux/init.h>
 #include <linux/smp.h>
 
-#include <asm/therm_throt.h>
 #include <asm/processor.h>
-#include <asm/system.h>
-#include <asm/apic.h>
+#include <asm/mce.h>
 #include <asm/msr.h>
 
-#include "mce.h"
-
 /* as supported by the P4/Xeon family */
 struct intel_mce_extended_msrs {
 	u32 eax;
@@ -33,46 +27,6 @@
 
 static int mce_num_extended_msrs;
 
-
-#ifdef CONFIG_X86_MCE_P4THERMAL
-
-static void unexpected_thermal_interrupt(struct pt_regs *regs)
-{
-	printk(KERN_ERR "CPU%d: Unexpected LVT TMR interrupt!\n",
-			smp_processor_id());
-	add_taint(TAINT_MACHINE_CHECK);
-}
-
-/* P4/Xeon Thermal transition interrupt handler: */
-static void intel_thermal_interrupt(struct pt_regs *regs)
-{
-	__u64 msr_val;
-
-	ack_APIC_irq();
-
-	rdmsrl(MSR_IA32_THERM_STATUS, msr_val);
-	therm_throt_process(msr_val & THERM_STATUS_PROCHOT);
-}
-
-/* Thermal interrupt handler for this CPU setup: */
-static void (*vendor_thermal_interrupt)(struct pt_regs *regs) =
-						unexpected_thermal_interrupt;
-
-void smp_thermal_interrupt(struct pt_regs *regs)
-{
-	irq_enter();
-	vendor_thermal_interrupt(regs);
-	__get_cpu_var(irq_stat).irq_thermal_count++;
-	irq_exit();
-}
-
-void intel_set_thermal_handler(void)
-{
-	vendor_thermal_interrupt = intel_thermal_interrupt;
-}
-
-#endif /* CONFIG_X86_MCE_P4THERMAL */
-
 /* P4/Xeon Extended MCE MSR retrieval, return 0 if unsupported */
 static void intel_get_extended_msrs(struct intel_mce_extended_msrs *r)
 {
diff --git a/arch/x86/kernel/cpu/mcheck/p5.c b/arch/x86/kernel/cpu/mcheck/p5.c
index 015f481..5c0e653 100644
--- a/arch/x86/kernel/cpu/mcheck/p5.c
+++ b/arch/x86/kernel/cpu/mcheck/p5.c
@@ -10,12 +10,11 @@
 
 #include <asm/processor.h>
 #include <asm/system.h>
+#include <asm/mce.h>
 #include <asm/msr.h>
 
-#include "mce.h"
-
 /* By default disabled */
-int		mce_p5_enable;
+int mce_p5_enabled __read_mostly;
 
 /* Machine check handler for Pentium class Intel CPUs: */
 static void pentium_machine_check(struct pt_regs *regs, long error_code)
@@ -43,16 +42,14 @@
 {
 	u32 l, h;
 
+	/* Default P5 to off as its often misconnected: */
+	if (!mce_p5_enabled)
+		return;
+
 	/* Check for MCE support: */
 	if (!cpu_has(c, X86_FEATURE_MCE))
 		return;
 
-#ifdef CONFIG_X86_OLD_MCE
-	/* Default P5 to off as its often misconnected: */
-	if (mce_disabled != -1)
-		return;
-#endif
-
 	machine_check_vector = pentium_machine_check;
 	/* Make sure the vector pointer is visible before we enable MCEs: */
 	wmb();
diff --git a/arch/x86/kernel/cpu/mcheck/p6.c b/arch/x86/kernel/cpu/mcheck/p6.c
index 43c24e6..01e4f81 100644
--- a/arch/x86/kernel/cpu/mcheck/p6.c
+++ b/arch/x86/kernel/cpu/mcheck/p6.c
@@ -10,10 +10,9 @@
 
 #include <asm/processor.h>
 #include <asm/system.h>
+#include <asm/mce.h>
 #include <asm/msr.h>
 
-#include "mce.h"
-
 /* Machine Check Handler For PII/PIII */
 static void intel_machine_check(struct pt_regs *regs, long error_code)
 {
diff --git a/arch/x86/kernel/cpu/mcheck/therm_throt.c b/arch/x86/kernel/cpu/mcheck/therm_throt.c
index 7b1ae2e..bff8dd1 100644
--- a/arch/x86/kernel/cpu/mcheck/therm_throt.c
+++ b/arch/x86/kernel/cpu/mcheck/therm_throt.c
@@ -13,13 +13,23 @@
  * Credits: Adapted from Zwane Mwaikambo's original code in mce_intel.c.
  *          Inspired by Ross Biro's and Al Borchers' counter code.
  */
+#include <linux/interrupt.h>
 #include <linux/notifier.h>
 #include <linux/jiffies.h>
+#include <linux/kernel.h>
 #include <linux/percpu.h>
 #include <linux/sysdev.h>
+#include <linux/types.h>
+#include <linux/init.h>
+#include <linux/smp.h>
 #include <linux/cpu.h>
 
-#include <asm/therm_throt.h>
+#include <asm/processor.h>
+#include <asm/system.h>
+#include <asm/apic.h>
+#include <asm/idle.h>
+#include <asm/mce.h>
+#include <asm/msr.h>
 
 /* How long to wait between reporting thermal events */
 #define CHECK_INTERVAL		(300 * HZ)
@@ -27,7 +37,7 @@
 static DEFINE_PER_CPU(__u64, next_check) = INITIAL_JIFFIES;
 static DEFINE_PER_CPU(unsigned long, thermal_throttle_count);
 
-atomic_t therm_throt_en		= ATOMIC_INIT(0);
+static atomic_t therm_throt_en		= ATOMIC_INIT(0);
 
 #ifdef CONFIG_SYSFS
 #define define_therm_throt_sysdev_one_ro(_name)				\
@@ -82,7 +92,7 @@
  *          1 : Event should be logged further, and a message has been
  *              printed to the syslog.
  */
-int therm_throt_process(int curr)
+static int therm_throt_process(int curr)
 {
 	unsigned int cpu = smp_processor_id();
 	__u64 tmp_jiffs = get_jiffies_64();
@@ -186,6 +196,94 @@
 
 	return 0;
 }
-
 device_initcall(thermal_throttle_init_device);
+
 #endif /* CONFIG_SYSFS */
+
+/* Thermal transition interrupt handler */
+static void intel_thermal_interrupt(void)
+{
+	__u64 msr_val;
+
+	rdmsrl(MSR_IA32_THERM_STATUS, msr_val);
+	if (therm_throt_process(msr_val & THERM_STATUS_PROCHOT))
+		mce_log_therm_throt_event(msr_val);
+}
+
+static void unexpected_thermal_interrupt(void)
+{
+	printk(KERN_ERR "CPU%d: Unexpected LVT TMR interrupt!\n",
+			smp_processor_id());
+	add_taint(TAINT_MACHINE_CHECK);
+}
+
+static void (*smp_thermal_vector)(void) = unexpected_thermal_interrupt;
+
+asmlinkage void smp_thermal_interrupt(struct pt_regs *regs)
+{
+	exit_idle();
+	irq_enter();
+	inc_irq_stat(irq_thermal_count);
+	smp_thermal_vector();
+	irq_exit();
+	/* Ack only at the end to avoid potential reentry */
+	ack_APIC_irq();
+}
+
+void intel_init_thermal(struct cpuinfo_x86 *c)
+{
+	unsigned int cpu = smp_processor_id();
+	int tm2 = 0;
+	u32 l, h;
+
+	/* Thermal monitoring depends on ACPI and clock modulation*/
+	if (!cpu_has(c, X86_FEATURE_ACPI) || !cpu_has(c, X86_FEATURE_ACC))
+		return;
+
+	/*
+	 * First check if its enabled already, in which case there might
+	 * be some SMM goo which handles it, so we can't even put a handler
+	 * since it might be delivered via SMI already:
+	 */
+	rdmsr(MSR_IA32_MISC_ENABLE, l, h);
+	h = apic_read(APIC_LVTTHMR);
+	if ((l & MSR_IA32_MISC_ENABLE_TM1) && (h & APIC_DM_SMI)) {
+		printk(KERN_DEBUG
+		       "CPU%d: Thermal monitoring handled by SMI\n", cpu);
+		return;
+	}
+
+	if (cpu_has(c, X86_FEATURE_TM2) && (l & MSR_IA32_MISC_ENABLE_TM2))
+		tm2 = 1;
+
+	/* Check whether a vector already exists */
+	if (h & APIC_VECTOR_MASK) {
+		printk(KERN_DEBUG
+		       "CPU%d: Thermal LVT vector (%#x) already installed\n",
+		       cpu, (h & APIC_VECTOR_MASK));
+		return;
+	}
+
+	/* We'll mask the thermal vector in the lapic till we're ready: */
+	h = THERMAL_APIC_VECTOR | APIC_DM_FIXED | APIC_LVT_MASKED;
+	apic_write(APIC_LVTTHMR, h);
+
+	rdmsr(MSR_IA32_THERM_INTERRUPT, l, h);
+	wrmsr(MSR_IA32_THERM_INTERRUPT,
+		l | (THERM_INT_LOW_ENABLE | THERM_INT_HIGH_ENABLE), h);
+
+	smp_thermal_vector = intel_thermal_interrupt;
+
+	rdmsr(MSR_IA32_MISC_ENABLE, l, h);
+	wrmsr(MSR_IA32_MISC_ENABLE, l | MSR_IA32_MISC_ENABLE_TM1, h);
+
+	/* Unmask the thermal vector: */
+	l = apic_read(APIC_LVTTHMR);
+	apic_write(APIC_LVTTHMR, l & ~APIC_LVT_MASKED);
+
+	printk(KERN_INFO "CPU%d: Thermal monitoring enabled (%s)\n",
+	       cpu, tm2 ? "TM2" : "TM1");
+
+	/* enable thermal throttle processing */
+	atomic_set(&therm_throt_en, 1);
+}
diff --git a/arch/x86/kernel/cpu/mcheck/winchip.c b/arch/x86/kernel/cpu/mcheck/winchip.c
index 81b0248..54060f5 100644
--- a/arch/x86/kernel/cpu/mcheck/winchip.c
+++ b/arch/x86/kernel/cpu/mcheck/winchip.c
@@ -9,10 +9,9 @@
 
 #include <asm/processor.h>
 #include <asm/system.h>
+#include <asm/mce.h>
 #include <asm/msr.h>
 
-#include "mce.h"
-
 /* Machine check handler for WinChip C6: */
 static void winchip_machine_check(struct pt_regs *regs, long error_code)
 {
diff --git a/arch/x86/kernel/cpu/perfctr-watchdog.c b/arch/x86/kernel/cpu/perfctr-watchdog.c
index d6f5b9f..5c481f6 100644
--- a/arch/x86/kernel/cpu/perfctr-watchdog.c
+++ b/arch/x86/kernel/cpu/perfctr-watchdog.c
@@ -716,11 +716,15 @@
 		wd_ops = &k7_wd_ops;
 		break;
 	case X86_VENDOR_INTEL:
-		/*
-		 * Work around Core Duo (Yonah) errata AE49 where perfctr1
-		 * doesn't have a working enable bit.
+		/* Work around where perfctr1 doesn't have a working enable
+		 * bit as described in the following errata:
+		 * AE49 Core Duo and Intel Core Solo 65 nm
+		 * AN49 Intel Pentium Dual-Core
+		 * AF49 Dual-Core Intel Xeon Processor LV
 		 */
-		if (boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model == 14) {
+		if ((boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model == 14) ||
+		    ((boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model == 15 &&
+		     boot_cpu_data.x86_mask == 4))) {
 			intel_arch_wd_ops.perfctr = MSR_ARCH_PERFMON_PERFCTR0;
 			intel_arch_wd_ops.evntsel = MSR_ARCH_PERFMON_EVENTSEL0;
 		}
diff --git a/arch/x86/kernel/crash.c b/arch/x86/kernel/crash.c
index ff95824..5e409dc 100644
--- a/arch/x86/kernel/crash.c
+++ b/arch/x86/kernel/crash.c
@@ -27,6 +27,7 @@
 #include <asm/cpu.h>
 #include <asm/reboot.h>
 #include <asm/virtext.h>
+#include <asm/iommu.h>
 
 
 #if defined(CONFIG_SMP) && defined(CONFIG_X86_LOCAL_APIC)
@@ -103,5 +104,10 @@
 #ifdef CONFIG_HPET_TIMER
 	hpet_disable();
 #endif
+
+#ifdef CONFIG_X86_64
+	pci_iommu_shutdown();
+#endif
+
 	crash_save_cpu(regs, safe_smp_processor_id());
 }
diff --git a/arch/x86/kernel/efi.c b/arch/x86/kernel/efi.c
index 1736acc..96f7ac0 100644
--- a/arch/x86/kernel/efi.c
+++ b/arch/x86/kernel/efi.c
@@ -240,10 +240,35 @@
 		unsigned long long size = md->num_pages << EFI_PAGE_SHIFT;
 		int e820_type;
 
-		if (md->attribute & EFI_MEMORY_WB)
-			e820_type = E820_RAM;
-		else
+		switch (md->type) {
+		case EFI_LOADER_CODE:
+		case EFI_LOADER_DATA:
+		case EFI_BOOT_SERVICES_CODE:
+		case EFI_BOOT_SERVICES_DATA:
+		case EFI_CONVENTIONAL_MEMORY:
+			if (md->attribute & EFI_MEMORY_WB)
+				e820_type = E820_RAM;
+			else
+				e820_type = E820_RESERVED;
+			break;
+		case EFI_ACPI_RECLAIM_MEMORY:
+			e820_type = E820_ACPI;
+			break;
+		case EFI_ACPI_MEMORY_NVS:
+			e820_type = E820_NVS;
+			break;
+		case EFI_UNUSABLE_MEMORY:
+			e820_type = E820_UNUSABLE;
+			break;
+		default:
+			/*
+			 * EFI_RESERVED_TYPE EFI_RUNTIME_SERVICES_CODE
+			 * EFI_RUNTIME_SERVICES_DATA EFI_MEMORY_MAPPED_IO
+			 * EFI_MEMORY_MAPPED_IO_PORT_SPACE EFI_PAL_CODE
+			 */
 			e820_type = E820_RESERVED;
+			break;
+		}
 		e820_add_region(start, size, e820_type);
 	}
 	sanitize_e820_map(e820.map, ARRAY_SIZE(e820.map), &e820.nr_map);
diff --git a/arch/x86/kernel/entry_32.S b/arch/x86/kernel/entry_32.S
index c929add..c097e7d 100644
--- a/arch/x86/kernel/entry_32.S
+++ b/arch/x86/kernel/entry_32.S
@@ -48,7 +48,6 @@
 #include <asm/segment.h>
 #include <asm/smp.h>
 #include <asm/page_types.h>
-#include <asm/desc.h>
 #include <asm/percpu.h>
 #include <asm/dwarf2.h>
 #include <asm/processor-flags.h>
@@ -84,7 +83,7 @@
 #define preempt_stop(clobbers)	DISABLE_INTERRUPTS(clobbers); TRACE_IRQS_OFF
 #else
 #define preempt_stop(clobbers)
-#define resume_kernel		restore_nocheck
+#define resume_kernel		restore_all
 #endif
 
 .macro TRACE_IRQS_IRET
@@ -372,7 +371,7 @@
 ENTRY(resume_kernel)
 	DISABLE_INTERRUPTS(CLBR_ANY)
 	cmpl $0,TI_preempt_count(%ebp)	# non-zero preempt_count ?
-	jnz restore_nocheck
+	jnz restore_all
 need_resched:
 	movl TI_flags(%ebp), %ecx	# need_resched set ?
 	testb $_TIF_NEED_RESCHED, %cl
@@ -540,6 +539,8 @@
 	jne syscall_exit_work
 
 restore_all:
+	TRACE_IRQS_IRET
+restore_all_notrace:
 	movl PT_EFLAGS(%esp), %eax	# mix EFLAGS, SS and CS
 	# Warning: PT_OLDSS(%esp) contains the wrong/random values if we
 	# are returning to the kernel.
@@ -551,8 +552,6 @@
 	CFI_REMEMBER_STATE
 	je ldt_ss			# returning to user-space with LDT SS
 restore_nocheck:
-	TRACE_IRQS_IRET
-restore_nocheck_notrace:
 	RESTORE_REGS 4			# skip orig_eax/error_code
 	CFI_ADJUST_CFA_OFFSET -4
 irq_return:
@@ -588,22 +587,34 @@
 	jne restore_nocheck
 #endif
 
-	/* If returning to userspace with 16bit stack,
-	 * try to fix the higher word of ESP, as the CPU
-	 * won't restore it.
-	 * This is an "official" bug of all the x86-compatible
-	 * CPUs, which we can try to work around to make
-	 * dosemu and wine happy. */
-	movl PT_OLDESP(%esp), %eax
-	movl %esp, %edx
-	call patch_espfix_desc
+/*
+ * Setup and switch to ESPFIX stack
+ *
+ * We're returning to userspace with a 16 bit stack. The CPU will not
+ * restore the high word of ESP for us on executing iret... This is an
+ * "official" bug of all the x86-compatible CPUs, which we can work
+ * around to make dosemu and wine happy. We do this by preloading the
+ * high word of ESP with the high word of the userspace ESP while
+ * compensating for the offset by changing to the ESPFIX segment with
+ * a base address that matches for the difference.
+ */
+	mov %esp, %edx			/* load kernel esp */
+	mov PT_OLDESP(%esp), %eax	/* load userspace esp */
+	mov %dx, %ax			/* eax: new kernel esp */
+	sub %eax, %edx			/* offset (low word is 0) */
+	PER_CPU(gdt_page, %ebx)
+	shr $16, %edx
+	mov %dl, GDT_ENTRY_ESPFIX_SS * 8 + 4(%ebx) /* bits 16..23 */
+	mov %dh, GDT_ENTRY_ESPFIX_SS * 8 + 7(%ebx) /* bits 24..31 */
 	pushl $__ESPFIX_SS
 	CFI_ADJUST_CFA_OFFSET 4
-	pushl %eax
+	push %eax			/* new kernel esp */
 	CFI_ADJUST_CFA_OFFSET 4
+	/* Disable interrupts, but do not irqtrace this section: we
+	 * will soon execute iret and the tracer was already set to
+	 * the irqstate after the iret */
 	DISABLE_INTERRUPTS(CLBR_EAX)
-	TRACE_IRQS_OFF
-	lss (%esp), %esp
+	lss (%esp), %esp		/* switch to espfix segment */
 	CFI_ADJUST_CFA_OFFSET -8
 	jmp restore_nocheck
 	CFI_ENDPROC
@@ -716,15 +727,24 @@
 PTREGSCALL(vm86old)
 
 .macro FIXUP_ESPFIX_STACK
-	/* since we are on a wrong stack, we cant make it a C code :( */
+/*
+ * Switch back for ESPFIX stack to the normal zerobased stack
+ *
+ * We can't call C functions using the ESPFIX stack. This code reads
+ * the high word of the segment base from the GDT and swiches to the
+ * normal stack and adjusts ESP with the matching offset.
+ */
+	/* fixup the stack */
 	PER_CPU(gdt_page, %ebx)
-	GET_DESC_BASE(GDT_ENTRY_ESPFIX_SS, %ebx, %eax, %ax, %al, %ah)
-	addl %esp, %eax
+	mov GDT_ENTRY_ESPFIX_SS * 8 + 4(%ebx), %al /* bits 16..23 */
+	mov GDT_ENTRY_ESPFIX_SS * 8 + 7(%ebx), %ah /* bits 24..31 */
+	shl $16, %eax
+	addl %esp, %eax			/* the adjusted stack pointer */
 	pushl $__KERNEL_DS
 	CFI_ADJUST_CFA_OFFSET 4
 	pushl %eax
 	CFI_ADJUST_CFA_OFFSET 4
-	lss (%esp), %esp
+	lss (%esp), %esp		/* switch to the normal stack segment */
 	CFI_ADJUST_CFA_OFFSET -8
 .endm
 .macro UNWIND_ESPFIX_STACK
@@ -1154,6 +1174,7 @@
 	pushl %edx
 	movl 0xc(%esp), %edx
 	lea 0x4(%ebp), %eax
+	movl (%ebp), %ecx
 	subl $MCOUNT_INSN_SIZE, %edx
 	call prepare_ftrace_return
 	popl %edx
@@ -1168,6 +1189,7 @@
 	pushl %eax
 	pushl %ecx
 	pushl %edx
+	movl %ebp, %eax
 	call ftrace_return_to_handler
 	movl %eax, 0xc(%esp)
 	popl %edx
@@ -1329,7 +1351,7 @@
 	xorl %edx,%edx		# zero error code
 	movl %esp,%eax		# pt_regs pointer
 	call do_nmi
-	jmp restore_nocheck_notrace
+	jmp restore_all_notrace
 	CFI_ENDPROC
 
 nmi_stack_fixup:
diff --git a/arch/x86/kernel/entry_64.S b/arch/x86/kernel/entry_64.S
index de74f0a..c251be7 100644
--- a/arch/x86/kernel/entry_64.S
+++ b/arch/x86/kernel/entry_64.S
@@ -135,6 +135,7 @@
 
 	leaq 8(%rbp), %rdi
 	movq 0x38(%rsp), %rsi
+	movq (%rbp), %rdx
 	subq $MCOUNT_INSN_SIZE, %rsi
 
 	call	prepare_ftrace_return
@@ -150,6 +151,7 @@
 	/* Save the return values */
 	movq %rax, (%rsp)
 	movq %rdx, 8(%rsp)
+	movq %rbp, %rdi
 
 	call ftrace_return_to_handler
 
diff --git a/arch/x86/kernel/ftrace.c b/arch/x86/kernel/ftrace.c
index b79c553..d94e1ea 100644
--- a/arch/x86/kernel/ftrace.c
+++ b/arch/x86/kernel/ftrace.c
@@ -408,7 +408,8 @@
  * Hook the return address and push it in the stack of return addrs
  * in current thread info.
  */
-void prepare_ftrace_return(unsigned long *parent, unsigned long self_addr)
+void prepare_ftrace_return(unsigned long *parent, unsigned long self_addr,
+			   unsigned long frame_pointer)
 {
 	unsigned long old;
 	int faulted;
@@ -453,7 +454,8 @@
 		return;
 	}
 
-	if (ftrace_push_return_trace(old, self_addr, &trace.depth) == -EBUSY) {
+	if (ftrace_push_return_trace(old, self_addr, &trace.depth,
+		    frame_pointer) == -EBUSY) {
 		*parent = old;
 		return;
 	}
diff --git a/arch/x86/kernel/head_32.S b/arch/x86/kernel/head_32.S
index dc5ed4b..8663afb 100644
--- a/arch/x86/kernel/head_32.S
+++ b/arch/x86/kernel/head_32.S
@@ -13,7 +13,6 @@
 #include <asm/segment.h>
 #include <asm/page_types.h>
 #include <asm/pgtable_types.h>
-#include <asm/desc.h>
 #include <asm/cache.h>
 #include <asm/thread_info.h>
 #include <asm/asm-offsets.h>
diff --git a/arch/x86/kernel/head_64.S b/arch/x86/kernel/head_64.S
index 54b29bb..fa54f78 100644
--- a/arch/x86/kernel/head_64.S
+++ b/arch/x86/kernel/head_64.S
@@ -12,7 +12,6 @@
 #include <linux/linkage.h>
 #include <linux/threads.h>
 #include <linux/init.h>
-#include <asm/desc.h>
 #include <asm/segment.h>
 #include <asm/pgtable.h>
 #include <asm/page.h>
diff --git a/arch/x86/kernel/hpet.c b/arch/x86/kernel/hpet.c
index 81408b9..dedc2bd 100644
--- a/arch/x86/kernel/hpet.c
+++ b/arch/x86/kernel/hpet.c
@@ -510,7 +510,8 @@
 {
 
 	if (request_irq(dev->irq, hpet_interrupt_handler,
-			IRQF_DISABLED|IRQF_NOBALANCING, dev->name, dev))
+			IRQF_TIMER | IRQF_DISABLED | IRQF_NOBALANCING,
+			dev->name, dev))
 		return -1;
 
 	disable_irq(dev->irq);
diff --git a/arch/x86/kernel/pci-dma.c b/arch/x86/kernel/pci-dma.c
index 745579b..328592f 100644
--- a/arch/x86/kernel/pci-dma.c
+++ b/arch/x86/kernel/pci-dma.c
@@ -290,6 +290,8 @@
 void pci_iommu_shutdown(void)
 {
 	gart_iommu_shutdown();
+
+	amd_iommu_shutdown();
 }
 /* Must execute after PCI subsystem */
 fs_initcall(pci_iommu_init);
diff --git a/arch/x86/kernel/traps.c b/arch/x86/kernel/traps.c
index 5f935f0..a0f48f5 100644
--- a/arch/x86/kernel/traps.c
+++ b/arch/x86/kernel/traps.c
@@ -54,6 +54,7 @@
 #include <asm/traps.h>
 #include <asm/desc.h>
 #include <asm/i387.h>
+#include <asm/mce.h>
 
 #include <asm/mach_traps.h>
 
@@ -65,8 +66,6 @@
 #include <asm/setup.h>
 #include <asm/traps.h>
 
-#include "cpu/mcheck/mce.h"
-
 asmlinkage int system_call(void);
 
 /* Do we ignore FPU interrupts ? */
diff --git a/arch/x86/kernel/tsc.c b/arch/x86/kernel/tsc.c
index ae3180c..6e1a368 100644
--- a/arch/x86/kernel/tsc.c
+++ b/arch/x86/kernel/tsc.c
@@ -590,22 +590,26 @@
  */
 
 DEFINE_PER_CPU(unsigned long, cyc2ns);
+DEFINE_PER_CPU(unsigned long long, cyc2ns_offset);
 
 static void set_cyc2ns_scale(unsigned long cpu_khz, int cpu)
 {
-	unsigned long long tsc_now, ns_now;
+	unsigned long long tsc_now, ns_now, *offset;
 	unsigned long flags, *scale;
 
 	local_irq_save(flags);
 	sched_clock_idle_sleep_event();
 
 	scale = &per_cpu(cyc2ns, cpu);
+	offset = &per_cpu(cyc2ns_offset, cpu);
 
 	rdtscll(tsc_now);
 	ns_now = __cycles_2_ns(tsc_now);
 
-	if (cpu_khz)
+	if (cpu_khz) {
 		*scale = (NSEC_PER_MSEC << CYC2NS_SCALE_FACTOR)/cpu_khz;
+		*offset = ns_now - (tsc_now * *scale >> CYC2NS_SCALE_FACTOR);
+	}
 
 	sched_clock_idle_wakeup_event(0);
 	local_irq_restore(flags);
@@ -632,17 +636,15 @@
 				void *data)
 {
 	struct cpufreq_freqs *freq = data;
-	unsigned long *lpj, dummy;
+	unsigned long *lpj;
 
 	if (cpu_has(&cpu_data(freq->cpu), X86_FEATURE_CONSTANT_TSC))
 		return 0;
 
-	lpj = &dummy;
-	if (!(freq->flags & CPUFREQ_CONST_LOOPS))
-#ifdef CONFIG_SMP
-		lpj = &cpu_data(freq->cpu).loops_per_jiffy;
-#else
 	lpj = &boot_cpu_data.loops_per_jiffy;
+#ifdef CONFIG_SMP
+	if (!(freq->flags & CPUFREQ_CONST_LOOPS))
+		lpj = &cpu_data(freq->cpu).loops_per_jiffy;
 #endif
 
 	if (!ref_freq) {
diff --git a/arch/x86/mm/fault.c b/arch/x86/mm/fault.c
index baa0e86..c403526 100644
--- a/arch/x86/mm/fault.c
+++ b/arch/x86/mm/fault.c
@@ -952,8 +952,6 @@
 	tsk = current;
 	mm = tsk->mm;
 
-	prefetchw(&mm->mmap_sem);
-
 	/* Get the faulting address: */
 	address = read_cr2();
 
@@ -963,6 +961,7 @@
 	 */
 	if (kmemcheck_active(regs))
 		kmemcheck_hide(regs);
+	prefetchw(&mm->mmap_sem);
 
 	if (unlikely(kmmio_fault(regs, address)))
 		return;
diff --git a/arch/x86/mm/gup.c b/arch/x86/mm/gup.c
index 2d1d784..71da1bc 100644
--- a/arch/x86/mm/gup.c
+++ b/arch/x86/mm/gup.c
@@ -303,11 +303,16 @@
 	start &= PAGE_MASK;
 	addr = start;
 	len = (unsigned long) nr_pages << PAGE_SHIFT;
+
 	end = start + len;
-	if (unlikely(!access_ok(write ? VERIFY_WRITE : VERIFY_READ,
-					(void __user *)start, len)))
+	if (end < start)
 		goto slow_irqon;
 
+#ifdef CONFIG_X86_64
+	if (end >> __VIRTUAL_MASK_SHIFT)
+		goto slow_irqon;
+#endif
+
 	/*
 	 * XXX: batch / limit 'nr', to avoid large irq off latency
 	 * needs some instrumenting to determine the common sizes used by
diff --git a/arch/x86/mm/init_64.c b/arch/x86/mm/init_64.c
index 9c54329..c4378f4 100644
--- a/arch/x86/mm/init_64.c
+++ b/arch/x86/mm/init_64.c
@@ -527,7 +527,7 @@
 	return phys_pud_init(pud, addr, end, page_size_mask);
 }
 
-unsigned long __init
+unsigned long __meminit
 kernel_physical_mapping_init(unsigned long start,
 			     unsigned long end,
 			     unsigned long page_size_mask)
diff --git a/arch/x86/pci/i386.c b/arch/x86/pci/i386.c
index a85bef2..0fb56db 100644
--- a/arch/x86/pci/i386.c
+++ b/arch/x86/pci/i386.c
@@ -116,7 +116,7 @@
 	struct pci_bus *bus;
 	struct pci_dev *dev;
 	int idx;
-	struct resource *r, *pr;
+	struct resource *r;
 
 	/* Depth-First Search on bus tree */
 	list_for_each_entry(bus, bus_list, node) {
@@ -126,9 +126,8 @@
 				r = &dev->resource[idx];
 				if (!r->flags)
 					continue;
-				pr = pci_find_parent_resource(dev, r);
-				if (!r->start || !pr ||
-				    request_resource(pr, r) < 0) {
+				if (!r->start ||
+				    pci_claim_resource(dev, idx) < 0) {
 					dev_info(&dev->dev, "BAR %d: can't allocate resource\n", idx);
 					/*
 					 * Something is wrong with the region.
@@ -149,7 +148,7 @@
 	struct pci_dev *dev = NULL;
 	int idx, disabled;
 	u16 command;
-	struct resource *r, *pr;
+	struct resource *r;
 
 	for_each_pci_dev(dev) {
 		pci_read_config_word(dev, PCI_COMMAND, &command);
@@ -168,8 +167,7 @@
 					(unsigned long long) r->start,
 					(unsigned long long) r->end,
 					r->flags, disabled, pass);
-				pr = pci_find_parent_resource(dev, r);
-				if (!pr || request_resource(pr, r) < 0) {
+				if (pci_claim_resource(dev, idx) < 0) {
 					dev_info(&dev->dev, "BAR %d: can't allocate resource\n", idx);
 					/* We'll assign a new address later */
 					r->end -= r->start;
@@ -197,7 +195,7 @@
 static int __init pcibios_assign_resources(void)
 {
 	struct pci_dev *dev = NULL;
-	struct resource *r, *pr;
+	struct resource *r;
 
 	if (!(pci_probe & PCI_ASSIGN_ROMS)) {
 		/*
@@ -209,8 +207,7 @@
 			r = &dev->resource[PCI_ROM_RESOURCE];
 			if (!r->flags || !r->start)
 				continue;
-			pr = pci_find_parent_resource(dev, r);
-			if (!pr || request_resource(pr, r) < 0) {
+			if (pci_claim_resource(dev, PCI_ROM_RESOURCE) < 0) {
 				r->end -= r->start;
 				r->start = 0;
 			}
diff --git a/arch/x86/vdso/Makefile b/arch/x86/vdso/Makefile
index 16a9020..88112b49 100644
--- a/arch/x86/vdso/Makefile
+++ b/arch/x86/vdso/Makefile
@@ -123,6 +123,7 @@
 		       -Wl,-T,$(filter %.lds,$^) $(filter %.o,$^)
 
 VDSO_LDFLAGS = -fPIC -shared $(call ld-option, -Wl$(comma)--hash-style=sysv)
+GCOV_PROFILE := n
 
 #
 # Install the unstripped copy of vdso*.so listed in $(vdso-install-y).
diff --git a/arch/xtensa/kernel/process.c b/arch/xtensa/kernel/process.c
index 031f366..e1a04a3 100644
--- a/arch/xtensa/kernel/process.c
+++ b/arch/xtensa/kernel/process.c
@@ -331,11 +331,6 @@
 	if (IS_ERR(filename))
 		goto out;
 	error = do_execve(filename, argv, envp, regs);
-	if (error == 0) {
-		task_lock(current);
-		current->ptrace &= ~PT_DTRACE;
-		task_unlock(current);
-	}
 	putname(filename);
 out:
 	return error;
diff --git a/block/Kconfig b/block/Kconfig
index 2c39527..95a86ad 100644
--- a/block/Kconfig
+++ b/block/Kconfig
@@ -23,8 +23,8 @@
 
 if BLOCK
 
-config LBD
-	bool "Support for large block devices and files"
+config LBDAF
+	bool "Support for large (2TB+) block devices and files"
 	depends on !64BIT
 	default y
 	help
diff --git a/block/blk-settings.c b/block/blk-settings.c
index 7541ea4..bd582a7 100644
--- a/block/blk-settings.c
+++ b/block/blk-settings.c
@@ -97,7 +97,7 @@
 
 /**
  * blk_set_default_limits - reset limits to default values
- * @limits:  the queue_limits structure to reset
+ * @lim:  the queue_limits structure to reset
  *
  * Description:
  *   Returns a queue_limit struct to its default state.  Can be used by
@@ -112,7 +112,7 @@
 	lim->max_segment_size = MAX_SEGMENT_SIZE;
 	lim->max_sectors = lim->max_hw_sectors = SAFE_MAX_SECTORS;
 	lim->logical_block_size = lim->physical_block_size = lim->io_min = 512;
-	lim->bounce_pfn = BLK_BOUNCE_ANY;
+	lim->bounce_pfn = (unsigned long)(BLK_BOUNCE_ANY >> PAGE_SHIFT);
 	lim->alignment_offset = 0;
 	lim->io_opt = 0;
 	lim->misaligned = 0;
diff --git a/drivers/Kconfig b/drivers/Kconfig
index a442c8f..48bbdbe 100644
--- a/drivers/Kconfig
+++ b/drivers/Kconfig
@@ -52,6 +52,8 @@
 
 source "drivers/spi/Kconfig"
 
+source "drivers/pps/Kconfig"
+
 source "drivers/gpio/Kconfig"
 
 source "drivers/w1/Kconfig"
diff --git a/drivers/Makefile b/drivers/Makefile
index 00b44f4..bc4205d 100644
--- a/drivers/Makefile
+++ b/drivers/Makefile
@@ -72,6 +72,7 @@
 obj-$(CONFIG_I2O)		+= message/
 obj-$(CONFIG_RTC_LIB)		+= rtc/
 obj-y				+= i2c/ media/
+obj-$(CONFIG_PPS)		+= pps/
 obj-$(CONFIG_W1)		+= w1/
 obj-$(CONFIG_POWER_SUPPLY)	+= power/
 obj-$(CONFIG_HWMON)		+= hwmon/
diff --git a/drivers/ata/pata_mpc52xx.c b/drivers/ata/pata_mpc52xx.c
index 68d27bc7..2bc2dbe 100644
--- a/drivers/ata/pata_mpc52xx.c
+++ b/drivers/ata/pata_mpc52xx.c
@@ -694,7 +694,7 @@
 	struct bcom_task *dmatsk = NULL;
 
 	/* Get ipb frequency */
-	ipb_freq = mpc52xx_find_ipb_freq(op->node);
+	ipb_freq = mpc5xxx_get_bus_frequency(op->node);
 	if (!ipb_freq) {
 		dev_err(&op->dev, "could not determine IPB bus frequency\n");
 		return -ENODEV;
diff --git a/drivers/block/hd.c b/drivers/block/hd.c
index f65b3f3..f9d0160 100644
--- a/drivers/block/hd.c
+++ b/drivers/block/hd.c
@@ -100,8 +100,6 @@
 static struct request_queue *hd_queue;
 static struct request *hd_req;
 
-#define MAJOR_NR HD_MAJOR
-
 #define TIMEOUT_VALUE	(6*HZ)
 #define	HD_DELAY	0
 
@@ -712,12 +710,12 @@
 {
 	int drive;
 
-	if (register_blkdev(MAJOR_NR, "hd"))
+	if (register_blkdev(HD_MAJOR, "hd"))
 		return -1;
 
 	hd_queue = blk_init_queue(do_hd_request, &hd_lock);
 	if (!hd_queue) {
-		unregister_blkdev(MAJOR_NR, "hd");
+		unregister_blkdev(HD_MAJOR, "hd");
 		return -ENOMEM;
 	}
 
@@ -751,7 +749,7 @@
 		struct hd_i_struct *p = &hd_info[drive];
 		if (!disk)
 			goto Enomem;
-		disk->major = MAJOR_NR;
+		disk->major = HD_MAJOR;
 		disk->first_minor = drive << 6;
 		disk->fops = &hd_fops;
 		sprintf(disk->disk_name, "hd%c", 'a'+drive);
@@ -795,7 +793,7 @@
 	NR_HD = 0;
 out:
 	del_timer(&device_timer);
-	unregister_blkdev(MAJOR_NR, "hd");
+	unregister_blkdev(HD_MAJOR, "hd");
 	blk_cleanup_queue(hd_queue);
 	return -1;
 Enomem:
diff --git a/drivers/char/Kconfig b/drivers/char/Kconfig
index 30bae6d..0bd01f4 100644
--- a/drivers/char/Kconfig
+++ b/drivers/char/Kconfig
@@ -807,7 +807,7 @@
 config RTC
 	tristate "Enhanced Real Time Clock Support (legacy PC RTC driver)"
 	depends on !PPC && !PARISC && !IA64 && !M68K && !SPARC && !FRV \
-			&& !ARM && !SUPERH && !S390 && !AVR32
+			&& !ARM && !SUPERH && !S390 && !AVR32 && !BLACKFIN
 	---help---
 	  If you say Y here and create a character special file /dev/rtc with
 	  major number 10 and minor number 135 using mknod ("man mknod"), you
diff --git a/drivers/char/agp/agp.h b/drivers/char/agp/agp.h
index 46f5075..178e2e9 100644
--- a/drivers/char/agp/agp.h
+++ b/drivers/char/agp/agp.h
@@ -107,7 +107,7 @@
 	void (*agp_enable)(struct agp_bridge_data *, u32);
 	void (*cleanup)(void);
 	void (*tlb_flush)(struct agp_memory *);
-	unsigned long (*mask_memory)(struct agp_bridge_data *, unsigned long, int);
+	unsigned long (*mask_memory)(struct agp_bridge_data *, struct page *, int);
 	void (*cache_flush)(void);
 	int (*create_gatt_table)(struct agp_bridge_data *);
 	int (*free_gatt_table)(struct agp_bridge_data *);
@@ -115,9 +115,9 @@
 	int (*remove_memory)(struct agp_memory *, off_t, int);
 	struct agp_memory *(*alloc_by_type) (size_t, int);
 	void (*free_by_type)(struct agp_memory *);
-	void *(*agp_alloc_page)(struct agp_bridge_data *);
+	struct page *(*agp_alloc_page)(struct agp_bridge_data *);
 	int (*agp_alloc_pages)(struct agp_bridge_data *, struct agp_memory *, size_t);
-	void (*agp_destroy_page)(void *, int flags);
+	void (*agp_destroy_page)(struct page *, int flags);
 	void (*agp_destroy_pages)(struct agp_memory *);
 	int (*agp_type_to_mask_type) (struct agp_bridge_data *, int);
 	void (*chipset_flush)(struct agp_bridge_data *);
@@ -278,10 +278,10 @@
 int agp_generic_remove_memory(struct agp_memory *mem, off_t pg_start, int type);
 struct agp_memory *agp_generic_alloc_by_type(size_t page_count, int type);
 void agp_generic_free_by_type(struct agp_memory *curr);
-void *agp_generic_alloc_page(struct agp_bridge_data *bridge);
+struct page *agp_generic_alloc_page(struct agp_bridge_data *bridge);
 int agp_generic_alloc_pages(struct agp_bridge_data *agp_bridge,
 			    struct agp_memory *memory, size_t page_count);
-void agp_generic_destroy_page(void *addr, int flags);
+void agp_generic_destroy_page(struct page *page, int flags);
 void agp_generic_destroy_pages(struct agp_memory *memory);
 void agp_free_key(int key);
 int agp_num_entries(void);
@@ -291,7 +291,7 @@
 void global_cache_flush(void);
 void get_agp_version(struct agp_bridge_data *bridge);
 unsigned long agp_generic_mask_memory(struct agp_bridge_data *bridge,
-	unsigned long addr, int type);
+				      struct page *page, int type);
 int agp_generic_type_to_mask_type(struct agp_bridge_data *bridge,
 				  int type);
 struct agp_bridge_data *agp_generic_find_bridge(struct pci_dev *pdev);
diff --git a/drivers/char/agp/ali-agp.c b/drivers/char/agp/ali-agp.c
index dc8d1a9..201ef3f 100644
--- a/drivers/char/agp/ali-agp.c
+++ b/drivers/char/agp/ali-agp.c
@@ -141,37 +141,37 @@
 	}
 }
 
-static void *m1541_alloc_page(struct agp_bridge_data *bridge)
+static struct page *m1541_alloc_page(struct agp_bridge_data *bridge)
 {
-	void *addr = agp_generic_alloc_page(agp_bridge);
+	struct page *page = agp_generic_alloc_page(agp_bridge);
 	u32 temp;
 
-	if (!addr)
+	if (!page)
 		return NULL;
 
 	pci_read_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL, &temp);
 	pci_write_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL,
 			(((temp & ALI_CACHE_FLUSH_ADDR_MASK) |
-			  virt_to_gart(addr)) | ALI_CACHE_FLUSH_EN ));
-	return addr;
+			  phys_to_gart(page_to_phys(page))) | ALI_CACHE_FLUSH_EN ));
+	return page;
 }
 
-static void ali_destroy_page(void * addr, int flags)
+static void ali_destroy_page(struct page *page, int flags)
 {
-	if (addr) {
+	if (page) {
 		if (flags & AGP_PAGE_DESTROY_UNMAP) {
 			global_cache_flush();	/* is this really needed?  --hch */
-			agp_generic_destroy_page(addr, flags);
+			agp_generic_destroy_page(page, flags);
 		} else
-			agp_generic_destroy_page(addr, flags);
+			agp_generic_destroy_page(page, flags);
 	}
 }
 
-static void m1541_destroy_page(void * addr, int flags)
+static void m1541_destroy_page(struct page *page, int flags)
 {
 	u32 temp;
 
-	if (addr == NULL)
+	if (page == NULL)
 		return;
 
 	if (flags & AGP_PAGE_DESTROY_UNMAP) {
@@ -180,9 +180,9 @@
 		pci_read_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL, &temp);
 		pci_write_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL,
 				       (((temp & ALI_CACHE_FLUSH_ADDR_MASK) |
-					 virt_to_gart(addr)) | ALI_CACHE_FLUSH_EN));
+					 phys_to_gart(page_to_phys(page))) | ALI_CACHE_FLUSH_EN));
 	}
-	agp_generic_destroy_page(addr, flags);
+	agp_generic_destroy_page(page, flags);
 }
 
 
@@ -346,7 +346,7 @@
 			devs[j].chipset_name = "M1641";
 			break;
 		case 0x43:
-			devs[j].chipset_name = "M????";
+			devs[j].chipset_name = "M1621";
 			break;
 		case 0x47:
 			devs[j].chipset_name = "M1647";
diff --git a/drivers/char/agp/amd-k7-agp.c b/drivers/char/agp/amd-k7-agp.c
index 3f98254b..ba9bde7 100644
--- a/drivers/char/agp/amd-k7-agp.c
+++ b/drivers/char/agp/amd-k7-agp.c
@@ -325,7 +325,7 @@
 		addr = (j * PAGE_SIZE) + agp_bridge->gart_bus_addr;
 		cur_gatt = GET_GATT(addr);
 		writel(agp_generic_mask_memory(agp_bridge,
-			mem->memory[i], mem->type), cur_gatt+GET_GATT_OFF(addr));
+			mem->pages[i], mem->type), cur_gatt+GET_GATT_OFF(addr));
 		readl(cur_gatt+GET_GATT_OFF(addr));	/* PCI Posting. */
 	}
 	amd_irongate_tlbflush(mem);
diff --git a/drivers/char/agp/amd64-agp.c b/drivers/char/agp/amd64-agp.c
index d765afd..3bf5dda 100644
--- a/drivers/char/agp/amd64-agp.c
+++ b/drivers/char/agp/amd64-agp.c
@@ -79,7 +79,7 @@
 
 	for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
 		tmp = agp_bridge->driver->mask_memory(agp_bridge,
-			mem->memory[i], mask_type);
+			mem->pages[i], mask_type);
 
 		BUG_ON(tmp & 0xffffff0000000ffcULL);
 		pte = (tmp & 0x000000ff00000000ULL) >> 28;
diff --git a/drivers/char/agp/ati-agp.c b/drivers/char/agp/ati-agp.c
index f1537ee..33656e1 100644
--- a/drivers/char/agp/ati-agp.c
+++ b/drivers/char/agp/ati-agp.c
@@ -269,12 +269,17 @@
 	int i, j, num_entries;
 	unsigned long __iomem *cur_gatt;
 	unsigned long addr;
+	int mask_type;
 
 	num_entries = A_SIZE_LVL2(agp_bridge->current_size)->num_entries;
 
-	if (type != 0 || mem->type != 0)
+	mask_type = agp_generic_type_to_mask_type(mem->bridge, type);
+	if (mask_type != 0 || type != mem->type)
 		return -EINVAL;
 
+	if (mem->page_count == 0)
+		return 0;
+
 	if ((pg_start + mem->page_count) > num_entries)
 		return -EINVAL;
 
@@ -296,10 +301,11 @@
 	for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
 		addr = (j * PAGE_SIZE) + agp_bridge->gart_bus_addr;
 		cur_gatt = GET_GATT(addr);
-		writel(agp_bridge->driver->mask_memory(agp_bridge,
-			mem->memory[i], mem->type), cur_gatt+GET_GATT_OFF(addr));
-		readl(cur_gatt+GET_GATT_OFF(addr));	/* PCI Posting. */
+		writel(agp_bridge->driver->mask_memory(agp_bridge,	
+						       mem->pages[i], mem->type),
+		       cur_gatt+GET_GATT_OFF(addr));
 	}
+	readl(GET_GATT(agp_bridge->gart_bus_addr)); /* PCI posting */
 	agp_bridge->driver->tlb_flush(mem);
 	return 0;
 }
@@ -310,17 +316,22 @@
 	int i;
 	unsigned long __iomem *cur_gatt;
 	unsigned long addr;
+	int mask_type;
 
-	if (type != 0 || mem->type != 0)
+	mask_type = agp_generic_type_to_mask_type(mem->bridge, type);
+	if (mask_type != 0 || type != mem->type)
 		return -EINVAL;
 
+	if (mem->page_count == 0)
+		return 0;
+
 	for (i = pg_start; i < (mem->page_count + pg_start); i++) {
 		addr = (i * PAGE_SIZE) + agp_bridge->gart_bus_addr;
 		cur_gatt = GET_GATT(addr);
 		writel(agp_bridge->scratch_page, cur_gatt+GET_GATT_OFF(addr));
-		readl(cur_gatt+GET_GATT_OFF(addr)); /* PCI Posting. */
 	}
 
+	readl(GET_GATT(agp_bridge->gart_bus_addr)); /* PCI posting */
 	agp_bridge->driver->tlb_flush(mem);
 	return 0;
 }
diff --git a/drivers/char/agp/backend.c b/drivers/char/agp/backend.c
index 8c617ad..cfa5a64 100644
--- a/drivers/char/agp/backend.c
+++ b/drivers/char/agp/backend.c
@@ -141,17 +141,17 @@
 	bridge->version = &agp_current_version;
 
 	if (bridge->driver->needs_scratch_page) {
-		void *addr = bridge->driver->agp_alloc_page(bridge);
+		struct page *page = bridge->driver->agp_alloc_page(bridge);
 
-		if (!addr) {
+		if (!page) {
 			dev_err(&bridge->dev->dev,
 				"can't get memory for scratch page\n");
 			return -ENOMEM;
 		}
 
-		bridge->scratch_page_real = virt_to_gart(addr);
+		bridge->scratch_page_real = phys_to_gart(page_to_phys(page));
 		bridge->scratch_page =
-		    bridge->driver->mask_memory(bridge, bridge->scratch_page_real, 0);
+		    bridge->driver->mask_memory(bridge, page, 0);
 	}
 
 	size_value = bridge->driver->fetch_size();
diff --git a/drivers/char/agp/efficeon-agp.c b/drivers/char/agp/efficeon-agp.c
index 453543a..35d50f2 100644
--- a/drivers/char/agp/efficeon-agp.c
+++ b/drivers/char/agp/efficeon-agp.c
@@ -65,8 +65,9 @@
 };
 
 /* This function does the same thing as mask_memory() for this chipset... */
-static inline unsigned long efficeon_mask_memory(unsigned long addr)
+static inline unsigned long efficeon_mask_memory(struct page *page)
 {
+	unsigned long addr = phys_to_gart(page_to_phys(page));
 	return addr | 0x00000001;
 }
 
@@ -257,7 +258,7 @@
 	last_page = NULL;
 	for (i = 0; i < count; i++) {
 		int index = pg_start + i;
-		unsigned long insert = efficeon_mask_memory(mem->memory[i]);
+		unsigned long insert = efficeon_mask_memory(mem->pages[i]);
 
 		page = (unsigned int *) efficeon_private.l1_table[index >> 10];
 
diff --git a/drivers/char/agp/generic.c b/drivers/char/agp/generic.c
index 2224b76..1e8b461 100644
--- a/drivers/char/agp/generic.c
+++ b/drivers/char/agp/generic.c
@@ -95,13 +95,13 @@
 
 void agp_alloc_page_array(size_t size, struct agp_memory *mem)
 {
-	mem->memory = NULL;
+	mem->pages = NULL;
 	mem->vmalloc_flag = false;
 
 	if (size <= 2*PAGE_SIZE)
-		mem->memory = kmalloc(size, GFP_KERNEL | __GFP_NORETRY);
-	if (mem->memory == NULL) {
-		mem->memory = vmalloc(size);
+		mem->pages = kmalloc(size, GFP_KERNEL | __GFP_NORETRY);
+	if (mem->pages == NULL) {
+		mem->pages = vmalloc(size);
 		mem->vmalloc_flag = true;
 	}
 }
@@ -110,9 +110,9 @@
 void agp_free_page_array(struct agp_memory *mem)
 {
 	if (mem->vmalloc_flag) {
-		vfree(mem->memory);
+		vfree(mem->pages);
 	} else {
-		kfree(mem->memory);
+		kfree(mem->pages);
 	}
 }
 EXPORT_SYMBOL(agp_free_page_array);
@@ -136,7 +136,7 @@
 
 	agp_alloc_page_array(alloc_size, new);
 
-	if (new->memory == NULL) {
+	if (new->pages == NULL) {
 		agp_free_key(new->key);
 		kfree(new);
 		return NULL;
@@ -162,7 +162,7 @@
 
 	agp_alloc_page_array(PAGE_SIZE * scratch_pages, new);
 
-	if (new->memory == NULL) {
+	if (new->pages == NULL) {
 		agp_free_key(new->key);
 		kfree(new);
 		return NULL;
@@ -206,15 +206,13 @@
 		} else {
 
 			for (i = 0; i < curr->page_count; i++) {
-				curr->memory[i] = (unsigned long)gart_to_virt(
-					curr->memory[i]);
 				curr->bridge->driver->agp_destroy_page(
-					(void *)curr->memory[i],
+					curr->pages[i],
 					AGP_PAGE_DESTROY_UNMAP);
 			}
 			for (i = 0; i < curr->page_count; i++) {
 				curr->bridge->driver->agp_destroy_page(
-					(void *)curr->memory[i],
+					curr->pages[i],
 					AGP_PAGE_DESTROY_FREE);
 			}
 		}
@@ -282,13 +280,13 @@
 	}
 
 	for (i = 0; i < page_count; i++) {
-		void *addr = bridge->driver->agp_alloc_page(bridge);
+		struct page *page = bridge->driver->agp_alloc_page(bridge);
 
-		if (addr == NULL) {
+		if (page == NULL) {
 			agp_free_memory(new);
 			return NULL;
 		}
-		new->memory[i] = virt_to_gart(addr);
+		new->pages[i] = page;
 		new->page_count++;
 	}
 	new->bridge = bridge;
@@ -1134,7 +1132,7 @@
 	}
 
 	for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
-		writel(bridge->driver->mask_memory(bridge, mem->memory[i], mask_type),
+		writel(bridge->driver->mask_memory(bridge, mem->pages[i], mask_type),
 		       bridge->gatt_table+j);
 	}
 	readl(bridge->gatt_table+j-1);	/* PCI Posting. */
@@ -1204,7 +1202,7 @@
 		return NULL;
 
 	for (i = 0; i < page_count; i++)
-		new->memory[i] = 0;
+		new->pages[i] = 0;
 	new->page_count = 0;
 	new->type = type;
 	new->num_scratch_pages = pages;
@@ -1237,23 +1235,20 @@
 		get_page(page);
 		atomic_inc(&agp_bridge->current_memory_agp);
 
-		/* set_memory_array_uc() needs virtual address */
-		mem->memory[i] = (unsigned long)page_address(page);
+		mem->pages[i] = page;
 		mem->page_count++;
 	}
 
 #ifdef CONFIG_X86
-	set_memory_array_uc(mem->memory, num_pages);
+	set_pages_array_uc(mem->pages, num_pages);
 #endif
 	ret = 0;
 out:
-	for (i = 0; i < mem->page_count; i++)
-		mem->memory[i] = virt_to_gart((void *)mem->memory[i]);
 	return ret;
 }
 EXPORT_SYMBOL(agp_generic_alloc_pages);
 
-void *agp_generic_alloc_page(struct agp_bridge_data *bridge)
+struct page *agp_generic_alloc_page(struct agp_bridge_data *bridge)
 {
 	struct page * page;
 
@@ -1265,56 +1260,47 @@
 
 	get_page(page);
 	atomic_inc(&agp_bridge->current_memory_agp);
-	return page_address(page);
+	return page;
 }
 EXPORT_SYMBOL(agp_generic_alloc_page);
 
 void agp_generic_destroy_pages(struct agp_memory *mem)
 {
 	int i;
-	void *addr;
 	struct page *page;
 
 	if (!mem)
 		return;
 
-	for (i = 0; i < mem->page_count; i++)
-		mem->memory[i] = (unsigned long)gart_to_virt(mem->memory[i]);
-
 #ifdef CONFIG_X86
-	set_memory_array_wb(mem->memory, mem->page_count);
+	set_pages_array_wb(mem->pages, mem->page_count);
 #endif
 
 	for (i = 0; i < mem->page_count; i++) {
-		addr = (void *)mem->memory[i];
-		page = virt_to_page(addr);
+		page = mem->pages[i];
 
 #ifndef CONFIG_X86
 		unmap_page_from_agp(page);
 #endif
-
 		put_page(page);
-		free_page((unsigned long)addr);
+		__free_page(page);
 		atomic_dec(&agp_bridge->current_memory_agp);
-		mem->memory[i] = 0;
+		mem->pages[i] = NULL;
 	}
 }
 EXPORT_SYMBOL(agp_generic_destroy_pages);
 
-void agp_generic_destroy_page(void *addr, int flags)
+void agp_generic_destroy_page(struct page *page, int flags)
 {
-	struct page *page;
-
-	if (addr == NULL)
+	if (page == NULL)
 		return;
 
-	page = virt_to_page(addr);
 	if (flags & AGP_PAGE_DESTROY_UNMAP)
 		unmap_page_from_agp(page);
 
 	if (flags & AGP_PAGE_DESTROY_FREE) {
 		put_page(page);
-		free_page((unsigned long)addr);
+		__free_page(page);
 		atomic_dec(&agp_bridge->current_memory_agp);
 	}
 }
@@ -1361,8 +1347,9 @@
 EXPORT_SYMBOL(global_cache_flush);
 
 unsigned long agp_generic_mask_memory(struct agp_bridge_data *bridge,
-	unsigned long addr, int type)
+				      struct page *page, int type)
 {
+	unsigned long addr = phys_to_gart(page_to_phys(page));
 	/* memory type is ignored in the generic routine */
 	if (bridge->driver->masks)
 		return addr | bridge->driver->masks[0].mask;
diff --git a/drivers/char/agp/hp-agp.c b/drivers/char/agp/hp-agp.c
index 183ac3f..8f3d4c1 100644
--- a/drivers/char/agp/hp-agp.c
+++ b/drivers/char/agp/hp-agp.c
@@ -361,13 +361,11 @@
 	for (i = 0, j = io_pg_start; i < mem->page_count; i++) {
 		unsigned long paddr;
 
-		paddr = mem->memory[i];
+		paddr = page_to_phys(mem->pages[i]);
 		for (k = 0;
 		     k < hp->io_pages_per_kpage;
 		     k++, j++, paddr += hp->io_page_size) {
-			hp->gatt[j] =
-				agp_bridge->driver->mask_memory(agp_bridge,
-					paddr, type);
+			hp->gatt[j] = HP_ZX1_PDIR_VALID_BIT | paddr;
 		}
 	}
 
@@ -397,8 +395,9 @@
 
 static unsigned long
 hp_zx1_mask_memory (struct agp_bridge_data *bridge,
-	unsigned long addr, int type)
+		    struct page *page, int type)
 {
+	unsigned long addr = phys_to_gart(page_to_phys(page));
 	return HP_ZX1_PDIR_VALID_BIT | addr;
 }
 
@@ -518,8 +517,9 @@
 	if (hp_zx1_setup(sba_hpa + HP_ZX1_IOC_OFFSET, lba_hpa))
 		return AE_OK;
 
-	printk(KERN_INFO PFX "Detected HP ZX1 %s AGP chipset (ioc=%lx, lba=%lx)\n",
-		(char *) context, sba_hpa + HP_ZX1_IOC_OFFSET, lba_hpa);
+	printk(KERN_INFO PFX "Detected HP ZX1 %s AGP chipset "
+		"(ioc=%llx, lba=%llx)\n", (char *)context,
+		sba_hpa + HP_ZX1_IOC_OFFSET, lba_hpa);
 
 	hp_zx1_gart_found = 1;
 	return AE_CTRL_TERMINATE; /* we only support one bridge; quit looking */
diff --git a/drivers/char/agp/i460-agp.c b/drivers/char/agp/i460-agp.c
index 10da687..60cc35b 100644
--- a/drivers/char/agp/i460-agp.c
+++ b/drivers/char/agp/i460-agp.c
@@ -60,6 +60,9 @@
  */
 #define WR_FLUSH_GATT(index)	RD_GATT(index)
 
+static unsigned long i460_mask_memory (struct agp_bridge_data *bridge,
+				       unsigned long addr, int type);
+
 static struct {
 	void *gatt;				/* ioremap'd GATT area */
 
@@ -74,6 +77,7 @@
 		unsigned long *alloced_map;	/* bitmap of kernel-pages in use */
 		int refcount;			/* number of kernel pages using the large page */
 		u64 paddr;			/* physical address of large page */
+		struct page *page; 		/* page pointer */
 	} *lp_desc;
 } i460;
 
@@ -294,7 +298,7 @@
 	void *temp;
 
 	pr_debug("i460_insert_memory_small_io_page(mem=%p, pg_start=%ld, type=%d, paddr0=0x%lx)\n",
-		 mem, pg_start, type, mem->memory[0]);
+		 mem, pg_start, type, page_to_phys(mem->pages[0]));
 
 	if (type >= AGP_USER_TYPES || mem->type >= AGP_USER_TYPES)
 		return -EINVAL;
@@ -321,10 +325,9 @@
 
 	io_page_size = 1UL << I460_IO_PAGE_SHIFT;
 	for (i = 0, j = io_pg_start; i < mem->page_count; i++) {
-		paddr = mem->memory[i];
+		paddr = phys_to_gart(page_to_phys(mem->pages[i]));
 		for (k = 0; k < I460_IOPAGES_PER_KPAGE; k++, j++, paddr += io_page_size)
-			WR_GATT(j, agp_bridge->driver->mask_memory(agp_bridge,
-				paddr, mem->type));
+			WR_GATT(j, i460_mask_memory(agp_bridge, paddr, mem->type));
 	}
 	WR_FLUSH_GATT(j - 1);
 	return 0;
@@ -364,10 +367,9 @@
 {
 	unsigned long order = I460_IO_PAGE_SHIFT - PAGE_SHIFT;
 	size_t map_size;
-	void *lpage;
 
-	lpage = (void *) __get_free_pages(GFP_KERNEL, order);
-	if (!lpage) {
+	lp->page = alloc_pages(GFP_KERNEL, order);
+	if (!lp->page) {
 		printk(KERN_ERR PFX "Couldn't alloc 4M GART page...\n");
 		return -ENOMEM;
 	}
@@ -375,12 +377,12 @@
 	map_size = ((I460_KPAGES_PER_IOPAGE + BITS_PER_LONG - 1) & -BITS_PER_LONG)/8;
 	lp->alloced_map = kzalloc(map_size, GFP_KERNEL);
 	if (!lp->alloced_map) {
-		free_pages((unsigned long) lpage, order);
+		__free_pages(lp->page, order);
 		printk(KERN_ERR PFX "Out of memory, we're in trouble...\n");
 		return -ENOMEM;
 	}
 
-	lp->paddr = virt_to_gart(lpage);
+	lp->paddr = phys_to_gart(page_to_phys(lp->page));
 	lp->refcount = 0;
 	atomic_add(I460_KPAGES_PER_IOPAGE, &agp_bridge->current_memory_agp);
 	return 0;
@@ -391,7 +393,7 @@
 	kfree(lp->alloced_map);
 	lp->alloced_map = NULL;
 
-	free_pages((unsigned long) gart_to_virt(lp->paddr), I460_IO_PAGE_SHIFT - PAGE_SHIFT);
+	__free_pages(lp->page, I460_IO_PAGE_SHIFT - PAGE_SHIFT);
 	atomic_sub(I460_KPAGES_PER_IOPAGE, &agp_bridge->current_memory_agp);
 }
 
@@ -439,8 +441,8 @@
 			if (i460_alloc_large_page(lp) < 0)
 				return -ENOMEM;
 			pg = lp - i460.lp_desc;
-			WR_GATT(pg, agp_bridge->driver->mask_memory(agp_bridge,
-				lp->paddr, 0));
+			WR_GATT(pg, i460_mask_memory(agp_bridge,
+						     lp->paddr, 0));
 			WR_FLUSH_GATT(pg);
 		}
 
@@ -448,7 +450,7 @@
 		     idx < ((lp == end) ? (end_offset + 1) : I460_KPAGES_PER_IOPAGE);
 		     idx++, i++)
 		{
-			mem->memory[i] = lp->paddr + idx*PAGE_SIZE;
+			mem->pages[i] = lp->page;
 			__set_bit(idx, lp->alloced_map);
 			++lp->refcount;
 		}
@@ -463,7 +465,7 @@
 	struct lp_desc *start, *end, *lp;
 	void *temp;
 
-	temp = agp_bridge->driver->current_size;
+	temp = agp_bridge->current_size;
 	num_entries = A_SIZE_8(temp)->num_entries;
 
 	/* Figure out what pg_start means in terms of our large GART pages */
@@ -477,7 +479,7 @@
 		     idx < ((lp == end) ? (end_offset + 1) : I460_KPAGES_PER_IOPAGE);
 		     idx++, i++)
 		{
-			mem->memory[i] = 0;
+			mem->pages[i] = NULL;
 			__clear_bit(idx, lp->alloced_map);
 			--lp->refcount;
 		}
@@ -521,7 +523,7 @@
  * Let's just hope nobody counts on the allocated AGP memory being there before bind time
  * (I don't think current drivers do)...
  */
-static void *i460_alloc_page (struct agp_bridge_data *bridge)
+static struct page *i460_alloc_page (struct agp_bridge_data *bridge)
 {
 	void *page;
 
@@ -534,7 +536,7 @@
 	return page;
 }
 
-static void i460_destroy_page (void *page, int flags)
+static void i460_destroy_page (struct page *page, int flags)
 {
 	if (I460_IO_PAGE_SHIFT <= PAGE_SHIFT) {
 		agp_generic_destroy_page(page, flags);
@@ -544,13 +546,20 @@
 #endif /* I460_LARGE_IO_PAGES */
 
 static unsigned long i460_mask_memory (struct agp_bridge_data *bridge,
-	unsigned long addr, int type)
+				       unsigned long addr, int type)
 {
 	/* Make sure the returned address is a valid GATT entry */
 	return bridge->driver->masks[0].mask
 		| (((addr & ~((1 << I460_IO_PAGE_SHIFT) - 1)) & 0xfffff000) >> 12);
 }
 
+static unsigned long i460_page_mask_memory(struct agp_bridge_data *bridge,
+					   struct page *page, int type)
+{
+	unsigned long addr = phys_to_gart(page_to_phys(page));
+	return i460_mask_memory(bridge, addr, type);
+}
+
 const struct agp_bridge_driver intel_i460_driver = {
 	.owner			= THIS_MODULE,
 	.aperture_sizes		= i460_sizes,
@@ -560,7 +569,7 @@
 	.fetch_size		= i460_fetch_size,
 	.cleanup		= i460_cleanup,
 	.tlb_flush		= i460_tlb_flush,
-	.mask_memory		= i460_mask_memory,
+	.mask_memory		= i460_page_mask_memory,
 	.masks			= i460_masks,
 	.agp_enable		= agp_generic_enable,
 	.cache_flush		= global_cache_flush,
diff --git a/drivers/char/agp/intel-agp.c b/drivers/char/agp/intel-agp.c
index 7a748fa..8c9d50d 100644
--- a/drivers/char/agp/intel-agp.c
+++ b/drivers/char/agp/intel-agp.c
@@ -257,7 +257,7 @@
 }
 
 /* Exists to support ARGB cursors */
-static void *i8xx_alloc_pages(void)
+static struct page *i8xx_alloc_pages(void)
 {
 	struct page *page;
 
@@ -272,17 +272,14 @@
 	}
 	get_page(page);
 	atomic_inc(&agp_bridge->current_memory_agp);
-	return page_address(page);
+	return page;
 }
 
-static void i8xx_destroy_pages(void *addr)
+static void i8xx_destroy_pages(struct page *page)
 {
-	struct page *page;
-
-	if (addr == NULL)
+	if (page == NULL)
 		return;
 
-	page = virt_to_page(addr);
 	set_pages_wb(page, 4);
 	put_page(page);
 	__free_pages(page, 2);
@@ -346,7 +343,7 @@
 			global_cache_flush();
 		for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
 			writel(agp_bridge->driver->mask_memory(agp_bridge,
-							       mem->memory[i],
+							       mem->pages[i],
 							       mask_type),
 			       intel_private.registers+I810_PTE_BASE+(j*4));
 		}
@@ -389,37 +386,37 @@
 static struct agp_memory *alloc_agpphysmem_i8xx(size_t pg_count, int type)
 {
 	struct agp_memory *new;
-	void *addr;
+	struct page *page;
 
 	switch (pg_count) {
-	case 1: addr = agp_bridge->driver->agp_alloc_page(agp_bridge);
+	case 1: page = agp_bridge->driver->agp_alloc_page(agp_bridge);
 		break;
 	case 4:
 		/* kludge to get 4 physical pages for ARGB cursor */
-		addr = i8xx_alloc_pages();
+		page = i8xx_alloc_pages();
 		break;
 	default:
 		return NULL;
 	}
 
-	if (addr == NULL)
+	if (page == NULL)
 		return NULL;
 
 	new = agp_create_memory(pg_count);
 	if (new == NULL)
 		return NULL;
 
-	new->memory[0] = virt_to_gart(addr);
+	new->pages[0] = page;
 	if (pg_count == 4) {
 		/* kludge to get 4 physical pages for ARGB cursor */
-		new->memory[1] = new->memory[0] + PAGE_SIZE;
-		new->memory[2] = new->memory[1] + PAGE_SIZE;
-		new->memory[3] = new->memory[2] + PAGE_SIZE;
+		new->pages[1] = new->pages[0] + 1;
+		new->pages[2] = new->pages[1] + 1;
+		new->pages[3] = new->pages[2] + 1;
 	}
 	new->page_count = pg_count;
 	new->num_scratch_pages = pg_count;
 	new->type = AGP_PHYS_MEMORY;
-	new->physical = new->memory[0];
+	new->physical = page_to_phys(new->pages[0]);
 	return new;
 }
 
@@ -451,13 +448,11 @@
 	agp_free_key(curr->key);
 	if (curr->type == AGP_PHYS_MEMORY) {
 		if (curr->page_count == 4)
-			i8xx_destroy_pages(gart_to_virt(curr->memory[0]));
+			i8xx_destroy_pages(curr->pages[0]);
 		else {
-			void *va = gart_to_virt(curr->memory[0]);
-
-			agp_bridge->driver->agp_destroy_page(va,
+			agp_bridge->driver->agp_destroy_page(curr->pages[0],
 							     AGP_PAGE_DESTROY_UNMAP);
-			agp_bridge->driver->agp_destroy_page(va,
+			agp_bridge->driver->agp_destroy_page(curr->pages[0],
 							     AGP_PAGE_DESTROY_FREE);
 		}
 		agp_free_page_array(curr);
@@ -466,8 +461,9 @@
 }
 
 static unsigned long intel_i810_mask_memory(struct agp_bridge_data *bridge,
-	unsigned long addr, int type)
+					    struct page *page, int type)
 {
+	unsigned long addr = phys_to_gart(page_to_phys(page));
 	/* Type checking must be done elsewhere */
 	return addr | bridge->driver->masks[type].mask;
 }
@@ -855,7 +851,7 @@
 
 	for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
 		writel(agp_bridge->driver->mask_memory(agp_bridge,
-						       mem->memory[i], mask_type),
+						       mem->pages[i], mask_type),
 		       intel_private.registers+I810_PTE_BASE+(j*4));
 	}
 	readl(intel_private.registers+I810_PTE_BASE+((j-1)*4));
@@ -1085,7 +1081,7 @@
 
 	for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
 		writel(agp_bridge->driver->mask_memory(agp_bridge,
-			mem->memory[i], mask_type), intel_private.gtt+j);
+						       mem->pages[i], mask_type), intel_private.gtt+j);
 	}
 
 	readl(intel_private.gtt+j-1);
@@ -1200,8 +1196,9 @@
  * this conditional.
  */
 static unsigned long intel_i965_mask_memory(struct agp_bridge_data *bridge,
-	unsigned long addr, int type)
+					    struct page *page, int type)
 {
+	dma_addr_t addr = phys_to_gart(page_to_phys(page));
 	/* Shift high bits down */
 	addr |= (addr >> 28) & 0xf0;
 
diff --git a/drivers/char/agp/nvidia-agp.c b/drivers/char/agp/nvidia-agp.c
index 16acee2..263d71d 100644
--- a/drivers/char/agp/nvidia-agp.c
+++ b/drivers/char/agp/nvidia-agp.c
@@ -225,7 +225,7 @@
 	}
 	for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
 		writel(agp_bridge->driver->mask_memory(agp_bridge,
-			mem->memory[i], mask_type),
+			mem->pages[i], mask_type),
 			agp_bridge->gatt_table+nvidia_private.pg_offset+j);
 	}
 
diff --git a/drivers/char/agp/parisc-agp.c b/drivers/char/agp/parisc-agp.c
index 699e342..f4bb43f 100644
--- a/drivers/char/agp/parisc-agp.c
+++ b/drivers/char/agp/parisc-agp.c
@@ -31,6 +31,10 @@
 #define AGP8X_MODE_BIT		3
 #define AGP8X_MODE		(1 << AGP8X_MODE_BIT)
 
+static unsigned long
+parisc_agp_mask_memory(struct agp_bridge_data *bridge, unsigned long addr,
+		       int type);
+
 static struct _parisc_agp_info {
 	void __iomem *ioc_regs;
 	void __iomem *lba_regs;
@@ -149,12 +153,12 @@
 	for (i = 0, j = io_pg_start; i < mem->page_count; i++) {
 		unsigned long paddr;
 
-		paddr = mem->memory[i];
+		paddr = page_to_phys(mem->pages[i]);
 		for (k = 0;
 		     k < info->io_pages_per_kpage;
 		     k++, j++, paddr += info->io_page_size) {
 			info->gatt[j] =
-				agp_bridge->driver->mask_memory(agp_bridge,
+				parisc_agp_mask_memory(agp_bridge,
 					paddr, type);
 		}
 	}
@@ -185,12 +189,20 @@
 }
 
 static unsigned long
-parisc_agp_mask_memory(struct agp_bridge_data *bridge,
-		    unsigned long addr, int type)
+parisc_agp_mask_memory(struct agp_bridge_data *bridge, unsigned long addr,
+		       int type)
 {
 	return SBA_PDIR_VALID_BIT | addr;
 }
 
+static unsigned long
+parisc_agp_page_mask_memory(struct agp_bridge_data *bridge, struct page *page,
+			    int type)
+{
+	unsigned long addr = phys_to_gart(page_to_phys(page));
+	return SBA_PDIR_VALID_BIT | addr;
+}
+
 static void
 parisc_agp_enable(struct agp_bridge_data *bridge, u32 mode)
 {
diff --git a/drivers/char/agp/sgi-agp.c b/drivers/char/agp/sgi-agp.c
index b972d83..d3ea2e4 100644
--- a/drivers/char/agp/sgi-agp.c
+++ b/drivers/char/agp/sgi-agp.c
@@ -38,7 +38,7 @@
 	{0, 0, 0},
 };
 
-static void *sgi_tioca_alloc_page(struct agp_bridge_data *bridge)
+static struct page *sgi_tioca_alloc_page(struct agp_bridge_data *bridge)
 {
 	struct page *page;
 	int nid;
@@ -52,7 +52,7 @@
 
 	get_page(page);
 	atomic_inc(&agp_bridge->current_memory_agp);
-	return page_address(page);
+	return page;
 }
 
 /*
@@ -71,8 +71,9 @@
  */
 static unsigned long
 sgi_tioca_mask_memory(struct agp_bridge_data *bridge,
-		      unsigned long addr, int type)
+		      struct page *page, int type)
 {
+	unsigned long addr = phys_to_gart(page_to_phys(page));
 	return tioca_physpage_to_gart(addr);
 }
 
@@ -189,7 +190,7 @@
 
 	for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
 		table[j] =
-		    bridge->driver->mask_memory(bridge, mem->memory[i],
+		    bridge->driver->mask_memory(bridge, mem->pages[i],
 						mem->type);
 	}
 
diff --git a/drivers/char/agp/sworks-agp.c b/drivers/char/agp/sworks-agp.c
index 6224df8..b964a21 100644
--- a/drivers/char/agp/sworks-agp.c
+++ b/drivers/char/agp/sworks-agp.c
@@ -349,7 +349,7 @@
 	for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
 		addr = (j * PAGE_SIZE) + agp_bridge->gart_bus_addr;
 		cur_gatt = SVRWRKS_GET_GATT(addr);
-		writel(agp_bridge->driver->mask_memory(agp_bridge, mem->memory[i], mem->type), cur_gatt+GET_GATT_OFF(addr));
+		writel(agp_bridge->driver->mask_memory(agp_bridge, mem->pages[i], mem->type), cur_gatt+GET_GATT_OFF(addr));
 	}
 	serverworks_tlbflush(mem);
 	return 0;
diff --git a/drivers/char/agp/uninorth-agp.c b/drivers/char/agp/uninorth-agp.c
index 03f95ec..f192c3b 100644
--- a/drivers/char/agp/uninorth-agp.c
+++ b/drivers/char/agp/uninorth-agp.c
@@ -146,13 +146,20 @@
 {
 	int i, j, num_entries;
 	void *temp;
+	int mask_type;
 
 	temp = agp_bridge->current_size;
 	num_entries = A_SIZE_32(temp)->num_entries;
 
-	if (type != 0 || mem->type != 0)
+	if (type != mem->type)
+		return -EINVAL;
+
+	mask_type = agp_bridge->driver->agp_type_to_mask_type(agp_bridge, type);
+	if (mask_type != 0) {
 		/* We know nothing of memory types */
 		return -EINVAL;
+	}
+
 	if ((pg_start + mem->page_count) > num_entries)
 		return -EINVAL;
 
@@ -166,9 +173,9 @@
 
 	for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
 		agp_bridge->gatt_table[j] =
-		    cpu_to_le32((mem->memory[i] & 0xFFFFF000UL) | 0x1UL);
-		flush_dcache_range((unsigned long)__va(mem->memory[i]),
-				   (unsigned long)__va(mem->memory[i])+0x1000);
+			cpu_to_le32((page_to_phys(mem->pages[i]) & 0xFFFFF000UL) | 0x1UL);
+		flush_dcache_range((unsigned long)__va(page_to_phys(mem->pages[i])),
+				   (unsigned long)__va(page_to_phys(mem->pages[i]))+0x1000);
 	}
 	(void)in_le32((volatile u32*)&agp_bridge->gatt_table[pg_start]);
 	mb();
@@ -184,13 +191,20 @@
 	int i, num_entries;
 	void *temp;
 	u32 *gp;
+	int mask_type;
 
 	temp = agp_bridge->current_size;
 	num_entries = A_SIZE_32(temp)->num_entries;
 
-	if (type != 0 || mem->type != 0)
+	if (type != mem->type)
+		return -EINVAL;
+
+	mask_type = agp_bridge->driver->agp_type_to_mask_type(agp_bridge, type);
+	if (mask_type != 0) {
 		/* We know nothing of memory types */
 		return -EINVAL;
+	}
+
 	if ((pg_start + mem->page_count) > num_entries)
 		return -EINVAL;
 
@@ -205,9 +219,9 @@
 	}
 
 	for (i = 0; i < mem->page_count; i++) {
-		gp[i] = (mem->memory[i] >> PAGE_SHIFT) | 0x80000000UL;
-		flush_dcache_range((unsigned long)__va(mem->memory[i]),
-				   (unsigned long)__va(mem->memory[i])+0x1000);
+		gp[i] = (page_to_phys(mem->pages[i]) >> PAGE_SHIFT) | 0x80000000UL;
+		flush_dcache_range((unsigned long)__va(page_to_phys(mem->pages[i])),
+				   (unsigned long)__va(page_to_phys(mem->pages[i]))+0x1000);
 	}
 	mb();
 	flush_dcache_range((unsigned long)gp, (unsigned long) &gp[i]);
diff --git a/drivers/char/dtlk.c b/drivers/char/dtlk.c
index 6b900b2..52e0658 100644
--- a/drivers/char/dtlk.c
+++ b/drivers/char/dtlk.c
@@ -571,7 +571,7 @@
 		portval = inb_p(dtlk_port_tts);
 	} while ((portval & TTS_READABLE) == 0 &&
 		 retries++ < DTLK_MAX_RETRIES);
-	if (retries == DTLK_MAX_RETRIES)
+	if (retries > DTLK_MAX_RETRIES)
 		printk(KERN_ERR "dtlk_read_tts() timeout\n");
 
 	ch = inb_p(dtlk_port_tts);	/* input from TTS port */
@@ -583,7 +583,7 @@
 		portval = inb_p(dtlk_port_tts);
 	} while ((portval & TTS_READABLE) != 0 &&
 		 retries++ < DTLK_MAX_RETRIES);
-	if (retries == DTLK_MAX_RETRIES)
+	if (retries > DTLK_MAX_RETRIES)
 		printk(KERN_ERR "dtlk_read_tts() timeout\n");
 
 	TRACE_RET;
@@ -640,7 +640,7 @@
 		while ((inb_p(dtlk_port_tts) & TTS_WRITABLE) == 0 &&
 		       retries++ < DTLK_MAX_RETRIES)	/* DT ready? */
 			;
-	if (retries == DTLK_MAX_RETRIES)
+	if (retries > DTLK_MAX_RETRIES)
 		printk(KERN_ERR "dtlk_write_tts() timeout\n");
 
 	outb_p(ch, dtlk_port_tts);	/* output to TTS port */
diff --git a/drivers/char/hvc_iseries.c b/drivers/char/hvc_iseries.c
index 449727b..936d05b 100644
--- a/drivers/char/hvc_iseries.c
+++ b/drivers/char/hvc_iseries.c
@@ -241,7 +241,7 @@
 static struct vio_driver hvc_vio_driver = {
 	.id_table	= hvc_driver_table,
 	.probe		= hvc_vio_probe,
-	.remove		= hvc_vio_remove,
+	.remove		= __devexit_p(hvc_vio_remove),
 	.driver		= {
 		.name	= hvc_driver_name,
 		.owner	= THIS_MODULE,
diff --git a/drivers/char/hvc_vio.c b/drivers/char/hvc_vio.c
index bd62dc8..c72b994 100644
--- a/drivers/char/hvc_vio.c
+++ b/drivers/char/hvc_vio.c
@@ -113,7 +113,7 @@
 static struct vio_driver hvc_vio_driver = {
 	.id_table	= hvc_driver_table,
 	.probe		= hvc_vio_probe,
-	.remove		= hvc_vio_remove,
+	.remove		= __devexit_p(hvc_vio_remove),
 	.driver		= {
 		.name	= hvc_driver_name,
 		.owner	= THIS_MODULE,
diff --git a/drivers/char/hvcs.c b/drivers/char/hvcs.c
index 7d64e42..266b858 100644
--- a/drivers/char/hvcs.c
+++ b/drivers/char/hvcs.c
@@ -868,7 +868,7 @@
 static struct vio_driver hvcs_vio_driver = {
 	.id_table	= hvcs_driver_table,
 	.probe		= hvcs_probe,
-	.remove		= hvcs_remove,
+	.remove		= __devexit_p(hvcs_remove),
 	.driver		= {
 		.name	= hvcs_driver_name,
 		.owner	= THIS_MODULE,
diff --git a/drivers/char/hw_random/Kconfig b/drivers/char/hw_random/Kconfig
index f4b3f72..ce66a70 100644
--- a/drivers/char/hw_random/Kconfig
+++ b/drivers/char/hw_random/Kconfig
@@ -149,6 +149,19 @@
 	  To compile this driver as a module, choose M here: the
 	  module will be called virtio-rng.  If unsure, say N.
 
+config HW_RANDOM_TX4939
+	tristate "TX4939 Random Number Generator support"
+	depends on HW_RANDOM && SOC_TX4939
+	default HW_RANDOM
+	---help---
+	  This driver provides kernel-side support for the Random Number
+	  Generator hardware found on TX4939 SoC.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called tx4939-rng.
+
+	  If unsure, say Y.
+
 config HW_RANDOM_MXC_RNGA
 	tristate "Freescale i.MX RNGA Random Number Generator"
 	depends on HW_RANDOM && ARCH_HAS_RNGA
diff --git a/drivers/char/hw_random/Makefile b/drivers/char/hw_random/Makefile
index fd1ecd2..676828b 100644
--- a/drivers/char/hw_random/Makefile
+++ b/drivers/char/hw_random/Makefile
@@ -15,4 +15,5 @@
 obj-$(CONFIG_HW_RANDOM_OMAP) += omap-rng.o
 obj-$(CONFIG_HW_RANDOM_PASEMI) += pasemi-rng.o
 obj-$(CONFIG_HW_RANDOM_VIRTIO) += virtio-rng.o
+obj-$(CONFIG_HW_RANDOM_TX4939) += tx4939-rng.o
 obj-$(CONFIG_HW_RANDOM_MXC_RNGA) += mxc-rnga.o
diff --git a/drivers/char/hw_random/tx4939-rng.c b/drivers/char/hw_random/tx4939-rng.c
new file mode 100644
index 0000000..544d908
--- /dev/null
+++ b/drivers/char/hw_random/tx4939-rng.c
@@ -0,0 +1,184 @@
+/*
+ * RNG driver for TX4939 Random Number Generators (RNG)
+ *
+ * Copyright (C) 2009 Atsushi Nemoto <anemo@mba.ocn.ne.jp>
+ *
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ */
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/delay.h>
+#include <linux/io.h>
+#include <linux/platform_device.h>
+#include <linux/hw_random.h>
+
+#define TX4939_RNG_RCSR		0x00000000
+#define TX4939_RNG_ROR(n)	(0x00000018 + (n) * 8)
+
+#define TX4939_RNG_RCSR_INTE	0x00000008
+#define TX4939_RNG_RCSR_RST	0x00000004
+#define TX4939_RNG_RCSR_FIN	0x00000002
+#define TX4939_RNG_RCSR_ST	0x00000001
+
+struct tx4939_rng {
+	struct hwrng rng;
+	void __iomem *base;
+	u64 databuf[3];
+	unsigned int data_avail;
+};
+
+static void rng_io_start(void)
+{
+#ifndef CONFIG_64BIT
+	/*
+	 * readq is reading a 64-bit register using a 64-bit load.  On
+	 * a 32-bit kernel however interrupts or any other processor
+	 * exception would clobber the upper 32-bit of the processor
+	 * register so interrupts need to be disabled.
+	 */
+	local_irq_disable();
+#endif
+}
+
+static void rng_io_end(void)
+{
+#ifndef CONFIG_64BIT
+	local_irq_enable();
+#endif
+}
+
+static u64 read_rng(void __iomem *base, unsigned int offset)
+{
+	return ____raw_readq(base + offset);
+}
+
+static void write_rng(u64 val, void __iomem *base, unsigned int offset)
+{
+	return ____raw_writeq(val, base + offset);
+}
+
+static int tx4939_rng_data_present(struct hwrng *rng, int wait)
+{
+	struct tx4939_rng *rngdev = container_of(rng, struct tx4939_rng, rng);
+	int i;
+
+	if (rngdev->data_avail)
+		return rngdev->data_avail;
+	for (i = 0; i < 20; i++) {
+		rng_io_start();
+		if (!(read_rng(rngdev->base, TX4939_RNG_RCSR)
+		      & TX4939_RNG_RCSR_ST)) {
+			rngdev->databuf[0] =
+				read_rng(rngdev->base, TX4939_RNG_ROR(0));
+			rngdev->databuf[1] =
+				read_rng(rngdev->base, TX4939_RNG_ROR(1));
+			rngdev->databuf[2] =
+				read_rng(rngdev->base, TX4939_RNG_ROR(2));
+			rngdev->data_avail =
+				sizeof(rngdev->databuf) / sizeof(u32);
+			/* Start RNG */
+			write_rng(TX4939_RNG_RCSR_ST,
+				  rngdev->base, TX4939_RNG_RCSR);
+			wait = 0;
+		}
+		rng_io_end();
+		if (!wait)
+			break;
+		/* 90 bus clock cycles by default for generation */
+		ndelay(90 * 5);
+	}
+	return rngdev->data_avail;
+}
+
+static int tx4939_rng_data_read(struct hwrng *rng, u32 *buffer)
+{
+	struct tx4939_rng *rngdev = container_of(rng, struct tx4939_rng, rng);
+
+	rngdev->data_avail--;
+	*buffer = *((u32 *)&rngdev->databuf + rngdev->data_avail);
+	return sizeof(u32);
+}
+
+static int __init tx4939_rng_probe(struct platform_device *dev)
+{
+	struct tx4939_rng *rngdev;
+	struct resource *r;
+	int i;
+
+	r = platform_get_resource(dev, IORESOURCE_MEM, 0);
+	if (!r)
+		return -EBUSY;
+	rngdev = devm_kzalloc(&dev->dev, sizeof(*rngdev), GFP_KERNEL);
+	if (!rngdev)
+		return -ENOMEM;
+	if (!devm_request_mem_region(&dev->dev, r->start, resource_size(r),
+				     dev_name(&dev->dev)))
+		return -EBUSY;
+	rngdev->base = devm_ioremap(&dev->dev, r->start, resource_size(r));
+	if (!rngdev->base)
+		return -EBUSY;
+
+	rngdev->rng.name = dev_name(&dev->dev);
+	rngdev->rng.data_present = tx4939_rng_data_present;
+	rngdev->rng.data_read = tx4939_rng_data_read;
+
+	rng_io_start();
+	/* Reset RNG */
+	write_rng(TX4939_RNG_RCSR_RST, rngdev->base, TX4939_RNG_RCSR);
+	write_rng(0, rngdev->base, TX4939_RNG_RCSR);
+	/* Start RNG */
+	write_rng(TX4939_RNG_RCSR_ST, rngdev->base, TX4939_RNG_RCSR);
+	rng_io_end();
+	/*
+	 * Drop first two results.  From the datasheet:
+	 * The quality of the random numbers generated immediately
+	 * after reset can be insufficient.  Therefore, do not use
+	 * random numbers obtained from the first and second
+	 * generations; use the ones from the third or subsequent
+	 * generation.
+	 */
+	for (i = 0; i < 2; i++) {
+		rngdev->data_avail = 0;
+		if (!tx4939_rng_data_present(&rngdev->rng, 1))
+			return -EIO;
+	}
+
+	platform_set_drvdata(dev, rngdev);
+	return hwrng_register(&rngdev->rng);
+}
+
+static int __exit tx4939_rng_remove(struct platform_device *dev)
+{
+	struct tx4939_rng *rngdev = platform_get_drvdata(dev);
+
+	hwrng_unregister(&rngdev->rng);
+	platform_set_drvdata(dev, NULL);
+	return 0;
+}
+
+static struct platform_driver tx4939_rng_driver = {
+	.driver		= {
+		.name	= "tx4939-rng",
+		.owner	= THIS_MODULE,
+	},
+	.remove = tx4939_rng_remove,
+};
+
+static int __init tx4939rng_init(void)
+{
+	return platform_driver_probe(&tx4939_rng_driver, tx4939_rng_probe);
+}
+
+static void __exit tx4939rng_exit(void)
+{
+	platform_driver_unregister(&tx4939_rng_driver);
+}
+
+module_init(tx4939rng_init);
+module_exit(tx4939rng_exit);
+
+MODULE_DESCRIPTION("H/W Random Number Generator (RNG) driver for TX4939");
+MODULE_LICENSE("GPL");
diff --git a/drivers/char/isicom.c b/drivers/char/isicom.c
index 4d745a8..4159292 100644
--- a/drivers/char/isicom.c
+++ b/drivers/char/isicom.c
@@ -1593,7 +1593,7 @@
 static int __devinit isicom_probe(struct pci_dev *pdev,
 	const struct pci_device_id *ent)
 {
-	unsigned int signature, index;
+	unsigned int uninitialized_var(signature), index;
 	int retval = -EPERM;
 	struct isi_board *board = NULL;
 
diff --git a/drivers/char/istallion.c b/drivers/char/istallion.c
index e18800c..0c999f5 100644
--- a/drivers/char/istallion.c
+++ b/drivers/char/istallion.c
@@ -3785,7 +3785,7 @@
 	return retval;
 }
 
-static void stli_pciremove(struct pci_dev *pdev)
+static void __devexit stli_pciremove(struct pci_dev *pdev)
 {
 	struct stlibrd *brdp = pci_get_drvdata(pdev);
 
diff --git a/drivers/char/keyboard.c b/drivers/char/keyboard.c
index de26a97..737be95 100644
--- a/drivers/char/keyboard.c
+++ b/drivers/char/keyboard.c
@@ -1123,8 +1123,6 @@
 
 #define HW_RAW(dev)	0
 
-#warning "Cannot generate rawmode keyboard for your architecture yet."
-
 static int emulate_raw(struct vc_data *vc, unsigned int keycode, unsigned char up_flag)
 {
 	if (keycode > 127)
diff --git a/drivers/char/mem.c b/drivers/char/mem.c
index f96d0be..afa8813 100644
--- a/drivers/char/mem.c
+++ b/drivers/char/mem.c
@@ -863,59 +863,58 @@
 	.write =	kmsg_write,
 };
 
-static int memory_open(struct inode * inode, struct file * filp)
+static const struct {
+	unsigned int		minor;
+	char			*name;
+	umode_t			mode;
+	const struct file_operations	*fops;
+	struct backing_dev_info	*dev_info;
+} devlist[] = { /* list of minor devices */
+	{1, "mem",     S_IRUSR | S_IWUSR | S_IRGRP, &mem_fops,
+		&directly_mappable_cdev_bdi},
+#ifdef CONFIG_DEVKMEM
+	{2, "kmem",    S_IRUSR | S_IWUSR | S_IRGRP, &kmem_fops,
+		&directly_mappable_cdev_bdi},
+#endif
+	{3, "null",    S_IRUGO | S_IWUGO,           &null_fops, NULL},
+#ifdef CONFIG_DEVPORT
+	{4, "port",    S_IRUSR | S_IWUSR | S_IRGRP, &port_fops, NULL},
+#endif
+	{5, "zero",    S_IRUGO | S_IWUGO,           &zero_fops, &zero_bdi},
+	{7, "full",    S_IRUGO | S_IWUGO,           &full_fops, NULL},
+	{8, "random",  S_IRUGO | S_IWUSR,           &random_fops, NULL},
+	{9, "urandom", S_IRUGO | S_IWUSR,           &urandom_fops, NULL},
+	{11,"kmsg",    S_IRUGO | S_IWUSR,           &kmsg_fops, NULL},
+#ifdef CONFIG_CRASH_DUMP
+	{12,"oldmem",    S_IRUSR | S_IWUSR | S_IRGRP, &oldmem_fops, NULL},
+#endif
+};
+
+static int memory_open(struct inode *inode, struct file *filp)
 {
 	int ret = 0;
+	int i;
 
 	lock_kernel();
-	switch (iminor(inode)) {
-		case 1:
-			filp->f_op = &mem_fops;
-			filp->f_mapping->backing_dev_info =
-				&directly_mappable_cdev_bdi;
+
+	for (i = 0; i < ARRAY_SIZE(devlist); i++) {
+		if (devlist[i].minor == iminor(inode)) {
+			filp->f_op = devlist[i].fops;
+			if (devlist[i].dev_info) {
+				filp->f_mapping->backing_dev_info =
+					devlist[i].dev_info;
+			}
+
 			break;
-#ifdef CONFIG_DEVKMEM
-		case 2:
-			filp->f_op = &kmem_fops;
-			filp->f_mapping->backing_dev_info =
-				&directly_mappable_cdev_bdi;
-			break;
-#endif
-		case 3:
-			filp->f_op = &null_fops;
-			break;
-#ifdef CONFIG_DEVPORT
-		case 4:
-			filp->f_op = &port_fops;
-			break;
-#endif
-		case 5:
-			filp->f_mapping->backing_dev_info = &zero_bdi;
-			filp->f_op = &zero_fops;
-			break;
-		case 7:
-			filp->f_op = &full_fops;
-			break;
-		case 8:
-			filp->f_op = &random_fops;
-			break;
-		case 9:
-			filp->f_op = &urandom_fops;
-			break;
-		case 11:
-			filp->f_op = &kmsg_fops;
-			break;
-#ifdef CONFIG_CRASH_DUMP
-		case 12:
-			filp->f_op = &oldmem_fops;
-			break;
-#endif
-		default:
-			unlock_kernel();
-			return -ENXIO;
+		}
 	}
-	if (filp->f_op && filp->f_op->open)
-		ret = filp->f_op->open(inode,filp);
+
+	if (i == ARRAY_SIZE(devlist))
+		ret = -ENXIO;
+	else
+		if (filp->f_op && filp->f_op->open)
+			ret = filp->f_op->open(inode, filp);
+
 	unlock_kernel();
 	return ret;
 }
@@ -924,30 +923,6 @@
 	.open		= memory_open,	/* just a selector for the real open */
 };
 
-static const struct {
-	unsigned int		minor;
-	char			*name;
-	umode_t			mode;
-	const struct file_operations	*fops;
-} devlist[] = { /* list of minor devices */
-	{1, "mem",     S_IRUSR | S_IWUSR | S_IRGRP, &mem_fops},
-#ifdef CONFIG_DEVKMEM
-	{2, "kmem",    S_IRUSR | S_IWUSR | S_IRGRP, &kmem_fops},
-#endif
-	{3, "null",    S_IRUGO | S_IWUGO,           &null_fops},
-#ifdef CONFIG_DEVPORT
-	{4, "port",    S_IRUSR | S_IWUSR | S_IRGRP, &port_fops},
-#endif
-	{5, "zero",    S_IRUGO | S_IWUGO,           &zero_fops},
-	{7, "full",    S_IRUGO | S_IWUGO,           &full_fops},
-	{8, "random",  S_IRUGO | S_IWUSR,           &random_fops},
-	{9, "urandom", S_IRUGO | S_IWUSR,           &urandom_fops},
-	{11,"kmsg",    S_IRUGO | S_IWUSR,           &kmsg_fops},
-#ifdef CONFIG_CRASH_DUMP
-	{12,"oldmem",    S_IRUSR | S_IWUSR | S_IRGRP, &oldmem_fops},
-#endif
-};
-
 static struct class *mem_class;
 
 static int __init chr_dev_init(void)
diff --git a/drivers/char/moxa.c b/drivers/char/moxa.c
index 65b6ff2..6799588 100644
--- a/drivers/char/moxa.c
+++ b/drivers/char/moxa.c
@@ -1189,6 +1189,11 @@
 		return -ENODEV;
 	}
 
+	if (port % MAX_PORTS_PER_BOARD >= brd->numPorts) {
+		retval = -ENODEV;
+		goto out_unlock;
+	}
+
 	ch = &brd->ports[port % MAX_PORTS_PER_BOARD];
 	ch->port.count++;
 	tty->driver_data = ch;
@@ -1213,8 +1218,8 @@
 				moxa_close_port(tty);
 	} else
 		ch->port.flags |= ASYNC_NORMAL_ACTIVE;
+out_unlock:
 	mutex_unlock(&moxa_openlock);
-
 	return retval;
 }
 
diff --git a/drivers/char/ppdev.c b/drivers/char/ppdev.c
index c84c34f..432655b 100644
--- a/drivers/char/ppdev.c
+++ b/drivers/char/ppdev.c
@@ -114,8 +114,7 @@
 
 	if (!(pp->flags & PP_CLAIMED)) {
 		/* Don't have the port claimed */
-		printk (KERN_DEBUG CHRDEV "%x: claim the port first\n",
-			minor);
+		pr_debug(CHRDEV "%x: claim the port first\n", minor);
 		return -EINVAL;
 	}
 
@@ -198,8 +197,7 @@
 
 	if (!(pp->flags & PP_CLAIMED)) {
 		/* Don't have the port claimed */
-		printk (KERN_DEBUG CHRDEV "%x: claim the port first\n",
-			minor);
+		pr_debug(CHRDEV "%x: claim the port first\n", minor);
 		return -EINVAL;
 	}
 
@@ -313,7 +311,7 @@
 	}
 
 	pp->pdev = pdev;
-	printk (KERN_DEBUG "%s: registered pardevice\n", name);
+	pr_debug("%s: registered pardevice\n", name);
 	return 0;
 }
 
@@ -343,8 +341,7 @@
 		int ret;
 
 		if (pp->flags & PP_CLAIMED) {
-			printk (KERN_DEBUG CHRDEV
-				"%x: you've already got it!\n", minor);
+			pr_debug(CHRDEV "%x: you've already got it!\n", minor);
 			return -EINVAL;
 		}
 
@@ -379,7 +376,7 @@
 	    }
 	case PPEXCL:
 		if (pp->pdev) {
-			printk (KERN_DEBUG CHRDEV "%x: too late for PPEXCL; "
+			pr_debug(CHRDEV "%x: too late for PPEXCL; "
 				"already registered\n", minor);
 			if (pp->flags & PP_EXCL)
 				/* But it's not really an error. */
@@ -491,8 +488,7 @@
 	/* Everything else requires the port to be claimed, so check
 	 * that now. */
 	if ((pp->flags & PP_CLAIMED) == 0) {
-		printk (KERN_DEBUG CHRDEV "%x: claim the port first\n",
-			minor);
+		pr_debug(CHRDEV "%x: claim the port first\n", minor);
 		return -EINVAL;
 	}
 
@@ -624,8 +620,7 @@
 		return 0;
 
 	default:
-		printk (KERN_DEBUG CHRDEV "%x: What? (cmd=0x%x)\n", minor,
-			cmd);
+		pr_debug(CHRDEV "%x: What? (cmd=0x%x)\n", minor, cmd);
 		return -EINVAL;
 	}
 
@@ -698,9 +693,8 @@
 	}
 	if (compat_negot) {
 		parport_negotiate (pp->pdev->port, IEEE1284_MODE_COMPAT);
-		printk (KERN_DEBUG CHRDEV
-			"%x: negotiated back to compatibility mode because "
-			"user-space forgot\n", minor);
+		pr_debug(CHRDEV "%x: negotiated back to compatibility "
+			"mode because user-space forgot\n", minor);
 	}
 
 	if (pp->flags & PP_CLAIMED) {
@@ -713,7 +707,7 @@
 		info->phase = pp->saved_state.phase;
 		parport_release (pp->pdev);
 		if (compat_negot != 1) {
-			printk (KERN_DEBUG CHRDEV "%x: released pardevice "
+			pr_debug(CHRDEV "%x: released pardevice "
 				"because user-space forgot\n", minor);
 		}
 	}
@@ -723,8 +717,7 @@
 		parport_unregister_device (pp->pdev);
 		kfree (name);
 		pp->pdev = NULL;
-		printk (KERN_DEBUG CHRDEV "%x: unregistered pardevice\n",
-			minor);
+		pr_debug(CHRDEV "%x: unregistered pardevice\n", minor);
 	}
 
 	kfree (pp);
diff --git a/drivers/char/sysrq.c b/drivers/char/sysrq.c
index 39a05b5..0db3585 100644
--- a/drivers/char/sysrq.c
+++ b/drivers/char/sysrq.c
@@ -121,20 +121,17 @@
 #define sysrq_unraw_op (*(struct sysrq_key_op *)0)
 #endif /* CONFIG_VT */
 
-#ifdef CONFIG_KEXEC
-static void sysrq_handle_crashdump(int key, struct tty_struct *tty)
+static void sysrq_handle_crash(int key, struct tty_struct *tty)
 {
-	crash_kexec(get_irq_regs());
+	char *killer = NULL;
+	*killer = 1;
 }
 static struct sysrq_key_op sysrq_crashdump_op = {
-	.handler	= sysrq_handle_crashdump,
-	.help_msg	= "Crashdump",
-	.action_msg	= "Trigger a crashdump",
+	.handler	= sysrq_handle_crash,
+	.help_msg	= "Crash",
+	.action_msg	= "Trigger a crash",
 	.enable_mask	= SYSRQ_ENABLE_DUMP,
 };
-#else
-#define sysrq_crashdump_op (*(struct sysrq_key_op *)0)
-#endif
 
 static void sysrq_handle_reboot(int key, struct tty_struct *tty)
 {
diff --git a/drivers/clocksource/sh_cmt.c b/drivers/clocksource/sh_cmt.c
index cf56a2a..2964f5f 100644
--- a/drivers/clocksource/sh_cmt.c
+++ b/drivers/clocksource/sh_cmt.c
@@ -184,6 +184,9 @@
 	/* disable channel */
 	sh_cmt_start_stop_ch(p, 0);
 
+	/* disable interrupts in CMT block */
+	sh_cmt_write(p, CMCSR, 0);
+
 	/* stop clock */
 	clk_disable(p->clk);
 }
@@ -599,7 +602,6 @@
 	p->irqaction.handler = sh_cmt_interrupt;
 	p->irqaction.dev_id = p;
 	p->irqaction.flags = IRQF_DISABLED | IRQF_TIMER | IRQF_IRQPOLL;
-	p->irqaction.mask = CPU_MASK_NONE;
 	ret = setup_irq(irq, &p->irqaction);
 	if (ret) {
 		pr_err("sh_cmt: failed to request irq %d\n", irq);
diff --git a/drivers/clocksource/sh_mtu2.c b/drivers/clocksource/sh_mtu2.c
index d1ae754..973e714 100644
--- a/drivers/clocksource/sh_mtu2.c
+++ b/drivers/clocksource/sh_mtu2.c
@@ -283,7 +283,6 @@
 	p->irqaction.dev_id = p;
 	p->irqaction.irq = irq;
 	p->irqaction.flags = IRQF_DISABLED | IRQF_TIMER | IRQF_IRQPOLL;
-	p->irqaction.mask = CPU_MASK_NONE;
 
 	/* get hold of clock */
 	p->clk = clk_get(&p->pdev->dev, cfg->clk);
diff --git a/drivers/clocksource/sh_tmu.c b/drivers/clocksource/sh_tmu.c
index d6ea439..9ffb05f 100644
--- a/drivers/clocksource/sh_tmu.c
+++ b/drivers/clocksource/sh_tmu.c
@@ -138,6 +138,9 @@
 	/* disable channel */
 	sh_tmu_start_stop_ch(p, 0);
 
+	/* disable interrupts in TMU block */
+	sh_tmu_write(p, TCR, 0x0000);
+
 	/* stop clock */
 	clk_disable(p->clk);
 }
@@ -385,7 +388,6 @@
 	p->irqaction.dev_id = p;
 	p->irqaction.irq = irq;
 	p->irqaction.flags = IRQF_DISABLED | IRQF_TIMER | IRQF_IRQPOLL;
-	p->irqaction.mask = CPU_MASK_NONE;
 
 	/* get hold of clock */
 	p->clk = clk_get(&p->pdev->dev, cfg->clk);
diff --git a/drivers/cpufreq/cpufreq_conservative.c b/drivers/cpufreq/cpufreq_conservative.c
index 7a74d17..7fc58af 100644
--- a/drivers/cpufreq/cpufreq_conservative.c
+++ b/drivers/cpufreq/cpufreq_conservative.c
@@ -42,27 +42,12 @@
  * this governor will not work.
  * All times here are in uS.
  */
-static unsigned int def_sampling_rate;
 #define MIN_SAMPLING_RATE_RATIO			(2)
-/* for correct statistics, we need at least 10 ticks between each measure */
-#define MIN_STAT_SAMPLING_RATE 			\
-			(MIN_SAMPLING_RATE_RATIO * jiffies_to_usecs(10))
-#define MIN_SAMPLING_RATE			\
-			(def_sampling_rate / MIN_SAMPLING_RATE_RATIO)
-/* Above MIN_SAMPLING_RATE will vanish with its sysfs file soon
- * Define the minimal settable sampling rate to the greater of:
- *   - "HW transition latency" * 100 (same as default sampling / 10)
- *   - MIN_STAT_SAMPLING_RATE
- * To avoid that userspace shoots itself.
-*/
-static unsigned int minimum_sampling_rate(void)
-{
-	return max(def_sampling_rate / 10, MIN_STAT_SAMPLING_RATE);
-}
 
-/* This will also vanish soon with removing sampling_rate_max */
-#define MAX_SAMPLING_RATE			(500 * def_sampling_rate)
+static unsigned int min_sampling_rate;
+
 #define LATENCY_MULTIPLIER			(1000)
+#define MIN_LATENCY_MULTIPLIER			(100)
 #define DEF_SAMPLING_DOWN_FACTOR		(1)
 #define MAX_SAMPLING_DOWN_FACTOR		(10)
 #define TRANSITION_LATENCY_LIMIT		(10 * 1000 * 1000)
@@ -182,27 +167,14 @@
 /************************** sysfs interface ************************/
 static ssize_t show_sampling_rate_max(struct cpufreq_policy *policy, char *buf)
 {
-	static int print_once;
-
-	if (!print_once) {
-		printk(KERN_INFO "CPUFREQ: conservative sampling_rate_max "
-		       "sysfs file is deprecated - used by: %s\n",
-		       current->comm);
-		print_once = 1;
-	}
-	return sprintf(buf, "%u\n", MAX_SAMPLING_RATE);
+	printk_once(KERN_INFO "CPUFREQ: conservative sampling_rate_max "
+		    "sysfs file is deprecated - used by: %s\n", current->comm);
+	return sprintf(buf, "%u\n", -1U);
 }
 
 static ssize_t show_sampling_rate_min(struct cpufreq_policy *policy, char *buf)
 {
-	static int print_once;
-
-	if (!print_once) {
-		printk(KERN_INFO "CPUFREQ: conservative sampling_rate_max "
-		       "sysfs file is deprecated - used by: %s\n", current->comm);
-		print_once = 1;
-	}
-	return sprintf(buf, "%u\n", MIN_SAMPLING_RATE);
+	return sprintf(buf, "%u\n", min_sampling_rate);
 }
 
 #define define_one_ro(_name)		\
@@ -254,7 +226,7 @@
 		return -EINVAL;
 
 	mutex_lock(&dbs_mutex);
-	dbs_tuners_ins.sampling_rate = max(input, minimum_sampling_rate());
+	dbs_tuners_ins.sampling_rate = max(input, min_sampling_rate);
 	mutex_unlock(&dbs_mutex);
 
 	return count;
@@ -601,11 +573,18 @@
 			if (latency == 0)
 				latency = 1;
 
-			def_sampling_rate =
-				max(latency * LATENCY_MULTIPLIER,
-				    MIN_STAT_SAMPLING_RATE);
-
-			dbs_tuners_ins.sampling_rate = def_sampling_rate;
+			/*
+			 * conservative does not implement micro like ondemand
+			 * governor, thus we are bound to jiffes/HZ
+			 */
+			min_sampling_rate =
+				MIN_SAMPLING_RATE_RATIO * jiffies_to_usecs(10);
+			/* Bring kernel and HW constraints together */
+			min_sampling_rate = max(min_sampling_rate,
+					MIN_LATENCY_MULTIPLIER * latency);
+			dbs_tuners_ins.sampling_rate =
+				max(min_sampling_rate,
+				    latency * LATENCY_MULTIPLIER);
 
 			cpufreq_register_notifier(
 					&dbs_cpufreq_notifier_block,
diff --git a/drivers/cpufreq/cpufreq_ondemand.c b/drivers/cpufreq/cpufreq_ondemand.c
index e741c33..1911d17 100644
--- a/drivers/cpufreq/cpufreq_ondemand.c
+++ b/drivers/cpufreq/cpufreq_ondemand.c
@@ -32,6 +32,7 @@
 #define DEF_FREQUENCY_UP_THRESHOLD		(80)
 #define MICRO_FREQUENCY_DOWN_DIFFERENTIAL	(3)
 #define MICRO_FREQUENCY_UP_THRESHOLD		(95)
+#define MICRO_FREQUENCY_MIN_SAMPLE_RATE		(10000)
 #define MIN_FREQUENCY_UP_THRESHOLD		(11)
 #define MAX_FREQUENCY_UP_THRESHOLD		(100)
 
@@ -45,27 +46,12 @@
  * this governor will not work.
  * All times here are in uS.
  */
-static unsigned int def_sampling_rate;
 #define MIN_SAMPLING_RATE_RATIO			(2)
-/* for correct statistics, we need at least 10 ticks between each measure */
-#define MIN_STAT_SAMPLING_RATE 			\
-			(MIN_SAMPLING_RATE_RATIO * jiffies_to_usecs(10))
-#define MIN_SAMPLING_RATE			\
-			(def_sampling_rate / MIN_SAMPLING_RATE_RATIO)
-/* Above MIN_SAMPLING_RATE will vanish with its sysfs file soon
- * Define the minimal settable sampling rate to the greater of:
- *   - "HW transition latency" * 100 (same as default sampling / 10)
- *   - MIN_STAT_SAMPLING_RATE
- * To avoid that userspace shoots itself.
-*/
-static unsigned int minimum_sampling_rate(void)
-{
-	return max(def_sampling_rate / 10, MIN_STAT_SAMPLING_RATE);
-}
 
-/* This will also vanish soon with removing sampling_rate_max */
-#define MAX_SAMPLING_RATE			(500 * def_sampling_rate)
+static unsigned int min_sampling_rate;
+
 #define LATENCY_MULTIPLIER			(1000)
+#define MIN_LATENCY_MULTIPLIER			(100)
 #define TRANSITION_LATENCY_LIMIT		(10 * 1000 * 1000)
 
 static void do_dbs_timer(struct work_struct *work);
@@ -219,28 +205,14 @@
 /************************** sysfs interface ************************/
 static ssize_t show_sampling_rate_max(struct cpufreq_policy *policy, char *buf)
 {
-	static int print_once;
-
-	if (!print_once) {
-		printk(KERN_INFO "CPUFREQ: ondemand sampling_rate_max "
-		       "sysfs file is deprecated - used by: %s\n",
-		       current->comm);
-		print_once = 1;
-	}
-	return sprintf(buf, "%u\n", MAX_SAMPLING_RATE);
+	printk_once(KERN_INFO "CPUFREQ: ondemand sampling_rate_max "
+	       "sysfs file is deprecated - used by: %s\n", current->comm);
+	return sprintf(buf, "%u\n", -1U);
 }
 
 static ssize_t show_sampling_rate_min(struct cpufreq_policy *policy, char *buf)
 {
-	static int print_once;
-
-	if (!print_once) {
-		printk(KERN_INFO "CPUFREQ: ondemand sampling_rate_min "
-		       "sysfs file is deprecated - used by: %s\n",
-		       current->comm);
-		print_once = 1;
-	}
-	return sprintf(buf, "%u\n", MIN_SAMPLING_RATE);
+	return sprintf(buf, "%u\n", min_sampling_rate);
 }
 
 #define define_one_ro(_name)		\
@@ -274,7 +246,7 @@
 		mutex_unlock(&dbs_mutex);
 		return -EINVAL;
 	}
-	dbs_tuners_ins.sampling_rate = max(input, minimum_sampling_rate());
+	dbs_tuners_ins.sampling_rate = max(input, min_sampling_rate);
 	mutex_unlock(&dbs_mutex);
 
 	return count;
@@ -619,12 +591,12 @@
 			latency = policy->cpuinfo.transition_latency / 1000;
 			if (latency == 0)
 				latency = 1;
-
-			def_sampling_rate =
-				max(latency * LATENCY_MULTIPLIER,
-				    MIN_STAT_SAMPLING_RATE);
-
-			dbs_tuners_ins.sampling_rate = def_sampling_rate;
+			/* Bring kernel and HW constraints together */
+			min_sampling_rate = max(min_sampling_rate,
+					MIN_LATENCY_MULTIPLIER * latency);
+			dbs_tuners_ins.sampling_rate =
+				max(min_sampling_rate,
+				    latency * LATENCY_MULTIPLIER);
 		}
 		dbs_timer_init(this_dbs_info);
 
@@ -678,6 +650,16 @@
 		dbs_tuners_ins.up_threshold = MICRO_FREQUENCY_UP_THRESHOLD;
 		dbs_tuners_ins.down_differential =
 					MICRO_FREQUENCY_DOWN_DIFFERENTIAL;
+		/*
+		 * In no_hz/micro accounting case we set the minimum frequency
+		 * not depending on HZ, but fixed (very low). The deferred
+		 * timer might skip some samples if idle/sleeping as needed.
+		*/
+		min_sampling_rate = MICRO_FREQUENCY_MIN_SAMPLE_RATE;
+	} else {
+		/* For correct statistics, we need 10 ticks for each measure */
+		min_sampling_rate =
+			MIN_SAMPLING_RATE_RATIO * jiffies_to_usecs(10);
 	}
 
 	kondemand_wq = create_workqueue("kondemand");
diff --git a/drivers/dma/Kconfig b/drivers/dma/Kconfig
index 3b3c01b..070357a 100644
--- a/drivers/dma/Kconfig
+++ b/drivers/dma/Kconfig
@@ -81,6 +81,14 @@
 	  To avoid bloating the irq_desc[] array we allocate a sufficient
 	  number of IRQ slots and map them dynamically to specific sources.
 
+config TXX9_DMAC
+	tristate "Toshiba TXx9 SoC DMA support"
+	depends on MACH_TX49XX || MACH_TX39XX
+	select DMA_ENGINE
+	help
+	  Support the TXx9 SoC internal DMA controller.  This can be
+	  integrated in chips such as the Toshiba TX4927/38/39.
+
 config DMA_ENGINE
 	bool
 
diff --git a/drivers/dma/Makefile b/drivers/dma/Makefile
index 2e5dc96..a0b6564 100644
--- a/drivers/dma/Makefile
+++ b/drivers/dma/Makefile
@@ -8,3 +8,4 @@
 obj-$(CONFIG_MV_XOR) += mv_xor.o
 obj-$(CONFIG_DW_DMAC) += dw_dmac.o
 obj-$(CONFIG_MX3_IPU) += ipu/
+obj-$(CONFIG_TXX9_DMAC) += txx9dmac.o
diff --git a/drivers/dma/txx9dmac.c b/drivers/dma/txx9dmac.c
new file mode 100644
index 0000000..9aa9ea9
--- /dev/null
+++ b/drivers/dma/txx9dmac.c
@@ -0,0 +1,1354 @@
+/*
+ * Driver for the TXx9 SoC DMA Controller
+ *
+ * Copyright (C) 2009 Atsushi Nemoto
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+#include <linux/dma-mapping.h>
+#include <linux/init.h>
+#include <linux/interrupt.h>
+#include <linux/io.h>
+#include <linux/module.h>
+#include <linux/platform_device.h>
+#include <linux/slab.h>
+#include <linux/scatterlist.h>
+#include "txx9dmac.h"
+
+static struct txx9dmac_chan *to_txx9dmac_chan(struct dma_chan *chan)
+{
+	return container_of(chan, struct txx9dmac_chan, chan);
+}
+
+static struct txx9dmac_cregs __iomem *__dma_regs(const struct txx9dmac_chan *dc)
+{
+	return dc->ch_regs;
+}
+
+static struct txx9dmac_cregs32 __iomem *__dma_regs32(
+	const struct txx9dmac_chan *dc)
+{
+	return dc->ch_regs;
+}
+
+#define channel64_readq(dc, name) \
+	__raw_readq(&(__dma_regs(dc)->name))
+#define channel64_writeq(dc, name, val) \
+	__raw_writeq((val), &(__dma_regs(dc)->name))
+#define channel64_readl(dc, name) \
+	__raw_readl(&(__dma_regs(dc)->name))
+#define channel64_writel(dc, name, val) \
+	__raw_writel((val), &(__dma_regs(dc)->name))
+
+#define channel32_readl(dc, name) \
+	__raw_readl(&(__dma_regs32(dc)->name))
+#define channel32_writel(dc, name, val) \
+	__raw_writel((val), &(__dma_regs32(dc)->name))
+
+#define channel_readq(dc, name) channel64_readq(dc, name)
+#define channel_writeq(dc, name, val) channel64_writeq(dc, name, val)
+#define channel_readl(dc, name) \
+	(is_dmac64(dc) ? \
+	 channel64_readl(dc, name) : channel32_readl(dc, name))
+#define channel_writel(dc, name, val) \
+	(is_dmac64(dc) ? \
+	 channel64_writel(dc, name, val) : channel32_writel(dc, name, val))
+
+static dma_addr_t channel64_read_CHAR(const struct txx9dmac_chan *dc)
+{
+	if (sizeof(__dma_regs(dc)->CHAR) == sizeof(u64))
+		return channel64_readq(dc, CHAR);
+	else
+		return channel64_readl(dc, CHAR);
+}
+
+static void channel64_write_CHAR(const struct txx9dmac_chan *dc, dma_addr_t val)
+{
+	if (sizeof(__dma_regs(dc)->CHAR) == sizeof(u64))
+		channel64_writeq(dc, CHAR, val);
+	else
+		channel64_writel(dc, CHAR, val);
+}
+
+static void channel64_clear_CHAR(const struct txx9dmac_chan *dc)
+{
+#if defined(CONFIG_32BIT) && !defined(CONFIG_64BIT_PHYS_ADDR)
+	channel64_writel(dc, CHAR, 0);
+	channel64_writel(dc, __pad_CHAR, 0);
+#else
+	channel64_writeq(dc, CHAR, 0);
+#endif
+}
+
+static dma_addr_t channel_read_CHAR(const struct txx9dmac_chan *dc)
+{
+	if (is_dmac64(dc))
+		return channel64_read_CHAR(dc);
+	else
+		return channel32_readl(dc, CHAR);
+}
+
+static void channel_write_CHAR(const struct txx9dmac_chan *dc, dma_addr_t val)
+{
+	if (is_dmac64(dc))
+		channel64_write_CHAR(dc, val);
+	else
+		channel32_writel(dc, CHAR, val);
+}
+
+static struct txx9dmac_regs __iomem *__txx9dmac_regs(
+	const struct txx9dmac_dev *ddev)
+{
+	return ddev->regs;
+}
+
+static struct txx9dmac_regs32 __iomem *__txx9dmac_regs32(
+	const struct txx9dmac_dev *ddev)
+{
+	return ddev->regs;
+}
+
+#define dma64_readl(ddev, name) \
+	__raw_readl(&(__txx9dmac_regs(ddev)->name))
+#define dma64_writel(ddev, name, val) \
+	__raw_writel((val), &(__txx9dmac_regs(ddev)->name))
+
+#define dma32_readl(ddev, name) \
+	__raw_readl(&(__txx9dmac_regs32(ddev)->name))
+#define dma32_writel(ddev, name, val) \
+	__raw_writel((val), &(__txx9dmac_regs32(ddev)->name))
+
+#define dma_readl(ddev, name) \
+	(__is_dmac64(ddev) ? \
+	dma64_readl(ddev, name) : dma32_readl(ddev, name))
+#define dma_writel(ddev, name, val) \
+	(__is_dmac64(ddev) ? \
+	dma64_writel(ddev, name, val) : dma32_writel(ddev, name, val))
+
+static struct device *chan2dev(struct dma_chan *chan)
+{
+	return &chan->dev->device;
+}
+static struct device *chan2parent(struct dma_chan *chan)
+{
+	return chan->dev->device.parent;
+}
+
+static struct txx9dmac_desc *
+txd_to_txx9dmac_desc(struct dma_async_tx_descriptor *txd)
+{
+	return container_of(txd, struct txx9dmac_desc, txd);
+}
+
+static dma_addr_t desc_read_CHAR(const struct txx9dmac_chan *dc,
+				 const struct txx9dmac_desc *desc)
+{
+	return is_dmac64(dc) ? desc->hwdesc.CHAR : desc->hwdesc32.CHAR;
+}
+
+static void desc_write_CHAR(const struct txx9dmac_chan *dc,
+			    struct txx9dmac_desc *desc, dma_addr_t val)
+{
+	if (is_dmac64(dc))
+		desc->hwdesc.CHAR = val;
+	else
+		desc->hwdesc32.CHAR = val;
+}
+
+#define TXX9_DMA_MAX_COUNT	0x04000000
+
+#define TXX9_DMA_INITIAL_DESC_COUNT	64
+
+static struct txx9dmac_desc *txx9dmac_first_active(struct txx9dmac_chan *dc)
+{
+	return list_entry(dc->active_list.next,
+			  struct txx9dmac_desc, desc_node);
+}
+
+static struct txx9dmac_desc *txx9dmac_last_active(struct txx9dmac_chan *dc)
+{
+	return list_entry(dc->active_list.prev,
+			  struct txx9dmac_desc, desc_node);
+}
+
+static struct txx9dmac_desc *txx9dmac_first_queued(struct txx9dmac_chan *dc)
+{
+	return list_entry(dc->queue.next, struct txx9dmac_desc, desc_node);
+}
+
+static struct txx9dmac_desc *txx9dmac_last_child(struct txx9dmac_desc *desc)
+{
+	if (!list_empty(&desc->txd.tx_list))
+		desc = list_entry(desc->txd.tx_list.prev,
+				  struct txx9dmac_desc, desc_node);
+	return desc;
+}
+
+static dma_cookie_t txx9dmac_tx_submit(struct dma_async_tx_descriptor *tx);
+
+static struct txx9dmac_desc *txx9dmac_desc_alloc(struct txx9dmac_chan *dc,
+						 gfp_t flags)
+{
+	struct txx9dmac_dev *ddev = dc->ddev;
+	struct txx9dmac_desc *desc;
+
+	desc = kzalloc(sizeof(*desc), flags);
+	if (!desc)
+		return NULL;
+	dma_async_tx_descriptor_init(&desc->txd, &dc->chan);
+	desc->txd.tx_submit = txx9dmac_tx_submit;
+	/* txd.flags will be overwritten in prep funcs */
+	desc->txd.flags = DMA_CTRL_ACK;
+	desc->txd.phys = dma_map_single(chan2parent(&dc->chan), &desc->hwdesc,
+					ddev->descsize, DMA_TO_DEVICE);
+	return desc;
+}
+
+static struct txx9dmac_desc *txx9dmac_desc_get(struct txx9dmac_chan *dc)
+{
+	struct txx9dmac_desc *desc, *_desc;
+	struct txx9dmac_desc *ret = NULL;
+	unsigned int i = 0;
+
+	spin_lock_bh(&dc->lock);
+	list_for_each_entry_safe(desc, _desc, &dc->free_list, desc_node) {
+		if (async_tx_test_ack(&desc->txd)) {
+			list_del(&desc->desc_node);
+			ret = desc;
+			break;
+		}
+		dev_dbg(chan2dev(&dc->chan), "desc %p not ACKed\n", desc);
+		i++;
+	}
+	spin_unlock_bh(&dc->lock);
+
+	dev_vdbg(chan2dev(&dc->chan), "scanned %u descriptors on freelist\n",
+		 i);
+	if (!ret) {
+		ret = txx9dmac_desc_alloc(dc, GFP_ATOMIC);
+		if (ret) {
+			spin_lock_bh(&dc->lock);
+			dc->descs_allocated++;
+			spin_unlock_bh(&dc->lock);
+		} else
+			dev_err(chan2dev(&dc->chan),
+				"not enough descriptors available\n");
+	}
+	return ret;
+}
+
+static void txx9dmac_sync_desc_for_cpu(struct txx9dmac_chan *dc,
+				       struct txx9dmac_desc *desc)
+{
+	struct txx9dmac_dev *ddev = dc->ddev;
+	struct txx9dmac_desc *child;
+
+	list_for_each_entry(child, &desc->txd.tx_list, desc_node)
+		dma_sync_single_for_cpu(chan2parent(&dc->chan),
+				child->txd.phys, ddev->descsize,
+				DMA_TO_DEVICE);
+	dma_sync_single_for_cpu(chan2parent(&dc->chan),
+			desc->txd.phys, ddev->descsize,
+			DMA_TO_DEVICE);
+}
+
+/*
+ * Move a descriptor, including any children, to the free list.
+ * `desc' must not be on any lists.
+ */
+static void txx9dmac_desc_put(struct txx9dmac_chan *dc,
+			      struct txx9dmac_desc *desc)
+{
+	if (desc) {
+		struct txx9dmac_desc *child;
+
+		txx9dmac_sync_desc_for_cpu(dc, desc);
+
+		spin_lock_bh(&dc->lock);
+		list_for_each_entry(child, &desc->txd.tx_list, desc_node)
+			dev_vdbg(chan2dev(&dc->chan),
+				 "moving child desc %p to freelist\n",
+				 child);
+		list_splice_init(&desc->txd.tx_list, &dc->free_list);
+		dev_vdbg(chan2dev(&dc->chan), "moving desc %p to freelist\n",
+			 desc);
+		list_add(&desc->desc_node, &dc->free_list);
+		spin_unlock_bh(&dc->lock);
+	}
+}
+
+/* Called with dc->lock held and bh disabled */
+static dma_cookie_t
+txx9dmac_assign_cookie(struct txx9dmac_chan *dc, struct txx9dmac_desc *desc)
+{
+	dma_cookie_t cookie = dc->chan.cookie;
+
+	if (++cookie < 0)
+		cookie = 1;
+
+	dc->chan.cookie = cookie;
+	desc->txd.cookie = cookie;
+
+	return cookie;
+}
+
+/*----------------------------------------------------------------------*/
+
+static void txx9dmac_dump_regs(struct txx9dmac_chan *dc)
+{
+	if (is_dmac64(dc))
+		dev_err(chan2dev(&dc->chan),
+			"  CHAR: %#llx SAR: %#llx DAR: %#llx CNTR: %#x"
+			" SAIR: %#x DAIR: %#x CCR: %#x CSR: %#x\n",
+			(u64)channel64_read_CHAR(dc),
+			channel64_readq(dc, SAR),
+			channel64_readq(dc, DAR),
+			channel64_readl(dc, CNTR),
+			channel64_readl(dc, SAIR),
+			channel64_readl(dc, DAIR),
+			channel64_readl(dc, CCR),
+			channel64_readl(dc, CSR));
+	else
+		dev_err(chan2dev(&dc->chan),
+			"  CHAR: %#x SAR: %#x DAR: %#x CNTR: %#x"
+			" SAIR: %#x DAIR: %#x CCR: %#x CSR: %#x\n",
+			channel32_readl(dc, CHAR),
+			channel32_readl(dc, SAR),
+			channel32_readl(dc, DAR),
+			channel32_readl(dc, CNTR),
+			channel32_readl(dc, SAIR),
+			channel32_readl(dc, DAIR),
+			channel32_readl(dc, CCR),
+			channel32_readl(dc, CSR));
+}
+
+static void txx9dmac_reset_chan(struct txx9dmac_chan *dc)
+{
+	channel_writel(dc, CCR, TXX9_DMA_CCR_CHRST);
+	if (is_dmac64(dc)) {
+		channel64_clear_CHAR(dc);
+		channel_writeq(dc, SAR, 0);
+		channel_writeq(dc, DAR, 0);
+	} else {
+		channel_writel(dc, CHAR, 0);
+		channel_writel(dc, SAR, 0);
+		channel_writel(dc, DAR, 0);
+	}
+	channel_writel(dc, CNTR, 0);
+	channel_writel(dc, SAIR, 0);
+	channel_writel(dc, DAIR, 0);
+	channel_writel(dc, CCR, 0);
+	mmiowb();
+}
+
+/* Called with dc->lock held and bh disabled */
+static void txx9dmac_dostart(struct txx9dmac_chan *dc,
+			     struct txx9dmac_desc *first)
+{
+	struct txx9dmac_slave *ds = dc->chan.private;
+	u32 sai, dai;
+
+	dev_vdbg(chan2dev(&dc->chan), "dostart %u %p\n",
+		 first->txd.cookie, first);
+	/* ASSERT:  channel is idle */
+	if (channel_readl(dc, CSR) & TXX9_DMA_CSR_XFACT) {
+		dev_err(chan2dev(&dc->chan),
+			"BUG: Attempted to start non-idle channel\n");
+		txx9dmac_dump_regs(dc);
+		/* The tasklet will hopefully advance the queue... */
+		return;
+	}
+
+	if (is_dmac64(dc)) {
+		channel64_writel(dc, CNTR, 0);
+		channel64_writel(dc, CSR, 0xffffffff);
+		if (ds) {
+			if (ds->tx_reg) {
+				sai = ds->reg_width;
+				dai = 0;
+			} else {
+				sai = 0;
+				dai = ds->reg_width;
+			}
+		} else {
+			sai = 8;
+			dai = 8;
+		}
+		channel64_writel(dc, SAIR, sai);
+		channel64_writel(dc, DAIR, dai);
+		/* All 64-bit DMAC supports SMPCHN */
+		channel64_writel(dc, CCR, dc->ccr);
+		/* Writing a non zero value to CHAR will assert XFACT */
+		channel64_write_CHAR(dc, first->txd.phys);
+	} else {
+		channel32_writel(dc, CNTR, 0);
+		channel32_writel(dc, CSR, 0xffffffff);
+		if (ds) {
+			if (ds->tx_reg) {
+				sai = ds->reg_width;
+				dai = 0;
+			} else {
+				sai = 0;
+				dai = ds->reg_width;
+			}
+		} else {
+			sai = 4;
+			dai = 4;
+		}
+		channel32_writel(dc, SAIR, sai);
+		channel32_writel(dc, DAIR, dai);
+		if (txx9_dma_have_SMPCHN()) {
+			channel32_writel(dc, CCR, dc->ccr);
+			/* Writing a non zero value to CHAR will assert XFACT */
+			channel32_writel(dc, CHAR, first->txd.phys);
+		} else {
+			channel32_writel(dc, CHAR, first->txd.phys);
+			channel32_writel(dc, CCR, dc->ccr);
+		}
+	}
+}
+
+/*----------------------------------------------------------------------*/
+
+static void
+txx9dmac_descriptor_complete(struct txx9dmac_chan *dc,
+			     struct txx9dmac_desc *desc)
+{
+	dma_async_tx_callback callback;
+	void *param;
+	struct dma_async_tx_descriptor *txd = &desc->txd;
+	struct txx9dmac_slave *ds = dc->chan.private;
+
+	dev_vdbg(chan2dev(&dc->chan), "descriptor %u %p complete\n",
+		 txd->cookie, desc);
+
+	dc->completed = txd->cookie;
+	callback = txd->callback;
+	param = txd->callback_param;
+
+	txx9dmac_sync_desc_for_cpu(dc, desc);
+	list_splice_init(&txd->tx_list, &dc->free_list);
+	list_move(&desc->desc_node, &dc->free_list);
+
+	/*
+	 * We use dma_unmap_page() regardless of how the buffers were
+	 * mapped before they were submitted...
+	 */
+	if (!ds) {
+		dma_addr_t dmaaddr;
+		if (!(txd->flags & DMA_COMPL_SKIP_DEST_UNMAP)) {
+			dmaaddr = is_dmac64(dc) ?
+				desc->hwdesc.DAR : desc->hwdesc32.DAR;
+			dma_unmap_page(chan2parent(&dc->chan), dmaaddr,
+				       desc->len, DMA_FROM_DEVICE);
+		}
+		if (!(txd->flags & DMA_COMPL_SKIP_SRC_UNMAP)) {
+			dmaaddr = is_dmac64(dc) ?
+				desc->hwdesc.SAR : desc->hwdesc32.SAR;
+			dma_unmap_page(chan2parent(&dc->chan), dmaaddr,
+				       desc->len, DMA_TO_DEVICE);
+		}
+	}
+
+	/*
+	 * The API requires that no submissions are done from a
+	 * callback, so we don't need to drop the lock here
+	 */
+	if (callback)
+		callback(param);
+	dma_run_dependencies(txd);
+}
+
+static void txx9dmac_dequeue(struct txx9dmac_chan *dc, struct list_head *list)
+{
+	struct txx9dmac_dev *ddev = dc->ddev;
+	struct txx9dmac_desc *desc;
+	struct txx9dmac_desc *prev = NULL;
+
+	BUG_ON(!list_empty(list));
+	do {
+		desc = txx9dmac_first_queued(dc);
+		if (prev) {
+			desc_write_CHAR(dc, prev, desc->txd.phys);
+			dma_sync_single_for_device(chan2parent(&dc->chan),
+				prev->txd.phys, ddev->descsize,
+				DMA_TO_DEVICE);
+		}
+		prev = txx9dmac_last_child(desc);
+		list_move_tail(&desc->desc_node, list);
+		/* Make chain-completion interrupt happen */
+		if ((desc->txd.flags & DMA_PREP_INTERRUPT) &&
+		    !txx9dmac_chan_INTENT(dc))
+			break;
+	} while (!list_empty(&dc->queue));
+}
+
+static void txx9dmac_complete_all(struct txx9dmac_chan *dc)
+{
+	struct txx9dmac_desc *desc, *_desc;
+	LIST_HEAD(list);
+
+	/*
+	 * Submit queued descriptors ASAP, i.e. before we go through
+	 * the completed ones.
+	 */
+	list_splice_init(&dc->active_list, &list);
+	if (!list_empty(&dc->queue)) {
+		txx9dmac_dequeue(dc, &dc->active_list);
+		txx9dmac_dostart(dc, txx9dmac_first_active(dc));
+	}
+
+	list_for_each_entry_safe(desc, _desc, &list, desc_node)
+		txx9dmac_descriptor_complete(dc, desc);
+}
+
+static void txx9dmac_dump_desc(struct txx9dmac_chan *dc,
+			       struct txx9dmac_hwdesc *desc)
+{
+	if (is_dmac64(dc)) {
+#ifdef TXX9_DMA_USE_SIMPLE_CHAIN
+		dev_crit(chan2dev(&dc->chan),
+			 "  desc: ch%#llx s%#llx d%#llx c%#x\n",
+			 (u64)desc->CHAR, desc->SAR, desc->DAR, desc->CNTR);
+#else
+		dev_crit(chan2dev(&dc->chan),
+			 "  desc: ch%#llx s%#llx d%#llx c%#x"
+			 " si%#x di%#x cc%#x cs%#x\n",
+			 (u64)desc->CHAR, desc->SAR, desc->DAR, desc->CNTR,
+			 desc->SAIR, desc->DAIR, desc->CCR, desc->CSR);
+#endif
+	} else {
+		struct txx9dmac_hwdesc32 *d = (struct txx9dmac_hwdesc32 *)desc;
+#ifdef TXX9_DMA_USE_SIMPLE_CHAIN
+		dev_crit(chan2dev(&dc->chan),
+			 "  desc: ch%#x s%#x d%#x c%#x\n",
+			 d->CHAR, d->SAR, d->DAR, d->CNTR);
+#else
+		dev_crit(chan2dev(&dc->chan),
+			 "  desc: ch%#x s%#x d%#x c%#x"
+			 " si%#x di%#x cc%#x cs%#x\n",
+			 d->CHAR, d->SAR, d->DAR, d->CNTR,
+			 d->SAIR, d->DAIR, d->CCR, d->CSR);
+#endif
+	}
+}
+
+static void txx9dmac_handle_error(struct txx9dmac_chan *dc, u32 csr)
+{
+	struct txx9dmac_desc *bad_desc;
+	struct txx9dmac_desc *child;
+	u32 errors;
+
+	/*
+	 * The descriptor currently at the head of the active list is
+	 * borked. Since we don't have any way to report errors, we'll
+	 * just have to scream loudly and try to carry on.
+	 */
+	dev_crit(chan2dev(&dc->chan), "Abnormal Chain Completion\n");
+	txx9dmac_dump_regs(dc);
+
+	bad_desc = txx9dmac_first_active(dc);
+	list_del_init(&bad_desc->desc_node);
+
+	/* Clear all error flags and try to restart the controller */
+	errors = csr & (TXX9_DMA_CSR_ABCHC |
+			TXX9_DMA_CSR_CFERR | TXX9_DMA_CSR_CHERR |
+			TXX9_DMA_CSR_DESERR | TXX9_DMA_CSR_SORERR);
+	channel_writel(dc, CSR, errors);
+
+	if (list_empty(&dc->active_list) && !list_empty(&dc->queue))
+		txx9dmac_dequeue(dc, &dc->active_list);
+	if (!list_empty(&dc->active_list))
+		txx9dmac_dostart(dc, txx9dmac_first_active(dc));
+
+	dev_crit(chan2dev(&dc->chan),
+		 "Bad descriptor submitted for DMA! (cookie: %d)\n",
+		 bad_desc->txd.cookie);
+	txx9dmac_dump_desc(dc, &bad_desc->hwdesc);
+	list_for_each_entry(child, &bad_desc->txd.tx_list, desc_node)
+		txx9dmac_dump_desc(dc, &child->hwdesc);
+	/* Pretend the descriptor completed successfully */
+	txx9dmac_descriptor_complete(dc, bad_desc);
+}
+
+static void txx9dmac_scan_descriptors(struct txx9dmac_chan *dc)
+{
+	dma_addr_t chain;
+	struct txx9dmac_desc *desc, *_desc;
+	struct txx9dmac_desc *child;
+	u32 csr;
+
+	if (is_dmac64(dc)) {
+		chain = channel64_read_CHAR(dc);
+		csr = channel64_readl(dc, CSR);
+		channel64_writel(dc, CSR, csr);
+	} else {
+		chain = channel32_readl(dc, CHAR);
+		csr = channel32_readl(dc, CSR);
+		channel32_writel(dc, CSR, csr);
+	}
+	/* For dynamic chain, we should look at XFACT instead of NCHNC */
+	if (!(csr & (TXX9_DMA_CSR_XFACT | TXX9_DMA_CSR_ABCHC))) {
+		/* Everything we've submitted is done */
+		txx9dmac_complete_all(dc);
+		return;
+	}
+	if (!(csr & TXX9_DMA_CSR_CHNEN))
+		chain = 0;	/* last descriptor of this chain */
+
+	dev_vdbg(chan2dev(&dc->chan), "scan_descriptors: char=%#llx\n",
+		 (u64)chain);
+
+	list_for_each_entry_safe(desc, _desc, &dc->active_list, desc_node) {
+		if (desc_read_CHAR(dc, desc) == chain) {
+			/* This one is currently in progress */
+			if (csr & TXX9_DMA_CSR_ABCHC)
+				goto scan_done;
+			return;
+		}
+
+		list_for_each_entry(child, &desc->txd.tx_list, desc_node)
+			if (desc_read_CHAR(dc, child) == chain) {
+				/* Currently in progress */
+				if (csr & TXX9_DMA_CSR_ABCHC)
+					goto scan_done;
+				return;
+			}
+
+		/*
+		 * No descriptors so far seem to be in progress, i.e.
+		 * this one must be done.
+		 */
+		txx9dmac_descriptor_complete(dc, desc);
+	}
+scan_done:
+	if (csr & TXX9_DMA_CSR_ABCHC) {
+		txx9dmac_handle_error(dc, csr);
+		return;
+	}
+
+	dev_err(chan2dev(&dc->chan),
+		"BUG: All descriptors done, but channel not idle!\n");
+
+	/* Try to continue after resetting the channel... */
+	txx9dmac_reset_chan(dc);
+
+	if (!list_empty(&dc->queue)) {
+		txx9dmac_dequeue(dc, &dc->active_list);
+		txx9dmac_dostart(dc, txx9dmac_first_active(dc));
+	}
+}
+
+static void txx9dmac_chan_tasklet(unsigned long data)
+{
+	int irq;
+	u32 csr;
+	struct txx9dmac_chan *dc;
+
+	dc = (struct txx9dmac_chan *)data;
+	csr = channel_readl(dc, CSR);
+	dev_vdbg(chan2dev(&dc->chan), "tasklet: status=%x\n", csr);
+
+	spin_lock(&dc->lock);
+	if (csr & (TXX9_DMA_CSR_ABCHC | TXX9_DMA_CSR_NCHNC |
+		   TXX9_DMA_CSR_NTRNFC))
+		txx9dmac_scan_descriptors(dc);
+	spin_unlock(&dc->lock);
+	irq = dc->irq;
+
+	enable_irq(irq);
+}
+
+static irqreturn_t txx9dmac_chan_interrupt(int irq, void *dev_id)
+{
+	struct txx9dmac_chan *dc = dev_id;
+
+	dev_vdbg(chan2dev(&dc->chan), "interrupt: status=%#x\n",
+			channel_readl(dc, CSR));
+
+	tasklet_schedule(&dc->tasklet);
+	/*
+	 * Just disable the interrupts. We'll turn them back on in the
+	 * softirq handler.
+	 */
+	disable_irq_nosync(irq);
+
+	return IRQ_HANDLED;
+}
+
+static void txx9dmac_tasklet(unsigned long data)
+{
+	int irq;
+	u32 csr;
+	struct txx9dmac_chan *dc;
+
+	struct txx9dmac_dev *ddev = (struct txx9dmac_dev *)data;
+	u32 mcr;
+	int i;
+
+	mcr = dma_readl(ddev, MCR);
+	dev_vdbg(ddev->chan[0]->dma.dev, "tasklet: mcr=%x\n", mcr);
+	for (i = 0; i < TXX9_DMA_MAX_NR_CHANNELS; i++) {
+		if ((mcr >> (24 + i)) & 0x11) {
+			dc = ddev->chan[i];
+			csr = channel_readl(dc, CSR);
+			dev_vdbg(chan2dev(&dc->chan), "tasklet: status=%x\n",
+				 csr);
+			spin_lock(&dc->lock);
+			if (csr & (TXX9_DMA_CSR_ABCHC | TXX9_DMA_CSR_NCHNC |
+				   TXX9_DMA_CSR_NTRNFC))
+				txx9dmac_scan_descriptors(dc);
+			spin_unlock(&dc->lock);
+		}
+	}
+	irq = ddev->irq;
+
+	enable_irq(irq);
+}
+
+static irqreturn_t txx9dmac_interrupt(int irq, void *dev_id)
+{
+	struct txx9dmac_dev *ddev = dev_id;
+
+	dev_vdbg(ddev->chan[0]->dma.dev, "interrupt: status=%#x\n",
+			dma_readl(ddev, MCR));
+
+	tasklet_schedule(&ddev->tasklet);
+	/*
+	 * Just disable the interrupts. We'll turn them back on in the
+	 * softirq handler.
+	 */
+	disable_irq_nosync(irq);
+
+	return IRQ_HANDLED;
+}
+
+/*----------------------------------------------------------------------*/
+
+static dma_cookie_t txx9dmac_tx_submit(struct dma_async_tx_descriptor *tx)
+{
+	struct txx9dmac_desc *desc = txd_to_txx9dmac_desc(tx);
+	struct txx9dmac_chan *dc = to_txx9dmac_chan(tx->chan);
+	dma_cookie_t cookie;
+
+	spin_lock_bh(&dc->lock);
+	cookie = txx9dmac_assign_cookie(dc, desc);
+
+	dev_vdbg(chan2dev(tx->chan), "tx_submit: queued %u %p\n",
+		 desc->txd.cookie, desc);
+
+	list_add_tail(&desc->desc_node, &dc->queue);
+	spin_unlock_bh(&dc->lock);
+
+	return cookie;
+}
+
+static struct dma_async_tx_descriptor *
+txx9dmac_prep_dma_memcpy(struct dma_chan *chan, dma_addr_t dest, dma_addr_t src,
+		size_t len, unsigned long flags)
+{
+	struct txx9dmac_chan *dc = to_txx9dmac_chan(chan);
+	struct txx9dmac_dev *ddev = dc->ddev;
+	struct txx9dmac_desc *desc;
+	struct txx9dmac_desc *first;
+	struct txx9dmac_desc *prev;
+	size_t xfer_count;
+	size_t offset;
+
+	dev_vdbg(chan2dev(chan), "prep_dma_memcpy d%#llx s%#llx l%#zx f%#lx\n",
+		 (u64)dest, (u64)src, len, flags);
+
+	if (unlikely(!len)) {
+		dev_dbg(chan2dev(chan), "prep_dma_memcpy: length is zero!\n");
+		return NULL;
+	}
+
+	prev = first = NULL;
+
+	for (offset = 0; offset < len; offset += xfer_count) {
+		xfer_count = min_t(size_t, len - offset, TXX9_DMA_MAX_COUNT);
+		/*
+		 * Workaround for ERT-TX49H2-033, ERT-TX49H3-020,
+		 * ERT-TX49H4-016 (slightly conservative)
+		 */
+		if (__is_dmac64(ddev)) {
+			if (xfer_count > 0x100 &&
+			    (xfer_count & 0xff) >= 0xfa &&
+			    (xfer_count & 0xff) <= 0xff)
+				xfer_count -= 0x20;
+		} else {
+			if (xfer_count > 0x80 &&
+			    (xfer_count & 0x7f) >= 0x7e &&
+			    (xfer_count & 0x7f) <= 0x7f)
+				xfer_count -= 0x20;
+		}
+
+		desc = txx9dmac_desc_get(dc);
+		if (!desc) {
+			txx9dmac_desc_put(dc, first);
+			return NULL;
+		}
+
+		if (__is_dmac64(ddev)) {
+			desc->hwdesc.SAR = src + offset;
+			desc->hwdesc.DAR = dest + offset;
+			desc->hwdesc.CNTR = xfer_count;
+			txx9dmac_desc_set_nosimple(ddev, desc, 8, 8,
+					dc->ccr | TXX9_DMA_CCR_XFACT);
+		} else {
+			desc->hwdesc32.SAR = src + offset;
+			desc->hwdesc32.DAR = dest + offset;
+			desc->hwdesc32.CNTR = xfer_count;
+			txx9dmac_desc_set_nosimple(ddev, desc, 4, 4,
+					dc->ccr | TXX9_DMA_CCR_XFACT);
+		}
+
+		/*
+		 * The descriptors on tx_list are not reachable from
+		 * the dc->queue list or dc->active_list after a
+		 * submit.  If we put all descriptors on active_list,
+		 * calling of callback on the completion will be more
+		 * complex.
+		 */
+		if (!first) {
+			first = desc;
+		} else {
+			desc_write_CHAR(dc, prev, desc->txd.phys);
+			dma_sync_single_for_device(chan2parent(&dc->chan),
+					prev->txd.phys, ddev->descsize,
+					DMA_TO_DEVICE);
+			list_add_tail(&desc->desc_node,
+					&first->txd.tx_list);
+		}
+		prev = desc;
+	}
+
+	/* Trigger interrupt after last block */
+	if (flags & DMA_PREP_INTERRUPT)
+		txx9dmac_desc_set_INTENT(ddev, prev);
+
+	desc_write_CHAR(dc, prev, 0);
+	dma_sync_single_for_device(chan2parent(&dc->chan),
+			prev->txd.phys, ddev->descsize,
+			DMA_TO_DEVICE);
+
+	first->txd.flags = flags;
+	first->len = len;
+
+	return &first->txd;
+}
+
+static struct dma_async_tx_descriptor *
+txx9dmac_prep_slave_sg(struct dma_chan *chan, struct scatterlist *sgl,
+		unsigned int sg_len, enum dma_data_direction direction,
+		unsigned long flags)
+{
+	struct txx9dmac_chan *dc = to_txx9dmac_chan(chan);
+	struct txx9dmac_dev *ddev = dc->ddev;
+	struct txx9dmac_slave *ds = chan->private;
+	struct txx9dmac_desc *prev;
+	struct txx9dmac_desc *first;
+	unsigned int i;
+	struct scatterlist *sg;
+
+	dev_vdbg(chan2dev(chan), "prep_dma_slave\n");
+
+	BUG_ON(!ds || !ds->reg_width);
+	if (ds->tx_reg)
+		BUG_ON(direction != DMA_TO_DEVICE);
+	else
+		BUG_ON(direction != DMA_FROM_DEVICE);
+	if (unlikely(!sg_len))
+		return NULL;
+
+	prev = first = NULL;
+
+	for_each_sg(sgl, sg, sg_len, i) {
+		struct txx9dmac_desc *desc;
+		dma_addr_t mem;
+		u32 sai, dai;
+
+		desc = txx9dmac_desc_get(dc);
+		if (!desc) {
+			txx9dmac_desc_put(dc, first);
+			return NULL;
+		}
+
+		mem = sg_dma_address(sg);
+
+		if (__is_dmac64(ddev)) {
+			if (direction == DMA_TO_DEVICE) {
+				desc->hwdesc.SAR = mem;
+				desc->hwdesc.DAR = ds->tx_reg;
+			} else {
+				desc->hwdesc.SAR = ds->rx_reg;
+				desc->hwdesc.DAR = mem;
+			}
+			desc->hwdesc.CNTR = sg_dma_len(sg);
+		} else {
+			if (direction == DMA_TO_DEVICE) {
+				desc->hwdesc32.SAR = mem;
+				desc->hwdesc32.DAR = ds->tx_reg;
+			} else {
+				desc->hwdesc32.SAR = ds->rx_reg;
+				desc->hwdesc32.DAR = mem;
+			}
+			desc->hwdesc32.CNTR = sg_dma_len(sg);
+		}
+		if (direction == DMA_TO_DEVICE) {
+			sai = ds->reg_width;
+			dai = 0;
+		} else {
+			sai = 0;
+			dai = ds->reg_width;
+		}
+		txx9dmac_desc_set_nosimple(ddev, desc, sai, dai,
+					dc->ccr | TXX9_DMA_CCR_XFACT);
+
+		if (!first) {
+			first = desc;
+		} else {
+			desc_write_CHAR(dc, prev, desc->txd.phys);
+			dma_sync_single_for_device(chan2parent(&dc->chan),
+					prev->txd.phys,
+					ddev->descsize,
+					DMA_TO_DEVICE);
+			list_add_tail(&desc->desc_node,
+					&first->txd.tx_list);
+		}
+		prev = desc;
+	}
+
+	/* Trigger interrupt after last block */
+	if (flags & DMA_PREP_INTERRUPT)
+		txx9dmac_desc_set_INTENT(ddev, prev);
+
+	desc_write_CHAR(dc, prev, 0);
+	dma_sync_single_for_device(chan2parent(&dc->chan),
+			prev->txd.phys, ddev->descsize,
+			DMA_TO_DEVICE);
+
+	first->txd.flags = flags;
+	first->len = 0;
+
+	return &first->txd;
+}
+
+static void txx9dmac_terminate_all(struct dma_chan *chan)
+{
+	struct txx9dmac_chan *dc = to_txx9dmac_chan(chan);
+	struct txx9dmac_desc *desc, *_desc;
+	LIST_HEAD(list);
+
+	dev_vdbg(chan2dev(chan), "terminate_all\n");
+	spin_lock_bh(&dc->lock);
+
+	txx9dmac_reset_chan(dc);
+
+	/* active_list entries will end up before queued entries */
+	list_splice_init(&dc->queue, &list);
+	list_splice_init(&dc->active_list, &list);
+
+	spin_unlock_bh(&dc->lock);
+
+	/* Flush all pending and queued descriptors */
+	list_for_each_entry_safe(desc, _desc, &list, desc_node)
+		txx9dmac_descriptor_complete(dc, desc);
+}
+
+static enum dma_status
+txx9dmac_is_tx_complete(struct dma_chan *chan,
+			dma_cookie_t cookie,
+		dma_cookie_t *done, dma_cookie_t *used)
+{
+	struct txx9dmac_chan *dc = to_txx9dmac_chan(chan);
+	dma_cookie_t last_used;
+	dma_cookie_t last_complete;
+	int ret;
+
+	last_complete = dc->completed;
+	last_used = chan->cookie;
+
+	ret = dma_async_is_complete(cookie, last_complete, last_used);
+	if (ret != DMA_SUCCESS) {
+		spin_lock_bh(&dc->lock);
+		txx9dmac_scan_descriptors(dc);
+		spin_unlock_bh(&dc->lock);
+
+		last_complete = dc->completed;
+		last_used = chan->cookie;
+
+		ret = dma_async_is_complete(cookie, last_complete, last_used);
+	}
+
+	if (done)
+		*done = last_complete;
+	if (used)
+		*used = last_used;
+
+	return ret;
+}
+
+static void txx9dmac_chain_dynamic(struct txx9dmac_chan *dc,
+				   struct txx9dmac_desc *prev)
+{
+	struct txx9dmac_dev *ddev = dc->ddev;
+	struct txx9dmac_desc *desc;
+	LIST_HEAD(list);
+
+	prev = txx9dmac_last_child(prev);
+	txx9dmac_dequeue(dc, &list);
+	desc = list_entry(list.next, struct txx9dmac_desc, desc_node);
+	desc_write_CHAR(dc, prev, desc->txd.phys);
+	dma_sync_single_for_device(chan2parent(&dc->chan),
+				   prev->txd.phys, ddev->descsize,
+				   DMA_TO_DEVICE);
+	mmiowb();
+	if (!(channel_readl(dc, CSR) & TXX9_DMA_CSR_CHNEN) &&
+	    channel_read_CHAR(dc) == prev->txd.phys)
+		/* Restart chain DMA */
+		channel_write_CHAR(dc, desc->txd.phys);
+	list_splice_tail(&list, &dc->active_list);
+}
+
+static void txx9dmac_issue_pending(struct dma_chan *chan)
+{
+	struct txx9dmac_chan *dc = to_txx9dmac_chan(chan);
+
+	spin_lock_bh(&dc->lock);
+
+	if (!list_empty(&dc->active_list))
+		txx9dmac_scan_descriptors(dc);
+	if (!list_empty(&dc->queue)) {
+		if (list_empty(&dc->active_list)) {
+			txx9dmac_dequeue(dc, &dc->active_list);
+			txx9dmac_dostart(dc, txx9dmac_first_active(dc));
+		} else if (txx9_dma_have_SMPCHN()) {
+			struct txx9dmac_desc *prev = txx9dmac_last_active(dc);
+
+			if (!(prev->txd.flags & DMA_PREP_INTERRUPT) ||
+			    txx9dmac_chan_INTENT(dc))
+				txx9dmac_chain_dynamic(dc, prev);
+		}
+	}
+
+	spin_unlock_bh(&dc->lock);
+}
+
+static int txx9dmac_alloc_chan_resources(struct dma_chan *chan)
+{
+	struct txx9dmac_chan *dc = to_txx9dmac_chan(chan);
+	struct txx9dmac_slave *ds = chan->private;
+	struct txx9dmac_desc *desc;
+	int i;
+
+	dev_vdbg(chan2dev(chan), "alloc_chan_resources\n");
+
+	/* ASSERT:  channel is idle */
+	if (channel_readl(dc, CSR) & TXX9_DMA_CSR_XFACT) {
+		dev_dbg(chan2dev(chan), "DMA channel not idle?\n");
+		return -EIO;
+	}
+
+	dc->completed = chan->cookie = 1;
+
+	dc->ccr = TXX9_DMA_CCR_IMMCHN | TXX9_DMA_CCR_INTENE | CCR_LE;
+	txx9dmac_chan_set_SMPCHN(dc);
+	if (!txx9_dma_have_SMPCHN() || (dc->ccr & TXX9_DMA_CCR_SMPCHN))
+		dc->ccr |= TXX9_DMA_CCR_INTENC;
+	if (chan->device->device_prep_dma_memcpy) {
+		if (ds)
+			return -EINVAL;
+		dc->ccr |= TXX9_DMA_CCR_XFSZ_X8;
+	} else {
+		if (!ds ||
+		    (ds->tx_reg && ds->rx_reg) || (!ds->tx_reg && !ds->rx_reg))
+			return -EINVAL;
+		dc->ccr |= TXX9_DMA_CCR_EXTRQ |
+			TXX9_DMA_CCR_XFSZ(__ffs(ds->reg_width));
+		txx9dmac_chan_set_INTENT(dc);
+	}
+
+	spin_lock_bh(&dc->lock);
+	i = dc->descs_allocated;
+	while (dc->descs_allocated < TXX9_DMA_INITIAL_DESC_COUNT) {
+		spin_unlock_bh(&dc->lock);
+
+		desc = txx9dmac_desc_alloc(dc, GFP_KERNEL);
+		if (!desc) {
+			dev_info(chan2dev(chan),
+				"only allocated %d descriptors\n", i);
+			spin_lock_bh(&dc->lock);
+			break;
+		}
+		txx9dmac_desc_put(dc, desc);
+
+		spin_lock_bh(&dc->lock);
+		i = ++dc->descs_allocated;
+	}
+	spin_unlock_bh(&dc->lock);
+
+	dev_dbg(chan2dev(chan),
+		"alloc_chan_resources allocated %d descriptors\n", i);
+
+	return i;
+}
+
+static void txx9dmac_free_chan_resources(struct dma_chan *chan)
+{
+	struct txx9dmac_chan *dc = to_txx9dmac_chan(chan);
+	struct txx9dmac_dev *ddev = dc->ddev;
+	struct txx9dmac_desc *desc, *_desc;
+	LIST_HEAD(list);
+
+	dev_dbg(chan2dev(chan), "free_chan_resources (descs allocated=%u)\n",
+			dc->descs_allocated);
+
+	/* ASSERT:  channel is idle */
+	BUG_ON(!list_empty(&dc->active_list));
+	BUG_ON(!list_empty(&dc->queue));
+	BUG_ON(channel_readl(dc, CSR) & TXX9_DMA_CSR_XFACT);
+
+	spin_lock_bh(&dc->lock);
+	list_splice_init(&dc->free_list, &list);
+	dc->descs_allocated = 0;
+	spin_unlock_bh(&dc->lock);
+
+	list_for_each_entry_safe(desc, _desc, &list, desc_node) {
+		dev_vdbg(chan2dev(chan), "  freeing descriptor %p\n", desc);
+		dma_unmap_single(chan2parent(chan), desc->txd.phys,
+				 ddev->descsize, DMA_TO_DEVICE);
+		kfree(desc);
+	}
+
+	dev_vdbg(chan2dev(chan), "free_chan_resources done\n");
+}
+
+/*----------------------------------------------------------------------*/
+
+static void txx9dmac_off(struct txx9dmac_dev *ddev)
+{
+	dma_writel(ddev, MCR, 0);
+	mmiowb();
+}
+
+static int __init txx9dmac_chan_probe(struct platform_device *pdev)
+{
+	struct txx9dmac_chan_platform_data *cpdata = pdev->dev.platform_data;
+	struct platform_device *dmac_dev = cpdata->dmac_dev;
+	struct txx9dmac_platform_data *pdata = dmac_dev->dev.platform_data;
+	struct txx9dmac_chan *dc;
+	int err;
+	int ch = pdev->id % TXX9_DMA_MAX_NR_CHANNELS;
+	int irq;
+
+	dc = devm_kzalloc(&pdev->dev, sizeof(*dc), GFP_KERNEL);
+	if (!dc)
+		return -ENOMEM;
+
+	dc->dma.dev = &pdev->dev;
+	dc->dma.device_alloc_chan_resources = txx9dmac_alloc_chan_resources;
+	dc->dma.device_free_chan_resources = txx9dmac_free_chan_resources;
+	dc->dma.device_terminate_all = txx9dmac_terminate_all;
+	dc->dma.device_is_tx_complete = txx9dmac_is_tx_complete;
+	dc->dma.device_issue_pending = txx9dmac_issue_pending;
+	if (pdata && pdata->memcpy_chan == ch) {
+		dc->dma.device_prep_dma_memcpy = txx9dmac_prep_dma_memcpy;
+		dma_cap_set(DMA_MEMCPY, dc->dma.cap_mask);
+	} else {
+		dc->dma.device_prep_slave_sg = txx9dmac_prep_slave_sg;
+		dma_cap_set(DMA_SLAVE, dc->dma.cap_mask);
+		dma_cap_set(DMA_PRIVATE, dc->dma.cap_mask);
+	}
+
+	INIT_LIST_HEAD(&dc->dma.channels);
+	dc->ddev = platform_get_drvdata(dmac_dev);
+	if (dc->ddev->irq < 0) {
+		irq = platform_get_irq(pdev, 0);
+		if (irq < 0)
+			return irq;
+		tasklet_init(&dc->tasklet, txx9dmac_chan_tasklet,
+				(unsigned long)dc);
+		dc->irq = irq;
+		err = devm_request_irq(&pdev->dev, dc->irq,
+			txx9dmac_chan_interrupt, 0, dev_name(&pdev->dev), dc);
+		if (err)
+			return err;
+	} else
+		dc->irq = -1;
+	dc->ddev->chan[ch] = dc;
+	dc->chan.device = &dc->dma;
+	list_add_tail(&dc->chan.device_node, &dc->chan.device->channels);
+	dc->chan.cookie = dc->completed = 1;
+
+	if (is_dmac64(dc))
+		dc->ch_regs = &__txx9dmac_regs(dc->ddev)->CHAN[ch];
+	else
+		dc->ch_regs = &__txx9dmac_regs32(dc->ddev)->CHAN[ch];
+	spin_lock_init(&dc->lock);
+
+	INIT_LIST_HEAD(&dc->active_list);
+	INIT_LIST_HEAD(&dc->queue);
+	INIT_LIST_HEAD(&dc->free_list);
+
+	txx9dmac_reset_chan(dc);
+
+	platform_set_drvdata(pdev, dc);
+
+	err = dma_async_device_register(&dc->dma);
+	if (err)
+		return err;
+	dev_dbg(&pdev->dev, "TXx9 DMA Channel (dma%d%s%s)\n",
+		dc->dma.dev_id,
+		dma_has_cap(DMA_MEMCPY, dc->dma.cap_mask) ? " memcpy" : "",
+		dma_has_cap(DMA_SLAVE, dc->dma.cap_mask) ? " slave" : "");
+
+	return 0;
+}
+
+static int __exit txx9dmac_chan_remove(struct platform_device *pdev)
+{
+	struct txx9dmac_chan *dc = platform_get_drvdata(pdev);
+
+	dma_async_device_unregister(&dc->dma);
+	if (dc->irq >= 0)
+		tasklet_kill(&dc->tasklet);
+	dc->ddev->chan[pdev->id % TXX9_DMA_MAX_NR_CHANNELS] = NULL;
+	return 0;
+}
+
+static int __init txx9dmac_probe(struct platform_device *pdev)
+{
+	struct txx9dmac_platform_data *pdata = pdev->dev.platform_data;
+	struct resource *io;
+	struct txx9dmac_dev *ddev;
+	u32 mcr;
+	int err;
+
+	io = platform_get_resource(pdev, IORESOURCE_MEM, 0);
+	if (!io)
+		return -EINVAL;
+
+	ddev = devm_kzalloc(&pdev->dev, sizeof(*ddev), GFP_KERNEL);
+	if (!ddev)
+		return -ENOMEM;
+
+	if (!devm_request_mem_region(&pdev->dev, io->start, resource_size(io),
+				     dev_name(&pdev->dev)))
+		return -EBUSY;
+
+	ddev->regs = devm_ioremap(&pdev->dev, io->start, resource_size(io));
+	if (!ddev->regs)
+		return -ENOMEM;
+	ddev->have_64bit_regs = pdata->have_64bit_regs;
+	if (__is_dmac64(ddev))
+		ddev->descsize = sizeof(struct txx9dmac_hwdesc);
+	else
+		ddev->descsize = sizeof(struct txx9dmac_hwdesc32);
+
+	/* force dma off, just in case */
+	txx9dmac_off(ddev);
+
+	ddev->irq = platform_get_irq(pdev, 0);
+	if (ddev->irq >= 0) {
+		tasklet_init(&ddev->tasklet, txx9dmac_tasklet,
+				(unsigned long)ddev);
+		err = devm_request_irq(&pdev->dev, ddev->irq,
+			txx9dmac_interrupt, 0, dev_name(&pdev->dev), ddev);
+		if (err)
+			return err;
+	}
+
+	mcr = TXX9_DMA_MCR_MSTEN | MCR_LE;
+	if (pdata && pdata->memcpy_chan >= 0)
+		mcr |= TXX9_DMA_MCR_FIFUM(pdata->memcpy_chan);
+	dma_writel(ddev, MCR, mcr);
+
+	platform_set_drvdata(pdev, ddev);
+	return 0;
+}
+
+static int __exit txx9dmac_remove(struct platform_device *pdev)
+{
+	struct txx9dmac_dev *ddev = platform_get_drvdata(pdev);
+
+	txx9dmac_off(ddev);
+	if (ddev->irq >= 0)
+		tasklet_kill(&ddev->tasklet);
+	return 0;
+}
+
+static void txx9dmac_shutdown(struct platform_device *pdev)
+{
+	struct txx9dmac_dev *ddev = platform_get_drvdata(pdev);
+
+	txx9dmac_off(ddev);
+}
+
+static int txx9dmac_suspend_late(struct platform_device *pdev,
+				 pm_message_t mesg)
+{
+	struct txx9dmac_dev *ddev = platform_get_drvdata(pdev);
+
+	txx9dmac_off(ddev);
+	return 0;
+}
+
+static int txx9dmac_resume_early(struct platform_device *pdev)
+{
+	struct txx9dmac_dev *ddev = platform_get_drvdata(pdev);
+	struct txx9dmac_platform_data *pdata = pdev->dev.platform_data;
+	u32 mcr;
+
+	mcr = TXX9_DMA_MCR_MSTEN | MCR_LE;
+	if (pdata && pdata->memcpy_chan >= 0)
+		mcr |= TXX9_DMA_MCR_FIFUM(pdata->memcpy_chan);
+	dma_writel(ddev, MCR, mcr);
+	return 0;
+
+}
+
+static struct platform_driver txx9dmac_chan_driver = {
+	.remove		= __exit_p(txx9dmac_chan_remove),
+	.driver = {
+		.name	= "txx9dmac-chan",
+	},
+};
+
+static struct platform_driver txx9dmac_driver = {
+	.remove		= __exit_p(txx9dmac_remove),
+	.shutdown	= txx9dmac_shutdown,
+	.suspend_late	= txx9dmac_suspend_late,
+	.resume_early	= txx9dmac_resume_early,
+	.driver = {
+		.name	= "txx9dmac",
+	},
+};
+
+static int __init txx9dmac_init(void)
+{
+	int rc;
+
+	rc = platform_driver_probe(&txx9dmac_driver, txx9dmac_probe);
+	if (!rc) {
+		rc = platform_driver_probe(&txx9dmac_chan_driver,
+					   txx9dmac_chan_probe);
+		if (rc)
+			platform_driver_unregister(&txx9dmac_driver);
+	}
+	return rc;
+}
+module_init(txx9dmac_init);
+
+static void __exit txx9dmac_exit(void)
+{
+	platform_driver_unregister(&txx9dmac_chan_driver);
+	platform_driver_unregister(&txx9dmac_driver);
+}
+module_exit(txx9dmac_exit);
+
+MODULE_LICENSE("GPL");
+MODULE_DESCRIPTION("TXx9 DMA Controller driver");
+MODULE_AUTHOR("Atsushi Nemoto <anemo@mba.ocn.ne.jp>");
diff --git a/drivers/dma/txx9dmac.h b/drivers/dma/txx9dmac.h
new file mode 100644
index 0000000..c907ff0
--- /dev/null
+++ b/drivers/dma/txx9dmac.h
@@ -0,0 +1,307 @@
+/*
+ * Driver for the TXx9 SoC DMA Controller
+ *
+ * Copyright (C) 2009 Atsushi Nemoto
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+#ifndef TXX9DMAC_H
+#define TXX9DMAC_H
+
+#include <linux/dmaengine.h>
+#include <asm/txx9/dmac.h>
+
+/*
+ * Design Notes:
+ *
+ * This DMAC have four channels and one FIFO buffer.  Each channel can
+ * be configured for memory-memory or device-memory transfer, but only
+ * one channel can do alignment-free memory-memory transfer at a time
+ * while the channel should occupy the FIFO buffer for effective
+ * transfers.
+ *
+ * Instead of dynamically assign the FIFO buffer to channels, I chose
+ * make one dedicated channel for memory-memory transfer.  The
+ * dedicated channel is public.  Other channels are private and used
+ * for slave transfer.  Some devices in the SoC are wired to certain
+ * DMA channel.
+ */
+
+#ifdef CONFIG_MACH_TX49XX
+static inline bool txx9_dma_have_SMPCHN(void)
+{
+	return true;
+}
+#define TXX9_DMA_USE_SIMPLE_CHAIN
+#else
+static inline bool txx9_dma_have_SMPCHN(void)
+{
+	return false;
+}
+#endif
+
+#ifdef __LITTLE_ENDIAN
+#ifdef CONFIG_MACH_TX49XX
+#define CCR_LE	TXX9_DMA_CCR_LE
+#define MCR_LE	0
+#else
+#define CCR_LE	0
+#define MCR_LE	TXX9_DMA_MCR_LE
+#endif
+#else
+#define CCR_LE	0
+#define MCR_LE	0
+#endif
+
+/*
+ * Redefine this macro to handle differences between 32- and 64-bit
+ * addressing, big vs. little endian, etc.
+ */
+#ifdef __BIG_ENDIAN
+#define TXX9_DMA_REG32(name)		u32 __pad_##name; u32 name
+#else
+#define TXX9_DMA_REG32(name)		u32 name; u32 __pad_##name
+#endif
+
+/* Hardware register definitions. */
+struct txx9dmac_cregs {
+#if defined(CONFIG_32BIT) && !defined(CONFIG_64BIT_PHYS_ADDR)
+	TXX9_DMA_REG32(CHAR);	/* Chain Address Register */
+#else
+	u64 CHAR;		/* Chain Address Register */
+#endif
+	u64 SAR;		/* Source Address Register */
+	u64 DAR;		/* Destination Address Register */
+	TXX9_DMA_REG32(CNTR);	/* Count Register */
+	TXX9_DMA_REG32(SAIR);	/* Source Address Increment Register */
+	TXX9_DMA_REG32(DAIR);	/* Destination Address Increment Register */
+	TXX9_DMA_REG32(CCR);	/* Channel Control Register */
+	TXX9_DMA_REG32(CSR);	/* Channel Status Register */
+};
+struct txx9dmac_cregs32 {
+	u32 CHAR;
+	u32 SAR;
+	u32 DAR;
+	u32 CNTR;
+	u32 SAIR;
+	u32 DAIR;
+	u32 CCR;
+	u32 CSR;
+};
+
+struct txx9dmac_regs {
+	/* per-channel registers */
+	struct txx9dmac_cregs	CHAN[TXX9_DMA_MAX_NR_CHANNELS];
+	u64	__pad[9];
+	u64	MFDR;		/* Memory Fill Data Register */
+	TXX9_DMA_REG32(MCR);	/* Master Control Register */
+};
+struct txx9dmac_regs32 {
+	struct txx9dmac_cregs32	CHAN[TXX9_DMA_MAX_NR_CHANNELS];
+	u32	__pad[9];
+	u32	MFDR;
+	u32	MCR;
+};
+
+/* bits for MCR */
+#define TXX9_DMA_MCR_EIS(ch)	(0x10000000<<(ch))
+#define TXX9_DMA_MCR_DIS(ch)	(0x01000000<<(ch))
+#define TXX9_DMA_MCR_RSFIF	0x00000080
+#define TXX9_DMA_MCR_FIFUM(ch)	(0x00000008<<(ch))
+#define TXX9_DMA_MCR_LE		0x00000004
+#define TXX9_DMA_MCR_RPRT	0x00000002
+#define TXX9_DMA_MCR_MSTEN	0x00000001
+
+/* bits for CCRn */
+#define TXX9_DMA_CCR_IMMCHN	0x20000000
+#define TXX9_DMA_CCR_USEXFSZ	0x10000000
+#define TXX9_DMA_CCR_LE		0x08000000
+#define TXX9_DMA_CCR_DBINH	0x04000000
+#define TXX9_DMA_CCR_SBINH	0x02000000
+#define TXX9_DMA_CCR_CHRST	0x01000000
+#define TXX9_DMA_CCR_RVBYTE	0x00800000
+#define TXX9_DMA_CCR_ACKPOL	0x00400000
+#define TXX9_DMA_CCR_REQPL	0x00200000
+#define TXX9_DMA_CCR_EGREQ	0x00100000
+#define TXX9_DMA_CCR_CHDN	0x00080000
+#define TXX9_DMA_CCR_DNCTL	0x00060000
+#define TXX9_DMA_CCR_EXTRQ	0x00010000
+#define TXX9_DMA_CCR_INTRQD	0x0000e000
+#define TXX9_DMA_CCR_INTENE	0x00001000
+#define TXX9_DMA_CCR_INTENC	0x00000800
+#define TXX9_DMA_CCR_INTENT	0x00000400
+#define TXX9_DMA_CCR_CHNEN	0x00000200
+#define TXX9_DMA_CCR_XFACT	0x00000100
+#define TXX9_DMA_CCR_SMPCHN	0x00000020
+#define TXX9_DMA_CCR_XFSZ(order)	(((order) << 2) & 0x0000001c)
+#define TXX9_DMA_CCR_XFSZ_1	TXX9_DMA_CCR_XFSZ(0)
+#define TXX9_DMA_CCR_XFSZ_2	TXX9_DMA_CCR_XFSZ(1)
+#define TXX9_DMA_CCR_XFSZ_4	TXX9_DMA_CCR_XFSZ(2)
+#define TXX9_DMA_CCR_XFSZ_8	TXX9_DMA_CCR_XFSZ(3)
+#define TXX9_DMA_CCR_XFSZ_X4	TXX9_DMA_CCR_XFSZ(4)
+#define TXX9_DMA_CCR_XFSZ_X8	TXX9_DMA_CCR_XFSZ(5)
+#define TXX9_DMA_CCR_XFSZ_X16	TXX9_DMA_CCR_XFSZ(6)
+#define TXX9_DMA_CCR_XFSZ_X32	TXX9_DMA_CCR_XFSZ(7)
+#define TXX9_DMA_CCR_MEMIO	0x00000002
+#define TXX9_DMA_CCR_SNGAD	0x00000001
+
+/* bits for CSRn */
+#define TXX9_DMA_CSR_CHNEN	0x00000400
+#define TXX9_DMA_CSR_STLXFER	0x00000200
+#define TXX9_DMA_CSR_XFACT	0x00000100
+#define TXX9_DMA_CSR_ABCHC	0x00000080
+#define TXX9_DMA_CSR_NCHNC	0x00000040
+#define TXX9_DMA_CSR_NTRNFC	0x00000020
+#define TXX9_DMA_CSR_EXTDN	0x00000010
+#define TXX9_DMA_CSR_CFERR	0x00000008
+#define TXX9_DMA_CSR_CHERR	0x00000004
+#define TXX9_DMA_CSR_DESERR	0x00000002
+#define TXX9_DMA_CSR_SORERR	0x00000001
+
+struct txx9dmac_chan {
+	struct dma_chan		chan;
+	struct dma_device	dma;
+	struct txx9dmac_dev	*ddev;
+	void __iomem		*ch_regs;
+	struct tasklet_struct	tasklet;
+	int			irq;
+	u32			ccr;
+
+	spinlock_t		lock;
+
+	/* these other elements are all protected by lock */
+	dma_cookie_t		completed;
+	struct list_head	active_list;
+	struct list_head	queue;
+	struct list_head	free_list;
+
+	unsigned int		descs_allocated;
+};
+
+struct txx9dmac_dev {
+	void __iomem		*regs;
+	struct tasklet_struct	tasklet;
+	int			irq;
+	struct txx9dmac_chan	*chan[TXX9_DMA_MAX_NR_CHANNELS];
+	bool			have_64bit_regs;
+	unsigned int		descsize;
+};
+
+static inline bool __is_dmac64(const struct txx9dmac_dev *ddev)
+{
+	return ddev->have_64bit_regs;
+}
+
+static inline bool is_dmac64(const struct txx9dmac_chan *dc)
+{
+	return __is_dmac64(dc->ddev);
+}
+
+#ifdef TXX9_DMA_USE_SIMPLE_CHAIN
+/* Hardware descriptor definition. (for simple-chain) */
+struct txx9dmac_hwdesc {
+#if defined(CONFIG_32BIT) && !defined(CONFIG_64BIT_PHYS_ADDR)
+	TXX9_DMA_REG32(CHAR);
+#else
+	u64 CHAR;
+#endif
+	u64 SAR;
+	u64 DAR;
+	TXX9_DMA_REG32(CNTR);
+};
+struct txx9dmac_hwdesc32 {
+	u32 CHAR;
+	u32 SAR;
+	u32 DAR;
+	u32 CNTR;
+};
+#else
+#define txx9dmac_hwdesc txx9dmac_cregs
+#define txx9dmac_hwdesc32 txx9dmac_cregs32
+#endif
+
+struct txx9dmac_desc {
+	/* FIRST values the hardware uses */
+	union {
+		struct txx9dmac_hwdesc hwdesc;
+		struct txx9dmac_hwdesc32 hwdesc32;
+	};
+
+	/* THEN values for driver housekeeping */
+	struct list_head		desc_node ____cacheline_aligned;
+	struct dma_async_tx_descriptor	txd;
+	size_t				len;
+};
+
+#ifdef TXX9_DMA_USE_SIMPLE_CHAIN
+
+static inline bool txx9dmac_chan_INTENT(struct txx9dmac_chan *dc)
+{
+	return (dc->ccr & TXX9_DMA_CCR_INTENT) != 0;
+}
+
+static inline void txx9dmac_chan_set_INTENT(struct txx9dmac_chan *dc)
+{
+	dc->ccr |= TXX9_DMA_CCR_INTENT;
+}
+
+static inline void txx9dmac_desc_set_INTENT(struct txx9dmac_dev *ddev,
+					    struct txx9dmac_desc *desc)
+{
+}
+
+static inline void txx9dmac_chan_set_SMPCHN(struct txx9dmac_chan *dc)
+{
+	dc->ccr |= TXX9_DMA_CCR_SMPCHN;
+}
+
+static inline void txx9dmac_desc_set_nosimple(struct txx9dmac_dev *ddev,
+					      struct txx9dmac_desc *desc,
+					      u32 sair, u32 dair, u32 ccr)
+{
+}
+
+#else /* TXX9_DMA_USE_SIMPLE_CHAIN */
+
+static inline bool txx9dmac_chan_INTENT(struct txx9dmac_chan *dc)
+{
+	return true;
+}
+
+static void txx9dmac_chan_set_INTENT(struct txx9dmac_chan *dc)
+{
+}
+
+static inline void txx9dmac_desc_set_INTENT(struct txx9dmac_dev *ddev,
+					    struct txx9dmac_desc *desc)
+{
+	if (__is_dmac64(ddev))
+		desc->hwdesc.CCR |= TXX9_DMA_CCR_INTENT;
+	else
+		desc->hwdesc32.CCR |= TXX9_DMA_CCR_INTENT;
+}
+
+static inline void txx9dmac_chan_set_SMPCHN(struct txx9dmac_chan *dc)
+{
+}
+
+static inline void txx9dmac_desc_set_nosimple(struct txx9dmac_dev *ddev,
+					      struct txx9dmac_desc *desc,
+					      u32 sai, u32 dai, u32 ccr)
+{
+	if (__is_dmac64(ddev)) {
+		desc->hwdesc.SAIR = sai;
+		desc->hwdesc.DAIR = dai;
+		desc->hwdesc.CCR = ccr;
+	} else {
+		desc->hwdesc32.SAIR = sai;
+		desc->hwdesc32.DAIR = dai;
+		desc->hwdesc32.CCR = ccr;
+	}
+}
+
+#endif /* TXX9_DMA_USE_SIMPLE_CHAIN */
+
+#endif /* TXX9DMAC_H */
diff --git a/drivers/edac/Kconfig b/drivers/edac/Kconfig
index ab4f359..4339b1a 100644
--- a/drivers/edac/Kconfig
+++ b/drivers/edac/Kconfig
@@ -5,7 +5,7 @@
 #
 
 menuconfig EDAC
-	bool "EDAC - error detection and reporting"
+	bool "EDAC (Error Detection And Correction) reporting"
 	depends on HAS_IOMEM
 	depends on X86 || PPC
 	help
@@ -232,4 +232,13 @@
 	  Note, add more Kconfig dependency if it's adopted
 	  on some machine other than Maple.
 
+config EDAC_CPC925
+	tristate "IBM CPC925 Memory Controller (PPC970FX)"
+	depends on EDAC_MM_EDAC && PPC64
+	help
+	  Support for error detection and correction on the
+	  IBM CPC925 Bridge and Memory Controller, which is
+	  a companion chip to the PowerPC 970 family of
+	  processors.
+
 endif # EDAC
diff --git a/drivers/edac/Makefile b/drivers/edac/Makefile
index 633dc56..98aa4a7 100644
--- a/drivers/edac/Makefile
+++ b/drivers/edac/Makefile
@@ -18,6 +18,7 @@
 endif
 
 obj-$(CONFIG_EDAC_AMD76X)		+= amd76x_edac.o
+obj-$(CONFIG_EDAC_CPC925)		+= cpc925_edac.o
 obj-$(CONFIG_EDAC_I5000)		+= i5000_edac.o
 obj-$(CONFIG_EDAC_I5100)		+= i5100_edac.o
 obj-$(CONFIG_EDAC_I5400)		+= i5400_edac.o
diff --git a/drivers/edac/amd8111_edac.c b/drivers/edac/amd8111_edac.c
index 2cb58ef..35b78d0 100644
--- a/drivers/edac/amd8111_edac.c
+++ b/drivers/edac/amd8111_edac.c
@@ -37,7 +37,6 @@
 #define AMD8111_EDAC_MOD_STR	"amd8111_edac"
 
 #define PCI_DEVICE_ID_AMD_8111_PCI	0x7460
-static int edac_dev_idx;
 
 enum amd8111_edac_devs {
 	LPC_BRIDGE = 0,
@@ -377,7 +376,7 @@
 	 * edac_device_ctl_info, but make use of existing
 	 * one instead.
 	*/
-	dev_info->edac_idx = edac_dev_idx++;
+	dev_info->edac_idx = edac_device_alloc_index();
 	dev_info->edac_dev =
 		edac_device_alloc_ctl_info(0, dev_info->ctl_name, 1,
 					   NULL, 0, 0,
diff --git a/drivers/edac/cell_edac.c b/drivers/edac/cell_edac.c
index cb0f639..c973004 100644
--- a/drivers/edac/cell_edac.c
+++ b/drivers/edac/cell_edac.c
@@ -227,7 +227,7 @@
 		.owner	= THIS_MODULE,
 	},
 	.probe		= cell_edac_probe,
-	.remove		= cell_edac_remove,
+	.remove		= __devexit_p(cell_edac_remove),
 };
 
 static int __init cell_edac_init(void)
diff --git a/drivers/edac/cpc925_edac.c b/drivers/edac/cpc925_edac.c
new file mode 100644
index 0000000..8c54196
--- /dev/null
+++ b/drivers/edac/cpc925_edac.c
@@ -0,0 +1,1017 @@
+/*
+ * cpc925_edac.c, EDAC driver for IBM CPC925 Bridge and Memory Controller.
+ *
+ * Copyright (c) 2008 Wind River Systems, Inc.
+ *
+ * Authors:	Cao Qingtao <qingtao.cao@windriver.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/io.h>
+#include <linux/edac.h>
+#include <linux/of.h>
+#include <linux/platform_device.h>
+
+#include "edac_core.h"
+#include "edac_module.h"
+
+#define CPC925_EDAC_REVISION	" Ver: 1.0.0 " __DATE__
+#define CPC925_EDAC_MOD_STR	"cpc925_edac"
+
+#define cpc925_printk(level, fmt, arg...) \
+	edac_printk(level, "CPC925", fmt, ##arg)
+
+#define cpc925_mc_printk(mci, level, fmt, arg...) \
+	edac_mc_chipset_printk(mci, level, "CPC925", fmt, ##arg)
+
+/*
+ * CPC925 registers are of 32 bits with bit0 defined at the
+ * most significant bit and bit31 at that of least significant.
+ */
+#define CPC925_BITS_PER_REG	32
+#define CPC925_BIT(nr)		(1UL << (CPC925_BITS_PER_REG - 1 - nr))
+
+/*
+ * EDAC device names for the error detections of
+ * CPU Interface and Hypertransport Link.
+ */
+#define CPC925_CPU_ERR_DEV	"cpu"
+#define CPC925_HT_LINK_DEV	"htlink"
+
+/* Suppose DDR Refresh cycle is 15.6 microsecond */
+#define CPC925_REF_FREQ		0xFA69
+#define CPC925_SCRUB_BLOCK_SIZE 64	/* bytes */
+#define CPC925_NR_CSROWS	8
+
+/*
+ * All registers and bits definitions are taken from
+ * "CPC925 Bridge and Memory Controller User Manual, SA14-2761-02".
+ */
+
+/*
+ * CPU and Memory Controller Registers
+ */
+/************************************************************
+ *	Processor Interface Exception Mask Register (APIMASK)
+ ************************************************************/
+#define REG_APIMASK_OFFSET	0x30070
+enum apimask_bits {
+	APIMASK_DART	= CPC925_BIT(0), /* DART Exception */
+	APIMASK_ADI0	= CPC925_BIT(1), /* Handshake Error on PI0_ADI */
+	APIMASK_ADI1	= CPC925_BIT(2), /* Handshake Error on PI1_ADI */
+	APIMASK_STAT	= CPC925_BIT(3), /* Status Exception */
+	APIMASK_DERR	= CPC925_BIT(4), /* Data Error Exception */
+	APIMASK_ADRS0	= CPC925_BIT(5), /* Addressing Exception on PI0 */
+	APIMASK_ADRS1	= CPC925_BIT(6), /* Addressing Exception on PI1 */
+					 /* BIT(7) Reserved */
+	APIMASK_ECC_UE_H = CPC925_BIT(8), /* UECC upper */
+	APIMASK_ECC_CE_H = CPC925_BIT(9), /* CECC upper */
+	APIMASK_ECC_UE_L = CPC925_BIT(10), /* UECC lower */
+	APIMASK_ECC_CE_L = CPC925_BIT(11), /* CECC lower */
+
+	CPU_MASK_ENABLE = (APIMASK_DART | APIMASK_ADI0 | APIMASK_ADI1 |
+			   APIMASK_STAT | APIMASK_DERR | APIMASK_ADRS0 |
+			   APIMASK_ADRS1),
+	ECC_MASK_ENABLE = (APIMASK_ECC_UE_H | APIMASK_ECC_CE_H |
+			   APIMASK_ECC_UE_L | APIMASK_ECC_CE_L),
+};
+
+/************************************************************
+ *	Processor Interface Exception Register (APIEXCP)
+ ************************************************************/
+#define REG_APIEXCP_OFFSET	0x30060
+enum apiexcp_bits {
+	APIEXCP_DART	= CPC925_BIT(0), /* DART Exception */
+	APIEXCP_ADI0	= CPC925_BIT(1), /* Handshake Error on PI0_ADI */
+	APIEXCP_ADI1	= CPC925_BIT(2), /* Handshake Error on PI1_ADI */
+	APIEXCP_STAT	= CPC925_BIT(3), /* Status Exception */
+	APIEXCP_DERR	= CPC925_BIT(4), /* Data Error Exception */
+	APIEXCP_ADRS0	= CPC925_BIT(5), /* Addressing Exception on PI0 */
+	APIEXCP_ADRS1	= CPC925_BIT(6), /* Addressing Exception on PI1 */
+					 /* BIT(7) Reserved */
+	APIEXCP_ECC_UE_H = CPC925_BIT(8), /* UECC upper */
+	APIEXCP_ECC_CE_H = CPC925_BIT(9), /* CECC upper */
+	APIEXCP_ECC_UE_L = CPC925_BIT(10), /* UECC lower */
+	APIEXCP_ECC_CE_L = CPC925_BIT(11), /* CECC lower */
+
+	CPU_EXCP_DETECTED = (APIEXCP_DART | APIEXCP_ADI0 | APIEXCP_ADI1 |
+			     APIEXCP_STAT | APIEXCP_DERR | APIEXCP_ADRS0 |
+			     APIEXCP_ADRS1),
+	UECC_EXCP_DETECTED = (APIEXCP_ECC_UE_H | APIEXCP_ECC_UE_L),
+	CECC_EXCP_DETECTED = (APIEXCP_ECC_CE_H | APIEXCP_ECC_CE_L),
+	ECC_EXCP_DETECTED = (UECC_EXCP_DETECTED | CECC_EXCP_DETECTED),
+};
+
+/************************************************************
+ *	Memory Bus Configuration Register (MBCR)
+************************************************************/
+#define REG_MBCR_OFFSET		0x2190
+#define MBCR_64BITCFG_SHIFT	23
+#define MBCR_64BITCFG_MASK	(1UL << MBCR_64BITCFG_SHIFT)
+#define MBCR_64BITBUS_SHIFT	22
+#define MBCR_64BITBUS_MASK	(1UL << MBCR_64BITBUS_SHIFT)
+
+/************************************************************
+ *	Memory Bank Mode Register (MBMR)
+************************************************************/
+#define REG_MBMR_OFFSET		0x21C0
+#define MBMR_MODE_MAX_VALUE	0xF
+#define MBMR_MODE_SHIFT		25
+#define MBMR_MODE_MASK		(MBMR_MODE_MAX_VALUE << MBMR_MODE_SHIFT)
+#define MBMR_BBA_SHIFT		24
+#define MBMR_BBA_MASK		(1UL << MBMR_BBA_SHIFT)
+
+/************************************************************
+ *	Memory Bank Boundary Address Register (MBBAR)
+ ************************************************************/
+#define REG_MBBAR_OFFSET	0x21D0
+#define MBBAR_BBA_MAX_VALUE	0xFF
+#define MBBAR_BBA_SHIFT		24
+#define MBBAR_BBA_MASK		(MBBAR_BBA_MAX_VALUE << MBBAR_BBA_SHIFT)
+
+/************************************************************
+ *	Memory Scrub Control Register (MSCR)
+ ************************************************************/
+#define REG_MSCR_OFFSET		0x2400
+#define MSCR_SCRUB_MOD_MASK	0xC0000000 /* scrub_mod - bit0:1*/
+#define MSCR_BACKGR_SCRUB	0x40000000 /* 01 */
+#define MSCR_SI_SHIFT		16 	/* si - bit8:15*/
+#define MSCR_SI_MAX_VALUE	0xFF
+#define MSCR_SI_MASK		(MSCR_SI_MAX_VALUE << MSCR_SI_SHIFT)
+
+/************************************************************
+ *	Memory Scrub Range Start Register (MSRSR)
+ ************************************************************/
+#define REG_MSRSR_OFFSET	0x2410
+
+/************************************************************
+ *	Memory Scrub Range End Register (MSRER)
+ ************************************************************/
+#define REG_MSRER_OFFSET	0x2420
+
+/************************************************************
+ *	Memory Scrub Pattern Register (MSPR)
+ ************************************************************/
+#define REG_MSPR_OFFSET		0x2430
+
+/************************************************************
+ *	Memory Check Control Register (MCCR)
+ ************************************************************/
+#define REG_MCCR_OFFSET		0x2440
+enum mccr_bits {
+	MCCR_ECC_EN	= CPC925_BIT(0), /* ECC high and low check */
+};
+
+/************************************************************
+ *	Memory Check Range End Register (MCRER)
+ ************************************************************/
+#define REG_MCRER_OFFSET	0x2450
+
+/************************************************************
+ *	Memory Error Address Register (MEAR)
+ ************************************************************/
+#define REG_MEAR_OFFSET		0x2460
+#define MEAR_BCNT_MAX_VALUE	0x3
+#define MEAR_BCNT_SHIFT		30
+#define MEAR_BCNT_MASK		(MEAR_BCNT_MAX_VALUE << MEAR_BCNT_SHIFT)
+#define MEAR_RANK_MAX_VALUE	0x7
+#define MEAR_RANK_SHIFT		27
+#define MEAR_RANK_MASK		(MEAR_RANK_MAX_VALUE << MEAR_RANK_SHIFT)
+#define MEAR_COL_MAX_VALUE	0x7FF
+#define MEAR_COL_SHIFT		16
+#define MEAR_COL_MASK		(MEAR_COL_MAX_VALUE << MEAR_COL_SHIFT)
+#define MEAR_BANK_MAX_VALUE	0x3
+#define MEAR_BANK_SHIFT		14
+#define MEAR_BANK_MASK		(MEAR_BANK_MAX_VALUE << MEAR_BANK_SHIFT)
+#define MEAR_ROW_MASK		0x00003FFF
+
+/************************************************************
+ *	Memory Error Syndrome Register (MESR)
+ ************************************************************/
+#define REG_MESR_OFFSET		0x2470
+#define MESR_ECC_SYN_H_MASK	0xFF00
+#define MESR_ECC_SYN_L_MASK	0x00FF
+
+/************************************************************
+ *	Memory Mode Control Register (MMCR)
+ ************************************************************/
+#define REG_MMCR_OFFSET		0x2500
+enum mmcr_bits {
+	MMCR_REG_DIMM_MODE = CPC925_BIT(3),
+};
+
+/*
+ * HyperTransport Link Registers
+ */
+/************************************************************
+ *  Error Handling/Enumeration Scratch Pad Register (ERRCTRL)
+ ************************************************************/
+#define REG_ERRCTRL_OFFSET	0x70140
+enum errctrl_bits {			 /* nonfatal interrupts for */
+	ERRCTRL_SERR_NF	= CPC925_BIT(0), /* system error */
+	ERRCTRL_CRC_NF	= CPC925_BIT(1), /* CRC error */
+	ERRCTRL_RSP_NF	= CPC925_BIT(2), /* Response error */
+	ERRCTRL_EOC_NF	= CPC925_BIT(3), /* End-Of-Chain error */
+	ERRCTRL_OVF_NF	= CPC925_BIT(4), /* Overflow error */
+	ERRCTRL_PROT_NF	= CPC925_BIT(5), /* Protocol error */
+
+	ERRCTRL_RSP_ERR	= CPC925_BIT(6), /* Response error received */
+	ERRCTRL_CHN_FAL = CPC925_BIT(7), /* Sync flooding detected */
+
+	HT_ERRCTRL_ENABLE = (ERRCTRL_SERR_NF | ERRCTRL_CRC_NF |
+			     ERRCTRL_RSP_NF | ERRCTRL_EOC_NF |
+			     ERRCTRL_OVF_NF | ERRCTRL_PROT_NF),
+	HT_ERRCTRL_DETECTED = (ERRCTRL_RSP_ERR | ERRCTRL_CHN_FAL),
+};
+
+/************************************************************
+ *  Link Configuration and Link Control Register (LINKCTRL)
+ ************************************************************/
+#define REG_LINKCTRL_OFFSET	0x70110
+enum linkctrl_bits {
+	LINKCTRL_CRC_ERR	= (CPC925_BIT(22) | CPC925_BIT(23)),
+	LINKCTRL_LINK_FAIL	= CPC925_BIT(27),
+
+	HT_LINKCTRL_DETECTED	= (LINKCTRL_CRC_ERR | LINKCTRL_LINK_FAIL),
+};
+
+/************************************************************
+ *  Link FreqCap/Error/Freq/Revision ID Register (LINKERR)
+ ************************************************************/
+#define REG_LINKERR_OFFSET	0x70120
+enum linkerr_bits {
+	LINKERR_EOC_ERR		= CPC925_BIT(17), /* End-Of-Chain error */
+	LINKERR_OVF_ERR		= CPC925_BIT(18), /* Receive Buffer Overflow */
+	LINKERR_PROT_ERR	= CPC925_BIT(19), /* Protocol error */
+
+	HT_LINKERR_DETECTED	= (LINKERR_EOC_ERR | LINKERR_OVF_ERR |
+				   LINKERR_PROT_ERR),
+};
+
+/************************************************************
+ *	Bridge Control Register (BRGCTRL)
+ ************************************************************/
+#define REG_BRGCTRL_OFFSET	0x70300
+enum brgctrl_bits {
+	BRGCTRL_DETSERR = CPC925_BIT(0), /* SERR on Secondary Bus */
+	BRGCTRL_SECBUSRESET = CPC925_BIT(9), /* Secondary Bus Reset */
+};
+
+/* Private structure for edac memory controller */
+struct cpc925_mc_pdata {
+	void __iomem *vbase;
+	unsigned long total_mem;
+	const char *name;
+	int edac_idx;
+};
+
+/* Private structure for common edac device */
+struct cpc925_dev_info {
+	void __iomem *vbase;
+	struct platform_device *pdev;
+	char *ctl_name;
+	int edac_idx;
+	struct edac_device_ctl_info *edac_dev;
+	void (*init)(struct cpc925_dev_info *dev_info);
+	void (*exit)(struct cpc925_dev_info *dev_info);
+	void (*check)(struct edac_device_ctl_info *edac_dev);
+};
+
+/* Get total memory size from Open Firmware DTB */
+static void get_total_mem(struct cpc925_mc_pdata *pdata)
+{
+	struct device_node *np = NULL;
+	const unsigned int *reg, *reg_end;
+	int len, sw, aw;
+	unsigned long start, size;
+
+	np = of_find_node_by_type(NULL, "memory");
+	if (!np)
+		return;
+
+	aw = of_n_addr_cells(np);
+	sw = of_n_size_cells(np);
+	reg = (const unsigned int *)of_get_property(np, "reg", &len);
+	reg_end = reg + len/4;
+
+	pdata->total_mem = 0;
+	do {
+		start = of_read_number(reg, aw);
+		reg += aw;
+		size = of_read_number(reg, sw);
+		reg += sw;
+		debugf1("%s: start 0x%lx, size 0x%lx\n", __func__,
+			start, size);
+		pdata->total_mem += size;
+	} while (reg < reg_end);
+
+	of_node_put(np);
+	debugf0("%s: total_mem 0x%lx\n", __func__, pdata->total_mem);
+}
+
+static void cpc925_init_csrows(struct mem_ctl_info *mci)
+{
+	struct cpc925_mc_pdata *pdata = mci->pvt_info;
+	struct csrow_info *csrow;
+	int index;
+	u32 mbmr, mbbar, bba;
+	unsigned long row_size, last_nr_pages = 0;
+
+	get_total_mem(pdata);
+
+	for (index = 0; index < mci->nr_csrows; index++) {
+		mbmr = __raw_readl(pdata->vbase + REG_MBMR_OFFSET +
+				   0x20 * index);
+		mbbar = __raw_readl(pdata->vbase + REG_MBBAR_OFFSET +
+				   0x20 + index);
+		bba = (((mbmr & MBMR_BBA_MASK) >> MBMR_BBA_SHIFT) << 8) |
+		       ((mbbar & MBBAR_BBA_MASK) >> MBBAR_BBA_SHIFT);
+
+		if (bba == 0)
+			continue; /* not populated */
+
+		csrow = &mci->csrows[index];
+
+		row_size = bba * (1UL << 28);	/* 256M */
+		csrow->first_page = last_nr_pages;
+		csrow->nr_pages = row_size >> PAGE_SHIFT;
+		csrow->last_page = csrow->first_page + csrow->nr_pages - 1;
+		last_nr_pages = csrow->last_page + 1;
+
+		csrow->mtype = MEM_RDDR;
+		csrow->edac_mode = EDAC_SECDED;
+
+		switch (csrow->nr_channels) {
+		case 1: /* Single channel */
+			csrow->grain = 32; /* four-beat burst of 32 bytes */
+			break;
+		case 2: /* Dual channel */
+		default:
+			csrow->grain = 64; /* four-beat burst of 64 bytes */
+			break;
+		}
+
+		switch ((mbmr & MBMR_MODE_MASK) >> MBMR_MODE_SHIFT) {
+		case 6: /* 0110, no way to differentiate X8 VS X16 */
+		case 5:	/* 0101 */
+		case 8: /* 1000 */
+			csrow->dtype = DEV_X16;
+			break;
+		case 7: /* 0111 */
+		case 9: /* 1001 */
+			csrow->dtype = DEV_X8;
+			break;
+		default:
+			csrow->dtype = DEV_UNKNOWN;
+			break;
+		}
+	}
+}
+
+/* Enable memory controller ECC detection */
+static void cpc925_mc_init(struct mem_ctl_info *mci)
+{
+	struct cpc925_mc_pdata *pdata = mci->pvt_info;
+	u32 apimask;
+	u32 mccr;
+
+	/* Enable various ECC error exceptions */
+	apimask = __raw_readl(pdata->vbase + REG_APIMASK_OFFSET);
+	if ((apimask & ECC_MASK_ENABLE) == 0) {
+		apimask |= ECC_MASK_ENABLE;
+		__raw_writel(apimask, pdata->vbase + REG_APIMASK_OFFSET);
+	}
+
+	/* Enable ECC detection */
+	mccr = __raw_readl(pdata->vbase + REG_MCCR_OFFSET);
+	if ((mccr & MCCR_ECC_EN) == 0) {
+		mccr |= MCCR_ECC_EN;
+		__raw_writel(mccr, pdata->vbase + REG_MCCR_OFFSET);
+	}
+}
+
+/* Disable memory controller ECC detection */
+static void cpc925_mc_exit(struct mem_ctl_info *mci)
+{
+	/*
+	 * WARNING:
+	 * We are supposed to clear the ECC error detection bits,
+	 * and it will be no problem to do so. However, once they
+	 * are cleared here if we want to re-install CPC925 EDAC
+	 * module later, setting them up in cpc925_mc_init() will
+	 * trigger machine check exception.
+	 * Also, it's ok to leave ECC error detection bits enabled,
+	 * since they are reset to 1 by default or by boot loader.
+	 */
+
+	return;
+}
+
+/*
+ * Revert DDR column/row/bank addresses into page frame number and
+ * offset in page.
+ *
+ * Suppose memory mode is 0x0111(128-bit mode, identical DIMM pairs),
+ * physical address(PA) bits to column address(CA) bits mappings are:
+ * CA	0   1   2   3   4   5   6   7   8   9   10
+ * PA	59  58  57  56  55  54  53  52  51  50  49
+ *
+ * physical address(PA) bits to bank address(BA) bits mappings are:
+ * BA	0   1
+ * PA	43  44
+ *
+ * physical address(PA) bits to row address(RA) bits mappings are:
+ * RA	0   1   2   3   4   5   6   7   8   9   10   11   12
+ * PA	36  35  34  48  47  46  45  40  41  42  39   38   37
+ */
+static void cpc925_mc_get_pfn(struct mem_ctl_info *mci, u32 mear,
+		unsigned long *pfn, unsigned long *offset, int *csrow)
+{
+	u32 bcnt, rank, col, bank, row;
+	u32 c;
+	unsigned long pa;
+	int i;
+
+	bcnt = (mear & MEAR_BCNT_MASK) >> MEAR_BCNT_SHIFT;
+	rank = (mear & MEAR_RANK_MASK) >> MEAR_RANK_SHIFT;
+	col = (mear & MEAR_COL_MASK) >> MEAR_COL_SHIFT;
+	bank = (mear & MEAR_BANK_MASK) >> MEAR_BANK_SHIFT;
+	row = mear & MEAR_ROW_MASK;
+
+	*csrow = rank;
+
+#ifdef CONFIG_EDAC_DEBUG
+	if (mci->csrows[rank].first_page == 0) {
+		cpc925_mc_printk(mci, KERN_ERR, "ECC occurs in a "
+			"non-populated csrow, broken hardware?\n");
+		return;
+	}
+#endif
+
+	/* Revert csrow number */
+	pa = mci->csrows[rank].first_page << PAGE_SHIFT;
+
+	/* Revert column address */
+	col += bcnt;
+	for (i = 0; i < 11; i++) {
+		c = col & 0x1;
+		col >>= 1;
+		pa |= c << (14 - i);
+	}
+
+	/* Revert bank address */
+	pa |= bank << 19;
+
+	/* Revert row address, in 4 steps */
+	for (i = 0; i < 3; i++) {
+		c = row & 0x1;
+		row >>= 1;
+		pa |= c << (26 - i);
+	}
+
+	for (i = 0; i < 3; i++) {
+		c = row & 0x1;
+		row >>= 1;
+		pa |= c << (21 + i);
+	}
+
+	for (i = 0; i < 4; i++) {
+		c = row & 0x1;
+		row >>= 1;
+		pa |= c << (18 - i);
+	}
+
+	for (i = 0; i < 3; i++) {
+		c = row & 0x1;
+		row >>= 1;
+		pa |= c << (29 - i);
+	}
+
+	*offset = pa & (PAGE_SIZE - 1);
+	*pfn = pa >> PAGE_SHIFT;
+
+	debugf0("%s: ECC physical address 0x%lx\n", __func__, pa);
+}
+
+static int cpc925_mc_find_channel(struct mem_ctl_info *mci, u16 syndrome)
+{
+	if ((syndrome & MESR_ECC_SYN_H_MASK) == 0)
+		return 0;
+
+	if ((syndrome & MESR_ECC_SYN_L_MASK) == 0)
+		return 1;
+
+	cpc925_mc_printk(mci, KERN_INFO, "Unexpected syndrome value: 0x%x\n",
+			 syndrome);
+	return 1;
+}
+
+/* Check memory controller registers for ECC errors */
+static void cpc925_mc_check(struct mem_ctl_info *mci)
+{
+	struct cpc925_mc_pdata *pdata = mci->pvt_info;
+	u32 apiexcp;
+	u32 mear;
+	u32 mesr;
+	u16 syndrome;
+	unsigned long pfn = 0, offset = 0;
+	int csrow = 0, channel = 0;
+
+	/* APIEXCP is cleared when read */
+	apiexcp = __raw_readl(pdata->vbase + REG_APIEXCP_OFFSET);
+	if ((apiexcp & ECC_EXCP_DETECTED) == 0)
+		return;
+
+	mesr = __raw_readl(pdata->vbase + REG_MESR_OFFSET);
+	syndrome = mesr | (MESR_ECC_SYN_H_MASK | MESR_ECC_SYN_L_MASK);
+
+	mear = __raw_readl(pdata->vbase + REG_MEAR_OFFSET);
+
+	/* Revert column/row addresses into page frame number, etc */
+	cpc925_mc_get_pfn(mci, mear, &pfn, &offset, &csrow);
+
+	if (apiexcp & CECC_EXCP_DETECTED) {
+		cpc925_mc_printk(mci, KERN_INFO, "DRAM CECC Fault\n");
+		channel = cpc925_mc_find_channel(mci, syndrome);
+		edac_mc_handle_ce(mci, pfn, offset, syndrome,
+				  csrow, channel, mci->ctl_name);
+	}
+
+	if (apiexcp & UECC_EXCP_DETECTED) {
+		cpc925_mc_printk(mci, KERN_INFO, "DRAM UECC Fault\n");
+		edac_mc_handle_ue(mci, pfn, offset, csrow, mci->ctl_name);
+	}
+
+	cpc925_mc_printk(mci, KERN_INFO, "Dump registers:\n");
+	cpc925_mc_printk(mci, KERN_INFO, "APIMASK		0x%08x\n",
+		__raw_readl(pdata->vbase + REG_APIMASK_OFFSET));
+	cpc925_mc_printk(mci, KERN_INFO, "APIEXCP		0x%08x\n",
+		apiexcp);
+	cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Ctrl	0x%08x\n",
+		__raw_readl(pdata->vbase + REG_MSCR_OFFSET));
+	cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Rge Start	0x%08x\n",
+		__raw_readl(pdata->vbase + REG_MSRSR_OFFSET));
+	cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Rge End	0x%08x\n",
+		__raw_readl(pdata->vbase + REG_MSRER_OFFSET));
+	cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Pattern	0x%08x\n",
+		__raw_readl(pdata->vbase + REG_MSPR_OFFSET));
+	cpc925_mc_printk(mci, KERN_INFO, "Mem Chk Ctrl		0x%08x\n",
+		__raw_readl(pdata->vbase + REG_MCCR_OFFSET));
+	cpc925_mc_printk(mci, KERN_INFO, "Mem Chk Rge End	0x%08x\n",
+		__raw_readl(pdata->vbase + REG_MCRER_OFFSET));
+	cpc925_mc_printk(mci, KERN_INFO, "Mem Err Address	0x%08x\n",
+		mesr);
+	cpc925_mc_printk(mci, KERN_INFO, "Mem Err Syndrome	0x%08x\n",
+		syndrome);
+}
+
+/******************** CPU err device********************************/
+/* Enable CPU Errors detection */
+static void cpc925_cpu_init(struct cpc925_dev_info *dev_info)
+{
+	u32 apimask;
+
+	apimask = __raw_readl(dev_info->vbase + REG_APIMASK_OFFSET);
+	if ((apimask & CPU_MASK_ENABLE) == 0) {
+		apimask |= CPU_MASK_ENABLE;
+		__raw_writel(apimask, dev_info->vbase + REG_APIMASK_OFFSET);
+	}
+}
+
+/* Disable CPU Errors detection */
+static void cpc925_cpu_exit(struct cpc925_dev_info *dev_info)
+{
+	/*
+	 * WARNING:
+	 * We are supposed to clear the CPU error detection bits,
+	 * and it will be no problem to do so. However, once they
+	 * are cleared here if we want to re-install CPC925 EDAC
+	 * module later, setting them up in cpc925_cpu_init() will
+	 * trigger machine check exception.
+	 * Also, it's ok to leave CPU error detection bits enabled,
+	 * since they are reset to 1 by default.
+	 */
+
+	return;
+}
+
+/* Check for CPU Errors */
+static void cpc925_cpu_check(struct edac_device_ctl_info *edac_dev)
+{
+	struct cpc925_dev_info *dev_info = edac_dev->pvt_info;
+	u32 apiexcp;
+	u32 apimask;
+
+	/* APIEXCP is cleared when read */
+	apiexcp = __raw_readl(dev_info->vbase + REG_APIEXCP_OFFSET);
+	if ((apiexcp & CPU_EXCP_DETECTED) == 0)
+		return;
+
+	apimask = __raw_readl(dev_info->vbase + REG_APIMASK_OFFSET);
+	cpc925_printk(KERN_INFO, "Processor Interface Fault\n"
+				 "Processor Interface register dump:\n");
+	cpc925_printk(KERN_INFO, "APIMASK		0x%08x\n", apimask);
+	cpc925_printk(KERN_INFO, "APIEXCP		0x%08x\n", apiexcp);
+
+	edac_device_handle_ue(edac_dev, 0, 0, edac_dev->ctl_name);
+}
+
+/******************** HT Link err device****************************/
+/* Enable HyperTransport Link Error detection */
+static void cpc925_htlink_init(struct cpc925_dev_info *dev_info)
+{
+	u32 ht_errctrl;
+
+	ht_errctrl = __raw_readl(dev_info->vbase + REG_ERRCTRL_OFFSET);
+	if ((ht_errctrl & HT_ERRCTRL_ENABLE) == 0) {
+		ht_errctrl |= HT_ERRCTRL_ENABLE;
+		__raw_writel(ht_errctrl, dev_info->vbase + REG_ERRCTRL_OFFSET);
+	}
+}
+
+/* Disable HyperTransport Link Error detection */
+static void cpc925_htlink_exit(struct cpc925_dev_info *dev_info)
+{
+	u32 ht_errctrl;
+
+	ht_errctrl = __raw_readl(dev_info->vbase + REG_ERRCTRL_OFFSET);
+	ht_errctrl &= ~HT_ERRCTRL_ENABLE;
+	__raw_writel(ht_errctrl, dev_info->vbase + REG_ERRCTRL_OFFSET);
+}
+
+/* Check for HyperTransport Link errors */
+static void cpc925_htlink_check(struct edac_device_ctl_info *edac_dev)
+{
+	struct cpc925_dev_info *dev_info = edac_dev->pvt_info;
+	u32 brgctrl = __raw_readl(dev_info->vbase + REG_BRGCTRL_OFFSET);
+	u32 linkctrl = __raw_readl(dev_info->vbase + REG_LINKCTRL_OFFSET);
+	u32 errctrl = __raw_readl(dev_info->vbase + REG_ERRCTRL_OFFSET);
+	u32 linkerr = __raw_readl(dev_info->vbase + REG_LINKERR_OFFSET);
+
+	if (!((brgctrl & BRGCTRL_DETSERR) ||
+	      (linkctrl & HT_LINKCTRL_DETECTED) ||
+	      (errctrl & HT_ERRCTRL_DETECTED) ||
+	      (linkerr & HT_LINKERR_DETECTED)))
+		return;
+
+	cpc925_printk(KERN_INFO, "HT Link Fault\n"
+				 "HT register dump:\n");
+	cpc925_printk(KERN_INFO, "Bridge Ctrl			0x%08x\n",
+		      brgctrl);
+	cpc925_printk(KERN_INFO, "Link Config Ctrl		0x%08x\n",
+		      linkctrl);
+	cpc925_printk(KERN_INFO, "Error Enum and Ctrl		0x%08x\n",
+		      errctrl);
+	cpc925_printk(KERN_INFO, "Link Error			0x%08x\n",
+		      linkerr);
+
+	/* Clear by write 1 */
+	if (brgctrl & BRGCTRL_DETSERR)
+		__raw_writel(BRGCTRL_DETSERR,
+				dev_info->vbase + REG_BRGCTRL_OFFSET);
+
+	if (linkctrl & HT_LINKCTRL_DETECTED)
+		__raw_writel(HT_LINKCTRL_DETECTED,
+				dev_info->vbase + REG_LINKCTRL_OFFSET);
+
+	/* Initiate Secondary Bus Reset to clear the chain failure */
+	if (errctrl & ERRCTRL_CHN_FAL)
+		__raw_writel(BRGCTRL_SECBUSRESET,
+				dev_info->vbase + REG_BRGCTRL_OFFSET);
+
+	if (errctrl & ERRCTRL_RSP_ERR)
+		__raw_writel(ERRCTRL_RSP_ERR,
+				dev_info->vbase + REG_ERRCTRL_OFFSET);
+
+	if (linkerr & HT_LINKERR_DETECTED)
+		__raw_writel(HT_LINKERR_DETECTED,
+				dev_info->vbase + REG_LINKERR_OFFSET);
+
+	edac_device_handle_ce(edac_dev, 0, 0, edac_dev->ctl_name);
+}
+
+static struct cpc925_dev_info cpc925_devs[] = {
+	{
+	.ctl_name = CPC925_CPU_ERR_DEV,
+	.init = cpc925_cpu_init,
+	.exit = cpc925_cpu_exit,
+	.check = cpc925_cpu_check,
+	},
+	{
+	.ctl_name = CPC925_HT_LINK_DEV,
+	.init = cpc925_htlink_init,
+	.exit = cpc925_htlink_exit,
+	.check = cpc925_htlink_check,
+	},
+	{0}, /* Terminated by NULL */
+};
+
+/*
+ * Add CPU Err detection and HyperTransport Link Err detection
+ * as common "edac_device", they have no corresponding device
+ * nodes in the Open Firmware DTB and we have to add platform
+ * devices for them. Also, they will share the MMIO with that
+ * of memory controller.
+ */
+static void cpc925_add_edac_devices(void __iomem *vbase)
+{
+	struct cpc925_dev_info *dev_info;
+
+	if (!vbase) {
+		cpc925_printk(KERN_ERR, "MMIO not established yet\n");
+		return;
+	}
+
+	for (dev_info = &cpc925_devs[0]; dev_info->init; dev_info++) {
+		dev_info->vbase = vbase;
+		dev_info->pdev = platform_device_register_simple(
+					dev_info->ctl_name, 0, NULL, 0);
+		if (IS_ERR(dev_info->pdev)) {
+			cpc925_printk(KERN_ERR,
+				"Can't register platform device for %s\n",
+				dev_info->ctl_name);
+			continue;
+		}
+
+		/*
+		 * Don't have to allocate private structure but
+		 * make use of cpc925_devs[] instead.
+		 */
+		dev_info->edac_idx = edac_device_alloc_index();
+		dev_info->edac_dev =
+			edac_device_alloc_ctl_info(0, dev_info->ctl_name,
+				1, NULL, 0, 0, NULL, 0, dev_info->edac_idx);
+		if (!dev_info->edac_dev) {
+			cpc925_printk(KERN_ERR, "No memory for edac device\n");
+			goto err1;
+		}
+
+		dev_info->edac_dev->pvt_info = dev_info;
+		dev_info->edac_dev->dev = &dev_info->pdev->dev;
+		dev_info->edac_dev->ctl_name = dev_info->ctl_name;
+		dev_info->edac_dev->mod_name = CPC925_EDAC_MOD_STR;
+		dev_info->edac_dev->dev_name = dev_name(&dev_info->pdev->dev);
+
+		if (edac_op_state == EDAC_OPSTATE_POLL)
+			dev_info->edac_dev->edac_check = dev_info->check;
+
+		if (dev_info->init)
+			dev_info->init(dev_info);
+
+		if (edac_device_add_device(dev_info->edac_dev) > 0) {
+			cpc925_printk(KERN_ERR,
+				"Unable to add edac device for %s\n",
+				dev_info->ctl_name);
+			goto err2;
+		}
+
+		debugf0("%s: Successfully added edac device for %s\n",
+			__func__, dev_info->ctl_name);
+
+		continue;
+
+err2:
+		if (dev_info->exit)
+			dev_info->exit(dev_info);
+		edac_device_free_ctl_info(dev_info->edac_dev);
+err1:
+		platform_device_unregister(dev_info->pdev);
+	}
+}
+
+/*
+ * Delete the common "edac_device" for CPU Err Detection
+ * and HyperTransport Link Err Detection
+ */
+static void cpc925_del_edac_devices(void)
+{
+	struct cpc925_dev_info *dev_info;
+
+	for (dev_info = &cpc925_devs[0]; dev_info->init; dev_info++) {
+		if (dev_info->edac_dev) {
+			edac_device_del_device(dev_info->edac_dev->dev);
+			edac_device_free_ctl_info(dev_info->edac_dev);
+			platform_device_unregister(dev_info->pdev);
+		}
+
+		if (dev_info->exit)
+			dev_info->exit(dev_info);
+
+		debugf0("%s: Successfully deleted edac device for %s\n",
+			__func__, dev_info->ctl_name);
+	}
+}
+
+/* Convert current back-ground scrub rate into byte/sec bandwith */
+static int cpc925_get_sdram_scrub_rate(struct mem_ctl_info *mci, u32 *bw)
+{
+	struct cpc925_mc_pdata *pdata = mci->pvt_info;
+	u32 mscr;
+	u8 si;
+
+	mscr = __raw_readl(pdata->vbase + REG_MSCR_OFFSET);
+	si = (mscr & MSCR_SI_MASK) >> MSCR_SI_SHIFT;
+
+	debugf0("%s, Mem Scrub Ctrl Register 0x%x\n", __func__, mscr);
+
+	if (((mscr & MSCR_SCRUB_MOD_MASK) != MSCR_BACKGR_SCRUB) ||
+	    (si == 0)) {
+		cpc925_mc_printk(mci, KERN_INFO, "Scrub mode not enabled\n");
+		*bw = 0;
+	} else
+		*bw = CPC925_SCRUB_BLOCK_SIZE * 0xFA67 / si;
+
+	return 0;
+}
+
+/* Return 0 for single channel; 1 for dual channel */
+static int cpc925_mc_get_channels(void __iomem *vbase)
+{
+	int dual = 0;
+	u32 mbcr;
+
+	mbcr = __raw_readl(vbase + REG_MBCR_OFFSET);
+
+	/*
+	 * Dual channel only when 128-bit wide physical bus
+	 * and 128-bit configuration.
+	 */
+	if (((mbcr & MBCR_64BITCFG_MASK) == 0) &&
+	    ((mbcr & MBCR_64BITBUS_MASK) == 0))
+		dual = 1;
+
+	debugf0("%s: %s channel\n", __func__,
+		(dual > 0) ? "Dual" : "Single");
+
+	return dual;
+}
+
+static int __devinit cpc925_probe(struct platform_device *pdev)
+{
+	static int edac_mc_idx;
+	struct mem_ctl_info *mci;
+	void __iomem *vbase;
+	struct cpc925_mc_pdata *pdata;
+	struct resource *r;
+	int res = 0, nr_channels;
+
+	debugf0("%s: %s platform device found!\n", __func__, pdev->name);
+
+	if (!devres_open_group(&pdev->dev, cpc925_probe, GFP_KERNEL)) {
+		res = -ENOMEM;
+		goto out;
+	}
+
+	r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
+	if (!r) {
+		cpc925_printk(KERN_ERR, "Unable to get resource\n");
+		res = -ENOENT;
+		goto err1;
+	}
+
+	if (!devm_request_mem_region(&pdev->dev,
+				     r->start,
+				     r->end - r->start + 1,
+				     pdev->name)) {
+		cpc925_printk(KERN_ERR, "Unable to request mem region\n");
+		res = -EBUSY;
+		goto err1;
+	}
+
+	vbase = devm_ioremap(&pdev->dev, r->start, r->end - r->start + 1);
+	if (!vbase) {
+		cpc925_printk(KERN_ERR, "Unable to ioremap device\n");
+		res = -ENOMEM;
+		goto err2;
+	}
+
+	nr_channels = cpc925_mc_get_channels(vbase);
+	mci = edac_mc_alloc(sizeof(struct cpc925_mc_pdata),
+			CPC925_NR_CSROWS, nr_channels + 1, edac_mc_idx);
+	if (!mci) {
+		cpc925_printk(KERN_ERR, "No memory for mem_ctl_info\n");
+		res = -ENOMEM;
+		goto err2;
+	}
+
+	pdata = mci->pvt_info;
+	pdata->vbase = vbase;
+	pdata->edac_idx = edac_mc_idx++;
+	pdata->name = pdev->name;
+
+	mci->dev = &pdev->dev;
+	platform_set_drvdata(pdev, mci);
+	mci->dev_name = dev_name(&pdev->dev);
+	mci->mtype_cap = MEM_FLAG_RDDR | MEM_FLAG_DDR;
+	mci->edac_ctl_cap = EDAC_FLAG_NONE | EDAC_FLAG_SECDED;
+	mci->edac_cap = EDAC_FLAG_SECDED;
+	mci->mod_name = CPC925_EDAC_MOD_STR;
+	mci->mod_ver = CPC925_EDAC_REVISION;
+	mci->ctl_name = pdev->name;
+
+	if (edac_op_state == EDAC_OPSTATE_POLL)
+		mci->edac_check = cpc925_mc_check;
+
+	mci->ctl_page_to_phys = NULL;
+	mci->scrub_mode = SCRUB_SW_SRC;
+	mci->set_sdram_scrub_rate = NULL;
+	mci->get_sdram_scrub_rate = cpc925_get_sdram_scrub_rate;
+
+	cpc925_init_csrows(mci);
+
+	/* Setup memory controller registers */
+	cpc925_mc_init(mci);
+
+	if (edac_mc_add_mc(mci) > 0) {
+		cpc925_mc_printk(mci, KERN_ERR, "Failed edac_mc_add_mc()\n");
+		goto err3;
+	}
+
+	cpc925_add_edac_devices(vbase);
+
+	/* get this far and it's successful */
+	debugf0("%s: success\n", __func__);
+
+	res = 0;
+	goto out;
+
+err3:
+	cpc925_mc_exit(mci);
+	edac_mc_free(mci);
+err2:
+	devm_release_mem_region(&pdev->dev, r->start, r->end-r->start+1);
+err1:
+	devres_release_group(&pdev->dev, cpc925_probe);
+out:
+	return res;
+}
+
+static int cpc925_remove(struct platform_device *pdev)
+{
+	struct mem_ctl_info *mci = platform_get_drvdata(pdev);
+
+	/*
+	 * Delete common edac devices before edac mc, because
+	 * the former share the MMIO of the latter.
+	 */
+	cpc925_del_edac_devices();
+	cpc925_mc_exit(mci);
+
+	edac_mc_del_mc(&pdev->dev);
+	edac_mc_free(mci);
+
+	return 0;
+}
+
+static struct platform_driver cpc925_edac_driver = {
+	.probe = cpc925_probe,
+	.remove = cpc925_remove,
+	.driver = {
+		   .name = "cpc925_edac",
+	}
+};
+
+static int __init cpc925_edac_init(void)
+{
+	int ret = 0;
+
+	printk(KERN_INFO "IBM CPC925 EDAC driver " CPC925_EDAC_REVISION "\n");
+	printk(KERN_INFO "\t(c) 2008 Wind River Systems, Inc\n");
+
+	/* Only support POLL mode so far */
+	edac_op_state = EDAC_OPSTATE_POLL;
+
+	ret = platform_driver_register(&cpc925_edac_driver);
+	if (ret) {
+		printk(KERN_WARNING "Failed to register %s\n",
+			CPC925_EDAC_MOD_STR);
+	}
+
+	return ret;
+}
+
+static void __exit cpc925_edac_exit(void)
+{
+	platform_driver_unregister(&cpc925_edac_driver);
+}
+
+module_init(cpc925_edac_init);
+module_exit(cpc925_edac_exit);
+
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Cao Qingtao <qingtao.cao@windriver.com>");
+MODULE_DESCRIPTION("IBM CPC925 Bridge and MC EDAC kernel module");
diff --git a/drivers/edac/edac_core.h b/drivers/edac/edac_core.h
index 48d3b14..3493c6b 100644
--- a/drivers/edac/edac_core.h
+++ b/drivers/edac/edac_core.h
@@ -841,6 +841,7 @@
 				int inst_nr, int block_nr, const char *msg);
 extern void edac_device_handle_ce(struct edac_device_ctl_info *edac_dev,
 				int inst_nr, int block_nr, const char *msg);
+extern int edac_device_alloc_index(void);
 
 /*
  * edac_pci APIs
diff --git a/drivers/edac/edac_device.c b/drivers/edac/edac_device.c
index a7d2c71..b02a6a6 100644
--- a/drivers/edac/edac_device.c
+++ b/drivers/edac/edac_device.c
@@ -490,6 +490,20 @@
 	mutex_unlock(&device_ctls_mutex);
 }
 
+/*
+ * edac_device_alloc_index: Allocate a unique device index number
+ *
+ * Return:
+ *	allocated index number
+ */
+int edac_device_alloc_index(void)
+{
+	static atomic_t device_indexes = ATOMIC_INIT(0);
+
+	return atomic_inc_return(&device_indexes) - 1;
+}
+EXPORT_SYMBOL_GPL(edac_device_alloc_index);
+
 /**
  * edac_device_add_device: Insert the 'edac_dev' structure into the
  * edac_device global list and create sysfs entries associated with
diff --git a/drivers/firmware/pcdp.c b/drivers/firmware/pcdp.c
index 58e9f8e..51e0e2d 100644
--- a/drivers/firmware/pcdp.c
+++ b/drivers/firmware/pcdp.c
@@ -28,10 +28,10 @@
 	char parity;
 
 	mmio = (uart->addr.space_id == ACPI_ADR_SPACE_SYSTEM_MEMORY);
-	p += sprintf(p, "uart8250,%s,0x%lx",
+	p += sprintf(p, "uart8250,%s,0x%llx",
 		mmio ? "mmio" : "io", uart->addr.address);
 	if (uart->baud) {
-		p += sprintf(p, ",%lu", uart->baud);
+		p += sprintf(p, ",%llu", uart->baud);
 		if (uart->bits) {
 			switch (uart->parity) {
 			    case 0x2: parity = 'e'; break;
diff --git a/drivers/gpio/Kconfig b/drivers/gpio/Kconfig
index 11f3739..3582c39 100644
--- a/drivers/gpio/Kconfig
+++ b/drivers/gpio/Kconfig
@@ -67,6 +67,12 @@
 
 comment "Memory mapped GPIO expanders:"
 
+config GPIO_PL061
+	bool "PrimeCell PL061 GPIO support"
+	depends on ARM_AMBA
+	help
+	  Say yes here to support the PrimeCell PL061 GPIO device
+
 config GPIO_XILINX
 	bool "Xilinx GPIO support"
 	depends on PPC_OF || MICROBLAZE
diff --git a/drivers/gpio/Makefile b/drivers/gpio/Makefile
index 49ac64e..ef90203 100644
--- a/drivers/gpio/Makefile
+++ b/drivers/gpio/Makefile
@@ -9,6 +9,7 @@
 obj-$(CONFIG_GPIO_MCP23S08)	+= mcp23s08.o
 obj-$(CONFIG_GPIO_PCA953X)	+= pca953x.o
 obj-$(CONFIG_GPIO_PCF857X)	+= pcf857x.o
+obj-$(CONFIG_GPIO_PL061)	+= pl061.o
 obj-$(CONFIG_GPIO_TWL4030)	+= twl4030-gpio.o
 obj-$(CONFIG_GPIO_XILINX)	+= xilinx_gpio.o
 obj-$(CONFIG_GPIO_BT8XX)	+= bt8xxgpio.o
diff --git a/drivers/gpio/max7301.c b/drivers/gpio/max7301.c
index 3e7f4e0..7b82eaa 100644
--- a/drivers/gpio/max7301.c
+++ b/drivers/gpio/max7301.c
@@ -287,7 +287,7 @@
 	return ret;
 }
 
-static int max7301_remove(struct spi_device *spi)
+static int __devexit max7301_remove(struct spi_device *spi)
 {
 	struct max7301 *ts;
 	int ret;
diff --git a/drivers/gpio/pca953x.c b/drivers/gpio/pca953x.c
index 8dc0164..cdb6574 100644
--- a/drivers/gpio/pca953x.c
+++ b/drivers/gpio/pca953x.c
@@ -15,6 +15,10 @@
 #include <linux/init.h>
 #include <linux/i2c.h>
 #include <linux/i2c/pca953x.h>
+#ifdef CONFIG_OF_GPIO
+#include <linux/of_platform.h>
+#include <linux/of_gpio.h>
+#endif
 
 #include <asm/gpio.h>
 
@@ -32,6 +36,7 @@
 	{ "pca9539", 16, },
 	{ "pca9554", 8, },
 	{ "pca9555", 16, },
+	{ "pca9556", 8, },
 	{ "pca9557", 8, },
 
 	{ "max7310", 8, },
@@ -49,7 +54,9 @@
 	uint16_t reg_direction;
 
 	struct i2c_client *client;
+	struct pca953x_platform_data *dyn_pdata;
 	struct gpio_chip gpio_chip;
+	char **names;
 };
 
 static int pca953x_write_reg(struct pca953x_chip *chip, int reg, uint16_t val)
@@ -192,8 +199,57 @@
 	gc->label = chip->client->name;
 	gc->dev = &chip->client->dev;
 	gc->owner = THIS_MODULE;
+	gc->names = chip->names;
 }
 
+/*
+ * Handlers for alternative sources of platform_data
+ */
+#ifdef CONFIG_OF_GPIO
+/*
+ * Translate OpenFirmware node properties into platform_data
+ */
+static struct pca953x_platform_data *
+pca953x_get_alt_pdata(struct i2c_client *client)
+{
+	struct pca953x_platform_data *pdata;
+	struct device_node *node;
+	const uint16_t *val;
+
+	node = dev_archdata_get_node(&client->dev.archdata);
+	if (node == NULL)
+		return NULL;
+
+	pdata = kzalloc(sizeof(struct pca953x_platform_data), GFP_KERNEL);
+	if (pdata == NULL) {
+		dev_err(&client->dev, "Unable to allocate platform_data\n");
+		return NULL;
+	}
+
+	pdata->gpio_base = -1;
+	val = of_get_property(node, "linux,gpio-base", NULL);
+	if (val) {
+		if (*val < 0)
+			dev_warn(&client->dev,
+				 "invalid gpio-base in device tree\n");
+		else
+			pdata->gpio_base = *val;
+	}
+
+	val = of_get_property(node, "polarity", NULL);
+	if (val)
+		pdata->invert = *val;
+
+	return pdata;
+}
+#else
+static struct pca953x_platform_data *
+pca953x_get_alt_pdata(struct i2c_client *client)
+{
+	return NULL;
+}
+#endif
+
 static int __devinit pca953x_probe(struct i2c_client *client,
 				   const struct i2c_device_id *id)
 {
@@ -201,20 +257,32 @@
 	struct pca953x_chip *chip;
 	int ret;
 
-	pdata = client->dev.platform_data;
-	if (pdata == NULL) {
-		dev_dbg(&client->dev, "no platform data\n");
-		return -EINVAL;
-	}
-
 	chip = kzalloc(sizeof(struct pca953x_chip), GFP_KERNEL);
 	if (chip == NULL)
 		return -ENOMEM;
 
+	pdata = client->dev.platform_data;
+	if (pdata == NULL) {
+		pdata = pca953x_get_alt_pdata(client);
+		/*
+		 * Unlike normal platform_data, this is allocated
+		 * dynamically and must be freed in the driver
+		 */
+		chip->dyn_pdata = pdata;
+	}
+
+	if (pdata == NULL) {
+		dev_dbg(&client->dev, "no platform data\n");
+		ret = -EINVAL;
+		goto out_failed;
+	}
+
 	chip->client = client;
 
 	chip->gpio_start = pdata->gpio_base;
 
+	chip->names = pdata->names;
+
 	/* initialize cached registers from their original values.
 	 * we can't share this chip with another i2c master.
 	 */
@@ -249,6 +317,7 @@
 	return 0;
 
 out_failed:
+	kfree(chip->dyn_pdata);
 	kfree(chip);
 	return ret;
 }
@@ -276,6 +345,7 @@
 		return ret;
 	}
 
+	kfree(chip->dyn_pdata);
 	kfree(chip);
 	return 0;
 }
diff --git a/drivers/gpio/pl061.c b/drivers/gpio/pl061.c
new file mode 100644
index 0000000..aa8e7cb
--- /dev/null
+++ b/drivers/gpio/pl061.c
@@ -0,0 +1,341 @@
+/*
+ *  linux/drivers/gpio/pl061.c
+ *
+ *  Copyright (C) 2008, 2009 Provigent Ltd.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * Driver for the ARM PrimeCell(tm) General Purpose Input/Output (PL061)
+ *
+ * Data sheet: ARM DDI 0190B, September 2000
+ */
+#include <linux/spinlock.h>
+#include <linux/errno.h>
+#include <linux/module.h>
+#include <linux/list.h>
+#include <linux/io.h>
+#include <linux/ioport.h>
+#include <linux/irq.h>
+#include <linux/bitops.h>
+#include <linux/workqueue.h>
+#include <linux/gpio.h>
+#include <linux/device.h>
+#include <linux/amba/bus.h>
+#include <linux/amba/pl061.h>
+
+#define GPIODIR 0x400
+#define GPIOIS  0x404
+#define GPIOIBE 0x408
+#define GPIOIEV 0x40C
+#define GPIOIE  0x410
+#define GPIORIS 0x414
+#define GPIOMIS 0x418
+#define GPIOIC  0x41C
+
+#define PL061_GPIO_NR	8
+
+struct pl061_gpio {
+	/* We use a list of pl061_gpio structs for each trigger IRQ in the main
+	 * interrupts controller of the system. We need this to support systems
+	 * in which more that one PL061s are connected to the same IRQ. The ISR
+	 * interates through this list to find the source of the interrupt.
+	 */
+	struct list_head	list;
+
+	/* Each of the two spinlocks protects a different set of hardware
+	 * regiters and data structurs. This decouples the code of the IRQ from
+	 * the GPIO code. This also makes the case of a GPIO routine call from
+	 * the IRQ code simpler.
+	 */
+	spinlock_t		lock;		/* GPIO registers */
+	spinlock_t		irq_lock;	/* IRQ registers */
+
+	void __iomem		*base;
+	unsigned		irq_base;
+	struct gpio_chip	gc;
+};
+
+static int pl061_direction_input(struct gpio_chip *gc, unsigned offset)
+{
+	struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
+	unsigned long flags;
+	unsigned char gpiodir;
+
+	if (offset >= gc->ngpio)
+		return -EINVAL;
+
+	spin_lock_irqsave(&chip->lock, flags);
+	gpiodir = readb(chip->base + GPIODIR);
+	gpiodir &= ~(1 << offset);
+	writeb(gpiodir, chip->base + GPIODIR);
+	spin_unlock_irqrestore(&chip->lock, flags);
+
+	return 0;
+}
+
+static int pl061_direction_output(struct gpio_chip *gc, unsigned offset,
+		int value)
+{
+	struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
+	unsigned long flags;
+	unsigned char gpiodir;
+
+	if (offset >= gc->ngpio)
+		return -EINVAL;
+
+	spin_lock_irqsave(&chip->lock, flags);
+	writeb(!!value << offset, chip->base + (1 << (offset + 2)));
+	gpiodir = readb(chip->base + GPIODIR);
+	gpiodir |= 1 << offset;
+	writeb(gpiodir, chip->base + GPIODIR);
+	spin_unlock_irqrestore(&chip->lock, flags);
+
+	return 0;
+}
+
+static int pl061_get_value(struct gpio_chip *gc, unsigned offset)
+{
+	struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
+
+	return !!readb(chip->base + (1 << (offset + 2)));
+}
+
+static void pl061_set_value(struct gpio_chip *gc, unsigned offset, int value)
+{
+	struct pl061_gpio *chip = container_of(gc, struct pl061_gpio, gc);
+
+	writeb(!!value << offset, chip->base + (1 << (offset + 2)));
+}
+
+/*
+ * PL061 GPIO IRQ
+ */
+static void pl061_irq_disable(unsigned irq)
+{
+	struct pl061_gpio *chip = get_irq_chip_data(irq);
+	int offset = irq - chip->irq_base;
+	unsigned long flags;
+	u8 gpioie;
+
+	spin_lock_irqsave(&chip->irq_lock, flags);
+	gpioie = readb(chip->base + GPIOIE);
+	gpioie &= ~(1 << offset);
+	writeb(gpioie, chip->base + GPIOIE);
+	spin_unlock_irqrestore(&chip->irq_lock, flags);
+}
+
+static void pl061_irq_enable(unsigned irq)
+{
+	struct pl061_gpio *chip = get_irq_chip_data(irq);
+	int offset = irq - chip->irq_base;
+	unsigned long flags;
+	u8 gpioie;
+
+	spin_lock_irqsave(&chip->irq_lock, flags);
+	gpioie = readb(chip->base + GPIOIE);
+	gpioie |= 1 << offset;
+	writeb(gpioie, chip->base + GPIOIE);
+	spin_unlock_irqrestore(&chip->irq_lock, flags);
+}
+
+static int pl061_irq_type(unsigned irq, unsigned trigger)
+{
+	struct pl061_gpio *chip = get_irq_chip_data(irq);
+	int offset = irq - chip->irq_base;
+	unsigned long flags;
+	u8 gpiois, gpioibe, gpioiev;
+
+	if (offset < 0 || offset > PL061_GPIO_NR)
+		return -EINVAL;
+
+	spin_lock_irqsave(&chip->irq_lock, flags);
+
+	gpioiev = readb(chip->base + GPIOIEV);
+
+	gpiois = readb(chip->base + GPIOIS);
+	if (trigger & (IRQ_TYPE_LEVEL_HIGH | IRQ_TYPE_LEVEL_LOW)) {
+		gpiois |= 1 << offset;
+		if (trigger & IRQ_TYPE_LEVEL_HIGH)
+			gpioiev |= 1 << offset;
+		else
+			gpioiev &= ~(1 << offset);
+	} else
+		gpiois &= ~(1 << offset);
+	writeb(gpiois, chip->base + GPIOIS);
+
+	gpioibe = readb(chip->base + GPIOIBE);
+	if ((trigger & IRQ_TYPE_EDGE_BOTH) == IRQ_TYPE_EDGE_BOTH)
+		gpioibe |= 1 << offset;
+	else {
+		gpioibe &= ~(1 << offset);
+		if (trigger & IRQ_TYPE_EDGE_RISING)
+			gpioiev |= 1 << offset;
+		else
+			gpioiev &= ~(1 << offset);
+	}
+	writeb(gpioibe, chip->base + GPIOIBE);
+
+	writeb(gpioiev, chip->base + GPIOIEV);
+
+	spin_unlock_irqrestore(&chip->irq_lock, flags);
+
+	return 0;
+}
+
+static struct irq_chip pl061_irqchip = {
+	.name		= "GPIO",
+	.enable		= pl061_irq_enable,
+	.disable	= pl061_irq_disable,
+	.set_type	= pl061_irq_type,
+};
+
+static void pl061_irq_handler(unsigned irq, struct irq_desc *desc)
+{
+	struct list_head *chip_list = get_irq_chip_data(irq);
+	struct list_head *ptr;
+	struct pl061_gpio *chip;
+
+	desc->chip->ack(irq);
+	list_for_each(ptr, chip_list) {
+		unsigned long pending;
+		int gpio;
+
+		chip = list_entry(ptr, struct pl061_gpio, list);
+		pending = readb(chip->base + GPIOMIS);
+		writeb(pending, chip->base + GPIOIC);
+
+		if (pending == 0)
+			continue;
+
+		for_each_bit(gpio, &pending, PL061_GPIO_NR)
+			generic_handle_irq(gpio_to_irq(gpio));
+	}
+	desc->chip->unmask(irq);
+}
+
+static int __init pl061_probe(struct amba_device *dev, struct amba_id *id)
+{
+	struct pl061_platform_data *pdata;
+	struct pl061_gpio *chip;
+	struct list_head *chip_list;
+	int ret, irq, i;
+	static unsigned long init_irq[BITS_TO_LONGS(NR_IRQS)];
+
+	pdata = dev->dev.platform_data;
+	if (pdata == NULL)
+		return -ENODEV;
+
+	chip = kzalloc(sizeof(*chip), GFP_KERNEL);
+	if (chip == NULL)
+		return -ENOMEM;
+
+	if (!request_mem_region(dev->res.start,
+				resource_size(&dev->res), "pl061")) {
+		ret = -EBUSY;
+		goto free_mem;
+	}
+
+	chip->base = ioremap(dev->res.start, resource_size(&dev->res));
+	if (chip->base == NULL) {
+		ret = -ENOMEM;
+		goto release_region;
+	}
+
+	spin_lock_init(&chip->lock);
+	spin_lock_init(&chip->irq_lock);
+	INIT_LIST_HEAD(&chip->list);
+
+	chip->gc.direction_input = pl061_direction_input;
+	chip->gc.direction_output = pl061_direction_output;
+	chip->gc.get = pl061_get_value;
+	chip->gc.set = pl061_set_value;
+	chip->gc.base = pdata->gpio_base;
+	chip->gc.ngpio = PL061_GPIO_NR;
+	chip->gc.label = dev_name(&dev->dev);
+	chip->gc.dev = &dev->dev;
+	chip->gc.owner = THIS_MODULE;
+
+	chip->irq_base = pdata->irq_base;
+
+	ret = gpiochip_add(&chip->gc);
+	if (ret)
+		goto iounmap;
+
+	/*
+	 * irq_chip support
+	 */
+
+	if (chip->irq_base == (unsigned) -1)
+		return 0;
+
+	writeb(0, chip->base + GPIOIE); /* disable irqs */
+	irq = dev->irq[0];
+	if (irq < 0) {
+		ret = -ENODEV;
+		goto iounmap;
+	}
+	set_irq_chained_handler(irq, pl061_irq_handler);
+	if (!test_and_set_bit(irq, init_irq)) { /* list initialized? */
+		chip_list = kmalloc(sizeof(*chip_list), GFP_KERNEL);
+		if (chip_list == NULL) {
+			ret = -ENOMEM;
+			goto iounmap;
+		}
+		INIT_LIST_HEAD(chip_list);
+		set_irq_chip_data(irq, chip_list);
+	} else
+		chip_list = get_irq_chip_data(irq);
+	list_add(&chip->list, chip_list);
+
+	for (i = 0; i < PL061_GPIO_NR; i++) {
+		if (pdata->directions & (1 << i))
+			pl061_direction_output(&chip->gc, i,
+					pdata->values & (1 << i));
+		else
+			pl061_direction_input(&chip->gc, i);
+
+		set_irq_chip(i+chip->irq_base, &pl061_irqchip);
+		set_irq_handler(i+chip->irq_base, handle_simple_irq);
+		set_irq_flags(i+chip->irq_base, IRQF_VALID);
+		set_irq_chip_data(i+chip->irq_base, chip);
+	}
+
+	return 0;
+
+iounmap:
+	iounmap(chip->base);
+release_region:
+	release_mem_region(dev->res.start, resource_size(&dev->res));
+free_mem:
+	kfree(chip);
+
+	return ret;
+}
+
+static struct amba_id pl061_ids[] __initdata = {
+	{
+		.id	= 0x00041061,
+		.mask	= 0x000fffff,
+	},
+	{ 0, 0 },
+};
+
+static struct amba_driver pl061_gpio_driver = {
+	.drv = {
+		.name	= "pl061_gpio",
+	},
+	.id_table	= pl061_ids,
+	.probe		= pl061_probe,
+};
+
+static int __init pl061_gpio_init(void)
+{
+	return amba_driver_register(&pl061_gpio_driver);
+}
+subsys_initcall(pl061_gpio_init);
+
+MODULE_AUTHOR("Baruch Siach <baruch@tkos.co.il>");
+MODULE_DESCRIPTION("PL061 GPIO driver");
+MODULE_LICENSE("GPL");
diff --git a/drivers/gpu/drm/drm_agpsupport.c b/drivers/gpu/drm/drm_agpsupport.c
index 1479659..d68888f 100644
--- a/drivers/gpu/drm/drm_agpsupport.c
+++ b/drivers/gpu/drm/drm_agpsupport.c
@@ -203,7 +203,7 @@
 
 	if (!dev->agp || !dev->agp->acquired)
 		return -EINVAL;
-	if (!(entry = drm_alloc(sizeof(*entry), DRM_MEM_AGPLISTS)))
+	if (!(entry = kmalloc(sizeof(*entry), GFP_KERNEL)))
 		return -ENOMEM;
 
 	memset(entry, 0, sizeof(*entry));
@@ -211,7 +211,7 @@
 	pages = (request->size + PAGE_SIZE - 1) / PAGE_SIZE;
 	type = (u32) request->type;
 	if (!(memory = drm_alloc_agp(dev, pages, type))) {
-		drm_free(entry, sizeof(*entry), DRM_MEM_AGPLISTS);
+		kfree(entry);
 		return -ENOMEM;
 	}
 
@@ -369,7 +369,7 @@
 	list_del(&entry->head);
 
 	drm_free_agp(entry->memory, entry->pages);
-	drm_free(entry, sizeof(*entry), DRM_MEM_AGPLISTS);
+	kfree(entry);
 	return 0;
 }
 EXPORT_SYMBOL(drm_agp_free);
@@ -397,13 +397,13 @@
 {
 	struct drm_agp_head *head = NULL;
 
-	if (!(head = drm_alloc(sizeof(*head), DRM_MEM_AGPLISTS)))
+	if (!(head = kmalloc(sizeof(*head), GFP_KERNEL)))
 		return NULL;
 	memset((void *)head, 0, sizeof(*head));
 	head->bridge = agp_find_bridge(dev->pdev);
 	if (!head->bridge) {
 		if (!(head->bridge = agp_backend_acquire(dev->pdev))) {
-			drm_free(head, sizeof(*head), DRM_MEM_AGPLISTS);
+			kfree(head);
 			return NULL;
 		}
 		agp_copy_info(head->bridge, &head->agp_info);
@@ -412,7 +412,7 @@
 		agp_copy_info(head->bridge, &head->agp_info);
 	}
 	if (head->agp_info.chipset == NOT_SUPPORTED) {
-		drm_free(head, sizeof(*head), DRM_MEM_AGPLISTS);
+		kfree(head);
 		return NULL;
 	}
 	INIT_LIST_HEAD(&head->memory);
@@ -482,7 +482,7 @@
 	}
 
 	for (i = 0; i < num_pages; i++)
-		mem->memory[i] = phys_to_gart(page_to_phys(pages[i]));
+		mem->pages[i] = pages[i];
 	mem->page_count = num_pages;
 
 	mem->is_flushed = true;
diff --git a/drivers/gpu/drm/drm_auth.c b/drivers/gpu/drm/drm_auth.c
index ca7a9ef..932b5aa 100644
--- a/drivers/gpu/drm/drm_auth.c
+++ b/drivers/gpu/drm/drm_auth.c
@@ -79,7 +79,7 @@
 	struct drm_device *dev = master->minor->dev;
 	DRM_DEBUG("%d\n", magic);
 
-	entry = drm_alloc(sizeof(*entry), DRM_MEM_MAGIC);
+	entry = kmalloc(sizeof(*entry), GFP_KERNEL);
 	if (!entry)
 		return -ENOMEM;
 	memset(entry, 0, sizeof(*entry));
@@ -120,7 +120,7 @@
 	list_del(&pt->head);
 	mutex_unlock(&dev->struct_mutex);
 
-	drm_free(pt, sizeof(*pt), DRM_MEM_MAGIC);
+	kfree(pt);
 
 	return 0;
 }
diff --git a/drivers/gpu/drm/drm_bufs.c b/drivers/gpu/drm/drm_bufs.c
index 80a2575..6246e3f 100644
--- a/drivers/gpu/drm/drm_bufs.c
+++ b/drivers/gpu/drm/drm_bufs.c
@@ -151,7 +151,7 @@
 	unsigned long user_token;
 	int ret;
 
-	map = drm_alloc(sizeof(*map), DRM_MEM_MAPS);
+	map = kmalloc(sizeof(*map), GFP_KERNEL);
 	if (!map)
 		return -ENOMEM;
 
@@ -165,7 +165,7 @@
 	 * when processes fork.
 	 */
 	if ((map->flags & _DRM_REMOVABLE) && map->type != _DRM_SHM) {
-		drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+		kfree(map);
 		return -EINVAL;
 	}
 	DRM_DEBUG("offset = 0x%08llx, size = 0x%08lx, type = %d\n",
@@ -179,7 +179,7 @@
 		map->size = PAGE_ALIGN(map->size);
 
 	if ((map->offset & (~(resource_size_t)PAGE_MASK)) || (map->size & (~PAGE_MASK))) {
-		drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+		kfree(map);
 		return -EINVAL;
 	}
 	map->mtrr = -1;
@@ -191,7 +191,7 @@
 #if !defined(__sparc__) && !defined(__alpha__) && !defined(__ia64__) && !defined(__powerpc64__) && !defined(__x86_64__)
 		if (map->offset + (map->size-1) < map->offset ||
 		    map->offset < virt_to_phys(high_memory)) {
-			drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+			kfree(map);
 			return -EINVAL;
 		}
 #endif
@@ -212,7 +212,7 @@
 				list->map->size = map->size;
 			}
 
-			drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+			kfree(map);
 			*maplist = list;
 			return 0;
 		}
@@ -227,7 +227,7 @@
 		if (map->type == _DRM_REGISTERS) {
 			map->handle = ioremap(map->offset, map->size);
 			if (!map->handle) {
-				drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+				kfree(map);
 				return -ENOMEM;
 			}
 		}
@@ -243,7 +243,7 @@
 				list->map->size = map->size;
 			}
 
-			drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+			kfree(map);
 			*maplist = list;
 			return 0;
 		}
@@ -251,7 +251,7 @@
 		DRM_DEBUG("%lu %d %p\n",
 			  map->size, drm_order(map->size), map->handle);
 		if (!map->handle) {
-			drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+			kfree(map);
 			return -ENOMEM;
 		}
 		map->offset = (unsigned long)map->handle;
@@ -259,7 +259,7 @@
 			/* Prevent a 2nd X Server from creating a 2nd lock */
 			if (dev->primary->master->lock.hw_lock != NULL) {
 				vfree(map->handle);
-				drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+				kfree(map);
 				return -EBUSY;
 			}
 			dev->sigdata.lock = dev->primary->master->lock.hw_lock = map->handle;	/* Pointer to lock */
@@ -270,7 +270,7 @@
 		int valid = 0;
 
 		if (!drm_core_has_AGP(dev)) {
-			drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+			kfree(map);
 			return -EINVAL;
 		}
 #ifdef __alpha__
@@ -303,7 +303,7 @@
 			}
 		}
 		if (!list_empty(&dev->agp->memory) && !valid) {
-			drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+			kfree(map);
 			return -EPERM;
 		}
 		DRM_DEBUG("AGP offset = 0x%08llx, size = 0x%08lx\n",
@@ -316,7 +316,7 @@
 	}
 	case _DRM_SCATTER_GATHER:
 		if (!dev->sg) {
-			drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+			kfree(map);
 			return -EINVAL;
 		}
 		map->offset += (unsigned long)dev->sg->virtual;
@@ -328,7 +328,7 @@
 		 * need to point to a 64bit variable first. */
 		dmah = drm_pci_alloc(dev, map->size, map->size, 0xffffffffUL);
 		if (!dmah) {
-			drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+			kfree(map);
 			return -ENOMEM;
 		}
 		map->handle = dmah->vaddr;
@@ -336,15 +336,15 @@
 		kfree(dmah);
 		break;
 	default:
-		drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+		kfree(map);
 		return -EINVAL;
 	}
 
-	list = drm_alloc(sizeof(*list), DRM_MEM_MAPS);
+	list = kmalloc(sizeof(*list), GFP_KERNEL);
 	if (!list) {
 		if (map->type == _DRM_REGISTERS)
 			iounmap(map->handle);
-		drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+		kfree(map);
 		return -EINVAL;
 	}
 	memset(list, 0, sizeof(*list));
@@ -362,8 +362,8 @@
 	if (ret) {
 		if (map->type == _DRM_REGISTERS)
 			iounmap(map->handle);
-		drm_free(map, sizeof(*map), DRM_MEM_MAPS);
-		drm_free(list, sizeof(*list), DRM_MEM_MAPS);
+		kfree(map);
+		kfree(list);
 		mutex_unlock(&dev->struct_mutex);
 		return ret;
 	}
@@ -448,7 +448,7 @@
 			list_del(&r_list->head);
 			drm_ht_remove_key(&dev->map_hash,
 					  r_list->user_token >> PAGE_SHIFT);
-			drm_free(r_list, sizeof(*r_list), DRM_MEM_MAPS);
+			kfree(r_list);
 			found = 1;
 			break;
 		}
@@ -491,7 +491,7 @@
 		DRM_ERROR("tried to rmmap GEM object\n");
 		break;
 	}
-	drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+	kfree(map);
 
 	return 0;
 }
@@ -582,24 +582,16 @@
 				drm_pci_free(dev, entry->seglist[i]);
 			}
 		}
-		drm_free(entry->seglist,
-			 entry->seg_count *
-			 sizeof(*entry->seglist), DRM_MEM_SEGS);
+		kfree(entry->seglist);
 
 		entry->seg_count = 0;
 	}
 
 	if (entry->buf_count) {
 		for (i = 0; i < entry->buf_count; i++) {
-			if (entry->buflist[i].dev_private) {
-				drm_free(entry->buflist[i].dev_private,
-					 entry->buflist[i].dev_priv_size,
-					 DRM_MEM_BUFS);
-			}
+			kfree(entry->buflist[i].dev_private);
 		}
-		drm_free(entry->buflist,
-			 entry->buf_count *
-			 sizeof(*entry->buflist), DRM_MEM_BUFS);
+		kfree(entry->buflist);
 
 		entry->buf_count = 0;
 	}
@@ -698,8 +690,7 @@
 		return -EINVAL;
 	}
 
-	entry->buflist = drm_alloc(count * sizeof(*entry->buflist),
-				   DRM_MEM_BUFS);
+	entry->buflist = kmalloc(count * sizeof(*entry->buflist), GFP_KERNEL);
 	if (!entry->buflist) {
 		mutex_unlock(&dev->struct_mutex);
 		atomic_dec(&dev->buf_alloc);
@@ -729,7 +720,7 @@
 		buf->file_priv = NULL;
 
 		buf->dev_priv_size = dev->driver->dev_priv_size;
-		buf->dev_private = drm_alloc(buf->dev_priv_size, DRM_MEM_BUFS);
+		buf->dev_private = kmalloc(buf->dev_priv_size, GFP_KERNEL);
 		if (!buf->dev_private) {
 			/* Set count correctly so we free the proper amount. */
 			entry->buf_count = count;
@@ -749,10 +740,9 @@
 
 	DRM_DEBUG("byte_count: %d\n", byte_count);
 
-	temp_buflist = drm_realloc(dma->buflist,
-				   dma->buf_count * sizeof(*dma->buflist),
-				   (dma->buf_count + entry->buf_count)
-				   * sizeof(*dma->buflist), DRM_MEM_BUFS);
+	temp_buflist = krealloc(dma->buflist,
+				(dma->buf_count + entry->buf_count) *
+				sizeof(*dma->buflist), GFP_KERNEL);
 	if (!temp_buflist) {
 		/* Free the entry because it isn't valid */
 		drm_cleanup_buf_error(dev, entry);
@@ -854,8 +844,7 @@
 		return -EINVAL;
 	}
 
-	entry->buflist = drm_alloc(count * sizeof(*entry->buflist),
-				   DRM_MEM_BUFS);
+	entry->buflist = kmalloc(count * sizeof(*entry->buflist), GFP_KERNEL);
 	if (!entry->buflist) {
 		mutex_unlock(&dev->struct_mutex);
 		atomic_dec(&dev->buf_alloc);
@@ -863,11 +852,9 @@
 	}
 	memset(entry->buflist, 0, count * sizeof(*entry->buflist));
 
-	entry->seglist = drm_alloc(count * sizeof(*entry->seglist),
-				   DRM_MEM_SEGS);
+	entry->seglist = kmalloc(count * sizeof(*entry->seglist), GFP_KERNEL);
 	if (!entry->seglist) {
-		drm_free(entry->buflist,
-			 count * sizeof(*entry->buflist), DRM_MEM_BUFS);
+		kfree(entry->buflist);
 		mutex_unlock(&dev->struct_mutex);
 		atomic_dec(&dev->buf_alloc);
 		return -ENOMEM;
@@ -877,13 +864,11 @@
 	/* Keep the original pagelist until we know all the allocations
 	 * have succeeded
 	 */
-	temp_pagelist = drm_alloc((dma->page_count + (count << page_order))
-				  * sizeof(*dma->pagelist), DRM_MEM_PAGES);
+	temp_pagelist = kmalloc((dma->page_count + (count << page_order)) *
+			       sizeof(*dma->pagelist), GFP_KERNEL);
 	if (!temp_pagelist) {
-		drm_free(entry->buflist,
-			 count * sizeof(*entry->buflist), DRM_MEM_BUFS);
-		drm_free(entry->seglist,
-			 count * sizeof(*entry->seglist), DRM_MEM_SEGS);
+		kfree(entry->buflist);
+		kfree(entry->seglist);
 		mutex_unlock(&dev->struct_mutex);
 		atomic_dec(&dev->buf_alloc);
 		return -ENOMEM;
@@ -907,9 +892,7 @@
 			entry->buf_count = count;
 			entry->seg_count = count;
 			drm_cleanup_buf_error(dev, entry);
-			drm_free(temp_pagelist,
-				 (dma->page_count + (count << page_order))
-				 * sizeof(*dma->pagelist), DRM_MEM_PAGES);
+			kfree(temp_pagelist);
 			mutex_unlock(&dev->struct_mutex);
 			atomic_dec(&dev->buf_alloc);
 			return -ENOMEM;
@@ -940,18 +923,14 @@
 			buf->file_priv = NULL;
 
 			buf->dev_priv_size = dev->driver->dev_priv_size;
-			buf->dev_private = drm_alloc(buf->dev_priv_size,
-						     DRM_MEM_BUFS);
+			buf->dev_private = kmalloc(buf->dev_priv_size,
+						  GFP_KERNEL);
 			if (!buf->dev_private) {
 				/* Set count correctly so we free the proper amount. */
 				entry->buf_count = count;
 				entry->seg_count = count;
 				drm_cleanup_buf_error(dev, entry);
-				drm_free(temp_pagelist,
-					 (dma->page_count +
-					  (count << page_order))
-					 * sizeof(*dma->pagelist),
-					 DRM_MEM_PAGES);
+				kfree(temp_pagelist);
 				mutex_unlock(&dev->struct_mutex);
 				atomic_dec(&dev->buf_alloc);
 				return -ENOMEM;
@@ -964,16 +943,13 @@
 		byte_count += PAGE_SIZE << page_order;
 	}
 
-	temp_buflist = drm_realloc(dma->buflist,
-				   dma->buf_count * sizeof(*dma->buflist),
-				   (dma->buf_count + entry->buf_count)
-				   * sizeof(*dma->buflist), DRM_MEM_BUFS);
+	temp_buflist = krealloc(dma->buflist,
+				(dma->buf_count + entry->buf_count) *
+				sizeof(*dma->buflist), GFP_KERNEL);
 	if (!temp_buflist) {
 		/* Free the entry because it isn't valid */
 		drm_cleanup_buf_error(dev, entry);
-		drm_free(temp_pagelist,
-			 (dma->page_count + (count << page_order))
-			 * sizeof(*dma->pagelist), DRM_MEM_PAGES);
+		kfree(temp_pagelist);
 		mutex_unlock(&dev->struct_mutex);
 		atomic_dec(&dev->buf_alloc);
 		return -ENOMEM;
@@ -988,9 +964,7 @@
 	 * with the new one.
 	 */
 	if (dma->page_count) {
-		drm_free(dma->pagelist,
-			 dma->page_count * sizeof(*dma->pagelist),
-			 DRM_MEM_PAGES);
+		kfree(dma->pagelist);
 	}
 	dma->pagelist = temp_pagelist;
 
@@ -1086,8 +1060,8 @@
 		return -EINVAL;
 	}
 
-	entry->buflist = drm_alloc(count * sizeof(*entry->buflist),
-				   DRM_MEM_BUFS);
+	entry->buflist = kmalloc(count * sizeof(*entry->buflist),
+				GFP_KERNEL);
 	if (!entry->buflist) {
 		mutex_unlock(&dev->struct_mutex);
 		atomic_dec(&dev->buf_alloc);
@@ -1118,7 +1092,7 @@
 		buf->file_priv = NULL;
 
 		buf->dev_priv_size = dev->driver->dev_priv_size;
-		buf->dev_private = drm_alloc(buf->dev_priv_size, DRM_MEM_BUFS);
+		buf->dev_private = kmalloc(buf->dev_priv_size, GFP_KERNEL);
 		if (!buf->dev_private) {
 			/* Set count correctly so we free the proper amount. */
 			entry->buf_count = count;
@@ -1139,10 +1113,9 @@
 
 	DRM_DEBUG("byte_count: %d\n", byte_count);
 
-	temp_buflist = drm_realloc(dma->buflist,
-				   dma->buf_count * sizeof(*dma->buflist),
-				   (dma->buf_count + entry->buf_count)
-				   * sizeof(*dma->buflist), DRM_MEM_BUFS);
+	temp_buflist = krealloc(dma->buflist,
+				(dma->buf_count + entry->buf_count) *
+				sizeof(*dma->buflist), GFP_KERNEL);
 	if (!temp_buflist) {
 		/* Free the entry because it isn't valid */
 		drm_cleanup_buf_error(dev, entry);
@@ -1248,8 +1221,8 @@
 		return -EINVAL;
 	}
 
-	entry->buflist = drm_alloc(count * sizeof(*entry->buflist),
-				   DRM_MEM_BUFS);
+	entry->buflist = kmalloc(count * sizeof(*entry->buflist),
+				GFP_KERNEL);
 	if (!entry->buflist) {
 		mutex_unlock(&dev->struct_mutex);
 		atomic_dec(&dev->buf_alloc);
@@ -1279,7 +1252,7 @@
 		buf->file_priv = NULL;
 
 		buf->dev_priv_size = dev->driver->dev_priv_size;
-		buf->dev_private = drm_alloc(buf->dev_priv_size, DRM_MEM_BUFS);
+		buf->dev_private = kmalloc(buf->dev_priv_size, GFP_KERNEL);
 		if (!buf->dev_private) {
 			/* Set count correctly so we free the proper amount. */
 			entry->buf_count = count;
@@ -1299,10 +1272,9 @@
 
 	DRM_DEBUG("byte_count: %d\n", byte_count);
 
-	temp_buflist = drm_realloc(dma->buflist,
-				   dma->buf_count * sizeof(*dma->buflist),
-				   (dma->buf_count + entry->buf_count)
-				   * sizeof(*dma->buflist), DRM_MEM_BUFS);
+	temp_buflist = krealloc(dma->buflist,
+				(dma->buf_count + entry->buf_count) *
+				sizeof(*dma->buflist), GFP_KERNEL);
 	if (!temp_buflist) {
 		/* Free the entry because it isn't valid */
 		drm_cleanup_buf_error(dev, entry);
diff --git a/drivers/gpu/drm/drm_context.c b/drivers/gpu/drm/drm_context.c
index 7d1e53c..2607753 100644
--- a/drivers/gpu/drm/drm_context.c
+++ b/drivers/gpu/drm/drm_context.c
@@ -341,7 +341,7 @@
 			}
 	}
 
-	ctx_entry = drm_alloc(sizeof(*ctx_entry), DRM_MEM_CTXLIST);
+	ctx_entry = kmalloc(sizeof(*ctx_entry), GFP_KERNEL);
 	if (!ctx_entry) {
 		DRM_DEBUG("out of memory\n");
 		return -ENOMEM;
@@ -456,7 +456,7 @@
 		list_for_each_entry_safe(pos, n, &dev->ctxlist, head) {
 			if (pos->handle == ctx->handle) {
 				list_del(&pos->head);
-				drm_free(pos, sizeof(*pos), DRM_MEM_CTXLIST);
+				kfree(pos);
 				--dev->ctx_count;
 			}
 		}
diff --git a/drivers/gpu/drm/drm_debugfs.c b/drivers/gpu/drm/drm_debugfs.c
index 6ce0e26..2960b6d 100644
--- a/drivers/gpu/drm/drm_debugfs.c
+++ b/drivers/gpu/drm/drm_debugfs.c
@@ -100,15 +100,13 @@
 		    (dev->driver->driver_features & features) != features)
 			continue;
 
-		tmp = drm_alloc(sizeof(struct drm_info_node),
-				_DRM_DRIVER);
+		tmp = kmalloc(sizeof(struct drm_info_node), GFP_KERNEL);
 		ent = debugfs_create_file(files[i].name, S_IFREG | S_IRUGO,
 					  root, tmp, &drm_debugfs_fops);
 		if (!ent) {
 			DRM_ERROR("Cannot create /sys/kernel/debug/dri/%s/%s\n",
 				  name, files[i].name);
-			drm_free(tmp, sizeof(struct drm_info_node),
-				 _DRM_DRIVER);
+			kfree(tmp);
 			ret = -1;
 			goto fail;
 		}
@@ -196,8 +194,7 @@
 			if (tmp->info_ent == &files[i]) {
 				debugfs_remove(tmp->dent);
 				list_del(pos);
-				drm_free(tmp, sizeof(struct drm_info_node),
-					 _DRM_DRIVER);
+				kfree(tmp);
 			}
 		}
 	}
diff --git a/drivers/gpu/drm/drm_dma.c b/drivers/gpu/drm/drm_dma.c
index 7a8e2fb..13f1537 100644
--- a/drivers/gpu/drm/drm_dma.c
+++ b/drivers/gpu/drm/drm_dma.c
@@ -47,7 +47,7 @@
 {
 	int i;
 
-	dev->dma = drm_alloc(sizeof(*dev->dma), DRM_MEM_DRIVER);
+	dev->dma = kmalloc(sizeof(*dev->dma), GFP_KERNEL);
 	if (!dev->dma)
 		return -ENOMEM;
 
@@ -88,36 +88,19 @@
 					drm_pci_free(dev, dma->bufs[i].seglist[j]);
 				}
 			}
-			drm_free(dma->bufs[i].seglist,
-				 dma->bufs[i].seg_count
-				 * sizeof(*dma->bufs[0].seglist), DRM_MEM_SEGS);
+			kfree(dma->bufs[i].seglist);
 		}
 		if (dma->bufs[i].buf_count) {
 			for (j = 0; j < dma->bufs[i].buf_count; j++) {
-				if (dma->bufs[i].buflist[j].dev_private) {
-					drm_free(dma->bufs[i].buflist[j].
-						 dev_private,
-						 dma->bufs[i].buflist[j].
-						 dev_priv_size, DRM_MEM_BUFS);
-				}
+				kfree(dma->bufs[i].buflist[j].dev_private);
 			}
-			drm_free(dma->bufs[i].buflist,
-				 dma->bufs[i].buf_count *
-				 sizeof(*dma->bufs[0].buflist), DRM_MEM_BUFS);
+			kfree(dma->bufs[i].buflist);
 		}
 	}
 
-	if (dma->buflist) {
-		drm_free(dma->buflist,
-			 dma->buf_count * sizeof(*dma->buflist), DRM_MEM_BUFS);
-	}
-
-	if (dma->pagelist) {
-		drm_free(dma->pagelist,
-			 dma->page_count * sizeof(*dma->pagelist),
-			 DRM_MEM_PAGES);
-	}
-	drm_free(dev->dma, sizeof(*dev->dma), DRM_MEM_DRIVER);
+	kfree(dma->buflist);
+	kfree(dma->pagelist);
+	kfree(dev->dma);
 	dev->dma = NULL;
 }
 
diff --git a/drivers/gpu/drm/drm_drawable.c b/drivers/gpu/drm/drm_drawable.c
index 80be1ca..c53c976 100644
--- a/drivers/gpu/drm/drm_drawable.c
+++ b/drivers/gpu/drm/drm_drawable.c
@@ -85,9 +85,8 @@
 		spin_unlock_irqrestore(&dev->drw_lock, irqflags);
 		return -EINVAL;
 	}
-	drm_free(info->rects, info->num_rects * sizeof(struct drm_clip_rect),
-			DRM_MEM_BUFS);
-	drm_free(info, sizeof(struct drm_drawable_info), DRM_MEM_BUFS);
+	kfree(info->rects);
+	kfree(info);
 
 	idr_remove(&dev->drw_idr, draw->handle);
 
@@ -106,12 +105,12 @@
 
 	info = idr_find(&dev->drw_idr, update->handle);
 	if (!info) {
-		info = drm_calloc(1, sizeof(*info), DRM_MEM_BUFS);
+		info = kzalloc(sizeof(*info), GFP_KERNEL);
 		if (!info)
 			return -ENOMEM;
 		if (IS_ERR(idr_replace(&dev->drw_idr, info, update->handle))) {
 			DRM_ERROR("No such drawable %d\n", update->handle);
-			drm_free(info, sizeof(*info), DRM_MEM_BUFS);
+			kfree(info);
 			return -EINVAL;
 		}
 	}
@@ -121,8 +120,9 @@
 		if (update->num == 0)
 			rects = NULL;
 		else if (update->num != info->num_rects) {
-			rects = drm_alloc(update->num * sizeof(struct drm_clip_rect),
-					 DRM_MEM_BUFS);
+			rects = kmalloc(update->num *
+					sizeof(struct drm_clip_rect),
+					GFP_KERNEL);
 		} else
 			rects = info->rects;
 
@@ -145,8 +145,7 @@
 		spin_lock_irqsave(&dev->drw_lock, irqflags);
 
 		if (rects != info->rects) {
-			drm_free(info->rects, info->num_rects *
-				 sizeof(struct drm_clip_rect), DRM_MEM_BUFS);
+			kfree(info->rects);
 		}
 
 		info->rects = rects;
@@ -166,8 +165,7 @@
 
 error:
 	if (rects != info->rects)
-		drm_free(rects, update->num * sizeof(struct drm_clip_rect),
-			 DRM_MEM_BUFS);
+		kfree(rects);
 
 	return err;
 }
@@ -186,9 +184,8 @@
 	struct drm_drawable_info *info = p;
 
 	if (info) {
-		drm_free(info->rects, info->num_rects *
-			 sizeof(struct drm_clip_rect), DRM_MEM_BUFS);
-		drm_free(info, sizeof(*info), DRM_MEM_BUFS);
+		kfree(info->rects);
+		kfree(info);
 	}
 
 	return 0;
diff --git a/drivers/gpu/drm/drm_drv.c b/drivers/gpu/drm/drm_drv.c
index 1bf7efd..b39d7bf 100644
--- a/drivers/gpu/drm/drm_drv.c
+++ b/drivers/gpu/drm/drm_drv.c
@@ -189,7 +189,7 @@
 			if (entry->bound)
 				drm_unbind_agp(entry->memory);
 			drm_free_agp(entry->memory, entry->pages);
-			drm_free(entry, sizeof(*entry), DRM_MEM_AGPLISTS);
+			kfree(entry);
 		}
 		INIT_LIST_HEAD(&dev->agp->memory);
 
@@ -208,21 +208,15 @@
 	/* Clear vma list (only built for debugging) */
 	list_for_each_entry_safe(vma, vma_temp, &dev->vmalist, head) {
 		list_del(&vma->head);
-		drm_free(vma, sizeof(*vma), DRM_MEM_VMAS);
+		kfree(vma);
 	}
 
 	if (drm_core_check_feature(dev, DRIVER_DMA_QUEUE) && dev->queuelist) {
 		for (i = 0; i < dev->queue_count; i++) {
-			if (dev->queuelist[i]) {
-				drm_free(dev->queuelist[i],
-					 sizeof(*dev->queuelist[0]),
-					 DRM_MEM_QUEUES);
-				dev->queuelist[i] = NULL;
-			}
+			kfree(dev->queuelist[i]);
+			dev->queuelist[i] = NULL;
 		}
-		drm_free(dev->queuelist,
-			 dev->queue_slots * sizeof(*dev->queuelist),
-			 DRM_MEM_QUEUES);
+		kfree(dev->queuelist);
 		dev->queuelist = NULL;
 	}
 	dev->queue_count = 0;
@@ -344,8 +338,6 @@
 		goto err_p3;
 	}
 
-	drm_mem_init();
-
 	DRM_INFO("Initialized %s %d.%d.%d %s\n",
 		 CORE_NAME, CORE_MAJOR, CORE_MINOR, CORE_PATCHLEVEL, CORE_DATE);
 	return 0;
diff --git a/drivers/gpu/drm/drm_edid.c b/drivers/gpu/drm/drm_edid.c
index 801a0d0..7d08352 100644
--- a/drivers/gpu/drm/drm_edid.c
+++ b/drivers/gpu/drm/drm_edid.c
@@ -252,16 +252,18 @@
 {
 	struct drm_display_mode *mode;
 	int hsize = t->hsize * 8 + 248, vsize;
+	unsigned aspect_ratio = (t->vfreq_aspect & EDID_TIMING_ASPECT_MASK)
+		>> EDID_TIMING_ASPECT_SHIFT;
 
 	mode = drm_mode_create(dev);
 	if (!mode)
 		return NULL;
 
-	if (t->aspect_ratio == 0)
+	if (aspect_ratio == 0)
 		vsize = (hsize * 10) / 16;
-	else if (t->aspect_ratio == 1)
+	else if (aspect_ratio == 1)
 		vsize = (hsize * 3) / 4;
-	else if (t->aspect_ratio == 2)
+	else if (aspect_ratio == 2)
 		vsize = (hsize * 4) / 5;
 	else
 		vsize = (hsize * 9) / 16;
@@ -288,17 +290,24 @@
 {
 	struct drm_display_mode *mode;
 	struct detailed_pixel_timing *pt = &timing->data.pixel_data;
+	unsigned hactive = (pt->hactive_hblank_hi & 0xf0) << 4 | pt->hactive_lo;
+	unsigned vactive = (pt->vactive_vblank_hi & 0xf0) << 4 | pt->vactive_lo;
+	unsigned hblank = (pt->hactive_hblank_hi & 0xf) << 8 | pt->hblank_lo;
+	unsigned vblank = (pt->vactive_vblank_hi & 0xf) << 8 | pt->vblank_lo;
+	unsigned hsync_offset = (pt->hsync_vsync_offset_pulse_width_hi & 0x3) << 8 | pt->hsync_offset_lo;
+	unsigned hsync_pulse_width = (pt->hsync_vsync_offset_pulse_width_hi & 0xc) << 6 | pt->hsync_pulse_width_lo;
+	unsigned vsync_offset = (pt->hsync_vsync_offset_pulse_width_hi & 0x30) | (pt->vsync_offset_pulse_width_lo & 0xf);
+	unsigned vsync_pulse_width = (pt->hsync_vsync_offset_pulse_width_hi & 0xc0) >> 2 | pt->vsync_offset_pulse_width_lo >> 4;
 
 	/* ignore tiny modes */
-	if (((pt->hactive_hi << 8) | pt->hactive_lo) < 64 ||
-	    ((pt->vactive_hi << 8) | pt->hactive_lo) < 64)
+	if (hactive < 64 || vactive < 64)
 		return NULL;
 
-	if (pt->stereo) {
+	if (pt->misc & DRM_EDID_PT_STEREO) {
 		printk(KERN_WARNING "stereo mode not supported\n");
 		return NULL;
 	}
-	if (!pt->separate_sync) {
+	if (!(pt->misc & DRM_EDID_PT_SEPARATE_SYNC)) {
 		printk(KERN_WARNING "integrated sync not supported\n");
 		return NULL;
 	}
@@ -310,41 +319,36 @@
 	mode->type = DRM_MODE_TYPE_DRIVER;
 
 	if (quirks & EDID_QUIRK_135_CLOCK_TOO_HIGH)
-		timing->pixel_clock = 1088;
+		timing->pixel_clock = cpu_to_le16(1088);
 
-	mode->clock = timing->pixel_clock * 10;
+	mode->clock = le16_to_cpu(timing->pixel_clock) * 10;
 
-	mode->hdisplay = (pt->hactive_hi << 8) | pt->hactive_lo;
-	mode->hsync_start = mode->hdisplay + ((pt->hsync_offset_hi << 8) |
-					      pt->hsync_offset_lo);
-	mode->hsync_end = mode->hsync_start +
-		((pt->hsync_pulse_width_hi << 8) |
-		 pt->hsync_pulse_width_lo);
-	mode->htotal = mode->hdisplay + ((pt->hblank_hi << 8) | pt->hblank_lo);
+	mode->hdisplay = hactive;
+	mode->hsync_start = mode->hdisplay + hsync_offset;
+	mode->hsync_end = mode->hsync_start + hsync_pulse_width;
+	mode->htotal = mode->hdisplay + hblank;
 
-	mode->vdisplay = (pt->vactive_hi << 8) | pt->vactive_lo;
-	mode->vsync_start = mode->vdisplay + ((pt->vsync_offset_hi << 4) |
-					      pt->vsync_offset_lo);
-	mode->vsync_end = mode->vsync_start +
-		((pt->vsync_pulse_width_hi << 4) |
-		 pt->vsync_pulse_width_lo);
-	mode->vtotal = mode->vdisplay + ((pt->vblank_hi << 8) | pt->vblank_lo);
+	mode->vdisplay = vactive;
+	mode->vsync_start = mode->vdisplay + vsync_offset;
+	mode->vsync_end = mode->vsync_start + vsync_pulse_width;
+	mode->vtotal = mode->vdisplay + vblank;
 
 	drm_mode_set_name(mode);
 
-	if (pt->interlaced)
+	if (pt->misc & DRM_EDID_PT_INTERLACED)
 		mode->flags |= DRM_MODE_FLAG_INTERLACE;
 
 	if (quirks & EDID_QUIRK_DETAILED_SYNC_PP) {
-		pt->hsync_positive = 1;
-		pt->vsync_positive = 1;
+		pt->misc |= DRM_EDID_PT_HSYNC_POSITIVE | DRM_EDID_PT_VSYNC_POSITIVE;
 	}
 
-	mode->flags |= pt->hsync_positive ? DRM_MODE_FLAG_PHSYNC : DRM_MODE_FLAG_NHSYNC;
-	mode->flags |= pt->vsync_positive ? DRM_MODE_FLAG_PVSYNC : DRM_MODE_FLAG_NVSYNC;
+	mode->flags |= (pt->misc & DRM_EDID_PT_HSYNC_POSITIVE) ?
+		DRM_MODE_FLAG_PHSYNC : DRM_MODE_FLAG_NHSYNC;
+	mode->flags |= (pt->misc & DRM_EDID_PT_VSYNC_POSITIVE) ?
+		DRM_MODE_FLAG_PVSYNC : DRM_MODE_FLAG_NVSYNC;
 
-	mode->width_mm = pt->width_mm_lo | (pt->width_mm_hi << 8);
-	mode->height_mm = pt->height_mm_lo | (pt->height_mm_hi << 8);
+	mode->width_mm = pt->width_mm_lo | (pt->width_height_mm_hi & 0xf) << 8;
+	mode->height_mm = pt->height_mm_lo | (pt->width_height_mm_hi & 0xf0) << 4;
 
 	if (quirks & EDID_QUIRK_DETAILED_IN_CM) {
 		mode->width_mm *= 10;
@@ -465,7 +469,7 @@
 		struct drm_display_mode *newmode;
 
 		/* If std timings bytes are 1, 1 it's empty */
-		if (t->hsize == 1 && (t->aspect_ratio | t->vfreq) == 1)
+		if (t->hsize == 1 && t->vfreq_aspect == 1)
 			continue;
 
 		newmode = drm_mode_std(dev, &edid->standard_timings[i]);
@@ -509,7 +513,7 @@
 				continue;
 
 			/* First detailed mode is preferred */
-			if (i == 0 && edid->preferred_timing)
+			if (i == 0 && (edid->features & DRM_EDID_FEATURE_PREFERRED_TIMING))
 				newmode->type |= DRM_MODE_TYPE_PREFERRED;
 			drm_mode_probed_add(connector, newmode);
 
@@ -767,22 +771,22 @@
 	if (quirks & (EDID_QUIRK_PREFER_LARGE_60 | EDID_QUIRK_PREFER_LARGE_75))
 		edid_fixup_preferred(connector, quirks);
 
-	connector->display_info.serration_vsync = edid->serration_vsync;
-	connector->display_info.sync_on_green = edid->sync_on_green;
-	connector->display_info.composite_sync = edid->composite_sync;
-	connector->display_info.separate_syncs = edid->separate_syncs;
-	connector->display_info.blank_to_black = edid->blank_to_black;
-	connector->display_info.video_level = edid->video_level;
-	connector->display_info.digital = edid->digital;
+	connector->display_info.serration_vsync = (edid->input & DRM_EDID_INPUT_SERRATION_VSYNC) ? 1 : 0;
+	connector->display_info.sync_on_green = (edid->input & DRM_EDID_INPUT_SYNC_ON_GREEN) ? 1 : 0;
+	connector->display_info.composite_sync = (edid->input & DRM_EDID_INPUT_COMPOSITE_SYNC) ? 1 : 0;
+	connector->display_info.separate_syncs = (edid->input & DRM_EDID_INPUT_SEPARATE_SYNCS) ? 1 : 0;
+	connector->display_info.blank_to_black = (edid->input & DRM_EDID_INPUT_BLANK_TO_BLACK) ? 1 : 0;
+	connector->display_info.video_level = (edid->input & DRM_EDID_INPUT_VIDEO_LEVEL) >> 5;
+	connector->display_info.digital = (edid->input & DRM_EDID_INPUT_DIGITAL) ? 1 : 0;
 	connector->display_info.width_mm = edid->width_cm * 10;
 	connector->display_info.height_mm = edid->height_cm * 10;
 	connector->display_info.gamma = edid->gamma;
-	connector->display_info.gtf_supported = edid->default_gtf;
-	connector->display_info.standard_color = edid->standard_color;
-	connector->display_info.display_type = edid->display_type;
-	connector->display_info.active_off_supported = edid->pm_active_off;
-	connector->display_info.suspend_supported = edid->pm_suspend;
-	connector->display_info.standby_supported = edid->pm_standby;
+	connector->display_info.gtf_supported = (edid->features & DRM_EDID_FEATURE_DEFAULT_GTF) ? 1 : 0;
+	connector->display_info.standard_color = (edid->features & DRM_EDID_FEATURE_STANDARD_COLOR) ? 1 : 0;
+	connector->display_info.display_type = (edid->features & DRM_EDID_FEATURE_DISPLAY_TYPE) >> 3;
+	connector->display_info.active_off_supported = (edid->features & DRM_EDID_FEATURE_PM_ACTIVE_OFF) ? 1 : 0;
+	connector->display_info.suspend_supported = (edid->features & DRM_EDID_FEATURE_PM_SUSPEND) ? 1 : 0;
+	connector->display_info.standby_supported = (edid->features & DRM_EDID_FEATURE_PM_STANDBY) ? 1 : 0;
 	connector->display_info.gamma = edid->gamma;
 
 	return num_modes;
diff --git a/drivers/gpu/drm/drm_fops.c b/drivers/gpu/drm/drm_fops.c
index 09a3571..251bc0e 100644
--- a/drivers/gpu/drm/drm_fops.c
+++ b/drivers/gpu/drm/drm_fops.c
@@ -240,7 +240,7 @@
 
 	DRM_DEBUG("pid = %d, minor = %d\n", task_pid_nr(current), minor_id);
 
-	priv = drm_alloc(sizeof(*priv), DRM_MEM_FILES);
+	priv = kmalloc(sizeof(*priv), GFP_KERNEL);
 	if (!priv)
 		return -ENOMEM;
 
@@ -328,7 +328,7 @@
 
 	return 0;
       out_free:
-	drm_free(priv, sizeof(*priv), DRM_MEM_FILES);
+	kfree(priv);
 	filp->private_data = NULL;
 	return ret;
 }
@@ -471,7 +471,7 @@
 				drm_ctxbitmap_free(dev, pos->handle);
 
 				list_del(&pos->head);
-				drm_free(pos, sizeof(*pos), DRM_MEM_CTXLIST);
+				kfree(pos);
 				--dev->ctx_count;
 			}
 		}
@@ -516,7 +516,7 @@
 
 	if (dev->driver->postclose)
 		dev->driver->postclose(dev, file_priv);
-	drm_free(file_priv, sizeof(*file_priv), DRM_MEM_FILES);
+	kfree(file_priv);
 
 	/* ========================================================
 	 * End inline drm_release
diff --git a/drivers/gpu/drm/drm_gem.c b/drivers/gpu/drm/drm_gem.c
index ec43005..8104eca 100644
--- a/drivers/gpu/drm/drm_gem.c
+++ b/drivers/gpu/drm/drm_gem.c
@@ -89,7 +89,7 @@
 	atomic_set(&dev->gtt_count, 0);
 	atomic_set(&dev->gtt_memory, 0);
 
-	mm = drm_calloc(1, sizeof(struct drm_gem_mm), DRM_MEM_MM);
+	mm = kzalloc(sizeof(struct drm_gem_mm), GFP_KERNEL);
 	if (!mm) {
 		DRM_ERROR("out of memory\n");
 		return -ENOMEM;
@@ -98,14 +98,14 @@
 	dev->mm_private = mm;
 
 	if (drm_ht_create(&mm->offset_hash, 19)) {
-		drm_free(mm, sizeof(struct drm_gem_mm), DRM_MEM_MM);
+		kfree(mm);
 		return -ENOMEM;
 	}
 
 	if (drm_mm_init(&mm->offset_manager, DRM_FILE_PAGE_OFFSET_START,
 			DRM_FILE_PAGE_OFFSET_SIZE)) {
 		drm_ht_remove(&mm->offset_hash);
-		drm_free(mm, sizeof(struct drm_gem_mm), DRM_MEM_MM);
+		kfree(mm);
 		return -ENOMEM;
 	}
 
@@ -119,7 +119,7 @@
 
 	drm_mm_takedown(&mm->offset_manager);
 	drm_ht_remove(&mm->offset_hash);
-	drm_free(mm, sizeof(struct drm_gem_mm), DRM_MEM_MM);
+	kfree(mm);
 	dev->mm_private = NULL;
 }
 
diff --git a/drivers/gpu/drm/drm_hashtab.c b/drivers/gpu/drm/drm_hashtab.c
index ac35145..f36b21c 100644
--- a/drivers/gpu/drm/drm_hashtab.c
+++ b/drivers/gpu/drm/drm_hashtab.c
@@ -46,8 +46,7 @@
 	ht->table = NULL;
 	ht->use_vmalloc = ((ht->size * sizeof(*ht->table)) > PAGE_SIZE);
 	if (!ht->use_vmalloc) {
-		ht->table = drm_calloc(ht->size, sizeof(*ht->table),
-				       DRM_MEM_HASHTAB);
+		ht->table = kcalloc(ht->size, sizeof(*ht->table), GFP_KERNEL);
 	}
 	if (!ht->table) {
 		ht->use_vmalloc = 1;
@@ -200,8 +199,7 @@
 		if (ht->use_vmalloc)
 			vfree(ht->table);
 		else
-			drm_free(ht->table, ht->size * sizeof(*ht->table),
-				 DRM_MEM_HASHTAB);
+			kfree(ht->table);
 		ht->table = NULL;
 	}
 }
diff --git a/drivers/gpu/drm/drm_ioctl.c b/drivers/gpu/drm/drm_ioctl.c
index 1fad762..9b9ff46 100644
--- a/drivers/gpu/drm/drm_ioctl.c
+++ b/drivers/gpu/drm/drm_ioctl.c
@@ -93,7 +93,7 @@
 
 	master->unique_len = u->unique_len;
 	master->unique_size = u->unique_len + 1;
-	master->unique = drm_alloc(master->unique_size, DRM_MEM_DRIVER);
+	master->unique = kmalloc(master->unique_size, GFP_KERNEL);
 	if (!master->unique)
 		return -ENOMEM;
 	if (copy_from_user(master->unique, u->unique, master->unique_len))
@@ -101,9 +101,8 @@
 
 	master->unique[master->unique_len] = '\0';
 
-	dev->devname =
-	    drm_alloc(strlen(dev->driver->pci_driver.name) +
-		      strlen(master->unique) + 2, DRM_MEM_DRIVER);
+	dev->devname = kmalloc(strlen(dev->driver->pci_driver.name) +
+			       strlen(master->unique) + 2, GFP_KERNEL);
 	if (!dev->devname)
 		return -ENOMEM;
 
@@ -138,7 +137,7 @@
 
 	master->unique_len = 40;
 	master->unique_size = master->unique_len;
-	master->unique = drm_alloc(master->unique_size, DRM_MEM_DRIVER);
+	master->unique = kmalloc(master->unique_size, GFP_KERNEL);
 	if (master->unique == NULL)
 		return -ENOMEM;
 
@@ -152,9 +151,8 @@
 	else
 		master->unique_len = len;
 
-	dev->devname =
-	    drm_alloc(strlen(dev->driver->pci_driver.name) + master->unique_len +
-		      2, DRM_MEM_DRIVER);
+	dev->devname = kmalloc(strlen(dev->driver->pci_driver.name) +
+			       master->unique_len + 2, GFP_KERNEL);
 	if (dev->devname == NULL)
 		return -ENOMEM;
 
diff --git a/drivers/gpu/drm/drm_irq.c b/drivers/gpu/drm/drm_irq.c
index fc8e5ac..b4a3dbc 100644
--- a/drivers/gpu/drm/drm_irq.c
+++ b/drivers/gpu/drm/drm_irq.c
@@ -104,21 +104,13 @@
 
 	vblank_disable_fn((unsigned long)dev);
 
-	drm_free(dev->vbl_queue, sizeof(*dev->vbl_queue) * dev->num_crtcs,
-		 DRM_MEM_DRIVER);
-	drm_free(dev->_vblank_count, sizeof(*dev->_vblank_count) *
-		 dev->num_crtcs, DRM_MEM_DRIVER);
-	drm_free(dev->vblank_refcount, sizeof(*dev->vblank_refcount) *
-		 dev->num_crtcs, DRM_MEM_DRIVER);
-	drm_free(dev->vblank_enabled, sizeof(*dev->vblank_enabled) *
-		 dev->num_crtcs, DRM_MEM_DRIVER);
-	drm_free(dev->last_vblank, sizeof(*dev->last_vblank) * dev->num_crtcs,
-		 DRM_MEM_DRIVER);
-	drm_free(dev->last_vblank_wait,
-		 sizeof(*dev->last_vblank_wait) * dev->num_crtcs,
-		 DRM_MEM_DRIVER);
-	drm_free(dev->vblank_inmodeset, sizeof(*dev->vblank_inmodeset) *
-		 dev->num_crtcs, DRM_MEM_DRIVER);
+	kfree(dev->vbl_queue);
+	kfree(dev->_vblank_count);
+	kfree(dev->vblank_refcount);
+	kfree(dev->vblank_enabled);
+	kfree(dev->last_vblank);
+	kfree(dev->last_vblank_wait);
+	kfree(dev->vblank_inmodeset);
 
 	dev->num_crtcs = 0;
 }
@@ -132,37 +124,33 @@
 	spin_lock_init(&dev->vbl_lock);
 	dev->num_crtcs = num_crtcs;
 
-	dev->vbl_queue = drm_alloc(sizeof(wait_queue_head_t) * num_crtcs,
-				   DRM_MEM_DRIVER);
+	dev->vbl_queue = kmalloc(sizeof(wait_queue_head_t) * num_crtcs,
+				 GFP_KERNEL);
 	if (!dev->vbl_queue)
 		goto err;
 
-	dev->_vblank_count = drm_alloc(sizeof(atomic_t) * num_crtcs,
-				      DRM_MEM_DRIVER);
+	dev->_vblank_count = kmalloc(sizeof(atomic_t) * num_crtcs, GFP_KERNEL);
 	if (!dev->_vblank_count)
 		goto err;
 
-	dev->vblank_refcount = drm_alloc(sizeof(atomic_t) * num_crtcs,
-					 DRM_MEM_DRIVER);
+	dev->vblank_refcount = kmalloc(sizeof(atomic_t) * num_crtcs,
+				       GFP_KERNEL);
 	if (!dev->vblank_refcount)
 		goto err;
 
-	dev->vblank_enabled = drm_calloc(num_crtcs, sizeof(int),
-					 DRM_MEM_DRIVER);
+	dev->vblank_enabled = kcalloc(num_crtcs, sizeof(int), GFP_KERNEL);
 	if (!dev->vblank_enabled)
 		goto err;
 
-	dev->last_vblank = drm_calloc(num_crtcs, sizeof(u32), DRM_MEM_DRIVER);
+	dev->last_vblank = kcalloc(num_crtcs, sizeof(u32), GFP_KERNEL);
 	if (!dev->last_vblank)
 		goto err;
 
-	dev->last_vblank_wait = drm_calloc(num_crtcs, sizeof(u32),
-					   DRM_MEM_DRIVER);
+	dev->last_vblank_wait = kcalloc(num_crtcs, sizeof(u32), GFP_KERNEL);
 	if (!dev->last_vblank_wait)
 		goto err;
 
-	dev->vblank_inmodeset = drm_calloc(num_crtcs, sizeof(int),
-					 DRM_MEM_DRIVER);
+	dev->vblank_inmodeset = kcalloc(num_crtcs, sizeof(int), GFP_KERNEL);
 	if (!dev->vblank_inmodeset)
 		goto err;
 
diff --git a/drivers/gpu/drm/drm_memory.c b/drivers/gpu/drm/drm_memory.c
index 0c707f5..e4865f9 100644
--- a/drivers/gpu/drm/drm_memory.c
+++ b/drivers/gpu/drm/drm_memory.c
@@ -36,15 +36,6 @@
 #include <linux/highmem.h>
 #include "drmP.h"
 
-#ifdef DEBUG_MEMORY
-#include "drm_memory_debug.h"
-#else
-
-/** No-op. */
-void drm_mem_init(void)
-{
-}
-
 /**
  * Called when "/proc/dri/%dev%/mem" is read.
  *
@@ -64,28 +55,15 @@
 	return 0;
 }
 
-/** Wrapper around kmalloc() and kfree() */
-void *drm_realloc(void *oldpt, size_t oldsize, size_t size, int area)
-{
-	void *pt;
-
-	if (!(pt = kmalloc(size, GFP_KERNEL)))
-		return NULL;
-	if (oldpt && oldsize) {
-		memcpy(pt, oldpt, oldsize);
-		kfree(oldpt);
-	}
-	return pt;
-}
-
 #if __OS_HAS_AGP
 static void *agp_remap(unsigned long offset, unsigned long size,
 		       struct drm_device * dev)
 {
-	unsigned long *phys_addr_map, i, num_pages =
+	unsigned long i, num_pages =
 	    PAGE_ALIGN(size) / PAGE_SIZE;
 	struct drm_agp_mem *agpmem;
 	struct page **page_map;
+	struct page **phys_page_map;
 	void *addr;
 
 	size = PAGE_ALIGN(size);
@@ -112,10 +90,9 @@
 	if (!page_map)
 		return NULL;
 
-	phys_addr_map =
-	    agpmem->memory->memory + (offset - agpmem->bound) / PAGE_SIZE;
+	phys_page_map = (agpmem->memory->pages + (offset - agpmem->bound) / PAGE_SIZE);
 	for (i = 0; i < num_pages; ++i)
-		page_map[i] = pfn_to_page(phys_addr_map[i] >> PAGE_SHIFT);
+		page_map[i] = phys_page_map[i];
 	addr = vmap(page_map, num_pages, VM_IOREMAP, PAGE_AGP);
 	vfree(page_map);
 
@@ -157,8 +134,6 @@
 
 #endif				/* agp */
 
-#endif				/* debug_memory */
-
 void drm_core_ioremap(struct drm_local_map *map, struct drm_device *dev)
 {
 	if (drm_core_has_AGP(dev) &&
diff --git a/drivers/gpu/drm/drm_mm.c b/drivers/gpu/drm/drm_mm.c
index a912a0f..3e47869 100644
--- a/drivers/gpu/drm/drm_mm.c
+++ b/drivers/gpu/drm/drm_mm.c
@@ -187,9 +187,10 @@
 }
 
 
-
-struct drm_mm_node *drm_mm_get_block(struct drm_mm_node *node,
-				     unsigned long size, unsigned alignment)
+struct drm_mm_node *drm_mm_get_block_generic(struct drm_mm_node *node,
+					     unsigned long size,
+					     unsigned alignment,
+					     int atomic)
 {
 
 	struct drm_mm_node *align_splitoff = NULL;
@@ -200,7 +201,7 @@
 
 	if (tmp) {
 		align_splitoff =
-		    drm_mm_split_at_start(node, alignment - tmp, 0);
+		    drm_mm_split_at_start(node, alignment - tmp, atomic);
 		if (unlikely(align_splitoff == NULL))
 			return NULL;
 	}
@@ -209,7 +210,7 @@
 		list_del_init(&node->fl_entry);
 		node->free = 0;
 	} else {
-		node = drm_mm_split_at_start(node, size, 0);
+		node = drm_mm_split_at_start(node, size, atomic);
 	}
 
 	if (align_splitoff)
@@ -217,42 +218,7 @@
 
 	return node;
 }
-
-EXPORT_SYMBOL(drm_mm_get_block);
-
-struct drm_mm_node *drm_mm_get_block_atomic(struct drm_mm_node *parent,
-					    unsigned long size,
-					    unsigned alignment)
-{
-
-	struct drm_mm_node *align_splitoff = NULL;
-	struct drm_mm_node *child;
-	unsigned tmp = 0;
-
-	if (alignment)
-		tmp = parent->start % alignment;
-
-	if (tmp) {
-		align_splitoff =
-		    drm_mm_split_at_start(parent, alignment - tmp, 1);
-		if (unlikely(align_splitoff == NULL))
-			return NULL;
-	}
-
-	if (parent->size == size) {
-		list_del_init(&parent->fl_entry);
-		parent->free = 0;
-		return parent;
-	} else {
-		child = drm_mm_split_at_start(parent, size, 1);
-	}
-
-	if (align_splitoff)
-		drm_mm_put_block(align_splitoff);
-
-	return child;
-}
-EXPORT_SYMBOL(drm_mm_get_block_atomic);
+EXPORT_SYMBOL(drm_mm_get_block_generic);
 
 /*
  * Put a block. Merge with the previous and / or next block if they are free.
diff --git a/drivers/gpu/drm/drm_pci.c b/drivers/gpu/drm/drm_pci.c
index b55d5bc..577094f 100644
--- a/drivers/gpu/drm/drm_pci.c
+++ b/drivers/gpu/drm/drm_pci.c
@@ -55,17 +55,6 @@
 	unsigned long addr;
 	size_t sz;
 #endif
-#ifdef DRM_DEBUG_MEMORY
-	int area = DRM_MEM_DMA;
-
-	spin_lock(&drm_mem_lock);
-	if ((drm_ram_used >> PAGE_SHIFT)
-	    > (DRM_RAM_PERCENT * drm_ram_available) / 100) {
-		spin_unlock(&drm_mem_lock);
-		return 0;
-	}
-	spin_unlock(&drm_mem_lock);
-#endif
 
 	/* pci_alloc_consistent only guarantees alignment to the smallest
 	 * PAGE_SIZE order which is greater than or equal to the requested size.
@@ -86,26 +75,10 @@
 	dmah->size = size;
 	dmah->vaddr = dma_alloc_coherent(&dev->pdev->dev, size, &dmah->busaddr, GFP_KERNEL | __GFP_COMP);
 
-#ifdef DRM_DEBUG_MEMORY
-	if (dmah->vaddr == NULL) {
-		spin_lock(&drm_mem_lock);
-		++drm_mem_stats[area].fail_count;
-		spin_unlock(&drm_mem_lock);
-		kfree(dmah);
-		return NULL;
-	}
-
-	spin_lock(&drm_mem_lock);
-	++drm_mem_stats[area].succeed_count;
-	drm_mem_stats[area].bytes_allocated += size;
-	drm_ram_used += size;
-	spin_unlock(&drm_mem_lock);
-#else
 	if (dmah->vaddr == NULL) {
 		kfree(dmah);
 		return NULL;
 	}
-#endif
 
 	memset(dmah->vaddr, 0, size);
 
@@ -132,17 +105,8 @@
 	unsigned long addr;
 	size_t sz;
 #endif
-#ifdef DRM_DEBUG_MEMORY
-	int area = DRM_MEM_DMA;
-	int alloc_count;
-	int free_count;
-#endif
 
-	if (!dmah->vaddr) {
-#ifdef DRM_DEBUG_MEMORY
-		DRM_MEM_ERROR(area, "Attempt to free address 0\n");
-#endif
-	} else {
+	if (dmah->vaddr) {
 		/* XXX - Is virt_to_page() legal for consistent mem? */
 		/* Unreserve */
 		for (addr = (unsigned long)dmah->vaddr, sz = dmah->size;
@@ -152,21 +116,6 @@
 		dma_free_coherent(&dev->pdev->dev, dmah->size, dmah->vaddr,
 				  dmah->busaddr);
 	}
-
-#ifdef DRM_DEBUG_MEMORY
-	spin_lock(&drm_mem_lock);
-	free_count = ++drm_mem_stats[area].free_count;
-	alloc_count = drm_mem_stats[area].succeed_count;
-	drm_mem_stats[area].bytes_freed += size;
-	drm_ram_used -= size;
-	spin_unlock(&drm_mem_lock);
-	if (free_count > alloc_count) {
-		DRM_MEM_ERROR(area,
-			      "Excess frees: %d frees, %d allocs\n",
-			      free_count, alloc_count);
-	}
-#endif
-
 }
 
 /**
diff --git a/drivers/gpu/drm/drm_proc.c b/drivers/gpu/drm/drm_proc.c
index bae5391..bbd4b3d 100644
--- a/drivers/gpu/drm/drm_proc.c
+++ b/drivers/gpu/drm/drm_proc.c
@@ -105,13 +105,12 @@
 		    (dev->driver->driver_features & features) != features)
 			continue;
 
-		tmp = drm_alloc(sizeof(struct drm_info_node), _DRM_DRIVER);
+		tmp = kmalloc(sizeof(struct drm_info_node), GFP_KERNEL);
 		ent = create_proc_entry(files[i].name, S_IFREG | S_IRUGO, root);
 		if (!ent) {
 			DRM_ERROR("Cannot create /proc/dri/%s/%s\n",
 				  name, files[i].name);
-			drm_free(tmp, sizeof(struct drm_info_node),
-				 _DRM_DRIVER);
+			kfree(tmp);
 			ret = -1;
 			goto fail;
 		}
@@ -192,8 +191,7 @@
 				remove_proc_entry(files[i].name,
 						  minor->proc_root);
 				list_del(pos);
-				drm_free(tmp, sizeof(struct drm_info_node),
-					 _DRM_DRIVER);
+				kfree(tmp);
 			}
 		}
 	}
diff --git a/drivers/gpu/drm/drm_scatter.c b/drivers/gpu/drm/drm_scatter.c
index b2b0f3d..c7823c8 100644
--- a/drivers/gpu/drm/drm_scatter.c
+++ b/drivers/gpu/drm/drm_scatter.c
@@ -58,11 +58,9 @@
 
 	vfree(entry->virtual);
 
-	drm_free(entry->busaddr,
-		 entry->pages * sizeof(*entry->busaddr), DRM_MEM_PAGES);
-	drm_free(entry->pagelist,
-		 entry->pages * sizeof(*entry->pagelist), DRM_MEM_PAGES);
-	drm_free(entry, sizeof(*entry), DRM_MEM_SGLISTS);
+	kfree(entry->busaddr);
+	kfree(entry->pagelist);
+	kfree(entry);
 }
 
 #ifdef _LP64
@@ -84,7 +82,7 @@
 	if (dev->sg)
 		return -EINVAL;
 
-	entry = drm_alloc(sizeof(*entry), DRM_MEM_SGLISTS);
+	entry = kmalloc(sizeof(*entry), GFP_KERNEL);
 	if (!entry)
 		return -ENOMEM;
 
@@ -93,34 +91,27 @@
 	DRM_DEBUG("size=%ld pages=%ld\n", request->size, pages);
 
 	entry->pages = pages;
-	entry->pagelist = drm_alloc(pages * sizeof(*entry->pagelist),
-				    DRM_MEM_PAGES);
+	entry->pagelist = kmalloc(pages * sizeof(*entry->pagelist), GFP_KERNEL);
 	if (!entry->pagelist) {
-		drm_free(entry, sizeof(*entry), DRM_MEM_SGLISTS);
+		kfree(entry);
 		return -ENOMEM;
 	}
 
 	memset(entry->pagelist, 0, pages * sizeof(*entry->pagelist));
 
-	entry->busaddr = drm_alloc(pages * sizeof(*entry->busaddr),
-				   DRM_MEM_PAGES);
+	entry->busaddr = kmalloc(pages * sizeof(*entry->busaddr), GFP_KERNEL);
 	if (!entry->busaddr) {
-		drm_free(entry->pagelist,
-			 entry->pages * sizeof(*entry->pagelist),
-			 DRM_MEM_PAGES);
-		drm_free(entry, sizeof(*entry), DRM_MEM_SGLISTS);
+		kfree(entry->pagelist);
+		kfree(entry);
 		return -ENOMEM;
 	}
 	memset((void *)entry->busaddr, 0, pages * sizeof(*entry->busaddr));
 
 	entry->virtual = drm_vmalloc_dma(pages << PAGE_SHIFT);
 	if (!entry->virtual) {
-		drm_free(entry->busaddr,
-			 entry->pages * sizeof(*entry->busaddr), DRM_MEM_PAGES);
-		drm_free(entry->pagelist,
-			 entry->pages * sizeof(*entry->pagelist),
-			 DRM_MEM_PAGES);
-		drm_free(entry, sizeof(*entry), DRM_MEM_SGLISTS);
+		kfree(entry->busaddr);
+		kfree(entry->pagelist);
+		kfree(entry);
 		return -ENOMEM;
 	}
 
diff --git a/drivers/gpu/drm/drm_sman.c b/drivers/gpu/drm/drm_sman.c
index 926f146..463aed9 100644
--- a/drivers/gpu/drm/drm_sman.c
+++ b/drivers/gpu/drm/drm_sman.c
@@ -48,9 +48,7 @@
 {
 	drm_ht_remove(&sman->user_hash_tab);
 	drm_ht_remove(&sman->owner_hash_tab);
-	if (sman->mm)
-		drm_free(sman->mm, sman->num_managers * sizeof(*sman->mm),
-			 DRM_MEM_MM);
+	kfree(sman->mm);
 }
 
 EXPORT_SYMBOL(drm_sman_takedown);
@@ -61,8 +59,9 @@
 {
 	int ret = 0;
 
-	sman->mm = (struct drm_sman_mm *) drm_calloc(num_managers, sizeof(*sman->mm),
-						DRM_MEM_MM);
+	sman->mm = (struct drm_sman_mm *) kcalloc(num_managers,
+						  sizeof(*sman->mm),
+						  GFP_KERNEL);
 	if (!sman->mm) {
 		ret = -ENOMEM;
 		goto out;
@@ -78,7 +77,7 @@
 
 	drm_ht_remove(&sman->owner_hash_tab);
 out1:
-	drm_free(sman->mm, num_managers * sizeof(*sman->mm), DRM_MEM_MM);
+	kfree(sman->mm);
 out:
 	return ret;
 }
@@ -110,7 +109,7 @@
 {
 	struct drm_mm *mm = (struct drm_mm *) private;
 	drm_mm_takedown(mm);
-	drm_free(mm, sizeof(*mm), DRM_MEM_MM);
+	kfree(mm);
 }
 
 static unsigned long drm_sman_mm_offset(void *private, void *ref)
@@ -130,7 +129,7 @@
 	BUG_ON(manager >= sman->num_managers);
 
 	sman_mm = &sman->mm[manager];
-	mm = drm_calloc(1, sizeof(*mm), DRM_MEM_MM);
+	mm = kzalloc(sizeof(*mm), GFP_KERNEL);
 	if (!mm) {
 		return -ENOMEM;
 	}
@@ -138,7 +137,7 @@
 	ret = drm_mm_init(mm, start, size);
 
 	if (ret) {
-		drm_free(mm, sizeof(*mm), DRM_MEM_MM);
+		kfree(mm);
 		return ret;
 	}
 
@@ -176,7 +175,7 @@
 				      owner_hash);
 	}
 
-	owner_item = drm_calloc(1, sizeof(*owner_item), DRM_MEM_MM);
+	owner_item = kzalloc(sizeof(*owner_item), GFP_KERNEL);
 	if (!owner_item)
 		goto out;
 
@@ -189,7 +188,7 @@
 	return owner_item;
 
 out1:
-	drm_free(owner_item, sizeof(*owner_item), DRM_MEM_MM);
+	kfree(owner_item);
 out:
 	return NULL;
 }
@@ -212,7 +211,7 @@
 		return NULL;
 	}
 
-	memblock = drm_calloc(1, sizeof(*memblock), DRM_MEM_MM);
+	memblock = kzalloc(sizeof(*memblock), GFP_KERNEL);
 
 	if (!memblock)
 		goto out;
@@ -237,7 +236,7 @@
 out2:
 	drm_ht_remove_item(&sman->user_hash_tab, &memblock->user_hash);
 out1:
-	drm_free(memblock, sizeof(*memblock), DRM_MEM_MM);
+	kfree(memblock);
 out:
 	sman_mm->free(sman_mm->private, tmp);
 
@@ -253,7 +252,7 @@
 	list_del(&item->owner_list);
 	drm_ht_remove_item(&sman->user_hash_tab, &item->user_hash);
 	item->mm->free(item->mm->private, item->mm_info);
-	drm_free(item, sizeof(*item), DRM_MEM_MM);
+	kfree(item);
 }
 
 int drm_sman_free_key(struct drm_sman *sman, unsigned int key)
@@ -277,7 +276,7 @@
 {
 	list_del(&owner_item->sman_list);
 	drm_ht_remove_item(&sman->owner_hash_tab, &owner_item->owner_hash);
-	drm_free(owner_item, sizeof(*owner_item), DRM_MEM_MM);
+	kfree(owner_item);
 }
 
 int drm_sman_owner_clean(struct drm_sman *sman, unsigned long owner)
diff --git a/drivers/gpu/drm/drm_stub.c b/drivers/gpu/drm/drm_stub.c
index 387a8de..155a5bb 100644
--- a/drivers/gpu/drm/drm_stub.c
+++ b/drivers/gpu/drm/drm_stub.c
@@ -107,7 +107,7 @@
 {
 	struct drm_master *master;
 
-	master = drm_calloc(1, sizeof(*master), DRM_MEM_DRIVER);
+	master = kzalloc(sizeof(*master), GFP_KERNEL);
 	if (!master)
 		return NULL;
 
@@ -149,7 +149,7 @@
 	}
 
 	if (master->unique) {
-		drm_free(master->unique, master->unique_size, DRM_MEM_DRIVER);
+		kfree(master->unique);
 		master->unique = NULL;
 		master->unique_len = 0;
 	}
@@ -157,12 +157,12 @@
 	list_for_each_entry_safe(pt, next, &master->magicfree, head) {
 		list_del(&pt->head);
 		drm_ht_remove_item(&master->magiclist, &pt->hash_item);
-		drm_free(pt, sizeof(*pt), DRM_MEM_MAGIC);
+		kfree(pt);
 	}
 
 	drm_ht_remove(&master->magiclist);
 
-	drm_free(master, sizeof(*master), DRM_MEM_DRIVER);
+	kfree(master);
 }
 
 void drm_master_put(struct drm_master **master)
@@ -390,7 +390,7 @@
 
 	DRM_DEBUG("\n");
 
-	dev = drm_calloc(1, sizeof(*dev), DRM_MEM_STUB);
+	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
 	if (!dev)
 		return -ENOMEM;
 
@@ -443,7 +443,7 @@
 err_g2:
 	pci_disable_device(pdev);
 err_g1:
-	drm_free(dev, sizeof(*dev), DRM_MEM_STUB);
+	kfree(dev);
 	return ret;
 }
 EXPORT_SYMBOL(drm_get_dev);
@@ -516,7 +516,7 @@
 		dev->driver->unload(dev);
 
 	if (drm_core_has_AGP(dev) && dev->agp) {
-		drm_free(dev->agp, sizeof(*dev->agp), DRM_MEM_AGPLISTS);
+		kfree(dev->agp);
 		dev->agp = NULL;
 	}
 
@@ -535,10 +535,9 @@
 	drm_put_minor(&dev->primary);
 
 	if (dev->devname) {
-		drm_free(dev->devname, strlen(dev->devname) + 1,
-			 DRM_MEM_DRIVER);
+		kfree(dev->devname);
 		dev->devname = NULL;
 	}
-	drm_free(dev, sizeof(*dev), DRM_MEM_STUB);
+	kfree(dev);
 }
 EXPORT_SYMBOL(drm_put_dev);
diff --git a/drivers/gpu/drm/drm_vm.c b/drivers/gpu/drm/drm_vm.c
index 22f7656..7e1fbe5 100644
--- a/drivers/gpu/drm/drm_vm.c
+++ b/drivers/gpu/drm/drm_vm.c
@@ -144,14 +144,14 @@
 		 * Get the page, inc the use count, and return it
 		 */
 		offset = (baddr - agpmem->bound) >> PAGE_SHIFT;
-		page = virt_to_page(__va(agpmem->memory->memory[offset]));
+		page = agpmem->memory->pages[offset];
 		get_page(page);
 		vmf->page = page;
 
 		DRM_DEBUG
 		    ("baddr = 0x%llx page = 0x%p, offset = 0x%llx, count=%d\n",
 		     (unsigned long long)baddr,
-		     __va(agpmem->memory->memory[offset]),
+		     agpmem->memory->pages[offset],
 		     (unsigned long long)offset,
 		     page_count(page));
 		return 0;
@@ -227,7 +227,7 @@
 			found_maps++;
 		if (pt->vma == vma) {
 			list_del(&pt->head);
-			drm_free(pt, sizeof(*pt), DRM_MEM_VMAS);
+			kfree(pt);
 		}
 	}
 
@@ -273,7 +273,7 @@
 				DRM_ERROR("tried to rmmap GEM object\n");
 				break;
 			}
-			drm_free(map, sizeof(*map), DRM_MEM_MAPS);
+			kfree(map);
 		}
 	}
 	mutex_unlock(&dev->struct_mutex);
@@ -414,7 +414,7 @@
 		  vma->vm_start, vma->vm_end - vma->vm_start);
 	atomic_inc(&dev->vma_count);
 
-	vma_entry = drm_alloc(sizeof(*vma_entry), DRM_MEM_VMAS);
+	vma_entry = kmalloc(sizeof(*vma_entry), GFP_KERNEL);
 	if (vma_entry) {
 		vma_entry->vma = vma;
 		vma_entry->pid = current->pid;
@@ -454,7 +454,7 @@
 	list_for_each_entry_safe(pt, temp, &dev->vmalist, head) {
 		if (pt->vma == vma) {
 			list_del(&pt->head);
-			drm_free(pt, sizeof(*pt), DRM_MEM_VMAS);
+			kfree(pt);
 			break;
 		}
 	}
diff --git a/drivers/gpu/drm/i810/i810_dma.c b/drivers/gpu/drm/i810/i810_dma.c
index e5de8ea..7d1d88c 100644
--- a/drivers/gpu/drm/i810/i810_dma.c
+++ b/drivers/gpu/drm/i810/i810_dma.c
@@ -227,8 +227,7 @@
 			/* Need to rewrite hardware status page */
 			I810_WRITE(0x02080, 0x1ffff000);
 		}
-		drm_free(dev->dev_private, sizeof(drm_i810_private_t),
-			 DRM_MEM_DRIVER);
+		kfree(dev->dev_private);
 		dev->dev_private = NULL;
 
 		for (i = 0; i < dma->buf_count; i++) {
@@ -439,8 +438,7 @@
 	switch (init->func) {
 	case I810_INIT_DMA_1_4:
 		DRM_INFO("Using v1.4 init.\n");
-		dev_priv = drm_alloc(sizeof(drm_i810_private_t),
-				     DRM_MEM_DRIVER);
+		dev_priv = kmalloc(sizeof(drm_i810_private_t), GFP_KERNEL);
 		if (dev_priv == NULL)
 			return -ENOMEM;
 		retcode = i810_dma_initialize(dev, dev_priv, init);
diff --git a/drivers/gpu/drm/i830/i830_dma.c b/drivers/gpu/drm/i830/i830_dma.c
index a86ab30..877bf6c 100644
--- a/drivers/gpu/drm/i830/i830_dma.c
+++ b/drivers/gpu/drm/i830/i830_dma.c
@@ -232,8 +232,7 @@
 			I830_WRITE(0x02080, 0x1ffff000);
 		}
 
-		drm_free(dev->dev_private, sizeof(drm_i830_private_t),
-			 DRM_MEM_DRIVER);
+		kfree(dev->dev_private);
 		dev->dev_private = NULL;
 
 		for (i = 0; i < dma->buf_count; i++) {
@@ -459,8 +458,7 @@
 
 	switch (init->func) {
 	case I830_INIT_DMA:
-		dev_priv = drm_alloc(sizeof(drm_i830_private_t),
-				     DRM_MEM_DRIVER);
+		dev_priv = kmalloc(sizeof(drm_i830_private_t), GFP_KERNEL);
 		if (dev_priv == NULL)
 			return -ENOMEM;
 		retcode = i830_dma_initialize(dev, dev_priv, init);
diff --git a/drivers/gpu/drm/i915/i915_dma.c b/drivers/gpu/drm/i915/i915_dma.c
index 1a60626f..f112c76 100644
--- a/drivers/gpu/drm/i915/i915_dma.c
+++ b/drivers/gpu/drm/i915/i915_dma.c
@@ -643,9 +643,9 @@
 		return -EINVAL;
 
 	if (batch->num_cliprects) {
-		cliprects = drm_calloc(batch->num_cliprects,
-				       sizeof(struct drm_clip_rect),
-				       DRM_MEM_DRIVER);
+		cliprects = kcalloc(batch->num_cliprects,
+				    sizeof(struct drm_clip_rect),
+				    GFP_KERNEL);
 		if (cliprects == NULL)
 			return -ENOMEM;
 
@@ -664,9 +664,7 @@
 		sarea_priv->last_dispatch = READ_BREADCRUMB(dev_priv);
 
 fail_free:
-	drm_free(cliprects,
-		 batch->num_cliprects * sizeof(struct drm_clip_rect),
-		 DRM_MEM_DRIVER);
+	kfree(cliprects);
 
 	return ret;
 }
@@ -692,7 +690,7 @@
 	if (cmdbuf->num_cliprects < 0)
 		return -EINVAL;
 
-	batch_data = drm_alloc(cmdbuf->sz, DRM_MEM_DRIVER);
+	batch_data = kmalloc(cmdbuf->sz, GFP_KERNEL);
 	if (batch_data == NULL)
 		return -ENOMEM;
 
@@ -701,9 +699,8 @@
 		goto fail_batch_free;
 
 	if (cmdbuf->num_cliprects) {
-		cliprects = drm_calloc(cmdbuf->num_cliprects,
-				       sizeof(struct drm_clip_rect),
-				       DRM_MEM_DRIVER);
+		cliprects = kcalloc(cmdbuf->num_cliprects,
+				    sizeof(struct drm_clip_rect), GFP_KERNEL);
 		if (cliprects == NULL)
 			goto fail_batch_free;
 
@@ -726,11 +723,9 @@
 		sarea_priv->last_dispatch = READ_BREADCRUMB(dev_priv);
 
 fail_clip_free:
-	drm_free(cliprects,
-		 cmdbuf->num_cliprects * sizeof(struct drm_clip_rect),
-		 DRM_MEM_DRIVER);
+	kfree(cliprects);
 fail_batch_free:
-	drm_free(batch_data, cmdbuf->sz, DRM_MEM_DRIVER);
+	kfree(batch_data);
 
 	return ret;
 }
@@ -1067,7 +1062,7 @@
 {
 	struct drm_i915_master_private *master_priv;
 
-	master_priv = drm_calloc(1, sizeof(*master_priv), DRM_MEM_DRIVER);
+	master_priv = kzalloc(sizeof(*master_priv), GFP_KERNEL);
 	if (!master_priv)
 		return -ENOMEM;
 
@@ -1082,7 +1077,7 @@
 	if (!master_priv)
 		return;
 
-	drm_free(master_priv, sizeof(*master_priv), DRM_MEM_DRIVER);
+	kfree(master_priv);
 
 	master->driver_priv = NULL;
 }
@@ -1111,12 +1106,10 @@
 	dev->types[8] = _DRM_STAT_SECONDARY;
 	dev->types[9] = _DRM_STAT_DMA;
 
-	dev_priv = drm_alloc(sizeof(drm_i915_private_t), DRM_MEM_DRIVER);
+	dev_priv = kzalloc(sizeof(drm_i915_private_t), GFP_KERNEL);
 	if (dev_priv == NULL)
 		return -ENOMEM;
 
-	memset(dev_priv, 0, sizeof(drm_i915_private_t));
-
 	dev->dev_private = (void *)dev_priv;
 	dev_priv->dev = dev;
 
@@ -1153,13 +1146,8 @@
 			 "performance may suffer.\n");
 	}
 
-#ifdef CONFIG_HIGHMEM64G
-	/* don't enable GEM on PAE - needs agp + set_memory_* interface fixes */
-	dev_priv->has_gem = 0;
-#else
 	/* enable GEM by default */
 	dev_priv->has_gem = 1;
-#endif
 
 	dev->driver->get_vblank_counter = i915_get_vblank_counter;
 	dev->max_vblank_count = 0xffffff; /* only 24 bits of frame count */
@@ -1221,7 +1209,7 @@
 out_rmmap:
 	iounmap(dev_priv->regs);
 free_priv:
-	drm_free(dev_priv, sizeof(struct drm_i915_private), DRM_MEM_DRIVER);
+	kfree(dev_priv);
 	return ret;
 }
 
@@ -1261,8 +1249,7 @@
 		i915_gem_lastclose(dev);
 	}
 
-	drm_free(dev->dev_private, sizeof(drm_i915_private_t),
-		 DRM_MEM_DRIVER);
+	kfree(dev->dev_private);
 
 	return 0;
 }
@@ -1273,7 +1260,7 @@
 
 	DRM_DEBUG_DRIVER(I915_DRV, "\n");
 	i915_file_priv = (struct drm_i915_file_private *)
-	    drm_alloc(sizeof(*i915_file_priv), DRM_MEM_FILES);
+	    kmalloc(sizeof(*i915_file_priv), GFP_KERNEL);
 
 	if (!i915_file_priv)
 		return -ENOMEM;
@@ -1326,7 +1313,7 @@
 {
 	struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
 
-	drm_free(i915_file_priv, sizeof(*i915_file_priv), DRM_MEM_FILES);
+	kfree(i915_file_priv);
 }
 
 struct drm_ioctl_desc i915_ioctls[] = {
diff --git a/drivers/gpu/drm/i915/i915_drv.h b/drivers/gpu/drm/i915/i915_drv.h
index 8ef6bce..7a84f04 100644
--- a/drivers/gpu/drm/i915/i915_drv.h
+++ b/drivers/gpu/drm/i915/i915_drv.h
@@ -646,6 +646,8 @@
 int i915_gem_object_unbind(struct drm_gem_object *obj);
 void i915_gem_lastclose(struct drm_device *dev);
 uint32_t i915_get_gem_seqno(struct drm_device *dev);
+int i915_gem_object_get_fence_reg(struct drm_gem_object *obj);
+int i915_gem_object_put_fence_reg(struct drm_gem_object *obj);
 void i915_gem_retire_requests(struct drm_device *dev);
 void i915_gem_retire_work_handler(struct work_struct *work);
 void i915_gem_clflush_object(struct drm_gem_object *obj);
diff --git a/drivers/gpu/drm/i915/i915_gem.c b/drivers/gpu/drm/i915/i915_gem.c
index c0ae6bb..fd2b8bd 100644
--- a/drivers/gpu/drm/i915/i915_gem.c
+++ b/drivers/gpu/drm/i915/i915_gem.c
@@ -46,7 +46,6 @@
 static int i915_gem_object_wait_rendering(struct drm_gem_object *obj);
 static int i915_gem_object_bind_to_gtt(struct drm_gem_object *obj,
 					   unsigned alignment);
-static int i915_gem_object_get_fence_reg(struct drm_gem_object *obj, bool write);
 static void i915_gem_clear_fence_reg(struct drm_gem_object *obj);
 static int i915_gem_evict_something(struct drm_device *dev);
 static int i915_gem_phys_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
@@ -1158,7 +1157,7 @@
 	/* Need a new fence register? */
 	if (obj_priv->fence_reg == I915_FENCE_REG_NONE &&
 	    obj_priv->tiling_mode != I915_TILING_NONE) {
-		ret = i915_gem_object_get_fence_reg(obj, write);
+		ret = i915_gem_object_get_fence_reg(obj);
 		if (ret) {
 			mutex_unlock(&dev->struct_mutex);
 			return VM_FAULT_SIGBUS;
@@ -1208,8 +1207,7 @@
 
 	/* Set the object up for mmap'ing */
 	list = &obj->map_list;
-	list->map = drm_calloc(1, sizeof(struct drm_map_list),
-			       DRM_MEM_DRIVER);
+	list->map = kzalloc(sizeof(struct drm_map_list), GFP_KERNEL);
 	if (!list->map)
 		return -ENOMEM;
 
@@ -1249,7 +1247,7 @@
 out_free_mm:
 	drm_mm_put_block(list->file_offset_node);
 out_free_list:
-	drm_free(list->map, sizeof(struct drm_map_list), DRM_MEM_DRIVER);
+	kfree(list->map);
 
 	return ret;
 }
@@ -1271,7 +1269,7 @@
 	}
 
 	if (list->map) {
-		drm_free(list->map, sizeof(struct drm_map), DRM_MEM_DRIVER);
+		kfree(list->map);
 		list->map = NULL;
 	}
 
@@ -1494,7 +1492,7 @@
 	if (file_priv != NULL)
 		i915_file_priv = file_priv->driver_priv;
 
-	request = drm_calloc(1, sizeof(*request), DRM_MEM_DRIVER);
+	request = kzalloc(sizeof(*request), GFP_KERNEL);
 	if (request == NULL)
 		return 0;
 
@@ -1676,7 +1674,7 @@
 
 			list_del(&request->list);
 			list_del(&request->client_list);
-			drm_free(request, sizeof(*request), DRM_MEM_DRIVER);
+			kfree(request);
 		} else
 			break;
 	}
@@ -2163,13 +2161,11 @@
 	val |= I830_FENCE_REG_VALID;
 
 	I915_WRITE(FENCE_REG_830_0 + (regnum * 4), val);
-
 }
 
 /**
  * i915_gem_object_get_fence_reg - set up a fence reg for an object
  * @obj: object to map through a fence reg
- * @write: object is about to be written
  *
  * When mapping objects through the GTT, userspace wants to be able to write
  * to them without having to worry about swizzling if the object is tiled.
@@ -2180,8 +2176,8 @@
  * It then sets up the reg based on the object's properties: address, pitch
  * and tiling format.
  */
-static int
-i915_gem_object_get_fence_reg(struct drm_gem_object *obj, bool write)
+int
+i915_gem_object_get_fence_reg(struct drm_gem_object *obj)
 {
 	struct drm_device *dev = obj->dev;
 	struct drm_i915_private *dev_priv = dev->dev_private;
@@ -2331,6 +2327,42 @@
 }
 
 /**
+ * i915_gem_object_put_fence_reg - waits on outstanding fenced access
+ * to the buffer to finish, and then resets the fence register.
+ * @obj: tiled object holding a fence register.
+ *
+ * Zeroes out the fence register itself and clears out the associated
+ * data structures in dev_priv and obj_priv.
+ */
+int
+i915_gem_object_put_fence_reg(struct drm_gem_object *obj)
+{
+	struct drm_device *dev = obj->dev;
+	struct drm_i915_gem_object *obj_priv = obj->driver_private;
+
+	if (obj_priv->fence_reg == I915_FENCE_REG_NONE)
+		return 0;
+
+	/* On the i915, GPU access to tiled buffers is via a fence,
+	 * therefore we must wait for any outstanding access to complete
+	 * before clearing the fence.
+	 */
+	if (!IS_I965G(dev)) {
+		int ret;
+
+		i915_gem_object_flush_gpu_write_domain(obj);
+		i915_gem_object_flush_gtt_write_domain(obj);
+		ret = i915_gem_object_wait_rendering(obj);
+		if (ret != 0)
+			return ret;
+	}
+
+	i915_gem_clear_fence_reg (obj);
+
+	return 0;
+}
+
+/**
  * Finds free space in the GTT aperture and binds the object there.
  */
 static int
@@ -2800,8 +2832,7 @@
 	/* Free the page_cpu_valid mappings which are now stale, whether
 	 * or not we've got I915_GEM_DOMAIN_CPU.
 	 */
-	drm_free(obj_priv->page_cpu_valid, obj->size / PAGE_SIZE,
-		 DRM_MEM_DRIVER);
+	kfree(obj_priv->page_cpu_valid);
 	obj_priv->page_cpu_valid = NULL;
 }
 
@@ -2843,8 +2874,8 @@
 	 * newly adding I915_GEM_DOMAIN_CPU
 	 */
 	if (obj_priv->page_cpu_valid == NULL) {
-		obj_priv->page_cpu_valid = drm_calloc(1, obj->size / PAGE_SIZE,
-						      DRM_MEM_DRIVER);
+		obj_priv->page_cpu_valid = kzalloc(obj->size / PAGE_SIZE,
+						   GFP_KERNEL);
 		if (obj_priv->page_cpu_valid == NULL)
 			return -ENOMEM;
 	} else if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0)
@@ -3267,8 +3298,8 @@
 	}
 
 	if (args->num_cliprects != 0) {
-		cliprects = drm_calloc(args->num_cliprects, sizeof(*cliprects),
-				       DRM_MEM_DRIVER);
+		cliprects = kcalloc(args->num_cliprects, sizeof(*cliprects),
+				    GFP_KERNEL);
 		if (cliprects == NULL)
 			goto pre_mutex_err;
 
@@ -3521,8 +3552,7 @@
 pre_mutex_err:
 	drm_free_large(object_list);
 	drm_free_large(exec_list);
-	drm_free(cliprects, sizeof(*cliprects) * args->num_cliprects,
-		 DRM_MEM_DRIVER);
+	kfree(cliprects);
 
 	return ret;
 }
@@ -3550,7 +3580,7 @@
 	if (!IS_I965G(dev) &&
 	    obj_priv->fence_reg == I915_FENCE_REG_NONE &&
 	    obj_priv->tiling_mode != I915_TILING_NONE) {
-		ret = i915_gem_object_get_fence_reg(obj, true);
+		ret = i915_gem_object_get_fence_reg(obj);
 		if (ret != 0) {
 			if (ret != -EBUSY && ret != -ERESTARTSYS)
 				DRM_ERROR("Failure to install fence: %d\n",
@@ -3739,7 +3769,7 @@
 {
 	struct drm_i915_gem_object *obj_priv;
 
-	obj_priv = drm_calloc(1, sizeof(*obj_priv), DRM_MEM_DRIVER);
+	obj_priv = kzalloc(sizeof(*obj_priv), GFP_KERNEL);
 	if (obj_priv == NULL)
 		return -ENOMEM;
 
@@ -3777,9 +3807,9 @@
 
 	i915_gem_free_mmap_offset(obj);
 
-	drm_free(obj_priv->page_cpu_valid, 1, DRM_MEM_DRIVER);
+	kfree(obj_priv->page_cpu_valid);
 	kfree(obj_priv->bit_17);
-	drm_free(obj->driver_private, 1, DRM_MEM_DRIVER);
+	kfree(obj->driver_private);
 }
 
 /** Unbinds all objects that are on the given buffer list. */
@@ -4233,7 +4263,7 @@
 	if (dev_priv->mm.phys_objs[id - 1] || !size)
 		return 0;
 
-	phys_obj = drm_calloc(1, sizeof(struct drm_i915_gem_phys_object), DRM_MEM_DRIVER);
+	phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
 	if (!phys_obj)
 		return -ENOMEM;
 
@@ -4252,7 +4282,7 @@
 
 	return 0;
 kfree_obj:
-	drm_free(phys_obj, sizeof(struct drm_i915_gem_phys_object), DRM_MEM_DRIVER);
+	kfree(phys_obj);
 	return ret;
 }
 
@@ -4312,6 +4342,8 @@
 	}
 	drm_clflush_pages(obj_priv->pages, page_count);
 	drm_agp_chipset_flush(dev);
+
+	i915_gem_object_put_pages(obj);
 out:
 	obj_priv->phys_obj->cur_obj = NULL;
 	obj_priv->phys_obj = NULL;
@@ -4369,6 +4401,8 @@
 		kunmap_atomic(src, KM_USER0);
 	}
 
+	i915_gem_object_put_pages(obj);
+
 	return 0;
 out:
 	return ret;
diff --git a/drivers/gpu/drm/i915/i915_gem_debugfs.c b/drivers/gpu/drm/i915/i915_gem_debugfs.c
index 986f108..28146e4 100644
--- a/drivers/gpu/drm/i915/i915_gem_debugfs.c
+++ b/drivers/gpu/drm/i915/i915_gem_debugfs.c
@@ -104,7 +104,7 @@
 		if (obj->name)
 			seq_printf(m, " (name: %d)", obj->name);
 		if (obj_priv->fence_reg != I915_FENCE_REG_NONE)
-			seq_printf(m, " (fence: %d\n", obj_priv->fence_reg);
+			seq_printf(m, " (fence: %d)\n", obj_priv->fence_reg);
 		seq_printf(m, "\n");
 	}
 
@@ -318,7 +318,7 @@
 	seq_printf(m, "RingTail :  %08x\n", tail);
 	seq_printf(m, "RingMask :  %08x\n", mask);
 	seq_printf(m, "RingSize :  %08lx\n", dev_priv->ring.Size);
-	seq_printf(m, "Acthd :  %08x\n", I915_READ(IS_I965G(dev) ? ACTHD_I965 : ACTHD));
+	seq_printf(m, "Acthd :     %08x\n", I915_READ(IS_I965G(dev) ? ACTHD_I965 : ACTHD));
 
 	return 0;
 }
diff --git a/drivers/gpu/drm/i915/i915_gem_tiling.c b/drivers/gpu/drm/i915/i915_gem_tiling.c
index 9a05cad..5c1ceec 100644
--- a/drivers/gpu/drm/i915/i915_gem_tiling.c
+++ b/drivers/gpu/drm/i915/i915_gem_tiling.c
@@ -408,7 +408,7 @@
 	if (stride & (stride - 1))
 		return false;
 
-	/* We don't handle the aperture area covered by the fence being bigger
+	/* We don't 0handle the aperture area covered by the fence being bigger
 	 * than the object size.
 	 */
 	if (i915_get_fence_size(dev, size) != size)
@@ -417,6 +417,33 @@
 	return true;
 }
 
+static bool
+i915_gem_object_fence_offset_ok(struct drm_gem_object *obj, int tiling_mode)
+{
+	struct drm_device *dev = obj->dev;
+	struct drm_i915_gem_object *obj_priv = obj->driver_private;
+
+	if (obj_priv->gtt_space == NULL)
+		return true;
+
+	if (tiling_mode == I915_TILING_NONE)
+		return true;
+
+	if (!IS_I965G(dev)) {
+		if (obj_priv->gtt_offset & (obj->size - 1))
+			return false;
+		if (IS_I9XX(dev)) {
+			if (obj_priv->gtt_offset & ~I915_FENCE_START_MASK)
+				return false;
+		} else {
+			if (obj_priv->gtt_offset & ~I830_FENCE_START_MASK)
+				return false;
+		}
+	}
+
+	return true;
+}
+
 /**
  * Sets the tiling mode of an object, returning the required swizzling of
  * bit 6 of addresses in the object.
@@ -429,6 +456,7 @@
 	drm_i915_private_t *dev_priv = dev->dev_private;
 	struct drm_gem_object *obj;
 	struct drm_i915_gem_object *obj_priv;
+	int ret = 0;
 
 	obj = drm_gem_object_lookup(dev, file_priv, args->handle);
 	if (obj == NULL)
@@ -436,14 +464,15 @@
 	obj_priv = obj->driver_private;
 
 	if (!i915_tiling_ok(dev, args->stride, obj->size, args->tiling_mode)) {
+		mutex_lock(&dev->struct_mutex);
 		drm_gem_object_unreference(obj);
+		mutex_unlock(&dev->struct_mutex);
 		return -EINVAL;
 	}
 
-	mutex_lock(&dev->struct_mutex);
-
 	if (args->tiling_mode == I915_TILING_NONE) {
 		args->swizzle_mode = I915_BIT_6_SWIZZLE_NONE;
+		args->stride = 0;
 	} else {
 		if (args->tiling_mode == I915_TILING_X)
 			args->swizzle_mode = dev_priv->mm.bit_6_swizzle_x;
@@ -466,32 +495,38 @@
 		if (args->swizzle_mode == I915_BIT_6_SWIZZLE_UNKNOWN) {
 			args->tiling_mode = I915_TILING_NONE;
 			args->swizzle_mode = I915_BIT_6_SWIZZLE_NONE;
+			args->stride = 0;
 		}
 	}
-	if (args->tiling_mode != obj_priv->tiling_mode) {
-		int ret;
 
-		/* Unbind the object, as switching tiling means we're
-		 * switching the cache organization due to fencing, probably.
+	mutex_lock(&dev->struct_mutex);
+	if (args->tiling_mode != obj_priv->tiling_mode ||
+	    args->stride != obj_priv->stride) {
+		/* We need to rebind the object if its current allocation
+		 * no longer meets the alignment restrictions for its new
+		 * tiling mode. Otherwise we can just leave it alone, but
+		 * need to ensure that any fence register is cleared.
 		 */
-		ret = i915_gem_object_unbind(obj);
+		if (!i915_gem_object_fence_offset_ok(obj, args->tiling_mode))
+		    ret = i915_gem_object_unbind(obj);
+		else
+		    ret = i915_gem_object_put_fence_reg(obj);
 		if (ret != 0) {
 			WARN(ret != -ERESTARTSYS,
-			     "failed to unbind object for tiling switch");
+			     "failed to reset object for tiling switch");
 			args->tiling_mode = obj_priv->tiling_mode;
-			mutex_unlock(&dev->struct_mutex);
-			drm_gem_object_unreference(obj);
-
-			return ret;
+			args->stride = obj_priv->stride;
+			goto err;
 		}
-		obj_priv->tiling_mode = args->tiling_mode;
-	}
-	obj_priv->stride = args->stride;
 
+		obj_priv->tiling_mode = args->tiling_mode;
+		obj_priv->stride = args->stride;
+	}
+err:
 	drm_gem_object_unreference(obj);
 	mutex_unlock(&dev->struct_mutex);
 
-	return 0;
+	return ret;
 }
 
 /**
diff --git a/drivers/gpu/drm/i915/i915_mem.c b/drivers/gpu/drm/i915/i915_mem.c
index 96e2719..83b7b81 100644
--- a/drivers/gpu/drm/i915/i915_mem.c
+++ b/drivers/gpu/drm/i915/i915_mem.c
@@ -94,8 +94,8 @@
 {
 	/* Maybe cut off the start of an existing block */
 	if (start > p->start) {
-		struct mem_block *newblock =
-		    drm_alloc(sizeof(*newblock), DRM_MEM_BUFLISTS);
+		struct mem_block *newblock = kmalloc(sizeof(*newblock),
+						     GFP_KERNEL);
 		if (!newblock)
 			goto out;
 		newblock->start = start;
@@ -111,8 +111,8 @@
 
 	/* Maybe cut off the end of an existing block */
 	if (size < p->size) {
-		struct mem_block *newblock =
-		    drm_alloc(sizeof(*newblock), DRM_MEM_BUFLISTS);
+		struct mem_block *newblock = kmalloc(sizeof(*newblock),
+						     GFP_KERNEL);
 		if (!newblock)
 			goto out;
 		newblock->start = start + size;
@@ -169,7 +169,7 @@
 		p->size += q->size;
 		p->next = q->next;
 		p->next->prev = p;
-		drm_free(q, sizeof(*q), DRM_MEM_BUFLISTS);
+		kfree(q);
 	}
 
 	if (p->prev->file_priv == NULL) {
@@ -177,7 +177,7 @@
 		q->size += p->size;
 		q->next = p->next;
 		q->next->prev = q;
-		drm_free(p, sizeof(*q), DRM_MEM_BUFLISTS);
+		kfree(p);
 	}
 }
 
@@ -185,14 +185,14 @@
  */
 static int init_heap(struct mem_block **heap, int start, int size)
 {
-	struct mem_block *blocks = drm_alloc(sizeof(*blocks), DRM_MEM_BUFLISTS);
+	struct mem_block *blocks = kmalloc(sizeof(*blocks), GFP_KERNEL);
 
 	if (!blocks)
 		return -ENOMEM;
 
-	*heap = drm_alloc(sizeof(**heap), DRM_MEM_BUFLISTS);
+	*heap = kmalloc(sizeof(**heap), GFP_KERNEL);
 	if (!*heap) {
-		drm_free(blocks, sizeof(*blocks), DRM_MEM_BUFLISTS);
+		kfree(blocks);
 		return -ENOMEM;
 	}
 
@@ -233,7 +233,7 @@
 			p->size += q->size;
 			p->next = q->next;
 			p->next->prev = p;
-			drm_free(q, sizeof(*q), DRM_MEM_BUFLISTS);
+			kfree(q);
 		}
 	}
 }
@@ -250,10 +250,10 @@
 	for (p = (*heap)->next; p != *heap;) {
 		struct mem_block *q = p;
 		p = p->next;
-		drm_free(q, sizeof(*q), DRM_MEM_BUFLISTS);
+		kfree(q);
 	}
 
-	drm_free(*heap, sizeof(**heap), DRM_MEM_BUFLISTS);
+	kfree(*heap);
 	*heap = NULL;
 }
 
diff --git a/drivers/gpu/drm/i915/intel_bios.c b/drivers/gpu/drm/i915/intel_bios.c
index 754dd22..cdd126d 100644
--- a/drivers/gpu/drm/i915/intel_bios.c
+++ b/drivers/gpu/drm/i915/intel_bios.c
@@ -124,8 +124,7 @@
 	entry = &lvds_lfp_data->data[lvds_options->panel_type];
 	dvo_timing = &entry->dvo_timing;
 
-	panel_fixed_mode = drm_calloc(1, sizeof(*panel_fixed_mode),
-				      DRM_MEM_DRIVER);
+	panel_fixed_mode = kzalloc(sizeof(*panel_fixed_mode), GFP_KERNEL);
 
 	fill_detail_timing_data(panel_fixed_mode, dvo_timing);
 
@@ -156,8 +155,7 @@
 	if (!dvo_timing)
 		return;
 
-	panel_fixed_mode = drm_calloc(1, sizeof(*panel_fixed_mode),
-				      DRM_MEM_DRIVER);
+	panel_fixed_mode = kzalloc(sizeof(*panel_fixed_mode), GFP_KERNEL);
 
 	if (!panel_fixed_mode)
 		return;
diff --git a/drivers/gpu/drm/i915/intel_display.c b/drivers/gpu/drm/i915/intel_display.c
index 028f5b6..3e1c781 100644
--- a/drivers/gpu/drm/i915/intel_display.c
+++ b/drivers/gpu/drm/i915/intel_display.c
@@ -828,19 +828,31 @@
 	}
 
 	mutex_lock(&dev->struct_mutex);
-	ret = i915_gem_object_pin(intel_fb->obj, alignment);
+	ret = i915_gem_object_pin(obj, alignment);
 	if (ret != 0) {
 		mutex_unlock(&dev->struct_mutex);
 		return ret;
 	}
 
-	ret = i915_gem_object_set_to_gtt_domain(intel_fb->obj, 1);
+	ret = i915_gem_object_set_to_gtt_domain(obj, 1);
 	if (ret != 0) {
-		i915_gem_object_unpin(intel_fb->obj);
+		i915_gem_object_unpin(obj);
 		mutex_unlock(&dev->struct_mutex);
 		return ret;
 	}
 
+	/* Pre-i965 needs to install a fence for tiled scan-out */
+	if (!IS_I965G(dev) &&
+	    obj_priv->fence_reg == I915_FENCE_REG_NONE &&
+	    obj_priv->tiling_mode != I915_TILING_NONE) {
+		ret = i915_gem_object_get_fence_reg(obj);
+		if (ret != 0) {
+			i915_gem_object_unpin(obj);
+			mutex_unlock(&dev->struct_mutex);
+			return ret;
+		}
+	}
+
 	dspcntr = I915_READ(dspcntr_reg);
 	/* Mask out pixel format bits in case we change it */
 	dspcntr &= ~DISPPLANE_PIXFORMAT_MASK;
@@ -860,7 +872,7 @@
 		break;
 	default:
 		DRM_ERROR("Unknown color depth\n");
-		i915_gem_object_unpin(intel_fb->obj);
+		i915_gem_object_unpin(obj);
 		mutex_unlock(&dev->struct_mutex);
 		return -EINVAL;
 	}
diff --git a/drivers/gpu/drm/i915/intel_fb.c b/drivers/gpu/drm/i915/intel_fb.c
index 8e28e59..1af7d68 100644
--- a/drivers/gpu/drm/i915/intel_fb.c
+++ b/drivers/gpu/drm/i915/intel_fb.c
@@ -870,7 +870,11 @@
  */
 void intelfb_restore(void)
 {
-	drm_crtc_helper_set_config(&kernelfb_mode);
+	int ret;
+	if ((ret = drm_crtc_helper_set_config(&kernelfb_mode)) != 0) {
+		printk(KERN_ERR "Failed to restore crtc configuration: %d\n",
+		       ret);
+	}
 }
 
 static void intelfb_restore_work_fn(struct work_struct *ignored)
diff --git a/drivers/gpu/drm/i915/intel_tv.c b/drivers/gpu/drm/i915/intel_tv.c
index 50d7ed7..ea68992 100644
--- a/drivers/gpu/drm/i915/intel_tv.c
+++ b/drivers/gpu/drm/i915/intel_tv.c
@@ -1561,8 +1561,7 @@
 
 	drm_sysfs_connector_remove(connector);
 	drm_connector_cleanup(connector);
-	drm_free(intel_output, sizeof(struct intel_output) + sizeof(struct intel_tv_priv),
-		 DRM_MEM_DRIVER);
+	kfree(intel_output);
 }
 
 
@@ -1695,8 +1694,8 @@
 	    (tv_dac_off & TVDAC_STATE_CHG_EN) != 0)
 		return;
 
-	intel_output = drm_calloc(1, sizeof(struct intel_output) +
-				  sizeof(struct intel_tv_priv), DRM_MEM_DRIVER);
+	intel_output = kzalloc(sizeof(struct intel_output) +
+			       sizeof(struct intel_tv_priv), GFP_KERNEL);
 	if (!intel_output) {
 		return;
 	}
@@ -1730,8 +1729,8 @@
 	connector->doublescan_allowed = false;
 
 	/* Create TV properties then attach current values */
-	tv_format_names = drm_alloc(sizeof(char *) * NUM_TV_MODES,
-				    DRM_MEM_DRIVER);
+	tv_format_names = kmalloc(sizeof(char *) * NUM_TV_MODES,
+				  GFP_KERNEL);
 	if (!tv_format_names)
 		goto out;
 	for (i = 0; i < NUM_TV_MODES; i++)
diff --git a/drivers/gpu/drm/mga/mga_dma.c b/drivers/gpu/drm/mga/mga_dma.c
index 7a6bf9f..6c67a02 100644
--- a/drivers/gpu/drm/mga/mga_dma.c
+++ b/drivers/gpu/drm/mga/mga_dma.c
@@ -254,23 +254,20 @@
 	int i;
 	DRM_DEBUG("count=%d\n", dma->buf_count);
 
-	dev_priv->head = drm_alloc(sizeof(drm_mga_freelist_t), DRM_MEM_DRIVER);
+	dev_priv->head = kzalloc(sizeof(drm_mga_freelist_t), GFP_KERNEL);
 	if (dev_priv->head == NULL)
 		return -ENOMEM;
 
-	memset(dev_priv->head, 0, sizeof(drm_mga_freelist_t));
 	SET_AGE(&dev_priv->head->age, MGA_BUFFER_USED, 0);
 
 	for (i = 0; i < dma->buf_count; i++) {
 		buf = dma->buflist[i];
 		buf_priv = buf->dev_private;
 
-		entry = drm_alloc(sizeof(drm_mga_freelist_t), DRM_MEM_DRIVER);
+		entry = kzalloc(sizeof(drm_mga_freelist_t), GFP_KERNEL);
 		if (entry == NULL)
 			return -ENOMEM;
 
-		memset(entry, 0, sizeof(drm_mga_freelist_t));
-
 		entry->next = dev_priv->head->next;
 		entry->prev = dev_priv->head;
 		SET_AGE(&entry->age, MGA_BUFFER_FREE, 0);
@@ -301,7 +298,7 @@
 	entry = dev_priv->head;
 	while (entry) {
 		next = entry->next;
-		drm_free(entry, sizeof(drm_mga_freelist_t), DRM_MEM_DRIVER);
+		kfree(entry);
 		entry = next;
 	}
 
@@ -399,12 +396,11 @@
 	drm_mga_private_t *dev_priv;
 	int ret;
 
-	dev_priv = drm_alloc(sizeof(drm_mga_private_t), DRM_MEM_DRIVER);
+	dev_priv = kzalloc(sizeof(drm_mga_private_t), GFP_KERNEL);
 	if (!dev_priv)
 		return -ENOMEM;
 
 	dev->dev_private = (void *)dev_priv;
-	memset(dev_priv, 0, sizeof(drm_mga_private_t));
 
 	dev_priv->usec_timeout = MGA_DEFAULT_USEC_TIMEOUT;
 	dev_priv->chipset = flags;
@@ -1150,7 +1146,7 @@
  */
 int mga_driver_unload(struct drm_device * dev)
 {
-	drm_free(dev->dev_private, sizeof(drm_mga_private_t), DRM_MEM_DRIVER);
+	kfree(dev->dev_private);
 	dev->dev_private = NULL;
 
 	return 0;
diff --git a/drivers/gpu/drm/r128/r128_cce.c b/drivers/gpu/drm/r128/r128_cce.c
index 077c045..c75fd35 100644
--- a/drivers/gpu/drm/r128/r128_cce.c
+++ b/drivers/gpu/drm/r128/r128_cce.c
@@ -353,12 +353,10 @@
 
 	DRM_DEBUG("\n");
 
-	dev_priv = drm_alloc(sizeof(drm_r128_private_t), DRM_MEM_DRIVER);
+	dev_priv = kzalloc(sizeof(drm_r128_private_t), GFP_KERNEL);
 	if (dev_priv == NULL)
 		return -ENOMEM;
 
-	memset(dev_priv, 0, sizeof(drm_r128_private_t));
-
 	dev_priv->is_pci = init->is_pci;
 
 	if (dev_priv->is_pci && !dev->sg) {
@@ -619,8 +617,7 @@
 					    ("failed to cleanup PCI GART!\n");
 		}
 
-		drm_free(dev->dev_private, sizeof(drm_r128_private_t),
-			 DRM_MEM_DRIVER);
+		kfree(dev->dev_private);
 		dev->dev_private = NULL;
 	}
 
@@ -768,18 +765,17 @@
 	drm_r128_freelist_t *entry;
 	int i;
 
-	dev_priv->head = drm_alloc(sizeof(drm_r128_freelist_t), DRM_MEM_DRIVER);
+	dev_priv->head = kzalloc(sizeof(drm_r128_freelist_t), GFP_KERNEL);
 	if (dev_priv->head == NULL)
 		return -ENOMEM;
 
-	memset(dev_priv->head, 0, sizeof(drm_r128_freelist_t));
 	dev_priv->head->age = R128_BUFFER_USED;
 
 	for (i = 0; i < dma->buf_count; i++) {
 		buf = dma->buflist[i];
 		buf_priv = buf->dev_private;
 
-		entry = drm_alloc(sizeof(drm_r128_freelist_t), DRM_MEM_DRIVER);
+		entry = kmalloc(sizeof(drm_r128_freelist_t), GFP_KERNEL);
 		if (!entry)
 			return -ENOMEM;
 
diff --git a/drivers/gpu/drm/r128/r128_state.c b/drivers/gpu/drm/r128/r128_state.c
index f7a5b57..026a48c 100644
--- a/drivers/gpu/drm/r128/r128_state.c
+++ b/drivers/gpu/drm/r128/r128_state.c
@@ -910,24 +910,24 @@
 	}
 
 	buffer_size = depth->n * sizeof(u32);
-	buffer = drm_alloc(buffer_size, DRM_MEM_BUFS);
+	buffer = kmalloc(buffer_size, GFP_KERNEL);
 	if (buffer == NULL)
 		return -ENOMEM;
 	if (DRM_COPY_FROM_USER(buffer, depth->buffer, buffer_size)) {
-		drm_free(buffer, buffer_size, DRM_MEM_BUFS);
+		kfree(buffer);
 		return -EFAULT;
 	}
 
 	mask_size = depth->n * sizeof(u8);
 	if (depth->mask) {
-		mask = drm_alloc(mask_size, DRM_MEM_BUFS);
+		mask = kmalloc(mask_size, GFP_KERNEL);
 		if (mask == NULL) {
-			drm_free(buffer, buffer_size, DRM_MEM_BUFS);
+			kfree(buffer);
 			return -ENOMEM;
 		}
 		if (DRM_COPY_FROM_USER(mask, depth->mask, mask_size)) {
-			drm_free(buffer, buffer_size, DRM_MEM_BUFS);
-			drm_free(mask, mask_size, DRM_MEM_BUFS);
+			kfree(buffer);
+			kfree(mask);
 			return -EFAULT;
 		}
 
@@ -954,7 +954,7 @@
 			}
 		}
 
-		drm_free(mask, mask_size, DRM_MEM_BUFS);
+		kfree(mask);
 	} else {
 		for (i = 0; i < count; i++, x++) {
 			BEGIN_RING(6);
@@ -978,7 +978,7 @@
 		}
 	}
 
-	drm_free(buffer, buffer_size, DRM_MEM_BUFS);
+	kfree(buffer);
 
 	return 0;
 }
@@ -1000,54 +1000,54 @@
 
 	xbuf_size = count * sizeof(*x);
 	ybuf_size = count * sizeof(*y);
-	x = drm_alloc(xbuf_size, DRM_MEM_BUFS);
+	x = kmalloc(xbuf_size, GFP_KERNEL);
 	if (x == NULL) {
 		return -ENOMEM;
 	}
-	y = drm_alloc(ybuf_size, DRM_MEM_BUFS);
+	y = kmalloc(ybuf_size, GFP_KERNEL);
 	if (y == NULL) {
-		drm_free(x, xbuf_size, DRM_MEM_BUFS);
+		kfree(x);
 		return -ENOMEM;
 	}
 	if (DRM_COPY_FROM_USER(x, depth->x, xbuf_size)) {
-		drm_free(x, xbuf_size, DRM_MEM_BUFS);
-		drm_free(y, ybuf_size, DRM_MEM_BUFS);
+		kfree(x);
+		kfree(y);
 		return -EFAULT;
 	}
 	if (DRM_COPY_FROM_USER(y, depth->y, xbuf_size)) {
-		drm_free(x, xbuf_size, DRM_MEM_BUFS);
-		drm_free(y, ybuf_size, DRM_MEM_BUFS);
+		kfree(x);
+		kfree(y);
 		return -EFAULT;
 	}
 
 	buffer_size = depth->n * sizeof(u32);
-	buffer = drm_alloc(buffer_size, DRM_MEM_BUFS);
+	buffer = kmalloc(buffer_size, GFP_KERNEL);
 	if (buffer == NULL) {
-		drm_free(x, xbuf_size, DRM_MEM_BUFS);
-		drm_free(y, ybuf_size, DRM_MEM_BUFS);
+		kfree(x);
+		kfree(y);
 		return -ENOMEM;
 	}
 	if (DRM_COPY_FROM_USER(buffer, depth->buffer, buffer_size)) {
-		drm_free(x, xbuf_size, DRM_MEM_BUFS);
-		drm_free(y, ybuf_size, DRM_MEM_BUFS);
-		drm_free(buffer, buffer_size, DRM_MEM_BUFS);
+		kfree(x);
+		kfree(y);
+		kfree(buffer);
 		return -EFAULT;
 	}
 
 	if (depth->mask) {
 		mask_size = depth->n * sizeof(u8);
-		mask = drm_alloc(mask_size, DRM_MEM_BUFS);
+		mask = kmalloc(mask_size, GFP_KERNEL);
 		if (mask == NULL) {
-			drm_free(x, xbuf_size, DRM_MEM_BUFS);
-			drm_free(y, ybuf_size, DRM_MEM_BUFS);
-			drm_free(buffer, buffer_size, DRM_MEM_BUFS);
+			kfree(x);
+			kfree(y);
+			kfree(buffer);
 			return -ENOMEM;
 		}
 		if (DRM_COPY_FROM_USER(mask, depth->mask, mask_size)) {
-			drm_free(x, xbuf_size, DRM_MEM_BUFS);
-			drm_free(y, ybuf_size, DRM_MEM_BUFS);
-			drm_free(buffer, buffer_size, DRM_MEM_BUFS);
-			drm_free(mask, mask_size, DRM_MEM_BUFS);
+			kfree(x);
+			kfree(y);
+			kfree(buffer);
+			kfree(mask);
 			return -EFAULT;
 		}
 
@@ -1074,7 +1074,7 @@
 			}
 		}
 
-		drm_free(mask, mask_size, DRM_MEM_BUFS);
+		kfree(mask);
 	} else {
 		for (i = 0; i < count; i++) {
 			BEGIN_RING(6);
@@ -1098,9 +1098,9 @@
 		}
 	}
 
-	drm_free(x, xbuf_size, DRM_MEM_BUFS);
-	drm_free(y, ybuf_size, DRM_MEM_BUFS);
-	drm_free(buffer, buffer_size, DRM_MEM_BUFS);
+	kfree(x);
+	kfree(y);
+	kfree(buffer);
 
 	return 0;
 }
@@ -1167,23 +1167,23 @@
 
 	xbuf_size = count * sizeof(*x);
 	ybuf_size = count * sizeof(*y);
-	x = drm_alloc(xbuf_size, DRM_MEM_BUFS);
+	x = kmalloc(xbuf_size, GFP_KERNEL);
 	if (x == NULL) {
 		return -ENOMEM;
 	}
-	y = drm_alloc(ybuf_size, DRM_MEM_BUFS);
+	y = kmalloc(ybuf_size, GFP_KERNEL);
 	if (y == NULL) {
-		drm_free(x, xbuf_size, DRM_MEM_BUFS);
+		kfree(x);
 		return -ENOMEM;
 	}
 	if (DRM_COPY_FROM_USER(x, depth->x, xbuf_size)) {
-		drm_free(x, xbuf_size, DRM_MEM_BUFS);
-		drm_free(y, ybuf_size, DRM_MEM_BUFS);
+		kfree(x);
+		kfree(y);
 		return -EFAULT;
 	}
 	if (DRM_COPY_FROM_USER(y, depth->y, ybuf_size)) {
-		drm_free(x, xbuf_size, DRM_MEM_BUFS);
-		drm_free(y, ybuf_size, DRM_MEM_BUFS);
+		kfree(x);
+		kfree(y);
 		return -EFAULT;
 	}
 
@@ -1210,8 +1210,8 @@
 		ADVANCE_RING();
 	}
 
-	drm_free(x, xbuf_size, DRM_MEM_BUFS);
-	drm_free(y, ybuf_size, DRM_MEM_BUFS);
+	kfree(x);
+	kfree(y);
 
 	return 0;
 }
diff --git a/drivers/gpu/drm/radeon/r100.c b/drivers/gpu/drm/radeon/r100.c
index 5225f5b..c550932 100644
--- a/drivers/gpu/drm/radeon/r100.c
+++ b/drivers/gpu/drm/radeon/r100.c
@@ -551,6 +551,9 @@
 	/* cp setup */
 	WREG32(0x718, pre_write_timer | (pre_write_limit << 28));
 	WREG32(RADEON_CP_RB_CNTL,
+#ifdef __BIG_ENDIAN
+	       RADEON_BUF_SWAP_32BIT |
+#endif
 	       REG_SET(RADEON_RB_BUFSZ, rb_bufsz) |
 	       REG_SET(RADEON_RB_BLKSZ, rb_blksz) |
 	       REG_SET(RADEON_MAX_FETCH, max_fetch) |
@@ -644,7 +647,7 @@
  */
 int r100_cs_parse_packet0(struct radeon_cs_parser *p,
 			  struct radeon_cs_packet *pkt,
-			  unsigned *auth, unsigned n,
+			  const unsigned *auth, unsigned n,
 			  radeon_packet0_check_t check)
 {
 	unsigned reg;
@@ -654,6 +657,10 @@
 
 	idx = pkt->idx + 1;
 	reg = pkt->reg;
+	/* Check that register fall into register range
+	 * determined by the number of entry (n) in the
+	 * safe register bitmap.
+	 */
 	if (pkt->one_reg_wr) {
 		if ((reg >> 7) > n) {
 			return -EINVAL;
@@ -683,24 +690,6 @@
 	return 0;
 }
 
-int r100_cs_parse_packet3(struct radeon_cs_parser *p,
-			  struct radeon_cs_packet *pkt,
-			  unsigned *auth, unsigned n,
-			  radeon_packet3_check_t check)
-{
-	unsigned i, m;
-
-	if ((pkt->opcode >> 5) > n) {
-		return -EINVAL;
-	}
-	i = pkt->opcode >> 5;
-	m = 1 << (pkt->opcode & 31);
-	if (auth[i] & m) {
-		return check(p, pkt);
-	}
-	return 0;
-}
-
 void r100_cs_dump_packet(struct radeon_cs_parser *p,
 			 struct radeon_cs_packet *pkt)
 {
@@ -901,6 +890,25 @@
 	return 0;
 }
 
+int r100_cs_track_check_pkt3_indx_buffer(struct radeon_cs_parser *p,
+					 struct radeon_cs_packet *pkt,
+					 struct radeon_object *robj)
+{
+	struct radeon_cs_chunk *ib_chunk;
+	unsigned idx;
+
+	ib_chunk = &p->chunks[p->chunk_ib_idx];
+	idx = pkt->idx + 1;
+	if ((ib_chunk->kdata[idx+2] + 1) > radeon_object_size(robj)) {
+		DRM_ERROR("[drm] Buffer too small for PACKET3 INDX_BUFFER "
+			  "(need %u have %lu) !\n",
+			  ib_chunk->kdata[idx+2] + 1,
+			  radeon_object_size(robj));
+		return -EINVAL;
+	}
+	return 0;
+}
+
 static int r100_packet3_check(struct radeon_cs_parser *p,
 			      struct radeon_cs_packet *pkt)
 {
@@ -954,6 +962,10 @@
 			return r;
 		}
 		ib[idx+1] = ib_chunk->kdata[idx+1] + ((u32)reloc->lobj.gpu_offset);
+		r = r100_cs_track_check_pkt3_indx_buffer(p, pkt, reloc->robj);
+		if (r) {
+			return r;
+		}
 		break;
 	case 0x23:
 		/* FIXME: cleanup */
@@ -999,18 +1011,18 @@
 		}
 		p->idx += pkt.count + 2;
 		switch (pkt.type) {
-		case PACKET_TYPE0:
-			r = r100_packet0_check(p, &pkt);
-			break;
-		case PACKET_TYPE2:
-			break;
-		case PACKET_TYPE3:
-			r = r100_packet3_check(p, &pkt);
-			break;
-		default:
-			DRM_ERROR("Unknown packet type %d !\n",
-					pkt.type);
-			return -EINVAL;
+			case PACKET_TYPE0:
+				r = r100_packet0_check(p, &pkt);
+				break;
+			case PACKET_TYPE2:
+				break;
+			case PACKET_TYPE3:
+				r = r100_packet3_check(p, &pkt);
+				break;
+			default:
+				DRM_ERROR("Unknown packet type %d !\n",
+					  pkt.type);
+				return -EINVAL;
 		}
 		if (r) {
 			return r;
@@ -1267,12 +1279,6 @@
 
 	rdev->mc.aper_base = drm_get_resource_start(rdev->ddev, 0);
 	rdev->mc.aper_size = drm_get_resource_len(rdev->ddev, 0);
-	if (rdev->mc.aper_size > rdev->mc.vram_size) {
-		/* Why does some hw doesn't have CONFIG_MEMSIZE properly
-		 * setup ? */
-		rdev->mc.vram_size = rdev->mc.aper_size;
-		WREG32(RADEON_CONFIG_MEMSIZE, rdev->mc.vram_size);
-	}
 }
 
 
@@ -1352,6 +1358,11 @@
 	}
 }
 
+int r100_init(struct radeon_device *rdev)
+{
+	return 0;
+}
+
 /*
  * Debugfs info
  */
diff --git a/drivers/gpu/drm/radeon/r300.c b/drivers/gpu/drm/radeon/r300.c
index f5870a0..e2ed5bc 100644
--- a/drivers/gpu/drm/radeon/r300.c
+++ b/drivers/gpu/drm/radeon/r300.c
@@ -48,14 +48,13 @@
 			      struct radeon_cs_reloc **cs_reloc);
 int r100_cs_parse_packet0(struct radeon_cs_parser *p,
 			  struct radeon_cs_packet *pkt,
-			  unsigned *auth, unsigned n,
+			  const unsigned *auth, unsigned n,
 			  radeon_packet0_check_t check);
-int r100_cs_parse_packet3(struct radeon_cs_parser *p,
-			  struct radeon_cs_packet *pkt,
-			  unsigned *auth, unsigned n,
-			  radeon_packet3_check_t check);
 void r100_cs_dump_packet(struct radeon_cs_parser *p,
 			 struct radeon_cs_packet *pkt);
+int r100_cs_track_check_pkt3_indx_buffer(struct radeon_cs_parser *p,
+					 struct radeon_cs_packet *pkt,
+					 struct radeon_object *robj);
 
 /* This files gather functions specifics to:
  * r300,r350,rv350,rv370,rv380
@@ -288,7 +287,7 @@
 		return r;
 	}
 	/* Must wait for 2D idle & clean before DMA or hangs might happen */
-	radeon_ring_write(rdev, PACKET0(RADEON_WAIT_UNTIL, 0));
+	radeon_ring_write(rdev, PACKET0(RADEON_WAIT_UNTIL, 0 ));
 	radeon_ring_write(rdev, (1 << 16));
 	for (i = 0; i < num_loops; i++) {
 		cur_size = size;
@@ -319,7 +318,7 @@
 
 	/* Sub pixel 1/12 so we can have 4K rendering according to doc */
 	gb_tile_config = (R300_ENABLE_TILING | R300_TILE_SIZE_16);
-	switch (rdev->num_gb_pipes) {
+	switch(rdev->num_gb_pipes) {
 	case 2:
 		gb_tile_config |= R300_PIPE_COUNT_R300;
 		break;
@@ -452,8 +451,8 @@
 	case 4:
 		gb_tile_config |= R300_PIPE_COUNT_R420;
 		break;
-	case 1:
 	default:
+	case 1:
 		gb_tile_config |= R300_PIPE_COUNT_RV350;
 		break;
 	}
@@ -725,18 +724,120 @@
 	unsigned		offset;
 };
 
-struct r300_cs_track {
-	unsigned		num_cb;
-	unsigned		maxy;
-	struct r300_cs_track_cb cb[4];
-	struct r300_cs_track_cb zb;
-	bool			z_enabled;
+struct r300_cs_track_array {
+	struct radeon_object	*robj;
+	unsigned		esize;
 };
 
+struct r300_cs_track_texture {
+	struct radeon_object	*robj;
+	unsigned		pitch;
+	unsigned		width;
+	unsigned		height;
+	unsigned		num_levels;
+	unsigned		cpp;
+	unsigned		tex_coord_type;
+	unsigned		txdepth;
+	unsigned		width_11;
+	unsigned		height_11;
+	bool			use_pitch;
+	bool			enabled;
+	bool			roundup_w;
+	bool			roundup_h;
+};
+
+struct r300_cs_track {
+	unsigned			num_cb;
+	unsigned			maxy;
+	unsigned			vtx_size;
+	unsigned			vap_vf_cntl;
+	unsigned			immd_dwords;
+	unsigned			num_arrays;
+	unsigned			max_indx;
+	struct r300_cs_track_array	arrays[11];
+	struct r300_cs_track_cb 	cb[4];
+	struct r300_cs_track_cb 	zb;
+	struct r300_cs_track_texture	textures[16];
+	bool				z_enabled;
+};
+
+static inline void r300_cs_track_texture_print(struct r300_cs_track_texture *t)
+{
+	DRM_ERROR("pitch                      %d\n", t->pitch);
+	DRM_ERROR("width                      %d\n", t->width);
+	DRM_ERROR("height                     %d\n", t->height);
+	DRM_ERROR("num levels                 %d\n", t->num_levels);
+	DRM_ERROR("depth                      %d\n", t->txdepth);
+	DRM_ERROR("bpp                        %d\n", t->cpp);
+	DRM_ERROR("coordinate type            %d\n", t->tex_coord_type);
+	DRM_ERROR("width round to power of 2  %d\n", t->roundup_w);
+	DRM_ERROR("height round to power of 2 %d\n", t->roundup_h);
+}
+
+static inline int r300_cs_track_texture_check(struct radeon_device *rdev,
+					      struct r300_cs_track *track)
+{
+	struct radeon_object *robj;
+	unsigned long size;
+	unsigned u, i, w, h;
+
+	for (u = 0; u < 16; u++) {
+		if (!track->textures[u].enabled)
+			continue;
+		robj = track->textures[u].robj;
+		if (robj == NULL) {
+			DRM_ERROR("No texture bound to unit %u\n", u);
+			return -EINVAL;
+		}
+		size = 0;
+		for (i = 0; i <= track->textures[u].num_levels; i++) {
+			if (track->textures[u].use_pitch) {
+				w = track->textures[u].pitch / (1 << i);
+			} else {
+				w = track->textures[u].width / (1 << i);
+				if (rdev->family >= CHIP_RV515)
+					w |= track->textures[u].width_11;
+				if (track->textures[u].roundup_w)
+					w = roundup_pow_of_two(w);
+			}
+			h = track->textures[u].height / (1 << i);
+			if (rdev->family >= CHIP_RV515)
+				h |= track->textures[u].height_11;
+			if (track->textures[u].roundup_h)
+				h = roundup_pow_of_two(h);
+			size += w * h;
+		}
+		size *= track->textures[u].cpp;
+		switch (track->textures[u].tex_coord_type) {
+		case 0:
+			break;
+		case 1:
+			size *= (1 << track->textures[u].txdepth);
+			break;
+		case 2:
+			size *= 6;
+			break;
+		default:
+			DRM_ERROR("Invalid texture coordinate type %u for unit "
+				  "%u\n", track->textures[u].tex_coord_type, u);
+			return -EINVAL;
+		}
+		if (size > radeon_object_size(robj)) {
+			DRM_ERROR("Texture of unit %u needs %lu bytes but is "
+				  "%lu\n", u, size, radeon_object_size(robj));
+			r300_cs_track_texture_print(&track->textures[u]);
+			return -EINVAL;
+		}
+	}
+	return 0;
+}
+
 int r300_cs_track_check(struct radeon_device *rdev, struct r300_cs_track *track)
 {
 	unsigned i;
 	unsigned long size;
+	unsigned prim_walk;
+	unsigned nverts;
 
 	for (i = 0; i < track->num_cb; i++) {
 		if (track->cb[i].robj == NULL) {
@@ -769,7 +870,59 @@
 			return -EINVAL;
 		}
 	}
-	return 0;
+	prim_walk = (track->vap_vf_cntl >> 4) & 0x3;
+	nverts = (track->vap_vf_cntl >> 16) & 0xFFFF;
+	switch (prim_walk) {
+	case 1:
+		for (i = 0; i < track->num_arrays; i++) {
+			size = track->arrays[i].esize * track->max_indx * 4;
+			if (track->arrays[i].robj == NULL) {
+				DRM_ERROR("(PW %u) Vertex array %u no buffer "
+					  "bound\n", prim_walk, i);
+				return -EINVAL;
+			}
+			if (size > radeon_object_size(track->arrays[i].robj)) {
+				DRM_ERROR("(PW %u) Vertex array %u need %lu dwords "
+					   "have %lu dwords\n", prim_walk, i,
+					   size >> 2,
+					   radeon_object_size(track->arrays[i].robj) >> 2);
+				DRM_ERROR("Max indices %u\n", track->max_indx);
+				return -EINVAL;
+			}
+		}
+		break;
+	case 2:
+		for (i = 0; i < track->num_arrays; i++) {
+			size = track->arrays[i].esize * (nverts - 1) * 4;
+			if (track->arrays[i].robj == NULL) {
+				DRM_ERROR("(PW %u) Vertex array %u no buffer "
+					  "bound\n", prim_walk, i);
+				return -EINVAL;
+			}
+			if (size > radeon_object_size(track->arrays[i].robj)) {
+				DRM_ERROR("(PW %u) Vertex array %u need %lu dwords "
+					   "have %lu dwords\n", prim_walk, i, size >> 2,
+					   radeon_object_size(track->arrays[i].robj) >> 2);
+				return -EINVAL;
+			}
+		}
+		break;
+	case 3:
+		size = track->vtx_size * nverts;
+		if (size != track->immd_dwords) {
+			DRM_ERROR("IMMD draw %u dwors but needs %lu dwords\n",
+				  track->immd_dwords, size);
+			DRM_ERROR("VAP_VF_CNTL.NUM_VERTICES %u, VTX_SIZE %u\n",
+				  nverts, track->vtx_size);
+			return -EINVAL;
+		}
+		break;
+	default:
+		DRM_ERROR("[drm] Invalid primitive walk %d for VAP_VF_CNTL\n",
+			  prim_walk);
+		return -EINVAL;
+	}
+	return r300_cs_track_texture_check(rdev, track);
 }
 
 static inline void r300_cs_track_clear(struct r300_cs_track *track)
@@ -789,9 +942,33 @@
 	track->zb.pitch = 8192;
 	track->zb.cpp = 4;
 	track->zb.offset = 0;
+	track->vtx_size = 0x7F;
+	track->immd_dwords = 0xFFFFFFFFUL;
+	track->num_arrays = 11;
+	track->max_indx = 0x00FFFFFFUL;
+	for (i = 0; i < track->num_arrays; i++) {
+		track->arrays[i].robj = NULL;
+		track->arrays[i].esize = 0x7F;
+	}
+	for (i = 0; i < 16; i++) {
+		track->textures[i].pitch = 16536;
+		track->textures[i].width = 16536;
+		track->textures[i].height = 16536;
+		track->textures[i].width_11 = 1 << 11;
+		track->textures[i].height_11 = 1 << 11;
+		track->textures[i].num_levels = 12;
+		track->textures[i].txdepth = 16;
+		track->textures[i].cpp = 64;
+		track->textures[i].tex_coord_type = 1;
+		track->textures[i].robj = NULL;
+		/* CS IB emission code makes sure texture unit are disabled */
+		track->textures[i].enabled = false;
+		track->textures[i].roundup_w = true;
+		track->textures[i].roundup_h = true;
+	}
 }
 
-static unsigned r300_auth_reg[] = {
+static const unsigned r300_reg_safe_bm[159] = {
 	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
 	0xFFFFFFBF, 0xFFFFFFFF, 0xFFFFFFBF, 0xFFFFFFFF,
 	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
@@ -808,7 +985,7 @@
 	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
 	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFF03F,
 	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
-	0xFFFFFFFF, 0xFFFFCFCC, 0xF00E9FFF, 0x007C0000,
+	0xFFFFFFFF, 0xFFFFEFCE, 0xF00EBFFF, 0x007C0000,
 	0xF0000078, 0xFF000009, 0xFFFFFFFF, 0xFFFFFFFF,
 	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
 	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
@@ -824,9 +1001,9 @@
 	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
 	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
 	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
-	0xFFFFFC78, 0xFFFFFFFF, 0xFFFFFFFC, 0xFFFFFFFF,
+	0xFFFFFC78, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFF,
 	0x38FF8F50, 0xFFF88082, 0xF000000C, 0xFAE009FF,
-	0x00000000, 0x00000000, 0xFFFF0000, 0x00000000,
+	0x0000FFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000,
 	0x00000000, 0x0000C100, 0x00000000, 0x00000000,
 	0x00000000, 0x00000000, 0x00000000, 0x00000000,
 	0x00000000, 0xFFFF0000, 0xFFFFFFFF, 0xFF80FFFF,
@@ -848,8 +1025,8 @@
 
 	ib = p->ib->ptr;
 	ib_chunk = &p->chunks[p->chunk_ib_idx];
-	track = (struct r300_cs_track *)p->track;
-	switch (reg) {
+	track = (struct r300_cs_track*)p->track;
+	switch(reg) {
 	case RADEON_DST_PITCH_OFFSET:
 	case RADEON_SRC_PITCH_OFFSET:
 		r = r100_cs_packet_next_reloc(p, &reloc);
@@ -907,6 +1084,7 @@
 	case R300_TX_OFFSET_0+52:
 	case R300_TX_OFFSET_0+56:
 	case R300_TX_OFFSET_0+60:
+		i = (reg - R300_TX_OFFSET_0) >> 2;
 		r = r100_cs_packet_next_reloc(p, &reloc);
 		if (r) {
 			DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
@@ -915,11 +1093,23 @@
 			return r;
 		}
 		ib[idx] = ib_chunk->kdata[idx] + ((u32)reloc->lobj.gpu_offset);
+		track->textures[i].robj = reloc->robj;
 		break;
 	/* Tracked registers */
+	case 0x2084:
+		/* VAP_VF_CNTL */
+		track->vap_vf_cntl = ib_chunk->kdata[idx];
+		break;
+	case 0x20B4:
+		/* VAP_VTX_SIZE */
+		track->vtx_size = ib_chunk->kdata[idx] & 0x7F;
+		break;
+	case 0x2134:
+		/* VAP_VF_MAX_VTX_INDX */
+		track->max_indx = ib_chunk->kdata[idx] & 0x00FFFFFFUL;
+		break;
 	case 0x43E4:
 		/* SC_SCISSOR1 */
-
 		track->maxy = ((ib_chunk->kdata[idx] >> 13) & 0x1FFF) + 1;
 		if (p->rdev->family < CHIP_RV515) {
 			track->maxy -= 1440;
@@ -994,8 +1184,166 @@
 		/* ZB_DEPTHPITCH */
 		track->zb.pitch = ib_chunk->kdata[idx] & 0x3FFC;
 		break;
+	case 0x4104:
+		for (i = 0; i < 16; i++) {
+			bool enabled;
+
+			enabled = !!(ib_chunk->kdata[idx] & (1 << i));
+			track->textures[i].enabled = enabled;
+		}
+		break;
+	case 0x44C0:
+	case 0x44C4:
+	case 0x44C8:
+	case 0x44CC:
+	case 0x44D0:
+	case 0x44D4:
+	case 0x44D8:
+	case 0x44DC:
+	case 0x44E0:
+	case 0x44E4:
+	case 0x44E8:
+	case 0x44EC:
+	case 0x44F0:
+	case 0x44F4:
+	case 0x44F8:
+	case 0x44FC:
+		/* TX_FORMAT1_[0-15] */
+		i = (reg - 0x44C0) >> 2;
+		tmp = (ib_chunk->kdata[idx] >> 25) & 0x3;
+		track->textures[i].tex_coord_type = tmp;
+		switch ((ib_chunk->kdata[idx] & 0x1F)) {
+		case 0:
+		case 2:
+		case 5:
+		case 18:
+		case 20:
+		case 21:
+			track->textures[i].cpp = 1;
+			break;
+		case 1:
+		case 3:
+		case 6:
+		case 7:
+		case 10:
+		case 11:
+		case 19:
+		case 22:
+		case 24:
+			track->textures[i].cpp = 2;
+			break;
+		case 4:
+		case 8:
+		case 9:
+		case 12:
+		case 13:
+		case 23:
+		case 25:
+		case 27:
+		case 30:
+			track->textures[i].cpp = 4;
+			break;
+		case 14:
+		case 26:
+		case 28:
+			track->textures[i].cpp = 8;
+			break;
+		case 29:
+			track->textures[i].cpp = 16;
+			break;
+		default:
+			DRM_ERROR("Invalid texture format %u\n",
+				  (ib_chunk->kdata[idx] & 0x1F));
+			return -EINVAL;
+			break;
+		}
+		break;
+	case 0x4400:
+	case 0x4404:
+	case 0x4408:
+	case 0x440C:
+	case 0x4410:
+	case 0x4414:
+	case 0x4418:
+	case 0x441C:
+	case 0x4420:
+	case 0x4424:
+	case 0x4428:
+	case 0x442C:
+	case 0x4430:
+	case 0x4434:
+	case 0x4438:
+	case 0x443C:
+		/* TX_FILTER0_[0-15] */
+		i = (reg - 0x4400) >> 2;
+		tmp = ib_chunk->kdata[idx] & 0x7;;
+		if (tmp == 2 || tmp == 4 || tmp == 6) {
+			track->textures[i].roundup_w = false;
+		}
+		tmp = (ib_chunk->kdata[idx] >> 3) & 0x7;;
+		if (tmp == 2 || tmp == 4 || tmp == 6) {
+			track->textures[i].roundup_h = false;
+		}
+		break;
+	case 0x4500:
+	case 0x4504:
+	case 0x4508:
+	case 0x450C:
+	case 0x4510:
+	case 0x4514:
+	case 0x4518:
+	case 0x451C:
+	case 0x4520:
+	case 0x4524:
+	case 0x4528:
+	case 0x452C:
+	case 0x4530:
+	case 0x4534:
+	case 0x4538:
+	case 0x453C:
+		/* TX_FORMAT2_[0-15] */
+		i = (reg - 0x4500) >> 2;
+		tmp = ib_chunk->kdata[idx] & 0x3FFF;
+		track->textures[i].pitch = tmp + 1;
+		if (p->rdev->family >= CHIP_RV515) {
+			tmp = ((ib_chunk->kdata[idx] >> 15) & 1) << 11;
+			track->textures[i].width_11 = tmp;
+			tmp = ((ib_chunk->kdata[idx] >> 16) & 1) << 11;
+			track->textures[i].height_11 = tmp;
+		}
+		break;
+	case 0x4480:
+	case 0x4484:
+	case 0x4488:
+	case 0x448C:
+	case 0x4490:
+	case 0x4494:
+	case 0x4498:
+	case 0x449C:
+	case 0x44A0:
+	case 0x44A4:
+	case 0x44A8:
+	case 0x44AC:
+	case 0x44B0:
+	case 0x44B4:
+	case 0x44B8:
+	case 0x44BC:
+		/* TX_FORMAT0_[0-15] */
+		i = (reg - 0x4480) >> 2;
+		tmp = ib_chunk->kdata[idx] & 0x7FF;
+		track->textures[i].width = tmp + 1;
+		tmp = (ib_chunk->kdata[idx] >> 11) & 0x7FF;
+		track->textures[i].height = tmp + 1;
+		tmp = (ib_chunk->kdata[idx] >> 26) & 0xF;
+		track->textures[i].num_levels = tmp;
+		tmp = ib_chunk->kdata[idx] & (1 << 31);
+		track->textures[i].use_pitch = !!tmp;
+		tmp = (ib_chunk->kdata[idx] >> 22) & 0xF;
+		track->textures[i].txdepth = tmp;
+		break;
 	default:
-		printk(KERN_ERR "Forbidden register 0x%04X in cs at %d\n", reg, idx);
+		printk(KERN_ERR "Forbidden register 0x%04X in cs at %d\n",
+		       reg, idx);
 		return -EINVAL;
 	}
 	return 0;
@@ -1015,11 +1363,12 @@
 	ib = p->ib->ptr;
 	ib_chunk = &p->chunks[p->chunk_ib_idx];
 	idx = pkt->idx + 1;
-	track = (struct r300_cs_track *)p->track;
-	switch (pkt->opcode) {
+	track = (struct r300_cs_track*)p->track;
+	switch(pkt->opcode) {
 	case PACKET3_3D_LOAD_VBPNTR:
-		c = ib_chunk->kdata[idx++];
-		for (i = 0; i < (c - 1); i += 2, idx += 3) {
+		c = ib_chunk->kdata[idx++] & 0x1F;
+		track->num_arrays = c;
+		for (i = 0; i < (c - 1); i+=2, idx+=3) {
 			r = r100_cs_packet_next_reloc(p, &reloc);
 			if (r) {
 				DRM_ERROR("No reloc for packet3 %d\n",
@@ -1028,6 +1377,9 @@
 				return r;
 			}
 			ib[idx+1] = ib_chunk->kdata[idx+1] + ((u32)reloc->lobj.gpu_offset);
+			track->arrays[i + 0].robj = reloc->robj;
+			track->arrays[i + 0].esize = ib_chunk->kdata[idx] >> 8;
+			track->arrays[i + 0].esize &= 0x7F;
 			r = r100_cs_packet_next_reloc(p, &reloc);
 			if (r) {
 				DRM_ERROR("No reloc for packet3 %d\n",
@@ -1036,6 +1388,9 @@
 				return r;
 			}
 			ib[idx+2] = ib_chunk->kdata[idx+2] + ((u32)reloc->lobj.gpu_offset);
+			track->arrays[i + 1].robj = reloc->robj;
+			track->arrays[i + 1].esize = ib_chunk->kdata[idx] >> 24;
+			track->arrays[i + 1].esize &= 0x7F;
 		}
 		if (c & 1) {
 			r = r100_cs_packet_next_reloc(p, &reloc);
@@ -1046,6 +1401,9 @@
 				return r;
 			}
 			ib[idx+1] = ib_chunk->kdata[idx+1] + ((u32)reloc->lobj.gpu_offset);
+			track->arrays[i + 0].robj = reloc->robj;
+			track->arrays[i + 0].esize = ib_chunk->kdata[idx] >> 8;
+			track->arrays[i + 0].esize &= 0x7F;
 		}
 		break;
 	case PACKET3_INDX_BUFFER:
@@ -1056,14 +1414,65 @@
 			return r;
 		}
 		ib[idx+1] = ib_chunk->kdata[idx+1] + ((u32)reloc->lobj.gpu_offset);
+		r = r100_cs_track_check_pkt3_indx_buffer(p, pkt, reloc->robj);
+		if (r) {
+			return r;
+		}
 		break;
 	/* Draw packet */
-	case PACKET3_3D_DRAW_VBUF:
 	case PACKET3_3D_DRAW_IMMD:
-	case PACKET3_3D_DRAW_INDX:
-	case PACKET3_3D_DRAW_VBUF_2:
+		/* Number of dwords is vtx_size * (num_vertices - 1)
+		 * PRIM_WALK must be equal to 3 vertex data in embedded
+		 * in cmd stream */
+		if (((ib_chunk->kdata[idx+1] >> 4) & 0x3) != 3) {
+			DRM_ERROR("PRIM_WALK must be 3 for IMMD draw\n");
+			return -EINVAL;
+		}
+		track->vap_vf_cntl = ib_chunk->kdata[idx+1];
+		track->immd_dwords = pkt->count - 1;
+		r = r300_cs_track_check(p->rdev, track);
+		if (r) {
+			return r;
+		}
+		break;
 	case PACKET3_3D_DRAW_IMMD_2:
+		/* Number of dwords is vtx_size * (num_vertices - 1)
+		 * PRIM_WALK must be equal to 3 vertex data in embedded
+		 * in cmd stream */
+		if (((ib_chunk->kdata[idx] >> 4) & 0x3) != 3) {
+			DRM_ERROR("PRIM_WALK must be 3 for IMMD draw\n");
+			return -EINVAL;
+		}
+		track->vap_vf_cntl = ib_chunk->kdata[idx];
+		track->immd_dwords = pkt->count;
+		r = r300_cs_track_check(p->rdev, track);
+		if (r) {
+			return r;
+		}
+		break;
+	case PACKET3_3D_DRAW_VBUF:
+		track->vap_vf_cntl = ib_chunk->kdata[idx + 1];
+		r = r300_cs_track_check(p->rdev, track);
+		if (r) {
+			return r;
+		}
+		break;
+	case PACKET3_3D_DRAW_VBUF_2:
+		track->vap_vf_cntl = ib_chunk->kdata[idx];
+		r = r300_cs_track_check(p->rdev, track);
+		if (r) {
+			return r;
+		}
+		break;
+	case PACKET3_3D_DRAW_INDX:
+		track->vap_vf_cntl = ib_chunk->kdata[idx + 1];
+		r = r300_cs_track_check(p->rdev, track);
+		if (r) {
+			return r;
+		}
+		break;
 	case PACKET3_3D_DRAW_INDX_2:
+		track->vap_vf_cntl = ib_chunk->kdata[idx];
 		r = r300_cs_track_check(p->rdev, track);
 		if (r) {
 			return r;
@@ -1095,8 +1504,8 @@
 		switch (pkt.type) {
 		case PACKET_TYPE0:
 			r = r100_cs_parse_packet0(p, &pkt,
-						  r300_auth_reg,
-						  ARRAY_SIZE(r300_auth_reg),
+						  p->rdev->config.r300.reg_safe_bm,
+						  p->rdev->config.r300.reg_safe_bm_size,
 						  &r300_packet0_check);
 			break;
 		case PACKET_TYPE2:
@@ -1114,3 +1523,10 @@
 	} while (p->idx < p->chunks[p->chunk_ib_idx].length_dw);
 	return 0;
 }
+
+int r300_init(struct radeon_device *rdev)
+{
+	rdev->config.r300.reg_safe_bm = r300_reg_safe_bm;
+	rdev->config.r300.reg_safe_bm_size = ARRAY_SIZE(r300_reg_safe_bm);
+	return 0;
+}
diff --git a/drivers/gpu/drm/radeon/r300.h b/drivers/gpu/drm/radeon/r300.h
new file mode 100644
index 0000000..8486b4d
--- /dev/null
+++ b/drivers/gpu/drm/radeon/r300.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2008 Advanced Micro Devices, Inc.
+ * Copyright 2008 Red Hat Inc.
+ * Copyright 2009 Jerome Glisse.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Authors: Dave Airlie
+ *          Alex Deucher
+ *          Jerome Glisse
+ */
+#ifndef R300_H
+#define R300_H
+
+struct r300_asic {
+	const unsigned	*reg_safe_bm;
+	unsigned	reg_safe_bm_size;
+};
+
+#endif
diff --git a/drivers/gpu/drm/radeon/radeon.h b/drivers/gpu/drm/radeon/radeon.h
index c3f24cc..d61f2fc 100644
--- a/drivers/gpu/drm/radeon/radeon.h
+++ b/drivers/gpu/drm/radeon/radeon.h
@@ -51,7 +51,7 @@
 
 #include "radeon_mode.h"
 #include "radeon_reg.h"
-
+#include "r300.h"
 
 /*
  * Modules parameters.
@@ -496,6 +496,7 @@
  * ASIC specific functions.
  */
 struct radeon_asic {
+	int (*init)(struct radeon_device *rdev);
 	void (*errata)(struct radeon_device *rdev);
 	void (*vram_info)(struct radeon_device *rdev);
 	int (*gpu_reset)(struct radeon_device *rdev);
@@ -536,6 +537,10 @@
 	void (*set_clock_gating)(struct radeon_device *rdev, int enable);
 };
 
+union radeon_asic_config {
+	struct r300_asic	r300;
+};
+
 
 /*
  * IOCTL.
@@ -573,6 +578,7 @@
 	struct drm_device		*ddev;
 	struct pci_dev			*pdev;
 	/* ASIC */
+	union radeon_asic_config	config;
 	enum radeon_family		family;
 	unsigned long			flags;
 	int				usec_timeout;
@@ -763,6 +769,7 @@
 /*
  * ASICs macro.
  */
+#define radeon_init(rdev) (rdev)->asic->init((rdev))
 #define radeon_cs_parse(p) rdev->asic->cs_parse((p))
 #define radeon_errata(rdev) (rdev)->asic->errata((rdev))
 #define radeon_vram_info(rdev) (rdev)->asic->vram_info((rdev))
diff --git a/drivers/gpu/drm/radeon/radeon_asic.h b/drivers/gpu/drm/radeon/radeon_asic.h
index e57d8a7..e2e5673 100644
--- a/drivers/gpu/drm/radeon/radeon_asic.h
+++ b/drivers/gpu/drm/radeon/radeon_asic.h
@@ -41,6 +41,7 @@
 /*
  * r100,rv100,rs100,rv200,rs200,r200,rv250,rs300,rv280
  */
+int r100_init(struct radeon_device *rdev);
 uint32_t r100_mm_rreg(struct radeon_device *rdev, uint32_t reg);
 void r100_mm_wreg(struct radeon_device *rdev, uint32_t reg, uint32_t v);
 void r100_errata(struct radeon_device *rdev);
@@ -72,6 +73,7 @@
 		   struct radeon_fence *fence);
 
 static struct radeon_asic r100_asic = {
+	.init = &r100_init,
 	.errata = &r100_errata,
 	.vram_info = &r100_vram_info,
 	.gpu_reset = &r100_gpu_reset,
@@ -104,6 +106,7 @@
 /*
  * r300,r350,rv350,rv380
  */
+int r300_init(struct radeon_device *rdev);
 void r300_errata(struct radeon_device *rdev);
 void r300_vram_info(struct radeon_device *rdev);
 int r300_gpu_reset(struct radeon_device *rdev);
@@ -126,6 +129,7 @@
 		  unsigned num_pages,
 		  struct radeon_fence *fence);
 static struct radeon_asic r300_asic = {
+	.init = &r300_init,
 	.errata = &r300_errata,
 	.vram_info = &r300_vram_info,
 	.gpu_reset = &r300_gpu_reset,
@@ -162,6 +166,7 @@
 int r420_mc_init(struct radeon_device *rdev);
 void r420_mc_fini(struct radeon_device *rdev);
 static struct radeon_asic r420_asic = {
+	.init = &r300_init,
 	.errata = &r420_errata,
 	.vram_info = &r420_vram_info,
 	.gpu_reset = &r300_gpu_reset,
@@ -205,6 +210,7 @@
 uint32_t rs400_mc_rreg(struct radeon_device *rdev, uint32_t reg);
 void rs400_mc_wreg(struct radeon_device *rdev, uint32_t reg, uint32_t v);
 static struct radeon_asic rs400_asic = {
+	.init = &r300_init,
 	.errata = &rs400_errata,
 	.vram_info = &rs400_vram_info,
 	.gpu_reset = &r300_gpu_reset,
@@ -249,6 +255,7 @@
 uint32_t rs600_mc_rreg(struct radeon_device *rdev, uint32_t reg);
 void rs600_mc_wreg(struct radeon_device *rdev, uint32_t reg, uint32_t v);
 static struct radeon_asic rs600_asic = {
+	.init = &r300_init,
 	.errata = &rs600_errata,
 	.vram_info = &rs600_vram_info,
 	.gpu_reset = &r300_gpu_reset,
@@ -288,6 +295,7 @@
 uint32_t rs690_mc_rreg(struct radeon_device *rdev, uint32_t reg);
 void rs690_mc_wreg(struct radeon_device *rdev, uint32_t reg, uint32_t v);
 static struct radeon_asic rs690_asic = {
+	.init = &r300_init,
 	.errata = &rs690_errata,
 	.vram_info = &rs690_vram_info,
 	.gpu_reset = &r300_gpu_reset,
@@ -320,6 +328,7 @@
 /*
  * rv515
  */
+int rv515_init(struct radeon_device *rdev);
 void rv515_errata(struct radeon_device *rdev);
 void rv515_vram_info(struct radeon_device *rdev);
 int rv515_gpu_reset(struct radeon_device *rdev);
@@ -331,6 +340,7 @@
 uint32_t rv515_pcie_rreg(struct radeon_device *rdev, uint32_t reg);
 void rv515_pcie_wreg(struct radeon_device *rdev, uint32_t reg, uint32_t v);
 static struct radeon_asic rv515_asic = {
+	.init = &rv515_init,
 	.errata = &rv515_errata,
 	.vram_info = &rv515_vram_info,
 	.gpu_reset = &rv515_gpu_reset,
@@ -349,7 +359,7 @@
 	.irq_set = &r100_irq_set,
 	.irq_process = &r100_irq_process,
 	.fence_ring_emit = &r300_fence_ring_emit,
-	.cs_parse = &r100_cs_parse,
+	.cs_parse = &r300_cs_parse,
 	.copy_blit = &r100_copy_blit,
 	.copy_dma = &r300_copy_dma,
 	.copy = &r100_copy_blit,
@@ -368,6 +378,7 @@
 int r520_mc_init(struct radeon_device *rdev);
 void r520_mc_fini(struct radeon_device *rdev);
 static struct radeon_asic r520_asic = {
+	.init = &rv515_init,
 	.errata = &r520_errata,
 	.vram_info = &r520_vram_info,
 	.gpu_reset = &rv515_gpu_reset,
@@ -386,7 +397,7 @@
 	.irq_set = &r100_irq_set,
 	.irq_process = &r100_irq_process,
 	.fence_ring_emit = &r300_fence_ring_emit,
-	.cs_parse = &r100_cs_parse,
+	.cs_parse = &r300_cs_parse,
 	.copy_blit = &r100_copy_blit,
 	.copy_dma = &r300_copy_dma,
 	.copy = &r100_copy_blit,
diff --git a/drivers/gpu/drm/radeon/radeon_atombios.c b/drivers/gpu/drm/radeon/radeon_atombios.c
index 786632d..1f5a1a4 100644
--- a/drivers/gpu/drm/radeon/radeon_atombios.c
+++ b/drivers/gpu/drm/radeon/radeon_atombios.c
@@ -835,7 +835,6 @@
 	struct _COMPASSIONATE_DATA *dac_info;
 	uint8_t frev, crev;
 	uint8_t bg, dac;
-	int i;
 	struct radeon_encoder_primary_dac *p_dac = NULL;
 
 	atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset);
@@ -867,7 +866,6 @@
 	struct _COMPASSIONATE_DATA *dac_info;
 	uint8_t frev, crev;
 	uint8_t bg, dac;
-	int i;
 	struct radeon_encoder_tv_dac *tv_dac = NULL;
 
 	atom_parse_data_header(mode_info->atom_context, index, NULL, &frev, &crev, &data_offset);
diff --git a/drivers/gpu/drm/radeon/radeon_combios.c b/drivers/gpu/drm/radeon/radeon_combios.c
index 06e8038..afc4db2 100644
--- a/drivers/gpu/drm/radeon/radeon_combios.c
+++ b/drivers/gpu/drm/radeon/radeon_combios.c
@@ -799,6 +799,7 @@
 	struct radeon_encoder_lvds *lvds = NULL;
 	uint32_t fp_vert_stretch, fp_horz_stretch;
 	uint32_t ppll_div_sel, ppll_val;
+	uint32_t lvds_ss_gen_cntl = RREG32(RADEON_LVDS_SS_GEN_CNTL);
 
 	lvds = kzalloc(sizeof(struct radeon_encoder_lvds), GFP_KERNEL);
 
@@ -808,6 +809,14 @@
 	fp_vert_stretch = RREG32(RADEON_FP_VERT_STRETCH);
 	fp_horz_stretch = RREG32(RADEON_FP_HORZ_STRETCH);
 
+	/* These should be fail-safe defaults, fingers crossed */
+	lvds->panel_pwr_delay = 200;
+	lvds->panel_vcc_delay = 2000;
+
+	lvds->lvds_gen_cntl = RREG32(RADEON_LVDS_GEN_CNTL);
+	lvds->panel_digon_delay = (lvds_ss_gen_cntl >> RADEON_LVDS_PWRSEQ_DELAY1_SHIFT) & 0xf;
+	lvds->panel_blon_delay = (lvds_ss_gen_cntl >> RADEON_LVDS_PWRSEQ_DELAY2_SHIFT) & 0xf;
+
 	if (fp_vert_stretch & RADEON_VERT_STRETCH_ENABLE)
 		lvds->native_mode.panel_yres =
 		    ((fp_vert_stretch & RADEON_VERT_PANEL_SIZE) >>
diff --git a/drivers/gpu/drm/radeon/radeon_cp.c b/drivers/gpu/drm/radeon/radeon_cp.c
index 89c4c44..d835682 100644
--- a/drivers/gpu/drm/radeon/radeon_cp.c
+++ b/drivers/gpu/drm/radeon/radeon_cp.c
@@ -2045,11 +2045,10 @@
 	drm_radeon_private_t *dev_priv;
 	int ret = 0;
 
-	dev_priv = drm_alloc(sizeof(drm_radeon_private_t), DRM_MEM_DRIVER);
+	dev_priv = kzalloc(sizeof(drm_radeon_private_t), GFP_KERNEL);
 	if (dev_priv == NULL)
 		return -ENOMEM;
 
-	memset(dev_priv, 0, sizeof(drm_radeon_private_t));
 	dev->dev_private = (void *)dev_priv;
 	dev_priv->flags = flags;
 
@@ -2103,7 +2102,7 @@
 	unsigned long sareapage;
 	int ret;
 
-	master_priv = drm_calloc(1, sizeof(*master_priv), DRM_MEM_DRIVER);
+	master_priv = kzalloc(sizeof(*master_priv), GFP_KERNEL);
 	if (!master_priv)
 		return -ENOMEM;
 
@@ -2137,7 +2136,7 @@
 	if (master_priv->sarea)
 		drm_rmmap_locked(dev, master_priv->sarea);
 
-	drm_free(master_priv, sizeof(*master_priv), DRM_MEM_DRIVER);
+	kfree(master_priv);
 
 	master->driver_priv = NULL;
 }
@@ -2171,7 +2170,7 @@
 
 	drm_rmmap(dev, dev_priv->mmio);
 
-	drm_free(dev_priv, sizeof(*dev_priv), DRM_MEM_DRIVER);
+	kfree(dev_priv);
 
 	dev->dev_private = NULL;
 	return 0;
diff --git a/drivers/gpu/drm/radeon/radeon_device.c b/drivers/gpu/drm/radeon/radeon_device.c
index 5fd2b63..f30aa72 100644
--- a/drivers/gpu/drm/radeon/radeon_device.c
+++ b/drivers/gpu/drm/radeon/radeon_device.c
@@ -470,6 +470,10 @@
 	if (r) {
 		return r;
 	}
+	r = radeon_init(rdev);
+	if (r) {
+		return r;
+	}
 
 	/* Report DMA addressing limitation */
 	r = pci_set_dma_mask(rdev->pdev, DMA_BIT_MASK(32));
diff --git a/drivers/gpu/drm/radeon/radeon_display.c b/drivers/gpu/drm/radeon/radeon_display.c
index 5452bb9..3efcf1a 100644
--- a/drivers/gpu/drm/radeon/radeon_display.c
+++ b/drivers/gpu/drm/radeon/radeon_display.c
@@ -351,7 +351,7 @@
 	radeon_i2c_do_lock(radeon_connector, 0);
 	if (edid) {
 		/* update digital bits here */
-		if (edid->digital)
+		if (edid->input & DRM_EDID_INPUT_DIGITAL)
 			radeon_connector->use_digital = 1;
 		else
 			radeon_connector->use_digital = 0;
diff --git a/drivers/gpu/drm/radeon/radeon_drv.c b/drivers/gpu/drm/radeon/radeon_drv.c
index c815a2c..09c9fb9 100644
--- a/drivers/gpu/drm/radeon/radeon_drv.c
+++ b/drivers/gpu/drm/radeon/radeon_drv.c
@@ -313,7 +313,7 @@
 {
 	driver = &driver_old;
 	driver->num_ioctls = radeon_max_ioctl;
-#if defined(CONFIG_DRM_RADEON_KMS) && defined(CONFIG_X86)
+#if defined(CONFIG_DRM_RADEON_KMS)
 	/* if enabled by default */
 	if (radeon_modeset == -1) {
 		DRM_INFO("radeon default to kernel modesetting.\n");
diff --git a/drivers/gpu/drm/radeon/radeon_i2c.c b/drivers/gpu/drm/radeon/radeon_i2c.c
index 71465ed..dd438d3 100644
--- a/drivers/gpu/drm/radeon/radeon_i2c.c
+++ b/drivers/gpu/drm/radeon/radeon_i2c.c
@@ -162,7 +162,7 @@
 	struct radeon_i2c_chan *i2c;
 	int ret;
 
-	i2c = drm_calloc(1, sizeof(struct radeon_i2c_chan), DRM_MEM_DRIVER);
+	i2c = kzalloc(sizeof(struct radeon_i2c_chan), GFP_KERNEL);
 	if (i2c == NULL)
 		return NULL;
 
@@ -189,7 +189,7 @@
 
 	return i2c;
 out_free:
-	drm_free(i2c, sizeof(struct radeon_i2c_chan), DRM_MEM_DRIVER);
+	kfree(i2c);
 	return NULL;
 
 }
@@ -200,7 +200,7 @@
 		return;
 
 	i2c_del_adapter(&i2c->adapter);
-	drm_free(i2c, sizeof(struct radeon_i2c_chan), DRM_MEM_DRIVER);
+	kfree(i2c);
 }
 
 struct drm_encoder *radeon_best_encoder(struct drm_connector *connector)
diff --git a/drivers/gpu/drm/radeon/radeon_kms.c b/drivers/gpu/drm/radeon/radeon_kms.c
index b0ce44b..4612a7c 100644
--- a/drivers/gpu/drm/radeon/radeon_kms.c
+++ b/drivers/gpu/drm/radeon/radeon_kms.c
@@ -169,14 +169,14 @@
 	unsigned long sareapage;
 	int ret;
 
-	master_priv = drm_calloc(1, sizeof(*master_priv), DRM_MEM_DRIVER);
+	master_priv = kzalloc(sizeof(*master_priv), GFP_KERNEL);
 	if (master_priv == NULL) {
 		return -ENOMEM;
 	}
 	/* prebuild the SAREA */
 	sareapage = max_t(unsigned long, SAREA_MAX, PAGE_SIZE);
 	ret = drm_addmap(dev, 0, sareapage, _DRM_SHM,
-			 _DRM_CONTAINS_LOCK|_DRM_DRIVER,
+			 _DRM_CONTAINS_LOCK,
 			 &master_priv->sarea);
 	if (ret) {
 		DRM_ERROR("SAREA setup failed\n");
@@ -199,7 +199,7 @@
 	if (master_priv->sarea) {
 		drm_rmmap_locked(dev, master_priv->sarea);
 	}
-	drm_free(master_priv, sizeof(*master_priv), DRM_MEM_DRIVER);
+	kfree(master_priv);
 	master->driver_priv = NULL;
 }
 
diff --git a/drivers/gpu/drm/radeon/radeon_mem.c b/drivers/gpu/drm/radeon/radeon_mem.c
index 4af5286..ed95155 100644
--- a/drivers/gpu/drm/radeon/radeon_mem.c
+++ b/drivers/gpu/drm/radeon/radeon_mem.c
@@ -43,8 +43,8 @@
 {
 	/* Maybe cut off the start of an existing block */
 	if (start > p->start) {
-		struct mem_block *newblock =
-		    drm_alloc(sizeof(*newblock), DRM_MEM_BUFS);
+		struct mem_block *newblock = kmalloc(sizeof(*newblock),
+						     GFP_KERNEL);
 		if (!newblock)
 			goto out;
 		newblock->start = start;
@@ -60,8 +60,8 @@
 
 	/* Maybe cut off the end of an existing block */
 	if (size < p->size) {
-		struct mem_block *newblock =
-		    drm_alloc(sizeof(*newblock), DRM_MEM_BUFS);
+		struct mem_block *newblock = kmalloc(sizeof(*newblock),
+						     GFP_KERNEL);
 		if (!newblock)
 			goto out;
 		newblock->start = start + size;
@@ -118,7 +118,7 @@
 		p->size += q->size;
 		p->next = q->next;
 		p->next->prev = p;
-		drm_free(q, sizeof(*q), DRM_MEM_BUFS);
+		kfree(q);
 	}
 
 	if (p->prev->file_priv == NULL) {
@@ -126,7 +126,7 @@
 		q->size += p->size;
 		q->next = p->next;
 		q->next->prev = q;
-		drm_free(p, sizeof(*q), DRM_MEM_BUFS);
+		kfree(p);
 	}
 }
 
@@ -134,14 +134,14 @@
  */
 static int init_heap(struct mem_block **heap, int start, int size)
 {
-	struct mem_block *blocks = drm_alloc(sizeof(*blocks), DRM_MEM_BUFS);
+	struct mem_block *blocks = kmalloc(sizeof(*blocks), GFP_KERNEL);
 
 	if (!blocks)
 		return -ENOMEM;
 
-	*heap = drm_alloc(sizeof(**heap), DRM_MEM_BUFS);
+	*heap = kmalloc(sizeof(**heap), GFP_KERNEL);
 	if (!*heap) {
-		drm_free(blocks, sizeof(*blocks), DRM_MEM_BUFS);
+		kfree(blocks);
 		return -ENOMEM;
 	}
 
@@ -179,7 +179,7 @@
 			p->size += q->size;
 			p->next = q->next;
 			p->next->prev = p;
-			drm_free(q, sizeof(*q), DRM_MEM_DRIVER);
+			kfree(q);
 		}
 	}
 }
@@ -196,10 +196,10 @@
 	for (p = (*heap)->next; p != *heap;) {
 		struct mem_block *q = p;
 		p = p->next;
-		drm_free(q, sizeof(*q), DRM_MEM_DRIVER);
+		kfree(q);
 	}
 
-	drm_free(*heap, sizeof(**heap), DRM_MEM_DRIVER);
+	kfree(*heap);
 	*heap = NULL;
 }
 
diff --git a/drivers/gpu/drm/radeon/radeon_reg.h b/drivers/gpu/drm/radeon/radeon_reg.h
index 6d3d904..e1b6185 100644
--- a/drivers/gpu/drm/radeon/radeon_reg.h
+++ b/drivers/gpu/drm/radeon/radeon_reg.h
@@ -3184,6 +3184,7 @@
 #	define RADEON_RB_BUFSZ_MASK		(0x3f << 0)
 #	define RADEON_RB_BLKSZ_SHIFT		8
 #	define RADEON_RB_BLKSZ_MASK		(0x3f << 8)
+#	define RADEON_BUF_SWAP_32BIT		(1 << 17)
 #	define RADEON_MAX_FETCH_SHIFT		18
 #	define RADEON_MAX_FETCH_MASK		(0x3 << 18)
 #	define RADEON_RB_NO_UPDATE		(1 << 27)
diff --git a/drivers/gpu/drm/radeon/radeon_state.c b/drivers/gpu/drm/radeon/radeon_state.c
index fa728ec..46645f3 100644
--- a/drivers/gpu/drm/radeon/radeon_state.c
+++ b/drivers/gpu/drm/radeon/radeon_state.c
@@ -2866,12 +2866,12 @@
 	 */
 	orig_bufsz = cmdbuf->bufsz;
 	if (orig_bufsz != 0) {
-		kbuf = drm_alloc(cmdbuf->bufsz, DRM_MEM_DRIVER);
+		kbuf = kmalloc(cmdbuf->bufsz, GFP_KERNEL);
 		if (kbuf == NULL)
 			return -ENOMEM;
 		if (DRM_COPY_FROM_USER(kbuf, (void __user *)cmdbuf->buf,
 				       cmdbuf->bufsz)) {
-			drm_free(kbuf, orig_bufsz, DRM_MEM_DRIVER);
+			kfree(kbuf);
 			return -EFAULT;
 		}
 		cmdbuf->buf = kbuf;
@@ -2884,7 +2884,7 @@
 		temp = r300_do_cp_cmdbuf(dev, file_priv, cmdbuf);
 
 		if (orig_bufsz != 0)
-			drm_free(kbuf, orig_bufsz, DRM_MEM_DRIVER);
+			kfree(kbuf);
 
 		return temp;
 	}
@@ -2991,7 +2991,7 @@
 	}
 
 	if (orig_bufsz != 0)
-		drm_free(kbuf, orig_bufsz, DRM_MEM_DRIVER);
+		kfree(kbuf);
 
 	DRM_DEBUG("DONE\n");
 	COMMIT_RING();
@@ -2999,7 +2999,7 @@
 
       err:
 	if (orig_bufsz != 0)
-		drm_free(kbuf, orig_bufsz, DRM_MEM_DRIVER);
+		kfree(kbuf);
 	return -EINVAL;
 }
 
@@ -3175,9 +3175,7 @@
 	struct drm_radeon_driver_file_fields *radeon_priv;
 
 	DRM_DEBUG("\n");
-	radeon_priv =
-	    (struct drm_radeon_driver_file_fields *)
-	    drm_alloc(sizeof(*radeon_priv), DRM_MEM_FILES);
+	radeon_priv = kmalloc(sizeof(*radeon_priv), GFP_KERNEL);
 
 	if (!radeon_priv)
 		return -ENOMEM;
@@ -3196,7 +3194,7 @@
 	struct drm_radeon_driver_file_fields *radeon_priv =
 	    file_priv->driver_priv;
 
-	drm_free(radeon_priv, sizeof(*radeon_priv), DRM_MEM_FILES);
+	kfree(radeon_priv);
 }
 
 struct drm_ioctl_desc radeon_ioctls[] = {
diff --git a/drivers/gpu/drm/radeon/radeon_ttm.c b/drivers/gpu/drm/radeon/radeon_ttm.c
index 4c087c1..1227a97 100644
--- a/drivers/gpu/drm/radeon/radeon_ttm.c
+++ b/drivers/gpu/drm/radeon/radeon_ttm.c
@@ -133,6 +133,7 @@
 		man->gpu_offset = 0;
 		man->available_caching = TTM_PL_MASK_CACHING;
 		man->default_caching = TTM_PL_FLAG_CACHED;
+		man->flags = TTM_MEMTYPE_FLAG_MAPPABLE | TTM_MEMTYPE_FLAG_CMA;
 #if __OS_HAS_AGP
 		if (rdev->flags & RADEON_IS_AGP) {
 			if (!(drm_core_has_AGP(rdev->ddev) && rdev->ddev->agp)) {
@@ -143,8 +144,9 @@
 			man->io_offset = rdev->mc.agp_base;
 			man->io_size = rdev->mc.gtt_size;
 			man->io_addr = NULL;
-			man->flags = TTM_MEMTYPE_FLAG_NEEDS_IOREMAP |
-				     TTM_MEMTYPE_FLAG_MAPPABLE;
+			if (!rdev->ddev->agp->cant_use_aperture)
+				man->flags = TTM_MEMTYPE_FLAG_NEEDS_IOREMAP |
+					     TTM_MEMTYPE_FLAG_MAPPABLE;
 			man->available_caching = TTM_PL_FLAG_UNCACHED |
 						 TTM_PL_FLAG_WC;
 			man->default_caching = TTM_PL_FLAG_WC;
@@ -154,8 +156,6 @@
 			man->io_offset = 0;
 			man->io_size = 0;
 			man->io_addr = NULL;
-			man->flags = TTM_MEMTYPE_FLAG_MAPPABLE |
-				     TTM_MEMTYPE_FLAG_CMA;
 		}
 		break;
 	case TTM_PL_VRAM:
diff --git a/drivers/gpu/drm/radeon/rv515.c b/drivers/gpu/drm/radeon/rv515.c
index 7eab95d..ffea37b 100644
--- a/drivers/gpu/drm/radeon/rv515.c
+++ b/drivers/gpu/drm/radeon/rv515.c
@@ -225,6 +225,8 @@
 	radeon_ring_write(rdev,
 			  R300_GEOMETRY_ROUND_NEAREST |
 			  R300_COLOR_ROUND_NEAREST);
+	radeon_ring_write(rdev, PACKET0(0x20C8, 0));
+	radeon_ring_write(rdev, 0);
 	radeon_ring_unlock_commit(rdev);
 }
 
@@ -502,3 +504,59 @@
 	return 0;
 #endif
 }
+
+
+/*
+ * Asic initialization
+ */
+static const unsigned r500_reg_safe_bm[159] = {
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFBF, 0xFFFFFFFF, 0xFFFFFFBF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0x17FF1FFF, 0xFFFFFFFC, 0xFFFFFFFF, 0xFF30FFBF,
+	0xFFFFFFF8, 0xC3E6FFFF, 0xFFFFF6DF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFF03F,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFEFCE, 0xF00EBFFF, 0x007C0000,
+	0xF0000038, 0xFF000009, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFF7FF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0x1FFFFC78, 0xFFFFE000, 0xFFFFFFFE, 0xFFFFFFFF,
+	0x38CF8F50, 0xFFF88082, 0xFF0000FC, 0xFAE009FF,
+	0x0000FFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000,
+	0xFFFF8CFC, 0xFFFFC1FF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFF80FFFF,
+	0x00000000, 0x00000000, 0x00000000, 0x00000000,
+	0x0003FC01, 0x3FFFFCF8, 0xFE800B19,
+};
+
+
+
+int rv515_init(struct radeon_device *rdev)
+{
+	rdev->config.r300.reg_safe_bm = r500_reg_safe_bm;
+	rdev->config.r300.reg_safe_bm_size = ARRAY_SIZE(r500_reg_safe_bm);
+	return 0;
+}
diff --git a/drivers/gpu/drm/savage/savage_bci.c b/drivers/gpu/drm/savage/savage_bci.c
index 456cd04..bff6fc2 100644
--- a/drivers/gpu/drm/savage/savage_bci.c
+++ b/drivers/gpu/drm/savage/savage_bci.c
@@ -298,8 +298,8 @@
 
 	dev_priv->nr_dma_pages = dev_priv->cmd_dma->size /
 	    (SAVAGE_DMA_PAGE_SIZE * 4);
-	dev_priv->dma_pages = drm_alloc(sizeof(drm_savage_dma_page_t) *
-					dev_priv->nr_dma_pages, DRM_MEM_DRIVER);
+	dev_priv->dma_pages = kmalloc(sizeof(drm_savage_dma_page_t) *
+				      dev_priv->nr_dma_pages, GFP_KERNEL);
 	if (dev_priv->dma_pages == NULL)
 		return -ENOMEM;
 
@@ -539,7 +539,7 @@
 {
 	drm_savage_private_t *dev_priv;
 
-	dev_priv = drm_alloc(sizeof(drm_savage_private_t), DRM_MEM_DRIVER);
+	dev_priv = kmalloc(sizeof(drm_savage_private_t), GFP_KERNEL);
 	if (dev_priv == NULL)
 		return -ENOMEM;
 
@@ -671,7 +671,7 @@
 {
 	drm_savage_private_t *dev_priv = dev->dev_private;
 
-	drm_free(dev_priv, sizeof(drm_savage_private_t), DRM_MEM_DRIVER);
+	kfree(dev_priv);
 
 	return 0;
 }
@@ -804,8 +804,8 @@
 		dev_priv->fake_dma.offset = 0;
 		dev_priv->fake_dma.size = SAVAGE_FAKE_DMA_SIZE;
 		dev_priv->fake_dma.type = _DRM_SHM;
-		dev_priv->fake_dma.handle = drm_alloc(SAVAGE_FAKE_DMA_SIZE,
-						      DRM_MEM_DRIVER);
+		dev_priv->fake_dma.handle = kmalloc(SAVAGE_FAKE_DMA_SIZE,
+						    GFP_KERNEL);
 		if (!dev_priv->fake_dma.handle) {
 			DRM_ERROR("could not allocate faked DMA buffer!\n");
 			savage_do_cleanup_bci(dev);
@@ -903,9 +903,7 @@
 	drm_savage_private_t *dev_priv = dev->dev_private;
 
 	if (dev_priv->cmd_dma == &dev_priv->fake_dma) {
-		if (dev_priv->fake_dma.handle)
-			drm_free(dev_priv->fake_dma.handle,
-				 SAVAGE_FAKE_DMA_SIZE, DRM_MEM_DRIVER);
+		kfree(dev_priv->fake_dma.handle);
 	} else if (dev_priv->cmd_dma && dev_priv->cmd_dma->handle &&
 		   dev_priv->cmd_dma->type == _DRM_AGP &&
 		   dev_priv->dma_type == SAVAGE_DMA_AGP)
@@ -920,10 +918,7 @@
 		dev->agp_buffer_map = NULL;
 	}
 
-	if (dev_priv->dma_pages)
-		drm_free(dev_priv->dma_pages,
-			 sizeof(drm_savage_dma_page_t) * dev_priv->nr_dma_pages,
-			 DRM_MEM_DRIVER);
+	kfree(dev_priv->dma_pages);
 
 	return 0;
 }
diff --git a/drivers/gpu/drm/savage/savage_state.c b/drivers/gpu/drm/savage/savage_state.c
index 5f6238f..8a3e315 100644
--- a/drivers/gpu/drm/savage/savage_state.c
+++ b/drivers/gpu/drm/savage/savage_state.c
@@ -988,20 +988,20 @@
 	 * for locking on FreeBSD.
 	 */
 	if (cmdbuf->size) {
-		kcmd_addr = drm_alloc(cmdbuf->size * 8, DRM_MEM_DRIVER);
+		kcmd_addr = kmalloc(cmdbuf->size * 8, GFP_KERNEL);
 		if (kcmd_addr == NULL)
 			return -ENOMEM;
 
 		if (DRM_COPY_FROM_USER(kcmd_addr, cmdbuf->cmd_addr,
 				       cmdbuf->size * 8))
 		{
-			drm_free(kcmd_addr, cmdbuf->size * 8, DRM_MEM_DRIVER);
+			kfree(kcmd_addr);
 			return -EFAULT;
 		}
 		cmdbuf->cmd_addr = kcmd_addr;
 	}
 	if (cmdbuf->vb_size) {
-		kvb_addr = drm_alloc(cmdbuf->vb_size, DRM_MEM_DRIVER);
+		kvb_addr = kmalloc(cmdbuf->vb_size, GFP_KERNEL);
 		if (kvb_addr == NULL) {
 			ret = -ENOMEM;
 			goto done;
@@ -1015,8 +1015,8 @@
 		cmdbuf->vb_addr = kvb_addr;
 	}
 	if (cmdbuf->nbox) {
-		kbox_addr = drm_alloc(cmdbuf->nbox * sizeof(struct drm_clip_rect),
-				       DRM_MEM_DRIVER);
+		kbox_addr = kmalloc(cmdbuf->nbox * sizeof(struct drm_clip_rect),
+				    GFP_KERNEL);
 		if (kbox_addr == NULL) {
 			ret = -ENOMEM;
 			goto done;
@@ -1154,10 +1154,9 @@
 
 done:
 	/* If we didn't need to allocate them, these'll be NULL */
-	drm_free(kcmd_addr, cmdbuf->size * 8, DRM_MEM_DRIVER);
-	drm_free(kvb_addr, cmdbuf->vb_size, DRM_MEM_DRIVER);
-	drm_free(kbox_addr, cmdbuf->nbox * sizeof(struct drm_clip_rect),
-		 DRM_MEM_DRIVER);
+	kfree(kcmd_addr);
+	kfree(kvb_addr);
+	kfree(kbox_addr);
 
 	return ret;
 }
diff --git a/drivers/gpu/drm/sis/sis_drv.c b/drivers/gpu/drm/sis/sis_drv.c
index 7dacc64..e725cc0 100644
--- a/drivers/gpu/drm/sis/sis_drv.c
+++ b/drivers/gpu/drm/sis/sis_drv.c
@@ -40,7 +40,7 @@
 	drm_sis_private_t *dev_priv;
 	int ret;
 
-	dev_priv = drm_calloc(1, sizeof(drm_sis_private_t), DRM_MEM_DRIVER);
+	dev_priv = kzalloc(sizeof(drm_sis_private_t), GFP_KERNEL);
 	if (dev_priv == NULL)
 		return -ENOMEM;
 
@@ -48,7 +48,7 @@
 	dev_priv->chipset = chipset;
 	ret = drm_sman_init(&dev_priv->sman, 2, 12, 8);
 	if (ret) {
-		drm_free(dev_priv, sizeof(dev_priv), DRM_MEM_DRIVER);
+		kfree(dev_priv);
 	}
 
 	return ret;
@@ -59,7 +59,7 @@
 	drm_sis_private_t *dev_priv = dev->dev_private;
 
 	drm_sman_takedown(&dev_priv->sman);
-	drm_free(dev_priv, sizeof(*dev_priv), DRM_MEM_DRIVER);
+	kfree(dev_priv);
 
 	return 0;
 }
diff --git a/drivers/gpu/drm/ttm/ttm_agp_backend.c b/drivers/gpu/drm/ttm/ttm_agp_backend.c
index e8f6d22..4648ed2 100644
--- a/drivers/gpu/drm/ttm/ttm_agp_backend.c
+++ b/drivers/gpu/drm/ttm/ttm_agp_backend.c
@@ -63,8 +63,7 @@
 		if (!page)
 			page = dummy_read_page;
 
-		mem->memory[mem->page_count++] =
-		    phys_to_gart(page_to_phys(page));
+		mem->pages[mem->page_count++] = page;
 	}
 	agp_be->mem = mem;
 	return 0;
diff --git a/drivers/gpu/drm/ttm/ttm_bo.c b/drivers/gpu/drm/ttm/ttm_bo.c
index 1587aeca..c1c407f 100644
--- a/drivers/gpu/drm/ttm/ttm_bo.c
+++ b/drivers/gpu/drm/ttm/ttm_bo.c
@@ -282,7 +282,7 @@
 
 		ret = ttm_tt_set_placement_caching(bo->ttm, mem->placement);
 		if (ret)
-			return ret;
+			goto out_err;
 
 		if (mem->mem_type != TTM_PL_SYSTEM) {
 			ret = ttm_tt_bind(bo->ttm, mem);
@@ -527,9 +527,12 @@
 	ret = ttm_bo_wait(bo, false, interruptible, no_wait);
 	spin_unlock(&bo->lock);
 
-	if (ret && ret != -ERESTART) {
-		printk(KERN_ERR TTM_PFX "Failed to expire sync object before "
-		       "buffer eviction.\n");
+	if (unlikely(ret != 0)) {
+		if (ret != -ERESTART) {
+			printk(KERN_ERR TTM_PFX
+			       "Failed to expire sync object before "
+			       "buffer eviction.\n");
+		}
 		goto out;
 	}
 
diff --git a/drivers/gpu/drm/ttm/ttm_tt.c b/drivers/gpu/drm/ttm/ttm_tt.c
index c27ab3a..0331fa7 100644
--- a/drivers/gpu/drm/ttm/ttm_tt.c
+++ b/drivers/gpu/drm/ttm/ttm_tt.c
@@ -68,7 +68,7 @@
 		ttm_tt_clflush_page(*pages++);
 	mb();
 }
-#else
+#elif !defined(__powerpc__)
 static void ttm_tt_ipi_handler(void *null)
 {
 	;
@@ -83,6 +83,15 @@
 		ttm_tt_cache_flush_clflush(pages, num_pages);
 		return;
 	}
+#elif defined(__powerpc__)
+	unsigned long i;
+
+	for (i = 0; i < num_pages; ++i) {
+		if (pages[i]) {
+			unsigned long start = (unsigned long)page_address(pages[i]);
+			flush_dcache_range(start, start + PAGE_SIZE);
+		}
+	}
 #else
 	if (on_each_cpu(ttm_tt_ipi_handler, NULL, 1) != 0)
 		printk(KERN_ERR TTM_PFX
diff --git a/drivers/gpu/drm/via/via_map.c b/drivers/gpu/drm/via/via_map.c
index 2c4f0b4..6e6f915 100644
--- a/drivers/gpu/drm/via/via_map.c
+++ b/drivers/gpu/drm/via/via_map.c
@@ -96,7 +96,7 @@
 	drm_via_private_t *dev_priv;
 	int ret = 0;
 
-	dev_priv = drm_calloc(1, sizeof(drm_via_private_t), DRM_MEM_DRIVER);
+	dev_priv = kzalloc(sizeof(drm_via_private_t), GFP_KERNEL);
 	if (dev_priv == NULL)
 		return -ENOMEM;
 
@@ -106,14 +106,14 @@
 
 	ret = drm_sman_init(&dev_priv->sman, 2, 12, 8);
 	if (ret) {
-		drm_free(dev_priv, sizeof(*dev_priv), DRM_MEM_DRIVER);
+		kfree(dev_priv);
 		return ret;
 	}
 
 	ret = drm_vblank_init(dev, 1);
 	if (ret) {
 		drm_sman_takedown(&dev_priv->sman);
-		drm_free(dev_priv, sizeof(drm_via_private_t), DRM_MEM_DRIVER);
+		kfree(dev_priv);
 		return ret;
 	}
 
@@ -126,7 +126,7 @@
 
 	drm_sman_takedown(&dev_priv->sman);
 
-	drm_free(dev_priv, sizeof(drm_via_private_t), DRM_MEM_DRIVER);
+	kfree(dev_priv);
 
 	return 0;
 }
diff --git a/drivers/i2c/busses/i2c-mpc.c b/drivers/i2c/busses/i2c-mpc.c
index dd778d7..d325e86 100644
--- a/drivers/i2c/busses/i2c-mpc.c
+++ b/drivers/i2c/busses/i2c-mpc.c
@@ -197,7 +197,7 @@
 		return -EINVAL;
 
 	/* Determine divider value */
-	divider = mpc52xx_find_ipb_freq(node) / clock;
+	divider = mpc5xxx_get_bus_frequency(node) / clock;
 
 	/*
 	 * We want to choose an FDR/DFSR that generates an I2C bus speed that
diff --git a/drivers/i2c/i2c-boardinfo.c b/drivers/i2c/i2c-boardinfo.c
index ffb35f0..a26a34a 100644
--- a/drivers/i2c/i2c-boardinfo.c
+++ b/drivers/i2c/i2c-boardinfo.c
@@ -18,6 +18,7 @@
 
 #include <linux/kernel.h>
 #include <linux/i2c.h>
+#include <linux/rwsem.h>
 
 #include "i2c-core.h"
 
@@ -25,7 +26,7 @@
 /* These symbols are exported ONLY FOR the i2c core.
  * No other users will be supported.
  */
-DEFINE_MUTEX(__i2c_board_lock);
+DECLARE_RWSEM(__i2c_board_lock);
 EXPORT_SYMBOL_GPL(__i2c_board_lock);
 
 LIST_HEAD(__i2c_board_list);
@@ -63,7 +64,7 @@
 {
 	int status;
 
-	mutex_lock(&__i2c_board_lock);
+	down_write(&__i2c_board_lock);
 
 	/* dynamic bus numbers will be assigned after the last static one */
 	if (busnum >= __i2c_first_dynamic_bus_num)
@@ -84,7 +85,7 @@
 		list_add_tail(&devinfo->list, &__i2c_board_list);
 	}
 
-	mutex_unlock(&__i2c_board_lock);
+	up_write(&__i2c_board_lock);
 
 	return status;
 }
diff --git a/drivers/i2c/i2c-core.c b/drivers/i2c/i2c-core.c
index 5ed622e..0e45c29 100644
--- a/drivers/i2c/i2c-core.c
+++ b/drivers/i2c/i2c-core.c
@@ -33,16 +33,20 @@
 #include <linux/completion.h>
 #include <linux/hardirq.h>
 #include <linux/irqflags.h>
+#include <linux/rwsem.h>
 #include <asm/uaccess.h>
 
 #include "i2c-core.h"
 
 
+/* core_lock protects i2c_adapter_idr, userspace_devices, and guarantees
+   that device detection, deletion of detected devices, and attach_adapter
+   and detach_adapter calls are serialized */
 static DEFINE_MUTEX(core_lock);
 static DEFINE_IDR(i2c_adapter_idr);
+static LIST_HEAD(userspace_devices);
 
-#define is_newstyle_driver(d) ((d)->probe || (d)->remove || (d)->detect)
-
+static int i2c_check_addr(struct i2c_adapter *adapter, int addr);
 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
 
 /* ------------------------------------------------------------------------- */
@@ -63,12 +67,6 @@
 	struct i2c_client	*client = to_i2c_client(dev);
 	struct i2c_driver	*driver = to_i2c_driver(drv);
 
-	/* make legacy i2c drivers bypass driver model probing entirely;
-	 * such drivers scan each i2c adapter/bus themselves.
-	 */
-	if (!is_newstyle_driver(driver))
-		return 0;
-
 	/* match on an id table if there is one */
 	if (driver->id_table)
 		return i2c_match_id(driver->id_table, client) != NULL;
@@ -83,10 +81,6 @@
 {
 	struct i2c_client	*client = to_i2c_client(dev);
 
-	/* by definition, legacy drivers can't hotplug */
-	if (dev->driver)
-		return 0;
-
 	if (add_uevent_var(env, "MODALIAS=%s%s",
 			   I2C_MODULE_PREFIX, client->name))
 		return -ENOMEM;
@@ -175,12 +169,6 @@
 	return driver->resume(to_i2c_client(dev));
 }
 
-static void i2c_client_release(struct device *dev)
-{
-	struct i2c_client *client = to_i2c_client(dev);
-	complete(&client->released);
-}
-
 static void i2c_client_dev_release(struct device *dev)
 {
 	kfree(to_i2c_client(dev));
@@ -240,15 +228,17 @@
 
 
 /**
- * i2c_new_device - instantiate an i2c device for use with a new style driver
+ * i2c_new_device - instantiate an i2c device
  * @adap: the adapter managing the device
  * @info: describes one I2C device; bus_num is ignored
  * Context: can sleep
  *
- * Create a device to work with a new style i2c driver, where binding is
- * handled through driver model probe()/remove() methods.  This call is not
- * appropriate for use by mainboad initialization logic, which usually runs
- * during an arch_initcall() long before any i2c_adapter could exist.
+ * Create an i2c device. Binding is handled through driver model
+ * probe()/remove() methods.  A driver may be bound to this device when we
+ * return from this function, or any later moment (e.g. maybe hotplugging will
+ * load the driver module).  This call is not appropriate for use by mainboard
+ * initialization logic, which usually runs during an arch_initcall() long
+ * before any i2c_adapter could exist.
  *
  * This returns the new i2c client, which may be saved for later use with
  * i2c_unregister_device(); or NULL to indicate an error.
@@ -276,17 +266,31 @@
 
 	strlcpy(client->name, info->type, sizeof(client->name));
 
-	/* a new style driver may be bound to this device when we
-	 * return from this function, or any later moment (e.g. maybe
-	 * hotplugging will load the driver module).  and the device
-	 * refcount model is the standard driver model one.
-	 */
-	status = i2c_attach_client(client);
-	if (status < 0) {
-		kfree(client);
-		client = NULL;
-	}
+	/* Check for address business */
+	status = i2c_check_addr(adap, client->addr);
+	if (status)
+		goto out_err;
+
+	client->dev.parent = &client->adapter->dev;
+	client->dev.bus = &i2c_bus_type;
+	client->dev.release = i2c_client_dev_release;
+
+	dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
+		     client->addr);
+	status = device_register(&client->dev);
+	if (status)
+		goto out_err;
+
+	dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
+		client->name, dev_name(&client->dev));
+
 	return client;
+
+out_err:
+	dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
+		"(%d)\n", client->name, client->addr, status);
+	kfree(client);
+	return NULL;
 }
 EXPORT_SYMBOL_GPL(i2c_new_device);
 
@@ -298,28 +302,6 @@
  */
 void i2c_unregister_device(struct i2c_client *client)
 {
-	struct i2c_adapter	*adapter = client->adapter;
-	struct i2c_driver	*driver = client->driver;
-
-	if (driver && !is_newstyle_driver(driver)) {
-		dev_err(&client->dev, "can't unregister devices "
-			"with legacy drivers\n");
-		WARN_ON(1);
-		return;
-	}
-
-	if (adapter->client_unregister) {
-		if (adapter->client_unregister(client)) {
-			dev_warn(&client->dev,
-				 "client_unregister [%s] failed\n",
-				 client->name);
-		}
-	}
-
-	mutex_lock(&adapter->clist_lock);
-	list_del(&client->list);
-	mutex_unlock(&adapter->clist_lock);
-
 	device_unregister(&client->dev);
 }
 EXPORT_SYMBOL_GPL(i2c_unregister_device);
@@ -393,8 +375,128 @@
 	return sprintf(buf, "%s\n", adap->name);
 }
 
+/*
+ * Let users instantiate I2C devices through sysfs. This can be used when
+ * platform initialization code doesn't contain the proper data for
+ * whatever reason. Also useful for drivers that do device detection and
+ * detection fails, either because the device uses an unexpected address,
+ * or this is a compatible device with different ID register values.
+ *
+ * Parameter checking may look overzealous, but we really don't want
+ * the user to provide incorrect parameters.
+ */
+static ssize_t
+i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
+		     const char *buf, size_t count)
+{
+	struct i2c_adapter *adap = to_i2c_adapter(dev);
+	struct i2c_board_info info;
+	struct i2c_client *client;
+	char *blank, end;
+	int res;
+
+	dev_warn(dev, "The new_device interface is still experimental "
+		 "and may change in a near future\n");
+	memset(&info, 0, sizeof(struct i2c_board_info));
+
+	blank = strchr(buf, ' ');
+	if (!blank) {
+		dev_err(dev, "%s: Missing parameters\n", "new_device");
+		return -EINVAL;
+	}
+	if (blank - buf > I2C_NAME_SIZE - 1) {
+		dev_err(dev, "%s: Invalid device name\n", "new_device");
+		return -EINVAL;
+	}
+	memcpy(info.type, buf, blank - buf);
+
+	/* Parse remaining parameters, reject extra parameters */
+	res = sscanf(++blank, "%hi%c", &info.addr, &end);
+	if (res < 1) {
+		dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
+		return -EINVAL;
+	}
+	if (res > 1  && end != '\n') {
+		dev_err(dev, "%s: Extra parameters\n", "new_device");
+		return -EINVAL;
+	}
+
+	if (info.addr < 0x03 || info.addr > 0x77) {
+		dev_err(dev, "%s: Invalid I2C address 0x%hx\n", "new_device",
+			info.addr);
+		return -EINVAL;
+	}
+
+	client = i2c_new_device(adap, &info);
+	if (!client)
+		return -EEXIST;
+
+	/* Keep track of the added device */
+	mutex_lock(&core_lock);
+	list_add_tail(&client->detected, &userspace_devices);
+	mutex_unlock(&core_lock);
+	dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
+		 info.type, info.addr);
+
+	return count;
+}
+
+/*
+ * And of course let the users delete the devices they instantiated, if
+ * they got it wrong. This interface can only be used to delete devices
+ * instantiated by i2c_sysfs_new_device above. This guarantees that we
+ * don't delete devices to which some kernel code still has references.
+ *
+ * Parameter checking may look overzealous, but we really don't want
+ * the user to delete the wrong device.
+ */
+static ssize_t
+i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
+			const char *buf, size_t count)
+{
+	struct i2c_adapter *adap = to_i2c_adapter(dev);
+	struct i2c_client *client, *next;
+	unsigned short addr;
+	char end;
+	int res;
+
+	/* Parse parameters, reject extra parameters */
+	res = sscanf(buf, "%hi%c", &addr, &end);
+	if (res < 1) {
+		dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
+		return -EINVAL;
+	}
+	if (res > 1  && end != '\n') {
+		dev_err(dev, "%s: Extra parameters\n", "delete_device");
+		return -EINVAL;
+	}
+
+	/* Make sure the device was added through sysfs */
+	res = -ENOENT;
+	mutex_lock(&core_lock);
+	list_for_each_entry_safe(client, next, &userspace_devices, detected) {
+		if (client->addr == addr && client->adapter == adap) {
+			dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
+				 "delete_device", client->name, client->addr);
+
+			list_del(&client->detected);
+			i2c_unregister_device(client);
+			res = count;
+			break;
+		}
+	}
+	mutex_unlock(&core_lock);
+
+	if (res < 0)
+		dev_err(dev, "%s: Can't find device in list\n",
+			"delete_device");
+	return res;
+}
+
 static struct device_attribute i2c_adapter_attrs[] = {
 	__ATTR(name, S_IRUGO, show_adapter_name, NULL),
+	__ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device),
+	__ATTR(delete_device, S_IWUSR, NULL, i2c_sysfs_delete_device),
 	{ },
 };
 
@@ -408,7 +510,7 @@
 {
 	struct i2c_devinfo	*devinfo;
 
-	mutex_lock(&__i2c_board_lock);
+	down_read(&__i2c_board_lock);
 	list_for_each_entry(devinfo, &__i2c_board_list, list) {
 		if (devinfo->busnum == adapter->nr
 				&& !i2c_new_device(adapter,
@@ -417,7 +519,7 @@
 				"Can't create device at 0x%02x\n",
 				devinfo->board_info.addr);
 	}
-	mutex_unlock(&__i2c_board_lock);
+	up_read(&__i2c_board_lock);
 }
 
 static int i2c_do_add_adapter(struct device_driver *d, void *data)
@@ -441,14 +543,12 @@
 	int res = 0, dummy;
 
 	/* Can't register until after driver model init */
-	if (unlikely(WARN_ON(!i2c_bus_type.p)))
-		return -EAGAIN;
+	if (unlikely(WARN_ON(!i2c_bus_type.p))) {
+		res = -EAGAIN;
+		goto out_list;
+	}
 
 	mutex_init(&adap->bus_lock);
-	mutex_init(&adap->clist_lock);
-	INIT_LIST_HEAD(&adap->clients);
-
-	mutex_lock(&core_lock);
 
 	/* Set default timeout to 1 second if not already set */
 	if (adap->timeout == 0)
@@ -463,21 +563,23 @@
 
 	dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
 
-	/* create pre-declared device nodes for new-style drivers */
+	/* create pre-declared device nodes */
 	if (adap->nr < __i2c_first_dynamic_bus_num)
 		i2c_scan_static_board_info(adap);
 
 	/* Notify drivers */
+	mutex_lock(&core_lock);
 	dummy = bus_for_each_drv(&i2c_bus_type, NULL, adap,
 				 i2c_do_add_adapter);
-
-out_unlock:
 	mutex_unlock(&core_lock);
-	return res;
+
+	return 0;
 
 out_list:
+	mutex_lock(&core_lock);
 	idr_remove(&i2c_adapter_idr, adap->nr);
-	goto out_unlock;
+	mutex_unlock(&core_lock);
+	return res;
 }
 
 /**
@@ -596,6 +698,14 @@
 	return res;
 }
 
+static int __unregister_client(struct device *dev, void *dummy)
+{
+	struct i2c_client *client = i2c_verify_client(dev);
+	if (client)
+		i2c_unregister_device(client);
+	return 0;
+}
+
 /**
  * i2c_del_adapter - unregister I2C adapter
  * @adap: the adapter being unregistered
@@ -606,46 +716,30 @@
  */
 int i2c_del_adapter(struct i2c_adapter *adap)
 {
-	struct i2c_client *client, *_n;
 	int res = 0;
-
-	mutex_lock(&core_lock);
+	struct i2c_adapter *found;
 
 	/* First make sure that this adapter was ever added */
-	if (idr_find(&i2c_adapter_idr, adap->nr) != adap) {
+	mutex_lock(&core_lock);
+	found = idr_find(&i2c_adapter_idr, adap->nr);
+	mutex_unlock(&core_lock);
+	if (found != adap) {
 		pr_debug("i2c-core: attempting to delete unregistered "
 			 "adapter [%s]\n", adap->name);
-		res = -EINVAL;
-		goto out_unlock;
+		return -EINVAL;
 	}
 
 	/* Tell drivers about this removal */
+	mutex_lock(&core_lock);
 	res = bus_for_each_drv(&i2c_bus_type, NULL, adap,
 			       i2c_do_del_adapter);
+	mutex_unlock(&core_lock);
 	if (res)
-		goto out_unlock;
+		return res;
 
-	/* detach any active clients. This must be done first, because
-	 * it can fail; in which case we give up. */
-	list_for_each_entry_safe_reverse(client, _n, &adap->clients, list) {
-		struct i2c_driver	*driver;
-
-		driver = client->driver;
-
-		/* new style, follow standard driver model */
-		if (!driver || is_newstyle_driver(driver)) {
-			i2c_unregister_device(client);
-			continue;
-		}
-
-		/* legacy drivers create and remove clients themselves */
-		if ((res = driver->detach_client(client))) {
-			dev_err(&adap->dev, "detach_client failed for client "
-				"[%s] at address 0x%02x\n", client->name,
-				client->addr);
-			goto out_unlock;
-		}
-	}
+	/* Detach any active clients. This can't fail, thus we do not
+	   checking the returned value. */
+	res = device_for_each_child(&adap->dev, NULL, __unregister_client);
 
 	/* clean up the sysfs representation */
 	init_completion(&adap->dev_released);
@@ -655,7 +749,9 @@
 	wait_for_completion(&adap->dev_released);
 
 	/* free bus id */
+	mutex_lock(&core_lock);
 	idr_remove(&i2c_adapter_idr, adap->nr);
+	mutex_unlock(&core_lock);
 
 	dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
 
@@ -663,9 +759,7 @@
 	   added again */
 	memset(&adap->dev, 0, sizeof(adap->dev));
 
- out_unlock:
-	mutex_unlock(&core_lock);
-	return res;
+	return 0;
 }
 EXPORT_SYMBOL(i2c_del_adapter);
 
@@ -688,11 +782,7 @@
 
 /*
  * An i2c_driver is used with one or more i2c_client (device) nodes to access
- * i2c slave chips, on a bus instance associated with some i2c_adapter.  There
- * are two models for binding the driver to its device:  "new style" drivers
- * follow the standard Linux driver model and just respond to probe() calls
- * issued if the driver core sees they match(); "legacy" drivers create device
- * nodes themselves.
+ * i2c slave chips, on a bus instance associated with some i2c_adapter.
  */
 
 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
@@ -703,37 +793,26 @@
 	if (unlikely(WARN_ON(!i2c_bus_type.p)))
 		return -EAGAIN;
 
-	/* new style driver methods can't mix with legacy ones */
-	if (is_newstyle_driver(driver)) {
-		if (driver->detach_adapter || driver->detach_client) {
-			printk(KERN_WARNING
-					"i2c-core: driver [%s] is confused\n",
-					driver->driver.name);
-			return -EINVAL;
-		}
-	}
-
 	/* add the driver to the list of i2c drivers in the driver core */
 	driver->driver.owner = owner;
 	driver->driver.bus = &i2c_bus_type;
 
-	/* for new style drivers, when registration returns the driver core
+	/* When registration returns, the driver core
 	 * will have called probe() for all matching-but-unbound devices.
 	 */
 	res = driver_register(&driver->driver);
 	if (res)
 		return res;
 
-	mutex_lock(&core_lock);
-
 	pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
 
 	INIT_LIST_HEAD(&driver->clients);
 	/* Walk the adapters that are already present */
+	mutex_lock(&core_lock);
 	class_for_each_device(&i2c_adapter_class, NULL, driver,
 			      __attach_adapter);
-
 	mutex_unlock(&core_lock);
+
 	return 0;
 }
 EXPORT_SYMBOL(i2c_register_driver);
@@ -753,32 +832,11 @@
 		i2c_unregister_device(client);
 	}
 
-	if (is_newstyle_driver(driver))
-		return 0;
-
-	/* Have a look at each adapter, if clients of this driver are still
-	 * attached. If so, detach them to be able to kill the driver
-	 * afterwards.
-	 */
 	if (driver->detach_adapter) {
 		if (driver->detach_adapter(adapter))
 			dev_err(&adapter->dev,
 				"detach_adapter failed for driver [%s]\n",
 				driver->driver.name);
-	} else {
-		struct i2c_client *client, *_n;
-
-		list_for_each_entry_safe(client, _n, &adapter->clients, list) {
-			if (client->driver != driver)
-				continue;
-			dev_dbg(&adapter->dev,
-				"detaching client [%s] at 0x%02x\n",
-				client->name, client->addr);
-			if (driver->detach_client(client))
-				dev_err(&adapter->dev, "detach_client "
-					"failed for client [%s] at 0x%02x\n",
-					client->name, client->addr);
-		}
 	}
 
 	return 0;
@@ -792,14 +850,12 @@
 void i2c_del_driver(struct i2c_driver *driver)
 {
 	mutex_lock(&core_lock);
-
 	class_for_each_device(&i2c_adapter_class, NULL, driver,
 			      __detach_adapter);
+	mutex_unlock(&core_lock);
 
 	driver_unregister(&driver->driver);
 	pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
-
-	mutex_unlock(&core_lock);
 }
 EXPORT_SYMBOL(i2c_del_driver);
 
@@ -820,86 +876,6 @@
 	return device_for_each_child(&adapter->dev, &addr, __i2c_check_addr);
 }
 
-int i2c_attach_client(struct i2c_client *client)
-{
-	struct i2c_adapter *adapter = client->adapter;
-	int res;
-
-	/* Check for address business */
-	res = i2c_check_addr(adapter, client->addr);
-	if (res)
-		return res;
-
-	client->dev.parent = &client->adapter->dev;
-	client->dev.bus = &i2c_bus_type;
-
-	if (client->driver)
-		client->dev.driver = &client->driver->driver;
-
-	if (client->driver && !is_newstyle_driver(client->driver)) {
-		client->dev.release = i2c_client_release;
-		dev_set_uevent_suppress(&client->dev, 1);
-	} else
-		client->dev.release = i2c_client_dev_release;
-
-	dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adapter),
-		     client->addr);
-	res = device_register(&client->dev);
-	if (res)
-		goto out_err;
-
-	mutex_lock(&adapter->clist_lock);
-	list_add_tail(&client->list, &adapter->clients);
-	mutex_unlock(&adapter->clist_lock);
-
-	dev_dbg(&adapter->dev, "client [%s] registered with bus id %s\n",
-		client->name, dev_name(&client->dev));
-
-	if (adapter->client_register)  {
-		if (adapter->client_register(client)) {
-			dev_dbg(&adapter->dev, "client_register "
-				"failed for client [%s] at 0x%02x\n",
-				client->name, client->addr);
-		}
-	}
-
-	return 0;
-
-out_err:
-	dev_err(&adapter->dev, "Failed to attach i2c client %s at 0x%02x "
-		"(%d)\n", client->name, client->addr, res);
-	return res;
-}
-EXPORT_SYMBOL(i2c_attach_client);
-
-int i2c_detach_client(struct i2c_client *client)
-{
-	struct i2c_adapter *adapter = client->adapter;
-	int res = 0;
-
-	if (adapter->client_unregister)  {
-		res = adapter->client_unregister(client);
-		if (res) {
-			dev_err(&client->dev,
-				"client_unregister [%s] failed, "
-				"client not detached\n", client->name);
-			goto out;
-		}
-	}
-
-	mutex_lock(&adapter->clist_lock);
-	list_del(&client->list);
-	mutex_unlock(&adapter->clist_lock);
-
-	init_completion(&client->released);
-	device_unregister(&client->dev);
-	wait_for_completion(&client->released);
-
- out:
-	return res;
-}
-EXPORT_SYMBOL(i2c_detach_client);
-
 /**
  * i2c_use_client - increments the reference count of the i2c client structure
  * @client: the client being referenced
@@ -1129,144 +1105,7 @@
  * Will not work for 10-bit addresses!
  * ----------------------------------------------------
  */
-static int i2c_probe_address(struct i2c_adapter *adapter, int addr, int kind,
-			     int (*found_proc) (struct i2c_adapter *, int, int))
-{
-	int err;
 
-	/* Make sure the address is valid */
-	if (addr < 0x03 || addr > 0x77) {
-		dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
-			 addr);
-		return -EINVAL;
-	}
-
-	/* Skip if already in use */
-	if (i2c_check_addr(adapter, addr))
-		return 0;
-
-	/* Make sure there is something at this address, unless forced */
-	if (kind < 0) {
-		if (i2c_smbus_xfer(adapter, addr, 0, 0, 0,
-				   I2C_SMBUS_QUICK, NULL) < 0)
-			return 0;
-
-		/* prevent 24RF08 corruption */
-		if ((addr & ~0x0f) == 0x50)
-			i2c_smbus_xfer(adapter, addr, 0, 0, 0,
-				       I2C_SMBUS_QUICK, NULL);
-	}
-
-	/* Finally call the custom detection function */
-	err = found_proc(adapter, addr, kind);
-	/* -ENODEV can be returned if there is a chip at the given address
-	   but it isn't supported by this chip driver. We catch it here as
-	   this isn't an error. */
-	if (err == -ENODEV)
-		err = 0;
-
-	if (err)
-		dev_warn(&adapter->dev, "Client creation failed at 0x%x (%d)\n",
-			 addr, err);
-	return err;
-}
-
-int i2c_probe(struct i2c_adapter *adapter,
-	      const struct i2c_client_address_data *address_data,
-	      int (*found_proc) (struct i2c_adapter *, int, int))
-{
-	int i, err;
-	int adap_id = i2c_adapter_id(adapter);
-
-	/* Force entries are done first, and are not affected by ignore
-	   entries */
-	if (address_data->forces) {
-		const unsigned short * const *forces = address_data->forces;
-		int kind;
-
-		for (kind = 0; forces[kind]; kind++) {
-			for (i = 0; forces[kind][i] != I2C_CLIENT_END;
-			     i += 2) {
-				if (forces[kind][i] == adap_id
-				 || forces[kind][i] == ANY_I2C_BUS) {
-					dev_dbg(&adapter->dev, "found force "
-						"parameter for adapter %d, "
-						"addr 0x%02x, kind %d\n",
-						adap_id, forces[kind][i + 1],
-						kind);
-					err = i2c_probe_address(adapter,
-						forces[kind][i + 1],
-						kind, found_proc);
-					if (err)
-						return err;
-				}
-			}
-		}
-	}
-
-	/* Stop here if we can't use SMBUS_QUICK */
-	if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_QUICK)) {
-		if (address_data->probe[0] == I2C_CLIENT_END
-		 && address_data->normal_i2c[0] == I2C_CLIENT_END)
-			return 0;
-
-		dev_dbg(&adapter->dev, "SMBus Quick command not supported, "
-			"can't probe for chips\n");
-		return -EOPNOTSUPP;
-	}
-
-	/* Probe entries are done second, and are not affected by ignore
-	   entries either */
-	for (i = 0; address_data->probe[i] != I2C_CLIENT_END; i += 2) {
-		if (address_data->probe[i] == adap_id
-		 || address_data->probe[i] == ANY_I2C_BUS) {
-			dev_dbg(&adapter->dev, "found probe parameter for "
-				"adapter %d, addr 0x%02x\n", adap_id,
-				address_data->probe[i + 1]);
-			err = i2c_probe_address(adapter,
-						address_data->probe[i + 1],
-						-1, found_proc);
-			if (err)
-				return err;
-		}
-	}
-
-	/* Normal entries are done last, unless shadowed by an ignore entry */
-	for (i = 0; address_data->normal_i2c[i] != I2C_CLIENT_END; i += 1) {
-		int j, ignore;
-
-		ignore = 0;
-		for (j = 0; address_data->ignore[j] != I2C_CLIENT_END;
-		     j += 2) {
-			if ((address_data->ignore[j] == adap_id ||
-			     address_data->ignore[j] == ANY_I2C_BUS)
-			 && address_data->ignore[j + 1]
-			    == address_data->normal_i2c[i]) {
-				dev_dbg(&adapter->dev, "found ignore "
-					"parameter for adapter %d, "
-					"addr 0x%02x\n", adap_id,
-					address_data->ignore[j + 1]);
-				ignore = 1;
-				break;
-			}
-		}
-		if (ignore)
-			continue;
-
-		dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
-			"addr 0x%02x\n", adap_id,
-			address_data->normal_i2c[i]);
-		err = i2c_probe_address(adapter, address_data->normal_i2c[i],
-					-1, found_proc);
-		if (err)
-			return err;
-	}
-
-	return 0;
-}
-EXPORT_SYMBOL(i2c_probe);
-
-/* Separate detection function for new-style drivers */
 static int i2c_detect_address(struct i2c_client *temp_client, int kind,
 			      struct i2c_driver *driver)
 {
diff --git a/drivers/i2c/i2c-core.h b/drivers/i2c/i2c-core.h
index cd5bff8..9f9c57f 100644
--- a/drivers/i2c/i2c-core.h
+++ b/drivers/i2c/i2c-core.h
@@ -16,6 +16,8 @@
  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  */
 
+#include <linux/rwsem.h>
+
 struct i2c_devinfo {
 	struct list_head	list;
 	int			busnum;
@@ -25,7 +27,7 @@
 /* board_lock protects board_list and first_dynamic_bus_num.
  * only i2c core components are allowed to use these symbols.
  */
-extern struct mutex	__i2c_board_lock;
+extern struct rw_semaphore	__i2c_board_lock;
 extern struct list_head	__i2c_board_list;
 extern int		__i2c_first_dynamic_bus_num;
 
diff --git a/drivers/ide/at91_ide.c b/drivers/ide/at91_ide.c
index fc0949a..dbfeda4 100644
--- a/drivers/ide/at91_ide.c
+++ b/drivers/ide/at91_ide.c
@@ -185,8 +185,7 @@
 	timing = ide_timing_find_mode(XFER_PIO_0 + pio);
 	BUG_ON(!timing);
 
-	if ((pio > 2 || ata_id_has_iordy(drive->id)) &&
-	    !(ata_id_is_cfa(drive->id) && pio > 4))
+	if (ide_pio_need_iordy(drive, pio))
 		use_iordy = 1;
 
 	apply_timings(chipselect, pio, timing, use_iordy);
diff --git a/drivers/ide/buddha.c b/drivers/ide/buddha.c
index e3c6a59..ab4f169 100644
--- a/drivers/ide/buddha.c
+++ b/drivers/ide/buddha.c
@@ -99,7 +99,7 @@
      *  Check and acknowledge the interrupt status
      */
 
-static int buddha_ack_intr(ide_hwif_t *hwif)
+static int buddha_test_irq(ide_hwif_t *hwif)
 {
     unsigned char ch;
 
@@ -109,21 +109,16 @@
     return 1;
 }
 
-static int xsurf_ack_intr(ide_hwif_t *hwif)
+static void xsurf_clear_irq(ide_drive_t *drive)
 {
-    unsigned char ch;
-
-    ch = z_readb(hwif->io_ports.irq_addr);
-    /* X-Surf needs a 0 written to IRQ register to ensure ISA bit A11 stays at 0 */
-    z_writeb(0, hwif->io_ports.irq_addr);
-    if (!(ch & 0x80))
-	    return 0;
-    return 1;
+    /*
+     * X-Surf needs 0 written to IRQ register to ensure ISA bit A11 stays at 0
+     */
+    z_writeb(0, drive->hwif->io_ports.irq_addr);
 }
 
 static void __init buddha_setup_ports(struct ide_hw *hw, unsigned long base,
-				      unsigned long ctl, unsigned long irq_port,
-				      ide_ack_intr_t *ack_intr)
+				      unsigned long ctl, unsigned long irq_port)
 {
 	int i;
 
@@ -138,10 +133,19 @@
 	hw->io_ports.irq_addr = irq_port;
 
 	hw->irq = IRQ_AMIGA_PORTS;
-	hw->ack_intr = ack_intr;
 }
 
+static const struct ide_port_ops buddha_port_ops = {
+	.test_irq		= buddha_test_irq,
+};
+
+static const struct ide_port_ops xsurf_port_ops = {
+	.clear_irq		= xsurf_clear_irq,
+	.test_irq		= buddha_test_irq,
+};
+
 static const struct ide_port_info buddha_port_info = {
+	.port_ops		= &buddha_port_ops,
 	.host_flags		= IDE_HFLAG_MMIO | IDE_HFLAG_NO_DMA,
 	.irq_flags		= IRQF_SHARED,
 	.chipset		= ide_generic,
@@ -161,6 +165,7 @@
 	while ((z = zorro_find_device(ZORRO_WILDCARD, z))) {
 		unsigned long board;
 		struct ide_hw hw[MAX_NUM_HWIFS], *hws[MAX_NUM_HWIFS];
+		struct ide_port_info d = buddha_port_info;
 
 		if (z->id == ZORRO_PROD_INDIVIDUAL_COMPUTERS_BUDDHA) {
 			buddha_num_hwifs = BUDDHA_NUM_HWIFS;
@@ -171,6 +176,7 @@
 		} else if (z->id == ZORRO_PROD_INDIVIDUAL_COMPUTERS_X_SURF) {
 			buddha_num_hwifs = XSURF_NUM_HWIFS;
 			type=BOARD_XSURF;
+			d.port_ops = &xsurf_port_ops;
 		} else 
 			continue;
 		
@@ -203,28 +209,24 @@
 
 		for (i = 0; i < buddha_num_hwifs; i++) {
 			unsigned long base, ctl, irq_port;
-			ide_ack_intr_t *ack_intr;
 
 			if (type != BOARD_XSURF) {
 				base = buddha_board + buddha_bases[i];
 				ctl = base + BUDDHA_CONTROL;
 				irq_port = buddha_board + buddha_irqports[i];
-				ack_intr = buddha_ack_intr;
 			} else {
 				base = buddha_board + xsurf_bases[i];
 				/* X-Surf has no CS1* (Control/AltStat) */
 				ctl = 0;
 				irq_port = buddha_board + xsurf_irqports[i];
-				ack_intr = xsurf_ack_intr;
 			}
 
-			buddha_setup_ports(&hw[i], base, ctl, irq_port,
-					   ack_intr);
+			buddha_setup_ports(&hw[i], base, ctl, irq_port);
 
 			hws[i] = &hw[i];
 		}
 
-		ide_host_add(&buddha_port_info, hws, i, NULL);
+		ide_host_add(&d, hws, i, NULL);
 	}
 
 	return 0;
diff --git a/drivers/ide/cmd640.c b/drivers/ide/cmd640.c
index 1683ed5..1a32d62 100644
--- a/drivers/ide/cmd640.c
+++ b/drivers/ide/cmd640.c
@@ -153,6 +153,7 @@
 #define ARTTIM23	0x57
 #define   ARTTIM23_DIS_RA2	0x04
 #define   ARTTIM23_DIS_RA3	0x08
+#define   ARTTIM23_IDE23INTR	0x10
 #define DRWTIM23	0x58
 #define BRST		0x59
 
@@ -629,12 +630,24 @@
 #endif /* CONFIG_BLK_DEV_CMD640_ENHANCED */
 }
 
+static int cmd640_test_irq(ide_hwif_t *hwif)
+{
+	struct pci_dev *dev	= to_pci_dev(hwif->dev);
+	int irq_reg		= hwif->channel ? ARTTIM23 : CFR;
+	u8  irq_stat, irq_mask	= hwif->channel ? ARTTIM23_IDE23INTR :
+						  CFR_IDE01INTR;
+
+	pci_read_config_byte(dev, irq_reg, &irq_stat);
+
+	return (irq_stat & irq_mask) ? 1 : 0;
+}
 
 static const struct ide_port_ops cmd640_port_ops = {
 	.init_dev		= cmd640_init_dev,
 #ifdef CONFIG_BLK_DEV_CMD640_ENHANCED
 	.set_pio_mode		= cmd640_set_pio_mode,
 #endif
+	.test_irq		= cmd640_test_irq,
 };
 
 static int pci_conf1(void)
diff --git a/drivers/ide/cmd64x.c b/drivers/ide/cmd64x.c
index 80b777e..03c8620 100644
--- a/drivers/ide/cmd64x.c
+++ b/drivers/ide/cmd64x.c
@@ -7,7 +7,7 @@
  * Copyright (C) 1998		David S. Miller (davem@redhat.com)
  *
  * Copyright (C) 1999-2002	Andre Hedrick <andre@linux-ide.org>
- * Copyright (C) 2007		MontaVista Software, Inc. <source@mvista.com>
+ * Copyright (C) 2007,2009	MontaVista Software, Inc. <source@mvista.com>
  */
 
 #include <linux/module.h>
@@ -118,8 +118,9 @@
 	ide_hwif_t *hwif	= drive->hwif;
 	struct pci_dev *dev	= to_pci_dev(hwif->dev);
 	struct ide_timing *t	= ide_timing_find_mode(XFER_PIO_0 + pio);
+	unsigned long setup_count;
 	unsigned int cycle_time;
-	u8 setup_count, arttim = 0;
+	u8 arttim = 0;
 
 	static const u8 setup_values[] = {0x40, 0x40, 0x40, 0x80, 0, 0xc0};
 	static const u8 arttim_regs[4] = {ARTTIM0, ARTTIM1, ARTTIM23, ARTTIM23};
@@ -140,10 +141,11 @@
 	if (hwif->channel) {
 		ide_drive_t *pair = ide_get_pair_dev(drive);
 
-		drive->drive_data = setup_count;
+		ide_set_drivedata(drive, (void *)setup_count);
 
 		if (pair)
-			setup_count = max_t(u8, setup_count, pair->drive_data);
+			setup_count = max_t(u8, setup_count,
+					(unsigned long)ide_get_drivedata(pair));
 	}
 
 	if (setup_count > 5)		/* shouldn't actually happen... */
@@ -226,11 +228,11 @@
 		(void) pci_write_config_byte(dev, pciU, regU);
 }
 
-static int cmd648_dma_end(ide_drive_t *drive)
+static void cmd648_clear_irq(ide_drive_t *drive)
 {
 	ide_hwif_t *hwif	= drive->hwif;
-	unsigned long base	= hwif->dma_base - (hwif->channel * 8);
-	int err			= ide_dma_end(drive);
+	struct pci_dev *dev	= to_pci_dev(hwif->dev);
+	unsigned long base	= pci_resource_start(dev, 4);
 	u8  irq_mask		= hwif->channel ? MRDMODE_INTR_CH1 :
 						  MRDMODE_INTR_CH0;
 	u8  mrdmode		= inb(base + 1);
@@ -238,11 +240,9 @@
 	/* clear the interrupt bit */
 	outb((mrdmode & ~(MRDMODE_INTR_CH0 | MRDMODE_INTR_CH1)) | irq_mask,
 	     base + 1);
-
-	return err;
 }
 
-static int cmd64x_dma_end(ide_drive_t *drive)
+static void cmd64x_clear_irq(ide_drive_t *drive)
 {
 	ide_hwif_t *hwif	= drive->hwif;
 	struct pci_dev *dev	= to_pci_dev(hwif->dev);
@@ -250,62 +250,40 @@
 	u8  irq_mask		= hwif->channel ? ARTTIM23_INTR_CH1 :
 						  CFR_INTR_CH0;
 	u8  irq_stat		= 0;
-	int err			= ide_dma_end(drive);
 
 	(void) pci_read_config_byte(dev, irq_reg, &irq_stat);
 	/* clear the interrupt bit */
 	(void) pci_write_config_byte(dev, irq_reg, irq_stat | irq_mask);
-
-	return err;
 }
 
-static int cmd648_dma_test_irq(ide_drive_t *drive)
+static int cmd648_test_irq(ide_hwif_t *hwif)
 {
-	ide_hwif_t *hwif	= drive->hwif;
-	unsigned long base	= hwif->dma_base - (hwif->channel * 8);
+	struct pci_dev *dev	= to_pci_dev(hwif->dev);
+	unsigned long base	= pci_resource_start(dev, 4);
 	u8 irq_mask		= hwif->channel ? MRDMODE_INTR_CH1 :
 						  MRDMODE_INTR_CH0;
-	u8 dma_stat		= inb(hwif->dma_base + ATA_DMA_STATUS);
 	u8 mrdmode		= inb(base + 1);
 
-#ifdef DEBUG
-	printk("%s: dma_stat: 0x%02x mrdmode: 0x%02x irq_mask: 0x%02x\n",
-	       drive->name, dma_stat, mrdmode, irq_mask);
-#endif
-	if (!(mrdmode & irq_mask))
-		return 0;
+	pr_debug("%s: mrdmode: 0x%02x irq_mask: 0x%02x\n",
+		 hwif->name, mrdmode, irq_mask);
 
-	/* return 1 if INTR asserted */
-	if (dma_stat & 4)
-		return 1;
-
-	return 0;
+	return (mrdmode & irq_mask) ? 1 : 0;
 }
 
-static int cmd64x_dma_test_irq(ide_drive_t *drive)
+static int cmd64x_test_irq(ide_hwif_t *hwif)
 {
-	ide_hwif_t *hwif	= drive->hwif;
 	struct pci_dev *dev	= to_pci_dev(hwif->dev);
 	int irq_reg		= hwif->channel ? ARTTIM23 : CFR;
 	u8  irq_mask		= hwif->channel ? ARTTIM23_INTR_CH1 :
 						  CFR_INTR_CH0;
-	u8  dma_stat		= inb(hwif->dma_base + ATA_DMA_STATUS);
 	u8  irq_stat		= 0;
 
 	(void) pci_read_config_byte(dev, irq_reg, &irq_stat);
 
-#ifdef DEBUG
-	printk("%s: dma_stat: 0x%02x irq_stat: 0x%02x irq_mask: 0x%02x\n",
-	       drive->name, dma_stat, irq_stat, irq_mask);
-#endif
-	if (!(irq_stat & irq_mask))
-		return 0;
+	pr_debug("%s: irq_stat: 0x%02x irq_mask: 0x%02x\n",
+		 hwif->name, irq_stat, irq_mask);
 
-	/* return 1 if INTR asserted */
-	if (dma_stat & 4)
-		return 1;
-
-	return 0;
+	return (irq_stat & irq_mask) ? 1 : 0;
 }
 
 /*
@@ -370,18 +348,17 @@
 static const struct ide_port_ops cmd64x_port_ops = {
 	.set_pio_mode		= cmd64x_set_pio_mode,
 	.set_dma_mode		= cmd64x_set_dma_mode,
+	.clear_irq		= cmd64x_clear_irq,
+	.test_irq		= cmd64x_test_irq,
 	.cable_detect		= cmd64x_cable_detect,
 };
 
-static const struct ide_dma_ops cmd64x_dma_ops = {
-	.dma_host_set		= ide_dma_host_set,
-	.dma_setup		= ide_dma_setup,
-	.dma_start		= ide_dma_start,
-	.dma_end		= cmd64x_dma_end,
-	.dma_test_irq		= cmd64x_dma_test_irq,
-	.dma_lost_irq		= ide_dma_lost_irq,
-	.dma_timer_expiry	= ide_dma_sff_timer_expiry,
-	.dma_sff_read_status	= ide_dma_sff_read_status,
+static const struct ide_port_ops cmd648_port_ops = {
+	.set_pio_mode		= cmd64x_set_pio_mode,
+	.set_dma_mode		= cmd64x_set_dma_mode,
+	.clear_irq		= cmd648_clear_irq,
+	.test_irq		= cmd648_test_irq,
+	.cable_detect		= cmd64x_cable_detect,
 };
 
 static const struct ide_dma_ops cmd646_rev1_dma_ops = {
@@ -395,24 +372,12 @@
 	.dma_sff_read_status	= ide_dma_sff_read_status,
 };
 
-static const struct ide_dma_ops cmd648_dma_ops = {
-	.dma_host_set		= ide_dma_host_set,
-	.dma_setup		= ide_dma_setup,
-	.dma_start		= ide_dma_start,
-	.dma_end		= cmd648_dma_end,
-	.dma_test_irq		= cmd648_dma_test_irq,
-	.dma_lost_irq		= ide_dma_lost_irq,
-	.dma_timer_expiry	= ide_dma_sff_timer_expiry,
-	.dma_sff_read_status	= ide_dma_sff_read_status,
-};
-
 static const struct ide_port_info cmd64x_chipsets[] __devinitdata = {
 	{	/* 0: CMD643 */
 		.name		= DRV_NAME,
 		.init_chipset	= init_chipset_cmd64x,
 		.enablebits	= {{0x00,0x00,0x00}, {0x51,0x08,0x08}},
 		.port_ops	= &cmd64x_port_ops,
-		.dma_ops	= &cmd64x_dma_ops,
 		.host_flags	= IDE_HFLAG_CLEAR_SIMPLEX |
 				  IDE_HFLAG_ABUSE_PREFETCH,
 		.pio_mask	= ATA_PIO5,
@@ -423,8 +388,7 @@
 		.name		= DRV_NAME,
 		.init_chipset	= init_chipset_cmd64x,
 		.enablebits	= {{0x51,0x04,0x04}, {0x51,0x08,0x08}},
-		.port_ops	= &cmd64x_port_ops,
-		.dma_ops	= &cmd648_dma_ops,
+		.port_ops	= &cmd648_port_ops,
 		.host_flags	= IDE_HFLAG_SERIALIZE |
 				  IDE_HFLAG_ABUSE_PREFETCH,
 		.pio_mask	= ATA_PIO5,
@@ -435,8 +399,7 @@
 		.name		= DRV_NAME,
 		.init_chipset	= init_chipset_cmd64x,
 		.enablebits	= {{0x51,0x04,0x04}, {0x51,0x08,0x08}},
-		.port_ops	= &cmd64x_port_ops,
-		.dma_ops	= &cmd648_dma_ops,
+		.port_ops	= &cmd648_port_ops,
 		.host_flags	= IDE_HFLAG_ABUSE_PREFETCH,
 		.pio_mask	= ATA_PIO5,
 		.mwdma_mask	= ATA_MWDMA2,
@@ -446,8 +409,7 @@
 		.name		= DRV_NAME,
 		.init_chipset	= init_chipset_cmd64x,
 		.enablebits	= {{0x51,0x04,0x04}, {0x51,0x08,0x08}},
-		.port_ops	= &cmd64x_port_ops,
-		.dma_ops	= &cmd648_dma_ops,
+		.port_ops	= &cmd648_port_ops,
 		.host_flags	= IDE_HFLAG_ABUSE_PREFETCH,
 		.pio_mask	= ATA_PIO5,
 		.mwdma_mask	= ATA_MWDMA2,
@@ -484,10 +446,9 @@
 			 */
 			if (dev->revision < 3) {
 				d.enablebits[0].reg = 0;
+				d.port_ops = &cmd64x_port_ops;
 				if (dev->revision == 1)
 					d.dma_ops = &cmd646_rev1_dma_ops;
-				else
-					d.dma_ops = &cmd64x_dma_ops;
 			}
 		}
 	}
diff --git a/drivers/ide/cs5536.c b/drivers/ide/cs5536.c
index 0332a95..9623b85 100644
--- a/drivers/ide/cs5536.c
+++ b/drivers/ide/cs5536.c
@@ -146,14 +146,16 @@
 	struct pci_dev *pdev = to_pci_dev(drive->hwif->dev);
 	ide_drive_t *pair = ide_get_pair_dev(drive);
 	int cshift = (drive->dn & 1) ? IDE_CAST_D1_SHIFT : IDE_CAST_D0_SHIFT;
+	unsigned long timings = (unsigned long)ide_get_drivedata(drive);
 	u32 cast;
 	u8 cmd_pio = pio;
 
 	if (pair)
 		cmd_pio = min(pio, ide_get_best_pio_mode(pair, 255, 4));
 
-	drive->drive_data &= (IDE_DRV_MASK << 8);
-	drive->drive_data |= drv_timings[pio];
+	timings &= (IDE_DRV_MASK << 8);
+	timings |= drv_timings[pio];
+	ide_set_drivedata(drive, (void *)timings);
 
 	cs5536_program_dtc(drive, drv_timings[pio]);
 
@@ -186,6 +188,7 @@
 
 	struct pci_dev *pdev = to_pci_dev(drive->hwif->dev);
 	int dshift = (drive->dn & 1) ? IDE_D1_SHIFT : IDE_D0_SHIFT;
+	unsigned long timings = (unsigned long)ide_get_drivedata(drive);
 	u32 etc;
 
 	cs5536_read(pdev, ETC, &etc);
@@ -195,8 +198,9 @@
 		etc |= udma_timings[mode - XFER_UDMA_0] << dshift;
 	} else { /* MWDMA */
 		etc &= ~(IDE_ETC_UDMA_MASK << dshift);
-		drive->drive_data &= IDE_DRV_MASK;
-		drive->drive_data |= mwdma_timings[mode - XFER_MW_DMA_0] << 8;
+		timings &= IDE_DRV_MASK;
+		timings |= mwdma_timings[mode - XFER_MW_DMA_0] << 8;
+		ide_set_drivedata(drive, (void *)timings);
 	}
 
 	cs5536_write(pdev, ETC, etc);
@@ -204,9 +208,11 @@
 
 static void cs5536_dma_start(ide_drive_t *drive)
 {
+	unsigned long timings = (unsigned long)ide_get_drivedata(drive);
+
 	if (drive->current_speed < XFER_UDMA_0 &&
-	    (drive->drive_data >> 8) != (drive->drive_data & IDE_DRV_MASK))
-		cs5536_program_dtc(drive, drive->drive_data >> 8);
+	    (timings >> 8) != (timings & IDE_DRV_MASK))
+		cs5536_program_dtc(drive, timings >> 8);
 
 	ide_dma_start(drive);
 }
@@ -214,10 +220,11 @@
 static int cs5536_dma_end(ide_drive_t *drive)
 {
 	int ret = ide_dma_end(drive);
+	unsigned long timings = (unsigned long)ide_get_drivedata(drive);
 
 	if (drive->current_speed < XFER_UDMA_0 &&
-	    (drive->drive_data >> 8) != (drive->drive_data & IDE_DRV_MASK))
-		cs5536_program_dtc(drive, drive->drive_data & IDE_DRV_MASK);
+	    (timings >> 8) != (timings & IDE_DRV_MASK))
+		cs5536_program_dtc(drive, timings & IDE_DRV_MASK);
 
 	return ret;
 }
diff --git a/drivers/ide/falconide.c b/drivers/ide/falconide.c
index 22fa273..a5a07cc 100644
--- a/drivers/ide/falconide.c
+++ b/drivers/ide/falconide.c
@@ -128,7 +128,6 @@
 	hw->io_ports.ctl_addr = ATA_HD_BASE + ATA_HD_CONTROL;
 
 	hw->irq = IRQ_MFP_IDE;
-	hw->ack_intr = NULL;
 }
 
     /*
diff --git a/drivers/ide/gayle.c b/drivers/ide/gayle.c
index 4451a6a..b9e517d 100644
--- a/drivers/ide/gayle.c
+++ b/drivers/ide/gayle.c
@@ -66,7 +66,7 @@
      *  Check and acknowledge the interrupt status
      */
 
-static int gayle_ack_intr_a4000(ide_hwif_t *hwif)
+static int gayle_test_irq(ide_hwif_t *hwif)
 {
     unsigned char ch;
 
@@ -76,21 +76,16 @@
     return 1;
 }
 
-static int gayle_ack_intr_a1200(ide_hwif_t *hwif)
+static void gayle_a1200_clear_irq(ide_drive_t *drive)
 {
-    unsigned char ch;
+    ide_hwif_t *hwif = drive->hwif;
 
-    ch = z_readb(hwif->io_ports.irq_addr);
-    if (!(ch & GAYLE_IRQ_IDE))
-	return 0;
     (void)z_readb(hwif->io_ports.status_addr);
     z_writeb(0x7c, hwif->io_ports.irq_addr);
-    return 1;
 }
 
 static void __init gayle_setup_ports(struct ide_hw *hw, unsigned long base,
-				     unsigned long ctl, unsigned long irq_port,
-				     ide_ack_intr_t *ack_intr)
+				     unsigned long ctl, unsigned long irq_port)
 {
 	int i;
 
@@ -105,9 +100,17 @@
 	hw->io_ports.irq_addr = irq_port;
 
 	hw->irq = IRQ_AMIGA_PORTS;
-	hw->ack_intr = ack_intr;
 }
 
+static const struct ide_port_ops gayle_a4000_port_ops = {
+	.test_irq		= gayle_test_irq,
+};
+
+static const struct ide_port_ops gayle_a1200_port_ops = {
+	.clear_irq		= gayle_a1200_clear_irq,
+	.test_irq		= gayle_test_irq,
+};
+
 static const struct ide_port_info gayle_port_info = {
 	.host_flags		= IDE_HFLAG_MMIO | IDE_HFLAG_SERIALIZE |
 				  IDE_HFLAG_NO_DMA,
@@ -123,9 +126,9 @@
 {
     unsigned long phys_base, res_start, res_n;
     unsigned long base, ctrlport, irqport;
-    ide_ack_intr_t *ack_intr;
     int a4000, i, rc;
     struct ide_hw hw[GAYLE_NUM_HWIFS], *hws[GAYLE_NUM_HWIFS];
+    struct ide_port_info d = gayle_port_info;
 
     if (!MACH_IS_AMIGA)
 	return -ENODEV;
@@ -148,11 +151,11 @@
 	if (a4000) {
 	    phys_base = GAYLE_BASE_4000;
 	    irqport = (unsigned long)ZTWO_VADDR(GAYLE_IRQ_4000);
-	    ack_intr = gayle_ack_intr_a4000;
+	    d.port_ops = &gayle_a4000_port_ops;
 	} else {
 	    phys_base = GAYLE_BASE_1200;
 	    irqport = (unsigned long)ZTWO_VADDR(GAYLE_IRQ_1200);
-	    ack_intr = gayle_ack_intr_a1200;
+	    d.port_ops = &gayle_a1200_port_ops;
 	}
 
 	res_start = ((unsigned long)phys_base) & ~(GAYLE_NEXT_PORT-1);
@@ -165,12 +168,12 @@
 	base = (unsigned long)ZTWO_VADDR(phys_base + i * GAYLE_NEXT_PORT);
 	ctrlport = GAYLE_HAS_CONTROL_REG ? (base + GAYLE_CONTROL) : 0;
 
-	gayle_setup_ports(&hw[i], base, ctrlport, irqport, ack_intr);
+	gayle_setup_ports(&hw[i], base, ctrlport, irqport);
 
 	hws[i] = &hw[i];
     }
 
-    rc = ide_host_add(&gayle_port_info, hws, i, NULL);
+    rc = ide_host_add(&d, hws, i, NULL);
     if (rc)
 	release_mem_region(res_start, res_n);
 
diff --git a/drivers/ide/ht6560b.c b/drivers/ide/ht6560b.c
index 2fb0f29..aafed80 100644
--- a/drivers/ide/ht6560b.c
+++ b/drivers/ide/ht6560b.c
@@ -44,7 +44,12 @@
  *    bit3 (0x08): "1" 3 cycle time, "0" 2 cycle time	      (?)
  */
 #define HT_CONFIG_PORT	  0x3e6
-#define HT_CONFIG(drivea) (u8)(((drivea)->drive_data & 0xff00) >> 8)
+
+static inline u8 HT_CONFIG(ide_drive_t *drive)
+{
+	return ((unsigned long)ide_get_drivedata(drive) & 0xff00) >> 8;
+}
+
 /*
  * FIFO + PREFETCH (both a/b-model)
  */
@@ -90,7 +95,11 @@
  * Active Time for each drive. Smaller value gives higher speed.
  * In case of failures you should probably fall back to a higher value.
  */
-#define HT_TIMING(drivea) (u8)((drivea)->drive_data & 0x00ff)
+static inline u8 HT_TIMING(ide_drive_t *drive)
+{
+	return (unsigned long)ide_get_drivedata(drive) & 0x00ff;
+}
+
 #define HT_TIMING_DEFAULT 0xff
 
 /*
@@ -242,23 +251,27 @@
  */
 static void ht_set_prefetch(ide_drive_t *drive, u8 state)
 {
-	unsigned long flags;
+	unsigned long flags, config;
 	int t = HT_PREFETCH_MODE << 8;
 
 	spin_lock_irqsave(&ht6560b_lock, flags);
 
+	config = (unsigned long)ide_get_drivedata(drive);
+
 	/*
 	 *  Prefetch mode and unmask irq seems to conflict
 	 */
 	if (state) {
-		drive->drive_data |= t;   /* enable prefetch mode */
+		config |= t;   /* enable prefetch mode */
 		drive->dev_flags |= IDE_DFLAG_NO_UNMASK;
 		drive->dev_flags &= ~IDE_DFLAG_UNMASK;
 	} else {
-		drive->drive_data &= ~t;  /* disable prefetch mode */
+		config &= ~t;  /* disable prefetch mode */
 		drive->dev_flags &= ~IDE_DFLAG_NO_UNMASK;
 	}
 
+	ide_set_drivedata(drive, (void *)config);
+
 	spin_unlock_irqrestore(&ht6560b_lock, flags);
 
 #ifdef DEBUG
@@ -268,7 +281,7 @@
 
 static void ht6560b_set_pio_mode(ide_drive_t *drive, const u8 pio)
 {
-	unsigned long flags;
+	unsigned long flags, config;
 	u8 timing;
 	
 	switch (pio) {
@@ -281,8 +294,10 @@
 	timing = ht_pio2timings(drive, pio);
 
 	spin_lock_irqsave(&ht6560b_lock, flags);
-	drive->drive_data &= 0xff00;
-	drive->drive_data |= timing;
+	config = (unsigned long)ide_get_drivedata(drive);
+	config &= 0xff00;
+	config |= timing;
+	ide_set_drivedata(drive, (void *)config);
 	spin_unlock_irqrestore(&ht6560b_lock, flags);
 
 #ifdef DEBUG
@@ -299,7 +314,7 @@
 	if (hwif->channel)
 		t |= (HT_SECONDARY_IF << 8);
 
-	drive->drive_data = t;
+	ide_set_drivedata(drive, (void *)t);
 }
 
 static int probe_ht6560b;
diff --git a/drivers/ide/icside.c b/drivers/ide/icside.c
index 5af3d0f..0f67f1a 100644
--- a/drivers/ide/icside.c
+++ b/drivers/ide/icside.c
@@ -187,7 +187,8 @@
  */
 static void icside_set_dma_mode(ide_drive_t *drive, const u8 xfer_mode)
 {
-	int cycle_time, use_dma_info = 0;
+	unsigned long cycle_time;
+	int use_dma_info = 0;
 
 	switch (xfer_mode) {
 	case XFER_MW_DMA_2:
@@ -218,10 +219,11 @@
 	if (use_dma_info && drive->id[ATA_ID_EIDE_DMA_TIME] > cycle_time)
 		cycle_time = drive->id[ATA_ID_EIDE_DMA_TIME];
 
-	drive->drive_data = cycle_time;
+	ide_set_drivedata(drive, (void *)cycle_time);
 
 	printk("%s: %s selected (peak %dMB/s)\n", drive->name,
-		ide_xfer_verbose(xfer_mode), 2000 / drive->drive_data);
+		ide_xfer_verbose(xfer_mode),
+		2000 / (unsigned long)ide_get_drivedata(drive));
 }
 
 static const struct ide_port_ops icside_v6_port_ops = {
@@ -277,7 +279,7 @@
 	/*
 	 * Select the correct timing for this drive.
 	 */
-	set_dma_speed(ec->dma, drive->drive_data);
+	set_dma_speed(ec->dma, (unsigned long)ide_get_drivedata(drive));
 
 	/*
 	 * Tell the DMA engine about the SG table and
diff --git a/drivers/ide/ide-atapi.c b/drivers/ide/ide-atapi.c
index 702ef64..eb2181a 100644
--- a/drivers/ide/ide-atapi.c
+++ b/drivers/ide/ide-atapi.c
@@ -10,6 +10,9 @@
 
 #include <scsi/scsi.h>
 
+#define DRV_NAME "ide-atapi"
+#define PFX DRV_NAME ": "
+
 #ifdef DEBUG
 #define debug_log(fmt, args...) \
 	printk(KERN_INFO "ide: " fmt, ## args)
@@ -74,8 +77,6 @@
 void ide_init_pc(struct ide_atapi_pc *pc)
 {
 	memset(pc, 0, sizeof(*pc));
-	pc->buf = pc->pc_buf;
-	pc->buf_size = IDE_PC_BUFFER_SIZE;
 }
 EXPORT_SYMBOL_GPL(ide_init_pc);
 
@@ -84,7 +85,7 @@
  * and wait for it to be serviced.
  */
 int ide_queue_pc_tail(ide_drive_t *drive, struct gendisk *disk,
-		      struct ide_atapi_pc *pc)
+		      struct ide_atapi_pc *pc, void *buf, unsigned int bufflen)
 {
 	struct request *rq;
 	int error;
@@ -93,8 +94,8 @@
 	rq->cmd_type = REQ_TYPE_SPECIAL;
 	rq->special = (char *)pc;
 
-	if (pc->req_xfer) {
-		error = blk_rq_map_kern(drive->queue, rq, pc->buf, pc->req_xfer,
+	if (buf && bufflen) {
+		error = blk_rq_map_kern(drive->queue, rq, buf, bufflen,
 					GFP_NOIO);
 		if (error)
 			goto put_req;
@@ -117,7 +118,7 @@
 	ide_init_pc(&pc);
 	pc.c[0] = TEST_UNIT_READY;
 
-	return ide_queue_pc_tail(drive, disk, &pc);
+	return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
 }
 EXPORT_SYMBOL_GPL(ide_do_test_unit_ready);
 
@@ -132,7 +133,7 @@
 	if (drive->media == ide_tape)
 		pc.flags |= PC_FLAG_WAIT_FOR_DSC;
 
-	return ide_queue_pc_tail(drive, disk, &pc);
+	return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
 }
 EXPORT_SYMBOL_GPL(ide_do_start_stop);
 
@@ -147,7 +148,7 @@
 	pc.c[0] = ALLOW_MEDIUM_REMOVAL;
 	pc.c[4] = on;
 
-	return ide_queue_pc_tail(drive, disk, &pc);
+	return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
 }
 EXPORT_SYMBOL_GPL(ide_set_media_lock);
 
@@ -172,8 +173,6 @@
 	unsigned int cmd_len, sense_len;
 	int err;
 
-	debug_log("%s: enter\n", __func__);
-
 	switch (drive->media) {
 	case ide_floppy:
 		cmd_len = 255;
@@ -201,8 +200,8 @@
 			      GFP_NOIO);
 	if (unlikely(err)) {
 		if (printk_ratelimit())
-			printk(KERN_WARNING "%s: failed to map sense buffer\n",
-			       drive->name);
+			printk(KERN_WARNING PFX "%s: failed to map sense "
+					    "buffer\n", drive->name);
 		return;
 	}
 
@@ -223,7 +222,7 @@
 {
 	/* deferred failure from ide_prep_sense() */
 	if (!drive->sense_rq_armed) {
-		printk(KERN_WARNING "%s: failed queue sense request\n",
+		printk(KERN_WARNING PFX "%s: error queuing a sense request\n",
 		       drive->name);
 		return -ENOMEM;
 	}
@@ -255,8 +254,6 @@
 	/* init pc from sense_rq */
 	ide_init_pc(pc);
 	memcpy(pc->c, sense_rq->cmd, 12);
-	pc->buf = bio_data(sense_rq->bio);	/* pointer to mapped address */
-	pc->req_xfer = blk_rq_bytes(sense_rq);
 
 	if (drive->media == ide_tape)
 		drive->atapi_flags |= IDE_AFLAG_IGNORE_DSC;
@@ -298,7 +295,7 @@
 		break;
 	default:
 		if (!(rq->cmd_flags & REQ_QUIET))
-			printk(KERN_INFO "cmd 0x%x timed out\n",
+			printk(KERN_INFO PFX "cmd 0x%x timed out\n",
 					 rq->cmd[0]);
 		wait = 0;
 		break;
@@ -332,6 +329,55 @@
 EXPORT_SYMBOL_GPL(ide_read_bcount_and_ireason);
 
 /*
+ * Check the contents of the interrupt reason register and attempt to recover if
+ * there are problems.
+ *
+ * Returns:
+ * - 0 if everything's ok
+ * - 1 if the request has to be terminated.
+ */
+int ide_check_ireason(ide_drive_t *drive, struct request *rq, int len,
+		      int ireason, int rw)
+{
+	ide_hwif_t *hwif = drive->hwif;
+
+	debug_log("ireason: 0x%x, rw: 0x%x\n", ireason, rw);
+
+	if (ireason == (!rw << 1))
+		return 0;
+	else if (ireason == (rw << 1)) {
+		printk(KERN_ERR PFX "%s: %s: wrong transfer direction!\n",
+				drive->name, __func__);
+
+		if (dev_is_idecd(drive))
+			ide_pad_transfer(drive, rw, len);
+	} else if (!rw && ireason == ATAPI_COD) {
+		if (dev_is_idecd(drive)) {
+			/*
+			 * Some drives (ASUS) seem to tell us that status info
+			 * is available.  Just get it and ignore.
+			 */
+			(void)hwif->tp_ops->read_status(hwif);
+			return 0;
+		}
+	} else {
+		if (ireason & ATAPI_COD)
+			printk(KERN_ERR PFX "%s: CoD != 0 in %s\n", drive->name,
+					__func__);
+
+		/* drive wants a command packet, or invalid ireason... */
+		printk(KERN_ERR PFX "%s: %s: bad interrupt reason 0x%02x\n",
+				drive->name, __func__, ireason);
+	}
+
+	if (dev_is_idecd(drive) && rq->cmd_type == REQ_TYPE_ATA_PC)
+		rq->cmd_flags |= REQ_FAILED;
+
+	return 1;
+}
+EXPORT_SYMBOL_GPL(ide_check_ireason);
+
+/*
  * This is the usual interrupt handler which will be called during a packet
  * command.  We will transfer some of the data (as requested by the drive)
  * and will re-point interrupt handler to us.
@@ -365,12 +411,12 @@
 
 		if (rc || (drive->media == ide_tape && (stat & ATA_ERR))) {
 			if (drive->media == ide_floppy)
-				printk(KERN_ERR "%s: DMA %s error\n",
+				printk(KERN_ERR PFX "%s: DMA %s error\n",
 					drive->name, rq_data_dir(pc->rq)
 						     ? "write" : "read");
 			pc->flags |= PC_FLAG_DMA_ERROR;
 		} else
-			pc->xferred = pc->req_xfer;
+			rq->resid_len = 0;
 		debug_log("%s: DMA finished\n", drive->name);
 	}
 
@@ -379,7 +425,7 @@
 		int uptodate, error;
 
 		debug_log("Packet command completed, %d bytes transferred\n",
-			  pc->xferred);
+			  blk_rq_bytes(rq));
 
 		pc->flags &= ~PC_FLAG_DMA_IN_PROGRESS;
 
@@ -397,8 +443,8 @@
 				pc->rq->errors++;
 
 			if (rq->cmd[0] == REQUEST_SENSE) {
-				printk(KERN_ERR "%s: I/O error in request sense"
-						" command\n", drive->name);
+				printk(KERN_ERR PFX "%s: I/O error in request "
+						"sense command\n", drive->name);
 				return ide_do_reset(drive);
 			}
 
@@ -446,8 +492,8 @@
 
 	if (pc->flags & PC_FLAG_DMA_IN_PROGRESS) {
 		pc->flags &= ~PC_FLAG_DMA_IN_PROGRESS;
-		printk(KERN_ERR "%s: The device wants to issue more interrupts "
-				"in DMA mode\n", drive->name);
+		printk(KERN_ERR PFX "%s: The device wants to issue more "
+				"interrupts in DMA mode\n", drive->name);
 		ide_dma_off(drive);
 		return ide_do_reset(drive);
 	}
@@ -455,33 +501,22 @@
 	/* Get the number of bytes to transfer on this interrupt. */
 	ide_read_bcount_and_ireason(drive, &bcount, &ireason);
 
-	if (ireason & ATAPI_COD) {
-		printk(KERN_ERR "%s: CoD != 0 in %s\n", drive->name, __func__);
+	if (ide_check_ireason(drive, rq, bcount, ireason, write))
 		return ide_do_reset(drive);
-	}
-
-	if (((ireason & ATAPI_IO) == ATAPI_IO) == write) {
-		/* Hopefully, we will never get here */
-		printk(KERN_ERR "%s: We wanted to %s, but the device wants us "
-				"to %s!\n", drive->name,
-				(ireason & ATAPI_IO) ? "Write" : "Read",
-				(ireason & ATAPI_IO) ? "Read" : "Write");
-		return ide_do_reset(drive);
-	}
 
 	done = min_t(unsigned int, bcount, cmd->nleft);
 	ide_pio_bytes(drive, cmd, write, done);
 
 	/* Update transferred byte count */
-	pc->xferred += done;
+	rq->resid_len -= done;
 
 	bcount -= done;
 
 	if (bcount)
 		ide_pad_transfer(drive, write, bcount);
 
-	debug_log("[cmd %x] transferred %d bytes, padded %d bytes\n",
-		  rq->cmd[0], done, bcount);
+	debug_log("[cmd %x] transferred %d bytes, padded %d bytes, resid: %u\n",
+		  rq->cmd[0], done, bcount, rq->resid_len);
 
 	/* And set the interrupt handler again */
 	ide_set_handler(drive, ide_pc_intr, timeout);
@@ -515,13 +550,13 @@
 
 	while (retries-- && ((ireason & ATAPI_COD) == 0 ||
 		(ireason & ATAPI_IO))) {
-		printk(KERN_ERR "%s: (IO,CoD != (0,1) while issuing "
+		printk(KERN_ERR PFX "%s: (IO,CoD != (0,1) while issuing "
 				"a packet command, retrying\n", drive->name);
 		udelay(100);
 		ireason = ide_read_ireason(drive);
 		if (retries == 0) {
-			printk(KERN_ERR "%s: (IO,CoD != (0,1) while issuing "
-					"a packet command, ignoring\n",
+			printk(KERN_ERR PFX "%s: (IO,CoD != (0,1) while issuing"
+					" a packet command, ignoring\n",
 					drive->name);
 			ireason |= ATAPI_COD;
 			ireason &= ~ATAPI_IO;
@@ -552,7 +587,7 @@
 	u8 ireason;
 
 	if (ide_wait_stat(&startstop, drive, ATA_DRQ, ATA_BUSY, WAIT_READY)) {
-		printk(KERN_ERR "%s: Strange, packet command initiated yet "
+		printk(KERN_ERR PFX "%s: Strange, packet command initiated yet "
 				"DRQ isn't asserted\n", drive->name);
 		return startstop;
 	}
@@ -594,8 +629,8 @@
 			ireason = ide_wait_ireason(drive, ireason);
 
 		if ((ireason & ATAPI_COD) == 0 || (ireason & ATAPI_IO)) {
-			printk(KERN_ERR "%s: (IO,CoD) != (0,1) while issuing "
-					"a packet command\n", drive->name);
+			printk(KERN_ERR PFX "%s: (IO,CoD) != (0,1) while "
+				"issuing a packet command\n", drive->name);
 
 			return ide_do_reset(drive);
 		}
@@ -633,7 +668,7 @@
 	ide_hwif_t *hwif = drive->hwif;
 	ide_expiry_t *expiry = NULL;
 	struct request *rq = hwif->rq;
-	unsigned int timeout;
+	unsigned int timeout, bytes;
 	u16 bcount;
 	u8 valid_tf;
 	u8 drq_int = !!(drive->atapi_flags & IDE_AFLAG_DRQ_INTERRUPT);
@@ -649,13 +684,14 @@
 	} else {
 		pc = drive->pc;
 
-		/* We haven't transferred any data yet */
-		pc->xferred = 0;
-
 		valid_tf = IDE_VALID_DEVICE;
-		bcount = ((drive->media == ide_tape) ?
-				pc->req_xfer :
-				min(pc->req_xfer, 63 * 1024));
+		bytes = blk_rq_bytes(rq);
+		bcount = ((drive->media == ide_tape) ? bytes
+						     : min_t(unsigned int,
+							     bytes, 63 * 1024));
+
+		/* We haven't transferred any data yet */
+		rq->resid_len = bcount;
 
 		if (pc->flags & PC_FLAG_DMA_ERROR) {
 			pc->flags &= ~PC_FLAG_DMA_ERROR;
diff --git a/drivers/ide/ide-cd.c b/drivers/ide/ide-cd.c
index 424140c..4a19686 100644
--- a/drivers/ide/ide-cd.c
+++ b/drivers/ide/ide-cd.c
@@ -92,16 +92,16 @@
 	drive->atapi_flags &= ~IDE_AFLAG_TOC_VALID;
 }
 
-static int cdrom_log_sense(ide_drive_t *drive, struct request *rq,
-			   struct request_sense *sense)
+static int cdrom_log_sense(ide_drive_t *drive, struct request *rq)
 {
+	struct request_sense *sense = &drive->sense_data;
 	int log = 0;
 
-	ide_debug_log(IDE_DBG_SENSE, "sense_key: 0x%x", sense->sense_key);
-
 	if (!sense || !rq || (rq->cmd_flags & REQ_QUIET))
 		return 0;
 
+	ide_debug_log(IDE_DBG_SENSE, "sense_key: 0x%x", sense->sense_key);
+
 	switch (sense->sense_key) {
 	case NO_SENSE:
 	case RECOVERED_ERROR:
@@ -140,12 +140,12 @@
 }
 
 static void cdrom_analyze_sense_data(ide_drive_t *drive,
-			      struct request *failed_command,
-			      struct request_sense *sense)
+				     struct request *failed_command)
 {
+	struct request_sense *sense = &drive->sense_data;
+	struct cdrom_info *info = drive->driver_data;
 	unsigned long sector;
 	unsigned long bio_sectors;
-	struct cdrom_info *info = drive->driver_data;
 
 	ide_debug_log(IDE_DBG_SENSE, "error_code: 0x%x, sense_key: 0x%x",
 				     sense->error_code, sense->sense_key);
@@ -154,7 +154,7 @@
 		ide_debug_log(IDE_DBG_SENSE, "failed cmd: 0x%x",
 					     failed_command->cmd[0]);
 
-	if (!cdrom_log_sense(drive, failed_command, sense))
+	if (!cdrom_log_sense(drive, failed_command))
 		return;
 
 	/*
@@ -225,15 +225,14 @@
 			 * sense pointer set.
 			 */
 			memcpy(failed->sense, sense, 18);
-			sense = failed->sense;
 			failed->sense_len = rq->sense_len;
 		}
-		cdrom_analyze_sense_data(drive, failed, sense);
+		cdrom_analyze_sense_data(drive, failed);
 
 		if (ide_end_rq(drive, failed, -EIO, blk_rq_bytes(failed)))
 			BUG();
 	} else
-		cdrom_analyze_sense_data(drive, NULL, sense);
+		cdrom_analyze_sense_data(drive, NULL);
 }
 
 
@@ -410,50 +409,6 @@
 		return 2;
 }
 
-/*
- * Check the contents of the interrupt reason register from the cdrom
- * and attempt to recover if there are problems.  Returns  0 if everything's
- * ok; nonzero if the request has been terminated.
- */
-static int ide_cd_check_ireason(ide_drive_t *drive, struct request *rq,
-				int len, int ireason, int rw)
-{
-	ide_hwif_t *hwif = drive->hwif;
-
-	ide_debug_log(IDE_DBG_FUNC, "ireason: 0x%x, rw: 0x%x", ireason, rw);
-
-	/*
-	 * ireason == 0: the drive wants to receive data from us
-	 * ireason == 2: the drive is expecting to transfer data to us
-	 */
-	if (ireason == (!rw << 1))
-		return 0;
-	else if (ireason == (rw << 1)) {
-
-		/* whoops... */
-		printk(KERN_ERR PFX "%s: %s: wrong transfer direction!\n",
-				drive->name, __func__);
-
-		ide_pad_transfer(drive, rw, len);
-	} else  if (rw == 0 && ireason == 1) {
-		/*
-		 * Some drives (ASUS) seem to tell us that status info is
-		 * available.  Just get it and ignore.
-		 */
-		(void)hwif->tp_ops->read_status(hwif);
-		return 0;
-	} else {
-		/* drive wants a command packet, or invalid ireason... */
-		printk(KERN_ERR PFX "%s: %s: bad interrupt reason 0x%02x\n",
-				drive->name, __func__, ireason);
-	}
-
-	if (rq->cmd_type == REQ_TYPE_ATA_PC)
-		rq->cmd_flags |= REQ_FAILED;
-
-	return -1;
-}
-
 static void ide_cd_request_sense_fixup(ide_drive_t *drive, struct ide_cmd *cmd)
 {
 	struct request *rq = cmd->rq;
@@ -645,8 +600,7 @@
 		goto out_end;
 	}
 
-	/* check which way to transfer data */
-	rc = ide_cd_check_ireason(drive, rq, len, ireason, write);
+	rc = ide_check_ireason(drive, rq, len, ireason, write);
 	if (rc)
 		goto out_end;
 
@@ -713,7 +667,7 @@
 				rq->errors = -EIO;
 		}
 
-		if (uptodate == 0)
+		if (uptodate == 0 && rq->bio)
 			ide_cd_error_cmd(drive, cmd);
 
 		/* make sure it's fully ended */
@@ -831,12 +785,8 @@
 		/* right now this can only be a reset... */
 		uptodate = 1;
 		goto out_end;
-	} else {
-		blk_dump_rq_flags(rq, DRV_NAME " bad flags");
-		if (rq->errors == 0)
-			rq->errors = -EIO;
-		goto out_end;
-	}
+	} else
+		BUG();
 
 	/* prepare sense request for this command */
 	ide_prep_sense(drive, rq);
diff --git a/drivers/ide/ide-disk.c b/drivers/ide/ide-disk.c
index 6a1de21..6951811 100644
--- a/drivers/ide/ide-disk.c
+++ b/drivers/ide/ide-disk.c
@@ -184,14 +184,7 @@
 	ide_hwif_t *hwif = drive->hwif;
 
 	BUG_ON(drive->dev_flags & IDE_DFLAG_BLOCKED);
-
-	if (!blk_fs_request(rq)) {
-		blk_dump_rq_flags(rq, "ide_do_rw_disk - bad command");
-		if (rq->errors == 0)
-			rq->errors = -EIO;
-		ide_complete_rq(drive, -EIO, ide_rq_bytes(rq));
-		return ide_stopped;
-	}
+	BUG_ON(!blk_fs_request(rq));
 
 	ledtrig_ide_activity();
 
diff --git a/drivers/ide/ide-floppy.c b/drivers/ide/ide-floppy.c
index 6509817..8b3f204 100644
--- a/drivers/ide/ide-floppy.c
+++ b/drivers/ide/ide-floppy.c
@@ -77,7 +77,8 @@
 	    (rq && blk_pc_request(rq)))
 		uptodate = 1; /* FIXME */
 	else if (pc->c[0] == GPCMD_REQUEST_SENSE) {
-		u8 *buf = pc->buf;
+
+		u8 *buf = bio_data(rq->bio);
 
 		if (!pc->error) {
 			floppy->sense_key = buf[2] & 0x0F;
@@ -209,8 +210,7 @@
 	pc->rq = rq;
 	if (rq->cmd_flags & REQ_RW)
 		pc->flags |= PC_FLAG_WRITING;
-	pc->buf = NULL;
-	pc->req_xfer = pc->buf_size = blocks * floppy->block_size;
+
 	pc->flags |= PC_FLAG_DMA_OK;
 }
 
@@ -225,9 +225,6 @@
 		if (rq_data_dir(rq) == WRITE)
 			pc->flags |= PC_FLAG_WRITING;
 	}
-	/* pio will be performed by ide_pio_bytes() which handles sg fine */
-	pc->buf = NULL;
-	pc->req_xfer = pc->buf_size = blk_rq_bytes(rq);
 }
 
 static ide_startstop_t ide_floppy_do_request(ide_drive_t *drive,
@@ -272,10 +269,8 @@
 	} else if (blk_pc_request(rq)) {
 		pc = &floppy->queued_pc;
 		idefloppy_blockpc_cmd(floppy, pc, rq);
-	} else {
-		blk_dump_rq_flags(rq, PFX "unsupported command in queue");
-		goto out_end;
-	}
+	} else
+		BUG();
 
 	ide_prep_sense(drive, rq);
 
@@ -286,8 +281,8 @@
 
 	cmd.rq = rq;
 
-	if (blk_fs_request(rq) || pc->req_xfer) {
-		ide_init_sg_cmd(&cmd, pc->req_xfer);
+	if (blk_fs_request(rq) || blk_rq_bytes(rq)) {
+		ide_init_sg_cmd(&cmd, blk_rq_bytes(rq));
 		ide_map_sg(drive, &cmd);
 	}
 
@@ -311,33 +306,33 @@
 {
 	struct ide_disk_obj *floppy = drive->driver_data;
 	struct gendisk *disk = floppy->disk;
-	u8 *page;
+	u8 *page, buf[40];
 	int capacity, lba_capacity;
 	u16 transfer_rate, sector_size, cyls, rpm;
 	u8 heads, sectors;
 
 	ide_floppy_create_mode_sense_cmd(pc, IDEFLOPPY_FLEXIBLE_DISK_PAGE);
 
-	if (ide_queue_pc_tail(drive, disk, pc)) {
+	if (ide_queue_pc_tail(drive, disk, pc, buf, pc->req_xfer)) {
 		printk(KERN_ERR PFX "Can't get flexible disk page params\n");
 		return 1;
 	}
 
-	if (pc->buf[3] & 0x80)
+	if (buf[3] & 0x80)
 		drive->dev_flags |= IDE_DFLAG_WP;
 	else
 		drive->dev_flags &= ~IDE_DFLAG_WP;
 
 	set_disk_ro(disk, !!(drive->dev_flags & IDE_DFLAG_WP));
 
-	page = &pc->buf[8];
+	page = &buf[8];
 
-	transfer_rate = be16_to_cpup((__be16 *)&pc->buf[8 + 2]);
-	sector_size   = be16_to_cpup((__be16 *)&pc->buf[8 + 6]);
-	cyls          = be16_to_cpup((__be16 *)&pc->buf[8 + 8]);
-	rpm           = be16_to_cpup((__be16 *)&pc->buf[8 + 28]);
-	heads         = pc->buf[8 + 4];
-	sectors       = pc->buf[8 + 5];
+	transfer_rate = be16_to_cpup((__be16 *)&buf[8 + 2]);
+	sector_size   = be16_to_cpup((__be16 *)&buf[8 + 6]);
+	cyls          = be16_to_cpup((__be16 *)&buf[8 + 8]);
+	rpm           = be16_to_cpup((__be16 *)&buf[8 + 28]);
+	heads         = buf[8 + 4];
+	sectors       = buf[8 + 5];
 
 	capacity = cyls * heads * sectors * sector_size;
 
@@ -387,22 +382,19 @@
 	drive->capacity64 = 0;
 
 	ide_floppy_create_read_capacity_cmd(&pc);
-	pc.buf = &pc_buf[0];
-	pc.buf_size = sizeof(pc_buf);
-
-	if (ide_queue_pc_tail(drive, disk, &pc)) {
+	if (ide_queue_pc_tail(drive, disk, &pc, pc_buf, pc.req_xfer)) {
 		printk(KERN_ERR PFX "Can't get floppy parameters\n");
 		return 1;
 	}
-	header_len = pc.buf[3];
-	cap_desc = &pc.buf[4];
+	header_len = pc_buf[3];
+	cap_desc = &pc_buf[4];
 	desc_cnt = header_len / 8; /* capacity descriptor of 8 bytes */
 
 	for (i = 0; i < desc_cnt; i++) {
 		unsigned int desc_start = 4 + i*8;
 
-		blocks = be32_to_cpup((__be32 *)&pc.buf[desc_start]);
-		length = be16_to_cpup((__be16 *)&pc.buf[desc_start + 6]);
+		blocks = be32_to_cpup((__be32 *)&pc_buf[desc_start]);
+		length = be16_to_cpup((__be16 *)&pc_buf[desc_start + 6]);
 
 		ide_debug_log(IDE_DBG_PROBE, "Descriptor %d: %dkB, %d blocks, "
 					     "%d sector size",
@@ -415,7 +407,7 @@
 		 * the code below is valid only for the 1st descriptor, ie i=0
 		 */
 
-		switch (pc.buf[desc_start + 4] & 0x03) {
+		switch (pc_buf[desc_start + 4] & 0x03) {
 		/* Clik! drive returns this instead of CAPACITY_CURRENT */
 		case CAPACITY_UNFORMATTED:
 			if (!(drive->atapi_flags & IDE_AFLAG_CLIK_DRIVE))
@@ -464,7 +456,7 @@
 			break;
 		}
 		ide_debug_log(IDE_DBG_PROBE, "Descriptor 0 Code: %d",
-					     pc.buf[desc_start + 4] & 0x03);
+					     pc_buf[desc_start + 4] & 0x03);
 	}
 
 	/* Clik! disk does not support get_flexible_disk_page */
diff --git a/drivers/ide/ide-floppy_ioctl.c b/drivers/ide/ide-floppy_ioctl.c
index cd8a420..9c22882 100644
--- a/drivers/ide/ide-floppy_ioctl.c
+++ b/drivers/ide/ide-floppy_ioctl.c
@@ -47,15 +47,13 @@
 		return -EINVAL;
 
 	ide_floppy_create_read_capacity_cmd(pc);
-	pc->buf = &pc_buf[0];
-	pc->buf_size = sizeof(pc_buf);
 
-	if (ide_queue_pc_tail(drive, floppy->disk, pc)) {
+	if (ide_queue_pc_tail(drive, floppy->disk, pc, pc_buf, pc->req_xfer)) {
 		printk(KERN_ERR "ide-floppy: Can't get floppy parameters\n");
 		return -EIO;
 	}
 
-	header_len = pc->buf[3];
+	header_len = pc_buf[3];
 	desc_cnt = header_len / 8; /* capacity descriptor of 8 bytes */
 
 	u_index = 0;
@@ -72,8 +70,8 @@
 		if (u_index >= u_array_size)
 			break;	/* User-supplied buffer too small */
 
-		blocks = be32_to_cpup((__be32 *)&pc->buf[desc_start]);
-		length = be16_to_cpup((__be16 *)&pc->buf[desc_start + 6]);
+		blocks = be32_to_cpup((__be32 *)&pc_buf[desc_start]);
+		length = be16_to_cpup((__be16 *)&pc_buf[desc_start + 6]);
 
 		if (put_user(blocks, argp))
 			return -EFAULT;
@@ -94,40 +92,42 @@
 	return 0;
 }
 
-static void ide_floppy_create_format_unit_cmd(struct ide_atapi_pc *pc, int b,
-		int l, int flags)
+static void ide_floppy_create_format_unit_cmd(struct ide_atapi_pc *pc,
+					      u8 *buf, int b, int l,
+					      int flags)
 {
 	ide_init_pc(pc);
 	pc->c[0] = GPCMD_FORMAT_UNIT;
 	pc->c[1] = 0x17;
 
-	memset(pc->buf, 0, 12);
-	pc->buf[1] = 0xA2;
+	memset(buf, 0, 12);
+	buf[1] = 0xA2;
 	/* Default format list header, u8 1: FOV/DCRT/IMM bits set */
 
 	if (flags & 1)				/* Verify bit on... */
-		pc->buf[1] ^= 0x20;		/* ... turn off DCRT bit */
-	pc->buf[3] = 8;
+		buf[1] ^= 0x20;			/* ... turn off DCRT bit */
+	buf[3] = 8;
 
-	put_unaligned(cpu_to_be32(b), (unsigned int *)(&pc->buf[4]));
-	put_unaligned(cpu_to_be32(l), (unsigned int *)(&pc->buf[8]));
-	pc->buf_size = 12;
+	put_unaligned(cpu_to_be32(b), (unsigned int *)(&buf[4]));
+	put_unaligned(cpu_to_be32(l), (unsigned int *)(&buf[8]));
+	pc->req_xfer = 12;
 	pc->flags |= PC_FLAG_WRITING;
 }
 
 static int ide_floppy_get_sfrp_bit(ide_drive_t *drive, struct ide_atapi_pc *pc)
 {
 	struct ide_disk_obj *floppy = drive->driver_data;
+	u8 buf[20];
 
 	drive->atapi_flags &= ~IDE_AFLAG_SRFP;
 
 	ide_floppy_create_mode_sense_cmd(pc, IDEFLOPPY_CAPABILITIES_PAGE);
 	pc->flags |= PC_FLAG_SUPPRESS_ERROR;
 
-	if (ide_queue_pc_tail(drive, floppy->disk, pc))
+	if (ide_queue_pc_tail(drive, floppy->disk, pc, buf, pc->req_xfer))
 		return 1;
 
-	if (pc->buf[8 + 2] & 0x40)
+	if (buf[8 + 2] & 0x40)
 		drive->atapi_flags |= IDE_AFLAG_SRFP;
 
 	return 0;
@@ -137,6 +137,7 @@
 				  int __user *arg)
 {
 	struct ide_disk_obj *floppy = drive->driver_data;
+	u8 buf[12];
 	int blocks, length, flags, err = 0;
 
 	if (floppy->openers > 1) {
@@ -170,9 +171,9 @@
 	}
 
 	ide_floppy_get_sfrp_bit(drive, pc);
-	ide_floppy_create_format_unit_cmd(pc, blocks, length, flags);
+	ide_floppy_create_format_unit_cmd(pc, buf, blocks, length, flags);
 
-	if (ide_queue_pc_tail(drive, floppy->disk, pc))
+	if (ide_queue_pc_tail(drive, floppy->disk, pc, buf, pc->req_xfer))
 		err = -EIO;
 
 out:
@@ -196,11 +197,13 @@
 					  int __user *arg)
 {
 	struct ide_disk_obj *floppy = drive->driver_data;
+	u8 sense_buf[18];
 	int progress_indication = 0x10000;
 
 	if (drive->atapi_flags & IDE_AFLAG_SRFP) {
 		ide_create_request_sense_cmd(drive, pc);
-		if (ide_queue_pc_tail(drive, floppy->disk, pc))
+		if (ide_queue_pc_tail(drive, floppy->disk, pc, sense_buf,
+				      pc->req_xfer))
 			return -EIO;
 
 		if (floppy->sense_key == 2 &&
diff --git a/drivers/ide/ide-io.c b/drivers/ide/ide-io.c
index 272cc38..1059f80 100644
--- a/drivers/ide/ide-io.c
+++ b/drivers/ide/ide-io.c
@@ -683,8 +683,9 @@
 		} else if (drive_is_ready(drive)) {
 			if (drive->waiting_for_dma)
 				hwif->dma_ops->dma_lost_irq(drive);
-			if (hwif->ack_intr)
-				hwif->ack_intr(hwif);
+			if (hwif->port_ops && hwif->port_ops->clear_irq)
+				hwif->port_ops->clear_irq(drive);
+
 			printk(KERN_WARNING "%s: lost interrupt\n",
 				drive->name);
 			startstop = handler(drive);
@@ -803,7 +804,8 @@
 
 	spin_lock_irqsave(&hwif->lock, flags);
 
-	if (hwif->ack_intr && hwif->ack_intr(hwif) == 0)
+	if (hwif->port_ops && hwif->port_ops->test_irq &&
+	    hwif->port_ops->test_irq(hwif) == 0)
 		goto out;
 
 	handler = hwif->handler;
diff --git a/drivers/ide/ide-ioctls.c b/drivers/ide/ide-ioctls.c
index 5991b23..82f252c 100644
--- a/drivers/ide/ide-ioctls.c
+++ b/drivers/ide/ide-ioctls.c
@@ -118,7 +118,6 @@
 	u8 args[4], xfer_rate = 0;
 	struct ide_cmd cmd;
 	struct ide_taskfile *tf = &cmd.tf;
-	u16 *id = drive->id;
 
 	if (NULL == (void *) arg) {
 		struct request *rq;
@@ -161,14 +160,10 @@
 
 	if (tf->command == ATA_CMD_SET_FEATURES &&
 	    tf->feature == SETFEATURES_XFER &&
-	    tf->nsect >= XFER_SW_DMA_0 &&
-	    (id[ATA_ID_UDMA_MODES] ||
-	     id[ATA_ID_MWDMA_MODES] ||
-	     id[ATA_ID_SWDMA_MODES])) {
-		xfer_rate = args[1];
-		if (tf->nsect > XFER_UDMA_2 && !eighty_ninty_three(drive)) {
-			printk(KERN_WARNING "%s: UDMA speeds >UDMA33 cannot "
-					    "be set\n", drive->name);
+	    tf->nsect >= XFER_SW_DMA_0) {
+		xfer_rate = ide_find_dma_mode(drive, XFER_UDMA_6);
+		if (xfer_rate != tf->nsect) {
+			err = -EINVAL;
 			goto abort;
 		}
 	}
diff --git a/drivers/ide/ide-probe.c b/drivers/ide/ide-probe.c
index 79e0af3..51af4ee 100644
--- a/drivers/ide/ide-probe.c
+++ b/drivers/ide/ide-probe.c
@@ -1170,7 +1170,6 @@
 	hwif->irq = hw->irq;
 	hwif->dev = hw->dev;
 	hwif->gendev.parent = hw->parent ? hw->parent : hw->dev;
-	hwif->ack_intr = hw->ack_intr;
 	hwif->config_data = hw->config;
 }
 
@@ -1378,6 +1377,9 @@
 
 		ide_init_port(hwif, i & 1, d);
 		ide_port_cable_detect(hwif);
+
+		hwif->port_flags |= IDE_PFLAG_PROBING;
+
 		ide_port_init_devices(hwif);
 	}
 
@@ -1388,6 +1390,8 @@
 		if (ide_probe_port(hwif) == 0)
 			hwif->present = 1;
 
+		hwif->port_flags &= ~IDE_PFLAG_PROBING;
+
 		if ((hwif->host_flags & IDE_HFLAG_4DRIVES) == 0 ||
 		    hwif->mate == NULL || hwif->mate->present == 0) {
 			if (ide_register_port(hwif)) {
@@ -1569,11 +1573,20 @@
 
 void ide_port_scan(ide_hwif_t *hwif)
 {
+	int rc;
+
 	ide_port_apply_params(hwif);
 	ide_port_cable_detect(hwif);
+
+	hwif->port_flags |= IDE_PFLAG_PROBING;
+
 	ide_port_init_devices(hwif);
 
-	if (ide_probe_port(hwif) < 0)
+	rc = ide_probe_port(hwif);
+
+	hwif->port_flags &= ~IDE_PFLAG_PROBING;
+
+	if (rc < 0)
 		return;
 
 	hwif->present = 1;
diff --git a/drivers/ide/ide-tape.c b/drivers/ide/ide-tape.c
index 4b447a8..013dc59 100644
--- a/drivers/ide/ide-tape.c
+++ b/drivers/ide/ide-tape.c
@@ -279,10 +279,12 @@
  * called on each failed packet command retry to analyze the request sense. We
  * currently do not utilize this information.
  */
-static void idetape_analyze_error(ide_drive_t *drive, u8 *sense)
+static void idetape_analyze_error(ide_drive_t *drive)
 {
 	idetape_tape_t *tape = drive->driver_data;
 	struct ide_atapi_pc *pc = drive->failed_pc;
+	struct request *rq = drive->hwif->rq;
+	u8 *sense = bio_data(rq->bio);
 
 	tape->sense_key = sense[2] & 0xF;
 	tape->asc       = sense[12];
@@ -291,11 +293,9 @@
 	debug_log(DBG_ERR, "pc = %x, sense key = %x, asc = %x, ascq = %x\n",
 		 pc->c[0], tape->sense_key, tape->asc, tape->ascq);
 
-	/* Correct pc->xferred by asking the tape.	 */
+	/* correct remaining bytes to transfer */
 	if (pc->flags & PC_FLAG_DMA_ERROR)
-		pc->xferred = pc->req_xfer -
-			tape->blk_size *
-			get_unaligned_be32(&sense[3]);
+		rq->resid_len = tape->blk_size * get_unaligned_be32(&sense[3]);
 
 	/*
 	 * If error was the result of a zero-length read or write command,
@@ -329,7 +329,7 @@
 			pc->flags |= PC_FLAG_ABORT;
 		}
 		if (!(pc->flags & PC_FLAG_ABORT) &&
-		    pc->xferred)
+		    (blk_rq_bytes(rq) - rq->resid_len))
 			pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
 	}
 }
@@ -354,12 +354,13 @@
 
 	if (pc->c[0] == REQUEST_SENSE) {
 		if (uptodate)
-			idetape_analyze_error(drive, pc->buf);
+			idetape_analyze_error(drive);
 		else
 			printk(KERN_ERR "ide-tape: Error in REQUEST SENSE "
 					"itself - Aborting request!\n");
 	} else if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
-		int blocks = pc->xferred / tape->blk_size;
+		unsigned int blocks =
+			(blk_rq_bytes(rq) - rq->resid_len) / tape->blk_size;
 
 		tape->avg_size += blocks * tape->blk_size;
 
@@ -371,38 +372,12 @@
 		}
 
 		tape->first_frame += blocks;
-		rq->resid_len -= blocks * tape->blk_size;
 
 		if (pc->error) {
 			uptodate = 0;
 			err = pc->error;
 		}
-	} else if (pc->c[0] == READ_POSITION && uptodate) {
-		u8 *readpos = pc->buf;
-
-		debug_log(DBG_SENSE, "BOP - %s\n",
-				(readpos[0] & 0x80) ? "Yes" : "No");
-		debug_log(DBG_SENSE, "EOP - %s\n",
-				(readpos[0] & 0x40) ? "Yes" : "No");
-
-		if (readpos[0] & 0x4) {
-			printk(KERN_INFO "ide-tape: Block location is unknown"
-					 "to the tape\n");
-			clear_bit(ilog2(IDE_AFLAG_ADDRESS_VALID),
-				  &drive->atapi_flags);
-			uptodate = 0;
-			err = IDE_DRV_ERROR_GENERAL;
-		} else {
-			debug_log(DBG_SENSE, "Block Location - %u\n",
-					be32_to_cpup((__be32 *)&readpos[4]));
-
-			tape->partition = readpos[1];
-			tape->first_frame = be32_to_cpup((__be32 *)&readpos[4]);
-			set_bit(ilog2(IDE_AFLAG_ADDRESS_VALID),
-				&drive->atapi_flags);
-		}
 	}
-
 	rq->errors = err;
 
 	return uptodate;
@@ -477,6 +452,7 @@
 					 struct ide_atapi_pc *pc)
 {
 	idetape_tape_t *tape = drive->driver_data;
+	struct request *rq = drive->hwif->rq;
 
 	if (drive->failed_pc == NULL && pc->c[0] != REQUEST_SENSE)
 		drive->failed_pc = pc;
@@ -486,7 +462,6 @@
 
 	if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
 		(pc->flags & PC_FLAG_ABORT)) {
-		unsigned int done = blk_rq_bytes(drive->hwif->rq);
 
 		/*
 		 * We will "abort" retrying a packet command in case legitimate
@@ -510,7 +485,7 @@
 
 		drive->failed_pc = NULL;
 		drive->pc_callback(drive, 0);
-		ide_complete_rq(drive, -EIO, done);
+		ide_complete_rq(drive, -EIO, blk_rq_bytes(rq));
 		return ide_stopped;
 	}
 	debug_log(DBG_SENSE, "Retry #%d, cmd = %02X\n", pc->retries, pc->c[0]);
@@ -579,15 +554,13 @@
 				   struct ide_atapi_pc *pc, struct request *rq,
 				   u8 opcode)
 {
-	unsigned int length = blk_rq_sectors(rq);
+	unsigned int length = blk_rq_sectors(rq) / (tape->blk_size >> 9);
 
 	ide_init_pc(pc);
 	put_unaligned(cpu_to_be32(length), (unsigned int *) &pc->c[1]);
 	pc->c[1] = 1;
-	pc->buf = NULL;
-	pc->buf_size = length * tape->blk_size;
-	pc->req_xfer = pc->buf_size;
-	if (pc->req_xfer == tape->buffer_size)
+
+	if (blk_rq_bytes(rq) == tape->buffer_size)
 		pc->flags |= PC_FLAG_DMA_OK;
 
 	if (opcode == READ_6)
@@ -613,15 +586,7 @@
 	debug_log(DBG_SENSE, "sector: %llu, nr_sectors: %u\n"
 		  (unsigned long long)blk_rq_pos(rq), blk_rq_sectors(rq));
 
-	if (!(blk_special_request(rq) || blk_sense_request(rq))) {
-		/* We do not support buffer cache originated requests. */
-		printk(KERN_NOTICE "ide-tape: %s: Unsupported request in "
-			"request queue (%d)\n", drive->name, rq->cmd_type);
-		if (blk_fs_request(rq) == 0 && rq->errors == 0)
-			rq->errors = -EIO;
-		ide_complete_rq(drive, -EIO, ide_rq_bytes(rq));
-		return ide_stopped;
-	}
+	BUG_ON(!(blk_special_request(rq) || blk_sense_request(rq)));
 
 	/* Retry a failed packet command */
 	if (drive->failed_pc && drive->pc->c[0] == REQUEST_SENSE) {
@@ -713,7 +678,7 @@
 
 	cmd.rq = rq;
 
-	ide_init_sg_cmd(&cmd, pc->req_xfer);
+	ide_init_sg_cmd(&cmd, blk_rq_bytes(rq));
 	ide_map_sg(drive, &cmd);
 
 	return ide_tape_issue_pc(drive, &cmd, pc);
@@ -767,33 +732,53 @@
 	int rc;
 
 	idetape_create_write_filemark_cmd(drive, &pc, 0);
-	rc = ide_queue_pc_tail(drive, tape->disk, &pc);
+	rc = ide_queue_pc_tail(drive, tape->disk, &pc, NULL, 0);
 	if (rc)
 		return rc;
 	idetape_wait_ready(drive, 60 * 5 * HZ);
 	return 0;
 }
 
-static void idetape_create_read_position_cmd(struct ide_atapi_pc *pc)
-{
-	ide_init_pc(pc);
-	pc->c[0] = READ_POSITION;
-	pc->req_xfer = 20;
-}
-
-static int idetape_read_position(ide_drive_t *drive)
+static int ide_tape_read_position(ide_drive_t *drive)
 {
 	idetape_tape_t *tape = drive->driver_data;
 	struct ide_atapi_pc pc;
-	int position;
+	u8 buf[20];
 
 	debug_log(DBG_PROCS, "Enter %s\n", __func__);
 
-	idetape_create_read_position_cmd(&pc);
-	if (ide_queue_pc_tail(drive, tape->disk, &pc))
+	/* prep cmd */
+	ide_init_pc(&pc);
+	pc.c[0] = READ_POSITION;
+	pc.req_xfer = 20;
+
+	if (ide_queue_pc_tail(drive, tape->disk, &pc, buf, pc.req_xfer))
 		return -1;
-	position = tape->first_frame;
-	return position;
+
+	if (!pc.error) {
+		debug_log(DBG_SENSE, "BOP - %s\n",
+				(buf[0] & 0x80) ? "Yes" : "No");
+		debug_log(DBG_SENSE, "EOP - %s\n",
+				(buf[0] & 0x40) ? "Yes" : "No");
+
+		if (buf[0] & 0x4) {
+			printk(KERN_INFO "ide-tape: Block location is unknown"
+					 "to the tape\n");
+			clear_bit(ilog2(IDE_AFLAG_ADDRESS_VALID),
+				  &drive->atapi_flags);
+			return -1;
+		} else {
+			debug_log(DBG_SENSE, "Block Location - %u\n",
+					be32_to_cpup((__be32 *)&buf[4]));
+
+			tape->partition = buf[1];
+			tape->first_frame = be32_to_cpup((__be32 *)&buf[4]);
+			set_bit(ilog2(IDE_AFLAG_ADDRESS_VALID),
+				&drive->atapi_flags);
+		}
+	}
+
+	return tape->first_frame;
 }
 
 static void idetape_create_locate_cmd(ide_drive_t *drive,
@@ -836,19 +821,21 @@
 {
 	idetape_tape_t *tape = drive->driver_data;
 	struct gendisk *disk = tape->disk;
-	int retval;
+	int ret;
 	struct ide_atapi_pc pc;
 
 	if (tape->chrdev_dir == IDETAPE_DIR_READ)
 		__ide_tape_discard_merge_buffer(drive);
 	idetape_wait_ready(drive, 60 * 5 * HZ);
 	idetape_create_locate_cmd(drive, &pc, block, partition, skip);
-	retval = ide_queue_pc_tail(drive, disk, &pc);
-	if (retval)
-		return (retval);
+	ret = ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
+	if (ret)
+		return ret;
 
-	idetape_create_read_position_cmd(&pc);
-	return ide_queue_pc_tail(drive, disk, &pc);
+	ret = ide_tape_read_position(drive);
+	if (ret < 0)
+		return ret;
+	return 0;
 }
 
 static void ide_tape_discard_merge_buffer(ide_drive_t *drive,
@@ -859,7 +846,7 @@
 
 	__ide_tape_discard_merge_buffer(drive);
 	if (restore_position) {
-		position = idetape_read_position(drive);
+		position = ide_tape_read_position(drive);
 		seek = position > 0 ? position : 0;
 		if (idetape_position_tape(drive, seek, 0, 0)) {
 			printk(KERN_INFO "ide-tape: %s: position_tape failed in"
@@ -1039,20 +1026,19 @@
 {
 	struct ide_tape_obj *tape = drive->driver_data;
 	struct gendisk *disk = tape->disk;
-	int retval;
 	struct ide_atapi_pc pc;
+	int ret;
 
 	debug_log(DBG_SENSE, "Enter %s\n", __func__);
 
 	idetape_create_rewind_cmd(drive, &pc);
-	retval = ide_queue_pc_tail(drive, disk, &pc);
-	if (retval)
-		return retval;
+	ret = ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
+	if (ret)
+		return ret;
 
-	idetape_create_read_position_cmd(&pc);
-	retval = ide_queue_pc_tail(drive, disk, &pc);
-	if (retval)
-		return retval;
+	ret = ide_tape_read_position(drive);
+	if (ret < 0)
+		return ret;
 	return 0;
 }
 
@@ -1119,7 +1105,7 @@
 	case MTBSF:
 		idetape_create_space_cmd(&pc, mt_count - count,
 					 IDETAPE_SPACE_OVER_FILEMARK);
-		return ide_queue_pc_tail(drive, disk, &pc);
+		return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
 	case MTFSFM:
 	case MTBSFM:
 		if (!sprev)
@@ -1259,7 +1245,7 @@
 
 	/* Write a filemark */
 	idetape_create_write_filemark_cmd(drive, &pc, 1);
-	if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
+	if (ide_queue_pc_tail(drive, tape->disk, &pc, NULL, 0)) {
 		printk(KERN_ERR "ide-tape: Couldn't write a filemark\n");
 		return -EIO;
 	}
@@ -1345,11 +1331,11 @@
 			IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
 	case MTEOM:
 		idetape_create_space_cmd(&pc, 0, IDETAPE_SPACE_TO_EOD);
-		return ide_queue_pc_tail(drive, disk, &pc);
+		return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
 	case MTERASE:
 		(void)idetape_rewind_tape(drive);
 		idetape_create_erase_cmd(&pc);
-		return ide_queue_pc_tail(drive, disk, &pc);
+		return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
 	case MTSETBLK:
 		if (mt_count) {
 			if (mt_count < tape->blk_size ||
@@ -1415,7 +1401,7 @@
 	if (cmd == MTIOCGET || cmd == MTIOCPOS) {
 		block_offset = tape->valid /
 			(tape->blk_size * tape->user_bs_factor);
-		position = idetape_read_position(drive);
+		position = ide_tape_read_position(drive);
 		if (position < 0)
 			return -EIO;
 	}
@@ -1458,9 +1444,10 @@
 {
 	idetape_tape_t *tape = drive->driver_data;
 	struct ide_atapi_pc pc;
+	u8 buf[12];
 
 	idetape_create_mode_sense_cmd(&pc, IDETAPE_BLOCK_DESCRIPTOR);
-	if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
+	if (ide_queue_pc_tail(drive, tape->disk, &pc, buf, pc.req_xfer)) {
 		printk(KERN_ERR "ide-tape: Can't get block descriptor\n");
 		if (tape->blk_size == 0) {
 			printk(KERN_WARNING "ide-tape: Cannot deal with zero "
@@ -1469,10 +1456,10 @@
 		}
 		return;
 	}
-	tape->blk_size = (pc.buf[4 + 5] << 16) +
-				(pc.buf[4 + 6] << 8)  +
-				 pc.buf[4 + 7];
-	tape->drv_write_prot = (pc.buf[2] & 0x80) >> 7;
+	tape->blk_size = (buf[4 + 5] << 16) +
+				(buf[4 + 6] << 8)  +
+				 buf[4 + 7];
+	tape->drv_write_prot = (buf[2] & 0x80) >> 7;
 }
 
 static int idetape_chrdev_open(struct inode *inode, struct file *filp)
@@ -1517,7 +1504,7 @@
 		goto out_put_tape;
 	}
 
-	idetape_read_position(drive);
+	ide_tape_read_position(drive);
 	if (!test_bit(ilog2(IDE_AFLAG_ADDRESS_VALID), &drive->atapi_flags))
 		(void)idetape_rewind_tape(drive);
 
@@ -1615,17 +1602,14 @@
 	char fw_rev[4], vendor_id[8], product_id[16];
 
 	idetape_create_inquiry_cmd(&pc);
-	pc.buf = &pc_buf[0];
-	pc.buf_size = sizeof(pc_buf);
-
-	if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
+	if (ide_queue_pc_tail(drive, tape->disk, &pc, pc_buf, pc.req_xfer)) {
 		printk(KERN_ERR "ide-tape: %s: can't get INQUIRY results\n",
 				tape->name);
 		return;
 	}
-	memcpy(vendor_id, &pc.buf[8], 8);
-	memcpy(product_id, &pc.buf[16], 16);
-	memcpy(fw_rev, &pc.buf[32], 4);
+	memcpy(vendor_id, &pc_buf[8], 8);
+	memcpy(product_id, &pc_buf[16], 16);
+	memcpy(fw_rev, &pc_buf[32], 4);
 
 	ide_fixstring(vendor_id, 8, 0);
 	ide_fixstring(product_id, 16, 0);
@@ -1643,11 +1627,11 @@
 {
 	idetape_tape_t *tape = drive->driver_data;
 	struct ide_atapi_pc pc;
-	u8 *caps;
+	u8 buf[24], *caps;
 	u8 speed, max_speed;
 
 	idetape_create_mode_sense_cmd(&pc, IDETAPE_CAPABILITIES_PAGE);
-	if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
+	if (ide_queue_pc_tail(drive, tape->disk, &pc, buf, pc.req_xfer)) {
 		printk(KERN_ERR "ide-tape: Can't get tape parameters - assuming"
 				" some default values\n");
 		tape->blk_size = 512;
@@ -1656,7 +1640,7 @@
 		put_unaligned(6*52, (u16 *)&tape->caps[16]);
 		return;
 	}
-	caps = pc.buf + 4 + pc.buf[3];
+	caps = buf + 4 + buf[3];
 
 	/* convert to host order and save for later use */
 	speed = be16_to_cpup((__be16 *)&caps[14]);
diff --git a/drivers/ide/ide-xfer-mode.c b/drivers/ide/ide-xfer-mode.c
index af44be9..46d203c 100644
--- a/drivers/ide/ide-xfer-mode.c
+++ b/drivers/ide/ide-xfer-mode.c
@@ -107,6 +107,18 @@
 }
 EXPORT_SYMBOL_GPL(ide_get_best_pio_mode);
 
+int ide_pio_need_iordy(ide_drive_t *drive, const u8 pio)
+{
+	/*
+	 * IORDY may lead to controller lock up on certain controllers
+	 * if the port is not occupied.
+	 */
+	if (pio == 0 && (drive->hwif->port_flags & IDE_PFLAG_PROBING))
+		return 0;
+	return ata_id_pio_need_iordy(drive->id, pio);
+}
+EXPORT_SYMBOL_GPL(ide_pio_need_iordy);
+
 int ide_set_pio_mode(ide_drive_t *drive, const u8 mode)
 {
 	ide_hwif_t *hwif = drive->hwif;
diff --git a/drivers/ide/it8172.c b/drivers/ide/it8172.c
index e021078..0d266a5 100644
--- a/drivers/ide/it8172.c
+++ b/drivers/ide/it8172.c
@@ -66,7 +66,7 @@
 	if (drive->media == ide_disk)
 		/* enable prefetch */
 		drive_enables |= 0x0004 << (drive->dn * 4);
-	if (ata_id_has_iordy(drive->id))
+	if (ide_pio_need_iordy(drive, pio))
 		/* enable IORDY sample-point */
 		drive_enables |= 0x0002 << (drive->dn * 4);
 
diff --git a/drivers/ide/it8213.c b/drivers/ide/it8213.c
index d7969b6..4797616 100644
--- a/drivers/ide/it8213.c
+++ b/drivers/ide/it8213.c
@@ -50,7 +50,7 @@
 		control |= 1;	/* Programmable timing on */
 	if (drive->media != ide_disk)
 		control |= 4;	/* ATAPI */
-	if (pio > 2)
+	if (ide_pio_need_iordy(drive, pio))
 		control |= 2;	/* IORDY */
 	if (is_slave) {
 		master_data |=  0x4000;
diff --git a/drivers/ide/macide.c b/drivers/ide/macide.c
index 1447c8c..505ec43 100644
--- a/drivers/ide/macide.c
+++ b/drivers/ide/macide.c
@@ -53,17 +53,20 @@
 
 volatile unsigned char *ide_ifr = (unsigned char *) (IDE_BASE + IDE_IFR);
 
-int macide_ack_intr(ide_hwif_t* hwif)
+int macide_test_irq(ide_hwif_t *hwif)
 {
-	if (*ide_ifr & 0x20) {
-		*ide_ifr &= ~0x20;
+	if (*ide_ifr & 0x20)
 		return 1;
-	}
 	return 0;
 }
 
+static void macide_clear_irq(ide_drive_t *drive)
+{
+	*ide_ifr &= ~0x20;
+}
+
 static void __init macide_setup_ports(struct ide_hw *hw, unsigned long base,
-				      int irq, ide_ack_intr_t *ack_intr)
+				      int irq)
 {
 	int i;
 
@@ -75,10 +78,15 @@
 	hw->io_ports.ctl_addr = base + IDE_CONTROL;
 
 	hw->irq = irq;
-	hw->ack_intr = ack_intr;
 }
 
+static const struct ide_port_ops macide_port_ops = {
+	.clear_irq		= macide_clear_irq,
+	.test_irq		= macide_test_irq,
+};
+
 static const struct ide_port_info macide_port_info = {
+	.port_ops		= &macide_port_ops,
 	.host_flags		= IDE_HFLAG_MMIO | IDE_HFLAG_NO_DMA,
 	.irq_flags		= IRQF_SHARED,
 	.chipset		= ide_generic,
@@ -93,10 +101,10 @@
 
 static int __init macide_init(void)
 {
-	ide_ack_intr_t *ack_intr;
 	unsigned long base;
 	int irq;
 	struct ide_hw hw, *hws[] = { &hw };
+	struct ide_port_info d = macide_port_info;
 
 	if (!MACH_IS_MAC)
 		return -ENODEV;
@@ -104,17 +112,15 @@
 	switch (macintosh_config->ide_type) {
 	case MAC_IDE_QUADRA:
 		base = IDE_BASE;
-		ack_intr = macide_ack_intr;
 		irq = IRQ_NUBUS_F;
 		break;
 	case MAC_IDE_PB:
 		base = IDE_BASE;
-		ack_intr = macide_ack_intr;
 		irq = IRQ_NUBUS_C;
 		break;
 	case MAC_IDE_BABOON:
 		base = BABOON_BASE;
-		ack_intr = NULL;
+		d.port_ops = NULL;
 		irq = IRQ_BABOON_1;
 		break;
 	default:
@@ -124,9 +130,9 @@
 	printk(KERN_INFO "ide: Macintosh %s IDE controller\n",
 			 mac_ide_name[macintosh_config->ide_type - 1]);
 
-	macide_setup_ports(&hw, base, irq, ack_intr);
+	macide_setup_ports(&hw, base, irq);
 
-	return ide_host_add(&macide_port_info, hws, 1, NULL);
+	return ide_host_add(&d, hws, 1, NULL);
 }
 
 module_init(macide_init);
diff --git a/drivers/ide/opti621.c b/drivers/ide/opti621.c
index 6048eda..f1d70d6 100644
--- a/drivers/ide/opti621.c
+++ b/drivers/ide/opti621.c
@@ -138,6 +138,7 @@
 	ide_hwif_t *hwif = drive->hwif;
 	ide_drive_t *pair = ide_get_pair_dev(drive);
 	unsigned long flags;
+	unsigned long mode = XFER_PIO_0 + pio, pair_mode;
 	u8 tim, misc, addr_pio = pio, clk;
 
 	/* DRDY is default 2 (by OPTi Databook) */
@@ -150,11 +151,12 @@
 		{ 0x48, 0x34, 0x21, 0x10, 0x10 }	/* 25 MHz */
 	};
 
-	drive->drive_data = XFER_PIO_0 + pio;
+	ide_set_drivedata(drive, (void *)mode);
 
 	if (pair) {
-		if (pair->drive_data && pair->drive_data < drive->drive_data)
-			addr_pio = pair->drive_data - XFER_PIO_0;
+		pair_mode = (unsigned long)ide_get_drivedata(pair);
+		if (pair_mode && pair_mode < mode)
+			addr_pio = pair_mode - XFER_PIO_0;
 	}
 
 	spin_lock_irqsave(&opti621_lock, flags);
diff --git a/drivers/ide/pdc202xx_old.c b/drivers/ide/pdc202xx_old.c
index b6abf7e..cb812f3 100644
--- a/drivers/ide/pdc202xx_old.c
+++ b/drivers/ide/pdc202xx_old.c
@@ -73,7 +73,7 @@
 		 * Prefetch_EN / IORDY_EN / PA[3:0] bits of register A
 		 */
 		AP &= ~0x3f;
-		if (ata_id_iordy_disable(drive->id))
+		if (ide_pio_need_iordy(drive, speed - XFER_PIO_0))
 			AP |= 0x20;	/* set IORDY_EN bit */
 		if (drive->media == ide_disk)
 			AP |= 0x10;	/* set Prefetch_EN bit */
@@ -104,6 +104,27 @@
 	pdc202xx_set_mode(drive, XFER_PIO_0 + pio);
 }
 
+static int pdc202xx_test_irq(ide_hwif_t *hwif)
+{
+	struct pci_dev *dev	= to_pci_dev(hwif->dev);
+	unsigned long high_16	= pci_resource_start(dev, 4);
+	u8 sc1d			= inb(high_16 + 0x1d);
+
+	if (hwif->channel) {
+		/*
+		 * bit 7: error, bit 6: interrupting,
+		 * bit 5: FIFO full, bit 4: FIFO empty
+		 */
+		return ((sc1d & 0x50) == 0x40) ? 1 : 0;
+	} else	{
+		/*
+		 * bit 3: error, bit 2: interrupting,
+		 * bit 1: FIFO full, bit 0: FIFO empty
+		 */
+		return ((sc1d & 0x05) == 0x04) ? 1 : 0;
+	}
+}
+
 static u8 pdc2026x_cable_detect(ide_hwif_t *hwif)
 {
 	struct pci_dev *dev = to_pci_dev(hwif->dev);
@@ -231,6 +252,7 @@
 static const struct ide_port_ops pdc20246_port_ops = {
 	.set_pio_mode		= pdc202xx_set_pio_mode,
 	.set_dma_mode		= pdc202xx_set_mode,
+	.test_irq		= pdc202xx_test_irq,
 };
 
 static const struct ide_port_ops pdc2026x_port_ops = {
diff --git a/drivers/ide/piix.c b/drivers/ide/piix.c
index 69860de..bf14f39 100644
--- a/drivers/ide/piix.c
+++ b/drivers/ide/piix.c
@@ -98,7 +98,7 @@
 		control |= 1;	/* Programmable timing on */
 	if (drive->media == ide_disk)
 		control |= 4;	/* Prefetch, post write */
-	if (pio > 2)
+	if (ide_pio_need_iordy(drive, pio))
 		control |= 2;	/* IORDY */
 	if (is_slave) {
 		master_data |=  0x4000;
diff --git a/drivers/ide/q40ide.c b/drivers/ide/q40ide.c
index ab49a97..9078608 100644
--- a/drivers/ide/q40ide.c
+++ b/drivers/ide/q40ide.c
@@ -51,9 +51,7 @@
 /*
  * Addresses are pretranslated for Q40 ISA access.
  */
-static void q40_ide_setup_ports(struct ide_hw *hw, unsigned long base,
-			ide_ack_intr_t *ack_intr,
-			int irq)
+static void q40_ide_setup_ports(struct ide_hw *hw, unsigned long base, int irq)
 {
 	memset(hw, 0, sizeof(*hw));
 	/* BIG FAT WARNING: 
@@ -69,7 +67,6 @@
 	hw->io_ports.ctl_addr = Q40_ISA_IO_B(base + 0x206);
 
 	hw->irq = irq;
-	hw->ack_intr = ack_intr;
 }
 
 static void q40ide_input_data(ide_drive_t *drive, struct ide_cmd *cmd,
@@ -156,7 +153,7 @@
 		release_region(pcide_bases[i], 8);
 		continue;
 	}
-	q40_ide_setup_ports(&hw[i], pcide_bases[i], NULL,
+	q40_ide_setup_ports(&hw[i], pcide_bases[i],
 			q40ide_default_irq(pcide_bases[i]));
 
 	hws[i] = &hw[i];
diff --git a/drivers/ide/qd65xx.c b/drivers/ide/qd65xx.c
index c9a1349..74696ed 100644
--- a/drivers/ide/qd65xx.c
+++ b/drivers/ide/qd65xx.c
@@ -180,8 +180,11 @@
 
 static void qd_set_timing (ide_drive_t *drive, u8 timing)
 {
-	drive->drive_data &= 0xff00;
-	drive->drive_data |= timing;
+	unsigned long data = (unsigned long)ide_get_drivedata(drive);
+
+	data &= 0xff00;
+	data |= timing;
+	ide_set_drivedata(drive, (void *)data);
 
 	printk(KERN_DEBUG "%s: %#x\n", drive->name, timing);
 }
@@ -292,7 +295,7 @@
 	u8 base = (hwif->config_data & 0xff00) >> 8;
 	u8 config = QD_CONFIG(hwif);
 
-	drive->drive_data = QD6500_DEF_DATA;
+	ide_set_drivedata(drive, (void *)QD6500_DEF_DATA);
 }
 
 static void __init qd6580_init_dev(ide_drive_t *drive)
@@ -308,7 +311,7 @@
 	} else
 		t2 = t1 = hwif->channel ? QD6580_DEF_DATA2 : QD6580_DEF_DATA;
 
-	drive->drive_data = (drive->dn & 1) ? t2 : t1;
+	ide_set_drivedata(drive, (void *)((drive->dn & 1) ? t2 : t1));
 }
 
 static const struct ide_tp_ops qd65xx_tp_ops = {
diff --git a/drivers/ide/qd65xx.h b/drivers/ide/qd65xx.h
index d7e67a1..1fba2a5 100644
--- a/drivers/ide/qd65xx.h
+++ b/drivers/ide/qd65xx.h
@@ -31,8 +31,15 @@
 
 #define QD_CONFIG(hwif)		((hwif)->config_data & 0x00ff)
 
-#define QD_TIMING(drive)	(u8)(((drive)->drive_data) & 0x00ff)
-#define QD_TIMREG(drive)	(u8)((((drive)->drive_data) & 0xff00) >> 8)
+static inline u8 QD_TIMING(ide_drive_t *drive)
+{
+	return (unsigned long)ide_get_drivedata(drive) & 0x00ff;
+}
+
+static inline u8 QD_TIMREG(ide_drive_t *drive)
+{
+	return ((unsigned long)ide_get_drivedata(drive) & 0xff00) >> 8;
+}
 
 #define QD6500_DEF_DATA		((QD_TIM1_PORT<<8) | (QD_ID3 ? 0x0c : 0x08))
 #define QD6580_DEF_DATA		((QD_TIM1_PORT<<8) | (QD_ID3 ? 0x0a : 0x00))
diff --git a/drivers/ide/sgiioc4.c b/drivers/ide/sgiioc4.c
index 5f37f16..b7d61dc 100644
--- a/drivers/ide/sgiioc4.c
+++ b/drivers/ide/sgiioc4.c
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2003-2006 Silicon Graphics, Inc.  All Rights Reserved.
- * Copyright (C) 2008 MontaVista Software, Inc.
+ * Copyright (C) 2008-2009 MontaVista Software, Inc.
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of version 2 of the GNU General Public License
@@ -29,8 +29,7 @@
 #include <linux/blkdev.h>
 #include <linux/scatterlist.h>
 #include <linux/ioc4.h>
-#include <asm/io.h>
-
+#include <linux/io.h>
 #include <linux/ide.h>
 
 #define DRV_NAME "SGIIOC4"
@@ -72,7 +71,7 @@
 #define IOC4_CMD_CTL_BLK_SIZE	0x20
 #define IOC4_SUPPORTED_FIRMWARE_REV 46
 
-typedef struct {
+struct ioc4_dma_regs {
 	u32 timing_reg0;
 	u32 timing_reg1;
 	u32 low_mem_ptr;
@@ -82,17 +81,18 @@
 	u32 dev_byte_count;
 	u32 mem_byte_count;
 	u32 status;
-} ioc4_dma_regs_t;
+};
 
 /* Each Physical Region Descriptor Entry size is 16 bytes (2 * 64 bits) */
 /* IOC4 has only 1 IDE channel */
-#define IOC4_PRD_BYTES       16
-#define IOC4_PRD_ENTRIES     (PAGE_SIZE /(4*IOC4_PRD_BYTES))
+#define IOC4_PRD_BYTES		16
+#define IOC4_PRD_ENTRIES	(PAGE_SIZE / (4 * IOC4_PRD_BYTES))
 
 
-static void
-sgiioc4_init_hwif_ports(struct ide_hw *hw, unsigned long data_port,
-			unsigned long ctrl_port, unsigned long irq_port)
+static void sgiioc4_init_hwif_ports(struct ide_hw *hw,
+				    unsigned long data_port,
+				    unsigned long ctrl_port,
+				    unsigned long irq_port)
 {
 	unsigned long reg = data_port;
 	int i;
@@ -105,13 +105,11 @@
 	hw->io_ports.irq_addr = irq_port;
 }
 
-static int
-sgiioc4_checkirq(ide_hwif_t * hwif)
+static int sgiioc4_checkirq(ide_hwif_t *hwif)
 {
-	unsigned long intr_addr =
-		hwif->io_ports.irq_addr + IOC4_INTR_REG * 4;
+	unsigned long intr_addr = hwif->io_ports.irq_addr + IOC4_INTR_REG * 4;
 
-	if ((u8)readl((void __iomem *)intr_addr) & 0x03)
+	if (readl((void __iomem *)intr_addr) & 0x03)
 		return 1;
 
 	return 0;
@@ -119,8 +117,7 @@
 
 static u8 sgiioc4_read_status(ide_hwif_t *);
 
-static int
-sgiioc4_clearirq(ide_drive_t * drive)
+static int sgiioc4_clearirq(ide_drive_t *drive)
 {
 	u32 intr_reg;
 	ide_hwif_t *hwif = drive->hwif;
@@ -158,12 +155,10 @@
 				readl((void __iomem *)(io_ports->irq_addr + 4));
 			pci_read_config_dword(dev, PCI_COMMAND,
 					      &pci_stat_cmd_reg);
-			printk(KERN_ERR
-			       "%s(%s) : PCI Bus Error when doing DMA:"
-				   " status-cmd reg is 0x%x\n",
+			printk(KERN_ERR "%s(%s): PCI Bus Error when doing DMA: "
+			       "status-cmd reg is 0x%x\n",
 			       __func__, drive->name, pci_stat_cmd_reg);
-			printk(KERN_ERR
-			       "%s(%s) : PCI Error Address is 0x%x%x\n",
+			printk(KERN_ERR "%s(%s): PCI Error Address is 0x%x%x\n",
 			       __func__, drive->name,
 			       pci_err_addr_high, pci_err_addr_low);
 			/* Clear the PCI Error indicator */
@@ -189,8 +184,7 @@
 	writel(temp_reg, (void __iomem *)ioc4_dma_addr);
 }
 
-static u32
-sgiioc4_ide_dma_stop(ide_hwif_t *hwif, u64 dma_base)
+static u32 sgiioc4_ide_dma_stop(ide_hwif_t *hwif, u64 dma_base)
 {
 	unsigned long ioc4_dma_addr = dma_base + IOC4_DMA_CTRL * 4;
 	u32	ioc4_dma;
@@ -227,7 +221,7 @@
 	}
 
 	/*
-	 * The IOC4 will DMA 1's to the ending dma area to indicate that
+	 * The IOC4 will DMA 1's to the ending DMA area to indicate that
 	 * previous data DMA is complete.  This is necessary because of relaxed
 	 * ordering between register reads and DMA writes on the Altix.
 	 */
@@ -265,7 +259,7 @@
 {
 }
 
-/* returns 1 if dma irq issued, 0 otherwise */
+/* Returns 1 if DMA IRQ issued, 0 otherwise */
 static int sgiioc4_dma_test_irq(ide_drive_t *drive)
 {
 	return sgiioc4_checkirq(drive->hwif);
@@ -286,8 +280,7 @@
 	sgiioc4_clearirq(drive);
 }
 
-static void
-sgiioc4_dma_lost_irq(ide_drive_t * drive)
+static void sgiioc4_dma_lost_irq(ide_drive_t *drive)
 {
 	sgiioc4_resetproc(drive);
 
@@ -313,13 +306,13 @@
 	return reg;
 }
 
-/* Creates a dma map for the scatter-gather list entries */
-static int __devinit
-ide_dma_sgiioc4(ide_hwif_t *hwif, const struct ide_port_info *d)
+/* Creates a DMA map for the scatter-gather list entries */
+static int __devinit ide_dma_sgiioc4(ide_hwif_t *hwif,
+				     const struct ide_port_info *d)
 {
 	struct pci_dev *dev = to_pci_dev(hwif->dev);
 	unsigned long dma_base = pci_resource_start(dev, 0) + IOC4_DMA_OFFSET;
-	int num_ports = sizeof (ioc4_dma_regs_t);
+	int num_ports = sizeof(struct ioc4_dma_regs);
 	void *pad;
 
 	printk(KERN_INFO "    %s: MMIO-DMA\n", hwif->name);
@@ -362,8 +355,7 @@
 }
 
 /* Initializes the IOC4 DMA Engine */
-static void
-sgiioc4_configure_for_dma(int dma_direction, ide_drive_t * drive)
+static void sgiioc4_configure_for_dma(int dma_direction, ide_drive_t *drive)
 {
 	u32 ioc4_dma;
 	ide_hwif_t *hwif = drive->hwif;
@@ -374,31 +366,27 @@
 	ioc4_dma = readl((void __iomem *)ioc4_dma_addr);
 
 	if (ioc4_dma & IOC4_S_DMA_ACTIVE) {
-		printk(KERN_WARNING
-			"%s(%s):Warning!! DMA from previous transfer was still active\n",
-		       __func__, drive->name);
+		printk(KERN_WARNING "%s(%s): Warning!! DMA from previous "
+		       "transfer was still active\n", __func__, drive->name);
 		writel(IOC4_S_DMA_STOP, (void __iomem *)ioc4_dma_addr);
 		ioc4_dma = sgiioc4_ide_dma_stop(hwif, dma_base);
 
 		if (ioc4_dma & IOC4_S_DMA_STOP)
-			printk(KERN_ERR
-			       "%s(%s) : IOC4 Dma STOP bit is still 1\n",
-			       __func__, drive->name);
+			printk(KERN_ERR "%s(%s): IOC4 DMA STOP bit is "
+			       "still 1\n", __func__, drive->name);
 	}
 
 	ioc4_dma = readl((void __iomem *)ioc4_dma_addr);
 	if (ioc4_dma & IOC4_S_DMA_ERROR) {
-		printk(KERN_WARNING
-		       "%s(%s) : Warning!! - DMA Error during Previous"
-		       " transfer | status 0x%x\n",
+		printk(KERN_WARNING "%s(%s): Warning!! DMA Error during "
+		       "previous transfer, status 0x%x\n",
 		       __func__, drive->name, ioc4_dma);
 		writel(IOC4_S_DMA_STOP, (void __iomem *)ioc4_dma_addr);
 		ioc4_dma = sgiioc4_ide_dma_stop(hwif, dma_base);
 
 		if (ioc4_dma & IOC4_S_DMA_STOP)
-			printk(KERN_ERR
-			       "%s(%s) : IOC4 DMA STOP bit is still 1\n",
-			       __func__, drive->name);
+			printk(KERN_ERR "%s(%s): IOC4 DMA STOP bit is "
+			       "still 1\n", __func__, drive->name);
 	}
 
 	/* Address of the Scatter Gather List */
@@ -408,20 +396,22 @@
 	/* Address of the Ending DMA */
 	memset(ide_get_hwifdata(hwif), 0, IOC4_IDE_CACHELINE_SIZE);
 	ending_dma_addr = cpu_to_le32(hwif->extra_base);
-	writel(ending_dma_addr, (void __iomem *)(dma_base + IOC4_DMA_END_ADDR * 4));
+	writel(ending_dma_addr, (void __iomem *)(dma_base +
+						 IOC4_DMA_END_ADDR * 4));
 
 	writel(dma_direction, (void __iomem *)ioc4_dma_addr);
 }
 
-/* IOC4 Scatter Gather list Format 					 */
+/* IOC4 Scatter Gather list Format					 */
 /* 128 Bit entries to support 64 bit addresses in the future		 */
 /* The Scatter Gather list Entry should be in the BIG-ENDIAN Format	 */
 /* --------------------------------------------------------------------- */
-/* | Upper 32 bits - Zero           |	 	Lower 32 bits- address | */
+/* | Upper 32 bits - Zero	    |		Lower 32 bits- address | */
 /* --------------------------------------------------------------------- */
 /* | Upper 32 bits - Zero	    |EOL| 15 unused     | 16 Bit Length| */
 /* --------------------------------------------------------------------- */
-/* Creates the scatter gather list, DMA Table */
+/* Creates the scatter gather list, DMA Table				 */
+
 static int sgiioc4_build_dmatable(ide_drive_t *drive, struct ide_cmd *cmd)
 {
 	ide_hwif_t *hwif = drive->hwif;
@@ -448,8 +438,10 @@
 				if (bcount > cur_len)
 					bcount = cur_len;
 
-				/* put the addr, length in
-				 * the IOC4 dma-table format */
+				/*
+				 * Put the address, length in
+				 * the IOC4 dma-table format
+				 */
 				*table = 0x0;
 				table++;
 				*table = cpu_to_be32(cur_addr);
@@ -540,8 +532,7 @@
 	.mwdma_mask		= ATA_MWDMA2_ONLY,
 };
 
-static int __devinit
-sgiioc4_ide_setup_pci_device(struct pci_dev *dev)
+static int __devinit sgiioc4_ide_setup_pci_device(struct pci_dev *dev)
 {
 	unsigned long cmd_base, irqport;
 	unsigned long bar0, cmd_phys_base, ctl;
@@ -549,7 +540,7 @@
 	struct ide_hw hw, *hws[] = { &hw };
 	int rc;
 
-	/*  Get the CmdBlk and CtrlBlk Base Registers */
+	/* Get the CmdBlk and CtrlBlk base registers */
 	bar0 = pci_resource_start(dev, 0);
 	virt_base = pci_ioremap_bar(dev, 0);
 	if (virt_base == NULL) {
@@ -557,9 +548,9 @@
 				DRV_NAME, bar0);
 		return -ENOMEM;
 	}
-	cmd_base = (unsigned long) virt_base + IOC4_CMD_OFFSET;
-	ctl = (unsigned long) virt_base + IOC4_CTRL_OFFSET;
-	irqport = (unsigned long) virt_base + IOC4_INTR_OFFSET;
+	cmd_base = (unsigned long)virt_base + IOC4_CMD_OFFSET;
+	ctl = (unsigned long)virt_base + IOC4_CTRL_OFFSET;
+	irqport = (unsigned long)virt_base + IOC4_INTR_OFFSET;
 
 	cmd_phys_base = bar0 + IOC4_CMD_OFFSET;
 	if (request_mem_region(cmd_phys_base, IOC4_CMD_CTL_BLK_SIZE,
@@ -577,7 +568,7 @@
 	hw.irq = dev->irq;
 	hw.dev = &dev->dev;
 
-	/* Initializing chipset IRQ Registers */
+	/* Initialize chipset IRQ registers */
 	writel(0x03, (void __iomem *)(irqport + IOC4_INTR_SET * 4));
 
 	rc = ide_host_add(&sgiioc4_port_info, hws, 1, NULL);
@@ -590,8 +581,7 @@
 	return rc;
 }
 
-static unsigned int __devinit
-pci_init_sgiioc4(struct pci_dev *dev)
+static unsigned int __devinit pci_init_sgiioc4(struct pci_dev *dev)
 {
 	int ret;
 
@@ -611,10 +601,10 @@
 	return ret;
 }
 
-int __devinit
-ioc4_ide_attach_one(struct ioc4_driver_data *idd)
+int __devinit ioc4_ide_attach_one(struct ioc4_driver_data *idd)
 {
-	/* PCI-RT does not bring out IDE connection.
+	/*
+	 * PCI-RT does not bring out IDE connection.
 	 * Do not attach to this particular IOC4.
 	 */
 	if (idd->idd_variant == IOC4_VARIANT_PCI_RT)
@@ -627,7 +617,6 @@
 	.is_name = "IOC4_ide",
 	.is_owner = THIS_MODULE,
 	.is_probe = ioc4_ide_attach_one,
-/*	.is_remove = ioc4_ide_remove_one,	*/
 };
 
 static int __init ioc4_ide_init(void)
diff --git a/drivers/ide/siimage.c b/drivers/ide/siimage.c
index bd82d22..d95df52 100644
--- a/drivers/ide/siimage.c
+++ b/drivers/ide/siimage.c
@@ -32,7 +32,6 @@
  *  smarter code in libata.
  *
  * TODO:
- * - IORDY fixes
  * - VDMA support
  */
 
@@ -234,8 +233,7 @@
  *	@pio: PIO mode number
  *
  *	Load the timing settings for this device mode into the
- *	controller. If we are in PIO mode 3 or 4 turn on IORDY
- *	monitoring (bit 9). The TF timing is bits 31:16
+ *	controller.
  */
 
 static void sil_set_pio_mode(ide_drive_t *drive, u8 pio)
@@ -276,13 +274,16 @@
 	/* now set up IORDY */
 	speedp = sil_ioread16(dev, tfaddr - 2);
 	speedp &= ~0x200;
-	if (pio > 2)
-		speedp |= 0x200;
-	sil_iowrite16(dev, speedp, tfaddr - 2);
 
 	mode = sil_ioread8(dev, base + addr_mask);
 	mode &= ~(unit ? 0x30 : 0x03);
-	mode |= unit ? 0x10 : 0x01;
+
+	if (ide_pio_need_iordy(drive, pio)) {
+		speedp |= 0x200;
+		mode |= unit ? 0x10 : 0x01;
+	}
+
+	sil_iowrite16(dev, speedp, tfaddr - 2);
 	sil_iowrite8(dev, mode, base + addr_mask);
 }
 
@@ -337,24 +338,14 @@
 	sil_iowrite16(dev, ultra, ua);
 }
 
-/* returns 1 if dma irq issued, 0 otherwise */
-static int siimage_io_dma_test_irq(ide_drive_t *drive)
+static int sil_test_irq(ide_hwif_t *hwif)
 {
-	ide_hwif_t *hwif	= drive->hwif;
 	struct pci_dev *dev	= to_pci_dev(hwif->dev);
-	u8 dma_altstat		= 0;
 	unsigned long addr	= siimage_selreg(hwif, 1);
+	u8 val			= sil_ioread8(dev, addr);
 
-	/* return 1 if INTR asserted */
-	if (inb(hwif->dma_base + ATA_DMA_STATUS) & 4)
-		return 1;
-
-	/* return 1 if Device INTR asserted */
-	pci_read_config_byte(dev, addr, &dma_altstat);
-	if (dma_altstat & 8)
-		return 0;	/* return 1; */
-
-	return 0;
+	/* Return 1 if INTRQ asserted */
+	return (val & 8) ? 1 : 0;
 }
 
 /**
@@ -368,7 +359,6 @@
 static int siimage_mmio_dma_test_irq(ide_drive_t *drive)
 {
 	ide_hwif_t *hwif	= drive->hwif;
-	unsigned long addr	= siimage_selreg(hwif, 0x1);
 	void __iomem *sata_error_addr
 		= (void __iomem *)hwif->sata_scr[SATA_ERROR_OFFSET];
 
@@ -397,10 +387,6 @@
 	if (readb((void __iomem *)(hwif->dma_base + ATA_DMA_STATUS)) & 4)
 		return 1;
 
-	/* return 1 if Device INTR asserted */
-	if (readb((void __iomem *)addr) & 8)
-		return 0;	/* return 1; */
-
 	return 0;
 }
 
@@ -409,7 +395,7 @@
 	if (drive->hwif->host_flags & IDE_HFLAG_MMIO)
 		return siimage_mmio_dma_test_irq(drive);
 	else
-		return siimage_io_dma_test_irq(drive);
+		return ide_dma_test_irq(drive);
 }
 
 /**
@@ -694,6 +680,7 @@
 	.set_pio_mode		= sil_set_pio_mode,
 	.set_dma_mode		= sil_set_dma_mode,
 	.quirkproc		= sil_quirkproc,
+	.test_irq		= sil_test_irq,
 	.udma_filter		= sil_pata_udma_filter,
 	.cable_detect		= sil_cable_detect,
 };
@@ -704,6 +691,7 @@
 	.reset_poll		= sil_sata_reset_poll,
 	.pre_reset		= sil_sata_pre_reset,
 	.quirkproc		= sil_quirkproc,
+	.test_irq		= sil_test_irq,
 	.udma_filter		= sil_sata_udma_filter,
 	.cable_detect		= sil_cable_detect,
 };
diff --git a/drivers/ide/sl82c105.c b/drivers/ide/sl82c105.c
index 0924abf..d698da4 100644
--- a/drivers/ide/sl82c105.c
+++ b/drivers/ide/sl82c105.c
@@ -61,8 +61,7 @@
 	if (cmd_off == 0)
 		cmd_off = 1;
 
-	if ((pio > 2 || ata_id_has_iordy(drive->id)) &&
-	    !(pio > 4 && ata_id_is_cfa(drive->id)))
+	if (ide_pio_need_iordy(drive, pio))
 		iordy = 0x40;
 
 	return (cmd_on - 1) << 8 | (cmd_off - 1) | iordy;
@@ -74,6 +73,7 @@
 static void sl82c105_set_pio_mode(ide_drive_t *drive, const u8 pio)
 {
 	struct pci_dev *dev	= to_pci_dev(drive->hwif->dev);
+	unsigned long timings	= (unsigned long)ide_get_drivedata(drive);
 	int reg			= 0x44 + drive->dn * 4;
 	u16 drv_ctrl;
 
@@ -83,8 +83,9 @@
 	 * Store the PIO timings so that we can restore them
 	 * in case DMA will be turned off...
 	 */
-	drive->drive_data &= 0xffff0000;
-	drive->drive_data |= drv_ctrl;
+	timings &= 0xffff0000;
+	timings |= drv_ctrl;
+	ide_set_drivedata(drive, (void *)timings);
 
 	pci_write_config_word(dev, reg,  drv_ctrl);
 	pci_read_config_word (dev, reg, &drv_ctrl);
@@ -100,6 +101,7 @@
 static void sl82c105_set_dma_mode(ide_drive_t *drive, const u8 speed)
 {
 	static u16 mwdma_timings[] = {0x0707, 0x0201, 0x0200};
+	unsigned long timings = (unsigned long)ide_get_drivedata(drive);
 	u16 drv_ctrl;
 
  	DBG(("sl82c105_tune_chipset(drive:%s, speed:%s)\n",
@@ -111,8 +113,19 @@
 	 * Store the DMA timings so that we can actually program
 	 * them when DMA will be turned on...
 	 */
-	drive->drive_data &= 0x0000ffff;
-	drive->drive_data |= (unsigned long)drv_ctrl << 16;
+	timings &= 0x0000ffff;
+	timings |= (unsigned long)drv_ctrl << 16;
+	ide_set_drivedata(drive, (void *)timings);
+}
+
+static int sl82c105_test_irq(ide_hwif_t *hwif)
+{
+	struct pci_dev *dev	= to_pci_dev(hwif->dev);
+	u32 val, mask		= hwif->channel ? CTRL_IDE_IRQB : CTRL_IDE_IRQA;
+
+	pci_read_config_dword(dev, 0x40, &val);
+
+	return (val & mask) ? 1 : 0;
 }
 
 /*
@@ -185,7 +198,8 @@
 
 	DBG(("%s(drive:%s)\n", __func__, drive->name));
 
-	pci_write_config_word(dev, reg, drive->drive_data >> 16);
+	pci_write_config_word(dev, reg,
+			      (unsigned long)ide_get_drivedata(drive) >> 16);
 
 	sl82c105_reset_host(dev);
 	ide_dma_start(drive);
@@ -210,7 +224,8 @@
 
 	ret = ide_dma_end(drive);
 
-	pci_write_config_word(dev, reg, drive->drive_data);
+	pci_write_config_word(dev, reg,
+			      (unsigned long)ide_get_drivedata(drive));
 
 	return ret;
 }
@@ -289,6 +304,7 @@
 	.set_pio_mode		= sl82c105_set_pio_mode,
 	.set_dma_mode		= sl82c105_set_dma_mode,
 	.resetproc		= sl82c105_resetproc,
+	.test_irq		= sl82c105_test_irq,
 };
 
 static const struct ide_dma_ops sl82c105_dma_ops = {
diff --git a/drivers/ide/slc90e66.c b/drivers/ide/slc90e66.c
index f55d7d6..9aec78d 100644
--- a/drivers/ide/slc90e66.c
+++ b/drivers/ide/slc90e66.c
@@ -44,7 +44,7 @@
 		control |= 1;	/* Programmable timing on */
 	if (drive->media == ide_disk)
 		control |= 4;	/* Prefetch, post write */
-	if (pio > 2)
+	if (ide_pio_need_iordy(drive, pio))
 		control |= 2;	/* IORDY */
 	if (is_slave) {
 		master_data |=  0x4000;
diff --git a/drivers/input/evdev.c b/drivers/input/evdev.c
index 7a7a026..114efd8 100644
--- a/drivers/input/evdev.c
+++ b/drivers/input/evdev.c
@@ -25,7 +25,6 @@
 	int exist;
 	int open;
 	int minor;
-	char name[16];
 	struct input_handle handle;
 	wait_queue_head_t wait;
 	struct evdev_client *grab;
@@ -609,7 +608,8 @@
 						    p, compat_mode);
 
 			if (_IOC_NR(cmd) == _IOC_NR(EVIOCGNAME(0)))
-				return str_to_user(dev->name, _IOC_SIZE(cmd), p);
+				return str_to_user(dev_name(&evdev->dev),
+						   _IOC_SIZE(cmd), p);
 
 			if (_IOC_NR(cmd) == _IOC_NR(EVIOCGPHYS(0)))
 				return str_to_user(dev->phys, _IOC_SIZE(cmd), p);
@@ -626,8 +626,11 @@
 				abs.maximum = dev->absmax[t];
 				abs.fuzz = dev->absfuzz[t];
 				abs.flat = dev->absflat[t];
+				abs.resolution = dev->absres[t];
 
-				if (copy_to_user(p, &abs, sizeof(struct input_absinfo)))
+				if (copy_to_user(p, &abs, min_t(size_t,
+								_IOC_SIZE(cmd),
+								sizeof(struct input_absinfo))))
 					return -EFAULT;
 
 				return 0;
@@ -654,8 +657,9 @@
 
 				t = _IOC_NR(cmd) & ABS_MAX;
 
-				if (copy_from_user(&abs, p,
-						sizeof(struct input_absinfo)))
+				if (copy_from_user(&abs, p, min_t(size_t,
+								  _IOC_SIZE(cmd),
+								  sizeof(struct input_absinfo))))
 					return -EFAULT;
 
 				/*
@@ -670,6 +674,8 @@
 				dev->absmax[t] = abs.maximum;
 				dev->absfuzz[t] = abs.fuzz;
 				dev->absflat[t] = abs.flat;
+				dev->absres[t] = _IOC_SIZE(cmd) < sizeof(struct input_absinfo) ?
+							0 : abs.resolution;
 
 				spin_unlock_irq(&dev->event_lock);
 
@@ -807,16 +813,15 @@
 	mutex_init(&evdev->mutex);
 	init_waitqueue_head(&evdev->wait);
 
-	snprintf(evdev->name, sizeof(evdev->name), "event%d", minor);
+	dev_set_name(&evdev->dev, "event%d", minor);
 	evdev->exist = 1;
 	evdev->minor = minor;
 
 	evdev->handle.dev = input_get_device(dev);
-	evdev->handle.name = evdev->name;
+	evdev->handle.name = dev_name(&evdev->dev);
 	evdev->handle.handler = handler;
 	evdev->handle.private = evdev;
 
-	dev_set_name(&evdev->dev, evdev->name);
 	evdev->dev.devt = MKDEV(INPUT_MAJOR, EVDEV_MINOR_BASE + minor);
 	evdev->dev.class = &input_class;
 	evdev->dev.parent = &dev->dev;
diff --git a/drivers/input/gameport/fm801-gp.c b/drivers/input/gameport/fm801-gp.c
index 1dec00e..8a1810f 100644
--- a/drivers/input/gameport/fm801-gp.c
+++ b/drivers/input/gameport/fm801-gp.c
@@ -167,5 +167,6 @@
 
 MODULE_DEVICE_TABLE(pci, fm801_gp_id_table);
 
+MODULE_DESCRIPTION("FM801 gameport driver");
 MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
 MODULE_LICENSE("GPL");
diff --git a/drivers/input/gameport/gameport.c b/drivers/input/gameport/gameport.c
index 2d175b5..ac11be0 100644
--- a/drivers/input/gameport/gameport.c
+++ b/drivers/input/gameport/gameport.c
@@ -30,16 +30,6 @@
 MODULE_DESCRIPTION("Generic gameport layer");
 MODULE_LICENSE("GPL");
 
-EXPORT_SYMBOL(__gameport_register_port);
-EXPORT_SYMBOL(gameport_unregister_port);
-EXPORT_SYMBOL(__gameport_register_driver);
-EXPORT_SYMBOL(gameport_unregister_driver);
-EXPORT_SYMBOL(gameport_open);
-EXPORT_SYMBOL(gameport_close);
-EXPORT_SYMBOL(gameport_set_phys);
-EXPORT_SYMBOL(gameport_start_polling);
-EXPORT_SYMBOL(gameport_stop_polling);
-
 /*
  * gameport_mutex protects entire gameport subsystem and is taken
  * every time gameport port or driver registrered or unregistered.
@@ -162,6 +152,7 @@
 
 	spin_unlock(&gameport->timer_lock);
 }
+EXPORT_SYMBOL(gameport_start_polling);
 
 void gameport_stop_polling(struct gameport *gameport)
 {
@@ -172,6 +163,7 @@
 
 	spin_unlock(&gameport->timer_lock);
 }
+EXPORT_SYMBOL(gameport_stop_polling);
 
 static void gameport_run_poll_handler(unsigned long d)
 {
@@ -516,6 +508,7 @@
 	vsnprintf(gameport->phys, sizeof(gameport->phys), fmt, args);
 	va_end(args);
 }
+EXPORT_SYMBOL(gameport_set_phys);
 
 /*
  * Prepare gameport port for registration.
@@ -658,6 +651,7 @@
 	gameport_init_port(gameport);
 	gameport_queue_event(gameport, owner, GAMEPORT_REGISTER_PORT);
 }
+EXPORT_SYMBOL(__gameport_register_port);
 
 /*
  * Synchronously unregisters gameport port.
@@ -669,6 +663,7 @@
 	gameport_destroy_port(gameport);
 	mutex_unlock(&gameport_mutex);
 }
+EXPORT_SYMBOL(gameport_unregister_port);
 
 
 /*
@@ -728,7 +723,7 @@
 	 * Temporarily disable automatic binding because probing
 	 * takes long time and we are better off doing it in kgameportd
 	 */
-	drv->ignore = 1;
+	drv->ignore = true;
 
 	error = driver_register(&drv->driver);
 	if (error) {
@@ -741,7 +736,7 @@
 	/*
 	 * Reset ignore flag and let kgameportd bind the driver to free ports
 	 */
-	drv->ignore = 0;
+	drv->ignore = false;
 	error = gameport_queue_event(drv, NULL, GAMEPORT_ATTACH_DRIVER);
 	if (error) {
 		driver_unregister(&drv->driver);
@@ -750,6 +745,7 @@
 
 	return 0;
 }
+EXPORT_SYMBOL(__gameport_register_driver);
 
 void gameport_unregister_driver(struct gameport_driver *drv)
 {
@@ -757,7 +753,7 @@
 
 	mutex_lock(&gameport_mutex);
 
-	drv->ignore = 1;	/* so gameport_find_driver ignores it */
+	drv->ignore = true;	/* so gameport_find_driver ignores it */
 	gameport_remove_pending_events(drv);
 
 start_over:
@@ -774,6 +770,7 @@
 
 	mutex_unlock(&gameport_mutex);
 }
+EXPORT_SYMBOL(gameport_unregister_driver);
 
 static int gameport_bus_match(struct device *dev, struct device_driver *drv)
 {
@@ -812,6 +809,7 @@
 	gameport_set_drv(gameport, drv);
 	return 0;
 }
+EXPORT_SYMBOL(gameport_open);
 
 void gameport_close(struct gameport *gameport)
 {
@@ -822,6 +820,7 @@
 	if (gameport->close)
 		gameport->close(gameport);
 }
+EXPORT_SYMBOL(gameport_close);
 
 static int __init gameport_init(void)
 {
diff --git a/drivers/input/joydev.c b/drivers/input/joydev.c
index 012a5e7..0e12f89 100644
--- a/drivers/input/joydev.c
+++ b/drivers/input/joydev.c
@@ -39,7 +39,6 @@
 	int exist;
 	int open;
 	int minor;
-	char name[16];
 	struct input_handle handle;
 	wait_queue_head_t wait;
 	struct list_head client_list;
@@ -537,12 +536,14 @@
 	default:
 		if ((cmd & ~IOCSIZE_MASK) == JSIOCGNAME(0)) {
 			int len;
-			if (!dev->name)
+			const char *name = dev_name(&dev->dev);
+
+			if (!name)
 				return 0;
-			len = strlen(dev->name) + 1;
+			len = strlen(name) + 1;
 			if (len > _IOC_SIZE(cmd))
 				len = _IOC_SIZE(cmd);
-			if (copy_to_user(argp, dev->name, len))
+			if (copy_to_user(argp, name, len))
 				return -EFAULT;
 			return len;
 		}
@@ -742,13 +743,13 @@
 	mutex_init(&joydev->mutex);
 	init_waitqueue_head(&joydev->wait);
 
-	snprintf(joydev->name, sizeof(joydev->name), "js%d", minor);
+	dev_set_name(&joydev->dev, "js%d", minor);
 	joydev->exist = 1;
 	joydev->minor = minor;
 
 	joydev->exist = 1;
 	joydev->handle.dev = input_get_device(dev);
-	joydev->handle.name = joydev->name;
+	joydev->handle.name = dev_name(&joydev->dev);
 	joydev->handle.handler = handler;
 	joydev->handle.private = joydev;
 
@@ -797,7 +798,6 @@
 		}
 	}
 
-	dev_set_name(&joydev->dev, joydev->name);
 	joydev->dev.devt = MKDEV(INPUT_MAJOR, JOYDEV_MINOR_BASE + minor);
 	joydev->dev.class = &input_class;
 	joydev->dev.parent = &dev->dev;
diff --git a/drivers/input/keyboard/Kconfig b/drivers/input/keyboard/Kconfig
index ea2638b..9d8f796 100644
--- a/drivers/input/keyboard/Kconfig
+++ b/drivers/input/keyboard/Kconfig
@@ -250,6 +250,17 @@
 	  To compile this driver as a module, choose M here: the
 	  module will be called jornada720_kbd.
 
+config KEYBOARD_LM8323
+	tristate "LM8323 keypad chip"
+	depends on I2C
+	depends on LEDS_CLASS
+	help
+	  If you say yes here you get support for the National Semiconductor
+	  LM8323 keypad controller.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called lm8323.
+
 config KEYBOARD_OMAP
 	tristate "TI OMAP keypad support"
 	depends on (ARCH_OMAP1 || ARCH_OMAP2)
@@ -332,4 +343,14 @@
 
 	  To compile this driver as a module, choose M here: the
 	  module will be called sh_keysc.
+
+config KEYBOARD_EP93XX
+	tristate "EP93xx Matrix Keypad support"
+	depends on ARCH_EP93XX
+	help
+	  Say Y here to enable the matrix keypad on the Cirrus EP93XX.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called ep93xx_keypad.
+
 endif
diff --git a/drivers/input/keyboard/Makefile b/drivers/input/keyboard/Makefile
index 36351e1..156b647 100644
--- a/drivers/input/keyboard/Makefile
+++ b/drivers/input/keyboard/Makefile
@@ -18,6 +18,7 @@
 obj-$(CONFIG_KEYBOARD_TOSA)		+= tosakbd.o
 obj-$(CONFIG_KEYBOARD_HIL)		+= hil_kbd.o
 obj-$(CONFIG_KEYBOARD_HIL_OLD)		+= hilkbd.o
+obj-$(CONFIG_KEYBOARD_LM8323)		+= lm8323.o
 obj-$(CONFIG_KEYBOARD_OMAP)		+= omap-keypad.o
 obj-$(CONFIG_KEYBOARD_PXA27x)		+= pxa27x_keypad.o
 obj-$(CONFIG_KEYBOARD_PXA930_ROTARY)	+= pxa930_rotary.o
@@ -28,3 +29,4 @@
 obj-$(CONFIG_KEYBOARD_MAPLE)		+= maple_keyb.o
 obj-$(CONFIG_KEYBOARD_BFIN)		+= bf54x-keys.o
 obj-$(CONFIG_KEYBOARD_SH_KEYSC)		+= sh_keysc.o
+obj-$(CONFIG_KEYBOARD_EP93XX)		+= ep93xx_keypad.o
diff --git a/drivers/input/keyboard/ep93xx_keypad.c b/drivers/input/keyboard/ep93xx_keypad.c
new file mode 100644
index 0000000..181d30e
--- /dev/null
+++ b/drivers/input/keyboard/ep93xx_keypad.c
@@ -0,0 +1,470 @@
+/*
+ * Driver for the Cirrus EP93xx matrix keypad controller.
+ *
+ * Copyright (c) 2008 H Hartley Sweeten <hsweeten@visionengravers.com>
+ *
+ * Based on the pxa27x matrix keypad controller by Rodolfo Giometti.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * NOTE:
+ *
+ * The 3-key reset is triggered by pressing the 3 keys in
+ * Row 0, Columns 2, 4, and 7 at the same time.  This action can
+ * be disabled by setting the EP93XX_KEYPAD_DISABLE_3_KEY flag.
+ *
+ * Normal operation for the matrix does not autorepeat the key press.
+ * This action can be enabled by setting the EP93XX_KEYPAD_AUTOREPEAT
+ * flag.
+ */
+
+#include <linux/platform_device.h>
+#include <linux/interrupt.h>
+#include <linux/input.h>
+#include <linux/clk.h>
+
+#include <mach/hardware.h>
+#include <mach/gpio.h>
+#include <mach/ep93xx_keypad.h>
+
+/*
+ * Keypad Interface Register offsets
+ */
+#define KEY_INIT		0x00	/* Key Scan Initialization register */
+#define KEY_DIAG		0x04	/* Key Scan Diagnostic register */
+#define KEY_REG			0x08	/* Key Value Capture register */
+
+/* Key Scan Initialization Register bit defines */
+#define KEY_INIT_DBNC_MASK	(0x00ff0000)
+#define KEY_INIT_DBNC_SHIFT	(16)
+#define KEY_INIT_DIS3KY		(1<<15)
+#define KEY_INIT_DIAG		(1<<14)
+#define KEY_INIT_BACK		(1<<13)
+#define KEY_INIT_T2		(1<<12)
+#define KEY_INIT_PRSCL_MASK	(0x000003ff)
+#define KEY_INIT_PRSCL_SHIFT	(0)
+
+/* Key Scan Diagnostic Register bit defines */
+#define KEY_DIAG_MASK		(0x0000003f)
+#define KEY_DIAG_SHIFT		(0)
+
+/* Key Value Capture Register bit defines */
+#define KEY_REG_K		(1<<15)
+#define KEY_REG_INT		(1<<14)
+#define KEY_REG_2KEYS		(1<<13)
+#define KEY_REG_1KEY		(1<<12)
+#define KEY_REG_KEY2_MASK	(0x00000fc0)
+#define KEY_REG_KEY2_SHIFT	(6)
+#define KEY_REG_KEY1_MASK	(0x0000003f)
+#define KEY_REG_KEY1_SHIFT	(0)
+
+#define keypad_readl(off)	__raw_readl(keypad->mmio_base + (off))
+#define keypad_writel(v, off)	__raw_writel((v), keypad->mmio_base + (off))
+
+#define MAX_MATRIX_KEY_NUM	(MAX_MATRIX_KEY_ROWS * MAX_MATRIX_KEY_COLS)
+
+struct ep93xx_keypad {
+	struct ep93xx_keypad_platform_data *pdata;
+
+	struct clk *clk;
+	struct input_dev *input_dev;
+	void __iomem *mmio_base;
+
+	int irq;
+	int enabled;
+
+	int key1;
+	int key2;
+
+	unsigned int matrix_keycodes[MAX_MATRIX_KEY_NUM];
+};
+
+static void ep93xx_keypad_build_keycode(struct ep93xx_keypad *keypad)
+{
+	struct ep93xx_keypad_platform_data *pdata = keypad->pdata;
+	struct input_dev *input_dev = keypad->input_dev;
+	int i;
+
+	for (i = 0; i < pdata->matrix_key_map_size; i++) {
+		unsigned int key = pdata->matrix_key_map[i];
+		int row = (key >> 28) & 0xf;
+		int col = (key >> 24) & 0xf;
+		int code = key & 0xffffff;
+
+		keypad->matrix_keycodes[(row << 3) + col] = code;
+		__set_bit(code, input_dev->keybit);
+	}
+}
+
+static irqreturn_t ep93xx_keypad_irq_handler(int irq, void *dev_id)
+{
+	struct ep93xx_keypad *keypad = dev_id;
+	struct input_dev *input_dev = keypad->input_dev;
+	unsigned int status = keypad_readl(KEY_REG);
+	int keycode, key1, key2;
+
+	keycode = (status & KEY_REG_KEY1_MASK) >> KEY_REG_KEY1_SHIFT;
+	key1 = keypad->matrix_keycodes[keycode];
+
+	keycode = (status & KEY_REG_KEY2_MASK) >> KEY_REG_KEY2_SHIFT;
+	key2 = keypad->matrix_keycodes[keycode];
+
+	if (status & KEY_REG_2KEYS) {
+		if (keypad->key1 && key1 != keypad->key1 && key2 != keypad->key1)
+			input_report_key(input_dev, keypad->key1, 0);
+
+		if (keypad->key2 && key1 != keypad->key2 && key2 != keypad->key2)
+			input_report_key(input_dev, keypad->key2, 0);
+
+		input_report_key(input_dev, key1, 1);
+		input_report_key(input_dev, key2, 1);
+
+		keypad->key1 = key1;
+		keypad->key2 = key2;
+
+	} else if (status & KEY_REG_1KEY) {
+		if (keypad->key1 && key1 != keypad->key1)
+			input_report_key(input_dev, keypad->key1, 0);
+
+		if (keypad->key2 && key1 != keypad->key2)
+			input_report_key(input_dev, keypad->key2, 0);
+
+		input_report_key(input_dev, key1, 1);
+
+		keypad->key1 = key1;
+		keypad->key2 = 0;
+
+	} else {
+		input_report_key(input_dev, keypad->key1, 0);
+		input_report_key(input_dev, keypad->key2, 0);
+
+		keypad->key1 = keypad->key2 = 0;
+	}
+	input_sync(input_dev);
+
+	return IRQ_HANDLED;
+}
+
+static void ep93xx_keypad_config(struct ep93xx_keypad *keypad)
+{
+	struct ep93xx_keypad_platform_data *pdata = keypad->pdata;
+	unsigned int val = 0;
+
+	clk_set_rate(keypad->clk, pdata->flags & EP93XX_KEYPAD_KDIV);
+
+	if (pdata->flags & EP93XX_KEYPAD_DISABLE_3_KEY)
+		val |= KEY_INIT_DIS3KY;
+	if (pdata->flags & EP93XX_KEYPAD_DIAG_MODE)
+		val |= KEY_INIT_DIAG;
+	if (pdata->flags & EP93XX_KEYPAD_BACK_DRIVE)
+		val |= KEY_INIT_BACK;
+	if (pdata->flags & EP93XX_KEYPAD_TEST_MODE)
+		val |= KEY_INIT_T2;
+
+	val |= ((pdata->debounce << KEY_INIT_DBNC_SHIFT) & KEY_INIT_DBNC_MASK);
+
+	val |= ((pdata->prescale << KEY_INIT_PRSCL_SHIFT) & KEY_INIT_PRSCL_MASK);
+
+	keypad_writel(val, KEY_INIT);
+}
+
+static int ep93xx_keypad_open(struct input_dev *pdev)
+{
+	struct ep93xx_keypad *keypad = input_get_drvdata(pdev);
+
+	if (!keypad->enabled) {
+		ep93xx_keypad_config(keypad);
+		clk_enable(keypad->clk);
+		keypad->enabled = 1;
+	}
+
+	return 0;
+}
+
+static void ep93xx_keypad_close(struct input_dev *pdev)
+{
+	struct ep93xx_keypad *keypad = input_get_drvdata(pdev);
+
+	if (keypad->enabled) {
+		clk_disable(keypad->clk);
+		keypad->enabled = 0;
+	}
+}
+
+
+#ifdef CONFIG_PM
+/*
+ * NOTE: I don't know if this is correct, or will work on the ep93xx.
+ *
+ * None of the existing ep93xx drivers have power management support.
+ * But, this is basically what the pxa27x_keypad driver does.
+ */
+static int ep93xx_keypad_suspend(struct platform_device *pdev,
+				 pm_message_t state)
+{
+	struct ep93xx_keypad *keypad = platform_get_drvdata(pdev);
+	struct input_dev *input_dev = keypad->input_dev;
+
+	mutex_lock(&input_dev->mutex);
+
+	if (keypad->enabled) {
+		clk_disable(keypad->clk);
+		keypad->enabled = 0;
+	}
+
+	mutex_unlock(&input_dev->mutex);
+
+	if (device_may_wakeup(&pdev->dev))
+		enable_irq_wake(keypad->irq);
+
+	return 0;
+}
+
+static int ep93xx_keypad_resume(struct platform_device *pdev)
+{
+	struct ep93xx_keypad *keypad = platform_get_drvdata(pdev);
+	struct input_dev *input_dev = keypad->input_dev;
+
+	if (device_may_wakeup(&pdev->dev))
+		disable_irq_wake(keypad->irq);
+
+	mutex_lock(&input_dev->mutex);
+
+	if (input_dev->users) {
+		if (!keypad->enabled) {
+			ep93xx_keypad_config(keypad);
+			clk_enable(keypad->clk);
+			keypad->enabled = 1;
+		}
+	}
+
+	mutex_unlock(&input_dev->mutex);
+
+	return 0;
+}
+#else	/* !CONFIG_PM */
+#define ep93xx_keypad_suspend	NULL
+#define ep93xx_keypad_resume	NULL
+#endif	/* !CONFIG_PM */
+
+static int __devinit ep93xx_keypad_probe(struct platform_device *pdev)
+{
+	struct ep93xx_keypad *keypad;
+	struct ep93xx_keypad_platform_data *pdata = pdev->dev.platform_data;
+	struct input_dev *input_dev;
+	struct resource *res;
+	int irq, err, i, gpio;
+
+	if (!pdata ||
+	    !pdata->matrix_key_rows ||
+	    pdata->matrix_key_rows > MAX_MATRIX_KEY_ROWS ||
+	    !pdata->matrix_key_cols ||
+	    pdata->matrix_key_cols > MAX_MATRIX_KEY_COLS) {
+		dev_err(&pdev->dev, "invalid or missing platform data\n");
+		return -EINVAL;
+	}
+
+	keypad = kzalloc(sizeof(struct ep93xx_keypad), GFP_KERNEL);
+	if (!keypad) {
+		dev_err(&pdev->dev, "failed to allocate driver data\n");
+		return -ENOMEM;
+	}
+
+	keypad->pdata = pdata;
+
+	irq = platform_get_irq(pdev, 0);
+	if (irq < 0) {
+		dev_err(&pdev->dev, "failed to get keypad irq\n");
+		err = -ENXIO;
+		goto failed_free;
+	}
+
+	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
+	if (!res) {
+		dev_err(&pdev->dev, "failed to get I/O memory\n");
+		err = -ENXIO;
+		goto failed_free;
+	}
+
+	res = request_mem_region(res->start, resource_size(res), pdev->name);
+	if (!res) {
+		dev_err(&pdev->dev, "failed to request I/O memory\n");
+		err = -EBUSY;
+		goto failed_free;
+	}
+
+	keypad->mmio_base = ioremap(res->start, resource_size(res));
+	if (keypad->mmio_base == NULL) {
+		dev_err(&pdev->dev, "failed to remap I/O memory\n");
+		err = -ENXIO;
+		goto failed_free_mem;
+	}
+
+	/* Request the needed GPIO's */
+	gpio = EP93XX_GPIO_LINE_ROW0;
+	for (i = 0; i < keypad->pdata->matrix_key_rows; i++, gpio++) {
+		err = gpio_request(gpio, pdev->name);
+		if (err) {
+			dev_err(&pdev->dev, "failed to request gpio-%d\n",
+				gpio);
+			goto failed_free_rows;
+		}
+	}
+
+	gpio = EP93XX_GPIO_LINE_COL0;
+	for (i = 0; i < keypad->pdata->matrix_key_cols; i++, gpio++) {
+		err = gpio_request(gpio, pdev->name);
+		if (err) {
+			dev_err(&pdev->dev, "failed to request gpio-%d\n",
+				gpio);
+			goto failed_free_cols;
+		}
+	}
+
+	keypad->clk = clk_get(&pdev->dev, "key_clk");
+	if (IS_ERR(keypad->clk)) {
+		dev_err(&pdev->dev, "failed to get keypad clock\n");
+		err = PTR_ERR(keypad->clk);
+		goto failed_free_io;
+	}
+
+	/* Create and register the input driver */
+	input_dev = input_allocate_device();
+	if (!input_dev) {
+		dev_err(&pdev->dev, "failed to allocate input device\n");
+		err = -ENOMEM;
+		goto failed_put_clk;
+	}
+
+	keypad->input_dev = input_dev;
+
+	input_dev->name = pdev->name;
+	input_dev->id.bustype = BUS_HOST;
+	input_dev->open = ep93xx_keypad_open;
+	input_dev->close = ep93xx_keypad_close;
+	input_dev->dev.parent = &pdev->dev;
+	input_dev->keycode = keypad->matrix_keycodes;
+	input_dev->keycodesize = sizeof(keypad->matrix_keycodes[0]);
+	input_dev->keycodemax = ARRAY_SIZE(keypad->matrix_keycodes);
+
+	input_set_drvdata(input_dev, keypad);
+
+	input_dev->evbit[0] = BIT_MASK(EV_KEY);
+	if (keypad->pdata->flags & EP93XX_KEYPAD_AUTOREPEAT)
+		input_dev->evbit[0] |= BIT_MASK(EV_REP);
+
+	ep93xx_keypad_build_keycode(keypad);
+	platform_set_drvdata(pdev, keypad);
+
+	err = request_irq(irq, ep93xx_keypad_irq_handler, IRQF_DISABLED,
+				pdev->name, keypad);
+	if (err) {
+		dev_err(&pdev->dev, "failed to request IRQ\n");
+		goto failed_free_dev;
+	}
+
+	keypad->irq = irq;
+
+	/* Register the input device */
+	err = input_register_device(input_dev);
+	if (err) {
+		dev_err(&pdev->dev, "failed to register input device\n");
+		goto failed_free_irq;
+	}
+
+	device_init_wakeup(&pdev->dev, 1);
+
+	return 0;
+
+failed_free_irq:
+	free_irq(irq, pdev);
+	platform_set_drvdata(pdev, NULL);
+failed_free_dev:
+	input_free_device(input_dev);
+failed_put_clk:
+	clk_put(keypad->clk);
+failed_free_io:
+	i = keypad->pdata->matrix_key_cols - 1;
+	gpio = EP93XX_GPIO_LINE_COL0 + i;
+failed_free_cols:
+	for ( ; i >= 0; i--, gpio--)
+		gpio_free(gpio);
+	i = keypad->pdata->matrix_key_rows - 1;
+	gpio = EP93XX_GPIO_LINE_ROW0 + i;
+failed_free_rows:
+	for ( ; i >= 0; i--, gpio--)
+		gpio_free(gpio);
+	iounmap(keypad->mmio_base);
+failed_free_mem:
+	release_mem_region(res->start, resource_size(res));
+failed_free:
+	kfree(keypad);
+	return err;
+}
+
+static int __devexit ep93xx_keypad_remove(struct platform_device *pdev)
+{
+	struct ep93xx_keypad *keypad = platform_get_drvdata(pdev);
+	struct resource *res;
+	int i, gpio;
+
+	free_irq(keypad->irq, pdev);
+
+	platform_set_drvdata(pdev, NULL);
+
+	if (keypad->enabled)
+		clk_disable(keypad->clk);
+	clk_put(keypad->clk);
+
+	input_unregister_device(keypad->input_dev);
+
+	i = keypad->pdata->matrix_key_cols - 1;
+	gpio = EP93XX_GPIO_LINE_COL0 + i;
+	for ( ; i >= 0; i--, gpio--)
+		gpio_free(gpio);
+
+	i = keypad->pdata->matrix_key_rows - 1;
+	gpio = EP93XX_GPIO_LINE_ROW0 + i;
+	for ( ; i >= 0; i--, gpio--)
+		gpio_free(gpio);
+
+	iounmap(keypad->mmio_base);
+
+	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
+	release_mem_region(res->start, resource_size(res));
+
+	kfree(keypad);
+
+	return 0;
+}
+
+static struct platform_driver ep93xx_keypad_driver = {
+	.driver		= {
+		.name	= "ep93xx-keypad",
+		.owner	= THIS_MODULE,
+	},
+	.probe		= ep93xx_keypad_probe,
+	.remove		= __devexit_p(ep93xx_keypad_remove),
+	.suspend	= ep93xx_keypad_suspend,
+	.resume		= ep93xx_keypad_resume,
+};
+
+static int __init ep93xx_keypad_init(void)
+{
+	return platform_driver_register(&ep93xx_keypad_driver);
+}
+
+static void __exit ep93xx_keypad_exit(void)
+{
+	platform_driver_unregister(&ep93xx_keypad_driver);
+}
+
+module_init(ep93xx_keypad_init);
+module_exit(ep93xx_keypad_exit);
+
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("H Hartley Sweeten <hsweeten@visionengravers.com>");
+MODULE_DESCRIPTION("EP93xx Matrix Keypad Controller");
+MODULE_ALIAS("platform:ep93xx-keypad");
diff --git a/drivers/input/keyboard/gpio_keys.c b/drivers/input/keyboard/gpio_keys.c
index ad67d76..2157cd7 100644
--- a/drivers/input/keyboard/gpio_keys.c
+++ b/drivers/input/keyboard/gpio_keys.c
@@ -22,13 +22,14 @@
 #include <linux/platform_device.h>
 #include <linux/input.h>
 #include <linux/gpio_keys.h>
+#include <linux/workqueue.h>
 
 #include <asm/gpio.h>
 
 struct gpio_button_data {
 	struct gpio_keys_button *button;
 	struct input_dev *input;
-	struct timer_list timer;
+	struct delayed_work work;
 };
 
 struct gpio_keys_drvdata {
@@ -36,8 +37,10 @@
 	struct gpio_button_data data[0];
 };
 
-static void gpio_keys_report_event(struct gpio_button_data *bdata)
+static void gpio_keys_report_event(struct work_struct *work)
 {
+	struct gpio_button_data *bdata =
+		container_of(work, struct gpio_button_data, work.work);
 	struct gpio_keys_button *button = bdata->button;
 	struct input_dev *input = bdata->input;
 	unsigned int type = button->type ?: EV_KEY;
@@ -47,25 +50,17 @@
 	input_sync(input);
 }
 
-static void gpio_check_button(unsigned long _data)
-{
-	struct gpio_button_data *data = (struct gpio_button_data *)_data;
-
-	gpio_keys_report_event(data);
-}
-
 static irqreturn_t gpio_keys_isr(int irq, void *dev_id)
 {
 	struct gpio_button_data *bdata = dev_id;
 	struct gpio_keys_button *button = bdata->button;
+	unsigned long delay;
 
 	BUG_ON(irq != gpio_to_irq(button->gpio));
 
-	if (button->debounce_interval)
-		mod_timer(&bdata->timer,
-			jiffies + msecs_to_jiffies(button->debounce_interval));
-	else
-		gpio_keys_report_event(bdata);
+	delay = button->debounce_interval ?
+			msecs_to_jiffies(button->debounce_interval) : 0;
+	schedule_delayed_work(&bdata->work, delay);
 
 	return IRQ_HANDLED;
 }
@@ -112,8 +107,7 @@
 
 		bdata->input = input;
 		bdata->button = button;
-		setup_timer(&bdata->timer,
-			    gpio_check_button, (unsigned long)bdata);
+		INIT_DELAYED_WORK(&bdata->work, gpio_keys_report_event);
 
 		error = gpio_request(button->gpio, button->desc ?: "gpio_keys");
 		if (error < 0) {
@@ -142,8 +136,7 @@
 		}
 
 		error = request_irq(irq, gpio_keys_isr,
-				    IRQF_SAMPLE_RANDOM | IRQF_TRIGGER_RISING |
-					IRQF_TRIGGER_FALLING,
+				    IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
 				    button->desc ? button->desc : "gpio_keys",
 				    bdata);
 		if (error) {
@@ -173,8 +166,7 @@
  fail2:
 	while (--i >= 0) {
 		free_irq(gpio_to_irq(pdata->buttons[i].gpio), &ddata->data[i]);
-		if (pdata->buttons[i].debounce_interval)
-			del_timer_sync(&ddata->data[i].timer);
+		cancel_delayed_work_sync(&ddata->data[i].work);
 		gpio_free(pdata->buttons[i].gpio);
 	}
 
@@ -198,8 +190,7 @@
 	for (i = 0; i < pdata->nbuttons; i++) {
 		int irq = gpio_to_irq(pdata->buttons[i].gpio);
 		free_irq(irq, &ddata->data[i]);
-		if (pdata->buttons[i].debounce_interval)
-			del_timer_sync(&ddata->data[i].timer);
+		cancel_delayed_work_sync(&ddata->data[i].work);
 		gpio_free(pdata->buttons[i].gpio);
 	}
 
diff --git a/drivers/input/keyboard/lm8323.c b/drivers/input/keyboard/lm8323.c
new file mode 100644
index 0000000..574eda2
--- /dev/null
+++ b/drivers/input/keyboard/lm8323.c
@@ -0,0 +1,878 @@
+/*
+ * drivers/i2c/chips/lm8323.c
+ *
+ * Copyright (C) 2007-2009 Nokia Corporation
+ *
+ * Written by Daniel Stone <daniel.stone@nokia.com>
+ *            Timo O. Karjalainen <timo.o.karjalainen@nokia.com>
+ *
+ * Updated by Felipe Balbi <felipe.balbi@nokia.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation (version 2 of the License only).
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include <linux/module.h>
+#include <linux/i2c.h>
+#include <linux/interrupt.h>
+#include <linux/sched.h>
+#include <linux/mutex.h>
+#include <linux/delay.h>
+#include <linux/input.h>
+#include <linux/leds.h>
+#include <linux/i2c/lm8323.h>
+
+/* Commands to send to the chip. */
+#define LM8323_CMD_READ_ID		0x80 /* Read chip ID. */
+#define LM8323_CMD_WRITE_CFG		0x81 /* Set configuration item. */
+#define LM8323_CMD_READ_INT		0x82 /* Get interrupt status. */
+#define LM8323_CMD_RESET		0x83 /* Reset, same as external one */
+#define LM8323_CMD_WRITE_PORT_SEL	0x85 /* Set GPIO in/out. */
+#define LM8323_CMD_WRITE_PORT_STATE	0x86 /* Set GPIO pullup. */
+#define LM8323_CMD_READ_PORT_SEL	0x87 /* Get GPIO in/out. */
+#define LM8323_CMD_READ_PORT_STATE	0x88 /* Get GPIO pullup. */
+#define LM8323_CMD_READ_FIFO		0x89 /* Read byte from FIFO. */
+#define LM8323_CMD_RPT_READ_FIFO	0x8a /* Read FIFO (no increment). */
+#define LM8323_CMD_SET_ACTIVE		0x8b /* Set active time. */
+#define LM8323_CMD_READ_ERR		0x8c /* Get error status. */
+#define LM8323_CMD_READ_ROTATOR		0x8e /* Read rotator status. */
+#define LM8323_CMD_SET_DEBOUNCE		0x8f /* Set debouncing time. */
+#define LM8323_CMD_SET_KEY_SIZE		0x90 /* Set keypad size. */
+#define LM8323_CMD_READ_KEY_SIZE	0x91 /* Get keypad size. */
+#define LM8323_CMD_READ_CFG		0x92 /* Get configuration item. */
+#define LM8323_CMD_WRITE_CLOCK		0x93 /* Set clock config. */
+#define LM8323_CMD_READ_CLOCK		0x94 /* Get clock config. */
+#define LM8323_CMD_PWM_WRITE		0x95 /* Write PWM script. */
+#define LM8323_CMD_START_PWM		0x96 /* Start PWM engine. */
+#define LM8323_CMD_STOP_PWM		0x97 /* Stop PWM engine. */
+
+/* Interrupt status. */
+#define INT_KEYPAD			0x01 /* Key event. */
+#define INT_ROTATOR			0x02 /* Rotator event. */
+#define INT_ERROR			0x08 /* Error: use CMD_READ_ERR. */
+#define INT_NOINIT			0x10 /* Lost configuration. */
+#define INT_PWM1			0x20 /* PWM1 stopped. */
+#define INT_PWM2			0x40 /* PWM2 stopped. */
+#define INT_PWM3			0x80 /* PWM3 stopped. */
+
+/* Errors (signalled by INT_ERROR, read with CMD_READ_ERR). */
+#define ERR_BADPAR			0x01 /* Bad parameter. */
+#define ERR_CMDUNK			0x02 /* Unknown command. */
+#define ERR_KEYOVR			0x04 /* Too many keys pressed. */
+#define ERR_FIFOOVER			0x40 /* FIFO overflow. */
+
+/* Configuration keys (CMD_{WRITE,READ}_CFG). */
+#define CFG_MUX1SEL			0x01 /* Select MUX1_OUT input. */
+#define CFG_MUX1EN			0x02 /* Enable MUX1_OUT. */
+#define CFG_MUX2SEL			0x04 /* Select MUX2_OUT input. */
+#define CFG_MUX2EN			0x08 /* Enable MUX2_OUT. */
+#define CFG_PSIZE			0x20 /* Package size (must be 0). */
+#define CFG_ROTEN			0x40 /* Enable rotator. */
+
+/* Clock settings (CMD_{WRITE,READ}_CLOCK). */
+#define CLK_RCPWM_INTERNAL		0x00
+#define CLK_RCPWM_EXTERNAL		0x03
+#define CLK_SLOWCLKEN			0x08 /* Enable 32.768kHz clock. */
+#define CLK_SLOWCLKOUT			0x40 /* Enable slow pulse output. */
+
+/* The possible addresses corresponding to CONFIG1 and CONFIG2 pin wirings. */
+#define LM8323_I2C_ADDR00		(0x84 >> 1)	/* 1000 010x */
+#define LM8323_I2C_ADDR01		(0x86 >> 1)	/* 1000 011x */
+#define LM8323_I2C_ADDR10		(0x88 >> 1)	/* 1000 100x */
+#define LM8323_I2C_ADDR11		(0x8A >> 1)	/* 1000 101x */
+
+/* Key event fifo length */
+#define LM8323_FIFO_LEN			15
+
+/* Commands for PWM engine; feed in with PWM_WRITE. */
+/* Load ramp counter from duty cycle field (range 0 - 0xff). */
+#define PWM_SET(v)			(0x4000 | ((v) & 0xff))
+/* Go to start of script. */
+#define PWM_GOTOSTART			0x0000
+/*
+ * Stop engine (generates interrupt).  If reset is 1, clear the program
+ * counter, else leave it.
+ */
+#define PWM_END(reset)			(0xc000 | (!!(reset) << 11))
+/*
+ * Ramp.  If s is 1, divide clock by 512, else divide clock by 16.
+ * Take t clock scales (up to 63) per step, for n steps (up to 126).
+ * If u is set, ramp up, else ramp down.
+ */
+#define PWM_RAMP(s, t, n, u)		((!!(s) << 14) | ((t) & 0x3f) << 8 | \
+					 ((n) & 0x7f) | ((u) ? 0 : 0x80))
+/*
+ * Loop (i.e. jump back to pos) for a given number of iterations (up to 63).
+ * If cnt is zero, execute until PWM_END is encountered.
+ */
+#define PWM_LOOP(cnt, pos)		(0xa000 | (((cnt) & 0x3f) << 7) | \
+					 ((pos) & 0x3f))
+/*
+ * Wait for trigger.  Argument is a mask of channels, shifted by the channel
+ * number, e.g. 0xa for channels 3 and 1.  Note that channels are numbered
+ * from 1, not 0.
+ */
+#define PWM_WAIT_TRIG(chans)		(0xe000 | (((chans) & 0x7) << 6))
+/* Send trigger.  Argument is same as PWM_WAIT_TRIG. */
+#define PWM_SEND_TRIG(chans)		(0xe000 | ((chans) & 0x7))
+
+struct lm8323_pwm {
+	int			id;
+	int			fade_time;
+	int			brightness;
+	int			desired_brightness;
+	bool			enabled;
+	bool			running;
+	/* pwm lock */
+	struct mutex		lock;
+	struct work_struct	work;
+	struct led_classdev	cdev;
+	struct lm8323_chip	*chip;
+};
+
+struct lm8323_chip {
+	/* device lock */
+	struct mutex		lock;
+	struct i2c_client	*client;
+	struct work_struct	work;
+	struct input_dev	*idev;
+	bool			kp_enabled;
+	bool			pm_suspend;
+	unsigned		keys_down;
+	char			phys[32];
+	unsigned short		keymap[LM8323_KEYMAP_SIZE];
+	int			size_x;
+	int			size_y;
+	int			debounce_time;
+	int			active_time;
+	struct lm8323_pwm	pwm[LM8323_NUM_PWMS];
+};
+
+#define client_to_lm8323(c)	container_of(c, struct lm8323_chip, client)
+#define dev_to_lm8323(d)	container_of(d, struct lm8323_chip, client->dev)
+#define work_to_lm8323(w)	container_of(w, struct lm8323_chip, work)
+#define cdev_to_pwm(c)		container_of(c, struct lm8323_pwm, cdev)
+#define work_to_pwm(w)		container_of(w, struct lm8323_pwm, work)
+
+#define LM8323_MAX_DATA 8
+
+/*
+ * To write, we just access the chip's address in write mode, and dump the
+ * command and data out on the bus.  The command byte and data are taken as
+ * sequential u8s out of varargs, to a maximum of LM8323_MAX_DATA.
+ */
+static int lm8323_write(struct lm8323_chip *lm, int len, ...)
+{
+	int ret, i;
+	va_list ap;
+	u8 data[LM8323_MAX_DATA];
+
+	va_start(ap, len);
+
+	if (unlikely(len > LM8323_MAX_DATA)) {
+		dev_err(&lm->client->dev, "tried to send %d bytes\n", len);
+		va_end(ap);
+		return 0;
+	}
+
+	for (i = 0; i < len; i++)
+		data[i] = va_arg(ap, int);
+
+	va_end(ap);
+
+	/*
+	 * If the host is asleep while we send the data, we can get a NACK
+	 * back while it wakes up, so try again, once.
+	 */
+	ret = i2c_master_send(lm->client, data, len);
+	if (unlikely(ret == -EREMOTEIO))
+		ret = i2c_master_send(lm->client, data, len);
+	if (unlikely(ret != len))
+		dev_err(&lm->client->dev, "sent %d bytes of %d total\n",
+			len, ret);
+
+	return ret;
+}
+
+/*
+ * To read, we first send the command byte to the chip and end the transaction,
+ * then access the chip in read mode, at which point it will send the data.
+ */
+static int lm8323_read(struct lm8323_chip *lm, u8 cmd, u8 *buf, int len)
+{
+	int ret;
+
+	/*
+	 * If the host is asleep while we send the byte, we can get a NACK
+	 * back while it wakes up, so try again, once.
+	 */
+	ret = i2c_master_send(lm->client, &cmd, 1);
+	if (unlikely(ret == -EREMOTEIO))
+		ret = i2c_master_send(lm->client, &cmd, 1);
+	if (unlikely(ret != 1)) {
+		dev_err(&lm->client->dev, "sending read cmd 0x%02x failed\n",
+			cmd);
+		return 0;
+	}
+
+	ret = i2c_master_recv(lm->client, buf, len);
+	if (unlikely(ret != len))
+		dev_err(&lm->client->dev, "wanted %d bytes, got %d\n",
+			len, ret);
+
+	return ret;
+}
+
+/*
+ * Set the chip active time (idle time before it enters halt).
+ */
+static void lm8323_set_active_time(struct lm8323_chip *lm, int time)
+{
+	lm8323_write(lm, 2, LM8323_CMD_SET_ACTIVE, time >> 2);
+}
+
+/*
+ * The signals are AT-style: the low 7 bits are the keycode, and the top
+ * bit indicates the state (1 for down, 0 for up).
+ */
+static inline u8 lm8323_whichkey(u8 event)
+{
+	return event & 0x7f;
+}
+
+static inline int lm8323_ispress(u8 event)
+{
+	return (event & 0x80) ? 1 : 0;
+}
+
+static void process_keys(struct lm8323_chip *lm)
+{
+	u8 event;
+	u8 key_fifo[LM8323_FIFO_LEN + 1];
+	int old_keys_down = lm->keys_down;
+	int ret;
+	int i = 0;
+
+	/*
+	 * Read all key events from the FIFO at once. Next READ_FIFO clears the
+	 * FIFO even if we didn't read all events previously.
+	 */
+	ret = lm8323_read(lm, LM8323_CMD_READ_FIFO, key_fifo, LM8323_FIFO_LEN);
+
+	if (ret < 0) {
+		dev_err(&lm->client->dev, "Failed reading fifo \n");
+		return;
+	}
+	key_fifo[ret] = 0;
+
+	while ((event = key_fifo[i++])) {
+		u8 key = lm8323_whichkey(event);
+		int isdown = lm8323_ispress(event);
+		unsigned short keycode = lm->keymap[key];
+
+		dev_vdbg(&lm->client->dev, "key 0x%02x %s\n",
+			 key, isdown ? "down" : "up");
+
+		if (lm->kp_enabled) {
+			input_event(lm->idev, EV_MSC, MSC_SCAN, key);
+			input_report_key(lm->idev, keycode, isdown);
+			input_sync(lm->idev);
+		}
+
+		if (isdown)
+			lm->keys_down++;
+		else
+			lm->keys_down--;
+	}
+
+	/*
+	 * Errata: We need to ensure that the chip never enters halt mode
+	 * during a keypress, so set active time to 0.  When it's released,
+	 * we can enter halt again, so set the active time back to normal.
+	 */
+	if (!old_keys_down && lm->keys_down)
+		lm8323_set_active_time(lm, 0);
+	if (old_keys_down && !lm->keys_down)
+		lm8323_set_active_time(lm, lm->active_time);
+}
+
+static void lm8323_process_error(struct lm8323_chip *lm)
+{
+	u8 error;
+
+	if (lm8323_read(lm, LM8323_CMD_READ_ERR, &error, 1) == 1) {
+		if (error & ERR_FIFOOVER)
+			dev_vdbg(&lm->client->dev, "fifo overflow!\n");
+		if (error & ERR_KEYOVR)
+			dev_vdbg(&lm->client->dev,
+					"more than two keys pressed\n");
+		if (error & ERR_CMDUNK)
+			dev_vdbg(&lm->client->dev,
+					"unknown command submitted\n");
+		if (error & ERR_BADPAR)
+			dev_vdbg(&lm->client->dev, "bad command parameter\n");
+	}
+}
+
+static void lm8323_reset(struct lm8323_chip *lm)
+{
+	/* The docs say we must pass 0xAA as the data byte. */
+	lm8323_write(lm, 2, LM8323_CMD_RESET, 0xAA);
+}
+
+static int lm8323_configure(struct lm8323_chip *lm)
+{
+	int keysize = (lm->size_x << 4) | lm->size_y;
+	int clock = (CLK_SLOWCLKEN | CLK_RCPWM_EXTERNAL);
+	int debounce = lm->debounce_time >> 2;
+	int active = lm->active_time >> 2;
+
+	/*
+	 * Active time must be greater than the debounce time: if it's
+	 * a close-run thing, give ourselves a 12ms buffer.
+	 */
+	if (debounce >= active)
+		active = debounce + 3;
+
+	lm8323_write(lm, 2, LM8323_CMD_WRITE_CFG, 0);
+	lm8323_write(lm, 2, LM8323_CMD_WRITE_CLOCK, clock);
+	lm8323_write(lm, 2, LM8323_CMD_SET_KEY_SIZE, keysize);
+	lm8323_set_active_time(lm, lm->active_time);
+	lm8323_write(lm, 2, LM8323_CMD_SET_DEBOUNCE, debounce);
+	lm8323_write(lm, 3, LM8323_CMD_WRITE_PORT_STATE, 0xff, 0xff);
+	lm8323_write(lm, 3, LM8323_CMD_WRITE_PORT_SEL, 0, 0);
+
+	/*
+	 * Not much we can do about errors at this point, so just hope
+	 * for the best.
+	 */
+
+	return 0;
+}
+
+static void pwm_done(struct lm8323_pwm *pwm)
+{
+	mutex_lock(&pwm->lock);
+	pwm->running = false;
+	if (pwm->desired_brightness != pwm->brightness)
+		schedule_work(&pwm->work);
+	mutex_unlock(&pwm->lock);
+}
+
+/*
+ * Bottom half: handle the interrupt by posting key events, or dealing with
+ * errors appropriately.
+ */
+static void lm8323_work(struct work_struct *work)
+{
+	struct lm8323_chip *lm = work_to_lm8323(work);
+	u8 ints;
+	int i;
+
+	mutex_lock(&lm->lock);
+
+	while ((lm8323_read(lm, LM8323_CMD_READ_INT, &ints, 1) == 1) && ints) {
+		if (likely(ints & INT_KEYPAD))
+			process_keys(lm);
+		if (ints & INT_ROTATOR) {
+			/* We don't currently support the rotator. */
+			dev_vdbg(&lm->client->dev, "rotator fired\n");
+		}
+		if (ints & INT_ERROR) {
+			dev_vdbg(&lm->client->dev, "error!\n");
+			lm8323_process_error(lm);
+		}
+		if (ints & INT_NOINIT) {
+			dev_err(&lm->client->dev, "chip lost config; "
+						  "reinitialising\n");
+			lm8323_configure(lm);
+		}
+		for (i = 0; i < LM8323_NUM_PWMS; i++) {
+			if (ints & (1 << (INT_PWM1 + i))) {
+				dev_vdbg(&lm->client->dev,
+					 "pwm%d engine completed\n", i);
+				pwm_done(&lm->pwm[i]);
+			}
+		}
+	}
+
+	mutex_unlock(&lm->lock);
+}
+
+/*
+ * We cannot use I2C in interrupt context, so we just schedule work.
+ */
+static irqreturn_t lm8323_irq(int irq, void *data)
+{
+	struct lm8323_chip *lm = data;
+
+	schedule_work(&lm->work);
+
+	return IRQ_HANDLED;
+}
+
+/*
+ * Read the chip ID.
+ */
+static int lm8323_read_id(struct lm8323_chip *lm, u8 *buf)
+{
+	int bytes;
+
+	bytes = lm8323_read(lm, LM8323_CMD_READ_ID, buf, 2);
+	if (unlikely(bytes != 2))
+		return -EIO;
+
+	return 0;
+}
+
+static void lm8323_write_pwm_one(struct lm8323_pwm *pwm, int pos, u16 cmd)
+{
+	lm8323_write(pwm->chip, 4, LM8323_CMD_PWM_WRITE, (pos << 2) | pwm->id,
+		     (cmd & 0xff00) >> 8, cmd & 0x00ff);
+}
+
+/*
+ * Write a script into a given PWM engine, concluding with PWM_END.
+ * If 'kill' is nonzero, the engine will be shut down at the end
+ * of the script, producing a zero output. Otherwise the engine
+ * will be kept running at the final PWM level indefinitely.
+ */
+static void lm8323_write_pwm(struct lm8323_pwm *pwm, int kill,
+			     int len, const u16 *cmds)
+{
+	int i;
+
+	for (i = 0; i < len; i++)
+		lm8323_write_pwm_one(pwm, i, cmds[i]);
+
+	lm8323_write_pwm_one(pwm, i++, PWM_END(kill));
+	lm8323_write(pwm->chip, 2, LM8323_CMD_START_PWM, pwm->id);
+	pwm->running = true;
+}
+
+static void lm8323_pwm_work(struct work_struct *work)
+{
+	struct lm8323_pwm *pwm = work_to_pwm(work);
+	int div512, perstep, steps, hz, up, kill;
+	u16 pwm_cmds[3];
+	int num_cmds = 0;
+
+	mutex_lock(&pwm->lock);
+
+	/*
+	 * Do nothing if we're already at the requested level,
+	 * or previous setting is not yet complete. In the latter
+	 * case we will be called again when the previous PWM script
+	 * finishes.
+	 */
+	if (pwm->running || pwm->desired_brightness == pwm->brightness)
+		goto out;
+
+	kill = (pwm->desired_brightness == 0);
+	up = (pwm->desired_brightness > pwm->brightness);
+	steps = abs(pwm->desired_brightness - pwm->brightness);
+
+	/*
+	 * Convert time (in ms) into a divisor (512 or 16 on a refclk of
+	 * 32768Hz), and number of ticks per step.
+	 */
+	if ((pwm->fade_time / steps) > (32768 / 512)) {
+		div512 = 1;
+		hz = 32768 / 512;
+	} else {
+		div512 = 0;
+		hz = 32768 / 16;
+	}
+
+	perstep = (hz * pwm->fade_time) / (steps * 1000);
+
+	if (perstep == 0)
+		perstep = 1;
+	else if (perstep > 63)
+		perstep = 63;
+
+	while (steps) {
+		int s;
+
+		s = min(126, steps);
+		pwm_cmds[num_cmds++] = PWM_RAMP(div512, perstep, s, up);
+		steps -= s;
+	}
+
+	lm8323_write_pwm(pwm, kill, num_cmds, pwm_cmds);
+	pwm->brightness = pwm->desired_brightness;
+
+ out:
+	mutex_unlock(&pwm->lock);
+}
+
+static void lm8323_pwm_set_brightness(struct led_classdev *led_cdev,
+				      enum led_brightness brightness)
+{
+	struct lm8323_pwm *pwm = cdev_to_pwm(led_cdev);
+	struct lm8323_chip *lm = pwm->chip;
+
+	mutex_lock(&pwm->lock);
+	pwm->desired_brightness = brightness;
+	mutex_unlock(&pwm->lock);
+
+	if (in_interrupt()) {
+		schedule_work(&pwm->work);
+	} else {
+		/*
+		 * Schedule PWM work as usual unless we are going into suspend
+		 */
+		mutex_lock(&lm->lock);
+		if (likely(!lm->pm_suspend))
+			schedule_work(&pwm->work);
+		else
+			lm8323_pwm_work(&pwm->work);
+		mutex_unlock(&lm->lock);
+	}
+}
+
+static ssize_t lm8323_pwm_show_time(struct device *dev,
+		struct device_attribute *attr, char *buf)
+{
+	struct led_classdev *led_cdev = dev_get_drvdata(dev);
+	struct lm8323_pwm *pwm = cdev_to_pwm(led_cdev);
+
+	return sprintf(buf, "%d\n", pwm->fade_time);
+}
+
+static ssize_t lm8323_pwm_store_time(struct device *dev,
+		struct device_attribute *attr, const char *buf, size_t len)
+{
+	struct led_classdev *led_cdev = dev_get_drvdata(dev);
+	struct lm8323_pwm *pwm = cdev_to_pwm(led_cdev);
+	int ret;
+	unsigned long time;
+
+	ret = strict_strtoul(buf, 10, &time);
+	/* Numbers only, please. */
+	if (ret)
+		return -EINVAL;
+
+	pwm->fade_time = time;
+
+	return strlen(buf);
+}
+static DEVICE_ATTR(time, 0644, lm8323_pwm_show_time, lm8323_pwm_store_time);
+
+static int init_pwm(struct lm8323_chip *lm, int id, struct device *dev,
+		    const char *name)
+{
+	struct lm8323_pwm *pwm;
+
+	BUG_ON(id > 3);
+
+	pwm = &lm->pwm[id - 1];
+
+	pwm->id = id;
+	pwm->fade_time = 0;
+	pwm->brightness = 0;
+	pwm->desired_brightness = 0;
+	pwm->running = false;
+	pwm->enabled = false;
+	INIT_WORK(&pwm->work, lm8323_pwm_work);
+	mutex_init(&pwm->lock);
+	pwm->chip = lm;
+
+	if (name) {
+		pwm->cdev.name = name;
+		pwm->cdev.brightness_set = lm8323_pwm_set_brightness;
+		if (led_classdev_register(dev, &pwm->cdev) < 0) {
+			dev_err(dev, "couldn't register PWM %d\n", id);
+			return -1;
+		}
+		if (device_create_file(pwm->cdev.dev,
+					&dev_attr_time) < 0) {
+			dev_err(dev, "couldn't register time attribute\n");
+			led_classdev_unregister(&pwm->cdev);
+			return -1;
+		}
+		pwm->enabled = true;
+	}
+
+	return 0;
+}
+
+static struct i2c_driver lm8323_i2c_driver;
+
+static ssize_t lm8323_show_disable(struct device *dev,
+				   struct device_attribute *attr, char *buf)
+{
+	struct lm8323_chip *lm = dev_get_drvdata(dev);
+
+	return sprintf(buf, "%u\n", !lm->kp_enabled);
+}
+
+static ssize_t lm8323_set_disable(struct device *dev,
+				  struct device_attribute *attr,
+				  const char *buf, size_t count)
+{
+	struct lm8323_chip *lm = dev_get_drvdata(dev);
+	int ret;
+	unsigned long i;
+
+	ret = strict_strtoul(buf, 10, &i);
+
+	mutex_lock(&lm->lock);
+	lm->kp_enabled = !i;
+	mutex_unlock(&lm->lock);
+
+	return count;
+}
+static DEVICE_ATTR(disable_kp, 0644, lm8323_show_disable, lm8323_set_disable);
+
+static int __devinit lm8323_probe(struct i2c_client *client,
+				  const struct i2c_device_id *id)
+{
+	struct lm8323_platform_data *pdata = client->dev.platform_data;
+	struct input_dev *idev;
+	struct lm8323_chip *lm;
+	int i, err;
+	unsigned long tmo;
+	u8 data[2];
+
+	if (!pdata || !pdata->size_x || !pdata->size_y) {
+		dev_err(&client->dev, "missing platform_data\n");
+		return -EINVAL;
+	}
+
+	if (pdata->size_x > 8) {
+		dev_err(&client->dev, "invalid x size %d specified\n",
+			pdata->size_x);
+		return -EINVAL;
+	}
+
+	if (pdata->size_y > 12) {
+		dev_err(&client->dev, "invalid y size %d specified\n",
+			pdata->size_y);
+		return -EINVAL;
+	}
+
+	lm = kzalloc(sizeof *lm, GFP_KERNEL);
+	idev = input_allocate_device();
+	if (!lm || !idev) {
+		err = -ENOMEM;
+		goto fail1;
+	}
+
+	i2c_set_clientdata(client, lm);
+
+	lm->client = client;
+	lm->idev = idev;
+	mutex_init(&lm->lock);
+	INIT_WORK(&lm->work, lm8323_work);
+
+	lm->size_x = pdata->size_x;
+	lm->size_y = pdata->size_y;
+	dev_vdbg(&client->dev, "Keypad size: %d x %d\n",
+		 lm->size_x, lm->size_y);
+
+	lm->debounce_time = pdata->debounce_time;
+	lm->active_time = pdata->active_time;
+
+	lm8323_reset(lm);
+
+	/* Nothing's set up to service the IRQ yet, so just spin for max.
+	 * 100ms until we can configure. */
+	tmo = jiffies + msecs_to_jiffies(100);
+	while (lm8323_read(lm, LM8323_CMD_READ_INT, data, 1) == 1) {
+		if (data[0] & INT_NOINIT)
+			break;
+
+		if (time_after(jiffies, tmo)) {
+			dev_err(&client->dev,
+				"timeout waiting for initialisation\n");
+			break;
+		}
+
+		msleep(1);
+	}
+
+	lm8323_configure(lm);
+
+	/* If a true probe check the device */
+	if (lm8323_read_id(lm, data) != 0) {
+		dev_err(&client->dev, "device not found\n");
+		err = -ENODEV;
+		goto fail1;
+	}
+
+	for (i = 0; i < LM8323_NUM_PWMS; i++) {
+		err = init_pwm(lm, i + 1, &client->dev, pdata->pwm_names[i]);
+		if (err < 0)
+			goto fail2;
+	}
+
+	lm->kp_enabled = true;
+	err = device_create_file(&client->dev, &dev_attr_disable_kp);
+	if (err < 0)
+		goto fail2;
+
+	idev->name = pdata->name ? : "LM8323 keypad";
+	snprintf(lm->phys, sizeof(lm->phys),
+		 "%s/input-kp", dev_name(&client->dev));
+	idev->phys = lm->phys;
+
+	idev->evbit[0] = BIT(EV_KEY) | BIT(EV_MSC);
+	__set_bit(MSC_SCAN, idev->mscbit);
+	for (i = 0; i < LM8323_KEYMAP_SIZE; i++) {
+		__set_bit(pdata->keymap[i], idev->keybit);
+		lm->keymap[i] = pdata->keymap[i];
+	}
+	__clear_bit(KEY_RESERVED, idev->keybit);
+
+	if (pdata->repeat)
+		__set_bit(EV_REP, idev->evbit);
+
+	err = input_register_device(idev);
+	if (err) {
+		dev_dbg(&client->dev, "error registering input device\n");
+		goto fail3;
+	}
+
+	err = request_irq(client->irq, lm8323_irq,
+			  IRQF_TRIGGER_FALLING | IRQF_DISABLED,
+			  "lm8323", lm);
+	if (err) {
+		dev_err(&client->dev, "could not get IRQ %d\n", client->irq);
+		goto fail4;
+	}
+
+	device_init_wakeup(&client->dev, 1);
+	enable_irq_wake(client->irq);
+
+	return 0;
+
+fail4:
+	input_unregister_device(idev);
+	idev = NULL;
+fail3:
+	device_remove_file(&client->dev, &dev_attr_disable_kp);
+fail2:
+	while (--i >= 0)
+		if (lm->pwm[i].enabled)
+			led_classdev_unregister(&lm->pwm[i].cdev);
+fail1:
+	input_free_device(idev);
+	kfree(lm);
+	return err;
+}
+
+static int __devexit lm8323_remove(struct i2c_client *client)
+{
+	struct lm8323_chip *lm = i2c_get_clientdata(client);
+	int i;
+
+	disable_irq_wake(client->irq);
+	free_irq(client->irq, lm);
+	cancel_work_sync(&lm->work);
+
+	input_unregister_device(lm->idev);
+
+	device_remove_file(&lm->client->dev, &dev_attr_disable_kp);
+
+	for (i = 0; i < 3; i++)
+		if (lm->pwm[i].enabled)
+			led_classdev_unregister(&lm->pwm[i].cdev);
+
+	kfree(lm);
+
+	return 0;
+}
+
+#ifdef CONFIG_PM
+/*
+ * We don't need to explicitly suspend the chip, as it already switches off
+ * when there's no activity.
+ */
+static int lm8323_suspend(struct i2c_client *client, pm_message_t mesg)
+{
+	struct lm8323_chip *lm = i2c_get_clientdata(client);
+	int i;
+
+	set_irq_wake(client->irq, 0);
+	disable_irq(client->irq);
+
+	mutex_lock(&lm->lock);
+	lm->pm_suspend = true;
+	mutex_unlock(&lm->lock);
+
+	for (i = 0; i < 3; i++)
+		if (lm->pwm[i].enabled)
+			led_classdev_suspend(&lm->pwm[i].cdev);
+
+	return 0;
+}
+
+static int lm8323_resume(struct i2c_client *client)
+{
+	struct lm8323_chip *lm = i2c_get_clientdata(client);
+	int i;
+
+	mutex_lock(&lm->lock);
+	lm->pm_suspend = false;
+	mutex_unlock(&lm->lock);
+
+	for (i = 0; i < 3; i++)
+		if (lm->pwm[i].enabled)
+			led_classdev_resume(&lm->pwm[i].cdev);
+
+	enable_irq(client->irq);
+	set_irq_wake(client->irq, 1);
+
+	return 0;
+}
+#else
+#define lm8323_suspend	NULL
+#define lm8323_resume	NULL
+#endif
+
+static const struct i2c_device_id lm8323_id[] = {
+	{ "lm8323", 0 },
+	{ }
+};
+
+static struct i2c_driver lm8323_i2c_driver = {
+	.driver = {
+		.name	= "lm8323",
+	},
+	.probe		= lm8323_probe,
+	.remove		= __devexit_p(lm8323_remove),
+	.suspend	= lm8323_suspend,
+	.resume		= lm8323_resume,
+	.id_table	= lm8323_id,
+};
+MODULE_DEVICE_TABLE(i2c, lm8323_id);
+
+static int __init lm8323_init(void)
+{
+	return i2c_add_driver(&lm8323_i2c_driver);
+}
+module_init(lm8323_init);
+
+static void __exit lm8323_exit(void)
+{
+	i2c_del_driver(&lm8323_i2c_driver);
+}
+module_exit(lm8323_exit);
+
+MODULE_AUTHOR("Timo O. Karjalainen <timo.o.karjalainen@nokia.com>");
+MODULE_AUTHOR("Daniel Stone");
+MODULE_AUTHOR("Felipe Balbi <felipe.balbi@nokia.com>");
+MODULE_DESCRIPTION("LM8323 keypad driver");
+MODULE_LICENSE("GPL");
+
diff --git a/drivers/input/misc/Kconfig b/drivers/input/misc/Kconfig
index 06f46fc..1acfa3a 100644
--- a/drivers/input/misc/Kconfig
+++ b/drivers/input/misc/Kconfig
@@ -193,6 +193,16 @@
 	  To compile this driver as a module, choose M here: the module will be
 	  called cm109.
 
+config INPUT_TWL4030_PWRBUTTON
+	tristate "TWL4030 Power button Driver"
+	depends on TWL4030_CORE
+	help
+	  Say Y here if you want to enable power key reporting via the
+	  TWL4030 family of chips.
+
+	  To compile this driver as a module, choose M here. The module will
+	  be called twl4030_pwrbutton.
+
 config INPUT_UINPUT
 	tristate "User level driver support"
 	help
@@ -250,4 +260,13 @@
 	  To compile this driver as a module, choose M here: the
 	  module will be called rb532_button.
 
+config INPUT_DM355EVM
+	tristate "TI DaVinci DM355 EVM Keypad and IR Remote"
+	depends on MFD_DM355EVM_MSP
+	help
+	  Supports the pushbuttons and IR remote used with
+	  the DM355 EVM board.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called dm355evm_keys.
 endif
diff --git a/drivers/input/misc/Makefile b/drivers/input/misc/Makefile
index eb3f407..0d979fd 100644
--- a/drivers/input/misc/Makefile
+++ b/drivers/input/misc/Makefile
@@ -10,6 +10,7 @@
 obj-$(CONFIG_INPUT_ATLAS_BTNS)		+= atlas_btns.o
 obj-$(CONFIG_INPUT_CM109)		+= cm109.o
 obj-$(CONFIG_INPUT_COBALT_BTNS)		+= cobalt_btns.o
+obj-$(CONFIG_INPUT_DM355EVM)		+= dm355evm_keys.o
 obj-$(CONFIG_HP_SDC_RTC)		+= hp_sdc_rtc.o
 obj-$(CONFIG_INPUT_IXP4XX_BEEPER)	+= ixp4xx-beeper.o
 obj-$(CONFIG_INPUT_KEYSPAN_REMOTE)	+= keyspan_remote.o
@@ -21,6 +22,7 @@
 obj-$(CONFIG_INPUT_GPIO_ROTARY_ENCODER)	+= rotary_encoder.o
 obj-$(CONFIG_INPUT_SGI_BTNS)		+= sgi_btns.o
 obj-$(CONFIG_INPUT_SPARCSPKR)		+= sparcspkr.o
+obj-$(CONFIG_INPUT_TWL4030_PWRBUTTON)	+= twl4030-pwrbutton.o
 obj-$(CONFIG_INPUT_UINPUT)		+= uinput.o
 obj-$(CONFIG_INPUT_WISTRON_BTNS)	+= wistron_btns.o
 obj-$(CONFIG_INPUT_YEALINK)		+= yealink.o
diff --git a/drivers/input/misc/ati_remote2.c b/drivers/input/misc/ati_remote2.c
index 922c051..0501f0e 100644
--- a/drivers/input/misc/ati_remote2.c
+++ b/drivers/input/misc/ati_remote2.c
@@ -509,7 +509,7 @@
 
 	old_keycode = ar2->keycode[mode][index];
 	ar2->keycode[mode][index] = keycode;
-	set_bit(keycode, idev->keybit);
+	__set_bit(keycode, idev->keybit);
 
 	for (mode = 0; mode < ATI_REMOTE2_MODES; mode++) {
 		for (index = 0; index < ARRAY_SIZE(ati_remote2_key_table); index++) {
@@ -518,7 +518,7 @@
 		}
 	}
 
-	clear_bit(old_keycode, idev->keybit);
+	__clear_bit(old_keycode, idev->keybit);
 
 	return 0;
 }
@@ -543,7 +543,7 @@
 	for (mode = 0; mode < ATI_REMOTE2_MODES; mode++) {
 		for (index = 0; index < ARRAY_SIZE(ati_remote2_key_table); index++) {
 			ar2->keycode[mode][index] = ati_remote2_key_table[index].keycode;
-			set_bit(ar2->keycode[mode][index], idev->keybit);
+			__set_bit(ar2->keycode[mode][index], idev->keybit);
 		}
 	}
 
@@ -554,11 +554,11 @@
 	ar2->keycode[ATI_REMOTE2_AUX3][index] = KEY_PROG3;
 	ar2->keycode[ATI_REMOTE2_AUX4][index] = KEY_PROG4;
 	ar2->keycode[ATI_REMOTE2_PC][index] = KEY_PC;
-	set_bit(KEY_PROG1, idev->keybit);
-	set_bit(KEY_PROG2, idev->keybit);
-	set_bit(KEY_PROG3, idev->keybit);
-	set_bit(KEY_PROG4, idev->keybit);
-	set_bit(KEY_PC, idev->keybit);
+	__set_bit(KEY_PROG1, idev->keybit);
+	__set_bit(KEY_PROG2, idev->keybit);
+	__set_bit(KEY_PROG3, idev->keybit);
+	__set_bit(KEY_PROG4, idev->keybit);
+	__set_bit(KEY_PC, idev->keybit);
 
 	idev->rep[REP_DELAY]  = 250;
 	idev->rep[REP_PERIOD] = 33;
diff --git a/drivers/input/misc/dm355evm_keys.c b/drivers/input/misc/dm355evm_keys.c
new file mode 100644
index 0000000..a63315c
--- /dev/null
+++ b/drivers/input/misc/dm355evm_keys.c
@@ -0,0 +1,329 @@
+/*
+ * dm355evm_keys.c - support buttons and IR remote on DM355 EVM board
+ *
+ * Copyright (c) 2008 by David Brownell
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ */
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/input.h>
+#include <linux/platform_device.h>
+#include <linux/interrupt.h>
+
+#include <linux/i2c/dm355evm_msp.h>
+
+
+/*
+ * The MSP430 firmware on the DM355 EVM monitors on-board pushbuttons
+ * and an IR receptor used for the remote control.  When any key is
+ * pressed, or its autorepeat kicks in, an event is sent.  This driver
+ * read those events from the small (32 event) queue and reports them.
+ *
+ * Because we communicate with the MSP430 using I2C, and all I2C calls
+ * in Linux sleep, we need to cons up a kind of threaded IRQ handler
+ * using a work_struct.  The IRQ is active low, but we use it through
+ * the GPIO controller so we can trigger on falling edges.
+ *
+ * Note that physically there can only be one of these devices.
+ *
+ * This driver was tested with firmware revision A4.
+ */
+struct dm355evm_keys {
+	struct work_struct	work;
+	struct input_dev	*input;
+	struct device		*dev;
+	int			irq;
+};
+
+static irqreturn_t dm355evm_keys_irq(int irq, void *_keys)
+{
+	struct dm355evm_keys	*keys = _keys;
+
+	schedule_work(&keys->work);
+	return IRQ_HANDLED;
+}
+
+/* These initial keycodes can be remapped by dm355evm_setkeycode(). */
+static struct {
+	u16	event;
+	u16	keycode;
+} dm355evm_keys[] = {
+
+	/*
+	 * Pushbuttons on the EVM board ... note that the labels for these
+	 * are SW10/SW11/etc on the PC board.  The left/right orientation
+	 * comes only from the firmware's documentation, and presumes the
+	 * power connector is immediately in front of you and the IR sensor
+	 * is to the right.  (That is, rotate the board counter-clockwise
+	 * by 90 degrees from the SW10/etc and "DM355 EVM" labels.)
+	 */
+	{ 0x00d8, KEY_OK, },		/* SW12 */
+	{ 0x00b8, KEY_UP, },		/* SW13 */
+	{ 0x00e8, KEY_DOWN, },		/* SW11 */
+	{ 0x0078, KEY_LEFT, },		/* SW14 */
+	{ 0x00f0, KEY_RIGHT, },		/* SW10 */
+
+	/*
+	 * IR buttons ... codes assigned to match the universal remote
+	 * provided with the EVM (Philips PM4S) using DVD code 0020.
+	 *
+	 * These event codes match firmware documentation, but other
+	 * remote controls could easily send more RC5-encoded events.
+	 * The PM4S manual was used in several cases to help select
+	 * a keycode reflecting the intended usage.
+	 *
+	 * RC5 codes are 14 bits, with two start bits (0x3 prefix)
+	 * and a toggle bit (masked out below).
+	 */
+	{ 0x300c, KEY_POWER, },		/* NOTE: docs omit this */
+	{ 0x3000, KEY_NUMERIC_0, },
+	{ 0x3001, KEY_NUMERIC_1, },
+	{ 0x3002, KEY_NUMERIC_2, },
+	{ 0x3003, KEY_NUMERIC_3, },
+	{ 0x3004, KEY_NUMERIC_4, },
+	{ 0x3005, KEY_NUMERIC_5, },
+	{ 0x3006, KEY_NUMERIC_6, },
+	{ 0x3007, KEY_NUMERIC_7, },
+	{ 0x3008, KEY_NUMERIC_8, },
+	{ 0x3009, KEY_NUMERIC_9, },
+	{ 0x3022, KEY_ENTER, },
+	{ 0x30ec, KEY_MODE, },		/* "tv/vcr/..." */
+	{ 0x300f, KEY_SELECT, },	/* "info" */
+	{ 0x3020, KEY_CHANNELUP, },	/* "up" */
+	{ 0x302e, KEY_MENU, },		/* "in/out" */
+	{ 0x3011, KEY_VOLUMEDOWN, },	/* "left" */
+	{ 0x300d, KEY_MUTE, },		/* "ok" */
+	{ 0x3010, KEY_VOLUMEUP, },	/* "right" */
+	{ 0x301e, KEY_SUBTITLE, },	/* "cc" */
+	{ 0x3021, KEY_CHANNELDOWN, },	/* "down" */
+	{ 0x3022, KEY_PREVIOUS, },
+	{ 0x3026, KEY_SLEEP, },
+	{ 0x3172, KEY_REWIND, },	/* NOTE: docs wrongly say 0x30ca */
+	{ 0x3175, KEY_PLAY, },
+	{ 0x3174, KEY_FASTFORWARD, },
+	{ 0x3177, KEY_RECORD, },
+	{ 0x3176, KEY_STOP, },
+	{ 0x3169, KEY_PAUSE, },
+};
+
+static void dm355evm_keys_work(struct work_struct *work)
+{
+	struct dm355evm_keys	*keys;
+	int			status;
+
+	keys = container_of(work, struct dm355evm_keys, work);
+
+	/* For simplicity we ignore INPUT_COUNT and just read
+	 * events until we get the "queue empty" indicator.
+	 * Reading INPUT_LOW decrements the count.
+	 */
+	for (;;) {
+		static u16	last_event;
+		u16		event;
+		int		keycode;
+		int		i;
+
+		status = dm355evm_msp_read(DM355EVM_MSP_INPUT_HIGH);
+		if (status < 0) {
+			dev_dbg(keys->dev, "input high err %d\n",
+					status);
+			break;
+		}
+		event = status << 8;
+
+		status = dm355evm_msp_read(DM355EVM_MSP_INPUT_LOW);
+		if (status < 0) {
+			dev_dbg(keys->dev, "input low err %d\n",
+					status);
+			break;
+		}
+		event |= status;
+		if (event == 0xdead)
+			break;
+
+		/* Press and release a button:  two events, same code.
+		 * Press and hold (autorepeat), then release: N events
+		 * (N > 2), same code.  For RC5 buttons the toggle bits
+		 * distinguish (for example) "1-autorepeat" from "1 1";
+		 * but PCB buttons don't support that bit.
+		 *
+		 * So we must synthesize release events.  We do that by
+		 * mapping events to a press/release event pair; then
+		 * to avoid adding extra events, skip the second event
+		 * of each pair.
+		 */
+		if (event == last_event) {
+			last_event = 0;
+			continue;
+		}
+		last_event = event;
+
+		/* ignore the RC5 toggle bit */
+		event &= ~0x0800;
+
+		/* find the key, or leave it as unknown */
+		keycode = KEY_UNKNOWN;
+		for (i = 0; i < ARRAY_SIZE(dm355evm_keys); i++) {
+			if (dm355evm_keys[i].event != event)
+				continue;
+			keycode = dm355evm_keys[i].keycode;
+			break;
+		}
+		dev_dbg(keys->dev,
+			"input event 0x%04x--> keycode %d\n",
+			event, keycode);
+
+		/* report press + release */
+		input_report_key(keys->input, keycode, 1);
+		input_sync(keys->input);
+		input_report_key(keys->input, keycode, 0);
+		input_sync(keys->input);
+	}
+}
+
+static int dm355evm_setkeycode(struct input_dev *dev, int index, int keycode)
+{
+	u16		old_keycode;
+	unsigned	i;
+
+	if (((unsigned)index) >= ARRAY_SIZE(dm355evm_keys))
+		return -EINVAL;
+
+	old_keycode = dm355evm_keys[index].keycode;
+	dm355evm_keys[index].keycode = keycode;
+	set_bit(keycode, dev->keybit);
+
+	for (i = 0; i < ARRAY_SIZE(dm355evm_keys); i++) {
+		if (dm355evm_keys[index].keycode == old_keycode)
+			goto done;
+	}
+	clear_bit(old_keycode, dev->keybit);
+done:
+	return 0;
+}
+
+static int dm355evm_getkeycode(struct input_dev *dev, int index, int *keycode)
+{
+	if (((unsigned)index) >= ARRAY_SIZE(dm355evm_keys))
+		return -EINVAL;
+
+	return dm355evm_keys[index].keycode;
+}
+
+/*----------------------------------------------------------------------*/
+
+static int __devinit dm355evm_keys_probe(struct platform_device *pdev)
+{
+	struct dm355evm_keys	*keys;
+	struct input_dev	*input;
+	int			status;
+	int			i;
+
+	/* allocate instance struct and input dev */
+	keys = kzalloc(sizeof *keys, GFP_KERNEL);
+	input = input_allocate_device();
+	if (!keys || !input) {
+		status = -ENOMEM;
+		goto fail1;
+	}
+
+	keys->dev = &pdev->dev;
+	keys->input = input;
+	INIT_WORK(&keys->work, dm355evm_keys_work);
+
+	/* set up "threaded IRQ handler" */
+	status = platform_get_irq(pdev, 0);
+	if (status < 0)
+		goto fail1;
+	keys->irq = status;
+
+	input_set_drvdata(input, keys);
+
+	input->name = "DM355 EVM Controls";
+	input->phys = "dm355evm/input0";
+	input->dev.parent = &pdev->dev;
+
+	input->id.bustype = BUS_I2C;
+	input->id.product = 0x0355;
+	input->id.version = dm355evm_msp_read(DM355EVM_MSP_FIRMREV);
+
+	input->evbit[0] = BIT(EV_KEY);
+	for (i = 0; i < ARRAY_SIZE(dm355evm_keys); i++)
+		__set_bit(dm355evm_keys[i].keycode, input->keybit);
+
+	input->setkeycode = dm355evm_setkeycode;
+	input->getkeycode = dm355evm_getkeycode;
+
+	/* REVISIT:  flush the event queue? */
+
+	status = request_irq(keys->irq, dm355evm_keys_irq,
+			     IRQF_TRIGGER_FALLING,
+			     dev_name(&pdev->dev), keys);
+	if (status < 0)
+		goto fail1;
+
+	/* register */
+	status = input_register_device(input);
+	if (status < 0)
+		goto fail2;
+
+	platform_set_drvdata(pdev, keys);
+
+	return 0;
+
+fail2:
+	free_irq(keys->irq, keys);
+fail1:
+	input_free_device(input);
+	kfree(keys);
+	dev_err(&pdev->dev, "can't register, err %d\n", status);
+
+	return status;
+}
+
+static int __devexit dm355evm_keys_remove(struct platform_device *pdev)
+{
+	struct dm355evm_keys	*keys = platform_get_drvdata(pdev);
+
+	free_irq(keys->irq, keys);
+	input_unregister_device(keys->input);
+	kfree(keys);
+
+	return 0;
+}
+
+/* REVISIT:  add suspend/resume when DaVinci supports it.  The IRQ should
+ * be able to wake up the system.  When device_may_wakeup(&pdev->dev), call
+ * enable_irq_wake() on suspend, and disable_irq_wake() on resume.
+ */
+
+/*
+ * I2C is used to talk to the MSP430, but this platform device is
+ * exposed by an MFD driver that manages I2C communications.
+ */
+static struct platform_driver dm355evm_keys_driver = {
+	.probe		= dm355evm_keys_probe,
+	.remove		= __devexit_p(dm355evm_keys_remove),
+	.driver		= {
+		.owner	= THIS_MODULE,
+		.name	= "dm355evm_keys",
+	},
+};
+
+static int __init dm355evm_keys_init(void)
+{
+	return platform_driver_register(&dm355evm_keys_driver);
+}
+module_init(dm355evm_keys_init);
+
+static void __exit dm355evm_keys_exit(void)
+{
+	platform_driver_unregister(&dm355evm_keys_driver);
+}
+module_exit(dm355evm_keys_exit);
+
+MODULE_LICENSE("GPL");
diff --git a/drivers/input/misc/rotary_encoder.c b/drivers/input/misc/rotary_encoder.c
index 5bb3ab5..c806fbf 100644
--- a/drivers/input/misc/rotary_encoder.c
+++ b/drivers/input/misc/rotary_encoder.c
@@ -26,13 +26,17 @@
 #define DRV_NAME "rotary-encoder"
 
 struct rotary_encoder {
-	unsigned int irq_a;
-	unsigned int irq_b;
-	unsigned int pos;
-	unsigned int armed;
-	unsigned int dir;
 	struct input_dev *input;
 	struct rotary_encoder_platform_data *pdata;
+
+	unsigned int axis;
+	unsigned int pos;
+
+	unsigned int irq_a;
+	unsigned int irq_b;
+
+	bool armed;
+	unsigned char dir;	/* 0 - clockwise, 1 - CCW */
 };
 
 static irqreturn_t rotary_encoder_irq(int irq, void *dev_id)
@@ -53,21 +57,32 @@
 		if (!encoder->armed)
 			break;
 
-		if (encoder->dir) {
-			/* turning counter-clockwise */
-			encoder->pos += pdata->steps;
-			encoder->pos--;
-			encoder->pos %= pdata->steps;
+		if (pdata->relative_axis) {
+			input_report_rel(encoder->input, pdata->axis,
+					 encoder->dir ? -1 : 1);
 		} else {
-			/* turning clockwise */
-			encoder->pos++;
-			encoder->pos %= pdata->steps;
-		}
+			unsigned int pos = encoder->pos;
 
-		input_report_abs(encoder->input, pdata->axis, encoder->pos);
+			if (encoder->dir) {
+				/* turning counter-clockwise */
+				if (pdata->rollover)
+					pos += pdata->steps;
+				if (pos)
+					pos--;
+			} else {
+				/* turning clockwise */
+				if (pdata->rollover || pos < pdata->steps)
+					pos++;
+			}
+			if (pdata->rollover)
+				pos %= pdata->steps;
+			encoder->pos = pos;
+			input_report_abs(encoder->input, pdata->axis,
+					 encoder->pos);
+		}
 		input_sync(encoder->input);
 
-		encoder->armed = 0;
+		encoder->armed = false;
 		break;
 
 	case 0x1:
@@ -77,7 +92,7 @@
 		break;
 
 	case 0x3:
-		encoder->armed = 1;
+		encoder->armed = true;
 		break;
 	}
 
@@ -113,9 +128,15 @@
 	input->name = pdev->name;
 	input->id.bustype = BUS_HOST;
 	input->dev.parent = &pdev->dev;
-	input->evbit[0] = BIT_MASK(EV_ABS);
-	input_set_abs_params(encoder->input,
-			     pdata->axis, 0, pdata->steps, 0, 1);
+
+	if (pdata->relative_axis) {
+		input->evbit[0] = BIT_MASK(EV_REL);
+		input->relbit[0] = BIT_MASK(pdata->axis);
+	} else {
+		input->evbit[0] = BIT_MASK(EV_ABS);
+		input_set_abs_params(encoder->input,
+				     pdata->axis, 0, pdata->steps, 0, 1);
+	}
 
 	err = input_register_device(input);
 	if (err) {
diff --git a/drivers/input/misc/twl4030-pwrbutton.c b/drivers/input/misc/twl4030-pwrbutton.c
new file mode 100644
index 0000000..f5fc997
--- /dev/null
+++ b/drivers/input/misc/twl4030-pwrbutton.c
@@ -0,0 +1,145 @@
+/**
+ * twl4030-pwrbutton.c - TWL4030 Power Button Input Driver
+ *
+ * Copyright (C) 2008-2009 Nokia Corporation
+ *
+ * Written by Peter De Schrijver <peter.de-schrijver@nokia.com>
+ * Several fixes by Felipe Balbi <felipe.balbi@nokia.com>
+ *
+ * This file is subject to the terms and conditions of the GNU General
+ * Public License. See the file "COPYING" in the main directory of this
+ * archive for more details.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/kernel.h>
+#include <linux/errno.h>
+#include <linux/input.h>
+#include <linux/interrupt.h>
+#include <linux/platform_device.h>
+#include <linux/i2c/twl4030.h>
+
+#define PWR_PWRON_IRQ (1 << 0)
+
+#define STS_HW_CONDITIONS 0xf
+
+static irqreturn_t powerbutton_irq(int irq, void *_pwr)
+{
+	struct input_dev *pwr = _pwr;
+	int err;
+	u8 value;
+
+#ifdef CONFIG_LOCKDEP
+	/* WORKAROUND for lockdep forcing IRQF_DISABLED on us, which
+	 * we don't want and can't tolerate since this is a threaded
+	 * IRQ and can sleep due to the i2c reads it has to issue.
+	 * Although it might be friendlier not to borrow this thread
+	 * context...
+	 */
+	local_irq_enable();
+#endif
+
+	err = twl4030_i2c_read_u8(TWL4030_MODULE_PM_MASTER, &value,
+				  STS_HW_CONDITIONS);
+	if (!err)  {
+		input_report_key(pwr, KEY_POWER, value & PWR_PWRON_IRQ);
+		input_sync(pwr);
+	} else {
+		dev_err(pwr->dev.parent, "twl4030: i2c error %d while reading"
+			" TWL4030 PM_MASTER STS_HW_CONDITIONS register\n", err);
+	}
+
+	return IRQ_HANDLED;
+}
+
+static int __devinit twl4030_pwrbutton_probe(struct platform_device *pdev)
+{
+	struct input_dev *pwr;
+	int irq = platform_get_irq(pdev, 0);
+	int err;
+
+	pwr = input_allocate_device();
+	if (!pwr) {
+		dev_dbg(&pdev->dev, "Can't allocate power button\n");
+		return -ENOMEM;
+	}
+
+	pwr->evbit[0] = BIT_MASK(EV_KEY);
+	pwr->keybit[BIT_WORD(KEY_POWER)] = BIT_MASK(KEY_POWER);
+	pwr->name = "twl4030_pwrbutton";
+	pwr->phys = "twl4030_pwrbutton/input0";
+	pwr->dev.parent = &pdev->dev;
+
+	err = request_irq(irq, powerbutton_irq,
+			IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING,
+			"twl4030_pwrbutton", pwr);
+	if (err < 0) {
+		dev_dbg(&pdev->dev, "Can't get IRQ for pwrbutton: %d\n", err);
+		goto free_input_dev;
+	}
+
+	err = input_register_device(pwr);
+	if (err) {
+		dev_dbg(&pdev->dev, "Can't register power button: %d\n", err);
+		goto free_irq;
+	}
+
+	platform_set_drvdata(pdev, pwr);
+
+	return 0;
+
+free_irq:
+	free_irq(irq, NULL);
+free_input_dev:
+	input_free_device(pwr);
+	return err;
+}
+
+static int __devexit twl4030_pwrbutton_remove(struct platform_device *pdev)
+{
+	struct input_dev *pwr = platform_get_drvdata(pdev);
+	int irq = platform_get_irq(pdev, 0);
+
+	free_irq(irq, pwr);
+	input_unregister_device(pwr);
+
+	return 0;
+}
+
+struct platform_driver twl4030_pwrbutton_driver = {
+	.probe		= twl4030_pwrbutton_probe,
+	.remove		= __devexit_p(twl4030_pwrbutton_remove),
+	.driver		= {
+		.name	= "twl4030_pwrbutton",
+		.owner	= THIS_MODULE,
+	},
+};
+
+static int __init twl4030_pwrbutton_init(void)
+{
+	return platform_driver_register(&twl4030_pwrbutton_driver);
+}
+module_init(twl4030_pwrbutton_init);
+
+static void __exit twl4030_pwrbutton_exit(void)
+{
+	platform_driver_unregister(&twl4030_pwrbutton_driver);
+}
+module_exit(twl4030_pwrbutton_exit);
+
+MODULE_ALIAS("platform:twl4030_pwrbutton");
+MODULE_DESCRIPTION("Triton2 Power Button");
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Peter De Schrijver <peter.de-schrijver@nokia.com>");
+MODULE_AUTHOR("Felipe Balbi <felipe.balbi@nokia.com>");
+
diff --git a/drivers/input/misc/uinput.c b/drivers/input/misc/uinput.c
index 46b7cae..c5a49ab 100644
--- a/drivers/input/misc/uinput.c
+++ b/drivers/input/misc/uinput.c
@@ -54,27 +54,28 @@
 	return 0;
 }
 
+/* Atomically allocate an ID for the given request. Returns 0 on success. */
 static int uinput_request_alloc_id(struct uinput_device *udev, struct uinput_request *request)
 {
-	/* Atomically allocate an ID for the given request. Returns 0 on success. */
 	int id;
 	int err = -1;
 
 	spin_lock(&udev->requests_lock);
 
-	for (id = 0; id < UINPUT_NUM_REQUESTS; id++)
+	for (id = 0; id < UINPUT_NUM_REQUESTS; id++) {
 		if (!udev->requests[id]) {
 			request->id = id;
 			udev->requests[id] = request;
 			err = 0;
 			break;
 		}
+	}
 
 	spin_unlock(&udev->requests_lock);
 	return err;
 }
 
-static struct uinput_request* uinput_request_find(struct uinput_device *udev, int id)
+static struct uinput_request *uinput_request_find(struct uinput_device *udev, int id)
 {
 	/* Find an input request, by ID. Returns NULL if the ID isn't valid. */
 	if (id >= UINPUT_NUM_REQUESTS || id < 0)
@@ -99,14 +100,51 @@
 	complete(&request->done);
 }
 
-static int uinput_request_submit(struct input_dev *dev, struct uinput_request *request)
+static int uinput_request_submit(struct uinput_device *udev, struct uinput_request *request)
 {
-	/* Tell our userspace app about this new request by queueing an input event */
-	uinput_dev_event(dev, EV_UINPUT, request->code, request->id);
+	int retval;
 
-	/* Wait for the request to complete */
-	wait_for_completion(&request->done);
-	return request->retval;
+	retval = uinput_request_reserve_slot(udev, request);
+	if (retval)
+		return retval;
+
+	retval = mutex_lock_interruptible(&udev->mutex);
+	if (retval)
+		return retval;
+
+	if (udev->state != UIST_CREATED) {
+		retval = -ENODEV;
+		goto out;
+	}
+
+	/* Tell our userspace app about this new request by queueing an input event */
+	uinput_dev_event(udev->dev, EV_UINPUT, request->code, request->id);
+
+ out:
+	mutex_unlock(&udev->mutex);
+	return retval;
+}
+
+/*
+ * Fail all ouitstanding requests so handlers don't wait for the userspace
+ * to finish processing them.
+ */
+static void uinput_flush_requests(struct uinput_device *udev)
+{
+	struct uinput_request *request;
+	int i;
+
+	spin_lock(&udev->requests_lock);
+
+	for (i = 0; i < UINPUT_NUM_REQUESTS; i++) {
+		request = udev->requests[i];
+		if (request) {
+			request->retval = -ENODEV;
+			uinput_request_done(udev, request);
+		}
+	}
+
+	spin_unlock(&udev->requests_lock);
 }
 
 static void uinput_dev_set_gain(struct input_dev *dev, u16 gain)
@@ -126,6 +164,7 @@
 
 static int uinput_dev_upload_effect(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old)
 {
+	struct uinput_device *udev = input_get_drvdata(dev);
 	struct uinput_request request;
 	int retval;
 
@@ -146,15 +185,18 @@
 	request.u.upload.effect = effect;
 	request.u.upload.old = old;
 
-	retval = uinput_request_reserve_slot(input_get_drvdata(dev), &request);
-	if (!retval)
-		retval = uinput_request_submit(dev, &request);
+	retval = uinput_request_submit(udev, &request);
+	if (!retval) {
+		wait_for_completion(&request.done);
+		retval = request.retval;
+	}
 
 	return retval;
 }
 
 static int uinput_dev_erase_effect(struct input_dev *dev, int effect_id)
 {
+	struct uinput_device *udev = input_get_drvdata(dev);
 	struct uinput_request request;
 	int retval;
 
@@ -166,9 +208,11 @@
 	request.code = UI_FF_ERASE;
 	request.u.effect_id = effect_id;
 
-	retval = uinput_request_reserve_slot(input_get_drvdata(dev), &request);
-	if (!retval)
-		retval = uinput_request_submit(dev, &request);
+	retval = uinput_request_submit(udev, &request);
+	if (!retval) {
+		wait_for_completion(&request.done);
+		retval = request.retval;
+	}
 
 	return retval;
 }
@@ -176,20 +220,24 @@
 static void uinput_destroy_device(struct uinput_device *udev)
 {
 	const char *name, *phys;
+	struct input_dev *dev = udev->dev;
+	enum uinput_state old_state = udev->state;
 
-	if (udev->dev) {
-		name = udev->dev->name;
-		phys = udev->dev->phys;
-		if (udev->state == UIST_CREATED)
-			input_unregister_device(udev->dev);
-		else
-			input_free_device(udev->dev);
+	udev->state = UIST_NEW_DEVICE;
+
+	if (dev) {
+		name = dev->name;
+		phys = dev->phys;
+		if (old_state == UIST_CREATED) {
+			uinput_flush_requests(udev);
+			input_unregister_device(dev);
+		} else {
+			input_free_device(dev);
+		}
 		kfree(name);
 		kfree(phys);
 		udev->dev = NULL;
 	}
-
-	udev->state = UIST_NEW_DEVICE;
 }
 
 static int uinput_create_device(struct uinput_device *udev)
diff --git a/drivers/input/mouse/Kconfig b/drivers/input/mouse/Kconfig
index c66cc3d..8a2c5b1 100644
--- a/drivers/input/mouse/Kconfig
+++ b/drivers/input/mouse/Kconfig
@@ -303,4 +303,22 @@
 	  To compile this driver as a module choose M here: the module will be
 	  called maplemouse.
 
+config MOUSE_SYNAPTICS_I2C
+	tristate "Synaptics I2C Touchpad support"
+	depends on I2C
+	help
+	  This driver supports Synaptics I2C touchpad controller on eXeda
+	  mobile device.
+	  The device will not work the synaptics X11 driver because
+	  (i) it  reports only relative coordinates and has no capabilities
+	  to report absolute coordinates
+	  (ii) the eXeda device itself uses Xfbdev as X Server and it does
+	  not allow using xf86-input-* drivers.
+
+	  Say y here if you have eXeda device and want to use a Synaptics
+	  I2C Touchpad.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called synaptics_i2c.
+
 endif
diff --git a/drivers/input/mouse/Makefile b/drivers/input/mouse/Makefile
index 4721894..010f265 100644
--- a/drivers/input/mouse/Makefile
+++ b/drivers/input/mouse/Makefile
@@ -18,6 +18,7 @@
 obj-$(CONFIG_MOUSE_PXA930_TRKBALL)	+= pxa930_trkball.o
 obj-$(CONFIG_MOUSE_RISCPC)		+= rpcmouse.o
 obj-$(CONFIG_MOUSE_SERIAL)		+= sermouse.o
+obj-$(CONFIG_MOUSE_SYNAPTICS_I2C)	+= synaptics_i2c.o
 obj-$(CONFIG_MOUSE_VSXXXAA)		+= vsxxxaa.o
 
 psmouse-objs := psmouse-base.o synaptics.o
diff --git a/drivers/input/mouse/alps.c b/drivers/input/mouse/alps.c
index daecc75..5547e24 100644
--- a/drivers/input/mouse/alps.c
+++ b/drivers/input/mouse/alps.c
@@ -38,25 +38,25 @@
 
 static const struct alps_model_info alps_model_data[] = {
 	{ { 0x32, 0x02, 0x14 },	0xf8, 0xf8, ALPS_PASS | ALPS_DUALPOINT }, /* Toshiba Salellite Pro M10 */
-	{ { 0x33, 0x02, 0x0a },	0x88, 0xf8, ALPS_OLDPROTO },		/* UMAX-530T */
+	{ { 0x33, 0x02, 0x0a },	0x88, 0xf8, ALPS_OLDPROTO },		  /* UMAX-530T */
 	{ { 0x53, 0x02, 0x0a },	0xf8, 0xf8, 0 },
 	{ { 0x53, 0x02, 0x14 },	0xf8, 0xf8, 0 },
-	{ { 0x60, 0x03, 0xc8 }, 0xf8, 0xf8, 0 },			/* HP ze1115 */
+	{ { 0x60, 0x03, 0xc8 }, 0xf8, 0xf8, 0 },			  /* HP ze1115 */
 	{ { 0x63, 0x02, 0x0a },	0xf8, 0xf8, 0 },
 	{ { 0x63, 0x02, 0x14 },	0xf8, 0xf8, 0 },
-	{ { 0x63, 0x02, 0x28 },	0xf8, 0xf8, ALPS_FW_BK_2 },		/* Fujitsu Siemens S6010 */
-	{ { 0x63, 0x02, 0x3c },	0x8f, 0x8f, ALPS_WHEEL },		/* Toshiba Satellite S2400-103 */
-	{ { 0x63, 0x02, 0x50 },	0xef, 0xef, ALPS_FW_BK_1 },		/* NEC Versa L320 */
+	{ { 0x63, 0x02, 0x28 },	0xf8, 0xf8, ALPS_FW_BK_2 },		  /* Fujitsu Siemens S6010 */
+	{ { 0x63, 0x02, 0x3c },	0x8f, 0x8f, ALPS_WHEEL },		  /* Toshiba Satellite S2400-103 */
+	{ { 0x63, 0x02, 0x50 },	0xef, 0xef, ALPS_FW_BK_1 },		  /* NEC Versa L320 */
 	{ { 0x63, 0x02, 0x64 },	0xf8, 0xf8, 0 },
-	{ { 0x63, 0x03, 0xc8 }, 0xf8, 0xf8, ALPS_PASS },		/* Dell Latitude D800 */
-	{ { 0x73, 0x00, 0x0a },	0xf8, 0xf8, ALPS_DUALPOINT },		/* ThinkPad R61 8918-5QG */
+	{ { 0x63, 0x03, 0xc8 }, 0xf8, 0xf8, ALPS_PASS | ALPS_DUALPOINT }, /* Dell Latitude D800 */
+	{ { 0x73, 0x00, 0x0a },	0xf8, 0xf8, ALPS_DUALPOINT },		  /* ThinkPad R61 8918-5QG */
 	{ { 0x73, 0x02, 0x0a },	0xf8, 0xf8, 0 },
-	{ { 0x73, 0x02, 0x14 },	0xf8, 0xf8, ALPS_FW_BK_2 },		/* Ahtec Laptop */
+	{ { 0x73, 0x02, 0x14 },	0xf8, 0xf8, ALPS_FW_BK_2 },		  /* Ahtec Laptop */
 	{ { 0x20, 0x02, 0x0e },	0xf8, 0xf8, ALPS_PASS | ALPS_DUALPOINT }, /* XXX */
 	{ { 0x22, 0x02, 0x0a },	0xf8, 0xf8, ALPS_PASS | ALPS_DUALPOINT },
 	{ { 0x22, 0x02, 0x14 }, 0xff, 0xff, ALPS_PASS | ALPS_DUALPOINT }, /* Dell Latitude D600 */
 	{ { 0x62, 0x02, 0x14 }, 0xcf, 0xcf, ALPS_PASS | ALPS_DUALPOINT }, /* Dell Latitude E6500 */
-	{ { 0x73, 0x02, 0x50 }, 0xcf, 0xcf, ALPS_FW_BK_1 } /* Dell Vostro 1400 */
+	{ { 0x73, 0x02, 0x50 }, 0xcf, 0xcf, ALPS_FW_BK_1 },		  /* Dell Vostro 1400 */
 };
 
 /*
@@ -132,18 +132,23 @@
 	ges = packet[2] & 1;
 	fin = packet[2] & 2;
 
-	input_report_key(dev, BTN_LEFT, left);
-	input_report_key(dev, BTN_RIGHT, right);
-	input_report_key(dev, BTN_MIDDLE, middle);
-
 	if ((priv->i->flags & ALPS_DUALPOINT) && z == 127) {
 		input_report_rel(dev2, REL_X,  (x > 383 ? (x - 768) : x));
 		input_report_rel(dev2, REL_Y, -(y > 255 ? (y - 512) : y));
+
+		input_report_key(dev2, BTN_LEFT, left);
+		input_report_key(dev2, BTN_RIGHT, right);
+		input_report_key(dev2, BTN_MIDDLE, middle);
+
 		input_sync(dev);
 		input_sync(dev2);
 		return;
 	}
 
+	input_report_key(dev, BTN_LEFT, left);
+	input_report_key(dev, BTN_RIGHT, right);
+	input_report_key(dev, BTN_MIDDLE, middle);
+
 	/* Convert hardware tap to a reasonable Z value */
 	if (ges && !fin) z = 40;
 
diff --git a/drivers/input/mouse/appletouch.c b/drivers/input/mouse/appletouch.c
index e0140fd..908b5b4 100644
--- a/drivers/input/mouse/appletouch.c
+++ b/drivers/input/mouse/appletouch.c
@@ -361,7 +361,7 @@
 		    (!is_increasing && xy_sensors[i - 1] < xy_sensors[i])) {
 			(*fingers)++;
 			is_increasing = 1;
-		} else if (i > 0 && xy_sensors[i - 1] >= xy_sensors[i]) {
+		} else if (i > 0 && (xy_sensors[i - 1] - xy_sensors[i] > threshold)) {
 			is_increasing = 0;
 		}
 
diff --git a/drivers/input/mouse/lifebook.c b/drivers/input/mouse/lifebook.c
index 15ac320..dcd4236 100644
--- a/drivers/input/mouse/lifebook.c
+++ b/drivers/input/mouse/lifebook.c
@@ -159,21 +159,22 @@
 		if (!dev2)
 			printk(KERN_WARNING "lifebook.c: got relative packet "
 				"but no relative device set up\n");
-	} else if (lifebook_use_6byte_proto) {
-		input_report_abs(dev1, ABS_X,
-				 ((packet[1] & 0x3f) << 6) | (packet[2] & 0x3f));
-		input_report_abs(dev1, ABS_Y,
-				 4096 - (((packet[4] & 0x3f) << 6) | (packet[5] & 0x3f)));
 	} else {
-		input_report_abs(dev1, ABS_X,
-				 (packet[1] | ((packet[0] & 0x30) << 4)));
-		input_report_abs(dev1, ABS_Y,
-				 1024 - (packet[2] | ((packet[0] & 0xC0) << 2)));
+		if (lifebook_use_6byte_proto) {
+			input_report_abs(dev1, ABS_X,
+				((packet[1] & 0x3f) << 6) | (packet[2] & 0x3f));
+			input_report_abs(dev1, ABS_Y,
+				4096 - (((packet[4] & 0x3f) << 6) | (packet[5] & 0x3f)));
+		} else {
+			input_report_abs(dev1, ABS_X,
+				(packet[1] | ((packet[0] & 0x30) << 4)));
+			input_report_abs(dev1, ABS_Y,
+				1024 - (packet[2] | ((packet[0] & 0xC0) << 2)));
+		}
+		input_report_key(dev1, BTN_TOUCH, packet[0] & 0x04);
+		input_sync(dev1);
 	}
 
-	input_report_key(dev1, BTN_TOUCH, packet[0] & 0x04);
-	input_sync(dev1);
-
 	if (dev2) {
 		if (relative_packet) {
 			input_report_rel(dev2, REL_X,
diff --git a/drivers/input/mouse/psmouse-base.c b/drivers/input/mouse/psmouse-base.c
index f8f86de..b407b35 100644
--- a/drivers/input/mouse/psmouse-base.c
+++ b/drivers/input/mouse/psmouse-base.c
@@ -327,7 +327,9 @@
 			goto out;
 		}
 
-		if (psmouse->packet[1] == PSMOUSE_RET_ID) {
+		if (psmouse->packet[1] == PSMOUSE_RET_ID ||
+		    (psmouse->type == PSMOUSE_HGPK &&
+		     psmouse->packet[1] == PSMOUSE_RET_BAT)) {
 			__psmouse_set_state(psmouse, PSMOUSE_IGNORE);
 			serio_reconnect(serio);
 			goto out;
diff --git a/drivers/input/mouse/synaptics.c b/drivers/input/mouse/synaptics.c
index f3e4f7b..19984bf 100644
--- a/drivers/input/mouse/synaptics.c
+++ b/drivers/input/mouse/synaptics.c
@@ -180,6 +180,29 @@
 	return -1;
 }
 
+/*
+ * Read touchpad resolution
+ * Resolution is left zero if touchpad does not support the query
+ */
+static int synaptics_resolution(struct psmouse *psmouse)
+{
+	struct synaptics_data *priv = psmouse->private;
+	unsigned char res[3];
+
+	if (SYN_ID_MAJOR(priv->identity) < 4)
+		return 0;
+
+	if (synaptics_send_cmd(psmouse, SYN_QUE_RESOLUTION, res))
+		return 0;
+
+	if ((res[0] != 0) && (res[1] & 0x80) && (res[2] != 0)) {
+		priv->x_res = res[0]; /* x resolution in units/mm */
+		priv->y_res = res[2]; /* y resolution in units/mm */
+	}
+
+	return 0;
+}
+
 static int synaptics_query_hardware(struct psmouse *psmouse)
 {
 	if (synaptics_identify(psmouse))
@@ -188,6 +211,8 @@
 		return -1;
 	if (synaptics_capability(psmouse))
 		return -1;
+	if (synaptics_resolution(psmouse))
+		return -1;
 
 	return 0;
 }
@@ -563,6 +588,9 @@
 	clear_bit(EV_REL, dev->evbit);
 	clear_bit(REL_X, dev->relbit);
 	clear_bit(REL_Y, dev->relbit);
+
+	dev->absres[ABS_X] = priv->x_res;
+	dev->absres[ABS_Y] = priv->y_res;
 }
 
 static void synaptics_disconnect(struct psmouse *psmouse)
diff --git a/drivers/input/mouse/synaptics.h b/drivers/input/mouse/synaptics.h
index 02aa4cf..3023821 100644
--- a/drivers/input/mouse/synaptics.h
+++ b/drivers/input/mouse/synaptics.h
@@ -97,6 +97,8 @@
 	unsigned long int capabilities;		/* Capabilities */
 	unsigned long int ext_cap;		/* Extended Capabilities */
 	unsigned long int identity;		/* Identification */
+	int x_res;				/* X resolution in units/mm */
+	int y_res;				/* Y resolution in units/mm */
 
 	unsigned char pkt_type;			/* packet type - old, new, etc */
 	unsigned char mode;			/* current mode byte */
diff --git a/drivers/input/mouse/synaptics_i2c.c b/drivers/input/mouse/synaptics_i2c.c
new file mode 100644
index 0000000..eac9fdd
--- /dev/null
+++ b/drivers/input/mouse/synaptics_i2c.c
@@ -0,0 +1,676 @@
+/*
+ * Synaptics touchpad with I2C interface
+ *
+ * Copyright (C) 2009 Compulab, Ltd.
+ * Mike Rapoport <mike@compulab.co.il>
+ * Igor Grinberg <grinberg@compulab.co.il>
+ *
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file COPYING in the main directory of this archive for
+ * more details.
+ */
+
+#include <linux/module.h>
+#include <linux/i2c.h>
+#include <linux/irq.h>
+#include <linux/interrupt.h>
+#include <linux/input.h>
+#include <linux/delay.h>
+#include <linux/workqueue.h>
+
+#define DRIVER_NAME		"synaptics_i2c"
+/* maximum product id is 15 characters */
+#define PRODUCT_ID_LENGTH	15
+#define REGISTER_LENGTH		8
+
+/*
+ * after soft reset, we should wait for 1 ms
+ * before the device becomes operational
+ */
+#define SOFT_RESET_DELAY_MS	3
+/* and after hard reset, we should wait for max 500ms */
+#define HARD_RESET_DELAY_MS	500
+
+/* Registers by SMBus address */
+#define PAGE_SEL_REG		0xff
+#define DEVICE_STATUS_REG	0x09
+
+/* Registers by RMI address */
+#define DEV_CONTROL_REG		0x0000
+#define INTERRUPT_EN_REG	0x0001
+#define ERR_STAT_REG		0x0002
+#define INT_REQ_STAT_REG	0x0003
+#define DEV_COMMAND_REG		0x0004
+
+#define RMI_PROT_VER_REG	0x0200
+#define MANUFACT_ID_REG		0x0201
+#define PHYS_INT_VER_REG	0x0202
+#define PROD_PROPERTY_REG	0x0203
+#define INFO_QUERY_REG0		0x0204
+#define INFO_QUERY_REG1		(INFO_QUERY_REG0 + 1)
+#define INFO_QUERY_REG2		(INFO_QUERY_REG0 + 2)
+#define INFO_QUERY_REG3		(INFO_QUERY_REG0 + 3)
+
+#define PRODUCT_ID_REG0		0x0210
+#define PRODUCT_ID_REG1		(PRODUCT_ID_REG0 + 1)
+#define PRODUCT_ID_REG2		(PRODUCT_ID_REG0 + 2)
+#define PRODUCT_ID_REG3		(PRODUCT_ID_REG0 + 3)
+#define PRODUCT_ID_REG4		(PRODUCT_ID_REG0 + 4)
+#define PRODUCT_ID_REG5		(PRODUCT_ID_REG0 + 5)
+#define PRODUCT_ID_REG6		(PRODUCT_ID_REG0 + 6)
+#define PRODUCT_ID_REG7		(PRODUCT_ID_REG0 + 7)
+#define PRODUCT_ID_REG8		(PRODUCT_ID_REG0 + 8)
+#define PRODUCT_ID_REG9		(PRODUCT_ID_REG0 + 9)
+#define PRODUCT_ID_REG10	(PRODUCT_ID_REG0 + 10)
+#define PRODUCT_ID_REG11	(PRODUCT_ID_REG0 + 11)
+#define PRODUCT_ID_REG12	(PRODUCT_ID_REG0 + 12)
+#define PRODUCT_ID_REG13	(PRODUCT_ID_REG0 + 13)
+#define PRODUCT_ID_REG14	(PRODUCT_ID_REG0 + 14)
+#define PRODUCT_ID_REG15	(PRODUCT_ID_REG0 + 15)
+
+#define DATA_REG0		0x0400
+#define ABS_PRESSURE_REG	0x0401
+#define ABS_MSB_X_REG		0x0402
+#define ABS_LSB_X_REG		(ABS_MSB_X_REG + 1)
+#define ABS_MSB_Y_REG		0x0404
+#define ABS_LSB_Y_REG		(ABS_MSB_Y_REG + 1)
+#define REL_X_REG		0x0406
+#define REL_Y_REG		0x0407
+
+#define DEV_QUERY_REG0		0x1000
+#define DEV_QUERY_REG1		(DEV_QUERY_REG0 + 1)
+#define DEV_QUERY_REG2		(DEV_QUERY_REG0 + 2)
+#define DEV_QUERY_REG3		(DEV_QUERY_REG0 + 3)
+#define DEV_QUERY_REG4		(DEV_QUERY_REG0 + 4)
+#define DEV_QUERY_REG5		(DEV_QUERY_REG0 + 5)
+#define DEV_QUERY_REG6		(DEV_QUERY_REG0 + 6)
+#define DEV_QUERY_REG7		(DEV_QUERY_REG0 + 7)
+#define DEV_QUERY_REG8		(DEV_QUERY_REG0 + 8)
+
+#define GENERAL_2D_CONTROL_REG	0x1041
+#define SENSOR_SENSITIVITY_REG	0x1044
+#define SENS_MAX_POS_MSB_REG	0x1046
+#define SENS_MAX_POS_LSB_REG	(SENS_MAX_POS_UPPER_REG + 1)
+
+/* Register bits */
+/* Device Control Register Bits */
+#define REPORT_RATE_1ST_BIT	6
+
+/* Interrupt Enable Register Bits (INTERRUPT_EN_REG) */
+#define F10_ABS_INT_ENA		0
+#define F10_REL_INT_ENA		1
+#define F20_INT_ENA		2
+
+/* Interrupt Request Register Bits (INT_REQ_STAT_REG | DEVICE_STATUS_REG) */
+#define F10_ABS_INT_REQ		0
+#define F10_REL_INT_REQ		1
+#define F20_INT_REQ		2
+/* Device Status Register Bits (DEVICE_STATUS_REG) */
+#define STAT_CONFIGURED		6
+#define STAT_ERROR		7
+
+/* Device Command Register Bits (DEV_COMMAND_REG) */
+#define RESET_COMMAND		0x01
+#define REZERO_COMMAND		0x02
+
+/* Data Register 0 Bits (DATA_REG0) */
+#define GESTURE			3
+
+/* Device Query Registers Bits */
+/* DEV_QUERY_REG3 */
+#define HAS_PALM_DETECT		1
+#define HAS_MULTI_FING		2
+#define HAS_SCROLLER		4
+#define HAS_2D_SCROLL		5
+
+/* General 2D Control Register Bits (GENERAL_2D_CONTROL_REG) */
+#define NO_DECELERATION		1
+#define REDUCE_REPORTING	3
+#define NO_FILTER		5
+
+/* Function Masks */
+/* Device Control Register Masks (DEV_CONTROL_REG) */
+#define REPORT_RATE_MSK		0xc0
+#define SLEEP_MODE_MSK		0x07
+
+/* Device Sleep Modes */
+#define FULL_AWAKE		0x0
+#define NORMAL_OP		0x1
+#define LOW_PWR_OP		0x2
+#define VERY_LOW_PWR_OP		0x3
+#define SENS_SLEEP		0x4
+#define SLEEP_MOD		0x5
+#define DEEP_SLEEP		0x6
+#define HIBERNATE		0x7
+
+/* Interrupt Register Mask */
+/* (INT_REQ_STAT_REG | DEVICE_STATUS_REG | INTERRUPT_EN_REG) */
+#define INT_ENA_REQ_MSK		0x07
+#define INT_ENA_ABS_MSK		0x01
+#define INT_ENA_REL_MSK		0x02
+#define INT_ENA_F20_MSK		0x04
+
+/* Device Status Register Masks (DEVICE_STATUS_REG) */
+#define CONFIGURED_MSK		0x40
+#define ERROR_MSK		0x80
+
+/* Data Register 0 Masks */
+#define FINGER_WIDTH_MSK	0xf0
+#define GESTURE_MSK		0x08
+#define SENSOR_STATUS_MSK	0x07
+
+/*
+ * MSB Position Register Masks
+ * ABS_MSB_X_REG | ABS_MSB_Y_REG | SENS_MAX_POS_MSB_REG |
+ * DEV_QUERY_REG3 | DEV_QUERY_REG5
+ */
+#define MSB_POSITION_MSK	0x1f
+
+/* Device Query Registers Masks */
+
+/* DEV_QUERY_REG2 */
+#define NUM_EXTRA_POS_MSK	0x07
+
+/* When in IRQ mode read the device every THREAD_IRQ_SLEEP_SECS */
+#define THREAD_IRQ_SLEEP_SECS	2
+#define THREAD_IRQ_SLEEP_MSECS	(THREAD_IRQ_SLEEP_SECS * MSEC_PER_SEC)
+
+/*
+ * When in Polling mode and no data received for NO_DATA_THRES msecs
+ * reduce the polling rate to NO_DATA_SLEEP_MSECS
+ */
+#define NO_DATA_THRES		(MSEC_PER_SEC)
+#define NO_DATA_SLEEP_MSECS	(MSEC_PER_SEC / 4)
+
+/* Control touchpad's No Deceleration option */
+static int no_decel = 1;
+module_param(no_decel, bool, 0644);
+MODULE_PARM_DESC(no_decel, "No Deceleration. Default = 1 (on)");
+
+/* Control touchpad's Reduced Reporting option */
+static int reduce_report;
+module_param(reduce_report, bool, 0644);
+MODULE_PARM_DESC(reduce_report, "Reduced Reporting. Default = 0 (off)");
+
+/* Control touchpad's No Filter option */
+static int no_filter;
+module_param(no_filter, bool, 0644);
+MODULE_PARM_DESC(no_filter, "No Filter. Default = 0 (off)");
+
+/*
+ * touchpad Attention line is Active Low and Open Drain,
+ * therefore should be connected to pulled up line
+ * and the irq configuration should be set to Falling Edge Trigger
+ */
+/* Control IRQ / Polling option */
+static int polling_req;
+module_param(polling_req, bool, 0444);
+MODULE_PARM_DESC(polling_req, "Request Polling. Default = 0 (use irq)");
+
+/* Control Polling Rate */
+static int scan_rate = 80;
+module_param(scan_rate, int, 0644);
+MODULE_PARM_DESC(scan_rate, "Polling rate in times/sec. Default = 80");
+
+/* The main device structure */
+struct synaptics_i2c {
+	struct i2c_client	*client;
+	struct input_dev	*input;
+	struct delayed_work	dwork;
+	int			no_data_count;
+	int			no_decel_param;
+	int			reduce_report_param;
+	int			no_filter_param;
+	int			scan_rate_param;
+	int			scan_ms;
+};
+
+static inline void set_scan_rate(struct synaptics_i2c *touch, int scan_rate)
+{
+	touch->scan_ms = MSEC_PER_SEC / scan_rate;
+	touch->scan_rate_param = scan_rate;
+}
+
+/*
+ * Driver's initial design makes no race condition possible on i2c bus,
+ * so there is no need in any locking.
+ * Keep it in mind, while playing with the code.
+ */
+static s32 synaptics_i2c_reg_get(struct i2c_client *client, u16 reg)
+{
+	int ret;
+
+	ret = i2c_smbus_write_byte_data(client, PAGE_SEL_REG, reg >> 8);
+	if (ret == 0)
+		ret = i2c_smbus_read_byte_data(client, reg & 0xff);
+
+	return ret;
+}
+
+static s32 synaptics_i2c_reg_set(struct i2c_client *client, u16 reg, u8 val)
+{
+	int ret;
+
+	ret = i2c_smbus_write_byte_data(client, PAGE_SEL_REG, reg >> 8);
+	if (ret == 0)
+		ret = i2c_smbus_write_byte_data(client, reg & 0xff, val);
+
+	return ret;
+}
+
+static s32 synaptics_i2c_word_get(struct i2c_client *client, u16 reg)
+{
+	int ret;
+
+	ret = i2c_smbus_write_byte_data(client, PAGE_SEL_REG, reg >> 8);
+	if (ret == 0)
+		ret = i2c_smbus_read_word_data(client, reg & 0xff);
+
+	return ret;
+}
+
+static int synaptics_i2c_config(struct i2c_client *client)
+{
+	int ret, control;
+	u8 int_en;
+
+	/* set Report Rate to Device Highest (>=80) and Sleep to normal */
+	ret = synaptics_i2c_reg_set(client, DEV_CONTROL_REG, 0xc1);
+	if (ret)
+		return ret;
+
+	/* set Interrupt Disable to Func20 / Enable to Func10) */
+	int_en = (polling_req) ? 0 : INT_ENA_ABS_MSK | INT_ENA_REL_MSK;
+	ret = synaptics_i2c_reg_set(client, INTERRUPT_EN_REG, int_en);
+	if (ret)
+		return ret;
+
+	control = synaptics_i2c_reg_get(client, GENERAL_2D_CONTROL_REG);
+	/* No Deceleration */
+	control |= no_decel ? 1 << NO_DECELERATION : 0;
+	/* Reduced Reporting */
+	control |= reduce_report ? 1 << REDUCE_REPORTING : 0;
+	/* No Filter */
+	control |= no_filter ? 1 << NO_FILTER : 0;
+	ret = synaptics_i2c_reg_set(client, GENERAL_2D_CONTROL_REG, control);
+	if (ret)
+		return ret;
+
+	return 0;
+}
+
+static int synaptics_i2c_reset_config(struct i2c_client *client)
+{
+	int ret;
+
+	/* Reset the Touchpad */
+	ret = synaptics_i2c_reg_set(client, DEV_COMMAND_REG, RESET_COMMAND);
+	if (ret) {
+		dev_err(&client->dev, "Unable to reset device\n");
+	} else {
+		msleep(SOFT_RESET_DELAY_MS);
+		ret = synaptics_i2c_config(client);
+		if (ret)
+			dev_err(&client->dev, "Unable to config device\n");
+	}
+
+	return ret;
+}
+
+static int synaptics_i2c_check_error(struct i2c_client *client)
+{
+	int status, ret = 0;
+
+	status = i2c_smbus_read_byte_data(client, DEVICE_STATUS_REG) &
+		(CONFIGURED_MSK | ERROR_MSK);
+
+	if (status != CONFIGURED_MSK)
+		ret = synaptics_i2c_reset_config(client);
+
+	return ret;
+}
+
+static bool synaptics_i2c_get_input(struct synaptics_i2c *touch)
+{
+	struct input_dev *input = touch->input;
+	int xy_delta, gesture;
+	s32 data;
+	s8 x_delta, y_delta;
+
+	/* Deal with spontanious resets and errors */
+	if (synaptics_i2c_check_error(touch->client))
+		return 0;
+
+	/* Get Gesture Bit */
+	data = synaptics_i2c_reg_get(touch->client, DATA_REG0);
+	gesture = (data >> GESTURE) & 0x1;
+
+	/*
+	 * Get Relative axes. we have to get them in one shot,
+	 * so we get 2 bytes starting from REL_X_REG.
+	 */
+	xy_delta = synaptics_i2c_word_get(touch->client, REL_X_REG) & 0xffff;
+
+	/* Separate X from Y */
+	x_delta = xy_delta & 0xff;
+	y_delta = (xy_delta >> REGISTER_LENGTH) & 0xff;
+
+	/* Report the button event */
+	input_report_key(input, BTN_LEFT, gesture);
+
+	/* Report the deltas */
+	input_report_rel(input, REL_X, x_delta);
+	input_report_rel(input, REL_Y, -y_delta);
+	input_sync(input);
+
+	return xy_delta || gesture;
+}
+
+static irqreturn_t synaptics_i2c_irq(int irq, void *dev_id)
+{
+	struct synaptics_i2c *touch = dev_id;
+
+	/*
+	 * We want to have the work run immediately but it might have
+	 * already been scheduled with a delay, that's why we have to
+	 * cancel it first.
+	 */
+	cancel_delayed_work(&touch->dwork);
+	schedule_delayed_work(&touch->dwork, 0);
+
+	return IRQ_HANDLED;
+}
+
+static void synaptics_i2c_check_params(struct synaptics_i2c *touch)
+{
+	bool reset = false;
+
+	if (scan_rate != touch->scan_rate_param)
+		set_scan_rate(touch, scan_rate);
+
+	if (no_decel != touch->no_decel_param) {
+		touch->no_decel_param = no_decel;
+		reset = true;
+	}
+
+	if (no_filter != touch->no_filter_param) {
+		touch->no_filter_param = no_filter;
+		reset = true;
+	}
+
+	if (reduce_report != touch->reduce_report_param) {
+		touch->reduce_report_param = reduce_report;
+		reset = true;
+	}
+
+	if (reset)
+		synaptics_i2c_reset_config(touch->client);
+}
+
+/* Control the Device polling rate / Work Handler sleep time */
+unsigned long synaptics_i2c_adjust_delay(struct synaptics_i2c *touch,
+					 bool have_data)
+{
+	unsigned long delay, nodata_count_thres;
+
+	if (polling_req) {
+		delay = touch->scan_ms;
+		if (have_data) {
+			touch->no_data_count = 0;
+		} else {
+			nodata_count_thres = NO_DATA_THRES / touch->scan_ms;
+			if (touch->no_data_count < nodata_count_thres)
+				touch->no_data_count++;
+			else
+				delay = NO_DATA_SLEEP_MSECS;
+		}
+		return msecs_to_jiffies(delay);
+	} else {
+		delay = msecs_to_jiffies(THREAD_IRQ_SLEEP_MSECS);
+		return round_jiffies_relative(delay);
+	}
+}
+
+/* Work Handler */
+static void synaptics_i2c_work_handler(struct work_struct *work)
+{
+	bool have_data;
+	struct synaptics_i2c *touch =
+			container_of(work, struct synaptics_i2c, dwork.work);
+	unsigned long delay;
+
+	synaptics_i2c_check_params(touch);
+
+	have_data = synaptics_i2c_get_input(touch);
+	delay = synaptics_i2c_adjust_delay(touch, have_data);
+
+	/*
+	 * While interrupt driven, there is no real need to poll the device.
+	 * But touchpads are very sensitive, so there could be errors
+	 * related to physical environment and the attention line isn't
+	 * neccesarily asserted. In such case we can lose the touchpad.
+	 * We poll the device once in THREAD_IRQ_SLEEP_SECS and
+	 * if error is detected, we try to reset and reconfigure the touchpad.
+	 */
+	schedule_delayed_work(&touch->dwork, delay);
+}
+
+static int synaptics_i2c_open(struct input_dev *input)
+{
+	struct synaptics_i2c *touch = input_get_drvdata(input);
+	int ret;
+
+	ret = synaptics_i2c_reset_config(touch->client);
+	if (ret)
+		return ret;
+
+	if (polling_req)
+		schedule_delayed_work(&touch->dwork,
+				       msecs_to_jiffies(NO_DATA_SLEEP_MSECS));
+
+	return 0;
+}
+
+static void synaptics_i2c_close(struct input_dev *input)
+{
+	struct synaptics_i2c *touch = input_get_drvdata(input);
+
+	if (!polling_req)
+		synaptics_i2c_reg_set(touch->client, INTERRUPT_EN_REG, 0);
+
+	cancel_delayed_work_sync(&touch->dwork);
+
+	/* Save some power */
+	synaptics_i2c_reg_set(touch->client, DEV_CONTROL_REG, DEEP_SLEEP);
+}
+
+static void synaptics_i2c_set_input_params(struct synaptics_i2c *touch)
+{
+	struct input_dev *input = touch->input;
+
+	input->name = touch->client->name;
+	input->phys = touch->client->adapter->name;
+	input->id.bustype = BUS_I2C;
+	input->id.version = synaptics_i2c_word_get(touch->client,
+						   INFO_QUERY_REG0);
+	input->dev.parent = &touch->client->dev;
+	input->open = synaptics_i2c_open;
+	input->close = synaptics_i2c_close;
+	input_set_drvdata(input, touch);
+
+	/* Register the device as mouse */
+	__set_bit(EV_REL, input->evbit);
+	__set_bit(REL_X, input->relbit);
+	__set_bit(REL_Y, input->relbit);
+
+	/* Register device's buttons and keys */
+	__set_bit(EV_KEY, input->evbit);
+	__set_bit(BTN_LEFT, input->keybit);
+}
+
+struct synaptics_i2c *synaptics_i2c_touch_create(struct i2c_client *client)
+{
+	struct synaptics_i2c *touch;
+
+	touch = kzalloc(sizeof(struct synaptics_i2c), GFP_KERNEL);
+	if (!touch)
+		return NULL;
+
+	touch->client = client;
+	touch->no_decel_param = no_decel;
+	touch->scan_rate_param = scan_rate;
+	set_scan_rate(touch, scan_rate);
+	INIT_DELAYED_WORK(&touch->dwork, synaptics_i2c_work_handler);
+
+	return touch;
+}
+
+static int __devinit synaptics_i2c_probe(struct i2c_client *client,
+			       const struct i2c_device_id *dev_id)
+{
+	int ret;
+	struct synaptics_i2c *touch;
+
+	touch = synaptics_i2c_touch_create(client);
+	if (!touch)
+		return -ENOMEM;
+
+	i2c_set_clientdata(client, touch);
+
+	ret = synaptics_i2c_reset_config(client);
+	if (ret)
+		goto err_mem_free;
+
+	if (client->irq < 1)
+		polling_req = 1;
+
+	touch->input = input_allocate_device();
+	if (!touch->input) {
+		ret = -ENOMEM;
+		goto err_mem_free;
+	}
+
+	synaptics_i2c_set_input_params(touch);
+
+	if (!polling_req) {
+		dev_dbg(&touch->client->dev,
+			 "Requesting IRQ: %d\n", touch->client->irq);
+
+		ret = request_irq(touch->client->irq, synaptics_i2c_irq,
+				  IRQF_DISABLED|IRQ_TYPE_EDGE_FALLING,
+				  DRIVER_NAME, touch);
+		if (ret) {
+			dev_warn(&touch->client->dev,
+				  "IRQ request failed: %d, "
+				  "falling back to polling\n", ret);
+			polling_req = 1;
+			synaptics_i2c_reg_set(touch->client,
+					      INTERRUPT_EN_REG, 0);
+		}
+	}
+
+	if (polling_req)
+		dev_dbg(&touch->client->dev,
+			 "Using polling at rate: %d times/sec\n", scan_rate);
+
+	/* Register the device in input subsystem */
+	ret = input_register_device(touch->input);
+	if (ret) {
+		dev_err(&client->dev,
+			 "Input device register failed: %d\n", ret);
+		goto err_input_free;
+	}
+	return 0;
+
+err_input_free:
+	input_free_device(touch->input);
+err_mem_free:
+	i2c_set_clientdata(client, NULL);
+	kfree(touch);
+
+	return ret;
+}
+
+static int __devexit synaptics_i2c_remove(struct i2c_client *client)
+{
+	struct synaptics_i2c *touch = i2c_get_clientdata(client);
+
+	if (!polling_req)
+		free_irq(touch->client->irq, touch);
+
+	input_unregister_device(touch->input);
+	i2c_set_clientdata(client, NULL);
+	kfree(touch);
+
+	return 0;
+}
+
+#ifdef CONFIG_PM
+static int synaptics_i2c_suspend(struct i2c_client *client, pm_message_t mesg)
+{
+	struct synaptics_i2c *touch = i2c_get_clientdata(client);
+
+	cancel_delayed_work_sync(&touch->dwork);
+
+	/* Save some power */
+	synaptics_i2c_reg_set(touch->client, DEV_CONTROL_REG, DEEP_SLEEP);
+
+	return 0;
+}
+
+static int synaptics_i2c_resume(struct i2c_client *client)
+{
+	int ret;
+	struct synaptics_i2c *touch = i2c_get_clientdata(client);
+
+	ret = synaptics_i2c_reset_config(client);
+	if (ret)
+		return ret;
+
+	schedule_delayed_work(&touch->dwork,
+			       msecs_to_jiffies(NO_DATA_SLEEP_MSECS));
+
+	return 0;
+}
+#else
+#define synaptics_i2c_suspend	NULL
+#define synaptics_i2c_resume	NULL
+#endif
+
+static const struct i2c_device_id synaptics_i2c_id_table[] = {
+	{ "synaptics_i2c", 0 },
+	{ },
+};
+MODULE_DEVICE_TABLE(i2c, synaptics_i2c_id_table);
+
+static struct i2c_driver synaptics_i2c_driver = {
+	.driver = {
+		.name	= DRIVER_NAME,
+		.owner	= THIS_MODULE,
+	},
+
+	.probe		= synaptics_i2c_probe,
+	.remove		= __devexit_p(synaptics_i2c_remove),
+
+	.suspend	= synaptics_i2c_suspend,
+	.resume		= synaptics_i2c_resume,
+	.id_table	= synaptics_i2c_id_table,
+};
+
+static int __init synaptics_i2c_init(void)
+{
+	return i2c_add_driver(&synaptics_i2c_driver);
+}
+
+static void __exit synaptics_i2c_exit(void)
+{
+	i2c_del_driver(&synaptics_i2c_driver);
+}
+
+module_init(synaptics_i2c_init);
+module_exit(synaptics_i2c_exit);
+
+MODULE_DESCRIPTION("Synaptics I2C touchpad driver");
+MODULE_AUTHOR("Mike Rapoport, Igor Grinberg, Compulab");
+MODULE_LICENSE("GPL");
+
diff --git a/drivers/input/mousedev.c b/drivers/input/mousedev.c
index 17fd6d4..966b886 100644
--- a/drivers/input/mousedev.c
+++ b/drivers/input/mousedev.c
@@ -60,7 +60,6 @@
 	int exist;
 	int open;
 	int minor;
-	char name[16];
 	struct input_handle handle;
 	wait_queue_head_t wait;
 	struct list_head client_list;
@@ -863,19 +862,17 @@
 	init_waitqueue_head(&mousedev->wait);
 
 	if (minor == MOUSEDEV_MIX)
-		strlcpy(mousedev->name, "mice", sizeof(mousedev->name));
+		dev_set_name(&mousedev->dev, "mice");
 	else
-		snprintf(mousedev->name, sizeof(mousedev->name),
-			 "mouse%d", minor);
+		dev_set_name(&mousedev->dev, "mouse%d", minor);
 
 	mousedev->minor = minor;
 	mousedev->exist = 1;
 	mousedev->handle.dev = input_get_device(dev);
-	mousedev->handle.name = mousedev->name;
+	mousedev->handle.name = dev_name(&mousedev->dev);
 	mousedev->handle.handler = handler;
 	mousedev->handle.private = mousedev;
 
-	dev_set_name(&mousedev->dev, mousedev->name);
 	mousedev->dev.class = &input_class;
 	if (dev)
 		mousedev->dev.parent = &dev->dev;
diff --git a/drivers/input/serio/i8042.c b/drivers/input/serio/i8042.c
index 3cffb70..f919bf5 100644
--- a/drivers/input/serio/i8042.c
+++ b/drivers/input/serio/i8042.c
@@ -10,6 +10,7 @@
  * the Free Software Foundation.
  */
 
+#include <linux/types.h>
 #include <linux/delay.h>
 #include <linux/module.h>
 #include <linux/interrupt.h>
@@ -921,6 +922,9 @@
 #endif
 
 #ifdef CONFIG_PM
+
+static bool i8042_suspended;
+
 /*
  * Here we try to restore the original BIOS settings. We only want to
  * do that once, when we really suspend, not when we taking memory
@@ -930,11 +934,9 @@
 
 static int i8042_suspend(struct platform_device *dev, pm_message_t state)
 {
-	if (dev->dev.power.power_state.event != state.event) {
-		if (state.event == PM_EVENT_SUSPEND)
-			i8042_controller_reset();
-
-		dev->dev.power.power_state = state;
+	if (!i8042_suspended && state.event == PM_EVENT_SUSPEND) {
+		i8042_controller_reset();
+		i8042_suspended = true;
 	}
 
 	return 0;
@@ -952,7 +954,7 @@
 /*
  * Do not bother with restoring state if we haven't suspened yet
  */
-	if (dev->dev.power.power_state.event == PM_EVENT_ON)
+	if (!i8042_suspended)
 		return 0;
 
 	error = i8042_controller_check();
@@ -998,10 +1000,9 @@
 	if (i8042_ports[I8042_KBD_PORT_NO].serio)
 		i8042_enable_kbd_port();
 
+	i8042_suspended = false;
 	i8042_interrupt(0, NULL);
 
-	dev->dev.power.power_state = PMSG_ON;
-
 	return 0;
 }
 #endif /* CONFIG_PM */
diff --git a/drivers/input/serio/serio.c b/drivers/input/serio/serio.c
index bc03325..fb17573 100644
--- a/drivers/input/serio/serio.c
+++ b/drivers/input/serio/serio.c
@@ -41,17 +41,6 @@
 MODULE_DESCRIPTION("Serio abstraction core");
 MODULE_LICENSE("GPL");
 
-EXPORT_SYMBOL(serio_interrupt);
-EXPORT_SYMBOL(__serio_register_port);
-EXPORT_SYMBOL(serio_unregister_port);
-EXPORT_SYMBOL(serio_unregister_child_port);
-EXPORT_SYMBOL(__serio_register_driver);
-EXPORT_SYMBOL(serio_unregister_driver);
-EXPORT_SYMBOL(serio_open);
-EXPORT_SYMBOL(serio_close);
-EXPORT_SYMBOL(serio_rescan);
-EXPORT_SYMBOL(serio_reconnect);
-
 /*
  * serio_mutex protects entire serio subsystem and is taken every time
  * serio port or driver registrered or unregistered.
@@ -506,9 +495,9 @@
 
 	retval = count;
 	if (!strncmp(buf, "manual", count)) {
-		serio->manual_bind = 1;
+		serio->manual_bind = true;
 	} else if (!strncmp(buf, "auto", count)) {
-		serio->manual_bind = 0;
+		serio->manual_bind = false;
 	} else {
 		retval = -EINVAL;
 	}
@@ -581,7 +570,7 @@
 			"serio: device_add() failed for %s (%s), error: %d\n",
 			serio->phys, serio->name, error);
 	else {
-		serio->registered = 1;
+		serio->registered = true;
 		error = sysfs_create_group(&serio->dev.kobj, &serio_id_attr_group);
 		if (error)
 			printk(KERN_ERR
@@ -617,7 +606,7 @@
 	if (serio->registered) {
 		sysfs_remove_group(&serio->dev.kobj, &serio_id_attr_group);
 		device_del(&serio->dev);
-		serio->registered = 0;
+		serio->registered = false;
 	}
 
 	list_del_init(&serio->node);
@@ -692,11 +681,13 @@
 {
 	serio_queue_event(serio, NULL, SERIO_RESCAN_PORT);
 }
+EXPORT_SYMBOL(serio_rescan);
 
 void serio_reconnect(struct serio *serio)
 {
 	serio_queue_event(serio, NULL, SERIO_RECONNECT_CHAIN);
 }
+EXPORT_SYMBOL(serio_reconnect);
 
 /*
  * Submits register request to kseriod for subsequent execution.
@@ -707,6 +698,7 @@
 	serio_init_port(serio);
 	serio_queue_event(serio, owner, SERIO_REGISTER_PORT);
 }
+EXPORT_SYMBOL(__serio_register_port);
 
 /*
  * Synchronously unregisters serio port.
@@ -718,6 +710,7 @@
 	serio_destroy_port(serio);
 	mutex_unlock(&serio_mutex);
 }
+EXPORT_SYMBOL(serio_unregister_port);
 
 /*
  * Safely unregisters child port if one is present.
@@ -731,6 +724,7 @@
 	}
 	mutex_unlock(&serio_mutex);
 }
+EXPORT_SYMBOL(serio_unregister_child_port);
 
 
 /*
@@ -756,9 +750,9 @@
 
 	retval = count;
 	if (!strncmp(buf, "manual", count)) {
-		serio_drv->manual_bind = 1;
+		serio_drv->manual_bind = true;
 	} else if (!strncmp(buf, "auto", count)) {
-		serio_drv->manual_bind = 0;
+		serio_drv->manual_bind = false;
 	} else {
 		retval = -EINVAL;
 	}
@@ -818,7 +812,7 @@
 
 int __serio_register_driver(struct serio_driver *drv, struct module *owner, const char *mod_name)
 {
-	int manual_bind = drv->manual_bind;
+	bool manual_bind = drv->manual_bind;
 	int error;
 
 	drv->driver.bus = &serio_bus;
@@ -829,7 +823,7 @@
 	 * Temporarily disable automatic binding because probing
 	 * takes long time and we are better off doing it in kseriod
 	 */
-	drv->manual_bind = 1;
+	drv->manual_bind = true;
 
 	error = driver_register(&drv->driver);
 	if (error) {
@@ -844,7 +838,7 @@
 	 * driver to free ports
 	 */
 	if (!manual_bind) {
-		drv->manual_bind = 0;
+		drv->manual_bind = false;
 		error = serio_queue_event(drv, NULL, SERIO_ATTACH_DRIVER);
 		if (error) {
 			driver_unregister(&drv->driver);
@@ -854,6 +848,7 @@
 
 	return 0;
 }
+EXPORT_SYMBOL(__serio_register_driver);
 
 void serio_unregister_driver(struct serio_driver *drv)
 {
@@ -861,7 +856,7 @@
 
 	mutex_lock(&serio_mutex);
 
-	drv->manual_bind = 1;	/* so serio_find_driver ignores it */
+	drv->manual_bind = true;	/* so serio_find_driver ignores it */
 	serio_remove_pending_events(drv);
 
 start_over:
@@ -877,6 +872,7 @@
 	driver_unregister(&drv->driver);
 	mutex_unlock(&serio_mutex);
 }
+EXPORT_SYMBOL(serio_unregister_driver);
 
 static void serio_set_drv(struct serio *serio, struct serio_driver *drv)
 {
@@ -937,11 +933,11 @@
 #ifdef CONFIG_PM
 static int serio_suspend(struct device *dev, pm_message_t state)
 {
-	if (dev->power.power_state.event != state.event) {
-		if (state.event == PM_EVENT_SUSPEND)
-			serio_cleanup(to_serio_port(dev));
+	struct serio *serio = to_serio_port(dev);
 
-		dev->power.power_state = state;
+	if (!serio->suspended && state.event == PM_EVENT_SUSPEND) {
+		serio_cleanup(serio);
+		serio->suspended = true;
 	}
 
 	return 0;
@@ -949,14 +945,15 @@
 
 static int serio_resume(struct device *dev)
 {
+	struct serio *serio = to_serio_port(dev);
+
 	/*
 	 * Driver reconnect can take a while, so better let kseriod
 	 * deal with it.
 	 */
-	if (dev->power.power_state.event != PM_EVENT_ON) {
-		dev->power.power_state = PMSG_ON;
-		serio_queue_event(to_serio_port(dev), NULL,
-				  SERIO_RECONNECT_PORT);
+	if (serio->suspended) {
+		serio->suspended = false;
+		serio_queue_event(serio, NULL, SERIO_RECONNECT_PORT);
 	}
 
 	return 0;
@@ -974,6 +971,7 @@
 	}
 	return 0;
 }
+EXPORT_SYMBOL(serio_open);
 
 /* called from serio_driver->connect/disconnect methods under serio_mutex */
 void serio_close(struct serio *serio)
@@ -983,6 +981,7 @@
 
 	serio_set_drv(serio, NULL);
 }
+EXPORT_SYMBOL(serio_close);
 
 irqreturn_t serio_interrupt(struct serio *serio,
 		unsigned char data, unsigned int dfl)
@@ -1003,6 +1002,7 @@
 
 	return ret;
 }
+EXPORT_SYMBOL(serio_interrupt);
 
 static struct bus_type serio_bus = {
 	.name		= "serio",
diff --git a/drivers/input/tablet/gtco.c b/drivers/input/tablet/gtco.c
index 2e18a1c..3d32d3f 100644
--- a/drivers/input/tablet/gtco.c
+++ b/drivers/input/tablet/gtco.c
@@ -1050,4 +1050,5 @@
 module_init(gtco_init);
 module_exit(gtco_exit);
 
+MODULE_DESCRIPTION("GTCO digitizer USB driver");
 MODULE_LICENSE("GPL");
diff --git a/drivers/input/tablet/wacom.h b/drivers/input/tablet/wacom.h
index 9710bfd..9114ae1 100644
--- a/drivers/input/tablet/wacom.h
+++ b/drivers/input/tablet/wacom.h
@@ -68,6 +68,7 @@
  *      v1.48 (pc) - Added support for Bamboo1, BambooFun, and Cintiq 12WX
  *      v1.49 (pc) - Added support for USB Tablet PC (0x90, 0x93, and 0x9A)
  *      v1.50 (pc) - Fixed a TabletPC touch bug in 2.6.28
+ *      v1.51 (pc) - Added support for Intuos4
  */
 
 /*
@@ -88,7 +89,7 @@
 /*
  * Version Information
  */
-#define DRIVER_VERSION "v1.50"
+#define DRIVER_VERSION "v1.51"
 #define DRIVER_AUTHOR "Vojtech Pavlik <vojtech@ucw.cz>"
 #define DRIVER_DESC "USB Wacom Graphire and Wacom Intuos tablet driver"
 #define DRIVER_LICENSE "GPL"
@@ -128,6 +129,8 @@
 extern void input_dev_i3s(struct input_dev *input_dev, struct wacom_wac *wacom_wac);
 extern void input_dev_i3(struct input_dev *input_dev, struct wacom_wac *wacom_wac);
 extern void input_dev_i(struct input_dev *input_dev, struct wacom_wac *wacom_wac);
+extern void input_dev_i4s(struct input_dev *input_dev, struct wacom_wac *wacom_wac);
+extern void input_dev_i4(struct input_dev *input_dev, struct wacom_wac *wacom_wac);
 extern void input_dev_pl(struct input_dev *input_dev, struct wacom_wac *wacom_wac);
 extern void input_dev_pt(struct input_dev *input_dev, struct wacom_wac *wacom_wac);
 extern void input_dev_mo(struct input_dev *input_dev, struct wacom_wac *wacom_wac);
diff --git a/drivers/input/tablet/wacom_sys.c b/drivers/input/tablet/wacom_sys.c
index b8624f2..a9d5031 100644
--- a/drivers/input/tablet/wacom_sys.c
+++ b/drivers/input/tablet/wacom_sys.c
@@ -229,6 +229,19 @@
 	input_set_abs_params(input_dev, ABS_RY, 0, 4096, 0, 0);
 }
 
+void input_dev_i4s(struct input_dev *input_dev, struct wacom_wac *wacom_wac)
+{
+	input_dev->keybit[BIT_WORD(BTN_DIGI)] |= BIT_MASK(BTN_TOOL_FINGER);
+	input_dev->keybit[BIT_WORD(BTN_MISC)] |= BIT_MASK(BTN_0) | BIT_MASK(BTN_1) | BIT_MASK(BTN_2) | BIT_MASK(BTN_3);
+	input_dev->keybit[BIT_WORD(BTN_MISC)] |= BIT_MASK(BTN_4) | BIT_MASK(BTN_5) | BIT_MASK(BTN_6);
+	input_set_abs_params(input_dev, ABS_Z, -900, 899, 0, 0);
+}
+
+void input_dev_i4(struct input_dev *input_dev, struct wacom_wac *wacom_wac)
+{
+	input_dev->keybit[BIT_WORD(BTN_MISC)] |= BIT_MASK(BTN_7) | BIT_MASK(BTN_8);
+}
+
 void input_dev_bee(struct input_dev *input_dev, struct wacom_wac *wacom_wac)
 {
 	input_dev->keybit[BIT_WORD(BTN_MISC)] |= BIT_MASK(BTN_8) | BIT_MASK(BTN_9);
diff --git a/drivers/input/tablet/wacom_wac.c b/drivers/input/tablet/wacom_wac.c
index 2638811..38bf863 100644
--- a/drivers/input/tablet/wacom_wac.c
+++ b/drivers/input/tablet/wacom_wac.c
@@ -283,10 +283,11 @@
 static int wacom_intuos_inout(struct wacom_wac *wacom, void *wcombo)
 {
 	unsigned char *data = wacom->data;
-	int idx;
+	int idx = 0;
 
 	/* tool number */
-	idx = data[1] & 0x01;
+	if (wacom->features->type == INTUOS)
+		idx = data[1] & 0x01;
 
 	/* Enter report */
 	if ((data[1] & 0xfc) == 0xc0) {
@@ -299,6 +300,7 @@
 		switch (wacom->id[idx]) {
 			case 0x812: /* Inking pen */
 			case 0x801: /* Intuos3 Inking pen */
+			case 0x20802: /* Intuos4 Classic Pen */
 			case 0x012:
 				wacom->tool[idx] = BTN_TOOL_PENCIL;
 				break;
@@ -308,6 +310,9 @@
 			case 0x823: /* Intuos3 Grip Pen */
 			case 0x813: /* Intuos3 Classic Pen */
 			case 0x885: /* Intuos3 Marker Pen */
+			case 0x802: /* Intuos4 Grip Pen Eraser */
+			case 0x804: /* Intuos4 Marker Pen */
+			case 0x40802: /* Intuos4 Classic Pen */
 			case 0x022:
 				wacom->tool[idx] = BTN_TOOL_PEN;
 				break;
@@ -319,10 +324,12 @@
 		        case 0x09c:
 			case 0x094:
 			case 0x017: /* Intuos3 2D Mouse */
+			case 0x806: /* Intuos4 Mouse */
 				wacom->tool[idx] = BTN_TOOL_MOUSE;
 				break;
 			case 0x096: /* Lens cursor */
 			case 0x097: /* Intuos3 Lens cursor */
+			case 0x006: /* Intuos4 Lens cursor */
 				wacom->tool[idx] = BTN_TOOL_LENS;
 				break;
 			case 0x82a: /* Eraser */
@@ -333,12 +340,17 @@
 			case 0x82b: /* Intuos3 Grip Pen Eraser */
 			case 0x81b: /* Intuos3 Classic Pen Eraser */
 			case 0x91b: /* Intuos3 Airbrush Eraser */
+			case 0x80c: /* Intuos4 Marker Pen Eraser */
+			case 0x80a: /* Intuos4 Grip Pen Eraser */
+			case 0x4080a: /* Intuos4 Classic Pen Eraser */
+			case 0x90a: /* Intuos4 Airbrush Eraser */
 				wacom->tool[idx] = BTN_TOOL_RUBBER;
 				break;
 			case 0xd12:
 			case 0x912:
 			case 0x112:
 			case 0x913: /* Intuos3 Airbrush */
+			case 0x902: /* Intuos4 Airbrush */
 				wacom->tool[idx] = BTN_TOOL_AIRBRUSH;
 				break;
 			default: /* Unknown tool */
@@ -349,9 +361,15 @@
 
 	/* Exit report */
 	if ((data[1] & 0xfe) == 0x80) {
+		/*
+		 * Reset all states otherwise we lose the initial states
+		 * when in-prox next time
+		 */
 		wacom_report_abs(wcombo, ABS_X, 0);
 		wacom_report_abs(wcombo, ABS_Y, 0);
 		wacom_report_abs(wcombo, ABS_DISTANCE, 0);
+		wacom_report_abs(wcombo, ABS_TILT_X, 0);
+		wacom_report_abs(wcombo, ABS_TILT_Y, 0);
 		if (wacom->tool[idx] >= BTN_TOOL_MOUSE) {
 			wacom_report_key(wcombo, BTN_LEFT, 0);
 			wacom_report_key(wcombo, BTN_MIDDLE, 0);
@@ -362,8 +380,6 @@
 			wacom_report_abs(wcombo, ABS_RZ, 0);
 		} else {
 			wacom_report_abs(wcombo, ABS_PRESSURE, 0);
-			wacom_report_abs(wcombo, ABS_TILT_X, 0);
-			wacom_report_abs(wcombo, ABS_TILT_Y, 0);
 			wacom_report_key(wcombo, BTN_STYLUS, 0);
 			wacom_report_key(wcombo, BTN_STYLUS2, 0);
 			wacom_report_key(wcombo, BTN_TOUCH, 0);
@@ -372,6 +388,7 @@
 		wacom_report_key(wcombo, wacom->tool[idx], 0);
 		wacom_report_abs(wcombo, ABS_MISC, 0); /* reset tool id */
 		wacom_input_event(wcombo, EV_MSC, MSC_SERIAL, wacom->serial[idx]);
+		wacom->id[idx] = 0;
 		return 2;
 	}
 	return 0;
@@ -385,6 +402,8 @@
 	/* general pen packet */
 	if ((data[1] & 0xb8) == 0xa0) {
 		t = (data[6] << 2) | ((data[7] >> 6) & 3);
+		if (wacom->features->type >= INTUOS4S && wacom->features->type <= INTUOS4L)
+			t = (t << 1) | (data[1] & 1);
 		wacom_report_abs(wcombo, ABS_PRESSURE, t);
 		wacom_report_abs(wcombo, ABS_TILT_X,
 				((data[7] << 1) & 0x7e) | (data[8] >> 7));
@@ -409,7 +428,7 @@
 {
 	unsigned char *data = wacom->data;
 	unsigned int t;
-	int idx, result;
+	int idx = 0, result;
 
 	if (data[0] != 2 && data[0] != 5 && data[0] != 6 && data[0] != 12) {
 		dbg("wacom_intuos_irq: received unknown report #%d", data[0]);
@@ -417,7 +436,8 @@
 	}
 
 	/* tool number */
-	idx = data[1] & 0x01;
+	if (wacom->features->type == INTUOS)
+		idx = data[1] & 0x01;
 
 	/* pad packets. Works as a second tool and is always in prox */
 	if (data[0] == 12) {
@@ -425,25 +445,54 @@
 		if (wacom->tool[1] != BTN_TOOL_FINGER)
 			wacom->tool[1] = BTN_TOOL_FINGER;
 
-		wacom_report_key(wcombo, BTN_0, (data[5] & 0x01));
-		wacom_report_key(wcombo, BTN_1, (data[5] & 0x02));
-		wacom_report_key(wcombo, BTN_2, (data[5] & 0x04));
-		wacom_report_key(wcombo, BTN_3, (data[5] & 0x08));
-		wacom_report_key(wcombo, BTN_4, (data[6] & 0x01));
-		wacom_report_key(wcombo, BTN_5, (data[6] & 0x02));
-		wacom_report_key(wcombo, BTN_6, (data[6] & 0x04));
-		wacom_report_key(wcombo, BTN_7, (data[6] & 0x08));
-		wacom_report_key(wcombo, BTN_8, (data[5] & 0x10));
-		wacom_report_key(wcombo, BTN_9, (data[6] & 0x10));
-		wacom_report_abs(wcombo, ABS_RX, ((data[1] & 0x1f) << 8) | data[2]);
-		wacom_report_abs(wcombo, ABS_RY, ((data[3] & 0x1f) << 8) | data[4]);
+		if (wacom->features->type >= INTUOS4S && wacom->features->type <= INTUOS4L) {
+			wacom_report_key(wcombo, BTN_0, (data[2] & 0x01));
+			wacom_report_key(wcombo, BTN_1, (data[3] & 0x01));
+			wacom_report_key(wcombo, BTN_2, (data[3] & 0x02));
+			wacom_report_key(wcombo, BTN_3, (data[3] & 0x04));
+			wacom_report_key(wcombo, BTN_4, (data[3] & 0x08));
+			wacom_report_key(wcombo, BTN_5, (data[3] & 0x10));
+			wacom_report_key(wcombo, BTN_6, (data[3] & 0x20));
+			if (data[1] & 0x80) {
+				wacom_report_abs(wcombo, ABS_WHEEL, (data[1] & 0x7f));
+			} else {
+				/* Out of proximity, clear wheel value. */
+				wacom_report_abs(wcombo, ABS_WHEEL, 0);
+			}
+			if (wacom->features->type != INTUOS4S) {
+				wacom_report_key(wcombo, BTN_7, (data[3] & 0x40));
+				wacom_report_key(wcombo, BTN_8, (data[3] & 0x80));
+			}
+			if (data[1] | (data[2] & 0x01) | data[3]) {
+				wacom_report_key(wcombo, wacom->tool[1], 1);
+				wacom_report_abs(wcombo, ABS_MISC, PAD_DEVICE_ID);
+			} else {
+				wacom_report_key(wcombo, wacom->tool[1], 0);
+				wacom_report_abs(wcombo, ABS_MISC, 0);
+			}
+		} else {
+			wacom_report_key(wcombo, BTN_0, (data[5] & 0x01));
+			wacom_report_key(wcombo, BTN_1, (data[5] & 0x02));
+			wacom_report_key(wcombo, BTN_2, (data[5] & 0x04));
+			wacom_report_key(wcombo, BTN_3, (data[5] & 0x08));
+			wacom_report_key(wcombo, BTN_4, (data[6] & 0x01));
+			wacom_report_key(wcombo, BTN_5, (data[6] & 0x02));
+			wacom_report_key(wcombo, BTN_6, (data[6] & 0x04));
+			wacom_report_key(wcombo, BTN_7, (data[6] & 0x08));
+			wacom_report_key(wcombo, BTN_8, (data[5] & 0x10));
+			wacom_report_key(wcombo, BTN_9, (data[6] & 0x10));
+			wacom_report_abs(wcombo, ABS_RX, ((data[1] & 0x1f) << 8) | data[2]);
+			wacom_report_abs(wcombo, ABS_RY, ((data[3] & 0x1f) << 8) | data[4]);
 
-		if ((data[5] & 0x1f) | (data[6] & 0x1f) | (data[1] & 0x1f) |
-			data[2] | (data[3] & 0x1f) | data[4])
-			wacom_report_key(wcombo, wacom->tool[1], 1);
-		else
-			wacom_report_key(wcombo, wacom->tool[1], 0);
-		wacom_report_abs(wcombo, ABS_MISC, PAD_DEVICE_ID);
+			if ((data[5] & 0x1f) | (data[6] & 0x1f) | (data[1] & 0x1f) |
+				data[2] | (data[3] & 0x1f) | data[4]) {
+				wacom_report_key(wcombo, wacom->tool[1], 1);
+				wacom_report_abs(wcombo, ABS_MISC, PAD_DEVICE_ID);
+			} else {
+				wacom_report_key(wcombo, wacom->tool[1], 0);
+				wacom_report_abs(wcombo, ABS_MISC, 0);
+			}
+		}
 		wacom_input_event(wcombo, EV_MSC, MSC_SERIAL, 0xffffffff);
                 return 1;
 	}
@@ -453,10 +502,16 @@
 	if (result)
                 return result-1;
 
-	/* Only large I3 and I1 & I2 support Lense Cursor */
+	/* don't proceed if we don't know the ID */
+	if (!wacom->id[idx])
+		return 0;
+
+	/* Only large Intuos support Lense Cursor */
 	if ((wacom->tool[idx] == BTN_TOOL_LENS)
 			&& ((wacom->features->type == INTUOS3)
-			|| (wacom->features->type == INTUOS3S)))
+			|| (wacom->features->type == INTUOS3S)
+			|| (wacom->features->type == INTUOS4)
+			|| (wacom->features->type == INTUOS4S)))
 		return 0;
 
 	/* Cintiq doesn't send data when RDY bit isn't set */
@@ -476,8 +531,8 @@
 	/* process general packets */
 	wacom_intuos_general(wacom, wcombo);
 
-	/* 4D mouse, 2D mouse, marker pen rotation, or Lens cursor packets */
-	if ((data[1] & 0xbc) == 0xa8 || (data[1] & 0xbe) == 0xb0) {
+	/* 4D mouse, 2D mouse, marker pen rotation, tilt mouse, or Lens cursor packets */
+	if ((data[1] & 0xbc) == 0xa8 || (data[1] & 0xbe) == 0xb0 || (data[1] & 0xbc) == 0xac) {
 
 		if (data[1] & 0x02) {
 			/* Rotation packet */
@@ -506,20 +561,36 @@
 			wacom_report_abs(wcombo, ABS_THROTTLE, (data[8] & 0x08) ? -t : t);
 
 		} else if (wacom->tool[idx] == BTN_TOOL_MOUSE) {
-			/* 2D mouse packet */
-			wacom_report_key(wcombo, BTN_LEFT,   data[8] & 0x04);
-			wacom_report_key(wcombo, BTN_MIDDLE, data[8] & 0x08);
-			wacom_report_key(wcombo, BTN_RIGHT,  data[8] & 0x10);
-			wacom_report_rel(wcombo, REL_WHEEL, (data[8] & 0x01)
+			/* I4 mouse */
+			if (wacom->features->type >= INTUOS4S && wacom->features->type <= INTUOS4L) {
+				wacom_report_key(wcombo, BTN_LEFT,   data[6] & 0x01);
+				wacom_report_key(wcombo, BTN_MIDDLE, data[6] & 0x02);
+				wacom_report_key(wcombo, BTN_RIGHT,  data[6] & 0x04);
+				wacom_report_rel(wcombo, REL_WHEEL, ((data[7] & 0x80) >> 7)
+						 - ((data[7] & 0x40) >> 6));
+				wacom_report_key(wcombo, BTN_SIDE,   data[6] & 0x08);
+				wacom_report_key(wcombo, BTN_EXTRA,  data[6] & 0x10);
+
+				wacom_report_abs(wcombo, ABS_TILT_X,
+					((data[7] << 1) & 0x7e) | (data[8] >> 7));
+				wacom_report_abs(wcombo, ABS_TILT_Y, data[8] & 0x7f);
+			} else {
+				/* 2D mouse packet */
+				wacom_report_key(wcombo, BTN_LEFT,   data[8] & 0x04);
+				wacom_report_key(wcombo, BTN_MIDDLE, data[8] & 0x08);
+				wacom_report_key(wcombo, BTN_RIGHT,  data[8] & 0x10);
+				wacom_report_rel(wcombo, REL_WHEEL, (data[8] & 0x01)
 						 - ((data[8] & 0x02) >> 1));
 
-			/* I3 2D mouse side buttons */
-			if (wacom->features->type >= INTUOS3S && wacom->features->type <= INTUOS3L) {
-				wacom_report_key(wcombo, BTN_SIDE,   data[8] & 0x40);
-				wacom_report_key(wcombo, BTN_EXTRA,  data[8] & 0x20);
+				/* I3 2D mouse side buttons */
+				if (wacom->features->type >= INTUOS3S && wacom->features->type <= INTUOS3L) {
+					wacom_report_key(wcombo, BTN_SIDE,   data[8] & 0x40);
+					wacom_report_key(wcombo, BTN_EXTRA,  data[8] & 0x20);
+				}
 			}
-
-		} else if (wacom->features->type < INTUOS3S || wacom->features->type == INTUOS3L) {
+		} else if ((wacom->features->type < INTUOS3S || wacom->features->type == INTUOS3L ||
+				wacom->features->type == INTUOS4L) &&
+			   wacom->tool[idx] == BTN_TOOL_LENS) {
 			/* Lens cursor packets */
 			wacom_report_key(wcombo, BTN_LEFT,   data[8] & 0x01);
 			wacom_report_key(wcombo, BTN_MIDDLE, data[8] & 0x02);
@@ -581,6 +652,7 @@
 			}
 		} else if (touchOut || !prox) { /* force touch out-prox */
 			wacom_report_abs(wcombo, ABS_MISC, TOUCH_DEVICE_ID);
+			wacom_report_key(wcombo, wacom->tool[1], 0);
 			wacom_report_key(wcombo, BTN_TOUCH, 0);
 			touchOut = 0;
 			touchInProx = 1;
@@ -669,6 +741,9 @@
 		case INTUOS3S:
 		case INTUOS3:
 		case INTUOS3L:
+		case INTUOS4S:
+		case INTUOS4:
+		case INTUOS4L:
 		case CINTIQ:
 		case WACOM_BEE:
 			return wacom_intuos_irq(wacom_wac, wcombo);
@@ -706,6 +781,14 @@
 		case INTUOS:
 			input_dev_i(input_dev, wacom_wac);
 			break;
+		case INTUOS4:
+		case INTUOS4L:
+			input_dev_i4(input_dev, wacom_wac);
+			/* fall through */
+		case INTUOS4S:
+			input_dev_i4s(input_dev, wacom_wac);
+			input_dev_i(input_dev, wacom_wac);
+			break;
 		case PL:
 		case PTU:
 		case TABLETPC:
@@ -766,6 +849,10 @@
 	{ "Wacom Intuos3 12x19", 10, 97536, 60960, 1023, 63, INTUOS3L },
 	{ "Wacom Intuos3 6x11",  10, 54204, 31750, 1023, 63, INTUOS3 },
 	{ "Wacom Intuos3 4x6",   10, 31496, 19685, 1023, 63, INTUOS3S },
+	{ "Wacom Intuos4 4x6",   10, 31496, 19685, 2047, 63, INTUOS4S },
+	{ "Wacom Intuos4 6x9",   10, 44704, 27940, 2047, 63, INTUOS4 },
+	{ "Wacom Intuos4 8x13",  10, 65024, 40640, 2047, 63, INTUOS4L },
+	{ "Wacom Intuos4 12x19", 10, 97536, 60960, 2047, 63, INTUOS4L },
 	{ "Wacom Cintiq 21UX",   10, 87200, 65600, 1023, 63, CINTIQ },
 	{ "Wacom Cintiq 20WSX",  10, 86680, 54180, 1023, 63, WACOM_BEE },
 	{ "Wacom Cintiq 12WX",   10, 53020, 33440, 1023, 63, WACOM_BEE },
@@ -825,6 +912,10 @@
 	{ USB_DEVICE(USB_VENDOR_ID_WACOM, 0xB4) },
 	{ USB_DEVICE(USB_VENDOR_ID_WACOM, 0xB5) },
 	{ USB_DEVICE(USB_VENDOR_ID_WACOM, 0xB7) },
+	{ USB_DEVICE(USB_VENDOR_ID_WACOM, 0xB8) },
+	{ USB_DEVICE(USB_VENDOR_ID_WACOM, 0xB9) },
+	{ USB_DEVICE(USB_VENDOR_ID_WACOM, 0xBA) },
+	{ USB_DEVICE(USB_VENDOR_ID_WACOM, 0xBB) },
 	{ USB_DEVICE(USB_VENDOR_ID_WACOM, 0x3F) },
 	{ USB_DEVICE(USB_VENDOR_ID_WACOM, 0xC5) },
 	{ USB_DEVICE(USB_VENDOR_ID_WACOM, 0xC6) },
diff --git a/drivers/input/tablet/wacom_wac.h b/drivers/input/tablet/wacom_wac.h
index f9c8b69..c10235a 100644
--- a/drivers/input/tablet/wacom_wac.h
+++ b/drivers/input/tablet/wacom_wac.h
@@ -25,6 +25,9 @@
 	INTUOS3S,
 	INTUOS3,
 	INTUOS3L,
+	INTUOS4S,
+	INTUOS4,
+	INTUOS4L,
 	CINTIQ,
 	WACOM_BEE,
 	WACOM_MO,
diff --git a/drivers/input/touchscreen/Kconfig b/drivers/input/touchscreen/Kconfig
index b01fd61d..72e2712 100644
--- a/drivers/input/touchscreen/Kconfig
+++ b/drivers/input/touchscreen/Kconfig
@@ -111,6 +111,15 @@
 	  Say Y here to enable the support for the touchscreen found
 	  on Dialog Semiconductor DA9034 PMIC.
 
+config TOUCHSCREEN_EETI
+	tristate "EETI touchscreen panel support"
+	depends on I2C
+	help
+	  Say Y here to enable support for I2C connected EETI touch panels.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called eeti_ts.
+
 config TOUCHSCREEN_FUJITSU
 	tristate "Fujitsu serial touchscreen"
 	select SERIO
@@ -341,6 +350,21 @@
 	  Say Y here to enable support for the Wolfson Microelectronics
 	  WM9713 touchscreen controller.
 
+config TOUCHSCREEN_WM97XX_ATMEL
+	tristate "WM97xx Atmel accelerated touch"
+	depends on TOUCHSCREEN_WM97XX && (AVR32 || ARCH_AT91)
+	help
+	  Say Y here for support for streaming mode with WM97xx touchscreens
+	  on Atmel AT91 or AVR32 systems with an AC97C module.
+
+	  Be aware that this will use channel B in the controller for
+	  streaming data, this must not conflict with other AC97C drivers.
+
+	  If unsure, say N.
+
+	  To compile this driver as a module, choose M here: the module will
+	  be called atmel-wm97xx.
+
 config TOUCHSCREEN_WM97XX_MAINSTONE
 	tristate "WM97xx Mainstone accelerated touch"
 	depends on TOUCHSCREEN_WM97XX && ARCH_PXA
@@ -466,4 +490,12 @@
 	  To compile this driver as a module, choose M here: the
 	  module will be called tsc2007.
 
+config TOUCHSCREEN_W90X900
+	tristate "W90P910 touchscreen driver"
+	help
+	  Say Y here if you have a W90P910 based touchscreen.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called w90p910_ts.
+
 endif
diff --git a/drivers/input/touchscreen/Makefile b/drivers/input/touchscreen/Makefile
index 6700f7b9..3e1c5e0 100644
--- a/drivers/input/touchscreen/Makefile
+++ b/drivers/input/touchscreen/Makefile
@@ -13,6 +13,7 @@
 obj-$(CONFIG_TOUCHSCREEN_BITSY)		+= h3600_ts_input.o
 obj-$(CONFIG_TOUCHSCREEN_CORGI)		+= corgi_ts.o
 obj-$(CONFIG_TOUCHSCREEN_GUNZE)		+= gunze.o
+obj-$(CONFIG_TOUCHSCREEN_EETI)		+= eeti_ts.o
 obj-$(CONFIG_TOUCHSCREEN_ELO)		+= elo.o
 obj-$(CONFIG_TOUCHSCREEN_FUJITSU)	+= fujitsu_ts.o
 obj-$(CONFIG_TOUCHSCREEN_INEXIO)	+= inexio.o
@@ -35,5 +36,7 @@
 wm97xx-ts-$(CONFIG_TOUCHSCREEN_WM9705)	+= wm9705.o
 wm97xx-ts-$(CONFIG_TOUCHSCREEN_WM9712)	+= wm9712.o
 wm97xx-ts-$(CONFIG_TOUCHSCREEN_WM9713)	+= wm9713.o
+obj-$(CONFIG_TOUCHSCREEN_WM97XX_ATMEL)	+= atmel-wm97xx.o
 obj-$(CONFIG_TOUCHSCREEN_WM97XX_MAINSTONE)	+= mainstone-wm97xx.o
 obj-$(CONFIG_TOUCHSCREEN_WM97XX_ZYLONITE)	+= zylonite-wm97xx.o
+obj-$(CONFIG_TOUCHSCREEN_W90X900)	+= w90p910_ts.o
diff --git a/drivers/input/touchscreen/ads7846.c b/drivers/input/touchscreen/ads7846.c
index 2b01e56..ba9d38c 100644
--- a/drivers/input/touchscreen/ads7846.c
+++ b/drivers/input/touchscreen/ads7846.c
@@ -83,6 +83,7 @@
 struct ads7846 {
 	struct input_dev	*input;
 	char			phys[32];
+	char			name[32];
 
 	struct spi_device	*spi;
 
@@ -97,6 +98,8 @@
 	u16			x_plate_ohms;
 	u16			pressure_max;
 
+	bool			swap_xy;
+
 	struct ads7846_packet	*packet;
 
 	struct spi_transfer	xfer[18];
@@ -599,6 +602,10 @@
 			dev_dbg(&ts->spi->dev, "DOWN\n");
 #endif
 		}
+
+		if (ts->swap_xy)
+			swap(x, y);
+
 		input_report_abs(input, ABS_X, x);
 		input_report_abs(input, ABS_Y, y);
 		input_report_abs(input, ABS_PRESSURE, Rt);
@@ -917,6 +924,7 @@
 	ts->spi = spi;
 	ts->input = input_dev;
 	ts->vref_mv = pdata->vref_mv;
+	ts->swap_xy = pdata->swap_xy;
 
 	hrtimer_init(&ts->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
 	ts->timer.function = ads7846_timer;
@@ -958,8 +966,9 @@
 	ts->wait_for_sync = pdata->wait_for_sync ? : null_wait_for_sync;
 
 	snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(&spi->dev));
+	snprintf(ts->name, sizeof(ts->name), "ADS%d Touchscreen", ts->model);
 
-	input_dev->name = "ADS784x Touchscreen";
+	input_dev->name = ts->name;
 	input_dev->phys = ts->phys;
 	input_dev->dev.parent = &spi->dev;
 
@@ -1141,9 +1150,15 @@
 
 	if (request_irq(spi->irq, ads7846_irq, IRQF_TRIGGER_FALLING,
 			spi->dev.driver->name, ts)) {
-		dev_dbg(&spi->dev, "irq %d busy?\n", spi->irq);
-		err = -EBUSY;
-		goto err_free_gpio;
+		dev_info(&spi->dev,
+			"trying pin change workaround on irq %d\n", spi->irq);
+		err = request_irq(spi->irq, ads7846_irq,
+				  IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING,
+				  spi->dev.driver->name, ts);
+		if (err) {
+			dev_dbg(&spi->dev, "irq %d busy?\n", spi->irq);
+			goto err_free_gpio;
+		}
 	}
 
 	err = ads784x_hwmon_register(spi, ts);
diff --git a/drivers/input/touchscreen/atmel-wm97xx.c b/drivers/input/touchscreen/atmel-wm97xx.c
new file mode 100644
index 0000000..35377f5
--- /dev/null
+++ b/drivers/input/touchscreen/atmel-wm97xx.c
@@ -0,0 +1,446 @@
+/*
+ * Atmel AT91 and AVR32 continuous touch screen driver for Wolfson WM97xx AC97
+ * codecs.
+ *
+ * Copyright (C) 2008 - 2009 Atmel Corporation
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 as published by
+ * the Free Software Foundation.
+ */
+#include <linux/module.h>
+#include <linux/moduleparam.h>
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/delay.h>
+#include <linux/irq.h>
+#include <linux/interrupt.h>
+#include <linux/wm97xx.h>
+#include <linux/timer.h>
+#include <linux/gpio.h>
+#include <linux/io.h>
+
+#define AC97C_ICA		0x10
+#define AC97C_CBRHR		0x30
+#define AC97C_CBSR		0x38
+#define AC97C_CBMR		0x3c
+#define AC97C_IER		0x54
+#define AC97C_IDR		0x58
+
+#define AC97C_RXRDY		(1 << 4)
+#define AC97C_OVRUN		(1 << 5)
+
+#define AC97C_CMR_SIZE_20	(0 << 16)
+#define AC97C_CMR_SIZE_18	(1 << 16)
+#define AC97C_CMR_SIZE_16	(2 << 16)
+#define AC97C_CMR_SIZE_10	(3 << 16)
+#define AC97C_CMR_CEM_LITTLE	(1 << 18)
+#define AC97C_CMR_CEM_BIG	(0 << 18)
+#define AC97C_CMR_CENA		(1 << 21)
+
+#define AC97C_INT_CBEVT		(1 << 4)
+
+#define AC97C_SR_CAEVT		(1 << 3)
+
+#define AC97C_CH_MASK(slot)						\
+	(0x7 << (3 * (slot - 3)))
+#define AC97C_CH_ASSIGN(slot, channel)					\
+	(AC97C_CHANNEL_##channel << (3 * (slot - 3)))
+#define AC97C_CHANNEL_NONE	0x0
+#define AC97C_CHANNEL_B		0x2
+
+#define ac97c_writel(chip, reg, val)			\
+	__raw_writel((val), (chip)->regs + AC97C_##reg)
+#define ac97c_readl(chip, reg)				\
+	__raw_readl((chip)->regs + AC97C_##reg)
+
+#ifdef CONFIG_CPU_AT32AP700X
+#define ATMEL_WM97XX_AC97C_IOMEM	(0xfff02800)
+#define ATMEL_WM97XX_AC97C_IRQ		(29)
+#define ATMEL_WM97XX_GPIO_DEFAULT	(32+16) /* Pin 16 on port B. */
+#else
+#error Unkown CPU, this driver only supports AT32AP700X CPUs.
+#endif
+
+struct continuous {
+	u16 id;    /* codec id */
+	u8 code;   /* continuous code */
+	u8 reads;  /* number of coord reads per read cycle */
+	u32 speed; /* number of coords per second */
+};
+
+#define WM_READS(sp) ((sp / HZ) + 1)
+
+static const struct continuous cinfo[] = {
+	{WM9705_ID2, 0, WM_READS(94), 94},
+	{WM9705_ID2, 1, WM_READS(188), 188},
+	{WM9705_ID2, 2, WM_READS(375), 375},
+	{WM9705_ID2, 3, WM_READS(750), 750},
+	{WM9712_ID2, 0, WM_READS(94), 94},
+	{WM9712_ID2, 1, WM_READS(188), 188},
+	{WM9712_ID2, 2, WM_READS(375), 375},
+	{WM9712_ID2, 3, WM_READS(750), 750},
+	{WM9713_ID2, 0, WM_READS(94), 94},
+	{WM9713_ID2, 1, WM_READS(120), 120},
+	{WM9713_ID2, 2, WM_READS(154), 154},
+	{WM9713_ID2, 3, WM_READS(188), 188},
+};
+
+/* Continuous speed index. */
+static int sp_idx;
+
+/*
+ * Pen sampling frequency (Hz) in continuous mode.
+ */
+static int cont_rate = 188;
+module_param(cont_rate, int, 0);
+MODULE_PARM_DESC(cont_rate, "Sampling rate in continuous mode (Hz)");
+
+/*
+ * Pen down detection.
+ *
+ * This driver can either poll or use an interrupt to indicate a pen down
+ * event. If the irq request fails then it will fall back to polling mode.
+ */
+static int pen_int = 1;
+module_param(pen_int, int, 0);
+MODULE_PARM_DESC(pen_int, "Pen down detection (1 = interrupt, 0 = polling)");
+
+/*
+ * Pressure readback.
+ *
+ * Set to 1 to read back pen down pressure.
+ */
+static int pressure;
+module_param(pressure, int, 0);
+MODULE_PARM_DESC(pressure, "Pressure readback (1 = pressure, 0 = no pressure)");
+
+/*
+ * AC97 touch data slot.
+ *
+ * Touch screen readback data ac97 slot.
+ */
+static int ac97_touch_slot = 5;
+module_param(ac97_touch_slot, int, 0);
+MODULE_PARM_DESC(ac97_touch_slot, "Touch screen data slot AC97 number");
+
+/*
+ * GPIO line number.
+ *
+ * Set to GPIO number where the signal from the WM97xx device is hooked up.
+ */
+static int atmel_gpio_line = ATMEL_WM97XX_GPIO_DEFAULT;
+module_param(atmel_gpio_line, int, 0);
+MODULE_PARM_DESC(atmel_gpio_line, "GPIO line number connected to WM97xx");
+
+struct atmel_wm97xx {
+	struct wm97xx		*wm;
+	struct timer_list	pen_timer;
+	void __iomem		*regs;
+	unsigned long		ac97c_irq;
+	unsigned long		gpio_pen;
+	unsigned long		gpio_irq;
+	unsigned short		x;
+	unsigned short		y;
+};
+
+static irqreturn_t atmel_wm97xx_channel_b_interrupt(int irq, void *dev_id)
+{
+	struct atmel_wm97xx *atmel_wm97xx = dev_id;
+	struct wm97xx *wm = atmel_wm97xx->wm;
+	int status = ac97c_readl(atmel_wm97xx, CBSR);
+	irqreturn_t retval = IRQ_NONE;
+
+	if (status & AC97C_OVRUN) {
+		dev_dbg(&wm->touch_dev->dev, "AC97C overrun\n");
+		ac97c_readl(atmel_wm97xx, CBRHR);
+		retval = IRQ_HANDLED;
+	} else if (status & AC97C_RXRDY) {
+		u16 data;
+		u16 value;
+		u16 source;
+		u16 pen_down;
+
+		data = ac97c_readl(atmel_wm97xx, CBRHR);
+		value = data & 0x0fff;
+		source = data & WM97XX_ADCSRC_MASK;
+		pen_down = (data & WM97XX_PEN_DOWN) >> 8;
+
+		if (source == WM97XX_ADCSEL_X)
+			atmel_wm97xx->x = value;
+		if (source == WM97XX_ADCSEL_Y)
+			atmel_wm97xx->y = value;
+
+		if (!pressure && source == WM97XX_ADCSEL_Y) {
+			input_report_abs(wm->input_dev, ABS_X, atmel_wm97xx->x);
+			input_report_abs(wm->input_dev, ABS_Y, atmel_wm97xx->y);
+			input_report_key(wm->input_dev, BTN_TOUCH, pen_down);
+			input_sync(wm->input_dev);
+		} else if (pressure && source == WM97XX_ADCSEL_PRES) {
+			input_report_abs(wm->input_dev, ABS_X, atmel_wm97xx->x);
+			input_report_abs(wm->input_dev, ABS_Y, atmel_wm97xx->y);
+			input_report_abs(wm->input_dev, ABS_PRESSURE, value);
+			input_report_key(wm->input_dev, BTN_TOUCH, value);
+			input_sync(wm->input_dev);
+		}
+
+		retval = IRQ_HANDLED;
+	}
+
+	return retval;
+}
+
+static void atmel_wm97xx_acc_pen_up(struct wm97xx *wm)
+{
+	struct atmel_wm97xx *atmel_wm97xx = platform_get_drvdata(wm->touch_dev);
+	struct input_dev *input_dev = wm->input_dev;
+	int pen_down = gpio_get_value(atmel_wm97xx->gpio_pen);
+
+	if (pen_down != 0) {
+		mod_timer(&atmel_wm97xx->pen_timer,
+			  jiffies + msecs_to_jiffies(1));
+	} else {
+		if (pressure)
+			input_report_abs(input_dev, ABS_PRESSURE, 0);
+		input_report_key(input_dev, BTN_TOUCH, 0);
+		input_sync(input_dev);
+	}
+}
+
+static void atmel_wm97xx_pen_timer(unsigned long data)
+{
+	atmel_wm97xx_acc_pen_up((struct wm97xx *)data);
+}
+
+static int atmel_wm97xx_acc_startup(struct wm97xx *wm)
+{
+	struct atmel_wm97xx *atmel_wm97xx = platform_get_drvdata(wm->touch_dev);
+	int idx = 0;
+
+	if (wm->ac97 == NULL)
+		return -ENODEV;
+
+	for (idx = 0; idx < ARRAY_SIZE(cinfo); idx++) {
+		if (wm->id != cinfo[idx].id)
+			continue;
+
+		sp_idx = idx;
+
+		if (cont_rate <= cinfo[idx].speed)
+			break;
+	}
+
+	wm->acc_rate = cinfo[sp_idx].code;
+	wm->acc_slot = ac97_touch_slot;
+	dev_info(&wm->touch_dev->dev, "atmel accelerated touchscreen driver, "
+			"%d samples/sec\n", cinfo[sp_idx].speed);
+
+	if (pen_int) {
+		unsigned long reg;
+
+		wm->pen_irq = atmel_wm97xx->gpio_irq;
+
+		switch (wm->id) {
+		case WM9712_ID2: /* Fall through. */
+		case WM9713_ID2:
+			/*
+			 * Use GPIO 13 (PEN_DOWN) to assert GPIO line 3
+			 * (PENDOWN).
+			 */
+			wm97xx_config_gpio(wm, WM97XX_GPIO_13, WM97XX_GPIO_IN,
+					WM97XX_GPIO_POL_HIGH,
+					WM97XX_GPIO_STICKY,
+					WM97XX_GPIO_WAKE);
+			wm97xx_config_gpio(wm, WM97XX_GPIO_3, WM97XX_GPIO_OUT,
+					WM97XX_GPIO_POL_HIGH,
+					WM97XX_GPIO_NOTSTICKY,
+					WM97XX_GPIO_NOWAKE);
+		case WM9705_ID2: /* Fall through. */
+			/*
+			 * Enable touch data slot in AC97 controller channel B.
+			 */
+			reg = ac97c_readl(atmel_wm97xx, ICA);
+			reg &= ~AC97C_CH_MASK(wm->acc_slot);
+			reg |= AC97C_CH_ASSIGN(wm->acc_slot, B);
+			ac97c_writel(atmel_wm97xx, ICA, reg);
+
+			/*
+			 * Enable channel and interrupt for RXRDY and OVERRUN.
+			 */
+			ac97c_writel(atmel_wm97xx, CBMR, AC97C_CMR_CENA
+					| AC97C_CMR_CEM_BIG
+					| AC97C_CMR_SIZE_16
+					| AC97C_OVRUN
+					| AC97C_RXRDY);
+			/* Dummy read to empty RXRHR. */
+			ac97c_readl(atmel_wm97xx, CBRHR);
+			/*
+			 * Enable interrupt for channel B in the AC97
+			 * controller.
+			 */
+			ac97c_writel(atmel_wm97xx, IER, AC97C_INT_CBEVT);
+			break;
+		default:
+			dev_err(&wm->touch_dev->dev, "pen down irq not "
+					"supported on this device\n");
+			pen_int = 0;
+			break;
+		}
+	}
+
+	return 0;
+}
+
+static void atmel_wm97xx_acc_shutdown(struct wm97xx *wm)
+{
+	if (pen_int) {
+		struct atmel_wm97xx *atmel_wm97xx =
+			platform_get_drvdata(wm->touch_dev);
+		unsigned long ica;
+
+		switch (wm->id & 0xffff) {
+		case WM9705_ID2: /* Fall through. */
+		case WM9712_ID2: /* Fall through. */
+		case WM9713_ID2:
+			/* Disable slot and turn off channel B interrupts. */
+			ica = ac97c_readl(atmel_wm97xx, ICA);
+			ica &= ~AC97C_CH_MASK(wm->acc_slot);
+			ac97c_writel(atmel_wm97xx, ICA, ica);
+			ac97c_writel(atmel_wm97xx, IDR, AC97C_INT_CBEVT);
+			ac97c_writel(atmel_wm97xx, CBMR, 0);
+			wm->pen_irq = 0;
+			break;
+		default:
+			dev_err(&wm->touch_dev->dev, "unknown codec\n");
+			break;
+		}
+	}
+}
+
+static void atmel_wm97xx_irq_enable(struct wm97xx *wm, int enable)
+{
+	/* Intentionally left empty. */
+}
+
+static struct wm97xx_mach_ops atmel_mach_ops = {
+	.acc_enabled	= 1,
+	.acc_pen_up	= atmel_wm97xx_acc_pen_up,
+	.acc_startup	= atmel_wm97xx_acc_startup,
+	.acc_shutdown	= atmel_wm97xx_acc_shutdown,
+	.irq_enable	= atmel_wm97xx_irq_enable,
+	.irq_gpio	= WM97XX_GPIO_3,
+};
+
+static int __init atmel_wm97xx_probe(struct platform_device *pdev)
+{
+	struct wm97xx *wm = platform_get_drvdata(pdev);
+	struct atmel_wm97xx *atmel_wm97xx;
+	int ret;
+
+	atmel_wm97xx = kzalloc(sizeof(struct atmel_wm97xx), GFP_KERNEL);
+	if (!atmel_wm97xx) {
+		dev_dbg(&pdev->dev, "out of memory\n");
+		return -ENOMEM;
+	}
+
+	atmel_wm97xx->wm	= wm;
+	atmel_wm97xx->regs	= (void *)ATMEL_WM97XX_AC97C_IOMEM;
+	atmel_wm97xx->ac97c_irq	= ATMEL_WM97XX_AC97C_IRQ;
+	atmel_wm97xx->gpio_pen	= atmel_gpio_line;
+	atmel_wm97xx->gpio_irq	= gpio_to_irq(atmel_wm97xx->gpio_pen);
+
+	setup_timer(&atmel_wm97xx->pen_timer, atmel_wm97xx_pen_timer,
+			(unsigned long)wm);
+
+	ret = request_irq(atmel_wm97xx->ac97c_irq,
+			  atmel_wm97xx_channel_b_interrupt,
+			  IRQF_SHARED, "atmel-wm97xx-ch-b", atmel_wm97xx);
+	if (ret) {
+		dev_dbg(&pdev->dev, "could not request ac97c irq\n");
+		goto err;
+	}
+
+	platform_set_drvdata(pdev, atmel_wm97xx);
+
+	ret = wm97xx_register_mach_ops(wm, &atmel_mach_ops);
+	if (ret)
+		goto err_irq;
+
+	return ret;
+
+err_irq:
+	free_irq(atmel_wm97xx->ac97c_irq, atmel_wm97xx);
+err:
+	platform_set_drvdata(pdev, NULL);
+	kfree(atmel_wm97xx);
+	return ret;
+}
+
+static int __exit atmel_wm97xx_remove(struct platform_device *pdev)
+{
+	struct atmel_wm97xx *atmel_wm97xx = platform_get_drvdata(pdev);
+	struct wm97xx *wm = atmel_wm97xx->wm;
+
+	ac97c_writel(atmel_wm97xx, IDR, AC97C_INT_CBEVT);
+	free_irq(atmel_wm97xx->ac97c_irq, atmel_wm97xx);
+	del_timer_sync(&atmel_wm97xx->pen_timer);
+	wm97xx_unregister_mach_ops(wm);
+	platform_set_drvdata(pdev, NULL);
+	kfree(atmel_wm97xx);
+
+	return 0;
+}
+
+#ifdef CONFIG_PM
+static int atmel_wm97xx_suspend(struct platform_device *pdev, pm_message_t msg)
+{
+	struct atmel_wm97xx *atmel_wm97xx = platform_get_drvdata(pdev);
+
+	ac97c_writel(atmel_wm97xx, IDR, AC97C_INT_CBEVT);
+	disable_irq(atmel_wm97xx->gpio_irq);
+	del_timer_sync(&atmel_wm97xx->pen_timer);
+
+	return 0;
+}
+
+static int atmel_wm97xx_resume(struct platform_device *pdev)
+{
+	struct atmel_wm97xx *atmel_wm97xx = platform_get_drvdata(pdev);
+	struct wm97xx *wm = atmel_wm97xx->wm;
+
+	if (wm->input_dev->users) {
+		enable_irq(atmel_wm97xx->gpio_irq);
+		ac97c_writel(atmel_wm97xx, IER, AC97C_INT_CBEVT);
+	}
+
+	return 0;
+}
+#else
+#define atmel_wm97xx_suspend	NULL
+#define atmel_wm97xx_resume	NULL
+#endif
+
+static struct platform_driver atmel_wm97xx_driver = {
+	.remove		= __exit_p(atmel_wm97xx_remove),
+	.driver		= {
+		.name = "wm97xx-touch",
+	},
+	.suspend	= atmel_wm97xx_suspend,
+	.resume		= atmel_wm97xx_resume,
+};
+
+static int __init atmel_wm97xx_init(void)
+{
+	return platform_driver_probe(&atmel_wm97xx_driver, atmel_wm97xx_probe);
+}
+module_init(atmel_wm97xx_init);
+
+static void __exit atmel_wm97xx_exit(void)
+{
+	platform_driver_unregister(&atmel_wm97xx_driver);
+}
+module_exit(atmel_wm97xx_exit);
+
+MODULE_AUTHOR("Hans-Christian Egtvedt <hans-christian.egtvedt@atmel.com>");
+MODULE_DESCRIPTION("wm97xx continuous touch driver for Atmel AT91 and AVR32");
+MODULE_LICENSE("GPL");
diff --git a/drivers/input/touchscreen/eeti_ts.c b/drivers/input/touchscreen/eeti_ts.c
new file mode 100644
index 0000000..3ab9222
--- /dev/null
+++ b/drivers/input/touchscreen/eeti_ts.c
@@ -0,0 +1,286 @@
+/*
+ * Touch Screen driver for EETI's I2C connected touch screen panels
+ *   Copyright (c) 2009 Daniel Mack <daniel@caiaq.de>
+ *
+ * See EETI's software guide for the protocol specification:
+ *   http://home.eeti.com.tw/web20/eg/guide.htm
+ *
+ * Based on migor_ts.c
+ *   Copyright (c) 2008 Magnus Damm
+ *   Copyright (c) 2007 Ujjwal Pande <ujjwal@kenati.com>
+ *
+ * This file is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU  General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This file is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+#include <linux/module.h>
+#include <linux/moduleparam.h>
+#include <linux/kernel.h>
+#include <linux/input.h>
+#include <linux/interrupt.h>
+#include <linux/i2c.h>
+#include <linux/timer.h>
+#include <linux/gpio.h>
+
+static int flip_x;
+module_param(flip_x, bool, 0644);
+MODULE_PARM_DESC(flip_x, "flip x coordinate");
+
+static int flip_y;
+module_param(flip_y, bool, 0644);
+MODULE_PARM_DESC(flip_y, "flip y coordinate");
+
+struct eeti_ts_priv {
+	struct i2c_client *client;
+	struct input_dev *input;
+	struct work_struct work;
+	struct mutex mutex;
+	int irq;
+};
+
+#define EETI_TS_BITDEPTH	(11)
+#define EETI_MAXVAL		((1 << (EETI_TS_BITDEPTH + 1)) - 1)
+
+#define REPORT_BIT_PRESSED	(1 << 0)
+#define REPORT_BIT_AD0		(1 << 1)
+#define REPORT_BIT_AD1		(1 << 2)
+#define REPORT_BIT_HAS_PRESSURE	(1 << 6)
+#define REPORT_RES_BITS(v)	(((v) >> 1) + EETI_TS_BITDEPTH)
+
+static void eeti_ts_read(struct work_struct *work)
+{
+	char buf[6];
+	unsigned int x, y, res, pressed, to = 100;
+	struct eeti_ts_priv *priv =
+		container_of(work, struct eeti_ts_priv, work);
+
+	mutex_lock(&priv->mutex);
+
+	while (!gpio_get_value(irq_to_gpio(priv->irq)) && --to)
+		i2c_master_recv(priv->client, buf, sizeof(buf));
+
+	if (!to) {
+		dev_err(&priv->client->dev,
+			"unable to clear IRQ - line stuck?\n");
+		goto out;
+	}
+
+	/* drop non-report packets */
+	if (!(buf[0] & 0x80))
+		goto out;
+
+	pressed = buf[0] & REPORT_BIT_PRESSED;
+	res = REPORT_RES_BITS(buf[0] & (REPORT_BIT_AD0 | REPORT_BIT_AD1));
+	x = buf[2] | (buf[1] << 8);
+	y = buf[4] | (buf[3] << 8);
+
+	/* fix the range to 11 bits */
+	x >>= res - EETI_TS_BITDEPTH;
+	y >>= res - EETI_TS_BITDEPTH;
+
+	if (flip_x)
+		x = EETI_MAXVAL - x;
+
+	if (flip_y)
+		y = EETI_MAXVAL - y;
+
+	if (buf[0] & REPORT_BIT_HAS_PRESSURE)
+		input_report_abs(priv->input, ABS_PRESSURE, buf[5]);
+
+	input_report_abs(priv->input, ABS_X, x);
+	input_report_abs(priv->input, ABS_Y, y);
+	input_report_key(priv->input, BTN_TOUCH, !!pressed);
+	input_sync(priv->input);
+
+out:
+	mutex_unlock(&priv->mutex);
+}
+
+static irqreturn_t eeti_ts_isr(int irq, void *dev_id)
+{
+	struct eeti_ts_priv *priv = dev_id;
+
+	 /* postpone I2C transactions as we are atomic */
+	schedule_work(&priv->work);
+
+	return IRQ_HANDLED;
+}
+
+static int eeti_ts_open(struct input_dev *dev)
+{
+	struct eeti_ts_priv *priv = input_get_drvdata(dev);
+
+	enable_irq(priv->irq);
+
+	/* Read the events once to arm the IRQ */
+	eeti_ts_read(&priv->work);
+
+	return 0;
+}
+
+static void eeti_ts_close(struct input_dev *dev)
+{
+	struct eeti_ts_priv *priv = input_get_drvdata(dev);
+
+	disable_irq(priv->irq);
+	cancel_work_sync(&priv->work);
+}
+
+static int __devinit eeti_ts_probe(struct i2c_client *client,
+				   const struct i2c_device_id *idp)
+{
+	struct eeti_ts_priv *priv;
+	struct input_dev *input;
+	int err = -ENOMEM;
+
+	/* In contrast to what's described in the datasheet, there seems
+	 * to be no way of probing the presence of that device using I2C
+	 * commands. So we need to blindly believe it is there, and wait
+	 * for interrupts to occur. */
+
+	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
+	if (!priv) {
+		dev_err(&client->dev, "failed to allocate driver data\n");
+		goto err0;
+	}
+
+	mutex_init(&priv->mutex);
+	input = input_allocate_device();
+
+	if (!input) {
+		dev_err(&client->dev, "Failed to allocate input device.\n");
+		goto err1;
+	}
+
+	input->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
+	input->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
+
+	input_set_abs_params(input, ABS_X, 0, EETI_MAXVAL, 0, 0);
+	input_set_abs_params(input, ABS_Y, 0, EETI_MAXVAL, 0, 0);
+	input_set_abs_params(input, ABS_PRESSURE, 0, 0xff, 0, 0);
+
+	input->name = client->name;
+	input->id.bustype = BUS_I2C;
+	input->dev.parent = &client->dev;
+	input->open = eeti_ts_open;
+	input->close = eeti_ts_close;
+
+	priv->client = client;
+	priv->input = input;
+	priv->irq = client->irq;
+
+	INIT_WORK(&priv->work, eeti_ts_read);
+	i2c_set_clientdata(client, priv);
+	input_set_drvdata(input, priv);
+
+	err = input_register_device(input);
+	if (err)
+		goto err1;
+
+	err = request_irq(priv->irq, eeti_ts_isr, IRQF_TRIGGER_FALLING,
+			  client->name, priv);
+	if (err) {
+		dev_err(&client->dev, "Unable to request touchscreen IRQ.\n");
+		goto err2;
+	}
+
+	/* Disable the irq for now. It will be enabled once the input device
+	 * is opened. */
+	disable_irq(priv->irq);
+
+	device_init_wakeup(&client->dev, 0);
+	return 0;
+
+err2:
+	input_unregister_device(input);
+	input = NULL; /* so we dont try to free it below */
+err1:
+	input_free_device(input);
+	i2c_set_clientdata(client, NULL);
+	kfree(priv);
+err0:
+	return err;
+}
+
+static int __devexit eeti_ts_remove(struct i2c_client *client)
+{
+	struct eeti_ts_priv *priv = i2c_get_clientdata(client);
+
+	free_irq(priv->irq, priv);
+	input_unregister_device(priv->input);
+	i2c_set_clientdata(client, NULL);
+	kfree(priv);
+
+	return 0;
+}
+
+#ifdef CONFIG_PM
+static int eeti_ts_suspend(struct i2c_client *client, pm_message_t mesg)
+{
+	struct eeti_ts_priv *priv = i2c_get_clientdata(client);
+
+	if (device_may_wakeup(&client->dev))
+		enable_irq_wake(priv->irq);
+
+	return 0;
+}
+
+static int eeti_ts_resume(struct i2c_client *client)
+{
+	struct eeti_ts_priv *priv = i2c_get_clientdata(client);
+
+	if (device_may_wakeup(&client->dev))
+		disable_irq_wake(priv->irq);
+
+	return 0;
+}
+#else
+#define eeti_ts_suspend NULL
+#define eeti_ts_resume NULL
+#endif
+
+static const struct i2c_device_id eeti_ts_id[] = {
+	{ "eeti_ts", 0 },
+	{ }
+};
+MODULE_DEVICE_TABLE(i2c, eeti_ts_id);
+
+static struct i2c_driver eeti_ts_driver = {
+	.driver = {
+		.name = "eeti_ts",
+	},
+	.probe = eeti_ts_probe,
+	.remove = __devexit_p(eeti_ts_remove),
+	.suspend = eeti_ts_suspend,
+	.resume = eeti_ts_resume,
+	.id_table = eeti_ts_id,
+};
+
+static int __init eeti_ts_init(void)
+{
+	return i2c_add_driver(&eeti_ts_driver);
+}
+
+static void __exit eeti_ts_exit(void)
+{
+	i2c_del_driver(&eeti_ts_driver);
+}
+
+MODULE_DESCRIPTION("EETI Touchscreen driver");
+MODULE_AUTHOR("Daniel Mack <daniel@caiaq.de>");
+MODULE_LICENSE("GPL");
+
+module_init(eeti_ts_init);
+module_exit(eeti_ts_exit);
+
diff --git a/drivers/input/touchscreen/tsc2007.c b/drivers/input/touchscreen/tsc2007.c
index 948e167..880f58c 100644
--- a/drivers/input/touchscreen/tsc2007.c
+++ b/drivers/input/touchscreen/tsc2007.c
@@ -257,7 +257,7 @@
 	struct input_dev *input_dev;
 	int err;
 
-	if (!pdata) {
+	if (!pdata || !pdata->get_pendown_state) {
 		dev_err(&client->dev, "platform data is required!\n");
 		return -EINVAL;
 	}
diff --git a/drivers/input/touchscreen/w90p910_ts.c b/drivers/input/touchscreen/w90p910_ts.c
new file mode 100644
index 0000000..6071f58
--- /dev/null
+++ b/drivers/input/touchscreen/w90p910_ts.c
@@ -0,0 +1,350 @@
+/*
+ * Copyright (c) 2008 Nuvoton technology corporation.
+ *
+ * Wan ZongShun <mcuos.com@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation;version 2 of the License.
+ *
+ */
+
+#include <linux/delay.h>
+#include <linux/module.h>
+#include <linux/platform_device.h>
+#include <linux/io.h>
+#include <linux/input.h>
+#include <linux/interrupt.h>
+
+/* ADC controller bit defines */
+#define ADC_DELAY	0xf00
+#define ADC_DOWN	0x01
+#define ADC_TSC_Y	(0x01 << 8)
+#define ADC_TSC_X	(0x00 << 8)
+#define TSC_FOURWIRE	(~(0x03 << 1))
+#define ADC_CLK_EN	(0x01 << 28)	/* ADC clock enable */
+#define ADC_READ_CON	(0x01 << 12)
+#define ADC_CONV	(0x01 << 13)
+#define ADC_SEMIAUTO	(0x01 << 14)
+#define ADC_WAITTRIG	(0x03 << 14)
+#define ADC_RST1	(0x01 << 16)
+#define ADC_RST0	(0x00 << 16)
+#define ADC_EN		(0x01 << 17)
+#define ADC_INT		(0x01 << 18)
+#define WT_INT		(0x01 << 20)
+#define ADC_INT_EN	(0x01 << 21)
+#define LVD_INT_EN	(0x01 << 22)
+#define WT_INT_EN	(0x01 << 23)
+#define ADC_DIV		(0x04 << 1)	/* div = 6 */
+
+enum ts_state {
+	TS_WAIT_NEW_PACKET,	/* We are waiting next touch report */
+	TS_WAIT_X_COORD,	/* We are waiting for ADC to report X coord */
+	TS_WAIT_Y_COORD,	/* We are waiting for ADC to report Y coord */
+	TS_IDLE,		/* Input device is closed, don't do anything */
+};
+
+struct w90p910_ts {
+	struct input_dev *input;
+	struct timer_list timer;
+	int irq_num;
+	void __iomem *clocken;
+	void __iomem *ts_reg;
+	spinlock_t lock;
+	enum ts_state state;
+};
+
+static void w90p910_report_event(struct w90p910_ts *w90p910_ts, bool down)
+{
+	struct input_dev *dev = w90p910_ts->input;
+
+	if (down) {
+		input_report_abs(dev, ABS_X,
+				 __raw_readl(w90p910_ts->ts_reg + 0x0c));
+		input_report_abs(dev, ABS_Y,
+				 __raw_readl(w90p910_ts->ts_reg + 0x10));
+	}
+
+	input_report_key(dev, BTN_TOUCH, down);
+	input_sync(dev);
+}
+
+static void w90p910_prepare_x_reading(struct w90p910_ts *w90p910_ts)
+{
+	unsigned long ctlreg;
+
+	__raw_writel(ADC_TSC_X, w90p910_ts->ts_reg + 0x04);
+	ctlreg = __raw_readl(w90p910_ts->ts_reg);
+	ctlreg &= ~(ADC_WAITTRIG | WT_INT | WT_INT_EN);
+	ctlreg |= ADC_SEMIAUTO | ADC_INT_EN | ADC_CONV;
+	__raw_writel(ctlreg, w90p910_ts->ts_reg);
+
+	w90p910_ts->state = TS_WAIT_X_COORD;
+}
+
+static void w90p910_prepare_y_reading(struct w90p910_ts *w90p910_ts)
+{
+	unsigned long ctlreg;
+
+	__raw_writel(ADC_TSC_Y, w90p910_ts->ts_reg + 0x04);
+	ctlreg = __raw_readl(w90p910_ts->ts_reg);
+	ctlreg &= ~(ADC_WAITTRIG | ADC_INT | WT_INT_EN);
+	ctlreg |= ADC_SEMIAUTO | ADC_INT_EN | ADC_CONV;
+	__raw_writel(ctlreg, w90p910_ts->ts_reg);
+
+	w90p910_ts->state = TS_WAIT_Y_COORD;
+}
+
+static void w90p910_prepare_next_packet(struct w90p910_ts *w90p910_ts)
+{
+	unsigned long ctlreg;
+
+	ctlreg = __raw_readl(w90p910_ts->ts_reg);
+	ctlreg &= ~(ADC_INT | ADC_INT_EN | ADC_SEMIAUTO | ADC_CONV);
+	ctlreg |= ADC_WAITTRIG | WT_INT_EN;
+	__raw_writel(ctlreg, w90p910_ts->ts_reg);
+
+	w90p910_ts->state = TS_WAIT_NEW_PACKET;
+}
+
+static irqreturn_t w90p910_ts_interrupt(int irq, void *dev_id)
+{
+	struct w90p910_ts *w90p910_ts = dev_id;
+	unsigned long flags;
+
+	spin_lock_irqsave(&w90p910_ts->lock, flags);
+
+	switch (w90p910_ts->state) {
+	case TS_WAIT_NEW_PACKET:
+		/*
+		 * The controller only generates interrupts when pen
+		 * is down.
+		 */
+		del_timer(&w90p910_ts->timer);
+		w90p910_prepare_x_reading(w90p910_ts);
+		break;
+
+
+	case TS_WAIT_X_COORD:
+		w90p910_prepare_y_reading(w90p910_ts);
+		break;
+
+	case TS_WAIT_Y_COORD:
+		w90p910_report_event(w90p910_ts, true);
+		w90p910_prepare_next_packet(w90p910_ts);
+		mod_timer(&w90p910_ts->timer, jiffies + msecs_to_jiffies(100));
+		break;
+
+	case TS_IDLE:
+		break;
+	}
+
+	spin_unlock_irqrestore(&w90p910_ts->lock, flags);
+
+	return IRQ_HANDLED;
+}
+
+static void w90p910_check_pen_up(unsigned long data)
+{
+	struct w90p910_ts *w90p910_ts = (struct w90p910_ts *) data;
+	unsigned long flags;
+
+	spin_lock_irqsave(&w90p910_ts->lock, flags);
+
+	if (w90p910_ts->state == TS_WAIT_NEW_PACKET &&
+	    !(__raw_readl(w90p910_ts->ts_reg + 0x04) & ADC_DOWN)) {
+
+		w90p910_report_event(w90p910_ts, false);
+	}
+
+	spin_unlock_irqrestore(&w90p910_ts->lock, flags);
+}
+
+static int w90p910_open(struct input_dev *dev)
+{
+	struct w90p910_ts *w90p910_ts = input_get_drvdata(dev);
+	unsigned long val;
+
+	/* enable the ADC clock */
+	val = __raw_readl(w90p910_ts->clocken);
+	__raw_writel(val | ADC_CLK_EN, w90p910_ts->clocken);
+
+	__raw_writel(ADC_RST1, w90p910_ts->ts_reg);
+	msleep(1);
+	__raw_writel(ADC_RST0, w90p910_ts->ts_reg);
+	msleep(1);
+
+	/* set delay and screen type */
+	val = __raw_readl(w90p910_ts->ts_reg + 0x04);
+	__raw_writel(val & TSC_FOURWIRE, w90p910_ts->ts_reg + 0x04);
+	__raw_writel(ADC_DELAY, w90p910_ts->ts_reg + 0x08);
+
+	w90p910_ts->state = TS_WAIT_NEW_PACKET;
+	wmb();
+
+	/* set trigger mode */
+	val = __raw_readl(w90p910_ts->ts_reg);
+	val |= ADC_WAITTRIG | ADC_DIV | ADC_EN | WT_INT_EN;
+	__raw_writel(val, w90p910_ts->ts_reg);
+
+	return 0;
+}
+
+static void w90p910_close(struct input_dev *dev)
+{
+	struct w90p910_ts *w90p910_ts = input_get_drvdata(dev);
+	unsigned long val;
+
+	/* disable trigger mode */
+
+	spin_lock_irq(&w90p910_ts->lock);
+
+	w90p910_ts->state = TS_IDLE;
+
+	val = __raw_readl(w90p910_ts->ts_reg);
+	val &= ~(ADC_WAITTRIG | ADC_DIV | ADC_EN | WT_INT_EN | ADC_INT_EN);
+	__raw_writel(val, w90p910_ts->ts_reg);
+
+	spin_unlock_irq(&w90p910_ts->lock);
+
+	/* Now that interrupts are shut off we can safely delete timer */
+	del_timer_sync(&w90p910_ts->timer);
+
+	/* stop the ADC clock */
+	val = __raw_readl(w90p910_ts->clocken);
+	__raw_writel(val & ~ADC_CLK_EN, w90p910_ts->clocken);
+}
+
+static int __devinit w90x900ts_probe(struct platform_device *pdev)
+{
+	struct w90p910_ts *w90p910_ts;
+	struct input_dev *input_dev;
+	struct resource *res;
+	int err;
+
+	w90p910_ts = kzalloc(sizeof(struct w90p910_ts), GFP_KERNEL);
+	input_dev = input_allocate_device();
+	if (!w90p910_ts || !input_dev) {
+		err = -ENOMEM;
+		goto fail1;
+	}
+
+	w90p910_ts->input = input_dev;
+	w90p910_ts->state = TS_IDLE;
+	spin_lock_init(&w90p910_ts->lock);
+	setup_timer(&w90p910_ts->timer, w90p910_check_pen_up,
+		    (unsigned long)&w90p910_ts);
+
+	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
+	if (!res) {
+		err = -ENXIO;
+		goto fail1;
+	}
+
+	if (!request_mem_region(res->start, res->end - res->start + 1,
+				pdev->name)) {
+		err = -EBUSY;
+		goto fail1;
+	}
+
+	w90p910_ts->ts_reg = ioremap(res->start, res->end - res->start + 1);
+	if (!w90p910_ts->ts_reg) {
+		err = -ENOMEM;
+		goto fail2;
+	}
+
+	res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
+	if (!res) {
+		err = -ENXIO;
+		goto fail3;
+	}
+
+	w90p910_ts->clocken = (void __iomem *)res->start;
+
+	input_dev->name = "W90P910 TouchScreen";
+	input_dev->phys = "w90p910ts/event0";
+	input_dev->id.bustype = BUS_HOST;
+	input_dev->id.vendor  = 0x0005;
+	input_dev->id.product = 0x0001;
+	input_dev->id.version = 0x0100;
+	input_dev->dev.parent = &pdev->dev;
+	input_dev->open = w90p910_open;
+	input_dev->close = w90p910_close;
+
+	input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
+	input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
+
+	input_set_abs_params(input_dev, ABS_X, 0, 0x400, 0, 0);
+	input_set_abs_params(input_dev, ABS_Y, 0, 0x400, 0, 0);
+
+	input_set_drvdata(input_dev, w90p910_ts);
+
+	w90p910_ts->irq_num = platform_get_irq(pdev, 0);
+	if (request_irq(w90p910_ts->irq_num, w90p910_ts_interrupt,
+			IRQF_DISABLED, "w90p910ts", w90p910_ts)) {
+		err = -EBUSY;
+		goto fail3;
+	}
+
+	err = input_register_device(w90p910_ts->input);
+	if (err)
+		goto fail4;
+
+	platform_set_drvdata(pdev, w90p910_ts);
+
+	return 0;
+
+fail4:	free_irq(w90p910_ts->irq_num, w90p910_ts);
+fail3:	iounmap(w90p910_ts->ts_reg);
+fail2:	release_mem_region(res->start, res->end - res->start + 1);
+fail1:	input_free_device(input_dev);
+	kfree(w90p910_ts);
+	return err;
+}
+
+static int __devexit w90x900ts_remove(struct platform_device *pdev)
+{
+	struct w90p910_ts *w90p910_ts = platform_get_drvdata(pdev);
+	struct resource *res;
+
+	free_irq(w90p910_ts->irq_num, w90p910_ts);
+	del_timer_sync(&w90p910_ts->timer);
+	iounmap(w90p910_ts->ts_reg);
+
+	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
+	release_mem_region(res->start, res->end - res->start + 1);
+
+	input_unregister_device(w90p910_ts->input);
+	kfree(w90p910_ts);
+
+	platform_set_drvdata(pdev, NULL);
+
+	return 0;
+}
+
+static struct platform_driver w90x900ts_driver = {
+	.probe		= w90x900ts_probe,
+	.remove		= __devexit_p(w90x900ts_remove),
+	.driver		= {
+		.name	= "w90x900-ts",
+		.owner	= THIS_MODULE,
+	},
+};
+
+static int __init w90x900ts_init(void)
+{
+	return platform_driver_register(&w90x900ts_driver);
+}
+
+static void __exit w90x900ts_exit(void)
+{
+	platform_driver_unregister(&w90x900ts_driver);
+}
+
+module_init(w90x900ts_init);
+module_exit(w90x900ts_exit);
+
+MODULE_AUTHOR("Wan ZongShun <mcuos.com@gmail.com>");
+MODULE_DESCRIPTION("w90p910 touch screen driver!");
+MODULE_LICENSE("GPL");
+MODULE_ALIAS("platform:w90p910-ts");
diff --git a/drivers/isdn/i4l/isdn_net.c b/drivers/isdn/i4l/isdn_net.c
index 34d54e7..de4aad0 100644
--- a/drivers/isdn/i4l/isdn_net.c
+++ b/drivers/isdn/i4l/isdn_net.c
@@ -1300,7 +1300,7 @@
 				netif_stop_queue(ndev);
 		}
 	}
-	return 1;
+	return NETDEV_TX_BUSY;
 }
 
 /*
diff --git a/drivers/md/dm-exception-store.h b/drivers/md/dm-exception-store.h
index 0a2e6e7..c92701d 100644
--- a/drivers/md/dm-exception-store.h
+++ b/drivers/md/dm-exception-store.h
@@ -111,7 +111,7 @@
 /*
  * Funtions to manipulate consecutive chunks
  */
-#  if defined(CONFIG_LBD) || (BITS_PER_LONG == 64)
+#  if defined(CONFIG_LBDAF) || (BITS_PER_LONG == 64)
 #    define DM_CHUNK_CONSECUTIVE_BITS 8
 #    define DM_CHUNK_NUMBER_BITS 56
 
diff --git a/drivers/md/faulty.c b/drivers/md/faulty.c
index 8695809..87d88db 100644
--- a/drivers/md/faulty.c
+++ b/drivers/md/faulty.c
@@ -255,14 +255,14 @@
 }
 
 
-static int reconfig(mddev_t *mddev, int layout, int chunk_size)
+static int reshape(mddev_t *mddev)
 {
-	int mode = layout & ModeMask;
-	int count = layout >> ModeShift;
+	int mode = mddev->new_layout & ModeMask;
+	int count = mddev->new_layout >> ModeShift;
 	conf_t *conf = mddev->private;
 
-	if (chunk_size != -1)
-		return -EINVAL;
+	if (mddev->new_layout < 0)
+		return 0;
 
 	/* new layout */
 	if (mode == ClearFaults)
@@ -279,6 +279,7 @@
 		atomic_set(&conf->counters[mode], count);
 	} else
 		return -EINVAL;
+	mddev->new_layout = -1;
 	mddev->layout = -1; /* makes sure further changes come through */
 	return 0;
 }
@@ -298,8 +299,12 @@
 {
 	mdk_rdev_t *rdev;
 	int i;
+	conf_t *conf;
 
-	conf_t *conf = kmalloc(sizeof(*conf), GFP_KERNEL);
+	if (md_check_no_bitmap(mddev))
+		return -EINVAL;
+
+	conf = kmalloc(sizeof(*conf), GFP_KERNEL);
 	if (!conf)
 		return -ENOMEM;
 
@@ -315,7 +320,7 @@
 	md_set_array_sectors(mddev, faulty_size(mddev, 0, 0));
 	mddev->private = conf;
 
-	reconfig(mddev, mddev->layout, -1);
+	reshape(mddev);
 
 	return 0;
 }
@@ -338,7 +343,7 @@
 	.run		= run,
 	.stop		= stop,
 	.status		= status,
-	.reconfig	= reconfig,
+	.check_reshape	= reshape,
 	.size		= faulty_size,
 };
 
diff --git a/drivers/md/linear.c b/drivers/md/linear.c
index 64f1f3e0..15c8b7b 100644
--- a/drivers/md/linear.c
+++ b/drivers/md/linear.c
@@ -27,19 +27,27 @@
  */
 static inline dev_info_t *which_dev(mddev_t *mddev, sector_t sector)
 {
-	dev_info_t *hash;
-	linear_conf_t *conf = mddev_to_conf(mddev);
-	sector_t idx = sector >> conf->sector_shift;
+	int lo, mid, hi;
+	linear_conf_t *conf;
+
+	lo = 0;
+	hi = mddev->raid_disks - 1;
+	conf = rcu_dereference(mddev->private);
 
 	/*
-	 * sector_div(a,b) returns the remainer and sets a to a/b
+	 * Binary Search
 	 */
-	(void)sector_div(idx, conf->spacing);
-	hash = conf->hash_table[idx];
 
-	while (sector >= hash->num_sectors + hash->start_sector)
-		hash++;
-	return hash;
+	while (hi > lo) {
+
+		mid = (hi + lo) / 2;
+		if (sector < conf->disks[mid].end_sector)
+			hi = mid;
+		else
+			lo = mid + 1;
+	}
+
+	return conf->disks + lo;
 }
 
 /**
@@ -59,8 +67,10 @@
 	unsigned long maxsectors, bio_sectors = bvm->bi_size >> 9;
 	sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
 
+	rcu_read_lock();
 	dev0 = which_dev(mddev, sector);
-	maxsectors = dev0->num_sectors - (sector - dev0->start_sector);
+	maxsectors = dev0->end_sector - sector;
+	rcu_read_unlock();
 
 	if (maxsectors < bio_sectors)
 		maxsectors = 0;
@@ -79,46 +89,57 @@
 static void linear_unplug(struct request_queue *q)
 {
 	mddev_t *mddev = q->queuedata;
-	linear_conf_t *conf = mddev_to_conf(mddev);
+	linear_conf_t *conf;
 	int i;
 
+	rcu_read_lock();
+	conf = rcu_dereference(mddev->private);
+
 	for (i=0; i < mddev->raid_disks; i++) {
 		struct request_queue *r_queue = bdev_get_queue(conf->disks[i].rdev->bdev);
 		blk_unplug(r_queue);
 	}
+	rcu_read_unlock();
 }
 
 static int linear_congested(void *data, int bits)
 {
 	mddev_t *mddev = data;
-	linear_conf_t *conf = mddev_to_conf(mddev);
+	linear_conf_t *conf;
 	int i, ret = 0;
 
+	rcu_read_lock();
+	conf = rcu_dereference(mddev->private);
+
 	for (i = 0; i < mddev->raid_disks && !ret ; i++) {
 		struct request_queue *q = bdev_get_queue(conf->disks[i].rdev->bdev);
 		ret |= bdi_congested(&q->backing_dev_info, bits);
 	}
+
+	rcu_read_unlock();
 	return ret;
 }
 
 static sector_t linear_size(mddev_t *mddev, sector_t sectors, int raid_disks)
 {
-	linear_conf_t *conf = mddev_to_conf(mddev);
+	linear_conf_t *conf;
+	sector_t array_sectors;
 
+	rcu_read_lock();
+	conf = rcu_dereference(mddev->private);
 	WARN_ONCE(sectors || raid_disks,
 		  "%s does not support generic reshape\n", __func__);
+	array_sectors = conf->array_sectors;
+	rcu_read_unlock();
 
-	return conf->array_sectors;
+	return array_sectors;
 }
 
 static linear_conf_t *linear_conf(mddev_t *mddev, int raid_disks)
 {
 	linear_conf_t *conf;
-	dev_info_t **table;
 	mdk_rdev_t *rdev;
-	int i, nb_zone, cnt;
-	sector_t min_sectors;
-	sector_t curr_sector;
+	int i, cnt;
 
 	conf = kzalloc (sizeof (*conf) + raid_disks*sizeof(dev_info_t),
 			GFP_KERNEL);
@@ -131,6 +152,7 @@
 	list_for_each_entry(rdev, &mddev->disks, same_set) {
 		int j = rdev->raid_disk;
 		dev_info_t *disk = conf->disks + j;
+		sector_t sectors;
 
 		if (j < 0 || j >= raid_disks || disk->rdev) {
 			printk("linear: disk numbering problem. Aborting!\n");
@@ -138,6 +160,11 @@
 		}
 
 		disk->rdev = rdev;
+		if (mddev->chunk_sectors) {
+			sectors = rdev->sectors;
+			sector_div(sectors, mddev->chunk_sectors);
+			rdev->sectors = sectors * mddev->chunk_sectors;
+		}
 
 		blk_queue_stack_limits(mddev->queue,
 				       rdev->bdev->bd_disk->queue);
@@ -149,102 +176,24 @@
 		    queue_max_sectors(mddev->queue) > (PAGE_SIZE>>9))
 			blk_queue_max_sectors(mddev->queue, PAGE_SIZE>>9);
 
-		disk->num_sectors = rdev->sectors;
 		conf->array_sectors += rdev->sectors;
-
 		cnt++;
+
 	}
 	if (cnt != raid_disks) {
 		printk("linear: not enough drives present. Aborting!\n");
 		goto out;
 	}
 
-	min_sectors = conf->array_sectors;
-	sector_div(min_sectors, PAGE_SIZE/sizeof(struct dev_info *));
-	if (min_sectors == 0)
-		min_sectors = 1;
-
-	/* min_sectors is the minimum spacing that will fit the hash
-	 * table in one PAGE.  This may be much smaller than needed.
-	 * We find the smallest non-terminal set of consecutive devices
-	 * that is larger than min_sectors and use the size of that as
-	 * the actual spacing
-	 */
-	conf->spacing = conf->array_sectors;
-	for (i=0; i < cnt-1 ; i++) {
-		sector_t tmp = 0;
-		int j;
-		for (j = i; j < cnt - 1 && tmp < min_sectors; j++)
-			tmp += conf->disks[j].num_sectors;
-		if (tmp >= min_sectors && tmp < conf->spacing)
-			conf->spacing = tmp;
-	}
-
-	/* spacing may be too large for sector_div to work with,
-	 * so we might need to pre-shift
-	 */
-	conf->sector_shift = 0;
-	if (sizeof(sector_t) > sizeof(u32)) {
-		sector_t space = conf->spacing;
-		while (space > (sector_t)(~(u32)0)) {
-			space >>= 1;
-			conf->sector_shift++;
-		}
-	}
 	/*
-	 * This code was restructured to work around a gcc-2.95.3 internal
-	 * compiler error.  Alter it with care.
+	 * Here we calculate the device offsets.
 	 */
-	{
-		sector_t sz;
-		unsigned round;
-		unsigned long base;
+	conf->disks[0].end_sector = conf->disks[0].rdev->sectors;
 
-		sz = conf->array_sectors >> conf->sector_shift;
-		sz += 1; /* force round-up */
-		base = conf->spacing >> conf->sector_shift;
-		round = sector_div(sz, base);
-		nb_zone = sz + (round ? 1 : 0);
-	}
-	BUG_ON(nb_zone > PAGE_SIZE / sizeof(struct dev_info *));
-
-	conf->hash_table = kmalloc (sizeof (struct dev_info *) * nb_zone,
-					GFP_KERNEL);
-	if (!conf->hash_table)
-		goto out;
-
-	/*
-	 * Here we generate the linear hash table
-	 * First calculate the device offsets.
-	 */
-	conf->disks[0].start_sector = 0;
 	for (i = 1; i < raid_disks; i++)
-		conf->disks[i].start_sector =
-			conf->disks[i-1].start_sector +
-			conf->disks[i-1].num_sectors;
-
-	table = conf->hash_table;
-	i = 0;
-	for (curr_sector = 0;
-	     curr_sector < conf->array_sectors;
-	     curr_sector += conf->spacing) {
-
-		while (i < raid_disks-1 &&
-		       curr_sector >= conf->disks[i+1].start_sector)
-			i++;
-
-		*table ++ = conf->disks + i;
-	}
-
-	if (conf->sector_shift) {
-		conf->spacing >>= conf->sector_shift;
-		/* round spacing up so that when we divide by it,
-		 * we err on the side of "too-low", which is safest.
-		 */
-		conf->spacing++;
-	}
-
-	BUG_ON(table - conf->hash_table > nb_zone);
+		conf->disks[i].end_sector =
+			conf->disks[i-1].end_sector +
+			conf->disks[i].rdev->sectors;
 
 	return conf;
 
@@ -257,6 +206,8 @@
 {
 	linear_conf_t *conf;
 
+	if (md_check_no_bitmap(mddev))
+		return -EINVAL;
 	mddev->queue->queue_lock = &mddev->queue->__queue_lock;
 	conf = linear_conf(mddev, mddev->raid_disks);
 
@@ -272,6 +223,12 @@
 	return 0;
 }
 
+static void free_conf(struct rcu_head *head)
+{
+	linear_conf_t *conf = container_of(head, linear_conf_t, rcu);
+	kfree(conf);
+}
+
 static int linear_add(mddev_t *mddev, mdk_rdev_t *rdev)
 {
 	/* Adding a drive to a linear array allows the array to grow.
@@ -282,7 +239,7 @@
 	 * The current one is never freed until the array is stopped.
 	 * This avoids races.
 	 */
-	linear_conf_t *newconf;
+	linear_conf_t *newconf, *oldconf;
 
 	if (rdev->saved_raid_disk != mddev->raid_disks)
 		return -EINVAL;
@@ -294,25 +251,29 @@
 	if (!newconf)
 		return -ENOMEM;
 
-	newconf->prev = mddev_to_conf(mddev);
-	mddev->private = newconf;
+	oldconf = rcu_dereference(mddev->private);
 	mddev->raid_disks++;
+	rcu_assign_pointer(mddev->private, newconf);
 	md_set_array_sectors(mddev, linear_size(mddev, 0, 0));
 	set_capacity(mddev->gendisk, mddev->array_sectors);
+	call_rcu(&oldconf->rcu, free_conf);
 	return 0;
 }
 
 static int linear_stop (mddev_t *mddev)
 {
-	linear_conf_t *conf = mddev_to_conf(mddev);
-  
+	linear_conf_t *conf = mddev->private;
+
+	/*
+	 * We do not require rcu protection here since
+	 * we hold reconfig_mutex for both linear_add and
+	 * linear_stop, so they cannot race.
+	 * We should make sure any old 'conf's are properly
+	 * freed though.
+	 */
+	rcu_barrier();
 	blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
-	do {
-		linear_conf_t *t = conf->prev;
-		kfree(conf->hash_table);
-		kfree(conf);
-		conf = t;
-	} while (conf);
+	kfree(conf);
 
 	return 0;
 }
@@ -322,6 +283,7 @@
 	const int rw = bio_data_dir(bio);
 	mddev_t *mddev = q->queuedata;
 	dev_info_t *tmp_dev;
+	sector_t start_sector;
 	int cpu;
 
 	if (unlikely(bio_barrier(bio))) {
@@ -335,33 +297,36 @@
 		      bio_sectors(bio));
 	part_stat_unlock();
 
+	rcu_read_lock();
 	tmp_dev = which_dev(mddev, bio->bi_sector);
-    
-	if (unlikely(bio->bi_sector >= (tmp_dev->num_sectors +
-					tmp_dev->start_sector)
-		     || (bio->bi_sector <
-			 tmp_dev->start_sector))) {
+	start_sector = tmp_dev->end_sector - tmp_dev->rdev->sectors;
+
+
+	if (unlikely(bio->bi_sector >= (tmp_dev->end_sector)
+		     || (bio->bi_sector < start_sector))) {
 		char b[BDEVNAME_SIZE];
 
 		printk("linear_make_request: Sector %llu out of bounds on "
 			"dev %s: %llu sectors, offset %llu\n",
 			(unsigned long long)bio->bi_sector,
 			bdevname(tmp_dev->rdev->bdev, b),
-			(unsigned long long)tmp_dev->num_sectors,
-			(unsigned long long)tmp_dev->start_sector);
+			(unsigned long long)tmp_dev->rdev->sectors,
+			(unsigned long long)start_sector);
+		rcu_read_unlock();
 		bio_io_error(bio);
 		return 0;
 	}
 	if (unlikely(bio->bi_sector + (bio->bi_size >> 9) >
-		     tmp_dev->start_sector + tmp_dev->num_sectors)) {
+		     tmp_dev->end_sector)) {
 		/* This bio crosses a device boundary, so we have to
 		 * split it.
 		 */
 		struct bio_pair *bp;
+		sector_t end_sector = tmp_dev->end_sector;
 
-		bp = bio_split(bio,
-			       tmp_dev->start_sector + tmp_dev->num_sectors
-			       - bio->bi_sector);
+		rcu_read_unlock();
+
+		bp = bio_split(bio, end_sector - bio->bi_sector);
 
 		if (linear_make_request(q, &bp->bio1))
 			generic_make_request(&bp->bio1);
@@ -372,8 +337,9 @@
 	}
 		    
 	bio->bi_bdev = tmp_dev->rdev->bdev;
-	bio->bi_sector = bio->bi_sector - tmp_dev->start_sector
+	bio->bi_sector = bio->bi_sector - start_sector
 		+ tmp_dev->rdev->data_offset;
+	rcu_read_unlock();
 
 	return 1;
 }
@@ -381,7 +347,7 @@
 static void linear_status (struct seq_file *seq, mddev_t *mddev)
 {
 
-	seq_printf(seq, " %dk rounding", mddev->chunk_size/1024);
+	seq_printf(seq, " %dk rounding", mddev->chunk_sectors / 2);
 }
 
 
diff --git a/drivers/md/linear.h b/drivers/md/linear.h
index bf81795..0ce29b6 100644
--- a/drivers/md/linear.h
+++ b/drivers/md/linear.h
@@ -3,27 +3,19 @@
 
 struct dev_info {
 	mdk_rdev_t	*rdev;
-	sector_t	num_sectors;
-	sector_t	start_sector;
+	sector_t	end_sector;
 };
 
 typedef struct dev_info dev_info_t;
 
 struct linear_private_data
 {
-	struct linear_private_data *prev;	/* earlier version */
-	dev_info_t		**hash_table;
-	sector_t		spacing;
 	sector_t		array_sectors;
-	int			sector_shift;	/* shift before dividing
-						 * by spacing
-						 */
 	dev_info_t		disks[0];
+	struct rcu_head		rcu;
 };
 
 
 typedef struct linear_private_data linear_conf_t;
 
-#define mddev_to_conf(mddev) ((linear_conf_t *) mddev->private)
-
 #endif
diff --git a/drivers/md/md.c b/drivers/md/md.c
index 20f6ac3..09be637 100644
--- a/drivers/md/md.c
+++ b/drivers/md/md.c
@@ -440,15 +440,6 @@
 	return MD_NEW_SIZE_SECTORS(num_sectors);
 }
 
-static sector_t calc_num_sectors(mdk_rdev_t *rdev, unsigned chunk_size)
-{
-	sector_t num_sectors = rdev->sb_start;
-
-	if (chunk_size)
-		num_sectors &= ~((sector_t)chunk_size/512 - 1);
-	return num_sectors;
-}
-
 static int alloc_disk_sb(mdk_rdev_t * rdev)
 {
 	if (rdev->sb_page)
@@ -745,6 +736,24 @@
 };
 
 /*
+ * Check that the given mddev has no bitmap.
+ *
+ * This function is called from the run method of all personalities that do not
+ * support bitmaps. It prints an error message and returns non-zero if mddev
+ * has a bitmap. Otherwise, it returns 0.
+ *
+ */
+int md_check_no_bitmap(mddev_t *mddev)
+{
+	if (!mddev->bitmap_file && !mddev->bitmap_offset)
+		return 0;
+	printk(KERN_ERR "%s: bitmaps are not supported for %s\n",
+		mdname(mddev), mddev->pers->name);
+	return 1;
+}
+EXPORT_SYMBOL(md_check_no_bitmap);
+
+/*
  * load_super for 0.90.0 
  */
 static int super_90_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
@@ -797,17 +806,6 @@
 	rdev->data_offset = 0;
 	rdev->sb_size = MD_SB_BYTES;
 
-	if (sb->state & (1<<MD_SB_BITMAP_PRESENT)) {
-		if (sb->level != 1 && sb->level != 4
-		    && sb->level != 5 && sb->level != 6
-		    && sb->level != 10) {
-			/* FIXME use a better test */
-			printk(KERN_WARNING
-			       "md: bitmaps not supported for this level.\n");
-			goto abort;
-		}
-	}
-
 	if (sb->level == LEVEL_MULTIPATH)
 		rdev->desc_nr = -1;
 	else
@@ -836,7 +834,7 @@
 		else 
 			ret = 0;
 	}
-	rdev->sectors = calc_num_sectors(rdev, sb->chunk_size);
+	rdev->sectors = rdev->sb_start;
 
 	if (rdev->sectors < sb->size * 2 && sb->level > 1)
 		/* "this cannot possibly happen" ... */
@@ -866,7 +864,7 @@
 		mddev->minor_version = sb->minor_version;
 		mddev->patch_version = sb->patch_version;
 		mddev->external = 0;
-		mddev->chunk_size = sb->chunk_size;
+		mddev->chunk_sectors = sb->chunk_size >> 9;
 		mddev->ctime = sb->ctime;
 		mddev->utime = sb->utime;
 		mddev->level = sb->level;
@@ -883,13 +881,13 @@
 			mddev->delta_disks = sb->delta_disks;
 			mddev->new_level = sb->new_level;
 			mddev->new_layout = sb->new_layout;
-			mddev->new_chunk = sb->new_chunk;
+			mddev->new_chunk_sectors = sb->new_chunk >> 9;
 		} else {
 			mddev->reshape_position = MaxSector;
 			mddev->delta_disks = 0;
 			mddev->new_level = mddev->level;
 			mddev->new_layout = mddev->layout;
-			mddev->new_chunk = mddev->chunk_size;
+			mddev->new_chunk_sectors = mddev->chunk_sectors;
 		}
 
 		if (sb->state & (1<<MD_SB_CLEAN))
@@ -1004,7 +1002,7 @@
 		sb->new_level = mddev->new_level;
 		sb->delta_disks = mddev->delta_disks;
 		sb->new_layout = mddev->new_layout;
-		sb->new_chunk = mddev->new_chunk;
+		sb->new_chunk = mddev->new_chunk_sectors << 9;
 	}
 	mddev->minor_version = sb->minor_version;
 	if (mddev->in_sync)
@@ -1018,7 +1016,7 @@
 		sb->recovery_cp = 0;
 
 	sb->layout = mddev->layout;
-	sb->chunk_size = mddev->chunk_size;
+	sb->chunk_size = mddev->chunk_sectors << 9;
 
 	if (mddev->bitmap && mddev->bitmap_file == NULL)
 		sb->state |= (1<<MD_SB_BITMAP_PRESENT);
@@ -1185,17 +1183,6 @@
 		       bdevname(rdev->bdev,b));
 		return -EINVAL;
 	}
-	if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET)) {
-		if (sb->level != cpu_to_le32(1) &&
-		    sb->level != cpu_to_le32(4) &&
-		    sb->level != cpu_to_le32(5) &&
-		    sb->level != cpu_to_le32(6) &&
-		    sb->level != cpu_to_le32(10)) {
-			printk(KERN_WARNING
-			       "md: bitmaps not supported for this level.\n");
-			return -EINVAL;
-		}
-	}
 
 	rdev->preferred_minor = 0xffff;
 	rdev->data_offset = le64_to_cpu(sb->data_offset);
@@ -1248,9 +1235,6 @@
 	if (rdev->sectors < le64_to_cpu(sb->data_size))
 		return -EINVAL;
 	rdev->sectors = le64_to_cpu(sb->data_size);
-	if (le32_to_cpu(sb->chunksize))
-		rdev->sectors &= ~((sector_t)le32_to_cpu(sb->chunksize) - 1);
-
 	if (le64_to_cpu(sb->size) > rdev->sectors)
 		return -EINVAL;
 	return ret;
@@ -1271,7 +1255,7 @@
 		mddev->major_version = 1;
 		mddev->patch_version = 0;
 		mddev->external = 0;
-		mddev->chunk_size = le32_to_cpu(sb->chunksize) << 9;
+		mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
 		mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
 		mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
 		mddev->level = le32_to_cpu(sb->level);
@@ -1297,13 +1281,13 @@
 			mddev->delta_disks = le32_to_cpu(sb->delta_disks);
 			mddev->new_level = le32_to_cpu(sb->new_level);
 			mddev->new_layout = le32_to_cpu(sb->new_layout);
-			mddev->new_chunk = le32_to_cpu(sb->new_chunk)<<9;
+			mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
 		} else {
 			mddev->reshape_position = MaxSector;
 			mddev->delta_disks = 0;
 			mddev->new_level = mddev->level;
 			mddev->new_layout = mddev->layout;
-			mddev->new_chunk = mddev->chunk_size;
+			mddev->new_chunk_sectors = mddev->chunk_sectors;
 		}
 
 	} else if (mddev->pers == NULL) {
@@ -1375,7 +1359,7 @@
 
 	sb->raid_disks = cpu_to_le32(mddev->raid_disks);
 	sb->size = cpu_to_le64(mddev->dev_sectors);
-	sb->chunksize = cpu_to_le32(mddev->chunk_size >> 9);
+	sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
 	sb->level = cpu_to_le32(mddev->level);
 	sb->layout = cpu_to_le32(mddev->layout);
 
@@ -1402,7 +1386,7 @@
 		sb->new_layout = cpu_to_le32(mddev->new_layout);
 		sb->delta_disks = cpu_to_le32(mddev->delta_disks);
 		sb->new_level = cpu_to_le32(mddev->new_level);
-		sb->new_chunk = cpu_to_le32(mddev->new_chunk>>9);
+		sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
 	}
 
 	max_dev = 0;
@@ -1897,6 +1881,7 @@
 	int sync_req;
 	int nospares = 0;
 
+	mddev->utime = get_seconds();
 	if (mddev->external)
 		return;
 repeat:
@@ -1926,7 +1911,6 @@
 		nospares = 0;
 
 	sync_req = mddev->in_sync;
-	mddev->utime = get_seconds();
 
 	/* If this is just a dirty<->clean transition, and the array is clean
 	 * and 'events' is odd, we can roll back to the previous clean state */
@@ -2597,15 +2581,6 @@
 			clear_bit(In_sync, &rdev->flags);
 		}
 	}
-
-
-
-	if (mddev->recovery_cp != MaxSector &&
-	    mddev->level >= 1)
-		printk(KERN_ERR "md: %s: raid array is not clean"
-		       " -- starting background reconstruction\n",
-		       mdname(mddev));
-
 }
 
 static void md_safemode_timeout(unsigned long data);
@@ -2746,7 +2721,7 @@
 	if (IS_ERR(priv)) {
 		mddev->new_level = mddev->level;
 		mddev->new_layout = mddev->layout;
-		mddev->new_chunk = mddev->chunk_size;
+		mddev->new_chunk_sectors = mddev->chunk_sectors;
 		mddev->raid_disks -= mddev->delta_disks;
 		mddev->delta_disks = 0;
 		module_put(pers->owner);
@@ -2764,7 +2739,7 @@
 	strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
 	mddev->level = mddev->new_level;
 	mddev->layout = mddev->new_layout;
-	mddev->chunk_size = mddev->new_chunk;
+	mddev->chunk_sectors = mddev->new_chunk_sectors;
 	mddev->delta_disks = 0;
 	pers->run(mddev);
 	mddev_resume(mddev);
@@ -2800,11 +2775,14 @@
 
 	if (mddev->pers) {
 		int err;
-		if (mddev->pers->reconfig == NULL)
+		if (mddev->pers->check_reshape == NULL)
 			return -EBUSY;
-		err = mddev->pers->reconfig(mddev, n, -1);
-		if (err)
+		mddev->new_layout = n;
+		err = mddev->pers->check_reshape(mddev);
+		if (err) {
+			mddev->new_layout = mddev->layout;
 			return err;
+		}
 	} else {
 		mddev->new_layout = n;
 		if (mddev->reshape_position == MaxSector)
@@ -2857,10 +2835,11 @@
 chunk_size_show(mddev_t *mddev, char *page)
 {
 	if (mddev->reshape_position != MaxSector &&
-	    mddev->chunk_size != mddev->new_chunk)
-		return sprintf(page, "%d (%d)\n", mddev->new_chunk,
-			       mddev->chunk_size);
-	return sprintf(page, "%d\n", mddev->chunk_size);
+	    mddev->chunk_sectors != mddev->new_chunk_sectors)
+		return sprintf(page, "%d (%d)\n",
+			       mddev->new_chunk_sectors << 9,
+			       mddev->chunk_sectors << 9);
+	return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
 }
 
 static ssize_t
@@ -2874,15 +2853,18 @@
 
 	if (mddev->pers) {
 		int err;
-		if (mddev->pers->reconfig == NULL)
+		if (mddev->pers->check_reshape == NULL)
 			return -EBUSY;
-		err = mddev->pers->reconfig(mddev, -1, n);
-		if (err)
+		mddev->new_chunk_sectors = n >> 9;
+		err = mddev->pers->check_reshape(mddev);
+		if (err) {
+			mddev->new_chunk_sectors = mddev->chunk_sectors;
 			return err;
+		}
 	} else {
-		mddev->new_chunk = n;
+		mddev->new_chunk_sectors = n >> 9;
 		if (mddev->reshape_position == MaxSector)
-			mddev->chunk_size = n;
+			mddev->chunk_sectors = n >> 9;
 	}
 	return len;
 }
@@ -3527,8 +3509,9 @@
 		return -EBUSY;
 
 	/* Must be a multiple of chunk_size */
-	if (mddev->chunk_size) {
-		if (min & (sector_t)((mddev->chunk_size>>9)-1))
+	if (mddev->chunk_sectors) {
+		sector_t temp = min;
+		if (sector_div(temp, mddev->chunk_sectors))
 			return -EINVAL;
 	}
 	mddev->resync_min = min;
@@ -3564,8 +3547,9 @@
 			return -EBUSY;
 
 		/* Must be a multiple of chunk_size */
-		if (mddev->chunk_size) {
-			if (max & (sector_t)((mddev->chunk_size>>9)-1))
+		if (mddev->chunk_sectors) {
+			sector_t temp = max;
+			if (sector_div(temp, mddev->chunk_sectors))
 				return -EINVAL;
 		}
 		mddev->resync_max = max;
@@ -3656,7 +3640,7 @@
 	mddev->delta_disks = 0;
 	mddev->new_level = mddev->level;
 	mddev->new_layout = mddev->layout;
-	mddev->new_chunk = mddev->chunk_size;
+	mddev->new_chunk_sectors = mddev->chunk_sectors;
 	return len;
 }
 
@@ -3976,11 +3960,9 @@
 static int do_md_run(mddev_t * mddev)
 {
 	int err;
-	int chunk_size;
 	mdk_rdev_t *rdev;
 	struct gendisk *disk;
 	struct mdk_personality *pers;
-	char b[BDEVNAME_SIZE];
 
 	if (list_empty(&mddev->disks))
 		/* cannot run an array with no devices.. */
@@ -3998,38 +3980,6 @@
 		analyze_sbs(mddev);
 	}
 
-	chunk_size = mddev->chunk_size;
-
-	if (chunk_size) {
-		if (chunk_size > MAX_CHUNK_SIZE) {
-			printk(KERN_ERR "too big chunk_size: %d > %d\n",
-				chunk_size, MAX_CHUNK_SIZE);
-			return -EINVAL;
-		}
-		/*
-		 * chunk-size has to be a power of 2
-		 */
-		if ( (1 << ffz(~chunk_size)) != chunk_size) {
-			printk(KERN_ERR "chunk_size of %d not valid\n", chunk_size);
-			return -EINVAL;
-		}
-
-		/* devices must have minimum size of one chunk */
-		list_for_each_entry(rdev, &mddev->disks, same_set) {
-			if (test_bit(Faulty, &rdev->flags))
-				continue;
-			if (rdev->sectors < chunk_size / 512) {
-				printk(KERN_WARNING
-					"md: Dev %s smaller than chunk_size:"
-					" %llu < %d\n",
-					bdevname(rdev->bdev,b),
-					(unsigned long long)rdev->sectors,
-					chunk_size / 512);
-				return -EINVAL;
-			}
-		}
-	}
-
 	if (mddev->level != LEVEL_NONE)
 		request_module("md-level-%d", mddev->level);
 	else if (mddev->clevel[0])
@@ -4405,7 +4355,7 @@
 		mddev->flags = 0;
 		mddev->ro = 0;
 		mddev->metadata_type[0] = 0;
-		mddev->chunk_size = 0;
+		mddev->chunk_sectors = 0;
 		mddev->ctime = mddev->utime = 0;
 		mddev->layout = 0;
 		mddev->max_disks = 0;
@@ -4413,7 +4363,7 @@
 		mddev->delta_disks = 0;
 		mddev->new_level = LEVEL_NONE;
 		mddev->new_layout = 0;
-		mddev->new_chunk = 0;
+		mddev->new_chunk_sectors = 0;
 		mddev->curr_resync = 0;
 		mddev->resync_mismatches = 0;
 		mddev->suspend_lo = mddev->suspend_hi = 0;
@@ -4618,7 +4568,7 @@
 	info.spare_disks   = spare;
 
 	info.layout        = mddev->layout;
-	info.chunk_size    = mddev->chunk_size;
+	info.chunk_size    = mddev->chunk_sectors << 9;
 
 	if (copy_to_user(arg, &info, sizeof(info)))
 		return -EFAULT;
@@ -4843,7 +4793,7 @@
 			rdev->sb_start = rdev->bdev->bd_inode->i_size / 512;
 		} else 
 			rdev->sb_start = calc_dev_sboffset(rdev->bdev);
-		rdev->sectors = calc_num_sectors(rdev, mddev->chunk_size);
+		rdev->sectors = rdev->sb_start;
 
 		err = bind_rdev_to_array(rdev, mddev);
 		if (err) {
@@ -4913,7 +4863,7 @@
 	else
 		rdev->sb_start = rdev->bdev->bd_inode->i_size / 512;
 
-	rdev->sectors = calc_num_sectors(rdev, mddev->chunk_size);
+	rdev->sectors = rdev->sb_start;
 
 	if (test_bit(Faulty, &rdev->flags)) {
 		printk(KERN_WARNING 
@@ -5062,7 +5012,7 @@
 	mddev->external	     = 0;
 
 	mddev->layout        = info->layout;
-	mddev->chunk_size    = info->chunk_size;
+	mddev->chunk_sectors = info->chunk_size >> 9;
 
 	mddev->max_disks     = MD_SB_DISKS;
 
@@ -5081,7 +5031,7 @@
 	get_random_bytes(mddev->uuid, 16);
 
 	mddev->new_level = mddev->level;
-	mddev->new_chunk = mddev->chunk_size;
+	mddev->new_chunk_sectors = mddev->chunk_sectors;
 	mddev->new_layout = mddev->layout;
 	mddev->delta_disks = 0;
 
@@ -5191,7 +5141,7 @@
 	    mddev->level         != info->level         ||
 /*	    mddev->layout        != info->layout        || */
 	    !mddev->persistent	 != info->not_persistent||
-	    mddev->chunk_size    != info->chunk_size    ||
+	    mddev->chunk_sectors != info->chunk_size >> 9 ||
 	    /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
 	    ((state^info->state) & 0xfffffe00)
 		)
@@ -5215,10 +5165,15 @@
 		 * we don't need to do anything at the md level, the
 		 * personality will take care of it all.
 		 */
-		if (mddev->pers->reconfig == NULL)
+		if (mddev->pers->check_reshape == NULL)
 			return -EINVAL;
-		else
-			return mddev->pers->reconfig(mddev, info->layout, -1);
+		else {
+			mddev->new_layout = info->layout;
+			rv = mddev->pers->check_reshape(mddev);
+			if (rv)
+				mddev->new_layout = mddev->layout;
+			return rv;
+		}
 	}
 	if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
 		rv = update_size(mddev, (sector_t)info->size * 2);
@@ -6717,7 +6672,8 @@
 		 */
 
 		if (mddev->reshape_position != MaxSector) {
-			if (mddev->pers->check_reshape(mddev) != 0)
+			if (mddev->pers->check_reshape == NULL ||
+			    mddev->pers->check_reshape(mddev) != 0)
 				/* Cannot proceed */
 				goto unlock;
 			set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
diff --git a/drivers/md/md.h b/drivers/md/md.h
index 8227ab9..9430a11 100644
--- a/drivers/md/md.h
+++ b/drivers/md/md.h
@@ -30,13 +30,6 @@
 typedef struct mdk_rdev_s mdk_rdev_t;
 
 /*
- * options passed in raidrun:
- */
-
-/* Currently this must fit in an 'int' */
-#define MAX_CHUNK_SIZE (1<<30)
-
-/*
  * MD's 'extended' device
  */
 struct mdk_rdev_s
@@ -145,7 +138,7 @@
 	int 				external;	/* metadata is
 							 * managed externally */
 	char				metadata_type[17]; /* externally set*/
-	int				chunk_size;
+	int				chunk_sectors;
 	time_t				ctime, utime;
 	int				level, layout;
 	char				clevel[16];
@@ -166,7 +159,8 @@
 	 * If reshape_position is MaxSector, then no reshape is happening (yet).
 	 */
 	sector_t			reshape_position;
-	int				delta_disks, new_level, new_layout, new_chunk;
+	int				delta_disks, new_level, new_layout;
+	int				new_chunk_sectors;
 
 	struct mdk_thread_s		*thread;	/* management thread */
 	struct mdk_thread_s		*sync_thread;	/* doing resync or reconstruct */
@@ -325,7 +319,6 @@
 	int (*check_reshape) (mddev_t *mddev);
 	int (*start_reshape) (mddev_t *mddev);
 	void (*finish_reshape) (mddev_t *mddev);
-	int (*reconfig) (mddev_t *mddev, int layout, int chunk_size);
 	/* quiesce moves between quiescence states
 	 * 0 - fully active
 	 * 1 - no new requests allowed
@@ -437,5 +430,6 @@
 extern int md_allow_write(mddev_t *mddev);
 extern void md_wait_for_blocked_rdev(mdk_rdev_t *rdev, mddev_t *mddev);
 extern void md_set_array_sectors(mddev_t *mddev, sector_t array_sectors);
+extern int md_check_no_bitmap(mddev_t *mddev);
 
 #endif /* _MD_MD_H */
diff --git a/drivers/md/multipath.c b/drivers/md/multipath.c
index 4ee31aa..cbe368f 100644
--- a/drivers/md/multipath.c
+++ b/drivers/md/multipath.c
@@ -58,7 +58,7 @@
 {
 	unsigned long flags;
 	mddev_t *mddev = mp_bh->mddev;
-	multipath_conf_t *conf = mddev_to_conf(mddev);
+	multipath_conf_t *conf = mddev->private;
 
 	spin_lock_irqsave(&conf->device_lock, flags);
 	list_add(&mp_bh->retry_list, &conf->retry_list);
@@ -75,7 +75,7 @@
 static void multipath_end_bh_io (struct multipath_bh *mp_bh, int err)
 {
 	struct bio *bio = mp_bh->master_bio;
-	multipath_conf_t *conf = mddev_to_conf(mp_bh->mddev);
+	multipath_conf_t *conf = mp_bh->mddev->private;
 
 	bio_endio(bio, err);
 	mempool_free(mp_bh, conf->pool);
@@ -85,7 +85,7 @@
 {
 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
 	struct multipath_bh * mp_bh = (struct multipath_bh *)(bio->bi_private);
-	multipath_conf_t *conf = mddev_to_conf(mp_bh->mddev);
+	multipath_conf_t *conf = mp_bh->mddev->private;
 	mdk_rdev_t *rdev = conf->multipaths[mp_bh->path].rdev;
 
 	if (uptodate)
@@ -107,7 +107,7 @@
 
 static void unplug_slaves(mddev_t *mddev)
 {
-	multipath_conf_t *conf = mddev_to_conf(mddev);
+	multipath_conf_t *conf = mddev->private;
 	int i;
 
 	rcu_read_lock();
@@ -138,7 +138,7 @@
 static int multipath_make_request (struct request_queue *q, struct bio * bio)
 {
 	mddev_t *mddev = q->queuedata;
-	multipath_conf_t *conf = mddev_to_conf(mddev);
+	multipath_conf_t *conf = mddev->private;
 	struct multipath_bh * mp_bh;
 	struct multipath_info *multipath;
 	const int rw = bio_data_dir(bio);
@@ -180,7 +180,7 @@
 
 static void multipath_status (struct seq_file *seq, mddev_t *mddev)
 {
-	multipath_conf_t *conf = mddev_to_conf(mddev);
+	multipath_conf_t *conf = mddev->private;
 	int i;
 	
 	seq_printf (seq, " [%d/%d] [", conf->raid_disks,
@@ -195,7 +195,7 @@
 static int multipath_congested(void *data, int bits)
 {
 	mddev_t *mddev = data;
-	multipath_conf_t *conf = mddev_to_conf(mddev);
+	multipath_conf_t *conf = mddev->private;
 	int i, ret = 0;
 
 	rcu_read_lock();
@@ -220,7 +220,7 @@
  */
 static void multipath_error (mddev_t *mddev, mdk_rdev_t *rdev)
 {
-	multipath_conf_t *conf = mddev_to_conf(mddev);
+	multipath_conf_t *conf = mddev->private;
 
 	if (conf->working_disks <= 1) {
 		/*
@@ -367,7 +367,7 @@
 	struct multipath_bh *mp_bh;
 	struct bio *bio;
 	unsigned long flags;
-	multipath_conf_t *conf = mddev_to_conf(mddev);
+	multipath_conf_t *conf = mddev->private;
 	struct list_head *head = &conf->retry_list;
 
 	md_check_recovery(mddev);
@@ -421,6 +421,9 @@
 	struct multipath_info *disk;
 	mdk_rdev_t *rdev;
 
+	if (md_check_no_bitmap(mddev))
+		return -EINVAL;
+
 	if (mddev->level != LEVEL_MULTIPATH) {
 		printk("multipath: %s: raid level not set to multipath IO (%d)\n",
 		       mdname(mddev), mddev->level);
@@ -531,7 +534,7 @@
 
 static int multipath_stop (mddev_t *mddev)
 {
-	multipath_conf_t *conf = mddev_to_conf(mddev);
+	multipath_conf_t *conf = mddev->private;
 
 	md_unregister_thread(mddev->thread);
 	mddev->thread = NULL;
diff --git a/drivers/md/multipath.h b/drivers/md/multipath.h
index 6fa70b4..d1c2a8d 100644
--- a/drivers/md/multipath.h
+++ b/drivers/md/multipath.h
@@ -19,12 +19,6 @@
 typedef struct multipath_private_data multipath_conf_t;
 
 /*
- * this is the only point in the RAID code where we violate
- * C type safety. mddev->private is an 'opaque' pointer.
- */
-#define mddev_to_conf(mddev) ((multipath_conf_t *) mddev->private)
-
-/*
  * this is our 'private' 'collective' MULTIPATH buffer head.
  * it contains information about what kind of IO operations were started
  * for this MULTIPATH operation, and about their status:
diff --git a/drivers/md/raid0.c b/drivers/md/raid0.c
index 925507e..ab4a489 100644
--- a/drivers/md/raid0.c
+++ b/drivers/md/raid0.c
@@ -26,8 +26,8 @@
 static void raid0_unplug(struct request_queue *q)
 {
 	mddev_t *mddev = q->queuedata;
-	raid0_conf_t *conf = mddev_to_conf(mddev);
-	mdk_rdev_t **devlist = conf->strip_zone[0].dev;
+	raid0_conf_t *conf = mddev->private;
+	mdk_rdev_t **devlist = conf->devlist;
 	int i;
 
 	for (i=0; i<mddev->raid_disks; i++) {
@@ -40,8 +40,8 @@
 static int raid0_congested(void *data, int bits)
 {
 	mddev_t *mddev = data;
-	raid0_conf_t *conf = mddev_to_conf(mddev);
-	mdk_rdev_t **devlist = conf->strip_zone[0].dev;
+	raid0_conf_t *conf = mddev->private;
+	mdk_rdev_t **devlist = conf->devlist;
 	int i, ret = 0;
 
 	for (i = 0; i < mddev->raid_disks && !ret ; i++) {
@@ -52,27 +52,60 @@
 	return ret;
 }
 
-
-static int create_strip_zones (mddev_t *mddev)
+/*
+ * inform the user of the raid configuration
+*/
+static void dump_zones(mddev_t *mddev)
 {
-	int i, c, j;
-	sector_t current_start, curr_zone_start;
-	sector_t min_spacing;
-	raid0_conf_t *conf = mddev_to_conf(mddev);
-	mdk_rdev_t *smallest, *rdev1, *rdev2, *rdev;
+	int j, k, h;
+	sector_t zone_size = 0;
+	sector_t zone_start = 0;
+	char b[BDEVNAME_SIZE];
+	raid0_conf_t *conf = mddev->private;
+	printk(KERN_INFO "******* %s configuration *********\n",
+		mdname(mddev));
+	h = 0;
+	for (j = 0; j < conf->nr_strip_zones; j++) {
+		printk(KERN_INFO "zone%d=[", j);
+		for (k = 0; k < conf->strip_zone[j].nb_dev; k++)
+			printk("%s/",
+			bdevname(conf->devlist[j*mddev->raid_disks
+						+ k]->bdev, b));
+		printk("]\n");
+
+		zone_size  = conf->strip_zone[j].zone_end - zone_start;
+		printk(KERN_INFO "        zone offset=%llukb "
+				"device offset=%llukb size=%llukb\n",
+			(unsigned long long)zone_start>>1,
+			(unsigned long long)conf->strip_zone[j].dev_start>>1,
+			(unsigned long long)zone_size>>1);
+		zone_start = conf->strip_zone[j].zone_end;
+	}
+	printk(KERN_INFO "**********************************\n\n");
+}
+
+static int create_strip_zones(mddev_t *mddev)
+{
+	int i, c, j, err;
+	sector_t curr_zone_end, sectors;
+	mdk_rdev_t *smallest, *rdev1, *rdev2, *rdev, **dev;
 	struct strip_zone *zone;
 	int cnt;
 	char b[BDEVNAME_SIZE];
- 
-	/*
-	 * The number of 'same size groups'
-	 */
-	conf->nr_strip_zones = 0;
- 
+	raid0_conf_t *conf = kzalloc(sizeof(*conf), GFP_KERNEL);
+
+	if (!conf)
+		return -ENOMEM;
 	list_for_each_entry(rdev1, &mddev->disks, same_set) {
 		printk(KERN_INFO "raid0: looking at %s\n",
 			bdevname(rdev1->bdev,b));
 		c = 0;
+
+		/* round size to chunk_size */
+		sectors = rdev1->sectors;
+		sector_div(sectors, mddev->chunk_sectors);
+		rdev1->sectors = sectors * mddev->chunk_sectors;
+
 		list_for_each_entry(rdev2, &mddev->disks, same_set) {
 			printk(KERN_INFO "raid0:   comparing %s(%llu)",
 			       bdevname(rdev1->bdev,b),
@@ -103,16 +136,16 @@
 		}
 	}
 	printk(KERN_INFO "raid0: FINAL %d zones\n", conf->nr_strip_zones);
-
+	err = -ENOMEM;
 	conf->strip_zone = kzalloc(sizeof(struct strip_zone)*
 				conf->nr_strip_zones, GFP_KERNEL);
 	if (!conf->strip_zone)
-		return 1;
+		goto abort;
 	conf->devlist = kzalloc(sizeof(mdk_rdev_t*)*
 				conf->nr_strip_zones*mddev->raid_disks,
 				GFP_KERNEL);
 	if (!conf->devlist)
-		return 1;
+		goto abort;
 
 	/* The first zone must contain all devices, so here we check that
 	 * there is a proper alignment of slots to devices and find them all
@@ -120,7 +153,8 @@
 	zone = &conf->strip_zone[0];
 	cnt = 0;
 	smallest = NULL;
-	zone->dev = conf->devlist;
+	dev = conf->devlist;
+	err = -EINVAL;
 	list_for_each_entry(rdev1, &mddev->disks, same_set) {
 		int j = rdev1->raid_disk;
 
@@ -129,12 +163,12 @@
 				"aborting!\n", j);
 			goto abort;
 		}
-		if (zone->dev[j]) {
+		if (dev[j]) {
 			printk(KERN_ERR "raid0: multiple devices for %d - "
 				"aborting!\n", j);
 			goto abort;
 		}
-		zone->dev[j] = rdev1;
+		dev[j] = rdev1;
 
 		blk_queue_stack_limits(mddev->queue,
 				       rdev1->bdev->bd_disk->queue);
@@ -157,34 +191,32 @@
 		goto abort;
 	}
 	zone->nb_dev = cnt;
-	zone->sectors = smallest->sectors * cnt;
-	zone->zone_start = 0;
+	zone->zone_end = smallest->sectors * cnt;
 
-	current_start = smallest->sectors;
-	curr_zone_start = zone->sectors;
+	curr_zone_end = zone->zone_end;
 
 	/* now do the other zones */
 	for (i = 1; i < conf->nr_strip_zones; i++)
 	{
 		zone = conf->strip_zone + i;
-		zone->dev = conf->strip_zone[i-1].dev + mddev->raid_disks;
+		dev = conf->devlist + i * mddev->raid_disks;
 
 		printk(KERN_INFO "raid0: zone %d\n", i);
-		zone->dev_start = current_start;
+		zone->dev_start = smallest->sectors;
 		smallest = NULL;
 		c = 0;
 
 		for (j=0; j<cnt; j++) {
 			char b[BDEVNAME_SIZE];
-			rdev = conf->strip_zone[0].dev[j];
+			rdev = conf->devlist[j];
 			printk(KERN_INFO "raid0: checking %s ...",
 				bdevname(rdev->bdev, b));
-			if (rdev->sectors <= current_start) {
+			if (rdev->sectors <= zone->dev_start) {
 				printk(KERN_INFO " nope.\n");
 				continue;
 			}
 			printk(KERN_INFO " contained as device %d\n", c);
-			zone->dev[c] = rdev;
+			dev[c] = rdev;
 			c++;
 			if (!smallest || rdev->sectors < smallest->sectors) {
 				smallest = rdev;
@@ -194,47 +226,39 @@
 		}
 
 		zone->nb_dev = c;
-		zone->sectors = (smallest->sectors - current_start) * c;
+		sectors = (smallest->sectors - zone->dev_start) * c;
 		printk(KERN_INFO "raid0: zone->nb_dev: %d, sectors: %llu\n",
-			zone->nb_dev, (unsigned long long)zone->sectors);
+			zone->nb_dev, (unsigned long long)sectors);
 
-		zone->zone_start = curr_zone_start;
-		curr_zone_start += zone->sectors;
+		curr_zone_end += sectors;
+		zone->zone_end = curr_zone_end;
 
-		current_start = smallest->sectors;
 		printk(KERN_INFO "raid0: current zone start: %llu\n",
-			(unsigned long long)current_start);
+			(unsigned long long)smallest->sectors);
 	}
-
-	/* Now find appropriate hash spacing.
-	 * We want a number which causes most hash entries to cover
-	 * at most two strips, but the hash table must be at most
-	 * 1 PAGE.  We choose the smallest strip, or contiguous collection
-	 * of strips, that has big enough size.  We never consider the last
-	 * strip though as it's size has no bearing on the efficacy of the hash
-	 * table.
-	 */
-	conf->spacing = curr_zone_start;
-	min_spacing = curr_zone_start;
-	sector_div(min_spacing, PAGE_SIZE/sizeof(struct strip_zone*));
-	for (i=0; i < conf->nr_strip_zones-1; i++) {
-		sector_t s = 0;
-		for (j = i; j < conf->nr_strip_zones - 1 &&
-				s < min_spacing; j++)
-			s += conf->strip_zone[j].sectors;
-		if (s >= min_spacing && s < conf->spacing)
-			conf->spacing = s;
-	}
-
 	mddev->queue->unplug_fn = raid0_unplug;
-
 	mddev->queue->backing_dev_info.congested_fn = raid0_congested;
 	mddev->queue->backing_dev_info.congested_data = mddev;
 
+	/*
+	 * now since we have the hard sector sizes, we can make sure
+	 * chunk size is a multiple of that sector size
+	 */
+	if ((mddev->chunk_sectors << 9) % queue_logical_block_size(mddev->queue)) {
+		printk(KERN_ERR "%s chunk_size of %d not valid\n",
+		       mdname(mddev),
+		       mddev->chunk_sectors << 9);
+		goto abort;
+	}
 	printk(KERN_INFO "raid0: done.\n");
+	mddev->private = conf;
 	return 0;
- abort:
-	return 1;
+abort:
+	kfree(conf->strip_zone);
+	kfree(conf->devlist);
+	kfree(conf);
+	mddev->private = NULL;
+	return err;
 }
 
 /**
@@ -252,10 +276,15 @@
 	mddev_t *mddev = q->queuedata;
 	sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
 	int max;
-	unsigned int chunk_sectors = mddev->chunk_size >> 9;
+	unsigned int chunk_sectors = mddev->chunk_sectors;
 	unsigned int bio_sectors = bvm->bi_size >> 9;
 
-	max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
+	if (is_power_of_2(chunk_sectors))
+		max =  (chunk_sectors - ((sector & (chunk_sectors-1))
+						+ bio_sectors)) << 9;
+	else
+		max =  (chunk_sectors - (sector_div(sector, chunk_sectors)
+						+ bio_sectors)) << 9;
 	if (max < 0) max = 0; /* bio_add cannot handle a negative return */
 	if (max <= biovec->bv_len && bio_sectors == 0)
 		return biovec->bv_len;
@@ -277,84 +306,28 @@
 	return array_sectors;
 }
 
-static int raid0_run (mddev_t *mddev)
+static int raid0_run(mddev_t *mddev)
 {
-	unsigned  cur=0, i=0, nb_zone;
-	s64 sectors;
-	raid0_conf_t *conf;
+	int ret;
 
-	if (mddev->chunk_size == 0) {
-		printk(KERN_ERR "md/raid0: non-zero chunk size required.\n");
+	if (mddev->chunk_sectors == 0) {
+		printk(KERN_ERR "md/raid0: chunk size must be set.\n");
 		return -EINVAL;
 	}
-	printk(KERN_INFO "%s: setting max_sectors to %d, segment boundary to %d\n",
-	       mdname(mddev),
-	       mddev->chunk_size >> 9,
-	       (mddev->chunk_size>>1)-1);
-	blk_queue_max_sectors(mddev->queue, mddev->chunk_size >> 9);
-	blk_queue_segment_boundary(mddev->queue, (mddev->chunk_size>>1) - 1);
+	if (md_check_no_bitmap(mddev))
+		return -EINVAL;
+	blk_queue_max_sectors(mddev->queue, mddev->chunk_sectors);
 	mddev->queue->queue_lock = &mddev->queue->__queue_lock;
 
-	conf = kmalloc(sizeof (raid0_conf_t), GFP_KERNEL);
-	if (!conf)
-		goto out;
-	mddev->private = (void *)conf;
- 
-	conf->strip_zone = NULL;
-	conf->devlist = NULL;
-	if (create_strip_zones (mddev)) 
-		goto out_free_conf;
+	ret = create_strip_zones(mddev);
+	if (ret < 0)
+		return ret;
 
 	/* calculate array device size */
 	md_set_array_sectors(mddev, raid0_size(mddev, 0, 0));
 
 	printk(KERN_INFO "raid0 : md_size is %llu sectors.\n",
 		(unsigned long long)mddev->array_sectors);
-	printk(KERN_INFO "raid0 : conf->spacing is %llu sectors.\n",
-		(unsigned long long)conf->spacing);
-	{
-		sector_t s = raid0_size(mddev, 0, 0);
-		sector_t space = conf->spacing;
-		int round;
-		conf->sector_shift = 0;
-		if (sizeof(sector_t) > sizeof(u32)) {
-			/*shift down space and s so that sector_div will work */
-			while (space > (sector_t) (~(u32)0)) {
-				s >>= 1;
-				space >>= 1;
-				s += 1; /* force round-up */
-				conf->sector_shift++;
-			}
-		}
-		round = sector_div(s, (u32)space) ? 1 : 0;
-		nb_zone = s + round;
-	}
-	printk(KERN_INFO "raid0 : nb_zone is %d.\n", nb_zone);
-
-	printk(KERN_INFO "raid0 : Allocating %zu bytes for hash.\n",
-				nb_zone*sizeof(struct strip_zone*));
-	conf->hash_table = kmalloc (sizeof (struct strip_zone *)*nb_zone, GFP_KERNEL);
-	if (!conf->hash_table)
-		goto out_free_conf;
-	sectors = conf->strip_zone[cur].sectors;
-
-	conf->hash_table[0] = conf->strip_zone + cur;
-	for (i=1; i< nb_zone; i++) {
-		while (sectors <= conf->spacing) {
-			cur++;
-			sectors += conf->strip_zone[cur].sectors;
-		}
-		sectors -= conf->spacing;
-		conf->hash_table[i] = conf->strip_zone + cur;
-	}
-	if (conf->sector_shift) {
-		conf->spacing >>= conf->sector_shift;
-		/* round spacing up so when we divide by it, we
-		 * err on the side of too-low, which is safest
-		 */
-		conf->spacing++;
-	}
-
 	/* calculate the max read-ahead size.
 	 * For read-ahead of large files to be effective, we need to
 	 * readahead at least twice a whole stripe. i.e. number of devices
@@ -365,48 +338,107 @@
 	 * chunksize should be used in that case.
 	 */
 	{
-		int stripe = mddev->raid_disks * mddev->chunk_size / PAGE_SIZE;
+		int stripe = mddev->raid_disks *
+			(mddev->chunk_sectors << 9) / PAGE_SIZE;
 		if (mddev->queue->backing_dev_info.ra_pages < 2* stripe)
 			mddev->queue->backing_dev_info.ra_pages = 2* stripe;
 	}
 
-
 	blk_queue_merge_bvec(mddev->queue, raid0_mergeable_bvec);
+	dump_zones(mddev);
 	return 0;
+}
 
-out_free_conf:
+static int raid0_stop(mddev_t *mddev)
+{
+	raid0_conf_t *conf = mddev->private;
+
+	blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
 	kfree(conf->strip_zone);
 	kfree(conf->devlist);
 	kfree(conf);
 	mddev->private = NULL;
-out:
-	return -ENOMEM;
-}
-
-static int raid0_stop (mddev_t *mddev)
-{
-	raid0_conf_t *conf = mddev_to_conf(mddev);
-
-	blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
-	kfree(conf->hash_table);
-	conf->hash_table = NULL;
-	kfree(conf->strip_zone);
-	conf->strip_zone = NULL;
-	kfree(conf);
-	mddev->private = NULL;
-
 	return 0;
 }
 
-static int raid0_make_request (struct request_queue *q, struct bio *bio)
+/* Find the zone which holds a particular offset
+ * Update *sectorp to be an offset in that zone
+ */
+static struct strip_zone *find_zone(struct raid0_private_data *conf,
+				    sector_t *sectorp)
+{
+	int i;
+	struct strip_zone *z = conf->strip_zone;
+	sector_t sector = *sectorp;
+
+	for (i = 0; i < conf->nr_strip_zones; i++)
+		if (sector < z[i].zone_end) {
+			if (i)
+				*sectorp = sector - z[i-1].zone_end;
+			return z + i;
+		}
+	BUG();
+}
+
+/*
+ * remaps the bio to the target device. we separate two flows.
+ * power 2 flow and a general flow for the sake of perfromance
+*/
+static mdk_rdev_t *map_sector(mddev_t *mddev, struct strip_zone *zone,
+				sector_t sector, sector_t *sector_offset)
+{
+	unsigned int sect_in_chunk;
+	sector_t chunk;
+	raid0_conf_t *conf = mddev->private;
+	unsigned int chunk_sects = mddev->chunk_sectors;
+
+	if (is_power_of_2(chunk_sects)) {
+		int chunksect_bits = ffz(~chunk_sects);
+		/* find the sector offset inside the chunk */
+		sect_in_chunk  = sector & (chunk_sects - 1);
+		sector >>= chunksect_bits;
+		/* chunk in zone */
+		chunk = *sector_offset;
+		/* quotient is the chunk in real device*/
+		sector_div(chunk, zone->nb_dev << chunksect_bits);
+	} else{
+		sect_in_chunk = sector_div(sector, chunk_sects);
+		chunk = *sector_offset;
+		sector_div(chunk, chunk_sects * zone->nb_dev);
+	}
+	/*
+	*  position the bio over the real device
+	*  real sector = chunk in device + starting of zone
+	*	+ the position in the chunk
+	*/
+	*sector_offset = (chunk * chunk_sects) + sect_in_chunk;
+	return conf->devlist[(zone - conf->strip_zone)*mddev->raid_disks
+			     + sector_div(sector, zone->nb_dev)];
+}
+
+/*
+ * Is io distribute over 1 or more chunks ?
+*/
+static inline int is_io_in_chunk_boundary(mddev_t *mddev,
+			unsigned int chunk_sects, struct bio *bio)
+{
+	if (likely(is_power_of_2(chunk_sects))) {
+		return chunk_sects >= ((bio->bi_sector & (chunk_sects-1))
+					+ (bio->bi_size >> 9));
+	} else{
+		sector_t sector = bio->bi_sector;
+		return chunk_sects >= (sector_div(sector, chunk_sects)
+						+ (bio->bi_size >> 9));
+	}
+}
+
+static int raid0_make_request(struct request_queue *q, struct bio *bio)
 {
 	mddev_t *mddev = q->queuedata;
-	unsigned int sect_in_chunk, chunksect_bits, chunk_sects;
-	raid0_conf_t *conf = mddev_to_conf(mddev);
+	unsigned int chunk_sects;
+	sector_t sector_offset;
 	struct strip_zone *zone;
 	mdk_rdev_t *tmp_dev;
-	sector_t chunk;
-	sector_t sector, rsect;
 	const int rw = bio_data_dir(bio);
 	int cpu;
 
@@ -421,11 +453,9 @@
 		      bio_sectors(bio));
 	part_stat_unlock();
 
-	chunk_sects = mddev->chunk_size >> 9;
-	chunksect_bits = ffz(~chunk_sects);
-	sector = bio->bi_sector;
-
-	if (unlikely(chunk_sects < (bio->bi_sector & (chunk_sects - 1)) + (bio->bi_size >> 9))) {
+	chunk_sects = mddev->chunk_sectors;
+	if (unlikely(!is_io_in_chunk_boundary(mddev, chunk_sects, bio))) {
+		sector_t sector = bio->bi_sector;
 		struct bio_pair *bp;
 		/* Sanity check -- queue functions should prevent this happening */
 		if (bio->bi_vcnt != 1 ||
@@ -434,7 +464,12 @@
 		/* This is a one page bio that upper layers
 		 * refuse to split for us, so we need to split it.
 		 */
-		bp = bio_split(bio, chunk_sects - (bio->bi_sector & (chunk_sects - 1)));
+		if (likely(is_power_of_2(chunk_sects)))
+			bp = bio_split(bio, chunk_sects - (sector &
+							   (chunk_sects-1)));
+		else
+			bp = bio_split(bio, chunk_sects -
+				       sector_div(sector, chunk_sects));
 		if (raid0_make_request(q, &bp->bio1))
 			generic_make_request(&bp->bio1);
 		if (raid0_make_request(q, &bp->bio2))
@@ -443,34 +478,14 @@
 		bio_pair_release(bp);
 		return 0;
 	}
- 
 
-	{
-		sector_t x = sector >> conf->sector_shift;
-		sector_div(x, (u32)conf->spacing);
-		zone = conf->hash_table[x];
-	}
-
-	while (sector >= zone->zone_start + zone->sectors)
-		zone++;
-
-	sect_in_chunk = bio->bi_sector & (chunk_sects - 1);
-
-
-	{
-		sector_t x = (sector - zone->zone_start) >> chunksect_bits;
-
-		sector_div(x, zone->nb_dev);
-		chunk = x;
-
-		x = sector >> chunksect_bits;
-		tmp_dev = zone->dev[sector_div(x, zone->nb_dev)];
-	}
-	rsect = (chunk << chunksect_bits) + zone->dev_start + sect_in_chunk;
- 
+	sector_offset = bio->bi_sector;
+	zone =  find_zone(mddev->private, &sector_offset);
+	tmp_dev = map_sector(mddev, zone, bio->bi_sector,
+			     &sector_offset);
 	bio->bi_bdev = tmp_dev->bdev;
-	bio->bi_sector = rsect + tmp_dev->data_offset;
-
+	bio->bi_sector = sector_offset + zone->dev_start +
+		tmp_dev->data_offset;
 	/*
 	 * Let the main block layer submit the IO and resolve recursion:
 	 */
@@ -485,31 +500,35 @@
 	return 0;
 }
 
-static void raid0_status (struct seq_file *seq, mddev_t *mddev)
+static void raid0_status(struct seq_file *seq, mddev_t *mddev)
 {
 #undef MD_DEBUG
 #ifdef MD_DEBUG
 	int j, k, h;
 	char b[BDEVNAME_SIZE];
-	raid0_conf_t *conf = mddev_to_conf(mddev);
+	raid0_conf_t *conf = mddev->private;
 
+	sector_t zone_size;
+	sector_t zone_start = 0;
 	h = 0;
+
 	for (j = 0; j < conf->nr_strip_zones; j++) {
 		seq_printf(seq, "      z%d", j);
-		if (conf->hash_table[h] == conf->strip_zone+j)
-			seq_printf(seq, "(h%d)", h++);
 		seq_printf(seq, "=[");
 		for (k = 0; k < conf->strip_zone[j].nb_dev; k++)
 			seq_printf(seq, "%s/", bdevname(
-				conf->strip_zone[j].dev[k]->bdev,b));
+				conf->devlist[j*mddev->raid_disks + k]
+						->bdev, b));
 
-		seq_printf(seq, "] zs=%d ds=%d s=%d\n",
-				conf->strip_zone[j].zone_start,
-				conf->strip_zone[j].dev_start,
-				conf->strip_zone[j].sectors);
+		zone_size  = conf->strip_zone[j].zone_end - zone_start;
+		seq_printf(seq, "] ze=%lld ds=%lld s=%lld\n",
+			(unsigned long long)zone_start>>1,
+			(unsigned long long)conf->strip_zone[j].dev_start>>1,
+			(unsigned long long)zone_size>>1);
+		zone_start = conf->strip_zone[j].zone_end;
 	}
 #endif
-	seq_printf(seq, " %dk chunks", mddev->chunk_size/1024);
+	seq_printf(seq, " %dk chunks", mddev->chunk_sectors / 2);
 	return;
 }
 
diff --git a/drivers/md/raid0.h b/drivers/md/raid0.h
index 824b12e..91f8e87 100644
--- a/drivers/md/raid0.h
+++ b/drivers/md/raid0.h
@@ -3,26 +3,18 @@
 
 struct strip_zone
 {
-	sector_t zone_start;	/* Zone offset in md_dev (in sectors) */
+	sector_t zone_end;	/* Start of the next zone (in sectors) */
 	sector_t dev_start;	/* Zone offset in real dev (in sectors) */
-	sector_t sectors;	/* Zone size in sectors */
 	int nb_dev;		/* # of devices attached to the zone */
-	mdk_rdev_t **dev;	/* Devices attached to the zone */
 };
 
 struct raid0_private_data
 {
-	struct strip_zone **hash_table; /* Table of indexes into strip_zone */
 	struct strip_zone *strip_zone;
 	mdk_rdev_t **devlist; /* lists of rdevs, pointed to by strip_zone->dev */
 	int nr_strip_zones;
-
-	sector_t spacing;
-	int sector_shift; /* shift this before divide by spacing */
 };
 
 typedef struct raid0_private_data raid0_conf_t;
 
-#define mddev_to_conf(mddev) ((raid0_conf_t *) mddev->private)
-
 #endif
diff --git a/drivers/md/raid1.c b/drivers/md/raid1.c
index e23758b..89939a7 100644
--- a/drivers/md/raid1.c
+++ b/drivers/md/raid1.c
@@ -182,7 +182,7 @@
 
 static void free_r1bio(r1bio_t *r1_bio)
 {
-	conf_t *conf = mddev_to_conf(r1_bio->mddev);
+	conf_t *conf = r1_bio->mddev->private;
 
 	/*
 	 * Wake up any possible resync thread that waits for the device
@@ -196,7 +196,7 @@
 
 static void put_buf(r1bio_t *r1_bio)
 {
-	conf_t *conf = mddev_to_conf(r1_bio->mddev);
+	conf_t *conf = r1_bio->mddev->private;
 	int i;
 
 	for (i=0; i<conf->raid_disks; i++) {
@@ -214,7 +214,7 @@
 {
 	unsigned long flags;
 	mddev_t *mddev = r1_bio->mddev;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 
 	spin_lock_irqsave(&conf->device_lock, flags);
 	list_add(&r1_bio->retry_list, &conf->retry_list);
@@ -253,7 +253,7 @@
  */
 static inline void update_head_pos(int disk, r1bio_t *r1_bio)
 {
-	conf_t *conf = mddev_to_conf(r1_bio->mddev);
+	conf_t *conf = r1_bio->mddev->private;
 
 	conf->mirrors[disk].head_position =
 		r1_bio->sector + (r1_bio->sectors);
@@ -264,7 +264,7 @@
 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
 	r1bio_t * r1_bio = (r1bio_t *)(bio->bi_private);
 	int mirror;
-	conf_t *conf = mddev_to_conf(r1_bio->mddev);
+	conf_t *conf = r1_bio->mddev->private;
 
 	mirror = r1_bio->read_disk;
 	/*
@@ -309,7 +309,7 @@
 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
 	r1bio_t * r1_bio = (r1bio_t *)(bio->bi_private);
 	int mirror, behind = test_bit(R1BIO_BehindIO, &r1_bio->state);
-	conf_t *conf = mddev_to_conf(r1_bio->mddev);
+	conf_t *conf = r1_bio->mddev->private;
 	struct bio *to_put = NULL;
 
 
@@ -541,7 +541,7 @@
 
 static void unplug_slaves(mddev_t *mddev)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int i;
 
 	rcu_read_lock();
@@ -573,7 +573,7 @@
 static int raid1_congested(void *data, int bits)
 {
 	mddev_t *mddev = data;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int i, ret = 0;
 
 	rcu_read_lock();
@@ -772,7 +772,7 @@
 static int make_request(struct request_queue *q, struct bio * bio)
 {
 	mddev_t *mddev = q->queuedata;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	mirror_info_t *mirror;
 	r1bio_t *r1_bio;
 	struct bio *read_bio;
@@ -991,7 +991,7 @@
 
 static void status(struct seq_file *seq, mddev_t *mddev)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int i;
 
 	seq_printf(seq, " [%d/%d] [", conf->raid_disks,
@@ -1010,7 +1010,7 @@
 static void error(mddev_t *mddev, mdk_rdev_t *rdev)
 {
 	char b[BDEVNAME_SIZE];
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 
 	/*
 	 * If it is not operational, then we have already marked it as dead
@@ -1214,7 +1214,7 @@
 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
 	r1bio_t * r1_bio = (r1bio_t *)(bio->bi_private);
 	mddev_t *mddev = r1_bio->mddev;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int i;
 	int mirror=0;
 
@@ -1248,7 +1248,7 @@
 
 static void sync_request_write(mddev_t *mddev, r1bio_t *r1_bio)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int i;
 	int disks = conf->raid_disks;
 	struct bio *bio, *wbio;
@@ -1562,7 +1562,7 @@
 	r1bio_t *r1_bio;
 	struct bio *bio;
 	unsigned long flags;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	struct list_head *head = &conf->retry_list;
 	int unplug=0;
 	mdk_rdev_t *rdev;
@@ -1585,7 +1585,7 @@
 		spin_unlock_irqrestore(&conf->device_lock, flags);
 
 		mddev = r1_bio->mddev;
-		conf = mddev_to_conf(mddev);
+		conf = mddev->private;
 		if (test_bit(R1BIO_IsSync, &r1_bio->state)) {
 			sync_request_write(mddev, r1_bio);
 			unplug = 1;
@@ -1706,7 +1706,7 @@
 
 static sector_t sync_request(mddev_t *mddev, sector_t sector_nr, int *skipped, int go_faster)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	r1bio_t *r1_bio;
 	struct bio *bio;
 	sector_t max_sector, nr_sectors;
@@ -2052,6 +2052,10 @@
 		goto out_free_conf;
 	}
 
+	if (mddev->recovery_cp != MaxSector)
+		printk(KERN_NOTICE "raid1: %s is not clean"
+		       " -- starting background reconstruction\n",
+		       mdname(mddev));
 	printk(KERN_INFO 
 		"raid1: raid set %s active with %d out of %d mirrors\n",
 		mdname(mddev), mddev->raid_disks - mddev->degraded, 
@@ -2087,7 +2091,7 @@
 
 static int stop(mddev_t *mddev)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	struct bitmap *bitmap = mddev->bitmap;
 	int behind_wait = 0;
 
@@ -2155,16 +2159,16 @@
 	mempool_t *newpool, *oldpool;
 	struct pool_info *newpoolinfo;
 	mirror_info_t *newmirrors;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int cnt, raid_disks;
 	unsigned long flags;
 	int d, d2, err;
 
 	/* Cannot change chunk_size, layout, or level */
-	if (mddev->chunk_size != mddev->new_chunk ||
+	if (mddev->chunk_sectors != mddev->new_chunk_sectors ||
 	    mddev->layout != mddev->new_layout ||
 	    mddev->level != mddev->new_level) {
-		mddev->new_chunk = mddev->chunk_size;
+		mddev->new_chunk_sectors = mddev->chunk_sectors;
 		mddev->new_layout = mddev->layout;
 		mddev->new_level = mddev->level;
 		return -EINVAL;
@@ -2252,7 +2256,7 @@
 
 static void raid1_quiesce(mddev_t *mddev, int state)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 
 	switch(state) {
 	case 1:
diff --git a/drivers/md/raid1.h b/drivers/md/raid1.h
index 1620eea..e87b84d 100644
--- a/drivers/md/raid1.h
+++ b/drivers/md/raid1.h
@@ -64,12 +64,6 @@
 typedef struct r1_private_data_s conf_t;
 
 /*
- * this is the only point in the RAID code where we violate
- * C type safety. mddev->private is an 'opaque' pointer.
- */
-#define mddev_to_conf(mddev) ((conf_t *) mddev->private)
-
-/*
  * this is our 'private' RAID1 bio.
  *
  * it contains information about what kind of IO operations were started
diff --git a/drivers/md/raid10.c b/drivers/md/raid10.c
index 750550c..ae12cea 100644
--- a/drivers/md/raid10.c
+++ b/drivers/md/raid10.c
@@ -188,7 +188,7 @@
 
 static void free_r10bio(r10bio_t *r10_bio)
 {
-	conf_t *conf = mddev_to_conf(r10_bio->mddev);
+	conf_t *conf = r10_bio->mddev->private;
 
 	/*
 	 * Wake up any possible resync thread that waits for the device
@@ -202,7 +202,7 @@
 
 static void put_buf(r10bio_t *r10_bio)
 {
-	conf_t *conf = mddev_to_conf(r10_bio->mddev);
+	conf_t *conf = r10_bio->mddev->private;
 
 	mempool_free(r10_bio, conf->r10buf_pool);
 
@@ -213,7 +213,7 @@
 {
 	unsigned long flags;
 	mddev_t *mddev = r10_bio->mddev;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 
 	spin_lock_irqsave(&conf->device_lock, flags);
 	list_add(&r10_bio->retry_list, &conf->retry_list);
@@ -245,7 +245,7 @@
  */
 static inline void update_head_pos(int slot, r10bio_t *r10_bio)
 {
-	conf_t *conf = mddev_to_conf(r10_bio->mddev);
+	conf_t *conf = r10_bio->mddev->private;
 
 	conf->mirrors[r10_bio->devs[slot].devnum].head_position =
 		r10_bio->devs[slot].addr + (r10_bio->sectors);
@@ -256,7 +256,7 @@
 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
 	r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
 	int slot, dev;
-	conf_t *conf = mddev_to_conf(r10_bio->mddev);
+	conf_t *conf = r10_bio->mddev->private;
 
 
 	slot = r10_bio->read_slot;
@@ -297,7 +297,7 @@
 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
 	r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
 	int slot, dev;
-	conf_t *conf = mddev_to_conf(r10_bio->mddev);
+	conf_t *conf = r10_bio->mddev->private;
 
 	for (slot = 0; slot < conf->copies; slot++)
 		if (r10_bio->devs[slot].bio == bio)
@@ -461,7 +461,7 @@
 	mddev_t *mddev = q->queuedata;
 	sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
 	int max;
-	unsigned int chunk_sectors = mddev->chunk_size >> 9;
+	unsigned int chunk_sectors = mddev->chunk_sectors;
 	unsigned int bio_sectors = bvm->bi_size >> 9;
 
 	max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
@@ -596,7 +596,7 @@
 
 static void unplug_slaves(mddev_t *mddev)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int i;
 
 	rcu_read_lock();
@@ -628,7 +628,7 @@
 static int raid10_congested(void *data, int bits)
 {
 	mddev_t *mddev = data;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int i, ret = 0;
 
 	rcu_read_lock();
@@ -788,7 +788,7 @@
 static int make_request(struct request_queue *q, struct bio * bio)
 {
 	mddev_t *mddev = q->queuedata;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	mirror_info_t *mirror;
 	r10bio_t *r10_bio;
 	struct bio *read_bio;
@@ -981,11 +981,11 @@
 
 static void status(struct seq_file *seq, mddev_t *mddev)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int i;
 
 	if (conf->near_copies < conf->raid_disks)
-		seq_printf(seq, " %dK chunks", mddev->chunk_size/1024);
+		seq_printf(seq, " %dK chunks", mddev->chunk_sectors / 2);
 	if (conf->near_copies > 1)
 		seq_printf(seq, " %d near-copies", conf->near_copies);
 	if (conf->far_copies > 1) {
@@ -1006,7 +1006,7 @@
 static void error(mddev_t *mddev, mdk_rdev_t *rdev)
 {
 	char b[BDEVNAME_SIZE];
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 
 	/*
 	 * If it is not operational, then we have already marked it as dead
@@ -1215,7 +1215,7 @@
 static void end_sync_read(struct bio *bio, int error)
 {
 	r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
-	conf_t *conf = mddev_to_conf(r10_bio->mddev);
+	conf_t *conf = r10_bio->mddev->private;
 	int i,d;
 
 	for (i=0; i<conf->copies; i++)
@@ -1253,7 +1253,7 @@
 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
 	r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
 	mddev_t *mddev = r10_bio->mddev;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int i,d;
 
 	for (i = 0; i < conf->copies; i++)
@@ -1300,7 +1300,7 @@
  */
 static void sync_request_write(mddev_t *mddev, r10bio_t *r10_bio)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int i, first;
 	struct bio *tbio, *fbio;
 
@@ -1400,7 +1400,7 @@
 
 static void recovery_request_write(mddev_t *mddev, r10bio_t *r10_bio)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	int i, d;
 	struct bio *bio, *wbio;
 
@@ -1549,7 +1549,7 @@
 	r10bio_t *r10_bio;
 	struct bio *bio;
 	unsigned long flags;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	struct list_head *head = &conf->retry_list;
 	int unplug=0;
 	mdk_rdev_t *rdev;
@@ -1572,7 +1572,7 @@
 		spin_unlock_irqrestore(&conf->device_lock, flags);
 
 		mddev = r10_bio->mddev;
-		conf = mddev_to_conf(mddev);
+		conf = mddev->private;
 		if (test_bit(R10BIO_IsSync, &r10_bio->state)) {
 			sync_request_write(mddev, r10_bio);
 			unplug = 1;
@@ -1680,7 +1680,7 @@
 
 static sector_t sync_request(mddev_t *mddev, sector_t sector_nr, int *skipped, int go_faster)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 	r10bio_t *r10_bio;
 	struct bio *biolist = NULL, *bio;
 	sector_t max_sector, nr_sectors;
@@ -2026,7 +2026,7 @@
 raid10_size(mddev_t *mddev, sector_t sectors, int raid_disks)
 {
 	sector_t size;
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 
 	if (!raid_disks)
 		raid_disks = mddev->raid_disks;
@@ -2050,9 +2050,10 @@
 	int nc, fc, fo;
 	sector_t stride, size;
 
-	if (mddev->chunk_size < PAGE_SIZE) {
+	if (mddev->chunk_sectors < (PAGE_SIZE >> 9) ||
+	    !is_power_of_2(mddev->chunk_sectors)) {
 		printk(KERN_ERR "md/raid10: chunk size must be "
-		       "at least PAGE_SIZE(%ld).\n", PAGE_SIZE);
+		       "at least PAGE_SIZE(%ld) and be a power of 2.\n", PAGE_SIZE);
 		return -EINVAL;
 	}
 
@@ -2095,8 +2096,8 @@
 	conf->far_copies = fc;
 	conf->copies = nc*fc;
 	conf->far_offset = fo;
-	conf->chunk_mask = (sector_t)(mddev->chunk_size>>9)-1;
-	conf->chunk_shift = ffz(~mddev->chunk_size) - 9;
+	conf->chunk_mask = mddev->chunk_sectors - 1;
+	conf->chunk_shift = ffz(~mddev->chunk_sectors);
 	size = mddev->dev_sectors >> conf->chunk_shift;
 	sector_div(size, fc);
 	size = size * conf->raid_disks;
@@ -2185,6 +2186,10 @@
 		goto out_free_conf;
 	}
 
+	if (mddev->recovery_cp != MaxSector)
+		printk(KERN_NOTICE "raid10: %s is not clean"
+		       " -- starting background reconstruction\n",
+		       mdname(mddev));
 	printk(KERN_INFO
 		"raid10: raid set %s active with %d out of %d devices\n",
 		mdname(mddev), mddev->raid_disks - mddev->degraded,
@@ -2204,7 +2209,8 @@
 	 * maybe...
 	 */
 	{
-		int stripe = conf->raid_disks * (mddev->chunk_size / PAGE_SIZE);
+		int stripe = conf->raid_disks *
+			((mddev->chunk_sectors << 9) / PAGE_SIZE);
 		stripe /= conf->near_copies;
 		if (mddev->queue->backing_dev_info.ra_pages < 2* stripe)
 			mddev->queue->backing_dev_info.ra_pages = 2* stripe;
@@ -2227,7 +2233,7 @@
 
 static int stop(mddev_t *mddev)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 
 	raise_barrier(conf, 0);
 	lower_barrier(conf);
@@ -2245,7 +2251,7 @@
 
 static void raid10_quiesce(mddev_t *mddev, int state)
 {
-	conf_t *conf = mddev_to_conf(mddev);
+	conf_t *conf = mddev->private;
 
 	switch(state) {
 	case 1:
diff --git a/drivers/md/raid10.h b/drivers/md/raid10.h
index 244dbe5..59cd1ef 100644
--- a/drivers/md/raid10.h
+++ b/drivers/md/raid10.h
@@ -62,12 +62,6 @@
 typedef struct r10_private_data_s conf_t;
 
 /*
- * this is the only point in the RAID code where we violate
- * C type safety. mddev->private is an 'opaque' pointer.
- */
-#define mddev_to_conf(mddev) ((conf_t *) mddev->private)
-
-/*
  * this is our 'private' RAID10 bio.
  *
  * it contains information about what kind of IO operations were started
diff --git a/drivers/md/raid5.c b/drivers/md/raid5.c
index bef8766..f9f991e 100644
--- a/drivers/md/raid5.c
+++ b/drivers/md/raid5.c
@@ -1274,8 +1274,8 @@
 	sector_t new_sector;
 	int algorithm = previous ? conf->prev_algo
 				 : conf->algorithm;
-	int sectors_per_chunk = previous ? (conf->prev_chunk >> 9)
-					 : (conf->chunk_size >> 9);
+	int sectors_per_chunk = previous ? conf->prev_chunk_sectors
+					 : conf->chunk_sectors;
 	int raid_disks = previous ? conf->previous_raid_disks
 				  : conf->raid_disks;
 	int data_disks = raid_disks - conf->max_degraded;
@@ -1480,8 +1480,8 @@
 	int raid_disks = sh->disks;
 	int data_disks = raid_disks - conf->max_degraded;
 	sector_t new_sector = sh->sector, check;
-	int sectors_per_chunk = previous ? (conf->prev_chunk >> 9)
-					 : (conf->chunk_size >> 9);
+	int sectors_per_chunk = previous ? conf->prev_chunk_sectors
+					 : conf->chunk_sectors;
 	int algorithm = previous ? conf->prev_algo
 				 : conf->algorithm;
 	sector_t stripe;
@@ -1997,8 +1997,7 @@
 			    struct stripe_head *sh)
 {
 	int sectors_per_chunk =
-		previous ? (conf->prev_chunk >> 9)
-			 : (conf->chunk_size >> 9);
+		previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
 	int dd_idx;
 	int chunk_offset = sector_div(stripe, sectors_per_chunk);
 	int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
@@ -3284,7 +3283,7 @@
 
 static void unplug_slaves(mddev_t *mddev)
 {
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 	int i;
 
 	rcu_read_lock();
@@ -3308,7 +3307,7 @@
 static void raid5_unplug_device(struct request_queue *q)
 {
 	mddev_t *mddev = q->queuedata;
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 	unsigned long flags;
 
 	spin_lock_irqsave(&conf->device_lock, flags);
@@ -3327,7 +3326,7 @@
 static int raid5_congested(void *data, int bits)
 {
 	mddev_t *mddev = data;
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 
 	/* No difference between reads and writes.  Just check
 	 * how busy the stripe_cache is
@@ -3352,14 +3351,14 @@
 	mddev_t *mddev = q->queuedata;
 	sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
 	int max;
-	unsigned int chunk_sectors = mddev->chunk_size >> 9;
+	unsigned int chunk_sectors = mddev->chunk_sectors;
 	unsigned int bio_sectors = bvm->bi_size >> 9;
 
 	if ((bvm->bi_rw & 1) == WRITE)
 		return biovec->bv_len; /* always allow writes to be mergeable */
 
-	if (mddev->new_chunk < mddev->chunk_size)
-		chunk_sectors = mddev->new_chunk >> 9;
+	if (mddev->new_chunk_sectors < mddev->chunk_sectors)
+		chunk_sectors = mddev->new_chunk_sectors;
 	max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
 	if (max < 0) max = 0;
 	if (max <= biovec->bv_len && bio_sectors == 0)
@@ -3372,11 +3371,11 @@
 static int in_chunk_boundary(mddev_t *mddev, struct bio *bio)
 {
 	sector_t sector = bio->bi_sector + get_start_sect(bio->bi_bdev);
-	unsigned int chunk_sectors = mddev->chunk_size >> 9;
+	unsigned int chunk_sectors = mddev->chunk_sectors;
 	unsigned int bio_sectors = bio->bi_size >> 9;
 
-	if (mddev->new_chunk < mddev->chunk_size)
-		chunk_sectors = mddev->new_chunk >> 9;
+	if (mddev->new_chunk_sectors < mddev->chunk_sectors)
+		chunk_sectors = mddev->new_chunk_sectors;
 	return  chunk_sectors >=
 		((sector & (chunk_sectors - 1)) + bio_sectors);
 }
@@ -3440,7 +3439,7 @@
 	bio_put(bi);
 
 	mddev = raid_bi->bi_bdev->bd_disk->queue->queuedata;
-	conf = mddev_to_conf(mddev);
+	conf = mddev->private;
 	rdev = (void*)raid_bi->bi_next;
 	raid_bi->bi_next = NULL;
 
@@ -3482,7 +3481,7 @@
 static int chunk_aligned_read(struct request_queue *q, struct bio * raid_bio)
 {
 	mddev_t *mddev = q->queuedata;
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 	unsigned int dd_idx;
 	struct bio* align_bi;
 	mdk_rdev_t *rdev;
@@ -3599,7 +3598,7 @@
 static int make_request(struct request_queue *q, struct bio * bi)
 {
 	mddev_t *mddev = q->queuedata;
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 	int dd_idx;
 	sector_t new_sector;
 	sector_t logical_sector, last_sector;
@@ -3696,6 +3695,7 @@
 				spin_unlock_irq(&conf->device_lock);
 				if (must_retry) {
 					release_stripe(sh);
+					schedule();
 					goto retry;
 				}
 			}
@@ -3791,10 +3791,10 @@
 	 * If old and new chunk sizes differ, we need to process the
 	 * largest of these
 	 */
-	if (mddev->new_chunk > mddev->chunk_size)
-		reshape_sectors = mddev->new_chunk / 512;
+	if (mddev->new_chunk_sectors > mddev->chunk_sectors)
+		reshape_sectors = mddev->new_chunk_sectors;
 	else
-		reshape_sectors = mddev->chunk_size / 512;
+		reshape_sectors = mddev->chunk_sectors;
 
 	/* we update the metadata when there is more than 3Meg
 	 * in the block range (that is rather arbitrary, should
@@ -3917,7 +3917,7 @@
 				     1, &dd_idx, NULL);
 	last_sector =
 		raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
-					    *(new_data_disks) - 1),
+					    * new_data_disks - 1),
 				     1, &dd_idx, NULL);
 	if (last_sector >= mddev->dev_sectors)
 		last_sector = mddev->dev_sectors - 1;
@@ -3946,7 +3946,7 @@
 		wait_event(conf->wait_for_overlap,
 			   atomic_read(&conf->reshape_stripes) == 0);
 		mddev->reshape_position = conf->reshape_progress;
-		mddev->curr_resync_completed = mddev->curr_resync;
+		mddev->curr_resync_completed = mddev->curr_resync + reshape_sectors;
 		conf->reshape_checkpoint = jiffies;
 		set_bit(MD_CHANGE_DEVS, &mddev->flags);
 		md_wakeup_thread(mddev->thread);
@@ -4129,7 +4129,7 @@
 static void raid5d(mddev_t *mddev)
 {
 	struct stripe_head *sh;
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 	int handled;
 
 	pr_debug("+++ raid5d active\n");
@@ -4185,7 +4185,7 @@
 static ssize_t
 raid5_show_stripe_cache_size(mddev_t *mddev, char *page)
 {
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 	if (conf)
 		return sprintf(page, "%d\n", conf->max_nr_stripes);
 	else
@@ -4195,7 +4195,7 @@
 static ssize_t
 raid5_store_stripe_cache_size(mddev_t *mddev, const char *page, size_t len)
 {
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 	unsigned long new;
 	int err;
 
@@ -4233,7 +4233,7 @@
 static ssize_t
 raid5_show_preread_threshold(mddev_t *mddev, char *page)
 {
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 	if (conf)
 		return sprintf(page, "%d\n", conf->bypass_threshold);
 	else
@@ -4243,7 +4243,7 @@
 static ssize_t
 raid5_store_preread_threshold(mddev_t *mddev, const char *page, size_t len)
 {
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 	unsigned long new;
 	if (len >= PAGE_SIZE)
 		return -EINVAL;
@@ -4267,7 +4267,7 @@
 static ssize_t
 stripe_cache_active_show(mddev_t *mddev, char *page)
 {
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 	if (conf)
 		return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
 	else
@@ -4291,7 +4291,7 @@
 static sector_t
 raid5_size(mddev_t *mddev, sector_t sectors, int raid_disks)
 {
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 
 	if (!sectors)
 		sectors = mddev->dev_sectors;
@@ -4303,8 +4303,8 @@
 			raid_disks = conf->previous_raid_disks;
 	}
 
-	sectors &= ~((sector_t)mddev->chunk_size/512 - 1);
-	sectors &= ~((sector_t)mddev->new_chunk/512 - 1);
+	sectors &= ~((sector_t)mddev->chunk_sectors - 1);
+	sectors &= ~((sector_t)mddev->new_chunk_sectors - 1);
 	return sectors * (raid_disks - conf->max_degraded);
 }
 
@@ -4336,9 +4336,11 @@
 		return ERR_PTR(-EINVAL);
 	}
 
-	if (!mddev->new_chunk || mddev->new_chunk % PAGE_SIZE) {
+	if (!mddev->new_chunk_sectors ||
+	    (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
+	    !is_power_of_2(mddev->new_chunk_sectors)) {
 		printk(KERN_ERR "raid5: invalid chunk size %d for %s\n",
-			mddev->new_chunk, mdname(mddev));
+		       mddev->new_chunk_sectors << 9, mdname(mddev));
 		return ERR_PTR(-EINVAL);
 	}
 
@@ -4401,7 +4403,7 @@
 			conf->fullsync = 1;
 	}
 
-	conf->chunk_size = mddev->new_chunk;
+	conf->chunk_sectors = mddev->new_chunk_sectors;
 	conf->level = mddev->new_level;
 	if (conf->level == 6)
 		conf->max_degraded = 2;
@@ -4411,7 +4413,7 @@
 	conf->max_nr_stripes = NR_STRIPES;
 	conf->reshape_progress = mddev->reshape_position;
 	if (conf->reshape_progress != MaxSector) {
-		conf->prev_chunk = mddev->chunk_size;
+		conf->prev_chunk_sectors = mddev->chunk_sectors;
 		conf->prev_algo = mddev->layout;
 	}
 
@@ -4453,6 +4455,10 @@
 	int working_disks = 0;
 	mdk_rdev_t *rdev;
 
+	if (mddev->recovery_cp != MaxSector)
+		printk(KERN_NOTICE "raid5: %s is not clean"
+		       " -- starting background reconstruction\n",
+		       mdname(mddev));
 	if (mddev->reshape_position != MaxSector) {
 		/* Check that we can continue the reshape.
 		 * Currently only disks can change, it must
@@ -4475,7 +4481,7 @@
 		 * geometry.
 		 */
 		here_new = mddev->reshape_position;
-		if (sector_div(here_new, (mddev->new_chunk>>9)*
+		if (sector_div(here_new, mddev->new_chunk_sectors *
 			       (mddev->raid_disks - max_degraded))) {
 			printk(KERN_ERR "raid5: reshape_position not "
 			       "on a stripe boundary\n");
@@ -4483,7 +4489,7 @@
 		}
 		/* here_new is the stripe we will write to */
 		here_old = mddev->reshape_position;
-		sector_div(here_old, (mddev->chunk_size>>9)*
+		sector_div(here_old, mddev->chunk_sectors *
 			   (old_disks-max_degraded));
 		/* here_old is the first stripe that we might need to read
 		 * from */
@@ -4498,7 +4504,7 @@
 	} else {
 		BUG_ON(mddev->level != mddev->new_level);
 		BUG_ON(mddev->layout != mddev->new_layout);
-		BUG_ON(mddev->chunk_size != mddev->new_chunk);
+		BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
 		BUG_ON(mddev->delta_disks != 0);
 	}
 
@@ -4532,7 +4538,7 @@
 	}
 
 	/* device size must be a multiple of chunk size */
-	mddev->dev_sectors &= ~(mddev->chunk_size / 512 - 1);
+	mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
 	mddev->resync_max_sectors = mddev->dev_sectors;
 
 	if (mddev->degraded > 0 &&
@@ -4581,7 +4587,7 @@
 	{
 		int data_disks = conf->previous_raid_disks - conf->max_degraded;
 		int stripe = data_disks *
-			(mddev->chunk_size / PAGE_SIZE);
+			((mddev->chunk_sectors << 9) / PAGE_SIZE);
 		if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
 			mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
 	}
@@ -4678,7 +4684,8 @@
 	raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
 	int i;
 
-	seq_printf (seq, " level %d, %dk chunk, algorithm %d", mddev->level, mddev->chunk_size >> 10, mddev->layout);
+	seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
+		mddev->chunk_sectors / 2, mddev->layout);
 	seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
 	for (i = 0; i < conf->raid_disks; i++)
 		seq_printf (seq, "%s",
@@ -4826,7 +4833,7 @@
 	 * any io in the removed space completes, but it hardly seems
 	 * worth it.
 	 */
-	sectors &= ~((sector_t)mddev->chunk_size/512 - 1);
+	sectors &= ~((sector_t)mddev->chunk_sectors - 1);
 	md_set_array_sectors(mddev, raid5_size(mddev, sectors,
 					       mddev->raid_disks));
 	if (mddev->array_sectors >
@@ -4843,14 +4850,37 @@
 	return 0;
 }
 
-static int raid5_check_reshape(mddev_t *mddev)
+static int check_stripe_cache(mddev_t *mddev)
 {
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	/* Can only proceed if there are plenty of stripe_heads.
+	 * We need a minimum of one full stripe,, and for sensible progress
+	 * it is best to have about 4 times that.
+	 * If we require 4 times, then the default 256 4K stripe_heads will
+	 * allow for chunk sizes up to 256K, which is probably OK.
+	 * If the chunk size is greater, user-space should request more
+	 * stripe_heads first.
+	 */
+	raid5_conf_t *conf = mddev->private;
+	if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
+	    > conf->max_nr_stripes ||
+	    ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
+	    > conf->max_nr_stripes) {
+		printk(KERN_WARNING "raid5: reshape: not enough stripes.  Needed %lu\n",
+		       ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
+			/ STRIPE_SIZE)*4);
+		return 0;
+	}
+	return 1;
+}
+
+static int check_reshape(mddev_t *mddev)
+{
+	raid5_conf_t *conf = mddev->private;
 
 	if (mddev->delta_disks == 0 &&
 	    mddev->new_layout == mddev->layout &&
-	    mddev->new_chunk == mddev->chunk_size)
-		return -EINVAL; /* nothing to do */
+	    mddev->new_chunk_sectors == mddev->chunk_sectors)
+		return 0; /* nothing to do */
 	if (mddev->bitmap)
 		/* Cannot grow a bitmap yet */
 		return -EBUSY;
@@ -4869,28 +4899,15 @@
 			return -EINVAL;
 	}
 
-	/* Can only proceed if there are plenty of stripe_heads.
-	 * We need a minimum of one full stripe,, and for sensible progress
-	 * it is best to have about 4 times that.
-	 * If we require 4 times, then the default 256 4K stripe_heads will
-	 * allow for chunk sizes up to 256K, which is probably OK.
-	 * If the chunk size is greater, user-space should request more
-	 * stripe_heads first.
-	 */
-	if ((mddev->chunk_size / STRIPE_SIZE) * 4 > conf->max_nr_stripes ||
-	    (mddev->new_chunk / STRIPE_SIZE) * 4 > conf->max_nr_stripes) {
-		printk(KERN_WARNING "raid5: reshape: not enough stripes.  Needed %lu\n",
-		       (max(mddev->chunk_size, mddev->new_chunk)
-			/ STRIPE_SIZE)*4);
+	if (!check_stripe_cache(mddev))
 		return -ENOSPC;
-	}
 
 	return resize_stripes(conf, conf->raid_disks + mddev->delta_disks);
 }
 
 static int raid5_start_reshape(mddev_t *mddev)
 {
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 	mdk_rdev_t *rdev;
 	int spares = 0;
 	int added_devices = 0;
@@ -4899,6 +4916,9 @@
 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
 		return -EBUSY;
 
+	if (!check_stripe_cache(mddev))
+		return -ENOSPC;
+
 	list_for_each_entry(rdev, &mddev->disks, same_set)
 		if (rdev->raid_disk < 0 &&
 		    !test_bit(Faulty, &rdev->flags))
@@ -4925,8 +4945,8 @@
 	spin_lock_irq(&conf->device_lock);
 	conf->previous_raid_disks = conf->raid_disks;
 	conf->raid_disks += mddev->delta_disks;
-	conf->prev_chunk = conf->chunk_size;
-	conf->chunk_size = mddev->new_chunk;
+	conf->prev_chunk_sectors = conf->chunk_sectors;
+	conf->chunk_sectors = mddev->new_chunk_sectors;
 	conf->prev_algo = conf->algorithm;
 	conf->algorithm = mddev->new_layout;
 	if (mddev->delta_disks < 0)
@@ -5008,7 +5028,7 @@
 		 */
 		{
 			int data_disks = conf->raid_disks - conf->max_degraded;
-			int stripe = data_disks * (conf->chunk_size
+			int stripe = data_disks * ((conf->chunk_sectors << 9)
 						   / PAGE_SIZE);
 			if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
 				conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
@@ -5022,7 +5042,7 @@
 static void raid5_finish_reshape(mddev_t *mddev)
 {
 	struct block_device *bdev;
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 
 	if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
 
@@ -5053,7 +5073,7 @@
 				raid5_remove_disk(mddev, d);
 		}
 		mddev->layout = conf->algorithm;
-		mddev->chunk_size = conf->chunk_size;
+		mddev->chunk_sectors = conf->chunk_sectors;
 		mddev->reshape_position = MaxSector;
 		mddev->delta_disks = 0;
 	}
@@ -5061,7 +5081,7 @@
 
 static void raid5_quiesce(mddev_t *mddev, int state)
 {
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
 
 	switch(state) {
 	case 2: /* resume for a suspend */
@@ -5111,7 +5131,7 @@
 
 	mddev->new_level = 5;
 	mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
-	mddev->new_chunk = chunksect << 9;
+	mddev->new_chunk_sectors = chunksect;
 
 	return setup_conf(mddev);
 }
@@ -5150,24 +5170,24 @@
 }
 
 
-static int raid5_reconfig(mddev_t *mddev, int new_layout, int new_chunk)
+static int raid5_check_reshape(mddev_t *mddev)
 {
 	/* For a 2-drive array, the layout and chunk size can be changed
 	 * immediately as not restriping is needed.
 	 * For larger arrays we record the new value - after validation
 	 * to be used by a reshape pass.
 	 */
-	raid5_conf_t *conf = mddev_to_conf(mddev);
+	raid5_conf_t *conf = mddev->private;
+	int new_chunk = mddev->new_chunk_sectors;
 
-	if (new_layout >= 0 && !algorithm_valid_raid5(new_layout))
+	if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
 		return -EINVAL;
 	if (new_chunk > 0) {
-		if (new_chunk & (new_chunk-1))
-			/* not a power of 2 */
+		if (!is_power_of_2(new_chunk))
 			return -EINVAL;
-		if (new_chunk < PAGE_SIZE)
+		if (new_chunk < (PAGE_SIZE>>9))
 			return -EINVAL;
-		if (mddev->array_sectors & ((new_chunk>>9)-1))
+		if (mddev->array_sectors & (new_chunk-1))
 			/* not factor of array size */
 			return -EINVAL;
 	}
@@ -5175,49 +5195,39 @@
 	/* They look valid */
 
 	if (mddev->raid_disks == 2) {
-
-		if (new_layout >= 0) {
-			conf->algorithm = new_layout;
-			mddev->layout = mddev->new_layout = new_layout;
+		/* can make the change immediately */
+		if (mddev->new_layout >= 0) {
+			conf->algorithm = mddev->new_layout;
+			mddev->layout = mddev->new_layout;
 		}
 		if (new_chunk > 0) {
-			conf->chunk_size = new_chunk;
-			mddev->chunk_size = mddev->new_chunk = new_chunk;
+			conf->chunk_sectors = new_chunk ;
+			mddev->chunk_sectors = new_chunk;
 		}
 		set_bit(MD_CHANGE_DEVS, &mddev->flags);
 		md_wakeup_thread(mddev->thread);
-	} else {
-		if (new_layout >= 0)
-			mddev->new_layout = new_layout;
-		if (new_chunk > 0)
-			mddev->new_chunk = new_chunk;
 	}
-	return 0;
+	return check_reshape(mddev);
 }
 
-static int raid6_reconfig(mddev_t *mddev, int new_layout, int new_chunk)
+static int raid6_check_reshape(mddev_t *mddev)
 {
-	if (new_layout >= 0 && !algorithm_valid_raid6(new_layout))
+	int new_chunk = mddev->new_chunk_sectors;
+
+	if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
 		return -EINVAL;
 	if (new_chunk > 0) {
-		if (new_chunk & (new_chunk-1))
-			/* not a power of 2 */
+		if (!is_power_of_2(new_chunk))
 			return -EINVAL;
-		if (new_chunk < PAGE_SIZE)
+		if (new_chunk < (PAGE_SIZE >> 9))
 			return -EINVAL;
-		if (mddev->array_sectors & ((new_chunk>>9)-1))
+		if (mddev->array_sectors & (new_chunk-1))
 			/* not factor of array size */
 			return -EINVAL;
 	}
 
 	/* They look valid */
-
-	if (new_layout >= 0)
-		mddev->new_layout = new_layout;
-	if (new_chunk > 0)
-		mddev->new_chunk = new_chunk;
-
-	return 0;
+	return check_reshape(mddev);
 }
 
 static void *raid5_takeover(mddev_t *mddev)
@@ -5227,8 +5237,6 @@
 	 *  raid1 - if there are two drives.  We need to know the chunk size
 	 *  raid4 - trivial - just use a raid4 layout.
 	 *  raid6 - Providing it is a *_6 layout
-	 *
-	 * For now, just do raid1
 	 */
 
 	if (mddev->level == 1)
@@ -5310,12 +5318,11 @@
 	.sync_request	= sync_request,
 	.resize		= raid5_resize,
 	.size		= raid5_size,
-	.check_reshape	= raid5_check_reshape,
+	.check_reshape	= raid6_check_reshape,
 	.start_reshape  = raid5_start_reshape,
 	.finish_reshape = raid5_finish_reshape,
 	.quiesce	= raid5_quiesce,
 	.takeover	= raid6_takeover,
-	.reconfig	= raid6_reconfig,
 };
 static struct mdk_personality raid5_personality =
 {
@@ -5338,7 +5345,6 @@
 	.finish_reshape = raid5_finish_reshape,
 	.quiesce	= raid5_quiesce,
 	.takeover	= raid5_takeover,
-	.reconfig	= raid5_reconfig,
 };
 
 static struct mdk_personality raid4_personality =
diff --git a/drivers/md/raid5.h b/drivers/md/raid5.h
index 52ba999..9459689 100644
--- a/drivers/md/raid5.h
+++ b/drivers/md/raid5.h
@@ -334,7 +334,8 @@
 	struct hlist_head	*stripe_hashtbl;
 	mddev_t			*mddev;
 	struct disk_info	*spare;
-	int			chunk_size, level, algorithm;
+	int			chunk_sectors;
+	int			level, algorithm;
 	int			max_degraded;
 	int			raid_disks;
 	int			max_nr_stripes;
@@ -350,7 +351,8 @@
 	 */
 	sector_t		reshape_safe;
 	int			previous_raid_disks;
-	int			prev_chunk, prev_algo;
+	int			prev_chunk_sectors;
+	int			prev_algo;
 	short			generation; /* increments with every reshape */
 	unsigned long		reshape_checkpoint; /* Time we last updated
 						     * metadata */
@@ -408,8 +410,6 @@
 
 typedef struct raid5_private_data raid5_conf_t;
 
-#define mddev_to_conf(mddev) ((raid5_conf_t *) mddev->private)
-
 /*
  * Our supported algorithms
  */
diff --git a/drivers/media/video/ov772x.c b/drivers/media/video/ov772x.c
index c0d9112..0bce255 100644
--- a/drivers/media/video/ov772x.c
+++ b/drivers/media/video/ov772x.c
@@ -1067,10 +1067,12 @@
 	struct i2c_adapter        *adapter = to_i2c_adapter(client->dev.parent);
 	int                        ret;
 
-	info = client->dev.platform_data;
-	if (!info)
+	if (!client->dev.platform_data)
 		return -EINVAL;
 
+	info = container_of(client->dev.platform_data,
+			    struct ov772x_camera_info, link);
+
 	if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
 		dev_err(&adapter->dev,
 			"I2C-Adapter doesn't support "
diff --git a/drivers/media/video/tw9910.c b/drivers/media/video/tw9910.c
index a399476..aa5065e 100644
--- a/drivers/media/video/tw9910.c
+++ b/drivers/media/video/tw9910.c
@@ -875,10 +875,12 @@
 	const struct tw9910_scale_ctrl *scale;
 	int                             i, ret;
 
-	info = client->dev.platform_data;
-	if (!info)
+	if (!client->dev.platform_data)
 		return -EINVAL;
 
+	info = container_of(client->dev.platform_data,
+			    struct tw9910_video_info, link);
+
 	if (!i2c_check_functionality(to_i2c_adapter(client->dev.parent),
 				     I2C_FUNC_SMBUS_BYTE_DATA)) {
 		dev_err(&client->dev,
diff --git a/drivers/message/fusion/mptbase.c b/drivers/message/fusion/mptbase.c
index 0df0652..5d0ba4f 100644
--- a/drivers/message/fusion/mptbase.c
+++ b/drivers/message/fusion/mptbase.c
@@ -4414,11 +4414,11 @@
 		 * 1078 errata workaround for the 36GB limitation
 		 */
 		if (ioc->pcidev->device == MPI_MANUFACTPAGE_DEVID_SAS1078 &&
-		    ioc->dma_mask > DMA_35BIT_MASK) {
+		    ioc->dma_mask > DMA_BIT_MASK(35)) {
 			if (!pci_set_dma_mask(ioc->pcidev, DMA_BIT_MASK(32))
 			    && !pci_set_consistent_dma_mask(ioc->pcidev,
 			    DMA_BIT_MASK(32))) {
-				dma_mask = DMA_35BIT_MASK;
+				dma_mask = DMA_BIT_MASK(35);
 				d36memprintk(ioc, printk(MYIOC_s_DEBUG_FMT
 				    "setting 35 bit addressing for "
 				    "Request/Reply/Chain and Sense Buffers\n",
@@ -4575,7 +4575,7 @@
 		alloc_dma += ioc->reply_sz;
 	}
 
-	if (dma_mask == DMA_35BIT_MASK && !pci_set_dma_mask(ioc->pcidev,
+	if (dma_mask == DMA_BIT_MASK(35) && !pci_set_dma_mask(ioc->pcidev,
 	    ioc->dma_mask) && !pci_set_consistent_dma_mask(ioc->pcidev,
 	    ioc->dma_mask))
 		d36memprintk(ioc, printk(MYIOC_s_DEBUG_FMT
@@ -4602,7 +4602,7 @@
 		ioc->sense_buf_pool = NULL;
 	}
 
-	if (dma_mask == DMA_35BIT_MASK && !pci_set_dma_mask(ioc->pcidev,
+	if (dma_mask == DMA_BIT_MASK(35) && !pci_set_dma_mask(ioc->pcidev,
 	    DMA_BIT_MASK(64)) && !pci_set_consistent_dma_mask(ioc->pcidev,
 	    DMA_BIT_MASK(64)))
 		d36memprintk(ioc, printk(MYIOC_s_DEBUG_FMT
diff --git a/drivers/mfd/Kconfig b/drivers/mfd/Kconfig
index ee3927a..491ac0f 100644
--- a/drivers/mfd/Kconfig
+++ b/drivers/mfd/Kconfig
@@ -30,6 +30,7 @@
 config MFD_ASIC3
 	bool "Support for Compaq ASIC3"
 	depends on GENERIC_HARDIRQS && GPIOLIB && ARM
+	select MFD_CORE
 	 ---help---
 	  This driver supports the ASIC3 multifunction chip found on many
 	  PDAs (mainly iPAQ and HTC based ones)
@@ -152,7 +153,7 @@
 	depends on I2C
 	help
 	  Support for the Wolfson Microelecronics WM8400 PMIC and audio
-	  CODEC.  This driver adds provides common support for accessing
+	  CODEC.  This driver provides common support for accessing
 	  the device, additional drivers must be enabled in order to use
 	  the functionality of the device.
 
@@ -241,6 +242,27 @@
 	 Say yes here if you want to include support GPIO for pins on
 	 the PCF50633 chip.
 
+config AB3100_CORE
+	tristate "ST-Ericsson AB3100 Mixed Signal Circuit core functions"
+	depends on I2C
+	default y if ARCH_U300
+	help
+	  Select this to enable the AB3100 Mixed Signal IC core
+	  functionality. This connects to a AB3100 on the I2C bus
+	  and expose a number of symbols needed for dependent devices
+	  to read and write registers and subscribe to events from
+	  this multi-functional IC. This is needed to use other features
+	  of the AB3100 such as battery-backed RTC, charging control,
+	  LEDs, vibrator, system power and temperature, power management
+	  and ALSA sound.
+
+config EZX_PCAP
+	bool "PCAP Support"
+	depends on GENERIC_HARDIRQS && SPI_MASTER
+	help
+	  This enables the PCAP ASIC present on EZX Phones. This is
+	  needed for MMC, TouchScreen, Sound, USB, etc..
+
 endmenu
 
 menu "Multimedia Capabilities Port drivers"
diff --git a/drivers/mfd/Makefile b/drivers/mfd/Makefile
index 3afb519..6f8a9a1af 100644
--- a/drivers/mfd/Makefile
+++ b/drivers/mfd/Makefile
@@ -26,6 +26,8 @@
 
 obj-$(CONFIG_MFD_CORE)		+= mfd-core.o
 
+obj-$(CONFIG_EZX_PCAP)		+= ezx-pcap.o
+
 obj-$(CONFIG_MCP)		+= mcp-core.o
 obj-$(CONFIG_MCP_SA11X0)	+= mcp-sa11x0.o
 obj-$(CONFIG_MCP_UCB1200)	+= ucb1x00-core.o
@@ -40,4 +42,5 @@
 
 obj-$(CONFIG_MFD_PCF50633)	+= pcf50633-core.o
 obj-$(CONFIG_PCF50633_ADC)	+= pcf50633-adc.o
-obj-$(CONFIG_PCF50633_GPIO)	+= pcf50633-gpio.o
\ No newline at end of file
+obj-$(CONFIG_PCF50633_GPIO)	+= pcf50633-gpio.o
+obj-$(CONFIG_AB3100_CORE)	+= ab3100-core.o
diff --git a/drivers/mfd/ab3100-core.c b/drivers/mfd/ab3100-core.c
new file mode 100644
index 0000000..13e7d7b
--- /dev/null
+++ b/drivers/mfd/ab3100-core.c
@@ -0,0 +1,991 @@
+/*
+ * Copyright (C) 2007-2009 ST-Ericsson
+ * License terms: GNU General Public License (GPL) version 2
+ * Low-level core for exclusive access to the AB3100 IC on the I2C bus
+ * and some basic chip-configuration.
+ * Author: Linus Walleij <linus.walleij@stericsson.com>
+ */
+
+#include <linux/i2c.h>
+#include <linux/mutex.h>
+#include <linux/list.h>
+#include <linux/notifier.h>
+#include <linux/err.h>
+#include <linux/platform_device.h>
+#include <linux/device.h>
+#include <linux/interrupt.h>
+#include <linux/workqueue.h>
+#include <linux/debugfs.h>
+#include <linux/seq_file.h>
+#include <linux/uaccess.h>
+#include <linux/mfd/ab3100.h>
+
+/* These are the only registers inside AB3100 used in this main file */
+
+/* Interrupt event registers */
+#define AB3100_EVENTA1		0x21
+#define AB3100_EVENTA2		0x22
+#define AB3100_EVENTA3		0x23
+
+/* AB3100 DAC converter registers */
+#define AB3100_DIS		0x00
+#define AB3100_D0C		0x01
+#define AB3100_D1C		0x02
+#define AB3100_D2C		0x03
+#define AB3100_D3C		0x04
+
+/* Chip ID register */
+#define AB3100_CID		0x20
+
+/* AB3100 interrupt registers */
+#define AB3100_IMRA1		0x24
+#define AB3100_IMRA2		0x25
+#define AB3100_IMRA3		0x26
+#define AB3100_IMRB1		0x2B
+#define AB3100_IMRB2		0x2C
+#define AB3100_IMRB3		0x2D
+
+/* System Power Monitoring and control registers */
+#define AB3100_MCA		0x2E
+#define AB3100_MCB		0x2F
+
+/* SIM power up */
+#define AB3100_SUP		0x50
+
+/*
+ * I2C communication
+ *
+ * The AB3100 is usually assigned address 0x48 (7-bit)
+ * The chip is defined in the platform i2c_board_data section.
+ */
+static unsigned short normal_i2c[] = { 0x48, I2C_CLIENT_END };
+I2C_CLIENT_INSMOD_1(ab3100);
+
+u8 ab3100_get_chip_type(struct ab3100 *ab3100)
+{
+	u8 chip = ABUNKNOWN;
+
+	switch (ab3100->chip_id & 0xf0) {
+	case  0xa0:
+		chip = AB3000;
+		break;
+	case  0xc0:
+		chip = AB3100;
+		break;
+	}
+	return chip;
+}
+EXPORT_SYMBOL(ab3100_get_chip_type);
+
+int ab3100_set_register(struct ab3100 *ab3100, u8 reg, u8 regval)
+{
+	u8 regandval[2] = {reg, regval};
+	int err;
+
+	err = mutex_lock_interruptible(&ab3100->access_mutex);
+	if (err)
+		return err;
+
+	/*
+	 * A two-byte write message with the first byte containing the register
+	 * number and the second byte containing the value to be written
+	 * effectively sets a register in the AB3100.
+	 */
+	err = i2c_master_send(ab3100->i2c_client, regandval, 2);
+	if (err < 0) {
+		dev_err(ab3100->dev,
+			"write error (write register): %d\n",
+			err);
+	} else if (err != 2) {
+		dev_err(ab3100->dev,
+			"write error (write register) "
+			"%d bytes transferred (expected 2)\n",
+			err);
+		err = -EIO;
+	} else {
+		/* All is well */
+		err = 0;
+	}
+	mutex_unlock(&ab3100->access_mutex);
+	return 0;
+}
+EXPORT_SYMBOL(ab3100_set_register);
+
+/*
+ * The test registers exist at an I2C bus address up one
+ * from the ordinary base. They are not supposed to be used
+ * in production code, but sometimes you have to do that
+ * anyway. It's currently only used from this file so declare
+ * it static and do not export.
+ */
+static int ab3100_set_test_register(struct ab3100 *ab3100,
+				    u8 reg, u8 regval)
+{
+	u8 regandval[2] = {reg, regval};
+	int err;
+
+	err = mutex_lock_interruptible(&ab3100->access_mutex);
+	if (err)
+		return err;
+
+	err = i2c_master_send(ab3100->testreg_client, regandval, 2);
+	if (err < 0) {
+		dev_err(ab3100->dev,
+			"write error (write test register): %d\n",
+			err);
+	} else if (err != 2) {
+		dev_err(ab3100->dev,
+			"write error (write test register) "
+			"%d bytes transferred (expected 2)\n",
+			err);
+		err = -EIO;
+	} else {
+		/* All is well */
+		err = 0;
+	}
+	mutex_unlock(&ab3100->access_mutex);
+
+	return err;
+}
+
+int ab3100_get_register(struct ab3100 *ab3100, u8 reg, u8 *regval)
+{
+	int err;
+
+	err = mutex_lock_interruptible(&ab3100->access_mutex);
+	if (err)
+		return err;
+
+	/*
+	 * AB3100 require an I2C "stop" command between each message, else
+	 * it will not work. The only way of achieveing this with the
+	 * message transport layer is to send the read and write messages
+	 * separately.
+	 */
+	err = i2c_master_send(ab3100->i2c_client, &reg, 1);
+	if (err < 0) {
+		dev_err(ab3100->dev,
+			"write error (send register address): %d\n",
+			err);
+		goto get_reg_out_unlock;
+	} else if (err != 1) {
+		dev_err(ab3100->dev,
+			"write error (send register address) "
+			"%d bytes transferred (expected 1)\n",
+			err);
+		err = -EIO;
+		goto get_reg_out_unlock;
+	} else {
+		/* All is well */
+		err = 0;
+	}
+
+	err = i2c_master_recv(ab3100->i2c_client, regval, 1);
+	if (err < 0) {
+		dev_err(ab3100->dev,
+			"write error (read register): %d\n",
+			err);
+		goto get_reg_out_unlock;
+	} else if (err != 1) {
+		dev_err(ab3100->dev,
+			"write error (read register) "
+			"%d bytes transferred (expected 1)\n",
+			err);
+		err = -EIO;
+		goto get_reg_out_unlock;
+	} else {
+		/* All is well */
+		err = 0;
+	}
+
+ get_reg_out_unlock:
+	mutex_unlock(&ab3100->access_mutex);
+	return err;
+}
+EXPORT_SYMBOL(ab3100_get_register);
+
+int ab3100_get_register_page(struct ab3100 *ab3100,
+			     u8 first_reg, u8 *regvals, u8 numregs)
+{
+	int err;
+
+	if (ab3100->chip_id == 0xa0 ||
+	    ab3100->chip_id == 0xa1)
+		/* These don't support paged reads */
+		return -EIO;
+
+	err = mutex_lock_interruptible(&ab3100->access_mutex);
+	if (err)
+		return err;
+
+	/*
+	 * Paged read also require an I2C "stop" command.
+	 */
+	err = i2c_master_send(ab3100->i2c_client, &first_reg, 1);
+	if (err < 0) {
+		dev_err(ab3100->dev,
+			"write error (send first register address): %d\n",
+			err);
+		goto get_reg_page_out_unlock;
+	} else if (err != 1) {
+		dev_err(ab3100->dev,
+			"write error (send first register address) "
+			"%d bytes transferred (expected 1)\n",
+			err);
+		err = -EIO;
+		goto get_reg_page_out_unlock;
+	}
+
+	err = i2c_master_recv(ab3100->i2c_client, regvals, numregs);
+	if (err < 0) {
+		dev_err(ab3100->dev,
+			"write error (read register page): %d\n",
+			err);
+		goto get_reg_page_out_unlock;
+	} else if (err != numregs) {
+		dev_err(ab3100->dev,
+			"write error (read register page) "
+			"%d bytes transferred (expected %d)\n",
+			err, numregs);
+		err = -EIO;
+		goto get_reg_page_out_unlock;
+	}
+
+	/* All is well */
+	err = 0;
+
+ get_reg_page_out_unlock:
+	mutex_unlock(&ab3100->access_mutex);
+	return err;
+}
+EXPORT_SYMBOL(ab3100_get_register_page);
+
+int ab3100_mask_and_set_register(struct ab3100 *ab3100,
+				 u8 reg, u8 andmask, u8 ormask)
+{
+	u8 regandval[2] = {reg, 0};
+	int err;
+
+	err = mutex_lock_interruptible(&ab3100->access_mutex);
+	if (err)
+		return err;
+
+	/* First read out the target register */
+	err = i2c_master_send(ab3100->i2c_client, &reg, 1);
+	if (err < 0) {
+		dev_err(ab3100->dev,
+			"write error (maskset send address): %d\n",
+			err);
+		goto get_maskset_unlock;
+	} else if (err != 1) {
+		dev_err(ab3100->dev,
+			"write error (maskset send address) "
+			"%d bytes transferred (expected 1)\n",
+			err);
+		err = -EIO;
+		goto get_maskset_unlock;
+	}
+
+	err = i2c_master_recv(ab3100->i2c_client, &regandval[1], 1);
+	if (err < 0) {
+		dev_err(ab3100->dev,
+			"write error (maskset read register): %d\n",
+			err);
+		goto get_maskset_unlock;
+	} else if (err != 1) {
+		dev_err(ab3100->dev,
+			"write error (maskset read register) "
+			"%d bytes transferred (expected 1)\n",
+			err);
+		err = -EIO;
+		goto get_maskset_unlock;
+	}
+
+	/* Modify the register */
+	regandval[1] &= andmask;
+	regandval[1] |= ormask;
+
+	/* Write the register */
+	err = i2c_master_send(ab3100->i2c_client, regandval, 2);
+	if (err < 0) {
+		dev_err(ab3100->dev,
+			"write error (write register): %d\n",
+			err);
+		goto get_maskset_unlock;
+	} else if (err != 2) {
+		dev_err(ab3100->dev,
+			"write error (write register) "
+			"%d bytes transferred (expected 2)\n",
+			err);
+		err = -EIO;
+		goto get_maskset_unlock;
+	}
+
+	/* All is well */
+	err = 0;
+
+ get_maskset_unlock:
+	mutex_unlock(&ab3100->access_mutex);
+	return err;
+}
+EXPORT_SYMBOL(ab3100_mask_and_set_register);
+
+/*
+ * Register a simple callback for handling any AB3100 events.
+ */
+int ab3100_event_register(struct ab3100 *ab3100,
+			  struct notifier_block *nb)
+{
+	return blocking_notifier_chain_register(&ab3100->event_subscribers,
+					       nb);
+}
+EXPORT_SYMBOL(ab3100_event_register);
+
+/*
+ * Remove a previously registered callback.
+ */
+int ab3100_event_unregister(struct ab3100 *ab3100,
+			    struct notifier_block *nb)
+{
+  return blocking_notifier_chain_unregister(&ab3100->event_subscribers,
+					    nb);
+}
+EXPORT_SYMBOL(ab3100_event_unregister);
+
+
+int ab3100_event_registers_startup_state_get(struct ab3100 *ab3100,
+					     u32 *fatevent)
+{
+	if (!ab3100->startup_events_read)
+		return -EAGAIN; /* Try again later */
+	*fatevent = ab3100->startup_events;
+	return 0;
+}
+EXPORT_SYMBOL(ab3100_event_registers_startup_state_get);
+
+/* Interrupt handling worker */
+static void ab3100_work(struct work_struct *work)
+{
+	struct ab3100 *ab3100 = container_of(work, struct ab3100, work);
+	u8 event_regs[3];
+	u32 fatevent;
+	int err;
+
+	err = ab3100_get_register_page(ab3100, AB3100_EVENTA1,
+				       event_regs, 3);
+	if (err)
+		goto err_event_wq;
+
+	fatevent = (event_regs[0] << 16) |
+		(event_regs[1] << 8) |
+		event_regs[2];
+
+	if (!ab3100->startup_events_read) {
+		ab3100->startup_events = fatevent;
+		ab3100->startup_events_read = true;
+	}
+	/*
+	 * The notified parties will have to mask out the events
+	 * they're interested in and react to them. They will be
+	 * notified on all events, then they use the fatevent value
+	 * to determine if they're interested.
+	 */
+	blocking_notifier_call_chain(&ab3100->event_subscribers,
+				     fatevent, NULL);
+
+	dev_dbg(ab3100->dev,
+		"IRQ Event: 0x%08x\n", fatevent);
+
+	/* By now the IRQ should be acked and deasserted so enable it again */
+	enable_irq(ab3100->i2c_client->irq);
+	return;
+
+ err_event_wq:
+	dev_dbg(ab3100->dev,
+		"error in event workqueue\n");
+	/* Enable the IRQ anyway, what choice do we have? */
+	enable_irq(ab3100->i2c_client->irq);
+	return;
+}
+
+static irqreturn_t ab3100_irq_handler(int irq, void *data)
+{
+	struct ab3100 *ab3100 = data;
+	/*
+	 * Disable the IRQ and dispatch a worker to handle the
+	 * event. Since the chip resides on I2C this is slow
+	 * stuff and we will re-enable the interrupts once th
+	 * worker has finished.
+	 */
+	disable_irq(ab3100->i2c_client->irq);
+	schedule_work(&ab3100->work);
+	return IRQ_HANDLED;
+}
+
+#ifdef CONFIG_DEBUG_FS
+/*
+ * Some debugfs entries only exposed if we're using debug
+ */
+static int ab3100_registers_print(struct seq_file *s, void *p)
+{
+	struct ab3100 *ab3100 = s->private;
+	u8 value;
+	u8 reg;
+
+	seq_printf(s, "AB3100 registers:\n");
+
+	for (reg = 0; reg < 0xff; reg++) {
+		ab3100_get_register(ab3100, reg, &value);
+		seq_printf(s, "[0x%x]:  0x%x\n", reg, value);
+	}
+	return 0;
+}
+
+static int ab3100_registers_open(struct inode *inode, struct file *file)
+{
+	return single_open(file, ab3100_registers_print, inode->i_private);
+}
+
+static const struct file_operations ab3100_registers_fops = {
+	.open = ab3100_registers_open,
+	.read = seq_read,
+	.llseek = seq_lseek,
+	.release = single_release,
+	.owner = THIS_MODULE,
+};
+
+struct ab3100_get_set_reg_priv {
+	struct ab3100 *ab3100;
+	bool mode;
+};
+
+static int ab3100_get_set_reg_open_file(struct inode *inode, struct file *file)
+{
+	file->private_data = inode->i_private;
+	return 0;
+}
+
+static int ab3100_get_set_reg(struct file *file,
+			      const char __user *user_buf,
+			      size_t count, loff_t *ppos)
+{
+	struct ab3100_get_set_reg_priv *priv = file->private_data;
+	struct ab3100 *ab3100 = priv->ab3100;
+	char buf[32];
+	int buf_size;
+	int regp;
+	unsigned long user_reg;
+	int err;
+	int i = 0;
+
+	/* Get userspace string and assure termination */
+	buf_size = min(count, (sizeof(buf)-1));
+	if (copy_from_user(buf, user_buf, buf_size))
+		return -EFAULT;
+	buf[buf_size] = 0;
+
+	/*
+	 * The idea is here to parse a string which is either
+	 * "0xnn" for reading a register, or "0xaa 0xbb" for
+	 * writing 0xbb to the register 0xaa. First move past
+	 * whitespace and then begin to parse the register.
+	 */
+	while ((i < buf_size) && (buf[i] == ' '))
+		i++;
+	regp = i;
+
+	/*
+	 * Advance pointer to end of string then terminate
+	 * the register string. This is needed to satisfy
+	 * the strict_strtoul() function.
+	 */
+	while ((i < buf_size) && (buf[i] != ' '))
+		i++;
+	buf[i] = '\0';
+
+	err = strict_strtoul(&buf[regp], 16, &user_reg);
+	if (err)
+		return err;
+	if (user_reg > 0xff)
+		return -EINVAL;
+
+	/* Either we read or we write a register here */
+	if (!priv->mode) {
+		/* Reading */
+		u8 reg = (u8) user_reg;
+		u8 regvalue;
+
+		ab3100_get_register(ab3100, reg, &regvalue);
+
+		dev_info(ab3100->dev,
+			 "debug read AB3100 reg[0x%02x]: 0x%02x\n",
+			 reg, regvalue);
+	} else {
+		int valp;
+		unsigned long user_value;
+		u8 reg = (u8) user_reg;
+		u8 value;
+		u8 regvalue;
+
+		/*
+		 * Writing, we need some value to write to
+		 * the register so keep parsing the string
+		 * from userspace.
+		 */
+		i++;
+		while ((i < buf_size) && (buf[i] == ' '))
+			i++;
+		valp = i;
+		while ((i < buf_size) && (buf[i] != ' '))
+			i++;
+		buf[i] = '\0';
+
+		err = strict_strtoul(&buf[valp], 16, &user_value);
+		if (err)
+			return err;
+		if (user_reg > 0xff)
+			return -EINVAL;
+
+		value = (u8) user_value;
+		ab3100_set_register(ab3100, reg, value);
+		ab3100_get_register(ab3100, reg, &regvalue);
+
+		dev_info(ab3100->dev,
+			 "debug write reg[0x%02x] with 0x%02x, "
+			 "after readback: 0x%02x\n",
+			 reg, value, regvalue);
+	}
+	return buf_size;
+}
+
+static const struct file_operations ab3100_get_set_reg_fops = {
+	.open = ab3100_get_set_reg_open_file,
+	.write = ab3100_get_set_reg,
+};
+
+static struct dentry *ab3100_dir;
+static struct dentry *ab3100_reg_file;
+static struct ab3100_get_set_reg_priv ab3100_get_priv;
+static struct dentry *ab3100_get_reg_file;
+static struct ab3100_get_set_reg_priv ab3100_set_priv;
+static struct dentry *ab3100_set_reg_file;
+
+static void ab3100_setup_debugfs(struct ab3100 *ab3100)
+{
+	int err;
+
+	ab3100_dir = debugfs_create_dir("ab3100", NULL);
+	if (!ab3100_dir)
+		goto exit_no_debugfs;
+
+	ab3100_reg_file = debugfs_create_file("registers",
+				S_IRUGO, ab3100_dir, ab3100,
+				&ab3100_registers_fops);
+	if (!ab3100_reg_file) {
+		err = -ENOMEM;
+		goto exit_destroy_dir;
+	}
+
+	ab3100_get_priv.ab3100 = ab3100;
+	ab3100_get_priv.mode = false;
+	ab3100_get_reg_file = debugfs_create_file("get_reg",
+				S_IWUGO, ab3100_dir, &ab3100_get_priv,
+				&ab3100_get_set_reg_fops);
+	if (!ab3100_get_reg_file) {
+		err = -ENOMEM;
+		goto exit_destroy_reg;
+	}
+
+	ab3100_set_priv.ab3100 = ab3100;
+	ab3100_set_priv.mode = true;
+	ab3100_set_reg_file = debugfs_create_file("set_reg",
+				S_IWUGO, ab3100_dir, &ab3100_set_priv,
+				&ab3100_get_set_reg_fops);
+	if (!ab3100_set_reg_file) {
+		err = -ENOMEM;
+		goto exit_destroy_get_reg;
+	}
+	return;
+
+ exit_destroy_get_reg:
+	debugfs_remove(ab3100_get_reg_file);
+ exit_destroy_reg:
+	debugfs_remove(ab3100_reg_file);
+ exit_destroy_dir:
+	debugfs_remove(ab3100_dir);
+ exit_no_debugfs:
+	return;
+}
+static inline void ab3100_remove_debugfs(void)
+{
+	debugfs_remove(ab3100_set_reg_file);
+	debugfs_remove(ab3100_get_reg_file);
+	debugfs_remove(ab3100_reg_file);
+	debugfs_remove(ab3100_dir);
+}
+#else
+static inline void ab3100_setup_debugfs(struct ab3100 *ab3100)
+{
+}
+static inline void ab3100_remove_debugfs(void)
+{
+}
+#endif
+
+/*
+ * Basic set-up, datastructure creation/destruction and I2C interface.
+ * This sets up a default config in the AB3100 chip so that it
+ * will work as expected.
+ */
+
+struct ab3100_init_setting {
+	u8 abreg;
+	u8 setting;
+};
+
+static const struct ab3100_init_setting __initdata
+ab3100_init_settings[] = {
+	{
+		.abreg = AB3100_MCA,
+		.setting = 0x01
+	}, {
+		.abreg = AB3100_MCB,
+		.setting = 0x30
+	}, {
+		.abreg = AB3100_IMRA1,
+		.setting = 0x00
+	}, {
+		.abreg = AB3100_IMRA2,
+		.setting = 0xFF
+	}, {
+		.abreg = AB3100_IMRA3,
+		.setting = 0x01
+	}, {
+		.abreg = AB3100_IMRB1,
+		.setting = 0xFF
+	}, {
+		.abreg = AB3100_IMRB2,
+		.setting = 0xFF
+	}, {
+		.abreg = AB3100_IMRB3,
+		.setting = 0xFF
+	}, {
+		.abreg = AB3100_SUP,
+		.setting = 0x00
+	}, {
+		.abreg = AB3100_DIS,
+		.setting = 0xF0
+	}, {
+		.abreg = AB3100_D0C,
+		.setting = 0x00
+	}, {
+		.abreg = AB3100_D1C,
+		.setting = 0x00
+	}, {
+		.abreg = AB3100_D2C,
+		.setting = 0x00
+	}, {
+		.abreg = AB3100_D3C,
+		.setting = 0x00
+	},
+};
+
+static int __init ab3100_setup(struct ab3100 *ab3100)
+{
+	int err = 0;
+	int i;
+
+	for (i = 0; i < ARRAY_SIZE(ab3100_init_settings); i++) {
+		err = ab3100_set_register(ab3100,
+					  ab3100_init_settings[i].abreg,
+					  ab3100_init_settings[i].setting);
+		if (err)
+			goto exit_no_setup;
+	}
+
+	/*
+	 * Special trick to make the AB3100 use the 32kHz clock (RTC)
+	 * bit 3 in test registe 0x02 is a special, undocumented test
+	 * register bit that only exist in AB3100 P1E
+	 */
+	if (ab3100->chip_id == 0xc4) {
+		dev_warn(ab3100->dev,
+			 "AB3100 P1E variant detected, "
+			 "forcing chip to 32KHz\n");
+		err = ab3100_set_test_register(ab3100, 0x02, 0x08);
+	}
+
+ exit_no_setup:
+	return err;
+}
+
+/*
+ * Here we define all the platform devices that appear
+ * as children of the AB3100. These are regular platform
+ * devices with the IORESOURCE_IO .start and .end set
+ * to correspond to the internal AB3100 register range
+ * mapping to the corresponding subdevice.
+ */
+
+#define AB3100_DEVICE(devname, devid)				\
+static struct platform_device ab3100_##devname##_device = {	\
+	.name		= devid,				\
+	.id		= -1,					\
+}
+
+/*
+ * This lists all the subdevices and corresponding register
+ * ranges.
+ */
+AB3100_DEVICE(dac, "ab3100-dac");
+AB3100_DEVICE(leds, "ab3100-leds");
+AB3100_DEVICE(power, "ab3100-power");
+AB3100_DEVICE(regulators, "ab3100-regulators");
+AB3100_DEVICE(sim, "ab3100-sim");
+AB3100_DEVICE(uart, "ab3100-uart");
+AB3100_DEVICE(rtc, "ab3100-rtc");
+AB3100_DEVICE(charger, "ab3100-charger");
+AB3100_DEVICE(boost, "ab3100-boost");
+AB3100_DEVICE(adc, "ab3100-adc");
+AB3100_DEVICE(fuelgauge, "ab3100-fuelgauge");
+AB3100_DEVICE(vibrator, "ab3100-vibrator");
+AB3100_DEVICE(otp, "ab3100-otp");
+AB3100_DEVICE(codec, "ab3100-codec");
+
+static struct platform_device *
+ab3100_platform_devs[] = {
+	&ab3100_dac_device,
+	&ab3100_leds_device,
+	&ab3100_power_device,
+	&ab3100_regulators_device,
+	&ab3100_sim_device,
+	&ab3100_uart_device,
+	&ab3100_rtc_device,
+	&ab3100_charger_device,
+	&ab3100_boost_device,
+	&ab3100_adc_device,
+	&ab3100_fuelgauge_device,
+	&ab3100_vibrator_device,
+	&ab3100_otp_device,
+	&ab3100_codec_device,
+};
+
+struct ab_family_id {
+	u8	id;
+	char	*name;
+};
+
+static const struct ab_family_id ids[] __initdata = {
+	/* AB3100 */
+	{
+		.id = 0xc0,
+		.name = "P1A"
+	}, {
+		.id = 0xc1,
+		.name = "P1B"
+	}, {
+		.id = 0xc2,
+		.name = "P1C"
+	}, {
+		.id = 0xc3,
+		.name = "P1D"
+	}, {
+		.id = 0xc4,
+		.name = "P1E"
+	}, {
+		.id = 0xc5,
+		.name = "P1F/R1A"
+	}, {
+		.id = 0xc6,
+		.name = "P1G/R1A"
+	}, {
+		.id = 0xc7,
+		.name = "P2A/R2A"
+	}, {
+		.id = 0xc8,
+		.name = "P2B/R2B"
+	},
+	/* AB3000 variants, not supported */
+	{
+		.id = 0xa0
+	}, {
+		.id = 0xa1
+	}, {
+		.id = 0xa2
+	}, {
+		.id = 0xa3
+	}, {
+		.id = 0xa4
+	}, {
+		.id = 0xa5
+	}, {
+		.id = 0xa6
+	}, {
+		.id = 0xa7
+	},
+	/* Terminator */
+	{
+		.id = 0x00,
+	},
+};
+
+static int __init ab3100_probe(struct i2c_client *client,
+			const struct i2c_device_id *id)
+{
+	struct ab3100 *ab3100;
+	int err;
+	int i;
+
+	ab3100 = kzalloc(sizeof(struct ab3100), GFP_KERNEL);
+	if (!ab3100) {
+		dev_err(&client->dev, "could not allocate AB3100 device\n");
+		return -ENOMEM;
+	}
+
+	/* Initialize data structure */
+	mutex_init(&ab3100->access_mutex);
+	BLOCKING_INIT_NOTIFIER_HEAD(&ab3100->event_subscribers);
+
+	ab3100->i2c_client = client;
+	ab3100->dev = &ab3100->i2c_client->dev;
+
+	i2c_set_clientdata(client, ab3100);
+
+	/* Read chip ID register */
+	err = ab3100_get_register(ab3100, AB3100_CID,
+				  &ab3100->chip_id);
+	if (err) {
+		dev_err(&client->dev,
+			"could not communicate with the AB3100 analog "
+			"baseband chip\n");
+		goto exit_no_detect;
+	}
+
+	for (i = 0; ids[i].id != 0x0; i++) {
+		if (ids[i].id == ab3100->chip_id) {
+			if (ids[i].name != NULL) {
+				snprintf(&ab3100->chip_name[0],
+					 sizeof(ab3100->chip_name) - 1,
+					 "AB3100 %s",
+					 ids[i].name);
+				break;
+			} else {
+				dev_err(&client->dev,
+					"AB3000 is not supported\n");
+				goto exit_no_detect;
+			}
+		}
+	}
+
+	if (ids[i].id == 0x0) {
+		dev_err(&client->dev, "unknown analog baseband chip id: 0x%x\n",
+			ab3100->chip_id);
+		dev_err(&client->dev, "accepting it anyway. Please update "
+			"the driver.\n");
+		goto exit_no_detect;
+	}
+
+	dev_info(&client->dev, "Detected chip: %s\n",
+		 &ab3100->chip_name[0]);
+
+	/* Attach a second dummy i2c_client to the test register address */
+	ab3100->testreg_client = i2c_new_dummy(client->adapter,
+						     client->addr + 1);
+	if (!ab3100->testreg_client) {
+		err = -ENOMEM;
+		goto exit_no_testreg_client;
+	}
+
+	strlcpy(ab3100->testreg_client->name, id->name,
+		sizeof(ab3100->testreg_client->name));
+
+	err = ab3100_setup(ab3100);
+	if (err)
+		goto exit_no_setup;
+
+	INIT_WORK(&ab3100->work, ab3100_work);
+
+	/* This real unpredictable IRQ is of course sampled for entropy */
+	err = request_irq(client->irq, ab3100_irq_handler,
+			  IRQF_DISABLED | IRQF_SAMPLE_RANDOM,
+			  "AB3100 IRQ", ab3100);
+	if (err)
+		goto exit_no_irq;
+
+	/* Set parent and a pointer back to the container in device data */
+	for (i = 0; i < ARRAY_SIZE(ab3100_platform_devs); i++) {
+		ab3100_platform_devs[i]->dev.parent =
+			&client->dev;
+		platform_set_drvdata(ab3100_platform_devs[i], ab3100);
+	}
+
+	/* Register the platform devices */
+	platform_add_devices(ab3100_platform_devs,
+			     ARRAY_SIZE(ab3100_platform_devs));
+
+	ab3100_setup_debugfs(ab3100);
+
+	return 0;
+
+ exit_no_irq:
+ exit_no_setup:
+	i2c_unregister_device(ab3100->testreg_client);
+ exit_no_testreg_client:
+ exit_no_detect:
+	kfree(ab3100);
+	return err;
+}
+
+static int __exit ab3100_remove(struct i2c_client *client)
+{
+	struct ab3100 *ab3100 = i2c_get_clientdata(client);
+	int i;
+
+	/* Unregister subdevices */
+	for (i = 0; i < ARRAY_SIZE(ab3100_platform_devs); i++)
+		platform_device_unregister(ab3100_platform_devs[i]);
+
+	ab3100_remove_debugfs();
+	i2c_unregister_device(ab3100->testreg_client);
+
+	/*
+	 * At this point, all subscribers should have unregistered
+	 * their notifiers so deactivate IRQ
+	 */
+	free_irq(client->irq, ab3100);
+	kfree(ab3100);
+	return 0;
+}
+
+static const struct i2c_device_id ab3100_id[] = {
+	{ "ab3100", ab3100 },
+	{ }
+};
+MODULE_DEVICE_TABLE(i2c, ab3100_id);
+
+static struct i2c_driver ab3100_driver = {
+	.driver = {
+		.name	= "ab3100",
+		.owner	= THIS_MODULE,
+	},
+	.id_table	= ab3100_id,
+	.probe		= ab3100_probe,
+	.remove		= __exit_p(ab3100_remove),
+};
+
+static int __init ab3100_i2c_init(void)
+{
+	return i2c_add_driver(&ab3100_driver);
+}
+
+static void __exit ab3100_i2c_exit(void)
+{
+	i2c_del_driver(&ab3100_driver);
+}
+
+subsys_initcall(ab3100_i2c_init);
+module_exit(ab3100_i2c_exit);
+
+MODULE_AUTHOR("Linus Walleij <linus.walleij@stericsson.com>");
+MODULE_DESCRIPTION("AB3100 core driver");
+MODULE_LICENSE("GPL");
diff --git a/drivers/mfd/asic3.c b/drivers/mfd/asic3.c
index 9e48545..63a2a66 100644
--- a/drivers/mfd/asic3.c
+++ b/drivers/mfd/asic3.c
@@ -17,6 +17,7 @@
  */
 
 #include <linux/kernel.h>
+#include <linux/delay.h>
 #include <linux/irq.h>
 #include <linux/gpio.h>
 #include <linux/io.h>
@@ -24,6 +25,51 @@
 #include <linux/platform_device.h>
 
 #include <linux/mfd/asic3.h>
+#include <linux/mfd/core.h>
+#include <linux/mfd/ds1wm.h>
+#include <linux/mfd/tmio.h>
+
+enum {
+	ASIC3_CLOCK_SPI,
+	ASIC3_CLOCK_OWM,
+	ASIC3_CLOCK_PWM0,
+	ASIC3_CLOCK_PWM1,
+	ASIC3_CLOCK_LED0,
+	ASIC3_CLOCK_LED1,
+	ASIC3_CLOCK_LED2,
+	ASIC3_CLOCK_SD_HOST,
+	ASIC3_CLOCK_SD_BUS,
+	ASIC3_CLOCK_SMBUS,
+	ASIC3_CLOCK_EX0,
+	ASIC3_CLOCK_EX1,
+};
+
+struct asic3_clk {
+	int enabled;
+	unsigned int cdex;
+	unsigned long rate;
+};
+
+#define INIT_CDEX(_name, _rate)	\
+	[ASIC3_CLOCK_##_name] = {		\
+		.cdex = CLOCK_CDEX_##_name,	\
+		.rate = _rate,			\
+	}
+
+struct asic3_clk asic3_clk_init[] __initdata = {
+	INIT_CDEX(SPI, 0),
+	INIT_CDEX(OWM, 5000000),
+	INIT_CDEX(PWM0, 0),
+	INIT_CDEX(PWM1, 0),
+	INIT_CDEX(LED0, 0),
+	INIT_CDEX(LED1, 0),
+	INIT_CDEX(LED2, 0),
+	INIT_CDEX(SD_HOST, 24576000),
+	INIT_CDEX(SD_BUS, 12288000),
+	INIT_CDEX(SMBUS, 0),
+	INIT_CDEX(EX0, 32768),
+	INIT_CDEX(EX1, 24576000),
+};
 
 struct asic3 {
 	void __iomem *mapping;
@@ -34,6 +80,8 @@
 	u16 irq_bothedge[4];
 	struct gpio_chip gpio;
 	struct device *dev;
+
+	struct asic3_clk clocks[ARRAY_SIZE(asic3_clk_init)];
 };
 
 static int asic3_gpio_get(struct gpio_chip *chip, unsigned offset);
@@ -52,6 +100,21 @@
 			(reg >> asic->bus_shift));
 }
 
+void asic3_set_register(struct asic3 *asic, u32 reg, u32 bits, bool set)
+{
+	unsigned long flags;
+	u32 val;
+
+	spin_lock_irqsave(&asic->lock, flags);
+	val = asic3_read_register(asic, reg);
+	if (set)
+		val |= bits;
+	else
+		val &= ~bits;
+	asic3_write_register(asic, reg, val);
+	spin_unlock_irqrestore(&asic->lock, flags);
+}
+
 /* IRQs */
 #define MAX_ASIC_ISR_LOOPS    20
 #define ASIC3_GPIO_BASE_INCR \
@@ -525,6 +588,240 @@
 	return gpiochip_remove(&asic->gpio);
 }
 
+static int asic3_clk_enable(struct asic3 *asic, struct asic3_clk *clk)
+{
+	unsigned long flags;
+	u32 cdex;
+
+	spin_lock_irqsave(&asic->lock, flags);
+	if (clk->enabled++ == 0) {
+		cdex = asic3_read_register(asic, ASIC3_OFFSET(CLOCK, CDEX));
+		cdex |= clk->cdex;
+		asic3_write_register(asic, ASIC3_OFFSET(CLOCK, CDEX), cdex);
+	}
+	spin_unlock_irqrestore(&asic->lock, flags);
+
+	return 0;
+}
+
+static void asic3_clk_disable(struct asic3 *asic, struct asic3_clk *clk)
+{
+	unsigned long flags;
+	u32 cdex;
+
+	WARN_ON(clk->enabled == 0);
+
+	spin_lock_irqsave(&asic->lock, flags);
+	if (--clk->enabled == 0) {
+		cdex = asic3_read_register(asic, ASIC3_OFFSET(CLOCK, CDEX));
+		cdex &= ~clk->cdex;
+		asic3_write_register(asic, ASIC3_OFFSET(CLOCK, CDEX), cdex);
+	}
+	spin_unlock_irqrestore(&asic->lock, flags);
+}
+
+/* MFD cells (SPI, PWM, LED, DS1WM, MMC) */
+static struct ds1wm_driver_data ds1wm_pdata = {
+	.active_high = 1,
+};
+
+static struct resource ds1wm_resources[] = {
+	{
+		.start = ASIC3_OWM_BASE,
+		.end   = ASIC3_OWM_BASE + 0x13,
+		.flags = IORESOURCE_MEM,
+	},
+	{
+		.start = ASIC3_IRQ_OWM,
+		.start = ASIC3_IRQ_OWM,
+		.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE,
+	},
+};
+
+static int ds1wm_enable(struct platform_device *pdev)
+{
+	struct asic3 *asic = dev_get_drvdata(pdev->dev.parent);
+
+	/* Turn on external clocks and the OWM clock */
+	asic3_clk_enable(asic, &asic->clocks[ASIC3_CLOCK_EX0]);
+	asic3_clk_enable(asic, &asic->clocks[ASIC3_CLOCK_EX1]);
+	asic3_clk_enable(asic, &asic->clocks[ASIC3_CLOCK_OWM]);
+	msleep(1);
+
+	/* Reset and enable DS1WM */
+	asic3_set_register(asic, ASIC3_OFFSET(EXTCF, RESET),
+			   ASIC3_EXTCF_OWM_RESET, 1);
+	msleep(1);
+	asic3_set_register(asic, ASIC3_OFFSET(EXTCF, RESET),
+			   ASIC3_EXTCF_OWM_RESET, 0);
+	msleep(1);
+	asic3_set_register(asic, ASIC3_OFFSET(EXTCF, SELECT),
+			   ASIC3_EXTCF_OWM_EN, 1);
+	msleep(1);
+
+	return 0;
+}
+
+static int ds1wm_disable(struct platform_device *pdev)
+{
+	struct asic3 *asic = dev_get_drvdata(pdev->dev.parent);
+
+	asic3_set_register(asic, ASIC3_OFFSET(EXTCF, SELECT),
+			   ASIC3_EXTCF_OWM_EN, 0);
+
+	asic3_clk_disable(asic, &asic->clocks[ASIC3_CLOCK_OWM]);
+	asic3_clk_disable(asic, &asic->clocks[ASIC3_CLOCK_EX0]);
+	asic3_clk_disable(asic, &asic->clocks[ASIC3_CLOCK_EX1]);
+
+	return 0;
+}
+
+static struct mfd_cell asic3_cell_ds1wm = {
+	.name          = "ds1wm",
+	.enable        = ds1wm_enable,
+	.disable       = ds1wm_disable,
+	.driver_data   = &ds1wm_pdata,
+	.num_resources = ARRAY_SIZE(ds1wm_resources),
+	.resources     = ds1wm_resources,
+};
+
+static struct tmio_mmc_data asic3_mmc_data = {
+	.hclk = 24576000,
+};
+
+static struct resource asic3_mmc_resources[] = {
+	{
+		.start = ASIC3_SD_CTRL_BASE,
+		.end   = ASIC3_SD_CTRL_BASE + 0x3ff,
+		.flags = IORESOURCE_MEM,
+	},
+	{
+		.start = ASIC3_SD_CONFIG_BASE,
+		.end   = ASIC3_SD_CONFIG_BASE + 0x1ff,
+		.flags = IORESOURCE_MEM,
+	},
+	{
+		.start = 0,
+		.end   = 0,
+		.flags = IORESOURCE_IRQ,
+	},
+};
+
+static int asic3_mmc_enable(struct platform_device *pdev)
+{
+	struct asic3 *asic = dev_get_drvdata(pdev->dev.parent);
+
+	/* Not sure if it must be done bit by bit, but leaving as-is */
+	asic3_set_register(asic, ASIC3_OFFSET(SDHWCTRL, SDCONF),
+			   ASIC3_SDHWCTRL_LEVCD, 1);
+	asic3_set_register(asic, ASIC3_OFFSET(SDHWCTRL, SDCONF),
+			   ASIC3_SDHWCTRL_LEVWP, 1);
+	asic3_set_register(asic, ASIC3_OFFSET(SDHWCTRL, SDCONF),
+			   ASIC3_SDHWCTRL_SUSPEND, 0);
+	asic3_set_register(asic, ASIC3_OFFSET(SDHWCTRL, SDCONF),
+			   ASIC3_SDHWCTRL_PCLR, 0);
+
+	asic3_clk_enable(asic, &asic->clocks[ASIC3_CLOCK_EX0]);
+	/* CLK32 used for card detection and for interruption detection
+	 * when HCLK is stopped.
+	 */
+	asic3_clk_enable(asic, &asic->clocks[ASIC3_CLOCK_EX1]);
+	msleep(1);
+
+	/* HCLK 24.576 MHz, BCLK 12.288 MHz: */
+	asic3_write_register(asic, ASIC3_OFFSET(CLOCK, SEL),
+		CLOCK_SEL_CX | CLOCK_SEL_SD_HCLK_SEL);
+
+	asic3_clk_enable(asic, &asic->clocks[ASIC3_CLOCK_SD_HOST]);
+	asic3_clk_enable(asic, &asic->clocks[ASIC3_CLOCK_SD_BUS]);
+	msleep(1);
+
+	asic3_set_register(asic, ASIC3_OFFSET(EXTCF, SELECT),
+			   ASIC3_EXTCF_SD_MEM_ENABLE, 1);
+
+	/* Enable SD card slot 3.3V power supply */
+	asic3_set_register(asic, ASIC3_OFFSET(SDHWCTRL, SDCONF),
+			   ASIC3_SDHWCTRL_SDPWR, 1);
+
+	return 0;
+}
+
+static int asic3_mmc_disable(struct platform_device *pdev)
+{
+	struct asic3 *asic = dev_get_drvdata(pdev->dev.parent);
+
+	/* Put in suspend mode */
+	asic3_set_register(asic, ASIC3_OFFSET(SDHWCTRL, SDCONF),
+			   ASIC3_SDHWCTRL_SUSPEND, 1);
+
+	/* Disable clocks */
+	asic3_clk_disable(asic, &asic->clocks[ASIC3_CLOCK_SD_HOST]);
+	asic3_clk_disable(asic, &asic->clocks[ASIC3_CLOCK_SD_BUS]);
+	asic3_clk_disable(asic, &asic->clocks[ASIC3_CLOCK_EX0]);
+	asic3_clk_disable(asic, &asic->clocks[ASIC3_CLOCK_EX1]);
+	return 0;
+}
+
+static struct mfd_cell asic3_cell_mmc = {
+	.name          = "tmio-mmc",
+	.enable        = asic3_mmc_enable,
+	.disable       = asic3_mmc_disable,
+	.driver_data   = &asic3_mmc_data,
+	.num_resources = ARRAY_SIZE(asic3_mmc_resources),
+	.resources     = asic3_mmc_resources,
+};
+
+static int __init asic3_mfd_probe(struct platform_device *pdev,
+				  struct resource *mem)
+{
+	struct asic3 *asic = platform_get_drvdata(pdev);
+	struct resource *mem_sdio;
+	int irq, ret;
+
+	mem_sdio = platform_get_resource(pdev, IORESOURCE_MEM, 1);
+	if (!mem_sdio)
+		dev_dbg(asic->dev, "no SDIO MEM resource\n");
+
+	irq = platform_get_irq(pdev, 1);
+	if (irq < 0)
+		dev_dbg(asic->dev, "no SDIO IRQ resource\n");
+
+	/* DS1WM */
+	asic3_set_register(asic, ASIC3_OFFSET(EXTCF, SELECT),
+			   ASIC3_EXTCF_OWM_SMB, 0);
+
+	ds1wm_resources[0].start >>= asic->bus_shift;
+	ds1wm_resources[0].end   >>= asic->bus_shift;
+
+	asic3_cell_ds1wm.platform_data = &asic3_cell_ds1wm;
+	asic3_cell_ds1wm.data_size = sizeof(asic3_cell_ds1wm);
+
+	/* MMC */
+	asic3_mmc_resources[0].start >>= asic->bus_shift;
+	asic3_mmc_resources[0].end   >>= asic->bus_shift;
+	asic3_mmc_resources[1].start >>= asic->bus_shift;
+	asic3_mmc_resources[1].end   >>= asic->bus_shift;
+
+	asic3_cell_mmc.platform_data = &asic3_cell_mmc;
+	asic3_cell_mmc.data_size = sizeof(asic3_cell_mmc);
+
+	ret = mfd_add_devices(&pdev->dev, pdev->id,
+			&asic3_cell_ds1wm, 1, mem, asic->irq_base);
+	if (ret < 0)
+		goto out;
+
+	if (mem_sdio && (irq >= 0))
+		ret = mfd_add_devices(&pdev->dev, pdev->id,
+			&asic3_cell_mmc, 1, mem_sdio, irq);
+
+ out:
+	return ret;
+}
+
+static void asic3_mfd_remove(struct platform_device *pdev)
+{
+	mfd_remove_devices(&pdev->dev);
+}
 
 /* Core */
 static int __init asic3_probe(struct platform_device *pdev)
@@ -533,7 +830,6 @@
 	struct asic3 *asic;
 	struct resource *mem;
 	unsigned long clksel;
-	int map_size;
 	int ret = 0;
 
 	asic = kzalloc(sizeof(struct asic3), GFP_KERNEL);
@@ -553,8 +849,7 @@
 		goto out_free;
 	}
 
-	map_size = mem->end - mem->start + 1;
-	asic->mapping = ioremap(mem->start, map_size);
+	asic->mapping = ioremap(mem->start, resource_size(mem));
 	if (!asic->mapping) {
 		ret = -ENOMEM;
 		dev_err(asic->dev, "Couldn't ioremap\n");
@@ -564,7 +859,7 @@
 	asic->irq_base = pdata->irq_base;
 
 	/* calculate bus shift from mem resource */
-	asic->bus_shift = 2 - (map_size >> 12);
+	asic->bus_shift = 2 - (resource_size(mem) >> 12);
 
 	clksel = 0;
 	asic3_write_register(asic, ASIC3_OFFSET(CLOCK, SEL), clksel);
@@ -590,6 +885,13 @@
 		goto out_irq;
 	}
 
+	/* Making a per-device copy is only needed for the
+	 * theoretical case of multiple ASIC3s on one board:
+	 */
+	memcpy(asic->clocks, asic3_clk_init, sizeof(asic3_clk_init));
+
+	asic3_mfd_probe(pdev, mem);
+
 	dev_info(asic->dev, "ASIC3 Core driver\n");
 
 	return 0;
@@ -611,6 +913,8 @@
 	int ret;
 	struct asic3 *asic = platform_get_drvdata(pdev);
 
+	asic3_mfd_remove(pdev);
+
 	ret = asic3_gpio_remove(pdev);
 	if (ret < 0)
 		return ret;
diff --git a/drivers/mfd/da903x.c b/drivers/mfd/da903x.c
index 7283d88..e5ffe56 100644
--- a/drivers/mfd/da903x.c
+++ b/drivers/mfd/da903x.c
@@ -561,7 +561,7 @@
 {
 	return i2c_add_driver(&da903x_driver);
 }
-module_init(da903x_init);
+subsys_initcall(da903x_init);
 
 static void __exit da903x_exit(void)
 {
diff --git a/drivers/mfd/ezx-pcap.c b/drivers/mfd/ezx-pcap.c
new file mode 100644
index 0000000..671a7ef
--- /dev/null
+++ b/drivers/mfd/ezx-pcap.c
@@ -0,0 +1,505 @@
+/*
+ * Driver for Motorola PCAP2 as present in EZX phones
+ *
+ * Copyright (C) 2006 Harald Welte <laforge@openezx.org>
+ * Copyright (C) 2009 Daniel Ribeiro <drwyrm@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ */
+
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/platform_device.h>
+#include <linux/interrupt.h>
+#include <linux/irq.h>
+#include <linux/mfd/ezx-pcap.h>
+#include <linux/spi/spi.h>
+
+#define PCAP_ADC_MAXQ		8
+struct pcap_adc_request {
+	u8 bank;
+	u8 ch[2];
+	u32 flags;
+	void (*callback)(void *, u16[]);
+	void *data;
+};
+
+struct pcap_adc_sync_request {
+	u16 res[2];
+	struct completion completion;
+};
+
+struct pcap_chip {
+	struct spi_device *spi;
+
+	/* IO */
+	u32 buf;
+	struct mutex io_mutex;
+
+	/* IRQ */
+	unsigned int irq_base;
+	u32 msr;
+	struct work_struct isr_work;
+	struct work_struct msr_work;
+	struct workqueue_struct *workqueue;
+
+	/* ADC */
+	struct pcap_adc_request *adc_queue[PCAP_ADC_MAXQ];
+	u8 adc_head;
+	u8 adc_tail;
+	struct mutex adc_mutex;
+};
+
+/* IO */
+static int ezx_pcap_putget(struct pcap_chip *pcap, u32 *data)
+{
+	struct spi_transfer t;
+	struct spi_message m;
+	int status;
+
+	memset(&t, 0, sizeof t);
+	spi_message_init(&m);
+	t.len = sizeof(u32);
+	spi_message_add_tail(&t, &m);
+
+	pcap->buf = *data;
+	t.tx_buf = (u8 *) &pcap->buf;
+	t.rx_buf = (u8 *) &pcap->buf;
+	status = spi_sync(pcap->spi, &m);
+
+	if (status == 0)
+		*data = pcap->buf;
+
+	return status;
+}
+
+int ezx_pcap_write(struct pcap_chip *pcap, u8 reg_num, u32 value)
+{
+	int ret;
+
+	mutex_lock(&pcap->io_mutex);
+	value &= PCAP_REGISTER_VALUE_MASK;
+	value |= PCAP_REGISTER_WRITE_OP_BIT
+		| (reg_num << PCAP_REGISTER_ADDRESS_SHIFT);
+	ret = ezx_pcap_putget(pcap, &value);
+	mutex_unlock(&pcap->io_mutex);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(ezx_pcap_write);
+
+int ezx_pcap_read(struct pcap_chip *pcap, u8 reg_num, u32 *value)
+{
+	int ret;
+
+	mutex_lock(&pcap->io_mutex);
+	*value = PCAP_REGISTER_READ_OP_BIT
+		| (reg_num << PCAP_REGISTER_ADDRESS_SHIFT);
+
+	ret = ezx_pcap_putget(pcap, value);
+	mutex_unlock(&pcap->io_mutex);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(ezx_pcap_read);
+
+/* IRQ */
+static inline unsigned int irq2pcap(struct pcap_chip *pcap, int irq)
+{
+	return 1 << (irq - pcap->irq_base);
+}
+
+int pcap_to_irq(struct pcap_chip *pcap, int irq)
+{
+	return pcap->irq_base + irq;
+}
+EXPORT_SYMBOL_GPL(pcap_to_irq);
+
+static void pcap_mask_irq(unsigned int irq)
+{
+	struct pcap_chip *pcap = get_irq_chip_data(irq);
+
+	pcap->msr |= irq2pcap(pcap, irq);
+	queue_work(pcap->workqueue, &pcap->msr_work);
+}
+
+static void pcap_unmask_irq(unsigned int irq)
+{
+	struct pcap_chip *pcap = get_irq_chip_data(irq);
+
+	pcap->msr &= ~irq2pcap(pcap, irq);
+	queue_work(pcap->workqueue, &pcap->msr_work);
+}
+
+static struct irq_chip pcap_irq_chip = {
+	.name	= "pcap",
+	.mask	= pcap_mask_irq,
+	.unmask	= pcap_unmask_irq,
+};
+
+static void pcap_msr_work(struct work_struct *work)
+{
+	struct pcap_chip *pcap = container_of(work, struct pcap_chip, msr_work);
+
+	ezx_pcap_write(pcap, PCAP_REG_MSR, pcap->msr);
+}
+
+static void pcap_isr_work(struct work_struct *work)
+{
+	struct pcap_chip *pcap = container_of(work, struct pcap_chip, isr_work);
+	struct pcap_platform_data *pdata = pcap->spi->dev.platform_data;
+	u32 msr, isr, int_sel, service;
+	int irq;
+
+	ezx_pcap_read(pcap, PCAP_REG_MSR, &msr);
+	ezx_pcap_read(pcap, PCAP_REG_ISR, &isr);
+
+	/* We cant service/ack irqs that are assigned to port 2 */
+	if (!(pdata->config & PCAP_SECOND_PORT)) {
+		ezx_pcap_read(pcap, PCAP_REG_INT_SEL, &int_sel);
+		isr &= ~int_sel;
+	}
+	ezx_pcap_write(pcap, PCAP_REG_ISR, isr);
+
+	local_irq_disable();
+	service = isr & ~msr;
+
+	for (irq = pcap->irq_base; service; service >>= 1, irq++) {
+		if (service & 1) {
+			struct irq_desc *desc = irq_to_desc(irq);
+
+			if (WARN(!desc, KERN_WARNING
+					"Invalid PCAP IRQ %d\n", irq))
+				break;
+
+			if (desc->status & IRQ_DISABLED)
+				note_interrupt(irq, desc, IRQ_NONE);
+			else
+				desc->handle_irq(irq, desc);
+		}
+	}
+	local_irq_enable();
+}
+
+static void pcap_irq_handler(unsigned int irq, struct irq_desc *desc)
+{
+	struct pcap_chip *pcap = get_irq_data(irq);
+
+	desc->chip->ack(irq);
+	queue_work(pcap->workqueue, &pcap->isr_work);
+	return;
+}
+
+/* ADC */
+static void pcap_disable_adc(struct pcap_chip *pcap)
+{
+	u32 tmp;
+
+	ezx_pcap_read(pcap, PCAP_REG_ADC, &tmp);
+	tmp &= ~(PCAP_ADC_ADEN|PCAP_ADC_BATT_I_ADC|PCAP_ADC_BATT_I_POLARITY);
+	ezx_pcap_write(pcap, PCAP_REG_ADC, tmp);
+}
+
+static void pcap_adc_trigger(struct pcap_chip *pcap)
+{
+	u32 tmp;
+	u8 head;
+
+	mutex_lock(&pcap->adc_mutex);
+	head = pcap->adc_head;
+	if (!pcap->adc_queue[head]) {
+		/* queue is empty, save power */
+		pcap_disable_adc(pcap);
+		mutex_unlock(&pcap->adc_mutex);
+		return;
+	}
+	mutex_unlock(&pcap->adc_mutex);
+
+	/* start conversion on requested bank */
+	tmp = pcap->adc_queue[head]->flags | PCAP_ADC_ADEN;
+
+	if (pcap->adc_queue[head]->bank == PCAP_ADC_BANK_1)
+		tmp |= PCAP_ADC_AD_SEL1;
+
+	ezx_pcap_write(pcap, PCAP_REG_ADC, tmp);
+	ezx_pcap_write(pcap, PCAP_REG_ADR, PCAP_ADR_ASC);
+}
+
+static irqreturn_t pcap_adc_irq(int irq, void *_pcap)
+{
+	struct pcap_chip *pcap = _pcap;
+	struct pcap_adc_request *req;
+	u16 res[2];
+	u32 tmp;
+
+	mutex_lock(&pcap->adc_mutex);
+	req = pcap->adc_queue[pcap->adc_head];
+
+	if (WARN(!req, KERN_WARNING "adc irq without pending request\n"))
+		return IRQ_HANDLED;
+
+	/* read requested channels results */
+	ezx_pcap_read(pcap, PCAP_REG_ADC, &tmp);
+	tmp &= ~(PCAP_ADC_ADA1_MASK | PCAP_ADC_ADA2_MASK);
+	tmp |= (req->ch[0] << PCAP_ADC_ADA1_SHIFT);
+	tmp |= (req->ch[1] << PCAP_ADC_ADA2_SHIFT);
+	ezx_pcap_write(pcap, PCAP_REG_ADC, tmp);
+	ezx_pcap_read(pcap, PCAP_REG_ADR, &tmp);
+	res[0] = (tmp & PCAP_ADR_ADD1_MASK) >> PCAP_ADR_ADD1_SHIFT;
+	res[1] = (tmp & PCAP_ADR_ADD2_MASK) >> PCAP_ADR_ADD2_SHIFT;
+
+	pcap->adc_queue[pcap->adc_head] = NULL;
+	pcap->adc_head = (pcap->adc_head + 1) & (PCAP_ADC_MAXQ - 1);
+	mutex_unlock(&pcap->adc_mutex);
+
+	/* pass the results and release memory */
+	req->callback(req->data, res);
+	kfree(req);
+
+	/* trigger next conversion (if any) on queue */
+	pcap_adc_trigger(pcap);
+
+	return IRQ_HANDLED;
+}
+
+int pcap_adc_async(struct pcap_chip *pcap, u8 bank, u32 flags, u8 ch[],
+						void *callback, void *data)
+{
+	struct pcap_adc_request *req;
+
+	/* This will be freed after we have a result */
+	req = kmalloc(sizeof(struct pcap_adc_request), GFP_KERNEL);
+	if (!req)
+		return -ENOMEM;
+
+	req->bank = bank;
+	req->flags = flags;
+	req->ch[0] = ch[0];
+	req->ch[1] = ch[1];
+	req->callback = callback;
+	req->data = data;
+
+	mutex_lock(&pcap->adc_mutex);
+	if (pcap->adc_queue[pcap->adc_tail]) {
+		mutex_unlock(&pcap->adc_mutex);
+		kfree(req);
+		return -EBUSY;
+	}
+	pcap->adc_queue[pcap->adc_tail] = req;
+	pcap->adc_tail = (pcap->adc_tail + 1) & (PCAP_ADC_MAXQ - 1);
+	mutex_unlock(&pcap->adc_mutex);
+
+	/* start conversion */
+	pcap_adc_trigger(pcap);
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(pcap_adc_async);
+
+static void pcap_adc_sync_cb(void *param, u16 res[])
+{
+	struct pcap_adc_sync_request *req = param;
+
+	req->res[0] = res[0];
+	req->res[1] = res[1];
+	complete(&req->completion);
+}
+
+int pcap_adc_sync(struct pcap_chip *pcap, u8 bank, u32 flags, u8 ch[],
+								u16 res[])
+{
+	struct pcap_adc_sync_request sync_data;
+	int ret;
+
+	init_completion(&sync_data.completion);
+	ret = pcap_adc_async(pcap, bank, flags, ch, pcap_adc_sync_cb,
+								&sync_data);
+	if (ret)
+		return ret;
+	wait_for_completion(&sync_data.completion);
+	res[0] = sync_data.res[0];
+	res[1] = sync_data.res[1];
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(pcap_adc_sync);
+
+/* subdevs */
+static int pcap_remove_subdev(struct device *dev, void *unused)
+{
+	platform_device_unregister(to_platform_device(dev));
+	return 0;
+}
+
+static int __devinit pcap_add_subdev(struct pcap_chip *pcap,
+						struct pcap_subdev *subdev)
+{
+	struct platform_device *pdev;
+
+	pdev = platform_device_alloc(subdev->name, subdev->id);
+	pdev->dev.parent = &pcap->spi->dev;
+	pdev->dev.platform_data = subdev->platform_data;
+	platform_set_drvdata(pdev, pcap);
+
+	return platform_device_add(pdev);
+}
+
+static int __devexit ezx_pcap_remove(struct spi_device *spi)
+{
+	struct pcap_chip *pcap = dev_get_drvdata(&spi->dev);
+	struct pcap_platform_data *pdata = spi->dev.platform_data;
+	int i, adc_irq;
+
+	/* remove all registered subdevs */
+	device_for_each_child(&spi->dev, NULL, pcap_remove_subdev);
+
+	/* cleanup ADC */
+	adc_irq = pcap_to_irq(pcap, (pdata->config & PCAP_SECOND_PORT) ?
+				PCAP_IRQ_ADCDONE2 : PCAP_IRQ_ADCDONE);
+	free_irq(adc_irq, pcap);
+	mutex_lock(&pcap->adc_mutex);
+	for (i = 0; i < PCAP_ADC_MAXQ; i++)
+		kfree(pcap->adc_queue[i]);
+	mutex_unlock(&pcap->adc_mutex);
+
+	/* cleanup irqchip */
+	for (i = pcap->irq_base; i < (pcap->irq_base + PCAP_NIRQS); i++)
+		set_irq_chip_and_handler(i, NULL, NULL);
+
+	destroy_workqueue(pcap->workqueue);
+
+	kfree(pcap);
+
+	return 0;
+}
+
+static int __devinit ezx_pcap_probe(struct spi_device *spi)
+{
+	struct pcap_platform_data *pdata = spi->dev.platform_data;
+	struct pcap_chip *pcap;
+	int i, adc_irq;
+	int ret = -ENODEV;
+
+	/* platform data is required */
+	if (!pdata)
+		goto ret;
+
+	pcap = kzalloc(sizeof(*pcap), GFP_KERNEL);
+	if (!pcap) {
+		ret = -ENOMEM;
+		goto ret;
+	}
+
+	mutex_init(&pcap->io_mutex);
+	mutex_init(&pcap->adc_mutex);
+	INIT_WORK(&pcap->isr_work, pcap_isr_work);
+	INIT_WORK(&pcap->msr_work, pcap_msr_work);
+	dev_set_drvdata(&spi->dev, pcap);
+
+	/* setup spi */
+	spi->bits_per_word = 32;
+	spi->mode = SPI_MODE_0 | (pdata->config & PCAP_CS_AH ? SPI_CS_HIGH : 0);
+	ret = spi_setup(spi);
+	if (ret)
+		goto free_pcap;
+
+	pcap->spi = spi;
+
+	/* setup irq */
+	pcap->irq_base = pdata->irq_base;
+	pcap->workqueue = create_singlethread_workqueue("pcapd");
+	if (!pcap->workqueue) {
+		dev_err(&spi->dev, "cant create pcap thread\n");
+		goto free_pcap;
+	}
+
+	/* redirect interrupts to AP, except adcdone2 */
+	if (!(pdata->config & PCAP_SECOND_PORT))
+		ezx_pcap_write(pcap, PCAP_REG_INT_SEL,
+					(1 << PCAP_IRQ_ADCDONE2));
+
+	/* setup irq chip */
+	for (i = pcap->irq_base; i < (pcap->irq_base + PCAP_NIRQS); i++) {
+		set_irq_chip_and_handler(i, &pcap_irq_chip, handle_simple_irq);
+		set_irq_chip_data(i, pcap);
+#ifdef CONFIG_ARM
+		set_irq_flags(i, IRQF_VALID);
+#else
+		set_irq_noprobe(i);
+#endif
+	}
+
+	/* mask/ack all PCAP interrupts */
+	ezx_pcap_write(pcap, PCAP_REG_MSR, PCAP_MASK_ALL_INTERRUPT);
+	ezx_pcap_write(pcap, PCAP_REG_ISR, PCAP_CLEAR_INTERRUPT_REGISTER);
+	pcap->msr = PCAP_MASK_ALL_INTERRUPT;
+
+	set_irq_type(spi->irq, IRQ_TYPE_EDGE_RISING);
+	set_irq_data(spi->irq, pcap);
+	set_irq_chained_handler(spi->irq, pcap_irq_handler);
+	set_irq_wake(spi->irq, 1);
+
+	/* ADC */
+	adc_irq = pcap_to_irq(pcap, (pdata->config & PCAP_SECOND_PORT) ?
+					PCAP_IRQ_ADCDONE2 : PCAP_IRQ_ADCDONE);
+
+	ret = request_irq(adc_irq, pcap_adc_irq, 0, "ADC", pcap);
+	if (ret)
+		goto free_irqchip;
+
+	/* setup subdevs */
+	for (i = 0; i < pdata->num_subdevs; i++) {
+		ret = pcap_add_subdev(pcap, &pdata->subdevs[i]);
+		if (ret)
+			goto remove_subdevs;
+	}
+
+	/* board specific quirks */
+	if (pdata->init)
+		pdata->init(pcap);
+
+	return 0;
+
+remove_subdevs:
+	device_for_each_child(&spi->dev, NULL, pcap_remove_subdev);
+/* free_adc: */
+	free_irq(adc_irq, pcap);
+free_irqchip:
+	for (i = pcap->irq_base; i < (pcap->irq_base + PCAP_NIRQS); i++)
+		set_irq_chip_and_handler(i, NULL, NULL);
+/* destroy_workqueue: */
+	destroy_workqueue(pcap->workqueue);
+free_pcap:
+	kfree(pcap);
+ret:
+	return ret;
+}
+
+static struct spi_driver ezxpcap_driver = {
+	.probe	= ezx_pcap_probe,
+	.remove = __devexit_p(ezx_pcap_remove),
+	.driver = {
+		.name	= "ezx-pcap",
+		.owner	= THIS_MODULE,
+	},
+};
+
+static int __init ezx_pcap_init(void)
+{
+	return spi_register_driver(&ezxpcap_driver);
+}
+
+static void __exit ezx_pcap_exit(void)
+{
+	spi_unregister_driver(&ezxpcap_driver);
+}
+
+module_init(ezx_pcap_init);
+module_exit(ezx_pcap_exit);
+
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Daniel Ribeiro / Harald Welte");
+MODULE_DESCRIPTION("Motorola PCAP2 ASIC Driver");
diff --git a/drivers/mfd/pcf50633-core.c b/drivers/mfd/pcf50633-core.c
index 082c197..8d3c38b 100644
--- a/drivers/mfd/pcf50633-core.c
+++ b/drivers/mfd/pcf50633-core.c
@@ -705,5 +705,5 @@
 MODULE_AUTHOR("Harald Welte <laforge@openmoko.org>");
 MODULE_LICENSE("GPL");
 
-module_init(pcf50633_init);
+subsys_initcall(pcf50633_init);
 module_exit(pcf50633_exit);
diff --git a/drivers/mfd/pcf50633-gpio.c b/drivers/mfd/pcf50633-gpio.c
index 2fa2eca..9ab19a8 100644
--- a/drivers/mfd/pcf50633-gpio.c
+++ b/drivers/mfd/pcf50633-gpio.c
@@ -15,6 +15,7 @@
  */
 
 #include <linux/kernel.h>
+#include <linux/module.h>
 
 #include <linux/mfd/pcf50633/core.h>
 #include <linux/mfd/pcf50633/gpio.h>
@@ -116,3 +117,5 @@
 	return pcf50633_reg_set_bit_mask(pcf, reg, mask, val);
 }
 EXPORT_SYMBOL_GPL(pcf50633_gpio_power_supply_set);
+
+MODULE_LICENSE("GPL");
diff --git a/drivers/mfd/t7l66xb.c b/drivers/mfd/t7l66xb.c
index 875f7a8..0a255c1 100644
--- a/drivers/mfd/t7l66xb.c
+++ b/drivers/mfd/t7l66xb.c
@@ -108,7 +108,7 @@
 
 /*--------------------------------------------------------------------------*/
 
-static const struct tmio_mmc_data t7166xb_mmc_data = {
+static struct tmio_mmc_data t7166xb_mmc_data = {
 	.hclk = 24000000,
 };
 
diff --git a/drivers/mfd/tc6387xb.c b/drivers/mfd/tc6387xb.c
index c3993ac..3280ab33 100644
--- a/drivers/mfd/tc6387xb.c
+++ b/drivers/mfd/tc6387xb.c
@@ -75,7 +75,7 @@
 
 /*--------------------------------------------------------------------------*/
 
-const static struct tmio_mmc_data tc6387xb_mmc_data = {
+static struct tmio_mmc_data tc6387xb_mmc_data = {
 	.hclk = 24000000,
 };
 
diff --git a/drivers/mfd/tc6393xb.c b/drivers/mfd/tc6393xb.c
index 9d2abb5..1429a73 100644
--- a/drivers/mfd/tc6393xb.c
+++ b/drivers/mfd/tc6393xb.c
@@ -136,7 +136,7 @@
 	return 0;
 }
 
-const static struct tmio_mmc_data tc6393xb_mmc_data = {
+static struct tmio_mmc_data tc6393xb_mmc_data = {
 	.hclk = 24000000,
 };
 
diff --git a/drivers/mfd/twl4030-core.c b/drivers/mfd/twl4030-core.c
index ec90e95..cd1008c 100644
--- a/drivers/mfd/twl4030-core.c
+++ b/drivers/mfd/twl4030-core.c
@@ -647,7 +647,7 @@
 	return e;
 }
 
-static void __init clocks_init(struct device *dev)
+static void clocks_init(struct device *dev)
 {
 	int e = 0;
 	struct clk *osc;
diff --git a/drivers/mfd/twl4030-irq.c b/drivers/mfd/twl4030-irq.c
index aca2670..bae61b2 100644
--- a/drivers/mfd/twl4030-irq.c
+++ b/drivers/mfd/twl4030-irq.c
@@ -255,7 +255,7 @@
  * thread.  All we do here is acknowledge and mask the interrupt and wakeup
  * the kernel thread.
  */
-static void handle_twl4030_pih(unsigned int irq, irq_desc_t *desc)
+static void handle_twl4030_pih(unsigned int irq, struct irq_desc *desc)
 {
 	/* Acknowledge, clear *AND* mask the interrupt... */
 	desc->chip->ack(irq);
diff --git a/drivers/mfd/ucb1400_core.c b/drivers/mfd/ucb1400_core.c
index 178159e..78c2135 100644
--- a/drivers/mfd/ucb1400_core.c
+++ b/drivers/mfd/ucb1400_core.c
@@ -23,6 +23,26 @@
 #include <linux/module.h>
 #include <linux/ucb1400.h>
 
+unsigned int ucb1400_adc_read(struct snd_ac97 *ac97, u16 adc_channel,
+		int adcsync)
+{
+	unsigned int val;
+
+	if (adcsync)
+		adc_channel |= UCB_ADC_SYNC_ENA;
+
+	ucb1400_reg_write(ac97, UCB_ADC_CR, UCB_ADC_ENA | adc_channel);
+	ucb1400_reg_write(ac97, UCB_ADC_CR, UCB_ADC_ENA | adc_channel |
+			UCB_ADC_START);
+
+	while (!((val = ucb1400_reg_read(ac97, UCB_ADC_DATA))
+				& UCB_ADC_DAT_VALID))
+		schedule_timeout_uninterruptible(1);
+
+	return val & UCB_ADC_DAT_MASK;
+}
+EXPORT_SYMBOL_GPL(ucb1400_adc_read);
+
 static int ucb1400_core_probe(struct device *dev)
 {
 	int err;
diff --git a/drivers/mfd/wm8350-regmap.c b/drivers/mfd/wm8350-regmap.c
index 9a4cc95..7ccc1ea 100644
--- a/drivers/mfd/wm8350-regmap.c
+++ b/drivers/mfd/wm8350-regmap.c
@@ -3186,7 +3186,7 @@
 	/*  read    write volatile */
 	{ 0xFFFF, 0xFFFF, 0xFFFF }, /* R0   - Reset/ID */
 	{ 0x7CFF, 0x0C00, 0x7FFF }, /* R1   - ID */
-	{ 0x0000, 0x0000, 0x0000 }, /* R2 */
+	{ 0x007F, 0x0000, 0x0000 }, /* R2   - ROM Mask ID */
 	{ 0xBE3B, 0xBE3B, 0x8000 }, /* R3   - System Control 1 */
 	{ 0xFEF7, 0xFEF7, 0xF800 }, /* R4   - System Control 2 */
 	{ 0x80FF, 0x80FF, 0x8000 }, /* R5   - System Hibernate */
@@ -3411,7 +3411,7 @@
 	{ 0x0000, 0x0000, 0x0000 }, /* R224 */
 	{ 0x8F3F, 0x0000, 0xFFFF }, /* R225 - DCDC/LDO status */
 	{ 0x0000, 0x0000, 0xFFFF }, /* R226 - Charger status */
-	{ 0x0000, 0x0000, 0xFFFF }, /* R227 */
+	{ 0x34FE, 0x0000, 0xFFFF }, /* R227 */
 	{ 0x0000, 0x0000, 0x0000 }, /* R228 */
 	{ 0x0000, 0x0000, 0x0000 }, /* R229 */
 	{ 0xFFFF, 0x1FFF, 0xFFFF }, /* R230 - GPIO Pin Status */
diff --git a/drivers/mfd/wm8400-core.c b/drivers/mfd/wm8400-core.c
index 7c21bf7..ecfc8bb 100644
--- a/drivers/mfd/wm8400-core.c
+++ b/drivers/mfd/wm8400-core.c
@@ -460,7 +460,7 @@
 
 	return ret;
 }
-module_init(wm8400_module_init);
+subsys_initcall(wm8400_module_init);
 
 static void __exit wm8400_module_exit(void)
 {
diff --git a/drivers/misc/sgi-gru/Makefile b/drivers/misc/sgi-gru/Makefile
index bcd8136..7c4c306 100644
--- a/drivers/misc/sgi-gru/Makefile
+++ b/drivers/misc/sgi-gru/Makefile
@@ -3,5 +3,5 @@
 endif
 
 obj-$(CONFIG_SGI_GRU) := gru.o
-gru-y := grufile.o grumain.o grufault.o grutlbpurge.o gruprocfs.o grukservices.o gruhandles.o
+gru-y := grufile.o grumain.o grufault.o grutlbpurge.o gruprocfs.o grukservices.o gruhandles.o grukdump.o
 
diff --git a/drivers/misc/sgi-gru/gru_instructions.h b/drivers/misc/sgi-gru/gru_instructions.h
index 3fde33c..3c9c066 100644
--- a/drivers/misc/sgi-gru/gru_instructions.h
+++ b/drivers/misc/sgi-gru/gru_instructions.h
@@ -81,6 +81,8 @@
 	int		exopc;
 	long		exceptdet0;
 	int		exceptdet1;
+	int		cbrstate;
+	int		cbrexecstatus;
 };
 
 /*
@@ -107,7 +109,8 @@
     unsigned char		reserved2: 2;
     unsigned char		istatus:   2;
     unsigned char		isubstatus:4;
-    unsigned char		reserved3: 2;
+    unsigned char		reserved3: 1;
+    unsigned char		tlb_fault_color: 1;
     /* DW 1 */
     unsigned long		idef4;		/* 42 bits: TRi1, BufSize */
     /* DW 2-6 */
@@ -250,17 +253,37 @@
 #define CBE_CAUSE_HA_RESPONSE_FATAL		(1 << 13)
 #define CBE_CAUSE_HA_RESPONSE_NON_FATAL		(1 << 14)
 #define CBE_CAUSE_ADDRESS_SPACE_DECODE_ERROR	(1 << 15)
-#define CBE_CAUSE_RESPONSE_DATA_ERROR		(1 << 16)
-#define CBE_CAUSE_PROTOCOL_STATE_DATA_ERROR	(1 << 17)
+#define CBE_CAUSE_PROTOCOL_STATE_DATA_ERROR	(1 << 16)
+#define CBE_CAUSE_RA_RESPONSE_DATA_ERROR	(1 << 17)
+#define CBE_CAUSE_HA_RESPONSE_DATA_ERROR	(1 << 18)
+
+/* CBE cbrexecstatus bits */
+#define CBR_EXS_ABORT_OCC_BIT			0
+#define CBR_EXS_INT_OCC_BIT			1
+#define CBR_EXS_PENDING_BIT			2
+#define CBR_EXS_QUEUED_BIT			3
+#define CBR_EXS_TLB_INVAL_BIT			4
+#define CBR_EXS_EXCEPTION_BIT			5
+
+#define CBR_EXS_ABORT_OCC			(1 << CBR_EXS_ABORT_OCC_BIT)
+#define CBR_EXS_INT_OCC				(1 << CBR_EXS_INT_OCC_BIT)
+#define CBR_EXS_PENDING				(1 << CBR_EXS_PENDING_BIT)
+#define CBR_EXS_QUEUED				(1 << CBR_EXS_QUEUED_BIT)
+#define CBR_TLB_INVAL				(1 << CBR_EXS_TLB_INVAL_BIT)
+#define CBR_EXS_EXCEPTION			(1 << CBR_EXS_EXCEPTION_BIT)
 
 /*
  * Exceptions are retried for the following cases. If any OTHER bits are set
  * in ecause, the exception is not retryable.
  */
-#define EXCEPTION_RETRY_BITS (CBE_CAUSE_RESPONSE_DATA_ERROR |		\
-			      CBE_CAUSE_RA_REQUEST_TIMEOUT |		\
+#define EXCEPTION_RETRY_BITS (CBE_CAUSE_EXECUTION_HW_ERROR |		\
 			      CBE_CAUSE_TLBHW_ERROR |			\
-			      CBE_CAUSE_HA_REQUEST_TIMEOUT)
+			      CBE_CAUSE_RA_REQUEST_TIMEOUT |		\
+			      CBE_CAUSE_RA_RESPONSE_NON_FATAL |		\
+			      CBE_CAUSE_HA_RESPONSE_NON_FATAL |		\
+			      CBE_CAUSE_RA_RESPONSE_DATA_ERROR |	\
+			      CBE_CAUSE_HA_RESPONSE_DATA_ERROR		\
+			      )
 
 /* Message queue head structure */
 union gru_mesqhead {
@@ -600,9 +623,11 @@
 	return cbs->isubstatus;
 }
 
-/* Check the status of a CB. If the CB is in UPM mode, call the
- * OS to handle the UPM status.
- * Returns the CB status field value (0 for normal completion)
+/*
+ * User interface to check an instruction status. UPM and exceptions
+ * are handled automatically. However, this function does NOT wait
+ * for an active instruction to complete.
+ *
  */
 static inline int gru_check_status(void *cb)
 {
@@ -610,34 +635,31 @@
 	int ret;
 
 	ret = cbs->istatus;
-	if (ret == CBS_CALL_OS)
+	if (ret != CBS_ACTIVE)
 		ret = gru_check_status_proc(cb);
 	return ret;
 }
 
-/* Wait for CB to complete.
- * Returns the CB status field value (0 for normal completion)
+/*
+ * User interface (via inline function) to wait for an instruction
+ * to complete. Completion status (IDLE or EXCEPTION is returned
+ * to the user. Exception due to hardware errors are automatically
+ * retried before returning an exception.
+ *
  */
 static inline int gru_wait(void *cb)
 {
-	struct gru_control_block_status *cbs = (void *)cb;
-	int ret = cbs->istatus;
-
-	if (ret != CBS_IDLE)
-		ret = gru_wait_proc(cb);
-	return ret;
+	return gru_wait_proc(cb);
 }
 
-/* Wait for CB to complete. Aborts program if error. (Note: error does NOT
+/*
+ * Wait for CB to complete. Aborts program if error. (Note: error does NOT
  * mean TLB mis - only fatal errors such as memory parity error or user
  * bugs will cause termination.
  */
 static inline void gru_wait_abort(void *cb)
 {
-	struct gru_control_block_status *cbs = (void *)cb;
-
-	if (cbs->istatus != CBS_IDLE)
-		gru_wait_abort_proc(cb);
+	gru_wait_abort_proc(cb);
 }
 
 
diff --git a/drivers/misc/sgi-gru/grufault.c b/drivers/misc/sgi-gru/grufault.c
index ab11855..679e017 100644
--- a/drivers/misc/sgi-gru/grufault.c
+++ b/drivers/misc/sgi-gru/grufault.c
@@ -166,7 +166,8 @@
  * the GRU, atomic operations must be used to clear bits.
  */
 static void get_clear_fault_map(struct gru_state *gru,
-				struct gru_tlb_fault_map *map)
+				struct gru_tlb_fault_map *imap,
+				struct gru_tlb_fault_map *dmap)
 {
 	unsigned long i, k;
 	struct gru_tlb_fault_map *tfm;
@@ -177,7 +178,11 @@
 		k = tfm->fault_bits[i];
 		if (k)
 			k = xchg(&tfm->fault_bits[i], 0UL);
-		map->fault_bits[i] = k;
+		imap->fault_bits[i] = k;
+		k = tfm->done_bits[i];
+		if (k)
+			k = xchg(&tfm->done_bits[i], 0UL);
+		dmap->fault_bits[i] = k;
 	}
 
 	/*
@@ -334,6 +339,12 @@
 	 * Might be a hardware race OR a stupid user. Ignore FMM because FMM
 	 * is a transient state.
 	 */
+	if (tfh->status != TFHSTATUS_EXCEPTION) {
+		gru_flush_cache(tfh);
+		if (tfh->status != TFHSTATUS_EXCEPTION)
+			goto failnoexception;
+		STAT(tfh_stale_on_fault);
+	}
 	if (tfh->state == TFHSTATE_IDLE)
 		goto failidle;
 	if (tfh->state == TFHSTATE_MISS_FMM && cb)
@@ -401,8 +412,17 @@
 	gru_dbg(grudev, "FAILED fmm tfh: 0x%p, state %d\n", tfh, tfh->state);
 	return 0;
 
+failnoexception:
+	/* TFH status did not show exception pending */
+	gru_flush_cache(tfh);
+	if (cb)
+		gru_flush_cache(cb);
+	STAT(tlb_dropin_fail_no_exception);
+	gru_dbg(grudev, "FAILED non-exception tfh: 0x%p, status %d, state %d\n", tfh, tfh->status, tfh->state);
+	return 0;
+
 failidle:
-	/* TFH was idle  - no miss pending */
+	/* TFH state was idle  - no miss pending */
 	gru_flush_cache(tfh);
 	if (cb)
 		gru_flush_cache(cb);
@@ -438,7 +458,7 @@
 irqreturn_t gru_intr(int irq, void *dev_id)
 {
 	struct gru_state *gru;
-	struct gru_tlb_fault_map map;
+	struct gru_tlb_fault_map imap, dmap;
 	struct gru_thread_state *gts;
 	struct gru_tlb_fault_handle *tfh = NULL;
 	int cbrnum, ctxnum;
@@ -451,11 +471,15 @@
 			raw_smp_processor_id(), irq);
 		return IRQ_NONE;
 	}
-	get_clear_fault_map(gru, &map);
-	gru_dbg(grudev, "irq %d, gru %x, map 0x%lx\n", irq, gru->gs_gid,
-		map.fault_bits[0]);
+	get_clear_fault_map(gru, &imap, &dmap);
 
-	for_each_cbr_in_tfm(cbrnum, map.fault_bits) {
+	for_each_cbr_in_tfm(cbrnum, dmap.fault_bits) {
+		complete(gru->gs_blade->bs_async_wq);
+		gru_dbg(grudev, "gid %d, cbr_done %d, done %d\n",
+			gru->gs_gid, cbrnum, gru->gs_blade->bs_async_wq->done);
+	}
+
+	for_each_cbr_in_tfm(cbrnum, imap.fault_bits) {
 		tfh = get_tfh_by_index(gru, cbrnum);
 		prefetchw(tfh);	/* Helps on hdw, required for emulator */
 
@@ -472,7 +496,9 @@
 		 * This is running in interrupt context. Trylock the mmap_sem.
 		 * If it fails, retry the fault in user context.
 		 */
-		if (down_read_trylock(&gts->ts_mm->mmap_sem)) {
+		if (!gts->ts_force_cch_reload &&
+					down_read_trylock(&gts->ts_mm->mmap_sem)) {
+			gts->ustats.fmm_tlbdropin++;
 			gru_try_dropin(gts, tfh, NULL);
 			up_read(&gts->ts_mm->mmap_sem);
 		} else {
@@ -491,6 +517,7 @@
 	struct gru_mm_struct *gms = gts->ts_gms;
 	int ret;
 
+	gts->ustats.upm_tlbdropin++;
 	while (1) {
 		wait_event(gms->ms_wait_queue,
 			   atomic_read(&gms->ms_range_active) == 0);
@@ -546,8 +573,8 @@
 	 * CCH may contain stale data if ts_force_cch_reload is set.
 	 */
 	if (gts->ts_gru && gts->ts_force_cch_reload) {
-		gru_update_cch(gts, 0);
 		gts->ts_force_cch_reload = 0;
+		gru_update_cch(gts, 0);
 	}
 
 	ret = -EAGAIN;
@@ -589,20 +616,26 @@
 	} else if (gts->ts_gru) {
 		cbrnum = thread_cbr_number(gts, ucbnum);
 		cbe = get_cbe_by_index(gts->ts_gru, cbrnum);
-		prefetchw(cbe);/* Harmless on hardware, required for emulator */
+		gru_flush_cache(cbe);	/* CBE not coherent */
 		excdet.opc = cbe->opccpy;
 		excdet.exopc = cbe->exopccpy;
 		excdet.ecause = cbe->ecause;
 		excdet.exceptdet0 = cbe->idef1upd;
 		excdet.exceptdet1 = cbe->idef3upd;
+		excdet.cbrstate = cbe->cbrstate;
+		excdet.cbrexecstatus = cbe->cbrexecstatus;
+		gru_flush_cache(cbe);
 		ret = 0;
 	} else {
 		ret = -EAGAIN;
 	}
 	gru_unlock_gts(gts);
 
-	gru_dbg(grudev, "address 0x%lx, ecause 0x%x\n", excdet.cb,
-		excdet.ecause);
+	gru_dbg(grudev,
+		"cb 0x%lx, op %d, exopc %d, cbrstate %d, cbrexecstatus 0x%x, ecause 0x%x, "
+		"exdet0 0x%lx, exdet1 0x%x\n",
+		excdet.cb, excdet.opc, excdet.exopc, excdet.cbrstate, excdet.cbrexecstatus,
+		excdet.ecause, excdet.exceptdet0, excdet.exceptdet1);
 	if (!ret && copy_to_user((void __user *)arg, &excdet, sizeof(excdet)))
 		ret = -EFAULT;
 	return ret;
@@ -627,7 +660,7 @@
 			if (gts && mutex_trylock(&gts->ts_ctxlock)) {
 				spin_unlock(&gru->gs_lock);
 				gru_unload_context(gts, 1);
-				gru_unlock_gts(gts);
+				mutex_unlock(&gts->ts_ctxlock);
 				spin_lock(&gru->gs_lock);
 			}
 		}
@@ -669,6 +702,7 @@
 {
 	struct gru_thread_state *gts;
 	struct gru_flush_tlb_req req;
+	struct gru_mm_struct *gms;
 
 	STAT(user_flush_tlb);
 	if (copy_from_user(&req, (void __user *)arg, sizeof(req)))
@@ -681,8 +715,34 @@
 	if (!gts)
 		return -EINVAL;
 
-	gru_flush_tlb_range(gts->ts_gms, req.vaddr, req.len);
+	gms = gts->ts_gms;
 	gru_unlock_gts(gts);
+	gru_flush_tlb_range(gms, req.vaddr, req.len);
+
+	return 0;
+}
+
+/*
+ * Fetch GSEG statisticss
+ */
+long gru_get_gseg_statistics(unsigned long arg)
+{
+	struct gru_thread_state *gts;
+	struct gru_get_gseg_statistics_req req;
+
+	if (copy_from_user(&req, (void __user *)arg, sizeof(req)))
+		return -EFAULT;
+
+	gts = gru_find_lock_gts(req.gseg);
+	if (gts) {
+		memcpy(&req.stats, &gts->ustats, sizeof(gts->ustats));
+		gru_unlock_gts(gts);
+	} else {
+		memset(&req.stats, 0, sizeof(gts->ustats));
+	}
+
+	if (copy_to_user((void __user *)arg, &req, sizeof(req)))
+		return -EFAULT;
 
 	return 0;
 }
@@ -691,18 +751,34 @@
  * Register the current task as the user of the GSEG slice.
  * Needed for TLB fault interrupt targeting.
  */
-int gru_set_task_slice(long address)
+int gru_set_context_option(unsigned long arg)
 {
 	struct gru_thread_state *gts;
+	struct gru_set_context_option_req req;
+	int ret = 0;
 
-	STAT(set_task_slice);
-	gru_dbg(grudev, "address 0x%lx\n", address);
-	gts = gru_alloc_locked_gts(address);
+	STAT(set_context_option);
+	if (copy_from_user(&req, (void __user *)arg, sizeof(req)))
+		return -EFAULT;
+	gru_dbg(grudev, "op %d, gseg 0x%lx, value1 0x%lx\n", req.op, req.gseg, req.val1);
+
+	gts = gru_alloc_locked_gts(req.gseg);
 	if (!gts)
 		return -EINVAL;
 
-	gts->ts_tgid_owner = current->tgid;
+	switch (req.op) {
+	case sco_gseg_owner:
+ 		/* Register the current task as the GSEG owner */
+		gts->ts_tgid_owner = current->tgid;
+		break;
+	case sco_cch_req_slice:
+ 		/* Set the CCH slice option */
+		gts->ts_cch_req_slice = req.val1 & 3;
+		break;
+	default:
+		ret = -EINVAL;
+	}
 	gru_unlock_gts(gts);
 
-	return 0;
+	return ret;
 }
diff --git a/drivers/misc/sgi-gru/grufile.c b/drivers/misc/sgi-gru/grufile.c
index 3ce2920..fa2d93a 100644
--- a/drivers/misc/sgi-gru/grufile.c
+++ b/drivers/misc/sgi-gru/grufile.c
@@ -46,6 +46,7 @@
 
 struct gru_blade_state *gru_base[GRU_MAX_BLADES] __read_mostly;
 unsigned long gru_start_paddr __read_mostly;
+void *gru_start_vaddr __read_mostly;
 unsigned long gru_end_paddr __read_mostly;
 unsigned int gru_max_gids __read_mostly;
 struct gru_stats_s gru_stats;
@@ -135,11 +136,9 @@
 	if (copy_from_user(&req, (void __user *)arg, sizeof(req)))
 		return -EFAULT;
 
-	if (req.data_segment_bytes == 0 ||
-				req.data_segment_bytes > max_user_dsr_bytes)
+	if (req.data_segment_bytes > max_user_dsr_bytes)
 		return -EINVAL;
-	if (!req.control_blocks || !req.maximum_thread_count ||
-				req.control_blocks > max_user_cbrs)
+	if (req.control_blocks > max_user_cbrs || !req.maximum_thread_count)
 		return -EINVAL;
 
 	if (!(req.options & GRU_OPT_MISS_MASK))
@@ -184,41 +183,6 @@
 }
 
 /*
- * Get GRU chiplet status
- */
-static long gru_get_chiplet_status(unsigned long arg)
-{
-	struct gru_state *gru;
-	struct gru_chiplet_info info;
-
-	if (copy_from_user(&info, (void __user *)arg, sizeof(info)))
-		return -EFAULT;
-
-	if (info.node == -1)
-		info.node = numa_node_id();
-	if (info.node >= num_possible_nodes() ||
-			info.chiplet >= GRU_CHIPLETS_PER_HUB ||
-			info.node < 0 || info.chiplet < 0)
-		return -EINVAL;
-
-	info.blade = uv_node_to_blade_id(info.node);
-	gru = get_gru(info.blade, info.chiplet);
-
-	info.total_dsr_bytes = GRU_NUM_DSR_BYTES;
-	info.total_cbr = GRU_NUM_CB;
-	info.total_user_dsr_bytes = GRU_NUM_DSR_BYTES -
-		gru->gs_reserved_dsr_bytes;
-	info.total_user_cbr = GRU_NUM_CB - gru->gs_reserved_cbrs;
-	info.free_user_dsr_bytes = hweight64(gru->gs_dsr_map) *
-			GRU_DSR_AU_BYTES;
-	info.free_user_cbr = hweight64(gru->gs_cbr_map) * GRU_CBR_AU_SIZE;
-
-	if (copy_to_user((void __user *)arg, &info, sizeof(info)))
-		return -EFAULT;
-	return 0;
-}
-
-/*
  * gru_file_unlocked_ioctl
  *
  * Called to update file attributes via IOCTL calls.
@@ -234,8 +198,8 @@
 	case GRU_CREATE_CONTEXT:
 		err = gru_create_new_context(arg);
 		break;
-	case GRU_SET_TASK_SLICE:
-		err = gru_set_task_slice(arg);
+	case GRU_SET_CONTEXT_OPTION:
+		err = gru_set_context_option(arg);
 		break;
 	case GRU_USER_GET_EXCEPTION_DETAIL:
 		err = gru_get_exception_detail(arg);
@@ -243,18 +207,24 @@
 	case GRU_USER_UNLOAD_CONTEXT:
 		err = gru_user_unload_context(arg);
 		break;
-	case GRU_GET_CHIPLET_STATUS:
-		err = gru_get_chiplet_status(arg);
-		break;
 	case GRU_USER_FLUSH_TLB:
 		err = gru_user_flush_tlb(arg);
 		break;
 	case GRU_USER_CALL_OS:
 		err = gru_handle_user_call_os(arg);
 		break;
+	case GRU_GET_GSEG_STATISTICS:
+		err = gru_get_gseg_statistics(arg);
+		break;
+	case GRU_KTEST:
+		err = gru_ktest(arg);
+		break;
 	case GRU_GET_CONFIG_INFO:
 		err = gru_get_config_info(arg);
 		break;
+	case GRU_DUMP_CHIPLET_STATE:
+		err = gru_dump_chiplet_request(arg);
+		break;
 	}
 	return err;
 }
@@ -282,7 +252,6 @@
 	gru_dbg(grudev, "bid %d, nid %d, gid %d, vaddr %p (0x%lx)\n",
 		bid, nid, gru->gs_gid, gru->gs_gru_base_vaddr,
 		gru->gs_gru_base_paddr);
-	gru_kservices_init(gru);
 }
 
 static int gru_init_tables(unsigned long gru_base_paddr, void *gru_base_vaddr)
@@ -309,6 +278,7 @@
 		memset(gru_base[bid], 0, sizeof(struct gru_blade_state));
 		gru_base[bid]->bs_lru_gru = &gru_base[bid]->bs_grus[0];
 		spin_lock_init(&gru_base[bid]->bs_lock);
+		init_rwsem(&gru_base[bid]->bs_kgts_sema);
 
 		dsrbytes = 0;
 		cbrs = 0;
@@ -372,7 +342,6 @@
 {
 	int ret, irq, chip;
 	char id[10];
-	void *gru_start_vaddr;
 
 	if (!is_uv_system())
 		return 0;
@@ -422,6 +391,7 @@
 		printk(KERN_ERR "%s: init tables failed\n", GRU_DRIVER_ID_STR);
 		goto exit3;
 	}
+	gru_kservices_init();
 
 	printk(KERN_INFO "%s: v%s\n", GRU_DRIVER_ID_STR,
 	       GRU_DRIVER_VERSION_STR);
@@ -440,7 +410,7 @@
 
 static void __exit gru_exit(void)
 {
-	int i, bid, gid;
+	int i, bid;
 	int order = get_order(sizeof(struct gru_state) *
 			      GRU_CHIPLETS_PER_BLADE);
 
@@ -449,10 +419,7 @@
 
 	for (i = 0; i < GRU_CHIPLETS_PER_BLADE; i++)
 		free_irq(IRQ_GRU + i, NULL);
-
-	foreach_gid(gid)
-		gru_kservices_exit(GID_TO_GRU(gid));
-
+	gru_kservices_exit();
 	for (bid = 0; bid < GRU_MAX_BLADES; bid++)
 		free_pages((unsigned long)gru_base[bid], order);
 
diff --git a/drivers/misc/sgi-gru/gruhandles.c b/drivers/misc/sgi-gru/gruhandles.c
index 9b7ccb3..37e7cfc 100644
--- a/drivers/misc/sgi-gru/gruhandles.c
+++ b/drivers/misc/sgi-gru/gruhandles.c
@@ -57,7 +57,7 @@
 static int wait_instruction_complete(void *h, enum mcs_op opc)
 {
 	int status;
-	cycles_t start_time = get_cycles();
+	unsigned long start_time = get_cycles();
 
 	while (1) {
 		cpu_relax();
@@ -65,25 +65,16 @@
 		if (status != CCHSTATUS_ACTIVE)
 			break;
 		if (GRU_OPERATION_TIMEOUT < (get_cycles() - start_time))
-			panic("GRU %p is malfunctioning\n", h);
+			panic("GRU %p is malfunctioning: start %ld, end %ld\n",
+			      h, start_time, (unsigned long)get_cycles());
 	}
 	if (gru_options & OPT_STATS)
 		update_mcs_stats(opc, get_cycles() - start_time);
 	return status;
 }
 
-int cch_allocate(struct gru_context_configuration_handle *cch,
-		int asidval, int sizeavail, unsigned long cbrmap,
-		unsigned long dsrmap)
+int cch_allocate(struct gru_context_configuration_handle *cch)
 {
-	int i;
-
-	for (i = 0; i < 8; i++) {
-		cch->asid[i] = (asidval++);
-		cch->sizeavail[i] = sizeavail;
-	}
-	cch->dsr_allocation_map = dsrmap;
-	cch->cbr_allocation_map = cbrmap;
 	cch->opc = CCHOP_ALLOCATE;
 	start_instruction(cch);
 	return wait_instruction_complete(cch, cchop_allocate);
diff --git a/drivers/misc/sgi-gru/gruhandles.h b/drivers/misc/sgi-gru/gruhandles.h
index 1ed74d7..f441122 100644
--- a/drivers/misc/sgi-gru/gruhandles.h
+++ b/drivers/misc/sgi-gru/gruhandles.h
@@ -39,7 +39,6 @@
 #define GRU_NUM_CBE		128
 #define GRU_NUM_TFH		128
 #define GRU_NUM_CCH		16
-#define GRU_NUM_GSH		1
 
 /* Maximum resource counts that can be reserved by user programs */
 #define GRU_NUM_USER_CBR	GRU_NUM_CBE
@@ -56,7 +55,6 @@
 #define GRU_CBE_BASE		(GRU_MCS_BASE + 0x10000)
 #define GRU_TFH_BASE		(GRU_MCS_BASE + 0x18000)
 #define GRU_CCH_BASE		(GRU_MCS_BASE + 0x20000)
-#define GRU_GSH_BASE		(GRU_MCS_BASE + 0x30000)
 
 /* User gseg constants */
 #define GRU_GSEG_STRIDE		(4 * 1024 * 1024)
@@ -251,15 +249,15 @@
 	unsigned int fill1:9;
 
 	unsigned int status:2;
-	unsigned int fill2:1;
-	unsigned int color:1;
+	unsigned int fill2:2;
 	unsigned int state:3;
 	unsigned int fill3:1;
 
-	unsigned int cause:7;		/* DW 0 - high 32 */
+	unsigned int cause:6;
+	unsigned int cb_int:1;
 	unsigned int fill4:1;
 
-	unsigned int indexway:12;
+	unsigned int indexway:12;	/* DW 0 - high 32 */
 	unsigned int fill5:4;
 
 	unsigned int ctxnum:4;
@@ -457,21 +455,7 @@
 	CBRSTATE_BUSY_INTERRUPT,
 };
 
-/* CBE cbrexecstatus bits */
-#define CBR_EXS_ABORT_OCC_BIT			0
-#define CBR_EXS_INT_OCC_BIT			1
-#define CBR_EXS_PENDING_BIT			2
-#define CBR_EXS_QUEUED_BIT			3
-#define CBR_EXS_TLBHW_BIT			4
-#define CBR_EXS_EXCEPTION_BIT			5
-
-#define CBR_EXS_ABORT_OCC			(1 << CBR_EXS_ABORT_OCC_BIT)
-#define CBR_EXS_INT_OCC				(1 << CBR_EXS_INT_OCC_BIT)
-#define CBR_EXS_PENDING				(1 << CBR_EXS_PENDING_BIT)
-#define CBR_EXS_QUEUED				(1 << CBR_EXS_QUEUED_BIT)
-#define CBR_EXS_TLBHW				(1 << CBR_EXS_TLBHW_BIT)
-#define CBR_EXS_EXCEPTION			(1 << CBR_EXS_EXCEPTION_BIT)
-
+/* CBE cbrexecstatus bits  - defined in gru_instructions.h*/
 /* CBE ecause bits  - defined in gru_instructions.h */
 
 /*
@@ -495,9 +479,7 @@
 /* minimum TLB purge count to ensure a full purge */
 #define GRUMAXINVAL		1024UL
 
-int cch_allocate(struct gru_context_configuration_handle *cch,
-       int asidval, int sizeavail, unsigned long cbrmap, unsigned long dsrmap);
-
+int cch_allocate(struct gru_context_configuration_handle *cch);
 int cch_start(struct gru_context_configuration_handle *cch);
 int cch_interrupt(struct gru_context_configuration_handle *cch);
 int cch_deallocate(struct gru_context_configuration_handle *cch);
diff --git a/drivers/misc/sgi-gru/grukdump.c b/drivers/misc/sgi-gru/grukdump.c
new file mode 100644
index 0000000..55eabfa
--- /dev/null
+++ b/drivers/misc/sgi-gru/grukdump.c
@@ -0,0 +1,232 @@
+/*
+ * SN Platform GRU Driver
+ *
+ *            Dump GRU State
+ *
+ *  Copyright (c) 2008 Silicon Graphics, Inc.  All Rights Reserved.
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+ */
+
+#include <linux/kernel.h>
+#include <linux/mm.h>
+#include <linux/spinlock.h>
+#include <linux/uaccess.h>
+#include <linux/delay.h>
+#include <linux/bitops.h>
+#include <asm/uv/uv_hub.h>
+#include "gru.h"
+#include "grutables.h"
+#include "gruhandles.h"
+#include "grulib.h"
+
+#define CCH_LOCK_ATTEMPTS	10
+
+static int gru_user_copy_handle(void __user **dp, void *s)
+{
+	if (copy_to_user(*dp, s, GRU_HANDLE_BYTES))
+		return -1;
+	*dp += GRU_HANDLE_BYTES;
+	return 0;
+}
+
+static int gru_dump_context_data(void *grubase,
+			struct gru_context_configuration_handle *cch,
+			void __user *ubuf, int ctxnum, int dsrcnt)
+{
+	void *cb, *cbe, *tfh, *gseg;
+	int i, scr;
+
+	gseg = grubase + ctxnum * GRU_GSEG_STRIDE;
+	cb = gseg + GRU_CB_BASE;
+	cbe = grubase + GRU_CBE_BASE;
+	tfh = grubase + GRU_TFH_BASE;
+
+	for_each_cbr_in_allocation_map(i, &cch->cbr_allocation_map, scr) {
+		if (gru_user_copy_handle(&ubuf, cb))
+			goto fail;
+		if (gru_user_copy_handle(&ubuf, tfh + i * GRU_HANDLE_STRIDE))
+			goto fail;
+		if (gru_user_copy_handle(&ubuf, cbe + i * GRU_HANDLE_STRIDE))
+			goto fail;
+		cb += GRU_HANDLE_STRIDE;
+	}
+	if (dsrcnt)
+		memcpy(ubuf, gseg + GRU_DS_BASE, dsrcnt * GRU_HANDLE_STRIDE);
+	return 0;
+
+fail:
+	return -EFAULT;
+}
+
+static int gru_dump_tfm(struct gru_state *gru,
+		void __user *ubuf, void __user *ubufend)
+{
+	struct gru_tlb_fault_map *tfm;
+	int i, ret, bytes;
+
+	bytes = GRU_NUM_TFM * GRU_CACHE_LINE_BYTES;
+	if (bytes > ubufend - ubuf)
+		ret = -EFBIG;
+
+	for (i = 0; i < GRU_NUM_TFM; i++) {
+		tfm = get_tfm(gru->gs_gru_base_vaddr, i);
+		if (gru_user_copy_handle(&ubuf, tfm))
+			goto fail;
+	}
+	return GRU_NUM_TFM * GRU_CACHE_LINE_BYTES;
+
+fail:
+	return -EFAULT;
+}
+
+static int gru_dump_tgh(struct gru_state *gru,
+		void __user *ubuf, void __user *ubufend)
+{
+	struct gru_tlb_global_handle *tgh;
+	int i, ret, bytes;
+
+	bytes = GRU_NUM_TGH * GRU_CACHE_LINE_BYTES;
+	if (bytes > ubufend - ubuf)
+		ret = -EFBIG;
+
+	for (i = 0; i < GRU_NUM_TGH; i++) {
+		tgh = get_tgh(gru->gs_gru_base_vaddr, i);
+		if (gru_user_copy_handle(&ubuf, tgh))
+			goto fail;
+	}
+	return GRU_NUM_TGH * GRU_CACHE_LINE_BYTES;
+
+fail:
+	return -EFAULT;
+}
+
+static int gru_dump_context(struct gru_state *gru, int ctxnum,
+		void __user *ubuf, void __user *ubufend, char data_opt,
+		char lock_cch)
+{
+	struct gru_dump_context_header hdr;
+	struct gru_dump_context_header __user *uhdr = ubuf;
+	struct gru_context_configuration_handle *cch, *ubufcch;
+	struct gru_thread_state *gts;
+	int try, cch_locked, cbrcnt = 0, dsrcnt = 0, bytes = 0, ret = 0;
+	void *grubase;
+
+	memset(&hdr, 0, sizeof(hdr));
+	grubase = gru->gs_gru_base_vaddr;
+	cch = get_cch(grubase, ctxnum);
+	for (try = 0; try < CCH_LOCK_ATTEMPTS; try++) {
+		cch_locked =  trylock_cch_handle(cch);
+		if (cch_locked)
+			break;
+		msleep(1);
+	}
+
+	ubuf += sizeof(hdr);
+	ubufcch = ubuf;
+	if (gru_user_copy_handle(&ubuf, cch))
+		goto fail;
+	if (cch_locked)
+		ubufcch->delresp = 0;
+	bytes = sizeof(hdr) + GRU_CACHE_LINE_BYTES;
+
+	if (cch_locked || !lock_cch) {
+		gts = gru->gs_gts[ctxnum];
+		if (gts && gts->ts_vma) {
+			hdr.pid = gts->ts_tgid_owner;
+			hdr.vaddr = gts->ts_vma->vm_start;
+		}
+		if (cch->state != CCHSTATE_INACTIVE) {
+			cbrcnt = hweight64(cch->cbr_allocation_map) *
+						GRU_CBR_AU_SIZE;
+			dsrcnt = data_opt ? hweight32(cch->dsr_allocation_map) *
+						GRU_DSR_AU_CL : 0;
+		}
+		bytes += (3 * cbrcnt + dsrcnt) * GRU_CACHE_LINE_BYTES;
+		if (bytes > ubufend - ubuf)
+			ret = -EFBIG;
+		else
+			ret = gru_dump_context_data(grubase, cch, ubuf, ctxnum,
+							dsrcnt);
+
+	}
+	if (cch_locked)
+		unlock_cch_handle(cch);
+	if (ret)
+		return ret;
+
+	hdr.magic = GRU_DUMP_MAGIC;
+	hdr.gid = gru->gs_gid;
+	hdr.ctxnum = ctxnum;
+	hdr.cbrcnt = cbrcnt;
+	hdr.dsrcnt = dsrcnt;
+	hdr.cch_locked = cch_locked;
+	if (!ret && copy_to_user((void __user *)uhdr, &hdr, sizeof(hdr)))
+		ret = -EFAULT;
+
+	return ret ? ret : bytes;
+
+fail:
+	unlock_cch_handle(cch);
+	return -EFAULT;
+}
+
+int gru_dump_chiplet_request(unsigned long arg)
+{
+	struct gru_state *gru;
+	struct gru_dump_chiplet_state_req req;
+	void __user *ubuf;
+	void __user *ubufend;
+	int ctxnum, ret, cnt = 0;
+
+	if (copy_from_user(&req, (void __user *)arg, sizeof(req)))
+		return -EFAULT;
+
+	/* Currently, only dump by gid is implemented */
+	if (req.gid >= gru_max_gids || req.gid < 0)
+		return -EINVAL;
+
+	gru = GID_TO_GRU(req.gid);
+	ubuf = req.buf;
+	ubufend = req.buf + req.buflen;
+
+	ret = gru_dump_tfm(gru, ubuf, ubufend);
+	if (ret < 0)
+		goto fail;
+	ubuf += ret;
+
+	ret = gru_dump_tgh(gru, ubuf, ubufend);
+	if (ret < 0)
+		goto fail;
+	ubuf += ret;
+
+	for (ctxnum = 0; ctxnum < GRU_NUM_CCH; ctxnum++) {
+		if (req.ctxnum == ctxnum || req.ctxnum < 0) {
+			ret = gru_dump_context(gru, ctxnum, ubuf, ubufend,
+						req.data_opt, req.lock_cch);
+			if (ret < 0)
+				goto fail;
+			ubuf += ret;
+			cnt++;
+		}
+	}
+
+	if (copy_to_user((void __user *)arg, &req, sizeof(req)))
+		return -EFAULT;
+	return cnt;
+
+fail:
+	return ret;
+}
diff --git a/drivers/misc/sgi-gru/grukservices.c b/drivers/misc/sgi-gru/grukservices.c
index d8bd7d8..eedbf9c 100644
--- a/drivers/misc/sgi-gru/grukservices.c
+++ b/drivers/misc/sgi-gru/grukservices.c
@@ -31,6 +31,7 @@
 #include <linux/proc_fs.h>
 #include <linux/interrupt.h>
 #include <linux/uaccess.h>
+#include <linux/delay.h>
 #include "gru.h"
 #include "grulib.h"
 #include "grutables.h"
@@ -45,18 +46,66 @@
  * resources. This will likely be replaced when we better understand the
  * kernel/user requirements.
  *
- * At boot time, the kernel permanently reserves a fixed number of
- * CBRs/DSRs for each cpu to use. The resources are all taken from
- * the GRU chiplet 1 on the blade. This leaves the full set of resources
- * of chiplet 0 available to be allocated to a single user.
+ * Blade percpu resources reserved for kernel use. These resources are
+ * reserved whenever the the kernel context for the blade is loaded. Note
+ * that the kernel context is not guaranteed to be always available. It is
+ * loaded on demand & can be stolen by a user if the user demand exceeds the
+ * kernel demand. The kernel can always reload the kernel context but
+ * a SLEEP may be required!!!.
+ *
+ * Async Overview:
+ *
+ * 	Each blade has one "kernel context" that owns GRU kernel resources
+ * 	located on the blade. Kernel drivers use GRU resources in this context
+ * 	for sending messages, zeroing memory, etc.
+ *
+ * 	The kernel context is dynamically loaded on demand. If it is not in
+ * 	use by the kernel, the kernel context can be unloaded & given to a user.
+ * 	The kernel context will be reloaded when needed. This may require that
+ * 	a context be stolen from a user.
+ * 		NOTE: frequent unloading/reloading of the kernel context is
+ * 		expensive. We are depending on batch schedulers, cpusets, sane
+ * 		drivers or some other mechanism to prevent the need for frequent
+ *	 	stealing/reloading.
+ *
+ * 	The kernel context consists of two parts:
+ * 		- 1 CB & a few DSRs that are reserved for each cpu on the blade.
+ * 		  Each cpu has it's own private resources & does not share them
+ * 		  with other cpus. These resources are used serially, ie,
+ * 		  locked, used & unlocked  on each call to a function in
+ * 		  grukservices.
+ * 		  	(Now that we have dynamic loading of kernel contexts, I
+ * 		  	 may rethink this & allow sharing between cpus....)
+ *
+ *		- Additional resources can be reserved long term & used directly
+ *		  by UV drivers located in the kernel. Drivers using these GRU
+ *		  resources can use asynchronous GRU instructions that send
+ *		  interrupts on completion.
+ *		  	- these resources must be explicitly locked/unlocked
+ *		  	- locked resources prevent (obviously) the kernel
+ *		  	  context from being unloaded.
+ *			- drivers using these resource directly issue their own
+ *			  GRU instruction and must wait/check completion.
+ *
+ * 		  When these resources are reserved, the caller can optionally
+ * 		  associate a wait_queue with the resources and use asynchronous
+ * 		  GRU instructions. When an async GRU instruction completes, the
+ * 		  driver will do a wakeup on the event.
+ *
  */
 
-/* Blade percpu resources PERMANENTLY reserved for kernel use */
+
+#define ASYNC_HAN_TO_BID(h)	((h) - 1)
+#define ASYNC_BID_TO_HAN(b)	((b) + 1)
+#define ASYNC_HAN_TO_BS(h)	gru_base[ASYNC_HAN_TO_BID(h)]
+#define KCB_TO_GID(cb)		((cb - gru_start_vaddr) /		\
+					(GRU_SIZE * GRU_CHIPLETS_PER_BLADE))
+#define KCB_TO_BS(cb)		gru_base[KCB_TO_GID(cb)]
+
 #define GRU_NUM_KERNEL_CBR	1
 #define GRU_NUM_KERNEL_DSR_BYTES 256
 #define GRU_NUM_KERNEL_DSR_CL	(GRU_NUM_KERNEL_DSR_BYTES /		\
 					GRU_CACHE_LINE_BYTES)
-#define KERNEL_CTXNUM           15
 
 /* GRU instruction attributes for all instructions */
 #define IMA			IMA_CB_DELAY
@@ -98,6 +147,108 @@
 
 #define HSTATUS(mq, h)	((mq) + offsetof(struct message_queue, hstatus[h]))
 
+/*
+ * Reload the blade's kernel context into a GRU chiplet. Called holding
+ * the bs_kgts_sema for READ. Will steal user contexts if necessary.
+ */
+static void gru_load_kernel_context(struct gru_blade_state *bs, int blade_id)
+{
+	struct gru_state *gru;
+	struct gru_thread_state *kgts;
+	void *vaddr;
+	int ctxnum, ncpus;
+
+	up_read(&bs->bs_kgts_sema);
+	down_write(&bs->bs_kgts_sema);
+
+	if (!bs->bs_kgts)
+		bs->bs_kgts = gru_alloc_gts(NULL, 0, 0, 0, 0);
+	kgts = bs->bs_kgts;
+
+	if (!kgts->ts_gru) {
+		STAT(load_kernel_context);
+		ncpus = uv_blade_nr_possible_cpus(blade_id);
+		kgts->ts_cbr_au_count = GRU_CB_COUNT_TO_AU(
+			GRU_NUM_KERNEL_CBR * ncpus + bs->bs_async_cbrs);
+		kgts->ts_dsr_au_count = GRU_DS_BYTES_TO_AU(
+			GRU_NUM_KERNEL_DSR_BYTES * ncpus +
+				bs->bs_async_dsr_bytes);
+		while (!gru_assign_gru_context(kgts, blade_id)) {
+			msleep(1);
+			gru_steal_context(kgts, blade_id);
+		}
+		gru_load_context(kgts);
+		gru = bs->bs_kgts->ts_gru;
+		vaddr = gru->gs_gru_base_vaddr;
+		ctxnum = kgts->ts_ctxnum;
+		bs->kernel_cb = get_gseg_base_address_cb(vaddr, ctxnum, 0);
+		bs->kernel_dsr = get_gseg_base_address_ds(vaddr, ctxnum, 0);
+	}
+	downgrade_write(&bs->bs_kgts_sema);
+}
+
+/*
+ * Free all kernel contexts that are not currently in use.
+ *   Returns 0 if all freed, else number of inuse context.
+ */
+static int gru_free_kernel_contexts(void)
+{
+	struct gru_blade_state *bs;
+	struct gru_thread_state *kgts;
+	int bid, ret = 0;
+
+	for (bid = 0; bid < GRU_MAX_BLADES; bid++) {
+		bs = gru_base[bid];
+		if (!bs)
+			continue;
+		if (down_write_trylock(&bs->bs_kgts_sema)) {
+			kgts = bs->bs_kgts;
+			if (kgts && kgts->ts_gru)
+				gru_unload_context(kgts, 0);
+			kfree(kgts);
+			bs->bs_kgts = NULL;
+			up_write(&bs->bs_kgts_sema);
+		} else {
+			ret++;
+		}
+	}
+	return ret;
+}
+
+/*
+ * Lock & load the kernel context for the specified blade.
+ */
+static struct gru_blade_state *gru_lock_kernel_context(int blade_id)
+{
+	struct gru_blade_state *bs;
+
+	STAT(lock_kernel_context);
+	bs = gru_base[blade_id];
+
+	down_read(&bs->bs_kgts_sema);
+	if (!bs->bs_kgts || !bs->bs_kgts->ts_gru)
+		gru_load_kernel_context(bs, blade_id);
+	return bs;
+
+}
+
+/*
+ * Unlock the kernel context for the specified blade. Context is not
+ * unloaded but may be stolen before next use.
+ */
+static void gru_unlock_kernel_context(int blade_id)
+{
+	struct gru_blade_state *bs;
+
+	bs = gru_base[blade_id];
+	up_read(&bs->bs_kgts_sema);
+	STAT(unlock_kernel_context);
+}
+
+/*
+ * Reserve & get pointers to the DSR/CBRs reserved for the current cpu.
+ * 	- returns with preemption disabled
+ */
 static int gru_get_cpu_resources(int dsr_bytes, void **cb, void **dsr)
 {
 	struct gru_blade_state *bs;
@@ -105,30 +256,148 @@
 
 	BUG_ON(dsr_bytes > GRU_NUM_KERNEL_DSR_BYTES);
 	preempt_disable();
-	bs = gru_base[uv_numa_blade_id()];
+	bs = gru_lock_kernel_context(uv_numa_blade_id());
 	lcpu = uv_blade_processor_id();
 	*cb = bs->kernel_cb + lcpu * GRU_HANDLE_STRIDE;
 	*dsr = bs->kernel_dsr + lcpu * GRU_NUM_KERNEL_DSR_BYTES;
 	return 0;
 }
 
+/*
+ * Free the current cpus reserved DSR/CBR resources.
+ */
 static void gru_free_cpu_resources(void *cb, void *dsr)
 {
+	gru_unlock_kernel_context(uv_numa_blade_id());
 	preempt_enable();
 }
 
+/*
+ * Reserve GRU resources to be used asynchronously.
+ *   Note: currently supports only 1 reservation per blade.
+ *
+ * 	input:
+ * 		blade_id  - blade on which resources should be reserved
+ * 		cbrs	  - number of CBRs
+ * 		dsr_bytes - number of DSR bytes needed
+ *	output:
+ *		handle to identify resource
+ *		(0 = async resources already reserved)
+ */
+unsigned long gru_reserve_async_resources(int blade_id, int cbrs, int dsr_bytes,
+			struct completion *cmp)
+{
+	struct gru_blade_state *bs;
+	struct gru_thread_state *kgts;
+	int ret = 0;
+
+	bs = gru_base[blade_id];
+
+	down_write(&bs->bs_kgts_sema);
+
+	/* Verify no resources already reserved */
+	if (bs->bs_async_dsr_bytes + bs->bs_async_cbrs)
+		goto done;
+	bs->bs_async_dsr_bytes = dsr_bytes;
+	bs->bs_async_cbrs = cbrs;
+	bs->bs_async_wq = cmp;
+	kgts = bs->bs_kgts;
+
+	/* Resources changed. Unload context if already loaded */
+	if (kgts && kgts->ts_gru)
+		gru_unload_context(kgts, 0);
+	ret = ASYNC_BID_TO_HAN(blade_id);
+
+done:
+	up_write(&bs->bs_kgts_sema);
+	return ret;
+}
+
+/*
+ * Release async resources previously reserved.
+ *
+ *	input:
+ *		han - handle to identify resources
+ */
+void gru_release_async_resources(unsigned long han)
+{
+	struct gru_blade_state *bs = ASYNC_HAN_TO_BS(han);
+
+	down_write(&bs->bs_kgts_sema);
+	bs->bs_async_dsr_bytes = 0;
+	bs->bs_async_cbrs = 0;
+	bs->bs_async_wq = NULL;
+	up_write(&bs->bs_kgts_sema);
+}
+
+/*
+ * Wait for async GRU instructions to complete.
+ *
+ *	input:
+ *		han - handle to identify resources
+ */
+void gru_wait_async_cbr(unsigned long han)
+{
+	struct gru_blade_state *bs = ASYNC_HAN_TO_BS(han);
+
+	wait_for_completion(bs->bs_async_wq);
+	mb();
+}
+
+/*
+ * Lock previous reserved async GRU resources
+ *
+ *	input:
+ *		han - handle to identify resources
+ *	output:
+ *		cb  - pointer to first CBR
+ *		dsr - pointer to first DSR
+ */
+void gru_lock_async_resource(unsigned long han,  void **cb, void **dsr)
+{
+	struct gru_blade_state *bs = ASYNC_HAN_TO_BS(han);
+	int blade_id = ASYNC_HAN_TO_BID(han);
+	int ncpus;
+
+	gru_lock_kernel_context(blade_id);
+	ncpus = uv_blade_nr_possible_cpus(blade_id);
+	if (cb)
+		*cb = bs->kernel_cb + ncpus * GRU_HANDLE_STRIDE;
+	if (dsr)
+		*dsr = bs->kernel_dsr + ncpus * GRU_NUM_KERNEL_DSR_BYTES;
+}
+
+/*
+ * Unlock previous reserved async GRU resources
+ *
+ *	input:
+ *		han - handle to identify resources
+ */
+void gru_unlock_async_resource(unsigned long han)
+{
+	int blade_id = ASYNC_HAN_TO_BID(han);
+
+	gru_unlock_kernel_context(blade_id);
+}
+
+/*----------------------------------------------------------------------*/
 int gru_get_cb_exception_detail(void *cb,
 		struct control_block_extended_exc_detail *excdet)
 {
 	struct gru_control_block_extended *cbe;
+	struct gru_blade_state *bs;
+	int cbrnum;
 
-	cbe = get_cbe(GRUBASE(cb), get_cb_number(cb));
-	prefetchw(cbe);	/* Harmless on hardware, required for emulator */
+	bs = KCB_TO_BS(cb);
+	cbrnum = thread_cbr_number(bs->bs_kgts, get_cb_number(cb));
+	cbe = get_cbe(GRUBASE(cb), cbrnum);
+	gru_flush_cache(cbe);	/* CBE not coherent */
 	excdet->opc = cbe->opccpy;
 	excdet->exopc = cbe->exopccpy;
 	excdet->ecause = cbe->ecause;
 	excdet->exceptdet0 = cbe->idef1upd;
 	excdet->exceptdet1 = cbe->idef3upd;
+	gru_flush_cache(cbe);
 	return 0;
 }
 
@@ -167,13 +436,13 @@
 	int retry = EXCEPTION_RETRY_LIMIT;
 
 	while (1)  {
-		if (gru_get_cb_message_queue_substatus(cb))
-			break;
 		if (gru_wait_idle_or_exception(gen) == CBS_IDLE)
 			return CBS_IDLE;
-
+		if (gru_get_cb_message_queue_substatus(cb))
+			return CBS_EXCEPTION;
 		gru_get_cb_exception_detail(cb, &excdet);
-		if (excdet.ecause & ~EXCEPTION_RETRY_BITS)
+		if ((excdet.ecause & ~EXCEPTION_RETRY_BITS) ||
+				(excdet.cbrexecstatus & CBR_EXS_ABORT_OCC))
 			break;
 		if (retry-- == 0)
 			break;
@@ -416,6 +685,29 @@
 				mqd->interrupt_vector);
 }
 
+/*
+ * Handle a PUT failure. Note: if message was a 2-line message, one of the
+ * lines might have successfully have been written. Before sending the
+ * message, "present" must be cleared in BOTH lines to prevent the receiver
+ * from prematurely seeing the full message.
+ */
+static int send_message_put_nacked(void *cb, struct gru_message_queue_desc *mqd,
+			void *mesg, int lines)
+{
+	unsigned long m;
+
+	m = mqd->mq_gpa + (gru_get_amo_value_head(cb) << 6);
+	if (lines == 2) {
+		gru_vset(cb, m, 0, XTYPE_CL, lines, 1, IMA);
+		if (gru_wait(cb) != CBS_IDLE)
+			return MQE_UNEXPECTED_CB_ERR;
+	}
+	gru_vstore(cb, m, gru_get_tri(mesg), XTYPE_CL, lines, 1, IMA);
+	if (gru_wait(cb) != CBS_IDLE)
+		return MQE_UNEXPECTED_CB_ERR;
+	send_message_queue_interrupt(mqd);
+	return MQE_OK;
+}
 
 /*
  * Handle a gru_mesq failure. Some of these failures are software recoverable
@@ -425,7 +717,6 @@
 				void *mesg, int lines)
 {
 	int substatus, ret = 0;
-	unsigned long m;
 
 	substatus = gru_get_cb_message_queue_substatus(cb);
 	switch (substatus) {
@@ -447,14 +738,7 @@
 		break;
 	case CBSS_PUT_NACKED:
 		STAT(mesq_send_put_nacked);
-		m = mqd->mq_gpa + (gru_get_amo_value_head(cb) << 6);
-		gru_vstore(cb, m, gru_get_tri(mesg), XTYPE_CL, lines, 1, IMA);
-		if (gru_wait(cb) == CBS_IDLE) {
-			ret = MQE_OK;
-			send_message_queue_interrupt(mqd);
-		} else {
-			ret = MQE_UNEXPECTED_CB_ERR;
-		}
+		ret = send_message_put_nacked(cb, mqd, mesg, lines);
 		break;
 	default:
 		BUG();
@@ -597,115 +881,177 @@
 
 /* ------------------- KERNEL QUICKTESTS RUN AT STARTUP ----------------*/
 /* 	Temp - will delete after we gain confidence in the GRU		*/
-static __cacheline_aligned unsigned long word0;
-static __cacheline_aligned unsigned long word1;
 
-static int quicktest(struct gru_state *gru)
+static int quicktest0(unsigned long arg)
 {
+	unsigned long word0;
+	unsigned long word1;
 	void *cb;
-	void *ds;
+	void *dsr;
 	unsigned long *p;
+	int ret = -EIO;
 
-	cb = get_gseg_base_address_cb(gru->gs_gru_base_vaddr, KERNEL_CTXNUM, 0);
-	ds = get_gseg_base_address_ds(gru->gs_gru_base_vaddr, KERNEL_CTXNUM, 0);
-	p = ds;
+	if (gru_get_cpu_resources(GRU_CACHE_LINE_BYTES, &cb, &dsr))
+		return MQE_BUG_NO_RESOURCES;
+	p = dsr;
 	word0 = MAGIC;
+	word1 = 0;
 
-	gru_vload(cb, uv_gpa(&word0), 0, XTYPE_DW, 1, 1, IMA);
-	if (gru_wait(cb) != CBS_IDLE)
-		BUG();
-
-	if (*(unsigned long *)ds != MAGIC)
-		BUG();
-	gru_vstore(cb, uv_gpa(&word1), 0, XTYPE_DW, 1, 1, IMA);
-	if (gru_wait(cb) != CBS_IDLE)
-		BUG();
-
-	if (word0 != word1 || word0 != MAGIC) {
-		printk
-		    ("GRU quicktest err: gid %d, found 0x%lx, expected 0x%lx\n",
-		     gru->gs_gid, word1, MAGIC);
-		BUG();		/* ZZZ should not be fatal */
+	gru_vload(cb, uv_gpa(&word0), gru_get_tri(dsr), XTYPE_DW, 1, 1, IMA);
+	if (gru_wait(cb) != CBS_IDLE) {
+		printk(KERN_DEBUG "GRU quicktest0: CBR failure 1\n");
+		goto done;
 	}
 
+	if (*p != MAGIC) {
+		printk(KERN_DEBUG "GRU: quicktest0 bad magic 0x%lx\n", *p);
+		goto done;
+	}
+	gru_vstore(cb, uv_gpa(&word1), gru_get_tri(dsr), XTYPE_DW, 1, 1, IMA);
+	if (gru_wait(cb) != CBS_IDLE) {
+		printk(KERN_DEBUG "GRU quicktest0: CBR failure 2\n");
+		goto done;
+	}
+
+	if (word0 != word1 || word1 != MAGIC) {
+		printk(KERN_DEBUG
+		       "GRU quicktest0 err: found 0x%lx, expected 0x%lx\n",
+		     word1, MAGIC);
+		goto done;
+	}
+	ret = 0;
+
+done:
+	gru_free_cpu_resources(cb, dsr);
+	return ret;
+}
+
+#define ALIGNUP(p, q)	((void *)(((unsigned long)(p) + (q) - 1) & ~(q - 1)))
+
+static int quicktest1(unsigned long arg)
+{
+	struct gru_message_queue_desc mqd;
+	void *p, *mq;
+	unsigned long *dw;
+	int i, ret = -EIO;
+	char mes[GRU_CACHE_LINE_BYTES], *m;
+
+	/* Need  1K cacheline aligned that does not cross page boundary */
+	p = kmalloc(4096, 0);
+	mq = ALIGNUP(p, 1024);
+	memset(mes, 0xee, sizeof(mes));
+	dw = mq;
+
+	gru_create_message_queue(&mqd, mq, 8 * GRU_CACHE_LINE_BYTES, 0, 0, 0);
+	for (i = 0; i < 6; i++) {
+		mes[8] = i;
+		do {
+			ret = gru_send_message_gpa(&mqd, mes, sizeof(mes));
+		} while (ret == MQE_CONGESTION);
+		if (ret)
+			break;
+	}
+	if (ret != MQE_QUEUE_FULL || i != 4)
+		goto done;
+
+	for (i = 0; i < 6; i++) {
+		m = gru_get_next_message(&mqd);
+		if (!m || m[8] != i)
+			break;
+		gru_free_message(&mqd, m);
+	}
+	ret = (i == 4) ? 0 : -EIO;
+
+done:
+	kfree(p);
+	return ret;
+}
+
+static int quicktest2(unsigned long arg)
+{
+	static DECLARE_COMPLETION(cmp);
+	unsigned long han;
+	int blade_id = 0;
+	int numcb = 4;
+	int ret = 0;
+	unsigned long *buf;
+	void *cb0, *cb;
+	int i, k, istatus, bytes;
+
+	bytes = numcb * 4 * 8;
+	buf = kmalloc(bytes, GFP_KERNEL);
+	if (!buf)
+		return -ENOMEM;
+
+	ret = -EBUSY;
+	han = gru_reserve_async_resources(blade_id, numcb, 0, &cmp);
+	if (!han)
+		goto done;
+
+	gru_lock_async_resource(han, &cb0, NULL);
+	memset(buf, 0xee, bytes);
+	for (i = 0; i < numcb; i++)
+		gru_vset(cb0 + i * GRU_HANDLE_STRIDE, uv_gpa(&buf[i * 4]), 0,
+				XTYPE_DW, 4, 1, IMA_INTERRUPT);
+
+	ret = 0;
+	for (k = 0; k < numcb; k++) {
+		gru_wait_async_cbr(han);
+		for (i = 0; i < numcb; i++) {
+			cb = cb0 + i * GRU_HANDLE_STRIDE;
+			istatus = gru_check_status(cb);
+			if (istatus == CBS_ACTIVE)
+				continue;
+			if (istatus == CBS_EXCEPTION)
+				ret = -EFAULT;
+			else if (buf[i] || buf[i + 1] || buf[i + 2] ||
+					buf[i + 3])
+				ret = -EIO;
+		}
+	}
+	BUG_ON(cmp.done);
+
+	gru_unlock_async_resource(han);
+	gru_release_async_resources(han);
+done:
+	kfree(buf);
+	return ret;
+}
+
+/*
+ * Debugging only. User hook for various kernel tests
+ * of driver & gru.
+ */
+int gru_ktest(unsigned long arg)
+{
+	int ret = -EINVAL;
+
+	switch (arg & 0xff) {
+	case 0:
+		ret = quicktest0(arg);
+		break;
+	case 1:
+		ret = quicktest1(arg);
+		break;
+	case 2:
+		ret = quicktest2(arg);
+		break;
+	case 99:
+		ret = gru_free_kernel_contexts();
+		break;
+	}
+	return ret;
+
+}
+
+int gru_kservices_init(void)
+{
 	return 0;
 }
 
-
-int gru_kservices_init(struct gru_state *gru)
+void gru_kservices_exit(void)
 {
-	struct gru_blade_state *bs;
-	struct gru_context_configuration_handle *cch;
-	unsigned long cbr_map, dsr_map;
-	int err, num, cpus_possible;
-
-	/*
-	 * Currently, resources are reserved ONLY on the second chiplet
-	 * on each blade. This leaves ALL resources on chiplet 0 available
-	 * for user code.
-	 */
-	bs = gru->gs_blade;
-	if (gru != &bs->bs_grus[1])
-		return 0;
-
-	cpus_possible = uv_blade_nr_possible_cpus(gru->gs_blade_id);
-
-	num = GRU_NUM_KERNEL_CBR * cpus_possible;
-	cbr_map = gru_reserve_cb_resources(gru, GRU_CB_COUNT_TO_AU(num), NULL);
-	gru->gs_reserved_cbrs += num;
-
-	num = GRU_NUM_KERNEL_DSR_BYTES * cpus_possible;
-	dsr_map = gru_reserve_ds_resources(gru, GRU_DS_BYTES_TO_AU(num), NULL);
-	gru->gs_reserved_dsr_bytes += num;
-
-	gru->gs_active_contexts++;
-	__set_bit(KERNEL_CTXNUM, &gru->gs_context_map);
-	cch = get_cch(gru->gs_gru_base_vaddr, KERNEL_CTXNUM);
-
-	bs->kernel_cb = get_gseg_base_address_cb(gru->gs_gru_base_vaddr,
-					KERNEL_CTXNUM, 0);
-	bs->kernel_dsr = get_gseg_base_address_ds(gru->gs_gru_base_vaddr,
-					KERNEL_CTXNUM, 0);
-
-	lock_cch_handle(cch);
-	cch->tfm_fault_bit_enable = 0;
-	cch->tlb_int_enable = 0;
-	cch->tfm_done_bit_enable = 0;
-	cch->unmap_enable = 1;
-	err = cch_allocate(cch, 0, 0, cbr_map, dsr_map);
-	if (err) {
-		gru_dbg(grudev,
-			"Unable to allocate kernel CCH: gid %d, err %d\n",
-			gru->gs_gid, err);
+	if (gru_free_kernel_contexts())
 		BUG();
-	}
-	if (cch_start(cch)) {
-		gru_dbg(grudev, "Unable to start kernel CCH: gid %d, err %d\n",
-			gru->gs_gid, err);
-		BUG();
-	}
-	unlock_cch_handle(cch);
-
-	if (gru_options & GRU_QUICKLOOK)
-		quicktest(gru);
-	return 0;
-}
-
-void gru_kservices_exit(struct gru_state *gru)
-{
-	struct gru_context_configuration_handle *cch;
-	struct gru_blade_state *bs;
-
-	bs = gru->gs_blade;
-	if (gru != &bs->bs_grus[1])
-		return;
-
-	cch = get_cch(gru->gs_gru_base_vaddr, KERNEL_CTXNUM);
-	lock_cch_handle(cch);
-	if (cch_interrupt_sync(cch))
-		BUG();
-	if (cch_deallocate(cch))
-		BUG();
-	unlock_cch_handle(cch);
 }
 
diff --git a/drivers/misc/sgi-gru/grukservices.h b/drivers/misc/sgi-gru/grukservices.h
index 747ed31..d60d34b 100644
--- a/drivers/misc/sgi-gru/grukservices.h
+++ b/drivers/misc/sgi-gru/grukservices.h
@@ -146,4 +146,55 @@
 extern int gru_copy_gpa(unsigned long dest_gpa, unsigned long src_gpa,
 							unsigned int bytes);
 
+/*
+ * Reserve GRU resources to be used asynchronously.
+ *
+ * 	input:
+ * 		blade_id  - blade on which resources should be reserved
+ * 		cbrs	  - number of CBRs
+ * 		dsr_bytes - number of DSR bytes needed
+ * 		cmp	  - completion structure for waiting for
+ * 			    async completions
+ *	output:
+ *		handle to identify resource
+ *		(0 = no resources)
+ */
+extern unsigned long gru_reserve_async_resources(int blade_id, int cbrs, int dsr_bytes,
+				struct completion *cmp);
+
+/*
+ * Release async resources previously reserved.
+ *
+ *	input:
+ *		han - handle to identify resources
+ */
+extern void gru_release_async_resources(unsigned long han);
+
+/*
+ * Wait for async GRU instructions to complete.
+ *
+ *	input:
+ *		han - handle to identify resources
+ */
+extern void gru_wait_async_cbr(unsigned long han);
+
+/*
+ * Lock previous reserved async GRU resources
+ *
+ *	input:
+ *		han - handle to identify resources
+ *	output:
+ *		cb  - pointer to first CBR
+ *		dsr - pointer to first DSR
+ */
+extern void gru_lock_async_resource(unsigned long han,  void **cb, void **dsr);
+
+/*
+ * Unlock previous reserved async GRU resources
+ *
+ *	input:
+ *		han - handle to identify resources
+ */
+extern void gru_unlock_async_resource(unsigned long han);
+
 #endif 		/* __GRU_KSERVICES_H_ */
diff --git a/drivers/misc/sgi-gru/grulib.h b/drivers/misc/sgi-gru/grulib.h
index e56e196..889bc44 100644
--- a/drivers/misc/sgi-gru/grulib.h
+++ b/drivers/misc/sgi-gru/grulib.h
@@ -32,8 +32,8 @@
 /* Set Number of Request Blocks */
 #define GRU_CREATE_CONTEXT		_IOWR(GRU_IOCTL_NUM, 1, void *)
 
-/* Register task as using the slice */
-#define GRU_SET_TASK_SLICE		_IOWR(GRU_IOCTL_NUM, 5, void *)
+/*  Set Context Options */
+#define GRU_SET_CONTEXT_OPTION		_IOWR(GRU_IOCTL_NUM, 4, void *)
 
 /* Fetch exception detail */
 #define GRU_USER_GET_EXCEPTION_DETAIL	_IOWR(GRU_IOCTL_NUM, 6, void *)
@@ -44,8 +44,11 @@
 /* For user unload context */
 #define GRU_USER_UNLOAD_CONTEXT		_IOWR(GRU_IOCTL_NUM, 9, void *)
 
-/* For fetching GRU chiplet status */
-#define GRU_GET_CHIPLET_STATUS		_IOWR(GRU_IOCTL_NUM, 10, void *)
+/* For dumpping GRU chiplet state */
+#define GRU_DUMP_CHIPLET_STATE		_IOWR(GRU_IOCTL_NUM, 11, void *)
+
+/* For getting gseg statistics */
+#define GRU_GET_GSEG_STATISTICS		_IOWR(GRU_IOCTL_NUM, 12, void *)
 
 /* For user TLB flushing (primarily for tests) */
 #define GRU_USER_FLUSH_TLB		_IOWR(GRU_IOCTL_NUM, 50, void *)
@@ -53,8 +56,26 @@
 /* Get some config options (primarily for tests & emulator) */
 #define GRU_GET_CONFIG_INFO		_IOWR(GRU_IOCTL_NUM, 51, void *)
 
+/* Various kernel self-tests */
+#define GRU_KTEST			_IOWR(GRU_IOCTL_NUM, 52, void *)
+
 #define CONTEXT_WINDOW_BYTES(th)        (GRU_GSEG_PAGESIZE * (th))
 #define THREAD_POINTER(p, th)		(p + GRU_GSEG_PAGESIZE * (th))
+#define GSEG_START(cb)			((void *)((unsigned long)(cb) & ~(GRU_GSEG_PAGESIZE - 1)))
+
+/*
+ * Statictics kept on a per-GTS basis.
+ */
+struct gts_statistics {
+	unsigned long	fmm_tlbdropin;
+	unsigned long	upm_tlbdropin;
+	unsigned long	context_stolen;
+};
+
+struct gru_get_gseg_statistics_req {
+	unsigned long		gseg;
+	struct gts_statistics	stats;
+};
 
 /*
  * Structure used to pass TLB flush parameters to the driver
@@ -75,6 +96,16 @@
 };
 
 /*
+ * Structure used to set context options
+ */
+enum {sco_gseg_owner, sco_cch_req_slice};
+struct gru_set_context_option_req {
+	unsigned long	gseg;
+	int		op;
+	unsigned long	val1;
+};
+
+/*
  * Structure used to pass TLB flush parameters to the driver
  */
 struct gru_flush_tlb_req {
@@ -84,6 +115,36 @@
 };
 
 /*
+ * Structure used to pass TLB flush parameters to the driver
+ */
+enum {dcs_pid, dcs_gid};
+struct gru_dump_chiplet_state_req {
+	unsigned int	op;
+	unsigned int	gid;
+	int		ctxnum;
+	char		data_opt;
+	char		lock_cch;
+	pid_t		pid;
+	void		*buf;
+	size_t		buflen;
+	/* ---- output --- */
+	unsigned int	num_contexts;
+};
+
+#define GRU_DUMP_MAGIC	0x3474ab6c
+struct gru_dump_context_header {
+	unsigned int	magic;
+	unsigned int	gid;
+	unsigned char	ctxnum;
+	unsigned char	cbrcnt;
+	unsigned char	dsrcnt;
+	pid_t		pid;
+	unsigned long	vaddr;
+	int		cch_locked;
+	unsigned long	data[0];
+};
+
+/*
  * GRU configuration info (temp - for testing)
  */
 struct gru_config_info {
diff --git a/drivers/misc/sgi-gru/grumain.c b/drivers/misc/sgi-gru/grumain.c
index ec3f7a1..3bc643d 100644
--- a/drivers/misc/sgi-gru/grumain.c
+++ b/drivers/misc/sgi-gru/grumain.c
@@ -3,11 +3,21 @@
  *
  *            DRIVER TABLE MANAGER + GRU CONTEXT LOAD/UNLOAD
  *
- * This file is subject to the terms and conditions of the GNU General Public
- * License.  See the file "COPYING" in the main directory of this archive
- * for more details.
+ *  Copyright (c) 2008 Silicon Graphics, Inc.  All Rights Reserved.
  *
- * Copyright (c) 2008 Silicon Graphics, Inc.  All Rights Reserved.
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  */
 
 #include <linux/kernel.h>
@@ -96,7 +106,7 @@
 	gid = gru->gs_gid;
 again:
 	for (i = 0; i < GRU_NUM_CCH; i++) {
-		if (!gru->gs_gts[i])
+		if (!gru->gs_gts[i] || is_kernel_context(gru->gs_gts[i]))
 			continue;
 		inuse_asid = gru->gs_gts[i]->ts_gms->ms_asids[gid].mt_asid;
 		gru_dbg(grudev, "gid %d, gts %p, gms %p, inuse 0x%x, cxt %d\n",
@@ -150,7 +160,7 @@
 	unsigned long bits = 0;
 	int i;
 
-	do {
+	while (n--) {
 		i = find_first_bit(p, mmax);
 		if (i == mmax)
 			BUG();
@@ -158,7 +168,7 @@
 		__set_bit(i, &bits);
 		if (idx)
 			*idx++ = i;
-	} while (--n);
+	}
 	return bits;
 }
 
@@ -299,38 +309,39 @@
 /*
  * Allocate a thread state structure.
  */
-static struct gru_thread_state *gru_alloc_gts(struct vm_area_struct *vma,
-					      struct gru_vma_data *vdata,
-					      int tsid)
+struct gru_thread_state *gru_alloc_gts(struct vm_area_struct *vma,
+		int cbr_au_count, int dsr_au_count, int options, int tsid)
 {
 	struct gru_thread_state *gts;
 	int bytes;
 
-	bytes = DSR_BYTES(vdata->vd_dsr_au_count) +
-				CBR_BYTES(vdata->vd_cbr_au_count);
+	bytes = DSR_BYTES(dsr_au_count) + CBR_BYTES(cbr_au_count);
 	bytes += sizeof(struct gru_thread_state);
-	gts = kzalloc(bytes, GFP_KERNEL);
+	gts = kmalloc(bytes, GFP_KERNEL);
 	if (!gts)
 		return NULL;
 
 	STAT(gts_alloc);
+	memset(gts, 0, sizeof(struct gru_thread_state)); /* zero out header */
 	atomic_set(&gts->ts_refcnt, 1);
 	mutex_init(&gts->ts_ctxlock);
-	gts->ts_cbr_au_count = vdata->vd_cbr_au_count;
-	gts->ts_dsr_au_count = vdata->vd_dsr_au_count;
-	gts->ts_user_options = vdata->vd_user_options;
+	gts->ts_cbr_au_count = cbr_au_count;
+	gts->ts_dsr_au_count = dsr_au_count;
+	gts->ts_user_options = options;
 	gts->ts_tsid = tsid;
-	gts->ts_user_options = vdata->vd_user_options;
 	gts->ts_ctxnum = NULLCTX;
-	gts->ts_mm = current->mm;
-	gts->ts_vma = vma;
 	gts->ts_tlb_int_select = -1;
-	gts->ts_gms = gru_register_mmu_notifier();
+	gts->ts_cch_req_slice = -1;
 	gts->ts_sizeavail = GRU_SIZEAVAIL(PAGE_SHIFT);
-	if (!gts->ts_gms)
-		goto err;
+	if (vma) {
+		gts->ts_mm = current->mm;
+		gts->ts_vma = vma;
+		gts->ts_gms = gru_register_mmu_notifier();
+		if (!gts->ts_gms)
+			goto err;
+	}
 
-	gru_dbg(grudev, "alloc vdata %p, new gts %p\n", vdata, gts);
+	gru_dbg(grudev, "alloc gts %p\n", gts);
 	return gts;
 
 err:
@@ -381,7 +392,8 @@
 	struct gru_vma_data *vdata = vma->vm_private_data;
 	struct gru_thread_state *gts, *ngts;
 
-	gts = gru_alloc_gts(vma, vdata, tsid);
+	gts = gru_alloc_gts(vma, vdata->vd_cbr_au_count, vdata->vd_dsr_au_count,
+			    vdata->vd_user_options, tsid);
 	if (!gts)
 		return NULL;
 
@@ -458,7 +470,8 @@
 }
 
 static void gru_load_context_data(void *save, void *grubase, int ctxnum,
-				  unsigned long cbrmap, unsigned long dsrmap)
+				  unsigned long cbrmap, unsigned long dsrmap,
+				  int data_valid)
 {
 	void *gseg, *cb, *cbe;
 	unsigned long length;
@@ -471,12 +484,22 @@
 	gru_prefetch_context(gseg, cb, cbe, cbrmap, length);
 
 	for_each_cbr_in_allocation_map(i, &cbrmap, scr) {
-		save += gru_copy_handle(cb, save);
-		save += gru_copy_handle(cbe + i * GRU_HANDLE_STRIDE, save);
+		if (data_valid) {
+			save += gru_copy_handle(cb, save);
+			save += gru_copy_handle(cbe + i * GRU_HANDLE_STRIDE,
+						save);
+		} else {
+			memset(cb, 0, GRU_CACHE_LINE_BYTES);
+			memset(cbe + i * GRU_HANDLE_STRIDE, 0,
+						GRU_CACHE_LINE_BYTES);
+		}
 		cb += GRU_HANDLE_STRIDE;
 	}
 
-	memcpy(gseg + GRU_DS_BASE, save, length);
+	if (data_valid)
+		memcpy(gseg + GRU_DS_BASE, save, length);
+	else
+		memset(gseg + GRU_DS_BASE, 0, length);
 }
 
 static void gru_unload_context_data(void *save, void *grubase, int ctxnum,
@@ -506,7 +529,8 @@
 	struct gru_context_configuration_handle *cch;
 	int ctxnum = gts->ts_ctxnum;
 
-	zap_vma_ptes(gts->ts_vma, UGRUADDR(gts), GRU_GSEG_PAGESIZE);
+	if (!is_kernel_context(gts))
+		zap_vma_ptes(gts->ts_vma, UGRUADDR(gts), GRU_GSEG_PAGESIZE);
 	cch = get_cch(gru->gs_gru_base_vaddr, ctxnum);
 
 	gru_dbg(grudev, "gts %p\n", gts);
@@ -514,11 +538,14 @@
 	if (cch_interrupt_sync(cch))
 		BUG();
 
-	gru_unload_mm_tracker(gru, gts);
-	if (savestate)
+	if (!is_kernel_context(gts))
+		gru_unload_mm_tracker(gru, gts);
+	if (savestate) {
 		gru_unload_context_data(gts->ts_gdata, gru->gs_gru_base_vaddr,
 					ctxnum, gts->ts_cbr_map,
 					gts->ts_dsr_map);
+		gts->ts_data_valid = 1;
+	}
 
 	if (cch_deallocate(cch))
 		BUG();
@@ -526,24 +553,22 @@
 	unlock_cch_handle(cch);
 
 	gru_free_gru_context(gts);
-	STAT(unload_context);
 }
 
 /*
  * Load a GRU context by copying it from the thread data structure in memory
  * to the GRU.
  */
-static void gru_load_context(struct gru_thread_state *gts)
+void gru_load_context(struct gru_thread_state *gts)
 {
 	struct gru_state *gru = gts->ts_gru;
 	struct gru_context_configuration_handle *cch;
-	int err, asid, ctxnum = gts->ts_ctxnum;
+	int i, err, asid, ctxnum = gts->ts_ctxnum;
 
 	gru_dbg(grudev, "gts %p\n", gts);
 	cch = get_cch(gru->gs_gru_base_vaddr, ctxnum);
 
 	lock_cch_handle(cch);
-	asid = gru_load_mm_tracker(gru, gts);
 	cch->tfm_fault_bit_enable =
 	    (gts->ts_user_options == GRU_OPT_MISS_FMM_POLL
 	     || gts->ts_user_options == GRU_OPT_MISS_FMM_INTR);
@@ -552,9 +577,32 @@
 		gts->ts_tlb_int_select = gru_cpu_fault_map_id();
 		cch->tlb_int_select = gts->ts_tlb_int_select;
 	}
+	if (gts->ts_cch_req_slice >= 0) {
+		cch->req_slice_set_enable = 1;
+		cch->req_slice = gts->ts_cch_req_slice;
+	} else {
+		cch->req_slice_set_enable =0;
+	}
 	cch->tfm_done_bit_enable = 0;
-	err = cch_allocate(cch, asid, gts->ts_sizeavail, gts->ts_cbr_map,
-				gts->ts_dsr_map);
+	cch->dsr_allocation_map = gts->ts_dsr_map;
+	cch->cbr_allocation_map = gts->ts_cbr_map;
+
+	if (is_kernel_context(gts)) {
+		cch->unmap_enable = 1;
+		cch->tfm_done_bit_enable = 1;
+		cch->cb_int_enable = 1;
+	} else {
+		cch->unmap_enable = 0;
+		cch->tfm_done_bit_enable = 0;
+		cch->cb_int_enable = 0;
+		asid = gru_load_mm_tracker(gru, gts);
+		for (i = 0; i < 8; i++) {
+			cch->asid[i] = asid + i;
+			cch->sizeavail[i] = gts->ts_sizeavail;
+		}
+	}
+
+	err = cch_allocate(cch);
 	if (err) {
 		gru_dbg(grudev,
 			"err %d: cch %p, gts %p, cbr 0x%lx, dsr 0x%lx\n",
@@ -563,13 +611,11 @@
 	}
 
 	gru_load_context_data(gts->ts_gdata, gru->gs_gru_base_vaddr, ctxnum,
-			      gts->ts_cbr_map, gts->ts_dsr_map);
+			gts->ts_cbr_map, gts->ts_dsr_map, gts->ts_data_valid);
 
 	if (cch_start(cch))
 		BUG();
 	unlock_cch_handle(cch);
-
-	STAT(load_context);
 }
 
 /*
@@ -599,6 +645,9 @@
 				cch->sizeavail[i] = gts->ts_sizeavail;
 			gts->ts_tlb_int_select = gru_cpu_fault_map_id();
 			cch->tlb_int_select = gru_cpu_fault_map_id();
+			cch->tfm_fault_bit_enable =
+			  (gts->ts_user_options == GRU_OPT_MISS_FMM_POLL
+			    || gts->ts_user_options == GRU_OPT_MISS_FMM_INTR);
 		} else {
 			for (i = 0; i < 8; i++)
 				cch->asid[i] = 0;
@@ -642,7 +691,28 @@
 #define next_gru(b, g)	(((g) < &(b)->bs_grus[GRU_CHIPLETS_PER_BLADE - 1]) ?  \
 				 ((g)+1) : &(b)->bs_grus[0])
 
-static void gru_steal_context(struct gru_thread_state *gts)
+static int is_gts_stealable(struct gru_thread_state *gts,
+		struct gru_blade_state *bs)
+{
+	if (is_kernel_context(gts))
+		return down_write_trylock(&bs->bs_kgts_sema);
+	else
+		return mutex_trylock(&gts->ts_ctxlock);
+}
+
+static void gts_stolen(struct gru_thread_state *gts,
+		struct gru_blade_state *bs)
+{
+	if (is_kernel_context(gts)) {
+		up_write(&bs->bs_kgts_sema);
+		STAT(steal_kernel_context);
+	} else {
+		mutex_unlock(&gts->ts_ctxlock);
+		STAT(steal_user_context);
+	}
+}
+
+void gru_steal_context(struct gru_thread_state *gts, int blade_id)
 {
 	struct gru_blade_state *blade;
 	struct gru_state *gru, *gru0;
@@ -652,8 +722,7 @@
 	cbr = gts->ts_cbr_au_count;
 	dsr = gts->ts_dsr_au_count;
 
-	preempt_disable();
-	blade = gru_base[uv_numa_blade_id()];
+	blade = gru_base[blade_id];
 	spin_lock(&blade->bs_lock);
 
 	ctxnum = next_ctxnum(blade->bs_lru_ctxnum);
@@ -676,7 +745,7 @@
 			 * success are high. If trylock fails, try to steal a
 			 * different GSEG.
 			 */
-			if (ngts && mutex_trylock(&ngts->ts_ctxlock))
+			if (ngts && is_gts_stealable(ngts, blade))
 				break;
 			ngts = NULL;
 			flag = 1;
@@ -690,13 +759,12 @@
 	blade->bs_lru_gru = gru;
 	blade->bs_lru_ctxnum = ctxnum;
 	spin_unlock(&blade->bs_lock);
-	preempt_enable();
 
 	if (ngts) {
-		STAT(steal_context);
+		gts->ustats.context_stolen++;
 		ngts->ts_steal_jiffies = jiffies;
-		gru_unload_context(ngts, 1);
-		mutex_unlock(&ngts->ts_ctxlock);
+		gru_unload_context(ngts, is_kernel_context(ngts) ? 0 : 1);
+		gts_stolen(ngts, blade);
 	} else {
 		STAT(steal_context_failed);
 	}
@@ -710,17 +778,17 @@
 /*
  * Scan the GRUs on the local blade & assign a GRU context.
  */
-static struct gru_state *gru_assign_gru_context(struct gru_thread_state *gts)
+struct gru_state *gru_assign_gru_context(struct gru_thread_state *gts,
+						int blade)
 {
 	struct gru_state *gru, *grux;
 	int i, max_active_contexts;
 
-	preempt_disable();
 
 again:
 	gru = NULL;
 	max_active_contexts = GRU_NUM_CCH;
-	for_each_gru_on_blade(grux, uv_numa_blade_id(), i) {
+	for_each_gru_on_blade(grux, blade, i) {
 		if (check_gru_resources(grux, gts->ts_cbr_au_count,
 					gts->ts_dsr_au_count,
 					max_active_contexts)) {
@@ -760,7 +828,6 @@
 		STAT(assign_context_failed);
 	}
 
-	preempt_enable();
 	return gru;
 }
 
@@ -775,6 +842,7 @@
 {
 	struct gru_thread_state *gts;
 	unsigned long paddr, vaddr;
+	int blade_id;
 
 	vaddr = (unsigned long)vmf->virtual_address;
 	gru_dbg(grudev, "vma %p, vaddr 0x%lx (0x%lx)\n",
@@ -789,8 +857,10 @@
 again:
 	mutex_lock(&gts->ts_ctxlock);
 	preempt_disable();
+	blade_id = uv_numa_blade_id();
+
 	if (gts->ts_gru) {
-		if (gts->ts_gru->gs_blade_id != uv_numa_blade_id()) {
+		if (gts->ts_gru->gs_blade_id != blade_id) {
 			STAT(migrated_nopfn_unload);
 			gru_unload_context(gts, 1);
 		} else {
@@ -800,12 +870,15 @@
 	}
 
 	if (!gts->ts_gru) {
-		if (!gru_assign_gru_context(gts)) {
-			mutex_unlock(&gts->ts_ctxlock);
+		STAT(load_user_context);
+		if (!gru_assign_gru_context(gts, blade_id)) {
 			preempt_enable();
+			mutex_unlock(&gts->ts_ctxlock);
+			set_current_state(TASK_INTERRUPTIBLE);
 			schedule_timeout(GRU_ASSIGN_DELAY);  /* true hack ZZZ */
+			blade_id = uv_numa_blade_id();
 			if (gts->ts_steal_jiffies + GRU_STEAL_DELAY < jiffies)
-				gru_steal_context(gts);
+				gru_steal_context(gts, blade_id);
 			goto again;
 		}
 		gru_load_context(gts);
@@ -815,8 +888,8 @@
 				vma->vm_page_prot);
 	}
 
-	mutex_unlock(&gts->ts_ctxlock);
 	preempt_enable();
+	mutex_unlock(&gts->ts_ctxlock);
 
 	return VM_FAULT_NOPAGE;
 }
diff --git a/drivers/misc/sgi-gru/gruprocfs.c b/drivers/misc/sgi-gru/gruprocfs.c
index ee74821..9cbf95b 100644
--- a/drivers/misc/sgi-gru/gruprocfs.c
+++ b/drivers/misc/sgi-gru/gruprocfs.c
@@ -51,9 +51,12 @@
 	printstat(s, assign_context);
 	printstat(s, assign_context_failed);
 	printstat(s, free_context);
-	printstat(s, load_context);
-	printstat(s, unload_context);
-	printstat(s, steal_context);
+	printstat(s, load_user_context);
+	printstat(s, load_kernel_context);
+	printstat(s, lock_kernel_context);
+	printstat(s, unlock_kernel_context);
+	printstat(s, steal_user_context);
+	printstat(s, steal_kernel_context);
 	printstat(s, steal_context_failed);
 	printstat(s, nopfn);
 	printstat(s, break_cow);
@@ -70,7 +73,7 @@
 	printstat(s, user_flush_tlb);
 	printstat(s, user_unload_context);
 	printstat(s, user_exception);
-	printstat(s, set_task_slice);
+	printstat(s, set_context_option);
 	printstat(s, migrate_check);
 	printstat(s, migrated_retarget);
 	printstat(s, migrated_unload);
@@ -84,6 +87,9 @@
 	printstat(s, tlb_dropin_fail_range_active);
 	printstat(s, tlb_dropin_fail_idle);
 	printstat(s, tlb_dropin_fail_fmm);
+	printstat(s, tlb_dropin_fail_no_exception);
+	printstat(s, tlb_dropin_fail_no_exception_war);
+	printstat(s, tfh_stale_on_fault);
 	printstat(s, mmu_invalidate_range);
 	printstat(s, mmu_invalidate_page);
 	printstat(s, mmu_clear_flush_young);
@@ -158,8 +164,7 @@
 	unsigned long val;
 	char buf[80];
 
-	if (copy_from_user
-	    (buf, userbuf, count < sizeof(buf) ? count : sizeof(buf)))
+	if (strncpy_from_user(buf, userbuf, sizeof(buf) - 1) < 0)
 		return -EFAULT;
 	buf[count - 1] = '\0';
 	if (!strict_strtoul(buf, 10, &val))
diff --git a/drivers/misc/sgi-gru/grutables.h b/drivers/misc/sgi-gru/grutables.h
index bf1eeb7..34ab3d4 100644
--- a/drivers/misc/sgi-gru/grutables.h
+++ b/drivers/misc/sgi-gru/grutables.h
@@ -148,11 +148,13 @@
 #include <linux/wait.h>
 #include <linux/mmu_notifier.h>
 #include "gru.h"
+#include "grulib.h"
 #include "gruhandles.h"
 
 extern struct gru_stats_s gru_stats;
 extern struct gru_blade_state *gru_base[];
 extern unsigned long gru_start_paddr, gru_end_paddr;
+extern void *gru_start_vaddr;
 extern unsigned int gru_max_gids;
 
 #define GRU_MAX_BLADES		MAX_NUMNODES
@@ -174,9 +176,12 @@
 	atomic_long_t assign_context;
 	atomic_long_t assign_context_failed;
 	atomic_long_t free_context;
-	atomic_long_t load_context;
-	atomic_long_t unload_context;
-	atomic_long_t steal_context;
+	atomic_long_t load_user_context;
+	atomic_long_t load_kernel_context;
+	atomic_long_t lock_kernel_context;
+	atomic_long_t unlock_kernel_context;
+	atomic_long_t steal_user_context;
+	atomic_long_t steal_kernel_context;
 	atomic_long_t steal_context_failed;
 	atomic_long_t nopfn;
 	atomic_long_t break_cow;
@@ -193,7 +198,7 @@
 	atomic_long_t user_flush_tlb;
 	atomic_long_t user_unload_context;
 	atomic_long_t user_exception;
-	atomic_long_t set_task_slice;
+	atomic_long_t set_context_option;
 	atomic_long_t migrate_check;
 	atomic_long_t migrated_retarget;
 	atomic_long_t migrated_unload;
@@ -207,6 +212,9 @@
 	atomic_long_t tlb_dropin_fail_range_active;
 	atomic_long_t tlb_dropin_fail_idle;
 	atomic_long_t tlb_dropin_fail_fmm;
+	atomic_long_t tlb_dropin_fail_no_exception;
+	atomic_long_t tlb_dropin_fail_no_exception_war;
+	atomic_long_t tfh_stale_on_fault;
 	atomic_long_t mmu_invalidate_range;
 	atomic_long_t mmu_invalidate_page;
 	atomic_long_t mmu_clear_flush_young;
@@ -253,7 +261,6 @@
 
 #define OPT_DPRINT	1
 #define OPT_STATS	2
-#define GRU_QUICKLOOK	4
 
 
 #define IRQ_GRU			110	/* Starting IRQ number for interrupts */
@@ -373,6 +380,7 @@
 						   required for contest */
 	unsigned char		ts_cbr_au_count;/* Number of CBR resources
 						   required for contest */
+	char			ts_cch_req_slice;/* CCH packet slice */
 	char			ts_blade;	/* If >= 0, migrate context if
 						   ref from diferent blade */
 	char			ts_force_cch_reload;
@@ -380,6 +388,9 @@
 						   after migration */
 	char			ts_cbr_idx[GRU_CBR_AU];/* CBR numbers of each
 							  allocated CB */
+	int			ts_data_valid;	/* Indicates if ts_gdata has
+						   valid data */
+	struct gts_statistics	ustats;		/* User statistics */
 	unsigned long		ts_gdata[0];	/* save area for GRU data (CB,
 						   DS, CBE) */
 };
@@ -452,6 +463,14 @@
 							   reserved cb */
 	void			*kernel_dsr;		/* First kernel
 							   reserved DSR */
+	struct rw_semaphore	bs_kgts_sema;		/* lock for kgts */
+	struct gru_thread_state *bs_kgts;		/* GTS for kernel use */
+
+	/* ---- the following are used for managing kernel async GRU CBRs --- */
+	int			bs_async_dsr_bytes;	/* DSRs for async */
+	int			bs_async_cbrs;		/* CBRs AU for async */
+	struct completion	*bs_async_wq;
+
 	/* ---- the following are protected by the bs_lock spinlock ---- */
 	spinlock_t		bs_lock;		/* lock used for
 							   stealing contexts */
@@ -552,6 +571,12 @@
 
 /* Lock hierarchy checking enabled only in emulator */
 
+/* 0 = lock failed, 1 = locked */
+static inline int __trylock_handle(void *h)
+{
+	return !test_and_set_bit(1, h);
+}
+
 static inline void __lock_handle(void *h)
 {
 	while (test_and_set_bit(1, h))
@@ -563,6 +588,11 @@
 	clear_bit(1, h);
 }
 
+static inline int trylock_cch_handle(struct gru_context_configuration_handle *cch)
+{
+	return __trylock_handle(cch);
+}
+
 static inline void lock_cch_handle(struct gru_context_configuration_handle *cch)
 {
 	__lock_handle(cch);
@@ -584,6 +614,11 @@
 	__unlock_handle(tgh);
 }
 
+static inline int is_kernel_context(struct gru_thread_state *gts)
+{
+	return !gts->ts_mm;
+}
+
 /*-----------------------------------------------------------------------------
  * Function prototypes & externs
  */
@@ -598,24 +633,32 @@
 				*vma, int tsid);
 extern struct gru_thread_state *gru_alloc_thread_state(struct vm_area_struct
 				*vma, int tsid);
+extern struct gru_state *gru_assign_gru_context(struct gru_thread_state *gts,
+		int blade);
+extern void gru_load_context(struct gru_thread_state *gts);
+extern void gru_steal_context(struct gru_thread_state *gts, int blade_id);
 extern void gru_unload_context(struct gru_thread_state *gts, int savestate);
 extern int gru_update_cch(struct gru_thread_state *gts, int force_unload);
 extern void gts_drop(struct gru_thread_state *gts);
 extern void gru_tgh_flush_init(struct gru_state *gru);
-extern int gru_kservices_init(struct gru_state *gru);
-extern void gru_kservices_exit(struct gru_state *gru);
+extern int gru_kservices_init(void);
+extern void gru_kservices_exit(void);
+extern int gru_dump_chiplet_request(unsigned long arg);
+extern long gru_get_gseg_statistics(unsigned long arg);
 extern irqreturn_t gru_intr(int irq, void *dev_id);
 extern int gru_handle_user_call_os(unsigned long address);
 extern int gru_user_flush_tlb(unsigned long arg);
 extern int gru_user_unload_context(unsigned long arg);
 extern int gru_get_exception_detail(unsigned long arg);
-extern int gru_set_task_slice(long address);
+extern int gru_set_context_option(unsigned long address);
 extern int gru_cpu_fault_map_id(void);
 extern struct vm_area_struct *gru_find_vma(unsigned long vaddr);
 extern void gru_flush_all_tlb(struct gru_state *gru);
 extern int gru_proc_init(void);
 extern void gru_proc_exit(void);
 
+extern struct gru_thread_state *gru_alloc_gts(struct vm_area_struct *vma,
+		int cbr_au_count, int dsr_au_count, int options, int tsid);
 extern unsigned long gru_reserve_cb_resources(struct gru_state *gru,
 		int cbr_au_count, char *cbmap);
 extern unsigned long gru_reserve_ds_resources(struct gru_state *gru,
@@ -624,6 +667,7 @@
 extern struct gru_mm_struct *gru_register_mmu_notifier(void);
 extern void gru_drop_mmu_notifier(struct gru_mm_struct *gms);
 
+extern int gru_ktest(unsigned long arg);
 extern void gru_flush_tlb_range(struct gru_mm_struct *gms, unsigned long start,
 					unsigned long len);
 
diff --git a/drivers/mtd/ubi/Kconfig b/drivers/mtd/ubi/Kconfig
index 3f06310..b1cd7a1 100644
--- a/drivers/mtd/ubi/Kconfig
+++ b/drivers/mtd/ubi/Kconfig
@@ -49,15 +49,16 @@
 	  reserved. Leave the default value if unsure.
 
 config MTD_UBI_GLUEBI
-	bool "Emulate MTD devices"
+	tristate "MTD devices emulation driver (gluebi)"
 	default n
 	depends on MTD_UBI
 	help
-	   This option enables MTD devices emulation on top of UBI volumes: for
-	   each UBI volumes an MTD device is created, and all I/O to this MTD
-	   device is redirected to the UBI volume. This is handy to make
-	   MTD-oriented software (like JFFS2) work on top of UBI. Do not enable
-	   this if no legacy software will be used.
+	   This option enables gluebi - an additional driver which emulates MTD
+	   devices on top of UBI volumes: for each UBI volumes an MTD device is
+	   created, and all I/O to this MTD device is redirected to the UBI
+	   volume. This is handy to make MTD-oriented software (like JFFS2)
+	   work on top of UBI. Do not enable this unless you use legacy
+	   software.
 
 source "drivers/mtd/ubi/Kconfig.debug"
 endmenu
diff --git a/drivers/mtd/ubi/Makefile b/drivers/mtd/ubi/Makefile
index dd834e0..c9302a5 100644
--- a/drivers/mtd/ubi/Makefile
+++ b/drivers/mtd/ubi/Makefile
@@ -4,4 +4,4 @@
 ubi-y += misc.o
 
 ubi-$(CONFIG_MTD_UBI_DEBUG) += debug.o
-ubi-$(CONFIG_MTD_UBI_GLUEBI) += gluebi.o
+obj-$(CONFIG_MTD_UBI_GLUEBI) += gluebi.o
diff --git a/drivers/mtd/ubi/build.c b/drivers/mtd/ubi/build.c
index 4048db8..286ed59 100644
--- a/drivers/mtd/ubi/build.c
+++ b/drivers/mtd/ubi/build.c
@@ -41,6 +41,7 @@
 #include <linux/miscdevice.h>
 #include <linux/log2.h>
 #include <linux/kthread.h>
+#include <linux/reboot.h>
 #include "ubi.h"
 
 /* Maximum length of the 'mtd=' parameter */
@@ -122,6 +123,94 @@
 	__ATTR(mtd_num, S_IRUGO, dev_attribute_show, NULL);
 
 /**
+ * ubi_volume_notify - send a volume change notification.
+ * @ubi: UBI device description object
+ * @vol: volume description object of the changed volume
+ * @ntype: notification type to send (%UBI_VOLUME_ADDED, etc)
+ *
+ * This is a helper function which notifies all subscribers about a volume
+ * change event (creation, removal, re-sizing, re-naming, updating). Returns
+ * zero in case of success and a negative error code in case of failure.
+ */
+int ubi_volume_notify(struct ubi_device *ubi, struct ubi_volume *vol, int ntype)
+{
+	struct ubi_notification nt;
+
+	ubi_do_get_device_info(ubi, &nt.di);
+	ubi_do_get_volume_info(ubi, vol, &nt.vi);
+	return blocking_notifier_call_chain(&ubi_notifiers, ntype, &nt);
+}
+
+/**
+ * ubi_notify_all - send a notification to all volumes.
+ * @ubi: UBI device description object
+ * @ntype: notification type to send (%UBI_VOLUME_ADDED, etc)
+ * @nb: the notifier to call
+ *
+ * This function walks all volumes of UBI device @ubi and sends the @ntype
+ * notification for each volume. If @nb is %NULL, then all registered notifiers
+ * are called, otherwise only the @nb notifier is called. Returns the number of
+ * sent notifications.
+ */
+int ubi_notify_all(struct ubi_device *ubi, int ntype, struct notifier_block *nb)
+{
+	struct ubi_notification nt;
+	int i, count = 0;
+
+	ubi_do_get_device_info(ubi, &nt.di);
+
+	mutex_lock(&ubi->device_mutex);
+	for (i = 0; i < ubi->vtbl_slots; i++) {
+		/*
+		 * Since the @ubi->device is locked, and we are not going to
+		 * change @ubi->volumes, we do not have to lock
+		 * @ubi->volumes_lock.
+		 */
+		if (!ubi->volumes[i])
+			continue;
+
+		ubi_do_get_volume_info(ubi, ubi->volumes[i], &nt.vi);
+		if (nb)
+			nb->notifier_call(nb, ntype, &nt);
+		else
+			blocking_notifier_call_chain(&ubi_notifiers, ntype,
+						     &nt);
+		count += 1;
+	}
+	mutex_unlock(&ubi->device_mutex);
+
+	return count;
+}
+
+/**
+ * ubi_enumerate_volumes - send "add" notification for all existing volumes.
+ * @nb: the notifier to call
+ *
+ * This function walks all UBI devices and volumes and sends the
+ * %UBI_VOLUME_ADDED notification for each volume. If @nb is %NULL, then all
+ * registered notifiers are called, otherwise only the @nb notifier is called.
+ * Returns the number of sent notifications.
+ */
+int ubi_enumerate_volumes(struct notifier_block *nb)
+{
+	int i, count = 0;
+
+	/*
+	 * Since the @ubi_devices_mutex is locked, and we are not going to
+	 * change @ubi_devices, we do not have to lock @ubi_devices_lock.
+	 */
+	for (i = 0; i < UBI_MAX_DEVICES; i++) {
+		struct ubi_device *ubi = ubi_devices[i];
+
+		if (!ubi)
+			continue;
+		count += ubi_notify_all(ubi, UBI_VOLUME_ADDED, nb);
+	}
+
+	return count;
+}
+
+/**
  * ubi_get_device - get UBI device.
  * @ubi_num: UBI device number
  *
@@ -380,7 +469,7 @@
  * @ubi: UBI device description object
  *
  * This function returns zero in case of success and a negative error code in
- * case of failure. Note, this function destroys all volumes if it failes.
+ * case of failure. Note, this function destroys all volumes if it fails.
  */
 static int uif_init(struct ubi_device *ubi)
 {
@@ -633,6 +722,15 @@
 	}
 
 	/*
+	 * Set maximum amount of physical erroneous eraseblocks to be 10%.
+	 * Erroneous PEB are those which have read errors.
+	 */
+	ubi->max_erroneous = ubi->peb_count / 10;
+	if (ubi->max_erroneous < 16)
+		ubi->max_erroneous = 16;
+	dbg_msg("max_erroneous    %d", ubi->max_erroneous);
+
+	/*
 	 * It may happen that EC and VID headers are situated in one minimal
 	 * I/O unit. In this case we can only accept this UBI image in
 	 * read-only mode.
@@ -726,6 +824,34 @@
 }
 
 /**
+ * ubi_reboot_notifier - halt UBI transactions immediately prior to a reboot.
+ * @n: reboot notifier object
+ * @state: SYS_RESTART, SYS_HALT, or SYS_POWER_OFF
+ * @cmd: pointer to command string for RESTART2
+ *
+ * This function stops the UBI background thread so that the flash device
+ * remains quiescent when Linux restarts the system. Any queued work will be
+ * discarded, but this function will block until do_work() finishes if an
+ * operation is already in progress.
+ *
+ * This function solves a real-life problem observed on NOR flashes when an
+ * PEB erase operation starts, then the system is rebooted before the erase is
+ * finishes, and the boot loader gets confused and dies. So we prefer to finish
+ * the ongoing operation before rebooting.
+ */
+static int ubi_reboot_notifier(struct notifier_block *n, unsigned long state,
+			       void *cmd)
+{
+	struct ubi_device *ubi;
+
+	ubi = container_of(n, struct ubi_device, reboot_notifier);
+	if (ubi->bgt_thread)
+		kthread_stop(ubi->bgt_thread);
+	ubi_sync(ubi->ubi_num);
+	return NOTIFY_DONE;
+}
+
+/**
  * ubi_attach_mtd_dev - attach an MTD device.
  * @mtd: MTD device description object
  * @ubi_num: number to assign to the new UBI device
@@ -806,8 +932,7 @@
 
 	mutex_init(&ubi->buf_mutex);
 	mutex_init(&ubi->ckvol_mutex);
-	mutex_init(&ubi->mult_mutex);
-	mutex_init(&ubi->volumes_mutex);
+	mutex_init(&ubi->device_mutex);
 	spin_lock_init(&ubi->volumes_lock);
 
 	ubi_msg("attaching mtd%d to ubi%d", mtd->index, ubi_num);
@@ -825,7 +950,7 @@
 	if (!ubi->peb_buf2)
 		goto out_free;
 
-#ifdef CONFIG_MTD_UBI_DEBUG
+#ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
 	mutex_init(&ubi->dbg_buf_mutex);
 	ubi->dbg_peb_buf = vmalloc(ubi->peb_size);
 	if (!ubi->dbg_peb_buf)
@@ -872,11 +997,23 @@
 		ubi->beb_rsvd_pebs);
 	ubi_msg("max/mean erase counter: %d/%d", ubi->max_ec, ubi->mean_ec);
 
+	/*
+	 * The below lock makes sure we do not race with 'ubi_thread()' which
+	 * checks @ubi->thread_enabled. Otherwise we may fail to wake it up.
+	 */
+	spin_lock(&ubi->wl_lock);
 	if (!DBG_DISABLE_BGT)
 		ubi->thread_enabled = 1;
 	wake_up_process(ubi->bgt_thread);
+	spin_unlock(&ubi->wl_lock);
+
+	/* Flash device priority is 0 - UBI needs to shut down first */
+	ubi->reboot_notifier.priority = 1;
+	ubi->reboot_notifier.notifier_call = ubi_reboot_notifier;
+	register_reboot_notifier(&ubi->reboot_notifier);
 
 	ubi_devices[ubi_num] = ubi;
+	ubi_notify_all(ubi, UBI_VOLUME_ADDED, NULL);
 	return ubi_num;
 
 out_uif:
@@ -892,7 +1029,7 @@
 out_free:
 	vfree(ubi->peb_buf1);
 	vfree(ubi->peb_buf2);
-#ifdef CONFIG_MTD_UBI_DEBUG
+#ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
 	vfree(ubi->dbg_peb_buf);
 #endif
 	kfree(ubi);
@@ -919,13 +1056,13 @@
 	if (ubi_num < 0 || ubi_num >= UBI_MAX_DEVICES)
 		return -EINVAL;
 
-	spin_lock(&ubi_devices_lock);
-	ubi = ubi_devices[ubi_num];
-	if (!ubi) {
-		spin_unlock(&ubi_devices_lock);
+	ubi = ubi_get_device(ubi_num);
+	if (!ubi)
 		return -EINVAL;
-	}
 
+	spin_lock(&ubi_devices_lock);
+	put_device(&ubi->dev);
+	ubi->ref_count -= 1;
 	if (ubi->ref_count) {
 		if (!anyway) {
 			spin_unlock(&ubi_devices_lock);
@@ -939,12 +1076,14 @@
 	spin_unlock(&ubi_devices_lock);
 
 	ubi_assert(ubi_num == ubi->ubi_num);
+	ubi_notify_all(ubi, UBI_VOLUME_REMOVED, NULL);
 	dbg_msg("detaching mtd%d from ubi%d", ubi->mtd->index, ubi_num);
 
 	/*
 	 * Before freeing anything, we have to stop the background thread to
 	 * prevent it from doing anything on this device while we are freeing.
 	 */
+	unregister_reboot_notifier(&ubi->reboot_notifier);
 	if (ubi->bgt_thread)
 		kthread_stop(ubi->bgt_thread);
 
@@ -961,7 +1100,7 @@
 	put_mtd_device(ubi->mtd);
 	vfree(ubi->peb_buf1);
 	vfree(ubi->peb_buf2);
-#ifdef CONFIG_MTD_UBI_DEBUG
+#ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
 	vfree(ubi->dbg_peb_buf);
 #endif
 	ubi_msg("mtd%d is detached from ubi%d", ubi->mtd->index, ubi->ubi_num);
diff --git a/drivers/mtd/ubi/cdev.c b/drivers/mtd/ubi/cdev.c
index f8e0f68..f237ddb 100644
--- a/drivers/mtd/ubi/cdev.c
+++ b/drivers/mtd/ubi/cdev.c
@@ -113,7 +113,8 @@
 	else
 		mode = UBI_READONLY;
 
-	dbg_gen("open volume %d, mode %d", vol_id, mode);
+	dbg_gen("open device %d, volume %d, mode %d",
+	        ubi_num, vol_id, mode);
 
 	desc = ubi_open_volume(ubi_num, vol_id, mode);
 	if (IS_ERR(desc))
@@ -128,7 +129,8 @@
 	struct ubi_volume_desc *desc = file->private_data;
 	struct ubi_volume *vol = desc->vol;
 
-	dbg_gen("release volume %d, mode %d", vol->vol_id, desc->mode);
+	dbg_gen("release device %d, volume %d, mode %d",
+		vol->ubi->ubi_num, vol->vol_id, desc->mode);
 
 	if (vol->updating) {
 		ubi_warn("update of volume %d not finished, volume is damaged",
@@ -393,7 +395,7 @@
 			vol->corrupted = 1;
 		}
 		vol->checked = 1;
-		ubi_gluebi_updated(vol);
+		ubi_volume_notify(ubi, vol, UBI_VOLUME_UPDATED);
 		revoke_exclusive(desc, UBI_READWRITE);
 	}
 
@@ -558,7 +560,7 @@
 		break;
 	}
 
-	/* Set volume property command*/
+	/* Set volume property command */
 	case UBI_IOCSETPROP:
 	{
 		struct ubi_set_prop_req req;
@@ -571,9 +573,9 @@
 		}
 		switch (req.property) {
 		case UBI_PROP_DIRECT_WRITE:
-			mutex_lock(&ubi->volumes_mutex);
+			mutex_lock(&ubi->device_mutex);
 			desc->vol->direct_writes = !!req.value;
-			mutex_unlock(&ubi->volumes_mutex);
+			mutex_unlock(&ubi->device_mutex);
 			break;
 		default:
 			err = -EINVAL;
@@ -810,9 +812,9 @@
 			re->desc->vol->vol_id, re->desc->vol->name);
 	}
 
-	mutex_lock(&ubi->volumes_mutex);
+	mutex_lock(&ubi->device_mutex);
 	err = ubi_rename_volumes(ubi, &rename_list);
-	mutex_unlock(&ubi->volumes_mutex);
+	mutex_unlock(&ubi->device_mutex);
 
 out_free:
 	list_for_each_entry_safe(re, re1, &rename_list, list) {
@@ -856,9 +858,9 @@
 		if (err)
 			break;
 
-		mutex_lock(&ubi->volumes_mutex);
+		mutex_lock(&ubi->device_mutex);
 		err = ubi_create_volume(ubi, &req);
-		mutex_unlock(&ubi->volumes_mutex);
+		mutex_unlock(&ubi->device_mutex);
 		if (err)
 			break;
 
@@ -887,9 +889,9 @@
 			break;
 		}
 
-		mutex_lock(&ubi->volumes_mutex);
+		mutex_lock(&ubi->device_mutex);
 		err = ubi_remove_volume(desc, 0);
-		mutex_unlock(&ubi->volumes_mutex);
+		mutex_unlock(&ubi->device_mutex);
 
 		/*
 		 * The volume is deleted (unless an error occurred), and the
@@ -926,9 +928,9 @@
 		pebs = div_u64(req.bytes + desc->vol->usable_leb_size - 1,
 			       desc->vol->usable_leb_size);
 
-		mutex_lock(&ubi->volumes_mutex);
+		mutex_lock(&ubi->device_mutex);
 		err = ubi_resize_volume(desc, pebs);
-		mutex_unlock(&ubi->volumes_mutex);
+		mutex_unlock(&ubi->device_mutex);
 		ubi_close_volume(desc);
 		break;
 	}
@@ -952,9 +954,7 @@
 			break;
 		}
 
-		mutex_lock(&ubi->mult_mutex);
 		err = rename_volumes(ubi, req);
-		mutex_unlock(&ubi->mult_mutex);
 		kfree(req);
 		break;
 	}
diff --git a/drivers/mtd/ubi/eba.c b/drivers/mtd/ubi/eba.c
index 25def34..0f2034c 100644
--- a/drivers/mtd/ubi/eba.c
+++ b/drivers/mtd/ubi/eba.c
@@ -419,8 +419,9 @@
 				 * not implemented.
 				 */
 				if (err == UBI_IO_BAD_VID_HDR) {
-					ubi_warn("bad VID header at PEB %d, LEB"
-						 "%d:%d", pnum, vol_id, lnum);
+					ubi_warn("corrupted VID header at PEB "
+						 "%d, LEB %d:%d", pnum, vol_id,
+						 lnum);
 					err = -EBADMSG;
 				} else
 					ubi_ro_mode(ubi);
@@ -940,6 +941,33 @@
 }
 
 /**
+ * is_error_sane - check whether a read error is sane.
+ * @err: code of the error happened during reading
+ *
+ * This is a helper function for 'ubi_eba_copy_leb()' which is called when we
+ * cannot read data from the target PEB (an error @err happened). If the error
+ * code is sane, then we treat this error as non-fatal. Otherwise the error is
+ * fatal and UBI will be switched to R/O mode later.
+ *
+ * The idea is that we try not to switch to R/O mode if the read error is
+ * something which suggests there was a real read problem. E.g., %-EIO. Or a
+ * memory allocation failed (-%ENOMEM). Otherwise, it is safer to switch to R/O
+ * mode, simply because we do not know what happened at the MTD level, and we
+ * cannot handle this. E.g., the underlying driver may have become crazy, and
+ * it is safer to switch to R/O mode to preserve the data.
+ *
+ * And bear in mind, this is about reading from the target PEB, i.e. the PEB
+ * which we have just written.
+ */
+static int is_error_sane(int err)
+{
+	if (err == -EIO || err == -ENOMEM || err == UBI_IO_BAD_VID_HDR ||
+	    err == -ETIMEDOUT)
+		return 0;
+	return 1;
+}
+
+/**
  * ubi_eba_copy_leb - copy logical eraseblock.
  * @ubi: UBI device description object
  * @from: physical eraseblock number from where to copy
@@ -950,12 +978,7 @@
  * physical eraseblock @to. The @vid_hdr buffer may be changed by this
  * function. Returns:
  *   o %0 in case of success;
- *   o %1 if the operation was canceled because the volume is being deleted
- *        or because the PEB was put meanwhile;
- *   o %2 if the operation was canceled because there was a write error to the
- *        target PEB;
- *   o %-EAGAIN if the operation was canceled because a bit-flip was detected
- *     in the target PEB;
+ *   o %MOVE_CANCEL_RACE, %MOVE_TARGET_WR_ERR, %MOVE_CANCEL_BITFLIPS, etc;
  *   o a negative error code in case of failure.
  */
 int ubi_eba_copy_leb(struct ubi_device *ubi, int from, int to,
@@ -968,7 +991,7 @@
 	vol_id = be32_to_cpu(vid_hdr->vol_id);
 	lnum = be32_to_cpu(vid_hdr->lnum);
 
-	dbg_eba("copy LEB %d:%d, PEB %d to PEB %d", vol_id, lnum, from, to);
+	dbg_wl("copy LEB %d:%d, PEB %d to PEB %d", vol_id, lnum, from, to);
 
 	if (vid_hdr->vol_type == UBI_VID_STATIC) {
 		data_size = be32_to_cpu(vid_hdr->data_size);
@@ -986,13 +1009,12 @@
 	 * be locked in 'ubi_wl_put_peb()' and wait for the WL worker to finish.
 	 */
 	vol = ubi->volumes[idx];
+	spin_unlock(&ubi->volumes_lock);
 	if (!vol) {
 		/* No need to do further work, cancel */
-		dbg_eba("volume %d is being removed, cancel", vol_id);
-		spin_unlock(&ubi->volumes_lock);
-		return 1;
+		dbg_wl("volume %d is being removed, cancel", vol_id);
+		return MOVE_CANCEL_RACE;
 	}
-	spin_unlock(&ubi->volumes_lock);
 
 	/*
 	 * We do not want anybody to write to this logical eraseblock while we
@@ -1004,12 +1026,13 @@
 	 * (@from). This task locks the LEB and goes sleep in the
 	 * 'ubi_wl_put_peb()' function on the @ubi->move_mutex. In turn, we are
 	 * holding @ubi->move_mutex and go sleep on the LEB lock. So, if the
-	 * LEB is already locked, we just do not move it and return %1.
+	 * LEB is already locked, we just do not move it and return
+	 * %MOVE_CANCEL_RACE, which means that UBI will re-try, but later.
 	 */
 	err = leb_write_trylock(ubi, vol_id, lnum);
 	if (err) {
-		dbg_eba("contention on LEB %d:%d, cancel", vol_id, lnum);
-		return err;
+		dbg_wl("contention on LEB %d:%d, cancel", vol_id, lnum);
+		return MOVE_CANCEL_RACE;
 	}
 
 	/*
@@ -1018,25 +1041,26 @@
 	 * cancel it.
 	 */
 	if (vol->eba_tbl[lnum] != from) {
-		dbg_eba("LEB %d:%d is no longer mapped to PEB %d, mapped to "
-			"PEB %d, cancel", vol_id, lnum, from,
-			vol->eba_tbl[lnum]);
-		err = 1;
+		dbg_wl("LEB %d:%d is no longer mapped to PEB %d, mapped to "
+		       "PEB %d, cancel", vol_id, lnum, from,
+		       vol->eba_tbl[lnum]);
+		err = MOVE_CANCEL_RACE;
 		goto out_unlock_leb;
 	}
 
 	/*
 	 * OK, now the LEB is locked and we can safely start moving it. Since
-	 * this function utilizes the @ubi->peb1_buf buffer which is shared
-	 * with some other functions, so lock the buffer by taking the
+	 * this function utilizes the @ubi->peb_buf1 buffer which is shared
+	 * with some other functions - we lock the buffer by taking the
 	 * @ubi->buf_mutex.
 	 */
 	mutex_lock(&ubi->buf_mutex);
-	dbg_eba("read %d bytes of data", aldata_size);
+	dbg_wl("read %d bytes of data", aldata_size);
 	err = ubi_io_read_data(ubi, ubi->peb_buf1, from, 0, aldata_size);
 	if (err && err != UBI_IO_BITFLIPS) {
 		ubi_warn("error %d while reading data from PEB %d",
 			 err, from);
+		err = MOVE_SOURCE_RD_ERR;
 		goto out_unlock_buf;
 	}
 
@@ -1059,7 +1083,7 @@
 	cond_resched();
 
 	/*
-	 * It may turn out to me that the whole @from physical eraseblock
+	 * It may turn out to be that the whole @from physical eraseblock
 	 * contains only 0xFF bytes. Then we have to only write the VID header
 	 * and do not write any data. This also means we should not set
 	 * @vid_hdr->copy_flag, @vid_hdr->data_size, and @vid_hdr->data_crc.
@@ -1074,7 +1098,7 @@
 	err = ubi_io_write_vid_hdr(ubi, to, vid_hdr);
 	if (err) {
 		if (err == -EIO)
-			err = 2;
+			err = MOVE_TARGET_WR_ERR;
 		goto out_unlock_buf;
 	}
 
@@ -1083,10 +1107,13 @@
 	/* Read the VID header back and check if it was written correctly */
 	err = ubi_io_read_vid_hdr(ubi, to, vid_hdr, 1);
 	if (err) {
-		if (err != UBI_IO_BITFLIPS)
-			ubi_warn("cannot read VID header back from PEB %d", to);
-		else
-			err = -EAGAIN;
+		if (err != UBI_IO_BITFLIPS) {
+			ubi_warn("error %d while reading VID header back from "
+				  "PEB %d", err, to);
+			if (is_error_sane(err))
+				err = MOVE_TARGET_RD_ERR;
+		} else
+			err = MOVE_CANCEL_BITFLIPS;
 		goto out_unlock_buf;
 	}
 
@@ -1094,7 +1121,7 @@
 		err = ubi_io_write_data(ubi, ubi->peb_buf1, to, 0, aldata_size);
 		if (err) {
 			if (err == -EIO)
-				err = 2;
+				err = MOVE_TARGET_WR_ERR;
 			goto out_unlock_buf;
 		}
 
@@ -1107,11 +1134,13 @@
 
 		err = ubi_io_read_data(ubi, ubi->peb_buf2, to, 0, aldata_size);
 		if (err) {
-			if (err != UBI_IO_BITFLIPS)
-				ubi_warn("cannot read data back from PEB %d",
-					 to);
-			else
-				err = -EAGAIN;
+			if (err != UBI_IO_BITFLIPS) {
+				ubi_warn("error %d while reading data back "
+					 "from PEB %d", err, to);
+				if (is_error_sane(err))
+					err = MOVE_TARGET_RD_ERR;
+			} else
+				err = MOVE_CANCEL_BITFLIPS;
 			goto out_unlock_buf;
 		}
 
diff --git a/drivers/mtd/ubi/gluebi.c b/drivers/mtd/ubi/gluebi.c
index 49cd55a..95aaac0 100644
--- a/drivers/mtd/ubi/gluebi.c
+++ b/drivers/mtd/ubi/gluebi.c
@@ -19,17 +19,71 @@
  */
 
 /*
- * This file includes implementation of fake MTD devices for each UBI volume.
- * This sounds strange, but it is in fact quite useful to make MTD-oriented
- * software (including all the legacy software) to work on top of UBI.
+ * This is a small driver which implements fake MTD devices on top of UBI
+ * volumes. This sounds strange, but it is in fact quite useful to make
+ * MTD-oriented software (including all the legacy software) work on top of
+ * UBI.
  *
  * Gluebi emulates MTD devices of "MTD_UBIVOLUME" type. Their minimal I/O unit
- * size (mtd->writesize) is equivalent to the UBI minimal I/O unit. The
+ * size (@mtd->writesize) is equivalent to the UBI minimal I/O unit. The
  * eraseblock size is equivalent to the logical eraseblock size of the volume.
  */
 
+#include <linux/err.h>
+#include <linux/list.h>
+#include <linux/sched.h>
 #include <linux/math64.h>
-#include "ubi.h"
+#include <linux/module.h>
+#include <linux/mutex.h>
+#include <linux/mtd/ubi.h>
+#include <linux/mtd/mtd.h>
+#include "ubi-media.h"
+
+#define err_msg(fmt, ...)                                   \
+	printk(KERN_DEBUG "gluebi (pid %d): %s: " fmt "\n", \
+	       current->pid, __func__, ##__VA_ARGS__)
+
+/**
+ * struct gluebi_device - a gluebi device description data structure.
+ * @mtd: emulated MTD device description object
+ * @refcnt: gluebi device reference count
+ * @desc: UBI volume descriptor
+ * @ubi_num: UBI device number this gluebi device works on
+ * @vol_id: ID of UBI volume this gluebi device works on
+ * @list: link in a list of gluebi devices
+ */
+struct gluebi_device {
+	struct mtd_info mtd;
+	int refcnt;
+	struct ubi_volume_desc *desc;
+	int ubi_num;
+	int vol_id;
+	struct list_head list;
+};
+
+/* List of all gluebi devices */
+static LIST_HEAD(gluebi_devices);
+static DEFINE_MUTEX(devices_mutex);
+
+/**
+ * find_gluebi_nolock - find a gluebi device.
+ * @ubi_num: UBI device number
+ * @vol_id: volume ID
+ *
+ * This function seraches for gluebi device corresponding to UBI device
+ * @ubi_num and UBI volume @vol_id. Returns the gluebi device description
+ * object in case of success and %NULL in case of failure. The caller has to
+ * have the &devices_mutex locked.
+ */
+static struct gluebi_device *find_gluebi_nolock(int ubi_num, int vol_id)
+{
+	struct gluebi_device *gluebi;
+
+	list_for_each_entry(gluebi, &gluebi_devices, list)
+		if (gluebi->ubi_num == ubi_num && gluebi->vol_id == vol_id)
+			return gluebi;
+	return NULL;
+}
 
 /**
  * gluebi_get_device - get MTD device reference.
@@ -41,15 +95,18 @@
  */
 static int gluebi_get_device(struct mtd_info *mtd)
 {
-	struct ubi_volume *vol;
+	struct gluebi_device *gluebi;
+	int ubi_mode = UBI_READONLY;
 
-	vol = container_of(mtd, struct ubi_volume, gluebi_mtd);
+	if (!try_module_get(THIS_MODULE))
+		return -ENODEV;
 
-	/*
-	 * We do not introduce locks for gluebi reference count because the
-	 * get_device()/put_device() calls are already serialized at MTD.
-	 */
-	if (vol->gluebi_refcount > 0) {
+	if (mtd->flags & MTD_WRITEABLE)
+		ubi_mode = UBI_READWRITE;
+
+	gluebi = container_of(mtd, struct gluebi_device, mtd);
+	mutex_lock(&devices_mutex);
+	if (gluebi->refcnt > 0) {
 		/*
 		 * The MTD device is already referenced and this is just one
 		 * more reference. MTD allows many users to open the same
@@ -58,7 +115,8 @@
 		 * open the UBI volume again - just increase the reference
 		 * counter and return.
 		 */
-		vol->gluebi_refcount += 1;
+		gluebi->refcnt += 1;
+		mutex_unlock(&devices_mutex);
 		return 0;
 	}
 
@@ -66,11 +124,15 @@
 	 * This is the first reference to this UBI volume via the MTD device
 	 * interface. Open the corresponding volume in read-write mode.
 	 */
-	vol->gluebi_desc = ubi_open_volume(vol->ubi->ubi_num, vol->vol_id,
-					   UBI_READWRITE);
-	if (IS_ERR(vol->gluebi_desc))
-		return PTR_ERR(vol->gluebi_desc);
-	vol->gluebi_refcount += 1;
+	gluebi->desc = ubi_open_volume(gluebi->ubi_num, gluebi->vol_id,
+				       ubi_mode);
+	if (IS_ERR(gluebi->desc)) {
+		mutex_unlock(&devices_mutex);
+		module_put(THIS_MODULE);
+		return PTR_ERR(gluebi->desc);
+	}
+	gluebi->refcnt += 1;
+	mutex_unlock(&devices_mutex);
 	return 0;
 }
 
@@ -83,13 +145,15 @@
  */
 static void gluebi_put_device(struct mtd_info *mtd)
 {
-	struct ubi_volume *vol;
+	struct gluebi_device *gluebi;
 
-	vol = container_of(mtd, struct ubi_volume, gluebi_mtd);
-	vol->gluebi_refcount -= 1;
-	ubi_assert(vol->gluebi_refcount >= 0);
-	if (vol->gluebi_refcount == 0)
-		ubi_close_volume(vol->gluebi_desc);
+	gluebi = container_of(mtd, struct gluebi_device, mtd);
+	mutex_lock(&devices_mutex);
+	gluebi->refcnt -= 1;
+	if (gluebi->refcnt == 0)
+		ubi_close_volume(gluebi->desc);
+	module_put(THIS_MODULE);
+	mutex_unlock(&devices_mutex);
 }
 
 /**
@@ -107,16 +171,12 @@
 		       size_t *retlen, unsigned char *buf)
 {
 	int err = 0, lnum, offs, total_read;
-	struct ubi_volume *vol;
-	struct ubi_device *ubi;
-
-	dbg_gen("read %zd bytes from offset %lld", len, from);
+	struct gluebi_device *gluebi;
 
 	if (len < 0 || from < 0 || from + len > mtd->size)
 		return -EINVAL;
 
-	vol = container_of(mtd, struct ubi_volume, gluebi_mtd);
-	ubi = vol->ubi;
+	gluebi = container_of(mtd, struct gluebi_device, mtd);
 
 	lnum = div_u64_rem(from, mtd->erasesize, &offs);
 	total_read = len;
@@ -126,7 +186,7 @@
 		if (to_read > total_read)
 			to_read = total_read;
 
-		err = ubi_eba_read_leb(ubi, vol, lnum, buf, offs, to_read, 0);
+		err = ubi_read(gluebi->desc, lnum, buf, offs, to_read);
 		if (err)
 			break;
 
@@ -152,21 +212,17 @@
  * case of failure.
  */
 static int gluebi_write(struct mtd_info *mtd, loff_t to, size_t len,
-		       size_t *retlen, const u_char *buf)
+			size_t *retlen, const u_char *buf)
 {
 	int err = 0, lnum, offs, total_written;
-	struct ubi_volume *vol;
-	struct ubi_device *ubi;
-
-	dbg_gen("write %zd bytes to offset %lld", len, to);
+	struct gluebi_device *gluebi;
 
 	if (len < 0 || to < 0 || len + to > mtd->size)
 		return -EINVAL;
 
-	vol = container_of(mtd, struct ubi_volume, gluebi_mtd);
-	ubi = vol->ubi;
+	gluebi = container_of(mtd, struct gluebi_device, mtd);
 
-	if (ubi->ro_mode)
+	if (!(mtd->flags & MTD_WRITEABLE))
 		return -EROFS;
 
 	lnum = div_u64_rem(to, mtd->erasesize, &offs);
@@ -181,8 +237,7 @@
 		if (to_write > total_written)
 			to_write = total_written;
 
-		err = ubi_eba_write_leb(ubi, vol, lnum, buf, offs, to_write,
-					UBI_UNKNOWN);
+		err = ubi_write(gluebi->desc, lnum, buf, offs, to_write);
 		if (err)
 			break;
 
@@ -207,41 +262,36 @@
 static int gluebi_erase(struct mtd_info *mtd, struct erase_info *instr)
 {
 	int err, i, lnum, count;
-	struct ubi_volume *vol;
-	struct ubi_device *ubi;
-
-	dbg_gen("erase %llu bytes at offset %llu", (unsigned long long)instr->len,
-		 (unsigned long long)instr->addr);
+	struct gluebi_device *gluebi;
 
 	if (instr->addr < 0 || instr->addr > mtd->size - mtd->erasesize)
 		return -EINVAL;
-
 	if (instr->len < 0 || instr->addr + instr->len > mtd->size)
 		return -EINVAL;
-
 	if (mtd_mod_by_ws(instr->addr, mtd) || mtd_mod_by_ws(instr->len, mtd))
 		return -EINVAL;
 
 	lnum = mtd_div_by_eb(instr->addr, mtd);
 	count = mtd_div_by_eb(instr->len, mtd);
 
-	vol = container_of(mtd, struct ubi_volume, gluebi_mtd);
-	ubi = vol->ubi;
+	gluebi = container_of(mtd, struct gluebi_device, mtd);
 
-	if (ubi->ro_mode)
+	if (!(mtd->flags & MTD_WRITEABLE))
 		return -EROFS;
 
-	for (i = 0; i < count; i++) {
-		err = ubi_eba_unmap_leb(ubi, vol, lnum + i);
+	for (i = 0; i < count - 1; i++) {
+		err = ubi_leb_unmap(gluebi->desc, lnum + i);
 		if (err)
 			goto out_err;
 	}
-
 	/*
 	 * MTD erase operations are synchronous, so we have to make sure the
 	 * physical eraseblock is wiped out.
+	 *
+	 * Thus, perform leb_erase instead of leb_unmap operation - leb_erase
+	 * will wait for the end of operations
 	 */
-	err = ubi_wl_flush(ubi);
+	err = ubi_leb_erase(gluebi->desc, lnum + i);
 	if (err)
 		goto out_err;
 
@@ -256,28 +306,38 @@
 }
 
 /**
- * ubi_create_gluebi - initialize gluebi for an UBI volume.
- * @ubi: UBI device description object
- * @vol: volume description object
+ * gluebi_create - create a gluebi device for an UBI volume.
+ * @di: UBI device description object
+ * @vi: UBI volume description object
  *
- * This function is called when an UBI volume is created in order to create
+ * This function is called when a new UBI volume is created in order to create
  * corresponding fake MTD device. Returns zero in case of success and a
  * negative error code in case of failure.
  */
-int ubi_create_gluebi(struct ubi_device *ubi, struct ubi_volume *vol)
+static int gluebi_create(struct ubi_device_info *di,
+			 struct ubi_volume_info *vi)
 {
-	struct mtd_info *mtd = &vol->gluebi_mtd;
+	struct gluebi_device *gluebi, *g;
+	struct mtd_info *mtd;
 
-	mtd->name = kmemdup(vol->name, vol->name_len + 1, GFP_KERNEL);
-	if (!mtd->name)
+	gluebi = kzalloc(sizeof(struct gluebi_device), GFP_KERNEL);
+	if (!gluebi)
 		return -ENOMEM;
 
+	mtd = &gluebi->mtd;
+	mtd->name = kmemdup(vi->name, vi->name_len + 1, GFP_KERNEL);
+	if (!mtd->name) {
+		kfree(gluebi);
+		return -ENOMEM;
+	}
+
+	gluebi->vol_id = vi->vol_id;
 	mtd->type = MTD_UBIVOLUME;
-	if (!ubi->ro_mode)
+	if (!di->ro_mode)
 		mtd->flags = MTD_WRITEABLE;
-	mtd->writesize  = ubi->min_io_size;
 	mtd->owner      = THIS_MODULE;
-	mtd->erasesize  = vol->usable_leb_size;
+	mtd->writesize  = di->min_io_size;
+	mtd->erasesize  = vi->usable_leb_size;
 	mtd->read       = gluebi_read;
 	mtd->write      = gluebi_write;
 	mtd->erase      = gluebi_erase;
@@ -285,60 +345,196 @@
 	mtd->put_device = gluebi_put_device;
 
 	/*
-	 * In case of dynamic volume, MTD device size is just volume size. In
+	 * In case of dynamic a volume, MTD device size is just volume size. In
 	 * case of a static volume the size is equivalent to the amount of data
 	 * bytes.
 	 */
-	if (vol->vol_type == UBI_DYNAMIC_VOLUME)
-		mtd->size = (long long)vol->usable_leb_size * vol->reserved_pebs;
+	if (vi->vol_type == UBI_DYNAMIC_VOLUME)
+		mtd->size = (unsigned long long)vi->usable_leb_size * vi->size;
 	else
-		mtd->size = vol->used_bytes;
+		mtd->size = vi->used_bytes;
+
+	/* Just a sanity check - make sure this gluebi device does not exist */
+	mutex_lock(&devices_mutex);
+	g = find_gluebi_nolock(vi->ubi_num, vi->vol_id);
+	if (g)
+		err_msg("gluebi MTD device %d form UBI device %d volume %d "
+			"already exists", g->mtd.index, vi->ubi_num,
+			vi->vol_id);
+	mutex_unlock(&devices_mutex);
 
 	if (add_mtd_device(mtd)) {
-		ubi_err("cannot not add MTD device");
+		err_msg("cannot add MTD device");
 		kfree(mtd->name);
+		kfree(gluebi);
 		return -ENFILE;
 	}
 
-	dbg_gen("added mtd%d (\"%s\"), size %llu, EB size %u",
-		mtd->index, mtd->name, (unsigned long long)mtd->size, mtd->erasesize);
+	mutex_lock(&devices_mutex);
+	list_add_tail(&gluebi->list, &gluebi_devices);
+	mutex_unlock(&devices_mutex);
 	return 0;
 }
 
 /**
- * ubi_destroy_gluebi - close gluebi for an UBI volume.
- * @vol: volume description object
+ * gluebi_remove - remove a gluebi device.
+ * @vi: UBI volume description object
  *
- * This function is called when an UBI volume is removed in order to remove
+ * This function is called when an UBI volume is removed and it removes
  * corresponding fake MTD device. Returns zero in case of success and a
  * negative error code in case of failure.
  */
-int ubi_destroy_gluebi(struct ubi_volume *vol)
+static int gluebi_remove(struct ubi_volume_info *vi)
 {
-	int err;
-	struct mtd_info *mtd = &vol->gluebi_mtd;
+	int err = 0;
+	struct mtd_info *mtd;
+	struct gluebi_device *gluebi;
 
-	dbg_gen("remove mtd%d", mtd->index);
-	err = del_mtd_device(mtd);
+	mutex_lock(&devices_mutex);
+	gluebi = find_gluebi_nolock(vi->ubi_num, vi->vol_id);
+	if (!gluebi) {
+		err_msg("got remove notification for unknown UBI device %d "
+			"volume %d", vi->ubi_num, vi->vol_id);
+		err = -ENOENT;
+	} else if (gluebi->refcnt)
+		err = -EBUSY;
+	else
+		list_del(&gluebi->list);
+	mutex_unlock(&devices_mutex);
 	if (err)
 		return err;
+
+	mtd = &gluebi->mtd;
+	err = del_mtd_device(mtd);
+	if (err) {
+		err_msg("cannot remove fake MTD device %d, UBI device %d, "
+			"volume %d, error %d", mtd->index, gluebi->ubi_num,
+			gluebi->vol_id, err);
+		mutex_lock(&devices_mutex);
+		list_add_tail(&gluebi->list, &gluebi_devices);
+		mutex_unlock(&devices_mutex);
+		return err;
+	}
+
 	kfree(mtd->name);
+	kfree(gluebi);
 	return 0;
 }
 
 /**
- * ubi_gluebi_updated - UBI volume was updated notifier.
- * @vol: volume description object
+ * gluebi_updated - UBI volume was updated notifier.
+ * @vi: volume info structure
  *
- * This function is called every time an UBI volume is updated. This function
- * does nothing if volume @vol is dynamic, and changes MTD device size if the
+ * This function is called every time an UBI volume is updated. It does nothing
+ * if te volume @vol is dynamic, and changes MTD device size if the
  * volume is static. This is needed because static volumes cannot be read past
- * data they contain.
+ * data they contain. This function returns zero in case of success and a
+ * negative error code in case of error.
  */
-void ubi_gluebi_updated(struct ubi_volume *vol)
+static int gluebi_updated(struct ubi_volume_info *vi)
 {
-	struct mtd_info *mtd = &vol->gluebi_mtd;
+	struct gluebi_device *gluebi;
 
-	if (vol->vol_type == UBI_STATIC_VOLUME)
-		mtd->size = vol->used_bytes;
+	mutex_lock(&devices_mutex);
+	gluebi = find_gluebi_nolock(vi->ubi_num, vi->vol_id);
+	if (!gluebi) {
+		mutex_unlock(&devices_mutex);
+		err_msg("got update notification for unknown UBI device %d "
+			"volume %d", vi->ubi_num, vi->vol_id);
+		return -ENOENT;
+	}
+
+	if (vi->vol_type == UBI_STATIC_VOLUME)
+		gluebi->mtd.size = vi->used_bytes;
+	mutex_unlock(&devices_mutex);
+	return 0;
 }
+
+/**
+ * gluebi_resized - UBI volume was re-sized notifier.
+ * @vi: volume info structure
+ *
+ * This function is called every time an UBI volume is re-size. It changes the
+ * corresponding fake MTD device size. This function returns zero in case of
+ * success and a negative error code in case of error.
+ */
+static int gluebi_resized(struct ubi_volume_info *vi)
+{
+	struct gluebi_device *gluebi;
+
+	mutex_lock(&devices_mutex);
+	gluebi = find_gluebi_nolock(vi->ubi_num, vi->vol_id);
+	if (!gluebi) {
+		mutex_unlock(&devices_mutex);
+		err_msg("got update notification for unknown UBI device %d "
+			"volume %d", vi->ubi_num, vi->vol_id);
+		return -ENOENT;
+	}
+	gluebi->mtd.size = vi->used_bytes;
+	mutex_unlock(&devices_mutex);
+	return 0;
+}
+
+/**
+ * gluebi_notify - UBI notification handler.
+ * @nb: registered notifier block
+ * @l: notification type
+ * @ptr: pointer to the &struct ubi_notification object
+ */
+static int gluebi_notify(struct notifier_block *nb, unsigned long l,
+			 void *ns_ptr)
+{
+	struct ubi_notification *nt = ns_ptr;
+
+	switch (l) {
+	case UBI_VOLUME_ADDED:
+		gluebi_create(&nt->di, &nt->vi);
+		break;
+	case UBI_VOLUME_REMOVED:
+		gluebi_remove(&nt->vi);
+		break;
+	case UBI_VOLUME_RESIZED:
+		gluebi_resized(&nt->vi);
+		break;
+	case UBI_VOLUME_UPDATED:
+		gluebi_updated(&nt->vi);
+		break;
+	default:
+		break;
+	}
+	return NOTIFY_OK;
+}
+
+static struct notifier_block gluebi_notifier = {
+	.notifier_call	= gluebi_notify,
+};
+
+static int __init ubi_gluebi_init(void)
+{
+	return ubi_register_volume_notifier(&gluebi_notifier, 0);
+}
+
+static void __exit ubi_gluebi_exit(void)
+{
+	struct gluebi_device *gluebi, *g;
+
+	list_for_each_entry_safe(gluebi, g, &gluebi_devices, list) {
+		int err;
+		struct mtd_info *mtd = &gluebi->mtd;
+
+		err = del_mtd_device(mtd);
+		if (err)
+			err_msg("error %d while removing gluebi MTD device %d, "
+				"UBI device %d, volume %d - ignoring", err,
+				mtd->index, gluebi->ubi_num, gluebi->vol_id);
+		kfree(mtd->name);
+		kfree(gluebi);
+	}
+	ubi_unregister_volume_notifier(&gluebi_notifier);
+}
+
+module_init(ubi_gluebi_init);
+module_exit(ubi_gluebi_exit);
+MODULE_DESCRIPTION("MTD emulation layer over UBI volumes");
+MODULE_AUTHOR("Artem Bityutskiy, Joern Engel");
+MODULE_LICENSE("GPL");
diff --git a/drivers/mtd/ubi/io.c b/drivers/mtd/ubi/io.c
index fe81039..effaff2 100644
--- a/drivers/mtd/ubi/io.c
+++ b/drivers/mtd/ubi/io.c
@@ -100,6 +100,7 @@
 				  const struct ubi_vid_hdr *vid_hdr);
 static int paranoid_check_all_ff(struct ubi_device *ubi, int pnum, int offset,
 				 int len);
+static int paranoid_check_empty(struct ubi_device *ubi, int pnum);
 #else
 #define paranoid_check_not_bad(ubi, pnum) 0
 #define paranoid_check_peb_ec_hdr(ubi, pnum)  0
@@ -107,6 +108,7 @@
 #define paranoid_check_peb_vid_hdr(ubi, pnum) 0
 #define paranoid_check_vid_hdr(ubi, pnum, vid_hdr) 0
 #define paranoid_check_all_ff(ubi, pnum, offset, len) 0
+#define paranoid_check_empty(ubi, pnum) 0
 #endif
 
 /**
@@ -670,11 +672,6 @@
 		if (read_err != -EBADMSG &&
 		    check_pattern(ec_hdr, 0xFF, UBI_EC_HDR_SIZE)) {
 			/* The physical eraseblock is supposedly empty */
-
-			/*
-			 * The below is just a paranoid check, it has to be
-			 * compiled out if paranoid checks are disabled.
-			 */
 			err = paranoid_check_all_ff(ubi, pnum, 0,
 						    ubi->peb_size);
 			if (err)
@@ -902,7 +899,7 @@
  * o %UBI_IO_BITFLIPS if the CRC is correct, but bit-flips were detected
  *   and corrected by the flash driver; this is harmless but may indicate that
  *   this eraseblock may become bad soon;
- * o %UBI_IO_BAD_VID_HRD if the volume identifier header is corrupted (a CRC
+ * o %UBI_IO_BAD_VID_HDR if the volume identifier header is corrupted (a CRC
  *   error detected);
  * o %UBI_IO_PEB_FREE if the physical eraseblock is free (i.e., there is no VID
  *   header there);
@@ -955,8 +952,7 @@
 			 * The below is just a paranoid check, it has to be
 			 * compiled out if paranoid checks are disabled.
 			 */
-			err = paranoid_check_all_ff(ubi, pnum, ubi->leb_start,
-						    ubi->leb_size);
+			err = paranoid_check_empty(ubi, pnum);
 			if (err)
 				return err > 0 ? UBI_IO_BAD_VID_HDR : err;
 
@@ -1280,4 +1276,74 @@
 	return err;
 }
 
+/**
+ * paranoid_check_empty - whether a PEB is empty.
+ * @ubi: UBI device description object
+ * @pnum: the physical eraseblock number to check
+ *
+ * This function makes sure PEB @pnum is empty, which means it contains only
+ * %0xFF data bytes. Returns zero if the PEB is empty, %1 if not, and a
+ * negative error code in case of failure.
+ *
+ * Empty PEBs have the EC header, and do not have the VID header. The caller of
+ * this function should have already made sure the PEB does not have the VID
+ * header. However, this function re-checks that, because it is possible that
+ * the header and data has already been written to the PEB.
+ *
+ * Let's consider a possible scenario. Suppose there are 2 tasks - A and B.
+ * Task A is in 'wear_leveling_worker()'. It is reading VID header of PEB X to
+ * find which LEB it corresponds to. PEB X is currently unmapped, and has no
+ * VID header. Task B is trying to write to PEB X.
+ *
+ * Task A: in 'ubi_io_read_vid_hdr()': reads the VID header from PEB X. The
+ *         read data contain all 0xFF bytes;
+ * Task B: writes VID header and some data to PEB X;
+ * Task A: assumes PEB X is empty, calls 'paranoid_check_empty()'. And if we
+ *         do not re-read the VID header, and do not cancel the checking if it
+ *         is there, we fail.
+ */
+static int paranoid_check_empty(struct ubi_device *ubi, int pnum)
+{
+	int err, offs = ubi->vid_hdr_aloffset, len = ubi->vid_hdr_alsize;
+	size_t read;
+	uint32_t magic;
+	const struct ubi_vid_hdr *vid_hdr;
+
+	mutex_lock(&ubi->dbg_buf_mutex);
+	err = ubi->mtd->read(ubi->mtd, offs, len, &read, ubi->dbg_peb_buf);
+	if (err && err != -EUCLEAN) {
+		ubi_err("error %d while reading %d bytes from PEB %d:%d, "
+			"read %zd bytes", err, len, pnum, offs, read);
+		goto error;
+	}
+
+	vid_hdr = ubi->dbg_peb_buf;
+	magic = be32_to_cpu(vid_hdr->magic);
+	if (magic == UBI_VID_HDR_MAGIC)
+		/* The PEB contains VID header, so it is not empty */
+		goto out;
+
+	err = check_pattern(ubi->dbg_peb_buf, 0xFF, len);
+	if (err == 0) {
+		ubi_err("flash region at PEB %d:%d, length %d does not "
+			"contain all 0xFF bytes", pnum, offs, len);
+		goto fail;
+	}
+
+out:
+	mutex_unlock(&ubi->dbg_buf_mutex);
+	return 0;
+
+fail:
+	ubi_err("paranoid check failed for PEB %d", pnum);
+	ubi_msg("hex dump of the %d-%d region", offs, offs + len);
+	print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
+		       ubi->dbg_peb_buf, len, 1);
+	err = 1;
+error:
+	ubi_dbg_dump_stack();
+	mutex_unlock(&ubi->dbg_buf_mutex);
+	return err;
+}
+
 #endif /* CONFIG_MTD_UBI_DEBUG_PARANOID */
diff --git a/drivers/mtd/ubi/kapi.c b/drivers/mtd/ubi/kapi.c
index 4abbe57..88a72e9 100644
--- a/drivers/mtd/ubi/kapi.c
+++ b/drivers/mtd/ubi/kapi.c
@@ -26,6 +26,24 @@
 #include "ubi.h"
 
 /**
+ * ubi_do_get_device_info - get information about UBI device.
+ * @ubi: UBI device description object
+ * @di: the information is stored here
+ *
+ * This function is the same as 'ubi_get_device_info()', but it assumes the UBI
+ * device is locked and cannot disappear.
+ */
+void ubi_do_get_device_info(struct ubi_device *ubi, struct ubi_device_info *di)
+{
+	di->ubi_num = ubi->ubi_num;
+	di->leb_size = ubi->leb_size;
+	di->min_io_size = ubi->min_io_size;
+	di->ro_mode = ubi->ro_mode;
+	di->cdev = ubi->cdev.dev;
+}
+EXPORT_SYMBOL_GPL(ubi_do_get_device_info);
+
+/**
  * ubi_get_device_info - get information about UBI device.
  * @ubi_num: UBI device number
  * @di: the information is stored here
@@ -39,33 +57,24 @@
 
 	if (ubi_num < 0 || ubi_num >= UBI_MAX_DEVICES)
 		return -EINVAL;
-
 	ubi = ubi_get_device(ubi_num);
 	if (!ubi)
 		return -ENODEV;
-
-	di->ubi_num = ubi->ubi_num;
-	di->leb_size = ubi->leb_size;
-	di->min_io_size = ubi->min_io_size;
-	di->ro_mode = ubi->ro_mode;
-	di->cdev = ubi->cdev.dev;
-
+	ubi_do_get_device_info(ubi, di);
 	ubi_put_device(ubi);
 	return 0;
 }
 EXPORT_SYMBOL_GPL(ubi_get_device_info);
 
 /**
- * ubi_get_volume_info - get information about UBI volume.
- * @desc: volume descriptor
+ * ubi_do_get_volume_info - get information about UBI volume.
+ * @ubi: UBI device description object
+ * @vol: volume description object
  * @vi: the information is stored here
  */
-void ubi_get_volume_info(struct ubi_volume_desc *desc,
-			 struct ubi_volume_info *vi)
+void ubi_do_get_volume_info(struct ubi_device *ubi, struct ubi_volume *vol,
+			    struct ubi_volume_info *vi)
 {
-	const struct ubi_volume *vol = desc->vol;
-	const struct ubi_device *ubi = vol->ubi;
-
 	vi->vol_id = vol->vol_id;
 	vi->ubi_num = ubi->ubi_num;
 	vi->size = vol->reserved_pebs;
@@ -79,6 +88,17 @@
 	vi->name = vol->name;
 	vi->cdev = vol->cdev.dev;
 }
+
+/**
+ * ubi_get_volume_info - get information about UBI volume.
+ * @desc: volume descriptor
+ * @vi: the information is stored here
+ */
+void ubi_get_volume_info(struct ubi_volume_desc *desc,
+			 struct ubi_volume_info *vi)
+{
+	ubi_do_get_volume_info(desc->vol->ubi, desc->vol, vi);
+}
 EXPORT_SYMBOL_GPL(ubi_get_volume_info);
 
 /**
@@ -106,7 +126,7 @@
 	struct ubi_device *ubi;
 	struct ubi_volume *vol;
 
-	dbg_gen("open device %d volume %d, mode %d", ubi_num, vol_id, mode);
+	dbg_gen("open device %d, volume %d, mode %d", ubi_num, vol_id, mode);
 
 	if (ubi_num < 0 || ubi_num >= UBI_MAX_DEVICES)
 		return ERR_PTR(-EINVAL);
@@ -196,6 +216,8 @@
 	kfree(desc);
 out_put_ubi:
 	ubi_put_device(ubi);
+	dbg_err("cannot open device %d, volume %d, error %d",
+		ubi_num, vol_id, err);
 	return ERR_PTR(err);
 }
 EXPORT_SYMBOL_GPL(ubi_open_volume);
@@ -215,7 +237,7 @@
 	struct ubi_device *ubi;
 	struct ubi_volume_desc *ret;
 
-	dbg_gen("open volume %s, mode %d", name, mode);
+	dbg_gen("open device %d, volume %s, mode %d", ubi_num, name, mode);
 
 	if (!name)
 		return ERR_PTR(-EINVAL);
@@ -266,7 +288,8 @@
 	struct ubi_volume *vol = desc->vol;
 	struct ubi_device *ubi = vol->ubi;
 
-	dbg_gen("close volume %d, mode %d", vol->vol_id, desc->mode);
+	dbg_gen("close device %d, volume %d, mode %d",
+		ubi->ubi_num, vol->vol_id, desc->mode);
 
 	spin_lock(&ubi->volumes_lock);
 	switch (desc->mode) {
@@ -558,7 +581,7 @@
 EXPORT_SYMBOL_GPL(ubi_leb_unmap);
 
 /**
- * ubi_leb_map - map logical erasblock to a physical eraseblock.
+ * ubi_leb_map - map logical eraseblock to a physical eraseblock.
  * @desc: volume descriptor
  * @lnum: logical eraseblock number
  * @dtype: expected data type
@@ -656,3 +679,59 @@
 	return 0;
 }
 EXPORT_SYMBOL_GPL(ubi_sync);
+
+BLOCKING_NOTIFIER_HEAD(ubi_notifiers);
+
+/**
+ * ubi_register_volume_notifier - register a volume notifier.
+ * @nb: the notifier description object
+ * @ignore_existing: if non-zero, do not send "added" notification for all
+ *                   already existing volumes
+ *
+ * This function registers a volume notifier, which means that
+ * 'nb->notifier_call()' will be invoked when an UBI  volume is created,
+ * removed, re-sized, re-named, or updated. The first argument of the function
+ * is the notification type. The second argument is pointer to a
+ * &struct ubi_notification object which describes the notification event.
+ * Using UBI API from the volume notifier is prohibited.
+ *
+ * This function returns zero in case of success and a negative error code
+ * in case of failure.
+ */
+int ubi_register_volume_notifier(struct notifier_block *nb,
+				 int ignore_existing)
+{
+	int err;
+
+	err = blocking_notifier_chain_register(&ubi_notifiers, nb);
+	if (err != 0)
+		return err;
+	if (ignore_existing)
+		return 0;
+
+	/*
+	 * We are going to walk all UBI devices and all volumes, and
+	 * notify the user about existing volumes by the %UBI_VOLUME_ADDED
+	 * event. We have to lock the @ubi_devices_mutex to make sure UBI
+	 * devices do not disappear.
+	 */
+	mutex_lock(&ubi_devices_mutex);
+	ubi_enumerate_volumes(nb);
+	mutex_unlock(&ubi_devices_mutex);
+
+	return err;
+}
+EXPORT_SYMBOL_GPL(ubi_register_volume_notifier);
+
+/**
+ * ubi_unregister_volume_notifier - unregister the volume notifier.
+ * @nb: the notifier description object
+ *
+ * This function unregisters volume notifier @nm and returns zero in case of
+ * success and a negative error code in case of failure.
+ */
+int ubi_unregister_volume_notifier(struct notifier_block *nb)
+{
+	return blocking_notifier_chain_unregister(&ubi_notifiers, nb);
+}
+EXPORT_SYMBOL_GPL(ubi_unregister_volume_notifier);
diff --git a/drivers/mtd/ubi/ubi.h b/drivers/mtd/ubi/ubi.h
index c055511bb..28acd13 100644
--- a/drivers/mtd/ubi/ubi.h
+++ b/drivers/mtd/ubi/ubi.h
@@ -36,6 +36,7 @@
 #include <linux/device.h>
 #include <linux/string.h>
 #include <linux/vmalloc.h>
+#include <linux/notifier.h>
 #include <linux/mtd/mtd.h>
 #include <linux/mtd/ubi.h>
 
@@ -100,6 +101,28 @@
 	UBI_IO_BITFLIPS
 };
 
+/*
+ * Return codes of the 'ubi_eba_copy_leb()' function.
+ *
+ * MOVE_CANCEL_RACE: canceled because the volume is being deleted, the source
+ *                   PEB was put meanwhile, or there is I/O on the source PEB
+ * MOVE_SOURCE_RD_ERR: canceled because there was a read error from the source
+ *                     PEB
+ * MOVE_TARGET_RD_ERR: canceled because there was a read error from the target
+ *                     PEB
+ * MOVE_TARGET_WR_ERR: canceled because there was a write error to the target
+ *                     PEB
+ * MOVE_CANCEL_BITFLIPS: canceled because a bit-flip was detected in the
+ *                       target PEB
+ */
+enum {
+	MOVE_CANCEL_RACE = 1,
+	MOVE_SOURCE_RD_ERR,
+	MOVE_TARGET_RD_ERR,
+	MOVE_TARGET_WR_ERR,
+	MOVE_CANCEL_BITFLIPS,
+};
+
 /**
  * struct ubi_wl_entry - wear-leveling entry.
  * @u.rb: link in the corresponding (free/used) RB-tree
@@ -208,10 +231,6 @@
  * @changing_leb: %1 if the atomic LEB change ioctl command is in progress
  * @direct_writes: %1 if direct writes are enabled for this volume
  *
- * @gluebi_desc: gluebi UBI volume descriptor
- * @gluebi_refcount: reference count of the gluebi MTD device
- * @gluebi_mtd: MTD device description object of the gluebi MTD device
- *
  * The @corrupted field indicates that the volume's contents is corrupted.
  * Since UBI protects only static volumes, this field is not relevant to
  * dynamic volumes - it is user's responsibility to assure their data
@@ -255,17 +274,6 @@
 	unsigned int updating:1;
 	unsigned int changing_leb:1;
 	unsigned int direct_writes:1;
-
-#ifdef CONFIG_MTD_UBI_GLUEBI
-	/*
-	 * Gluebi-related stuff may be compiled out.
-	 * Note: this should not be built into UBI but should be a separate
-	 * ubimtd driver which works on top of UBI and emulates MTD devices.
-	 */
-	struct ubi_volume_desc *gluebi_desc;
-	int gluebi_refcount;
-	struct mtd_info gluebi_mtd;
-#endif
 };
 
 /**
@@ -305,9 +313,9 @@
  * @vtbl_slots: how many slots are available in the volume table
  * @vtbl_size: size of the volume table in bytes
  * @vtbl: in-RAM volume table copy
- * @volumes_mutex: protects on-flash volume table and serializes volume
- *                 changes, like creation, deletion, update, re-size,
- *                 re-name and set property
+ * @device_mutex: protects on-flash volume table and serializes volume
+ *                creation, deletion, update, re-size, re-name and set
+ *                property
  *
  * @max_ec: current highest erase counter value
  * @mean_ec: current mean erase counter value
@@ -318,14 +326,15 @@
  * @alc_mutex: serializes "atomic LEB change" operations
  *
  * @used: RB-tree of used physical eraseblocks
+ * @erroneous: RB-tree of erroneous used physical eraseblocks
  * @free: RB-tree of free physical eraseblocks
  * @scrub: RB-tree of physical eraseblocks which need scrubbing
  * @pq: protection queue (contain physical eraseblocks which are temporarily
  *      protected from the wear-leveling worker)
  * @pq_head: protection queue head
  * @wl_lock: protects the @used, @free, @pq, @pq_head, @lookuptbl, @move_from,
- * 	     @move_to, @move_to_put @erase_pending, @wl_scheduled and @works
- * 	     fields
+ * 	     @move_to, @move_to_put @erase_pending, @wl_scheduled, @works,
+ * 	     @erroneous, and @erroneous_peb_count fields
  * @move_mutex: serializes eraseblock moves
  * @work_sem: synchronizes the WL worker with use tasks
  * @wl_scheduled: non-zero if the wear-leveling was scheduled
@@ -339,12 +348,15 @@
  * @bgt_thread: background thread description object
  * @thread_enabled: if the background thread is enabled
  * @bgt_name: background thread name
+ * @reboot_notifier: notifier to terminate background thread before rebooting
  *
  * @flash_size: underlying MTD device size (in bytes)
  * @peb_count: count of physical eraseblocks on the MTD device
  * @peb_size: physical eraseblock size
  * @bad_peb_count: count of bad physical eraseblocks
  * @good_peb_count: count of good physical eraseblocks
+ * @erroneous_peb_count: count of erroneous physical eraseblocks in @erroneous
+ * @max_erroneous: maximum allowed amount of erroneous physical eraseblocks
  * @min_io_size: minimal input/output unit size of the underlying MTD device
  * @hdrs_min_io_size: minimal I/O unit size used for VID and EC headers
  * @ro_mode: if the UBI device is in read-only mode
@@ -366,7 +378,6 @@
  * @peb_buf2: another buffer of PEB size used for different purposes
  * @buf_mutex: protects @peb_buf1 and @peb_buf2
  * @ckvol_mutex: serializes static volume checking when opening
- * @mult_mutex: serializes operations on multiple volumes, like re-naming
  * @dbg_peb_buf: buffer of PEB size used for debugging
  * @dbg_buf_mutex: protects @dbg_peb_buf
  */
@@ -389,7 +400,7 @@
 	int vtbl_slots;
 	int vtbl_size;
 	struct ubi_vtbl_record *vtbl;
-	struct mutex volumes_mutex;
+	struct mutex device_mutex;
 
 	int max_ec;
 	/* Note, mean_ec is not updated run-time - should be fixed */
@@ -403,6 +414,7 @@
 
 	/* Wear-leveling sub-system's stuff */
 	struct rb_root used;
+	struct rb_root erroneous;
 	struct rb_root free;
 	struct rb_root scrub;
 	struct list_head pq[UBI_PROT_QUEUE_LEN];
@@ -420,6 +432,7 @@
 	struct task_struct *bgt_thread;
 	int thread_enabled;
 	char bgt_name[sizeof(UBI_BGT_NAME_PATTERN)+2];
+	struct notifier_block reboot_notifier;
 
 	/* I/O sub-system's stuff */
 	long long flash_size;
@@ -427,6 +440,8 @@
 	int peb_size;
 	int bad_peb_count;
 	int good_peb_count;
+	int erroneous_peb_count;
+	int max_erroneous;
 	int min_io_size;
 	int hdrs_min_io_size;
 	int ro_mode;
@@ -444,8 +459,7 @@
 	void *peb_buf2;
 	struct mutex buf_mutex;
 	struct mutex ckvol_mutex;
-	struct mutex mult_mutex;
-#ifdef CONFIG_MTD_UBI_DEBUG
+#ifdef CONFIG_MTD_UBI_DEBUG_PARANOID
 	void *dbg_peb_buf;
 	struct mutex dbg_buf_mutex;
 #endif
@@ -457,6 +471,7 @@
 extern const struct file_operations ubi_vol_cdev_operations;
 extern struct class *ubi_class;
 extern struct mutex ubi_devices_mutex;
+extern struct blocking_notifier_head ubi_notifiers;
 
 /* vtbl.c */
 int ubi_change_vtbl_record(struct ubi_device *ubi, int idx,
@@ -489,17 +504,6 @@
 int ubi_check_volume(struct ubi_device *ubi, int vol_id);
 void ubi_calculate_reserved(struct ubi_device *ubi);
 
-/* gluebi.c */
-#ifdef CONFIG_MTD_UBI_GLUEBI
-int ubi_create_gluebi(struct ubi_device *ubi, struct ubi_volume *vol);
-int ubi_destroy_gluebi(struct ubi_volume *vol);
-void ubi_gluebi_updated(struct ubi_volume *vol);
-#else
-#define ubi_create_gluebi(ubi, vol) 0
-#define ubi_destroy_gluebi(vol) 0
-#define ubi_gluebi_updated(vol)
-#endif
-
 /* eba.c */
 int ubi_eba_unmap_leb(struct ubi_device *ubi, struct ubi_volume *vol,
 		      int lnum);
@@ -549,6 +553,16 @@
 void ubi_put_device(struct ubi_device *ubi);
 struct ubi_device *ubi_get_by_major(int major);
 int ubi_major2num(int major);
+int ubi_volume_notify(struct ubi_device *ubi, struct ubi_volume *vol,
+		      int ntype);
+int ubi_notify_all(struct ubi_device *ubi, int ntype,
+		   struct notifier_block *nb);
+int ubi_enumerate_volumes(struct notifier_block *nb);
+
+/* kapi.c */
+void ubi_do_get_device_info(struct ubi_device *ubi, struct ubi_device_info *di);
+void ubi_do_get_volume_info(struct ubi_device *ubi, struct ubi_volume *vol,
+			    struct ubi_volume_info *vi);
 
 /*
  * ubi_rb_for_each_entry - walk an RB-tree.
diff --git a/drivers/mtd/ubi/upd.c b/drivers/mtd/ubi/upd.c
index 6b4d1ae..74fdc40 100644
--- a/drivers/mtd/ubi/upd.c
+++ b/drivers/mtd/ubi/upd.c
@@ -68,10 +68,10 @@
 	       sizeof(struct ubi_vtbl_record));
 	vtbl_rec.upd_marker = 1;
 
-	mutex_lock(&ubi->volumes_mutex);
+	mutex_lock(&ubi->device_mutex);
 	err = ubi_change_vtbl_record(ubi, vol->vol_id, &vtbl_rec);
-	mutex_unlock(&ubi->volumes_mutex);
 	vol->upd_marker = 1;
+	mutex_unlock(&ubi->device_mutex);
 	return err;
 }
 
@@ -109,10 +109,10 @@
 			vol->last_eb_bytes = vol->usable_leb_size;
 	}
 
-	mutex_lock(&ubi->volumes_mutex);
+	mutex_lock(&ubi->device_mutex);
 	err = ubi_change_vtbl_record(ubi, vol->vol_id, &vtbl_rec);
-	mutex_unlock(&ubi->volumes_mutex);
 	vol->upd_marker = 0;
+	mutex_unlock(&ubi->device_mutex);
 	return err;
 }
 
diff --git a/drivers/mtd/ubi/vmt.c b/drivers/mtd/ubi/vmt.c
index df54835..ab64cb5 100644
--- a/drivers/mtd/ubi/vmt.c
+++ b/drivers/mtd/ubi/vmt.c
@@ -198,7 +198,7 @@
  * %UBI_VOL_NUM_AUTO, this function automatically assign ID to the new volume
  * and saves it in @req->vol_id. Returns zero in case of success and a negative
  * error code in case of failure. Note, the caller has to have the
- * @ubi->volumes_mutex locked.
+ * @ubi->device_mutex locked.
  */
 int ubi_create_volume(struct ubi_device *ubi, struct ubi_mkvol_req *req)
 {
@@ -232,8 +232,8 @@
 		req->vol_id = vol_id;
 	}
 
-	dbg_gen("volume ID %d, %llu bytes, type %d, name %s",
-		vol_id, (unsigned long long)req->bytes,
+	dbg_gen("create device %d, volume %d, %llu bytes, type %d, name %s",
+		ubi->ubi_num, vol_id, (unsigned long long)req->bytes,
 		(int)req->vol_type, req->name);
 
 	/* Ensure that this volume does not exist */
@@ -317,10 +317,6 @@
 		goto out_mapping;
 	}
 
-	err = ubi_create_gluebi(ubi, vol);
-	if (err)
-		goto out_cdev;
-
 	vol->dev.release = vol_release;
 	vol->dev.parent = &ubi->dev;
 	vol->dev.devt = dev;
@@ -330,7 +326,7 @@
 	err = device_register(&vol->dev);
 	if (err) {
 		ubi_err("cannot register device");
-		goto out_gluebi;
+		goto out_cdev;
 	}
 
 	err = volume_sysfs_init(ubi, vol);
@@ -358,7 +354,9 @@
 	ubi->vol_count += 1;
 	spin_unlock(&ubi->volumes_lock);
 
-	err = paranoid_check_volumes(ubi);
+	ubi_volume_notify(ubi, vol, UBI_VOLUME_ADDED);
+	if (paranoid_check_volumes(ubi))
+		dbg_err("check failed while creating volume %d", vol_id);
 	return err;
 
 out_sysfs:
@@ -373,10 +371,6 @@
 	do_free = 0;
 	get_device(&vol->dev);
 	volume_sysfs_close(vol);
-out_gluebi:
-	if (ubi_destroy_gluebi(vol))
-		dbg_err("cannot destroy gluebi for volume %d:%d",
-			ubi->ubi_num, vol_id);
 out_cdev:
 	cdev_del(&vol->cdev);
 out_mapping:
@@ -403,7 +397,7 @@
  *
  * This function removes volume described by @desc. The volume has to be opened
  * in "exclusive" mode. Returns zero in case of success and a negative error
- * code in case of failure. The caller has to have the @ubi->volumes_mutex
+ * code in case of failure. The caller has to have the @ubi->device_mutex
  * locked.
  */
 int ubi_remove_volume(struct ubi_volume_desc *desc, int no_vtbl)
@@ -412,7 +406,7 @@
 	struct ubi_device *ubi = vol->ubi;
 	int i, err, vol_id = vol->vol_id, reserved_pebs = vol->reserved_pebs;
 
-	dbg_gen("remove UBI volume %d", vol_id);
+	dbg_gen("remove device %d, volume %d", ubi->ubi_num, vol_id);
 	ubi_assert(desc->mode == UBI_EXCLUSIVE);
 	ubi_assert(vol == ubi->volumes[vol_id]);
 
@@ -431,10 +425,6 @@
 	ubi->volumes[vol_id] = NULL;
 	spin_unlock(&ubi->volumes_lock);
 
-	err = ubi_destroy_gluebi(vol);
-	if (err)
-		goto out_err;
-
 	if (!no_vtbl) {
 		err = ubi_change_vtbl_record(ubi, vol_id, NULL);
 		if (err)
@@ -465,8 +455,10 @@
 	ubi->vol_count -= 1;
 	spin_unlock(&ubi->volumes_lock);
 
-	if (!no_vtbl)
-		err = paranoid_check_volumes(ubi);
+	ubi_volume_notify(ubi, vol, UBI_VOLUME_REMOVED);
+	if (!no_vtbl && paranoid_check_volumes(ubi))
+		dbg_err("check failed while removing volume %d", vol_id);
+
 	return err;
 
 out_err:
@@ -485,7 +477,7 @@
  *
  * This function re-sizes the volume and returns zero in case of success, and a
  * negative error code in case of failure. The caller has to have the
- * @ubi->volumes_mutex locked.
+ * @ubi->device_mutex locked.
  */
 int ubi_resize_volume(struct ubi_volume_desc *desc, int reserved_pebs)
 {
@@ -498,8 +490,8 @@
 	if (ubi->ro_mode)
 		return -EROFS;
 
-	dbg_gen("re-size volume %d to from %d to %d PEBs",
-		vol_id, vol->reserved_pebs, reserved_pebs);
+	dbg_gen("re-size device %d, volume %d to from %d to %d PEBs",
+		ubi->ubi_num, vol_id, vol->reserved_pebs, reserved_pebs);
 
 	if (vol->vol_type == UBI_STATIC_VOLUME &&
 	    reserved_pebs < vol->used_ebs) {
@@ -587,7 +579,9 @@
 			(long long)vol->used_ebs * vol->usable_leb_size;
 	}
 
-	err = paranoid_check_volumes(ubi);
+	ubi_volume_notify(ubi, vol, UBI_VOLUME_RESIZED);
+	if (paranoid_check_volumes(ubi))
+		dbg_err("check failed while re-sizing volume %d", vol_id);
 	return err;
 
 out_acc:
@@ -632,11 +626,12 @@
 			vol->name_len = re->new_name_len;
 			memcpy(vol->name, re->new_name, re->new_name_len + 1);
 			spin_unlock(&ubi->volumes_lock);
+			ubi_volume_notify(ubi, vol, UBI_VOLUME_RENAMED);
 		}
 	}
 
-	if (!err)
-		err = paranoid_check_volumes(ubi);
+	if (!err && paranoid_check_volumes(ubi))
+		;
 	return err;
 }
 
@@ -667,10 +662,6 @@
 		return err;
 	}
 
-	err = ubi_create_gluebi(ubi, vol);
-	if (err)
-		goto out_cdev;
-
 	vol->dev.release = vol_release;
 	vol->dev.parent = &ubi->dev;
 	vol->dev.devt = dev;
@@ -678,21 +669,19 @@
 	dev_set_name(&vol->dev, "%s_%d", ubi->ubi_name, vol->vol_id);
 	err = device_register(&vol->dev);
 	if (err)
-		goto out_gluebi;
+		goto out_cdev;
 
 	err = volume_sysfs_init(ubi, vol);
 	if (err) {
 		cdev_del(&vol->cdev);
-		err = ubi_destroy_gluebi(vol);
 		volume_sysfs_close(vol);
 		return err;
 	}
 
-	err = paranoid_check_volumes(ubi);
+	if (paranoid_check_volumes(ubi))
+		dbg_err("check failed while adding volume %d", vol_id);
 	return err;
 
-out_gluebi:
-	err = ubi_destroy_gluebi(vol);
 out_cdev:
 	cdev_del(&vol->cdev);
 	return err;
@@ -708,12 +697,9 @@
  */
 void ubi_free_volume(struct ubi_device *ubi, struct ubi_volume *vol)
 {
-	int err;
-
 	dbg_gen("free volume %d", vol->vol_id);
 
 	ubi->volumes[vol->vol_id] = NULL;
-	err = ubi_destroy_gluebi(vol);
 	cdev_del(&vol->cdev);
 	volume_sysfs_close(vol);
 }
@@ -868,6 +854,7 @@
 	if (vol)
 		ubi_dbg_dump_vol_info(vol);
 	ubi_dbg_dump_vtbl_record(&ubi->vtbl[vol_id], vol_id);
+	dump_stack();
 	spin_unlock(&ubi->volumes_lock);
 	return -EINVAL;
 }
diff --git a/drivers/mtd/ubi/wl.c b/drivers/mtd/ubi/wl.c
index 891534f..2b24723 100644
--- a/drivers/mtd/ubi/wl.c
+++ b/drivers/mtd/ubi/wl.c
@@ -55,8 +55,8 @@
  *
  * As it was said, for the UBI sub-system all physical eraseblocks are either
  * "free" or "used". Free eraseblock are kept in the @wl->free RB-tree, while
- * used eraseblocks are kept in @wl->used or @wl->scrub RB-trees, or
- * (temporarily) in the @wl->pq queue.
+ * used eraseblocks are kept in @wl->used, @wl->erroneous, or @wl->scrub
+ * RB-trees, as well as (temporarily) in the @wl->pq queue.
  *
  * When the WL sub-system returns a physical eraseblock, the physical
  * eraseblock is protected from being moved for some "time". For this reason,
@@ -83,6 +83,8 @@
  * used. The former state corresponds to the @wl->free tree. The latter state
  * is split up on several sub-states:
  * o the WL movement is allowed (@wl->used tree);
+ * o the WL movement is disallowed (@wl->erroneous) because the PEB is
+ *   erroneous - e.g., there was a read error;
  * o the WL movement is temporarily prohibited (@wl->pq queue);
  * o scrubbing is needed (@wl->scrub tree).
  *
@@ -653,7 +655,8 @@
 static int wear_leveling_worker(struct ubi_device *ubi, struct ubi_work *wrk,
 				int cancel)
 {
-	int err, scrubbing = 0, torture = 0;
+	int err, scrubbing = 0, torture = 0, protect = 0, erroneous = 0;
+	int vol_id = -1, uninitialized_var(lnum);
 	struct ubi_wl_entry *e1, *e2;
 	struct ubi_vid_hdr *vid_hdr;
 
@@ -738,68 +741,78 @@
 			/*
 			 * We are trying to move PEB without a VID header. UBI
 			 * always write VID headers shortly after the PEB was
-			 * given, so we have a situation when it did not have
-			 * chance to write it down because it was preempted.
-			 * Just re-schedule the work, so that next time it will
-			 * likely have the VID header in place.
+			 * given, so we have a situation when it has not yet
+			 * had a chance to write it, because it was preempted.
+			 * So add this PEB to the protection queue so far,
+			 * because presumably more data will be written there
+			 * (including the missing VID header), and then we'll
+			 * move it.
 			 */
 			dbg_wl("PEB %d has no VID header", e1->pnum);
+			protect = 1;
 			goto out_not_moved;
 		}
 
 		ubi_err("error %d while reading VID header from PEB %d",
 			err, e1->pnum);
-		if (err > 0)
-			err = -EIO;
 		goto out_error;
 	}
 
+	vol_id = be32_to_cpu(vid_hdr->vol_id);
+	lnum = be32_to_cpu(vid_hdr->lnum);
+
 	err = ubi_eba_copy_leb(ubi, e1->pnum, e2->pnum, vid_hdr);
 	if (err) {
-		if (err == -EAGAIN)
+		if (err == MOVE_CANCEL_RACE) {
+			/*
+			 * The LEB has not been moved because the volume is
+			 * being deleted or the PEB has been put meanwhile. We
+			 * should prevent this PEB from being selected for
+			 * wear-leveling movement again, so put it to the
+			 * protection queue.
+			 */
+			protect = 1;
 			goto out_not_moved;
-		if (err < 0)
-			goto out_error;
-		if (err == 2) {
-			/* Target PEB write error, torture it */
+		}
+
+		if (err == MOVE_CANCEL_BITFLIPS || err == MOVE_TARGET_WR_ERR ||
+		    err == MOVE_TARGET_RD_ERR) {
+			/*
+			 * Target PEB had bit-flips or write error - torture it.
+			 */
 			torture = 1;
 			goto out_not_moved;
 		}
 
-		/*
-		 * The LEB has not been moved because the volume is being
-		 * deleted or the PEB has been put meanwhile. We should prevent
-		 * this PEB from being selected for wear-leveling movement
-		 * again, so put it to the protection queue.
-		 */
+		if (err == MOVE_SOURCE_RD_ERR) {
+			/*
+			 * An error happened while reading the source PEB. Do
+			 * not switch to R/O mode in this case, and give the
+			 * upper layers a possibility to recover from this,
+			 * e.g. by unmapping corresponding LEB. Instead, just
+			 * put this PEB to the @ubi->erroneous list to prevent
+			 * UBI from trying to move it over and over again.
+			 */
+			if (ubi->erroneous_peb_count > ubi->max_erroneous) {
+				ubi_err("too many erroneous eraseblocks (%d)",
+					ubi->erroneous_peb_count);
+				goto out_error;
+			}
+			erroneous = 1;
+			goto out_not_moved;
+		}
 
-		dbg_wl("canceled moving PEB %d", e1->pnum);
-		ubi_assert(err == 1);
-
-		ubi_free_vid_hdr(ubi, vid_hdr);
-		vid_hdr = NULL;
-
-		spin_lock(&ubi->wl_lock);
-		prot_queue_add(ubi, e1);
-		ubi_assert(!ubi->move_to_put);
-		ubi->move_from = ubi->move_to = NULL;
-		ubi->wl_scheduled = 0;
-		spin_unlock(&ubi->wl_lock);
-
-		e1 = NULL;
-		err = schedule_erase(ubi, e2, 0);
-		if (err)
+		if (err < 0)
 			goto out_error;
-		mutex_unlock(&ubi->move_mutex);
-		return 0;
+
+		ubi_assert(0);
 	}
 
 	/* The PEB has been successfully moved */
-	ubi_free_vid_hdr(ubi, vid_hdr);
-	vid_hdr = NULL;
 	if (scrubbing)
-		ubi_msg("scrubbed PEB %d, data moved to PEB %d",
-			e1->pnum, e2->pnum);
+		ubi_msg("scrubbed PEB %d (LEB %d:%d), data moved to PEB %d",
+			e1->pnum, vol_id, lnum, e2->pnum);
+	ubi_free_vid_hdr(ubi, vid_hdr);
 
 	spin_lock(&ubi->wl_lock);
 	if (!ubi->move_to_put) {
@@ -812,8 +825,10 @@
 
 	err = schedule_erase(ubi, e1, 0);
 	if (err) {
-		e1 = NULL;
-		goto out_error;
+		kmem_cache_free(ubi_wl_entry_slab, e1);
+		if (e2)
+			kmem_cache_free(ubi_wl_entry_slab, e2);
+		goto out_ro;
 	}
 
 	if (e2) {
@@ -821,10 +836,13 @@
 		 * Well, the target PEB was put meanwhile, schedule it for
 		 * erasure.
 		 */
-		dbg_wl("PEB %d was put meanwhile, erase", e2->pnum);
+		dbg_wl("PEB %d (LEB %d:%d) was put meanwhile, erase",
+		       e2->pnum, vol_id, lnum);
 		err = schedule_erase(ubi, e2, 0);
-		if (err)
-			goto out_error;
+		if (err) {
+			kmem_cache_free(ubi_wl_entry_slab, e2);
+			goto out_ro;
+		}
 	}
 
 	dbg_wl("done");
@@ -837,11 +855,19 @@
 	 * have been changed, schedule it for erasure.
 	 */
 out_not_moved:
-	dbg_wl("canceled moving PEB %d", e1->pnum);
-	ubi_free_vid_hdr(ubi, vid_hdr);
-	vid_hdr = NULL;
+	if (vol_id != -1)
+		dbg_wl("cancel moving PEB %d (LEB %d:%d) to PEB %d (%d)",
+		       e1->pnum, vol_id, lnum, e2->pnum, err);
+	else
+		dbg_wl("cancel moving PEB %d to PEB %d (%d)",
+		       e1->pnum, e2->pnum, err);
 	spin_lock(&ubi->wl_lock);
-	if (scrubbing)
+	if (protect)
+		prot_queue_add(ubi, e1);
+	else if (erroneous) {
+		wl_tree_add(e1, &ubi->erroneous);
+		ubi->erroneous_peb_count += 1;
+	} else if (scrubbing)
 		wl_tree_add(e1, &ubi->scrub);
 	else
 		wl_tree_add(e1, &ubi->used);
@@ -850,32 +876,36 @@
 	ubi->wl_scheduled = 0;
 	spin_unlock(&ubi->wl_lock);
 
-	e1 = NULL;
+	ubi_free_vid_hdr(ubi, vid_hdr);
 	err = schedule_erase(ubi, e2, torture);
-	if (err)
-		goto out_error;
-
+	if (err) {
+		kmem_cache_free(ubi_wl_entry_slab, e2);
+		goto out_ro;
+	}
 	mutex_unlock(&ubi->move_mutex);
 	return 0;
 
 out_error:
-	ubi_err("error %d while moving PEB %d to PEB %d",
-		err, e1->pnum, e2->pnum);
-
-	ubi_free_vid_hdr(ubi, vid_hdr);
+	if (vol_id != -1)
+		ubi_err("error %d while moving PEB %d to PEB %d",
+			err, e1->pnum, e2->pnum);
+	else
+		ubi_err("error %d while moving PEB %d (LEB %d:%d) to PEB %d",
+			err, e1->pnum, vol_id, lnum, e2->pnum);
 	spin_lock(&ubi->wl_lock);
 	ubi->move_from = ubi->move_to = NULL;
 	ubi->move_to_put = ubi->wl_scheduled = 0;
 	spin_unlock(&ubi->wl_lock);
 
-	if (e1)
-		kmem_cache_free(ubi_wl_entry_slab, e1);
-	if (e2)
-		kmem_cache_free(ubi_wl_entry_slab, e2);
-	ubi_ro_mode(ubi);
+	ubi_free_vid_hdr(ubi, vid_hdr);
+	kmem_cache_free(ubi_wl_entry_slab, e1);
+	kmem_cache_free(ubi_wl_entry_slab, e2);
 
+out_ro:
+	ubi_ro_mode(ubi);
 	mutex_unlock(&ubi->move_mutex);
-	return err;
+	ubi_assert(err != 0);
+	return err < 0 ? err : -EIO;
 
 out_cancel:
 	ubi->wl_scheduled = 0;
@@ -1015,7 +1045,7 @@
 		/*
 		 * If this is not %-EIO, we have no idea what to do. Scheduling
 		 * this physical eraseblock for erasure again would cause
-		 * errors again and again. Well, lets switch to RO mode.
+		 * errors again and again. Well, lets switch to R/O mode.
 		 */
 		goto out_ro;
 	}
@@ -1043,10 +1073,9 @@
 		ubi_err("no reserved physical eraseblocks");
 		goto out_ro;
 	}
-
 	spin_unlock(&ubi->volumes_lock);
-	ubi_msg("mark PEB %d as bad", pnum);
 
+	ubi_msg("mark PEB %d as bad", pnum);
 	err = ubi_io_mark_bad(ubi, pnum);
 	if (err)
 		goto out_ro;
@@ -1056,7 +1085,9 @@
 	ubi->bad_peb_count += 1;
 	ubi->good_peb_count -= 1;
 	ubi_calculate_reserved(ubi);
-	if (ubi->beb_rsvd_pebs == 0)
+	if (ubi->beb_rsvd_pebs)
+		ubi_msg("%d PEBs left in the reserve", ubi->beb_rsvd_pebs);
+	else
 		ubi_warn("last PEB from the reserved pool was used");
 	spin_unlock(&ubi->volumes_lock);
 
@@ -1125,6 +1156,13 @@
 		} else if (in_wl_tree(e, &ubi->scrub)) {
 			paranoid_check_in_wl_tree(e, &ubi->scrub);
 			rb_erase(&e->u.rb, &ubi->scrub);
+		} else if (in_wl_tree(e, &ubi->erroneous)) {
+			paranoid_check_in_wl_tree(e, &ubi->erroneous);
+			rb_erase(&e->u.rb, &ubi->erroneous);
+			ubi->erroneous_peb_count -= 1;
+			ubi_assert(ubi->erroneous_peb_count >= 0);
+			/* Erroneous PEBs should be tortured */
+			torture = 1;
 		} else {
 			err = prot_queue_del(ubi, e->pnum);
 			if (err) {
@@ -1373,7 +1411,7 @@
 	struct ubi_scan_leb *seb, *tmp;
 	struct ubi_wl_entry *e;
 
-	ubi->used = ubi->free = ubi->scrub = RB_ROOT;
+	ubi->used = ubi->erroneous = ubi->free = ubi->scrub = RB_ROOT;
 	spin_lock_init(&ubi->wl_lock);
 	mutex_init(&ubi->move_mutex);
 	init_rwsem(&ubi->work_sem);
@@ -1511,6 +1549,7 @@
 	cancel_pending(ubi);
 	protection_queue_destroy(ubi);
 	tree_destroy(&ubi->used);
+	tree_destroy(&ubi->erroneous);
 	tree_destroy(&ubi->free);
 	tree_destroy(&ubi->scrub);
 	kfree(ubi->lookuptbl);
diff --git a/drivers/net/Kconfig b/drivers/net/Kconfig
index 3b63831..892a9e4 100644
--- a/drivers/net/Kconfig
+++ b/drivers/net/Kconfig
@@ -2272,8 +2272,9 @@
 
 config CNIC
 	tristate "Broadcom CNIC support"
-	depends on BNX2
-	depends on UIO
+	depends on PCI
+	select BNX2
+	select UIO
 	help
 	  This driver supports offload features of Broadcom NetXtremeII
 	  gigabit Ethernet cards.
diff --git a/drivers/net/bnx2.c b/drivers/net/bnx2.c
index 7e37381..38f1c33 100644
--- a/drivers/net/bnx2.c
+++ b/drivers/net/bnx2.c
@@ -3552,14 +3552,14 @@
 		sort_mode |= BNX2_RPM_SORT_USER0_MC_HSH_EN;
 	}
 
-	if (dev->uc_count > BNX2_MAX_UNICAST_ADDRESSES) {
+	if (dev->uc.count > BNX2_MAX_UNICAST_ADDRESSES) {
 		rx_mode |= BNX2_EMAC_RX_MODE_PROMISCUOUS;
 		sort_mode |= BNX2_RPM_SORT_USER0_PROM_EN |
 			     BNX2_RPM_SORT_USER0_PROM_VLAN;
 	} else if (!(dev->flags & IFF_PROMISC)) {
 		/* Add all entries into to the match filter list */
 		i = 0;
-		list_for_each_entry(ha, &dev->uc_list, list) {
+		list_for_each_entry(ha, &dev->uc.list, list) {
 			bnx2_set_mac_addr(bp, ha->addr,
 					  i + BNX2_START_UNICAST_ADDRESS_INDEX);
 			sort_mode |= (1 <<
diff --git a/drivers/net/davinci_emac.c b/drivers/net/davinci_emac.c
index 0e9b9f9..2df8fb0a 100644
--- a/drivers/net/davinci_emac.c
+++ b/drivers/net/davinci_emac.c
@@ -2767,7 +2767,6 @@
 
 	dev_notice(&ndev->dev, "DaVinci EMAC: davinci_emac_remove()\n");
 
-	clk_disable(emac_clk);
 	platform_set_drvdata(pdev, NULL);
 	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
 	mdiobus_unregister(priv->mii_bus);
diff --git a/drivers/net/e100.c b/drivers/net/e100.c
index f7929e8..efa680f 100644
--- a/drivers/net/e100.c
+++ b/drivers/net/e100.c
@@ -2895,12 +2895,13 @@
 
 static int __e100_power_off(struct pci_dev *pdev, bool wake)
 {
-	if (wake) {
+	if (wake)
 		return pci_prepare_to_sleep(pdev);
-	} else {
-		pci_wake_from_d3(pdev, false);
-		return pci_set_power_state(pdev, PCI_D3hot);
-	}
+
+	pci_wake_from_d3(pdev, false);
+	pci_set_power_state(pdev, PCI_D3hot);
+
+	return 0;
 }
 
 #ifdef CONFIG_PM
diff --git a/drivers/net/e1000/e1000_main.c b/drivers/net/e1000/e1000_main.c
index 8d36743..5e3356f 100644
--- a/drivers/net/e1000/e1000_main.c
+++ b/drivers/net/e1000/e1000_main.c
@@ -2370,7 +2370,7 @@
 			rctl |= E1000_RCTL_VFE;
 	}
 
-	if (netdev->uc_count > rar_entries - 1) {
+	if (netdev->uc.count > rar_entries - 1) {
 		rctl |= E1000_RCTL_UPE;
 	} else if (!(netdev->flags & IFF_PROMISC)) {
 		rctl &= ~E1000_RCTL_UPE;
@@ -2394,7 +2394,7 @@
 	 */
 	i = 1;
 	if (use_uc)
-		list_for_each_entry(ha, &netdev->uc_list, list) {
+		list_for_each_entry(ha, &netdev->uc.list, list) {
 			if (i == rar_entries)
 				break;
 			e1000_rar_set(hw, ha->addr, i++);
diff --git a/drivers/net/fec_mpc52xx.c b/drivers/net/fec_mpc52xx.c
index 7d44340..cc78633 100644
--- a/drivers/net/fec_mpc52xx.c
+++ b/drivers/net/fec_mpc52xx.c
@@ -948,7 +948,7 @@
 	/* Start with safe defaults for link connection */
 	priv->speed = 100;
 	priv->duplex = DUPLEX_HALF;
-	priv->mdio_speed = ((mpc52xx_find_ipb_freq(op->node) >> 20) / 5) << 1;
+	priv->mdio_speed = ((mpc5xxx_get_bus_frequency(op->node) >> 20) / 5) << 1;
 
 	/* The current speed preconfigures the speed of the MII link */
 	prop = of_get_property(op->node, "current-speed", &prop_size);
diff --git a/drivers/net/fec_mpc52xx_phy.c b/drivers/net/fec_mpc52xx_phy.c
index fec9f245..31e6d62 100644
--- a/drivers/net/fec_mpc52xx_phy.c
+++ b/drivers/net/fec_mpc52xx_phy.c
@@ -106,7 +106,7 @@
 
 	/* set MII speed */
 	out_be32(&priv->regs->mii_speed,
-		((mpc52xx_find_ipb_freq(of->node) >> 20) / 5) << 1);
+		((mpc5xxx_get_bus_frequency(of->node) >> 20) / 5) << 1);
 
 	err = of_mdiobus_register(bus, np);
 	if (err)
diff --git a/drivers/net/forcedeth.c b/drivers/net/forcedeth.c
index b60a304..1094d29 100644
--- a/drivers/net/forcedeth.c
+++ b/drivers/net/forcedeth.c
@@ -719,7 +719,8 @@
 struct nv_skb_map {
 	struct sk_buff *skb;
 	dma_addr_t dma;
-	unsigned int dma_len;
+	unsigned int dma_len:31;
+	unsigned int dma_single:1;
 	struct ring_desc_ex *first_tx_desc;
 	struct nv_skb_map *next_tx_ctx;
 };
@@ -1912,6 +1913,7 @@
 		np->tx_skb[i].skb = NULL;
 		np->tx_skb[i].dma = 0;
 		np->tx_skb[i].dma_len = 0;
+		np->tx_skb[i].dma_single = 0;
 		np->tx_skb[i].first_tx_desc = NULL;
 		np->tx_skb[i].next_tx_ctx = NULL;
 	}
@@ -1930,23 +1932,30 @@
 		return nv_alloc_rx_optimized(dev);
 }
 
-static int nv_release_txskb(struct net_device *dev, struct nv_skb_map* tx_skb)
+static void nv_unmap_txskb(struct fe_priv *np, struct nv_skb_map *tx_skb)
 {
-	struct fe_priv *np = netdev_priv(dev);
-
 	if (tx_skb->dma) {
-		pci_unmap_page(np->pci_dev, tx_skb->dma,
-			       tx_skb->dma_len,
-			       PCI_DMA_TODEVICE);
+		if (tx_skb->dma_single)
+			pci_unmap_single(np->pci_dev, tx_skb->dma,
+					 tx_skb->dma_len,
+					 PCI_DMA_TODEVICE);
+		else
+			pci_unmap_page(np->pci_dev, tx_skb->dma,
+				       tx_skb->dma_len,
+				       PCI_DMA_TODEVICE);
 		tx_skb->dma = 0;
 	}
+}
+
+static int nv_release_txskb(struct fe_priv *np, struct nv_skb_map *tx_skb)
+{
+	nv_unmap_txskb(np, tx_skb);
 	if (tx_skb->skb) {
 		dev_kfree_skb_any(tx_skb->skb);
 		tx_skb->skb = NULL;
 		return 1;
-	} else {
-		return 0;
 	}
+	return 0;
 }
 
 static void nv_drain_tx(struct net_device *dev)
@@ -1964,10 +1973,11 @@
 			np->tx_ring.ex[i].bufhigh = 0;
 			np->tx_ring.ex[i].buflow = 0;
 		}
-		if (nv_release_txskb(dev, &np->tx_skb[i]))
+		if (nv_release_txskb(np, &np->tx_skb[i]))
 			dev->stats.tx_dropped++;
 		np->tx_skb[i].dma = 0;
 		np->tx_skb[i].dma_len = 0;
+		np->tx_skb[i].dma_single = 0;
 		np->tx_skb[i].first_tx_desc = NULL;
 		np->tx_skb[i].next_tx_ctx = NULL;
 	}
@@ -2171,6 +2181,7 @@
 		np->put_tx_ctx->dma = pci_map_single(np->pci_dev, skb->data + offset, bcnt,
 						PCI_DMA_TODEVICE);
 		np->put_tx_ctx->dma_len = bcnt;
+		np->put_tx_ctx->dma_single = 1;
 		put_tx->buf = cpu_to_le32(np->put_tx_ctx->dma);
 		put_tx->flaglen = cpu_to_le32((bcnt-1) | tx_flags);
 
@@ -2196,6 +2207,7 @@
 			np->put_tx_ctx->dma = pci_map_page(np->pci_dev, frag->page, frag->page_offset+offset, bcnt,
 							   PCI_DMA_TODEVICE);
 			np->put_tx_ctx->dma_len = bcnt;
+			np->put_tx_ctx->dma_single = 0;
 			put_tx->buf = cpu_to_le32(np->put_tx_ctx->dma);
 			put_tx->flaglen = cpu_to_le32((bcnt-1) | tx_flags);
 
@@ -2291,6 +2303,7 @@
 		np->put_tx_ctx->dma = pci_map_single(np->pci_dev, skb->data + offset, bcnt,
 						PCI_DMA_TODEVICE);
 		np->put_tx_ctx->dma_len = bcnt;
+		np->put_tx_ctx->dma_single = 1;
 		put_tx->bufhigh = cpu_to_le32(dma_high(np->put_tx_ctx->dma));
 		put_tx->buflow = cpu_to_le32(dma_low(np->put_tx_ctx->dma));
 		put_tx->flaglen = cpu_to_le32((bcnt-1) | tx_flags);
@@ -2317,6 +2330,7 @@
 			np->put_tx_ctx->dma = pci_map_page(np->pci_dev, frag->page, frag->page_offset+offset, bcnt,
 							   PCI_DMA_TODEVICE);
 			np->put_tx_ctx->dma_len = bcnt;
+			np->put_tx_ctx->dma_single = 0;
 			put_tx->bufhigh = cpu_to_le32(dma_high(np->put_tx_ctx->dma));
 			put_tx->buflow = cpu_to_le32(dma_low(np->put_tx_ctx->dma));
 			put_tx->flaglen = cpu_to_le32((bcnt-1) | tx_flags);
@@ -2434,10 +2448,7 @@
 		dprintk(KERN_DEBUG "%s: nv_tx_done: flags 0x%x.\n",
 					dev->name, flags);
 
-		pci_unmap_page(np->pci_dev, np->get_tx_ctx->dma,
-			       np->get_tx_ctx->dma_len,
-			       PCI_DMA_TODEVICE);
-		np->get_tx_ctx->dma = 0;
+		nv_unmap_txskb(np, np->get_tx_ctx);
 
 		if (np->desc_ver == DESC_VER_1) {
 			if (flags & NV_TX_LASTPACKET) {
@@ -2502,10 +2513,7 @@
 		dprintk(KERN_DEBUG "%s: nv_tx_done_optimized: flags 0x%x.\n",
 					dev->name, flags);
 
-		pci_unmap_page(np->pci_dev, np->get_tx_ctx->dma,
-			       np->get_tx_ctx->dma_len,
-			       PCI_DMA_TODEVICE);
-		np->get_tx_ctx->dma = 0;
+		nv_unmap_txskb(np, np->get_tx_ctx);
 
 		if (flags & NV_TX2_LASTPACKET) {
 			if (!(flags & NV_TX2_ERROR))
@@ -5091,7 +5099,7 @@
 		dprintk(KERN_DEBUG "%s: loopback - did not receive test packet\n", dev->name);
 	}
 
-	pci_unmap_page(np->pci_dev, test_dma_addr,
+	pci_unmap_single(np->pci_dev, test_dma_addr,
 		       (skb_end_pointer(tx_skb) - tx_skb->data),
 		       PCI_DMA_TODEVICE);
 	dev_kfree_skb_any(tx_skb);
diff --git a/drivers/net/hamradio/bpqether.c b/drivers/net/hamradio/bpqether.c
index 5105548..abcd19a 100644
--- a/drivers/net/hamradio/bpqether.c
+++ b/drivers/net/hamradio/bpqether.c
@@ -260,7 +260,7 @@
 	 */
 	if (!netif_running(dev)) {
 		kfree_skb(skb);
-		return -ENODEV;
+		return NETDEV_TX_OK;
 	}
 
 	skb_pull(skb, 1);
diff --git a/drivers/net/hp100.c b/drivers/net/hp100.c
index 8feda9f..1d3429a 100644
--- a/drivers/net/hp100.c
+++ b/drivers/net/hp100.c
@@ -1495,13 +1495,8 @@
 	hp100_outw(0x4210, TRACE);
 	printk("hp100: %s: start_xmit_bm\n", dev->name);
 #endif
-
-	if (skb == NULL) {
-		return 0;
-	}
-
 	if (skb->len <= 0)
-		return 0;
+		goto drop;
 
 	if (lp->chip == HP100_CHIPID_SHASTA && skb_padto(skb, ETH_ZLEN))
 		return 0;
@@ -1514,10 +1509,10 @@
 #endif
 		/* not waited long enough since last tx? */
 		if (time_before(jiffies, dev->trans_start + HZ))
-			return -EAGAIN;
+			goto drop;
 
 		if (hp100_check_lan(dev))
-			return -EIO;
+			goto drop;
 
 		if (lp->lan_type == HP100_LAN_100 && lp->hub_status < 0) {
 			/* we have a 100Mb/s adapter but it isn't connected to hub */
@@ -1551,7 +1546,7 @@
 		}
 
 		dev->trans_start = jiffies;
-		return -EAGAIN;
+		goto drop;
 	}
 
 	/*
@@ -1591,6 +1586,10 @@
 	dev->trans_start = jiffies;
 
 	return 0;
+
+drop:
+	dev_kfree_skb(skb);
+	return NETDEV_TX_OK;
 }
 
 
@@ -1648,16 +1647,11 @@
 	hp100_outw(0x4212, TRACE);
 	printk("hp100: %s: start_xmit\n", dev->name);
 #endif
-
-	if (skb == NULL) {
-		return 0;
-	}
-
 	if (skb->len <= 0)
-		return 0;
+		goto drop;
 
 	if (hp100_check_lan(dev))
-		return -EIO;
+		goto drop;
 
 	/* If there is not enough free memory on the card... */
 	i = hp100_inl(TX_MEM_FREE) & 0x7fffffff;
@@ -1671,7 +1665,7 @@
 			printk("hp100: %s: trans_start timing problem\n",
 			       dev->name);
 #endif
-			return -EAGAIN;
+			goto drop;
 		}
 		if (lp->lan_type == HP100_LAN_100 && lp->hub_status < 0) {
 			/* we have a 100Mb/s adapter but it isn't connected to hub */
@@ -1705,7 +1699,7 @@
 			}
 		}
 		dev->trans_start = jiffies;
-		return -EAGAIN;
+		goto drop;
 	}
 
 	for (i = 0; i < 6000 && (hp100_inb(OPTION_MSW) & HP100_TX_CMD); i++) {
@@ -1759,6 +1753,11 @@
 #endif
 
 	return 0;
+
+drop:
+	dev_kfree_skb(skb);
+	return NETDEV_TX_OK;
+
 }
 
 
diff --git a/drivers/net/igbvf/netdev.c b/drivers/net/igbvf/netdev.c
index 22aadb7..2bc9d63 100644
--- a/drivers/net/igbvf/netdev.c
+++ b/drivers/net/igbvf/netdev.c
@@ -1281,7 +1281,7 @@
 	/* Setup the HW Tx Head and Tail descriptor pointers */
 	ew32(TDLEN(0), tx_ring->count * sizeof(union e1000_adv_tx_desc));
 	tdba = tx_ring->dma;
-	ew32(TDBAL(0), (tdba & DMA_32BIT_MASK));
+	ew32(TDBAL(0), (tdba & DMA_BIT_MASK(32)));
 	ew32(TDBAH(0), (tdba >> 32));
 	ew32(TDH(0), 0);
 	ew32(TDT(0), 0);
@@ -1367,7 +1367,7 @@
 	 * the Base and Length of the Rx Descriptor Ring
 	 */
 	rdba = rx_ring->dma;
-	ew32(RDBAL(0), (rdba & DMA_32BIT_MASK));
+	ew32(RDBAL(0), (rdba & DMA_BIT_MASK(32)));
 	ew32(RDBAH(0), (rdba >> 32));
 	ew32(RDLEN(0), rx_ring->count * sizeof(union e1000_adv_rx_desc));
 	rx_ring->head = E1000_RDH(0);
@@ -2628,15 +2628,16 @@
 		return err;
 
 	pci_using_dac = 0;
-	err = pci_set_dma_mask(pdev, DMA_64BIT_MASK);
+	err = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
 	if (!err) {
-		err = pci_set_consistent_dma_mask(pdev, DMA_64BIT_MASK);
+		err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
 		if (!err)
 			pci_using_dac = 1;
 	} else {
-		err = pci_set_dma_mask(pdev, DMA_32BIT_MASK);
+		err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
 		if (err) {
-			err = pci_set_consistent_dma_mask(pdev, DMA_32BIT_MASK);
+			err = pci_set_consistent_dma_mask(pdev,
+							  DMA_BIT_MASK(32));
 			if (err) {
 				dev_err(&pdev->dev, "No usable DMA "
 				        "configuration, aborting\n");
diff --git a/drivers/net/ixgbe/ixgbe_fcoe.c b/drivers/net/ixgbe/ixgbe_fcoe.c
index 3c3bf1f..fa9f24e 100644
--- a/drivers/net/ixgbe/ixgbe_fcoe.c
+++ b/drivers/net/ixgbe/ixgbe_fcoe.c
@@ -251,7 +251,7 @@
 	/* program DMA context */
 	hw = &adapter->hw;
 	spin_lock_bh(&fcoe->lock);
-	IXGBE_WRITE_REG(hw, IXGBE_FCPTRL, ddp->udp & DMA_32BIT_MASK);
+	IXGBE_WRITE_REG(hw, IXGBE_FCPTRL, ddp->udp & DMA_BIT_MASK(32));
 	IXGBE_WRITE_REG(hw, IXGBE_FCPTRH, (u64)ddp->udp >> 32);
 	IXGBE_WRITE_REG(hw, IXGBE_FCBUFF, fcbuff);
 	IXGBE_WRITE_REG(hw, IXGBE_FCDMARW, fcdmarw);
diff --git a/drivers/net/ixgbe/ixgbe_main.c b/drivers/net/ixgbe/ixgbe_main.c
index a551a96..e756e22 100644
--- a/drivers/net/ixgbe/ixgbe_main.c
+++ b/drivers/net/ixgbe/ixgbe_main.c
@@ -2321,7 +2321,7 @@
 	IXGBE_WRITE_REG(hw, IXGBE_VLNCTRL, vlnctrl);
 
 	/* reprogram secondary unicast list */
-	hw->mac.ops.update_uc_addr_list(hw, &netdev->uc_list);
+	hw->mac.ops.update_uc_addr_list(hw, &netdev->uc.list);
 
 	/* reprogram multicast list */
 	addr_count = netdev->mc_count;
@@ -5261,7 +5261,7 @@
 
 /**
  * ixgbe_add_sanmac_netdev - Add the SAN MAC address to the corresponding
- * netdev->dev_addr_list
+ * netdev->dev_addrs
  * @netdev: network interface device structure
  *
  * Returns non-zero on failure
@@ -5282,7 +5282,7 @@
 
 /**
  * ixgbe_del_sanmac_netdev - Removes the SAN MAC address to the corresponding
- * netdev->dev_addr_list
+ * netdev->dev_addrs
  * @netdev: network interface device structure
  *
  * Returns non-zero on failure
diff --git a/drivers/net/mv643xx_eth.c b/drivers/net/mv643xx_eth.c
index b4e18a5..745ae8b4 100644
--- a/drivers/net/mv643xx_eth.c
+++ b/drivers/net/mv643xx_eth.c
@@ -1729,7 +1729,7 @@
 		return 0;
 
 	nibbles = 1 << (dev->dev_addr[5] & 0x0f);
-	list_for_each_entry(ha, &dev->uc_list, list) {
+	list_for_each_entry(ha, &dev->uc.list, list) {
 		if (memcmp(dev->dev_addr, ha->addr, 5))
 			return 0;
 		if ((dev->dev_addr[5] ^ ha->addr[5]) & 0xf0)
diff --git a/drivers/net/netxen/netxen_nic.h b/drivers/net/netxen/netxen_nic.h
index ab11c2b..970cede 100644
--- a/drivers/net/netxen/netxen_nic.h
+++ b/drivers/net/netxen/netxen_nic.h
@@ -169,6 +169,7 @@
 #define	MAX_NUM_CARDS		4
 
 #define MAX_BUFFERS_PER_CMD	32
+#define TX_STOP_THRESH		((MAX_SKB_FRAGS >> 2) + 4)
 
 /*
  * Following are the states of the Phantom. Phantom will set them and
@@ -1436,7 +1437,7 @@
 struct net_device_stats *netxen_nic_get_stats(struct net_device *netdev);
 
 void netxen_nic_update_cmd_producer(struct netxen_adapter *adapter,
-		struct nx_host_tx_ring *tx_ring, uint32_t crb_producer);
+		struct nx_host_tx_ring *tx_ring);
 
 /*
  * NetXen Board information
@@ -1538,6 +1539,14 @@
 }
 
 
+static inline u32 netxen_tx_avail(struct nx_host_tx_ring *tx_ring)
+{
+	smp_mb();
+	return find_diff_among(tx_ring->producer,
+			tx_ring->sw_consumer, tx_ring->num_desc);
+
+}
+
 int netxen_get_flash_mac_addr(struct netxen_adapter *adapter, __le64 *mac);
 int netxen_p3_get_mac_addr(struct netxen_adapter *adapter, __le64 *mac);
 extern void netxen_change_ringparam(struct netxen_adapter *adapter);
diff --git a/drivers/net/netxen/netxen_nic_hdr.h b/drivers/net/netxen/netxen_nic_hdr.h
index 7f0ddbf..3cc0478 100644
--- a/drivers/net/netxen/netxen_nic_hdr.h
+++ b/drivers/net/netxen/netxen_nic_hdr.h
@@ -355,6 +355,7 @@
 #define NETXEN_HW_CRB_HUB_AGT_ADR_LPC	\
 	((NETXEN_HW_H6_CH_HUB_ADR << 7) | NETXEN_HW_LPC_CRB_AGT_ADR)
 
+#define NETXEN_SRE_MISC			(NETXEN_CRB_SRE + 0x0002c)
 #define NETXEN_SRE_INT_STATUS		(NETXEN_CRB_SRE + 0x00034)
 #define NETXEN_SRE_PBI_ACTIVE_STATUS	(NETXEN_CRB_SRE + 0x01014)
 #define NETXEN_SRE_L1RE_CTL		(NETXEN_CRB_SRE + 0x03000)
diff --git a/drivers/net/netxen/netxen_nic_hw.c b/drivers/net/netxen/netxen_nic_hw.c
index 42ffb825..ce3b89d 100644
--- a/drivers/net/netxen/netxen_nic_hw.c
+++ b/drivers/net/netxen/netxen_nic_hw.c
@@ -488,7 +488,7 @@
 
 	tx_ring->producer = producer;
 
-	netxen_nic_update_cmd_producer(adapter, tx_ring, producer);
+	netxen_nic_update_cmd_producer(adapter, tx_ring);
 
 	netif_tx_unlock_bh(adapter->netdev);
 
@@ -2041,8 +2041,8 @@
 			fw_major, fw_minor, fw_build);
 
 	if (NX_IS_REVISION_P3(adapter->ahw.revision_id)) {
-		i = NXRD32(adapter, NETXEN_MIU_MN_CONTROL);
-		adapter->ahw.cut_through = (i & 0x4) ? 1 : 0;
+		i = NXRD32(adapter, NETXEN_SRE_MISC);
+		adapter->ahw.cut_through = (i & 0x8000) ? 1 : 0;
 		dev_info(&pdev->dev, "firmware running in %s mode\n",
 		adapter->ahw.cut_through ? "cut-through" : "legacy");
 	}
diff --git a/drivers/net/netxen/netxen_nic_init.c b/drivers/net/netxen/netxen_nic_init.c
index 6f77ad5..bdb143d 100644
--- a/drivers/net/netxen/netxen_nic_init.c
+++ b/drivers/net/netxen/netxen_nic_init.c
@@ -1292,7 +1292,6 @@
 		return 1;
 
 	sw_consumer = tx_ring->sw_consumer;
-	barrier(); /* hw_consumer can change underneath */
 	hw_consumer = le32_to_cpu(*(tx_ring->hw_consumer));
 
 	while (sw_consumer != hw_consumer) {
@@ -1319,14 +1318,15 @@
 			break;
 	}
 
-	tx_ring->sw_consumer = sw_consumer;
-
 	if (count && netif_running(netdev)) {
+		tx_ring->sw_consumer = sw_consumer;
+
 		smp_mb();
+
 		if (netif_queue_stopped(netdev) && netif_carrier_ok(netdev)) {
 			netif_tx_lock(netdev);
-			netif_wake_queue(netdev);
-			smp_mb();
+			if (netxen_tx_avail(tx_ring) > TX_STOP_THRESH)
+				netif_wake_queue(netdev);
 			netif_tx_unlock(netdev);
 		}
 	}
@@ -1343,7 +1343,6 @@
 	 * There is still a possible race condition and the host could miss an
 	 * interrupt. The card has to take care of this.
 	 */
-	barrier(); /* hw_consumer can change underneath */
 	hw_consumer = le32_to_cpu(*(tx_ring->hw_consumer));
 	done = (sw_consumer == hw_consumer);
 	spin_unlock(&adapter->tx_clean_lock);
diff --git a/drivers/net/netxen/netxen_nic_main.c b/drivers/net/netxen/netxen_nic_main.c
index 98737ef..71daa3d 100644
--- a/drivers/net/netxen/netxen_nic_main.c
+++ b/drivers/net/netxen/netxen_nic_main.c
@@ -107,9 +107,14 @@
 
 void
 netxen_nic_update_cmd_producer(struct netxen_adapter *adapter,
-		struct nx_host_tx_ring *tx_ring, u32 producer)
+		struct nx_host_tx_ring *tx_ring)
 {
-	NXWR32(adapter, tx_ring->crb_cmd_producer, producer);
+	NXWR32(adapter, tx_ring->crb_cmd_producer, tx_ring->producer);
+
+	if (netxen_tx_avail(tx_ring) <= TX_STOP_THRESH) {
+		netif_stop_queue(adapter->netdev);
+		smp_mb();
+	}
 }
 
 static uint32_t crb_cmd_consumer[4] = {
@@ -119,9 +124,9 @@
 
 static inline void
 netxen_nic_update_cmd_consumer(struct netxen_adapter *adapter,
-		struct nx_host_tx_ring *tx_ring, u32 consumer)
+		struct nx_host_tx_ring *tx_ring)
 {
-	NXWR32(adapter, tx_ring->crb_cmd_consumer, consumer);
+	NXWR32(adapter, tx_ring->crb_cmd_consumer, tx_ring->sw_consumer);
 }
 
 static uint32_t msi_tgt_status[8] = {
@@ -900,8 +905,11 @@
 		tx_ring->crb_cmd_producer = crb_cmd_producer[adapter->portnum];
 		tx_ring->crb_cmd_consumer = crb_cmd_consumer[adapter->portnum];
 
-		netxen_nic_update_cmd_producer(adapter, tx_ring, 0);
-		netxen_nic_update_cmd_consumer(adapter, tx_ring, 0);
+		tx_ring->producer = 0;
+		tx_ring->sw_consumer = 0;
+
+		netxen_nic_update_cmd_producer(adapter, tx_ring);
+		netxen_nic_update_cmd_consumer(adapter, tx_ring);
 	}
 
 	for (ring = 0; ring < adapter->max_rds_rings; ring++) {
@@ -1362,7 +1370,7 @@
 	dma_addr_t temp_dma;
 	int i, k;
 
-	u32 producer, consumer;
+	u32 producer;
 	int frag_count, no_of_desc;
 	u32 num_txd = tx_ring->num_desc;
 	bool is_tso = false;
@@ -1372,15 +1380,13 @@
 	/* 4 fragments per cmd des */
 	no_of_desc = (frag_count + 3) >> 2;
 
-	producer = tx_ring->producer;
-	smp_mb();
-	consumer = tx_ring->sw_consumer;
-	if ((no_of_desc+2) >= find_diff_among(producer, consumer, num_txd)) {
+	if (unlikely(no_of_desc + 2) > netxen_tx_avail(tx_ring)) {
 		netif_stop_queue(netdev);
-		smp_mb();
 		return NETDEV_TX_BUSY;
 	}
 
+	producer = tx_ring->producer;
+
 	hwdesc = &tx_ring->desc_head[producer];
 	netxen_clear_cmddesc((u64 *)hwdesc);
 	pbuf = &tx_ring->cmd_buf_arr[producer];
@@ -1493,7 +1499,7 @@
 	tx_ring->producer = producer;
 	adapter->stats.txbytes += skb->len;
 
-	netxen_nic_update_cmd_producer(adapter, tx_ring, producer);
+	netxen_nic_update_cmd_producer(adapter, tx_ring);
 
 	adapter->stats.xmitcalled++;
 
diff --git a/drivers/net/niu.c b/drivers/net/niu.c
index fa61a12..d2146d4 100644
--- a/drivers/net/niu.c
+++ b/drivers/net/niu.c
@@ -6376,7 +6376,7 @@
 	if ((dev->flags & IFF_ALLMULTI) || (dev->mc_count > 0))
 		np->flags |= NIU_FLAGS_MCAST;
 
-	alt_cnt = dev->uc_count;
+	alt_cnt = dev->uc.count;
 	if (alt_cnt > niu_num_alt_addr(np)) {
 		alt_cnt = 0;
 		np->flags |= NIU_FLAGS_PROMISC;
@@ -6385,7 +6385,7 @@
 	if (alt_cnt) {
 		int index = 0;
 
-		list_for_each_entry(ha, &dev->uc_list, list) {
+		list_for_each_entry(ha, &dev->uc.list, list) {
 			err = niu_set_alt_mac(np, index, ha->addr);
 			if (err)
 				printk(KERN_WARNING PFX "%s: Error %d "
diff --git a/drivers/net/phy/phy_device.c b/drivers/net/phy/phy_device.c
index a2ece89..eba937c 100644
--- a/drivers/net/phy/phy_device.c
+++ b/drivers/net/phy/phy_device.c
@@ -244,7 +244,7 @@
 
 /**
  * phy_device_register - Register the phy device on the MDIO bus
- * @phy_device: phy_device structure to be added to the MDIO bus
+ * @phydev: phy_device structure to be added to the MDIO bus
  */
 int phy_device_register(struct phy_device *phydev)
 {
diff --git a/drivers/net/ps3_gelic_net.c b/drivers/net/ps3_gelic_net.c
index 2b38f39..d1a5fb4 100644
--- a/drivers/net/ps3_gelic_net.c
+++ b/drivers/net/ps3_gelic_net.c
@@ -214,9 +214,10 @@
  *
  * returns 0 on success, <0 on failure
  */
-static int gelic_card_init_chain(struct gelic_card *card,
-				 struct gelic_descr_chain *chain,
-				 struct gelic_descr *start_descr, int no)
+static int __devinit gelic_card_init_chain(struct gelic_card *card,
+					   struct gelic_descr_chain *chain,
+					   struct gelic_descr *start_descr,
+					   int no)
 {
 	int i;
 	struct gelic_descr *descr;
@@ -407,7 +408,7 @@
  *
  * returns 0 on success, < 0 on failure
  */
-static int gelic_card_alloc_rx_skbs(struct gelic_card *card)
+static int __devinit gelic_card_alloc_rx_skbs(struct gelic_card *card)
 {
 	struct gelic_descr_chain *chain;
 	int ret;
@@ -1422,8 +1423,8 @@
  *
  * fills out function pointers in the net_device structure
  */
-static void gelic_ether_setup_netdev_ops(struct net_device *netdev,
-					 struct napi_struct *napi)
+static void __devinit gelic_ether_setup_netdev_ops(struct net_device *netdev,
+						   struct napi_struct *napi)
 {
 	netdev->watchdog_timeo = GELIC_NET_WATCHDOG_TIMEOUT;
 	/* NAPI */
@@ -1443,7 +1444,8 @@
  * gelic_ether_setup_netdev initializes the net_device structure
  * and register it.
  **/
-int gelic_net_setup_netdev(struct net_device *netdev, struct gelic_card *card)
+int __devinit gelic_net_setup_netdev(struct net_device *netdev,
+				     struct gelic_card *card)
 {
 	int status;
 	u64 v1, v2;
@@ -1491,7 +1493,7 @@
  * the card and net_device structures are linked to each other
  */
 #define GELIC_ALIGN (32)
-static struct gelic_card *gelic_alloc_card_net(struct net_device **netdev)
+static struct gelic_card * __devinit gelic_alloc_card_net(struct net_device **netdev)
 {
 	struct gelic_card *card;
 	struct gelic_port *port;
@@ -1542,7 +1544,7 @@
 	return card;
 }
 
-static void gelic_card_get_vlan_info(struct gelic_card *card)
+static void __devinit gelic_card_get_vlan_info(struct gelic_card *card)
 {
 	u64 v1, v2;
 	int status;
@@ -1616,7 +1618,7 @@
 /**
  * ps3_gelic_driver_probe - add a device to the control of this driver
  */
-static int ps3_gelic_driver_probe(struct ps3_system_bus_device *dev)
+static int __devinit ps3_gelic_driver_probe(struct ps3_system_bus_device *dev)
 {
 	struct gelic_card *card;
 	struct net_device *netdev;
diff --git a/drivers/net/ps3_gelic_wireless.c b/drivers/net/ps3_gelic_wireless.c
index 4f3ada6..b6b3ca9 100644
--- a/drivers/net/ps3_gelic_wireless.c
+++ b/drivers/net/ps3_gelic_wireless.c
@@ -2442,7 +2442,7 @@
 #endif
 };
 
-static struct net_device *gelic_wl_alloc(struct gelic_card *card)
+static struct net_device * __devinit gelic_wl_alloc(struct gelic_card *card)
 {
 	struct net_device *netdev;
 	struct gelic_port *port;
@@ -2722,7 +2722,7 @@
 	.set_rx_csum	= gelic_net_set_rx_csum,
 };
 
-static void gelic_wl_setup_netdev_ops(struct net_device *netdev)
+static void __devinit gelic_wl_setup_netdev_ops(struct net_device *netdev)
 {
 	struct gelic_wl_info *wl;
 	wl = port_wl(netdev_priv(netdev));
@@ -2738,7 +2738,7 @@
 /*
  * driver probe/remove
  */
-int gelic_wl_driver_probe(struct gelic_card *card)
+int __devinit gelic_wl_driver_probe(struct gelic_card *card)
 {
 	int ret;
 	struct net_device *netdev;
diff --git a/drivers/net/r8169.c b/drivers/net/r8169.c
index 35196fa..4e22462 100644
--- a/drivers/net/r8169.c
+++ b/drivers/net/r8169.c
@@ -3811,22 +3811,11 @@
 
 static void rtl8169_net_suspend(struct net_device *dev)
 {
-	struct rtl8169_private *tp = netdev_priv(dev);
-	void __iomem *ioaddr = tp->mmio_addr;
-
 	if (!netif_running(dev))
 		return;
 
 	netif_device_detach(dev);
 	netif_stop_queue(dev);
-
-	spin_lock_irq(&tp->lock);
-
-	rtl8169_asic_down(ioaddr);
-
-	rtl8169_rx_missed(dev, ioaddr);
-
-	spin_unlock_irq(&tp->lock);
 }
 
 #ifdef CONFIG_PM
@@ -3876,9 +3865,17 @@
 static void rtl_shutdown(struct pci_dev *pdev)
 {
 	struct net_device *dev = pci_get_drvdata(pdev);
+	struct rtl8169_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
 
 	rtl8169_net_suspend(dev);
 
+	spin_lock_irq(&tp->lock);
+
+	rtl8169_asic_down(ioaddr);
+
+	spin_unlock_irq(&tp->lock);
+
 	if (system_state == SYSTEM_POWER_OFF) {
 		pci_wake_from_d3(pdev, true);
 		pci_set_power_state(pdev, PCI_D3hot);
diff --git a/drivers/net/sis190.c b/drivers/net/sis190.c
index e224766..1f040e8 100644
--- a/drivers/net/sis190.c
+++ b/drivers/net/sis190.c
@@ -1281,7 +1281,7 @@
 		else if (phy_lan)
 			phy_default = phy_lan;
 		else
-			phy_default = list_entry(&tp->first_phy,
+			phy_default = list_first_entry(&tp->first_phy,
 						 struct sis190_phy, list);
 	}
 
diff --git a/drivers/net/sky2.c b/drivers/net/sky2.c
index 6b5946f..7681d28 100644
--- a/drivers/net/sky2.c
+++ b/drivers/net/sky2.c
@@ -50,7 +50,7 @@
 #include "sky2.h"
 
 #define DRV_NAME		"sky2"
-#define DRV_VERSION		"1.22"
+#define DRV_VERSION		"1.23"
 #define PFX			DRV_NAME " "
 
 /*
@@ -65,9 +65,9 @@
 #define RX_DEF_PENDING		RX_MAX_PENDING
 
 #define TX_RING_SIZE		512
-#define TX_DEF_PENDING		(TX_RING_SIZE - 1)
-#define TX_MIN_PENDING		64
+#define TX_DEF_PENDING		128
 #define MAX_SKB_TX_LE		(4 + (sizeof(dma_addr_t)/sizeof(u32))*MAX_SKB_FRAGS)
+#define TX_MIN_PENDING		(MAX_SKB_TX_LE+1)
 
 #define STATUS_RING_SIZE	2048	/* 2 ports * (TX + 2*RX) */
 #define STATUS_LE_BYTES		(STATUS_RING_SIZE*sizeof(struct sky2_status_le))
@@ -1151,7 +1151,14 @@
 
 	/* reset the Rx prefetch unit */
 	sky2_write32(hw, Y2_QADDR(rxq, PREF_UNIT_CTRL), PREF_UNIT_RST_SET);
-	mmiowb();
+
+	/* Reset the RAM Buffer receive queue */
+	sky2_write8(hw, RB_ADDR(rxq, RB_CTRL), RB_RST_SET);
+
+	/* Reset Rx MAC FIFO */
+	sky2_write8(hw, SK_REG(sky2->port, RX_GMF_CTRL_T), GMF_RST_SET);
+
+	sky2_read8(hw, B0_CTST);
 }
 
 /* Clean out receive buffer area, assumes receiver hardware stopped */
@@ -1169,6 +1176,7 @@
 			re->skb = NULL;
 		}
 	}
+	skb_queue_purge(&sky2->rx_recycle);
 }
 
 /* Basic MII support */
@@ -1245,6 +1253,12 @@
 }
 #endif
 
+/* Amount of required worst case padding in rx buffer */
+static inline unsigned sky2_rx_pad(const struct sky2_hw *hw)
+{
+	return (hw->flags & SKY2_HW_RAM_BUFFER) ? 8 : 2;
+}
+
 /*
  * Allocate an skb for receiving. If the MTU is large enough
  * make the skb non-linear with a fragment list of pages.
@@ -1254,6 +1268,13 @@
 	struct sk_buff *skb;
 	int i;
 
+	skb = __skb_dequeue(&sky2->rx_recycle);
+	if (!skb)
+		skb = netdev_alloc_skb(sky2->netdev, sky2->rx_data_size
+				       + sky2_rx_pad(sky2->hw));
+	if (!skb)
+		goto nomem;
+
 	if (sky2->hw->flags & SKY2_HW_RAM_BUFFER) {
 		unsigned char *start;
 		/*
@@ -1262,18 +1283,10 @@
 		 * The buffer returned from netdev_alloc_skb is
 		 * aligned except if slab debugging is enabled.
 		 */
-		skb = netdev_alloc_skb(sky2->netdev, sky2->rx_data_size + 8);
-		if (!skb)
-			goto nomem;
 		start = PTR_ALIGN(skb->data, 8);
 		skb_reserve(skb, start - skb->data);
-	} else {
-		skb = netdev_alloc_skb(sky2->netdev,
-				       sky2->rx_data_size + NET_IP_ALIGN);
-		if (!skb)
-			goto nomem;
+	} else
 		skb_reserve(skb, NET_IP_ALIGN);
-	}
 
 	for (i = 0; i < sky2->rx_nfrags; i++) {
 		struct page *page = alloc_page(GFP_ATOMIC);
@@ -1350,6 +1363,8 @@
 
 	sky2->rx_data_size = size;
 
+	skb_queue_head_init(&sky2->rx_recycle);
+
 	/* Fill Rx ring */
 	for (i = 0; i < sky2->rx_pending; i++) {
 		re = sky2->rx_ring + i;
@@ -1488,6 +1503,7 @@
 	imask = sky2_read32(hw, B0_IMSK);
 	imask |= portirq_msk[port];
 	sky2_write32(hw, B0_IMSK, imask);
+	sky2_read32(hw, B0_IMSK);
 
 	sky2_set_multicast(dev);
 
@@ -1756,14 +1772,22 @@
 		}
 
 		if (le->ctrl & EOP) {
+			struct sk_buff *skb = re->skb;
+
 			if (unlikely(netif_msg_tx_done(sky2)))
 				printk(KERN_DEBUG "%s: tx done %u\n",
 				       dev->name, idx);
 
 			dev->stats.tx_packets++;
-			dev->stats.tx_bytes += re->skb->len;
+			dev->stats.tx_bytes += skb->len;
 
-			dev_kfree_skb_any(re->skb);
+			if (skb_queue_len(&sky2->rx_recycle) < sky2->rx_pending
+			    && skb_recycle_check(skb, sky2->rx_data_size
+						 + sky2_rx_pad(sky2->hw)))
+				__skb_queue_head(&sky2->rx_recycle, skb);
+			else
+				dev_kfree_skb_any(skb);
+
 			sky2->tx_next = RING_NEXT(idx, TX_RING_SIZE);
 		}
 	}
@@ -1805,10 +1829,10 @@
 	imask = sky2_read32(hw, B0_IMSK);
 	imask &= ~portirq_msk[port];
 	sky2_write32(hw, B0_IMSK, imask);
+	sky2_read32(hw, B0_IMSK);
 
-	synchronize_irq(hw->pdev->irq);
-
-	sky2_gmac_reset(hw, port);
+	/* Force flow control off */
+	sky2_write8(hw, SK_REG(port, GMAC_CTRL), GMC_PAUSE_OFF);
 
 	/* Stop transmitter */
 	sky2_write32(hw, Q_ADDR(txqaddr[port], Q_CSR), BMU_STOP);
@@ -1821,9 +1845,6 @@
 	ctrl &= ~(GM_GPCR_TX_ENA | GM_GPCR_RX_ENA);
 	gma_write16(hw, port, GM_GP_CTRL, ctrl);
 
-	/* Make sure no packets are pending */
-	napi_synchronize(&hw->napi);
-
 	sky2_write8(hw, SK_REG(port, GPHY_CTRL), GPC_RST_SET);
 
 	/* Workaround shared GMAC reset */
@@ -1854,6 +1875,15 @@
 	sky2_write8(hw, SK_REG(port, RX_GMF_CTRL_T), GMF_RST_SET);
 	sky2_write8(hw, SK_REG(port, TX_GMF_CTRL_T), GMF_RST_SET);
 
+	/* Force any delayed status interrrupt and NAPI */
+	sky2_write32(hw, STAT_LEV_TIMER_CNT, 0);
+	sky2_write32(hw, STAT_TX_TIMER_CNT, 0);
+	sky2_write32(hw, STAT_ISR_TIMER_CNT, 0);
+	sky2_read8(hw, STAT_ISR_TIMER_CTRL);
+
+	synchronize_irq(hw->pdev->irq);
+	napi_synchronize(&hw->napi);
+
 	sky2_phy_power_down(hw, port);
 
 	/* turn off LED's */
@@ -2343,11 +2373,45 @@
 	}
 }
 
+static inline void sky2_skb_rx(const struct sky2_port *sky2,
+			       u32 status, struct sk_buff *skb)
+{
+#ifdef SKY2_VLAN_TAG_USED
+	u16 vlan_tag = be16_to_cpu(sky2->rx_tag);
+	if (sky2->vlgrp && (status & GMR_FS_VLAN)) {
+		if (skb->ip_summed == CHECKSUM_NONE)
+			vlan_hwaccel_receive_skb(skb, sky2->vlgrp, vlan_tag);
+		else
+			vlan_gro_receive(&sky2->hw->napi, sky2->vlgrp,
+					 vlan_tag, skb);
+		return;
+	}
+#endif
+	if (skb->ip_summed == CHECKSUM_NONE)
+		netif_receive_skb(skb);
+	else
+		napi_gro_receive(&sky2->hw->napi, skb);
+}
+
+static inline void sky2_rx_done(struct sky2_hw *hw, unsigned port,
+				unsigned packets, unsigned bytes)
+{
+	if (packets) {
+		struct net_device *dev = hw->dev[port];
+
+		dev->stats.rx_packets += packets;
+		dev->stats.rx_bytes += bytes;
+		dev->last_rx = jiffies;
+		sky2_rx_update(netdev_priv(dev), rxqaddr[port]);
+	}
+}
+
 /* Process status response ring */
 static int sky2_status_intr(struct sky2_hw *hw, int to_do, u16 idx)
 {
 	int work_done = 0;
-	unsigned rx[2] = { 0, 0 };
+	unsigned int total_bytes[2] = { 0 };
+	unsigned int total_packets[2] = { 0 };
 
 	rmb();
 	do {
@@ -2374,7 +2438,8 @@
 		le->opcode = 0;
 		switch (opcode & ~HW_OWNER) {
 		case OP_RXSTAT:
-			++rx[port];
+			total_packets[port]++;
+			total_bytes[port] += length;
 			skb = sky2_receive(dev, length, status);
 			if (unlikely(!skb)) {
 				dev->stats.rx_dropped++;
@@ -2392,18 +2457,8 @@
 			}
 
 			skb->protocol = eth_type_trans(skb, dev);
-			dev->stats.rx_packets++;
-			dev->stats.rx_bytes += skb->len;
-			dev->last_rx = jiffies;
 
-#ifdef SKY2_VLAN_TAG_USED
-			if (sky2->vlgrp && (status & GMR_FS_VLAN)) {
-				vlan_hwaccel_receive_skb(skb,
-							 sky2->vlgrp,
-							 be16_to_cpu(sky2->rx_tag));
-			} else
-#endif
-				netif_receive_skb(skb);
+			sky2_skb_rx(sky2, status, skb);
 
 			/* Stop after net poll weight */
 			if (++work_done >= to_do)
@@ -2473,11 +2528,8 @@
 	sky2_write32(hw, STAT_CTRL, SC_STAT_CLR_IRQ);
 
 exit_loop:
-	if (rx[0])
-		sky2_rx_update(netdev_priv(hw->dev[0]), Q_R1);
-
-	if (rx[1])
-		sky2_rx_update(netdev_priv(hw->dev[1]), Q_R2);
+	sky2_rx_done(hw, 0, total_packets[0], total_bytes[0]);
+	sky2_rx_done(hw, 1, total_packets[1], total_bytes[1]);
 
 	return work_done;
 }
@@ -4364,6 +4416,22 @@
 		goto err_out;
 	}
 
+	/* Get configuration information
+	 * Note: only regular PCI config access once to test for HW issues
+	 *       other PCI access through shared memory for speed and to
+	 *	 avoid MMCONFIG problems.
+	 */
+	err = pci_read_config_dword(pdev, PCI_DEV_REG2, &reg);
+	if (err) {
+		dev_err(&pdev->dev, "PCI read config failed\n");
+		goto err_out;
+	}
+
+	if (~reg == 0) {
+		dev_err(&pdev->dev, "PCI configuration read error\n");
+		goto err_out;
+	}
+
 	err = pci_request_regions(pdev, DRV_NAME);
 	if (err) {
 		dev_err(&pdev->dev, "cannot obtain PCI resources\n");
@@ -4389,21 +4457,6 @@
 		}
 	}
 
-	/* Get configuration information
-	 * Note: only regular PCI config access once to test for HW issues
-	 *       other PCI access through shared memory for speed and to
-	 *	 avoid MMCONFIG problems.
-	 */
-	err = pci_read_config_dword(pdev, PCI_DEV_REG2, &reg);
-	if (err) {
-		dev_err(&pdev->dev, "PCI read config failed\n");
-		goto err_out_free_regions;
-	}
-
-	/* size of available VPD, only impact sysfs */
-	err = pci_vpd_truncate(pdev, 1ul << (((reg & PCI_VPD_ROM_SZ) >> 14) + 8));
-	if (err)
-		dev_warn(&pdev->dev, "Can't set VPD size\n");
 
 #ifdef __BIG_ENDIAN
 	/* The sk98lin vendor driver uses hardware byte swapping but
diff --git a/drivers/net/sky2.h b/drivers/net/sky2.h
index 92fb24b..b5549c9 100644
--- a/drivers/net/sky2.h
+++ b/drivers/net/sky2.h
@@ -2028,6 +2028,7 @@
 	u16		     rx_pending;
 	u16		     rx_data_size;
 	u16		     rx_nfrags;
+	struct sk_buff_head  rx_recycle;
 
 #ifdef SKY2_VLAN_TAG_USED
 	u16		     rx_tag;
diff --git a/drivers/net/sonic.c b/drivers/net/sonic.c
index e4255d8..753a1fb 100644
--- a/drivers/net/sonic.c
+++ b/drivers/net/sonic.c
@@ -223,7 +223,7 @@
 	if (!laddr) {
 		printk(KERN_ERR "%s: failed to map tx DMA buffer.\n", dev->name);
 		dev_kfree_skb(skb);
-		return NETDEV_TX_BUSY
+		return NETDEV_TX_BUSY;
 	}
 
 	sonic_tda_put(dev, entry, SONIC_TD_STATUS, 0);       /* clear status */
diff --git a/drivers/net/ucc_geth.c b/drivers/net/ucc_geth.c
index e2f2e91..40c6eba 100644
--- a/drivers/net/ucc_geth.c
+++ b/drivers/net/ucc_geth.c
@@ -65,8 +65,6 @@
 
 static DEFINE_SPINLOCK(ugeth_lock);
 
-static void uec_configure_serdes(struct net_device *dev);
-
 static struct {
 	u32 msg_enable;
 } debug = { -1 };
@@ -1536,6 +1534,49 @@
 	spin_unlock_irqrestore(&ugeth->lock, flags);
 }
 
+/* Initialize TBI PHY interface for communicating with the
+ * SERDES lynx PHY on the chip.  We communicate with this PHY
+ * through the MDIO bus on each controller, treating it as a
+ * "normal" PHY at the address found in the UTBIPA register.  We assume
+ * that the UTBIPA register is valid.  Either the MDIO bus code will set
+ * it to a value that doesn't conflict with other PHYs on the bus, or the
+ * value doesn't matter, as there are no other PHYs on the bus.
+ */
+static void uec_configure_serdes(struct net_device *dev)
+{
+	struct ucc_geth_private *ugeth = netdev_priv(dev);
+	struct ucc_geth_info *ug_info = ugeth->ug_info;
+	struct phy_device *tbiphy;
+
+	if (!ug_info->tbi_node) {
+		dev_warn(&dev->dev, "SGMII mode requires that the device "
+			"tree specify a tbi-handle\n");
+		return;
+	}
+
+	tbiphy = of_phy_find_device(ug_info->tbi_node);
+	if (!tbiphy) {
+		dev_err(&dev->dev, "error: Could not get TBI device\n");
+		return;
+	}
+
+	/*
+	 * If the link is already up, we must already be ok, and don't need to
+	 * configure and reset the TBI<->SerDes link.  Maybe U-Boot configured
+	 * everything for us?  Resetting it takes the link down and requires
+	 * several seconds for it to come back.
+	 */
+	if (phy_read(tbiphy, ENET_TBI_MII_SR) & TBISR_LSTATUS)
+		return;
+
+	/* Single clk mode, mii mode off(for serdes communication) */
+	phy_write(tbiphy, ENET_TBI_MII_ANA, TBIANA_SETTINGS);
+
+	phy_write(tbiphy, ENET_TBI_MII_TBICON, TBICON_CLK_SELECT);
+
+	phy_write(tbiphy, ENET_TBI_MII_CR, TBICR_SETTINGS);
+}
+
 /* Configure the PHY for dev.
  * returns 0 if success.  -1 if failure
  */
@@ -1577,41 +1618,7 @@
 	return 0;
 }
 
-/* Initialize TBI PHY interface for communicating with the
- * SERDES lynx PHY on the chip.  We communicate with this PHY
- * through the MDIO bus on each controller, treating it as a
- * "normal" PHY at the address found in the UTBIPA register.  We assume
- * that the UTBIPA register is valid.  Either the MDIO bus code will set
- * it to a value that doesn't conflict with other PHYs on the bus, or the
- * value doesn't matter, as there are no other PHYs on the bus.
- */
-static void uec_configure_serdes(struct net_device *dev)
-{
-	struct ucc_geth_private *ugeth = netdev_priv(dev);
 
-	if (!ugeth->tbiphy) {
-		printk(KERN_WARNING "SGMII mode requires that the device "
-			"tree specify a tbi-handle\n");
-	return;
-	}
-
-	/*
-	 * If the link is already up, we must already be ok, and don't need to
-	 * configure and reset the TBI<->SerDes link.  Maybe U-Boot configured
-	 * everything for us?  Resetting it takes the link down and requires
-	 * several seconds for it to come back.
-	 */
-	if (phy_read(ugeth->tbiphy, ENET_TBI_MII_SR) & TBISR_LSTATUS)
-		return;
-
-	/* Single clk mode, mii mode off(for serdes communication) */
-	phy_write(ugeth->tbiphy, ENET_TBI_MII_ANA, TBIANA_SETTINGS);
-
-	phy_write(ugeth->tbiphy, ENET_TBI_MII_TBICON, TBICON_CLK_SELECT);
-
-	phy_write(ugeth->tbiphy, ENET_TBI_MII_CR, TBICR_SETTINGS);
-
-}
 
 static int ugeth_graceful_stop_tx(struct ucc_geth_private *ugeth)
 {
@@ -3711,6 +3718,9 @@
 	}
 	ug_info->phy_node = phy;
 
+	/* Find the TBI PHY node.  If it's not there, we don't support SGMII */
+	ug_info->tbi_node = of_parse_phandle(np, "tbi-handle", 0);
+
 	/* get the phy interface type, or default to MII */
 	prop = of_get_property(np, "phy-connection-type", NULL);
 	if (!prop) {
@@ -3818,37 +3828,6 @@
 	ugeth->ndev = dev;
 	ugeth->node = np;
 
-	/* Find the TBI PHY.  If it's not there, we don't support SGMII */
-	ph = of_get_property(np, "tbi-handle", NULL);
-	if (ph) {
-		struct device_node *tbi = of_find_node_by_phandle(*ph);
-		struct of_device *ofdev;
-		struct mii_bus *bus;
-		const unsigned int *id;
-
-		if (!tbi)
-			return 0;
-
-		mdio = of_get_parent(tbi);
-		if (!mdio)
-			return 0;
-
-		ofdev = of_find_device_by_node(mdio);
-
-		of_node_put(mdio);
-
-		id = of_get_property(tbi, "reg", NULL);
-		if (!id)
-			return 0;
-		of_node_put(tbi);
-
-		bus = dev_get_drvdata(&ofdev->dev);
-		if (!bus)
-			return 0;
-
-		ugeth->tbiphy = bus->phy_map[*id];
-	}
-
 	return 0;
 }
 
diff --git a/drivers/net/ucc_geth.h b/drivers/net/ucc_geth.h
index 5beba4c..195ab26 100644
--- a/drivers/net/ucc_geth.h
+++ b/drivers/net/ucc_geth.h
@@ -1125,6 +1125,7 @@
 	u16 pausePeriod;
 	u16 extensionField;
 	struct device_node *phy_node;
+	struct device_node *tbi_node;
 	u8 weightfactor[NUM_TX_QUEUES];
 	u8 interruptcoalescingmaxvalue[NUM_RX_QUEUES];
 	u8 l2qt[UCC_GETH_VLAN_PRIORITY_MAX];
@@ -1213,7 +1214,6 @@
 
 	struct ugeth_mii_info *mii_info;
 	struct phy_device *phydev;
-	struct phy_device *tbiphy;
 	phy_interface_t phy_interface;
 	int max_speed;
 	uint32_t msg_enable;
diff --git a/drivers/net/via-velocity.c b/drivers/net/via-velocity.c
index e2a7725..b02f7ad 100644
--- a/drivers/net/via-velocity.c
+++ b/drivers/net/via-velocity.c
@@ -989,8 +989,10 @@
 	if (ret < 0)
 		goto err_iounmap;
 
-	if (velocity_get_link(dev))
+	if (!velocity_get_link(dev)) {
 		netif_carrier_off(dev);
+		vptr->mii_status |= VELOCITY_LINK_FAIL;
+	}
 
 	velocity_print_info(vptr);
 	pci_set_drvdata(pdev, dev);
diff --git a/drivers/net/virtio_net.c b/drivers/net/virtio_net.c
index 52198f6..2a6e81d 100644
--- a/drivers/net/virtio_net.c
+++ b/drivers/net/virtio_net.c
@@ -709,7 +709,7 @@
 			 allmulti ? "en" : "dis");
 
 	/* MAC filter - use one buffer for both lists */
-	mac_data = buf = kzalloc(((dev->uc_count + dev->mc_count) * ETH_ALEN) +
+	mac_data = buf = kzalloc(((dev->uc.count + dev->mc_count) * ETH_ALEN) +
 				 (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
 	if (!buf) {
 		dev_warn(&dev->dev, "No memory for MAC address buffer\n");
@@ -719,16 +719,16 @@
 	sg_init_table(sg, 2);
 
 	/* Store the unicast list and count in the front of the buffer */
-	mac_data->entries = dev->uc_count;
+	mac_data->entries = dev->uc.count;
 	i = 0;
-	list_for_each_entry(ha, &dev->uc_list, list)
+	list_for_each_entry(ha, &dev->uc.list, list)
 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
 
 	sg_set_buf(&sg[0], mac_data,
-		   sizeof(mac_data->entries) + (dev->uc_count * ETH_ALEN));
+		   sizeof(mac_data->entries) + (dev->uc.count * ETH_ALEN));
 
 	/* multicast list and count fill the end */
-	mac_data = (void *)&mac_data->macs[dev->uc_count][0];
+	mac_data = (void *)&mac_data->macs[dev->uc.count][0];
 
 	mac_data->entries = dev->mc_count;
 	addr = dev->mc_list;
diff --git a/drivers/net/vxge/vxge-config.c b/drivers/net/vxge/vxge-config.c
index 26cde57..58d2551 100644
--- a/drivers/net/vxge/vxge-config.c
+++ b/drivers/net/vxge/vxge-config.c
@@ -454,7 +454,7 @@
 	return VXGE_HW_OK;
 }
 
-static enum vxge_hw_status
+enum vxge_hw_status
 __vxge_hw_device_is_privilaged(struct __vxge_hw_device *hldev)
 {
 	if ((hldev->host_type == VXGE_HW_NO_MR_NO_SR_NORMAL_FUNCTION ||
@@ -676,10 +676,12 @@
 {
 	enum vxge_hw_status status = VXGE_HW_OK;
 
-	/* Validate the pci-e link width and speed */
-	status = __vxge_hw_verify_pci_e_info(hldev);
-	if (status != VXGE_HW_OK)
-		goto exit;
+	if (VXGE_HW_OK == __vxge_hw_device_is_privilaged(hldev)) {
+		/* Validate the pci-e link width and speed */
+		status = __vxge_hw_verify_pci_e_info(hldev);
+		if (status != VXGE_HW_OK)
+			goto exit;
+	}
 
 	vxge_hw_wrr_rebalance(hldev);
 exit:
diff --git a/drivers/net/vxge/vxge-main.c b/drivers/net/vxge/vxge-main.c
index 6c838b3..6034497 100644
--- a/drivers/net/vxge/vxge-main.c
+++ b/drivers/net/vxge/vxge-main.c
@@ -4203,6 +4203,16 @@
 		max_vpath_supported++;
 	}
 
+	/* Enable SRIOV mode, if firmware has SRIOV support and if it is a PF */
+	if ((VXGE_HW_FUNCTION_MODE_SRIOV ==
+		ll_config.device_hw_info.function_mode) &&
+		(max_config_dev > 1) && (pdev->is_physfn)) {
+			ret = pci_enable_sriov(pdev, max_config_dev - 1);
+			if (ret)
+				vxge_debug_ll_config(VXGE_ERR,
+					"Failed to enable SRIOV: %d \n", ret);
+	}
+
 	/*
 	 * Configure vpaths and get driver configured number of vpaths
 	 * which is less than or equal to the maximum vpaths per function.
@@ -4366,6 +4376,7 @@
 
 	vxge_device_unregister(hldev);
 _exit5:
+	pci_disable_sriov(pdev);
 	vxge_hw_device_terminate(hldev);
 _exit4:
 	iounmap(attr.bar1);
@@ -4429,6 +4440,8 @@
 	iounmap(vdev->bar0);
 	iounmap(vdev->bar1);
 
+	pci_disable_sriov(pdev);
+
 	/* we are safe to free it now */
 	free_netdev(dev);
 
diff --git a/drivers/net/vxge/vxge-version.h b/drivers/net/vxge/vxge-version.h
index 7da02c5..82786ff 100644
--- a/drivers/net/vxge/vxge-version.h
+++ b/drivers/net/vxge/vxge-version.h
@@ -17,7 +17,7 @@
 
 #define VXGE_VERSION_MAJOR	"2"
 #define VXGE_VERSION_MINOR	"0"
-#define VXGE_VERSION_FIX	"1"
-#define VXGE_VERSION_BUILD	"17129"
+#define VXGE_VERSION_FIX	"4"
+#define VXGE_VERSION_BUILD	"17795"
 #define VXGE_VERSION_FOR	"k"
 #endif
diff --git a/drivers/net/wan/lapbether.c b/drivers/net/wan/lapbether.c
index 2dd78d2..aff4f6bd 100644
--- a/drivers/net/wan/lapbether.c
+++ b/drivers/net/wan/lapbether.c
@@ -149,46 +149,40 @@
  */
 static int lapbeth_xmit(struct sk_buff *skb, struct net_device *dev)
 {
-	int err = -ENODEV;
+	int err;
 
 	/*
 	 * Just to be *really* sure not to send anything if the interface
 	 * is down, the ethernet device may have gone.
 	 */
-	if (!netif_running(dev)) {
+	if (!netif_running(dev))
 		goto drop;
-	}
 
 	switch (skb->data[0]) {
 	case 0x00:
-		err = 0;
 		break;
 	case 0x01:
 		if ((err = lapb_connect_request(dev)) != LAPB_OK)
 			printk(KERN_ERR "lapbeth: lapb_connect_request "
 			       "error: %d\n", err);
-		goto drop_ok;
+		goto drop;
 	case 0x02:
 		if ((err = lapb_disconnect_request(dev)) != LAPB_OK)
 			printk(KERN_ERR "lapbeth: lapb_disconnect_request "
 			       "err: %d\n", err);
 		/* Fall thru */
 	default:
-		goto drop_ok;
+		goto drop;
 	}
 
 	skb_pull(skb, 1);
 
 	if ((err = lapb_data_request(dev, skb)) != LAPB_OK) {
 		printk(KERN_ERR "lapbeth: lapb_data_request error - %d\n", err);
-		err = -ENOMEM;
 		goto drop;
 	}
-	err = 0;
 out:
-	return err;
-drop_ok:
-	err = 0;
+	return NETDEV_TX_OK;
 drop:
 	kfree_skb(skb);
 	goto out;
diff --git a/drivers/net/wireless/ath/ath5k/pcu.c b/drivers/net/wireless/ath/ath5k/pcu.c
index ec35503..2942f13 100644
--- a/drivers/net/wireless/ath/ath5k/pcu.c
+++ b/drivers/net/wireless/ath/ath5k/pcu.c
@@ -733,8 +733,9 @@
 	/*
 	 * Set the beacon register and enable all timers.
 	 */
-	/* When in AP mode zero timer0 to start TSF */
-	if (ah->ah_op_mode == NL80211_IFTYPE_AP)
+	/* When in AP or Mesh Point mode zero timer0 to start TSF */
+	if (ah->ah_op_mode == NL80211_IFTYPE_AP ||
+	    ah->ah_op_mode == NL80211_IFTYPE_MESH_POINT)
 		ath5k_hw_reg_write(ah, 0, AR5K_TIMER0);
 
 	ath5k_hw_reg_write(ah, next_beacon, AR5K_TIMER0);
diff --git a/drivers/net/wireless/ath/ath9k/Kconfig b/drivers/net/wireless/ath/ath9k/Kconfig
index 0ed1ac3..2d79610 100644
--- a/drivers/net/wireless/ath/ath9k/Kconfig
+++ b/drivers/net/wireless/ath/ath9k/Kconfig
@@ -1,7 +1,6 @@
 config ATH9K
 	tristate "Atheros 802.11n wireless cards support"
 	depends on PCI && MAC80211 && WLAN_80211
-	depends on RFKILL || RFKILL=n
 	select ATH_COMMON
 	select MAC80211_LEDS
 	select LEDS_CLASS
diff --git a/drivers/net/wireless/ath/ath9k/ath9k.h b/drivers/net/wireless/ath/ath9k/ath9k.h
index 515880a..5efc934 100644
--- a/drivers/net/wireless/ath/ath9k/ath9k.h
+++ b/drivers/net/wireless/ath/ath9k/ath9k.h
@@ -21,7 +21,6 @@
 #include <linux/device.h>
 #include <net/mac80211.h>
 #include <linux/leds.h>
-#include <linux/rfkill.h>
 
 #include "hw.h"
 #include "rc.h"
@@ -460,12 +459,6 @@
 	bool registered;
 };
 
-struct ath_rfkill {
-	struct rfkill *rfkill;
-	struct rfkill_ops ops;
-	char rfkill_name[32];
-};
-
 /********************/
 /* Main driver core */
 /********************/
@@ -505,7 +498,6 @@
 #define SC_OP_PROTECT_ENABLE    BIT(6)
 #define SC_OP_RXFLUSH           BIT(7)
 #define SC_OP_LED_ASSOCIATED    BIT(8)
-#define SC_OP_RFKILL_REGISTERED BIT(9)
 #define SC_OP_WAIT_FOR_BEACON   BIT(12)
 #define SC_OP_LED_ON            BIT(13)
 #define SC_OP_SCANNING          BIT(14)
@@ -591,7 +583,6 @@
 
 	int beacon_interval;
 
-	struct ath_rfkill rf_kill;
 	struct ath_ani ani;
 	struct ath9k_node_stats nodestats;
 #ifdef CONFIG_ATH9K_DEBUG
@@ -677,6 +668,7 @@
 	if (atomic_dec_and_test(&sc->ps_usecount))
 		if ((sc->hw->conf.flags & IEEE80211_CONF_PS) &&
 		    !(sc->sc_flags & (SC_OP_WAIT_FOR_BEACON |
+				      SC_OP_WAIT_FOR_CAB |
 				      SC_OP_WAIT_FOR_PSPOLL_DATA |
 				      SC_OP_WAIT_FOR_TX_ACK)))
 			ath9k_hw_setpower(sc->sc_ah,
diff --git a/drivers/net/wireless/ath/ath9k/hw.c b/drivers/net/wireless/ath/ath9k/hw.c
index 1579c94..34935a8 100644
--- a/drivers/net/wireless/ath/ath9k/hw.c
+++ b/drivers/net/wireless/ath/ath9k/hw.c
@@ -2186,6 +2186,18 @@
 	REG_WRITE(ah, AR_PHY_MASK2_P_61_45, tmp_mask);
 }
 
+static void ath9k_enable_rfkill(struct ath_hw *ah)
+{
+	REG_SET_BIT(ah, AR_GPIO_INPUT_EN_VAL,
+		    AR_GPIO_INPUT_EN_VAL_RFSILENT_BB);
+
+	REG_CLR_BIT(ah, AR_GPIO_INPUT_MUX2,
+		    AR_GPIO_INPUT_MUX2_RFSILENT);
+
+	ath9k_hw_cfg_gpio_input(ah, ah->rfkill_gpio);
+	REG_SET_BIT(ah, AR_PHY_TEST, RFSILENT_BB);
+}
+
 int ath9k_hw_reset(struct ath_hw *ah, struct ath9k_channel *chan,
 		    bool bChannelChange)
 {
@@ -2313,10 +2325,9 @@
 	ath9k_hw_init_interrupt_masks(ah, ah->opmode);
 	ath9k_hw_init_qos(ah);
 
-#if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
 	if (ah->caps.hw_caps & ATH9K_HW_CAP_RFSILENT)
 		ath9k_enable_rfkill(ah);
-#endif
+
 	ath9k_hw_init_user_settings(ah);
 
 	REG_WRITE(ah, AR_STA_ID1,
@@ -3613,20 +3624,6 @@
 		AR_GPIO_BIT(gpio));
 }
 
-#if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
-void ath9k_enable_rfkill(struct ath_hw *ah)
-{
-	REG_SET_BIT(ah, AR_GPIO_INPUT_EN_VAL,
-		    AR_GPIO_INPUT_EN_VAL_RFSILENT_BB);
-
-	REG_CLR_BIT(ah, AR_GPIO_INPUT_MUX2,
-		    AR_GPIO_INPUT_MUX2_RFSILENT);
-
-	ath9k_hw_cfg_gpio_input(ah, ah->rfkill_gpio);
-	REG_SET_BIT(ah, AR_PHY_TEST, RFSILENT_BB);
-}
-#endif
-
 u32 ath9k_hw_getdefantenna(struct ath_hw *ah)
 {
 	return REG_READ(ah, AR_DEF_ANTENNA) & 0x7;
diff --git a/drivers/net/wireless/ath/ath9k/hw.h b/drivers/net/wireless/ath/ath9k/hw.h
index dd8508e..9d0b31a 100644
--- a/drivers/net/wireless/ath/ath9k/hw.h
+++ b/drivers/net/wireless/ath/ath9k/hw.h
@@ -565,9 +565,6 @@
 void ath9k_hw_cfg_output(struct ath_hw *ah, u32 gpio,
 			 u32 ah_signal_type);
 void ath9k_hw_set_gpio(struct ath_hw *ah, u32 gpio, u32 val);
-#if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
-void ath9k_enable_rfkill(struct ath_hw *ah);
-#endif
 u32 ath9k_hw_getdefantenna(struct ath_hw *ah);
 void ath9k_hw_setantenna(struct ath_hw *ah, u32 antenna);
 bool ath9k_hw_setantennaswitch(struct ath_hw *ah,
diff --git a/drivers/net/wireless/ath/ath9k/main.c b/drivers/net/wireless/ath/ath9k/main.c
index f7baa40..9f49a32 100644
--- a/drivers/net/wireless/ath/ath9k/main.c
+++ b/drivers/net/wireless/ath/ath9k/main.c
@@ -231,6 +231,19 @@
 	}
 }
 
+static struct ath9k_channel *ath_get_curchannel(struct ath_softc *sc,
+						struct ieee80211_hw *hw)
+{
+	struct ieee80211_channel *curchan = hw->conf.channel;
+	struct ath9k_channel *channel;
+	u8 chan_idx;
+
+	chan_idx = curchan->hw_value;
+	channel = &sc->sc_ah->channels[chan_idx];
+	ath9k_update_ichannel(sc, hw, channel);
+	return channel;
+}
+
 /*
  * Set/change channels.  If the channel is really being changed, it's done
  * by reseting the chip.  To accomplish this we must first cleanup any pending
@@ -283,7 +296,7 @@
 			"reset status %d\n",
 			channel->center_freq, r);
 		spin_unlock_bh(&sc->sc_resetlock);
-		return r;
+		goto ps_restore;
 	}
 	spin_unlock_bh(&sc->sc_resetlock);
 
@@ -292,14 +305,17 @@
 	if (ath_startrecv(sc) != 0) {
 		DPRINTF(sc, ATH_DBG_FATAL,
 			"Unable to restart recv logic\n");
-		return -EIO;
+		r = -EIO;
+		goto ps_restore;
 	}
 
 	ath_cache_conf_rate(sc, &hw->conf);
 	ath_update_txpow(sc);
 	ath9k_hw_set_interrupts(ah, sc->imask);
+
+ ps_restore:
 	ath9k_ps_restore(sc);
-	return 0;
+	return r;
 }
 
 /*
@@ -1110,6 +1126,9 @@
 	ath9k_ps_wakeup(sc);
 	ath9k_hw_configpcipowersave(ah, 0);
 
+	if (!ah->curchan)
+		ah->curchan = ath_get_curchannel(sc, sc->hw);
+
 	spin_lock_bh(&sc->sc_resetlock);
 	r = ath9k_hw_reset(ah, ah->curchan, false);
 	if (r) {
@@ -1162,6 +1181,9 @@
 	ath_stoprecv(sc);		/* turn off frame recv */
 	ath_flushrecv(sc);		/* flush recv queue */
 
+	if (!ah->curchan)
+		ah->curchan = ath_get_curchannel(sc, sc->hw);
+
 	spin_lock_bh(&sc->sc_resetlock);
 	r = ath9k_hw_reset(ah, ah->curchan, false);
 	if (r) {
@@ -1178,8 +1200,6 @@
 	ath9k_ps_restore(sc);
 }
 
-#if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
-
 /*******************/
 /*	Rfkill	   */
 /*******************/
@@ -1192,82 +1212,28 @@
 				  ah->rfkill_polarity;
 }
 
-/* s/w rfkill handlers */
-static int ath_rfkill_set_block(void *data, bool blocked)
+static void ath9k_rfkill_poll_state(struct ieee80211_hw *hw)
 {
-	struct ath_softc *sc = data;
+	struct ath_wiphy *aphy = hw->priv;
+	struct ath_softc *sc = aphy->sc;
+	bool blocked = !!ath_is_rfkill_set(sc);
+
+	wiphy_rfkill_set_hw_state(hw->wiphy, blocked);
 
 	if (blocked)
 		ath_radio_disable(sc);
 	else
 		ath_radio_enable(sc);
-
-	return 0;
 }
 
-static void ath_rfkill_poll_state(struct rfkill *rfkill, void *data)
+static void ath_start_rfkill_poll(struct ath_softc *sc)
 {
-	struct ath_softc *sc = data;
-	bool blocked = !!ath_is_rfkill_set(sc);
+	struct ath_hw *ah = sc->sc_ah;
 
-	if (rfkill_set_hw_state(rfkill, blocked))
-		ath_radio_disable(sc);
-	else
-		ath_radio_enable(sc);
+	if (ah->caps.hw_caps & ATH9K_HW_CAP_RFSILENT)
+		wiphy_rfkill_start_polling(sc->hw->wiphy);
 }
 
-/* Init s/w rfkill */
-static int ath_init_sw_rfkill(struct ath_softc *sc)
-{
-	sc->rf_kill.ops.set_block = ath_rfkill_set_block;
-	if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_RFSILENT)
-		sc->rf_kill.ops.poll = ath_rfkill_poll_state;
-
-	snprintf(sc->rf_kill.rfkill_name, sizeof(sc->rf_kill.rfkill_name),
-		"ath9k-%s::rfkill", wiphy_name(sc->hw->wiphy));
-
-	sc->rf_kill.rfkill = rfkill_alloc(sc->rf_kill.rfkill_name,
-					  wiphy_dev(sc->hw->wiphy),
-					  RFKILL_TYPE_WLAN,
-					  &sc->rf_kill.ops, sc);
-	if (!sc->rf_kill.rfkill) {
-		DPRINTF(sc, ATH_DBG_FATAL, "Failed to allocate rfkill\n");
-		return -ENOMEM;
-	}
-
-	return 0;
-}
-
-/* Deinitialize rfkill */
-static void ath_deinit_rfkill(struct ath_softc *sc)
-{
-	if (sc->sc_flags & SC_OP_RFKILL_REGISTERED) {
-		rfkill_unregister(sc->rf_kill.rfkill);
-		rfkill_destroy(sc->rf_kill.rfkill);
-		sc->sc_flags &= ~SC_OP_RFKILL_REGISTERED;
-	}
-}
-
-static int ath_start_rfkill_poll(struct ath_softc *sc)
-{
-	if (!(sc->sc_flags & SC_OP_RFKILL_REGISTERED)) {
-		if (rfkill_register(sc->rf_kill.rfkill)) {
-			DPRINTF(sc, ATH_DBG_FATAL,
-				"Unable to register rfkill\n");
-			rfkill_destroy(sc->rf_kill.rfkill);
-
-			/* Deinitialize the device */
-			ath_cleanup(sc);
-			return -EIO;
-		} else {
-			sc->sc_flags |= SC_OP_RFKILL_REGISTERED;
-		}
-	}
-
-	return 0;
-}
-#endif /* CONFIG_RFKILL */
-
 void ath_cleanup(struct ath_softc *sc)
 {
 	ath_detach(sc);
@@ -1286,9 +1252,6 @@
 
 	DPRINTF(sc, ATH_DBG_CONFIG, "Detach ATH hw\n");
 
-#if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
-	ath_deinit_rfkill(sc);
-#endif
 	ath_deinit_leds(sc);
 	cancel_work_sync(&sc->chan_work);
 	cancel_delayed_work_sync(&sc->wiphy_work);
@@ -1626,13 +1589,6 @@
 	if (error != 0)
 		goto error_attach;
 
-#if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
-	/* Initialize s/w rfkill */
-	error = ath_init_sw_rfkill(sc);
-	if (error)
-		goto error_attach;
-#endif
-
 	INIT_WORK(&sc->chan_work, ath9k_wiphy_chan_work);
 	INIT_DELAYED_WORK(&sc->wiphy_work, ath9k_wiphy_work);
 	sc->wiphy_scheduler_int = msecs_to_jiffies(500);
@@ -1648,6 +1604,7 @@
 	/* Initialize LED control */
 	ath_init_leds(sc);
 
+	ath_start_rfkill_poll(sc);
 
 	return 0;
 
@@ -1920,7 +1877,7 @@
 	struct ath_softc *sc = aphy->sc;
 	struct ieee80211_channel *curchan = hw->conf.channel;
 	struct ath9k_channel *init_channel;
-	int r, pos;
+	int r;
 
 	DPRINTF(sc, ATH_DBG_CONFIG, "Starting driver with "
 		"initial channel: %d MHz\n", curchan->center_freq);
@@ -1950,11 +1907,9 @@
 
 	/* setup initial channel */
 
-	pos = curchan->hw_value;
+	sc->chan_idx = curchan->hw_value;
 
-	sc->chan_idx = pos;
-	init_channel = &sc->sc_ah->channels[pos];
-	ath9k_update_ichannel(sc, hw, init_channel);
+	init_channel = ath_get_curchannel(sc, hw);
 
 	/* Reset SERDES registers */
 	ath9k_hw_configpcipowersave(sc->sc_ah, 0);
@@ -2018,10 +1973,6 @@
 
 	ieee80211_wake_queues(hw);
 
-#if defined(CONFIG_RFKILL) || defined(CONFIG_RFKILL_MODULE)
-	r = ath_start_rfkill_poll(sc);
-#endif
-
 mutex_unlock:
 	mutex_unlock(&sc->mutex);
 
@@ -2159,7 +2110,7 @@
 	} else
 		sc->rx.rxlink = NULL;
 
-	rfkill_pause_polling(sc->rf_kill.rfkill);
+	wiphy_rfkill_stop_polling(sc->hw->wiphy);
 
 	/* disable HAL and put h/w to sleep */
 	ath9k_hw_disable(sc->sc_ah);
@@ -2765,6 +2716,7 @@
 	.ampdu_action       = ath9k_ampdu_action,
 	.sw_scan_start      = ath9k_sw_scan_start,
 	.sw_scan_complete   = ath9k_sw_scan_complete,
+	.rfkill_poll        = ath9k_rfkill_poll_state,
 };
 
 static struct {
diff --git a/drivers/net/wireless/ath/ath9k/recv.c b/drivers/net/wireless/ath/ath9k/recv.c
index 5014a19..f99f3a7 100644
--- a/drivers/net/wireless/ath/ath9k/recv.c
+++ b/drivers/net/wireless/ath/ath9k/recv.c
@@ -817,6 +817,7 @@
 		}
 
 		if (unlikely(sc->sc_flags & (SC_OP_WAIT_FOR_BEACON |
+					     SC_OP_WAIT_FOR_CAB |
 					     SC_OP_WAIT_FOR_PSPOLL_DATA)))
 			ath_rx_ps(sc, skb);
 
diff --git a/drivers/net/wireless/iwlwifi/iwl-agn.c b/drivers/net/wireless/iwlwifi/iwl-agn.c
index a5637c4..6d1519e 100644
--- a/drivers/net/wireless/iwlwifi/iwl-agn.c
+++ b/drivers/net/wireless/iwlwifi/iwl-agn.c
@@ -2152,7 +2152,6 @@
 	/* we should be verifying the device is ready to be opened */
 	mutex_lock(&priv->mutex);
 
-	memset(&priv->staging_rxon, 0, sizeof(struct iwl_rxon_cmd));
 	/* fetch ucode file from disk, alloc and copy to bus-master buffers ...
 	 * ucode filename and max sizes are card-specific. */
 
diff --git a/drivers/net/wireless/iwlwifi/iwl-core.c b/drivers/net/wireless/iwlwifi/iwl-core.c
index f9d16ca..6ab0716 100644
--- a/drivers/net/wireless/iwlwifi/iwl-core.c
+++ b/drivers/net/wireless/iwlwifi/iwl-core.c
@@ -629,13 +629,9 @@
 		if (!sta_ht_inf->ht_supported)
 			return 0;
 	}
-
-	if (iwl_ht_conf->ht_protection & IEEE80211_HT_OP_MODE_PROTECTION_20MHZ)
-		return 1;
-	else
-		return iwl_is_channel_extension(priv, priv->band,
-				le16_to_cpu(priv->staging_rxon.channel),
-				iwl_ht_conf->extension_chan_offset);
+	return iwl_is_channel_extension(priv, priv->band,
+			le16_to_cpu(priv->staging_rxon.channel),
+			iwl_ht_conf->extension_chan_offset);
 }
 EXPORT_SYMBOL(iwl_is_fat_tx_allowed);
 
@@ -826,9 +822,18 @@
 			 RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK);
 	if (iwl_is_fat_tx_allowed(priv, NULL)) {
 		/* pure 40 fat */
-		if (rxon->flags & RXON_FLG_FAT_PROT_MSK)
+		if (ht_info->ht_protection == IEEE80211_HT_OP_MODE_PROTECTION_20MHZ) {
 			rxon->flags |= RXON_FLG_CHANNEL_MODE_PURE_40;
-		else {
+			/* Note: control channel is opposite of extension channel */
+			switch (ht_info->extension_chan_offset) {
+			case IEEE80211_HT_PARAM_CHA_SEC_ABOVE:
+				rxon->flags &= ~RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
+				break;
+			case IEEE80211_HT_PARAM_CHA_SEC_BELOW:
+				rxon->flags |= RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
+				break;
+			}
+		} else {
 			/* Note: control channel is opposite of extension channel */
 			switch (ht_info->extension_chan_offset) {
 			case IEEE80211_HT_PARAM_CHA_SEC_ABOVE:
@@ -2390,39 +2395,46 @@
 		priv->ibss_beacon = ieee80211_beacon_get(hw, vif);
 	}
 
-	if ((changes & BSS_CHANGED_BSSID) && !iwl_is_rfkill(priv)) {
-		/* If there is currently a HW scan going on in the background
-		 * then we need to cancel it else the RXON below will fail. */
+	if (changes & BSS_CHANGED_BEACON_INT) {
+		priv->beacon_int = bss_conf->beacon_int;
+		/* TODO: in AP mode, do something to make this take effect */
+	}
+
+	if (changes & BSS_CHANGED_BSSID) {
+		IWL_DEBUG_MAC80211(priv, "BSSID %pM\n", bss_conf->bssid);
+
+		/*
+		 * If there is currently a HW scan going on in the
+		 * background then we need to cancel it else the RXON
+		 * below/in post_associate will fail.
+		 */
 		if (iwl_scan_cancel_timeout(priv, 100)) {
-			IWL_WARN(priv, "Aborted scan still in progress "
-				    "after 100ms\n");
+			IWL_WARN(priv, "Aborted scan still in progress after 100ms\n");
 			IWL_DEBUG_MAC80211(priv, "leaving - scan abort failed.\n");
 			mutex_unlock(&priv->mutex);
 			return;
 		}
-		memcpy(priv->staging_rxon.bssid_addr,
-		       bss_conf->bssid, ETH_ALEN);
 
-		/* TODO: Audit driver for usage of these members and see
-		 * if mac80211 deprecates them (priv->bssid looks like it
-		 * shouldn't be there, but I haven't scanned the IBSS code
-		 * to verify) - jpk */
-		memcpy(priv->bssid, bss_conf->bssid, ETH_ALEN);
+		/* mac80211 only sets assoc when in STATION mode */
+		if (priv->iw_mode == NL80211_IFTYPE_ADHOC ||
+		    bss_conf->assoc) {
+			memcpy(priv->staging_rxon.bssid_addr,
+			       bss_conf->bssid, ETH_ALEN);
 
-		if (priv->iw_mode == NL80211_IFTYPE_AP)
-			iwlcore_config_ap(priv);
-		else {
-			int rc = iwlcore_commit_rxon(priv);
-			if ((priv->iw_mode == NL80211_IFTYPE_STATION) && rc)
-				iwl_rxon_add_station(
-					priv, priv->active_rxon.bssid_addr, 1);
+			/* currently needed in a few places */
+			memcpy(priv->bssid, bss_conf->bssid, ETH_ALEN);
+		} else {
+			priv->staging_rxon.filter_flags &=
+				~RXON_FILTER_ASSOC_MSK;
 		}
-	} else if (!iwl_is_rfkill(priv)) {
-		iwl_scan_cancel_timeout(priv, 100);
-		priv->staging_rxon.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
-		iwlcore_commit_rxon(priv);
+
 	}
 
+	/*
+	 * This needs to be after setting the BSSID in case
+	 * mac80211 decides to do both changes at once because
+	 * it will invoke post_associate.
+	 */
 	if (priv->iw_mode == NL80211_IFTYPE_ADHOC &&
 	    changes & BSS_CHANGED_BEACON) {
 		struct sk_buff *beacon = ieee80211_beacon_get(hw, vif);
@@ -2431,8 +2443,6 @@
 			iwl_mac_beacon_update(hw, beacon);
 	}
 
-	mutex_unlock(&priv->mutex);
-
 	if (changes & BSS_CHANGED_ERP_PREAMBLE) {
 		IWL_DEBUG_MAC80211(priv, "ERP_PREAMBLE %d\n",
 				   bss_conf->use_short_preamble);
@@ -2450,6 +2460,23 @@
 			priv->staging_rxon.flags &= ~RXON_FLG_TGG_PROTECT_MSK;
 	}
 
+	if (changes & BSS_CHANGED_BASIC_RATES) {
+		/* XXX use this information
+		 *
+		 * To do that, remove code from iwl_set_rate() and put something
+		 * like this here:
+		 *
+		if (A-band)
+			priv->staging_rxon.ofdm_basic_rates =
+				bss_conf->basic_rates;
+		else
+			priv->staging_rxon.ofdm_basic_rates =
+				bss_conf->basic_rates >> 4;
+			priv->staging_rxon.cck_basic_rates =
+				bss_conf->basic_rates & 0xF;
+		 */
+	}
+
 	if (changes & BSS_CHANGED_HT) {
 		iwl_ht_conf(priv, bss_conf);
 
@@ -2459,10 +2486,6 @@
 
 	if (changes & BSS_CHANGED_ASSOC) {
 		IWL_DEBUG_MAC80211(priv, "ASSOC %d\n", bss_conf->assoc);
-		/* This should never happen as this function should
-		 * never be called from interrupt context. */
-		if (WARN_ON_ONCE(in_interrupt()))
-			return;
 		if (bss_conf->assoc) {
 			priv->assoc_id = bss_conf->aid;
 			priv->beacon_int = bss_conf->beacon_int;
@@ -2470,27 +2493,35 @@
 			priv->timestamp = bss_conf->timestamp;
 			priv->assoc_capability = bss_conf->assoc_capability;
 
-			/* we have just associated, don't start scan too early
-			 * leave time for EAPOL exchange to complete
+			/*
+			 * We have just associated, don't start scan too early
+			 * leave time for EAPOL exchange to complete.
+			 *
+			 * XXX: do this in mac80211
 			 */
 			priv->next_scan_jiffies = jiffies +
 					IWL_DELAY_NEXT_SCAN_AFTER_ASSOC;
-			mutex_lock(&priv->mutex);
-			priv->cfg->ops->lib->post_associate(priv);
-			mutex_unlock(&priv->mutex);
-		} else {
+			if (!iwl_is_rfkill(priv))
+				priv->cfg->ops->lib->post_associate(priv);
+		} else
 			priv->assoc_id = 0;
-			IWL_DEBUG_MAC80211(priv, "DISASSOC %d\n", bss_conf->assoc);
-		}
-	} else if (changes && iwl_is_associated(priv) && priv->assoc_id) {
-			IWL_DEBUG_MAC80211(priv, "Associated Changes %d\n", changes);
-			ret = iwl_send_rxon_assoc(priv);
-			if (!ret)
-				/* Sync active_rxon with latest change. */
-				memcpy((void *)&priv->active_rxon,
-					&priv->staging_rxon,
-					sizeof(struct iwl_rxon_cmd));
+
 	}
+
+	if (changes && iwl_is_associated(priv) && priv->assoc_id) {
+		IWL_DEBUG_MAC80211(priv, "Changes (%#x) while associated\n",
+				   changes);
+		ret = iwl_send_rxon_assoc(priv);
+		if (!ret) {
+			/* Sync active_rxon with latest change. */
+			memcpy((void *)&priv->active_rxon,
+				&priv->staging_rxon,
+				sizeof(struct iwl_rxon_cmd));
+		}
+	}
+
+	mutex_unlock(&priv->mutex);
+
 	IWL_DEBUG_MAC80211(priv, "leave\n");
 }
 EXPORT_SYMBOL(iwl_bss_info_changed);
diff --git a/drivers/net/wireless/iwlwifi/iwl3945-base.c b/drivers/net/wireless/iwlwifi/iwl3945-base.c
index 83d3160..cb9bd4c 100644
--- a/drivers/net/wireless/iwlwifi/iwl3945-base.c
+++ b/drivers/net/wireless/iwlwifi/iwl3945-base.c
@@ -2498,8 +2498,7 @@
 		struct iwl3945_rxon_cmd *active_rxon =
 				(struct iwl3945_rxon_cmd *)(&priv->active_rxon);
 
-		memcpy(&priv->staging_rxon, &priv->active_rxon,
-		       sizeof(priv->staging_rxon));
+		priv->staging_rxon.filter_flags |= RXON_FILTER_ASSOC_MSK;
 		active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
 	} else {
 		/* Initialize our rx_config data */
@@ -3147,7 +3146,6 @@
 	/* we should be verifying the device is ready to be opened */
 	mutex_lock(&priv->mutex);
 
-	memset(&priv->staging_rxon, 0, sizeof(priv->staging_rxon));
 	/* fetch ucode file from disk, alloc and copy to bus-master buffers ...
 	 * ucode filename and max sizes are card-specific. */
 
diff --git a/drivers/net/wireless/libertas/if_spi.c b/drivers/net/wireless/libertas/if_spi.c
index 06a46d7..6564282 100644
--- a/drivers/net/wireless/libertas/if_spi.c
+++ b/drivers/net/wireless/libertas/if_spi.c
@@ -812,7 +812,6 @@
 static void if_spi_e2h(struct if_spi_card *card)
 {
 	int err = 0;
-	unsigned long flags;
 	u32 cause;
 	struct lbs_private *priv = card->priv;
 
@@ -827,10 +826,7 @@
 	/* generate a card interrupt */
 	spu_write_u16(card, IF_SPI_CARD_INT_CAUSE_REG, IF_SPI_CIC_HOST_EVENT);
 
-	spin_lock_irqsave(&priv->driver_lock, flags);
 	lbs_queue_event(priv, cause & 0xff);
-	spin_unlock_irqrestore(&priv->driver_lock, flags);
-
 out:
 	if (err)
 		lbs_pr_err("%s: error %d\n", __func__, err);
@@ -875,7 +871,12 @@
 			err = if_spi_c2h_data(card);
 			if (err)
 				goto err;
-		if (hiStatus & IF_SPI_HIST_CMD_DOWNLOAD_RDY) {
+
+		/* workaround: in PS mode, the card does not set the Command
+		 * Download Ready bit, but it sets TX Download Ready. */
+		if (hiStatus & IF_SPI_HIST_CMD_DOWNLOAD_RDY ||
+		   (card->priv->psstate != PS_STATE_FULL_POWER &&
+		    (hiStatus & IF_SPI_HIST_TX_DOWNLOAD_RDY))) {
 			/* This means two things. First of all,
 			 * if there was a previous command sent, the card has
 			 * successfully received it.
diff --git a/drivers/pci/setup-res.c b/drivers/pci/setup-res.c
index 3039fcb..1240351 100644
--- a/drivers/pci/setup-res.c
+++ b/drivers/pci/setup-res.c
@@ -99,11 +99,11 @@
 int pci_claim_resource(struct pci_dev *dev, int resource)
 {
 	struct resource *res = &dev->resource[resource];
-	struct resource *root = NULL;
+	struct resource *root;
 	char *dtype = resource < PCI_BRIDGE_RESOURCES ? "device" : "bridge";
 	int err;
 
-	root = pcibios_select_root(dev, res);
+	root = pci_find_parent_resource(dev, res);
 
 	err = -EINVAL;
 	if (root != NULL)
diff --git a/drivers/platform/x86/dell-laptop.c b/drivers/platform/x86/dell-laptop.c
index 2faf0e1..74909c4 100644
--- a/drivers/platform/x86/dell-laptop.c
+++ b/drivers/platform/x86/dell-laptop.c
@@ -177,7 +177,7 @@
 static int dell_rfkill_set(void *data, bool blocked)
 {
 	struct calling_interface_buffer buffer;
-	int disable = blocked ? 0 : 1;
+	int disable = blocked ? 1 : 0;
 	unsigned long radio = (unsigned long)data;
 
 	memset(&buffer, 0, sizeof(struct calling_interface_buffer));
diff --git a/drivers/platform/x86/sony-laptop.c b/drivers/platform/x86/sony-laptop.c
index e48d9a4..dafaa4a 100644
--- a/drivers/platform/x86/sony-laptop.c
+++ b/drivers/platform/x86/sony-laptop.c
@@ -1133,8 +1133,9 @@
 			continue;
 
 		if (hwblock) {
-			if (rfkill_set_hw_state(sony_rfkill_devices[i], true))
-				sony_nc_rfkill_set((void *)i, true);
+			if (rfkill_set_hw_state(sony_rfkill_devices[i], true)) {
+				/* we already know we're blocked */
+			}
 			continue;
 		}
 
diff --git a/drivers/pps/Kconfig b/drivers/pps/Kconfig
new file mode 100644
index 0000000..cc2eb8e
--- /dev/null
+++ b/drivers/pps/Kconfig
@@ -0,0 +1,33 @@
+#
+# PPS support configuration
+#
+
+menu "PPS support"
+
+config PPS
+	tristate "PPS support"
+	depends on EXPERIMENTAL
+	---help---
+	  PPS (Pulse Per Second) is a special pulse provided by some GPS
+	  antennae. Userland can use it to get a high-precision time
+	  reference.
+
+	  Some antennae's PPS signals are connected with the CD (Carrier
+	  Detect) pin of the serial line they use to communicate with the
+	  host. In this case use the SERIAL_LINE client support.
+
+	  Some antennae's PPS signals are connected with some special host
+	  inputs so you have to enable the corresponding client support.
+
+	  To compile this driver as a module, choose M here: the module
+	  will be called pps_core.ko.
+
+config PPS_DEBUG
+	bool "PPS debugging messages"
+	depends on PPS
+	help
+	  Say Y here if you want the PPS support to produce a bunch of debug
+	  messages to the system log.  Select this if you are having a
+	  problem with PPS support and want to see more of what is going on.
+
+endmenu
diff --git a/drivers/pps/Makefile b/drivers/pps/Makefile
new file mode 100644
index 0000000..19ea582
--- /dev/null
+++ b/drivers/pps/Makefile
@@ -0,0 +1,8 @@
+#
+# Makefile for the PPS core.
+#
+
+pps_core-y			:= pps.o kapi.o sysfs.o
+obj-$(CONFIG_PPS)		:= pps_core.o
+
+ccflags-$(CONFIG_PPS_DEBUG) := -DDEBUG
diff --git a/drivers/pps/kapi.c b/drivers/pps/kapi.c
new file mode 100644
index 0000000..35a0b19
--- /dev/null
+++ b/drivers/pps/kapi.c
@@ -0,0 +1,329 @@
+/*
+ * kernel API
+ *
+ *
+ * Copyright (C) 2005-2009   Rodolfo Giometti <giometti@linux.it>
+ *
+ *   This program is free software; you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/sched.h>
+#include <linux/time.h>
+#include <linux/spinlock.h>
+#include <linux/idr.h>
+#include <linux/fs.h>
+#include <linux/pps_kernel.h>
+
+/*
+ * Global variables
+ */
+
+DEFINE_SPINLOCK(pps_idr_lock);
+DEFINE_IDR(pps_idr);
+
+/*
+ * Local functions
+ */
+
+static void pps_add_offset(struct pps_ktime *ts, struct pps_ktime *offset)
+{
+	ts->nsec += offset->nsec;
+	while (ts->nsec >= NSEC_PER_SEC) {
+		ts->nsec -= NSEC_PER_SEC;
+		ts->sec++;
+	}
+	while (ts->nsec < 0) {
+		ts->nsec += NSEC_PER_SEC;
+		ts->sec--;
+	}
+	ts->sec += offset->sec;
+}
+
+/*
+ * Exported functions
+ */
+
+/* pps_get_source - find a PPS source
+ * @source: the PPS source ID.
+ *
+ * This function is used to find an already registered PPS source into the
+ * system.
+ *
+ * The function returns NULL if found nothing, otherwise it returns a pointer
+ * to the PPS source data struct (the refcounter is incremented by 1).
+ */
+
+struct pps_device *pps_get_source(int source)
+{
+	struct pps_device *pps;
+	unsigned long flags;
+
+	spin_lock_irqsave(&pps_idr_lock, flags);
+
+	pps = idr_find(&pps_idr, source);
+	if (pps != NULL)
+		atomic_inc(&pps->usage);
+
+	spin_unlock_irqrestore(&pps_idr_lock, flags);
+
+	return pps;
+}
+
+/* pps_put_source - free the PPS source data
+ * @pps: a pointer to the PPS source.
+ *
+ * This function is used to free a PPS data struct if its refcount is 0.
+ */
+
+void pps_put_source(struct pps_device *pps)
+{
+	unsigned long flags;
+
+	spin_lock_irqsave(&pps_idr_lock, flags);
+	BUG_ON(atomic_read(&pps->usage) == 0);
+
+	if (!atomic_dec_and_test(&pps->usage)) {
+		pps = NULL;
+		goto exit;
+	}
+
+	/* No more reference to the PPS source. We can safely remove the
+	 * PPS data struct.
+	 */
+	idr_remove(&pps_idr, pps->id);
+
+exit:
+	spin_unlock_irqrestore(&pps_idr_lock, flags);
+	kfree(pps);
+}
+
+/* pps_register_source - add a PPS source in the system
+ * @info: the PPS info struct
+ * @default_params: the default PPS parameters of the new source
+ *
+ * This function is used to add a new PPS source in the system. The new
+ * source is described by info's fields and it will have, as default PPS
+ * parameters, the ones specified into default_params.
+ *
+ * The function returns, in case of success, the PPS source ID.
+ */
+
+int pps_register_source(struct pps_source_info *info, int default_params)
+{
+	struct pps_device *pps;
+	int id;
+	int err;
+
+	/* Sanity checks */
+	if ((info->mode & default_params) != default_params) {
+		printk(KERN_ERR "pps: %s: unsupported default parameters\n",
+					info->name);
+		err = -EINVAL;
+		goto pps_register_source_exit;
+	}
+	if ((info->mode & (PPS_ECHOASSERT | PPS_ECHOCLEAR)) != 0 &&
+			info->echo == NULL) {
+		printk(KERN_ERR "pps: %s: echo function is not defined\n",
+					info->name);
+		err = -EINVAL;
+		goto pps_register_source_exit;
+	}
+	if ((info->mode & (PPS_TSFMT_TSPEC | PPS_TSFMT_NTPFP)) == 0) {
+		printk(KERN_ERR "pps: %s: unspecified time format\n",
+					info->name);
+		err = -EINVAL;
+		goto pps_register_source_exit;
+	}
+
+	/* Allocate memory for the new PPS source struct */
+	pps = kzalloc(sizeof(struct pps_device), GFP_KERNEL);
+	if (pps == NULL) {
+		err = -ENOMEM;
+		goto pps_register_source_exit;
+	}
+
+	/* These initializations must be done before calling idr_get_new()
+	 * in order to avoid reces into pps_event().
+	 */
+	pps->params.api_version = PPS_API_VERS;
+	pps->params.mode = default_params;
+	pps->info = *info;
+
+	init_waitqueue_head(&pps->queue);
+	spin_lock_init(&pps->lock);
+	atomic_set(&pps->usage, 1);
+
+	/* Get new ID for the new PPS source */
+	if (idr_pre_get(&pps_idr, GFP_KERNEL) == 0) {
+		err = -ENOMEM;
+		goto kfree_pps;
+	}
+
+	spin_lock_irq(&pps_idr_lock);
+
+	/* Now really allocate the PPS source.
+	 * After idr_get_new() calling the new source will be freely available
+	 * into the kernel.
+	 */
+	err = idr_get_new(&pps_idr, pps, &id);
+	if (err < 0) {
+		spin_unlock_irq(&pps_idr_lock);
+		goto kfree_pps;
+	}
+
+	id = id & MAX_ID_MASK;
+	if (id >= PPS_MAX_SOURCES) {
+		spin_unlock_irq(&pps_idr_lock);
+
+		printk(KERN_ERR "pps: %s: too many PPS sources in the system\n",
+					info->name);
+		err = -EBUSY;
+		goto free_idr;
+	}
+	pps->id = id;
+
+	spin_unlock_irq(&pps_idr_lock);
+
+	/* Create the char device */
+	err = pps_register_cdev(pps);
+	if (err < 0) {
+		printk(KERN_ERR "pps: %s: unable to create char device\n",
+					info->name);
+		goto free_idr;
+	}
+
+	pr_info("new PPS source %s at ID %d\n", info->name, id);
+
+	return id;
+
+free_idr:
+	spin_lock_irq(&pps_idr_lock);
+	idr_remove(&pps_idr, id);
+	spin_unlock_irq(&pps_idr_lock);
+
+kfree_pps:
+	kfree(pps);
+
+pps_register_source_exit:
+	printk(KERN_ERR "pps: %s: unable to register source\n", info->name);
+
+	return err;
+}
+EXPORT_SYMBOL(pps_register_source);
+
+/* pps_unregister_source - remove a PPS source from the system
+ * @source: the PPS source ID
+ *
+ * This function is used to remove a previously registered PPS source from
+ * the system.
+ */
+
+void pps_unregister_source(int source)
+{
+	struct pps_device *pps;
+
+	spin_lock_irq(&pps_idr_lock);
+	pps = idr_find(&pps_idr, source);
+
+	if (!pps) {
+		BUG();
+		spin_unlock_irq(&pps_idr_lock);
+		return;
+	}
+	spin_unlock_irq(&pps_idr_lock);
+
+	pps_unregister_cdev(pps);
+	pps_put_source(pps);
+}
+EXPORT_SYMBOL(pps_unregister_source);
+
+/* pps_event - register a PPS event into the system
+ * @source: the PPS source ID
+ * @ts: the event timestamp
+ * @event: the event type
+ * @data: userdef pointer
+ *
+ * This function is used by each PPS client in order to register a new
+ * PPS event into the system (it's usually called inside an IRQ handler).
+ *
+ * If an echo function is associated with the PPS source it will be called
+ * as:
+ *	pps->info.echo(source, event, data);
+ */
+
+void pps_event(int source, struct pps_ktime *ts, int event, void *data)
+{
+	struct pps_device *pps;
+	unsigned long flags;
+
+	if ((event & (PPS_CAPTUREASSERT | PPS_CAPTURECLEAR)) == 0) {
+		printk(KERN_ERR "pps: unknown event (%x) for source %d\n",
+			event, source);
+		return;
+	}
+
+	pps = pps_get_source(source);
+	if (!pps)
+		return;
+
+	pr_debug("PPS event on source %d at %llu.%06u\n",
+			pps->id, (unsigned long long) ts->sec, ts->nsec);
+
+	spin_lock_irqsave(&pps->lock, flags);
+
+	/* Must call the echo function? */
+	if ((pps->params.mode & (PPS_ECHOASSERT | PPS_ECHOCLEAR)))
+		pps->info.echo(source, event, data);
+
+	/* Check the event */
+	pps->current_mode = pps->params.mode;
+	if (event & PPS_CAPTUREASSERT) {
+		/* We have to add an offset? */
+		if (pps->params.mode & PPS_OFFSETASSERT)
+			pps_add_offset(ts, &pps->params.assert_off_tu);
+
+		/* Save the time stamp */
+		pps->assert_tu = *ts;
+		pps->assert_sequence++;
+		pr_debug("capture assert seq #%u for source %d\n",
+			pps->assert_sequence, source);
+	}
+	if (event & PPS_CAPTURECLEAR) {
+		/* We have to add an offset? */
+		if (pps->params.mode & PPS_OFFSETCLEAR)
+			pps_add_offset(ts, &pps->params.clear_off_tu);
+
+		/* Save the time stamp */
+		pps->clear_tu = *ts;
+		pps->clear_sequence++;
+		pr_debug("capture clear seq #%u for source %d\n",
+			pps->clear_sequence, source);
+	}
+
+	pps->go = ~0;
+	wake_up_interruptible(&pps->queue);
+
+	kill_fasync(&pps->async_queue, SIGIO, POLL_IN);
+
+	spin_unlock_irqrestore(&pps->lock, flags);
+
+	/* Now we can release the PPS source for (possible) deregistration */
+	pps_put_source(pps);
+}
+EXPORT_SYMBOL(pps_event);
diff --git a/drivers/pps/pps.c b/drivers/pps/pps.c
new file mode 100644
index 0000000..ac8cc8c
--- /dev/null
+++ b/drivers/pps/pps.c
@@ -0,0 +1,312 @@
+/*
+ * PPS core file
+ *
+ *
+ * Copyright (C) 2005-2009   Rodolfo Giometti <giometti@linux.it>
+ *
+ *   This program is free software; you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/sched.h>
+#include <linux/uaccess.h>
+#include <linux/idr.h>
+#include <linux/cdev.h>
+#include <linux/poll.h>
+#include <linux/pps_kernel.h>
+
+/*
+ * Local variables
+ */
+
+static dev_t pps_devt;
+static struct class *pps_class;
+
+/*
+ * Char device methods
+ */
+
+static unsigned int pps_cdev_poll(struct file *file, poll_table *wait)
+{
+	struct pps_device *pps = file->private_data;
+
+	poll_wait(file, &pps->queue, wait);
+
+	return POLLIN | POLLRDNORM;
+}
+
+static int pps_cdev_fasync(int fd, struct file *file, int on)
+{
+	struct pps_device *pps = file->private_data;
+	return fasync_helper(fd, file, on, &pps->async_queue);
+}
+
+static long pps_cdev_ioctl(struct file *file,
+		unsigned int cmd, unsigned long arg)
+{
+	struct pps_device *pps = file->private_data;
+	struct pps_kparams params;
+	struct pps_fdata fdata;
+	unsigned long ticks;
+	void __user *uarg = (void __user *) arg;
+	int __user *iuarg = (int __user *) arg;
+	int err;
+
+	switch (cmd) {
+	case PPS_GETPARAMS:
+		pr_debug("PPS_GETPARAMS: source %d\n", pps->id);
+
+		/* Return current parameters */
+		err = copy_to_user(uarg, &pps->params,
+						sizeof(struct pps_kparams));
+		if (err)
+			return -EFAULT;
+
+		break;
+
+	case PPS_SETPARAMS:
+		pr_debug("PPS_SETPARAMS: source %d\n", pps->id);
+
+		/* Check the capabilities */
+		if (!capable(CAP_SYS_TIME))
+			return -EPERM;
+
+		err = copy_from_user(&params, uarg, sizeof(struct pps_kparams));
+		if (err)
+			return -EFAULT;
+		if (!(params.mode & (PPS_CAPTUREASSERT | PPS_CAPTURECLEAR))) {
+			pr_debug("capture mode unspecified (%x)\n",
+								params.mode);
+			return -EINVAL;
+		}
+
+		/* Check for supported capabilities */
+		if ((params.mode & ~pps->info.mode) != 0) {
+			pr_debug("unsupported capabilities (%x)\n",
+								params.mode);
+			return -EINVAL;
+		}
+
+		spin_lock_irq(&pps->lock);
+
+		/* Save the new parameters */
+		pps->params = params;
+
+		/* Restore the read only parameters */
+		if ((params.mode & (PPS_TSFMT_TSPEC | PPS_TSFMT_NTPFP)) == 0) {
+			/* section 3.3 of RFC 2783 interpreted */
+			pr_debug("time format unspecified (%x)\n",
+								params.mode);
+			pps->params.mode |= PPS_TSFMT_TSPEC;
+		}
+		if (pps->info.mode & PPS_CANWAIT)
+			pps->params.mode |= PPS_CANWAIT;
+		pps->params.api_version = PPS_API_VERS;
+
+		spin_unlock_irq(&pps->lock);
+
+		break;
+
+	case PPS_GETCAP:
+		pr_debug("PPS_GETCAP: source %d\n", pps->id);
+
+		err = put_user(pps->info.mode, iuarg);
+		if (err)
+			return -EFAULT;
+
+		break;
+
+	case PPS_FETCH:
+		pr_debug("PPS_FETCH: source %d\n", pps->id);
+
+		err = copy_from_user(&fdata, uarg, sizeof(struct pps_fdata));
+		if (err)
+			return -EFAULT;
+
+		pps->go = 0;
+
+		/* Manage the timeout */
+		if (fdata.timeout.flags & PPS_TIME_INVALID)
+			err = wait_event_interruptible(pps->queue, pps->go);
+		else {
+			pr_debug("timeout %lld.%09d\n",
+					(long long) fdata.timeout.sec,
+					fdata.timeout.nsec);
+			ticks = fdata.timeout.sec * HZ;
+			ticks += fdata.timeout.nsec / (NSEC_PER_SEC / HZ);
+
+			if (ticks != 0) {
+				err = wait_event_interruptible_timeout(
+						pps->queue, pps->go, ticks);
+				if (err == 0)
+					return -ETIMEDOUT;
+			}
+		}
+
+		/* Check for pending signals */
+		if (err == -ERESTARTSYS) {
+			pr_debug("pending signal caught\n");
+			return -EINTR;
+		}
+
+		/* Return the fetched timestamp */
+		spin_lock_irq(&pps->lock);
+
+		fdata.info.assert_sequence = pps->assert_sequence;
+		fdata.info.clear_sequence = pps->clear_sequence;
+		fdata.info.assert_tu = pps->assert_tu;
+		fdata.info.clear_tu = pps->clear_tu;
+		fdata.info.current_mode = pps->current_mode;
+
+		spin_unlock_irq(&pps->lock);
+
+		err = copy_to_user(uarg, &fdata, sizeof(struct pps_fdata));
+		if (err)
+			return -EFAULT;
+
+		break;
+
+	default:
+		return -ENOTTY;
+		break;
+	}
+
+	return 0;
+}
+
+static int pps_cdev_open(struct inode *inode, struct file *file)
+{
+	struct pps_device *pps = container_of(inode->i_cdev,
+						struct pps_device, cdev);
+	int found;
+
+	found = pps_get_source(pps->id) != 0;
+	if (!found)
+		return -ENODEV;
+
+	file->private_data = pps;
+
+	return 0;
+}
+
+static int pps_cdev_release(struct inode *inode, struct file *file)
+{
+	struct pps_device *pps = file->private_data;
+
+	/* Free the PPS source and wake up (possible) deregistration */
+	pps_put_source(pps);
+
+	return 0;
+}
+
+/*
+ * Char device stuff
+ */
+
+static const struct file_operations pps_cdev_fops = {
+	.owner		= THIS_MODULE,
+	.llseek		= no_llseek,
+	.poll		= pps_cdev_poll,
+	.fasync		= pps_cdev_fasync,
+	.unlocked_ioctl	= pps_cdev_ioctl,
+	.open		= pps_cdev_open,
+	.release	= pps_cdev_release,
+};
+
+int pps_register_cdev(struct pps_device *pps)
+{
+	int err;
+
+	pps->devno = MKDEV(MAJOR(pps_devt), pps->id);
+	cdev_init(&pps->cdev, &pps_cdev_fops);
+	pps->cdev.owner = pps->info.owner;
+
+	err = cdev_add(&pps->cdev, pps->devno, 1);
+	if (err) {
+		printk(KERN_ERR "pps: %s: failed to add char device %d:%d\n",
+				pps->info.name, MAJOR(pps_devt), pps->id);
+		return err;
+	}
+	pps->dev = device_create(pps_class, pps->info.dev, pps->devno, NULL,
+							"pps%d", pps->id);
+	if (err)
+		goto del_cdev;
+	dev_set_drvdata(pps->dev, pps);
+
+	pr_debug("source %s got cdev (%d:%d)\n", pps->info.name,
+			MAJOR(pps_devt), pps->id);
+
+	return 0;
+
+del_cdev:
+	cdev_del(&pps->cdev);
+
+	return err;
+}
+
+void pps_unregister_cdev(struct pps_device *pps)
+{
+	device_destroy(pps_class, pps->devno);
+	cdev_del(&pps->cdev);
+}
+
+/*
+ * Module stuff
+ */
+
+static void __exit pps_exit(void)
+{
+	class_destroy(pps_class);
+	unregister_chrdev_region(pps_devt, PPS_MAX_SOURCES);
+}
+
+static int __init pps_init(void)
+{
+	int err;
+
+	pps_class = class_create(THIS_MODULE, "pps");
+	if (!pps_class) {
+		printk(KERN_ERR "pps: failed to allocate class\n");
+		return -ENOMEM;
+	}
+	pps_class->dev_attrs = pps_attrs;
+
+	err = alloc_chrdev_region(&pps_devt, 0, PPS_MAX_SOURCES, "pps");
+	if (err < 0) {
+		printk(KERN_ERR "pps: failed to allocate char device region\n");
+		goto remove_class;
+	}
+
+	pr_info("LinuxPPS API ver. %d registered\n", PPS_API_VERS);
+	pr_info("Software ver. %s - Copyright 2005-2007 Rodolfo Giometti "
+		"<giometti@linux.it>\n", PPS_VERSION);
+
+	return 0;
+
+remove_class:
+	class_destroy(pps_class);
+
+	return err;
+}
+
+subsys_initcall(pps_init);
+module_exit(pps_exit);
+
+MODULE_AUTHOR("Rodolfo Giometti <giometti@linux.it>");
+MODULE_DESCRIPTION("LinuxPPS support (RFC 2783) - ver. " PPS_VERSION);
+MODULE_LICENSE("GPL");
diff --git a/drivers/pps/sysfs.c b/drivers/pps/sysfs.c
new file mode 100644
index 0000000..ef0978c
--- /dev/null
+++ b/drivers/pps/sysfs.c
@@ -0,0 +1,98 @@
+/*
+ * PPS sysfs support
+ *
+ *
+ * Copyright (C) 2007-2009   Rodolfo Giometti <giometti@linux.it>
+ *
+ *   This program is free software; you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+
+#include <linux/device.h>
+#include <linux/module.h>
+#include <linux/string.h>
+#include <linux/pps_kernel.h>
+
+/*
+ * Attribute functions
+ */
+
+static ssize_t pps_show_assert(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct pps_device *pps = dev_get_drvdata(dev);
+
+	if (!(pps->info.mode & PPS_CAPTUREASSERT))
+		return 0;
+
+	return sprintf(buf, "%lld.%09d#%d\n",
+			(long long) pps->assert_tu.sec, pps->assert_tu.nsec,
+			pps->assert_sequence);
+}
+
+static ssize_t pps_show_clear(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct pps_device *pps = dev_get_drvdata(dev);
+
+	if (!(pps->info.mode & PPS_CAPTURECLEAR))
+		return 0;
+
+	return sprintf(buf, "%lld.%09d#%d\n",
+			(long long) pps->clear_tu.sec, pps->clear_tu.nsec,
+			pps->clear_sequence);
+}
+
+static ssize_t pps_show_mode(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct pps_device *pps = dev_get_drvdata(dev);
+
+	return sprintf(buf, "%4x\n", pps->info.mode);
+}
+
+static ssize_t pps_show_echo(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct pps_device *pps = dev_get_drvdata(dev);
+
+	return sprintf(buf, "%d\n", !!pps->info.echo);
+}
+
+static ssize_t pps_show_name(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct pps_device *pps = dev_get_drvdata(dev);
+
+	return sprintf(buf, "%s\n", pps->info.name);
+}
+
+static ssize_t pps_show_path(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	struct pps_device *pps = dev_get_drvdata(dev);
+
+	return sprintf(buf, "%s\n", pps->info.path);
+}
+
+struct device_attribute pps_attrs[] = {
+	__ATTR(assert, S_IRUGO, pps_show_assert, NULL),
+	__ATTR(clear, S_IRUGO, pps_show_clear, NULL),
+	__ATTR(mode, S_IRUGO, pps_show_mode, NULL),
+	__ATTR(echo, S_IRUGO, pps_show_echo, NULL),
+	__ATTR(name, S_IRUGO, pps_show_name, NULL),
+	__ATTR(path, S_IRUGO, pps_show_path, NULL),
+	__ATTR_NULL,
+};
diff --git a/drivers/rapidio/rio-scan.c b/drivers/rapidio/rio-scan.c
index 3b78540..4541509 100644
--- a/drivers/rapidio/rio-scan.c
+++ b/drivers/rapidio/rio-scan.c
@@ -263,15 +263,21 @@
  * device to the RIO device list.  Creates the generic sysfs nodes
  * for an RIO device.
  */
-static void __devinit rio_add_device(struct rio_dev *rdev)
+static int __devinit rio_add_device(struct rio_dev *rdev)
 {
-	device_add(&rdev->dev);
+	int err;
+
+	err = device_add(&rdev->dev);
+	if (err)
+		return err;
 
 	spin_lock(&rio_global_list_lock);
 	list_add_tail(&rdev->global_list, &rio_devices);
 	spin_unlock(&rio_global_list_lock);
 
 	rio_create_sysfs_dev_files(rdev);
+
+	return 0;
 }
 
 /**
@@ -294,13 +300,14 @@
 					struct rio_mport *port, u16 destid,
 					u8 hopcount, int do_enum)
 {
+	int ret = 0;
 	struct rio_dev *rdev;
-	struct rio_switch *rswitch;
+	struct rio_switch *rswitch = NULL;
 	int result, rdid;
 
 	rdev = kzalloc(sizeof(struct rio_dev), GFP_KERNEL);
 	if (!rdev)
-		goto out;
+		return NULL;
 
 	rdev->net = net;
 	rio_mport_read_config_32(port, destid, hopcount, RIO_DEV_ID_CAR,
@@ -343,23 +350,16 @@
 		rio_mport_read_config_32(port, destid, hopcount,
 					 RIO_SWP_INFO_CAR, &rdev->swpinfo);
 		rswitch = kmalloc(sizeof(struct rio_switch), GFP_KERNEL);
-		if (!rswitch) {
-			kfree(rdev);
-			rdev = NULL;
-			goto out;
-		}
+		if (!rswitch)
+			goto cleanup;
 		rswitch->switchid = next_switchid;
 		rswitch->hopcount = hopcount;
 		rswitch->destid = destid;
 		rswitch->route_table = kzalloc(sizeof(u8)*
 					RIO_MAX_ROUTE_ENTRIES(port->sys_size),
 					GFP_KERNEL);
-		if (!rswitch->route_table) {
-			kfree(rdev);
-			rdev = NULL;
-			kfree(rswitch);
-			goto out;
-		}
+		if (!rswitch->route_table)
+			goto cleanup;
 		/* Initialize switch route table */
 		for (rdid = 0; rdid < RIO_MAX_ROUTE_ENTRIES(port->sys_size);
 				rdid++)
@@ -390,10 +390,19 @@
 		rio_init_dbell_res(&rdev->riores[RIO_DOORBELL_RESOURCE],
 				   0, 0xffff);
 
-	rio_add_device(rdev);
+	ret = rio_add_device(rdev);
+	if (ret)
+		goto cleanup;
 
-      out:
 	return rdev;
+
+cleanup:
+	if (rswitch) {
+		kfree(rswitch->route_table);
+		kfree(rswitch);
+	}
+	kfree(rdev);
+	return NULL;
 }
 
 /**
diff --git a/drivers/rapidio/rio-sysfs.c b/drivers/rapidio/rio-sysfs.c
index 97a147f..ba742e8 100644
--- a/drivers/rapidio/rio-sysfs.c
+++ b/drivers/rapidio/rio-sysfs.c
@@ -214,9 +214,11 @@
  */
 int rio_create_sysfs_dev_files(struct rio_dev *rdev)
 {
-	sysfs_create_bin_file(&rdev->dev.kobj, &rio_config_attr);
+	int err = 0;
 
-	return 0;
+	err = sysfs_create_bin_file(&rdev->dev.kobj, &rio_config_attr);
+
+	return err;
 }
 
 /**
diff --git a/drivers/rtc/Kconfig b/drivers/rtc/Kconfig
index 277d35d..81adbdb 100644
--- a/drivers/rtc/Kconfig
+++ b/drivers/rtc/Kconfig
@@ -296,6 +296,15 @@
 	  This driver can also be built as a module. If so the module
 	  will be called rtc-rx8581.
 
+config RTC_DRV_RX8025
+	tristate "Epson RX-8025SA/NB"
+	help
+	  If you say yes here you get support for the Epson
+	  RX-8025SA/NB RTC chips.
+
+	  This driver can also be built as a module. If so, the module
+	  will be called rtc-rx8025.
+
 endif # I2C
 
 comment "SPI RTC drivers"
diff --git a/drivers/rtc/Makefile b/drivers/rtc/Makefile
index 6c0639a..3c0f2b2 100644
--- a/drivers/rtc/Makefile
+++ b/drivers/rtc/Makefile
@@ -62,6 +62,7 @@
 obj-$(CONFIG_RTC_DRV_RS5C313)	+= rtc-rs5c313.o
 obj-$(CONFIG_RTC_DRV_RS5C348)	+= rtc-rs5c348.o
 obj-$(CONFIG_RTC_DRV_RS5C372)	+= rtc-rs5c372.o
+obj-$(CONFIG_RTC_DRV_RX8025)	+= rtc-rx8025.o
 obj-$(CONFIG_RTC_DRV_RX8581)	+= rtc-rx8581.o
 obj-$(CONFIG_RTC_DRV_S35390A)	+= rtc-s35390a.o
 obj-$(CONFIG_RTC_DRV_S3C)	+= rtc-s3c.o
diff --git a/drivers/rtc/interface.c b/drivers/rtc/interface.c
index 4348c4b..4cdb31a 100644
--- a/drivers/rtc/interface.c
+++ b/drivers/rtc/interface.c
@@ -371,19 +371,21 @@
  * @rtc: the rtc device
  * @num: how many irqs are being reported (usually one)
  * @events: mask of RTC_IRQF with one or more of RTC_PF, RTC_AF, RTC_UF
- * Context: in_interrupt(), irqs blocked
+ * Context: any
  */
 void rtc_update_irq(struct rtc_device *rtc,
 		unsigned long num, unsigned long events)
 {
-	spin_lock(&rtc->irq_lock);
-	rtc->irq_data = (rtc->irq_data + (num << 8)) | events;
-	spin_unlock(&rtc->irq_lock);
+	unsigned long flags;
 
-	spin_lock(&rtc->irq_task_lock);
+	spin_lock_irqsave(&rtc->irq_lock, flags);
+	rtc->irq_data = (rtc->irq_data + (num << 8)) | events;
+	spin_unlock_irqrestore(&rtc->irq_lock, flags);
+
+	spin_lock_irqsave(&rtc->irq_task_lock, flags);
 	if (rtc->irq_task)
 		rtc->irq_task->func(rtc->irq_task->private_data);
-	spin_unlock(&rtc->irq_task_lock);
+	spin_unlock_irqrestore(&rtc->irq_task_lock, flags);
 
 	wake_up_interruptible(&rtc->irq_queue);
 	kill_fasync(&rtc->async_queue, SIGIO, POLL_IN);
diff --git a/drivers/rtc/rtc-dev.c b/drivers/rtc/rtc-dev.c
index 45152f4..8a11de9 100644
--- a/drivers/rtc/rtc-dev.c
+++ b/drivers/rtc/rtc-dev.c
@@ -60,8 +60,7 @@
 
 	err = rtc_read_time(rtc, &tm);
 
-	local_irq_disable();
-	spin_lock(&rtc->irq_lock);
+	spin_lock_irq(&rtc->irq_lock);
 	if (rtc->stop_uie_polling || err) {
 		rtc->uie_task_active = 0;
 	} else if (rtc->oldsecs != tm.tm_sec) {
@@ -74,10 +73,9 @@
 	} else if (schedule_work(&rtc->uie_task) == 0) {
 		rtc->uie_task_active = 0;
 	}
-	spin_unlock(&rtc->irq_lock);
+	spin_unlock_irq(&rtc->irq_lock);
 	if (num)
 		rtc_update_irq(rtc, num, RTC_UF | RTC_IRQF);
-	local_irq_enable();
 }
 static void rtc_uie_timer(unsigned long data)
 {
diff --git a/drivers/rtc/rtc-ds1305.c b/drivers/rtc/rtc-ds1305.c
index fc372df..8f410e5 100644
--- a/drivers/rtc/rtc-ds1305.c
+++ b/drivers/rtc/rtc-ds1305.c
@@ -499,10 +499,7 @@
 	if (!test_bit(FLAG_EXITING, &ds1305->flags))
 		enable_irq(spi->irq);
 
-	/* rtc_update_irq() requires an IRQ-disabled context */
-	local_irq_disable();
 	rtc_update_irq(ds1305->rtc, 1, RTC_AF | RTC_IRQF);
-	local_irq_enable();
 }
 
 /*
diff --git a/drivers/rtc/rtc-ds1307.c b/drivers/rtc/rtc-ds1307.c
index 2c4a653..47a93c0 100644
--- a/drivers/rtc/rtc-ds1307.c
+++ b/drivers/rtc/rtc-ds1307.c
@@ -31,6 +31,8 @@
 	ds_1338,
 	ds_1339,
 	ds_1340,
+	ds_1388,
+	ds_3231,
 	m41t00,
 	rx_8025,
 	// rs5c372 too?  different address...
@@ -66,6 +68,7 @@
 #define DS1337_REG_CONTROL	0x0e
 #	define DS1337_BIT_nEOSC		0x80
 #	define DS1339_BIT_BBSQI		0x20
+#	define DS3231_BIT_BBSQW		0x40 /* same as BBSQI */
 #	define DS1337_BIT_RS2		0x10
 #	define DS1337_BIT_RS1		0x08
 #	define DS1337_BIT_INTCN		0x04
@@ -94,6 +97,7 @@
 
 
 struct ds1307 {
+	u8			offset; /* register's offset */
 	u8			regs[11];
 	enum ds_type		type;
 	unsigned long		flags;
@@ -128,6 +132,9 @@
 },
 [ds_1340] = {
 },
+[ds_3231] = {
+	.alarm		= 1,
+},
 [m41t00] = {
 },
 [rx_8025] = {
@@ -138,7 +145,9 @@
 	{ "ds1337", ds_1337 },
 	{ "ds1338", ds_1338 },
 	{ "ds1339", ds_1339 },
+	{ "ds1388", ds_1388 },
 	{ "ds1340", ds_1340 },
+	{ "ds3231", ds_3231 },
 	{ "m41t00", m41t00 },
 	{ "rx8025", rx_8025 },
 	{ }
@@ -258,12 +267,7 @@
 		control &= ~DS1337_BIT_A1IE;
 		i2c_smbus_write_byte_data(client, DS1337_REG_CONTROL, control);
 
-		/* rtc_update_irq() assumes that it is called
-		 * from IRQ-disabled context.
-		 */
-		local_irq_disable();
 		rtc_update_irq(ds1307->rtc, 1, RTC_AF | RTC_IRQF);
-		local_irq_enable();
 	}
 
 out:
@@ -291,7 +295,7 @@
 
 	/* read the RTC date and time registers all at once */
 	tmp = ds1307->read_block_data(ds1307->client,
-		DS1307_REG_SECS, 7, ds1307->regs);
+		ds1307->offset, 7, ds1307->regs);
 	if (tmp != 7) {
 		dev_err(dev, "%s error %d\n", "read", tmp);
 		return -EIO;
@@ -353,6 +357,7 @@
 	switch (ds1307->type) {
 	case ds_1337:
 	case ds_1339:
+	case ds_3231:
 		buf[DS1307_REG_MONTH] |= DS1337_BIT_CENTURY;
 		break;
 	case ds_1340:
@@ -367,7 +372,8 @@
 		"write", buf[0], buf[1], buf[2], buf[3],
 		buf[4], buf[5], buf[6]);
 
-	result = ds1307->write_block_data(ds1307->client, 0, 7, buf);
+	result = ds1307->write_block_data(ds1307->client,
+		ds1307->offset, 7, buf);
 	if (result < 0) {
 		dev_err(dev, "%s error %d\n", "write", result);
 		return result;
@@ -624,6 +630,11 @@
 	struct i2c_adapter	*adapter = to_i2c_adapter(client->dev.parent);
 	int			want_irq = false;
 	unsigned char		*buf;
+	static const int	bbsqi_bitpos[] = {
+		[ds_1337] = 0,
+		[ds_1339] = DS1339_BIT_BBSQI,
+		[ds_3231] = DS3231_BIT_BBSQW,
+	};
 
 	if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)
 	    && !i2c_check_functionality(adapter, I2C_FUNC_SMBUS_I2C_BLOCK))
@@ -632,9 +643,12 @@
 	if (!(ds1307 = kzalloc(sizeof(struct ds1307), GFP_KERNEL)))
 		return -ENOMEM;
 
-	ds1307->client = client;
 	i2c_set_clientdata(client, ds1307);
-	ds1307->type = id->driver_data;
+
+	ds1307->client	= client;
+	ds1307->type	= id->driver_data;
+	ds1307->offset	= 0;
+
 	buf = ds1307->regs;
 	if (i2c_check_functionality(adapter, I2C_FUNC_SMBUS_I2C_BLOCK)) {
 		ds1307->read_block_data = i2c_smbus_read_i2c_block_data;
@@ -647,6 +661,7 @@
 	switch (ds1307->type) {
 	case ds_1337:
 	case ds_1339:
+	case ds_3231:
 		/* has IRQ? */
 		if (ds1307->client->irq > 0 && chip->alarm) {
 			INIT_WORK(&ds1307->work, ds1307_work);
@@ -666,12 +681,12 @@
 			ds1307->regs[0] &= ~DS1337_BIT_nEOSC;
 
 		/* Using IRQ?  Disable the square wave and both alarms.
-		 * For ds1339, be sure alarms can trigger when we're
-		 * running on Vbackup (BBSQI); we assume ds1337 will
-		 * ignore that bit
+		 * For some variants, be sure alarms can trigger when we're
+		 * running on Vbackup (BBSQI/BBSQW)
 		 */
 		if (want_irq) {
-			ds1307->regs[0] |= DS1337_BIT_INTCN | DS1339_BIT_BBSQI;
+			ds1307->regs[0] |= DS1337_BIT_INTCN
+					| bbsqi_bitpos[ds1307->type];
 			ds1307->regs[0] &= ~(DS1337_BIT_A2IE | DS1337_BIT_A1IE);
 		}
 
@@ -751,6 +766,9 @@
 						  hour);
 		}
 		break;
+	case ds_1388:
+		ds1307->offset = 1; /* Seconds starts at 1 */
+		break;
 	default:
 		break;
 	}
@@ -814,6 +832,8 @@
 	case rx_8025:
 	case ds_1337:
 	case ds_1339:
+	case ds_1388:
+	case ds_3231:
 		break;
 	}
 
diff --git a/drivers/rtc/rtc-ds1374.c b/drivers/rtc/rtc-ds1374.c
index 4d32e32..32b2773 100644
--- a/drivers/rtc/rtc-ds1374.c
+++ b/drivers/rtc/rtc-ds1374.c
@@ -296,12 +296,7 @@
 		control &= ~(DS1374_REG_CR_WACE | DS1374_REG_CR_AIE);
 		i2c_smbus_write_byte_data(client, DS1374_REG_CR, control);
 
-		/* rtc_update_irq() assumes that it is called
-		 * from IRQ-disabled context.
-		 */
-		local_irq_disable();
 		rtc_update_irq(ds1374->rtc, 1, RTC_AF | RTC_IRQF);
-		local_irq_enable();
 	}
 
 out:
diff --git a/drivers/rtc/rtc-ds1553.c b/drivers/rtc/rtc-ds1553.c
index 38d472b..7172885 100644
--- a/drivers/rtc/rtc-ds1553.c
+++ b/drivers/rtc/rtc-ds1553.c
@@ -329,8 +329,7 @@
 	if (pdata->irq > 0) {
 		writeb(0, ioaddr + RTC_INTERRUPTS);
 		if (request_irq(pdata->irq, ds1553_rtc_interrupt,
-				IRQF_DISABLED | IRQF_SHARED,
-				pdev->name, pdev) < 0) {
+				IRQF_DISABLED, pdev->name, pdev) < 0) {
 			dev_warn(&pdev->dev, "interrupt not available.\n");
 			pdata->irq = 0;
 		}
diff --git a/drivers/rtc/rtc-ds1742.c b/drivers/rtc/rtc-ds1742.c
index 8bc8501..0924945 100644
--- a/drivers/rtc/rtc-ds1742.c
+++ b/drivers/rtc/rtc-ds1742.c
@@ -57,6 +57,7 @@
 	size_t size;
 	resource_size_t baseaddr;
 	unsigned long last_jiffies;
+	struct bin_attribute nvram_attr;
 };
 
 static int ds1742_rtc_set_time(struct device *dev, struct rtc_time *tm)
@@ -157,18 +158,6 @@
 	return count;
 }
 
-static struct bin_attribute ds1742_nvram_attr = {
-	.attr = {
-		.name = "nvram",
-		.mode = S_IRUGO | S_IWUSR,
-	},
-	.read = ds1742_nvram_read,
-	.write = ds1742_nvram_write,
-	/* REVISIT: size in sysfs won't match actual size... if it's
-	 * not a constant, each RTC should have its own attribute.
-	 */
-};
-
 static int __devinit ds1742_rtc_probe(struct platform_device *pdev)
 {
 	struct rtc_device *rtc;
@@ -199,6 +188,12 @@
 	pdata->size_nvram = pdata->size - RTC_SIZE;
 	pdata->ioaddr_rtc = ioaddr + pdata->size_nvram;
 
+	pdata->nvram_attr.attr.name = "nvram";
+	pdata->nvram_attr.attr.mode = S_IRUGO | S_IWUSR;
+	pdata->nvram_attr.read = ds1742_nvram_read;
+	pdata->nvram_attr.write = ds1742_nvram_write;
+	pdata->nvram_attr.size = pdata->size_nvram;
+
 	/* turn RTC on if it was not on */
 	ioaddr = pdata->ioaddr_rtc;
 	sec = readb(ioaddr + RTC_SECONDS);
@@ -221,11 +216,13 @@
 	pdata->rtc = rtc;
 	pdata->last_jiffies = jiffies;
 	platform_set_drvdata(pdev, pdata);
-	ds1742_nvram_attr.size = max(ds1742_nvram_attr.size,
-				     pdata->size_nvram);
-	ret = sysfs_create_bin_file(&pdev->dev.kobj, &ds1742_nvram_attr);
-	if (ret)
+
+	ret = sysfs_create_bin_file(&pdev->dev.kobj, &pdata->nvram_attr);
+	if (ret) {
+		dev_err(&pdev->dev, "creating nvram file in sysfs failed\n");
 		goto out;
+	}
+
 	return 0;
  out:
 	if (pdata->rtc)
@@ -242,7 +239,7 @@
 {
 	struct rtc_plat_data *pdata = platform_get_drvdata(pdev);
 
-	sysfs_remove_bin_file(&pdev->dev.kobj, &ds1742_nvram_attr);
+	sysfs_remove_bin_file(&pdev->dev.kobj, &pdata->nvram_attr);
 	rtc_device_unregister(pdata->rtc);
 	iounmap(pdata->ioaddr_nvram);
 	release_mem_region(pdata->baseaddr, pdata->size);
diff --git a/drivers/rtc/rtc-rx8025.c b/drivers/rtc/rtc-rx8025.c
new file mode 100644
index 0000000..b1a29bc
--- /dev/null
+++ b/drivers/rtc/rtc-rx8025.c
@@ -0,0 +1,688 @@
+/*
+ * Driver for Epson's RTC module RX-8025 SA/NB
+ *
+ * Copyright (C) 2009 Wolfgang Grandegger <wg@grandegger.com>
+ *
+ * Copyright (C) 2005 by Digi International Inc.
+ * All rights reserved.
+ *
+ * Modified by fengjh at rising.com.cn
+ * <http://lists.lm-sensors.org/mailman/listinfo/lm-sensors>
+ * 2006.11
+ *
+ * Code cleanup by Sergei Poselenov, <sposelenov@emcraft.com>
+ * Converted to new style by Wolfgang Grandegger <wg@grandegger.com>
+ * Alarm and periodic interrupt added by Dmitry Rakhchev <rda@emcraft.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * version 2 as published by the Free Software Foundation.
+ */
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/bcd.h>
+#include <linux/i2c.h>
+#include <linux/list.h>
+#include <linux/rtc.h>
+
+/* Register definitions */
+#define RX8025_REG_SEC		0x00
+#define RX8025_REG_MIN		0x01
+#define RX8025_REG_HOUR		0x02
+#define RX8025_REG_WDAY		0x03
+#define RX8025_REG_MDAY		0x04
+#define RX8025_REG_MONTH	0x05
+#define RX8025_REG_YEAR		0x06
+#define RX8025_REG_DIGOFF	0x07
+#define RX8025_REG_ALWMIN	0x08
+#define RX8025_REG_ALWHOUR	0x09
+#define RX8025_REG_ALWWDAY	0x0a
+#define RX8025_REG_ALDMIN	0x0b
+#define RX8025_REG_ALDHOUR	0x0c
+/* 0x0d is reserved */
+#define RX8025_REG_CTRL1	0x0e
+#define RX8025_REG_CTRL2	0x0f
+
+#define RX8025_BIT_CTRL1_CT	(7 << 0)
+/* 1 Hz periodic level irq */
+#define RX8025_BIT_CTRL1_CT_1HZ	4
+#define RX8025_BIT_CTRL1_TEST	(1 << 3)
+#define RX8025_BIT_CTRL1_1224	(1 << 5)
+#define RX8025_BIT_CTRL1_DALE	(1 << 6)
+#define RX8025_BIT_CTRL1_WALE	(1 << 7)
+
+#define RX8025_BIT_CTRL2_DAFG	(1 << 0)
+#define RX8025_BIT_CTRL2_WAFG	(1 << 1)
+#define RX8025_BIT_CTRL2_CTFG	(1 << 2)
+#define RX8025_BIT_CTRL2_PON	(1 << 4)
+#define RX8025_BIT_CTRL2_XST	(1 << 5)
+#define RX8025_BIT_CTRL2_VDET	(1 << 6)
+
+/* Clock precision adjustment */
+#define RX8025_ADJ_RESOLUTION	3050 /* in ppb */
+#define RX8025_ADJ_DATA_MAX	62
+#define RX8025_ADJ_DATA_MIN	-62
+
+static const struct i2c_device_id rx8025_id[] = {
+	{ "rx8025", 0 },
+	{ }
+};
+MODULE_DEVICE_TABLE(i2c, rx8025_id);
+
+struct rx8025_data {
+	struct i2c_client *client;
+	struct rtc_device *rtc;
+	struct work_struct work;
+	u8 ctrl1;
+	unsigned exiting:1;
+};
+
+static int rx8025_read_reg(struct i2c_client *client, int number, u8 *value)
+{
+	int ret = i2c_smbus_read_byte_data(client, (number << 4) | 0x08);
+
+	if (ret < 0) {
+		dev_err(&client->dev, "Unable to read register #%d\n", number);
+		return ret;
+	}
+
+	*value = ret;
+	return 0;
+}
+
+static int rx8025_read_regs(struct i2c_client *client,
+			    int number, u8 length, u8 *values)
+{
+	int ret = i2c_smbus_read_i2c_block_data(client, (number << 4) | 0x08,
+						length, values);
+
+	if (ret != length) {
+		dev_err(&client->dev, "Unable to read registers #%d..#%d\n",
+			number, number + length - 1);
+		return ret < 0 ? ret : -EIO;
+	}
+
+	return 0;
+}
+
+static int rx8025_write_reg(struct i2c_client *client, int number, u8 value)
+{
+	int ret = i2c_smbus_write_byte_data(client, number << 4, value);
+
+	if (ret)
+		dev_err(&client->dev, "Unable to write register #%d\n",
+			number);
+
+	return ret;
+}
+
+static int rx8025_write_regs(struct i2c_client *client,
+			     int number, u8 length, u8 *values)
+{
+	int ret = i2c_smbus_write_i2c_block_data(client, (number << 4) | 0x08,
+						 length, values);
+
+	if (ret)
+		dev_err(&client->dev, "Unable to write registers #%d..#%d\n",
+			number, number + length - 1);
+
+	return ret;
+}
+
+static irqreturn_t rx8025_irq(int irq, void *dev_id)
+{
+	struct i2c_client *client = dev_id;
+	struct rx8025_data *rx8025 = i2c_get_clientdata(client);
+
+	disable_irq_nosync(irq);
+	schedule_work(&rx8025->work);
+	return IRQ_HANDLED;
+}
+
+static void rx8025_work(struct work_struct *work)
+{
+	struct rx8025_data *rx8025 = container_of(work, struct rx8025_data,
+						  work);
+	struct i2c_client *client = rx8025->client;
+	struct mutex *lock = &rx8025->rtc->ops_lock;
+	u8 status;
+
+	mutex_lock(lock);
+
+	if (rx8025_read_reg(client, RX8025_REG_CTRL2, &status))
+		goto out;
+
+	if (!(status & RX8025_BIT_CTRL2_XST))
+		dev_warn(&client->dev, "Oscillation stop was detected,"
+			 "you may have to readjust the clock\n");
+
+	if (status & RX8025_BIT_CTRL2_CTFG) {
+		/* periodic */
+		status &= ~RX8025_BIT_CTRL2_CTFG;
+		local_irq_disable();
+		rtc_update_irq(rx8025->rtc, 1, RTC_PF | RTC_IRQF);
+		local_irq_enable();
+	}
+
+	if (status & RX8025_BIT_CTRL2_DAFG) {
+		/* alarm */
+		status &= RX8025_BIT_CTRL2_DAFG;
+		if (rx8025_write_reg(client, RX8025_REG_CTRL1,
+				     rx8025->ctrl1 & ~RX8025_BIT_CTRL1_DALE))
+			goto out;
+		local_irq_disable();
+		rtc_update_irq(rx8025->rtc, 1, RTC_AF | RTC_IRQF);
+		local_irq_enable();
+	}
+
+	/* acknowledge IRQ */
+	rx8025_write_reg(client, RX8025_REG_CTRL2,
+			 status | RX8025_BIT_CTRL2_XST);
+
+out:
+	if (!rx8025->exiting)
+		enable_irq(client->irq);
+
+	mutex_unlock(lock);
+}
+
+static int rx8025_get_time(struct device *dev, struct rtc_time *dt)
+{
+	struct rx8025_data *rx8025 = dev_get_drvdata(dev);
+	u8 date[7];
+	int err;
+
+	err = rx8025_read_regs(rx8025->client, RX8025_REG_SEC, 7, date);
+	if (err)
+		return err;
+
+	dev_dbg(dev, "%s: read 0x%02x 0x%02x "
+		"0x%02x 0x%02x 0x%02x 0x%02x 0x%02x\n", __func__,
+		date[0], date[1], date[2], date[3], date[4],
+		date[5], date[6]);
+
+	dt->tm_sec = bcd2bin(date[RX8025_REG_SEC] & 0x7f);
+	dt->tm_min = bcd2bin(date[RX8025_REG_MIN] & 0x7f);
+	if (rx8025->ctrl1 & RX8025_BIT_CTRL1_1224)
+		dt->tm_hour = bcd2bin(date[RX8025_REG_HOUR] & 0x3f);
+	else
+		dt->tm_hour = bcd2bin(date[RX8025_REG_HOUR] & 0x1f) % 12
+			+ (date[RX8025_REG_HOUR] & 0x20 ? 12 : 0);
+
+	dt->tm_mday = bcd2bin(date[RX8025_REG_MDAY] & 0x3f);
+	dt->tm_mon = bcd2bin(date[RX8025_REG_MONTH] & 0x1f) - 1;
+	dt->tm_year = bcd2bin(date[RX8025_REG_YEAR]);
+
+	if (dt->tm_year < 70)
+		dt->tm_year += 100;
+
+	dev_dbg(dev, "%s: date %ds %dm %dh %dmd %dm %dy\n", __func__,
+		dt->tm_sec, dt->tm_min, dt->tm_hour,
+		dt->tm_mday, dt->tm_mon, dt->tm_year);
+
+	return rtc_valid_tm(dt);
+}
+
+static int rx8025_set_time(struct device *dev, struct rtc_time *dt)
+{
+	struct rx8025_data *rx8025 = dev_get_drvdata(dev);
+	u8 date[7];
+
+	/*
+	 * BUG: The HW assumes every year that is a multiple of 4 to be a leap
+	 * year.  Next time this is wrong is 2100, which will not be a leap
+	 * year.
+	 */
+
+	/*
+	 * Here the read-only bits are written as "0".  I'm not sure if that
+	 * is sound.
+	 */
+	date[RX8025_REG_SEC] = bin2bcd(dt->tm_sec);
+	date[RX8025_REG_MIN] = bin2bcd(dt->tm_min);
+	if (rx8025->ctrl1 & RX8025_BIT_CTRL1_1224)
+		date[RX8025_REG_HOUR] = bin2bcd(dt->tm_hour);
+	else
+		date[RX8025_REG_HOUR] = (dt->tm_hour >= 12 ? 0x20 : 0)
+			| bin2bcd((dt->tm_hour + 11) % 12 + 1);
+
+	date[RX8025_REG_WDAY] = bin2bcd(dt->tm_wday);
+	date[RX8025_REG_MDAY] = bin2bcd(dt->tm_mday);
+	date[RX8025_REG_MONTH] = bin2bcd(dt->tm_mon + 1);
+	date[RX8025_REG_YEAR] = bin2bcd(dt->tm_year % 100);
+
+	dev_dbg(dev,
+		"%s: write 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x\n",
+		__func__,
+		date[0], date[1], date[2], date[3], date[4], date[5], date[6]);
+
+	return rx8025_write_regs(rx8025->client, RX8025_REG_SEC, 7, date);
+}
+
+static int rx8025_init_client(struct i2c_client *client, int *need_reset)
+{
+	struct rx8025_data *rx8025 = i2c_get_clientdata(client);
+	u8 ctrl[2], ctrl2;
+	int need_clear = 0;
+	int err;
+
+	err = rx8025_read_regs(rx8025->client, RX8025_REG_CTRL1, 2, ctrl);
+	if (err)
+		goto out;
+
+	/* Keep test bit zero ! */
+	rx8025->ctrl1 = ctrl[0] & ~RX8025_BIT_CTRL1_TEST;
+
+	if (ctrl[1] & RX8025_BIT_CTRL2_PON) {
+		dev_warn(&client->dev, "power-on reset was detected, "
+			 "you may have to readjust the clock\n");
+		*need_reset = 1;
+	}
+
+	if (ctrl[1] & RX8025_BIT_CTRL2_VDET) {
+		dev_warn(&client->dev, "a power voltage drop was detected, "
+			 "you may have to readjust the clock\n");
+		*need_reset = 1;
+	}
+
+	if (!(ctrl[1] & RX8025_BIT_CTRL2_XST)) {
+		dev_warn(&client->dev, "Oscillation stop was detected,"
+			 "you may have to readjust the clock\n");
+		*need_reset = 1;
+	}
+
+	if (ctrl[1] & (RX8025_BIT_CTRL2_DAFG | RX8025_BIT_CTRL2_WAFG)) {
+		dev_warn(&client->dev, "Alarm was detected\n");
+		need_clear = 1;
+	}
+
+	if (!(ctrl[1] & RX8025_BIT_CTRL2_CTFG))
+		need_clear = 1;
+
+	if (*need_reset || need_clear) {
+		ctrl2 = ctrl[0];
+		ctrl2 &= ~(RX8025_BIT_CTRL2_PON | RX8025_BIT_CTRL2_VDET |
+			   RX8025_BIT_CTRL2_CTFG | RX8025_BIT_CTRL2_WAFG |
+			   RX8025_BIT_CTRL2_DAFG);
+		ctrl2 |= RX8025_BIT_CTRL2_XST;
+
+		err = rx8025_write_reg(client, RX8025_REG_CTRL2, ctrl2);
+	}
+out:
+	return err;
+}
+
+/* Alarm support */
+static int rx8025_read_alarm(struct device *dev, struct rtc_wkalrm *t)
+{
+	struct rx8025_data *rx8025 = dev_get_drvdata(dev);
+	struct i2c_client *client = rx8025->client;
+	u8 ctrl2, ald[2];
+	int err;
+
+	if (client->irq <= 0)
+		return -EINVAL;
+
+	err = rx8025_read_regs(client, RX8025_REG_ALDMIN, 2, ald);
+	if (err)
+		return err;
+
+	err = rx8025_read_reg(client, RX8025_REG_CTRL2, &ctrl2);
+	if (err)
+		return err;
+
+	dev_dbg(dev, "%s: read alarm 0x%02x 0x%02x ctrl2 %02x\n",
+		__func__, ald[0], ald[1], ctrl2);
+
+	/* Hardware alarms precision is 1 minute! */
+	t->time.tm_sec = 0;
+	t->time.tm_min = bcd2bin(ald[0] & 0x7f);
+	if (rx8025->ctrl1 & RX8025_BIT_CTRL1_1224)
+		t->time.tm_hour = bcd2bin(ald[1] & 0x3f);
+	else
+		t->time.tm_hour = bcd2bin(ald[1] & 0x1f) % 12
+			+ (ald[1] & 0x20 ? 12 : 0);
+
+	t->time.tm_wday = -1;
+	t->time.tm_mday = -1;
+	t->time.tm_mon = -1;
+	t->time.tm_year = -1;
+
+	dev_dbg(dev, "%s: date: %ds %dm %dh %dmd %dm %dy\n",
+		__func__,
+		t->time.tm_sec, t->time.tm_min, t->time.tm_hour,
+		t->time.tm_mday, t->time.tm_mon, t->time.tm_year);
+	t->enabled = !!(rx8025->ctrl1 & RX8025_BIT_CTRL1_DALE);
+	t->pending = (ctrl2 & RX8025_BIT_CTRL2_DAFG) && t->enabled;
+
+	return err;
+}
+
+static int rx8025_set_alarm(struct device *dev, struct rtc_wkalrm *t)
+{
+	struct i2c_client *client = to_i2c_client(dev);
+	struct rx8025_data *rx8025 = dev_get_drvdata(dev);
+	u8 ald[2];
+	int err;
+
+	if (client->irq <= 0)
+		return -EINVAL;
+
+	/* Hardware alarm precision is 1 minute! */
+	ald[0] = bin2bcd(t->time.tm_min);
+	if (rx8025->ctrl1 & RX8025_BIT_CTRL1_1224)
+		ald[1] = bin2bcd(t->time.tm_hour);
+	else
+		ald[1] = (t->time.tm_hour >= 12 ? 0x20 : 0)
+			| bin2bcd((t->time.tm_hour + 11) % 12 + 1);
+
+	dev_dbg(dev, "%s: write 0x%02x 0x%02x\n", __func__, ald[0], ald[1]);
+
+	if (rx8025->ctrl1 & RX8025_BIT_CTRL1_DALE) {
+		rx8025->ctrl1 &= ~RX8025_BIT_CTRL1_DALE;
+		err = rx8025_write_reg(rx8025->client, RX8025_REG_CTRL1,
+				       rx8025->ctrl1);
+		if (err)
+			return err;
+	}
+	err = rx8025_write_regs(rx8025->client, RX8025_REG_ALDMIN, 2, ald);
+	if (err)
+		return err;
+
+	if (t->enabled) {
+		rx8025->ctrl1 |= RX8025_BIT_CTRL1_DALE;
+		err = rx8025_write_reg(rx8025->client, RX8025_REG_CTRL1,
+				       rx8025->ctrl1);
+		if (err)
+			return err;
+	}
+
+	return 0;
+}
+
+static int rx8025_alarm_irq_enable(struct device *dev, unsigned int enabled)
+{
+	struct rx8025_data *rx8025 = dev_get_drvdata(dev);
+	u8 ctrl1;
+	int err;
+
+	ctrl1 = rx8025->ctrl1;
+	if (enabled)
+		ctrl1 |= RX8025_BIT_CTRL1_DALE;
+	else
+		ctrl1 &= ~RX8025_BIT_CTRL1_DALE;
+
+	if (ctrl1 != rx8025->ctrl1) {
+		rx8025->ctrl1 = ctrl1;
+		err = rx8025_write_reg(rx8025->client, RX8025_REG_CTRL1,
+				       rx8025->ctrl1);
+		if (err)
+			return err;
+	}
+	return 0;
+}
+
+static int rx8025_irq_set_state(struct device *dev, int enabled)
+{
+	struct i2c_client *client = to_i2c_client(dev);
+	struct rx8025_data *rx8025 = i2c_get_clientdata(client);
+	int ctrl1;
+	int err;
+
+	if (client->irq <= 0)
+		return -ENXIO;
+
+	ctrl1 = rx8025->ctrl1 & ~RX8025_BIT_CTRL1_CT;
+	if (enabled)
+		ctrl1 |= RX8025_BIT_CTRL1_CT_1HZ;
+	if (ctrl1 != rx8025->ctrl1) {
+		rx8025->ctrl1 = ctrl1;
+		err = rx8025_write_reg(rx8025->client, RX8025_REG_CTRL1,
+				       rx8025->ctrl1);
+		if (err)
+			return err;
+	}
+
+	return 0;
+}
+
+static struct rtc_class_ops rx8025_rtc_ops = {
+	.read_time = rx8025_get_time,
+	.set_time = rx8025_set_time,
+	.read_alarm = rx8025_read_alarm,
+	.set_alarm = rx8025_set_alarm,
+	.alarm_irq_enable = rx8025_alarm_irq_enable,
+	.irq_set_state  = rx8025_irq_set_state,
+};
+
+/*
+ * Clock precision adjustment support
+ *
+ * According to the RX8025 SA/NB application manual the frequency and
+ * temperature charateristics can be approximated using the following
+ * equation:
+ *
+ *   df = a * (ut - t)**2
+ *
+ *   df: Frequency deviation in any temperature
+ *   a : Coefficient = (-35 +-5) * 10**-9
+ *   ut: Ultimate temperature in degree = +25 +-5 degree
+ *   t : Any temperature in degree
+ *
+ * Note that the clock adjustment in ppb must be entered (which is
+ * the negative value of the deviation).
+ */
+static int rx8025_get_clock_adjust(struct device *dev, int *adj)
+{
+	struct i2c_client *client = to_i2c_client(dev);
+	u8 digoff;
+	int err;
+
+	err = rx8025_read_reg(client, RX8025_REG_DIGOFF, &digoff);
+	if (err)
+		return err;
+
+	*adj = digoff >= 64 ? digoff - 128 : digoff;
+	if (*adj > 0)
+		(*adj)--;
+	*adj *= -RX8025_ADJ_RESOLUTION;
+
+	return 0;
+}
+
+static int rx8025_set_clock_adjust(struct device *dev, int adj)
+{
+	struct i2c_client *client = to_i2c_client(dev);
+	u8 digoff;
+	int err;
+
+	adj /= -RX8025_ADJ_RESOLUTION;
+	if (adj > RX8025_ADJ_DATA_MAX)
+		adj = RX8025_ADJ_DATA_MAX;
+	else if (adj < RX8025_ADJ_DATA_MIN)
+		adj = RX8025_ADJ_DATA_MIN;
+	else if (adj > 0)
+		adj++;
+	else if (adj < 0)
+		adj += 128;
+	digoff = adj;
+
+	err = rx8025_write_reg(client, RX8025_REG_DIGOFF, digoff);
+	if (err)
+		return err;
+
+	dev_dbg(dev, "%s: write 0x%02x\n", __func__, digoff);
+
+	return 0;
+}
+
+static ssize_t rx8025_sysfs_show_clock_adjust(struct device *dev,
+					      struct device_attribute *attr,
+					      char *buf)
+{
+	int err, adj;
+
+	err = rx8025_get_clock_adjust(dev, &adj);
+	if (err)
+		return err;
+
+	return sprintf(buf, "%d\n", adj);
+}
+
+static ssize_t rx8025_sysfs_store_clock_adjust(struct device *dev,
+					       struct device_attribute *attr,
+					       const char *buf, size_t count)
+{
+	int adj, err;
+
+	if (sscanf(buf, "%i", &adj) != 1)
+		return -EINVAL;
+
+	err = rx8025_set_clock_adjust(dev, adj);
+
+	return err ? err : count;
+}
+
+static DEVICE_ATTR(clock_adjust_ppb, S_IRUGO | S_IWUSR,
+		   rx8025_sysfs_show_clock_adjust,
+		   rx8025_sysfs_store_clock_adjust);
+
+static int rx8025_sysfs_register(struct device *dev)
+{
+	return device_create_file(dev, &dev_attr_clock_adjust_ppb);
+}
+
+static void rx8025_sysfs_unregister(struct device *dev)
+{
+	device_remove_file(dev, &dev_attr_clock_adjust_ppb);
+}
+
+static int __devinit rx8025_probe(struct i2c_client *client,
+				  const struct i2c_device_id *id)
+{
+	struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
+	struct rx8025_data *rx8025;
+	int err, need_reset = 0;
+
+	if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA
+				     | I2C_FUNC_SMBUS_I2C_BLOCK)) {
+		dev_err(&adapter->dev,
+			"doesn't support required functionality\n");
+		err = -EIO;
+		goto errout;
+	}
+
+	rx8025 = kzalloc(sizeof(*rx8025), GFP_KERNEL);
+	if (!rx8025) {
+		dev_err(&adapter->dev, "failed to alloc memory\n");
+		err = -ENOMEM;
+		goto errout;
+	}
+
+	rx8025->client = client;
+	i2c_set_clientdata(client, rx8025);
+	INIT_WORK(&rx8025->work, rx8025_work);
+
+	err = rx8025_init_client(client, &need_reset);
+	if (err)
+		goto errout_free;
+
+	if (need_reset) {
+		struct rtc_time tm;
+		dev_info(&client->dev,
+			 "bad conditions detected, resetting date\n");
+		rtc_time_to_tm(0, &tm);	/* 1970/1/1 */
+		rx8025_set_time(&client->dev, &tm);
+	}
+
+	rx8025->rtc = rtc_device_register(client->name, &client->dev,
+					  &rx8025_rtc_ops, THIS_MODULE);
+	if (IS_ERR(rx8025->rtc)) {
+		err = PTR_ERR(rx8025->rtc);
+		dev_err(&client->dev, "unable to register the class device\n");
+		goto errout_free;
+	}
+
+	if (client->irq > 0) {
+		dev_info(&client->dev, "IRQ %d supplied\n", client->irq);
+		err = request_irq(client->irq, rx8025_irq,
+				  0, "rx8025", client);
+		if (err) {
+			dev_err(&client->dev, "unable to request IRQ\n");
+			goto errout_reg;
+		}
+	}
+
+	rx8025->rtc->irq_freq = 1;
+	rx8025->rtc->max_user_freq = 1;
+
+	err = rx8025_sysfs_register(&client->dev);
+	if (err)
+		goto errout_irq;
+
+	return 0;
+
+errout_irq:
+	if (client->irq > 0)
+		free_irq(client->irq, client);
+
+errout_reg:
+	rtc_device_unregister(rx8025->rtc);
+
+errout_free:
+	i2c_set_clientdata(client, NULL);
+	kfree(rx8025);
+
+errout:
+	dev_err(&adapter->dev, "probing for rx8025 failed\n");
+	return err;
+}
+
+static int __devexit rx8025_remove(struct i2c_client *client)
+{
+	struct rx8025_data *rx8025 = i2c_get_clientdata(client);
+	struct mutex *lock = &rx8025->rtc->ops_lock;
+
+	if (client->irq > 0) {
+		mutex_lock(lock);
+		rx8025->exiting = 1;
+		mutex_unlock(lock);
+
+		free_irq(client->irq, client);
+		flush_scheduled_work();
+	}
+
+	rx8025_sysfs_unregister(&client->dev);
+	rtc_device_unregister(rx8025->rtc);
+	i2c_set_clientdata(client, NULL);
+	kfree(rx8025);
+	return 0;
+}
+
+static struct i2c_driver rx8025_driver = {
+	.driver = {
+		.name = "rtc-rx8025",
+		.owner = THIS_MODULE,
+	},
+	.probe		= rx8025_probe,
+	.remove		= __devexit_p(rx8025_remove),
+	.id_table	= rx8025_id,
+};
+
+static int __init rx8025_init(void)
+{
+	return i2c_add_driver(&rx8025_driver);
+}
+
+static void __exit rx8025_exit(void)
+{
+	i2c_del_driver(&rx8025_driver);
+}
+
+MODULE_AUTHOR("Wolfgang Grandegger <wg@grandegger.com>");
+MODULE_DESCRIPTION("RX-8025 SA/NB RTC driver");
+MODULE_LICENSE("GPL");
+
+module_init(rx8025_init);
+module_exit(rx8025_exit);
diff --git a/drivers/rtc/rtc-test.c b/drivers/rtc/rtc-test.c
index e478280..51725f7 100644
--- a/drivers/rtc/rtc-test.c
+++ b/drivers/rtc/rtc-test.c
@@ -93,7 +93,6 @@
 	struct rtc_device *rtc = platform_get_drvdata(plat_dev);
 
 	retval = count;
-	local_irq_disable();
 	if (strncmp(buf, "tick", 4) == 0)
 		rtc_update_irq(rtc, 1, RTC_PF | RTC_IRQF);
 	else if (strncmp(buf, "alarm", 5) == 0)
@@ -102,7 +101,6 @@
 		rtc_update_irq(rtc, 1, RTC_UF | RTC_IRQF);
 	else
 		retval = -EINVAL;
-	local_irq_enable();
 
 	return retval;
 }
diff --git a/drivers/rtc/rtc-tx4939.c b/drivers/rtc/rtc-tx4939.c
index 4ee4857..4a6ed11 100644
--- a/drivers/rtc/rtc-tx4939.c
+++ b/drivers/rtc/rtc-tx4939.c
@@ -261,10 +261,8 @@
 
 	tx4939_rtc_cmd(pdata->rtcreg, TX4939_RTCCTL_COMMAND_NOP);
 	if (devm_request_irq(&pdev->dev, irq, tx4939_rtc_interrupt,
-			     IRQF_DISABLED | IRQF_SHARED,
-			     pdev->name, &pdev->dev) < 0) {
+			     IRQF_DISABLED, pdev->name, &pdev->dev) < 0)
 		return -EBUSY;
-	}
 	rtc = rtc_device_register(pdev->name, &pdev->dev,
 				  &tx4939_rtc_ops, THIS_MODULE);
 	if (IS_ERR(rtc))
diff --git a/drivers/s390/net/qeth_l2_main.c b/drivers/s390/net/qeth_l2_main.c
index 81d7f26..691cecd 100644
--- a/drivers/s390/net/qeth_l2_main.c
+++ b/drivers/s390/net/qeth_l2_main.c
@@ -655,7 +655,7 @@
 	for (dm = dev->mc_list; dm; dm = dm->next)
 		qeth_l2_add_mc(card, dm->da_addr, 0);
 
-	list_for_each_entry(ha, &dev->uc_list, list)
+	list_for_each_entry(ha, &dev->uc.list, list)
 		qeth_l2_add_mc(card, ha->addr, 1);
 
 	spin_unlock_bh(&card->mclock);
diff --git a/drivers/s390/scsi/zfcp_aux.c b/drivers/s390/scsi/zfcp_aux.c
index 3ac27ee..2ccbd18 100644
--- a/drivers/s390/scsi/zfcp_aux.c
+++ b/drivers/s390/scsi/zfcp_aux.c
@@ -470,6 +470,12 @@
 	if (!adapter)
 		return -ENOMEM;
 
+	adapter->gs = kzalloc(sizeof(struct zfcp_wka_ports), GFP_KERNEL);
+	if (!adapter->gs) {
+		kfree(adapter);
+		return -ENOMEM;
+	}
+
 	ccw_device->handler = NULL;
 	adapter->ccw_device = ccw_device;
 	atomic_set(&adapter->refcount, 0);
@@ -523,8 +529,7 @@
 		goto sysfs_failed;
 
 	atomic_clear_mask(ZFCP_STATUS_COMMON_REMOVE, &adapter->status);
-
-	zfcp_fc_nameserver_init(adapter);
+	zfcp_fc_wka_ports_init(adapter);
 
 	if (!zfcp_adapter_scsi_register(adapter))
 		return 0;
@@ -571,6 +576,7 @@
 	kfree(adapter->req_list);
 	kfree(adapter->fc_stats);
 	kfree(adapter->stats_reset_data);
+	kfree(adapter->gs);
 	kfree(adapter);
 }
 
diff --git a/drivers/s390/scsi/zfcp_def.h b/drivers/s390/scsi/zfcp_def.h
index 2074d45..49d0532 100644
--- a/drivers/s390/scsi/zfcp_def.h
+++ b/drivers/s390/scsi/zfcp_def.h
@@ -22,6 +22,8 @@
 #include <linux/syscalls.h>
 #include <linux/scatterlist.h>
 #include <linux/ioctl.h>
+#include <scsi/fc/fc_fs.h>
+#include <scsi/fc/fc_gs.h>
 #include <scsi/scsi.h>
 #include <scsi/scsi_tcq.h>
 #include <scsi/scsi_cmnd.h>
@@ -29,6 +31,7 @@
 #include <scsi/scsi_host.h>
 #include <scsi/scsi_transport.h>
 #include <scsi/scsi_transport_fc.h>
+#include <scsi/scsi_bsg_fc.h>
 #include <asm/ccwdev.h>
 #include <asm/qdio.h>
 #include <asm/debug.h>
@@ -228,11 +231,6 @@
 
 /* FC-PH/FC-GS well-known address identifiers for generic services */
 #define ZFCP_DID_WKA				0xFFFFF0
-#define ZFCP_DID_MANAGEMENT_SERVICE		0xFFFFFA
-#define ZFCP_DID_TIME_SERVICE			0xFFFFFB
-#define ZFCP_DID_DIRECTORY_SERVICE		0xFFFFFC
-#define ZFCP_DID_ALIAS_SERVICE			0xFFFFF8
-#define ZFCP_DID_KEY_DISTRIBUTION_SERVICE	0xFFFFF7
 
 /* remote port status */
 #define ZFCP_STATUS_PORT_PHYS_OPEN		0x00000001
@@ -376,6 +374,14 @@
 	struct delayed_work	work;
 };
 
+struct zfcp_wka_ports {
+	struct zfcp_wka_port ms; 	/* management service */
+	struct zfcp_wka_port ts; 	/* time service */
+	struct zfcp_wka_port ds; 	/* directory service */
+	struct zfcp_wka_port as; 	/* alias service */
+	struct zfcp_wka_port ks; 	/* key distribution service */
+};
+
 struct zfcp_qdio_queue {
 	struct qdio_buffer *sbal[QDIO_MAX_BUFFERS_PER_Q];
 	u8		   first;	/* index of next free bfr in queue */
@@ -461,7 +467,7 @@
 						      actions */
 	u32			erp_low_mem_count; /* nr of erp actions waiting
 						      for memory */
-	struct zfcp_wka_port	nsp;		   /* adapter's nameserver */
+	struct zfcp_wka_ports	*gs;		   /* generic services */
 	debug_info_t		*rec_dbf;
 	debug_info_t		*hba_dbf;
 	debug_info_t		*san_dbf;          /* debug feature areas */
diff --git a/drivers/s390/scsi/zfcp_erp.c b/drivers/s390/scsi/zfcp_erp.c
index e50ea46..8030e25 100644
--- a/drivers/s390/scsi/zfcp_erp.c
+++ b/drivers/s390/scsi/zfcp_erp.c
@@ -719,7 +719,7 @@
 	zfcp_qdio_close(adapter);
 	zfcp_fsf_req_dismiss_all(adapter);
 	adapter->fsf_req_seq_no = 0;
-	zfcp_fc_wka_port_force_offline(&adapter->nsp);
+	zfcp_fc_wka_port_force_offline(&adapter->gs->ds);
 	/* all ports and units are closed */
 	zfcp_erp_modify_adapter_status(adapter, "erascl1", NULL,
 				       ZFCP_STATUS_COMMON_OPEN, ZFCP_CLEAR);
diff --git a/drivers/s390/scsi/zfcp_ext.h b/drivers/s390/scsi/zfcp_ext.h
index 120a9a1..3044c60 100644
--- a/drivers/s390/scsi/zfcp_ext.h
+++ b/drivers/s390/scsi/zfcp_ext.h
@@ -106,8 +106,12 @@
 extern void zfcp_fc_plogi_evaluate(struct zfcp_port *, struct fsf_plogi *);
 extern void zfcp_test_link(struct zfcp_port *);
 extern void zfcp_fc_link_test_work(struct work_struct *);
-extern void zfcp_fc_nameserver_init(struct zfcp_adapter *);
 extern void zfcp_fc_wka_port_force_offline(struct zfcp_wka_port *);
+extern void zfcp_fc_wka_ports_init(struct zfcp_adapter *);
+extern int zfcp_fc_execute_els_fc_job(struct fc_bsg_job *);
+extern int zfcp_fc_execute_ct_fc_job(struct fc_bsg_job *);
+extern void zfcp_fc_wka_port_force_offline(struct zfcp_wka_port *);
+
 
 /* zfcp_fsf.c */
 extern int zfcp_fsf_open_port(struct zfcp_erp_action *);
diff --git a/drivers/s390/scsi/zfcp_fc.c b/drivers/s390/scsi/zfcp_fc.c
index 35493a8..2f0705d 100644
--- a/drivers/s390/scsi/zfcp_fc.c
+++ b/drivers/s390/scsi/zfcp_fc.c
@@ -120,14 +120,13 @@
 	schedule_delayed_work(&wka_port->work, HZ / 100);
 }
 
-void zfcp_fc_nameserver_init(struct zfcp_adapter *adapter)
+static void zfcp_fc_wka_port_init(struct zfcp_wka_port *wka_port, u32 d_id,
+				  struct zfcp_adapter *adapter)
 {
-	struct zfcp_wka_port *wka_port = &adapter->nsp;
-
 	init_waitqueue_head(&wka_port->completion_wq);
 
 	wka_port->adapter = adapter;
-	wka_port->d_id = ZFCP_DID_DIRECTORY_SERVICE;
+	wka_port->d_id = d_id;
 
 	wka_port->status = ZFCP_WKA_PORT_OFFLINE;
 	atomic_set(&wka_port->refcount, 0);
@@ -143,6 +142,17 @@
 	mutex_unlock(&wka->mutex);
 }
 
+void zfcp_fc_wka_ports_init(struct zfcp_adapter *adapter)
+{
+	struct zfcp_wka_ports *gs = adapter->gs;
+
+	zfcp_fc_wka_port_init(&gs->ms, FC_FID_MGMT_SERV, adapter);
+	zfcp_fc_wka_port_init(&gs->ts, FC_FID_TIME_SERV, adapter);
+	zfcp_fc_wka_port_init(&gs->ds, FC_FID_DIR_SERV, adapter);
+	zfcp_fc_wka_port_init(&gs->as, FC_FID_ALIASES, adapter);
+	zfcp_fc_wka_port_init(&gs->ks, FC_FID_SEC_KEY, adapter);
+}
+
 static void _zfcp_fc_incoming_rscn(struct zfcp_fsf_req *fsf_req, u32 range,
 				   struct fcp_rscn_element *elem)
 {
@@ -282,7 +292,7 @@
 
 	/* setup parameters for send generic command */
 	gid_pn->port = erp_action->port;
-	gid_pn->ct.wka_port = &adapter->nsp;
+	gid_pn->ct.wka_port = &adapter->gs->ds;
 	gid_pn->ct.handler = zfcp_fc_ns_handler;
 	gid_pn->ct.handler_data = (unsigned long) &compl_rec;
 	gid_pn->ct.timeout = ZFCP_NS_GID_PN_TIMEOUT;
@@ -329,13 +339,13 @@
 
 	memset(gid_pn, 0, sizeof(*gid_pn));
 
-	ret = zfcp_wka_port_get(&adapter->nsp);
+	ret = zfcp_wka_port_get(&adapter->gs->ds);
 	if (ret)
 		goto out;
 
 	ret = zfcp_fc_ns_gid_pn_request(erp_action, gid_pn);
 
-	zfcp_wka_port_put(&adapter->nsp);
+	zfcp_wka_port_put(&adapter->gs->ds);
 out:
 	mempool_free(gid_pn, adapter->pool.data_gid_pn);
 	return ret;
@@ -525,7 +535,7 @@
 	req->fc4_type = ZFCP_CT_SCSI_FCP;
 
 	/* prepare zfcp_send_ct */
-	ct->wka_port = &adapter->nsp;
+	ct->wka_port = &adapter->gs->ds;
 	ct->handler = zfcp_fc_ns_handler;
 	ct->handler_data = (unsigned long)&compl_rec;
 	ct->timeout = 10;
@@ -644,7 +654,7 @@
 	    fc_host_port_type(adapter->scsi_host) != FC_PORTTYPE_NPIV)
 		return 0;
 
-	ret = zfcp_wka_port_get(&adapter->nsp);
+	ret = zfcp_wka_port_get(&adapter->gs->ds);
 	if (ret)
 		return ret;
 
@@ -666,7 +676,7 @@
 	}
 	zfcp_free_sg_env(gpn_ft, buf_num);
 out:
-	zfcp_wka_port_put(&adapter->nsp);
+	zfcp_wka_port_put(&adapter->gs->ds);
 	return ret;
 }
 
@@ -675,3 +685,158 @@
 {
 	zfcp_scan_ports(container_of(work, struct zfcp_adapter, scan_work));
 }
+
+struct zfcp_els_fc_job {
+	struct zfcp_send_els els;
+	struct fc_bsg_job *job;
+};
+
+static void zfcp_fc_generic_els_handler(unsigned long data)
+{
+	struct zfcp_els_fc_job *els_fc_job = (struct zfcp_els_fc_job *) data;
+	struct fc_bsg_job *job = els_fc_job->job;
+	struct fc_bsg_reply *reply = job->reply;
+
+	if (els_fc_job->els.status) {
+		/* request rejected or timed out */
+		reply->reply_data.ctels_reply.status = FC_CTELS_STATUS_REJECT;
+		goto out;
+	}
+
+	reply->reply_data.ctels_reply.status = FC_CTELS_STATUS_OK;
+	reply->reply_payload_rcv_len = job->reply_payload.payload_len;
+
+out:
+	job->state_flags = FC_RQST_STATE_DONE;
+	job->job_done(job);
+	kfree(els_fc_job);
+}
+
+int zfcp_fc_execute_els_fc_job(struct fc_bsg_job *job)
+{
+	struct zfcp_els_fc_job *els_fc_job;
+	struct fc_rport *rport = job->rport;
+	struct Scsi_Host *shost;
+	struct zfcp_adapter *adapter;
+	struct zfcp_port *port;
+	u8 *port_did;
+
+	shost = rport ? rport_to_shost(rport) : job->shost;
+	adapter = (struct zfcp_adapter *)shost->hostdata[0];
+
+	if (!(atomic_read(&adapter->status) & ZFCP_STATUS_COMMON_OPEN))
+		return -EINVAL;
+
+	els_fc_job = kzalloc(sizeof(struct zfcp_els_fc_job), GFP_KERNEL);
+	if (!els_fc_job)
+		return -ENOMEM;
+
+	els_fc_job->els.adapter = adapter;
+	if (rport) {
+		read_lock_irq(&zfcp_data.config_lock);
+		port = rport->dd_data;
+		if (port)
+			els_fc_job->els.d_id = port->d_id;
+		read_unlock_irq(&zfcp_data.config_lock);
+		if (!port) {
+			kfree(els_fc_job);
+			return -EINVAL;
+		}
+	} else {
+		port_did = job->request->rqst_data.h_els.port_id;
+		els_fc_job->els.d_id = (port_did[0] << 16) +
+					(port_did[1] << 8) + port_did[2];
+	}
+
+	els_fc_job->els.req = job->request_payload.sg_list;
+	els_fc_job->els.resp = job->reply_payload.sg_list;
+	els_fc_job->els.handler = zfcp_fc_generic_els_handler;
+	els_fc_job->els.handler_data = (unsigned long) els_fc_job;
+	els_fc_job->job = job;
+
+	return zfcp_fsf_send_els(&els_fc_job->els);
+}
+
+struct zfcp_ct_fc_job {
+	struct zfcp_send_ct ct;
+	struct fc_bsg_job *job;
+};
+
+static void zfcp_fc_generic_ct_handler(unsigned long data)
+{
+	struct zfcp_ct_fc_job *ct_fc_job = (struct zfcp_ct_fc_job *) data;
+	struct fc_bsg_job *job = ct_fc_job->job;
+
+	job->reply->reply_data.ctels_reply.status = ct_fc_job->ct.status ?
+				FC_CTELS_STATUS_REJECT : FC_CTELS_STATUS_OK;
+	job->reply->reply_payload_rcv_len = job->reply_payload.payload_len;
+	job->state_flags = FC_RQST_STATE_DONE;
+	job->job_done(job);
+
+	zfcp_wka_port_put(ct_fc_job->ct.wka_port);
+
+	kfree(ct_fc_job);
+}
+
+int zfcp_fc_execute_ct_fc_job(struct fc_bsg_job *job)
+{
+	int ret;
+	u8 gs_type;
+	struct fc_rport *rport = job->rport;
+	struct Scsi_Host *shost;
+	struct zfcp_adapter *adapter;
+	struct zfcp_ct_fc_job *ct_fc_job;
+	u32 preamble_word1;
+
+	shost = rport ? rport_to_shost(rport) : job->shost;
+
+	adapter = (struct zfcp_adapter *)shost->hostdata[0];
+	if (!(atomic_read(&adapter->status) & ZFCP_STATUS_COMMON_OPEN))
+		return -EINVAL;
+
+	ct_fc_job = kzalloc(sizeof(struct zfcp_ct_fc_job), GFP_KERNEL);
+	if (!ct_fc_job)
+		return -ENOMEM;
+
+	preamble_word1 = job->request->rqst_data.r_ct.preamble_word1;
+	gs_type = (preamble_word1 & 0xff000000) >> 24;
+
+	switch (gs_type) {
+	case FC_FST_ALIAS:
+		ct_fc_job->ct.wka_port = &adapter->gs->as;
+		break;
+	case FC_FST_MGMT:
+		ct_fc_job->ct.wka_port = &adapter->gs->ms;
+		break;
+	case FC_FST_TIME:
+		ct_fc_job->ct.wka_port = &adapter->gs->ts;
+		break;
+	case FC_FST_DIR:
+		ct_fc_job->ct.wka_port = &adapter->gs->ds;
+		break;
+	default:
+		kfree(ct_fc_job);
+		return -EINVAL; /* no such service */
+	}
+
+	ret = zfcp_wka_port_get(ct_fc_job->ct.wka_port);
+	if (ret) {
+		kfree(ct_fc_job);
+		return ret;
+	}
+
+	ct_fc_job->ct.req = job->request_payload.sg_list;
+	ct_fc_job->ct.resp = job->reply_payload.sg_list;
+	ct_fc_job->ct.timeout = ZFCP_FSF_REQUEST_TIMEOUT;
+	ct_fc_job->ct.handler = zfcp_fc_generic_ct_handler;
+	ct_fc_job->ct.handler_data = (unsigned long) ct_fc_job;
+	ct_fc_job->ct.completion = NULL;
+	ct_fc_job->job = job;
+
+	ret = zfcp_fsf_send_ct(&ct_fc_job->ct, NULL, NULL);
+	if (ret) {
+		kfree(ct_fc_job);
+		zfcp_wka_port_put(ct_fc_job->ct.wka_port);
+	}
+	return ret;
+}
diff --git a/drivers/s390/scsi/zfcp_fsf.c b/drivers/s390/scsi/zfcp_fsf.c
index e6dae37..c57658f 100644
--- a/drivers/s390/scsi/zfcp_fsf.c
+++ b/drivers/s390/scsi/zfcp_fsf.c
@@ -1146,7 +1146,8 @@
 	case FSF_RESPONSE_SIZE_TOO_LARGE:
 		break;
 	case FSF_ACCESS_DENIED:
-		zfcp_fsf_access_denied_port(req, port);
+		if (port)
+			zfcp_fsf_access_denied_port(req, port);
 		break;
 	case FSF_SBAL_MISMATCH:
 		/* should never occure, avoided in zfcp_fsf_send_els */
diff --git a/drivers/s390/scsi/zfcp_scsi.c b/drivers/s390/scsi/zfcp_scsi.c
index 7d0da23..967ede7 100644
--- a/drivers/s390/scsi/zfcp_scsi.c
+++ b/drivers/s390/scsi/zfcp_scsi.c
@@ -623,6 +623,20 @@
 	zfcp_unit_put(unit);
 }
 
+static int zfcp_execute_fc_job(struct fc_bsg_job *job)
+{
+	switch (job->request->msgcode) {
+	case FC_BSG_RPT_ELS:
+	case FC_BSG_HST_ELS_NOLOGIN:
+		return zfcp_fc_execute_els_fc_job(job);
+	case FC_BSG_RPT_CT:
+	case FC_BSG_HST_CT:
+		return zfcp_fc_execute_ct_fc_job(job);
+	default:
+		return -EINVAL;
+	}
+}
+
 struct fc_function_template zfcp_transport_functions = {
 	.show_starget_port_id = 1,
 	.show_starget_port_name = 1,
@@ -644,6 +658,7 @@
 	.dev_loss_tmo_callbk = zfcp_scsi_dev_loss_tmo_callbk,
 	.terminate_rport_io = zfcp_scsi_terminate_rport_io,
 	.show_host_port_state = 1,
+	.bsg_request = zfcp_execute_fc_job,
 	/* no functions registered for following dynamic attributes but
 	   directly set by LLDD */
 	.show_host_port_type = 1,
diff --git a/drivers/scsi/aic7xxx/aic79xx_osm.c b/drivers/scsi/aic7xxx/aic79xx_osm.c
index 0f829b3..75b2331 100644
--- a/drivers/scsi/aic7xxx/aic79xx_osm.c
+++ b/drivers/scsi/aic7xxx/aic79xx_osm.c
@@ -627,19 +627,15 @@
 					    starget->id, &tstate);
 
 		if ((flags  & CFPACKETIZED) == 0) {
-			/* Do not negotiate packetized transfers */
-			spi_rd_strm(starget) = 0;
-			spi_pcomp_en(starget) = 0;
-			spi_rti(starget) = 0;
-			spi_wr_flow(starget) = 0;
-			spi_hold_mcs(starget) = 0;
+			/* don't negotiate packetized (IU) transfers */
+			spi_max_iu(starget) = 0;
 		} else {
 			if ((ahd->features & AHD_RTI) == 0)
 				spi_rti(starget) = 0;
 		}
 
 		if ((flags & CFQAS) == 0)
-			spi_qas(starget) = 0;
+			spi_max_qas(starget) = 0;
 
 		/* Transinfo values have been set to BIOS settings */
 		spi_max_width(starget) = (flags & CFWIDEB) ? 1 : 0;
diff --git a/drivers/scsi/bnx2i/Kconfig b/drivers/scsi/bnx2i/Kconfig
index 820d428..b62b482 100644
--- a/drivers/scsi/bnx2i/Kconfig
+++ b/drivers/scsi/bnx2i/Kconfig
@@ -2,6 +2,7 @@
 	tristate "Broadcom NetXtreme II iSCSI support"
 	select SCSI_ISCSI_ATTRS
 	select CNIC
+	depends on PCI
 	---help---
 	This driver supports iSCSI offload for the Broadcom NetXtreme II
 	devices.
diff --git a/drivers/scsi/lpfc/lpfc.h b/drivers/scsi/lpfc/lpfc.h
index 5405698..1877d98 100644
--- a/drivers/scsi/lpfc/lpfc.h
+++ b/drivers/scsi/lpfc/lpfc.h
@@ -457,10 +457,6 @@
 	void (*lpfc_scsi_prep_cmnd)
 		(struct lpfc_vport *, struct lpfc_scsi_buf *,
 		 struct lpfc_nodelist *);
-	int (*lpfc_scsi_prep_task_mgmt_cmd)
-		(struct lpfc_vport *, struct lpfc_scsi_buf *,
-		 unsigned int, uint8_t);
-
 	/* IOCB interface function jump table entries */
 	int (*__lpfc_sli_issue_iocb)
 		(struct lpfc_hba *, uint32_t,
diff --git a/drivers/scsi/lpfc/lpfc_attr.c b/drivers/scsi/lpfc/lpfc_attr.c
index d73e677..fc07be5 100644
--- a/drivers/scsi/lpfc/lpfc_attr.c
+++ b/drivers/scsi/lpfc/lpfc_attr.c
@@ -3113,6 +3113,9 @@
 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
 	struct lpfc_hba   *phba = vport->phba;
 
+	if (phba->sli_rev >= LPFC_SLI_REV4)
+		return -EPERM;
+
 	if ((off + count) > FF_REG_AREA_SIZE)
 		return -ERANGE;
 
@@ -3163,6 +3166,9 @@
 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
 	struct lpfc_hba   *phba = vport->phba;
 
+	if (phba->sli_rev >= LPFC_SLI_REV4)
+		return -EPERM;
+
 	if (off > FF_REG_AREA_SIZE)
 		return -ERANGE;
 
diff --git a/drivers/scsi/lpfc/lpfc_ct.c b/drivers/scsi/lpfc/lpfc_ct.c
index 1dbccfd..0e532f0 100644
--- a/drivers/scsi/lpfc/lpfc_ct.c
+++ b/drivers/scsi/lpfc/lpfc_ct.c
@@ -1732,7 +1732,9 @@
 	uint32_t *ptr, str[4];
 	uint8_t *fwname;
 
-	if (vp->rev.rBit) {
+	if (phba->sli_rev == LPFC_SLI_REV4)
+		sprintf(fwrevision, "%s", vp->rev.opFwName);
+	else if (vp->rev.rBit) {
 		if (psli->sli_flag & LPFC_SLI_ACTIVE)
 			rev = vp->rev.sli2FwRev;
 		else
diff --git a/drivers/scsi/lpfc/lpfc_els.c b/drivers/scsi/lpfc/lpfc_els.c
index 6bdeb14..f72fdf2 100644
--- a/drivers/scsi/lpfc/lpfc_els.c
+++ b/drivers/scsi/lpfc/lpfc_els.c
@@ -168,6 +168,19 @@
 	if (elsiocb == NULL)
 		return NULL;
 
+	/*
+	 * If this command is for fabric controller and HBA running
+	 * in FIP mode send FLOGI, FDISC and LOGO as FIP frames.
+	 */
+	if ((did == Fabric_DID) &&
+		bf_get(lpfc_fip_flag, &phba->sli4_hba.sli4_flags) &&
+		((elscmd == ELS_CMD_FLOGI) ||
+		 (elscmd == ELS_CMD_FDISC) ||
+		 (elscmd == ELS_CMD_LOGO)))
+		elsiocb->iocb_flag |= LPFC_FIP_ELS;
+	else
+		elsiocb->iocb_flag &= ~LPFC_FIP_ELS;
+
 	icmd = &elsiocb->iocb;
 
 	/* fill in BDEs for command */
@@ -6108,9 +6121,17 @@
 	icmd->un.elsreq64.myID = 0;
 	icmd->un.elsreq64.fl = 1;
 
-	/* For FDISC, Let FDISC rsp set the NPortID for this VPI */
-	icmd->ulpCt_h = 1;
-	icmd->ulpCt_l = 0;
+	if  (phba->sli_rev == LPFC_SLI_REV4) {
+		/* FDISC needs to be 1 for WQE VPI */
+		elsiocb->iocb.ulpCt_h = (SLI4_CT_VPI >> 1) & 1;
+		elsiocb->iocb.ulpCt_l = SLI4_CT_VPI & 1 ;
+		/* Set the ulpContext to the vpi */
+		elsiocb->iocb.ulpContext = vport->vpi + phba->vpi_base;
+	} else {
+		/* For FDISC, Let FDISC rsp set the NPortID for this VPI */
+		icmd->ulpCt_h = 1;
+		icmd->ulpCt_l = 0;
+	}
 
 	pcmd = (uint8_t *) (((struct lpfc_dmabuf *) elsiocb->context2)->virt);
 	*((uint32_t *) (pcmd)) = ELS_CMD_FDISC;
diff --git a/drivers/scsi/lpfc/lpfc_hbadisc.c b/drivers/scsi/lpfc/lpfc_hbadisc.c
index 35c41ae..ed46b24 100644
--- a/drivers/scsi/lpfc/lpfc_hbadisc.c
+++ b/drivers/scsi/lpfc/lpfc_hbadisc.c
@@ -1197,6 +1197,11 @@
 {
 	struct lpfc_fcf_conn_entry *conn_entry;
 
+	/* If FCF not available return 0 */
+	if (!bf_get(lpfc_fcf_record_fcf_avail, new_fcf_record) ||
+		!bf_get(lpfc_fcf_record_fcf_valid, new_fcf_record))
+		return 0;
+
 	if (!phba->cfg_enable_fip) {
 		*boot_flag = 0;
 		*addr_mode = bf_get(lpfc_fcf_record_mac_addr_prov,
@@ -1216,6 +1221,14 @@
 		*boot_flag = 0;
 		*addr_mode = bf_get(lpfc_fcf_record_mac_addr_prov,
 			new_fcf_record);
+
+		/*
+		 * When there are no FCF connect entries, use driver's default
+		 * addressing mode - FPMA.
+		 */
+		if (*addr_mode & LPFC_FCF_FPMA)
+			*addr_mode = LPFC_FCF_FPMA;
+
 		*vlan_id = 0xFFFF;
 		return 1;
 	}
@@ -1241,6 +1254,14 @@
 		}
 
 		/*
+		 * If connection record does not support any addressing mode,
+		 * skip the FCF record.
+		 */
+		if (!(bf_get(lpfc_fcf_record_mac_addr_prov, new_fcf_record)
+			& (LPFC_FCF_FPMA | LPFC_FCF_SPMA)))
+			continue;
+
+		/*
 		 * Check if the connection record specifies a required
 		 * addressing mode.
 		 */
@@ -1272,6 +1293,11 @@
 		else
 			*boot_flag = 0;
 
+		/*
+		 * If user did not specify any addressing mode, or if the
+		 * prefered addressing mode specified by user is not supported
+		 * by FCF, allow fabric to pick the addressing mode.
+		 */
 		*addr_mode = bf_get(lpfc_fcf_record_mac_addr_prov,
 				new_fcf_record);
 		/*
@@ -1297,12 +1323,6 @@
 			!(conn_entry->conn_rec.flags & FCFCNCT_AM_SPMA) &&
 			(*addr_mode & LPFC_FCF_FPMA))
 				*addr_mode = LPFC_FCF_FPMA;
-		/*
-		 * If user did not specify any addressing mode, use FPMA if
-		 * possible else use SPMA.
-		 */
-		else if (*addr_mode & LPFC_FCF_FPMA)
-			*addr_mode = LPFC_FCF_FPMA;
 
 		if (conn_entry->conn_rec.flags & FCFCNCT_VLAN_VALID)
 			*vlan_id = conn_entry->conn_rec.vlan_tag;
@@ -1864,7 +1884,7 @@
 		vport->fc_flag &= ~FC_BYPASSED_MODE;
 	spin_unlock_irq(shost->host_lock);
 
-	if (((phba->fc_eventTag + 1) < la->eventTag) ||
+	if ((phba->fc_eventTag  < la->eventTag) ||
 	    (phba->fc_eventTag == la->eventTag)) {
 		phba->fc_stat.LinkMultiEvent++;
 		if (la->attType == AT_LINK_UP)
@@ -2925,6 +2945,7 @@
 		lpfc_no_rpi(phba, ndlp);
 		ndlp->nlp_rpi = 0;
 		ndlp->nlp_flag &= ~NLP_RPI_VALID;
+		ndlp->nlp_flag &= ~NLP_NPR_ADISC;
 		return 1;
 	}
 	return 0;
diff --git a/drivers/scsi/lpfc/lpfc_hw.h b/drivers/scsi/lpfc/lpfc_hw.h
index 02aa016..8a3a026 100644
--- a/drivers/scsi/lpfc/lpfc_hw.h
+++ b/drivers/scsi/lpfc/lpfc_hw.h
@@ -1183,7 +1183,6 @@
 #define PCI_DEVICE_ID_ZEPHYR_DCSP   0xfe12
 #define PCI_VENDOR_ID_SERVERENGINE  0x19a2
 #define PCI_DEVICE_ID_TIGERSHARK    0x0704
-#define PCI_DEVICE_ID_TIGERSHARK_S  0x0705
 
 #define JEDEC_ID_ADDRESS            0x0080001c
 #define FIREFLY_JEDEC_ID            0x1ACC
diff --git a/drivers/scsi/lpfc/lpfc_hw4.h b/drivers/scsi/lpfc/lpfc_hw4.h
index 39c34b3..2995d12 100644
--- a/drivers/scsi/lpfc/lpfc_hw4.h
+++ b/drivers/scsi/lpfc/lpfc_hw4.h
@@ -422,9 +422,9 @@
 #define lpfc_wqe_gen_pri_WORD		word10
 	uint32_t word11;
 #define lpfc_wqe_gen_cq_id_SHIFT	16
-#define lpfc_wqe_gen_cq_id_MASK		0x000003FF
+#define lpfc_wqe_gen_cq_id_MASK		0x0000FFFF
 #define lpfc_wqe_gen_cq_id_WORD		word11
-#define LPFC_WQE_CQ_ID_DEFAULT	0x3ff
+#define LPFC_WQE_CQ_ID_DEFAULT	0xffff
 #define lpfc_wqe_gen_wqec_SHIFT		7
 #define lpfc_wqe_gen_wqec_MASK		0x00000001
 #define lpfc_wqe_gen_wqec_WORD		word11
@@ -1128,7 +1128,7 @@
 #define lpfc_fcf_record_mac_5_WORD		word4
 #define lpfc_fcf_record_fcf_avail_SHIFT		16
 #define lpfc_fcf_record_fcf_avail_MASK		0x000000FF
-#define lpfc_fcf_record_fc_avail_WORD		word4
+#define lpfc_fcf_record_fcf_avail_WORD		word4
 #define lpfc_fcf_record_mac_addr_prov_SHIFT	24
 #define lpfc_fcf_record_mac_addr_prov_MASK	0x000000FF
 #define lpfc_fcf_record_mac_addr_prov_WORD	word4
diff --git a/drivers/scsi/lpfc/lpfc_init.c b/drivers/scsi/lpfc/lpfc_init.c
index 2f5907f..fc67cc6 100644
--- a/drivers/scsi/lpfc/lpfc_init.c
+++ b/drivers/scsi/lpfc/lpfc_init.c
@@ -428,7 +428,8 @@
 	/* Reset the DFT_HBA_Q_DEPTH to the max xri  */
 	if (phba->cfg_hba_queue_depth > (mb->un.varRdConfig.max_xri+1))
 		phba->cfg_hba_queue_depth =
-			mb->un.varRdConfig.max_xri + 1;
+			(mb->un.varRdConfig.max_xri + 1) -
+					lpfc_sli4_get_els_iocb_cnt(phba);
 
 	phba->lmt = mb->un.varRdConfig.lmt;
 
@@ -1646,10 +1647,6 @@
 		oneConnect = 1;
 		m = (typeof(m)) {"OCe10100-F", max_speed, "PCIe"};
 		break;
-	case PCI_DEVICE_ID_TIGERSHARK_S:
-		oneConnect = 1;
-		m = (typeof(m)) {"OCe10100-F-S", max_speed, "PCIe"};
-		break;
 	default:
 		m = (typeof(m)){ NULL };
 		break;
@@ -3543,6 +3540,7 @@
 
 	/* Free the allocated rpi headers. */
 	lpfc_sli4_remove_rpi_hdrs(phba);
+	lpfc_sli4_remove_rpis(phba);
 
 	/* Free the ELS sgl list */
 	lpfc_free_active_sgl(phba);
@@ -7184,16 +7182,19 @@
 {
 	int max_xri = phba->sli4_hba.max_cfg_param.max_xri;
 
-	if (max_xri <= 100)
-		return 4;
-	else if (max_xri <= 256)
-		return 8;
-	else if (max_xri <= 512)
-		return 16;
-	else if (max_xri <= 1024)
-		return 32;
-	else
-		return 48;
+	if (phba->sli_rev == LPFC_SLI_REV4) {
+		if (max_xri <= 100)
+			return 4;
+		else if (max_xri <= 256)
+			return 8;
+		else if (max_xri <= 512)
+			return 16;
+		else if (max_xri <= 1024)
+			return 32;
+		else
+			return 48;
+	} else
+		return 0;
 }
 
 /**
@@ -7642,7 +7643,6 @@
 
 	switch (dev_id) {
 	case PCI_DEVICE_ID_TIGERSHARK:
-	case PCI_DEVICE_ID_TIGERSHARK_S:
 		rc = lpfc_pci_probe_one_s4(pdev, pid);
 		break;
 	default:
@@ -7941,8 +7941,6 @@
 		PCI_ANY_ID, PCI_ANY_ID, },
 	{PCI_VENDOR_ID_SERVERENGINE, PCI_DEVICE_ID_TIGERSHARK,
 		PCI_ANY_ID, PCI_ANY_ID, },
-	{PCI_VENDOR_ID_SERVERENGINE, PCI_DEVICE_ID_TIGERSHARK_S,
-		PCI_ANY_ID, PCI_ANY_ID, },
 	{ 0 }
 };
 
diff --git a/drivers/scsi/lpfc/lpfc_mbox.c b/drivers/scsi/lpfc/lpfc_mbox.c
index b9b451c..3423571 100644
--- a/drivers/scsi/lpfc/lpfc_mbox.c
+++ b/drivers/scsi/lpfc/lpfc_mbox.c
@@ -1631,6 +1631,7 @@
 		/* In case of malloc fails, proceed with whatever we have */
 		if (!viraddr)
 			break;
+		memset(viraddr, 0, PAGE_SIZE);
 		mbox->sge_array->addr[pagen] = viraddr;
 		/* Keep the first page for later sub-header construction */
 		if (pagen == 0)
@@ -1715,8 +1716,10 @@
 	/* Set up host requested features. */
 	bf_set(lpfc_mbx_rq_ftr_rq_fcpi, &mboxq->u.mqe.un.req_ftrs, 1);
 
-	/* Virtual fabrics and FIPs are not supported yet. */
-	bf_set(lpfc_mbx_rq_ftr_rq_ifip, &mboxq->u.mqe.un.req_ftrs, 0);
+	if (phba->cfg_enable_fip)
+		bf_set(lpfc_mbx_rq_ftr_rq_ifip, &mboxq->u.mqe.un.req_ftrs, 0);
+	else
+		bf_set(lpfc_mbx_rq_ftr_rq_ifip, &mboxq->u.mqe.un.req_ftrs, 1);
 
 	/* Enable DIF (block guard) only if configured to do so. */
 	if (phba->cfg_enable_bg)
diff --git a/drivers/scsi/lpfc/lpfc_nportdisc.c b/drivers/scsi/lpfc/lpfc_nportdisc.c
index 09f659f..3e74136 100644
--- a/drivers/scsi/lpfc/lpfc_nportdisc.c
+++ b/drivers/scsi/lpfc/lpfc_nportdisc.c
@@ -497,7 +497,7 @@
 		lpfc_els_rsp_acc(vport, ELS_CMD_PRLO, cmdiocb, ndlp, NULL);
 	else
 		lpfc_els_rsp_acc(vport, ELS_CMD_ACC, cmdiocb, ndlp, NULL);
-	if ((ndlp->nlp_type & NLP_FABRIC) &&
+	if ((ndlp->nlp_DID == Fabric_DID) &&
 		vport->port_type == LPFC_NPIV_PORT) {
 		lpfc_linkdown_port(vport);
 		mod_timer(&ndlp->nlp_delayfunc, jiffies + HZ * 1);
diff --git a/drivers/scsi/lpfc/lpfc_scsi.c b/drivers/scsi/lpfc/lpfc_scsi.c
index 7991ba1..da59c4f 100644
--- a/drivers/scsi/lpfc/lpfc_scsi.c
+++ b/drivers/scsi/lpfc/lpfc_scsi.c
@@ -116,6 +116,27 @@
 }
 
 /**
+ * lpfc_sli4_set_rsp_sgl_last - Set the last bit in the response sge.
+ * @phba: Pointer to HBA object.
+ * @lpfc_cmd: lpfc scsi command object pointer.
+ *
+ * This function is called from the lpfc_prep_task_mgmt_cmd function to
+ * set the last bit in the response sge entry.
+ **/
+static void
+lpfc_sli4_set_rsp_sgl_last(struct lpfc_hba *phba,
+				struct lpfc_scsi_buf *lpfc_cmd)
+{
+	struct sli4_sge *sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
+	if (sgl) {
+		sgl += 1;
+		sgl->word2 = le32_to_cpu(sgl->word2);
+		bf_set(lpfc_sli4_sge_last, sgl, 1);
+		sgl->word2 = cpu_to_le32(sgl->word2);
+	}
+}
+
+/**
  * lpfc_update_stats - Update statistical data for the command completion
  * @phba: Pointer to HBA object.
  * @lpfc_cmd: lpfc scsi command object pointer.
@@ -1978,7 +1999,7 @@
 }
 
 /**
- * lpfc_scsi_unprep_dma_buf_s3 - Un-map DMA mapping of SG-list for SLI3 dev
+ * lpfc_scsi_unprep_dma_buf - Un-map DMA mapping of SG-list for dev
  * @phba: The HBA for which this call is being executed.
  * @psb: The scsi buffer which is going to be un-mapped.
  *
@@ -1986,7 +2007,7 @@
  * field of @lpfc_cmd for device with SLI-3 interface spec.
  **/
 static void
-lpfc_scsi_unprep_dma_buf_s3(struct lpfc_hba *phba, struct lpfc_scsi_buf *psb)
+lpfc_scsi_unprep_dma_buf(struct lpfc_hba *phba, struct lpfc_scsi_buf *psb)
 {
 	/*
 	 * There are only two special cases to consider.  (1) the scsi command
@@ -2003,36 +2024,6 @@
 }
 
 /**
- * lpfc_scsi_unprep_dma_buf_s4 - Un-map DMA mapping of SG-list for SLI4 dev
- * @phba: The Hba for which this call is being executed.
- * @psb: The scsi buffer which is going to be un-mapped.
- *
- * This routine does DMA un-mapping of scatter gather list of scsi command
- * field of @lpfc_cmd for device with SLI-4 interface spec. If we have to
- * remove the sgl for this scsi buffer then we will do it here. For now
- * we should be able to just call the sli3 unprep routine.
- **/
-static void
-lpfc_scsi_unprep_dma_buf_s4(struct lpfc_hba *phba, struct lpfc_scsi_buf *psb)
-{
-	lpfc_scsi_unprep_dma_buf_s3(phba, psb);
-}
-
-/**
- * lpfc_scsi_unprep_dma_buf - Wrapper function for unmap DMA mapping of SG-list
- * @phba: The Hba for which this call is being executed.
- * @psb: The scsi buffer which is going to be un-mapped.
- *
- * This routine does DMA un-mapping of scatter gather list of scsi command
- * field of @lpfc_cmd for device with SLI-4 interface spec.
- **/
-static void
-lpfc_scsi_unprep_dma_buf(struct lpfc_hba *phba, struct lpfc_scsi_buf *psb)
-{
-	phba->lpfc_scsi_unprep_dma_buf(phba, psb);
-}
-
-/**
  * lpfc_handler_fcp_err - FCP response handler
  * @vport: The virtual port for which this call is being executed.
  * @lpfc_cmd: Pointer to lpfc_scsi_buf data structure.
@@ -2461,7 +2452,7 @@
 }
 
 /**
- * lpfc_scsi_prep_cmnd_s3 - Convert scsi cmnd to FCP infor unit for SLI3 dev
+ * lpfc_scsi_prep_cmnd - Wrapper func for convert scsi cmnd to FCP info unit
  * @vport: The virtual port for which this call is being executed.
  * @lpfc_cmd: The scsi command which needs to send.
  * @pnode: Pointer to lpfc_nodelist.
@@ -2470,7 +2461,7 @@
  * to transfer for device with SLI3 interface spec.
  **/
 static void
-lpfc_scsi_prep_cmnd_s3(struct lpfc_vport *vport, struct lpfc_scsi_buf *lpfc_cmd,
+lpfc_scsi_prep_cmnd(struct lpfc_vport *vport, struct lpfc_scsi_buf *lpfc_cmd,
 		    struct lpfc_nodelist *pnode)
 {
 	struct lpfc_hba *phba = vport->phba;
@@ -2558,46 +2549,7 @@
 }
 
 /**
- * lpfc_scsi_prep_cmnd_s4 - Convert scsi cmnd to FCP infor unit for SLI4 dev
- * @vport: The virtual port for which this call is being executed.
- * @lpfc_cmd: The scsi command which needs to send.
- * @pnode: Pointer to lpfc_nodelist.
- *
- * This routine initializes fcp_cmnd and iocb data structure from scsi command
- * to transfer for device with SLI4 interface spec.
- **/
-static void
-lpfc_scsi_prep_cmnd_s4(struct lpfc_vport *vport, struct lpfc_scsi_buf *lpfc_cmd,
-		       struct lpfc_nodelist *pnode)
-{
-	/*
-	 * The prep cmnd routines do not touch the sgl or its
-	 * entries. We may not have to do anything different.
-	 * I will leave this function in place until we can
-	 * run some IO through the driver and determine if changes
-	 * are needed.
-	 */
-	return lpfc_scsi_prep_cmnd_s3(vport, lpfc_cmd, pnode);
-}
-
-/**
- * lpfc_scsi_prep_cmnd - Wrapper func for convert scsi cmnd to FCP info unit
- * @vport: The virtual port for which this call is being executed.
- * @lpfc_cmd: The scsi command which needs to send.
- * @pnode: Pointer to lpfc_nodelist.
- *
- * This routine wraps the actual convert SCSI cmnd function pointer from
- * the lpfc_hba struct.
- **/
-static inline void
-lpfc_scsi_prep_cmnd(struct lpfc_vport *vport, struct lpfc_scsi_buf *lpfc_cmd,
-		    struct lpfc_nodelist *pnode)
-{
-	vport->phba->lpfc_scsi_prep_cmnd(vport, lpfc_cmd, pnode);
-}
-
-/**
- * lpfc_scsi_prep_task_mgmt_cmnd_s3 - Convert SLI3 scsi TM cmd to FCP info unit
+ * lpfc_scsi_prep_task_mgmt_cmnd - Convert SLI3 scsi TM cmd to FCP info unit
  * @vport: The virtual port for which this call is being executed.
  * @lpfc_cmd: Pointer to lpfc_scsi_buf data structure.
  * @lun: Logical unit number.
@@ -2611,7 +2563,7 @@
  *   1 - Success
  **/
 static int
-lpfc_scsi_prep_task_mgmt_cmd_s3(struct lpfc_vport *vport,
+lpfc_scsi_prep_task_mgmt_cmd(struct lpfc_vport *vport,
 			     struct lpfc_scsi_buf *lpfc_cmd,
 			     unsigned int lun,
 			     uint8_t task_mgmt_cmd)
@@ -2653,71 +2605,16 @@
 		 * The driver will provide the timeout mechanism.
 		 */
 		piocb->ulpTimeout = 0;
-	} else {
+	} else
 		piocb->ulpTimeout = lpfc_cmd->timeout;
-	}
+
+	if (vport->phba->sli_rev == LPFC_SLI_REV4)
+		lpfc_sli4_set_rsp_sgl_last(vport->phba, lpfc_cmd);
 
 	return 1;
 }
 
 /**
- * lpfc_scsi_prep_task_mgmt_cmnd_s4 - Convert SLI4 scsi TM cmd to FCP info unit
- * @vport: The virtual port for which this call is being executed.
- * @lpfc_cmd: Pointer to lpfc_scsi_buf data structure.
- * @lun: Logical unit number.
- * @task_mgmt_cmd: SCSI task management command.
- *
- * This routine creates FCP information unit corresponding to @task_mgmt_cmd
- * for device with SLI-4 interface spec.
- *
- * Return codes:
- * 	0 - Error
- * 	1 - Success
- **/
-static int
-lpfc_scsi_prep_task_mgmt_cmd_s4(struct lpfc_vport *vport,
-				struct lpfc_scsi_buf *lpfc_cmd,
-				unsigned int lun,
-				uint8_t task_mgmt_cmd)
-{
-	/*
-	 * The prep cmnd routines do not touch the sgl or its
-	 * entries. We may not have to do anything different.
-	 * I will leave this function in place until we can
-	 * run some IO through the driver and determine if changes
-	 * are needed.
-	 */
-	return lpfc_scsi_prep_task_mgmt_cmd_s3(vport, lpfc_cmd, lun,
-						task_mgmt_cmd);
-}
-
-/**
- * lpfc_scsi_prep_task_mgmt_cmnd - Wrapper func convert scsi TM cmd to FCP info
- * @vport: The virtual port for which this call is being executed.
- * @lpfc_cmd: Pointer to lpfc_scsi_buf data structure.
- * @lun: Logical unit number.
- * @task_mgmt_cmd: SCSI task management command.
- *
- * This routine wraps the actual convert SCSI TM to FCP information unit
- * function pointer from the lpfc_hba struct.
- *
- * Return codes:
- * 	0 - Error
- * 	1 - Success
- **/
-static inline int
-lpfc_scsi_prep_task_mgmt_cmd(struct lpfc_vport *vport,
-			     struct lpfc_scsi_buf *lpfc_cmd,
-			     unsigned int lun,
-			     uint8_t task_mgmt_cmd)
-{
-	struct lpfc_hba *phba = vport->phba;
-
-	return phba->lpfc_scsi_prep_task_mgmt_cmd(vport, lpfc_cmd, lun,
-						  task_mgmt_cmd);
-}
-
-/**
  * lpfc_scsi_api_table_setup - Set up scsi api fucntion jump table
  * @phba: The hba struct for which this call is being executed.
  * @dev_grp: The HBA PCI-Device group number.
@@ -2730,23 +2627,19 @@
 lpfc_scsi_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
 {
 
+	phba->lpfc_scsi_unprep_dma_buf = lpfc_scsi_unprep_dma_buf;
+	phba->lpfc_scsi_prep_cmnd = lpfc_scsi_prep_cmnd;
+	phba->lpfc_get_scsi_buf = lpfc_get_scsi_buf;
+
 	switch (dev_grp) {
 	case LPFC_PCI_DEV_LP:
 		phba->lpfc_new_scsi_buf = lpfc_new_scsi_buf_s3;
 		phba->lpfc_scsi_prep_dma_buf = lpfc_scsi_prep_dma_buf_s3;
-		phba->lpfc_scsi_prep_cmnd = lpfc_scsi_prep_cmnd_s3;
-		phba->lpfc_scsi_unprep_dma_buf = lpfc_scsi_unprep_dma_buf_s3;
-		phba->lpfc_scsi_prep_task_mgmt_cmd =
-					lpfc_scsi_prep_task_mgmt_cmd_s3;
 		phba->lpfc_release_scsi_buf = lpfc_release_scsi_buf_s3;
 		break;
 	case LPFC_PCI_DEV_OC:
 		phba->lpfc_new_scsi_buf = lpfc_new_scsi_buf_s4;
 		phba->lpfc_scsi_prep_dma_buf = lpfc_scsi_prep_dma_buf_s4;
-		phba->lpfc_scsi_prep_cmnd = lpfc_scsi_prep_cmnd_s4;
-		phba->lpfc_scsi_unprep_dma_buf = lpfc_scsi_unprep_dma_buf_s4;
-		phba->lpfc_scsi_prep_task_mgmt_cmd =
-					lpfc_scsi_prep_task_mgmt_cmd_s4;
 		phba->lpfc_release_scsi_buf = lpfc_release_scsi_buf_s4;
 		break;
 	default:
@@ -2783,72 +2676,6 @@
 }
 
 /**
- * lpfc_scsi_tgt_reset - Target reset handler
- * @lpfc_cmd: Pointer to lpfc_scsi_buf data structure
- * @vport: The virtual port for which this call is being executed.
- * @tgt_id: Target ID.
- * @lun: Lun number.
- * @rdata: Pointer to lpfc_rport_data.
- *
- * This routine issues a TARGET RESET iocb to reset a target with @tgt_id ID.
- *
- * Return Code:
- *   0x2003 - Error
- *   0x2002 - Success.
- **/
-static int
-lpfc_scsi_tgt_reset(struct lpfc_scsi_buf *lpfc_cmd, struct lpfc_vport *vport,
-		    unsigned  tgt_id, unsigned int lun,
-		    struct lpfc_rport_data *rdata)
-{
-	struct lpfc_hba   *phba = vport->phba;
-	struct lpfc_iocbq *iocbq;
-	struct lpfc_iocbq *iocbqrsp;
-	int ret;
-	int status;
-
-	if (!rdata->pnode || !NLP_CHK_NODE_ACT(rdata->pnode))
-		return FAILED;
-
-	lpfc_cmd->rdata = rdata;
-	status = lpfc_scsi_prep_task_mgmt_cmd(vport, lpfc_cmd, lun,
-					   FCP_TARGET_RESET);
-	if (!status)
-		return FAILED;
-
-	iocbq = &lpfc_cmd->cur_iocbq;
-	iocbqrsp = lpfc_sli_get_iocbq(phba);
-
-	if (!iocbqrsp)
-		return FAILED;
-
-	/* Issue Target Reset to TGT <num> */
-	lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
-			 "0702 Issue Target Reset to TGT %d Data: x%x x%x\n",
-			 tgt_id, rdata->pnode->nlp_rpi, rdata->pnode->nlp_flag);
-	status = lpfc_sli_issue_iocb_wait(phba, LPFC_FCP_RING,
-					  iocbq, iocbqrsp, lpfc_cmd->timeout);
-	if (status != IOCB_SUCCESS) {
-		if (status == IOCB_TIMEDOUT) {
-			iocbq->iocb_cmpl = lpfc_tskmgmt_def_cmpl;
-			ret = TIMEOUT_ERROR;
-		} else
-			ret = FAILED;
-		lpfc_cmd->status = IOSTAT_DRIVER_REJECT;
-	} else {
-		ret = SUCCESS;
-		lpfc_cmd->result = iocbqrsp->iocb.un.ulpWord[4];
-		lpfc_cmd->status = iocbqrsp->iocb.ulpStatus;
-		if (lpfc_cmd->status == IOSTAT_LOCAL_REJECT &&
-			(lpfc_cmd->result & IOERR_DRVR_MASK))
-				lpfc_cmd->status = IOSTAT_DRIVER_REJECT;
-	}
-
-	lpfc_sli_release_iocbq(phba, iocbqrsp);
-	return ret;
-}
-
-/**
  * lpfc_info - Info entry point of scsi_host_template data structure
  * @host: The scsi host for which this call is being executed.
  *
@@ -3228,11 +3055,201 @@
 	return ret;
 }
 
+static char *
+lpfc_taskmgmt_name(uint8_t task_mgmt_cmd)
+{
+	switch (task_mgmt_cmd) {
+	case FCP_ABORT_TASK_SET:
+		return "ABORT_TASK_SET";
+	case FCP_CLEAR_TASK_SET:
+		return "FCP_CLEAR_TASK_SET";
+	case FCP_BUS_RESET:
+		return "FCP_BUS_RESET";
+	case FCP_LUN_RESET:
+		return "FCP_LUN_RESET";
+	case FCP_TARGET_RESET:
+		return "FCP_TARGET_RESET";
+	case FCP_CLEAR_ACA:
+		return "FCP_CLEAR_ACA";
+	case FCP_TERMINATE_TASK:
+		return "FCP_TERMINATE_TASK";
+	default:
+		return "unknown";
+	}
+}
+
+/**
+ * lpfc_send_taskmgmt - Generic SCSI Task Mgmt Handler
+ * @vport: The virtual port for which this call is being executed.
+ * @rdata: Pointer to remote port local data
+ * @tgt_id: Target ID of remote device.
+ * @lun_id: Lun number for the TMF
+ * @task_mgmt_cmd: type of TMF to send
+ *
+ * This routine builds and sends a TMF (SCSI Task Mgmt Function) to
+ * a remote port.
+ *
+ * Return Code:
+ *   0x2003 - Error
+ *   0x2002 - Success.
+ **/
+static int
+lpfc_send_taskmgmt(struct lpfc_vport *vport, struct lpfc_rport_data *rdata,
+		    unsigned  tgt_id, unsigned int lun_id,
+		    uint8_t task_mgmt_cmd)
+{
+	struct lpfc_hba   *phba = vport->phba;
+	struct lpfc_scsi_buf *lpfc_cmd;
+	struct lpfc_iocbq *iocbq;
+	struct lpfc_iocbq *iocbqrsp;
+	int ret;
+	int status;
+
+	if (!rdata->pnode || !NLP_CHK_NODE_ACT(rdata->pnode))
+		return FAILED;
+
+	lpfc_cmd = lpfc_get_scsi_buf(phba);
+	if (lpfc_cmd == NULL)
+		return FAILED;
+	lpfc_cmd->timeout = 60;
+	lpfc_cmd->rdata = rdata;
+
+	status = lpfc_scsi_prep_task_mgmt_cmd(vport, lpfc_cmd, lun_id,
+					   task_mgmt_cmd);
+	if (!status) {
+		lpfc_release_scsi_buf(phba, lpfc_cmd);
+		return FAILED;
+	}
+
+	iocbq = &lpfc_cmd->cur_iocbq;
+	iocbqrsp = lpfc_sli_get_iocbq(phba);
+	if (iocbqrsp == NULL) {
+		lpfc_release_scsi_buf(phba, lpfc_cmd);
+		return FAILED;
+	}
+
+	lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
+			 "0702 Issue %s to TGT %d LUN %d "
+			 "rpi x%x nlp_flag x%x\n",
+			 lpfc_taskmgmt_name(task_mgmt_cmd), tgt_id, lun_id,
+			 rdata->pnode->nlp_rpi, rdata->pnode->nlp_flag);
+
+	status = lpfc_sli_issue_iocb_wait(phba, LPFC_FCP_RING,
+					  iocbq, iocbqrsp, lpfc_cmd->timeout);
+	if (status != IOCB_SUCCESS) {
+		if (status == IOCB_TIMEDOUT) {
+			iocbq->iocb_cmpl = lpfc_tskmgmt_def_cmpl;
+			ret = TIMEOUT_ERROR;
+		} else
+			ret = FAILED;
+		lpfc_cmd->status = IOSTAT_DRIVER_REJECT;
+		lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
+			 "0727 TMF %s to TGT %d LUN %d failed (%d, %d)\n",
+			 lpfc_taskmgmt_name(task_mgmt_cmd),
+			 tgt_id, lun_id, iocbqrsp->iocb.ulpStatus,
+			 iocbqrsp->iocb.un.ulpWord[4]);
+	} else
+		ret = SUCCESS;
+
+	lpfc_sli_release_iocbq(phba, iocbqrsp);
+
+	if (ret != TIMEOUT_ERROR)
+		lpfc_release_scsi_buf(phba, lpfc_cmd);
+
+	return ret;
+}
+
+/**
+ * lpfc_chk_tgt_mapped -
+ * @vport: The virtual port to check on
+ * @cmnd: Pointer to scsi_cmnd data structure.
+ *
+ * This routine delays until the scsi target (aka rport) for the
+ * command exists (is present and logged in) or we declare it non-existent.
+ *
+ * Return code :
+ *  0x2003 - Error
+ *  0x2002 - Success
+ **/
+static int
+lpfc_chk_tgt_mapped(struct lpfc_vport *vport, struct scsi_cmnd *cmnd)
+{
+	struct lpfc_rport_data *rdata = cmnd->device->hostdata;
+	struct lpfc_nodelist *pnode = rdata->pnode;
+	unsigned long later;
+
+	/*
+	 * If target is not in a MAPPED state, delay until
+	 * target is rediscovered or devloss timeout expires.
+	 */
+	later = msecs_to_jiffies(2 * vport->cfg_devloss_tmo * 1000) + jiffies;
+	while (time_after(later, jiffies)) {
+		if (!pnode || !NLP_CHK_NODE_ACT(pnode))
+			return FAILED;
+		if (pnode->nlp_state == NLP_STE_MAPPED_NODE)
+			return SUCCESS;
+		schedule_timeout_uninterruptible(msecs_to_jiffies(500));
+		rdata = cmnd->device->hostdata;
+		if (!rdata)
+			return FAILED;
+		pnode = rdata->pnode;
+	}
+	if (!pnode || !NLP_CHK_NODE_ACT(pnode) ||
+	    (pnode->nlp_state != NLP_STE_MAPPED_NODE))
+		return FAILED;
+	return SUCCESS;
+}
+
+/**
+ * lpfc_reset_flush_io_context -
+ * @vport: The virtual port (scsi_host) for the flush context
+ * @tgt_id: If aborting by Target contect - specifies the target id
+ * @lun_id: If aborting by Lun context - specifies the lun id
+ * @context: specifies the context level to flush at.
+ *
+ * After a reset condition via TMF, we need to flush orphaned i/o
+ * contexts from the adapter. This routine aborts any contexts
+ * outstanding, then waits for their completions. The wait is
+ * bounded by devloss_tmo though.
+ *
+ * Return code :
+ *  0x2003 - Error
+ *  0x2002 - Success
+ **/
+static int
+lpfc_reset_flush_io_context(struct lpfc_vport *vport, uint16_t tgt_id,
+			uint64_t lun_id, lpfc_ctx_cmd context)
+{
+	struct lpfc_hba   *phba = vport->phba;
+	unsigned long later;
+	int cnt;
+
+	cnt = lpfc_sli_sum_iocb(vport, tgt_id, lun_id, context);
+	if (cnt)
+		lpfc_sli_abort_iocb(vport, &phba->sli.ring[phba->sli.fcp_ring],
+				    tgt_id, lun_id, context);
+	later = msecs_to_jiffies(2 * vport->cfg_devloss_tmo * 1000) + jiffies;
+	while (time_after(later, jiffies) && cnt) {
+		schedule_timeout_uninterruptible(msecs_to_jiffies(20));
+		cnt = lpfc_sli_sum_iocb(vport, tgt_id, lun_id, context);
+	}
+	if (cnt) {
+		lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
+			"0724 I/O flush failure for context %s : cnt x%x\n",
+			((context == LPFC_CTX_LUN) ? "LUN" :
+			 ((context == LPFC_CTX_TGT) ? "TGT" :
+			  ((context == LPFC_CTX_HOST) ? "HOST" : "Unknown"))),
+			cnt);
+		return FAILED;
+	}
+	return SUCCESS;
+}
+
 /**
  * lpfc_device_reset_handler - scsi_host_template eh_device_reset entry point
  * @cmnd: Pointer to scsi_cmnd data structure.
  *
- * This routine does a device reset by sending a TARGET_RESET task management
+ * This routine does a device reset by sending a LUN_RESET task management
  * command.
  *
  * Return code :
@@ -3244,33 +3261,79 @@
 {
 	struct Scsi_Host  *shost = cmnd->device->host;
 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
-	struct lpfc_hba   *phba = vport->phba;
-	struct lpfc_scsi_buf *lpfc_cmd;
-	struct lpfc_iocbq *iocbq, *iocbqrsp;
 	struct lpfc_rport_data *rdata = cmnd->device->hostdata;
 	struct lpfc_nodelist *pnode = rdata->pnode;
-	unsigned long later;
-	int ret = SUCCESS;
-	int status;
-	int cnt;
+	unsigned tgt_id = cmnd->device->id;
+	unsigned int lun_id = cmnd->device->lun;
 	struct lpfc_scsi_event_header scsi_event;
+	int status;
 
 	lpfc_block_error_handler(cmnd);
+
+	status = lpfc_chk_tgt_mapped(vport, cmnd);
+	if (status == FAILED) {
+		lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
+			"0721 Device Reset rport failure: rdata x%p\n", rdata);
+		return FAILED;
+	}
+
+	scsi_event.event_type = FC_REG_SCSI_EVENT;
+	scsi_event.subcategory = LPFC_EVENT_LUNRESET;
+	scsi_event.lun = lun_id;
+	memcpy(scsi_event.wwpn, &pnode->nlp_portname, sizeof(struct lpfc_name));
+	memcpy(scsi_event.wwnn, &pnode->nlp_nodename, sizeof(struct lpfc_name));
+
+	fc_host_post_vendor_event(shost, fc_get_event_number(),
+		sizeof(scsi_event), (char *)&scsi_event, LPFC_NL_VENDOR_ID);
+
+	status = lpfc_send_taskmgmt(vport, rdata, tgt_id, lun_id,
+						FCP_LUN_RESET);
+
+	lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
+			 "0713 SCSI layer issued Device Reset (%d, %d) "
+			 "return x%x\n", tgt_id, lun_id, status);
+
 	/*
-	 * If target is not in a MAPPED state, delay the reset until
-	 * target is rediscovered or devloss timeout expires.
+	 * We have to clean up i/o as : they may be orphaned by the TMF;
+	 * or if the TMF failed, they may be in an indeterminate state.
+	 * So, continue on.
+	 * We will report success if all the i/o aborts successfully.
 	 */
-	later = msecs_to_jiffies(2 * vport->cfg_devloss_tmo * 1000) + jiffies;
-	while (time_after(later, jiffies)) {
-		if (!pnode || !NLP_CHK_NODE_ACT(pnode))
-			return FAILED;
-		if (pnode->nlp_state == NLP_STE_MAPPED_NODE)
-			break;
-		schedule_timeout_uninterruptible(msecs_to_jiffies(500));
-		rdata = cmnd->device->hostdata;
-		if (!rdata)
-			break;
-		pnode = rdata->pnode;
+	status = lpfc_reset_flush_io_context(vport, tgt_id, lun_id,
+						LPFC_CTX_LUN);
+	return status;
+}
+
+/**
+ * lpfc_target_reset_handler - scsi_host_template eh_target_reset entry point
+ * @cmnd: Pointer to scsi_cmnd data structure.
+ *
+ * This routine does a target reset by sending a TARGET_RESET task management
+ * command.
+ *
+ * Return code :
+ *  0x2003 - Error
+ *  0x2002 - Success
+ **/
+static int
+lpfc_target_reset_handler(struct scsi_cmnd *cmnd)
+{
+	struct Scsi_Host  *shost = cmnd->device->host;
+	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
+	struct lpfc_rport_data *rdata = cmnd->device->hostdata;
+	struct lpfc_nodelist *pnode = rdata->pnode;
+	unsigned tgt_id = cmnd->device->id;
+	unsigned int lun_id = cmnd->device->lun;
+	struct lpfc_scsi_event_header scsi_event;
+	int status;
+
+	lpfc_block_error_handler(cmnd);
+
+	status = lpfc_chk_tgt_mapped(vport, cmnd);
+	if (status == FAILED) {
+		lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
+			"0722 Target Reset rport failure: rdata x%p\n", rdata);
+		return FAILED;
 	}
 
 	scsi_event.event_type = FC_REG_SCSI_EVENT;
@@ -3279,105 +3342,47 @@
 	memcpy(scsi_event.wwpn, &pnode->nlp_portname, sizeof(struct lpfc_name));
 	memcpy(scsi_event.wwnn, &pnode->nlp_nodename, sizeof(struct lpfc_name));
 
-	fc_host_post_vendor_event(shost,
-		fc_get_event_number(),
-		sizeof(scsi_event),
-		(char *)&scsi_event,
-		LPFC_NL_VENDOR_ID);
+	fc_host_post_vendor_event(shost, fc_get_event_number(),
+		sizeof(scsi_event), (char *)&scsi_event, LPFC_NL_VENDOR_ID);
 
-	if (!rdata || pnode->nlp_state != NLP_STE_MAPPED_NODE) {
-		lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
-				 "0721 LUN Reset rport "
-				 "failure: msec x%x rdata x%p\n",
-				 jiffies_to_msecs(jiffies - later), rdata);
-		return FAILED;
-	}
-	lpfc_cmd = lpfc_get_scsi_buf(phba);
-	if (lpfc_cmd == NULL)
-		return FAILED;
-	lpfc_cmd->timeout = 60;
-	lpfc_cmd->rdata = rdata;
+	status = lpfc_send_taskmgmt(vport, rdata, tgt_id, lun_id,
+					FCP_TARGET_RESET);
 
-	status = lpfc_scsi_prep_task_mgmt_cmd(vport, lpfc_cmd,
-					      cmnd->device->lun,
-					      FCP_TARGET_RESET);
-	if (!status) {
-		lpfc_release_scsi_buf(phba, lpfc_cmd);
-		return FAILED;
-	}
-	iocbq = &lpfc_cmd->cur_iocbq;
-
-	/* get a buffer for this IOCB command response */
-	iocbqrsp = lpfc_sli_get_iocbq(phba);
-	if (iocbqrsp == NULL) {
-		lpfc_release_scsi_buf(phba, lpfc_cmd);
-		return FAILED;
-	}
-	lpfc_printf_vlog(vport, KERN_INFO, LOG_FCP,
-			 "0703 Issue target reset to TGT %d LUN %d "
-			 "rpi x%x nlp_flag x%x\n", cmnd->device->id,
-			 cmnd->device->lun, pnode->nlp_rpi, pnode->nlp_flag);
-	status = lpfc_sli_issue_iocb_wait(phba, LPFC_FCP_RING,
-					  iocbq, iocbqrsp, lpfc_cmd->timeout);
-	if (status == IOCB_TIMEDOUT) {
-		iocbq->iocb_cmpl = lpfc_tskmgmt_def_cmpl;
-		ret = TIMEOUT_ERROR;
-	} else {
-		if (status != IOCB_SUCCESS)
-			ret = FAILED;
-		lpfc_release_scsi_buf(phba, lpfc_cmd);
-	}
 	lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
-			 "0713 SCSI layer issued device reset (%d, %d) "
-			 "return x%x status x%x result x%x\n",
-			 cmnd->device->id, cmnd->device->lun, ret,
-			 iocbqrsp->iocb.ulpStatus,
-			 iocbqrsp->iocb.un.ulpWord[4]);
-	lpfc_sli_release_iocbq(phba, iocbqrsp);
-	cnt = lpfc_sli_sum_iocb(vport, cmnd->device->id, cmnd->device->lun,
-				LPFC_CTX_TGT);
-	if (cnt)
-		lpfc_sli_abort_iocb(vport, &phba->sli.ring[phba->sli.fcp_ring],
-				    cmnd->device->id, cmnd->device->lun,
-				    LPFC_CTX_TGT);
-	later = msecs_to_jiffies(2 * vport->cfg_devloss_tmo * 1000) + jiffies;
-	while (time_after(later, jiffies) && cnt) {
-		schedule_timeout_uninterruptible(msecs_to_jiffies(20));
-		cnt = lpfc_sli_sum_iocb(vport, cmnd->device->id,
-					cmnd->device->lun, LPFC_CTX_TGT);
-	}
-	if (cnt) {
-		lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
-				 "0719 device reset I/O flush failure: "
-				 "cnt x%x\n", cnt);
-		ret = FAILED;
-	}
-	return ret;
+			 "0723 SCSI layer issued Target Reset (%d, %d) "
+			 "return x%x\n", tgt_id, lun_id, status);
+
+	/*
+	 * We have to clean up i/o as : they may be orphaned by the TMF;
+	 * or if the TMF failed, they may be in an indeterminate state.
+	 * So, continue on.
+	 * We will report success if all the i/o aborts successfully.
+	 */
+	status = lpfc_reset_flush_io_context(vport, tgt_id, lun_id,
+					LPFC_CTX_TGT);
+	return status;
 }
 
 /**
  * lpfc_bus_reset_handler - scsi_host_template eh_bus_reset_handler entry point
  * @cmnd: Pointer to scsi_cmnd data structure.
  *
- * This routine does target reset to all target on @cmnd->device->host.
+ * This routine does target reset to all targets on @cmnd->device->host.
+ * This emulates Parallel SCSI Bus Reset Semantics.
  *
- * Return Code:
- *   0x2003 - Error
- *   0x2002 - Success
+ * Return code :
+ *  0x2003 - Error
+ *  0x2002 - Success
  **/
 static int
 lpfc_bus_reset_handler(struct scsi_cmnd *cmnd)
 {
 	struct Scsi_Host  *shost = cmnd->device->host;
 	struct lpfc_vport *vport = (struct lpfc_vport *) shost->hostdata;
-	struct lpfc_hba   *phba = vport->phba;
 	struct lpfc_nodelist *ndlp = NULL;
-	int match;
-	int ret = SUCCESS, status = SUCCESS, i;
-	int cnt;
-	struct lpfc_scsi_buf * lpfc_cmd;
-	unsigned long later;
 	struct lpfc_scsi_event_header scsi_event;
+	int match;
+	int ret = SUCCESS, status, i;
 
 	scsi_event.event_type = FC_REG_SCSI_EVENT;
 	scsi_event.subcategory = LPFC_EVENT_BUSRESET;
@@ -3385,13 +3390,11 @@
 	memcpy(scsi_event.wwpn, &vport->fc_portname, sizeof(struct lpfc_name));
 	memcpy(scsi_event.wwnn, &vport->fc_nodename, sizeof(struct lpfc_name));
 
-	fc_host_post_vendor_event(shost,
-		fc_get_event_number(),
-		sizeof(scsi_event),
-		(char *)&scsi_event,
-		LPFC_NL_VENDOR_ID);
+	fc_host_post_vendor_event(shost, fc_get_event_number(),
+		sizeof(scsi_event), (char *)&scsi_event, LPFC_NL_VENDOR_ID);
 
 	lpfc_block_error_handler(cmnd);
+
 	/*
 	 * Since the driver manages a single bus device, reset all
 	 * targets known to the driver.  Should any target reset
@@ -3414,16 +3417,11 @@
 		spin_unlock_irq(shost->host_lock);
 		if (!match)
 			continue;
-		lpfc_cmd = lpfc_get_scsi_buf(phba);
-		if (lpfc_cmd) {
-			lpfc_cmd->timeout = 60;
-			status = lpfc_scsi_tgt_reset(lpfc_cmd, vport, i,
-						     cmnd->device->lun,
-						     ndlp->rport->dd_data);
-			if (status != TIMEOUT_ERROR)
-				lpfc_release_scsi_buf(phba, lpfc_cmd);
-		}
-		if (!lpfc_cmd || status != SUCCESS) {
+
+		status = lpfc_send_taskmgmt(vport, ndlp->rport->dd_data,
+					i, 0, FCP_TARGET_RESET);
+
+		if (status != SUCCESS) {
 			lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
 					 "0700 Bus Reset on target %d failed\n",
 					 i);
@@ -3431,25 +3429,16 @@
 		}
 	}
 	/*
-	 * All outstanding txcmplq I/Os should have been aborted by
-	 * the targets.  Unfortunately, some targets do not abide by
-	 * this forcing the driver to double check.
+	 * We have to clean up i/o as : they may be orphaned by the TMFs
+	 * above; or if any of the TMFs failed, they may be in an
+	 * indeterminate state.
+	 * We will report success if all the i/o aborts successfully.
 	 */
-	cnt = lpfc_sli_sum_iocb(vport, 0, 0, LPFC_CTX_HOST);
-	if (cnt)
-		lpfc_sli_abort_iocb(vport, &phba->sli.ring[phba->sli.fcp_ring],
-				    0, 0, LPFC_CTX_HOST);
-	later = msecs_to_jiffies(2 * vport->cfg_devloss_tmo * 1000) + jiffies;
-	while (time_after(later, jiffies) && cnt) {
-		schedule_timeout_uninterruptible(msecs_to_jiffies(20));
-		cnt = lpfc_sli_sum_iocb(vport, 0, 0, LPFC_CTX_HOST);
-	}
-	if (cnt) {
-		lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
-				 "0715 Bus Reset I/O flush failure: "
-				 "cnt x%x left x%x\n", cnt, i);
+
+	status = lpfc_reset_flush_io_context(vport, 0, 0, LPFC_CTX_HOST);
+	if (status != SUCCESS)
 		ret = FAILED;
-	}
+
 	lpfc_printf_vlog(vport, KERN_ERR, LOG_FCP,
 			 "0714 SCSI layer issued Bus Reset Data: x%x\n", ret);
 	return ret;
@@ -3582,7 +3571,8 @@
 	.info			= lpfc_info,
 	.queuecommand		= lpfc_queuecommand,
 	.eh_abort_handler	= lpfc_abort_handler,
-	.eh_device_reset_handler= lpfc_device_reset_handler,
+	.eh_device_reset_handler = lpfc_device_reset_handler,
+	.eh_target_reset_handler = lpfc_target_reset_handler,
 	.eh_bus_reset_handler	= lpfc_bus_reset_handler,
 	.slave_alloc		= lpfc_slave_alloc,
 	.slave_configure	= lpfc_slave_configure,
@@ -3602,7 +3592,8 @@
 	.info			= lpfc_info,
 	.queuecommand		= lpfc_queuecommand,
 	.eh_abort_handler	= lpfc_abort_handler,
-	.eh_device_reset_handler= lpfc_device_reset_handler,
+	.eh_device_reset_handler = lpfc_device_reset_handler,
+	.eh_target_reset_handler = lpfc_target_reset_handler,
 	.eh_bus_reset_handler	= lpfc_bus_reset_handler,
 	.slave_alloc		= lpfc_slave_alloc,
 	.slave_configure	= lpfc_slave_configure,
diff --git a/drivers/scsi/lpfc/lpfc_sli.c b/drivers/scsi/lpfc/lpfc_sli.c
index ff04daf..acc43b0 100644
--- a/drivers/scsi/lpfc/lpfc_sli.c
+++ b/drivers/scsi/lpfc/lpfc_sli.c
@@ -4139,8 +4139,11 @@
 		return -EIO;
 	}
 	data_length = mqe->un.mb_words[5];
-	if (data_length > DMP_FCOEPARAM_RGN_SIZE)
+	if (data_length > DMP_FCOEPARAM_RGN_SIZE) {
+		lpfc_mbuf_free(phba, mp->virt, mp->phys);
+		kfree(mp);
 		return -EIO;
+	}
 
 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
@@ -4211,27 +4214,6 @@
 		return -EIO;
 	}
 
-	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
-			"(%d):0380 Mailbox cmd x%x Status x%x "
-			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
-			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
-			"CQ: x%x x%x x%x x%x\n",
-			mboxq->vport ? mboxq->vport->vpi : 0,
-			bf_get(lpfc_mqe_command, mqe),
-			bf_get(lpfc_mqe_status, mqe),
-			mqe->un.mb_words[0], mqe->un.mb_words[1],
-			mqe->un.mb_words[2], mqe->un.mb_words[3],
-			mqe->un.mb_words[4], mqe->un.mb_words[5],
-			mqe->un.mb_words[6], mqe->un.mb_words[7],
-			mqe->un.mb_words[8], mqe->un.mb_words[9],
-			mqe->un.mb_words[10], mqe->un.mb_words[11],
-			mqe->un.mb_words[12], mqe->un.mb_words[13],
-			mqe->un.mb_words[14], mqe->un.mb_words[15],
-			mqe->un.mb_words[16], mqe->un.mb_words[50],
-			mboxq->mcqe.word0,
-			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
-			mboxq->mcqe.trailer);
-
 	/*
 	 * The available vpd length cannot be bigger than the
 	 * DMA buffer passed to the port.  Catch the less than
@@ -4337,21 +4319,18 @@
 		goto out_free_vpd;
 
 	mqe = &mboxq->u.mqe;
-	if ((bf_get(lpfc_mbx_rd_rev_sli_lvl,
-		    &mqe->un.read_rev) != LPFC_SLI_REV4) ||
-	    (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev) == 0)) {
+	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
+	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev))
+		phba->hba_flag |= HBA_FCOE_SUPPORT;
+	if (phba->sli_rev != LPFC_SLI_REV4 ||
+	    !(phba->hba_flag & HBA_FCOE_SUPPORT)) {
 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
 			"0376 READ_REV Error. SLI Level %d "
 			"FCoE enabled %d\n",
-			bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev),
-			bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev));
+			phba->sli_rev, phba->hba_flag & HBA_FCOE_SUPPORT);
 		rc = -EIO;
 		goto out_free_vpd;
 	}
-	/* Single threaded at this point, no need for lock */
-	spin_lock_irq(&phba->hbalock);
-	phba->hba_flag |= HBA_FCOE_SUPPORT;
-	spin_unlock_irq(&phba->hbalock);
 	/*
 	 * Evaluate the read rev and vpd data. Populate the driver
 	 * state with the results. If this routine fails, the failure
@@ -4365,8 +4344,32 @@
 		rc = 0;
 	}
 
-	/* By now, we should determine the SLI revision, hard code for now */
-	phba->sli_rev = LPFC_SLI_REV4;
+	/* Save information as VPD data */
+	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
+	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
+	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
+	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
+					 &mqe->un.read_rev);
+	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
+				       &mqe->un.read_rev);
+	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
+					    &mqe->un.read_rev);
+	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
+					   &mqe->un.read_rev);
+	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
+	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
+	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
+	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
+	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
+	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
+	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
+			"(%d):0380 READ_REV Status x%x "
+			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
+			mboxq->vport ? mboxq->vport->vpi : 0,
+			bf_get(lpfc_mqe_status, mqe),
+			phba->vpd.rev.opFwName,
+			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
+			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
 
 	/*
 	 * Discover the port's supported feature set and match it against the
@@ -4491,8 +4494,10 @@
 		rc = -ENODEV;
 		goto out_free_vpd;
 	}
-	/* Temporary initialization of lpfc_fip_flag to non-fip */
-	bf_set(lpfc_fip_flag, &phba->sli4_hba.sli4_flags, 0);
+	if (phba->cfg_enable_fip)
+		bf_set(lpfc_fip_flag, &phba->sli4_hba.sli4_flags, 1);
+	else
+		bf_set(lpfc_fip_flag, &phba->sli4_hba.sli4_flags, 0);
 
 	/* Set up all the queues to the device */
 	rc = lpfc_sli4_queue_setup(phba);
@@ -5030,6 +5035,92 @@
 }
 
 /**
+ * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
+ * @phba: Pointer to HBA context object.
+ *
+ * The function blocks the posting of SLI4 asynchronous mailbox commands from
+ * the driver internal pending mailbox queue. It will then try to wait out the
+ * possible outstanding mailbox command before return.
+ *
+ * Returns:
+ * 	0 - the outstanding mailbox command completed; otherwise, the wait for
+ * 	the outstanding mailbox command timed out.
+ **/
+static int
+lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
+{
+	struct lpfc_sli *psli = &phba->sli;
+	uint8_t actcmd = MBX_HEARTBEAT;
+	int rc = 0;
+	unsigned long timeout;
+
+	/* Mark the asynchronous mailbox command posting as blocked */
+	spin_lock_irq(&phba->hbalock);
+	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
+	if (phba->sli.mbox_active)
+		actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
+	spin_unlock_irq(&phba->hbalock);
+	/* Determine how long we might wait for the active mailbox
+	 * command to be gracefully completed by firmware.
+	 */
+	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, actcmd) * 1000) +
+				   jiffies;
+	/* Wait for the outstnading mailbox command to complete */
+	while (phba->sli.mbox_active) {
+		/* Check active mailbox complete status every 2ms */
+		msleep(2);
+		if (time_after(jiffies, timeout)) {
+			/* Timeout, marked the outstanding cmd not complete */
+			rc = 1;
+			break;
+		}
+	}
+
+	/* Can not cleanly block async mailbox command, fails it */
+	if (rc) {
+		spin_lock_irq(&phba->hbalock);
+		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
+		spin_unlock_irq(&phba->hbalock);
+	}
+	return rc;
+}
+
+/**
+ * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
+ * @phba: Pointer to HBA context object.
+ *
+ * The function unblocks and resume posting of SLI4 asynchronous mailbox
+ * commands from the driver internal pending mailbox queue. It makes sure
+ * that there is no outstanding mailbox command before resuming posting
+ * asynchronous mailbox commands. If, for any reason, there is outstanding
+ * mailbox command, it will try to wait it out before resuming asynchronous
+ * mailbox command posting.
+ **/
+static void
+lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
+{
+	struct lpfc_sli *psli = &phba->sli;
+
+	spin_lock_irq(&phba->hbalock);
+	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
+		/* Asynchronous mailbox posting is not blocked, do nothing */
+		spin_unlock_irq(&phba->hbalock);
+		return;
+	}
+
+	/* Outstanding synchronous mailbox command is guaranteed to be done,
+	 * successful or timeout, after timing-out the outstanding mailbox
+	 * command shall always be removed, so just unblock posting async
+	 * mailbox command and resume
+	 */
+	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
+	spin_unlock_irq(&phba->hbalock);
+
+	/* wake up worker thread to post asynchronlous mailbox command */
+	lpfc_worker_wake_up(phba);
+}
+
+/**
  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
  * @phba: Pointer to HBA context object.
  * @mboxq: Pointer to mailbox object.
@@ -5204,14 +5295,35 @@
 					psli->sli_flag, flag);
 		return rc;
 	} else if (flag == MBX_POLL) {
-		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
-				"(%d):2542 Mailbox command x%x (x%x) "
-				"cannot issue Data: x%x x%x\n",
+		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
+				"(%d):2542 Try to issue mailbox command "
+				"x%x (x%x) synchronously ahead of async"
+				"mailbox command queue: x%x x%x\n",
 				mboxq->vport ? mboxq->vport->vpi : 0,
 				mboxq->u.mb.mbxCommand,
 				lpfc_sli4_mbox_opcode_get(phba, mboxq),
 				psli->sli_flag, flag);
-		return -EIO;
+		/* Try to block the asynchronous mailbox posting */
+		rc = lpfc_sli4_async_mbox_block(phba);
+		if (!rc) {
+			/* Successfully blocked, now issue sync mbox cmd */
+			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
+			if (rc != MBX_SUCCESS)
+				lpfc_printf_log(phba, KERN_ERR,
+						LOG_MBOX | LOG_SLI,
+						"(%d):2597 Mailbox command "
+						"x%x (x%x) cannot issue "
+						"Data: x%x x%x\n",
+						mboxq->vport ?
+						mboxq->vport->vpi : 0,
+						mboxq->u.mb.mbxCommand,
+						lpfc_sli4_mbox_opcode_get(phba,
+								mboxq),
+						psli->sli_flag, flag);
+			/* Unblock the async mailbox posting afterward */
+			lpfc_sli4_async_mbox_unblock(phba);
+		}
+		return rc;
 	}
 
 	/* Now, interrupt mode asynchrous mailbox command */
@@ -5749,18 +5861,13 @@
 
 	fip = bf_get(lpfc_fip_flag, &phba->sli4_hba.sli4_flags);
 	/* The fcp commands will set command type */
-	if ((!(iocbq->iocb_flag &  LPFC_IO_FCP)) && (!fip))
-		command_type = ELS_COMMAND_NON_FIP;
-	else if (!(iocbq->iocb_flag &  LPFC_IO_FCP))
-		command_type = ELS_COMMAND_FIP;
-	else if (iocbq->iocb_flag &  LPFC_IO_FCP)
+	if (iocbq->iocb_flag &  LPFC_IO_FCP)
 		command_type = FCP_COMMAND;
-	else {
-		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
-			"2019 Invalid cmd 0x%x\n",
-			iocbq->iocb.ulpCommand);
-		return IOCB_ERROR;
-	}
+	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS))
+		command_type = ELS_COMMAND_FIP;
+	else
+		command_type = ELS_COMMAND_NON_FIP;
+
 	/* Some of the fields are in the right position already */
 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
 	abort_tag = (uint32_t) iocbq->iotag;
@@ -5814,11 +5921,6 @@
 		bf_set(lpfc_wqe_gen_context, &wqe->generic,
 				iocbq->iocb.ulpContext);
 
-		if (iocbq->vport->fc_myDID != 0) {
-			bf_set(els_req64_sid, &wqe->els_req,
-				 iocbq->vport->fc_myDID);
-			bf_set(els_req64_sp, &wqe->els_req, 1);
-		}
 		bf_set(lpfc_wqe_gen_ct, &wqe->generic, ct);
 		bf_set(lpfc_wqe_gen_pu, &wqe->generic, 0);
 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
@@ -5877,14 +5979,19 @@
 		 * is set and we are sending our 2nd or greater command on
 		 * this exchange.
 		 */
-
-	/* ALLOW read & write to fall through to ICMD64 */
-	case CMD_FCP_ICMND64_CR:
 		/* Always open the exchange */
 		bf_set(wqe_xc, &wqe->fcp_iread.wqe_com, 0);
 
 		wqe->words[10] &= 0xffff0000; /* zero out ebde count */
 		bf_set(lpfc_wqe_gen_pu, &wqe->generic, iocbq->iocb.ulpPU);
+		break;
+	case CMD_FCP_ICMND64_CR:
+		/* Always open the exchange */
+		bf_set(wqe_xc, &wqe->fcp_iread.wqe_com, 0);
+
+		wqe->words[4] = 0;
+		wqe->words[10] &= 0xffff0000; /* zero out ebde count */
+		bf_set(lpfc_wqe_gen_pu, &wqe->generic, 0);
 	break;
 	case CMD_GEN_REQUEST64_CR:
 		/* word3 command length is described as byte offset to the
@@ -7247,6 +7354,32 @@
 }
 
 /**
+ * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
+ * @phba: Pointer to HBA context object..
+ * @piocbq: Pointer to command iocb.
+ * @flag: Flag to test.
+ *
+ * This routine grabs the hbalock and then test the iocb_flag to
+ * see if the passed in flag is set.
+ * Returns:
+ * 1 if flag is set.
+ * 0 if flag is not set.
+ **/
+static int
+lpfc_chk_iocb_flg(struct lpfc_hba *phba,
+		 struct lpfc_iocbq *piocbq, uint32_t flag)
+{
+	unsigned long iflags;
+	int ret;
+
+	spin_lock_irqsave(&phba->hbalock, iflags);
+	ret = piocbq->iocb_flag & flag;
+	spin_unlock_irqrestore(&phba->hbalock, iflags);
+	return ret;
+
+}
+
+/**
  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
  * @phba: Pointer to HBA context object..
  * @pring: Pointer to sli ring.
@@ -7313,7 +7446,7 @@
 	if (retval == IOCB_SUCCESS) {
 		timeout_req = timeout * HZ;
 		timeleft = wait_event_timeout(done_q,
-				piocb->iocb_flag & LPFC_IO_WAKE,
+				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
 				timeout_req);
 
 		if (piocb->iocb_flag & LPFC_IO_WAKE) {
@@ -7498,20 +7631,16 @@
 		if ((HS_FFER1 & phba->work_hs) &&
 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
 		     HS_FFER6 | HS_FFER7) & phba->work_hs)) {
-			spin_lock_irq(&phba->hbalock);
 			phba->hba_flag |= DEFER_ERATT;
-			spin_unlock_irq(&phba->hbalock);
 			/* Clear all interrupt enable conditions */
 			writel(0, phba->HCregaddr);
 			readl(phba->HCregaddr);
 		}
 
 		/* Set the driver HA work bitmap */
-		spin_lock_irq(&phba->hbalock);
 		phba->work_ha |= HA_ERATT;
 		/* Indicate polling handles this ERATT */
 		phba->hba_flag |= HBA_ERATT_HANDLED;
-		spin_unlock_irq(&phba->hbalock);
 		return 1;
 	}
 	return 0;
@@ -7557,12 +7686,10 @@
 			return 0;
 			phba->work_status[0] = uerr_sta_lo;
 			phba->work_status[1] = uerr_sta_hi;
-			spin_lock_irq(&phba->hbalock);
 			/* Set the driver HA work bitmap */
 			phba->work_ha |= HA_ERATT;
 			/* Indicate polling handles this ERATT */
 			phba->hba_flag |= HBA_ERATT_HANDLED;
-			spin_unlock_irq(&phba->hbalock);
 			return 1;
 		}
 	}
@@ -9245,6 +9372,7 @@
 			kfree(dmabuf);
 			goto out_fail;
 		}
+		memset(dmabuf->virt, 0, PAGE_SIZE);
 		dmabuf->buffer_tag = x;
 		list_add_tail(&dmabuf->list, &queue->page_list);
 		/* initialize queue's entry array */
@@ -9667,7 +9795,7 @@
 	/* link the wq onto the parent cq child list */
 	list_add_tail(&wq->list, &cq->child_list);
 out:
-	if (rc == MBX_TIMEOUT)
+	if (rc != MBX_TIMEOUT)
 		mempool_free(mbox, phba->mbox_mem_pool);
 	return status;
 }
@@ -11020,10 +11148,7 @@
 	       rpi_page->start_rpi);
 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
-	if (!phba->sli4_hba.intr_enable)
-		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
-	else
-		rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
+	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
@@ -11363,6 +11488,7 @@
 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
+	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
diff --git a/drivers/scsi/lpfc/lpfc_sli.h b/drivers/scsi/lpfc/lpfc_sli.h
index 7d37eb7..3c53316 100644
--- a/drivers/scsi/lpfc/lpfc_sli.h
+++ b/drivers/scsi/lpfc/lpfc_sli.h
@@ -56,6 +56,7 @@
 #define LPFC_DRIVER_ABORTED	8	/* driver aborted this request */
 #define LPFC_IO_FABRIC		0x10	/* Iocb send using fabric scheduler */
 #define LPFC_DELAY_MEM_FREE	0x20    /* Defer free'ing of FC data */
+#define LPFC_FIP_ELS		0x40
 
 	uint8_t abort_count;
 	uint8_t rsvd2;
diff --git a/drivers/scsi/lpfc/lpfc_sli4.h b/drivers/scsi/lpfc/lpfc_sli4.h
index 5196b466..3b276b4 100644
--- a/drivers/scsi/lpfc/lpfc_sli4.h
+++ b/drivers/scsi/lpfc/lpfc_sli4.h
@@ -229,7 +229,7 @@
 
 #define LPFC_EQE_DEF_COUNT	1024
 #define LPFC_CQE_DEF_COUNT      256
-#define LPFC_WQE_DEF_COUNT      64
+#define LPFC_WQE_DEF_COUNT      256
 #define LPFC_MQE_DEF_COUNT      16
 #define LPFC_RQE_DEF_COUNT	512
 
diff --git a/drivers/scsi/lpfc/lpfc_version.h b/drivers/scsi/lpfc/lpfc_version.h
index 6b8a148..41094e0 100644
--- a/drivers/scsi/lpfc/lpfc_version.h
+++ b/drivers/scsi/lpfc/lpfc_version.h
@@ -18,7 +18,7 @@
  * included with this package.                                     *
  *******************************************************************/
 
-#define LPFC_DRIVER_VERSION "8.3.2"
+#define LPFC_DRIVER_VERSION "8.3.3"
 
 #define LPFC_DRIVER_NAME		"lpfc"
 #define LPFC_SP_DRIVER_HANDLER_NAME	"lpfc:sp"
diff --git a/drivers/scsi/lpfc/lpfc_vport.c b/drivers/scsi/lpfc/lpfc_vport.c
index a6313ee..e0b4992 100644
--- a/drivers/scsi/lpfc/lpfc_vport.c
+++ b/drivers/scsi/lpfc/lpfc_vport.c
@@ -695,8 +695,6 @@
 		}
 		vport->unreg_vpi_cmpl = VPORT_INVAL;
 		timeout = msecs_to_jiffies(phba->fc_ratov * 2000);
-		if (ndlp->nlp_state == NLP_STE_UNUSED_NODE)
-			goto skip_logo;
 		if (!lpfc_issue_els_npiv_logo(vport, ndlp))
 			while (vport->unreg_vpi_cmpl == VPORT_INVAL && timeout)
 				timeout = schedule_timeout(timeout);
diff --git a/drivers/scsi/ncr53c8xx.c b/drivers/scsi/ncr53c8xx.c
index 3b7240e..e3c482a 100644
--- a/drivers/scsi/ncr53c8xx.c
+++ b/drivers/scsi/ncr53c8xx.c
@@ -5444,7 +5444,7 @@
 	**	input speed faster than the period.
 	*/
 	kpc = per * clk;
-	while (--div >= 0)
+	while (--div > 0)
 		if (kpc >= (div_10M[div] << 2)) break;
 
 	/*
diff --git a/drivers/scsi/pcmcia/nsp_cs.c b/drivers/scsi/pcmcia/nsp_cs.c
index 11a61ea..70b60ad 100644
--- a/drivers/scsi/pcmcia/nsp_cs.c
+++ b/drivers/scsi/pcmcia/nsp_cs.c
@@ -530,7 +530,7 @@
 		if (reg == 0xff) {
 			break;
 		}
-	} while ((time_out-- != 0) && (reg & mask) != 0);
+	} while ((--time_out != 0) && (reg & mask) != 0);
 
 	if (time_out == 0) {
 		nsp_msg(KERN_DEBUG, " %s signal off timeut", str);
@@ -801,7 +801,7 @@
 
 	data->FifoCount = ocount;
 
-	if (time_out == 0) {
+	if (time_out < 0) {
 		nsp_msg(KERN_DEBUG, "pio read timeout resid=%d this_residual=%d buffers_residual=%d",
 			scsi_get_resid(SCpnt), SCpnt->SCp.this_residual,
 			SCpnt->SCp.buffers_residual);
@@ -897,7 +897,7 @@
 
 	data->FifoCount = ocount;
 
-	if (time_out == 0) {
+	if (time_out < 0) {
 		nsp_msg(KERN_DEBUG, "pio write timeout resid=0x%x",
 		                                        scsi_get_resid(SCpnt));
 	}
diff --git a/drivers/scsi/ps3rom.c b/drivers/scsi/ps3rom.c
index ca0dd33..db90caf 100644
--- a/drivers/scsi/ps3rom.c
+++ b/drivers/scsi/ps3rom.c
@@ -299,7 +299,7 @@
 		return IRQ_HANDLED;
 	}
 
-	host = dev->sbd.core.driver_data;
+	host = ps3_system_bus_get_drvdata(&dev->sbd);
 	priv = shost_priv(host);
 	cmd = priv->curr_cmd;
 
@@ -387,7 +387,7 @@
 	}
 
 	priv = shost_priv(host);
-	dev->sbd.core.driver_data = host;
+	ps3_system_bus_set_drvdata(&dev->sbd, host);
 	priv->dev = dev;
 
 	/* One device/LUN per SCSI bus */
@@ -407,7 +407,7 @@
 
 fail_host_put:
 	scsi_host_put(host);
-	dev->sbd.core.driver_data = NULL;
+	ps3_system_bus_set_drvdata(&dev->sbd, NULL);
 fail_teardown:
 	ps3stor_teardown(dev);
 fail_free_bounce:
@@ -418,12 +418,12 @@
 static int ps3rom_remove(struct ps3_system_bus_device *_dev)
 {
 	struct ps3_storage_device *dev = to_ps3_storage_device(&_dev->core);
-	struct Scsi_Host *host = dev->sbd.core.driver_data;
+	struct Scsi_Host *host = ps3_system_bus_get_drvdata(&dev->sbd);
 
 	scsi_remove_host(host);
 	ps3stor_teardown(dev);
 	scsi_host_put(host);
-	dev->sbd.core.driver_data = NULL;
+	ps3_system_bus_set_drvdata(&dev->sbd, NULL);
 	kfree(dev->bounce_buf);
 	return 0;
 }
diff --git a/drivers/scsi/qla2xxx/qla_isr.c b/drivers/scsi/qla2xxx/qla_isr.c
index c8d0a17..245e7af 100644
--- a/drivers/scsi/qla2xxx/qla_isr.c
+++ b/drivers/scsi/qla2xxx/qla_isr.c
@@ -37,6 +37,7 @@
 	uint16_t	hccr;
 	uint16_t	mb[4];
 	struct rsp_que *rsp;
+	unsigned long	flags;
 
 	rsp = (struct rsp_que *) dev_id;
 	if (!rsp) {
@@ -49,7 +50,7 @@
 	reg = &ha->iobase->isp;
 	status = 0;
 
-	spin_lock(&ha->hardware_lock);
+	spin_lock_irqsave(&ha->hardware_lock, flags);
 	vha = pci_get_drvdata(ha->pdev);
 	for (iter = 50; iter--; ) {
 		hccr = RD_REG_WORD(&reg->hccr);
@@ -101,7 +102,7 @@
 			RD_REG_WORD(&reg->hccr);
 		}
 	}
-	spin_unlock(&ha->hardware_lock);
+	spin_unlock_irqrestore(&ha->hardware_lock, flags);
 
 	if (test_bit(MBX_INTR_WAIT, &ha->mbx_cmd_flags) &&
 	    (status & MBX_INTERRUPT) && ha->flags.mbox_int) {
@@ -133,6 +134,7 @@
 	uint16_t	mb[4];
 	struct rsp_que *rsp;
 	struct qla_hw_data *ha;
+	unsigned long	flags;
 
 	rsp = (struct rsp_que *) dev_id;
 	if (!rsp) {
@@ -145,7 +147,7 @@
 	reg = &ha->iobase->isp;
 	status = 0;
 
-	spin_lock(&ha->hardware_lock);
+	spin_lock_irqsave(&ha->hardware_lock, flags);
 	vha = pci_get_drvdata(ha->pdev);
 	for (iter = 50; iter--; ) {
 		stat = RD_REG_DWORD(&reg->u.isp2300.host_status);
@@ -216,7 +218,7 @@
 		WRT_REG_WORD(&reg->hccr, HCCR_CLR_RISC_INT);
 		RD_REG_WORD_RELAXED(&reg->hccr);
 	}
-	spin_unlock(&ha->hardware_lock);
+	spin_unlock_irqrestore(&ha->hardware_lock, flags);
 
 	if (test_bit(MBX_INTR_WAIT, &ha->mbx_cmd_flags) &&
 	    (status & MBX_INTERRUPT) && ha->flags.mbox_int) {
@@ -1626,6 +1628,7 @@
 	uint32_t	hccr;
 	uint16_t	mb[4];
 	struct rsp_que *rsp;
+	unsigned long	flags;
 
 	rsp = (struct rsp_que *) dev_id;
 	if (!rsp) {
@@ -1638,7 +1641,7 @@
 	reg = &ha->iobase->isp24;
 	status = 0;
 
-	spin_lock(&ha->hardware_lock);
+	spin_lock_irqsave(&ha->hardware_lock, flags);
 	vha = pci_get_drvdata(ha->pdev);
 	for (iter = 50; iter--; ) {
 		stat = RD_REG_DWORD(&reg->host_status);
@@ -1688,7 +1691,7 @@
 		WRT_REG_DWORD(&reg->hccr, HCCRX_CLR_RISC_INT);
 		RD_REG_DWORD_RELAXED(&reg->hccr);
 	}
-	spin_unlock(&ha->hardware_lock);
+	spin_unlock_irqrestore(&ha->hardware_lock, flags);
 
 	if (test_bit(MBX_INTR_WAIT, &ha->mbx_cmd_flags) &&
 	    (status & MBX_INTERRUPT) && ha->flags.mbox_int) {
diff --git a/drivers/scsi/qla2xxx/qla_sup.c b/drivers/scsi/qla2xxx/qla_sup.c
index 6260505..010e69b 100644
--- a/drivers/scsi/qla2xxx/qla_sup.c
+++ b/drivers/scsi/qla2xxx/qla_sup.c
@@ -945,7 +945,9 @@
 
 		DEBUG2(qla_printk(KERN_INFO, ha, "NPIV[%02x]: wwpn=%llx "
 			"wwnn=%llx vf_id=0x%x Q_qos=0x%x F_qos=0x%x.\n", cnt,
-			vid.port_name, vid.node_name, le16_to_cpu(entry->vf_id),
+			(unsigned long long)vid.port_name,
+			(unsigned long long)vid.node_name,
+			le16_to_cpu(entry->vf_id),
 			entry->q_qos, entry->f_qos));
 
 		if (i < QLA_PRECONFIG_VPORTS) {
@@ -954,7 +956,8 @@
 				qla_printk(KERN_INFO, ha,
 				"NPIV-Config: Failed to create vport [%02x]: "
 				"wwpn=%llx wwnn=%llx.\n", cnt,
-				vid.port_name, vid.node_name);
+				(unsigned long long)vid.port_name,
+				(unsigned long long)vid.node_name);
 		}
 	}
 done:
diff --git a/drivers/scsi/scsi_devinfo.c b/drivers/scsi/scsi_devinfo.c
index b134813..8821df9 100644
--- a/drivers/scsi/scsi_devinfo.c
+++ b/drivers/scsi/scsi_devinfo.c
@@ -225,6 +225,7 @@
 	{"SGI", "Universal Xport", "*", BLIST_NO_ULD_ATTACH},
 	{"IBM", "Universal Xport", "*", BLIST_NO_ULD_ATTACH},
 	{"SUN", "Universal Xport", "*", BLIST_NO_ULD_ATTACH},
+	{"DELL", "Universal Xport", "*", BLIST_NO_ULD_ATTACH},
 	{"SMSC", "USB 2 HS-CF", NULL, BLIST_SPARSELUN | BLIST_INQUIRY_36},
 	{"SONY", "CD-ROM CDU-8001", NULL, BLIST_BORKEN},
 	{"SONY", "TSL", NULL, BLIST_FORCELUN},		/* DDS3 & DDS4 autoloaders */
diff --git a/drivers/scsi/scsi_transport_fc.c b/drivers/scsi/scsi_transport_fc.c
index a152f89..3f64d93 100644
--- a/drivers/scsi/scsi_transport_fc.c
+++ b/drivers/scsi/scsi_transport_fc.c
@@ -35,6 +35,7 @@
 #include <linux/netlink.h>
 #include <net/netlink.h>
 #include <scsi/scsi_netlink_fc.h>
+#include <scsi/scsi_bsg_fc.h>
 #include "scsi_priv.h"
 #include "scsi_transport_fc_internal.h"
 
@@ -43,6 +44,10 @@
 static int fc_vport_setup(struct Scsi_Host *shost, int channel,
 	struct device *pdev, struct fc_vport_identifiers  *ids,
 	struct fc_vport **vport);
+static int fc_bsg_hostadd(struct Scsi_Host *, struct fc_host_attrs *);
+static int fc_bsg_rportadd(struct Scsi_Host *, struct fc_rport *);
+static void fc_bsg_remove(struct request_queue *);
+static void fc_bsg_goose_queue(struct fc_rport *);
 
 /*
  * Redefine so that we can have same named attributes in the
@@ -411,13 +416,26 @@
 		return -ENOMEM;
 	}
 
+	fc_bsg_hostadd(shost, fc_host);
+	/* ignore any bsg add error - we just can't do sgio */
+
+	return 0;
+}
+
+static int fc_host_remove(struct transport_container *tc, struct device *dev,
+			 struct device *cdev)
+{
+	struct Scsi_Host *shost = dev_to_shost(dev);
+	struct fc_host_attrs *fc_host = shost_to_fc_host(shost);
+
+	fc_bsg_remove(fc_host->rqst_q);
 	return 0;
 }
 
 static DECLARE_TRANSPORT_CLASS(fc_host_class,
 			       "fc_host",
 			       fc_host_setup,
-			       NULL,
+			       fc_host_remove,
 			       NULL);
 
 /*
@@ -2375,6 +2393,7 @@
 		scsi_flush_work(shost);
 
 	fc_terminate_rport_io(rport);
+
 	/*
 	 * Cancel any outstanding timers. These should really exist
 	 * only when rmmod'ing the LLDD and we're asking for
@@ -2407,6 +2426,8 @@
 	    (i->f->dev_loss_tmo_callbk))
 		i->f->dev_loss_tmo_callbk(rport);
 
+	fc_bsg_remove(rport->rqst_q);
+
 	transport_remove_device(dev);
 	device_del(dev);
 	transport_destroy_device(dev);
@@ -2494,6 +2515,9 @@
 	transport_add_device(dev);
 	transport_configure_device(dev);
 
+	fc_bsg_rportadd(shost, rport);
+	/* ignore any bsg add error - we just can't do sgio */
+
 	if (rport->roles & FC_PORT_ROLE_FCP_TARGET) {
 		/* initiate a scan of the target */
 		rport->flags |= FC_RPORT_SCAN_PENDING;
@@ -2658,6 +2682,8 @@
 					spin_unlock_irqrestore(shost->host_lock,
 							flags);
 
+				fc_bsg_goose_queue(rport);
+
 				return rport;
 			}
 		}
@@ -3343,6 +3369,592 @@
 }
 
 
+/*
+ * BSG support
+ */
+
+
+/**
+ * fc_destroy_bsgjob - routine to teardown/delete a fc bsg job
+ * @job:	fc_bsg_job that is to be torn down
+ */
+static void
+fc_destroy_bsgjob(struct fc_bsg_job *job)
+{
+	unsigned long flags;
+
+	spin_lock_irqsave(&job->job_lock, flags);
+	if (job->ref_cnt) {
+		spin_unlock_irqrestore(&job->job_lock, flags);
+		return;
+	}
+	spin_unlock_irqrestore(&job->job_lock, flags);
+
+	put_device(job->dev);	/* release reference for the request */
+
+	kfree(job->request_payload.sg_list);
+	kfree(job->reply_payload.sg_list);
+	kfree(job);
+}
+
+
+/**
+ * fc_bsg_jobdone - completion routine for bsg requests that the LLD has
+ *                  completed
+ * @job:	fc_bsg_job that is complete
+ */
+static void
+fc_bsg_jobdone(struct fc_bsg_job *job)
+{
+	struct request *req = job->req;
+	struct request *rsp = req->next_rq;
+	unsigned long flags;
+	int err;
+
+	spin_lock_irqsave(&job->job_lock, flags);
+	job->state_flags |= FC_RQST_STATE_DONE;
+	job->ref_cnt--;
+	spin_unlock_irqrestore(&job->job_lock, flags);
+
+	err = job->req->errors = job->reply->result;
+	if (err < 0)
+		/* we're only returning the result field in the reply */
+		job->req->sense_len = sizeof(uint32_t);
+	else
+		job->req->sense_len = job->reply_len;
+
+	/* we assume all request payload was transferred, residual == 0 */
+	req->resid_len = 0;
+
+	if (rsp) {
+		WARN_ON(job->reply->reply_payload_rcv_len > rsp->resid_len);
+
+		/* set reply (bidi) residual */
+		rsp->resid_len -= min(job->reply->reply_payload_rcv_len,
+				      rsp->resid_len);
+	}
+
+	blk_end_request_all(req, err);
+
+	fc_destroy_bsgjob(job);
+}
+
+
+/**
+ * fc_bsg_job_timeout - handler for when a bsg request timesout
+ * @req:	request that timed out
+ */
+static enum blk_eh_timer_return
+fc_bsg_job_timeout(struct request *req)
+{
+	struct fc_bsg_job *job = (void *) req->special;
+	struct Scsi_Host *shost = job->shost;
+	struct fc_internal *i = to_fc_internal(shost->transportt);
+	unsigned long flags;
+	int err = 0, done = 0;
+
+	if (job->rport && job->rport->port_state == FC_PORTSTATE_BLOCKED)
+		return BLK_EH_RESET_TIMER;
+
+	spin_lock_irqsave(&job->job_lock, flags);
+	if (job->state_flags & FC_RQST_STATE_DONE)
+		done = 1;
+	else
+		job->ref_cnt++;
+	spin_unlock_irqrestore(&job->job_lock, flags);
+
+	if (!done && i->f->bsg_timeout) {
+		/* call LLDD to abort the i/o as it has timed out */
+		err = i->f->bsg_timeout(job);
+		if (err)
+			printk(KERN_ERR "ERROR: FC BSG request timeout - LLD "
+				"abort failed with status %d\n", err);
+	}
+
+	if (!done) {
+		spin_lock_irqsave(&job->job_lock, flags);
+		job->ref_cnt--;
+		spin_unlock_irqrestore(&job->job_lock, flags);
+		fc_destroy_bsgjob(job);
+	}
+
+	/* the blk_end_sync_io() doesn't check the error */
+	return BLK_EH_HANDLED;
+}
+
+
+
+static int
+fc_bsg_map_buffer(struct fc_bsg_buffer *buf, struct request *req)
+{
+	size_t sz = (sizeof(struct scatterlist) * req->nr_phys_segments);
+
+	BUG_ON(!req->nr_phys_segments);
+
+	buf->sg_list = kzalloc(sz, GFP_KERNEL);
+	if (!buf->sg_list)
+		return -ENOMEM;
+	sg_init_table(buf->sg_list, req->nr_phys_segments);
+	buf->sg_cnt = blk_rq_map_sg(req->q, req, buf->sg_list);
+	buf->payload_len = blk_rq_bytes(req);
+	return 0;
+}
+
+
+/**
+ * fc_req_to_bsgjob - Allocate/create the fc_bsg_job structure for the
+ *                   bsg request
+ * @shost:	SCSI Host corresponding to the bsg object
+ * @rport:	(optional) FC Remote Port corresponding to the bsg object
+ * @req:	BSG request that needs a job structure
+ */
+static int
+fc_req_to_bsgjob(struct Scsi_Host *shost, struct fc_rport *rport,
+	struct request *req)
+{
+	struct fc_internal *i = to_fc_internal(shost->transportt);
+	struct request *rsp = req->next_rq;
+	struct fc_bsg_job *job;
+	int ret;
+
+	BUG_ON(req->special);
+
+	job = kzalloc(sizeof(struct fc_bsg_job) + i->f->dd_bsg_size,
+			GFP_KERNEL);
+	if (!job)
+		return -ENOMEM;
+
+	/*
+	 * Note: this is a bit silly.
+	 * The request gets formatted as a SGIO v4 ioctl request, which
+	 * then gets reformatted as a blk request, which then gets
+	 * reformatted as a fc bsg request. And on completion, we have
+	 * to wrap return results such that SGIO v4 thinks it was a scsi
+	 * status.  I hope this was all worth it.
+	 */
+
+	req->special = job;
+	job->shost = shost;
+	job->rport = rport;
+	job->req = req;
+	if (i->f->dd_bsg_size)
+		job->dd_data = (void *)&job[1];
+	spin_lock_init(&job->job_lock);
+	job->request = (struct fc_bsg_request *)req->cmd;
+	job->request_len = req->cmd_len;
+	job->reply = req->sense;
+	job->reply_len = SCSI_SENSE_BUFFERSIZE;	/* Size of sense buffer
+						 * allocated */
+	if (req->bio) {
+		ret = fc_bsg_map_buffer(&job->request_payload, req);
+		if (ret)
+			goto failjob_rls_job;
+	}
+	if (rsp && rsp->bio) {
+		ret = fc_bsg_map_buffer(&job->reply_payload, rsp);
+		if (ret)
+			goto failjob_rls_rqst_payload;
+	}
+	job->job_done = fc_bsg_jobdone;
+	if (rport)
+		job->dev = &rport->dev;
+	else
+		job->dev = &shost->shost_gendev;
+	get_device(job->dev);		/* take a reference for the request */
+
+	job->ref_cnt = 1;
+
+	return 0;
+
+
+failjob_rls_rqst_payload:
+	kfree(job->request_payload.sg_list);
+failjob_rls_job:
+	kfree(job);
+	return -ENOMEM;
+}
+
+
+enum fc_dispatch_result {
+	FC_DISPATCH_BREAK,	/* on return, q is locked, break from q loop */
+	FC_DISPATCH_LOCKED,	/* on return, q is locked, continue on */
+	FC_DISPATCH_UNLOCKED,	/* on return, q is unlocked, continue on */
+};
+
+
+/**
+ * fc_bsg_host_dispatch - process fc host bsg requests and dispatch to LLDD
+ * @shost:	scsi host rport attached to
+ * @job:	bsg job to be processed
+ */
+static enum fc_dispatch_result
+fc_bsg_host_dispatch(struct request_queue *q, struct Scsi_Host *shost,
+			 struct fc_bsg_job *job)
+{
+	struct fc_internal *i = to_fc_internal(shost->transportt);
+	int cmdlen = sizeof(uint32_t);	/* start with length of msgcode */
+	int ret;
+
+	/* Validate the host command */
+	switch (job->request->msgcode) {
+	case FC_BSG_HST_ADD_RPORT:
+		cmdlen += sizeof(struct fc_bsg_host_add_rport);
+		break;
+
+	case FC_BSG_HST_DEL_RPORT:
+		cmdlen += sizeof(struct fc_bsg_host_del_rport);
+		break;
+
+	case FC_BSG_HST_ELS_NOLOGIN:
+		cmdlen += sizeof(struct fc_bsg_host_els);
+		/* there better be a xmt and rcv payloads */
+		if ((!job->request_payload.payload_len) ||
+		    (!job->reply_payload.payload_len)) {
+			ret = -EINVAL;
+			goto fail_host_msg;
+		}
+		break;
+
+	case FC_BSG_HST_CT:
+		cmdlen += sizeof(struct fc_bsg_host_ct);
+		/* there better be xmt and rcv payloads */
+		if ((!job->request_payload.payload_len) ||
+		    (!job->reply_payload.payload_len)) {
+			ret = -EINVAL;
+			goto fail_host_msg;
+		}
+		break;
+
+	case FC_BSG_HST_VENDOR:
+		cmdlen += sizeof(struct fc_bsg_host_vendor);
+		if ((shost->hostt->vendor_id == 0L) ||
+		    (job->request->rqst_data.h_vendor.vendor_id !=
+			shost->hostt->vendor_id)) {
+			ret = -ESRCH;
+			goto fail_host_msg;
+		}
+		break;
+
+	default:
+		ret = -EBADR;
+		goto fail_host_msg;
+	}
+
+	/* check if we really have all the request data needed */
+	if (job->request_len < cmdlen) {
+		ret = -ENOMSG;
+		goto fail_host_msg;
+	}
+
+	ret = i->f->bsg_request(job);
+	if (!ret)
+		return FC_DISPATCH_UNLOCKED;
+
+fail_host_msg:
+	/* return the errno failure code as the only status */
+	BUG_ON(job->reply_len < sizeof(uint32_t));
+	job->reply->result = ret;
+	job->reply_len = sizeof(uint32_t);
+	fc_bsg_jobdone(job);
+	return FC_DISPATCH_UNLOCKED;
+}
+
+
+/*
+ * fc_bsg_goose_queue - restart rport queue in case it was stopped
+ * @rport:	rport to be restarted
+ */
+static void
+fc_bsg_goose_queue(struct fc_rport *rport)
+{
+	int flagset;
+
+	if (!rport->rqst_q)
+		return;
+
+	get_device(&rport->dev);
+
+	spin_lock(rport->rqst_q->queue_lock);
+	flagset = test_bit(QUEUE_FLAG_REENTER, &rport->rqst_q->queue_flags) &&
+		  !test_bit(QUEUE_FLAG_REENTER, &rport->rqst_q->queue_flags);
+	if (flagset)
+		queue_flag_set(QUEUE_FLAG_REENTER, rport->rqst_q);
+	__blk_run_queue(rport->rqst_q);
+	if (flagset)
+		queue_flag_clear(QUEUE_FLAG_REENTER, rport->rqst_q);
+	spin_unlock(rport->rqst_q->queue_lock);
+
+	put_device(&rport->dev);
+}
+
+
+/**
+ * fc_bsg_rport_dispatch - process rport bsg requests and dispatch to LLDD
+ * @shost:	scsi host rport attached to
+ * @rport:	rport request destined to
+ * @job:	bsg job to be processed
+ */
+static enum fc_dispatch_result
+fc_bsg_rport_dispatch(struct request_queue *q, struct Scsi_Host *shost,
+			 struct fc_rport *rport, struct fc_bsg_job *job)
+{
+	struct fc_internal *i = to_fc_internal(shost->transportt);
+	int cmdlen = sizeof(uint32_t);	/* start with length of msgcode */
+	int ret;
+
+	/* Validate the rport command */
+	switch (job->request->msgcode) {
+	case FC_BSG_RPT_ELS:
+		cmdlen += sizeof(struct fc_bsg_rport_els);
+		goto check_bidi;
+
+	case FC_BSG_RPT_CT:
+		cmdlen += sizeof(struct fc_bsg_rport_ct);
+check_bidi:
+		/* there better be xmt and rcv payloads */
+		if ((!job->request_payload.payload_len) ||
+		    (!job->reply_payload.payload_len)) {
+			ret = -EINVAL;
+			goto fail_rport_msg;
+		}
+		break;
+	default:
+		ret = -EBADR;
+		goto fail_rport_msg;
+	}
+
+	/* check if we really have all the request data needed */
+	if (job->request_len < cmdlen) {
+		ret = -ENOMSG;
+		goto fail_rport_msg;
+	}
+
+	ret = i->f->bsg_request(job);
+	if (!ret)
+		return FC_DISPATCH_UNLOCKED;
+
+fail_rport_msg:
+	/* return the errno failure code as the only status */
+	BUG_ON(job->reply_len < sizeof(uint32_t));
+	job->reply->result = ret;
+	job->reply_len = sizeof(uint32_t);
+	fc_bsg_jobdone(job);
+	return FC_DISPATCH_UNLOCKED;
+}
+
+
+/**
+ * fc_bsg_request_handler - generic handler for bsg requests
+ * @q:		request queue to manage
+ * @shost:	Scsi_Host related to the bsg object
+ * @rport:	FC remote port related to the bsg object (optional)
+ * @dev:	device structure for bsg object
+ */
+static void
+fc_bsg_request_handler(struct request_queue *q, struct Scsi_Host *shost,
+		       struct fc_rport *rport, struct device *dev)
+{
+	struct request *req;
+	struct fc_bsg_job *job;
+	enum fc_dispatch_result ret;
+
+	if (!get_device(dev))
+		return;
+
+	while (!blk_queue_plugged(q)) {
+		if (rport && (rport->port_state == FC_PORTSTATE_BLOCKED))
+				break;
+
+		req = blk_fetch_request(q);
+		if (!req)
+			break;
+
+		if (rport && (rport->port_state != FC_PORTSTATE_ONLINE)) {
+			req->errors = -ENXIO;
+			spin_unlock_irq(q->queue_lock);
+			blk_end_request(req, -ENXIO, blk_rq_bytes(req));
+			spin_lock_irq(q->queue_lock);
+			continue;
+		}
+
+		spin_unlock_irq(q->queue_lock);
+
+		ret = fc_req_to_bsgjob(shost, rport, req);
+		if (ret) {
+			req->errors = ret;
+			blk_end_request(req, ret, blk_rq_bytes(req));
+			spin_lock_irq(q->queue_lock);
+			continue;
+		}
+
+		job = req->special;
+
+		/* check if we have the msgcode value at least */
+		if (job->request_len < sizeof(uint32_t)) {
+			BUG_ON(job->reply_len < sizeof(uint32_t));
+			job->reply->result = -ENOMSG;
+			job->reply_len = sizeof(uint32_t);
+			fc_bsg_jobdone(job);
+			spin_lock_irq(q->queue_lock);
+			continue;
+		}
+
+		/* the dispatch routines will unlock the queue_lock */
+		if (rport)
+			ret = fc_bsg_rport_dispatch(q, shost, rport, job);
+		else
+			ret = fc_bsg_host_dispatch(q, shost, job);
+
+		/* did dispatcher hit state that can't process any more */
+		if (ret == FC_DISPATCH_BREAK)
+			break;
+
+		/* did dispatcher had released the lock */
+		if (ret == FC_DISPATCH_UNLOCKED)
+			spin_lock_irq(q->queue_lock);
+	}
+
+	spin_unlock_irq(q->queue_lock);
+	put_device(dev);
+	spin_lock_irq(q->queue_lock);
+}
+
+
+/**
+ * fc_bsg_host_handler - handler for bsg requests for a fc host
+ * @q:		fc host request queue
+ */
+static void
+fc_bsg_host_handler(struct request_queue *q)
+{
+	struct Scsi_Host *shost = q->queuedata;
+
+	fc_bsg_request_handler(q, shost, NULL, &shost->shost_gendev);
+}
+
+
+/**
+ * fc_bsg_rport_handler - handler for bsg requests for a fc rport
+ * @q:		rport request queue
+ */
+static void
+fc_bsg_rport_handler(struct request_queue *q)
+{
+	struct fc_rport *rport = q->queuedata;
+	struct Scsi_Host *shost = rport_to_shost(rport);
+
+	fc_bsg_request_handler(q, shost, rport, &rport->dev);
+}
+
+
+/**
+ * fc_bsg_hostadd - Create and add the bsg hooks so we can receive requests
+ * @shost:	shost for fc_host
+ * @fc_host:	fc_host adding the structures to
+ */
+static int
+fc_bsg_hostadd(struct Scsi_Host *shost, struct fc_host_attrs *fc_host)
+{
+	struct device *dev = &shost->shost_gendev;
+	struct fc_internal *i = to_fc_internal(shost->transportt);
+	struct request_queue *q;
+	int err;
+	char bsg_name[BUS_ID_SIZE]; /*20*/
+
+	fc_host->rqst_q = NULL;
+
+	if (!i->f->bsg_request)
+		return -ENOTSUPP;
+
+	snprintf(bsg_name, sizeof(bsg_name),
+		 "fc_host%d", shost->host_no);
+
+	q = __scsi_alloc_queue(shost, fc_bsg_host_handler);
+	if (!q) {
+		printk(KERN_ERR "fc_host%d: bsg interface failed to "
+				"initialize - no request queue\n",
+				 shost->host_no);
+		return -ENOMEM;
+	}
+
+	q->queuedata = shost;
+	queue_flag_set_unlocked(QUEUE_FLAG_BIDI, q);
+	blk_queue_rq_timed_out(q, fc_bsg_job_timeout);
+	blk_queue_rq_timeout(q, FC_DEFAULT_BSG_TIMEOUT);
+
+	err = bsg_register_queue(q, dev, bsg_name, NULL);
+	if (err) {
+		printk(KERN_ERR "fc_host%d: bsg interface failed to "
+				"initialize - register queue\n",
+				shost->host_no);
+		blk_cleanup_queue(q);
+		return err;
+	}
+
+	fc_host->rqst_q = q;
+	return 0;
+}
+
+
+/**
+ * fc_bsg_rportadd - Create and add the bsg hooks so we can receive requests
+ * @shost:	shost that rport is attached to
+ * @rport:	rport that the bsg hooks are being attached to
+ */
+static int
+fc_bsg_rportadd(struct Scsi_Host *shost, struct fc_rport *rport)
+{
+	struct device *dev = &rport->dev;
+	struct fc_internal *i = to_fc_internal(shost->transportt);
+	struct request_queue *q;
+	int err;
+
+	rport->rqst_q = NULL;
+
+	if (!i->f->bsg_request)
+		return -ENOTSUPP;
+
+	q = __scsi_alloc_queue(shost, fc_bsg_rport_handler);
+	if (!q) {
+		printk(KERN_ERR "%s: bsg interface failed to "
+				"initialize - no request queue\n",
+				 dev->kobj.name);
+		return -ENOMEM;
+	}
+
+	q->queuedata = rport;
+	queue_flag_set_unlocked(QUEUE_FLAG_BIDI, q);
+	blk_queue_rq_timed_out(q, fc_bsg_job_timeout);
+	blk_queue_rq_timeout(q, BLK_DEFAULT_SG_TIMEOUT);
+
+	err = bsg_register_queue(q, dev, NULL, NULL);
+	if (err) {
+		printk(KERN_ERR "%s: bsg interface failed to "
+				"initialize - register queue\n",
+				 dev->kobj.name);
+		blk_cleanup_queue(q);
+		return err;
+	}
+
+	rport->rqst_q = q;
+	return 0;
+}
+
+
+/**
+ * fc_bsg_remove - Deletes the bsg hooks on fchosts/rports
+ * @q:	the request_queue that is to be torn down.
+ */
+static void
+fc_bsg_remove(struct request_queue *q)
+{
+	if (q) {
+		bsg_unregister_queue(q);
+		blk_cleanup_queue(q);
+	}
+}
+
+
 /* Original Author:  Martin Hicks */
 MODULE_AUTHOR("James Smart");
 MODULE_DESCRIPTION("FC Transport Attributes");
diff --git a/drivers/scsi/scsi_transport_spi.c b/drivers/scsi/scsi_transport_spi.c
index f49f55c..654a34f 100644
--- a/drivers/scsi/scsi_transport_spi.c
+++ b/drivers/scsi/scsi_transport_spi.c
@@ -234,8 +234,10 @@
 	spi_width(starget) = 0;	/* narrow */
 	spi_max_width(starget) = 1;
 	spi_iu(starget) = 0;	/* no IU */
+	spi_max_iu(starget) = 1;
 	spi_dt(starget) = 0;	/* ST */
 	spi_qas(starget) = 0;
+	spi_max_qas(starget) = 1;
 	spi_wr_flow(starget) = 0;
 	spi_rd_strm(starget) = 0;
 	spi_rti(starget) = 0;
@@ -360,9 +362,9 @@
 /* The Parallel SCSI Tranport Attributes: */
 spi_transport_max_attr(offset, "%d\n");
 spi_transport_max_attr(width, "%d\n");
-spi_transport_rd_attr(iu, "%d\n");
+spi_transport_max_attr(iu, "%d\n");
 spi_transport_rd_attr(dt, "%d\n");
-spi_transport_rd_attr(qas, "%d\n");
+spi_transport_max_attr(qas, "%d\n");
 spi_transport_rd_attr(wr_flow, "%d\n");
 spi_transport_rd_attr(rd_strm, "%d\n");
 spi_transport_rd_attr(rti, "%d\n");
@@ -874,13 +876,13 @@
 
 	/* try QAS requests; this should be harmless to set if the
 	 * target supports it */
-	if (scsi_device_qas(sdev)) {
+	if (scsi_device_qas(sdev) && spi_max_qas(starget)) {
 		DV_SET(qas, 1);
 	} else {
 		DV_SET(qas, 0);
 	}
 
-	if (scsi_device_ius(sdev) && min_period < 9) {
+	if (scsi_device_ius(sdev) && spi_max_iu(starget) && min_period < 9) {
 		/* This u320 (or u640). Set IU transfers */
 		DV_SET(iu, 1);
 		/* Then set the optional parameters */
@@ -1412,12 +1414,18 @@
 	else if (attr == &dev_attr_iu.attr &&
 		 spi_support_ius(starget))
 		return TARGET_ATTRIBUTE_HELPER(iu);
+	else if (attr == &dev_attr_max_iu.attr &&
+		 spi_support_ius(starget))
+		return TARGET_ATTRIBUTE_HELPER(iu);
 	else if (attr == &dev_attr_dt.attr &&
 		 spi_support_dt(starget))
 		return TARGET_ATTRIBUTE_HELPER(dt);
 	else if (attr == &dev_attr_qas.attr &&
 		 spi_support_qas(starget))
 		return TARGET_ATTRIBUTE_HELPER(qas);
+	else if (attr == &dev_attr_max_qas.attr &&
+		 spi_support_qas(starget))
+		return TARGET_ATTRIBUTE_HELPER(qas);
 	else if (attr == &dev_attr_wr_flow.attr &&
 		 spi_support_ius(starget))
 		return TARGET_ATTRIBUTE_HELPER(wr_flow);
@@ -1447,8 +1455,10 @@
 	&dev_attr_width.attr,
 	&dev_attr_max_width.attr,
 	&dev_attr_iu.attr,
+	&dev_attr_max_iu.attr,
 	&dev_attr_dt.attr,
 	&dev_attr_qas.attr,
+	&dev_attr_max_qas.attr,
 	&dev_attr_wr_flow.attr,
 	&dev_attr_rd_strm.attr,
 	&dev_attr_rti.attr,
diff --git a/drivers/serial/mpc52xx_uart.c b/drivers/serial/mpc52xx_uart.c
index b3feb619..abbd146 100644
--- a/drivers/serial/mpc52xx_uart.c
+++ b/drivers/serial/mpc52xx_uart.c
@@ -76,7 +76,6 @@
 #include <linux/of_platform.h>
 
 #include <asm/mpc52xx.h>
-#include <asm/mpc512x.h>
 #include <asm/mpc52xx_psc.h>
 
 #if defined(CONFIG_SERIAL_MPC52xx_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ)
@@ -254,7 +253,7 @@
 	 * but the generic serial code assumes 16
 	 * so return ipb freq / 2
 	 */
-	return mpc52xx_find_ipb_freq(p) / 2;
+	return mpc5xxx_get_bus_frequency(p) / 2;
 }
 
 static struct psc_ops mpc52xx_psc_ops = {
@@ -391,7 +390,7 @@
 
 static unsigned long mpc512x_getuartclk(void *p)
 {
-	return mpc512x_find_ips_freq(p);
+	return mpc5xxx_get_bus_frequency(p);
 }
 
 static struct psc_ops mpc512x_psc_ops = {
diff --git a/drivers/serial/of_serial.c b/drivers/serial/of_serial.c
index 54483cd..02406ba 100644
--- a/drivers/serial/of_serial.c
+++ b/drivers/serial/of_serial.c
@@ -67,7 +67,7 @@
 	port->type = type;
 	port->uartclk = *clk;
 	port->flags = UPF_SHARE_IRQ | UPF_BOOT_AUTOCONF | UPF_IOREMAP
-		| UPF_FIXED_PORT;
+		| UPF_FIXED_PORT | UPF_FIXED_TYPE;
 	port->dev = &ofdev->dev;
 	/* If current-speed was set, then try not to change it. */
 	if (spd)
diff --git a/drivers/serial/sh-sci.c b/drivers/serial/sh-sci.c
index a4cf107..66f5267 100644
--- a/drivers/serial/sh-sci.c
+++ b/drivers/serial/sh-sci.c
@@ -1332,44 +1332,46 @@
 	return ret;
 }
 
-static int sci_suspend(struct platform_device *dev, pm_message_t state)
+static int sci_suspend(struct device *dev)
 {
-	struct sh_sci_priv *priv = platform_get_drvdata(dev);
+	struct sh_sci_priv *priv = dev_get_drvdata(dev);
 	struct sci_port *p;
 	unsigned long flags;
 
 	spin_lock_irqsave(&priv->lock, flags);
 	list_for_each_entry(p, &priv->ports, node)
 		uart_suspend_port(&sci_uart_driver, &p->port);
-
 	spin_unlock_irqrestore(&priv->lock, flags);
 
 	return 0;
 }
 
-static int sci_resume(struct platform_device *dev)
+static int sci_resume(struct device *dev)
 {
-	struct sh_sci_priv *priv = platform_get_drvdata(dev);
+	struct sh_sci_priv *priv = dev_get_drvdata(dev);
 	struct sci_port *p;
 	unsigned long flags;
 
 	spin_lock_irqsave(&priv->lock, flags);
 	list_for_each_entry(p, &priv->ports, node)
 		uart_resume_port(&sci_uart_driver, &p->port);
-
 	spin_unlock_irqrestore(&priv->lock, flags);
 
 	return 0;
 }
 
+static struct dev_pm_ops sci_dev_pm_ops = {
+	.suspend	= sci_suspend,
+	.resume		= sci_resume,
+};
+
 static struct platform_driver sci_driver = {
 	.probe		= sci_probe,
 	.remove		= __devexit_p(sci_remove),
-	.suspend	= sci_suspend,
-	.resume		= sci_resume,
 	.driver		= {
 		.name	= "sh-sci",
 		.owner	= THIS_MODULE,
+		.pm	= &sci_dev_pm_ops,
 	},
 };
 
diff --git a/drivers/serial/ucc_uart.c b/drivers/serial/ucc_uart.c
index 7de66c06..e945e78 100644
--- a/drivers/serial/ucc_uart.c
+++ b/drivers/serial/ucc_uart.c
@@ -681,22 +681,27 @@
 	out_be16(&uccup->rccm, 0xc0ff);
 
 	/* Configure the GUMR registers for UART */
-	if (soft_uart)
+	if (soft_uart) {
 		/* Soft-UART requires a 1X multiplier for TX */
 		clrsetbits_be32(&uccp->gumr_l,
 			UCC_SLOW_GUMR_L_MODE_MASK | UCC_SLOW_GUMR_L_TDCR_MASK |
 			UCC_SLOW_GUMR_L_RDCR_MASK,
 			UCC_SLOW_GUMR_L_MODE_UART | UCC_SLOW_GUMR_L_TDCR_1 |
 			UCC_SLOW_GUMR_L_RDCR_16);
-	else
+
+		clrsetbits_be32(&uccp->gumr_h, UCC_SLOW_GUMR_H_RFW,
+			UCC_SLOW_GUMR_H_TRX | UCC_SLOW_GUMR_H_TTX);
+	} else {
 		clrsetbits_be32(&uccp->gumr_l,
 			UCC_SLOW_GUMR_L_MODE_MASK | UCC_SLOW_GUMR_L_TDCR_MASK |
 			UCC_SLOW_GUMR_L_RDCR_MASK,
 			UCC_SLOW_GUMR_L_MODE_UART | UCC_SLOW_GUMR_L_TDCR_16 |
 			UCC_SLOW_GUMR_L_RDCR_16);
 
-	clrsetbits_be32(&uccp->gumr_h, UCC_SLOW_GUMR_H_RFW,
-		UCC_SLOW_GUMR_H_TRX | UCC_SLOW_GUMR_H_TTX);
+		clrsetbits_be32(&uccp->gumr_h,
+			UCC_SLOW_GUMR_H_TRX | UCC_SLOW_GUMR_H_TTX,
+			UCC_SLOW_GUMR_H_RFW);
+	}
 
 #ifdef LOOPBACK
 	clrsetbits_be32(&uccp->gumr_l, UCC_SLOW_GUMR_L_DIAG_MASK,
@@ -706,7 +711,7 @@
 		UCC_SLOW_GUMR_H_CDS);
 #endif
 
-	/* Enable rx interrupts  and clear all pending events.  */
+	/* Disable rx interrupts  and clear all pending events.  */
 	out_be16(&uccp->uccm, 0);
 	out_be16(&uccp->ucce, 0xffff);
 	out_be16(&uccp->udsr, 0x7e7e);
@@ -765,6 +770,10 @@
 		cecr_subblock = ucc_slow_get_qe_cr_subblock(qe_port->ucc_num);
 		qe_issue_cmd(QE_INIT_TX_RX, cecr_subblock,
 			QE_CR_PROTOCOL_UNSPECIFIED, 0);
+	} else {
+		cecr_subblock = ucc_slow_get_qe_cr_subblock(qe_port->ucc_num);
+		qe_issue_cmd(QE_INIT_TX_RX, cecr_subblock,
+			QE_CR_PROTOCOL_UART, 0);
 	}
 }
 
diff --git a/drivers/sh/intc.c b/drivers/sh/intc.c
index d687a9b..3dd231a 100644
--- a/drivers/sh/intc.c
+++ b/drivers/sh/intc.c
@@ -20,7 +20,6 @@
 #include <linux/module.h>
 #include <linux/io.h>
 #include <linux/interrupt.h>
-#include <linux/bootmem.h>
 #include <linux/sh_intc.h>
 #include <linux/sysdev.h>
 #include <linux/list.h>
@@ -675,7 +674,7 @@
 	unsigned int i, k, smp;
 	struct intc_desc_int *d;
 
-	d = alloc_bootmem(sizeof(*d));
+	d = kzalloc(sizeof(*d), GFP_NOWAIT);
 
 	INIT_LIST_HEAD(&d->list);
 	list_add(&d->list, &intc_list);
@@ -687,9 +686,9 @@
 #if defined(CONFIG_CPU_SH3) || defined(CONFIG_CPU_SH4A)
 	d->nr_reg += desc->ack_regs ? desc->nr_ack_regs : 0;
 #endif
-	d->reg = alloc_bootmem(d->nr_reg * sizeof(*d->reg));
+	d->reg = kzalloc(d->nr_reg * sizeof(*d->reg), GFP_NOWAIT);
 #ifdef CONFIG_SMP
-	d->smp = alloc_bootmem(d->nr_reg * sizeof(*d->smp));
+	d->smp = kzalloc(d->nr_reg * sizeof(*d->smp), GFP_NOWAIT);
 #endif
 	k = 0;
 
@@ -702,7 +701,7 @@
 	}
 
 	if (desc->prio_regs) {
-		d->prio = alloc_bootmem(desc->nr_vectors * sizeof(*d->prio));
+		d->prio = kzalloc(desc->nr_vectors * sizeof(*d->prio), GFP_NOWAIT);
 
 		for (i = 0; i < desc->nr_prio_regs; i++) {
 			smp = IS_SMP(desc->prio_regs[i]);
@@ -712,7 +711,7 @@
 	}
 
 	if (desc->sense_regs) {
-		d->sense = alloc_bootmem(desc->nr_vectors * sizeof(*d->sense));
+		d->sense = kzalloc(desc->nr_vectors * sizeof(*d->sense), GFP_NOWAIT);
 
 		for (i = 0; i < desc->nr_sense_regs; i++) {
 			k += save_reg(d, k, desc->sense_regs[i].reg, 0);
@@ -757,7 +756,7 @@
 			vect2->enum_id = 0;
 
 			if (!intc_evt2irq_table)
-				intc_evt2irq_table = alloc_bootmem(NR_IRQS);
+				intc_evt2irq_table = kzalloc(NR_IRQS, GFP_NOWAIT);
 
 			if (!intc_evt2irq_table) {
 				pr_warning("intc: cannot allocate evt2irq!\n");
diff --git a/drivers/spi/Kconfig b/drivers/spi/Kconfig
index e8aae22..2c733c2 100644
--- a/drivers/spi/Kconfig
+++ b/drivers/spi/Kconfig
@@ -139,17 +139,15 @@
 	  This enables using the Freescale MPC52xx Programmable Serial
 	  Controller in master SPI mode.
 
-config SPI_MPC83xx
-	tristate "Freescale MPC83xx/QUICC Engine SPI controller"
-	depends on (PPC_83xx || QUICC_ENGINE) && EXPERIMENTAL
+config SPI_MPC8xxx
+	tristate "Freescale MPC8xxx SPI controller"
+	depends on FSL_SOC
 	help
-	  This enables using the Freescale MPC83xx and QUICC Engine SPI
-	  controllers in master mode.
+	  This enables using the Freescale MPC8xxx SPI controllers in master
+	  mode.
 
-	  Note, this driver uniquely supports the SPI controller on the MPC83xx
-	  family of PowerPC processors, plus processors with QUICC Engine
-	  technology. This driver uses a simple set of shift registers for data
-	  (opposed to the CPM based descriptor model).
+	  This driver uses a simple set of shift registers for data (opposed
+	  to the CPM based descriptor model).
 
 config SPI_OMAP_UWIRE
 	tristate "OMAP1 MicroWire"
diff --git a/drivers/spi/Makefile b/drivers/spi/Makefile
index ecfadb1..3de408d 100644
--- a/drivers/spi/Makefile
+++ b/drivers/spi/Makefile
@@ -25,7 +25,7 @@
 obj-$(CONFIG_SPI_ORION)			+= orion_spi.o
 obj-$(CONFIG_SPI_PL022)			+= amba-pl022.o
 obj-$(CONFIG_SPI_MPC52xx_PSC)		+= mpc52xx_psc_spi.o
-obj-$(CONFIG_SPI_MPC83xx)		+= spi_mpc83xx.o
+obj-$(CONFIG_SPI_MPC8xxx)		+= spi_mpc8xxx.o
 obj-$(CONFIG_SPI_S3C24XX_GPIO)		+= spi_s3c24xx_gpio.o
 obj-$(CONFIG_SPI_S3C24XX)		+= spi_s3c24xx.o
 obj-$(CONFIG_SPI_TXX9)			+= spi_txx9.o
diff --git a/drivers/spi/atmel_spi.c b/drivers/spi/atmel_spi.c
index 12e443c..f5b3fdb 100644
--- a/drivers/spi/atmel_spi.c
+++ b/drivers/spi/atmel_spi.c
@@ -530,9 +530,6 @@
 	return ret;
 }
 
-/* the spi->mode bits understood by this driver: */
-#define MODEBITS (SPI_CPOL | SPI_CPHA | SPI_CS_HIGH)
-
 static int atmel_spi_setup(struct spi_device *spi)
 {
 	struct atmel_spi	*as;
@@ -555,8 +552,6 @@
 		return -EINVAL;
 	}
 
-	if (bits == 0)
-		bits = 8;
 	if (bits < 8 || bits > 16) {
 		dev_dbg(&spi->dev,
 				"setup: invalid bits_per_word %u (8 to 16)\n",
@@ -564,12 +559,6 @@
 		return -EINVAL;
 	}
 
-	if (spi->mode & ~MODEBITS) {
-		dev_dbg(&spi->dev, "setup: unsupported mode bits %x\n",
-			spi->mode & ~MODEBITS);
-		return -EINVAL;
-	}
-
 	/* see notes above re chipselect */
 	if (!atmel_spi_is_v2()
 			&& spi->chip_select == 0
@@ -775,6 +764,9 @@
 	if (!master)
 		goto out_free;
 
+	/* the spi->mode bits understood by this driver: */
+	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH;
+
 	master->bus_num = pdev->id;
 	master->num_chipselect = 4;
 	master->setup = atmel_spi_setup;
diff --git a/drivers/spi/au1550_spi.c b/drivers/spi/au1550_spi.c
index b02f25c..76cbc1a 100644
--- a/drivers/spi/au1550_spi.c
+++ b/drivers/spi/au1550_spi.c
@@ -284,27 +284,16 @@
 	return 0;
 }
 
-/* the spi->mode bits understood by this driver: */
-#define MODEBITS (SPI_CPOL | SPI_CPHA | SPI_CS_HIGH | SPI_LSB_FIRST)
-
 static int au1550_spi_setup(struct spi_device *spi)
 {
 	struct au1550_spi *hw = spi_master_get_devdata(spi->master);
 
-	if (spi->bits_per_word == 0)
-		spi->bits_per_word = 8;
 	if (spi->bits_per_word < 4 || spi->bits_per_word > 24) {
 		dev_err(&spi->dev, "setup: invalid bits_per_word=%d\n",
 			spi->bits_per_word);
 		return -EINVAL;
 	}
 
-	if (spi->mode & ~MODEBITS) {
-		dev_dbg(&spi->dev, "setup: unsupported mode bits %x\n",
-			spi->mode & ~MODEBITS);
-		return -EINVAL;
-	}
-
 	if (spi->max_speed_hz == 0)
 		spi->max_speed_hz = hw->freq_max;
 	if (spi->max_speed_hz > hw->freq_max
@@ -781,6 +770,9 @@
 		goto err_nomem;
 	}
 
+	/* the spi->mode bits understood by this driver: */
+	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH | SPI_LSB_FIRST;
+
 	hw = spi_master_get_devdata(master);
 
 	hw->master = spi_master_get(master);
diff --git a/drivers/spi/mpc52xx_psc_spi.c b/drivers/spi/mpc52xx_psc_spi.c
index 68c77a9..1b74d5c 100644
--- a/drivers/spi/mpc52xx_psc_spi.c
+++ b/drivers/spi/mpc52xx_psc_spi.c
@@ -13,6 +13,7 @@
 
 #include <linux/module.h>
 #include <linux/init.h>
+#include <linux/types.h>
 #include <linux/errno.h>
 #include <linux/interrupt.h>
 #include <linux/of_platform.h>
@@ -30,8 +31,7 @@
 
 struct mpc52xx_psc_spi {
 	/* fsl_spi_platform data */
-	void (*activate_cs)(u8, u8);
-	void (*deactivate_cs)(u8, u8);
+	void (*cs_control)(struct spi_device *spi, bool on);
 	u32 sysclk;
 
 	/* driver internal data */
@@ -111,18 +111,16 @@
 	out_be16((u16 __iomem *)&psc->ccr, ccr);
 	mps->bits_per_word = cs->bits_per_word;
 
-	if (mps->activate_cs)
-		mps->activate_cs(spi->chip_select,
-				(spi->mode & SPI_CS_HIGH) ? 1 : 0);
+	if (mps->cs_control)
+		mps->cs_control(spi, (spi->mode & SPI_CS_HIGH) ? 1 : 0);
 }
 
 static void mpc52xx_psc_spi_deactivate_cs(struct spi_device *spi)
 {
 	struct mpc52xx_psc_spi *mps = spi_master_get_devdata(spi->master);
 
-	if (mps->deactivate_cs)
-		mps->deactivate_cs(spi->chip_select,
-				(spi->mode & SPI_CS_HIGH) ? 1 : 0);
+	if (mps->cs_control)
+		mps->cs_control(spi, (spi->mode & SPI_CS_HIGH) ? 0 : 1);
 }
 
 #define MPC52xx_PSC_BUFSIZE (MPC52xx_PSC_RFNUM_MASK + 1)
@@ -261,9 +259,6 @@
 	spin_unlock_irq(&mps->lock);
 }
 
-/* the spi->mode bits understood by this driver: */
-#define MODEBITS (SPI_CPOL | SPI_CPHA | SPI_CS_HIGH | SPI_LSB_FIRST)
-
 static int mpc52xx_psc_spi_setup(struct spi_device *spi)
 {
 	struct mpc52xx_psc_spi *mps = spi_master_get_devdata(spi->master);
@@ -273,12 +268,6 @@
 	if (spi->bits_per_word%8)
 		return -EINVAL;
 
-	if (spi->mode & ~MODEBITS) {
-		dev_dbg(&spi->dev, "setup: unsupported mode bits %x\n",
-			spi->mode & ~MODEBITS);
-		return -EINVAL;
-	}
-
 	if (!cs) {
 		cs = kzalloc(sizeof *cs, GFP_KERNEL);
 		if (!cs)
@@ -385,18 +374,19 @@
 	dev_set_drvdata(dev, master);
 	mps = spi_master_get_devdata(master);
 
+	/* the spi->mode bits understood by this driver: */
+	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH | SPI_LSB_FIRST;
+
 	mps->irq = irq;
 	if (pdata == NULL) {
 		dev_warn(dev, "probe called without platform data, no "
-				"(de)activate_cs function will be called\n");
-		mps->activate_cs = NULL;
-		mps->deactivate_cs = NULL;
+				"cs_control function will be called\n");
+		mps->cs_control = NULL;
 		mps->sysclk = 0;
 		master->bus_num = bus_num;
 		master->num_chipselect = 255;
 	} else {
-		mps->activate_cs = pdata->activate_cs;
-		mps->deactivate_cs = pdata->deactivate_cs;
+		mps->cs_control = pdata->cs_control;
 		mps->sysclk = pdata->sysclk;
 		master->bus_num = pdata->bus_num;
 		master->num_chipselect = pdata->max_chipselect;
diff --git a/drivers/spi/omap2_mcspi.c b/drivers/spi/omap2_mcspi.c
index d6d0c5d..eee4b6e 100644
--- a/drivers/spi/omap2_mcspi.c
+++ b/drivers/spi/omap2_mcspi.c
@@ -603,9 +603,6 @@
 	return 0;
 }
 
-/* the spi->mode bits understood by this driver: */
-#define MODEBITS (SPI_CPOL | SPI_CPHA | SPI_CS_HIGH)
-
 static int omap2_mcspi_setup(struct spi_device *spi)
 {
 	int			ret;
@@ -613,15 +610,7 @@
 	struct omap2_mcspi_dma	*mcspi_dma;
 	struct omap2_mcspi_cs	*cs = spi->controller_state;
 
-	if (spi->mode & ~MODEBITS) {
-		dev_dbg(&spi->dev, "setup: unsupported mode bits %x\n",
-			spi->mode & ~MODEBITS);
-		return -EINVAL;
-	}
-
-	if (spi->bits_per_word == 0)
-		spi->bits_per_word = 8;
-	else if (spi->bits_per_word < 4 || spi->bits_per_word > 32) {
+	if (spi->bits_per_word < 4 || spi->bits_per_word > 32) {
 		dev_dbg(&spi->dev, "setup: unsupported %d bit words\n",
 			spi->bits_per_word);
 		return -EINVAL;
@@ -984,6 +973,9 @@
 		return -ENOMEM;
 	}
 
+	/* the spi->mode bits understood by this driver: */
+	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH;
+
 	if (pdev->id != -1)
 		master->bus_num = pdev->id;
 
diff --git a/drivers/spi/omap_uwire.c b/drivers/spi/omap_uwire.c
index fe8b9ac..aa90ddb 100644
--- a/drivers/spi/omap_uwire.c
+++ b/drivers/spi/omap_uwire.c
@@ -339,8 +339,6 @@
 	bits = spi->bits_per_word;
 	if (t != NULL && t->bits_per_word)
 		bits = t->bits_per_word;
-	if (!bits)
-		bits = 8;
 
 	if (bits > 16) {
 		pr_debug("%s: wordsize %d?\n", dev_name(&spi->dev), bits);
@@ -449,19 +447,10 @@
 	return status;
 }
 
-/* the spi->mode bits understood by this driver: */
-#define MODEBITS (SPI_CPOL | SPI_CPHA | SPI_CS_HIGH)
-
 static int uwire_setup(struct spi_device *spi)
 {
 	struct uwire_state *ust = spi->controller_state;
 
-	if (spi->mode & ~MODEBITS) {
-		dev_dbg(&spi->dev, "setup: unsupported mode bits %x\n",
-			spi->mode & ~MODEBITS);
-		return -EINVAL;
-	}
-
 	if (ust == NULL) {
 		ust = kzalloc(sizeof(*ust), GFP_KERNEL);
 		if (ust == NULL)
@@ -522,6 +511,9 @@
 
 	uwire_write_reg(UWIRE_SR3, 1);
 
+	/* the spi->mode bits understood by this driver: */
+	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH;
+
 	master->bus_num = 2;	/* "official" */
 	master->num_chipselect = 4;
 	master->setup = uwire_setup;
diff --git a/drivers/spi/orion_spi.c b/drivers/spi/orion_spi.c
index c8b0bab..3aea50d 100644
--- a/drivers/spi/orion_spi.c
+++ b/drivers/spi/orion_spi.c
@@ -358,20 +358,11 @@
 
 	orion_spi = spi_master_get_devdata(spi->master);
 
-	if (spi->mode) {
-		dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
-			spi->mode);
-		return -EINVAL;
-	}
-
 	/* Fix ac timing if required.   */
 	if (orion_spi->spi_info->enable_clock_fix)
 		orion_spi_setbits(orion_spi, ORION_SPI_IF_CONFIG_REG,
 				  (1 << 14));
 
-	if (spi->bits_per_word == 0)
-		spi->bits_per_word = 8;
-
 	if ((spi->max_speed_hz == 0)
 			|| (spi->max_speed_hz > orion_spi->max_speed))
 		spi->max_speed_hz = orion_spi->max_speed;
@@ -476,6 +467,9 @@
 	if (pdev->id != -1)
 		master->bus_num = pdev->id;
 
+	/* we support only mode 0, and no options */
+	master->mode_bits = 0;
+
 	master->setup = orion_spi_setup;
 	master->transfer = orion_spi_transfer;
 	master->num_chipselect = ORION_NUM_CHIPSELECTS;
diff --git a/drivers/spi/pxa2xx_spi.c b/drivers/spi/pxa2xx_spi.c
index 3f3c08c..d949dbf 100644
--- a/drivers/spi/pxa2xx_spi.c
+++ b/drivers/spi/pxa2xx_spi.c
@@ -1185,9 +1185,6 @@
 	return 0;
 }
 
-/* the spi->mode bits understood by this driver: */
-#define MODEBITS (SPI_CPOL | SPI_CPHA)
-
 static int setup_cs(struct spi_device *spi, struct chip_data *chip,
 		    struct pxa2xx_spi_chip *chip_info)
 {
@@ -1236,9 +1233,6 @@
 	uint tx_thres = TX_THRESH_DFLT;
 	uint rx_thres = RX_THRESH_DFLT;
 
-	if (!spi->bits_per_word)
-		spi->bits_per_word = 8;
-
 	if (drv_data->ssp_type != PXA25x_SSP
 		&& (spi->bits_per_word < 4 || spi->bits_per_word > 32)) {
 		dev_err(&spi->dev, "failed setup: ssp_type=%d, bits/wrd=%d "
@@ -1255,12 +1249,6 @@
 		return -EINVAL;
 	}
 
-	if (spi->mode & ~MODEBITS) {
-		dev_dbg(&spi->dev, "setup: unsupported mode bits %x\n",
-			spi->mode & ~MODEBITS);
-		return -EINVAL;
-	}
-
 	/* Only alloc on first setup */
 	chip = spi_get_ctldata(spi);
 	if (!chip) {
@@ -1328,18 +1316,14 @@
 
 	/* NOTE:  PXA25x_SSP _could_ use external clocking ... */
 	if (drv_data->ssp_type != PXA25x_SSP)
-		dev_dbg(&spi->dev, "%d bits/word, %ld Hz, mode %d, %s\n",
-				spi->bits_per_word,
+		dev_dbg(&spi->dev, "%ld Hz actual, %s\n",
 				clk_get_rate(ssp->clk)
 					/ (1 + ((chip->cr0 & SSCR0_SCR) >> 8)),
-				spi->mode & 0x3,
 				chip->enable_dma ? "DMA" : "PIO");
 	else
-		dev_dbg(&spi->dev, "%d bits/word, %ld Hz, mode %d, %s\n",
-				spi->bits_per_word,
+		dev_dbg(&spi->dev, "%ld Hz actual, %s\n",
 				clk_get_rate(ssp->clk) / 2
 					/ (1 + ((chip->cr0 & SSCR0_SCR) >> 8)),
-				spi->mode & 0x3,
 				chip->enable_dma ? "DMA" : "PIO");
 
 	if (spi->bits_per_word <= 8) {
@@ -1500,6 +1484,9 @@
 	drv_data->pdev = pdev;
 	drv_data->ssp = ssp;
 
+	/* the spi->mode bits understood by this driver: */
+	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH;
+
 	master->bus_num = pdev->id;
 	master->num_chipselect = platform_info->num_chipselect;
 	master->dma_alignment = DMA_ALIGNMENT;
diff --git a/drivers/spi/spi.c b/drivers/spi/spi.c
index 8eba98c..70845ccd 100644
--- a/drivers/spi/spi.c
+++ b/drivers/spi/spi.c
@@ -265,7 +265,7 @@
 	 * normally rely on the device being setup.  Devices
 	 * using SPI_CS_HIGH can't coexist well otherwise...
 	 */
-	status = spi->master->setup(spi);
+	status = spi_setup(spi);
 	if (status < 0) {
 		dev_err(dev, "can't %s %s, status %d\n",
 				"setup", dev_name(&spi->dev), status);
@@ -583,6 +583,70 @@
 
 /*-------------------------------------------------------------------------*/
 
+/* Core methods for SPI master protocol drivers.  Some of the
+ * other core methods are currently defined as inline functions.
+ */
+
+/**
+ * spi_setup - setup SPI mode and clock rate
+ * @spi: the device whose settings are being modified
+ * Context: can sleep, and no requests are queued to the device
+ *
+ * SPI protocol drivers may need to update the transfer mode if the
+ * device doesn't work with its default.  They may likewise need
+ * to update clock rates or word sizes from initial values.  This function
+ * changes those settings, and must be called from a context that can sleep.
+ * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
+ * effect the next time the device is selected and data is transferred to
+ * or from it.  When this function returns, the spi device is deselected.
+ *
+ * Note that this call will fail if the protocol driver specifies an option
+ * that the underlying controller or its driver does not support.  For
+ * example, not all hardware supports wire transfers using nine bit words,
+ * LSB-first wire encoding, or active-high chipselects.
+ */
+int spi_setup(struct spi_device *spi)
+{
+	unsigned	bad_bits;
+	int		status;
+
+	/* help drivers fail *cleanly* when they need options
+	 * that aren't supported with their current master
+	 */
+	bad_bits = spi->mode & ~spi->master->mode_bits;
+	if (bad_bits) {
+		dev_dbg(&spi->dev, "setup: unsupported mode bits %x\n",
+			bad_bits);
+		return -EINVAL;
+	}
+
+	if (!spi->bits_per_word)
+		spi->bits_per_word = 8;
+
+	status = spi->master->setup(spi);
+
+	dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s"
+				"%u bits/w, %u Hz max --> %d\n",
+			(int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
+			(spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
+			(spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
+			(spi->mode & SPI_3WIRE) ? "3wire, " : "",
+			(spi->mode & SPI_LOOP) ? "loopback, " : "",
+			spi->bits_per_word, spi->max_speed_hz,
+			status);
+
+	return status;
+}
+EXPORT_SYMBOL_GPL(spi_setup);
+
+
+/*-------------------------------------------------------------------------*/
+
+/* Utility methods for SPI master protocol drivers, layered on
+ * top of the core.  Some other utility methods are defined as
+ * inline functions.
+ */
+
 static void spi_complete(void *arg)
 {
 	complete(arg);
@@ -636,8 +700,8 @@
  * @spi: device with which data will be exchanged
  * @txbuf: data to be written (need not be dma-safe)
  * @n_tx: size of txbuf, in bytes
- * @rxbuf: buffer into which data will be read
- * @n_rx: size of rxbuf, in bytes (need not be dma-safe)
+ * @rxbuf: buffer into which data will be read (need not be dma-safe)
+ * @n_rx: size of rxbuf, in bytes
  * Context: can sleep
  *
  * This performs a half duplex MicroWire style transaction with the
diff --git a/drivers/spi/spi_bfin5xx.c b/drivers/spi/spi_bfin5xx.c
index 011c5bd..73e24ef 100644
--- a/drivers/spi/spi_bfin5xx.c
+++ b/drivers/spi/spi_bfin5xx.c
@@ -169,7 +169,7 @@
 	unsigned long limit = loops_per_jiffy << 1;
 
 	/* wait for stop and clear stat */
-	while (!(read_STAT(drv_data) & BIT_STAT_SPIF) && limit--)
+	while (!(read_STAT(drv_data) & BIT_STAT_SPIF) && --limit)
 		cpu_relax();
 
 	write_STAT(drv_data, BIT_STAT_CLR);
@@ -1010,16 +1010,6 @@
 	struct driver_data *drv_data = spi_master_get_devdata(spi->master);
 	int ret;
 
-	/* Abort device setup if requested features are not supported */
-	if (spi->mode & ~(SPI_CPOL | SPI_CPHA | SPI_LSB_FIRST)) {
-		dev_err(&spi->dev, "requested mode not fully supported\n");
-		return -EINVAL;
-	}
-
-	/* Zero (the default) here means 8 bits */
-	if (!spi->bits_per_word)
-		spi->bits_per_word = 8;
-
 	if (spi->bits_per_word != 8 && spi->bits_per_word != 16)
 		return -EINVAL;
 
@@ -1287,6 +1277,9 @@
 	drv_data->pdev = pdev;
 	drv_data->pin_req = platform_info->pin_req;
 
+	/* the spi->mode bits supported by this driver: */
+	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_LSB_FIRST;
+
 	master->bus_num = pdev->id;
 	master->num_chipselect = platform_info->num_chipselect;
 	master->cleanup = bfin_spi_cleanup;
diff --git a/drivers/spi/spi_bitbang.c b/drivers/spi/spi_bitbang.c
index 85e61f4..2a5abc0 100644
--- a/drivers/spi/spi_bitbang.c
+++ b/drivers/spi/spi_bitbang.c
@@ -188,12 +188,6 @@
 
 	bitbang = spi_master_get_devdata(spi->master);
 
-	/* Bitbangers can support SPI_CS_HIGH, SPI_3WIRE, and so on;
-	 * add those to master->flags, and provide the other support.
-	 */
-	if ((spi->mode & ~(SPI_CPOL|SPI_CPHA|bitbang->flags)) != 0)
-		return -EINVAL;
-
 	if (!cs) {
 		cs = kzalloc(sizeof *cs, GFP_KERNEL);
 		if (!cs)
@@ -201,9 +195,6 @@
 		spi->controller_state = cs;
 	}
 
-	if (!spi->bits_per_word)
-		spi->bits_per_word = 8;
-
 	/* per-word shift register access, in hardware or bitbanging */
 	cs->txrx_word = bitbang->txrx_word[spi->mode & (SPI_CPOL|SPI_CPHA)];
 	if (!cs->txrx_word)
@@ -213,9 +204,7 @@
 	if (retval < 0)
 		return retval;
 
-	dev_dbg(&spi->dev, "%s, mode %d, %u bits/w, %u nsec/bit\n",
-			__func__, spi->mode & (SPI_CPOL | SPI_CPHA),
-			spi->bits_per_word, 2 * cs->nsecs);
+	dev_dbg(&spi->dev, "%s, %u nsec/bit\n", __func__, 2 * cs->nsecs);
 
 	/* NOTE we _need_ to call chipselect() early, ideally with adapter
 	 * setup, unless the hardware defaults cooperate to avoid confusion
@@ -457,6 +446,9 @@
 	spin_lock_init(&bitbang->lock);
 	INIT_LIST_HEAD(&bitbang->queue);
 
+	if (!bitbang->master->mode_bits)
+		bitbang->master->mode_bits = SPI_CPOL | SPI_CPHA | bitbang->flags;
+
 	if (!bitbang->master->transfer)
 		bitbang->master->transfer = spi_bitbang_transfer;
 	if (!bitbang->txrx_bufs) {
diff --git a/drivers/spi/spi_imx.c b/drivers/spi/spi_imx.c
index 0671aee..c195e45 100644
--- a/drivers/spi/spi_imx.c
+++ b/drivers/spi/spi_imx.c
@@ -1171,9 +1171,6 @@
 	return -EINVAL;
 }
 
-/* the spi->mode bits understood by this driver: */
-#define MODEBITS (SPI_CPOL | SPI_CPHA | SPI_CS_HIGH)
-
 /* On first setup bad values must free chip_data memory since will cause
    spi_new_device to fail. Bad value setup from protocol driver are simply not
    applied and notified to the calling driver. */
@@ -1186,12 +1183,6 @@
 	u32 tmp;
 	int status = 0;
 
-	if (spi->mode & ~MODEBITS) {
-		dev_dbg(&spi->dev, "setup: unsupported mode bits %x\n",
-			spi->mode & ~MODEBITS);
-		return -EINVAL;
-	}
-
 	/* Get controller data */
 	chip_info = spi->controller_data;
 
@@ -1286,10 +1277,7 @@
 
 	/* SPI word width */
 	tmp = spi->bits_per_word;
-	if (tmp == 0) {
-		tmp = 8;
-		spi->bits_per_word = 8;
-	} else if (tmp > 16) {
+	if (tmp > 16) {
 		status = -EINVAL;
 		dev_err(&spi->dev,
 			"setup - "
@@ -1481,6 +1469,9 @@
 	drv_data->master_info = platform_info;
 	drv_data->pdev = pdev;
 
+	/* the spi->mode bits understood by this driver: */
+	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH;
+
 	master->bus_num = pdev->id;
 	master->num_chipselect = platform_info->num_chipselect;
 	master->dma_alignment = DMA_ALIGNMENT;
diff --git a/drivers/spi/spi_mpc83xx.c b/drivers/spi/spi_mpc83xx.c
deleted file mode 100644
index a32ccb4..0000000
--- a/drivers/spi/spi_mpc83xx.c
+++ /dev/null
@@ -1,966 +0,0 @@
-/*
- * MPC83xx SPI controller driver.
- *
- * Maintainer: Kumar Gala
- *
- * Copyright (C) 2006 Polycom, Inc.
- *
- * This program is free software; you can redistribute  it and/or modify it
- * under  the terms of  the GNU General  Public License as published by the
- * Free Software Foundation;  either version 2 of the  License, or (at your
- * option) any later version.
- */
-#include <linux/module.h>
-#include <linux/init.h>
-#include <linux/types.h>
-#include <linux/kernel.h>
-#include <linux/errno.h>
-#include <linux/err.h>
-#include <linux/completion.h>
-#include <linux/interrupt.h>
-#include <linux/delay.h>
-#include <linux/irq.h>
-#include <linux/device.h>
-#include <linux/spi/spi.h>
-#include <linux/spi/spi_bitbang.h>
-#include <linux/platform_device.h>
-#include <linux/fsl_devices.h>
-#include <linux/of.h>
-#include <linux/of_platform.h>
-#include <linux/gpio.h>
-#include <linux/of_gpio.h>
-#include <linux/of_spi.h>
-
-#include <sysdev/fsl_soc.h>
-#include <asm/irq.h>
-#include <asm/io.h>
-
-/* SPI Controller registers */
-struct mpc83xx_spi_reg {
-	u8 res1[0x20];
-	__be32 mode;
-	__be32 event;
-	__be32 mask;
-	__be32 command;
-	__be32 transmit;
-	__be32 receive;
-};
-
-/* SPI Controller mode register definitions */
-#define	SPMODE_LOOP		(1 << 30)
-#define	SPMODE_CI_INACTIVEHIGH	(1 << 29)
-#define	SPMODE_CP_BEGIN_EDGECLK	(1 << 28)
-#define	SPMODE_DIV16		(1 << 27)
-#define	SPMODE_REV		(1 << 26)
-#define	SPMODE_MS		(1 << 25)
-#define	SPMODE_ENABLE		(1 << 24)
-#define	SPMODE_LEN(x)		((x) << 20)
-#define	SPMODE_PM(x)		((x) << 16)
-#define	SPMODE_OP		(1 << 14)
-#define	SPMODE_CG(x)		((x) << 7)
-
-/*
- * Default for SPI Mode:
- * 	SPI MODE 0 (inactive low, phase middle, MSB, 8-bit length, slow clk
- */
-#define	SPMODE_INIT_VAL (SPMODE_CI_INACTIVEHIGH | SPMODE_DIV16 | SPMODE_REV | \
-			 SPMODE_MS | SPMODE_LEN(7) | SPMODE_PM(0xf))
-
-/* SPIE register values */
-#define	SPIE_NE		0x00000200	/* Not empty */
-#define	SPIE_NF		0x00000100	/* Not full */
-
-/* SPIM register values */
-#define	SPIM_NE		0x00000200	/* Not empty */
-#define	SPIM_NF		0x00000100	/* Not full */
-
-/* SPI Controller driver's private data. */
-struct mpc83xx_spi {
-	struct mpc83xx_spi_reg __iomem *base;
-
-	/* rx & tx bufs from the spi_transfer */
-	const void *tx;
-	void *rx;
-
-	/* functions to deal with different sized buffers */
-	void (*get_rx) (u32 rx_data, struct mpc83xx_spi *);
-	u32(*get_tx) (struct mpc83xx_spi *);
-
-	unsigned int count;
-	unsigned int irq;
-
-	unsigned nsecs;		/* (clock cycle time)/2 */
-
-	u32 spibrg;		/* SPIBRG input clock */
-	u32 rx_shift;		/* RX data reg shift when in qe mode */
-	u32 tx_shift;		/* TX data reg shift when in qe mode */
-
-	bool qe_mode;
-
-	u8 busy;
-
-	struct workqueue_struct *workqueue;
-	struct work_struct work;
-
-	struct list_head queue;
-	spinlock_t lock;
-
-	struct completion done;
-};
-
-struct spi_mpc83xx_cs {
-	/* functions to deal with different sized buffers */
-	void (*get_rx) (u32 rx_data, struct mpc83xx_spi *);
-	u32 (*get_tx) (struct mpc83xx_spi *);
-	u32 rx_shift;		/* RX data reg shift when in qe mode */
-	u32 tx_shift;		/* TX data reg shift when in qe mode */
-	u32 hw_mode;		/* Holds HW mode register settings */
-};
-
-static inline void mpc83xx_spi_write_reg(__be32 __iomem * reg, u32 val)
-{
-	out_be32(reg, val);
-}
-
-static inline u32 mpc83xx_spi_read_reg(__be32 __iomem * reg)
-{
-	return in_be32(reg);
-}
-
-#define MPC83XX_SPI_RX_BUF(type) 					  \
-static									  \
-void mpc83xx_spi_rx_buf_##type(u32 data, struct mpc83xx_spi *mpc83xx_spi) \
-{									  \
-	type * rx = mpc83xx_spi->rx;					  \
-	*rx++ = (type)(data >> mpc83xx_spi->rx_shift);			  \
-	mpc83xx_spi->rx = rx;						  \
-}
-
-#define MPC83XX_SPI_TX_BUF(type)				\
-static								\
-u32 mpc83xx_spi_tx_buf_##type(struct mpc83xx_spi *mpc83xx_spi)	\
-{								\
-	u32 data;						\
-	const type * tx = mpc83xx_spi->tx;			\
-	if (!tx)						\
-		return 0;					\
-	data = *tx++ << mpc83xx_spi->tx_shift;			\
-	mpc83xx_spi->tx = tx;					\
-	return data;						\
-}
-
-MPC83XX_SPI_RX_BUF(u8)
-MPC83XX_SPI_RX_BUF(u16)
-MPC83XX_SPI_RX_BUF(u32)
-MPC83XX_SPI_TX_BUF(u8)
-MPC83XX_SPI_TX_BUF(u16)
-MPC83XX_SPI_TX_BUF(u32)
-
-static void mpc83xx_spi_chipselect(struct spi_device *spi, int value)
-{
-	struct mpc83xx_spi *mpc83xx_spi = spi_master_get_devdata(spi->master);
-	struct fsl_spi_platform_data *pdata = spi->dev.parent->platform_data;
-	bool pol = spi->mode & SPI_CS_HIGH;
-	struct spi_mpc83xx_cs	*cs = spi->controller_state;
-
-	if (value == BITBANG_CS_INACTIVE) {
-		if (pdata->cs_control)
-			pdata->cs_control(spi, !pol);
-	}
-
-	if (value == BITBANG_CS_ACTIVE) {
-		u32 regval = mpc83xx_spi_read_reg(&mpc83xx_spi->base->mode);
-
-		mpc83xx_spi->rx_shift = cs->rx_shift;
-		mpc83xx_spi->tx_shift = cs->tx_shift;
-		mpc83xx_spi->get_rx = cs->get_rx;
-		mpc83xx_spi->get_tx = cs->get_tx;
-
-		if (cs->hw_mode != regval) {
-			unsigned long flags;
-			__be32 __iomem *mode = &mpc83xx_spi->base->mode;
-
-			regval = cs->hw_mode;
-			/* Turn off IRQs locally to minimize time that
-			 * SPI is disabled
-			 */
-			local_irq_save(flags);
-			/* Turn off SPI unit prior changing mode */
-			mpc83xx_spi_write_reg(mode, regval & ~SPMODE_ENABLE);
-			mpc83xx_spi_write_reg(mode, regval);
-			local_irq_restore(flags);
-		}
-		if (pdata->cs_control)
-			pdata->cs_control(spi, pol);
-	}
-}
-
-static
-int mpc83xx_spi_setup_transfer(struct spi_device *spi, struct spi_transfer *t)
-{
-	struct mpc83xx_spi *mpc83xx_spi;
-	u32 regval;
-	u8 bits_per_word, pm;
-	u32 hz;
-	struct spi_mpc83xx_cs	*cs = spi->controller_state;
-
-	mpc83xx_spi = spi_master_get_devdata(spi->master);
-
-	if (t) {
-		bits_per_word = t->bits_per_word;
-		hz = t->speed_hz;
-	} else {
-		bits_per_word = 0;
-		hz = 0;
-	}
-
-	/* spi_transfer level calls that work per-word */
-	if (!bits_per_word)
-		bits_per_word = spi->bits_per_word;
-
-	/* Make sure its a bit width we support [4..16, 32] */
-	if ((bits_per_word < 4)
-	    || ((bits_per_word > 16) && (bits_per_word != 32)))
-		return -EINVAL;
-
-	if (!hz)
-		hz = spi->max_speed_hz;
-
-	cs->rx_shift = 0;
-	cs->tx_shift = 0;
-	if (bits_per_word <= 8) {
-		cs->get_rx = mpc83xx_spi_rx_buf_u8;
-		cs->get_tx = mpc83xx_spi_tx_buf_u8;
-		if (mpc83xx_spi->qe_mode) {
-			cs->rx_shift = 16;
-			cs->tx_shift = 24;
-		}
-	} else if (bits_per_word <= 16) {
-		cs->get_rx = mpc83xx_spi_rx_buf_u16;
-		cs->get_tx = mpc83xx_spi_tx_buf_u16;
-		if (mpc83xx_spi->qe_mode) {
-			cs->rx_shift = 16;
-			cs->tx_shift = 16;
-		}
-	} else if (bits_per_word <= 32) {
-		cs->get_rx = mpc83xx_spi_rx_buf_u32;
-		cs->get_tx = mpc83xx_spi_tx_buf_u32;
-	} else
-		return -EINVAL;
-
-	if (mpc83xx_spi->qe_mode && spi->mode & SPI_LSB_FIRST) {
-		cs->tx_shift = 0;
-		if (bits_per_word <= 8)
-			cs->rx_shift = 8;
-		else
-			cs->rx_shift = 0;
-	}
-
-	mpc83xx_spi->rx_shift = cs->rx_shift;
-	mpc83xx_spi->tx_shift = cs->tx_shift;
-	mpc83xx_spi->get_rx = cs->get_rx;
-	mpc83xx_spi->get_tx = cs->get_tx;
-
-	if (bits_per_word == 32)
-		bits_per_word = 0;
-	else
-		bits_per_word = bits_per_word - 1;
-
-	/* mask out bits we are going to set */
-	cs->hw_mode &= ~(SPMODE_LEN(0xF) | SPMODE_DIV16
-				  | SPMODE_PM(0xF));
-
-	cs->hw_mode |= SPMODE_LEN(bits_per_word);
-
-	if ((mpc83xx_spi->spibrg / hz) > 64) {
-		cs->hw_mode |= SPMODE_DIV16;
-		pm = mpc83xx_spi->spibrg / (hz * 64);
-		if (pm > 16) {
-			dev_err(&spi->dev, "Requested speed is too "
-				"low: %d Hz. Will use %d Hz instead.\n",
-				hz, mpc83xx_spi->spibrg / 1024);
-			pm = 16;
-		}
-	} else
-		pm = mpc83xx_spi->spibrg / (hz * 4);
-	if (pm)
-		pm--;
-
-	cs->hw_mode |= SPMODE_PM(pm);
-	regval =  mpc83xx_spi_read_reg(&mpc83xx_spi->base->mode);
-	if (cs->hw_mode != regval) {
-		unsigned long flags;
-		__be32 __iomem *mode = &mpc83xx_spi->base->mode;
-
-		regval = cs->hw_mode;
-		/* Turn off IRQs locally to minimize time
-		 * that SPI is disabled
-		 */
-		local_irq_save(flags);
-		/* Turn off SPI unit prior changing mode */
-		mpc83xx_spi_write_reg(mode, regval & ~SPMODE_ENABLE);
-		mpc83xx_spi_write_reg(mode, regval);
-		local_irq_restore(flags);
-	}
-	return 0;
-}
-
-static int mpc83xx_spi_bufs(struct spi_device *spi, struct spi_transfer *t)
-{
-	struct mpc83xx_spi *mpc83xx_spi;
-	u32 word, len, bits_per_word;
-
-	mpc83xx_spi = spi_master_get_devdata(spi->master);
-
-	mpc83xx_spi->tx = t->tx_buf;
-	mpc83xx_spi->rx = t->rx_buf;
-	bits_per_word = spi->bits_per_word;
-	if (t->bits_per_word)
-		bits_per_word = t->bits_per_word;
-	len = t->len;
-	if (bits_per_word > 8) {
-		/* invalid length? */
-		if (len & 1)
-			return -EINVAL;
-		len /= 2;
-	}
-	if (bits_per_word > 16) {
-		/* invalid length? */
-		if (len & 1)
-			return -EINVAL;
-		len /= 2;
-	}
-	mpc83xx_spi->count = len;
-
-	INIT_COMPLETION(mpc83xx_spi->done);
-
-	/* enable rx ints */
-	mpc83xx_spi_write_reg(&mpc83xx_spi->base->mask, SPIM_NE);
-
-	/* transmit word */
-	word = mpc83xx_spi->get_tx(mpc83xx_spi);
-	mpc83xx_spi_write_reg(&mpc83xx_spi->base->transmit, word);
-
-	wait_for_completion(&mpc83xx_spi->done);
-
-	/* disable rx ints */
-	mpc83xx_spi_write_reg(&mpc83xx_spi->base->mask, 0);
-
-	return mpc83xx_spi->count;
-}
-
-static void mpc83xx_spi_work(struct work_struct *work)
-{
-	struct mpc83xx_spi *mpc83xx_spi =
-		container_of(work, struct mpc83xx_spi, work);
-
-	spin_lock_irq(&mpc83xx_spi->lock);
-	mpc83xx_spi->busy = 1;
-	while (!list_empty(&mpc83xx_spi->queue)) {
-		struct spi_message *m;
-		struct spi_device *spi;
-		struct spi_transfer *t = NULL;
-		unsigned cs_change;
-		int status, nsecs = 50;
-
-		m = container_of(mpc83xx_spi->queue.next,
-				struct spi_message, queue);
-		list_del_init(&m->queue);
-		spin_unlock_irq(&mpc83xx_spi->lock);
-
-		spi = m->spi;
-		cs_change = 1;
-		status = 0;
-		list_for_each_entry(t, &m->transfers, transfer_list) {
-			if (t->bits_per_word || t->speed_hz) {
-				/* Don't allow changes if CS is active */
-				status = -EINVAL;
-
-				if (cs_change)
-					status = mpc83xx_spi_setup_transfer(spi, t);
-				if (status < 0)
-					break;
-			}
-
-			if (cs_change)
-				mpc83xx_spi_chipselect(spi, BITBANG_CS_ACTIVE);
-			cs_change = t->cs_change;
-			if (t->len)
-				status = mpc83xx_spi_bufs(spi, t);
-			if (status) {
-				status = -EMSGSIZE;
-				break;
-			}
-			m->actual_length += t->len;
-
-			if (t->delay_usecs)
-				udelay(t->delay_usecs);
-
-			if (cs_change) {
-				ndelay(nsecs);
-				mpc83xx_spi_chipselect(spi, BITBANG_CS_INACTIVE);
-				ndelay(nsecs);
-			}
-		}
-
-		m->status = status;
-		m->complete(m->context);
-
-		if (status || !cs_change) {
-			ndelay(nsecs);
-			mpc83xx_spi_chipselect(spi, BITBANG_CS_INACTIVE);
-		}
-
-		mpc83xx_spi_setup_transfer(spi, NULL);
-
-		spin_lock_irq(&mpc83xx_spi->lock);
-	}
-	mpc83xx_spi->busy = 0;
-	spin_unlock_irq(&mpc83xx_spi->lock);
-}
-
-/* the spi->mode bits understood by this driver: */
-#define MODEBITS	(SPI_CPOL | SPI_CPHA | SPI_CS_HIGH \
-			| SPI_LSB_FIRST | SPI_LOOP)
-
-static int mpc83xx_spi_setup(struct spi_device *spi)
-{
-	struct mpc83xx_spi *mpc83xx_spi;
-	int retval;
-	u32 hw_mode;
-	struct spi_mpc83xx_cs	*cs = spi->controller_state;
-
-	if (spi->mode & ~MODEBITS) {
-		dev_dbg(&spi->dev, "setup: unsupported mode bits %x\n",
-			spi->mode & ~MODEBITS);
-		return -EINVAL;
-	}
-
-	if (!spi->max_speed_hz)
-		return -EINVAL;
-
-	if (!cs) {
-		cs = kzalloc(sizeof *cs, GFP_KERNEL);
-		if (!cs)
-			return -ENOMEM;
-		spi->controller_state = cs;
-	}
-	mpc83xx_spi = spi_master_get_devdata(spi->master);
-
-	if (!spi->bits_per_word)
-		spi->bits_per_word = 8;
-
-	hw_mode = cs->hw_mode; /* Save orginal settings */
-	cs->hw_mode = mpc83xx_spi_read_reg(&mpc83xx_spi->base->mode);
-	/* mask out bits we are going to set */
-	cs->hw_mode &= ~(SPMODE_CP_BEGIN_EDGECLK | SPMODE_CI_INACTIVEHIGH
-			 | SPMODE_REV | SPMODE_LOOP);
-
-	if (spi->mode & SPI_CPHA)
-		cs->hw_mode |= SPMODE_CP_BEGIN_EDGECLK;
-	if (spi->mode & SPI_CPOL)
-		cs->hw_mode |= SPMODE_CI_INACTIVEHIGH;
-	if (!(spi->mode & SPI_LSB_FIRST))
-		cs->hw_mode |= SPMODE_REV;
-	if (spi->mode & SPI_LOOP)
-		cs->hw_mode |= SPMODE_LOOP;
-
-	retval = mpc83xx_spi_setup_transfer(spi, NULL);
-	if (retval < 0) {
-		cs->hw_mode = hw_mode; /* Restore settings */
-		return retval;
-	}
-
-	dev_dbg(&spi->dev, "%s, mode %d, %u bits/w, %u Hz\n",
-		__func__, spi->mode & (SPI_CPOL | SPI_CPHA),
-		spi->bits_per_word, spi->max_speed_hz);
-#if 0 /* Don't think this is needed */
-	/* NOTE we _need_ to call chipselect() early, ideally with adapter
-	 * setup, unless the hardware defaults cooperate to avoid confusion
-	 * between normal (active low) and inverted chipselects.
-	 */
-
-	/* deselect chip (low or high) */
-	spin_lock(&mpc83xx_spi->lock);
-	if (!mpc83xx_spi->busy)
-		mpc83xx_spi_chipselect(spi, BITBANG_CS_INACTIVE);
-	spin_unlock(&mpc83xx_spi->lock);
-#endif
-	return 0;
-}
-
-static irqreturn_t mpc83xx_spi_irq(s32 irq, void *context_data)
-{
-	struct mpc83xx_spi *mpc83xx_spi = context_data;
-	u32 event;
-	irqreturn_t ret = IRQ_NONE;
-
-	/* Get interrupt events(tx/rx) */
-	event = mpc83xx_spi_read_reg(&mpc83xx_spi->base->event);
-
-	/* We need handle RX first */
-	if (event & SPIE_NE) {
-		u32 rx_data = mpc83xx_spi_read_reg(&mpc83xx_spi->base->receive);
-
-		if (mpc83xx_spi->rx)
-			mpc83xx_spi->get_rx(rx_data, mpc83xx_spi);
-
-		ret = IRQ_HANDLED;
-	}
-
-	if ((event & SPIE_NF) == 0)
-		/* spin until TX is done */
-		while (((event =
-			 mpc83xx_spi_read_reg(&mpc83xx_spi->base->event)) &
-						SPIE_NF) == 0)
-			 cpu_relax();
-
-	mpc83xx_spi->count -= 1;
-	if (mpc83xx_spi->count) {
-		u32 word = mpc83xx_spi->get_tx(mpc83xx_spi);
-		mpc83xx_spi_write_reg(&mpc83xx_spi->base->transmit, word);
-	} else {
-		complete(&mpc83xx_spi->done);
-	}
-
-	/* Clear the events */
-	mpc83xx_spi_write_reg(&mpc83xx_spi->base->event, event);
-
-	return ret;
-}
-static int mpc83xx_spi_transfer(struct spi_device *spi,
-				struct spi_message *m)
-{
-	struct mpc83xx_spi *mpc83xx_spi = spi_master_get_devdata(spi->master);
-	unsigned long flags;
-
-	m->actual_length = 0;
-	m->status = -EINPROGRESS;
-
-	spin_lock_irqsave(&mpc83xx_spi->lock, flags);
-	list_add_tail(&m->queue, &mpc83xx_spi->queue);
-	queue_work(mpc83xx_spi->workqueue, &mpc83xx_spi->work);
-	spin_unlock_irqrestore(&mpc83xx_spi->lock, flags);
-
-	return 0;
-}
-
-
-static void mpc83xx_spi_cleanup(struct spi_device *spi)
-{
-	kfree(spi->controller_state);
-}
-
-static struct spi_master * __devinit
-mpc83xx_spi_probe(struct device *dev, struct resource *mem, unsigned int irq)
-{
-	struct fsl_spi_platform_data *pdata = dev->platform_data;
-	struct spi_master *master;
-	struct mpc83xx_spi *mpc83xx_spi;
-	u32 regval;
-	int ret = 0;
-
-	master = spi_alloc_master(dev, sizeof(struct mpc83xx_spi));
-	if (master == NULL) {
-		ret = -ENOMEM;
-		goto err;
-	}
-
-	dev_set_drvdata(dev, master);
-
-	master->setup = mpc83xx_spi_setup;
-	master->transfer = mpc83xx_spi_transfer;
-	master->cleanup = mpc83xx_spi_cleanup;
-
-	mpc83xx_spi = spi_master_get_devdata(master);
-	mpc83xx_spi->qe_mode = pdata->qe_mode;
-	mpc83xx_spi->get_rx = mpc83xx_spi_rx_buf_u8;
-	mpc83xx_spi->get_tx = mpc83xx_spi_tx_buf_u8;
-	mpc83xx_spi->spibrg = pdata->sysclk;
-
-	mpc83xx_spi->rx_shift = 0;
-	mpc83xx_spi->tx_shift = 0;
-	if (mpc83xx_spi->qe_mode) {
-		mpc83xx_spi->rx_shift = 16;
-		mpc83xx_spi->tx_shift = 24;
-	}
-
-	init_completion(&mpc83xx_spi->done);
-
-	mpc83xx_spi->base = ioremap(mem->start, mem->end - mem->start + 1);
-	if (mpc83xx_spi->base == NULL) {
-		ret = -ENOMEM;
-		goto put_master;
-	}
-
-	mpc83xx_spi->irq = irq;
-
-	/* Register for SPI Interrupt */
-	ret = request_irq(mpc83xx_spi->irq, mpc83xx_spi_irq,
-			  0, "mpc83xx_spi", mpc83xx_spi);
-
-	if (ret != 0)
-		goto unmap_io;
-
-	master->bus_num = pdata->bus_num;
-	master->num_chipselect = pdata->max_chipselect;
-
-	/* SPI controller initializations */
-	mpc83xx_spi_write_reg(&mpc83xx_spi->base->mode, 0);
-	mpc83xx_spi_write_reg(&mpc83xx_spi->base->mask, 0);
-	mpc83xx_spi_write_reg(&mpc83xx_spi->base->command, 0);
-	mpc83xx_spi_write_reg(&mpc83xx_spi->base->event, 0xffffffff);
-
-	/* Enable SPI interface */
-	regval = pdata->initial_spmode | SPMODE_INIT_VAL | SPMODE_ENABLE;
-	if (pdata->qe_mode)
-		regval |= SPMODE_OP;
-
-	mpc83xx_spi_write_reg(&mpc83xx_spi->base->mode, regval);
-	spin_lock_init(&mpc83xx_spi->lock);
-	init_completion(&mpc83xx_spi->done);
-	INIT_WORK(&mpc83xx_spi->work, mpc83xx_spi_work);
-	INIT_LIST_HEAD(&mpc83xx_spi->queue);
-
-	mpc83xx_spi->workqueue = create_singlethread_workqueue(
-		dev_name(master->dev.parent));
-	if (mpc83xx_spi->workqueue == NULL) {
-		ret = -EBUSY;
-		goto free_irq;
-	}
-
-	ret = spi_register_master(master);
-	if (ret < 0)
-		goto unreg_master;
-
-	printk(KERN_INFO
-	       "%s: MPC83xx SPI Controller driver at 0x%p (irq = %d)\n",
-	       dev_name(dev), mpc83xx_spi->base, mpc83xx_spi->irq);
-
-	return master;
-
-unreg_master:
-	destroy_workqueue(mpc83xx_spi->workqueue);
-free_irq:
-	free_irq(mpc83xx_spi->irq, mpc83xx_spi);
-unmap_io:
-	iounmap(mpc83xx_spi->base);
-put_master:
-	spi_master_put(master);
-err:
-	return ERR_PTR(ret);
-}
-
-static int __devexit mpc83xx_spi_remove(struct device *dev)
-{
-	struct mpc83xx_spi *mpc83xx_spi;
-	struct spi_master *master;
-
-	master = dev_get_drvdata(dev);
-	mpc83xx_spi = spi_master_get_devdata(master);
-
-	flush_workqueue(mpc83xx_spi->workqueue);
-	destroy_workqueue(mpc83xx_spi->workqueue);
-	spi_unregister_master(master);
-
-	free_irq(mpc83xx_spi->irq, mpc83xx_spi);
-	iounmap(mpc83xx_spi->base);
-
-	return 0;
-}
-
-struct mpc83xx_spi_probe_info {
-	struct fsl_spi_platform_data pdata;
-	int *gpios;
-	bool *alow_flags;
-};
-
-static struct mpc83xx_spi_probe_info *
-to_of_pinfo(struct fsl_spi_platform_data *pdata)
-{
-	return container_of(pdata, struct mpc83xx_spi_probe_info, pdata);
-}
-
-static void mpc83xx_spi_cs_control(struct spi_device *spi, bool on)
-{
-	struct device *dev = spi->dev.parent;
-	struct mpc83xx_spi_probe_info *pinfo = to_of_pinfo(dev->platform_data);
-	u16 cs = spi->chip_select;
-	int gpio = pinfo->gpios[cs];
-	bool alow = pinfo->alow_flags[cs];
-
-	gpio_set_value(gpio, on ^ alow);
-}
-
-static int of_mpc83xx_spi_get_chipselects(struct device *dev)
-{
-	struct device_node *np = dev_archdata_get_node(&dev->archdata);
-	struct fsl_spi_platform_data *pdata = dev->platform_data;
-	struct mpc83xx_spi_probe_info *pinfo = to_of_pinfo(pdata);
-	unsigned int ngpios;
-	int i = 0;
-	int ret;
-
-	ngpios = of_gpio_count(np);
-	if (!ngpios) {
-		/*
-		 * SPI w/o chip-select line. One SPI device is still permitted
-		 * though.
-		 */
-		pdata->max_chipselect = 1;
-		return 0;
-	}
-
-	pinfo->gpios = kmalloc(ngpios * sizeof(*pinfo->gpios), GFP_KERNEL);
-	if (!pinfo->gpios)
-		return -ENOMEM;
-	memset(pinfo->gpios, -1, ngpios * sizeof(*pinfo->gpios));
-
-	pinfo->alow_flags = kzalloc(ngpios * sizeof(*pinfo->alow_flags),
-				    GFP_KERNEL);
-	if (!pinfo->alow_flags) {
-		ret = -ENOMEM;
-		goto err_alloc_flags;
-	}
-
-	for (; i < ngpios; i++) {
-		int gpio;
-		enum of_gpio_flags flags;
-
-		gpio = of_get_gpio_flags(np, i, &flags);
-		if (!gpio_is_valid(gpio)) {
-			dev_err(dev, "invalid gpio #%d: %d\n", i, gpio);
-			goto err_loop;
-		}
-
-		ret = gpio_request(gpio, dev_name(dev));
-		if (ret) {
-			dev_err(dev, "can't request gpio #%d: %d\n", i, ret);
-			goto err_loop;
-		}
-
-		pinfo->gpios[i] = gpio;
-		pinfo->alow_flags[i] = flags & OF_GPIO_ACTIVE_LOW;
-
-		ret = gpio_direction_output(pinfo->gpios[i],
-					    pinfo->alow_flags[i]);
-		if (ret) {
-			dev_err(dev, "can't set output direction for gpio "
-				"#%d: %d\n", i, ret);
-			goto err_loop;
-		}
-	}
-
-	pdata->max_chipselect = ngpios;
-	pdata->cs_control = mpc83xx_spi_cs_control;
-
-	return 0;
-
-err_loop:
-	while (i >= 0) {
-		if (gpio_is_valid(pinfo->gpios[i]))
-			gpio_free(pinfo->gpios[i]);
-		i--;
-	}
-
-	kfree(pinfo->alow_flags);
-	pinfo->alow_flags = NULL;
-err_alloc_flags:
-	kfree(pinfo->gpios);
-	pinfo->gpios = NULL;
-	return ret;
-}
-
-static int of_mpc83xx_spi_free_chipselects(struct device *dev)
-{
-	struct fsl_spi_platform_data *pdata = dev->platform_data;
-	struct mpc83xx_spi_probe_info *pinfo = to_of_pinfo(pdata);
-	int i;
-
-	if (!pinfo->gpios)
-		return 0;
-
-	for (i = 0; i < pdata->max_chipselect; i++) {
-		if (gpio_is_valid(pinfo->gpios[i]))
-			gpio_free(pinfo->gpios[i]);
-	}
-
-	kfree(pinfo->gpios);
-	kfree(pinfo->alow_flags);
-	return 0;
-}
-
-static int __devinit of_mpc83xx_spi_probe(struct of_device *ofdev,
-					  const struct of_device_id *ofid)
-{
-	struct device *dev = &ofdev->dev;
-	struct device_node *np = ofdev->node;
-	struct mpc83xx_spi_probe_info *pinfo;
-	struct fsl_spi_platform_data *pdata;
-	struct spi_master *master;
-	struct resource mem;
-	struct resource irq;
-	const void *prop;
-	int ret = -ENOMEM;
-
-	pinfo = kzalloc(sizeof(*pinfo), GFP_KERNEL);
-	if (!pinfo)
-		return -ENOMEM;
-
-	pdata = &pinfo->pdata;
-	dev->platform_data = pdata;
-
-	/* Allocate bus num dynamically. */
-	pdata->bus_num = -1;
-
-	/* SPI controller is either clocked from QE or SoC clock. */
-	pdata->sysclk = get_brgfreq();
-	if (pdata->sysclk == -1) {
-		pdata->sysclk = fsl_get_sys_freq();
-		if (pdata->sysclk == -1) {
-			ret = -ENODEV;
-			goto err_clk;
-		}
-	}
-
-	prop = of_get_property(np, "mode", NULL);
-	if (prop && !strcmp(prop, "cpu-qe"))
-		pdata->qe_mode = 1;
-
-	ret = of_mpc83xx_spi_get_chipselects(dev);
-	if (ret)
-		goto err;
-
-	ret = of_address_to_resource(np, 0, &mem);
-	if (ret)
-		goto err;
-
-	ret = of_irq_to_resource(np, 0, &irq);
-	if (!ret) {
-		ret = -EINVAL;
-		goto err;
-	}
-
-	master = mpc83xx_spi_probe(dev, &mem, irq.start);
-	if (IS_ERR(master)) {
-		ret = PTR_ERR(master);
-		goto err;
-	}
-
-	of_register_spi_devices(master, np);
-
-	return 0;
-
-err:
-	of_mpc83xx_spi_free_chipselects(dev);
-err_clk:
-	kfree(pinfo);
-	return ret;
-}
-
-static int __devexit of_mpc83xx_spi_remove(struct of_device *ofdev)
-{
-	int ret;
-
-	ret = mpc83xx_spi_remove(&ofdev->dev);
-	if (ret)
-		return ret;
-	of_mpc83xx_spi_free_chipselects(&ofdev->dev);
-	return 0;
-}
-
-static const struct of_device_id of_mpc83xx_spi_match[] = {
-	{ .compatible = "fsl,spi" },
-	{},
-};
-MODULE_DEVICE_TABLE(of, of_mpc83xx_spi_match);
-
-static struct of_platform_driver of_mpc83xx_spi_driver = {
-	.name		= "mpc83xx_spi",
-	.match_table	= of_mpc83xx_spi_match,
-	.probe		= of_mpc83xx_spi_probe,
-	.remove		= __devexit_p(of_mpc83xx_spi_remove),
-};
-
-#ifdef CONFIG_MPC832x_RDB
-/*
- * 				XXX XXX XXX
- * This is "legacy" platform driver, was used by the MPC8323E-RDB boards
- * only. The driver should go away soon, since newer MPC8323E-RDB's device
- * tree can work with OpenFirmware driver. But for now we support old trees
- * as well.
- */
-static int __devinit plat_mpc83xx_spi_probe(struct platform_device *pdev)
-{
-	struct resource *mem;
-	unsigned int irq;
-	struct spi_master *master;
-
-	if (!pdev->dev.platform_data)
-		return -EINVAL;
-
-	mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
-	if (!mem)
-		return -EINVAL;
-
-	irq = platform_get_irq(pdev, 0);
-	if (!irq)
-		return -EINVAL;
-
-	master = mpc83xx_spi_probe(&pdev->dev, mem, irq);
-	if (IS_ERR(master))
-		return PTR_ERR(master);
-	return 0;
-}
-
-static int __devexit plat_mpc83xx_spi_remove(struct platform_device *pdev)
-{
-	return mpc83xx_spi_remove(&pdev->dev);
-}
-
-MODULE_ALIAS("platform:mpc83xx_spi");
-static struct platform_driver mpc83xx_spi_driver = {
-	.probe = plat_mpc83xx_spi_probe,
-	.remove = __exit_p(plat_mpc83xx_spi_remove),
-	.driver = {
-		.name = "mpc83xx_spi",
-		.owner = THIS_MODULE,
-	},
-};
-
-static bool legacy_driver_failed;
-
-static void __init legacy_driver_register(void)
-{
-	legacy_driver_failed = platform_driver_register(&mpc83xx_spi_driver);
-}
-
-static void __exit legacy_driver_unregister(void)
-{
-	if (legacy_driver_failed)
-		return;
-	platform_driver_unregister(&mpc83xx_spi_driver);
-}
-#else
-static void __init legacy_driver_register(void) {}
-static void __exit legacy_driver_unregister(void) {}
-#endif /* CONFIG_MPC832x_RDB */
-
-static int __init mpc83xx_spi_init(void)
-{
-	legacy_driver_register();
-	return of_register_platform_driver(&of_mpc83xx_spi_driver);
-}
-
-static void __exit mpc83xx_spi_exit(void)
-{
-	of_unregister_platform_driver(&of_mpc83xx_spi_driver);
-	legacy_driver_unregister();
-}
-
-module_init(mpc83xx_spi_init);
-module_exit(mpc83xx_spi_exit);
-
-MODULE_AUTHOR("Kumar Gala");
-MODULE_DESCRIPTION("Simple MPC83xx SPI Driver");
-MODULE_LICENSE("GPL");
diff --git a/drivers/spi/spi_mpc8xxx.c b/drivers/spi/spi_mpc8xxx.c
new file mode 100644
index 0000000..0fd0ec4
--- /dev/null
+++ b/drivers/spi/spi_mpc8xxx.c
@@ -0,0 +1,945 @@
+/*
+ * MPC8xxx SPI controller driver.
+ *
+ * Maintainer: Kumar Gala
+ *
+ * Copyright (C) 2006 Polycom, Inc.
+ *
+ * This program is free software; you can redistribute  it and/or modify it
+ * under  the terms of  the GNU General  Public License as published by the
+ * Free Software Foundation;  either version 2 of the  License, or (at your
+ * option) any later version.
+ */
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/types.h>
+#include <linux/kernel.h>
+#include <linux/bug.h>
+#include <linux/errno.h>
+#include <linux/err.h>
+#include <linux/io.h>
+#include <linux/completion.h>
+#include <linux/interrupt.h>
+#include <linux/delay.h>
+#include <linux/irq.h>
+#include <linux/device.h>
+#include <linux/spi/spi.h>
+#include <linux/spi/spi_bitbang.h>
+#include <linux/platform_device.h>
+#include <linux/fsl_devices.h>
+#include <linux/of.h>
+#include <linux/of_platform.h>
+#include <linux/gpio.h>
+#include <linux/of_gpio.h>
+#include <linux/of_spi.h>
+
+#include <sysdev/fsl_soc.h>
+#include <asm/irq.h>
+
+/* SPI Controller registers */
+struct mpc8xxx_spi_reg {
+	u8 res1[0x20];
+	__be32 mode;
+	__be32 event;
+	__be32 mask;
+	__be32 command;
+	__be32 transmit;
+	__be32 receive;
+};
+
+/* SPI Controller mode register definitions */
+#define	SPMODE_LOOP		(1 << 30)
+#define	SPMODE_CI_INACTIVEHIGH	(1 << 29)
+#define	SPMODE_CP_BEGIN_EDGECLK	(1 << 28)
+#define	SPMODE_DIV16		(1 << 27)
+#define	SPMODE_REV		(1 << 26)
+#define	SPMODE_MS		(1 << 25)
+#define	SPMODE_ENABLE		(1 << 24)
+#define	SPMODE_LEN(x)		((x) << 20)
+#define	SPMODE_PM(x)		((x) << 16)
+#define	SPMODE_OP		(1 << 14)
+#define	SPMODE_CG(x)		((x) << 7)
+
+/*
+ * Default for SPI Mode:
+ * 	SPI MODE 0 (inactive low, phase middle, MSB, 8-bit length, slow clk
+ */
+#define	SPMODE_INIT_VAL (SPMODE_CI_INACTIVEHIGH | SPMODE_DIV16 | SPMODE_REV | \
+			 SPMODE_MS | SPMODE_LEN(7) | SPMODE_PM(0xf))
+
+/* SPIE register values */
+#define	SPIE_NE		0x00000200	/* Not empty */
+#define	SPIE_NF		0x00000100	/* Not full */
+
+/* SPIM register values */
+#define	SPIM_NE		0x00000200	/* Not empty */
+#define	SPIM_NF		0x00000100	/* Not full */
+
+/* SPI Controller driver's private data. */
+struct mpc8xxx_spi {
+	struct mpc8xxx_spi_reg __iomem *base;
+
+	/* rx & tx bufs from the spi_transfer */
+	const void *tx;
+	void *rx;
+
+	/* functions to deal with different sized buffers */
+	void (*get_rx) (u32 rx_data, struct mpc8xxx_spi *);
+	u32(*get_tx) (struct mpc8xxx_spi *);
+
+	unsigned int count;
+	unsigned int irq;
+
+	unsigned nsecs;		/* (clock cycle time)/2 */
+
+	u32 spibrg;		/* SPIBRG input clock */
+	u32 rx_shift;		/* RX data reg shift when in qe mode */
+	u32 tx_shift;		/* TX data reg shift when in qe mode */
+
+	bool qe_mode;
+
+	struct workqueue_struct *workqueue;
+	struct work_struct work;
+
+	struct list_head queue;
+	spinlock_t lock;
+
+	struct completion done;
+};
+
+struct spi_mpc8xxx_cs {
+	/* functions to deal with different sized buffers */
+	void (*get_rx) (u32 rx_data, struct mpc8xxx_spi *);
+	u32 (*get_tx) (struct mpc8xxx_spi *);
+	u32 rx_shift;		/* RX data reg shift when in qe mode */
+	u32 tx_shift;		/* TX data reg shift when in qe mode */
+	u32 hw_mode;		/* Holds HW mode register settings */
+};
+
+static inline void mpc8xxx_spi_write_reg(__be32 __iomem *reg, u32 val)
+{
+	out_be32(reg, val);
+}
+
+static inline u32 mpc8xxx_spi_read_reg(__be32 __iomem *reg)
+{
+	return in_be32(reg);
+}
+
+#define MPC83XX_SPI_RX_BUF(type) 					  \
+static									  \
+void mpc8xxx_spi_rx_buf_##type(u32 data, struct mpc8xxx_spi *mpc8xxx_spi) \
+{									  \
+	type *rx = mpc8xxx_spi->rx;					  \
+	*rx++ = (type)(data >> mpc8xxx_spi->rx_shift);			  \
+	mpc8xxx_spi->rx = rx;						  \
+}
+
+#define MPC83XX_SPI_TX_BUF(type)				\
+static								\
+u32 mpc8xxx_spi_tx_buf_##type(struct mpc8xxx_spi *mpc8xxx_spi)	\
+{								\
+	u32 data;						\
+	const type *tx = mpc8xxx_spi->tx;			\
+	if (!tx)						\
+		return 0;					\
+	data = *tx++ << mpc8xxx_spi->tx_shift;			\
+	mpc8xxx_spi->tx = tx;					\
+	return data;						\
+}
+
+MPC83XX_SPI_RX_BUF(u8)
+MPC83XX_SPI_RX_BUF(u16)
+MPC83XX_SPI_RX_BUF(u32)
+MPC83XX_SPI_TX_BUF(u8)
+MPC83XX_SPI_TX_BUF(u16)
+MPC83XX_SPI_TX_BUF(u32)
+
+static void mpc8xxx_spi_chipselect(struct spi_device *spi, int value)
+{
+	struct mpc8xxx_spi *mpc8xxx_spi = spi_master_get_devdata(spi->master);
+	struct fsl_spi_platform_data *pdata = spi->dev.parent->platform_data;
+	bool pol = spi->mode & SPI_CS_HIGH;
+	struct spi_mpc8xxx_cs	*cs = spi->controller_state;
+
+	if (value == BITBANG_CS_INACTIVE) {
+		if (pdata->cs_control)
+			pdata->cs_control(spi, !pol);
+	}
+
+	if (value == BITBANG_CS_ACTIVE) {
+		u32 regval = mpc8xxx_spi_read_reg(&mpc8xxx_spi->base->mode);
+
+		mpc8xxx_spi->rx_shift = cs->rx_shift;
+		mpc8xxx_spi->tx_shift = cs->tx_shift;
+		mpc8xxx_spi->get_rx = cs->get_rx;
+		mpc8xxx_spi->get_tx = cs->get_tx;
+
+		if (cs->hw_mode != regval) {
+			unsigned long flags;
+			__be32 __iomem *mode = &mpc8xxx_spi->base->mode;
+
+			regval = cs->hw_mode;
+			/* Turn off IRQs locally to minimize time that
+			 * SPI is disabled
+			 */
+			local_irq_save(flags);
+			/* Turn off SPI unit prior changing mode */
+			mpc8xxx_spi_write_reg(mode, regval & ~SPMODE_ENABLE);
+			mpc8xxx_spi_write_reg(mode, regval);
+			local_irq_restore(flags);
+		}
+		if (pdata->cs_control)
+			pdata->cs_control(spi, pol);
+	}
+}
+
+static
+int mpc8xxx_spi_setup_transfer(struct spi_device *spi, struct spi_transfer *t)
+{
+	struct mpc8xxx_spi *mpc8xxx_spi;
+	u32 regval;
+	u8 bits_per_word, pm;
+	u32 hz;
+	struct spi_mpc8xxx_cs	*cs = spi->controller_state;
+
+	mpc8xxx_spi = spi_master_get_devdata(spi->master);
+
+	if (t) {
+		bits_per_word = t->bits_per_word;
+		hz = t->speed_hz;
+	} else {
+		bits_per_word = 0;
+		hz = 0;
+	}
+
+	/* spi_transfer level calls that work per-word */
+	if (!bits_per_word)
+		bits_per_word = spi->bits_per_word;
+
+	/* Make sure its a bit width we support [4..16, 32] */
+	if ((bits_per_word < 4)
+	    || ((bits_per_word > 16) && (bits_per_word != 32)))
+		return -EINVAL;
+
+	if (!hz)
+		hz = spi->max_speed_hz;
+
+	cs->rx_shift = 0;
+	cs->tx_shift = 0;
+	if (bits_per_word <= 8) {
+		cs->get_rx = mpc8xxx_spi_rx_buf_u8;
+		cs->get_tx = mpc8xxx_spi_tx_buf_u8;
+		if (mpc8xxx_spi->qe_mode) {
+			cs->rx_shift = 16;
+			cs->tx_shift = 24;
+		}
+	} else if (bits_per_word <= 16) {
+		cs->get_rx = mpc8xxx_spi_rx_buf_u16;
+		cs->get_tx = mpc8xxx_spi_tx_buf_u16;
+		if (mpc8xxx_spi->qe_mode) {
+			cs->rx_shift = 16;
+			cs->tx_shift = 16;
+		}
+	} else if (bits_per_word <= 32) {
+		cs->get_rx = mpc8xxx_spi_rx_buf_u32;
+		cs->get_tx = mpc8xxx_spi_tx_buf_u32;
+	} else
+		return -EINVAL;
+
+	if (mpc8xxx_spi->qe_mode && spi->mode & SPI_LSB_FIRST) {
+		cs->tx_shift = 0;
+		if (bits_per_word <= 8)
+			cs->rx_shift = 8;
+		else
+			cs->rx_shift = 0;
+	}
+
+	mpc8xxx_spi->rx_shift = cs->rx_shift;
+	mpc8xxx_spi->tx_shift = cs->tx_shift;
+	mpc8xxx_spi->get_rx = cs->get_rx;
+	mpc8xxx_spi->get_tx = cs->get_tx;
+
+	if (bits_per_word == 32)
+		bits_per_word = 0;
+	else
+		bits_per_word = bits_per_word - 1;
+
+	/* mask out bits we are going to set */
+	cs->hw_mode &= ~(SPMODE_LEN(0xF) | SPMODE_DIV16
+				  | SPMODE_PM(0xF));
+
+	cs->hw_mode |= SPMODE_LEN(bits_per_word);
+
+	if ((mpc8xxx_spi->spibrg / hz) > 64) {
+		cs->hw_mode |= SPMODE_DIV16;
+		pm = mpc8xxx_spi->spibrg / (hz * 64);
+
+		WARN_ONCE(pm > 16, "%s: Requested speed is too low: %d Hz. "
+			  "Will use %d Hz instead.\n", dev_name(&spi->dev),
+			  hz, mpc8xxx_spi->spibrg / 1024);
+		if (pm > 16)
+			pm = 16;
+	} else
+		pm = mpc8xxx_spi->spibrg / (hz * 4);
+	if (pm)
+		pm--;
+
+	cs->hw_mode |= SPMODE_PM(pm);
+	regval =  mpc8xxx_spi_read_reg(&mpc8xxx_spi->base->mode);
+	if (cs->hw_mode != regval) {
+		unsigned long flags;
+		__be32 __iomem *mode = &mpc8xxx_spi->base->mode;
+
+		regval = cs->hw_mode;
+		/* Turn off IRQs locally to minimize time
+		 * that SPI is disabled
+		 */
+		local_irq_save(flags);
+		/* Turn off SPI unit prior changing mode */
+		mpc8xxx_spi_write_reg(mode, regval & ~SPMODE_ENABLE);
+		mpc8xxx_spi_write_reg(mode, regval);
+		local_irq_restore(flags);
+	}
+	return 0;
+}
+
+static int mpc8xxx_spi_bufs(struct spi_device *spi, struct spi_transfer *t)
+{
+	struct mpc8xxx_spi *mpc8xxx_spi;
+	u32 word, len, bits_per_word;
+
+	mpc8xxx_spi = spi_master_get_devdata(spi->master);
+
+	mpc8xxx_spi->tx = t->tx_buf;
+	mpc8xxx_spi->rx = t->rx_buf;
+	bits_per_word = spi->bits_per_word;
+	if (t->bits_per_word)
+		bits_per_word = t->bits_per_word;
+	len = t->len;
+	if (bits_per_word > 8) {
+		/* invalid length? */
+		if (len & 1)
+			return -EINVAL;
+		len /= 2;
+	}
+	if (bits_per_word > 16) {
+		/* invalid length? */
+		if (len & 1)
+			return -EINVAL;
+		len /= 2;
+	}
+	mpc8xxx_spi->count = len;
+
+	INIT_COMPLETION(mpc8xxx_spi->done);
+
+	/* enable rx ints */
+	mpc8xxx_spi_write_reg(&mpc8xxx_spi->base->mask, SPIM_NE);
+
+	/* transmit word */
+	word = mpc8xxx_spi->get_tx(mpc8xxx_spi);
+	mpc8xxx_spi_write_reg(&mpc8xxx_spi->base->transmit, word);
+
+	wait_for_completion(&mpc8xxx_spi->done);
+
+	/* disable rx ints */
+	mpc8xxx_spi_write_reg(&mpc8xxx_spi->base->mask, 0);
+
+	return mpc8xxx_spi->count;
+}
+
+static void mpc8xxx_spi_do_one_msg(struct spi_message *m)
+{
+	struct spi_device *spi = m->spi;
+	struct spi_transfer *t;
+	unsigned int cs_change;
+	const int nsecs = 50;
+	int status;
+
+	cs_change = 1;
+	status = 0;
+	list_for_each_entry(t, &m->transfers, transfer_list) {
+		if (t->bits_per_word || t->speed_hz) {
+			/* Don't allow changes if CS is active */
+			status = -EINVAL;
+
+			if (cs_change)
+				status = mpc8xxx_spi_setup_transfer(spi, t);
+			if (status < 0)
+				break;
+		}
+
+		if (cs_change) {
+			mpc8xxx_spi_chipselect(spi, BITBANG_CS_ACTIVE);
+			ndelay(nsecs);
+		}
+		cs_change = t->cs_change;
+		if (t->len)
+			status = mpc8xxx_spi_bufs(spi, t);
+		if (status) {
+			status = -EMSGSIZE;
+			break;
+		}
+		m->actual_length += t->len;
+
+		if (t->delay_usecs)
+			udelay(t->delay_usecs);
+
+		if (cs_change) {
+			ndelay(nsecs);
+			mpc8xxx_spi_chipselect(spi, BITBANG_CS_INACTIVE);
+			ndelay(nsecs);
+		}
+	}
+
+	m->status = status;
+	m->complete(m->context);
+
+	if (status || !cs_change) {
+		ndelay(nsecs);
+		mpc8xxx_spi_chipselect(spi, BITBANG_CS_INACTIVE);
+	}
+
+	mpc8xxx_spi_setup_transfer(spi, NULL);
+}
+
+static void mpc8xxx_spi_work(struct work_struct *work)
+{
+	struct mpc8xxx_spi *mpc8xxx_spi = container_of(work, struct mpc8xxx_spi,
+						       work);
+
+	spin_lock_irq(&mpc8xxx_spi->lock);
+	while (!list_empty(&mpc8xxx_spi->queue)) {
+		struct spi_message *m = container_of(mpc8xxx_spi->queue.next,
+						   struct spi_message, queue);
+
+		list_del_init(&m->queue);
+		spin_unlock_irq(&mpc8xxx_spi->lock);
+
+		mpc8xxx_spi_do_one_msg(m);
+
+		spin_lock_irq(&mpc8xxx_spi->lock);
+	}
+	spin_unlock_irq(&mpc8xxx_spi->lock);
+}
+
+static int mpc8xxx_spi_setup(struct spi_device *spi)
+{
+	struct mpc8xxx_spi *mpc8xxx_spi;
+	int retval;
+	u32 hw_mode;
+	struct spi_mpc8xxx_cs	*cs = spi->controller_state;
+
+	if (!spi->max_speed_hz)
+		return -EINVAL;
+
+	if (!cs) {
+		cs = kzalloc(sizeof *cs, GFP_KERNEL);
+		if (!cs)
+			return -ENOMEM;
+		spi->controller_state = cs;
+	}
+	mpc8xxx_spi = spi_master_get_devdata(spi->master);
+
+	hw_mode = cs->hw_mode; /* Save orginal settings */
+	cs->hw_mode = mpc8xxx_spi_read_reg(&mpc8xxx_spi->base->mode);
+	/* mask out bits we are going to set */
+	cs->hw_mode &= ~(SPMODE_CP_BEGIN_EDGECLK | SPMODE_CI_INACTIVEHIGH
+			 | SPMODE_REV | SPMODE_LOOP);
+
+	if (spi->mode & SPI_CPHA)
+		cs->hw_mode |= SPMODE_CP_BEGIN_EDGECLK;
+	if (spi->mode & SPI_CPOL)
+		cs->hw_mode |= SPMODE_CI_INACTIVEHIGH;
+	if (!(spi->mode & SPI_LSB_FIRST))
+		cs->hw_mode |= SPMODE_REV;
+	if (spi->mode & SPI_LOOP)
+		cs->hw_mode |= SPMODE_LOOP;
+
+	retval = mpc8xxx_spi_setup_transfer(spi, NULL);
+	if (retval < 0) {
+		cs->hw_mode = hw_mode; /* Restore settings */
+		return retval;
+	}
+	return 0;
+}
+
+static irqreturn_t mpc8xxx_spi_irq(s32 irq, void *context_data)
+{
+	struct mpc8xxx_spi *mpc8xxx_spi = context_data;
+	u32 event;
+	irqreturn_t ret = IRQ_NONE;
+
+	/* Get interrupt events(tx/rx) */
+	event = mpc8xxx_spi_read_reg(&mpc8xxx_spi->base->event);
+
+	/* We need handle RX first */
+	if (event & SPIE_NE) {
+		u32 rx_data = mpc8xxx_spi_read_reg(&mpc8xxx_spi->base->receive);
+
+		if (mpc8xxx_spi->rx)
+			mpc8xxx_spi->get_rx(rx_data, mpc8xxx_spi);
+
+		ret = IRQ_HANDLED;
+	}
+
+	if ((event & SPIE_NF) == 0)
+		/* spin until TX is done */
+		while (((event =
+			 mpc8xxx_spi_read_reg(&mpc8xxx_spi->base->event)) &
+						SPIE_NF) == 0)
+			cpu_relax();
+
+	mpc8xxx_spi->count -= 1;
+	if (mpc8xxx_spi->count) {
+		u32 word = mpc8xxx_spi->get_tx(mpc8xxx_spi);
+		mpc8xxx_spi_write_reg(&mpc8xxx_spi->base->transmit, word);
+	} else {
+		complete(&mpc8xxx_spi->done);
+	}
+
+	/* Clear the events */
+	mpc8xxx_spi_write_reg(&mpc8xxx_spi->base->event, event);
+
+	return ret;
+}
+static int mpc8xxx_spi_transfer(struct spi_device *spi,
+				struct spi_message *m)
+{
+	struct mpc8xxx_spi *mpc8xxx_spi = spi_master_get_devdata(spi->master);
+	unsigned long flags;
+
+	m->actual_length = 0;
+	m->status = -EINPROGRESS;
+
+	spin_lock_irqsave(&mpc8xxx_spi->lock, flags);
+	list_add_tail(&m->queue, &mpc8xxx_spi->queue);
+	queue_work(mpc8xxx_spi->workqueue, &mpc8xxx_spi->work);
+	spin_unlock_irqrestore(&mpc8xxx_spi->lock, flags);
+
+	return 0;
+}
+
+
+static void mpc8xxx_spi_cleanup(struct spi_device *spi)
+{
+	kfree(spi->controller_state);
+}
+
+static struct spi_master * __devinit
+mpc8xxx_spi_probe(struct device *dev, struct resource *mem, unsigned int irq)
+{
+	struct fsl_spi_platform_data *pdata = dev->platform_data;
+	struct spi_master *master;
+	struct mpc8xxx_spi *mpc8xxx_spi;
+	u32 regval;
+	int ret = 0;
+
+	master = spi_alloc_master(dev, sizeof(struct mpc8xxx_spi));
+	if (master == NULL) {
+		ret = -ENOMEM;
+		goto err;
+	}
+
+	dev_set_drvdata(dev, master);
+
+	/* the spi->mode bits understood by this driver: */
+	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH
+			| SPI_LSB_FIRST | SPI_LOOP;
+
+	master->setup = mpc8xxx_spi_setup;
+	master->transfer = mpc8xxx_spi_transfer;
+	master->cleanup = mpc8xxx_spi_cleanup;
+
+	mpc8xxx_spi = spi_master_get_devdata(master);
+	mpc8xxx_spi->qe_mode = pdata->qe_mode;
+	mpc8xxx_spi->get_rx = mpc8xxx_spi_rx_buf_u8;
+	mpc8xxx_spi->get_tx = mpc8xxx_spi_tx_buf_u8;
+	mpc8xxx_spi->spibrg = pdata->sysclk;
+
+	mpc8xxx_spi->rx_shift = 0;
+	mpc8xxx_spi->tx_shift = 0;
+	if (mpc8xxx_spi->qe_mode) {
+		mpc8xxx_spi->rx_shift = 16;
+		mpc8xxx_spi->tx_shift = 24;
+	}
+
+	init_completion(&mpc8xxx_spi->done);
+
+	mpc8xxx_spi->base = ioremap(mem->start, mem->end - mem->start + 1);
+	if (mpc8xxx_spi->base == NULL) {
+		ret = -ENOMEM;
+		goto put_master;
+	}
+
+	mpc8xxx_spi->irq = irq;
+
+	/* Register for SPI Interrupt */
+	ret = request_irq(mpc8xxx_spi->irq, mpc8xxx_spi_irq,
+			  0, "mpc8xxx_spi", mpc8xxx_spi);
+
+	if (ret != 0)
+		goto unmap_io;
+
+	master->bus_num = pdata->bus_num;
+	master->num_chipselect = pdata->max_chipselect;
+
+	/* SPI controller initializations */
+	mpc8xxx_spi_write_reg(&mpc8xxx_spi->base->mode, 0);
+	mpc8xxx_spi_write_reg(&mpc8xxx_spi->base->mask, 0);
+	mpc8xxx_spi_write_reg(&mpc8xxx_spi->base->command, 0);
+	mpc8xxx_spi_write_reg(&mpc8xxx_spi->base->event, 0xffffffff);
+
+	/* Enable SPI interface */
+	regval = pdata->initial_spmode | SPMODE_INIT_VAL | SPMODE_ENABLE;
+	if (pdata->qe_mode)
+		regval |= SPMODE_OP;
+
+	mpc8xxx_spi_write_reg(&mpc8xxx_spi->base->mode, regval);
+	spin_lock_init(&mpc8xxx_spi->lock);
+	init_completion(&mpc8xxx_spi->done);
+	INIT_WORK(&mpc8xxx_spi->work, mpc8xxx_spi_work);
+	INIT_LIST_HEAD(&mpc8xxx_spi->queue);
+
+	mpc8xxx_spi->workqueue = create_singlethread_workqueue(
+		dev_name(master->dev.parent));
+	if (mpc8xxx_spi->workqueue == NULL) {
+		ret = -EBUSY;
+		goto free_irq;
+	}
+
+	ret = spi_register_master(master);
+	if (ret < 0)
+		goto unreg_master;
+
+	printk(KERN_INFO
+	       "%s: MPC8xxx SPI Controller driver at 0x%p (irq = %d)\n",
+	       dev_name(dev), mpc8xxx_spi->base, mpc8xxx_spi->irq);
+
+	return master;
+
+unreg_master:
+	destroy_workqueue(mpc8xxx_spi->workqueue);
+free_irq:
+	free_irq(mpc8xxx_spi->irq, mpc8xxx_spi);
+unmap_io:
+	iounmap(mpc8xxx_spi->base);
+put_master:
+	spi_master_put(master);
+err:
+	return ERR_PTR(ret);
+}
+
+static int __devexit mpc8xxx_spi_remove(struct device *dev)
+{
+	struct mpc8xxx_spi *mpc8xxx_spi;
+	struct spi_master *master;
+
+	master = dev_get_drvdata(dev);
+	mpc8xxx_spi = spi_master_get_devdata(master);
+
+	flush_workqueue(mpc8xxx_spi->workqueue);
+	destroy_workqueue(mpc8xxx_spi->workqueue);
+	spi_unregister_master(master);
+
+	free_irq(mpc8xxx_spi->irq, mpc8xxx_spi);
+	iounmap(mpc8xxx_spi->base);
+
+	return 0;
+}
+
+struct mpc8xxx_spi_probe_info {
+	struct fsl_spi_platform_data pdata;
+	int *gpios;
+	bool *alow_flags;
+};
+
+static struct mpc8xxx_spi_probe_info *
+to_of_pinfo(struct fsl_spi_platform_data *pdata)
+{
+	return container_of(pdata, struct mpc8xxx_spi_probe_info, pdata);
+}
+
+static void mpc8xxx_spi_cs_control(struct spi_device *spi, bool on)
+{
+	struct device *dev = spi->dev.parent;
+	struct mpc8xxx_spi_probe_info *pinfo = to_of_pinfo(dev->platform_data);
+	u16 cs = spi->chip_select;
+	int gpio = pinfo->gpios[cs];
+	bool alow = pinfo->alow_flags[cs];
+
+	gpio_set_value(gpio, on ^ alow);
+}
+
+static int of_mpc8xxx_spi_get_chipselects(struct device *dev)
+{
+	struct device_node *np = dev_archdata_get_node(&dev->archdata);
+	struct fsl_spi_platform_data *pdata = dev->platform_data;
+	struct mpc8xxx_spi_probe_info *pinfo = to_of_pinfo(pdata);
+	unsigned int ngpios;
+	int i = 0;
+	int ret;
+
+	ngpios = of_gpio_count(np);
+	if (!ngpios) {
+		/*
+		 * SPI w/o chip-select line. One SPI device is still permitted
+		 * though.
+		 */
+		pdata->max_chipselect = 1;
+		return 0;
+	}
+
+	pinfo->gpios = kmalloc(ngpios * sizeof(*pinfo->gpios), GFP_KERNEL);
+	if (!pinfo->gpios)
+		return -ENOMEM;
+	memset(pinfo->gpios, -1, ngpios * sizeof(*pinfo->gpios));
+
+	pinfo->alow_flags = kzalloc(ngpios * sizeof(*pinfo->alow_flags),
+				    GFP_KERNEL);
+	if (!pinfo->alow_flags) {
+		ret = -ENOMEM;
+		goto err_alloc_flags;
+	}
+
+	for (; i < ngpios; i++) {
+		int gpio;
+		enum of_gpio_flags flags;
+
+		gpio = of_get_gpio_flags(np, i, &flags);
+		if (!gpio_is_valid(gpio)) {
+			dev_err(dev, "invalid gpio #%d: %d\n", i, gpio);
+			goto err_loop;
+		}
+
+		ret = gpio_request(gpio, dev_name(dev));
+		if (ret) {
+			dev_err(dev, "can't request gpio #%d: %d\n", i, ret);
+			goto err_loop;
+		}
+
+		pinfo->gpios[i] = gpio;
+		pinfo->alow_flags[i] = flags & OF_GPIO_ACTIVE_LOW;
+
+		ret = gpio_direction_output(pinfo->gpios[i],
+					    pinfo->alow_flags[i]);
+		if (ret) {
+			dev_err(dev, "can't set output direction for gpio "
+				"#%d: %d\n", i, ret);
+			goto err_loop;
+		}
+	}
+
+	pdata->max_chipselect = ngpios;
+	pdata->cs_control = mpc8xxx_spi_cs_control;
+
+	return 0;
+
+err_loop:
+	while (i >= 0) {
+		if (gpio_is_valid(pinfo->gpios[i]))
+			gpio_free(pinfo->gpios[i]);
+		i--;
+	}
+
+	kfree(pinfo->alow_flags);
+	pinfo->alow_flags = NULL;
+err_alloc_flags:
+	kfree(pinfo->gpios);
+	pinfo->gpios = NULL;
+	return ret;
+}
+
+static int of_mpc8xxx_spi_free_chipselects(struct device *dev)
+{
+	struct fsl_spi_platform_data *pdata = dev->platform_data;
+	struct mpc8xxx_spi_probe_info *pinfo = to_of_pinfo(pdata);
+	int i;
+
+	if (!pinfo->gpios)
+		return 0;
+
+	for (i = 0; i < pdata->max_chipselect; i++) {
+		if (gpio_is_valid(pinfo->gpios[i]))
+			gpio_free(pinfo->gpios[i]);
+	}
+
+	kfree(pinfo->gpios);
+	kfree(pinfo->alow_flags);
+	return 0;
+}
+
+static int __devinit of_mpc8xxx_spi_probe(struct of_device *ofdev,
+					  const struct of_device_id *ofid)
+{
+	struct device *dev = &ofdev->dev;
+	struct device_node *np = ofdev->node;
+	struct mpc8xxx_spi_probe_info *pinfo;
+	struct fsl_spi_platform_data *pdata;
+	struct spi_master *master;
+	struct resource mem;
+	struct resource irq;
+	const void *prop;
+	int ret = -ENOMEM;
+
+	pinfo = kzalloc(sizeof(*pinfo), GFP_KERNEL);
+	if (!pinfo)
+		return -ENOMEM;
+
+	pdata = &pinfo->pdata;
+	dev->platform_data = pdata;
+
+	/* Allocate bus num dynamically. */
+	pdata->bus_num = -1;
+
+	/* SPI controller is either clocked from QE or SoC clock. */
+	pdata->sysclk = get_brgfreq();
+	if (pdata->sysclk == -1) {
+		pdata->sysclk = fsl_get_sys_freq();
+		if (pdata->sysclk == -1) {
+			ret = -ENODEV;
+			goto err_clk;
+		}
+	}
+
+	prop = of_get_property(np, "mode", NULL);
+	if (prop && !strcmp(prop, "cpu-qe"))
+		pdata->qe_mode = 1;
+
+	ret = of_mpc8xxx_spi_get_chipselects(dev);
+	if (ret)
+		goto err;
+
+	ret = of_address_to_resource(np, 0, &mem);
+	if (ret)
+		goto err;
+
+	ret = of_irq_to_resource(np, 0, &irq);
+	if (!ret) {
+		ret = -EINVAL;
+		goto err;
+	}
+
+	master = mpc8xxx_spi_probe(dev, &mem, irq.start);
+	if (IS_ERR(master)) {
+		ret = PTR_ERR(master);
+		goto err;
+	}
+
+	of_register_spi_devices(master, np);
+
+	return 0;
+
+err:
+	of_mpc8xxx_spi_free_chipselects(dev);
+err_clk:
+	kfree(pinfo);
+	return ret;
+}
+
+static int __devexit of_mpc8xxx_spi_remove(struct of_device *ofdev)
+{
+	int ret;
+
+	ret = mpc8xxx_spi_remove(&ofdev->dev);
+	if (ret)
+		return ret;
+	of_mpc8xxx_spi_free_chipselects(&ofdev->dev);
+	return 0;
+}
+
+static const struct of_device_id of_mpc8xxx_spi_match[] = {
+	{ .compatible = "fsl,spi" },
+	{},
+};
+MODULE_DEVICE_TABLE(of, of_mpc8xxx_spi_match);
+
+static struct of_platform_driver of_mpc8xxx_spi_driver = {
+	.name		= "mpc8xxx_spi",
+	.match_table	= of_mpc8xxx_spi_match,
+	.probe		= of_mpc8xxx_spi_probe,
+	.remove		= __devexit_p(of_mpc8xxx_spi_remove),
+};
+
+#ifdef CONFIG_MPC832x_RDB
+/*
+ * 				XXX XXX XXX
+ * This is "legacy" platform driver, was used by the MPC8323E-RDB boards
+ * only. The driver should go away soon, since newer MPC8323E-RDB's device
+ * tree can work with OpenFirmware driver. But for now we support old trees
+ * as well.
+ */
+static int __devinit plat_mpc8xxx_spi_probe(struct platform_device *pdev)
+{
+	struct resource *mem;
+	unsigned int irq;
+	struct spi_master *master;
+
+	if (!pdev->dev.platform_data)
+		return -EINVAL;
+
+	mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
+	if (!mem)
+		return -EINVAL;
+
+	irq = platform_get_irq(pdev, 0);
+	if (!irq)
+		return -EINVAL;
+
+	master = mpc8xxx_spi_probe(&pdev->dev, mem, irq);
+	if (IS_ERR(master))
+		return PTR_ERR(master);
+	return 0;
+}
+
+static int __devexit plat_mpc8xxx_spi_remove(struct platform_device *pdev)
+{
+	return mpc8xxx_spi_remove(&pdev->dev);
+}
+
+MODULE_ALIAS("platform:mpc8xxx_spi");
+static struct platform_driver mpc8xxx_spi_driver = {
+	.probe = plat_mpc8xxx_spi_probe,
+	.remove = __exit_p(plat_mpc8xxx_spi_remove),
+	.driver = {
+		.name = "mpc8xxx_spi",
+		.owner = THIS_MODULE,
+	},
+};
+
+static bool legacy_driver_failed;
+
+static void __init legacy_driver_register(void)
+{
+	legacy_driver_failed = platform_driver_register(&mpc8xxx_spi_driver);
+}
+
+static void __exit legacy_driver_unregister(void)
+{
+	if (legacy_driver_failed)
+		return;
+	platform_driver_unregister(&mpc8xxx_spi_driver);
+}
+#else
+static void __init legacy_driver_register(void) {}
+static void __exit legacy_driver_unregister(void) {}
+#endif /* CONFIG_MPC832x_RDB */
+
+static int __init mpc8xxx_spi_init(void)
+{
+	legacy_driver_register();
+	return of_register_platform_driver(&of_mpc8xxx_spi_driver);
+}
+
+static void __exit mpc8xxx_spi_exit(void)
+{
+	of_unregister_platform_driver(&of_mpc8xxx_spi_driver);
+	legacy_driver_unregister();
+}
+
+module_init(mpc8xxx_spi_init);
+module_exit(mpc8xxx_spi_exit);
+
+MODULE_AUTHOR("Kumar Gala");
+MODULE_DESCRIPTION("Simple MPC8xxx SPI Driver");
+MODULE_LICENSE("GPL");
diff --git a/drivers/spi/spi_s3c24xx.c b/drivers/spi/spi_s3c24xx.c
index b3ebc1d..e0d44af 100644
--- a/drivers/spi/spi_s3c24xx.c
+++ b/drivers/spi/spi_s3c24xx.c
@@ -146,32 +146,16 @@
 	return 0;
 }
 
-/* the spi->mode bits understood by this driver: */
-#define MODEBITS (SPI_CPOL | SPI_CPHA | SPI_CS_HIGH)
-
 static int s3c24xx_spi_setup(struct spi_device *spi)
 {
 	int ret;
 
-	if (!spi->bits_per_word)
-		spi->bits_per_word = 8;
-
-	if (spi->mode & ~MODEBITS) {
-		dev_dbg(&spi->dev, "setup: unsupported mode bits %x\n",
-			spi->mode & ~MODEBITS);
-		return -EINVAL;
-	}
-
 	ret = s3c24xx_spi_setupxfer(spi, NULL);
 	if (ret < 0) {
 		dev_err(&spi->dev, "setupxfer returned %d\n", ret);
 		return ret;
 	}
 
-	dev_dbg(&spi->dev, "%s: mode %d, %u bpw, %d hz\n",
-		__func__, spi->mode, spi->bits_per_word,
-		spi->max_speed_hz);
-
 	return 0;
 }
 
@@ -290,6 +274,9 @@
 
 	/* setup the master state. */
 
+	/* the spi->mode bits understood by this driver: */
+	master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH;
+
 	master->num_chipselect = hw->pdata->num_cs;
 	master->bus_num = pdata->bus_num;
 
diff --git a/drivers/spi/spi_txx9.c b/drivers/spi/spi_txx9.c
index 29cbb06..96057de 100644
--- a/drivers/spi/spi_txx9.c
+++ b/drivers/spi/spi_txx9.c
@@ -110,23 +110,17 @@
 	ndelay(cs_delay);	/* CS Setup Time / CS Recovery Time */
 }
 
-/* the spi->mode bits understood by this driver: */
-#define MODEBITS	(SPI_CS_HIGH|SPI_CPOL|SPI_CPHA)
-
 static int txx9spi_setup(struct spi_device *spi)
 {
 	struct txx9spi *c = spi_master_get_devdata(spi->master);
 	u8 bits_per_word;
 
-	if (spi->mode & ~MODEBITS)
-		return -EINVAL;
-
 	if (!spi->max_speed_hz
 			|| spi->max_speed_hz > c->max_speed_hz
 			|| spi->max_speed_hz < c->min_speed_hz)
 		return -EINVAL;
 
-	bits_per_word = spi->bits_per_word ? : 8;
+	bits_per_word = spi->bits_per_word;
 	if (bits_per_word != 8 && bits_per_word != 16)
 		return -EINVAL;
 
@@ -414,6 +408,9 @@
 		 (unsigned long long)res->start, irq,
 		 (c->baseclk + 500000) / 1000000);
 
+	/* the spi->mode bits understood by this driver: */
+	master->mode_bits = SPI_CS_HIGH | SPI_CPOL | SPI_CPHA;
+
 	master->bus_num = dev->id;
 	master->setup = txx9spi_setup;
 	master->transfer = txx9spi_transfer;
diff --git a/drivers/spi/xilinx_spi.c b/drivers/spi/xilinx_spi.c
index 494d3f7..46b8c5c 100644
--- a/drivers/spi/xilinx_spi.c
+++ b/drivers/spi/xilinx_spi.c
@@ -158,9 +158,6 @@
 	return 0;
 }
 
-/* the spi->mode bits understood by this driver: */
-#define MODEBITS (SPI_CPOL | SPI_CPHA)
-
 static int xilinx_spi_setup(struct spi_device *spi)
 {
 	struct spi_bitbang *bitbang;
@@ -170,22 +167,10 @@
 	xspi = spi_master_get_devdata(spi->master);
 	bitbang = &xspi->bitbang;
 
-	if (!spi->bits_per_word)
-		spi->bits_per_word = 8;
-
-	if (spi->mode & ~MODEBITS) {
-		dev_err(&spi->dev, "%s, unsupported mode bits %x\n",
-			__func__, spi->mode & ~MODEBITS);
-		return -EINVAL;
-	}
-
 	retval = xilinx_spi_setup_transfer(spi, NULL);
 	if (retval < 0)
 		return retval;
 
-	dev_dbg(&spi->dev, "%s, mode %d, %u bits/w, %u nsec/bit\n",
-		__func__, spi->mode & MODEBITS, spi->bits_per_word, 0);
-
 	return 0;
 }
 
@@ -333,6 +318,9 @@
 		goto put_master;
 	}
 
+	/* the spi->mode bits understood by this driver: */
+	master->mode_bits = SPI_CPOL | SPI_CPHA;
+
 	xspi = spi_master_get_devdata(master);
 	xspi->bitbang.master = spi_master_get(master);
 	xspi->bitbang.chipselect = xilinx_spi_chipselect;
diff --git a/drivers/staging/Kconfig b/drivers/staging/Kconfig
index d0fcf36..348bf61 100644
--- a/drivers/staging/Kconfig
+++ b/drivers/staging/Kconfig
@@ -85,6 +85,8 @@
 
 source "drivers/staging/rtl8187se/Kconfig"
 
+source "drivers/staging/rtl8192su/Kconfig"
+
 source "drivers/staging/rspiusb/Kconfig"
 
 source "drivers/staging/mimio/Kconfig"
@@ -113,9 +115,19 @@
 
 source "drivers/staging/line6/Kconfig"
 
-source "drivers/staging/serqt_usb/Kconfig"
-
 source "drivers/gpu/drm/radeon/Kconfig"
 
+source "drivers/staging/octeon/Kconfig"
+
+source "drivers/staging/serqt_usb2/Kconfig"
+
+source "drivers/staging/vt6655/Kconfig"
+
+source "drivers/staging/cpc-usb/Kconfig"
+
+source "drivers/staging/pata_rdc/Kconfig"
+
+source "drivers/staging/udlfb/Kconfig"
+
 endif # !STAGING_EXCLUDE_BUILD
 endif # STAGING
diff --git a/drivers/staging/Makefile b/drivers/staging/Makefile
index 47dfd5b4..8d61d7b 100644
--- a/drivers/staging/Makefile
+++ b/drivers/staging/Makefile
@@ -25,6 +25,7 @@
 obj-$(CONFIG_PANEL)		+= panel/
 obj-$(CONFIG_ALTERA_PCIE_CHDMA)	+= altpciechdma/
 obj-$(CONFIG_RTL8187SE)		+= rtl8187se/
+obj-$(CONFIG_RTL8192SU)		+= rtl8192su/
 obj-$(CONFIG_USB_RSPI)		+= rspiusb/
 obj-$(CONFIG_INPUT_MIMIO)	+= mimio/
 obj-$(CONFIG_TRANZPORT)		+= frontier/
@@ -39,4 +40,9 @@
 obj-$(CONFIG_PLAN9AUTH)		+= p9auth/
 obj-$(CONFIG_HECI)		+= heci/
 obj-$(CONFIG_LINE6_USB)		+= line6/
-obj-$(CONFIG_USB_SERIAL_QUATECH_ESU100)	+= serqt_usb/
+obj-$(CONFIG_USB_SERIAL_QUATECH2)	+= serqt_usb2/
+obj-$(CONFIG_OCTEON_ETHERNET)	+= octeon/
+obj-$(CONFIG_VT6655)		+= vt6655/
+obj-$(CONFIG_USB_CPC)		+= cpc-usb/
+obj-$(CONFIG_RDC_17F3101X)	+= pata_rdc/
+obj-$(CONFIG_FB_UDL)		+= udlfb/
diff --git a/drivers/staging/agnx/debug.h b/drivers/staging/agnx/debug.h
index 761d99c..7947f32 100644
--- a/drivers/staging/agnx/debug.h
+++ b/drivers/staging/agnx/debug.h
@@ -312,7 +312,6 @@
 {
 	u16 fctl;
 	int hdrlen;
-	DECLARE_MAC_BUF(mac);
 
 	fctl = le16_to_cpu(hdr->frame_control);
 	switch (fctl & IEEE80211_FCTL_FTYPE) {
@@ -375,13 +374,13 @@
 		printk("FC=0x%04x DUR=0x%04x",
 		       fctl, le16_to_cpu(hdr->duration_id));
 	if (hdrlen >= 10)
-		printk(" A1=%s", print_mac(mac, hdr->addr1));
+		printk(" A1=%pM", hdr->addr1);
 	if (hdrlen >= 16)
-		printk(" A2=%s", print_mac(mac, hdr->addr2));
+		printk(" A2=%pM", hdr->addr2);
 	if (hdrlen >= 24)
-		printk(" A3=%s", print_mac(mac, hdr->addr3));
+		printk(" A3=%pM", hdr->addr3);
 	if (hdrlen >= 30)
-		printk(" A4=%s", print_mac(mac, hdr->addr4));
+		printk(" A4=%pM", hdr->addr4);
 	printk("\n");
 }
 
diff --git a/drivers/staging/agnx/pci.c b/drivers/staging/agnx/pci.c
index 43b3fe3..1fe9870 100644
--- a/drivers/staging/agnx/pci.c
+++ b/drivers/staging/agnx/pci.c
@@ -58,15 +58,17 @@
 			*reason |= AGNX_STAT_TXM;
 		}
 	}
-/*	if (*reason & AGNX_STAT_X) {
+#if 0
+	if (*reason & AGNX_STAT_X) {
 		reg = ioread32(ctl + AGNX_INT_STAT);
 		iowrite32(reg, ctl + AGNX_INT_STAT);
-		/* FIXME reinit interrupt mask *\/
+		/* FIXME reinit interrupt mask */
 		reg = 0xc390bf9 & ~IRQ_TX_BEACON;
 		reg &= ~IRQ_TX_DISABLE;
 		iowrite32(reg, ctl + AGNX_INT_MASK);
 		iowrite32(0x800, ctl + AGNX_CIR_BLKCTL);
-	} */
+	}
+#endif
 } /* agnx_interrupt_ack */
 
 static irqreturn_t agnx_interrupt_handler(int irq, void *dev_id)
@@ -150,8 +152,7 @@
 	*((u32 *)(priv->mac_addr + 2)) = cpu_to_le32(reg);
 
 	if (!is_valid_ether_addr(priv->mac_addr)) {
-		DECLARE_MAC_BUF(mbuf);
-		printk(KERN_WARNING PFX "read mac %s\n", print_mac(mbuf, priv->mac_addr));
+		printk(KERN_WARNING PFX "read mac %pM\n", priv->mac_addr);
 		printk(KERN_WARNING PFX "Invalid hwaddr! Using random hwaddr\n");
 		random_ether_addr(priv->mac_addr);
 	}
@@ -220,7 +221,7 @@
 	/* TODO Recalibrate*/
 /*	calibrate_oscillator(priv); */
 /*	antenna_calibrate(priv); */
-/*	agnx_send_packet(priv, 997); /
+/*	agnx_send_packet(priv, 997); */
 	/* FIXME */
 /* 	if (debug == 3) */
 /*                 delay = msecs_to_jiffies(AGNX_PERIODIC_DELAY); */
@@ -455,47 +456,35 @@
 {
 	struct ieee80211_hw *dev;
 	struct agnx_priv *priv;
-	u32 mem_addr0, mem_len0;
-	u32 mem_addr1, mem_len1;
 	int err;
-	DECLARE_MAC_BUF(mac);
 
 	err = pci_enable_device(pdev);
 	if (err) {
-		printk(KERN_ERR PFX "Can't enable new PCI device\n");
+		dev_err(&pdev->dev, "can't enable pci device\n");
 		return err;
 	}
 
-	/* get pci resource */
-	mem_addr0 = pci_resource_start(pdev, 0);
-	mem_len0 = pci_resource_len(pdev, 0);
-	mem_addr1 = pci_resource_start(pdev, 1);
-	mem_len1 = pci_resource_len(pdev, 1);
-	printk(KERN_DEBUG PFX "Memaddr0 is %x, length is %x\n", mem_addr0, mem_len0);
-	printk(KERN_DEBUG PFX "Memaddr1 is %x, length is %x\n", mem_addr1, mem_len1);
-
 	err = pci_request_regions(pdev, "agnx-pci");
 	if (err) {
-		printk(KERN_ERR PFX "Can't obtain PCI resource\n");
+		dev_err(&pdev->dev, "can't reserve PCI resources\n");
 		return err;
 	}
 
 	if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) ||
 	    pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
-		printk(KERN_ERR PFX "No suitable DMA available\n");
+		dev_err(&pdev->dev, "no suitable DMA available\n");
+		err = -EIO;
 		goto err_free_reg;
 	}
 
 	pci_set_master(pdev);
-	printk(KERN_DEBUG PFX "pdev->irq is %d\n", pdev->irq);
 
 	dev = ieee80211_alloc_hw(sizeof(*priv), &agnx_ops);
 	if (!dev) {
-		printk(KERN_ERR PFX "ieee80211 alloc failed\n");
+		dev_err(&pdev->dev, "ieee80211 alloc failed\n");
 		err = -ENOMEM;
 		goto err_free_reg;
 	}
-	/* init priv  */
 	priv = dev->priv;
 	memset(priv, 0, sizeof(*priv));
 	priv->mode = NL80211_IFTYPE_MONITOR;
@@ -504,17 +493,17 @@
 	spin_lock_init(&priv->lock);
 	priv->init_status = AGNX_UNINIT;
 
-	/* Map mem #1 and #2 */
-	priv->ctl = pci_iomap(pdev, 0, mem_len0);
-/*	printk(KERN_DEBUG PFX"MEM1 mapped address is 0x%p\n", priv->ctl); */
+	priv->ctl = pci_iomap(pdev, 0, 0);
+/*	dev_dbg(&pdev->dev, "MEM1 mapped address is 0x%p\n", priv->ctl); */
 	if (!priv->ctl) {
-		printk(KERN_ERR PFX "Can't map device memory\n");
+		dev_err(&pdev->dev, "can't map device memory\n");
+		err = -ENOMEM;
 		goto err_free_dev;
 	}
-	priv->data = pci_iomap(pdev, 1, mem_len1);
-	printk(KERN_DEBUG PFX "MEM2 mapped address is 0x%p\n", priv->data);
+	priv->data = pci_iomap(pdev, 1, 0);
 	if (!priv->data) {
-		printk(KERN_ERR PFX "Can't map device memory\n");
+		dev_err(&pdev->dev, "can't map device memory\n");
+		err = -ENOMEM;
 		goto err_iounmap2;
 	}
 
@@ -555,15 +544,15 @@
 
 	err = ieee80211_register_hw(dev);
 	if (err) {
-		printk(KERN_ERR PFX "Can't register hardware\n");
+		dev_err(&pdev->dev, "can't register hardware\n");
 		goto err_iounmap;
 	}
 
 	agnx_hw_reset(priv);
 
-
-	printk(PFX "%s: hwaddr %s, Rev 0x%02x\n", wiphy_name(dev->wiphy),
-	       print_mac(mac, dev->wiphy->perm_addr), priv->revid);
+	dev_info(&pdev->dev, "%s: hwaddr %pM, Rev 0x%02x\n",
+		wiphy_name(dev->wiphy),
+		dev->wiphy->perm_addr, priv->revid);
 	return 0;
 
  err_iounmap:
diff --git a/drivers/staging/agnx/phy.c b/drivers/staging/agnx/phy.c
index 2be6331..ec1ca86 100644
--- a/drivers/staging/agnx/phy.c
+++ b/drivers/staging/agnx/phy.c
@@ -118,7 +118,7 @@
 	iowrite32(reg, ctl + AGNX_RXM_MACLO);
 }
 
-static void receiver_bssid_set(struct agnx_priv *priv, u8 *bssid)
+static void receiver_bssid_set(struct agnx_priv *priv, const u8 *bssid)
 {
 	void __iomem *ctl = priv->ctl;
 	u32 reg;
@@ -954,7 +954,7 @@
 	return 0;
 }
 
-void agnx_set_bssid(struct agnx_priv *priv, u8 *bssid)
+void agnx_set_bssid(struct agnx_priv *priv, const u8 *bssid)
 {
 	receiver_bssid_set(priv, bssid);
 }
diff --git a/drivers/staging/agnx/phy.h b/drivers/staging/agnx/phy.h
index 55e1e22..a955f05 100644
--- a/drivers/staging/agnx/phy.h
+++ b/drivers/staging/agnx/phy.h
@@ -401,7 +401,7 @@
 void agnx_hw_init(struct agnx_priv *priv);
 int agnx_hw_reset(struct agnx_priv *priv);
 int agnx_set_ssid(struct agnx_priv *priv, u8 *ssid, size_t ssid_len);
-void agnx_set_bssid(struct agnx_priv *priv, u8 *bssid);
+void agnx_set_bssid(struct agnx_priv *priv, const u8 *bssid);
 void enable_power_saving(struct agnx_priv *priv);
 void disable_power_saving(struct agnx_priv *priv);
 void calibrate_antenna_period(unsigned long data);
diff --git a/drivers/staging/agnx/sta.c b/drivers/staging/agnx/sta.c
index 5b2d54a..3e7db5e 100644
--- a/drivers/staging/agnx/sta.c
+++ b/drivers/staging/agnx/sta.c
@@ -22,7 +22,7 @@
 	printk(PFX "RX hash cmd are : %.8x%.8x\n", reghi, reglo);
 }
 
-void hash_write(struct agnx_priv *priv, u8 *mac_addr, u8 sta_id)
+void hash_write(struct agnx_priv *priv, const u8 *mac_addr, u8 sta_id)
 {
 	void __iomem *ctl = priv->ctl;
 	u32 reghi, reglo;
diff --git a/drivers/staging/agnx/sta.h b/drivers/staging/agnx/sta.h
index 94e2cf1..fd504e3 100644
--- a/drivers/staging/agnx/sta.h
+++ b/drivers/staging/agnx/sta.h
@@ -201,7 +201,7 @@
 	/* 802.11(abg) beacon */
 } __attribute__((__packed__));
 
-void hash_write(struct agnx_priv *priv, u8 *mac_addr, u8 sta_id);
+void hash_write(struct agnx_priv *priv, const u8 *mac_addr, u8 sta_id);
 void hash_dump(struct agnx_priv *priv, u8 sta_id);
 void hash_read(struct agnx_priv *priv, u32 reghi, u32 reglo, u8 sta_id);
 void hash_delete(struct agnx_priv *priv, u32 reghi, u32 reglo, u8 sta_id);
diff --git a/drivers/staging/altpciechdma/altpciechdma.c b/drivers/staging/altpciechdma/altpciechdma.c
index 5869e14..3724b8a 100644
--- a/drivers/staging/altpciechdma/altpciechdma.c
+++ b/drivers/staging/altpciechdma/altpciechdma.c
@@ -399,6 +399,7 @@
 	desc->rc_addr_l = cpu_to_le32(pci_dma_l(addr));
 }
 
+#if ALTPCIECHDMA_CDEV
 /*
  * ape_sg_to_chdma_table() - Create a device descriptor table from a scatterlist.
  *
@@ -456,6 +457,7 @@
 	j++;
 	return j;
 }
+#endif
 
 /* compare buffers */
 static inline int compare(u32 *p, u32 *q, int len)
@@ -540,8 +542,8 @@
 		printk(KERN_DEBUG "Could not allocate coherent DMA buffer.\n");
 		goto fail;
 	}
-	printk(KERN_DEBUG "Allocated cache-coherent DMA buffer (virtual address = 0x%016llx, bus address = 0x%016llx).\n",
-		(u64)buffer_virt, (u64)buffer_bus);
+	printk(KERN_DEBUG "Allocated cache-coherent DMA buffer (virtual address = %p, bus address = 0x%016llx).\n",
+	       buffer_virt, (u64)buffer_bus);
 
 	/* fill first half of buffer with its virtual address as data */
 	for (i = 0; i < 4 * PAGE_SIZE; i += 4)
@@ -783,7 +785,7 @@
 		goto err_ape;
 	}
 	ape->pci_dev = dev;
-	dev->dev.driver_data = (void *)ape;
+	dev_set_drvdata(&dev->dev, ape);
 	printk(KERN_DEBUG "probe() ape = 0x%p\n", ape);
 
 	printk(KERN_DEBUG "sizeof(struct ape_chdma_table) = %d.\n",
@@ -801,8 +803,8 @@
 		goto err_table;
 	}
 
-	printk(KERN_DEBUG "table_virt = 0x%16llx, table_bus = 0x%16llx.\n",
-		(u64)ape->table_virt, (u64)ape->table_bus);
+	printk(KERN_DEBUG "table_virt = %p, table_bus = 0x%16llx.\n",
+		ape->table_virt, (u64)ape->table_bus);
 
 	/* enable device */
 	rc = pci_enable_device(dev);
@@ -913,9 +915,11 @@
 	rc = 0;
 	printk(KERN_DEBUG "probe() successful.\n");
 	goto end;
+#if ALTPCIECHDMA_CDEV
 err_cdev:
 	/* unmap the BARs */
 	unmap_bars(ape, dev);
+#endif
 err_map:
 	/* free allocated irq */
 	if (ape->irq_line >= 0)
@@ -930,7 +934,7 @@
 		pci_release_regions(dev);
 err_mask:
 err_regions:
-err_rev:
+/*err_rev:*/
 /* clean up everything before device enable() */
 err_enable:
 	if (ape->table_virt)
@@ -946,19 +950,11 @@
 
 static void __devexit remove(struct pci_dev *dev)
 {
-	struct ape_dev *ape;
+	struct ape_dev *ape = dev_get_drvdata(&dev->dev);
+
 	printk(KERN_DEBUG "remove(0x%p)\n", dev);
-	if ((dev == 0) || (dev->dev.driver_data == 0)) {
-		printk(KERN_DEBUG "remove(dev = 0x%p) dev->dev.driver_data = 0x%p\n",
-			dev, (dev? dev->dev.driver_data: NULL));
-		return;
-	}
-	ape = (struct ape_dev *)dev->dev.driver_data;
-	printk(KERN_DEBUG "remove(dev = 0x%p) where dev->dev.driver_data = 0x%p\n", dev, ape);
-	if (ape->pci_dev != dev) {
-		printk(KERN_DEBUG "dev->dev.driver_data->pci_dev (0x%08lx) != dev (0x%08lx)\n",
-		(unsigned long)ape->pci_dev, (unsigned long)dev);
-	}
+	printk(KERN_DEBUG "remove(dev = 0x%p) where ape = 0x%p\n", dev, ape);
+
 	/* remove character device */
 #if ALTPCIECHDMA_CDEV
 	sg_exit(ape);
@@ -1151,7 +1147,7 @@
 	.name = DRV_NAME,
 	.id_table = ids,
 	.probe = probe,
-	.remove = remove,
+	.remove = __devexit_p(remove),
 	/* resume, suspend are optional */
 };
 
diff --git a/drivers/staging/android/Kconfig b/drivers/staging/android/Kconfig
index 604bd1e..2471949 100644
--- a/drivers/staging/android/Kconfig
+++ b/drivers/staging/android/Kconfig
@@ -6,6 +6,8 @@
 	---help---
 	  Enable support for various drivers needed on the Android platform
 
+if ANDROID
+
 config ANDROID_BINDER_IPC
 	bool "Android Binder IPC Driver"
 	default n
@@ -73,9 +75,13 @@
 	default 0
 	depends on ANDROID_RAM_CONSOLE_EARLY_INIT
 
+config ANDROID_TIMED_OUTPUT
+	bool "Timed output class driver"
+	default y
+
 config ANDROID_TIMED_GPIO
 	tristate "Android timed gpio driver"
-	depends on GENERIC_GPIO
+	depends on GENERIC_GPIO && ANDROID_TIMED_OUTPUT
 	default n
 
 config ANDROID_LOW_MEMORY_KILLER
@@ -84,4 +90,6 @@
 	---help---
 	  Register processes to be killed when memory is low
 
+endif # if ANDROID
+
 endmenu
diff --git a/drivers/staging/android/Makefile b/drivers/staging/android/Makefile
index 95209d6..8e057e6 100644
--- a/drivers/staging/android/Makefile
+++ b/drivers/staging/android/Makefile
@@ -1,5 +1,6 @@
 obj-$(CONFIG_ANDROID_BINDER_IPC)	+= binder.o
 obj-$(CONFIG_ANDROID_LOGGER)		+= logger.o
 obj-$(CONFIG_ANDROID_RAM_CONSOLE)	+= ram_console.o
+obj-$(CONFIG_ANDROID_TIMED_OUTPUT)	+= timed_output.o
 obj-$(CONFIG_ANDROID_TIMED_GPIO)	+= timed_gpio.o
 obj-$(CONFIG_ANDROID_LOW_MEMORY_KILLER)	+= lowmemorykiller.o
diff --git a/drivers/staging/android/binder.c b/drivers/staging/android/binder.c
index 299d29d..17d89a8 100644
--- a/drivers/staging/android/binder.c
+++ b/drivers/staging/android/binder.c
@@ -44,8 +44,8 @@
 static HLIST_HEAD(binder_deferred_list);
 static DEFINE_MUTEX(binder_deferred_lock);
 
-static int binder_read_proc_proc(
-	char *page, char **start, off_t off, int count, int *eof, void *data);
+static int binder_read_proc_proc(char *page, char **start, off_t off,
+				 int count, int *eof, void *data);
 
 /* This is only defined in include/asm-arm/sizes.h */
 #ifndef SZ_1K
@@ -81,12 +81,15 @@
 static uint32_t binder_debug_mask = BINDER_DEBUG_USER_ERROR |
 	BINDER_DEBUG_FAILED_TRANSACTION | BINDER_DEBUG_DEAD_TRANSACTION;
 module_param_named(debug_mask, binder_debug_mask, uint, S_IWUSR | S_IRUGO);
+
 static int binder_debug_no_lock;
 module_param_named(proc_no_lock, binder_debug_no_lock, bool, S_IWUSR | S_IRUGO);
+
 static DECLARE_WAIT_QUEUE_HEAD(binder_user_error_wait);
 static int binder_stop_on_user_error;
-static int binder_set_stop_on_user_error(
-	const char *val, struct kernel_param *kp)
+
+static int binder_set_stop_on_user_error(const char *val,
+					 struct kernel_param *kp)
 {
 	int ret;
 	ret = param_set_int(val, kp);
@@ -185,13 +188,13 @@
 	int local_strong_refs;
 	void __user *ptr;
 	void __user *cookie;
-	unsigned has_strong_ref : 1;
-	unsigned pending_strong_ref : 1;
-	unsigned has_weak_ref : 1;
-	unsigned pending_weak_ref : 1;
-	unsigned has_async_transaction : 1;
-	unsigned accept_fds : 1;
-	int min_priority : 8;
+	unsigned has_strong_ref:1;
+	unsigned pending_strong_ref:1;
+	unsigned has_weak_ref:1;
+	unsigned pending_weak_ref:1;
+	unsigned has_async_transaction:1;
+	unsigned accept_fds:1;
+	unsigned min_priority:8;
 	struct list_head async_todo;
 };
 
@@ -221,10 +224,10 @@
 	struct list_head entry; /* free and allocated entries by addesss */
 	struct rb_node rb_node; /* free entry by size or allocated entry */
 				/* by address */
-	unsigned free : 1;
-	unsigned allow_user_free : 1;
-	unsigned async_transaction : 1;
-	unsigned debug_id : 29;
+	unsigned free:1;
+	unsigned allow_user_free:1;
+	unsigned async_transaction:1;
+	unsigned debug_id:29;
 
 	struct binder_transaction *transaction;
 
@@ -306,8 +309,8 @@
 	struct binder_proc *to_proc;
 	struct binder_thread *to_thread;
 	struct binder_transaction *to_parent;
-	unsigned need_reply : 1;
-	/*unsigned is_dead : 1;*/ /* not used at the moment */
+	unsigned need_reply:1;
+	/* unsigned is_dead:1; */	/* not used at the moment */
 
 	struct binder_buffer *buffer;
 	unsigned int	code;
@@ -474,8 +477,8 @@
 	binder_user_error("binder: %d RLIMIT_NICE not set\n", current->pid);
 }
 
-static size_t binder_buffer_size(
-	struct binder_proc *proc, struct binder_buffer *buffer)
+static size_t binder_buffer_size(struct binder_proc *proc,
+				 struct binder_buffer *buffer)
 {
 	if (list_is_last(&buffer->entry, &proc->buffers))
 		return proc->buffer + proc->buffer_size - (void *)buffer->data;
@@ -484,8 +487,8 @@
 			struct binder_buffer, entry) - (size_t)buffer->data;
 }
 
-static void binder_insert_free_buffer(
-	struct binder_proc *proc, struct binder_buffer *new_buffer)
+static void binder_insert_free_buffer(struct binder_proc *proc,
+				      struct binder_buffer *new_buffer)
 {
 	struct rb_node **p = &proc->free_buffers.rb_node;
 	struct rb_node *parent = NULL;
@@ -517,8 +520,8 @@
 	rb_insert_color(&new_buffer->rb_node, &proc->free_buffers);
 }
 
-static void binder_insert_allocated_buffer(
-	struct binder_proc *proc, struct binder_buffer *new_buffer)
+static void binder_insert_allocated_buffer(struct binder_proc *proc,
+					   struct binder_buffer *new_buffer)
 {
 	struct rb_node **p = &proc->allocated_buffers.rb_node;
 	struct rb_node *parent = NULL;
@@ -542,8 +545,8 @@
 	rb_insert_color(&new_buffer->rb_node, &proc->allocated_buffers);
 }
 
-static struct binder_buffer *binder_buffer_lookup(
-	struct binder_proc *proc, void __user *user_ptr)
+static struct binder_buffer *binder_buffer_lookup(struct binder_proc *proc,
+						  void __user *user_ptr)
 {
 	struct rb_node *n = proc->allocated_buffers.rb_node;
 	struct binder_buffer *buffer;
@@ -567,7 +570,8 @@
 }
 
 static int binder_update_page_range(struct binder_proc *proc, int allocate,
-	void *start, void *end, struct vm_area_struct *vma)
+				    void *start, void *end,
+				    struct vm_area_struct *vma)
 {
 	void *page_addr;
 	unsigned long user_page_addr;
@@ -664,7 +668,8 @@
 }
 
 static struct binder_buffer *binder_alloc_buf(struct binder_proc *proc,
-	size_t data_size, size_t offsets_size, int is_async)
+					      size_t data_size,
+					      size_t offsets_size, int is_async)
 {
 	struct rb_node *n = proc->free_buffers.rb_node;
 	struct binder_buffer *buffer;
@@ -692,8 +697,9 @@
 	if (is_async &&
 	    proc->free_async_space < size + sizeof(struct binder_buffer)) {
 		if (binder_debug_mask & BINDER_DEBUG_BUFFER_ALLOC)
-			printk(KERN_ERR "binder: %d: binder_alloc_buf size %zd f"
-			       "ailed, no async space left\n", proc->pid, size);
+			printk(KERN_ERR
+			       "binder: %d: binder_alloc_buf size %zd failed, "
+			       "no async space left\n", proc->pid, size);
 		return NULL;
 	}
 
@@ -777,8 +783,8 @@
 	return (void *)(((uintptr_t)(buffer + 1) - 1) & PAGE_MASK);
 }
 
-static void binder_delete_free_buffer(
-	struct binder_proc *proc, struct binder_buffer *buffer)
+static void binder_delete_free_buffer(struct binder_proc *proc,
+				      struct binder_buffer *buffer)
 {
 	struct binder_buffer *prev, *next = NULL;
 	int free_page_end = 1;
@@ -824,8 +830,8 @@
 	}
 }
 
-static void binder_free_buf(
-	struct binder_proc *proc, struct binder_buffer *buffer)
+static void binder_free_buf(struct binder_proc *proc,
+			    struct binder_buffer *buffer)
 {
 	size_t size, buffer_size;
 
@@ -877,8 +883,8 @@
 	binder_insert_free_buffer(proc, buffer);
 }
 
-static struct binder_node *
-binder_get_node(struct binder_proc *proc, void __user *ptr)
+static struct binder_node *binder_get_node(struct binder_proc *proc,
+					   void __user *ptr)
 {
 	struct rb_node *n = proc->nodes.rb_node;
 	struct binder_node *node;
@@ -896,8 +902,9 @@
 	return NULL;
 }
 
-static struct binder_node *
-binder_new_node(struct binder_proc *proc, void __user *ptr, void __user *cookie)
+static struct binder_node *binder_new_node(struct binder_proc *proc,
+					   void __user *ptr,
+					   void __user *cookie)
 {
 	struct rb_node **p = &proc->nodes.rb_node;
 	struct rb_node *parent = NULL;
@@ -935,9 +942,8 @@
 	return node;
 }
 
-static int
-binder_inc_node(struct binder_node *node, int strong, int internal,
-		struct list_head *target_list)
+static int binder_inc_node(struct binder_node *node, int strong, int internal,
+			   struct list_head *target_list)
 {
 	if (strong) {
 		if (internal) {
@@ -971,8 +977,7 @@
 	return 0;
 }
 
-static int
-binder_dec_node(struct binder_node *node, int strong, int internal)
+static int binder_dec_node(struct binder_node *node, int strong, int internal)
 {
 	if (strong) {
 		if (internal)
@@ -1014,8 +1019,8 @@
 }
 
 
-static struct binder_ref *
-binder_get_ref(struct binder_proc *proc, uint32_t desc)
+static struct binder_ref *binder_get_ref(struct binder_proc *proc,
+					 uint32_t desc)
 {
 	struct rb_node *n = proc->refs_by_desc.rb_node;
 	struct binder_ref *ref;
@@ -1033,8 +1038,8 @@
 	return NULL;
 }
 
-static struct binder_ref *
-binder_get_ref_for_node(struct binder_proc *proc, struct binder_node *node)
+static struct binder_ref *binder_get_ref_for_node(struct binder_proc *proc,
+						  struct binder_node *node)
 {
 	struct rb_node *n;
 	struct rb_node **p = &proc->refs_by_node.rb_node;
@@ -1099,8 +1104,7 @@
 	return new_ref;
 }
 
-static void
-binder_delete_ref(struct binder_ref *ref)
+static void binder_delete_ref(struct binder_ref *ref)
 {
 	if (binder_debug_mask & BINDER_DEBUG_INTERNAL_REFS)
 		printk(KERN_INFO "binder: %d delete ref %d desc %d for "
@@ -1125,9 +1129,8 @@
 	binder_stats.obj_deleted[BINDER_STAT_REF]++;
 }
 
-static int
-binder_inc_ref(
-	struct binder_ref *ref, int strong, struct list_head *target_list)
+static int binder_inc_ref(struct binder_ref *ref, int strong,
+			  struct list_head *target_list)
 {
 	int ret;
 	if (strong) {
@@ -1149,8 +1152,7 @@
 }
 
 
-static int
-binder_dec_ref(struct binder_ref *ref, int strong)
+static int binder_dec_ref(struct binder_ref *ref, int strong)
 {
 	if (strong) {
 		if (ref->strong == 0) {
@@ -1182,9 +1184,8 @@
 	return 0;
 }
 
-static void
-binder_pop_transaction(
-	struct binder_thread *target_thread, struct binder_transaction *t)
+static void binder_pop_transaction(struct binder_thread *target_thread,
+				   struct binder_transaction *t)
 {
 	if (target_thread) {
 		BUG_ON(target_thread->transaction_stack != t);
@@ -1200,8 +1201,8 @@
 	binder_stats.obj_deleted[BINDER_STAT_TRANSACTION]++;
 }
 
-static void
-binder_send_failed_reply(struct binder_transaction *t, uint32_t error_code)
+static void binder_send_failed_reply(struct binder_transaction *t,
+				     uint32_t error_code)
 {
 	struct binder_thread *target_thread;
 	BUG_ON(t->flags & TF_ONE_WAY);
@@ -1253,13 +1254,13 @@
 	}
 }
 
-static void
-binder_transaction_buffer_release(struct binder_proc *proc,
-			struct binder_buffer *buffer, size_t *failed_at);
+static void binder_transaction_buffer_release(struct binder_proc *proc,
+					      struct binder_buffer *buffer,
+					      size_t *failed_at);
 
-static void
-binder_transaction(struct binder_proc *proc, struct binder_thread *thread,
-	struct binder_transaction_data *tr, int reply)
+static void binder_transaction(struct binder_proc *proc,
+			       struct binder_thread *thread,
+			       struct binder_transaction_data *tr, int reply)
 {
 	struct binder_transaction *t;
 	struct binder_work *tcomplete;
@@ -1661,8 +1662,9 @@
 		thread->return_error = return_error;
 }
 
-static void
-binder_transaction_buffer_release(struct binder_proc *proc, struct binder_buffer *buffer, size_t *failed_at)
+static void binder_transaction_buffer_release(struct binder_proc *proc,
+					      struct binder_buffer *buffer,
+					      size_t *failed_at)
 {
 	size_t *offp, *off_end;
 	int debug_id = buffer->debug_id;
@@ -1730,9 +1732,8 @@
 	}
 }
 
-int
-binder_thread_write(struct binder_proc *proc, struct binder_thread *thread,
-		    void __user *buffer, int size, signed long *consumed)
+int binder_thread_write(struct binder_proc *proc, struct binder_thread *thread,
+			void __user *buffer, int size, signed long *consumed)
 {
 	uint32_t cmd;
 	void __user *ptr = buffer + *consumed;
@@ -2104,7 +2105,8 @@
 		} break;
 
 		default:
-			printk(KERN_ERR "binder: %d:%d unknown command %d\n", proc->pid, thread->pid, cmd);
+			printk(KERN_ERR "binder: %d:%d unknown command %d\n",
+			       proc->pid, thread->pid, cmd);
 			return -EINVAL;
 		}
 		*consumed = ptr - buffer;
@@ -2112,8 +2114,8 @@
 	return 0;
 }
 
-void
-binder_stat_br(struct binder_proc *proc, struct binder_thread *thread, uint32_t cmd)
+void binder_stat_br(struct binder_proc *proc, struct binder_thread *thread,
+		    uint32_t cmd)
 {
 	if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.br)) {
 		binder_stats.br[_IOC_NR(cmd)]++;
@@ -2122,22 +2124,23 @@
 	}
 }
 
-static int
-binder_has_proc_work(struct binder_proc *proc, struct binder_thread *thread)
+static int binder_has_proc_work(struct binder_proc *proc,
+				struct binder_thread *thread)
 {
-	return !list_empty(&proc->todo) || (thread->looper & BINDER_LOOPER_STATE_NEED_RETURN);
+	return !list_empty(&proc->todo) ||
+		(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN);
 }
 
-static int
-binder_has_thread_work(struct binder_thread *thread)
+static int binder_has_thread_work(struct binder_thread *thread)
 {
 	return !list_empty(&thread->todo) || thread->return_error != BR_OK ||
 		(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN);
 }
 
-static int
-binder_thread_read(struct binder_proc *proc, struct binder_thread *thread,
-	void  __user *buffer, int size, signed long *consumed, int non_block)
+static int binder_thread_read(struct binder_proc *proc,
+			      struct binder_thread *thread,
+			      void  __user *buffer, int size,
+			      signed long *consumed, int non_block)
 {
 	void __user *ptr = buffer + *consumed;
 	void __user *end = buffer + size;
@@ -2152,7 +2155,8 @@
 	}
 
 retry:
-	wait_for_proc_work = thread->transaction_stack == NULL && list_empty(&thread->todo);
+	wait_for_proc_work = thread->transaction_stack == NULL &&
+				list_empty(&thread->todo);
 
 	if (thread->return_error != BR_OK && ptr < end) {
 		if (thread->return_error2 != BR_OK) {
@@ -2182,7 +2186,8 @@
 				"for process work before calling BC_REGISTER_"
 				"LOOPER or BC_ENTER_LOOPER (state %x)\n",
 				proc->pid, thread->pid, thread->looper);
-			wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
+			wait_event_interruptible(binder_user_error_wait,
+						 binder_stop_on_user_error < 2);
 		}
 		binder_set_nice(proc->default_priority);
 		if (non_block) {
@@ -2304,8 +2309,10 @@
 		case BINDER_WORK_DEAD_BINDER:
 		case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
 		case BINDER_WORK_CLEAR_DEATH_NOTIFICATION: {
-			struct binder_ref_death *death = container_of(w, struct binder_ref_death, work);
+			struct binder_ref_death *death;
 			uint32_t cmd;
+
+			death = container_of(w, struct binder_ref_death, work);
 			if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION)
 				cmd = BR_CLEAR_DEATH_NOTIFICATION_DONE;
 			else
@@ -2362,15 +2369,19 @@
 
 		if (t->from) {
 			struct task_struct *sender = t->from->proc->tsk;
-			tr.sender_pid = task_tgid_nr_ns(sender, current->nsproxy->pid_ns);
+			tr.sender_pid = task_tgid_nr_ns(sender,
+							current->nsproxy->pid_ns);
 		} else {
 			tr.sender_pid = 0;
 		}
 
 		tr.data_size = t->buffer->data_size;
 		tr.offsets_size = t->buffer->offsets_size;
-		tr.data.ptr.buffer = (void *)t->buffer->data + proc->user_buffer_offset;
-		tr.data.ptr.offsets = tr.data.ptr.buffer + ALIGN(t->buffer->data_size, sizeof(void *));
+		tr.data.ptr.buffer = (void *)t->buffer->data +
+					proc->user_buffer_offset;
+		tr.data.ptr.offsets = tr.data.ptr.buffer +
+					ALIGN(t->buffer->data_size,
+					    sizeof(void *));
 
 		if (put_user(cmd, (uint32_t __user *)ptr))
 			return -EFAULT;
@@ -2384,7 +2395,8 @@
 			printk(KERN_INFO "binder: %d:%d %s %d %d:%d, cmd %d"
 				"size %zd-%zd ptr %p-%p\n",
 			       proc->pid, thread->pid,
-			       (cmd == BR_TRANSACTION) ? "BR_TRANSACTION" : "BR_REPLY",
+			       (cmd == BR_TRANSACTION) ? "BR_TRANSACTION" :
+							 "BR_REPLY",
 			       t->debug_id, t->from ? t->from->proc->pid : 0,
 			       t->from ? t->from->pid : 0, cmd,
 			       t->buffer->data_size, t->buffer->offsets_size,
@@ -2430,7 +2442,9 @@
 		list_del_init(&w->entry);
 		switch (w->type) {
 		case BINDER_WORK_TRANSACTION: {
-			struct binder_transaction *t = container_of(w, struct binder_transaction, work);
+			struct binder_transaction *t;
+
+			t = container_of(w, struct binder_transaction, work);
 			if (t->buffer->target_node && !(t->flags & TF_ONE_WAY))
 				binder_send_failed_reply(t, BR_DEAD_REPLY);
 		} break;
@@ -2480,7 +2494,8 @@
 	return thread;
 }
 
-static int binder_free_thread(struct binder_proc *proc, struct binder_thread *thread)
+static int binder_free_thread(struct binder_proc *proc,
+			      struct binder_thread *thread)
 {
 	struct binder_transaction *t;
 	struct binder_transaction *send_reply = NULL;
@@ -2493,8 +2508,10 @@
 	while (t) {
 		active_transactions++;
 		if (binder_debug_mask & BINDER_DEBUG_DEAD_TRANSACTION)
-			printk(KERN_INFO "binder: release %d:%d transaction %d %s, still active\n",
-			       proc->pid, thread->pid, t->debug_id, (t->to_thread == thread) ? "in" : "out");
+			printk(KERN_INFO "binder: release %d:%d transaction %d "
+			       "%s, still active\n", proc->pid, thread->pid,
+			       t->debug_id,
+			       (t->to_thread == thread) ? "in" : "out");
 		if (t->to_thread == thread) {
 			t->to_proc = NULL;
 			t->to_thread = NULL;
@@ -2517,7 +2534,8 @@
 	return active_transactions;
 }
 
-static unsigned int binder_poll(struct file *filp, struct poll_table_struct *wait)
+static unsigned int binder_poll(struct file *filp,
+				struct poll_table_struct *wait)
 {
 	struct binder_proc *proc = filp->private_data;
 	struct binder_thread *thread = NULL;
@@ -2778,7 +2796,8 @@
 	proc->files = get_files_struct(current);
 	proc->vma = vma;
 
-	/*printk(KERN_INFO "binder_mmap: %d %lx-%lx maps %p\n", proc->pid, vma->vm_start, vma->vm_end, proc->buffer);*/
+	/*printk(KERN_INFO "binder_mmap: %d %lx-%lx maps %p\n",
+		 proc->pid, vma->vm_start, vma->vm_end, proc->buffer);*/
 	return 0;
 
 err_alloc_small_buf_failed:
@@ -2790,7 +2809,8 @@
 err_get_vm_area_failed:
 err_already_mapped:
 err_bad_arg:
-	printk(KERN_ERR "binder_mmap: %d %lx-%lx %s failed %d\n", proc->pid, vma->vm_start, vma->vm_end, failure_string, ret);
+	printk(KERN_ERR "binder_mmap: %d %lx-%lx %s failed %d\n",
+	       proc->pid, vma->vm_start, vma->vm_end, failure_string, ret);
 	return ret;
 }
 
@@ -2799,7 +2819,8 @@
 	struct binder_proc *proc;
 
 	if (binder_debug_mask & BINDER_DEBUG_OPEN_CLOSE)
-		printk(KERN_INFO "binder_open: %d:%d\n", current->group_leader->pid, current->pid);
+		printk(KERN_INFO "binder_open: %d:%d\n",
+		       current->group_leader->pid, current->pid);
 
 	proc = kzalloc(sizeof(*proc), GFP_KERNEL);
 	if (proc == NULL)
@@ -2821,7 +2842,9 @@
 		char strbuf[11];
 		snprintf(strbuf, sizeof(strbuf), "%u", proc->pid);
 		remove_proc_entry(strbuf, binder_proc_dir_entry_proc);
-		create_proc_read_entry(strbuf, S_IRUGO, binder_proc_dir_entry_proc, binder_read_proc_proc, proc);
+		create_proc_read_entry(strbuf, S_IRUGO,
+				       binder_proc_dir_entry_proc,
+				       binder_read_proc_proc, proc);
 	}
 
 	return 0;
@@ -2925,12 +2948,15 @@
 				}
 			}
 			if (binder_debug_mask & BINDER_DEBUG_DEAD_BINDER)
-				printk(KERN_INFO "binder: node %d now dead, refs %d, death %d\n", node->debug_id, incoming_refs, death);
+				printk(KERN_INFO "binder: node %d now dead, "
+				       "refs %d, death %d\n", node->debug_id,
+				       incoming_refs, death);
 		}
 	}
 	outgoing_refs = 0;
 	while ((n = rb_first(&proc->refs_by_desc))) {
-		struct binder_ref *ref = rb_entry(n, struct binder_ref, rb_node_desc);
+		struct binder_ref *ref = rb_entry(n, struct binder_ref,
+						  rb_node_desc);
 		outgoing_refs++;
 		binder_delete_ref(ref);
 	}
@@ -2938,12 +2964,15 @@
 	buffers = 0;
 
 	while ((n = rb_first(&proc->allocated_buffers))) {
-		struct binder_buffer *buffer = rb_entry(n, struct binder_buffer, rb_node);
+		struct binder_buffer *buffer = rb_entry(n, struct binder_buffer,
+							rb_node);
 		t = buffer->transaction;
 		if (t) {
 			t->buffer = NULL;
 			buffer->transaction = NULL;
-			printk(KERN_ERR "binder: release proc %d, transaction %d, not freed\n", proc->pid, t->debug_id);
+			printk(KERN_ERR "binder: release proc %d, "
+			       "transaction %d, not freed\n",
+			       proc->pid, t->debug_id);
 			/*BUG();*/
 		}
 		binder_free_buf(proc, buffer);
@@ -2957,8 +2986,13 @@
 		int i;
 		for (i = 0; i < proc->buffer_size / PAGE_SIZE; i++) {
 			if (proc->pages[i]) {
-				if (binder_debug_mask & BINDER_DEBUG_BUFFER_ALLOC)
-					printk(KERN_INFO "binder_release: %d: page %d at %p not freed\n", proc->pid, i, proc->buffer + i * PAGE_SIZE);
+				if (binder_debug_mask &
+				    BINDER_DEBUG_BUFFER_ALLOC)
+					printk(KERN_INFO
+					       "binder_release: %d: "
+					       "page %d at %p not freed\n",
+					       proc->pid, i,
+					       proc->buffer + i * PAGE_SIZE);
 				__free_page(proc->pages[i]);
 				page_count++;
 			}
@@ -2970,8 +3004,12 @@
 	put_task_struct(proc->tsk);
 
 	if (binder_debug_mask & BINDER_DEBUG_OPEN_CLOSE)
-		printk(KERN_INFO "binder_release: %d threads %d, nodes %d (ref %d), refs %d, active transactions %d, buffers %d, pages %d\n",
-		       proc->pid, threads, nodes, incoming_refs, outgoing_refs, active_transactions, buffers, page_count);
+		printk(KERN_INFO
+		       "binder_release: %d threads %d, nodes %d (ref %d), "
+		       "refs %d, active transactions %d, buffers %d, "
+		       "pages %d\n",
+		       proc->pid, threads, nodes, incoming_refs, outgoing_refs,
+		       active_transactions, buffers, page_count);
 
 	kfree(proc);
 }
@@ -2998,9 +3036,11 @@
 		mutex_unlock(&binder_deferred_lock);
 
 		files = NULL;
-		if (defer & BINDER_DEFERRED_PUT_FILES)
-			if ((files = proc->files))
+		if (defer & BINDER_DEFERRED_PUT_FILES) {
+			files = proc->files;
+			if (files)
 				proc->files = NULL;
+		}
 
 		if (defer & BINDER_DEFERRED_FLUSH)
 			binder_deferred_flush(proc);
@@ -3027,10 +3067,14 @@
 	mutex_unlock(&binder_deferred_lock);
 }
 
-static char *print_binder_transaction(char *buf, char *end, const char *prefix, struct binder_transaction *t)
+static char *print_binder_transaction(char *buf, char *end, const char *prefix,
+				      struct binder_transaction *t)
 {
-	buf += snprintf(buf, end - buf, "%s %d: %p from %d:%d to %d:%d code %x flags %x pri %ld r%d",
-			prefix, t->debug_id, t, t->from ? t->from->proc->pid : 0,
+	buf += snprintf(buf, end - buf,
+			"%s %d: %p from %d:%d to %d:%d code %x "
+			"flags %x pri %ld r%d",
+			prefix, t->debug_id, t,
+			t->from ? t->from->proc->pid : 0,
 			t->from ? t->from->pid : 0,
 			t->to_proc ? t->to_proc->pid : 0,
 			t->to_thread ? t->to_thread->pid : 0,
@@ -3053,7 +3097,8 @@
 	return buf;
 }
 
-static char *print_binder_buffer(char *buf, char *end, const char *prefix, struct binder_buffer *buffer)
+static char *print_binder_buffer(char *buf, char *end, const char *prefix,
+				 struct binder_buffer *buffer)
 {
 	buf += snprintf(buf, end - buf, "%s %d: %p size %zd:%zd %s\n",
 			prefix, buffer->debug_id, buffer->data,
@@ -3063,7 +3108,8 @@
 }
 
 static char *print_binder_work(char *buf, char *end, const char *prefix,
-	const char *transaction_prefix, struct binder_work *w)
+			       const char *transaction_prefix,
+			       struct binder_work *w)
 {
 	struct binder_node *node;
 	struct binder_transaction *t;
@@ -3080,7 +3126,8 @@
 	case BINDER_WORK_NODE:
 		node = container_of(w, struct binder_node, work);
 		buf += snprintf(buf, end - buf, "%snode work %d: u%p c%p\n",
-				prefix, node->debug_id, node->ptr, node->cookie);
+				prefix, node->debug_id, node->ptr,
+				node->cookie);
 		break;
 	case BINDER_WORK_DEAD_BINDER:
 		buf += snprintf(buf, end - buf, "%shas dead binder\n", prefix);
@@ -3101,27 +3148,33 @@
 	return buf;
 }
 
-static char *print_binder_thread(char *buf, char *end, struct binder_thread *thread, int print_always)
+static char *print_binder_thread(char *buf, char *end,
+				 struct binder_thread *thread,
+				 int print_always)
 {
 	struct binder_transaction *t;
 	struct binder_work *w;
 	char *start_buf = buf;
 	char *header_buf;
 
-	buf += snprintf(buf, end - buf, "  thread %d: l %02x\n", thread->pid, thread->looper);
+	buf += snprintf(buf, end - buf, "  thread %d: l %02x\n",
+			thread->pid, thread->looper);
 	header_buf = buf;
 	t = thread->transaction_stack;
 	while (t) {
 		if (buf >= end)
 			break;
 		if (t->from == thread) {
-			buf = print_binder_transaction(buf, end, "    outgoing transaction", t);
+			buf = print_binder_transaction(buf, end,
+						"    outgoing transaction", t);
 			t = t->from_parent;
 		} else if (t->to_thread == thread) {
-			buf = print_binder_transaction(buf, end, "    incoming transaction", t);
+			buf = print_binder_transaction(buf, end,
+						"    incoming transaction", t);
 			t = t->to_parent;
 		} else {
-			buf = print_binder_transaction(buf, end, "    bad transaction", t);
+			buf = print_binder_transaction(buf, end,
+						"    bad transaction", t);
 			t = NULL;
 		}
 	}
@@ -3142,11 +3195,14 @@
 	struct hlist_node *pos;
 	struct binder_work *w;
 	int count;
+
 	count = 0;
 	hlist_for_each_entry(ref, pos, &node->refs, node_entry)
 		count++;
 
-	buf += snprintf(buf, end - buf, "  node %d: u%p c%p hs %d hw %d ls %d lw %d is %d iw %d",
+	buf += snprintf(buf, end - buf,
+			"  node %d: u%p c%p hs %d hw %d ls %d lw %d "
+			"is %d iw %d",
 			node->debug_id, node->ptr, node->cookie,
 			node->has_strong_ref, node->has_weak_ref,
 			node->local_strong_refs, node->local_weak_refs,
@@ -3175,13 +3231,16 @@
 
 static char *print_binder_ref(char *buf, char *end, struct binder_ref *ref)
 {
-	buf += snprintf(buf, end - buf, "  ref %d: desc %d %snode %d s %d w %d d %p\n",
-			ref->debug_id, ref->desc, ref->node->proc ? "" : "dead ",
-			ref->node->debug_id, ref->strong, ref->weak, ref->death);
+	buf += snprintf(buf, end - buf,
+			"  ref %d: desc %d %snode %d s %d w %d d %p\n",
+			ref->debug_id, ref->desc,
+			ref->node->proc ? "" : "dead ", ref->node->debug_id,
+			ref->strong, ref->weak, ref->death);
 	return buf;
 }
 
-static char *print_binder_proc(char *buf, char *end, struct binder_proc *proc, int print_all)
+static char *print_binder_proc(char *buf, char *end,
+			       struct binder_proc *proc, int print_all)
 {
 	struct binder_work *w;
 	struct rb_node *n;
@@ -3191,19 +3250,34 @@
 	buf += snprintf(buf, end - buf, "proc %d\n", proc->pid);
 	header_buf = buf;
 
-	for (n = rb_first(&proc->threads); n != NULL && buf < end; n = rb_next(n))
-		buf = print_binder_thread(buf, end, rb_entry(n, struct binder_thread, rb_node), print_all);
-	for (n = rb_first(&proc->nodes); n != NULL && buf < end; n = rb_next(n)) {
-		struct binder_node *node = rb_entry(n, struct binder_node, rb_node);
+	for (n = rb_first(&proc->threads);
+	     n != NULL && buf < end;
+	     n = rb_next(n))
+		buf = print_binder_thread(buf, end,
+					  rb_entry(n, struct binder_thread,
+						   rb_node), print_all);
+	for (n = rb_first(&proc->nodes);
+	     n != NULL && buf < end;
+	     n = rb_next(n)) {
+		struct binder_node *node = rb_entry(n, struct binder_node,
+						    rb_node);
 		if (print_all || node->has_async_transaction)
 			buf = print_binder_node(buf, end, node);
 	}
 	if (print_all) {
-		for (n = rb_first(&proc->refs_by_desc); n != NULL && buf < end; n = rb_next(n))
-			buf = print_binder_ref(buf, end, rb_entry(n, struct binder_ref, rb_node_desc));
+		for (n = rb_first(&proc->refs_by_desc);
+		     n != NULL && buf < end;
+		     n = rb_next(n))
+			buf = print_binder_ref(buf, end,
+					       rb_entry(n, struct binder_ref,
+							rb_node_desc));
 	}
-	for (n = rb_first(&proc->allocated_buffers); n != NULL && buf < end; n = rb_next(n))
-		buf = print_binder_buffer(buf, end, "  buffer", rb_entry(n, struct binder_buffer, rb_node));
+	for (n = rb_first(&proc->allocated_buffers);
+	     n != NULL && buf < end;
+	     n = rb_next(n))
+		buf = print_binder_buffer(buf, end, "  buffer",
+					  rb_entry(n, struct binder_buffer,
+						   rb_node));
 	list_for_each_entry(w, &proc->todo, entry) {
 		if (buf >= end)
 			break;
@@ -3213,7 +3287,8 @@
 	list_for_each_entry(w, &proc->delivered_death, entry) {
 		if (buf >= end)
 			break;
-		buf += snprintf(buf, end - buf, "  has delivered dead binder\n");
+		buf += snprintf(buf, end - buf,
+				"  has delivered dead binder\n");
 		break;
 	}
 	if (!print_all && buf == header_buf)
@@ -3272,20 +3347,24 @@
 	"transaction_complete"
 };
 
-static char *print_binder_stats(char *buf, char *end, const char *prefix, struct binder_stats *stats)
+static char *print_binder_stats(char *buf, char *end, const char *prefix,
+				struct binder_stats *stats)
 {
 	int i;
 
-	BUILD_BUG_ON(ARRAY_SIZE(stats->bc) != ARRAY_SIZE(binder_command_strings));
+	BUILD_BUG_ON(ARRAY_SIZE(stats->bc) !=
+			ARRAY_SIZE(binder_command_strings));
 	for (i = 0; i < ARRAY_SIZE(stats->bc); i++) {
 		if (stats->bc[i])
 			buf += snprintf(buf, end - buf, "%s%s: %d\n", prefix,
-					binder_command_strings[i], stats->bc[i]);
+					binder_command_strings[i],
+					stats->bc[i]);
 		if (buf >= end)
 			return buf;
 	}
 
-	BUILD_BUG_ON(ARRAY_SIZE(stats->br) != ARRAY_SIZE(binder_return_strings));
+	BUILD_BUG_ON(ARRAY_SIZE(stats->br) !=
+			ARRAY_SIZE(binder_return_strings));
 	for (i = 0; i < ARRAY_SIZE(stats->br); i++) {
 		if (stats->br[i])
 			buf += snprintf(buf, end - buf, "%s%s: %d\n", prefix,
@@ -3294,13 +3373,17 @@
 			return buf;
 	}
 
-	BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) != ARRAY_SIZE(binder_objstat_strings));
-	BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) != ARRAY_SIZE(stats->obj_deleted));
+	BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) !=
+			ARRAY_SIZE(binder_objstat_strings));
+	BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) !=
+			ARRAY_SIZE(stats->obj_deleted));
 	for (i = 0; i < ARRAY_SIZE(stats->obj_created); i++) {
 		if (stats->obj_created[i] || stats->obj_deleted[i])
-			buf += snprintf(buf, end - buf, "%s%s: active %d total %d\n", prefix,
+			buf += snprintf(buf, end - buf,
+					"%s%s: active %d total %d\n", prefix,
 					binder_objstat_strings[i],
-					stats->obj_created[i] - stats->obj_deleted[i],
+					stats->obj_created[i] -
+						stats->obj_deleted[i],
 					stats->obj_created[i]);
 		if (buf >= end)
 			return buf;
@@ -3308,7 +3391,8 @@
 	return buf;
 }
 
-static char *print_binder_proc_stats(char *buf, char *end, struct binder_proc *proc)
+static char *print_binder_proc_stats(char *buf, char *end,
+				     struct binder_proc *proc)
 {
 	struct binder_work *w;
 	struct rb_node *n;
@@ -3340,12 +3424,14 @@
 	strong = 0;
 	weak = 0;
 	for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) {
-		struct binder_ref *ref = rb_entry(n, struct binder_ref, rb_node_desc);
+		struct binder_ref *ref = rb_entry(n, struct binder_ref,
+						  rb_node_desc);
 		count++;
 		strong += ref->strong;
 		weak += ref->weak;
 	}
-	buf += snprintf(buf, end - buf, "  refs: %d s %d w %d\n", count, strong, weak);
+	buf += snprintf(buf, end - buf, "  refs: %d s %d w %d\n",
+			count, strong, weak);
 	if (buf >= end)
 		return buf;
 
@@ -3376,8 +3462,8 @@
 }
 
 
-static int binder_read_proc_state(
-	char *page, char **start, off_t off, int count, int *eof, void *data)
+static int binder_read_proc_state(char *page, char **start, off_t off,
+				  int count, int *eof, void *data)
 {
 	struct binder_proc *proc;
 	struct hlist_node *pos;
@@ -3424,8 +3510,8 @@
 	return len < count ? len  : count;
 }
 
-static int binder_read_proc_stats(
-	char *page, char **start, off_t off, int count, int *eof, void *data)
+static int binder_read_proc_stats(char *page, char **start, off_t off,
+				  int count, int *eof, void *data)
 {
 	struct binder_proc *proc;
 	struct hlist_node *pos;
@@ -3464,8 +3550,8 @@
 	return len < count ? len  : count;
 }
 
-static int binder_read_proc_transactions(
-	char *page, char **start, off_t off, int count, int *eof, void *data)
+static int binder_read_proc_transactions(char *page, char **start, off_t off,
+					 int count, int *eof, void *data)
 {
 	struct binder_proc *proc;
 	struct hlist_node *pos;
@@ -3502,8 +3588,8 @@
 	return len < count ? len  : count;
 }
 
-static int binder_read_proc_proc(
-	char *page, char **start, off_t off, int count, int *eof, void *data)
+static int binder_read_proc_proc(char *page, char **start, off_t off,
+				 int count, int *eof, void *data)
 {
 	struct binder_proc *proc = data;
 	int len = 0;
@@ -3533,9 +3619,12 @@
 	return len < count ? len  : count;
 }
 
-static char *print_binder_transaction_log_entry(char *buf, char *end, struct binder_transaction_log_entry *e)
+static char *print_binder_transaction_log_entry(char *buf, char *end,
+					struct binder_transaction_log_entry *e)
 {
-	buf += snprintf(buf, end - buf, "%d: %s from %d:%d to %d:%d node %d handle %d size %d:%d\n",
+	buf += snprintf(buf, end - buf,
+			"%d: %s from %d:%d to %d:%d node %d handle %d "
+			"size %d:%d\n",
 			e->debug_id, (e->call_type == 2) ? "reply" :
 			((e->call_type == 1) ? "async" : "call "), e->from_proc,
 			e->from_thread, e->to_proc, e->to_thread, e->to_node,
@@ -3559,13 +3648,15 @@
 		for (i = log->next; i < ARRAY_SIZE(log->entry); i++) {
 			if (buf >= end)
 				break;
-			buf = print_binder_transaction_log_entry(buf, end, &log->entry[i]);
+			buf = print_binder_transaction_log_entry(buf, end,
+								&log->entry[i]);
 		}
 	}
 	for (i = 0; i < log->next; i++) {
 		if (buf >= end)
 			break;
-		buf = print_binder_transaction_log_entry(buf, end, &log->entry[i]);
+		buf = print_binder_transaction_log_entry(buf, end,
+							 &log->entry[i]);
 	}
 
 	*start = page + off;
@@ -3579,7 +3670,7 @@
 	return len < count ? len  : count;
 }
 
-static struct file_operations binder_fops = {
+static const struct file_operations binder_fops = {
 	.owner = THIS_MODULE,
 	.poll = binder_poll,
 	.unlocked_ioctl = binder_ioctl,
@@ -3601,14 +3692,35 @@
 
 	binder_proc_dir_entry_root = proc_mkdir("binder", NULL);
 	if (binder_proc_dir_entry_root)
-		binder_proc_dir_entry_proc = proc_mkdir("proc", binder_proc_dir_entry_root);
+		binder_proc_dir_entry_proc = proc_mkdir("proc",
+						binder_proc_dir_entry_root);
 	ret = misc_register(&binder_miscdev);
 	if (binder_proc_dir_entry_root) {
-		create_proc_read_entry("state", S_IRUGO, binder_proc_dir_entry_root, binder_read_proc_state, NULL);
-		create_proc_read_entry("stats", S_IRUGO, binder_proc_dir_entry_root, binder_read_proc_stats, NULL);
-		create_proc_read_entry("transactions", S_IRUGO, binder_proc_dir_entry_root, binder_read_proc_transactions, NULL);
-		create_proc_read_entry("transaction_log", S_IRUGO, binder_proc_dir_entry_root, binder_read_proc_transaction_log, &binder_transaction_log);
-		create_proc_read_entry("failed_transaction_log", S_IRUGO, binder_proc_dir_entry_root, binder_read_proc_transaction_log, &binder_transaction_log_failed);
+		create_proc_read_entry("state",
+				       S_IRUGO,
+				       binder_proc_dir_entry_root,
+				       binder_read_proc_state,
+				       NULL);
+		create_proc_read_entry("stats",
+				       S_IRUGO,
+				       binder_proc_dir_entry_root,
+				       binder_read_proc_stats,
+				       NULL);
+		create_proc_read_entry("transactions",
+				       S_IRUGO,
+				       binder_proc_dir_entry_root,
+				       binder_read_proc_transactions,
+				       NULL);
+		create_proc_read_entry("transaction_log",
+				       S_IRUGO,
+				       binder_proc_dir_entry_root,
+				       binder_read_proc_transaction_log,
+				       &binder_transaction_log);
+		create_proc_read_entry("failed_transaction_log",
+				       S_IRUGO,
+				       binder_proc_dir_entry_root,
+				       binder_read_proc_transaction_log,
+				       &binder_transaction_log_failed);
 	}
 	return ret;
 }
diff --git a/drivers/staging/android/logger.c b/drivers/staging/android/logger.c
index ab32003..6c10b45 100644
--- a/drivers/staging/android/logger.c
+++ b/drivers/staging/android/logger.c
@@ -35,7 +35,7 @@
  * mutex 'mutex'.
  */
 struct logger_log {
-	unsigned char *		buffer;	/* the ring buffer itself */
+	unsigned char 		*buffer;/* the ring buffer itself */
 	struct miscdevice	misc;	/* misc device representing the log */
 	wait_queue_head_t	wq;	/* wait queue for readers */
 	struct list_head	readers; /* this log's readers */
@@ -52,7 +52,7 @@
  * reference counting. The structure is protected by log->mutex.
  */
 struct logger_reader {
-	struct logger_log *	log;	/* associated log */
+	struct logger_log	*log;	/* associated log */
 	struct list_head	list;	/* entry in logger_log's list */
 	size_t			r_off;	/* current read head offset */
 };
@@ -74,7 +74,7 @@
  * file->logger_log. Thus what file->private_data points at depends on whether
  * or not the file was opened for reading. This function hides that dirtiness.
  */
-static inline struct logger_log * file_get_log(struct file *file)
+static inline struct logger_log *file_get_log(struct file *file)
 {
 	if (file->f_mode & FMODE_READ) {
 		struct logger_reader *reader = file->private_data;
@@ -379,7 +379,7 @@
 	return ret;
 }
 
-static struct logger_log * get_log_from_minor(int);
+static struct logger_log *get_log_from_minor(int);
 
 /*
  * logger_open - the log's open() file operation
@@ -519,7 +519,7 @@
 	return ret;
 }
 
-static struct file_operations logger_fops = {
+static const struct file_operations logger_fops = {
 	.owner = THIS_MODULE,
 	.read = logger_read,
 	.aio_write = logger_aio_write,
@@ -557,7 +557,7 @@
 DEFINE_LOGGER_DEVICE(log_events, LOGGER_LOG_EVENTS, 256*1024)
 DEFINE_LOGGER_DEVICE(log_radio, LOGGER_LOG_RADIO, 64*1024)
 
-static struct logger_log * get_log_from_minor(int minor)
+static struct logger_log *get_log_from_minor(int minor)
 {
 	if (log_main.misc.minor == minor)
 		return &log_main;
diff --git a/drivers/staging/android/lowmemorykiller.c b/drivers/staging/android/lowmemorykiller.c
index 3715d56..fe72240 100644
--- a/drivers/staging/android/lowmemorykiller.c
+++ b/drivers/staging/android/lowmemorykiller.c
@@ -34,18 +34,24 @@
 };
 static int lowmem_adj_size = 4;
 static size_t lowmem_minfree[6] = {
-	3*512, // 6MB
-	2*1024, // 8MB
-	4*1024, // 16MB
-	16*1024, // 64MB
+	3 * 512,	/* 6MB */
+	2 * 1024,	/* 8MB */
+	4 * 1024,	/* 16MB */
+	16 * 1024,	/* 64MB */
 };
 static int lowmem_minfree_size = 4;
 
-#define lowmem_print(level, x...) do { if(lowmem_debug_level >= (level)) printk(x); } while(0)
+#define lowmem_print(level, x...)			\
+	do {						\
+		if (lowmem_debug_level >= (level))	\
+			printk(x);			\
+	} while (0)
 
 module_param_named(cost, lowmem_shrinker.seeks, int, S_IRUGO | S_IWUSR);
-module_param_array_named(adj, lowmem_adj, int, &lowmem_adj_size, S_IRUGO | S_IWUSR);
-module_param_array_named(minfree, lowmem_minfree, uint, &lowmem_minfree_size, S_IRUGO | S_IWUSR);
+module_param_array_named(adj, lowmem_adj, int, &lowmem_adj_size,
+			 S_IRUGO | S_IWUSR);
+module_param_array_named(minfree, lowmem_minfree, uint, &lowmem_minfree_size,
+			 S_IRUGO | S_IWUSR);
 module_param_named(debug_level, lowmem_debug_level, uint, S_IRUGO | S_IWUSR);
 
 static int lowmem_shrink(int nr_to_scan, gfp_t gfp_mask)
@@ -57,46 +63,77 @@
 	int i;
 	int min_adj = OOM_ADJUST_MAX + 1;
 	int selected_tasksize = 0;
+	int selected_oom_adj;
 	int array_size = ARRAY_SIZE(lowmem_adj);
-	int other_free = global_page_state(NR_FREE_PAGES) + global_page_state(NR_FILE_PAGES);
-	if(lowmem_adj_size < array_size)
+	int other_free = global_page_state(NR_FREE_PAGES);
+	int other_file = global_page_state(NR_FILE_PAGES);
+
+	if (lowmem_adj_size < array_size)
 		array_size = lowmem_adj_size;
-	if(lowmem_minfree_size < array_size)
+	if (lowmem_minfree_size < array_size)
 		array_size = lowmem_minfree_size;
-	for(i = 0; i < array_size; i++) {
-		if(other_free < lowmem_minfree[i]) {
+	for (i = 0; i < array_size; i++) {
+		if (other_free < lowmem_minfree[i] &&
+		    other_file < lowmem_minfree[i]) {
 			min_adj = lowmem_adj[i];
 			break;
 		}
 	}
-	if(nr_to_scan > 0)
-		lowmem_print(3, "lowmem_shrink %d, %x, ofree %d, ma %d\n", nr_to_scan, gfp_mask, other_free, min_adj);
+	if (nr_to_scan > 0)
+		lowmem_print(3, "lowmem_shrink %d, %x, ofree %d %d, ma %d\n",
+			     nr_to_scan, gfp_mask, other_free, other_file,
+			     min_adj);
+	rem = global_page_state(NR_ACTIVE_ANON) +
+		global_page_state(NR_ACTIVE_FILE) +
+		global_page_state(NR_INACTIVE_ANON) +
+		global_page_state(NR_INACTIVE_FILE);
+	if (nr_to_scan <= 0 || min_adj == OOM_ADJUST_MAX + 1) {
+		lowmem_print(5, "lowmem_shrink %d, %x, return %d\n",
+			     nr_to_scan, gfp_mask, rem);
+		return rem;
+	}
+	selected_oom_adj = min_adj;
+
 	read_lock(&tasklist_lock);
 	for_each_process(p) {
-		if(p->oomkilladj >= 0 && p->mm) {
-			tasksize = get_mm_rss(p->mm);
-			if(nr_to_scan > 0 && tasksize > 0 && p->oomkilladj >= min_adj) {
-				if(selected == NULL ||
-				   p->oomkilladj > selected->oomkilladj ||
-				   (p->oomkilladj == selected->oomkilladj &&
-				    tasksize > selected_tasksize)) {
-					selected = p;
-					selected_tasksize = tasksize;
-					lowmem_print(2, "select %d (%s), adj %d, size %d, to kill\n",
-					             p->pid, p->comm, p->oomkilladj, tasksize);
-				}
-			}
-			rem += tasksize;
+		int oom_adj;
+
+		task_lock(p);
+		if (!p->mm) {
+			task_unlock(p);
+			continue;
 		}
+		oom_adj = p->oomkilladj;
+		if (oom_adj < min_adj) {
+			task_unlock(p);
+			continue;
+		}
+		tasksize = get_mm_rss(p->mm);
+		task_unlock(p);
+		if (tasksize <= 0)
+			continue;
+		if (selected) {
+			if (oom_adj < selected_oom_adj)
+				continue;
+			if (oom_adj == selected_oom_adj &&
+			    tasksize <= selected_tasksize)
+				continue;
+		}
+		selected = p;
+		selected_tasksize = tasksize;
+		selected_oom_adj = oom_adj;
+		lowmem_print(2, "select %d (%s), adj %d, size %d, to kill\n",
+			     p->pid, p->comm, oom_adj, tasksize);
 	}
-	if(selected != NULL) {
+	if (selected) {
 		lowmem_print(1, "send sigkill to %d (%s), adj %d, size %d\n",
-		             selected->pid, selected->comm,
-		             selected->oomkilladj, selected_tasksize);
+			     selected->pid, selected->comm,
+			     selected_oom_adj, selected_tasksize);
 		force_sig(SIGKILL, selected);
 		rem -= selected_tasksize;
 	}
-	lowmem_print(4, "lowmem_shrink %d, %x, return %d\n", nr_to_scan, gfp_mask, rem);
+	lowmem_print(4, "lowmem_shrink %d, %x, return %d\n",
+		     nr_to_scan, gfp_mask, rem);
 	read_unlock(&tasklist_lock);
 	return rem;
 }
diff --git a/drivers/staging/android/ram_console.c b/drivers/staging/android/ram_console.c
index 3375c1c..8f18a59 100644
--- a/drivers/staging/android/ram_console.c
+++ b/drivers/staging/android/ram_console.c
@@ -20,7 +20,7 @@
 #include <linux/proc_fs.h>
 #include <linux/string.h>
 #include <linux/uaccess.h>
-#include <asm/io.h>
+#include <linux/io.h>
 
 #ifdef CONFIG_ANDROID_RAM_CONSOLE_ERROR_CORRECTION
 #include <linux/rslib.h>
@@ -225,8 +225,9 @@
 		buffer_size - sizeof(struct ram_console_buffer);
 
 	if (ram_console_buffer_size > buffer_size) {
-		pr_err("ram_console: buffer %p, invalid size %zu, datasize %zu\n",
-		       buffer, buffer_size, ram_console_buffer_size);
+		pr_err("ram_console: buffer %p, invalid size %zu, "
+		       "datasize %zu\n", buffer, buffer_size,
+		       ram_console_buffer_size);
 		return 0;
 	}
 
@@ -365,7 +366,7 @@
 	return count;
 }
 
-static struct file_operations ram_console_file_ops = {
+static const struct file_operations ram_console_file_ops = {
 	.owner = THIS_MODULE,
 	.read = ram_console_read_old,
 };
diff --git a/drivers/staging/android/timed_gpio.c b/drivers/staging/android/timed_gpio.c
index 33daff0..be7cdaa 100644
--- a/drivers/staging/android/timed_gpio.c
+++ b/drivers/staging/android/timed_gpio.c
@@ -20,13 +20,12 @@
 #include <linux/err.h>
 #include <linux/gpio.h>
 
+#include "timed_output.h"
 #include "timed_gpio.h"
 
 
-static struct class *timed_gpio_class;
-
 struct timed_gpio_data {
-	struct device *dev;
+	struct timed_output_dev dev;
 	struct hrtimer timer;
 	spinlock_t lock;
 	unsigned 	gpio;
@@ -36,70 +35,62 @@
 
 static enum hrtimer_restart gpio_timer_func(struct hrtimer *timer)
 {
-	struct timed_gpio_data *gpio_data = container_of(timer, struct timed_gpio_data, timer);
+	struct timed_gpio_data *data =
+		container_of(timer, struct timed_gpio_data, timer);
 
-	gpio_direction_output(gpio_data->gpio, gpio_data->active_low ? 1 : 0);
+	gpio_direction_output(data->gpio, data->active_low ? 1 : 0);
 	return HRTIMER_NORESTART;
 }
 
-static ssize_t gpio_enable_show(struct device *dev, struct device_attribute *attr, char *buf)
+static int gpio_get_time(struct timed_output_dev *dev)
 {
-	struct timed_gpio_data *gpio_data = dev_get_drvdata(dev);
-	int remaining;
+	struct timed_gpio_data	*data =
+		container_of(dev, struct timed_gpio_data, dev);
 
-	if (hrtimer_active(&gpio_data->timer)) {
-		ktime_t r = hrtimer_get_remaining(&gpio_data->timer);
+	if (hrtimer_active(&data->timer)) {
+		ktime_t r = hrtimer_get_remaining(&data->timer);
 		struct timeval t = ktime_to_timeval(r);
-		remaining = t.tv_sec * 1000 + t.tv_usec / 1000;
+		return t.tv_sec * 1000 + t.tv_usec / 1000;
 	} else
-		remaining = 0;
-
-	return sprintf(buf, "%d\n", remaining);
+		return 0;
 }
 
-static ssize_t gpio_enable_store(
-		struct device *dev, struct device_attribute *attr,
-		const char *buf, size_t size)
+static void gpio_enable(struct timed_output_dev *dev, int value)
 {
-	struct timed_gpio_data *gpio_data = dev_get_drvdata(dev);
-	int value;
+	struct timed_gpio_data	*data =
+		container_of(dev, struct timed_gpio_data, dev);
 	unsigned long	flags;
 
-	sscanf(buf, "%d", &value);
-
-	spin_lock_irqsave(&gpio_data->lock, flags);
+	spin_lock_irqsave(&data->lock, flags);
 
 	/* cancel previous timer and set GPIO according to value */
-	hrtimer_cancel(&gpio_data->timer);
-	gpio_direction_output(gpio_data->gpio, gpio_data->active_low ? !value : !!value);
+	hrtimer_cancel(&data->timer);
+	gpio_direction_output(data->gpio, data->active_low ? !value : !!value);
 
 	if (value > 0) {
-		if (value > gpio_data->max_timeout)
-			value = gpio_data->max_timeout;
+		if (value > data->max_timeout)
+			value = data->max_timeout;
 
-		hrtimer_start(&gpio_data->timer,
-						ktime_set(value / 1000, (value % 1000) * 1000000),
-						HRTIMER_MODE_REL);
+		hrtimer_start(&data->timer,
+			ktime_set(value / 1000, (value % 1000) * 1000000),
+			HRTIMER_MODE_REL);
 	}
 
-	spin_unlock_irqrestore(&gpio_data->lock, flags);
-
-	return size;
+	spin_unlock_irqrestore(&data->lock, flags);
 }
 
-static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR, gpio_enable_show, gpio_enable_store);
-
 static int timed_gpio_probe(struct platform_device *pdev)
 {
 	struct timed_gpio_platform_data *pdata = pdev->dev.platform_data;
 	struct timed_gpio *cur_gpio;
 	struct timed_gpio_data *gpio_data, *gpio_dat;
-	int i, ret = 0;
+	int i, j, ret = 0;
 
 	if (!pdata)
 		return -EBUSY;
 
-	gpio_data = kzalloc(sizeof(struct timed_gpio_data) * pdata->num_gpios, GFP_KERNEL);
+	gpio_data = kzalloc(sizeof(struct timed_gpio_data) * pdata->num_gpios,
+			GFP_KERNEL);
 	if (!gpio_data)
 		return -ENOMEM;
 
@@ -107,23 +98,26 @@
 		cur_gpio = &pdata->gpios[i];
 		gpio_dat = &gpio_data[i];
 
-		hrtimer_init(&gpio_dat->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
+		hrtimer_init(&gpio_dat->timer, CLOCK_MONOTONIC,
+				HRTIMER_MODE_REL);
 		gpio_dat->timer.function = gpio_timer_func;
 		spin_lock_init(&gpio_dat->lock);
 
+		gpio_dat->dev.name = cur_gpio->name;
+		gpio_dat->dev.get_time = gpio_get_time;
+		gpio_dat->dev.enable = gpio_enable;
+		ret = timed_output_dev_register(&gpio_dat->dev);
+		if (ret < 0) {
+			for (j = 0; j < i; j++)
+				timed_output_dev_unregister(&gpio_data[i].dev);
+			kfree(gpio_data);
+			return ret;
+		}
+
 		gpio_dat->gpio = cur_gpio->gpio;
 		gpio_dat->max_timeout = cur_gpio->max_timeout;
 		gpio_dat->active_low = cur_gpio->active_low;
 		gpio_direction_output(gpio_dat->gpio, gpio_dat->active_low);
-
-		gpio_dat->dev = device_create(timed_gpio_class, &pdev->dev, 0, "%s", cur_gpio->name);
-		if (unlikely(IS_ERR(gpio_dat->dev)))
-			return PTR_ERR(gpio_dat->dev);
-
-		dev_set_drvdata(gpio_dat->dev, gpio_dat);
-		ret = device_create_file(gpio_dat->dev, &dev_attr_enable);
-		if (ret)
-			return ret;
 	}
 
 	platform_set_drvdata(pdev, gpio_data);
@@ -137,10 +131,8 @@
 	struct timed_gpio_data *gpio_data = platform_get_drvdata(pdev);
 	int i;
 
-	for (i = 0; i < pdata->num_gpios; i++) {
-		device_remove_file(gpio_data[i].dev, &dev_attr_enable);
-		device_unregister(gpio_data[i].dev);
-	}
+	for (i = 0; i < pdata->num_gpios; i++)
+		timed_output_dev_unregister(&gpio_data[i].dev);
 
 	kfree(gpio_data);
 
@@ -151,22 +143,18 @@
 	.probe		= timed_gpio_probe,
 	.remove		= timed_gpio_remove,
 	.driver		= {
-		.name		= "timed-gpio",
+		.name		= TIMED_GPIO_NAME,
 		.owner		= THIS_MODULE,
 	},
 };
 
 static int __init timed_gpio_init(void)
 {
-	timed_gpio_class = class_create(THIS_MODULE, "timed_output");
-	if (IS_ERR(timed_gpio_class))
-		return PTR_ERR(timed_gpio_class);
 	return platform_driver_register(&timed_gpio_driver);
 }
 
 static void __exit timed_gpio_exit(void)
 {
-	class_destroy(timed_gpio_class);
 	platform_driver_unregister(&timed_gpio_driver);
 }
 
diff --git a/drivers/staging/android/timed_gpio.h b/drivers/staging/android/timed_gpio.h
index 78449b2..a0e15f8 100644
--- a/drivers/staging/android/timed_gpio.h
+++ b/drivers/staging/android/timed_gpio.h
@@ -16,10 +16,12 @@
 #ifndef _LINUX_TIMED_GPIO_H
 #define _LINUX_TIMED_GPIO_H
 
+#define TIMED_GPIO_NAME "timed-gpio"
+
 struct timed_gpio {
 	const char *name;
 	unsigned 	gpio;
-	int     max_timeout;
+	int		max_timeout;
 	u8 		active_low;
 };
 
diff --git a/drivers/staging/android/timed_output.c b/drivers/staging/android/timed_output.c
new file mode 100644
index 0000000..62e7918
--- /dev/null
+++ b/drivers/staging/android/timed_output.c
@@ -0,0 +1,121 @@
+/* drivers/misc/timed_output.c
+ *
+ * Copyright (C) 2009 Google, Inc.
+ * Author: Mike Lockwood <lockwood@android.com>
+ *
+ * This software is licensed under the terms of the GNU General Public
+ * License version 2, as published by the Free Software Foundation, and
+ * may be copied, distributed, and modified under those terms.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ */
+
+#include <linux/module.h>
+#include <linux/types.h>
+#include <linux/device.h>
+#include <linux/fs.h>
+#include <linux/err.h>
+
+#include "timed_output.h"
+
+static struct class *timed_output_class;
+static atomic_t device_count;
+
+static ssize_t enable_show(struct device *dev, struct device_attribute *attr,
+		char *buf)
+{
+	struct timed_output_dev *tdev = dev_get_drvdata(dev);
+	int remaining = tdev->get_time(tdev);
+
+	return sprintf(buf, "%d\n", remaining);
+}
+
+static ssize_t enable_store(
+		struct device *dev, struct device_attribute *attr,
+		const char *buf, size_t size)
+{
+	struct timed_output_dev *tdev = dev_get_drvdata(dev);
+	int value;
+
+	sscanf(buf, "%d", &value);
+	tdev->enable(tdev, value);
+
+	return size;
+}
+
+static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR, enable_show, enable_store);
+
+static int create_timed_output_class(void)
+{
+	if (!timed_output_class) {
+		timed_output_class = class_create(THIS_MODULE, "timed_output");
+		if (IS_ERR(timed_output_class))
+			return PTR_ERR(timed_output_class);
+		atomic_set(&device_count, 0);
+	}
+
+	return 0;
+}
+
+int timed_output_dev_register(struct timed_output_dev *tdev)
+{
+	int ret;
+
+	if (!tdev || !tdev->name || !tdev->enable || !tdev->get_time)
+		return -EINVAL;
+
+	ret = create_timed_output_class();
+	if (ret < 0)
+		return ret;
+
+	tdev->index = atomic_inc_return(&device_count);
+	tdev->dev = device_create(timed_output_class, NULL,
+		MKDEV(0, tdev->index), NULL, tdev->name);
+	if (IS_ERR(tdev->dev))
+		return PTR_ERR(tdev->dev);
+
+	ret = device_create_file(tdev->dev, &dev_attr_enable);
+	if (ret < 0)
+		goto err_create_file;
+
+	dev_set_drvdata(tdev->dev, tdev);
+	tdev->state = 0;
+	return 0;
+
+err_create_file:
+	device_destroy(timed_output_class, MKDEV(0, tdev->index));
+	printk(KERN_ERR "timed_output: Failed to register driver %s\n",
+			tdev->name);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(timed_output_dev_register);
+
+void timed_output_dev_unregister(struct timed_output_dev *tdev)
+{
+	device_remove_file(tdev->dev, &dev_attr_enable);
+	device_destroy(timed_output_class, MKDEV(0, tdev->index));
+	dev_set_drvdata(tdev->dev, NULL);
+}
+EXPORT_SYMBOL_GPL(timed_output_dev_unregister);
+
+static int __init timed_output_init(void)
+{
+	return create_timed_output_class();
+}
+
+static void __exit timed_output_exit(void)
+{
+	class_destroy(timed_output_class);
+}
+
+module_init(timed_output_init);
+module_exit(timed_output_exit);
+
+MODULE_AUTHOR("Mike Lockwood <lockwood@android.com>");
+MODULE_DESCRIPTION("timed output class driver");
+MODULE_LICENSE("GPL");
diff --git a/drivers/staging/android/timed_output.h b/drivers/staging/android/timed_output.h
new file mode 100644
index 0000000..ec907ab
--- /dev/null
+++ b/drivers/staging/android/timed_output.h
@@ -0,0 +1,37 @@
+/* include/linux/timed_output.h
+ *
+ * Copyright (C) 2008 Google, Inc.
+ *
+ * This software is licensed under the terms of the GNU General Public
+ * License version 2, as published by the Free Software Foundation, and
+ * may be copied, distributed, and modified under those terms.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+*/
+
+#ifndef _LINUX_TIMED_OUTPUT_H
+#define _LINUX_TIMED_OUTPUT_H
+
+struct timed_output_dev {
+	const char	*name;
+
+	/* enable the output and set the timer */
+	void	(*enable)(struct timed_output_dev *sdev, int timeout);
+
+	/* returns the current number of milliseconds remaining on the timer */
+	int		(*get_time)(struct timed_output_dev *sdev);
+
+	/* private data */
+	struct device	*dev;
+	int		index;
+	int		state;
+};
+
+extern int timed_output_dev_register(struct timed_output_dev *dev);
+extern void timed_output_dev_unregister(struct timed_output_dev *dev);
+
+#endif
diff --git a/drivers/staging/asus_oled/asus_oled.c b/drivers/staging/asus_oled/asus_oled.c
index 04dde4b..9270f5d 100644
--- a/drivers/staging/asus_oled/asus_oled.c
+++ b/drivers/staging/asus_oled/asus_oled.c
@@ -516,7 +516,7 @@
 	max_offs = odev->width * odev->height;
 
 	while (offs < count && odev->buf_offs < max_offs) {
-		int ret;
+		int ret = 0;
 
 		if (buf[offs] == '1' || buf[offs] == '#') {
 			ret = append_values(odev, 1, 1);
diff --git a/drivers/staging/b3dfg/b3dfg.c b/drivers/staging/b3dfg/b3dfg.c
index 75ebe33..eec9c99 100644
--- a/drivers/staging/b3dfg/b3dfg.c
+++ b/drivers/staging/b3dfg/b3dfg.c
@@ -35,14 +35,13 @@
 #include <linux/poll.h>
 #include <linux/wait.h>
 #include <linux/mm.h>
-#include <linux/version.h>
 #include <linux/uaccess.h>
 
 static unsigned int b3dfg_nbuf = 2;
 
 module_param_named(buffer_count, b3dfg_nbuf, uint, 0444);
 
-MODULE_PARM_DESC(buffer_count, "Number of buffers (min 2, default 2)\n");
+MODULE_PARM_DESC(buffer_count, "Number of buffers (min 2, default 2)");
 
 MODULE_AUTHOR("Daniel Drake <ddrake@brontes3d.com>");
 MODULE_DESCRIPTION("Brontes frame grabber driver");
diff --git a/drivers/staging/comedi/Kconfig b/drivers/staging/comedi/Kconfig
index 2d819d2..af723cb 100644
--- a/drivers/staging/comedi/Kconfig
+++ b/drivers/staging/comedi/Kconfig
@@ -13,13 +13,6 @@
 	  This is an option for use by developers; most people should
 	  say N here. This enables comedi core and driver debugging.
 
-config COMEDI_RT
-	tristate "Comedi Real-time support"
-	depends on COMEDI && RT
-	default N
-	---help---
-	  Enable Real time support for the Comedi core.
-
 config COMEDI_PCI_DRIVERS
 	tristate "Comedi PCI drivers"
 	depends on COMEDI && PCI
@@ -29,10 +22,10 @@
 
 config COMEDI_PCMCIA_DRIVERS
 	tristate "Comedi PCMCIA drivers"
-	depends on COMEDI && PCMCIAI
+	depends on COMEDI && PCMCIA && PCCARD
 	default N
 	---help---
-	  Enable lots of comedi PCMCIA drivers to be built
+	  Enable lots of comedi PCMCIA and PCCARD drivers to be built
 
 config COMEDI_USB_DRIVERS
 	tristate "Comedi USB drivers"
diff --git a/drivers/staging/comedi/Makefile b/drivers/staging/comedi/Makefile
index afd1a19..05811f7 100644
--- a/drivers/staging/comedi/Makefile
+++ b/drivers/staging/comedi/Makefile
@@ -1,5 +1,4 @@
 obj-$(CONFIG_COMEDI) += comedi.o
-obj-$(CONFIG_COMEDI_RT) += comedi_rt.o
 
 obj-$(CONFIG_COMEDI)	+= kcomedilib/
 obj-$(CONFIG_COMEDI)	+= drivers/
@@ -11,7 +10,3 @@
 	drivers.o	\
 	comedi_compat32.o \
 	comedi_ksyms.o	\
-
-comedi_rt-objs :=	\
-	rt_pend_tq.o	\
-	rt.o
diff --git a/drivers/staging/comedi/comedi.h b/drivers/staging/comedi/comedi.h
index e6b5f16..8101cea 100644
--- a/drivers/staging/comedi/comedi.h
+++ b/drivers/staging/comedi/comedi.h
@@ -188,7 +188,6 @@
 #define SDF_WRITABLE	0x00020000	/* subdevice can be written (e.g. analog output) */
 #define SDF_WRITEABLE	SDF_WRITABLE	/* spelling error in API */
 #define SDF_INTERNAL	0x00040000	/* subdevice does not have externally visible lines */
-#define SDF_RT		0x00080000	/* DEPRECATED: subdevice is RT capable */
 #define SDF_GROUND	0x00100000	/* can do aref=ground */
 #define SDF_COMMON	0x00200000	/* can do aref=common */
 #define SDF_DIFF	0x00400000	/* can do aref=diff */
diff --git a/drivers/staging/comedi/comedi_fops.c b/drivers/staging/comedi/comedi_fops.c
index 19dce2e..9d7c993 100644
--- a/drivers/staging/comedi/comedi_fops.c
+++ b/drivers/staging/comedi/comedi_fops.c
@@ -44,6 +44,7 @@
 #include <linux/fs.h>
 #include "comedidev.h"
 #include <linux/cdev.h>
+#include <linux/stat.h>
 
 #include <linux/io.h>
 #include <linux/uaccess.h>
@@ -92,6 +93,15 @@
 static int comedi_fasync(int fd, struct file *file, int on);
 
 static int is_device_busy(struct comedi_device *dev);
+static int resize_async_buffer(struct comedi_device *dev,
+			       struct comedi_subdevice *s,
+			       struct comedi_async *async, unsigned new_size);
+
+/* declarations for sysfs attribute files */
+static struct device_attribute dev_attr_max_read_buffer_kb;
+static struct device_attribute dev_attr_read_buffer_kb;
+static struct device_attribute dev_attr_max_write_buffer_kb;
+static struct device_attribute dev_attr_write_buffer_kb;
 
 #ifdef HAVE_UNLOCKED_IOCTL
 static long comedi_unlocked_ioctl(struct file *file, unsigned int cmd,
@@ -277,7 +287,7 @@
 	struct comedi_bufconfig bc;
 	struct comedi_async *async;
 	struct comedi_subdevice *s;
-	int ret = 0;
+	int retval = 0;
 
 	if (copy_from_user(&bc, arg, sizeof(struct comedi_bufconfig)))
 		return -EFAULT;
@@ -303,37 +313,9 @@
 	}
 
 	if (bc.size) {
-		if (bc.size > async->max_bufsize)
-			return -EPERM;
-
-		if (s->busy) {
-			DPRINTK("subdevice is busy, cannot resize buffer\n");
-			return -EBUSY;
-		}
-		if (async->mmap_count) {
-			DPRINTK("subdevice is mmapped, cannot resize buffer\n");
-			return -EBUSY;
-		}
-
-		if (!async->prealloc_buf)
-			return -EINVAL;
-
-		/* make sure buffer is an integral number of pages
-		 * (we round up) */
-		bc.size = (bc.size + PAGE_SIZE - 1) & PAGE_MASK;
-
-		ret = comedi_buf_alloc(dev, s, bc.size);
-		if (ret < 0)
-			return ret;
-
-		if (s->buf_change) {
-			ret = s->buf_change(dev, s, bc.size);
-			if (ret < 0)
-				return ret;
-		}
-
-		DPRINTK("comedi%i subd %d buffer resized to %i bytes\n",
-			dev->minor, bc.subdevice, async->prealloc_bufsz);
+		retval = resize_async_buffer(dev, s, async, bc.size);
+		if (retval < 0)
+			return retval;
 	}
 
 	bc.size = async->prealloc_bufsz;
@@ -746,7 +728,7 @@
 	/* by default we allow the insn since we don't have checks for
 	 * all possible cases yet */
 	default:
-		rt_printk("comedi: no check for data length of config insn id "
+		printk("comedi: no check for data length of config insn id "
 			  "%i is implemented.\n"
 			  " Add a check to %s in %s.\n"
 			  " Assuming n=%i is correct.\n", data[0], __func__,
@@ -1097,13 +1079,6 @@
 
 	comedi_set_subdevice_runflags(s, ~0, SRF_USER | SRF_RUNNING);
 
-#ifdef CONFIG_COMEDI_RT
-	if (async->cmd.flags & TRIG_RT) {
-		if (comedi_switch_to_rt(dev) == 0)
-			comedi_set_subdevice_runflags(s, SRF_RT, SRF_RT);
-	}
-#endif
-
 	ret = s->do_cmd(dev, s);
 	if (ret == 0)
 		return 0;
@@ -1237,12 +1212,12 @@
 		return -EINVAL;
 	s = dev->subdevices + arg;
 
-	comedi_spin_lock_irqsave(&s->spin_lock, flags);
+	spin_lock_irqsave(&s->spin_lock, flags);
 	if (s->busy || s->lock)
 		ret = -EBUSY;
 	else
 		s->lock = file;
-	comedi_spin_unlock_irqrestore(&s->spin_lock, flags);
+	spin_unlock_irqrestore(&s->spin_lock, flags);
 
 	if (ret < 0)
 		return ret;
@@ -1738,12 +1713,6 @@
 	struct comedi_async *async = s->async;
 
 	comedi_set_subdevice_runflags(s, SRF_RUNNING, 0);
-#ifdef CONFIG_COMEDI_RT
-	if (comedi_get_subdevice_runflags(s) & SRF_RT) {
-		comedi_switch_to_non_rt(dev);
-		comedi_set_subdevice_runflags(s, SRF_RT, 0);
-	}
-#endif
 	if (async) {
 		comedi_reset_async_buf(async);
 		async->inttrig = NULL;
@@ -1970,8 +1939,6 @@
 		}
 	}
 
-	comedi_rt_init();
-
 	comedi_register_ioctl32();
 
 	return 0;
@@ -1992,8 +1959,6 @@
 
 	comedi_proc_cleanup();
 
-	comedi_rt_cleanup();
-
 	comedi_unregister_ioctl32();
 }
 
@@ -2002,8 +1967,7 @@
 
 void comedi_error(const struct comedi_device *dev, const char *s)
 {
-	rt_printk("comedi%d: %s: %s\n", dev->minor, dev->driver->driver_name,
-		  s);
+	printk("comedi%d: %s: %s\n", dev->minor, dev->driver->driver_name, s);
 }
 
 void comedi_event(struct comedi_device *dev, struct comedi_subdevice *s)
@@ -2034,34 +1998,18 @@
 
 	if (async->cb_mask & s->async->events) {
 		if (comedi_get_subdevice_runflags(s) & SRF_USER) {
-
-			if (dev->rt) {
-#ifdef CONFIG_COMEDI_RT
-				/* pend wake up */
-				comedi_rt_pend_wakeup(&async->wait_head);
-#else
-				printk
-				    ("BUG: comedi_event() code unreachable\n");
-#endif
-			} else {
-				wake_up_interruptible(&async->wait_head);
-				if (s->subdev_flags & SDF_CMD_READ) {
-					kill_fasync(&dev->async_queue, SIGIO,
-						    POLL_IN);
-				}
-				if (s->subdev_flags & SDF_CMD_WRITE) {
-					kill_fasync(&dev->async_queue, SIGIO,
-						    POLL_OUT);
-				}
+			wake_up_interruptible(&async->wait_head);
+			if (s->subdev_flags & SDF_CMD_READ) {
+				kill_fasync(&dev->async_queue, SIGIO,
+					    POLL_IN);
+			}
+			if (s->subdev_flags & SDF_CMD_WRITE) {
+				kill_fasync(&dev->async_queue, SIGIO,
+					    POLL_OUT);
 			}
 		} else {
 			if (async->cb_func)
 				async->cb_func(s->async->events, async->cb_arg);
-			/* XXX bug here.  If subdevice A is rt, and
-			 * subdevice B tries to callback to a normal
-			 * linux kernel function, it will be at the
-			 * wrong priority.  Since this isn't very
-			 * common, I'm not going to worry about it. */
 		}
 	}
 	s->async->events = 0;
@@ -2072,10 +2020,10 @@
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&s->spin_lock, flags);
+	spin_lock_irqsave(&s->spin_lock, flags);
 	s->runflags &= ~mask;
 	s->runflags |= (bits & mask);
-	comedi_spin_unlock_irqrestore(&s->spin_lock, flags);
+	spin_unlock_irqrestore(&s->spin_lock, flags);
 }
 
 unsigned comedi_get_subdevice_runflags(struct comedi_subdevice *s)
@@ -2083,9 +2031,9 @@
 	unsigned long flags;
 	unsigned runflags;
 
-	comedi_spin_lock_irqsave(&s->spin_lock, flags);
+	spin_lock_irqsave(&s->spin_lock, flags);
 	runflags = s->runflags;
-	comedi_spin_unlock_irqrestore(&s->spin_lock, flags);
+	spin_unlock_irqrestore(&s->spin_lock, flags);
 	return runflags;
 }
 
@@ -2132,6 +2080,7 @@
 	struct comedi_device_file_info *info;
 	struct device *csdev;
 	unsigned i;
+	int retval;
 
 	info = kzalloc(sizeof(struct comedi_device_file_info), GFP_KERNEL);
 	if (info == NULL)
@@ -2142,20 +2091,19 @@
 		return -ENOMEM;
 	}
 	comedi_device_init(info->device);
-	comedi_spin_lock_irqsave(&comedi_file_info_table_lock, flags);
+	spin_lock_irqsave(&comedi_file_info_table_lock, flags);
 	for (i = 0; i < COMEDI_NUM_BOARD_MINORS; ++i) {
 		if (comedi_file_info_table[i] == NULL) {
 			comedi_file_info_table[i] = info;
 			break;
 		}
 	}
-	comedi_spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
+	spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
 	if (i == COMEDI_NUM_BOARD_MINORS) {
 		comedi_device_cleanup(info->device);
 		kfree(info->device);
 		kfree(info);
-		rt_printk
-		    ("comedi: error: ran out of minor numbers for board device files.\n");
+		printk(KERN_ERR "comedi: error: ran out of minor numbers for board device files.\n");
 		return -EBUSY;
 	}
 	info->device->minor = i;
@@ -2164,7 +2112,35 @@
 				     hardware_device, "comedi%i", i);
 	if (!IS_ERR(csdev))
 		info->device->class_dev = csdev;
-
+	dev_set_drvdata(csdev, info);
+	retval = device_create_file(csdev, &dev_attr_max_read_buffer_kb);
+	if (retval) {
+		printk(KERN_ERR "comedi: failed to create sysfs attribute file \"%s\".\n",
+			dev_attr_max_read_buffer_kb.attr.name);
+		comedi_free_board_minor(i);
+		return retval;
+	}
+	retval = device_create_file(csdev, &dev_attr_read_buffer_kb);
+	if (retval) {
+		printk(KERN_ERR "comedi: failed to create sysfs attribute file \"%s\".\n",
+			dev_attr_read_buffer_kb.attr.name);
+		comedi_free_board_minor(i);
+		return retval;
+	}
+	retval = device_create_file(csdev, &dev_attr_max_write_buffer_kb);
+	if (retval) {
+		printk(KERN_ERR "comedi: failed to create sysfs attribute file \"%s\".\n",
+			dev_attr_max_write_buffer_kb.attr.name);
+		comedi_free_board_minor(i);
+		return retval;
+	}
+	retval = device_create_file(csdev, &dev_attr_write_buffer_kb);
+	if (retval) {
+		printk(KERN_ERR "comedi: failed to create sysfs attribute file \"%s\".\n",
+			dev_attr_write_buffer_kb.attr.name);
+		comedi_free_board_minor(i);
+		return retval;
+	}
 	return i;
 }
 
@@ -2174,10 +2150,10 @@
 	struct comedi_device_file_info *info;
 
 	BUG_ON(minor >= COMEDI_NUM_BOARD_MINORS);
-	comedi_spin_lock_irqsave(&comedi_file_info_table_lock, flags);
+	spin_lock_irqsave(&comedi_file_info_table_lock, flags);
 	info = comedi_file_info_table[minor];
 	comedi_file_info_table[minor] = NULL;
-	comedi_spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
+	spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
 
 	if (info) {
 		struct comedi_device *dev = info->device;
@@ -2193,12 +2169,14 @@
 	}
 }
 
-int comedi_alloc_subdevice_minor(struct comedi_device *dev, struct comedi_subdevice *s)
+int comedi_alloc_subdevice_minor(struct comedi_device *dev,
+				 struct comedi_subdevice *s)
 {
 	unsigned long flags;
 	struct comedi_device_file_info *info;
 	struct device *csdev;
 	unsigned i;
+	int retval;
 
 	info = kmalloc(sizeof(struct comedi_device_file_info), GFP_KERNEL);
 	if (info == NULL)
@@ -2206,18 +2184,17 @@
 	info->device = dev;
 	info->read_subdevice = s;
 	info->write_subdevice = s;
-	comedi_spin_lock_irqsave(&comedi_file_info_table_lock, flags);
+	spin_lock_irqsave(&comedi_file_info_table_lock, flags);
 	for (i = COMEDI_FIRST_SUBDEVICE_MINOR; i < COMEDI_NUM_MINORS; ++i) {
 		if (comedi_file_info_table[i] == NULL) {
 			comedi_file_info_table[i] = info;
 			break;
 		}
 	}
-	comedi_spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
+	spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
 	if (i == COMEDI_NUM_MINORS) {
 		kfree(info);
-		rt_printk
-		    ("comedi: error: ran out of minor numbers for board device files.\n");
+		printk(KERN_ERR "comedi: error: ran out of minor numbers for board device files.\n");
 		return -EBUSY;
 	}
 	s->minor = i;
@@ -2227,7 +2204,35 @@
 				     (int)(s - dev->subdevices));
 	if (!IS_ERR(csdev))
 		s->class_dev = csdev;
-
+	dev_set_drvdata(csdev, info);
+	retval = device_create_file(csdev, &dev_attr_max_read_buffer_kb);
+	if (retval) {
+		printk(KERN_ERR "comedi: failed to create sysfs attribute file \"%s\".\n",
+			dev_attr_max_read_buffer_kb.attr.name);
+		comedi_free_subdevice_minor(s);
+		return retval;
+	}
+	retval = device_create_file(csdev, &dev_attr_read_buffer_kb);
+	if (retval) {
+		printk(KERN_ERR "comedi: failed to create sysfs attribute file \"%s\".\n",
+			dev_attr_read_buffer_kb.attr.name);
+		comedi_free_subdevice_minor(s);
+		return retval;
+	}
+	retval = device_create_file(csdev, &dev_attr_max_write_buffer_kb);
+	if (retval) {
+		printk(KERN_ERR "comedi: failed to create sysfs attribute file \"%s\".\n",
+			dev_attr_max_write_buffer_kb.attr.name);
+		comedi_free_subdevice_minor(s);
+		return retval;
+	}
+	retval = device_create_file(csdev, &dev_attr_write_buffer_kb);
+	if (retval) {
+		printk(KERN_ERR "comedi: failed to create sysfs attribute file \"%s\".\n",
+			dev_attr_write_buffer_kb.attr.name);
+		comedi_free_subdevice_minor(s);
+		return retval;
+	}
 	return i;
 }
 
@@ -2244,10 +2249,10 @@
 	BUG_ON(s->minor >= COMEDI_NUM_MINORS);
 	BUG_ON(s->minor < COMEDI_FIRST_SUBDEVICE_MINOR);
 
-	comedi_spin_lock_irqsave(&comedi_file_info_table_lock, flags);
+	spin_lock_irqsave(&comedi_file_info_table_lock, flags);
 	info = comedi_file_info_table[s->minor];
 	comedi_file_info_table[s->minor] = NULL;
-	comedi_spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
+	spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
 
 	if (s->class_dev) {
 		device_destroy(comedi_class, MKDEV(COMEDI_MAJOR, s->minor));
@@ -2262,8 +2267,309 @@
 	struct comedi_device_file_info *info;
 
 	BUG_ON(minor >= COMEDI_NUM_MINORS);
-	comedi_spin_lock_irqsave(&comedi_file_info_table_lock, flags);
+	spin_lock_irqsave(&comedi_file_info_table_lock, flags);
 	info = comedi_file_info_table[minor];
-	comedi_spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
+	spin_unlock_irqrestore(&comedi_file_info_table_lock, flags);
 	return info;
 }
+
+static int resize_async_buffer(struct comedi_device *dev,
+			       struct comedi_subdevice *s,
+			       struct comedi_async *async, unsigned new_size)
+{
+	int retval;
+
+	if (new_size > async->max_bufsize)
+		return -EPERM;
+
+	if (s->busy) {
+		DPRINTK("subdevice is busy, cannot resize buffer\n");
+		return -EBUSY;
+	}
+	if (async->mmap_count) {
+		DPRINTK("subdevice is mmapped, cannot resize buffer\n");
+		return -EBUSY;
+	}
+
+	if (!async->prealloc_buf)
+		return -EINVAL;
+
+	/* make sure buffer is an integral number of pages
+		* (we round up) */
+	new_size = (new_size + PAGE_SIZE - 1) & PAGE_MASK;
+
+	retval = comedi_buf_alloc(dev, s, new_size);
+	if (retval < 0)
+		return retval;
+
+	if (s->buf_change) {
+		retval = s->buf_change(dev, s, new_size);
+		if (retval < 0)
+			return retval;
+	}
+
+	DPRINTK("comedi%i subd %d buffer resized to %i bytes\n",
+		dev->minor, s - dev->subdevices, async->prealloc_bufsz);
+	return 0;
+}
+
+/* sysfs attribute files */
+
+static const unsigned bytes_per_kibi = 1024;
+
+static ssize_t show_max_read_buffer_kb(struct device *dev,
+				       struct device_attribute *attr, char *buf)
+{
+	ssize_t retval;
+	struct comedi_device_file_info *info = dev_get_drvdata(dev);
+	unsigned max_buffer_size_kb = 0;
+	struct comedi_subdevice *const read_subdevice =
+					comedi_get_read_subdevice(info);
+
+	mutex_lock(&info->device->mutex);
+	if (read_subdevice &&
+	    (read_subdevice->subdev_flags & SDF_CMD_READ) &&
+	    read_subdevice->async) {
+		max_buffer_size_kb = read_subdevice->async->max_bufsize /
+					bytes_per_kibi;
+	}
+	retval =  snprintf(buf, PAGE_SIZE, "%i\n", max_buffer_size_kb);
+	mutex_unlock(&info->device->mutex);
+
+	return retval;
+}
+
+static ssize_t store_max_read_buffer_kb(struct device *dev,
+					struct device_attribute *attr,
+					const char *buf, size_t count)
+{
+	struct comedi_device_file_info *info = dev_get_drvdata(dev);
+	unsigned long new_max_size_kb;
+	uint64_t new_max_size;
+	struct comedi_subdevice *const read_subdevice =
+					comedi_get_read_subdevice(info);
+
+	if (strict_strtoul(buf, 10, &new_max_size_kb))
+		return -EINVAL;
+	if (new_max_size_kb != (uint32_t)new_max_size_kb)
+		return -EINVAL;
+	new_max_size = ((uint64_t)new_max_size_kb) * bytes_per_kibi;
+	if (new_max_size != (uint32_t)new_max_size)
+		return -EINVAL;
+
+	mutex_lock(&info->device->mutex);
+	if (read_subdevice == NULL ||
+	    (read_subdevice->subdev_flags & SDF_CMD_READ) == 0 ||
+	    read_subdevice->async == NULL) {
+		mutex_unlock(&info->device->mutex);
+		return -EINVAL;
+	}
+	read_subdevice->async->max_bufsize = new_max_size;
+	mutex_unlock(&info->device->mutex);
+
+	return count;
+}
+
+static struct device_attribute dev_attr_max_read_buffer_kb = {
+	.attr = {
+			.name = "max_read_buffer_kb",
+			.mode = S_IRUGO | S_IWUSR
+		},
+	.show = &show_max_read_buffer_kb,
+	.store = &store_max_read_buffer_kb
+};
+
+static ssize_t show_read_buffer_kb(struct device *dev,
+				   struct device_attribute *attr, char *buf)
+{
+	ssize_t retval;
+	struct comedi_device_file_info *info = dev_get_drvdata(dev);
+	unsigned buffer_size_kb = 0;
+	struct comedi_subdevice *const read_subdevice =
+					comedi_get_read_subdevice(info);
+
+	mutex_lock(&info->device->mutex);
+	if (read_subdevice &&
+		(read_subdevice->subdev_flags & SDF_CMD_READ) &&
+		read_subdevice->async) {
+		buffer_size_kb = read_subdevice->async->prealloc_bufsz /
+					bytes_per_kibi;
+	}
+	retval =  snprintf(buf, PAGE_SIZE, "%i\n", buffer_size_kb);
+	mutex_unlock(&info->device->mutex);
+
+	return retval;
+}
+
+static ssize_t store_read_buffer_kb(struct device *dev,
+				    struct device_attribute *attr,
+				    const char *buf, size_t count)
+{
+	struct comedi_device_file_info *info = dev_get_drvdata(dev);
+	unsigned long new_size_kb;
+	uint64_t new_size;
+	int retval;
+	struct comedi_subdevice *const read_subdevice =
+					comedi_get_read_subdevice(info);
+
+	if (strict_strtoul(buf, 10, &new_size_kb))
+		return -EINVAL;
+	if (new_size_kb != (uint32_t)new_size_kb)
+		return -EINVAL;
+	new_size = ((uint64_t)new_size_kb) * bytes_per_kibi;
+	if (new_size != (uint32_t)new_size)
+		return -EINVAL;
+
+	mutex_lock(&info->device->mutex);
+	if (read_subdevice == NULL ||
+	    (read_subdevice->subdev_flags & SDF_CMD_READ) == 0 ||
+	    read_subdevice->async == NULL) {
+		mutex_unlock(&info->device->mutex);
+		return -EINVAL;
+	}
+	retval = resize_async_buffer(info->device, read_subdevice,
+				     read_subdevice->async, new_size);
+	mutex_unlock(&info->device->mutex);
+
+	if (retval < 0)
+		return retval;
+	return count;
+}
+
+static struct device_attribute dev_attr_read_buffer_kb = {
+	.attr = {
+			.name = "read_buffer_kb",
+			.mode = S_IRUGO | S_IWUSR | S_IWGRP
+		},
+	.show = &show_read_buffer_kb,
+	.store = &store_read_buffer_kb
+};
+
+static ssize_t show_max_write_buffer_kb(struct device *dev,
+					struct device_attribute *attr,
+					char *buf)
+{
+	ssize_t retval;
+	struct comedi_device_file_info *info = dev_get_drvdata(dev);
+	unsigned max_buffer_size_kb = 0;
+	struct comedi_subdevice *const write_subdevice =
+					comedi_get_write_subdevice(info);
+
+	mutex_lock(&info->device->mutex);
+	if (write_subdevice &&
+	    (write_subdevice->subdev_flags & SDF_CMD_WRITE) &&
+	    write_subdevice->async) {
+		max_buffer_size_kb = write_subdevice->async->max_bufsize /
+					bytes_per_kibi;
+	}
+	retval =  snprintf(buf, PAGE_SIZE, "%i\n", max_buffer_size_kb);
+	mutex_unlock(&info->device->mutex);
+
+	return retval;
+}
+
+static ssize_t store_max_write_buffer_kb(struct device *dev,
+					 struct device_attribute *attr,
+					 const char *buf, size_t count)
+{
+	struct comedi_device_file_info *info = dev_get_drvdata(dev);
+	unsigned long new_max_size_kb;
+	uint64_t new_max_size;
+	struct comedi_subdevice *const write_subdevice =
+					comedi_get_write_subdevice(info);
+
+	if (strict_strtoul(buf, 10, &new_max_size_kb))
+		return -EINVAL;
+	if (new_max_size_kb != (uint32_t)new_max_size_kb)
+		return -EINVAL;
+	new_max_size = ((uint64_t)new_max_size_kb) * bytes_per_kibi;
+	if (new_max_size != (uint32_t)new_max_size)
+		return -EINVAL;
+
+	mutex_lock(&info->device->mutex);
+	if (write_subdevice == NULL ||
+	    (write_subdevice->subdev_flags & SDF_CMD_WRITE) == 0 ||
+	    write_subdevice->async == NULL) {
+		mutex_unlock(&info->device->mutex);
+		return -EINVAL;
+	}
+	write_subdevice->async->max_bufsize = new_max_size;
+	mutex_unlock(&info->device->mutex);
+
+	return count;
+}
+
+static struct device_attribute dev_attr_max_write_buffer_kb = {
+	.attr = {
+			.name = "max_write_buffer_kb",
+			.mode = S_IRUGO | S_IWUSR
+		},
+	.show = &show_max_write_buffer_kb,
+	.store = &store_max_write_buffer_kb
+};
+
+static ssize_t show_write_buffer_kb(struct device *dev,
+				    struct device_attribute *attr, char *buf)
+{
+	ssize_t retval;
+	struct comedi_device_file_info *info = dev_get_drvdata(dev);
+	unsigned buffer_size_kb = 0;
+	struct comedi_subdevice *const write_subdevice =
+					comedi_get_write_subdevice(info);
+
+	mutex_lock(&info->device->mutex);
+	if (write_subdevice &&
+	    (write_subdevice->subdev_flags & SDF_CMD_WRITE) &&
+	    write_subdevice->async) {
+		buffer_size_kb = write_subdevice->async->prealloc_bufsz /
+					bytes_per_kibi;
+	}
+	retval =  snprintf(buf, PAGE_SIZE, "%i\n", buffer_size_kb);
+	mutex_unlock(&info->device->mutex);
+
+	return retval;
+}
+
+static ssize_t store_write_buffer_kb(struct device *dev,
+				     struct device_attribute *attr,
+				     const char *buf, size_t count)
+{
+	struct comedi_device_file_info *info = dev_get_drvdata(dev);
+	unsigned long new_size_kb;
+	uint64_t new_size;
+	int retval;
+	struct comedi_subdevice *const write_subdevice =
+					comedi_get_write_subdevice(info);
+
+	if (strict_strtoul(buf, 10, &new_size_kb))
+		return -EINVAL;
+	if (new_size_kb != (uint32_t)new_size_kb)
+		return -EINVAL;
+	new_size = ((uint64_t)new_size_kb) * bytes_per_kibi;
+	if (new_size != (uint32_t)new_size)
+		return -EINVAL;
+
+	mutex_lock(&info->device->mutex);
+	if (write_subdevice == NULL ||
+	    (write_subdevice->subdev_flags & SDF_CMD_WRITE) == 0 ||
+	    write_subdevice->async == NULL) {
+		mutex_unlock(&info->device->mutex);
+		return -EINVAL;
+	}
+	retval = resize_async_buffer(info->device, write_subdevice,
+		write_subdevice->async, new_size);
+	mutex_unlock(&info->device->mutex);
+
+	if (retval < 0)
+		return retval;
+	return count;
+}
+
+static struct device_attribute dev_attr_write_buffer_kb = {
+	.attr = {
+			.name = "write_buffer_kb",
+			.mode = S_IRUGO | S_IWUSR | S_IWGRP
+		},
+	.show = &show_write_buffer_kb,
+	.store = &store_write_buffer_kb
+};
diff --git a/drivers/staging/comedi/comedi_ksyms.c b/drivers/staging/comedi/comedi_ksyms.c
index 6e6fb97..a732e34 100644
--- a/drivers/staging/comedi/comedi_ksyms.c
+++ b/drivers/staging/comedi/comedi_ksyms.c
@@ -46,13 +46,6 @@
 EXPORT_SYMBOL(range_unipolar10);
 EXPORT_SYMBOL(range_unipolar5);
 EXPORT_SYMBOL(range_unknown);
-#ifdef CONFIG_COMEDI_RT
-EXPORT_SYMBOL(comedi_free_irq);
-EXPORT_SYMBOL(comedi_request_irq);
-EXPORT_SYMBOL(comedi_switch_to_rt);
-EXPORT_SYMBOL(comedi_switch_to_non_rt);
-EXPORT_SYMBOL(rt_pend_call);
-#endif
 #ifdef CONFIG_COMEDI_DEBUG
 EXPORT_SYMBOL(comedi_debug);
 #endif
diff --git a/drivers/staging/comedi/comedi_rt.h b/drivers/staging/comedi/comedi_rt.h
deleted file mode 100644
index 169ca96..0000000
--- a/drivers/staging/comedi/comedi_rt.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
-    module/comedi_rt.h
-    header file for real-time structures, variables, and constants
-
-    COMEDI - Linux Control and Measurement Device Interface
-    Copyright (C) 1997-2000 David A. Schleef <ds@schleef.org>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program; if not, write to the Free Software
-    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
-*/
-
-#ifndef _COMEDI_RT_H
-#define _COMEDI_RT_H
-
-#ifndef _COMEDIDEV_H
-#error comedi_rt.h should only be included by comedidev.h
-#endif
-
-#include <linux/kdev_t.h>
-#include <linux/slab.h>
-#include <linux/errno.h>
-#include <linux/spinlock.h>
-#include <linux/delay.h>
-
-#ifdef CONFIG_COMEDI_RT
-
-#ifdef CONFIG_COMEDI_RTAI
-#include <rtai.h>
-#include <rtai_sched.h>
-#include <rtai_version.h>
-#endif
-#ifdef CONFIG_COMEDI_RTL
-#include <rtl_core.h>
-#include <rtl_time.h>
-/* #ifdef RTLINUX_VERSION_CODE */
-#include <rtl_sync.h>
-/* #endif */
-#define rt_printk rtl_printf
-#endif
-#ifdef CONFIG_COMEDI_FUSION
-#define rt_printk(format, args...) printk(format , ## args)
-#endif /* CONFIG_COMEDI_FUSION */
-#ifdef CONFIG_PRIORITY_IRQ
-#define rt_printk printk
-#endif
-
-int comedi_request_irq(unsigned int irq, irqreturn_t(*handler) (int,
-		void *PT_REGS_ARG), unsigned long flags, const char *device,
-		struct comedi_device *dev_id);
-void comedi_free_irq(unsigned int irq, struct comedi_device *dev_id);
-void comedi_rt_init(void);
-void comedi_rt_cleanup(void);
-int comedi_switch_to_rt(struct comedi_device *dev);
-void comedi_switch_to_non_rt(struct comedi_device *dev);
-void comedi_rt_pend_wakeup(wait_queue_head_t *q);
-extern int rt_pend_call(void (*func) (int arg1, void *arg2), int arg1,
-	void *arg2);
-
-#else
-
-#define comedi_request_irq(a, b, c, d, e) request_irq(a, b, c, d, e)
-#define comedi_free_irq(a, b) free_irq(a, b)
-#define comedi_rt_init() do {} while (0)
-#define comedi_rt_cleanup() do {} while (0)
-#define comedi_switch_to_rt(a) (-1)
-#define comedi_switch_to_non_rt(a) do {} while (0)
-#define comedi_rt_pend_wakeup(a) do {} while (0)
-
-#define rt_printk(format, args...)	printk(format, ##args)
-
-#endif
-
-/* Define a spin_lock_irqsave function that will work with rt or without.
- * Use inline functions instead of just macros to enforce some type checking.
- */
-#define comedi_spin_lock_irqsave(lock_ptr, flags) \
-	(flags = __comedi_spin_lock_irqsave(lock_ptr))
-
-static inline unsigned long __comedi_spin_lock_irqsave(spinlock_t *lock_ptr)
-{
-	unsigned long flags;
-
-#if defined(CONFIG_COMEDI_RTAI)
-	flags = rt_spin_lock_irqsave(lock_ptr);
-
-#elif defined(CONFIG_COMEDI_RTL)
-	rtl_spin_lock_irqsave(lock_ptr, flags);
-
-#elif defined(CONFIG_COMEDI_RTL_V1)
-	rtl_spin_lock_irqsave(lock_ptr, flags);
-
-#elif defined(CONFIG_COMEDI_FUSION)
-	rthal_spin_lock_irqsave(lock_ptr, flags);
-#else
-	spin_lock_irqsave(lock_ptr, flags);
-
-#endif
-
-	return flags;
-}
-
-static inline void comedi_spin_unlock_irqrestore(spinlock_t *lock_ptr,
-	unsigned long flags)
-{
-
-#if defined(CONFIG_COMEDI_RTAI)
-	rt_spin_unlock_irqrestore(flags, lock_ptr);
-
-#elif defined(CONFIG_COMEDI_RTL)
-	rtl_spin_unlock_irqrestore(lock_ptr, flags);
-
-#elif defined(CONFIG_COMEDI_RTL_V1)
-	rtl_spin_unlock_irqrestore(lock_ptr, flags);
-#elif defined(CONFIG_COMEDI_FUSION)
-	rthal_spin_unlock_irqrestore(lock_ptr, flags);
-#else
-	spin_unlock_irqrestore(lock_ptr, flags);
-
-#endif
-
-}
-
-/* define a RT safe udelay */
-static inline void comedi_udelay(unsigned int usec)
-{
-#if defined(CONFIG_COMEDI_RTAI)
-	static const int nanosec_per_usec = 1000;
-	rt_busy_sleep(usec * nanosec_per_usec);
-#elif defined(CONFIG_COMEDI_RTL)
-	static const int nanosec_per_usec = 1000;
-	rtl_delay(usec * nanosec_per_usec);
-#else
-	udelay(usec);
-#endif
-}
-
-#endif
diff --git a/drivers/staging/comedi/comedidev.h b/drivers/staging/comedi/comedidev.h
index ea31936..89af44a 100644
--- a/drivers/staging/comedi/comedidev.h
+++ b/drivers/staging/comedi/comedidev.h
@@ -28,6 +28,7 @@
 #include <linux/module.h>
 #include <linux/kdev_t.h>
 #include <linux/slab.h>
+#include <linux/delay.h>
 #include <linux/errno.h>
 #include <linux/spinlock.h>
 #include <linux/mutex.h>
@@ -35,10 +36,10 @@
 #include <linux/mm.h>
 #include <linux/init.h>
 #include <linux/vmalloc.h>
-#include "interrupt.h"
 #include <linux/dma-mapping.h>
 #include <linux/uaccess.h>
 #include <linux/io.h>
+#include <linux/timer.h>
 
 #include "comedi.h"
 
@@ -264,7 +265,6 @@
 	const char *board_name;
 	const void *board_ptr;
 	int attached;
-	int rt;
 	spinlock_t spinlock;
 	struct mutex mutex;
 	int in_request_module;
@@ -524,6 +524,17 @@
 int comedi_usb_auto_config(struct usb_device *usbdev, const char *board_name);
 void comedi_usb_auto_unconfig(struct usb_device *usbdev);
 
-#include "comedi_rt.h"
+#ifdef CONFIG_COMEDI_PCI_DRIVERS
+	#define CONFIG_COMEDI_PCI
+#endif
+#ifdef CONFIG_COMEDI_PCI_DRIVERS_MODULE
+	#define CONFIG_COMEDI_PCI
+#endif
+#ifdef CONFIG_COMEDI_PCMCIA_DRIVERS
+	#define CONFIG_COMEDI_PCMCIA
+#endif
+#ifdef CONFIG_COMEDI_PCMCIA_DRIVERS_MODULE
+	#define CONFIG_COMEDI_PCMCIA
+#endif
 
 #endif /* _COMEDIDEV_H */
diff --git a/drivers/staging/comedi/drivers.c b/drivers/staging/comedi/drivers.c
index 6e13e45..42a0257 100644
--- a/drivers/staging/comedi/drivers.c
+++ b/drivers/staging/comedi/drivers.c
@@ -198,7 +198,7 @@
 		struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(i);
 		struct comedi_device *dev;
 
-		if(dev_file_info == NULL) continue;
+		if (dev_file_info == NULL) continue;
 		dev = dev_file_info->device;
 
 		mutex_lock(&dev->mutex);
@@ -554,7 +554,7 @@
 
 		block_size = num_bytes - count;
 		if (block_size < 0) {
-			rt_printk("%s: %s: bug! block_size is negative\n",
+			printk("%s: %s: bug! block_size is negative\n",
 				__FILE__, __func__);
 			break;
 		}
@@ -633,8 +633,7 @@
 {
 	if ((int)(async->buf_write_count + nbytes -
 			async->buf_write_alloc_count) > 0) {
-		rt_printk
-			("comedi: attempted to write-free more bytes than have been write-allocated.\n");
+		printk("comedi: attempted to write-free more bytes than have been write-allocated.\n");
 		nbytes = async->buf_write_alloc_count - async->buf_write_count;
 	}
 	async->buf_write_count += nbytes;
@@ -667,8 +666,7 @@
 	smp_mb();
 	if ((int)(async->buf_read_count + nbytes -
 			async->buf_read_alloc_count) > 0) {
-		rt_printk
-			("comedi: attempted to read-free more bytes than have been read-allocated.\n");
+		printk("comedi: attempted to read-free more bytes than have been read-allocated.\n");
 		nbytes = async->buf_read_alloc_count - async->buf_read_count;
 	}
 	async->buf_read_count += nbytes;
@@ -801,7 +799,7 @@
 	}
 
 	minor = comedi_alloc_board_minor(hardware_device);
-	if(minor < 0) return minor;
+	if (minor < 0) return minor;
 
 	private_data = kmalloc(sizeof(unsigned), GFP_KERNEL);
 	if (private_data == NULL) {
@@ -824,7 +822,7 @@
 	mutex_unlock(&dev_file_info->device->mutex);
 
 cleanup:
-	if(retval < 0)
+	if (retval < 0)
 	{
 		kfree(private_data);
 		comedi_free_board_minor(minor);
@@ -835,7 +833,7 @@
 void comedi_auto_unconfig(struct device *hardware_device)
 {
 	unsigned *minor = (unsigned *)dev_get_drvdata(hardware_device);
-	if(minor == NULL) return;
+	if (minor == NULL) return;
 
 	BUG_ON(*minor >= COMEDI_NUM_BOARD_MINORS);
 
@@ -853,7 +851,8 @@
 	/*  pci slot */
 	options[1] = PCI_SLOT(pcidev->devfn);
 
-	return comedi_auto_config(&pcidev->dev, board_name, options, sizeof(options) / sizeof(options[0]));
+	return comedi_auto_config(&pcidev->dev, board_name,
+				  options, ARRAY_SIZE(options));
 }
 
 void comedi_pci_auto_unconfig(struct pci_dev *pcidev)
diff --git a/drivers/staging/comedi/drivers/8253.h b/drivers/staging/comedi/drivers/8253.h
index 08a11a5..ad467ac 100644
--- a/drivers/staging/comedi/drivers/8253.h
+++ b/drivers/staging/comedi/drivers/8253.h
@@ -24,11 +24,7 @@
 #ifndef _8253_H
 #define _8253_H
 
-#ifndef CMDTEST
 #include "../comedi.h"
-#else
-#include "../comedi.h"
-#endif
 
 #define i8253_cascade_ns_to_timer i8253_cascade_ns_to_timer_2div
 
@@ -205,7 +201,7 @@
 	}
 
 	*nanosec = div1 * div2 * i8253_osc_base;
-	*d1 = div1 & 0xffff;	// masking is done since counter maps zero to 0x10000
+	*d1 = div1 & 0xffff;	/*  masking is done since counter maps zero to 0x10000 */
 	*d2 = div2 & 0xffff;
 	return;
 }
@@ -247,12 +243,12 @@
 		return -1;
 
 	byte = counter_number << 6;
-	byte |= 0x30;		// load low then high byte
-	byte |= (mode << 1);	// set counter mode
+	byte |= 0x30;		/*  load low then high byte */
+	byte |= (mode << 1);	/*  set counter mode */
 	outb(byte, base_address + (i8254_control_reg << regshift));
-	byte = count & 0xff;	// lsb of counter value
+	byte = count & 0xff;	/*  lsb of counter value */
 	outb(byte, base_address + (counter_number << regshift));
-	byte = (count >> 8) & 0xff;	// msb of counter value
+	byte = (count >> 8) & 0xff;	/*  msb of counter value */
 	outb(byte, base_address + (counter_number << regshift));
 
 	return 0;
@@ -273,12 +269,12 @@
 		return -1;
 
 	byte = counter_number << 6;
-	byte |= 0x30;		// load low then high byte
-	byte |= (mode << 1);	// set counter mode
+	byte |= 0x30;		/*  load low then high byte */
+	byte |= (mode << 1);	/*  set counter mode */
 	writeb(byte, base_address + (i8254_control_reg << regshift));
-	byte = count & 0xff;	// lsb of counter value
+	byte = count & 0xff;	/*  lsb of counter value */
 	writeb(byte, base_address + (counter_number << regshift));
-	byte = (count >> 8) & 0xff;	// msb of counter value
+	byte = (count >> 8) & 0xff;	/*  msb of counter value */
 	writeb(byte, base_address + (counter_number << regshift));
 
 	return 0;
@@ -294,13 +290,13 @@
 	if (counter_number > 2)
 		return -1;
 
-	// latch counter
+	/*  latch counter */
 	byte = counter_number << 6;
 	outb(byte, base_address + (i8254_control_reg << regshift));
 
-	// read lsb
+	/*  read lsb */
 	ret = inb(base_address + (counter_number << regshift));
-	// read msb
+	/*  read msb */
 	ret += inb(base_address + (counter_number << regshift)) << 8;
 
 	return ret;
@@ -315,13 +311,13 @@
 	if (counter_number > 2)
 		return -1;
 
-	// latch counter
+	/*  latch counter */
 	byte = counter_number << 6;
 	writeb(byte, base_address + (i8254_control_reg << regshift));
 
-	// read lsb
+	/*  read lsb */
 	ret = readb(base_address + (counter_number << regshift));
-	// read msb
+	/*  read msb */
 	ret += readb(base_address + (counter_number << regshift)) << 8;
 
 	return ret;
@@ -336,9 +332,9 @@
 	if (counter_number > 2)
 		return;
 
-	byte = count & 0xff;	// lsb of counter value
+	byte = count & 0xff;	/*  lsb of counter value */
 	outb(byte, base_address + (counter_number << regshift));
-	byte = (count >> 8) & 0xff;	// msb of counter value
+	byte = (count >> 8) & 0xff;	/*  msb of counter value */
 	outb(byte, base_address + (counter_number << regshift));
 }
 
@@ -350,9 +346,9 @@
 	if (counter_number > 2)
 		return;
 
-	byte = count & 0xff;	// lsb of counter value
+	byte = count & 0xff;	/*  lsb of counter value */
 	writeb(byte, base_address + (counter_number << regshift));
-	byte = (count >> 8) & 0xff;	// msb of counter value
+	byte = (count >> 8) & 0xff;	/*  msb of counter value */
 	writeb(byte, base_address + (counter_number << regshift));
 }
 
@@ -374,8 +370,8 @@
 		return -1;
 
 	byte = counter_number << 6;
-	byte |= 0x30;		// load low then high byte
-	byte |= mode;		// set counter mode and BCD|binary
+	byte |= 0x30;		/*  load low then high byte */
+	byte |= mode;		/*  set counter mode and BCD|binary */
 	outb(byte, base_address + (i8254_control_reg << regshift));
 
 	return 0;
@@ -392,8 +388,8 @@
 		return -1;
 
 	byte = counter_number << 6;
-	byte |= 0x30;		// load low then high byte
-	byte |= mode;		// set counter mode and BCD|binary
+	byte |= 0x30;		/*  load low then high byte */
+	byte |= mode;		/*  set counter mode and BCD|binary */
 	writeb(byte, base_address + (i8254_control_reg << regshift));
 
 	return 0;
diff --git a/drivers/staging/comedi/drivers/8255.c b/drivers/staging/comedi/drivers/8255.c
index 0369c7c..bdc3957 100644
--- a/drivers/staging/comedi/drivers/8255.c
+++ b/drivers/staging/comedi/drivers/8255.c
@@ -108,10 +108,10 @@
 static int dev_8255_attach(struct comedi_device *dev, struct comedi_devconfig * it);
 static int dev_8255_detach(struct comedi_device *dev);
 static struct comedi_driver driver_8255 = {
-      driver_name:"8255",
-      module:THIS_MODULE,
-      attach:dev_8255_attach,
-      detach:dev_8255_detach,
+	.driver_name = "8255",
+	.module = THIS_MODULE,
+	.attach = dev_8255_attach,
+	.detach = dev_8255_detach,
 };
 
 COMEDI_INITCLEANUP(driver_8255);
@@ -144,7 +144,7 @@
 }
 
 static int subdev_8255_insn(struct comedi_device *dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (data[0]) {
 		s->state &= ~data[0];
@@ -169,7 +169,7 @@
 }
 
 static int subdev_8255_insn_config(struct comedi_device *dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int mask;
 	unsigned int bits;
@@ -223,7 +223,7 @@
 }
 
 static int subdev_8255_cmdtest(struct comedi_device *dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	unsigned int tmp;
@@ -361,8 +361,10 @@
 void subdev_8255_cleanup(struct comedi_device *dev, struct comedi_subdevice * s)
 {
 	if (s->private) {
-		if (subdevpriv->have_irq) {
-		}
+		/* this test does nothing, so comment it out
+		 * if (subdevpriv->have_irq) {
+		 * }
+		 */
 
 		kfree(s->private);
 	}
@@ -394,7 +396,8 @@
 		return -EINVAL;
 	}
 
-	if ((ret = alloc_subdevices(dev, i)) < 0)
+	ret = alloc_subdevices(dev, i);
+	if (ret < 0)
 		return ret;
 
 	for (i = 0; i < dev->n_subdevices; i++) {
diff --git a/drivers/staging/comedi/drivers/8255.h b/drivers/staging/comedi/drivers/8255.h
index 979311b..5457c6b 100644
--- a/drivers/staging/comedi/drivers/8255.h
+++ b/drivers/staging/comedi/drivers/8255.h
@@ -28,16 +28,16 @@
 
 #if defined(CONFIG_COMEDI_8255) || defined(CONFIG_COMEDI_8255_MODULE)
 
-int subdev_8255_init(struct comedi_device * dev, struct comedi_subdevice * s,
+int subdev_8255_init(struct comedi_device *dev, struct comedi_subdevice *s,
 	int (*cb) (int, int, int, unsigned long), unsigned long arg);
-int subdev_8255_init_irq(struct comedi_device * dev, struct comedi_subdevice * s,
+int subdev_8255_init_irq(struct comedi_device *dev, struct comedi_subdevice *s,
 	int (*cb) (int, int, int, unsigned long), unsigned long arg);
-void subdev_8255_cleanup(struct comedi_device * dev, struct comedi_subdevice * s);
-void subdev_8255_interrupt(struct comedi_device * dev, struct comedi_subdevice * s);
+void subdev_8255_cleanup(struct comedi_device *dev, struct comedi_subdevice *s);
+void subdev_8255_interrupt(struct comedi_device *dev, struct comedi_subdevice *s);
 
 #else
 
-static inline int subdev_8255_init(struct comedi_device * dev, struct comedi_subdevice * s,
+static inline int subdev_8255_init(struct comedi_device *dev, struct comedi_subdevice *s,
 	void *x, unsigned long y)
 {
 	printk("8255 support not configured -- disabling subdevice\n");
@@ -47,8 +47,8 @@
 	return 0;
 }
 
-static inline void subdev_8255_cleanup(struct comedi_device * dev,
-	struct comedi_subdevice * s)
+static inline void subdev_8255_cleanup(struct comedi_device *dev,
+	struct comedi_subdevice *s)
 {
 }
 
diff --git a/drivers/staging/comedi/drivers/Makefile b/drivers/staging/comedi/drivers/Makefile
index 12d6e43..df2854d 100644
--- a/drivers/staging/comedi/drivers/Makefile
+++ b/drivers/staging/comedi/drivers/Makefile
@@ -6,6 +6,7 @@
 obj-$(CONFIG_COMEDI)			+= comedi_bond.o
 obj-$(CONFIG_COMEDI)			+= comedi_test.o
 obj-$(CONFIG_COMEDI)			+= comedi_parport.o
+obj-$(CONFIG_COMEDI)			+= pcm_common.o
 
 # Comedi PCI drivers
 obj-$(CONFIG_COMEDI_PCI_DRIVERS)	+= 8255.o
@@ -125,6 +126,8 @@
 obj-$(CONFIG_COMEDI_PCMCIA_DRIVERS)	+= quatech_daqp_cs.o
 
 # Comedi USB drivers
+obj-$(CONFIG_COMEDI_USB_DRIVERS)	+= dt9812.o
 obj-$(CONFIG_COMEDI_USB_DRIVERS)	+= usbdux.o
 obj-$(CONFIG_COMEDI_USB_DRIVERS)	+= usbduxfast.o
-obj-$(CONFIG_COMEDI_USB_DRIVERS)	+= dt9812.o
+obj-$(CONFIG_COMEDI_USB_DRIVERS)	+= vmk80xx.o
+
diff --git a/drivers/staging/comedi/drivers/acl7225b.c b/drivers/staging/comedi/drivers/acl7225b.c
index b21320f..5b986aa 100644
--- a/drivers/staging/comedi/drivers/acl7225b.c
+++ b/drivers/staging/comedi/drivers/acl7225b.c
@@ -26,8 +26,8 @@
 static int acl7225b_detach(struct comedi_device *dev);
 
 struct boardtype {
-	const char *name;	// driver name
-	int io_range;		// len of I/O space
+	const char *name;	/*  driver name */
+	int io_range;		/*  len of I/O space */
 };
 
 static const struct boardtype boardtypes[] = {
@@ -39,19 +39,19 @@
 #define this_board ((const struct boardtype *)dev->board_ptr)
 
 static struct comedi_driver driver_acl7225b = {
-      driver_name:"acl7225b",
-      module:THIS_MODULE,
-      attach:acl7225b_attach,
-      detach:acl7225b_detach,
-      board_name:&boardtypes[0].name,
-      num_names:n_boardtypes,
-      offset:sizeof(struct boardtype),
+	.driver_name = "acl7225b",
+	.module = THIS_MODULE,
+	.attach = acl7225b_attach,
+	.detach = acl7225b_detach,
+	.board_name = &boardtypes[0].name,
+	.num_names = n_boardtypes,
+	.offset = sizeof(struct boardtype),
 };
 
 COMEDI_INITCLEANUP(driver_acl7225b);
 
 static int acl7225b_do_insn(struct comedi_device *dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -72,7 +72,7 @@
 }
 
 static int acl7225b_di_insn(struct comedi_device *dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_82x54.c b/drivers/staging/comedi/drivers/addi-data/APCI1710_82x54.c
index c96aee0..60213d2 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_82x54.c
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_82x54.c
@@ -23,16 +23,16 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_     i_APCI1710_InitTimer                         |
-|                               (BYTE_   b_BoardHandle,                      |
-|                                BYTE_   b_ModulNbr,                         |
-|                                BYTE_   b_TimerNbr,                         |
-|                                BYTE_   b_TimerMode,                        |
+|                               (unsigned char_   b_BoardHandle,                      |
+|                                unsigned char_   b_ModulNbr,                         |
+|                                unsigned char_   b_TimerNbr,                         |
+|                                unsigned char_   b_TimerMode,                        |
 |                                ULONG_ ul_ReloadValue,                      |
-|                                BYTE_   b_InputClockSelection,              |
-|                                BYTE_   b_InputClockLevel,                  |
-|                                BYTE_   b_OutputLevel,                      |
-|                                BYTE_   b_HardwareGateLevel)
-INT i_InsnConfig_InitTimer(struct comedi_device *dev,struct comedi_subdevice *s,
+|                                unsigned char_   b_InputClockSelection,              |
+|                                unsigned char_   b_InputClockLevel,                  |
+|                                unsigned char_   b_OutputLevel,                      |
+|                                unsigned char_   b_HardwareGateLevel)
+int i_InsnConfig_InitTimer(struct comedi_device *dev,struct comedi_subdevice *s,
 	struct comedi_insn *insn,unsigned int *data)
 |
 +----------------------------------------------------------------------------+
@@ -148,13 +148,13 @@
 |  +--------------------------------+------------------------------------+   |
 |                                                                            |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_   b_BoardHandle        : Handle of board         |
+| Input Parameters  : unsigned char_   b_BoardHandle        : Handle of board         |
 |                                                    APCI-1710               |
-|                     BYTE_   b_ModulNbr           : Module number to        |
+|                     unsigned char_   b_ModulNbr           : Module number to        |
 |                                                    configure (0 to 3)      |
-|                     BYTE_   b_TimerNbr           : Timer number to         |
+|                     unsigned char_   b_TimerNbr           : Timer number to         |
 |                                                    configure (0 to 2)      |
-|                     BYTE_   b_TimerMode          : Timer mode selection    |
+|                     unsigned char_   b_TimerMode          : Timer mode selection    |
 |                                                    (0 to 5)                |
 |                                                    0: Interrupt on terminal|
 |                                                       count                |
@@ -173,21 +173,21 @@
 |                                                     or division factor     |
 |                                                     See timer mode         |
 |                                                     description table.     |
-|                     BYTE_   b_InputClockSelection : Selection from input   |
+|                     unsigned char_   b_InputClockSelection : Selection from input   |
 |                                                     timer clock.           |
 |                                                     See input clock        |
 |                                                     selection table.       |
-|                     BYTE_   b_InputClockLevel     : Selection from input   |
+|                     unsigned char_   b_InputClockLevel     : Selection from input   |
 |                                                     clock level.           |
 |                                                     0 : Low active         |
 |                                                         (Input inverted)   |
 |                                                     1 : High active        |
-|                     BYTE_   b_OutputLevel,        : Selection from output  |
+|                     unsigned char_   b_OutputLevel,        : Selection from output  |
 |                                                     clock level.           |
 |                                                     0 : Low active         |
 |                                                     1 : High active        |
 |                                                         (Output inverted)  |
-|                     BYTE_   b_HardwareGateLevel   : Selection from         |
+|                     unsigned char_   b_HardwareGateLevel   : Selection from         |
 |                                                     hardware gate level.   |
 |                                                     0 : Low active         |
 |                                                         (Input inverted)   |
@@ -195,14 +195,14 @@
 |                                                     If you will not used   |
 |                                                     the hardware gate set  |
 |                                                     this value to 0.
-|b_ModulNbr        = (BYTE) CR_AREF(insn->chanspec);
-	b_TimerNbr		  = (BYTE) CR_CHAN(insn->chanspec);
-	b_TimerMode		  = (BYTE) data[0];
-	ul_ReloadValue	  = (ULONG) data[1];
-	b_InputClockSelection	=(BYTE) data[2];
-	b_InputClockLevel		=(BYTE) data[3];
-	b_OutputLevel			=(BYTE) data[4];
-	b_HardwareGateLevel		=(BYTE) data[5];
+|b_ModulNbr        = (unsigned char) CR_AREF(insn->chanspec);
+	b_TimerNbr		  = (unsigned char) CR_CHAN(insn->chanspec);
+	b_TimerMode		  = (unsigned char) data[0];
+	ul_ReloadValue	  = (unsigned int) data[1];
+	b_InputClockSelection	=(unsigned char) data[2];
+	b_InputClockLevel		=(unsigned char) data[3];
+	b_OutputLevel			=(unsigned char) data[4];
+	b_HardwareGateLevel		=(unsigned char) data[5];
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -219,33 +219,33 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnConfigInitTimer(struct comedi_device * dev, struct comedi_subdevice * s,
-				   struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnConfigInitTimer(struct comedi_device *dev, struct comedi_subdevice *s,
+				   struct comedi_insn *insn, unsigned int *data)
 {
 
-	INT i_ReturnValue = 0;
-	BYTE b_ModulNbr;
-	BYTE b_TimerNbr;
-	BYTE b_TimerMode;
-	ULONG ul_ReloadValue;
-	BYTE b_InputClockSelection;
-	BYTE b_InputClockLevel;
-	BYTE b_OutputLevel;
-	BYTE b_HardwareGateLevel;
+	int i_ReturnValue = 0;
+	unsigned char b_ModulNbr;
+	unsigned char b_TimerNbr;
+	unsigned char b_TimerMode;
+	unsigned int ul_ReloadValue;
+	unsigned char b_InputClockSelection;
+	unsigned char b_InputClockLevel;
+	unsigned char b_OutputLevel;
+	unsigned char b_HardwareGateLevel;
 
-	//BEGIN JK 27.10.2003 : Add the possibility to use a 40 Mhz quartz
-	DWORD dw_Test = 0;
-	//END JK 27.10.2003 : Add the possibility to use a 40 Mhz quartz
+	/* BEGIN JK 27.10.2003 : Add the possibility to use a 40 Mhz quartz */
+	unsigned int dw_Test = 0;
+	/* END JK 27.10.2003 : Add the possibility to use a 40 Mhz quartz */
 
 	i_ReturnValue = insn->n;
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_TimerNbr = (BYTE) CR_CHAN(insn->chanspec);
-	b_TimerMode = (BYTE) data[0];
-	ul_ReloadValue = (ULONG) data[1];
-	b_InputClockSelection = (BYTE) data[2];
-	b_InputClockLevel = (BYTE) data[3];
-	b_OutputLevel = (BYTE) data[4];
-	b_HardwareGateLevel = (BYTE) data[5];
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_TimerNbr = (unsigned char) CR_CHAN(insn->chanspec);
+	b_TimerMode = (unsigned char) data[0];
+	ul_ReloadValue = (unsigned int) data[1];
+	b_InputClockSelection = (unsigned char) data[2];
+	b_InputClockLevel = (unsigned char) data[3];
+	b_OutputLevel = (unsigned char) data[4];
+	b_HardwareGateLevel = (unsigned char) data[5];
 
 	/* Test the module number */
 	if (b_ModulNbr < 4) {
@@ -256,7 +256,7 @@
 			if (b_TimerNbr <= 2) {
 				/* Test the timer mode */
 				if (b_TimerMode <= 5) {
-					//BEGIN JK 27.10.2003 : Add the possibility to use a 40 Mhz quartz
+					/* BEGIN JK 27.10.2003 : Add the possibility to use a 40 Mhz quartz */
 					/* Test te imput clock selection */
 					/*
 					   if (((b_TimerNbr == 0) && (b_InputClockSelection == 0)) ||
@@ -271,11 +271,11 @@
 					     ((b_InputClockSelection == APCI1710_PCI_BUS_CLOCK) ||
 					      (b_InputClockSelection == APCI1710_FRONT_CONNECTOR_INPUT) ||
 					      (b_InputClockSelection == APCI1710_10MHZ)))) {
-						//BEGIN JK 27.10.2003 : Add the possibility to use a 40 Mhz quartz
+						/* BEGIN JK 27.10.2003 : Add the possibility to use a 40 Mhz quartz */
 						if (((b_InputClockSelection == APCI1710_10MHZ) &&
 						     ((devpriv->s_BoardInfos.dw_MolduleConfiguration[b_ModulNbr] & 0x0000FFFFUL) >= 0x3131)) ||
 						     (b_InputClockSelection != APCI1710_10MHZ)) {
-							//END JK 27.10.2003 : Add the possibility to use a 40 Mhz quartz
+							/* END JK 27.10.2003 : Add the possibility to use a 40 Mhz quartz */
 							/* Test the input clock level selection */
 
 							if ((b_InputClockLevel == 0) ||
@@ -284,7 +284,7 @@
 								if ((b_OutputLevel == 0) || (b_OutputLevel == 1)) {
 									/* Test the hardware gate level selection */
 									if ((b_HardwareGateLevel == 0) || (b_HardwareGateLevel == 1)) {
-										//BEGIN JK 27.10.03 : Add the possibility to use a 40 Mhz quartz
+										/* BEGIN JK 27.10.03 : Add the possibility to use a 40 Mhz quartz */
 										/* Test if version > 1.1 and clock selection = 10MHz */
 										if ((b_InputClockSelection == APCI1710_10MHZ) && ((devpriv->s_BoardInfos.dw_MolduleConfiguration[b_ModulNbr] & 0x0000FFFFUL) > 0x3131)) {
 											/* Test if 40MHz quartz on board */
@@ -297,7 +297,7 @@
 
 										/* Test if detection OK */
 										if (dw_Test == 1) {
-											//END JK 27.10.03 : Add the possibility to use a 40 Mhz quartz
+											/* END JK 27.10.03 : Add the possibility to use a 40 Mhz quartz */
 											/* Initialisation OK */
 											devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].b_82X54Init = 1;
 
@@ -314,12 +314,12 @@
 											devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].b_HardwareGateLevel = b_HardwareGateLevel;
 
 											/* Set the configuration word and disable the timer */
-											//BEGIN JK 27.10.03 : Add the possibility to use a 40 Mhz quartz
+											/* BEGIN JK 27.10.03 : Add the possibility to use a 40 Mhz quartz */
 											/*
 											   devpriv->s_ModuleInfo [b_ModulNbr].
 											   s_82X54ModuleInfo.
 											   s_82X54TimerInfo  [b_TimerNbr].
-											   dw_ConfigurationWord = (DWORD) (((b_HardwareGateLevel         << 0) & 0x1) |
+											   dw_ConfigurationWord = (unsigned int) (((b_HardwareGateLevel         << 0) & 0x1) |
 											   ((b_InputClockLevel           << 1) & 0x2) |
 											   (((~b_OutputLevel       & 1)  << 2) & 0x4) |
 											   ((b_InputClockSelection       << 4) & 0x10));
@@ -329,40 +329,40 @@
 												b_InputClockSelection = 2;
 											}
 
-											devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].dw_ConfigurationWord = (DWORD)(((b_HardwareGateLevel << 0) & 0x1) | ((b_InputClockLevel << 1) & 0x2) | (((~b_OutputLevel & 1) << 2) & 0x4) | ((b_InputClockSelection << 4) & 0x30));
-											//END JK 27.10.03 : Add the possibility to use a 40 Mhz quartz
+											devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].dw_ConfigurationWord = (unsigned int)(((b_HardwareGateLevel << 0) & 0x1) | ((b_InputClockLevel << 1) & 0x2) | (((~b_OutputLevel & 1) << 2) & 0x4) | ((b_InputClockSelection << 4) & 0x30));
+											/* END JK 27.10.03 : Add the possibility to use a 40 Mhz quartz */
 											outl(devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].dw_ConfigurationWord, devpriv->s_BoardInfos.ui_Address + 32 + (b_TimerNbr * 4) + (64 * b_ModulNbr));
 
 											/* Initialise the 82X54 Timer */
-											outl((DWORD) b_TimerMode, devpriv->s_BoardInfos.ui_Address + 16 + (b_TimerNbr * 4) + (64 * b_ModulNbr));
+											outl((unsigned int) b_TimerMode, devpriv->s_BoardInfos.ui_Address + 16 + (b_TimerNbr * 4) + (64 * b_ModulNbr));
 
 											/* Write the reload value */
 											outl(ul_ReloadValue, devpriv->s_BoardInfos.ui_Address + 0 + (b_TimerNbr * 4) + (64 * b_ModulNbr));
-											//BEGIN JK 27.10.03 : Add the possibility to use a 40 Mhz quartz
-										}	// if (dw_Test == 1)
+											/* BEGIN JK 27.10.03 : Add the possibility to use a 40 Mhz quartz */
+										}	/*  if (dw_Test == 1) */
 										else {
 											/* Input timer clock selection is wrong */
 											i_ReturnValue = -6;
-										}	// if (dw_Test == 1)
-										//END JK 27.10.03 : Add the possibility to use a 40 Mhz quartz
-									}	// if ((b_HardwareGateLevel == 0) || (b_HardwareGateLevel == 1))
+										}	/*  if (dw_Test == 1) */
+										/* END JK 27.10.03 : Add the possibility to use a 40 Mhz quartz */
+									}	/*  if ((b_HardwareGateLevel == 0) || (b_HardwareGateLevel == 1)) */
 									else {
 										/* Selection from hardware gate level is wrong */
 										DPRINTK("Selection from hardware gate level is wrong\n");
 										i_ReturnValue = -9;
-									}	// if ((b_HardwareGateLevel == 0) || (b_HardwareGateLevel == 1))
-								}	// if ((b_OutputLevel == 0) || (b_OutputLevel == 1))
+									}	/*  if ((b_HardwareGateLevel == 0) || (b_HardwareGateLevel == 1)) */
+								}	/*  if ((b_OutputLevel == 0) || (b_OutputLevel == 1)) */
 								else {
 									/* Selection from output clock level is wrong */
 									DPRINTK("Selection from output clock level is wrong\n");
 									i_ReturnValue = -8;
-								}	// if ((b_OutputLevel == 0) || (b_OutputLevel == 1))
-							}	// if ((b_InputClockLevel == 0) || (b_InputClockLevel == 1))
+								}	/*  if ((b_OutputLevel == 0) || (b_OutputLevel == 1)) */
+							}	/*  if ((b_InputClockLevel == 0) || (b_InputClockLevel == 1)) */
 							else {
 								/* Selection from input clock level is wrong */
 								DPRINTK("Selection from input clock level is wrong\n");
 								i_ReturnValue = -7;
-							}	// if ((b_InputClockLevel == 0) || (b_InputClockLevel == 1))
+							}	/*  if ((b_InputClockLevel == 0) || (b_InputClockLevel == 1)) */
 						} else {
 							/* Input timer clock selection is wrong */
 							DPRINTK("Input timer clock selection is wrong\n");
@@ -373,18 +373,18 @@
 						DPRINTK("Input timer clock selection is wrong\n");
 						i_ReturnValue = -6;
 					}
-				}	// if ((b_TimerMode >= 0) && (b_TimerMode <= 5))
+				}	/*  if ((b_TimerMode >= 0) && (b_TimerMode <= 5)) */
 				else {
 					/* Timer mode selection is wrong */
 					DPRINTK("Timer mode selection is wrong\n");
 					i_ReturnValue = -5;
-				}	// if ((b_TimerMode >= 0) && (b_TimerMode <= 5))
-			}	// if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2))
+				}	/*  if ((b_TimerMode >= 0) && (b_TimerMode <= 5)) */
+			}	/*  if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2)) */
 			else {
 				/* Timer selection wrong */
 				DPRINTK("Timer selection wrong\n");
 				i_ReturnValue = -3;
-			}	// if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2))
+			}	/*  if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2)) */
 		} else {
 			/* The module is not a TIMER module */
 			DPRINTK("The module is not a TIMER module\n");
@@ -396,17 +396,17 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_     i_APCI1710_EnableTimer                       |
-|                               (BYTE_ b_BoardHandle,                        |
-|                                BYTE_ b_ModulNbr,                           |
-|                                BYTE_ b_TimerNbr,                           |
-|                                BYTE_ b_InterruptEnable)
-INT i_APCI1710_InsnWriteEnableDisableTimer(struct comedi_device *dev,struct comedi_subdevice *s,
+|                               (unsigned char_ b_BoardHandle,                        |
+|                                unsigned char_ b_ModulNbr,                           |
+|                                unsigned char_ b_TimerNbr,                           |
+|                                unsigned char_ b_InterruptEnable)
+int i_APCI1710_InsnWriteEnableDisableTimer(struct comedi_device *dev,struct comedi_subdevice *s,
 	struct comedi_insn *insn,unsigned int *data)                |
 +----------------------------------------------------------------------------+
 | Task              : Enable OR Disable the Timer (b_TimerNbr) from selected module     |
@@ -416,22 +416,22 @@
 |                     generate a interrupt after the timer value reach       |
 |                     the zero. See function "i_APCI1710_SetBoardIntRoutineX"|
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_   b_BoardHandle     : Handle of board            |
+| Input Parameters  : unsigned char_   b_BoardHandle     : Handle of board            |
 |                                                 APCI-1710                  |
-|                     BYTE_   b_ModulNbr        : Selected module number     |
+|                     unsigned char_   b_ModulNbr        : Selected module number     |
 |                                                 (0 to 3)                   |
-|                     BYTE_   b_TimerNbr        : Timer number to enable     |
+|                     unsigned char_   b_TimerNbr        : Timer number to enable     |
 |                                                 (0 to 2)                   |
-|                     BYTE_   b_InterruptEnable : Enable or disable the      |
+|                     unsigned char_   b_InterruptEnable : Enable or disable the      |
 |                                                 timer interrupt.           |
 |                                                 APCI1710_ENABLE :          |
 |                                                 Enable the timer interrupt |
 |                                                 APCI1710_DISABLE :         |
 |                                                 Disable the timer interrupt|
 i_ReturnValue=insn->n;
-	b_ModulNbr        = (BYTE) CR_AREF(insn->chanspec);
-	b_TimerNbr		  = (BYTE) CR_CHAN(insn->chanspec);
-	b_ActionType      = (BYTE) data[0]; // enable disable
+	b_ModulNbr        = (unsigned char) CR_AREF(insn->chanspec);
+	b_TimerNbr		  = (unsigned char) CR_CHAN(insn->chanspec);
+	b_ActionType      = (unsigned char) data[0]; /*  enable disable */
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -448,21 +448,21 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnWriteEnableDisableTimer(struct comedi_device * dev,
-					   struct comedi_subdevice * s,
-					   struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnWriteEnableDisableTimer(struct comedi_device *dev,
+					   struct comedi_subdevice *s,
+					   struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_DummyRead;
-	BYTE b_ModulNbr;
-	BYTE b_TimerNbr;
-	BYTE b_ActionType;
-	BYTE b_InterruptEnable;
+	int i_ReturnValue = 0;
+	unsigned int dw_DummyRead;
+	unsigned char b_ModulNbr;
+	unsigned char b_TimerNbr;
+	unsigned char b_ActionType;
+	unsigned char b_InterruptEnable;
 
 	i_ReturnValue = insn->n;
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_TimerNbr = (BYTE) CR_CHAN(insn->chanspec);
-	b_ActionType = (BYTE) data[0];	// enable disable
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_TimerNbr = (unsigned char) CR_CHAN(insn->chanspec);
+	b_ActionType = (unsigned char) data[0];	/*  enable disable */
 
 	/* Test the module number */
 	if (b_ModulNbr < 4) {
@@ -475,7 +475,7 @@
 
 					switch (b_ActionType) {
 					case APCI1710_ENABLE:
-						b_InterruptEnable = (BYTE) data[1];
+						b_InterruptEnable = (unsigned char) data[1];
 						/* Test the interrupt selection */
 						if ((b_InterruptEnable == APCI1710_ENABLE) ||
 						    (b_InterruptEnable == APCI1710_DISABLE)) {
@@ -487,9 +487,9 @@
 								devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].dw_ConfigurationWord = devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].dw_ConfigurationWord | 0x8;
 
 								outl(devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].dw_ConfigurationWord, devpriv->s_BoardInfos.ui_Address + 32 + (b_TimerNbr * 4) + (64 * b_ModulNbr));
-								devpriv->tsk_Current = current;	// Save the current process task structure
+								devpriv->tsk_Current = current;	/*  Save the current process task structure */
 
-							}	// if (b_InterruptEnable == APCI1710_ENABLE)
+							}	/*  if (b_InterruptEnable == APCI1710_ENABLE) */
 							else {
 								/* Disable the interrupt */
 								devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].dw_ConfigurationWord = devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].dw_ConfigurationWord & 0xF7;
@@ -498,7 +498,7 @@
 
 								/* Save the interrupt flag */
 								devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.b_InterruptMask = devpriv->s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.b_InterruptMask & (0xFF - (1 << b_TimerNbr));
-							}	// if (b_InterruptEnable == APCI1710_ENABLE)
+							}	/*  if (b_InterruptEnable == APCI1710_ENABLE) */
 
 							/* Test if error occur */
 							if (i_ReturnValue >= 0) {
@@ -530,7 +530,7 @@
 						/* Disable the timer */
 						outl(0, devpriv->s_BoardInfos.ui_Address + 44 + (b_TimerNbr * 4) + (64 * b_ModulNbr));
 						break;
-					}	// Switch end
+					}	/*  Switch end */
 				} else {
 					/* Timer not initialised see function */
 					DPRINTK ("Timer not initialised see function\n");
@@ -540,7 +540,7 @@
 				/* Timer selection wrong */
 				DPRINTK("Timer selection wrong\n");
 				i_ReturnValue = -3;
-			}	// if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2))
+			}	/*  if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2)) */
 		} else {
 			/* The module is not a TIMER module */
 			DPRINTK("The module is not a TIMER module\n");
@@ -552,24 +552,24 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_     i_APCI1710_ReadAllTimerValue                 |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
 |                                        PULONG_ pul_TimerValueArray)
-INT i_APCI1710_InsnReadAllTimerValue(struct comedi_device *dev,struct comedi_subdevice *s,
+int i_APCI1710_InsnReadAllTimerValue(struct comedi_device *dev,struct comedi_subdevice *s,
 	struct comedi_insn *insn,unsigned int *data)        |
 +----------------------------------------------------------------------------+
 | Task              : Return the all timer values from selected timer        |
 |                     module (b_ModulNbr).                                   |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_   b_BoardHandle     : Handle of board            |
+| Input Parameters  : unsigned char_   b_BoardHandle     : Handle of board            |
 |                                                 APCI-1710                  |
-|                     BYTE_   b_ModulNbr        : Selected module number     |
+|                     unsigned char_   b_ModulNbr        : Selected module number     |
 |                                                 (0 to 3)                   |
 +----------------------------------------------------------------------------+
 | Output Parameters : PULONG_ pul_TimerValueArray : Timer value array.       |
@@ -590,16 +590,16 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnReadAllTimerValue(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnReadAllTimerValue(struct comedi_device *dev, struct comedi_subdevice *s,
 				     struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	BYTE b_ModulNbr, b_ReadType;
-	PULONG pul_TimerValueArray;
+	int i_ReturnValue = 0;
+	unsigned char b_ModulNbr, b_ReadType;
+	unsigned int *pul_TimerValueArray;
 
 	b_ModulNbr = CR_AREF(insn->chanspec);
 	b_ReadType = CR_CHAN(insn->chanspec);
-	pul_TimerValueArray = (PULONG) data;
+	pul_TimerValueArray = (unsigned int *) data;
 	i_ReturnValue = insn->n;
 
 	switch (b_ReadType) {
@@ -662,8 +662,8 @@
 			i_ReturnValue = -2;
 		}
 
-	}			// End of Switch
-	return (i_ReturnValue);
+	}			/*  End of Switch */
+	return i_ReturnValue;
 }
 
 /*
@@ -681,11 +681,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnBitsTimer(struct comedi_device * dev, struct comedi_subdevice * s,
-			     struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnBitsTimer(struct comedi_device *dev, struct comedi_subdevice *s,
+			     struct comedi_insn *insn, unsigned int *data)
 {
-	BYTE b_BitsType;
-	INT i_ReturnValue = 0;
+	unsigned char b_BitsType;
+	int i_ReturnValue = 0;
 	b_BitsType = data[0];
 
 	printk("\n82X54");
@@ -693,30 +693,30 @@
 	switch (b_BitsType) {
 	case APCI1710_TIMER_READVALUE:
 		i_ReturnValue = i_APCI1710_ReadTimerValue(dev,
-							  (BYTE)CR_AREF(insn->chanspec),
-							  (BYTE)CR_CHAN(insn->chanspec),
-							  (PULONG) & data[0]);
+							  (unsigned char)CR_AREF(insn->chanspec),
+							  (unsigned char)CR_CHAN(insn->chanspec),
+							  (unsigned int *) &data[0]);
 		break;
 
 	case APCI1710_TIMER_GETOUTPUTLEVEL:
 		i_ReturnValue = i_APCI1710_GetTimerOutputLevel(dev,
-							       (BYTE)CR_AREF(insn->chanspec),
-							       (BYTE)CR_CHAN(insn->chanspec),
-							       (PBYTE) &data[0]);
+							       (unsigned char)CR_AREF(insn->chanspec),
+							       (unsigned char)CR_CHAN(insn->chanspec),
+							       (unsigned char *) &data[0]);
 		break;
 
 	case APCI1710_TIMER_GETPROGRESSSTATUS:
 		i_ReturnValue = i_APCI1710_GetTimerProgressStatus(dev,
-								  (BYTE)CR_AREF(insn->chanspec),
-								  (BYTE)CR_CHAN(insn->chanspec),
-								  (PBYTE)&data[0]);
+								  (unsigned char)CR_AREF(insn->chanspec),
+								  (unsigned char)CR_CHAN(insn->chanspec),
+								  (unsigned char *)&data[0]);
 		break;
 
 	case APCI1710_TIMER_WRITEVALUE:
 		i_ReturnValue = i_APCI1710_WriteTimerValue(dev,
-							   (BYTE)CR_AREF(insn->chanspec),
-							   (BYTE)CR_CHAN(insn->chanspec),
-							   (ULONG)data[1]);
+							   (unsigned char)CR_AREF(insn->chanspec),
+							   (unsigned char)CR_CHAN(insn->chanspec),
+							   (unsigned int)data[1]);
 
 		break;
 
@@ -727,25 +727,25 @@
 
 	if (i_ReturnValue >= 0)
 		i_ReturnValue = insn->n;
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_     i_APCI1710_ReadTimerValue                    |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
-|                                        BYTE_     b_TimerNbr,               |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
+|                                        unsigned char_     b_TimerNbr,               |
 |                                        PULONG_ pul_TimerValue)             |
 +----------------------------------------------------------------------------+
 | Task              : Return the timer value from selected digital timer     |
 |                     (b_TimerNbr) from selected timer  module (b_ModulNbr). |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_   b_BoardHandle     : Handle of board            |
+| Input Parameters  : unsigned char_   b_BoardHandle     : Handle of board            |
 |                                                 APCI-1710                  |
-|                     BYTE_   b_ModulNbr        : Selected module number     |
+|                     unsigned char_   b_ModulNbr        : Selected module number     |
 |                                                 (0 to 3)                   |
-|                     BYTE_   b_TimerNbr        : Timer number to read       |
+|                     unsigned char_   b_TimerNbr        : Timer number to read       |
 |                                                 (0 to 2)                   |
 +----------------------------------------------------------------------------+
 | Output Parameters : PULONG_ pul_TimerValue    : Timer value                |
@@ -760,11 +760,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_ReadTimerValue(struct comedi_device * dev,
-			      BYTE b_ModulNbr, BYTE b_TimerNbr,
-			      PULONG pul_TimerValue)
+int i_APCI1710_ReadTimerValue(struct comedi_device *dev,
+			      unsigned char b_ModulNbr, unsigned char b_TimerNbr,
+			      unsigned int *pul_TimerValue)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/* Test the module number */
 	if (b_ModulNbr < 4) {
@@ -800,7 +800,7 @@
 				/* Timer selection wrong */
 				DPRINTK("Timer selection wrong\n");
 				i_ReturnValue = -3;
-			}	// if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2))
+			}	/*  if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2)) */
 		} else {
 			/* The module is not a TIMER module */
 			DPRINTK("The module is not a TIMER module\n");
@@ -812,29 +812,29 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 	/*
 	   +----------------------------------------------------------------------------+
 	   | Function Name     : _INT_     i_APCI1710_GetTimerOutputLevel               |
-	   |                                       (BYTE_     b_BoardHandle,            |
-	   |                                        BYTE_     b_ModulNbr,               |
-	   |                                        BYTE_     b_TimerNbr,               |
-	   |                                        PBYTE_   pb_OutputLevel)            |
+	   |                                       (unsigned char_     b_BoardHandle,            |
+	   |                                        unsigned char_     b_ModulNbr,               |
+	   |                                        unsigned char_     b_TimerNbr,               |
+	   |                                        unsigned char *_   pb_OutputLevel)            |
 	   +----------------------------------------------------------------------------+
 	   | Task              : Return the output signal level (pb_OutputLevel) from   |
 	   |                     selected digital timer (b_TimerNbr) from selected timer|
 	   |                     module (b_ModulNbr).                                   |
 	   +----------------------------------------------------------------------------+
-	   | Input Parameters  : BYTE_   b_BoardHandle     : Handle of board            |
+	   | Input Parameters  : unsigned char_   b_BoardHandle     : Handle of board            |
 	   |                                                 APCI-1710                  |
-	   |                     BYTE_   b_ModulNbr        : Selected module number     |
+	   |                     unsigned char_   b_ModulNbr        : Selected module number     |
 	   |                                                 (0 to 3)                   |
-	   |                     BYTE_   b_TimerNbr        : Timer number to test       |
+	   |                     unsigned char_   b_TimerNbr        : Timer number to test       |
 	   |                                                 (0 to 2)                   |
 	   +----------------------------------------------------------------------------+
-	   | Output Parameters : PBYTE_ pb_OutputLevel     : Output signal level        |
+	   | Output Parameters : unsigned char *_ pb_OutputLevel     : Output signal level        |
 	   |                                                 0 : The output is low      |
 	   |                                                 1 : The output is high     |
 	   +----------------------------------------------------------------------------+
@@ -848,12 +848,12 @@
 	   +----------------------------------------------------------------------------+
 	 */
 
-INT i_APCI1710_GetTimerOutputLevel(struct comedi_device * dev,
-				   BYTE b_ModulNbr, BYTE b_TimerNbr,
-				   PBYTE pb_OutputLevel)
+int i_APCI1710_GetTimerOutputLevel(struct comedi_device *dev,
+				   unsigned char b_ModulNbr, unsigned char b_TimerNbr,
+				   unsigned char *pb_OutputLevel)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_TimerStatus;
+	int i_ReturnValue = 0;
+	unsigned int dw_TimerStatus;
 
 	/* Test the module number */
 	if (b_ModulNbr < 4) {
@@ -869,7 +869,7 @@
 					/* Read the timer status */
 					dw_TimerStatus = inl(devpriv->s_BoardInfos.ui_Address + 16 + (b_TimerNbr * 4) + (64 * b_ModulNbr));
 
-					*pb_OutputLevel = (BYTE) (((dw_TimerStatus >> 7) & 1) ^ devpriv-> s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].b_OutputLevel);
+					*pb_OutputLevel = (unsigned char) (((dw_TimerStatus >> 7) & 1) ^ devpriv-> s_ModuleInfo[b_ModulNbr].s_82X54ModuleInfo.s_82X54TimerInfo[b_TimerNbr].b_OutputLevel);
 				} else {
 					/* Timer not initialised see function */
 					DPRINTK("Timer not initialised see function\n");
@@ -879,7 +879,7 @@
 				/* Timer selection wrong */
 				DPRINTK("Timer selection wrong\n");
 				i_ReturnValue = -3;
-			}	// if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2))
+			}	/*  if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2)) */
 		} else {
 			/* The module is not a TIMER module */
 			DPRINTK("The module is not a TIMER module\n");
@@ -891,29 +891,29 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_     i_APCI1710_GetTimerProgressStatus            |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
-|                                        BYTE_     b_TimerNbr,               |
-|                                        PBYTE_   pb_TimerStatus)            |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
+|                                        unsigned char_     b_TimerNbr,               |
+|                                        unsigned char *_   pb_TimerStatus)            |
 +----------------------------------------------------------------------------+
 | Task              : Return the progress status (pb_TimerStatus) from       |
 |                     selected digital timer (b_TimerNbr) from selected timer|
 |                     module (b_ModulNbr).                                   |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_   b_BoardHandle     : Handle of board            |
+| Input Parameters  : unsigned char_   b_BoardHandle     : Handle of board            |
 |                                                 APCI-1710                  |
-|                     BYTE_   b_ModulNbr        : Selected module number     |
+|                     unsigned char_   b_ModulNbr        : Selected module number     |
 |                                                 (0 to 3)                   |
-|                     BYTE_   b_TimerNbr        : Timer number to test       |
+|                     unsigned char_   b_TimerNbr        : Timer number to test       |
 |                                                 (0 to 2)                   |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_TimerStatus     : Output signal level        |
+| Output Parameters : unsigned char *_ pb_TimerStatus     : Output signal level        |
 |                                                 0 : Timer not in progress  |
 |                                                 1 : Timer in progress      |
 +----------------------------------------------------------------------------+
@@ -927,12 +927,12 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_GetTimerProgressStatus(struct comedi_device *dev,
-				      BYTE b_ModulNbr, BYTE b_TimerNbr,
-				      PBYTE pb_TimerStatus)
+int i_APCI1710_GetTimerProgressStatus(struct comedi_device *dev,
+				      unsigned char b_ModulNbr, unsigned char b_TimerNbr,
+				      unsigned char *pb_TimerStatus)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_TimerStatus;
+	int i_ReturnValue = 0;
+	unsigned int dw_TimerStatus;
 
 	/* Test the module number */
 	if (b_ModulNbr < 4) {
@@ -949,7 +949,7 @@
 					/* Read the timer status */
 					dw_TimerStatus = inl(devpriv->s_BoardInfos.ui_Address + 16 + (b_TimerNbr * 4) + (64 * b_ModulNbr));
 
-					*pb_TimerStatus = (BYTE) ((dw_TimerStatus) >> 8) & 1;
+					*pb_TimerStatus = (unsigned char) ((dw_TimerStatus) >> 8) & 1;
 					printk("ProgressStatus : %d", *pb_TimerStatus);
 				} else {
 					/* Timer not initialised see function */
@@ -958,7 +958,7 @@
 			} else {
 				/* Timer selection wrong */
 				i_ReturnValue = -3;
-			}	// if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2))
+			}	/*  if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2)) */
 		} else {
 			/* The module is not a TIMER module */
 
@@ -976,9 +976,9 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_     i_APCI1710_WriteTimerValue                   |
-|                                       (BYTE_   b_BoardHandle,              |
-|                                        BYTE_   b_ModulNbr,                 |
-|                                        BYTE_   b_TimerNbr,                 |
+|                                       (unsigned char_   b_BoardHandle,              |
+|                                        unsigned char_   b_ModulNbr,                 |
+|                                        unsigned char_   b_TimerNbr,                 |
 |                                        ULONG_ ul_WriteValue)               |
 +----------------------------------------------------------------------------+
 | Task              : Write the value (ul_WriteValue) into the selected timer|
@@ -986,11 +986,11 @@
 |                     The action in depend of the time mode selection.       |
 |                     See timer mode description table.                      |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_   b_BoardHandle     : Handle of board            |
+| Input Parameters  : unsigned char_   b_BoardHandle     : Handle of board            |
 |                                                 APCI-1710                  |
-|                     BYTE_   b_ModulNbr        : Selected module number     |
+|                     unsigned char_   b_ModulNbr        : Selected module number     |
 |                                                 (0 to 3)                   |
-|                     BYTE_   b_TimerNbr        : Timer number to write      |
+|                     unsigned char_   b_TimerNbr        : Timer number to write      |
 |                                                 (0 to 2)                   |
 |                     ULONG_ ul_WriteValue      : Value to write             |
 +----------------------------------------------------------------------------+
@@ -1006,11 +1006,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_WriteTimerValue(struct comedi_device * dev,
-			       BYTE b_ModulNbr, BYTE b_TimerNbr,
-			       ULONG ul_WriteValue)
+int i_APCI1710_WriteTimerValue(struct comedi_device *dev,
+			       unsigned char b_ModulNbr, unsigned char b_TimerNbr,
+			       unsigned int ul_WriteValue)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/* Test the module number */
 	if (b_ModulNbr < 4) {
@@ -1031,7 +1031,7 @@
 				/* Timer selection wrong */
 				DPRINTK("Timer selection wrong\n");
 				i_ReturnValue = -3;
-			}	// if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2))
+			}	/*  if ((b_TimerNbr >= 0) && (b_TimerNbr <= 2)) */
 		} else {
 			/* The module is not a TIMER module */
 			DPRINTK("The module is not a TIMER module\n");
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_82x54.h b/drivers/staging/comedi/drivers/addi-data/APCI1710_82x54.h
index 4797c0b..9698ae1 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_82x54.h
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_82x54.h
@@ -34,40 +34,40 @@
 /*
  * 82X54 TIMER INISIALISATION FUNCTION
  */
-INT i_APCI1710_InsnConfigInitTimer(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnConfigInitTimer(struct comedi_device *dev, struct comedi_subdevice *s,
 				   struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_InsnWriteEnableDisableTimer(struct comedi_device *dev,
+int i_APCI1710_InsnWriteEnableDisableTimer(struct comedi_device *dev,
 					   struct comedi_subdevice *s,
 					   struct comedi_insn *insn, unsigned int *data);
 
 /*
  * 82X54 READ FUNCTION
  */
-INT i_APCI1710_InsnReadAllTimerValue(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnReadAllTimerValue(struct comedi_device *dev, struct comedi_subdevice *s,
 				     struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_InsnBitsTimer(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnBitsTimer(struct comedi_device *dev, struct comedi_subdevice *s,
 			     struct comedi_insn *insn, unsigned int *data);
 
 /*
  * 82X54 READ & WRITE FUNCTION
  */
-INT i_APCI1710_ReadTimerValue(struct comedi_device *dev,
-			      BYTE b_ModulNbr, BYTE b_TimerNbr,
-			      PULONG pul_TimerValue);
+int i_APCI1710_ReadTimerValue(struct comedi_device *dev,
+			      unsigned char b_ModulNbr, unsigned char b_TimerNbr,
+			      unsigned int *pul_TimerValue);
 
-INT i_APCI1710_GetTimerOutputLevel(struct comedi_device *dev,
-				   BYTE b_ModulNbr, BYTE b_TimerNbr,
-				   PBYTE pb_OutputLevel);
+int i_APCI1710_GetTimerOutputLevel(struct comedi_device *dev,
+				   unsigned char b_ModulNbr, unsigned char b_TimerNbr,
+				   unsigned char *pb_OutputLevel);
 
-INT i_APCI1710_GetTimerProgressStatus(struct comedi_device *dev,
-				      BYTE b_ModulNbr, BYTE b_TimerNbr,
-				      PBYTE pb_TimerStatus);
+int i_APCI1710_GetTimerProgressStatus(struct comedi_device *dev,
+				      unsigned char b_ModulNbr, unsigned char b_TimerNbr,
+				      unsigned char *pb_TimerStatus);
 
 /*
  * 82X54 WRITE FUNCTION
  */
-INT i_APCI1710_WriteTimerValue(struct comedi_device *dev,
-			       BYTE b_ModulNbr, BYTE b_TimerNbr,
-			       ULONG ul_WriteValue);
+int i_APCI1710_WriteTimerValue(struct comedi_device *dev,
+			       unsigned char b_ModulNbr, unsigned char b_TimerNbr,
+			       unsigned int ul_WriteValue);
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Chrono.c b/drivers/staging/comedi/drivers/addi-data/APCI1710_Chrono.c
index 1a54d3b..ccb109a 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Chrono.c
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Chrono.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -62,11 +62,11 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_     i_APCI1710_InitChrono                        |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
-|                                        BYTE_     b_ChronoMode,             |
-|                                        BYTE_     b_PCIInputClock,          |
-|                                        BYTE_     b_TimingUnit,             |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
+|                                        unsigned char_     b_ChronoMode,             |
+|                                        unsigned char_     b_PCIInputClock,          |
+|                                        unsigned char_     b_TimingUnit,             |
 |                                        ULONG_   ul_TimingInterval,         |
 |                                        PULONG_ pul_RealTimingInterval)
 
@@ -88,12 +88,12 @@
 |                     The mode 4 to 7 is appropriate for measuring the timing|
 |                     between  two event.                                    |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_   b_BoardHandle    : Handle of board APCI-1710   |
-| BYTE_   b_ModulNbr  CR_AREF(insn->chanspec)  : Module number to configure  |
+| Input Parameters  : unsigned char_   b_BoardHandle    : Handle of board APCI-1710   |
+| unsigned char_   b_ModulNbr  CR_AREF(insn->chanspec)  : Module number to configure  |
 |                                                (0 to 3)                    |
-| BYTE_   b_ChronoMode				data[0]    : Chronometer action mode     |
+| unsigned char_   b_ChronoMode				data[0]    : Chronometer action mode     |
 |                                                (0 to 7).                   |
-| BYTE_   b_PCIInputClock			data[1] : Selection from PCI bus clock|
+| unsigned char_   b_PCIInputClock			data[1] : Selection from PCI bus clock|
 |                                                - APCI1710_30MHZ :          |
 |                                                  The PC have a PCI bus     |
 |                                                  clock from 30 MHz         |
@@ -104,7 +104,7 @@
 |                                                  The APCI-1710 have a      |
 |                                                  integrated 40Mhz          |
 |                                                  quartz.                   |
-|               BYTE_   b_TimingUnit	data[2]    : Base timing unity (0 to 4) |
+|               unsigned char_   b_TimingUnit	data[2]    : Base timing unity (0 to 4) |
 |                                                 0 : ns                     |
 |                                                 1 : µs                     |
 |                                                 2 : ms                     |
@@ -131,23 +131,23 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnConfigInitChrono(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnConfigInitChrono(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	ULONG ul_TimerValue = 0;
-	ULONG ul_TimingInterval = 0;
-	ULONG ul_RealTimingInterval = 0;
+	int i_ReturnValue = 0;
+	unsigned int ul_TimerValue = 0;
+	unsigned int ul_TimingInterval = 0;
+	unsigned int ul_RealTimingInterval = 0;
 	double d_RealTimingInterval = 0;
-	DWORD dw_ModeArray[8] =
+	unsigned int dw_ModeArray[8] =
 		{ 0x01, 0x05, 0x00, 0x04, 0x02, 0x0E, 0x0A, 0x06 };
-	BYTE b_ModulNbr, b_ChronoMode, b_PCIInputClock, b_TimingUnit;
+	unsigned char b_ModulNbr, b_ChronoMode, b_PCIInputClock, b_TimingUnit;
 
 	b_ModulNbr = CR_AREF(insn->chanspec);
-	b_ChronoMode = (BYTE) data[0];
-	b_PCIInputClock = (BYTE) data[1];
-	b_TimingUnit = (BYTE) data[2];
-	ul_TimingInterval = (ULONG) data[3];
+	b_ChronoMode = (unsigned char) data[0];
+	b_PCIInputClock = (unsigned char) data[1];
+	b_TimingUnit = (unsigned char) data[2];
+	ul_TimingInterval = (unsigned int) data[3];
 	i_ReturnValue = insn->n;
 
 	/**************************/
@@ -214,7 +214,7 @@
 
 										ul_TimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_TimingInterval
 											*
 											(0.001 * b_PCIInputClock));
@@ -237,7 +237,7 @@
 
 										ul_RealTimingInterval
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_TimerValue
 											/
 											(0.001 * (double)b_PCIInputClock));
@@ -272,7 +272,7 @@
 										if (b_PCIInputClock != APCI1710_40MHZ) {
 											ul_TimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_TimerValue)
@@ -294,7 +294,7 @@
 
 										ul_TimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_TimingInterval
 											*
 											(1.0 * b_PCIInputClock));
@@ -317,7 +317,7 @@
 
 										ul_RealTimingInterval
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_TimerValue
 											/
 											(1.0 * (double)b_PCIInputClock));
@@ -354,7 +354,7 @@
 										if (b_PCIInputClock != APCI1710_40MHZ) {
 											ul_TimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_TimerValue)
@@ -400,7 +400,7 @@
 
 										ul_RealTimingInterval
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_TimerValue
 											/
 											(1000.0 * (double)b_PCIInputClock));
@@ -435,7 +435,7 @@
 										if (b_PCIInputClock != APCI1710_40MHZ) {
 											ul_TimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_TimerValue)
@@ -457,7 +457,7 @@
 
 										ul_TimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_TimingInterval
 											*
 											(1000000.0
@@ -482,7 +482,7 @@
 
 										ul_RealTimingInterval
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_TimerValue
 											/
 											(1000000.0
@@ -520,7 +520,7 @@
 										if (b_PCIInputClock != APCI1710_40MHZ) {
 											ul_TimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_TimerValue)
@@ -542,7 +542,7 @@
 
 										ul_TimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(ul_TimingInterval
 												*
@@ -570,7 +570,7 @@
 
 										ul_RealTimingInterval
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_TimerValue
 											/
 											(1000000.0
@@ -608,7 +608,7 @@
 										if (b_PCIInputClock != APCI1710_40MHZ) {
 											ul_TimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_TimerValue)
@@ -736,7 +736,7 @@
 							DPRINTK("Base timing selection is wrong\n");
 							i_ReturnValue = -7;
 						}
-					}	// if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4))
+					}	/*  if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
 					else {
 		       /***********************************/
 						/* Timing unity selection is wrong */
@@ -744,8 +744,8 @@
 
 						DPRINTK("Timing unity selection is wrong\n");
 						i_ReturnValue = -6;
-					}	// if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4))
-				}	// if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ))
+					}	/*  if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
+				}	/*  if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ)) */
 				else {
 		    /*****************************************/
 					/* The selected PCI input clock is wrong */
@@ -753,8 +753,8 @@
 
 					DPRINTK("The selected PCI input clock is wrong\n");
 					i_ReturnValue = -5;
-				}	// if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ))
-			}	// if (b_ChronoMode >= 0 && b_ChronoMode <= 7)
+				}	/*  if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ)) */
+			}	/*  if (b_ChronoMode >= 0 && b_ChronoMode <= 7) */
 			else {
 		 /***************************************/
 				/* Chronometer mode selection is wrong */
@@ -762,7 +762,7 @@
 
 				DPRINTK("Chronometer mode selection is wrong\n");
 				i_ReturnValue = -4;
-			}	// if (b_ChronoMode >= 0 && b_ChronoMode <= 7)
+			}	/*  if (b_ChronoMode >= 0 && b_ChronoMode <= 7) */
 		} else {
 	      /******************************************/
 			/* The module is not a Chronometer module */
@@ -780,17 +780,17 @@
 		i_ReturnValue = -2;
 	}
 	data[0] = ul_RealTimingInterval;
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_EnableChrono                          |
-|                                               (BYTE_ b_BoardHandle,        |
-|                                                BYTE_ b_ModulNbr,           |
-|                                                BYTE_ b_CycleMode,          |
-|                                                BYTE_ b_InterruptEnable)
-INT i_APCI1710_InsnWriteEnableDisableChrono(struct comedi_device *dev,
+|                                               (unsigned char_ b_BoardHandle,        |
+|                                                unsigned char_ b_ModulNbr,           |
+|                                                unsigned char_ b_CycleMode,          |
+|                                                unsigned char_ b_InterruptEnable)
+int i_APCI1710_InsnWriteEnableDisableChrono(struct comedi_device *dev,
 struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)						 |
 +----------------------------------------------------------------------------+
 | Task              : Enable the chronometer from selected module            |
@@ -810,12 +810,12 @@
 |                     witch the " i_APCI1710_EnableChrono" function, if no   |
 |                     stop signal occur this start signal is ignored.
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle  : Handle of board APCI-1710       |
-|                     BYTE_ b_ModulNbr   CR_AREF(chanspec)  : Selected module number (0 to 3) |
+| Input Parameters  : unsigned char_ b_BoardHandle  : Handle of board APCI-1710       |
+|                     unsigned char_ b_ModulNbr   CR_AREF(chanspec)  : Selected module number (0 to 3) |
                                   data[0]  ENABle/Disable chrono
-|                     BYTE_ b_CycleMode    : Selected the chronometer        |
+|                     unsigned char_ b_CycleMode    : Selected the chronometer        |
 |                                  data[1]           acquisition mode                |
-|                     BYTE_ b_InterruptEnable : Enable or disable the        |
+|                     unsigned char_ b_InterruptEnable : Enable or disable the        |
 |                                   data[2]            chronometer interrupt.       |
 |                                               APCI1710_ENABLE:             |
 |                                               Enable the chronometer       |
@@ -840,15 +840,15 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnWriteEnableDisableChrono(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnWriteEnableDisableChrono(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	BYTE b_ModulNbr, b_CycleMode, b_InterruptEnable, b_Action;
+	int i_ReturnValue = 0;
+	unsigned char b_ModulNbr, b_CycleMode, b_InterruptEnable, b_Action;
 	b_ModulNbr = CR_AREF(insn->chanspec);
-	b_Action = (BYTE) data[0];
-	b_CycleMode = (BYTE) data[1];
-	b_InterruptEnable = (BYTE) data[2];
+	b_Action = (unsigned char) data[0];
+	b_CycleMode = (unsigned char) data[1];
+	b_InterruptEnable = (unsigned char) data[2];
 	i_ReturnValue = insn->n;
 
 	/**************************/
@@ -951,7 +951,7 @@
 									ui_Address
 									+ 32 +
 									(64 * b_ModulNbr));
-								devpriv->tsk_Current = current;	// Save the current process task structure
+								devpriv->tsk_Current = current;	/*  Save the current process task structure */
 							}
 
 			  /***********************************/
@@ -980,7 +980,7 @@
 								36 +
 								(64 * b_ModulNbr));
 
-						}	// if ((b_InterruptEnable == APCI1710_ENABLE) || (b_InterruptEnable == APCI1710_DISABLE))
+						}	/*  if ((b_InterruptEnable == APCI1710_ENABLE) || (b_InterruptEnable == APCI1710_DISABLE)) */
 						else {
 		       /********************************/
 							/* Interrupt parameter is wrong */
@@ -988,8 +988,8 @@
 
 							DPRINTK("Interrupt parameter is wrong\n");
 							i_ReturnValue = -6;
-						}	// if ((b_InterruptEnable == APCI1710_ENABLE) || (b_InterruptEnable == APCI1710_DISABLE))
-					}	// if ((b_CycleMode == APCI1710_SINGLE) || (b_CycleMode == APCI1710_CONTINUOUS))
+						}	/*  if ((b_InterruptEnable == APCI1710_ENABLE) || (b_InterruptEnable == APCI1710_DISABLE)) */
+					}	/*  if ((b_CycleMode == APCI1710_SINGLE) || (b_CycleMode == APCI1710_CONTINUOUS)) */
 					else {
 		    /***********************************************/
 						/* Chronometer acquisition mode cycle is wrong */
@@ -997,7 +997,7 @@
 
 						DPRINTK("Chronometer acquisition mode cycle is wrong\n");
 						i_ReturnValue = -5;
-					}	// if ((b_CycleMode == APCI1710_SINGLE) || (b_CycleMode == APCI1710_CONTINUOUS))
+					}	/*  if ((b_CycleMode == APCI1710_SINGLE) || (b_CycleMode == APCI1710_CONTINUOUS)) */
 					break;
 
 				case APCI1710_DISABLE:
@@ -1046,7 +1046,7 @@
 				default:
 					DPRINTK("Inputs wrong! Enable or Disable chrono\n");
 					i_ReturnValue = -8;
-				}	// switch ENABLE/DISABLE
+				}	/*  switch ENABLE/DISABLE */
 			} else {
 		 /*******************************/
 				/* Chronometer not initialised */
@@ -1072,7 +1072,7 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -1090,36 +1090,36 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnReadChrono(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnReadChrono(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	BYTE b_ReadType;
-	INT i_ReturnValue = insn->n;
+	unsigned char b_ReadType;
+	int i_ReturnValue = insn->n;
 
 	b_ReadType = CR_CHAN(insn->chanspec);
 
 	switch (b_ReadType) {
 	case APCI1710_CHRONO_PROGRESS_STATUS:
 		i_ReturnValue = i_APCI1710_GetChronoProgressStatus(dev,
-			(BYTE) CR_AREF(insn->chanspec), (PBYTE) & data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned char *) &data[0]);
 		break;
 
 	case APCI1710_CHRONO_READVALUE:
 		i_ReturnValue = i_APCI1710_ReadChronoValue(dev,
-			(BYTE) CR_AREF(insn->chanspec),
-			(UINT) insn->unused[0],
-			(PBYTE) & data[0], (PULONG) & data[1]);
+			(unsigned char) CR_AREF(insn->chanspec),
+			(unsigned int) insn->unused[0],
+			(unsigned char *) &data[0], (unsigned int *) &data[1]);
 		break;
 
 	case APCI1710_CHRONO_CONVERTVALUE:
 		i_ReturnValue = i_APCI1710_ConvertChronoValue(dev,
-			(BYTE) CR_AREF(insn->chanspec),
-			(ULONG) insn->unused[0],
-			(PULONG) & data[0],
-			(PBYTE) & data[1],
-			(PBYTE) & data[2],
-			(PUINT) & data[3],
-			(PUINT) & data[4], (PUINT) & data[5]);
+			(unsigned char) CR_AREF(insn->chanspec),
+			(unsigned int) insn->unused[0],
+			(unsigned int *) &data[0],
+			(unsigned char *) &data[1],
+			(unsigned char *) &data[2],
+			(unsigned int *) &data[3],
+			(unsigned int *) &data[4], (unsigned int *) &data[5]);
 		break;
 
 	case APCI1710_CHRONO_READINTERRUPT:
@@ -1152,22 +1152,22 @@
 
 	if (i_ReturnValue >= 0)
 		i_ReturnValue = insn->n;
-	return (i_ReturnValue);
+	return i_ReturnValue;
 
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_GetChronoProgressStatus               |
-|                               (BYTE_    b_BoardHandle,                     |
-|                                BYTE_    b_ModulNbr,                        |
-|                                PBYTE_  pb_ChronoStatus)                    |
+|                               (unsigned char_    b_BoardHandle,                     |
+|                                unsigned char_    b_ModulNbr,                        |
+|                                unsigned char *_  pb_ChronoStatus)                    |
 +----------------------------------------------------------------------------+
 | Task              : Return the chronometer status (pb_ChronoStatus) from   |
 |                     selected chronometer module (b_ModulNbr).              |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle  : Handle of board APCI-1710       |
-|                     BYTE_ b_ModulNbr     : Selected module number (0 to 3) |
+| Input Parameters  : unsigned char_ b_BoardHandle  : Handle of board APCI-1710       |
+|                     unsigned char_ b_ModulNbr     : Selected module number (0 to 3) |
 +----------------------------------------------------------------------------+
 | Output Parameters : PULONG_  pb_ChronoStatus : Return the chronometer      |
 |                                                status.                     |
@@ -1194,11 +1194,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_GetChronoProgressStatus(struct comedi_device * dev,
-	BYTE b_ModulNbr, PBYTE pb_ChronoStatus)
+int i_APCI1710_GetChronoProgressStatus(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char *pb_ChronoStatus)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_Status;
+	int i_ReturnValue = 0;
+	unsigned int dw_Status;
 
 	/**************************/
 	/* Test the module number */
@@ -1233,7 +1233,7 @@
 		    /******************/
 
 					*pb_ChronoStatus = 3;
-				}	// if ((dw_Status & 8) == 8)
+				}	/*  if ((dw_Status & 8) == 8) */
 				else {
 		    /*******************************/
 					/* Test if measurement stopped */
@@ -1245,7 +1245,7 @@
 		       /***********************/
 
 						*pb_ChronoStatus = 2;
-					}	// if ((dw_Status & 2) == 2)
+					}	/*  if ((dw_Status & 2) == 2) */
 					else {
 		       /*******************************/
 						/* Test if measurement started */
@@ -1257,16 +1257,16 @@
 			  /************************/
 
 							*pb_ChronoStatus = 1;
-						}	// if ((dw_Status & 1) == 1)
+						}	/*  if ((dw_Status & 1) == 1) */
 						else {
 			  /***************************/
 							/* Measurement not started */
 			  /***************************/
 
 							*pb_ChronoStatus = 0;
-						}	// if ((dw_Status & 1) == 1)
-					}	// if ((dw_Status & 2) == 2)
-				}	// if ((dw_Status & 8) == 8)
+						}	/*  if ((dw_Status & 1) == 1) */
+					}	/*  if ((dw_Status & 2) == 2) */
+				}	/*  if ((dw_Status & 8) == 8) */
 			} else {
 		 /*******************************/
 				/* Chronometer not initialised */
@@ -1289,16 +1289,16 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_ReadChronoValue                       |
-|                               (BYTE_     b_BoardHandle,                    |
-|                                BYTE_     b_ModulNbr,                       |
-|                                UINT_    ui_TimeOut,                        |
-|                                PBYTE_   pb_ChronoStatus,                   |
+|                               (unsigned char_     b_BoardHandle,                    |
+|                                unsigned char_     b_ModulNbr,                       |
+|                                unsigned int_    ui_TimeOut,                        |
+|                                unsigned char *_   pb_ChronoStatus,                   |
 |                                PULONG_ pul_ChronoValue)                    |
 +----------------------------------------------------------------------------+
 | Task              : Return the chronometer status (pb_ChronoStatus) and the|
@@ -1323,8 +1323,8 @@
 |                     "i_APCI1710_InitChrono" function and the time unity is |
 |                     the b_TimingUnit from "i_APCI1710_InitChrono" function|
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle  : Handle of board APCI-1710       |
-|                     BYTE_ b_ModulNbr     : Selected module number (0 to 3) |
+| Input Parameters  : unsigned char_ b_BoardHandle  : Handle of board APCI-1710       |
+|                     unsigned char_ b_ModulNbr     : Selected module number (0 to 3) |
 +----------------------------------------------------------------------------+
 | Output Parameters : PULONG_  pb_ChronoStatus : Return the chronometer      |
 |                                                status.                     |
@@ -1341,7 +1341,7 @@
 |                                                   timing witch the         |
 |                                                   function                 |
 |                                                   "i_APCI1710_InitChrono"  |
-|                     PULONG  pul_ChronoValue  : Chronometer timing value.   |
+|                     unsigned int *  pul_ChronoValue  : Chronometer timing value.   |
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
 |                     -1: The handle parameter of the board is wrong         |
@@ -1355,13 +1355,13 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_ReadChronoValue(struct comedi_device * dev,
-	BYTE b_ModulNbr,
-	UINT ui_TimeOut, PBYTE pb_ChronoStatus, PULONG pul_ChronoValue)
+int i_APCI1710_ReadChronoValue(struct comedi_device *dev,
+	unsigned char b_ModulNbr,
+	unsigned int ui_TimeOut, unsigned char *pb_ChronoStatus, unsigned int *pul_ChronoValue)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_Status;
-	DWORD dw_TimeOut = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_Status;
+	unsigned int dw_TimeOut = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -1430,7 +1430,7 @@
 							}
 
 							break;
-						}	// if ((dw_Status & 8) == 8)
+						}	/*  if ((dw_Status & 8) == 8) */
 						else {
 			     /*******************************/
 							/* Test if measurement stopped */
@@ -1464,7 +1464,7 @@
 									outl(0, devpriv->s_BoardInfos.ui_Address + 36 + (64 * b_ModulNbr));
 								}
 								break;
-							}	// if ((dw_Status & 2) == 2)
+							}	/*  if ((dw_Status & 2) == 2) */
 							else {
 				/*******************************/
 								/* Test if measurement started */
@@ -1478,7 +1478,7 @@
 									*pb_ChronoStatus
 										=
 										1;
-								}	// if ((dw_Status & 1) == 1)
+								}	/*  if ((dw_Status & 1) == 1) */
 								else {
 				   /***************************/
 									/* Measurement not started */
@@ -1487,9 +1487,9 @@
 									*pb_ChronoStatus
 										=
 										0;
-								}	// if ((dw_Status & 1) == 1)
-							}	// if ((dw_Status & 2) == 2)
-						}	// if ((dw_Status & 8) == 8)
+								}	/*  if ((dw_Status & 1) == 1) */
+							}	/*  if ((dw_Status & 2) == 2) */
+						}	/*  if ((dw_Status & 8) == 8) */
 
 						if (dw_TimeOut == ui_TimeOut) {
 			     /*****************/
@@ -1507,7 +1507,7 @@
 							mdelay(1000);
 
 						}
-					}	// for (;;)
+					}	/*  for (;;) */
 
 		       /*****************************/
 					/* Test if stop signal occur */
@@ -1575,39 +1575,39 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_ConvertChronoValue                    |
-|                               (BYTE_     b_BoardHandle,                    |
-|                                BYTE_     b_ModulNbr,                       |
+|                               (unsigned char_     b_BoardHandle,                    |
+|                                unsigned char_     b_ModulNbr,                       |
 |                                ULONG_   ul_ChronoValue,                    |
 |                                PULONG_ pul_Hour,                           |
-|                                PBYTE_   pb_Minute,                         |
-|                                PBYTE_   pb_Second,                         |
-|                                PUINT_  pui_MilliSecond,                    |
-|                                PUINT_  pui_MicroSecond,                    |
-|                                PUINT_  pui_NanoSecond)                     |
+|                                unsigned char *_   pb_Minute,                         |
+|                                unsigned char *_   pb_Second,                         |
+|                                unsigned int *_  pui_MilliSecond,                    |
+|                                unsigned int *_  pui_MicroSecond,                    |
+|                                unsigned int *_  pui_NanoSecond)                     |
 +----------------------------------------------------------------------------+
 | Task              : Convert the chronometer measured timing                |
 |                     (ul_ChronoValue) in to h, mn, s, ms, µs, ns.           |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_   b_BoardHandle : Handle of board APCI-1710      |
-|                     BYTE_   b_ModulNbr    : Selected module number (0 to 3)|
+| Input Parameters  : unsigned char_   b_BoardHandle : Handle of board APCI-1710      |
+|                     unsigned char_   b_ModulNbr    : Selected module number (0 to 3)|
 |                     ULONG_ ul_ChronoValue : Measured chronometer timing    |
 |                                             value.                         |
 |                                             See"i_APCI1710_ReadChronoValue"|
 +----------------------------------------------------------------------------+
 | Output Parameters : PULONG_   pul_Hour        : Chronometer timing hour    |
-|                     PBYTE_     pb_Minute      : Chronometer timing minute  |
-|                     PBYTE_     pb_Second      : Chronometer timing second  |
-|                     PUINT_    pui_MilliSecond  : Chronometer timing mini   |
+|                     unsigned char *_     pb_Minute      : Chronometer timing minute  |
+|                     unsigned char *_     pb_Second      : Chronometer timing second  |
+|                     unsigned int *_    pui_MilliSecond  : Chronometer timing mini   |
 |                                                 second                     |
-|                     PUINT_    pui_MicroSecond : Chronometer timing micro   |
+|                     unsigned int *_    pui_MicroSecond : Chronometer timing micro   |
 |                                                 second                     |
-|                     PUINT_    pui_NanoSecond  : Chronometer timing nano    |
+|                     unsigned int *_    pui_NanoSecond  : Chronometer timing nano    |
 |                                                 second                     |
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
@@ -1619,15 +1619,15 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_ConvertChronoValue(struct comedi_device * dev,
-	BYTE b_ModulNbr,
-	ULONG ul_ChronoValue,
-	PULONG pul_Hour,
-	PBYTE pb_Minute,
-	PBYTE pb_Second,
-	PUINT pui_MilliSecond, PUINT pui_MicroSecond, PUINT pui_NanoSecond)
+int i_APCI1710_ConvertChronoValue(struct comedi_device *dev,
+	unsigned char b_ModulNbr,
+	unsigned int ul_ChronoValue,
+	unsigned int *pul_Hour,
+	unsigned char *pb_Minute,
+	unsigned char *pb_Second,
+	unsigned int *pui_MilliSecond, unsigned int *pui_MicroSecond, unsigned int *pui_NanoSecond)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 	double d_Hour;
 	double d_Minute;
 	double d_Second;
@@ -1681,7 +1681,7 @@
 			    /**********************/
 
 					d_Hour = d_Hour / (double)60.0;
-					*pul_Hour = (ULONG) d_Hour;
+					*pul_Hour = (unsigned int) d_Hour;
 
 			    /************************/
 					/* Calculate the minute */
@@ -1689,7 +1689,7 @@
 
 					d_Minute = d_Hour - *pul_Hour;
 					d_Minute = d_Minute * 60;
-					*pb_Minute = (BYTE) d_Minute;
+					*pb_Minute = (unsigned char) d_Minute;
 
 			    /************************/
 					/* Calculate the second */
@@ -1697,7 +1697,7 @@
 
 					d_Second = d_Minute - *pb_Minute;
 					d_Second = d_Second * 60;
-					*pb_Second = (BYTE) d_Second;
+					*pb_Second = (unsigned char) d_Second;
 
 			    /*****************************/
 					/* Calculate the mini second */
@@ -1705,7 +1705,7 @@
 
 					d_MilliSecond = d_Second - *pb_Second;
 					d_MilliSecond = d_MilliSecond * 1000;
-					*pui_MilliSecond = (UINT) d_MilliSecond;
+					*pui_MilliSecond = (unsigned int) d_MilliSecond;
 
 			    /******************************/
 					/* Calculate the micro second */
@@ -1715,7 +1715,7 @@
 						d_MilliSecond -
 						*pui_MilliSecond;
 					d_MicroSecond = d_MicroSecond * 1000;
-					*pui_MicroSecond = (UINT) d_MicroSecond;
+					*pui_MicroSecond = (unsigned int) d_MicroSecond;
 
 			    /******************************/
 					/* Calculate the micro second */
@@ -1725,7 +1725,7 @@
 						d_MicroSecond -
 						*pui_MicroSecond;
 					d_NanoSecond = d_NanoSecond * 1000;
-					*pui_NanoSecond = (UINT) d_NanoSecond;
+					*pui_NanoSecond = (unsigned int) d_NanoSecond;
 					break;
 				}
 
@@ -1752,21 +1752,21 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT i_APCI1710_InsnBitsChronoDigitalIO(struct comedi_device *dev,struct comedi_subdevice *s,
+| Function Name     : int i_APCI1710_InsnBitsChronoDigitalIO(struct comedi_device *dev,struct comedi_subdevice *s,
 	struct comedi_insn *insn,unsigned int *data)                    |
 +----------------------------------------------------------------------------+
 | Task              : Sets the output witch has been passed with the         |
 |                     parameter b_Channel. Setting an output means setting an|
 |                     output high.                                           |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle   : Handle of board APCI-1710      |
-|                     BYTE_ b_ModulNbr      : Selected module number (0 to 3)|
-|                     BYTE_ b_OutputChannel : Selection from digital output  |
+| Input Parameters  : unsigned char_ b_BoardHandle   : Handle of board APCI-1710      |
+|                     unsigned char_ b_ModulNbr      : Selected module number (0 to 3)|
+|                     unsigned char_ b_OutputChannel : Selection from digital output  |
 |                           CR_CHAN()                  channel (0 to 2)               |
 |                                              0 : Channel H                 |
 |                                              1 : Channel A                 |
@@ -1787,19 +1787,19 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_SetChronoChlOff                       |
-|                               (BYTE_  b_BoardHandle,                       |
-|                                BYTE_  b_ModulNbr,                          |
-|                                BYTE_  b_OutputChannel)                     |
+|                               (unsigned char_  b_BoardHandle,                       |
+|                                unsigned char_  b_ModulNbr,                          |
+|                                unsigned char_  b_OutputChannel)                     |
 +----------------------------------------------------------------------------+
 | Task              : Resets the output witch has been passed with the       |
 |                     parameter b_Channel. Resetting an output means setting |
 |                     an output low.                                         |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle   : Handle of board APCI-1710
+| Input Parameters  : unsigned char_ b_BoardHandle   : Handle of board APCI-1710
                         data[0] : Chl ON, Chl OFF , Chl Read , Port Read
 
-|                     BYTE_ b_ModulNbr  CR_AREF    : Selected module number (0 to 3)|
-|                     BYTE_ b_OutputChannel CR_CHAN : Selection from digital output  |
+|                     unsigned char_ b_ModulNbr  CR_AREF    : Selected module number (0 to 3)|
+|                     unsigned char_ b_OutputChannel CR_CHAN : Selection from digital output  |
 |                                             channel (0 to 2)               |
 |                                              0 : Channel H                 |
 |                                              1 : Channel A                 |
@@ -1820,24 +1820,24 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_ReadChronoChlValue                    |
-|                               (BYTE_   b_BoardHandle,                      |
-|                                BYTE_   b_ModulNbr,                         |
-|                                BYTE_   b_InputChannel,                     |
-|                                PBYTE_ pb_ChannelStatus)                    |
+|                               (unsigned char_   b_BoardHandle,                      |
+|                                unsigned char_   b_ModulNbr,                         |
+|                                unsigned char_   b_InputChannel,                     |
+|                                unsigned char *_ pb_ChannelStatus)                    |
 +----------------------------------------------------------------------------+
 | Task              : Return the status from selected digital input          |
 |                     (b_InputChannel) from selected chronometer             |
 |                     module (b_ModulNbr).                                   |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle   : Handle of board APCI-1710      |
-|                     BYTE_ b_ModulNbr      : Selected module number (0 to 3)|
-|                     BYTE_ b_InputChannel  : Selection from digital input   |
+| Input Parameters  : unsigned char_ b_BoardHandle   : Handle of board APCI-1710      |
+|                     unsigned char_ b_ModulNbr      : Selected module number (0 to 3)|
+|                     unsigned char_ b_InputChannel  : Selection from digital input   |
 |                                             channel (0 to 2)               |
 |                                   CR_CHAN()             0 : Channel E               |
 |                                                1 : Channel F               |
 |                                                2 : Channel G               |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_ChannelStatus : Digital input channel status.|
+| Output Parameters : unsigned char *_ pb_ChannelStatus : Digital input channel status.|
 |                                data[0]                0 : Channel is not active   |
 |                                                1 : Channel is active       |
 +----------------------------------------------------------------------------+
@@ -1854,17 +1854,17 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_ReadChronoPortValue                   |
-|                               (BYTE_   b_BoardHandle,                      |
-|                                BYTE_   b_ModulNbr,                         |
-|                                PBYTE_ pb_PortValue)                        |
+|                               (unsigned char_   b_BoardHandle,                      |
+|                                unsigned char_   b_ModulNbr,                         |
+|                                unsigned char *_ pb_PortValue)                        |
 +----------------------------------------------------------------------------+
 | Task              : Return the status from digital inputs port from        |
 |                     selected  (b_ModulNbr) chronometer module.             |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle   : Handle of board APCI-1710      |
-|                     BYTE_ b_ModulNbr      : Selected module number (0 to 3)|
+| Input Parameters  : unsigned char_ b_BoardHandle   : Handle of board APCI-1710      |
+|                     unsigned char_ b_ModulNbr      : Selected module number (0 to 3)|
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_PortValue   : Digital inputs port status.
+| Output Parameters : unsigned char *_ pb_PortValue   : Digital inputs port status.
 |                     data[0]
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
@@ -1876,18 +1876,18 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnBitsChronoDigitalIO(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnBitsChronoDigitalIO(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	BYTE b_ModulNbr, b_OutputChannel, b_InputChannel, b_IOType;
-	DWORD dw_Status;
-	PBYTE pb_ChannelStatus;
-	PBYTE pb_PortValue;
+	int i_ReturnValue = 0;
+	unsigned char b_ModulNbr, b_OutputChannel, b_InputChannel, b_IOType;
+	unsigned int dw_Status;
+	unsigned char *pb_ChannelStatus;
+	unsigned char *pb_PortValue;
 
 	b_ModulNbr = CR_AREF(insn->chanspec);
 	i_ReturnValue = insn->n;
-	b_IOType = (BYTE) data[0];
+	b_IOType = (unsigned char) data[0];
 
 	/**************************/
 	/* Test the module number */
@@ -1915,14 +1915,14 @@
 				case APCI1710_CHRONO_SET_CHANNELOFF:
 
 					b_OutputChannel =
-						(BYTE) CR_CHAN(insn->chanspec);
+						(unsigned char) CR_CHAN(insn->chanspec);
 					if (b_OutputChannel <= 2) {
 
 						outl(0, devpriv->s_BoardInfos.
 							ui_Address + 20 +
 							(b_OutputChannel * 4) +
 							(64 * b_ModulNbr));
-					}	// if ((b_OutputChannel >= 0) && (b_OutputChannel <= 2))
+					}	/*  if ((b_OutputChannel >= 0) && (b_OutputChannel <= 2)) */
 					else {
 		    /****************************************/
 						/* The selected digital output is wrong */
@@ -1931,21 +1931,21 @@
 						DPRINTK("The selected digital output is wrong\n");
 						i_ReturnValue = -4;
 
-					}	// if ((b_OutputChannel >= 0) && (b_OutputChannel <= 2))
+					}	/*  if ((b_OutputChannel >= 0) && (b_OutputChannel <= 2)) */
 
 					break;
 
 				case APCI1710_CHRONO_SET_CHANNELON:
 
 					b_OutputChannel =
-						(BYTE) CR_CHAN(insn->chanspec);
+						(unsigned char) CR_CHAN(insn->chanspec);
 					if (b_OutputChannel <= 2) {
 
 						outl(1, devpriv->s_BoardInfos.
 							ui_Address + 20 +
 							(b_OutputChannel * 4) +
 							(64 * b_ModulNbr));
-					}	// if ((b_OutputChannel >= 0) && (b_OutputChannel <= 2))
+					}	/*  if ((b_OutputChannel >= 0) && (b_OutputChannel <= 2)) */
 					else {
 		    /****************************************/
 						/* The selected digital output is wrong */
@@ -1954,7 +1954,7 @@
 						DPRINTK("The selected digital output is wrong\n");
 						i_ReturnValue = -4;
 
-					}	// if ((b_OutputChannel >= 0) && (b_OutputChannel <= 2))
+					}	/*  if ((b_OutputChannel >= 0) && (b_OutputChannel <= 2)) */
 
 					break;
 
@@ -1962,9 +1962,9 @@
 		 /**********************************/
 					/* Test the digital input channel */
 		 /**********************************/
-					pb_ChannelStatus = (PBYTE) & data[0];
+					pb_ChannelStatus = (unsigned char *) &data[0];
 					b_InputChannel =
-						(BYTE) CR_CHAN(insn->chanspec);
+						(unsigned char) CR_CHAN(insn->chanspec);
 
 					if (b_InputChannel <= 2) {
 
@@ -1975,10 +1975,10 @@
 							(64 * b_ModulNbr));
 
 						*pb_ChannelStatus =
-							(BYTE) (((dw_Status >>
+							(unsigned char) (((dw_Status >>
 									b_InputChannel)
 								& 1) ^ 1);
-					}	// if ((b_InputChannel >= 0) && (b_InputChannel <= 2))
+					}	/*  if ((b_InputChannel >= 0) && (b_InputChannel <= 2)) */
 					else {
 		    /***************************************/
 						/* The selected digital input is wrong */
@@ -1986,13 +1986,13 @@
 
 						DPRINTK("The selected digital input is wrong\n");
 						i_ReturnValue = -4;
-					}	// if ((b_InputChannel >= 0) && (b_InputChannel <= 2))
+					}	/*  if ((b_InputChannel >= 0) && (b_InputChannel <= 2)) */
 
 					break;
 
 				case APCI1710_CHRONO_READ_PORT:
 
-					pb_PortValue = (PBYTE) & data[0];
+					pb_PortValue = (unsigned char *) &data[0];
 
 					dw_Status =
 						inl(devpriv->s_BoardInfos.
@@ -2000,7 +2000,7 @@
 						(64 * b_ModulNbr));
 
 					*pb_PortValue =
-						(BYTE) ((dw_Status & 0x7) ^ 7);
+						(unsigned char) ((dw_Status & 0x7) ^ 7);
 					break;
 				}
 			} else {
@@ -2028,5 +2028,5 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Chrono.h b/drivers/staging/comedi/drivers/addi-data/APCI1710_Chrono.h
index 26b50ce..29bad1d 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Chrono.h
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Chrono.h
@@ -35,10 +35,10 @@
 /*
  * CHRONOMETER INISIALISATION FUNCTION
  */
-INT i_APCI1710_InsnConfigInitChrono(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnConfigInitChrono(struct comedi_device *dev, struct comedi_subdevice *s,
 				    struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_InsnWriteEnableDisableChrono(struct comedi_device *dev,
+int i_APCI1710_InsnWriteEnableDisableChrono(struct comedi_device *dev,
 					    struct comedi_subdevice *s,
 					    struct comedi_insn *insn,
 					    unsigned int *data);
@@ -46,29 +46,29 @@
 /*
  * CHRONOMETER READ FUNCTION
  */
-INT i_APCI1710_InsnReadChrono(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnReadChrono(struct comedi_device *dev, struct comedi_subdevice *s,
 			      struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_GetChronoProgressStatus(struct comedi_device *dev,
-				       BYTE b_ModulNbr, PBYTE pb_ChronoStatus);
+int i_APCI1710_GetChronoProgressStatus(struct comedi_device *dev,
+				       unsigned char b_ModulNbr, unsigned char *pb_ChronoStatus);
 
-INT i_APCI1710_ReadChronoValue(struct comedi_device *dev,
-			       BYTE b_ModulNbr,
-			       UINT ui_TimeOut, PBYTE pb_ChronoStatus,
-			       PULONG pul_ChronoValue);
+int i_APCI1710_ReadChronoValue(struct comedi_device *dev,
+			       unsigned char b_ModulNbr,
+			       unsigned int ui_TimeOut, unsigned char *pb_ChronoStatus,
+			       unsigned int *pul_ChronoValue);
 
-INT i_APCI1710_ConvertChronoValue(struct comedi_device *dev,
-				  BYTE b_ModulNbr,
-				  ULONG ul_ChronoValue,
-				  PULONG pul_Hour,
-				  PBYTE pb_Minute,
-				  PBYTE pb_Second,
-				  PUINT pui_MilliSecond, PUINT pui_MicroSecond,
-				  PUINT pui_NanoSecond);
+int i_APCI1710_ConvertChronoValue(struct comedi_device *dev,
+				  unsigned char b_ModulNbr,
+				  unsigned int ul_ChronoValue,
+				  unsigned int *pul_Hour,
+				  unsigned char *pb_Minute,
+				  unsigned char *pb_Second,
+				  unsigned int *pui_MilliSecond, unsigned int *pui_MicroSecond,
+				  unsigned int *pui_NanoSecond);
 
 /*
  * CHRONOMETER DIGITAL INPUT OUTPUT FUNCTION
  */
-INT i_APCI1710_InsnBitsChronoDigitalIO(struct comedi_device *dev,
+int i_APCI1710_InsnBitsChronoDigitalIO(struct comedi_device *dev,
 				       struct comedi_subdevice *s, struct comedi_insn *insn,
 				       unsigned int *data);
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Dig_io.c b/drivers/staging/comedi/drivers/addi-data/APCI1710_Dig_io.c
index 8be27ae..f3e47e5 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Dig_io.c
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Dig_io.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -61,7 +61,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT i_APCI1710_InsnConfigDigitalIO(struct comedi_device *dev, |
+| Function Name     : int i_APCI1710_InsnConfigDigitalIO(struct comedi_device *dev, |
 |						struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)|
 +----------------------------------------------------------------------------+
 | Task              : Configure the digital I/O operating mode from selected |
@@ -70,14 +70,14 @@
 |                     I/O.                                                   |
 +----------------------------------------------------------------------------+
 | Input Parameters  :													     |
-|                  BYTE_ b_ModulNbr      data[0]: Module number to               |
+|                  unsigned char_ b_ModulNbr      data[0]: Module number to               |
 |                                             configure (0 to 3)             |
-|                     BYTE_ b_ChannelAMode data[1]  : Channel A mode selection       |
+|                     unsigned char_ b_ChannelAMode data[1]  : Channel A mode selection       |
 |                                             0 : Channel used for digital   |
 |                                                 input                      |
 |                                             1 : Channel used for digital   |
 |                                                 output                     |
-|                     BYTE_ b_ChannelBMode data[2] : Channel B mode selection       |
+|                     unsigned char_ b_ChannelBMode data[2] : Channel B mode selection       |
 |                                             0 : Channel used for digital   |
 |                                                 input                      |
 |                                             1 : Channel used for digital   |
@@ -99,19 +99,19 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnConfigDigitalIO(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnConfigDigitalIO(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	BYTE b_ModulNbr, b_ChannelAMode, b_ChannelBMode;
-	BYTE b_MemoryOnOff, b_ConfigType;
-	INT i_ReturnValue = 0;
-	DWORD dw_WriteConfig = 0;
+	unsigned char b_ModulNbr, b_ChannelAMode, b_ChannelBMode;
+	unsigned char b_MemoryOnOff, b_ConfigType;
+	int i_ReturnValue = 0;
+	unsigned int dw_WriteConfig = 0;
 
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_ConfigType = (BYTE) data[0];	// Memory or  Init
-	b_ChannelAMode = (BYTE) data[1];
-	b_ChannelBMode = (BYTE) data[2];
-	b_MemoryOnOff = (BYTE) data[1];	// if memory operation
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_ConfigType = (unsigned char) data[0];	/*  Memory or  Init */
+	b_ChannelAMode = (unsigned char) data[1];
+	b_ChannelBMode = (unsigned char) data[2];
+	b_MemoryOnOff = (unsigned char) data[1];	/*  if memory operation */
 	i_ReturnValue = insn->n;
 
 		/**************************/
@@ -126,7 +126,7 @@
 	switch (b_ConfigType) {
 	case APCI1710_DIGIO_MEMORYONOFF:
 
-		if (b_MemoryOnOff)	// If Memory ON
+		if (b_MemoryOnOff)	/*  If Memory ON */
 		{
 		 /****************************/
 			/* Set the output memory on */
@@ -140,7 +140,7 @@
 		 /***************************/
 			devpriv->s_ModuleInfo[b_ModulNbr].
 				s_DigitalIOInfo.dw_OutputMemory = 0;
-		} else		// If memory off
+		} else		/*  If memory off */
 		{
 		 /*****************************/
 			/* Set the output memory off */
@@ -197,7 +197,7 @@
 	/*****************************************/
 
 					dw_WriteConfig =
-						(DWORD) (b_ChannelAMode |
+						(unsigned int) (b_ChannelAMode |
 						(b_ChannelBMode * 2));
 
 	/***************************/
@@ -233,7 +233,7 @@
 			DPRINTK("The module is not a digital I/O module\n");
 			i_ReturnValue = -3;
 		}
-	}			// end of Switch
+	}			/*  end of Switch */
 	printk("Return Value %d\n", i_ReturnValue);
 	return i_ReturnValue;
 }
@@ -257,9 +257,9 @@
 
 
 |
-|  BYTE_ b_ModulNbr  CR_AREF(chanspec)          : Selected module number   |
+|  unsigned char_ b_ModulNbr  CR_AREF(chanspec)          : Selected module number   |
 |                                                   (0 to 3)                 |
-|  BYTE_ b_InputChannel CR_CHAN(chanspec)        : Selection from digital   |
+|  unsigned char_ b_InputChannel CR_CHAN(chanspec)        : Selection from digital   |
 |                                                   input ( 0 to 6)          |
 |                                                      0 : Channel C         |
 |                                                      1 : Channel D         |
@@ -288,22 +288,22 @@
 +----------------------------------------------------------------------------+
 */
 
-//_INT_   i_APCI1710_ReadDigitalIOChlValue      (BYTE_    b_BoardHandle,
-//                                             BYTE_    b_ModulNbr,
-//                                             BYTE_    b_InputChannel,
-//
-//                                             PBYTE_  pb_ChannelStatus)
-INT i_APCI1710_InsnReadDigitalIOChlValue(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+/* _INT_   i_APCI1710_ReadDigitalIOChlValue      (unsigned char_    b_BoardHandle, */
+/*
+* unsigned char_ b_ModulNbr, unsigned char_ b_InputChannel,
+* unsigned char *_ pb_ChannelStatus)
+*/
+int i_APCI1710_InsnReadDigitalIOChlValue(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg;
-	BYTE b_ModulNbr, b_InputChannel;
-	PBYTE pb_ChannelStatus;
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_InputChannel = (BYTE) CR_CHAN(insn->chanspec);
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg;
+	unsigned char b_ModulNbr, b_InputChannel;
+	unsigned char *pb_ChannelStatus;
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_InputChannel = (unsigned char) CR_CHAN(insn->chanspec);
 	data[0] = 0;
-	pb_ChannelStatus = (PBYTE) & data[0];
+	pb_ChannelStatus = (unsigned char *) &data[0];
 	i_ReturnValue = insn->n;
 
 	/**************************/
@@ -356,7 +356,7 @@
 								i_ReturnValue =
 									-6;
 							}
-						}	// if (b_InputChannel == 5)
+						}	/*  if (b_InputChannel == 5) */
 						else {
 			  /***************************/
 							/* Test the channel B mode */
@@ -375,8 +375,8 @@
 								i_ReturnValue =
 									-7;
 							}
-						}	// if (b_InputChannel == 5)
-					}	// if (b_InputChannel > 4)
+						}	/*  if (b_InputChannel == 5) */
+					}	/*  if (b_InputChannel > 4) */
 
 		    /***********************/
 					/* Test if error occur */
@@ -387,11 +387,10 @@
 						/* Read all digital input */
 		       /**************************/
 
-						//INPDW (ps_APCI1710Variable->
-						//   s_Board [b_BoardHandle].
-						//   s_BoardInfos.
-						//  ui_Address + (64 * b_ModulNbr),
-						// &dw_StatusReg);
+/*
+* INPDW (ps_APCI1710Variable-> s_Board [b_BoardHandle].
+* s_BoardInfos. ui_Address + (64 * b_ModulNbr), &dw_StatusReg);
+*/
 
 						dw_StatusReg =
 							inl(devpriv->
@@ -400,11 +399,11 @@
 							(64 * b_ModulNbr));
 
 						*pb_ChannelStatus =
-							(BYTE) ((dw_StatusReg ^
+							(unsigned char) ((dw_StatusReg ^
 								0x1C) >>
 							b_InputChannel) & 1;
 
-					}	// if (i_ReturnValue == 0)
+					}	/*  if (i_ReturnValue == 0) */
 				} else {
 		    /*******************************/
 					/* Digital I/O not initialised */
@@ -434,7 +433,7 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -445,7 +444,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT i_APCI1710_InsnWriteDigitalIOChlOnOff(comedi_device
+| Function Name     : int i_APCI1710_InsnWriteDigitalIOChlOnOff(comedi_device
 |*dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)
 
 +----------------------------------------------------------------------------+
@@ -453,9 +452,9 @@
 |                     parameter b_Channel. Setting an output means setting   |
 |                     an ouput high.                                         |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle   : Handle of board APCI-1710      |
-|                     BYTE_ b_ModulNbr (aref )    : Selected module number (0 to 3)|
-|                     BYTE_ b_OutputChannel (CR_CHAN) : Selection from digital output  |
+| Input Parameters  : unsigned char_ b_BoardHandle   : Handle of board APCI-1710      |
+|                     unsigned char_ b_ModulNbr (aref )    : Selected module number (0 to 3)|
+|                     unsigned char_ b_OutputChannel (CR_CHAN) : Selection from digital output  |
 |                                             channel (0 to 2)               |
 |                                                0 : Channel H               |
 |                                                1 : Channel A               |
@@ -478,15 +477,16 @@
 +----------------------------------------------------------------------------+
 */
 
-//_INT_   i_APCI1710_SetDigitalIOChlOn    (BYTE_ b_BoardHandle,
-//                                       BYTE_ b_ModulNbr,
-//                                       BYTE_ b_OutputChannel)
-INT i_APCI1710_InsnWriteDigitalIOChlOnOff(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+/*
+* _INT_ i_APCI1710_SetDigitalIOChlOn (unsigned char_ b_BoardHandle,
+* unsigned char_ b_ModulNbr, unsigned char_ b_OutputChannel)
+*/
+int i_APCI1710_InsnWriteDigitalIOChlOnOff(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_WriteValue = 0;
-	BYTE b_ModulNbr, b_OutputChannel;
+	int i_ReturnValue = 0;
+	unsigned int dw_WriteValue = 0;
+	unsigned char b_ModulNbr, b_OutputChannel;
 	i_ReturnValue = insn->n;
 	b_ModulNbr = CR_AREF(insn->chanspec);
 	b_OutputChannel = CR_CHAN(insn->chanspec);
@@ -602,7 +602,7 @@
 								1 <<
 								b_OutputChannel;
 						}
-					}	// set channel off
+					}	/*  set channel off */
 					else {
 						if (devpriv->
 							s_ModuleInfo
@@ -627,23 +627,24 @@
 								dw_OutputMemory
 								= dw_WriteValue;
 						} else {
-		       /*****************************/
+							/*****************************/
 							/* Digital Output Memory OFF */
-		       /*****************************/
-							// +Use previously the function "i_APCI1710_SetDigitalIOMemoryOn"
+							/*****************************/
+							/*  +Use previously the function "i_APCI1710_SetDigitalIOMemoryOn" */
 							i_ReturnValue = -8;
 						}
 
 					}
-		    /*******************/
+					/*******************/
 					/* Write the value */
-		    /*******************/
+					/*******************/
 
-					//OUTPDW (ps_APCI1710Variable->
-					//    s_Board [b_BoardHandle].
-					//   s_BoardInfos.
-					//   ui_Address + (64 * b_ModulNbr),
-					//   dw_WriteValue);
+					/* OUTPDW (ps_APCI1710Variable->
+					 * s_Board [b_BoardHandle].
+					 * s_BoardInfos. ui_Address + (64 * b_ModulNbr),
+					 * dw_WriteValue);
+					 */
+*/
 					outl(dw_WriteValue,
 						devpriv->s_BoardInfos.
 						ui_Address + (64 * b_ModulNbr));
@@ -670,7 +671,7 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -690,19 +691,19 @@
 |                     from selected digital I/O module (b_ModulNbr)
 +----------------------------------------------------------------------------+
 | Input Parameters  :
-	BYTE_ b_BoardHandle   : Handle of board APCI-1710      |
-|   BYTE_ b_ModulNbr  CR_AREF(aref)    : Selected module number (0 to 3)|
-|   BYTE_ b_PortValue CR_CHAN(chanspec) : Output Value ( 0 To 7 )
+	unsigned char_ b_BoardHandle   : Handle of board APCI-1710      |
+|   unsigned char_ b_ModulNbr  CR_AREF(aref)    : Selected module number (0 to 3)|
+|   unsigned char_ b_PortValue CR_CHAN(chanspec) : Output Value ( 0 To 7 )
 |                       data[0]           read or write port
-                        data[1]            if write then indicate ON or OFF
+|                       data[1]            if write then indicate ON or OFF
 
-                        if read : data[1] will return port status.
+|                       if read : data[1] will return port status.
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
 | Return Value      :
 
-                INPUT :
+|                INPUT :
 
 					  0: No error                                            |
 |                    -1: The handle parameter of the board is wrong          |
@@ -725,75 +726,78 @@
 +----------------------------------------------------------------------------+
 */
 
-//_INT_   i_APCI1710_SetDigitalIOPortOn   (BYTE_ b_BoardHandle,
-//                                       BYTE_ b_ModulNbr,
-//                                       BYTE_ b_PortValue)
-INT i_APCI1710_InsnBitsDigitalIOPortOnOff(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+/*
+ * _INT_ i_APCI1710_SetDigitalIOPortOn (unsigned char_
+ * b_BoardHandle, unsigned char_ b_ModulNbr, unsigned char_
+ * b_PortValue)
+*/
+int i_APCI1710_InsnBitsDigitalIOPortOnOff(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_WriteValue = 0;
-	DWORD dw_StatusReg;
-	BYTE b_ModulNbr, b_PortValue;
-	BYTE b_PortOperation, b_PortOnOFF;
+	int i_ReturnValue = 0;
+	unsigned int dw_WriteValue = 0;
+	unsigned int dw_StatusReg;
+	unsigned char b_ModulNbr, b_PortValue;
+	unsigned char b_PortOperation, b_PortOnOFF;
 
-	PBYTE pb_PortValue;
+	unsigned char *pb_PortValue;
 
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_PortOperation = (BYTE) data[0];	// Input or output
-	b_PortOnOFF = (BYTE) data[1];	// if output then On or Off
-	b_PortValue = (BYTE) data[2];	// if out put then Value
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_PortOperation = (unsigned char) data[0];	/*  Input or output */
+	b_PortOnOFF = (unsigned char) data[1];	/*  if output then On or Off */
+	b_PortValue = (unsigned char) data[2];	/*  if out put then Value */
 	i_ReturnValue = insn->n;
-	pb_PortValue = (PBYTE) & data[0];
-// if input then read value
+	pb_PortValue = (unsigned char *) &data[0];
+/* if input then read value */
 
 	switch (b_PortOperation) {
 	case APCI1710_INPUT:
-	/**************************/
+		/**************************/
 		/* Test the module number */
-	/**************************/
+		/**************************/
 
 		if (b_ModulNbr < 4) {
-	   /*******************************/
+			/*******************************/
 			/* Test if digital I/O counter */
-	   /*******************************/
+			/*******************************/
 
 			if ((devpriv->s_BoardInfos.
 					dw_MolduleConfiguration[b_ModulNbr] &
 					0xFFFF0000UL) == APCI1710_DIGITAL_IO) {
-	      /**********************************************/
+				/**********************************************/
 				/* Test if the digital I/O module initialised */
-	      /**********************************************/
+				/**********************************************/
 
 				if (devpriv->s_ModuleInfo[b_ModulNbr].
 					s_DigitalIOInfo.b_DigitalInit == 1) {
-		 /**************************/
+					/**************************/
 					/* Read all digital input */
-		 /**************************/
+					/**************************/
 
-					//INPDW (ps_APCI1710Variable->
-					//      s_Board [b_BoardHandle].
-					//      s_BoardInfos.
-					//      ui_Address + (64 * b_ModulNbr),
-					//      &dw_StatusReg);
+					/* INPDW (ps_APCI1710Variable->
+					 * s_Board [b_BoardHandle].
+					 * s_BoardInfos.
+					 * ui_Address + (64 * b_ModulNbr),
+					 * &dw_StatusReg);
+					 */
 
 					dw_StatusReg =
 						inl(devpriv->s_BoardInfos.
 						ui_Address + (64 * b_ModulNbr));
 					*pb_PortValue =
-						(BYTE) (dw_StatusReg ^ 0x1C);
+						(unsigned char) (dw_StatusReg ^ 0x1C);
 
 				} else {
-		 /*******************************/
+					/*******************************/
 					/* Digital I/O not initialised */
-		 /*******************************/
+					/*******************************/
 
 					i_ReturnValue = -4;
 				}
 			} else {
-	      /******************************************/
+				/******************************************/
 				/* The module is not a digital I/O module */
-	      /******************************************/
+				/******************************************/
 
 				i_ReturnValue = -3;
 			}
@@ -853,11 +857,11 @@
 								i_ReturnValue =
 									-6;
 							}
-						}	// if ((b_PortValue & 2) == 2)
+						}	/*  if ((b_PortValue & 2) == 2) */
 
-		    /**************************/
+						/**************************/
 						/* Test if channel B used */
-		    /**************************/
+						/**************************/
 
 						if ((b_PortValue & 4) == 4) {
 							if (devpriv->
@@ -866,33 +870,33 @@
 								s_DigitalIOInfo.
 								b_ChannelBMode
 								!= 1) {
-			  /*******************************************/
+								/*******************************************/
 								/* The digital channel B is used for input */
-			  /*******************************************/
+								/*******************************************/
 
 								i_ReturnValue =
 									-7;
 							}
-						}	// if ((b_PortValue & 4) == 4)
+						}	/*  if ((b_PortValue & 4) == 4) */
 
-		    /***********************/
+						/***********************/
 						/* Test if error occur */
-		    /***********************/
+						/***********************/
 
 						if (i_ReturnValue >= 0) {
 
-							//if(data[1])
-							//{
+							/* if(data[1]) { */
+
 							switch (b_PortOnOFF) {
-			   /*********************************/
+								/*********************************/
 								/* Test if set Port ON                   */
-		       /*********************************/
+								/*********************************/
 
 							case APCI1710_ON:
 
-		       /*********************************/
+								/*********************************/
 								/* Test if output memory enabled */
-		       /*********************************/
+								/*********************************/
 
 								if (devpriv->
 									s_ModuleInfo
@@ -924,7 +928,7 @@
 								}
 								break;
 
-								// If Set PORT  OFF
+								/*  If Set PORT  OFF */
 							case APCI1710_OFF:
 
 			   /*********************************/
@@ -957,25 +961,26 @@
 										=
 										dw_WriteValue;
 								} else {
-			  /*****************************/
+									/*****************************/
 									/* Digital Output Memory OFF */
-			  /*****************************/
+									/*****************************/
 
 									i_ReturnValue
 										=
 										-8;
 								}
-							}	// switch
+							}	/*  switch */
 
-		       /*******************/
+							/*******************/
 							/* Write the value */
-		       /*******************/
+							/*******************/
 
-							//  OUTPDW (ps_APCI1710Variable->
-							//      s_Board [b_BoardHandle].
-							//      s_BoardInfos.
-							//      ui_Address + (64 * b_ModulNbr),
-							//      dw_WriteValue);
+							/* OUTPDW (ps_APCI1710Variable->
+							 * s_Board [b_BoardHandle].
+							 * s_BoardInfos.
+							 * ui_Address + (64 * b_ModulNbr),
+							 * dw_WriteValue); */
+
 							outl(dw_WriteValue,
 								devpriv->
 								s_BoardInfos.
@@ -983,16 +988,16 @@
 								(64 * b_ModulNbr));
 						}
 					} else {
-		    /**********************/
+						/**********************/
 						/* Output value wrong */
-		    /**********************/
+						/**********************/
 
 						i_ReturnValue = -4;
 					}
 				} else {
-		 /*******************************/
+					/*******************************/
 					/* Digital I/O not initialised */
-		 /*******************************/
+					/*******************************/
 
 					i_ReturnValue = -5;
 				}
@@ -1015,6 +1020,6 @@
 	default:
 		i_ReturnValue = -9;
 		DPRINTK("NO INPUT/OUTPUT specified\n");
-	}			//switch INPUT / OUTPUT
-	return (i_ReturnValue);
+	}			/* switch INPUT / OUTPUT */
+	return i_ReturnValue;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Dig_io.h b/drivers/staging/comedi/drivers/addi-data/APCI1710_Dig_io.h
index 5ef157a..af1b9cd 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Dig_io.h
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Dig_io.h
@@ -27,20 +27,20 @@
 /*
  * DIGITAL I/O INISIALISATION FUNCTION
  */
-INT i_APCI1710_InsnConfigDigitalIO(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnConfigDigitalIO(struct comedi_device *dev, struct comedi_subdevice *s,
 				   struct comedi_insn *insn, unsigned int *data);
 
 /*
  * INPUT OUTPUT  FUNCTIONS
  */
-INT i_APCI1710_InsnReadDigitalIOChlValue(struct comedi_device *dev,
+int i_APCI1710_InsnReadDigitalIOChlValue(struct comedi_device *dev,
 					 struct comedi_subdevice *s,
 					 struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_InsnWriteDigitalIOChlOnOff(struct comedi_device *dev,
+int i_APCI1710_InsnWriteDigitalIOChlOnOff(struct comedi_device *dev,
 					  struct comedi_subdevice *s,
 					  struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_InsnBitsDigitalIOPortOnOff(struct comedi_device *dev,
+int i_APCI1710_InsnBitsDigitalIOPortOnOff(struct comedi_device *dev,
 					  struct comedi_subdevice *s,
 					  struct comedi_insn *insn, unsigned int *data);
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_INCCPT.c b/drivers/staging/comedi/drivers/addi-data/APCI1710_INCCPT.c
index 1062f2f..6c092ef 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_INCCPT.c
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_INCCPT.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -61,7 +61,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| INT	i_APCI1710_InsnConfigINCCPT(struct comedi_device *dev,struct comedi_subdevice *s,
+| int	i_APCI1710_InsnConfigINCCPT(struct comedi_device *dev,struct comedi_subdevice *s,
 struct comedi_insn *insn,unsigned int *data)
 
 +----------------------------------------------------------------------------+
@@ -75,58 +75,58 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnConfigINCCPT(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnConfigINCCPT(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_ConfigType;
-	INT i_ReturnValue = 0;
+	unsigned int ui_ConfigType;
+	int i_ReturnValue = 0;
 	ui_ConfigType = CR_CHAN(insn->chanspec);
 
 	printk("\nINC_CPT");
 
-	devpriv->tsk_Current = current;	// Save the current process task structure
+	devpriv->tsk_Current = current;	/*  Save the current process task structure */
 	switch (ui_ConfigType) {
 	case APCI1710_INCCPT_INITCOUNTER:
 		i_ReturnValue = i_APCI1710_InitCounter(dev,
 			CR_AREF(insn->chanspec),
-			(BYTE) data[0],
-			(BYTE) data[1],
-			(BYTE) data[2], (BYTE) data[3], (BYTE) data[4]);
+			(unsigned char) data[0],
+			(unsigned char) data[1],
+			(unsigned char) data[2], (unsigned char) data[3], (unsigned char) data[4]);
 		break;
 
 	case APCI1710_INCCPT_COUNTERAUTOTEST:
 		i_ReturnValue = i_APCI1710_CounterAutoTest(dev,
-			(PBYTE) & data[0]);
+			(unsigned char *) &data[0]);
 		break;
 
 	case APCI1710_INCCPT_INITINDEX:
 		i_ReturnValue = i_APCI1710_InitIndex(dev,
 			CR_AREF(insn->chanspec),
-			(BYTE) data[0],
-			(BYTE) data[1], (BYTE) data[2], (BYTE) data[3]);
+			(unsigned char) data[0],
+			(unsigned char) data[1], (unsigned char) data[2], (unsigned char) data[3]);
 		break;
 
 	case APCI1710_INCCPT_INITREFERENCE:
 		i_ReturnValue = i_APCI1710_InitReference(dev,
-			CR_AREF(insn->chanspec), (BYTE) data[0]);
+			CR_AREF(insn->chanspec), (unsigned char) data[0]);
 		break;
 
 	case APCI1710_INCCPT_INITEXTERNALSTROBE:
 		i_ReturnValue = i_APCI1710_InitExternalStrobe(dev,
 			CR_AREF(insn->chanspec),
-			(BYTE) data[0], (BYTE) data[1]);
+			(unsigned char) data[0], (unsigned char) data[1]);
 		break;
 
 	case APCI1710_INCCPT_INITCOMPARELOGIC:
 		i_ReturnValue = i_APCI1710_InitCompareLogic(dev,
-			CR_AREF(insn->chanspec), (UINT) data[0]);
+			CR_AREF(insn->chanspec), (unsigned int) data[0]);
 		break;
 
 	case APCI1710_INCCPT_INITFREQUENCYMEASUREMENT:
 		i_ReturnValue = i_APCI1710_InitFrequencyMeasurement(dev,
 			CR_AREF(insn->chanspec),
-			(BYTE) data[0],
-			(BYTE) data[1], (ULONG) data[2], (PULONG) & data[0]);
+			(unsigned char) data[0],
+			(unsigned char) data[1], (unsigned int) data[2], (unsigned int *) &data[0]);
 		break;
 
 	default:
@@ -136,19 +136,19 @@
 
 	if (i_ReturnValue >= 0)
 		i_ReturnValue = insn->n;
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_InitCounter                           |
-|                               (BYTE_          b_BoardHandle,               |
-|                                BYTE_          b_ModulNbr,                  |
-|                                BYTE_          b_CounterRange,              |
-|                                BYTE_          b_FirstCounterModus,         |
-|                                BYTE_          b_FirstCounterOption,        |
-|                                BYTE_          b_SecondCounterModus,        |
-|                                BYTE_          b_SecondCounterOption)       |
+|                               (unsigned char_          b_BoardHandle,               |
+|                                unsigned char_          b_ModulNbr,                  |
+|                                unsigned char_          b_CounterRange,              |
+|                                unsigned char_          b_FirstCounterModus,         |
+|                                unsigned char_          b_FirstCounterOption,        |
+|                                unsigned char_          b_SecondCounterModus,        |
+|                                unsigned char_          b_SecondCounterOption)       |
 +----------------------------------------------------------------------------+
 | Task              : Configure the counter operating mode from selected     |
 |                     module (b_ModulNbr). You must calling this function be |
@@ -273,17 +273,17 @@
 | +----------------------+--------------------+----------------------------+ |
 |                                                                            |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle         : Handle of board APCI-1710|
-|                     BYTE_ b_ModulNbr            : Module number to         |
+| Input Parameters  : unsigned char_ b_BoardHandle         : Handle of board APCI-1710|
+|                     unsigned char_ b_ModulNbr            : Module number to         |
 |                                                   configure (0 to 3)       |
-|                     BYTE_ b_CounterRange        : Selection form counter   |
+|                     unsigned char_ b_CounterRange        : Selection form counter   |
 |                                                   range.                   |
-|                     BYTE_ b_FirstCounterModus   : First counter operating  |
+|                     unsigned char_ b_FirstCounterModus   : First counter operating  |
 |                                                   mode.                    |
-|                     BYTE_ b_FirstCounterOption  : First counter  option.   |
-|                     BYTE_ b_SecondCounterModus  : Second counter operating |
+|                     unsigned char_ b_FirstCounterOption  : First counter  option.   |
+|                     unsigned char_ b_SecondCounterModus  : Second counter operating |
 |                                                   mode.                    |
-|                     BYTE_ b_SecondCounterOption : Second counter  option.  |
+|                     unsigned char_ b_SecondCounterOption : Second counter  option.  |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -299,14 +299,14 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InitCounter(struct comedi_device * dev,
-	BYTE b_ModulNbr,
-	BYTE b_CounterRange,
-	BYTE b_FirstCounterModus,
-	BYTE b_FirstCounterOption,
-	BYTE b_SecondCounterModus, BYTE b_SecondCounterOption)
+int i_APCI1710_InitCounter(struct comedi_device *dev,
+	unsigned char b_ModulNbr,
+	unsigned char b_CounterRange,
+	unsigned char b_FirstCounterModus,
+	unsigned char b_FirstCounterOption,
+	unsigned char b_SecondCounterModus, unsigned char b_SecondCounterOption)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/*******************************/
 	/* Test if incremental counter */
@@ -502,14 +502,14 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_CounterAutoTest                       |
-|                                               (BYTE_     b_BoardHandle,    |
-|                                                PBYTE_   pb_TestStatus)     |
+|                                               (unsigned char_     b_BoardHandle,    |
+|                                                unsigned char *_   pb_TestStatus)     |
 +----------------------------------------------------------------------------+
 | Task              : A test mode is intended for testing the component and  |
 |                     the connected periphery. All the 8-bit counter chains  |
@@ -535,9 +535,9 @@
 |              |    1000         | Error detected of counter 3 |             |
 |              +-----------------+-----------------------------+             |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_   b_BoardHandle : Handle of board APCI-1710      |  |
+| Input Parameters  : unsigned char_   b_BoardHandle : Handle of board APCI-1710      |  |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_TestStatus  : Auto test conclusion. See table|
+| Output Parameters : unsigned char *_ pb_TestStatus  : Auto test conclusion. See table|
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
 |                     -1: The handle parameter of the board is wrong         |
@@ -545,11 +545,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_CounterAutoTest(struct comedi_device * dev, PBYTE pb_TestStatus)
+int i_APCI1710_CounterAutoTest(struct comedi_device *dev, unsigned char *pb_TestStatus)
 {
-	BYTE b_ModulCpt = 0;
-	INT i_ReturnValue = 0;
-	DWORD dw_LathchValue;
+	unsigned char b_ModulCpt = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_LathchValue;
 
 	*pb_TestStatus = 0;
 
@@ -627,17 +627,17 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : _INT_ i_APCI1710_InitIndex (BYTE_ b_BoardHandle,       |
-|                                                 BYTE_ b_ModulNbr,          |
-|                                                 BYTE_ b_ReferenceAction,   |
-|                                                 BYTE_ b_IndexOperation,    |
-|                                                 BYTE_ b_AutoMode,          |
-|                                                 BYTE_ b_InterruptEnable)   |
+| Function Name     : _INT_ i_APCI1710_InitIndex (unsigned char_ b_BoardHandle,       |
+|                                                 unsigned char_ b_ModulNbr,          |
+|                                                 unsigned char_ b_ReferenceAction,   |
+|                                                 unsigned char_ b_IndexOperation,    |
+|                                                 unsigned char_ b_AutoMode,          |
+|                                                 unsigned char_ b_InterruptEnable)   |
 +----------------------------------------------------------------------------+
 | Task              : Initialise the index corresponding to the selected     |
 |                     module (b_ModulNbr). If a INDEX flag occur, you have   |
@@ -665,10 +665,10 @@
 |           |                        | value is cleared (32-Bit)          |  |
 |           +------------------------+------------------------------------+  |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
-|                     BYTE_ b_ReferenceAction : Determine if the reference   |
+|                     unsigned char_ b_ReferenceAction : Determine if the reference   |
 |                                               must set or no for the       |
 |                                               acceptance from index        |
 |                                               APCI1710_ENABLE :            |
@@ -677,15 +677,15 @@
 |                                               APCI1710_DISABLE :           |
 |                                                  Reference have not        |
 |                                                  importance                |
-|                     BYTE_ b_IndexOperation  : Index operating mode.        |
+|                     unsigned char_ b_IndexOperation  : Index operating mode.        |
 |                                               See table.                   |
-|                     BYTE_ b_AutoMode        : Enable or disable the        |
+|                     unsigned char_ b_AutoMode        : Enable or disable the        |
 |                                               automatic index reset.       |
 |                                               APCI1710_ENABLE :            |
 |                                                 Enable the automatic mode  |
 |                                               APCI1710_DISABLE :           |
 |                                                 Disable the automatic mode |
-|                     BYTE_ b_InterruptEnable : Enable or disable the        |
+|                     unsigned char_ b_InterruptEnable : Enable or disable the        |
 |                                               interrupt.                   |
 |                                               APCI1710_ENABLE :            |
 |                                               Enable the interrupt         |
@@ -708,12 +708,12 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InitIndex(struct comedi_device * dev,
-	BYTE b_ModulNbr,
-	BYTE b_ReferenceAction,
-	BYTE b_IndexOperation, BYTE b_AutoMode, BYTE b_InterruptEnable)
+int i_APCI1710_InitIndex(struct comedi_device *dev,
+	unsigned char b_ModulNbr,
+	unsigned char b_ReferenceAction,
+	unsigned char b_IndexOperation, unsigned char b_AutoMode, unsigned char b_InterruptEnable)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -902,7 +902,7 @@
 									b_ModeRegister4
 									|
 									APCI1710_ENABLE_LATCH_AND_CLEAR;
-							}	// if (b_IndexOperation == APCI1710_HIGH_EDGE_LATCH_AND_CLEAR_COUNTER || b_IndexOperation == APCI1710_LOW_EDGE_LATCH_AND_CLEAR_COUNTER)
+							}	/*  if (b_IndexOperation == APCI1710_HIGH_EDGE_LATCH_AND_CLEAR_COUNTER || b_IndexOperation == APCI1710_LOW_EDGE_LATCH_AND_CLEAR_COUNTER) */
 							else {
 				/*****************************************/
 								/* Clear the latch and clear flag (DQ27) */
@@ -975,7 +975,7 @@
 										&
 										(~APCI1710_INDEX_LATCH_COUNTER);
 								}
-							}	// // if (b_IndexOperation == APCI1710_HIGH_EDGE_LATCH_AND_CLEAR_COUNTER || b_IndexOperation == APCI1710_LOW_EDGE_LATCH_AND_CLEAR_COUNTER)
+							}	/*  // if (b_IndexOperation == APCI1710_HIGH_EDGE_LATCH_AND_CLEAR_COUNTER || b_IndexOperation == APCI1710_LOW_EDGE_LATCH_AND_CLEAR_COUNTER) */
 
 							if (b_AutoMode ==
 								APCI1710_DISABLE)
@@ -1113,15 +1113,15 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_InitReference                         |
-|                                                (BYTE_ b_BoardHandle,       |
-|                                                 BYTE_ b_ModulNbr,          |
-|                                                 BYTE_ b_ReferenceLevel)    |
+|                                                (unsigned char_ b_BoardHandle,       |
+|                                                 unsigned char_ b_ModulNbr,          |
+|                                                 unsigned char_ b_ReferenceLevel)    |
 +----------------------------------------------------------------------------+
 | Task              : Initialise the reference corresponding to the selected |
 |                     module (b_ModulNbr).                                   |
@@ -1136,10 +1136,10 @@
 |             |   APCI1710_HIGH    |  Reference occur if "1" |               |
 |             +--------------------+-------------------------+               |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
-|                     BYTE_ b_ReferenceLevel  : Reference level.             |
+|                     unsigned char_ b_ReferenceLevel  : Reference level.             |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -1152,10 +1152,10 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InitReference(struct comedi_device * dev,
-	BYTE b_ModulNbr, BYTE b_ReferenceLevel)
+int i_APCI1710_InitReference(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char b_ReferenceLevel)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -1239,27 +1239,27 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_	i_APCI1710_InitExternalStrobe                |
-|					(BYTE_ b_BoardHandle,                |
-|					 BYTE_ b_ModulNbr,                   |
-|					 BYTE_ b_ExternalStrobe,             |
-|					 BYTE_ b_ExternalStrobeLevel)        |
+|					(unsigned char_ b_BoardHandle,                |
+|					 unsigned char_ b_ModulNbr,                   |
+|					 unsigned char_ b_ExternalStrobe,             |
+|					 unsigned char_ b_ExternalStrobeLevel)        |
 +----------------------------------------------------------------------------+
 | Task              : Initialises the external strobe level corresponding to |
 |		      the selected module (b_ModulNbr).                      |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
-|		      BYTE_ b_ExternalStrobe  : External strobe selection    |
+|		      unsigned char_ b_ExternalStrobe  : External strobe selection    |
 |						0 : External strobe A        |
 |						1 : External strobe B        |
-|		      BYTE_ b_ExternalStrobeLevel : External strobe level    |
+|		      unsigned char_ b_ExternalStrobeLevel : External strobe level    |
 |						APCI1710_LOW :               |
 |						External latch occurs if "0" |
 |						APCI1710_HIGH :              |
@@ -1277,10 +1277,10 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InitExternalStrobe(struct comedi_device * dev,
-	BYTE b_ModulNbr, BYTE b_ExternalStrobe, BYTE b_ExternalStrobeLevel)
+int i_APCI1710_InitExternalStrobe(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char b_ExternalStrobe, unsigned char b_ExternalStrobeLevel)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -1335,7 +1335,7 @@
 					DPRINTK("External strobe level parameter is wrong\n");
 					i_ReturnValue = -5;
 				}
-			}	// if (b_ExternalStrobe == 0 || b_ExternalStrobe == 1)
+			}	/*  if (b_ExternalStrobe == 0 || b_ExternalStrobe == 1) */
 			else {
 		 /**************************************/
 				/* External strobe selection is wrong */
@@ -1343,7 +1343,7 @@
 
 				DPRINTK("External strobe selection is wrong\n");
 				i_ReturnValue = -4;
-			}	// if (b_ExternalStrobe == 0 || b_ExternalStrobe == 1)
+			}	/*  if (b_ExternalStrobe == 0 || b_ExternalStrobe == 1) */
 		} else {
 	      /****************************************/
 			/* Counter not initialised see function */
@@ -1362,24 +1362,24 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 	/*
 	   +----------------------------------------------------------------------------+
 	   | Function Name     : _INT_ i_APCI1710_InitCompareLogic                      |
-	   |                               (BYTE_   b_BoardHandle,                      |
-	   |                                BYTE_   b_ModulNbr,                         |
-	   |                                UINT_  ui_CompareValue)                     |
+	   |                               (unsigned char_   b_BoardHandle,                      |
+	   |                                unsigned char_   b_ModulNbr,                         |
+	   |                                unsigned int_  ui_CompareValue)                     |
 	   +----------------------------------------------------------------------------+
 	   | Task              : Set the 32-Bit compare value. At that moment that the  |
 	   |                     incremental counter arrive to the compare value        |
 	   |                     (ui_CompareValue) a interrupt is generated.            |
 	   +----------------------------------------------------------------------------+
-	   | Input Parameters  : BYTE_  b_BoardHandle    : Handle of board APCI-1710    |
-	   |                     BYTE_  b_ModulNbr       : Module number to configure   |
+	   | Input Parameters  : unsigned char_  b_BoardHandle    : Handle of board APCI-1710    |
+	   |                     unsigned char_  b_ModulNbr       : Module number to configure   |
 	   |                                               (0 to 3)                     |
-	   |                     UINT_ ui_CompareValue   : 32-Bit compare value         |
+	   |                     unsigned int_ ui_CompareValue   : 32-Bit compare value         |
 	   +----------------------------------------------------------------------------+
 	   | Output Parameters : -
 	   +----------------------------------------------------------------------------+
@@ -1391,10 +1391,10 @@
 	   +----------------------------------------------------------------------------+
 	 */
 
-INT i_APCI1710_InitCompareLogic(struct comedi_device * dev,
-	BYTE b_ModulNbr, UINT ui_CompareValue)
+int i_APCI1710_InitCompareLogic(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned int ui_CompareValue)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -1434,16 +1434,16 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_InitFrequencyMeasurement              |
-|				(BYTE_		 b_BoardHandle,              |
-|				 BYTE_		 b_ModulNbr,                 |
-|				 BYTE_		 b_PCIInputClock,            |
-|				 BYTE_		 b_TimingUnity,              |
+|				(unsigned char_		 b_BoardHandle,              |
+|				 unsigned char_		 b_ModulNbr,                 |
+|				 unsigned char_		 b_PCIInputClock,            |
+|				 unsigned char_		 b_TimingUnity,              |
 |				 ULONG_ 	ul_TimingInterval,           |
 |				 PULONG_       pul_RealTimingInterval)       |
 +----------------------------------------------------------------------------+
@@ -1456,10 +1456,10 @@
 |		      you call up any other function which gives access to   |
 |		      the frequency measurement.                             |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_  b_BoardHandle    : Handle of board APCI-1710    |
-|		      BYTE_  b_ModulNbr	      :	Number of the module to be   |
+| Input Parameters  : unsigned char_  b_BoardHandle    : Handle of board APCI-1710    |
+|		      unsigned char_  b_ModulNbr	      :	Number of the module to be   |
 |						configured (0 to 3)          |
-|		      BYTE_  b_PCIInputClock  :	Selection of the PCI bus     |
+|		      unsigned char_  b_PCIInputClock  :	Selection of the PCI bus     |
 |						clock                        |
 |						- APCI1710_30MHZ :           |
 |						  The PC has a PCI bus clock |
@@ -1467,7 +1467,7 @@
 |						- APCI1710_33MHZ :           |
 |						  The PC has a PCI bus clock |
 |						  of 33 MHz                  |
-|		      BYTE_  b_TimingUnity    : Base time unit (0 to 2)      |
+|		      unsigned char_  b_TimingUnity    : Base time unit (0 to 2)      |
 |						  0 : ns                     |
 |						  1 : æs                     |
 |						  2 : ms                     |
@@ -1487,16 +1487,16 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InitFrequencyMeasurement(struct comedi_device * dev,
-	BYTE b_ModulNbr,
-	BYTE b_PCIInputClock,
-	BYTE b_TimingUnity,
-	ULONG ul_TimingInterval, PULONG pul_RealTimingInterval)
+int i_APCI1710_InitFrequencyMeasurement(struct comedi_device *dev,
+	unsigned char b_ModulNbr,
+	unsigned char b_PCIInputClock,
+	unsigned char b_TimingUnity,
+	unsigned int ul_TimingInterval, unsigned int *pul_RealTimingInterval)
 {
-	INT i_ReturnValue = 0;
-	ULONG ul_TimerValue = 0;
+	int i_ReturnValue = 0;
+	unsigned int ul_TimerValue = 0;
 	double d_RealTimingInterval;
-	DWORD dw_Status = 0;
+	unsigned int dw_Status = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -1637,7 +1637,7 @@
 								i_ReturnValue =
 									-7;
 							}
-						}	// if (b_PCIInputClock == APCI1710_40MHZ)
+						}	/*  if (b_PCIInputClock == APCI1710_40MHZ) */
 
 		       /***************************/
 						/* Test if not error occur */
@@ -1676,7 +1676,7 @@
 										b_ModeRegister4
 										|
 										APCI1710_ENABLE_40MHZ_FREQUENCY;
-								}	// if (b_PCIInputClock == APCI1710_40MHZ)
+								}	/*  if (b_PCIInputClock == APCI1710_40MHZ) */
 								else {
 				   /**********************************/
 									/* Disable the 40MHz quarz (DQ30) */
@@ -1700,7 +1700,7 @@
 										&
 										APCI1710_DISABLE_40MHZ_FREQUENCY;
 
-								}	// if (b_PCIInputClock == APCI1710_40MHZ)
+								}	/*  if (b_PCIInputClock == APCI1710_40MHZ) */
 
 			     /********************************/
 								/* Calculate the division fator */
@@ -1720,7 +1720,7 @@
 
 									ul_TimerValue
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_TimingInterval
 										*
 										(0.00025 * b_PCIInputClock));
@@ -1743,7 +1743,7 @@
 
 									*pul_RealTimingInterval
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_TimerValue
 										/
 										(0.00025 * (double)b_PCIInputClock));
@@ -1790,7 +1790,7 @@
 
 									ul_TimerValue
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_TimingInterval
 										*
 										(0.25 * b_PCIInputClock));
@@ -1813,7 +1813,7 @@
 
 									*pul_RealTimingInterval
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_TimerValue
 										/
 										(0.25 * (double)b_PCIInputClock));
@@ -1886,7 +1886,7 @@
 
 									*pul_RealTimingInterval
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_TimerValue
 										/
 										(250.0 * (double)b_PCIInputClock));
@@ -1949,7 +1949,7 @@
 								i_ReturnValue =
 									-3;
 							}
-						}	// if (i_ReturnValue == 0)
+						}	/*  if (i_ReturnValue == 0) */
 					} else {
 		       /**********************************/
 						/* Base timing selection is wrong */
@@ -1992,12 +1992,12 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*########################################################################### */
 
-							//INSN BITS
+							/* INSN BITS */
 /*########################################################################### */
 
 /*
@@ -2015,18 +2015,18 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnBitsINCCPT(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnBitsINCCPT(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_BitsType;
-	INT i_ReturnValue = 0;
+	unsigned int ui_BitsType;
+	int i_ReturnValue = 0;
 	ui_BitsType = CR_CHAN(insn->chanspec);
-	devpriv->tsk_Current = current;	// Save the current process task structure
+	devpriv->tsk_Current = current;	/*  Save the current process task structure */
 
 	switch (ui_BitsType) {
 	case APCI1710_INCCPT_CLEARCOUNTERVALUE:
 		i_ReturnValue = i_APCI1710_ClearCounterValue(dev,
-			(BYTE) CR_AREF(insn->chanspec));
+			(unsigned char) CR_AREF(insn->chanspec));
 		break;
 
 	case APCI1710_INCCPT_CLEARALLCOUNTERVALUE:
@@ -2035,28 +2035,28 @@
 
 	case APCI1710_INCCPT_SETINPUTFILTER:
 		i_ReturnValue = i_APCI1710_SetInputFilter(dev,
-			(BYTE) CR_AREF(insn->chanspec),
-			(BYTE) data[0], (BYTE) data[1]);
+			(unsigned char) CR_AREF(insn->chanspec),
+			(unsigned char) data[0], (unsigned char) data[1]);
 		break;
 
 	case APCI1710_INCCPT_LATCHCOUNTER:
 		i_ReturnValue = i_APCI1710_LatchCounter(dev,
-			(BYTE) CR_AREF(insn->chanspec), (BYTE) data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned char) data[0]);
 		break;
 
 	case APCI1710_INCCPT_SETINDEXANDREFERENCESOURCE:
 		i_ReturnValue = i_APCI1710_SetIndexAndReferenceSource(dev,
-			(BYTE) CR_AREF(insn->chanspec), (BYTE) data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned char) data[0]);
 		break;
 
 	case APCI1710_INCCPT_SETDIGITALCHLON:
 		i_ReturnValue = i_APCI1710_SetDigitalChlOn(dev,
-			(BYTE) CR_AREF(insn->chanspec));
+			(unsigned char) CR_AREF(insn->chanspec));
 		break;
 
 	case APCI1710_INCCPT_SETDIGITALCHLOFF:
 		i_ReturnValue = i_APCI1710_SetDigitalChlOff(dev,
-			(BYTE) CR_AREF(insn->chanspec));
+			(unsigned char) CR_AREF(insn->chanspec));
 		break;
 
 	default:
@@ -2065,20 +2065,20 @@
 
 	if (i_ReturnValue >= 0)
 		i_ReturnValue = insn->n;
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_ClearCounterValue                     |
-|                               (BYTE_      b_BoardHandle,                   |
-|                                BYTE_       b_ModulNbr)                     |
+|                               (unsigned char_      b_BoardHandle,                   |
+|                                unsigned char_       b_ModulNbr)                     |
 +----------------------------------------------------------------------------+
 | Task              : Clear the counter value from selected module           |
 |                     (b_ModulNbr).                                          |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle : Handle of board APCI-1710        |
-|                     BYTE_ b_ModulNbr    : Module number to configure       |
+| Input Parameters  : unsigned char_ b_BoardHandle : Handle of board APCI-1710        |
+|                     unsigned char_ b_ModulNbr    : Module number to configure       |
 |                                           (0 to 3)                         |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -2091,9 +2091,9 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_ClearCounterValue(struct comedi_device * dev, BYTE b_ModulNbr)
+int i_APCI1710_ClearCounterValue(struct comedi_device *dev, unsigned char b_ModulNbr)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -2131,17 +2131,17 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_ClearAllCounterValue                  |
-|                               (BYTE_      b_BoardHandle)                   |
+|                               (unsigned char_      b_BoardHandle)                   |
 +----------------------------------------------------------------------------+
 | Task              : Clear all counter value.                               |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle : Handle of board APCI-1710        |
+| Input Parameters  : unsigned char_ b_BoardHandle : Handle of board APCI-1710        |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -2151,10 +2151,10 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_ClearAllCounterValue(struct comedi_device * dev)
+int i_APCI1710_ClearAllCounterValue(struct comedi_device *dev)
 {
-	BYTE b_ModulCpt = 0;
-	INT i_ReturnValue = 0;
+	unsigned char b_ModulCpt = 0;
+	int i_ReturnValue = 0;
 
 	/********************************/
 	/* Test if counter module found */
@@ -2198,24 +2198,24 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_SetInputFilter                        |
-|					(BYTE_ b_BoardHandle,                |
-|					 BYTE_ b_Module,                     |
-|					 BYTE_ b_PCIInputClock,              |
-|					 BYTE_ b_Filter)     		     |
+|					(unsigned char_ b_BoardHandle,                |
+|					 unsigned char_ b_Module,                     |
+|					 unsigned char_ b_PCIInputClock,              |
+|					 unsigned char_ b_Filter)     		     |
 +----------------------------------------------------------------------------+
 | Task              : Disable or enable the software filter from selected    |
 |		      module (b_ModulNbr). b_Filter determine the filter time|
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_  b_BoardHandle    : Handle of board APCI-1710    |
-|		      BYTE_  b_ModulNbr	      :	Number of the module to be   |
+| Input Parameters  : unsigned char_  b_BoardHandle    : Handle of board APCI-1710    |
+|		      unsigned char_  b_ModulNbr	      :	Number of the module to be   |
 |						configured (0 to 3)          |
-|		      BYTE_  b_PCIInputClock  :	Selection of the PCI bus     |
+|		      unsigned char_  b_PCIInputClock  :	Selection of the PCI bus     |
 |						clock                        |
 |						- APCI1710_30MHZ :           |
 |						  The PC has a PCI bus clock |
@@ -2226,7 +2226,7 @@
 |						- APCI1710_40MHZ :           |
 |						  The APCI1710 has a 40MHz    |
 |						  quartz		     |
-|		      BYTE_  b_Filter	      : Filter selection             |
+|		      unsigned char_  b_Filter	      : Filter selection             |
 |                                                                            |
 |				30 MHz                                       |
 |				------                                       |
@@ -2297,11 +2297,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_SetInputFilter(struct comedi_device * dev,
-	BYTE b_ModulNbr, BYTE b_PCIInputClock, BYTE b_Filter)
+int i_APCI1710_SetInputFilter(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char b_PCIInputClock, unsigned char b_Filter)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_Status = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_Status = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -2365,7 +2365,7 @@
 								i_ReturnValue =
 									-6;
 							}
-						}	// if (b_PCIInputClock == APCI1710_40MHZ)
+						}	/*  if (b_PCIInputClock == APCI1710_40MHZ) */
 
 		       /***************************/
 						/* Test if error not occur */
@@ -2401,7 +2401,7 @@
 									|
 									APCI1710_ENABLE_40MHZ_FILTER;
 
-							}	// if (b_PCIInputClock == APCI1710_40MHZ)
+							}	/*  if (b_PCIInputClock == APCI1710_40MHZ) */
 							else {
 			     /**********************************/
 								/* Disable the 40MHz quarz (DQ31) */
@@ -2425,7 +2425,7 @@
 									&
 									APCI1710_DISABLE_40MHZ_FILTER;
 
-							}	// if (b_PCIInputClock == APCI1710_40MHZ)
+							}	/*  if (b_PCIInputClock == APCI1710_40MHZ) */
 
 			  /************************/
 							/* Set the filter value */
@@ -2486,8 +2486,8 @@
 								ui_Address +
 								20 +
 								(64 * b_ModulNbr));
-						}	// if (i_ReturnValue == 0)
-					}	// if (b_Filter < 16)
+						}	/*  if (i_ReturnValue == 0) */
+					}	/*  if (b_Filter < 16) */
 					else {
 		       /**************************************/
 						/* The selected filter value is wrong */
@@ -2495,8 +2495,8 @@
 
 						DPRINTK("The selected filter value is wrong\n");
 						i_ReturnValue = -5;
-					}	// if (b_Filter < 16)
-				}	// if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ) || (b_PCIInputClock == APCI1710_40MHZ))
+					}	/*  if (b_Filter < 16) */
+				}	/*  if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ) || (b_PCIInputClock == APCI1710_40MHZ)) */
 				else {
 		    /*****************************************/
 					/* The selected PCI input clock is wrong */
@@ -2504,7 +2504,7 @@
 
 					DPRINTK("The selected PCI input clock is wrong\n");
 					i_ReturnValue = 4;
-				}	// if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ) || (b_PCIInputClock == APCI1710_40MHZ))
+				}	/*  if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ) || (b_PCIInputClock == APCI1710_40MHZ)) */
 			} else {
 		 /**************************************/
 				/* The module is not a counter module */
@@ -2530,23 +2530,23 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : _INT_ i_APCI1710_LatchCounter (BYTE_ b_BoardHandle,    |
-|                                                    BYTE_ b_ModulNbr,       |
-|                                                    BYTE_ b_LatchReg)       |
+| Function Name     : _INT_ i_APCI1710_LatchCounter (unsigned char_ b_BoardHandle,    |
+|                                                    unsigned char_ b_ModulNbr,       |
+|                                                    unsigned char_ b_LatchReg)       |
 +----------------------------------------------------------------------------+
 | Task              : Latch the courant value from selected module           |
 |                     (b_ModulNbr) in to the selected latch register         |
 |                     (b_LatchReg).                                          |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle : Handle of board APCI-1710        |
-|                     BYTE_ b_ModulNbr    : Module number to configure       |
+| Input Parameters  : unsigned char_ b_BoardHandle : Handle of board APCI-1710        |
+|                     unsigned char_ b_ModulNbr    : Module number to configure       |
 |                                           (0 to 3)                         |
-|                     BYTE_ b_LatchReg    : Selected latch register          |
+|                     unsigned char_ b_LatchReg    : Selected latch register          |
 |                               0 : for the first latch register             |
 |                               1 : for the second latch register            |
 +----------------------------------------------------------------------------+
@@ -2561,10 +2561,10 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_LatchCounter(struct comedi_device * dev,
-	BYTE b_ModulNbr, BYTE b_LatchReg)
+int i_APCI1710_LatchCounter(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char b_LatchReg)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -2616,25 +2616,25 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_	i_APCI1710_SetIndexAndReferenceSource        |
-|					(BYTE_ b_BoardHandle,                |
-|					 BYTE_ b_ModulNbr,                   |
-|					 BYTE_ b_SourceSelection)            |
+|					(unsigned char_ b_BoardHandle,                |
+|					 unsigned char_ b_ModulNbr,                   |
+|					 unsigned char_ b_SourceSelection)            |
 +----------------------------------------------------------------------------+
 | Task              : Determine the hardware source for the index and the    |
 |		      reference logic. Per default the index logic is        |
 |		      connected to the difference input C and the reference  |
 |		      logic is connected to the 24V input E                  |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
-|		      BYTE_ b_SourceSelection : APCI1710_SOURCE_0 :          |
+|		      unsigned char_ b_SourceSelection : APCI1710_SOURCE_0 :          |
 |						The index logic is connected |
 |						to the difference input C and|
 |						the reference logic is       |
@@ -2658,10 +2658,10 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_SetIndexAndReferenceSource(struct comedi_device * dev,
-	BYTE b_ModulNbr, BYTE b_SourceSelection)
+int i_APCI1710_SetIndexAndReferenceSource(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char b_SourceSelection)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -2735,7 +2735,7 @@
 							b_ModeRegister4 &
 							APCI1710_DEFAULT_INDEX_RFERENCE;
 					}
-				}	// if (b_SourceSelection == APCI1710_SOURCE_0 ||b_SourceSelection == APCI1710_SOURCE_1)
+				}	/*  if (b_SourceSelection == APCI1710_SOURCE_0 ||b_SourceSelection == APCI1710_SOURCE_1) */
 				else {
 		    /*********************************/
 					/* The source selection is wrong */
@@ -2743,7 +2743,7 @@
 
 					DPRINTK("The source selection is wrong\n");
 					i_ReturnValue = -4;
-				}	// if (b_SourceSelection == APCI1710_SOURCE_0 ||b_SourceSelection == APCI1710_SOURCE_1)
+				}	/*  if (b_SourceSelection == APCI1710_SOURCE_0 ||b_SourceSelection == APCI1710_SOURCE_1) */
 			} else {
 		 /**************************************/
 				/* The module is not a counter module */
@@ -2769,20 +2769,20 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_	i_APCI1710_SetDigitalChlOn                   |
-|				   (BYTE_  b_BoardHandle,                    |
-|				    BYTE_  b_ModulNbr)                       |
+|				   (unsigned char_  b_BoardHandle,                    |
+|				    unsigned char_  b_ModulNbr)                       |
 +----------------------------------------------------------------------------+
 | Task              : Sets the digital output H Setting an output means      |
 |		      setting an ouput high.                                 |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_  b_BoardHandle    : Handle of board APCI-1710    |
-|		      BYTE_  b_ModulNbr	      :	Number of the module to be   |
+| Input Parameters  : unsigned char_  b_BoardHandle    : Handle of board APCI-1710    |
+|		      unsigned char_  b_ModulNbr	      :	Number of the module to be   |
 |						configured (0 to 3)          |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -2795,9 +2795,9 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_SetDigitalChlOn(struct comedi_device * dev, BYTE b_ModulNbr)
+int i_APCI1710_SetDigitalChlOn(struct comedi_device *dev, unsigned char b_ModulNbr)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -2849,20 +2849,20 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_	i_APCI1710_SetDigitalChlOff                  |
-|				   (BYTE_  b_BoardHandle,                    |
-|				    BYTE_  b_ModulNbr)                       |
+|				   (unsigned char_  b_BoardHandle,                    |
+|				    unsigned char_  b_ModulNbr)                       |
 +----------------------------------------------------------------------------+
 | Task              : Resets the digital output H. Resetting an output means |
 |		      setting an ouput low.                                  |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_  b_BoardHandle    : Handle of board APCI-1710    |
-|		      BYTE_  b_ModulNbr	      :	Number of the module to be   |
+| Input Parameters  : unsigned char_  b_BoardHandle    : Handle of board APCI-1710    |
+|		      unsigned char_  b_ModulNbr	      :	Number of the module to be   |
 |						configured (0 to 3)          |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -2875,9 +2875,9 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_SetDigitalChlOff(struct comedi_device * dev, BYTE b_ModulNbr)
+int i_APCI1710_SetDigitalChlOff(struct comedi_device *dev, unsigned char b_ModulNbr)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -2929,12 +2929,12 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*########################################################################### */
 
-							// INSN WRITE
+							/*  INSN WRITE */
 /*########################################################################### */
 
 /*
@@ -2951,65 +2951,65 @@
 | Return Value      :
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1710_InsnWriteINCCPT(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnWriteINCCPT(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_WriteType;
-	INT i_ReturnValue = 0;
+	unsigned int ui_WriteType;
+	int i_ReturnValue = 0;
 
 	ui_WriteType = CR_CHAN(insn->chanspec);
-	devpriv->tsk_Current = current;	// Save the current process task structure
+	devpriv->tsk_Current = current;	/*  Save the current process task structure */
 
 	switch (ui_WriteType) {
 	case APCI1710_INCCPT_ENABLELATCHINTERRUPT:
 		i_ReturnValue = i_APCI1710_EnableLatchInterrupt(dev,
-			(BYTE) CR_AREF(insn->chanspec));
+			(unsigned char) CR_AREF(insn->chanspec));
 		break;
 
 	case APCI1710_INCCPT_DISABLELATCHINTERRUPT:
 		i_ReturnValue = i_APCI1710_DisableLatchInterrupt(dev,
-			(BYTE) CR_AREF(insn->chanspec));
+			(unsigned char) CR_AREF(insn->chanspec));
 		break;
 
 	case APCI1710_INCCPT_WRITE16BITCOUNTERVALUE:
 		i_ReturnValue = i_APCI1710_Write16BitCounterValue(dev,
-			(BYTE) CR_AREF(insn->chanspec),
-			(BYTE) data[0], (UINT) data[1]);
+			(unsigned char) CR_AREF(insn->chanspec),
+			(unsigned char) data[0], (unsigned int) data[1]);
 		break;
 
 	case APCI1710_INCCPT_WRITE32BITCOUNTERVALUE:
 		i_ReturnValue = i_APCI1710_Write32BitCounterValue(dev,
-			(BYTE) CR_AREF(insn->chanspec), (ULONG) data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned int) data[0]);
 
 		break;
 
 	case APCI1710_INCCPT_ENABLEINDEX:
-		i_APCI1710_EnableIndex(dev, (BYTE) CR_AREF(insn->chanspec));
+		i_APCI1710_EnableIndex(dev, (unsigned char) CR_AREF(insn->chanspec));
 		break;
 
 	case APCI1710_INCCPT_DISABLEINDEX:
 		i_ReturnValue = i_APCI1710_DisableIndex(dev,
-			(BYTE) CR_AREF(insn->chanspec));
+			(unsigned char) CR_AREF(insn->chanspec));
 		break;
 
 	case APCI1710_INCCPT_ENABLECOMPARELOGIC:
 		i_ReturnValue = i_APCI1710_EnableCompareLogic(dev,
-			(BYTE) CR_AREF(insn->chanspec));
+			(unsigned char) CR_AREF(insn->chanspec));
 		break;
 
 	case APCI1710_INCCPT_DISABLECOMPARELOGIC:
 		i_ReturnValue = i_APCI1710_DisableCompareLogic(dev,
-			(BYTE) CR_AREF(insn->chanspec));
+			(unsigned char) CR_AREF(insn->chanspec));
 		break;
 
 	case APCI1710_INCCPT_ENABLEFREQUENCYMEASUREMENT:
 		i_ReturnValue = i_APCI1710_EnableFrequencyMeasurement(dev,
-			(BYTE) CR_AREF(insn->chanspec), (BYTE) data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned char) data[0]);
 		break;
 
 	case APCI1710_INCCPT_DISABLEFREQUENCYMEASUREMENT:
 		i_ReturnValue = i_APCI1710_DisableFrequencyMeasurement(dev,
-			(BYTE) CR_AREF(insn->chanspec));
+			(unsigned char) CR_AREF(insn->chanspec));
 		break;
 
 	default:
@@ -3018,21 +3018,21 @@
 
 	if (i_ReturnValue >= 0)
 		i_ReturnValue = insn->n;
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_EnableLatchInterrupt                  |
-|                               (BYTE_ b_BoardHandle,                        |
-|                                BYTE_ b_ModulNbr)                           |
+|                               (unsigned char_ b_BoardHandle,                        |
+|                                unsigned char_ b_ModulNbr)                           |
 +----------------------------------------------------------------------------+
 | Task              : Enable the latch interrupt from selected module        |
 |                     (b_ModulNbr). Each software or hardware latch occur a  |
 |                     interrupt.                                             |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle : Handle of board APCI-1710        |
-|                     BYTE_ b_ModulNbr    : Module number to configure       |
+| Input Parameters  : unsigned char_ b_BoardHandle : Handle of board APCI-1710        |
+|                     unsigned char_ b_ModulNbr    : Module number to configure       |
 |                                           (0 to 3)                         |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -3047,9 +3047,9 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_EnableLatchInterrupt(struct comedi_device * dev, BYTE b_ModulNbr)
+int i_APCI1710_EnableLatchInterrupt(struct comedi_device *dev, unsigned char b_ModulNbr)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -3105,20 +3105,20 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_DisableLatchInterrupt                 |
-|                               (BYTE_ b_BoardHandle,                        |
-|                                BYTE_ b_ModulNbr)                           |
+|                               (unsigned char_ b_BoardHandle,                        |
+|                                unsigned char_ b_ModulNbr)                           |
 +----------------------------------------------------------------------------+
 | Task              : Disable the latch interrupt from selected module       |
 |                     (b_ModulNbr).                                          |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle : Handle of board APCI-1710        |
-|                     BYTE_ b_ModulNbr    : Module number to configure       |
+| Input Parameters  : unsigned char_ b_BoardHandle : Handle of board APCI-1710        |
+|                     unsigned char_ b_ModulNbr    : Module number to configure       |
 |                                           (0 to 3)                         |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -3133,9 +3133,9 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_DisableLatchInterrupt(struct comedi_device * dev, BYTE b_ModulNbr)
+int i_APCI1710_DisableLatchInterrupt(struct comedi_device *dev, unsigned char b_ModulNbr)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -3198,27 +3198,27 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_Write16BitCounterValue                |
-|                                               (BYTE_  b_BoardHandle        |
-|                                                BYTE_  b_ModulNbr,          |
-|                                                BYTE_  b_SelectedCounter,   |
-|                                                UINT_ ui_WriteValue)        |
+|                                               (unsigned char_  b_BoardHandle        |
+|                                                unsigned char_  b_ModulNbr,          |
+|                                                unsigned char_  b_SelectedCounter,   |
+|                                                unsigned int_ ui_WriteValue)        |
 +----------------------------------------------------------------------------+
 | Task              : Write a 16-Bit value (ui_WriteValue) in to the selected|
 |                     16-Bit counter (b_SelectedCounter) from selected module|
 |                     (b_ModulNbr).                                          |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                              (0 to 3)                      |
-|                     BYTE_ b_SelectedCounter : Selected 16-Bit counter      |
+|                     unsigned char_ b_SelectedCounter : Selected 16-Bit counter      |
 |                                               (0 or 1)                     |
-|                     UINT_ ui_WriteValue     : 16-Bit write value           |
+|                     unsigned int_ ui_WriteValue     : 16-Bit write value           |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -3231,10 +3231,10 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_Write16BitCounterValue(struct comedi_device * dev,
-	BYTE b_ModulNbr, BYTE b_SelectedCounter, UINT ui_WriteValue)
+int i_APCI1710_Write16BitCounterValue(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char b_SelectedCounter, unsigned int ui_WriteValue)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -3257,7 +3257,7 @@
 				/* Write the value */
 		 /*******************/
 
-				outl((ULONG) ((ULONG) (ui_WriteValue) << (16 *
+				outl((unsigned int) ((unsigned int) (ui_WriteValue) << (16 *
 							b_SelectedCounter)),
 					devpriv->s_BoardInfos.ui_Address + 8 +
 					(b_SelectedCounter * 4) +
@@ -3288,21 +3288,21 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_Write32BitCounterValue                |
-|                                               (BYTE_   b_BoardHandle       |
-|                                                BYTE_   b_ModulNbr,         |
+|                                               (unsigned char_   b_BoardHandle       |
+|                                                unsigned char_   b_ModulNbr,         |
 |                                                ULONG_ ul_WriteValue)       |
 +----------------------------------------------------------------------------+
 | Task              : Write a 32-Bit value (ui_WriteValue) in to the selected|
 |                     module (b_ModulNbr).                                   |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                              (0 to 3)                      |
 |                     ULONG_ ul_WriteValue    : 32-Bit write value           |
 +----------------------------------------------------------------------------+
@@ -3316,10 +3316,10 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_Write32BitCounterValue(struct comedi_device * dev,
-	BYTE b_ModulNbr, ULONG ul_WriteValue)
+int i_APCI1710_Write32BitCounterValue(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned int ul_WriteValue)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -3357,18 +3357,18 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : _INT_ i_APCI1710_EnableIndex (BYTE_  b_BoardHandle,    |
-|                                                   BYTE_  b_ModulNbr)       |
+| Function Name     : _INT_ i_APCI1710_EnableIndex (unsigned char_  b_BoardHandle,    |
+|                                                   unsigned char_  b_ModulNbr)       |
 +----------------------------------------------------------------------------+
 | Task              : Enable the INDEX actions                               |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -3383,10 +3383,10 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_EnableIndex(struct comedi_device * dev, BYTE b_ModulNbr)
+int i_APCI1710_EnableIndex(struct comedi_device *dev, unsigned char b_ModulNbr)
 {
-	INT i_ReturnValue = 0;
-	ULONG ul_InterruptLatchReg;
+	int i_ReturnValue = 0;
+	unsigned int ul_InterruptLatchReg;
 
 	/**************************/
 	/* Test the module number */
@@ -3455,18 +3455,18 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : _INT_ i_APCI1710_DisableIndex (BYTE_  b_BoardHandle,   |
-|                                                    BYTE_  b_ModulNbr)      |
+| Function Name     : _INT_ i_APCI1710_DisableIndex (unsigned char_  b_BoardHandle,   |
+|                                                    unsigned char_  b_ModulNbr)      |
 +----------------------------------------------------------------------------+
 | Task              : Disable the INDEX actions                              |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -3481,9 +3481,9 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_DisableIndex(struct comedi_device * dev, BYTE b_ModulNbr)
+int i_APCI1710_DisableIndex(struct comedi_device *dev, unsigned char b_ModulNbr)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -3549,21 +3549,21 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_EnableCompareLogic                    |
-|                               (BYTE_   b_BoardHandle,                      |
-|                                BYTE_   b_ModulNbr)                         |
+|                               (unsigned char_   b_BoardHandle,                      |
+|                                unsigned char_   b_ModulNbr)                         |
 +----------------------------------------------------------------------------+
 | Task              : Enable the 32-Bit compare logic. At that moment that   |
 |                     the incremental counter arrive to the compare value a  |
 |                     interrupt is generated.                                |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_  b_BoardHandle    : Handle of board APCI-1710    |
-|                     BYTE_  b_ModulNbr       : Module number to configure   |
+| Input Parameters  : unsigned char_  b_BoardHandle    : Handle of board APCI-1710    |
+|                     unsigned char_  b_ModulNbr       : Module number to configure   |
 |                                               (0 to 3)                     |
 +----------------------------------------------------------------------------+
 | Output Parameters : -
@@ -3580,9 +3580,9 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_EnableCompareLogic(struct comedi_device * dev, BYTE b_ModulNbr)
+int i_APCI1710_EnableCompareLogic(struct comedi_device *dev, unsigned char b_ModulNbr)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -3653,19 +3653,19 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_DisableCompareLogic                   |
-|                               (BYTE_   b_BoardHandle,                      |
-|                                BYTE_   b_ModulNbr)                         |
+|                               (unsigned char_   b_BoardHandle,                      |
+|                                unsigned char_   b_ModulNbr)                         |
 +----------------------------------------------------------------------------+
 | Task              : Disable the 32-Bit compare logic.
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_  b_BoardHandle    : Handle of board APCI-1710    |
-|                     BYTE_  b_ModulNbr       : Module number to configure   |
+| Input Parameters  : unsigned char_  b_BoardHandle    : Handle of board APCI-1710    |
+|                     unsigned char_  b_ModulNbr       : Module number to configure   |
 |                                               (0 to 3)                     |
 +----------------------------------------------------------------------------+
 | Output Parameters : -
@@ -3680,9 +3680,9 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_DisableCompareLogic(struct comedi_device * dev, BYTE b_ModulNbr)
+int i_APCI1710_DisableCompareLogic(struct comedi_device *dev, unsigned char b_ModulNbr)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -3753,22 +3753,22 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 	/*
 	   +----------------------------------------------------------------------------+
 	   | Function Name     : _INT_ i_APCI1710_EnableFrequencyMeasurement            |
-	   |                            (BYTE_   b_BoardHandle,                      |
-	   |                             BYTE_   b_ModulNbr,                         |
-	   |                             BYTE_   b_InterruptEnable)                  |
+	   |                            (unsigned char_   b_BoardHandle,                      |
+	   |                             unsigned char_   b_ModulNbr,                         |
+	   |                             unsigned char_   b_InterruptEnable)                  |
 	   +----------------------------------------------------------------------------+
 	   | Task              : Enables the frequency measurement function             |
 	   +----------------------------------------------------------------------------+
-	   | Input Parameters  : BYTE_  b_BoardHandle    : Handle of board APCI-1710    |
-	   |                  BYTE_  b_ModulNbr       : Number of the module to be   |
+	   | Input Parameters  : unsigned char_  b_BoardHandle    : Handle of board APCI-1710    |
+	   |                  unsigned char_  b_ModulNbr       : Number of the module to be   |
 	   |                                            configured (0 to 3)          |
-	   |                  BYTE_  b_InterruptEnable: Enable or disable the        |
+	   |                  unsigned char_  b_InterruptEnable: Enable or disable the        |
 	   |                                            interrupt.                   |
 	   |                                            APCI1710_ENABLE:             |
 	   |                                            Enable the interrupt         |
@@ -3789,10 +3789,10 @@
 	   +----------------------------------------------------------------------------+
 	 */
 
-INT i_APCI1710_EnableFrequencyMeasurement(struct comedi_device * dev,
-	BYTE b_ModulNbr, BYTE b_InterruptEnable)
+int i_APCI1710_EnableFrequencyMeasurement(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char b_InterruptEnable)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -3909,19 +3909,19 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 	/*
 	   +----------------------------------------------------------------------------+
 	   | Function Name     : _INT_ i_APCI1710_DisableFrequencyMeasurement           |
-	   |                            (BYTE_   b_BoardHandle,                      |
-	   |                             BYTE_   b_ModulNbr)                         |
+	   |                            (unsigned char_   b_BoardHandle,                      |
+	   |                             unsigned char_   b_ModulNbr)                         |
 	   +----------------------------------------------------------------------------+
 	   | Task              : Disables the frequency measurement function             |
 	   +----------------------------------------------------------------------------+
-	   | Input Parameters  : BYTE_  b_BoardHandle    : Handle of board APCI-1710    |
-	   |                  BYTE_  b_ModulNbr       : Number of the module to be   |
+	   | Input Parameters  : unsigned char_  b_BoardHandle    : Handle of board APCI-1710    |
+	   |                  unsigned char_  b_ModulNbr       : Number of the module to be   |
 	   |                                            configured (0 to 3)          |
 	   +----------------------------------------------------------------------------+
 	   | Output Parameters : -                                                      |
@@ -3936,9 +3936,9 @@
 	   +----------------------------------------------------------------------------+
 	 */
 
-INT i_APCI1710_DisableFrequencyMeasurement(struct comedi_device * dev, BYTE b_ModulNbr)
+int i_APCI1710_DisableFrequencyMeasurement(struct comedi_device *dev, unsigned char b_ModulNbr)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -3976,9 +3976,9 @@
 					s_ByteModeRegister.
 					b_ModeRegister3 &
 					APCI1710_DISABLE_FREQUENCY
-					// Begin CG 29/06/01 CG 1100/0231 -> 0701/0232 Frequence measure IRQ must be cleared
+					/*  Begin CG 29/06/01 CG 1100/0231 -> 0701/0232 Frequence measure IRQ must be cleared */
 					& APCI1710_DISABLE_FREQUENCY_INT;
-				// End CG 29/06/01 CG 1100/0231 -> 0701/0232 Frequence measure IRQ must be cleared
+				/*  End CG 29/06/01 CG 1100/0231 -> 0701/0232 Frequence measure IRQ must be cleared */
 
 		 /***************************/
 				/* Write the configuration */
@@ -4026,12 +4026,12 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*########################################################################### */
 
-							// INSN READ
+							/*  INSN READ */
 
 /*########################################################################### */
 
@@ -4049,82 +4049,82 @@
 | Return Value      :
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1710_InsnReadINCCPT(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnReadINCCPT(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_ReadType;
-	INT i_ReturnValue = 0;
+	unsigned int ui_ReadType;
+	int i_ReturnValue = 0;
 
 	ui_ReadType = CR_CHAN(insn->chanspec);
 
-	devpriv->tsk_Current = current;	// Save the current process task structure
+	devpriv->tsk_Current = current;	/*  Save the current process task structure */
 	switch (ui_ReadType) {
 	case APCI1710_INCCPT_READLATCHREGISTERSTATUS:
 		i_ReturnValue = i_APCI1710_ReadLatchRegisterStatus(dev,
-			(BYTE) CR_AREF(insn->chanspec),
-			(BYTE) CR_RANGE(insn->chanspec), (PBYTE) & data[0]);
+			(unsigned char) CR_AREF(insn->chanspec),
+			(unsigned char) CR_RANGE(insn->chanspec), (unsigned char *) &data[0]);
 		break;
 
 	case APCI1710_INCCPT_READLATCHREGISTERVALUE:
 		i_ReturnValue = i_APCI1710_ReadLatchRegisterValue(dev,
-			(BYTE) CR_AREF(insn->chanspec),
-			(BYTE) CR_RANGE(insn->chanspec), (PULONG) & data[0]);
+			(unsigned char) CR_AREF(insn->chanspec),
+			(unsigned char) CR_RANGE(insn->chanspec), (unsigned int *) &data[0]);
 		printk("Latch Register Value %d\n", data[0]);
 		break;
 
 	case APCI1710_INCCPT_READ16BITCOUNTERVALUE:
 		i_ReturnValue = i_APCI1710_Read16BitCounterValue(dev,
-			(BYTE) CR_AREF(insn->chanspec),
-			(BYTE) CR_RANGE(insn->chanspec), (PUINT) & data[0]);
+			(unsigned char) CR_AREF(insn->chanspec),
+			(unsigned char) CR_RANGE(insn->chanspec), (unsigned int *) &data[0]);
 		break;
 
 	case APCI1710_INCCPT_READ32BITCOUNTERVALUE:
 		i_ReturnValue = i_APCI1710_Read32BitCounterValue(dev,
-			(BYTE) CR_AREF(insn->chanspec), (PULONG) & data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned int *) &data[0]);
 		break;
 
 	case APCI1710_INCCPT_GETINDEXSTATUS:
 		i_ReturnValue = i_APCI1710_GetIndexStatus(dev,
-			(BYTE) CR_AREF(insn->chanspec), (PBYTE) & data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned char *) &data[0]);
 		break;
 
 	case APCI1710_INCCPT_GETREFERENCESTATUS:
 		i_ReturnValue = i_APCI1710_GetReferenceStatus(dev,
-			(BYTE) CR_AREF(insn->chanspec), (PBYTE) & data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned char *) &data[0]);
 		break;
 
 	case APCI1710_INCCPT_GETUASSTATUS:
 		i_ReturnValue = i_APCI1710_GetUASStatus(dev,
-			(BYTE) CR_AREF(insn->chanspec), (PBYTE) & data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned char *) &data[0]);
 		break;
 
 	case APCI1710_INCCPT_GETCBSTATUS:
 		i_ReturnValue = i_APCI1710_GetCBStatus(dev,
-			(BYTE) CR_AREF(insn->chanspec), (PBYTE) & data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned char *) &data[0]);
 		break;
 
 	case APCI1710_INCCPT_GET16BITCBSTATUS:
 		i_ReturnValue = i_APCI1710_Get16BitCBStatus(dev,
-			(BYTE) CR_AREF(insn->chanspec),
-			(PBYTE) & data[0], (PBYTE) & data[1]);
+			(unsigned char) CR_AREF(insn->chanspec),
+			(unsigned char *) &data[0], (unsigned char *) &data[1]);
 		break;
 
 	case APCI1710_INCCPT_GETUDSTATUS:
 		i_ReturnValue = i_APCI1710_GetUDStatus(dev,
-			(BYTE) CR_AREF(insn->chanspec), (PBYTE) & data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned char *) &data[0]);
 
 		break;
 
 	case APCI1710_INCCPT_GETINTERRUPTUDLATCHEDSTATUS:
 		i_ReturnValue = i_APCI1710_GetInterruptUDLatchedStatus(dev,
-			(BYTE) CR_AREF(insn->chanspec), (PBYTE) & data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned char *) &data[0]);
 		break;
 
 	case APCI1710_INCCPT_READFREQUENCYMEASUREMENT:
 		i_ReturnValue = i_APCI1710_ReadFrequencyMeasurement(dev,
-			(BYTE) CR_AREF(insn->chanspec),
-			(PBYTE) & data[0],
-			(PBYTE) & data[1], (PULONG) & data[2]);
+			(unsigned char) CR_AREF(insn->chanspec),
+			(unsigned char *) &data[0],
+			(unsigned char *) &data[1], (unsigned int *) &data[2]);
 		break;
 
 	case APCI1710_INCCPT_READINTERRUPT:
@@ -4155,29 +4155,29 @@
 
 	if (i_ReturnValue >= 0)
 		i_ReturnValue = insn->n;
-	return (i_ReturnValue);
+	return i_ReturnValue;
 
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_ReadLatchRegisterStatus               |
-|                                                   (BYTE_   b_BoardHandle,  |
-|                                                    BYTE_   b_ModulNbr,     |
-|                                                    BYTE_   b_LatchReg,     |
-|                                                    PBYTE_ pb_LatchStatus)  |
+|                                                   (unsigned char_   b_BoardHandle,  |
+|                                                    unsigned char_   b_ModulNbr,     |
+|                                                    unsigned char_   b_LatchReg,     |
+|                                                    unsigned char *_ pb_LatchStatus)  |
 +----------------------------------------------------------------------------+
 | Task              : Read the latch register status from selected module    |
 |                     (b_ModulNbr) and selected latch register (b_LatchReg). |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle : Handle of board APCI-1710        |
-|                     BYTE_ b_ModulNbr    : Module number to configure       |
+| Input Parameters  : unsigned char_ b_BoardHandle : Handle of board APCI-1710        |
+|                     unsigned char_ b_ModulNbr    : Module number to configure       |
 |                                           (0 to 3)                         |
-|                     BYTE_ b_LatchReg    : Selected latch register          |
+|                     unsigned char_ b_LatchReg    : Selected latch register          |
 |                               0 : for the first latch register             |
 |                               1 : for the second latch register            |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_LatchStatus :   Latch register status.       |
+| Output Parameters : unsigned char *_ pb_LatchStatus :   Latch register status.       |
 |                                               0 : No latch occur           |
 |                                               1 : A software latch occur   |
 |                                               2 : A hardware latch occur   |
@@ -4193,11 +4193,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_ReadLatchRegisterStatus(struct comedi_device * dev,
-	BYTE b_ModulNbr, BYTE b_LatchReg, PBYTE pb_LatchStatus)
+int i_APCI1710_ReadLatchRegisterStatus(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char b_LatchReg, unsigned char *pb_LatchStatus)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_LatchReg;
+	int i_ReturnValue = 0;
+	unsigned int dw_LatchReg;
 
 	/**************************/
 	/* Test the module number */
@@ -4220,7 +4220,7 @@
 					ui_Address + (64 * b_ModulNbr));
 
 				*pb_LatchStatus =
-					(BYTE) ((dw_LatchReg >> (b_LatchReg *
+					(unsigned char) ((dw_LatchReg >> (b_LatchReg *
 							4)) & 0x3);
 			} else {
 		 /**************************************************/
@@ -4248,24 +4248,24 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_ReadLatchRegisterValue                |
-|                                                   (BYTE_     b_BoardHandle,|
-|                                                    BYTE_     b_ModulNbr,   |
-|                                                    BYTE_     b_LatchReg,   |
+|                                                   (unsigned char_     b_BoardHandle,|
+|                                                    unsigned char_     b_ModulNbr,   |
+|                                                    unsigned char_     b_LatchReg,   |
 |                                                    PULONG_ pul_LatchValue) |
 +----------------------------------------------------------------------------+
 | Task              : Read the latch register value from selected module     |
 |                     (b_ModulNbr) and selected latch register (b_LatchReg). |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle : Handle of board APCI-1710        |
-|                     BYTE_ b_ModulNbr    : Module number to configure       |
+| Input Parameters  : unsigned char_ b_BoardHandle : Handle of board APCI-1710        |
+|                     unsigned char_ b_ModulNbr    : Module number to configure       |
 |                                           (0 to 3)                         |
-|                     BYTE_ b_LatchReg    : Selected latch register          |
+|                     unsigned char_ b_LatchReg    : Selected latch register          |
 |                               0 : for the first latch register             |
 |                               1 : for the second latch register            |
 +----------------------------------------------------------------------------+
@@ -4280,10 +4280,10 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_ReadLatchRegisterValue(struct comedi_device * dev,
-	BYTE b_ModulNbr, BYTE b_LatchReg, PULONG pul_LatchValue)
+int i_APCI1710_ReadLatchRegisterValue(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char b_LatchReg, unsigned int *pul_LatchValue)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -4332,28 +4332,28 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_Read16BitCounterValue                 |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
-|                                        BYTE_     b_SelectedCounter,        |
-|                                        PUINT_   pui_CounterValue)          |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
+|                                        unsigned char_     b_SelectedCounter,        |
+|                                        unsigned int *_   pui_CounterValue)          |
 +----------------------------------------------------------------------------+
 | Task              : Latch the selected 16-Bit counter (b_SelectedCounter)  |
 |                     from selected module (b_ModulNbr) in to the first      |
 |                     latch register and return the latched value.           |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                              (0 to 3)                      |
-|                     BYTE_ b_SelectedCounter : Selected 16-Bit counter      |
+|                     unsigned char_ b_SelectedCounter : Selected 16-Bit counter      |
 |                                               (0 or 1)                     |
 +----------------------------------------------------------------------------+
-| Output Parameters : PUINT_ pui_CounterValue : 16-Bit counter value         |
+| Output Parameters : unsigned int *_ pui_CounterValue : 16-Bit counter value         |
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
 |                     -1: The handle parameter of the board is wrong         |
@@ -4364,11 +4364,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_Read16BitCounterValue(struct comedi_device * dev,
-	BYTE b_ModulNbr, BYTE b_SelectedCounter, PUINT pui_CounterValue)
+int i_APCI1710_Read16BitCounterValue(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char b_SelectedCounter, unsigned int *pui_CounterValue)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_LathchValue = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_LathchValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -4402,7 +4402,7 @@
 					ui_Address + 4 + (64 * b_ModulNbr));
 
 				*pui_CounterValue =
-					(UINT) ((dw_LathchValue >> (16 *
+					(unsigned int) ((dw_LathchValue >> (16 *
 							b_SelectedCounter)) &
 					0xFFFFU);
 			} else {
@@ -4431,22 +4431,22 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_Read32BitCounterValue                 |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
 |                                        PULONG_ pul_CounterValue)           |
 +----------------------------------------------------------------------------+
 | Task              : Latch the 32-Bit counter from selected module          |
 |                     (b_ModulNbr) in to the first latch register and return |
 |                     the latched value.                                     |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                              (0 to 3)                      |
 +----------------------------------------------------------------------------+
 | Output Parameters : PULONG_  pul_CounterValue : 32-Bit counter value       |
@@ -4459,10 +4459,10 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_Read32BitCounterValue(struct comedi_device * dev,
-	BYTE b_ModulNbr, PULONG pul_CounterValue)
+int i_APCI1710_Read32BitCounterValue(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned int *pul_CounterValue)
 {
-	INT i_ReturnValue = 0;
+	int i_ReturnValue = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -4507,22 +4507,22 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : _INT_ i_APCI1710_GetIndexStatus (BYTE_   b_BoardHandle,|
-|                                                      BYTE_   b_ModulNbr,   |
-|                                                      PBYTE_ pb_IndexStatus)|
+| Function Name     : _INT_ i_APCI1710_GetIndexStatus (unsigned char_   b_BoardHandle,|
+|                                                      unsigned char_   b_ModulNbr,   |
+|                                                      unsigned char *_ pb_IndexStatus)|
 +----------------------------------------------------------------------------+
 | Task              : Return the index status                                |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_IndexStatus   : 0 : No INDEX occur           |
+| Output Parameters : unsigned char *_ pb_IndexStatus   : 0 : No INDEX occur           |
 |                                               1 : A INDEX occur            |
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
@@ -4535,11 +4535,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_GetIndexStatus(struct comedi_device * dev,
-	BYTE b_ModulNbr, PBYTE pb_IndexStatus)
+int i_APCI1710_GetIndexStatus(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char *pb_IndexStatus)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -4563,7 +4563,7 @@
 				dw_StatusReg = inl(devpriv->s_BoardInfos.
 					ui_Address + 12 + (64 * b_ModulNbr));
 
-				*pb_IndexStatus = (BYTE) (dw_StatusReg & 1);
+				*pb_IndexStatus = (unsigned char) (dw_StatusReg & 1);
 			} else {
 		 /*************************************************************/
 				/* Index not initialised see function "i_APCI1710_InitIndex" */
@@ -4590,23 +4590,23 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_GetReferenceStatus                    |
-|                                                (BYTE_   b_BoardHandle,     |
-|                                                 BYTE_   b_ModulNbr,        |
-|                                                 PBYTE_ pb_ReferenceStatus) |
+|                                                (unsigned char_   b_BoardHandle,     |
+|                                                 unsigned char_   b_ModulNbr,        |
+|                                                 unsigned char *_ pb_ReferenceStatus) |
 +----------------------------------------------------------------------------+
 | Task              : Return the reference status                            |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_ReferenceStatus   : 0 : No REFERENCE occur   |
+| Output Parameters : unsigned char *_ pb_ReferenceStatus   : 0 : No REFERENCE occur   |
 |                                                   1 : A REFERENCE occur    |
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
@@ -4619,11 +4619,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_GetReferenceStatus(struct comedi_device * dev,
-	BYTE b_ModulNbr, PBYTE pb_ReferenceStatus)
+int i_APCI1710_GetReferenceStatus(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char *pb_ReferenceStatus)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -4649,7 +4649,7 @@
 					ui_Address + 24 + (64 * b_ModulNbr));
 
 				*pb_ReferenceStatus =
-					(BYTE) (~dw_StatusReg & 1);
+					(unsigned char) (~dw_StatusReg & 1);
 			} else {
 		 /*********************************************************************/
 				/* Reference not initialised see function "i_APCI1710_InitReference" */
@@ -4676,23 +4676,23 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_GetUASStatus                          |
-|                               (BYTE_   b_BoardHandle,                      |
-|                                BYTE_   b_ModulNbr,                         |
-|                                PBYTE_ pb_UASStatus)                        |
+|                               (unsigned char_   b_BoardHandle,                      |
+|                                unsigned char_   b_ModulNbr,                         |
+|                                unsigned char *_ pb_UASStatus)                        |
 +----------------------------------------------------------------------------+
 | Task              : Return the error signal (UAS) status                   |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_UASStatus      : 0 : UAS is low "0"          |
+| Output Parameters : unsigned char *_ pb_UASStatus      : 0 : UAS is low "0"          |
 |                                                1 : UAS is high "1"         |
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
@@ -4703,11 +4703,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_GetUASStatus(struct comedi_device * dev,
-	BYTE b_ModulNbr, PBYTE pb_UASStatus)
+int i_APCI1710_GetUASStatus(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char *pb_UASStatus)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -4724,7 +4724,7 @@
 			dw_StatusReg = inl(devpriv->s_BoardInfos.
 				ui_Address + 24 + (64 * b_ModulNbr));
 
-			*pb_UASStatus = (BYTE) ((dw_StatusReg >> 1) & 1);
+			*pb_UASStatus = (unsigned char) ((dw_StatusReg >> 1) & 1);
 		} else {
 	      /****************************************/
 			/* Counter not initialised see function */
@@ -4744,23 +4744,23 @@
 
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_GetCBStatus                           |
-|                               (BYTE_   b_BoardHandle,                      |
-|                                BYTE_   b_ModulNbr,                         |
-|                                PBYTE_ pb_CBStatus)                         |
+|                               (unsigned char_   b_BoardHandle,                      |
+|                                unsigned char_   b_ModulNbr,                         |
+|                                unsigned char *_ pb_CBStatus)                         |
 +----------------------------------------------------------------------------+
 | Task              : Return the counter overflow status                     |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_CBStatus      : 0 : Counter no overflow      |
+| Output Parameters : unsigned char *_ pb_CBStatus      : 0 : Counter no overflow      |
 |                                               1 : Counter overflow         |
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
@@ -4771,11 +4771,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_GetCBStatus(struct comedi_device * dev,
-	BYTE b_ModulNbr, PBYTE pb_CBStatus)
+int i_APCI1710_GetCBStatus(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char *pb_CBStatus)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -4792,7 +4792,7 @@
 			dw_StatusReg = inl(devpriv->s_BoardInfos.
 				ui_Address + 16 + (64 * b_ModulNbr));
 
-			*pb_CBStatus = (BYTE) (dw_StatusReg & 1);
+			*pb_CBStatus = (unsigned char) (dw_StatusReg & 1);
 
 		} else {
 	      /****************************************/
@@ -4812,31 +4812,31 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_Get16BitCBStatus                      |
-|					(BYTE_     b_BoardHandle,            |
-|					 BYTE_     b_ModulNbr,               |
-|					 PBYTE_ pb_CBStatusCounter0,         |
-|					 PBYTE_ pb_CBStatusCounter1)         |
+|					(unsigned char_     b_BoardHandle,            |
+|					 unsigned char_     b_ModulNbr,               |
+|					 unsigned char *_ pb_CBStatusCounter0,         |
+|					 unsigned char *_ pb_CBStatusCounter1)         |
 +----------------------------------------------------------------------------+
 | Task              : Returns the counter overflow (counter initialised to   |
 |		      2*16-bit) status from selected incremental counter     |
 |		      module                                                 |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_CBStatusCounter0 : 0 : No overflow occur for |
+| Output Parameters : unsigned char *_ pb_CBStatusCounter0 : 0 : No overflow occur for |
 |						       the first 16-bit      |
 |						       counter               |
 |						   1 : Overflow occur for the|
 |						       first 16-bit counter  |
-|		      PBYTE_ pb_CBStatusCounter1 : 0 : No overflow occur for |
+|		      unsigned char *_ pb_CBStatusCounter1 : 0 : No overflow occur for |
 |						       the second 16-bit     |
 |						       counter               |
 |						   1 : Overflow occur for the|
@@ -4853,11 +4853,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_Get16BitCBStatus(struct comedi_device * dev,
-	BYTE b_ModulNbr, PBYTE pb_CBStatusCounter0, PBYTE pb_CBStatusCounter1)
+int i_APCI1710_Get16BitCBStatus(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char *pb_CBStatusCounter0, unsigned char *pb_CBStatusCounter1)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -4894,20 +4894,20 @@
 						(64 * b_ModulNbr));
 
 					*pb_CBStatusCounter1 =
-						(BYTE) ((dw_StatusReg >> 0) &
+						(unsigned char) ((dw_StatusReg >> 0) &
 						1);
 					*pb_CBStatusCounter0 =
-						(BYTE) ((dw_StatusReg >> 1) &
+						(unsigned char) ((dw_StatusReg >> 1) &
 						1);
-				}	// if ((ps_APCI1710Variable->s_Board [b_BoardHandle].s_BoardInfos.dw_MolduleConfiguration [b_ModulNbr] & 0xFFFF) >= 0x3136)
+				}	/*  if ((ps_APCI1710Variable->s_Board [b_BoardHandle].s_BoardInfos.dw_MolduleConfiguration [b_ModulNbr] & 0xFFFF) >= 0x3136) */
 				else {
 		    /****************************/
 					/* Firmware revision error  */
 		    /****************************/
 
 					i_ReturnValue = -5;
-				}	// if ((ps_APCI1710Variable->s_Board [b_BoardHandle].s_BoardInfos.dw_MolduleConfiguration [b_ModulNbr] & 0xFFFF) >= 0x3136)
-			}	// if ((ps_APCI1710Variable->s_Board [b_BoardHandle].s_ModuleInfo [b_ModulNbr].s_SiemensCounterInfo.s_ModeRegister.s_ByteModeRegister.b_ModeRegister1 & 0x10) == 0x10)
+				}	/*  if ((ps_APCI1710Variable->s_Board [b_BoardHandle].s_BoardInfos.dw_MolduleConfiguration [b_ModulNbr] & 0xFFFF) >= 0x3136) */
+			}	/*  if ((ps_APCI1710Variable->s_Board [b_BoardHandle].s_ModuleInfo [b_ModulNbr].s_SiemensCounterInfo.s_ModeRegister.s_ByteModeRegister.b_ModeRegister1 & 0x10) == 0x10) */
 			else {
 		 /********************************************/
 				/* Counter not initialised to 2*16-bit mode */
@@ -4916,8 +4916,8 @@
 
 				DPRINTK("Counter not initialised\n");
 				i_ReturnValue = -4;
-			}	// if ((ps_APCI1710Variable->s_Board [b_BoardHandle].s_ModuleInfo [b_ModulNbr].s_SiemensCounterInfo.s_ModeRegister.s_ByteModeRegister.b_ModeRegister1 & 0x10) == 0x10)
-		}		// if (ps_APCI1710Variable->s_Board [b_BoardHandle].s_ModuleInfo [b_ModulNbr].s_SiemensCounterInfo.s_InitFlag.b_CounterInit == 1)
+			}	/*  if ((ps_APCI1710Variable->s_Board [b_BoardHandle].s_ModuleInfo [b_ModulNbr].s_SiemensCounterInfo.s_ModeRegister.s_ByteModeRegister.b_ModeRegister1 & 0x10) == 0x10) */
+		}		/*  if (ps_APCI1710Variable->s_Board [b_BoardHandle].s_ModuleInfo [b_ModulNbr].s_SiemensCounterInfo.s_InitFlag.b_CounterInit == 1) */
 		else {
 	      /****************************************/
 			/* Counter not initialised see function */
@@ -4926,8 +4926,8 @@
 
 			DPRINTK("Counter not initialised\n");
 			i_ReturnValue = -3;
-		}		// if (ps_APCI1710Variable->s_Board [b_BoardHandle].s_ModuleInfo [b_ModulNbr].s_SiemensCounterInfo.s_InitFlag.b_CounterInit == 1)
-	}			// if (b_ModulNbr < 4)
+		}		/*  if (ps_APCI1710Variable->s_Board [b_BoardHandle].s_ModuleInfo [b_ModulNbr].s_SiemensCounterInfo.s_InitFlag.b_CounterInit == 1) */
+	}			/*  if (b_ModulNbr < 4) */
 	else {
 	   /*************************************************/
 		/* The selected module number parameter is wrong */
@@ -4935,25 +4935,25 @@
 
 		DPRINTK("The selected module number parameter is wrong\n");
 		i_ReturnValue = -2;
-	}			// if (b_ModulNbr < 4)
+	}			/*  if (b_ModulNbr < 4) */
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_GetUDStatus                           |
-|                               (BYTE_   b_BoardHandle,                      |
-|                                BYTE_   b_ModulNbr,                         |
-|                                PBYTE_ pb_UDStatus)                         |
+|                               (unsigned char_   b_BoardHandle,                      |
+|                                unsigned char_   b_ModulNbr,                         |
+|                                unsigned char *_ pb_UDStatus)                         |
 +----------------------------------------------------------------------------+
 | Task              : Return the counter progress status                     |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_UDStatus      : 0 : Counter progress in the  |
+| Output Parameters : unsigned char *_ pb_UDStatus      : 0 : Counter progress in the  |
 |                                                   selected mode down       |
 |                                               1 : Counter progress in the  |
 |                                                   selected mode up         |
@@ -4966,11 +4966,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_GetUDStatus(struct comedi_device * dev,
-	BYTE b_ModulNbr, PBYTE pb_UDStatus)
+int i_APCI1710_GetUDStatus(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char *pb_UDStatus)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -4987,7 +4987,7 @@
 			dw_StatusReg = inl(devpriv->s_BoardInfos.
 				ui_Address + 24 + (64 * b_ModulNbr));
 
-			*pb_UDStatus = (BYTE) ((dw_StatusReg >> 2) & 1);
+			*pb_UDStatus = (unsigned char) ((dw_StatusReg >> 2) & 1);
 
 		} else {
 	      /****************************************/
@@ -5007,24 +5007,24 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_GetInterruptUDLatchedStatus           |
-|                               (BYTE_   b_BoardHandle,                      |
-|                                BYTE_   b_ModulNbr,                         |
-|                                PBYTE_ pb_UDStatus)                         |
+|                               (unsigned char_   b_BoardHandle,                      |
+|                                unsigned char_   b_ModulNbr,                         |
+|                                unsigned char *_ pb_UDStatus)                         |
 +----------------------------------------------------------------------------+
 | Task              : Return the counter progress latched status after a     |
 |                     index interrupt occur.                                 |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Module number to configure   |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Module number to configure   |
 |                                               (0 to 3)                     |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_UDStatus      : 0 : Counter progress in the  |
+| Output Parameters : unsigned char *_ pb_UDStatus      : 0 : Counter progress in the  |
 |                                                   selected mode down       |
 |                                               1 : Counter progress in the  |
 |                                                   selected mode up         |
@@ -5040,11 +5040,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_GetInterruptUDLatchedStatus(struct comedi_device * dev,
-	BYTE b_ModulNbr, PBYTE pb_UDStatus)
+int i_APCI1710_GetInterruptUDLatchedStatus(struct comedi_device *dev,
+	unsigned char b_ModulNbr, unsigned char *pb_UDStatus)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg = 0;
 
 	/**************************/
 	/* Test the module number */
@@ -5074,7 +5074,7 @@
 				dw_StatusReg = inl(devpriv->s_BoardInfos.
 					ui_Address + 12 + (64 * b_ModulNbr));
 
-				*pb_UDStatus = (BYTE) ((dw_StatusReg >> 1) & 1);
+				*pb_UDStatus = (unsigned char) ((dw_StatusReg >> 1) & 1);
 			} else {
 		    /****************************/
 				/* No index interrupt occur */
@@ -5100,26 +5100,26 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 	/*
 	   +----------------------------------------------------------------------------+
 	   | Function Name     : _INT_ i_APCI1710_ReadFrequencyMeasurement              |
-	   |                            (BYTE_            b_BoardHandle,             |
-	   |                             BYTE_            b_ModulNbr,                |
-	   |                             PBYTE_          pb_Status,                  |
+	   |                            (unsigned char_            b_BoardHandle,             |
+	   |                             unsigned char_            b_ModulNbr,                |
+	   |                             unsigned char *_          pb_Status,                  |
 	   |                             PULONG_        pul_ReadValue)               |
 	   +----------------------------------------------------------------------------+
 	   | Task              : Returns the status (pb_Status) and the number of       |
 	   |                  increments in the set time.                            |
 	   |                  See function " i_APCI1710_InitFrequencyMeasurement "   |
 	   +----------------------------------------------------------------------------+
-	   | Input Parameters  : BYTE_  b_BoardHandle    : Handle of board APCI-1710    |
-	   |                  BYTE_  b_ModulNbr       : Number of the module to be   |
+	   | Input Parameters  : unsigned char_  b_BoardHandle    : Handle of board APCI-1710    |
+	   |                  unsigned char_  b_ModulNbr       : Number of the module to be   |
 	   |                                            configured (0 to 3)          |
 	   +----------------------------------------------------------------------------+
-	   | Output Parameters : PBYTE_ pb_Status     : Returns the frequency        |
+	   | Output Parameters : unsigned char *_ pb_Status     : Returns the frequency        |
 	   |                                            measurement status           |
 	   |                                            0 : Counting cycle not       |
 	   |                                                started.                 |
@@ -5127,7 +5127,7 @@
 	   |                                            2 : Counting cycle stopped.  |
 	   |                                                The measurement cycle is |
 	   |                                                completed.               |
-	   |                  PBYTE_ pb_UDStatus      : 0 : Counter progress in the  |
+	   |                  unsigned char *_ pb_UDStatus      : 0 : Counter progress in the  |
 	   |                                                   selected mode down       |
 	   |                                               1 : Counter progress in the  |
 	   |                                                   selected mode up         |
@@ -5145,13 +5145,13 @@
 	   +----------------------------------------------------------------------------+
 	 */
 
-INT i_APCI1710_ReadFrequencyMeasurement(struct comedi_device * dev,
-	BYTE b_ModulNbr,
-	PBYTE pb_Status, PBYTE pb_UDStatus, PULONG pul_ReadValue)
+int i_APCI1710_ReadFrequencyMeasurement(struct comedi_device *dev,
+	unsigned char b_ModulNbr,
+	unsigned char *pb_Status, unsigned char *pb_UDStatus, unsigned int *pul_ReadValue)
 {
-	INT i_ReturnValue = 0;
-	UINT ui_16BitValue;
-	DWORD dw_StatusReg;
+	int i_ReturnValue = 0;
+	unsigned int ui_16BitValue;
+	unsigned int dw_StatusReg;
 
 	/**************************/
 	/* Test the module number */
@@ -5198,7 +5198,7 @@
 					if (dw_StatusReg & 1) {
 						*pb_Status = 2;
 						*pb_UDStatus =
-							(BYTE) ((dw_StatusReg >>
+							(unsigned char) ((dw_StatusReg >>
 								1) & 3);
 
 		       /******************/
@@ -5224,7 +5224,7 @@
 								if ((*pul_ReadValue & 0xFFFFU) != 0) {
 									ui_16BitValue
 										=
-										(UINT)
+										(unsigned int)
 										*
 										pul_ReadValue
 										&
@@ -5247,7 +5247,7 @@
 								if ((*pul_ReadValue & 0xFFFF0000UL) != 0) {
 									ui_16BitValue
 										=
-										(UINT)
+										(unsigned int)
 										(
 										(*pul_ReadValue
 											>>
@@ -5281,7 +5281,7 @@
 								if ((*pul_ReadValue & 0xFFFF0000UL) != 0) {
 									ui_16BitValue
 										=
-										(UINT)
+										(unsigned int)
 										(
 										(*pul_ReadValue
 											>>
@@ -5307,7 +5307,7 @@
 									if ((*pul_ReadValue & 0xFFFFU) != 0) {
 										ui_16BitValue
 											=
-											(UINT)
+											(unsigned int)
 											*
 											pul_ReadValue
 											&
@@ -5359,5 +5359,5 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_INCCPT.h b/drivers/staging/comedi/drivers/addi-data/APCI1710_INCCPT.h
index 5153cf6..7b48110 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_INCCPT.h
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_INCCPT.h
@@ -132,140 +132,140 @@
 #define APCI1710_INCCPT_DISABLEFREQUENCYMEASUREMENT		409
 
 /************ Main Functions *************/
-INT i_APCI1710_InsnConfigINCCPT(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnConfigINCCPT(struct comedi_device *dev, struct comedi_subdevice *s,
 				struct comedi_insn *insn, unsigned int * data);
 
-INT i_APCI1710_InsnBitsINCCPT(struct comedi_device *dev, struct comedi_subdevice * s,
+int i_APCI1710_InsnBitsINCCPT(struct comedi_device *dev, struct comedi_subdevice * s,
 			      struct comedi_insn *insn, unsigned int * data);
 
-INT i_APCI1710_InsnWriteINCCPT(struct comedi_device *dev, struct comedi_subdevice * s,
+int i_APCI1710_InsnWriteINCCPT(struct comedi_device *dev, struct comedi_subdevice * s,
 			       struct comedi_insn *insn, unsigned int * data);
 
-INT i_APCI1710_InsnReadINCCPT(struct comedi_device *dev, struct comedi_subdevice * s,
+int i_APCI1710_InsnReadINCCPT(struct comedi_device *dev, struct comedi_subdevice * s,
 			      struct comedi_insn *insn, unsigned int * data);
 
 /*********** Supplementary Functions********/
 
 /* INSN CONFIG */
-INT i_APCI1710_InitCounter(struct comedi_device *dev,
-			   BYTE b_ModulNbr,
-			   BYTE b_CounterRange,
-			   BYTE b_FirstCounterModus,
-			   BYTE b_FirstCounterOption,
-			   BYTE b_SecondCounterModus,
-			   BYTE b_SecondCounterOption);
+int i_APCI1710_InitCounter(struct comedi_device *dev,
+			   unsigned char b_ModulNbr,
+			   unsigned char b_CounterRange,
+			   unsigned char b_FirstCounterModus,
+			   unsigned char b_FirstCounterOption,
+			   unsigned char b_SecondCounterModus,
+			   unsigned char b_SecondCounterOption);
 
-INT i_APCI1710_CounterAutoTest(struct comedi_device *dev, PBYTE pb_TestStatus);
+int i_APCI1710_CounterAutoTest(struct comedi_device *dev, unsigned char * pb_TestStatus);
 
-INT i_APCI1710_InitIndex(struct comedi_device *dev,
-			 BYTE b_ModulNbr,
-			 BYTE b_ReferenceAction,
-			 BYTE b_IndexOperation, BYTE b_AutoMode,
-			 BYTE b_InterruptEnable);
+int i_APCI1710_InitIndex(struct comedi_device *dev,
+			 unsigned char b_ModulNbr,
+			 unsigned char b_ReferenceAction,
+			 unsigned char b_IndexOperation, unsigned char b_AutoMode,
+			 unsigned char b_InterruptEnable);
 
-INT i_APCI1710_InitReference(struct comedi_device *dev,
-			     BYTE b_ModulNbr, BYTE b_ReferenceLevel);
+int i_APCI1710_InitReference(struct comedi_device *dev,
+			     unsigned char b_ModulNbr, unsigned char b_ReferenceLevel);
 
-INT i_APCI1710_InitExternalStrobe(struct comedi_device *dev,
-				  BYTE b_ModulNbr, BYTE b_ExternalStrobe,
-				  BYTE b_ExternalStrobeLevel);
+int i_APCI1710_InitExternalStrobe(struct comedi_device *dev,
+				  unsigned char b_ModulNbr, unsigned char b_ExternalStrobe,
+				  unsigned char b_ExternalStrobeLevel);
 
-INT i_APCI1710_InitCompareLogic(struct comedi_device *dev,
-				BYTE b_ModulNbr, UINT ui_CompareValue);
+int i_APCI1710_InitCompareLogic(struct comedi_device *dev,
+				unsigned char b_ModulNbr, unsigned int ui_CompareValue);
 
-INT i_APCI1710_InitFrequencyMeasurement(struct comedi_device *dev,
-					BYTE b_ModulNbr,
-					BYTE b_PCIInputClock,
-					BYTE b_TimingUnity,
-					ULONG ul_TimingInterval,
-					PULONG pul_RealTimingInterval);
+int i_APCI1710_InitFrequencyMeasurement(struct comedi_device *dev,
+					unsigned char b_ModulNbr,
+					unsigned char b_PCIInputClock,
+					unsigned char b_TimingUnity,
+					unsigned int ul_TimingInterval,
+					unsigned int *pul_RealTimingInterval);
 
 /* INSN BITS */
-INT i_APCI1710_ClearCounterValue(struct comedi_device *dev, BYTE b_ModulNbr);
+int i_APCI1710_ClearCounterValue(struct comedi_device *dev, unsigned char b_ModulNbr);
 
-INT i_APCI1710_ClearAllCounterValue(struct comedi_device *dev);
+int i_APCI1710_ClearAllCounterValue(struct comedi_device *dev);
 
-INT i_APCI1710_SetInputFilter(struct comedi_device *dev,
-			      BYTE b_ModulNbr, BYTE b_PCIInputClock,
-			      BYTE b_Filter);
+int i_APCI1710_SetInputFilter(struct comedi_device *dev,
+			      unsigned char b_ModulNbr, unsigned char b_PCIInputClock,
+			      unsigned char b_Filter);
 
-INT i_APCI1710_LatchCounter(struct comedi_device *dev,
-			    BYTE b_ModulNbr, BYTE b_LatchReg);
+int i_APCI1710_LatchCounter(struct comedi_device *dev,
+			    unsigned char b_ModulNbr, unsigned char b_LatchReg);
 
-INT i_APCI1710_SetIndexAndReferenceSource(struct comedi_device *dev,
-					  BYTE b_ModulNbr,
-					  BYTE b_SourceSelection);
+int i_APCI1710_SetIndexAndReferenceSource(struct comedi_device *dev,
+					  unsigned char b_ModulNbr,
+					  unsigned char b_SourceSelection);
 
-INT i_APCI1710_SetDigitalChlOn(struct comedi_device *dev, BYTE b_ModulNbr);
+int i_APCI1710_SetDigitalChlOn(struct comedi_device *dev, unsigned char b_ModulNbr);
 
-INT i_APCI1710_SetDigitalChlOff(struct comedi_device *dev, BYTE b_ModulNbr);
+int i_APCI1710_SetDigitalChlOff(struct comedi_device *dev, unsigned char b_ModulNbr);
 
 /* INSN WRITE */
-INT i_APCI1710_EnableLatchInterrupt(struct comedi_device *dev, BYTE b_ModulNbr);
+int i_APCI1710_EnableLatchInterrupt(struct comedi_device *dev, unsigned char b_ModulNbr);
 
-INT i_APCI1710_DisableLatchInterrupt(struct comedi_device *dev, BYTE b_ModulNbr);
+int i_APCI1710_DisableLatchInterrupt(struct comedi_device *dev, unsigned char b_ModulNbr);
 
-INT i_APCI1710_Write16BitCounterValue(struct comedi_device *dev,
-				      BYTE b_ModulNbr, BYTE b_SelectedCounter,
-				      UINT ui_WriteValue);
+int i_APCI1710_Write16BitCounterValue(struct comedi_device *dev,
+				      unsigned char b_ModulNbr, unsigned char b_SelectedCounter,
+				      unsigned int ui_WriteValue);
 
-INT i_APCI1710_Write32BitCounterValue(struct comedi_device *dev,
-				      BYTE b_ModulNbr, ULONG ul_WriteValue);
+int i_APCI1710_Write32BitCounterValue(struct comedi_device *dev,
+				      unsigned char b_ModulNbr, unsigned int ul_WriteValue);
 
-INT i_APCI1710_EnableIndex(struct comedi_device *dev, BYTE b_ModulNbr);
+int i_APCI1710_EnableIndex(struct comedi_device *dev, unsigned char b_ModulNbr);
 
-INT i_APCI1710_DisableIndex(struct comedi_device *dev, BYTE b_ModulNbr);
+int i_APCI1710_DisableIndex(struct comedi_device *dev, unsigned char b_ModulNbr);
 
-INT i_APCI1710_EnableCompareLogic(struct comedi_device *dev, BYTE b_ModulNbr);
+int i_APCI1710_EnableCompareLogic(struct comedi_device *dev, unsigned char b_ModulNbr);
 
-INT i_APCI1710_DisableCompareLogic(struct comedi_device *dev, BYTE b_ModulNbr);
+int i_APCI1710_DisableCompareLogic(struct comedi_device *dev, unsigned char b_ModulNbr);
 
-INT i_APCI1710_EnableFrequencyMeasurement(struct comedi_device *dev,
-					  BYTE b_ModulNbr,
-					  BYTE b_InterruptEnable);
+int i_APCI1710_EnableFrequencyMeasurement(struct comedi_device *dev,
+					  unsigned char b_ModulNbr,
+					  unsigned char b_InterruptEnable);
 
-INT i_APCI1710_DisableFrequencyMeasurement(struct comedi_device *dev,
-					   BYTE b_ModulNbr);
+int i_APCI1710_DisableFrequencyMeasurement(struct comedi_device *dev,
+					   unsigned char b_ModulNbr);
 
 /* INSN READ */
-INT i_APCI1710_ReadLatchRegisterStatus(struct comedi_device *dev,
-				       BYTE b_ModulNbr, BYTE b_LatchReg,
-				       PBYTE pb_LatchStatus);
+int i_APCI1710_ReadLatchRegisterStatus(struct comedi_device *dev,
+				       unsigned char b_ModulNbr, unsigned char b_LatchReg,
+				       unsigned char *pb_LatchStatus);
 
-INT i_APCI1710_ReadLatchRegisterValue(struct comedi_device *dev,
-				      BYTE b_ModulNbr, BYTE b_LatchReg,
-				      PULONG pul_LatchValue);
+int i_APCI1710_ReadLatchRegisterValue(struct comedi_device *dev,
+				      unsigned char b_ModulNbr, unsigned char b_LatchReg,
+				      unsigned int *pul_LatchValue);
 
-INT i_APCI1710_Read16BitCounterValue(struct comedi_device *dev,
-				     BYTE b_ModulNbr, BYTE b_SelectedCounter,
-				     PUINT pui_CounterValue);
+int i_APCI1710_Read16BitCounterValue(struct comedi_device *dev,
+				     unsigned char b_ModulNbr, unsigned char b_SelectedCounter,
+				     unsigned int *pui_CounterValue);
 
-INT i_APCI1710_Read32BitCounterValue(struct comedi_device *dev,
-				     BYTE b_ModulNbr, PULONG pul_CounterValue);
+int i_APCI1710_Read32BitCounterValue(struct comedi_device *dev,
+				     unsigned char b_ModulNbr, unsigned int *pul_CounterValue);
 
-INT i_APCI1710_GetIndexStatus(struct comedi_device *dev,
-			      BYTE b_ModulNbr, PBYTE pb_IndexStatus);
+int i_APCI1710_GetIndexStatus(struct comedi_device *dev,
+			      unsigned char b_ModulNbr, unsigned char *pb_IndexStatus);
 
-INT i_APCI1710_GetReferenceStatus(struct comedi_device *dev,
-				  BYTE b_ModulNbr, PBYTE pb_ReferenceStatus);
+int i_APCI1710_GetReferenceStatus(struct comedi_device *dev,
+				  unsigned char b_ModulNbr, unsigned char *pb_ReferenceStatus);
 
-INT i_APCI1710_GetUASStatus(struct comedi_device *dev,
-			    BYTE b_ModulNbr, PBYTE pb_UASStatus);
+int i_APCI1710_GetUASStatus(struct comedi_device *dev,
+			    unsigned char b_ModulNbr, unsigned char *pb_UASStatus);
 
-INT i_APCI1710_GetCBStatus(struct comedi_device *dev,
-			   BYTE b_ModulNbr, PBYTE pb_CBStatus);
+int i_APCI1710_GetCBStatus(struct comedi_device *dev,
+			   unsigned char b_ModulNbr, unsigned char *pb_CBStatus);
 
-INT i_APCI1710_Get16BitCBStatus(struct comedi_device *dev,
-				BYTE b_ModulNbr, PBYTE pb_CBStatusCounter0,
-				PBYTE pb_CBStatusCounter1);
+int i_APCI1710_Get16BitCBStatus(struct comedi_device *dev,
+				unsigned char b_ModulNbr, unsigned char *pb_CBStatusCounter0,
+				unsigned char *pb_CBStatusCounter1);
 
-INT i_APCI1710_GetUDStatus(struct comedi_device *dev,
-			   BYTE b_ModulNbr, PBYTE pb_UDStatus);
+int i_APCI1710_GetUDStatus(struct comedi_device *dev,
+			   unsigned char b_ModulNbr, unsigned char *pb_UDStatus);
 
-INT i_APCI1710_GetInterruptUDLatchedStatus(struct comedi_device *dev,
-					   BYTE b_ModulNbr, PBYTE pb_UDStatus);
+int i_APCI1710_GetInterruptUDLatchedStatus(struct comedi_device *dev,
+					   unsigned char b_ModulNbr, unsigned char *pb_UDStatus);
 
-INT i_APCI1710_ReadFrequencyMeasurement(struct comedi_device *dev,
-					BYTE b_ModulNbr,
-					PBYTE pb_Status, PBYTE pb_UDStatus,
-					PULONG pul_ReadValue);
+int i_APCI1710_ReadFrequencyMeasurement(struct comedi_device *dev,
+					unsigned char b_ModulNbr,
+					unsigned char *pb_Status, unsigned char *pb_UDStatus,
+					unsigned int *pul_ReadValue);
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Inp_cpt.c b/drivers/staging/comedi/drivers/addi-data/APCI1710_Inp_cpt.c
index 3ac6a26..0fc2285 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Inp_cpt.c
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Inp_cpt.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -60,11 +60,11 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_InitPulseEncoder                      |
-|                               (BYTE_          b_BoardHandle,               |
-|                                BYTE_          b_ModulNbr,                  |
-|                                BYTE_          b_PulseEncoderNbr,           |
-|                                BYTE_          b_InputLevelSelection,       |
-|                                BYTE_          b_TriggerOutputAction,       |
+|                               (unsigned char_          b_BoardHandle,               |
+|                                unsigned char_          b_ModulNbr,                  |
+|                                unsigned char_          b_PulseEncoderNbr,           |
+|                                unsigned char_          b_InputLevelSelection,       |
+|                                unsigned char_          b_TriggerOutputAction,       |
 |                                ULONG_        ul_StartValue)                |
 +----------------------------------------------------------------------------+
 | Task              : Configure the pulse encoder operating mode selected via|
@@ -74,12 +74,12 @@
 |                     You must calling this function be for you call any     |
 |                     other function witch access of pulse encoders.         |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle         : Handle of board APCI-1710|
-|                     BYTE_ b_ModulNbr            : Module number to         |
+| Input Parameters  : unsigned char_ b_BoardHandle         : Handle of board APCI-1710|
+|                     unsigned char_ b_ModulNbr            : Module number to         |
 |                                                   configure (0 to 3)       |
-|                     BYTE_ b_PulseEncoderNbr     : Pulse encoder selection  |
+|                     unsigned char_ b_PulseEncoderNbr     : Pulse encoder selection  |
 |                                                   (0 to 3)                 |
-|                     BYTE_ b_InputLevelSelection : Input level selection    |
+|                     unsigned char_ b_InputLevelSelection : Input level selection    |
 |                                                   (0 or 1)                 |
 |                                                       0 : Set pulse encoder|
 |                                                           count the the low|
@@ -87,7 +87,7 @@
 |                                                       1 : Set pulse encoder|
 |                                                           count the the    |
 |                                                           high level pulse.|
-|                     BYTE_ b_TriggerOutputAction : Digital TRIGGER output   |
+|                     unsigned char_ b_TriggerOutputAction : Digital TRIGGER output   |
 |                                                   action                   |
 |                                                       0 : No action        |
 |                                                       1 : Set the trigger  |
@@ -104,11 +104,11 @@
 |                                                           encoder          |
 |                     ULONG_ ul_StartValue        : Pulse encoder start value|
 |                                                   (1 to 4294967295)
-	b_ModulNbr				=(BYTE) CR_AREF(insn->chanspec);
-	b_PulseEncoderNbr		=(BYTE) data[0];
-	b_InputLevelSelection	=(BYTE) data[1];
-	b_TriggerOutputAction	=(BYTE) data[2];
-	ul_StartValue			=(ULONG) data[3];
+	b_ModulNbr				=(unsigned char) CR_AREF(insn->chanspec);
+	b_PulseEncoderNbr		=(unsigned char) data[0];
+	b_InputLevelSelection	=(unsigned char) data[1];
+	b_TriggerOutputAction	=(unsigned char) data[2];
+	ul_StartValue			=(unsigned int) data[3];
        |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -123,23 +123,23 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnConfigInitPulseEncoder(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnConfigInitPulseEncoder(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_IntRegister;
+	int i_ReturnValue = 0;
+	unsigned int dw_IntRegister;
 
-	BYTE b_ModulNbr;
-	BYTE b_PulseEncoderNbr;
-	BYTE b_InputLevelSelection;
-	BYTE b_TriggerOutputAction;
-	ULONG ul_StartValue;
+	unsigned char b_ModulNbr;
+	unsigned char b_PulseEncoderNbr;
+	unsigned char b_InputLevelSelection;
+	unsigned char b_TriggerOutputAction;
+	unsigned int ul_StartValue;
 
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_PulseEncoderNbr = (BYTE) data[0];
-	b_InputLevelSelection = (BYTE) data[1];
-	b_TriggerOutputAction = (BYTE) data[2];
-	ul_StartValue = (ULONG) data[3];
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_PulseEncoderNbr = (unsigned char) data[0];
+	b_InputLevelSelection = (unsigned char) data[1];
+	b_TriggerOutputAction = (unsigned char) data[2];
+	ul_StartValue = (unsigned int) data[3];
 
 	i_ReturnValue = insn->n;
 
@@ -346,17 +346,17 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_EnablePulseEncoder                    |
-|                                       (BYTE_  b_BoardHandle,               |
-|                                        BYTE_  b_ModulNbr,                  |
-|                                        BYTE_  b_PulseEncoderNbr,           |
-|                                        BYTE_  b_CycleSelection,            |
-|                                        BYTE_  b_InterruptHandling)         |
+|                                       (unsigned char_  b_BoardHandle,               |
+|                                        unsigned char_  b_ModulNbr,                  |
+|                                        unsigned char_  b_PulseEncoderNbr,           |
+|                                        unsigned char_  b_CycleSelection,            |
+|                                        unsigned char_  b_InterruptHandling)         |
 +----------------------------------------------------------------------------+
 | Task              : Enableor disable  the selected pulse encoder (b_PulseEncoderNbr)  |
 |                     from selected module (b_ModulNbr). Each input pulse    |
@@ -365,12 +365,12 @@
 |                     interrupt is generated when the pulse encoder has run  |
 |                     down.                                                  |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_   b_BoardHandle       : Handle of board APCI-1710|
-|                     BYTE_   b_ModulNbr          : Module number to         |
+| Input Parameters  : unsigned char_   b_BoardHandle       : Handle of board APCI-1710|
+|                     unsigned char_   b_ModulNbr          : Module number to         |
 |                                                   configure (0 to 3)       |
-|                     BYTE_   b_PulseEncoderNbr   : Pulse encoder selection  |
+|                     unsigned char_   b_PulseEncoderNbr   : Pulse encoder selection  |
 |                                                   (0 to 3)                 |
-|                     BYTE_   b_CycleSelection    : APCI1710_CONTINUOUS:     |
+|                     unsigned char_   b_CycleSelection    : APCI1710_CONTINUOUS:     |
 |                                                       Each time the        |
 |                                                       counting value is set|
 |                                                       on "0", the pulse    |
@@ -381,7 +381,7 @@
 |                                                       If the counter is set|
 |                                                       on "0", the pulse    |
 |                                                       encoder is stopped.  |
-|                     BYTE_   b_InterruptHandling : Interrupts can be        |
+|                     unsigned char_   b_InterruptHandling : Interrupts can be        |
 |                                                   generated, when the pulse|
 |                                                   encoder has run down.    |
 |                                                   With this parameter the  |
@@ -393,11 +393,11 @@
 |                                                     APCI1710_DISABLE:      |
 |                                                     Interrupts are disabled
 
-  	b_ModulNbr			=(BYTE) CR_AREF(insn->chanspec);
-	b_Action			=(BYTE) data[0];
-	b_PulseEncoderNbr	=(BYTE) data[1];
-	b_CycleSelection	=(BYTE) data[2];
-	b_InterruptHandling	=(BYTE) data[3];|
+	b_ModulNbr			=(unsigned char) CR_AREF(insn->chanspec);
+	b_Action			=(unsigned char) data[0];
+	b_PulseEncoderNbr	=(unsigned char) data[1];
+	b_CycleSelection	=(unsigned char) data[2];
+	b_InterruptHandling	=(unsigned char) data[3];|
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -414,22 +414,22 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnWriteEnableDisablePulseEncoder(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnWriteEnableDisablePulseEncoder(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	BYTE b_ModulNbr;
-	BYTE b_PulseEncoderNbr;
-	BYTE b_CycleSelection;
-	BYTE b_InterruptHandling;
-	BYTE b_Action;
+	int i_ReturnValue = 0;
+	unsigned char b_ModulNbr;
+	unsigned char b_PulseEncoderNbr;
+	unsigned char b_CycleSelection;
+	unsigned char b_InterruptHandling;
+	unsigned char b_Action;
 
 	i_ReturnValue = insn->n;
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_Action = (BYTE) data[0];
-	b_PulseEncoderNbr = (BYTE) data[1];
-	b_CycleSelection = (BYTE) data[2];
-	b_InterruptHandling = (BYTE) data[3];
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_Action = (unsigned char) data[0];
+	b_PulseEncoderNbr = (unsigned char) data[1];
+	b_CycleSelection = (unsigned char) data[2];
+	b_InterruptHandling = (unsigned char) data[3];
 
 	/***********************************/
 	/* Test the selected module number */
@@ -515,7 +515,7 @@
 									| (1UL
 									<<
 									b_PulseEncoderNbr);
-								devpriv->tsk_Current = current;	// Save the current process task structure
+								devpriv->tsk_Current = current;	/*  Save the current process task structure */
 
 							}
 
@@ -629,7 +629,7 @@
 						(64 * b_ModulNbr));
 
 					break;
-				}	// switch End
+				}	/*  switch End */
 
 			} else {
 		 /*********************************/
@@ -656,39 +656,39 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_ReadPulseEncoderStatus                |
-|                                       (BYTE_  b_BoardHandle,               |
-|                                        BYTE_  b_ModulNbr,                  |
-|                                        BYTE_  b_PulseEncoderNbr,           |
-|                                        PBYTE_ pb_Status)                   |
+|                                       (unsigned char_  b_BoardHandle,               |
+|                                        unsigned char_  b_ModulNbr,                  |
+|                                        unsigned char_  b_PulseEncoderNbr,           |
+|                                        unsigned char *_ pb_Status)                   |
 +----------------------------------------------------------------------------+
 | Task    APCI1710_PULSEENCODER_READ          : Reads the pulse encoder status
 											and valuefrom selected pulse     |
 |                     encoder (b_PulseEncoderNbr) from selected module       |
 |                     (b_ModulNbr).                                          |
 +----------------------------------------------------------------------------+
-	BYTE   b_Type; data[0]
+	unsigned char   b_Type; data[0]
    APCI1710_PULSEENCODER_WRITE
  Writes a 32-bit value (ul_WriteValue) into the selected|
 |                     pulse encoder (b_PulseEncoderNbr) from selected module |
 |                     (b_ModulNbr). This operation set the new start pulse   |
 |                     encoder value.
  APCI1710_PULSEENCODER_READ
-| Input Parameters  : BYTE_   b_BoardHandle       : Handle of board APCI-1710|
-|            CRAREF()         BYTE_   b_ModulNbr          : Module number to         |
+| Input Parameters  : unsigned char_   b_BoardHandle       : Handle of board APCI-1710|
+|            CRAREF()         unsigned char_   b_ModulNbr          : Module number to         |
 |                                                   configure (0 to 3)       |
-|              data[1]       BYTE_   b_PulseEncoderNbr   : Pulse encoder selection  |
+|              data[1]       unsigned char_   b_PulseEncoderNbr   : Pulse encoder selection  |
 |                                                   (0 to 3)
    APCI1710_PULSEENCODER_WRITE
 				data[2]		ULONG_ ul_WriteValue        : 32-bit value to be       |
 |                                                   written             |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_ pb_Status            : Pulse encoder status.    |
+| Output Parameters : unsigned char *_ pb_Status            : Pulse encoder status.    |
 |                                                       0 : No overflow occur|
 |                                                       1 : Overflow occur
 						PULONG_ pul_ReadValue       : Pulse encoder value      |  |
@@ -702,30 +702,30 @@
 +----------------------------------------------------------------------------+
 */
 
-/*_INT_   i_APCI1710_ReadPulseEncoderStatus       (BYTE_   b_BoardHandle,
-						 BYTE_   b_ModulNbr,
-						 BYTE_   b_PulseEncoderNbr,
+/*_INT_   i_APCI1710_ReadPulseEncoderStatus       (unsigned char_   b_BoardHandle,
+						 unsigned char_   b_ModulNbr,
+						 unsigned char_   b_PulseEncoderNbr,
 
-   						 PBYTE_ pb_Status)
+						 unsigned char *_ pb_Status)
 						 */
-INT i_APCI1710_InsnBitsReadWritePulseEncoder(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnBitsReadWritePulseEncoder(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusRegister;
-	BYTE b_ModulNbr;
-	BYTE b_PulseEncoderNbr;
-	PBYTE pb_Status;
-	BYTE b_Type;
-	PULONG pul_ReadValue;
-	ULONG ul_WriteValue;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusRegister;
+	unsigned char b_ModulNbr;
+	unsigned char b_PulseEncoderNbr;
+	unsigned char *pb_Status;
+	unsigned char b_Type;
+	unsigned int *pul_ReadValue;
+	unsigned int ul_WriteValue;
 
 	i_ReturnValue = insn->n;
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_Type = (BYTE) data[0];
-	b_PulseEncoderNbr = (BYTE) data[1];
-	pb_Status = (PBYTE) & data[0];
-	pul_ReadValue = (PULONG) & data[1];
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_Type = (unsigned char) data[0];
+	b_PulseEncoderNbr = (unsigned char) data[1];
+	pb_Status = (unsigned char *) &data[0];
+	pul_ReadValue = (unsigned int *) &data[1];
 
 	/***********************************/
 	/* Test the selected module number */
@@ -766,7 +766,7 @@
 						dw_StatusRegister;
 
 					*pb_Status =
-						(BYTE) (devpriv->
+						(unsigned char) (devpriv->
 						s_ModuleInfo[b_ModulNbr].
 						s_PulseEncoderModuleInfo.
 						dw_StatusRegister >> (1 +
@@ -794,7 +794,7 @@
 					break;
 
 				case APCI1710_PULSEENCODER_WRITE:
-					ul_WriteValue = (ULONG) data[2];
+					ul_WriteValue = (unsigned int) data[2];
 			/*******************/
 					/* Write the value */
 			/*******************/
@@ -805,7 +805,7 @@
 						(4 * b_PulseEncoderNbr) +
 						(64 * b_ModulNbr));
 
-				}	//end of switch
+				}	/* end of switch */
 			} else {
 		 /*********************************/
 				/* Pulse encoder not initialised */
@@ -831,11 +831,11 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
-INT i_APCI1710_InsnReadInterruptPulseEncoder(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnReadInterruptPulseEncoder(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 
 	data[0] = devpriv->s_InterruptParameters.
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Inp_cpt.h b/drivers/staging/comedi/drivers/addi-data/APCI1710_Inp_cpt.h
index 2825287..61a21cc 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Inp_cpt.h
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Inp_cpt.h
@@ -21,11 +21,11 @@
 #define APCI1710_PULSEENCODER_READ	0
 #define APCI1710_PULSEENCODER_WRITE	1
 
-INT i_APCI1710_InsnConfigInitPulseEncoder(struct comedi_device *dev,
+int i_APCI1710_InsnConfigInitPulseEncoder(struct comedi_device *dev,
 					  struct comedi_subdevice *s,
 					  struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_InsnWriteEnableDisablePulseEncoder(struct comedi_device *dev,
+int i_APCI1710_InsnWriteEnableDisablePulseEncoder(struct comedi_device *dev,
 						  struct comedi_subdevice *s,
 						  struct comedi_insn *insn,
 						  unsigned int *data);
@@ -33,7 +33,7 @@
 /*
  * READ PULSE ENCODER FUNCTIONS
  */
-INT i_APCI1710_InsnReadInterruptPulseEncoder(struct comedi_device *dev,
+int i_APCI1710_InsnReadInterruptPulseEncoder(struct comedi_device *dev,
 					     struct comedi_subdevice *s,
 					     struct comedi_insn *insn,
 					     unsigned int *data);
@@ -41,7 +41,7 @@
 /*
  * WRITE PULSE ENCODER FUNCTIONS
  */
-INT i_APCI1710_InsnBitsReadWritePulseEncoder(struct comedi_device *dev,
+int i_APCI1710_InsnBitsReadWritePulseEncoder(struct comedi_device *dev,
 					     struct comedi_subdevice *s,
 					     struct comedi_insn *insn,
 					     unsigned int *data);
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Pwm.c b/drivers/staging/comedi/drivers/addi-data/APCI1710_Pwm.c
index 5ddd092..138a84f 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Pwm.c
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Pwm.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -70,38 +70,38 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnConfigPWM(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnConfigPWM(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	BYTE b_ConfigType;
-	INT i_ReturnValue = 0;
+	unsigned char b_ConfigType;
+	int i_ReturnValue = 0;
 	b_ConfigType = CR_CHAN(insn->chanspec);
 
 	switch (b_ConfigType) {
 	case APCI1710_PWM_INIT:
-		i_ReturnValue = i_APCI1710_InitPWM(dev, (BYTE) CR_AREF(insn->chanspec),	//  b_ModulNbr
-			(BYTE) data[0],	//b_PWM
-			(BYTE) data[1],	// b_ClockSelection
-			(BYTE) data[2],	// b_TimingUnit
-			(ULONG) data[3],	//ul_LowTiming
-			(ULONG) data[4],	//ul_HighTiming
-			(PULONG) & data[0],	//pul_RealLowTiming
-			(PULONG) & data[1]	//pul_RealHighTiming
+		i_ReturnValue = i_APCI1710_InitPWM(dev, (unsigned char) CR_AREF(insn->chanspec),	/*   b_ModulNbr */
+			(unsigned char) data[0],	/* b_PWM */
+			(unsigned char) data[1],	/*  b_ClockSelection */
+			(unsigned char) data[2],	/*  b_TimingUnit */
+			(unsigned int) data[3],	/* ul_LowTiming */
+			(unsigned int) data[4],	/* ul_HighTiming */
+			(unsigned int *) &data[0],	/* pul_RealLowTiming */
+			(unsigned int *) &data[1]	/* pul_RealHighTiming */
 			);
 		break;
 
 	case APCI1710_PWM_GETINITDATA:
-		i_ReturnValue = i_APCI1710_GetPWMInitialisation(dev, (BYTE) CR_AREF(insn->chanspec),	// b_ModulNbr
-			(BYTE) data[0],	//b_PWM
-			(PBYTE) & data[0],	//pb_TimingUnit
-			(PULONG) & data[1],	//pul_LowTiming
-			(PULONG) & data[2],	//pul_HighTiming
-			(PBYTE) & data[3],	// pb_StartLevel
-			(PBYTE) & data[4],	// pb_StopMode
-			(PBYTE) & data[5],	// pb_StopLevel
-			(PBYTE) & data[6],	// pb_ExternGate
-			(PBYTE) & data[7],	// pb_InterruptEnable
-			(PBYTE) & data[8]	// pb_Enable
+		i_ReturnValue = i_APCI1710_GetPWMInitialisation(dev, (unsigned char) CR_AREF(insn->chanspec),	/*  b_ModulNbr */
+			(unsigned char) data[0],	/* b_PWM */
+			(unsigned char *) &data[0],	/* pb_TimingUnit */
+			(unsigned int *) &data[1],	/* pul_LowTiming */
+			(unsigned int *) &data[2],	/* pul_HighTiming */
+			(unsigned char *) &data[3],	/*  pb_StartLevel */
+			(unsigned char *) &data[4],	/*  pb_StopMode */
+			(unsigned char *) &data[5],	/*  pb_StopLevel */
+			(unsigned char *) &data[6],	/*  pb_ExternGate */
+			(unsigned char *) &data[7],	/*  pb_InterruptEnable */
+			(unsigned char *) &data[8]	/*  pb_Enable */
 			);
 		break;
 
@@ -111,17 +111,17 @@
 
 	if (i_ReturnValue >= 0)
 		i_ReturnValue = insn->n;
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_InitPWM                               |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
-|                                        BYTE_     b_PWM,                    |
-|                                        BYTE_     b_ClockSelection,         |
-|                                        BYTE_     b_TimingUnit,             |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
+|                                        unsigned char_     b_PWM,                    |
+|                                        unsigned char_     b_ClockSelection,         |
+|                                        unsigned char_     b_TimingUnit,             |
 |                                        ULONG_   ul_LowTiming,              |
 |                                        ULONG_   ul_HighTiming,             |
 |                                        PULONG_ pul_RealLowTiming,          |
@@ -135,11 +135,11 @@
 |                     You must calling this function be for you call any     |
 |                     other function witch access of the PWM.                |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_     b_BoardHandle    : Handle of board APCI-1710 |
-|                     BYTE_     b_ModulNbr       : Module number to configure|
+| Input Parameters  : unsigned char_     b_BoardHandle    : Handle of board APCI-1710 |
+|                     unsigned char_     b_ModulNbr       : Module number to configure|
 |                                                  (0 to 3)                  |
-|                     BYTE_     b_PWM            : Selected PWM (0 or 1).    |
-|                     BYTE_     b_ClockSelection : Selection from PCI bus    |
+|                     unsigned char_     b_PWM            : Selected PWM (0 or 1).    |
+|                     unsigned char_     b_ClockSelection : Selection from PCI bus    |
 |                                                  clock                     |
 |                                                   - APCI1710_30MHZ :       |
 |                                                     The PC have a 30 MHz   |
@@ -151,7 +151,7 @@
 |                                                     The APCI-1710 have a   |
 |                                                     integrated 40Mhz       |
 |                                                     quartz.                |
-|                     BYTE_     b_TimingUnit     : Base timing Unit (0 to 4) |
+|                     unsigned char_     b_TimingUnit     : Base timing Unit (0 to 4) |
 |                                                       0 : ns               |
 |                                                       1 : æs               |
 |                                                       2 : ms               |
@@ -179,19 +179,19 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InitPWM(struct comedi_device * dev,
-	BYTE b_ModulNbr,
-	BYTE b_PWM,
-	BYTE b_ClockSelection,
-	BYTE b_TimingUnit,
-	ULONG ul_LowTiming,
-	ULONG ul_HighTiming,
-	PULONG pul_RealLowTiming, PULONG pul_RealHighTiming)
+int i_APCI1710_InitPWM(struct comedi_device *dev,
+	unsigned char b_ModulNbr,
+	unsigned char b_PWM,
+	unsigned char b_ClockSelection,
+	unsigned char b_TimingUnit,
+	unsigned int ul_LowTiming,
+	unsigned int ul_HighTiming,
+	unsigned int *pul_RealLowTiming, unsigned int *pul_RealHighTiming)
 {
-	INT i_ReturnValue = 0;
-	ULONG ul_LowTimerValue = 0;
-	ULONG ul_HighTimerValue = 0;
-	DWORD dw_Command;
+	int i_ReturnValue = 0;
+	unsigned int ul_LowTimerValue = 0;
+	unsigned int ul_HighTimerValue = 0;
+	unsigned int dw_Command;
 	double d_RealLowTiming = 0;
 	double d_RealHighTiming = 0;
 
@@ -200,33 +200,33 @@
 	/**************************/
 
 	if (b_ModulNbr < 4) {
-	   /***************/
+		/***************/
 		/* Test if PWM */
-	   /***************/
+		/***************/
 
 		if ((devpriv->s_BoardInfos.
 				dw_MolduleConfiguration[b_ModulNbr] &
 				0xFFFF0000UL) == APCI1710_PWM) {
-	      /**************************/
+			/**************************/
 			/* Test the PWM selection */
-	      /**************************/
+			/**************************/
 
 			if (b_PWM <= 1) {
-		 /******************/
+				/******************/
 				/* Test the clock */
-		 /******************/
+				/******************/
 
 				if ((b_ClockSelection == APCI1710_30MHZ) ||
 					(b_ClockSelection == APCI1710_33MHZ) ||
 					(b_ClockSelection == APCI1710_40MHZ)) {
-		    /************************/
+					/************************/
 					/* Test the timing unit */
-		    /************************/
+					/************************/
 
 					if (b_TimingUnit <= 4) {
-		       /*********************************/
+						/*********************************/
 						/* Test the low timing selection */
-		       /*********************************/
+						/*********************************/
 
 						if (((b_ClockSelection ==
 									APCI1710_30MHZ)
@@ -361,45 +361,45 @@
 								&& (ul_LowTiming
 									<=
 									7UL))) {
-			  /**********************************/
+							/**********************************/
 							/* Test the High timing selection */
-			  /**********************************/
+							/**********************************/
 
 							if (((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 266) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571230650UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571230UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 9UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 242) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 519691043UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 519691UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 520UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 8UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 200) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429496729UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429496UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 7UL))) {
-			     /**************************/
+								/**************************/
 								/* Test the board version */
-			     /**************************/
+								/**************************/
 
 								if (((b_ClockSelection == APCI1710_40MHZ) && (devpriv->s_BoardInfos.b_BoardVersion > 0)) || (b_ClockSelection != APCI1710_40MHZ)) {
 
-				/************************************/
+									/************************************/
 									/* Calculate the low division fator */
-				/************************************/
+									/************************************/
 
 									fpu_begin
 										();
 
 									switch (b_TimingUnit) {
-				   /******/
+										/******/
 										/* ns */
-				   /******/
+										/******/
 
 									case 0:
 
-					   /******************/
+										/******************/
 										/* Timer 0 factor */
-					   /******************/
+										/******************/
 
 										ul_LowTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_LowTiming
 											*
 											(0.00025 * b_ClockSelection));
 
-					   /*******************/
+										/*******************/
 										/* Round the value */
-					   /*******************/
+										/*******************/
 
 										if ((double)((double)ul_LowTiming * (0.00025 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
 											ul_LowTimerValue
@@ -409,13 +409,13 @@
 												1;
 										}
 
-					   /*****************************/
+										/*****************************/
 										/* Calculate the real timing */
-					   /*****************************/
+										/*****************************/
 
 										*pul_RealLowTiming
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_LowTimerValue
 											/
 											(0.00025 * (double)b_ClockSelection));
@@ -451,7 +451,7 @@
 										if (b_ClockSelection != APCI1710_40MHZ) {
 											ul_LowTimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_LowTimerValue)
@@ -461,26 +461,26 @@
 
 										break;
 
-				   /******/
+										/******/
 										/* æs */
-				   /******/
+										/******/
 
 									case 1:
 
-					   /******************/
+										/******************/
 										/* Timer 0 factor */
-					   /******************/
+										/******************/
 
 										ul_LowTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_LowTiming
 											*
 											(0.25 * b_ClockSelection));
 
-					   /*******************/
+										/*******************/
 										/* Round the value */
-					   /*******************/
+										/*******************/
 
 										if ((double)((double)ul_LowTiming * (0.25 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
 											ul_LowTimerValue
@@ -490,13 +490,13 @@
 												1;
 										}
 
-					   /*****************************/
+										/*****************************/
 										/* Calculate the real timing */
-					   /*****************************/
+										/*****************************/
 
 										*pul_RealLowTiming
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_LowTimerValue
 											/
 											(0.25 * (double)b_ClockSelection));
@@ -534,7 +534,7 @@
 										if (b_ClockSelection != APCI1710_40MHZ) {
 											ul_LowTimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_LowTimerValue)
@@ -544,15 +544,15 @@
 
 										break;
 
-				   /******/
+										/******/
 										/* ms */
-				   /******/
+										/******/
 
 									case 2:
 
-					   /******************/
+										/******************/
 										/* Timer 0 factor */
-					   /******************/
+										/******************/
 
 										ul_LowTimerValue
 											=
@@ -562,9 +562,9 @@
 											*
 											b_ClockSelection);
 
-					   /*******************/
+										/*******************/
 										/* Round the value */
-					   /*******************/
+										/*******************/
 
 										if ((double)((double)ul_LowTiming * (250.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
 											ul_LowTimerValue
@@ -574,13 +574,13 @@
 												1;
 										}
 
-					   /*****************************/
+										/*****************************/
 										/* Calculate the real timing */
-					   /*****************************/
+										/*****************************/
 
 										*pul_RealLowTiming
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_LowTimerValue
 											/
 											(250.0 * (double)b_ClockSelection));
@@ -616,7 +616,7 @@
 										if (b_ClockSelection != APCI1710_40MHZ) {
 											ul_LowTimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_LowTimerValue)
@@ -626,27 +626,27 @@
 
 										break;
 
-				   /*****/
+										/*****/
 										/* s */
-				   /*****/
+										/*****/
 
 									case 3:
-					   /******************/
+										/******************/
 										/* Timer 0 factor */
-					   /******************/
+										/******************/
 
 										ul_LowTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_LowTiming
 											*
 											(250000.0
 												*
 												b_ClockSelection));
 
-					   /*******************/
+										/*******************/
 										/* Round the value */
-					   /*******************/
+										/*******************/
 
 										if ((double)((double)ul_LowTiming * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
 											ul_LowTimerValue
@@ -656,13 +656,13 @@
 												1;
 										}
 
-					   /*****************************/
+										/*****************************/
 										/* Calculate the real timing */
-					   /*****************************/
+										/*****************************/
 
 										*pul_RealLowTiming
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_LowTimerValue
 											/
 											(250000.0
@@ -701,7 +701,7 @@
 										if (b_ClockSelection != APCI1710_40MHZ) {
 											ul_LowTimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_LowTimerValue)
@@ -711,19 +711,19 @@
 
 										break;
 
-				   /******/
+										/******/
 										/* mn */
-				   /******/
+										/******/
 
 									case 4:
 
-					   /******************/
+										/******************/
 										/* Timer 0 factor */
-					   /******************/
+										/******************/
 
 										ul_LowTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(ul_LowTiming
 												*
@@ -733,9 +733,9 @@
 												*
 												b_ClockSelection));
 
-					   /*******************/
+										/*******************/
 										/* Round the value */
-					   /*******************/
+										/*******************/
 
 										if ((double)((double)(ul_LowTiming * 60.0) * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
 											ul_LowTimerValue
@@ -745,13 +745,13 @@
 												1;
 										}
 
-					   /*****************************/
+										/*****************************/
 										/* Calculate the real timing */
-					   /*****************************/
+										/*****************************/
 
 										*pul_RealLowTiming
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_LowTimerValue
 											/
 											(250000.0
@@ -795,7 +795,7 @@
 										if (b_ClockSelection != APCI1710_40MHZ) {
 											ul_LowTimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_LowTimerValue)
@@ -806,31 +806,31 @@
 										break;
 									}
 
-				/*************************************/
+									/*************************************/
 									/* Calculate the high division fator */
-				/*************************************/
+									/*************************************/
 
 									switch (b_TimingUnit) {
-				   /******/
+										/******/
 										/* ns */
-				   /******/
+										/******/
 
 									case 0:
 
-					   /******************/
+										/******************/
 										/* Timer 0 factor */
-					   /******************/
+										/******************/
 
 										ul_HighTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_HighTiming
 											*
 											(0.00025 * b_ClockSelection));
 
-					   /*******************/
+										/*******************/
 										/* Round the value */
-					   /*******************/
+										/*******************/
 
 										if ((double)((double)ul_HighTiming * (0.00025 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
 											ul_HighTimerValue
@@ -840,13 +840,13 @@
 												1;
 										}
 
-					   /*****************************/
+										/*****************************/
 										/* Calculate the real timing */
-					   /*****************************/
+										/*****************************/
 
 										*pul_RealHighTiming
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_HighTimerValue
 											/
 											(0.00025 * (double)b_ClockSelection));
@@ -882,7 +882,7 @@
 										if (b_ClockSelection != APCI1710_40MHZ) {
 											ul_HighTimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_HighTimerValue)
@@ -892,26 +892,26 @@
 
 										break;
 
-				   /******/
+										/******/
 										/* æs */
-				   /******/
+										/******/
 
 									case 1:
 
-					   /******************/
+										/******************/
 										/* Timer 0 factor */
-					   /******************/
+										/******************/
 
 										ul_HighTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_HighTiming
 											*
 											(0.25 * b_ClockSelection));
 
-					   /*******************/
+										/*******************/
 										/* Round the value */
-					   /*******************/
+										/*******************/
 
 										if ((double)((double)ul_HighTiming * (0.25 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
 											ul_HighTimerValue
@@ -921,13 +921,13 @@
 												1;
 										}
 
-					   /*****************************/
+										/*****************************/
 										/* Calculate the real timing */
-					   /*****************************/
+										/*****************************/
 
 										*pul_RealHighTiming
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_HighTimerValue
 											/
 											(0.25 * (double)b_ClockSelection));
@@ -965,7 +965,7 @@
 										if (b_ClockSelection != APCI1710_40MHZ) {
 											ul_HighTimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_HighTimerValue)
@@ -975,15 +975,15 @@
 
 										break;
 
-				   /******/
+										/******/
 										/* ms */
-				   /******/
+										/******/
 
 									case 2:
 
-					   /******************/
+										/******************/
 										/* Timer 0 factor */
-					   /******************/
+										/******************/
 
 										ul_HighTimerValue
 											=
@@ -993,9 +993,9 @@
 											*
 											b_ClockSelection);
 
-					   /*******************/
+										/*******************/
 										/* Round the value */
-					   /*******************/
+										/*******************/
 
 										if ((double)((double)ul_HighTiming * (250.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
 											ul_HighTimerValue
@@ -1005,13 +1005,13 @@
 												1;
 										}
 
-					   /*****************************/
+										/*****************************/
 										/* Calculate the real timing */
-					   /*****************************/
+										/*****************************/
 
 										*pul_RealHighTiming
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_HighTimerValue
 											/
 											(250.0 * (double)b_ClockSelection));
@@ -1047,7 +1047,7 @@
 										if (b_ClockSelection != APCI1710_40MHZ) {
 											ul_HighTimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_HighTimerValue)
@@ -1057,28 +1057,28 @@
 
 										break;
 
-				   /*****/
+										/*****/
 										/* s */
-				   /*****/
+										/*****/
 
 									case 3:
 
-					   /******************/
+										/******************/
 										/* Timer 0 factor */
-					   /******************/
+										/******************/
 
 										ul_HighTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_HighTiming
 											*
 											(250000.0
 												*
 												b_ClockSelection));
 
-					   /*******************/
+										/*******************/
 										/* Round the value */
-					   /*******************/
+										/*******************/
 
 										if ((double)((double)ul_HighTiming * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
 											ul_HighTimerValue
@@ -1088,13 +1088,13 @@
 												1;
 										}
 
-					   /*****************************/
+										/*****************************/
 										/* Calculate the real timing */
-					   /*****************************/
+										/*****************************/
 
 										*pul_RealHighTiming
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_HighTimerValue
 											/
 											(250000.0
@@ -1133,7 +1133,7 @@
 										if (b_ClockSelection != APCI1710_40MHZ) {
 											ul_HighTimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_HighTimerValue)
@@ -1143,19 +1143,19 @@
 
 										break;
 
-				   /******/
+										/******/
 										/* mn */
-				   /******/
+										/******/
 
 									case 4:
 
-					   /******************/
+										/******************/
 										/* Timer 0 factor */
-					   /******************/
+										/******************/
 
 										ul_HighTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(ul_HighTiming
 												*
@@ -1165,9 +1165,9 @@
 												*
 												b_ClockSelection));
 
-					   /*******************/
+										/*******************/
 										/* Round the value */
-					   /*******************/
+										/*******************/
 
 										if ((double)((double)(ul_HighTiming * 60.0) * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
 											ul_HighTimerValue
@@ -1177,13 +1177,13 @@
 												1;
 										}
 
-					   /*****************************/
+										/*****************************/
 										/* Calculate the real timing */
-					   /*****************************/
+										/*****************************/
 
 										*pul_RealHighTiming
 											=
-											(ULONG)
+											(unsigned int)
 											(ul_HighTimerValue
 											/
 											(250000.0
@@ -1227,7 +1227,7 @@
 										if (b_ClockSelection != APCI1710_40MHZ) {
 											ul_HighTimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(double)
 												(ul_HighTimerValue)
@@ -1239,9 +1239,9 @@
 									}
 
 									fpu_end();
-				/****************************/
+									/****************************/
 									/* Save the clock selection */
-				/****************************/
+									/****************************/
 
 									devpriv->
 										s_ModuleInfo
@@ -1251,9 +1251,9 @@
 										=
 										b_ClockSelection;
 
-				/************************/
+									/************************/
 									/* Save the timing unit */
-				/************************/
+									/************************/
 
 									devpriv->
 										s_ModuleInfo
@@ -1265,9 +1265,9 @@
 										=
 										b_TimingUnit;
 
-				/****************************/
+									/****************************/
 									/* Save the low base timing */
-				/****************************/
+									/****************************/
 
 									devpriv->
 										s_ModuleInfo
@@ -1289,9 +1289,9 @@
 										=
 										*pul_RealLowTiming;
 
-				/****************************/
+									/****************************/
 									/* Save the high base timing */
-				/****************************/
+									/****************************/
 
 									devpriv->
 										s_ModuleInfo
@@ -1313,21 +1313,21 @@
 										=
 										*pul_RealHighTiming;
 
-				/************************/
+									/************************/
 									/* Write the low timing */
-				/************************/
+									/************************/
 
 									outl(ul_LowTimerValue, devpriv->s_BoardInfos.ui_Address + 0 + (20 * b_PWM) + (64 * b_ModulNbr));
 
-				/*************************/
+									/*************************/
 									/* Write the high timing */
-				/*************************/
+									/*************************/
 
 									outl(ul_HighTimerValue, devpriv->s_BoardInfos.ui_Address + 4 + (20 * b_PWM) + (64 * b_ModulNbr));
 
-				/***************************/
+									/***************************/
 									/* Set the clock selection */
-				/***************************/
+									/***************************/
 
 									dw_Command
 										=
@@ -1354,15 +1354,15 @@
 											0x80;
 									}
 
-				/***************************/
+									/***************************/
 									/* Set the clock selection */
-				/***************************/
+									/***************************/
 
 									outl(dw_Command, devpriv->s_BoardInfos.ui_Address + 8 + (20 * b_PWM) + (64 * b_ModulNbr));
 
-				/*************/
+									/*************/
 									/* PWM init. */
-				/*************/
+									/*************/
 									devpriv->
 										s_ModuleInfo
 										[b_ModulNbr].
@@ -1373,98 +1373,98 @@
 										=
 										1;
 								} else {
-				/***************************************************/
+									/***************************************************/
 									/* You can not used the 40MHz clock selection with */
 									/* this board                                      */
-				/***************************************************/
+									/***************************************************/
 									DPRINTK("You can not used the 40MHz clock selection with this board\n");
 									i_ReturnValue
 										=
 										-9;
 								}
 							} else {
-			     /***************************************/
+								/***************************************/
 								/* High base timing selection is wrong */
-			     /***************************************/
+								/***************************************/
 								DPRINTK("High base timing selection is wrong\n");
 								i_ReturnValue =
 									-8;
 							}
 						} else {
-			  /**************************************/
+							/**************************************/
 							/* Low base timing selection is wrong */
-			  /**************************************/
+							/**************************************/
 							DPRINTK("Low base timing selection is wrong\n");
 							i_ReturnValue = -7;
 						}
-					}	// if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4))
+					}	/*  if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
 					else {
-		       /**********************************/
+						/**********************************/
 						/* Timing unit selection is wrong */
-		       /**********************************/
+						/**********************************/
 						DPRINTK("Timing unit selection is wrong\n");
 						i_ReturnValue = -6;
-					}	// if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4))
-				}	// if ((b_ClockSelection == APCI1710_30MHZ) || (b_ClockSelection == APCI1710_33MHZ) || (b_ClockSelection == APCI1710_40MHZ))
+					}	/*  if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
+				}	/*  if ((b_ClockSelection == APCI1710_30MHZ) || (b_ClockSelection == APCI1710_33MHZ) || (b_ClockSelection == APCI1710_40MHZ)) */
 				else {
-		    /*******************************/
+					/*******************************/
 					/* The selected clock is wrong */
-		    /*******************************/
+					/*******************************/
 					DPRINTK("The selected clock is wrong\n");
 					i_ReturnValue = -5;
-				}	// if ((b_ClockSelection == APCI1710_30MHZ) || (b_ClockSelection == APCI1710_33MHZ) || (b_ClockSelection == APCI1710_40MHZ))
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+				}	/*  if ((b_ClockSelection == APCI1710_30MHZ) || (b_ClockSelection == APCI1710_33MHZ) || (b_ClockSelection == APCI1710_40MHZ)) */
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 			else {
-		 /******************************/
+				/******************************/
 				/* Tor PWM selection is wrong */
-		 /******************************/
+				/******************************/
 				DPRINTK("Tor PWM selection is wrong\n");
 				i_ReturnValue = -4;
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 		} else {
-	      /**********************************/
+			/**********************************/
 			/* The module is not a PWM module */
-	      /**********************************/
+			/**********************************/
 			DPRINTK("The module is not a PWM module\n");
 			i_ReturnValue = -3;
 		}
 	} else {
-	   /***********************/
+		/***********************/
 		/* Module number error */
-	   /***********************/
+		/***********************/
 		DPRINTK("Module number error\n");
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_GetPWMInitialisation                  |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
-|                                        BYTE_     b_PWM,                    |
-|                                        PBYTE_   pb_TimingUnit,             |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
+|                                        unsigned char_     b_PWM,                    |
+|                                        unsigned char *_   pb_TimingUnit,             |
 |                                        PULONG_ pul_LowTiming,              |
 |                                        PULONG_ pul_HighTiming,             |
-|                                        PBYTE_   pb_StartLevel,             |
-|                                        PBYTE_   pb_StopMode,               |
-|                                        PBYTE_   pb_StopLevel,              |
-|                                        PBYTE_   pb_ExternGate,             |
-|                                        PBYTE_   pb_InterruptEnable,        |
-|                                        PBYTE_   pb_Enable)                 |
+|                                        unsigned char *_   pb_StartLevel,             |
+|                                        unsigned char *_   pb_StopMode,               |
+|                                        unsigned char *_   pb_StopLevel,              |
+|                                        unsigned char *_   pb_ExternGate,             |
+|                                        unsigned char *_   pb_InterruptEnable,        |
+|                                        unsigned char *_   pb_Enable)                 |
 +----------------------------------------------------------------------------+
 | Task              : Return the PWM (b_PWM) initialisation from selected    |
 |                     module (b_ModulNbr). You must calling the              |
 |                     "i_APCI1710_InitPWM" function be for you call this     |
 |                     function.                                              |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle : Handle of board APCI-1710        |
-|                     BYTE_ b_ModulNbr    : Selected module number (0 to 3)  |
-|                     BYTE_ b_PWM         : Selected PWM (0 or 1)            |
+| Input Parameters  : unsigned char_ b_BoardHandle : Handle of board APCI-1710        |
+|                     unsigned char_ b_ModulNbr    : Selected module number (0 to 3)  |
+|                     unsigned char_ b_PWM         : Selected PWM (0 or 1)            |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_  pb_TimingUnit      : Base timing Unit (0 to 4) |
+| Output Parameters : unsigned char *_  pb_TimingUnit      : Base timing Unit (0 to 4) |
 |                                                       0 : ns               |
 |                                                       1 : æs               |
 |                                                       2 : ms               |
@@ -1472,13 +1472,13 @@
 |                                                       4 : mn               |
 |                     PULONG_ pul_LowTiming      : Low base timing value.    |
 |                     PULONG_ pul_HighTiming     : High base timing value.   |
-|                     PBYTE_  pb_StartLevel      : Start period level        |
+|                     unsigned char *_  pb_StartLevel      : Start period level        |
 |                                                  selection                 |
 |                                                       0 : The period start |
 |                                                           with a low level |
 |                                                       1 : The period start |
 |                                                           with a high level|
-|                     PBYTE_  pb_StopMode        : Stop mode selection       |
+|                     unsigned char *_  pb_StopMode        : Stop mode selection       |
 |                                                  0 : The PWM is stopped    |
 |                                                      directly after the    |
 |                                                     "i_APCI1710_DisablePWM"|
@@ -1489,7 +1489,7 @@
 |                                                      function the PWM is   |
 |                                                      stopped at the end    |
 |                                                      from last period cycle|
-|                     PBYTE_  pb_StopLevel        : Stop PWM level selection |
+|                     unsigned char *_  pb_StopLevel        : Stop PWM level selection |
 |                                                    0 : The output signal   |
 |                                                        keep the level after|
 |                                                        the                 |
@@ -1504,13 +1504,13 @@
 |                                                        the                 |
 |                                                     "i_APCI1710_DisablePWM"|
 |                                                        function            |
-|                     PBYTE_  pb_ExternGate      : Extern gate action        |
+|                     unsigned char *_  pb_ExternGate      : Extern gate action        |
 |                                                  selection                 |
 |                                                   0 : Extern gate signal   |
 |                                                       not used.            |
 |                                                   1 : Extern gate signal   |
 |                                                       used.                |
-|                     PBYTE_  pb_InterruptEnable : Enable or disable the PWM |
+|                     unsigned char *_  pb_InterruptEnable : Enable or disable the PWM |
 |                                                  interrupt.                |
 |                                                  - APCI1710_ENABLE :       |
 |                                                    Enable the PWM interrupt|
@@ -1519,7 +1519,7 @@
 |                                                  - APCI1710_DISABLE :      |
 |                                                    Disable the PWM         |
 |                                                    interrupt               |
-|                     PBYTE_  pb_Enable          : Indicate if the PWM is    |
+|                     unsigned char *_  pb_Enable          : Indicate if the PWM is    |
 |                                                  enabled or no             |
 |                                                       0 : PWM not enabled  |
 |                                                       1 : PWM enabled      |
@@ -1534,138 +1534,138 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_GetPWMInitialisation(struct comedi_device * dev,
-	BYTE b_ModulNbr,
-	BYTE b_PWM,
-	PBYTE pb_TimingUnit,
-	PULONG pul_LowTiming,
-	PULONG pul_HighTiming,
-	PBYTE pb_StartLevel,
-	PBYTE pb_StopMode,
-	PBYTE pb_StopLevel,
-	PBYTE pb_ExternGate, PBYTE pb_InterruptEnable, PBYTE pb_Enable)
+int i_APCI1710_GetPWMInitialisation(struct comedi_device *dev,
+	unsigned char b_ModulNbr,
+	unsigned char b_PWM,
+	unsigned char *pb_TimingUnit,
+	unsigned int *pul_LowTiming,
+	unsigned int *pul_HighTiming,
+	unsigned char *pb_StartLevel,
+	unsigned char *pb_StopMode,
+	unsigned char *pb_StopLevel,
+	unsigned char *pb_ExternGate, unsigned char *pb_InterruptEnable, unsigned char *pb_Enable)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_Status;
-	DWORD dw_Command;
+	int i_ReturnValue = 0;
+	unsigned int dw_Status;
+	unsigned int dw_Command;
 
 	/**************************/
 	/* Test the module number */
 	/**************************/
 
 	if (b_ModulNbr < 4) {
-	   /***************/
+		/***************/
 		/* Test if PWM */
-	   /***************/
+		/***************/
 
 		if ((devpriv->s_BoardInfos.
 				dw_MolduleConfiguration[b_ModulNbr] &
 				0xFFFF0000UL) == APCI1710_PWM) {
-	      /**************************/
+			/**************************/
 			/* Test the PWM selection */
-	      /**************************/
+			/**************************/
 
 			if (b_PWM <= 1) {
-		 /***************************/
+				/***************************/
 				/* Test if PWM initialised */
-		 /***************************/
+				/***************************/
 
 				dw_Status = inl(devpriv->s_BoardInfos.
 					ui_Address + 12 + (20 * b_PWM) +
 					(64 * b_ModulNbr));
 
 				if (dw_Status & 0x10) {
-		    /***********************/
+					/***********************/
 					/* Read the low timing */
-		    /***********************/
+					/***********************/
 
 					*pul_LowTiming =
 						inl(devpriv->s_BoardInfos.
 						ui_Address + 0 + (20 * b_PWM) +
 						(64 * b_ModulNbr));
 
-		    /************************/
+					/************************/
 					/* Read the high timing */
-		    /************************/
+					/************************/
 
 					*pul_HighTiming =
 						inl(devpriv->s_BoardInfos.
 						ui_Address + 4 + (20 * b_PWM) +
 						(64 * b_ModulNbr));
 
-		    /********************/
+					/********************/
 					/* Read the command */
-		    /********************/
+					/********************/
 
 					dw_Command = inl(devpriv->s_BoardInfos.
 						ui_Address + 8 + (20 * b_PWM) +
 						(64 * b_ModulNbr));
 
 					*pb_StartLevel =
-						(BYTE) ((dw_Command >> 5) & 1);
+						(unsigned char) ((dw_Command >> 5) & 1);
 					*pb_StopMode =
-						(BYTE) ((dw_Command >> 0) & 1);
+						(unsigned char) ((dw_Command >> 0) & 1);
 					*pb_StopLevel =
-						(BYTE) ((dw_Command >> 1) & 1);
+						(unsigned char) ((dw_Command >> 1) & 1);
 					*pb_ExternGate =
-						(BYTE) ((dw_Command >> 4) & 1);
+						(unsigned char) ((dw_Command >> 4) & 1);
 					*pb_InterruptEnable =
-						(BYTE) ((dw_Command >> 3) & 1);
+						(unsigned char) ((dw_Command >> 3) & 1);
 
 					if (*pb_StopLevel) {
 						*pb_StopLevel =
 							*pb_StopLevel +
-							(BYTE) ((dw_Command >>
+							(unsigned char) ((dw_Command >>
 								2) & 1);
 					}
 
-		    /********************/
+					/********************/
 					/* Read the command */
-		    /********************/
+					/********************/
 
 					dw_Command = inl(devpriv->s_BoardInfos.
 						ui_Address + 8 + (20 * b_PWM) +
 						(64 * b_ModulNbr));
 
 					*pb_Enable =
-						(BYTE) ((dw_Command >> 0) & 1);
+						(unsigned char) ((dw_Command >> 0) & 1);
 
 					*pb_TimingUnit = devpriv->
 						s_ModuleInfo[b_ModulNbr].
 						s_PWMModuleInfo.
 						s_PWMInfo[b_PWM].b_TimingUnit;
-				}	// if (dw_Status & 0x10)
+				}	/*  if (dw_Status & 0x10) */
 				else {
-		    /***********************/
+					/***********************/
 					/* PWM not initialised */
-		    /***********************/
+					/***********************/
 					DPRINTK("PWM not initialised\n");
 					i_ReturnValue = -5;
-				}	// if (dw_Status & 0x10)
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+				}	/*  if (dw_Status & 0x10) */
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 			else {
-		 /******************************/
+				/******************************/
 				/* Tor PWM selection is wrong */
-		 /******************************/
+				/******************************/
 				DPRINTK("Tor PWM selection is wrong\n");
 				i_ReturnValue = -4;
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 		} else {
-	      /**********************************/
+			/**********************************/
 			/* The module is not a PWM module */
-	      /**********************************/
+			/**********************************/
 			DPRINTK("The module is not a PWM module\n");
 			i_ReturnValue = -3;
 		}
 	} else {
-	   /***********************/
+		/***********************/
 		/* Module number error */
-	   /***********************/
+		/***********************/
 		DPRINTK("Module number error\n");
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -1683,33 +1683,33 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnWritePWM(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnWritePWM(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	BYTE b_WriteType;
-	INT i_ReturnValue = 0;
+	unsigned char b_WriteType;
+	int i_ReturnValue = 0;
 	b_WriteType = CR_CHAN(insn->chanspec);
 
 	switch (b_WriteType) {
 	case APCI1710_PWM_ENABLE:
 		i_ReturnValue = i_APCI1710_EnablePWM(dev,
-			(BYTE) CR_AREF(insn->chanspec),
-			(BYTE) data[0],
-			(BYTE) data[1],
-			(BYTE) data[2],
-			(BYTE) data[3], (BYTE) data[4], (BYTE) data[5]);
+			(unsigned char) CR_AREF(insn->chanspec),
+			(unsigned char) data[0],
+			(unsigned char) data[1],
+			(unsigned char) data[2],
+			(unsigned char) data[3], (unsigned char) data[4], (unsigned char) data[5]);
 		break;
 
 	case APCI1710_PWM_DISABLE:
 		i_ReturnValue = i_APCI1710_DisablePWM(dev,
-			(BYTE) CR_AREF(insn->chanspec), (BYTE) data[0]);
+			(unsigned char) CR_AREF(insn->chanspec), (unsigned char) data[0]);
 		break;
 
 	case APCI1710_PWM_NEWTIMING:
 		i_ReturnValue = i_APCI1710_SetNewPWMTiming(dev,
-			(BYTE) CR_AREF(insn->chanspec),
-			(BYTE) data[0],
-			(BYTE) data[1], (ULONG) data[2], (ULONG) data[3]);
+			(unsigned char) CR_AREF(insn->chanspec),
+			(unsigned char) data[0],
+			(unsigned char) data[1], (unsigned int) data[2], (unsigned int) data[3]);
 		break;
 
 	default:
@@ -1718,20 +1718,20 @@
 
 	if (i_ReturnValue >= 0)
 		i_ReturnValue = insn->n;
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_     i_APCI1710_EnablePWM                         |
-|                                       (BYTE_  b_BoardHandle,               |
-|                                        BYTE_  b_ModulNbr,                  |
-|                                        BYTE_  b_PWM,                       |
-|                                        BYTE_  b_StartLevel,                |
-|                                        BYTE_  b_StopMode,                  |
-|                                        BYTE_  b_StopLevel,                 |
-|                                        BYTE_  b_ExternGate,                |
-|                                        BYTE_  b_InterruptEnable)           |
+|                                       (unsigned char_  b_BoardHandle,               |
+|                                        unsigned char_  b_ModulNbr,                  |
+|                                        unsigned char_  b_PWM,                       |
+|                                        unsigned char_  b_StartLevel,                |
+|                                        unsigned char_  b_StopMode,                  |
+|                                        unsigned char_  b_StopLevel,                 |
+|                                        unsigned char_  b_ExternGate,                |
+|                                        unsigned char_  b_InterruptEnable)           |
 +----------------------------------------------------------------------------+
 | Task              : Enable the selected PWM (b_PWM) from selected module   |
 |                     (b_ModulNbr). You must calling the "i_APCI1710_InitPWM"|
@@ -1741,16 +1741,16 @@
 |                     See function "i_APCI1710_SetBoardIntRoutineX" and the  |
 |                     Interrupt mask description chapter.                    |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle     : Handle of board APCI-1710    |
-|                     BYTE_ b_ModulNbr        : Selected module number       |
+| Input Parameters  : unsigned char_ b_BoardHandle     : Handle of board APCI-1710    |
+|                     unsigned char_ b_ModulNbr        : Selected module number       |
 |                                               (0 to 3)                     |
-|                     BYTE_ b_PWM             : Selected PWM (0 or 1)        |
-|                     BYTE_ b_StartLevel      : Start period level selection |
+|                     unsigned char_ b_PWM             : Selected PWM (0 or 1)        |
+|                     unsigned char_ b_StartLevel      : Start period level selection |
 |                                                0 : The period start with a |
 |                                                    low level               |
 |                                                1 : The period start with a |
 |                                                    high level              |
-|                     BYTE_ b_StopMode        : Stop mode selection          |
+|                     unsigned char_ b_StopMode        : Stop mode selection          |
 |                                                0 : The PWM is stopped      |
 |                                                    directly after the      |
 |                                                    "i_APCI1710_DisablePWM" |
@@ -1761,7 +1761,7 @@
 |                                                     function the PWM is    |
 |                                                     stopped at the end from|
 |                                                     last period cycle.     |
-|                     BYTE_ b_StopLevel       : Stop PWM level selection     |
+|                     unsigned char_ b_StopLevel       : Stop PWM level selection     |
 |                                                0 : The output signal keep  |
 |                                                    the level after the     |
 |                                                    "i_APCI1710_DisablePWM" |
@@ -1774,11 +1774,11 @@
 |                                                    to high after the       |
 |                                                    "i_APCI1710_DisablePWM" |
 |                                                    function                |
-|                     BYTE_ b_ExternGate      : Extern gate action selection |
+|                     unsigned char_ b_ExternGate      : Extern gate action selection |
 |                                                0 : Extern gate signal not  |
 |                                                    used.                   |
 |                                                1 : Extern gate signal used.|
-|                     BYTE_ b_InterruptEnable : Enable or disable the PWM    |
+|                     unsigned char_ b_InterruptEnable : Enable or disable the PWM    |
 |                                               interrupt.                   |
 |                                               - APCI1710_ENABLE :          |
 |                                                 Enable the PWM interrupt   |
@@ -1806,77 +1806,77 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_EnablePWM(struct comedi_device * dev,
-	BYTE b_ModulNbr,
-	BYTE b_PWM,
-	BYTE b_StartLevel,
-	BYTE b_StopMode,
-	BYTE b_StopLevel, BYTE b_ExternGate, BYTE b_InterruptEnable)
+int i_APCI1710_EnablePWM(struct comedi_device *dev,
+	unsigned char b_ModulNbr,
+	unsigned char b_PWM,
+	unsigned char b_StartLevel,
+	unsigned char b_StopMode,
+	unsigned char b_StopLevel, unsigned char b_ExternGate, unsigned char b_InterruptEnable)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_Status;
-	DWORD dw_Command;
+	int i_ReturnValue = 0;
+	unsigned int dw_Status;
+	unsigned int dw_Command;
 
-	devpriv->tsk_Current = current;	// Save the current process task structure
+	devpriv->tsk_Current = current;	/*  Save the current process task structure */
 	/**************************/
 	/* Test the module number */
 	/**************************/
 
 	if (b_ModulNbr < 4) {
-	   /***************/
+		/***************/
 		/* Test if PWM */
-	   /***************/
+		/***************/
 
 		if ((devpriv->s_BoardInfos.
 				dw_MolduleConfiguration[b_ModulNbr] &
 				0xFFFF0000UL) == APCI1710_PWM) {
-	      /**************************/
+			/**************************/
 			/* Test the PWM selection */
-	      /**************************/
+			/**************************/
 
 			if (b_PWM <= 1) {
-		 /***************************/
+				/***************************/
 				/* Test if PWM initialised */
-		 /***************************/
+				/***************************/
 
 				dw_Status = inl(devpriv->s_BoardInfos.
 					ui_Address + 12 + (20 * b_PWM) +
 					(64 * b_ModulNbr));
 
 				if (dw_Status & 0x10) {
-		    /**********************************/
+					/**********************************/
 					/* Test the start level selection */
-		    /**********************************/
+					/**********************************/
 
 					if (b_StartLevel <= 1) {
-		       /**********************/
+						/**********************/
 						/* Test the stop mode */
-		       /**********************/
+						/**********************/
 
 						if (b_StopMode <= 1) {
-			  /***********************/
+							/***********************/
 							/* Test the stop level */
-			  /***********************/
+							/***********************/
 
 							if (b_StopLevel <= 2) {
-			     /*****************************/
+								/*****************************/
 								/* Test the extern gate mode */
-			     /*****************************/
+								/*****************************/
 
 								if (b_ExternGate
 									<= 1) {
-				/*****************************/
+									/*****************************/
 									/* Test the interrupt action */
-				/*****************************/
+									/*****************************/
 
 									if (b_InterruptEnable == APCI1710_ENABLE || b_InterruptEnable == APCI1710_DISABLE) {
-				   /******************************************/
+										/******************************************/
 										/* Test if interrupt function initialised */
-				   /******************************************/
+										/******************************************/
 
-				      /********************/
+										/********************/
 										/* Read the command */
-				      /********************/
+										/********************/
 
 										dw_Command
 											=
@@ -1895,9 +1895,9 @@
 											&
 											0x80;
 
-				      /********************/
+										/********************/
 										/* Make the command */
-				      /********************/
+										/********************/
 
 										dw_Command
 											=
@@ -1943,100 +1943,100 @@
 											=
 											b_InterruptEnable;
 
-				      /*******************/
+										/*******************/
 										/* Set the command */
-				      /*******************/
+										/*******************/
 
 										outl(dw_Command, devpriv->s_BoardInfos.ui_Address + 8 + (20 * b_PWM) + (64 * b_ModulNbr));
 
-				      /******************/
+										/******************/
 										/* Enable the PWM */
-				      /******************/
+										/******************/
 										outl(1, devpriv->s_BoardInfos.ui_Address + 12 + (20 * b_PWM) + (64 * b_ModulNbr));
-									}	// if (b_InterruptEnable == APCI1710_ENABLE || b_InterruptEnable == APCI1710_DISABLE)
+									}	/*  if (b_InterruptEnable == APCI1710_ENABLE || b_InterruptEnable == APCI1710_DISABLE) */
 									else {
-				   /********************************/
+										/********************************/
 										/* Interrupt parameter is wrong */
-				   /********************************/
+										/********************************/
 										DPRINTK("Interrupt parameter is wrong\n");
 										i_ReturnValue
 											=
 											-10;
-									}	// if (b_InterruptEnable == APCI1710_ENABLE || b_InterruptEnable == APCI1710_DISABLE)
-								}	// if (b_ExternGate >= 0 && b_ExternGate <= 1)
+									}	/*  if (b_InterruptEnable == APCI1710_ENABLE || b_InterruptEnable == APCI1710_DISABLE) */
+								}	/*  if (b_ExternGate >= 0 && b_ExternGate <= 1) */
 								else {
-				/*****************************************/
+									/*****************************************/
 									/* Extern gate signal selection is wrong */
-				/*****************************************/
+									/*****************************************/
 									DPRINTK("Extern gate signal selection is wrong\n");
 									i_ReturnValue
 										=
 										-9;
-								}	// if (b_ExternGate >= 0 && b_ExternGate <= 1)
-							}	// if (b_StopLevel >= 0 && b_StopLevel <= 2)
+								}	/*  if (b_ExternGate >= 0 && b_ExternGate <= 1) */
+							}	/*  if (b_StopLevel >= 0 && b_StopLevel <= 2) */
 							else {
-			     /*************************************/
+								/*************************************/
 								/* PWM stop level selection is wrong */
-			     /*************************************/
+								/*************************************/
 								DPRINTK("PWM stop level selection is wrong\n");
 								i_ReturnValue =
 									-8;
-							}	// if (b_StopLevel >= 0 && b_StopLevel <= 2)
-						}	// if (b_StopMode >= 0 && b_StopMode <= 1)
+							}	/*  if (b_StopLevel >= 0 && b_StopLevel <= 2) */
+						}	/*  if (b_StopMode >= 0 && b_StopMode <= 1) */
 						else {
-			  /************************************/
+							/************************************/
 							/* PWM stop mode selection is wrong */
-			  /************************************/
+							/************************************/
 							DPRINTK("PWM stop mode selection is wrong\n");
 							i_ReturnValue = -7;
-						}	// if (b_StopMode >= 0 && b_StopMode <= 1)
-					}	// if (b_StartLevel >= 0 && b_StartLevel <= 1)
+						}	/*  if (b_StopMode >= 0 && b_StopMode <= 1) */
+					}	/*  if (b_StartLevel >= 0 && b_StartLevel <= 1) */
 					else {
-		       /**************************************/
+						/**************************************/
 						/* PWM start level selection is wrong */
-		       /**************************************/
+						/**************************************/
 						DPRINTK("PWM start level selection is wrong\n");
 						i_ReturnValue = -6;
-					}	// if (b_StartLevel >= 0 && b_StartLevel <= 1)
-				}	// if (dw_Status & 0x10)
+					}	/*  if (b_StartLevel >= 0 && b_StartLevel <= 1) */
+				}	/*  if (dw_Status & 0x10) */
 				else {
-		    /***********************/
+					/***********************/
 					/* PWM not initialised */
-		    /***********************/
+					/***********************/
 					DPRINTK("PWM not initialised\n");
 					i_ReturnValue = -5;
-				}	// if (dw_Status & 0x10)
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+				}	/*  if (dw_Status & 0x10) */
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 			else {
-		 /******************************/
+				/******************************/
 				/* Tor PWM selection is wrong */
-		 /******************************/
+				/******************************/
 				DPRINTK("Tor PWM selection is wrong\n");
 				i_ReturnValue = -4;
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 		} else {
-	      /**********************************/
+			/**********************************/
 			/* The module is not a PWM module */
-	      /**********************************/
+			/**********************************/
 			DPRINTK("The module is not a PWM module\n");
 			i_ReturnValue = -3;
 		}
 	} else {
-	   /***********************/
+		/***********************/
 		/* Module number error */
-	   /***********************/
+		/***********************/
 		DPRINTK("Module number error\n");
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : _INT_ i_APCI1710_DisablePWM (BYTE_  b_BoardHandle,     |
-|                                                  BYTE_  b_ModulNbr,        |
-|                                                  BYTE_  b_PWM)             |
+| Function Name     : _INT_ i_APCI1710_DisablePWM (unsigned char_  b_BoardHandle,     |
+|                                                  unsigned char_  b_ModulNbr,        |
+|                                                  unsigned char_  b_PWM)             |
 +----------------------------------------------------------------------------+
 | Task              : Disable the selected PWM (b_PWM) from selected module  |
 |                     (b_ModulNbr). The output signal level depend of the    |
@@ -2045,8 +2045,8 @@
 |                     parameters from this function.                         |
 +----------------------------------------------------------------------------+
 | Input Parameters  :BYTE_ b_BoardHandle : Handle of board APCI-1710         |
-|                    BYTE_ b_ModulNbr    : Selected module number (0 to 3)   |
-|                    BYTE_ b_PWM         : Selected PWM (0 or 1)             |
+|                    unsigned char_ b_ModulNbr    : Selected module number (0 to 3)   |
+|                    unsigned char_ b_PWM         : Selected PWM (0 or 1)             |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -2062,99 +2062,99 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_DisablePWM(struct comedi_device * dev, BYTE b_ModulNbr, BYTE b_PWM)
+int i_APCI1710_DisablePWM(struct comedi_device *dev, unsigned char b_ModulNbr, unsigned char b_PWM)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_Status;
+	int i_ReturnValue = 0;
+	unsigned int dw_Status;
 
 	/**************************/
 	/* Test the module number */
 	/**************************/
 
 	if (b_ModulNbr < 4) {
-	   /***************/
+		/***************/
 		/* Test if PWM */
-	   /***************/
+		/***************/
 
 		if ((devpriv->s_BoardInfos.
 				dw_MolduleConfiguration[b_ModulNbr] &
 				0xFFFF0000UL) == APCI1710_PWM) {
-	      /**************************/
+			/**************************/
 			/* Test the PWM selection */
-	      /**************************/
+			/**************************/
 
 			if (b_PWM <= 1) {
-		 /***************************/
+				/***************************/
 				/* Test if PWM initialised */
-		 /***************************/
+				/***************************/
 
 				dw_Status = inl(devpriv->s_BoardInfos.
 					ui_Address + 12 + (20 * b_PWM) +
 					(64 * b_ModulNbr));
 
 				if (dw_Status & 0x10) {
-		    /***********************/
+					/***********************/
 					/* Test if PWM enabled */
-		    /***********************/
+					/***********************/
 
 					if (dw_Status & 0x1) {
-		       /*******************/
+						/*******************/
 						/* Disable the PWM */
-		       /*******************/
+						/*******************/
 						outl(0, devpriv->s_BoardInfos.
 							ui_Address + 12 +
 							(20 * b_PWM) +
 							(64 * b_ModulNbr));
-					}	// if (dw_Status & 0x1)
+					}	/*  if (dw_Status & 0x1) */
 					else {
-		       /*******************/
+						/*******************/
 						/* PWM not enabled */
-		       /*******************/
+						/*******************/
 						DPRINTK("PWM not enabled\n");
 						i_ReturnValue = -6;
-					}	// if (dw_Status & 0x1)
-				}	// if (dw_Status & 0x10)
+					}	/*  if (dw_Status & 0x1) */
+				}	/*  if (dw_Status & 0x10) */
 				else {
-		    /***********************/
+					/***********************/
 					/* PWM not initialised */
-		    /***********************/
+					/***********************/
 					DPRINTK(" PWM not initialised\n");
 					i_ReturnValue = -5;
-				}	// if (dw_Status & 0x10)
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+				}	/*  if (dw_Status & 0x10) */
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 			else {
-		 /******************************/
+				/******************************/
 				/* Tor PWM selection is wrong */
-		 /******************************/
+				/******************************/
 				DPRINTK("Tor PWM selection is wrong\n");
 				i_ReturnValue = -4;
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 		} else {
-	      /**********************************/
+			/**********************************/
 			/* The module is not a PWM module */
-	      /**********************************/
+			/**********************************/
 			DPRINTK("The module is not a PWM module\n");
 			i_ReturnValue = -3;
 		}
 	} else {
-	   /***********************/
+		/***********************/
 		/* Module number error */
-	   /***********************/
+		/***********************/
 		DPRINTK("Module number error\n");
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_SetNewPWMTiming                       |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
-|                                        BYTE_     b_PWM,                    |
-|                                        BYTE_     b_ClockSelection,         |
-|                                        BYTE_     b_TimingUnit,             |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
+|                                        unsigned char_     b_PWM,                    |
+|                                        unsigned char_     b_ClockSelection,         |
+|                                        unsigned char_     b_TimingUnit,             |
 |                                        ULONG_   ul_LowTiming,              |
 |                                        ULONG_   ul_HighTiming)             |
 +----------------------------------------------------------------------------+
@@ -2162,11 +2162,11 @@
 |                     ul_TimingUnit determine the low/high timing base for   |
 |                     the period.                                            |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_     b_BoardHandle    : Handle of board APCI-1710 |
-|                     BYTE_     b_ModulNbr       : Module number to configure|
+| Input Parameters  : unsigned char_     b_BoardHandle    : Handle of board APCI-1710 |
+|                     unsigned char_     b_ModulNbr       : Module number to configure|
 |                                                  (0 to 3)                  |
-|                     BYTE_     b_PWM            : Selected PWM (0 or 1).    |
-|                     BYTE_     b_TimingUnit     : Base timing Unit (0 to 4) |
+|                     unsigned char_     b_PWM            : Selected PWM (0 or 1).    |
+|                     unsigned char_     b_TimingUnit     : Base timing Unit (0 to 4) |
 |                                                       0 : ns               |
 |                                                       1 : æs               |
 |                                                       2 : ms               |
@@ -2189,18 +2189,18 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_SetNewPWMTiming(struct comedi_device * dev,
-	BYTE b_ModulNbr,
-	BYTE b_PWM, BYTE b_TimingUnit, ULONG ul_LowTiming, ULONG ul_HighTiming)
+int i_APCI1710_SetNewPWMTiming(struct comedi_device *dev,
+	unsigned char b_ModulNbr,
+	unsigned char b_PWM, unsigned char b_TimingUnit, unsigned int ul_LowTiming, unsigned int ul_HighTiming)
 {
-	BYTE b_ClockSelection;
-	INT i_ReturnValue = 0;
-	ULONG ul_LowTimerValue = 0;
-	ULONG ul_HighTimerValue = 0;
-	ULONG ul_RealLowTiming = 0;
-	ULONG ul_RealHighTiming = 0;
-	DWORD dw_Status;
-	DWORD dw_Command;
+	unsigned char b_ClockSelection;
+	int i_ReturnValue = 0;
+	unsigned int ul_LowTimerValue = 0;
+	unsigned int ul_HighTimerValue = 0;
+	unsigned int ul_RealLowTiming = 0;
+	unsigned int ul_RealHighTiming = 0;
+	unsigned int dw_Status;
+	unsigned int dw_Command;
 	double d_RealLowTiming = 0;
 	double d_RealHighTiming = 0;
 
@@ -2209,21 +2209,21 @@
 	/**************************/
 
 	if (b_ModulNbr < 4) {
-	   /***************/
+		/***************/
 		/* Test if PWM */
-	   /***************/
+		/***************/
 
 		if ((devpriv->s_BoardInfos.
 				dw_MolduleConfiguration[b_ModulNbr] &
 				0xFFFF0000UL) == APCI1710_PWM) {
-	      /**************************/
+			/**************************/
 			/* Test the PWM selection */
-	      /**************************/
+			/**************************/
 
 			if (b_PWM <= 1) {
-		 /***************************/
+				/***************************/
 				/* Test if PWM initialised */
-		 /***************************/
+				/***************************/
 
 				dw_Status = inl(devpriv->s_BoardInfos.
 					ui_Address + 12 + (20 * b_PWM) +
@@ -2235,14 +2235,14 @@
 						s_PWMModuleInfo.
 						b_ClockSelection;
 
-		    /************************/
+					/************************/
 					/* Test the timing unit */
-		    /************************/
+					/************************/
 
 					if (b_TimingUnit <= 4) {
-		       /*********************************/
+						/*********************************/
 						/* Test the low timing selection */
-		       /*********************************/
+						/*********************************/
 
 						if (((b_ClockSelection ==
 									APCI1710_30MHZ)
@@ -2377,37 +2377,37 @@
 								&& (ul_LowTiming
 									<=
 									7UL))) {
-			  /**********************************/
+							/**********************************/
 							/* Test the High timing selection */
-			  /**********************************/
+							/**********************************/
 
 							if (((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 266) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571230650UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571230UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 9UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 242) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 519691043UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 519691UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 520UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 8UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 200) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429496729UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429496UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 7UL))) {
-			     /************************************/
+								/************************************/
 								/* Calculate the low division fator */
-			     /************************************/
+								/************************************/
 
 								fpu_begin();
 								switch (b_TimingUnit) {
-				/******/
+									/******/
 									/* ns */
-				/******/
+									/******/
 
 								case 0:
 
-					/******************/
+									/******************/
 									/* Timer 0 factor */
-					/******************/
+									/******************/
 
 									ul_LowTimerValue
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_LowTiming
 										*
 										(0.00025 * b_ClockSelection));
 
-					/*******************/
+									/*******************/
 									/* Round the value */
-					/*******************/
+									/*******************/
 
 									if ((double)((double)ul_LowTiming * (0.00025 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
 										ul_LowTimerValue
@@ -2417,13 +2417,13 @@
 											1;
 									}
 
-					/*****************************/
+									/*****************************/
 									/* Calculate the real timing */
-					/*****************************/
+									/*****************************/
 
 									ul_RealLowTiming
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_LowTimerValue
 										/
 										(0.00025 * (double)b_ClockSelection));
@@ -2459,7 +2459,7 @@
 									if (b_ClockSelection != APCI1710_40MHZ) {
 										ul_LowTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(double)
 											(ul_LowTimerValue)
@@ -2469,26 +2469,26 @@
 
 									break;
 
-				/******/
+									/******/
 									/* æs */
-				/******/
+									/******/
 
 								case 1:
 
-					/******************/
+									/******************/
 									/* Timer 0 factor */
-					/******************/
+									/******************/
 
 									ul_LowTimerValue
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_LowTiming
 										*
 										(0.25 * b_ClockSelection));
 
-					/*******************/
+									/*******************/
 									/* Round the value */
-					/*******************/
+									/*******************/
 
 									if ((double)((double)ul_LowTiming * (0.25 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
 										ul_LowTimerValue
@@ -2498,13 +2498,13 @@
 											1;
 									}
 
-					/*****************************/
+									/*****************************/
 									/* Calculate the real timing */
-					/*****************************/
+									/*****************************/
 
 									ul_RealLowTiming
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_LowTimerValue
 										/
 										(0.25 * (double)b_ClockSelection));
@@ -2542,7 +2542,7 @@
 									if (b_ClockSelection != APCI1710_40MHZ) {
 										ul_LowTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(double)
 											(ul_LowTimerValue)
@@ -2552,15 +2552,15 @@
 
 									break;
 
-				/******/
+									/******/
 									/* ms */
-				/******/
+									/******/
 
 								case 2:
 
-					/******************/
+									/******************/
 									/* Timer 0 factor */
-					/******************/
+									/******************/
 
 									ul_LowTimerValue
 										=
@@ -2570,9 +2570,9 @@
 										*
 										b_ClockSelection);
 
-					/*******************/
+									/*******************/
 									/* Round the value */
-					/*******************/
+									/*******************/
 
 									if ((double)((double)ul_LowTiming * (250.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
 										ul_LowTimerValue
@@ -2582,13 +2582,13 @@
 											1;
 									}
 
-					/*****************************/
+									/*****************************/
 									/* Calculate the real timing */
-					/*****************************/
+									/*****************************/
 
 									ul_RealLowTiming
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_LowTimerValue
 										/
 										(250.0 * (double)b_ClockSelection));
@@ -2624,7 +2624,7 @@
 									if (b_ClockSelection != APCI1710_40MHZ) {
 										ul_LowTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(double)
 											(ul_LowTimerValue)
@@ -2634,28 +2634,28 @@
 
 									break;
 
-				/*****/
+									/*****/
 									/* s */
-				/*****/
+									/*****/
 
 								case 3:
 
-					/******************/
+									/******************/
 									/* Timer 0 factor */
-					/******************/
+									/******************/
 
 									ul_LowTimerValue
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_LowTiming
 										*
 										(250000.0
 											*
 											b_ClockSelection));
 
-					/*******************/
+									/*******************/
 									/* Round the value */
-					/*******************/
+									/*******************/
 
 									if ((double)((double)ul_LowTiming * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
 										ul_LowTimerValue
@@ -2665,13 +2665,13 @@
 											1;
 									}
 
-					/*****************************/
+									/*****************************/
 									/* Calculate the real timing */
-					/*****************************/
+									/*****************************/
 
 									ul_RealLowTiming
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_LowTimerValue
 										/
 										(250000.0
@@ -2710,7 +2710,7 @@
 									if (b_ClockSelection != APCI1710_40MHZ) {
 										ul_LowTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(double)
 											(ul_LowTimerValue)
@@ -2720,19 +2720,19 @@
 
 									break;
 
-				/******/
+									/******/
 									/* mn */
-				/******/
+									/******/
 
 								case 4:
 
-					/******************/
+									/******************/
 									/* Timer 0 factor */
-					/******************/
+									/******************/
 
 									ul_LowTimerValue
 										=
-										(ULONG)
+										(unsigned int)
 										(
 										(ul_LowTiming
 											*
@@ -2742,9 +2742,9 @@
 											*
 											b_ClockSelection));
 
-					/*******************/
+									/*******************/
 									/* Round the value */
-					/*******************/
+									/*******************/
 
 									if ((double)((double)(ul_LowTiming * 60.0) * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
 										ul_LowTimerValue
@@ -2754,13 +2754,13 @@
 											1;
 									}
 
-					/*****************************/
+									/*****************************/
 									/* Calculate the real timing */
-					/*****************************/
+									/*****************************/
 
 									ul_RealLowTiming
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_LowTimerValue
 										/
 										(250000.0
@@ -2804,7 +2804,7 @@
 									if (b_ClockSelection != APCI1710_40MHZ) {
 										ul_LowTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(double)
 											(ul_LowTimerValue)
@@ -2815,31 +2815,31 @@
 									break;
 								}
 
-			     /*************************************/
+								/*************************************/
 								/* Calculate the high division fator */
-			     /*************************************/
+								/*************************************/
 
 								switch (b_TimingUnit) {
-				/******/
+									/******/
 									/* ns */
-				/******/
+									/******/
 
 								case 0:
 
-					/******************/
+									/******************/
 									/* Timer 0 factor */
-					/******************/
+									/******************/
 
 									ul_HighTimerValue
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_HighTiming
 										*
 										(0.00025 * b_ClockSelection));
 
-					/*******************/
+									/*******************/
 									/* Round the value */
-					/*******************/
+									/*******************/
 
 									if ((double)((double)ul_HighTiming * (0.00025 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
 										ul_HighTimerValue
@@ -2849,13 +2849,13 @@
 											1;
 									}
 
-					/*****************************/
+									/*****************************/
 									/* Calculate the real timing */
-					/*****************************/
+									/*****************************/
 
 									ul_RealHighTiming
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_HighTimerValue
 										/
 										(0.00025 * (double)b_ClockSelection));
@@ -2891,7 +2891,7 @@
 									if (b_ClockSelection != APCI1710_40MHZ) {
 										ul_HighTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(double)
 											(ul_HighTimerValue)
@@ -2901,26 +2901,26 @@
 
 									break;
 
-				/******/
+									/******/
 									/* æs */
-				/******/
+									/******/
 
 								case 1:
 
-					/******************/
+									/******************/
 									/* Timer 0 factor */
-					/******************/
+									/******************/
 
 									ul_HighTimerValue
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_HighTiming
 										*
 										(0.25 * b_ClockSelection));
 
-					/*******************/
+									/*******************/
 									/* Round the value */
-					/*******************/
+									/*******************/
 
 									if ((double)((double)ul_HighTiming * (0.25 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
 										ul_HighTimerValue
@@ -2930,13 +2930,13 @@
 											1;
 									}
 
-					/*****************************/
+									/*****************************/
 									/* Calculate the real timing */
-					/*****************************/
+									/*****************************/
 
 									ul_RealHighTiming
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_HighTimerValue
 										/
 										(0.25 * (double)b_ClockSelection));
@@ -2974,7 +2974,7 @@
 									if (b_ClockSelection != APCI1710_40MHZ) {
 										ul_HighTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(double)
 											(ul_HighTimerValue)
@@ -2984,15 +2984,15 @@
 
 									break;
 
-				/******/
+									/******/
 									/* ms */
-				/******/
+									/******/
 
 								case 2:
 
-					/******************/
+									/******************/
 									/* Timer 0 factor */
-					/******************/
+									/******************/
 
 									ul_HighTimerValue
 										=
@@ -3002,9 +3002,9 @@
 										*
 										b_ClockSelection);
 
-					/*******************/
+									/*******************/
 									/* Round the value */
-					/*******************/
+									/*******************/
 
 									if ((double)((double)ul_HighTiming * (250.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
 										ul_HighTimerValue
@@ -3014,13 +3014,13 @@
 											1;
 									}
 
-					/*****************************/
+									/*****************************/
 									/* Calculate the real timing */
-					/*****************************/
+									/*****************************/
 
 									ul_RealHighTiming
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_HighTimerValue
 										/
 										(250.0 * (double)b_ClockSelection));
@@ -3056,7 +3056,7 @@
 									if (b_ClockSelection != APCI1710_40MHZ) {
 										ul_HighTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(double)
 											(ul_HighTimerValue)
@@ -3066,28 +3066,28 @@
 
 									break;
 
-				/*****/
+									/*****/
 									/* s */
-				/*****/
+									/*****/
 
 								case 3:
 
-					/******************/
+									/******************/
 									/* Timer 0 factor */
-					/******************/
+									/******************/
 
 									ul_HighTimerValue
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_HighTiming
 										*
 										(250000.0
 											*
 											b_ClockSelection));
 
-					/*******************/
+									/*******************/
 									/* Round the value */
-					/*******************/
+									/*******************/
 
 									if ((double)((double)ul_HighTiming * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
 										ul_HighTimerValue
@@ -3097,13 +3097,13 @@
 											1;
 									}
 
-					/*****************************/
+									/*****************************/
 									/* Calculate the real timing */
-					/*****************************/
+									/*****************************/
 
 									ul_RealHighTiming
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_HighTimerValue
 										/
 										(250000.0
@@ -3142,7 +3142,7 @@
 									if (b_ClockSelection != APCI1710_40MHZ) {
 										ul_HighTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(double)
 											(ul_HighTimerValue)
@@ -3152,19 +3152,19 @@
 
 									break;
 
-				/******/
+									/******/
 									/* mn */
-				/******/
+									/******/
 
 								case 4:
 
-					/******************/
+									/******************/
 									/* Timer 0 factor */
-					/******************/
+									/******************/
 
 									ul_HighTimerValue
 										=
-										(ULONG)
+										(unsigned int)
 										(
 										(ul_HighTiming
 											*
@@ -3174,9 +3174,9 @@
 											*
 											b_ClockSelection));
 
-					/*******************/
+									/*******************/
 									/* Round the value */
-					/*******************/
+									/*******************/
 
 									if ((double)((double)(ul_HighTiming * 60.0) * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
 										ul_HighTimerValue
@@ -3186,13 +3186,13 @@
 											1;
 									}
 
-					/*****************************/
+									/*****************************/
 									/* Calculate the real timing */
-					/*****************************/
+									/*****************************/
 
 									ul_RealHighTiming
 										=
-										(ULONG)
+										(unsigned int)
 										(ul_HighTimerValue
 										/
 										(250000.0
@@ -3236,7 +3236,7 @@
 									if (b_ClockSelection != APCI1710_40MHZ) {
 										ul_HighTimerValue
 											=
-											(ULONG)
+											(unsigned int)
 											(
 											(double)
 											(ul_HighTimerValue)
@@ -3249,9 +3249,9 @@
 
 								fpu_end();
 
-			     /************************/
+								/************************/
 								/* Save the timing unit */
-			     /************************/
+								/************************/
 
 								devpriv->
 									s_ModuleInfo
@@ -3263,9 +3263,9 @@
 									=
 									b_TimingUnit;
 
-			     /****************************/
+								/****************************/
 								/* Save the low base timing */
-			     /****************************/
+								/****************************/
 
 								devpriv->
 									s_ModuleInfo
@@ -3287,9 +3287,9 @@
 									=
 									ul_RealLowTiming;
 
-			     /****************************/
+								/****************************/
 								/* Save the high base timing */
-			     /****************************/
+								/****************************/
 
 								devpriv->
 									s_ModuleInfo
@@ -3311,21 +3311,21 @@
 									=
 									ul_RealHighTiming;
 
-			     /************************/
+								/************************/
 								/* Write the low timing */
-			     /************************/
+								/************************/
 
 								outl(ul_LowTimerValue, devpriv->s_BoardInfos.ui_Address + 0 + (20 * b_PWM) + (64 * b_ModulNbr));
 
-			     /*************************/
+								/*************************/
 								/* Write the high timing */
-			     /*************************/
+								/*************************/
 
 								outl(ul_HighTimerValue, devpriv->s_BoardInfos.ui_Address + 4 + (20 * b_PWM) + (64 * b_ModulNbr));
 
-			     /***************************/
+								/***************************/
 								/* Set the clock selection */
-			     /***************************/
+								/***************************/
 
 								dw_Command =
 									inl
@@ -3347,9 +3347,9 @@
 										0x80;
 								}
 
-			     /***************************/
+								/***************************/
 								/* Set the clock selection */
-			     /***************************/
+								/***************************/
 
 								outl(dw_Command,
 									devpriv->
@@ -3358,96 +3358,96 @@
 									+ 8 +
 									(20 * b_PWM) + (64 * b_ModulNbr));
 							} else {
-			     /***************************************/
+								/***************************************/
 								/* High base timing selection is wrong */
-			     /***************************************/
+								/***************************************/
 								DPRINTK("High base timing selection is wrong\n");
 								i_ReturnValue =
 									-8;
 							}
 						} else {
-			  /**************************************/
+							/**************************************/
 							/* Low base timing selection is wrong */
-			  /**************************************/
+							/**************************************/
 							DPRINTK("Low base timing selection is wrong\n");
 							i_ReturnValue = -7;
 						}
-					}	// if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4))
+					}	/*  if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
 					else {
-		       /**********************************/
+						/**********************************/
 						/* Timing unit selection is wrong */
-		       /**********************************/
+						/**********************************/
 						DPRINTK("Timing unit selection is wrong\n");
 						i_ReturnValue = -6;
-					}	// if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4))
-				}	// if (dw_Status & 0x10)
+					}	/*  if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
+				}	/*  if (dw_Status & 0x10) */
 				else {
-		    /***********************/
+					/***********************/
 					/* PWM not initialised */
-		    /***********************/
+					/***********************/
 					DPRINTK("PWM not initialised\n");
 					i_ReturnValue = -5;
-				}	// if (dw_Status & 0x10)
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+				}	/*  if (dw_Status & 0x10) */
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 			else {
-		 /******************************/
+				/******************************/
 				/* Tor PWM selection is wrong */
-		 /******************************/
+				/******************************/
 				DPRINTK("Tor PWM selection is wrong\n");
 				i_ReturnValue = -4;
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 		} else {
-	      /**********************************/
+			/**********************************/
 			/* The module is not a PWM module */
-	      /**********************************/
+			/**********************************/
 			DPRINTK("The module is not a PWM module\n");
 			i_ReturnValue = -3;
 		}
 	} else {
-	   /***********************/
+		/***********************/
 		/* Module number error */
-	   /***********************/
+		/***********************/
 		DPRINTK("Module number error\n");
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_GetPWMStatus                          |
-|                               (BYTE_    b_BoardHandle,                     |
-|                                BYTE_    b_ModulNbr,                        |
-|                                BYTE_    b_PWM,                             |
-|                                PBYTE_  pb_PWMOutputStatus,                 |
-|                                PBYTE_  pb_ExternGateStatus)                |
+|                               (unsigned char_    b_BoardHandle,                     |
+|                                unsigned char_    b_ModulNbr,                        |
+|                                unsigned char_    b_PWM,                             |
+|                                unsigned char *_  pb_PWMOutputStatus,                 |
+|                                unsigned char *_  pb_ExternGateStatus)                |
 +----------------------------------------------------------------------------+
 | Task              : Return the status from selected PWM (b_PWM) from       |
 |                     selected module (b_ModulNbr).                          |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_  b_BoardHandle : Handle of board APCI-1710       |
-|                     BYTE_  b_PWM         : Selected PWM (0 or 1)           |
-|                     BYTE_  b_ModulNbr    : Selected module number (0 to 3)
-	b_ModulNbr			=(BYTE)  CR_AREF(insn->chanspec);
-	b_PWM				=(BYTE)  data[0];
+| Input Parameters  : unsigned char_  b_BoardHandle : Handle of board APCI-1710       |
+|                     unsigned char_  b_PWM         : Selected PWM (0 or 1)           |
+|                     unsigned char_  b_ModulNbr    : Selected module number (0 to 3)
+	b_ModulNbr			=(unsigned char)  CR_AREF(insn->chanspec);
+	b_PWM				=(unsigned char)  data[0];
 
  |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_  pb_PWMOutputStatus  : Return the PWM output    |
+| Output Parameters : unsigned char *_  pb_PWMOutputStatus  : Return the PWM output    |
 |                                                   level status.            |
 |                                                    0 : The PWM output level|
 |                                                        is low.             |
 |                                                    1 : The PWM output level|
 |                                                        is high.            |
-|                     PBYTE_  pb_ExternGateStatus : Return the extern gate   |
+|                     unsigned char *_  pb_ExternGateStatus : Return the extern gate   |
 |                                                   level status.            |
 |                                                    0 : The extern gate is  |
 |                                                        low.                |
 |                                                    1 : The extern gate is  |
 |                                                        high.
-    pb_PWMOutputStatus	=(PBYTE) data[0];
-	pb_ExternGateStatus =(PBYTE) data[1];             |
+    pb_PWMOutputStatus	=(unsigned char *) data[0];
+	pb_ExternGateStatus =(unsigned char *) data[1];             |
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
 |                     -1: The handle parameter of the board is wrong         |
@@ -3460,109 +3460,109 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnReadGetPWMStatus(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnReadGetPWMStatus(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_Status;
+	int i_ReturnValue = 0;
+	unsigned int dw_Status;
 
-	BYTE b_ModulNbr;
-	BYTE b_PWM;
-	PBYTE pb_PWMOutputStatus;
-	PBYTE pb_ExternGateStatus;
+	unsigned char b_ModulNbr;
+	unsigned char b_PWM;
+	unsigned char *pb_PWMOutputStatus;
+	unsigned char *pb_ExternGateStatus;
 
 	i_ReturnValue = insn->n;
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_PWM = (BYTE) CR_CHAN(insn->chanspec);
-	pb_PWMOutputStatus = (PBYTE) & data[0];
-	pb_ExternGateStatus = (PBYTE) & data[1];
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_PWM = (unsigned char) CR_CHAN(insn->chanspec);
+	pb_PWMOutputStatus = (unsigned char *) &data[0];
+	pb_ExternGateStatus = (unsigned char *) &data[1];
 
 	/**************************/
 	/* Test the module number */
 	/**************************/
 
 	if (b_ModulNbr < 4) {
-	   /***************/
+		/***************/
 		/* Test if PWM */
-	   /***************/
+		/***************/
 
 		if ((devpriv->s_BoardInfos.
 				dw_MolduleConfiguration[b_ModulNbr] &
 				0xFFFF0000UL) == APCI1710_PWM) {
-	      /**************************/
+			/**************************/
 			/* Test the PWM selection */
-	      /**************************/
+			/**************************/
 
 			if (b_PWM <= 1) {
-		 /***************************/
+				/***************************/
 				/* Test if PWM initialised */
-		 /***************************/
+				/***************************/
 
 				dw_Status = inl(devpriv->s_BoardInfos.
 					ui_Address + 12 + (20 * b_PWM) +
 					(64 * b_ModulNbr));
 
 				if (dw_Status & 0x10) {
-		    /***********************/
+					/***********************/
 					/* Test if PWM enabled */
-		    /***********************/
+					/***********************/
 
 					if (dw_Status & 0x1) {
 						*pb_PWMOutputStatus =
-							(BYTE) ((dw_Status >> 7)
+							(unsigned char) ((dw_Status >> 7)
 							& 1);
 						*pb_ExternGateStatus =
-							(BYTE) ((dw_Status >> 6)
+							(unsigned char) ((dw_Status >> 6)
 							& 1);
-					}	// if (dw_Status & 0x1)
+					}	/*  if (dw_Status & 0x1) */
 					else {
-		       /*******************/
+						/*******************/
 						/* PWM not enabled */
-		       /*******************/
+						/*******************/
 
 						DPRINTK("PWM not enabled \n");
 						i_ReturnValue = -6;
-					}	// if (dw_Status & 0x1)
-				}	// if (dw_Status & 0x10)
+					}	/*  if (dw_Status & 0x1) */
+				}	/*  if (dw_Status & 0x10) */
 				else {
-		    /***********************/
+					/***********************/
 					/* PWM not initialised */
-		    /***********************/
+					/***********************/
 
 					DPRINTK("PWM not initialised\n");
 					i_ReturnValue = -5;
-				}	// if (dw_Status & 0x10)
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+				}	/*  if (dw_Status & 0x10) */
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 			else {
-		 /******************************/
+				/******************************/
 				/* Tor PWM selection is wrong */
-		 /******************************/
+				/******************************/
 
 				DPRINTK("Tor PWM selection is wrong\n");
 				i_ReturnValue = -4;
-			}	// if (b_PWM >= 0 && b_PWM <= 1)
+			}	/*  if (b_PWM >= 0 && b_PWM <= 1) */
 		} else {
-	      /**********************************/
+			/**********************************/
 			/* The module is not a PWM module */
-	      /**********************************/
+			/**********************************/
 
 			DPRINTK("The module is not a PWM module\n");
 			i_ReturnValue = -3;
 		}
 	} else {
-	   /***********************/
+		/***********************/
 		/* Module number error */
-	   /***********************/
+		/***********************/
 
 		DPRINTK("Module number error\n");
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
-INT i_APCI1710_InsnBitsReadPWMInterrupt(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnBitsReadPWMInterrupt(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->s_InterruptParameters.
 		s_FIFOInterruptParameters[devpriv->
@@ -3574,9 +3574,9 @@
 		s_FIFOInterruptParameters[devpriv->
 		s_InterruptParameters.ui_Read].ul_OldCounterLatchValue;
 
-			     /**************************/
+	/**************************/
 	/* Increment the read FIFO */
-			     /***************************/
+	/***************************/
 
 	devpriv->
 		s_InterruptParameters.
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Pwm.h b/drivers/staging/comedi/drivers/addi-data/APCI1710_Pwm.h
index c1b7f4c..bf1b4c3 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Pwm.h
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Pwm.h
@@ -26,51 +26,51 @@
 #define APCI1710_PWM_ENABLE		1
 #define APCI1710_PWM_NEWTIMING		2
 
-INT i_APCI1710_InsnConfigPWM(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnConfigPWM(struct comedi_device *dev, struct comedi_subdevice *s,
 			     struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_InitPWM(struct comedi_device *dev,
-		       BYTE b_ModulNbr,
-		       BYTE b_PWM,
-		       BYTE b_ClockSelection,
-		       BYTE b_TimingUnit,
-		       ULONG ul_LowTiming,
-		       ULONG ul_HighTiming,
-		       PULONG pul_RealLowTiming, PULONG pul_RealHighTiming);
+int i_APCI1710_InitPWM(struct comedi_device *dev,
+		       unsigned char b_ModulNbr,
+		       unsigned char b_PWM,
+		       unsigned char b_ClockSelection,
+		       unsigned char b_TimingUnit,
+		       unsigned int ul_LowTiming,
+		       unsigned int ul_HighTiming,
+		       unsigned int *pul_RealLowTiming, unsigned int *pul_RealHighTiming);
 
-INT i_APCI1710_GetPWMInitialisation(struct comedi_device *dev,
-				    BYTE b_ModulNbr,
-				    BYTE b_PWM,
-				    PBYTE pb_TimingUnit,
-				    PULONG pul_LowTiming,
-				    PULONG pul_HighTiming,
-				    PBYTE pb_StartLevel,
-				    PBYTE pb_StopMode,
-				    PBYTE pb_StopLevel,
-				    PBYTE pb_ExternGate,
-				    PBYTE pb_InterruptEnable, PBYTE pb_Enable);
+int i_APCI1710_GetPWMInitialisation(struct comedi_device *dev,
+				    unsigned char b_ModulNbr,
+				    unsigned char b_PWM,
+				    unsigned char *pb_TimingUnit,
+				    unsigned int *pul_LowTiming,
+				    unsigned int *pul_HighTiming,
+				    unsigned char *pb_StartLevel,
+				    unsigned char *pb_StopMode,
+				    unsigned char *pb_StopLevel,
+				    unsigned char *pb_ExternGate,
+				    unsigned char *pb_InterruptEnable, unsigned char *pb_Enable);
 
-INT i_APCI1710_InsnWritePWM(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnWritePWM(struct comedi_device *dev, struct comedi_subdevice *s,
 			    struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_EnablePWM(struct comedi_device *dev,
-			 BYTE b_ModulNbr,
-			 BYTE b_PWM,
-			 BYTE b_StartLevel,
-			 BYTE b_StopMode,
-			 BYTE b_StopLevel, BYTE b_ExternGate,
-			 BYTE b_InterruptEnable);
+int i_APCI1710_EnablePWM(struct comedi_device *dev,
+			 unsigned char b_ModulNbr,
+			 unsigned char b_PWM,
+			 unsigned char b_StartLevel,
+			 unsigned char b_StopMode,
+			 unsigned char b_StopLevel, unsigned char b_ExternGate,
+			 unsigned char b_InterruptEnable);
 
-INT i_APCI1710_SetNewPWMTiming(struct comedi_device *dev,
-			       BYTE b_ModulNbr,
-			       BYTE b_PWM, BYTE b_TimingUnit,
-			       ULONG ul_LowTiming, ULONG ul_HighTiming);
+int i_APCI1710_SetNewPWMTiming(struct comedi_device *dev,
+			       unsigned char b_ModulNbr,
+			       unsigned char b_PWM, unsigned char b_TimingUnit,
+			       unsigned int ul_LowTiming, unsigned int ul_HighTiming);
 
-INT i_APCI1710_DisablePWM(struct comedi_device *dev, BYTE b_ModulNbr, BYTE b_PWM);
+int i_APCI1710_DisablePWM(struct comedi_device *dev, unsigned char b_ModulNbr, unsigned char b_PWM);
 
-INT i_APCI1710_InsnReadGetPWMStatus(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnReadGetPWMStatus(struct comedi_device *dev, struct comedi_subdevice *s,
 				    struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_InsnBitsReadPWMInterrupt(struct comedi_device *dev,
+int i_APCI1710_InsnBitsReadPWMInterrupt(struct comedi_device *dev,
 					struct comedi_subdevice *s,
 					struct comedi_insn *insn, unsigned int *data);
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Ssi.c b/drivers/staging/comedi/drivers/addi-data/APCI1710_Ssi.c
index bb6e162..a445dab 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Ssi.c
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Ssi.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -65,31 +65,31 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_InitSSI                               |
-|                               (BYTE_    b_BoardHandle,                     |
-|                                BYTE_    b_ModulNbr,                        |
-|                                BYTE_    b_SSIProfile,                      |
-|                                BYTE_    b_PositionTurnLength,              |
-|                                BYTE_    b_TurnCptLength,                   |
-|                                BYTE_    b_PCIInputClock,                   |
+|                               (unsigned char_    b_BoardHandle,                     |
+|                                unsigned char_    b_ModulNbr,                        |
+|                                unsigned char_    b_SSIProfile,                      |
+|                                unsigned char_    b_PositionTurnLength,              |
+|                                unsigned char_    b_TurnCptLength,                   |
+|                                unsigned char_    b_PCIInputClock,                   |
 |                                ULONG_  ul_SSIOutputClock,                  |
-|                                BYTE_    b_SSICountingMode)                 |
+|                                unsigned char_    b_SSICountingMode)                 |
 +----------------------------------------------------------------------------+
 | Task              : Configure the SSI operating mode from selected module  |
 |                     (b_ModulNbr). You must calling this function be for you|
 |                     call any other function witch access of SSI.           |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle         : Handle of board APCI-1710|
-|                     BYTE_ b_ModulNbr            : Module number to         |
+| Input Parameters  : unsigned char_ b_BoardHandle         : Handle of board APCI-1710|
+|                     unsigned char_ b_ModulNbr            : Module number to         |
 |                                                   configure (0 to 3)       |
-|                     BYTE_  b_SSIProfile         : Selection from SSI       |
+|                     unsigned char_  b_SSIProfile         : Selection from SSI       |
 |                                                   profile length (2 to 32).|
-|                     BYTE_  b_PositionTurnLength : Selection from SSI       |
+|                     unsigned char_  b_PositionTurnLength : Selection from SSI       |
 |                                                   position data length     |
 |                                                   (1 to 31).               |
-|                     BYTE_  b_TurnCptLength      : Selection from SSI turn  |
+|                     unsigned char_  b_TurnCptLength      : Selection from SSI turn  |
 |                                                   counter data length      |
 |                                                   (1 to 31).               |
-|                     BYTE   b_PCIInputClock      : Selection from PCI bus   |
+|                     unsigned char   b_PCIInputClock      : Selection from PCI bus   |
 |                                                   clock                    |
 |                                                 - APCI1710_30MHZ :         |
 |                                                   The PC have a PCI bus    |
@@ -103,7 +103,7 @@
 |                                                   for 30 MHz selection.    |
 |                                                   From  252 to 5 000 000 Hz|
 |                                                   for 33 MHz selection.    |
-|                     BYTE   b_SSICountingMode    : SSI counting mode        |
+|                     unsigned char   b_SSICountingMode    : SSI counting mode        |
 |                                                   selection                |
 |                                                 - APCI1710_BINARY_MODE :   |
 |                                                    Binary counting mode.   |
@@ -111,12 +111,12 @@
 |                                                    Gray counting mode.
 
 	b_ModulNbr			= CR_AREF(insn->chanspec);
-	b_SSIProfile		= (BYTE) data[0];
-	b_PositionTurnLength= (BYTE) data[1];
-	b_TurnCptLength		= (BYTE) data[2];
-	b_PCIInputClock		= (BYTE) data[3];
-	ul_SSIOutputClock	= (ULONG) data[4];
-	b_SSICountingMode	= (BYTE)  data[5];     |
+	b_SSIProfile		= (unsigned char) data[0];
+	b_PositionTurnLength= (unsigned char) data[1];
+	b_TurnCptLength		= (unsigned char) data[2];
+	b_PCIInputClock		= (unsigned char) data[3];
+	ul_SSIOutputClock	= (unsigned int) data[4];
+	b_SSICountingMode	= (unsigned char)  data[5];     |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -133,22 +133,22 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnConfigInitSSI(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnConfigInitSSI(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	UINT ui_TimerValue;
-	BYTE b_ModulNbr, b_SSIProfile, b_PositionTurnLength, b_TurnCptLength,
+	int i_ReturnValue = 0;
+	unsigned int ui_TimerValue;
+	unsigned char b_ModulNbr, b_SSIProfile, b_PositionTurnLength, b_TurnCptLength,
 		b_PCIInputClock, b_SSICountingMode;
-	ULONG ul_SSIOutputClock;
+	unsigned int ul_SSIOutputClock;
 
 	b_ModulNbr = CR_AREF(insn->chanspec);
-	b_SSIProfile = (BYTE) data[0];
-	b_PositionTurnLength = (BYTE) data[1];
-	b_TurnCptLength = (BYTE) data[2];
-	b_PCIInputClock = (BYTE) data[3];
-	ul_SSIOutputClock = (ULONG) data[4];
-	b_SSICountingMode = (BYTE) data[5];
+	b_SSIProfile = (unsigned char) data[0];
+	b_PositionTurnLength = (unsigned char) data[1];
+	b_TurnCptLength = (unsigned char) data[2];
+	b_PCIInputClock = (unsigned char) data[3];
+	ul_SSIOutputClock = (unsigned int) data[4];
+	b_SSICountingMode = (unsigned char) data[5];
 
 	i_ReturnValue = insn->n;
 	/**************************/
@@ -167,7 +167,7 @@
 			/* Test the SSI profile length */
 	      /*******************************/
 
-			// CG 22/03/00 b_SSIProfile >= 2 anstatt b_SSIProfile > 2
+			/*  CG 22/03/00 b_SSIProfile >= 2 anstatt b_SSIProfile > 2 */
 			if (b_SSIProfile >= 2 && b_SSIProfile < 33) {
 		 /*************************************/
 				/* Test the SSI position data length */
@@ -250,9 +250,9 @@
 
 										ui_TimerValue
 											=
-											(UINT)
+											(unsigned int)
 											(
-											((ULONG) (b_PCIInputClock) * 500000UL) / ul_SSIOutputClock);
+											((unsigned int) (b_PCIInputClock) * 500000UL) / ul_SSIOutputClock);
 
 				   /************************/
 										/* Initialise the timer */
@@ -351,18 +351,18 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_  i_APCI1710_Read1SSIValue                        |
-|                               (BYTE_     b_BoardHandle,                    |
-|                                BYTE_     b_ModulNbr,                       |
-|                                BYTE_     b_SelectedSSI,                    |
+|                               (unsigned char_     b_BoardHandle,                    |
+|                                unsigned char_     b_ModulNbr,                       |
+|                                unsigned char_     b_SelectedSSI,                    |
 |                                PULONG_ pul_Position,                       |
 |                                PULONG_ pul_TurnCpt)
- INT i_APCI1710_ReadSSIValue(struct comedi_device *dev,struct comedi_subdevice *s,
+ int i_APCI1710_ReadSSIValue(struct comedi_device *dev,struct comedi_subdevice *s,
 	struct comedi_insn *insn,unsigned int *data)                       |
 +----------------------------------------------------------------------------+
 | Task              :
@@ -373,22 +373,22 @@
 						or Read all SSI counter (b_SelectedSSI) from              |
 |                     selected module (b_ModulNbr).                            |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle         : Handle of board APCI-1710|
-|                     BYTE_ b_ModulNbr            : Module number to         |
+| Input Parameters  : unsigned char_ b_BoardHandle         : Handle of board APCI-1710|
+|                     unsigned char_ b_ModulNbr            : Module number to         |
 |                                                   configure (0 to 3)       |
-|                     BYTE_ b_SelectedSSI         : Selection from SSI       |
+|                     unsigned char_ b_SelectedSSI         : Selection from SSI       |
 |                                                   counter (0 to 2)
 
-    b_ModulNbr		=   (BYTE) CR_AREF(insn->chanspec);
-	b_SelectedSSI	=	(BYTE) CR_CHAN(insn->chanspec); (in case of single ssi)
-	b_ReadType		=	(BYTE) CR_RANGE(insn->chanspec);
+    b_ModulNbr		=   (unsigned char) CR_AREF(insn->chanspec);
+	b_SelectedSSI	=	(unsigned char) CR_CHAN(insn->chanspec); (in case of single ssi)
+	b_ReadType		=	(unsigned char) CR_RANGE(insn->chanspec);
 |
 +----------------------------------------------------------------------------+
 | Output Parameters : PULONG_  pul_Position       : SSI position in the turn |
 |                     PULONG_  pul_TurnCpt        : Number of turns
 
-pul_Position	=	(PULONG) &data[0];
-	pul_TurnCpt		=	(PULONG) &data[1];         |
+pul_Position	=	(unsigned int *) &data[0];
+	pul_TurnCpt		=	(unsigned int *) &data[1];         |
 +----------------------------------------------------------------------------+
 | Return Value      : 0: No error                                            |
 |                    -1: The handle parameter of the board is wrong          |
@@ -400,37 +400,37 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnReadSSIValue(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnReadSSIValue(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	BYTE b_Cpt;
-	BYTE b_Length;
-	BYTE b_Schift;
-	BYTE b_SSICpt;
-	DWORD dw_And;
-	DWORD dw_And1;
-	DWORD dw_And2;
-	DWORD dw_StatusReg;
-	DWORD dw_CounterValue;
-	BYTE b_ModulNbr;
-	BYTE b_SelectedSSI;
-	BYTE b_ReadType;
-	PULONG pul_Position;
-	PULONG pul_TurnCpt;
-	PULONG pul_Position1;
-	PULONG pul_TurnCpt1;
+	int i_ReturnValue = 0;
+	unsigned char b_Cpt;
+	unsigned char b_Length;
+	unsigned char b_Schift;
+	unsigned char b_SSICpt;
+	unsigned int dw_And;
+	unsigned int dw_And1;
+	unsigned int dw_And2;
+	unsigned int dw_StatusReg;
+	unsigned int dw_CounterValue;
+	unsigned char b_ModulNbr;
+	unsigned char b_SelectedSSI;
+	unsigned char b_ReadType;
+	unsigned int *pul_Position;
+	unsigned int *pul_TurnCpt;
+	unsigned int *pul_Position1;
+	unsigned int *pul_TurnCpt1;
 
 	i_ReturnValue = insn->n;
-	pul_Position1 = (PULONG) & data[0];
-// For Read1
-	pul_TurnCpt1 = (PULONG) & data[1];
-// For Read all
-	pul_Position = (PULONG) & data[0];	//0-2
-	pul_TurnCpt = (PULONG) & data[3];	//3-5
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_SelectedSSI = (BYTE) CR_CHAN(insn->chanspec);
-	b_ReadType = (BYTE) CR_RANGE(insn->chanspec);
+	pul_Position1 = (unsigned int *) &data[0];
+/* For Read1 */
+	pul_TurnCpt1 = (unsigned int *) &data[1];
+/* For Read all */
+	pul_Position = (unsigned int *) &data[0];	/* 0-2 */
+	pul_TurnCpt = (unsigned int *) &data[3];	/* 3-5 */
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_SelectedSSI = (unsigned char) CR_CHAN(insn->chanspec);
+	b_ReadType = (unsigned char) CR_RANGE(insn->chanspec);
 
 	/**************************/
 	/* Test the module number */
@@ -477,9 +477,8 @@
 								s_BoardInfos.
 								ui_Address +
 								(64 * b_ModulNbr));
-						}
-						while ((dw_StatusReg & 0x1) !=
-							0);
+						} while ((dw_StatusReg & 0x1)
+							 != 0);
 
 		    /******************************/
 						/* Read the SSI counter value */
@@ -608,8 +607,7 @@
 							s_BoardInfos.
 							ui_Address +
 							(64 * b_ModulNbr));
-					}
-					while ((dw_StatusReg & 0x1) != 0);
+					} while ((dw_StatusReg & 0x1) != 0);
 
 					for (b_SSICpt = 0; b_SSICpt < 3;
 						b_SSICpt++) {
@@ -667,7 +665,7 @@
 				default:
 					printk("Read Type Inputs Wrong\n");
 
-				}	// switch  ending
+				}	/*  switch  ending */
 
 			} else {
 		 /***********************/
@@ -695,16 +693,16 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_   i_APCI1710_ReadSSI1DigitalInput                |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
-|                                        BYTE_     b_InputChannel,           |
-|                                        PBYTE_   pb_ChannelStatus)          |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
+|                                        unsigned char_     b_InputChannel,           |
+|                                        unsigned char *_   pb_ChannelStatus)          |
 +----------------------------------------------------------------------------+
 | Task              :
 					(0) Set the digital output from selected SSI moule         |
@@ -716,13 +714,13 @@
                     (3)Read the status from all SSI digital inputs from       |
 |                     selected SSI module (b_ModulNbr)                   |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle         : Handle of board APCI-1710|
-|                     BYTE_ b_ModulNbr    CR_AREF        : Module number to         |
+| Input Parameters  : unsigned char_ b_BoardHandle         : Handle of board APCI-1710|
+|                     unsigned char_ b_ModulNbr    CR_AREF        : Module number to         |
 |                                                   configure (0 to 3)       |
-|                     BYTE_ b_InputChannel CR_CHAN       : Selection from digital   |
+|                     unsigned char_ b_InputChannel CR_CHAN       : Selection from digital   |
 |                        data[0] which IOTYPE                           input ( 0 to 2)          |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_  pb_ChannelStatus    : Digital input channel    |
+| Output Parameters : unsigned char *_  pb_ChannelStatus    : Digital input channel    |
 |                                 data[0]                  status                   |
 |                                                   0 : Channle is not active|
 |                                                   1 : Channle is active    |
@@ -735,19 +733,19 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnBitsSSIDigitalIO(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnBitsSSIDigitalIO(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg;
-	BYTE b_ModulNbr;
-	BYTE b_InputChannel;
-	PBYTE pb_ChannelStatus;
-	PBYTE pb_InputStatus;
-	BYTE b_IOType;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg;
+	unsigned char b_ModulNbr;
+	unsigned char b_InputChannel;
+	unsigned char *pb_ChannelStatus;
+	unsigned char *pb_InputStatus;
+	unsigned char b_IOType;
 	i_ReturnValue = insn->n;
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_IOType = (BYTE) data[0];
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_IOType = (unsigned char) data[0];
 
 	/**************************/
 	/* Test the module number */
@@ -785,8 +783,8 @@
 				/* Test the digital imnput channel number */
 				   /******************************************/
 
-				b_InputChannel = (BYTE) CR_CHAN(insn->chanspec);
-				pb_ChannelStatus = (PBYTE) & data[0];
+				b_InputChannel = (unsigned char) CR_CHAN(insn->chanspec);
+				pb_ChannelStatus = (unsigned char *) &data[0];
 
 				if (b_InputChannel <= 2) {
 					/**************************/
@@ -797,7 +795,7 @@
 						inl(devpriv->s_BoardInfos.
 						ui_Address + (64 * b_ModulNbr));
 					*pb_ChannelStatus =
-						(BYTE) (((~dw_StatusReg) >> (4 +
+						(unsigned char) (((~dw_StatusReg) >> (4 +
 								b_InputChannel))
 						& 1);
 				} else {
@@ -814,19 +812,19 @@
 					/**************************/
 				/* Read all digital input */
 					/**************************/
-				pb_InputStatus = (PBYTE) & data[0];
+				pb_InputStatus = (unsigned char *) &data[0];
 
 				dw_StatusReg =
 					inl(devpriv->s_BoardInfos.ui_Address +
 					(64 * b_ModulNbr));
 				*pb_InputStatus =
-					(BYTE) (((~dw_StatusReg) >> 4) & 7);
+					(unsigned char) (((~dw_StatusReg) >> 4) & 7);
 				break;
 
 			default:
 				printk("IO type wrong\n");
 
-			}	//switch end
+			}	/* switch end */
 		} else {
 	      /**********************************/
 			/* The module is not a SSI module */
@@ -844,5 +842,5 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Ssi.h b/drivers/staging/comedi/drivers/addi-data/APCI1710_Ssi.h
index 88daad1..eb7f101 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Ssi.h
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Ssi.h
@@ -33,11 +33,11 @@
 /*
  * SSI INISIALISATION FUNCTION
  */
-INT i_APCI1710_InsnConfigInitSSI(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnConfigInitSSI(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_InsnReadSSIValue(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnReadSSIValue(struct comedi_device *dev, struct comedi_subdevice *s,
 				struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_InsnBitsSSIDigitalIO(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnBitsSSIDigitalIO(struct comedi_device *dev, struct comedi_subdevice *s,
 				    struct comedi_insn *insn, unsigned int *data);
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Tor.c b/drivers/staging/comedi/drivers/addi-data/APCI1710_Tor.c
index 90316e1..43198aa 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Tor.c
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Tor.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -63,11 +63,11 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_     i_APCI1710_InitTorCounter                    |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
-|                                        BYTE_     b_TorCounter,             |
-|                                        BYTE_     b_PCIInputClock,          |
-|                                        BYTE_     b_TimingUnit,             |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
+|                                        unsigned char_     b_TorCounter,             |
+|                                        unsigned char_     b_PCIInputClock,          |
+|                                        unsigned char_     b_TimingUnit,             |
 |                                        ULONG_   ul_TimingInterval,         |
 |                                        PULONG_ pul_RealTimingInterval)     |
 +----------------------------------------------------------------------------+
@@ -82,11 +82,11 @@
 +----------------------------------------------------------------------------+
 | Input Parameters  :    |
 |
-		CR_AREF	BYTE_   b_ModulNbr       : Module number to configure  |
+		CR_AREF	unsigned char_   b_ModulNbr       : Module number to configure  |
 |                                                (0 to 3)                    |
-|           data[0] BYTE_   b_TorCounter     : Tor counter selection       |
+|           data[0] unsigned char_   b_TorCounter     : Tor counter selection       |
 |                                                (0 or 1).                   |
-|           data[1] BYTE_   b_PCIInputClock  : Selection from PCI bus clock|
+|           data[1] unsigned char_   b_PCIInputClock  : Selection from PCI bus clock|
 |                                                - APCI1710_30MHZ :          |
 |                                                  The PC have a PCI bus     |
 |                                                  clock from 30 MHz         |
@@ -104,7 +104,7 @@
 |						   than it is not possibl to |
 |						   used the gate input for   |
 |						   enabled the acquisition   |
-|           data[2] BYTE_   b_TimingUnit    : Base timing unit (0 to 4)    |
+|           data[2] unsigned char_   b_TimingUnit    : Base timing unit (0 to 4)    |
 |                                                 0 : ns                     |
 |                                                 1 : µs                     |
 |                                                 2 : ms                     |
@@ -130,27 +130,27 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnConfigInitTorCounter(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnConfigInitTorCounter(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	ULONG ul_TimerValue = 0;
-	DWORD dw_Command;
+	int i_ReturnValue = 0;
+	unsigned int ul_TimerValue = 0;
+	unsigned int dw_Command;
 	double d_RealTimingInterval = 0;
-	BYTE b_ModulNbr;
-	BYTE b_TorCounter;
-	BYTE b_PCIInputClock;
-	BYTE b_TimingUnit;
-	ULONG ul_TimingInterval;
-	ULONG ul_RealTimingInterval = 0;
+	unsigned char b_ModulNbr;
+	unsigned char b_TorCounter;
+	unsigned char b_PCIInputClock;
+	unsigned char b_TimingUnit;
+	unsigned int ul_TimingInterval;
+	unsigned int ul_RealTimingInterval = 0;
 
 	i_ReturnValue = insn->n;
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
 
-	b_TorCounter = (BYTE) data[0];
-	b_PCIInputClock = (BYTE) data[1];
-	b_TimingUnit = (BYTE) data[2];
-	ul_TimingInterval = (ULONG) data[3];
+	b_TorCounter = (unsigned char) data[0];
+	b_PCIInputClock = (unsigned char) data[1];
+	b_TimingUnit = (unsigned char) data[2];
+	ul_TimingInterval = (unsigned int) data[3];
 	printk("INPUT clock %d\n", b_PCIInputClock);
 
 		/**************************/
@@ -225,7 +225,7 @@
 
 											ul_TimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(ul_TimingInterval
 												*
 												(0.00025 * b_PCIInputClock));
@@ -248,7 +248,7 @@
 
 											ul_RealTimingInterval
 												=
-												(ULONG)
+												(unsigned int)
 												(ul_TimerValue
 												/
 												(0.00025 * (double)b_PCIInputClock));
@@ -284,7 +284,7 @@
 											if (b_PCIInputClock != APCI1710_40MHZ) {
 												ul_TimerValue
 													=
-													(ULONG)
+													(unsigned int)
 													(
 													(double)
 													(ul_TimerValue)
@@ -306,7 +306,7 @@
 
 											ul_TimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(ul_TimingInterval
 												*
 												(0.25 * b_PCIInputClock));
@@ -329,7 +329,7 @@
 
 											ul_RealTimingInterval
 												=
-												(ULONG)
+												(unsigned int)
 												(ul_TimerValue
 												/
 												(0.25 * (double)b_PCIInputClock));
@@ -367,7 +367,7 @@
 											if (b_PCIInputClock != APCI1710_40MHZ) {
 												ul_TimerValue
 													=
-													(ULONG)
+													(unsigned int)
 													(
 													(double)
 													(ul_TimerValue)
@@ -413,7 +413,7 @@
 
 											ul_RealTimingInterval
 												=
-												(ULONG)
+												(unsigned int)
 												(ul_TimerValue
 												/
 												(250.0 * (double)b_PCIInputClock));
@@ -449,7 +449,7 @@
 											if (b_PCIInputClock != APCI1710_40MHZ) {
 												ul_TimerValue
 													=
-													(ULONG)
+													(unsigned int)
 													(
 													(double)
 													(ul_TimerValue)
@@ -471,7 +471,7 @@
 
 											ul_TimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(ul_TimingInterval
 												*
 												(250000.0
@@ -496,7 +496,7 @@
 
 											ul_RealTimingInterval
 												=
-												(ULONG)
+												(unsigned int)
 												(ul_TimerValue
 												/
 												(250000.0
@@ -535,7 +535,7 @@
 											if (b_PCIInputClock != APCI1710_40MHZ) {
 												ul_TimerValue
 													=
-													(ULONG)
+													(unsigned int)
 													(
 													(double)
 													(ul_TimerValue)
@@ -557,7 +557,7 @@
 
 											ul_TimerValue
 												=
-												(ULONG)
+												(unsigned int)
 												(
 												(ul_TimingInterval
 													*
@@ -585,7 +585,7 @@
 
 											ul_RealTimingInterval
 												=
-												(ULONG)
+												(unsigned int)
 												(ul_TimerValue
 												/
 												(250000.0
@@ -629,7 +629,7 @@
 											if (b_PCIInputClock != APCI1710_40MHZ) {
 												ul_TimerValue
 													=
-													(ULONG)
+													(unsigned int)
 													(
 													(double)
 													(ul_TimerValue)
@@ -641,7 +641,7 @@
 										}
 
 										fpu_end();
-									}	// if (b_PCIInputClock != APCI1710_GATE_INPUT)
+									}	/*  if (b_PCIInputClock != APCI1710_GATE_INPUT) */
 									else {
 				   /*************************************************************/
 										/* 2 Clock used for the overflow and the reload from counter */
@@ -652,7 +652,7 @@
 											ul_TimingInterval
 											-
 											2;
-									}	// if (b_PCIInputClock != APCI1710_GATE_INPUT)
+									}	/*  if (b_PCIInputClock != APCI1710_GATE_INPUT) */
 
 				/****************************/
 									/* Save the PCI input clock */
@@ -814,7 +814,7 @@
 							DPRINTK("Base timing selection is wrong\n");
 							i_ReturnValue = -7;
 						}
-					}	// if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4))
+					}	/*  if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
 					else {
 		       /**********************************/
 						/* Timing unit selection is wrong */
@@ -822,8 +822,8 @@
 
 						DPRINTK("Timing unit selection is wrong\n");
 						i_ReturnValue = -6;
-					}	// if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4))
-				}	// if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ))
+					}	/*  if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
+				}	/*  if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ)) */
 				else {
 		    /*****************************************/
 					/* The selected PCI input clock is wrong */
@@ -831,8 +831,8 @@
 
 					DPRINTK("The selected PCI input clock is wrong\n");
 					i_ReturnValue = -5;
-				}	// if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ))
-			}	// if (b_TorCounterMode >= 0 && b_TorCounterMode <= 7)
+				}	/*  if ((b_PCIInputClock == APCI1710_30MHZ) || (b_PCIInputClock == APCI1710_33MHZ)) */
+			}	/*  if (b_TorCounterMode >= 0 && b_TorCounterMode <= 7) */
 			else {
 		 /**********************************/
 				/* Tor Counter selection is wrong */
@@ -840,7 +840,7 @@
 
 				DPRINTK("Tor Counter selection is wrong\n");
 				i_ReturnValue = -4;
-			}	// if (b_TorCounterMode >= 0 && b_TorCounterMode <= 7)
+			}	/*  if (b_TorCounterMode >= 0 && b_TorCounterMode <= 7) */
 		} else {
 	      /******************************************/
 			/* The module is not a tor counter module */
@@ -857,20 +857,20 @@
 		DPRINTK("Module number error\n");
 		i_ReturnValue = -2;
 	}
-	data[0] = (UINT) ul_RealTimingInterval;
-	return (i_ReturnValue);
+	data[0] = (unsigned int) ul_RealTimingInterval;
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_EnableTorCounter                      |
-|                                               (BYTE_ b_BoardHandle,        |
-|                                                BYTE_ b_ModulNbr,           |
-|						 BYTE_ b_TorCounter,         |
-|						 BYTE_ b_InputMode,          |
-|						 BYTE_ b_ExternGate,         |
-|                                                BYTE_ b_CycleMode,          |
-|                                                BYTE_ b_InterruptEnable)    |
+|                                               (unsigned char_ b_BoardHandle,        |
+|                                                unsigned char_ b_ModulNbr,           |
+|						 unsigned char_ b_TorCounter,         |
+|						 unsigned char_ b_InputMode,          |
+|						 unsigned char_ b_ExternGate,         |
+|                                                unsigned char_ b_CycleMode,          |
+|                                                unsigned char_ b_InterruptEnable)    |
 +----------------------------------------------------------------------------+
 | Task              : Enable the tor counter (b_TorCounter) from selected    |
 |		      module (b_ModulNbr). You must calling the              |
@@ -883,13 +883,13 @@
 |                     The b_CycleMode parameter determine if you will        |
 |                     measured a single or more cycle.                       |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle  : Handle of board APCI-1710       |
-|                     BYTE_ b_ModulNbr     : Selected module number (0 to 3) |
-|                     BYTE_ b_TorCounter   : Tor counter selection (0 or 1). |
-|		      BYTE_ b_InputMode    : Input signal level selection    |
+| Input Parameters  : unsigned char_ b_BoardHandle  : Handle of board APCI-1710       |
+|                     unsigned char_ b_ModulNbr     : Selected module number (0 to 3) |
+|                     unsigned char_ b_TorCounter   : Tor counter selection (0 or 1). |
+|		      unsigned char_ b_InputMode    : Input signal level selection    |
 |						0 : Tor count each low level |
 |						1 : Tor count each high level|
-|		      BYTE_ b_ExternGate   : Extern gate action selection    |
+|		      unsigned char_ b_ExternGate   : Extern gate action selection    |
 |						0 : Extern gate signal not   |
 |						    used                     |
 |						1 : Extern gate signal used. |
@@ -928,9 +928,9 @@
 |					      The gate input is used for the |
 |					      signal B                       |
 |									     |
-|                     BYTE_ b_CycleMode    : Selected the tor counter        |
+|                     unsigned char_ b_CycleMode    : Selected the tor counter        |
 |                                            acquisition mode                |
-|                     BYTE_ b_InterruptEnable : Enable or disable the        |
+|                     unsigned char_ b_InterruptEnable : Enable or disable the        |
 |                                               tor counter interrupt.       |
 |                                               APCI1710_ENABLE:             |
 |                                               Enable the tor counter       |
@@ -959,9 +959,9 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_DisableTorCounter                     |
-|                                               (BYTE_  b_BoardHandle,       |
-|                                                BYTE_  b_ModulNbr,          |
-|						 BYTE_  b_TorCounter)        |
+|                                               (unsigned char_  b_BoardHandle,       |
+|                                                unsigned char_  b_ModulNbr,          |
+|						 unsigned char_  b_TorCounter)        |
 +----------------------------------------------------------------------------+
 | Task              : Disable the tor counter (b_TorCounter) from selected   |
 |		      module (b_ModulNbr). If you disable the tor counter    |
@@ -969,9 +969,9 @@
 |		      counter witch the " i_APCI1710_EnableTorCounter"       |
 |		      function, the status register is cleared               |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle  : Handle of board APCI-1710       |
-|                     BYTE_ b_ModulNbr     : Selected module number (0 to 3) |
-|                     BYTE_ b_TorCounter   : Tor counter selection (0 or 1). |
+| Input Parameters  : unsigned char_ b_BoardHandle  : Handle of board APCI-1710       |
+|                     unsigned char_ b_ModulNbr     : Selected module number (0 to 3) |
+|                     unsigned char_ b_TorCounter   : Tor counter selection (0 or 1). |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -987,29 +987,29 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnWriteEnableDisableTorCounter(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnWriteEnableDisableTorCounter(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_Status;
-	DWORD dw_DummyRead;
-	DWORD dw_ConfigReg;
-	BYTE b_ModulNbr, b_Action;
-	BYTE b_TorCounter;
-	BYTE b_InputMode;
-	BYTE b_ExternGate;
-	BYTE b_CycleMode;
-	BYTE b_InterruptEnable;
+	int i_ReturnValue = 0;
+	unsigned int dw_Status;
+	unsigned int dw_DummyRead;
+	unsigned int dw_ConfigReg;
+	unsigned char b_ModulNbr, b_Action;
+	unsigned char b_TorCounter;
+	unsigned char b_InputMode;
+	unsigned char b_ExternGate;
+	unsigned char b_CycleMode;
+	unsigned char b_InterruptEnable;
 
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_Action = (BYTE) data[0];	// enable or disable
-	b_TorCounter = (BYTE) data[1];
-	b_InputMode = (BYTE) data[2];
-	b_ExternGate = (BYTE) data[3];
-	b_CycleMode = (BYTE) data[4];
-	b_InterruptEnable = (BYTE) data[5];
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_Action = (unsigned char) data[0];	/*  enable or disable */
+	b_TorCounter = (unsigned char) data[1];
+	b_InputMode = (unsigned char) data[2];
+	b_ExternGate = (unsigned char) data[3];
+	b_CycleMode = (unsigned char) data[4];
+	b_InterruptEnable = (unsigned char) data[5];
 	i_ReturnValue = insn->n;;
-	devpriv->tsk_Current = current;	// Save the current process task structure
+	devpriv->tsk_Current = current;	/*  Save the current process task structure */
 	/**************************/
 	/* Test the module number */
 	/**************************/
@@ -1027,7 +1027,7 @@
 	      /**********************************/
 
 			if (b_TorCounter <= 1) {
-				switch (b_Action)	// Enable or Disable
+				switch (b_Action)	/*  Enable or Disable */
 				{
 				case APCI1710_ENABLE:
 		 /***********************************/
@@ -1149,7 +1149,7 @@
 													|
 													0x780;
 
-											}	// if (b_InputMode == APCI1710_TOR_SIMPLE_MODE)
+											}	/*  if (b_InputMode == APCI1710_TOR_SIMPLE_MODE) */
 
 				      /***********************/
 											/* Test if double mode */
@@ -1166,12 +1166,12 @@
 													|
 													0x180;
 
-											}	// if (b_InputMode == APCI1710_TOR_DOUBLE_MODE)
+											}	/*  if (b_InputMode == APCI1710_TOR_DOUBLE_MODE) */
 
 											b_InputMode
 												=
 												0;
-										}	// if (b_InputMode > 1)
+										}	/*  if (b_InputMode > 1) */
 
 				   /*******************/
 										/* Set the command */
@@ -1237,7 +1237,7 @@
 
 										outl(1, devpriv->s_BoardInfos.ui_Address + 8 + (16 * b_TorCounter) + (64 * b_ModulNbr));
 
-									}	// if ((b_InterruptEnable == APCI1710_ENABLE) || (b_InterruptEnable == APCI1710_DISABLE))
+									}	/*  if ((b_InterruptEnable == APCI1710_ENABLE) || (b_InterruptEnable == APCI1710_DISABLE)) */
 									else {
 				/********************************/
 										/* Interrupt parameter is wrong */
@@ -1247,8 +1247,8 @@
 										i_ReturnValue
 											=
 											-9;
-									}	// if ((b_InterruptEnable == APCI1710_ENABLE) || (b_InterruptEnable == APCI1710_DISABLE))
-								}	// if ((b_CycleMode == APCI1710_SINGLE) || (b_CycleMode == APCI1710_CONTINUOUS))
+									}	/*  if ((b_InterruptEnable == APCI1710_ENABLE) || (b_InterruptEnable == APCI1710_DISABLE)) */
+								}	/*  if ((b_CycleMode == APCI1710_SINGLE) || (b_CycleMode == APCI1710_CONTINUOUS)) */
 								else {
 			     /***********************************************/
 									/* Tor counter acquisition mode cycle is wrong */
@@ -1258,8 +1258,8 @@
 									i_ReturnValue
 										=
 										-8;
-								}	// if ((b_CycleMode == APCI1710_SINGLE) || (b_CycleMode == APCI1710_CONTINUOUS))
-							}	// if (b_ExternGate >= 0 && b_ExternGate <= 1)
+								}	/*  if ((b_CycleMode == APCI1710_SINGLE) || (b_CycleMode == APCI1710_CONTINUOUS)) */
+							}	/*  if (b_ExternGate >= 0 && b_ExternGate <= 1) */
 							else {
 			  /***********************************/
 								/* Extern gate input mode is wrong */
@@ -1268,8 +1268,8 @@
 								DPRINTK("Extern gate input mode is wrong\n");
 								i_ReturnValue =
 									-7;
-							}	// if (b_ExternGate >= 0 && b_ExternGate <= 1)
-						}	// if (b_InputMode >= 0 && b_InputMode <= 1)
+							}	/*  if (b_ExternGate >= 0 && b_ExternGate <= 1) */
+						}	/*  if (b_InputMode >= 0 && b_InputMode <= 1) */
 						else {
 		       /***************************************/
 							/* Tor input signal selection is wrong */
@@ -1329,7 +1329,7 @@
 								s_BoardInfos.
 								ui_Address + 8 +
 								(16 * b_TorCounter) + (64 * b_ModulNbr));
-						}	// if (dw_Status & 0x1)
+						}	/*  if (dw_Status & 0x1) */
 						else {
 		       /***************************/
 							/* Tor counter not enabled */
@@ -1337,8 +1337,8 @@
 
 							DPRINTK("Tor counter not enabled \n");
 							i_ReturnValue = -6;
-						}	// if (dw_Status & 0x1)
-					}	// if (dw_Status & 0x10)
+						}	/*  if (dw_Status & 0x1) */
+					}	/*  if (dw_Status & 0x10) */
 					else {
 		    /*******************************/
 						/* Tor counter not initialised */
@@ -1346,10 +1346,10 @@
 
 						DPRINTK("Tor counter not initialised\n");
 						i_ReturnValue = -5;
-					}	// // if (dw_Status & 0x10)
+					}	/*  // if (dw_Status & 0x10) */
 
-				}	// switch
-			}	// if (b_TorCounter <= 1)
+				}	/*  switch */
+			}	/*  if (b_TorCounter <= 1) */
 			else {
 		 /**********************************/
 				/* Tor counter selection is wrong */
@@ -1357,7 +1357,7 @@
 
 				DPRINTK("Tor counter selection is wrong\n");
 				i_ReturnValue = -4;
-			}	// if (b_TorCounter <= 1)
+			}	/*  if (b_TorCounter <= 1) */
 		} else {
 	      /******************************************/
 			/* The module is not a tor counter module */
@@ -1375,22 +1375,22 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_GetTorCounterInitialisation           |
-|                                               (BYTE_     b_BoardHandle,    |
-|                                                BYTE_     b_ModulNbr,       |
-|						 BYTE_     b_TorCounter,     |
-|                                        	 PBYTE_   pb_TimingUnit,     |
+|                                               (unsigned char_     b_BoardHandle,    |
+|                                                unsigned char_     b_ModulNbr,       |
+|						 unsigned char_     b_TorCounter,     |
+|                                        	 unsigned char *_   pb_TimingUnit,     |
 |                                        	 PULONG_ pul_TimingInterval, |
-|						 PBYTE_   pb_InputMode,      |
-|						 PBYTE_   pb_ExternGate,     |
-|                                                PBYTE_   pb_CycleMode,      |
-|						 PBYTE_   pb_Enable,         |
-|                                                PBYTE_   pb_InterruptEnable)|
+|						 unsigned char *_   pb_InputMode,      |
+|						 unsigned char *_   pb_ExternGate,     |
+|                                                unsigned char *_   pb_CycleMode,      |
+|						 unsigned char *_   pb_Enable,         |
+|                                                unsigned char *_   pb_InterruptEnable)|
 +----------------------------------------------------------------------------+
 | Task              : Enable the tor counter (b_TorCounter) from selected    |
 |		      module (b_ModulNbr). You must calling the              |
@@ -1403,37 +1403,37 @@
 |                     The b_CycleMode parameter determine if you will        |
 |                     measured a single or more cycle.                       |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle  : Handle of board APCI-1710       |
-|                     BYTE_ b_ModulNbr     : Selected module number (0 to 3) |
-|                     BYTE_ b_TorCounter   : Tor counter selection (0 or 1)
+| Input Parameters  : unsigned char_ b_BoardHandle  : Handle of board APCI-1710       |
+|                     unsigned char_ b_ModulNbr     : Selected module number (0 to 3) |
+|                     unsigned char_ b_TorCounter   : Tor counter selection (0 or 1)
 
 	b_ModulNbr			=	CR_AREF(insn->chanspec);
 	b_TorCounter		=	CR_CHAN(insn->chanspec);
 . |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_  pb_TimingUnit    : Base timing unit (0 to 4)   |
+| Output Parameters : unsigned char *_  pb_TimingUnit    : Base timing unit (0 to 4)   |
 |                                                 0 : ns                     |
 |                                                 1 : µs                     |
 |                                                 2 : ms                     |
 |                                                 3 : s                      |
 |                                                 4 : mn                     |
 |                     PULONG_ pul_TimingInterval : Base timing value.        |
-|		      PBYTE_ pb_InputMode        : Input signal level        |
+|		      unsigned char *_ pb_InputMode        : Input signal level        |
 |						   selection  		     |
 |						0 : Tor count each low level |
 |						1 : Tor count each high level|
-|		      PBYTE_ pb_ExternGate	: Extern gate action         |
+|		      unsigned char *_ pb_ExternGate	: Extern gate action         |
 |						  selection                  |
 |						  0 : Extern gate signal not |
 |						      used                   |
 |						  1 : Extern gate signal used|
-|                     PBYTE_ pb_CycleMode       : Tor counter acquisition    |
+|                     unsigned char *_ pb_CycleMode       : Tor counter acquisition    |
 |						  mode           	     |
-|		      PBYTE_ pb_Enable		: Indicate if the tor counter|
+|		      unsigned char *_ pb_Enable		: Indicate if the tor counter|
 |						  is enabled or no           |
 |						  0 : Tor counter disabled   |
 |						  1 : Tor counter enabled    |
-|                     PBYTE_ pb_InterruptEnable : Enable or disable the      |
+|                     unsigned char *_ pb_InterruptEnable : Enable or disable the      |
 |                                                 tor counter interrupt.     |
 |                                                 APCI1710_ENABLE:           |
 |                                                 Enable the tor counter     |
@@ -1441,13 +1441,13 @@
 |                                                 APCI1710_DISABLE:          |
 |                                                 Disable the tor counter    |
 |                                                 interrupt
-	pb_TimingUnit		=	(PBYTE) &data[0];
-	pul_TimingInterval	=  (PULONG) &data[1];
-	pb_InputMode		=	(PBYTE) &data[2];
-	pb_ExternGate		=	(PBYTE) &data[3];
-	pb_CycleMode		=	(PBYTE) &data[4];
-	pb_Enable			=	(PBYTE) &data[5];
-	pb_InterruptEnable	=	(PBYTE) &data[6];
+	pb_TimingUnit		=	(unsigned char *) &data[0];
+	pul_TimingInterval	=  (unsigned int *) &data[1];
+	pb_InputMode		=	(unsigned char *) &data[2];
+	pb_ExternGate		=	(unsigned char *) &data[3];
+	pb_CycleMode		=	(unsigned char *) &data[4];
+	pb_Enable			=	(unsigned char *) &data[5];
+	pb_InterruptEnable	=	(unsigned char *) &data[6];
                  |
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
@@ -1460,32 +1460,32 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnReadGetTorCounterInitialisation(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnReadGetTorCounterInitialisation(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_Status;
-	BYTE b_ModulNbr;
-	BYTE b_TorCounter;
-	PBYTE pb_TimingUnit;
-	PULONG pul_TimingInterval;
-	PBYTE pb_InputMode;
-	PBYTE pb_ExternGate;
-	PBYTE pb_CycleMode;
-	PBYTE pb_Enable;
-	PBYTE pb_InterruptEnable;
+	int i_ReturnValue = 0;
+	unsigned int dw_Status;
+	unsigned char b_ModulNbr;
+	unsigned char b_TorCounter;
+	unsigned char *pb_TimingUnit;
+	unsigned int *pul_TimingInterval;
+	unsigned char *pb_InputMode;
+	unsigned char *pb_ExternGate;
+	unsigned char *pb_CycleMode;
+	unsigned char *pb_Enable;
+	unsigned char *pb_InterruptEnable;
 
 	i_ReturnValue = insn->n;
 	b_ModulNbr = CR_AREF(insn->chanspec);
 	b_TorCounter = CR_CHAN(insn->chanspec);
 
-	pb_TimingUnit = (PBYTE) & data[0];
-	pul_TimingInterval = (PULONG) & data[1];
-	pb_InputMode = (PBYTE) & data[2];
-	pb_ExternGate = (PBYTE) & data[3];
-	pb_CycleMode = (PBYTE) & data[4];
-	pb_Enable = (PBYTE) & data[5];
-	pb_InterruptEnable = (PBYTE) & data[6];
+	pb_TimingUnit = (unsigned char *) &data[0];
+	pul_TimingInterval = (unsigned int *) &data[1];
+	pb_InputMode = (unsigned char *) &data[2];
+	pb_ExternGate = (unsigned char *) &data[3];
+	pb_CycleMode = (unsigned char *) &data[4];
+	pb_Enable = (unsigned char *) &data[5];
+	pb_InterruptEnable = (unsigned char *) &data[6];
 
 	/**************************/
 	/* Test the module number */
@@ -1526,9 +1526,9 @@
 						(64 * b_ModulNbr));
 
 					*pb_CycleMode =
-						(BYTE) ((dw_Status >> 4) & 1);
+						(unsigned char) ((dw_Status >> 4) & 1);
 					*pb_InterruptEnable =
-						(BYTE) ((dw_Status >> 5) & 1);
+						(unsigned char) ((dw_Status >> 5) & 1);
 
 		    /******************************************************/
 					/* Test if extern gate used for clock or for signal B */
@@ -1569,25 +1569,25 @@
 								*pb_InputMode =
 									APCI1710_TOR_QUADRUPLE_MODE;
 							}
-						}	// if (dw_Status & 0x400)
+						}	/*  if (dw_Status & 0x400) */
 						else {
 							*pb_InputMode = 1;
-						}	// // if (dw_Status & 0x400)
+						}	/*  // if (dw_Status & 0x400) */
 
 		       /************************/
 						/* Extern gate not used */
 		       /************************/
 
 						*pb_ExternGate = 0;
-					}	// if (dw_Status & 0x600)
+					}	/*  if (dw_Status & 0x600) */
 					else {
 						*pb_InputMode =
-							(BYTE) ((dw_Status >> 6)
+							(unsigned char) ((dw_Status >> 6)
 							& 1);
 						*pb_ExternGate =
-							(BYTE) ((dw_Status >> 7)
+							(unsigned char) ((dw_Status >> 7)
 							& 1);
-					}	// if (dw_Status & 0x600)
+					}	/*  if (dw_Status & 0x600) */
 
 					*pb_TimingUnit =
 						devpriv->
@@ -1611,7 +1611,7 @@
 					i_ReturnValue = -5;
 				}
 
-			}	// if (b_TorCounter <= 1)
+			}	/*  if (b_TorCounter <= 1) */
 			else {
 		 /**********************************/
 				/* Tor counter selection is wrong */
@@ -1619,7 +1619,7 @@
 
 				DPRINTK("Tor counter selection is wrong \n");
 				i_ReturnValue = -4;
-			}	// if (b_TorCounter <= 1)
+			}	/*  if (b_TorCounter <= 1) */
 		} else {
 	      /******************************************/
 			/* The module is not a tor counter module */
@@ -1637,17 +1637,17 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_ReadTorCounterValue                   |
-|                               (BYTE_     b_BoardHandle,                    |
-|                                BYTE_     b_ModulNbr,                       |
-|				 BYTE_     b_TorCounter,                     |
-|                                UINT_    ui_TimeOut,                        |
-|                                PBYTE_   pb_TorCounterStatus,               |
+|                               (unsigned char_     b_BoardHandle,                    |
+|                                unsigned char_     b_ModulNbr,                       |
+|				 unsigned char_     b_TorCounter,                     |
+|                                unsigned int_    ui_TimeOut,                        |
+|                                unsigned char *_   pb_TorCounterStatus,               |
 |                                PULONG_ pul_TorCounterValue)                |
 +----------------------------------------------------------------------------+
 | Task        	case APCI1710_TOR_GETPROGRESSSTATUS: Return the tor counter
@@ -1660,15 +1660,15 @@
 |		      (pul_TorCounterValue) after a conting cycle stop       |
 |                     from selected tor counter module (b_ModulNbr).         |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle  : Handle of board APCI-1710       |
-|                     BYTE_ b_ModulNbr     : Selected module number (0 to 3) |
-|                     BYTE_ b_TorCounter   : Tor counter selection (0 or 1).
+| Input Parameters  : unsigned char_ b_BoardHandle  : Handle of board APCI-1710       |
+|                     unsigned char_ b_ModulNbr     : Selected module number (0 to 3) |
+|                     unsigned char_ b_TorCounter   : Tor counter selection (0 or 1).
 	b_ModulNbr    = CR_AREF(insn->chanspec);
-	b_ReadType    = (BYTE) data[0];
-	b_TorCounter  =	(BYTE) data[1];
-	ui_TimeOut	  = (UINT) data[2]; |
+	b_ReadType    = (unsigned char) data[0];
+	b_TorCounter  =	(unsigned char) data[1];
+	ui_TimeOut	  = (unsigned int) data[2]; |
 +----------------------------------------------------------------------------+
-| Output Parameters : PBYTE_  pb_TorCounterStatus : Return the tor counter   |
+| Output Parameters : unsigned char *_  pb_TorCounterStatus : Return the tor counter   |
 |                                                    status.                 |
 |                                               0 : Conting cycle not started|
 |                                                   Software gate not set.   |
@@ -1683,9 +1683,9 @@
 |                                                   function                 |
 |                                                 "i_APCI1710_InitTorCounter"|
 |						4 : Timeeout occur           |
-|                     PULONG  pul_TorCounterValue  : Tor counter value.
-	pb_TorCounterStatus=(PBYTE) &data[0];
-	pul_TorCounterValue=(PULONG) &data[1];    |
+|                     unsigned int *  pul_TorCounterValue  : Tor counter value.
+	pb_TorCounterStatus=(unsigned char *) &data[0];
+	pul_TorCounterValue=(unsigned int *) &data[1];    |
 +----------------------------------------------------------------------------+
 | Return Value      :  0: No error                                           |
 |                     -1: The handle parameter of the board is wrong         |
@@ -1700,27 +1700,27 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnBitsGetTorCounterProgressStatusAndValue(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnBitsGetTorCounterProgressStatusAndValue(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_Status;
-	DWORD dw_TimeOut = 0;
+	int i_ReturnValue = 0;
+	unsigned int dw_Status;
+	unsigned int dw_TimeOut = 0;
 
-	BYTE b_ModulNbr;
-	BYTE b_TorCounter;
-	BYTE b_ReadType;
-	UINT ui_TimeOut;
-	PBYTE pb_TorCounterStatus;
-	PULONG pul_TorCounterValue;
+	unsigned char b_ModulNbr;
+	unsigned char b_TorCounter;
+	unsigned char b_ReadType;
+	unsigned int ui_TimeOut;
+	unsigned char *pb_TorCounterStatus;
+	unsigned int *pul_TorCounterValue;
 
 	i_ReturnValue = insn->n;
 	b_ModulNbr = CR_AREF(insn->chanspec);
-	b_ReadType = (BYTE) data[0];
-	b_TorCounter = (BYTE) data[1];
-	ui_TimeOut = (UINT) data[2];
-	pb_TorCounterStatus = (PBYTE) & data[0];
-	pul_TorCounterValue = (PULONG) & data[1];
+	b_ReadType = (unsigned char) data[0];
+	b_TorCounter = (unsigned char) data[1];
+	ui_TimeOut = (unsigned int) data[2];
+	pb_TorCounterStatus = (unsigned char *) &data[0];
+	pul_TorCounterValue = (unsigned int *) &data[1];
 
 	/**************************/
 	/* Test the module number */
@@ -1896,7 +1896,7 @@
 											+
 											(16 * b_TorCounter) + (64 * b_ModulNbr));
 										break;
-									}	// if ((dw_Status & 4) == 4)
+									}	/*  if ((dw_Status & 4) == 4) */
 									else {
 				/*******************************/
 										/* Test if measurement stopped */
@@ -1927,7 +1927,7 @@
 												(16 * b_TorCounter) + (64 * b_ModulNbr));
 
 											break;
-										}	// if ((dw_Status & 2) == 2)
+										}	/*  if ((dw_Status & 2) == 2) */
 										else {
 				   /*******************************/
 											/* Test if measurement started */
@@ -1941,7 +1941,7 @@
 												*pb_TorCounterStatus
 													=
 													1;
-											}	// if ((dw_Status & 1) == 1)
+											}	/*  if ((dw_Status & 1) == 1) */
 											else {
 				      /***************************/
 												/* Measurement not started */
@@ -1950,9 +1950,9 @@
 												*pb_TorCounterStatus
 													=
 													0;
-											}	// if ((dw_Status & 1) == 1)
-										}	// if ((dw_Status & 2) == 2)
-									}	// if ((dw_Status & 8) == 8)
+											}	/*  if ((dw_Status & 1) == 1) */
+										}	/*  if ((dw_Status & 2) == 2) */
+									}	/*  if ((dw_Status & 8) == 8) */
 
 									if (dw_TimeOut == ui_TimeOut) {
 				/*****************/
@@ -1973,7 +1973,7 @@
 
 										mdelay(1000);
 									}
-								}	// for (;;)
+								}	/*  for (;;) */
 
 			  /*************************/
 								/* Test if timeout occur */
@@ -2001,8 +2001,8 @@
 
 						default:
 							printk("Inputs wrong\n");
-						}	// switch end
-					}	// if (dw_Status & 0x1)
+						}	/*  switch end */
+					}	/*  if (dw_Status & 0x1) */
 					else {
 		       /***************************/
 						/* Tor counter not enabled */
@@ -2010,7 +2010,7 @@
 
 						DPRINTK("Tor counter not enabled\n");
 						i_ReturnValue = -6;
-					}	// if (dw_Status & 0x1)
+					}	/*  if (dw_Status & 0x1) */
 				} else {
 		    /*******************************/
 					/* Tor counter not initialised */
@@ -2019,7 +2019,7 @@
 					DPRINTK("Tor counter not initialised\n");
 					i_ReturnValue = -5;
 				}
-			}	// if (b_TorCounter <= 1)
+			}	/*  if (b_TorCounter <= 1) */
 			else {
 		 /**********************************/
 				/* Tor counter selection is wrong */
@@ -2027,7 +2027,7 @@
 
 				DPRINTK("Tor counter selection is wrong\n");
 				i_ReturnValue = -4;
-			}	// if (b_TorCounter <= 1)
+			}	/*  if (b_TorCounter <= 1) */
 		} else {
 	      /******************************************/
 			/* The module is not a tor counter module */
@@ -2045,5 +2045,5 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Tor.h b/drivers/staging/comedi/drivers/addi-data/APCI1710_Tor.h
index c245d16..03a93cb 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Tor.h
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Tor.h
@@ -35,23 +35,23 @@
 /*
  * TOR_COUNTER INISIALISATION FUNCTION
  */
-INT i_APCI1710_InsnConfigInitTorCounter(struct comedi_device *dev,
+int i_APCI1710_InsnConfigInitTorCounter(struct comedi_device *dev,
 					struct comedi_subdevice *s,
 					struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1710_InsnWriteEnableDisableTorCounter(struct comedi_device *dev,
+int i_APCI1710_InsnWriteEnableDisableTorCounter(struct comedi_device *dev,
 						struct comedi_subdevice *s,
 						struct comedi_insn *insn,
 						unsigned int *data);
 
-INT i_APCI1710_InsnReadGetTorCounterInitialisation(struct comedi_device *dev,
+int i_APCI1710_InsnReadGetTorCounterInitialisation(struct comedi_device *dev,
 						   struct comedi_subdevice *s,
 						   struct comedi_insn *insn,
 						   unsigned int *data);
 /*
  * TOR_COUNTER READ FUNCTION
  */
-INT i_APCI1710_InsnBitsGetTorCounterProgressStatusAndValue(struct comedi_device *dev,
+int i_APCI1710_InsnBitsGetTorCounterProgressStatusAndValue(struct comedi_device *dev,
 							   struct comedi_subdevice *s,
 							   struct comedi_insn *insn,
 							   unsigned int *data);
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Ttl.c b/drivers/staging/comedi/drivers/addi-data/APCI1710_Ttl.c
index 68b1d26..d3d78d3 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Ttl.c
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Ttl.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -63,12 +63,12 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_InitTTLIODirection                    |
-|                               (BYTE_    b_BoardHandle,                     |
-|				 BYTE_    b_ModulNbr,                        |
-|				 BYTE_    b_PortAMode,                       |
-|				 BYTE_    b_PortBMode,                       |
-|				 BYTE_    b_PortCMode,                       |
-|				 BYTE_    b_PortDMode)                       |
+|                               (unsigned char_    b_BoardHandle,                     |
+|				 unsigned char_    b_ModulNbr,                        |
+|				 unsigned char_    b_PortAMode,                       |
+|				 unsigned char_    b_PortBMode,                       |
+|				 unsigned char_    b_PortCMode,                       |
+|				 unsigned char_    b_PortDMode)                       |
 +----------------------------------------------------------------------------+
 | Task           APCI1710_TTL_INIT (using defaults)   : Configure the TTL I/O operating mode from selected     |
 |                     module  (b_ModulNbr). You must calling this function be|
@@ -76,15 +76,15 @@
 				 APCI1710_TTL_INITDIRECTION(user inputs for direction)
 
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle         : Handle of board APCI-1710|
-|                     BYTE_ b_ModulNbr            : Module number to         |
+| Input Parameters  : unsigned char_ b_BoardHandle         : Handle of board APCI-1710|
+|                     unsigned char_ b_ModulNbr            : Module number to         |
 |                                                   configure (0 to 3)
-		b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-		b_InitType = (BYTE) data[0];
-		b_PortAMode	= (BYTE) data[1];
-		b_PortBMode = (BYTE) data[2];
-		b_PortCMode = (BYTE) data[3];
-		b_PortDMode	= (BYTE) data[4];|
+		b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+		b_InitType = (unsigned char) data[0];
+		b_PortAMode	= (unsigned char) data[1];
+		b_PortBMode = (unsigned char) data[2];
+		b_PortCMode = (unsigned char) data[3];
+		b_PortDMode	= (unsigned char) data[4];|
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -100,19 +100,19 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnConfigInitTTLIO(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnConfigInitTTLIO(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	BYTE b_ModulNbr;
-	BYTE b_InitType;
-	BYTE b_PortAMode;
-	BYTE b_PortBMode;
-	BYTE b_PortCMode;
-	BYTE b_PortDMode;
+	int i_ReturnValue = 0;
+	unsigned char b_ModulNbr;
+	unsigned char b_InitType;
+	unsigned char b_PortAMode;
+	unsigned char b_PortBMode;
+	unsigned char b_PortCMode;
+	unsigned char b_PortDMode;
 
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
-	b_InitType = (BYTE) data[0];
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
+	b_InitType = (unsigned char) data[0];
 	i_ReturnValue = insn->n;
 
 	/**************************/
@@ -172,10 +172,10 @@
 
 			case APCI1710_TTL_INITDIRECTION:
 
-				b_PortAMode = (BYTE) data[1];
-				b_PortBMode = (BYTE) data[2];
-				b_PortCMode = (BYTE) data[3];
-				b_PortDMode = (BYTE) data[4];
+				b_PortAMode = (unsigned char) data[1];
+				b_PortBMode = (unsigned char) data[2];
+				b_PortCMode = (unsigned char) data[3];
+				b_PortDMode = (unsigned char) data[4];
 
 	      /********************/
 				/* Test the version */
@@ -322,7 +322,7 @@
 				DPRINTK("\n");
 			default:
 				printk("Bad Config Type\n");
-			}	// switch end
+			}	/*  switch end */
 		} else {
 	      /**********************************/
 			/* The module is not a TTL module */
@@ -340,7 +340,7 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -352,11 +352,11 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_   i_APCI1710_ReadTTLIOChannelValue               |
-|                                       (BYTE_     b_BoardHandle,            |
-|                                        BYTE_     b_ModulNbr,               |
-|                                        BYTE_     b_SelectedPort,           |
-|                                        BYTE_     b_InputChannel,           |
-|                                        PBYTE_   pb_ChannelStatus)          |
+|                                       (unsigned char_     b_BoardHandle,            |
+|                                        unsigned char_     b_ModulNbr,               |
+|                                        unsigned char_     b_SelectedPort,           |
+|                                        unsigned char_     b_InputChannel,           |
+|                                        unsigned char *_   pb_ChannelStatus)          |
 +----------------------------------------------------------------------------+
 | Task              : Read the status from selected TTL digital input        |
 |                     (b_InputChannel)
@@ -366,32 +366,32 @@
 +----------------------------------------------------------------------------+
 
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle         : Handle of board APCI-1710|
-|                     BYTE_ b_ModulNbr            : Module number to         |
+| Input Parameters  : unsigned char_ b_BoardHandle         : Handle of board APCI-1710|
+|                     unsigned char_ b_ModulNbr            : Module number to         |
 |                                                   configure (0 to 7)       |
-|                     BYTE_ b_SelectedPort,       : Selection from TTL I/O   |
+|                     unsigned char_ b_SelectedPort,       : Selection from TTL I/O   |
 |                                                   port (0 to 2)            |
 |                                                      0 : Port A selection  |
 |                                                      1 : Port B selection  |
 |                                                      2 : Port C selection  |
 |                                                      3 : Port D selection  |
-|                     BYTE_ b_InputChannel        : Selection from digital   |
+|                     unsigned char_ b_InputChannel        : Selection from digital   |
 |                                                   input ( 0 to 2)
 APCI1710_TTL_READCHANNEL
 	b_ModulNbr	  = CR_AREF(insn->chanspec);
 	b_SelectedPort= CR_RANGE(insn->chanspec);
 	b_InputChannel= CR_CHAN(insn->chanspec);
-	b_ReadType	  = (BYTE) data[0];
+	b_ReadType	  = (unsigned char) data[0];
 
  APCI1710_TTL_READPORT|
 	b_ModulNbr	  = CR_AREF(insn->chanspec);
 	b_SelectedPort= CR_RANGE(insn->chanspec);
-	b_ReadType	  = (BYTE) data[0];
+	b_ReadType	  = (unsigned char) data[0];
 
 +----------------------------------------------------------------------------+
 | Output Parameters : data[0]
 
-	PBYTE_  pb_ChannelStatus    : Digital input channel    |
+	unsigned char *_  pb_ChannelStatus    : Digital input channel    |
 |                                                   status                   |
 |                                                   0 : Channle is not active|
 |                                                   1 : Channle is active    |
@@ -406,20 +406,20 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnBitsReadTTLIO(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnBitsReadTTLIO(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg;
-	BYTE b_ModulNbr;
-	BYTE b_SelectedPort;
-	BYTE b_InputChannel;
-	BYTE b_ReadType;
-	PBYTE pb_ChannelStatus;
-	PBYTE pb_PortValue;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg;
+	unsigned char b_ModulNbr;
+	unsigned char b_SelectedPort;
+	unsigned char b_InputChannel;
+	unsigned char b_ReadType;
+	unsigned char *pb_ChannelStatus;
+	unsigned char *pb_PortValue;
 
 	i_ReturnValue = insn->n;
-	b_ReadType = (BYTE) data[0];
+	b_ReadType = (unsigned char) data[0];
 	b_ModulNbr = CR_AREF(insn->chanspec);
 	b_SelectedPort = CR_RANGE(insn->chanspec);
 	b_InputChannel = CR_CHAN(insn->chanspec);
@@ -439,7 +439,7 @@
 			switch (b_ReadType) {
 
 			case APCI1710_TTL_READCHANNEL:
-				pb_ChannelStatus = (PBYTE) & data[0];
+				pb_ChannelStatus = (unsigned char *) &data[0];
 	      /********************************/
 				/* Test the TTL I/O port number */
 	      /********************************/
@@ -493,7 +493,7 @@
 
 								*pb_ChannelStatus
 									=
-									(BYTE) (
+									(unsigned char) (
 									(dw_StatusReg
 										>>
 										(8 * b_SelectedPort)) >> b_InputChannel) & 1;
@@ -533,7 +533,7 @@
 				break;
 
 			case APCI1710_TTL_READPORT:
-				pb_PortValue = (PBYTE) & data[0];
+				pb_PortValue = (unsigned char *) &data[0];
 			  /********************************/
 				/* Test the TTL I/O port number */
 			  /********************************/
@@ -578,7 +578,7 @@
 								(64 * b_ModulNbr));
 
 							*pb_PortValue =
-								(BYTE) (
+								(unsigned char) (
 								(dw_StatusReg >>
 									(8 * b_SelectedPort)) & 0xFF);
 						} else {
@@ -610,7 +610,7 @@
 			default:
 				printk("Bad ReadType\n");
 
-			}	//End Switch
+			}	/* End Switch */
 		} else {
 	      /**********************************/
 			/* The module is not a TTL module */
@@ -628,20 +628,20 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT i_APCI1710_InsnReadTTLIOAllPortValue(comedi_device
+| Function Name     : int i_APCI1710_InsnReadTTLIOAllPortValue(comedi_device
 *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)              |
 +----------------------------------------------------------------------------+
 | Task              : Read the status from all digital input ports           |
 |                     (port A, port B and port C) from selected TTL          |
 |		      module (b_ModulNbr) 				     |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle         : Handle of board APCI-1710|
-|                     BYTE_ b_ModulNbr            : Module number to         |
+| Input Parameters  : unsigned char_ b_BoardHandle         : Handle of board APCI-1710|
+|                     unsigned char_ b_ModulNbr            : Module number to         |
 |                                                   configure (0 to 3)       |
 +----------------------------------------------------------------------------+
 | Output Parameters : PULONG_  pul_PortValue      : Digital TTL inputs port  |
@@ -655,17 +655,17 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnReadTTLIOAllPortValue(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnReadTTLIOAllPortValue(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg;
-	BYTE b_ModulNbr;
-	PULONG pul_PortValue;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg;
+	unsigned char b_ModulNbr;
+	unsigned int *pul_PortValue;
 
-	b_ModulNbr = (BYTE) CR_AREF(insn->chanspec);
+	b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
 	i_ReturnValue = insn->n;
-	pul_PortValue = (PULONG) & data[0];
+	pul_PortValue = (unsigned int *) &data[0];
 
 	/**************************/
 	/* Test the module number */
@@ -777,7 +777,7 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -789,19 +789,19 @@
 /*
 +----------------------------------------------------------------------------+
 | Function Name     : _INT_ i_APCI1710_SetTTLIOChlOn                         |
-|                               (BYTE_           b_BoardHandle,              |
-|                                BYTE_           b_ModulNbr,                 |
-|                                BYTE_           b_OutputChannel)
-INT i_APCI1710_InsnWriteSetTTLIOChlOnOff(struct comedi_device *dev,struct comedi_subdevice *s,
+|                               (unsigned char_           b_BoardHandle,              |
+|                                unsigned char_           b_ModulNbr,                 |
+|                                unsigned char_           b_OutputChannel)
+int i_APCI1710_InsnWriteSetTTLIOChlOnOff(struct comedi_device *dev,struct comedi_subdevice *s,
 	struct comedi_insn *insn,unsigned int *data)           |
 +----------------------------------------------------------------------------+
 | Task              : Sets or resets  the output witch has been passed with the         |
 |                     parameter b_Channel. Setting an output means setting   |
 |                     an ouput high.                                         |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE_ b_BoardHandle   : Handle of board APCI-1710      |
-|                     BYTE_ b_ModulNbr      : Selected module number (0 to 3)|
-|                     BYTE_ b_OutputChannel : Selection from digital output  |
+| Input Parameters  : unsigned char_ b_BoardHandle   : Handle of board APCI-1710      |
+|                     unsigned char_ b_ModulNbr      : Selected module number (0 to 3)|
+|                     unsigned char_ b_OutputChannel : Selection from digital output  |
 |                                             channel (0 or 1)               |
 |                                                0      : PD0                |
 |                                                1      : PD1                |
@@ -811,7 +811,7 @@
 
   b_ModulNbr	   = CR_AREF(insn->chanspec);
 	b_OutputChannel= CR_CHAN(insn->chanspec);
-	ui_State	   = data[0]; // ON or OFF
+	ui_State	   = data[0]; /*  ON or OFF */
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -825,19 +825,19 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1710_InsnWriteSetTTLIOChlOnOff(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1710_InsnWriteSetTTLIOChlOnOff(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = 0;
-	DWORD dw_StatusReg = 0;
-	BYTE b_ModulNbr;
-	BYTE b_OutputChannel;
-	UINT ui_State;
+	int i_ReturnValue = 0;
+	unsigned int dw_StatusReg = 0;
+	unsigned char b_ModulNbr;
+	unsigned char b_OutputChannel;
+	unsigned int ui_State;
 
 	i_ReturnValue = insn->n;
 	b_ModulNbr = CR_AREF(insn->chanspec);
 	b_OutputChannel = CR_CHAN(insn->chanspec);
-	ui_State = data[0];	// ON or OFF
+	ui_State = data[0];	/*  ON or OFF */
 
 	/**************************/
 	/* Test the module number */
@@ -953,7 +953,7 @@
 									ui_Address
 									+
 									(64 * b_ModulNbr));
-								if (ui_State)	// ON
+								if (ui_State)	/*  ON */
 								{
 									dw_StatusReg
 										=
@@ -969,7 +969,7 @@
 										(b_OutputChannel
 											%
 											8));
-								} else	// Off
+								} else	/*  Off */
 								{
 									dw_StatusReg
 										=
@@ -1034,5 +1034,5 @@
 		i_ReturnValue = -2;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/APCI1710_Ttl.h b/drivers/staging/comedi/drivers/addi-data/APCI1710_Ttl.h
index 00915dd..c4f1134 100644
--- a/drivers/staging/comedi/drivers/addi-data/APCI1710_Ttl.h
+++ b/drivers/staging/comedi/drivers/addi-data/APCI1710_Ttl.h
@@ -24,21 +24,21 @@
 /*
  * TTL INISIALISATION FUNCTION
  */
-INT i_APCI1710_InsnConfigInitTTLIO(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnConfigInitTTLIO(struct comedi_device *dev, struct comedi_subdevice *s,
 				   struct comedi_insn *insn, unsigned int *data);
 
 /*
  * TTL INPUT FUNCTION
  */
-INT i_APCI1710_InsnBitsReadTTLIO(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1710_InsnBitsReadTTLIO(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
-INT i_APCI1710_InsnReadTTLIOAllPortValue(struct comedi_device *dev,
+int i_APCI1710_InsnReadTTLIOAllPortValue(struct comedi_device *dev,
 					 struct comedi_subdevice *s,
 					 struct comedi_insn *insn, unsigned int *data);
 
 /*
  * TTL OUTPUT FUNCTIONS
  */
-INT i_APCI1710_InsnWriteSetTTLIOChlOnOff(struct comedi_device *dev,
+int i_APCI1710_InsnWriteSetTTLIOChlOnOff(struct comedi_device *dev,
 					 struct comedi_subdevice *s,
 					 struct comedi_insn *insn, unsigned int *data);
diff --git a/drivers/staging/comedi/drivers/addi-data/addi_amcc_S5920.c b/drivers/staging/comedi/drivers/addi-data/addi_amcc_S5920.c
index b0907ec..6e9e7ed 100644
--- a/drivers/staging/comedi/drivers/addi-data/addi_amcc_S5920.c
+++ b/drivers/staging/comedi/drivers/addi-data/addi_amcc_S5920.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -49,37 +49,37 @@
 #include "addi_amcc_S5920.h"
 
 /*+----------------------------------------------------------------------------+*/
-/*| Function   Name   : INT i_AddiHeaderRW_ReadEeprom                          |*/
-/*|                               (INT    i_NbOfWordsToRead,                   |*/
-/*|                                DWORD dw_PCIBoardEepromAddress,             |*/
-/*|                                WORD   w_EepromStartAddress,                |*/
-/*|                                PWORD pw_DataRead)                          |*/
+/*| Function   Name   : int i_AddiHeaderRW_ReadEeprom                          |*/
+/*|                               (int    i_NbOfWordsToRead,                   |*/
+/*|                                unsigned int dw_PCIBoardEepromAddress,             |*/
+/*|                                unsigned short   w_EepromStartAddress,                |*/
+/*|                                unsigned short * pw_DataRead)                          |*/
 /*+----------------------------------------------------------------------------+*/
 /*| Task              : Read word from the 5920 eeprom.                        |*/
 /*+----------------------------------------------------------------------------+*/
-/*| Input Parameters  : INT    i_NbOfWordsToRead : Nbr. of word to read        |*/
-/*|                     DWORD dw_PCIBoardEepromAddress : Address of the eeprom |*/
-/*|                     WORD   w_EepromStartAddress : Eeprom strat address     |*/
+/*| Input Parameters  : int    i_NbOfWordsToRead : Nbr. of word to read        |*/
+/*|                     unsigned int dw_PCIBoardEepromAddress : Address of the eeprom |*/
+/*|                     unsigned short   w_EepromStartAddress : Eeprom strat address     |*/
 /*+----------------------------------------------------------------------------+*/
-/*| Output Parameters : PWORD pw_DataRead : Read data                          |*/
+/*| Output Parameters : unsigned short * pw_DataRead : Read data                          |*/
 /*+----------------------------------------------------------------------------+*/
 /*| Return Value      : -                                                      |*/
 /*+----------------------------------------------------------------------------+*/
 
-INT i_AddiHeaderRW_ReadEeprom(INT i_NbOfWordsToRead,
-	DWORD dw_PCIBoardEepromAddress,
-	WORD w_EepromStartAddress, PWORD pw_DataRead)
+int i_AddiHeaderRW_ReadEeprom(int i_NbOfWordsToRead,
+	unsigned int dw_PCIBoardEepromAddress,
+	unsigned short w_EepromStartAddress, unsigned short *pw_DataRead)
 {
-	DWORD dw_eeprom_busy = 0;
-	INT i_Counter = 0;
-	INT i_WordCounter;
-	INT i;
-	BYTE pb_ReadByte[1];
-	BYTE b_ReadLowByte = 0;
-	BYTE b_ReadHighByte = 0;
-	BYTE b_SelectedAddressLow = 0;
-	BYTE b_SelectedAddressHigh = 0;
-	WORD w_ReadWord = 0;
+	unsigned int dw_eeprom_busy = 0;
+	int i_Counter = 0;
+	int i_WordCounter;
+	int i;
+	unsigned char pb_ReadByte[1];
+	unsigned char b_ReadLowByte = 0;
+	unsigned char b_ReadHighByte = 0;
+	unsigned char b_SelectedAddressLow = 0;
+	unsigned char b_SelectedAddressHigh = 0;
+	unsigned short w_ReadWord = 0;
 
 	for (i_WordCounter = 0; i_WordCounter < i_NbOfWordsToRead;
 		i_WordCounter++) {
@@ -88,106 +88,99 @@
 				inl(dw_PCIBoardEepromAddress +
 				AMCC_OP_REG_MCSR);
 			dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-		}
-		while (dw_eeprom_busy == EEPROM_BUSY);
+		} while (dw_eeprom_busy == EEPROM_BUSY);
 
 		for (i_Counter = 0; i_Counter < 2; i_Counter++) {
-			b_SelectedAddressLow = (w_EepromStartAddress + i_Counter) % 256;	//Read the low 8 bit part
-			b_SelectedAddressHigh = (w_EepromStartAddress + i_Counter) / 256;	//Read the high 8 bit part
+			b_SelectedAddressLow = (w_EepromStartAddress + i_Counter) % 256;	/* Read the low 8 bit part */
+			b_SelectedAddressHigh = (w_EepromStartAddress + i_Counter) / 256;	/* Read the high 8 bit part */
 
-			//Select the load low address mode
+			/* Select the load low address mode */
 			outb(NVCMD_LOAD_LOW,
 				dw_PCIBoardEepromAddress + AMCC_OP_REG_MCSR +
 				3);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Load the low address
+			/* Load the low address */
 			outb(b_SelectedAddressLow,
 				dw_PCIBoardEepromAddress + AMCC_OP_REG_MCSR +
 				2);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Select the load high address mode
+			/* Select the load high address mode */
 			outb(NVCMD_LOAD_HIGH,
 				dw_PCIBoardEepromAddress + AMCC_OP_REG_MCSR +
 				3);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Load the high address
+			/* Load the high address */
 			outb(b_SelectedAddressHigh,
 				dw_PCIBoardEepromAddress + AMCC_OP_REG_MCSR +
 				2);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Select the READ mode
+			/* Select the READ mode */
 			outb(NVCMD_BEGIN_READ,
 				dw_PCIBoardEepromAddress + AMCC_OP_REG_MCSR +
 				3);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Read data into the EEPROM
+			/* Read data into the EEPROM */
 			*pb_ReadByte =
 				inb(dw_PCIBoardEepromAddress +
 				AMCC_OP_REG_MCSR + 2);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Select the upper address part
+			/* Select the upper address part */
 			if (i_Counter == 0) {
 				b_ReadLowByte = pb_ReadByte[0];
 			} else {
 				b_ReadHighByte = pb_ReadByte[0];
 			}
 
-			//Sleep
-			for (i = 0; i < 10000; i++) ;
+			/* Sleep */
+			msleep(1);
 
 		}
 		w_ReadWord =
@@ -196,8 +189,8 @@
 
 		pw_DataRead[i_WordCounter] = w_ReadWord;
 
-		w_EepromStartAddress += 2;	// to read the next word
+		w_EepromStartAddress += 2;	/*  to read the next word */
 
-	}			// for (...) i_NbOfWordsToRead
-	return (0);
+	}			/*  for (...) i_NbOfWordsToRead */
+	return 0;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/addi_amcc_S5920.h b/drivers/staging/comedi/drivers/addi-data/addi_amcc_S5920.h
index 9ae56bc..622a4ac 100644
--- a/drivers/staging/comedi/drivers/addi-data/addi_amcc_S5920.h
+++ b/drivers/staging/comedi/drivers/addi-data/addi_amcc_S5920.h
@@ -22,6 +22,6 @@
 #define NVCMD_BEGIN_READ	(0x7 << 5)	/* nvRam begin read command */
 #define NVCMD_BEGIN_WRITE	(0x6 << 5)	/* EEPROM begin write command */
 
-INT i_AddiHeaderRW_ReadEeprom(INT i_NbOfWordsToRead,
-			      DWORD dw_PCIBoardEepromAddress,
-			      WORD w_EepromStartAddress, PWORD pw_DataRead);
+int i_AddiHeaderRW_ReadEeprom(int i_NbOfWordsToRead,
+			      unsigned int dw_PCIBoardEepromAddress,
+			      unsigned short w_EepromStartAddress, unsigned short *pw_DataRead);
diff --git a/drivers/staging/comedi/drivers/addi-data/addi_amcc_s5933.h b/drivers/staging/comedi/drivers/addi-data/addi_amcc_s5933.h
index b50774c..d288289 100644
--- a/drivers/staging/comedi/drivers/addi-data/addi_amcc_s5933.h
+++ b/drivers/staging/comedi/drivers/addi-data/addi_amcc_s5933.h
@@ -85,7 +85,7 @@
 #define AMCC_OP_REG_MRTC		0x30
 #define AMCC_OP_REG_MBEF		0x34
 #define AMCC_OP_REG_INTCSR		0x38
-/* INT source */
+/* int source */
 #define  AMCC_OP_REG_INTCSR_SRC		(AMCC_OP_REG_INTCSR + 2)
 /* FIFO ctrl */
 #define  AMCC_OP_REG_INTCSR_FEC		(AMCC_OP_REG_INTCSR + 3)
@@ -343,7 +343,7 @@
 				*card = amcc;
 				return 0;	/* ok, card is found */
 			} else {
-				rt_printk(" - \nCard on requested position is used b:s %d:%d!\n",
+				printk(" - \nCard on requested position is used b:s %d:%d!\n",
 					  pci_bus, pci_slot);
 				return 2;	/* card exist but is used */
 			}
@@ -447,7 +447,7 @@
 		/* use autodetection */
 		card = ptr_find_free_pci_card_by_device(vendor_id, device_id);
 		if (card == NULL) {
-			rt_printk(" - Unused card not found in system!\n");
+			printk(" - Unused card not found in system!\n");
 			return NULL;
 		}
 	} else {
@@ -455,18 +455,18 @@
 							 pci_bus, pci_slot,
 							 &card)) {
 		case 1:
-			rt_printk(" - Card not found on requested position b:s %d:%d!\n",
+			printk(" - Card not found on requested position b:s %d:%d!\n",
 				  pci_bus, pci_slot);
 			return NULL;
 		case 2:
-			rt_printk(" - Card on requested position is used b:s %d:%d!\n",
+			printk(" - Card on requested position is used b:s %d:%d!\n",
 				  pci_bus, pci_slot);
 			return NULL;
 		}
 	}
 
 	if (pci_card_alloc(card, i_Master) != 0) {
-		rt_printk(" - Can't allocate card!\n");
+		printk(" - Can't allocate card!\n");
 		return NULL;
 
 	}
diff --git a/drivers/staging/comedi/drivers/addi-data/addi_common.c b/drivers/staging/comedi/drivers/addi-data/addi_common.c
index 618c69b..a56535f 100644
--- a/drivers/staging/comedi/drivers/addi-data/addi_common.c
+++ b/drivers/staging/comedi/drivers/addi-data/addi_common.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -68,25 +68,25 @@
 #include "addi_common.h"
 #include "addi_amcc_s5933.h"
 
-//Update-0.7.57->0.7.68MODULE_AUTHOR("ADDI-DATA GmbH <info@addi-data.com>");
-//Update-0.7.57->0.7.68MODULE_DESCRIPTION("Comedi ADDI-DATA module");
-//Update-0.7.57->0.7.68MODULE_LICENSE("GPL");
+/* Update-0.7.57->0.7.68MODULE_AUTHOR("ADDI-DATA GmbH <info@addi-data.com>"); */
+/* Update-0.7.57->0.7.68MODULE_DESCRIPTION("Comedi ADDI-DATA module"); */
+/* Update-0.7.57->0.7.68MODULE_LICENSE("GPL"); */
 
-#define devpriv ((addi_private *)dev->private)
-#define this_board ((boardtype *)dev->board_ptr)
+#define devpriv ((struct addi_private *)dev->private)
+#define this_board ((struct addi_board *)dev->board_ptr)
 
 #if defined(CONFIG_APCI_1710) || defined(CONFIG_APCI_3200) || defined(CONFIG_APCI_3300)
-//BYTE b_SaveFPUReg [94];
+/* BYTE b_SaveFPUReg [94]; */
 
 void fpu_begin(void)
 {
-	//asm ("fstenv b_SaveFPUReg");
+	/* asm ("fstenv b_SaveFPUReg"); */
 	kernel_fpu_begin();
 }
 
 void fpu_end(void)
 {
-	// asm ("frstor b_SaveFPUReg");
+	/*  asm ("frstor b_SaveFPUReg"); */
 	kernel_fpu_end();
 }
 #endif
@@ -219,7 +219,7 @@
 
 MODULE_DEVICE_TABLE(pci, addi_apci_tbl);
 
-static const boardtype boardtypes[] = {
+static const struct addi_board boardtypes[] = {
 #ifdef CONFIG_APCI_3120
 	{"apci3120",
 			APCI3120_BOARD_VENDOR_ID,
@@ -901,7 +901,7 @@
 		NULL},
 #endif
 #ifdef CONFIG_APCI_3300
-	//Begin JK 20.10.2004: APCI-3300 integration
+	/* Begin JK	.20.10.2004 = APCI-3300 integration */
 	{"apci3300",
 			APCI3200_BOARD_VENDOR_ID,
 			0x3007,
@@ -2525,16 +2525,16 @@
 #endif
 };
 
-#define n_boardtypes (sizeof(boardtypes)/sizeof(boardtype))
+#define n_boardtypes (sizeof(boardtypes)/sizeof(struct addi_board))
 
 struct comedi_driver driver_addi = {
-      driver_name:"addi_common",
-      module:THIS_MODULE,
-      attach:i_ADDI_Attach,
-      detach:i_ADDI_Detach,
-      num_names:n_boardtypes,
-      board_name:&boardtypes[0].pc_DriverName,
-      offset:sizeof(boardtype),
+	.driver_name = "addi_common",
+	.module = THIS_MODULE,
+	.attach = i_ADDI_Attach,
+	.detach = i_ADDI_Detach,
+	.num_names = n_boardtypes,
+	.board_name = &boardtypes[0].pc_DriverName,
+	.offset = sizeof(struct addi_board),
 };
 
 COMEDI_PCI_INITCLEANUP(driver_addi, addi_apci_tbl);
@@ -2559,11 +2559,11 @@
 +----------------------------------------------------------------------------+
 */
 
-static int i_ADDI_Attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int i_ADDI_Attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int ret, pages, i, n_subdevices;
-	DWORD dw_Dummy;
+	unsigned int dw_Dummy;
 	resource_size_t io_addr[5];
 	unsigned int irq;
 	resource_size_t iobase_a, iobase_main, iobase_addon, iobase_reserved;
@@ -2575,26 +2575,28 @@
 	sprintf(c_Identifier, "Addi-Data GmbH Comedi %s",
 		this_board->pc_DriverName);
 
-	if ((ret = alloc_private(dev, sizeof(addi_private))) < 0) {
-	  	return -ENOMEM;
-	}
+	ret = alloc_private(dev, sizeof(struct addi_private));
+	if (ret < 0)
+		return -ENOMEM;
 
 	if (!pci_list_builded) {
-		v_pci_card_list_init(this_board->i_VendorId, 1);	//1 for displaying the list..
+		v_pci_card_list_init(this_board->i_VendorId, 1);	/* 1 for displaying the list.. */
 		pci_list_builded = 1;
 	}
-	//rt_printk("comedi%d: addi_common: board=%s",dev->minor,this_board->pc_DriverName);
+	/* printk("comedi%d: addi_common: board=%s",dev->minor,this_board->pc_DriverName); */
 
 	if ((this_board->i_Dma) && (it->options[2] == 0)) {
 		i_Dma = 1;
 	}
 
-	if ((card = ptr_select_and_alloc_pci_card(this_board->i_VendorId,
-				this_board->i_DeviceId,
-				it->options[0],
-				it->options[1], i_Dma)) == NULL) {
+	card = ptr_select_and_alloc_pci_card(this_board->i_VendorId,
+					     this_board->i_DeviceId,
+					     it->options[0],
+					     it->options[1], i_Dma);
+
+	if (card == NULL)
 		return -EIO;
-	}
+
 	devpriv->allocated = 1;
 
 	if ((i_pci_card_data(card, &pci_bus, &pci_slot, &pci_func, &io_addr[0],
@@ -2617,63 +2619,63 @@
 	   /************************************/
 
 		if (this_board->i_IorangeBase1 != 0) {
-			dev->iobase = (unsigned long)iobase_main;	// DAQ base address...
+			dev->iobase = (unsigned long)iobase_main;	/*  DAQ base address... */
 		} else {
-			dev->iobase = (unsigned long)iobase_a;	// DAQ base address...
+			dev->iobase = (unsigned long)iobase_a;	/*  DAQ base address... */
 		}
 
 		dev->board_name = this_board->pc_DriverName;
 		devpriv->amcc = card;
-		devpriv->iobase = (INT) dev->iobase;
-		devpriv->i_IobaseAmcc = (INT) iobase_a;	//AMCC base address...
-		devpriv->i_IobaseAddon = (INT) iobase_addon;	//ADD ON base address....
-		devpriv->i_IobaseReserved = (INT) iobase_reserved;
+		devpriv->iobase = (int) dev->iobase;
+		devpriv->i_IobaseAmcc = (int) iobase_a;	/* AMCC base address... */
+		devpriv->i_IobaseAddon = (int) iobase_addon;	/* ADD ON base address.... */
+		devpriv->i_IobaseReserved = (int) iobase_reserved;
 		devpriv->ps_BoardInfo = this_board;
 	} else {
 		dev->board_name = this_board->pc_DriverName;
 		dev->iobase = (unsigned long)io_addr[2];
 		devpriv->amcc = card;
-		devpriv->iobase = (INT) io_addr[2];
+		devpriv->iobase = (int) io_addr[2];
 		devpriv->ps_BoardInfo = this_board;
-		devpriv->i_IobaseReserved = (INT) io_addr[3];
+		devpriv->i_IobaseReserved = (int) io_addr[3];
 		printk("\nioremap begin");
 		devpriv->dw_AiBase =
-			(ULONG_PTR) ioremap(io_addr[3],
+			(unsigned long) ioremap(io_addr[3],
 			this_board->i_IorangeBase3);
 		printk("\nioremap end");
 	}
 
-	//##
+	/* ## */
 
 	if (irq > 0) {
-		if (comedi_request_irq(irq, v_ADDI_Interrupt, IRQF_SHARED,
+		if (request_irq(irq, v_ADDI_Interrupt, IRQF_SHARED,
 				c_Identifier, dev) < 0) {
 			printk(", unable to allocate IRQ %u, DISABLING IT",
 				irq);
 			irq = 0;	/* Can't use IRQ */
 		} else {
-			rt_printk("\nirq=%u", irq);
+			printk("\nirq=%u", irq);
 		}
 	} else {
-		rt_printk(", IRQ disabled");
+		printk(", IRQ disabled");
 	}
 
 	printk("\nOption %d %d %d\n", it->options[0], it->options[1],
 		it->options[2]);
 	dev->irq = irq;
 
-	// Read eepeom and fill boardtype Structure
+	/*  Read eepeom and fill addi_board Structure */
 
 	if (this_board->i_PCIEeprom) {
 		printk("\nPCI Eeprom used");
 		if (!(strcmp(this_board->pc_EepromChip, "S5920"))) {
-			// Set 3 wait stait
+			/*  Set 3 wait stait */
 			if (!(strcmp(this_board->pc_DriverName, "apci035"))) {
 				outl(0x80808082, devpriv->i_IobaseAmcc + 0x60);
 			} else {
 				outl(0x83838383, devpriv->i_IobaseAmcc + 0x60);
 			}
-			// Enable the interrupt for the controler
+			/*  Enable the interrupt for the controler */
 			dw_Dummy = inl(devpriv->i_IobaseAmcc + 0x38);
 			outl(dw_Dummy | 0x2000, devpriv->i_IobaseAmcc + 0x38);
 			printk("\nEnable the interrupt for the controler");
@@ -2694,16 +2696,15 @@
 	if (this_board->i_Dma) {
 		printk("\nDMA used");
 		if (devpriv->us_UseDma == ADDI_ENABLE) {
-			// alloc DMA buffers
+			/*  alloc DMA buffers */
 			devpriv->b_DmaDoubleBuffer = 0;
 			for (i = 0; i < 2; i++) {
 				for (pages = 4; pages >= 0; pages--) {
-					if ((devpriv->ul_DmaBufferVirtual[i] =
-							(void *)
-							__get_free_pages
-							(GFP_KERNEL, pages))) {
+					devpriv->ul_DmaBufferVirtual[i] =
+						(void *) __get_free_pages(GFP_KERNEL, pages);
+
+					if (devpriv->ul_DmaBufferVirtual[i])
 						break;
-					}
 				}
 				if (devpriv->ul_DmaBufferVirtual[i]) {
 					devpriv->ui_DmaBufferPages[i] = pages;
@@ -2718,7 +2719,7 @@
 				}
 			}
 			if (!devpriv->ul_DmaBufferVirtual[0]) {
-				rt_printk
+				printk
 					(", Can't allocate DMA buffer, DMA disabled!");
 				devpriv->us_UseDma = ADDI_DISABLE;
 			}
@@ -2729,7 +2730,7 @@
 		}
 
 		if ((devpriv->us_UseDma == ADDI_ENABLE)) {
-			rt_printk("\nDMA ENABLED\n");
+			printk("\nDMA ENABLED\n");
 		} else {
 			printk("\nDMA DISABLED\n");
 		}
@@ -2739,23 +2740,24 @@
 #ifdef CONFIG_APCI_1710
 		i_ADDI_AttachPCI1710(dev);
 
-		// save base address
+		/*  save base address */
 		devpriv->s_BoardInfos.ui_Address = io_addr[2];
 #endif
 	} else {
-		//Update-0.7.57->0.7.68dev->n_subdevices = 7;
+		/* Update-0.7.57->0.7.68dev->n_subdevices = 7; */
 		n_subdevices = 7;
-		if ((ret = alloc_subdevices(dev, n_subdevices)) < 0)
+		ret = alloc_subdevices(dev, n_subdevices);
+		if (ret < 0)
 			return ret;
 
-		// Allocate and Initialise AI Subdevice Structures
+		/*  Allocate and Initialise AI Subdevice Structures */
 		s = dev->subdevices + 0;
 		if ((this_board->i_NbrAiChannel)
 			|| (this_board->i_NbrAiChannelDiff)) {
 			dev->read_subdev = s;
 			s->type = COMEDI_SUBD_AI;
 			s->subdev_flags =
-				SDF_READABLE | SDF_RT | SDF_COMMON | SDF_GROUND
+				SDF_READABLE | SDF_COMMON | SDF_GROUND
 				| SDF_DIFF;
 			if (this_board->i_NbrAiChannel) {
 				s->n_chan = this_board->i_NbrAiChannel;
@@ -2786,13 +2788,11 @@
 			s->type = COMEDI_SUBD_UNUSED;
 		}
 
-		// Allocate and Initialise AO Subdevice Structures
+		/*  Allocate and Initialise AO Subdevice Structures */
 		s = dev->subdevices + 1;
 		if (this_board->i_NbrAoChannel) {
 			s->type = COMEDI_SUBD_AO;
-			s->subdev_flags =
-				SDF_WRITEABLE | SDF_GROUND | SDF_COMMON |
-				SDF_RT;
+			s->subdev_flags = SDF_WRITEABLE | SDF_GROUND | SDF_COMMON;
 			s->n_chan = this_board->i_NbrAoChannel;
 			s->maxdata = this_board->i_AoMaxdata;
 			s->len_chanlist = this_board->i_NbrAoChannel;
@@ -2804,12 +2804,11 @@
 		} else {
 			s->type = COMEDI_SUBD_UNUSED;
 		}
-		// Allocate and Initialise DI Subdevice Structures
+		/*  Allocate and Initialise DI Subdevice Structures */
 		s = dev->subdevices + 2;
 		if (this_board->i_NbrDiChannel) {
 			s->type = COMEDI_SUBD_DI;
-			s->subdev_flags =
-				SDF_READABLE | SDF_RT | SDF_GROUND | SDF_COMMON;
+			s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_COMMON;
 			s->n_chan = this_board->i_NbrDiChannel;
 			s->maxdata = 1;
 			s->len_chanlist = this_board->i_NbrDiChannel;
@@ -2824,20 +2823,19 @@
 		} else {
 			s->type = COMEDI_SUBD_UNUSED;
 		}
-		// Allocate and Initialise DO Subdevice Structures
+		/*  Allocate and Initialise DO Subdevice Structures */
 		s = dev->subdevices + 3;
 		if (this_board->i_NbrDoChannel) {
 			s->type = COMEDI_SUBD_DO;
 			s->subdev_flags =
-				SDF_READABLE | SDF_WRITEABLE | SDF_RT |
-				SDF_GROUND | SDF_COMMON;
+				SDF_READABLE | SDF_WRITEABLE | SDF_GROUND | SDF_COMMON;
 			s->n_chan = this_board->i_NbrDoChannel;
 			s->maxdata = this_board->i_DoMaxdata;
 			s->len_chanlist = this_board->i_NbrDoChannel;
 			s->range_table = &range_digital;
 			s->io_bits = 0xf;	/* all bits output */
 
-			s->insn_config = this_board->i_hwdrv_InsnConfigDigitalOutput;	//for digital output memory..
+			s->insn_config = this_board->i_hwdrv_InsnConfigDigitalOutput;	/* for digital output memory.. */
 			s->insn_write =
 				this_board->i_hwdrv_InsnWriteDigitalOutput;
 			s->insn_bits =
@@ -2848,13 +2846,11 @@
 			s->type = COMEDI_SUBD_UNUSED;
 		}
 
-		// Allocate and Initialise Timer Subdevice Structures
+		/*  Allocate and Initialise Timer Subdevice Structures */
 		s = dev->subdevices + 4;
 		if (this_board->i_Timer) {
 			s->type = COMEDI_SUBD_TIMER;
-			s->subdev_flags =
-				SDF_WRITEABLE | SDF_RT | SDF_GROUND |
-				SDF_COMMON;
+			s->subdev_flags = SDF_WRITEABLE | SDF_GROUND | SDF_COMMON;
 			s->n_chan = 1;
 			s->maxdata = 0;
 			s->len_chanlist = 1;
@@ -2868,13 +2864,12 @@
 			s->type = COMEDI_SUBD_UNUSED;
 		}
 
-		// Allocate and Initialise TTL
+		/*  Allocate and Initialise TTL */
 		s = dev->subdevices + 5;
 		if (this_board->i_NbrTTLChannel) {
 			s->type = COMEDI_SUBD_TTLIO;
 			s->subdev_flags =
-				SDF_WRITEABLE | SDF_READABLE | SDF_RT |
-				SDF_GROUND | SDF_COMMON;
+				SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
 			s->n_chan = this_board->i_NbrTTLChannel;
 			s->maxdata = 1;
 			s->io_bits = 0;	/* all bits input */
@@ -2926,7 +2921,7 @@
 +----------------------------------------------------------------------------+
 */
 
-static int i_ADDI_Detach(struct comedi_device * dev)
+static int i_ADDI_Detach(struct comedi_device *dev)
 {
 
 	if (dev->private) {
@@ -2935,7 +2930,7 @@
 		}
 
 		if (dev->irq) {
-			comedi_free_irq(dev->irq, dev);
+			free_irq(dev->irq, dev);
 		}
 
 		if ((devpriv->ps_BoardInfo->pc_EepromChip == NULL)
@@ -2965,7 +2960,7 @@
 		}
 
 		if (pci_list_builded) {
-			//v_pci_card_list_cleanup(PCI_VENDOR_ID_AMCC);
+			/* v_pci_card_list_cleanup(PCI_VENDOR_ID_AMCC); */
 			v_pci_card_list_cleanup(this_board->i_VendorId);
 			pci_list_builded = 0;
 		}
@@ -2992,18 +2987,18 @@
 +----------------------------------------------------------------------------+
 */
 
-static int i_ADDI_Reset(struct comedi_device * dev)
+static int i_ADDI_Reset(struct comedi_device *dev)
 {
 
 	this_board->i_hwdrv_Reset(dev);
 	return 0;
 }
 
-// Interrupt function
+/* Interrupt function */
 /*
 +----------------------------------------------------------------------------+
 | Function name     :                                                        |
-|static void v_ADDI_Interrupt(int irq, void *d  PT_REGS_ARG)                 |
+|static void v_ADDI_Interrupt(int irq, void *d)                 |
 |                                        									 |
 +----------------------------------------------------------------------------+
 | Task              : Registerd interrupt routine						     |
@@ -3018,14 +3013,14 @@
 +----------------------------------------------------------------------------+
 */
 
-static irqreturn_t v_ADDI_Interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t v_ADDI_Interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	this_board->v_hwdrv_Interrupt(irq, d);
 	return IRQ_RETVAL(1);
 }
 
-// EEPROM Read Function
+/* EEPROM Read Function */
 /*
 +----------------------------------------------------------------------------+
 | Function name     :                                                        |
@@ -3046,17 +3041,17 @@
 +----------------------------------------------------------------------------+
 */
 
-static int i_ADDIDATA_InsnReadEeprom(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int i_ADDIDATA_InsnReadEeprom(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	WORD w_Data;
-	WORD w_Address;
-	w_Address = CR_CHAN(insn->chanspec);	// address to be read as 0,1,2,3...255
+	unsigned short w_Data;
+	unsigned short w_Address;
+	w_Address = CR_CHAN(insn->chanspec);	/*  address to be read as 0,1,2,3...255 */
 
 	w_Data = w_EepromReadWord(devpriv->i_IobaseAmcc,
 		this_board->pc_EepromChip, 0x100 + (2 * w_Address));
 	data[0] = w_Data;
-	//multiplied by 2 bcozinput will be like 0,1,2...255
+	/* multiplied by 2 bcozinput will be like 0,1,2...255 */
 	return insn->n;
 
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/addi_common.h b/drivers/staging/comedi/drivers/addi-data/addi_common.h
index 19df5c1..edd657b 100644
--- a/drivers/staging/comedi/drivers/addi-data/addi_common.h
+++ b/drivers/staging/comedi/drivers/addi-data/addi_common.h
@@ -36,26 +36,12 @@
 #define ERROR	-1
 #define SUCCESS	1
 
-/* variable type definition */
-typedef unsigned char BYTE, *PBYTE;
-typedef short SHORT, *PSHORT;
-typedef unsigned short USHORT, *PUSHORT;
-typedef unsigned short WORD, *PWORD;
-typedef int INT, *PINT;;
-typedef unsigned int UINT, *PUINT;
-typedef int LONG, *PLONG;		/* 32-bit */
-typedef unsigned int ULONG, *PULONG;	/* 32-bit */
-typedef unsigned int DWORD, *PDWORD;	/* 32-bit */
-typedef unsigned long ULONG_PTR;
-
-typedef const struct comedi_lrange *PCRANGE;
-
-#define LOBYTE(W)	(BYTE)((W) & 0xFF)
-#define HIBYTE(W)	(BYTE)(((W) >> 8) & 0xFF)
-#define MAKEWORD(H, L)	(USHORT)((L) | ((H) << 8))
-#define LOWORD(W)	(USHORT)((W) & 0xFFFF)
-#define HIWORD(W)	(USHORT)(((W) >> 16) & 0xFFFF)
-#define MAKEDWORD(H, L)	(UINT)((L) | ((H) << 16))
+#define LOBYTE(W)	(unsigned char)((W) & 0xFF)
+#define HIBYTE(W)	(unsigned char)(((W) >> 8) & 0xFF)
+#define MAKEWORD(H, L)	(unsigned short)((L) | ((H) << 8))
+#define LOWORD(W)	(unsigned short)((W) & 0xFFFF)
+#define HIWORD(W)	(unsigned short)(((W) >> 16) & 0xFFFF)
+#define MAKEDWORD(H, L)	(unsigned int)((L) | ((H) << 16))
 
 #define ADDI_ENABLE		1
 #define ADDI_DISABLE		0
@@ -75,37 +61,37 @@
 /* Structures */
 
 /* structure for the boardtype */
-typedef struct {
-	const char *pc_DriverName;	// driver name
-	INT i_VendorId;		//PCI vendor a device ID of card
-	INT i_DeviceId;
-	INT i_IorangeBase0;
-	INT i_IorangeBase1;
-	INT i_IorangeBase2;	//  base 2 range
-	INT i_IorangeBase3;	//  base 3 range
-	INT i_PCIEeprom;	// eeprom present or not
-	char *pc_EepromChip;	// type of chip
-	INT i_NbrAiChannel;	// num of A/D chans
-	INT i_NbrAiChannelDiff;	// num of A/D chans in diff mode
-	INT i_AiChannelList;	// len of chanlist
-	INT i_NbrAoChannel;	// num of D/A chans
-	INT i_AiMaxdata;	// resolution of A/D
-	INT i_AoMaxdata;	// resolution of D/A
-	PCRANGE pr_AiRangelist;	// rangelist for A/D
-	PCRANGE pr_AoRangelist;	// rangelist for D/A
+struct addi_board {
+	const char *pc_DriverName;	/*  driver name */
+	int i_VendorId;		/* PCI vendor a device ID of card */
+	int i_DeviceId;
+	int i_IorangeBase0;
+	int i_IorangeBase1;
+	int i_IorangeBase2;	/*   base 2 range */
+	int i_IorangeBase3;	/*   base 3 range */
+	int i_PCIEeprom;	/*  eeprom present or not */
+	char *pc_EepromChip;	/*  type of chip */
+	int i_NbrAiChannel;	/*  num of A/D chans */
+	int i_NbrAiChannelDiff;	/*  num of A/D chans in diff mode */
+	int i_AiChannelList;	/*  len of chanlist */
+	int i_NbrAoChannel;	/*  num of D/A chans */
+	int i_AiMaxdata;	/*  resolution of A/D */
+	int i_AoMaxdata;	/*  resolution of D/A */
+        const struct comedi_lrange *pr_AiRangelist;	/* rangelist for A/D */
+        const struct comedi_lrange *pr_AoRangelist;	/* rangelist for D/A */
 
-	INT i_NbrDiChannel;	// Number of DI channels
-	INT i_NbrDoChannel;	// Number of DO channels
-	INT i_DoMaxdata;	// data to set all chanels high
+	int i_NbrDiChannel;	/*  Number of DI channels */
+	int i_NbrDoChannel;	/*  Number of DO channels */
+	int i_DoMaxdata;	/*  data to set all chanels high */
 
-	INT i_NbrTTLChannel;	// Number of TTL channels
-	PCRANGE pr_TTLRangelist;	// rangelist for TTL
+	int i_NbrTTLChannel;	/*  Number of TTL channels */
+	const struct comedi_lrange *pr_TTLRangelist;	/* rangelist for TTL */
 
-	INT i_Dma;		// dma present or not
-	INT i_Timer;		//   timer subdevice present or not
-	BYTE b_AvailableConvertUnit;
-	UINT ui_MinAcquisitiontimeNs;	// Minimum Acquisition in Nano secs
-	UINT ui_MinDelaytimeNs;	// Minimum Delay in Nano secs
+	int i_Dma;		/*  dma present or not */
+	int i_Timer;		/*    timer subdevice present or not */
+	unsigned char b_AvailableConvertUnit;
+	unsigned int ui_MinAcquisitiontimeNs;	/*  Minimum Acquisition in Nano secs */
+	unsigned int ui_MinDelaytimeNs;	/*  Minimum Delay in Nano secs */
 
 	/* interrupt and reset */
 	void (*v_hwdrv_Interrupt)(int irq, void *d);
@@ -213,21 +199,21 @@
 	int (*i_hwdr_WriteTTLIOChlOnOff)(struct comedi_device *dev,
 					 struct comedi_subdevice *s,
 					 struct comedi_insn *insn, unsigned int *data);
-} boardtype;
+};
 
-//MODULE INFO STRUCTURE
+/* MODULE INFO STRUCTURE */
 
-typedef union {
+union str_ModuleInfo {
 	/* Incremental counter infos */
 	struct {
 		union {
 			struct {
-				BYTE b_ModeRegister1;
-				BYTE b_ModeRegister2;
-				BYTE b_ModeRegister3;
-				BYTE b_ModeRegister4;
+				unsigned char b_ModeRegister1;
+				unsigned char b_ModeRegister2;
+				unsigned char b_ModeRegister3;
+				unsigned char b_ModeRegister4;
 			} s_ByteModeRegister;
-			DWORD dw_ModeRegister1_2_3_4;
+			unsigned int dw_ModeRegister1_2_3_4;
 		} s_ModeRegister;
 
 		struct {
@@ -244,25 +230,25 @@
 
 	/* SSI infos */
 	struct {
-		BYTE b_SSIProfile;
-		BYTE b_PositionTurnLength;
-		BYTE b_TurnCptLength;
-		BYTE b_SSIInit;
+		unsigned char b_SSIProfile;
+		unsigned char b_PositionTurnLength;
+		unsigned char b_TurnCptLength;
+		unsigned char b_SSIInit;
 	} s_SSICounterInfo;
 
 	/* TTL I/O infos */
 	struct {
-		BYTE b_TTLInit;
-		BYTE b_PortConfiguration[4];
+		unsigned char b_TTLInit;
+		unsigned char b_PortConfiguration[4];
 	} s_TTLIOInfo;
 
 	/* Digital I/O infos */
 	struct {
-		BYTE b_DigitalInit;
-		BYTE b_ChannelAMode;
-		BYTE b_ChannelBMode;
-		BYTE b_OutputMemoryEnabled;
-		DWORD dw_OutputMemory;
+		unsigned char b_DigitalInit;
+		unsigned char b_ChannelAMode;
+		unsigned char b_ChannelBMode;
+		unsigned char b_OutputMemoryEnabled;
+		unsigned int dw_OutputMemory;
 	} s_DigitalIOInfo;
 
       /*********************/
@@ -271,14 +257,14 @@
 
 	struct {
 		struct {
-			BYTE b_82X54Init;
-			BYTE b_InputClockSelection;
-			BYTE b_InputClockLevel;
-			BYTE b_OutputLevel;
-			BYTE b_HardwareGateLevel;
-			DWORD dw_ConfigurationWord;
+			unsigned char b_82X54Init;
+			unsigned char b_InputClockSelection;
+			unsigned char b_InputClockLevel;
+			unsigned char b_OutputLevel;
+			unsigned char b_HardwareGateLevel;
+			unsigned int dw_ConfigurationWord;
 		} s_82X54TimerInfo[3];
-		BYTE b_InterruptMask;
+		unsigned char b_InterruptMask;
 	} s_82X54ModuleInfo;
 
       /*********************/
@@ -286,13 +272,13 @@
       /*********************/
 
 	struct {
-		BYTE b_ChronoInit;
-		BYTE b_InterruptMask;
-		BYTE b_PCIInputClock;
-		BYTE b_TimingUnit;
-		BYTE b_CycleMode;
+		unsigned char b_ChronoInit;
+		unsigned char b_InterruptMask;
+		unsigned char b_PCIInputClock;
+		unsigned char b_TimingUnit;
+		unsigned char b_CycleMode;
 		double d_TimingInterval;
-		DWORD dw_ConfigReg;
+		unsigned int dw_ConfigReg;
 	} s_ChronoModuleInfo;
 
       /***********************/
@@ -301,154 +287,154 @@
 
 	struct {
 		struct {
-			BYTE b_PulseEncoderInit;
+			unsigned char b_PulseEncoderInit;
 		} s_PulseEncoderInfo[4];
-		DWORD dw_SetRegister;
-		DWORD dw_ControlRegister;
-		DWORD dw_StatusRegister;
+		unsigned int dw_SetRegister;
+		unsigned int dw_ControlRegister;
+		unsigned int dw_StatusRegister;
 	} s_PulseEncoderModuleInfo;
 
 	/* Tor conter infos */
 	struct {
 		struct {
-			BYTE b_TorCounterInit;
-			BYTE b_TimingUnit;
-			BYTE b_InterruptEnable;
+			unsigned char b_TorCounterInit;
+			unsigned char b_TimingUnit;
+			unsigned char b_InterruptEnable;
 			double d_TimingInterval;
-			ULONG ul_RealTimingInterval;
+			unsigned int ul_RealTimingInterval;
 		} s_TorCounterInfo[2];
-		BYTE b_PCIInputClock;
+		unsigned char b_PCIInputClock;
 	} s_TorCounterModuleInfo;
 
 	/* PWM infos */
 	struct {
 		struct {
-			BYTE b_PWMInit;
-			BYTE b_TimingUnit;
-			BYTE b_InterruptEnable;
+			unsigned char b_PWMInit;
+			unsigned char b_TimingUnit;
+			unsigned char b_InterruptEnable;
 			double d_LowTiming;
 			double d_HighTiming;
-			ULONG ul_RealLowTiming;
-			ULONG ul_RealHighTiming;
+			unsigned int ul_RealLowTiming;
+			unsigned int ul_RealHighTiming;
 		} s_PWMInfo[2];
-		BYTE b_ClockSelection;
+		unsigned char b_ClockSelection;
 	} s_PWMModuleInfo;
 
 	/* ETM infos */
 	struct {
 		struct {
-			BYTE b_ETMEnable;
-			BYTE b_ETMInterrupt;
+			unsigned char b_ETMEnable;
+			unsigned char b_ETMInterrupt;
 		} s_ETMInfo[2];
-		BYTE b_ETMInit;
-		BYTE b_TimingUnit;
-		BYTE b_ClockSelection;
+		unsigned char b_ETMInit;
+		unsigned char b_TimingUnit;
+		unsigned char b_ClockSelection;
 		double d_TimingInterval;
-		ULONG ul_Timing;
+		unsigned int ul_Timing;
 	} s_ETMModuleInfo;
 
 	/* CDA infos */
 	struct {
-		BYTE b_CDAEnable;
-		BYTE b_CDAInterrupt;
-		BYTE b_CDAInit;
-		BYTE b_FctSelection;
-		BYTE b_CDAReadFIFOOverflow;
+		unsigned char b_CDAEnable;
+		unsigned char b_CDAInterrupt;
+		unsigned char b_CDAInit;
+		unsigned char b_FctSelection;
+		unsigned char b_CDAReadFIFOOverflow;
 	} s_CDAModuleInfo;
 
-} str_ModuleInfo;
+};
 
 /* Private structure for the addi_apci3120 driver */
-typedef struct {
+struct addi_private {
 
-	INT iobase;
-	INT i_IobaseAmcc;	// base+size for AMCC chip
-	INT i_IobaseAddon;	//addon base address
-	INT i_IobaseReserved;
-	ULONG_PTR dw_AiBase;
-	struct pcilst_struct *amcc;	// ptr too AMCC data
-	BYTE allocated;		// we have blocked card
-	BYTE b_ValidDriver;	// driver is ok
-	BYTE b_AiContinuous;	// we do unlimited AI
-	BYTE b_AiInitialisation;
-	UINT ui_AiActualScan;	//how many scans we finished
-	UINT ui_AiBufferPtr;	// data buffer ptr in samples
-	UINT ui_AiNbrofChannels;	// how many channels is measured
-	UINT ui_AiScanLength;	// Length of actual scanlist
-	UINT ui_AiActualScanPosition;	// position in actual scan
-	PUINT pui_AiChannelList;	// actual chanlist
-	UINT ui_AiChannelList[32];	// actual chanlist
-	BYTE b_AiChannelConfiguration[32];	// actual chanlist
-	UINT ui_AiReadData[32];
-	DWORD dw_AiInitialised;
-	UINT ui_AiTimer0;	//Timer Constant for Timer0
-	UINT ui_AiTimer1;	//Timer constant for Timer1
-	UINT ui_AiFlags;
-	UINT ui_AiDataLength;
-	short *AiData;	// Pointer to sample data
-	UINT ui_AiNbrofScans;	// number of scans to do
-	USHORT us_UseDma;	// To use Dma or not
-	BYTE b_DmaDoubleBuffer;	// we can use double buffering
-	UINT ui_DmaActualBuffer;	// which buffer is used now
-	//*UPDATE-0.7.57->0.7.68
-	//ULONG               ul_DmaBufferVirtual[2];// pointers to begin of DMA buffer
-	short *ul_DmaBufferVirtual[2];	// pointers to begin of DMA buffer
-	ULONG ul_DmaBufferHw[2];	// hw address of DMA buff
-	UINT ui_DmaBufferSize[2];	// size of dma buffer in bytes
-	UINT ui_DmaBufferUsesize[2];	// which size we may now used for transfer
-	UINT ui_DmaBufferSamples[2];	// size in samples
-	UINT ui_DmaBufferPages[2];	// number of pages in buffer
-	BYTE b_DigitalOutputRegister;	// Digital Output Register
-	BYTE b_OutputMemoryStatus;
-	BYTE b_AnalogInputChannelNbr;	// Analog input channel Nbr
-	BYTE b_AnalogOutputChannelNbr;	// Analog input Output  Nbr
-	BYTE b_TimerSelectMode;	// Contain data written at iobase + 0C
-	BYTE b_ModeSelectRegister;	// Contain data written at iobase + 0E
-	USHORT us_OutputRegister;	// Contain data written at iobase + 0
-	BYTE b_InterruptState;
-	BYTE b_TimerInit;	// Specify if InitTimerWatchdog was load
-	BYTE b_TimerStarted;	// Specify if timer 2 is running or not
-	BYTE b_Timer2Mode;	// Specify the timer 2 mode
-	BYTE b_Timer2Interrupt;	//Timer2  interrupt enable or disable
-	BYTE b_AiCyclicAcquisition;	// indicate cyclic acquisition
-	BYTE b_InterruptMode;	// eoc eos or dma
-	BYTE b_EocEosInterrupt;	// Enable disable eoc eos interrupt
-	UINT ui_EocEosConversionTime;
-	BYTE b_EocEosConversionTimeBase;
-	BYTE b_SingelDiff;
-	BYTE b_ExttrigEnable;	/* To enable or disable external trigger */
+	int iobase;
+	int i_IobaseAmcc;	/*  base+size for AMCC chip */
+	int i_IobaseAddon;	/* addon base address */
+	int i_IobaseReserved;
+	unsigned long dw_AiBase;
+	struct pcilst_struct *amcc;	/*  ptr too AMCC data */
+	unsigned char allocated;		/*  we have blocked card */
+	unsigned char b_ValidDriver;	/*  driver is ok */
+	unsigned char b_AiContinuous;	/*  we do unlimited AI */
+	unsigned char b_AiInitialisation;
+	unsigned int ui_AiActualScan;	/* how many scans we finished */
+	unsigned int ui_AiBufferPtr;	/*  data buffer ptr in samples */
+	unsigned int ui_AiNbrofChannels;	/*  how many channels is measured */
+	unsigned int ui_AiScanLength;	/*  Length of actual scanlist */
+	unsigned int ui_AiActualScanPosition;	/*  position in actual scan */
+	unsigned int *pui_AiChannelList;	/*  actual chanlist */
+	unsigned int ui_AiChannelList[32];	/*  actual chanlist */
+	unsigned char b_AiChannelConfiguration[32];	/*  actual chanlist */
+	unsigned int ui_AiReadData[32];
+	unsigned int dw_AiInitialised;
+	unsigned int ui_AiTimer0;	/* Timer Constant for Timer0 */
+	unsigned int ui_AiTimer1;	/* Timer constant for Timer1 */
+	unsigned int ui_AiFlags;
+	unsigned int ui_AiDataLength;
+	short *AiData;	/*  Pointer to sample data */
+	unsigned int ui_AiNbrofScans;	/*  number of scans to do */
+	unsigned short us_UseDma;	/*  To use Dma or not */
+	unsigned char b_DmaDoubleBuffer;	/*  we can use double buffering */
+	unsigned int ui_DmaActualBuffer;	/*  which buffer is used now */
+	/* UPDATE-0.7.57->0.7.68 */
+	/* unsigned int               ul_DmaBufferVirtual[2]; pointers to begin of DMA buffer */
+	short *ul_DmaBufferVirtual[2];	/*  pointers to begin of DMA buffer */
+	unsigned int ul_DmaBufferHw[2];	/*  hw address of DMA buff */
+	unsigned int ui_DmaBufferSize[2];	/*  size of dma buffer in bytes */
+	unsigned int ui_DmaBufferUsesize[2];	/*  which size we may now used for transfer */
+	unsigned int ui_DmaBufferSamples[2];	/*  size in samples */
+	unsigned int ui_DmaBufferPages[2];	/*  number of pages in buffer */
+	unsigned char b_DigitalOutputRegister;	/*  Digital Output Register */
+	unsigned char b_OutputMemoryStatus;
+	unsigned char b_AnalogInputChannelNbr;	/*  Analog input channel Nbr */
+	unsigned char b_AnalogOutputChannelNbr;	/*  Analog input Output  Nbr */
+	unsigned char b_TimerSelectMode;	/*  Contain data written at iobase + 0C */
+	unsigned char b_ModeSelectRegister;	/*  Contain data written at iobase + 0E */
+	unsigned short us_OutputRegister;	/*  Contain data written at iobase + 0 */
+	unsigned char b_InterruptState;
+	unsigned char b_TimerInit;	/*  Specify if InitTimerWatchdog was load */
+	unsigned char b_TimerStarted;	/*  Specify if timer 2 is running or not */
+	unsigned char b_Timer2Mode;	/*  Specify the timer 2 mode */
+	unsigned char b_Timer2Interrupt;	/* Timer2  interrupt enable or disable */
+	unsigned char b_AiCyclicAcquisition;	/*  indicate cyclic acquisition */
+	unsigned char b_InterruptMode;	/*  eoc eos or dma */
+	unsigned char b_EocEosInterrupt;	/*  Enable disable eoc eos interrupt */
+	unsigned int ui_EocEosConversionTime;
+	unsigned char b_EocEosConversionTimeBase;
+	unsigned char b_SingelDiff;
+	unsigned char b_ExttrigEnable;	/* To enable or disable external trigger */
 
 	/* Pointer to the current process */
 	struct task_struct *tsk_Current;
-	boardtype *ps_BoardInfo;
+	struct addi_board *ps_BoardInfo;
 
 	/* Hardware board infos for 1710 */
 	struct {
-		UINT ui_Address;	/* Board address */
-		UINT ui_FlashAddress;
-		BYTE b_InterruptNbr;	/* Board interrupt number */
-		BYTE b_SlotNumber;	/* PCI slot number */
-		BYTE b_BoardVersion;
-		DWORD dw_MolduleConfiguration[4];	/* Module config */
+		unsigned int ui_Address;	/* Board address */
+		unsigned int ui_FlashAddress;
+		unsigned char b_InterruptNbr;	/* Board interrupt number */
+		unsigned char b_SlotNumber;	/* PCI slot number */
+		unsigned char b_BoardVersion;
+		unsigned int dw_MolduleConfiguration[4];	/* Module config */
 	} s_BoardInfos;
 
 	/* Interrupt infos */
 	struct {
-		ULONG ul_InterruptOccur;	/* 0   : No interrupt occur */
+		unsigned int ul_InterruptOccur;	/* 0   : No interrupt occur */
 						/* > 0 : Interrupt occur */
-		UINT ui_Read;	/* Read FIFO */
-		UINT ui_Write;	/* Write FIFO */
+		unsigned int ui_Read;	/* Read FIFO */
+		unsigned int ui_Write;	/* Write FIFO */
 		struct {
-			BYTE b_OldModuleMask;
-			ULONG ul_OldInterruptMask;	/* Interrupt mask */
-			ULONG ul_OldCounterLatchValue;	/* Interrupt counter value */
+			unsigned char b_OldModuleMask;
+			unsigned int ul_OldInterruptMask;	/* Interrupt mask */
+			unsigned int ul_OldCounterLatchValue;	/* Interrupt counter value */
 		} s_FIFOInterruptParameters[APCI1710_SAVE_INTERRUPT];
 	} s_InterruptParameters;
 
-	str_ModuleInfo s_ModuleInfo[4];
-	ULONG ul_TTLPortConfiguration[10];
+	union str_ModuleInfo s_ModuleInfo[4];
+	unsigned int ul_TTLPortConfiguration[10];
 
-} addi_private;
+};
 
 static unsigned short pci_list_builded;	/* set to 1 when list of card is known */
 
@@ -457,6 +443,6 @@
 static int i_ADDI_Detach(struct comedi_device *dev);
 static int i_ADDI_Reset(struct comedi_device *dev);
 
-static irqreturn_t v_ADDI_Interrupt(int irq, void *d PT_REGS_ARG);
+static irqreturn_t v_ADDI_Interrupt(int irq, void *d);
 static int i_ADDIDATA_InsnReadEeprom(struct comedi_device *dev, struct comedi_subdevice *s,
 				     struct comedi_insn *insn, unsigned int *data);
diff --git a/drivers/staging/comedi/drivers/addi-data/addi_eeprom.c b/drivers/staging/comedi/drivers/addi-data/addi_eeprom.c
index a8a1bb2..69b4273 100644
--- a/drivers/staging/comedi/drivers/addi-data/addi_eeprom.c
+++ b/drivers/staging/comedi/drivers/addi-data/addi_eeprom.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -45,19 +45,11 @@
   +----------+-----------+------------------------------------------------+
 */
 
-#define NVCMD_BEGIN_READ 	(0x7 << 5 )	// nvRam begin read command
-#define NVCMD_LOAD_LOW   	(0x4 << 5 )	// nvRam load low command
-#define NVCMD_LOAD_HIGH  	(0x5 << 5 )	// nvRam load high command
-#define EE76_CMD_LEN    	13	// bits in instructions
-#define EE_READ         	0x0180	// 01 1000 0000 read instruction
-
-#define	WORD				unsigned short
-#define PWORD				unsigned short *
-#define PDWORD				unsigned int  *
-
-#ifndef DWORD
-#define	DWORD				unsigned int
-#endif
+#define NVCMD_BEGIN_READ 	(0x7 << 5)	/*  nvRam begin read command */
+#define NVCMD_LOAD_LOW   	(0x4 << 5)	/*  nvRam load low command */
+#define NVCMD_LOAD_HIGH  	(0x5 << 5)	/*  nvRam load high command */
+#define EE76_CMD_LEN    	13	/*  bits in instructions */
+#define EE_READ         	0x0180	/*  01 1000 0000 read instruction */
 
 #define EEPROM_DIGITALINPUT 			0
 #define EEPROM_DIGITALOUTPUT			1
@@ -68,107 +60,114 @@
 #define EEPROM_TIMER_WATCHDOG_COUNTER	10
 
 struct str_Functionality {
-	BYTE b_Type;
-	WORD w_Address;
+	unsigned char b_Type;
+	unsigned short w_Address;
 };
 
-typedef struct {
-	WORD w_HeaderSize;
-	BYTE b_Nfunctions;
+struct str_MainHeader {
+	unsigned short w_HeaderSize;
+	unsigned char b_Nfunctions;
 	struct str_Functionality s_Functions[7];
-} str_MainHeader;
+};
+
+struct str_DigitalInputHeader {
+	unsigned short w_Nchannel;
+	unsigned char b_Interruptible;
+	unsigned short w_NinterruptLogic;
+};
+
+struct str_DigitalOutputHeader {
+
+	unsigned short w_Nchannel;
+};
+
+
+/* used for timer as well as watchdog */
+
+struct str_TimerDetails {
+
+	unsigned short w_HeaderSize;
+	unsigned char b_Resolution;
+	unsigned char b_Mode;		/*  in case of Watchdog it is functionality */
+	unsigned short w_MinTiming;
+	unsigned char b_TimeBase;
+};
+
+struct str_TimerMainHeader {
+
+
+	unsigned short w_Ntimer;
+	struct str_TimerDetails s_TimerDetails[4];	/*   supports 4 timers */
+};
+
 
 typedef struct {
-	WORD w_Nchannel;
-	BYTE b_Interruptible;
-	WORD w_NinterruptLogic;
-} str_DigitalInputHeader;
-
-typedef struct {
-	WORD w_Nchannel;
-} str_DigitalOutputHeader;
-
-// used for timer as well as watchdog
-
-typedef struct {
-	WORD w_HeaderSize;
-	BYTE b_Resolution;
-	BYTE b_Mode;		// in case of Watchdog it is functionality
-	WORD w_MinTiming;
-	BYTE b_TimeBase;
-} str_TimerDetails;
-typedef struct {
-
-	WORD w_Ntimer;
-	str_TimerDetails s_TimerDetails[4];	//  supports 4 timers
-} str_TimerMainHeader;
-
-typedef struct {
-	WORD w_Nchannel;
-	BYTE b_Resolution;
+	unsigned short w_Nchannel;
+	unsigned char b_Resolution;
 } str_AnalogOutputHeader;
 
-typedef struct {
-	WORD w_Nchannel;
-	WORD w_MinConvertTiming;
-	WORD w_MinDelayTiming;
-	BYTE b_HasDma;
-	BYTE b_Resolution;
-} str_AnalogInputHeader;
+struct str_AnalogInputHeader {
+	unsigned short w_Nchannel;
+	unsigned short w_MinConvertTiming;
+	unsigned short w_MinDelayTiming;
+	unsigned char b_HasDma;
+	unsigned char b_Resolution;
+};
+
 
 		/*****************************************/
 		/*            Read Header Functions              */
 		/*****************************************/
 
-INT i_EepromReadMainHeader(WORD w_PCIBoardEepromAddress,
+int i_EepromReadMainHeader(unsigned short w_PCIBoardEepromAddress,
 	char *pc_PCIChipInformation, struct comedi_device *dev);
 
-INT i_EepromReadDigitalInputHeader(WORD w_PCIBoardEepromAddress,
-	char *pc_PCIChipInformation, WORD w_Address,
-	str_DigitalInputHeader * s_Header);
+int i_EepromReadDigitalInputHeader(unsigned short w_PCIBoardEepromAddress,
+	char *pc_PCIChipInformation, unsigned short w_Address,
+	struct str_DigitalInputHeader *s_Header);
 
-INT i_EepromReadDigitalOutputHeader(WORD w_PCIBoardEepromAddress,
-	char *pc_PCIChipInformation, WORD w_Address,
-	str_DigitalOutputHeader * s_Header);
+int i_EepromReadDigitalOutputHeader(unsigned short w_PCIBoardEepromAddress,
+	char *pc_PCIChipInformation, unsigned short w_Address,
+	struct str_DigitalOutputHeader *s_Header);
 
-INT i_EepromReadTimerHeader(WORD w_PCIBoardEepromAddress,
-	char *pc_PCIChipInformation, WORD w_Address,
-	str_TimerMainHeader * s_Header);
+int i_EepromReadTimerHeader(unsigned short w_PCIBoardEepromAddress,
+	char *pc_PCIChipInformation, unsigned short w_Address,
+	struct str_TimerMainHeader *s_Header);
 
-INT i_EepromReadAnlogOutputHeader(WORD w_PCIBoardEepromAddress,
-	char *pc_PCIChipInformation, WORD w_Address,
-	str_AnalogOutputHeader * s_Header);
+int i_EepromReadAnlogOutputHeader(unsigned short w_PCIBoardEepromAddress,
+	char *pc_PCIChipInformation, unsigned short w_Address,
+	str_AnalogOutputHeader *s_Header);
 
-INT i_EepromReadAnlogInputHeader(WORD w_PCIBoardEepromAddress,
-	char *pc_PCIChipInformation, WORD w_Address,
-	str_AnalogInputHeader * s_Header);
+int i_EepromReadAnlogInputHeader(unsigned short w_PCIBoardEepromAddress,
+	char *pc_PCIChipInformation, unsigned short w_Address,
+	struct str_AnalogInputHeader *s_Header);
 
 		/******************************************/
 		/*      Eeprom Specific Functions                         */
 		/******************************************/
-WORD w_EepromReadWord(WORD w_PCIBoardEepromAddress, char *pc_PCIChipInformation,
-	WORD w_EepromStartAddress);
-void v_EepromWaitBusy(WORD w_PCIBoardEepromAddress);
-void v_EepromClock76(DWORD dw_Address, DWORD dw_RegisterValue);
-void v_EepromWaitBusy(WORD w_PCIBoardEepromAddress);
-void v_EepromSendCommand76(DWORD dw_Address, DWORD dw_EepromCommand,
-	BYTE b_DataLengthInBits);
-void v_EepromCs76Read(DWORD dw_Address, WORD w_offset, PWORD pw_Value);
+unsigned short w_EepromReadWord(unsigned short w_PCIBoardEepromAddress, char *pc_PCIChipInformation,
+	unsigned short w_EepromStartAddress);
+void v_EepromWaitBusy(unsigned short w_PCIBoardEepromAddress);
+void v_EepromClock76(unsigned int dw_Address, unsigned int dw_RegisterValue);
+void v_EepromWaitBusy(unsigned short w_PCIBoardEepromAddress);
+void v_EepromSendCommand76(unsigned int dw_Address, unsigned int dw_EepromCommand,
+	unsigned char b_DataLengthInBits);
+void v_EepromCs76Read(unsigned int dw_Address, unsigned short w_offset, unsigned short *pw_Value);
 
 /*
 +----------------------------------------------------------------------------+
-| Function   Name   : WORD w_EepromReadWord                                  |
-|				(WORD	w_PCIBoardEepromAddress,             		 |
+| Function   Name   : unsigned short w_EepromReadWord                                  |
+|				(unsigned short	w_PCIBoardEepromAddress,             		 |
 |				 char *	pc_PCIChipInformation,               		 |
-|				 WORD   w_EepromStartAddress)                		 |
+|				 unsigned short   w_EepromStartAddress)                		 |
 +----------------------------------------------------------------------------+
 | Task              : Read from eepromn a word                               |
 +----------------------------------------------------------------------------+
-| Input Parameters  : WORD w_PCIBoardEepromAddress : PCI eeprom address      |
+| Input Parameters  : unsigned short w_PCIBoardEepromAddress : PCI eeprom address      |
 |																	 |
 |		      char *pc_PCIChipInformation  : PCI Chip Type.          |
 |																	 |
-|		      WORD w_EepromStartAddress    : Selected eeprom address |
+|		      unsigned short w_EepromStartAddress    : Selected eeprom address |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -176,23 +175,23 @@
 +----------------------------------------------------------------------------+
 */
 
-WORD w_EepromReadWord(WORD w_PCIBoardEepromAddress, char *pc_PCIChipInformation,
-	WORD w_EepromStartAddress)
+unsigned short w_EepromReadWord(unsigned short w_PCIBoardEepromAddress, char *pc_PCIChipInformation,
+	unsigned short w_EepromStartAddress)
 {
 
-	BYTE b_Counter = 0;
+	unsigned char b_Counter = 0;
 
-	BYTE b_ReadByte = 0;
+	unsigned char b_ReadByte = 0;
 
-	BYTE b_ReadLowByte = 0;
+	unsigned char b_ReadLowByte = 0;
 
-	BYTE b_ReadHighByte = 0;
+	unsigned char b_ReadHighByte = 0;
 
-	BYTE b_SelectedAddressLow = 0;
+	unsigned char b_SelectedAddressLow = 0;
 
-	BYTE b_SelectedAddressHigh = 0;
+	unsigned char b_SelectedAddressHigh = 0;
 
-	WORD w_ReadWord = 0;
+	unsigned short w_ReadWord = 0;
 
 	/**************************/
 
@@ -207,9 +206,9 @@
 		for (b_Counter = 0; b_Counter < 2; b_Counter++)
 		{
 
-			b_SelectedAddressLow = (w_EepromStartAddress + b_Counter) % 256;	//Read the low 8 bit part
+			b_SelectedAddressLow = (w_EepromStartAddress + b_Counter) % 256;	/* Read the low 8 bit part */
 
-			b_SelectedAddressHigh = (w_EepromStartAddress + b_Counter) / 256;	//Read the high 8 bit part
+			b_SelectedAddressHigh = (w_EepromStartAddress + b_Counter) / 256;	/* Read the high 8 bit part */
 
 	      /************************************/
 
@@ -320,20 +319,20 @@
 
 				b_ReadLowByte = b_ReadByte;
 
-			}	// if(b_Counter==0)
+			}	/*  if(b_Counter==0) */
 
 			else
 			{
 
 				b_ReadHighByte = b_ReadByte;
 
-			}	// if(b_Counter==0)
+			}	/*  if(b_Counter==0) */
 
-		}		// for (b_Counter=0; b_Counter<2; b_Counter++)
+		}		/*  for (b_Counter=0; b_Counter<2; b_Counter++) */
 
-		w_ReadWord = (b_ReadLowByte | (((WORD) b_ReadHighByte) * 256));
+		w_ReadWord = (b_ReadLowByte | (((unsigned short) b_ReadHighByte) * 256));
 
-	}			// end of if ((!strcmp(pc_PCIChipInformation, "S5920")) || (!strcmp(pc_PCIChipInformation, "S5933")))
+	}			/*  end of if ((!strcmp(pc_PCIChipInformation, "S5920")) || (!strcmp(pc_PCIChipInformation, "S5933"))) */
 
 	if (!strcmp(pc_PCIChipInformation, "93C76"))
 	{
@@ -349,7 +348,7 @@
 
 	}
 
-	return (w_ReadWord);
+	return w_ReadWord;
 
 }
 
@@ -359,7 +358,7 @@
 
 | Function   Name   : void v_EepromWaitBusy                                  |
 
-|			(WORD	w_PCIBoardEepromAddress)                    	 |
+|			(unsigned short	w_PCIBoardEepromAddress)                    	 |
 
 +----------------------------------------------------------------------------+
 
@@ -367,7 +366,7 @@
 
 +----------------------------------------------------------------------------+
 
-| Input Parameters  : WORD w_PCIBoardEepromAddress : PCI eeprom base address |
+| Input Parameters  : unsigned short w_PCIBoardEepromAddress : PCI eeprom base address |
 
 +----------------------------------------------------------------------------+
 
@@ -381,10 +380,10 @@
 
 */
 
-void v_EepromWaitBusy(WORD w_PCIBoardEepromAddress)
+void v_EepromWaitBusy(unsigned short w_PCIBoardEepromAddress)
 {
 
-	BYTE b_EepromBusy = 0;
+	unsigned char b_EepromBusy = 0;
 
 	do
 	{
@@ -403,17 +402,16 @@
 
 		/*      the operator register is AMCC_OP_REG_MCSR+3 */
 
-		/*      WORD read  EEPROM=0x8000 andAMCC_OP_REG_MCSR+2                  */
+		/*      unsigned short read  EEPROM=0x8000 andAMCC_OP_REG_MCSR+2                  */
 
-		/*      DWORD read  EEPROM=0x80000000 and AMCC_OP_REG_MCSR */
+		/*      unsigned int read  EEPROM=0x80000000 and AMCC_OP_REG_MCSR */
 
 	   /************************************************************************/
 
 		b_EepromBusy = inb(w_PCIBoardEepromAddress + 0x3F);
 		b_EepromBusy = b_EepromBusy & 0x80;
 
-	}
-	while (b_EepromBusy == 0x80);
+	} while (b_EepromBusy == 0x80);
 
 }
 
@@ -421,9 +419,9 @@
 
 +---------------------------------------------------------------------------------+
 
-| Function   Name   : void v_EepromClock76(DWORD dw_Address,                      |
+| Function   Name   : void v_EepromClock76(unsigned int dw_Address,                      |
 
-|					   DWORD dw_RegisterValue)                 			  |
+|					   unsigned int dw_RegisterValue)                 			  |
 
 +---------------------------------------------------------------------------------+
 
@@ -431,9 +429,9 @@
 
 +---------------------------------------------------------------------------------+
 
-| Input Parameters  : DWORD dw_Address : PCI eeprom base address                  |
+| Input Parameters  : unsigned int dw_Address : PCI eeprom base address                  |
 
-|		      DWORD dw_RegisterValue : PCI eeprom register value to write.|
+|		      unsigned int dw_RegisterValue : PCI eeprom register value to write.|
 
 +---------------------------------------------------------------------------------+
 
@@ -447,7 +445,7 @@
 
 */
 
-void v_EepromClock76(DWORD dw_Address, DWORD dw_RegisterValue)
+void v_EepromClock76(unsigned int dw_Address, unsigned int dw_RegisterValue)
 {
 
    /************************/
@@ -488,11 +486,11 @@
 
 +---------------------------------------------------------------------------------+
 
-| Function   Name   : void v_EepromSendCommand76(DWORD dw_Address,                |
+| Function   Name   : void v_EepromSendCommand76(unsigned int dw_Address,                |
 
-|					   DWORD   dw_EepromCommand,                		  |
+|					   unsigned int   dw_EepromCommand,                		  |
 
-|					   BYTE    b_DataLengthInBits)                        |
+|					   unsigned char    b_DataLengthInBits)                        |
 
 +---------------------------------------------------------------------------------+
 
@@ -500,11 +498,11 @@
 
 +---------------------------------------------------------------------------------+
 
-| Input Parameters  : DWORD dw_Address : PCI eeprom base address                  |
+| Input Parameters  : unsigned int dw_Address : PCI eeprom base address                  |
 
-|		      DWORD dw_EepromCommand : PCI eeprom command to write.       |
+|		      unsigned int dw_EepromCommand : PCI eeprom command to write.       |
 
-|		      BYTE  b_DataLengthInBits : PCI eeprom command data length.  |
+|		      unsigned char  b_DataLengthInBits : PCI eeprom command data length.  |
 
 +---------------------------------------------------------------------------------+
 
@@ -518,13 +516,13 @@
 
 */
 
-void v_EepromSendCommand76(DWORD dw_Address, DWORD dw_EepromCommand,
-	BYTE b_DataLengthInBits)
+void v_EepromSendCommand76(unsigned int dw_Address, unsigned int dw_EepromCommand,
+	unsigned char b_DataLengthInBits)
 {
 
 	char c_BitPos = 0;
 
-	DWORD dw_RegisterValue = 0;
+	unsigned int dw_RegisterValue = 0;
 
    /*****************************/
 
@@ -623,11 +621,11 @@
 
 +---------------------------------------------------------------------------------+
 
-| Function   Name   : void v_EepromCs76Read(DWORD dw_Address,                     |
+| Function   Name   : void v_EepromCs76Read(unsigned int dw_Address,                     |
 
-|					   WORD    w_offset,                      			  |
+|					   unsigned short    w_offset,                      			  |
 
-|					   PWORD   pw_Value)                      			  |
+|					   unsigned short *   pw_Value)                      			  |
 
 +---------------------------------------------------------------------------------+
 
@@ -635,11 +633,11 @@
 
 +---------------------------------------------------------------------------------+
 
-| Input Parameters  : DWORD dw_Address : PCI eeprom base address                  |
+| Input Parameters  : unsigned int dw_Address : PCI eeprom base address                  |
 
-|		      WORD    w_offset : Offset of the adress to read             |
+|		      unsigned short    w_offset : Offset of the adress to read             |
 
-|		      PWORD   pw_Value : PCI eeprom 16 bit read value.            |
+|		      unsigned short *   pw_Value : PCI eeprom 16 bit read value.            |
 
 +---------------------------------------------------------------------------------+
 
@@ -653,14 +651,14 @@
 
 */
 
-void v_EepromCs76Read(DWORD dw_Address, WORD w_offset, PWORD pw_Value)
+void v_EepromCs76Read(unsigned int dw_Address, unsigned short w_offset, unsigned short *pw_Value)
 {
 
         char c_BitPos = 0;
 
-	DWORD dw_RegisterValue = 0;
+	unsigned int dw_RegisterValue = 0;
 
-	DWORD dw_RegisterValueRead = 0;
+	unsigned int dw_RegisterValueRead = 0;
 
    /*************************************************/
 
@@ -786,12 +784,12 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name  : INT i_EepromReadMainHeader(WORD w_PCIBoardEepromAddress,  |
+| Function Name  : int i_EepromReadMainHeader(unsigned short w_PCIBoardEepromAddress,  |
 |				char *	pc_PCIChipInformation,struct comedi_device *dev)    |
 +----------------------------------------------------------------------------+
 | Task              : Read from eeprom Main Header                           |
 +----------------------------------------------------------------------------+
-| Input Parameters  : WORD w_PCIBoardEepromAddress : PCI eeprom address      |
+| Input Parameters  : unsigned short w_PCIBoardEepromAddress : PCI eeprom address      |
 |																	 |
 |		      char *pc_PCIChipInformation  : PCI Chip Type.          |
 |																	 |
@@ -804,43 +802,43 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_EepromReadMainHeader(WORD w_PCIBoardEepromAddress,
+int i_EepromReadMainHeader(unsigned short w_PCIBoardEepromAddress,
 	char *pc_PCIChipInformation, struct comedi_device *dev)
 {
-	WORD w_Temp, i, w_Count = 0;
-	UINT ui_Temp;
-	str_MainHeader s_MainHeader;
-	str_DigitalInputHeader s_DigitalInputHeader;
-	str_DigitalOutputHeader s_DigitalOutputHeader;
-	//str_TimerMainHeader     s_TimerMainHeader,s_WatchdogMainHeader;
+	unsigned short w_Temp, i, w_Count = 0;
+	unsigned int ui_Temp;
+	struct str_MainHeader s_MainHeader;
+	struct str_DigitalInputHeader s_DigitalInputHeader;
+	struct str_DigitalOutputHeader s_DigitalOutputHeader;
+	/* struct str_TimerMainHeader     s_TimerMainHeader,s_WatchdogMainHeader; */
 	str_AnalogOutputHeader s_AnalogOutputHeader;
-	str_AnalogInputHeader s_AnalogInputHeader;
+	struct str_AnalogInputHeader s_AnalogInputHeader;
 
-	// Read size
+	/* Read size */
 	s_MainHeader.w_HeaderSize =
 		w_EepromReadWord(w_PCIBoardEepromAddress, pc_PCIChipInformation,
 		0x100 + 8);
 
-	// Read nbr of functionality
+	/* Read nbr of functionality */
 	w_Temp = w_EepromReadWord(w_PCIBoardEepromAddress,
 		pc_PCIChipInformation, 0x100 + 10);
-	s_MainHeader.b_Nfunctions = (BYTE) w_Temp & 0x00FF;
+	s_MainHeader.b_Nfunctions = (unsigned char) w_Temp & 0x00FF;
 
-	// Read functionality details
+	/* Read functionality details */
 	for (i = 0; i < s_MainHeader.b_Nfunctions; i++) {
-		// Read Type
+		/* Read Type */
 		w_Temp = w_EepromReadWord(w_PCIBoardEepromAddress,
 			pc_PCIChipInformation, 0x100 + 12 + w_Count);
-		s_MainHeader.s_Functions[i].b_Type = (BYTE) w_Temp & 0x3F;
+		s_MainHeader.s_Functions[i].b_Type = (unsigned char) w_Temp & 0x3F;
 		w_Count = w_Count + 2;
-		//Read Address
+		/* Read Address */
 		s_MainHeader.s_Functions[i].w_Address =
 			w_EepromReadWord(w_PCIBoardEepromAddress,
 			pc_PCIChipInformation, 0x100 + 12 + w_Count);
 		w_Count = w_Count + 2;
 	}
 
-	// Display main header info
+	/* Display main header info */
 	for (i = 0; i < s_MainHeader.b_Nfunctions; i++) {
 
 		switch (s_MainHeader.s_Functions[i].b_Type) {
@@ -878,10 +876,10 @@
 					s_AnalogInputHeader.w_Nchannel;
 			this_board->i_Dma = s_AnalogInputHeader.b_HasDma;
 			this_board->ui_MinAcquisitiontimeNs =
-				(UINT) s_AnalogInputHeader.w_MinConvertTiming *
+				(unsigned int) s_AnalogInputHeader.w_MinConvertTiming *
 				1000;
 			this_board->ui_MinDelaytimeNs =
-				(UINT) s_AnalogInputHeader.w_MinDelayTiming *
+				(unsigned int) s_AnalogInputHeader.w_MinDelayTiming *
 				1000;
 			ui_Temp = 0xffff;
 			this_board->i_AiMaxdata =
@@ -903,15 +901,15 @@
 			break;
 
 		case EEPROM_TIMER:
-			this_board->i_Timer = 1;	//Timer subdevice present
+			this_board->i_Timer = 1;	/* Timer subdevice present */
 			break;
 
 		case EEPROM_WATCHDOG:
-			this_board->i_Timer = 1;	//Timer subdevice present
+			this_board->i_Timer = 1;	/* Timer subdevice present */
 			break;
 
 		case EEPROM_TIMER_WATCHDOG_COUNTER:
-			this_board->i_Timer = 1;	//Timer subdevice present
+			this_board->i_Timer = 1;	/* Timer subdevice present */
 		}
 	}
 
@@ -920,18 +918,18 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name  : INT i_EepromReadDigitalInputHeader(WORD 					 |
+| Function Name  : int i_EepromReadDigitalInputHeader(unsigned short 					 |
 |			w_PCIBoardEepromAddress,char *pc_PCIChipInformation,	 |
-|			WORD w_Address,str_DigitalInputHeader *s_Header)		 |
+|			unsigned short w_Address,struct str_DigitalInputHeader *s_Header)		 |
 |																	 |
 +----------------------------------------------------------------------------+
 | Task              : Read Digital Input Header                              |
 +----------------------------------------------------------------------------+
-| Input Parameters  : WORD w_PCIBoardEepromAddress : PCI eeprom address      |
+| Input Parameters  : unsigned short w_PCIBoardEepromAddress : PCI eeprom address      |
 |																	 |
 |		      char *pc_PCIChipInformation  : PCI Chip Type.          |
 |																	 |
-|			 str_DigitalInputHeader *s_Header: Digita Input Header   |
+|			 struct str_DigitalInputHeader *s_Header: Digita Input Header   |
 |												   Pointer			 |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -939,23 +937,23 @@
 | Return Value      : 0							                             |
 +----------------------------------------------------------------------------+
 */
-INT i_EepromReadDigitalInputHeader(WORD w_PCIBoardEepromAddress,
-	char *pc_PCIChipInformation, WORD w_Address,
-	str_DigitalInputHeader * s_Header)
+int i_EepromReadDigitalInputHeader(unsigned short w_PCIBoardEepromAddress,
+	char *pc_PCIChipInformation, unsigned short w_Address,
+	struct str_DigitalInputHeader *s_Header)
 {
-	WORD w_Temp;
+	unsigned short w_Temp;
 
-	// read nbr of channels
+	/*  read nbr of channels */
 	s_Header->w_Nchannel =
 		w_EepromReadWord(w_PCIBoardEepromAddress, pc_PCIChipInformation,
 		0x100 + w_Address + 6);
 
-	// interruptible or not
+	/*  interruptible or not */
 	w_Temp = w_EepromReadWord(w_PCIBoardEepromAddress,
 		pc_PCIChipInformation, 0x100 + w_Address + 8);
-	s_Header->b_Interruptible = (BYTE) (w_Temp >> 7) & 0x01;
+	s_Header->b_Interruptible = (unsigned char) (w_Temp >> 7) & 0x01;
 
-// How many interruptible logic
+/* How many interruptible logic */
 	s_Header->w_NinterruptLogic =
 		w_EepromReadWord(w_PCIBoardEepromAddress, pc_PCIChipInformation,
 		0x100 + w_Address + 10);
@@ -965,18 +963,18 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name  : INT i_EepromReadDigitalOutputHeader(WORD 				 |
+| Function Name  : int i_EepromReadDigitalOutputHeader(unsigned short 				 |
 |			w_PCIBoardEepromAddress,char *pc_PCIChipInformation,	 |
-|			WORD w_Address,str_DigitalOutputHeader *s_Header)	     |
+|			unsigned short w_Address,struct str_DigitalOutputHeader *s_Header)	     |
 |																	 |
 +----------------------------------------------------------------------------+
 | Task              : Read Digital Output Header                             |
 +----------------------------------------------------------------------------+
-| Input Parameters  : WORD w_PCIBoardEepromAddress : PCI eeprom address      |
+| Input Parameters  : unsigned short w_PCIBoardEepromAddress : PCI eeprom address      |
 |																	 |
 |		      char *pc_PCIChipInformation  : PCI Chip Type.          |
 |																	 |
-|			 str_DigitalOutputHeader *s_Header: Digital Output Header|
+|			 struct str_DigitalOutputHeader *s_Header: Digital Output Header|
 |											   Pointer				 |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -984,11 +982,11 @@
 | Return Value      : 0							                             |
 +----------------------------------------------------------------------------+
 */
-INT i_EepromReadDigitalOutputHeader(WORD w_PCIBoardEepromAddress,
-	char *pc_PCIChipInformation, WORD w_Address,
-	str_DigitalOutputHeader * s_Header)
+int i_EepromReadDigitalOutputHeader(unsigned short w_PCIBoardEepromAddress,
+	char *pc_PCIChipInformation, unsigned short w_Address,
+	struct str_DigitalOutputHeader *s_Header)
 {
-// Read Nbr channels
+/* Read Nbr channels */
 	s_Header->w_Nchannel =
 		w_EepromReadWord(w_PCIBoardEepromAddress, pc_PCIChipInformation,
 		0x100 + w_Address + 6);
@@ -997,17 +995,17 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name  : INT i_EepromReadTimerHeader(WORD w_PCIBoardEepromAddress, |
+| Function Name  : int i_EepromReadTimerHeader(unsigned short w_PCIBoardEepromAddress, |
 |			char *pc_PCIChipInformation,WORD w_Address,				 |
-|			str_TimerMainHeader *s_Header)							 |
+|			struct str_TimerMainHeader *s_Header)							 |
 +----------------------------------------------------------------------------+
 | Task              : Read Timer or Watchdog Header                          |
 +----------------------------------------------------------------------------+
-| Input Parameters  : WORD w_PCIBoardEepromAddress : PCI eeprom address      |
+| Input Parameters  : unsigned short w_PCIBoardEepromAddress : PCI eeprom address      |
 |																	 |
 |		      char *pc_PCIChipInformation  : PCI Chip Type.          |
 |																	 |
-|			 str_TimerMainHeader *s_Header: Timer Header			 |
+|			 struct str_TimerMainHeader *s_Header: Timer Header			 |
 |											   Pointer				 |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -1015,18 +1013,18 @@
 | Return Value      : 0							                             |
 +----------------------------------------------------------------------------+
 */
-INT i_EepromReadTimerHeader(WORD w_PCIBoardEepromAddress,
-	char *pc_PCIChipInformation, WORD w_Address,
-	str_TimerMainHeader * s_Header)
+int i_EepromReadTimerHeader(unsigned short w_PCIBoardEepromAddress,
+	char *pc_PCIChipInformation, unsigned short w_Address,
+	struct str_TimerMainHeader *s_Header)
 {
 
-	WORD i, w_Size = 0, w_Temp;
+	unsigned short i, w_Size = 0, w_Temp;
 
-//Read No of Timer
+/* Read No of Timer */
 	s_Header->w_Ntimer =
 		w_EepromReadWord(w_PCIBoardEepromAddress, pc_PCIChipInformation,
 		0x100 + w_Address + 6);
-//Read header size
+/* Read header size */
 
 	for (i = 0; i < s_Header->w_Ntimer; i++) {
 		s_Header->s_TimerDetails[i].w_HeaderSize =
@@ -1037,23 +1035,23 @@
 			pc_PCIChipInformation,
 			0x100 + w_Address + 8 + w_Size + 2);
 
-		//Read Resolution
+		/* Read Resolution */
 		s_Header->s_TimerDetails[i].b_Resolution =
-			(BYTE) (w_Temp >> 10) & 0x3F;
+			(unsigned char) (w_Temp >> 10) & 0x3F;
 
-		//Read Mode
+		/* Read Mode */
 		s_Header->s_TimerDetails[i].b_Mode =
-			(BYTE) (w_Temp >> 4) & 0x3F;
+			(unsigned char) (w_Temp >> 4) & 0x3F;
 
 		w_Temp = w_EepromReadWord(w_PCIBoardEepromAddress,
 			pc_PCIChipInformation,
 			0x100 + w_Address + 8 + w_Size + 4);
 
-		//Read MinTiming
+		/* Read MinTiming */
 		s_Header->s_TimerDetails[i].w_MinTiming = (w_Temp >> 6) & 0x3FF;
 
-		//Read Timebase
-		s_Header->s_TimerDetails[i].b_TimeBase = (BYTE) (w_Temp) & 0x3F;
+		/* Read Timebase */
+		s_Header->s_TimerDetails[i].b_TimeBase = (unsigned char) (w_Temp) & 0x3F;
 		w_Size += s_Header->s_TimerDetails[i].w_HeaderSize;
 	}
 
@@ -1062,13 +1060,13 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name  : INT i_EepromReadAnlogOutputHeader(WORD 					 |
+| Function Name  : int i_EepromReadAnlogOutputHeader(unsigned short 					 |
 |			w_PCIBoardEepromAddress,char *pc_PCIChipInformation,	 |
-|			WORD w_Address,str_AnalogOutputHeader *s_Header)         |
+|			unsigned short w_Address,str_AnalogOutputHeader *s_Header)         |
 +----------------------------------------------------------------------------+
 | Task              : Read Nalog Output  Header                              |
 +----------------------------------------------------------------------------+
-| Input Parameters  : WORD w_PCIBoardEepromAddress : PCI eeprom address      |
+| Input Parameters  : unsigned short w_PCIBoardEepromAddress : PCI eeprom address      |
 |																	 |
 |		      char *pc_PCIChipInformation  : PCI Chip Type.          |
 |																	 |
@@ -1081,35 +1079,35 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_EepromReadAnlogOutputHeader(WORD w_PCIBoardEepromAddress,
-	char *pc_PCIChipInformation, WORD w_Address,
-	str_AnalogOutputHeader * s_Header)
+int i_EepromReadAnlogOutputHeader(unsigned short w_PCIBoardEepromAddress,
+	char *pc_PCIChipInformation, unsigned short w_Address,
+	str_AnalogOutputHeader *s_Header)
 {
-	WORD w_Temp;
-	// No of channels for 1st hard component
+	unsigned short w_Temp;
+	/*  No of channels for 1st hard component */
 	w_Temp = w_EepromReadWord(w_PCIBoardEepromAddress,
 		pc_PCIChipInformation, 0x100 + w_Address + 10);
 	s_Header->w_Nchannel = (w_Temp >> 4) & 0x03FF;
-	// Resolution for 1st hard component
+	/*  Resolution for 1st hard component */
 	w_Temp = w_EepromReadWord(w_PCIBoardEepromAddress,
 		pc_PCIChipInformation, 0x100 + w_Address + 16);
-	s_Header->b_Resolution = (BYTE) (w_Temp >> 8) & 0xFF;
+	s_Header->b_Resolution = (unsigned char) (w_Temp >> 8) & 0xFF;
 	return 0;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name  : INT i_EepromReadAnlogInputHeader(WORD 					 |
+| Function Name  : int i_EepromReadAnlogInputHeader(unsigned short 					 |
 |			w_PCIBoardEepromAddress,char *pc_PCIChipInformation,     |
-|			WORD w_Address,str_AnalogInputHeader *s_Header)          |
+|			unsigned short w_Address,struct str_AnalogInputHeader *s_Header)          |
 +----------------------------------------------------------------------------+
 | Task              : Read Nalog Output  Header                              |
 +----------------------------------------------------------------------------+
-| Input Parameters  : WORD w_PCIBoardEepromAddress : PCI eeprom address      |
+| Input Parameters  : unsigned short w_PCIBoardEepromAddress : PCI eeprom address      |
 |																	 |
 |		      char *pc_PCIChipInformation  : PCI Chip Type.          |
 |																	 |
-|			 str_AnalogInputHeader *s_Header:Anlog Input Header      |
+|			 struct str_AnalogInputHeader *s_Header:Anlog Input Header      |
 |											   Pointer				 |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -1118,12 +1116,12 @@
 +----------------------------------------------------------------------------+
 */
 
-// Reads only for ONE  hardware component
-INT i_EepromReadAnlogInputHeader(WORD w_PCIBoardEepromAddress,
-	char *pc_PCIChipInformation, WORD w_Address,
-	str_AnalogInputHeader * s_Header)
+/* Reads only for ONE  hardware component */
+int i_EepromReadAnlogInputHeader(unsigned short w_PCIBoardEepromAddress,
+	char *pc_PCIChipInformation, unsigned short w_Address,
+	struct str_AnalogInputHeader *s_Header)
 {
-	WORD w_Temp, w_Offset;
+	unsigned short w_Temp, w_Offset;
 	w_Temp = w_EepromReadWord(w_PCIBoardEepromAddress,
 		pc_PCIChipInformation, 0x100 + w_Address + 10);
 	s_Header->w_Nchannel = (w_Temp >> 4) & 0x03FF;
@@ -1135,24 +1133,24 @@
 		0x100 + w_Address + 30);
 	w_Temp = w_EepromReadWord(w_PCIBoardEepromAddress,
 		pc_PCIChipInformation, 0x100 + w_Address + 20);
-	s_Header->b_HasDma = (w_Temp >> 13) & 0x01;	// whether dma present or not
+	s_Header->b_HasDma = (w_Temp >> 13) & 0x01;	/*  whether dma present or not */
 
-	w_Temp = w_EepromReadWord(w_PCIBoardEepromAddress, pc_PCIChipInformation, 0x100 + w_Address + 72);	// reading Y
+	w_Temp = w_EepromReadWord(w_PCIBoardEepromAddress, pc_PCIChipInformation, 0x100 + w_Address + 72);	/*  reading Y */
 	w_Temp = w_Temp & 0x00FF;
-	if (w_Temp)		//Y>0
+	if (w_Temp)		/* Y>0 */
 	{
-		w_Offset = 74 + (2 * w_Temp) + (10 * (1 + (w_Temp / 16)));	// offset of first analog input single header
-		w_Offset = w_Offset + 2;	// resolution
-	} else			//Y=0
+		w_Offset = 74 + (2 * w_Temp) + (10 * (1 + (w_Temp / 16)));	/*  offset of first analog input single header */
+		w_Offset = w_Offset + 2;	/*  resolution */
+	} else			/* Y=0 */
 	{
 		w_Offset = 74;
-		w_Offset = w_Offset + 2;	// resolution
+		w_Offset = w_Offset + 2;	/*  resolution */
 	}
 
-// read Resolution
+/* read Resolution */
 	w_Temp = w_EepromReadWord(w_PCIBoardEepromAddress,
 		pc_PCIChipInformation, 0x100 + w_Address + w_Offset);
-	s_Header->b_Resolution = w_Temp & 0x001F;	// last 5 bits
+	s_Header->b_Resolution = w_Temp & 0x001F;	/*  last 5 bits */
 
 	return 0;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/amcc_s5933_58.h b/drivers/staging/comedi/drivers/addi-data/amcc_s5933_58.h
index 617dc08..b76f877 100644
--- a/drivers/staging/comedi/drivers/addi-data/amcc_s5933_58.h
+++ b/drivers/staging/comedi/drivers/addi-data/amcc_s5933_58.h
@@ -31,15 +31,15 @@
 
 *************************/
 
-#define FIFO_ADVANCE_ON_BYTE_2     0x20000000	// written on base0
+#define FIFO_ADVANCE_ON_BYTE_2     0x20000000	/*  written on base0 */
 
-#define AMWEN_ENABLE                     0x02	// added for step 6 dma written on base2
+#define AMWEN_ENABLE                     0x02	/*  added for step 6 dma written on base2 */
 #define A2P_FIFO_WRITE_ENABLE            0x01
 
-#define AGCSTS_TC_ENABLE		   0x10000000	// Added for transfer count enable bit
+#define AGCSTS_TC_ENABLE		   0x10000000	/*  Added for transfer count enable bit */
 
-//  ADDON RELATED ADDITIONS
-// Constant
+/* ADDON RELATED ADDITIONS */
+/* Constant */
 #define     APCI3120_ENABLE_TRANSFER_ADD_ON_LOW       0x00
 #define     APCI3120_ENABLE_TRANSFER_ADD_ON_HIGH      0x1200
 #define     APCI3120_A2P_FIFO_MANAGEMENT              0x04000400L
@@ -52,7 +52,7 @@
 #define     APCI3120_DISABLE_BUS_MASTER_ADD_ON        0x0
 #define     APCI3120_DISABLE_BUS_MASTER_PCI           0x0
 
- // ADD_ON ::: this needed since apci supports 16 bit interface to add on
+ /*  ADD_ON ::: this needed since apci supports 16 bit interface to add on */
 #define     APCI3120_ADD_ON_AGCSTS_LOW       0x3C
 #define     APCI3120_ADD_ON_AGCSTS_HIGH      APCI3120_ADD_ON_AGCSTS_LOW + 2
 #define     APCI3120_ADD_ON_MWAR_LOW         0x24
@@ -60,7 +60,7 @@
 #define     APCI3120_ADD_ON_MWTC_LOW         0x058
 #define     APCI3120_ADD_ON_MWTC_HIGH        APCI3120_ADD_ON_MWTC_LOW + 2
 
-// AMCC
+/* AMCC */
 #define     APCI3120_AMCC_OP_MCSR            0x3C
 #define     APCI3120_AMCC_OP_REG_INTCSR      0x38
 
@@ -85,7 +85,7 @@
 #define AMCC_OP_REG_MRTC         0x30
 #define AMCC_OP_REG_MBEF         0x34
 #define AMCC_OP_REG_INTCSR       0x38
-#define  AMCC_OP_REG_INTCSR_SRC  (AMCC_OP_REG_INTCSR + 2)	/* INT source */
+#define  AMCC_OP_REG_INTCSR_SRC  (AMCC_OP_REG_INTCSR + 2)	/* int source */
 #define  AMCC_OP_REG_INTCSR_FEC  (AMCC_OP_REG_INTCSR + 3)	/* FIFO ctrl */
 #define AMCC_OP_REG_MCSR         0x3c
 #define  AMCC_OP_REG_MCSR_NVDATA (AMCC_OP_REG_MCSR + 2)	/* Data in byte 2 */
@@ -212,7 +212,7 @@
 	unsigned int irq;
 };
 
-struct pcilst_struct *amcc_devices;	// ptr to root list of all amcc devices
+struct pcilst_struct *amcc_devices;	/*  ptr to root list of all amcc devices */
 
 /****************************************************************************/
 
@@ -267,7 +267,7 @@
 			amcc->vendor = pcidev->vendor;
 			amcc->device = pcidev->device;
 #if 0
-			amcc->master = pcidev->master;	// how get this information under 2.4 kernels?
+			amcc->master = pcidev->master;	/*  how get this information under 2.4 kernels? */
 #endif
 			amcc->pci_bus = pcidev->bus->number;
 			amcc->pci_slot = PCI_SLOT(pcidev->devfn);
@@ -333,17 +333,17 @@
 		    && (amcc->pci_slot == pci_slot)) {
 			if (!(amcc->used)) {
 				*card = amcc;
-				return 0;	// ok, card is found
+				return 0;	/*  ok, card is found */
 			} else {
-				rt_printk
+				printk
 				    (" - \nCard on requested position is used b:s %d:%d!\n",
 				     pci_bus, pci_slot);
-				return 2;	// card exist but is used
+				return 2;	/*  card exist but is used */
 			}
 		}
 	}
 
-	return 1;		// no card found
+	return 1;		/*  no card found */
 }
 
 /****************************************************************************/
@@ -422,11 +422,10 @@
 {
 	struct pcilst_struct *card;
 
-	if ((pci_bus < 1) & (pci_slot < 1)) {	// use autodetection
-		if ((card = ptr_find_free_pci_card_by_device(vendor_id,
-							     device_id)) ==
-		    NULL) {
-			rt_printk(" - Unused card not found in system!\n");
+	if ((pci_bus < 1) & (pci_slot < 1)) {	/*  use autodetection */
+		card = ptr_find_free_pci_card_by_device(vendor_id, device_id);
+		if (card == NULL) {
+			printk(" - Unused card not found in system!\n");
 			return NULL;
 		}
 	} else {
@@ -434,12 +433,12 @@
 							 pci_bus, pci_slot,
 							 &card)) {
 		case 1:
-			rt_printk
+			printk
 			    (" - Card not found on requested position b:s %d:%d!\n",
 			     pci_bus, pci_slot);
 			return NULL;
 		case 2:
-			rt_printk
+			printk
 			    (" - Card on requested position is used b:s %d:%d!\n",
 			     pci_bus, pci_slot);
 			return NULL;
@@ -447,7 +446,7 @@
 	}
 
 	if (i_pci_card_alloc(card) != 0) {
-		rt_printk(" - Can't allocate card!\n");
+		printk(" - Can't allocate card!\n");
 		return NULL;
 	}
 
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_APCI1710.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_APCI1710.c
index 3f8929c..47517a9 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_APCI1710.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_APCI1710.c
@@ -1,15 +1,15 @@
-/**
+//**
 @verbatim
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -56,21 +56,22 @@
 #include "APCI1710_Pwm.c"
 #include "APCI1710_INCCPT.c"
 
-void i_ADDI_AttachPCI1710(struct comedi_device * dev)
+void i_ADDI_AttachPCI1710(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s;
 	int ret = 0;
 	int n_subdevices = 9;
 
-	//Update-0.7.57->0.7.68dev->n_subdevices = 9;
-	if ((ret = alloc_subdevices(dev, n_subdevices)) < 0)
+	/* Update-0.7.57->0.7.68dev->n_subdevices = 9; */
+	ret = alloc_subdevices(dev, n_subdevices);
+	if (ret < 0)
 		return;
 
-	// Allocate and Initialise Timer Subdevice Structures
+	/*  Allocate and Initialise Timer Subdevice Structures */
 	s = dev->subdevices + 0;
 
 	s->type = COMEDI_SUBD_TIMER;
-	s->subdev_flags = SDF_WRITEABLE | SDF_RT | SDF_GROUND | SDF_COMMON;
+	s->subdev_flags = SDF_WRITEABLE | SDF_GROUND | SDF_COMMON;
 	s->n_chan = 3;
 	s->maxdata = 0;
 	s->len_chanlist = 3;
@@ -80,12 +81,12 @@
 	s->insn_config = i_APCI1710_InsnConfigInitTimer;
 	s->insn_bits = i_APCI1710_InsnBitsTimer;
 
-	// Allocate and Initialise DIO Subdevice Structures
+	/*  Allocate and Initialise DIO Subdevice Structures */
 	s = dev->subdevices + 1;
 
 	s->type = COMEDI_SUBD_DIO;
 	s->subdev_flags =
-		SDF_WRITEABLE | SDF_READABLE | SDF_RT | SDF_GROUND | SDF_COMMON;
+		SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
 	s->n_chan = 7;
 	s->maxdata = 1;
 	s->len_chanlist = 7;
@@ -95,11 +96,11 @@
 	s->insn_bits = i_APCI1710_InsnBitsDigitalIOPortOnOff;
 	s->insn_write = i_APCI1710_InsnWriteDigitalIOChlOnOff;
 
-	// Allocate and Initialise Chrono Subdevice Structures
+	/*  Allocate and Initialise Chrono Subdevice Structures */
 	s = dev->subdevices + 2;
 
 	s->type = COMEDI_SUBD_CHRONO;
-	s->subdev_flags = SDF_WRITEABLE | SDF_RT | SDF_GROUND | SDF_COMMON;
+	s->subdev_flags = SDF_WRITEABLE | SDF_GROUND | SDF_COMMON;
 	s->n_chan = 4;
 	s->maxdata = 0;
 	s->len_chanlist = 4;
@@ -109,55 +110,55 @@
 	s->insn_config = i_APCI1710_InsnConfigInitChrono;
 	s->insn_bits = i_APCI1710_InsnBitsChronoDigitalIO;
 
-	// Allocate and Initialise PWM Subdevice Structures
+	/*  Allocate and Initialise PWM Subdevice Structures */
 	s = dev->subdevices + 3;
 	s->type = COMEDI_SUBD_PWM;
 	s->subdev_flags =
-		SDF_WRITEABLE | SDF_READABLE | SDF_RT | SDF_GROUND | SDF_COMMON;
+		SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
 	s->n_chan = 3;
 	s->maxdata = 1;
 	s->len_chanlist = 3;
 	s->range_table = &range_digital;
-	s->io_bits = 0;		//all bits input
+	s->io_bits = 0;		/* all bits input */
 	s->insn_config = i_APCI1710_InsnConfigPWM;
 	s->insn_read = i_APCI1710_InsnReadGetPWMStatus;
 	s->insn_write = i_APCI1710_InsnWritePWM;
 	s->insn_bits = i_APCI1710_InsnBitsReadPWMInterrupt;
 
-	// Allocate and Initialise TTLIO Subdevice Structures
+	/*  Allocate and Initialise TTLIO Subdevice Structures */
 	s = dev->subdevices + 4;
 	s->type = COMEDI_SUBD_TTLIO;
 	s->subdev_flags =
-		SDF_WRITEABLE | SDF_READABLE | SDF_RT | SDF_GROUND | SDF_COMMON;
+		SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
 	s->n_chan = 8;
 	s->maxdata = 1;
 	s->len_chanlist = 8;
-	s->range_table = &range_apci1710_ttl;	// to pass arguments in range
+	s->range_table = &range_apci1710_ttl;	/*  to pass arguments in range */
 	s->insn_config = i_APCI1710_InsnConfigInitTTLIO;
 	s->insn_bits = i_APCI1710_InsnBitsReadTTLIO;
 	s->insn_write = i_APCI1710_InsnWriteSetTTLIOChlOnOff;
 	s->insn_read = i_APCI1710_InsnReadTTLIOAllPortValue;
 
-	// Allocate and Initialise TOR Subdevice Structures
+	/*  Allocate and Initialise TOR Subdevice Structures */
 	s = dev->subdevices + 5;
 	s->type = COMEDI_SUBD_TOR;
 	s->subdev_flags =
-		SDF_WRITEABLE | SDF_READABLE | SDF_RT | SDF_GROUND | SDF_COMMON;
+		SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
 	s->n_chan = 8;
 	s->maxdata = 1;
 	s->len_chanlist = 8;
 	s->range_table = &range_digital;
-	s->io_bits = 0;		//all bits input
+	s->io_bits = 0;		/* all bits input */
 	s->insn_config = i_APCI1710_InsnConfigInitTorCounter;
 	s->insn_read = i_APCI1710_InsnReadGetTorCounterInitialisation;
 	s->insn_write = i_APCI1710_InsnWriteEnableDisableTorCounter;
 	s->insn_bits = i_APCI1710_InsnBitsGetTorCounterProgressStatusAndValue;
 
-	// Allocate and Initialise SSI Subdevice Structures
+	/*  Allocate and Initialise SSI Subdevice Structures */
 	s = dev->subdevices + 6;
 	s->type = COMEDI_SUBD_SSI;
 	s->subdev_flags =
-		SDF_WRITEABLE | SDF_READABLE | SDF_RT | SDF_GROUND | SDF_COMMON;
+		SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
 	s->n_chan = 4;
 	s->maxdata = 1;
 	s->len_chanlist = 4;
@@ -166,11 +167,11 @@
 	s->insn_read = i_APCI1710_InsnReadSSIValue;
 	s->insn_bits = i_APCI1710_InsnBitsSSIDigitalIO;
 
-	// Allocate and Initialise PULSEENCODER Subdevice Structures
+	/*  Allocate and Initialise PULSEENCODER Subdevice Structures */
 	s = dev->subdevices + 7;
 	s->type = COMEDI_SUBD_PULSEENCODER;
 	s->subdev_flags =
-		SDF_WRITEABLE | SDF_READABLE | SDF_RT | SDF_GROUND | SDF_COMMON;
+		SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
 	s->n_chan = 4;
 	s->maxdata = 1;
 	s->len_chanlist = 4;
@@ -180,11 +181,11 @@
 	s->insn_bits = i_APCI1710_InsnBitsReadWritePulseEncoder;
 	s->insn_read = i_APCI1710_InsnReadInterruptPulseEncoder;
 
-	// Allocate and Initialise INCREMENTALCOUNTER Subdevice Structures
+	/*  Allocate and Initialise INCREMENTALCOUNTER Subdevice Structures */
 	s = dev->subdevices + 8;
 	s->type = COMEDI_SUBD_INCREMENTALCOUNTER;
 	s->subdev_flags =
-		SDF_WRITEABLE | SDF_READABLE | SDF_RT | SDF_GROUND | SDF_COMMON;
+		SDF_WRITEABLE | SDF_READABLE | SDF_GROUND | SDF_COMMON;
 	s->n_chan = 500;
 	s->maxdata = 1;
 	s->len_chanlist = 500;
@@ -195,14 +196,14 @@
 	s->insn_bits = i_APCI1710_InsnBitsINCCPT;
 }
 
-int i_APCI1710_Reset(struct comedi_device * dev);
+int i_APCI1710_Reset(struct comedi_device *dev);
 void v_APCI1710_Interrupt(int irq, void *d);
-//for 1710
+/* for 1710 */
 
-int i_APCI1710_Reset(struct comedi_device * dev)
+int i_APCI1710_Reset(struct comedi_device *dev)
 {
 	int ret;
-	DWORD dw_Dummy;
+	unsigned int dw_Dummy;
 
 	/*********************************/
 	/* Read all module configuration */
@@ -219,12 +220,12 @@
 	ret = inl(devpriv->s_BoardInfos.ui_Address + 252);
 	devpriv->s_BoardInfos.dw_MolduleConfiguration[3] = ret;
 
-	// outl(0x80808082,devpriv->s_BoardInfos.ui_Address+0x60);
+	/*  outl(0x80808082,devpriv->s_BoardInfos.ui_Address+0x60); */
 	outl(0x83838383, devpriv->s_BoardInfos.ui_Address + 0x60);
 
 	devpriv->s_BoardInfos.b_BoardVersion = 1;
 
-	// Enable the interrupt for the controler
+	/*  Enable the interrupt for the controler */
 	dw_Dummy = inl(devpriv->s_BoardInfos.ui_Address + 0x38);
 	outl(dw_Dummy | 0x2000, devpriv->s_BoardInfos.ui_Address + 0x38);
 
@@ -234,11 +235,11 @@
 /*
 +----------------------------------------------------------------------------+
 | Function's Name   : __void__ v_APCI1710_InterruptFunction                  |
-|				(BYTE b_Interrupt, __CPPARGS)                |
+|				(unsigned char b_Interrupt, __CPPARGS)                |
 +----------------------------------------------------------------------------+
 | Task              : APCI-1710 interrupt function                           |
 +----------------------------------------------------------------------------+
-| Input Parameters  : BYTE b_Interrupt : Interrupt number                    |
+| Input Parameters  : unsigned char b_Interrupt : Interrupt number                    |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -250,18 +251,18 @@
 void v_APCI1710_Interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
-	BYTE b_ModuleCpt = 0;
-	BYTE b_InterruptFlag = 0;
-	BYTE b_PWMCpt = 0;
-	BYTE b_TorCounterCpt = 0;
-	BYTE b_PulseIncoderCpt = 0;
-	UINT ui_16BitValue;
-	ULONG ul_InterruptLatchReg = 0;
-	ULONG ul_LatchRegisterValue = 0;
-	ULONG ul_82X54InterruptStatus;
-	ULONG ul_StatusRegister;
+	unsigned char b_ModuleCpt = 0;
+	unsigned char b_InterruptFlag = 0;
+	unsigned char b_PWMCpt = 0;
+	unsigned char b_TorCounterCpt = 0;
+	unsigned char b_PulseIncoderCpt = 0;
+	unsigned int ui_16BitValue;
+	unsigned int ul_InterruptLatchReg = 0;
+	unsigned int ul_LatchRegisterValue = 0;
+	unsigned int ul_82X54InterruptStatus;
+	unsigned int ul_StatusRegister;
 
-	str_ModuleInfo *ps_ModuleInfo;
+	union str_ModuleInfo *ps_ModuleInfo;
 
 	printk("APCI1710 Interrupt\n");
 	for (b_ModuleCpt = 0; b_ModuleCpt < 4; b_ModuleCpt++, ps_ModuleInfo++) {
@@ -279,7 +280,7 @@
 				dw_MolduleConfiguration[b_ModuleCpt] &
 				0xFFFF0000UL) == APCI1710_82X54_TIMER) {
 
-			//printk("TIMER Interrupt Occurred\n");
+			/* printk("TIMER Interrupt Occurred\n"); */
 			ul_82X54InterruptStatus = inl(devpriv->s_BoardInfos.
 				ui_Address + 12 + (64 * b_ModuleCpt));
 
@@ -332,11 +333,11 @@
 			     /**********************/
 				/* Call user function */
 			     /**********************/
-				//Send a signal to from kernel to user space
+				/* Send a signal to from kernel to user space */
 				send_sig(SIGIO, devpriv->tsk_Current, 0);
 
-			}	// if ((ul_82X54InterruptStatus & 0x7) != 0)
-		}		// 82X54 timer
+			}	/*  if ((ul_82X54InterruptStatus & 0x7) != 0) */
+		}		/*  82X54 timer */
 
 		 /***************************/
 		/* Test if increm. counter */
@@ -412,7 +413,7 @@
 				/**********************/
 					/* Call user function */
 				/**********************/
-					//Send a signal to from kernel to user space
+					/* Send a signal to from kernel to user space */
 					send_sig(SIGIO, devpriv->tsk_Current,
 						0);
 
@@ -473,7 +474,7 @@
 			    /**********************/
 					/* Call user function */
 				/**********************/
-					//Send a signal to from kernel to user space
+					/* Send a signal to from kernel to user space */
 					send_sig(SIGIO, devpriv->tsk_Current,
 						0);
 
@@ -562,7 +563,7 @@
 				/**********************/
 					/* Call user function */
 				/**********************/
-					//Send a signal to from kernel to user space
+					/* Send a signal to from kernel to user space */
 					send_sig(SIGIO, devpriv->tsk_Current,
 						0);
 
@@ -628,7 +629,7 @@
 				/**********************/
 					/* Call user function */
 				/**********************/
-					//Send a signal to from kernel to user space
+					/* Send a signal to from kernel to user space */
 					send_sig(SIGIO, devpriv->tsk_Current,
 						0);
 
@@ -675,7 +676,7 @@
 						if ((ul_LatchRegisterValue &
 								0xFFFFU) != 0) {
 							ui_16BitValue =
-								(UINT)
+								(unsigned int)
 								ul_LatchRegisterValue
 								& 0xFFFFU;
 							ul_LatchRegisterValue =
@@ -693,7 +694,7 @@
 								0xFFFF0000UL) !=
 							0) {
 							ui_16BitValue =
-								(UINT) (
+								(unsigned int) (
 								(ul_LatchRegisterValue
 									>> 16) &
 								0xFFFFU);
@@ -721,7 +722,7 @@
 					if ((ul_LatchRegisterValue &
 							0xFFFF0000UL) != 0) {
 						ui_16BitValue =
-							(UINT) (
+							(unsigned int) (
 							(ul_LatchRegisterValue
 								>> 16) &
 							0xFFFFU);
@@ -741,7 +742,7 @@
 					if ((ul_LatchRegisterValue & 0xFFFFU) !=
 						0) {
 						ui_16BitValue =
-							(UINT)
+							(unsigned int)
 							ul_LatchRegisterValue &
 							0xFFFFU;
 						ul_LatchRegisterValue =
@@ -795,11 +796,11 @@
 			     /**********************/
 				/* Call user function */
 			     /**********************/
-				//Send a signal to from kernel to user space
+				/* Send a signal to from kernel to user space */
 				send_sig(SIGIO, devpriv->tsk_Current, 0);
 
 			}
-		}		// Incremental counter
+		}		/*  Incremental counter */
 
 		 /***************/
 		/* Test if CDA */
@@ -870,14 +871,14 @@
 					/* Call user function */
 				/**********************/
 
-					//Send a signal to from kernel to user space
+					/* Send a signal to from kernel to user space */
 					send_sig(SIGIO, devpriv->tsk_Current,
 						0);
 
-				}	// if (ul_StatusRegister & 1)
+				}	/*  if (ul_StatusRegister & 1) */
 
 			}
-		}		// CDA
+		}		/*  CDA */
 
 		 /***********************/
 		/* Test if PWM counter */
@@ -950,15 +951,15 @@
 				   /**********************/
 						/* Call user function */
 				   /**********************/
-						//Send a signal to from kernel to user space
+						/* Send a signal to from kernel to user space */
 						send_sig(SIGIO,
 							devpriv->tsk_Current,
 							0);
 
-					}	// if (ul_StatusRegister & 0x1)
-				}	// if (APCI1710_ENABLE)
-			}	// for (b_PWMCpt == 0; b_PWMCpt < 0; b_PWMCpt ++)
-		}		// PWM counter
+					}	/*  if (ul_StatusRegister & 0x1) */
+				}	/*  if (APCI1710_ENABLE) */
+			}	/*  for (b_PWMCpt == 0; b_PWMCpt < 0; b_PWMCpt ++) */
+		}		/*  PWM counter */
 
 		 /***********************/
 		/* Test if tor counter */
@@ -1054,14 +1055,14 @@
 						/* Call user function */
 				   /**********************/
 
-						//Send a signal to from kernel to user space
+						/* Send a signal to from kernel to user space */
 						send_sig(SIGIO,
 							devpriv->tsk_Current,
 							0);
-					}	// if (ul_StatusRegister & 0x1)
-				}	// if (APCI1710_ENABLE)
-			}	// for (b_TorCounterCpt == 0; b_TorCounterCpt < 0; b_TorCounterCpt ++)
-		}		// Tor counter
+					}	/*  if (ul_StatusRegister & 0x1) */
+				}	/*  if (APCI1710_ENABLE) */
+			}	/*  for (b_TorCounterCpt == 0; b_TorCounterCpt < 0; b_TorCounterCpt ++) */
+		}		/*  Tor counter */
 
 		 /***********************/
 		/* Test if chronometer */
@@ -1071,7 +1072,7 @@
 				dw_MolduleConfiguration[b_ModuleCpt] &
 				0xFFFF0000UL) == APCI1710_CHRONOMETER) {
 
-			//printk("APCI1710 Chrono Interrupt\n");
+			/* printk("APCI1710 Chrono Interrupt\n"); */
 		    /*****************************/
 			/* Read the interrupt status */
 		    /*****************************/
@@ -1163,13 +1164,13 @@
 				/**********************/
 					/* Call user function */
 				/**********************/
-					//Send a signal to from kernel to user space
+					/* Send a signal to from kernel to user space */
 					send_sig(SIGIO, devpriv->tsk_Current,
 						0);
 
 				}
 			}
-		}		// Chronometer
+		}		/*  Chronometer */
 
 		 /*************************/
 		/* Test if pulse encoder */
@@ -1249,7 +1250,7 @@
 				   /**********************/
 						/* Call user function */
 				   /**********************/
-						//Send a signal to from kernel to user space
+						/* Send a signal to from kernel to user space */
 						send_sig(SIGIO,
 							devpriv->tsk_Current,
 							0);
@@ -1257,7 +1258,7 @@
 					}
 				}
 			}
-		}		//pulse encoder
+		}		/* pulse encoder */
 
 	}
 	return;
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_APCI1710.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_APCI1710.h
index 998cbba..22b3e56 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_APCI1710.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_APCI1710.h
@@ -44,7 +44,7 @@
 #define APCI1710_SYNCHRONOUS_MODE	1
 #define APCI1710_ASYNCHRONOUS_MODE	0
 
-//MODULE INFO STRUCTURE
+/* MODULE INFO STRUCTURE */
 
 static const struct comedi_lrange range_apci1710_ttl = { 4, {
 						      BIP_RANGE(10),
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci035.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci035.c
index e452792..016721e 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci035.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci035.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -52,9 +52,9 @@
 +----------------------------------------------------------------------------+
 */
 #include "hwdrv_apci035.h"
-INT i_WatchdogNbr = 0;
-INT i_Temp = 0;
-INT i_Flag = 1;
+int i_WatchdogNbr = 0;
+int i_Temp = 0;
+int i_Flag = 1;
 /*
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI035_ConfigTimerWatchdog                      |
@@ -64,42 +64,42 @@
 | Task              : Configures The Timer , Counter or Watchdog             |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 |					  data[0]            : 0 Configure As Timer      |
 |										   1 Configure As Watchdog   |
-                              data[1]            : Watchdog number
+|                                         data[1]            : Watchdog number
 |					  data[2]            : Time base Unit            |
 |					  data[3]			 : Reload Value			     |
-                              data[4]            : External Trigger          |
-                                                   1:Enable
-                                                   0:Disable
-                              data[5]            :External Trigger Level
-                                                  00 Trigger Disabled
-                                                  01 Trigger Enabled (Low level)
-                                                  10 Trigger Enabled (High Level)
-                                                  11 Trigger Enabled (High/Low level)
-                              data[6]            : External Gate            |
-                                                   1:Enable
-                                                   0:Disable
-                              data[7]            : External Gate level
-                                                  00 Gate Disabled
-                                                  01 Gate Enabled (Low level)
-                                                  10 Gate Enabled (High Level)
-                              data[8]            :Warning Relay
-                                                  1: ENABLE
-                                                  0: DISABLE
-                              data[9]            :Warning Delay available
-                              data[10]           :Warning Relay Time unit
-                              data[11]           :Warning Relay Time Reload value
-                              data[12]           :Reset Relay
-                                                  1 : ENABLE
-                                                  0 : DISABLE
-                              data[13]           :Interrupt
-                                                  1 : ENABLE
-                                                  0 : DISABLE
-
+|                                         data[4]            : External Trigger          |
+|                                                              1:Enable
+|                                                           0:Disable
+|                              data[5]            :External Trigger Level
+|                                                  00 Trigger Disabled
+|                                                  01 Trigger Enabled (Low level)
+|                                                  10 Trigger Enabled (High Level)
+|                                                  11 Trigger Enabled (High/Low level)
+|                              data[6]            : External Gate            |
+|                                                   1:Enable
+|                                                   0:Disable
+|                              data[7]            : External Gate level
+|                                                  00 Gate Disabled
+|                                                  01 Gate Enabled (Low level)
+|                                                  10 Gate Enabled (High Level)
+|                              data[8]            :Warning Relay
+|                                                  1: ENABLE
+|                                                  0: DISABLE
+|                              data[9]            :Warning Delay available
+|                              data[10]           :Warning Relay Time unit
+|                              data[11]           :Warning Relay Time Reload value
+|                              data[12]           :Reset Relay
+|                                                  1 : ENABLE
+|                                                  0 : DISABLE
+|                              data[13]           :Interrupt
+|                                                  1 : ENABLE
+|                                                  0 : DISABLE
+|
 |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -109,12 +109,12 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI035_ConfigTimerWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI035_ConfigTimerWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Status = 0;
-	UINT ui_Command = 0;
-	UINT ui_Mode = 0;
+	unsigned int ui_Status = 0;
+	unsigned int ui_Command = 0;
+	unsigned int ui_Mode = 0;
 	i_Temp = 0;
 	devpriv->tsk_Current = current;
 	devpriv->b_TimerSelectMode = data[0];
@@ -124,9 +124,9 @@
 	} else {
 		ui_Mode = 0;
 	}
-//ui_Command = inl(devpriv->iobase+((i_WatchdogNbr-1)*32)+12);
+/* ui_Command = inl(devpriv->iobase+((i_WatchdogNbr-1)*32)+12); */
 	ui_Command = 0;
-//ui_Command = ui_Command & 0xFFFFF9FEUL;
+/* ui_Command = ui_Command & 0xFFFFF9FEUL; */
 	outl(ui_Command, devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
 	ui_Command = 0;
 	ui_Command = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
@@ -153,7 +153,7 @@
 		ui_Command =
 			(ui_Command & 0xFFF719E2UL) | ui_Mode << 13UL | 0x10UL;
 
-	}			//if (data[0] == ADDIDATA_TIMER)
+	}			/* if (data[0] == ADDIDATA_TIMER) */
 	else {
 		if (data[0] == ADDIDATA_WATCHDOG) {
 
@@ -260,7 +260,7 @@
 | Task              : Start / Stop The Selected Timer , or Watchdog  |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |					                                                 |
 |					  data[0] : 0 - Stop Selected Timer/Watchdog     |
@@ -278,11 +278,11 @@
 |					                                                 |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI035_StartStopWriteTimerWatchdog(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI035_StartStopWriteTimerWatchdog(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Command = 0;
-	INT i_Count = 0;
+	unsigned int ui_Command = 0;
+	int i_Count = 0;
 	if (data[0] == 1) {
 		ui_Command =
 			inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
@@ -292,7 +292,7 @@
 		ui_Command = (ui_Command & 0xFFFFF9FFUL) | 0x1UL;
 		outl(ui_Command,
 			devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
-	}			// if  (data[0]==1)
+	}			/*  if  (data[0]==1) */
 	if (data[0] == 2) {
 		ui_Command =
 			inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
@@ -304,16 +304,18 @@
 			devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
 	}
 
-	if (data[0] == 0)	//Stop The Watchdog
+	if (data[0] == 0)	/* Stop The Watchdog */
 	{
-		//Stop The Watchdog
+		/* Stop The Watchdog */
 		ui_Command = 0;
-		//ui_Command = inl(devpriv->iobase+((i_WatchdogNbr-1)*32)+12);
-		//ui_Command = ui_Command & 0xFFFFF9FEUL;
+/*
+* ui_Command = inl(devpriv->iobase+((i_WatchdogNbr-1)*32)+12);
+* ui_Command = ui_Command & 0xFFFFF9FEUL;
+*/
 		outl(ui_Command,
 			devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
-	}			//  if (data[1]==0)
-	if (data[0] == 3)	//stop all Watchdogs
+	}			/*   if (data[1]==0) */
+	if (data[0] == 3)	/* stop all Watchdogs */
 	{
 		ui_Command = 0;
 		for (i_Count = 1; i_Count <= 4; i_Count++) {
@@ -329,7 +331,7 @@
 		}
 
 	}
-	if (data[0] == 4)	//start all Watchdogs
+	if (data[0] == 4)	/* start all Watchdogs */
 	{
 		ui_Command = 0;
 		for (i_Count = 1; i_Count <= 4; i_Count++) {
@@ -344,7 +346,7 @@
 				0);
 		}
 	}
-	if (data[0] == 5)	//trigger all Watchdogs
+	if (data[0] == 5)	/* trigger all Watchdogs */
 	{
 		ui_Command = 0;
 		for (i_Count = 1; i_Count <= 4; i_Count++) {
@@ -373,17 +375,17 @@
 | Task              : Read The Selected Timer , Counter or Watchdog          |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 |     																	 |
 +----------------------------------------------------------------------------+
 | Output Parameters :	data[0]            : software trigger status
-              data[1]            : hardware trigger status
-|     				data[2]            : Software clear status
-                        data[3]            : Overflow status
-                     data[4]            : Timer actual value
-
+|                       data[1]            : hardware trigger status
+|     	  	        data[2]            : Software clear status
+|                       data[3]            : Overflow status
+|                       data[4]            : Timer actual value
+|
 
 +----------------------------------------------------------------------------+
 | Return Value      : TRUE  : No error occur                                 |
@@ -391,42 +393,46 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI035_ReadTimerWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI035_ReadTimerWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Status = 0;	// Status register
+	unsigned int ui_Status = 0;	/*  Status register */
 	i_WatchdogNbr = insn->unused[0];
-	      /******************/
+
+	/******************/
 	/* Get the status */
-	      /******************/
+	/******************/
+
 	ui_Status = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 16);
-      /***********************************/
+
+	/***********************************/
 	/* Get the software trigger status */
-      /***********************************/
+	/***********************************/
+
 	data[0] = ((ui_Status >> 1) & 1);
-      /***********************************/
+	/***********************************/
 	/* Get the hardware trigger status */
-      /***********************************/
+	/***********************************/
 	data[1] = ((ui_Status >> 2) & 1);
-      /*********************************/
+	/*********************************/
 	/* Get the software clear status */
-      /*********************************/
+	/*********************************/
 	data[2] = ((ui_Status >> 3) & 1);
-      /***************************/
+	/***************************/
 	/* Get the overflow status */
-      /***************************/
+	/***************************/
 	data[3] = ((ui_Status >> 0) & 1);
 	if (devpriv->b_TimerSelectMode == ADDIDATA_TIMER) {
 		data[4] = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 0);
 
-	}			//  if  (devpriv->b_TimerSelectMode==ADDIDATA_TIMER)
+	}			/*   if  (devpriv->b_TimerSelectMode==ADDIDATA_TIMER) */
 
 	return insn->n;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function   Name   : INT i_APCI035_ConfigAnalogInput                        |
+| Function   Name   : int i_APCI035_ConfigAnalogInput                        |
 |			  (struct comedi_device *dev,struct comedi_subdevice *s,               |
 |                      struct comedi_insn *insn,unsigned int *data)                     |
 +----------------------------------------------------------------------------+
@@ -447,8 +453,8 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI035_ConfigAnalogInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI035_ConfigAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	devpriv->tsk_Current = current;
 	outl(0x200 | 0, devpriv->iobase + 128 + 0x4);
@@ -472,8 +478,8 @@
 | Task              : Read  value  of the selected channel			         |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To read       |
-|                     UINT *data              : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To read       |
+|                     unsigned int *data              : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 |			          data[0]  : Digital Value Of Input              |
@@ -484,10 +490,10 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI035_ReadAnalogInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI035_ReadAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_CommandRegister = 0;
+	unsigned int ui_CommandRegister = 0;
 /******************/
 /*  Set the start */
 /******************/
@@ -519,14 +525,14 @@
 |			                                                                 |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI035_Reset(struct comedi_device * dev)
+int i_APCI035_Reset(struct comedi_device *dev)
 {
-	INT i_Count = 0;
+	int i_Count = 0;
 	for (i_Count = 1; i_Count <= 4; i_Count++) {
 		i_WatchdogNbr = i_Count;
-		outl(0x0, devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 0);	//stop all timers
+		outl(0x0, devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 0);	/* stop all timers */
 	}
-	outl(0x0, devpriv->iobase + 128 + 12);	//Disable the warning delay
+	outl(0x0, devpriv->iobase + 128 + 12);	/* Disable the warning delay */
 
 	return 0;
 }
@@ -551,11 +557,11 @@
 static void v_APCI035_Interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
-	UINT ui_StatusRegister1 = 0;
-	UINT ui_StatusRegister2 = 0;
-	UINT ui_ReadCommand = 0;
-	UINT ui_ChannelNumber = 0;
-	UINT ui_DigitalTemperature = 0;
+	unsigned int ui_StatusRegister1 = 0;
+	unsigned int ui_StatusRegister2 = 0;
+	unsigned int ui_ReadCommand = 0;
+	unsigned int ui_ChannelNumber = 0;
+	unsigned int ui_DigitalTemperature = 0;
 	if (i_Temp == 1) {
 		i_WatchdogNbr = i_Flag;
 		i_Flag = i_Flag + 1;
@@ -571,7 +577,7 @@
 	ui_StatusRegister2 =
 		inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 20);
 
-	if ((((ui_StatusRegister1) & 0x8) == 0x8))	//Test if warning relay interrupt
+	if ((((ui_StatusRegister1) & 0x8) == 0x8))	/* Test if warning relay interrupt */
 	{
 	/**********************************/
 		/* Disable the temperature warning */
@@ -587,14 +593,14 @@
 		/* Read the digital temperature value */
 	/**************************************/
 		ui_DigitalTemperature = inl(devpriv->iobase + 128 + 60);
-		send_sig(SIGIO, devpriv->tsk_Current, 0);	// send signal to the sample
-	}			//if (((ui_StatusRegister1 & 0x8) == 0x8))
+		send_sig(SIGIO, devpriv->tsk_Current, 0);	/*  send signal to the sample */
+	}			/* if (((ui_StatusRegister1 & 0x8) == 0x8)) */
 
 	else {
 		if ((ui_StatusRegister2 & 0x1) == 0x1) {
-			send_sig(SIGIO, devpriv->tsk_Current, 0);	// send signal to the sample
+			send_sig(SIGIO, devpriv->tsk_Current, 0);	/*  send signal to the sample */
 		}
-	}			//else if (((ui_StatusRegister1 & 0x8) == 0x8))
+	}			/* else if (((ui_StatusRegister1 & 0x8) == 0x8)) */
 
 	return;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci035.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci035.h
index 80d7c0d..e0023c8 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci035.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci035.h
@@ -19,18 +19,18 @@
 #define APCI035_BOARD_VENDOR_ID		0x15B8
 #define APCI035_ADDRESS_RANGE		255
 
-INT i_TW_Number;
+int i_TW_Number;
 struct {
-	INT i_Gain;
-	INT i_Polarity;
-	INT i_OffsetRange;
-	INT i_Coupling;
-	INT i_SingleDiff;
-	INT i_AutoCalibration;
-	UINT ui_ReloadValue;
-	UINT ui_TimeUnitReloadVal;
-	INT i_Interrupt;
-	INT i_ModuleSelection;
+	int i_Gain;
+	int i_Polarity;
+	int i_OffsetRange;
+	int i_Coupling;
+	int i_SingleDiff;
+	int i_AutoCalibration;
+	unsigned int ui_ReloadValue;
+	unsigned int ui_TimeUnitReloadVal;
+	int i_Interrupt;
+	int i_ModuleSelection;
 } Config_Parameters_Main;
 
 /* ANALOG INPUT RANGE */
@@ -101,23 +101,23 @@
 
 /* TIMER */
 /* timer value is passed as u seconds */
-INT i_APCI035_ConfigTimerWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI035_ConfigTimerWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
 				  struct comedi_insn *insn, unsigned int *data);
-INT i_APCI035_StartStopWriteTimerWatchdog(struct comedi_device *dev,
+int i_APCI035_StartStopWriteTimerWatchdog(struct comedi_device *dev,
 					  struct comedi_subdevice *s,
 					  struct comedi_insn *insn, unsigned int *data);
-INT i_APCI035_ReadTimerWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI035_ReadTimerWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
 				struct comedi_insn *insn, unsigned int *data);
 
 /* Temperature Related Defines (Analog Input Subdevice) */
 
-INT i_APCI035_ConfigAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI035_ConfigAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				struct comedi_insn *insn, unsigned int *data);
-INT i_APCI035_ReadAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI035_ReadAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
 			      struct comedi_insn *insn, unsigned int *data);
 
 /* Interrupt */
 static void v_APCI035_Interrupt(int irq, void *d);
 
 /* Reset functions */
-INT i_APCI035_Reset(struct comedi_device *dev);
+int i_APCI035_Reset(struct comedi_device *dev);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1032.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1032.c
index 32796ce..e9021cd 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1032.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1032.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -53,8 +53,8 @@
 */
 #include "hwdrv_apci1032.h"
 #include <linux/delay.h>
-//Global variables
-UINT ui_InterruptStatus = 0;
+/* Global variables */
+unsigned int ui_InterruptStatus = 0;
 
 /*
 +----------------------------------------------------------------------------+
@@ -84,13 +84,13 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1032_ConfigDigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1032_ConfigDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_TmpValue;
+	unsigned int ui_TmpValue;
 
-	ULONG ul_Command1 = 0;
-	ULONG ul_Command2 = 0;
+	unsigned int ul_Command1 = 0;
+	unsigned int ul_Command2 = 0;
 	devpriv->tsk_Current = current;
 
   /*******************************/
@@ -107,11 +107,11 @@
 			outl(0x4, devpriv->iobase + APCI1032_DIGITAL_IP_IRQ);
 			ui_TmpValue =
 				inl(devpriv->iobase + APCI1032_DIGITAL_IP_IRQ);
-		}		//if (data[1] == ADDIDATA_OR)
+		}		/* if (data[1] == ADDIDATA_OR) */
 		else {
 			outl(0x6, devpriv->iobase + APCI1032_DIGITAL_IP_IRQ);
-		}		//else if(data[1] == ADDIDATA_OR)
-	}			// if( data[0] == ADDIDATA_ENABLE)
+		}		/* else if(data[1] == ADDIDATA_OR) */
+	}			/*  if( data[0] == ADDIDATA_ENABLE) */
 	else {
 		ul_Command1 = ul_Command1 & 0xFFFF0000;
 		ul_Command2 = ul_Command2 & 0xFFFF0000;
@@ -120,7 +120,7 @@
 		outl(ul_Command2,
 			devpriv->iobase + APCI1032_DIGITAL_IP_INTERRUPT_MODE2);
 		outl(0x0, devpriv->iobase + APCI1032_DIGITAL_IP_IRQ);
-	}			//else if  ( data[0] == ADDIDATA_ENABLE)
+	}			/* else if  ( data[0] == ADDIDATA_ENABLE) */
 
 	return insn->n;
 }
@@ -134,7 +134,7 @@
 | Task              : Return the status of the digital input                 |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|		              UINT ui_Channel : Channel number to read       |
+|		              unsigned int ui_Channel : Channel number to read       |
 |                     unsigned int *data          : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -144,22 +144,24 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1032_Read1DigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1032_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_TmpValue = 0;
-	UINT ui_Channel;
+	unsigned int ui_TmpValue = 0;
+	unsigned int ui_Channel;
 	ui_Channel = CR_CHAN(insn->chanspec);
 	if (ui_Channel >= 0 && ui_Channel <= 31) {
-		ui_TmpValue = (UINT) inl(devpriv->iobase + APCI1032_DIGITAL_IP);
-		//  since only 1 channel reqd  to bring it to last bit it is rotated
-		//  8 +(chan - 1) times then ANDed with 1 for last bit.
+		ui_TmpValue = (unsigned int) inl(devpriv->iobase + APCI1032_DIGITAL_IP);
+/*
+* since only 1 channel reqd to bring it to last bit it is rotated 8
+* +(chan - 1) times then ANDed with 1 for last bit.
+*/
 		*data = (ui_TmpValue >> ui_Channel) & 0x1;
-	}			//if(ui_Channel >= 0 && ui_Channel <=31)
+	}			/* if(ui_Channel >= 0 && ui_Channel <=31) */
 	else {
-		//comedi_error(dev," \n chan spec wrong\n");
-		return -EINVAL;	// "sorry channel spec wrong "
-	}			//else if(ui_Channel >= 0 && ui_Channel <=31)
+		/* comedi_error(dev," \n chan spec wrong\n"); */
+		return -EINVAL;	/*  "sorry channel spec wrong " */
+	}			/* else if(ui_Channel >= 0 && ui_Channel <=31) */
 	return insn->n;
 }
 
@@ -172,8 +174,8 @@
 | Task              : Return the status of the Requested digital inputs      |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To be Read    |
-|                      UINT *data             : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To be Read    |
+|                      unsigned int *data             : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -183,16 +185,16 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1032_ReadMoreDigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1032_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_PortValue = data[0];
-	UINT ui_Mask = 0;
-	UINT ui_NoOfChannels;
+	unsigned int ui_PortValue = data[0];
+	unsigned int ui_Mask = 0;
+	unsigned int ui_NoOfChannels;
 
 	ui_NoOfChannels = CR_CHAN(insn->chanspec);
 	if (data[1] == 0) {
-		*data = (UINT) inl(devpriv->iobase + APCI1032_DIGITAL_IP);
+		*data = (unsigned int) inl(devpriv->iobase + APCI1032_DIGITAL_IP);
 		switch (ui_NoOfChannels) {
 		case 2:
 			ui_Mask = 3;
@@ -213,16 +215,16 @@
 		case 31:
 			break;
 		default:
-			//comedi_error(dev," \nchan spec wrong\n");
-			return -EINVAL;	// "sorry channel spec wrong "
+			/* comedi_error(dev," \nchan spec wrong\n"); */
+			return -EINVAL;	/*  "sorry channel spec wrong " */
 			break;
-		}		//switch(ui_NoOfChannels)
-	}			//if(data[1]==0)
+		}		/* switch(ui_NoOfChannels) */
+	}			/* if(data[1]==0) */
 	else {
 		if (data[1] == 1) {
 			*data = ui_InterruptStatus;
-		}		//if(data[1]==1)
-	}			//else if(data[1]==0)
+		}		/* if(data[1]==1) */
+	}			/* else if(data[1]==0) */
 	return insn->n;
 }
 
@@ -247,16 +249,16 @@
 {
 	struct comedi_device *dev = d;
 
-	UINT ui_Temp;
-	//disable the interrupt
+	unsigned int ui_Temp;
+	/* disable the interrupt */
 	ui_Temp = inl(devpriv->iobase + APCI1032_DIGITAL_IP_IRQ);
 	outl(ui_Temp & APCI1032_DIGITAL_IP_INTERRUPT_DISABLE,
 		devpriv->iobase + APCI1032_DIGITAL_IP_IRQ);
 	ui_InterruptStatus =
 		inl(devpriv->iobase + APCI1032_DIGITAL_IP_INTERRUPT_STATUS);
 	ui_InterruptStatus = ui_InterruptStatus & 0X0000FFFF;
-	send_sig(SIGIO, devpriv->tsk_Current, 0);	// send signal to the sample
-	outl(ui_Temp, devpriv->iobase + APCI1032_DIGITAL_IP_IRQ);	//enable the interrupt
+	send_sig(SIGIO, devpriv->tsk_Current, 0);	/*  send signal to the sample */
+	outl(ui_Temp, devpriv->iobase + APCI1032_DIGITAL_IP_IRQ);	/* enable the interrupt */
 	return;
 }
 
@@ -275,11 +277,11 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1032_Reset(struct comedi_device * dev)
+int i_APCI1032_Reset(struct comedi_device *dev)
 {
-	outl(0x0, devpriv->iobase + APCI1032_DIGITAL_IP_IRQ);	//disable the interrupts
-	inl(devpriv->iobase + APCI1032_DIGITAL_IP_INTERRUPT_STATUS);	//Reset the interrupt status register
-	outl(0x0, devpriv->iobase + APCI1032_DIGITAL_IP_INTERRUPT_MODE1);	//Disable the and/or interrupt
+	outl(0x0, devpriv->iobase + APCI1032_DIGITAL_IP_IRQ);	/* disable the interrupts */
+	inl(devpriv->iobase + APCI1032_DIGITAL_IP_INTERRUPT_STATUS);	/* Reset the interrupt status register */
+	outl(0x0, devpriv->iobase + APCI1032_DIGITAL_IP_INTERRUPT_MODE1);	/* Disable the and/or interrupt */
 	outl(0x0, devpriv->iobase + APCI1032_DIGITAL_IP_INTERRUPT_MODE2);
 	return 0;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1032.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1032.h
index 659ef85..e29a72a 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1032.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1032.h
@@ -19,45 +19,46 @@
 
 #define APCI1032_BOARD_VENDOR_ID 0x15B8
 #define APCI1032_ADDRESS_RANGE  20
-//DIGITAL INPUT DEFINE
+/* DIGITAL INPUT DEFINE */
 
 #define APCI1032_DIGITAL_IP                     0
 #define APCI1032_DIGITAL_IP_INTERRUPT_MODE1     4
 #define APCI1032_DIGITAL_IP_INTERRUPT_MODE2     8
 #define APCI1032_DIGITAL_IP_IRQ                 16
 
-//Digital Input IRQ Function Selection
+/* Digital Input IRQ Function Selection */
 #define ADDIDATA_OR                  0
 #define ADDIDATA_AND                 1
 
-//Digital Input Interrupt Status
+/* Digital Input Interrupt Status */
 #define APCI1032_DIGITAL_IP_INTERRUPT_STATUS    12
 
-//Digital Input Interrupt Enable Disable.
+/* Digital Input Interrupt Enable Disable. */
 #define APCI1032_DIGITAL_IP_INTERRUPT_ENABLE    0x4
 #define APCI1032_DIGITAL_IP_INTERRUPT_DISABLE   0xFFFFFFFB
 
-//ADDIDATA Enable Disable
+/* ADDIDATA Enable Disable */
 
 #define ADDIDATA_ENABLE                            1
 #define ADDIDATA_DISABLE                           0
 
-// Hardware Layer  functions for Apci1032
+/* Hardware Layer  functions for Apci1032 */
 
-//DI
-// for di read
+/*
+* DI for di read
+*/
 
-INT i_APCI1032_ConfigDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1032_ConfigDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				  struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1032_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1032_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
 
-INT i_APCI1032_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1032_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				    struct comedi_insn *insn, unsigned int *data);
 
-// Interrupt functions.....
+/* Interrupt functions..... */
 
 static void v_APCI1032_Interrupt(int irq, void *d);
-//Reset
-INT i_APCI1032_Reset(struct comedi_device *dev);
+/* Reset */
+int i_APCI1032_Reset(struct comedi_device *dev);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1500.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1500.c
index 2d6adcf..236b8a3 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1500.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1500.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -77,7 +77,7 @@
 |			  data[0]            :Number of the input port on        |
 |                                         which the event will take place    |
 |                                         (1 or 2)
-                      data[1]            : The event logic for port 1 has    |
+|                      data[1]            : The event logic for port 1 has    |
 |                                            three possibilities             |
 |                                        :0  APCI1500_AND       :This logic  |
 |                                                                links       |
@@ -137,8 +137,8 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1500_ConfigDigitalInputEvent(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1500_ConfigDigitalInputEvent(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int i_PatternPolarity = 0, i_PatternTransition = 0, i_PatternMask = 0;
 	int i_MaxChannel = 0, i_Count = 0, i_EventMask = 0;
@@ -157,16 +157,16 @@
 
 	if (data[0] == 1) {
 		i_MaxChannel = 8;
-	}			// if (data[0] == 1)
+	}			/*  if (data[0] == 1) */
 	else {
 		if (data[0] == 2) {
 			i_MaxChannel = 6;
-		}		// if(data[0]==2)
+		}		/*  if(data[0]==2) */
 		else {
 			printk("\nThe specified port event  does not exist\n");
 			return -EINVAL;
-		}		//else if(data[0]==2)
-	}			//else  if (data[0] == 1)
+		}		/* else if(data[0]==2) */
+	}			/* else  if (data[0] == 1) */
 	switch (data[1]) {
 	case 0:
 		data[1] = APCI1500_AND;
@@ -180,7 +180,7 @@
 	default:
 		printk("\nThe specified interrupt logic does not exist\n");
 		return -EINVAL;
-	}			//switch(data[1]);
+	}			/* switch(data[1]); */
 
 	i_Logic = data[1];
 	for (i_Count = i_MaxChannel, i = 0; i_Count > 0; i_Count--, i++) {
@@ -224,8 +224,8 @@
 		default:
 			printk("\nThe option indicated in the event mask does not exist\n");
 			return -EINVAL;
-		}		// switch(i_EventMask)
-	}			//for (i_Count = i_MaxChannel; i_Count >0;i_Count --)
+		}		/*  switch(i_EventMask) */
+	}			/* for (i_Count = i_MaxChannel; i_Count >0;i_Count --) */
 
 	if (data[0] == 1) {
 		    /****************************/
@@ -247,7 +247,7 @@
 			      /********************************************/
 				printk("\nTransition error on an OR PRIORITY logic\n");
 				return -EINVAL;
-			}	// if (data[1]== APCI1500_OR_PRIORITY && i_PatternTransition != 0)
+			}	/*  if (data[1]== APCI1500_OR_PRIORITY && i_PatternTransition != 0) */
 
 		       /*************************************/
 			/* Tests if more than one transition */
@@ -261,7 +261,7 @@
 						((i_PatternTransition >>
 							i_Count) & 0x1);
 
-				}	//for (i_Count = 0; i_Count < 8; i_Count++)
+				}	/* for (i_Count = 0; i_Count < 8; i_Count++) */
 
 				if (i_PatternTransitionCount > 1) {
 				  /****************************************/
@@ -269,8 +269,8 @@
 				  /****************************************/
 					printk("\n Transition error on an AND logic\n");
 					return -EINVAL;
-				}	// if (i_PatternTransitionCount > 1)
-			}	// if (data[1]== APCI1500_AND)
+				}	/*  if (i_PatternTransitionCount > 1) */
+			}	/*  if (data[1]== APCI1500_AND) */
 
 			    /*****************************************************************/
 			/* Selects the APCI1500_RW_MASTER_CONFIGURATION_CONTROL register */
@@ -359,12 +359,12 @@
 				devpriv->iobase +
 				APCI1500_Z8536_CONTROL_REGISTER);
 
-		}		// if(data[1]==APCI1500_AND||data[1]==APCI1500_OR||data[1]==APCI1500_OR_PRIORITY)
+		}		/*  if(data[1]==APCI1500_AND||data[1]==APCI1500_OR||data[1]==APCI1500_OR_PRIORITY) */
 		else {
 			printk("\nThe choice for interrupt logic does not exist\n");
 			return -EINVAL;
-		}		// else }// if(data[1]==APCI1500_AND||data[1]==APCI1500_OR||data[1]==APCI1500_OR_PRIORITY)
-	}			//   if (data[0]== 1)
+		}		/*  else }// if(data[1]==APCI1500_AND||data[1]==APCI1500_OR||data[1]==APCI1500_OR_PRIORITY) */
+	}			/*    if (data[0]== 1) */
 
 		 /************************************/
 	/* Test if event setting for port 2 */
@@ -487,12 +487,12 @@
 			outb(0xF4,
 				devpriv->iobase +
 				APCI1500_Z8536_CONTROL_REGISTER);
-		}		//  if (data[1] == APCI1500_OR)
+		}		/*   if (data[1] == APCI1500_OR) */
 		else {
 			printk("\nThe choice for interrupt logic does not exist\n");
 			return -EINVAL;
-		}		//elseif (data[1] == APCI1500_OR)
-	}			//if(data[0]==2)
+		}		/* elseif (data[1] == APCI1500_OR) */
+	}			/* if(data[0]==2) */
 
 	return insn->n;
 }
@@ -506,11 +506,11 @@
 | Task              :  Allows or disallows a port event                      |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|		              UINT ui_Channel : Channel number to read       |
+|		              unsigned int ui_Channel : Channel number to read       |
 |                     unsigned int *data          : Data Pointer to read status  |
-                      data[0]                 :0 Start input event
-                                               1 Stop input event
-                      data[1]                 :No of port (1 or 2)
+|                      data[0]                 :0 Start input event
+|                                               1 Stop input event
+|                      data[1]                 :No of port (1 or 2)
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -519,8 +519,8 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI1500_StartStopInputEvent(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1500_StartStopInputEvent(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i_Event1InterruptStatus = 0, i_Event2InterruptStatus =
 		0, i_RegValue;
@@ -589,12 +589,12 @@
 						devpriv->iobase +
 						APCI1500_Z8536_CONTROL_REGISTER);
 
-				}	// if(i_Event1Status==1)
+				}	/*  if(i_Event1Status==1) */
 				else {
 					printk("\nEvent 1 not initialised\n");
 					return -EINVAL;
-				}	//else if(i_Event1Status==1)
-			}	//if (data[1]==1)
+				}	/* else if(i_Event1Status==1) */
+			}	/* if (data[1]==1) */
 			if (data[1] == 2) {
 
 				if (i_Event2Status == 1) {
@@ -640,17 +640,17 @@
 						devpriv->iobase +
 						APCI1500_Z8536_CONTROL_REGISTER);
 					i_Event2InterruptStatus = 1;
-				}	// if(i_Event2Status==1)
+				}	/*  if(i_Event2Status==1) */
 				else {
 					printk("\nEvent 2 not initialised\n");
 					return -EINVAL;
-				}	//else if(i_Event2Status==1)
-			}	// if(data[1]==2)
-		}		// if (data[1] == 1 || data[0] == 2)
+				}	/* else if(i_Event2Status==1) */
+			}	/*  if(data[1]==2) */
+		}		/*  if (data[1] == 1 || data[0] == 2) */
 		else {
 			printk("\nThe port parameter is in error\n");
 			return -EINVAL;
-		}		//else if (data[1] == 1 || data[0] == 2)
+		}		/* else if (data[1] == 1 || data[0] == 2) */
 
 		break;
 
@@ -701,12 +701,12 @@
 						devpriv->iobase +
 						APCI1500_Z8536_CONTROL_REGISTER);
 					i_Event1InterruptStatus = 0;
-				}	// if(i_Event1Status==1)
+				}	/*  if(i_Event1Status==1) */
 				else {
 					printk("\nEvent 1 not initialised\n");
 					return -EINVAL;
-				}	//else if(i_Event1Status==1)
-			}	//if (data[1]==1)
+				}	/* else if(i_Event1Status==1) */
+			}	/* if (data[1]==1) */
 			if (data[1] == 2) {
 			 /*****************************/
 				/* Test if event initialised */
@@ -744,23 +744,23 @@
 						devpriv->iobase +
 						APCI1500_Z8536_CONTROL_REGISTER);
 					i_Event2InterruptStatus = 0;
-				}	// if(i_Event2Status==1)
+				}	/*  if(i_Event2Status==1) */
 				else {
 					printk("\nEvent 2 not initialised\n");
 					return -EINVAL;
-				}	//else if(i_Event2Status==1)
-			}	//if(data[1]==2)
+				}	/* else if(i_Event2Status==1) */
+			}	/* if(data[1]==2) */
 
-		}		// if (data[1] == 1 || data[1] == 2)
+		}		/*  if (data[1] == 1 || data[1] == 2) */
 		else {
 			printk("\nThe port parameter is in error\n");
 			return -EINVAL;
-		}		//else if (data[1] == 1 || data[1] == 2)
+		}		/* else if (data[1] == 1 || data[1] == 2) */
 		break;
 	default:
 		printk("\nThe option of START/STOP logic does not exist\n");
 		return -EINVAL;
-	}			//switch(data[0])
+	}			/* switch(data[0]) */
 
 	return insn->n;
 }
@@ -774,7 +774,7 @@
 | Task              : Return the status of the digital input                 |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|		              UINT ui_Channel : Channel number to read       |
+|		              unsigned int ui_Channel : Channel number to read       |
 |                     unsigned int *data          : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -784,8 +784,8 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1500_Initialisation(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1500_Initialisation(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i_DummyRead = 0;
     /******************/
@@ -943,11 +943,11 @@
 | Task              : Return the status of the Requested digital inputs      |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To be Read    |
-|                      UINT *data             : Data Pointer
-                      data[0]                 : 0 Read a single channel
-                                                1 read a port value
-                      data[1]                 : port value
+|                     unsigned int ui_NoOfChannels    : No Of Channels To be Read    |
+|                      unsigned int *data             : Data Pointer
+|                      data[0]                 : 0 Read a single channel
+|                                                1 read a port value
+|                      data[1]                 : port value
 +----------------------------------------------------------------------------+
 | Output Parameters :	--	data[0]    :The read status value
 +----------------------------------------------------------------------------+
@@ -957,31 +957,31 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1500_ReadMoreDigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1500_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_PortValue = data[1];
-	UINT ui_Mask = 0;
-	UINT ui_Channel;
-	UINT ui_TmpValue = 0;
+	unsigned int ui_PortValue = data[1];
+	unsigned int ui_Mask = 0;
+	unsigned int ui_Channel;
+	unsigned int ui_TmpValue = 0;
 	ui_Channel = CR_CHAN(insn->chanspec);
 
 	switch (data[0]) {
 	case 0:
 		if (ui_Channel >= 0 && ui_Channel <= 15) {
 			ui_TmpValue =
-				(UINT) inw(devpriv->i_IobaseAddon +
+				(unsigned int) inw(devpriv->i_IobaseAddon +
 				APCI1500_DIGITAL_IP);
 			*data = (ui_TmpValue >> ui_Channel) & 0x1;
-		}		//if(ui_Channel >= 0 && ui_Channel <=15)
+		}		/* if(ui_Channel >= 0 && ui_Channel <=15) */
 		else {
 			printk("\nThe channel specification are in error\n");
-			return -EINVAL;	// "sorry channel spec wrong "
-		}		//else if(ui_Channel >= 0 && ui_Channel <=15)
+			return -EINVAL;	/*  "sorry channel spec wrong " */
+		}		/* else if(ui_Channel >= 0 && ui_Channel <=15) */
 		break;
 	case 1:
 
-		*data = (UINT) inw(devpriv->i_IobaseAddon +
+		*data = (unsigned int) inw(devpriv->i_IobaseAddon +
 			APCI1500_DIGITAL_IP);
 		switch (ui_Channel) {
 		case 2:
@@ -1001,35 +1001,35 @@
 
 		default:
 			printk("\nSpecified channel cannot be read \n");
-			return -EINVAL;	// "sorry channel spec wrong "
+			return -EINVAL;	/*  "sorry channel spec wrong " */
 			break;
-		}		//switch(ui_Channel)
+		}		/* switch(ui_Channel) */
 		break;
 	default:
 		printk("\nThe specified functionality does not exist\n");
 		return -EINVAL;
-	}			//switch(data[0])
+	}			/* switch(data[0]) */
 	return insn->n;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI1500_ConfigDigitalOutputErrorInterrupt
-                      (struct comedi_device *dev,struct comedi_subdevice *s struct comedi_insn
-                      *insn,unsigned int *data)                                  |
+|                      (struct comedi_device *dev,struct comedi_subdevice *s struct comedi_insn
+|                      *insn,unsigned int *data)                                  |
 |				                                                     |
 +----------------------------------------------------------------------------+
 | Task              : Configures the digital output memory and the digital
-                      output error interrupt                                 |
+|                      output error interrupt                                 |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
 |                     unsigned int *data         : Data Pointer contains         |
 |                                          configuration parameters as below |
 |                      struct comedi_subdevice *s,   :pointer to subdevice structure
-                       struct comedi_insn *insn      :pointer to insn structure                                                                                                                |
+|                       struct comedi_insn *insn      :pointer to insn structure                                                                                                                |
 |					  data[0]  :1:Memory on                          |
 |					            0:Memory off                         |
-                              data[1]  :1 Enable the voltage error interrupt
+|                              data[1]  :1 Enable the voltage error interrupt
 |							   :0 Disable the voltage error interrupt 		                                                                                                    |
 |																	 |
 +----------------------------------------------------------------------------+
@@ -1040,8 +1040,8 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI1500_ConfigDigitalOutputErrorInterrupt(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1500_ConfigDigitalOutputErrorInterrupt(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	devpriv->b_OutputMemoryStatus = data[0];
 	return insn->n;
@@ -1056,8 +1056,8 @@
 | Task              : Writes port value  To the selected port                |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To Write      |
-|                     UINT *data              : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To Write      |
+|                     unsigned int *data              : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -1067,24 +1067,24 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1500_WriteDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1500_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	static UINT ui_Temp = 0;
-	UINT ui_Temp1;
+	static unsigned int ui_Temp = 0;
+	unsigned int ui_Temp1;
 
-	UINT ui_NoOfChannel = CR_CHAN(insn->chanspec);	// get the channel
+	unsigned int ui_NoOfChannel = CR_CHAN(insn->chanspec);	/*  get the channel */
 
 	if (!devpriv->b_OutputMemoryStatus) {
 		ui_Temp = 0;
 
-	}			//if(!devpriv->b_OutputMemoryStatus )
+	}			/* if(!devpriv->b_OutputMemoryStatus ) */
 	if (data[3] == 0) {
 		if (data[1] == 0) {
 			data[0] = (data[0] << ui_NoOfChannel) | ui_Temp;
 			outw(data[0],
 				devpriv->i_IobaseAddon + APCI1500_DIGITAL_OP);
-		}		//if(data[1]==0)
+		}		/* if(data[1]==0) */
 		else {
 			if (data[1] == 1) {
 				switch (ui_NoOfChannel) {
@@ -1113,19 +1113,19 @@
 
 				default:
 					comedi_error(dev, " chan spec wrong");
-					return -EINVAL;	// "sorry channel spec wrong "
+					return -EINVAL;	/*  "sorry channel spec wrong " */
 
-				}	//switch(ui_NoOfChannels)
+				}	/* switch(ui_NoOfChannels) */
 
 				outw(data[0],
 					devpriv->i_IobaseAddon +
 					APCI1500_DIGITAL_OP);
-			}	// if(data[1]==1)
+			}	/*  if(data[1]==1) */
 			else {
 				printk("\nSpecified channel not supported\n");
-			}	//else if(data[1]==1)
-		}		//elseif(data[1]==0)
-	}			//if(data[3]==0)
+			}	/* else if(data[1]==1) */
+		}		/* elseif(data[1]==0) */
+	}			/* if(data[3]==0) */
 	else {
 		if (data[3] == 1) {
 			if (data[1] == 0) {
@@ -1140,7 +1140,7 @@
 				outw(data[0],
 					devpriv->i_IobaseAddon +
 					APCI1500_DIGITAL_OP);
-			}	//if(data[1]==0)
+			}	/* if(data[1]==0) */
 			else {
 				if (data[1] == 1) {
 					switch (ui_NoOfChannel) {
@@ -1190,48 +1190,48 @@
 					default:
 						comedi_error(dev,
 							" chan spec wrong");
-						return -EINVAL;	// "sorry channel spec wrong "
+						return -EINVAL;	/*  "sorry channel spec wrong " */
 
-					}	//switch(ui_NoOfChannels)
+					}	/* switch(ui_NoOfChannels) */
 
 					outw(data[0],
 						devpriv->i_IobaseAddon +
 						APCI1500_DIGITAL_OP);
-				}	// if(data[1]==1)
+				}	/*  if(data[1]==1) */
 				else {
 					printk("\nSpecified channel not supported\n");
-				}	//else if(data[1]==1)
-			}	//elseif(data[1]==0)
-		}		//if(data[3]==1);
+				}	/* else if(data[1]==1) */
+			}	/* elseif(data[1]==0) */
+		}		/* if(data[3]==1); */
 		else {
 			printk("\nSpecified functionality does not exist\n");
 			return -EINVAL;
-		}		//if else data[3]==1)
-	}			//if else data[3]==0)
+		}		/* if else data[3]==1) */
+	}			/* if else data[3]==0) */
 	ui_Temp = data[0];
-	return (insn->n);;
+	return insn->n;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI1500_ConfigCounterTimerWatchdog(comedi_device
-                   *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)|
+|                   *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)|
 |				                                                     |
 +----------------------------------------------------------------------------+
 | Task              : Configures The Watchdog                                |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                      struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data         : Data Pointer to read status                                                       data[0]                : 2     APCI1500_1_8_KHZ
 |                                              1     APCI1500_3_6_KHZ        |
 |                                              0     APCI1500_115_KHZ
-                      data[1]                : 0     Counter1/Timer1
-                                               1     Counter2/Timer2
-                                               2     Counter3/Watchdog
-                      data[2]                : 0     Counter
-                                               1     Timer/Watchdog
-                      data[3]                :         This parameter has    |
+|                      data[1]                : 0     Counter1/Timer1
+|                                               1     Counter2/Timer2
+|                                               2     Counter3/Watchdog
+|                      data[2]                : 0     Counter
+|                                               1     Timer/Watchdog
+|                      data[3]                :         This parameter has    |
 |                                                      two meanings.         |
 |                                                    - If the counter/timer  |
 |                                                      is used as a counter  |
@@ -1243,15 +1243,15 @@
 |                                                      the divider factor    |
 |                                                      for the output is     |
 |                                                      given.
-                       data[4]                 : 0    APCI1500_CONTINUOUS
-                                                 1    APCI1500_SINGLE
-                       data[5]                 : 0    Software Trigger
-                                                 1    Hardware Trigger
-
-                       data[6]                  :0    Software gate
-                                                 1    Hardware gate
-                       data[7]                  :0    Interrupt Disable
-                                                 1    Interrupt Enable
+|                       data[4]                 : 0    APCI1500_CONTINUOUS
+|                                                 1    APCI1500_SINGLE
+|                       data[5]                 : 0    Software Trigger
+|                                                 1    Hardware Trigger
+|
+|                       data[6]                  :0    Software gate
+|                                                 1    Hardware gate
+|                       data[7]                  :0    Interrupt Disable
+|                                                 1    Interrupt Enable
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -1261,27 +1261,27 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI1500_ConfigCounterTimerWatchdog(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1500_ConfigCounterTimerWatchdog(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int i_TimerCounterMode, i_MasterConfiguration;
 
 	devpriv->tsk_Current = current;
 
-//Selection of the input clock
+/* Selection of the input clock */
 	if (data[0] == 0 || data[0] == 1 || data[0] == 2) {
 		outw(data[0], devpriv->i_IobaseAddon + APCI1500_CLK_SELECT);
-	}			// if(data[0]==0||data[0]==1||data[0]==2)
+	}			/*  if(data[0]==0||data[0]==1||data[0]==2) */
 	else {
 		if (data[0] != 3) {
 			printk("\nThe option for input clock selection does not exist\n");
 			return -EINVAL;
-		}		// if(data[0]!=3)
-	}			//elseif(data[0]==0||data[0]==1||data[0]==2)
-	//Select the counter/timer
+		}		/*  if(data[0]!=3) */
+	}			/* elseif(data[0]==0||data[0]==1||data[0]==2) */
+	/* Select the counter/timer */
 	switch (data[1]) {
 	case COUNTER1:
-		//selecting counter or timer
+		/* selecting counter or timer */
 		switch (data[2]) {
 		case 0:
 			data[2] = APCI1500_COUNTER;
@@ -1292,9 +1292,9 @@
 		default:
 			printk("\nThis choice is not a timer nor a counter\n");
 			return -EINVAL;
-		}		// switch(data[2])
+		}		/*  switch(data[2]) */
 
-		//Selecting  single or continuous mode
+		/* Selecting  single or continuous mode */
 		switch (data[4]) {
 		case 0:
 			data[4] = APCI1500_CONTINUOUS;
@@ -1305,7 +1305,7 @@
 		default:
 			printk("\nThis option for single/continuous mode does not exist\n");
 			return -EINVAL;
-		}		// switch(data[4])
+		}		/*  switch(data[4]) */
 
 		i_TimerCounterMode = data[2] | data[4] | 7;
 			 /*************************/
@@ -1428,21 +1428,21 @@
 				outb(0x2,
 					devpriv->iobase +
 					APCI1500_Z8536_CONTROL_REGISTER);
-			}	//if(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE)
+			}	/* if(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
 			else {
 				printk("\nError in selection of interrupt enable or disable\n");
 				return -EINVAL;
-			}	//elseif(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE)
-		}		// if ((data[3]>= 0) && (data[3] <= 65535))
+			}	/* elseif(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
+		}		/*  if ((data[3]>= 0) && (data[3] <= 65535)) */
 		else {
 			printk("\nError in selection of reload value\n");
 			return -EINVAL;
-		}		//else if ((data[3]>= 0) && (data[3] <= 65535))
+		}		/* else if ((data[3]>= 0) && (data[3] <= 65535)) */
 		i_TimerCounterWatchdogInterrupt = data[7];
 		i_TimerCounter1Init = 1;
 		break;
 
-	case COUNTER2:		//selecting counter or timer
+	case COUNTER2:		/* selecting counter or timer */
 		switch (data[2]) {
 		case 0:
 			data[2] = APCI1500_COUNTER;
@@ -1453,9 +1453,9 @@
 		default:
 			printk("\nThis choice is not a timer nor a counter\n");
 			return -EINVAL;
-		}		// switch(data[2])
+		}		/*  switch(data[2]) */
 
-		//Selecting  single or continuous mode
+		/* Selecting  single or continuous mode */
 		switch (data[4]) {
 		case 0:
 			data[4] = APCI1500_CONTINUOUS;
@@ -1466,9 +1466,9 @@
 		default:
 			printk("\nThis option for single/continuous mode does not exist\n");
 			return -EINVAL;
-		}		// switch(data[4])
+		}		/*  switch(data[4]) */
 
-		//Selecting  software or hardware trigger
+		/* Selecting  software or hardware trigger */
 		switch (data[5]) {
 		case 0:
 			data[5] = APCI1500_SOFTWARE_TRIGGER;
@@ -1479,9 +1479,9 @@
 		default:
 			printk("\nThis choice for software or hardware trigger does not exist\n");
 			return -EINVAL;
-		}		// switch(data[5])
+		}		/*  switch(data[5]) */
 
-		//Selecting  software or hardware gate
+		/* Selecting  software or hardware gate */
 		switch (data[6]) {
 		case 0:
 			data[6] = APCI1500_SOFTWARE_GATE;
@@ -1492,7 +1492,7 @@
 		default:
 			printk("\nThis choice for software or hardware gate does not exist\n");
 			return -EINVAL;
-		}		// switch(data[6])
+		}		/*  switch(data[6]) */
 
 		i_TimerCounterMode = data[2] | data[4] | data[5] | data[6] | 7;
 
@@ -1616,21 +1616,21 @@
 				outb(0x2,
 					devpriv->iobase +
 					APCI1500_Z8536_CONTROL_REGISTER);
-			}	//if(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE)
+			}	/* if(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
 			else {
 				printk("\nError in selection of interrupt enable or disable\n");
 				return -EINVAL;
-			}	//elseif(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE)
-		}		// if ((data[3]>= 0) && (data[3] <= 65535))
+			}	/* elseif(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
+		}		/*  if ((data[3]>= 0) && (data[3] <= 65535)) */
 		else {
 			printk("\nError in selection of reload value\n");
 			return -EINVAL;
-		}		//else if ((data[3]>= 0) && (data[3] <= 65535))
+		}		/* else if ((data[3]>= 0) && (data[3] <= 65535)) */
 		i_TimerCounterWatchdogInterrupt = data[7];
 		i_TimerCounter2Init = 1;
 		break;
 
-	case COUNTER3:		//selecting counter or watchdog
+	case COUNTER3:		/* selecting counter or watchdog */
 		switch (data[2]) {
 		case 0:
 			data[2] = APCI1500_COUNTER;
@@ -1641,9 +1641,9 @@
 		default:
 			printk("\nThis choice is not a watchdog nor a counter\n");
 			return -EINVAL;
-		}		// switch(data[2])
+		}		/*  switch(data[2]) */
 
-		//Selecting  single or continuous mode
+		/* Selecting  single or continuous mode */
 		switch (data[4]) {
 		case 0:
 			data[4] = APCI1500_CONTINUOUS;
@@ -1654,9 +1654,9 @@
 		default:
 			printk("\nThis option for single/continuous mode does not exist\n");
 			return -EINVAL;
-		}		// switch(data[4])
+		}		/*  switch(data[4]) */
 
-		//Selecting  software or hardware gate
+		/* Selecting  software or hardware gate */
 		switch (data[6]) {
 		case 0:
 			data[6] = APCI1500_SOFTWARE_GATE;
@@ -1667,7 +1667,7 @@
 		default:
 			printk("\nThis choice for software or hardware gate does not exist\n");
 			return -EINVAL;
-		}		// switch(data[6])
+		}		/*  switch(data[6]) */
 
 		      /*****************************/
 		/* Test if used for watchdog */
@@ -1680,10 +1680,10 @@
 			/* - Pulses output           */
 			     /*****************************/
 			i_TimerCounterMode = data[2] | data[4] | 0x54;
-		}		//if (data[2] == APCI1500_WATCHDOG)
+		}		/* if (data[2] == APCI1500_WATCHDOG) */
 		else {
 			i_TimerCounterMode = data[2] | data[4] | data[6] | 7;
-		}		//elseif (data[2] == APCI1500_WATCHDOG)
+		}		/* elseif (data[2] == APCI1500_WATCHDOG) */
 				 /*************************/
 		/* Test the reload value */
 			     /*************************/
@@ -1809,25 +1809,25 @@
 						devpriv->iobase +
 						APCI1500_Z8536_CONTROL_REGISTER);
 
-				}	//elseif(data[2]==APCI1500_COUNTER)
+				}	/* elseif(data[2]==APCI1500_COUNTER) */
 
-			}	//if(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE)
+			}	/* if(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
 			else {
 				printk("\nError in selection of interrupt enable or disable\n");
 				return -EINVAL;
-			}	//elseif(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE)
-		}		// if ((data[3]>= 0) && (data[3] <= 65535))
+			}	/* elseif(data[7]== APCI1500_ENABLE ||data[7]== APCI1500_DISABLE) */
+		}		/*  if ((data[3]>= 0) && (data[3] <= 65535)) */
 		else {
 			printk("\nError in selection of reload value\n");
 			return -EINVAL;
-		}		//else if ((data[3]>= 0) && (data[3] <= 65535))
+		}		/* else if ((data[3]>= 0) && (data[3] <= 65535)) */
 		i_TimerCounterWatchdogInterrupt = data[7];
 		i_WatchdogCounter3Init = 1;
 		break;
 
 	default:
 		printk("\nThe specified counter\timer option does not exist\n");
-	}			//switch(data[1])
+	}			/* switch(data[1]) */
 	i_CounterLogic = data[2];
 	return insn->n;
 }
@@ -1836,22 +1836,22 @@
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI1500_StartStopTriggerTimerCounterWatchdog      |
 |				(struct comedi_device *dev,struct comedi_subdevice *s,
-                         struct comedi_insn *insn,unsigned int *data);                  |
+|                         struct comedi_insn *insn,unsigned int *data);                  |
 +----------------------------------------------------------------------------+
 | Task              : Start / Stop or trigger the timer counter or Watchdog  |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev     : Driver handle                 |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                      struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data         : Data Pointer to read status   |
-                      data[0]                : 0     Counter1/Timer1
-                                               1     Counter2/Timer2
-                                               2     Counter3/Watchdog
-                      data[1]                : 0     start
-                                               1     stop
-                                               2     Trigger
-                      data[2]                : 0     Counter
-                                               1     Timer/Watchdog
+|                      data[0]                : 0     Counter1/Timer1
+|                                               1     Counter2/Timer2
+|                                               2     Counter3/Watchdog
+|                      data[1]                : 0     start
+|                                               1     stop
+|                                               2     Trigger
+|                      data[2]                : 0     Counter
+|                                               1     Timer/Watchdog
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -1860,8 +1860,8 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI1500_StartStopTriggerTimerCounterWatchdog(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1500_StartStopTriggerTimerCounterWatchdog(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int i_CommandAndStatusValue;
 
@@ -1871,11 +1871,11 @@
 		case START:
 			if (i_TimerCounter1Init == 1) {
 				if (i_TimerCounterWatchdogInterrupt == 1) {
-					i_CommandAndStatusValue = 0xC4;	//Enable the interrupt
-				}	// if(i_TimerCounterWatchdogInterrupt==1)
+					i_CommandAndStatusValue = 0xC4;	/* Enable the interrupt */
+				}	/*  if(i_TimerCounterWatchdogInterrupt==1) */
 				else {
-					i_CommandAndStatusValue = 0xE4;	//disable the interrupt
-				}	//elseif(i_TimerCounterWatchdogInterrupt==1)
+					i_CommandAndStatusValue = 0xE4;	/* disable the interrupt */
+				}	/* elseif(i_TimerCounterWatchdogInterrupt==1) */
 					      /**************************/
 				/* Starts timer/counter 1 */
 					      /**************************/
@@ -1889,7 +1889,7 @@
 				outb(i_CommandAndStatusValue,
 					devpriv->iobase +
 					APCI1500_Z8536_CONTROL_REGISTER);
-			}	//if( i_TimerCounter1Init==1)
+			}	/* if( i_TimerCounter1Init==1) */
 			else {
 				printk("\nCounter/Timer1 not configured\n");
 				return -EINVAL;
@@ -1922,14 +1922,14 @@
 						 /************************/
 
 					i_CommandAndStatusValue = 0x6;
-				}	//if( i_TimerCounter1Enabled==1)
+				}	/* if( i_TimerCounter1Enabled==1) */
 				else {
 						   /***************/
 					/* Set Trigger */
 						   /***************/
 
 					i_CommandAndStatusValue = 0x2;
-				}	//elseif(i_TimerCounter1Enabled==1)
+				}	/* elseif(i_TimerCounter1Enabled==1) */
 
 						/********************************************/
 				/* Selects the commands and status register */
@@ -1940,7 +1940,7 @@
 				outb(i_CommandAndStatusValue,
 					devpriv->iobase +
 					APCI1500_Z8536_CONTROL_REGISTER);
-			}	//if( i_TimerCounter1Init==1)
+			}	/* if( i_TimerCounter1Init==1) */
 			else {
 				printk("\nCounter/Timer1 not configured\n");
 				return -EINVAL;
@@ -1950,7 +1950,7 @@
 		default:
 			printk("\nThe specified option for start/stop/trigger does not exist\n");
 			return -EINVAL;
-		}		//switch(data[1])
+		}		/* switch(data[1]) */
 		break;
 
 	case COUNTER2:
@@ -1958,11 +1958,11 @@
 		case START:
 			if (i_TimerCounter2Init == 1) {
 				if (i_TimerCounterWatchdogInterrupt == 1) {
-					i_CommandAndStatusValue = 0xC4;	//Enable the interrupt
-				}	// if(i_TimerCounterWatchdogInterrupt==1)
+					i_CommandAndStatusValue = 0xC4;	/* Enable the interrupt */
+				}	/*  if(i_TimerCounterWatchdogInterrupt==1) */
 				else {
-					i_CommandAndStatusValue = 0xE4;	//disable the interrupt
-				}	//elseif(i_TimerCounterWatchdogInterrupt==1)
+					i_CommandAndStatusValue = 0xE4;	/* disable the interrupt */
+				}	/* elseif(i_TimerCounterWatchdogInterrupt==1) */
 					      /**************************/
 				/* Starts timer/counter 2 */
 					      /**************************/
@@ -1976,7 +1976,7 @@
 				outb(i_CommandAndStatusValue,
 					devpriv->iobase +
 					APCI1500_Z8536_CONTROL_REGISTER);
-			}	//if( i_TimerCounter2Init==1)
+			}	/* if( i_TimerCounter2Init==1) */
 			else {
 				printk("\nCounter/Timer2 not configured\n");
 				return -EINVAL;
@@ -2008,14 +2008,14 @@
 						 /************************/
 
 					i_CommandAndStatusValue = 0x6;
-				}	//if( i_TimerCounter2Enabled==1)
+				}	/* if( i_TimerCounter2Enabled==1) */
 				else {
 						   /***************/
 					/* Set Trigger */
 						   /***************/
 
 					i_CommandAndStatusValue = 0x2;
-				}	//elseif(i_TimerCounter2Enabled==1)
+				}	/* elseif(i_TimerCounter2Enabled==1) */
 
 						/********************************************/
 				/* Selects the commands and status register */
@@ -2026,7 +2026,7 @@
 				outb(i_CommandAndStatusValue,
 					devpriv->iobase +
 					APCI1500_Z8536_CONTROL_REGISTER);
-			}	//if( i_TimerCounter2Init==1)
+			}	/* if( i_TimerCounter2Init==1) */
 			else {
 				printk("\nCounter/Timer2 not configured\n");
 				return -EINVAL;
@@ -2035,7 +2035,7 @@
 		default:
 			printk("\nThe specified option for start/stop/trigger does not exist\n");
 			return -EINVAL;
-		}		//switch(data[1])
+		}		/* switch(data[1]) */
 		break;
 	case COUNTER3:
 		switch (data[1]) {
@@ -2043,11 +2043,11 @@
 			if (i_WatchdogCounter3Init == 1) {
 
 				if (i_TimerCounterWatchdogInterrupt == 1) {
-					i_CommandAndStatusValue = 0xC4;	//Enable the interrupt
-				}	// if(i_TimerCounterWatchdogInterrupt==1)
+					i_CommandAndStatusValue = 0xC4;	/* Enable the interrupt */
+				}	/*  if(i_TimerCounterWatchdogInterrupt==1) */
 				else {
-					i_CommandAndStatusValue = 0xE4;	//disable the interrupt
-				}	//elseif(i_TimerCounterWatchdogInterrupt==1)
+					i_CommandAndStatusValue = 0xE4;	/* disable the interrupt */
+				}	/* elseif(i_TimerCounterWatchdogInterrupt==1) */
 					      /**************************/
 				/* Starts Watchdog/counter 3 */
 					      /**************************/
@@ -2062,7 +2062,7 @@
 					devpriv->iobase +
 					APCI1500_Z8536_CONTROL_REGISTER);
 
-			}	// if( i_WatchdogCounter3init==1)
+			}	/*  if( i_WatchdogCounter3init==1) */
 			else {
 				printk("\nWatchdog/Counter3 not configured\n");
 				return -EINVAL;
@@ -2089,7 +2089,7 @@
 
 		case TRIGGER:
 			switch (data[2]) {
-			case 0:	//triggering counter 3
+			case 0:	/* triggering counter 3 */
 				if (i_WatchdogCounter3Init == 1) {
 					if (i_WatchdogCounter3Enabled == 1) {
 							       /************************/
@@ -2097,14 +2097,14 @@
 							       /************************/
 
 						i_CommandAndStatusValue = 0x6;
-					}	//if( i_WatchdogCounter3Enabled==1)
+					}	/* if( i_WatchdogCounter3Enabled==1) */
 					else {
 							   /***************/
 						/* Set Trigger */
 							   /***************/
 
 						i_CommandAndStatusValue = 0x2;
-					}	//elseif(i_WatchdogCounter3Enabled==1)
+					}	/* elseif(i_WatchdogCounter3Enabled==1) */
 
 						/********************************************/
 					/* Selects the commands and status register */
@@ -2115,14 +2115,14 @@
 					outb(i_CommandAndStatusValue,
 						devpriv->iobase +
 						APCI1500_Z8536_CONTROL_REGISTER);
-				}	//if( i_WatchdogCounter3Init==1)
+				}	/* if( i_WatchdogCounter3Init==1) */
 				else {
 					printk("\nCounter3 not configured\n");
 					return -EINVAL;
 				}
 				break;
 			case 1:
-				//triggering Watchdog 3
+				/* triggering Watchdog 3 */
 				if (i_WatchdogCounter3Init == 1) {
 
 						/********************************************/
@@ -2134,7 +2134,7 @@
 					outb(0x6,
 						devpriv->iobase +
 						APCI1500_Z8536_CONTROL_REGISTER);
-				}	//if( i_WatchdogCounter3Init==1)
+				}	/* if( i_WatchdogCounter3Init==1) */
 				else {
 					printk("\nWatchdog 3 not configured\n");
 					return -EINVAL;
@@ -2143,17 +2143,17 @@
 			default:
 				printk("\nWrong choice of watchdog/counter3\n");
 				return -EINVAL;
-			}	//switch(data[2])
+			}	/* switch(data[2]) */
 			break;
 		default:
 			printk("\nThe specified option for start/stop/trigger does not exist\n");
 			return -EINVAL;
-		}		//switch(data[1])
+		}		/* switch(data[1]) */
 		break;
 	default:
 		printk("\nThe specified choice for counter/watchdog/timer does not exist\n");
 		return -EINVAL;
-	}			//switch(data[0])
+	}			/* switch(data[0]) */
 	return insn->n;
 }
 
@@ -2161,18 +2161,18 @@
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI1500_ReadCounterTimerWatchdog                |
 |			(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
-                    unsigned int *data); 	                                     |
+|                    unsigned int *data); 	                                     |
 +----------------------------------------------------------------------------+
 | Task              : Read The Watchdog                                      |
 +----------------------------------------------------------------------------+
 | Input Parameters  :   struct comedi_device *dev      : Driver handle              |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                      struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data          : Data Pointer to read status  |
-                      data[0]                : 0     Counter1/Timer1
-                                               1     Counter2/Timer2
-                                               2     Counter3/Watchdog
-
+|                      data[0]                : 0     Counter1/Timer1
+|                                               1     Counter2/Timer2
+|                                               2     Counter3/Watchdog
+|
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -2182,13 +2182,13 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI1500_ReadCounterTimerWatchdog(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1500_ReadCounterTimerWatchdog(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int i_CommandAndStatusValue;
 	switch (data[0]) {
 	case COUNTER1:
-		//Read counter/timer1
+		/* Read counter/timer1 */
 		if (i_TimerCounter1Init == 1) {
 			if (i_TimerCounter1Enabled == 1) {
 		  /************************/
@@ -2196,14 +2196,14 @@
 		  /************************/
 
 				i_CommandAndStatusValue = 0xC;
-			}	//if( i_TimerCounter1Init==1)
+			}	/* if( i_TimerCounter1Init==1) */
 			else {
 		    /***************/
 				/* Set RCC */
 		    /***************/
 
 				i_CommandAndStatusValue = 0x8;
-			}	//elseif(i_TimerCounter1Init==1)
+			}	/* elseif(i_TimerCounter1Init==1) */
 
 		/********************************************/
 			/* Selects the commands and status register */
@@ -2232,14 +2232,14 @@
 			data[0] =
 				data[0] | inb(devpriv->iobase +
 				APCI1500_Z8536_CONTROL_REGISTER);
-		}		//if( i_TimerCounter1Init==1)
+		}		/* if( i_TimerCounter1Init==1) */
 		else {
 			printk("\nTimer/Counter1 not configured\n");
 			return -EINVAL;
-		}		//elseif( i_TimerCounter1Init==1)
+		}		/* elseif( i_TimerCounter1Init==1) */
 		break;
 	case COUNTER2:
-		//Read counter/timer2
+		/* Read counter/timer2 */
 		if (i_TimerCounter2Init == 1) {
 			if (i_TimerCounter2Enabled == 1) {
 		  /************************/
@@ -2247,14 +2247,14 @@
 		  /************************/
 
 				i_CommandAndStatusValue = 0xC;
-			}	//if( i_TimerCounter2Init==1)
+			}	/* if( i_TimerCounter2Init==1) */
 			else {
 		    /***************/
 				/* Set RCC */
 		    /***************/
 
 				i_CommandAndStatusValue = 0x8;
-			}	//elseif(i_TimerCounter2Init==1)
+			}	/* elseif(i_TimerCounter2Init==1) */
 
 		/********************************************/
 			/* Selects the commands and status register */
@@ -2283,14 +2283,14 @@
 			data[0] =
 				data[0] | inb(devpriv->iobase +
 				APCI1500_Z8536_CONTROL_REGISTER);
-		}		//if( i_TimerCounter2Init==1)
+		}		/* if( i_TimerCounter2Init==1) */
 		else {
 			printk("\nTimer/Counter2 not configured\n");
 			return -EINVAL;
-		}		//elseif( i_TimerCounter2Init==1)
+		}		/* elseif( i_TimerCounter2Init==1) */
 		break;
 	case COUNTER3:
-		//Read counter/watchdog2
+		/* Read counter/watchdog2 */
 		if (i_WatchdogCounter3Init == 1) {
 			if (i_WatchdogCounter3Enabled == 1) {
 		  /************************/
@@ -2298,14 +2298,14 @@
 		  /************************/
 
 				i_CommandAndStatusValue = 0xC;
-			}	//if( i_TimerCounter2Init==1)
+			}	/* if( i_TimerCounter2Init==1) */
 			else {
 		    /***************/
 				/* Set RCC */
 		    /***************/
 
 				i_CommandAndStatusValue = 0x8;
-			}	//elseif(i_WatchdogCounter3Init==1)
+			}	/* elseif(i_WatchdogCounter3Init==1) */
 
 		/********************************************/
 			/* Selects the commands and status register */
@@ -2334,16 +2334,16 @@
 			data[0] =
 				data[0] | inb(devpriv->iobase +
 				APCI1500_Z8536_CONTROL_REGISTER);
-		}		//if( i_WatchdogCounter3Init==1)
+		}		/* if( i_WatchdogCounter3Init==1) */
 		else {
 			printk("\nWatchdogCounter3 not configured\n");
 			return -EINVAL;
-		}		//elseif( i_WatchdogCounter3Init==1)
+		}		/* elseif( i_WatchdogCounter3Init==1) */
 		break;
 	default:
 		printk("\nThe choice of timer/counter/watchdog does not exist\n");
 		return -EINVAL;
-	}			//switch(data[0])
+	}			/* switch(data[0]) */
 
 	return insn->n;
 }
@@ -2352,13 +2352,13 @@
 +----------------------------------------------------------------------------+
 | Function   Name   : int  i_APCI1500_ReadInterruptMask                      |
 |			(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
-                    unsigned int *data); 	                                     |
+|                    unsigned int *data); 	                                     |
 +----------------------------------------------------------------------------+
 | Task              : Read the interrupt mask                                |
 +----------------------------------------------------------------------------+
 | Input Parameters  :   struct comedi_device *dev      : Driver handle              |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                      struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data          : Data Pointer to read status  |
 
 
@@ -2370,8 +2370,8 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI1500_ReadInterruptMask(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1500_ReadInterruptMask(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = i_InterruptMask;
 	data[1] = i_InputChannel;
@@ -2383,15 +2383,15 @@
 +----------------------------------------------------------------------------+
 | Function   Name   : int  i_APCI1500_ConfigureInterrupt                     |
 |			(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
-                    unsigned int *data); 	                                     |
+|                    unsigned int *data); 	                                     |
 +----------------------------------------------------------------------------+
 | Task              : Configures the interrupt registers                     |
 +----------------------------------------------------------------------------+
 | Input Parameters  :   struct comedi_device *dev      : Driver handle              |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                      struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data          : Data Pointer                 |
-
+|
 
 +----------------------------------------------------------------------------+
 | Output Parameters :	--
@@ -2401,26 +2401,26 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI1500_ConfigureInterrupt(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1500_ConfigureInterrupt(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Status;
+	unsigned int ui_Status;
 	int i_RegValue;
 	int i_Constant;
 	devpriv->tsk_Current = current;
 	outl(0x0, devpriv->i_IobaseAmcc + 0x38);
 	if (data[0] == 1) {
 		i_Constant = 0xC0;
-	}			//if(data[0]==1)
+	}			/* if(data[0]==1) */
 	else {
 		if (data[0] == 0) {
 			i_Constant = 0x00;
-		}		//if{data[0]==0)
+		}		/* if{data[0]==0) */
 		else {
 			printk("\nThe parameter passed to driver is in error for enabling the voltage interrupt\n");
 			return -EINVAL;
-		}		//else if(data[0]==0)
-	}			//elseif(data[0]==1)
+		}		/* else if(data[0]==0) */
+	}			/* elseif(data[0]==1) */
 
 	 /*****************************************************/
 	/* Selects the mode specification register of port B */
@@ -2580,7 +2580,7 @@
 {
 
 	struct comedi_device *dev = d;
-	UINT ui_InterruptStatus = 0;
+	unsigned int ui_InterruptStatus = 0;
 	int i_RegValue = 0;
 	i_InterruptMask = 0;
 
@@ -2599,11 +2599,11 @@
       /*************************************************/
 		/* Selects the master interrupt control register */
       /*************************************************/
-		//outb(APCI1500_RW_MASTER_INTERRUPT_CONTROL,devpriv->iobase+APCI1500_Z8536_CONTROL_REGISTER);
+		/* outb(APCI1500_RW_MASTER_INTERRUPT_CONTROL,devpriv->iobase+APCI1500_Z8536_CONTROL_REGISTER); */
 	/**********************************************/
 		/* Disables  the main interrupt on the board */
 	/**********************************************/
-		//outb(0x00,devpriv->iobase+APCI1500_Z8536_CONTROL_REGISTER);
+		/* outb(0x00,devpriv->iobase+APCI1500_Z8536_CONTROL_REGISTER); */
 
    /*****************************************************/
 		/* Selects the command and status register of port A */
@@ -2647,11 +2647,11 @@
 
 				i_InputChannel = 1 + (i_RegValue >> 1);
 
-			}	// if(i_Logic==APCI1500_OR_PRIORITY)
+			}	/*  if(i_Logic==APCI1500_OR_PRIORITY) */
 			else {
 				i_InputChannel = 0;
-			}	//elseif(i_Logic==APCI1500_OR_PRIORITY)
-		}		// if ((i_RegValue & 0x60) == 0x60)
+			}	/* elseif(i_Logic==APCI1500_OR_PRIORITY) */
+		}		/*  if ((i_RegValue & 0x60) == 0x60) */
 
 	   /*****************************************************/
 		/* Selects the command and status register of port B */
@@ -2679,7 +2679,7 @@
 			/* Reads port B */
 	     /****************/
 			i_RegValue =
-				inb((UINT) devpriv->iobase +
+				inb((unsigned int) devpriv->iobase +
 				APCI1500_Z8536_PORT_B);
 
 			i_RegValue = i_RegValue & 0xC0;
@@ -2688,7 +2688,7 @@
 	      /**************************************/
 
 			if (i_RegValue) {
-				//Disable the interrupt
+				/* Disable the interrupt */
 		     /*****************************************************/
 				/* Selects the command and status register of port B */
 		     /*****************************************************/
@@ -2697,17 +2697,17 @@
 				if (i_RegValue & 0x80) {
 					i_InterruptMask =
 						i_InterruptMask | 0x40;
-				}	//if (i_RegValue & 0x80)
+				}	/* if (i_RegValue & 0x80) */
 
 				if (i_RegValue & 0x40) {
 					i_InterruptMask =
 						i_InterruptMask | 0x80;
-				}	//if (i_RegValue & 0x40)
-			}	// if (i_RegValue)
+				}	/* if (i_RegValue & 0x40) */
+			}	/*  if (i_RegValue) */
 			else {
 				i_InterruptMask = i_InterruptMask | 2;
-			}	// if (i_RegValue)
-		}		//if ((i_RegValue & 0x60) == 0x60)
+			}	/*  if (i_RegValue) */
+		}		/* if ((i_RegValue & 0x60) == 0x60) */
 
 		/*****************************************************/
 		/* Selects the command and status register of timer 1 */
@@ -2731,7 +2731,7 @@
 				devpriv->iobase +
 				APCI1500_Z8536_CONTROL_REGISTER);
 			i_InterruptMask = i_InterruptMask | 4;
-		}		// if ((i_RegValue & 0x60) == 0x60)
+		}		/*  if ((i_RegValue & 0x60) == 0x60) */
 		/*****************************************************/
 		/* Selects the command and status register of timer 2 */
 		/*****************************************************/
@@ -2754,7 +2754,7 @@
 				devpriv->iobase +
 				APCI1500_Z8536_CONTROL_REGISTER);
 			i_InterruptMask = i_InterruptMask | 8;
-		}		// if ((i_RegValue & 0x60) == 0x60)
+		}		/*  if ((i_RegValue & 0x60) == 0x60) */
 
 		/*****************************************************/
 		/* Selects the command and status register of timer 3 */
@@ -2779,13 +2779,13 @@
 				APCI1500_Z8536_CONTROL_REGISTER);
 			if (i_CounterLogic == APCI1500_COUNTER) {
 				i_InterruptMask = i_InterruptMask | 0x10;
-			}	//if(i_CounterLogic==APCI1500_COUNTER)
+			}	/* if(i_CounterLogic==APCI1500_COUNTER) */
 			else {
 				i_InterruptMask = i_InterruptMask | 0x20;
 			}
-		}		// if ((i_RegValue & 0x60) == 0x60)
+		}		/*  if ((i_RegValue & 0x60) == 0x60) */
 
-		send_sig(SIGIO, devpriv->tsk_Current, 0);	// send signal to the sample
+		send_sig(SIGIO, devpriv->tsk_Current, 0);	/*  send signal to the sample */
 	       /***********************/
 		/* Enable all Interrupts */
 	       /***********************/
@@ -2799,11 +2799,11 @@
 		/* Authorizes the main interrupt on the board */
 	       /**********************************************/
 		outb(0xD0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
-	}			//  if ((ui_InterruptStatus & 0x800000) == 0x800000)
+	}			/*   if ((ui_InterruptStatus & 0x800000) == 0x800000) */
 	else {
 		printk("\nInterrupt from unknown source\n");
 
-	}			//else if ((ui_InterruptStatus & 0x800000) == 0x800000)
+	}			/* else if ((ui_InterruptStatus & 0x800000) == 0x800000) */
 	return;
 }
 
@@ -2822,7 +2822,7 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1500_Reset(struct comedi_device * dev)
+int i_APCI1500_Reset(struct comedi_device *dev)
 {
 	int i_DummyRead = 0;
 	i_TimerCounter1Init = 0;
@@ -2982,7 +2982,7 @@
 		devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
 	/* Deletes all interrupts */
 	outb(0, devpriv->iobase + APCI1500_Z8536_CONTROL_REGISTER);
-	//reset all the digital outputs
+	/* reset all the digital outputs */
 	outw(0x0, devpriv->i_IobaseAddon + APCI1500_DIGITAL_OP);
 /*******************************/
 /* Disable the board interrupt */
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1500.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1500.h
index 5d960b4..0579033 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1500.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1500.h
@@ -17,11 +17,11 @@
 
 /*********      Definitions for APCI-1500 card  *****/
 
-// Card Specific information
+/* Card Specific information */
 #define APCI1500_BOARD_VENDOR_ID           0x10e8
 #define APCI1500_ADDRESS_RANGE              4
 
-//DIGITAL INPUT-OUTPUT DEFINE
+/* DIGITAL INPUT-OUTPUT DEFINE */
 
 #define  APCI1500_DIGITAL_OP                 	2
 #define  APCI1500_DIGITAL_IP                    0
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1516.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1516.c
index 5ae9a93..3841635 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1516.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1516.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -63,7 +63,7 @@
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
 |		       struct comedi_subdevice *s,   :pointer to subdevice structure
-                       struct comedi_insn *insn      :pointer to insn structure     |
+|                       struct comedi_insn *insn      :pointer to insn structure     |
 |                     unsigned int *data          : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -73,22 +73,22 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1516_Read1DigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1516_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_TmpValue = 0;
-	UINT ui_Channel;
+	unsigned int ui_TmpValue = 0;
+	unsigned int ui_Channel;
 	ui_Channel = CR_CHAN(insn->chanspec);
 	if (ui_Channel >= 0 && ui_Channel <= 7) {
-		ui_TmpValue = (UINT) inw(devpriv->iobase + APCI1516_DIGITAL_IP);
-		//  since only 1 channel reqd  to bring it to last bit it is rotated
-		//  8 +(chan - 1) times then ANDed with 1 for last bit.
+		ui_TmpValue = (unsigned int) inw(devpriv->iobase + APCI1516_DIGITAL_IP);
+		/*   since only 1 channel reqd  to bring it to last bit it is rotated */
+		/*   8 +(chan - 1) times then ANDed with 1 for last bit. */
 		*data = (ui_TmpValue >> ui_Channel) & 0x1;
-	}			//if(ui_Channel >= 0 && ui_Channel <=7)
+	}			/* if(ui_Channel >= 0 && ui_Channel <=7) */
 	else {
-		//comedi_error(dev," \n chan spec wrong\n");
-		return -EINVAL;	// "sorry channel spec wrong "
-	}			//else if(ui_Channel >= 0 && ui_Channel <=7)
+		/* comedi_error(dev," \n chan spec wrong\n"); */
+		return -EINVAL;	/*  "sorry channel spec wrong " */
+	}			/* else if(ui_Channel >= 0 && ui_Channel <=7) */
 
 	return insn->n;
 }
@@ -103,7 +103,7 @@
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
 |                      struct comedi_subdevice *s,   :pointer to subdevice structure
-                       struct comedi_insn *insn      :pointer to insn structure     |
+|                       struct comedi_insn *insn      :pointer to insn structure     |
 |                      unsigned int *data         : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -114,17 +114,17 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1516_ReadMoreDigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1516_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
-	UINT ui_PortValue = data[0];
-	UINT ui_Mask = 0;
-	UINT ui_NoOfChannels;
+	unsigned int ui_PortValue = data[0];
+	unsigned int ui_Mask = 0;
+	unsigned int ui_NoOfChannels;
 
 	ui_NoOfChannels = CR_CHAN(insn->chanspec);
 
-	*data = (UINT) inw(devpriv->iobase + APCI1516_DIGITAL_IP);
+	*data = (unsigned int) inw(devpriv->iobase + APCI1516_DIGITAL_IP);
 	switch (ui_NoOfChannels) {
 	case 2:
 		ui_Mask = 3;
@@ -139,9 +139,9 @@
 
 	default:
 		printk("\nWrong parameters\n");
-		return -EINVAL;	// "sorry channel spec wrong "
+		return -EINVAL;	/*  "sorry channel spec wrong " */
 		break;
-	}			//switch(ui_NoOfChannels)
+	}			/* switch(ui_NoOfChannels) */
 
 	return insn->n;
 }
@@ -149,7 +149,7 @@
 /*
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI1516_ConfigDigitalOutput (struct comedi_device *dev,
-                    struct comedi_subdevice *s struct comedi_insn *insn,unsigned int *data)    |
+|                    struct comedi_subdevice *s struct comedi_insn *insn,unsigned int *data)    |
 |				                                                     |
 +----------------------------------------------------------------------------+
 | Task              : Configures The Digital Output Subdevice.               |
@@ -158,7 +158,7 @@
 |                     unsigned int *data         : Data Pointer contains         |
 |                                          configuration parameters as below |
 |                      struct comedi_subdevice *s,   :pointer to subdevice structure
-                       struct comedi_insn *insn      :pointer to insn structure                                                           |
+|                      struct comedi_insn *insn      :pointer to insn structure                                                           |
 |					  data[0]  :1:Memory on                          |
 |					            0:Memory off                         |
 |										                             |
@@ -171,8 +171,8 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI1516_ConfigDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1516_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	devpriv->b_OutputMemoryStatus = data[0];
 	return insn->n;
@@ -182,13 +182,13 @@
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI1516_WriteDigitalOutput                      |
 |			(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
-                     unsigned int *data)                                         |
+|                     unsigned int *data)                                         |
 +----------------------------------------------------------------------------+
 | Task              : Writes port value  To the selected port                |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                     struct comedi_insn *insn      :pointer to insn structure      |
 |                    unsigned int *data           : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -199,21 +199,21 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1516_WriteDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1516_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp, ui_Temp1;
-	UINT ui_NoOfChannel = CR_CHAN(insn->chanspec);	// get the channel
+	unsigned int ui_Temp, ui_Temp1;
+	unsigned int ui_NoOfChannel = CR_CHAN(insn->chanspec);	/*  get the channel */
 
 	printk("EL311003 : @=%x\n", devpriv->iobase + APCI1516_DIGITAL_OP);
 
 	if (devpriv->b_OutputMemoryStatus) {
 		ui_Temp = inw(devpriv->iobase + APCI1516_DIGITAL_OP);
 
-	}			//if(devpriv->b_OutputMemoryStatus )
+	}			/* if(devpriv->b_OutputMemoryStatus ) */
 	else {
 		ui_Temp = 0;
-	}			//if(devpriv->b_OutputMemoryStatus )
+	}			/* if(devpriv->b_OutputMemoryStatus ) */
 	if (data[3] == 0) {
 		if (data[1] == 0) {
 			data[0] = (data[0] << ui_NoOfChannel) | ui_Temp;
@@ -222,7 +222,7 @@
 			printk("EL311003 : d=%d @=%x\n", data[0],
 				devpriv->iobase + APCI1516_DIGITAL_OP);
 
-		}		//if(data[1]==0)
+		}		/* if(data[1]==0) */
 		else {
 			if (data[1] == 1) {
 				switch (ui_NoOfChannel) {
@@ -245,21 +245,21 @@
 
 				default:
 					comedi_error(dev, " chan spec wrong");
-					return -EINVAL;	// "sorry channel spec wrong "
+					return -EINVAL;	/*  "sorry channel spec wrong " */
 
-				}	//switch(ui_NoOfChannels)
+				}	/* switch(ui_NoOfChannels) */
 
 				outw(data[0],
 					devpriv->iobase + APCI1516_DIGITAL_OP);
 
 				printk("EL311003 : d=%d @=%x\n", data[0],
 					devpriv->iobase + APCI1516_DIGITAL_OP);
-			}	// if(data[1]==1)
+			}	/*  if(data[1]==1) */
 			else {
 				printk("\nSpecified channel not supported\n");
-			}	//else if(data[1]==1)
-		}		//elseif(data[1]==0)
-	}			//if(data[3]==0)
+			}	/* else if(data[1]==1) */
+		}		/* elseif(data[1]==0) */
+	}			/* if(data[3]==0) */
 	else {
 		if (data[3] == 1) {
 			if (data[1] == 0) {
@@ -275,7 +275,7 @@
 				printk("EL311003 : d=%d @=%x\n", data[0],
 					devpriv->iobase + APCI1516_DIGITAL_OP);
 
-			}	//if(data[1]==0)
+			}	/* if(data[1]==0) */
 			else {
 				if (data[1] == 1) {
 					switch (ui_NoOfChannel) {
@@ -312,9 +312,9 @@
 					default:
 						comedi_error(dev,
 							" chan spec wrong");
-						return -EINVAL;	// "sorry channel spec wrong "
+						return -EINVAL;	/*  "sorry channel spec wrong " */
 
-					}	//switch(ui_NoOfChannels)
+					}	/* switch(ui_NoOfChannels) */
 
 					outw(data[0],
 						devpriv->iobase +
@@ -324,17 +324,17 @@
 						data[0],
 						devpriv->iobase +
 						APCI1516_DIGITAL_OP);
-				}	// if(data[1]==1)
+				}	/*  if(data[1]==1) */
 				else {
 					printk("\nSpecified channel not supported\n");
-				}	//else if(data[1]==1)
-			}	//elseif(data[1]==0)
-		}		//if(data[3]==1);
+				}	/* else if(data[1]==1) */
+			}	/* elseif(data[1]==0) */
+		}		/* if(data[3]==1); */
 		else {
 			printk("\nSpecified functionality does not exist\n");
 			return -EINVAL;
-		}		//if else data[3]==1)
-	}			//if else data[3]==0)
+		}		/* if else data[3]==1) */
+	}			/* if else data[3]==0) */
 	return (insn->n);;
 }
 
@@ -342,13 +342,13 @@
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI1516_ReadDigitalOutput                       |
 |			(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
-                    unsigned int *data) 	                                     |
+|                    unsigned int *data) 	                                     |
 +----------------------------------------------------------------------------+
 | Task              : Read  value  of the selected channel or port           |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                     struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data          : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -359,17 +359,17 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1516_ReadDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1516_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
-	UINT ui_Temp;
-	UINT ui_NoOfChannel = CR_CHAN(insn->chanspec);	// get the channel
+	unsigned int ui_Temp;
+	unsigned int ui_NoOfChannel = CR_CHAN(insn->chanspec);	/*  get the channel */
 	ui_Temp = data[0];
 	*data = inw(devpriv->iobase + APCI1516_DIGITAL_OP_RW);
 	if (ui_Temp == 0) {
 		*data = (*data >> ui_NoOfChannel) & 0x1;
-	}			//if(ui_Temp==0)
+	}			/* if(ui_Temp==0) */
 	else {
 		if (ui_Temp == 1) {
 			switch (ui_NoOfChannel) {
@@ -387,28 +387,28 @@
 
 			default:
 				comedi_error(dev, " chan spec wrong");
-				return -EINVAL;	// "sorry channel spec wrong "
+				return -EINVAL;	/*  "sorry channel spec wrong " */
 
-			}	//switch(ui_NoOfChannels)
-		}		//if(ui_Temp==1)
+			}	/* switch(ui_NoOfChannels) */
+		}		/* if(ui_Temp==1) */
 		else {
 			printk("\nSpecified channel not supported \n");
-		}		//elseif(ui_Temp==1)
-	}			//elseif(ui_Temp==0)
+		}		/* elseif(ui_Temp==1) */
+	}			/* elseif(ui_Temp==0) */
 	return insn->n;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI1516_ConfigWatchdog(struct comedi_device *dev,
-                      struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)  |
+|                      struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)  |
 |				                                                     |
 +----------------------------------------------------------------------------+
 | Task              : Configures The Watchdog                                |
 +----------------------------------------------------------------------------+
 | Input Parameters  :   struct comedi_device *dev      : Driver handle              |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                      struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data          : Data Pointer to read status                                                     |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -419,15 +419,15 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI1516_ConfigWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1516_ConfigWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (data[0] == 0) {
-		//Disable the watchdog
+		/* Disable the watchdog */
 		outw(0x0,
 			devpriv->i_IobaseAddon +
 			APCI1516_WATCHDOG_ENABLEDISABLE);
-		//Loading the Reload value
+		/* Loading the Reload value */
 		outw(data[1],
 			devpriv->i_IobaseAddon +
 			APCI1516_WATCHDOG_RELOAD_VALUE);
@@ -435,11 +435,11 @@
 		outw(data[1],
 			devpriv->i_IobaseAddon +
 			APCI1516_WATCHDOG_RELOAD_VALUE + 2);
-	}			//if(data[0]==0)
+	}			/* if(data[0]==0) */
 	else {
 		printk("\nThe input parameters are wrong\n");
 		return -EINVAL;
-	}			//elseif(data[0]==0)
+	}			/* elseif(data[0]==0) */
 
 	return insn->n;
 }
@@ -465,19 +465,19 @@
     +----------------------------------------------------------------------------+
   */
 
-int i_APCI1516_StartStopWriteWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1516_StartStopWriteWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	switch (data[0]) {
-	case 0:		//stop the watchdog
-		outw(0x0, devpriv->i_IobaseAddon + APCI1516_WATCHDOG_ENABLEDISABLE);	//disable the watchdog
+	case 0:		/* stop the watchdog */
+		outw(0x0, devpriv->i_IobaseAddon + APCI1516_WATCHDOG_ENABLEDISABLE);	/* disable the watchdog */
 		break;
-	case 1:		//start the watchdog
+	case 1:		/* start the watchdog */
 		outw(0x0001,
 			devpriv->i_IobaseAddon +
 			APCI1516_WATCHDOG_ENABLEDISABLE);
 		break;
-	case 2:		//Software trigger
+	case 2:		/* Software trigger */
 		outw(0x0201,
 			devpriv->i_IobaseAddon +
 			APCI1516_WATCHDOG_ENABLEDISABLE);
@@ -485,7 +485,7 @@
 	default:
 		printk("\nSpecified functionality does not exist\n");
 		return -EINVAL;
-	}			// switch(data[0])
+	}			/*  switch(data[0]) */
 	return insn->n;
 }
 
@@ -510,8 +510,8 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI1516_ReadWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1516_ReadWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = inw(devpriv->i_IobaseAddon + APCI1516_WATCHDOG_STATUS) & 0x1;
 	return insn->n;
@@ -532,9 +532,9 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1516_Reset(struct comedi_device * dev)
+int i_APCI1516_Reset(struct comedi_device *dev)
 {
-	outw(0x0, devpriv->iobase + APCI1516_DIGITAL_OP);	//RESETS THE DIGITAL OUTPUTS
+	outw(0x0, devpriv->iobase + APCI1516_DIGITAL_OP);	/* RESETS THE DIGITAL OUTPUTS */
 	outw(0x0, devpriv->i_IobaseAddon + APCI1516_WATCHDOG_ENABLEDISABLE);
 	outw(0x0, devpriv->i_IobaseAddon + APCI1516_WATCHDOG_RELOAD_VALUE);
 	outw(0x0, devpriv->i_IobaseAddon + APCI1516_WATCHDOG_RELOAD_VALUE + 2);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1516.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1516.h
index 398baa0..21c09ed 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1516.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1516.h
@@ -17,17 +17,17 @@
 
 /*********      Definitions for APCI-1516 card  *****/
 
-// Card Specific information
+/* Card Specific information */
 #define APCI1516_BOARD_VENDOR_ID                 0x15B8
 #define APCI1516_ADDRESS_RANGE                   8
 
-//DIGITAL INPUT-OUTPUT DEFINE
+/* DIGITAL INPUT-OUTPUT DEFINE */
 
 #define APCI1516_DIGITAL_OP                 	4
 #define APCI1516_DIGITAL_OP_RW                 	4
 #define APCI1516_DIGITAL_IP                     0
 
-// TIMER COUNTER WATCHDOG DEFINES
+/* TIMER COUNTER WATCHDOG DEFINES */
 
 #define ADDIDATA_WATCHDOG                          2
 #define APCI1516_DIGITAL_OP_WATCHDOG               0
@@ -35,24 +35,25 @@
 #define APCI1516_WATCHDOG_RELOAD_VALUE             4
 #define APCI1516_WATCHDOG_STATUS                   16
 
-// Hardware Layer  functions for Apci1516
+/* Hardware Layer  functions for Apci1516 */
 
-//Digital Input
-INT i_APCI1516_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+/* Digital Input */
+int i_APCI1516_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				    struct comedi_insn *insn, unsigned int *data);
-INT i_APCI1516_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1516_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
 
-//Digital Output
+/* Digital Output */
 int i_APCI1516_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				   struct comedi_insn *insn, unsigned int *data);
-INT i_APCI1516_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1516_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				  struct comedi_insn *insn, unsigned int *data);
-INT i_APCI1516_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1516_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
 
-// TIMER
-// timer value is passed as u seconds
+/*
+* TIMER timer value is passed as u seconds
+*/
 int i_APCI1516_ConfigWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
 			      struct comedi_insn *insn, unsigned int *data);
 int i_APCI1516_StartStopWriteWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
@@ -60,5 +61,5 @@
 int i_APCI1516_ReadWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
 			    struct comedi_insn *insn, unsigned int *data);
 
-//reset
-INT i_APCI1516_Reset(struct comedi_device *dev);
+/* reset */
+int i_APCI1516_Reset(struct comedi_device *dev);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1564.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1564.c
index a6b504c..3a47c30 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1564.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1564.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -55,9 +55,9 @@
 #include <linux/delay.h>
 #include "hwdrv_apci1564.h"
 
-//Global variables
-UINT ui_InterruptStatus_1564 = 0;
-UINT ui_InterruptData, ui_Type;
+/* Global variables */
+unsigned int ui_InterruptStatus_1564 = 0;
+unsigned int ui_InterruptData, ui_Type;
 
 /*
 +----------------------------------------------------------------------------+
@@ -86,8 +86,8 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1564_ConfigDigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1564_ConfigDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	devpriv->tsk_Current = current;
    /*******************************/
@@ -106,13 +106,13 @@
 			outl(0x4,
 				devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP +
 				APCI1564_DIGITAL_IP_IRQ);
-		}		// if  (data[1] == ADDIDATA_OR)
+		}		/*  if  (data[1] == ADDIDATA_OR) */
 		else {
 			outl(0x6,
 				devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP +
 				APCI1564_DIGITAL_IP_IRQ);
-		}		// else if  (data[1] == ADDIDATA_OR)
-	}			// if  (data[0] == ADDIDATA_ENABLE)
+		}		/*  else if  (data[1] == ADDIDATA_OR) */
+	}			/*  if  (data[0] == ADDIDATA_ENABLE) */
 	else {
 		outl(0x0,
 			devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP +
@@ -123,7 +123,7 @@
 		outl(0x0,
 			devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP +
 			APCI1564_DIGITAL_IP_IRQ);
-	}			// else if  (data[0] == ADDIDATA_ENABLE)
+	}			/*  else if  (data[0] == ADDIDATA_ENABLE) */
 
 	return insn->n;
 }
@@ -137,7 +137,7 @@
 | Task              : Return the status of the digital input                 |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|		              UINT ui_Channel : Channel number to read       |
+|		              unsigned int ui_Channel : Channel number to read       |
 |                     unsigned int *data          : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -147,24 +147,26 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1564_Read1DigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1564_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_TmpValue = 0;
-	UINT ui_Channel;
+	unsigned int ui_TmpValue = 0;
+	unsigned int ui_Channel;
 
 	ui_Channel = CR_CHAN(insn->chanspec);
 	if (ui_Channel >= 0 && ui_Channel <= 31) {
 		ui_TmpValue =
-			(UINT) inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP);
-		//  since only 1 channel reqd  to bring it to last bit it is rotated
-		//  8 +(chan - 1) times then ANDed with 1 for last bit.
+			(unsigned int) inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP);
+/*
+* since only 1 channel reqd to bring it to last bit it is rotated 8
+* +(chan - 1) times then ANDed with 1 for last bit.
+*/
 		*data = (ui_TmpValue >> ui_Channel) & 0x1;
-	}			// if  (ui_Channel >= 0 && ui_Channel <=31)
+	}			/*  if  (ui_Channel >= 0 && ui_Channel <=31) */
 	else {
 		comedi_error(dev, "Not a valid channel number !!! \n");
-		return -EINVAL;	// "sorry channel spec wrong "
-	}			//else if  (ui_Channel >= 0 && ui_Channel <=31)
+		return -EINVAL;	/*  "sorry channel spec wrong " */
+	}			/* else if  (ui_Channel >= 0 && ui_Channel <=31) */
 	return insn->n;
 }
 
@@ -177,8 +179,8 @@
 | Task              : Return the status of the Requested digital inputs      |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To be Read    |
-|                      UINT *data             : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To be Read    |
+|                      unsigned int *data             : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -187,16 +189,16 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1564_ReadMoreDigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1564_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_PortValue = data[0];
-	UINT ui_Mask = 0;
-	UINT ui_NoOfChannels;
+	unsigned int ui_PortValue = data[0];
+	unsigned int ui_Mask = 0;
+	unsigned int ui_NoOfChannels;
 
 	ui_NoOfChannels = CR_CHAN(insn->chanspec);
 	if (data[1] == 0) {
-		*data = (UINT) inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP);
+		*data = (unsigned int) inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP);
 		switch (ui_NoOfChannels) {
 		case 2:
 			ui_Mask = 3;
@@ -218,15 +220,15 @@
 			break;
 		default:
 			comedi_error(dev, "Not a valid Channel number !!!\n");
-			return -EINVAL;	// "sorry channel spec wrong "
+			return -EINVAL;	/*  "sorry channel spec wrong " */
 			break;
-		}		// switch  (ui_NoOfChannels)
-	}			// if  (data[1]==0)
+		}		/*  switch  (ui_NoOfChannels) */
+	}			/*  if  (data[1]==0) */
 	else {
 		if (data[1] == 1) {
 			*data = ui_InterruptStatus_1564;
-		}		// if  (data[1]==1)
-	}			// else if  (data[1]==0)
+		}		/*  if  (data[1]==1) */
+	}			/*  else if  (data[1]==0) */
 	return insn->n;
 }
 
@@ -239,7 +241,7 @@
 | Task              : Configures The Digital Output Subdevice.               |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 |					  data[1]            : 1 Enable  VCC  Interrupt  |
@@ -255,34 +257,34 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1564_ConfigDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1564_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	ULONG ul_Command = 0;
+	unsigned int ul_Command = 0;
 
 	if ((data[0] != 0) && (data[0] != 1)) {
 		comedi_error(dev,
 			"Not a valid Data !!! ,Data should be 1 or 0\n");
 		return -EINVAL;
-	}			// if  ((data[0]!=0) && (data[0]!=1))
+	}			/*  if  ((data[0]!=0) && (data[0]!=1)) */
 	if (data[0]) {
 		devpriv->b_OutputMemoryStatus = ADDIDATA_ENABLE;
-	}			// if  (data[0])
+	}			/*  if  (data[0]) */
 	else {
 		devpriv->b_OutputMemoryStatus = ADDIDATA_DISABLE;
-	}			// else if  (data[0])
+	}			/*  else if  (data[0]) */
 	if (data[1] == ADDIDATA_ENABLE) {
 		ul_Command = ul_Command | 0x1;
-	}			// if  (data[1] == ADDIDATA_ENABLE)
+	}			/*  if  (data[1] == ADDIDATA_ENABLE) */
 	else {
 		ul_Command = ul_Command & 0xFFFFFFFE;
-	}			// else if  (data[1] == ADDIDATA_ENABLE)
+	}			/*  else if  (data[1] == ADDIDATA_ENABLE) */
 	if (data[2] == ADDIDATA_ENABLE) {
 		ul_Command = ul_Command | 0x2;
-	}			// if  (data[2] == ADDIDATA_ENABLE)
+	}			/*  if  (data[2] == ADDIDATA_ENABLE) */
 	else {
 		ul_Command = ul_Command & 0xFFFFFFFD;
-	}			// else if  (data[2] == ADDIDATA_ENABLE)
+	}			/*  else if  (data[2] == ADDIDATA_ENABLE) */
 	outl(ul_Command,
 		devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP +
 		APCI1564_DIGITAL_OP_INTERRUPT);
@@ -302,8 +304,8 @@
 | Task              : Writes port value  To the selected port                |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To Write      |
-|                     UINT *data              : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To Write      |
+|                     unsigned int *data              : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -312,28 +314,28 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1564_WriteDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1564_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp, ui_Temp1;
-	UINT ui_NoOfChannel;
+	unsigned int ui_Temp, ui_Temp1;
+	unsigned int ui_NoOfChannel;
 
 	ui_NoOfChannel = CR_CHAN(insn->chanspec);
 	if (devpriv->b_OutputMemoryStatus) {
 		ui_Temp =
 			inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP +
 			APCI1564_DIGITAL_OP_RW);
-	}			// if  (devpriv->b_OutputMemoryStatus )
+	}			/*  if  (devpriv->b_OutputMemoryStatus ) */
 	else {
 		ui_Temp = 0;
-	}			// else if  (devpriv->b_OutputMemoryStatus )
+	}			/*  else if  (devpriv->b_OutputMemoryStatus ) */
 	if (data[3] == 0) {
 		if (data[1] == 0) {
 			data[0] = (data[0] << ui_NoOfChannel) | ui_Temp;
 			outl(data[0],
 				devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP +
 				APCI1564_DIGITAL_OP_RW);
-		}		// if  (data[1]==0)
+		}		/*  if  (data[1]==0) */
 		else {
 			if (data[1] == 1) {
 				switch (ui_NoOfChannel) {
@@ -362,18 +364,18 @@
 					break;
 				default:
 					comedi_error(dev, " chan spec wrong");
-					return -EINVAL;	// "sorry channel spec wrong "
-				}	// switch (ui_NoOfChannels)
+					return -EINVAL;	/*  "sorry channel spec wrong " */
+				}	/*  switch (ui_NoOfChannels) */
 				outl(data[0],
 					devpriv->i_IobaseAmcc +
 					APCI1564_DIGITAL_OP +
 					APCI1564_DIGITAL_OP_RW);
-			}	// if  (data[1]==1)
+			}	/*  if  (data[1]==1) */
 			else {
 				printk("\nSpecified channel not supported\n");
-			}	// else if  (data[1]==1)
-		}		// else if (data[1]==0)
-	}			//if(data[3]==0)
+			}	/*  else if  (data[1]==1) */
+		}		/*  else if (data[1]==0) */
+	}			/* if(data[3]==0) */
 	else {
 		if (data[3] == 1) {
 			if (data[1] == 0) {
@@ -389,7 +391,7 @@
 					devpriv->i_IobaseAmcc +
 					APCI1564_DIGITAL_OP +
 					APCI1564_DIGITAL_OP_RW);
-			}	// if  (data[1]==0)
+			}	/*  if  (data[1]==0) */
 			else {
 				if (data[1] == 1) {
 					switch (ui_NoOfChannel) {
@@ -447,23 +449,23 @@
 					default:
 						comedi_error(dev,
 							" chan spec wrong");
-						return -EINVAL;	// "sorry channel spec wrong "
-					}	//switch(ui_NoOfChannels)
+						return -EINVAL;	/*  "sorry channel spec wrong " */
+					}	/* switch(ui_NoOfChannels) */
 					outl(data[0],
 						devpriv->i_IobaseAmcc +
 						APCI1564_DIGITAL_OP +
 						APCI1564_DIGITAL_OP_RW);
-				}	// if  (data[1]==1)
+				}	/*  if  (data[1]==1) */
 				else {
 					printk("\nSpecified channel not supported\n");
-				}	// else if  (data[1]==1)
-			}	// else if  (data[1]==0)
-		}		// if  (data[3]==1);
+				}	/*  else if  (data[1]==1) */
+			}	/*  else if  (data[1]==0) */
+		}		/*  if  (data[3]==1); */
 		else {
 			printk("\nSpecified functionality does not exist\n");
 			return -EINVAL;
-		}		// else if (data[3]==1)
-	}			// else if (data[3]==0)
+		}		/*  else if (data[3]==1) */
+	}			/*  else if (data[3]==0) */
 	return insn->n;
 }
 
@@ -476,8 +478,8 @@
 | Task              : Read  value  of the selected channel or port           |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To read       |
-|                     UINT *data              : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To read       |
+|                     unsigned int *data              : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -486,11 +488,11 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1564_ReadDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1564_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp;
-	UINT ui_NoOfChannel;
+	unsigned int ui_Temp;
+	unsigned int ui_NoOfChannel;
 
 	ui_NoOfChannel = CR_CHAN(insn->chanspec);
 	ui_Temp = data[0];
@@ -498,7 +500,7 @@
 		APCI1564_DIGITAL_OP_RW);
 	if (ui_Temp == 0) {
 		*data = (*data >> ui_NoOfChannel) & 0x1;
-	}			// if  (ui_Temp==0)
+	}			/*  if  (ui_Temp==0) */
 	else {
 		if (ui_Temp == 1) {
 			switch (ui_NoOfChannel) {
@@ -523,14 +525,14 @@
 
 			default:
 				comedi_error(dev, " chan spec wrong");
-				return -EINVAL;	// "sorry channel spec wrong "
+				return -EINVAL;	/*  "sorry channel spec wrong " */
 				break;
-			}	// switch(ui_NoOfChannels)
-		}		// if  (ui_Temp==1)
+			}	/*  switch(ui_NoOfChannels) */
+		}		/*  if  (ui_Temp==1) */
 		else {
 			printk("\nSpecified channel not supported \n");
-		}		// else if (ui_Temp==1)
-	}			// else if  (ui_Temp==0)
+		}		/*  else if (ui_Temp==1) */
+	}			/*  else if  (ui_Temp==0) */
 	return insn->n;
 }
 
@@ -543,7 +545,7 @@
 | Task              : Configures The Timer , Counter or Watchdog             |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 |					  data[0]            : 0 Configure As Timer      |
@@ -564,34 +566,34 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1564_ConfigTimerCounterWatchdog(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1564_ConfigTimerCounterWatchdog(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	ULONG ul_Command1 = 0;
+	unsigned int ul_Command1 = 0;
 	devpriv->tsk_Current = current;
 	if (data[0] == ADDIDATA_WATCHDOG) {
 		devpriv->b_TimerSelectMode = ADDIDATA_WATCHDOG;
 
-		//Disable the watchdog
+		/* Disable the watchdog */
 		outl(0x0,
 			devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP_WATCHDOG +
 			APCI1564_TCW_PROG);
-		//Loading the Reload value
+		/* Loading the Reload value */
 		outl(data[3],
 			devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP_WATCHDOG +
 			APCI1564_TCW_RELOAD_VALUE);
-	}			// if  (data[0]==ADDIDATA_WATCHDOG)
+	}			/*  if  (data[0]==ADDIDATA_WATCHDOG) */
 	else if (data[0] == ADDIDATA_TIMER) {
-		//First Stop The Timer
+		/* First Stop The Timer */
 		ul_Command1 =
 			inl(devpriv->i_IobaseAmcc + APCI1564_TIMER +
 			APCI1564_TCW_PROG);
 		ul_Command1 = ul_Command1 & 0xFFFFF9FEUL;
-		outl(ul_Command1, devpriv->i_IobaseAmcc + APCI1564_TIMER + APCI1564_TCW_PROG);	//Stop The Timer
+		outl(ul_Command1, devpriv->i_IobaseAmcc + APCI1564_TIMER + APCI1564_TCW_PROG);	/* Stop The Timer */
 
 		devpriv->b_TimerSelectMode = ADDIDATA_TIMER;
 		if (data[1] == 1) {
-			outl(0x02, devpriv->i_IobaseAmcc + APCI1564_TIMER + APCI1564_TCW_PROG);	//Enable TIMER int & DISABLE ALL THE OTHER int SOURCES
+			outl(0x02, devpriv->i_IobaseAmcc + APCI1564_TIMER + APCI1564_TCW_PROG);	/* Enable TIMER int & DISABLE ALL THE OTHER int SOURCES */
 			outl(0x0,
 				devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP +
 				APCI1564_DIGITAL_IP_IRQ);
@@ -614,18 +616,18 @@
 			outl(0x0,
 				devpriv->iobase + APCI1564_COUNTER4 +
 				APCI1564_TCW_IRQ);
-		}		// if  (data[1]==1)
+		}		/*  if  (data[1]==1) */
 		else {
-			outl(0x0, devpriv->i_IobaseAmcc + APCI1564_TIMER + APCI1564_TCW_PROG);	//disable Timer interrupt
-		}		// else if  (data[1]==1)
+			outl(0x0, devpriv->i_IobaseAmcc + APCI1564_TIMER + APCI1564_TCW_PROG);	/* disable Timer interrupt */
+		}		/*  else if  (data[1]==1) */
 
-		// Loading Timebase
+		/*  Loading Timebase */
 
 		outl(data[2],
 			devpriv->i_IobaseAmcc + APCI1564_TIMER +
 			APCI1564_TCW_TIMEBASE);
 
-		//Loading the Reload value
+		/* Loading the Reload value */
 		outl(data[3],
 			devpriv->i_IobaseAmcc + APCI1564_TIMER +
 			APCI1564_TCW_RELOAD_VALUE);
@@ -635,18 +637,18 @@
 			APCI1564_TCW_PROG);
 		ul_Command1 =
 			(ul_Command1 & 0xFFF719E2UL) | 2UL << 13UL | 0x10UL;
-		outl(ul_Command1, devpriv->i_IobaseAmcc + APCI1564_TIMER + APCI1564_TCW_PROG);	//mode 2
-	}			// else if  (data[0]==ADDIDATA_TIMER)
+		outl(ul_Command1, devpriv->i_IobaseAmcc + APCI1564_TIMER + APCI1564_TCW_PROG);	/* mode 2 */
+	}			/*  else if  (data[0]==ADDIDATA_TIMER) */
 	else if (data[0] == ADDIDATA_COUNTER) {
 		devpriv->b_TimerSelectMode = ADDIDATA_COUNTER;
 		devpriv->b_ModeSelectRegister = data[5];
 
-		//First Stop The Counter
+		/* First Stop The Counter */
 		ul_Command1 =
 			inl(devpriv->iobase + ((data[5] - 1) * 0x20) +
 			APCI1564_TCW_PROG);
 		ul_Command1 = ul_Command1 & 0xFFFFF9FEUL;
-		outl(ul_Command1, devpriv->iobase + ((data[5] - 1) * 0x20) + APCI1564_TCW_PROG);	//Stop The Timer
+		outl(ul_Command1, devpriv->iobase + ((data[5] - 1) * 0x20) + APCI1564_TCW_PROG);	/* Stop The Timer */
 
       /************************/
 		/* Set the reload value */
@@ -666,12 +668,12 @@
       /******************************/
 		ul_Command1 =
 			(ul_Command1 & 0xFFFC19E2UL) | 0x80000UL |
-			(ULONG) ((ULONG) data[4] << 16UL);
+			(unsigned int) ((unsigned int) data[4] << 16UL);
 		outl(ul_Command1,
 			devpriv->iobase + ((data[5] - 1) * 0x20) +
 			APCI1564_TCW_PROG);
 
-		// Enable or Disable Interrupt
+		/*  Enable or Disable Interrupt */
 		ul_Command1 = (ul_Command1 & 0xFFFFF9FD) | (data[1] << 1);
 		outl(ul_Command1,
 			devpriv->iobase + ((data[5] - 1) * 0x20) +
@@ -684,10 +686,10 @@
 		outl(ul_Command1,
 			devpriv->iobase + ((data[5] - 1) * 0x20) +
 			APCI1564_TCW_PROG);
-	}			// else if  (data[0]==ADDIDATA_COUNTER)
+	}			/*  else if  (data[0]==ADDIDATA_COUNTER) */
 	else {
 		printk(" Invalid subdevice.");
-	}			// else if  (data[0]==ADDIDATA_WATCHDOG)
+	}			/*  else if  (data[0]==ADDIDATA_WATCHDOG) */
 
 	return insn->n;
 }
@@ -701,7 +703,7 @@
 | Task              : Start / Stop The Selected Timer , Counter or Watchdog  |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 |					  data[0]            : 0 Timer                   |
@@ -718,22 +720,22 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1564_StartStopWriteTimerCounterWatchdog(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1564_StartStopWriteTimerCounterWatchdog(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	ULONG ul_Command1 = 0;
+	unsigned int ul_Command1 = 0;
 	if (devpriv->b_TimerSelectMode == ADDIDATA_WATCHDOG) {
 		switch (data[1]) {
-		case 0:	//stop the watchdog
-			outl(0x0, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP_WATCHDOG + APCI1564_TCW_PROG);	//disable the watchdog
+		case 0:	/* stop the watchdog */
+			outl(0x0, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP_WATCHDOG + APCI1564_TCW_PROG);	/* disable the watchdog */
 			break;
-		case 1:	//start the watchdog
+		case 1:	/* start the watchdog */
 			outl(0x0001,
 				devpriv->i_IobaseAmcc +
 				APCI1564_DIGITAL_OP_WATCHDOG +
 				APCI1564_TCW_PROG);
 			break;
-		case 2:	//Software trigger
+		case 2:	/* Software trigger */
 			outl(0x0201,
 				devpriv->i_IobaseAmcc +
 				APCI1564_DIGITAL_OP_WATCHDOG +
@@ -742,8 +744,8 @@
 		default:
 			printk("\nSpecified functionality does not exist\n");
 			return -EINVAL;
-		}		// switch (data[1])
-	}			// if  (devpriv->b_TimerSelectMode==ADDIDATA_WATCHDOG)
+		}		/*  switch (data[1]) */
+	}			/*  if  (devpriv->b_TimerSelectMode==ADDIDATA_WATCHDOG) */
 	if (devpriv->b_TimerSelectMode == ADDIDATA_TIMER) {
 		if (data[1] == 1) {
 			ul_Command1 =
@@ -751,13 +753,13 @@
 				APCI1564_TCW_PROG);
 			ul_Command1 = (ul_Command1 & 0xFFFFF9FFUL) | 0x1UL;
 
-			//Enable the Timer
+			/* Enable the Timer */
 			outl(ul_Command1,
 				devpriv->i_IobaseAmcc + APCI1564_TIMER +
 				APCI1564_TCW_PROG);
-		}		// if  (data[1]==1)
+		}		/*  if  (data[1]==1) */
 		else if (data[1] == 0) {
-			//Stop The Timer
+			/* Stop The Timer */
 
 			ul_Command1 =
 				inl(devpriv->i_IobaseAmcc + APCI1564_TIMER +
@@ -766,29 +768,29 @@
 			outl(ul_Command1,
 				devpriv->i_IobaseAmcc + APCI1564_TIMER +
 				APCI1564_TCW_PROG);
-		}		// else if(data[1]==0)
-	}			// if  (devpriv->b_TimerSelectMode==ADDIDATA_TIMER)
+		}		/*  else if(data[1]==0) */
+	}			/*  if  (devpriv->b_TimerSelectMode==ADDIDATA_TIMER) */
 	if (devpriv->b_TimerSelectMode == ADDIDATA_COUNTER) {
 		ul_Command1 =
 			inl(devpriv->iobase + ((devpriv->b_ModeSelectRegister -
 					1) * 0x20) + APCI1564_TCW_PROG);
 		if (data[1] == 1) {
-			//Start the Counter subdevice
+			/* Start the Counter subdevice */
 			ul_Command1 = (ul_Command1 & 0xFFFFF9FFUL) | 0x1UL;
-		}		// if  (data[1] == 1)
+		}		/*  if  (data[1] == 1) */
 		else if (data[1] == 0) {
-			// Stops the Counter subdevice
+			/*  Stops the Counter subdevice */
 			ul_Command1 = 0;
 
-		}		// else if  (data[1] == 0)
+		}		/*  else if  (data[1] == 0) */
 		else if (data[1] == 2) {
-			// Clears the Counter subdevice
+			/*  Clears the Counter subdevice */
 			ul_Command1 = (ul_Command1 & 0xFFFFF9FFUL) | 0x400;
-		}		// else if  (data[1] == 3)
+		}		/*  else if  (data[1] == 3) */
 		outl(ul_Command1,
 			devpriv->iobase + ((devpriv->b_ModeSelectRegister -
 					1) * 0x20) + APCI1564_TCW_PROG);
-	}			// if (devpriv->b_TimerSelectMode==ADDIDATA_COUNTER)
+	}			/*  if (devpriv->b_TimerSelectMode==ADDIDATA_COUNTER) */
 	return insn->n;
 }
 
@@ -801,7 +803,7 @@
 | Task              : Read The Selected Timer , Counter or Watchdog          |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 
@@ -813,13 +815,13 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI1564_ReadTimerCounterWatchdog(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI1564_ReadTimerCounterWatchdog(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	ULONG ul_Command1 = 0;
+	unsigned int ul_Command1 = 0;
 
 	if (devpriv->b_TimerSelectMode == ADDIDATA_WATCHDOG) {
-		// Stores the status of the Watchdog
+		/*  Stores the status of the Watchdog */
 		data[0] =
 			inl(devpriv->i_IobaseAmcc +
 			APCI1564_DIGITAL_OP_WATCHDOG +
@@ -827,18 +829,18 @@
 		data[1] =
 			inl(devpriv->i_IobaseAmcc +
 			APCI1564_DIGITAL_OP_WATCHDOG);
-	}			// if  (devpriv->b_TimerSelectMode==ADDIDATA_WATCHDOG)
+	}			/*  if  (devpriv->b_TimerSelectMode==ADDIDATA_WATCHDOG) */
 	else if (devpriv->b_TimerSelectMode == ADDIDATA_TIMER) {
-		// Stores the status of the Timer
+		/*  Stores the status of the Timer */
 		data[0] =
 			inl(devpriv->i_IobaseAmcc + APCI1564_TIMER +
 			APCI1564_TCW_TRIG_STATUS) & 0x1;
 
-		// Stores the Actual value of the Timer
+		/*  Stores the Actual value of the Timer */
 		data[1] = inl(devpriv->i_IobaseAmcc + APCI1564_TIMER);
-	}			// else if  (devpriv->b_TimerSelectMode==ADDIDATA_TIMER)
+	}			/*  else if  (devpriv->b_TimerSelectMode==ADDIDATA_TIMER) */
 	else if (devpriv->b_TimerSelectMode == ADDIDATA_COUNTER) {
-		// Read the Counter Actual Value.
+		/*  Read the Counter Actual Value. */
 		data[0] =
 			inl(devpriv->iobase + ((devpriv->b_ModeSelectRegister -
 					1) * 0x20) +
@@ -850,28 +852,28 @@
       /***********************************/
 		/* Get the software trigger status */
       /***********************************/
-		data[1] = (BYTE) ((ul_Command1 >> 1) & 1);
+		data[1] = (unsigned char) ((ul_Command1 >> 1) & 1);
 
       /***********************************/
 		/* Get the hardware trigger status */
       /***********************************/
-		data[2] = (BYTE) ((ul_Command1 >> 2) & 1);
+		data[2] = (unsigned char) ((ul_Command1 >> 2) & 1);
 
       /*********************************/
 		/* Get the software clear status */
       /*********************************/
-		data[3] = (BYTE) ((ul_Command1 >> 3) & 1);
+		data[3] = (unsigned char) ((ul_Command1 >> 3) & 1);
 
       /***************************/
 		/* Get the overflow status */
       /***************************/
-		data[4] = (BYTE) ((ul_Command1 >> 0) & 1);
-	}			// else  if  (devpriv->b_TimerSelectMode==ADDIDATA_COUNTER)
+		data[4] = (unsigned char) ((ul_Command1 >> 0) & 1);
+	}			/*  else  if  (devpriv->b_TimerSelectMode==ADDIDATA_COUNTER) */
 	else if ((devpriv->b_TimerSelectMode != ADDIDATA_TIMER)
 		&& (devpriv->b_TimerSelectMode != ADDIDATA_WATCHDOG)
 		&& (devpriv->b_TimerSelectMode != ADDIDATA_COUNTER)) {
 		printk("\n Invalid Subdevice !!!\n");
-	}			// else if ((devpriv->b_TimerSelectMode!=ADDIDATA_TIMER) && (devpriv->b_TimerSelectMode!=ADDIDATA_WATCHDOG)&& (devpriv->b_TimerSelectMode!=ADDIDATA_COUNTER))
+	}			/*  else if ((devpriv->b_TimerSelectMode!=ADDIDATA_TIMER) && (devpriv->b_TimerSelectMode!=ADDIDATA_WATCHDOG)&& (devpriv->b_TimerSelectMode!=ADDIDATA_COUNTER)) */
 	return insn->n;
 }
 
@@ -892,8 +894,8 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI1564_ReadInterruptStatus(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI1564_ReadInterruptStatus(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	*data = ui_Type;
 	return insn->n;
@@ -919,10 +921,10 @@
 static void v_APCI1564_Interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
-	UINT ui_DO, ui_DI;
-	UINT ui_Timer;
-	UINT ui_C1, ui_C2, ui_C3, ui_C4;
-	ULONG ul_Command2 = 0;
+	unsigned int ui_DO, ui_DI;
+	unsigned int ui_Timer;
+	unsigned int ui_C1, ui_C2, ui_C3, ui_C4;
+	unsigned int ul_Command2 = 0;
 	ui_DI = inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP +
 		APCI1564_DIGITAL_IP_IRQ) & 0x01;
 	ui_DO = inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP +
@@ -941,7 +943,7 @@
 	if (ui_DI == 0 && ui_DO == 0 && ui_Timer == 0 && ui_C1 == 0
 		&& ui_C2 == 0 && ui_C3 == 0 && ui_C4 == 0) {
 		printk("\nInterrupt from unknown source\n");
-	}			// if(ui_DI==0 && ui_DO==0 && ui_Timer==0 && ui_C1==0 && ui_C2==0 && ui_C3==0 && ui_C4==0)
+	}			/*  if(ui_DI==0 && ui_DO==0 && ui_Timer==0 && ui_C1==0 && ui_C2==0 && ui_C3==0 && ui_C4==0) */
 
 	if (ui_DI == 1) {
 		ui_DI = inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP +
@@ -953,116 +955,137 @@
 			inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP +
 			APCI1564_DIGITAL_IP_INTERRUPT_STATUS);
 		ui_InterruptStatus_1564 = ui_InterruptStatus_1564 & 0X000FFFF0;
-		send_sig(SIGIO, devpriv->tsk_Current, 0);	// send signal to the sample
-		outl(ui_DI, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP + APCI1564_DIGITAL_IP_IRQ);	//enable the interrupt
+		send_sig(SIGIO, devpriv->tsk_Current, 0);	/*  send signal to the sample */
+		outl(ui_DI, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP + APCI1564_DIGITAL_IP_IRQ);	/* enable the interrupt */
 		return;
 	}
 
 	if (ui_DO == 1) {
-		// Check for Digital Output interrupt Type - 1: Vcc interrupt 2: CC interrupt.
+		/*  Check for Digital Output interrupt Type - 1: Vcc interrupt 2: CC interrupt. */
 		ui_Type =
 			inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP +
 			APCI1564_DIGITAL_OP_INTERRUPT_STATUS) & 0x3;
-		//Disable the  Interrupt
+		/* Disable the  Interrupt */
 		outl(0x0,
 			devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP +
 			APCI1564_DIGITAL_OP_INTERRUPT);
 
-		//Sends signal to user space
+		/* Sends signal to user space */
 		send_sig(SIGIO, devpriv->tsk_Current, 0);
 
-	}			// if  (ui_DO)
+	}			/*  if  (ui_DO) */
 
-	if ((ui_Timer == 1) && (devpriv->b_TimerSelectMode = ADDIDATA_TIMER)) {
-		// Disable Timer Interrupt
-		ul_Command2 =
-			inl(devpriv->i_IobaseAmcc + APCI1564_TIMER +
-			APCI1564_TCW_PROG);
-		outl(0x0,
-			devpriv->i_IobaseAmcc + APCI1564_TIMER +
-			APCI1564_TCW_PROG);
+	if (ui_Timer == 1) {
+		devpriv->b_TimerSelectMode = ADDIDATA_TIMER;
+		if (devpriv->b_TimerSelectMode) {
 
-		//Send a signal to from kernel to user space
-		send_sig(SIGIO, devpriv->tsk_Current, 0);
+			/*  Disable Timer Interrupt */
+			ul_Command2 =
+				inl(devpriv->i_IobaseAmcc + APCI1564_TIMER +
+				    APCI1564_TCW_PROG);
+			outl(0x0,
+			     devpriv->i_IobaseAmcc + APCI1564_TIMER +
+			     APCI1564_TCW_PROG);
 
-		// Enable Timer Interrupt
+			/* Send a signal to from kernel to user space */
+			send_sig(SIGIO, devpriv->tsk_Current, 0);
 
-		outl(ul_Command2,
-			devpriv->i_IobaseAmcc + APCI1564_TIMER +
-			APCI1564_TCW_PROG);
-	}			// if  ((ui_Timer == 1) && (devpriv->b_TimerSelectMode =ADDIDATA_TIMER))
+			/*  Enable Timer Interrupt */
 
-	if ((ui_C1 == 1) && (devpriv->b_TimerSelectMode = ADDIDATA_COUNTER)) {
-		// Disable Counter Interrupt
-		ul_Command2 =
-			inl(devpriv->iobase + APCI1564_COUNTER1 +
-			APCI1564_TCW_PROG);
-		outl(0x0,
-			devpriv->iobase + APCI1564_COUNTER1 +
-			APCI1564_TCW_PROG);
+			outl(ul_Command2,
+			     devpriv->i_IobaseAmcc + APCI1564_TIMER +
+			     APCI1564_TCW_PROG);
+		}
+	}/* if  (ui_Timer == 1) */
 
-		//Send a signal to from kernel to user space
-		send_sig(SIGIO, devpriv->tsk_Current, 0);
 
-		// Enable Counter Interrupt
-		outl(ul_Command2,
-			devpriv->iobase + APCI1564_COUNTER1 +
-			APCI1564_TCW_PROG);
-	}			// if  ((ui_C1 == 1) && (devpriv->b_TimerSelectMode = ADDIDATA_COUNTER))
+	if (ui_C1 == 1) {
+		devpriv->b_TimerSelectMode = ADDIDATA_COUNTER;
+		if (devpriv->b_TimerSelectMode) {
 
-	if ((ui_C2 == 1) && (devpriv->b_TimerSelectMode = ADDIDATA_COUNTER)) {
-		// Disable Counter Interrupt
-		ul_Command2 =
-			inl(devpriv->iobase + APCI1564_COUNTER2 +
-			APCI1564_TCW_PROG);
-		outl(0x0,
-			devpriv->iobase + APCI1564_COUNTER2 +
-			APCI1564_TCW_PROG);
+			/*  Disable Counter Interrupt */
+			ul_Command2 =
+				inl(devpriv->iobase + APCI1564_COUNTER1 +
+				    APCI1564_TCW_PROG);
+			outl(0x0,
+			     devpriv->iobase + APCI1564_COUNTER1 +
+			     APCI1564_TCW_PROG);
 
-		//Send a signal to from kernel to user space
-		send_sig(SIGIO, devpriv->tsk_Current, 0);
+			/* Send a signal to from kernel to user space */
+			send_sig(SIGIO, devpriv->tsk_Current, 0);
 
-		// Enable Counter Interrupt
-		outl(ul_Command2,
-			devpriv->iobase + APCI1564_COUNTER2 +
-			APCI1564_TCW_PROG);
-	}			// if  ((ui_C2 == 1) && (devpriv->b_TimerSelectMode =ADDIDATA_COUNTER))
+			/*  Enable Counter Interrupt */
+			outl(ul_Command2,
+			     devpriv->iobase + APCI1564_COUNTER1 +
+			     APCI1564_TCW_PROG);
+		}
+	} /* if  (ui_C1 == 1) */
 
-	if ((ui_C3 == 1) && (devpriv->b_TimerSelectMode = ADDIDATA_COUNTER)) {
-		// Disable Counter Interrupt
-		ul_Command2 =
-			inl(devpriv->iobase + APCI1564_COUNTER3 +
-			APCI1564_TCW_PROG);
-		outl(0x0,
-			devpriv->iobase + APCI1564_COUNTER3 +
-			APCI1564_TCW_PROG);
+	if (ui_C2 == 1) {
+		devpriv->b_TimerSelectMode = ADDIDATA_COUNTER;
+		if (devpriv->b_TimerSelectMode) {
 
-		//Send a signal to from kernel to user space
-		send_sig(SIGIO, devpriv->tsk_Current, 0);
+			/*  Disable Counter Interrupt */
+			ul_Command2 =
+				inl(devpriv->iobase + APCI1564_COUNTER2 +
+				    APCI1564_TCW_PROG);
+			outl(0x0,
+			     devpriv->iobase + APCI1564_COUNTER2 +
+			     APCI1564_TCW_PROG);
 
-		// Enable Counter Interrupt
-		outl(ul_Command2,
-			devpriv->iobase + APCI1564_COUNTER3 +
-			APCI1564_TCW_PROG);
-	}			// if ((ui_C3 == 1) && (devpriv->b_TimerSelectMode =ADDIDATA_COUNTER))
+			/* Send a signal to from kernel to user space */
+			send_sig(SIGIO, devpriv->tsk_Current, 0);
 
-	if ((ui_C4 == 1) && (devpriv->b_TimerSelectMode = ADDIDATA_COUNTER)) {
-		// Disable Counter Interrupt
-		ul_Command2 =
-			inl(devpriv->iobase + APCI1564_COUNTER4 +
-			APCI1564_TCW_PROG);
-		outl(0x0,
-			devpriv->iobase + APCI1564_COUNTER4 +
-			APCI1564_TCW_PROG);
+			/*  Enable Counter Interrupt */
+			outl(ul_Command2,
+			     devpriv->iobase + APCI1564_COUNTER2 +
+			     APCI1564_TCW_PROG);
+		}
+	} /*  if  ((ui_C2 == 1) */
 
-		//Send a signal to from kernel to user space
-		send_sig(SIGIO, devpriv->tsk_Current, 0);
+	if (ui_C3 == 1) {
+		devpriv->b_TimerSelectMode = ADDIDATA_COUNTER;
+		if (devpriv->b_TimerSelectMode) {
 
-		// Enable Counter Interrupt
-		outl(ul_Command2,
-			devpriv->iobase + APCI1564_COUNTER4 +
-			APCI1564_TCW_PROG);
-	}			// if ((ui_C4 == 1) && (devpriv->b_TimerSelectMode =ADDIDATA_COUNTER))
+			/*  Disable Counter Interrupt */
+			ul_Command2 =
+				inl(devpriv->iobase + APCI1564_COUNTER3 +
+				    APCI1564_TCW_PROG);
+			outl(0x0,
+			     devpriv->iobase + APCI1564_COUNTER3 +
+			     APCI1564_TCW_PROG);
+
+			/* Send a signal to from kernel to user space */
+			send_sig(SIGIO, devpriv->tsk_Current, 0);
+
+			/*  Enable Counter Interrupt */
+			outl(ul_Command2,
+			     devpriv->iobase + APCI1564_COUNTER3 +
+			     APCI1564_TCW_PROG);
+		}
+	}	/*  if ((ui_C3 == 1) */
+
+	if (ui_C4 == 1) {
+		devpriv->b_TimerSelectMode = ADDIDATA_COUNTER;
+		if (devpriv->b_TimerSelectMode) {
+
+			/*  Disable Counter Interrupt */
+			ul_Command2 =
+				inl(devpriv->iobase + APCI1564_COUNTER4 +
+				    APCI1564_TCW_PROG);
+			outl(0x0,
+			     devpriv->iobase + APCI1564_COUNTER4 +
+			     APCI1564_TCW_PROG);
+
+			/* Send a signal to from kernel to user space */
+			send_sig(SIGIO, devpriv->tsk_Current, 0);
+
+			/*  Enable Counter Interrupt */
+			outl(ul_Command2,
+			     devpriv->iobase + APCI1564_COUNTER4 +
+			     APCI1564_TCW_PROG);
+		}
+	}	/*  if (ui_C4 == 1) */
 	return;
 }
 
@@ -1081,16 +1104,16 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI1564_Reset(struct comedi_device * dev)
+int i_APCI1564_Reset(struct comedi_device *dev)
 {
-	outl(0x0, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP_IRQ);	//disable the interrupts
-	inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP_INTERRUPT_STATUS);	//Reset the interrupt status register
-	outl(0x0, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP_INTERRUPT_MODE1);	//Disable the and/or interrupt
+	outl(0x0, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP_IRQ);	/* disable the interrupts */
+	inl(devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP_INTERRUPT_STATUS);	/* Reset the interrupt status register */
+	outl(0x0, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP_INTERRUPT_MODE1);	/* Disable the and/or interrupt */
 	outl(0x0, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_IP_INTERRUPT_MODE2);
 	devpriv->b_DigitalOutputRegister = 0;
 	ui_Type = 0;
-	outl(0x0, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP);	//Resets the output channels
-	outl(0x0, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP_INTERRUPT);	//Disables the interrupt.
+	outl(0x0, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP);	/* Resets the output channels */
+	outl(0x0, devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP_INTERRUPT);	/* Disables the interrupt. */
 	outl(0x0,
 		devpriv->i_IobaseAmcc + APCI1564_DIGITAL_OP_WATCHDOG +
 		APCI1564_TCW_RELOAD_VALUE);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1564.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1564.h
index f0c461c..0780c44 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1564.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci1564.h
@@ -20,45 +20,45 @@
 #define APCI1564_BOARD_VENDOR_ID                0x15B8
 #define APCI1564_ADDRESS_RANGE                  128
 
-//DIGITAL INPUT-OUTPUT DEFINE
-// Input defines
+/* DIGITAL INPUT-OUTPUT DEFINE */
+/* Input defines */
 #define APCI1564_DIGITAL_IP                     0x04
 #define APCI1564_DIGITAL_IP_INTERRUPT_MODE1     4
 #define APCI1564_DIGITAL_IP_INTERRUPT_MODE2     8
 #define APCI1564_DIGITAL_IP_IRQ                 16
 
-// Output defines
+/* Output defines */
 #define APCI1564_DIGITAL_OP                 	0x18
 #define APCI1564_DIGITAL_OP_RW               	0
 #define APCI1564_DIGITAL_OP_INTERRUPT           4
 #define APCI1564_DIGITAL_OP_IRQ                 12
 
-//Digital Input IRQ Function Selection
+/* Digital Input IRQ Function Selection */
 #define ADDIDATA_OR                             0
 #define ADDIDATA_AND                            1
 
-//Digital Input Interrupt Status
+/* Digital Input Interrupt Status */
 #define APCI1564_DIGITAL_IP_INTERRUPT_STATUS    12
 
-//Digital Output Interrupt Status
+/* Digital Output Interrupt Status */
 #define APCI1564_DIGITAL_OP_INTERRUPT_STATUS    8
 
-//Digital Input Interrupt Enable Disable.
+/* Digital Input Interrupt Enable Disable. */
 #define APCI1564_DIGITAL_IP_INTERRUPT_ENABLE    0x4
 #define APCI1564_DIGITAL_IP_INTERRUPT_DISABLE   0xFFFFFFFB
 
-//Digital Output Interrupt Enable Disable.
+/* Digital Output Interrupt Enable Disable. */
 #define APCI1564_DIGITAL_OP_VCC_INTERRUPT_ENABLE   0x1
 #define APCI1564_DIGITAL_OP_VCC_INTERRUPT_DISABLE  0xFFFFFFFE
 #define APCI1564_DIGITAL_OP_CC_INTERRUPT_ENABLE    0x2
 #define APCI1564_DIGITAL_OP_CC_INTERRUPT_DISABLE   0xFFFFFFFD
 
-//ADDIDATA Enable Disable
+/* ADDIDATA Enable Disable */
 
 #define ADDIDATA_ENABLE                            1
 #define ADDIDATA_DISABLE                           0
 
-// TIMER COUNTER WATCHDOG DEFINES
+/* TIMER COUNTER WATCHDOG DEFINES */
 
 #define ADDIDATA_TIMER                             0
 #define ADDIDATA_COUNTER                           1
@@ -78,30 +78,32 @@
 #define APCI1564_TCW_WARN_TIMEVAL                  24
 #define APCI1564_TCW_WARN_TIMEBASE                 28
 
-// Hardware Layer  functions for Apci1564
+/* Hardware Layer  functions for Apci1564 */
 
-//DI
-// for di read
-INT i_APCI1564_ConfigDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+/*
+* DI for di read
+*/
+int i_APCI1564_ConfigDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				  struct comedi_insn *insn, unsigned int *data);
-INT i_APCI1564_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1564_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
-INT i_APCI1564_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1564_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				    struct comedi_insn *insn, unsigned int *data);
 
-//DO
+/* DO */
 int i_APCI1564_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				   struct comedi_insn *insn, unsigned int *data);
-INT i_APCI1564_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1564_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				  struct comedi_insn *insn, unsigned int *data);
-INT i_APCI1564_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI1564_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
 int i_APCI1564_ReadInterruptStatus(struct comedi_device *dev, struct comedi_subdevice *s,
 				   struct comedi_insn *insn, unsigned int *data);
 
-// TIMER
-// timer value is passed as u seconds
-INT i_APCI1564_ConfigTimerCounterWatchdog(struct comedi_device *dev,
+/*
+* TIMER timer value is passed as u seconds
+*/
+int i_APCI1564_ConfigTimerCounterWatchdog(struct comedi_device *dev,
 					  struct comedi_subdevice *s,
 					  struct comedi_insn *insn, unsigned int *data);
 int i_APCI1564_StartStopWriteTimerCounterWatchdog(struct comedi_device *dev,
@@ -112,8 +114,8 @@
 					struct comedi_subdevice *s,
 					struct comedi_insn *insn, unsigned int *data);
 
-// INTERRUPT
+/* intERRUPT */
 static void v_APCI1564_Interrupt(int irq, void *d);
 
-// RESET
-INT i_APCI1564_Reset(struct comedi_device *dev);
+/* RESET */
+int i_APCI1564_Reset(struct comedi_device *dev);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci16xx.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci16xx.c
index 906d635..988e3fc 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci16xx.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci16xx.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -57,7 +57,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT   i_APCI16XX_InsnConfigInitTTLIO                   |
+| Function Name     : int   i_APCI16XX_InsnConfigInitTTLIO                   |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -69,11 +69,11 @@
 |                for you call any other function witch access of TTL.        |
 |                APCI16XX_TTL_INITDIRECTION(user inputs for direction)       |
 +----------------------------------------------------------------------------+
-| Input Parameters  : b_InitType    = (BYTE) data[0];                        |
-|                     b_Port0Mode   = (BYTE) data[1];                        |
-|                     b_Port1Mode   = (BYTE) data[2];                        |
-|                     b_Port2Mode   = (BYTE) data[3];                        |
-|                     b_Port3Mode   = (BYTE) data[4];                        |
+| Input Parameters  : b_InitType    = (unsigned char) data[0];                        |
+|                     b_Port0Mode   = (unsigned char) data[1];                        |
+|                     b_Port1Mode   = (unsigned char) data[2];                        |
+|                     b_Port2Mode   = (unsigned char) data[3];                        |
+|                     b_Port3Mode   = (unsigned char) data[4];                        |
 |                     ........                                               |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -90,14 +90,14 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI16XX_InsnConfigInitTTLIO(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI16XX_InsnConfigInitTTLIO(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_Command = 0;
-	BYTE b_Cpt = 0;
-	BYTE b_NumberOfPort =
-		(BYTE) (devpriv->ps_BoardInfo->i_NbrTTLChannel / 8);
+	int i_ReturnValue = insn->n;
+	unsigned char b_Command = 0;
+	unsigned char b_Cpt = 0;
+	unsigned char b_NumberOfPort =
+		(unsigned char) (devpriv->ps_BoardInfo->i_NbrTTLChannel / 8);
 
 	/************************/
 	/* Test the buffer size */
@@ -108,7 +108,7 @@
 		/* Get the command */
 		/* **************** */
 
-		b_Command = (BYTE) data[0];
+		b_Command = (unsigned char) data[0];
 
 	   /********************/
 		/* Test the command */
@@ -122,7 +122,7 @@
 	      /***************************************/
 
 			if ((b_Command == APCI16XX_TTL_INITDIRECTION)
-				&& ((BYTE) (insn->n - 1) != b_NumberOfPort)) {
+				&& ((unsigned char) (insn->n - 1) != b_NumberOfPort)) {
 		 /*******************/
 				/* Data size error */
 		 /*******************/
@@ -132,7 +132,7 @@
 			}
 
 			if ((b_Command == APCI16XX_TTL_OUTPUTMEMORY)
-				&& ((BYTE) (insn->n) != 2)) {
+				&& ((unsigned char) (insn->n) != 2)) {
 		 /*******************/
 				/* Data size error */
 		 /*******************/
@@ -182,8 +182,8 @@
 		 /************************/
 
 				printk("\nPort %d direction selection error",
-					(INT) b_Cpt);
-				i_ReturnValue = -(INT) b_Cpt;
+					(int) b_Cpt);
+				i_ReturnValue = -(int) b_Cpt;
 			}
 
 	      /**************************/
@@ -239,7 +239,7 @@
 		}
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -250,7 +250,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT     i_APCI16XX_InsnBitsReadTTLIO                   |
+| Function Name     : int     i_APCI16XX_InsnBitsReadTTLIO                   |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -266,11 +266,11 @@
 |              APCI16XX_TTL_READCHANNEL                                      |
 |                    b_SelectedPort= CR_RANGE(insn->chanspec);               |
 |                    b_InputChannel= CR_CHAN(insn->chanspec);                |
-|                    b_ReadType	  = (BYTE) data[0];                          |
+|                    b_ReadType	  = (unsigned char) data[0];                          |
 |                                                                            |
 |              APCI16XX_TTL_READPORT                                         |
 |                    b_SelectedPort= CR_RANGE(insn->chanspec);               |
-|                    b_ReadType	  = (BYTE) data[0];                          |
+|                    b_ReadType	  = (unsigned char) data[0];                          |
 +----------------------------------------------------------------------------+
 | Output Parameters : data[0]    0 : Channle is not active                   |
 |                                1 : Channle is active                       |
@@ -283,17 +283,17 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI16XX_InsnBitsReadTTLIO(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI16XX_InsnBitsReadTTLIO(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_Command = 0;
-	BYTE b_NumberOfPort =
-		(BYTE) (devpriv->ps_BoardInfo->i_NbrTTLChannel / 8);
-	BYTE b_SelectedPort = CR_RANGE(insn->chanspec);
-	BYTE b_InputChannel = CR_CHAN(insn->chanspec);
-	BYTE *pb_Status;
-	DWORD dw_Status;
+	int i_ReturnValue = insn->n;
+	unsigned char b_Command = 0;
+	unsigned char b_NumberOfPort =
+		(unsigned char) (devpriv->ps_BoardInfo->i_NbrTTLChannel / 8);
+	unsigned char b_SelectedPort = CR_RANGE(insn->chanspec);
+	unsigned char b_InputChannel = CR_CHAN(insn->chanspec);
+	unsigned char *pb_Status;
+	unsigned int dw_Status;
 
 	/************************/
 	/* Test the buffer size */
@@ -304,7 +304,7 @@
 		/* Get the command */
 		/* **************** */
 
-		b_Command = (BYTE) data[0];
+		b_Command = (unsigned char) data[0];
 
 	   /********************/
 		/* Test the command */
@@ -380,7 +380,7 @@
 	/**************************/
 
 	if (i_ReturnValue >= 0) {
-		pb_Status = (PBYTE) & data[0];
+		pb_Status = (unsigned char *) &data[0];
 
 	   /*******************************/
 		/* Get the digital inpu status */
@@ -394,7 +394,7 @@
 		/* Save the port value */
 	   /***********************/
 
-		*pb_Status = (BYTE) dw_Status;
+		*pb_Status = (unsigned char) dw_Status;
 
 	   /***************************************/
 		/* Test if read channel status command */
@@ -405,12 +405,12 @@
 		}
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT i_APCI16XX_InsnReadTTLIOAllPortValue               |
+| Function Name     : int i_APCI16XX_InsnReadTTLIOAllPortValue               |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -430,13 +430,13 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI16XX_InsnReadTTLIOAllPortValue(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI16XX_InsnReadTTLIOAllPortValue(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	BYTE b_Command = (BYTE) CR_AREF(insn->chanspec);
-	INT i_ReturnValue = insn->n;
-	BYTE b_Cpt = 0;
-	BYTE b_NumberOfPort = 0;
+	unsigned char b_Command = (unsigned char) CR_AREF(insn->chanspec);
+	int i_ReturnValue = insn->n;
+	unsigned char b_Cpt = 0;
+	unsigned char b_NumberOfPort = 0;
 	unsigned int *pls_ReadData = data;
 
 	/********************/
@@ -450,7 +450,7 @@
 	   /**********************************/
 
 		b_NumberOfPort =
-			(BYTE) (devpriv->ps_BoardInfo->i_NbrTTLChannel / 32);
+			(unsigned char) (devpriv->ps_BoardInfo->i_NbrTTLChannel / 32);
 		if ((b_NumberOfPort * 32) <
 			devpriv->ps_BoardInfo->i_NbrTTLChannel) {
 			b_NumberOfPort = b_NumberOfPort + 1;
@@ -524,7 +524,7 @@
 		i_ReturnValue = -100;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -535,7 +535,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT     i_APCI16XX_InsnBitsWriteTTLIO                  |
+| Function Name     : int     i_APCI16XX_InsnBitsWriteTTLIO                  |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -551,11 +551,11 @@
 |              APCI16XX_TTL_WRITECHANNEL_ON | APCI16XX_TTL_WRITECHANNEL_OFF  |
 |                    b_SelectedPort = CR_RANGE(insn->chanspec);              |
 |                    b_OutputChannel= CR_CHAN(insn->chanspec);               |
-|                    b_Command      = (BYTE) data[0];                        |
+|                    b_Command      = (unsigned char) data[0];                        |
 |                                                                            |
 |              APCI16XX_TTL_WRITEPORT_ON | APCI16XX_TTL_WRITEPORT_OFF        |
 |                    b_SelectedPort = CR_RANGE(insn->chanspec);              |
-|                    b_Command      = (BYTE) data[0];                        |
+|                    b_Command      = (unsigned char) data[0];                        |
 +----------------------------------------------------------------------------+
 | Output Parameters : data[0] : TTL output port 0 to 3 data                  |
 |                     data[1] : TTL output port 4 to 7 data                  |
@@ -570,16 +570,16 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI16XX_InsnBitsWriteTTLIO(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI16XX_InsnBitsWriteTTLIO(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_Command = 0;
-	BYTE b_NumberOfPort =
-		(BYTE) (devpriv->ps_BoardInfo->i_NbrTTLChannel / 8);
-	BYTE b_SelectedPort = CR_RANGE(insn->chanspec);
-	BYTE b_OutputChannel = CR_CHAN(insn->chanspec);
-	DWORD dw_Status = 0;
+	int i_ReturnValue = insn->n;
+	unsigned char b_Command = 0;
+	unsigned char b_NumberOfPort =
+		(unsigned char) (devpriv->ps_BoardInfo->i_NbrTTLChannel / 8);
+	unsigned char b_SelectedPort = CR_RANGE(insn->chanspec);
+	unsigned char b_OutputChannel = CR_CHAN(insn->chanspec);
+	unsigned int dw_Status = 0;
 
 	/************************/
 	/* Test the buffer size */
@@ -590,7 +590,7 @@
 		/* Get the command */
 		/* **************** */
 
-		b_Command = (BYTE) data[0];
+		b_Command = (unsigned char) data[0];
 
 	   /********************/
 		/* Test the command */
@@ -758,7 +758,7 @@
 			devpriv->iobase + 20 + ((b_SelectedPort / 4) * 4));
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -774,7 +774,7 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI16XX_Reset(struct comedi_device * dev)
+int i_APCI16XX_Reset(struct comedi_device *dev)
 {
 	return 0;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2016.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2016.c
index 31f55da..457917f 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2016.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2016.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -62,7 +62,7 @@
 | Task              : Configures The Digital Output Subdevice.               |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 |			  data[0]            : 1 Digital Memory On               |
@@ -75,20 +75,20 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI2016_ConfigDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2016_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if ((data[0] != 0) && (data[0] != 1)) {
 		comedi_error(dev,
 			"Not a valid Data !!! ,Data should be 1 or 0\n");
 		return -EINVAL;
-	}			// if  ((data[0]!=0) && (data[0]!=1))
+	}			/*  if  ((data[0]!=0) && (data[0]!=1)) */
 	if (data[0]) {
 		devpriv->b_OutputMemoryStatus = ADDIDATA_ENABLE;
-	}			// if  (data[0]
+	}			/*  if  (data[0] */
 	else {
 		devpriv->b_OutputMemoryStatus = ADDIDATA_DISABLE;
-	}			// else if  (data[0]
+	}			/*  else if  (data[0] */
 	return insn->n;
 }
 
@@ -101,8 +101,8 @@
 | Task              : Writes port value  To the selected port                |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To Write      |
-|                     UINT *data              : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To Write      |
+|                     unsigned int *data              : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -111,34 +111,34 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI2016_WriteDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2016_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_NoOfChannel;
-	UINT ui_Temp, ui_Temp1;
+	unsigned int ui_NoOfChannel;
+	unsigned int ui_Temp, ui_Temp1;
 	ui_NoOfChannel = CR_CHAN(insn->chanspec);
 	if ((ui_NoOfChannel < 0) || (ui_NoOfChannel > 15)) {
 		comedi_error(dev,
 			"Invalid Channel Numbers !!!, Channel Numbers must be between 0 and 15\n");
 		return -EINVAL;
-	}			// if  ((ui_NoOfChannel<0) || (ui_NoOfChannel>15))
+	}			/*  if  ((ui_NoOfChannel<0) || (ui_NoOfChannel>15)) */
 	if (devpriv->b_OutputMemoryStatus) {
 		ui_Temp = inw(devpriv->iobase + APCI2016_DIGITAL_OP);
-	}			// if  (devpriv->b_OutputMemoryStatus )
+	}			/*  if  (devpriv->b_OutputMemoryStatus ) */
 	else {
 		ui_Temp = 0;
-	}			// else if  (devpriv->b_OutputMemoryStatus )
+	}			/*  else if  (devpriv->b_OutputMemoryStatus ) */
 	if ((data[1] != 0) && (data[1] != 1)) {
 		comedi_error(dev,
 			"Invalid Data[1] value !!!, Data[1] should be 0 or 1\n");
 		return -EINVAL;
-	}			// if  ((data[1]!=0) && (data[1]!=1))
+	}			/*  if  ((data[1]!=0) && (data[1]!=1)) */
 
 	if (data[3] == 0) {
 		if (data[1] == 0) {
 			data[0] = (data[0] << ui_NoOfChannel) | ui_Temp;
 			outw(data[0], devpriv->iobase + APCI2016_DIGITAL_OP);
-		}		// if (data[1]==0)
+		}		/*  if (data[1]==0) */
 		else {
 			if (data[1] == 1) {
 				switch (ui_NoOfChannel) {
@@ -162,16 +162,16 @@
 					break;
 				default:
 					comedi_error(dev, " chan spec wrong");
-					return -EINVAL;	// "sorry channel spec wrong "
-				}	//switch(ui_NoOfChannels)
+					return -EINVAL;	/*  "sorry channel spec wrong " */
+				}	/* switch(ui_NoOfChannels) */
 				outw(data[0],
 					devpriv->iobase + APCI2016_DIGITAL_OP);
-			}	// if  (data[1]==1)
+			}	/*  if  (data[1]==1) */
 			else {
 				printk("\nSpecified channel not supported\n");
-			}	// else if  (data[1]==1)
-		}		// else if (data[1]==0)
-	}			// if (data[3]==0)
+			}	/*  else if  (data[1]==1) */
+		}		/*  else if (data[1]==0) */
+	}			/*  if (data[3]==0) */
 	else {
 		if (data[3] == 1) {
 			if (data[1] == 0) {
@@ -183,7 +183,7 @@
 				data[0] = data[0] & ui_Temp;
 				outw(data[0],
 					devpriv->iobase + APCI2016_DIGITAL_OP);
-			}	// if  (data[1]==0)
+			}	/*  if  (data[1]==0) */
 			else {
 				if (data[1] == 1) {
 					switch (ui_NoOfChannel) {
@@ -228,22 +228,22 @@
 					default:
 						comedi_error(dev,
 							" chan spec wrong");
-						return -EINVAL;	// "sorry channel spec wrong "
-					}	//switch(ui_NoOfChannels)
+						return -EINVAL;	/*  "sorry channel spec wrong " */
+					}	/* switch(ui_NoOfChannels) */
 					outw(data[0],
 						devpriv->iobase +
 						APCI2016_DIGITAL_OP);
-				}	// if(data[1]==1)
+				}	/*  if(data[1]==1) */
 				else {
 					printk("\nSpecified channel not supported\n");
-				}	//else if(data[1]==1)
-			}	//elseif(data[1]==0)
-		}		//if(data[3]==1);
+				}	/* else if(data[1]==1) */
+			}	/* elseif(data[1]==0) */
+		}		/* if(data[3]==1); */
 		else {
 			printk("\nSpecified functionality does not exist\n");
 			return -EINVAL;
-		}		//if else data[3]==1)
-	}			//if else data[3]==0)
+		}		/* if else data[3]==1) */
+	}			/* if else data[3]==0) */
 	return insn->n;
 }
 
@@ -256,8 +256,8 @@
 | Task              : Read  value  of the selected channel or port           |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To read       |
-|                     UINT *data              : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To read       |
+|                     unsigned int *data              : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -266,27 +266,27 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI2016_BitsDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2016_BitsDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp;
-	UINT ui_NoOfChannel;
+	unsigned int ui_Temp;
+	unsigned int ui_NoOfChannel;
 	ui_NoOfChannel = CR_CHAN(insn->chanspec);
 	if ((ui_NoOfChannel < 0) || (ui_NoOfChannel > 15)) {
 		comedi_error(dev,
 			"Invalid Channel Numbers !!!, Channel Numbers must be between 0 and 15\n");
 		return -EINVAL;
-	}			// if  ((ui_NoOfChannel<0) || (ui_NoOfChannel>15))
+	}			/*  if  ((ui_NoOfChannel<0) || (ui_NoOfChannel>15)) */
 	if ((data[0] != 0) && (data[0] != 1)) {
 		comedi_error(dev,
 			"Invalid Data[0] value !!!, Data[0] should be 0 or 1\n");
 		return -EINVAL;
-	}			// if  ((data[0]!=0) && (data[0]!=1))
+	}			/*  if  ((data[0]!=0) && (data[0]!=1)) */
 	ui_Temp = data[0];
 	*data = inw(devpriv->iobase + APCI2016_DIGITAL_OP_RW);
 	if (ui_Temp == 0) {
 		*data = (*data >> ui_NoOfChannel) & 0x1;
-	}			// if  (ui_Temp==0)
+	}			/*  if  (ui_Temp==0) */
 	else {
 		if (ui_Temp == 1) {
 			switch (ui_NoOfChannel) {
@@ -307,13 +307,13 @@
 
 			default:
 				comedi_error(dev, " chan spec wrong");
-				return -EINVAL;	// "sorry channel spec wrong "
-			}	//switch(ui_NoOfChannel)
-		}		// if  (ui_Temp==1)
+				return -EINVAL;	/*  "sorry channel spec wrong " */
+			}	/* switch(ui_NoOfChannel) */
+		}		/*  if  (ui_Temp==1) */
 		else {
 			printk("\nSpecified channel not supported \n");
-		}		// else if  (ui_Temp==1)
-	}			// if  (ui_Temp==0)
+		}		/*  else if  (ui_Temp==1) */
+	}			/*  if  (ui_Temp==0) */
 	return insn->n;
 }
 
@@ -337,16 +337,16 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI2016_ConfigWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2016_ConfigWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
 	if (data[0] == 0) {
-		//Disable the watchdog
+		/* Disable the watchdog */
 		outw(0x0,
 			devpriv->i_IobaseAddon +
 			APCI2016_WATCHDOG_ENABLEDISABLE);
-		//Loading the Reload value
+		/* Loading the Reload value */
 		outw(data[1],
 			devpriv->i_IobaseAddon +
 			APCI2016_WATCHDOG_RELOAD_VALUE);
@@ -380,20 +380,20 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI2016_StartStopWriteWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2016_StartStopWriteWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
 	switch (data[0]) {
-	case 0:		//stop the watchdog
-		outw(0x0, devpriv->i_IobaseAddon + APCI2016_WATCHDOG_ENABLEDISABLE);	//disable the watchdog
+	case 0:		/* stop the watchdog */
+		outw(0x0, devpriv->i_IobaseAddon + APCI2016_WATCHDOG_ENABLEDISABLE);	/* disable the watchdog */
 		break;
-	case 1:		//start the watchdog
+	case 1:		/* start the watchdog */
 		outw(0x0001,
 			devpriv->i_IobaseAddon +
 			APCI2016_WATCHDOG_ENABLEDISABLE);
 		break;
-	case 2:		//Software trigger
+	case 2:		/* Software trigger */
 		outw(0x0201,
 			devpriv->i_IobaseAddon +
 			APCI2016_WATCHDOG_ENABLEDISABLE);
@@ -401,7 +401,7 @@
 	default:
 		printk("\nSpecified functionality does not exist\n");
 		return -EINVAL;
-	}			// switch(data[0])
+	}			/*  switch(data[0]) */
 
 	return insn->n;
 }
@@ -427,8 +427,8 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI2016_ReadWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2016_ReadWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	udelay(5);
 	data[0] = inw(devpriv->i_IobaseAddon + APCI2016_WATCHDOG_STATUS) & 0x1;
@@ -450,9 +450,9 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI2016_Reset(struct comedi_device * dev)
+int i_APCI2016_Reset(struct comedi_device *dev)
 {
-	outw(0x0, devpriv->iobase + APCI2016_DIGITAL_OP);	// Resets the digital output channels
+	outw(0x0, devpriv->iobase + APCI2016_DIGITAL_OP);	/*  Resets the digital output channels */
 	outw(0x0, devpriv->i_IobaseAddon + APCI2016_WATCHDOG_ENABLEDISABLE);
 	outw(0x0, devpriv->i_IobaseAddon + APCI2016_WATCHDOG_RELOAD_VALUE);
 	outw(0x0, devpriv->i_IobaseAddon + APCI2016_WATCHDOG_RELOAD_VALUE + 2);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2016.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2016.h
index 9261aac..639944c 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2016.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2016.h
@@ -19,17 +19,17 @@
 #define APCI2016_BOARD_VENDOR_ID 0x15B8
 #define APCI2016_ADDRESS_RANGE   8
 
-//DIGITAL INPUT-OUTPUT DEFINE
+/* DIGITAL INPUT-OUTPUT DEFINE */
 
 #define APCI2016_DIGITAL_OP                 	0x04
 #define APCI2016_DIGITAL_OP_RW                 	4
 
-//ADDIDATA Enable Disable
+/* ADDIDATA Enable Disable */
 
 #define ADDIDATA_ENABLE                            1
 #define ADDIDATA_DISABLE                           0
 
-// TIMER COUNTER WATCHDOG DEFINES
+/* TIMER COUNTER WATCHDOG DEFINES */
 
 #define ADDIDATA_WATCHDOG                          2
 #define APCI2016_DIGITAL_OP_WATCHDOG               0
@@ -37,9 +37,9 @@
 #define APCI2016_WATCHDOG_RELOAD_VALUE             4
 #define APCI2016_WATCHDOG_STATUS                   16
 
-// Hardware Layer  functions for Apci2016
+/* Hardware Layer  functions for Apci2016 */
 
-//DO
+/* DO */
 int i_APCI2016_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				   struct comedi_insn *insn, unsigned int *data);
 
@@ -49,8 +49,10 @@
 int i_APCI2016_BitsDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
 
-// TIMER
-// timer value is passed as u seconds
+/*
+* TIMER
+* timer value is passed as u seconds
+*/
 
 int i_APCI2016_ConfigWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
 			      struct comedi_insn *insn, unsigned int *data);
@@ -61,10 +63,10 @@
 int i_APCI2016_ReadWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
 			    struct comedi_insn *insn, unsigned int *data);
 
-// Interrupt functions.....
+/* Interrupt functions..... */
 
-// void v_APCI2016_Interrupt(int irq, void *d) ;
+/* void v_APCI2016_Interrupt(int irq, void *d); */
 
- //void v_APCI2016_Interrupt(int irq, void *d);
-// RESET
-INT i_APCI2016_Reset(struct comedi_device *dev);
+/* void v_APCI2016_Interrupt(int irq, void *d); */
+/* RESET */
+int i_APCI2016_Reset(struct comedi_device *dev);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2032.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2032.c
index 1347bc3..ec81708 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2032.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2032.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -53,7 +53,7 @@
 */
 
 #include "hwdrv_apci2032.h"
-UINT ui_InterruptData, ui_Type;
+unsigned int ui_InterruptData, ui_Type;
 /*
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI2032_ConfigDigitalOutput                     |
@@ -63,7 +63,7 @@
 | Task              : Configures The Digital Output Subdevice.               |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 |					  data[1]            : 1 Enable  VCC  Interrupt  |
@@ -79,36 +79,36 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI2032_ConfigDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2032_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	ULONG ul_Command = 0;
+	unsigned int ul_Command = 0;
 	devpriv->tsk_Current = current;
 
 	if ((data[0] != 0) && (data[0] != 1)) {
 		comedi_error(dev,
 			"Not a valid Data !!! ,Data should be 1 or 0\n");
 		return -EINVAL;
-	}			//if  ( (data[0]!=0) && (data[0]!=1) )
+	}			/* if  ( (data[0]!=0) && (data[0]!=1) ) */
 	if (data[0]) {
 		devpriv->b_OutputMemoryStatus = ADDIDATA_ENABLE;
-	}			// if  (data[0])
+	}			/*  if  (data[0]) */
 	else {
 		devpriv->b_OutputMemoryStatus = ADDIDATA_DISABLE;
-	}			//else if  (data[0])
+	}			/* else if  (data[0]) */
 
 	if (data[1] == ADDIDATA_ENABLE) {
 		ul_Command = ul_Command | 0x1;
-	}			//if  (data[1] == ADDIDATA_ENABLE)
+	}			/* if  (data[1] == ADDIDATA_ENABLE) */
 	else {
 		ul_Command = ul_Command & 0xFFFFFFFE;
-	}			//elseif  (data[1] == ADDIDATA_ENABLE)
+	}			/* elseif  (data[1] == ADDIDATA_ENABLE) */
 	if (data[2] == ADDIDATA_ENABLE) {
 		ul_Command = ul_Command | 0x2;
-	}			//if  (data[2] == ADDIDATA_ENABLE)
+	}			/* if  (data[2] == ADDIDATA_ENABLE) */
 	else {
 		ul_Command = ul_Command & 0xFFFFFFFD;
-	}			//elseif  (data[2] == ADDIDATA_ENABLE)
+	}			/* elseif  (data[2] == ADDIDATA_ENABLE) */
 	outl(ul_Command, devpriv->iobase + APCI2032_DIGITAL_OP_INTERRUPT);
 	ui_InterruptData = inl(devpriv->iobase + APCI2032_DIGITAL_OP_INTERRUPT);
 	return insn->n;
@@ -123,8 +123,8 @@
 | Task              : Writes port value  To the selected port                |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To Write      |
-|                     UINT *data              : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To Write      |
+|                     unsigned int *data              : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -134,23 +134,23 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI2032_WriteDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2032_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp, ui_Temp1;
-	UINT ui_NoOfChannel = CR_CHAN(insn->chanspec);	// get the channel
+	unsigned int ui_Temp, ui_Temp1;
+	unsigned int ui_NoOfChannel = CR_CHAN(insn->chanspec);	/*  get the channel */
 	if (devpriv->b_OutputMemoryStatus) {
 		ui_Temp = inl(devpriv->iobase + APCI2032_DIGITAL_OP);
 
-	}			//if(devpriv->b_OutputMemoryStatus )
+	}			/* if(devpriv->b_OutputMemoryStatus ) */
 	else {
 		ui_Temp = 0;
-	}			//if(devpriv->b_OutputMemoryStatus )
+	}			/* if(devpriv->b_OutputMemoryStatus ) */
 	if (data[3] == 0) {
 		if (data[1] == 0) {
 			data[0] = (data[0] << ui_NoOfChannel) | ui_Temp;
 			outl(data[0], devpriv->iobase + APCI2032_DIGITAL_OP);
-		}		//if(data[1]==0)
+		}		/* if(data[1]==0) */
 		else {
 			if (data[1] == 1) {
 				switch (ui_NoOfChannel) {
@@ -184,18 +184,18 @@
 
 				default:
 					comedi_error(dev, " chan spec wrong");
-					return -EINVAL;	// "sorry channel spec wrong "
+					return -EINVAL;	/*  "sorry channel spec wrong " */
 
-				}	//switch(ui_NoOfChannels)
+				}	/* switch(ui_NoOfChannels) */
 
 				outl(data[0],
 					devpriv->iobase + APCI2032_DIGITAL_OP);
-			}	// if(data[1]==1)
+			}	/*  if(data[1]==1) */
 			else {
 				printk("\nSpecified channel not supported\n");
-			}	//else if(data[1]==1)
-		}		//elseif(data[1]==0)
-	}			//if(data[3]==0)
+			}	/* else if(data[1]==1) */
+		}		/* elseif(data[1]==0) */
+	}			/* if(data[3]==0) */
 	else {
 		if (data[3] == 1) {
 			if (data[1] == 0) {
@@ -209,7 +209,7 @@
 				data[0] = data[0] & ui_Temp;
 				outl(data[0],
 					devpriv->iobase + APCI2032_DIGITAL_OP);
-			}	//if(data[1]==0)
+			}	/* if(data[1]==0) */
 			else {
 				if (data[1] == 1) {
 					switch (ui_NoOfChannel) {
@@ -272,25 +272,25 @@
 					default:
 						comedi_error(dev,
 							" chan spec wrong");
-						return -EINVAL;	// "sorry channel spec wrong "
+						return -EINVAL;	/*  "sorry channel spec wrong " */
 
-					}	//switch(ui_NoOfChannels)
+					}	/* switch(ui_NoOfChannels) */
 
 					outl(data[0],
 						devpriv->iobase +
 						APCI2032_DIGITAL_OP);
-				}	// if(data[1]==1)
+				}	/*  if(data[1]==1) */
 				else {
 					printk("\nSpecified channel not supported\n");
-				}	//else if(data[1]==1)
-			}	//elseif(data[1]==0)
-		}		//if(data[3]==1);
+				}	/* else if(data[1]==1) */
+			}	/* elseif(data[1]==0) */
+		}		/* if(data[3]==1); */
 		else {
 			printk("\nSpecified functionality does not exist\n");
 			return -EINVAL;
-		}		//if else data[3]==1)
-	}			//if else data[3]==0)
-	return (insn->n);;
+		}		/* if else data[3]==1) */
+	}			/* if else data[3]==0) */
+	return insn->n;
 }
 
 /*
@@ -302,8 +302,8 @@
 | Task              : Read  value  of the selected channel or port           |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To read       |
-|                     UINT *data              : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To read       |
+|                     unsigned int *data              : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -313,17 +313,17 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI2032_ReadDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2032_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp;
-	UINT ui_NoOfChannel;
+	unsigned int ui_Temp;
+	unsigned int ui_NoOfChannel;
 	ui_NoOfChannel = CR_CHAN(insn->chanspec);
 	ui_Temp = data[0];
 	*data = inl(devpriv->iobase + APCI2032_DIGITAL_OP_RW);
 	if (ui_Temp == 0) {
 		*data = (*data >> ui_NoOfChannel) & 0x1;
-	}			//if  (ui_Temp==0)
+	}			/* if  (ui_Temp==0) */
 	else {
 		if (ui_Temp == 1) {
 			switch (ui_NoOfChannel) {
@@ -349,28 +349,28 @@
 
 			default:
 				comedi_error(dev, " chan spec wrong");
-				return -EINVAL;	// "sorry channel spec wrong "
+				return -EINVAL;	/*  "sorry channel spec wrong " */
 
-			}	//switch(ui_NoOfChannels)
-		}		//if  (ui_Temp==1)
+			}	/* switch(ui_NoOfChannels) */
+		}		/* if  (ui_Temp==1) */
 		else {
 			printk("\nSpecified channel not supported \n");
-		}		//elseif  (ui_Temp==1)
+		}		/* elseif  (ui_Temp==1) */
 	}
 	return insn->n;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function   Name   : INT i_APCI2032_ConfigWatchdog(comedi_device
-                   *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)|
+| Function   Name   : int i_APCI2032_ConfigWatchdog(comedi_device
+|                   *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)|
 |				                                                     |
 +----------------------------------------------------------------------------+
 | Task              : Configures The Watchdog                                |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                      struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data          : Data Pointer to read status                                                                                                             |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -380,15 +380,15 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI2032_ConfigWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2032_ConfigWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (data[0] == 0) {
-		//Disable the watchdog
+		/* Disable the watchdog */
 		outl(0x0,
 			devpriv->iobase + APCI2032_DIGITAL_OP_WATCHDOG +
 			APCI2032_TCW_PROG);
-		//Loading the Reload value
+		/* Loading the Reload value */
 		outl(data[1],
 			devpriv->iobase + APCI2032_DIGITAL_OP_WATCHDOG +
 			APCI2032_TCW_RELOAD_VALUE);
@@ -421,19 +421,19 @@
     +----------------------------------------------------------------------------+
   */
 
-int i_APCI2032_StartStopWriteWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2032_StartStopWriteWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	switch (data[0]) {
-	case 0:		//stop the watchdog
-		outl(0x0, devpriv->iobase + APCI2032_DIGITAL_OP_WATCHDOG + APCI2032_TCW_PROG);	//disable the watchdog
+	case 0:		/* stop the watchdog */
+		outl(0x0, devpriv->iobase + APCI2032_DIGITAL_OP_WATCHDOG + APCI2032_TCW_PROG);	/* disable the watchdog */
 		break;
-	case 1:		//start the watchdog
+	case 1:		/* start the watchdog */
 		outl(0x0001,
 			devpriv->iobase + APCI2032_DIGITAL_OP_WATCHDOG +
 			APCI2032_TCW_PROG);
 		break;
-	case 2:		//Software trigger
+	case 2:		/* Software trigger */
 		outl(0x0201,
 			devpriv->iobase + APCI2032_DIGITAL_OP_WATCHDOG +
 			APCI2032_TCW_PROG);
@@ -449,13 +449,13 @@
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI2032_ReadWatchdog                            |
 |			(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
-                    unsigned int *data); 	                                     |
+|                    unsigned int *data); 	                                     |
 +----------------------------------------------------------------------------+
 | Task              : Read The Watchdog                                      |
 +----------------------------------------------------------------------------+
 | Input Parameters  :   struct comedi_device *dev      : Driver handle              |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                      struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data          : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -466,8 +466,8 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI2032_ReadWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2032_ReadWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
 	data[0] =
@@ -498,13 +498,13 @@
 	struct comedi_device *dev = d;
 	unsigned int ui_DO;
 
-	ui_DO = inl(devpriv->iobase + APCI2032_DIGITAL_OP_IRQ) & 0x1;	//Check if VCC OR CC interrupt has occured.
+	ui_DO = inl(devpriv->iobase + APCI2032_DIGITAL_OP_IRQ) & 0x1;	/* Check if VCC OR CC interrupt has occured. */
 
 	if (ui_DO == 0) {
 		printk("\nInterrupt from unKnown source\n");
-	}			// if(ui_DO==0)
+	}			/*  if(ui_DO==0) */
 	if (ui_DO) {
-		// Check for Digital Output interrupt Type - 1: Vcc interrupt 2: CC interrupt.
+		/*  Check for Digital Output interrupt Type - 1: Vcc interrupt 2: CC interrupt. */
 		ui_Type =
 			inl(devpriv->iobase +
 			APCI2032_DIGITAL_OP_INTERRUPT_STATUS) & 0x3;
@@ -512,16 +512,16 @@
 			devpriv->iobase + APCI2032_DIGITAL_OP +
 			APCI2032_DIGITAL_OP_INTERRUPT);
 		if (ui_Type == 1) {
-			//Sends signal to user space
+			/* Sends signal to user space */
 			send_sig(SIGIO, devpriv->tsk_Current, 0);
-		}		// if (ui_Type==1)
+		}		/*  if (ui_Type==1) */
 		else {
 			if (ui_Type == 2) {
-				// Sends signal to user space
+				/*  Sends signal to user space */
 				send_sig(SIGIO, devpriv->tsk_Current, 0);
-			}	//if (ui_Type==2)
-		}		//else if (ui_Type==1)
-	}			//if(ui_DO)
+			}	/* if (ui_Type==2) */
+		}		/* else if (ui_Type==1) */
+	}			/* if(ui_DO) */
 
 	return;
 
@@ -544,8 +544,8 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI2032_ReadInterruptStatus(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2032_ReadInterruptStatus(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	*data = ui_Type;
 	return insn->n;
@@ -567,13 +567,13 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI2032_Reset(struct comedi_device * dev)
+int i_APCI2032_Reset(struct comedi_device *dev)
 {
 	devpriv->b_DigitalOutputRegister = 0;
 	ui_Type = 0;
-	outl(0x0, devpriv->iobase + APCI2032_DIGITAL_OP);	//Resets the output channels
-	outl(0x0, devpriv->iobase + APCI2032_DIGITAL_OP_INTERRUPT);	//Disables the interrupt.
-	outl(0x0, devpriv->iobase + APCI2032_DIGITAL_OP_WATCHDOG + APCI2032_TCW_PROG);	//disable the watchdog
-	outl(0x0, devpriv->iobase + APCI2032_DIGITAL_OP_WATCHDOG + APCI2032_TCW_RELOAD_VALUE);	//reload=0
+	outl(0x0, devpriv->iobase + APCI2032_DIGITAL_OP);	/* Resets the output channels */
+	outl(0x0, devpriv->iobase + APCI2032_DIGITAL_OP_INTERRUPT);	/* Disables the interrupt. */
+	outl(0x0, devpriv->iobase + APCI2032_DIGITAL_OP_WATCHDOG + APCI2032_TCW_PROG);	/* disable the watchdog */
+	outl(0x0, devpriv->iobase + APCI2032_DIGITAL_OP_WATCHDOG + APCI2032_TCW_RELOAD_VALUE);	/* reload=0 */
 	return 0;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2032.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2032.h
index 55002e0..c971d14 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2032.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2032.h
@@ -17,32 +17,32 @@
 
 /*********      Definitions for APCI-2032 card  *****/
 
-// Card Specific information
+/* Card Specific information */
 #define APCI2032_BOARD_VENDOR_ID                 0x15B8
 #define APCI2032_ADDRESS_RANGE                   63
 
-//DIGITAL INPUT-OUTPUT DEFINE
+/* DIGITAL INPUT-OUTPUT DEFINE */
 
 #define APCI2032_DIGITAL_OP                 	0
 #define APCI2032_DIGITAL_OP_RW                 	0
 #define APCI2032_DIGITAL_OP_INTERRUPT           4
 #define APCI2032_DIGITAL_OP_IRQ                 12
 
-//Digital Output Interrupt Status
+/* Digital Output Interrupt Status */
 #define APCI2032_DIGITAL_OP_INTERRUPT_STATUS    8
 
-//Digital Output Interrupt Enable Disable.
+/* Digital Output Interrupt Enable Disable. */
 #define APCI2032_DIGITAL_OP_VCC_INTERRUPT_ENABLE   0x1
 #define APCI2032_DIGITAL_OP_VCC_INTERRUPT_DISABLE  0xFFFFFFFE
 #define APCI2032_DIGITAL_OP_CC_INTERRUPT_ENABLE    0x2
 #define APCI2032_DIGITAL_OP_CC_INTERRUPT_DISABLE   0xFFFFFFFD
 
-//ADDIDATA Enable Disable
+/* ADDIDATA Enable Disable */
 
 #define ADDIDATA_ENABLE                            1
 #define ADDIDATA_DISABLE                           0
 
-// TIMER COUNTER WATCHDOG DEFINES
+/* TIMER COUNTER WATCHDOG DEFINES */
 
 #define ADDIDATA_WATCHDOG                          2
 #define APCI2032_DIGITAL_OP_WATCHDOG               16
@@ -52,30 +52,32 @@
 #define APCI2032_TCW_TRIG_STATUS                   16
 #define APCI2032_TCW_IRQ                           20
 
-// Hardware Layer  functions for Apci2032
+/* Hardware Layer  functions for Apci2032 */
 
-//DO
+/* DO */
 int i_APCI2032_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				   struct comedi_insn *insn, unsigned int *data);
-INT i_APCI2032_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI2032_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				  struct comedi_insn *insn, unsigned int *data);
-INT i_APCI2032_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI2032_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
 int i_APCI2032_ReadInterruptStatus(struct comedi_device *dev, struct comedi_subdevice *s,
 				   struct comedi_insn *insn, unsigned int *data);
 
-// TIMER
-// timer value is passed as u seconds
-INT i_APCI2032_ConfigWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+/* TIMER
+ * timer value is passed as u seconds
+*/
+
+int i_APCI2032_ConfigWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
 			      struct comedi_insn *insn, unsigned int *data);
 int i_APCI2032_StartStopWriteWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
 				      struct comedi_insn *insn, unsigned int *data);
 int i_APCI2032_ReadWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
 			    struct comedi_insn *insn, unsigned int *data);
 
-// Interrupt functions.....
+/* Interrupt functions..... */
 
 void v_APCI2032_Interrupt(int irq, void *d);
 
-//Reset functions
+/* Reset functions */
 int i_APCI2032_Reset(struct comedi_device *dev);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2200.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2200.c
index 947e18e..a853c62 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2200.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2200.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -63,7 +63,7 @@
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
 |		       struct comedi_subdevice *s,   :pointer to subdevice structure
-                       struct comedi_insn *insn      :pointer to insn structure     |
+|                       struct comedi_insn *insn      :pointer to insn structure     |
 |                     unsigned int *data          : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -73,20 +73,20 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI2200_Read1DigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2200_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_TmpValue = 0;
-	UINT ui_Channel;
+	unsigned int ui_TmpValue = 0;
+	unsigned int ui_Channel;
 	ui_Channel = CR_CHAN(insn->chanspec);
 	if (ui_Channel >= 0 && ui_Channel <= 7) {
-		ui_TmpValue = (UINT) inw(devpriv->iobase + APCI2200_DIGITAL_IP);
+		ui_TmpValue = (unsigned int) inw(devpriv->iobase + APCI2200_DIGITAL_IP);
 		*data = (ui_TmpValue >> ui_Channel) & 0x1;
-	}			//if(ui_Channel >= 0 && ui_Channel <=7)
+	}			/* if(ui_Channel >= 0 && ui_Channel <=7) */
 	else {
 		printk("\nThe specified channel does not exist\n");
-		return -EINVAL;	// "sorry channel spec wrong "
-	}			//else if(ui_Channel >= 0 && ui_Channel <=7)
+		return -EINVAL;	/*  "sorry channel spec wrong " */
+	}			/* else if(ui_Channel >= 0 && ui_Channel <=7) */
 
 	return insn->n;
 }
@@ -101,7 +101,7 @@
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
 |                      struct comedi_subdevice *s,   :pointer to subdevice structure
-                       struct comedi_insn *insn      :pointer to insn structure     |
+|                       struct comedi_insn *insn      :pointer to insn structure     |
 |                      unsigned int *data         : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -112,17 +112,17 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI2200_ReadMoreDigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2200_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
-	UINT ui_PortValue = data[0];
-	UINT ui_Mask = 0;
-	UINT ui_NoOfChannels;
+	unsigned int ui_PortValue = data[0];
+	unsigned int ui_Mask = 0;
+	unsigned int ui_NoOfChannels;
 
 	ui_NoOfChannels = CR_CHAN(insn->chanspec);
 
-	*data = (UINT) inw(devpriv->iobase + APCI2200_DIGITAL_IP);
+	*data = (unsigned int) inw(devpriv->iobase + APCI2200_DIGITAL_IP);
 	switch (ui_NoOfChannels) {
 	case 2:
 		ui_Mask = 3;
@@ -137,9 +137,9 @@
 
 	default:
 		printk("\nWrong parameters\n");
-		return -EINVAL;	// "sorry channel spec wrong "
+		return -EINVAL;	/*  "sorry channel spec wrong " */
 		break;
-	}			//switch(ui_NoOfChannels)
+	}			/* switch(ui_NoOfChannels) */
 
 	return insn->n;
 }
@@ -147,7 +147,7 @@
 /*
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI2200_ConfigDigitalOutput (struct comedi_device *dev,
-                    struct comedi_subdevice *s struct comedi_insn *insn,unsigned int *data)    |
+|                    struct comedi_subdevice *s struct comedi_insn *insn,unsigned int *data)    |
 |				                                                     |
 +----------------------------------------------------------------------------+
 | Task              : Configures The Digital Output Subdevice.               |
@@ -156,7 +156,7 @@
 |                     unsigned int *data         : Data Pointer contains         |
 |                                          configuration parameters as below |
 |                      struct comedi_subdevice *s,   :pointer to subdevice structure
-                       struct comedi_insn *insn      :pointer to insn structure                                                           |
+|                       struct comedi_insn *insn      :pointer to insn structure                                                           |
 |					  data[0]  :1:Memory on                          |
 |					            0:Memory off                         |
 |										                             |
@@ -169,8 +169,8 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI2200_ConfigDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2200_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	devpriv->b_OutputMemoryStatus = data[0];
 	return insn->n;
@@ -180,13 +180,13 @@
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI2200_WriteDigitalOutput                      |
 |			(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
-                     unsigned int *data)                                         |
+|                     unsigned int *data)                                         |
 +----------------------------------------------------------------------------+
 | Task              : Writes port value  To the selected port                |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                      struct comedi_insn *insn      :pointer to insn structure      |
 |                    unsigned int *data           : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -197,23 +197,23 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI2200_WriteDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2200_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp, ui_Temp1;
-	UINT ui_NoOfChannel = CR_CHAN(insn->chanspec);	// get the channel
+	unsigned int ui_Temp, ui_Temp1;
+	unsigned int ui_NoOfChannel = CR_CHAN(insn->chanspec);	/*  get the channel */
 	if (devpriv->b_OutputMemoryStatus) {
 		ui_Temp = inw(devpriv->iobase + APCI2200_DIGITAL_OP);
 
-	}			//if(devpriv->b_OutputMemoryStatus )
+	}			/* if(devpriv->b_OutputMemoryStatus ) */
 	else {
 		ui_Temp = 0;
-	}			//if(devpriv->b_OutputMemoryStatus )
+	}			/* if(devpriv->b_OutputMemoryStatus ) */
 	if (data[3] == 0) {
 		if (data[1] == 0) {
 			data[0] = (data[0] << ui_NoOfChannel) | ui_Temp;
 			outw(data[0], devpriv->iobase + APCI2200_DIGITAL_OP);
-		}		//if(data[1]==0)
+		}		/* if(data[1]==0) */
 		else {
 			if (data[1] == 1) {
 				switch (ui_NoOfChannel) {
@@ -240,18 +240,18 @@
 					break;
 				default:
 					comedi_error(dev, " chan spec wrong");
-					return -EINVAL;	// "sorry channel spec wrong "
+					return -EINVAL;	/*  "sorry channel spec wrong " */
 
-				}	//switch(ui_NoOfChannels)
+				}	/* switch(ui_NoOfChannels) */
 
 				outw(data[0],
 					devpriv->iobase + APCI2200_DIGITAL_OP);
-			}	// if(data[1]==1)
+			}	/*  if(data[1]==1) */
 			else {
 				printk("\nSpecified channel not supported\n");
-			}	//else if(data[1]==1)
-		}		//elseif(data[1]==0)
-	}			//if(data[3]==0)
+			}	/* else if(data[1]==1) */
+		}		/* elseif(data[1]==0) */
+	}			/* if(data[3]==0) */
 	else {
 		if (data[3] == 1) {
 			if (data[1] == 0) {
@@ -263,7 +263,7 @@
 				data[0] = data[0] & ui_Temp;
 				outw(data[0],
 					devpriv->iobase + APCI2200_DIGITAL_OP);
-			}	//if(data[1]==0)
+			}	/* if(data[1]==0) */
 			else {
 				if (data[1] == 1) {
 					switch (ui_NoOfChannel) {
@@ -312,38 +312,38 @@
 					default:
 						comedi_error(dev,
 							" chan spec wrong");
-						return -EINVAL;	// "sorry channel spec wrong "
+						return -EINVAL;	/*  "sorry channel spec wrong " */
 
-					}	//switch(ui_NoOfChannels)
+					}	/* switch(ui_NoOfChannels) */
 
 					outw(data[0],
 						devpriv->iobase +
 						APCI2200_DIGITAL_OP);
-				}	// if(data[1]==1)
+				}	/*  if(data[1]==1) */
 				else {
 					printk("\nSpecified channel not supported\n");
-				}	//else if(data[1]==1)
-			}	//elseif(data[1]==0)
-		}		//if(data[3]==1);
+				}	/* else if(data[1]==1) */
+			}	/* elseif(data[1]==0) */
+		}		/* if(data[3]==1); */
 		else {
 			printk("\nSpecified functionality does not exist\n");
 			return -EINVAL;
-		}		//if else data[3]==1)
-	}			//if else data[3]==0)
-	return (insn->n);;
+		}		/* if else data[3]==1) */
+	}			/* if else data[3]==0) */
+	return insn->n;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI2200_ReadDigitalOutput                       |
 |			(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
-                    unsigned int *data) 	                                     |
+|                    unsigned int *data) 	                                     |
 +----------------------------------------------------------------------------+
 | Task              : Read  value  of the selected channel or port           |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                     struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data          : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -354,17 +354,17 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI2200_ReadDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2200_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
-	UINT ui_Temp;
-	UINT ui_NoOfChannel = CR_CHAN(insn->chanspec);	// get the channel
+	unsigned int ui_Temp;
+	unsigned int ui_NoOfChannel = CR_CHAN(insn->chanspec);	/*  get the channel */
 	ui_Temp = data[0];
 	*data = inw(devpriv->iobase + APCI2200_DIGITAL_OP);
 	if (ui_Temp == 0) {
 		*data = (*data >> ui_NoOfChannel) & 0x1;
-	}			//if(ui_Temp==0)
+	}			/* if(ui_Temp==0) */
 	else {
 		if (ui_Temp == 1) {
 			switch (ui_NoOfChannel) {
@@ -386,28 +386,28 @@
 
 			default:
 				comedi_error(dev, " chan spec wrong");
-				return -EINVAL;	// "sorry channel spec wrong "
+				return -EINVAL;	/*  "sorry channel spec wrong " */
 
-			}	//switch(ui_NoOfChannels)
-		}		//if(ui_Temp==1)
+			}	/* switch(ui_NoOfChannels) */
+		}		/* if(ui_Temp==1) */
 		else {
 			printk("\nSpecified channel not supported \n");
-		}		//elseif(ui_Temp==1)
-	}			//elseif(ui_Temp==0)
+		}		/* elseif(ui_Temp==1) */
+	}			/* elseif(ui_Temp==0) */
 	return insn->n;
 }
 
 /*
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI2200_ConfigWatchdog(struct comedi_device *dev,
-                      struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)  |
+|                      struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)  |
 |				                                                     |
 +----------------------------------------------------------------------------+
 | Task              : Configures The Watchdog                                |
 +----------------------------------------------------------------------------+
 | Input Parameters  :   struct comedi_device *dev      : Driver handle              |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                      struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data          : Data Pointer to read status                                                                                                             |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -418,15 +418,15 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI2200_ConfigWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2200_ConfigWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (data[0] == 0) {
-		//Disable the watchdog
+		/* Disable the watchdog */
 		outw(0x0,
 			devpriv->iobase + APCI2200_WATCHDOG +
 			APCI2200_WATCHDOG_ENABLEDISABLE);
-		//Loading the Reload value
+		/* Loading the Reload value */
 		outw(data[1],
 			devpriv->iobase + APCI2200_WATCHDOG +
 			APCI2200_WATCHDOG_RELOAD_VALUE);
@@ -434,11 +434,11 @@
 		outw(data[1],
 			devpriv->iobase + APCI2200_WATCHDOG +
 			APCI2200_WATCHDOG_RELOAD_VALUE + 2);
-	}			//if(data[0]==0)
+	}			/* if(data[0]==0) */
 	else {
 		printk("\nThe input parameters are wrong\n");
 		return -EINVAL;
-	}			//elseif(data[0]==0)
+	}			/* elseif(data[0]==0) */
 
 	return insn->n;
 }
@@ -464,19 +464,19 @@
     +----------------------------------------------------------------------------+
   */
 
-int i_APCI2200_StartStopWriteWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2200_StartStopWriteWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	switch (data[0]) {
-	case 0:		//stop the watchdog
-		outw(0x0, devpriv->iobase + APCI2200_WATCHDOG + APCI2200_WATCHDOG_ENABLEDISABLE);	//disable the watchdog
+	case 0:		/* stop the watchdog */
+		outw(0x0, devpriv->iobase + APCI2200_WATCHDOG + APCI2200_WATCHDOG_ENABLEDISABLE);	/* disable the watchdog */
 		break;
-	case 1:		//start the watchdog
+	case 1:		/* start the watchdog */
 		outw(0x0001,
 			devpriv->iobase + APCI2200_WATCHDOG +
 			APCI2200_WATCHDOG_ENABLEDISABLE);
 		break;
-	case 2:		//Software trigger
+	case 2:		/* Software trigger */
 		outw(0x0201,
 			devpriv->iobase + APCI2200_WATCHDOG +
 			APCI2200_WATCHDOG_ENABLEDISABLE);
@@ -484,7 +484,7 @@
 	default:
 		printk("\nSpecified functionality does not exist\n");
 		return -EINVAL;
-	}			// switch(data[0])
+	}			/*  switch(data[0]) */
 	return insn->n;
 }
 
@@ -492,13 +492,13 @@
 +----------------------------------------------------------------------------+
 | Function   Name   : int i_APCI2200_ReadWatchdog                            |
 |			(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,
-                    unsigned int *data); 	                                     |
+|                    unsigned int *data); 	                                     |
 +----------------------------------------------------------------------------+
 | Task              : Read The Watchdog                                      |
 +----------------------------------------------------------------------------+
 | Input Parameters  :   struct comedi_device *dev      : Driver handle              |
 |                     struct comedi_subdevice *s,   :pointer to subdevice structure
-                      struct comedi_insn *insn      :pointer to insn structure      |
+|                      struct comedi_insn *insn      :pointer to insn structure      |
 |                     unsigned int *data          : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
@@ -509,8 +509,8 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI2200_ReadWatchdog(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI2200_ReadWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] =
 		inw(devpriv->iobase + APCI2200_WATCHDOG +
@@ -533,9 +533,9 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI2200_Reset(struct comedi_device * dev)
+int i_APCI2200_Reset(struct comedi_device *dev)
 {
-	outw(0x0, devpriv->iobase + APCI2200_DIGITAL_OP);	//RESETS THE DIGITAL OUTPUTS
+	outw(0x0, devpriv->iobase + APCI2200_DIGITAL_OP);	/* RESETS THE DIGITAL OUTPUTS */
 	outw(0x0,
 		devpriv->iobase + APCI2200_WATCHDOG +
 		APCI2200_WATCHDOG_ENABLEDISABLE);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2200.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2200.h
index 0a115b4..63e5f1f 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2200.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci2200.h
@@ -17,39 +17,39 @@
 
 /*********      Definitions for APCI-2200 card  *****/
 
-// Card Specific information
+/* Card Specific information */
 #define APCI2200_BOARD_VENDOR_ID                 0x15b8
 #define APCI2200_ADDRESS_RANGE                   64
 
-//DIGITAL INPUT-OUTPUT DEFINE
+/* DIGITAL INPUT-OUTPUT DEFINE */
 
 #define APCI2200_DIGITAL_OP                 	4
 #define APCI2200_DIGITAL_IP                     0
 
-// TIMER COUNTER WATCHDOG DEFINES
+/* TIMER COUNTER WATCHDOG DEFINES */
 
 #define APCI2200_WATCHDOG                          0x08
 #define APCI2200_WATCHDOG_ENABLEDISABLE            12
 #define APCI2200_WATCHDOG_RELOAD_VALUE             4
 #define APCI2200_WATCHDOG_STATUS                   16
 
-// Hardware Layer  functions for Apci2200
+/* Hardware Layer  functions for Apci2200 */
 
-//Digital Input
-INT i_APCI2200_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+/* Digital Input */
+int i_APCI2200_ReadMoreDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				    struct comedi_insn *insn, unsigned int *data);
-INT i_APCI2200_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI2200_Read1DigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
 
-//Digital Output
+/* Digital Output */
 int i_APCI2200_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				   struct comedi_insn *insn, unsigned int *data);
-INT i_APCI2200_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI2200_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				  struct comedi_insn *insn, unsigned int *data);
-INT i_APCI2200_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI2200_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
 
-// TIMER
+/* TIMER */
 int i_APCI2200_ConfigWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
 			      struct comedi_insn *insn, unsigned int *data);
 int i_APCI2200_StartStopWriteWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
@@ -57,5 +57,5 @@
 int i_APCI2200_ReadWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
 			    struct comedi_insn *insn, unsigned int *data);
 
-//reset
-INT i_APCI2200_Reset(struct comedi_device *dev);
+/* reset */
+int i_APCI2200_Reset(struct comedi_device *dev);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3120.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3120.c
index 68eb8df..169cee4 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3120.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3120.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -45,9 +45,9 @@
 */
 
 #include "hwdrv_apci3120.h"
-static UINT ui_Temp = 0;
+static unsigned int ui_Temp = 0;
 
-// FUNCTION DEFINITIONS
+/* FUNCTION DEFINITIONS */
 
 /*
 +----------------------------------------------------------------------------+
@@ -74,20 +74,20 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_InsnConfigAnalogInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3120_InsnConfigAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT i;
+	unsigned int i;
 
 	if ((data[0] != APCI3120_EOC_MODE) && (data[0] != APCI3120_EOS_MODE))
 		return -1;
 
-	// Check for Conversion time to be added ??
+	/*  Check for Conversion time to be added ?? */
 	devpriv->ui_EocEosConversionTime = data[2];
 
 	if (data[0] == APCI3120_EOS_MODE) {
 
-		//Test the number of the channel
+		/* Test the number of the channel */
 		for (i = 0; i < data[3]; i++) {
 
 			if (CR_CHAN(data[4 + i]) >= this_board->i_NbrAiChannel) {
@@ -102,14 +102,14 @@
 			devpriv->b_EocEosInterrupt = APCI3120_ENABLE;
 		} else
 			devpriv->b_EocEosInterrupt = APCI3120_DISABLE;
-		// Copy channel list and Range List to devpriv
+		/*  Copy channel list and Range List to devpriv */
 
 		devpriv->ui_AiNbrofChannels = data[3];
 		for (i = 0; i < devpriv->ui_AiNbrofChannels; i++) {
 			devpriv->ui_AiChannelList[i] = data[4 + i];
 		}
 
-	} else			// EOC
+	} else			/*  EOC */
 	{
 		devpriv->b_InterruptMode = APCI3120_EOC_MODE;
 		if (data[1]) {
@@ -145,28 +145,28 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_InsnReadAnalogInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3120_InsnReadAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	USHORT us_ConvertTiming, us_TmpValue, i;
-	BYTE b_Tmp;
+	unsigned short us_ConvertTiming, us_TmpValue, i;
+	unsigned char b_Tmp;
 
-	// fix convertion time to 10 us
+	/*  fix convertion time to 10 us */
 	if (!devpriv->ui_EocEosConversionTime) {
 		printk("No timer0 Value using 10 us\n");
 		us_ConvertTiming = 10;
 	} else
-		us_ConvertTiming = (USHORT) (devpriv->ui_EocEosConversionTime / 1000);	// nano to useconds
+		us_ConvertTiming = (unsigned short) (devpriv->ui_EocEosConversionTime / 1000);	/*  nano to useconds */
 
-	// this_board->i_hwdrv_InsnReadAnalogInput(dev,us_ConvertTiming,insn->n,&insn->chanspec,data,insn->unused[0]);
+	/*  this_board->i_hwdrv_InsnReadAnalogInput(dev,us_ConvertTiming,insn->n,&insn->chanspec,data,insn->unused[0]); */
 
-	// Clear software registers
+	/*  Clear software registers */
 	devpriv->b_TimerSelectMode = 0;
 	devpriv->b_ModeSelectRegister = 0;
 	devpriv->us_OutputRegister = 0;
-//        devpriv->b_DigitalOutputRegister=0;
+/* devpriv->b_DigitalOutputRegister=0; */
 
-	if (insn->unused[0] == 222)	// second insn read
+	if (insn->unused[0] == 222)	/*  second insn read */
 	{
 
 		for (i = 0; i < insn->n; i++) {
@@ -174,14 +174,16 @@
 		}
 
 	} else {
-		devpriv->tsk_Current = current;	// Save the current process task structure
-		//Testing if board have the new Quartz and calculate the time value
-		//to set in the timer
+		devpriv->tsk_Current = current;	/*  Save the current process task structure */
+/*
+ * Testing if board have the new Quartz and calculate the time value
+ * to set in the timer
+ */
 
 		us_TmpValue =
-			(USHORT) inw(devpriv->iobase + APCI3120_RD_STATUS);
+			(unsigned short) inw(devpriv->iobase + APCI3120_RD_STATUS);
 
-		//EL250804: Testing if board APCI3120 have the new Quartz or if it is an APCI3001
+		/* EL250804: Testing if board APCI3120 have the new Quartz or if it is an APCI3001 */
 		if ((us_TmpValue & 0x00B0) == 0x00B0
 			|| !strcmp(this_board->pc_DriverName, "apci3001")) {
 			us_ConvertTiming = (us_ConvertTiming * 2) - 2;
@@ -190,25 +192,26 @@
 				((us_ConvertTiming * 12926) / 10000) - 1;
 		}
 
-		us_TmpValue = (USHORT) devpriv->b_InterruptMode;
+		us_TmpValue = (unsigned short) devpriv->b_InterruptMode;
 
 		switch (us_TmpValue) {
 
 		case APCI3120_EOC_MODE:
 
-			// Testing the interrupt flag and set the EOC bit
-			// Clears the FIFO
+/*
+ * Testing the interrupt flag and set the EOC bit Clears the FIFO
+ */
 			inw(devpriv->iobase + APCI3120_RESET_FIFO);
 
-			// Initialize the sequence array
+			/*  Initialize the sequence array */
 
-			//if (!i_APCI3120_SetupChannelList(dev,s,1,chanlist,0))  return -EINVAL;
+			/* if (!i_APCI3120_SetupChannelList(dev,s,1,chanlist,0))  return -EINVAL; */
 
 			if (!i_APCI3120_SetupChannelList(dev, s, 1,
 					&insn->chanspec, 0))
 				return -EINVAL;
 
-			//Initialize Timer 0 mode 4
+			/* Initialize Timer 0 mode 4 */
 			devpriv->b_TimerSelectMode =
 				(devpriv->
 				b_TimerSelectMode & 0xFC) |
@@ -216,14 +219,14 @@
 			outb(devpriv->b_TimerSelectMode,
 				devpriv->iobase + APCI3120_TIMER_CRT1);
 
-			// Reset the scan bit and Disables the  EOS, DMA, EOC interrupt
+			/*  Reset the scan bit and Disables the  EOS, DMA, EOC interrupt */
 			devpriv->b_ModeSelectRegister =
 				devpriv->
 				b_ModeSelectRegister & APCI3120_DISABLE_SCAN;
 
 			if (devpriv->b_EocEosInterrupt == APCI3120_ENABLE) {
 
-				//Disables the EOS,DMA and enables the EOC interrupt
+				/* Disables the EOS,DMA and enables the EOC interrupt */
 				devpriv->b_ModeSelectRegister =
 					(devpriv->
 					b_ModeSelectRegister &
@@ -241,7 +244,7 @@
 			outb(devpriv->b_ModeSelectRegister,
 				devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
 
-			// Sets gate 0
+			/*  Sets gate 0 */
 			devpriv->us_OutputRegister =
 				(devpriv->
 				us_OutputRegister & APCI3120_CLEAR_PA_PR) |
@@ -249,30 +252,30 @@
 			outw(devpriv->us_OutputRegister,
 				devpriv->iobase + APCI3120_WR_ADDRESS);
 
-			// Select Timer 0
+			/*  Select Timer 0 */
 			b_Tmp = ((devpriv->
 					b_DigitalOutputRegister) & 0xF0) |
 				APCI3120_SELECT_TIMER_0_WORD;
 			outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
 
-			//Set the convertion time
+			/* Set the convertion time */
 			outw(us_ConvertTiming,
 				devpriv->iobase + APCI3120_TIMER_VALUE);
 
 			us_TmpValue =
-				(USHORT) inw(dev->iobase + APCI3120_RD_STATUS);
+				(unsigned short) inw(dev->iobase + APCI3120_RD_STATUS);
 
 			if (devpriv->b_EocEosInterrupt == APCI3120_DISABLE) {
 
 				do {
-					// Waiting for the end of conversion
+					/*  Waiting for the end of conversion */
 					us_TmpValue =
 						inw(devpriv->iobase +
 						APCI3120_RD_STATUS);
 				} while ((us_TmpValue & APCI3120_EOC) ==
 					APCI3120_EOC);
 
-				//Read the result in FIFO  and put it in insn data pointer
+				/* Read the result in FIFO  and put it in insn data pointer */
 				us_TmpValue = inw(devpriv->iobase + 0);
 				*data = us_TmpValue;
 
@@ -284,9 +287,9 @@
 		case APCI3120_EOS_MODE:
 
 			inw(devpriv->iobase);
-			// Clears the FIFO
+			/*  Clears the FIFO */
 			inw(devpriv->iobase + APCI3120_RESET_FIFO);
-			// clear PA PR  and disable timer 0
+			/*  clear PA PR  and disable timer 0 */
 
 			devpriv->us_OutputRegister =
 				(devpriv->
@@ -301,7 +304,7 @@
 					devpriv->ui_AiChannelList, 0))
 				return -EINVAL;
 
-			//Initialize Timer 0 mode 2
+			/* Initialize Timer 0 mode 2 */
 			devpriv->b_TimerSelectMode =
 				(devpriv->
 				b_TimerSelectMode & 0xFC) |
@@ -309,26 +312,26 @@
 			outb(devpriv->b_TimerSelectMode,
 				devpriv->iobase + APCI3120_TIMER_CRT1);
 
-			//Select Timer 0
+			/* Select Timer 0 */
 			b_Tmp = ((devpriv->
 					b_DigitalOutputRegister) & 0xF0) |
 				APCI3120_SELECT_TIMER_0_WORD;
 			outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
 
-			//Set the convertion time
+			/* Set the convertion time */
 			outw(us_ConvertTiming,
 				devpriv->iobase + APCI3120_TIMER_VALUE);
 
-			//Set the scan bit
+			/* Set the scan bit */
 			devpriv->b_ModeSelectRegister =
 				devpriv->
 				b_ModeSelectRegister | APCI3120_ENABLE_SCAN;
 			outb(devpriv->b_ModeSelectRegister,
 				devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
 
-			//If Interrupt function is loaded
+			/* If Interrupt function is loaded */
 			if (devpriv->b_EocEosInterrupt == APCI3120_ENABLE) {
-				//Disables the EOC,DMA and enables the EOS interrupt
+				/* Disables the EOC,DMA and enables the EOS interrupt */
 				devpriv->b_ModeSelectRegister =
 					(devpriv->
 					b_ModeSelectRegister &
@@ -347,7 +350,7 @@
 
 			inw(devpriv->iobase + APCI3120_RD_STATUS);
 
-			//Sets gate 0
+			/* Sets gate 0 */
 
 			devpriv->us_OutputRegister =
 				devpriv->
@@ -355,28 +358,27 @@
 			outw(devpriv->us_OutputRegister,
 				devpriv->iobase + APCI3120_WR_ADDRESS);
 
-			//Start conversion
+			/* Start conversion */
 			outw(0, devpriv->iobase + APCI3120_START_CONVERSION);
 
-			//Waiting of end of convertion if interrupt is not installed
+			/* Waiting of end of convertion if interrupt is not installed */
 			if (devpriv->b_EocEosInterrupt == APCI3120_DISABLE) {
-				//Waiting the end of convertion
+				/* Waiting the end of convertion */
 				do {
 					us_TmpValue =
 						inw(devpriv->iobase +
 						APCI3120_RD_STATUS);
-				}
-				while ((us_TmpValue & APCI3120_EOS) !=
-					APCI3120_EOS);
+				} while ((us_TmpValue & APCI3120_EOS) !=
+					 APCI3120_EOS);
 
 				for (i = 0; i < devpriv->ui_AiNbrofChannels;
 					i++) {
-					//Read the result in FIFO and write them in shared memory
+					/* Read the result in FIFO and write them in shared memory */
 					us_TmpValue = inw(devpriv->iobase);
-					data[i] = (UINT) us_TmpValue;
+					data[i] = (unsigned int) us_TmpValue;
 				}
 
-				devpriv->b_InterruptMode = APCI3120_EOC_MODE;	// Restore defaults.
+				devpriv->b_InterruptMode = APCI3120_EOC_MODE;	/*  Restore defaults. */
 			}
 			break;
 
@@ -384,7 +386,7 @@
 			printk("inputs wrong\n");
 
 		}
-		devpriv->ui_EocEosConversionTime = 0;	// re initializing the variable;
+		devpriv->ui_EocEosConversionTime = 0;	/*  re initializing the variable; */
 	}
 
 	return insn->n;
@@ -409,38 +411,41 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_StopCyclicAcquisition(struct comedi_device * dev, struct comedi_subdevice * s)
+int i_APCI3120_StopCyclicAcquisition(struct comedi_device *dev, struct comedi_subdevice *s)
 {
-	// Disable A2P Fifo write and AMWEN signal
+	/*  Disable A2P Fifo write and AMWEN signal */
 	outw(0, devpriv->i_IobaseAddon + 4);
 
-	//Disable Bus Master ADD ON
+	/* Disable Bus Master ADD ON */
 	outw(APCI3120_ADD_ON_AGCSTS_LOW, devpriv->i_IobaseAddon + 0);
 	outw(0, devpriv->i_IobaseAddon + 2);
 	outw(APCI3120_ADD_ON_AGCSTS_HIGH, devpriv->i_IobaseAddon + 0);
 	outw(0, devpriv->i_IobaseAddon + 2);
 
-	//Disable BUS Master PCI
+	/* Disable BUS Master PCI */
 	outl(0, devpriv->i_IobaseAmcc + AMCC_OP_REG_MCSR);
 
-	//outl(inl(devpriv->i_IobaseAmcc+AMCC_OP_REG_INTCSR)&(~AINT_WRITE_COMPL), devpriv->i_IobaseAmcc+AMCC_OP_REG_INTCSR);    // stop amcc irqs
-	//outl(inl(devpriv->i_IobaseAmcc+AMCC_OP_REG_MCSR)&(~EN_A2P_TRANSFERS), devpriv->i_IobaseAmcc+AMCC_OP_REG_MCSR); // stop DMA
+	/* outl(inl(devpriv->i_IobaseAmcc+AMCC_OP_REG_INTCSR)&(~AINT_WRITE_COMPL),
+	 * devpriv->i_IobaseAmcc+AMCC_OP_REG_INTCSR);  stop amcc irqs */
 
-	//Disable ext trigger
+	/* outl(inl(devpriv->i_IobaseAmcc+AMCC_OP_REG_MCSR)&(~EN_A2P_TRANSFERS),
+	 * devpriv->i_IobaseAmcc+AMCC_OP_REG_MCSR);  stop DMA */
+
+	/* Disable ext trigger */
 	i_APCI3120_ExttrigDisable(dev);
 
 	devpriv->us_OutputRegister = 0;
-	//stop  counters
+	/* stop  counters */
 	outw(devpriv->
 		us_OutputRegister & APCI3120_DISABLE_TIMER0 &
 		APCI3120_DISABLE_TIMER1, dev->iobase + APCI3120_WR_ADDRESS);
 
 	outw(APCI3120_DISABLE_ALL_TIMER, dev->iobase + APCI3120_WR_ADDRESS);
 
-	//DISABLE_ALL_INTERRUPT
+	/* DISABLE_ALL_INTERRUPT */
 	outb(APCI3120_DISABLE_ALL_INTERRUPT,
 		dev->iobase + APCI3120_WRITE_MODE_SELECT);
-	//Flush FIFO
+	/* Flush FIFO */
 	inb(dev->iobase + APCI3120_RESET_FIFO);
 	inw(dev->iobase + APCI3120_RD_STATUS);
 	devpriv->ui_AiActualScan = 0;
@@ -476,13 +481,13 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_CommandTestAnalogInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+int i_APCI3120_CommandTestAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
-	int tmp;		// divisor1,divisor2;
+	int tmp;		/*  divisor1,divisor2; */
 
-	// step 1: make sure trigger sources are trivially valid
+	/*  step 1: make sure trigger sources are trivially valid */
 
 	tmp = cmd->start_src;
 	cmd->start_src &= TRIG_NOW | TRIG_EXT;
@@ -512,7 +517,7 @@
 	if (err)
 		return 1;
 
-	//step 2: make sure trigger sources are unique and mutually compatible
+	/* step 2: make sure trigger sources are unique and mutually compatible */
 
 	if (cmd->start_src != TRIG_NOW && cmd->start_src != TRIG_EXT) {
 		err++;
@@ -536,14 +541,14 @@
 	if (err)
 		return 2;
 
-	// step 3: make sure arguments are trivially compatible
+	/*  step 3: make sure arguments are trivially compatible */
 
 	if (cmd->start_arg != 0) {
 		cmd->start_arg = 0;
 		err++;
 	}
 
-	if (cmd->scan_begin_src == TRIG_TIMER)	// Test Delay timing
+	if (cmd->scan_begin_src == TRIG_TIMER)	/*  Test Delay timing */
 	{
 		if (cmd->scan_begin_arg < this_board->ui_MinDelaytimeNs) {
 			cmd->scan_begin_arg = this_board->ui_MinDelaytimeNs;
@@ -551,7 +556,7 @@
 		}
 	}
 
-	if (cmd->convert_src == TRIG_TIMER)	// Test Acquisition timing
+	if (cmd->convert_src == TRIG_TIMER)	/*  Test Acquisition timing */
 	{
 		if (cmd->scan_begin_src == TRIG_TIMER) {
 			if ((cmd->convert_arg)
@@ -585,7 +590,7 @@
 			cmd->stop_arg = 1;
 			err++;
 		}
-	} else {		// TRIG_NONE
+	} else {		/*  TRIG_NONE */
 		if (cmd->stop_arg != 0) {
 			cmd->stop_arg = 0;
 			err++;
@@ -595,7 +600,7 @@
 	if (err)
 		return 3;
 
-	// step 4: fix up any arguments
+	/*  step 4: fix up any arguments */
 
 	if (cmd->convert_src == TRIG_TIMER) {
 
@@ -633,19 +638,19 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_CommandAnalogInput(struct comedi_device * dev, struct comedi_subdevice * s)
+int i_APCI3120_CommandAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 
-	//loading private structure with cmd structure inputs
+	/* loading private structure with cmd structure inputs */
 	devpriv->ui_AiFlags = cmd->flags;
 	devpriv->ui_AiNbrofChannels = cmd->chanlist_len;
 	devpriv->ui_AiScanLength = cmd->scan_end_arg;
 	devpriv->pui_AiChannelList = cmd->chanlist;
 
-	//UPDATE-0.7.57->0.7.68devpriv->AiData=s->async->data;
+	/* UPDATE-0.7.57->0.7.68devpriv->AiData=s->async->data; */
 	devpriv->AiData = s->async->prealloc_buf;
-	//UPDATE-0.7.57->0.7.68devpriv->ui_AiDataLength=s->async->data_len;
+	/* UPDATE-0.7.57->0.7.68devpriv->ui_AiDataLength=s->async->data_len; */
 	devpriv->ui_AiDataLength = s->async->prealloc_bufsz;
 
 	if (cmd->stop_src == TRIG_COUNT) {
@@ -654,11 +659,11 @@
 		devpriv->ui_AiNbrofScans = 0;
 	}
 
-	devpriv->ui_AiTimer0 = 0;	// variables changed to timer0,timer1
+	devpriv->ui_AiTimer0 = 0;	/*  variables changed to timer0,timer1 */
 	devpriv->ui_AiTimer1 = 0;
 	if ((devpriv->ui_AiNbrofScans == 0) || (devpriv->ui_AiNbrofScans == -1))
-		devpriv->b_AiContinuous = 1;	// user want neverending analog acquisition
-	// stopped using cancel
+		devpriv->b_AiContinuous = 1;	/*  user want neverending analog acquisition */
+	/*  stopped using cancel */
 
 	if (cmd->start_src == TRIG_EXT)
 		devpriv->b_ExttrigEnable = APCI3120_ENABLE;
@@ -666,22 +671,22 @@
 		devpriv->b_ExttrigEnable = APCI3120_DISABLE;
 
 	if (cmd->scan_begin_src == TRIG_FOLLOW) {
-		// mode 1 or 3
+		/*  mode 1 or 3 */
 		if (cmd->convert_src == TRIG_TIMER) {
-			// mode 1
+			/*  mode 1 */
 
-			devpriv->ui_AiTimer0 = cmd->convert_arg;	// timer constant in nano seconds
-			//return this_board->i_hwdrv_CommandAnalogInput(1,dev,s);
+			devpriv->ui_AiTimer0 = cmd->convert_arg;	/*  timer constant in nano seconds */
+			/* return this_board->i_hwdrv_CommandAnalogInput(1,dev,s); */
 			return i_APCI3120_CyclicAnalogInput(1, dev, s);
 		}
 
 	}
 	if ((cmd->scan_begin_src == TRIG_TIMER)
 		&& (cmd->convert_src == TRIG_TIMER)) {
-		// mode 2
+		/*  mode 2 */
 		devpriv->ui_AiTimer1 = cmd->scan_begin_arg;
-		devpriv->ui_AiTimer0 = cmd->convert_arg;	// variable changed timer2 to timer0
-		//return this_board->i_hwdrv_CommandAnalogInput(2,dev,s);
+		devpriv->ui_AiTimer0 = cmd->convert_arg;	/*  variable changed timer2 to timer0 */
+		/* return this_board->i_hwdrv_CommandAnalogInput(2,dev,s); */
 		return i_APCI3120_CyclicAnalogInput(2, dev, s);
 	}
 	return -1;
@@ -707,73 +712,74 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_CyclicAnalogInput(int mode, struct comedi_device * dev,
-	struct comedi_subdevice * s)
+int i_APCI3120_CyclicAnalogInput(int mode, struct comedi_device *dev,
+	struct comedi_subdevice *s)
 {
-	BYTE b_Tmp;
-	UINT ui_Tmp, ui_DelayTiming = 0, ui_TimerValue1 = 0, dmalen0 =
+	unsigned char b_Tmp;
+	unsigned int ui_Tmp, ui_DelayTiming = 0, ui_TimerValue1 = 0, dmalen0 =
 		0, dmalen1 = 0, ui_TimerValue2 =
 		0, ui_TimerValue0, ui_ConvertTiming;
-	USHORT us_TmpValue;
+	unsigned short us_TmpValue;
 
-	//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
-	//devpriv->b_AiCyclicAcquisition=APCI3120_ENABLE;
-	//END JK 07.05.04: Comparison between WIN32 and Linux driver
+	/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
+	/* devpriv->b_AiCyclicAcquisition=APCI3120_ENABLE; */
+	/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
 
 	/*******************/
 	/* Resets the FIFO */
 	/*******************/
 	inb(dev->iobase + APCI3120_RESET_FIFO);
 
-	//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
-	//inw(dev->iobase+APCI3120_RD_STATUS);
-	//END JK 07.05.04: Comparison between WIN32 and Linux driver
+	/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
+	/* inw(dev->iobase+APCI3120_RD_STATUS); */
+	/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
 
 	/***************************/
 	/* Acquisition initialized */
 	/***************************/
-	//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
+	/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
 	devpriv->b_AiCyclicAcquisition = APCI3120_ENABLE;
-	//END JK 07.05.04: Comparison between WIN32 and Linux driver
+	/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
 
-	// clear software  registers
+	/*  clear software  registers */
 	devpriv->b_TimerSelectMode = 0;
 	devpriv->us_OutputRegister = 0;
 	devpriv->b_ModeSelectRegister = 0;
-	//devpriv->b_DigitalOutputRegister=0;
+	/* devpriv->b_DigitalOutputRegister=0; */
 
-	//COMMENT JK 07.05.04: Followings calls are in i_APCI3120_StartAnalogInputAcquisition
+	/* COMMENT JK 07.05.04: Followings calls are in i_APCI3120_StartAnalogInputAcquisition */
 
-   /****************************/
-	/* Clear Timer Write TC INT */
-   /****************************/
+	/****************************/
+	/* Clear Timer Write TC int */
+	/****************************/
 	outl(APCI3120_CLEAR_WRITE_TC_INT,
 		devpriv->i_IobaseAmcc + APCI3120_AMCC_OP_REG_INTCSR);
 
-   /************************************/
+	/************************************/
 	/* Clears the timer status register */
-   /************************************/
-	//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
-	//inw(dev->iobase+APCI3120_TIMER_STATUS_REGISTER);
-	inb(dev->iobase + APCI3120_TIMER_STATUS_REGISTER);
-	//END JK 07.05.04: Comparison between WIN32 and Linux driver
+	/************************************/
 
-   /**************************/
+	/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
+	/* inw(dev->iobase+APCI3120_TIMER_STATUS_REGISTER); */
+	/* inb(dev->iobase + APCI3120_TIMER_STATUS_REGISTER); */
+	/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
+
+	/**************************/
 	/* Disables All Timer     */
 	/* Sets PR and PA to 0    */
-   /**************************/
+	/**************************/
 	devpriv->us_OutputRegister = devpriv->us_OutputRegister &
 		APCI3120_DISABLE_TIMER0 &
 		APCI3120_DISABLE_TIMER1 & APCI3120_CLEAR_PA_PR;
 
 	outw(devpriv->us_OutputRegister, dev->iobase + APCI3120_WR_ADDRESS);
 
-   /*******************/
+	/*******************/
 	/* Resets the FIFO */
-   /*******************/
-	//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
+	/*******************/
+	/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
 	inb(devpriv->iobase + APCI3120_RESET_FIFO);
-	//END JK 07.05.04: Comparison between WIN32 and Linux driver
+	/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
 
 	devpriv->ui_AiActualScan = 0;
 	devpriv->ui_AiActualScanPosition = 0;
@@ -781,7 +787,7 @@
 	devpriv->ui_AiBufferPtr = 0;
 	devpriv->ui_DmaActualBuffer = 0;
 
-	// value for timer2  minus -2 has to be done .....dunno y??
+	/*  value for timer2  minus -2 has to be done .....dunno y?? */
 	ui_TimerValue2 = devpriv->ui_AiNbrofScans - 2;
 	ui_ConvertTiming = devpriv->ui_AiTimer0;
 
@@ -795,31 +801,31 @@
 			devpriv->pui_AiChannelList, 0))
 		return -EINVAL;
 
-	us_TmpValue = (USHORT) inw(dev->iobase + APCI3120_RD_STATUS);
+	us_TmpValue = (unsigned short) inw(dev->iobase + APCI3120_RD_STATUS);
 /*** EL241003 : add this section in comment because floats must not be used
-	 if((us_TmpValue & 0x00B0)==0x00B0)
+	if((us_TmpValue & 0x00B0)==0x00B0)
 	 {
-           f_ConvertValue=(((float)ui_ConvertTiming * 0.002) - 2);
-		ui_TimerValue0=(UINT)f_ConvertValue;
+		f_ConvertValue=(((float)ui_ConvertTiming * 0.002) - 2);
+		ui_TimerValue0=(unsigned int)f_ConvertValue;
 		if (mode==2)
 		{
 			f_DelayValue     = (((float)ui_DelayTiming * 0.00002) - 2);
-			ui_TimerValue1  =   (UINT) f_DelayValue;
+			ui_TimerValue1  =   (unsigned int) f_DelayValue;
 		}
 	 }
-   	 else
+	else
 	 {
 		f_ConvertValue=(((float)ui_ConvertTiming * 0.0012926) - 1);
-		ui_TimerValue0=(UINT)f_ConvertValue;
+		ui_TimerValue0=(unsigned int)f_ConvertValue;
 		if (mode == 2)
 		{
 		     f_DelayValue     = (((float)ui_DelayTiming * 0.000012926) - 1);
-		     ui_TimerValue1  =   (UINT) f_DelayValue;
+		     ui_TimerValue1  =   (unsigned int) f_DelayValue;
 		}
 	}
 ***********************************************************************************************/
 /*** EL241003 Begin : add this section to replace floats calculation by integer calculations **/
-	//EL250804: Testing if board APCI3120 have the new Quartz or if it is an APCI3001
+	/* EL250804: Testing if board APCI3120 have the new Quartz or if it is an APCI3001 */
 	if ((us_TmpValue & 0x00B0) == 0x00B0
 		|| !strcmp(this_board->pc_DriverName, "apci3001")) {
 		ui_TimerValue0 = ui_ConvertTiming * 2 - 2000;
@@ -844,79 +850,82 @@
 /*** EL241003 End ******************************************************************************/
 
 	if (devpriv->b_ExttrigEnable == APCI3120_ENABLE) {
-		i_APCI3120_ExttrigEnable(dev);	// activate EXT trigger
+		i_APCI3120_ExttrigEnable(dev);	/*  activate EXT trigger */
 	}
 	switch (mode) {
 	case 1:
-		// init timer0 in mode 2
+		/*  init timer0 in mode 2 */
 		devpriv->b_TimerSelectMode =
 			(devpriv->
 			b_TimerSelectMode & 0xFC) | APCI3120_TIMER_0_MODE_2;
 		outb(devpriv->b_TimerSelectMode,
 			dev->iobase + APCI3120_TIMER_CRT1);
 
-		//Select Timer 0
+		/* Select Timer 0 */
 		b_Tmp = ((devpriv->
 				b_DigitalOutputRegister) & 0xF0) |
 			APCI3120_SELECT_TIMER_0_WORD;
 		outb(b_Tmp, dev->iobase + APCI3120_TIMER_CRT0);
-		//Set the convertion time
-		outw(((USHORT) ui_TimerValue0),
+		/* Set the convertion time */
+		outw(((unsigned short) ui_TimerValue0),
 			dev->iobase + APCI3120_TIMER_VALUE);
 		break;
 
 	case 2:
-		// init timer1 in mode 2
+		/*  init timer1 in mode 2 */
 		devpriv->b_TimerSelectMode =
 			(devpriv->
 			b_TimerSelectMode & 0xF3) | APCI3120_TIMER_1_MODE_2;
 		outb(devpriv->b_TimerSelectMode,
 			dev->iobase + APCI3120_TIMER_CRT1);
 
-		//Select Timer 1
+		/* Select Timer 1 */
 		b_Tmp = ((devpriv->
 				b_DigitalOutputRegister) & 0xF0) |
 			APCI3120_SELECT_TIMER_1_WORD;
 		outb(b_Tmp, dev->iobase + APCI3120_TIMER_CRT0);
-		//Set the convertion time
-		outw(((USHORT) ui_TimerValue1),
+		/* Set the convertion time */
+		outw(((unsigned short) ui_TimerValue1),
 			dev->iobase + APCI3120_TIMER_VALUE);
 
-		// init timer0 in mode 2
+		/*  init timer0 in mode 2 */
 		devpriv->b_TimerSelectMode =
 			(devpriv->
 			b_TimerSelectMode & 0xFC) | APCI3120_TIMER_0_MODE_2;
 		outb(devpriv->b_TimerSelectMode,
 			dev->iobase + APCI3120_TIMER_CRT1);
 
-		//Select Timer 0
+		/* Select Timer 0 */
 		b_Tmp = ((devpriv->
 				b_DigitalOutputRegister) & 0xF0) |
 			APCI3120_SELECT_TIMER_0_WORD;
 		outb(b_Tmp, dev->iobase + APCI3120_TIMER_CRT0);
 
-		//Set the convertion time
-		outw(((USHORT) ui_TimerValue0),
+		/* Set the convertion time */
+		outw(((unsigned short) ui_TimerValue0),
 			dev->iobase + APCI3120_TIMER_VALUE);
 		break;
 
 	}
-	//   ##########common for all modes#################
+	/*    ##########common for all modes################# */
 
 	/***********************/
 	/* Clears the SCAN bit */
 	/***********************/
-	//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
-	//devpriv->b_ModeSelectRegister=devpriv->b_ModeSelectRegister | APCI3120_DISABLE_SCAN;
+
+	/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
+	/* devpriv->b_ModeSelectRegister=devpriv->b_ModeSelectRegister | APCI3120_DISABLE_SCAN; */
+
 	devpriv->b_ModeSelectRegister = devpriv->b_ModeSelectRegister &
 		APCI3120_DISABLE_SCAN;
-	//END JK 07.05.04: Comparison between WIN32 and Linux driver
+	/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
+
 	outb(devpriv->b_ModeSelectRegister,
 		dev->iobase + APCI3120_WRITE_MODE_SELECT);
 
-	// If DMA is disabled
+	/*  If DMA is disabled */
 	if (devpriv->us_UseDma == APCI3120_DISABLE) {
-		// disable EOC and enable EOS
+		/*  disable EOC and enable EOS */
 		devpriv->b_InterruptMode = APCI3120_EOS_MODE;
 		devpriv->b_EocEosInterrupt = APCI3120_ENABLE;
 
@@ -928,15 +937,17 @@
 			dev->iobase + APCI3120_WRITE_MODE_SELECT);
 
 		if (!devpriv->b_AiContinuous) {
-			// configure Timer2 For counting  EOS
-			//Reset gate 2 of Timer 2 to disable it (Set Bit D14 to 0)
+/*
+ * configure Timer2 For counting EOS Reset gate 2 of Timer 2 to
+ * disable it (Set Bit D14 to 0)
+ */
 			devpriv->us_OutputRegister =
 				devpriv->
 				us_OutputRegister & APCI3120_DISABLE_TIMER2;
 			outw(devpriv->us_OutputRegister,
 				dev->iobase + APCI3120_WR_ADDRESS);
 
-			// DISABLE TIMER INTERRUPT
+			/*  DISABLE TIMER intERRUPT */
 			devpriv->b_ModeSelectRegister =
 				devpriv->
 				b_ModeSelectRegister &
@@ -944,7 +955,7 @@
 			outb(devpriv->b_ModeSelectRegister,
 				dev->iobase + APCI3120_WRITE_MODE_SELECT);
 
-			//(1) Init timer 2 in mode 0 and write timer value
+			/* (1) Init timer 2 in mode 0 and write timer value */
 			devpriv->b_TimerSelectMode =
 				(devpriv->
 				b_TimerSelectMode & 0x0F) |
@@ -952,7 +963,7 @@
 			outb(devpriv->b_TimerSelectMode,
 				dev->iobase + APCI3120_TIMER_CRT1);
 
-			//Writing LOW WORD
+			/* Writing LOW unsigned short */
 			b_Tmp = ((devpriv->
 					b_DigitalOutputRegister) & 0xF0) |
 				APCI3120_SELECT_TIMER_2_LOW_WORD;
@@ -960,7 +971,7 @@
 			outw(LOWORD(ui_TimerValue2),
 				dev->iobase + APCI3120_TIMER_VALUE);
 
-			//Writing HIGH WORD
+			/* Writing HIGH unsigned short */
 			b_Tmp = ((devpriv->
 					b_DigitalOutputRegister) & 0xF0) |
 				APCI3120_SELECT_TIMER_2_HIGH_WORD;
@@ -968,20 +979,20 @@
 			outw(HIWORD(ui_TimerValue2),
 				dev->iobase + APCI3120_TIMER_VALUE);
 
-			//(2) Reset FC_TIMER BIT  Clearing timer status register
+			/* (2) Reset FC_TIMER BIT  Clearing timer status register */
 			inb(dev->iobase + APCI3120_TIMER_STATUS_REGISTER);
-			// enable timer counter and disable watch dog
+			/*  enable timer counter and disable watch dog */
 			devpriv->b_ModeSelectRegister =
 				(devpriv->
 				b_ModeSelectRegister |
 				APCI3120_ENABLE_TIMER_COUNTER) &
 				APCI3120_DISABLE_WATCHDOG;
-			// select EOS clock input for timer 2
+			/*  select EOS clock input for timer 2 */
 			devpriv->b_ModeSelectRegister =
 				devpriv->
 				b_ModeSelectRegister |
 				APCI3120_TIMER2_SELECT_EOS;
-			// Enable timer2  interrupt
+			/*  Enable timer2  interrupt */
 			devpriv->b_ModeSelectRegister =
 				devpriv->
 				b_ModeSelectRegister |
@@ -992,15 +1003,16 @@
 			devpriv->b_Timer2Interrupt = APCI3120_ENABLE;
 		}
 	} else {
-		// If DMA Enabled
-		//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
-		//inw(dev->iobase+0);// reset EOC bit
-		//END JK 07.05.04: Comparison between WIN32 and Linux driver
+		/* If DMA Enabled */
+
+		/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
+		/* inw(dev->iobase+0); reset EOC bit */
+		/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
 		devpriv->b_InterruptMode = APCI3120_DMA_MODE;
 
-      /************************************/
+		/************************************/
 		/* Disables the EOC, EOS interrupt  */
-	  /************************************/
+		/************************************/
 		devpriv->b_ModeSelectRegister = devpriv->b_ModeSelectRegister &
 			APCI3120_DISABLE_EOC_INT & APCI3120_DISABLE_EOS_INT;
 
@@ -1012,18 +1024,18 @@
 
 		if (!devpriv->b_AiContinuous) {
 
-			if (dmalen0 > (devpriv->ui_AiNbrofScans * devpriv->ui_AiScanLength * 2)) {	// must we fill full first buffer?
+			if (dmalen0 > (devpriv->ui_AiNbrofScans * devpriv->ui_AiScanLength * 2)) {	/*  must we fill full first buffer? */
 				dmalen0 =
 					devpriv->ui_AiNbrofScans *
 					devpriv->ui_AiScanLength * 2;
-			} else if (dmalen1 > (devpriv->ui_AiNbrofScans * devpriv->ui_AiScanLength * 2 - dmalen0))	// and must we fill full second buffer when first is once filled?
+			} else if (dmalen1 > (devpriv->ui_AiNbrofScans * devpriv->ui_AiScanLength * 2 - dmalen0))	/*  and must we fill full second buffer when first is once filled? */
 				dmalen1 =
 					devpriv->ui_AiNbrofScans *
 					devpriv->ui_AiScanLength * 2 - dmalen0;
 		}
 
 		if (devpriv->ui_AiFlags & TRIG_WAKE_EOS) {
-			// don't we want wake up every scan?
+			/*  don't we want wake up every scan? */
 			if (dmalen0 > (devpriv->ui_AiScanLength * 2)) {
 				dmalen0 = devpriv->ui_AiScanLength * 2;
 				if (devpriv->ui_AiScanLength & 1)
@@ -1036,7 +1048,7 @@
 				if (dmalen1 < 4)
 					dmalen1 = 4;
 			}
-		} else {	// isn't output buff smaller that our DMA buff?
+		} else {	/*  isn't output buff smaller that our DMA buff? */
 			if (dmalen0 > (devpriv->ui_AiDataLength)) {
 				dmalen0 = devpriv->ui_AiDataLength;
 			}
@@ -1047,14 +1059,16 @@
 		devpriv->ui_DmaBufferUsesize[0] = dmalen0;
 		devpriv->ui_DmaBufferUsesize[1] = dmalen1;
 
-		//Initialize DMA
+		/* Initialize DMA */
 
-		// Set Transfer count enable bit and A2P_fifo reset bit in AGCSTS register
-		//1
+/*
+ * Set Transfer count enable bit and A2P_fifo reset bit in AGCSTS
+ * register 1
+ */
 		ui_Tmp = AGCSTS_TC_ENABLE | AGCSTS_RESET_A2P_FIFO;
 		outl(ui_Tmp, devpriv->i_IobaseAmcc + AMCC_OP_REG_AGCSTS);
 
-		// changed  since 16 bit interface for add on
+		/*  changed  since 16 bit interface for add on */
 		/*********************/
 		/* ENABLE BUS MASTER */
 		/*********************/
@@ -1066,104 +1080,121 @@
 		outw(APCI3120_ENABLE_TRANSFER_ADD_ON_HIGH,
 			devpriv->i_IobaseAddon + 2);
 
-		// TO VERIFIED
-		//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
+/*
+ * TO VERIFIED BEGIN JK 07.05.04: Comparison between WIN32 and Linux
+ * driver
+ */
 		outw(0x1000, devpriv->i_IobaseAddon + 2);
-		//END JK 07.05.04: Comparison between WIN32 and Linux driver
+		/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
 
-		//2  No change
-		// A2P FIFO MANAGEMENT
-		// A2P fifo reset  & transfer control enable
-		 /***********************/
+		/* 2 No change */
 		/* A2P FIFO MANAGEMENT */
-		 /***********************/
+		/* A2P fifo reset & transfer control enable */
+
+		/***********************/
+		/* A2P FIFO MANAGEMENT */
+		/***********************/
 		outl(APCI3120_A2P_FIFO_MANAGEMENT, devpriv->i_IobaseAmcc +
 			APCI3120_AMCC_OP_MCSR);
 
-		//3
-		//beginning address of dma buf
-		//The 32 bit address of dma buffer is converted into two 16 bit addresses
-		// Can done by using _attach and put into into an array
-		// array used may be for differnet pages
+/*
+ * 3
+ * beginning address of dma buf The 32 bit address of dma buffer
+ * is converted into two 16 bit addresses Can done by using _attach
+ * and put into into an array array used may be for differnet pages
+ */
 
-		// DMA Start Adress Low
+		/*  DMA Start Adress Low */
 		outw(APCI3120_ADD_ON_MWAR_LOW, devpriv->i_IobaseAddon + 0);
 		outw((devpriv->ul_DmaBufferHw[0] & 0xFFFF),
 			devpriv->i_IobaseAddon + 2);
 
-		 /*************************/
+		/*************************/
 		/* DMA Start Adress High */
-		 /*************************/
+		/*************************/
 		outw(APCI3120_ADD_ON_MWAR_HIGH, devpriv->i_IobaseAddon + 0);
 		outw((devpriv->ul_DmaBufferHw[0] / 65536),
 			devpriv->i_IobaseAddon + 2);
 
-		//4
-		// amount of bytes to be transfered  set transfer count
-		// used ADDON MWTC register
-		//commented testing             outl(devpriv->ui_DmaBufferUsesize[0], devpriv->i_IobaseAddon+AMCC_OP_REG_AMWTC);
+/*
+ * 4
+ * amount of bytes to be transfered set transfer count used ADDON
+ * MWTC register commented testing
+ * outl(devpriv->ui_DmaBufferUsesize[0],
+ * devpriv->i_IobaseAddon+AMCC_OP_REG_AMWTC);
+ */
 
-		 /**************************/
+		/**************************/
 		/* Nbr of acquisition LOW */
-		 /**************************/
+		/**************************/
 		outw(APCI3120_ADD_ON_MWTC_LOW, devpriv->i_IobaseAddon + 0);
 		outw((devpriv->ui_DmaBufferUsesize[0] & 0xFFFF),
 			devpriv->i_IobaseAddon + 2);
 
-		 /***************************/
+		/***************************/
 		/* Nbr of acquisition HIGH */
-		 /***************************/
+		/***************************/
 		outw(APCI3120_ADD_ON_MWTC_HIGH, devpriv->i_IobaseAddon + 0);
 		outw((devpriv->ui_DmaBufferUsesize[0] / 65536),
 			devpriv->i_IobaseAddon + 2);
 
-		//5
-		// To configure A2P FIFO
-		// testing outl( FIFO_ADVANCE_ON_BYTE_2,devpriv->i_IobaseAmcc+AMCC_OP_REG_INTCSR);
+/*
+ * 5
+ * To configure A2P FIFO testing outl(
+ * FIFO_ADVANCE_ON_BYTE_2,devpriv->i_IobaseAmcc+AMCC_OP_REG_INTCSR);
+ */
 
 		/******************/
 		/* A2P FIFO RESET */
 		/******************/
-		// TO VERIFY
-		//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
+/*
+ * TO VERIFY BEGIN JK 07.05.04: Comparison between WIN32 and Linux
+ * driver
+ */
 		outl(0x04000000UL, devpriv->i_IobaseAmcc + AMCC_OP_REG_MCSR);
-		//END JK 07.05.04: Comparison between WIN32 and Linux driver
+		/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
 
-		//6
-		//ENABLE A2P FIFO WRITE AND ENABLE AMWEN
-		// AMWEN_ENABLE | A2P_FIFO_WRITE_ENABLE (0x01|0x02)=0x03
-		//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
-		//outw(3,devpriv->i_IobaseAddon + 4);
-		//END JK 07.05.04: Comparison between WIN32 and Linux driver
+/*
+ * 6
+ * ENABLE A2P FIFO WRITE AND ENABLE AMWEN AMWEN_ENABLE |
+ * A2P_FIFO_WRITE_ENABLE (0x01|0x02)=0x03
+ */
 
-		//7
-		//initialise end of dma interrupt  AINT_WRITE_COMPL = ENABLE_WRITE_TC_INT(ADDI)
+		/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
+		/* outw(3,devpriv->i_IobaseAddon + 4); */
+		/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
+
+/*
+ * 7
+ * initialise end of dma interrupt AINT_WRITE_COMPL =
+ * ENABLE_WRITE_TC_INT(ADDI)
+ */
 		/***************************************************/
-		/* A2P FIFO CONFIGURATE, END OF DMA INTERRUPT INIT */
+		/* A2P FIFO CONFIGURATE, END OF DMA intERRUPT INIT */
 		/***************************************************/
 		outl((APCI3120_FIFO_ADVANCE_ON_BYTE_2 |
 				APCI3120_ENABLE_WRITE_TC_INT),
 			devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR);
 
-		//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
+		/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
 		/******************************************/
 		/* ENABLE A2P FIFO WRITE AND ENABLE AMWEN */
 		/******************************************/
 		outw(3, devpriv->i_IobaseAddon + 4);
-		//END JK 07.05.04: Comparison between WIN32 and Linux driver
+		/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
 
 		/******************/
 		/* A2P FIFO RESET */
 		/******************/
-		//BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver
+		/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
 		outl(0x04000000UL,
 			devpriv->i_IobaseAmcc + APCI3120_AMCC_OP_MCSR);
-		//END JK 07.05.04: Comparison between WIN32 and Linux driver
+		/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
 	}
 
 	if ((devpriv->us_UseDma == APCI3120_DISABLE)
 		&& !devpriv->b_AiContinuous) {
-		// set gate 2   to start conversion
+		/*  set gate 2   to start conversion */
 		devpriv->us_OutputRegister =
 			devpriv->us_OutputRegister | APCI3120_ENABLE_TIMER2;
 		outw(devpriv->us_OutputRegister,
@@ -1172,14 +1203,14 @@
 
 	switch (mode) {
 	case 1:
-		// set gate 0   to start conversion
+		/*  set gate 0   to start conversion */
 		devpriv->us_OutputRegister =
 			devpriv->us_OutputRegister | APCI3120_ENABLE_TIMER0;
 		outw(devpriv->us_OutputRegister,
 			dev->iobase + APCI3120_WR_ADDRESS);
 		break;
 	case 2:
-		// set  gate 0 and gate 1
+		/*  set  gate 0 and gate 1 */
 		devpriv->us_OutputRegister =
 			devpriv->us_OutputRegister | APCI3120_ENABLE_TIMER1;
 		devpriv->us_OutputRegister =
@@ -1196,7 +1227,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| 			INTERNAL FUNCTIONS						                 |
+| 			intERNAL FUNCTIONS						                 |
 +----------------------------------------------------------------------------+
 */
 
@@ -1218,7 +1249,7 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_Reset(struct comedi_device * dev)
+int i_APCI3120_Reset(struct comedi_device *dev)
 {
 	unsigned int i;
 	unsigned short us_TmpValue;
@@ -1226,47 +1257,49 @@
 	devpriv->b_AiCyclicAcquisition = APCI3120_DISABLE;
 	devpriv->b_EocEosInterrupt = APCI3120_DISABLE;
 	devpriv->b_InterruptMode = APCI3120_EOC_MODE;
-	devpriv->ui_EocEosConversionTime = 0;	// set eoc eos conv time to 0
+	devpriv->ui_EocEosConversionTime = 0;	/*  set eoc eos conv time to 0 */
 	devpriv->b_OutputMemoryStatus = 0;
 
-	// variables used in timer subdevice
+	/*  variables used in timer subdevice */
 	devpriv->b_Timer2Mode = 0;
 	devpriv->b_Timer2Interrupt = 0;
-	devpriv->b_ExttrigEnable = 0;	// Disable ext trigger
+	devpriv->b_ExttrigEnable = 0;	/*  Disable ext trigger */
 
 	/* Disable all interrupts, watchdog for the anolog output */
 	devpriv->b_ModeSelectRegister = 0;
 	outb(devpriv->b_ModeSelectRegister,
 		dev->iobase + APCI3120_WRITE_MODE_SELECT);
 
-	// Disables all counters, ext trigger and clears PA, PR
+	/*  Disables all counters, ext trigger and clears PA, PR */
 	devpriv->us_OutputRegister = 0;
 	outw(devpriv->us_OutputRegister, dev->iobase + APCI3120_WR_ADDRESS);
 
-	//Code to set the all anolog o/p channel to 0v
-	//8191 is decimal value for zero(0 v)volt in bipolar mode(default)
-	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_1, dev->iobase + APCI3120_ANALOG_OUTPUT_1);	//channel 1
-	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_2, dev->iobase + APCI3120_ANALOG_OUTPUT_1);	//channel 2
-	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_3, dev->iobase + APCI3120_ANALOG_OUTPUT_1);	//channel 3
-	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_4, dev->iobase + APCI3120_ANALOG_OUTPUT_1);	//channel 4
+/*
+ * Code to set the all anolog o/p channel to 0v 8191 is decimal
+ * value for zero(0 v)volt in bipolar mode(default)
+ */
+	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_1, dev->iobase + APCI3120_ANALOG_OUTPUT_1);	/* channel 1 */
+	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_2, dev->iobase + APCI3120_ANALOG_OUTPUT_1);	/* channel 2 */
+	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_3, dev->iobase + APCI3120_ANALOG_OUTPUT_1);	/* channel 3 */
+	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_4, dev->iobase + APCI3120_ANALOG_OUTPUT_1);	/* channel 4 */
 
-	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_5, dev->iobase + APCI3120_ANALOG_OUTPUT_2);	//channel 5
-	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_6, dev->iobase + APCI3120_ANALOG_OUTPUT_2);	//channel 6
-	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_7, dev->iobase + APCI3120_ANALOG_OUTPUT_2);	//channel 7
-	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_8, dev->iobase + APCI3120_ANALOG_OUTPUT_2);	//channel 8
+	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_5, dev->iobase + APCI3120_ANALOG_OUTPUT_2);	/* channel 5 */
+	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_6, dev->iobase + APCI3120_ANALOG_OUTPUT_2);	/* channel 6 */
+	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_7, dev->iobase + APCI3120_ANALOG_OUTPUT_2);	/* channel 7 */
+	outw(8191 | APCI3120_ANALOG_OP_CHANNEL_8, dev->iobase + APCI3120_ANALOG_OUTPUT_2);	/* channel 8 */
 
-	//  Reset digital output to L0W
+	/*   Reset digital output to L0W */
 
-//ES05  outb(0x0,dev->iobase+APCI3120_DIGITAL_OUTPUT);
+/* ES05  outb(0x0,dev->iobase+APCI3120_DIGITAL_OUTPUT); */
 	udelay(10);
 
-	inw(dev->iobase + 0);	//make a dummy read
-	inb(dev->iobase + APCI3120_RESET_FIFO);	// flush FIFO
-	inw(dev->iobase + APCI3120_RD_STATUS);	// flush A/D status register
+	inw(dev->iobase + 0);	/* make a dummy read */
+	inb(dev->iobase + APCI3120_RESET_FIFO);	/*  flush FIFO */
+	inw(dev->iobase + APCI3120_RD_STATUS);	/*  flush A/D status register */
 
-	//code to reset the RAM sequence
+	/* code to reset the RAM sequence */
 	for (i = 0; i < 16; i++) {
-		us_TmpValue = i << 8;	//select the location
+		us_TmpValue = i << 8;	/* select the location */
 		outw(us_TmpValue, dev->iobase + APCI3120_SEQ_RAM_ADDRESS);
 	}
 	return 0;
@@ -1296,10 +1329,10 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_SetupChannelList(struct comedi_device * dev, struct comedi_subdevice * s,
+int i_APCI3120_SetupChannelList(struct comedi_device *dev, struct comedi_subdevice *s,
 	int n_chan, unsigned int *chanlist, char check)
 {
-	unsigned int i;		//, differencial=0, bipolar=0;
+	unsigned int i;		/* , differencial=0, bipolar=0; */
 	unsigned int gain;
 	unsigned short us_TmpValue;
 
@@ -1309,29 +1342,29 @@
 			comedi_error(dev, "range/channel list is empty!");
 		return 0;
 	}
-	// All is ok, so we can setup channel/range list
+	/*  All is ok, so we can setup channel/range list */
 	if (check)
 		return 1;
 
-	//Code  to set the PA and PR...Here it set PA to 0..
+	/* Code  to set the PA and PR...Here it set PA to 0.. */
 	devpriv->us_OutputRegister =
 		devpriv->us_OutputRegister & APCI3120_CLEAR_PA_PR;
 	devpriv->us_OutputRegister = ((n_chan - 1) & 0xf) << 8;
 	outw(devpriv->us_OutputRegister, dev->iobase + APCI3120_WR_ADDRESS);
 
 	for (i = 0; i < n_chan; i++) {
-		// store range list to card
-		us_TmpValue = CR_CHAN(chanlist[i]);	// get channel number;
+		/*  store range list to card */
+		us_TmpValue = CR_CHAN(chanlist[i]);	/*  get channel number; */
 
 		if (CR_RANGE(chanlist[i]) < APCI3120_BIPOLAR_RANGES) {
-			us_TmpValue &= ((~APCI3120_UNIPOLAR) & 0xff);	// set bipolar
+			us_TmpValue &= ((~APCI3120_UNIPOLAR) & 0xff);	/*  set bipolar */
 		} else {
-			us_TmpValue |= APCI3120_UNIPOLAR;	// enable unipolar......
+			us_TmpValue |= APCI3120_UNIPOLAR;	/*  enable unipolar...... */
 		}
 
-		gain = CR_RANGE(chanlist[i]);	// get gain number
-		us_TmpValue |= ((gain & 0x03) << 4);	//<<4 for G0 and G1 bit in RAM
-		us_TmpValue |= i << 8;	//To select the RAM LOCATION....
+		gain = CR_RANGE(chanlist[i]);	/*  get gain number */
+		us_TmpValue |= ((gain & 0x03) << 4);	/* <<4 for G0 and G1 bit in RAM */
+		us_TmpValue |= i << 8;	/* To select the RAM LOCATION.... */
 		outw(us_TmpValue, dev->iobase + APCI3120_SEQ_RAM_ADDRESS);
 
 		printk("\n Gain = %i",
@@ -1339,7 +1372,7 @@
 		printk("\n Channel = %i", CR_CHAN(chanlist[i]));
 		printk("\n Polarity = %i", us_TmpValue & APCI3120_UNIPOLAR);
 	}
-	return 1;		// we can serve this with scan logic
+	return 1;		/*  we can serve this with scan logic */
 }
 
 /*
@@ -1360,7 +1393,7 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_ExttrigEnable(struct comedi_device * dev)
+int i_APCI3120_ExttrigEnable(struct comedi_device *dev)
 {
 
 	devpriv->us_OutputRegister |= APCI3120_ENABLE_EXT_TRIGGER;
@@ -1385,7 +1418,7 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_ExttrigDisable(struct comedi_device * dev)
+int i_APCI3120_ExttrigDisable(struct comedi_device *dev)
 {
 	devpriv->us_OutputRegister &= ~APCI3120_ENABLE_EXT_TRIGGER;
 	outw(devpriv->us_OutputRegister, dev->iobase + APCI3120_WR_ADDRESS);
@@ -1394,7 +1427,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-|                    INTERRUPT FUNCTIONS		    		                 |
+|                    intERRUPT FUNCTIONS		    		                 |
 +----------------------------------------------------------------------------+
 */
 
@@ -1422,33 +1455,33 @@
 void v_APCI3120_Interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
-	USHORT int_daq;
+	unsigned short int_daq;
 
 	unsigned int int_amcc, ui_Check, i;
-	USHORT us_TmpValue;
-	BYTE b_DummyRead;
+	unsigned short us_TmpValue;
+	unsigned char b_DummyRead;
 
 	struct comedi_subdevice *s = dev->subdevices + 0;
 	ui_Check = 1;
 
-	int_daq = inw(dev->iobase + APCI3120_RD_STATUS) & 0xf000;	// get IRQ reasons
-	int_amcc = inl(devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR);	// get AMCC INT register
+	int_daq = inw(dev->iobase + APCI3120_RD_STATUS) & 0xf000;	/*  get IRQ reasons */
+	int_amcc = inl(devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR);	/*  get AMCC int register */
 
 	if ((!int_daq) && (!(int_amcc & ANY_S593X_INT))) {
 		comedi_error(dev, "IRQ from unknow source");
 		return;
 	}
 
-	outl(int_amcc | 0x00ff0000, devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR);	// shutdown IRQ reasons in AMCC
+	outl(int_amcc | 0x00ff0000, devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR);	/*  shutdown IRQ reasons in AMCC */
 
 	int_daq = (int_daq >> 12) & 0xF;
 
 	if (devpriv->b_ExttrigEnable == APCI3120_ENABLE) {
-		//Disable ext trigger
+		/* Disable ext trigger */
 		i_APCI3120_ExttrigDisable(dev);
 		devpriv->b_ExttrigEnable = APCI3120_DISABLE;
 	}
-	//clear the timer 2 interrupt
+	/* clear the timer 2 interrupt */
 	inb(devpriv->i_IobaseAmcc + APCI3120_TIMER_STATUS_REGISTER);
 
 	if (int_amcc & MASTER_ABORT_INT)
@@ -1456,19 +1489,19 @@
 	if (int_amcc & TARGET_ABORT_INT)
 		comedi_error(dev, "AMCC IRQ - TARGET DMA ABORT!");
 
-	// Ckeck if EOC interrupt
+	/*  Ckeck if EOC interrupt */
 	if (((int_daq & 0x8) == 0)
 		&& (devpriv->b_InterruptMode == APCI3120_EOC_MODE)) {
 		if (devpriv->b_EocEosInterrupt == APCI3120_ENABLE) {
 
-			// Read the AI Value
+			/*  Read the AI Value */
 
 			devpriv->ui_AiReadData[0] =
-				(UINT) inw(devpriv->iobase + 0);
+				(unsigned int) inw(devpriv->iobase + 0);
 			devpriv->b_EocEosInterrupt = APCI3120_DISABLE;
-			send_sig(SIGIO, devpriv->tsk_Current, 0);	// send signal to the sample
+			send_sig(SIGIO, devpriv->tsk_Current, 0);	/*  send signal to the sample */
 		} else {
-			//Disable EOC Interrupt
+			/* Disable EOC Interrupt */
 			devpriv->b_ModeSelectRegister =
 				devpriv->
 				b_ModeSelectRegister & APCI3120_DISABLE_EOC_INT;
@@ -1478,10 +1511,10 @@
 		}
 	}
 
-	// Check If EOS interrupt
+	/*  Check If EOS interrupt */
 	if ((int_daq & 0x2) && (devpriv->b_InterruptMode == APCI3120_EOS_MODE)) {
 
-		if (devpriv->b_EocEosInterrupt == APCI3120_ENABLE)	// enable this in without DMA ???
+		if (devpriv->b_EocEosInterrupt == APCI3120_ENABLE)	/*  enable this in without DMA ??? */
 		{
 
 			if (devpriv->b_AiCyclicAcquisition == APCI3120_ENABLE) {
@@ -1501,12 +1534,12 @@
 					i++) {
 					us_TmpValue = inw(devpriv->iobase + 0);
 					devpriv->ui_AiReadData[i] =
-						(UINT) us_TmpValue;
+						(unsigned int) us_TmpValue;
 				}
 				devpriv->b_EocEosInterrupt = APCI3120_DISABLE;
 				devpriv->b_InterruptMode = APCI3120_EOC_MODE;
 
-				send_sig(SIGIO, devpriv->tsk_Current, 0);	// send signal to the sample
+				send_sig(SIGIO, devpriv->tsk_Current, 0);	/*  send signal to the sample */
 
 			}
 
@@ -1516,12 +1549,12 @@
 				b_ModeSelectRegister & APCI3120_DISABLE_EOS_INT;
 			outb(devpriv->b_ModeSelectRegister,
 				dev->iobase + APCI3120_WRITE_MODE_SELECT);
-			devpriv->b_EocEosInterrupt = APCI3120_DISABLE;	//Default settings
+			devpriv->b_EocEosInterrupt = APCI3120_DISABLE;	/* Default settings */
 			devpriv->b_InterruptMode = APCI3120_EOC_MODE;
 		}
 
 	}
-	//Timer2 interrupt
+	/* Timer2 interrupt */
 	if (int_daq & 0x1) {
 
 		switch (devpriv->b_Timer2Mode) {
@@ -1534,18 +1567,18 @@
 			outb(devpriv->b_ModeSelectRegister,
 				dev->iobase + APCI3120_WRITE_MODE_SELECT);
 
-			// stop timer 2
+			/*  stop timer 2 */
 			devpriv->us_OutputRegister =
 				devpriv->
 				us_OutputRegister & APCI3120_DISABLE_ALL_TIMER;
 			outw(devpriv->us_OutputRegister,
 				dev->iobase + APCI3120_WR_ADDRESS);
 
-			//stop timer 0 and timer 1
+			/* stop timer 0 and timer 1 */
 			i_APCI3120_StopCyclicAcquisition(dev, s);
 			devpriv->b_AiCyclicAcquisition = APCI3120_DISABLE;
 
-			//UPDATE-0.7.57->0.7.68comedi_done(dev,s);
+			/* UPDATE-0.7.57->0.7.68comedi_done(dev,s); */
 			s->async->events |= COMEDI_CB_EOA;
 			comedi_event(dev, s);
 
@@ -1553,19 +1586,19 @@
 
 		case APCI3120_TIMER:
 
-			//Send a signal to from kernel to user space
+			/* Send a signal to from kernel to user space */
 			send_sig(SIGIO, devpriv->tsk_Current, 0);
 			break;
 
 		case APCI3120_WATCHDOG:
 
-			//Send a signal to from kernel to user space
+			/* Send a signal to from kernel to user space */
 			send_sig(SIGIO, devpriv->tsk_Current, 0);
 			break;
 
 		default:
 
-			// disable Timer Interrupt
+			/*  disable Timer Interrupt */
 
 			devpriv->b_ModeSelectRegister =
 				devpriv->
@@ -1585,7 +1618,7 @@
 		if (devpriv->b_AiCyclicAcquisition == APCI3120_ENABLE) {
 
 			/****************************/
-			/* Clear Timer Write TC INT */
+			/* Clear Timer Write TC int */
 			/****************************/
 
 			outl(APCI3120_CLEAR_WRITE_TC_INT,
@@ -1596,7 +1629,7 @@
 			/* Clears the timer status register */
 			/************************************/
 			inw(dev->iobase + APCI3120_TIMER_STATUS_REGISTER);
-			v_APCI3120_InterruptDma(irq, d);	// do some data transfer
+			v_APCI3120_InterruptDma(irq, d);	/*  do some data transfer */
 		} else {
 			/* Stops the Timer */
 			outw(devpriv->
@@ -1630,32 +1663,8 @@
 +----------------------------------------------------------------------------+
 */
 
-/*
- * int i_APCI3120_InterruptHandleEos(struct comedi_device *dev)
-{
-       int n_chan,i;
-       short *data;
-       struct comedi_subdevice *s=dev->subdevices+0;
-       struct comedi_async *async = s->async;
-       data=async->data+async->buf_int_ptr;
-        n_chan=devpriv->ui_AiNbrofChannels;
 
-       for(i=0;i<n_chan;i++)
-         {
-           data[i]=inw(dev->iobase+0);
-         }
-       async->buf_int_count+=n_chan*sizeof(short);
-       async->buf_int_ptr+=n_chan*sizeof(short);
-       comedi_eos(dev,s);
-       if (s->async->buf_int_ptr>=s->async->data_len) //  for buffer rool over
-		         {
-*//* buffer rollover */
-/*	        s->async->buf_int_ptr=0;
-		comedi_eobuf(dev,s);
-         }
- 	return 0;
-}*/
-int i_APCI3120_InterruptHandleEos(struct comedi_device * dev)
+int i_APCI3120_InterruptHandleEos(struct comedi_device *dev)
 {
 	int n_chan, i;
 	struct comedi_subdevice *s = dev->subdevices + 0;
@@ -1704,7 +1713,7 @@
 	unsigned int next_dma_buf, samplesinbuf;
 	unsigned long low_word, high_word, var;
 
-	UINT ui_Tmp;
+	unsigned int ui_Tmp;
 	samplesinbuf =
 		devpriv->ui_DmaBufferUsesize[devpriv->ui_DmaActualBuffer] -
 		inl(devpriv->i_IobaseAmcc + AMCC_OP_REG_MWTC);
@@ -1720,20 +1729,20 @@
 
 		return;
 	}
-	samplesinbuf = samplesinbuf >> 1;	// number of received samples
+	samplesinbuf = samplesinbuf >> 1;	/*  number of received samples */
 	if (devpriv->b_DmaDoubleBuffer) {
-		// switch DMA buffers if is used double buffering
+		/*  switch DMA buffers if is used double buffering */
 		next_dma_buf = 1 - devpriv->ui_DmaActualBuffer;
 
 		ui_Tmp = AGCSTS_TC_ENABLE | AGCSTS_RESET_A2P_FIFO;
 		outl(ui_Tmp, devpriv->i_IobaseAddon + AMCC_OP_REG_AGCSTS);
 
-		// changed  since 16 bit interface for add on
+		/*  changed  since 16 bit interface for add on */
 		outw(APCI3120_ADD_ON_AGCSTS_LOW, devpriv->i_IobaseAddon + 0);
 		outw(APCI3120_ENABLE_TRANSFER_ADD_ON_LOW,
 			devpriv->i_IobaseAddon + 2);
 		outw(APCI3120_ADD_ON_AGCSTS_HIGH, devpriv->i_IobaseAddon + 0);
-		outw(APCI3120_ENABLE_TRANSFER_ADD_ON_HIGH, devpriv->i_IobaseAddon + 2);	// 0x1000 is out putted in windows driver
+		outw(APCI3120_ENABLE_TRANSFER_ADD_ON_HIGH, devpriv->i_IobaseAddon + 2);	/*  0x1000 is out putted in windows driver */
 
 		var = devpriv->ul_DmaBufferHw[next_dma_buf];
 		low_word = var & 0xffff;
@@ -1761,54 +1770,18 @@
 		outw(APCI3120_ADD_ON_MWTC_HIGH, devpriv->i_IobaseAddon + 0);
 		outw(high_word, devpriv->i_IobaseAddon + 2);
 
-		// To configure A2P FIFO
-		// ENABLE A2P FIFO WRITE AND ENABLE AMWEN
-		// AMWEN_ENABLE | A2P_FIFO_WRITE_ENABLE (0x01|0x02)=0x03
+/*
+ * To configure A2P FIFO
+ * ENABLE A2P FIFO WRITE AND ENABLE AMWEN
+ * AMWEN_ENABLE | A2P_FIFO_WRITE_ENABLE (0x01|0x02)=0x03
+ */
 		outw(3, devpriv->i_IobaseAddon + 4);
-		//initialise end of dma interrupt  AINT_WRITE_COMPL = ENABLE_WRITE_TC_INT(ADDI)
+		/* initialise end of dma interrupt  AINT_WRITE_COMPL = ENABLE_WRITE_TC_INT(ADDI) */
 		outl((APCI3120_FIFO_ADVANCE_ON_BYTE_2 |
 				APCI3120_ENABLE_WRITE_TC_INT),
 			devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR);
 
 	}
-/*UPDATE-0.7.57->0.7.68
-	ptr=(short *)devpriv->ul_DmaBufferVirtual[devpriv->ui_DmaActualBuffer];
-
-
-	// if there is not enough space left in the buffer to copy all data contained in the DMABufferVirtual
-	if(s->async->buf_int_ptr+samplesinbuf*sizeof(short)>=devpriv->ui_AiDataLength)
-	{
-		m=(devpriv->ui_AiDataLength-s->async->buf_int_ptr)/sizeof(short);
-		v_APCI3120_InterruptDmaMoveBlock16bit(dev,s,(void *)ptr,((void *)(devpriv->AiData))+s->async->buf_int_ptr,m);
-		s->async->buf_int_count+=m*sizeof(short);
-		ptr+=m*sizeof(short);
-                samplesinbuf-=m;
-		s->async->buf_int_ptr=0;
-		comedi_eobuf(dev,s);
-	}
-
-	if (samplesinbuf)
-	{
-	        v_APCI3120_InterruptDmaMoveBlock16bit(dev,s,(void *)ptr,((void *)(devpriv->AiData))+s->async->buf_int_ptr,samplesinbuf);
-
-		s->async->buf_int_count+=samplesinbuf*sizeof(short);
-		s->async->buf_int_ptr+=samplesinbuf*sizeof(short);
-		if (!(devpriv->ui_AiFlags & TRIG_WAKE_EOS))
-		{
-			comedi_bufcheck(dev,s);
-                }
-	}
-	if (!devpriv->b_AiContinuous)
-	if ( devpriv->ui_AiActualScan>=devpriv->ui_AiNbrofScans )
-	{
-	    // all data sampled
-	    i_APCI3120_StopCyclicAcquisition(dev,s);
-            devpriv->b_AiCyclicAcquisition=APCI3120_DISABLE;
-	    //DPRINTK("\n Single DMA completed..\n");
-		comedi_done(dev,s);
-            	return;
-	}
-*/
 	if (samplesinbuf) {
 		v_APCI3120_InterruptDmaMoveBlock16bit(dev, s,
 			devpriv->ul_DmaBufferVirtual[devpriv->
@@ -1821,7 +1794,7 @@
 	}
 	if (!devpriv->b_AiContinuous)
 		if (devpriv->ui_AiActualScan >= devpriv->ui_AiNbrofScans) {
-			// all data sampled
+			/*  all data sampled */
 			i_APCI3120_StopCyclicAcquisition(dev, s);
 			devpriv->b_AiCyclicAcquisition = APCI3120_DISABLE;
 			s->async->events |= COMEDI_CB_EOA;
@@ -1829,22 +1802,26 @@
 			return;
 		}
 
-	if (devpriv->b_DmaDoubleBuffer) {	// switch dma buffers
+	if (devpriv->b_DmaDoubleBuffer) {	/*  switch dma buffers */
 		devpriv->ui_DmaActualBuffer = 1 - devpriv->ui_DmaActualBuffer;
 	} else {
-		// restart DMA if is not used double buffering
-		//ADDED REINITIALISE THE DMA
+/*
+ * restart DMA if is not used double buffering
+ * ADDED REINITIALISE THE DMA
+ */
 		ui_Tmp = AGCSTS_TC_ENABLE | AGCSTS_RESET_A2P_FIFO;
 		outl(ui_Tmp, devpriv->i_IobaseAddon + AMCC_OP_REG_AGCSTS);
 
-		// changed  since 16 bit interface for add on
+		/*  changed  since 16 bit interface for add on */
 		outw(APCI3120_ADD_ON_AGCSTS_LOW, devpriv->i_IobaseAddon + 0);
 		outw(APCI3120_ENABLE_TRANSFER_ADD_ON_LOW,
 			devpriv->i_IobaseAddon + 2);
 		outw(APCI3120_ADD_ON_AGCSTS_HIGH, devpriv->i_IobaseAddon + 0);
-		outw(APCI3120_ENABLE_TRANSFER_ADD_ON_HIGH, devpriv->i_IobaseAddon + 2);	//
-		// A2P FIFO MANAGEMENT
-		// A2P fifo reset  & transfer control enable
+		outw(APCI3120_ENABLE_TRANSFER_ADD_ON_HIGH, devpriv->i_IobaseAddon + 2);	/*  */
+/*
+ * A2P FIFO MANAGEMENT
+ * A2P fifo reset & transfer control enable
+ */
 		outl(APCI3120_A2P_FIFO_MANAGEMENT,
 			devpriv->i_IobaseAmcc + AMCC_OP_REG_MCSR);
 
@@ -1858,7 +1835,7 @@
 		outw(high_word, devpriv->i_IobaseAddon + 2);
 
 		var = devpriv->ui_DmaBufferUsesize[0];
-		low_word = var & 0xffff;	//changed
+		low_word = var & 0xffff;	/* changed */
 		var = devpriv->ui_DmaBufferUsesize[0];
 		high_word = var / 65536;
 		outw(APCI3120_ADD_ON_MWTC_LOW, devpriv->i_IobaseAddon + 0);
@@ -1866,11 +1843,13 @@
 		outw(APCI3120_ADD_ON_MWTC_HIGH, devpriv->i_IobaseAddon + 0);
 		outw(high_word, devpriv->i_IobaseAddon + 2);
 
-		// To configure A2P FIFO
-		//ENABLE A2P FIFO WRITE AND ENABLE AMWEN
-		// AMWEN_ENABLE | A2P_FIFO_WRITE_ENABLE (0x01|0x02)=0x03
+/*
+ * To configure A2P FIFO
+ * ENABLE A2P FIFO WRITE AND ENABLE AMWEN
+ * AMWEN_ENABLE | A2P_FIFO_WRITE_ENABLE (0x01|0x02)=0x03
+ */
 		outw(3, devpriv->i_IobaseAddon + 4);
-		//initialise end of dma interrupt  AINT_WRITE_COMPL = ENABLE_WRITE_TC_INT(ADDI)
+		/* initialise end of dma interrupt  AINT_WRITE_COMPL = ENABLE_WRITE_TC_INT(ADDI) */
 		outl((APCI3120_FIFO_ADVANCE_ON_BYTE_2 |
 				APCI3120_ENABLE_WRITE_TC_INT),
 			devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR);
@@ -1897,37 +1876,8 @@
 +----------------------------------------------------------------------------+
 */
 
-/*void v_APCI3120_InterruptDmaMoveBlock16bit(struct comedi_device *dev,struct comedi_subdevice *s,short *dma,short *data,int n)
-{
-	int i,j,m;
-
-	j=s->async->cur_chan;
-	m=devpriv->ui_AiActualScanPosition;
-        for(i=0;i<n;i++)
-	{
-		*data=*dma;
-   		data++; dma++;
-		j++;
-		if(j>=devpriv->ui_AiNbrofChannels)
-		{
-			m+=j;
-			j=0;
-			if(m>=devpriv->ui_AiScanLength)
-			{
-				m=0;
-			        devpriv->ui_AiActualScan++;
-				if (devpriv->ui_AiFlags & TRIG_WAKE_EOS)
-;//UPDATE-0.7.57->0.7.68					comedi_eos(dev,s);
-			}
-		}
-	}
-        devpriv->ui_AiActualScanPosition=m;
-	s->async->cur_chan=j;
-
-}
-*/
-void v_APCI3120_InterruptDmaMoveBlock16bit(struct comedi_device * dev,
-	struct comedi_subdevice * s, short * dma_buffer, unsigned int num_samples)
+void v_APCI3120_InterruptDmaMoveBlock16bit(struct comedi_device *dev,
+	struct comedi_subdevice *s, short *dma_buffer, unsigned int num_samples)
 {
 	devpriv->ui_AiActualScan +=
 		(s->async->cur_chan + num_samples) / devpriv->ui_AiScanLength;
@@ -1968,71 +1918,77 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_InsnConfigTimer(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3120_InsnConfigTimer(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
-	UINT ui_Timervalue2;
-	USHORT us_TmpValue;
-	BYTE b_Tmp;
+	unsigned int ui_Timervalue2;
+	unsigned short us_TmpValue;
+	unsigned char b_Tmp;
 
 	if (!data[1])
 		comedi_error(dev, "config:No timer constant !");
 
-	devpriv->b_Timer2Interrupt = (BYTE) data[2];	// save info whether to enable or disable interrupt
+	devpriv->b_Timer2Interrupt = (unsigned char) data[2];	/*  save info whether to enable or disable interrupt */
 
-	ui_Timervalue2 = data[1] / 1000;	// convert nano seconds  to u seconds
+	ui_Timervalue2 = data[1] / 1000;	/*  convert nano seconds  to u seconds */
 
-	//this_board->i_hwdrv_InsnConfigTimer(dev, ui_Timervalue2,(BYTE)data[0]);
-	us_TmpValue = (USHORT) inw(devpriv->iobase + APCI3120_RD_STATUS);
+	/* this_board->i_hwdrv_InsnConfigTimer(dev, ui_Timervalue2,(unsigned char)data[0]); */
+	us_TmpValue = (unsigned short) inw(devpriv->iobase + APCI3120_RD_STATUS);
 
-	//EL250804: Testing if board APCI3120 have the new Quartz or if it is an APCI3001
-	// and calculate the time value to set in the timer
+/*
+ * EL250804: Testing if board APCI3120 have the new Quartz or if it
+ * is an APCI3001 and calculate the time value to set in the timer
+ */
 	if ((us_TmpValue & 0x00B0) == 0x00B0
 		|| !strcmp(this_board->pc_DriverName, "apci3001")) {
-		//Calculate the time value to set in the timer
+		/* Calculate the time value to set in the timer */
 		ui_Timervalue2 = ui_Timervalue2 / 50;
 	} else {
-		//Calculate the time value to set in the timer
+		/* Calculate the time value to set in the timer */
 		ui_Timervalue2 = ui_Timervalue2 / 70;
 	}
 
-	//Reset gate 2 of Timer 2 to disable it (Set Bit D14 to 0)
+	/* Reset gate 2 of Timer 2 to disable it (Set Bit D14 to 0) */
 	devpriv->us_OutputRegister =
 		devpriv->us_OutputRegister & APCI3120_DISABLE_TIMER2;
 	outw(devpriv->us_OutputRegister, devpriv->iobase + APCI3120_WR_ADDRESS);
 
-	// Disable TIMER Interrupt
+	/*  Disable TIMER Interrupt */
 	devpriv->b_ModeSelectRegister =
 		devpriv->
 		b_ModeSelectRegister & APCI3120_DISABLE_TIMER_INT & 0xEF;
 
-	// Disable Eoc and Eos Interrupts
+	/*  Disable Eoc and Eos Interrupts */
 	devpriv->b_ModeSelectRegister =
 		devpriv->
 		b_ModeSelectRegister & APCI3120_DISABLE_EOC_INT &
 		APCI3120_DISABLE_EOS_INT;
 	outb(devpriv->b_ModeSelectRegister,
 		devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
-	if (data[0] == APCI3120_TIMER)	//initialize timer
+	if (data[0] == APCI3120_TIMER)	/* initialize timer */
 	{
+		/* devpriv->b_ModeSelectRegister=devpriv->b_ModeSelectRegister |
+		 * APCI3120_ENABLE_TIMER_INT; */
 
-		//devpriv->b_ModeSelectRegister=devpriv->b_ModeSelectRegister| APCI3120_ENABLE_TIMER_INT ;
-		//outb(devpriv->b_ModeSelectRegister,devpriv->iobase+APCI3120_WRITE_MODE_SELECT);
+		/* outb(devpriv->b_ModeSelectRegister,devpriv->iobase+APCI3120_WRITE_MODE_SELECT); */
 
-		//Set the Timer 2 in mode 2(Timer)
+		/* Set the Timer 2 in mode 2(Timer) */
 		devpriv->b_TimerSelectMode =
 			(devpriv->
 			b_TimerSelectMode & 0x0F) | APCI3120_TIMER_2_MODE_2;
 		outb(devpriv->b_TimerSelectMode,
 			devpriv->iobase + APCI3120_TIMER_CRT1);
 
-		//Configure the timer 2 for writing the LOW WORD of timer is Delay value
-		//You must make a b_tmp variable with DigitalOutPutRegister because at Address_1+APCI3120_TIMER_CRT0
-		//you can set the digital output and configure the timer 2,and if you don't make this, digital output
-		//are erase (Set to 0)
+/*
+ * Configure the timer 2 for writing the LOW unsigned short of timer
+ * is Delay value You must make a b_tmp variable with
+ * DigitalOutPutRegister because at Address_1+APCI3120_TIMER_CRT0
+ * you can set the digital output and configure the timer 2,and if
+ * you don't make this, digital output are erase (Set to 0)
+ */
 
-		//Writing LOW WORD
+		/* Writing LOW unsigned short */
 		b_Tmp = ((devpriv->
 				b_DigitalOutputRegister) & 0xF0) |
 			APCI3120_SELECT_TIMER_2_LOW_WORD;
@@ -2040,20 +1996,20 @@
 		outw(LOWORD(ui_Timervalue2),
 			devpriv->iobase + APCI3120_TIMER_VALUE);
 
-		//Writing HIGH WORD
+		/* Writing HIGH unsigned short */
 		b_Tmp = ((devpriv->
 				b_DigitalOutputRegister) & 0xF0) |
 			APCI3120_SELECT_TIMER_2_HIGH_WORD;
 		outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
 		outw(HIWORD(ui_Timervalue2),
 			devpriv->iobase + APCI3120_TIMER_VALUE);
-		// timer2 in Timer mode enabled
+		/*  timer2 in Timer mode enabled */
 		devpriv->b_Timer2Mode = APCI3120_TIMER;
 
-	} else			// Initialize Watch dog
+	} else			/*  Initialize Watch dog */
 	{
 
-		//Set the Timer 2 in mode 5(Watchdog)
+		/* Set the Timer 2 in mode 5(Watchdog) */
 
 		devpriv->b_TimerSelectMode =
 			(devpriv->
@@ -2061,12 +2017,15 @@
 		outb(devpriv->b_TimerSelectMode,
 			devpriv->iobase + APCI3120_TIMER_CRT1);
 
-		//Configure the timer 2 for writing the LOW WORD of timer is Delay value
-		//You must make a b_tmp variable with DigitalOutPutRegister because at Address_1+APCI3120_TIMER_CRT0
-		//you can set the digital output and configure the timer 2,and if you don't make this, digital output
-		//are erase (Set to 0)
+/*
+ * Configure the timer 2 for writing the LOW unsigned short of timer
+ * is Delay value You must make a b_tmp variable with
+ * DigitalOutPutRegister because at Address_1+APCI3120_TIMER_CRT0
+ * you can set the digital output and configure the timer 2,and if
+ * you don't make this, digital output are erase (Set to 0)
+ */
 
-		//Writing LOW WORD
+		/* Writing LOW unsigned short */
 		b_Tmp = ((devpriv->
 				b_DigitalOutputRegister) & 0xF0) |
 			APCI3120_SELECT_TIMER_2_LOW_WORD;
@@ -2074,7 +2033,7 @@
 		outw(LOWORD(ui_Timervalue2),
 			devpriv->iobase + APCI3120_TIMER_VALUE);
 
-		//Writing HIGH WORD
+		/* Writing HIGH unsigned short */
 		b_Tmp = ((devpriv->
 				b_DigitalOutputRegister) & 0xF0) |
 			APCI3120_SELECT_TIMER_2_HIGH_WORD;
@@ -2082,7 +2041,7 @@
 
 		outw(HIWORD(ui_Timervalue2),
 			devpriv->iobase + APCI3120_TIMER_VALUE);
-		//watchdog enabled
+		/* watchdog enabled */
 		devpriv->b_Timer2Mode = APCI3120_WATCHDOG;
 
 	}
@@ -2119,13 +2078,13 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_InsnWriteTimer(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3120_InsnWriteTimer(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
-	UINT ui_Timervalue2 = 0;
-	USHORT us_TmpValue;
-	BYTE b_Tmp;
+	unsigned int ui_Timervalue2 = 0;
+	unsigned short us_TmpValue;
+	unsigned char b_Tmp;
 
 	if ((devpriv->b_Timer2Mode != APCI3120_WATCHDOG)
 		&& (devpriv->b_Timer2Mode != APCI3120_TIMER)) {
@@ -2133,7 +2092,7 @@
 		return -EINVAL;
 	}
 
-	if (data[0] == 2)	// write new value
+	if (data[0] == 2)	/*  write new value */
 	{
 		if (devpriv->b_Timer2Mode != APCI3120_TIMER) {
 			comedi_error(dev,
@@ -2147,35 +2106,35 @@
 			ui_Timervalue2 = 0;
 	}
 
-	//this_board->i_hwdrv_InsnWriteTimer(dev,data[0],ui_Timervalue2);
+	/* this_board->i_hwdrv_InsnWriteTimer(dev,data[0],ui_Timervalue2); */
 
 	switch (data[0]) {
 	case APCI3120_START:
 
-		// Reset FC_TIMER BIT
+		/*  Reset FC_TIMER BIT */
 		inb(devpriv->iobase + APCI3120_TIMER_STATUS_REGISTER);
-		if (devpriv->b_Timer2Mode == APCI3120_TIMER)	//start timer
+		if (devpriv->b_Timer2Mode == APCI3120_TIMER)	/* start timer */
 		{
-			//Enable Timer
+			/* Enable Timer */
 			devpriv->b_ModeSelectRegister =
 				devpriv->b_ModeSelectRegister & 0x0B;
-		} else		//start watch dog
+		} else		/* start watch dog */
 		{
-			//Enable WatchDog
+			/* Enable WatchDog */
 			devpriv->b_ModeSelectRegister =
 				(devpriv->
 				b_ModeSelectRegister & 0x0B) |
 				APCI3120_ENABLE_WATCHDOG;
 		}
 
-		//enable disable interrupt
+		/* enable disable interrupt */
 		if ((devpriv->b_Timer2Interrupt) == APCI3120_ENABLE) {
 
 			devpriv->b_ModeSelectRegister =
 				devpriv->
 				b_ModeSelectRegister |
 				APCI3120_ENABLE_TIMER_INT;
-			// save the task structure to pass info to user
+			/*  save the task structure to pass info to user */
 			devpriv->tsk_Current = current;
 		} else {
 
@@ -2187,9 +2146,9 @@
 		outb(devpriv->b_ModeSelectRegister,
 			devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
 
-		if (devpriv->b_Timer2Mode == APCI3120_TIMER)	//start timer
+		if (devpriv->b_Timer2Mode == APCI3120_TIMER)	/* start timer */
 		{
-			//For Timer mode is  Gate2 must be activated   **timer started
+			/* For Timer mode is  Gate2 must be activated   **timer started */
 			devpriv->us_OutputRegister =
 				devpriv->
 				us_OutputRegister | APCI3120_ENABLE_TIMER2;
@@ -2201,62 +2160,64 @@
 
 	case APCI3120_STOP:
 		if (devpriv->b_Timer2Mode == APCI3120_TIMER) {
-			//Disable timer
+			/* Disable timer */
 			devpriv->b_ModeSelectRegister =
 				devpriv->
 				b_ModeSelectRegister &
 				APCI3120_DISABLE_TIMER_COUNTER;
 		} else {
-			//Disable WatchDog
+			/* Disable WatchDog */
 			devpriv->b_ModeSelectRegister =
 				devpriv->
 				b_ModeSelectRegister &
 				APCI3120_DISABLE_WATCHDOG;
 		}
-		// Disable timer interrupt
+		/*  Disable timer interrupt */
 		devpriv->b_ModeSelectRegister =
 			devpriv->
 			b_ModeSelectRegister & APCI3120_DISABLE_TIMER_INT;
 
-		// Write above states  to register
+		/*  Write above states  to register */
 		outb(devpriv->b_ModeSelectRegister,
 			devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
 
-		// Reset Gate 2
+		/*  Reset Gate 2 */
 		devpriv->us_OutputRegister =
 			devpriv->us_OutputRegister & APCI3120_DISABLE_TIMER_INT;
 		outw(devpriv->us_OutputRegister,
 			devpriv->iobase + APCI3120_WR_ADDRESS);
 
-		// Reset FC_TIMER BIT
+		/*  Reset FC_TIMER BIT */
 		inb(devpriv->iobase + APCI3120_TIMER_STATUS_REGISTER);
 
-		// Disable timer
-		//devpriv->b_Timer2Mode=APCI3120_DISABLE;
+		/* Disable timer */
+		/* devpriv->b_Timer2Mode=APCI3120_DISABLE;  */
 
 		break;
 
-	case 2:		//write new value to Timer
+	case 2:		/* write new value to Timer */
 		if (devpriv->b_Timer2Mode != APCI3120_TIMER) {
 			comedi_error(dev,
 				"write :timer2  not configured  in TIMER MODE");
 			return -EINVAL;
 		}
-		// ui_Timervalue2=data[1]; // passed as argument
+		/*  ui_Timervalue2=data[1]; // passed as argument */
 		us_TmpValue =
-			(USHORT) inw(devpriv->iobase + APCI3120_RD_STATUS);
+			(unsigned short) inw(devpriv->iobase + APCI3120_RD_STATUS);
 
-		//EL250804: Testing if board APCI3120 have the new Quartz or if it is an APCI3001
-		// and calculate the time value to set in the timer
+/*
+ * EL250804: Testing if board APCI3120 have the new Quartz or if it
+ * is an APCI3001 and calculate the time value to set in the timer
+ */
 		if ((us_TmpValue & 0x00B0) == 0x00B0
 			|| !strcmp(this_board->pc_DriverName, "apci3001")) {
-			//Calculate the time value to set in the timer
+			/* Calculate the time value to set in the timer */
 			ui_Timervalue2 = ui_Timervalue2 / 50;
 		} else {
-			//Calculate the time value to set in the timer
+			/* Calculate the time value to set in the timer */
 			ui_Timervalue2 = ui_Timervalue2 / 70;
 		}
-		//Writing LOW WORD
+		/* Writing LOW unsigned short */
 		b_Tmp = ((devpriv->
 				b_DigitalOutputRegister) & 0xF0) |
 			APCI3120_SELECT_TIMER_2_LOW_WORD;
@@ -2265,7 +2226,7 @@
 		outw(LOWORD(ui_Timervalue2),
 			devpriv->iobase + APCI3120_TIMER_VALUE);
 
-		//Writing HIGH WORD
+		/* Writing HIGH unsigned short */
 		b_Tmp = ((devpriv->
 				b_DigitalOutputRegister) & 0xF0) |
 			APCI3120_SELECT_TIMER_2_HIGH_WORD;
@@ -2276,7 +2237,7 @@
 
 		break;
 	default:
-		return -EINVAL;	// Not a valid input
+		return -EINVAL;	/*  Not a valid input */
 	}
 
 	return insn->n;
@@ -2305,21 +2266,21 @@
 |                    													     |
 +----------------------------------------------------------------------------+
 */
-int i_APCI3120_InsnReadTimer(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3120_InsnReadTimer(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	BYTE b_Tmp;
-	USHORT us_TmpValue, us_TmpValue_2, us_StatusValue;
+	unsigned char b_Tmp;
+	unsigned short us_TmpValue, us_TmpValue_2, us_StatusValue;
 
 	if ((devpriv->b_Timer2Mode != APCI3120_WATCHDOG)
 		&& (devpriv->b_Timer2Mode != APCI3120_TIMER)) {
 		comedi_error(dev, "\nread:timer2  not configured ");
 	}
 
-	//this_board->i_hwdrv_InsnReadTimer(dev,data);
+	/* this_board->i_hwdrv_InsnReadTimer(dev,data); */
 	if (devpriv->b_Timer2Mode == APCI3120_TIMER) {
 
-		//Read the LOW WORD of Timer 2 register
+		/* Read the LOW unsigned short of Timer 2 register */
 		b_Tmp = ((devpriv->
 				b_DigitalOutputRegister) & 0xF0) |
 			APCI3120_SELECT_TIMER_2_LOW_WORD;
@@ -2327,7 +2288,7 @@
 
 		us_TmpValue = inw(devpriv->iobase + APCI3120_TIMER_VALUE);
 
-		//Read the HIGH WORD of Timer 2 register
+		/* Read the HIGH unsigned short of Timer 2 register */
 		b_Tmp = ((devpriv->
 				b_DigitalOutputRegister) & 0xF0) |
 			APCI3120_SELECT_TIMER_2_HIGH_WORD;
@@ -2335,20 +2296,20 @@
 
 		us_TmpValue_2 = inw(devpriv->iobase + APCI3120_TIMER_VALUE);
 
-		// combining both words
-		data[0] = (UINT) ((us_TmpValue) | ((us_TmpValue_2) << 16));
+		/*  combining both words */
+		data[0] = (unsigned int) ((us_TmpValue) | ((us_TmpValue_2) << 16));
 
-	} else			// Read watch dog status
+	} else			/*  Read watch dog status */
 	{
 
 		us_StatusValue = inw(devpriv->iobase + APCI3120_RD_STATUS);
 		us_StatusValue =
 			((us_StatusValue & APCI3120_FC_TIMER) >> 12) & 1;
 		if (us_StatusValue == 1) {
-			// RESET FC_TIMER BIT
+			/*  RESET FC_TIMER BIT */
 			inb(devpriv->iobase + APCI3120_TIMER_STATUS_REGISTER);
 		}
-		data[0] = us_StatusValue;	// when data[0] = 1 then the watch dog has rundown
+		data[0] = us_StatusValue;	/*  when data[0] = 1 then the watch dog has rundown */
 	}
 	return insn->n;
 }
@@ -2384,21 +2345,23 @@
 				    struct comedi_insn *insn,
 				    unsigned int *data)
 {
-	UINT ui_Chan, ui_TmpValue;
+	unsigned int ui_Chan, ui_TmpValue;
 
-	ui_Chan = CR_CHAN(insn->chanspec);	// channel specified
+	ui_Chan = CR_CHAN(insn->chanspec);	/*  channel specified */
 
-	//this_board->i_hwdrv_InsnReadDigitalInput(dev,ui_Chan,data);
+	/* this_board->i_hwdrv_InsnReadDigitalInput(dev,ui_Chan,data); */
 	if (ui_Chan >= 0 && ui_Chan <= 3) {
-		ui_TmpValue = (UINT) inw(devpriv->iobase + APCI3120_RD_STATUS);
+		ui_TmpValue = (unsigned int) inw(devpriv->iobase + APCI3120_RD_STATUS);
 
-		//      since only 1 channel reqd  to bring it to last bit it is rotated
-		//  8 +(chan - 1) times then ANDed with 1 for last bit.
+/*
+ * since only 1 channel reqd to bring it to last bit it is rotated 8
+ * +(chan - 1) times then ANDed with 1 for last bit.
+ */
 		*data = (ui_TmpValue >> (ui_Chan + 8)) & 1;
-		//return 0;
+		/* return 0; */
 	} else {
-		//      comedi_error(dev," chan spec wrong");
-		return -EINVAL;	// "sorry channel spec wrong "
+		/*       comedi_error(dev," chan spec wrong"); */
+		return -EINVAL;	/*  "sorry channel spec wrong " */
 	}
 	return insn->n;
 
@@ -2423,18 +2386,18 @@
 |                    													     |
 +----------------------------------------------------------------------------+
 */
-int i_APCI3120_InsnBitsDigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3120_InsnBitsDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_TmpValue;
-	ui_TmpValue = (UINT) inw(devpriv->iobase + APCI3120_RD_STATUS);
+	unsigned int ui_TmpValue;
+	ui_TmpValue = (unsigned int) inw(devpriv->iobase + APCI3120_RD_STATUS);
 	/*****	state of 4 channels  in the 11, 10, 9, 8   bits of status reg
 			rotated right 8 times to bring them to last four bits
 			ANDed with oxf for  value.
 	*****/
 
 	*data = (ui_TmpValue >> 8) & 0xf;
-	//this_board->i_hwdrv_InsnBitsDigitalInput(dev,data);
+	/* this_board->i_hwdrv_InsnBitsDigitalInput(dev,data); */
 	return insn->n;
 }
 
@@ -2462,8 +2425,8 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_InsnConfigDigitalOutput(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3120_InsnConfigDigitalOutput(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 
 	if ((data[0] != 0) && (data[0] != 1)) {
@@ -2481,7 +2444,7 @@
 	if (!devpriv->b_OutputMemoryStatus) {
 		ui_Temp = 0;
 
-	}			//if(!devpriv->b_OutputMemoryStatus )
+	}			/* if(!devpriv->b_OutputMemoryStatus ) */
 
 	return insn->n;
 }
@@ -2499,16 +2462,16 @@
 |                     struct comedi_subdevice *s									 |
 |                     struct comedi_insn *insn                                      |
 |                     unsigned int *data 										 |
-                      data[0]     Value to be written
-                      data[1]    :1 Set digital o/p ON
-                      data[1]     2 Set digital o/p OFF with memory ON
+|                      data[0]     Value to be written
+|                      data[1]    :1 Set digital o/p ON
+|                      data[1]     2 Set digital o/p OFF with memory ON
 +----------------------------------------------------------------------------+
 | Return Value      :              					                         |
 |                    													     |
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3120_InsnBitsDigitalOutput(struct comedi_device * dev,
+int i_APCI3120_InsnBitsDigitalOutput(struct comedi_device *dev,
 				     struct comedi_subdevice *s,
 				     struct comedi_insn *insn,
 				     unsigned int *data)
@@ -2530,7 +2493,7 @@
 	default:
 		printk("\nThe parameter passed is in error \n");
 		return -EINVAL;
-	}			// switch(data[1])
+	}			/*  switch(data[1]) */
 	outb(data[0], devpriv->iobase + APCI3120_DIGITAL_OUTPUT);
 
 	devpriv->b_DigitalOutputRegister = data[0] & 0xF0;
@@ -2567,9 +2530,9 @@
 				      unsigned int *data)
 {
 
-	UINT ui_Temp1;
+	unsigned int ui_Temp1;
 
-	UINT ui_NoOfChannel = CR_CHAN(insn->chanspec);	// get the channel
+	unsigned int ui_NoOfChannel = CR_CHAN(insn->chanspec);	/*  get the channel */
 
 	if ((data[0] != 0) && (data[0] != 1)) {
 		comedi_error(dev,
@@ -2586,7 +2549,7 @@
 	switch (data[1]) {
 	case 1:
 		data[0] = (data[0] << ui_NoOfChannel);
-//ES05                   data[0]=(data[0]<<4)|ui_Temp;
+/* ES05                   data[0]=(data[0]<<4)|ui_Temp; */
 		data[0] = (data[0] << 4) | devpriv->b_DigitalOutputRegister;
 		break;
 
@@ -2595,24 +2558,24 @@
 		ui_Temp1 = 1;
 		ui_Temp1 = ui_Temp1 << ui_NoOfChannel;
 		ui_Temp1 = ui_Temp1 << 4;
-//ES05                   ui_Temp=ui_Temp|ui_Temp1;
+/* ES05                   ui_Temp=ui_Temp|ui_Temp1; */
 		devpriv->b_DigitalOutputRegister =
 			devpriv->b_DigitalOutputRegister | ui_Temp1;
 
 		data[0] = (data[0] << ui_NoOfChannel) ^ 0xf;
 		data[0] = data[0] << 4;
-//ES05                   data[0]=data[0]& ui_Temp;
+/* ES05                   data[0]=data[0]& ui_Temp; */
 		data[0] = data[0] & devpriv->b_DigitalOutputRegister;
 		break;
 	default:
 		printk("\nThe parameter passed is in error \n");
 		return -EINVAL;
-	}			// switch(data[1])
+	}			/*  switch(data[1]) */
 	outb(data[0], devpriv->iobase + APCI3120_DIGITAL_OUTPUT);
 
-//ES05        ui_Temp=data[0] & 0xf0;
+/* ES05        ui_Temp=data[0] & 0xf0; */
 	devpriv->b_DigitalOutputRegister = data[0] & 0xf0;
-	return (insn->n);
+	return insn->n;
 
 }
 
@@ -2646,14 +2609,14 @@
 				     struct comedi_insn *insn,
 				     unsigned int *data)
 {
-	UINT ui_Range, ui_Channel;
-	USHORT us_TmpValue;
+	unsigned int ui_Range, ui_Channel;
+	unsigned short us_TmpValue;
 
 	ui_Range = CR_RANGE(insn->chanspec);
 	ui_Channel = CR_CHAN(insn->chanspec);
 
-	//this_board->i_hwdrv_InsnWriteAnalogOutput(dev, ui_Range, ui_Channel,data[0]);
-	if (ui_Range)		// if 1 then unipolar
+	/* this_board->i_hwdrv_InsnWriteAnalogOutput(dev, ui_Range, ui_Channel,data[0]); */
+	if (ui_Range)		/*  if 1 then unipolar */
 	{
 
 		if (data[0] != 0)
@@ -2665,7 +2628,7 @@
 				((((ui_Channel & 0x03) << 14) & 0xC000) | (1 <<
 					13) | 8192);
 
-	} else			// if 0 then   bipolar
+	} else			/*  if 0 then   bipolar */
 	{
 		data[0] =
 			((((ui_Channel & 0x03) << 14) & 0xC000) | (0 << 13) |
@@ -2673,24 +2636,30 @@
 
 	}
 
-	//out put n values at the given channel.
-	// rt_printk("\nwaiting for DA_READY BIT");
-	do			//Waiting of DA_READY BIT
+/*
+ * out put n values at the given channel. printk("\nwaiting for
+ * DA_READY BIT");
+ */
+	do			/* Waiting of DA_READY BIT */
 	{
 		us_TmpValue =
-			((USHORT) inw(devpriv->iobase +
+			((unsigned short) inw(devpriv->iobase +
 				APCI3120_RD_STATUS)) & 0x0001;
 	} while (us_TmpValue != 0x0001);
 
 	if (ui_Channel <= 3)
-		// for channel 0-3 out at  the register 1 (wrDac1-8)
-		// data[i] typecasted to ushort since  word write is to be done
-		outw((USHORT) data[0],
+/*
+ * for channel 0-3 out at the register 1 (wrDac1-8) data[i]
+ * typecasted to ushort since word write is to be done
+ */
+		outw((unsigned short) data[0],
 			devpriv->iobase + APCI3120_ANALOG_OUTPUT_1);
 	else
-		// for channel 4-7 out at the register 2 (wrDac5-8)
-		//data[i] typecasted to ushort since  word write is to be done
-		outw((USHORT) data[0],
+/*
+ * for channel 4-7 out at the register 2 (wrDac5-8) data[i]
+ * typecasted to ushort since word write is to be done
+ */
+		outw((unsigned short) data[0],
 			devpriv->iobase + APCI3120_ANALOG_OUTPUT_2);
 
 	return insn->n;
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3120.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3120.h
index 59d5d87..fedfc9c 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3120.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3120.h
@@ -1,5 +1,5 @@
 
-// hwdrv_apci3120.h
+/* hwdrv_apci3120.h */
 
 /*
  * Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
@@ -18,9 +18,9 @@
  * any later version.
  */
 
-// comedi related defines
+/* comedi related defines */
 
-//ANALOG INPUT RANGE
+/* ANALOG INPUT RANGE */
 static const struct comedi_lrange range_apci3120_ai = { 8, {
 						     BIP_RANGE(10),
 						     BIP_RANGE(5),
@@ -33,14 +33,14 @@
 						     }
 };
 
-// ANALOG OUTPUT RANGE
+/* ANALOG OUTPUT RANGE */
 static const struct comedi_lrange range_apci3120_ao = { 2, {
 						     BIP_RANGE(10),
 						     UNI_RANGE(10)
 						     }
 };
 
-#define APCI3120_BIPOLAR_RANGES	4	// used for test on mixture of BIP/UNI ranges
+#define APCI3120_BIPOLAR_RANGES	4	/*  used for test on mixture of BIP/UNI ranges */
 
 #define APCI3120_BOARD_VENDOR_ID                 0x10E8
 #define APCI3120_ADDRESS_RANGE            			16
@@ -55,17 +55,17 @@
 #define     APCI3120_EOS_MODE         2
 #define     APCI3120_DMA_MODE         3
 
-//DIGITAL INPUT-OUTPUT DEFINE
+/* DIGITAL INPUT-OUTPUT DEFINE */
 
 #define APCI3120_DIGITAL_OUTPUT                  	0x0D
 #define APCI3120_RD_STATUS                       	0x02
 #define APCI3120_RD_FIFO                     		0x00
 
-// digital output insn_write ON /OFF selection
+/* digital output insn_write ON /OFF selection */
 #define	APCI3120_SET4DIGITALOUTPUTON				1
 #define APCI3120_SET4DIGITALOUTPUTOFF				0
 
-// analog output SELECT BIT
+/* analog output SELECT BIT */
 #define APCI3120_ANALOG_OP_CHANNEL_1   0x0000
 #define APCI3120_ANALOG_OP_CHANNEL_2   0x4000
 #define APCI3120_ANALOG_OP_CHANNEL_3   0x8000
@@ -75,32 +75,32 @@
 #define APCI3120_ANALOG_OP_CHANNEL_7   0x8000
 #define APCI3120_ANALOG_OP_CHANNEL_8   0xC000
 
-// Enable external trigger bit in nWrAddress
+/* Enable external trigger bit in nWrAddress */
 #define APCI3120_ENABLE_EXT_TRIGGER    0x8000
 
-//ANALOG OUTPUT AND INPUT DEFINE
-#define APCI3120_UNIPOLAR 0x80	//$$ RAM sequence polarity BIT
-#define APCI3120_BIPOLAR  0x00	//$$ RAM sequence polarity BIT
-#define APCI3120_ANALOG_OUTPUT_1 0x08	// (ADDRESS )
-#define APCI3120_ANALOG_OUTPUT_2 0x0A	// (ADDRESS )
-#define APCI3120_1_GAIN              0x00	//$$ RAM sequence Gain Bits for gain 1
-#define APCI3120_2_GAIN              0x10	//$$ RAM sequence Gain Bits for gain 2
-#define APCI3120_5_GAIN              0x20	//$$ RAM sequence Gain Bits for gain 5
-#define APCI3120_10_GAIN             0x30	//$$ RAM sequence Gain Bits for gain 10
-#define APCI3120_SEQ_RAM_ADDRESS        0x06	//$$ EARLIER NAMED APCI3120_FIFO_ADDRESS
-#define APCI3120_RESET_FIFO          0x0C	//(ADDRESS)
-#define APCI3120_TIMER_0_MODE_2      0x01	//$$ Bits for timer mode
+/* ANALOG OUTPUT AND INPUT DEFINE */
+#define APCI3120_UNIPOLAR 0x80	/* $$ RAM sequence polarity BIT */
+#define APCI3120_BIPOLAR  0x00	/* $$ RAM sequence polarity BIT */
+#define APCI3120_ANALOG_OUTPUT_1 0x08	/*  (ADDRESS ) */
+#define APCI3120_ANALOG_OUTPUT_2 0x0A	/*  (ADDRESS ) */
+#define APCI3120_1_GAIN              0x00	/* $$ RAM sequence Gain Bits for gain 1 */
+#define APCI3120_2_GAIN              0x10	/* $$ RAM sequence Gain Bits for gain 2 */
+#define APCI3120_5_GAIN              0x20	/* $$ RAM sequence Gain Bits for gain 5 */
+#define APCI3120_10_GAIN             0x30	/* $$ RAM sequence Gain Bits for gain 10 */
+#define APCI3120_SEQ_RAM_ADDRESS        0x06	/* $$ EARLIER NAMED APCI3120_FIFO_ADDRESS */
+#define APCI3120_RESET_FIFO          0x0C	/* (ADDRESS) */
+#define APCI3120_TIMER_0_MODE_2      0x01	/* $$ Bits for timer mode */
 #define APCI3120_TIMER_0_MODE_4       0x2
 #define APCI3120_SELECT_TIMER_0_WORD 0x00
-#define APCI3120_ENABLE_TIMER0     0x1000	//$$Gatebit 0 in nWrAddress
+#define APCI3120_ENABLE_TIMER0     0x1000	/* $$Gatebit 0 in nWrAddress */
 #define APCI3120_CLEAR_PR          0xF0FF
 #define APCI3120_CLEAR_PA          0xFFF0
 #define APCI3120_CLEAR_PA_PR       (APCI3120_CLEAR_PR & APCI3120_CLEAR_PA)
 
-// nWrMode_Select
-#define APCI3120_ENABLE_SCAN          0x8	//$$ bit in nWrMode_Select
+/* nWrMode_Select */
+#define APCI3120_ENABLE_SCAN          0x8	/* $$ bit in nWrMode_Select */
 #define APCI3120_DISABLE_SCAN      (~APCI3120_ENABLE_SCAN)
-#define APCI3120_ENABLE_EOS_INT       0x2	//$$ bit in nWrMode_Select
+#define APCI3120_ENABLE_EOS_INT       0x2	/* $$ bit in nWrMode_Select */
 
 #define APCI3120_DISABLE_EOS_INT   (~APCI3120_ENABLE_EOS_INT)
 #define APCI3120_ENABLE_EOC_INT       0x1
@@ -108,50 +108,50 @@
 #define APCI3120_DISABLE_ALL_INTERRUPT_WITHOUT_TIMER   (APCI3120_DISABLE_EOS_INT & APCI3120_DISABLE_EOC_INT)
 #define APCI3120_DISABLE_ALL_INTERRUPT   (APCI3120_DISABLE_TIMER_INT & APCI3120_DISABLE_EOS_INT & APCI3120_DISABLE_EOC_INT)
 
-//status register bits
+/* status register bits */
 #define APCI3120_EOC                     0x8000
 #define APCI3120_EOS                     0x2000
 
-// software trigger dummy register
-#define APCI3120_START_CONVERSION        0x02	//(ADDRESS)
+/* software trigger dummy register */
+#define APCI3120_START_CONVERSION        0x02	/* (ADDRESS) */
 
-//TIMER DEFINE
+/* TIMER DEFINE */
 #define APCI3120_QUARTZ_A				  70
 #define APCI3120_QUARTZ_B				  50
 #define APCI3120_TIMER                            1
 #define APCI3120_WATCHDOG                         2
 #define APCI3120_TIMER_DISABLE                    0
 #define APCI3120_TIMER_ENABLE                     1
-#define APCI3120_ENABLE_TIMER2                    0x4000	//$$ gatebit 2 in nWrAddress
+#define APCI3120_ENABLE_TIMER2                    0x4000	/* $$ gatebit 2 in nWrAddress */
 #define APCI3120_DISABLE_TIMER2                   (~APCI3120_ENABLE_TIMER2)
-#define APCI3120_ENABLE_TIMER_INT                 0x04	//$$ ENAIRQ_FC_Bit in nWrModeSelect
+#define APCI3120_ENABLE_TIMER_INT                 0x04	/* $$ ENAIRQ_FC_Bit in nWrModeSelect */
 #define APCI3120_DISABLE_TIMER_INT                (~APCI3120_ENABLE_TIMER_INT)
-#define APCI3120_WRITE_MODE_SELECT                0x0E	// (ADDRESS)
+#define APCI3120_WRITE_MODE_SELECT                0x0E	/*  (ADDRESS) */
 #define APCI3120_SELECT_TIMER_0_WORD  0x00
 #define APCI3120_SELECT_TIMER_1_WORD  0x01
 #define APCI3120_TIMER_1_MODE_2       0x4
 
-//$$ BIT FOR MODE IN nCsTimerCtr1
+/* $$ BIT FOR MODE IN nCsTimerCtr1 */
 #define APCI3120_TIMER_2_MODE_0                   0x0
 #define APCI3120_TIMER_2_MODE_2                   0x10
 #define APCI3120_TIMER_2_MODE_5                   0x30
 
-//$$ BIT FOR MODE IN nCsTimerCtr0
+/* $$ BIT FOR MODE IN nCsTimerCtr0 */
 #define APCI3120_SELECT_TIMER_2_LOW_WORD          0x02
 #define APCI3120_SELECT_TIMER_2_HIGH_WORD         0x03
 
-#define APCI3120_TIMER_CRT0                       0x0D	//(ADDRESS for cCsTimerCtr0)
-#define APCI3120_TIMER_CRT1                       0x0C	//(ADDRESS for cCsTimerCtr1)
+#define APCI3120_TIMER_CRT0                       0x0D	/* (ADDRESS for cCsTimerCtr0) */
+#define APCI3120_TIMER_CRT1                       0x0C	/* (ADDRESS for cCsTimerCtr1) */
 
-#define APCI3120_TIMER_VALUE                      0x04	//ADDRESS for nCsTimerWert
-#define APCI3120_TIMER_STATUS_REGISTER            0x0D	//ADDRESS for delete timer 2 interrupt
-#define APCI3120_RD_STATUS                        0x02	//ADDRESS
-#define APCI3120_WR_ADDRESS                       0x00	//ADDRESS
-#define APCI3120_ENABLE_WATCHDOG                  0x20	//$$BIT in nWrMode_Select
+#define APCI3120_TIMER_VALUE                      0x04	/* ADDRESS for nCsTimerWert */
+#define APCI3120_TIMER_STATUS_REGISTER            0x0D	/* ADDRESS for delete timer 2 interrupt */
+#define APCI3120_RD_STATUS                        0x02	/* ADDRESS */
+#define APCI3120_WR_ADDRESS                       0x00	/* ADDRESS */
+#define APCI3120_ENABLE_WATCHDOG                  0x20	/* $$BIT in nWrMode_Select */
 #define APCI3120_DISABLE_WATCHDOG                 (~APCI3120_ENABLE_WATCHDOG)
-#define APCI3120_ENABLE_TIMER_COUNTER    		  0x10	//$$BIT in nWrMode_Select
+#define APCI3120_ENABLE_TIMER_COUNTER    		  0x10	/* $$BIT in nWrMode_Select */
 #define APCI3120_DISABLE_TIMER_COUNTER            (~APCI3120_ENABLE_TIMER_COUNTER)
-#define APCI3120_FC_TIMER                         0x1000	//bit in  status register
+#define APCI3120_FC_TIMER                         0x1000	/* bit in  status register */
 #define APCI3120_ENABLE_TIMER0                    0x1000
 #define APCI3120_ENABLE_TIMER1                    0x2000
 #define APCI3120_ENABLE_TIMER2                    0x4000
@@ -159,25 +159,27 @@
 #define APCI3120_DISABLE_TIMER1		              (~APCI3120_ENABLE_TIMER1)
 #define APCI3120_DISABLE_TIMER2	                  (~APCI3120_ENABLE_TIMER2)
 
-#define APCI3120_TIMER2_SELECT_EOS                0xC0	// ADDED on 20-6
-#define APCI3120_COUNTER                          3	// on 20-6
-#define APCI3120_DISABLE_ALL_TIMER                ( APCI3120_DISABLE_TIMER0 & APCI3120_DISABLE_TIMER1 & APCI3120_DISABLE_TIMER2 )	// on 20-6
+#define APCI3120_TIMER2_SELECT_EOS                0xC0	/*  ADDED on 20-6 */
+#define APCI3120_COUNTER                          3	/*  on 20-6 */
+#define APCI3120_DISABLE_ALL_TIMER                (APCI3120_DISABLE_TIMER0 & APCI3120_DISABLE_TIMER1 & APCI3120_DISABLE_TIMER2)	/*  on 20-6 */
 
 #define MAX_ANALOGINPUT_CHANNELS    32
 
-typedef struct {
-	BYTE b_Type;		/* EOC or EOS */
-	BYTE b_InterruptFlag;	/* Interrupt use or not                    */
-	UINT ui_ConvertTiming;	/* Selection of the convertion time        */
-	BYTE b_NbrOfChannel;	/* Number of channel to read               */
-	UINT ui_ChannelList[MAX_ANALOGINPUT_CHANNELS];	/* Number of the channel to be read        */
-	UINT ui_RangeList[MAX_ANALOGINPUT_CHANNELS];	/* Gain of each channel                    */
+struct str_AnalogReadInformation {
 
-} str_AnalogReadInformation;
+	unsigned char b_Type;		/* EOC or EOS */
+	unsigned char b_InterruptFlag;	/* Interrupt use or not                    */
+	unsigned int ui_ConvertTiming;	/* Selection of the convertion time        */
+	unsigned char b_NbrOfChannel;	/* Number of channel to read               */
+	unsigned int ui_ChannelList[MAX_ANALOGINPUT_CHANNELS];	/* Number of the channel to be read        */
+	unsigned int ui_RangeList[MAX_ANALOGINPUT_CHANNELS];	/* Gain of each channel                    */
 
-// Function Declaration For APCI-3120
+};
 
-// Internal functions
+
+/* Function Declaration For APCI-3120 */
+
+/* Internal functions */
 int i_APCI3120_SetupChannelList(struct comedi_device *dev, struct comedi_subdevice *s,
 				int n_chan, unsigned int *chanlist, char check);
 int i_APCI3120_ExttrigEnable(struct comedi_device *dev);
@@ -186,9 +188,9 @@
 int i_APCI3120_Reset(struct comedi_device *dev);
 int i_APCI3120_CyclicAnalogInput(int mode, struct comedi_device *dev,
 				 struct comedi_subdevice *s);
-// Interrupt functions
+/* Interrupt functions */
 void v_APCI3120_Interrupt(int irq, void *d);
-//UPDATE-0.7.57->0.7.68 void v_APCI3120_InterruptDmaMoveBlock16bit(struct comedi_device *dev,struct comedi_subdevice *s,short *dma,short *data,int n);
+/* UPDATE-0.7.57->0.7.68 void v_APCI3120_InterruptDmaMoveBlock16bit(struct comedi_device *dev,struct comedi_subdevice *s,short *dma,short *data,int n); */
 void v_APCI3120_InterruptDmaMoveBlock16bit(struct comedi_device *dev,
 					   struct comedi_subdevice *s,
 					   short *dma_buffer,
@@ -196,7 +198,7 @@
 int i_APCI3120_InterruptHandleEos(struct comedi_device *dev);
 void v_APCI3120_InterruptDma(int irq, void *d);
 
-// TIMER
+/* TIMER */
 
 int i_APCI3120_InsnConfigTimer(struct comedi_device *dev, struct comedi_subdevice *s,
 			       struct comedi_insn *insn, unsigned int *data);
@@ -205,16 +207,19 @@
 int i_APCI3120_InsnReadTimer(struct comedi_device *dev, struct comedi_subdevice *s,
 			     struct comedi_insn *insn, unsigned int *data);
 
-//DI
-// for di read
+/*
+* DI for di read
+*/
 
 int i_APCI3120_InsnBitsDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				    struct comedi_insn *insn, unsigned int *data);
 int i_APCI3120_InsnReadDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				    struct comedi_insn *insn, unsigned int *data);
 
-//DO
-//int i_APCI3120_WriteDigitalOutput(struct comedi_device *dev, BYTE data);
+/* DO */
+/* int i_APCI3120_WriteDigitalOutput(struct comedi_device *dev,
+ * unsigned char data);
+ */
 int i_APCI3120_InsnConfigDigitalOutput(struct comedi_device *dev,
 				       struct comedi_subdevice *s, struct comedi_insn *insn,
 				       unsigned int *data);
@@ -223,12 +228,15 @@
 int i_APCI3120_InsnWriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				      struct comedi_insn *insn, unsigned int *data);
 
-//AO
-//int i_APCI3120_Write1AnalogValue(struct comedi_device *dev,UINT ui_Range,UINT ui_Channel,UINT data );
+/* AO */
+/* int i_APCI3120_Write1AnalogValue(struct comedi_device *dev,UINT ui_Range,
+ * UINT ui_Channel,UINT data );
+ */
+
 int i_APCI3120_InsnWriteAnalogOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				     struct comedi_insn *insn, unsigned int *data);
 
-//AI HArdware layer
+/* AI HArdware layer */
 
 int i_APCI3120_InsnConfigAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				     struct comedi_insn *insn, unsigned int *data);
@@ -237,5 +245,5 @@
 int i_APCI3120_CommandTestAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				      struct comedi_cmd *cmd);
 int i_APCI3120_CommandAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s);
-//int i_APCI3120_CancelAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s);
+/* int i_APCI3120_CancelAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s); */
 int i_APCI3120_StopCyclicAcquisition(struct comedi_device *dev, struct comedi_subdevice *s);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3200.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3200.c
index 1ff66be..9b53255 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3200.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3200.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -57,73 +57,73 @@
   +----------------------------------------------------------------------------+
 */
 #include "hwdrv_apci3200.h"
-//Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+/* Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 #include "addi_amcc_S5920.h"
-//#define PRINT_INFO
+/* #define PRINT_INFO */
 
-//End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+/* End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
-//BEGIN JK 06.07.04: Management of sevrals boards
+/* BEGIN JK 06.07.04: Management of sevrals boards */
 /*
-  INT i_CJCAvailable=1;
-  INT i_CJCPolarity=0;
-  INT i_CJCGain=2;//changed from 0 to 2
-  INT i_InterruptFlag=0;
-  INT i_ADDIDATAPolarity;
-  INT i_ADDIDATAGain;
-  INT i_AutoCalibration=0;   //: auto calibration
-  INT i_ADDIDATAConversionTime;
-  INT i_ADDIDATAConversionTimeUnit;
-  INT i_ADDIDATAType;
-  INT i_ChannelNo;
-  INT i_ChannelCount=0;
-  INT i_ScanType;
-  INT i_FirstChannel;
-  INT i_LastChannel;
-  INT i_Sum=0;
-  INT i_Offset;
-  UINT ui_Channel_num=0;
+  int i_CJCAvailable=1;
+  int i_CJCPolarity=0;
+  int i_CJCGain=2;/* changed from 0 to 2 */
+  int i_InterruptFlag=0;
+  int i_ADDIDATAPolarity;
+  int i_ADDIDATAGain;
+  int i_AutoCalibration=0;   /* : auto calibration */
+  int i_ADDIDATAConversionTime;
+  int i_ADDIDATAConversionTimeUnit;
+  int i_ADDIDATAType;
+  int i_ChannelNo;
+  int i_ChannelCount=0;
+  int i_ScanType;
+  int i_FirstChannel;
+  int i_LastChannel;
+  int i_Sum=0;
+  int i_Offset;
+  unsigned int ui_Channel_num=0;
   static int i_Count=0;
-  INT i_Initialised=0;
-  UINT ui_InterruptChannelValue[96]; //Buffer
+  int i_Initialised=0;
+  unsigned int ui_InterruptChannelValue[96]; /* Buffer */
 */
-str_BoardInfos s_BoardInfos[100];	// 100 will be the max number of boards to be used
-//END JK 06.07.04: Management of sevrals boards
+struct str_BoardInfos s_BoardInfos[100];	/*  100 will be the max number of boards to be used */
+/* END JK 06.07.04: Management of sevrals boards */
 
-//Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+/* Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
 /*+----------------------------------------------------------------------------+*/
-/*| Function   Name   : INT i_AddiHeaderRW_ReadEeprom                          |*/
-/*|                               (INT    i_NbOfWordsToRead,                   |*/
-/*|                                DWORD dw_PCIBoardEepromAddress,             |*/
-/*|                                WORD   w_EepromStartAddress,                |*/
-/*|                                PWORD pw_DataRead)                          |*/
+/*| Function   Name   : int i_AddiHeaderRW_ReadEeprom                          |*/
+/*|                               (int    i_NbOfWordsToRead,                   |*/
+/*|                                unsigned int dw_PCIBoardEepromAddress,             |*/
+/*|                                unsigned short   w_EepromStartAddress,                |*/
+/*|                                unsigned short * pw_DataRead)                          |*/
 /*+----------------------------------------------------------------------------+*/
 /*| Task              : Read word from the 5920 eeprom.                        |*/
 /*+----------------------------------------------------------------------------+*/
-/*| Input Parameters  : INT    i_NbOfWordsToRead : Nbr. of word to read        |*/
-/*|                     DWORD dw_PCIBoardEepromAddress : Address of the eeprom |*/
-/*|                     WORD   w_EepromStartAddress : Eeprom strat address     |*/
+/*| Input Parameters  : int    i_NbOfWordsToRead : Nbr. of word to read        |*/
+/*|                     unsigned int dw_PCIBoardEepromAddress : Address of the eeprom |*/
+/*|                     unsigned short   w_EepromStartAddress : Eeprom strat address     |*/
 /*+----------------------------------------------------------------------------+*/
-/*| Output Parameters : PWORD pw_DataRead : Read data                          |*/
+/*| Output Parameters : unsigned short * pw_DataRead : Read data                          |*/
 /*+----------------------------------------------------------------------------+*/
 /*| Return Value      : -                                                      |*/
 /*+----------------------------------------------------------------------------+*/
 
-INT i_AddiHeaderRW_ReadEeprom(INT i_NbOfWordsToRead,
-	DWORD dw_PCIBoardEepromAddress,
-	WORD w_EepromStartAddress, PWORD pw_DataRead)
+int i_AddiHeaderRW_ReadEeprom(int i_NbOfWordsToRead,
+	unsigned int dw_PCIBoardEepromAddress,
+	unsigned short w_EepromStartAddress, unsigned short *pw_DataRead)
 {
-	DWORD dw_eeprom_busy = 0;
-	INT i_Counter = 0;
-	INT i_WordCounter;
-	INT i;
-	BYTE pb_ReadByte[1];
-	BYTE b_ReadLowByte = 0;
-	BYTE b_ReadHighByte = 0;
-	BYTE b_SelectedAddressLow = 0;
-	BYTE b_SelectedAddressHigh = 0;
-	WORD w_ReadWord = 0;
+	unsigned int dw_eeprom_busy = 0;
+	int i_Counter = 0;
+	int i_WordCounter;
+	int i;
+	unsigned char pb_ReadByte[1];
+	unsigned char b_ReadLowByte = 0;
+	unsigned char b_ReadHighByte = 0;
+	unsigned char b_SelectedAddressLow = 0;
+	unsigned char b_SelectedAddressHigh = 0;
+	unsigned short w_ReadWord = 0;
 
 	for (i_WordCounter = 0; i_WordCounter < i_NbOfWordsToRead;
 		i_WordCounter++) {
@@ -132,106 +132,99 @@
 				inl(dw_PCIBoardEepromAddress +
 				AMCC_OP_REG_MCSR);
 			dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-		}
-		while (dw_eeprom_busy == EEPROM_BUSY);
+		} while (dw_eeprom_busy == EEPROM_BUSY);
 
 		for (i_Counter = 0; i_Counter < 2; i_Counter++) {
-			b_SelectedAddressLow = (w_EepromStartAddress + i_Counter) % 256;	//Read the low 8 bit part
-			b_SelectedAddressHigh = (w_EepromStartAddress + i_Counter) / 256;	//Read the high 8 bit part
+			b_SelectedAddressLow = (w_EepromStartAddress + i_Counter) % 256;	/* Read the low 8 bit part */
+			b_SelectedAddressHigh = (w_EepromStartAddress + i_Counter) / 256;	/* Read the high 8 bit part */
 
-			//Select the load low address mode
+			/* Select the load low address mode */
 			outb(NVCMD_LOAD_LOW,
 				dw_PCIBoardEepromAddress + AMCC_OP_REG_MCSR +
 				3);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Load the low address
+			/* Load the low address */
 			outb(b_SelectedAddressLow,
 				dw_PCIBoardEepromAddress + AMCC_OP_REG_MCSR +
 				2);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Select the load high address mode
+			/* Select the load high address mode */
 			outb(NVCMD_LOAD_HIGH,
 				dw_PCIBoardEepromAddress + AMCC_OP_REG_MCSR +
 				3);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Load the high address
+			/* Load the high address */
 			outb(b_SelectedAddressHigh,
 				dw_PCIBoardEepromAddress + AMCC_OP_REG_MCSR +
 				2);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Select the READ mode
+			/* Select the READ mode */
 			outb(NVCMD_BEGIN_READ,
 				dw_PCIBoardEepromAddress + AMCC_OP_REG_MCSR +
 				3);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Read data into the EEPROM
+			/* Read data into the EEPROM */
 			*pb_ReadByte =
 				inb(dw_PCIBoardEepromAddress +
 				AMCC_OP_REG_MCSR + 2);
 
-			//Wait on busy
+			/* Wait on busy */
 			do {
 				dw_eeprom_busy =
 					inl(dw_PCIBoardEepromAddress +
 					AMCC_OP_REG_MCSR);
 				dw_eeprom_busy = dw_eeprom_busy & EEPROM_BUSY;
-			}
-			while (dw_eeprom_busy == EEPROM_BUSY);
+			} while (dw_eeprom_busy == EEPROM_BUSY);
 
-			//Select the upper address part
-			if (i_Counter == 0) {
+			/* Select the upper address part */
+			if (i_Counter == 0)
 				b_ReadLowByte = pb_ReadByte[0];
-			} else {
+			else
 				b_ReadHighByte = pb_ReadByte[0];
-			}
 
-			//Sleep
-			for (i = 0; i < 10000; i++) ;
+
+			/* Sleep */
+			msleep(1);
 
 		}
 		w_ReadWord =
@@ -240,10 +233,10 @@
 
 		pw_DataRead[i_WordCounter] = w_ReadWord;
 
-		w_EepromStartAddress += 2;	// to read the next word
+		w_EepromStartAddress += 2;	/*  to read the next word */
 
-	}			// for (...) i_NbOfWordsToRead
-	return (0);
+	}			/*  for (...) i_NbOfWordsToRead */
+	return 0;
 }
 
 /*+----------------------------------------------------------------------------+*/
@@ -258,31 +251,31 @@
 /*| Return Value      : -                                                      |*/
 /*+----------------------------------------------------------------------------+*/
 
-void v_GetAPCI3200EepromCalibrationValue(DWORD dw_PCIBoardEepromAddress,
-	str_BoardInfos * BoardInformations)
+void v_GetAPCI3200EepromCalibrationValue(unsigned int dw_PCIBoardEepromAddress,
+	struct str_BoardInfos *BoardInformations)
 {
-	WORD w_AnalogInputMainHeaderAddress;
-	WORD w_AnalogInputComponentAddress;
-	WORD w_NumberOfModuls = 0;
-	WORD w_CurrentSources[2];
-	WORD w_ModulCounter = 0;
-	WORD w_FirstHeaderSize = 0;
-	WORD w_NumberOfInputs = 0;
-	WORD w_CJCFlag = 0;
-	WORD w_NumberOfGainValue = 0;
-	WORD w_SingleHeaderAddress = 0;
-	WORD w_SingleHeaderSize = 0;
-	WORD w_Input = 0;
-	WORD w_GainFactorAddress = 0;
-	WORD w_GainFactorValue[2];
-	WORD w_GainIndex = 0;
-	WORD w_GainValue = 0;
+	unsigned short w_AnalogInputMainHeaderAddress;
+	unsigned short w_AnalogInputComponentAddress;
+	unsigned short w_NumberOfModuls = 0;
+	unsigned short w_CurrentSources[2];
+	unsigned short w_ModulCounter = 0;
+	unsigned short w_FirstHeaderSize = 0;
+	unsigned short w_NumberOfInputs = 0;
+	unsigned short w_CJCFlag = 0;
+	unsigned short w_NumberOfGainValue = 0;
+	unsigned short w_SingleHeaderAddress = 0;
+	unsigned short w_SingleHeaderSize = 0;
+	unsigned short w_Input = 0;
+	unsigned short w_GainFactorAddress = 0;
+	unsigned short w_GainFactorValue[2];
+	unsigned short w_GainIndex = 0;
+	unsigned short w_GainValue = 0;
 
   /*****************************************/
   /** Get the Analog input header address **/
   /*****************************************/
-	i_AddiHeaderRW_ReadEeprom(1,	//i_NbOfWordsToRead
-		dw_PCIBoardEepromAddress, 0x116,	//w_EepromStartAddress: Analog input header address
+	i_AddiHeaderRW_ReadEeprom(1,	/* i_NbOfWordsToRead */
+		dw_PCIBoardEepromAddress, 0x116,	/* w_EepromStartAddress: Analog input header address */
 		&w_AnalogInputMainHeaderAddress);
 
   /*******************************************/
@@ -293,8 +286,8 @@
   /******************************/
   /** Get the number of moduls **/
   /******************************/
-	i_AddiHeaderRW_ReadEeprom(1,	//i_NbOfWordsToRead
-		dw_PCIBoardEepromAddress, w_AnalogInputMainHeaderAddress + 0x02,	//w_EepromStartAddress: Number of conponment
+	i_AddiHeaderRW_ReadEeprom(1,	/* i_NbOfWordsToRead */
+		dw_PCIBoardEepromAddress, w_AnalogInputMainHeaderAddress + 0x02,	/* w_EepromStartAddress: Number of conponment */
 		&w_NumberOfModuls);
 
 	for (w_ModulCounter = 0; w_ModulCounter < w_NumberOfModuls;
@@ -309,8 +302,8 @@
       /****************************/
       /** Read first header size **/
       /****************************/
-		i_AddiHeaderRW_ReadEeprom(1,	//i_NbOfWordsToRead
-			dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress,	// Address of the first header
+		i_AddiHeaderRW_ReadEeprom(1,	/* i_NbOfWordsToRead */
+			dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress,	/*  Address of the first header */
 			&w_FirstHeaderSize);
 
 		w_FirstHeaderSize = w_FirstHeaderSize >> 4;
@@ -318,8 +311,8 @@
       /***************************/
       /** Read number of inputs **/
       /***************************/
-		i_AddiHeaderRW_ReadEeprom(1,	//i_NbOfWordsToRead
-			dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress + 0x06,	// Number of inputs for the first modul
+		i_AddiHeaderRW_ReadEeprom(1,	/* i_NbOfWordsToRead */
+			dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress + 0x06,	/*  Number of inputs for the first modul */
 			&w_NumberOfInputs);
 
 		w_NumberOfInputs = w_NumberOfInputs >> 4;
@@ -327,17 +320,17 @@
       /***********************/
       /** Read the CJC flag **/
       /***********************/
-		i_AddiHeaderRW_ReadEeprom(1,	//i_NbOfWordsToRead
-			dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress + 0x08,	// CJC flag
+		i_AddiHeaderRW_ReadEeprom(1,	/* i_NbOfWordsToRead */
+			dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress + 0x08,	/*  CJC flag */
 			&w_CJCFlag);
 
-		w_CJCFlag = (w_CJCFlag >> 3) & 0x1;	// Get only the CJC flag
+		w_CJCFlag = (w_CJCFlag >> 3) & 0x1;	/*  Get only the CJC flag */
 
       /*******************************/
       /** Read number of gain value **/
       /*******************************/
-		i_AddiHeaderRW_ReadEeprom(1,	//i_NbOfWordsToRead
-			dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress + 0x44,	// Number of gain value
+		i_AddiHeaderRW_ReadEeprom(1,	/* i_NbOfWordsToRead */
+			dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress + 0x44,	/*  Number of gain value */
 			&w_NumberOfGainValue);
 
 		w_NumberOfGainValue = w_NumberOfGainValue & 0xFF;
@@ -354,8 +347,8 @@
       /********************************************/
       /** Read current sources value for input 1 **/
       /********************************************/
-		i_AddiHeaderRW_ReadEeprom(1,	//i_NbOfWordsToRead
-			dw_PCIBoardEepromAddress, w_SingleHeaderAddress,	//w_EepromStartAddress: Single header address
+		i_AddiHeaderRW_ReadEeprom(1,	/* i_NbOfWordsToRead */
+			dw_PCIBoardEepromAddress, w_SingleHeaderAddress,	/* w_EepromStartAddress: Single header address */
 			&w_SingleHeaderSize);
 
 		w_SingleHeaderSize = w_SingleHeaderSize >> 4;
@@ -370,8 +363,8 @@
 	  /************************************/
 	  /** Read gain value for the module **/
 	  /************************************/
-			i_AddiHeaderRW_ReadEeprom(1,	//i_NbOfWordsToRead
-				dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress + 70 + (2 * (1 + (w_NumberOfGainValue / 16))) + (0x02 * w_GainIndex),	// Gain value
+			i_AddiHeaderRW_ReadEeprom(1,	/* i_NbOfWordsToRead */
+				dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress + 70 + (2 * (1 + (w_NumberOfGainValue / 16))) + (0x02 * w_GainIndex),	/*  Gain value */
 				&w_GainValue);
 
 			BoardInformations->s_Module[w_ModulCounter].
@@ -386,8 +379,8 @@
 	  /*************************************/
 	  /** Read gain factor for the module **/
 	  /*************************************/
-			i_AddiHeaderRW_ReadEeprom(2,	//i_NbOfWordsToRead
-				dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress + 70 + ((2 * w_NumberOfGainValue) + (2 * (1 + (w_NumberOfGainValue / 16)))) + (0x04 * w_GainIndex),	// Gain factor
+			i_AddiHeaderRW_ReadEeprom(2,	/* i_NbOfWordsToRead */
+				dw_PCIBoardEepromAddress, w_AnalogInputComponentAddress + 70 + ((2 * w_NumberOfGainValue) + (2 * (1 + (w_NumberOfGainValue / 16)))) + (0x04 * w_GainIndex),	/*  Gain factor */
 				w_GainFactorValue);
 
 			BoardInformations->s_Module[w_ModulCounter].
@@ -409,7 +402,7 @@
 	  /********************************************/
 	  /** Read current sources value for input 1 **/
 	  /********************************************/
-			i_AddiHeaderRW_ReadEeprom(2,	//i_NbOfWordsToRead
+			i_AddiHeaderRW_ReadEeprom(2,	/* i_NbOfWordsToRead */
 				dw_PCIBoardEepromAddress,
 				(w_Input * w_SingleHeaderSize) +
 				w_SingleHeaderAddress + 0x0C, w_CurrentSources);
@@ -432,7 +425,7 @@
       /***************************************/
       /** Read the CJC current source value **/
       /***************************************/
-		i_AddiHeaderRW_ReadEeprom(2,	//i_NbOfWordsToRead
+		i_AddiHeaderRW_ReadEeprom(2,	/* i_NbOfWordsToRead */
 			dw_PCIBoardEepromAddress,
 			(w_Input * w_SingleHeaderSize) + w_SingleHeaderAddress +
 			0x0C, w_CurrentSources);
@@ -453,9 +446,9 @@
 	}
 }
 
-INT i_APCI3200_GetChannelCalibrationValue(struct comedi_device * dev,
-	unsigned int ui_Channel_num, unsigned int * CJCCurrentSource,
-	unsigned int * ChannelCurrentSource, unsigned int * ChannelGainFactor)
+int i_APCI3200_GetChannelCalibrationValue(struct comedi_device *dev,
+	unsigned int ui_Channel_num, unsigned int *CJCCurrentSource,
+	unsigned int *ChannelCurrentSource, unsigned int *ChannelGainFactor)
 {
 	int i_DiffChannel = 0;
 	int i_Module = 0;
@@ -464,9 +457,9 @@
 	printk("\n Channel = %u", ui_Channel_num);
 #endif
 
-	//Test if single or differential mode
+	/* Test if single or differential mode */
 	if (s_BoardInfos[dev->minor].i_ConnectionType == 1) {
-		//if diff
+		/* if diff */
 
 		if ((ui_Channel_num >= 0) && (ui_Channel_num <= 1))
 			i_DiffChannel = ui_Channel_num, i_Module = 0;
@@ -478,7 +471,7 @@
 			i_DiffChannel = ui_Channel_num - 6, i_Module = 3;
 
 	} else {
-		// if single
+		/*  if single */
 		if ((ui_Channel_num == 0) || (ui_Channel_num == 1))
 			i_DiffChannel = 0, i_Module = 0;
 		else if ((ui_Channel_num == 2) || (ui_Channel_num == 3))
@@ -497,7 +490,7 @@
 			i_DiffChannel = 1, i_Module = 3;
 	}
 
-	//Test if thermocouple or RTD mode
+	/* Test if thermocouple or RTD mode */
 	*CJCCurrentSource =
 		s_BoardInfos[dev->minor].s_Module[i_Module].ul_CurrentSourceCJC;
 #ifdef PRINT_INFO
@@ -510,22 +503,22 @@
 #ifdef PRINT_INFO
 	printk("\n ChannelCurrentSource = %lu", *ChannelCurrentSource);
 #endif
-	//      }
-	//   }
+	/*       } */
+	/*    } */
 
-	//Channle gain factor
+	/* Channle gain factor */
 	*ChannelGainFactor =
 		s_BoardInfos[dev->minor].s_Module[i_Module].
 		ul_GainFactor[s_BoardInfos[dev->minor].i_ADDIDATAGain];
 #ifdef PRINT_INFO
 	printk("\n ChannelGainFactor = %lu", *ChannelGainFactor);
 #endif
-	//End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+	/* End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
-	return (0);
+	return 0;
 }
 
-//End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+/* End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
 /*
   +----------------------------------------------------------------------------+
@@ -536,9 +529,9 @@
   | Task              : Read  value  of the selected channel or port           |
   +----------------------------------------------------------------------------+
   | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-  |                     UINT ui_NoOfChannels    : No Of Channels To read  for Port
+  |                     unsigned int ui_NoOfChannels    : No Of Channels To read  for Port
   Channel Numberfor single channel
-  |                     UINT data[0]            : 0: Read single channel
+  |                     unsigned int data[0]            : 0: Read single channel
   1: Read port value
   data[1]              Port number
   +----------------------------------------------------------------------------+
@@ -550,24 +543,24 @@
   +----------------------------------------------------------------------------+
 */
 
-INT i_APCI3200_ReadDigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3200_ReadDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp = 0;
-	UINT ui_NoOfChannel = 0;
+	unsigned int ui_Temp = 0;
+	unsigned int ui_NoOfChannel = 0;
 	ui_NoOfChannel = CR_CHAN(insn->chanspec);
 	ui_Temp = data[0];
 	*data = inl(devpriv->i_IobaseReserved);
 
 	if (ui_Temp == 0) {
 		*data = (*data >> ui_NoOfChannel) & 0x1;
-	}			//if  (ui_Temp==0)
+	}			/* if  (ui_Temp==0) */
 	else {
 		if (ui_Temp == 1) {
 			if (data[1] < 0 || data[1] > 1) {
 				printk("\nThe port number is in error\n");
 				return -EINVAL;
-			}	//if(data[1] < 0 || data[1] >1)
+			}	/* if(data[1] < 0 || data[1] >1) */
 			switch (ui_NoOfChannel) {
 
 			case 2:
@@ -578,13 +571,13 @@
 				break;
 			default:
 				comedi_error(dev, " chan spec wrong");
-				return -EINVAL;	// "sorry channel spec wrong "
+				return -EINVAL;	/*  "sorry channel spec wrong " */
 
-			}	//switch(ui_NoOfChannels)
-		}		//if  (ui_Temp==1)
+			}	/* switch(ui_NoOfChannels) */
+		}		/* if  (ui_Temp==1) */
 		else {
 			printk("\nSpecified channel not supported \n");
-		}		//elseif  (ui_Temp==1)
+		}		/* elseif  (ui_Temp==1) */
 	}
 	return insn->n;
 }
@@ -608,21 +601,21 @@
   |																	 |
   +----------------------------------------------------------------------------+
 */
-int i_APCI3200_ConfigDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3200_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
 	if ((data[0] != 0) && (data[0] != 1)) {
 		comedi_error(dev,
 			"Not a valid Data !!! ,Data should be 1 or 0\n");
 		return -EINVAL;
-	}			//if  ( (data[0]!=0) && (data[0]!=1) )
+	}			/* if  ( (data[0]!=0) && (data[0]!=1) ) */
 	if (data[0]) {
 		devpriv->b_OutputMemoryStatus = ADDIDATA_ENABLE;
-	}			// if  (data[0])
+	}			/*  if  (data[0]) */
 	else {
 		devpriv->b_OutputMemoryStatus = ADDIDATA_DISABLE;
-	}			//else if  (data[0])
+	}			/* else if  (data[0]) */
 	return insn->n;
 }
 
@@ -653,23 +646,23 @@
   |			                                                         |
   +----------------------------------------------------------------------------+
 */
-INT i_APCI3200_WriteDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3200_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp = 0, ui_Temp1 = 0;
-	UINT ui_NoOfChannel = CR_CHAN(insn->chanspec);	// get the channel
+	unsigned int ui_Temp = 0, ui_Temp1 = 0;
+	unsigned int ui_NoOfChannel = CR_CHAN(insn->chanspec);	/*  get the channel */
 	if (devpriv->b_OutputMemoryStatus) {
 		ui_Temp = inl(devpriv->i_IobaseAddon);
 
-	}			//if(devpriv->b_OutputMemoryStatus )
+	}			/* if(devpriv->b_OutputMemoryStatus ) */
 	else {
 		ui_Temp = 0;
-	}			//if(devpriv->b_OutputMemoryStatus )
+	}			/* if(devpriv->b_OutputMemoryStatus ) */
 	if (data[3] == 0) {
 		if (data[1] == 0) {
 			data[0] = (data[0] << ui_NoOfChannel) | ui_Temp;
 			outl(data[0], devpriv->i_IobaseAddon);
-		}		//if(data[1]==0)
+		}		/* if(data[1]==0) */
 		else {
 			if (data[1] == 1) {
 				switch (ui_NoOfChannel) {
@@ -682,15 +675,15 @@
 				case 3:
 					data[0] = (data[0] | ui_Temp);
 					break;
-				}	//switch(ui_NoOfChannels)
+				}	/* switch(ui_NoOfChannels) */
 
 				outl(data[0], devpriv->i_IobaseAddon);
-			}	// if(data[1]==1)
+			}	/*  if(data[1]==1) */
 			else {
 				printk("\nSpecified channel not supported\n");
-			}	//else if(data[1]==1)
-		}		//elseif(data[1]==0)
-	}			//if(data[3]==0)
+			}	/* else if(data[1]==1) */
+		}		/* elseif(data[1]==0) */
+	}			/* if(data[3]==0) */
 	else {
 		if (data[3] == 1) {
 			if (data[1] == 0) {
@@ -701,7 +694,7 @@
 				data[0] = (data[0] << ui_NoOfChannel) ^ 0xf;
 				data[0] = data[0] & ui_Temp;
 				outl(data[0], devpriv->i_IobaseAddon);
-			}	//if(data[1]==0)
+			}	/* if(data[1]==0) */
 			else {
 				if (data[1] == 1) {
 					switch (ui_NoOfChannel) {
@@ -725,21 +718,21 @@
 					default:
 						comedi_error(dev,
 							" chan spec wrong");
-						return -EINVAL;	// "sorry channel spec wrong "
-					}	//switch(ui_NoOfChannels)
+						return -EINVAL;	/*  "sorry channel spec wrong " */
+					}	/* switch(ui_NoOfChannels) */
 
 					outl(data[0], devpriv->i_IobaseAddon);
-				}	// if(data[1]==1)
+				}	/*  if(data[1]==1) */
 				else {
 					printk("\nSpecified channel not supported\n");
-				}	//else if(data[1]==1)
-			}	//elseif(data[1]==0)
-		}		//if(data[3]==1);
+				}	/* else if(data[1]==1) */
+			}	/* elseif(data[1]==0) */
+		}		/* if(data[3]==1); */
 		else {
 			printk("\nSpecified functionality does not exist\n");
 			return -EINVAL;
-		}		//if else data[3]==1)
-	}			//if else data[3]==0)
+		}		/* if else data[3]==1) */
+	}			/* if else data[3]==0) */
 	return insn->n;
 }
 
@@ -752,8 +745,8 @@
   | Task              : Read  value  of the selected channel or port           |
   +----------------------------------------------------------------------------+
   | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-  |                     UINT ui_NoOfChannels    : No Of Channels To read       |
-  |                     UINT *data              : Data Pointer to read status  |
+  |                     unsigned int ui_NoOfChannels    : No Of Channels To read       |
+  |                     unsigned int *data              : Data Pointer to read status  |
   data[0]                 :0 read single channel
   1 read port value
   data[1]                  port no
@@ -766,23 +759,23 @@
   |			                                                         |
   +----------------------------------------------------------------------------+
 */
-INT i_APCI3200_ReadDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3200_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp;
-	UINT ui_NoOfChannel;
+	unsigned int ui_Temp;
+	unsigned int ui_NoOfChannel;
 	ui_NoOfChannel = CR_CHAN(insn->chanspec);
 	ui_Temp = data[0];
 	*data = inl(devpriv->i_IobaseAddon);
 	if (ui_Temp == 0) {
 		*data = (*data >> ui_NoOfChannel) & 0x1;
-	}			// if  (ui_Temp==0)
+	}			/*  if  (ui_Temp==0) */
 	else {
 		if (ui_Temp == 1) {
 			if (data[1] < 0 || data[1] > 1) {
 				printk("\nThe port selection is in error\n");
 				return -EINVAL;
-			}	//if(data[1] <0 ||data[1] >1)
+			}	/* if(data[1] <0 ||data[1] >1) */
 			switch (ui_NoOfChannel) {
 			case 2:
 				*data = (*data >> (2 * data[1])) & 3;
@@ -793,20 +786,20 @@
 
 			default:
 				comedi_error(dev, " chan spec wrong");
-				return -EINVAL;	// "sorry channel spec wrong "
+				return -EINVAL;	/*  "sorry channel spec wrong " */
 				break;
-			}	// switch(ui_NoOfChannels)
-		}		// if  (ui_Temp==1)
+			}	/*  switch(ui_NoOfChannels) */
+		}		/*  if  (ui_Temp==1) */
 		else {
 			printk("\nSpecified channel not supported \n");
-		}		// else if (ui_Temp==1)
-	}			// else if  (ui_Temp==0)
+		}		/*  else if (ui_Temp==1) */
+	}			/*  else if  (ui_Temp==0) */
 	return insn->n;
 }
 
 /*
   +----------------------------------------------------------------------------+
-  | Function   Name   : INT i_APCI3200_ConfigAnalogInput                       |
+  | Function   Name   : int i_APCI3200_ConfigAnalogInput                       |
   |			  (struct comedi_device *dev,struct comedi_subdevice *s,               |
   |                      struct comedi_insn *insn,unsigned int *data)                     |
   +----------------------------------------------------------------------------+
@@ -874,30 +867,30 @@
   |			                                                         |
   +----------------------------------------------------------------------------+
 */
-INT i_APCI3200_ConfigAnalogInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3200_ConfigAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
-	UINT ul_Config = 0, ul_Temp = 0;
-	UINT ui_ChannelNo = 0;
-	UINT ui_Dummy = 0;
-	INT i_err = 0;
+	unsigned int ul_Config = 0, ul_Temp = 0;
+	unsigned int ui_ChannelNo = 0;
+	unsigned int ui_Dummy = 0;
+	int i_err = 0;
 
-	//Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+	/* Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
 #ifdef PRINT_INFO
-	INT i = 0, i2 = 0;
+	int i = 0, i2 = 0;
 #endif
-	//End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+	/* End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	// Initialize the structure
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/*  Initialize the structure */
 	if (s_BoardInfos[dev->minor].b_StructInitialized != 1) {
 		s_BoardInfos[dev->minor].i_CJCAvailable = 1;
 		s_BoardInfos[dev->minor].i_CJCPolarity = 0;
-		s_BoardInfos[dev->minor].i_CJCGain = 2;	//changed from 0 to 2
+		s_BoardInfos[dev->minor].i_CJCGain = 2;	/* changed from 0 to 2 */
 		s_BoardInfos[dev->minor].i_InterruptFlag = 0;
-		s_BoardInfos[dev->minor].i_AutoCalibration = 0;	//: auto calibration
+		s_BoardInfos[dev->minor].i_AutoCalibration = 0;	/* : auto calibration */
 		s_BoardInfos[dev->minor].i_ChannelCount = 0;
 		s_BoardInfos[dev->minor].i_Sum = 0;
 		s_BoardInfos[dev->minor].ui_Channel_num = 0;
@@ -905,11 +898,11 @@
 		s_BoardInfos[dev->minor].i_Initialised = 0;
 		s_BoardInfos[dev->minor].b_StructInitialized = 1;
 
-		//Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+		/* Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 		s_BoardInfos[dev->minor].i_ConnectionType = 0;
-		//End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+		/* End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
-		//Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+		/* Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 		memset(s_BoardInfos[dev->minor].s_Module, 0,
 			sizeof(s_BoardInfos[dev->minor].s_Module[MAX_MODULE]));
 
@@ -938,72 +931,72 @@
 			}
 		}
 #endif
-		//End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+		/* End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 	}
 
 	if (data[0] != 0 && data[0] != 1 && data[0] != 2) {
 		printk("\nThe selection of acquisition type is in error\n");
 		i_err++;
-	}			//if(data[0]!=0 && data[0]!=1 && data[0]!=2)
+	}			/* if(data[0]!=0 && data[0]!=1 && data[0]!=2) */
 	if (data[0] == 1) {
 		if (data[14] != 0 && data[14] != 1 && data[14] != 2
 			&& data[14] != 4) {
 			printk("\n Error in selection of RTD connection type\n");
 			i_err++;
-		}		//if(data[14]!=0 && data[14]!=1 && data[14]!=2 && data[14]!=4)
-	}			//if(data[0]==1 )
+		}		/* if(data[14]!=0 && data[14]!=1 && data[14]!=2 && data[14]!=4) */
+	}			/* if(data[0]==1 ) */
 	if (data[1] < 0 || data[1] > 7) {
 		printk("\nThe selection of gain is in error\n");
 		i_err++;
-	}			// if(data[1]<0 || data[1]>7)
+	}			/*  if(data[1]<0 || data[1]>7) */
 	if (data[2] != 0 && data[2] != 1) {
 		printk("\nThe selection of polarity is in error\n");
 		i_err++;
-	}			//if(data[2]!=0 &&  data[2]!=1)
+	}			/* if(data[2]!=0 &&  data[2]!=1) */
 	if (data[3] != 0) {
 		printk("\nThe selection of offset range  is in error\n");
 		i_err++;
-	}			// if(data[3]!=0)
+	}			/*  if(data[3]!=0) */
 	if (data[4] != 0 && data[4] != 1) {
 		printk("\nThe selection of coupling is in error\n");
 		i_err++;
-	}			//if(data[4]!=0 &&  data[4]!=1)
+	}			/* if(data[4]!=0 &&  data[4]!=1) */
 	if (data[5] != 0 && data[5] != 1) {
 		printk("\nThe selection of single/differential mode is in error\n");
 		i_err++;
-	}			//if(data[5]!=0 &&  data[5]!=1)
+	}			/* if(data[5]!=0 &&  data[5]!=1) */
 	if (data[8] != 0 && data[8] != 1 && data[2] != 2) {
 		printk("\nError in selection of functionality\n");
-	}			//if(data[8]!=0 && data[8]!=1 && data[2]!=2)
+	}			/* if(data[8]!=0 && data[8]!=1 && data[2]!=2) */
 	if (data[12] == 0 || data[12] == 1) {
 		if (data[6] != 20 && data[6] != 40 && data[6] != 80
 			&& data[6] != 160) {
 			printk("\nThe selection of conversion time reload value is in error\n");
 			i_err++;
-		}		// if (data[6]!=20 && data[6]!=40 && data[6]!=80 && data[6]!=160 )
+		}		/*  if (data[6]!=20 && data[6]!=40 && data[6]!=80 && data[6]!=160 ) */
 		if (data[7] != 2) {
 			printk("\nThe selection of conversion time unit  is in error\n");
 			i_err++;
-		}		// if(data[7]!=2)
+		}		/*  if(data[7]!=2) */
 	}
 	if (data[9] != 0 && data[9] != 1) {
 		printk("\nThe selection of interrupt enable is in error\n");
 		i_err++;
-	}			//if(data[9]!=0 &&  data[9]!=1)
+	}			/* if(data[9]!=0 &&  data[9]!=1) */
 	if (data[11] < 0 || data[11] > 4) {
 		printk("\nThe selection of module is in error\n");
 		i_err++;
-	}			//if(data[11] <0 ||  data[11]>1)
+	}			/* if(data[11] <0 ||  data[11]>1) */
 	if (data[12] < 0 || data[12] > 3) {
 		printk("\nThe selection of singlechannel/scan selection is in error\n");
 		i_err++;
-	}			//if(data[12] < 0 ||  data[12]> 3)
+	}			/* if(data[12] < 0 ||  data[12]> 3) */
 	if (data[13] < 0 || data[13] > 16) {
 		printk("\nThe selection of number of channels is in error\n");
 		i_err++;
-	}			// if(data[13] <0 ||data[13] >15)
+	}			/*  if(data[13] <0 ||data[13] >15) */
 
-	//BEGIN JK 06.07.04: Management of sevrals boards
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
 	/*
 	   i_ChannelCount=data[13];
 	   i_ScanType=data[12];
@@ -1014,7 +1007,7 @@
 	   i_ADDIDATAType=data[0];
 	 */
 
-	// Save acquisition configuration for the actual board
+	/*  Save acquisition configuration for the actual board */
 	s_BoardInfos[dev->minor].i_ChannelCount = data[13];
 	s_BoardInfos[dev->minor].i_ScanType = data[12];
 	s_BoardInfos[dev->minor].i_ADDIDATAPolarity = data[2];
@@ -1022,307 +1015,307 @@
 	s_BoardInfos[dev->minor].i_ADDIDATAConversionTime = data[6];
 	s_BoardInfos[dev->minor].i_ADDIDATAConversionTimeUnit = data[7];
 	s_BoardInfos[dev->minor].i_ADDIDATAType = data[0];
-	//Begin JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
+	/* Begin JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
 	s_BoardInfos[dev->minor].i_ConnectionType = data[5];
-	//End JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
-	//END JK 06.07.04: Management of sevrals boards
+	/* End JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
+	/* END JK 06.07.04: Management of sevrals boards */
 
-	//Begin JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
-	memset(s_BoardInfos[dev->minor].ui_ScanValueArray, 0, (7 + 12) * sizeof(unsigned int));	// 7 is the maximal number of channels
-	//End JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
+	/* Begin JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
+	memset(s_BoardInfos[dev->minor].ui_ScanValueArray, 0, (7 + 12) * sizeof(unsigned int));	/*  7 is the maximal number of channels */
+	/* End JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
 
-	//BEGIN JK 02.07.04 : This while can't be do, it block the process when using severals boards
-	//while(i_InterruptFlag==1)
+	/* BEGIN JK 02.07.04 : This while can't be do, it block the process when using severals boards */
+	/* while(i_InterruptFlag==1) */
 	while (s_BoardInfos[dev->minor].i_InterruptFlag == 1) {
 #ifndef MSXBOX
 		udelay(1);
 #else
-		// In the case where the driver is compiled for the MSX-Box
-		// we used a printk to have a little delay because udelay
-		// seems to be broken under the MSX-Box.
-		// This solution hat to be studied.
+		/*  In the case where the driver is compiled for the MSX-Box */
+		/*  we used a printk to have a little delay because udelay */
+		/*  seems to be broken under the MSX-Box. */
+		/*  This solution hat to be studied. */
 		printk("");
 #endif
 	}
-	//END JK 02.07.04 : This while can't be do, it block the process when using severals boards
+	/* END JK 02.07.04 : This while can't be do, it block the process when using severals boards */
 
-	ui_ChannelNo = CR_CHAN(insn->chanspec);	// get the channel
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//i_ChannelNo=ui_ChannelNo;
-	//ui_Channel_num =ui_ChannelNo;
+	ui_ChannelNo = CR_CHAN(insn->chanspec);	/*  get the channel */
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* i_ChannelNo=ui_ChannelNo; */
+	/* ui_Channel_num =ui_ChannelNo; */
 
 	s_BoardInfos[dev->minor].i_ChannelNo = ui_ChannelNo;
 	s_BoardInfos[dev->minor].ui_Channel_num = ui_ChannelNo;
 
-	//END JK 06.07.04: Management of sevrals boards
+	/* END JK 06.07.04: Management of sevrals boards */
 
 	if (data[5] == 0) {
 		if (ui_ChannelNo < 0 || ui_ChannelNo > 15) {
 			printk("\nThe Selection of the channel is in error\n");
 			i_err++;
-		}		// if(ui_ChannelNo<0 || ui_ChannelNo>15)
-	}			//if(data[5]==0)
+		}		/*  if(ui_ChannelNo<0 || ui_ChannelNo>15) */
+	}			/* if(data[5]==0) */
 	else {
 		if (data[14] == 2) {
 			if (ui_ChannelNo < 0 || ui_ChannelNo > 3) {
 				printk("\nThe Selection of the channel is in error\n");
 				i_err++;
-			}	// if(ui_ChannelNo<0 || ui_ChannelNo>3)
-		}		//if(data[14]==2)
+			}	/*  if(ui_ChannelNo<0 || ui_ChannelNo>3) */
+		}		/* if(data[14]==2) */
 		else {
 			if (ui_ChannelNo < 0 || ui_ChannelNo > 7) {
 				printk("\nThe Selection of the channel is in error\n");
 				i_err++;
-			}	// if(ui_ChannelNo<0 || ui_ChannelNo>7)
-		}		//elseif(data[14]==2)
-	}			//elseif(data[5]==0)
+			}	/*  if(ui_ChannelNo<0 || ui_ChannelNo>7) */
+		}		/* elseif(data[14]==2) */
+	}			/* elseif(data[5]==0) */
 	if (data[12] == 0 || data[12] == 1) {
 		switch (data[5]) {
 		case 0:
 			if (ui_ChannelNo >= 0 && ui_ChannelNo <= 3) {
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//i_Offset=0;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* i_Offset=0; */
 				s_BoardInfos[dev->minor].i_Offset = 0;
-				//END JK 06.07.04: Management of sevrals boards
-			}	//if(ui_ChannelNo >=0 && ui_ChannelNo <=3)
+				/* END JK 06.07.04: Management of sevrals boards */
+			}	/* if(ui_ChannelNo >=0 && ui_ChannelNo <=3) */
 			if (ui_ChannelNo >= 4 && ui_ChannelNo <= 7) {
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//i_Offset=64;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* i_Offset=64; */
 				s_BoardInfos[dev->minor].i_Offset = 64;
-				//END JK 06.07.04: Management of sevrals boards
-			}	//if(ui_ChannelNo >=4 && ui_ChannelNo <=7)
+				/* END JK 06.07.04: Management of sevrals boards */
+			}	/* if(ui_ChannelNo >=4 && ui_ChannelNo <=7) */
 			if (ui_ChannelNo >= 8 && ui_ChannelNo <= 11) {
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//i_Offset=128;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* i_Offset=128; */
 				s_BoardInfos[dev->minor].i_Offset = 128;
-				//END JK 06.07.04: Management of sevrals boards
-			}	//if(ui_ChannelNo >=8 && ui_ChannelNo <=11)
+				/* END JK 06.07.04: Management of sevrals boards */
+			}	/* if(ui_ChannelNo >=8 && ui_ChannelNo <=11) */
 			if (ui_ChannelNo >= 12 && ui_ChannelNo <= 15) {
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//i_Offset=192;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* i_Offset=192; */
 				s_BoardInfos[dev->minor].i_Offset = 192;
-				//END JK 06.07.04: Management of sevrals boards
-			}	//if(ui_ChannelNo >=12 && ui_ChannelNo <=15)
+				/* END JK 06.07.04: Management of sevrals boards */
+			}	/* if(ui_ChannelNo >=12 && ui_ChannelNo <=15) */
 			break;
 		case 1:
 			if (data[14] == 2) {
 				if (ui_ChannelNo == 0) {
-					//BEGIN JK 06.07.04: Management of sevrals boards
-					//i_Offset=0;
+					/* BEGIN JK 06.07.04: Management of sevrals boards */
+					/* i_Offset=0; */
 					s_BoardInfos[dev->minor].i_Offset = 0;
-					//END JK 06.07.04: Management of sevrals boards
-				}	//if(ui_ChannelNo ==0 )
+					/* END JK 06.07.04: Management of sevrals boards */
+				}	/* if(ui_ChannelNo ==0 ) */
 				if (ui_ChannelNo == 1) {
-					//BEGIN JK 06.07.04: Management of sevrals boards
-					//i_Offset=0;
+					/* BEGIN JK 06.07.04: Management of sevrals boards */
+					/* i_Offset=0; */
 					s_BoardInfos[dev->minor].i_Offset = 64;
-					//END JK 06.07.04: Management of sevrals boards
-				}	// if(ui_ChannelNo ==1)
+					/* END JK 06.07.04: Management of sevrals boards */
+				}	/*  if(ui_ChannelNo ==1) */
 				if (ui_ChannelNo == 2) {
-					//BEGIN JK 06.07.04: Management of sevrals boards
-					//i_Offset=128;
+					/* BEGIN JK 06.07.04: Management of sevrals boards */
+					/* i_Offset=128; */
 					s_BoardInfos[dev->minor].i_Offset = 128;
-					//END JK 06.07.04: Management of sevrals boards
-				}	//if(ui_ChannelNo ==2 )
+					/* END JK 06.07.04: Management of sevrals boards */
+				}	/* if(ui_ChannelNo ==2 ) */
 				if (ui_ChannelNo == 3) {
-					//BEGIN JK 06.07.04: Management of sevrals boards
-					//i_Offset=192;
+					/* BEGIN JK 06.07.04: Management of sevrals boards */
+					/* i_Offset=192; */
 					s_BoardInfos[dev->minor].i_Offset = 192;
-					//END JK 06.07.04: Management of sevrals boards
-				}	//if(ui_ChannelNo ==3)
+					/* END JK 06.07.04: Management of sevrals boards */
+				}	/* if(ui_ChannelNo ==3) */
 
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//i_ChannelNo=0;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* i_ChannelNo=0; */
 				s_BoardInfos[dev->minor].i_ChannelNo = 0;
-				//END JK 06.07.04: Management of sevrals boards
+				/* END JK 06.07.04: Management of sevrals boards */
 				ui_ChannelNo = 0;
 				break;
-			}	//if(data[14]==2)
+			}	/* if(data[14]==2) */
 			if (ui_ChannelNo >= 0 && ui_ChannelNo <= 1) {
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//i_Offset=0;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* i_Offset=0; */
 				s_BoardInfos[dev->minor].i_Offset = 0;
-				//END JK 06.07.04: Management of sevrals boards
-			}	//if(ui_ChannelNo >=0 && ui_ChannelNo <=1)
+				/* END JK 06.07.04: Management of sevrals boards */
+			}	/* if(ui_ChannelNo >=0 && ui_ChannelNo <=1) */
 			if (ui_ChannelNo >= 2 && ui_ChannelNo <= 3) {
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//i_ChannelNo=i_ChannelNo-2;
-				//i_Offset=64;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* i_ChannelNo=i_ChannelNo-2; */
+				/* i_Offset=64; */
 				s_BoardInfos[dev->minor].i_ChannelNo =
 					s_BoardInfos[dev->minor].i_ChannelNo -
 					2;
 				s_BoardInfos[dev->minor].i_Offset = 64;
-				//END JK 06.07.04: Management of sevrals boards
+				/* END JK 06.07.04: Management of sevrals boards */
 				ui_ChannelNo = ui_ChannelNo - 2;
-			}	//if(ui_ChannelNo >=2 && ui_ChannelNo <=3)
+			}	/* if(ui_ChannelNo >=2 && ui_ChannelNo <=3) */
 			if (ui_ChannelNo >= 4 && ui_ChannelNo <= 5) {
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//i_ChannelNo=i_ChannelNo-4;
-				//i_Offset=128;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* i_ChannelNo=i_ChannelNo-4; */
+				/* i_Offset=128; */
 				s_BoardInfos[dev->minor].i_ChannelNo =
 					s_BoardInfos[dev->minor].i_ChannelNo -
 					4;
 				s_BoardInfos[dev->minor].i_Offset = 128;
-				//END JK 06.07.04: Management of sevrals boards
+				/* END JK 06.07.04: Management of sevrals boards */
 				ui_ChannelNo = ui_ChannelNo - 4;
-			}	//if(ui_ChannelNo >=4 && ui_ChannelNo <=5)
+			}	/* if(ui_ChannelNo >=4 && ui_ChannelNo <=5) */
 			if (ui_ChannelNo >= 6 && ui_ChannelNo <= 7) {
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//i_ChannelNo=i_ChannelNo-6;
-				//i_Offset=192;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* i_ChannelNo=i_ChannelNo-6; */
+				/* i_Offset=192; */
 				s_BoardInfos[dev->minor].i_ChannelNo =
 					s_BoardInfos[dev->minor].i_ChannelNo -
 					6;
 				s_BoardInfos[dev->minor].i_Offset = 192;
-				//END JK 06.07.04: Management of sevrals boards
+				/* END JK 06.07.04: Management of sevrals boards */
 				ui_ChannelNo = ui_ChannelNo - 6;
-			}	//if(ui_ChannelNo >=6 && ui_ChannelNo <=7)
+			}	/* if(ui_ChannelNo >=6 && ui_ChannelNo <=7) */
 			break;
 
 		default:
 			printk("\n This selection of polarity does not exist\n");
 			i_err++;
-		}		//switch(data[2])
-	}			//if(data[12]==0 || data[12]==1)
+		}		/* switch(data[2]) */
+	}			/* if(data[12]==0 || data[12]==1) */
 	else {
 		switch (data[11]) {
 		case 1:
-			//BEGIN JK 06.07.04: Management of sevrals boards
-			//i_Offset=0;
+			/* BEGIN JK 06.07.04: Management of sevrals boards */
+			/* i_Offset=0; */
 			s_BoardInfos[dev->minor].i_Offset = 0;
-			//END JK 06.07.04: Management of sevrals boards
+			/* END JK 06.07.04: Management of sevrals boards */
 			break;
 		case 2:
-			//BEGIN JK 06.07.04: Management of sevrals boards
-			//i_Offset=64;
+			/* BEGIN JK 06.07.04: Management of sevrals boards */
+			/* i_Offset=64; */
 			s_BoardInfos[dev->minor].i_Offset = 64;
-			//END JK 06.07.04: Management of sevrals boards
+			/* END JK 06.07.04: Management of sevrals boards */
 			break;
 		case 3:
-			//BEGIN JK 06.07.04: Management of sevrals boards
-			//i_Offset=128;
+			/* BEGIN JK 06.07.04: Management of sevrals boards */
+			/* i_Offset=128; */
 			s_BoardInfos[dev->minor].i_Offset = 128;
-			//END JK 06.07.04: Management of sevrals boards
+			/* END JK 06.07.04: Management of sevrals boards */
 			break;
 		case 4:
-			//BEGIN JK 06.07.04: Management of sevrals boards
-			//i_Offset=192;
+			/* BEGIN JK 06.07.04: Management of sevrals boards */
+			/* i_Offset=192; */
 			s_BoardInfos[dev->minor].i_Offset = 192;
-			//END JK 06.07.04: Management of sevrals boards
+			/* END JK 06.07.04: Management of sevrals boards */
 			break;
 		default:
 			printk("\nError in module selection\n");
 			i_err++;
-		}		// switch(data[11])
-	}			// elseif(data[12]==0 || data[12]==1)
+		}		/*  switch(data[11]) */
+	}			/*  elseif(data[12]==0 || data[12]==1) */
 	if (i_err) {
 		i_APCI3200_Reset(dev);
 		return -EINVAL;
 	}
-	//if(i_ScanType!=1)
+	/* if(i_ScanType!=1) */
 	if (s_BoardInfos[dev->minor].i_ScanType != 1) {
-		//BEGIN JK 06.07.04: Management of sevrals boards
-		//i_Count=0;
-		//i_Sum=0;
+		/* BEGIN JK 06.07.04: Management of sevrals boards */
+		/* i_Count=0; */
+		/* i_Sum=0; */
 		s_BoardInfos[dev->minor].i_Count = 0;
 		s_BoardInfos[dev->minor].i_Sum = 0;
-		//END JK 06.07.04: Management of sevrals boards
-	}			//if(i_ScanType!=1)
+		/* END JK 06.07.04: Management of sevrals boards */
+	}			/* if(i_ScanType!=1) */
 
 	ul_Config =
 		data[1] | (data[2] << 6) | (data[5] << 7) | (data[3] << 8) |
 		(data[4] << 9);
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//END JK 06.07.04: Management of sevrals boards
+	/* END JK 06.07.04: Management of sevrals boards */
   /*********************************/
 	/* Write the channel to configure */
   /*********************************/
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//outl(0 | ui_ChannelNo , devpriv->iobase+i_Offset + 0x4);
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* outl(0 | ui_ChannelNo , devpriv->iobase+i_Offset + 0x4); */
 	outl(0 | ui_ChannelNo,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 0x4);
-	//END JK 06.07.04: Management of sevrals boards
+	/* END JK 06.07.04: Management of sevrals boards */
 
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//END JK 06.07.04: Management of sevrals boards
+	/* END JK 06.07.04: Management of sevrals boards */
   /**************************/
 	/* Reset the configuration */
   /**************************/
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//outl(0 , devpriv->iobase+i_Offset + 0x0);
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* outl(0 , devpriv->iobase+i_Offset + 0x0); */
 	outl(0, devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 0x0);
-	//END JK 06.07.04: Management of sevrals boards
+	/* END JK 06.07.04: Management of sevrals boards */
 
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//END JK 06.07.04: Management of sevrals boards
+	/* END JK 06.07.04: Management of sevrals boards */
 
   /***************************/
 	/* Write the configuration */
   /***************************/
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//outl(ul_Config , devpriv->iobase+i_Offset + 0x0);
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* outl(ul_Config , devpriv->iobase+i_Offset + 0x0); */
 	outl(ul_Config,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 0x0);
-	//END JK 06.07.04: Management of sevrals boards
+	/* END JK 06.07.04: Management of sevrals boards */
 
   /***************************/
 	/*Reset the calibration bit */
   /***************************/
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//ul_Temp = inl(devpriv->iobase+i_Offset + 12);
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* ul_Temp = inl(devpriv->iobase+i_Offset + 12); */
 	ul_Temp = inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 12);
-	//END JK 06.07.04: Management of sevrals boards
+	/* END JK 06.07.04: Management of sevrals boards */
 
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//END JK 06.07.04: Management of sevrals boards
+	/* END JK 06.07.04: Management of sevrals boards */
 
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//outl((ul_Temp & 0xFFF9FFFF) , devpriv->iobase+.i_Offset + 12);
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* outl((ul_Temp & 0xFFF9FFFF) , devpriv->iobase+.i_Offset + 12); */
 	outl((ul_Temp & 0xFFF9FFFF),
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 12);
-	//END JK 06.07.04: Management of sevrals boards
+	/* END JK 06.07.04: Management of sevrals boards */
 
 	if (data[9] == 1) {
 		devpriv->tsk_Current = current;
-		//BEGIN JK 06.07.04: Management of sevrals boards
-		//i_InterruptFlag=1;
+		/* BEGIN JK 06.07.04: Management of sevrals boards */
+		/* i_InterruptFlag=1; */
 		s_BoardInfos[dev->minor].i_InterruptFlag = 1;
-		//END JK 06.07.04: Management of sevrals boards
-	}			// if(data[9]==1)
+		/* END JK 06.07.04: Management of sevrals boards */
+	}			/*  if(data[9]==1) */
 	else {
-		//BEGIN JK 06.07.04: Management of sevrals boards
-		//i_InterruptFlag=0;
+		/* BEGIN JK 06.07.04: Management of sevrals boards */
+		/* i_InterruptFlag=0; */
 		s_BoardInfos[dev->minor].i_InterruptFlag = 0;
-		//END JK 06.07.04: Management of sevrals boards
-	}			//else  if(data[9]==1)
+		/* END JK 06.07.04: Management of sevrals boards */
+	}			/* else  if(data[9]==1) */
 
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//i_Initialised=1;
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* i_Initialised=1; */
 	s_BoardInfos[dev->minor].i_Initialised = 1;
-	//END JK 06.07.04: Management of sevrals boards
+	/* END JK 06.07.04: Management of sevrals boards */
 
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//if(i_ScanType==1)
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* if(i_ScanType==1) */
 	if (s_BoardInfos[dev->minor].i_ScanType == 1)
-		//END JK 06.07.04: Management of sevrals boards
+		/* END JK 06.07.04: Management of sevrals boards */
 	{
-		//BEGIN JK 06.07.04: Management of sevrals boards
-		//i_Sum=i_Sum+1;
+		/* BEGIN JK 06.07.04: Management of sevrals boards */
+		/* i_Sum=i_Sum+1; */
 		s_BoardInfos[dev->minor].i_Sum =
 			s_BoardInfos[dev->minor].i_Sum + 1;
-		//END JK 06.07.04: Management of sevrals boards
+		/* END JK 06.07.04: Management of sevrals boards */
 
 		insn->unused[0] = 0;
 		i_APCI3200_ReadAnalogInput(dev, s, insn, &ui_Dummy);
@@ -1340,8 +1333,8 @@
   | Task              : Read  value  of the selected channel			         |
   +----------------------------------------------------------------------------+
   | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-  |                     UINT ui_NoOfChannels    : No Of Channels To read       |
-  |                     UINT *data              : Data Pointer to read status  |
+  |                     unsigned int ui_NoOfChannels    : No Of Channels To read       |
+  |                     unsigned int *data              : Data Pointer to read status  |
   +----------------------------------------------------------------------------+
   | Output Parameters :	--													 |
   |				data[0]  : Digital Value Of Input             |
@@ -1361,21 +1354,21 @@
   |			                                                         |
   +----------------------------------------------------------------------------+
 */
-INT i_APCI3200_ReadAnalogInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3200_ReadAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_DummyValue = 0;
+	unsigned int ui_DummyValue = 0;
 	int i_ConvertCJCCalibration;
 	int i = 0;
 
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//if(i_Initialised==0)
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* if(i_Initialised==0) */
 	if (s_BoardInfos[dev->minor].i_Initialised == 0)
-		//END JK 06.07.04: Management of sevrals boards
+		/* END JK 06.07.04: Management of sevrals boards */
 	{
 		i_APCI3200_Reset(dev);
 		return -EINVAL;
-	}			//if(i_Initialised==0);
+	}			/* if(i_Initialised==0); */
 
 #ifdef PRINT_INFO
 	printk("\n insn->unused[0] = %i", insn->unused[0]);
@@ -1386,14 +1379,14 @@
 
 		i_APCI3200_Read1AnalogInputChannel(dev, s, insn,
 			&ui_DummyValue);
-		//BEGIN JK 06.07.04: Management of sevrals boards
-		//ui_InterruptChannelValue[i_Count+0]=ui_DummyValue;
+		/* BEGIN JK 06.07.04: Management of sevrals boards */
+		/* ui_InterruptChannelValue[i_Count+0]=ui_DummyValue; */
 		s_BoardInfos[dev->minor].
 			ui_InterruptChannelValue[s_BoardInfos[dev->minor].
 			i_Count + 0] = ui_DummyValue;
-		//END JK 06.07.04: Management of sevrals boards
+		/* END JK 06.07.04: Management of sevrals boards */
 
-		//Begin JK 25.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+		/* Begin JK 25.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 		i_APCI3200_GetChannelCalibrationValue(dev,
 			s_BoardInfos[dev->minor].ui_Channel_num,
 			&s_BoardInfos[dev->minor].
@@ -1414,62 +1407,62 @@
 		printk("\n s_BoardInfos [dev->minor].ui_InterruptChannelValue[s_BoardInfos [dev->minor].i_Count+8] = %lu", s_BoardInfos[dev->minor].ui_InterruptChannelValue[s_BoardInfos[dev->minor].i_Count + 8]);
 #endif
 
-		//End JK 25.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+		/* End JK 25.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
-		//BEGIN JK 06.07.04: Management of sevrals boards
-		//if((i_ADDIDATAType==2) && (i_InterruptFlag == FALSE) && (i_CJCAvailable==1))
+		/* BEGIN JK 06.07.04: Management of sevrals boards */
+		/* if((i_ADDIDATAType==2) && (i_InterruptFlag == FALSE) && (i_CJCAvailable==1)) */
 		if ((s_BoardInfos[dev->minor].i_ADDIDATAType == 2)
 			&& (s_BoardInfos[dev->minor].i_InterruptFlag == FALSE)
 			&& (s_BoardInfos[dev->minor].i_CJCAvailable == 1))
-			//END JK 06.07.04: Management of sevrals boards
+			/* END JK 06.07.04: Management of sevrals boards */
 		{
 			i_APCI3200_ReadCJCValue(dev, &ui_DummyValue);
-			//BEGIN JK 06.07.04: Management of sevrals boards
-			//ui_InterruptChannelValue[i_Count + 3]=ui_DummyValue;
+			/* BEGIN JK 06.07.04: Management of sevrals boards */
+			/* ui_InterruptChannelValue[i_Count + 3]=ui_DummyValue; */
 			s_BoardInfos[dev->minor].
 				ui_InterruptChannelValue[s_BoardInfos[dev->
 					minor].i_Count + 3] = ui_DummyValue;
-			//END JK 06.07.04: Management of sevrals boards
-		}		//if((i_ADDIDATAType==2) && (i_InterruptFlag == FALSE))
+			/* END JK 06.07.04: Management of sevrals boards */
+		}		/* if((i_ADDIDATAType==2) && (i_InterruptFlag == FALSE)) */
 		else {
-			//BEGIN JK 06.07.04: Management of sevrals boards
-			//ui_InterruptChannelValue[i_Count + 3]=0;
+			/* BEGIN JK 06.07.04: Management of sevrals boards */
+			/* ui_InterruptChannelValue[i_Count + 3]=0; */
 			s_BoardInfos[dev->minor].
 				ui_InterruptChannelValue[s_BoardInfos[dev->
 					minor].i_Count + 3] = 0;
-			//END JK 06.07.04: Management of sevrals boards
-		}		//elseif((i_ADDIDATAType==2) && (i_InterruptFlag == FALSE) && (i_CJCAvailable==1))
+			/* END JK 06.07.04: Management of sevrals boards */
+		}		/* elseif((i_ADDIDATAType==2) && (i_InterruptFlag == FALSE) && (i_CJCAvailable==1)) */
 
-		//BEGIN JK 06.07.04: Management of sevrals boards
-		//if (( i_AutoCalibration == FALSE) && (i_InterruptFlag == FALSE))
+		/* BEGIN JK 06.07.04: Management of sevrals boards */
+		/* if (( i_AutoCalibration == FALSE) && (i_InterruptFlag == FALSE)) */
 		if ((s_BoardInfos[dev->minor].i_AutoCalibration == FALSE)
 			&& (s_BoardInfos[dev->minor].i_InterruptFlag == FALSE))
-			//END JK 06.07.04: Management of sevrals boards
+			/* END JK 06.07.04: Management of sevrals boards */
 		{
 			i_APCI3200_ReadCalibrationOffsetValue(dev,
 				&ui_DummyValue);
-			//BEGIN JK 06.07.04: Management of sevrals boards
-			//ui_InterruptChannelValue[i_Count + 1]=ui_DummyValue;
+			/* BEGIN JK 06.07.04: Management of sevrals boards */
+			/* ui_InterruptChannelValue[i_Count + 1]=ui_DummyValue; */
 			s_BoardInfos[dev->minor].
 				ui_InterruptChannelValue[s_BoardInfos[dev->
 					minor].i_Count + 1] = ui_DummyValue;
-			//END JK 06.07.04: Management of sevrals boards
+			/* END JK 06.07.04: Management of sevrals boards */
 			i_APCI3200_ReadCalibrationGainValue(dev,
 				&ui_DummyValue);
-			//BEGIN JK 06.07.04: Management of sevrals boards
-			//ui_InterruptChannelValue[i_Count + 2]=ui_DummyValue;
+			/* BEGIN JK 06.07.04: Management of sevrals boards */
+			/* ui_InterruptChannelValue[i_Count + 2]=ui_DummyValue; */
 			s_BoardInfos[dev->minor].
 				ui_InterruptChannelValue[s_BoardInfos[dev->
 					minor].i_Count + 2] = ui_DummyValue;
-			//END JK 06.07.04: Management of sevrals boards
-		}		//if (( i_AutoCalibration == FALSE) && (i_InterruptFlag == FALSE))
+			/* END JK 06.07.04: Management of sevrals boards */
+		}		/* if (( i_AutoCalibration == FALSE) && (i_InterruptFlag == FALSE)) */
 
-		//BEGIN JK 06.07.04: Management of sevrals boards
-		//if((i_ADDIDATAType==2) && (i_InterruptFlag == FALSE)&& (i_CJCAvailable==1))
+		/* BEGIN JK 06.07.04: Management of sevrals boards */
+		/* if((i_ADDIDATAType==2) && (i_InterruptFlag == FALSE)&& (i_CJCAvailable==1)) */
 		if ((s_BoardInfos[dev->minor].i_ADDIDATAType == 2)
 			&& (s_BoardInfos[dev->minor].i_InterruptFlag == FALSE)
 			&& (s_BoardInfos[dev->minor].i_CJCAvailable == 1))
-			//END JK 06.07.04: Management of sevrals boards
+			/* END JK 06.07.04: Management of sevrals boards */
 		{
 	  /**********************************************************/
 			/*Test if the Calibration channel must be read for the CJC */
@@ -1477,52 +1470,52 @@
 	  /**********************************/
 			/*Test if the polarity is the same */
 	  /**********************************/
-			//BEGIN JK 06.07.04: Management of sevrals boards
-			//if(i_CJCPolarity!=i_ADDIDATAPolarity)
+			/* BEGIN JK 06.07.04: Management of sevrals boards */
+			/* if(i_CJCPolarity!=i_ADDIDATAPolarity) */
 			if (s_BoardInfos[dev->minor].i_CJCPolarity !=
 				s_BoardInfos[dev->minor].i_ADDIDATAPolarity)
-				//END JK 06.07.04: Management of sevrals boards
+				/* END JK 06.07.04: Management of sevrals boards */
 			{
 				i_ConvertCJCCalibration = 1;
-			}	//if(i_CJCPolarity!=i_ADDIDATAPolarity)
+			}	/* if(i_CJCPolarity!=i_ADDIDATAPolarity) */
 			else {
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//if(i_CJCGain==i_ADDIDATAGain)
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* if(i_CJCGain==i_ADDIDATAGain) */
 				if (s_BoardInfos[dev->minor].i_CJCGain ==
 					s_BoardInfos[dev->minor].i_ADDIDATAGain)
-					//END JK 06.07.04: Management of sevrals boards
+					/* END JK 06.07.04: Management of sevrals boards */
 				{
 					i_ConvertCJCCalibration = 0;
-				}	//if(i_CJCGain==i_ADDIDATAGain)
+				}	/* if(i_CJCGain==i_ADDIDATAGain) */
 				else {
 					i_ConvertCJCCalibration = 1;
-				}	//elseif(i_CJCGain==i_ADDIDATAGain)
-			}	//elseif(i_CJCPolarity!=i_ADDIDATAPolarity)
+				}	/* elseif(i_CJCGain==i_ADDIDATAGain) */
+			}	/* elseif(i_CJCPolarity!=i_ADDIDATAPolarity) */
 			if (i_ConvertCJCCalibration == 1) {
 				i_APCI3200_ReadCJCCalOffset(dev,
 					&ui_DummyValue);
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//ui_InterruptChannelValue[i_Count+4]=ui_DummyValue;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* ui_InterruptChannelValue[i_Count+4]=ui_DummyValue; */
 				s_BoardInfos[dev->minor].
 					ui_InterruptChannelValue[s_BoardInfos
 					[dev->minor].i_Count + 4] =
 					ui_DummyValue;
-				//END JK 06.07.04: Management of sevrals boards
+				/* END JK 06.07.04: Management of sevrals boards */
 
 				i_APCI3200_ReadCJCCalGain(dev, &ui_DummyValue);
 
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//ui_InterruptChannelValue[i_Count+5]=ui_DummyValue;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* ui_InterruptChannelValue[i_Count+5]=ui_DummyValue; */
 				s_BoardInfos[dev->minor].
 					ui_InterruptChannelValue[s_BoardInfos
 					[dev->minor].i_Count + 5] =
 					ui_DummyValue;
-				//END JK 06.07.04: Management of sevrals boards
-			}	//if(i_ConvertCJCCalibration==1)
+				/* END JK 06.07.04: Management of sevrals boards */
+			}	/* if(i_ConvertCJCCalibration==1) */
 			else {
-				//BEGIN JK 06.07.04: Management of sevrals boards
-				//ui_InterruptChannelValue[i_Count+4]=0;
-				//ui_InterruptChannelValue[i_Count+5]=0;
+				/* BEGIN JK 06.07.04: Management of sevrals boards */
+				/* ui_InterruptChannelValue[i_Count+4]=0; */
+				/* ui_InterruptChannelValue[i_Count+5]=0; */
 
 				s_BoardInfos[dev->minor].
 					ui_InterruptChannelValue[s_BoardInfos
@@ -1530,36 +1523,36 @@
 				s_BoardInfos[dev->minor].
 					ui_InterruptChannelValue[s_BoardInfos
 					[dev->minor].i_Count + 5] = 0;
-				//END JK 06.07.04: Management of sevrals boards
-			}	//elseif(i_ConvertCJCCalibration==1)
-		}		//if((i_ADDIDATAType==2) && (i_InterruptFlag == FALSE))
+				/* END JK 06.07.04: Management of sevrals boards */
+			}	/* elseif(i_ConvertCJCCalibration==1) */
+		}		/* if((i_ADDIDATAType==2) && (i_InterruptFlag == FALSE)) */
 
-		//BEGIN JK 06.07.04: Management of sevrals boards
-		//if(i_ScanType!=1)
+		/* BEGIN JK 06.07.04: Management of sevrals boards */
+		/* if(i_ScanType!=1) */
 		if (s_BoardInfos[dev->minor].i_ScanType != 1) {
-			//i_Count=0;
+			/* i_Count=0; */
 			s_BoardInfos[dev->minor].i_Count = 0;
-		}		//if(i_ScanType!=1)
+		}		/* if(i_ScanType!=1) */
 		else {
-			//i_Count=i_Count +6;
-			//Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
-			//s_BoardInfos [dev->minor].i_Count=s_BoardInfos [dev->minor].i_Count +6;
+			/* i_Count=i_Count +6; */
+			/* Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
+			/* s_BoardInfos [dev->minor].i_Count=s_BoardInfos [dev->minor].i_Count +6; */
 			s_BoardInfos[dev->minor].i_Count =
 				s_BoardInfos[dev->minor].i_Count + 9;
-			//End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
-		}		//else if(i_ScanType!=1)
+			/* End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
+		}		/* else if(i_ScanType!=1) */
 
-		//if((i_ScanType==1) &&(i_InterruptFlag==1))
+		/* if((i_ScanType==1) &&(i_InterruptFlag==1)) */
 		if ((s_BoardInfos[dev->minor].i_ScanType == 1)
 			&& (s_BoardInfos[dev->minor].i_InterruptFlag == 1)) {
-			//i_Count=i_Count-6;
-			//Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
-			//s_BoardInfos [dev->minor].i_Count=s_BoardInfos [dev->minor].i_Count-6;
+			/* i_Count=i_Count-6; */
+			/* Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
+			/* s_BoardInfos [dev->minor].i_Count=s_BoardInfos [dev->minor].i_Count-6; */
 			s_BoardInfos[dev->minor].i_Count =
 				s_BoardInfos[dev->minor].i_Count - 9;
-			//End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+			/* End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 		}
-		//if(i_ScanType==0)
+		/* if(i_ScanType==0) */
 		if (s_BoardInfos[dev->minor].i_ScanType == 0) {
 			/*
 			   data[0]= ui_InterruptChannelValue[0];
@@ -1591,41 +1584,41 @@
 				s_BoardInfos[dev->minor].
 				ui_InterruptChannelValue[5];
 
-			//Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
-			//printk("\n 0 - i_APCI3200_GetChannelCalibrationValue data [6] = %lu, data [7] = %lu, data [8] = %lu", data [6], data [7], data [8]);
+			/* Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
+			/* printk("\n 0 - i_APCI3200_GetChannelCalibrationValue data [6] = %lu, data [7] = %lu, data [8] = %lu", data [6], data [7], data [8]); */
 			i_APCI3200_GetChannelCalibrationValue(dev,
 				s_BoardInfos[dev->minor].ui_Channel_num,
 				&data[6], &data[7], &data[8]);
-			//End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+			/* End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 		}
 		break;
 	case 1:
 
 		for (i = 0; i < insn->n; i++) {
-			//data[i]=ui_InterruptChannelValue[i];
+			/* data[i]=ui_InterruptChannelValue[i]; */
 			data[i] =
 				s_BoardInfos[dev->minor].
 				ui_InterruptChannelValue[i];
 		}
 
-		//i_Count=0;
-		//i_Sum=0;
-		//if(i_ScanType==1)
+		/* i_Count=0; */
+		/* i_Sum=0; */
+		/* if(i_ScanType==1) */
 		s_BoardInfos[dev->minor].i_Count = 0;
 		s_BoardInfos[dev->minor].i_Sum = 0;
 		if (s_BoardInfos[dev->minor].i_ScanType == 1) {
-			//i_Initialised=0;
-			//i_InterruptFlag=0;
+			/* i_Initialised=0; */
+			/* i_InterruptFlag=0; */
 			s_BoardInfos[dev->minor].i_Initialised = 0;
 			s_BoardInfos[dev->minor].i_InterruptFlag = 0;
-			//END JK 06.07.04: Management of sevrals boards
+			/* END JK 06.07.04: Management of sevrals boards */
 		}
 		break;
 	default:
 		printk("\nThe parameters passed are in error\n");
 		i_APCI3200_Reset(dev);
 		return -EINVAL;
-	}			//switch(insn->unused[0])
+	}			/* switch(insn->unused[0]) */
 
 	return insn->n;
 }
@@ -1639,8 +1632,8 @@
   | Task              : Read  value  of the selected channel			         |
   +----------------------------------------------------------------------------+
   | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-  |                     UINT ui_NoOfChannel    : Channel No to read            |
-  |                     UINT *data              : Data Pointer to read status  |
+  |                     unsigned int ui_NoOfChannel    : Channel No to read            |
+  |                     unsigned int *data              : Data Pointer to read status  |
   +----------------------------------------------------------------------------+
   | Output Parameters :	--													 |
   |			          data[0]  : Digital Value read                   |
@@ -1651,49 +1644,49 @@
   |			                                                         |
   +----------------------------------------------------------------------------+
 */
-INT i_APCI3200_Read1AnalogInputChannel(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3200_Read1AnalogInputChannel(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_EOC = 0;
-	UINT ui_ChannelNo = 0;
-	UINT ui_CommandRegister = 0;
+	unsigned int ui_EOC = 0;
+	unsigned int ui_ChannelNo = 0;
+	unsigned int ui_CommandRegister = 0;
 
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//ui_ChannelNo=i_ChannelNo;
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* ui_ChannelNo=i_ChannelNo; */
 	ui_ChannelNo = s_BoardInfos[dev->minor].i_ChannelNo;
 
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
   /*********************************/
 	/* Write the channel to configure */
   /*********************************/
-	//Begin JK 20.10.2004: Bad channel value is used when using differential mode
-	//outl(0 | ui_Channel_num , devpriv->iobase+i_Offset + 0x4);
-	//outl(0 | s_BoardInfos [dev->minor].ui_Channel_num , devpriv->iobase+s_BoardInfos [dev->minor].i_Offset + 0x4);
+	/* Begin JK 20.10.2004: Bad channel value is used when using differential mode */
+	/* outl(0 | ui_Channel_num , devpriv->iobase+i_Offset + 0x4); */
+	/* outl(0 | s_BoardInfos [dev->minor].ui_Channel_num , devpriv->iobase+s_BoardInfos [dev->minor].i_Offset + 0x4); */
 	outl(0 | s_BoardInfos[dev->minor].i_ChannelNo,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 0x4);
-	//End JK 20.10.2004: Bad channel value is used when using differential mode
+	/* End JK 20.10.2004: Bad channel value is used when using differential mode */
 
   /*******************************/
 	/* Set the convert timing unit */
   /*******************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
 
-	//outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36);
+	/* outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTimeUnit,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 36);
 
   /**************************/
 	/* Set the convert timing */
   /**************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
 
-	//outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32);
+	/* outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTime,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 32);
 
@@ -1707,36 +1700,36 @@
 	/*Test if the interrupt is enable */
   /*********************************/
 
-	//if (i_InterruptFlag == ADDIDATA_ENABLE)
+	/* if (i_InterruptFlag == ADDIDATA_ENABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_ENABLE) {
       /************************/
 		/* Enable the interrupt */
       /************************/
 		ui_CommandRegister = ui_CommandRegister | 0x00100000;
-	}			//if (i_InterruptFlag == ADDIDATA_ENABLE)
+	}			/* if (i_InterruptFlag == ADDIDATA_ENABLE) */
 
   /******************************/
 	/* Write the command register */
   /******************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
 
-	//outl(ui_CommandRegister, devpriv->iobase+i_Offset + 8);
+	/* outl(ui_CommandRegister, devpriv->iobase+i_Offset + 8); */
 	outl(ui_CommandRegister,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 8);
 
   /*****************************/
 	/*Test if interrupt is enable */
   /*****************************/
-	//if (i_InterruptFlag == ADDIDATA_DISABLE)
+	/* if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_DISABLE) {
 		do {
 	  /*************************/
 			/*Read the EOC Status bit */
 	  /*************************/
 
-			//ui_EOC = inl(devpriv->iobase+i_Offset + 20) & 1;
+			/* ui_EOC = inl(devpriv->iobase+i_Offset + 20) & 1; */
 			ui_EOC = inl(devpriv->iobase +
 				s_BoardInfos[dev->minor].i_Offset + 20) & 1;
 
@@ -1746,13 +1739,13 @@
 		/* Read the digital value of the input */
       /***************************************/
 
-		//data[0] = inl (devpriv->iobase+i_Offset + 28);
+		/* data[0] = inl (devpriv->iobase+i_Offset + 28); */
 		data[0] =
 			inl(devpriv->iobase +
 			s_BoardInfos[dev->minor].i_Offset + 28);
-		//END JK 06.07.04: Management of sevrals boards
+		/* END JK 06.07.04: Management of sevrals boards */
 
-	}			// if (i_InterruptFlag == ADDIDATA_DISABLE)
+	}			/*  if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	return 0;
 }
 
@@ -1765,7 +1758,7 @@
   | Task              : Read calibration offset  value  of the selected channel|
   +----------------------------------------------------------------------------+
   | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-  |                     UINT *data              : Data Pointer to read status  |
+  |                     unsigned int *data              : Data Pointer to read status  |
   +----------------------------------------------------------------------------+
   | Output Parameters :	--													 |
   |			          data[0]  : Calibration offset Value   |
@@ -1776,54 +1769,54 @@
   |			                                                         |
   +----------------------------------------------------------------------------+
 */
-int i_APCI3200_ReadCalibrationOffsetValue(struct comedi_device * dev, UINT * data)
+int i_APCI3200_ReadCalibrationOffsetValue(struct comedi_device *dev, unsigned int *data)
 {
-	UINT ui_Temp = 0, ui_EOC = 0;
-	UINT ui_CommandRegister = 0;
+	unsigned int ui_Temp = 0, ui_EOC = 0;
+	unsigned int ui_CommandRegister = 0;
 
-	//BEGIN JK 06.07.04: Management of sevrals boards
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* BEGIN JK 06.07.04: Management of sevrals boards */
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
   /*********************************/
 	/* Write the channel to configure */
   /*********************************/
-	//Begin JK 20.10.2004: This seems not necessary !
-	//outl(0 | ui_Channel_num , devpriv->iobase+i_Offset + 0x4);
-	//outl(0 | s_BoardInfos [dev->minor].ui_Channel_num , devpriv->iobase+s_BoardInfos [dev->minor].i_Offset + 0x4);
-	//End JK 20.10.2004: This seems not necessary !
+	/* Begin JK 20.10.2004: This seems not necessary ! */
+	/* outl(0 | ui_Channel_num , devpriv->iobase+i_Offset + 0x4); */
+	/* outl(0 | s_BoardInfos [dev->minor].ui_Channel_num , devpriv->iobase+s_BoardInfos [dev->minor].i_Offset + 0x4); */
+	/* End JK 20.10.2004: This seems not necessary ! */
 
   /*******************************/
 	/* Set the convert timing unit */
   /*******************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36);
+	/* outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTimeUnit,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 36);
   /**************************/
 	/* Set the convert timing */
   /**************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32);
+	/* outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTime,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 32);
   /*****************************/
 	/*Read the calibration offset */
   /*****************************/
-	//ui_Temp = inl(devpriv->iobase+i_Offset + 12);
+	/* ui_Temp = inl(devpriv->iobase+i_Offset + 12); */
 	ui_Temp = inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 12);
 
   /*********************************/
 	/*Configure the Offset Conversion */
   /*********************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl((ui_Temp | 0x00020000), devpriv->iobase+i_Offset + 12);
+	/* outl((ui_Temp | 0x00020000), devpriv->iobase+i_Offset + 12); */
 	outl((ui_Temp | 0x00020000),
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 12);
   /*******************************/
@@ -1836,7 +1829,7 @@
 	/*Test if the interrupt is enable */
   /*********************************/
 
-	//if (i_InterruptFlag == ADDIDATA_ENABLE)
+	/* if (i_InterruptFlag == ADDIDATA_ENABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_ENABLE) {
 
       /**********************/
@@ -1845,7 +1838,7 @@
 
 		ui_CommandRegister = ui_CommandRegister | 0x00100000;
 
-	}			//if (i_InterruptFlag == ADDIDATA_ENABLE)
+	}			/* if (i_InterruptFlag == ADDIDATA_ENABLE) */
 
   /**********************/
 	/*Start the conversion */
@@ -1855,10 +1848,10 @@
   /***************************/
 	/*Write the command regiter */
   /***************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(ui_CommandRegister, devpriv->iobase+i_Offset + 8);
+	/* outl(ui_CommandRegister, devpriv->iobase+i_Offset + 8); */
 	outl(ui_CommandRegister,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 8);
 
@@ -1866,7 +1859,7 @@
 	/*Test if interrupt is enable */
   /*****************************/
 
-	//if (i_InterruptFlag == ADDIDATA_DISABLE)
+	/* if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_DISABLE) {
 
 		do {
@@ -1874,7 +1867,7 @@
 			/*Read the EOC flag */
 	  /*******************/
 
-			//ui_EOC = inl (devpriv->iobase+i_Offset + 20) & 1;
+			/* ui_EOC = inl (devpriv->iobase+i_Offset + 20) & 1; */
 			ui_EOC = inl(devpriv->iobase +
 				s_BoardInfos[dev->minor].i_Offset + 20) & 1;
 
@@ -1884,11 +1877,11 @@
 		/*Read the digital value of the calibration Offset */
       /**************************************************/
 
-		//data[0] = inl(devpriv->iobase+i_Offset+ 28);
+		/* data[0] = inl(devpriv->iobase+i_Offset+ 28); */
 		data[0] =
 			inl(devpriv->iobase +
 			s_BoardInfos[dev->minor].i_Offset + 28);
-	}			//if (i_InterruptFlag == ADDIDATA_DISABLE)
+	}			/* if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	return 0;
 }
 
@@ -1901,7 +1894,7 @@
   | Task              : Read calibration gain  value  of the selected channel  |
   +----------------------------------------------------------------------------+
   | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-  |                     UINT *data              : Data Pointer to read status  |
+  |                     unsigned int *data              : Data Pointer to read status  |
   +----------------------------------------------------------------------------+
   | Output Parameters :	--													 |
   |			          data[0]  : Calibration gain Value Of Input     |
@@ -1912,21 +1905,21 @@
   |			                                                         |
   +----------------------------------------------------------------------------+
 */
-int i_APCI3200_ReadCalibrationGainValue(struct comedi_device * dev, UINT * data)
+int i_APCI3200_ReadCalibrationGainValue(struct comedi_device *dev, unsigned int *data)
 {
-	UINT ui_EOC = 0;
-	INT ui_CommandRegister = 0;
+	unsigned int ui_EOC = 0;
+	int ui_CommandRegister = 0;
 
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
   /*********************************/
 	/* Write the channel to configure */
   /*********************************/
-	//Begin JK 20.10.2004: This seems not necessary !
-	//outl(0 | ui_Channel_num , devpriv->iobase+i_Offset + 0x4);
-	//outl(0 | s_BoardInfos [dev->minor].ui_Channel_num , devpriv->iobase+s_BoardInfos [dev->minor].i_Offset + 0x4);
-	//End JK 20.10.2004: This seems not necessary !
+	/* Begin JK 20.10.2004: This seems not necessary ! */
+	/* outl(0 | ui_Channel_num , devpriv->iobase+i_Offset + 0x4); */
+	/* outl(0 | s_BoardInfos [dev->minor].ui_Channel_num , devpriv->iobase+s_BoardInfos [dev->minor].i_Offset + 0x4); */
+	/* End JK 20.10.2004: This seems not necessary ! */
 
   /***************************/
 	/*Read the calibration gain */
@@ -1934,28 +1927,28 @@
   /*******************************/
 	/* Set the convert timing unit */
   /*******************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36);
+	/* outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTimeUnit,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 36);
   /**************************/
 	/* Set the convert timing */
   /**************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32);
+	/* outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTime,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 32);
   /*******************************/
 	/*Configure the Gain Conversion */
   /*******************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(0x00040000 , devpriv->iobase+i_Offset + 12);
+	/* outl(0x00040000 , devpriv->iobase+i_Offset + 12); */
 	outl(0x00040000,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 12);
 
@@ -1969,7 +1962,7 @@
 	/*Test if the interrupt is enable */
   /*********************************/
 
-	//if (i_InterruptFlag == ADDIDATA_ENABLE)
+	/* if (i_InterruptFlag == ADDIDATA_ENABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_ENABLE) {
 
       /**********************/
@@ -1978,7 +1971,7 @@
 
 		ui_CommandRegister = ui_CommandRegister | 0x00100000;
 
-	}			//if (i_InterruptFlag == ADDIDATA_ENABLE)
+	}			/* if (i_InterruptFlag == ADDIDATA_ENABLE) */
 
   /**********************/
 	/*Start the conversion */
@@ -1988,10 +1981,10 @@
   /***************************/
 	/*Write the command regiter */
   /***************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(ui_CommandRegister , devpriv->iobase+i_Offset + 8);
+	/* outl(ui_CommandRegister , devpriv->iobase+i_Offset + 8); */
 	outl(ui_CommandRegister,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 8);
 
@@ -1999,7 +1992,7 @@
 	/*Test if interrupt is enable */
   /*****************************/
 
-	//if (i_InterruptFlag == ADDIDATA_DISABLE)
+	/* if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_DISABLE) {
 
 		do {
@@ -2008,7 +2001,7 @@
 			/*Read the EOC flag */
 	  /*******************/
 
-			//ui_EOC = inl(devpriv->iobase+i_Offset + 20) & 1;
+			/* ui_EOC = inl(devpriv->iobase+i_Offset + 20) & 1; */
 			ui_EOC = inl(devpriv->iobase +
 				s_BoardInfos[dev->minor].i_Offset + 20) & 1;
 
@@ -2018,12 +2011,12 @@
 		/*Read the digital value of the calibration Gain */
       /************************************************/
 
-		//data[0] = inl(devpriv->iobase+i_Offset + 28);
+		/* data[0] = inl(devpriv->iobase+i_Offset + 28); */
 		data[0] =
 			inl(devpriv->iobase +
 			s_BoardInfos[dev->minor].i_Offset + 28);
 
-	}			//if (i_InterruptFlag == ADDIDATA_DISABLE)
+	}			/* if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	return 0;
 }
 
@@ -2036,7 +2029,7 @@
   | Task              : Read CJC  value  of the selected channel               |
   +----------------------------------------------------------------------------+
   | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-  |                     UINT *data              : Data Pointer to read status  |
+  |                     unsigned int *data              : Data Pointer to read status  |
   +----------------------------------------------------------------------------+
   | Output Parameters :	--													 |
   |			          data[0]  : CJC Value                           |
@@ -2048,41 +2041,41 @@
   +----------------------------------------------------------------------------+
 */
 
-int i_APCI3200_ReadCJCValue(struct comedi_device * dev, unsigned int * data)
+int i_APCI3200_ReadCJCValue(struct comedi_device *dev, unsigned int *data)
 {
-	UINT ui_EOC = 0;
-	INT ui_CommandRegister = 0;
+	unsigned int ui_EOC = 0;
+	int ui_CommandRegister = 0;
 
   /******************************/
 	/*Set the converting time unit */
   /******************************/
 
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
 
-	//outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36);
+	/* outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTimeUnit,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 36);
   /**************************/
 	/* Set the convert timing */
   /**************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
 
-	//outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32);
+	/* outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTime,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 32);
 
   /******************************/
 	/*Configure the CJC Conversion */
   /******************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
 
-	//outl( 0x00000400 , devpriv->iobase+i_Offset + 4);
+	/* outl( 0x00000400 , devpriv->iobase+i_Offset + 4); */
 	outl(0x00000400,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 4);
   /*******************************/
@@ -2092,7 +2085,7 @@
   /*********************************/
 	/*Test if the interrupt is enable */
   /*********************************/
-	//if (i_InterruptFlag == ADDIDATA_ENABLE)
+	/* if (i_InterruptFlag == ADDIDATA_ENABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_ENABLE) {
       /**********************/
 		/*Enable the interrupt */
@@ -2109,10 +2102,10 @@
   /***************************/
 	/*Write the command regiter */
   /***************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(ui_CommandRegister , devpriv->iobase+i_Offset + 8);
+	/* outl(ui_CommandRegister , devpriv->iobase+i_Offset + 8); */
 	outl(ui_CommandRegister,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 8);
 
@@ -2120,7 +2113,7 @@
 	/*Test if interrupt is enable */
   /*****************************/
 
-	//if (i_InterruptFlag == ADDIDATA_DISABLE)
+	/* if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_DISABLE) {
 		do {
 
@@ -2128,7 +2121,7 @@
 			/*Read the EOC flag */
 	  /*******************/
 
-			//ui_EOC = inl(devpriv->iobase+i_Offset + 20) & 1;
+			/* ui_EOC = inl(devpriv->iobase+i_Offset + 20) & 1; */
 			ui_EOC = inl(devpriv->iobase +
 				s_BoardInfos[dev->minor].i_Offset + 20) & 1;
 
@@ -2138,12 +2131,12 @@
 		/*Read the digital value of the CJC */
       /***********************************/
 
-		//data[0] = inl(devpriv->iobase+i_Offset + 28);
+		/* data[0] = inl(devpriv->iobase+i_Offset + 28); */
 		data[0] =
 			inl(devpriv->iobase +
 			s_BoardInfos[dev->minor].i_Offset + 28);
 
-	}			//if (i_InterruptFlag == ADDIDATA_DISABLE)
+	}			/* if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	return 0;
 }
 
@@ -2156,7 +2149,7 @@
   | Task              : Read CJC calibration offset  value  of the selected channel
   +----------------------------------------------------------------------------+
   | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-  |                     UINT *data              : Data Pointer to read status  |
+  |                     unsigned int *data              : Data Pointer to read status  |
   +----------------------------------------------------------------------------+
   | Output Parameters :	--													 |
   |			          data[0]  : CJC calibration offset Value
@@ -2167,47 +2160,47 @@
   |			                                                         |
   +----------------------------------------------------------------------------+
 */
-int i_APCI3200_ReadCJCCalOffset(struct comedi_device * dev, unsigned int * data)
+int i_APCI3200_ReadCJCCalOffset(struct comedi_device *dev, unsigned int *data)
 {
-	UINT ui_EOC = 0;
-	INT ui_CommandRegister = 0;
+	unsigned int ui_EOC = 0;
+	int ui_CommandRegister = 0;
   /*******************************************/
 	/*Read calibration offset value for the CJC */
   /*******************************************/
   /*******************************/
 	/* Set the convert timing unit */
   /*******************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36);
+	/* outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTimeUnit,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 36);
   /**************************/
 	/* Set the convert timing */
   /**************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32);
+	/* outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTime,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 32);
   /******************************/
 	/*Configure the CJC Conversion */
   /******************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(0x00000400 , devpriv->iobase+i_Offset + 4);
+	/* outl(0x00000400 , devpriv->iobase+i_Offset + 4); */
 	outl(0x00000400,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 4);
   /*********************************/
 	/*Configure the Offset Conversion */
   /*********************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(0x00020000, devpriv->iobase+i_Offset + 12);
+	/* outl(0x00020000, devpriv->iobase+i_Offset + 12); */
 	outl(0x00020000,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 12);
   /*******************************/
@@ -2218,7 +2211,7 @@
 	/*Test if the interrupt is enable */
   /*********************************/
 
-	//if (i_InterruptFlag == ADDIDATA_ENABLE)
+	/* if (i_InterruptFlag == ADDIDATA_ENABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_ENABLE) {
       /**********************/
 		/*Enable the interrupt */
@@ -2234,19 +2227,19 @@
   /***************************/
 	/*Write the command regiter */
   /***************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(ui_CommandRegister,devpriv->iobase+i_Offset + 8);
+	/* outl(ui_CommandRegister,devpriv->iobase+i_Offset + 8); */
 	outl(ui_CommandRegister,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 8);
-	//if (i_InterruptFlag == ADDIDATA_DISABLE)
+	/* if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_DISABLE) {
 		do {
 	  /*******************/
 			/*Read the EOC flag */
 	  /*******************/
-			//ui_EOC = inl(devpriv->iobase+i_Offset + 20) & 1;
+			/* ui_EOC = inl(devpriv->iobase+i_Offset + 20) & 1; */
 			ui_EOC = inl(devpriv->iobase +
 				s_BoardInfos[dev->minor].i_Offset + 20) & 1;
 		} while (ui_EOC != 1);
@@ -2254,11 +2247,11 @@
       /**************************************************/
 		/*Read the digital value of the calibration Offset */
       /**************************************************/
-		//data[0] = inl(devpriv->iobase+i_Offset + 28);
+		/* data[0] = inl(devpriv->iobase+i_Offset + 28); */
 		data[0] =
 			inl(devpriv->iobase +
 			s_BoardInfos[dev->minor].i_Offset + 28);
-	}			//if (i_InterruptFlag == ADDIDATA_DISABLE)
+	}			/* if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	return 0;
 }
 
@@ -2271,8 +2264,8 @@
   | Task              : Read CJC calibration gain value
   +----------------------------------------------------------------------------+
   | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-  |                     UINT ui_NoOfChannels    : No Of Channels To read       |
-  |                     UINT *data              : Data Pointer to read status  |
+  |                     unsigned int ui_NoOfChannels    : No Of Channels To read       |
+  |                     unsigned int *data              : Data Pointer to read status  |
   +----------------------------------------------------------------------------+
   | Output Parameters :	--													 |
   |			          data[0]  : CJC calibration gain value
@@ -2283,44 +2276,44 @@
   |			                                                         |
   +----------------------------------------------------------------------------+
 */
-int i_APCI3200_ReadCJCCalGain(struct comedi_device * dev, unsigned int * data)
+int i_APCI3200_ReadCJCCalGain(struct comedi_device *dev, unsigned int *data)
 {
-	UINT ui_EOC = 0;
-	INT ui_CommandRegister = 0;
+	unsigned int ui_EOC = 0;
+	int ui_CommandRegister = 0;
   /*******************************/
 	/* Set the convert timing unit */
   /*******************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36);
+	/* outl(i_ADDIDATAConversionTimeUnit , devpriv->iobase+i_Offset + 36); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTimeUnit,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 36);
   /**************************/
 	/* Set the convert timing */
   /**************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32);
+	/* outl(i_ADDIDATAConversionTime , devpriv->iobase+i_Offset + 32); */
 	outl(s_BoardInfos[dev->minor].i_ADDIDATAConversionTime,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 32);
   /******************************/
 	/*Configure the CJC Conversion */
   /******************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(0x00000400,devpriv->iobase+i_Offset + 4);
+	/* outl(0x00000400,devpriv->iobase+i_Offset + 4); */
 	outl(0x00000400,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 4);
   /*******************************/
 	/*Configure the Gain Conversion */
   /*******************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(0x00040000,devpriv->iobase+i_Offset + 12);
+	/* outl(0x00040000,devpriv->iobase+i_Offset + 12); */
 	outl(0x00040000,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 12);
 
@@ -2331,7 +2324,7 @@
   /*********************************/
 	/*Test if the interrupt is enable */
   /*********************************/
-	//if (i_InterruptFlag == ADDIDATA_ENABLE)
+	/* if (i_InterruptFlag == ADDIDATA_ENABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_ENABLE) {
       /**********************/
 		/*Enable the interrupt */
@@ -2345,30 +2338,30 @@
   /***************************/
 	/*Write the command regiter */
   /***************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(ui_CommandRegister ,devpriv->iobase+i_Offset + 8);
+	/* outl(ui_CommandRegister ,devpriv->iobase+i_Offset + 8); */
 	outl(ui_CommandRegister,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 8);
-	//if (i_InterruptFlag == ADDIDATA_DISABLE)
+	/* if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == ADDIDATA_DISABLE) {
 		do {
 	  /*******************/
 			/*Read the EOC flag */
 	  /*******************/
-			//ui_EOC = inl(devpriv->iobase+i_Offset + 20) & 1;
+			/* ui_EOC = inl(devpriv->iobase+i_Offset + 20) & 1; */
 			ui_EOC = inl(devpriv->iobase +
 				s_BoardInfos[dev->minor].i_Offset + 20) & 1;
 		} while (ui_EOC != 1);
       /************************************************/
 		/*Read the digital value of the calibration Gain */
       /************************************************/
-		//data[0] = inl (devpriv->iobase+i_Offset + 28);
+		/* data[0] = inl (devpriv->iobase+i_Offset + 28); */
 		data[0] =
 			inl(devpriv->iobase +
 			s_BoardInfos[dev->minor].i_Offset + 28);
-	}			//if (i_InterruptFlag == ADDIDATA_DISABLE)
+	}			/* if (i_InterruptFlag == ADDIDATA_DISABLE) */
 	return 0;
 }
 
@@ -2404,33 +2397,33 @@
   +----------------------------------------------------------------------------+
 */
 
-INT i_APCI3200_InsnBits_AnalogInput_Test(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3200_InsnBits_AnalogInput_Test(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Configuration = 0;
-	INT i_Temp;		//,i_TimeUnit;
-	//if(i_Initialised==0)
+	unsigned int ui_Configuration = 0;
+	int i_Temp;		/* ,i_TimeUnit; */
+	/* if(i_Initialised==0) */
 
 	if (s_BoardInfos[dev->minor].i_Initialised == 0) {
 		i_APCI3200_Reset(dev);
 		return -EINVAL;
-	}			//if(i_Initialised==0);
+	}			/* if(i_Initialised==0); */
 	if (data[0] != 0 && data[0] != 1) {
 		printk("\nError in selection of functionality\n");
 		i_APCI3200_Reset(dev);
 		return -EINVAL;
-	}			//if(data[0]!=0 && data[0]!=1)
+	}			/* if(data[0]!=0 && data[0]!=1) */
 
-	if (data[0] == 1)	//Perform Short Circuit TEST
+	if (data[0] == 1)	/* Perform Short Circuit TEST */
 	{
       /**************************/
 		/*Set the short-cicuit bit */
       /**************************/
-		//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+		/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 		while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].
 						i_Offset + 12) >> 19) & 1) !=
 			1) ;
-		//outl((0x00001000 |i_ChannelNo) , devpriv->iobase+i_Offset + 4);
+		/* outl((0x00001000 |i_ChannelNo) , devpriv->iobase+i_Offset + 4); */
 		outl((0x00001000 | s_BoardInfos[dev->minor].i_ChannelNo),
 			devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 			4);
@@ -2439,19 +2432,19 @@
       /*************************/
 		/* i_TimeUnit= i_ADDIDATAConversionTimeUnit;
 		   i_ADDIDATAConversionTimeUnit= 1; */
-		//i_Temp= i_InterruptFlag ;
+		/* i_Temp= i_InterruptFlag ; */
 		i_Temp = s_BoardInfos[dev->minor].i_InterruptFlag;
-		//i_InterruptFlag = ADDIDATA_DISABLE;
+		/* i_InterruptFlag = ADDIDATA_DISABLE; */
 		s_BoardInfos[dev->minor].i_InterruptFlag = ADDIDATA_DISABLE;
 		i_APCI3200_Read1AnalogInputChannel(dev, s, insn, data);
-		//if(i_AutoCalibration == FALSE)
+		/* if(i_AutoCalibration == FALSE) */
 		if (s_BoardInfos[dev->minor].i_AutoCalibration == FALSE) {
-			//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+			/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 			while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].
 							i_Offset +
 							12) >> 19) & 1) != 1) ;
 
-			//outl((0x00001000 |i_ChannelNo) , devpriv->iobase+i_Offset + 4);
+			/* outl((0x00001000 |i_ChannelNo) , devpriv->iobase+i_Offset + 4); */
 			outl((0x00001000 | s_BoardInfos[dev->minor].
 					i_ChannelNo),
 				devpriv->iobase +
@@ -2462,15 +2455,15 @@
 			i_APCI3200_ReadCalibrationGainValue(dev, data);
 		}
 	} else {
-		//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+		/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 		while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].
 						i_Offset + 12) >> 19) & 1) !=
 			1) ;
-		//outl((0x00000800|i_ChannelNo) , devpriv->iobase+i_Offset + 4);
+		/* outl((0x00000800|i_ChannelNo) , devpriv->iobase+i_Offset + 4); */
 		outl((0x00000800 | s_BoardInfos[dev->minor].i_ChannelNo),
 			devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 			4);
-		//ui_Configuration = inl(devpriv->iobase+i_Offset + 0);
+		/* ui_Configuration = inl(devpriv->iobase+i_Offset + 0); */
 		ui_Configuration =
 			inl(devpriv->iobase +
 			s_BoardInfos[dev->minor].i_Offset + 0);
@@ -2479,18 +2472,18 @@
       /*************************/
 		/* i_TimeUnit= i_ADDIDATAConversionTimeUnit;
 		   i_ADDIDATAConversionTimeUnit= 1; */
-		//i_Temp= i_InterruptFlag ;
+		/* i_Temp= i_InterruptFlag ; */
 		i_Temp = s_BoardInfos[dev->minor].i_InterruptFlag;
-		//i_InterruptFlag = ADDIDATA_DISABLE;
+		/* i_InterruptFlag = ADDIDATA_DISABLE; */
 		s_BoardInfos[dev->minor].i_InterruptFlag = ADDIDATA_DISABLE;
 		i_APCI3200_Read1AnalogInputChannel(dev, s, insn, data);
-		//if(i_AutoCalibration == FALSE)
+		/* if(i_AutoCalibration == FALSE) */
 		if (s_BoardInfos[dev->minor].i_AutoCalibration == FALSE) {
-			//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+			/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 			while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].
 							i_Offset +
 							12) >> 19) & 1) != 1) ;
-			//outl((0x00000800|i_ChannelNo) , devpriv->iobase+i_Offset + 4);
+			/* outl((0x00000800|i_ChannelNo) , devpriv->iobase+i_Offset + 4); */
 			outl((0x00000800 | s_BoardInfos[dev->minor].
 					i_ChannelNo),
 				devpriv->iobase +
@@ -2501,9 +2494,9 @@
 			i_APCI3200_ReadCalibrationGainValue(dev, data);
 		}
 	}
-	//i_InterruptFlag=i_Temp ;
+	/* i_InterruptFlag=i_Temp ; */
 	s_BoardInfos[dev->minor].i_InterruptFlag = i_Temp;
-	//printk("\ni_InterruptFlag=%d\n",i_InterruptFlag);
+	/* printk("\ni_InterruptFlag=%d\n",i_InterruptFlag); */
 	return insn->n;
 }
 
@@ -2529,8 +2522,8 @@
   +----------------------------------------------------------------------------+
 */
 
-INT i_APCI3200_InsnWriteReleaseAnalogInput(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3200_InsnWriteReleaseAnalogInput(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	i_APCI3200_Reset(dev);
 	return insn->n;
@@ -2560,23 +2553,23 @@
   +----------------------------------------------------------------------------+
 */
 
-int i_APCI3200_CommandTestAnalogInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+int i_APCI3200_CommandTestAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 
 	int err = 0;
-	int tmp;		// divisor1,divisor2;
-	UINT ui_ConvertTime = 0;
-	UINT ui_ConvertTimeBase = 0;
-	UINT ui_DelayTime = 0;
-	UINT ui_DelayTimeBase = 0;
-	INT i_Triggermode = 0;
-	INT i_TriggerEdge = 0;
-	INT i_NbrOfChannel = 0;
-	INT i_Cpt = 0;
+	int tmp;		/*  divisor1,divisor2; */
+	unsigned int ui_ConvertTime = 0;
+	unsigned int ui_ConvertTimeBase = 0;
+	unsigned int ui_DelayTime = 0;
+	unsigned int ui_DelayTimeBase = 0;
+	int i_Triggermode = 0;
+	int i_TriggerEdge = 0;
+	int i_NbrOfChannel = 0;
+	int i_Cpt = 0;
 	double d_ConversionTimeForAllChannels = 0.0;
 	double d_SCANTimeNewUnit = 0.0;
-	// step 1: make sure trigger sources are trivially valid
+	/*  step 1: make sure trigger sources are trivially valid */
 
 	tmp = cmd->start_src;
 	cmd->start_src &= TRIG_NOW | TRIG_EXT;
@@ -2598,10 +2591,10 @@
 	cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
 	if (!cmd->stop_src || tmp != cmd->stop_src)
 		err++;
-	//if(i_InterruptFlag==0)
+	/* if(i_InterruptFlag==0) */
 	if (s_BoardInfos[dev->minor].i_InterruptFlag == 0) {
 		err++;
-		//          printk("\nThe interrupt should be enabled\n");
+		/*           printk("\nThe interrupt should be enabled\n"); */
 	}
 	if (err) {
 		i_APCI3200_Reset(dev);
@@ -2643,9 +2636,9 @@
 		i_APCI3200_Reset(dev);
 		return 2;
 	}
-	//i_FirstChannel=cmd->chanlist[0];
+	/* i_FirstChannel=cmd->chanlist[0]; */
 	s_BoardInfos[dev->minor].i_FirstChannel = cmd->chanlist[0];
-	//i_LastChannel=cmd->chanlist[1];
+	/* i_LastChannel=cmd->chanlist[1]; */
 	s_BoardInfos[dev->minor].i_LastChannel = cmd->chanlist[1];
 
 	if (cmd->convert_src == TRIG_TIMER) {
@@ -2656,11 +2649,11 @@
 		{
 			printk("\nThe selection of conversion time reload value is in error\n");
 			err++;
-		}		// if (ui_ConvertTime!=20 && ui_ConvertTime!=40 && ui_ConvertTime!=80 && ui_ConvertTime!=160 )
+		}		/*  if (ui_ConvertTime!=20 && ui_ConvertTime!=40 && ui_ConvertTime!=80 && ui_ConvertTime!=160 ) */
 		if (ui_ConvertTimeBase != 2) {
 			printk("\nThe selection of conversion time unit  is in error\n");
 			err++;
-		}		//if(ui_ConvertTimeBase!=2)
+		}		/* if(ui_ConvertTimeBase!=2) */
 	} else {
 		ui_ConvertTime = 0;
 		ui_ConvertTimeBase = 0;
@@ -2668,7 +2661,7 @@
 	if (cmd->scan_begin_src == TRIG_FOLLOW) {
 		ui_DelayTime = 0;
 		ui_DelayTimeBase = 0;
-	}			//if(cmd->scan_begin_src==TRIG_FOLLOW)
+	}			/* if(cmd->scan_begin_src==TRIG_FOLLOW) */
 	else {
 		ui_DelayTime = cmd->scan_begin_arg & 0xFFFF;
 		ui_DelayTimeBase = cmd->scan_begin_arg >> 16;
@@ -2686,7 +2679,7 @@
 		}
 		fpu_begin();
 		d_SCANTimeNewUnit = (double)ui_DelayTime;
-		//i_NbrOfChannel= i_LastChannel-i_FirstChannel + 4;
+		/* i_NbrOfChannel= i_LastChannel-i_FirstChannel + 4; */
 		i_NbrOfChannel =
 			s_BoardInfos[dev->minor].i_LastChannel -
 			s_BoardInfos[dev->minor].i_FirstChannel + 4;
@@ -2736,7 +2729,7 @@
 			err++;
 		}
 		fpu_end();
-	}			//else if(cmd->scan_begin_src==TRIG_FOLLOW)
+	}			/* else if(cmd->scan_begin_src==TRIG_FOLLOW) */
 
 	if (err) {
 		i_APCI3200_Reset(dev);
@@ -2764,13 +2757,13 @@
   +----------------------------------------------------------------------------+
 */
 
-int i_APCI3200_StopCyclicAcquisition(struct comedi_device * dev, struct comedi_subdevice * s)
+int i_APCI3200_StopCyclicAcquisition(struct comedi_device *dev, struct comedi_subdevice *s)
 {
-	UINT ui_Configuration = 0;
-	//i_InterruptFlag=0;
-	//i_Initialised=0;
-	//i_Count=0;
-	//i_Sum=0;
+	unsigned int ui_Configuration = 0;
+	/* i_InterruptFlag=0; */
+	/* i_Initialised=0; */
+	/* i_Count=0; */
+	/* i_Sum=0; */
 	s_BoardInfos[dev->minor].i_InterruptFlag = 0;
 	s_BoardInfos[dev->minor].i_Initialised = 0;
 	s_BoardInfos[dev->minor].i_Count = 0;
@@ -2779,16 +2772,16 @@
   /*******************/
 	/*Read the register */
   /*******************/
-	//ui_Configuration = inl(devpriv->iobase+i_Offset + 8);
+	/* ui_Configuration = inl(devpriv->iobase+i_Offset + 8); */
 	ui_Configuration =
 		inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 8);
   /*****************************/
 	/*Reset the START and IRQ bit */
   /*****************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl((ui_Configuration & 0xFFE7FFFF),devpriv->iobase+i_Offset + 8);
+	/* outl((ui_Configuration & 0xFFE7FFFF),devpriv->iobase+i_Offset + 8); */
 	outl((ui_Configuration & 0xFFE7FFFF),
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 8);
 	return 0;
@@ -2814,52 +2807,52 @@
   +----------------------------------------------------------------------------+
 */
 
-int i_APCI3200_CommandAnalogInput(struct comedi_device * dev, struct comedi_subdevice * s)
+int i_APCI3200_CommandAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
-	UINT ui_Configuration = 0;
-	//INT  i_CurrentSource = 0;
-	UINT ui_Trigger = 0;
-	UINT ui_TriggerEdge = 0;
-	UINT ui_Triggermode = 0;
-	UINT ui_ScanMode = 0;
-	UINT ui_ConvertTime = 0;
-	UINT ui_ConvertTimeBase = 0;
-	UINT ui_DelayTime = 0;
-	UINT ui_DelayTimeBase = 0;
-	UINT ui_DelayMode = 0;
-	//i_FirstChannel=cmd->chanlist[0];
-	//i_LastChannel=cmd->chanlist[1];
+	unsigned int ui_Configuration = 0;
+	/* INT  i_CurrentSource = 0; */
+	unsigned int ui_Trigger = 0;
+	unsigned int ui_TriggerEdge = 0;
+	unsigned int ui_Triggermode = 0;
+	unsigned int ui_ScanMode = 0;
+	unsigned int ui_ConvertTime = 0;
+	unsigned int ui_ConvertTimeBase = 0;
+	unsigned int ui_DelayTime = 0;
+	unsigned int ui_DelayTimeBase = 0;
+	unsigned int ui_DelayMode = 0;
+	/* i_FirstChannel=cmd->chanlist[0]; */
+	/* i_LastChannel=cmd->chanlist[1]; */
 	s_BoardInfos[dev->minor].i_FirstChannel = cmd->chanlist[0];
 	s_BoardInfos[dev->minor].i_LastChannel = cmd->chanlist[1];
 	if (cmd->start_src == TRIG_EXT) {
 		ui_Trigger = 1;
 		ui_TriggerEdge = cmd->start_arg & 0xFFFF;
 		ui_Triggermode = cmd->start_arg >> 16;
-	}			//if(cmd->start_src==TRIG_EXT)
+	}			/* if(cmd->start_src==TRIG_EXT) */
 	else {
 		ui_Trigger = 0;
-	}			//elseif(cmd->start_src==TRIG_EXT)
+	}			/* elseif(cmd->start_src==TRIG_EXT) */
 
 	if (cmd->stop_src == TRIG_COUNT) {
 		ui_ScanMode = 0;
-	}			// if (cmd->stop_src==TRIG_COUNT)
+	}			/*  if (cmd->stop_src==TRIG_COUNT) */
 	else {
 		ui_ScanMode = 2;
-	}			//else if (cmd->stop_src==TRIG_COUNT)
+	}			/* else if (cmd->stop_src==TRIG_COUNT) */
 
 	if (cmd->scan_begin_src == TRIG_FOLLOW) {
 		ui_DelayTime = 0;
 		ui_DelayTimeBase = 0;
 		ui_DelayMode = 0;
-	}			//if(cmd->scan_begin_src==TRIG_FOLLOW)
+	}			/* if(cmd->scan_begin_src==TRIG_FOLLOW) */
 	else {
 		ui_DelayTime = cmd->scan_begin_arg & 0xFFFF;
 		ui_DelayTimeBase = cmd->scan_begin_arg >> 16;
 		ui_DelayMode = 1;
-	}			//else if(cmd->scan_begin_src==TRIG_FOLLOW)
-	//        printk("\nui_DelayTime=%u\n",ui_DelayTime);
-	//        printk("\nui_DelayTimeBase=%u\n",ui_DelayTimeBase);
+	}			/* else if(cmd->scan_begin_src==TRIG_FOLLOW) */
+	/*         printk("\nui_DelayTime=%u\n",ui_DelayTime); */
+	/*         printk("\nui_DelayTimeBase=%u\n",ui_DelayTimeBase); */
 	if (cmd->convert_src == TRIG_TIMER) {
 		ui_ConvertTime = cmd->convert_arg & 0xFFFF;
 		ui_ConvertTimeBase = cmd->convert_arg >> 16;
@@ -2868,34 +2861,34 @@
 		ui_ConvertTimeBase = 0;
 	}
 
-	// if(i_ADDIDATAType ==1 || ((i_ADDIDATAType==2)))
-	//   {
+	/*  if(i_ADDIDATAType ==1 || ((i_ADDIDATAType==2))) */
+	/*    { */
   /**************************************************/
 	/*Read the old configuration of the current source */
   /**************************************************/
-	//ui_Configuration = inl(devpriv->iobase+i_Offset + 12);
+	/* ui_Configuration = inl(devpriv->iobase+i_Offset + 12); */
 	ui_Configuration =
 		inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 12);
   /***********************************************/
 	/*Write the configuration of the current source */
   /***********************************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl((ui_Configuration & 0xFFC00000 ), devpriv->iobase+i_Offset +12);
+	/* outl((ui_Configuration & 0xFFC00000 ), devpriv->iobase+i_Offset +12); */
 	outl((ui_Configuration & 0xFFC00000),
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 12);
-	// }
+	/*  } */
 	ui_Configuration = 0;
-	//     printk("\nfirstchannel=%u\n",i_FirstChannel);
-	//     printk("\nlastchannel=%u\n",i_LastChannel);
-	//     printk("\nui_Trigger=%u\n",ui_Trigger);
-	//     printk("\nui_TriggerEdge=%u\n",ui_TriggerEdge);
-	//     printk("\nui_Triggermode=%u\n",ui_Triggermode);
-	//      printk("\nui_DelayMode=%u\n",ui_DelayMode);
-	//     printk("\nui_ScanMode=%u\n",ui_ScanMode);
+	/*      printk("\nfirstchannel=%u\n",i_FirstChannel); */
+	/*      printk("\nlastchannel=%u\n",i_LastChannel); */
+	/*      printk("\nui_Trigger=%u\n",ui_Trigger); */
+	/*      printk("\nui_TriggerEdge=%u\n",ui_TriggerEdge); */
+	/*      printk("\nui_Triggermode=%u\n",ui_Triggermode); */
+	/*       printk("\nui_DelayMode=%u\n",ui_DelayMode); */
+	/*      printk("\nui_ScanMode=%u\n",ui_ScanMode); */
 
-	//ui_Configuration = i_FirstChannel |(i_LastChannel << 8)| 0x00100000 |
+	/* ui_Configuration = i_FirstChannel |(i_LastChannel << 8)| 0x00100000 | */
 	ui_Configuration =
 		s_BoardInfos[dev->minor].i_FirstChannel | (s_BoardInfos[dev->
 			minor].
@@ -2906,80 +2899,80 @@
   /*************************/
 	/*Write the Configuration */
   /*************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl( ui_Configuration, devpriv->iobase+i_Offset + 0x8);
+	/* outl( ui_Configuration, devpriv->iobase+i_Offset + 0x8); */
 	outl(ui_Configuration,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 0x8);
   /***********************/
 	/*Write the Delay Value */
   /***********************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(ui_DelayTime,devpriv->iobase+i_Offset + 40);
+	/* outl(ui_DelayTime,devpriv->iobase+i_Offset + 40); */
 	outl(ui_DelayTime,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 40);
   /***************************/
 	/*Write the Delay time base */
   /***************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(ui_DelayTimeBase,devpriv->iobase+i_Offset + 44);
+	/* outl(ui_DelayTimeBase,devpriv->iobase+i_Offset + 44); */
 	outl(ui_DelayTimeBase,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 44);
   /*********************************/
 	/*Write the conversion time value */
   /*********************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(ui_ConvertTime,devpriv->iobase+i_Offset + 32);
+	/* outl(ui_ConvertTime,devpriv->iobase+i_Offset + 32); */
 	outl(ui_ConvertTime,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 32);
 
   /********************************/
 	/*Write the conversion time base */
   /********************************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl(ui_ConvertTimeBase,devpriv->iobase+i_Offset + 36);
+	/* outl(ui_ConvertTimeBase,devpriv->iobase+i_Offset + 36); */
 	outl(ui_ConvertTimeBase,
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 36);
   /*******************/
 	/*Read the register */
   /*******************/
-	//ui_Configuration = inl(devpriv->iobase+i_Offset + 4);
+	/* ui_Configuration = inl(devpriv->iobase+i_Offset + 4); */
 	ui_Configuration =
 		inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 4);
   /******************/
 	/*Set the SCAN bit */
   /******************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
 
-	//outl(((ui_Configuration & 0x1E0FF) | 0x00002000),devpriv->iobase+i_Offset + 4);
+	/* outl(((ui_Configuration & 0x1E0FF) | 0x00002000),devpriv->iobase+i_Offset + 4); */
 	outl(((ui_Configuration & 0x1E0FF) | 0x00002000),
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 4);
   /*******************/
 	/*Read the register */
   /*******************/
 	ui_Configuration = 0;
-	//ui_Configuration = inl(devpriv->iobase+i_Offset + 8);
+	/* ui_Configuration = inl(devpriv->iobase+i_Offset + 8); */
 	ui_Configuration =
 		inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 8);
 
   /*******************/
 	/*Set the START bit */
   /*******************/
-	//while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1);
+	/* while (((inl(devpriv->iobase+i_Offset+12)>>19) & 1) != 1); */
 	while (((inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset +
 					12) >> 19) & 1) != 1) ;
-	//outl((ui_Configuration | 0x00080000),devpriv->iobase+i_Offset + 8);
+	/* outl((ui_Configuration | 0x00080000),devpriv->iobase+i_Offset + 8); */
 	outl((ui_Configuration | 0x00080000),
 		devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 8);
 	return 0;
@@ -3001,14 +2994,14 @@
   +----------------------------------------------------------------------------+
 */
 
-int i_APCI3200_Reset(struct comedi_device * dev)
+int i_APCI3200_Reset(struct comedi_device *dev)
 {
-	INT i_Temp;
-	DWORD dw_Dummy;
-	//i_InterruptFlag=0;
-	//i_Initialised==0;
-	//i_Count=0;
-	//i_Sum=0;
+	int i_Temp;
+	unsigned int dw_Dummy;
+	/* i_InterruptFlag=0; */
+	/* i_Initialised==0; */
+	/* i_Count=0; */
+	/* i_Sum=0; */
 
 	s_BoardInfos[dev->minor].i_InterruptFlag = 0;
 	s_BoardInfos[dev->minor].i_Initialised = 0;
@@ -3018,17 +3011,17 @@
 
 	outl(0x83838383, devpriv->i_IobaseAmcc + 0x60);
 
-	// Enable the interrupt for the controler
+	/*  Enable the interrupt for the controler */
 	dw_Dummy = inl(devpriv->i_IobaseAmcc + 0x38);
 	outl(dw_Dummy | 0x2000, devpriv->i_IobaseAmcc + 0x38);
-	outl(0, devpriv->i_IobaseAddon);	//Resets the output
+	outl(0, devpriv->i_IobaseAddon);	/* Resets the output */
   /***************/
 	/*Empty the buffer */
   /**************/
 	for (i_Temp = 0; i_Temp <= 95; i_Temp++) {
-		//ui_InterruptChannelValue[i_Temp]=0;
+		/* ui_InterruptChannelValue[i_Temp]=0; */
 		s_BoardInfos[dev->minor].ui_InterruptChannelValue[i_Temp] = 0;
-	}			//for(i_Temp=0;i_Temp<=95;i_Temp++)
+	}			/* for(i_Temp=0;i_Temp<=95;i_Temp++) */
   /*****************************/
 	/*Reset the START and IRQ bit */
   /*****************************/
@@ -3036,7 +3029,7 @@
 		while (((inl(devpriv->iobase + i_Temp + 12) >> 19) & 1) != 1) ;
 		outl(0, devpriv->iobase + i_Temp + 8);
 		i_Temp = i_Temp + 64;
-	}			//for(i_Temp=0;i_Temp<=192;i_Temp+64)
+	}			/* for(i_Temp=0;i_Temp<=192;i_Temp+64) */
 	return 0;
 }
 
@@ -3060,26 +3053,26 @@
 void v_APCI3200_Interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
-	UINT ui_StatusRegister = 0;
-	UINT ui_ChannelNumber = 0;
-	INT i_CalibrationFlag = 0;
-	INT i_CJCFlag = 0;
-	UINT ui_DummyValue = 0;
-	UINT ui_DigitalTemperature = 0;
-	UINT ui_DigitalInput = 0;
+	unsigned int ui_StatusRegister = 0;
+	unsigned int ui_ChannelNumber = 0;
+	int i_CalibrationFlag = 0;
+	int i_CJCFlag = 0;
+	unsigned int ui_DummyValue = 0;
+	unsigned int ui_DigitalTemperature = 0;
+	unsigned int ui_DigitalInput = 0;
 	int i_ConvertCJCCalibration;
 
-	//BEGIN JK TEST
+	/* BEGIN JK TEST */
 	int i_ReturnValue = 0;
-	//END JK TEST
+	/* END JK TEST */
 
-	//printk ("\n i_ScanType = %i i_ADDIDATAType = %i", s_BoardInfos [dev->minor].i_ScanType, s_BoardInfos [dev->minor].i_ADDIDATAType);
+	/* printk ("\n i_ScanType = %i i_ADDIDATAType = %i", s_BoardInfos [dev->minor].i_ScanType, s_BoardInfos [dev->minor].i_ADDIDATAType); */
 
-	//switch(i_ScanType)
+	/* switch(i_ScanType) */
 	switch (s_BoardInfos[dev->minor].i_ScanType) {
 	case 0:
 	case 1:
-		//switch(i_ADDIDATAType)
+		/* switch(i_ADDIDATAType) */
 		switch (s_BoardInfos[dev->minor].i_ADDIDATAType) {
 		case 0:
 		case 1:
@@ -3087,12 +3080,12 @@
 	  /************************************/
 			/*Read the interrupt status register */
 	  /************************************/
-			//ui_StatusRegister = inl(devpriv->iobase+i_Offset + 16);
+			/* ui_StatusRegister = inl(devpriv->iobase+i_Offset + 16); */
 			ui_StatusRegister =
 				inl(devpriv->iobase +
 				s_BoardInfos[dev->minor].i_Offset + 16);
 			if ((ui_StatusRegister & 0x2) == 0x2) {
-				//i_CalibrationFlag = ((inl(devpriv->iobase+i_Offset + 12) & 0x00060000) >> 17);
+				/* i_CalibrationFlag = ((inl(devpriv->iobase+i_Offset + 12) & 0x00060000) >> 17); */
 				i_CalibrationFlag =
 					((inl(devpriv->iobase +
 							s_BoardInfos[dev->
@@ -3103,12 +3096,12 @@
 	      /*************************/
 				/*Read the channel number */
 	      /*************************/
-				//ui_ChannelNumber = inl(devpriv->iobase+i_Offset + 24);
+				/* ui_ChannelNumber = inl(devpriv->iobase+i_Offset + 24); */
 
 	      /*************************************/
 				/*Read the digital analog input value */
 	      /*************************************/
-				//ui_DigitalInput = inl(devpriv->iobase+i_Offset + 28);
+				/* ui_DigitalInput = inl(devpriv->iobase+i_Offset + 28); */
 				ui_DigitalInput =
 					inl(devpriv->iobase +
 					s_BoardInfos[dev->minor].i_Offset + 28);
@@ -3117,13 +3110,13 @@
 				/* Test if the value read is the channel value */
 	      /***********************************************/
 				if (i_CalibrationFlag == 0) {
-					//ui_InterruptChannelValue[i_Count + 0] = ui_DigitalInput;
+					/* ui_InterruptChannelValue[i_Count + 0] = ui_DigitalInput; */
 					s_BoardInfos[dev->minor].
 						ui_InterruptChannelValue
 						[s_BoardInfos[dev->minor].
 						i_Count + 0] = ui_DigitalInput;
 
-					//Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+					/* Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 					/*
 					   printk("\n 1 - i_APCI3200_GetChannelCalibrationValue (dev, s_BoardInfos %i", ui_ChannelNumber);
 					   i_APCI3200_GetChannelCalibrationValue (dev, s_BoardInfos [dev->minor].ui_Channel_num,
@@ -3131,14 +3124,14 @@
 					   &s_BoardInfos [dev->minor].ui_InterruptChannelValue[s_BoardInfos [dev->minor].i_Count + 7],
 					   &s_BoardInfos [dev->minor].ui_InterruptChannelValue[s_BoardInfos [dev->minor].i_Count + 8]);
 					 */
-					//End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+					/* End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
 		  /******************************************************/
 					/*Start the conversion of the calibration offset value */
 		  /******************************************************/
 					i_APCI3200_ReadCalibrationOffsetValue
 						(dev, &ui_DummyValue);
-				}	//if (i_CalibrationFlag == 0)
+				}	/* if (i_CalibrationFlag == 0) */
 	      /**********************************************************/
 				/* Test if the value read is the calibration offset value */
 	      /**********************************************************/
@@ -3149,7 +3142,7 @@
 					/* Save the value */
 		  /******************/
 
-					//ui_InterruptChannelValue[i_Count + 1] = ui_DigitalInput;
+					/* ui_InterruptChannelValue[i_Count + 1] = ui_DigitalInput; */
 					s_BoardInfos[dev->minor].
 						ui_InterruptChannelValue
 						[s_BoardInfos[dev->minor].
@@ -3160,7 +3153,7 @@
 		  /******************************************************/
 					i_APCI3200_ReadCalibrationGainValue(dev,
 						&ui_DummyValue);
-				}	//if (i_CalibrationFlag == 1)
+				}	/* if (i_CalibrationFlag == 1) */
 	      /******************************************************/
 				/*Test if the value read is the calibration gain value */
 	      /******************************************************/
@@ -3170,48 +3163,48 @@
 		  /****************/
 					/*Save the value */
 		  /****************/
-					//ui_InterruptChannelValue[i_Count + 2] = ui_DigitalInput;
+					/* ui_InterruptChannelValue[i_Count + 2] = ui_DigitalInput; */
 					s_BoardInfos[dev->minor].
 						ui_InterruptChannelValue
 						[s_BoardInfos[dev->minor].
 						i_Count + 2] = ui_DigitalInput;
-					//if(i_ScanType==1)
+					/* if(i_ScanType==1) */
 					if (s_BoardInfos[dev->minor].
 						i_ScanType == 1) {
 
-						//i_InterruptFlag=0;
+						/* i_InterruptFlag=0; */
 						s_BoardInfos[dev->minor].
 							i_InterruptFlag = 0;
-						//i_Count=i_Count + 6;
-						//Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
-						//s_BoardInfos [dev->minor].i_Count=s_BoardInfos [dev->minor].i_Count + 6;
+						/* i_Count=i_Count + 6; */
+						/* Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
+						/* s_BoardInfos [dev->minor].i_Count=s_BoardInfos [dev->minor].i_Count + 6; */
 						s_BoardInfos[dev->minor].
 							i_Count =
 							s_BoardInfos[dev->
 							minor].i_Count + 9;
-						//End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
-					}	//if(i_ScanType==1)
+						/* End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
+					}	/* if(i_ScanType==1) */
 					else {
-						//i_Count=0;
+						/* i_Count=0; */
 						s_BoardInfos[dev->minor].
 							i_Count = 0;
-					}	//elseif(i_ScanType==1)
-					//if(i_ScanType!=1)
+					}	/* elseif(i_ScanType==1) */
+					/* if(i_ScanType!=1) */
 					if (s_BoardInfos[dev->minor].
 						i_ScanType != 1) {
-						i_ReturnValue = send_sig(SIGIO, devpriv->tsk_Current, 0);	// send signal to the sample
-					}	//if(i_ScanType!=1)
+						i_ReturnValue = send_sig(SIGIO, devpriv->tsk_Current, 0);	/*  send signal to the sample */
+					}	/* if(i_ScanType!=1) */
 					else {
-						//if(i_ChannelCount==i_Sum)
+						/* if(i_ChannelCount==i_Sum) */
 						if (s_BoardInfos[dev->minor].
 							i_ChannelCount ==
 							s_BoardInfos[dev->
 								minor].i_Sum) {
-							send_sig(SIGIO, devpriv->tsk_Current, 0);	// send signal to the sample
+							send_sig(SIGIO, devpriv->tsk_Current, 0);	/*  send signal to the sample */
 						}
-					}	//if(i_ScanType!=1)
-				}	//if (i_CalibrationFlag == 2)
-			}	// if ((ui_StatusRegister & 0x2) == 0x2)
+					}	/* if(i_ScanType!=1) */
+				}	/* if (i_CalibrationFlag == 2) */
+			}	/*  if ((ui_StatusRegister & 0x2) == 0x2) */
 
 			break;
 
@@ -3220,7 +3213,7 @@
 			/*Read the interrupt status register */
 	  /************************************/
 
-			//ui_StatusRegister = inl(devpriv->iobase+i_Offset + 16);
+			/* ui_StatusRegister = inl(devpriv->iobase+i_Offset + 16); */
 			ui_StatusRegister =
 				inl(devpriv->iobase +
 				s_BoardInfos[dev->minor].i_Offset + 16);
@@ -3230,7 +3223,7 @@
 
 			if ((ui_StatusRegister & 0x2) == 0x2) {
 
-				//i_CJCFlag = ((inl(devpriv->iobase+i_Offset + 4) & 0x00000400) >> 10);
+				/* i_CJCFlag = ((inl(devpriv->iobase+i_Offset + 4) & 0x00000400) >> 10); */
 				i_CJCFlag =
 					((inl(devpriv->iobase +
 							s_BoardInfos[dev->
@@ -3238,7 +3231,7 @@
 							i_Offset +
 							4) & 0x00000400) >> 10);
 
-				//i_CalibrationFlag = ((inl(devpriv->iobase+i_Offset + 12) & 0x00060000) >> 17);
+				/* i_CalibrationFlag = ((inl(devpriv->iobase+i_Offset + 12) & 0x00060000) >> 17); */
 				i_CalibrationFlag =
 					((inl(devpriv->iobase +
 							s_BoardInfos[dev->
@@ -3251,19 +3244,19 @@
 				/*Read the channel number */
 	      /*************************/
 
-				//ui_ChannelNumber = inl(devpriv->iobase+i_Offset + 24);
+				/* ui_ChannelNumber = inl(devpriv->iobase+i_Offset + 24); */
 				ui_ChannelNumber =
 					inl(devpriv->iobase +
 					s_BoardInfos[dev->minor].i_Offset + 24);
-				//Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+				/* Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 				s_BoardInfos[dev->minor].ui_Channel_num =
 					ui_ChannelNumber;
-				//End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+				/* End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
 	      /************************************/
 				/*Read the digital temperature value */
 	      /************************************/
-				//ui_DigitalTemperature = inl(devpriv->iobase+i_Offset + 28);
+				/* ui_DigitalTemperature = inl(devpriv->iobase+i_Offset + 28); */
 				ui_DigitalTemperature =
 					inl(devpriv->iobase +
 					s_BoardInfos[dev->minor].i_Offset + 28);
@@ -3274,7 +3267,7 @@
 
 				if ((i_CalibrationFlag == 0)
 					&& (i_CJCFlag == 0)) {
-					//ui_InterruptChannelValue[i_Count + 0]=ui_DigitalTemperature;
+					/* ui_InterruptChannelValue[i_Count + 0]=ui_DigitalTemperature; */
 					s_BoardInfos[dev->minor].
 						ui_InterruptChannelValue
 						[s_BoardInfos[dev->minor].
@@ -3287,7 +3280,7 @@
 					i_APCI3200_ReadCJCValue(dev,
 						&ui_DummyValue);
 
-				}	//if ((i_CalibrationFlag == 0) && (i_CJCFlag == 0))
+				}	/* if ((i_CalibrationFlag == 0) && (i_CJCFlag == 0)) */
 
 		 /*****************************************/
 				/*Test if the value read is the CJC value */
@@ -3295,7 +3288,7 @@
 
 				if ((i_CJCFlag == 1)
 					&& (i_CalibrationFlag == 0)) {
-					//ui_InterruptChannelValue[i_Count + 3]=ui_DigitalTemperature;
+					/* ui_InterruptChannelValue[i_Count + 3]=ui_DigitalTemperature; */
 					s_BoardInfos[dev->minor].
 						ui_InterruptChannelValue
 						[s_BoardInfos[dev->minor].
@@ -3307,7 +3300,7 @@
 		  /******************************************************/
 					i_APCI3200_ReadCalibrationOffsetValue
 						(dev, &ui_DummyValue);
-				}	// if ((i_CJCFlag == 1) && (i_CalibrationFlag == 0))
+				}	/*  if ((i_CJCFlag == 1) && (i_CalibrationFlag == 0)) */
 
 		 /********************************************************/
 				/*Test if the value read is the calibration offset value */
@@ -3315,7 +3308,7 @@
 
 				if ((i_CalibrationFlag == 1)
 					&& (i_CJCFlag == 0)) {
-					//ui_InterruptChannelValue[i_Count + 1]=ui_DigitalTemperature;
+					/* ui_InterruptChannelValue[i_Count + 1]=ui_DigitalTemperature; */
 					s_BoardInfos[dev->minor].
 						ui_InterruptChannelValue
 						[s_BoardInfos[dev->minor].
@@ -3328,7 +3321,7 @@
 					i_APCI3200_ReadCalibrationGainValue(dev,
 						&ui_DummyValue);
 
-				}	//if ((i_CalibrationFlag == 1) && (i_CJCFlag == 0))
+				}	/* if ((i_CalibrationFlag == 1) && (i_CJCFlag == 0)) */
 
 	      /******************************************************/
 				/*Test if the value read is the calibration gain value */
@@ -3336,7 +3329,7 @@
 
 				if ((i_CalibrationFlag == 2)
 					&& (i_CJCFlag == 0)) {
-					//ui_InterruptChannelValue[i_Count + 2]=ui_DigitalTemperature;
+					/* ui_InterruptChannelValue[i_Count + 2]=ui_DigitalTemperature; */
 					s_BoardInfos[dev->minor].
 						ui_InterruptChannelValue
 						[s_BoardInfos[dev->minor].
@@ -3349,15 +3342,15 @@
 
 					/*Test if the polarity is the same */
 		  /**********************************/
-					//if(i_CJCPolarity!=i_ADDIDATAPolarity)
+					/* if(i_CJCPolarity!=i_ADDIDATAPolarity) */
 					if (s_BoardInfos[dev->minor].
 						i_CJCPolarity !=
 						s_BoardInfos[dev->minor].
 						i_ADDIDATAPolarity) {
 						i_ConvertCJCCalibration = 1;
-					}	//if(i_CJCPolarity!=i_ADDIDATAPolarity)
+					}	/* if(i_CJCPolarity!=i_ADDIDATAPolarity) */
 					else {
-						//if(i_CJCGain==i_ADDIDATAGain)
+						/* if(i_CJCGain==i_ADDIDATAGain) */
 						if (s_BoardInfos[dev->minor].
 							i_CJCGain ==
 							s_BoardInfos[dev->
@@ -3365,12 +3358,12 @@
 							i_ADDIDATAGain) {
 							i_ConvertCJCCalibration
 								= 0;
-						}	//if(i_CJCGain==i_ADDIDATAGain)
+						}	/* if(i_CJCGain==i_ADDIDATAGain) */
 						else {
 							i_ConvertCJCCalibration
 								= 1;
-						}	//elseif(i_CJCGain==i_ADDIDATAGain)
-					}	//elseif(i_CJCPolarity!=i_ADDIDATAPolarity)
+						}	/* elseif(i_CJCGain==i_ADDIDATAGain) */
+					}	/* elseif(i_CJCPolarity!=i_ADDIDATAPolarity) */
 					if (i_ConvertCJCCalibration == 1) {
 		      /****************************************************************/
 						/*Start the conversion of the calibration gain value for the CJC */
@@ -3378,10 +3371,10 @@
 						i_APCI3200_ReadCJCCalOffset(dev,
 							&ui_DummyValue);
 
-					}	//if(i_ConvertCJCCalibration==1)
+					}	/* if(i_ConvertCJCCalibration==1) */
 					else {
-						//ui_InterruptChannelValue[i_Count + 4]=0;
-						//ui_InterruptChannelValue[i_Count + 5]=0;
+						/* ui_InterruptChannelValue[i_Count + 4]=0; */
+						/* ui_InterruptChannelValue[i_Count + 5]=0; */
 						s_BoardInfos[dev->minor].
 							ui_InterruptChannelValue
 							[s_BoardInfos[dev->
@@ -3392,8 +3385,8 @@
 							[s_BoardInfos[dev->
 								minor].i_Count +
 							5] = 0;
-					}	//elseif(i_ConvertCJCCalibration==1)
-				}	//else if ((i_CalibrationFlag == 2) && (i_CJCFlag == 0))
+					}	/* elseif(i_ConvertCJCCalibration==1) */
+				}	/* else if ((i_CalibrationFlag == 2) && (i_CJCFlag == 0)) */
 
 		 /********************************************************************/
 				/*Test if the value read is the calibration offset value for the CJC */
@@ -3401,7 +3394,7 @@
 
 				if ((i_CalibrationFlag == 1)
 					&& (i_CJCFlag == 1)) {
-					//ui_InterruptChannelValue[i_Count + 4]=ui_DigitalTemperature;
+					/* ui_InterruptChannelValue[i_Count + 4]=ui_DigitalTemperature; */
 					s_BoardInfos[dev->minor].
 						ui_InterruptChannelValue
 						[s_BoardInfos[dev->minor].
@@ -3414,7 +3407,7 @@
 					i_APCI3200_ReadCJCCalGain(dev,
 						&ui_DummyValue);
 
-				}	//if ((i_CalibrationFlag == 1) && (i_CJCFlag == 1))
+				}	/* if ((i_CalibrationFlag == 1) && (i_CJCFlag == 1)) */
 
 	      /******************************************************************/
 				/*Test if the value read is the calibration gain value for the CJC */
@@ -3422,61 +3415,61 @@
 
 				if ((i_CalibrationFlag == 2)
 					&& (i_CJCFlag == 1)) {
-					//ui_InterruptChannelValue[i_Count + 5]=ui_DigitalTemperature;
+					/* ui_InterruptChannelValue[i_Count + 5]=ui_DigitalTemperature; */
 					s_BoardInfos[dev->minor].
 						ui_InterruptChannelValue
 						[s_BoardInfos[dev->minor].
 						i_Count + 5] =
 						ui_DigitalTemperature;
 
-					//if(i_ScanType==1)
+					/* if(i_ScanType==1) */
 					if (s_BoardInfos[dev->minor].
 						i_ScanType == 1) {
 
-						//i_InterruptFlag=0;
+						/* i_InterruptFlag=0; */
 						s_BoardInfos[dev->minor].
 							i_InterruptFlag = 0;
-						//i_Count=i_Count + 6;
-						//Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
-						//s_BoardInfos [dev->minor].i_Count=s_BoardInfos [dev->minor].i_Count + 6;
+						/* i_Count=i_Count + 6; */
+						/* Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
+						/* s_BoardInfos [dev->minor].i_Count=s_BoardInfos [dev->minor].i_Count + 6; */
 						s_BoardInfos[dev->minor].
 							i_Count =
 							s_BoardInfos[dev->
 							minor].i_Count + 9;
-						//End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
-					}	//if(i_ScanType==1)
+						/* End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
+					}	/* if(i_ScanType==1) */
 					else {
-						//i_Count=0;
+						/* i_Count=0; */
 						s_BoardInfos[dev->minor].
 							i_Count = 0;
-					}	//elseif(i_ScanType==1)
+					}	/* elseif(i_ScanType==1) */
 
-					//if(i_ScanType!=1)
+					/* if(i_ScanType!=1) */
 					if (s_BoardInfos[dev->minor].
 						i_ScanType != 1) {
-						send_sig(SIGIO, devpriv->tsk_Current, 0);	// send signal to the sample
-					}	//if(i_ScanType!=1)
+						send_sig(SIGIO, devpriv->tsk_Current, 0);	/*  send signal to the sample */
+					}	/* if(i_ScanType!=1) */
 					else {
-						//if(i_ChannelCount==i_Sum)
+						/* if(i_ChannelCount==i_Sum) */
 						if (s_BoardInfos[dev->minor].
 							i_ChannelCount ==
 							s_BoardInfos[dev->
 								minor].i_Sum) {
-							send_sig(SIGIO, devpriv->tsk_Current, 0);	// send signal to the sample
+							send_sig(SIGIO, devpriv->tsk_Current, 0);	/*  send signal to the sample */
 
-						}	//if(i_ChannelCount==i_Sum)
-					}	//else if(i_ScanType!=1)
-				}	//if ((i_CalibrationFlag == 2) && (i_CJCFlag == 1))
+						}	/* if(i_ChannelCount==i_Sum) */
+					}	/* else if(i_ScanType!=1) */
+				}	/* if ((i_CalibrationFlag == 2) && (i_CJCFlag == 1)) */
 
-			}	//else if ((ui_StatusRegister & 0x2) == 0x2)
+			}	/* else if ((ui_StatusRegister & 0x2) == 0x2) */
 			break;
-		}		//switch(i_ADDIDATAType)
+		}		/* switch(i_ADDIDATAType) */
 		break;
 	case 2:
 	case 3:
 		i_APCI3200_InterruptHandleEos(dev);
 		break;
-	}			//switch(i_ScanType)
+	}			/* switch(i_ScanType) */
 	return;
 }
 
@@ -3499,22 +3492,22 @@
   |                    													     |
   +----------------------------------------------------------------------------+
 */
-int i_APCI3200_InterruptHandleEos(struct comedi_device * dev)
+int i_APCI3200_InterruptHandleEos(struct comedi_device *dev)
 {
-	UINT ui_StatusRegister = 0;
+	unsigned int ui_StatusRegister = 0;
 	struct comedi_subdevice *s = dev->subdevices + 0;
 
-	//BEGIN JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
-	//comedi_async *async = s->async;
-	//UINT *data;
-	//data=async->data+async->buf_int_ptr;//new samples added from here onwards
+	/* BEGIN JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
+	/* comedi_async *async = s->async; */
+	/* UINT *data; */
+	/* data=async->data+async->buf_int_ptr;//new samples added from here onwards */
 	int n = 0, i = 0;
-	//END JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
+	/* END JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
 
   /************************************/
 	/*Read the interrupt status register */
   /************************************/
-	//ui_StatusRegister = inl(devpriv->iobase+i_Offset + 16);
+	/* ui_StatusRegister = inl(devpriv->iobase+i_Offset + 16); */
 	ui_StatusRegister =
 		inl(devpriv->iobase + s_BoardInfos[dev->minor].i_Offset + 16);
 
@@ -3526,33 +3519,33 @@
       /*************************/
 		/*Read the channel number */
       /*************************/
-		//ui_ChannelNumber = inl(devpriv->iobase+i_Offset + 24);
-		//BEGIN JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
-		//This value is not used
-		//ui_ChannelNumber = inl(devpriv->iobase+s_BoardInfos [dev->minor].i_Offset + 24);
+		/* ui_ChannelNumber = inl(devpriv->iobase+i_Offset + 24); */
+		/* BEGIN JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
+		/* This value is not used */
+		/* ui_ChannelNumber = inl(devpriv->iobase+s_BoardInfos [dev->minor].i_Offset + 24); */
 		s->async->events = 0;
-		//END JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
+		/* END JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
 
       /*************************************/
 		/*Read the digital Analog Input value */
       /*************************************/
 
-		//data[i_Count] = inl(devpriv->iobase+i_Offset + 28);
-		//Begin JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
-		//data[s_BoardInfos [dev->minor].i_Count] = inl(devpriv->iobase+s_BoardInfos [dev->minor].i_Offset + 28);
+		/* data[i_Count] = inl(devpriv->iobase+i_Offset + 28); */
+		/* Begin JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
+		/* data[s_BoardInfos [dev->minor].i_Count] = inl(devpriv->iobase+s_BoardInfos [dev->minor].i_Offset + 28); */
 		s_BoardInfos[dev->minor].ui_ScanValueArray[s_BoardInfos[dev->
 				minor].i_Count] =
 			inl(devpriv->iobase +
 			s_BoardInfos[dev->minor].i_Offset + 28);
-		//End JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
+		/* End JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
 
-		//if((i_Count == (i_LastChannel-i_FirstChannel+3)))
+		/* if((i_Count == (i_LastChannel-i_FirstChannel+3))) */
 		if ((s_BoardInfos[dev->minor].i_Count ==
 				(s_BoardInfos[dev->minor].i_LastChannel -
 					s_BoardInfos[dev->minor].
 					i_FirstChannel + 3))) {
 
-			//Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+			/* Begin JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 			s_BoardInfos[dev->minor].i_Count++;
 
 			for (i = s_BoardInfos[dev->minor].i_FirstChannel;
@@ -3582,61 +3575,61 @@
 							* 3) + 2]);
 			}
 
-			//End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+			/* End JK 22.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
-			//i_Count=-1;
+			/* i_Count=-1; */
 
 			s_BoardInfos[dev->minor].i_Count = -1;
 
-			//async->buf_int_count+=(i_LastChannel-i_FirstChannel+4)*sizeof(UINT);
-			//Begin JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
-			//async->buf_int_count+=(s_BoardInfos [dev->minor].i_LastChannel-s_BoardInfos [dev->minor].i_FirstChannel+4)*sizeof(UINT);
-			//End JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
-			//async->buf_int_ptr+=(i_LastChannel-i_FirstChannel+4)*sizeof(UINT);
-			//Begin JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
-			//async->buf_int_ptr+=(s_BoardInfos [dev->minor].i_LastChannel-s_BoardInfos [dev->minor].i_FirstChannel+4)*sizeof(UINT);
-			//comedi_eos(dev,s);
+			/* async->buf_int_count+=(i_LastChannel-i_FirstChannel+4)*sizeof(unsigned int); */
+			/* Begin JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
+			/* async->buf_int_count+=(s_BoardInfos [dev->minor].i_LastChannel-s_BoardInfos [dev->minor].i_FirstChannel+4)*sizeof(unsigned int); */
+			/* End JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
+			/* async->buf_int_ptr+=(i_LastChannel-i_FirstChannel+4)*sizeof(unsigned int); */
+			/* Begin JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
+			/* async->buf_int_ptr+=(s_BoardInfos [dev->minor].i_LastChannel-s_BoardInfos [dev->minor].i_FirstChannel+4)*sizeof(unsigned int); */
+			/* comedi_eos(dev,s); */
 
-			// Set the event type (Comedi Buffer End Of Scan)
+			/*  Set the event type (Comedi Buffer End Of Scan) */
 			s->async->events |= COMEDI_CB_EOS;
 
-			// Test if enougth memory is available and allocate it for 7 values
-			//n = comedi_buf_write_alloc(s->async, 7*sizeof(unsigned int));
+			/*  Test if enougth memory is available and allocate it for 7 values */
+			/* n = comedi_buf_write_alloc(s->async, 7*sizeof(unsigned int)); */
 			n = comedi_buf_write_alloc(s->async,
 				(7 + 12) * sizeof(unsigned int));
 
-			// If not enougth memory available, event is set to Comedi Buffer Errror
+			/*  If not enougth memory available, event is set to Comedi Buffer Errror */
 			if (n > ((7 + 12) * sizeof(unsigned int))) {
 				printk("\ncomedi_buf_write_alloc n = %i", n);
 				s->async->events |= COMEDI_CB_ERROR;
 			}
-			// Write all 7 scan values in the comedi buffer
+			/*  Write all 7 scan values in the comedi buffer */
 			comedi_buf_memcpy_to(s->async, 0,
 				(unsigned int *) s_BoardInfos[dev->minor].
 				ui_ScanValueArray, (7 + 12) * sizeof(unsigned int));
 
-			// Update comedi buffer pinters indexes
+			/*  Update comedi buffer pinters indexes */
 			comedi_buf_write_free(s->async,
 				(7 + 12) * sizeof(unsigned int));
 
-			// Send events
+			/*  Send events */
 			comedi_event(dev, s);
-			//End JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
+			/* End JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
 
-			//BEGIN JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
-			//
-			//if (s->async->buf_int_ptr>=s->async->data_len) //  for buffer rool over
-			//  {
-			//    /* buffer rollover */
-			//    s->async->buf_int_ptr=0;
-			//    comedi_eobuf(dev,s);
-			//  }
-			//End JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
+			/* BEGIN JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
+			/*  */
+			/* if (s->async->buf_int_ptr>=s->async->data_len) //  for buffer rool over */
+			/*   { */
+			/*     /* buffer rollover */ */
+			/*     s->async->buf_int_ptr=0; */
+			/*     comedi_eobuf(dev,s); */
+			/*   } */
+			/* End JK 18.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
 		}
-		//i_Count++;
+		/* i_Count++; */
 		s_BoardInfos[dev->minor].i_Count++;
 	}
-	//i_InterruptFlag=0;
+	/* i_InterruptFlag=0; */
 	s_BoardInfos[dev->minor].i_InterruptFlag = 0;
 	return 0;
 }
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3200.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3200.h
index a6f57f5..f3e7ebf 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3200.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3200.h
@@ -15,26 +15,26 @@
  * any later version.
  */
 
-// Card Specific information
+/* Card Specific information */
 #define APCI3200_BOARD_VENDOR_ID                 0x15B8
-//#define APCI3200_ADDRESS_RANGE                   264
+/* #define APCI3200_ADDRESS_RANGE                   264 */
 
 int MODULE_NO;
 struct {
-	INT i_Gain;
-	INT i_Polarity;
-	INT i_OffsetRange;
-	INT i_Coupling;
-	INT i_SingleDiff;
-	INT i_AutoCalibration;
-	UINT ui_ReloadValue;
-	UINT ui_TimeUnitReloadVal;
-	INT i_Interrupt;
-	INT i_ModuleSelection;
+	int i_Gain;
+	int i_Polarity;
+	int i_OffsetRange;
+	int i_Coupling;
+	int i_SingleDiff;
+	int i_AutoCalibration;
+	unsigned int ui_ReloadValue;
+	unsigned int ui_TimeUnitReloadVal;
+	int i_Interrupt;
+	int i_ModuleSelection;
 } Config_Parameters_Module1, Config_Parameters_Module2,
     Config_Parameters_Module3, Config_Parameters_Module4;
 
-//ANALOG INPUT RANGE
+/* ANALOG INPUT RANGE */
 static const struct comedi_lrange range_apci3200_ai = { 8, {
 						     BIP_RANGE(10),
 						     BIP_RANGE(5),
@@ -55,7 +55,7 @@
 						     }
 };
 
-//Analog Input related Defines
+/* Analog Input related Defines */
 #define APCI3200_AI_OFFSET_GAIN                  0
 #define APCI3200_AI_SC_TEST                      4
 #define APCI3200_AI_IRQ                          8
@@ -89,98 +89,102 @@
 #define ADDIDATA_UNIPOLAR                        1
 #define ADDIDATA_BIPOLAR                         2
 
-//BEGIN JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+/* BEGIN JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 #define MAX_MODULE				4
-//END JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+/* END JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
-typedef struct {
-	ULONG ul_NumberOfValue;
-	ULONG *pul_ResistanceValue;
-	ULONG *pul_TemperatureValue;
-} str_ADDIDATA_RTDStruct, *pstr_ADDIDATA_RTDStruct;
+struct str_ADDIDATA_RTDStruct {
+	unsigned int ul_NumberOfValue;
+	unsigned int *pul_ResistanceValue;
+	unsigned int *pul_TemperatureValue;
+};
 
-//BEGIN JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
-typedef struct {
-	// Begin JK 05/08/2003 change for Linux
+/* BEGIN JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
+struct str_Module {
+
+	/*  Begin JK 05/08/2003 change for Linux */
 	unsigned long ul_CurrentSourceCJC;
 	unsigned long ul_CurrentSource[5];
-	// End JK 05/08/2003 change for Linux
+	/*  End JK 05/08/2003 change for Linux */
 
-	// Begin CG 15/02/02 Rev 1.0 -> Rev 1.1 : Add Header Type 1
-	unsigned long ul_GainFactor[8];	// Gain Factor
+	/*  Begin CG 15/02/02 Rev 1.0 -> Rev 1.1 : Add Header Type 1 */
+	unsigned long ul_GainFactor[8];	/*  Gain Factor */
 	unsigned int w_GainValue[10];
-	// End CG 15/02/02 Rev 1.0 -> Rev 1.1 : Add Header Type 1
-} str_Module;
-//END JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
+	/*  End CG 15/02/02 Rev 1.0 -> Rev 1.1 : Add Header Type 1 */
+};
 
-//BEGIN JK 06.07.04: Management of sevrals boards
-typedef struct {
-	INT i_CJCAvailable;
-	INT i_CJCPolarity;
-	INT i_CJCGain;
-	INT i_InterruptFlag;
-	INT i_ADDIDATAPolarity;
-	INT i_ADDIDATAGain;
-	INT i_AutoCalibration;
-	INT i_ADDIDATAConversionTime;
-	INT i_ADDIDATAConversionTimeUnit;
-	INT i_ADDIDATAType;
-	INT i_ChannelNo;
-	INT i_ChannelCount;
-	INT i_ScanType;
-	INT i_FirstChannel;
-	INT i_LastChannel;
-	INT i_Sum;
-	INT i_Offset;
-	UINT ui_Channel_num;
-	INT i_Count;
-	INT i_Initialised;
-	//UINT ui_InterruptChannelValue[96]; //Buffer
-	UINT ui_InterruptChannelValue[144];	//Buffer
-	BYTE b_StructInitialized;
-	//Begin JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
-	unsigned int ui_ScanValueArray[7 + 12];	// 7 is the maximal number of channels
-	//End JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68
+/* END JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
 
-	//Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
-	INT i_ConnectionType;
-	INT i_NbrOfModule;
-	str_Module s_Module[MAX_MODULE];
-	//End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values
-} str_BoardInfos;
-//END JK 06.07.04: Management of sevrals boards
+/* BEGIN JK 06.07.04: Management of sevrals boards */
+struct str_BoardInfos {
 
-// Hardware Layer  functions for Apci3200
+	int i_CJCAvailable;
+	int i_CJCPolarity;
+	int i_CJCGain;
+	int i_InterruptFlag;
+	int i_ADDIDATAPolarity;
+	int i_ADDIDATAGain;
+	int i_AutoCalibration;
+	int i_ADDIDATAConversionTime;
+	int i_ADDIDATAConversionTimeUnit;
+	int i_ADDIDATAType;
+	int i_ChannelNo;
+	int i_ChannelCount;
+	int i_ScanType;
+	int i_FirstChannel;
+	int i_LastChannel;
+	int i_Sum;
+	int i_Offset;
+	unsigned int ui_Channel_num;
+	int i_Count;
+	int i_Initialised;
+	/* UINT ui_InterruptChannelValue[96]; //Buffer */
+	unsigned int ui_InterruptChannelValue[144];	/* Buffer */
+	unsigned char b_StructInitialized;
+	/* Begin JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
+	unsigned int ui_ScanValueArray[7 + 12];	/*  7 is the maximal number of channels */
+	/* End JK 19.10.2004: APCI-3200 Driver update 0.7.57 -> 0.7.68 */
 
-//AI
+	/* Begin JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
+	int i_ConnectionType;
+	int i_NbrOfModule;
+	struct str_Module s_Module[MAX_MODULE];
+	/* End JK 21.10.2004: APCI-3200 / APCI-3300 Reading of EEPROM values */
+};
 
-INT i_APCI3200_ConfigAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+/* END JK 06.07.04: Management of sevrals boards */
+
+/* Hardware Layer  functions for Apci3200 */
+
+/* AI */
+
+int i_APCI3200_ConfigAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
-INT i_APCI3200_ReadAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI3200_ReadAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
 			       struct comedi_insn *insn, unsigned int *data);
-INT i_APCI3200_InsnWriteReleaseAnalogInput(struct comedi_device *dev,
+int i_APCI3200_InsnWriteReleaseAnalogInput(struct comedi_device *dev,
 					   struct comedi_subdevice *s,
 					   struct comedi_insn *insn, unsigned int *data);
-INT i_APCI3200_InsnBits_AnalogInput_Test(struct comedi_device *dev,
+int i_APCI3200_InsnBits_AnalogInput_Test(struct comedi_device *dev,
 					 struct comedi_subdevice *s,
 					 struct comedi_insn *insn, unsigned int *data);
-INT i_APCI3200_StopCyclicAcquisition(struct comedi_device *dev, struct comedi_subdevice *s);
-INT i_APCI3200_InterruptHandleEos(struct comedi_device *dev);
-INT i_APCI3200_CommandTestAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI3200_StopCyclicAcquisition(struct comedi_device *dev, struct comedi_subdevice *s);
+int i_APCI3200_InterruptHandleEos(struct comedi_device *dev);
+int i_APCI3200_CommandTestAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				      struct comedi_cmd *cmd);
-INT i_APCI3200_CommandAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s);
-INT i_APCI3200_ReadDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI3200_CommandAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s);
+int i_APCI3200_ReadDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				struct comedi_insn *insn, unsigned int *data);
-//Interrupt
+/* Interrupt */
 void v_APCI3200_Interrupt(int irq, void *d);
 int i_APCI3200_InterruptHandleEos(struct comedi_device *dev);
-//Reset functions
-INT i_APCI3200_Reset(struct comedi_device *dev);
+/* Reset functions */
+int i_APCI3200_Reset(struct comedi_device *dev);
 
 int i_APCI3200_ReadCJCCalOffset(struct comedi_device *dev, unsigned int *data);
 int i_APCI3200_ReadCJCValue(struct comedi_device *dev, unsigned int *data);
-int i_APCI3200_ReadCalibrationGainValue(struct comedi_device *dev, UINT *data);
-int i_APCI3200_ReadCalibrationOffsetValue(struct comedi_device *dev, UINT *data);
+int i_APCI3200_ReadCalibrationGainValue(struct comedi_device *dev, unsigned int *data);
+int i_APCI3200_ReadCalibrationOffsetValue(struct comedi_device *dev, unsigned int *data);
 int i_APCI3200_Read1AnalogInputChannel(struct comedi_device *dev,
 				       struct comedi_subdevice *s, struct comedi_insn *insn,
 				       unsigned int *data);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3501.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3501.c
index 20391a9..ef21f03 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3501.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3501.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -62,8 +62,8 @@
 | Task              : Read  value  of the selected channel or port           |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To read       |
-|                     UINT *data              : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To read       |
+|                     unsigned int *data              : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -73,26 +73,26 @@
 +----------------------------------------------------------------------------+
 */
 
-INT i_APCI3501_ReadDigitalInput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3501_ReadDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp;
-	UINT ui_NoOfChannel;
+	unsigned int ui_Temp;
+	unsigned int ui_NoOfChannel;
 	ui_NoOfChannel = CR_CHAN(insn->chanspec);
 	ui_Temp = data[0];
 	*data = inl(devpriv->iobase + APCI3501_DIGITAL_IP);
 	if (ui_Temp == 0) {
 		*data = (*data >> ui_NoOfChannel) & 0x1;
-	}			//if  (ui_Temp==0)
+	}			/* if  (ui_Temp==0) */
 	else {
 		if (ui_Temp == 1) {
 
 			*data = *data & 0x3;
-		}		//if  (ui_Temp==1)
+		}		/* if  (ui_Temp==1) */
 		else {
 			printk("\nSpecified channel not supported \n");
-		}		//elseif  (ui_Temp==1)
-	}			//elseif  (ui_Temp==0)
+		}		/* elseif  (ui_Temp==1) */
+	}			/* elseif  (ui_Temp==0) */
 	return insn->n;
 }
 
@@ -105,7 +105,7 @@
 | Task              : Configures The Digital Output Subdevice.               |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 |					  data[1]            : 1 Enable  VCC  Interrupt  |
@@ -121,21 +121,21 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-int i_APCI3501_ConfigDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3501_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
 	if ((data[0] != 0) && (data[0] != 1)) {
 		comedi_error(dev,
 			"Not a valid Data !!! ,Data should be 1 or 0\n");
 		return -EINVAL;
-	}			//if  ( (data[0]!=0) && (data[0]!=1) )
+	}			/* if  ( (data[0]!=0) && (data[0]!=1) ) */
 	if (data[0]) {
 		devpriv->b_OutputMemoryStatus = ADDIDATA_ENABLE;
-	}			// if  (data[0])
+	}			/*  if  (data[0]) */
 	else {
 		devpriv->b_OutputMemoryStatus = ADDIDATA_DISABLE;
-	}			//else if  (data[0])
+	}			/* else if  (data[0]) */
 	return insn->n;
 }
 
@@ -161,33 +161,33 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI3501_WriteDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3501_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp, ui_Temp1;
-	UINT ui_NoOfChannel = CR_CHAN(insn->chanspec);	// get the channel
+	unsigned int ui_Temp, ui_Temp1;
+	unsigned int ui_NoOfChannel = CR_CHAN(insn->chanspec);	/*  get the channel */
 	if (devpriv->b_OutputMemoryStatus) {
 		ui_Temp = inl(devpriv->iobase + APCI3501_DIGITAL_OP);
-	}			//if(devpriv->b_OutputMemoryStatus )
+	}			/* if(devpriv->b_OutputMemoryStatus ) */
 	else {
 		ui_Temp = 0;
-	}			//if(devpriv->b_OutputMemoryStatus )
+	}			/* if(devpriv->b_OutputMemoryStatus ) */
 	if (data[3] == 0) {
 		if (data[1] == 0) {
 			data[0] = (data[0] << ui_NoOfChannel) | ui_Temp;
 			outl(data[0], devpriv->iobase + APCI3501_DIGITAL_OP);
-		}		//if(data[1]==0)
+		}		/* if(data[1]==0) */
 		else {
 			if (data[1] == 1) {
 				data[0] = (data[0] << (2 * data[2])) | ui_Temp;
 				outl(data[0],
 					devpriv->iobase + APCI3501_DIGITAL_OP);
-			}	// if(data[1]==1)
+			}	/*  if(data[1]==1) */
 			else {
 				printk("\nSpecified channel not supported\n");
-			}	//else if(data[1]==1)
-		}		//elseif(data[1]==0)
-	}			//if(data[3]==0)
+			}	/* else if(data[1]==1) */
+		}		/* elseif(data[1]==0) */
+	}			/* if(data[3]==0) */
 	else {
 		if (data[3] == 1) {
 			if (data[1] == 0) {
@@ -201,7 +201,7 @@
 				data[0] = data[0] & ui_Temp;
 				outl(data[0],
 					devpriv->iobase + APCI3501_DIGITAL_OP);
-			}	//if(data[1]==0)
+			}	/* if(data[1]==0) */
 			else {
 				if (data[1] == 1) {
 					data[0] = ~data[0] & 0x3;
@@ -215,17 +215,17 @@
 					outl(data[0],
 						devpriv->iobase +
 						APCI3501_DIGITAL_OP);
-				}	// if(data[1]==1)
+				}	/*  if(data[1]==1) */
 				else {
 					printk("\nSpecified channel not supported\n");
-				}	//else if(data[1]==1)
-			}	//elseif(data[1]==0)
-		}		//if(data[3]==1);
+				}	/* else if(data[1]==1) */
+			}	/* elseif(data[1]==0) */
+		}		/* if(data[3]==1); */
 		else {
 			printk("\nSpecified functionality does not exist\n");
 			return -EINVAL;
-		}		//if else data[3]==1)
-	}			//if else data[3]==0)
+		}		/* if else data[3]==1) */
+	}			/* if else data[3]==0) */
 	return insn->n;
 }
 
@@ -238,8 +238,8 @@
 | Task              : Read  value  of the selected channel or port           |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev      : Driver handle                |
-|                     UINT ui_NoOfChannels    : No Of Channels To read       |
-|                     UINT *data              : Data Pointer to read status  |
+|                     unsigned int ui_NoOfChannels    : No Of Channels To read       |
+|                     unsigned int *data              : Data Pointer to read status  |
 +----------------------------------------------------------------------------+
 | Output Parameters :	--													 |
 +----------------------------------------------------------------------------+
@@ -248,27 +248,27 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI3501_ReadDigitalOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3501_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	UINT ui_Temp;
-	UINT ui_NoOfChannel;
+	unsigned int ui_Temp;
+	unsigned int ui_NoOfChannel;
 
 	ui_NoOfChannel = CR_CHAN(insn->chanspec);
 	ui_Temp = data[0];
 	*data = inl(devpriv->iobase + APCI3501_DIGITAL_OP);
 	if (ui_Temp == 0) {
 		*data = (*data >> ui_NoOfChannel) & 0x1;
-	}			// if  (ui_Temp==0)
+	}			/*  if  (ui_Temp==0) */
 	else {
 		if (ui_Temp == 1) {
 			*data = *data & 0x3;
 
-		}		// if  (ui_Temp==1)
+		}		/*  if  (ui_Temp==1) */
 		else {
 			printk("\nSpecified channel not supported \n");
-		}		// else if (ui_Temp==1)
-	}			// else if  (ui_Temp==0)
+		}		/*  else if (ui_Temp==1) */
+	}			/*  else if  (ui_Temp==0) */
 	return insn->n;
 }
 
@@ -298,8 +298,8 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI3501_ConfigAnalogOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3501_ConfigAnalogOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	outl(data[0],
 		devpriv->iobase + APCI3501_ANALOG_OUTPUT +
@@ -336,10 +336,10 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI3501_WriteAnalogOutput(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+int i_APCI3501_WriteAnalogOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	ULONG ul_Command1 = 0, ul_Channel_no, ul_Polarity, ul_DAC_Ready = 0;;
+	unsigned int ul_Command1 = 0, ul_Channel_no, ul_Polarity, ul_DAC_Ready = 0;;
 
 	ul_Channel_no = CR_CHAN(insn->chanspec);
 
@@ -349,18 +349,18 @@
 			printk("\nIn WriteAnalogOutput :: Not Valid Data\n");
 		}
 
-	}			// end if(devpriv->b_InterruptMode==MODE1)
+	}			/*  end if(devpriv->b_InterruptMode==MODE1) */
 	else {
 		ul_Polarity = 0;
 		if ((*data < 0) || (*data > 8192)) {
 			printk("\nIn WriteAnalogOutput :: Not Valid Data\n");
 		}
 
-	}			// end else
+	}			/*  end else */
 
 	if ((ul_Channel_no < 0) || (ul_Channel_no > 7)) {
 		printk("\nIn WriteAnalogOutput :: Not Valid Channel\n");
-	}			// end if((ul_Channel_no<0)||(ul_Channel_no>7))
+	}			/*  end if((ul_Channel_no<0)||(ul_Channel_no>7)) */
 
 	ul_DAC_Ready = inl(devpriv->iobase + APCI3501_ANALOG_OUTPUT);
 
@@ -370,11 +370,11 @@
 	}
 
 	if (ul_DAC_Ready) {
-// Output the Value on the output channels.
+/* Output the Value on the output channels. */
 		ul_Command1 =
-			(ULONG) ((ULONG) (ul_Channel_no & 0xFF) |
-			(ULONG) ((*data << 0x8) & 0x7FFFFF00L) |
-			(ULONG) (ul_Polarity));
+			(unsigned int) ((unsigned int) (ul_Channel_no & 0xFF) |
+			(unsigned int) ((*data << 0x8) & 0x7FFFFF00L) |
+			(unsigned int) (ul_Polarity));
 		outl(ul_Command1,
 			devpriv->iobase + APCI3501_ANALOG_OUTPUT +
 			APCI3501_AO_PROG);
@@ -392,7 +392,7 @@
 | Task              : Configures The Timer , Counter or Watchdog             |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 |					  data[0]            : 0 Configure As Timer      |
@@ -410,78 +410,78 @@
 |			                                                         |
 +----------------------------------------------------------------------------+
 */
-INT i_APCI3501_ConfigTimerCounterWatchdog(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3501_ConfigTimerCounterWatchdog(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	ULONG ul_Command1 = 0;
+	unsigned int ul_Command1 = 0;
 	devpriv->tsk_Current = current;
 	if (data[0] == ADDIDATA_WATCHDOG) {
 
 		devpriv->b_TimerSelectMode = ADDIDATA_WATCHDOG;
-		//Disable the watchdog
-		outl(0x0, devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);	//disable Wa
+		/* Disable the watchdog */
+		outl(0x0, devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);	/* disable Wa */
 
 		if (data[1] == 1) {
-			//Enable TIMER int & DISABLE ALL THE OTHER int SOURCES
+			/* Enable TIMER int & DISABLE ALL THE OTHER int SOURCES */
 			outl(0x02,
 				devpriv->iobase + APCI3501_WATCHDOG +
 				APCI3501_TCW_PROG);
 		} else {
-			outl(0x0, devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);	//disable Timer interrupt
+			outl(0x0, devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);	/* disable Timer interrupt */
 		}
 
-		//Loading the Timebase value
+		/* Loading the Timebase value */
 		outl(data[2],
 			devpriv->iobase + APCI3501_WATCHDOG +
 			APCI3501_TCW_TIMEBASE);
 
-		//Loading the Reload value
+		/* Loading the Reload value */
 		outl(data[3],
 			devpriv->iobase + APCI3501_WATCHDOG +
 			APCI3501_TCW_RELOAD_VALUE);
-		//Set the mode
-		ul_Command1 = inl(devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG) | 0xFFF819E0UL;	//e2->e0
+		/* Set the mode */
+		ul_Command1 = inl(devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG) | 0xFFF819E0UL;	/* e2->e0 */
 		outl(ul_Command1,
 			devpriv->iobase + APCI3501_WATCHDOG +
 			APCI3501_TCW_PROG);
-	}			//end if(data[0]==ADDIDATA_WATCHDOG)
+	}			/* end if(data[0]==ADDIDATA_WATCHDOG) */
 
 	else if (data[0] == ADDIDATA_TIMER) {
-		//First Stop The Timer
+		/* First Stop The Timer */
 		ul_Command1 =
 			inl(devpriv->iobase + APCI3501_WATCHDOG +
 			APCI3501_TCW_PROG);
 		ul_Command1 = ul_Command1 & 0xFFFFF9FEUL;
-		outl(ul_Command1, devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);	//Stop The Timer
+		outl(ul_Command1, devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);	/* Stop The Timer */
 		devpriv->b_TimerSelectMode = ADDIDATA_TIMER;
 		if (data[1] == 1) {
-			//Enable TIMER int & DISABLE ALL THE OTHER int SOURCES
+			/* Enable TIMER int & DISABLE ALL THE OTHER int SOURCES */
 			outl(0x02,
 				devpriv->iobase + APCI3501_WATCHDOG +
 				APCI3501_TCW_PROG);
 		} else {
-			outl(0x0, devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);	//disable Timer interrupt
+			outl(0x0, devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);	/* disable Timer interrupt */
 		}
 
-		// Loading Timebase
+		/*  Loading Timebase */
 		outl(data[2],
 			devpriv->iobase + APCI3501_WATCHDOG +
 			APCI3501_TCW_TIMEBASE);
 
-		//Loading the Reload value
+		/* Loading the Reload value */
 		outl(data[3],
 			devpriv->iobase + APCI3501_WATCHDOG +
 			APCI3501_TCW_RELOAD_VALUE);
 
-		// printk ("\nTimer Address :: %x\n", (devpriv->iobase+APCI3501_WATCHDOG));
+		/*  printk ("\nTimer Address :: %x\n", (devpriv->iobase+APCI3501_WATCHDOG)); */
 		ul_Command1 =
 			inl(devpriv->iobase + APCI3501_WATCHDOG +
 			APCI3501_TCW_PROG);
 		ul_Command1 =
 			(ul_Command1 & 0xFFF719E2UL) | 2UL << 13UL | 0x10UL;
-		outl(ul_Command1, devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);	//mode 2
+		outl(ul_Command1, devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);	/* mode 2 */
 
-	}			//end if(data[0]==ADDIDATA_TIMER)
+	}			/* end if(data[0]==ADDIDATA_TIMER) */
 
 	return insn->n;
 }
@@ -495,7 +495,7 @@
 | Task              : Start / Stop The Selected Timer , Counter or Watchdog  |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 |					  data[0]            : 0 Timer                   |
@@ -511,10 +511,10 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3501_StartStopWriteTimerCounterWatchdog(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3501_StartStopWriteTimerCounterWatchdog(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	ULONG ul_Command1 = 0;
+	unsigned int ul_Command1 = 0;
 	int i_Temp;
 	if (devpriv->b_TimerSelectMode == ADDIDATA_WATCHDOG) {
 
@@ -523,15 +523,15 @@
 				inl(devpriv->iobase + APCI3501_WATCHDOG +
 				APCI3501_TCW_PROG);
 			ul_Command1 = (ul_Command1 & 0xFFFFF9FFUL) | 0x1UL;
-			//Enable the Watchdog
+			/* Enable the Watchdog */
 			outl(ul_Command1,
 				devpriv->iobase + APCI3501_WATCHDOG +
 				APCI3501_TCW_PROG);
 		}
 
-		else if (data[1] == 0)	//Stop The Watchdog
+		else if (data[1] == 0)	/* Stop The Watchdog */
 		{
-			//Stop The Watchdog
+			/* Stop The Watchdog */
 			ul_Command1 =
 				inl(devpriv->iobase + APCI3501_WATCHDOG +
 				APCI3501_TCW_PROG);
@@ -547,8 +547,8 @@
 			outl(ul_Command1,
 				devpriv->iobase + APCI3501_WATCHDOG +
 				APCI3501_TCW_PROG);
-		}		//if(data[1]==2)
-	}			// end if (devpriv->b_TimerSelectMode==ADDIDATA_WATCHDOG)
+		}		/* if(data[1]==2) */
+	}			/*  end if (devpriv->b_TimerSelectMode==ADDIDATA_WATCHDOG) */
 
 	if (devpriv->b_TimerSelectMode == ADDIDATA_TIMER) {
 		if (data[1] == 1) {
@@ -557,12 +557,12 @@
 				inl(devpriv->iobase + APCI3501_WATCHDOG +
 				APCI3501_TCW_PROG);
 			ul_Command1 = (ul_Command1 & 0xFFFFF9FFUL) | 0x1UL;
-			//Enable the Timer
+			/* Enable the Timer */
 			outl(ul_Command1,
 				devpriv->iobase + APCI3501_WATCHDOG +
 				APCI3501_TCW_PROG);
 		} else if (data[1] == 0) {
-			//Stop The Timer
+			/* Stop The Timer */
 			ul_Command1 =
 				inl(devpriv->iobase + APCI3501_WATCHDOG +
 				APCI3501_TCW_PROG);
@@ -573,7 +573,7 @@
 		}
 
 		else if (data[1] == 2) {
-			//Trigger the Timer
+			/* Trigger the Timer */
 			ul_Command1 =
 				inl(devpriv->iobase + APCI3501_WATCHDOG +
 				APCI3501_TCW_PROG);
@@ -583,7 +583,7 @@
 				APCI3501_TCW_PROG);
 		}
 
-	}			// end if (devpriv->b_TimerSelectMode==ADDIDATA_TIMER)
+	}			/*  end if (devpriv->b_TimerSelectMode==ADDIDATA_TIMER) */
 	i_Temp = inl(devpriv->iobase + APCI3501_WATCHDOG +
 		APCI3501_TCW_TRIG_STATUS) & 0x1;
 	return insn->n;
@@ -598,7 +598,7 @@
 | Task              : Read The Selected Timer , Counter or Watchdog          |
 +----------------------------------------------------------------------------+
 | Input Parameters  : struct comedi_device *dev : Driver handle                     |
-|                     UINT *data         : Data Pointer contains             |
+|                     unsigned int *data         : Data Pointer contains             |
 |                                          configuration parameters as below |
 |                                                                            |
 |					  data[0]            : 0 Timer                   |
@@ -613,8 +613,8 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3501_ReadTimerCounterWatchdog(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3501_ReadTimerCounterWatchdog(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 
 	if (devpriv->b_TimerSelectMode == ADDIDATA_WATCHDOG) {
@@ -622,14 +622,14 @@
 			inl(devpriv->iobase + APCI3501_WATCHDOG +
 			APCI3501_TCW_TRIG_STATUS) & 0x1;
 		data[1] = inl(devpriv->iobase + APCI3501_WATCHDOG);
-	}			// end if  (devpriv->b_TimerSelectMode==ADDIDATA_WATCHDOG)
+	}			/*  end if  (devpriv->b_TimerSelectMode==ADDIDATA_WATCHDOG) */
 
 	else if (devpriv->b_TimerSelectMode == ADDIDATA_TIMER) {
 		data[0] =
 			inl(devpriv->iobase + APCI3501_WATCHDOG +
 			APCI3501_TCW_TRIG_STATUS) & 0x1;
 		data[1] = inl(devpriv->iobase + APCI3501_WATCHDOG);
-	}			// end if  (devpriv->b_TimerSelectMode==ADDIDATA_TIMER)
+	}			/*  end if  (devpriv->b_TimerSelectMode==ADDIDATA_TIMER) */
 
 	else if ((devpriv->b_TimerSelectMode != ADDIDATA_TIMER)
 		&& (devpriv->b_TimerSelectMode != ADDIDATA_WATCHDOG)) {
@@ -654,10 +654,10 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3501_Reset(struct comedi_device * dev)
+int i_APCI3501_Reset(struct comedi_device *dev)
 {
 	int i_Count = 0, i_temp = 0;
-	ULONG ul_Command1 = 0, ul_Polarity, ul_DAC_Ready = 0;
+	unsigned int ul_Command1 = 0, ul_Polarity, ul_DAC_Ready = 0;
 	outl(0x0, devpriv->iobase + APCI3501_DIGITAL_OP);
 	outl(1, devpriv->iobase + APCI3501_ANALOG_OUTPUT +
 		APCI3501_AO_VOLT_MODE);
@@ -674,11 +674,11 @@
 		}
 
 		if (ul_DAC_Ready) {
-			// Output the Value on the output channels.
+			/*  Output the Value on the output channels. */
 			ul_Command1 =
-				(ULONG) ((ULONG) (i_Count & 0xFF) |
-				(ULONG) ((i_temp << 0x8) & 0x7FFFFF00L) |
-				(ULONG) (ul_Polarity));
+				(unsigned int) ((unsigned int) (i_Count & 0xFF) |
+				(unsigned int) ((i_temp << 0x8) & 0x7FFFFF00L) |
+				(unsigned int) (ul_Polarity));
 			outl(ul_Command1,
 				devpriv->iobase + APCI3501_ANALOG_OUTPUT +
 				APCI3501_AO_PROG);
@@ -711,7 +711,7 @@
 	struct comedi_device *dev = d;
 	unsigned int ui_Timer_AOWatchdog;
 	unsigned long ul_Command1;
-	// Disable Interrupt
+	/*  Disable Interrupt */
 	ul_Command1 =
 		inl(devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);
 
@@ -728,8 +728,9 @@
 		return;
 	}
 
-	// Enable Interrupt
-	//Send a signal to from kernel to user space
+/*
+* Enable Interrupt Send a signal to from kernel to user space
+*/
 	send_sig(SIGIO, devpriv->tsk_Current, 0);
 	ul_Command1 =
 		inl(devpriv->iobase + APCI3501_WATCHDOG + APCI3501_TCW_PROG);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3501.h b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3501.h
index 51e7b66..c456d75 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3501.h
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3501.h
@@ -15,7 +15,7 @@
  * any later version.
  */
 
-// Card Specific information
+/* Card Specific information */
 #define APCI3501_BOARD_VENDOR_ID                 0x15B8
 #define APCI3501_ADDRESS_RANGE                   255
 
@@ -23,7 +23,7 @@
 #define APCI3501_DIGITAL_OP                       0x40
 #define APCI3501_ANALOG_OUTPUT                    0x00
 
-//Analog Output related Defines
+/* Analog Output related Defines */
 #define APCI3501_AO_VOLT_MODE                     0
 #define APCI3501_AO_PROG                          4
 #define APCI3501_AO_TRIG_SCS                      8
@@ -31,14 +31,14 @@
 #define BIPOLAR                                   1
 #define MODE0                                     0
 #define MODE1                                     1
-// ANALOG OUTPUT RANGE
+/* ANALOG OUTPUT RANGE */
 struct comedi_lrange range_apci3501_ao = { 2, {
 					BIP_RANGE(10),
 					UNI_RANGE(10)
 					}
 };
 
-//Watchdog Related Defines
+/* Watchdog Related Defines */
 
 #define APCI3501_WATCHDOG                         0x20
 #define APCI3501_TCW_SYNC_ENABLEDISABLE           0
@@ -52,32 +52,36 @@
 #define ADDIDATA_TIMER                            0
 #define ADDIDATA_WATCHDOG                         2
 
-// Hardware Layer  functions for Apci3501
+/* Hardware Layer  functions for Apci3501 */
 
-//AO
-INT i_APCI3501_ConfigAnalogOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+/* AO */
+int i_APCI3501_ConfigAnalogOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				  struct comedi_insn *insn, unsigned int *data);
-INT i_APCI3501_WriteAnalogOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI3501_WriteAnalogOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
 
-//DI
-// for di read
-//INT i_APCI3501_ReadDigitalInput(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data);
+/*
+* DI for di read INT i_APCI3501_ReadDigitalInput(struct
+* comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn
+* *insn,unsigned int *data);
+*/
 
-INT i_APCI3501_ReadDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI3501_ReadDigitalInput(struct comedi_device *dev, struct comedi_subdevice *s,
 				struct comedi_insn *insn, unsigned int *data);
 
-//DO
+/* DO */
 int i_APCI3501_ConfigDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				   struct comedi_insn *insn, unsigned int *data);
-INT i_APCI3501_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI3501_WriteDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				  struct comedi_insn *insn, unsigned int *data);
-INT i_APCI3501_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
+int i_APCI3501_ReadDigitalOutput(struct comedi_device *dev, struct comedi_subdevice *s,
 				 struct comedi_insn *insn, unsigned int *data);
 
-// TIMER
-// timer value is passed as u seconds
-INT i_APCI3501_ConfigTimerCounterWatchdog(struct comedi_device *dev,
+/* TIMER
+ * timer value is passed as u seconds
+ */
+
+int i_APCI3501_ConfigTimerCounterWatchdog(struct comedi_device *dev,
 					  struct comedi_subdevice *s,
 					  struct comedi_insn *insn, unsigned int *data);
 int i_APCI3501_StartStopWriteTimerCounterWatchdog(struct comedi_device *dev,
@@ -87,8 +91,8 @@
 int i_APCI3501_ReadTimerCounterWatchdog(struct comedi_device *dev,
 					struct comedi_subdevice *s,
 					struct comedi_insn *insn, unsigned int *data);
-//Interrupt
+/* Interrupt */
 void v_APCI3501_Interrupt(int irq, void *d);
 
-//Reset functions
+/* Reset functions */
 int i_APCI3501_Reset(struct comedi_device *dev);
diff --git a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3xxx.c b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3xxx.c
index b7268e4..3387278 100644
--- a/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3xxx.c
+++ b/drivers/staging/comedi/drivers/addi-data/hwdrv_apci3xxx.c
@@ -3,13 +3,13 @@
 
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code of this module.
 
-        ADDI-DATA GmbH
-        Dieselstrasse 3
-        D-77833 Ottersweier
-        Tel: +19(0)7223/9493-0
-        Fax: +49(0)7223/9493-92
-        http://www.addi-data-com
-        info@addi-data.com
+	ADDI-DATA GmbH
+	Dieselstrasse 3
+	D-77833 Ottersweier
+	Tel: +19(0)7223/9493-0
+	Fax: +49(0)7223/9493-92
+	http://www.addi-data-com
+	info@addi-data.com
 
 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 
@@ -54,7 +54,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT   i_APCI3XXX_TestConversionStarted                 |
+| Function Name     : int   i_APCI3XXX_TestConversionStarted                 |
 |                          (struct comedi_device    *dev)                           |
 +----------------------------------------------------------------------------+
 | Task                Test if any conversion started                         |
@@ -68,18 +68,18 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_TestConversionStarted(struct comedi_device * dev)
+int i_APCI3XXX_TestConversionStarted(struct comedi_device *dev)
 {
-	if ((readl((void *)(devpriv->dw_AiBase + 8)) & 0x80000UL) == 0x80000UL) {
-		return (1);
-	} else {
-		return (0);
-	}
+	if ((readl((void *)(devpriv->dw_AiBase + 8)) & 0x80000UL) == 0x80000UL)
+		return 1;
+	else
+		return 0;
+
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT   i_APCI3XXX_AnalogInputConfigOperatingMode        |
+| Function Name     : int   i_APCI3XXX_AnalogInputConfigOperatingMode        |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -87,9 +87,9 @@
 +----------------------------------------------------------------------------+
 | Task           Converting mode and convert time selection                  |
 +----------------------------------------------------------------------------+
-| Input Parameters  : b_SingleDiff  = (BYTE)  data[1];                       |
-|                     b_TimeBase    = (BYTE)  data[2]; (0: ns, 1:micros 2:ms)|
-|                    dw_ReloadValue = (DWORD) data[3];                       |
+| Input Parameters  : b_SingleDiff  = (unsigned char)  data[1];                       |
+|                     b_TimeBase    = (unsigned char)  data[2]; (0: ns, 1:micros 2:ms)|
+|                    dw_ReloadValue = (unsigned int) data[3];                       |
 |                     ........                                               |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -105,14 +105,14 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_AnalogInputConfigOperatingMode(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_AnalogInputConfigOperatingMode(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_TimeBase = 0;
-	BYTE b_SingleDiff = 0;
-	DWORD dw_ReloadValue = 0;
-	DWORD dw_TestReloadValue = 0;
+	int i_ReturnValue = insn->n;
+	unsigned char b_TimeBase = 0;
+	unsigned char b_SingleDiff = 0;
+	unsigned int dw_ReloadValue = 0;
+	unsigned int dw_TestReloadValue = 0;
 
 	/************************/
 	/* Test the buffer size */
@@ -123,19 +123,19 @@
 		/* Get the Singel/Diff flag */
 	   /****************************/
 
-		b_SingleDiff = (BYTE) data[1];
+		b_SingleDiff = (unsigned char) data[1];
 
 	   /****************************/
 		/* Get the time base unitiy */
 	   /****************************/
 
-		b_TimeBase = (BYTE) data[2];
+		b_TimeBase = (unsigned char) data[2];
 
 	   /*************************************/
 		/* Get the convert time reload value */
 	   /*************************************/
 
-		dw_ReloadValue = (DWORD) data[3];
+		dw_ReloadValue = (unsigned int) data[3];
 
 	   /**********************/
 		/* Test the time base */
@@ -186,7 +186,7 @@
 								devpriv->
 									ui_EocEosConversionTime
 									=
-									(UINT)
+									(unsigned int)
 									dw_ReloadValue;
 								devpriv->
 									b_EocEosConversionTimeBase
@@ -204,7 +204,7 @@
 								/* Set the convert timing unit */
 			      /*******************************/
 
-								writel((DWORD)
+								writel((unsigned int)
 									b_TimeBase,
 									(void *)
 									(devpriv->
@@ -268,12 +268,12 @@
 		i_ReturnValue = -101;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT   i_APCI3XXX_InsnConfigAnalogInput                 |
+| Function Name     : int   i_APCI3XXX_InsnConfigAnalogInput                 |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -281,9 +281,9 @@
 +----------------------------------------------------------------------------+
 | Task           Converting mode and convert time selection                  |
 +----------------------------------------------------------------------------+
-| Input Parameters  : b_ConvertMode = (BYTE)  data[0];                       |
-|                     b_TimeBase    = (BYTE)  data[1]; (0: ns, 1:micros 2:ms)|
-|                    dw_ReloadValue = (DWORD) data[2];                       |
+| Input Parameters  : b_ConvertMode = (unsigned char)  data[0];                       |
+|                     b_TimeBase    = (unsigned char)  data[1]; (0: ns, 1:micros 2:ms)|
+|                    dw_ReloadValue = (unsigned int) data[2];                       |
 |                     ........                                               |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
@@ -295,17 +295,17 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_InsnConfigAnalogInput(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnConfigAnalogInput(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
+	int i_ReturnValue = insn->n;
 
 	/************************/
 	/* Test the buffer size */
 	/************************/
 
 	if (insn->n >= 1) {
-		switch ((BYTE) data[0]) {
+		switch ((unsigned char) data[0]) {
 		case APCI3XXX_CONFIGURATION:
 			i_ReturnValue =
 				i_APCI3XXX_AnalogInputConfigOperatingMode(dev,
@@ -326,12 +326,12 @@
 		i_ReturnValue = -101;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT   i_APCI3XXX_InsnReadAnalogInput                   |
+| Function Name     : int   i_APCI3XXX_InsnReadAnalogInput                   |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -355,16 +355,16 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_InsnReadAnalogInput(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnReadAnalogInput(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_Configuration = (BYTE) CR_RANGE(insn->chanspec);
-	BYTE b_Channel = (BYTE) CR_CHAN(insn->chanspec);
-	DWORD dw_Temp = 0;
-	DWORD dw_Configuration = 0;
-	DWORD dw_AcquisitionCpt = 0;
-	BYTE b_Interrupt = 0;
+	int i_ReturnValue = insn->n;
+	unsigned char b_Configuration = (unsigned char) CR_RANGE(insn->chanspec);
+	unsigned char b_Channel = (unsigned char) CR_CHAN(insn->chanspec);
+	unsigned int dw_Temp = 0;
+	unsigned int dw_Configuration = 0;
+	unsigned int dw_AcquisitionCpt = 0;
+	unsigned char b_Interrupt = 0;
 
 	/*************************************/
 	/* Test if operating mode configured */
@@ -449,8 +449,8 @@
 
 					dw_Configuration =
 						(b_Configuration & 3) |
-						((DWORD) (b_Configuration >> 2)
-						<< 6) | ((DWORD) devpriv->
+						((unsigned int) (b_Configuration >> 2)
+						<< 6) | ((unsigned int) devpriv->
 						b_SingelDiff << 7);
 
 		    /***************************/
@@ -468,7 +468,7 @@
 					writel(dw_Temp | 0x100UL,
 						(void *)(devpriv->dw_AiBase +
 							4));
-					writel((DWORD) b_Channel,
+					writel((unsigned int) b_Channel,
 						(void *)(devpriv->dw_AiBase +
 							0));
 
@@ -535,8 +535,7 @@
 								dw_Temp =
 									dw_Temp
 									& 1;
-							}
-							while (dw_Temp != 1);
+							} while (dw_Temp != 1);
 
 			  /*************************/
 							/* Read the analog value */
@@ -585,7 +584,7 @@
 		printk("Operating mode not configured\n");
 		i_ReturnValue = -1;
 	}
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -607,15 +606,15 @@
 void v_APCI3XXX_Interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
-	BYTE b_CopyCpt = 0;
-	DWORD dw_Status = 0;
+	unsigned char b_CopyCpt = 0;
+	unsigned int dw_Status = 0;
 
 	/***************************/
 	/* Test if interrupt occur */
 	/***************************/
 
-	if (((dw_Status = readl((void *)(devpriv->dw_AiBase + 16))) & 0x2UL) ==
-		0x2UL) {
+	dw_Status = readl((void *)(devpriv->dw_AiBase + 16));
+	if ( (dw_Status & 0x2UL) == 0x2UL) {
 	   /***********************/
 		/* Reset the interrupt */
 	   /***********************/
@@ -635,7 +634,7 @@
 				b_CopyCpt < devpriv->ui_AiNbrofChannels;
 				b_CopyCpt++) {
 				devpriv->ui_AiReadData[b_CopyCpt] =
-					(UINT) readl((void *)(devpriv->
+					(unsigned int) readl((void *)(devpriv->
 						dw_AiBase + 28));
 			}
 
@@ -662,7 +661,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT   i_APCI3XXX_InsnWriteAnalogOutput                 |
+| Function Name     : int   i_APCI3XXX_InsnWriteAnalogOutput                 |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -684,13 +683,13 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_InsnWriteAnalogOutput(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnWriteAnalogOutput(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	BYTE b_Range = (BYTE) CR_RANGE(insn->chanspec);
-	BYTE b_Channel = (BYTE) CR_CHAN(insn->chanspec);
-	DWORD dw_Status = 0;
-	INT i_ReturnValue = insn->n;
+	unsigned char b_Range = (unsigned char) CR_RANGE(insn->chanspec);
+	unsigned char b_Channel = (unsigned char) CR_CHAN(insn->chanspec);
+	unsigned int dw_Status = 0;
+	int i_ReturnValue = insn->n;
 
 	/************************/
 	/* Test the buffer size */
@@ -729,8 +728,7 @@
 					dw_Status =
 						readl((void *)(devpriv->
 							dw_AiBase + 96));
-				}
-				while ((dw_Status & 0x100) != 0x100);
+				} while ((dw_Status & 0x100) != 0x100);
 			} else {
 		 /***************************/
 				/* Channel not initialised */
@@ -757,7 +755,7 @@
 		i_ReturnValue = -101;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -768,7 +766,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT   i_APCI3XXX_InsnConfigInitTTLIO                   |
+| Function Name     : int   i_APCI3XXX_InsnConfigInitTTLIO                   |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -778,8 +776,8 @@
 |                for you call any other function witch access of TTL.        |
 |                APCI3XXX_TTL_INIT_DIRECTION_PORT2(user inputs for direction)|
 +----------------------------------------------------------------------------+
-| Input Parameters  : b_InitType    = (BYTE) data[0];                        |
-|                     b_Port2Mode   = (BYTE) data[1];                        |
+| Input Parameters  : b_InitType    = (unsigned char) data[0];                        |
+|                     b_Port2Mode   = (unsigned char) data[1];                        |
 +----------------------------------------------------------------------------+
 | Output Parameters : -                                                      |
 +----------------------------------------------------------------------------+
@@ -791,11 +789,11 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_InsnConfigInitTTLIO(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnConfigInitTTLIO(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_Command = 0;
+	int i_ReturnValue = insn->n;
+	unsigned char b_Command = 0;
 
 	/************************/
 	/* Test the buffer size */
@@ -806,7 +804,7 @@
 		/* Get the command */
 		/* **************** */
 
-		b_Command = (BYTE) data[0];
+		b_Command = (unsigned char) data[0];
 
 	   /********************/
 		/* Test the command */
@@ -888,7 +886,7 @@
 		}
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -899,7 +897,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT     i_APCI3XXX_InsnBitsTTLIO                       |
+| Function Name     : int     i_APCI3XXX_InsnBitsTTLIO                       |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -919,14 +917,14 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_InsnBitsTTLIO(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnBitsTTLIO(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_ChannelCpt = 0;
-	DWORD dw_ChannelMask = 0;
-	DWORD dw_BitMask = 0;
-	DWORD dw_Status = 0;
+	int i_ReturnValue = insn->n;
+	unsigned char b_ChannelCpt = 0;
+	unsigned int dw_ChannelMask = 0;
+	unsigned int dw_BitMask = 0;
+	unsigned int dw_Status = 0;
 
 	/************************/
 	/* Test the buffer size */
@@ -1051,12 +1049,12 @@
 		i_ReturnValue = -101;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT i_APCI3XXX_InsnReadTTLIO                           |
+| Function Name     : int i_APCI3XXX_InsnReadTTLIO                           |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -1074,11 +1072,11 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_InsnReadTTLIO(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnReadTTLIO(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	BYTE b_Channel = (BYTE) CR_CHAN(insn->chanspec);
-	INT i_ReturnValue = insn->n;
+	unsigned char b_Channel = (unsigned char) CR_CHAN(insn->chanspec);
+	int i_ReturnValue = insn->n;
 	unsigned int *pls_ReadData = data;
 
 	/************************/
@@ -1157,7 +1155,7 @@
 		i_ReturnValue = -101;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -1168,7 +1166,7 @@
 
 /*
 +----------------------------------------------------------------------------+
-| Function Name     : INT     i_APCI3XXX_InsnWriteTTLIO                      |
+| Function Name     : int     i_APCI3XXX_InsnWriteTTLIO                      |
 |                          (struct comedi_device    *dev,                           |
 |                           struct comedi_subdevice *s,                             |
 |                           struct comedi_insn      *insn,                          |
@@ -1187,20 +1185,20 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_InsnWriteTTLIO(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnWriteTTLIO(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_Channel = (BYTE) CR_CHAN(insn->chanspec);
-	BYTE b_State = 0;
-	DWORD dw_Status = 0;
+	int i_ReturnValue = insn->n;
+	unsigned char b_Channel = (unsigned char) CR_CHAN(insn->chanspec);
+	unsigned char b_State = 0;
+	unsigned int dw_Status = 0;
 
 	/************************/
 	/* Test the buffer size */
 	/************************/
 
 	if (insn->n >= 1) {
-		b_State = (BYTE) data[0];
+		b_State = (unsigned char) data[0];
 
 	   /***********************/
 		/* Test if read port 0 */
@@ -1269,7 +1267,7 @@
 		i_ReturnValue = -101;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -1298,12 +1296,12 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_InsnReadDigitalInput(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnReadDigitalInput(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_Channel = (BYTE) CR_CHAN(insn->chanspec);
-	DWORD dw_Temp = 0;
+	int i_ReturnValue = insn->n;
+	unsigned char b_Channel = (unsigned char) CR_CHAN(insn->chanspec);
+	unsigned int dw_Temp = 0;
 
 	/***************************/
 	/* Test the channel number */
@@ -1334,7 +1332,7 @@
 		i_ReturnValue = -3;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -1356,11 +1354,11 @@
 |                    -101 : Data size error                                  |
 +----------------------------------------------------------------------------+
 */
-int i_APCI3XXX_InsnBitsDigitalInput(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnBitsDigitalInput(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	DWORD dw_Temp = 0;
+	int i_ReturnValue = insn->n;
+	unsigned int dw_Temp = 0;
 
 	/************************/
 	/* Test the buffer size */
@@ -1378,7 +1376,7 @@
 		i_ReturnValue = -101;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -1409,14 +1407,14 @@
 |                    -101 : Data size error                                  |
 +----------------------------------------------------------------------------+
 */
-int i_APCI3XXX_InsnBitsDigitalOutput(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnBitsDigitalOutput(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_ChannelCpt = 0;
-	DWORD dw_ChannelMask = 0;
-	DWORD dw_BitMask = 0;
-	DWORD dw_Status = 0;
+	int i_ReturnValue = insn->n;
+	unsigned char b_ChannelCpt = 0;
+	unsigned int dw_ChannelMask = 0;
+	unsigned int dw_BitMask = 0;
+	unsigned int dw_Status = 0;
 
 	/************************/
 	/* Test the buffer size */
@@ -1481,7 +1479,7 @@
 		i_ReturnValue = -101;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -1505,13 +1503,13 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_InsnWriteDigitalOutput(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnWriteDigitalOutput(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_Channel = CR_CHAN(insn->chanspec);
-	BYTE b_State = 0;
-	DWORD dw_Status = 0;
+	int i_ReturnValue = insn->n;
+	unsigned char b_Channel = CR_CHAN(insn->chanspec);
+	unsigned char b_State = 0;
+	unsigned int dw_Status = 0;
 
 	/************************/
 	/* Test the buffer size */
@@ -1527,7 +1525,7 @@
 			/* Get the command */
 	      /*******************/
 
-			b_State = (BYTE) data[0];
+			b_State = (unsigned char) data[0];
 
 	      /********************************/
 			/* Read the digital output port */
@@ -1557,7 +1555,7 @@
 		i_ReturnValue = -101;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -1580,12 +1578,12 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_InsnReadDigitalOutput(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+int i_APCI3XXX_InsnReadDigitalOutput(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	INT i_ReturnValue = insn->n;
-	BYTE b_Channel = CR_CHAN(insn->chanspec);
-	DWORD dw_Status = 0;
+	int i_ReturnValue = insn->n;
+	unsigned char b_Channel = CR_CHAN(insn->chanspec);
+	unsigned int dw_Status = 0;
 
 	/************************/
 	/* Test the buffer size */
@@ -1622,7 +1620,7 @@
 		i_ReturnValue = -101;
 	}
 
-	return (i_ReturnValue);
+	return i_ReturnValue;
 }
 
 /*
@@ -1638,7 +1636,7 @@
 +----------------------------------------------------------------------------+
 */
 
-int i_APCI3XXX_Reset(struct comedi_device * dev)
+int i_APCI3XXX_Reset(struct comedi_device *dev)
 {
 	unsigned char b_Cpt = 0;
 
diff --git a/drivers/staging/comedi/drivers/addi_apci_035.c b/drivers/staging/comedi/drivers/addi_apci_035.c
index bac0182..da454e8 100644
--- a/drivers/staging/comedi/drivers/addi_apci_035.c
+++ b/drivers/staging/comedi/drivers/addi_apci_035.c
@@ -1,5 +1,5 @@
 #define CONFIG_APCI_035 1
 
-#define ADDIDATA_WATCHDOG 2	// Or shold it be something else
+#define ADDIDATA_WATCHDOG 2	/*  Or shold it be something else */
 
 #include "addi-data/addi_common.c"
diff --git a/drivers/staging/comedi/drivers/adl_pci6208.c b/drivers/staging/comedi/drivers/adl_pci6208.c
index f710f551..b4807fc7 100644
--- a/drivers/staging/comedi/drivers/adl_pci6208.c
+++ b/drivers/staging/comedi/drivers/adl_pci6208.c
@@ -61,35 +61,35 @@
 	const char *name;
 	unsigned short dev_id;	/* `lspci` will show you this */
 	int ao_chans;
-	//int ao_bits;
+	/* int ao_bits; */
 };
 
 static const struct pci6208_board pci6208_boards[] = {
 	/*{
-	   name :  "pci6208v",
-	   dev_id       :  0x6208,      //not sure
-	   ao_chans:  8
-	   //,  ao_bits :  16
+	.name = "pci6208v",
+	.dev_id = 0x6208,      // not sure
+	.ao_chans = 8
+	   // ,	.ao_bits = 16
 	   },
 	   {
-	   name :  "pci6216v",
-	   dev_id       :  0x6208,      //not sure
-	   ao_chans:  16
-	   //,  ao_bits :  16
+	.name = "pci6216v",
+	.dev_id = 0x6208,      // not sure
+	.ao_chans = 16
+	   // ,	.ao_bits = 16
 	   }, */
 	{
-	      name:	"pci6208a",
-	      dev_id:	0x6208,
-	      ao_chans:8
-			//,     ao_bits :  16
+	.name = "pci6208a",
+	.dev_id = 0x6208,
+	.ao_chans = 8
+			/* ,	.ao_bits = 16 */
 		}
 };
 
 /* This is used by modprobe to translate PCI IDs to drivers.  Should
  * only be used for PCI and ISA-PnP devices */
 static DEFINE_PCI_DEVICE_TABLE(pci6208_pci_table) = {
-	//{ PCI_VENDOR_ID_ADLINK, 0x6208, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
-	//{ PCI_VENDOR_ID_ADLINK, 0x6208, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
+	/* { PCI_VENDOR_ID_ADLINK, 0x6208, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, */
+	/* { PCI_VENDOR_ID_ADLINK, 0x6208, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, */
 	{PCI_VENDOR_ID_ADLINK, 0x6208, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
 	{0}
 };
@@ -107,35 +107,32 @@
 
 #define devpriv ((struct pci6208_private *)dev->private)
 
-static int pci6208_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pci6208_detach(struct comedi_device * dev);
-
-#define pci6208_board_nbr \
-	(sizeof(pci6208_boards) / sizeof(struct pci6208_board))
+static int pci6208_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pci6208_detach(struct comedi_device *dev);
 
 static struct comedi_driver driver_pci6208 = {
-      driver_name:PCI6208_DRIVER_NAME,
-      module:THIS_MODULE,
-      attach:pci6208_attach,
-      detach:pci6208_detach,
+	.driver_name = PCI6208_DRIVER_NAME,
+	.module = THIS_MODULE,
+	.attach = pci6208_attach,
+	.detach = pci6208_detach,
 };
 
 COMEDI_PCI_INITCLEANUP(driver_pci6208, pci6208_pci_table);
 
-static int pci6208_find_device(struct comedi_device * dev, int bus, int slot);
+static int pci6208_find_device(struct comedi_device *dev, int bus, int slot);
 static int
 pci6208_pci_setup(struct pci_dev *pci_dev, unsigned long *io_base_ptr,
 	int dev_minor);
 
 /*read/write functions*/
-static int pci6208_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int pci6208_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-//static int pci6208_dio_insn_bits(struct comedi_device *dev,struct comedi_subdevice *s,
-//      struct comedi_insn *insn,unsigned int *data);
-//static int pci6208_dio_insn_config(struct comedi_device *dev,struct comedi_subdevice *s,
-//      struct comedi_insn *insn,unsigned int *data);
+static int pci6208_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int pci6208_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+/* static int pci6208_dio_insn_bits(struct comedi_device *dev,struct comedi_subdevice *s, */
+/* struct comedi_insn *insn,unsigned int *data); */
+/* static int pci6208_dio_insn_config(struct comedi_device *dev,struct comedi_subdevice *s, */
+/* struct comedi_insn *insn,unsigned int *data); */
 
 /*
  * Attach is called by the Comedi core to configure the driver
@@ -143,7 +140,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int pci6208_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pci6208_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int retval;
@@ -176,22 +173,22 @@
 	s = dev->subdevices + 0;
 	/* analog output subdevice */
 	s->type = COMEDI_SUBD_AO;
-	s->subdev_flags = SDF_WRITABLE;	//anything else to add here??
+	s->subdev_flags = SDF_WRITABLE;	/* anything else to add here?? */
 	s->n_chan = thisboard->ao_chans;
-	s->maxdata = 0xffff;	//16-bit DAC
-	s->range_table = &range_bipolar10;	//this needs to be checked.
+	s->maxdata = 0xffff;	/* 16-bit DAC */
+	s->range_table = &range_bipolar10;	/* this needs to be checked. */
 	s->insn_write = pci6208_ao_winsn;
 	s->insn_read = pci6208_ao_rinsn;
 
-	//s=dev->subdevices+1;
+	/* s=dev->subdevices+1; */
 	/* digital i/o subdevice */
-	//s->type=COMEDI_SUBD_DIO;
-	//s->subdev_flags=SDF_READABLE|SDF_WRITABLE;
-	//s->n_chan=16;
-	//s->maxdata=1;
-	//s->range_table=&range_digital;
-	//s->insn_bits = pci6208_dio_insn_bits;
-	//s->insn_config = pci6208_dio_insn_config;
+	/* s->type=COMEDI_SUBD_DIO; */
+	/* s->subdev_flags=SDF_READABLE|SDF_WRITABLE; */
+	/* s->n_chan=16; */
+	/* s->maxdata=1; */
+	/* s->range_table=&range_digital; */
+	/* s->insn_bits = pci6208_dio_insn_bits; */
+	/* s->insn_config = pci6208_dio_insn_config; */
 
 	printk("attached\n");
 
@@ -206,7 +203,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int pci6208_detach(struct comedi_device * dev)
+static int pci6208_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: pci6208: remove\n", dev->minor);
 
@@ -220,8 +217,8 @@
 	return 0;
 }
 
-static int pci6208_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci6208_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i = 0, Data_Read;
 	unsigned short chan = CR_CHAN(insn->chanspec);
@@ -245,8 +242,8 @@
 
 /* AO subdevices should have a read insn as well as a write insn.
  * Usually this means copying a value stored in devpriv. */
-static int pci6208_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci6208_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -262,51 +259,51 @@
  * useful to applications if you implement the insn_bits interface.
  * This allows packed reading/writing of the DIO channels.  The
  * comedi core can convert between insn_bits and insn_read/write */
-//static int pci6208_dio_insn_bits(struct comedi_device *dev,struct comedi_subdevice *s,
-//      struct comedi_insn *insn,unsigned int *data)
-//{
-//      if(insn->n!=2)return -EINVAL;
+/* static int pci6208_dio_insn_bits(struct comedi_device *dev,struct comedi_subdevice *s, */
+/* struct comedi_insn *insn,unsigned int *data) */
+/* { */
+/* if(insn->n!=2)return -EINVAL; */
 
 	/* The insn data is a mask in data[0] and the new data
 	 * in data[1], each channel cooresponding to a bit. */
-//      if(data[0]){
-//              s->state &= ~data[0];
-//              s->state |= data[0]&data[1];
+/* if(data[0]){ */
+/* s->state &= ~data[0]; */
+/* s->state |= data[0]&data[1]; */
 		/* Write out the new digital output lines */
-		//outw(s->state,dev->iobase + SKEL_DIO);
-//      }
+		/* outw(s->state,dev->iobase + SKEL_DIO); */
+/* } */
 
 	/* on return, data[1] contains the value of the digital
 	 * input and output lines. */
-	//data[1]=inw(dev->iobase + SKEL_DIO);
+	/* data[1]=inw(dev->iobase + SKEL_DIO); */
 	/* or we could just return the software copy of the output values if
 	 * it was a purely digital output subdevice */
-	//data[1]=s->state;
+	/* data[1]=s->state; */
 
-//      return 2;
-//}
+/* return 2; */
+/* } */
 
-//static int pci6208_dio_insn_config(struct comedi_device *dev,struct comedi_subdevice *s,
-//      struct comedi_insn *insn,unsigned int *data)
-//{
-//      int chan=CR_CHAN(insn->chanspec);
+/* static int pci6208_dio_insn_config(struct comedi_device *dev,struct comedi_subdevice *s, */
+/* struct comedi_insn *insn,unsigned int *data) */
+/* { */
+/* int chan=CR_CHAN(insn->chanspec); */
 
 	/* The input or output configuration of each digital line is
 	 * configured by a special insn_config instruction.  chanspec
 	 * contains the channel to be changed, and data[0] contains the
 	 * value COMEDI_INPUT or COMEDI_OUTPUT. */
 
-//      if(data[0]==COMEDI_OUTPUT){
-//              s->io_bits |= 1<<chan;
-//      }else{
-//              s->io_bits &= ~(1<<chan);
-//      }
-	//outw(s->io_bits,dev->iobase + SKEL_DIO_CONFIG);
+/* if(data[0]==COMEDI_OUTPUT){ */
+/* s->io_bits |= 1<<chan; */
+/* }else{ */
+/* s->io_bits &= ~(1<<chan); */
+/* } */
+	/* outw(s->io_bits,dev->iobase + SKEL_DIO_CONFIG); */
 
-//      return 1;
-//}
+/* return 1; */
+/* } */
 
-static int pci6208_find_device(struct comedi_device * dev, int bus, int slot)
+static int pci6208_find_device(struct comedi_device *dev, int bus, int slot)
 {
 	struct pci_dev *pci_dev;
 	int i;
@@ -315,11 +312,11 @@
 		pci_dev != NULL;
 		pci_dev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pci_dev)) {
 		if (pci_dev->vendor == PCI_VENDOR_ID_ADLINK) {
-			for (i = 0; i < pci6208_board_nbr; i++) {
+			for (i = 0; i < ARRAY_SIZE(pci6208_boards); i++) {
 				if (pci6208_boards[i].dev_id == pci_dev->device) {
-					// was a particular bus/slot requested?
+					/*  was a particular bus/slot requested? */
 					if ((bus != 0) || (slot != 0)) {
-						// are we on the wrong bus/slot?
+						/*  are we on the wrong bus/slot? */
 						if (pci_dev->bus->number
 							!= bus ||
 							PCI_SLOT(pci_dev->devfn)
@@ -346,10 +343,10 @@
 		PCI_SLOT(pci_dev->devfn),
 		PCI_FUNC(pci_dev->devfn), pci_dev->irq);
 
-	// TODO: Warn about non-tested boards.
-	//switch(board->device_id)
-	//{
-	//};
+	/*  TODO: Warn about non-tested boards. */
+	/* switch(board->device_id) */
+	/* { */
+	/* }; */
 
 	devpriv->pci_dev = pci_dev;
 
@@ -362,19 +359,19 @@
 {
 	unsigned long io_base, io_range, lcr_io_base, lcr_io_range;
 
-	// Enable PCI device and request regions
+	/*  Enable PCI device and request regions */
 	if (comedi_pci_enable(pci_dev, PCI6208_DRIVER_NAME) < 0) {
 		printk("comedi%d: Failed to enable PCI device and request regions\n", dev_minor);
 		return -EIO;
 	}
-	// Read local configuration register base address [PCI_BASE_ADDRESS #1].
+	/*  Read local configuration register base address [PCI_BASE_ADDRESS #1]. */
 	lcr_io_base = pci_resource_start(pci_dev, 1);
 	lcr_io_range = pci_resource_len(pci_dev, 1);
 
 	printk("comedi%d: local config registers at address 0x%4lx [0x%4lx]\n",
 		dev_minor, lcr_io_base, lcr_io_range);
 
-	// Read PCI6208 register base address [PCI_BASE_ADDRESS #2].
+	/*  Read PCI6208 register base address [PCI_BASE_ADDRESS #2]. */
 	io_base = pci_resource_start(pci_dev, 2);
 	io_range = pci_resource_end(pci_dev, 2) - io_base + 1;
 
@@ -382,10 +379,10 @@
 		dev_minor, io_base, io_range);
 
 	*io_base_ptr = io_base;
-	//devpriv->io_range = io_range;
-	//devpriv->is_valid=0;
-	//devpriv->lcr_io_base=lcr_io_base;
-	//devpriv->lcr_io_range=lcr_io_range;
+	/* devpriv->io_range = io_range; */
+	/* devpriv->is_valid=0; */
+	/* devpriv->lcr_io_base=lcr_io_base; */
+	/* devpriv->lcr_io_range=lcr_io_range; */
 
 	return 0;
 }
diff --git a/drivers/staging/comedi/drivers/adl_pci7296.c b/drivers/staging/comedi/drivers/adl_pci7296.c
index bd0f9ab..d2f23a8 100644
--- a/drivers/staging/comedi/drivers/adl_pci7296.c
+++ b/drivers/staging/comedi/drivers/adl_pci7296.c
@@ -39,7 +39,7 @@
 
 #include "comedi_pci.h"
 #include "8255.h"
-// #include "8253.h"
+/* #include "8253.h" */
 
 #define PORT1A 0
 #define PORT2A 4
@@ -64,16 +64,16 @@
 
 #define devpriv ((struct adl_pci7296_private *)dev->private)
 
-static int adl_pci7296_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int adl_pci7296_detach(struct comedi_device * dev);
+static int adl_pci7296_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int adl_pci7296_detach(struct comedi_device *dev);
 static struct comedi_driver driver_adl_pci7296 = {
-      driver_name:"adl_pci7296",
-      module:THIS_MODULE,
-      attach:adl_pci7296_attach,
-      detach:adl_pci7296_detach,
+	.driver_name = "adl_pci7296",
+	.module = THIS_MODULE,
+	.attach = adl_pci7296_attach,
+	.detach = adl_pci7296_detach,
 };
 
-static int adl_pci7296_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int adl_pci7296_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct pci_dev *pcidev;
 	struct comedi_subdevice *s;
@@ -115,7 +115,7 @@
 			dev->iobase = pci_resource_start(pcidev, 2);
 			printk("comedi: base addr %4lx\n", dev->iobase);
 
-			// four 8255 digital io subdevices
+			/*  four 8255 digital io subdevices */
 			s = dev->subdevices + 0;
 			subdev_8255_init(dev, s, NULL,
 				(unsigned long)(dev->iobase));
@@ -149,7 +149,7 @@
 	return -EIO;
 }
 
-static int adl_pci7296_detach(struct comedi_device * dev)
+static int adl_pci7296_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: pci7432: remove\n", dev->minor);
 
@@ -159,7 +159,7 @@
 		}
 		pci_dev_put(devpriv->pci_dev);
 	}
-	// detach four 8255 digital io subdevices
+	/*  detach four 8255 digital io subdevices */
 	if (dev->subdevices) {
 		subdev_8255_cleanup(dev, dev->subdevices + 0);
 		subdev_8255_cleanup(dev, dev->subdevices + 1);
diff --git a/drivers/staging/comedi/drivers/adl_pci7432.c b/drivers/staging/comedi/drivers/adl_pci7432.c
index a8f1715..78becbd 100644
--- a/drivers/staging/comedi/drivers/adl_pci7432.c
+++ b/drivers/staging/comedi/drivers/adl_pci7432.c
@@ -58,26 +58,26 @@
 
 #define devpriv ((struct adl_pci7432_private *)dev->private)
 
-static int adl_pci7432_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int adl_pci7432_detach(struct comedi_device * dev);
+static int adl_pci7432_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int adl_pci7432_detach(struct comedi_device *dev);
 static struct comedi_driver driver_adl_pci7432 = {
-      driver_name:"adl_pci7432",
-      module:THIS_MODULE,
-      attach:adl_pci7432_attach,
-      detach:adl_pci7432_detach,
+	.driver_name = "adl_pci7432",
+	.module = THIS_MODULE,
+	.attach = adl_pci7432_attach,
+	.detach = adl_pci7432_detach,
 };
 
 /* Digital IO */
 
-static int adl_pci7432_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int adl_pci7432_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int adl_pci7432_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int adl_pci7432_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 /*            */
 
-static int adl_pci7432_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int adl_pci7432_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct pci_dev *pcidev;
 	struct comedi_subdevice *s;
@@ -150,7 +150,7 @@
 	return -EIO;
 }
 
-static int adl_pci7432_detach(struct comedi_device * dev)
+static int adl_pci7432_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: pci7432: remove\n", dev->minor);
 
@@ -164,8 +164,8 @@
 	return 0;
 }
 
-static int adl_pci7432_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int adl_pci7432_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	printk("comedi: pci7432_do_insn_bits called\n");
 	printk("comedi: data0: %8x data1: %8x\n", data[0], data[1]);
@@ -184,8 +184,8 @@
 	return 2;
 }
 
-static int adl_pci7432_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int adl_pci7432_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	printk("comedi: pci7432_di_insn_bits called\n");
 	printk("comedi: data0: %8x data1: %8x\n", data[0], data[1]);
diff --git a/drivers/staging/comedi/drivers/adl_pci8164.c b/drivers/staging/comedi/drivers/adl_pci8164.c
index adf90be..2d7d68a 100644
--- a/drivers/staging/comedi/drivers/adl_pci8164.c
+++ b/drivers/staging/comedi/drivers/adl_pci8164.c
@@ -70,40 +70,40 @@
 
 #define devpriv ((struct adl_pci8164_private *)dev->private)
 
-static int adl_pci8164_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int adl_pci8164_detach(struct comedi_device * dev);
+static int adl_pci8164_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int adl_pci8164_detach(struct comedi_device *dev);
 static struct comedi_driver driver_adl_pci8164 = {
-      driver_name:"adl_pci8164",
-      module:THIS_MODULE,
-      attach:adl_pci8164_attach,
-      detach:adl_pci8164_detach,
+	.driver_name = "adl_pci8164",
+	.module = THIS_MODULE,
+	.attach = adl_pci8164_attach,
+	.detach = adl_pci8164_detach,
 };
 
-static int adl_pci8164_insn_read_msts(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int adl_pci8164_insn_read_msts(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int adl_pci8164_insn_read_ssts(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int adl_pci8164_insn_read_ssts(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int adl_pci8164_insn_read_buf0(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int adl_pci8164_insn_read_buf0(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int adl_pci8164_insn_read_buf1(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int adl_pci8164_insn_read_buf1(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int adl_pci8164_insn_write_cmd(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int adl_pci8164_insn_write_cmd(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int adl_pci8164_insn_write_otp(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int adl_pci8164_insn_write_otp(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int adl_pci8164_insn_write_buf0(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
+static int adl_pci8164_insn_write_buf0(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
 
-static int adl_pci8164_insn_write_buf1(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
+static int adl_pci8164_insn_write_buf1(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
 
-static int adl_pci8164_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int adl_pci8164_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct pci_dev *pcidev;
 	struct comedi_subdevice *s;
@@ -149,7 +149,7 @@
 			s->n_chan = 4;
 			s->maxdata = 0xffff;
 			s->len_chanlist = 4;
-			//s->range_table = &range_axis;
+			/* s->range_table = &range_axis; */
 			s->insn_read = adl_pci8164_insn_read_msts;
 			s->insn_write = adl_pci8164_insn_write_cmd;
 
@@ -159,7 +159,7 @@
 			s->n_chan = 4;
 			s->maxdata = 0xffff;
 			s->len_chanlist = 4;
-			//s->range_table = &range_axis;
+			/* s->range_table = &range_axis; */
 			s->insn_read = adl_pci8164_insn_read_ssts;
 			s->insn_write = adl_pci8164_insn_write_otp;
 
@@ -169,7 +169,7 @@
 			s->n_chan = 4;
 			s->maxdata = 0xffff;
 			s->len_chanlist = 4;
-			//s->range_table = &range_axis;
+			/* s->range_table = &range_axis; */
 			s->insn_read = adl_pci8164_insn_read_buf0;
 			s->insn_write = adl_pci8164_insn_write_buf0;
 
@@ -179,7 +179,7 @@
 			s->n_chan = 4;
 			s->maxdata = 0xffff;
 			s->len_chanlist = 4;
-			//s->range_table = &range_axis;
+			/* s->range_table = &range_axis; */
 			s->insn_read = adl_pci8164_insn_read_buf1;
 			s->insn_write = adl_pci8164_insn_write_buf1;
 
@@ -194,7 +194,7 @@
 	return -EIO;
 }
 
-static int adl_pci8164_detach(struct comedi_device * dev)
+static int adl_pci8164_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: pci8164: remove\n", dev->minor);
 
@@ -208,8 +208,16 @@
 	return 0;
 }
 
-static int adl_pci8164_insn_read_msts(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+/*
+ all the read commands are the same except for the addition a constant
+ * const to the data for inw()
+ */
+static void adl_pci8164_insn_read(struct comedi_device *dev,
+				  struct comedi_subdevice *s,
+				  struct comedi_insn *insn,
+				  unsigned int *data,
+				  char *action,
+				  unsigned short offset)
 {
 	int axis, axis_reg;
 	char *axisname;
@@ -238,127 +246,51 @@
 		axisname = "X";
 	}
 
-	data[0] = inw(dev->iobase + axis_reg + PCI8164_MSTS);
-	printk("comedi: pci8164 MSTS read -> %04X:%04X on axis %s\n", data[0],
+	data[0] = inw(dev->iobase + axis_reg + offset);
+	printk("comedi: pci8164 %s read -> %04X:%04X on axis %s\n", action, data[0],
 		data[1], axisname);
-
-	return 2;
 }
 
-static int adl_pci8164_insn_read_ssts(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int adl_pci8164_insn_read_msts(struct comedi_device *dev,
+				      struct comedi_subdevice *s,
+				      struct comedi_insn *insn,
+				      unsigned int *data)
 {
-	int axis, axis_reg;
-	char *axisname;
-
-	axis = CR_CHAN(insn->chanspec);
-
-	switch (axis) {
-	case 0:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-		break;
-	case 1:
-		axis_reg = PCI8164_AXIS_Y;
-		axisname = "Y";
-		break;
-	case 2:
-		axis_reg = PCI8164_AXIS_Z;
-		axisname = "Z";
-		break;
-	case 3:
-		axis_reg = PCI8164_AXIS_U;
-		axisname = "U";
-		break;
-	default:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-	}
-
-	data[0] = inw(dev->iobase + axis_reg + PCI8164_SSTS);
-	printk("comedi: pci8164 SSTS read -> %04X:%04X on axis %s\n", data[0],
-		data[1], axisname);
-
+	adl_pci8164_insn_read(dev, s, insn, data, "MSTS", PCI8164_MSTS);
 	return 2;
 }
 
-static int adl_pci8164_insn_read_buf0(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int adl_pci8164_insn_read_ssts(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	int axis, axis_reg;
-	char *axisname;
-
-	axis = CR_CHAN(insn->chanspec);
-
-	switch (axis) {
-	case 0:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-		break;
-	case 1:
-		axis_reg = PCI8164_AXIS_Y;
-		axisname = "Y";
-		break;
-	case 2:
-		axis_reg = PCI8164_AXIS_Z;
-		axisname = "Z";
-		break;
-	case 3:
-		axis_reg = PCI8164_AXIS_U;
-		axisname = "U";
-		break;
-	default:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-	}
-
-	data[0] = inw(dev->iobase + axis_reg + PCI8164_BUF0);
-	printk("comedi: pci8164 BUF0 read -> %04X:%04X on axis %s\n", data[0],
-		data[1], axisname);
-
+	adl_pci8164_insn_read(dev, s, insn, data, "SSTS", PCI8164_SSTS);
 	return 2;
 }
 
-static int adl_pci8164_insn_read_buf1(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int adl_pci8164_insn_read_buf0(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	int axis, axis_reg;
-
-	char *axisname;
-
-	axis = CR_CHAN(insn->chanspec);
-
-	switch (axis) {
-	case 0:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-		break;
-	case 1:
-		axis_reg = PCI8164_AXIS_Y;
-		axisname = "Y";
-		break;
-	case 2:
-		axis_reg = PCI8164_AXIS_Z;
-		axisname = "Z";
-		break;
-	case 3:
-		axis_reg = PCI8164_AXIS_U;
-		axisname = "U";
-		break;
-	default:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-	}
-
-	data[0] = inw(dev->iobase + axis_reg + PCI8164_BUF1);
-	printk("comedi: pci8164 BUF1 read -> %04X:%04X on axis %s\n", data[0],
-		data[1], axisname);
-
+	adl_pci8164_insn_read(dev, s, insn, data, "BUF0", PCI8164_BUF0);
 	return 2;
 }
 
-static int adl_pci8164_insn_write_cmd(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int adl_pci8164_insn_read_buf1(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
+{
+	adl_pci8164_insn_read(dev, s, insn, data, "BUF1", PCI8164_BUF1);
+	return 2;
+}
+
+/*
+ all the write commands are the same except for the addition a constant
+ * const to the data for outw()
+ */
+static void adl_pci8164_insn_out(struct comedi_device *dev,
+					struct comedi_subdevice *s,
+					struct comedi_insn *insn,
+					unsigned int *data,
+					char *action,
+					unsigned short offset)
 {
 	unsigned int axis, axis_reg;
 
@@ -388,124 +320,39 @@
 		axisname = "X";
 	}
 
-	outw(data[0], dev->iobase + axis_reg + PCI8164_CMD);
-	printk("comedi: pci8164 CMD write -> %04X:%04X on axis %s\n", data[0],
-		data[1], axisname);
+	outw(data[0], dev->iobase + axis_reg + offset);
 
+	printk("comedi: pci8164 %s write -> %04X:%04X on axis %s\n", action,
+	       data[0], data[1], axisname);
+
+}
+
+
+static int adl_pci8164_insn_write_cmd(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
+{
+	adl_pci8164_insn_out(dev, s, insn, data, "CMD", PCI8164_CMD);
 	return 2;
 }
 
-static int adl_pci8164_insn_write_otp(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int adl_pci8164_insn_write_otp(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	int axis, axis_reg;
-
-	char *axisname;
-
-	axis = CR_CHAN(insn->chanspec);
-
-	switch (axis) {
-	case 0:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-		break;
-	case 1:
-		axis_reg = PCI8164_AXIS_Y;
-		axisname = "Y";
-		break;
-	case 2:
-		axis_reg = PCI8164_AXIS_Z;
-		axisname = "Z";
-		break;
-	case 3:
-		axis_reg = PCI8164_AXIS_U;
-		axisname = "U";
-		break;
-	default:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-	}
-
-	outw(data[0], dev->iobase + axis_reg + PCI8164_OTP);
-	printk("comedi: pci8164 OTP write -> %04X:%04X on axis %s\n", data[0],
-		data[1], axisname);
-
+	adl_pci8164_insn_out(dev, s, insn, data, "OTP", PCI8164_OTP);
 	return 2;
 }
 
-static int adl_pci8164_insn_write_buf0(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int adl_pci8164_insn_write_buf0(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	int axis, axis_reg;
-
-	char *axisname;
-
-	axis = CR_CHAN(insn->chanspec);
-
-	switch (axis) {
-	case 0:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-		break;
-	case 1:
-		axis_reg = PCI8164_AXIS_Y;
-		axisname = "Y";
-		break;
-	case 2:
-		axis_reg = PCI8164_AXIS_Z;
-		axisname = "Z";
-		break;
-	case 3:
-		axis_reg = PCI8164_AXIS_U;
-		axisname = "U";
-		break;
-	default:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-	}
-
-	outw(data[0], dev->iobase + axis_reg + PCI8164_BUF0);
-	printk("comedi: pci8164 BUF0 write -> %04X:%04X on axis %s\n", data[0],
-		data[1], axisname);
-
+	adl_pci8164_insn_out(dev, s, insn, data, "BUF0", PCI8164_BUF0);
 	return 2;
 }
 
-static int adl_pci8164_insn_write_buf1(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int adl_pci8164_insn_write_buf1(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	int axis, axis_reg;
-
-	char *axisname;
-
-	axis = CR_CHAN(insn->chanspec);
-
-	switch (axis) {
-	case 0:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-		break;
-	case 1:
-		axis_reg = PCI8164_AXIS_Y;
-		axisname = "Y";
-		break;
-	case 2:
-		axis_reg = PCI8164_AXIS_Z;
-		axisname = "Z";
-		break;
-	case 3:
-		axis_reg = PCI8164_AXIS_U;
-		axisname = "U";
-		break;
-	default:
-		axis_reg = PCI8164_AXIS_X;
-		axisname = "X";
-	}
-
-	outw(data[0], dev->iobase + axis_reg + PCI8164_BUF1);
-	printk("comedi: pci8164 BUF1 write -> %04X:%04X on axis %s\n", data[0],
-		data[1], axisname);
-
+	adl_pci8164_insn_out(dev, s, insn, data, "BUF1", PCI8164_BUF1);
 	return 2;
 }
 
diff --git a/drivers/staging/comedi/drivers/adl_pci9111.c b/drivers/staging/comedi/drivers/adl_pci9111.c
index b4a61c5..0ac722e 100644
--- a/drivers/staging/comedi/drivers/adl_pci9111.c
+++ b/drivers/staging/comedi/drivers/adl_pci9111.c
@@ -77,6 +77,7 @@
 #include "../comedidev.h"
 
 #include <linux/delay.h>
+#include <linux/interrupt.h>
 
 #include "8253.h"
 #include "comedi_pci.h"
@@ -186,24 +187,24 @@
   (inb(PCI9111_IO_BASE+PCI9111_REGISTER_AD_MODE_INTERRUPT_READBACK)&0x0F)
 
 #define pci9111_trigger_and_autoscan_set(flags) \
-  outb(flags,PCI9111_IO_BASE+PCI9111_REGISTER_TRIGGER_MODE_CONTROL)
+  outb(flags, PCI9111_IO_BASE+PCI9111_REGISTER_TRIGGER_MODE_CONTROL)
 
 #define pci9111_interrupt_and_fifo_get() \
   ((inb(PCI9111_IO_BASE+PCI9111_REGISTER_AD_MODE_INTERRUPT_READBACK) >> 4) &0x03)
 
 #define pci9111_interrupt_and_fifo_set(flags) \
-  outb(flags,PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL)
+  outb(flags, PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL)
 
 #define pci9111_interrupt_clear() \
-  outb(0,PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CLEAR)
+  outb(0, PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CLEAR)
 
 #define pci9111_software_trigger() \
-  outb(0,PCI9111_IO_BASE+PCI9111_REGISTER_SOFTWARE_TRIGGER)
+  outb(0, PCI9111_IO_BASE+PCI9111_REGISTER_SOFTWARE_TRIGGER)
 
 #define pci9111_fifo_reset() \
-  outb(PCI9111_FFEN_SET_FIFO_ENABLE,PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL); \
-  outb(PCI9111_FFEN_SET_FIFO_DISABLE,PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL); \
-  outb(PCI9111_FFEN_SET_FIFO_ENABLE,PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL)
+  outb(PCI9111_FFEN_SET_FIFO_ENABLE, PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL); \
+  outb(PCI9111_FFEN_SET_FIFO_DISABLE, PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL); \
+  outb(PCI9111_FFEN_SET_FIFO_ENABLE, PCI9111_IO_BASE+PCI9111_REGISTER_INTERRUPT_CONTROL)
 
 #define pci9111_is_fifo_full() \
   ((inb(PCI9111_IO_BASE+PCI9111_REGISTER_RANGE_STATUS_READBACK)& \
@@ -218,13 +219,13 @@
     PCI9111_FIFO_EMPTY_MASK)==0)
 
 #define pci9111_ai_channel_set(channel) \
-  outb((channel)&PCI9111_CHANNEL_MASK,PCI9111_IO_BASE+PCI9111_REGISTER_AD_CHANNEL_CONTROL)
+  outb((channel)&PCI9111_CHANNEL_MASK, PCI9111_IO_BASE+PCI9111_REGISTER_AD_CHANNEL_CONTROL)
 
 #define pci9111_ai_channel_get() \
   inb(PCI9111_IO_BASE+PCI9111_REGISTER_AD_CHANNEL_READBACK)&PCI9111_CHANNEL_MASK
 
 #define pci9111_ai_range_set(range) \
-  outb((range)&PCI9111_RANGE_MASK,PCI9111_IO_BASE+PCI9111_REGISTER_INPUT_SIGNAL_RANGE)
+  outb((range)&PCI9111_RANGE_MASK, PCI9111_IO_BASE+PCI9111_REGISTER_INPUT_SIGNAL_RANGE)
 
 #define pci9111_ai_range_get() \
   inb(PCI9111_IO_BASE+PCI9111_REGISTER_RANGE_STATUS_READBACK)&PCI9111_RANGE_MASK
@@ -238,34 +239,34 @@
   ^ PCI9111_HR_AI_RESOLUTION_2_CMP_BIT
 
 #define pci9111_ao_set_data(data) \
-  outw(data&PCI9111_AO_RESOLUTION_MASK,PCI9111_IO_BASE+PCI9111_REGISTER_DA_OUTPUT)
+  outw(data&PCI9111_AO_RESOLUTION_MASK, PCI9111_IO_BASE+PCI9111_REGISTER_DA_OUTPUT)
 
 #define pci9111_di_get_bits() \
   inw(PCI9111_IO_BASE+PCI9111_REGISTER_DIGITAL_IO)
 
 #define pci9111_do_set_bits(bits) \
-  outw(bits,PCI9111_IO_BASE+PCI9111_REGISTER_DIGITAL_IO)
+  outw(bits, PCI9111_IO_BASE+PCI9111_REGISTER_DIGITAL_IO)
 
 #define pci9111_8254_control_set(flags) \
-  outb(flags,PCI9111_IO_BASE+PCI9111_REGISTER_8254_CONTROL)
+  outb(flags, PCI9111_IO_BASE+PCI9111_REGISTER_8254_CONTROL)
 
 #define pci9111_8254_counter_0_set(data) \
   outb(data & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_0); \
-  outb( (data >> 8) & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_0)
+  outb((data >> 8) & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_0)
 
 #define pci9111_8254_counter_1_set(data) \
   outb(data & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_1); \
-  outb( (data >> 8) & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_1)
+  outb((data >> 8) & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_1)
 
 #define pci9111_8254_counter_2_set(data) \
   outb(data & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_2); \
-  outb( (data >> 8) & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_2)
+  outb((data >> 8) & 0xFF, PCI9111_IO_BASE+PCI9111_REGISTER_8254_COUNTER_2)
 
 /*  Function prototypes */
 
-static int pci9111_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pci9111_detach(struct comedi_device * dev);
-static void pci9111_ai_munge(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pci9111_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pci9111_detach(struct comedi_device *dev);
+static void pci9111_ai_munge(struct comedi_device *dev, struct comedi_subdevice *s,
 	void *data, unsigned int num_bytes, unsigned int start_chan_index);
 
 static const struct comedi_lrange pci9111_hr_ai_range = {
@@ -308,27 +309,27 @@
 
 static const struct pci9111_board pci9111_boards[] = {
 	{
-	      name:	"pci9111_hr",
-	      device_id:PCI9111_HR_DEVICE_ID,
-	      ai_channel_nbr:PCI9111_AI_CHANNEL_NBR,
-	      ao_channel_nbr:PCI9111_AO_CHANNEL_NBR,
-	      ai_resolution:PCI9111_HR_AI_RESOLUTION,
-	      ai_resolution_mask:PCI9111_HR_AI_RESOLUTION_MASK,
-	      ao_resolution:PCI9111_AO_RESOLUTION,
-	      ao_resolution_mask:PCI9111_AO_RESOLUTION_MASK,
-	      ai_range_list:&pci9111_hr_ai_range,
-	      ao_range_list:&range_bipolar10,
-      ai_acquisition_period_min_ns:PCI9111_AI_ACQUISITION_PERIOD_MIN_NS}
+	.name = "pci9111_hr",
+	.device_id = PCI9111_HR_DEVICE_ID,
+	.ai_channel_nbr = PCI9111_AI_CHANNEL_NBR,
+	.ao_channel_nbr = PCI9111_AO_CHANNEL_NBR,
+	.ai_resolution = PCI9111_HR_AI_RESOLUTION,
+	.ai_resolution_mask = PCI9111_HR_AI_RESOLUTION_MASK,
+	.ao_resolution = PCI9111_AO_RESOLUTION,
+	.ao_resolution_mask = PCI9111_AO_RESOLUTION_MASK,
+	.ai_range_list = &pci9111_hr_ai_range,
+	.ao_range_list = &range_bipolar10,
+	.ai_acquisition_period_min_ns = PCI9111_AI_ACQUISITION_PERIOD_MIN_NS}
 };
 
 #define pci9111_board_nbr \
   (sizeof(pci9111_boards)/sizeof(struct pci9111_board))
 
 static struct comedi_driver pci9111_driver = {
-      driver_name:PCI9111_DRIVER_NAME,
-      module:THIS_MODULE,
-      attach:pci9111_attach,
-      detach:pci9111_detach,
+	.driver_name = PCI9111_DRIVER_NAME,
+	.module = THIS_MODULE,
+	.attach = pci9111_attach,
+	.detach = pci9111_detach,
 };
 
 COMEDI_PCI_INITCLEANUP(pci9111_driver, pci9111_pci_table);
@@ -405,7 +406,7 @@
 
 /*  8254 timer */
 
-static void pci9111_timer_set(struct comedi_device * dev)
+static void pci9111_timer_set(struct comedi_device *dev)
 {
 	pci9111_8254_control_set(PCI9111_8254_COUNTER_0 |
 		PCI9111_8254_READ_LOAD_LSB_MSB |
@@ -419,7 +420,7 @@
 		PCI9111_8254_READ_LOAD_LSB_MSB |
 		PCI9111_8254_MODE_2 | PCI9111_8254_BINARY_COUNTER);
 
-	comedi_udelay(1);
+	udelay(1);
 
 	pci9111_8254_counter_2_set(dev_private->timer_divisor_2);
 	pci9111_8254_counter_1_set(dev_private->timer_divisor_1);
@@ -431,7 +432,7 @@
 	external
 };
 
-static void pci9111_trigger_source_set(struct comedi_device * dev,
+static void pci9111_trigger_source_set(struct comedi_device *dev,
 	enum pci9111_trigger_sources source)
 {
 	int flags;
@@ -455,7 +456,7 @@
 	pci9111_trigger_and_autoscan_set(flags);
 }
 
-static void pci9111_pretrigger_set(struct comedi_device * dev, bool pretrigger)
+static void pci9111_pretrigger_set(struct comedi_device *dev, bool pretrigger)
 {
 	int flags;
 
@@ -467,7 +468,7 @@
 	pci9111_trigger_and_autoscan_set(flags);
 }
 
-static void pci9111_autoscan_set(struct comedi_device * dev, bool autoscan)
+static void pci9111_autoscan_set(struct comedi_device *dev, bool autoscan)
 {
 	int flags;
 
@@ -489,7 +490,7 @@
 	irq_on_external_trigger
 };
 
-static void pci9111_interrupt_source_set(struct comedi_device * dev,
+static void pci9111_interrupt_source_set(struct comedi_device *dev,
 	enum pci9111_ISC0_sources irq_0_source, enum pci9111_ISC1_sources irq_1_source)
 {
 	int flags;
@@ -513,7 +514,7 @@
 
 #undef AI_DO_CMD_DEBUG
 
-static int pci9111_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci9111_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	/*  Disable interrupts */
 
@@ -535,14 +536,14 @@
 
 /*  Test analog input command */
 
-#define pci9111_check_trigger_src(src,flags) \
+#define pci9111_check_trigger_src(src, flags) \
   tmp = src; \
   src &= flags; \
   if (!src || tmp != src) error++
 
 static int
-pci9111_ai_do_cmd_test(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_cmd * cmd)
+pci9111_ai_do_cmd_test(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_cmd *cmd)
 {
 	int tmp;
 	int error = 0;
@@ -740,7 +741,7 @@
 
 /*  Analog input command */
 
-static int pci9111_ai_do_cmd(struct comedi_device * dev, struct comedi_subdevice * subdevice)
+static int pci9111_ai_do_cmd(struct comedi_device *dev, struct comedi_subdevice *subdevice)
 {
 	struct comedi_cmd *async_cmd = &subdevice->async->cmd;
 
@@ -858,7 +859,7 @@
 	return 0;
 }
 
-static void pci9111_ai_munge(struct comedi_device * dev, struct comedi_subdevice * s,
+static void pci9111_ai_munge(struct comedi_device *dev, struct comedi_subdevice *s,
 	void *data, unsigned int num_bytes, unsigned int start_chan_index)
 {
 	unsigned int i, num_samples = num_bytes / sizeof(short);
@@ -884,7 +885,7 @@
 
 #undef INTERRUPT_DEBUG
 
-static irqreturn_t pci9111_interrupt(int irq, void *p_device PT_REGS_ARG)
+static irqreturn_t pci9111_interrupt(int irq, void *p_device)
 {
 	struct comedi_device *dev = p_device;
 	struct comedi_subdevice *subdevice = dev->read_subdev;
@@ -900,7 +901,7 @@
 
 	async = subdevice->async;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 
 	/*  Check if we are source of interrupt */
 	intcsr = inb(dev_private->lcr_io_base +
@@ -918,7 +919,7 @@
 						PLX9050_LINTI2_STATUS))))) {
 		/*  Not the source of the interrupt. */
 		/*  (N.B. not using PLX9050_SOFTWARE_INTERRUPT) */
-		comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+		spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 		return IRQ_NONE;
 	}
 
@@ -927,7 +928,7 @@
 		/*  Interrupt comes from fifo_half-full signal */
 
 		if (pci9111_is_fifo_full()) {
-			comedi_spin_unlock_irqrestore(&dev->spinlock,
+			spin_unlock_irqrestore(&dev->spinlock,
 				irq_flags);
 			comedi_error(dev, PCI9111_DRIVER_NAME " fifo overflow");
 			pci9111_interrupt_clear();
@@ -1027,7 +1028,7 @@
 
 	pci9111_interrupt_clear();
 
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 
 	comedi_event(dev, subdevice);
 
@@ -1042,8 +1043,8 @@
 
 #undef AI_INSN_DEBUG
 
-static int pci9111_ai_insn_read(struct comedi_device * dev,
-	struct comedi_subdevice * subdevice, struct comedi_insn * insn, unsigned int * data)
+static int pci9111_ai_insn_read(struct comedi_device *dev,
+	struct comedi_subdevice *subdevice, struct comedi_insn *insn, unsigned int *data)
 {
 	int resolution =
 		((struct pci9111_board *) dev->board_ptr)->ai_resolution;
@@ -1100,8 +1101,8 @@
 /*  Analog instant output */
 
 static int
-pci9111_ao_insn_write(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+pci9111_ao_insn_write(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 
@@ -1115,8 +1116,8 @@
 
 /*  Analog output readback */
 
-static int pci9111_ao_insn_read(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int pci9111_ao_insn_read(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 
@@ -1133,8 +1134,8 @@
 
 /*  Digital inputs */
 
-static int pci9111_di_insn_bits(struct comedi_device * dev,
-	struct comedi_subdevice * subdevice, struct comedi_insn * insn, unsigned int * data)
+static int pci9111_di_insn_bits(struct comedi_device *dev,
+	struct comedi_subdevice *subdevice, struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int bits;
 
@@ -1146,8 +1147,8 @@
 
 /*  Digital outputs */
 
-static int pci9111_do_insn_bits(struct comedi_device * dev,
-	struct comedi_subdevice * subdevice, struct comedi_insn * insn, unsigned int * data)
+static int pci9111_do_insn_bits(struct comedi_device *dev,
+	struct comedi_subdevice *subdevice, struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int bits;
 
@@ -1175,7 +1176,7 @@
 
 /*  Reset device */
 
-static int pci9111_reset(struct comedi_device * dev)
+static int pci9111_reset(struct comedi_device *dev)
 {
 	/*  Set trigger source to software */
 
@@ -1200,7 +1201,7 @@
 /*       - Register PCI device */
 /*       - Declare device driver capability */
 
-static int pci9111_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pci9111_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *subdevice;
 	unsigned long io_base, io_range, lcr_io_base, lcr_io_range;
@@ -1297,8 +1298,7 @@
 
 	dev->irq = 0;
 	if (pci_device->irq > 0) {
-		if (comedi_request_irq(pci_device->irq,
-				pci9111_interrupt,
+		if (request_irq(pci_device->irq, pci9111_interrupt,
 				IRQF_SHARED, PCI9111_DRIVER_NAME, dev) != 0) {
 			printk("comedi%d: unable to allocate irq  %u\n",
 				dev->minor, pci_device->irq);
@@ -1309,7 +1309,8 @@
 
 	/*  TODO: Add external multiplexer setup (according to option[2]). */
 
-	if ((error = alloc_subdevices(dev, 4)) < 0)
+	error = alloc_subdevices(dev, 4);
+	if (error < 0)
 		return error;
 
 	subdevice = dev->subdevices + 0;
@@ -1365,7 +1366,7 @@
 
 /*  Detach */
 
-static int pci9111_detach(struct comedi_device * dev)
+static int pci9111_detach(struct comedi_device *dev)
 {
 	/*  Reset device */
 
@@ -1377,7 +1378,7 @@
 	/*  Release previously allocated irq */
 
 	if (dev->irq != 0) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 
 	if (dev_private != 0 && dev_private->pci_device != 0) {
diff --git a/drivers/staging/comedi/drivers/adl_pci9118.c b/drivers/staging/comedi/drivers/adl_pci9118.c
index 278cf30..65f522b 100644
--- a/drivers/staging/comedi/drivers/adl_pci9118.c
+++ b/drivers/staging/comedi/drivers/adl_pci9118.c
@@ -66,6 +66,7 @@
 #include "../pci_ids.h"
 
 #include <linux/delay.h>
+#include <linux/interrupt.h>
 
 #include "amcc_s5933.h"
 #include "8253.h"
@@ -79,7 +80,7 @@
 
 #undef DPRINTK
 #ifdef PCI9118_EXTDEBUG
-#define DPRINTK(fmt, args...) rt_printk(fmt, ## args)
+#define DPRINTK(fmt, args...) printk(fmt, ## args)
 #else
 #define DPRINTK(fmt, args...)
 #endif
@@ -107,7 +108,7 @@
 #define PCI9118_INTSRC	0x38	/* R:   interrupt reason register */
 #define PCI9118_INTCTRL	0x38	/* W:   interrupt control register */
 
-// bits from A/D control register (PCI9118_ADCNTRL)
+/* bits from A/D control register (PCI9118_ADCNTRL) */
 #define AdControl_UniP	0x80	/* 1=bipolar, 0=unipolar */
 #define AdControl_Diff	0x40	/* 1=differential, 0= single end inputs */
 #define AdControl_SoftG	0x20	/* 1=8254 counter works, 0=counter stops */
@@ -117,7 +118,7 @@
 #define AdControl_Int	0x02	/* 1=enable INT, 0=disable */
 #define AdControl_Dma	0x01	/* 1=enable DMA, 0=disable */
 
-// bits from A/D function register (PCI9118_ADFUNC)
+/* bits from A/D function register (PCI9118_ADFUNC) */
 #define AdFunction_PDTrg	0x80	/* 1=positive, 0=negative digital trigger (only positive is correct) */
 #define AdFunction_PETrg	0x40	/* 1=positive, 0=negative external trigger (only positive is correct) */
 #define AdFunction_BSSH		0x20	/* 1=with sample&hold, 0=without */
@@ -127,7 +128,7 @@
 #define AdFunction_AM		0x02	/* 1=about trigger mode, 0=not about trigger */
 #define AdFunction_Start	0x01	/* 1=trigger start, 0=trigger stop */
 
-// bits from A/D status register (PCI9118_ADSTAT)
+/* bits from A/D status register (PCI9118_ADSTAT) */
 #define AdStatus_nFull	0x100	/* 0=FIFO full (fatal), 1=not full */
 #define AdStatus_nHfull	0x080	/* 0=FIFO half full, 1=FIFO not half full */
 #define AdStatus_nEpty	0x040	/* 0=FIFO empty, 1=FIFO not empty */
@@ -138,8 +139,8 @@
 #define AdStatus_ADOR	0x002	/* 1=A/D overrun (fatal) */
 #define AdStatus_ADrdy	0x001	/* 1=A/D already ready, 0=not ready */
 
-// bits for interrupt reason and control (PCI9118_INTSRC, PCI9118_INTCTRL)
-// 1=interrupt occur, enable source,  0=interrupt not occur, disable source
+/* bits for interrupt reason and control (PCI9118_INTSRC, PCI9118_INTCTRL) */
+/* 1=interrupt occur, enable source,  0=interrupt not occur, disable source */
 #define Int_Timer	0x08	/* timer interrupt */
 #define Int_About	0x04	/* about trigger complete */
 #define Int_Hfull	0x02	/* A/D FIFO hlaf full */
@@ -178,27 +179,27 @@
 
 #define PCI9118_BIPOLAR_RANGES	4	/* used for test on mixture of BIP/UNI ranges */
 
-static int pci9118_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pci9118_detach(struct comedi_device * dev);
+static int pci9118_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pci9118_detach(struct comedi_device *dev);
 
 struct boardtype {
-	const char *name;	// board name
-	int vendor_id;		// PCI vendor a device ID of card
+	const char *name;	/*  board name */
+	int vendor_id;		/*  PCI vendor a device ID of card */
 	int device_id;
-	int iorange_amcc;	// iorange for own S5933 region
-	int iorange_9118;	// pass thru card region size
-	int n_aichan;		// num of A/D chans
-	int n_aichand;		// num of A/D chans in diff mode
-	int mux_aichan;		// num of A/D chans with external multiplexor
-	int n_aichanlist;	// len of chanlist
-	int n_aochan;		// num of D/A chans
-	int ai_maxdata;		// resolution of A/D
-	int ao_maxdata;		// resolution of D/A
-	const struct comedi_lrange *rangelist_ai;	// rangelist for A/D
-	const struct comedi_lrange *rangelist_ao;	// rangelist for D/A
-	unsigned int ai_ns_min;	// max sample speed of card v ns
-	unsigned int ai_pacer_min;	// minimal pacer value (c1*c2 or c1 in burst)
-	int half_fifo_size;	// size of FIFO/2
+	int iorange_amcc;	/*  iorange for own S5933 region */
+	int iorange_9118;	/*  pass thru card region size */
+	int n_aichan;		/*  num of A/D chans */
+	int n_aichand;		/*  num of A/D chans in diff mode */
+	int mux_aichan;		/*  num of A/D chans with external multiplexor */
+	int n_aichanlist;	/*  len of chanlist */
+	int n_aochan;		/*  num of D/A chans */
+	int ai_maxdata;		/*  resolution of A/D */
+	int ao_maxdata;		/*  resolution of D/A */
+	const struct comedi_lrange *rangelist_ai;	/*  rangelist for A/D */
+	const struct comedi_lrange *rangelist_ao;	/*  rangelist for D/A */
+	unsigned int ai_ns_min;	/*  max sample speed of card v ns */
+	unsigned int ai_pacer_min;	/*  minimal pacer value (c1*c2 or c1 in burst) */
+	int half_fifo_size;	/*  size of FIFO/2 */
 
 };
 
@@ -230,75 +231,75 @@
 #define n_boardtypes (sizeof(boardtypes)/sizeof(struct boardtype))
 
 static struct comedi_driver driver_pci9118 = {
-      driver_name:"adl_pci9118",
-      module:THIS_MODULE,
-      attach:pci9118_attach,
-      detach:pci9118_detach,
-      num_names:n_boardtypes,
-      board_name:&boardtypes[0].name,
-      offset:sizeof(struct boardtype),
+	.driver_name = "adl_pci9118",
+	.module = THIS_MODULE,
+	.attach = pci9118_attach,
+	.detach = pci9118_detach,
+	.num_names = n_boardtypes,
+	.board_name = &boardtypes[0].name,
+	.offset = sizeof(struct boardtype),
 };
 
 COMEDI_PCI_INITCLEANUP(driver_pci9118, pci9118_pci_table);
 
 struct pci9118_private {
-	unsigned long iobase_a;	// base+size for AMCC chip
-	unsigned int master;	// master capable
-	struct pci_dev *pcidev;	// ptr to actual pcidev
-	unsigned int usemux;	// we want to use external multiplexor!
+	unsigned long iobase_a;	/*  base+size for AMCC chip */
+	unsigned int master;	/*  master capable */
+	struct pci_dev *pcidev;	/*  ptr to actual pcidev */
+	unsigned int usemux;	/*  we want to use external multiplexor! */
 #ifdef PCI9118_PARANOIDCHECK
-	unsigned short chanlist[PCI9118_CHANLEN + 1];	// list of scaned channel
-	unsigned char chanlistlen;	// number of scanlist
+	unsigned short chanlist[PCI9118_CHANLEN + 1];	/*  list of scaned channel */
+	unsigned char chanlistlen;	/*  number of scanlist */
 #endif
-	unsigned char AdControlReg;	// A/D control register
-	unsigned char IntControlReg;	// Interrupt control register
-	unsigned char AdFunctionReg;	// A/D function register
-	char valid;		// driver is ok
-	char ai_neverending;	// we do unlimited AI
-	unsigned int i8254_osc_base;	// frequence of onboard oscilator
-	unsigned int ai_do;	// what do AI? 0=nothing, 1 to 4 mode
-	unsigned int ai_act_scan;	// how many scans we finished
-	unsigned int ai_buf_ptr;	// data buffer ptr in samples
-	unsigned int ai_n_chan;	// how many channels is measured
-	unsigned int ai_n_scanlen;	// len of actual scanlist
-	unsigned int ai_n_realscanlen;	// what we must transfer for one outgoing scan include front/back adds
-	unsigned int ai_act_dmapos;	// position in actual real stream
-	unsigned int ai_add_front;	// how many channels we must add before scan to satisfy S&H?
-	unsigned int ai_add_back;	// how many channels we must add before scan to satisfy DMA?
-	unsigned int *ai_chanlist;	// actaul chanlist
+	unsigned char AdControlReg;	/*  A/D control register */
+	unsigned char IntControlReg;	/*  Interrupt control register */
+	unsigned char AdFunctionReg;	/*  A/D function register */
+	char valid;		/*  driver is ok */
+	char ai_neverending;	/*  we do unlimited AI */
+	unsigned int i8254_osc_base;	/*  frequence of onboard oscilator */
+	unsigned int ai_do;	/*  what do AI? 0=nothing, 1 to 4 mode */
+	unsigned int ai_act_scan;	/*  how many scans we finished */
+	unsigned int ai_buf_ptr;	/*  data buffer ptr in samples */
+	unsigned int ai_n_chan;	/*  how many channels is measured */
+	unsigned int ai_n_scanlen;	/*  len of actual scanlist */
+	unsigned int ai_n_realscanlen;	/*  what we must transfer for one outgoing scan include front/back adds */
+	unsigned int ai_act_dmapos;	/*  position in actual real stream */
+	unsigned int ai_add_front;	/*  how many channels we must add before scan to satisfy S&H? */
+	unsigned int ai_add_back;	/*  how many channels we must add before scan to satisfy DMA? */
+	unsigned int *ai_chanlist;	/*  actaul chanlist */
 	unsigned int ai_timer1;
 	unsigned int ai_timer2;
 	unsigned int ai_flags;
-	char ai12_startstop;	// measure can start/stop on external trigger
-	unsigned int ai_divisor1, ai_divisor2;	// divisors for start of measure on external start
+	char ai12_startstop;	/*  measure can start/stop on external trigger */
+	unsigned int ai_divisor1, ai_divisor2;	/*  divisors for start of measure on external start */
 	unsigned int ai_data_len;
 	short *ai_data;
-	short ao_data[2];	// data output buffer
-	unsigned int ai_scans;	// number of scans to do
-	char dma_doublebuf;	// we can use double buffring
-	unsigned int dma_actbuf;	// which buffer is used now
-	short *dmabuf_virt[2];	// pointers to begin of DMA buffer
-	unsigned long dmabuf_hw[2];	// hw address of DMA buff
-	unsigned int dmabuf_size[2];	// size of dma buffer in bytes
-	unsigned int dmabuf_use_size[2];	// which size we may now used for transfer
-	unsigned int dmabuf_used_size[2];	// which size was trully used
+	short ao_data[2];	/*  data output buffer */
+	unsigned int ai_scans;	/*  number of scans to do */
+	char dma_doublebuf;	/*  we can use double buffring */
+	unsigned int dma_actbuf;	/*  which buffer is used now */
+	short *dmabuf_virt[2];	/*  pointers to begin of DMA buffer */
+	unsigned long dmabuf_hw[2];	/*  hw address of DMA buff */
+	unsigned int dmabuf_size[2];	/*  size of dma buffer in bytes */
+	unsigned int dmabuf_use_size[2];	/*  which size we may now used for transfer */
+	unsigned int dmabuf_used_size[2];	/*  which size was trully used */
 	unsigned int dmabuf_panic_size[2];
-	unsigned int dmabuf_samples[2];	// size in samples
-	int dmabuf_pages[2];	// number of pages in buffer
-	unsigned char cnt0_users;	// bit field of 8254 CNT0 users (0-unused, 1-AO, 2-DI, 3-DO)
-	unsigned char exttrg_users;	// bit field of external trigger users (0-AI, 1-AO, 2-DI, 3-DO)
-	unsigned int cnt0_divisor;	// actual CNT0 divisor
-	void (*int_ai_func) (struct comedi_device *, struct comedi_subdevice *, unsigned short, unsigned int, unsigned short);	// ptr to actual interrupt AI function
-	unsigned char ai16bits;	// =1 16 bit card
-	unsigned char usedma;	// =1 use DMA transfer and not INT
-	unsigned char useeoshandle;	// =1 change WAKE_EOS DMA transfer to fit on every second
-	unsigned char usessh;	// =1 turn on S&H support
-	int softsshdelay;	// >0 use software S&H, numer is requested delay in ns
-	unsigned char softsshsample;	// polarity of S&H signal in sample state
-	unsigned char softsshhold;	// polarity of S&H signal in hold state
-	unsigned int ai_maskerr;	// which warning was printed
-	unsigned int ai_maskharderr;	// on which error bits stops
-	unsigned int ai_inttrig_start;	// TRIG_INT for start
+	unsigned int dmabuf_samples[2];	/*  size in samples */
+	int dmabuf_pages[2];	/*  number of pages in buffer */
+	unsigned char cnt0_users;	/*  bit field of 8254 CNT0 users (0-unused, 1-AO, 2-DI, 3-DO) */
+	unsigned char exttrg_users;	/*  bit field of external trigger users (0-AI, 1-AO, 2-DI, 3-DO) */
+	unsigned int cnt0_divisor;	/*  actual CNT0 divisor */
+	void (*int_ai_func) (struct comedi_device *, struct comedi_subdevice *, unsigned short, unsigned int, unsigned short);	/*  ptr to actual interrupt AI function */
+	unsigned char ai16bits;	/*  =1 16 bit card */
+	unsigned char usedma;	/*  =1 use DMA transfer and not INT */
+	unsigned char useeoshandle;	/*  =1 change WAKE_EOS DMA transfer to fit on every second */
+	unsigned char usessh;	/*  =1 turn on S&H support */
+	int softsshdelay;	/*  >0 use software S&H, numer is requested delay in ns */
+	unsigned char softsshsample;	/*  polarity of S&H signal in sample state */
+	unsigned char softsshhold;	/*  polarity of S&H signal in hold state */
+	unsigned int ai_maskerr;	/*  which warning was printed */
+	unsigned int ai_maskharderr;	/*  on which error bits stops */
+	unsigned int ai_inttrig_start;	/*  TRIG_INT for start */
 };
 
 #define devpriv ((struct pci9118_private *)dev->private)
@@ -308,53 +309,53 @@
 ==============================================================================
 */
 
-static int check_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static int check_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	int n_chan, unsigned int *chanlist, int frontadd, int backadd);
-static int setup_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static int setup_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	int n_chan, unsigned int *chanlist, int rot, int frontadd, int backadd,
 	int usedma, char eoshandle);
-static void start_pacer(struct comedi_device * dev, int mode, unsigned int divisor1,
+static void start_pacer(struct comedi_device *dev, int mode, unsigned int divisor1,
 	unsigned int divisor2);
-static int pci9118_reset(struct comedi_device * dev);
-static int pci9118_exttrg_add(struct comedi_device * dev, unsigned char source);
-static int pci9118_exttrg_del(struct comedi_device * dev, unsigned char source);
-static int pci9118_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static void pci9118_calc_divisors(char mode, struct comedi_device * dev,
-	struct comedi_subdevice * s, unsigned int *tim1, unsigned int *tim2,
+static int pci9118_reset(struct comedi_device *dev);
+static int pci9118_exttrg_add(struct comedi_device *dev, unsigned char source);
+static int pci9118_exttrg_del(struct comedi_device *dev, unsigned char source);
+static int pci9118_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static void pci9118_calc_divisors(char mode, struct comedi_device *dev,
+	struct comedi_subdevice *s, unsigned int *tim1, unsigned int *tim2,
 	unsigned int flags, int chans, unsigned int *div1, unsigned int *div2,
 	char usessh, unsigned int chnsshfront);
 
 /*
 ==============================================================================
 */
-static int pci9118_insn_read_ai(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci9118_insn_read_ai(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
 	int n, timeout;
 
 	devpriv->AdControlReg = AdControl_Int & 0xff;
 	devpriv->AdFunctionReg = AdFunction_PDTrg | AdFunction_PETrg;
-	outl(devpriv->AdFunctionReg, dev->iobase + PCI9118_ADFUNC);	// positive triggers, no S&H, no burst, burst stop, no post trigger, no about trigger, trigger stop
+	outl(devpriv->AdFunctionReg, dev->iobase + PCI9118_ADFUNC);	/*  positive triggers, no S&H, no burst, burst stop, no post trigger, no about trigger, trigger stop */
 
 	if (!setup_channel_list(dev, s, 1, &insn->chanspec, 0, 0, 0, 0, 0))
 		return -EINVAL;
 
-	outl(0, dev->iobase + PCI9118_DELFIFO);	// flush FIFO
+	outl(0, dev->iobase + PCI9118_DELFIFO);	/*  flush FIFO */
 
 	for (n = 0; n < insn->n; n++) {
 		outw(0, dev->iobase + PCI9118_SOFTTRG);	/* start conversion */
-		comedi_udelay(2);
+		udelay(2);
 		timeout = 100;
 		while (timeout--) {
 			if (inl(dev->iobase + PCI9118_ADSTAT) & AdStatus_ADrdy)
 				goto conv_finish;
-			comedi_udelay(1);
+			udelay(1);
 		}
 
 		comedi_error(dev, "A/D insn timeout");
 		data[n] = 0;
-		outl(0, dev->iobase + PCI9118_DELFIFO);	// flush FIFO
+		outl(0, dev->iobase + PCI9118_DELFIFO);	/*  flush FIFO */
 		return -ETIME;
 
 	      conv_finish:
@@ -369,7 +370,7 @@
 		}
 	}
 
-	outl(0, dev->iobase + PCI9118_DELFIFO);	// flush FIFO
+	outl(0, dev->iobase + PCI9118_DELFIFO);	/*  flush FIFO */
 	return n;
 
 }
@@ -377,8 +378,8 @@
 /*
 ==============================================================================
 */
-static int pci9118_insn_write_ao(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci9118_insn_write_ao(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, chanreg, ch;
 
@@ -400,8 +401,8 @@
 /*
 ==============================================================================
 */
-static int pci9118_insn_read_ao(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci9118_insn_read_ao(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, chan;
 
@@ -415,8 +416,8 @@
 /*
 ==============================================================================
 */
-static int pci9118_insn_bits_di(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci9118_insn_bits_di(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[1] = inl(dev->iobase + PCI9118_DI) & 0xf;
 
@@ -426,8 +427,8 @@
 /*
 ==============================================================================
 */
-static int pci9118_insn_bits_do(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci9118_insn_bits_do(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (data[0]) {
 		s->state &= ~data[0];
@@ -442,7 +443,7 @@
 /*
 ==============================================================================
 */
-static void interrupt_pci9118_ai_mode4_switch(struct comedi_device * dev)
+static void interrupt_pci9118_ai_mode4_switch(struct comedi_device *dev)
 {
 	devpriv->AdFunctionReg =
 		AdFunction_PDTrg | AdFunction_PETrg | AdFunction_AM;
@@ -456,8 +457,8 @@
 	outl(devpriv->AdFunctionReg, dev->iobase + PCI9118_ADFUNC);
 }
 
-static unsigned int defragment_dma_buffer(struct comedi_device * dev,
-	struct comedi_subdevice * s, short * dma_buffer, unsigned int num_samples)
+static unsigned int defragment_dma_buffer(struct comedi_device *dev,
+	struct comedi_subdevice *s, short *dma_buffer, unsigned int num_samples)
 {
 	unsigned int i = 0, j = 0;
 	unsigned int start_pos = devpriv->ai_add_front,
@@ -480,8 +481,8 @@
 /*
 ==============================================================================
 */
-static unsigned int move_block_from_dma(struct comedi_device * dev,
-	struct comedi_subdevice * s, short * dma_buffer, unsigned int num_samples)
+static unsigned int move_block_from_dma(struct comedi_device *dev,
+	struct comedi_subdevice *s, short *dma_buffer, unsigned int num_samples)
 {
 	unsigned int num_bytes;
 
@@ -501,8 +502,8 @@
 /*
 ==============================================================================
 */
-static char pci9118_decode_error_status(struct comedi_device * dev,
-	struct comedi_subdevice * s, unsigned char m)
+static char pci9118_decode_error_status(struct comedi_device *dev,
+	struct comedi_subdevice *s, unsigned char m)
 {
 	if (m & 0x100) {
 		comedi_error(dev, "A/D FIFO Full status (Fatal Error!)");
@@ -531,7 +532,7 @@
 	return 0;
 }
 
-static void pci9118_ai_munge(struct comedi_device * dev, struct comedi_subdevice * s,
+static void pci9118_ai_munge(struct comedi_device *dev, struct comedi_subdevice *s,
 	void *data, unsigned int num_bytes, unsigned int start_chan_index)
 {
 	unsigned int i, num_samples = num_bytes / sizeof(short);
@@ -551,8 +552,8 @@
 /*
 ==============================================================================
 */
-static void interrupt_pci9118_ai_onesample(struct comedi_device * dev,
-	struct comedi_subdevice * s, unsigned short int_adstat, unsigned int int_amcc,
+static void interrupt_pci9118_ai_onesample(struct comedi_device *dev,
+	struct comedi_subdevice *s, unsigned short int_adstat, unsigned int int_amcc,
 	unsigned short int_daq)
 {
 	register short sampl;
@@ -567,8 +568,8 @@
 
 #ifdef PCI9118_PARANOIDCHECK
 	if (devpriv->ai16bits == 0) {
-		if ((sampl & 0x000f) != devpriv->chanlist[s->async->cur_chan]) {	// data dropout!
-			rt_printk
+		if ((sampl & 0x000f) != devpriv->chanlist[s->async->cur_chan]) {	/*  data dropout! */
+			printk
 				("comedi: A/D  SAMPL - data dropout: received channel %d, expected %d!\n",
 				sampl & 0x000f,
 				devpriv->chanlist[s->async->cur_chan]);
@@ -598,7 +599,7 @@
 /*
 ==============================================================================
 */
-static void interrupt_pci9118_ai_dma(struct comedi_device * dev, struct comedi_subdevice * s,
+static void interrupt_pci9118_ai_dma(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned short int_adstat, unsigned int int_amcc,
 	unsigned short int_daq)
 {
@@ -621,14 +622,14 @@
 	}
 
 	if (int_adstat & devpriv->ai_maskerr)
-//      if (int_adstat & 0x106)
+/* if (int_adstat & 0x106) */
 		if (pci9118_decode_error_status(dev, s, int_adstat))
 			return;
 
-	samplesinbuf = devpriv->dmabuf_use_size[devpriv->dma_actbuf] >> 1;	// number of received real samples
-//      DPRINTK("dma_actbuf=%d\n",devpriv->dma_actbuf);
+	samplesinbuf = devpriv->dmabuf_use_size[devpriv->dma_actbuf] >> 1;	/*  number of received real samples */
+/* DPRINTK("dma_actbuf=%d\n",devpriv->dma_actbuf); */
 
-	if (devpriv->dma_doublebuf) {	// switch DMA buffers if is used double buffering
+	if (devpriv->dma_doublebuf) {	/*  switch DMA buffers if is used double buffering */
 		next_dma_buf = 1 - devpriv->dma_actbuf;
 		outl(devpriv->dmabuf_hw[next_dma_buf],
 			devpriv->iobase_a + AMCC_OP_REG_MWAR);
@@ -641,15 +642,15 @@
 	}
 
 	if (samplesinbuf) {
-		m = devpriv->ai_data_len >> 1;	// how many samples is to end of buffer
-//              DPRINTK("samps=%d m=%d %d %d\n",samplesinbuf,m,s->async->buf_int_count,s->async->buf_int_ptr);
+		m = devpriv->ai_data_len >> 1;	/*  how many samples is to end of buffer */
+/* DPRINTK("samps=%d m=%d %d %d\n",samplesinbuf,m,s->async->buf_int_count,s->async->buf_int_ptr); */
 		sampls = m;
 		move_block_from_dma(dev, s,
 			devpriv->dmabuf_virt[devpriv->dma_actbuf],
 			samplesinbuf);
-		m = m - sampls;	// m= how many samples was transfered
+		m = m - sampls;	/*  m= how many samples was transfered */
 	}
-//      DPRINTK("YYY\n");
+/* DPRINTK("YYY\n"); */
 
 	if (!devpriv->ai_neverending)
 		if (devpriv->ai_act_scan >= devpriv->ai_scans) {	/* all data sampled */
@@ -657,9 +658,9 @@
 			s->async->events |= COMEDI_CB_EOA;
 		}
 
-	if (devpriv->dma_doublebuf) {	// switch dma buffers
+	if (devpriv->dma_doublebuf) {	/*  switch dma buffers */
 		devpriv->dma_actbuf = 1 - devpriv->dma_actbuf;
-	} else {		// restart DMA if is not used double buffering
+	} else {		/*  restart DMA if is not used double buffering */
 		outl(devpriv->dmabuf_hw[0],
 			devpriv->iobase_a + AMCC_OP_REG_MWAR);
 		outl(devpriv->dmabuf_use_size[0],
@@ -674,36 +675,36 @@
 /*
 ==============================================================================
 */
-static irqreturn_t interrupt_pci9118(int irq, void *d PT_REGS_ARG)
+static irqreturn_t interrupt_pci9118(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	unsigned int int_daq = 0, int_amcc, int_adstat;
 
 	if (!dev->attached)
-		return IRQ_NONE;	// not fully initialized
+		return IRQ_NONE;	/*  not fully initialized */
 
-	int_daq = inl(dev->iobase + PCI9118_INTSRC) & 0xf;	// get IRQ reasons from card
-	int_amcc = inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR);	// get INT register from AMCC chip
+	int_daq = inl(dev->iobase + PCI9118_INTSRC) & 0xf;	/*  get IRQ reasons from card */
+	int_amcc = inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR);	/*  get INT register from AMCC chip */
 
-//      DPRINTK("INT daq=0x%01x amcc=0x%08x MWAR=0x%08x MWTC=0x%08x ADSTAT=0x%02x ai_do=%d\n", int_daq, int_amcc, inl(devpriv->iobase_a+AMCC_OP_REG_MWAR), inl(devpriv->iobase_a+AMCC_OP_REG_MWTC), inw(dev->iobase+PCI9118_ADSTAT)&0x1ff,devpriv->ai_do);
+/* DPRINTK("INT daq=0x%01x amcc=0x%08x MWAR=0x%08x MWTC=0x%08x ADSTAT=0x%02x ai_do=%d\n", int_daq, int_amcc, inl(devpriv->iobase_a+AMCC_OP_REG_MWAR), inl(devpriv->iobase_a+AMCC_OP_REG_MWTC), inw(dev->iobase+PCI9118_ADSTAT)&0x1ff,devpriv->ai_do); */
 
 	if ((!int_daq) && (!(int_amcc & ANY_S593X_INT)))
-		return IRQ_NONE;	// interrupt from other source
+		return IRQ_NONE;	/*  interrupt from other source */
 
-	outl(int_amcc | 0x00ff0000, devpriv->iobase_a + AMCC_OP_REG_INTCSR);	// shutdown IRQ reasons in AMCC
+	outl(int_amcc | 0x00ff0000, devpriv->iobase_a + AMCC_OP_REG_INTCSR);	/*  shutdown IRQ reasons in AMCC */
 
-	int_adstat = inw(dev->iobase + PCI9118_ADSTAT) & 0x1ff;	// get STATUS register
+	int_adstat = inw(dev->iobase + PCI9118_ADSTAT) & 0x1ff;	/*  get STATUS register */
 
 	if (devpriv->ai_do) {
 		if (devpriv->ai12_startstop)
-			if ((int_adstat & AdStatus_DTH) && (int_daq & Int_DTrg)) {	// start stop of measure
+			if ((int_adstat & AdStatus_DTH) && (int_daq & Int_DTrg)) {	/*  start stop of measure */
 				if (devpriv->ai12_startstop & START_AI_EXT) {
 					devpriv->ai12_startstop &=
 						~START_AI_EXT;
 					if (!(devpriv->ai12_startstop &
 							STOP_AI_EXT))
-						pci9118_exttrg_del(dev, EXTTRG_AI);	// deactivate EXT trigger
-					start_pacer(dev, devpriv->ai_do, devpriv->ai_divisor1, devpriv->ai_divisor2);	// start pacer
+						pci9118_exttrg_del(dev, EXTTRG_AI);	/*  deactivate EXT trigger */
+					start_pacer(dev, devpriv->ai_do, devpriv->ai_divisor1, devpriv->ai_divisor2);	/*  start pacer */
 					outl(devpriv->AdControlReg,
 						dev->iobase + PCI9118_ADCNTRL);
 				} else {
@@ -711,8 +712,8 @@
 						ai12_startstop & STOP_AI_EXT) {
 						devpriv->ai12_startstop &=
 							~STOP_AI_EXT;
-						pci9118_exttrg_del(dev, EXTTRG_AI);	// deactivate EXT trigger
-						devpriv->ai_neverending = 0;	//well, on next interrupt from DMA/EOC measure will stop
+						pci9118_exttrg_del(dev, EXTTRG_AI);	/*  deactivate EXT trigger */
+						devpriv->ai_neverending = 0;	/* well, on next interrupt from DMA/EOC measure will stop */
 					}
 				}
 			}
@@ -727,7 +728,7 @@
 /*
 ==============================================================================
 */
-static int pci9118_ai_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pci9118_ai_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum)
 {
 	if (trignum != devpriv->ai_inttrig_start)
@@ -751,8 +752,8 @@
 /*
 ==============================================================================
 */
-static int pci9118_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int pci9118_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp, divisor1, divisor2;
@@ -949,11 +950,11 @@
 
 	if (cmd->scan_begin_src == TRIG_TIMER) {
 		tmp = cmd->scan_begin_arg;
-//              rt_printk("S1 timer1=%u timer2=%u\n",cmd->scan_begin_arg,cmd->convert_arg);
+/* printk("S1 timer1=%u timer2=%u\n",cmd->scan_begin_arg,cmd->convert_arg); */
 		i8253_cascade_ns_to_timer(devpriv->i8254_osc_base, &divisor1,
 			&divisor2, &cmd->scan_begin_arg,
 			cmd->flags & TRIG_ROUND_MASK);
-//              rt_printk("S2 timer1=%u timer2=%u\n",cmd->scan_begin_arg,cmd->convert_arg);
+/* printk("S2 timer1=%u timer2=%u\n",cmd->scan_begin_arg,cmd->convert_arg); */
 		if (cmd->scan_begin_arg < this_board->ai_ns_min)
 			cmd->scan_begin_arg = this_board->ai_ns_min;
 		if (tmp != cmd->scan_begin_arg)
@@ -965,7 +966,7 @@
 		i8253_cascade_ns_to_timer(devpriv->i8254_osc_base, &divisor1,
 			&divisor2, &cmd->convert_arg,
 			cmd->flags & TRIG_ROUND_MASK);
-//              rt_printk("s1 timer1=%u timer2=%u\n",cmd->scan_begin_arg,cmd->convert_arg);
+/* printk("s1 timer1=%u timer2=%u\n",cmd->scan_begin_arg,cmd->convert_arg); */
 		if (cmd->convert_arg < this_board->ai_ns_min)
 			cmd->convert_arg = this_board->ai_ns_min;
 		if (tmp != cmd->convert_arg)
@@ -979,7 +980,7 @@
 					cmd->scan_begin_arg =
 						this_board->ai_ns_min *
 						(cmd->scan_end_arg + 2);
-//              rt_printk("s2 timer1=%u timer2=%u\n",cmd->scan_begin_arg,cmd->convert_arg);
+/* printk("s2 timer1=%u timer2=%u\n",cmd->scan_begin_arg,cmd->convert_arg); */
 					err++;
 				}
 			} else {
@@ -988,7 +989,7 @@
 					cmd->scan_begin_arg =
 						cmd->convert_arg *
 						cmd->chanlist_len;
-//              rt_printk("s3 timer1=%u timer2=%u\n",cmd->scan_begin_arg,cmd->convert_arg);
+/* printk("s3 timer1=%u timer2=%u\n",cmd->scan_begin_arg,cmd->convert_arg); */
 					err++;
 				}
 			}
@@ -1001,7 +1002,7 @@
 	if (cmd->chanlist)
 		if (!check_channel_list(dev, s, cmd->chanlist_len,
 				cmd->chanlist, 0, 0))
-			return 5;	// incorrect channels list
+			return 5;	/*  incorrect channels list */
 
 	return 0;
 }
@@ -1009,7 +1010,7 @@
 /*
 ==============================================================================
 */
-static int Compute_and_setup_dma(struct comedi_device * dev)
+static int Compute_and_setup_dma(struct comedi_device *dev)
 {
 	unsigned int dmalen0, dmalen1, i;
 
@@ -1018,32 +1019,32 @@
 	dmalen1 = devpriv->dmabuf_size[1];
 	DPRINTK("1 dmalen0=%d dmalen1=%d ai_data_len=%d\n", dmalen0, dmalen1,
 		devpriv->ai_data_len);
-	// isn't output buff smaller that our DMA buff?
+	/*  isn't output buff smaller that our DMA buff? */
 	if (dmalen0 > (devpriv->ai_data_len)) {
-		dmalen0 = devpriv->ai_data_len & ~3L;	// allign to 32bit down
+		dmalen0 = devpriv->ai_data_len & ~3L;	/*  allign to 32bit down */
 	}
 	if (dmalen1 > (devpriv->ai_data_len)) {
-		dmalen1 = devpriv->ai_data_len & ~3L;	// allign to 32bit down
+		dmalen1 = devpriv->ai_data_len & ~3L;	/*  allign to 32bit down */
 	}
 	DPRINTK("2 dmalen0=%d dmalen1=%d \n", dmalen0, dmalen1);
 
-	// we want wake up every scan?
+	/*  we want wake up every scan? */
 	if (devpriv->ai_flags & TRIG_WAKE_EOS) {
 		if (dmalen0 < (devpriv->ai_n_realscanlen << 1)) {
-			// uff, too short DMA buffer, disable EOS support!
+			/*  uff, too short DMA buffer, disable EOS support! */
 			devpriv->ai_flags &= (~TRIG_WAKE_EOS);
-			rt_printk
+			printk
 				("comedi%d: WAR: DMA0 buf too short, cann't support TRIG_WAKE_EOS (%d<%d)\n",
 				dev->minor, dmalen0,
 				devpriv->ai_n_realscanlen << 1);
 		} else {
-			// short first DMA buffer to one scan
+			/*  short first DMA buffer to one scan */
 			dmalen0 = devpriv->ai_n_realscanlen << 1;
 			DPRINTK("21 dmalen0=%d ai_n_realscanlen=%d useeoshandle=%d\n", dmalen0, devpriv->ai_n_realscanlen, devpriv->useeoshandle);
 			if (devpriv->useeoshandle)
 				dmalen0 += 2;
 			if (dmalen0 < 4) {
-				rt_printk
+				printk
 					("comedi%d: ERR: DMA0 buf len bug? (%d<4)\n",
 					dev->minor, dmalen0);
 				dmalen0 = 4;
@@ -1052,20 +1053,20 @@
 	}
 	if (devpriv->ai_flags & TRIG_WAKE_EOS) {
 		if (dmalen1 < (devpriv->ai_n_realscanlen << 1)) {
-			// uff, too short DMA buffer, disable EOS support!
+			/*  uff, too short DMA buffer, disable EOS support! */
 			devpriv->ai_flags &= (~TRIG_WAKE_EOS);
-			rt_printk
+			printk
 				("comedi%d: WAR: DMA1 buf too short, cann't support TRIG_WAKE_EOS (%d<%d)\n",
 				dev->minor, dmalen1,
 				devpriv->ai_n_realscanlen << 1);
 		} else {
-			// short second DMA buffer to one scan
+			/*  short second DMA buffer to one scan */
 			dmalen1 = devpriv->ai_n_realscanlen << 1;
 			DPRINTK("22 dmalen1=%d ai_n_realscanlen=%d useeoshandle=%d\n", dmalen1, devpriv->ai_n_realscanlen, devpriv->useeoshandle);
 			if (devpriv->useeoshandle)
 				dmalen1 -= 2;
 			if (dmalen1 < 4) {
-				rt_printk
+				printk
 					("comedi%d: ERR: DMA1 buf len bug? (%d<4)\n",
 					dev->minor, dmalen1);
 				dmalen1 = 4;
@@ -1074,26 +1075,26 @@
 	}
 
 	DPRINTK("3 dmalen0=%d dmalen1=%d \n", dmalen0, dmalen1);
-	// transfer without TRIG_WAKE_EOS
+	/*  transfer without TRIG_WAKE_EOS */
 	if (!(devpriv->ai_flags & TRIG_WAKE_EOS)) {
-		// if it's possible then allign DMA buffers to length of scan
+		/*  if it's possible then allign DMA buffers to length of scan */
 		i = dmalen0;
 		dmalen0 =
 			(dmalen0 / (devpriv->ai_n_realscanlen << 1)) *
 			(devpriv->ai_n_realscanlen << 1);
 		dmalen0 &= ~3L;
 		if (!dmalen0)
-			dmalen0 = i;	// uff. very long scan?
+			dmalen0 = i;	/*  uff. very long scan? */
 		i = dmalen1;
 		dmalen1 =
 			(dmalen1 / (devpriv->ai_n_realscanlen << 1)) *
 			(devpriv->ai_n_realscanlen << 1);
 		dmalen1 &= ~3L;
 		if (!dmalen1)
-			dmalen1 = i;	// uff. very long scan?
-		// if measure isn't neverending then test, if it whole fits into one or two DMA buffers
+			dmalen1 = i;	/*  uff. very long scan? */
+		/*  if measure isn't neverending then test, if it whole fits into one or two DMA buffers */
 		if (!devpriv->ai_neverending) {
-			// fits whole measure into one DMA buffer?
+			/*  fits whole measure into one DMA buffer? */
 			if (dmalen0 >
 				((devpriv->ai_n_realscanlen << 1) *
 					devpriv->ai_scans)) {
@@ -1104,7 +1105,7 @@
 				DPRINTK("3.1 dmalen0=%d dmalen1=%d \n", dmalen0,
 					dmalen1);
 				dmalen0 &= ~3L;
-			} else {	// fits whole measure into two DMA buffer?
+			} else {	/*  fits whole measure into two DMA buffer? */
 				if (dmalen1 >
 					((devpriv->ai_n_realscanlen << 1) *
 						devpriv->ai_scans - dmalen0))
@@ -1121,7 +1122,7 @@
 
 	DPRINTK("4 dmalen0=%d dmalen1=%d \n", dmalen0, dmalen1);
 
-	// these DMA buffer size we'll be used
+	/*  these DMA buffer size we'll be used */
 	devpriv->dma_actbuf = 0;
 	devpriv->dmabuf_use_size[0] = dmalen0;
 	devpriv->dmabuf_use_size[1] = dmalen1;
@@ -1143,18 +1144,18 @@
 	}
 #endif
 
-	outl(inl(devpriv->iobase_a + AMCC_OP_REG_MCSR) & (~EN_A2P_TRANSFERS), devpriv->iobase_a + AMCC_OP_REG_MCSR);	// stop DMA
+	outl(inl(devpriv->iobase_a + AMCC_OP_REG_MCSR) & (~EN_A2P_TRANSFERS), devpriv->iobase_a + AMCC_OP_REG_MCSR);	/*  stop DMA */
 	outl(devpriv->dmabuf_hw[0], devpriv->iobase_a + AMCC_OP_REG_MWAR);
 	outl(devpriv->dmabuf_use_size[0], devpriv->iobase_a + AMCC_OP_REG_MWTC);
-	// init DMA transfer
+	/*  init DMA transfer */
 	outl(0x00000000 | AINT_WRITE_COMPL,
 		devpriv->iobase_a + AMCC_OP_REG_INTCSR);
-//      outl(0x02000000|AINT_WRITE_COMPL, devpriv->iobase_a+AMCC_OP_REG_INTCSR);
+/* outl(0x02000000|AINT_WRITE_COMPL, devpriv->iobase_a+AMCC_OP_REG_INTCSR); */
 
 	outl(inl(devpriv->iobase_a +
 			AMCC_OP_REG_MCSR) | RESET_A2P_FLAGS | A2P_HI_PRIORITY |
 		EN_A2P_TRANSFERS, devpriv->iobase_a + AMCC_OP_REG_MCSR);
-	outl(inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR) | EN_A2P_TRANSFERS, devpriv->iobase_a + AMCC_OP_REG_INTCSR);	// allow bus mastering
+	outl(inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR) | EN_A2P_TRANSFERS, devpriv->iobase_a + AMCC_OP_REG_INTCSR);	/*  allow bus mastering */
 
 	DPRINTK("adl_pci9118 EDBG: END: Compute_and_setup_dma()\n");
 	return 0;
@@ -1163,7 +1164,7 @@
 /*
 ==============================================================================
 */
-static int pci9118_ai_docmd_sampl(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci9118_ai_docmd_sampl(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	DPRINTK("adl_pci9118 EDBG: BGN: pci9118_ai_docmd_sampl(%d,) [%d]\n",
 		dev->minor, devpriv->ai_do);
@@ -1186,17 +1187,17 @@
 		return -EIO;
 	};
 
-	devpriv->int_ai_func = interrupt_pci9118_ai_onesample;	//transfer function
+	devpriv->int_ai_func = interrupt_pci9118_ai_onesample;	/* transfer function */
 
 	if (devpriv->ai12_startstop)
-		pci9118_exttrg_add(dev, EXTTRG_AI);	// activate EXT trigger
+		pci9118_exttrg_add(dev, EXTTRG_AI);	/*  activate EXT trigger */
 
 	if ((devpriv->ai_do == 1) || (devpriv->ai_do == 2))
 		devpriv->IntControlReg |= Int_Timer;
 
 	devpriv->AdControlReg |= AdControl_Int;
 
-	outl(inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR) | 0x1f00, devpriv->iobase_a + AMCC_OP_REG_INTCSR);	// allow INT in AMCC
+	outl(inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR) | 0x1f00, devpriv->iobase_a + AMCC_OP_REG_INTCSR);	/*  allow INT in AMCC */
 
 	if (!(devpriv->ai12_startstop & (START_AI_EXT | START_AI_INT))) {
 		outl(devpriv->IntControlReg, dev->iobase + PCI9118_INTCTRL);
@@ -1216,7 +1217,7 @@
 /*
 ==============================================================================
 */
-static int pci9118_ai_docmd_dma(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci9118_ai_docmd_dma(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	DPRINTK("adl_pci9118 EDBG: BGN: pci9118_ai_docmd_dma(%d,) [%d,%d]\n",
 		dev->minor, devpriv->ai_do, devpriv->usedma);
@@ -1261,10 +1262,10 @@
 	};
 
 	if (devpriv->ai12_startstop) {
-		pci9118_exttrg_add(dev, EXTTRG_AI);	// activate EXT trigger
+		pci9118_exttrg_add(dev, EXTTRG_AI);	/*  activate EXT trigger */
 	}
 
-	devpriv->int_ai_func = interrupt_pci9118_ai_dma;	//transfer function
+	devpriv->int_ai_func = interrupt_pci9118_ai_dma;	/* transfer function */
 
 	outl(0x02000000 | AINT_WRITE_COMPL,
 		devpriv->iobase_a + AMCC_OP_REG_INTCSR);
@@ -1287,7 +1288,7 @@
 /*
 ==============================================================================
 */
-static int pci9118_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci9118_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	unsigned int addchans = 0;
@@ -1307,7 +1308,7 @@
 	devpriv->ai_add_back = 0;
 	devpriv->ai_maskerr = 0x10e;
 
-	// prepare for start/stop conditions
+	/*  prepare for start/stop conditions */
 	if (cmd->start_src == TRIG_EXT)
 		devpriv->ai12_startstop |= START_AI_EXT;
 	if (cmd->stop_src == TRIG_EXT) {
@@ -1334,19 +1335,19 @@
 		devpriv->ai_scans = 0;
 	}
 
-	// use sample&hold signal?
+	/*  use sample&hold signal? */
 	if (cmd->convert_src == TRIG_NOW) {
 		devpriv->usessh = 1;
-	}			// yes
+	}			/*  yes */
 	else {
 		devpriv->usessh = 0;
-	}			// no
+	}			/*  no */
 
 	DPRINTK("1 neverending=%d scans=%u usessh=%d ai_startstop=0x%2x\n",
 		devpriv->ai_neverending, devpriv->ai_scans, devpriv->usessh,
 		devpriv->ai12_startstop);
 
-	// use additional sample at end of every scan to satisty DMA 32 bit transfer?
+	/*  use additional sample at end of every scan to satisty DMA 32 bit transfer? */
 	devpriv->ai_add_front = 0;
 	devpriv->ai_add_back = 0;
 	devpriv->useeoshandle = 0;
@@ -1358,27 +1359,27 @@
 				devpriv->ai_add_back = 1;
 			}
 			if (cmd->convert_src == TRIG_TIMER) {
-				devpriv->usedma = 0;	// use INT transfer if scanlist have only one channel
+				devpriv->usedma = 0;	/*  use INT transfer if scanlist have only one channel */
 			}
 		}
 		if ((cmd->flags & TRIG_WAKE_EOS) &&
 			(devpriv->ai_n_scanlen & 1) &&
 			(devpriv->ai_n_scanlen > 1)) {
 			if (cmd->scan_begin_src == TRIG_FOLLOW) {
-				//vpriv->useeoshandle=1; // change DMA transfer block to fit EOS on every second call
-				devpriv->usedma = 0;	// XXX maybe can be corrected to use 16 bit DMA
-			} else {	// well, we must insert one sample to end of EOS to meet 32 bit transfer
+				/* vpriv->useeoshandle=1; // change DMA transfer block to fit EOS on every second call */
+				devpriv->usedma = 0;	/*  XXX maybe can be corrected to use 16 bit DMA */
+			} else {	/*  well, we must insert one sample to end of EOS to meet 32 bit transfer */
 				devpriv->ai_add_back = 1;
 			}
 		}
-	} else {		// interrupt transfer don't need any correction
+	} else {		/*  interrupt transfer don't need any correction */
 		devpriv->usedma = 0;
 	}
 
-	// we need software S&H signal? It add  two samples before every scan as minimum
+	/*  we need software S&H signal? It add  two samples before every scan as minimum */
 	if (devpriv->usessh && devpriv->softsshdelay) {
 		devpriv->ai_add_front = 2;
-		if ((devpriv->usedma == 1) && (devpriv->ai_add_back == 1)) {	// move it to front
+		if ((devpriv->usedma == 1) && (devpriv->ai_add_back == 1)) {	/*  move it to front */
 			devpriv->ai_add_front++;
 			devpriv->ai_add_back = 0;
 		}
@@ -1387,17 +1388,17 @@
 		addchans = devpriv->softsshdelay / cmd->convert_arg;
 		if (devpriv->softsshdelay % cmd->convert_arg)
 			addchans++;
-		if (addchans > (devpriv->ai_add_front - 1)) {	// uff, still short :-(
+		if (addchans > (devpriv->ai_add_front - 1)) {	/*  uff, still short :-( */
 			devpriv->ai_add_front = addchans + 1;
 			if (devpriv->usedma == 1)
 				if ((devpriv->ai_add_front +
 						devpriv->ai_n_chan +
 						devpriv->ai_add_back) & 1)
-					devpriv->ai_add_front++;	// round up to 32 bit
+					devpriv->ai_add_front++;	/*  round up to 32 bit */
 		}
-	}			// well, we now know what must be all added
+	}			/*  well, we now know what must be all added */
 
-	devpriv->ai_n_realscanlen =	// what we must take from card in real to have ai_n_scanlen on output?
+	devpriv->ai_n_realscanlen =	/*  what we must take from card in real to have ai_n_scanlen on output? */
 		(devpriv->ai_add_front + devpriv->ai_n_chan +
 		devpriv->ai_add_back) * (devpriv->ai_n_scanlen /
 		devpriv->ai_n_chan);
@@ -1408,7 +1409,7 @@
 		devpriv->ai_n_chan, devpriv->ai_add_back,
 		devpriv->ai_n_scanlen);
 
-	// check and setup channel list
+	/*  check and setup channel list */
 	if (!check_channel_list(dev, s, devpriv->ai_n_chan,
 			devpriv->ai_chanlist, devpriv->ai_add_front,
 			devpriv->ai_add_back))
@@ -1419,9 +1420,9 @@
 			devpriv->useeoshandle))
 		return -EINVAL;
 
-	// compute timers settings
-	// simplest way, fr=4Mhz/(tim1*tim2), channel manipulation without timers effect
-	if (((cmd->scan_begin_src == TRIG_FOLLOW) || (cmd->scan_begin_src == TRIG_EXT) || (cmd->scan_begin_src == TRIG_INT)) && (cmd->convert_src == TRIG_TIMER)) {	// both timer is used for one time
+	/*  compute timers settings */
+	/*  simplest way, fr=4Mhz/(tim1*tim2), channel manipulation without timers effect */
+	if (((cmd->scan_begin_src == TRIG_FOLLOW) || (cmd->scan_begin_src == TRIG_EXT) || (cmd->scan_begin_src == TRIG_INT)) && (cmd->convert_src == TRIG_TIMER)) {	/*  both timer is used for one time */
 		if (cmd->scan_begin_src == TRIG_EXT) {
 			devpriv->ai_do = 4;
 		} else {
@@ -1435,7 +1436,7 @@
 		devpriv->ai_timer2 = cmd->convert_arg;
 	}
 
-	if ((cmd->scan_begin_src == TRIG_TIMER) && ((cmd->convert_src == TRIG_TIMER) || (cmd->convert_src == TRIG_NOW))) {	// double timed action
+	if ((cmd->scan_begin_src == TRIG_TIMER) && ((cmd->convert_src == TRIG_TIMER) || (cmd->convert_src == TRIG_NOW))) {	/*  double timed action */
 		if (!devpriv->usedma) {
 			comedi_error(dev,
 				"cmd->scan_begin_src=TRIG_TIMER works only with bus mastering!");
@@ -1457,15 +1458,15 @@
 		devpriv->ai_do = 3;
 	}
 
-	start_pacer(dev, -1, 0, 0);	// stop pacer
+	start_pacer(dev, -1, 0, 0);	/*  stop pacer */
 
-	devpriv->AdControlReg = 0;	// bipolar, S.E., use 8254, stop 8354, internal trigger, soft trigger, disable DMA
+	devpriv->AdControlReg = 0;	/*  bipolar, S.E., use 8254, stop 8354, internal trigger, soft trigger, disable DMA */
 	outl(devpriv->AdControlReg, dev->iobase + PCI9118_ADCNTRL);
-	devpriv->AdFunctionReg = AdFunction_PDTrg | AdFunction_PETrg;	// positive triggers, no S&H, no burst, burst stop, no post trigger, no about trigger, trigger stop
+	devpriv->AdFunctionReg = AdFunction_PDTrg | AdFunction_PETrg;	/*  positive triggers, no S&H, no burst, burst stop, no post trigger, no about trigger, trigger stop */
 	outl(devpriv->AdFunctionReg, dev->iobase + PCI9118_ADFUNC);
-	comedi_udelay(1);
-	outl(0, dev->iobase + PCI9118_DELFIFO);	// flush FIFO
-	inl(dev->iobase + PCI9118_ADSTAT);	// flush A/D and INT status register
+	udelay(1);
+	outl(0, dev->iobase + PCI9118_DELFIFO);	/*  flush FIFO */
+	inl(dev->iobase + PCI9118_ADSTAT);	/*  flush A/D and INT status register */
 	inl(dev->iobase + PCI9118_INTSRC);
 
 	devpriv->ai_act_scan = 0;
@@ -1473,11 +1474,10 @@
 	s->async->cur_chan = 0;
 	devpriv->ai_buf_ptr = 0;
 
-	if (devpriv->usedma) {
+	if (devpriv->usedma)
 		ret = pci9118_ai_docmd_dma(dev, s);
-	} else {
+	else
 		ret = pci9118_ai_docmd_sampl(dev, s);
-	}
 
 	DPRINTK("adl_pci9118 EDBG: END: pci9118_ai_cmd()\n");
 	return ret;
@@ -1486,7 +1486,7 @@
 /*
 ==============================================================================
 */
-static int check_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static int check_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	int n_chan, unsigned int *chanlist, int frontadd, int backadd)
 {
 	unsigned int i, differencial = 0, bipolar = 0;
@@ -1497,7 +1497,7 @@
 		return 0;
 	}
 	if ((frontadd + n_chan + backadd) > s->len_chanlist) {
-		rt_printk
+		printk
 			("comedi%d: range/channel list is too long for actual configuration (%d>%d)!",
 			dev->minor, n_chan,
 			s->len_chanlist - frontadd - backadd);
@@ -1505,11 +1505,11 @@
 	}
 
 	if (CR_AREF(chanlist[0]) == AREF_DIFF)
-		differencial = 1;	// all input must be diff
+		differencial = 1;	/*  all input must be diff */
 	if (CR_RANGE(chanlist[0]) < PCI9118_BIPOLAR_RANGES)
-		bipolar = 1;	// all input must be bipolar
+		bipolar = 1;	/*  all input must be bipolar */
 	if (n_chan > 1)
-		for (i = 1; i < n_chan; i++) {	// check S.E/diff
+		for (i = 1; i < n_chan; i++) {	/*  check S.E/diff */
 			if ((CR_AREF(chanlist[i]) == AREF_DIFF) !=
 				(differencial)) {
 				comedi_error(dev,
@@ -1537,7 +1537,7 @@
 /*
 ==============================================================================
 */
-static int setup_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static int setup_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	int n_chan, unsigned int *chanlist, int rot, int frontadd, int backadd,
 	int usedma, char useeos)
 {
@@ -1552,27 +1552,27 @@
 	}
 
 	if (CR_AREF(chanlist[0]) == AREF_DIFF)
-		differencial = 1;	// all input must be diff
+		differencial = 1;	/*  all input must be diff */
 	if (CR_RANGE(chanlist[0]) < PCI9118_BIPOLAR_RANGES)
-		bipolar = 1;	// all input must be bipolar
+		bipolar = 1;	/*  all input must be bipolar */
 
-	// All is ok, so we can setup channel/range list
+	/*  All is ok, so we can setup channel/range list */
 
 	if (!bipolar) {
-		devpriv->AdControlReg |= AdControl_UniP;	// set unibipolar
+		devpriv->AdControlReg |= AdControl_UniP;	/*  set unibipolar */
 	} else {
-		devpriv->AdControlReg &= ((~AdControl_UniP) & 0xff);	// enable bipolar
+		devpriv->AdControlReg &= ((~AdControl_UniP) & 0xff);	/*  enable bipolar */
 	}
 
 	if (differencial) {
-		devpriv->AdControlReg |= AdControl_Diff;	// enable diff inputs
+		devpriv->AdControlReg |= AdControl_Diff;	/*  enable diff inputs */
 	} else {
-		devpriv->AdControlReg &= ((~AdControl_Diff) & 0xff);	// set single ended inputs
+		devpriv->AdControlReg &= ((~AdControl_Diff) & 0xff);	/*  set single ended inputs */
 	}
 
-	outl(devpriv->AdControlReg, dev->iobase + PCI9118_ADCNTRL);	// setup mode
+	outl(devpriv->AdControlReg, dev->iobase + PCI9118_ADCNTRL);	/*  setup mode */
 
-	outl(2, dev->iobase + PCI9118_SCANMOD);	// gods know why this sequence!
+	outl(2, dev->iobase + PCI9118_SCANMOD);	/*  gods know why this sequence! */
 	outl(0, dev->iobase + PCI9118_SCANMOD);
 	outl(1, dev->iobase + PCI9118_SCANMOD);
 
@@ -1582,12 +1582,12 @@
 		devpriv->chanlist[i] = 0x55aa;
 #endif
 
-	if (frontadd) {		// insert channels for S&H
+	if (frontadd) {		/*  insert channels for S&H */
 		ssh = devpriv->softsshsample;
 		DPRINTK("FA: %04x: ", ssh);
-		for (i = 0; i < frontadd; i++) {	// store range list to card
-			scanquad = CR_CHAN(chanlist[0]);	// get channel number;
-			gain = CR_RANGE(chanlist[0]);	// get gain number
+		for (i = 0; i < frontadd; i++) {	/*  store range list to card */
+			scanquad = CR_CHAN(chanlist[0]);	/*  get channel number; */
+			gain = CR_RANGE(chanlist[0]);	/*  get gain number */
 			scanquad |= ((gain & 0x03) << 8);
 			outl(scanquad | ssh, dev->iobase + PCI9118_GAIN);
 			DPRINTK("%02x ", scanquad | ssh);
@@ -1597,23 +1597,23 @@
 	}
 
 	DPRINTK("SL: ", ssh);
-	for (i = 0; i < n_chan; i++) {	// store range list to card
-		scanquad = CR_CHAN(chanlist[i]);	// get channel number;
+	for (i = 0; i < n_chan; i++) {	/*  store range list to card */
+		scanquad = CR_CHAN(chanlist[i]);	/*  get channel number; */
 #ifdef PCI9118_PARANOIDCHECK
 		devpriv->chanlist[i ^ usedma] = (scanquad & 0xf) << rot;
 #endif
-		gain = CR_RANGE(chanlist[i]);	// get gain number
+		gain = CR_RANGE(chanlist[i]);	/*  get gain number */
 		scanquad |= ((gain & 0x03) << 8);
 		outl(scanquad | ssh, dev->iobase + PCI9118_GAIN);
 		DPRINTK("%02x ", scanquad | ssh);
 	}
 	DPRINTK("\n ");
 
-	if (backadd) {		// insert channels for fit onto 32bit DMA
+	if (backadd) {		/*  insert channels for fit onto 32bit DMA */
 		DPRINTK("BA: %04x: ", ssh);
-		for (i = 0; i < backadd; i++) {	// store range list to card
-			scanquad = CR_CHAN(chanlist[0]);	// get channel number;
-			gain = CR_RANGE(chanlist[0]);	// get gain number
+		for (i = 0; i < backadd; i++) {	/*  store range list to card */
+			scanquad = CR_CHAN(chanlist[0]);	/*  get channel number; */
+			gain = CR_RANGE(chanlist[0]);	/*  get gain number */
 			scanquad |= ((gain & 0x03) << 8);
 			outl(scanquad | ssh, dev->iobase + PCI9118_GAIN);
 			DPRINTK("%02x ", scanquad | ssh);
@@ -1621,13 +1621,13 @@
 		DPRINTK("\n ");
 	}
 #ifdef PCI9118_PARANOIDCHECK
-	devpriv->chanlist[n_chan ^ usedma] = devpriv->chanlist[0 ^ usedma];	// for 32bit oerations
+	devpriv->chanlist[n_chan ^ usedma] = devpriv->chanlist[0 ^ usedma];	/*  for 32bit oerations */
 	if (useeos) {
-		for (i = 1; i < n_chan; i++) {	// store range list to card
+		for (i = 1; i < n_chan; i++) {	/*  store range list to card */
 			devpriv->chanlist[(n_chan + i) ^ usedma] =
 				(CR_CHAN(chanlist[i]) & 0xf) << rot;
 		}
-		devpriv->chanlist[(2 * n_chan) ^ usedma] = devpriv->chanlist[0 ^ usedma];	// for 32bit oerations
+		devpriv->chanlist[(2 * n_chan) ^ usedma] = devpriv->chanlist[0 ^ usedma];	/*  for 32bit oerations */
 		useeos = 2;
 	} else {
 		useeos = 1;
@@ -1640,19 +1640,19 @@
 	DPRINTK("\n ");
 #endif
 #endif
-	outl(0, dev->iobase + PCI9118_SCANMOD);	// close scan queue
-//      comedi_udelay(100);                             // important delay, or first sample will be cripled
+	outl(0, dev->iobase + PCI9118_SCANMOD);	/*  close scan queue */
+/* udelay(100);                               important delay, or first sample will be cripled */
 
 	DPRINTK("adl_pci9118 EDBG: END: setup_channel_list()\n");
-	return 1;		// we can serve this with scan logic
+	return 1;		/*  we can serve this with scan logic */
 }
 
 /*
 ==============================================================================
   calculate 8254 divisors if they are used for dual timing
 */
-static void pci9118_calc_divisors(char mode, struct comedi_device * dev,
-	struct comedi_subdevice * s, unsigned int *tim1, unsigned int *tim2,
+static void pci9118_calc_divisors(char mode, struct comedi_device *dev,
+	struct comedi_subdevice *s, unsigned int *tim1, unsigned int *tim2,
 	unsigned int flags, int chans, unsigned int *div1, unsigned int *div2,
 	char usessh, unsigned int chnsshfront)
 {
@@ -1672,17 +1672,17 @@
 			*tim2 = this_board->ai_ns_min;
 		DPRINTK("1 div1=%u div2=%u timer1=%u timer2=%u\n", *div1, *div2,
 			*tim1, *tim2);
-		*div1 = *tim2 / devpriv->i8254_osc_base;	// convert timer (burst)
+		*div1 = *tim2 / devpriv->i8254_osc_base;	/*  convert timer (burst) */
 		DPRINTK("2 div1=%u div2=%u timer1=%u timer2=%u\n", *div1, *div2,
 			*tim1, *tim2);
 		if (*div1 < this_board->ai_pacer_min)
 			*div1 = this_board->ai_pacer_min;
 		DPRINTK("3 div1=%u div2=%u timer1=%u timer2=%u\n", *div1, *div2,
 			*tim1, *tim2);
-		*div2 = *tim1 / devpriv->i8254_osc_base;	// scan timer
+		*div2 = *tim1 / devpriv->i8254_osc_base;	/*  scan timer */
 		DPRINTK("4 div1=%u div2=%u timer1=%u timer2=%u\n", *div1, *div2,
 			*tim1, *tim2);
-		*div2 = *div2 / *div1;	// major timer is c1*c2
+		*div2 = *div2 / *div1;	/*  major timer is c1*c2 */
 		DPRINTK("5 div1=%u div2=%u timer1=%u timer2=%u\n", *div1, *div2,
 			*tim1, *tim2);
 		if (*div2 < chans)
@@ -1690,9 +1690,9 @@
 		DPRINTK("6 div1=%u div2=%u timer1=%u timer2=%u\n", *div1, *div2,
 			*tim1, *tim2);
 
-		*tim2 = *div1 * devpriv->i8254_osc_base;	// real convert timer
+		*tim2 = *div1 * devpriv->i8254_osc_base;	/*  real convert timer */
 
-		if (usessh & (chnsshfront == 0))	// use BSSH signal
+		if (usessh & (chnsshfront == 0))	/*  use BSSH signal */
 			if (*div2 < (chans + 2))
 				*div2 = chans + 2;
 
@@ -1710,13 +1710,13 @@
 /*
 ==============================================================================
 */
-static void start_pacer(struct comedi_device * dev, int mode, unsigned int divisor1,
+static void start_pacer(struct comedi_device *dev, int mode, unsigned int divisor1,
 	unsigned int divisor2)
 {
 	outl(0x74, dev->iobase + PCI9118_CNTCTRL);
 	outl(0xb4, dev->iobase + PCI9118_CNTCTRL);
-//      outl(0x30, dev->iobase + PCI9118_CNTCTRL);
-	comedi_udelay(1);
+/* outl(0x30, dev->iobase + PCI9118_CNTCTRL); */
+	udelay(1);
 
 	if ((mode == 1) || (mode == 2) || (mode == 4)) {
 		outl(divisor2 & 0xff, dev->iobase + PCI9118_CNT2);
@@ -1729,29 +1729,29 @@
 /*
 ==============================================================================
 */
-static int pci9118_exttrg_add(struct comedi_device * dev, unsigned char source)
+static int pci9118_exttrg_add(struct comedi_device *dev, unsigned char source)
 {
 	if (source > 3)
-		return -1;	// incorrect source
+		return -1;	/*  incorrect source */
 	devpriv->exttrg_users |= (1 << source);
 	devpriv->IntControlReg |= Int_DTrg;
 	outl(devpriv->IntControlReg, dev->iobase + PCI9118_INTCTRL);
-	outl(inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR) | 0x1f00, devpriv->iobase_a + AMCC_OP_REG_INTCSR);	// allow INT in AMCC
+	outl(inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR) | 0x1f00, devpriv->iobase_a + AMCC_OP_REG_INTCSR);	/*  allow INT in AMCC */
 	return 0;
 }
 
 /*
 ==============================================================================
 */
-static int pci9118_exttrg_del(struct comedi_device * dev, unsigned char source)
+static int pci9118_exttrg_del(struct comedi_device *dev, unsigned char source)
 {
 	if (source > 3)
-		return -1;	// incorrect source
+		return -1;	/*  incorrect source */
 	devpriv->exttrg_users &= ~(1 << source);
-	if (!devpriv->exttrg_users) {	// shutdown ext trg intterrupts
+	if (!devpriv->exttrg_users) {	/*  shutdown ext trg intterrupts */
 		devpriv->IntControlReg &= ~Int_DTrg;
-		if (!devpriv->IntControlReg)	// all IRQ disabled
-			outl(inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR) & (~0x00001f00), devpriv->iobase_a + AMCC_OP_REG_INTCSR);	// disable int in AMCC
+		if (!devpriv->IntControlReg)	/*  all IRQ disabled */
+			outl(inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR) & (~0x00001f00), devpriv->iobase_a + AMCC_OP_REG_INTCSR);	/*  disable int in AMCC */
 		outl(devpriv->IntControlReg, dev->iobase + PCI9118_INTCTRL);
 	}
 	return 0;
@@ -1760,20 +1760,20 @@
 /*
 ==============================================================================
 */
-static int pci9118_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci9118_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	if (devpriv->usedma)
-		outl(inl(devpriv->iobase_a + AMCC_OP_REG_MCSR) & (~EN_A2P_TRANSFERS), devpriv->iobase_a + AMCC_OP_REG_MCSR);	// stop DMA
+		outl(inl(devpriv->iobase_a + AMCC_OP_REG_MCSR) & (~EN_A2P_TRANSFERS), devpriv->iobase_a + AMCC_OP_REG_MCSR);	/*  stop DMA */
 	pci9118_exttrg_del(dev, EXTTRG_AI);
-	start_pacer(dev, 0, 0, 0);	// stop 8254 counters
+	start_pacer(dev, 0, 0, 0);	/*  stop 8254 counters */
 	devpriv->AdFunctionReg = AdFunction_PDTrg | AdFunction_PETrg;
-	outl(devpriv->AdFunctionReg, dev->iobase + PCI9118_ADFUNC);	// positive triggers, no S&H, no burst, burst stop, no post trigger, no about trigger, trigger stop
+	outl(devpriv->AdFunctionReg, dev->iobase + PCI9118_ADFUNC);	/*  positive triggers, no S&H, no burst, burst stop, no post trigger, no about trigger, trigger stop */
 	devpriv->AdControlReg = 0x00;
-	outl(devpriv->AdControlReg, dev->iobase + PCI9118_ADCNTRL);	// bipolar, S.E., use 8254, stop 8354, internal trigger, soft trigger, disable INT and DMA
+	outl(devpriv->AdControlReg, dev->iobase + PCI9118_ADCNTRL);	/*  bipolar, S.E., use 8254, stop 8354, internal trigger, soft trigger, disable INT and DMA */
 	outl(0, dev->iobase + PCI9118_BURST);
 	outl(1, dev->iobase + PCI9118_SCANMOD);
-	outl(2, dev->iobase + PCI9118_SCANMOD);	// reset scan queue
-	outl(0, dev->iobase + PCI9118_DELFIFO);	// flush FIFO
+	outl(2, dev->iobase + PCI9118_SCANMOD);	/*  reset scan queue */
+	outl(0, dev->iobase + PCI9118_DELFIFO);	/*  flush FIFO */
 
 	devpriv->ai_do = 0;
 	devpriv->usedma = 0;
@@ -1787,7 +1787,7 @@
 	devpriv->dma_actbuf = 0;
 
 	if (!devpriv->IntControlReg)
-		outl(inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR) | 0x1f00, devpriv->iobase_a + AMCC_OP_REG_INTCSR);	// allow INT in AMCC
+		outl(inl(devpriv->iobase_a + AMCC_OP_REG_INTCSR) | 0x1f00, devpriv->iobase_a + AMCC_OP_REG_INTCSR);	/*  allow INT in AMCC */
 
 	return 0;
 }
@@ -1795,36 +1795,36 @@
 /*
 ==============================================================================
 */
-static int pci9118_reset(struct comedi_device * dev)
+static int pci9118_reset(struct comedi_device *dev)
 {
 	devpriv->IntControlReg = 0;
 	devpriv->exttrg_users = 0;
 	inl(dev->iobase + PCI9118_INTCTRL);
-	outl(devpriv->IntControlReg, dev->iobase + PCI9118_INTCTRL);	// disable interrupts source
+	outl(devpriv->IntControlReg, dev->iobase + PCI9118_INTCTRL);	/*  disable interrupts source */
 	outl(0x30, dev->iobase + PCI9118_CNTCTRL);
-//        outl(0xb4, dev->iobase + PCI9118_CNTCTRL);
-	start_pacer(dev, 0, 0, 0);	// stop 8254 counters
+/* outl(0xb4, dev->iobase + PCI9118_CNTCTRL); */
+	start_pacer(dev, 0, 0, 0);	/*  stop 8254 counters */
 	devpriv->AdControlReg = 0;
-	outl(devpriv->AdControlReg, dev->iobase + PCI9118_ADCNTRL);	// bipolar, S.E., use 8254, stop 8354, internal trigger, soft trigger, disable INT and DMA
+	outl(devpriv->AdControlReg, dev->iobase + PCI9118_ADCNTRL);	/*  bipolar, S.E., use 8254, stop 8354, internal trigger, soft trigger, disable INT and DMA */
 	outl(0, dev->iobase + PCI9118_BURST);
 	outl(1, dev->iobase + PCI9118_SCANMOD);
-	outl(2, dev->iobase + PCI9118_SCANMOD);	// reset scan queue
+	outl(2, dev->iobase + PCI9118_SCANMOD);	/*  reset scan queue */
 	devpriv->AdFunctionReg = AdFunction_PDTrg | AdFunction_PETrg;
-	outl(devpriv->AdFunctionReg, dev->iobase + PCI9118_ADFUNC);	// positive triggers, no S&H, no burst, burst stop, no post trigger, no about trigger, trigger stop
+	outl(devpriv->AdFunctionReg, dev->iobase + PCI9118_ADFUNC);	/*  positive triggers, no S&H, no burst, burst stop, no post trigger, no about trigger, trigger stop */
 
 	devpriv->ao_data[0] = 2047;
 	devpriv->ao_data[1] = 2047;
-	outl(devpriv->ao_data[0], dev->iobase + PCI9118_DA1);	// reset A/D outs to 0V
+	outl(devpriv->ao_data[0], dev->iobase + PCI9118_DA1);	/*  reset A/D outs to 0V */
 	outl(devpriv->ao_data[1], dev->iobase + PCI9118_DA2);
-	outl(0, dev->iobase + PCI9118_DO);	// reset digi outs to L
-	comedi_udelay(10);
+	outl(0, dev->iobase + PCI9118_DO);	/*  reset digi outs to L */
+	udelay(10);
 	inl(dev->iobase + PCI9118_AD_DATA);
-	outl(0, dev->iobase + PCI9118_DELFIFO);	// flush FIFO
-	outl(0, dev->iobase + PCI9118_INTSRC);	// remove INT requests
-	inl(dev->iobase + PCI9118_ADSTAT);	// flush A/D status register
-	inl(dev->iobase + PCI9118_INTSRC);	// flush INT requests
+	outl(0, dev->iobase + PCI9118_DELFIFO);	/*  flush FIFO */
+	outl(0, dev->iobase + PCI9118_INTSRC);	/*  remove INT requests */
+	inl(dev->iobase + PCI9118_ADSTAT);	/*  flush A/D status register */
+	inl(dev->iobase + PCI9118_INTSRC);	/*  flush INT requests */
 	devpriv->AdControlReg = 0;
-	outl(devpriv->AdControlReg, dev->iobase + PCI9118_ADCNTRL);	// bipolar, S.E., use 8254, stop 8354, internal trigger, soft trigger, disable INT and DMA
+	outl(devpriv->AdControlReg, dev->iobase + PCI9118_ADCNTRL);	/*  bipolar, S.E., use 8254, stop 8354, internal trigger, soft trigger, disable INT and DMA */
 
 	devpriv->cnt0_users = 0;
 	devpriv->exttrg_users = 0;
@@ -1835,7 +1835,7 @@
 /*
 ==============================================================================
 */
-static int pci9118_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pci9118_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int ret, pages, i;
@@ -1848,19 +1848,20 @@
 	unsigned char pci_bus, pci_slot, pci_func;
 	u16 u16w;
 
-	rt_printk("comedi%d: adl_pci9118: board=%s", dev->minor,
+	printk("comedi%d: adl_pci9118: board=%s", dev->minor,
 		this_board->name);
 
 	opt_bus = it->options[0];
 	opt_slot = it->options[1];
 	if (it->options[3] & 1) {
-		master = 0;	// user don't want use bus master
+		master = 0;	/*  user don't want use bus master */
 	} else {
 		master = 1;
 	}
 
-	if ((ret = alloc_private(dev, sizeof(struct pci9118_private))) < 0) {
-		rt_printk(" - Allocation failed!\n");
+	ret = alloc_private(dev, sizeof(struct pci9118_private));
+	if (ret < 0) {
+		printk(" - Allocation failed!\n");
 		return -ENOMEM;
 	}
 
@@ -1889,10 +1890,10 @@
 
 	if (!pcidev) {
 		if (opt_bus || opt_slot) {
-			rt_printk(" - Card at b:s %d:%d %s\n",
+			printk(" - Card at b:s %d:%d %s\n",
 				opt_bus, opt_slot, errstr);
 		} else {
-			rt_printk(" - Card %s\n", errstr);
+			printk(" - Card %s\n", errstr);
 		}
 		return -EIO;
 	}
@@ -1908,7 +1909,7 @@
 	iobase_a = pci_resource_start(pcidev, 0);
 	iobase_9 = pci_resource_start(pcidev, 2);
 
-	rt_printk(", b:s:f=%d:%d:%d, io=0x%4lx, 0x%4lx", pci_bus, pci_slot,
+	printk(", b:s:f=%d:%d:%d, io=0x%4lx, 0x%4lx", pci_bus, pci_slot,
 		pci_func, iobase_9, iobase_a);
 
 	dev->iobase = iobase_9;
@@ -1920,30 +1921,32 @@
 	pci9118_reset(dev);
 
 	if (it->options[3] & 2)
-		irq = 0;	// user don't want use IRQ
+		irq = 0;	/*  user don't want use IRQ */
 	if (irq > 0) {
-		if (comedi_request_irq(irq, interrupt_pci9118, IRQF_SHARED,
+		if (request_irq(irq, interrupt_pci9118, IRQF_SHARED,
 				"ADLink PCI-9118", dev)) {
-			rt_printk(", unable to allocate IRQ %d, DISABLING IT",
+			printk(", unable to allocate IRQ %d, DISABLING IT",
 				irq);
 			irq = 0;	/* Can't use IRQ */
 		} else {
-			rt_printk(", irq=%u", irq);
+			printk(", irq=%u", irq);
 		}
 	} else {
-		rt_printk(", IRQ disabled");
+		printk(", IRQ disabled");
 	}
 
 	dev->irq = irq;
 
-	if (master) {		// alloc DMA buffers
+	if (master) {		/*  alloc DMA buffers */
 		devpriv->dma_doublebuf = 0;
 		for (i = 0; i < 2; i++) {
-			for (pages = 4; pages >= 0; pages--)
-				if ((devpriv->dmabuf_virt[i] = (short *)
-						__get_free_pages(GFP_KERNEL,
-							pages)))
+			for (pages = 4; pages >= 0; pages--) {
+				devpriv->dmabuf_virt[i] =
+					(short *) __get_free_pages(GFP_KERNEL,
+								   pages);
+				if (devpriv->dmabuf_virt[i])
 					break;
+			}
 			if (devpriv->dmabuf_virt[i]) {
 				devpriv->dmabuf_pages[i] = pages;
 				devpriv->dmabuf_size[i] = PAGE_SIZE * pages;
@@ -1955,7 +1958,7 @@
 			}
 		}
 		if (!devpriv->dmabuf_virt[0]) {
-			rt_printk(", Can't allocate DMA buffer, DMA disabled!");
+			printk(", Can't allocate DMA buffer, DMA disabled!");
 			master = 0;
 		}
 
@@ -1964,26 +1967,26 @@
 
 	}
 
-	if ((devpriv->master = master)) {
-		rt_printk(", bus master");
-	} else {
-		rt_printk(", no bus master");
-	}
+	devpriv->master = master;
+	if (devpriv->master)
+		printk(", bus master");
+	else
+		printk(", no bus master");
 
 	devpriv->usemux = 0;
 	if (it->options[2] > 0) {
 		devpriv->usemux = it->options[2];
 		if (devpriv->usemux > 256)
-			devpriv->usemux = 256;	// max 256 channels!
+			devpriv->usemux = 256;	/*  max 256 channels! */
 		if (it->options[4] > 0)
 			if (devpriv->usemux > 128) {
-				devpriv->usemux = 128;	// max 128 channels with softare S&H!
+				devpriv->usemux = 128;	/*  max 128 channels with softare S&H! */
 			}
-		rt_printk(", ext. mux %d channels", devpriv->usemux);
+		printk(", ext. mux %d channels", devpriv->usemux);
 	}
 
 	devpriv->softsshdelay = it->options[4];
-	if (devpriv->softsshdelay < 0) {	// select sample&hold signal polarity
+	if (devpriv->softsshdelay < 0) {	/*  select sample&hold signal polarity */
 		devpriv->softsshdelay = -devpriv->softsshdelay;
 		devpriv->softsshsample = 0x80;
 		devpriv->softsshhold = 0x00;
@@ -1992,12 +1995,13 @@
 		devpriv->softsshhold = 0x80;
 	}
 
-	rt_printk(".\n");
+	printk(".\n");
 
 	pci_read_config_word(devpriv->pcidev, PCI_COMMAND, &u16w);
-	pci_write_config_word(devpriv->pcidev, PCI_COMMAND, u16w | 64);	// Enable parity check for parity error
+	pci_write_config_word(devpriv->pcidev, PCI_COMMAND, u16w | 64);	/*  Enable parity check for parity error */
 
-	if ((ret = alloc_subdevices(dev, 4)) < 0)
+	ret = alloc_subdevices(dev, 4);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -2052,9 +2056,9 @@
 	s->insn_bits = pci9118_insn_bits_do;
 
 	devpriv->valid = 1;
-	devpriv->i8254_osc_base = 250;	// 250ns=4MHz
-	devpriv->ai_maskharderr = 0x10a;	// default measure crash condition
-	if (it->options[5])	// disable some requested
+	devpriv->i8254_osc_base = 250;	/*  250ns=4MHz */
+	devpriv->ai_maskharderr = 0x10a;	/*  default measure crash condition */
+	if (it->options[5])	/*  disable some requested */
 		devpriv->ai_maskharderr &= ~it->options[5];
 
 	switch (this_board->ai_maxdata) {
@@ -2071,13 +2075,13 @@
 /*
 ==============================================================================
 */
-static int pci9118_detach(struct comedi_device * dev)
+static int pci9118_detach(struct comedi_device *dev)
 {
 	if (dev->private) {
 		if (devpriv->valid)
 			pci9118_reset(dev);
 		if (dev->irq)
-			comedi_free_irq(dev->irq, dev);
+			free_irq(dev->irq, dev);
 		if (devpriv->pcidev) {
 			if (dev->iobase) {
 				comedi_pci_disable(devpriv->pcidev);
diff --git a/drivers/staging/comedi/drivers/adq12b.c b/drivers/staging/comedi/drivers/adq12b.c
index 92f6285..d09d149 100644
--- a/drivers/staging/comedi/drivers/adq12b.c
+++ b/drivers/staging/comedi/drivers/adq12b.c
@@ -81,7 +81,7 @@
 
 #include "../comedidev.h"
 
-// address scheme (page 2.17 of the manual)
+/* address scheme (page 2.17 of the manual) */
 #define ADQ12B_SIZE     16
 
 #define ADQ12B_CTREG    0x00
@@ -94,24 +94,24 @@
 #define ADQ12B_CONT2    0x0e
 #define ADQ12B_COWORD   0x0f
 
-// mask of the bit at STINR to check end of conversion
+/* mask of the bit at STINR to check end of conversion */
 #define ADQ12B_EOC     0x20
 
 #define TIMEOUT        20
 
-// available ranges through the PGA gains
+/* available ranges through the PGA gains */
 static const struct comedi_lrange range_adq12b_ai_bipolar = { 4, {
-        BIP_RANGE( 5 ),
-        BIP_RANGE( 2 ),
-        BIP_RANGE( 1 ),
-        BIP_RANGE( 0.5 )
+        BIP_RANGE(5),
+        BIP_RANGE(2),
+        BIP_RANGE(1),
+        BIP_RANGE(0.5)
 }};
 
 static const struct comedi_lrange range_adq12b_ai_unipolar = { 4, {
-        UNI_RANGE( 5 ),
-        UNI_RANGE( 2 ),
-        UNI_RANGE( 1 ),
-        UNI_RANGE( 0.5 )
+        UNI_RANGE(5),
+        UNI_RANGE(2),
+        UNI_RANGE(1),
+        UNI_RANGE(0.5)
 }};
 
 
@@ -127,20 +127,20 @@
 
 static const struct adq12b_board adq12b_boards[] = {
         {
-        name:           "adq12b",
-        ai_se_chans:    16,
-        ai_diff_chans:  8,
-        ai_bits:        12,
-        di_chans:       5,
-        do_chans:       8
+	.name = "adq12b",
+	.ai_se_chans = 16,
+	.ai_diff_chans = 8,
+	.ai_bits = 12,
+	.di_chans = 5,
+	.do_chans = 8
         }
-// potentially, more adq-based deviced will be added
+/* potentially, more adq-based deviced will be added */
 /*,
-        name:           "adq12b",
-        ai_chans:       16,  // this is just for reference, hardcoded again later
-        ai_bits:        12,
-        di_chans:       8,
-        do_chans:       5
+	.name = "adq12b",
+	.ai_chans = 16,  // this is just for reference, hardcoded again later
+	.ai_bits = 12,
+	.di_chans = 8,
+	.do_chans = 5
         }*/
 };
 
@@ -162,7 +162,7 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int adq12b_attach(struct comedi_device *dev,struct comedi_devconfig *it);
+static int adq12b_attach(struct comedi_device *dev, struct comedi_devconfig *it);
 static int adq12b_detach(struct comedi_device *dev);
 static struct comedi_driver driver_adq12b={
         driver_name:    "adq12b",
@@ -171,12 +171,12 @@
         detach:         adq12b_detach,
         board_name:     &adq12b_boards[0].name,
         offset:         sizeof(struct adq12b_board),
-        num_names:      sizeof(adq12b_boards) / sizeof(struct adq12b_board),
+        num_names:      ARRAY_SIZE(adq12b_boards),
 };
 
-static int adq12b_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data);
-static int adq12b_di_insn_bits(struct comedi_device *dev,struct comedi_subdevice *s, struct comedi_insn *insn,unsigned int *data);
-static int adq12b_do_insn_bits(struct comedi_device *dev,struct comedi_subdevice *s, struct comedi_insn *insn,unsigned int *data);
+static int adq12b_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
+static int adq12b_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
+static int adq12b_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
 
 /*
  * Attach is called by the Comedi core to configure the driver
@@ -184,7 +184,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int adq12b_attach(struct comedi_device *dev,struct comedi_devconfig *it)
+static int adq12b_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
         struct comedi_subdevice *s;
         unsigned long iobase;
@@ -194,7 +194,7 @@
         unipolar = it->options[1];
         differential = it->options[2];
 
-        printk("comedi%d: adq12b called with options base=0x%03lx, %s and %s\n",dev->minor, iobase, (unipolar==1)?"unipolar":"bipolar", (differential==1)?"differential":"single-ended");
+        printk("comedi%d: adq12b called with options base=0x%03lx, %s and %s\n", dev->minor, iobase, (unipolar==1)?"unipolar":"bipolar", (differential==1) ? "differential" : "single-ended");
 
         /* if no address was specified, try the default 0x300 */
         if (iobase == 0) {
@@ -219,7 +219,7 @@
  * Allocate the private structure area.  alloc_private() is a
  * convenient macro defined in comedidev.h.
  */
-        if(alloc_private(dev, sizeof(struct adq12b_private)) < 0)
+        if (alloc_private (dev, sizeof (struct adq12b_private)) < 0)
           return -ENOMEM;
 
 /* fill in devpriv structure */
@@ -236,7 +236,7 @@
  * Allocate the subdevice structures.  alloc_subdevice() is a
  * convenient macro defined in comedidev.h.
  */
-        if(alloc_subdevices(dev, 3)<0)
+        if (alloc_subdevices (dev, 3)<0)
            return -ENOMEM;
 
         s = dev->subdevices+0;
@@ -304,7 +304,7 @@
 
         kfree(devpriv);
 
-        printk("comedi%d: adq12b: removed\n",dev->minor);
+        printk("comedi%d: adq12b: removed\n", dev->minor);
 
         return 0;
 }
@@ -314,7 +314,7 @@
  * mode.
  */
 
-static int adq12b_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)
+static int adq12b_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
         int n, i;
         int range, channel;
@@ -325,29 +325,29 @@
         channel = CR_CHAN(insn->chanspec);
         if (channel != devpriv->last_channel || range != devpriv->last_range) {
           outb((range << 4) | channel, dev->iobase + ADQ12B_CTREG);
-          comedi_udelay(50);   /* wait for the mux to settle */
+          udelay(50);   /* wait for the mux to settle */
         }
 
         /* trigger conversion */
         status = inb(dev->iobase + ADQ12B_ADLOW);
 
         /* convert n samples */
-        for(n=0; n < insn->n; n++){
+        for (n=0; n < insn->n; n++){
 
           /* wait for end of convertion */
 	  i = 0;
           do {
-//            comedi_udelay(1);
+/* udelay(1); */
 	    status = inb(dev->iobase + ADQ12B_STINR);
             status = status & ADQ12B_EOC;
           } while (status == 0 && ++i < TIMEOUT);
-//          } while (++i < 10);
+/* } while (++i < 10); */
 
           /* read data */
           hi = inb(dev->iobase + ADQ12B_ADHIG);
           lo = inb(dev->iobase + ADQ12B_ADLOW);
 
-          //rt_printk("debug: chan=%d range=%d status=%d hi=%d lo=%d\n", channel, range, status,  hi, lo);
+          /* printk("debug: chan=%d range=%d status=%d hi=%d lo=%d\n", channel, range, status,  hi, lo); */
           data[n] = (hi << 8) | lo;
 
         }
@@ -357,7 +357,7 @@
 }
 
 
-static int adq12b_di_insn_bits(struct comedi_device *dev,struct comedi_subdevice *s, 	struct comedi_insn *insn,unsigned int *data)
+static int adq12b_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s, 	struct comedi_insn *insn, unsigned int *data)
 {
 
         /* only bits 0-4 have information about digital inputs */
@@ -367,7 +367,7 @@
 }
 
 
-static int adq12b_do_insn_bits(struct comedi_device *dev,struct comedi_subdevice *s, 	struct comedi_insn *insn,unsigned int *data)
+static int adq12b_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s, 	struct comedi_insn *insn, unsigned int *data)
 {
         int channel;
 
diff --git a/drivers/staging/comedi/drivers/adv_pci1710.c b/drivers/staging/comedi/drivers/adv_pci1710.c
index 29eac74..0b56c14 100644
--- a/drivers/staging/comedi/drivers/adv_pci1710.c
+++ b/drivers/staging/comedi/drivers/adv_pci1710.c
@@ -41,6 +41,8 @@
           device will be used.
 */
 
+#include <linux/interrupt.h>
+
 #include "../comedidev.h"
 
 #include "comedi_pci.h"
@@ -56,12 +58,12 @@
 
 #undef DPRINTK
 #ifdef PCI171X_EXTDEBUG
-#define DPRINTK(fmt, args...) rt_printk(fmt, ## args)
+#define DPRINTK(fmt, args...) printk(fmt, ## args)
 #else
 #define DPRINTK(fmt, args...)
 #endif
 
-// hardware types of the cards
+/* hardware types of the cards */
 #define TYPE_PCI171X	0
 #define TYPE_PCI1713	2
 #define TYPE_PCI1720	3
@@ -87,12 +89,12 @@
 #define PCI171x_CNT2	28	/* R/W: 8254 couter 2 */
 #define PCI171x_CNTCTRL	30	/* W:   8254 counter control */
 
-// upper bits from status register (PCI171x_STATUS) (lower is same woth control reg)
+/* upper bits from status register (PCI171x_STATUS) (lower is same woth control reg) */
 #define	Status_FE	0x0100	/* 1=FIFO is empty */
 #define Status_FH	0x0200	/* 1=FIFO is half full */
 #define Status_FF	0x0400	/* 1=FIFO is full, fatal error */
 #define Status_IRQ	0x0800	/* 1=IRQ occured */
-// bits from control register (PCI171x_CONTROL)
+/* bits from control register (PCI171x_CONTROL) */
 #define Control_CNT0	0x0040	/* 1=CNT0 have external source, 0=have internal 100kHz source */
 #define Control_ONEFH	0x0020	/* 1=IRQ on FIFO is half full, 0=every sample */
 #define Control_IRQEN	0x0010	/* 1=enable IRQ */
@@ -100,7 +102,7 @@
 #define Control_EXT	0x0004	/* 1=external trigger source */
 #define Control_PACER	0x0002	/* 1=enable internal 8254 trigger source */
 #define Control_SW	0x0001	/* 1=enable software trigger source */
-// bits from counter control register (PCI171x_CNTCTRL)
+/* bits from counter control register (PCI171x_CNTCTRL) */
 #define Counter_BCD     0x0001	/* 0 = binary counter, 1 = BCD counter */
 #define Counter_M0      0x0002	/* M0-M2 select modes 0-5 */
 #define Counter_M1      0x0004	/* 000 = mode 0, 010 = mode 2 ... */
@@ -118,7 +120,7 @@
 #define PCI1720_SYNCOUT	 9	/* W:   D/A synchronized output register */
 #define PCI1720_SYNCONT	15	/* R/W: D/A synchronized control */
 
-// D/A synchronized control (PCI1720_SYNCONT)
+/* D/A synchronized control (PCI1720_SYNCONT) */
 #define Syncont_SC0	 1	/* set synchronous output mode */
 
 static const struct comedi_lrange range_pci1710_3 = { 9, {
@@ -182,28 +184,28 @@
 	}
 };
 
-static int pci1710_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pci1710_detach(struct comedi_device * dev);
+static int pci1710_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pci1710_detach(struct comedi_device *dev);
 
 struct boardtype {
-	const char *name;	// board name
+	const char *name;	/*  board name */
 	int device_id;
-	int iorange;		// I/O range len
-	char have_irq;		// 1=card support IRQ
-	char cardtype;		// 0=1710& co. 2=1713, ...
-	int n_aichan;		// num of A/D chans
-	int n_aichand;		// num of A/D chans in diff mode
-	int n_aochan;		// num of D/A chans
-	int n_dichan;		// num of DI chans
-	int n_dochan;		// num of DO chans
-	int n_counter;		// num of counters
-	int ai_maxdata;		// resolution of A/D
-	int ao_maxdata;		// resolution of D/A
-	const struct comedi_lrange *rangelist_ai;	// rangelist for A/D
-	const char *rangecode_ai;	// range codes for programming
-	const struct comedi_lrange *rangelist_ao;	// rangelist for D/A
-	unsigned int ai_ns_min;	// max sample speed of card v ns
-	unsigned int fifo_half_size;	// size of FIFO/2
+	int iorange;		/*  I/O range len */
+	char have_irq;		/*  1=card support IRQ */
+	char cardtype;		/*  0=1710& co. 2=1713, ... */
+	int n_aichan;		/*  num of A/D chans */
+	int n_aichand;		/*  num of A/D chans in diff mode */
+	int n_aochan;		/*  num of D/A chans */
+	int n_dichan;		/*  num of DI chans */
+	int n_dochan;		/*  num of DO chans */
+	int n_counter;		/*  num of counters */
+	int ai_maxdata;		/*  resolution of A/D */
+	int ao_maxdata;		/*  resolution of D/A */
+	const struct comedi_lrange *rangelist_ai;	/*  rangelist for A/D */
+	const char *rangecode_ai;	/*  range codes for programming */
+	const struct comedi_lrange *rangelist_ao;	/*  rangelist for D/A */
+	unsigned int ai_ns_min;	/*  max sample speed of card v ns */
+	unsigned int fifo_half_size;	/*  size of FIFO/2 */
 };
 
 static DEFINE_PCI_DEVICE_TABLE(pci1710_pci_table) = {
@@ -250,7 +252,7 @@
 		16, 0, 0, 16, 16, 0, 0x0fff, 0x0000,
 		&range_pci17x1, range_codes_pci17x1, NULL,
 		10000, 512},
-	// dummy entry corresponding to driver name
+	/*  dummy entry corresponding to driver name */
 	{.name = DRV_NAME},
 };
 
@@ -267,34 +269,34 @@
 };
 
 struct pci1710_private {
-	struct pci_dev *pcidev;	// ptr to PCI device
-	char valid;		// card is usable
-	char neverending_ai;	// we do unlimited AI
-	unsigned int CntrlReg;	// Control register
-	unsigned int i8254_osc_base;	// frequence of onboard oscilator
-	unsigned int ai_do;	// what do AI? 0=nothing, 1 to 4 mode
-	unsigned int ai_act_scan;	// how many scans we finished
-	unsigned int ai_act_chan;	// actual position in actual scan
-	unsigned int ai_buf_ptr;	// data buffer ptr in samples
-	unsigned char ai_eos;	// 1=EOS wake up
+	struct pci_dev *pcidev;	/*  ptr to PCI device */
+	char valid;		/*  card is usable */
+	char neverending_ai;	/*  we do unlimited AI */
+	unsigned int CntrlReg;	/*  Control register */
+	unsigned int i8254_osc_base;	/*  frequence of onboard oscilator */
+	unsigned int ai_do;	/*  what do AI? 0=nothing, 1 to 4 mode */
+	unsigned int ai_act_scan;	/*  how many scans we finished */
+	unsigned int ai_act_chan;	/*  actual position in actual scan */
+	unsigned int ai_buf_ptr;	/*  data buffer ptr in samples */
+	unsigned char ai_eos;	/*  1=EOS wake up */
 	unsigned char ai_et;
 	unsigned int ai_et_CntrlReg;
 	unsigned int ai_et_MuxVal;
 	unsigned int ai_et_div1, ai_et_div2;
-	unsigned int act_chanlist[32];	// list of scaned channel
-	unsigned char act_chanlist_len;	// len of scanlist
-	unsigned char act_chanlist_pos;	// actual position in MUX list
-	unsigned char da_ranges;	// copy of D/A outpit range register
-	unsigned int ai_scans;	// len of scanlist
-	unsigned int ai_n_chan;	// how many channels is measured
-	unsigned int *ai_chanlist;	// actaul chanlist
-	unsigned int ai_flags;	// flaglist
-	unsigned int ai_data_len;	// len of data buffer
-	short *ai_data;	// data buffer
-	unsigned int ai_timer1;	// timers
+	unsigned int act_chanlist[32];	/*  list of scaned channel */
+	unsigned char act_chanlist_len;	/*  len of scanlist */
+	unsigned char act_chanlist_pos;	/*  actual position in MUX list */
+	unsigned char da_ranges;	/*  copy of D/A outpit range register */
+	unsigned int ai_scans;	/*  len of scanlist */
+	unsigned int ai_n_chan;	/*  how many channels is measured */
+	unsigned int *ai_chanlist;	/*  actaul chanlist */
+	unsigned int ai_flags;	/*  flaglist */
+	unsigned int ai_data_len;	/*  len of data buffer */
+	short *ai_data;	/*  data buffer */
+	unsigned int ai_timer1;	/*  timers */
 	unsigned int ai_timer2;
-	short ao_data[4];	// data output buffer
-	unsigned int cnt0_write_wait;	// after a write, wait for update of the internal state
+	short ao_data[4];	/*  data output buffer */
+	unsigned int cnt0_write_wait;	/*  after a write, wait for update of the internal state */
 };
 
 #define devpriv ((struct pci1710_private *)dev->private)
@@ -304,16 +306,16 @@
 ==============================================================================
 */
 
-static int check_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static int check_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int *chanlist, unsigned int n_chan);
-static void setup_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static void setup_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int *chanlist, unsigned int n_chan, unsigned int seglen);
-static void start_pacer(struct comedi_device * dev, int mode, unsigned int divisor1,
+static void start_pacer(struct comedi_device *dev, int mode, unsigned int divisor1,
 	unsigned int divisor2);
-static int pci1710_reset(struct comedi_device * dev);
-static int pci171x_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
+static int pci1710_reset(struct comedi_device *dev);
+static int pci171x_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
 
-static const unsigned int muxonechan[] = { 0x0000, 0x0101, 0x0202, 0x0303, 0x0404, 0x0505, 0x0606, 0x0707,	// used for gain list programming
+static const unsigned int muxonechan[] = { 0x0000, 0x0101, 0x0202, 0x0303, 0x0404, 0x0505, 0x0606, 0x0707,	/*  used for gain list programming */
 	0x0808, 0x0909, 0x0a0a, 0x0b0b, 0x0c0c, 0x0d0d, 0x0e0e, 0x0f0f,
 	0x1010, 0x1111, 0x1212, 0x1313, 0x1414, 0x1515, 0x1616, 0x1717,
 	0x1818, 0x1919, 0x1a1a, 0x1b1b, 0x1c1c, 0x1d1d, 0x1e1e, 0x1f1f
@@ -322,8 +324,8 @@
 /*
 ==============================================================================
 */
-static int pci171x_insn_read_ai(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci171x_insn_read_ai(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, timeout;
 #ifdef PCI171x_PARANOIDCHECK
@@ -332,7 +334,7 @@
 
 	DPRINTK("adv_pci1710 EDBG: BGN: pci171x_insn_read_ai(...)\n");
 	devpriv->CntrlReg &= Control_CNT0;
-	devpriv->CntrlReg |= Control_SW;	// set software trigger
+	devpriv->CntrlReg |= Control_SW;	/*  set software trigger */
 	outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
 	outb(0, dev->iobase + PCI171x_CLRFIFO);
 	outb(0, dev->iobase + PCI171x_CLRINT);
@@ -346,7 +348,7 @@
 		outw(0, dev->iobase + PCI171x_SOFTTRG);	/* start conversion */
 		DPRINTK("adv_pci1710 B n=%d ST=%4x\n", n,
 			inw(dev->iobase + PCI171x_STATUS));
-		//comedi_udelay(1);
+		/* udelay(1); */
 		DPRINTK("adv_pci1710 C n=%d ST=%4x\n", n,
 			inw(dev->iobase + PCI171x_STATUS));
 		timeout = 100;
@@ -390,8 +392,8 @@
 /*
 ==============================================================================
 */
-static int pci171x_insn_write_ao(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci171x_insn_write_ao(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, chan, range, ofs;
 
@@ -421,8 +423,8 @@
 /*
 ==============================================================================
 */
-static int pci171x_insn_read_ao(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci171x_insn_read_ao(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, chan;
 
@@ -436,8 +438,8 @@
 /*
 ==============================================================================
 */
-static int pci171x_insn_bits_di(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci171x_insn_bits_di(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[1] = inw(dev->iobase + PCI171x_DI);
 
@@ -447,8 +449,8 @@
 /*
 ==============================================================================
 */
-static int pci171x_insn_bits_do(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci171x_insn_bits_do(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (data[0]) {
 		s->state &= ~data[0];
@@ -463,8 +465,8 @@
 /*
 ==============================================================================
 */
-static int pci171x_insn_counter_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci171x_insn_counter_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int msb, lsb, ccntrl;
 	int i;
@@ -485,8 +487,8 @@
 /*
 ==============================================================================
 */
-static int pci171x_insn_counter_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci171x_insn_counter_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	uint msb, lsb, ccntrl, status;
 
@@ -512,8 +514,8 @@
 /*
 ==============================================================================
 */
-static int pci171x_insn_counter_config(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int pci171x_insn_counter_config(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 #ifdef unused
 	/* This doesn't work like a normal Comedi counter config */
@@ -548,8 +550,8 @@
 /*
 ==============================================================================
 */
-static int pci1720_insn_write_ao(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci1720_insn_write_ao(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, rangereg, chan;
 
@@ -563,7 +565,7 @@
 
 	for (n = 0; n < insn->n; n++) {
 		outw(data[n], dev->iobase + PCI1720_DA0 + (chan << 1));
-		outb(0, dev->iobase + PCI1720_SYNCOUT);	// update outputs
+		outb(0, dev->iobase + PCI1720_SYNCOUT);	/*  update outputs */
 	}
 
 	devpriv->ao_data[chan] = data[n];
@@ -586,14 +588,14 @@
 	DPRINTK("adv_pci1710 EDBG: BGN: interrupt_pci1710_every_sample(...)\n");
 	m = inw(dev->iobase + PCI171x_STATUS);
 	if (m & Status_FE) {
-		rt_printk("comedi%d: A/D FIFO empty (%4x)\n", dev->minor, m);
+		printk("comedi%d: A/D FIFO empty (%4x)\n", dev->minor, m);
 		pci171x_ai_cancel(dev, s);
 		s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
 		comedi_event(dev, s);
 		return;
 	}
 	if (m & Status_FF) {
-		rt_printk
+		printk
 			("comedi%d: A/D FIFO Full status (Fatal Error!) (%4x)\n",
 			dev->minor, m);
 		pci171x_ai_cancel(dev, s);
@@ -602,7 +604,7 @@
 		return;
 	}
 
-	outb(0, dev->iobase + PCI171x_CLRINT);	// clear our INT request
+	outb(0, dev->iobase + PCI171x_CLRINT);	/*  clear our INT request */
 
 	DPRINTK("FOR ");
 	for (; !(inw(dev->iobase + PCI171x_STATUS) & Status_FE);) {
@@ -612,7 +614,7 @@
 		if (this_board->cardtype != TYPE_PCI1713)
 			if ((sampl & 0xf000) !=
 				devpriv->act_chanlist[s->async->cur_chan]) {
-				rt_printk
+				printk
 					("comedi: A/D data dropout: received data from channel %d, expected %d!\n",
 					(sampl & 0xf000) >> 12,
 					(devpriv->act_chanlist[s->async->
@@ -637,11 +639,11 @@
 			s->async->cur_chan = 0;
 		}
 
-		if (s->async->cur_chan == 0) {	// one scan done
+		if (s->async->cur_chan == 0) {	/*  one scan done */
 			devpriv->ai_act_scan++;
 			DPRINTK("adv_pci1710 EDBG: EOS1 bic %d bip %d buc %d bup %d\n", s->async->buf_int_count, s->async->buf_int_ptr, s->async->buf_user_count, s->async->buf_user_ptr);
 			DPRINTK("adv_pci1710 EDBG: EOS2\n");
-			if ((!devpriv->neverending_ai) && (devpriv->ai_act_scan >= devpriv->ai_scans)) {	// all data sampled
+			if ((!devpriv->neverending_ai) && (devpriv->ai_act_scan >= devpriv->ai_scans)) {	/*  all data sampled */
 				pci171x_ai_cancel(dev, s);
 				s->async->events |= COMEDI_CB_EOA;
 				comedi_event(dev, s);
@@ -650,7 +652,7 @@
 		}
 	}
 
-	outb(0, dev->iobase + PCI171x_CLRINT);	// clear our INT request
+	outb(0, dev->iobase + PCI171x_CLRINT);	/*  clear our INT request */
 	DPRINTK("adv_pci1710 EDBG: END: interrupt_pci1710_every_sample(...)\n");
 
 	comedi_event(dev, s);
@@ -659,7 +661,7 @@
 /*
 ==============================================================================
 */
-static int move_block_from_fifo(struct comedi_device * dev, struct comedi_subdevice * s,
+static int move_block_from_fifo(struct comedi_device *dev, struct comedi_subdevice *s,
 	int n, int turn)
 {
 	int i, j;
@@ -674,7 +676,7 @@
 		sampl = inw(dev->iobase + PCI171x_AD_DATA);
 		if (this_board->cardtype != TYPE_PCI1713)
 			if ((sampl & 0xf000) != devpriv->act_chanlist[j]) {
-				rt_printk
+				printk
 					("comedi%d: A/D  FIFO data dropout: received data from channel %d, expected %d! (%d/%d/%d/%d/%d/%4x)\n",
 					dev->minor, (sampl & 0xf000) >> 12,
 					(devpriv->
@@ -714,7 +716,7 @@
 	DPRINTK("adv_pci1710 EDBG: BGN: interrupt_pci1710_half_fifo(...)\n");
 	m = inw(dev->iobase + PCI171x_STATUS);
 	if (!(m & Status_FH)) {
-		rt_printk("comedi%d: A/D FIFO not half full! (%4x)\n",
+		printk("comedi%d: A/D FIFO not half full! (%4x)\n",
 			dev->minor, m);
 		pci171x_ai_cancel(dev, s);
 		s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
@@ -722,7 +724,7 @@
 		return;
 	}
 	if (m & Status_FF) {
-		rt_printk
+		printk
 			("comedi%d: A/D FIFO Full status (Fatal Error!) (%4x)\n",
 			dev->minor, m);
 		pci171x_ai_cancel(dev, s);
@@ -751,7 +753,7 @@
 			comedi_event(dev, s);
 			return;
 		}
-	outb(0, dev->iobase + PCI171x_CLRINT);	// clear our INT request
+	outb(0, dev->iobase + PCI171x_CLRINT);	/*  clear our INT request */
 	DPRINTK("adv_pci1710 EDBG: END: interrupt_pci1710_half_fifo(...)\n");
 
 	comedi_event(dev, s);
@@ -760,36 +762,36 @@
 /*
 ==============================================================================
 */
-static irqreturn_t interrupt_service_pci1710(int irq, void *d PT_REGS_ARG)
+static irqreturn_t interrupt_service_pci1710(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 
 	DPRINTK("adv_pci1710 EDBG: BGN: interrupt_service_pci1710(%d,...)\n",
 		irq);
-	if (!dev->attached)	// is device attached?
-		return IRQ_NONE;	// no, exit
+	if (!dev->attached)	/*  is device attached? */
+		return IRQ_NONE;	/*  no, exit */
 
-	if (!(inw(dev->iobase + PCI171x_STATUS) & Status_IRQ))	// is this interrupt from our board?
-		return IRQ_NONE;	// no, exit
+	if (!(inw(dev->iobase + PCI171x_STATUS) & Status_IRQ))	/*  is this interrupt from our board? */
+		return IRQ_NONE;	/*  no, exit */
 
 	DPRINTK("adv_pci1710 EDBG: interrupt_service_pci1710() ST: %4x\n",
 		inw(dev->iobase + PCI171x_STATUS));
 
-	if (devpriv->ai_et) {	// Switch from initial TRIG_EXT to TRIG_xxx.
+	if (devpriv->ai_et) {	/*  Switch from initial TRIG_EXT to TRIG_xxx. */
 		devpriv->ai_et = 0;
 		devpriv->CntrlReg &= Control_CNT0;
-		devpriv->CntrlReg |= Control_SW;	// set software trigger
+		devpriv->CntrlReg |= Control_SW;	/*  set software trigger */
 		outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
 		devpriv->CntrlReg = devpriv->ai_et_CntrlReg;
 		outb(0, dev->iobase + PCI171x_CLRFIFO);
 		outb(0, dev->iobase + PCI171x_CLRINT);
 		outw(devpriv->ai_et_MuxVal, dev->iobase + PCI171x_MUX);
 		outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
-		// start pacer
+		/*  start pacer */
 		start_pacer(dev, 1, devpriv->ai_et_div1, devpriv->ai_et_div2);
 		return IRQ_HANDLED;
 	}
-	if (devpriv->ai_eos) {	// We use FIFO half full INT or not?
+	if (devpriv->ai_eos) {	/*  We use FIFO half full INT or not? */
 		interrupt_pci1710_every_sample(d);
 	} else {
 		interrupt_pci1710_half_fifo(d);
@@ -801,15 +803,15 @@
 /*
 ==============================================================================
 */
-static int pci171x_ai_docmd_and_mode(int mode, struct comedi_device * dev,
-	struct comedi_subdevice * s)
+static int pci171x_ai_docmd_and_mode(int mode, struct comedi_device *dev,
+	struct comedi_subdevice *s)
 {
 	unsigned int divisor1, divisor2;
 	unsigned int seglen;
 
 	DPRINTK("adv_pci1710 EDBG: BGN: pci171x_ai_docmd_and_mode(%d,...)\n",
 		mode);
-	start_pacer(dev, -1, 0, 0);	// stop pacer
+	start_pacer(dev, -1, 0, 0);	/*  stop pacer */
 
 	seglen = check_channel_list(dev, s, devpriv->ai_chanlist,
 		devpriv->ai_n_chan);
@@ -829,7 +831,7 @@
 	devpriv->neverending_ai = 0;
 
 	devpriv->CntrlReg &= Control_CNT0;
-	if ((devpriv->ai_flags & TRIG_WAKE_EOS)) {	// don't we want wake up every scan?            devpriv->ai_eos=1;
+	if ((devpriv->ai_flags & TRIG_WAKE_EOS)) {	/*  don't we want wake up every scan?            devpriv->ai_eos=1; */
 		devpriv->ai_eos = 1;
 	} else {
 		devpriv->CntrlReg |= Control_ONEFH;
@@ -838,7 +840,7 @@
 
 	if ((devpriv->ai_scans == 0) || (devpriv->ai_scans == -1)) {
 		devpriv->neverending_ai = 1;
-	}			//well, user want neverending
+	}			/* well, user want neverending */
 	else {
 		devpriv->neverending_ai = 0;
 	}
@@ -863,7 +865,7 @@
 		DPRINTK("adv_pci1710 EDBG: OSC base=%u div1=%u div2=%u timer=%u\n", devpriv->i8254_osc_base, divisor1, divisor2, devpriv->ai_timer1);
 		outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
 		if (mode != 2) {
-			// start pacer
+			/*  start pacer */
 			start_pacer(dev, mode, divisor1, divisor2);
 		} else {
 			devpriv->ai_et_div1 = divisor1;
@@ -884,15 +886,15 @@
 /*
 ==============================================================================
 */
-static void pci171x_cmdtest_out(int e, struct comedi_cmd * cmd)
+static void pci171x_cmdtest_out(int e, struct comedi_cmd *cmd)
 {
-	rt_printk("adv_pci1710 e=%d startsrc=%x scansrc=%x convsrc=%x\n", e,
+	printk("adv_pci1710 e=%d startsrc=%x scansrc=%x convsrc=%x\n", e,
 		cmd->start_src, cmd->scan_begin_src, cmd->convert_src);
-	rt_printk("adv_pci1710 e=%d startarg=%d scanarg=%d convarg=%d\n", e,
+	printk("adv_pci1710 e=%d startarg=%d scanarg=%d convarg=%d\n", e,
 		cmd->start_arg, cmd->scan_begin_arg, cmd->convert_arg);
-	rt_printk("adv_pci1710 e=%d stopsrc=%x scanend=%x\n", e, cmd->stop_src,
+	printk("adv_pci1710 e=%d stopsrc=%x scanend=%x\n", e, cmd->stop_src,
 		cmd->scan_end_src);
-	rt_printk("adv_pci1710 e=%d stoparg=%d scanendarg=%d chanlistlen=%d\n",
+	printk("adv_pci1710 e=%d stoparg=%d scanendarg=%d chanlistlen=%d\n",
 		e, cmd->stop_arg, cmd->scan_end_arg, cmd->chanlist_len);
 }
 #endif
@@ -900,8 +902,8 @@
 /*
 ==============================================================================
 */
-static int pci171x_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int pci171x_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp, divisor1, divisor2;
@@ -1055,7 +1057,7 @@
 	if (cmd->chanlist) {
 		if (!check_channel_list(dev, s, cmd->chanlist,
 				cmd->chanlist_len))
-			return 5;	// incorrect channels list
+			return 5;	/*  incorrect channels list */
 	}
 
 	DPRINTK("adv_pci1710 EDBG: BGN: pci171x_ai_cmdtest(...) ret=0\n");
@@ -1065,7 +1067,7 @@
 /*
 ==============================================================================
 */
-static int pci171x_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci171x_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 
@@ -1084,13 +1086,13 @@
 		devpriv->ai_scans = 0;
 	}
 
-	if (cmd->scan_begin_src == TRIG_FOLLOW) {	// mode 1, 2, 3
-		if (cmd->convert_src == TRIG_TIMER) {	// mode 1 and 2
+	if (cmd->scan_begin_src == TRIG_FOLLOW) {	/*  mode 1, 2, 3 */
+		if (cmd->convert_src == TRIG_TIMER) {	/*  mode 1 and 2 */
 			devpriv->ai_timer1 = cmd->convert_arg;
 			return pci171x_ai_docmd_and_mode(cmd->start_src ==
 				TRIG_EXT ? 2 : 1, dev, s);
 		}
-		if (cmd->convert_src == TRIG_EXT) {	// mode 3
+		if (cmd->convert_src == TRIG_EXT) {	/*  mode 3 */
 			return pci171x_ai_docmd_and_mode(3, dev, s);
 		}
 	}
@@ -1104,7 +1106,7 @@
  If it's ok, then program scan/gain logic.
  This works for all cards.
 */
-static int check_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static int check_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int *chanlist, unsigned int n_chan)
 {
 	unsigned int chansegment[32];
@@ -1118,12 +1120,12 @@
 	}
 
 	if (n_chan > 1) {
-		chansegment[0] = chanlist[0];	// first channel is everytime ok
-		for (i = 1, seglen = 1; i < n_chan; i++, seglen++) {	// build part of chanlist
-			// rt_printk("%d. %d %d\n",i,CR_CHAN(chanlist[i]),CR_RANGE(chanlist[i]));
+		chansegment[0] = chanlist[0];	/*  first channel is everytime ok */
+		for (i = 1, seglen = 1; i < n_chan; i++, seglen++) {	/*  build part of chanlist */
+			/*  printk("%d. %d %d\n",i,CR_CHAN(chanlist[i]),CR_RANGE(chanlist[i])); */
 			if (chanlist[0] == chanlist[i])
-				break;	// we detect loop, this must by finish
-			if (CR_CHAN(chanlist[i]) & 1)	// odd channel cann't by differencial
+				break;	/*  we detect loop, this must by finish */
+			if (CR_CHAN(chanlist[i]) & 1)	/*  odd channel cann't by differencial */
 				if (CR_AREF(chanlist[i]) == AREF_DIFF) {
 					comedi_error(dev,
 						"Odd channel can't be differential input!\n");
@@ -1133,20 +1135,20 @@
 				(CR_CHAN(chansegment[i - 1]) + 1) % s->n_chan;
 			if (CR_AREF(chansegment[i - 1]) == AREF_DIFF)
 				nowmustbechan = (nowmustbechan + 1) % s->n_chan;
-			if (nowmustbechan != CR_CHAN(chanlist[i])) {	// channel list isn't continous :-(
-				rt_printk
+			if (nowmustbechan != CR_CHAN(chanlist[i])) {	/*  channel list isn't continous :-( */
+				printk
 					("channel list must be continous! chanlist[%i]=%d but must be %d or %d!\n",
 					i, CR_CHAN(chanlist[i]), nowmustbechan,
 					CR_CHAN(chanlist[0]));
 				return 0;
 			}
-			chansegment[i] = chanlist[i];	// well, this is next correct channel in list
+			chansegment[i] = chanlist[i];	/*  well, this is next correct channel in list */
 		}
 
-		for (i = 0, segpos = 0; i < n_chan; i++) {	// check whole chanlist
-			//rt_printk("%d %d=%d %d\n",CR_CHAN(chansegment[i%seglen]),CR_RANGE(chansegment[i%seglen]),CR_CHAN(chanlist[i]),CR_RANGE(chanlist[i]));
+		for (i = 0, segpos = 0; i < n_chan; i++) {	/*  check whole chanlist */
+			/* printk("%d %d=%d %d\n",CR_CHAN(chansegment[i%seglen]),CR_RANGE(chansegment[i%seglen]),CR_CHAN(chanlist[i]),CR_RANGE(chanlist[i])); */
 			if (chanlist[i] != chansegment[i % seglen]) {
-				rt_printk
+				printk
 					("bad channel, reference or range number! chanlist[%i]=%d,%d,%d and not %d,%d,%d!\n",
 					i, CR_CHAN(chansegment[i]),
 					CR_RANGE(chansegment[i]),
@@ -1154,7 +1156,7 @@
 					CR_CHAN(chanlist[i % seglen]),
 					CR_RANGE(chanlist[i % seglen]),
 					CR_AREF(chansegment[i % seglen]));
-				return 0;	// chan/gain list is strange
+				return 0;	/*  chan/gain list is strange */
 			}
 		}
 	} else {
@@ -1163,7 +1165,7 @@
 	return seglen;
 }
 
-static void setup_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static void setup_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int *chanlist, unsigned int n_chan, unsigned int seglen)
 {
 	unsigned int i, range, chanprog;
@@ -1174,7 +1176,7 @@
 	devpriv->act_chanlist_pos = 0;
 
 	DPRINTK("SegLen: %d\n", seglen);
-	for (i = 0; i < seglen; i++) {	// store range list to card
+	for (i = 0; i < seglen; i++) {	/*  store range list to card */
 		chanprog = muxonechan[CR_CHAN(chanlist[i])];
 		outw(chanprog, dev->iobase + PCI171x_MUX);	/* select channel */
 		range = this_board->rangecode_ai[CR_RANGE(chanlist[i])];
@@ -1200,7 +1202,7 @@
 /*
 ==============================================================================
 */
-static void start_pacer(struct comedi_device * dev, int mode, unsigned int divisor1,
+static void start_pacer(struct comedi_device *dev, int mode, unsigned int divisor1,
 	unsigned int divisor2)
 {
 	DPRINTK("adv_pci1710 EDBG: BGN: start_pacer(%d,%u,%u)\n", mode,
@@ -1220,7 +1222,7 @@
 /*
 ==============================================================================
 */
-static int pci171x_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci171x_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	DPRINTK("adv_pci1710 EDBG: BGN: pci171x_ai_cancel(...)\n");
 
@@ -1229,7 +1231,7 @@
 		devpriv->CntrlReg &= Control_CNT0;
 		devpriv->CntrlReg |= Control_SW;
 
-		outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);	// reset any operations
+		outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);	/*  reset any operations */
 		start_pacer(dev, -1, 0, 0);
 		outb(0, dev->iobase + PCI171x_CLRFIFO);
 		outb(0, dev->iobase + PCI171x_CLRINT);
@@ -1249,28 +1251,28 @@
 /*
 ==============================================================================
 */
-static int pci171x_reset(struct comedi_device * dev)
+static int pci171x_reset(struct comedi_device *dev)
 {
 	DPRINTK("adv_pci1710 EDBG: BGN: pci171x_reset(...)\n");
 	outw(0x30, dev->iobase + PCI171x_CNTCTRL);
-	devpriv->CntrlReg = Control_SW | Control_CNT0;	// Software trigger, CNT0=external
-	outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);	// reset any operations
-	outb(0, dev->iobase + PCI171x_CLRFIFO);	// clear FIFO
-	outb(0, dev->iobase + PCI171x_CLRINT);	// clear INT request
-	start_pacer(dev, -1, 0, 0);	// stop 8254
+	devpriv->CntrlReg = Control_SW | Control_CNT0;	/*  Software trigger, CNT0=external */
+	outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);	/*  reset any operations */
+	outb(0, dev->iobase + PCI171x_CLRFIFO);	/*  clear FIFO */
+	outb(0, dev->iobase + PCI171x_CLRINT);	/*  clear INT request */
+	start_pacer(dev, -1, 0, 0);	/*  stop 8254 */
 	devpriv->da_ranges = 0;
 	if (this_board->n_aochan) {
-		outb(devpriv->da_ranges, dev->iobase + PCI171x_DAREF);	// set DACs to 0..5V
-		outw(0, dev->iobase + PCI171x_DA1);	// set DA outputs to 0V
+		outb(devpriv->da_ranges, dev->iobase + PCI171x_DAREF);	/*  set DACs to 0..5V */
+		outw(0, dev->iobase + PCI171x_DA1);	/*  set DA outputs to 0V */
 		devpriv->ao_data[0] = 0x0000;
 		if (this_board->n_aochan > 1) {
 			outw(0, dev->iobase + PCI171x_DA2);
 			devpriv->ao_data[1] = 0x0000;
 		}
 	}
-	outw(0, dev->iobase + PCI171x_DO);	// digital outputs to 0
-	outb(0, dev->iobase + PCI171x_CLRFIFO);	// clear FIFO
-	outb(0, dev->iobase + PCI171x_CLRINT);	// clear INT request
+	outw(0, dev->iobase + PCI171x_DO);	/*  digital outputs to 0 */
+	outb(0, dev->iobase + PCI171x_CLRFIFO);	/*  clear FIFO */
+	outb(0, dev->iobase + PCI171x_CLRINT);	/*  clear INT request */
 
 	DPRINTK("adv_pci1710 EDBG: END: pci171x_reset(...)\n");
 	return 0;
@@ -1279,17 +1281,17 @@
 /*
 ==============================================================================
 */
-static int pci1720_reset(struct comedi_device * dev)
+static int pci1720_reset(struct comedi_device *dev)
 {
 	DPRINTK("adv_pci1710 EDBG: BGN: pci1720_reset(...)\n");
-	outb(Syncont_SC0, dev->iobase + PCI1720_SYNCONT);	// set synchronous output mode
+	outb(Syncont_SC0, dev->iobase + PCI1720_SYNCONT);	/*  set synchronous output mode */
 	devpriv->da_ranges = 0xAA;
-	outb(devpriv->da_ranges, dev->iobase + PCI1720_RANGE);	// set all ranges to +/-5V
-	outw(0x0800, dev->iobase + PCI1720_DA0);	// set outputs to 0V
+	outb(devpriv->da_ranges, dev->iobase + PCI1720_RANGE);	/*  set all ranges to +/-5V */
+	outw(0x0800, dev->iobase + PCI1720_DA0);	/*  set outputs to 0V */
 	outw(0x0800, dev->iobase + PCI1720_DA1);
 	outw(0x0800, dev->iobase + PCI1720_DA2);
 	outw(0x0800, dev->iobase + PCI1720_DA3);
-	outb(0, dev->iobase + PCI1720_SYNCOUT);	// update outputs
+	outb(0, dev->iobase + PCI1720_SYNCOUT);	/*  update outputs */
 	devpriv->ao_data[0] = 0x0800;
 	devpriv->ao_data[1] = 0x0800;
 	devpriv->ao_data[2] = 0x0800;
@@ -1301,7 +1303,7 @@
 /*
 ==============================================================================
 */
-static int pci1710_reset(struct comedi_device * dev)
+static int pci1710_reset(struct comedi_device *dev)
 {
 	DPRINTK("adv_pci1710 EDBG: BGN: pci1710_reset(...)\n");
 	switch (this_board->cardtype) {
@@ -1316,7 +1318,7 @@
 /*
 ==============================================================================
 */
-static int pci1710_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pci1710_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int ret, subdev, n_subdevices;
@@ -1329,13 +1331,14 @@
 	int i;
 	int board_index;
 
-	rt_printk("comedi%d: adv_pci1710: ", dev->minor);
+	printk("comedi%d: adv_pci1710: ", dev->minor);
 
 	opt_bus = it->options[0];
 	opt_slot = it->options[1];
 
-	if ((ret = alloc_private(dev, sizeof(struct pci1710_private))) < 0) {
-		rt_printk(" - Allocation failed!\n");
+	ret = alloc_private(dev, sizeof(struct pci1710_private));
+	if (ret < 0) {
+		printk(" - Allocation failed!\n");
 		return -ENOMEM;
 	}
 
@@ -1345,20 +1348,20 @@
 	board_index = this_board - boardtypes;
 	while (NULL != (pcidev = pci_get_device(PCI_VENDOR_ID_ADVANTECH,
 		PCI_ANY_ID, pcidev))) {
-		if(strcmp(this_board->name, DRV_NAME) == 0)
+		if (strcmp (this_board->name, DRV_NAME) == 0)
 		{
-			for(i = 0; i < n_boardtypes; ++i)
+			for (i = 0; i < n_boardtypes; ++i)
 			{
-				if(pcidev->device == boardtypes[i].device_id)
+				if (pcidev->device == boardtypes[i].device_id)
 				{
 					board_index = i;
 					break;
 				}
 			}
-			if(i == n_boardtypes) continue;
+			if (i == n_boardtypes) continue;
 		}else
 		{
-			if(pcidev->device != boardtypes[board_index].device_id) continue;
+			if (pcidev->device != boardtypes[board_index].device_id) continue;
 		}
 
 		/* Found matching vendor/device. */
@@ -1376,17 +1379,17 @@
 			errstr = "failed to enable PCI device and request regions!";
 			continue;
 		}
-		// fixup board_ptr in case we were using the dummy entry with the driver name
+		/*  fixup board_ptr in case we were using the dummy entry with the driver name */
 		dev->board_ptr = &boardtypes[board_index];
 		break;
 	}
 
 	if (!pcidev) {
 		if (opt_bus || opt_slot) {
-			rt_printk(" - Card at b:s %d:%d %s\n",
+			printk(" - Card at b:s %d:%d %s\n",
 				opt_bus, opt_slot, errstr);
 		} else {
-			rt_printk(" - Card %s\n", errstr);
+			printk(" - Card %s\n", errstr);
 		}
 		return -EIO;
 	}
@@ -1397,7 +1400,7 @@
 	irq = pcidev->irq;
 	iobase = pci_resource_start(pcidev, 2);
 
-	rt_printk(", b:s:f=%d:%d:%d, io=0x%4lx", pci_bus, pci_slot, pci_func,
+	printk(", b:s:f=%d:%d:%d, io=0x%4lx", pci_bus, pci_slot, pci_func,
 		iobase);
 
 	dev->iobase = iobase;
@@ -1417,8 +1420,9 @@
 	if (this_board->n_counter)
 		n_subdevices++;
 
-	if ((ret = alloc_subdevices(dev, n_subdevices)) < 0) {
-		rt_printk(" - Allocation failed!\n");
+	ret = alloc_subdevices(dev, n_subdevices);
+	if (ret < 0) {
+		printk(" - Allocation failed!\n");
 		return ret;
 	}
 
@@ -1426,18 +1430,18 @@
 
 	if (this_board->have_irq) {
 		if (irq) {
-			if (comedi_request_irq(irq, interrupt_service_pci1710,
+			if (request_irq(irq, interrupt_service_pci1710,
 					IRQF_SHARED, "Advantech PCI-1710",
 					dev)) {
-				rt_printk
+				printk
 					(", unable to allocate IRQ %d, DISABLING IT",
 					irq);
 				irq = 0;	/* Can't use IRQ */
 			} else {
-				rt_printk(", irq=%u", irq);
+				printk(", irq=%u", irq);
 			}
 		} else {
-			rt_printk(", IRQ disabled");
+			printk(", IRQ disabled");
 		}
 	} else {
 		irq = 0;
@@ -1467,7 +1471,7 @@
 			s->do_cmdtest = pci171x_ai_cmdtest;
 			s->do_cmd = pci171x_ai_cmd;
 		}
-		devpriv->i8254_osc_base = 100;	// 100ns=10MHz
+		devpriv->i8254_osc_base = 100;	/*  100ns=10MHz */
 		subdev++;
 	}
 
@@ -1540,14 +1544,14 @@
 /*
 ==============================================================================
 */
-static int pci1710_detach(struct comedi_device * dev)
+static int pci1710_detach(struct comedi_device *dev)
 {
 
 	if (dev->private) {
 		if (devpriv->valid)
 			pci1710_reset(dev);
 		if (dev->irq)
-			comedi_free_irq(dev->irq, dev);
+			free_irq(dev->irq, dev);
 		if (devpriv->pcidev) {
 			if (dev->iobase) {
 				comedi_pci_disable(devpriv->pcidev);
diff --git a/drivers/staging/comedi/drivers/adv_pci1723.c b/drivers/staging/comedi/drivers/adv_pci1723.c
index 81f7ee1..e1994a5 100644
--- a/drivers/staging/comedi/drivers/adv_pci1723.c
+++ b/drivers/staging/comedi/drivers/adv_pci1723.c
@@ -54,7 +54,7 @@
 
 #define ADVANTECH_VENDOR        0x13fe	/* Advantech PCI vendor ID */
 
-// hardware types of the cards
+/* hardware types of the cards */
 #define TYPE_PCI1723 0
 
 #define IORANGE_1723  0x2A
@@ -92,7 +92,7 @@
 
 #define PCI1723_SELECT_CALIBRATION 0x28	/* Select the calibration Ref_V */
 
-//static unsigned short pci_list_builded=0;     /*=1 list of card is know */
+/* static unsigned short pci_list_builded=0;      =1 list of card is know */
 
 static const struct comedi_lrange range_pci1723 = { 1, {
 			BIP_RANGE(10)
@@ -104,27 +104,27 @@
  */
 struct pci1723_board {
 	const char *name;
-	int vendor_id;		// PCI vendor a device ID of card
+	int vendor_id;		/*  PCI vendor a device ID of card */
 	int device_id;
 	int iorange;
 	char cardtype;
-	int n_aochan;		// num of D/A chans
-	int n_diochan;		// num of DIO chans
-	int ao_maxdata;		// resolution of D/A
-	const struct comedi_lrange *rangelist_ao;	// rangelist for D/A
+	int n_aochan;		/*  num of D/A chans */
+	int n_diochan;		/*  num of DIO chans */
+	int ao_maxdata;		/*  resolution of D/A */
+	const struct comedi_lrange *rangelist_ao;	/*  rangelist for D/A */
 };
 
 static const struct pci1723_board boardtypes[] = {
 	{
-	      name:	"pci1723",
-	      vendor_id:ADVANTECH_VENDOR,
-	      device_id:0x1723,
-	      iorange:	IORANGE_1723,
-	      cardtype:TYPE_PCI1723,
-	      n_aochan:8,
-	      n_diochan:16,
-	      ao_maxdata:0xffff,
-	      rangelist_ao:&range_pci1723,
+	.name = "pci1723",
+	.vendor_id = ADVANTECH_VENDOR,
+	.device_id = 0x1723,
+	.iorange = IORANGE_1723,
+	.cardtype = TYPE_PCI1723,
+	.n_aochan = 8,
+	.n_diochan = 16,
+	.ao_maxdata = 0xffff,
+	.rangelist_ao = &range_pci1723,
 		},
 };
 
@@ -143,26 +143,26 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int pci1723_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pci1723_detach(struct comedi_device * dev);
+static int pci1723_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pci1723_detach(struct comedi_device *dev);
 
 #define n_boardtypes (sizeof(boardtypes)/sizeof(struct pci1723_board))
 
 static struct comedi_driver driver_pci1723 = {
-      driver_name:"adv_pci1723",
-      module:THIS_MODULE,
-      attach:pci1723_attach,
-      detach:pci1723_detach,
+	.driver_name = "adv_pci1723",
+	.module = THIS_MODULE,
+	.attach = pci1723_attach,
+	.detach = pci1723_detach,
 };
 
 /* this structure is for data unique to this hardware driver. */
 struct pci1723_private {
-	int valid;		//card is usable;
+	int valid;		/* card is usable; */
 
 	struct pci_dev *pcidev;
-	unsigned char da_range[8];	// D/A output range for each channel
+	unsigned char da_range[8];	/*  D/A output range for each channel */
 
-	short ao_data[8];	// data output buffer
+	short ao_data[8];	/*  data output buffer */
 };
 
 /*the following macro to make it easy to
@@ -175,35 +175,35 @@
 /*
  *   the pci1723 card reset;
  */
-static int pci1723_reset(struct comedi_device * dev)
+static int pci1723_reset(struct comedi_device *dev)
 {
 	int i;
 	DPRINTK("adv_pci1723 EDBG: BGN: pci1723_reset(...)\n");
 
-	outw(0x01, dev->iobase + PCI1723_SYN_SET);	// set synchronous output mode
+	outw(0x01, dev->iobase + PCI1723_SYN_SET);	/*  set synchronous output mode */
 
 	for (i = 0; i < 8; i++) {
-		// set all outputs to 0V
+		/*  set all outputs to 0V */
 		devpriv->ao_data[i] = 0x8000;
 		outw(devpriv->ao_data[i], dev->iobase + PCI1723_DA(i));
-		// set all ranges to +/- 10V
+		/*  set all ranges to +/- 10V */
 		devpriv->da_range[i] = 0;
 		outw(((devpriv->da_range[i] << 4) | i),
 			PCI1723_RANGE_CALIBRATION_MODE);
 	}
 
-	outw(0, dev->iobase + PCI1723_CHANGE_CHA_OUTPUT_TYPE_STROBE);	// update ranges
-	outw(0, dev->iobase + PCI1723_SYN_STROBE);	// update outputs
+	outw(0, dev->iobase + PCI1723_CHANGE_CHA_OUTPUT_TYPE_STROBE);	/*  update ranges */
+	outw(0, dev->iobase + PCI1723_SYN_STROBE);	/*  update outputs */
 
-	// set asynchronous output mode
+	/*  set asynchronous output mode */
 	outw(0, dev->iobase + PCI1723_SYN_SET);
 
 	DPRINTK("adv_pci1723 EDBG: END: pci1723_reset(...)\n");
 	return 0;
 }
 
-static int pci1723_insn_read_ao(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci1723_insn_read_ao(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, chan;
 
@@ -218,8 +218,8 @@
 /*
   analog data output;
 */
-static int pci1723_ao_write_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci1723_ao_write_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, chan;
 	chan = CR_CHAN(insn->chanspec);
@@ -238,8 +238,8 @@
 /*
   digital i/o config/query
 */
-static int pci1723_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci1723_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int mask;
 	unsigned int bits;
@@ -265,12 +265,12 @@
 		return -EINVAL;
 	}
 
-	// update hardware DIO mode
-	dio_mode = 0x0000;	// low byte output, high byte output
+	/*  update hardware DIO mode */
+	dio_mode = 0x0000;	/*  low byte output, high byte output */
 	if ((s->io_bits & 0x00FF) == 0)
-		dio_mode |= 0x0001;	// low byte input
+		dio_mode |= 0x0001;	/*  low byte input */
 	if ((s->io_bits & 0xFF00) == 0)
-		dio_mode |= 0x0002;	// high byte input
+		dio_mode |= 0x0002;	/*  high byte input */
 	outw(dio_mode, dev->iobase + PCI1723_DIGITAL_IO_PORT_SET);
 	return 1;
 }
@@ -278,8 +278,8 @@
 /*
   digital i/o bits read/write
 */
-static int pci1723_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci1723_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (data[0]) {
 		s->state &= ~data[0];
@@ -294,7 +294,7 @@
  * Attach is called by the Comedi core to configure the driver
  * for a pci1723 board.
  */
-static int pci1723_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pci1723_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int ret, subdev, n_subdevices;
@@ -304,14 +304,15 @@
 	int opt_bus, opt_slot;
 	const char *errstr;
 
-	rt_printk("comedi%d: adv_pci1723: board=%s", dev->minor,
+	printk("comedi%d: adv_pci1723: board=%s", dev->minor,
 		this_board->name);
 
 	opt_bus = it->options[0];
 	opt_slot = it->options[1];
 
-	if ((ret = alloc_private(dev, sizeof(struct pci1723_private))) < 0) {
-		rt_printk(" - Allocation failed!\n");
+	ret = alloc_private(dev, sizeof(struct pci1723_private));
+	if (ret < 0) {
+		printk(" - Allocation failed!\n");
 		return -ENOMEM;
 	}
 
@@ -341,10 +342,10 @@
 
 	if (!pcidev) {
 		if (opt_bus || opt_slot) {
-			rt_printk(" - Card at b:s %d:%d %s\n",
+			printk(" - Card at b:s %d:%d %s\n",
 				opt_bus, opt_slot, errstr);
 		} else {
-			rt_printk(" - Card %s\n", errstr);
+			printk(" - Card %s\n", errstr);
 		}
 		return -EIO;
 	}
@@ -354,7 +355,7 @@
 	pci_func = PCI_FUNC(pcidev->devfn);
 	iobase = pci_resource_start(pcidev, 2);
 
-	rt_printk(", b:s:f=%d:%d:%d, io=0x%4x", pci_bus, pci_slot, pci_func,
+	printk(", b:s:f=%d:%d:%d, io=0x%4x", pci_bus, pci_slot, pci_func,
 		iobase);
 
 	dev->iobase = iobase;
@@ -369,8 +370,9 @@
 	if (this_board->n_diochan)
 		n_subdevices++;
 
-	if ((ret = alloc_subdevices(dev, n_subdevices)) < 0) {
-		rt_printk(" - Allocation failed!\n");
+	ret = alloc_subdevices(dev, n_subdevices);
+	if (ret < 0) {
+		printk(" - Allocation failed!\n");
 		return ret;
 	}
 
@@ -389,22 +391,22 @@
 		s->insn_write = pci1723_ao_write_winsn;
 		s->insn_read = pci1723_insn_read_ao;
 
-		// read DIO config
+		/*  read DIO config */
 		switch (inw(dev->iobase + PCI1723_DIGITAL_IO_PORT_MODE) & 0x03) {
-		case 0x00:	// low byte output, high byte output
+		case 0x00:	/*  low byte output, high byte output */
 			s->io_bits = 0xFFFF;
 			break;
-		case 0x01:	// low byte input, high byte output
+		case 0x01:	/*  low byte input, high byte output */
 			s->io_bits = 0xFF00;
 			break;
-		case 0x02:	// low byte output, high byte input
+		case 0x02:	/*  low byte output, high byte input */
 			s->io_bits = 0x00FF;
 			break;
-		case 0x03:	// low byte input, high byte input
+		case 0x03:	/*  low byte input, high byte input */
 			s->io_bits = 0x0000;
 			break;
 		}
-		// read DIO port state
+		/*  read DIO port state */
 		s->state = inw(dev->iobase + PCI1723_READ_DIGITAL_INPUT_DATA);
 
 		subdev++;
@@ -439,7 +441,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int pci1723_detach(struct comedi_device * dev)
+static int pci1723_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: pci1723: remove\n", dev->minor);
 
diff --git a/drivers/staging/comedi/drivers/adv_pci_dio.c b/drivers/staging/comedi/drivers/adv_pci_dio.c
index 2604425..5a8c0a3 100644
--- a/drivers/staging/comedi/drivers/adv_pci_dio.c
+++ b/drivers/staging/comedi/drivers/adv_pci_dio.c
@@ -40,7 +40,7 @@
 
 #undef DPRINTK
 #ifdef PCI_DIO_EXTDEBUG
-#define DPRINTK(fmt, args...) rt_printk(fmt, ## args)
+#define DPRINTK(fmt, args...) printk(fmt, ## args)
 #else
 #define DPRINTK(fmt, args...)
 #endif
@@ -183,8 +183,8 @@
 
 #define OMBCMD_RETRY	0x03	/* 3 times try request before error */
 
-static int pci_dio_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pci_dio_detach(struct comedi_device * dev);
+static int pci_dio_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pci_dio_detach(struct comedi_device *dev);
 
 struct diosubd_data {
 	int chans;		/*  num of chans */
@@ -323,10 +323,10 @@
 #define n_boardtypes (sizeof(boardtypes)/sizeof(struct dio_boardtype))
 
 static struct comedi_driver driver_pci_dio = {
-      driver_name:"adv_pci_dio",
-      module:THIS_MODULE,
-      attach:pci_dio_attach,
-      detach:pci_dio_detach
+	.driver_name = "adv_pci_dio",
+	.module = THIS_MODULE,
+	.attach = pci_dio_attach,
+	.detach = pci_dio_detach
 };
 
 struct pci_dio_private {
@@ -357,8 +357,8 @@
 /*
 ==============================================================================
 */
-static int pci_dio_insn_bits_di_b(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci_dio_insn_bits_di_b(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	const struct diosubd_data *d = (const struct diosubd_data *)s->private;
 	int i;
@@ -374,8 +374,8 @@
 /*
 ==============================================================================
 */
-static int pci_dio_insn_bits_di_w(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci_dio_insn_bits_di_w(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	const struct diosubd_data *d = (const struct diosubd_data *)s->private;
 	int i;
@@ -390,8 +390,8 @@
 /*
 ==============================================================================
 */
-static int pci_dio_insn_bits_do_b(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci_dio_insn_bits_do_b(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	const struct diosubd_data *d = (const struct diosubd_data *)s->private;
 	int i;
@@ -411,8 +411,8 @@
 /*
 ==============================================================================
 */
-static int pci_dio_insn_bits_do_w(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci_dio_insn_bits_do_w(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	const struct diosubd_data *d = (const struct diosubd_data *)s->private;
 	int i;
@@ -432,7 +432,7 @@
 /*
 ==============================================================================
 */
-static int pci1760_unchecked_mbxrequest(struct comedi_device * dev,
+static int pci1760_unchecked_mbxrequest(struct comedi_device *dev,
 	unsigned char *omb, unsigned char *imb, int repeats)
 {
 	int cnt, tout, ok = 0;
@@ -443,14 +443,15 @@
 		outb(omb[2], dev->iobase + OMB2);
 		outb(omb[3], dev->iobase + OMB3);
 		for (tout = 0; tout < 251; tout++) {
-			if ((imb[2] = inb(dev->iobase + IMB2)) == omb[2]) {
+			imb[2] = inb(dev->iobase + IMB2);
+			if (imb[2] == omb[2]) {
 				imb[0] = inb(dev->iobase + IMB0);
 				imb[1] = inb(dev->iobase + IMB1);
 				imb[3] = inb(dev->iobase + IMB3);
 				ok = 1;
 				break;
 			}
-			comedi_udelay(1);
+			udelay(1);
 		}
 		if (ok)
 			return 0;
@@ -460,7 +461,7 @@
 	return -ETIME;
 }
 
-static int pci1760_clear_imb2(struct comedi_device * dev)
+static int pci1760_clear_imb2(struct comedi_device *dev)
 {
 	unsigned char omb[4] = { 0x0, 0x0, CMD_ClearIMB2, 0x0 };
 	unsigned char imb[4];
@@ -470,7 +471,7 @@
 	return pci1760_unchecked_mbxrequest(dev, omb, imb, OMBCMD_RETRY);
 }
 
-static int pci1760_mbxrequest(struct comedi_device * dev,
+static int pci1760_mbxrequest(struct comedi_device *dev,
 	unsigned char *omb, unsigned char *imb)
 {
 	if (omb[2] == CMD_ClearIMB2) {
@@ -490,8 +491,8 @@
 /*
 ==============================================================================
 */
-static int pci1760_insn_bits_di(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci1760_insn_bits_di(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[1] = inb(dev->iobase + IMB3);
 
@@ -501,8 +502,8 @@
 /*
 ==============================================================================
 */
-static int pci1760_insn_bits_do(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci1760_insn_bits_do(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int ret;
 	unsigned char omb[4] = {
@@ -517,7 +518,8 @@
 		s->state &= ~data[0];
 		s->state |= (data[0] & data[1]);
 		omb[0] = s->state;
-		if (!(ret = pci1760_mbxrequest(dev, omb, imb)))
+		ret = pci1760_mbxrequest(dev, omb, imb);
+		if (!ret)
 			return ret;
 	}
 	data[1] = s->state;
@@ -528,8 +530,8 @@
 /*
 ==============================================================================
 */
-static int pci1760_insn_cnt_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci1760_insn_cnt_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int ret, n;
 	unsigned char omb[4] = {
@@ -541,7 +543,8 @@
 	unsigned char imb[4];
 
 	for (n = 0; n < insn->n; n++) {
-		if (!(ret = pci1760_mbxrequest(dev, omb, imb)))
+		ret = pci1760_mbxrequest(dev, omb, imb);
+		if (!ret)
 			return ret;
 		data[n] = (imb[1] << 8) + imb[0];
 	}
@@ -552,8 +555,8 @@
 /*
 ==============================================================================
 */
-static int pci1760_insn_cnt_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci1760_insn_cnt_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int ret;
 	unsigned char chan = CR_CHAN(insn->chanspec) & 0x07;
@@ -567,20 +570,23 @@
 	unsigned char imb[4];
 
 	if (devpriv->CntResValue[chan] != (data[0] & 0xffff)) {	/*  Set reset value if different */
-		if (!(ret = pci1760_mbxrequest(dev, omb, imb)))
+		ret =  pci1760_mbxrequest(dev, omb, imb);
+		if (!ret)
 			return ret;
 		devpriv->CntResValue[chan] = data[0] & 0xffff;
 	}
 
 	omb[0] = bitmask;	/*  reset counter to it reset value */
 	omb[2] = CMD_ResetIDICounters;
-	if (!(ret = pci1760_mbxrequest(dev, omb, imb)))
+	ret = pci1760_mbxrequest(dev, omb, imb);
+	if (!ret)
 		return ret;
 
 	if (!(bitmask & devpriv->IDICntEnable)) {	/*  start counter if it don't run */
 		omb[0] = bitmask;
 		omb[2] = CMD_EnableIDICounters;
-		if (!(ret = pci1760_mbxrequest(dev, omb, imb)))
+		ret = pci1760_mbxrequest(dev, omb, imb);
+		if (!ret)
 			return ret;
 		devpriv->IDICntEnable |= bitmask;
 	}
@@ -590,7 +596,7 @@
 /*
 ==============================================================================
 */
-static int pci1760_reset(struct comedi_device * dev)
+static int pci1760_reset(struct comedi_device *dev)
 {
 	int i;
 	unsigned char omb[4] = { 0x00, 0x00, 0x00, 0x00 };
@@ -667,7 +673,7 @@
 /*
 ==============================================================================
 */
-static int pci_dio_reset(struct comedi_device * dev)
+static int pci_dio_reset(struct comedi_device *dev)
 {
 	DPRINTK("adv_pci_dio EDBG: BGN: pci171x_reset(...)\n");
 
@@ -750,7 +756,7 @@
 /*
 ==============================================================================
 */
-static int pci1760_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pci1760_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int subdev = 0;
@@ -802,8 +808,8 @@
 /*
 ==============================================================================
 */
-static int pci_dio_add_di(struct comedi_device * dev, struct comedi_subdevice * s,
-	const struct diosubd_data * d, int subdev)
+static int pci_dio_add_di(struct comedi_device *dev, struct comedi_subdevice *s,
+	const struct diosubd_data *d, int subdev)
 {
 	s->type = COMEDI_SUBD_DI;
 	s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_COMMON | d->specflags;
@@ -829,8 +835,8 @@
 /*
 ==============================================================================
 */
-static int pci_dio_add_do(struct comedi_device * dev, struct comedi_subdevice * s,
-	const struct diosubd_data * d, int subdev)
+static int pci_dio_add_do(struct comedi_device *dev, struct comedi_subdevice *s,
+	const struct diosubd_data *d, int subdev)
 {
 	s->type = COMEDI_SUBD_DO;
 	s->subdev_flags = SDF_WRITABLE | SDF_GROUND | SDF_COMMON;
@@ -857,7 +863,7 @@
 /*
 ==============================================================================
 */
-static int CheckAndAllocCard(struct comedi_device * dev, struct comedi_devconfig * it,
+static int CheckAndAllocCard(struct comedi_device *dev, struct comedi_devconfig *it,
 	struct pci_dev *pcidev)
 {
 	struct pci_dio_private *pr, *prev;
@@ -883,17 +889,18 @@
 /*
 ==============================================================================
 */
-static int pci_dio_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pci_dio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int ret, subdev, n_subdevices, i, j;
 	unsigned long iobase;
 	struct pci_dev *pcidev;
 
-	rt_printk("comedi%d: adv_pci_dio: ", dev->minor);
+	printk("comedi%d: adv_pci_dio: ", dev->minor);
 
-	if ((ret = alloc_private(dev, sizeof(struct pci_dio_private))) < 0) {
-		rt_printk(", Error: Cann't allocate private memory!\n");
+	ret = alloc_private(dev, sizeof(struct pci_dio_private));
+	if (ret < 0) {
+		printk(", Error: Cann't allocate private memory!\n");
 		return -ENOMEM;
 	}
 
@@ -925,18 +932,18 @@
 	}
 
 	if (!dev->board_ptr) {
-		rt_printk
+		printk
 			(", Error: Requested type of the card was not found!\n");
 		return -EIO;
 	}
 
 	if (comedi_pci_enable(pcidev, driver_pci_dio.driver_name)) {
-		rt_printk
+		printk
 			(", Error: Can't enable PCI device and request regions!\n");
 		return -EIO;
 	}
 	iobase = pci_resource_start(pcidev, this_board->main_pci_region);
-	rt_printk(", b:s:f=%d:%d:%d, io=0x%4lx",
+	printk(", b:s:f=%d:%d:%d, io=0x%4lx",
 		pcidev->bus->number, PCI_SLOT(pcidev->devfn),
 		PCI_FUNC(pcidev->devfn), iobase);
 
@@ -959,12 +966,13 @@
 			n_subdevices++;
 	}
 
-	if ((ret = alloc_subdevices(dev, n_subdevices)) < 0) {
-		rt_printk(", Error: Cann't allocate subdevice memory!\n");
+	ret = alloc_subdevices(dev, n_subdevices);
+	if (ret < 0) {
+		printk(", Error: Cann't allocate subdevice memory!\n");
 		return ret;
 	}
 
-	rt_printk(".\n");
+	printk(".\n");
 
 	subdev = 0;
 
@@ -1011,7 +1019,7 @@
 /*
 ==============================================================================
 */
-static int pci_dio_detach(struct comedi_device * dev)
+static int pci_dio_detach(struct comedi_device *dev)
 {
 	int i, j;
 	struct comedi_subdevice *s;
diff --git a/drivers/staging/comedi/drivers/aio_aio12_8.c b/drivers/staging/comedi/drivers/aio_aio12_8.c
index b97b4d8..72283ae 100644
--- a/drivers/staging/comedi/drivers/aio_aio12_8.c
+++ b/drivers/staging/comedi/drivers/aio_aio12_8.c
@@ -77,7 +77,7 @@
 
 static const struct aio12_8_boardtype board_types[] = {
 	{
-      name:	"aio_aio12_8"},
+	.name = "aio_aio12_8"},
 };
 
 #define	thisboard	((const struct aio12_8_boardtype  *) dev->board_ptr)
@@ -88,29 +88,29 @@
 
 #define devpriv	((struct aio12_8_private *) dev->private)
 
-static int aio_aio12_8_ai_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int aio_aio12_8_ai_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	unsigned char control =
 		ADC_MODE_NORMAL |
 		(CR_RANGE(insn->chanspec) << 3) | CR_CHAN(insn->chanspec);
 
-	//read status to clear EOC latch
+	/* read status to clear EOC latch */
 	inb(dev->iobase + AIO12_8_STATUS);
 
 	for (n = 0; n < insn->n; n++) {
 		int timeout = 5;
 
-		// Setup and start conversion
+		/*  Setup and start conversion */
 		outb(control, dev->iobase + AIO12_8_ADC);
 
-		// Wait for conversion to complete
+		/*  Wait for conversion to complete */
 		while (timeout &&
 			!(inb(dev->iobase + AIO12_8_STATUS) & STATUS_ADC_EOC)) {
 			timeout--;
 			printk("timeout %d\n", timeout);
-			comedi_udelay(1);
+			udelay(1);
 		}
 		if (timeout == 0) {
 			comedi_error(dev, "ADC timeout");
@@ -122,8 +122,8 @@
 	return n;
 }
 
-static int aio_aio12_8_ao_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int aio_aio12_8_ao_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int val = devpriv->ao_readback[CR_CHAN(insn->chanspec)];
@@ -133,19 +133,19 @@
 	return insn->n;
 }
 
-static int aio_aio12_8_ao_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int aio_aio12_8_ao_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
 	unsigned long port = dev->iobase + AIO12_8_DAC_0 + (2 * chan);
 
-	//enable DACs
+	/* enable DACs */
 	outb(0x01, dev->iobase + DAC_ENABLE);
 
 	for (i = 0; i < insn->n; i++) {
-		outb(data[i] & 0xFF, port);	// LSB
-		outb((data[i] >> 8) & 0x0F, port + 1);	// MSB
+		outb(data[i] & 0xFF, port);	/*  LSB */
+		outb((data[i] >> 8) & 0x0F, port + 1);	/*  MSB */
 		devpriv->ao_readback[chan] = data[i];
 	}
 	return insn->n;
@@ -161,7 +161,7 @@
 		}
 };
 
-static int aio_aio12_8_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int aio_aio12_8_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int iobase;
 	struct comedi_subdevice *s;
@@ -205,7 +205,7 @@
 	return 0;
 }
 
-static int aio_aio12_8_detach(struct comedi_device * dev)
+static int aio_aio12_8_detach(struct comedi_device *dev)
 {
 	subdev_8255_cleanup(dev, &dev->subdevices[2]);
 	if (dev->iobase)
@@ -214,13 +214,13 @@
 }
 
 static struct comedi_driver driver_aio_aio12_8 = {
-      driver_name:"aio_aio12_8",
-      module:THIS_MODULE,
-      attach:aio_aio12_8_attach,
-      detach:aio_aio12_8_detach,
-      board_name:&board_types[0].name,
-      num_names:1,
-      offset:sizeof(struct aio12_8_boardtype),
+	.driver_name = "aio_aio12_8",
+	.module = THIS_MODULE,
+	.attach = aio_aio12_8_attach,
+	.detach = aio_aio12_8_detach,
+	.board_name = &board_types[0].name,
+	.num_names = 1,
+	.offset = sizeof(struct aio12_8_boardtype),
 };
 
 COMEDI_INITCLEANUP(driver_aio_aio12_8);
diff --git a/drivers/staging/comedi/drivers/aio_iiro_16.c b/drivers/staging/comedi/drivers/aio_iiro_16.c
index 9160fdf..d062f86 100644
--- a/drivers/staging/comedi/drivers/aio_iiro_16.c
+++ b/drivers/staging/comedi/drivers/aio_iiro_16.c
@@ -52,9 +52,9 @@
 
 static const struct aio_iiro_16_board aio_iiro_16_boards[] = {
 	{
-	      name:	"aio_iiro_16",
-	      di:	16,
-      do_:	16},
+	.name = "aio_iiro_16",
+	.di = 16,
+	.do_ = 16},
 };
 
 #define	thisboard	((const struct aio_iiro_16_board *) dev->board_ptr)
@@ -67,27 +67,27 @@
 
 #define	devpriv	((struct aio_iiro_16_private *) dev->private)
 
-static int aio_iiro_16_attach(struct comedi_device * dev, struct comedi_devconfig * it);
+static int aio_iiro_16_attach(struct comedi_device *dev, struct comedi_devconfig *it);
 
-static int aio_iiro_16_detach(struct comedi_device * dev);
+static int aio_iiro_16_detach(struct comedi_device *dev);
 
 static struct comedi_driver driver_aio_iiro_16 = {
-      driver_name:"aio_iiro_16",
-      module:THIS_MODULE,
-      attach:aio_iiro_16_attach,
-      detach:aio_iiro_16_detach,
-      board_name:&aio_iiro_16_boards[0].name,
-      offset:sizeof(struct aio_iiro_16_board),
-      num_names:sizeof(aio_iiro_16_boards) / sizeof(struct aio_iiro_16_board),
+	.driver_name = "aio_iiro_16",
+	.module = THIS_MODULE,
+	.attach = aio_iiro_16_attach,
+	.detach = aio_iiro_16_detach,
+	.board_name = &aio_iiro_16_boards[0].name,
+	.offset = sizeof(struct aio_iiro_16_board),
+	.num_names = ARRAY_SIZE(aio_iiro_16_boards),
 };
 
-static int aio_iiro_16_dio_insn_bits_read(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
+static int aio_iiro_16_dio_insn_bits_read(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
 
-static int aio_iiro_16_dio_insn_bits_write(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
+static int aio_iiro_16_dio_insn_bits_write(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
 
-static int aio_iiro_16_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int aio_iiro_16_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int iobase;
 	struct comedi_subdevice *s;
@@ -132,7 +132,7 @@
 	return 1;
 }
 
-static int aio_iiro_16_detach(struct comedi_device * dev)
+static int aio_iiro_16_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: aio_iiro_16: remove\n", dev->minor);
 
@@ -142,8 +142,8 @@
 	return 0;
 }
 
-static int aio_iiro_16_dio_insn_bits_write(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int aio_iiro_16_dio_insn_bits_write(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -161,8 +161,8 @@
 	return 2;
 }
 
-static int aio_iiro_16_dio_insn_bits_read(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int aio_iiro_16_dio_insn_bits_read(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
diff --git a/drivers/staging/comedi/drivers/am9513.h b/drivers/staging/comedi/drivers/am9513.h
index f533cf1..73367d6 100644
--- a/drivers/staging/comedi/drivers/am9513.h
+++ b/drivers/staging/comedi/drivers/am9513.h
@@ -46,33 +46,33 @@
 
 #ifdef Am9513_8BITBUS
 
-#define Am9513_write_register(reg,val)				\
+#define Am9513_write_register(reg, val)				\
 	do{							\
 		Am9513_output_control(reg);			\
 		Am9513_output_data(val>>8);			\
 		Am9513_output_data(val&0xff);			\
-	}while(0)
+	}while (0)
 
-#define Am9513_read_register(reg,val)				\
+#define Am9513_read_register(reg, val)				\
 	do{							\
 		Am9513_output_control(reg);			\
 		val=Am9513_input_data()<<8;			\
 		val|=Am9513_input_data();			\
-	}while(0)
+	}while (0)
 
 #else /* Am9513_16BITBUS */
 
-#define Am9513_write_register(reg,val)				\
+#define Am9513_write_register(reg, val)				\
 	do{							\
 		Am9513_output_control(reg);			\
 		Am9513_output_data(val);			\
-	}while(0)
+	}while (0)
 
-#define Am9513_read_register(reg,val)				\
+#define Am9513_read_register(reg, val)				\
 	do{							\
 		Am9513_output_control(reg);			\
 		val=Am9513_input_data();			\
-	}while(0)
+	}while (0)
 
 #endif
 
diff --git a/drivers/staging/comedi/drivers/amcc_s5933.h b/drivers/staging/comedi/drivers/amcc_s5933.h
index aceffce..b810d5f 100644
--- a/drivers/staging/comedi/drivers/amcc_s5933.h
+++ b/drivers/staging/comedi/drivers/amcc_s5933.h
@@ -48,12 +48,12 @@
 /****************************************************************************/
 #define INTCSR_OUTBOX_BYTE(x)	((x) & 0x3)
 #define INTCSR_OUTBOX_SELECT(x)	(((x) & 0x3) << 2)
-#define INTCSR_OUTBOX_EMPTY_INT	0x10	// enable outbox empty interrupt
+#define INTCSR_OUTBOX_EMPTY_INT	0x10	/*  enable outbox empty interrupt */
 #define INTCSR_INBOX_BYTE(x)	(((x) & 0x3) << 8)
 #define INTCSR_INBOX_SELECT(x)	(((x) & 0x3) << 10)
-#define INTCSR_INBOX_FULL_INT	0x1000	// enable inbox full interrupt
-#define INTCSR_INBOX_INTR_STATUS	0x20000	// read, or write clear inbox full interrupt
-#define INTCSR_INTR_ASSERTED	0x800000	// read only, interrupt asserted
+#define INTCSR_INBOX_FULL_INT	0x1000	/*  enable inbox full interrupt */
+#define INTCSR_INBOX_INTR_STATUS	0x20000	/*  read, or write clear inbox full interrupt */
+#define INTCSR_INTR_ASSERTED	0x800000	/*  read only, interrupt asserted */
 
 /****************************************************************************/
 /* AMCC - PCI non-volatile ram command register (byte 3 of master control/status register) */
@@ -153,7 +153,7 @@
 #define AINT_IMB_SELECT 	0x0000000c
 #define AINT_IMB_BYTE		0x00000003
 
-// these are bits from various different registers, needs cleanup XXX
+/* these are bits from various different registers, needs cleanup XXX */
 /* Enable Bus Mastering */
 #define EN_A2P_TRANSFERS	0x00000400
 /* FIFO Flag Reset */
diff --git a/drivers/staging/comedi/drivers/amplc_dio200.c b/drivers/staging/comedi/drivers/amplc_dio200.c
index 8555e27..7446800 100644
--- a/drivers/staging/comedi/drivers/amplc_dio200.c
+++ b/drivers/staging/comedi/drivers/amplc_dio200.c
@@ -205,6 +205,8 @@
 order they appear in the channel list.
 */
 
+#include <linux/interrupt.h>
+
 #include "../comedidev.h"
 
 #include "comedi_pci.h"
@@ -288,59 +290,59 @@
 
 static const struct dio200_board dio200_boards[] = {
 	{
-	      name:	"pc212e",
-	      bustype:	isa_bustype,
-	      model:	pc212e_model,
-	      layout:	pc212_layout,
+	.name = "pc212e",
+	.bustype = isa_bustype,
+	.model = pc212e_model,
+	.layout = pc212_layout,
 		},
 	{
-	      name:	"pc214e",
-	      bustype:	isa_bustype,
-	      model:	pc214e_model,
-	      layout:	pc214_layout,
+	.name = "pc214e",
+	.bustype = isa_bustype,
+	.model = pc214e_model,
+	.layout = pc214_layout,
 		},
 	{
-	      name:	"pc215e",
-	      bustype:	isa_bustype,
-	      model:	pc215e_model,
-	      layout:	pc215_layout,
+	.name = "pc215e",
+	.bustype = isa_bustype,
+	.model = pc215e_model,
+	.layout = pc215_layout,
 		},
 #ifdef CONFIG_COMEDI_PCI
 	{
-	      name:	"pci215",
-	      devid:	PCI_DEVICE_ID_AMPLICON_PCI215,
-	      bustype:	pci_bustype,
-	      model:	pci215_model,
-	      layout:	pc215_layout,
+	.name = "pci215",
+	.devid = PCI_DEVICE_ID_AMPLICON_PCI215,
+	.bustype = pci_bustype,
+	.model = pci215_model,
+	.layout = pc215_layout,
 		},
 #endif
 	{
-	      name:	"pc218e",
-	      bustype:	isa_bustype,
-	      model:	pc218e_model,
-	      layout:	pc218_layout,
+	.name = "pc218e",
+	.bustype = isa_bustype,
+	.model = pc218e_model,
+	.layout = pc218_layout,
 		},
 	{
-	      name:	"pc272e",
-	      bustype:	isa_bustype,
-	      model:	pc272e_model,
-	      layout:	pc272_layout,
+	.name = "pc272e",
+	.bustype = isa_bustype,
+	.model = pc272e_model,
+	.layout = pc272_layout,
 		},
 #ifdef CONFIG_COMEDI_PCI
 	{
-	      name:	"pci272",
-	      devid:	PCI_DEVICE_ID_AMPLICON_PCI272,
-	      bustype:	pci_bustype,
-	      model:	pci272_model,
-	      layout:	pc272_layout,
+	.name = "pci272",
+	.devid = PCI_DEVICE_ID_AMPLICON_PCI272,
+	.bustype = pci_bustype,
+	.model = pci272_model,
+	.layout = pc272_layout,
 		},
 #endif
 #ifdef CONFIG_COMEDI_PCI
 	{
-	      name:	DIO200_DRIVER_NAME,
-	      devid:	PCI_DEVICE_ID_INVALID,
-	      bustype:	pci_bustype,
-	      model:	anypci_model,	/* wildcard */
+	.name = DIO200_DRIVER_NAME,
+	.devid = PCI_DEVICE_ID_INVALID,
+	.bustype = pci_bustype,
+	.model = anypci_model,	/* wildcard */
 		},
 #endif
 };
@@ -365,50 +367,50 @@
 
 static const struct dio200_layout_struct dio200_layouts[] = {
 	[pc212_layout] = {
-	      n_subdevs:6,
-	      sdtype:	{sd_8255, sd_8254, sd_8254, sd_8254,
+	.n_subdevs = 6,
+	.sdtype = {sd_8255, sd_8254, sd_8254, sd_8254,
 					sd_8254,
 				sd_intr},
-	      sdinfo:	{0x00, 0x08, 0x0C, 0x10, 0x14,
+	.sdinfo = {0x00, 0x08, 0x0C, 0x10, 0x14,
 				0x3F},
-	      has_int_sce:1,
-	      has_clk_gat_sce:1,
+	.has_int_sce = 1,
+	.has_clk_gat_sce = 1,
 		},
 	[pc214_layout] = {
-	      n_subdevs:4,
-	      sdtype:	{sd_8255, sd_8255, sd_8254,
+	.n_subdevs = 4,
+	.sdtype = {sd_8255, sd_8255, sd_8254,
 				sd_intr},
-	      sdinfo:	{0x00, 0x08, 0x10, 0x01},
-	      has_int_sce:0,
-	      has_clk_gat_sce:0,
+	.sdinfo = {0x00, 0x08, 0x10, 0x01},
+	.has_int_sce = 0,
+	.has_clk_gat_sce = 0,
 		},
 	[pc215_layout] = {
-	      n_subdevs:5,
-	      sdtype:	{sd_8255, sd_8255, sd_8254,
+	.n_subdevs = 5,
+	.sdtype = {sd_8255, sd_8255, sd_8254,
 					sd_8254,
 				sd_intr},
-	      sdinfo:	{0x00, 0x08, 0x10, 0x14, 0x3F},
-	      has_int_sce:1,
-	      has_clk_gat_sce:1,
+	.sdinfo = {0x00, 0x08, 0x10, 0x14, 0x3F},
+	.has_int_sce = 1,
+	.has_clk_gat_sce = 1,
 		},
 	[pc218_layout] = {
-	      n_subdevs:7,
-	      sdtype:	{sd_8254, sd_8254, sd_8255, sd_8254,
+	.n_subdevs = 7,
+	.sdtype = {sd_8254, sd_8254, sd_8255, sd_8254,
 					sd_8254,
 				sd_intr},
-	      sdinfo:	{0x00, 0x04, 0x08, 0x0C, 0x10,
+	.sdinfo = {0x00, 0x04, 0x08, 0x0C, 0x10,
 					0x14,
 				0x3F},
-	      has_int_sce:1,
-	      has_clk_gat_sce:1,
+	.has_int_sce = 1,
+	.has_clk_gat_sce = 1,
 		},
 	[pc272_layout] = {
-	      n_subdevs:4,
-	      sdtype:	{sd_8255, sd_8255, sd_8255,
+	.n_subdevs = 4,
+	.sdtype = {sd_8255, sd_8255, sd_8255,
 				sd_intr},
-	      sdinfo:	{0x00, 0x08, 0x10, 0x3F},
-	      has_int_sce:1,
-	      has_clk_gat_sce:0,
+	.sdinfo = {0x00, 0x08, 0x10, 0x3F},
+	.has_int_sce = 1,
+	.has_clk_gat_sce = 0,
 		},
 };
 
@@ -473,16 +475,16 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int dio200_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dio200_detach(struct comedi_device * dev);
+static int dio200_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dio200_detach(struct comedi_device *dev);
 static struct comedi_driver driver_amplc_dio200 = {
-      driver_name:DIO200_DRIVER_NAME,
-      module:THIS_MODULE,
-      attach:dio200_attach,
-      detach:dio200_detach,
-      board_name:&dio200_boards[0].name,
-      offset:sizeof(struct dio200_board),
-      num_names:sizeof(dio200_boards) / sizeof(struct dio200_board),
+	.driver_name = DIO200_DRIVER_NAME,
+	.module = THIS_MODULE,
+	.attach = dio200_attach,
+	.detach = dio200_detach,
+	.board_name = &dio200_boards[0].name,
+	.offset = sizeof(struct dio200_board),
+	.num_names = ARRAY_SIZE(dio200_boards),
 };
 
 #ifdef CONFIG_COMEDI_PCI
@@ -497,7 +499,7 @@
  */
 #ifdef CONFIG_COMEDI_PCI
 static int
-dio200_find_pci(struct comedi_device * dev, int bus, int slot,
+dio200_find_pci(struct comedi_device *dev, int bus, int slot,
 	struct pci_dev **pci_dev_p)
 {
 	struct pci_dev *pci_dev = NULL;
@@ -572,8 +574,8 @@
  * 'insn_bits' function for an 'INTERRUPT' subdevice.
  */
 static int
-dio200_subdev_intr_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+dio200_subdev_intr_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct dio200_subdev_intr *subpriv = s->private;
 
@@ -591,7 +593,7 @@
 /*
  * Called to stop acquisition for an 'INTERRUPT' subdevice.
  */
-static void dio200_stop_intr(struct comedi_device * dev, struct comedi_subdevice * s)
+static void dio200_stop_intr(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct dio200_subdev_intr *subpriv = s->private;
 
@@ -605,7 +607,7 @@
 /*
  * Called to start acquisition for an 'INTERRUPT' subdevice.
  */
-static int dio200_start_intr(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dio200_start_intr(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned int n;
 	unsigned isn_bits;
@@ -641,7 +643,7 @@
  * Internal trigger function to start acquisition for an 'INTERRUPT' subdevice.
  */
 static int
-dio200_inttrig_start_intr(struct comedi_device * dev, struct comedi_subdevice * s,
+dio200_inttrig_start_intr(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum)
 {
 	struct dio200_subdev_intr *subpriv;
@@ -653,12 +655,12 @@
 
 	subpriv = s->private;
 
-	comedi_spin_lock_irqsave(&subpriv->spinlock, flags);
+	spin_lock_irqsave(&subpriv->spinlock, flags);
 	s->async->inttrig = 0;
 	if (subpriv->active) {
 		event = dio200_start_intr(dev, s);
 	}
-	comedi_spin_unlock_irqrestore(&subpriv->spinlock, flags);
+	spin_unlock_irqrestore(&subpriv->spinlock, flags);
 
 	if (event) {
 		comedi_event(dev, s);
@@ -671,7 +673,7 @@
  * This is called from the interrupt service routine to handle a read
  * scan on an 'INTERRUPT' subdevice.
  */
-static int dio200_handle_read_intr(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dio200_handle_read_intr(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct dio200_subdev_intr *subpriv = s->private;
 	unsigned triggered;
@@ -682,7 +684,7 @@
 
 	triggered = 0;
 
-	comedi_spin_lock_irqsave(&subpriv->spinlock, flags);
+	spin_lock_irqsave(&subpriv->spinlock, flags);
 	oldevents = s->async->events;
 	if (subpriv->has_int_sce) {
 		/*
@@ -771,7 +773,7 @@
 			}
 		}
 	}
-	comedi_spin_unlock_irqrestore(&subpriv->spinlock, flags);
+	spin_unlock_irqrestore(&subpriv->spinlock, flags);
 
 	if (oldevents != s->async->events) {
 		comedi_event(dev, s);
@@ -783,16 +785,16 @@
 /*
  * 'cancel' function for an 'INTERRUPT' subdevice.
  */
-static int dio200_subdev_intr_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dio200_subdev_intr_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct dio200_subdev_intr *subpriv = s->private;
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&subpriv->spinlock, flags);
+	spin_lock_irqsave(&subpriv->spinlock, flags);
 	if (subpriv->active) {
 		dio200_stop_intr(dev, s);
 	}
-	comedi_spin_unlock_irqrestore(&subpriv->spinlock, flags);
+	spin_unlock_irqrestore(&subpriv->spinlock, flags);
 
 	return 0;
 }
@@ -801,8 +803,8 @@
  * 'do_cmdtest' function for an 'INTERRUPT' subdevice.
  */
 static int
-dio200_subdev_intr_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+dio200_subdev_intr_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	unsigned int tmp;
@@ -907,14 +909,14 @@
 /*
  * 'do_cmd' function for an 'INTERRUPT' subdevice.
  */
-static int dio200_subdev_intr_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dio200_subdev_intr_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	struct dio200_subdev_intr *subpriv = s->private;
 	unsigned long flags;
 	int event = 0;
 
-	comedi_spin_lock_irqsave(&subpriv->spinlock, flags);
+	spin_lock_irqsave(&subpriv->spinlock, flags);
 	subpriv->active = 1;
 
 	/* Set up end of acquisition. */
@@ -940,7 +942,7 @@
 		event = dio200_start_intr(dev, s);
 		break;
 	}
-	comedi_spin_unlock_irqrestore(&subpriv->spinlock, flags);
+	spin_unlock_irqrestore(&subpriv->spinlock, flags);
 
 	if (event) {
 		comedi_event(dev, s);
@@ -953,7 +955,7 @@
  * This function initializes an 'INTERRUPT' subdevice.
  */
 static int
-dio200_subdev_intr_init(struct comedi_device * dev, struct comedi_subdevice * s,
+dio200_subdev_intr_init(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long iobase, unsigned valid_isns, int has_int_sce)
 {
 	struct dio200_subdev_intr *subpriv;
@@ -998,7 +1000,7 @@
  * This function cleans up an 'INTERRUPT' subdevice.
  */
 static void
-dio200_subdev_intr_cleanup(struct comedi_device * dev, struct comedi_subdevice * s)
+dio200_subdev_intr_cleanup(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct dio200_subdev_intr *subpriv = s->private;
 
@@ -1010,7 +1012,7 @@
 /*
  * Interrupt service routine.
  */
-static irqreturn_t dio200_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t dio200_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	int handled;
@@ -1033,8 +1035,8 @@
  * Handle 'insn_read' for an '8254' counter subdevice.
  */
 static int
-dio200_subdev_8254_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+dio200_subdev_8254_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct dio200_subdev_8254 *subpriv = s->private;
 	int chan = CR_CHAN(insn->chanspec);
@@ -1048,8 +1050,8 @@
  * Handle 'insn_write' for an '8254' counter subdevice.
  */
 static int
-dio200_subdev_8254_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+dio200_subdev_8254_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct dio200_subdev_8254 *subpriv = s->private;
 	int chan = CR_CHAN(insn->chanspec);
@@ -1063,7 +1065,7 @@
  * Set gate source for an '8254' counter subdevice channel.
  */
 static int
-dio200_set_gate_src(struct dio200_subdev_8254 * subpriv, unsigned int counter_number,
+dio200_set_gate_src(struct dio200_subdev_8254 *subpriv, unsigned int counter_number,
 	unsigned int gate_src)
 {
 	unsigned char byte;
@@ -1086,7 +1088,7 @@
  * Get gate source for an '8254' counter subdevice channel.
  */
 static int
-dio200_get_gate_src(struct dio200_subdev_8254 * subpriv, unsigned int counter_number)
+dio200_get_gate_src(struct dio200_subdev_8254 *subpriv, unsigned int counter_number)
 {
 	if (!subpriv->has_clk_gat_sce)
 		return -1;
@@ -1100,7 +1102,7 @@
  * Set clock source for an '8254' counter subdevice channel.
  */
 static int
-dio200_set_clock_src(struct dio200_subdev_8254 * subpriv, unsigned int counter_number,
+dio200_set_clock_src(struct dio200_subdev_8254 *subpriv, unsigned int counter_number,
 	unsigned int clock_src)
 {
 	unsigned char byte;
@@ -1123,8 +1125,8 @@
  * Get clock source for an '8254' counter subdevice channel.
  */
 static int
-dio200_get_clock_src(struct dio200_subdev_8254 * subpriv, unsigned int counter_number,
-	unsigned int * period_ns)
+dio200_get_clock_src(struct dio200_subdev_8254 *subpriv, unsigned int counter_number,
+	unsigned int *period_ns)
 {
 	unsigned clock_src;
 
@@ -1142,8 +1144,8 @@
  * Handle 'insn_config' for an '8254' counter subdevice.
  */
 static int
-dio200_subdev_8254_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+dio200_subdev_8254_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct dio200_subdev_8254 *subpriv = s->private;
 	int ret;
@@ -1194,7 +1196,7 @@
  * offset is the offset to the 8254 chip.
  */
 static int
-dio200_subdev_8254_init(struct comedi_device * dev, struct comedi_subdevice * s,
+dio200_subdev_8254_init(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long iobase, unsigned offset, int has_clk_gat_sce)
 {
 	struct dio200_subdev_8254 *subpriv;
@@ -1247,7 +1249,7 @@
  * This function cleans up an '8254' counter subdevice.
  */
 static void
-dio200_subdev_8254_cleanup(struct comedi_device * dev, struct comedi_subdevice * s)
+dio200_subdev_8254_cleanup(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct dio200_subdev_intr *subpriv = s->private;
 
@@ -1262,7 +1264,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int dio200_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dio200_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase = 0;
@@ -1280,7 +1282,8 @@
 	printk(KERN_DEBUG "comedi%d: %s: attach\n", dev->minor,
 		DIO200_DRIVER_NAME);
 
-	if ((ret = alloc_private(dev, sizeof(struct dio200_private))) < 0) {
+	ret = alloc_private(dev, sizeof(struct dio200_private));
+	if (ret < 0) {
 		printk(KERN_ERR "comedi%d: error! out of memory!\n",
 			dev->minor);
 		return ret;
@@ -1299,7 +1302,8 @@
 		slot = it->options[1];
 		share_irq = 1;
 
-		if ((ret = dio200_find_pci(dev, bus, slot, &pci_dev)) < 0)
+		ret = dio200_find_pci(dev, bus, slot, &pci_dev);
+		if (ret < 0)
 			return ret;
 		devpriv->pci_dev = pci_dev;
 		break;
@@ -1337,7 +1341,9 @@
 	dev->iobase = iobase;
 
 	layout = thislayout;
-	if ((ret = alloc_subdevices(dev, layout->n_subdevs)) < 0) {
+
+	ret = alloc_subdevices(dev, layout->n_subdevs);
+	if (ret < 0) {
 		printk(KERN_ERR "comedi%d: error! out of memory!\n",
 			dev->minor);
 		return ret;
@@ -1392,7 +1398,7 @@
 	if (irq) {
 		unsigned long flags = share_irq ? IRQF_SHARED : 0;
 
-		if (comedi_request_irq(irq, dio200_interrupt, flags,
+		if (request_irq(irq, dio200_interrupt, flags,
 				DIO200_DRIVER_NAME, dev) >= 0) {
 			dev->irq = irq;
 		} else {
@@ -1429,7 +1435,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int dio200_detach(struct comedi_device * dev)
+static int dio200_detach(struct comedi_device *dev)
 {
 	const struct dio200_layout_struct *layout;
 	unsigned n;
@@ -1438,7 +1444,7 @@
 		DIO200_DRIVER_NAME);
 
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 	if (dev->subdevices) {
 		layout = thislayout;
diff --git a/drivers/staging/comedi/drivers/amplc_pc236.c b/drivers/staging/comedi/drivers/amplc_pc236.c
index 2027c75..48d7ccb 100644
--- a/drivers/staging/comedi/drivers/amplc_pc236.c
+++ b/drivers/staging/comedi/drivers/amplc_pc236.c
@@ -27,7 +27,7 @@
 Description: Amplicon PC36AT, PCI236
 Author: Ian Abbott <abbotti@mev.co.uk>
 Devices: [Amplicon] PC36AT (pc36at), PCI236 (pci236 or amplc_pc236)
-Updated: Wed, 22 Oct 2008 13:40:03 +0100
+Updated: Wed, 01 Apr 2009 15:41:25 +0100
 Status: works
 
 Configuration options - PC36AT:
@@ -45,13 +45,15 @@
 
 Subdevice 1 pretends to be a digital input device, but it always returns
 0 when read. However, if you run a command with scan_begin_src=TRIG_EXT,
-a rising edge on port C bit 7 acts as an external trigger, which can be
+a rising edge on port C bit 3 acts as an external trigger, which can be
 used to wake up tasks.  This is like the comedi_parport device, but the
 only way to physically disable the interrupt on the PC36AT is to remove
 the IRQ jumper.  If no interrupt is connected, then subdevice 1 is
 unused.
 */
 
+#include <linux/interrupt.h>
+
 #include "../comedidev.h"
 
 #include "comedi_pci.h"
@@ -75,19 +77,19 @@
  * INTCSR values for PCI236.
  */
 /* Disable interrupt, also clear any interrupt there */
-#define PCI236_INTR_DISABLE ( PLX9052_INTCSR_LI1ENAB_DISABLED \
+#define PCI236_INTR_DISABLE (PLX9052_INTCSR_LI1ENAB_DISABLED \
         | PLX9052_INTCSR_LI1POL_HIGH \
         | PLX9052_INTCSR_LI2POL_HIGH \
         | PLX9052_INTCSR_PCIENAB_DISABLED \
         | PLX9052_INTCSR_LI1SEL_EDGE \
-        | PLX9052_INTCSR_LI1CLRINT_ASSERTED )
+        | PLX9052_INTCSR_LI1CLRINT_ASSERTED)
 /* Enable interrupt, also clear any interrupt there. */
-#define PCI236_INTR_ENABLE ( PLX9052_INTCSR_LI1ENAB_ENABLED \
+#define PCI236_INTR_ENABLE (PLX9052_INTCSR_LI1ENAB_ENABLED \
         | PLX9052_INTCSR_LI1POL_HIGH \
         | PLX9052_INTCSR_LI2POL_HIGH \
         | PLX9052_INTCSR_PCIENAB_ENABLED \
         | PLX9052_INTCSR_LI1SEL_EDGE \
-        | PLX9052_INTCSR_LI1CLRINT_ASSERTED )
+        | PLX9052_INTCSR_LI1CLRINT_ASSERTED)
 
 /*
  * Board descriptions for Amplicon PC36AT and PCI236.
@@ -105,27 +107,27 @@
 };
 static const struct pc236_board pc236_boards[] = {
 	{
-	      name:	"pc36at",
-	      fancy_name:"PC36AT",
-	      bustype:	isa_bustype,
-	      model:	pc36at_model,
+	.name = "pc36at",
+	.fancy_name = "PC36AT",
+	.bustype = isa_bustype,
+	.model = pc36at_model,
 		},
 #ifdef CONFIG_COMEDI_PCI
 	{
-	      name:	"pci236",
-	      fancy_name:"PCI236",
-	      devid:	PCI_DEVICE_ID_AMPLICON_PCI236,
-	      bustype:	pci_bustype,
-	      model:	pci236_model,
+	.name = "pci236",
+	.fancy_name = "PCI236",
+	.devid = PCI_DEVICE_ID_AMPLICON_PCI236,
+	.bustype = pci_bustype,
+	.model = pci236_model,
 		},
 #endif
 #ifdef CONFIG_COMEDI_PCI
 	{
-	      name:	PC236_DRIVER_NAME,
-	      fancy_name:PC236_DRIVER_NAME,
-	      devid:	PCI_DEVICE_ID_INVALID,
-	      bustype:	pci_bustype,
-	      model:	anypci_model,	/* wildcard */
+	.name = PC236_DRIVER_NAME,
+	.fancy_name = PC236_DRIVER_NAME,
+	.devid = PCI_DEVICE_ID_INVALID,
+	.bustype = pci_bustype,
+	.model = anypci_model,	/* wildcard */
 		},
 #endif
 };
@@ -165,16 +167,16 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int pc236_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pc236_detach(struct comedi_device * dev);
+static int pc236_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pc236_detach(struct comedi_device *dev);
 static struct comedi_driver driver_amplc_pc236 = {
-      driver_name:PC236_DRIVER_NAME,
-      module:THIS_MODULE,
-      attach:pc236_attach,
-      detach:pc236_detach,
-      board_name:&pc236_boards[0].name,
-      offset:sizeof(struct pc236_board),
-      num_names:sizeof(pc236_boards) / sizeof(struct pc236_board),
+	.driver_name = PC236_DRIVER_NAME,
+	.module = THIS_MODULE,
+	.attach = pc236_attach,
+	.detach = pc236_detach,
+	.board_name = &pc236_boards[0].name,
+	.offset = sizeof(struct pc236_board),
+	.num_names = ARRAY_SIZE(pc236_boards),
 };
 
 #ifdef CONFIG_COMEDI_PCI
@@ -185,16 +187,16 @@
 
 static int pc236_request_region(unsigned minor, unsigned long from,
 	unsigned long extent);
-static void pc236_intr_disable(struct comedi_device * dev);
-static void pc236_intr_enable(struct comedi_device * dev);
-static int pc236_intr_check(struct comedi_device * dev);
-static int pc236_intr_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int pc236_intr_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int pc236_intr_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int pc236_intr_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static irqreturn_t pc236_interrupt(int irq, void *d PT_REGS_ARG);
+static void pc236_intr_disable(struct comedi_device *dev);
+static void pc236_intr_enable(struct comedi_device *dev);
+static int pc236_intr_check(struct comedi_device *dev);
+static int pc236_intr_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int pc236_intr_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int pc236_intr_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int pc236_intr_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static irqreturn_t pc236_interrupt(int irq, void *d);
 
 /*
  * This function looks for a PCI device matching the requested board name,
@@ -202,7 +204,7 @@
  */
 #ifdef CONFIG_COMEDI_PCI
 static int
-pc236_find_pci(struct comedi_device * dev, int bus, int slot,
+pc236_find_pci(struct comedi_device *dev, int bus, int slot,
 	struct pci_dev **pci_dev_p)
 {
 	struct pci_dev *pci_dev = NULL;
@@ -264,7 +266,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int pc236_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pc236_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase = 0;
@@ -282,7 +284,8 @@
  * Allocate the private structure area.  alloc_private() is a
  * convenient macro defined in comedidev.h.
  */
-	if ((ret = alloc_private(dev, sizeof(struct pc236_private))) < 0) {
+	ret = alloc_private(dev, sizeof(struct pc236_private));
+	if (ret < 0) {
 		printk(KERN_ERR "comedi%d: error! out of memory!\n",
 			dev->minor);
 		return ret;
@@ -300,7 +303,8 @@
 		slot = it->options[1];
 		share_irq = 1;
 
-		if ((ret = pc236_find_pci(dev, bus, slot, &pci_dev)) < 0)
+		ret = pc236_find_pci(dev, bus, slot, &pci_dev);
+		if (ret < 0)
 			return ret;
 		devpriv->pci_dev = pci_dev;
 		break;
@@ -321,7 +325,9 @@
 	/* Enable device and reserve I/O spaces. */
 #ifdef CONFIG_COMEDI_PCI
 	if (pci_dev) {
-		if ((ret = comedi_pci_enable(pci_dev, PC236_DRIVER_NAME)) < 0) {
+
+		ret = comedi_pci_enable(pci_dev, PC236_DRIVER_NAME);
+		if (ret < 0) {
 			printk(KERN_ERR
 				"comedi%d: error! cannot enable PCI device and request regions!\n",
 				dev->minor);
@@ -344,7 +350,8 @@
  * Allocate the subdevice structures.  alloc_subdevice() is a
  * convenient macro defined in comedidev.h.
  */
-	if ((ret = alloc_subdevices(dev, 2)) < 0) {
+	ret = alloc_subdevices(dev, 2);
+	if (ret < 0) {
 		printk(KERN_ERR "comedi%d: error! out of memory!\n",
 			dev->minor);
 		return ret;
@@ -352,7 +359,8 @@
 
 	s = dev->subdevices + 0;
 	/* digital i/o subdevice (8255) */
-	if ((ret = subdev_8255_init(dev, s, NULL, iobase)) < 0) {
+	ret = subdev_8255_init(dev, s, NULL, iobase);
+	if (ret < 0) {
 		printk(KERN_ERR "comedi%d: error! out of memory!\n",
 			dev->minor);
 		return ret;
@@ -364,7 +372,7 @@
 	if (irq) {
 		unsigned long flags = share_irq ? IRQF_SHARED : 0;
 
-		if (comedi_request_irq(irq, pc236_interrupt, flags,
+		if (request_irq(irq, pc236_interrupt, flags,
 				PC236_DRIVER_NAME, dev) >= 0) {
 			dev->irq = irq;
 			s->type = COMEDI_SUBD_DI;
@@ -405,7 +413,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int pc236_detach(struct comedi_device * dev)
+static int pc236_detach(struct comedi_device *dev)
 {
 	printk(KERN_DEBUG "comedi%d: %s: detach\n", dev->minor,
 		PC236_DRIVER_NAME);
@@ -413,7 +421,7 @@
 		pc236_intr_disable(dev);
 	}
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	if (dev->subdevices) {
 		subdev_8255_cleanup(dev, dev->subdevices + 0);
 	}
@@ -459,17 +467,17 @@
  * configured on subdevice 1) and to physically disable the interrupt
  * (not possible on the PC36AT, except by removing the IRQ jumper!).
  */
-static void pc236_intr_disable(struct comedi_device * dev)
+static void pc236_intr_disable(struct comedi_device *dev)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	devpriv->enable_irq = 0;
 #ifdef CONFIG_COMEDI_PCI
 	if (devpriv->lcr_iobase)
 		outl(PCI236_INTR_DISABLE, devpriv->lcr_iobase + PLX9052_INTCSR);
 #endif
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 }
 
 /*
@@ -477,17 +485,17 @@
  * configured on subdevice 1) and to physically enable the interrupt
  * (not possible on the PC36AT, except by (re)connecting the IRQ jumper!).
  */
-static void pc236_intr_enable(struct comedi_device * dev)
+static void pc236_intr_enable(struct comedi_device *dev)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	devpriv->enable_irq = 1;
 #ifdef CONFIG_COMEDI_PCI
 	if (devpriv->lcr_iobase)
 		outl(PCI236_INTR_ENABLE, devpriv->lcr_iobase + PLX9052_INTCSR);
 #endif
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 }
 
 /*
@@ -497,12 +505,12 @@
  * interrupt.
  * Returns 0 if the interrupt should be ignored.
  */
-static int pc236_intr_check(struct comedi_device * dev)
+static int pc236_intr_check(struct comedi_device *dev)
 {
 	int retval = 0;
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	if (devpriv->enable_irq) {
 		retval = 1;
 #ifdef CONFIG_COMEDI_PCI
@@ -519,7 +527,7 @@
 		}
 #endif
 	}
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	return retval;
 }
@@ -528,8 +536,8 @@
  * Input from subdevice 1.
  * Copied from the comedi_parport driver.
  */
-static int pc236_intr_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pc236_intr_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[1] = 0;
 	return 2;
@@ -539,8 +547,8 @@
  * Subdevice 1 command test.
  * Copied from the comedi_parport driver.
  */
-static int pc236_intr_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int pc236_intr_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -617,7 +625,7 @@
 /*
  * Subdevice 1 command.
  */
-static int pc236_intr_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pc236_intr_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	pc236_intr_enable(dev);
 
@@ -627,7 +635,7 @@
 /*
  * Subdevice 1 cancel command.
  */
-static int pc236_intr_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pc236_intr_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	pc236_intr_disable(dev);
 
@@ -638,7 +646,7 @@
  * Interrupt service routine.
  * Based on the comedi_parport driver.
  */
-static irqreturn_t pc236_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t pc236_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s = dev->subdevices + 1;
diff --git a/drivers/staging/comedi/drivers/amplc_pc263.c b/drivers/staging/comedi/drivers/amplc_pc263.c
index 97ac415..730b677 100644
--- a/drivers/staging/comedi/drivers/amplc_pc263.c
+++ b/drivers/staging/comedi/drivers/amplc_pc263.c
@@ -74,27 +74,27 @@
 };
 static const struct pc263_board pc263_boards[] = {
 	{
-	      name:	"pc263",
-	      fancy_name:"PC263",
-	      bustype:	isa_bustype,
-	      model:	pc263_model,
+	.name = "pc263",
+	.fancy_name = "PC263",
+	.bustype = isa_bustype,
+	.model = pc263_model,
 		},
 #ifdef CONFIG_COMEDI_PCI
 	{
-	      name:	"pci263",
-	      fancy_name:"PCI263",
-	      devid:	PCI_DEVICE_ID_AMPLICON_PCI263,
-	      bustype:	pci_bustype,
-	      model:	pci263_model,
+	.name = "pci263",
+	.fancy_name = "PCI263",
+	.devid = PCI_DEVICE_ID_AMPLICON_PCI263,
+	.bustype = pci_bustype,
+	.model = pci263_model,
 		},
 #endif
 #ifdef CONFIG_COMEDI_PCI
 	{
-	      name:	PC263_DRIVER_NAME,
-	      fancy_name:PC263_DRIVER_NAME,
-	      devid:	PCI_DEVICE_ID_INVALID,
-	      bustype:	pci_bustype,
-	      model:	anypci_model,	/* wildcard */
+	.name = PC263_DRIVER_NAME,
+	.fancy_name = PC263_DRIVER_NAME,
+	.devid = PCI_DEVICE_ID_INVALID,
+	.bustype = pci_bustype,
+	.model = anypci_model,	/* wildcard */
 		},
 #endif
 };
@@ -132,24 +132,24 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int pc263_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pc263_detach(struct comedi_device * dev);
+static int pc263_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pc263_detach(struct comedi_device *dev);
 static struct comedi_driver driver_amplc_pc263 = {
-      driver_name:PC263_DRIVER_NAME,
-      module:THIS_MODULE,
-      attach:pc263_attach,
-      detach:pc263_detach,
-      board_name:&pc263_boards[0].name,
-      offset:sizeof(struct pc263_board),
-      num_names:sizeof(pc263_boards) / sizeof(struct pc263_board),
+	.driver_name = PC263_DRIVER_NAME,
+	.module = THIS_MODULE,
+	.attach = pc263_attach,
+	.detach = pc263_detach,
+	.board_name = &pc263_boards[0].name,
+	.offset = sizeof(struct pc263_board),
+	.num_names = ARRAY_SIZE(pc263_boards),
 };
 
 static int pc263_request_region(unsigned minor, unsigned long from,
 	unsigned long extent);
-static int pc263_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int pc263_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int pc263_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int pc263_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 /*
  * This function looks for a PCI device matching the requested board name,
@@ -157,7 +157,7 @@
  */
 #ifdef CONFIG_COMEDI_PCI
 static int
-pc263_find_pci(struct comedi_device * dev, int bus, int slot,
+pc263_find_pci(struct comedi_device *dev, int bus, int slot,
 	struct pci_dev **pci_dev_p)
 {
 	struct pci_dev *pci_dev = NULL;
@@ -219,7 +219,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int pc263_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pc263_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase = 0;
@@ -236,7 +236,8 @@
  * convenient macro defined in comedidev.h.
  */
 #ifdef CONFIG_COMEDI_PCI
-	if ((ret = alloc_private(dev, sizeof(struct pc263_private))) < 0) {
+	ret = alloc_private(dev, sizeof(struct pc263_private));
+	if (ret < 0) {
 		printk(KERN_ERR "comedi%d: error! out of memory!\n",
 			dev->minor);
 		return ret;
@@ -252,7 +253,8 @@
 		bus = it->options[0];
 		slot = it->options[1];
 
-		if ((ret = pc263_find_pci(dev, bus, slot, &pci_dev)) < 0)
+		ret = pc263_find_pci(dev, bus, slot, &pci_dev);
+		if (ret < 0)
 			return ret;
 		devpriv->pci_dev = pci_dev;
 		break;
@@ -273,7 +275,8 @@
 	/* Enable device and reserve I/O spaces. */
 #ifdef CONFIG_COMEDI_PCI
 	if (pci_dev) {
-		if ((ret = comedi_pci_enable(pci_dev, PC263_DRIVER_NAME)) < 0) {
+		ret = comedi_pci_enable(pci_dev, PC263_DRIVER_NAME);
+		if (ret < 0) {
 			printk(KERN_ERR
 				"comedi%d: error! cannot enable PCI device and request regions!\n",
 				dev->minor);
@@ -294,7 +297,8 @@
  * Allocate the subdevice structures.  alloc_subdevice() is a
  * convenient macro defined in comedidev.h.
  */
-	if ((ret = alloc_subdevices(dev, 1)) < 0) {
+	ret = alloc_subdevices(dev, 1);
+	if (ret < 0) {
 		printk(KERN_ERR "comedi%d: error! out of memory!\n",
 			dev->minor);
 		return ret;
@@ -303,7 +307,7 @@
 	s = dev->subdevices + 0;
 	/* digital i/o subdevice */
 	s->type = COMEDI_SUBD_DIO;
-	s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_RT;
+	s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
 	s->n_chan = 16;
 	s->maxdata = 1;
 	s->range_table = &range_digital;
@@ -337,7 +341,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int pc263_detach(struct comedi_device * dev)
+static int pc263_detach(struct comedi_device *dev)
 {
 	printk(KERN_DEBUG "comedi%d: %s: detach\n", dev->minor,
 		PC263_DRIVER_NAME);
@@ -387,8 +391,8 @@
  * useful to applications if you implement the insn_bits interface.
  * This allows packed reading/writing of the DIO channels.  The
  * comedi core can convert between insn_bits and insn_read/write */
-static int pc263_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pc263_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -412,8 +416,8 @@
 	return 2;
 }
 
-static int pc263_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pc263_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 1)
 		return -EINVAL;
diff --git a/drivers/staging/comedi/drivers/amplc_pci224.c b/drivers/staging/comedi/drivers/amplc_pci224.c
index 770b966..d1a64e8 100644
--- a/drivers/staging/comedi/drivers/amplc_pci224.c
+++ b/drivers/staging/comedi/drivers/amplc_pci224.c
@@ -103,6 +103,8 @@
      correctly.
 */
 
+#include <linux/interrupt.h>
+
 #include "../comedidev.h"
 
 #include "comedi_pci.h"
@@ -356,23 +358,23 @@
 
 static const struct pci224_board pci224_boards[] = {
 	{
-	      name:	"pci224",
-	      devid: PCI_DEVICE_ID_AMPLICON_PCI224,
-	      model:	pci224_model,
-	      ao_chans:16,
-	      ao_bits:	12,
+	.name = "pci224",
+	.devid = PCI_DEVICE_ID_AMPLICON_PCI224,
+	.model = pci224_model,
+	.ao_chans = 16,
+	.ao_bits = 12,
 		},
 	{
-	      name:	"pci234",
-	      devid: PCI_DEVICE_ID_AMPLICON_PCI234,
-	      model:	pci234_model,
-	      ao_chans:4,
-	      ao_bits:	16,
+	.name = "pci234",
+	.devid = PCI_DEVICE_ID_AMPLICON_PCI234,
+	.model = pci234_model,
+	.ao_chans = 4,
+	.ao_bits = 16,
 		},
 	{
-	      name:	DRIVER_NAME,
-	      devid: PCI_DEVICE_ID_INVALID,
-	      model:	any_model,	/* wildcard */
+	.name = DRIVER_NAME,
+	.devid = PCI_DEVICE_ID_INVALID,
+	.model = any_model,	/* wildcard */
 		},
 };
 
@@ -426,16 +428,16 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int pci224_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pci224_detach(struct comedi_device * dev);
+static int pci224_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pci224_detach(struct comedi_device *dev);
 static struct comedi_driver driver_amplc_pci224 = {
-      driver_name:DRIVER_NAME,
-      module:THIS_MODULE,
-      attach:pci224_attach,
-      detach:pci224_detach,
-      board_name:&pci224_boards[0].name,
-      offset:sizeof(struct pci224_board),
-      num_names:sizeof(pci224_boards) / sizeof(struct pci224_board),
+	.driver_name = DRIVER_NAME,
+	.module = THIS_MODULE,
+	.attach = pci224_attach,
+	.detach = pci224_detach,
+	.board_name = &pci224_boards[0].name,
+	.offset = sizeof(struct pci224_board),
+	.num_names = ARRAY_SIZE(pci224_boards),
 };
 
 COMEDI_PCI_INITCLEANUP(driver_amplc_pci224, pci224_pci_table);
@@ -444,7 +446,7 @@
  * Called from the 'insn_write' function to perform a single write.
  */
 static void
-pci224_ao_set_data(struct comedi_device * dev, int chan, int range, unsigned int data)
+pci224_ao_set_data(struct comedi_device *dev, int chan, int range, unsigned int data)
 {
 	unsigned short mangled;
 
@@ -477,8 +479,8 @@
  * 'insn_write' function for AO subdevice.
  */
 static int
-pci224_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+pci224_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan, range;
@@ -504,8 +506,8 @@
  * command.
  */
 static int
-pci224_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+pci224_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan;
@@ -532,7 +534,7 @@
 /*
  * Kills a command running on the AO subdevice.
  */
-static void pci224_ao_stop(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pci224_ao_stop(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 
@@ -540,7 +542,7 @@
 		return;
 	}
 
-	comedi_spin_lock_irqsave(&devpriv->ao_spinlock, flags);
+	spin_lock_irqsave(&devpriv->ao_spinlock, flags);
 	/* Kill the interrupts. */
 	devpriv->intsce = 0;
 	outb(0, devpriv->iobase1 + PCI224_INT_SCE);
@@ -556,10 +558,10 @@
 	 * routine.
 	 */
 	while (devpriv->intr_running && devpriv->intr_cpuid != THISCPU) {
-		comedi_spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
-		comedi_spin_lock_irqsave(&devpriv->ao_spinlock, flags);
+		spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
+		spin_lock_irqsave(&devpriv->ao_spinlock, flags);
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
+	spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
 	/* Reconfigure DAC for insn_write usage. */
 	outw(0, dev->iobase + PCI224_DACCEN);	/* Disable channels. */
 	devpriv->daccon = COMBINE(devpriv->daccon,
@@ -572,7 +574,7 @@
 /*
  * Handles start of acquisition for the AO subdevice.
  */
-static void pci224_ao_start(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pci224_ao_start(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	unsigned long flags;
@@ -585,21 +587,21 @@
 		comedi_event(dev, s);
 	} else {
 		/* Enable interrupts. */
-		comedi_spin_lock_irqsave(&devpriv->ao_spinlock, flags);
+		spin_lock_irqsave(&devpriv->ao_spinlock, flags);
 		if (cmd->stop_src == TRIG_EXT) {
 			devpriv->intsce = PCI224_INTR_EXT | PCI224_INTR_DAC;
 		} else {
 			devpriv->intsce = PCI224_INTR_DAC;
 		}
 		outb(devpriv->intsce, devpriv->iobase1 + PCI224_INT_SCE);
-		comedi_spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
+		spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
 	}
 }
 
 /*
  * Handles interrupts from the DAC FIFO.
  */
-static void pci224_ao_handle_fifo(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pci224_ao_handle_fifo(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	unsigned int num_scans;
@@ -653,7 +655,7 @@
 			/* Nothing left to put in the FIFO. */
 			pci224_ao_stop(dev, s);
 			s->async->events |= COMEDI_CB_OVERFLOW;
-			rt_printk(KERN_ERR "comedi%d: "
+			printk(KERN_ERR "comedi%d: "
 				"AO buffer underrun\n", dev->minor);
 		}
 	}
@@ -728,7 +730,7 @@
  * Internal trigger function to start acquisition on AO subdevice.
  */
 static int
-pci224_ao_inttrig_start(struct comedi_device * dev, struct comedi_subdevice * s,
+pci224_ao_inttrig_start(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum)
 {
 	if (trignum != 0)
@@ -748,7 +750,7 @@
  * 'do_cmdtest' function for AO subdevice.
  */
 static int
-pci224_ao_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s, struct comedi_cmd * cmd)
+pci224_ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_cmd *cmd)
 {
 	int err = 0;
 	unsigned int tmp;
@@ -1015,7 +1017,7 @@
 /*
  * 'do_cmd' function for AO subdevice.
  */
-static int pci224_ao_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci224_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	int range;
@@ -1153,16 +1155,16 @@
 	 */
 	switch (cmd->start_src) {
 	case TRIG_INT:
-		comedi_spin_lock_irqsave(&devpriv->ao_spinlock, flags);
+		spin_lock_irqsave(&devpriv->ao_spinlock, flags);
 		s->async->inttrig = &pci224_ao_inttrig_start;
-		comedi_spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
+		spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
 		break;
 	case TRIG_EXT:
 		/* Enable external interrupt trigger to start acquisition. */
-		comedi_spin_lock_irqsave(&devpriv->ao_spinlock, flags);
+		spin_lock_irqsave(&devpriv->ao_spinlock, flags);
 		devpriv->intsce |= PCI224_INTR_EXT;
 		outb(devpriv->intsce, devpriv->iobase1 + PCI224_INT_SCE);
-		comedi_spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
+		spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
 		break;
 	}
 
@@ -1172,7 +1174,7 @@
 /*
  * 'cancel' function for AO subdevice.
  */
-static int pci224_ao_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci224_ao_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	pci224_ao_stop(dev, s);
 	return 0;
@@ -1182,7 +1184,7 @@
  * 'munge' data for AO command.
  */
 static void
-pci224_ao_munge(struct comedi_device * dev, struct comedi_subdevice * s, void *data,
+pci224_ao_munge(struct comedi_device *dev, struct comedi_subdevice *s, void *data,
 	unsigned int num_bytes, unsigned int chan_index)
 {
 	struct comedi_async *async = s->async;
@@ -1212,7 +1214,7 @@
 /*
  * Interrupt handler.
  */
-static irqreturn_t pci224_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t pci224_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s = &dev->subdevices[0];
@@ -1225,14 +1227,14 @@
 	intstat = inb(devpriv->iobase1 + PCI224_INT_SCE) & 0x3F;
 	if (intstat) {
 		retval = 1;
-		comedi_spin_lock_irqsave(&devpriv->ao_spinlock, flags);
+		spin_lock_irqsave(&devpriv->ao_spinlock, flags);
 		valid_intstat = devpriv->intsce & intstat;
 		/* Temporarily disable interrupt sources. */
 		curenab = devpriv->intsce & ~intstat;
 		outb(curenab, devpriv->iobase1 + PCI224_INT_SCE);
 		devpriv->intr_running = 1;
 		devpriv->intr_cpuid = THISCPU;
-		comedi_spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
+		spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
 		if (valid_intstat != 0) {
 			cmd = &s->async->cmd;
 			if (valid_intstat & PCI224_INTR_EXT) {
@@ -1248,13 +1250,13 @@
 			}
 		}
 		/* Reenable interrupt sources. */
-		comedi_spin_lock_irqsave(&devpriv->ao_spinlock, flags);
+		spin_lock_irqsave(&devpriv->ao_spinlock, flags);
 		if (curenab != devpriv->intsce) {
 			outb(devpriv->intsce,
 				devpriv->iobase1 + PCI224_INT_SCE);
 		}
 		devpriv->intr_running = 0;
-		comedi_spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
+		spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
 	}
 	return IRQ_RETVAL(retval);
 }
@@ -1264,7 +1266,7 @@
  * bus and slot.
  */
 static int
-pci224_find_pci(struct comedi_device * dev, int bus, int slot,
+pci224_find_pci(struct comedi_device *dev, int bus, int slot,
 	struct pci_dev **pci_dev_p)
 {
 	struct pci_dev *pci_dev = NULL;
@@ -1323,7 +1325,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int pci224_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pci224_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	struct pci_dev *pci_dev;
@@ -1336,16 +1338,20 @@
 
 	bus = it->options[0];
 	slot = it->options[1];
-	if ((ret = alloc_private(dev, sizeof(struct pci224_private))) < 0) {
+	ret = alloc_private(dev, sizeof(struct pci224_private));
+	if (ret < 0) {
 		printk(KERN_ERR "comedi%d: error! out of memory!\n",
 			dev->minor);
 		return ret;
 	}
-	if ((ret = pci224_find_pci(dev, bus, slot, &pci_dev)) < 0)
-		return ret;
-	devpriv->pci_dev = pci_dev;
 
-	if ((ret = comedi_pci_enable(pci_dev, DRIVER_NAME)) < 0) {
+	ret = pci224_find_pci(dev, bus, slot, &pci_dev);
+	if (ret < 0)
+		return ret;
+
+	devpriv->pci_dev = pci_dev;
+	ret = comedi_pci_enable(pci_dev, DRIVER_NAME);
+	if (ret < 0) {
 		printk(KERN_ERR
 			"comedi%d: error! cannot enable PCI device "
 			"and request regions!\n", dev->minor);
@@ -1392,7 +1398,8 @@
 		dev->iobase + PCI224_DACCON);
 
 	/* Allocate subdevices.  There is only one!  */
-	if ((ret = alloc_subdevices(dev, 1)) < 0) {
+	ret = alloc_subdevices(dev, 1);
+	if (ret < 0) {
 		printk(KERN_ERR "comedi%d: error! out of memory!\n",
 			dev->minor);
 		return ret;
@@ -1471,8 +1478,8 @@
 	dev->board_name = thisboard->name;
 
 	if (irq) {
-		ret = comedi_request_irq(irq, pci224_interrupt, IRQF_SHARED,
-			DRIVER_NAME, dev);
+		ret = request_irq(irq, pci224_interrupt, IRQF_SHARED,
+				  DRIVER_NAME, dev);
 		if (ret < 0) {
 			printk(KERN_ERR "comedi%d: error! "
 				"unable to allocate irq %u\n", dev->minor, irq);
@@ -1503,12 +1510,12 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int pci224_detach(struct comedi_device * dev)
+static int pci224_detach(struct comedi_device *dev)
 {
 	printk(KERN_DEBUG "comedi%d: %s: detach\n", dev->minor, DRIVER_NAME);
 
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 	if (dev->subdevices) {
 		struct comedi_subdevice *s;
diff --git a/drivers/staging/comedi/drivers/amplc_pci230.c b/drivers/staging/comedi/drivers/amplc_pci230.c
index 0c9e573..21133f0 100644
--- a/drivers/staging/comedi/drivers/amplc_pci230.c
+++ b/drivers/staging/comedi/drivers/amplc_pci230.c
@@ -187,9 +187,11 @@
 Support for PCI230+/260+, more triggered scan functionality, and workarounds
 for (or detection of) various hardware problems added by Ian Abbott.
 */
+
 #include "../comedidev.h"
 
 #include <linux/delay.h>
+#include <linux/interrupt.h>
 
 #include "comedi_pci.h"
 #include "8253.h"
@@ -455,46 +457,46 @@
 };
 static const struct pci230_board pci230_boards[] = {
 	{
-	      name:	"pci230+",
-	      id:	PCI_DEVICE_ID_PCI230,
-	      ai_chans:16,
-	      ai_bits:	16,
-	      ao_chans:2,
-	      ao_bits:	12,
-	      have_dio:1,
-	      min_hwver:1,
+	.name = "pci230+",
+	.id = PCI_DEVICE_ID_PCI230,
+	.ai_chans = 16,
+	.ai_bits = 16,
+	.ao_chans = 2,
+	.ao_bits = 12,
+	.have_dio = 1,
+	.min_hwver = 1,
 		},
 	{
-	      name:	"pci260+",
-	      id:	PCI_DEVICE_ID_PCI260,
-	      ai_chans:16,
-	      ai_bits:	16,
-	      ao_chans:0,
-	      ao_bits:	0,
-	      have_dio:0,
-	      min_hwver:1,
+	.name = "pci260+",
+	.id = PCI_DEVICE_ID_PCI260,
+	.ai_chans = 16,
+	.ai_bits = 16,
+	.ao_chans = 0,
+	.ao_bits = 0,
+	.have_dio = 0,
+	.min_hwver = 1,
 		},
 	{
-	      name:	"pci230",
-	      id:	PCI_DEVICE_ID_PCI230,
-	      ai_chans:16,
-	      ai_bits:	12,
-	      ao_chans:2,
-	      ao_bits:	12,
-	      have_dio:1,
+	.name = "pci230",
+	.id = PCI_DEVICE_ID_PCI230,
+	.ai_chans = 16,
+	.ai_bits = 12,
+	.ao_chans = 2,
+	.ao_bits = 12,
+	.have_dio = 1,
 		},
 	{
-	      name:	"pci260",
-	      id:	PCI_DEVICE_ID_PCI260,
-	      ai_chans:16,
-	      ai_bits:	12,
-	      ao_chans:0,
-	      ao_bits:	0,
-	      have_dio:0,
+	.name = "pci260",
+	.id = PCI_DEVICE_ID_PCI260,
+	.ai_chans = 16,
+	.ai_bits = 12,
+	.ao_chans = 0,
+	.ao_bits = 0,
+	.have_dio = 0,
 		},
 	{
-	      name:	"amplc_pci230",	/* Wildcard matches any above */
-	      id:	PCI_DEVICE_ID_INVALID,
+	.name = "amplc_pci230",	/* Wildcard matches any above */
+	.id = PCI_DEVICE_ID_INVALID,
 		},
 };
 
@@ -601,46 +603,46 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int pci230_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pci230_detach(struct comedi_device * dev);
+static int pci230_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pci230_detach(struct comedi_device *dev);
 static struct comedi_driver driver_amplc_pci230 = {
-      driver_name:"amplc_pci230",
-      module:THIS_MODULE,
-      attach:pci230_attach,
-      detach:pci230_detach,
-      board_name:&pci230_boards[0].name,
-      offset:sizeof(pci230_boards[0]),
-      num_names:sizeof(pci230_boards) / sizeof(pci230_boards[0]),
+	.driver_name = "amplc_pci230",
+	.module = THIS_MODULE,
+	.attach = pci230_attach,
+	.detach = pci230_detach,
+	.board_name = &pci230_boards[0].name,
+	.offset = sizeof(pci230_boards[0]),
+	.num_names = ARRAY_SIZE(pci230_boards),
 };
 
 COMEDI_PCI_INITCLEANUP(driver_amplc_pci230, pci230_pci_table);
 
-static int pci230_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int pci230_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int pci230_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static void pci230_ct_setup_ns_mode(struct comedi_device * dev, unsigned int ct,
+static int pci230_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int pci230_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int pci230_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static void pci230_ct_setup_ns_mode(struct comedi_device *dev, unsigned int ct,
 	unsigned int mode, uint64_t ns, unsigned int round);
 static void pci230_ns_to_single_timer(unsigned int *ns, unsigned int round);
-static void pci230_cancel_ct(struct comedi_device * dev, unsigned int ct);
-static irqreturn_t pci230_interrupt(int irq, void *d PT_REGS_ARG);
-static int pci230_ao_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int pci230_ao_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int pci230_ao_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static void pci230_ao_stop(struct comedi_device * dev, struct comedi_subdevice * s);
-static void pci230_handle_ao_nofifo(struct comedi_device * dev, struct comedi_subdevice * s);
-static int pci230_handle_ao_fifo(struct comedi_device * dev, struct comedi_subdevice * s);
-static int pci230_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int pci230_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int pci230_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static void pci230_ai_stop(struct comedi_device * dev, struct comedi_subdevice * s);
-static void pci230_handle_ai(struct comedi_device * dev, struct comedi_subdevice * s);
+static void pci230_cancel_ct(struct comedi_device *dev, unsigned int ct);
+static irqreturn_t pci230_interrupt(int irq, void *d);
+static int pci230_ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int pci230_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int pci230_ao_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static void pci230_ao_stop(struct comedi_device *dev, struct comedi_subdevice *s);
+static void pci230_handle_ao_nofifo(struct comedi_device *dev, struct comedi_subdevice *s);
+static int pci230_handle_ao_fifo(struct comedi_device *dev, struct comedi_subdevice *s);
+static int pci230_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int pci230_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int pci230_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static void pci230_ai_stop(struct comedi_device *dev, struct comedi_subdevice *s);
+static void pci230_handle_ai(struct comedi_device *dev, struct comedi_subdevice *s);
 
-static short pci230_ai_read(struct comedi_device * dev)
+static short pci230_ai_read(struct comedi_device *dev)
 {
 	/* Read sample. */
 	short data = (short) inw(dev->iobase + PCI230_ADCDATA);
@@ -658,7 +660,7 @@
 	return data;
 }
 
-static inline unsigned short pci230_ao_mangle_datum(struct comedi_device * dev,
+static inline unsigned short pci230_ao_mangle_datum(struct comedi_device *dev,
 	short datum)
 {
 	/* If a bipolar range was specified, mangle it (straight binary->twos
@@ -674,7 +676,7 @@
 	return (unsigned short)datum;
 }
 
-static inline void pci230_ao_write_nofifo(struct comedi_device * dev, short datum,
+static inline void pci230_ao_write_nofifo(struct comedi_device *dev, short datum,
 	unsigned int chan)
 {
 	/* Store unmangled datum to be read back later. */
@@ -685,7 +687,7 @@
 			? PCI230_DACOUT1 : PCI230_DACOUT2));
 }
 
-static inline void pci230_ao_write_fifo(struct comedi_device * dev, short datum,
+static inline void pci230_ao_write_fifo(struct comedi_device *dev, short datum,
 	unsigned int chan)
 {
 	/* Store unmangled datum to be read back later. */
@@ -702,7 +704,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int pci230_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pci230_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase1, iobase2;
@@ -874,8 +876,8 @@
 		dev->iobase + PCI230_ADCCON);
 
 	/* Register the interrupt handler. */
-	irq_hdl = comedi_request_irq(devpriv->pci_dev->irq, pci230_interrupt,
-		IRQF_SHARED, "amplc_pci230", dev);
+	irq_hdl = request_irq(devpriv->pci_dev->irq, pci230_interrupt,
+			      IRQF_SHARED, "amplc_pci230", dev);
 	if (irq_hdl < 0) {
 		printk("comedi%d: unable to register irq, "
 			"commands will not be available %d\n", dev->minor,
@@ -959,7 +961,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int pci230_detach(struct comedi_device * dev)
+static int pci230_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: amplc_pci230: remove\n", dev->minor);
 
@@ -968,7 +970,7 @@
 		subdev_8255_cleanup(dev, dev->subdevices + 2);
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	if (devpriv) {
 		if (devpriv->pci_dev) {
@@ -982,7 +984,7 @@
 	return 0;
 }
 
-static int get_resources(struct comedi_device * dev, unsigned int res_mask,
+static int get_resources(struct comedi_device *dev, unsigned int res_mask,
 	unsigned char owner)
 {
 	int ok;
@@ -993,7 +995,7 @@
 
 	ok = 1;
 	claimed = 0;
-	comedi_spin_lock_irqsave(&devpriv->res_spinlock, irqflags);
+	spin_lock_irqsave(&devpriv->res_spinlock, irqflags);
 	for (b = 1, i = 0; (i < NUM_RESOURCES)
 		&& (res_mask != 0); b <<= 1, i++) {
 		if ((res_mask & b) != 0) {
@@ -1014,24 +1016,24 @@
 			}
 		}
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->res_spinlock, irqflags);
+	spin_unlock_irqrestore(&devpriv->res_spinlock, irqflags);
 	return ok;
 }
 
-static inline int get_one_resource(struct comedi_device * dev, unsigned int resource,
+static inline int get_one_resource(struct comedi_device *dev, unsigned int resource,
 	unsigned char owner)
 {
 	return get_resources(dev, (1U << resource), owner);
 }
 
-static void put_resources(struct comedi_device * dev, unsigned int res_mask,
+static void put_resources(struct comedi_device *dev, unsigned int res_mask,
 	unsigned char owner)
 {
 	unsigned int i;
 	unsigned int b;
 	unsigned long irqflags;
 
-	comedi_spin_lock_irqsave(&devpriv->res_spinlock, irqflags);
+	spin_lock_irqsave(&devpriv->res_spinlock, irqflags);
 	for (b = 1, i = 0; (i < NUM_RESOURCES)
 		&& (res_mask != 0); b <<= 1, i++) {
 		if ((res_mask & b) != 0) {
@@ -1041,16 +1043,16 @@
 			}
 		}
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->res_spinlock, irqflags);
+	spin_unlock_irqrestore(&devpriv->res_spinlock, irqflags);
 }
 
-static inline void put_one_resource(struct comedi_device * dev, unsigned int resource,
+static inline void put_one_resource(struct comedi_device *dev, unsigned int resource,
 	unsigned char owner)
 {
 	put_resources(dev, (1U << resource), owner);
 }
 
-static inline void put_all_resources(struct comedi_device * dev, unsigned char owner)
+static inline void put_all_resources(struct comedi_device *dev, unsigned char owner)
 {
 	put_resources(dev, (1U << NUM_RESOURCES) - 1, owner);
 }
@@ -1058,8 +1060,8 @@
 /*
  *  COMEDI_SUBD_AI instruction;
  */
-static int pci230_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci230_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int n, i;
 	unsigned int chan, range, aref;
@@ -1143,12 +1145,12 @@
 			status = inw(dev->iobase + PCI230_ADCCON);
 			if (!(status & PCI230_ADC_FIFO_EMPTY))
 				break;
-			comedi_udelay(1);
+			udelay(1);
 		}
 		if (i == TIMEOUT) {
-			/* rt_printk() should be used instead of printk()
+			/* printk() should be used instead of printk()
 			 * whenever the code can be called from real-time. */
-			rt_printk("timeout\n");
+			printk("timeout\n");
 			return -ETIMEDOUT;
 		}
 
@@ -1163,8 +1165,8 @@
 /*
  *  COMEDI_SUBD_AO instructions;
  */
-static int pci230_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci230_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan, range;
@@ -1191,8 +1193,8 @@
 
 /* AO subdevices should have a read insn as well as a write insn.
  * Usually this means copying a value stored in devpriv. */
-static int pci230_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci230_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -1203,8 +1205,8 @@
 	return i;
 }
 
-static int pci230_ao_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int pci230_ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	unsigned int tmp;
@@ -1416,20 +1418,20 @@
 	return 0;
 }
 
-static int pci230_ao_inttrig_scan_begin(struct comedi_device * dev,
-	struct comedi_subdevice * s, unsigned int trig_num)
+static int pci230_ao_inttrig_scan_begin(struct comedi_device *dev,
+	struct comedi_subdevice *s, unsigned int trig_num)
 {
 	unsigned long irqflags;
 
 	if (trig_num != 0)
 		return -EINVAL;
 
-	comedi_spin_lock_irqsave(&devpriv->ao_stop_spinlock, irqflags);
+	spin_lock_irqsave(&devpriv->ao_stop_spinlock, irqflags);
 	if (test_bit(AO_CMD_STARTED, &devpriv->state)) {
 		/* Perform scan. */
 		if (devpriv->hwver < 2) {
 			/* Not using DAC FIFO. */
-			comedi_spin_unlock_irqrestore(&devpriv->
+			spin_unlock_irqrestore(&devpriv->
 				ao_stop_spinlock, irqflags);
 			pci230_handle_ao_nofifo(dev, s);
 			comedi_event(dev, s);
@@ -1437,18 +1439,18 @@
 			/* Using DAC FIFO. */
 			/* Read DACSWTRIG register to trigger conversion. */
 			inw(dev->iobase + PCI230P2_DACSWTRIG);
-			comedi_spin_unlock_irqrestore(&devpriv->
+			spin_unlock_irqrestore(&devpriv->
 				ao_stop_spinlock, irqflags);
 		}
 		/* Delay.  Should driver be responsible for this? */
 		/* XXX TODO: See if DAC busy bit can be used. */
-		comedi_udelay(8);
+		udelay(8);
 	}
 
 	return 1;
 }
 
-static void pci230_ao_start(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pci230_ao_start(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_async *async = s->async;
 	struct comedi_cmd *cmd = &async->cmd;
@@ -1506,13 +1508,13 @@
 			if (devpriv->hwver < 2) {
 				/* Not using DAC FIFO. */
 				/* Enable CT1 timer interrupt. */
-				comedi_spin_lock_irqsave(&devpriv->isr_spinlock,
+				spin_lock_irqsave(&devpriv->isr_spinlock,
 					irqflags);
 				devpriv->int_en |= PCI230_INT_ZCLK_CT1;
 				devpriv->ier |= PCI230_INT_ZCLK_CT1;
 				outb(devpriv->ier,
 					devpriv->iobase1 + PCI230_INT_SCE);
-				comedi_spin_unlock_irqrestore(&devpriv->
+				spin_unlock_irqrestore(&devpriv->
 					isr_spinlock, irqflags);
 			}
 			/* Set CT1 gate high to start counting. */
@@ -1525,18 +1527,18 @@
 		}
 		if (devpriv->hwver >= 2) {
 			/* Using DAC FIFO.  Enable DAC FIFO interrupt. */
-			comedi_spin_lock_irqsave(&devpriv->isr_spinlock,
+			spin_lock_irqsave(&devpriv->isr_spinlock,
 				irqflags);
 			devpriv->int_en |= PCI230P2_INT_DAC;
 			devpriv->ier |= PCI230P2_INT_DAC;
 			outb(devpriv->ier, devpriv->iobase1 + PCI230_INT_SCE);
-			comedi_spin_unlock_irqrestore(&devpriv->isr_spinlock,
+			spin_unlock_irqrestore(&devpriv->isr_spinlock,
 				irqflags);
 		}
 	}
 }
 
-static int pci230_ao_inttrig_start(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pci230_ao_inttrig_start(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trig_num)
 {
 	if (trig_num != 0)
@@ -1548,7 +1550,7 @@
 	return 1;
 }
 
-static int pci230_ao_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci230_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned short daccon;
 	unsigned int range;
@@ -1624,7 +1626,7 @@
 	return 0;
 }
 
-static int pci230_ai_check_scan_period(struct comedi_cmd * cmd)
+static int pci230_ai_check_scan_period(struct comedi_cmd *cmd)
 {
 	unsigned int min_scan_period, chanlist_len;
 	int err = 0;
@@ -1648,8 +1650,8 @@
 	return !err;
 }
 
-static int pci230_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int pci230_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	unsigned int tmp;
@@ -2034,8 +2036,8 @@
 	return 0;
 }
 
-static void pci230_ai_update_fifo_trigger_level(struct comedi_device * dev,
-	struct comedi_subdevice * s)
+static void pci230_ai_update_fifo_trigger_level(struct comedi_device *dev,
+	struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	unsigned int scanlen = cmd->scan_end_arg;
@@ -2078,7 +2080,7 @@
 	}
 }
 
-static int pci230_ai_inttrig_convert(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pci230_ai_inttrig_convert(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trig_num)
 {
 	unsigned long irqflags;
@@ -2086,7 +2088,7 @@
 	if (trig_num != 0)
 		return -EINVAL;
 
-	comedi_spin_lock_irqsave(&devpriv->ai_stop_spinlock, irqflags);
+	spin_lock_irqsave(&devpriv->ai_stop_spinlock, irqflags);
 	if (test_bit(AI_CMD_STARTED, &devpriv->state)) {
 		unsigned int delayus;
 
@@ -2110,19 +2112,19 @@
 			/* single-ended or PCI230+/260+ */
 			delayus = 4;
 		}
-		comedi_spin_unlock_irqrestore(&devpriv->ai_stop_spinlock,
+		spin_unlock_irqrestore(&devpriv->ai_stop_spinlock,
 			irqflags);
-		comedi_udelay(delayus);
+		udelay(delayus);
 	} else {
-		comedi_spin_unlock_irqrestore(&devpriv->ai_stop_spinlock,
+		spin_unlock_irqrestore(&devpriv->ai_stop_spinlock,
 			irqflags);
 	}
 
 	return 1;
 }
 
-static int pci230_ai_inttrig_scan_begin(struct comedi_device * dev,
-	struct comedi_subdevice * s, unsigned int trig_num)
+static int pci230_ai_inttrig_scan_begin(struct comedi_device *dev,
+	struct comedi_subdevice *s, unsigned int trig_num)
 {
 	unsigned long irqflags;
 	unsigned char zgat;
@@ -2130,7 +2132,7 @@
 	if (trig_num != 0)
 		return -EINVAL;
 
-	comedi_spin_lock_irqsave(&devpriv->ai_stop_spinlock, irqflags);
+	spin_lock_irqsave(&devpriv->ai_stop_spinlock, irqflags);
 	if (test_bit(AI_CMD_STARTED, &devpriv->state)) {
 		/* Trigger scan by waggling CT0 gate source. */
 		zgat = GAT_CONFIG(0, GAT_GND);
@@ -2138,12 +2140,12 @@
 		zgat = GAT_CONFIG(0, GAT_VCC);
 		outb(zgat, devpriv->iobase1 + PCI230_ZGAT_SCE);
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->ai_stop_spinlock, irqflags);
+	spin_unlock_irqrestore(&devpriv->ai_stop_spinlock, irqflags);
 
 	return 1;
 }
 
-static void pci230_ai_start(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pci230_ai_start(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long irqflags;
 	unsigned short conv;
@@ -2158,11 +2160,11 @@
 		comedi_event(dev, s);
 	} else {
 		/* Enable ADC FIFO trigger level interrupt. */
-		comedi_spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
+		spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
 		devpriv->int_en |= PCI230_INT_ADC;
 		devpriv->ier |= PCI230_INT_ADC;
 		outb(devpriv->ier, devpriv->iobase1 + PCI230_INT_SCE);
-		comedi_spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
+		spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
 
 		/* Update conversion trigger source which is currently set
 		 * to CT2 output, which is currently stuck high. */
@@ -2280,7 +2282,7 @@
 	}
 }
 
-static int pci230_ai_inttrig_start(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pci230_ai_inttrig_start(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trig_num)
 {
 	if (trig_num != 0)
@@ -2292,7 +2294,7 @@
 	return 1;
 }
 
-static int pci230_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci230_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned int i, chan, range, diff;
 	unsigned int res_mask;
@@ -2424,7 +2426,7 @@
 	 * FIFO reset (above) and the second FIFO reset (below). Setting the
 	 * channel gains and scan list _before_ the first FIFO reset also
 	 * helps, though only slightly. */
-	comedi_udelay(25);
+	udelay(25);
 
 	/* Reset FIFO again. */
 	outw(adccon | PCI230_ADC_FIFO_RESET, dev->iobase + PCI230_ADCCON);
@@ -2532,7 +2534,7 @@
 	return;
 }
 
-static void pci230_ct_setup_ns_mode(struct comedi_device * dev, unsigned int ct,
+static void pci230_ct_setup_ns_mode(struct comedi_device *dev, unsigned int ct,
 	unsigned int mode, uint64_t ns, unsigned int round)
 {
 	unsigned int clk_src;
@@ -2551,7 +2553,7 @@
 	i8254_write(devpriv->iobase1 + PCI230_Z2_CT_BASE, 0, ct, count);
 }
 
-static void pci230_cancel_ct(struct comedi_device * dev, unsigned int ct)
+static void pci230_cancel_ct(struct comedi_device *dev, unsigned int ct)
 {
 	i8254_set_mode(devpriv->iobase1 + PCI230_Z2_CT_BASE, 0, ct,
 		I8254_MODE1);
@@ -2559,7 +2561,7 @@
 }
 
 /* Interrupt handler */
-static irqreturn_t pci230_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t pci230_interrupt(int irq, void *d)
 {
 	unsigned char status_int, valid_status_int;
 	struct comedi_device *dev = (struct comedi_device *) d;
@@ -2573,7 +2575,7 @@
 		return IRQ_NONE;
 	}
 
-	comedi_spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
+	spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
 	valid_status_int = devpriv->int_en & status_int;
 	/* Disable triggered interrupts.
 	 * (Only those interrupts that need re-enabling, are, later in the
@@ -2582,7 +2584,7 @@
 	outb(devpriv->ier, devpriv->iobase1 + PCI230_INT_SCE);
 	devpriv->intr_running = 1;
 	devpriv->intr_cpuid = THISCPU;
-	comedi_spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
+	spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
 
 	/*
 	 * Check the source of interrupt and handle it.
@@ -2611,18 +2613,18 @@
 	}
 
 	/* Reenable interrupts. */
-	comedi_spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
+	spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
 	if (devpriv->ier != devpriv->int_en) {
 		devpriv->ier = devpriv->int_en;
 		outb(devpriv->ier, devpriv->iobase1 + PCI230_INT_SCE);
 	}
 	devpriv->intr_running = 0;
-	comedi_spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
+	spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
 
 	return IRQ_HANDLED;
 }
 
-static void pci230_handle_ao_nofifo(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pci230_handle_ao_nofifo(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	short data;
 	int i, ret;
@@ -2659,7 +2661,7 @@
 
 /* Loads DAC FIFO (if using it) from buffer. */
 /* Returns 0 if AO finished due to completion or error, 1 if still going. */
-static int pci230_handle_ao_fifo(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci230_handle_ao_fifo(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_async *async = s->async;
 	struct comedi_cmd *cmd = &async->cmd;
@@ -2762,7 +2764,7 @@
 	return running;
 }
 
-static void pci230_handle_ai(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pci230_handle_ai(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned int events = 0;
 	unsigned int status_fifo;
@@ -2861,16 +2863,16 @@
 	}
 }
 
-static void pci230_ao_stop(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pci230_ao_stop(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long irqflags;
 	unsigned char intsrc;
 	int started;
 	struct comedi_cmd *cmd;
 
-	comedi_spin_lock_irqsave(&devpriv->ao_stop_spinlock, irqflags);
+	spin_lock_irqsave(&devpriv->ao_stop_spinlock, irqflags);
 	started = test_and_clear_bit(AO_CMD_STARTED, &devpriv->state);
-	comedi_spin_unlock_irqrestore(&devpriv->ao_stop_spinlock, irqflags);
+	spin_unlock_irqrestore(&devpriv->ao_stop_spinlock, irqflags);
 	if (!started) {
 		return;
 	}
@@ -2891,17 +2893,17 @@
 	}
 	/* Disable interrupt and wait for interrupt routine to finish running
 	 * unless we are called from the interrupt routine. */
-	comedi_spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
+	spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
 	devpriv->int_en &= ~intsrc;
 	while (devpriv->intr_running && devpriv->intr_cpuid != THISCPU) {
-		comedi_spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
-		comedi_spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
+		spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
+		spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
 	}
 	if (devpriv->ier != devpriv->int_en) {
 		devpriv->ier = devpriv->int_en;
 		outb(devpriv->ier, devpriv->iobase1 + PCI230_INT_SCE);
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
+	spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
 
 	if (devpriv->hwver >= 2) {
 		/* Using DAC FIFO.  Reset FIFO, clear underrun error,
@@ -2916,21 +2918,21 @@
 	put_all_resources(dev, OWNER_AOCMD);
 }
 
-static int pci230_ao_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci230_ao_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	pci230_ao_stop(dev, s);
 	return 0;
 }
 
-static void pci230_ai_stop(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pci230_ai_stop(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long irqflags;
 	struct comedi_cmd *cmd;
 	int started;
 
-	comedi_spin_lock_irqsave(&devpriv->ai_stop_spinlock, irqflags);
+	spin_lock_irqsave(&devpriv->ai_stop_spinlock, irqflags);
 	started = test_and_clear_bit(AI_CMD_STARTED, &devpriv->state);
-	comedi_spin_unlock_irqrestore(&devpriv->ai_stop_spinlock, irqflags);
+	spin_unlock_irqrestore(&devpriv->ai_stop_spinlock, irqflags);
 	if (!started) {
 		return;
 	}
@@ -2945,19 +2947,19 @@
 		pci230_cancel_ct(dev, 0);
 	}
 
-	comedi_spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
+	spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
 	/* Disable ADC interrupt and wait for interrupt routine to finish
 	 * running unless we are called from the interrupt routine. */
 	devpriv->int_en &= ~PCI230_INT_ADC;
 	while (devpriv->intr_running && devpriv->intr_cpuid != THISCPU) {
-		comedi_spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
-		comedi_spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
+		spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
+		spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
 	}
 	if (devpriv->ier != devpriv->int_en) {
 		devpriv->ier = devpriv->int_en;
 		outb(devpriv->ier, devpriv->iobase1 + PCI230_INT_SCE);
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
+	spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
 
 	/* Reset FIFO, disable FIFO and set start conversion source to none.
 	 * Keep se/diff and bip/uni settings */
@@ -2970,7 +2972,7 @@
 	put_all_resources(dev, OWNER_AICMD);
 }
 
-static int pci230_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci230_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	pci230_ai_stop(dev, s);
 	return 0;
diff --git a/drivers/staging/comedi/drivers/c6xdigio.c b/drivers/staging/comedi/drivers/c6xdigio.c
index 2efffb1..b204793 100644
--- a/drivers/staging/comedi/drivers/c6xdigio.c
+++ b/drivers/staging/comedi/drivers/c6xdigio.c
@@ -77,7 +77,7 @@
 	unsigned sb4:2;
 };
 union pwmcmdtype {
-	unsigned cmd;		// assuming here that int is 32bit
+	unsigned cmd;		/*  assuming here that int is 32bit */
 	struct pwmbitstype bits;
 };
 struct encbitstype {
@@ -97,20 +97,20 @@
 
 #define C6XDIGIO_TIME_OUT 20
 
-static int c6xdigio_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int c6xdigio_detach(struct comedi_device * dev);
+static int c6xdigio_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int c6xdigio_detach(struct comedi_device *dev);
 struct comedi_driver driver_c6xdigio = {
-      driver_name:"c6xdigio",
-      module:THIS_MODULE,
-      attach:c6xdigio_attach,
-      detach:c6xdigio_detach,
+	.driver_name = "c6xdigio",
+	.module = THIS_MODULE,
+	.attach = c6xdigio_attach,
+	.detach = c6xdigio_detach,
 };
 
 static void C6X_pwmInit(unsigned long baseAddr)
 {
 	int timeout = 0;
 
-//printk("Inside C6X_pwmInit\n");
+/* printk("Inside C6X_pwmInit\n"); */
 
 	WriteByteToHwPort(baseAddr, 0x70);
 	while (((ReadByteFromHwPort(baseAddr + 1) & 0x80) == 0)
@@ -148,7 +148,7 @@
 	int timeout = 0;
 	unsigned tmp;
 
-	//printk("Inside C6X_pwmOutput\n");
+	/* printk("Inside C6X_pwmOutput\n"); */
 
 	pwm.cmd = value;
 	if (pwm.cmd > 498)
@@ -158,7 +158,7 @@
 
 	if (channel == 0) {
 		ppcmd = 0x28;
-	} else {		// if channel == 1
+	} else {		/*  if channel == 1 */
 		ppcmd = 0x30;
 	}			/* endif */
 
@@ -216,7 +216,7 @@
 	int timeout = 0;
 	int tmp;
 
-	//printk("Inside C6X_encInput\n");
+	/* printk("Inside C6X_encInput\n"); */
 
 	enc.value = 0;
 	if (channel == 0) {
@@ -304,14 +304,14 @@
 		timeout++;
 	}
 
-	return (enc.value ^ 0x800000);
+	return enc.value ^ 0x800000;
 }
 
 static void C6X_encResetAll(unsigned long baseAddr)
 {
 	unsigned timeout = 0;
 
-//printk("Inside C6X_encResetAll\n");
+/* printk("Inside C6X_encResetAll\n"); */
 
 	WriteByteToHwPort(baseAddr, 0x68);
 	while (((ReadByteFromHwPort(baseAddr + 1) & 0x80) == 0)
@@ -338,20 +338,20 @@
 	}
 }
 
-static int c6xdigio_pwmo_insn_read(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int c6xdigio_pwmo_insn_read(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	printk("c6xdigio_pwmo_insn_read %x\n", insn->n);
 	return insn->n;
 }
 
-static int c6xdigio_pwmo_insn_write(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int c6xdigio_pwmo_insn_write(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
 
-	//  printk("c6xdigio_pwmo_insn_write %x\n", insn->n);
+	/*   printk("c6xdigio_pwmo_insn_write %x\n", insn->n); */
 	for (i = 0; i < insn->n; i++) {
 		C6X_pwmOutput(dev->iobase, chan, data[i]);
 		/*    devpriv->ao_readback[chan] = data[i]; */
@@ -359,32 +359,30 @@
 	return i;
 }
 
-//static int c6xdigio_ei_init_insn_read(struct comedi_device *dev,
-//                                 struct comedi_subdevice *s,
-//                                 struct comedi_insn *insn,
-//                                 unsigned int *data)
-//{
-//  printk("c6xdigio_ei_init_insn_read %x\n", insn->n);
-//  return insn->n;
-//}
+/* static int c6xdigio_ei_init_insn_read(struct comedi_device *dev, */
+/* struct comedi_subdevice *s, */
+/* struct comedi_insn *insn, */
+/* unsigned int *data) */
+/* { */
+/* printk("c6xdigio_ei_init_insn_read %x\n", insn->n); */
+/* return insn->n; */
+/* } */
 
-//static int c6xdigio_ei_init_insn_write(struct comedi_device *dev,
-//                                 struct comedi_subdevice *s,
-//                                 struct comedi_insn *insn,
-//                                 unsigned int *data)
-//{
-//  int i;
-//  int chan = CR_CHAN(insn->chanspec);
-//
-//  C6X_encResetAll( dev->iobase );
-//
-//  return insn->n;
-//}
+/* static int c6xdigio_ei_init_insn_write(struct comedi_device *dev, */
+/* struct comedi_subdevice *s, */
+/* struct comedi_insn *insn, */
+/* unsigned int *data) */
+/* { */
+/* int i; */
+/* int chan = CR_CHAN(insn->chanspec); */
+/*  *//* C6X_encResetAll( dev->iobase ); */
+/*  *//* return insn->n; */
+/* } */
 
-static int c6xdigio_ei_insn_read(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int c6xdigio_ei_insn_read(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
-	//  printk("c6xdigio_ei__insn_read %x\n", insn->n);
+	/*   printk("c6xdigio_ei__insn_read %x\n", insn->n); */
 	int n;
 	int chan = CR_CHAN(insn->chanspec);
 
@@ -395,19 +393,19 @@
 	return n;
 }
 
-static void board_init(struct comedi_device * dev)
+static void board_init(struct comedi_device *dev)
 {
 
-	//printk("Inside board_init\n");
+	/* printk("Inside board_init\n"); */
 
 	C6X_pwmInit(dev->iobase);
 	C6X_encResetAll(dev->iobase);
 
 }
 
-//static void board_halt(struct comedi_device *dev) {
-//  C6X_pwmInit(dev->iobase);
-//}
+/* static void board_halt(struct comedi_device *dev) { */
+/* C6X_pwmInit(dev->iobase); */
+/* } */
 
 /*
    options[0] - I/O port
@@ -417,9 +415,9 @@
 
 static const struct pnp_device_id c6xdigio_pnp_tbl[] = {
 	/* Standard LPT Printer Port */
-	{.id = "PNP0400",.driver_data = 0},
+	{.id = "PNP0400", .driver_data = 0},
 	/* ECP Printer Port */
-	{.id = "PNP0401",.driver_data = 0},
+	{.id = "PNP0401", .driver_data = 0},
 	{}
 };
 
@@ -428,7 +426,7 @@
 	.id_table = c6xdigio_pnp_tbl,
 };
 
-static int c6xdigio_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int c6xdigio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int result = 0;
 	unsigned long iobase;
@@ -444,11 +442,11 @@
 	dev->iobase = iobase;
 	dev->board_name = "c6xdigio";
 
-	result = alloc_subdevices(dev, 2);	// 3 with encoder_init write
+	result = alloc_subdevices(dev, 2);	/*  3 with encoder_init write */
 	if (result < 0)
 		return result;
 
-	// Make sure that PnP ports gets activated
+	/*  Make sure that PnP ports gets activated */
 	pnp_register_driver(&c6xdigio_pnp_driver);
 
 	irq = it->options[1];
@@ -460,14 +458,14 @@
 
 	s = dev->subdevices + 0;
 	/* pwm output subdevice */
-	s->type = COMEDI_SUBD_AO;	// Not sure what to put here
+	s->type = COMEDI_SUBD_AO;	/*  Not sure what to put here */
 	s->subdev_flags = SDF_WRITEABLE;
 	s->n_chan = 2;
 	/*      s->trig[0] = c6xdigio_pwmo; */
 	s->insn_read = c6xdigio_pwmo_insn_read;
 	s->insn_write = c6xdigio_pwmo_insn_write;
 	s->maxdata = 500;
-	s->range_table = &range_bipolar10;	// A suitable lie
+	s->range_table = &range_bipolar10;	/*  A suitable lie */
 
 	s = dev->subdevices + 1;
 	/* encoder (counter) subdevice */
@@ -479,27 +477,27 @@
 	s->maxdata = 0xffffff;
 	s->range_table = &range_unknown;
 
-	//          s = dev->subdevices + 2;
-	//      /* pwm output subdevice */
-	//      s->type = COMEDI_SUBD_COUNTER;  // Not sure what to put here
-	//      s->subdev_flags = SDF_WRITEABLE;
-	//      s->n_chan = 1;
-	//      /* s->trig[0] = c6xdigio_ei_init; */
-	//      s->insn_read = c6xdigio_ei_init_insn_read;
-	//      s->insn_write = c6xdigio_ei_init_insn_write;
-	//      s->maxdata = 0xFFFF;  // Really just a don't care
-	//      s->range_table = &range_unknown; // Not sure what to put here
+	/*           s = dev->subdevices + 2; */
+	      /* pwm output subdevice */
+	/*       s->type = COMEDI_SUBD_COUNTER;  // Not sure what to put here */
+	/*       s->subdev_flags = SDF_WRITEABLE; */
+	/*       s->n_chan = 1; */
+	/*       s->trig[0] = c6xdigio_ei_init; */
+	/*       s->insn_read = c6xdigio_ei_init_insn_read; */
+	/*       s->insn_write = c6xdigio_ei_init_insn_write; */
+	/*       s->maxdata = 0xFFFF;  // Really just a don't care */
+	/*       s->range_table = &range_unknown; // Not sure what to put here */
 
-	// I will call this init anyway but more than likely the DSP board will not be connect
-	// when device driver is loaded.
+	/*  I will call this init anyway but more than likely the DSP board will not be connect */
+	/*  when device driver is loaded. */
 	board_init(dev);
 
 	return 0;
 }
 
-static int c6xdigio_detach(struct comedi_device * dev)
+static int c6xdigio_detach(struct comedi_device *dev)
 {
-//  board_halt(dev);  // may not need this
+/* board_halt(dev);  may not need this */
 
 	printk("comedi%d: c6xdigio: remove\n", dev->minor);
 
@@ -508,7 +506,7 @@
 	}
 	if (dev->irq) {
 		free_irq(dev->irq, dev);
-	}			// Not using IRQ so I am not sure if I need this
+	}			/*  Not using IRQ so I am not sure if I need this */
 	pnp_unregister_driver(&c6xdigio_pnp_driver);
 
 	return 0;
diff --git a/drivers/staging/comedi/drivers/cb_das16_cs.c b/drivers/staging/comedi/drivers/cb_das16_cs.c
index 0bfe4c9..7af245b 100644
--- a/drivers/staging/comedi/drivers/cb_das16_cs.c
+++ b/drivers/staging/comedi/drivers/cb_das16_cs.c
@@ -31,6 +31,7 @@
 
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 #include <linux/delay.h>
 #include <linux/pci.h>
@@ -61,19 +62,19 @@
 };
 static const struct das16cs_board das16cs_boards[] = {
 	{
-	      device_id:0x0000,/* unknown */
-	      name:	"PC-CARD DAS16/16",
-	      n_ao_chans:0,
+	.device_id = 0x0000,/* unknown */
+	.name = "PC-CARD DAS16/16",
+	.n_ao_chans = 0,
 		},
 	{
-	      device_id:0x0039,
-	      name:	"PC-CARD DAS16/16-AO",
-	      n_ao_chans:2,
+	.device_id = 0x0039,
+	.name = "PC-CARD DAS16/16-AO",
+	.n_ao_chans = 2,
 		},
 	{
-	      device_id:0x4009,
-	      name:	"PCM-DAS16s/16",
-	      n_ao_chans:0,
+	.device_id = 0x4009,
+	.name = "PCM-DAS16s/16",
+	.n_ao_chans = 0,
 		},
 };
 
@@ -89,13 +90,13 @@
 };
 #define devpriv ((struct das16cs_private *)dev->private)
 
-static int das16cs_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int das16cs_detach(struct comedi_device * dev);
+static int das16cs_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int das16cs_detach(struct comedi_device *dev);
 static struct comedi_driver driver_das16cs = {
-      driver_name:"cb_das16_cs",
-      module:THIS_MODULE,
-      attach:das16cs_attach,
-      detach:das16cs_detach,
+	.driver_name = "cb_das16_cs",
+	.module = THIS_MODULE,
+	.attach = das16cs_attach,
+	.detach = das16cs_detach,
 };
 
 static struct pcmcia_device *cur_dev = NULL;
@@ -108,26 +109,26 @@
 	}
 };
 
-static irqreturn_t das16cs_interrupt(int irq, void *d PT_REGS_ARG);
-static int das16cs_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das16cs_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int das16cs_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int das16cs_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das16cs_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das16cs_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das16cs_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das16cs_timer_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das16cs_timer_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static irqreturn_t das16cs_interrupt(int irq, void *d);
+static int das16cs_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das16cs_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int das16cs_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int das16cs_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das16cs_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das16cs_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das16cs_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das16cs_timer_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das16cs_timer_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int get_prodid(struct comedi_device * dev, struct pcmcia_device *link)
+static int get_prodid(struct comedi_device *dev, struct pcmcia_device *link)
 {
 	tuple_t tuple;
 	u_short buf[128];
@@ -165,7 +166,7 @@
 	return NULL;
 }
 
-static int das16cs_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int das16cs_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct pcmcia_device *link;
 	struct comedi_subdevice *s;
@@ -187,8 +188,8 @@
 	}
 	printk("\n");
 
-	ret = comedi_request_irq(link->irq.AssignedIRQ, das16cs_interrupt,
-		IRQF_SHARED, "cb_das16_cs", dev);
+	ret = request_irq(link->irq.AssignedIRQ, das16cs_interrupt,
+			  IRQF_SHARED, "cb_das16_cs", dev);
 	if (ret < 0) {
 		return ret;
 	}
@@ -265,20 +266,20 @@
 	return 1;
 }
 
-static int das16cs_detach(struct comedi_device * dev)
+static int das16cs_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: das16cs: remove\n", dev->minor);
 
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 
 	return 0;
 }
 
-static irqreturn_t das16cs_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t das16cs_interrupt(int irq, void *d)
 {
-	//struct comedi_device *dev = d;
+	/* struct comedi_device *dev = d; */
 	return IRQ_HANDLED;
 }
 
@@ -286,8 +287,8 @@
  * "instructions" read/write data in "one-shot" or "software-triggered"
  * mode.
  */
-static int das16cs_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16cs_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int to;
@@ -328,13 +329,13 @@
 	return i;
 }
 
-static int das16cs_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int das16cs_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	return -EINVAL;
 }
 
-static int das16cs_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int das16cs_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -489,8 +490,8 @@
 	return 0;
 }
 
-static int das16cs_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16cs_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -503,7 +504,7 @@
 		d = data[i];
 
 		outw(devpriv->status1, dev->iobase + 4);
-		comedi_udelay(1);
+		udelay(1);
 
 		status1 = devpriv->status1 & ~0xf;
 		if (chan)
@@ -513,17 +514,17 @@
 
 /* 		printk("0x%04x\n",status1);*/
 		outw(status1, dev->iobase + 4);
-		comedi_udelay(1);
+		udelay(1);
 
 		for (bit = 15; bit >= 0; bit--) {
 			int b = (d >> bit) & 0x1;
 			b <<= 1;
 /*			printk("0x%04x\n",status1 | b | 0x0000);*/
 			outw(status1 | b | 0x0000, dev->iobase + 4);
-			comedi_udelay(1);
+			udelay(1);
 /*			printk("0x%04x\n",status1 | b | 0x0004);*/
 			outw(status1 | b | 0x0004, dev->iobase + 4);
-			comedi_udelay(1);
+			udelay(1);
 		}
 /*		make high both DAC0CS and DAC1CS to load
 		new data and update analog output*/
@@ -535,8 +536,8 @@
 
 /* AO subdevices should have a read insn as well as a write insn.
  * Usually this means copying a value stored in devpriv. */
-static int das16cs_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16cs_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -552,8 +553,8 @@
  * useful to applications if you implement the insn_bits interface.
  * This allows packed reading/writing of the DIO channels.  The
  * comedi core can convert between insn_bits and insn_read/write */
-static int das16cs_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16cs_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -572,8 +573,8 @@
 	return 2;
 }
 
-static int das16cs_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16cs_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 	int bits;
@@ -610,14 +611,14 @@
 	return insn->n;
 }
 
-static int das16cs_timer_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16cs_timer_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	return -EINVAL;
 }
 
-static int das16cs_timer_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16cs_timer_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	return -EINVAL;
 }
@@ -766,15 +767,22 @@
 	tuple.TupleData = buf;
 	tuple.TupleDataMax = sizeof(buf);
 	tuple.TupleOffset = 0;
+
 	last_fn = GetFirstTuple;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple)) != 0)
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret != 0)
 		goto cs_failed;
+
 	last_fn = GetTupleData;
-	if ((last_ret = pcmcia_get_tuple_data(link, &tuple)) != 0)
+	last_ret = pcmcia_get_tuple_data(link, &tuple);
+	if (last_ret != 0)
 		goto cs_failed;
+
 	last_fn = ParseTuple;
-	if ((last_ret = pcmcia_parse_tuple(link, &tuple, &parse)) != 0)
+	last_ret = pcmcia_parse_tuple(&tuple, &parse);
+	if (last_ret != 0)
 		goto cs_failed;
+
 	link->conf.ConfigBase = parse.config.base;
 	link->conf.Present = parse.config.rmask[0];
 
@@ -792,13 +800,16 @@
 	 */
 	tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
 	last_fn = GetFirstTuple;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple)) != 0)
+
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret)
 		goto cs_failed;
+
 	while (1) {
 		cistpl_cftable_entry_t *cfg = &(parse.cftable_entry);
 		if (pcmcia_get_tuple_data(link, &tuple))
 			goto next_entry;
-		if (pcmcia_parse_tuple(link, &tuple, &parse))
+		if (pcmcia_parse_tuple(&tuple, &parse))
 			goto next_entry;
 
 		if (cfg->flags & CISTPL_CFTABLE_DEFAULT)
@@ -844,7 +855,9 @@
 
 	      next_entry:
 		last_fn = GetNextTuple;
-		if ((last_ret = pcmcia_get_next_tuple(link, &tuple)) != 0)
+
+		last_ret = pcmcia_get_next_tuple(link, &tuple);
+		if (last_ret)
 			goto cs_failed;
 	}
 
@@ -855,7 +868,9 @@
 	 */
 	if (link->conf.Attributes & CONF_ENABLE_IRQ) {
 		last_fn = RequestIRQ;
-		if ((last_ret = pcmcia_request_irq(link, &link->irq)) != 0)
+
+		last_ret = pcmcia_request_irq(link, &link->irq);
+		if (last_ret)
 			goto cs_failed;
 	}
 	/*
@@ -864,7 +879,8 @@
 	   card and host interface into "Memory and IO" mode.
 	 */
 	last_fn = RequestConfiguration;
-	if ((last_ret = pcmcia_request_configuration(link, &link->conf)) != 0)
+	last_ret = pcmcia_request_configuration(link, &link->conf);
+	if (last_ret)
 		goto cs_failed;
 
 	/*
@@ -973,4 +989,4 @@
 
 #else
 COMEDI_INITCLEANUP(driver_das16cs);
-#endif //CONFIG_PCMCIA
+#endif /* CONFIG_PCMCIA */
diff --git a/drivers/staging/comedi/drivers/cb_pcidas.c b/drivers/staging/comedi/drivers/cb_pcidas.c
index fcc5516..702de15 100644
--- a/drivers/staging/comedi/drivers/cb_pcidas.c
+++ b/drivers/staging/comedi/drivers/cb_pcidas.c
@@ -63,6 +63,7 @@
 
 #include "../comedidev.h"
 #include <linux/delay.h>
+#include <linux/interrupt.h>
 
 #include "8253.h"
 #include "8255.h"
@@ -70,14 +71,14 @@
 #include "comedi_pci.h"
 #include "comedi_fc.h"
 
-#undef CB_PCIDAS_DEBUG		// disable debugging code
-//#define CB_PCIDAS_DEBUG       // enable debugging code
+#undef CB_PCIDAS_DEBUG		/*  disable debugging code */
+/* #define CB_PCIDAS_DEBUG         enable debugging code */
 
-// PCI vendor number of ComputerBoards/MeasurementComputing
+/* PCI vendor number of ComputerBoards/MeasurementComputing */
 #define PCI_VENDOR_ID_CB	0x1307
-#define TIMER_BASE 100		// 10MHz master clock
-#define AI_BUFFER_SIZE 1024	// maximum fifo size of any supported board
-#define AO_BUFFER_SIZE 1024	// maximum fifo size of any supported board
+#define TIMER_BASE 100		/*  10MHz master clock */
+#define AI_BUFFER_SIZE 1024	/*  maximum fifo size of any supported board */
+#define AO_BUFFER_SIZE 1024	/*  maximum fifo size of any supported board */
 #define NUM_CHANNELS_8800 8
 #define NUM_CHANNELS_7376 1
 #define NUM_CHANNELS_8402 2
@@ -85,71 +86,71 @@
 
 /* PCI-DAS base addresses */
 
-// indices of base address regions
+/* indices of base address regions */
 #define S5933_BADRINDEX 0
 #define CONT_STAT_BADRINDEX 1
 #define ADC_FIFO_BADRINDEX 2
 #define PACER_BADRINDEX 3
 #define AO_BADRINDEX 4
-// sizes of io regions
+/* sizes of io regions */
 #define CONT_STAT_SIZE 10
 #define ADC_FIFO_SIZE 4
 #define PACER_SIZE 12
 #define AO_SIZE 4
 
 /* Control/Status registers */
-#define INT_ADCFIFO	0	// INTERRUPT / ADC FIFO register
-#define   INT_EOS 0x1		// interrupt end of scan
-#define   INT_FHF 0x2		// interrupt fifo half full
-#define   INT_FNE 0x3		// interrupt fifo not empty
-#define   INT_MASK 0x3		// mask of interrupt select bits
-#define   INTE 0x4		// interrupt enable
-#define   DAHFIE 0x8		// dac half full interrupt enable
-#define   EOAIE	0x10		// end of aquisition interrupt enable
-#define   DAHFI	0x20		// dac half full read status / write interrupt clear
-#define   EOAI 0x40		// read end of acq. interrupt status / write clear
-#define   INT 0x80		// read interrupt status / write clear
-#define   EOBI 0x200		// read end of burst interrupt status
-#define   ADHFI 0x400		// read half-full interrupt status
-#define   ADNEI 0x800		// read fifo not empty interrupt latch status
-#define   ADNE 0x1000		// read, fifo not empty (realtime, not latched) status
-#define   DAEMIE	0x1000	// write, dac empty interrupt enable
-#define   LADFUL 0x2000		// read fifo overflow / write clear
-#define   DAEMI 0x4000		// dac fifo empty interrupt status / write clear
+#define INT_ADCFIFO	0	/*  INTERRUPT / ADC FIFO register */
+#define   INT_EOS 0x1		/*  interrupt end of scan */
+#define   INT_FHF 0x2		/*  interrupt fifo half full */
+#define   INT_FNE 0x3		/*  interrupt fifo not empty */
+#define   INT_MASK 0x3		/*  mask of interrupt select bits */
+#define   INTE 0x4		/*  interrupt enable */
+#define   DAHFIE 0x8		/*  dac half full interrupt enable */
+#define   EOAIE	0x10		/*  end of aquisition interrupt enable */
+#define   DAHFI	0x20		/*  dac half full read status / write interrupt clear */
+#define   EOAI 0x40		/*  read end of acq. interrupt status / write clear */
+#define   INT 0x80		/*  read interrupt status / write clear */
+#define   EOBI 0x200		/*  read end of burst interrupt status */
+#define   ADHFI 0x400		/*  read half-full interrupt status */
+#define   ADNEI 0x800		/*  read fifo not empty interrupt latch status */
+#define   ADNE 0x1000		/*  read, fifo not empty (realtime, not latched) status */
+#define   DAEMIE	0x1000	/*  write, dac empty interrupt enable */
+#define   LADFUL 0x2000		/*  read fifo overflow / write clear */
+#define   DAEMI 0x4000		/*  dac fifo empty interrupt status / write clear */
 
-#define ADCMUX_CONT	2	// ADC CHANNEL MUX AND CONTROL register
+#define ADCMUX_CONT	2	/*  ADC CHANNEL MUX AND CONTROL register */
 #define   BEGIN_SCAN(x)	((x) & 0xf)
 #define   END_SCAN(x)	(((x) & 0xf) << 4)
 #define   GAIN_BITS(x)	(((x) & 0x3) << 8)
-#define   UNIP	0x800		// Analog front-end unipolar for range
-#define   SE	0x400		// Inputs in single-ended mode
-#define   PACER_MASK	0x3000	// pacer source bits
-#define   PACER_INT 0x1000	// internal pacer
-#define   PACER_EXT_FALL	0x2000	// external falling edge
-#define   PACER_EXT_RISE	0x3000	// external rising edge
-#define   EOC	0x4000		// adc not busy
+#define   UNIP	0x800		/*  Analog front-end unipolar for range */
+#define   SE	0x400		/*  Inputs in single-ended mode */
+#define   PACER_MASK	0x3000	/*  pacer source bits */
+#define   PACER_INT 0x1000	/*  internal pacer */
+#define   PACER_EXT_FALL	0x2000	/*  external falling edge */
+#define   PACER_EXT_RISE	0x3000	/*  external rising edge */
+#define   EOC	0x4000		/*  adc not busy */
 
-#define TRIG_CONTSTAT 4		// TRIGGER CONTROL/STATUS register
-#define   SW_TRIGGER 0x1	// software start trigger
-#define   EXT_TRIGGER 0x2	// external start trigger
-#define   ANALOG_TRIGGER 0x3	// external analog trigger
-#define   TRIGGER_MASK	0x3	// mask of bits that determine start trigger
-#define   TGEN	0x10		// enable external start trigger
-#define   BURSTE 0x20		// burst mode enable
-#define   XTRCL	0x80		// clear external trigger
+#define TRIG_CONTSTAT 4		/*  TRIGGER CONTROL/STATUS register */
+#define   SW_TRIGGER 0x1	/*  software start trigger */
+#define   EXT_TRIGGER 0x2	/*  external start trigger */
+#define   ANALOG_TRIGGER 0x3	/*  external analog trigger */
+#define   TRIGGER_MASK	0x3	/*  mask of bits that determine start trigger */
+#define   TGEN	0x10		/*  enable external start trigger */
+#define   BURSTE 0x20		/*  burst mode enable */
+#define   XTRCL	0x80		/*  clear external trigger */
 
-#define CALIBRATION_REG	6	// CALIBRATION register
-#define   SELECT_8800_BIT	0x100	// select 8800 caldac
-#define   SELECT_TRIMPOT_BIT	0x200	// select ad7376 trim pot
-#define   SELECT_DAC08_BIT	0x400	// select dac08 caldac
+#define CALIBRATION_REG	6	/*  CALIBRATION register */
+#define   SELECT_8800_BIT	0x100	/*  select 8800 caldac */
+#define   SELECT_TRIMPOT_BIT	0x200	/*  select ad7376 trim pot */
+#define   SELECT_DAC08_BIT	0x400	/*  select dac08 caldac */
 #define   CAL_SRC_BITS(x)	(((x) & 0x7) << 11)
-#define   CAL_EN_BIT	0x4000	// read calibration source instead of analog input channel 0
-#define   SERIAL_DATA_IN_BIT	0x8000	// serial data stream going to 8800 and 7376
+#define   CAL_EN_BIT	0x4000	/*  read calibration source instead of analog input channel 0 */
+#define   SERIAL_DATA_IN_BIT	0x8000	/*  serial data stream going to 8800 and 7376 */
 
-#define DAC_CSR	0x8		// dac control and status register
+#define DAC_CSR	0x8		/*  dac control and status register */
 enum dac_csr_bits {
-	DACEN = 0x2,		// dac enable
-	DAC_MODE_UPDATE_BOTH = 0x80,	// update both dacs when dac0 is written
+	DACEN = 0x2,		/*  dac enable */
+	DAC_MODE_UPDATE_BOTH = 0x80,	/*  update both dacs when dac0 is written */
 };
 static inline unsigned int DAC_RANGE(unsigned int channel, unsigned int range)
 {
@@ -160,42 +161,42 @@
 	return 0x3 << (8 + 2 * (channel & 0x1));
 };
 
-// bits for 1602 series only
+/* bits for 1602 series only */
 enum dac_csr_bits_1602 {
-	DAC_EMPTY = 0x1,	// dac fifo empty, read, write clear
-	DAC_START = 0x4,	// start/arm dac fifo operations
-	DAC_PACER_MASK = 0x18,	// bits that set dac pacer source
-	DAC_PACER_INT = 0x8,	// dac internal pacing
-	DAC_PACER_EXT_FALL = 0x10,	// dac external pacing, falling edge
-	DAC_PACER_EXT_RISE = 0x18,	// dac external pacing, rising edge
+	DAC_EMPTY = 0x1,	/*  dac fifo empty, read, write clear */
+	DAC_START = 0x4,	/*  start/arm dac fifo operations */
+	DAC_PACER_MASK = 0x18,	/*  bits that set dac pacer source */
+	DAC_PACER_INT = 0x8,	/*  dac internal pacing */
+	DAC_PACER_EXT_FALL = 0x10,	/*  dac external pacing, falling edge */
+	DAC_PACER_EXT_RISE = 0x18,	/*  dac external pacing, rising edge */
 };
 static inline unsigned int DAC_CHAN_EN(unsigned int channel)
 {
-	return 1 << (5 + (channel & 0x1));	// enable channel 0 or 1
+	return 1 << (5 + (channel & 0x1));	/*  enable channel 0 or 1 */
 };
 
 /* analog input fifo */
-#define ADCDATA	0		// ADC DATA register
-#define ADCFIFOCLR	2	// ADC FIFO CLEAR
+#define ADCDATA	0		/*  ADC DATA register */
+#define ADCFIFOCLR	2	/*  ADC FIFO CLEAR */
 
-// pacer, counter, dio registers
+/* pacer, counter, dio registers */
 #define ADC8254 0
 #define DIO_8255 4
 #define DAC8254 8
 
-// analog output registers for 100x, 1200 series
+/* analog output registers for 100x, 1200 series */
 static inline unsigned int DAC_DATA_REG(unsigned int channel)
 {
 	return 2 * (channel & 0x1);
 }
 
 /* analog output registers for 1602 series*/
-#define DACDATA	0		// DAC DATA register
-#define DACFIFOCLR	2	// DAC FIFO CLEAR
+#define DACDATA	0		/*  DAC DATA register */
+#define DACFIFOCLR	2	/*  DAC FIFO CLEAR */
 
-// bit in hexadecimal representation of range index that indicates unipolar input range
+/* bit in hexadecimal representation of range index that indicates unipolar input range */
 #define IS_UNIPOLAR 0x4
-// analog input ranges for most boards
+/* analog input ranges for most boards */
 static const struct comedi_lrange cb_pcidas_ranges = {
 	8,
 	{
@@ -210,7 +211,7 @@
 		}
 };
 
-// pci-das1001 input ranges
+/* pci-das1001 input ranges */
 static const struct comedi_lrange cb_pcidas_alt_ranges = {
 	8,
 	{
@@ -225,7 +226,7 @@
 		}
 };
 
-// analog output ranges
+/* analog output ranges */
 static const struct comedi_lrange cb_pcidas_ao_ranges = {
 	4,
 	{
@@ -244,14 +245,14 @@
 struct cb_pcidas_board {
 	const char *name;
 	unsigned short device_id;
-	int ai_se_chans;	// Inputs in single-ended mode
-	int ai_diff_chans;	// Inputs in differential mode
-	int ai_bits;		// analog input resolution
-	int ai_speed;		// fastest conversion period in ns
-	int ao_nchan;		// number of analog out channels
-	int has_ao_fifo;	// analog output has fifo
-	int ao_scan_speed;	// analog output speed for 1602 series (for a scan, not conversion)
-	int fifo_size;		// number of samples fifo can hold
+	int ai_se_chans;	/*  Inputs in single-ended mode */
+	int ai_diff_chans;	/*  Inputs in differential mode */
+	int ai_bits;		/*  analog input resolution */
+	int ai_speed;		/*  fastest conversion period in ns */
+	int ao_nchan;		/*  number of analog out channels */
+	int has_ao_fifo;	/*  analog output has fifo */
+	int ao_scan_speed;	/*  analog output speed for 1602 series (for a scan, not conversion) */
+	int fifo_size;		/*  number of samples fifo can hold */
 	const struct comedi_lrange *ranges;
 	enum trimpot_model trimpot;
 	unsigned has_dac08:1;
@@ -259,124 +260,121 @@
 
 static const struct cb_pcidas_board cb_pcidas_boards[] = {
 	{
-	      name:	"pci-das1602/16",
-	      device_id:0x1,
-	      ai_se_chans:16,
-	      ai_diff_chans:8,
-	      ai_bits:	16,
-	      ai_speed:5000,
-	      ao_nchan:2,
-	      has_ao_fifo:1,
-	      ao_scan_speed:10000,
-	      fifo_size:512,
-	      ranges:	&cb_pcidas_ranges,
-	      trimpot:	AD8402,
-	      has_dac08:1,
+	.name = "pci-das1602/16",
+	.device_id = 0x1,
+	.ai_se_chans = 16,
+	.ai_diff_chans = 8,
+	.ai_bits = 16,
+	.ai_speed = 5000,
+	.ao_nchan = 2,
+	.has_ao_fifo = 1,
+	.ao_scan_speed = 10000,
+	.fifo_size = 512,
+	.ranges = &cb_pcidas_ranges,
+	.trimpot = AD8402,
+	.has_dac08 = 1,
 		},
 	{
-	      name:	"pci-das1200",
-	      device_id:0xF,
-	      ai_se_chans:16,
-	      ai_diff_chans:8,
-	      ai_bits:	12,
-	      ai_speed:3200,
-	      ao_nchan:2,
-	      has_ao_fifo:0,
-	      fifo_size:1024,
-	      ranges:	&cb_pcidas_ranges,
-	      trimpot:	AD7376,
-	      has_dac08:0,
+	.name = "pci-das1200",
+	.device_id = 0xF,
+	.ai_se_chans = 16,
+	.ai_diff_chans = 8,
+	.ai_bits = 12,
+	.ai_speed = 3200,
+	.ao_nchan = 2,
+	.has_ao_fifo = 0,
+	.fifo_size = 1024,
+	.ranges = &cb_pcidas_ranges,
+	.trimpot = AD7376,
+	.has_dac08 = 0,
 		},
 	{
-	      name:	"pci-das1602/12",
-	      device_id:0x10,
-	      ai_se_chans:16,
-	      ai_diff_chans:8,
-	      ai_bits:	12,
-	      ai_speed:3200,
-	      ao_nchan:2,
-	      has_ao_fifo:1,
-	      ao_scan_speed:4000,
-	      fifo_size:1024,
-	      ranges:	&cb_pcidas_ranges,
-	      trimpot:	AD7376,
-	      has_dac08:0,
+	.name = "pci-das1602/12",
+	.device_id = 0x10,
+	.ai_se_chans = 16,
+	.ai_diff_chans = 8,
+	.ai_bits = 12,
+	.ai_speed = 3200,
+	.ao_nchan = 2,
+	.has_ao_fifo = 1,
+	.ao_scan_speed = 4000,
+	.fifo_size = 1024,
+	.ranges = &cb_pcidas_ranges,
+	.trimpot = AD7376,
+	.has_dac08 = 0,
 		},
 	{
-	      name:	"pci-das1200/jr",
-	      device_id:0x19,
-	      ai_se_chans:16,
-	      ai_diff_chans:8,
-	      ai_bits:	12,
-	      ai_speed:3200,
-	      ao_nchan:0,
-	      has_ao_fifo:0,
-	      fifo_size:1024,
-	      ranges:	&cb_pcidas_ranges,
-	      trimpot:	AD7376,
-	      has_dac08:0,
+	.name = "pci-das1200/jr",
+	.device_id = 0x19,
+	.ai_se_chans = 16,
+	.ai_diff_chans = 8,
+	.ai_bits = 12,
+	.ai_speed = 3200,
+	.ao_nchan = 0,
+	.has_ao_fifo = 0,
+	.fifo_size = 1024,
+	.ranges = &cb_pcidas_ranges,
+	.trimpot = AD7376,
+	.has_dac08 = 0,
 		},
 	{
-	      name:	"pci-das1602/16/jr",
-	      device_id:0x1C,
-	      ai_se_chans:16,
-	      ai_diff_chans:8,
-	      ai_bits:	16,
-	      ai_speed:5000,
-	      ao_nchan:0,
-	      has_ao_fifo:0,
-	      fifo_size:512,
-	      ranges:	&cb_pcidas_ranges,
-	      trimpot:	AD8402,
-	      has_dac08:1,
+	.name = "pci-das1602/16/jr",
+	.device_id = 0x1C,
+	.ai_se_chans = 16,
+	.ai_diff_chans = 8,
+	.ai_bits = 16,
+	.ai_speed = 5000,
+	.ao_nchan = 0,
+	.has_ao_fifo = 0,
+	.fifo_size = 512,
+	.ranges = &cb_pcidas_ranges,
+	.trimpot = AD8402,
+	.has_dac08 = 1,
 		},
 	{
-	      name:	"pci-das1000",
-	      device_id:0x4C,
-	      ai_se_chans:16,
-	      ai_diff_chans:8,
-	      ai_bits:	12,
-	      ai_speed:4000,
-	      ao_nchan:0,
-	      has_ao_fifo:0,
-	      fifo_size:1024,
-	      ranges:	&cb_pcidas_ranges,
-	      trimpot:	AD7376,
-	      has_dac08:0,
+	.name = "pci-das1000",
+	.device_id = 0x4C,
+	.ai_se_chans = 16,
+	.ai_diff_chans = 8,
+	.ai_bits = 12,
+	.ai_speed = 4000,
+	.ao_nchan = 0,
+	.has_ao_fifo = 0,
+	.fifo_size = 1024,
+	.ranges = &cb_pcidas_ranges,
+	.trimpot = AD7376,
+	.has_dac08 = 0,
 		},
 	{
-	      name:	"pci-das1001",
-	      device_id:0x1a,
-	      ai_se_chans:16,
-	      ai_diff_chans:8,
-	      ai_bits:	12,
-	      ai_speed:6800,
-	      ao_nchan:2,
-	      has_ao_fifo:0,
-	      fifo_size:1024,
-	      ranges:	&cb_pcidas_alt_ranges,
-	      trimpot:	AD7376,
-	      has_dac08:0,
+	.name = "pci-das1001",
+	.device_id = 0x1a,
+	.ai_se_chans = 16,
+	.ai_diff_chans = 8,
+	.ai_bits = 12,
+	.ai_speed = 6800,
+	.ao_nchan = 2,
+	.has_ao_fifo = 0,
+	.fifo_size = 1024,
+	.ranges = &cb_pcidas_alt_ranges,
+	.trimpot = AD7376,
+	.has_dac08 = 0,
 		},
 	{
-	      name:	"pci-das1002",
-	      device_id:0x1b,
-	      ai_se_chans:16,
-	      ai_diff_chans:8,
-	      ai_bits:	12,
-	      ai_speed:6800,
-	      ao_nchan:2,
-	      has_ao_fifo:0,
-	      fifo_size:1024,
-	      ranges:	&cb_pcidas_ranges,
-	      trimpot:	AD7376,
-	      has_dac08:0,
+	.name = "pci-das1002",
+	.device_id = 0x1b,
+	.ai_se_chans = 16,
+	.ai_diff_chans = 8,
+	.ai_bits = 12,
+	.ai_speed = 6800,
+	.ao_nchan = 2,
+	.has_ao_fifo = 0,
+	.fifo_size = 1024,
+	.ranges = &cb_pcidas_ranges,
+	.trimpot = AD7376,
+	.has_dac08 = 0,
 		},
 };
 
-// Number of boards in cb_pcidas_boards
-#define N_BOARDS	(sizeof(cb_pcidas_boards) / sizeof(struct cb_pcidas_board))
-
 static DEFINE_PCI_DEVICE_TABLE(cb_pcidas_pci_table) = {
 	{PCI_VENDOR_ID_CB, 0x0001, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
 	{PCI_VENDOR_ID_CB, 0x000f, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
@@ -402,28 +400,28 @@
 struct cb_pcidas_private {
 	/* would be useful for a PCI device */
 	struct pci_dev *pci_dev;
-	// base addresses
+	/*  base addresses */
 	unsigned long s5933_config;
 	unsigned long control_status;
 	unsigned long adc_fifo;
 	unsigned long pacer_counter_dio;
 	unsigned long ao_registers;
-	// divisors of master clock for analog input pacing
+	/*  divisors of master clock for analog input pacing */
 	unsigned int divisor1;
 	unsigned int divisor2;
-	volatile unsigned int count;	// number of analog input samples remaining
-	volatile unsigned int adc_fifo_bits;	// bits to write to interupt/adcfifo register
-	volatile unsigned int s5933_intcsr_bits;	// bits to write to amcc s5933 interrupt control/status register
-	volatile unsigned int ao_control_bits;	// bits to write to ao control and status register
+	volatile unsigned int count;	/*  number of analog input samples remaining */
+	volatile unsigned int adc_fifo_bits;	/*  bits to write to interupt/adcfifo register */
+	volatile unsigned int s5933_intcsr_bits;	/*  bits to write to amcc s5933 interrupt control/status register */
+	volatile unsigned int ao_control_bits;	/*  bits to write to ao control and status register */
 	short ai_buffer[AI_BUFFER_SIZE];
 	short ao_buffer[AO_BUFFER_SIZE];
-	// divisors of master clock for analog output pacing
+	/*  divisors of master clock for analog output pacing */
 	unsigned int ao_divisor1;
 	unsigned int ao_divisor2;
-	volatile unsigned int ao_count;	// number of analog output samples remaining
-	int ao_value[2];	// remember what the analog outputs are set to, to allow readback
-	unsigned int caldac_value[NUM_CHANNELS_8800];	// for readback of caldac
-	unsigned int trimpot_value[NUM_CHANNELS_8402];	// for readback of trimpot
+	volatile unsigned int ao_count;	/*  number of analog output samples remaining */
+	int ao_value[2];	/*  remember what the analog outputs are set to, to allow readback */
+	unsigned int caldac_value[NUM_CHANNELS_8800];	/*  for readback of caldac */
+	unsigned int trimpot_value[NUM_CHANNELS_8402];	/*  for readback of trimpot */
 	unsigned int dac08_value;
 	unsigned int calibration_source;
 };
@@ -440,66 +438,66 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int cb_pcidas_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int cb_pcidas_detach(struct comedi_device * dev);
+static int cb_pcidas_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int cb_pcidas_detach(struct comedi_device *dev);
 static struct comedi_driver driver_cb_pcidas = {
-      driver_name:"cb_pcidas",
-      module:THIS_MODULE,
-      attach:cb_pcidas_attach,
-      detach:cb_pcidas_detach,
+	.driver_name = "cb_pcidas",
+	.module = THIS_MODULE,
+	.attach = cb_pcidas_attach,
+	.detach = cb_pcidas_detach,
 };
 
 static int cb_pcidas_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ai_config_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int cb_pcidas_ao_nofifo_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int cb_pcidas_ao_fifo_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int cb_pcidas_ao_readback_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int cb_pcidas_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int cb_pcidas_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int cb_pcidas_ao_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
+	struct comedi_insn *insn, unsigned int *data);
+static int ai_config_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int cb_pcidas_ao_nofifo_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int cb_pcidas_ao_fifo_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int cb_pcidas_ao_readback_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int cb_pcidas_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int cb_pcidas_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int cb_pcidas_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
 static int cb_pcidas_ao_inttrig(struct comedi_device *dev,
 				struct comedi_subdevice *subdev,
 				unsigned int trig_num);
-static int cb_pcidas_ao_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static irqreturn_t cb_pcidas_interrupt(int irq, void *d PT_REGS_ARG);
-static void handle_ao_interrupt(struct comedi_device * dev, unsigned int status);
-static int cb_pcidas_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static int cb_pcidas_ao_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static void cb_pcidas_load_counters(struct comedi_device * dev, unsigned int *ns,
+static int cb_pcidas_ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static irqreturn_t cb_pcidas_interrupt(int irq, void *d);
+static void handle_ao_interrupt(struct comedi_device *dev, unsigned int status);
+static int cb_pcidas_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static int cb_pcidas_ao_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static void cb_pcidas_load_counters(struct comedi_device *dev, unsigned int *ns,
 	int round_flags);
-static int eeprom_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int caldac_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int caldac_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int trimpot_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int cb_pcidas_trimpot_write(struct comedi_device * dev, unsigned int channel,
+static int eeprom_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int caldac_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int caldac_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int trimpot_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int cb_pcidas_trimpot_write(struct comedi_device *dev, unsigned int channel,
 	unsigned int value);
-static int trimpot_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dac08_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dac08_write(struct comedi_device * dev, unsigned int value);
-static int dac08_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int caldac_8800_write(struct comedi_device * dev, unsigned int address,
+static int trimpot_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dac08_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dac08_write(struct comedi_device *dev, unsigned int value);
+static int dac08_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int caldac_8800_write(struct comedi_device *dev, unsigned int address,
 	uint8_t value);
-static int trimpot_7376_write(struct comedi_device * dev, uint8_t value);
-static int trimpot_8402_write(struct comedi_device * dev, unsigned int channel,
+static int trimpot_7376_write(struct comedi_device *dev, uint8_t value);
+static int trimpot_8402_write(struct comedi_device *dev, unsigned int channel,
 	uint8_t value);
-static int nvram_read(struct comedi_device * dev, unsigned int address,
-	uint8_t * data);
+static int nvram_read(struct comedi_device *dev, unsigned int address,
+	uint8_t *data);
 
-static inline unsigned int cal_enable_bits(struct comedi_device * dev)
+static inline unsigned int cal_enable_bits(struct comedi_device *dev)
 {
 	return CAL_EN_BIT | CAL_SRC_BITS(devpriv->calibration_source);
 }
@@ -508,7 +506,7 @@
  * Attach is called by the Comedi core to configure the driver
  * for a particular board.
  */
-static int cb_pcidas_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int cb_pcidas_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	struct pci_dev *pcidev;
@@ -531,16 +529,16 @@
 	for (pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL);
 		pcidev != NULL;
 		pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pcidev)) {
-		// is it not a computer boards card?
+		/*  is it not a computer boards card? */
 		if (pcidev->vendor != PCI_VENDOR_ID_CB)
 			continue;
-		// loop through cards supported by this driver
-		for (index = 0; index < N_BOARDS; index++) {
+		/*  loop through cards supported by this driver */
+		for (index = 0; index < ARRAY_SIZE(cb_pcidas_boards); index++) {
 			if (cb_pcidas_boards[index].device_id != pcidev->device)
 				continue;
-			// was a particular bus/slot requested?
+			/*  was a particular bus/slot requested? */
 			if (it->options[0] || it->options[1]) {
-				// are we on the wrong bus/slot?
+				/*  are we on the wrong bus/slot? */
 				if (pcidev->bus->number != it->options[0] ||
 					PCI_SLOT(pcidev->devfn) !=
 					it->options[1]) {
@@ -585,19 +583,19 @@
 		devpriv->ao_registers =
 			pci_resource_start(devpriv->pci_dev, AO_BADRINDEX);
 	}
-	// disable and clear interrupts on amcc s5933
+	/*  disable and clear interrupts on amcc s5933 */
 	outl(INTCSR_INBOX_INTR_STATUS,
 		devpriv->s5933_config + AMCC_OP_REG_INTCSR);
 
-	// get irq
-	if (comedi_request_irq(devpriv->pci_dev->irq, cb_pcidas_interrupt,
+	/*  get irq */
+	if (request_irq(devpriv->pci_dev->irq, cb_pcidas_interrupt,
 			IRQF_SHARED, "cb_pcidas", dev)) {
 		printk(" unable to allocate irq %d\n", devpriv->pci_dev->irq);
 		return -EINVAL;
 	}
 	dev->irq = devpriv->pci_dev->irq;
 
-	//Initialize dev->board_name
+	/* Initialize dev->board_name */
 	dev->board_name = thisboard->name;
 
 /*
@@ -628,7 +626,7 @@
 		s->type = COMEDI_SUBD_AO;
 		s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_GROUND;
 		s->n_chan = thisboard->ao_nchan;
-		// analog out resolution is the same as analog input resolution, so use ai_bits
+		/*  analog out resolution is the same as analog input resolution, so use ai_bits */
 		s->maxdata = (1 << thisboard->ai_bits) - 1;
 		s->range_table = &cb_pcidas_ao_ranges;
 		s->insn_read = cb_pcidas_ao_readback_insn;
@@ -650,7 +648,7 @@
 	s = dev->subdevices + 2;
 	subdev_8255_init(dev, s, NULL, devpriv->pacer_counter_dio + DIO_8255);
 
-	// serial EEPROM,
+	/*  serial EEPROM, */
 	s = dev->subdevices + 3;
 	s->type = COMEDI_SUBD_MEMORY;
 	s->subdev_flags = SDF_READABLE | SDF_INTERNAL;
@@ -658,7 +656,7 @@
 	s->maxdata = 0xff;
 	s->insn_read = eeprom_read_insn;
 
-	// 8800 caldac
+	/*  8800 caldac */
 	s = dev->subdevices + 4;
 	s->type = COMEDI_SUBD_CALIB;
 	s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
@@ -669,7 +667,7 @@
 	for (i = 0; i < s->n_chan; i++)
 		caldac_8800_write(dev, i, s->maxdata / 2);
 
-	// trim potentiometer
+	/*  trim potentiometer */
 	s = dev->subdevices + 5;
 	s->type = COMEDI_SUBD_CALIB;
 	s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
@@ -685,7 +683,7 @@
 	for (i = 0; i < s->n_chan; i++)
 		cb_pcidas_trimpot_write(dev, i, s->maxdata / 2);
 
-	// dac08 caldac
+	/*  dac08 caldac */
 	s = dev->subdevices + 6;
 	if (thisboard->has_dac08) {
 		s->type = COMEDI_SUBD_CALIB;
@@ -698,13 +696,13 @@
 	} else
 		s->type = COMEDI_SUBD_UNUSED;
 
-	// make sure mailbox 4 is empty
+	/*  make sure mailbox 4 is empty */
 	inl(devpriv->s5933_config + AMCC_OP_REG_IMB4);
 	/* Set bits to enable incoming mailbox interrupts on amcc s5933. */
 	devpriv->s5933_intcsr_bits =
 		INTCSR_INBOX_BYTE(3) | INTCSR_INBOX_SELECT(3) |
 		INTCSR_INBOX_FULL_INT;
-	// clear and enable interrupt on amcc s5933
+	/*  clear and enable interrupt on amcc s5933 */
 	outl(devpriv->s5933_intcsr_bits | INTCSR_INBOX_INTR_STATUS,
 		devpriv->s5933_config + AMCC_OP_REG_INTCSR);
 
@@ -719,24 +717,24 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int cb_pcidas_detach(struct comedi_device * dev)
+static int cb_pcidas_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: cb_pcidas: remove\n", dev->minor);
 
 	if (devpriv) {
 		if (devpriv->s5933_config) {
-			// disable and clear interrupts on amcc s5933
+			/*  disable and clear interrupts on amcc s5933 */
 			outl(INTCSR_INBOX_INTR_STATUS,
 				devpriv->s5933_config + AMCC_OP_REG_INTCSR);
 #ifdef CB_PCIDAS_DEBUG
-			rt_printk("detaching, incsr is 0x%x\n",
+			printk("detaching, incsr is 0x%x\n",
 				inl(devpriv->s5933_config +
 					AMCC_OP_REG_INTCSR));
 #endif
 		}
 	}
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	if (dev->subdevices)
 		subdev_8255_cleanup(dev, dev->subdevices + 2);
 	if (devpriv && devpriv->pci_dev) {
@@ -753,14 +751,14 @@
  * "instructions" read/write data in "one-shot" or "software-triggered"
  * mode.
  */
-static int cb_pcidas_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int cb_pcidas_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, i;
 	unsigned int bits;
 	static const int timeout = 10000;
 	int channel;
-	// enable calibration input if appropriate
+	/*  enable calibration input if appropriate */
 	if (insn->chanspec & CR_ALT_SOURCE) {
 		outw(cal_enable_bits(dev),
 			devpriv->control_status + CALIBRATION_REG);
@@ -769,13 +767,13 @@
 		outw(0, devpriv->control_status + CALIBRATION_REG);
 		channel = CR_CHAN(insn->chanspec);
 	}
-	// set mux limits and gain
+	/*  set mux limits and gain */
 	bits = BEGIN_SCAN(channel) |
 		END_SCAN(channel) | GAIN_BITS(CR_RANGE(insn->chanspec));
-	// set unipolar/bipolar
+	/*  set unipolar/bipolar */
 	if (CR_RANGE(insn->chanspec) & IS_UNIPOLAR)
 		bits |= UNIP;
-	// set singleended/differential
+	/*  set singleended/differential */
 	if (CR_AREF(insn->chanspec) != AREF_DIFF)
 		bits |= SE;
 	outw(bits, devpriv->control_status + ADCMUX_CONT);
@@ -805,7 +803,7 @@
 	return n;
 }
 
-static int ai_config_calibration_source(struct comedi_device * dev, unsigned int * data)
+static int ai_config_calibration_source(struct comedi_device *dev, unsigned int *data)
 {
 	static const int num_calibration_sources = 8;
 	unsigned int source = data[1];
@@ -820,8 +818,8 @@
 	return 2;
 }
 
-static int ai_config_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ai_config_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int id = data[0];
 
@@ -836,44 +834,44 @@
 	return -EINVAL;
 }
 
-// analog output insn for pcidas-1000 and 1200 series
-static int cb_pcidas_ao_nofifo_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+/* analog output insn for pcidas-1000 and 1200 series */
+static int cb_pcidas_ao_nofifo_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int channel;
 	unsigned long flags;
 
-	// set channel and range
+	/*  set channel and range */
 	channel = CR_CHAN(insn->chanspec);
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	devpriv->ao_control_bits &=
 		~DAC_MODE_UPDATE_BOTH & ~DAC_RANGE_MASK(channel);
 	devpriv->ao_control_bits |=
 		DACEN | DAC_RANGE(channel, CR_RANGE(insn->chanspec));
 	outw(devpriv->ao_control_bits, devpriv->control_status + DAC_CSR);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// remember value for readback
+	/*  remember value for readback */
 	devpriv->ao_value[channel] = data[0];
-	// send data
+	/*  send data */
 	outw(data[0], devpriv->ao_registers + DAC_DATA_REG(channel));
 
 	return 1;
 }
 
-// analog output insn for pcidas-1602 series
-static int cb_pcidas_ao_fifo_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+/* analog output insn for pcidas-1602 series */
+static int cb_pcidas_ao_fifo_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int channel;
 	unsigned long flags;
 
-	// clear dac fifo
+	/*  clear dac fifo */
 	outw(0, devpriv->ao_registers + DACFIFOCLR);
 
-	// set channel and range
+	/*  set channel and range */
 	channel = CR_CHAN(insn->chanspec);
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	devpriv->ao_control_bits &=
 		~DAC_CHAN_EN(0) & ~DAC_CHAN_EN(1) & ~DAC_RANGE_MASK(channel) &
 		~DAC_PACER_MASK;
@@ -881,28 +879,28 @@
 		DACEN | DAC_RANGE(channel,
 		CR_RANGE(insn->chanspec)) | DAC_CHAN_EN(channel) | DAC_START;
 	outw(devpriv->ao_control_bits, devpriv->control_status + DAC_CSR);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// remember value for readback
+	/*  remember value for readback */
 	devpriv->ao_value[channel] = data[0];
-	// send data
+	/*  send data */
 	outw(data[0], devpriv->ao_registers + DACDATA);
 
 	return 1;
 }
 
-// analog output readback insn
-// XXX loses track of analog output value back after an analog ouput command is executed
-static int cb_pcidas_ao_readback_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+/* analog output readback insn */
+/* XXX loses track of analog output value back after an analog ouput command is executed */
+static int cb_pcidas_ao_readback_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->ao_value[CR_CHAN(insn->chanspec)];
 
 	return 1;
 }
 
-static int eeprom_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int eeprom_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	uint8_t nvram_data;
 	int retval;
@@ -916,16 +914,16 @@
 	return 1;
 }
 
-static int caldac_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int caldac_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	const unsigned int channel = CR_CHAN(insn->chanspec);
 
 	return caldac_8800_write(dev, channel, data[0]);
 }
 
-static int caldac_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int caldac_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->caldac_value[CR_CHAN(insn->chanspec)];
 
@@ -933,7 +931,7 @@
 }
 
 /* 1602/16 pregain offset */
-static int dac08_write(struct comedi_device * dev, unsigned int value)
+static int dac08_write(struct comedi_device *dev, unsigned int value)
 {
 	if (devpriv->dac08_value == value)
 		return 1;
@@ -942,32 +940,32 @@
 
 	outw(cal_enable_bits(dev) | (value & 0xff),
 		devpriv->control_status + CALIBRATION_REG);
-	comedi_udelay(1);
+	udelay(1);
 	outw(cal_enable_bits(dev) | SELECT_DAC08_BIT | (value & 0xff),
 		devpriv->control_status + CALIBRATION_REG);
-	comedi_udelay(1);
+	udelay(1);
 	outw(cal_enable_bits(dev) | (value & 0xff),
 		devpriv->control_status + CALIBRATION_REG);
-	comedi_udelay(1);
+	udelay(1);
 
 	return 1;
 }
 
-static int dac08_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dac08_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	return dac08_write(dev, data[0]);
 }
 
-static int dac08_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dac08_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->dac08_value;
 
 	return 1;
 }
 
-static int cb_pcidas_trimpot_write(struct comedi_device * dev,
+static int cb_pcidas_trimpot_write(struct comedi_device *dev,
 	unsigned int channel, unsigned int value)
 {
 	if (devpriv->trimpot_value[channel] == value)
@@ -990,16 +988,16 @@
 	return 1;
 }
 
-static int trimpot_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int trimpot_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int channel = CR_CHAN(insn->chanspec);
 
 	return cb_pcidas_trimpot_write(dev, channel, data[0]);
 }
 
-static int trimpot_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int trimpot_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int channel = CR_CHAN(insn->chanspec);
 
@@ -1008,8 +1006,8 @@
 	return 1;
 }
 
-static int cb_pcidas_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int cb_pcidas_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -1066,7 +1064,7 @@
 	if (cmd->stop_src != TRIG_COUNT && cmd->stop_src != TRIG_NONE)
 		err++;
 
-	// make sure trigger sources are compatible with each other
+	/*  make sure trigger sources are compatible with each other */
 	if (cmd->scan_begin_src == TRIG_FOLLOW && cmd->convert_src == TRIG_NOW)
 		err++;
 	if (cmd->scan_begin_src != TRIG_FOLLOW && cmd->convert_src != TRIG_NOW)
@@ -1138,7 +1136,7 @@
 	if (err)
 		return 4;
 
-	// check channel/gain list against card's limitations
+	/*  check channel/gain list against card's limitations */
 	if (cmd->chanlist) {
 		gain = CR_RANGE(cmd->chanlist[0]);
 		start_chan = CR_CHAN(cmd->chanlist[0]);
@@ -1163,31 +1161,31 @@
 	return 0;
 }
 
-static int cb_pcidas_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int cb_pcidas_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_async *async = s->async;
 	struct comedi_cmd *cmd = &async->cmd;
 	unsigned int bits;
 	unsigned long flags;
 
-	// make sure CAL_EN_BIT is disabled
+	/*  make sure CAL_EN_BIT is disabled */
 	outw(0, devpriv->control_status + CALIBRATION_REG);
-	// initialize before settings pacer source and count values
+	/*  initialize before settings pacer source and count values */
 	outw(0, devpriv->control_status + TRIG_CONTSTAT);
-	// clear fifo
+	/*  clear fifo */
 	outw(0, devpriv->adc_fifo + ADCFIFOCLR);
 
-	// set mux limits, gain and pacer source
+	/*  set mux limits, gain and pacer source */
 	bits = BEGIN_SCAN(CR_CHAN(cmd->chanlist[0])) |
 		END_SCAN(CR_CHAN(cmd->chanlist[cmd->chanlist_len - 1])) |
 		GAIN_BITS(CR_RANGE(cmd->chanlist[0]));
-	// set unipolar/bipolar
+	/*  set unipolar/bipolar */
 	if (CR_RANGE(cmd->chanlist[0]) & IS_UNIPOLAR)
 		bits |= UNIP;
-	// set singleended/differential
+	/*  set singleended/differential */
 	if (CR_AREF(cmd->chanlist[0]) != AREF_DIFF)
 		bits |= SE;
-	// set pacer source
+	/*  set pacer source */
 	if (cmd->convert_src == TRIG_EXT || cmd->scan_begin_src == TRIG_EXT)
 		bits |= PACER_EXT_RISE;
 	else
@@ -1195,10 +1193,10 @@
 	outw(bits, devpriv->control_status + ADCMUX_CONT);
 
 #ifdef CB_PCIDAS_DEBUG
-	rt_printk("comedi: sent 0x%x to adcmux control\n", bits);
+	printk("comedi: sent 0x%x to adcmux control\n", bits);
 #endif
 
-	// load counters
+	/*  load counters */
 	if (cmd->convert_src == TRIG_TIMER)
 		cb_pcidas_load_counters(dev, &cmd->convert_arg,
 			cmd->flags & TRIG_ROUND_MASK);
@@ -1206,31 +1204,31 @@
 		cb_pcidas_load_counters(dev, &cmd->scan_begin_arg,
 			cmd->flags & TRIG_ROUND_MASK);
 
-	// set number of conversions
+	/*  set number of conversions */
 	if (cmd->stop_src == TRIG_COUNT) {
 		devpriv->count = cmd->chanlist_len * cmd->stop_arg;
 	}
-	// enable interrupts
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  enable interrupts */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	devpriv->adc_fifo_bits |= INTE;
 	devpriv->adc_fifo_bits &= ~INT_MASK;
 	if (cmd->flags & TRIG_WAKE_EOS) {
 		if (cmd->convert_src == TRIG_NOW && cmd->chanlist_len > 1)
-			devpriv->adc_fifo_bits |= INT_EOS;	// interrupt end of burst
+			devpriv->adc_fifo_bits |= INT_EOS;	/*  interrupt end of burst */
 		else
-			devpriv->adc_fifo_bits |= INT_FNE;	// interrupt fifo not empty
+			devpriv->adc_fifo_bits |= INT_FNE;	/*  interrupt fifo not empty */
 	} else {
-		devpriv->adc_fifo_bits |= INT_FHF;	//interrupt fifo half full
+		devpriv->adc_fifo_bits |= INT_FHF;	/* interrupt fifo half full */
 	}
 #ifdef CB_PCIDAS_DEBUG
-	rt_printk("comedi: adc_fifo_bits are 0x%x\n", devpriv->adc_fifo_bits);
+	printk("comedi: adc_fifo_bits are 0x%x\n", devpriv->adc_fifo_bits);
 #endif
-	// enable (and clear) interrupts
+	/*  enable (and clear) interrupts */
 	outw(devpriv->adc_fifo_bits | EOAI | INT | LADFUL,
 		devpriv->control_status + INT_ADCFIFO);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// set start trigger and burst mode
+	/*  set start trigger and burst mode */
 	bits = 0;
 	if (cmd->start_src == TRIG_NOW)
 		bits |= SW_TRIGGER;
@@ -1244,14 +1242,14 @@
 		bits |= BURSTE;
 	outw(bits, devpriv->control_status + TRIG_CONTSTAT);
 #ifdef CB_PCIDAS_DEBUG
-	rt_printk("comedi: sent 0x%x to trig control\n", bits);
+	printk("comedi: sent 0x%x to trig control\n", bits);
 #endif
 
 	return 0;
 }
 
-static int cb_pcidas_ao_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int cb_pcidas_ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -1347,7 +1345,7 @@
 	if (err)
 		return 4;
 
-	// check channel/gain list against card's limitations
+	/*  check channel/gain list against card's limitations */
 	if (cmd->chanlist && cmd->chanlist_len > 1) {
 		if (CR_CHAN(cmd->chanlist[0]) != 0 ||
 			CR_CHAN(cmd->chanlist[1]) != 1) {
@@ -1363,32 +1361,32 @@
 	return 0;
 }
 
-static int cb_pcidas_ao_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int cb_pcidas_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_async *async = s->async;
 	struct comedi_cmd *cmd = &async->cmd;
 	unsigned int i;
 	unsigned long flags;
 
-	// set channel limits, gain
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  set channel limits, gain */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	for (i = 0; i < cmd->chanlist_len; i++) {
-		// enable channel
+		/*  enable channel */
 		devpriv->ao_control_bits |=
 			DAC_CHAN_EN(CR_CHAN(cmd->chanlist[i]));
-		// set range
+		/*  set range */
 		devpriv->ao_control_bits |= DAC_RANGE(CR_CHAN(cmd->chanlist[i]),
 			CR_RANGE(cmd->chanlist[i]));
 	}
 
-	// disable analog out before settings pacer source and count values
+	/*  disable analog out before settings pacer source and count values */
 	outw(devpriv->ao_control_bits, devpriv->control_status + DAC_CSR);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// clear fifo
+	/*  clear fifo */
 	outw(0, devpriv->ao_registers + DACFIFOCLR);
 
-	// load counters
+	/*  load counters */
 	if (cmd->scan_begin_src == TRIG_TIMER) {
 		i8253_cascade_ns_to_timer_2div(TIMER_BASE,
 			&(devpriv->ao_divisor1), &(devpriv->ao_divisor2),
@@ -1400,12 +1398,12 @@
 		i8254_load(devpriv->pacer_counter_dio + DAC8254, 0, 2,
 			devpriv->ao_divisor2, 2);
 	}
-	// set number of conversions
+	/*  set number of conversions */
 	if (cmd->stop_src == TRIG_COUNT) {
 		devpriv->ao_count = cmd->chanlist_len * cmd->stop_arg;
 	}
-	// set pacer source
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  set pacer source */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	switch (cmd->scan_begin_src) {
 	case TRIG_TIMER:
 		devpriv->ao_control_bits |= DAC_PACER_INT;
@@ -1414,12 +1412,12 @@
 		devpriv->ao_control_bits |= DAC_PACER_EXT_RISE;
 		break;
 	default:
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 		comedi_error(dev, "error setting dac pacer source");
 		return -1;
 		break;
 	}
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	async->inttrig = cb_pcidas_ao_inttrig;
 
@@ -1438,7 +1436,7 @@
 	if (trig_num != 0)
 		return -EINVAL;
 
-	// load up fifo
+	/*  load up fifo */
 	if (cmd->stop_src == TRIG_COUNT && devpriv->ao_count < num_points)
 		num_points = devpriv->ao_count;
 
@@ -1449,34 +1447,34 @@
 	if (cmd->stop_src == TRIG_COUNT) {
 		devpriv->ao_count -= num_points;
 	}
-	// write data to board's fifo
+	/*  write data to board's fifo */
 	outsw(devpriv->ao_registers + DACDATA, devpriv->ao_buffer, num_bytes);
 
-	// enable dac half-full and empty interrupts
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  enable dac half-full and empty interrupts */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	devpriv->adc_fifo_bits |= DAEMIE | DAHFIE;
 #ifdef CB_PCIDAS_DEBUG
-	rt_printk("comedi: adc_fifo_bits are 0x%x\n", devpriv->adc_fifo_bits);
+	printk("comedi: adc_fifo_bits are 0x%x\n", devpriv->adc_fifo_bits);
 #endif
-	// enable and clear interrupts
+	/*  enable and clear interrupts */
 	outw(devpriv->adc_fifo_bits | DAEMI | DAHFI,
 		devpriv->control_status + INT_ADCFIFO);
 
-	// start dac
+	/*  start dac */
 	devpriv->ao_control_bits |= DAC_START | DACEN | DAC_EMPTY;
 	outw(devpriv->ao_control_bits, devpriv->control_status + DAC_CSR);
 #ifdef CB_PCIDAS_DEBUG
-	rt_printk("comedi: sent 0x%x to dac control\n",
+	printk("comedi: sent 0x%x to dac control\n",
 		devpriv->ao_control_bits);
 #endif
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	async->inttrig = NULL;
 
 	return 0;
 }
 
-static irqreturn_t cb_pcidas_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t cb_pcidas_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = (struct comedi_device *) d;
 	struct comedi_subdevice *s = dev->read_subdev;
@@ -1496,16 +1494,16 @@
 
 	s5933_status = inl(devpriv->s5933_config + AMCC_OP_REG_INTCSR);
 #ifdef CB_PCIDAS_DEBUG
-	rt_printk("intcsr 0x%x\n", s5933_status);
-	rt_printk("mbef 0x%x\n", inl(devpriv->s5933_config + AMCC_OP_REG_MBEF));
+	printk("intcsr 0x%x\n", s5933_status);
+	printk("mbef 0x%x\n", inl(devpriv->s5933_config + AMCC_OP_REG_MBEF));
 #endif
 
 	if ((INTCSR_INTR_ASSERTED & s5933_status) == 0)
 		return IRQ_NONE;
 
-	// make sure mailbox 4 is empty
+	/*  make sure mailbox 4 is empty */
 	inl_p(devpriv->s5933_config + AMCC_OP_REG_IMB4);
-	// clear interrupt on amcc s5933
+	/*  clear interrupt on amcc s5933 */
 	outl(devpriv->s5933_intcsr_bits | INTCSR_INBOX_INTR_STATUS,
 		devpriv->s5933_config + AMCC_OP_REG_INTCSR);
 
@@ -1516,14 +1514,14 @@
 	}
 #endif
 
-	// check for analog output interrupt
+	/*  check for analog output interrupt */
 	if (status & (DAHFI | DAEMI)) {
 		handle_ao_interrupt(dev, status);
 	}
-	// check for analog input interrupts
-	// if fifo half-full
+	/*  check for analog input interrupts */
+	/*  if fifo half-full */
 	if (status & ADHFI) {
-		// read data
+		/*  read data */
 		num_samples = half_fifo;
 		if (async->cmd.stop_src == TRIG_COUNT &&
 			num_samples > devpriv->count) {
@@ -1538,15 +1536,15 @@
 			async->events |= COMEDI_CB_EOA;
 			cb_pcidas_cancel(dev, s);
 		}
-		// clear half-full interrupt latch
-		comedi_spin_lock_irqsave(&dev->spinlock, flags);
+		/*  clear half-full interrupt latch */
+		spin_lock_irqsave(&dev->spinlock, flags);
 		outw(devpriv->adc_fifo_bits | INT,
 			devpriv->control_status + INT_ADCFIFO);
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
-		// else if fifo not empty
+		spin_unlock_irqrestore(&dev->spinlock, flags);
+		/*  else if fifo not empty */
 	} else if (status & (ADNEI | EOBI)) {
 		for (i = 0; i < timeout; i++) {
-			// break if fifo is empty
+			/*  break if fifo is empty */
 			if ((ADNE & inw(devpriv->control_status +
 						INT_ADCFIFO)) == 0)
 				break;
@@ -1557,28 +1555,28 @@
 				break;
 			}
 		}
-		// clear not-empty interrupt latch
-		comedi_spin_lock_irqsave(&dev->spinlock, flags);
+		/*  clear not-empty interrupt latch */
+		spin_lock_irqsave(&dev->spinlock, flags);
 		outw(devpriv->adc_fifo_bits | INT,
 			devpriv->control_status + INT_ADCFIFO);
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 	} else if (status & EOAI) {
 		comedi_error(dev,
 			"bug! encountered end of aquisition interrupt?");
-		// clear EOA interrupt latch
-		comedi_spin_lock_irqsave(&dev->spinlock, flags);
+		/*  clear EOA interrupt latch */
+		spin_lock_irqsave(&dev->spinlock, flags);
 		outw(devpriv->adc_fifo_bits | EOAI,
 			devpriv->control_status + INT_ADCFIFO);
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 	}
-	//check for fifo overflow
+	/* check for fifo overflow */
 	if (status & LADFUL) {
 		comedi_error(dev, "fifo overflow");
-		// clear overflow interrupt latch
-		comedi_spin_lock_irqsave(&dev->spinlock, flags);
+		/*  clear overflow interrupt latch */
+		spin_lock_irqsave(&dev->spinlock, flags);
 		outw(devpriv->adc_fifo_bits | LADFUL,
 			devpriv->control_status + INT_ADCFIFO);
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 		cb_pcidas_cancel(dev, s);
 		async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
 	}
@@ -1588,23 +1586,23 @@
 	return IRQ_HANDLED;
 }
 
-static void handle_ao_interrupt(struct comedi_device * dev, unsigned int status)
+static void handle_ao_interrupt(struct comedi_device *dev, unsigned int status)
 {
 	struct comedi_subdevice *s = dev->write_subdev;
 	struct comedi_async *async = s->async;
 	struct comedi_cmd *cmd = &async->cmd;
 	unsigned int half_fifo = thisboard->fifo_size / 2;
 	unsigned int num_points;
-	unsigned int flags;
+	unsigned long flags;
 
 	async->events = 0;
 
 	if (status & DAEMI) {
-		// clear dac empty interrupt latch
-		comedi_spin_lock_irqsave(&dev->spinlock, flags);
+		/*  clear dac empty interrupt latch */
+		spin_lock_irqsave(&dev->spinlock, flags);
 		outw(devpriv->adc_fifo_bits | DAEMI,
 			devpriv->control_status + INT_ADCFIFO);
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 		if (inw(devpriv->ao_registers + DAC_CSR) & DAC_EMPTY) {
 			if (cmd->stop_src == TRIG_NONE ||
 				(cmd->stop_src == TRIG_COUNT
@@ -1618,7 +1616,7 @@
 	} else if (status & DAHFI) {
 		unsigned int num_bytes;
 
-		// figure out how many points we are writing to fifo
+		/*  figure out how many points we are writing to fifo */
 		num_points = half_fifo;
 		if (cmd->stop_src == TRIG_COUNT &&
 			devpriv->ao_count < num_points)
@@ -1631,33 +1629,33 @@
 		if (async->cmd.stop_src == TRIG_COUNT) {
 			devpriv->ao_count -= num_points;
 		}
-		// write data to board's fifo
+		/*  write data to board's fifo */
 		outsw(devpriv->ao_registers + DACDATA, devpriv->ao_buffer,
 			num_points);
-		// clear half-full interrupt latch
-		comedi_spin_lock_irqsave(&dev->spinlock, flags);
+		/*  clear half-full interrupt latch */
+		spin_lock_irqsave(&dev->spinlock, flags);
 		outw(devpriv->adc_fifo_bits | DAHFI,
 			devpriv->control_status + INT_ADCFIFO);
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 	}
 
 	comedi_event(dev, s);
 }
 
 /* cancel analog input command */
-static int cb_pcidas_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int cb_pcidas_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
-	// disable interrupts
+	spin_lock_irqsave(&dev->spinlock, flags);
+	/*  disable interrupts */
 	devpriv->adc_fifo_bits &= ~INTE & ~EOAIE;
 	outw(devpriv->adc_fifo_bits, devpriv->control_status + INT_ADCFIFO);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// disable start trigger source and burst mode
+	/*  disable start trigger source and burst mode */
 	outw(0, devpriv->control_status + TRIG_CONTSTAT);
-	// software pacer source
+	/*  software pacer source */
 	outw(0, devpriv->control_status + ADCMUX_CONT);
 
 	return 0;
@@ -1669,20 +1667,20 @@
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
-	// disable interrupts
+	spin_lock_irqsave(&dev->spinlock, flags);
+	/*  disable interrupts */
 	devpriv->adc_fifo_bits &= ~DAHFIE & ~DAEMIE;
 	outw(devpriv->adc_fifo_bits, devpriv->control_status + INT_ADCFIFO);
 
-	// disable output
+	/*  disable output */
 	devpriv->ao_control_bits &= ~DACEN & ~DAC_PACER_MASK;
 	outw(devpriv->ao_control_bits, devpriv->control_status + DAC_CSR);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	return 0;
 }
 
-static void cb_pcidas_load_counters(struct comedi_device * dev, unsigned int *ns,
+static void cb_pcidas_load_counters(struct comedi_device *dev, unsigned int *ns,
 	int rounding_flags)
 {
 	i8253_cascade_ns_to_timer_2div(TIMER_BASE, &(devpriv->divisor1),
@@ -1695,7 +1693,7 @@
 		devpriv->divisor2, 2);
 }
 
-static void write_calibration_bitstream(struct comedi_device * dev,
+static void write_calibration_bitstream(struct comedi_device *dev,
 	unsigned int register_bits, unsigned int bitstream,
 	unsigned int bitstream_length)
 {
@@ -1707,18 +1705,18 @@
 			register_bits |= SERIAL_DATA_IN_BIT;
 		else
 			register_bits &= ~SERIAL_DATA_IN_BIT;
-		comedi_udelay(write_delay);
+		udelay(write_delay);
 		outw(register_bits, devpriv->control_status + CALIBRATION_REG);
 	}
 }
 
-static int caldac_8800_write(struct comedi_device * dev, unsigned int address,
+static int caldac_8800_write(struct comedi_device *dev, unsigned int address,
 	uint8_t value)
 {
 	static const int num_caldac_channels = 8;
 	static const int bitstream_length = 11;
 	unsigned int bitstream = ((address & 0x7) << 8) | value;
-	static const int caldac_8800_comedi_udelay = 1;
+	static const int caldac_8800_udelay = 1;
 
 	if (address >= num_caldac_channels) {
 		comedi_error(dev, "illegal caldac channel");
@@ -1733,30 +1731,30 @@
 	write_calibration_bitstream(dev, cal_enable_bits(dev), bitstream,
 		bitstream_length);
 
-	comedi_udelay(caldac_8800_comedi_udelay);
+	udelay(caldac_8800_udelay);
 	outw(cal_enable_bits(dev) | SELECT_8800_BIT,
 		devpriv->control_status + CALIBRATION_REG);
-	comedi_udelay(caldac_8800_comedi_udelay);
+	udelay(caldac_8800_udelay);
 	outw(cal_enable_bits(dev), devpriv->control_status + CALIBRATION_REG);
 
 	return 1;
 }
 
-static int trimpot_7376_write(struct comedi_device * dev, uint8_t value)
+static int trimpot_7376_write(struct comedi_device *dev, uint8_t value)
 {
 	static const int bitstream_length = 7;
 	unsigned int bitstream = value & 0x7f;
 	unsigned int register_bits;
-	static const int ad7376_comedi_udelay = 1;
+	static const int ad7376_udelay = 1;
 
 	register_bits = cal_enable_bits(dev) | SELECT_TRIMPOT_BIT;
-	comedi_udelay(ad7376_comedi_udelay);
+	udelay(ad7376_udelay);
 	outw(register_bits, devpriv->control_status + CALIBRATION_REG);
 
 	write_calibration_bitstream(dev, register_bits, bitstream,
 		bitstream_length);
 
-	comedi_udelay(ad7376_comedi_udelay);
+	udelay(ad7376_udelay);
 	outw(cal_enable_bits(dev), devpriv->control_status + CALIBRATION_REG);
 
 	return 0;
@@ -1765,22 +1763,22 @@
 /* For 1602/16 only
  * ch 0 : adc gain
  * ch 1 : adc postgain offset */
-static int trimpot_8402_write(struct comedi_device * dev, unsigned int channel,
+static int trimpot_8402_write(struct comedi_device *dev, unsigned int channel,
 	uint8_t value)
 {
 	static const int bitstream_length = 10;
 	unsigned int bitstream = ((channel & 0x3) << 8) | (value & 0xff);
 	unsigned int register_bits;
-	static const int ad8402_comedi_udelay = 1;
+	static const int ad8402_udelay = 1;
 
 	register_bits = cal_enable_bits(dev) | SELECT_TRIMPOT_BIT;
-	comedi_udelay(ad8402_comedi_udelay);
+	udelay(ad8402_udelay);
 	outw(register_bits, devpriv->control_status + CALIBRATION_REG);
 
 	write_calibration_bitstream(dev, register_bits, bitstream,
 		bitstream_length);
 
-	comedi_udelay(ad8402_comedi_udelay);
+	udelay(ad8402_udelay);
 	outw(cal_enable_bits(dev), devpriv->control_status + CALIBRATION_REG);
 
 	return 0;
@@ -1796,12 +1794,12 @@
 					AMCC_OP_REG_MCSR_NVCMD) & MCSR_NV_BUSY)
 			== 0)
 			return 0;
-		comedi_udelay(1);
+		udelay(1);
 	}
 	return -1;
 }
 
-static int nvram_read(struct comedi_device * dev, unsigned int address, uint8_t * data)
+static int nvram_read(struct comedi_device *dev, unsigned int address, uint8_t *data)
 {
 	unsigned long iobase = devpriv->s5933_config;
 
diff --git a/drivers/staging/comedi/drivers/cb_pcidas64.c b/drivers/staging/comedi/drivers/cb_pcidas64.c
index 1a580bd..210b462 100644
--- a/drivers/staging/comedi/drivers/cb_pcidas64.c
+++ b/drivers/staging/comedi/drivers/cb_pcidas64.c
@@ -85,6 +85,7 @@
 
 #include "../comedidev.h"
 #include <linux/delay.h>
+#include <linux/interrupt.h>
 #include <asm/system.h>
 
 #include "comedi_pci.h"
@@ -93,17 +94,17 @@
 #include "plx9080.h"
 #include "comedi_fc.h"
 
-#undef PCIDAS64_DEBUG		// disable debugging code
-//#define PCIDAS64_DEBUG        // enable debugging code
+#undef PCIDAS64_DEBUG		/*  disable debugging code */
+/* #define PCIDAS64_DEBUG         enable debugging code */
 
 #ifdef PCIDAS64_DEBUG
-#define DEBUG_PRINT(format, args...)  rt_printk(format , ## args )
+#define DEBUG_PRINT(format, args...)  printk(format , ## args)
 #else
 #define DEBUG_PRINT(format, args...)
 #endif
 
-#define TIMER_BASE 25		// 40MHz master clock
-#define PRESCALED_TIMER_BASE	10000	// 100kHz 'prescaled' clock for slow aquisition, maybe I'll support this someday
+#define TIMER_BASE 25		/*  40MHz master clock */
+#define PRESCALED_TIMER_BASE	10000	/*  100kHz 'prescaled' clock for slow aquisition, maybe I'll support this someday */
 #define DMA_BUFFER_SIZE 0x1000
 
 /* maximum value that can be loaded into board's 24-bit counters*/
@@ -111,41 +112,41 @@
 
 /* PCI-DAS64xxx base addresses */
 
-// indices of base address regions
+/* indices of base address regions */
 enum base_address_regions {
 	PLX9080_BADDRINDEX = 0,
 	MAIN_BADDRINDEX = 2,
 	DIO_COUNTER_BADDRINDEX = 3,
 };
 
-// priv(dev)->main_iobase registers
+/* priv(dev)->main_iobase registers */
 enum write_only_registers {
-	INTR_ENABLE_REG = 0x0,	// interrupt enable register
-	HW_CONFIG_REG = 0x2,	// hardware config register
+	INTR_ENABLE_REG = 0x0,	/*  interrupt enable register */
+	HW_CONFIG_REG = 0x2,	/*  hardware config register */
 	DAQ_SYNC_REG = 0xc,
 	DAQ_ATRIG_LOW_4020_REG = 0xc,
-	ADC_CONTROL0_REG = 0x10,	// adc control register 0
-	ADC_CONTROL1_REG = 0x12,	// adc control register 1
+	ADC_CONTROL0_REG = 0x10,	/*  adc control register 0 */
+	ADC_CONTROL1_REG = 0x12,	/*  adc control register 1 */
 	CALIBRATION_REG = 0x14,
-	ADC_SAMPLE_INTERVAL_LOWER_REG = 0x16,	// lower 16 bits of adc sample interval counter
-	ADC_SAMPLE_INTERVAL_UPPER_REG = 0x18,	// upper 8 bits of adc sample interval counter
-	ADC_DELAY_INTERVAL_LOWER_REG = 0x1a,	// lower 16 bits of delay interval counter
-	ADC_DELAY_INTERVAL_UPPER_REG = 0x1c,	// upper 8 bits of delay interval counter
-	ADC_COUNT_LOWER_REG = 0x1e,	// lower 16 bits of hardware conversion/scan counter
-	ADC_COUNT_UPPER_REG = 0x20,	// upper 8 bits of hardware conversion/scan counter
-	ADC_START_REG = 0x22,	// software trigger to start aquisition
-	ADC_CONVERT_REG = 0x24,	// initiates single conversion
-	ADC_QUEUE_CLEAR_REG = 0x26,	// clears adc queue
-	ADC_QUEUE_LOAD_REG = 0x28,	// loads adc queue
+	ADC_SAMPLE_INTERVAL_LOWER_REG = 0x16,	/*  lower 16 bits of adc sample interval counter */
+	ADC_SAMPLE_INTERVAL_UPPER_REG = 0x18,	/*  upper 8 bits of adc sample interval counter */
+	ADC_DELAY_INTERVAL_LOWER_REG = 0x1a,	/*  lower 16 bits of delay interval counter */
+	ADC_DELAY_INTERVAL_UPPER_REG = 0x1c,	/*  upper 8 bits of delay interval counter */
+	ADC_COUNT_LOWER_REG = 0x1e,	/*  lower 16 bits of hardware conversion/scan counter */
+	ADC_COUNT_UPPER_REG = 0x20,	/*  upper 8 bits of hardware conversion/scan counter */
+	ADC_START_REG = 0x22,	/*  software trigger to start aquisition */
+	ADC_CONVERT_REG = 0x24,	/*  initiates single conversion */
+	ADC_QUEUE_CLEAR_REG = 0x26,	/*  clears adc queue */
+	ADC_QUEUE_LOAD_REG = 0x28,	/*  loads adc queue */
 	ADC_BUFFER_CLEAR_REG = 0x2a,
-	ADC_QUEUE_HIGH_REG = 0x2c,	// high channel for internal queue, use adc_chan_bits() inline above
-	DAC_CONTROL0_REG = 0x50,	// dac control register 0
-	DAC_CONTROL1_REG = 0x52,	// dac control register 0
-	DAC_SAMPLE_INTERVAL_LOWER_REG = 0x54,	// lower 16 bits of dac sample interval counter
-	DAC_SAMPLE_INTERVAL_UPPER_REG = 0x56,	// upper 8 bits of dac sample interval counter
+	ADC_QUEUE_HIGH_REG = 0x2c,	/*  high channel for internal queue, use adc_chan_bits() inline above */
+	DAC_CONTROL0_REG = 0x50,	/*  dac control register 0 */
+	DAC_CONTROL1_REG = 0x52,	/*  dac control register 0 */
+	DAC_SAMPLE_INTERVAL_LOWER_REG = 0x54,	/*  lower 16 bits of dac sample interval counter */
+	DAC_SAMPLE_INTERVAL_UPPER_REG = 0x56,	/*  upper 8 bits of dac sample interval counter */
 	DAC_SELECT_REG = 0x60,
 	DAC_START_REG = 0x64,
-	DAC_BUFFER_CLEAR_REG = 0x66,	// clear dac buffer
+	DAC_BUFFER_CLEAR_REG = 0x66,	/*  clear dac buffer */
 };
 static inline unsigned int dac_convert_reg(unsigned int channel)
 {
@@ -161,7 +162,7 @@
 }
 
 enum read_only_registers {
-	HW_STATUS_REG = 0x0,	// hardware status register, reading this apparently clears pending interrupts as well
+	HW_STATUS_REG = 0x0,	/*  hardware status register, reading this apparently clears pending interrupts as well */
 	PIPE1_READ_REG = 0x4,
 	ADC_READ_PNTR_REG = 0x8,
 	LOWER_XFER_REG = 0x10,
@@ -170,13 +171,13 @@
 };
 
 enum read_write_registers {
-	I8255_4020_REG = 0x48,	// 8255 offset, for 4020 only
-	ADC_QUEUE_FIFO_REG = 0x100,	// external channel/gain queue, uses same bits as ADC_QUEUE_LOAD_REG
+	I8255_4020_REG = 0x48,	/*  8255 offset, for 4020 only */
+	ADC_QUEUE_FIFO_REG = 0x100,	/*  external channel/gain queue, uses same bits as ADC_QUEUE_LOAD_REG */
 	ADC_FIFO_REG = 0x200,	/* adc data fifo */
 	DAC_FIFO_REG = 0x300,	/* dac data fifo, has weird interactions with external channel queue */
 };
 
-// priv(dev)->dio_counter_iobase registers
+/* priv(dev)->dio_counter_iobase registers */
 enum dio_counter_registers {
 	DIO_8255_OFFSET = 0x0,
 	DO_REG = 0x20,
@@ -185,47 +186,47 @@
 	DIO_DATA_60XX_REG = 0x48,
 };
 
-// bit definitions for write-only registers
+/* bit definitions for write-only registers */
 
 enum intr_enable_contents {
-	ADC_INTR_SRC_MASK = 0x3,	// bits that set adc interrupt source
-	ADC_INTR_QFULL_BITS = 0x0,	// interrupt fifo quater full
-	ADC_INTR_EOC_BITS = 0x1,	// interrupt end of conversion
-	ADC_INTR_EOSCAN_BITS = 0x2,	// interrupt end of scan
-	ADC_INTR_EOSEQ_BITS = 0x3,	// interrupt end of sequence (probably wont use this it's pretty fancy)
-	EN_ADC_INTR_SRC_BIT = 0x4,	// enable adc interrupt source
-	EN_ADC_DONE_INTR_BIT = 0x8,	// enable adc aquisition done interrupt
+	ADC_INTR_SRC_MASK = 0x3,	/*  bits that set adc interrupt source */
+	ADC_INTR_QFULL_BITS = 0x0,	/*  interrupt fifo quater full */
+	ADC_INTR_EOC_BITS = 0x1,	/*  interrupt end of conversion */
+	ADC_INTR_EOSCAN_BITS = 0x2,	/*  interrupt end of scan */
+	ADC_INTR_EOSEQ_BITS = 0x3,	/*  interrupt end of sequence (probably wont use this it's pretty fancy) */
+	EN_ADC_INTR_SRC_BIT = 0x4,	/*  enable adc interrupt source */
+	EN_ADC_DONE_INTR_BIT = 0x8,	/*  enable adc aquisition done interrupt */
 	DAC_INTR_SRC_MASK = 0x30,
 	DAC_INTR_QEMPTY_BITS = 0x0,
 	DAC_INTR_HIGH_CHAN_BITS = 0x10,
-	EN_DAC_INTR_SRC_BIT = 0x40,	// enable dac interrupt source
+	EN_DAC_INTR_SRC_BIT = 0x40,	/*  enable dac interrupt source */
 	EN_DAC_DONE_INTR_BIT = 0x80,
-	EN_ADC_ACTIVE_INTR_BIT = 0x200,	// enable adc active interrupt
-	EN_ADC_STOP_INTR_BIT = 0x400,	// enable adc stop trigger interrupt
-	EN_DAC_ACTIVE_INTR_BIT = 0x800,	// enable dac active interrupt
-	EN_DAC_UNDERRUN_BIT = 0x4000,	// enable dac underrun status bit
-	EN_ADC_OVERRUN_BIT = 0x8000,	// enable adc overrun status bit
+	EN_ADC_ACTIVE_INTR_BIT = 0x200,	/*  enable adc active interrupt */
+	EN_ADC_STOP_INTR_BIT = 0x400,	/*  enable adc stop trigger interrupt */
+	EN_DAC_ACTIVE_INTR_BIT = 0x800,	/*  enable dac active interrupt */
+	EN_DAC_UNDERRUN_BIT = 0x4000,	/*  enable dac underrun status bit */
+	EN_ADC_OVERRUN_BIT = 0x8000,	/*  enable adc overrun status bit */
 };
 
 enum hw_config_contents {
-	MASTER_CLOCK_4020_MASK = 0x3,	// bits that specify master clock source for 4020
-	INTERNAL_CLOCK_4020_BITS = 0x1,	// use 40 MHz internal master clock for 4020
-	BNC_CLOCK_4020_BITS = 0x2,	// use BNC input for master clock
-	EXT_CLOCK_4020_BITS = 0x3,	// use dio input for master clock
-	EXT_QUEUE_BIT = 0x200,	// use external channel/gain queue (more versatile than internal queue)
-	SLOW_DAC_BIT = 0x400,	// use 225 nanosec strobe when loading dac instead of 50 nanosec
-	HW_CONFIG_DUMMY_BITS = 0x2000,	// bit with unknown function yet given as default value in pci-das64 manual
-	DMA_CH_SELECT_BIT = 0x8000,	// bit selects channels 1/0 for analog input/output, otherwise 0/1
-	FIFO_SIZE_REG = 0x4,	// allows adjustment of fifo sizes
-	DAC_FIFO_SIZE_MASK = 0xff00,	// bits that set dac fifo size
+	MASTER_CLOCK_4020_MASK = 0x3,	/*  bits that specify master clock source for 4020 */
+	INTERNAL_CLOCK_4020_BITS = 0x1,	/*  use 40 MHz internal master clock for 4020 */
+	BNC_CLOCK_4020_BITS = 0x2,	/*  use BNC input for master clock */
+	EXT_CLOCK_4020_BITS = 0x3,	/*  use dio input for master clock */
+	EXT_QUEUE_BIT = 0x200,	/*  use external channel/gain queue (more versatile than internal queue) */
+	SLOW_DAC_BIT = 0x400,	/*  use 225 nanosec strobe when loading dac instead of 50 nanosec */
+	HW_CONFIG_DUMMY_BITS = 0x2000,	/*  bit with unknown function yet given as default value in pci-das64 manual */
+	DMA_CH_SELECT_BIT = 0x8000,	/*  bit selects channels 1/0 for analog input/output, otherwise 0/1 */
+	FIFO_SIZE_REG = 0x4,	/*  allows adjustment of fifo sizes */
+	DAC_FIFO_SIZE_MASK = 0xff00,	/*  bits that set dac fifo size */
 	DAC_FIFO_BITS = 0xf800,	/* 8k sample ao fifo */
 };
 #define DAC_FIFO_SIZE 0x2000
 
 enum daq_atrig_low_4020_contents {
-	EXT_AGATE_BNC_BIT = 0x8000,	// use trig/ext clk bnc input for analog gate signal
-	EXT_STOP_TRIG_BNC_BIT = 0x4000,	// use trig/ext clk bnc input for external stop trigger signal
-	EXT_START_TRIG_BNC_BIT = 0x2000,	// use trig/ext clk bnc input for external start trigger signal
+	EXT_AGATE_BNC_BIT = 0x8000,	/*  use trig/ext clk bnc input for analog gate signal */
+	EXT_STOP_TRIG_BNC_BIT = 0x4000,	/*  use trig/ext clk bnc input for external stop trigger signal */
+	EXT_START_TRIG_BNC_BIT = 0x2000,	/*  use trig/ext clk bnc input for external start trigger signal */
 };
 static inline uint16_t analog_trig_low_threshold_bits(uint16_t threshold)
 {
@@ -233,34 +234,34 @@
 }
 
 enum adc_control0_contents {
-	ADC_GATE_SRC_MASK = 0x3,	// bits that select gate
-	ADC_SOFT_GATE_BITS = 0x1,	// software gate
-	ADC_EXT_GATE_BITS = 0x2,	// external digital gate
-	ADC_ANALOG_GATE_BITS = 0x3,	// analog level gate
-	ADC_GATE_LEVEL_BIT = 0x4,	// level-sensitive gate (for digital)
-	ADC_GATE_POLARITY_BIT = 0x8,	// gate active low
+	ADC_GATE_SRC_MASK = 0x3,	/*  bits that select gate */
+	ADC_SOFT_GATE_BITS = 0x1,	/*  software gate */
+	ADC_EXT_GATE_BITS = 0x2,	/*  external digital gate */
+	ADC_ANALOG_GATE_BITS = 0x3,	/*  analog level gate */
+	ADC_GATE_LEVEL_BIT = 0x4,	/*  level-sensitive gate (for digital) */
+	ADC_GATE_POLARITY_BIT = 0x8,	/*  gate active low */
 	ADC_START_TRIG_SOFT_BITS = 0x10,
 	ADC_START_TRIG_EXT_BITS = 0x20,
 	ADC_START_TRIG_ANALOG_BITS = 0x30,
 	ADC_START_TRIG_MASK = 0x30,
-	ADC_START_TRIG_FALLING_BIT = 0x40,	// trig 1 uses falling edge
-	ADC_EXT_CONV_FALLING_BIT = 0x800,	// external pacing uses falling edge
-	ADC_SAMPLE_COUNTER_EN_BIT = 0x1000,	// enable hardware scan counter
-	ADC_DMA_DISABLE_BIT = 0x4000,	// disables dma
-	ADC_ENABLE_BIT = 0x8000,	// master adc enable
+	ADC_START_TRIG_FALLING_BIT = 0x40,	/*  trig 1 uses falling edge */
+	ADC_EXT_CONV_FALLING_BIT = 0x800,	/*  external pacing uses falling edge */
+	ADC_SAMPLE_COUNTER_EN_BIT = 0x1000,	/*  enable hardware scan counter */
+	ADC_DMA_DISABLE_BIT = 0x4000,	/*  disables dma */
+	ADC_ENABLE_BIT = 0x8000,	/*  master adc enable */
 };
 
 enum adc_control1_contents {
-	ADC_QUEUE_CONFIG_BIT = 0x1,	// should be set for boards with > 16 channels
+	ADC_QUEUE_CONFIG_BIT = 0x1,	/*  should be set for boards with > 16 channels */
 	CONVERT_POLARITY_BIT = 0x10,
 	EOC_POLARITY_BIT = 0x20,
-	ADC_SW_GATE_BIT = 0x40,	// software gate of adc
-	ADC_DITHER_BIT = 0x200,	// turn on extra noise for dithering
+	ADC_SW_GATE_BIT = 0x40,	/*  software gate of adc */
+	ADC_DITHER_BIT = 0x200,	/*  turn on extra noise for dithering */
 	RETRIGGER_BIT = 0x800,
 	ADC_LO_CHANNEL_4020_MASK = 0x300,
 	ADC_HI_CHANNEL_4020_MASK = 0xc00,
-	TWO_CHANNEL_4020_BITS = 0x1000,	// two channel mode for 4020
-	FOUR_CHANNEL_4020_BITS = 0x2000,	// four channel mode for 4020
+	TWO_CHANNEL_4020_BITS = 0x1000,	/*  two channel mode for 4020 */
+	FOUR_CHANNEL_4020_BITS = 0x2000,	/*  four channel mode for 4020 */
 	CHANNEL_MODE_4020_MASK = 0x3000,
 	ADC_MODE_MASK = 0xf000,
 };
@@ -281,10 +282,10 @@
 	SELECT_8800_BIT = 0x1,
 	SELECT_8402_64XX_BIT = 0x2,
 	SELECT_1590_60XX_BIT = 0x2,
-	CAL_EN_64XX_BIT = 0x40,	// calibration enable for 64xx series
+	CAL_EN_64XX_BIT = 0x40,	/*  calibration enable for 64xx series */
 	SERIAL_DATA_IN_BIT = 0x80,
 	SERIAL_CLOCK_BIT = 0x100,
-	CAL_EN_60XX_BIT = 0x200,	// calibration enable for 60xx series
+	CAL_EN_60XX_BIT = 0x200,	/*  calibration enable for 60xx series */
 	CAL_GAIN_BIT = 0x800,
 };
 /* calibration sources for 6025 are:
@@ -308,11 +309,11 @@
 };
 
 enum adc_queue_load_contents {
-	UNIP_BIT = 0x800,	// unipolar/bipolar bit
-	ADC_SE_DIFF_BIT = 0x1000,	// single-ended/ differential bit
-	ADC_COMMON_BIT = 0x2000,	// non-referenced single-ended (common-mode input)
-	QUEUE_EOSEQ_BIT = 0x4000,	// queue end of sequence
-	QUEUE_EOSCAN_BIT = 0x8000,	// queue end of scan
+	UNIP_BIT = 0x800,	/*  unipolar/bipolar bit */
+	ADC_SE_DIFF_BIT = 0x1000,	/*  single-ended/ differential bit */
+	ADC_COMMON_BIT = 0x2000,	/*  non-referenced single-ended (common-mode input) */
+	QUEUE_EOSEQ_BIT = 0x4000,	/*  queue end of sequence */
+	QUEUE_EOSCAN_BIT = 0x8000,	/*  queue end of scan */
 };
 static inline uint16_t adc_chan_bits(unsigned int channel)
 {
@@ -320,7 +321,7 @@
 };
 
 enum dac_control0_contents {
-	DAC_ENABLE_BIT = 0x8000,	// dac controller enable bit
+	DAC_ENABLE_BIT = 0x8000,	/*  dac controller enable bit */
 	DAC_CYCLIC_STOP_BIT = 0x4000,
 	DAC_WAVEFORM_MODE_BIT = 0x100,
 	DAC_EXT_UPDATE_FALLING_BIT = 0x80,
@@ -340,14 +341,14 @@
 	DAC_WRITE_POLARITY_BIT = 0x800,	/* board-dependent setting */
 	DAC1_EXT_REF_BIT = 0x200,
 	DAC0_EXT_REF_BIT = 0x100,
-	DAC_OUTPUT_ENABLE_BIT = 0x80,	// dac output enable bit
+	DAC_OUTPUT_ENABLE_BIT = 0x80,	/*  dac output enable bit */
 	DAC_UPDATE_POLARITY_BIT = 0x40,	/* board-dependent setting */
 	DAC_SW_GATE_BIT = 0x20,
 	DAC1_UNIPOLAR_BIT = 0x8,
 	DAC0_UNIPOLAR_BIT = 0x2,
 };
 
-// bit definitions for read-only registers
+/* bit definitions for read-only registers */
 enum hw_status_contents {
 	DAC_UNDERRUN_BIT = 0x1,
 	ADC_OVERRUN_BIT = 0x2,
@@ -378,7 +379,7 @@
 	return (prepost_bits >> 14) & 0x3;
 }
 
-// I2C addresses for 4020
+/* I2C addresses for 4020 */
 enum i2c_addresses {
 	RANGE_CAL_I2C_ADDR = 0x20,
 	CALDAC0_I2C_ADDR = 0xc,
@@ -386,8 +387,8 @@
 };
 
 enum range_cal_i2c_contents {
-	ADC_SRC_4020_MASK = 0x70,	// bits that set what source the adc converter measures
-	BNC_TRIG_THRESHOLD_0V_BIT = 0x80,	// make bnc trig/ext clock threshold 0V instead of 2.5V
+	ADC_SRC_4020_MASK = 0x70,	/*  bits that set what source the adc converter measures */
+	BNC_TRIG_THRESHOLD_0V_BIT = 0x80,	/*  make bnc trig/ext clock threshold 0V instead of 2.5V */
 };
 static inline uint8_t adc_src_4020_bits(unsigned int source)
 {
@@ -395,11 +396,11 @@
 };
 static inline uint8_t attenuate_bit(unsigned int channel)
 {
-	// attenuate channel (+-5V input range)
+	/*  attenuate channel (+-5V input range) */
 	return 1 << (channel & 0x3);
 };
 
-// analog input ranges for 64xx boards
+/* analog input ranges for 64xx boards */
 static const struct comedi_lrange ai_ranges_64xx = {
 	8,
 	{
@@ -468,7 +469,7 @@
 		}
 };
 
-// analog input ranges for 4020 board
+/* analog input ranges for 4020 board */
 static const struct comedi_lrange ai_ranges_4020 = {
 	2,
 	{
@@ -477,7 +478,7 @@
 		}
 };
 
-// analog output ranges
+/* analog output ranges */
 static const struct comedi_lrange ao_ranges_64xx = {
 	4,
 	{
@@ -543,40 +544,40 @@
 
 struct pcidas64_board {
 	const char *name;
-	int device_id;		// pci device id
-	int ai_se_chans;	// number of ai inputs in single-ended mode
-	int ai_bits;		// analog input resolution
-	int ai_speed;		// fastest conversion period in ns
+	int device_id;		/*  pci device id */
+	int ai_se_chans;	/*  number of ai inputs in single-ended mode */
+	int ai_bits;		/*  analog input resolution */
+	int ai_speed;		/*  fastest conversion period in ns */
 	const struct comedi_lrange *ai_range_table;
-	int ao_nchan;		// number of analog out channels
-	int ao_bits;		// analog output resolution
-	int ao_scan_speed;	// analog output speed (for a scan, not conversion)
+	int ao_nchan;		/*  number of analog out channels */
+	int ao_bits;		/*  analog output resolution */
+	int ao_scan_speed;	/*  analog output speed (for a scan, not conversion) */
 	const struct comedi_lrange *ao_range_table;
 	const int *ao_range_code;
 	const struct hw_fifo_info *const ai_fifo;
-	enum register_layout layout;	// different board families have slightly different registers
+	enum register_layout layout;	/*  different board families have slightly different registers */
 	unsigned has_8255:1;
 };
 
 static const struct hw_fifo_info ai_fifo_4020 = {
-      num_segments:2,
-      max_segment_length:0x8000,
-      sample_packing_ratio:2,
-      fifo_size_reg_mask:0x7f,
+	.num_segments = 2,
+	.max_segment_length = 0x8000,
+	.sample_packing_ratio = 2,
+	.fifo_size_reg_mask = 0x7f,
 };
 
 static const struct hw_fifo_info ai_fifo_64xx = {
-      num_segments:4,
-      max_segment_length:0x800,
-      sample_packing_ratio:1,
-      fifo_size_reg_mask:0x3f,
+	.num_segments = 4,
+	.max_segment_length = 0x800,
+	.sample_packing_ratio = 1,
+	.fifo_size_reg_mask = 0x3f,
 };
 
 static const struct hw_fifo_info ai_fifo_60xx = {
-      num_segments:4,
-      max_segment_length:0x800,
-      sample_packing_ratio:1,
-      fifo_size_reg_mask:0x7f,
+	.num_segments = 4,
+	.max_segment_length = 0x800,
+	.sample_packing_ratio = 1,
+	.fifo_size_reg_mask = 0x7f,
 };
 
 /* maximum number of dma transfers we will chain together into a ring
@@ -584,7 +585,7 @@
 #define MAX_AI_DMA_RING_COUNT (0x80000 / DMA_BUFFER_SIZE)
 #define MIN_AI_DMA_RING_COUNT (0x10000 / DMA_BUFFER_SIZE)
 #define AO_DMA_RING_COUNT (0x10000 / DMA_BUFFER_SIZE)
-static inline unsigned int ai_dma_ring_count(struct pcidas64_board * board)
+static inline unsigned int ai_dma_ring_count(struct pcidas64_board *board)
 {
 	if (board->layout == LAYOUT_4020)
 		return MAX_AI_DMA_RING_COUNT;
@@ -596,84 +597,84 @@
 
 static const struct pcidas64_board pcidas64_boards[] = {
 	{
-	      name:	"pci-das6402/16",
-	      device_id:0x1d,
-	      ai_se_chans:64,
-	      ai_bits:	16,
-	      ai_speed:5000,
-	      ao_nchan:2,
-	      ao_bits:	16,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ao_range_table:&ao_ranges_64xx,
-	      ao_range_code:ao_range_code_64xx,
-	      ai_fifo:	&ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das6402/16",
+	.device_id = 0x1d,
+	.ai_se_chans = 64,
+	.ai_bits = 16,
+	.ai_speed = 5000,
+	.ao_nchan = 2,
+	.ao_bits = 16,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ao_range_table = &ao_ranges_64xx,
+	.ao_range_code = ao_range_code_64xx,
+	.ai_fifo = &ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das6402/12",	// XXX check
-	      device_id:0x1e,
-	      ai_se_chans:64,
-	      ai_bits:	12,
-	      ai_speed:5000,
-	      ao_nchan:2,
-	      ao_bits:	12,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ao_range_table:&ao_ranges_64xx,
-	      ao_range_code:ao_range_code_64xx,
-	      ai_fifo:	&ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das6402/12",	/*  XXX check */
+	.device_id = 0x1e,
+	.ai_se_chans = 64,
+	.ai_bits = 12,
+	.ai_speed = 5000,
+	.ao_nchan = 2,
+	.ao_bits = 12,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ao_range_table = &ao_ranges_64xx,
+	.ao_range_code = ao_range_code_64xx,
+	.ai_fifo = &ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das64/m1/16",
-	      device_id:0x35,
-	      ai_se_chans:64,
-	      ai_bits:	16,
-	      ai_speed:1000,
-	      ao_nchan:2,
-	      ao_bits:	16,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ao_range_table:&ao_ranges_64xx,
-	      ao_range_code:ao_range_code_64xx,
-	      ai_fifo:	&ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das64/m1/16",
+	.device_id = 0x35,
+	.ai_se_chans = 64,
+	.ai_bits = 16,
+	.ai_speed = 1000,
+	.ao_nchan = 2,
+	.ao_bits = 16,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ao_range_table = &ao_ranges_64xx,
+	.ao_range_code = ao_range_code_64xx,
+	.ai_fifo = &ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das64/m2/16",
-	      device_id:0x36,
-	      ai_se_chans:64,
-	      ai_bits:	16,
-	      ai_speed:500,
-	      ao_nchan:2,
-	      ao_bits:	16,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ao_range_table:&ao_ranges_64xx,
-	      ao_range_code:ao_range_code_64xx,
-	      ai_fifo:	&ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das64/m2/16",
+	.device_id = 0x36,
+	.ai_se_chans = 64,
+	.ai_bits = 16,
+	.ai_speed = 500,
+	.ao_nchan = 2,
+	.ao_bits = 16,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ao_range_table = &ao_ranges_64xx,
+	.ao_range_code = ao_range_code_64xx,
+	.ai_fifo = &ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das64/m3/16",
-	      device_id:0x37,
-	      ai_se_chans:64,
-	      ai_bits:	16,
-	      ai_speed:333,
-	      ao_nchan:2,
-	      ao_bits:	16,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ao_range_table:&ao_ranges_64xx,
-	      ao_range_code:ao_range_code_64xx,
-	      ai_fifo:	&ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das64/m3/16",
+	.device_id = 0x37,
+	.ai_se_chans = 64,
+	.ai_bits = 16,
+	.ai_speed = 333,
+	.ao_nchan = 2,
+	.ao_bits = 16,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ao_range_table = &ao_ranges_64xx,
+	.ao_range_code = ao_range_code_64xx,
+	.ai_fifo = &ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 	{
 		.name = "pci-das6013",
@@ -691,334 +692,328 @@
 		.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6014",
-	      device_id:0x79,
-	      ai_se_chans:16,
-	      ai_bits:	16,
-	      ai_speed:5000,
-	      ao_nchan:2,
-	      ao_bits:	16,
-	      ao_scan_speed:100000,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_60xx,
-	      ao_range_table:&ao_ranges_60xx,
-	      ao_range_code:ao_range_code_60xx,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6014",
+	.device_id = 0x79,
+	.ai_se_chans = 16,
+	.ai_bits = 16,
+	.ai_speed = 5000,
+	.ao_nchan = 2,
+	.ao_bits = 16,
+	.ao_scan_speed = 100000,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_60xx,
+	.ao_range_table = &ao_ranges_60xx,
+	.ao_range_code = ao_range_code_60xx,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6023",
-	      device_id:0x5d,
-	      ai_se_chans:16,
-	      ai_bits:	12,
-	      ai_speed:5000,
-	      ao_nchan:0,
-	      ao_scan_speed:100000,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_60xx,
-	      ao_range_table:&ao_ranges_60xx,
-	      ao_range_code:ao_range_code_60xx,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:1,
+	.name = "pci-das6023",
+	.device_id = 0x5d,
+	.ai_se_chans = 16,
+	.ai_bits = 12,
+	.ai_speed = 5000,
+	.ao_nchan = 0,
+	.ao_scan_speed = 100000,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_60xx,
+	.ao_range_table = &ao_ranges_60xx,
+	.ao_range_code = ao_range_code_60xx,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das6025",
-	      device_id:0x5e,
-	      ai_se_chans:16,
-	      ai_bits:	12,
-	      ai_speed:5000,
-	      ao_nchan:2,
-	      ao_bits:	12,
-	      ao_scan_speed:100000,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_60xx,
-	      ao_range_table:&ao_ranges_60xx,
-	      ao_range_code:ao_range_code_60xx,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:1,
+	.name = "pci-das6025",
+	.device_id = 0x5e,
+	.ai_se_chans = 16,
+	.ai_bits = 12,
+	.ai_speed = 5000,
+	.ao_nchan = 2,
+	.ao_bits = 12,
+	.ao_scan_speed = 100000,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_60xx,
+	.ao_range_table = &ao_ranges_60xx,
+	.ao_range_code = ao_range_code_60xx,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das6030",
-	      device_id:0x5f,
-	      ai_se_chans:16,
-	      ai_bits:	16,
-	      ai_speed:10000,
-	      ao_nchan:2,
-	      ao_bits:	16,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_6030,
-	      ao_range_table:&ao_ranges_6030,
-	      ao_range_code:ao_range_code_6030,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6030",
+	.device_id = 0x5f,
+	.ai_se_chans = 16,
+	.ai_bits = 16,
+	.ai_speed = 10000,
+	.ao_nchan = 2,
+	.ao_bits = 16,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_6030,
+	.ao_range_table = &ao_ranges_6030,
+	.ao_range_code = ao_range_code_6030,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6031",
-	      device_id:0x60,
-	      ai_se_chans:64,
-	      ai_bits:	16,
-	      ai_speed:10000,
-	      ao_nchan:2,
-	      ao_bits:	16,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_6030,
-	      ao_range_table:&ao_ranges_6030,
-	      ao_range_code:ao_range_code_6030,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6031",
+	.device_id = 0x60,
+	.ai_se_chans = 64,
+	.ai_bits = 16,
+	.ai_speed = 10000,
+	.ao_nchan = 2,
+	.ao_bits = 16,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_6030,
+	.ao_range_table = &ao_ranges_6030,
+	.ao_range_code = ao_range_code_6030,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6032",
-	      device_id:0x61,
-	      ai_se_chans:16,
-	      ai_bits:	16,
-	      ai_speed:10000,
-	      ao_nchan:0,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_6030,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6032",
+	.device_id = 0x61,
+	.ai_se_chans = 16,
+	.ai_bits = 16,
+	.ai_speed = 10000,
+	.ao_nchan = 0,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_6030,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6033",
-	      device_id:0x62,
-	      ai_se_chans:64,
-	      ai_bits:	16,
-	      ai_speed:10000,
-	      ao_nchan:0,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_6030,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6033",
+	.device_id = 0x62,
+	.ai_se_chans = 64,
+	.ai_bits = 16,
+	.ai_speed = 10000,
+	.ao_nchan = 0,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_6030,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6034",
-	      device_id:0x63,
-	      ai_se_chans:16,
-	      ai_bits:	16,
-	      ai_speed:5000,
-	      ao_nchan:0,
-	      ao_scan_speed:0,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_60xx,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6034",
+	.device_id = 0x63,
+	.ai_se_chans = 16,
+	.ai_bits = 16,
+	.ai_speed = 5000,
+	.ao_nchan = 0,
+	.ao_scan_speed = 0,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_60xx,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6035",
-	      device_id:0x64,
-	      ai_se_chans:16,
-	      ai_bits:	16,
-	      ai_speed:5000,
-	      ao_nchan:2,
-	      ao_bits:	12,
-	      ao_scan_speed:100000,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_60xx,
-	      ao_range_table:&ao_ranges_60xx,
-	      ao_range_code:ao_range_code_60xx,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6035",
+	.device_id = 0x64,
+	.ai_se_chans = 16,
+	.ai_bits = 16,
+	.ai_speed = 5000,
+	.ao_nchan = 2,
+	.ao_bits = 12,
+	.ao_scan_speed = 100000,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_60xx,
+	.ao_range_table = &ao_ranges_60xx,
+	.ao_range_code = ao_range_code_60xx,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6036",
-	      device_id:0x6f,
-	      ai_se_chans:16,
-	      ai_bits:	16,
-	      ai_speed:5000,
-	      ao_nchan:2,
-	      ao_bits:	16,
-	      ao_scan_speed:100000,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_60xx,
-	      ao_range_table:&ao_ranges_60xx,
-	      ao_range_code:ao_range_code_60xx,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6036",
+	.device_id = 0x6f,
+	.ai_se_chans = 16,
+	.ai_bits = 16,
+	.ai_speed = 5000,
+	.ao_nchan = 2,
+	.ao_bits = 16,
+	.ao_scan_speed = 100000,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_60xx,
+	.ao_range_table = &ao_ranges_60xx,
+	.ao_range_code = ao_range_code_60xx,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6040",
-	      device_id:0x65,
-	      ai_se_chans:16,
-	      ai_bits:	12,
-	      ai_speed:2000,
-	      ao_nchan:2,
-	      ao_bits:	12,
-	      ao_scan_speed:1000,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_6052,
-	      ao_range_table:&ao_ranges_6030,
-	      ao_range_code:ao_range_code_6030,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6040",
+	.device_id = 0x65,
+	.ai_se_chans = 16,
+	.ai_bits = 12,
+	.ai_speed = 2000,
+	.ao_nchan = 2,
+	.ao_bits = 12,
+	.ao_scan_speed = 1000,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_6052,
+	.ao_range_table = &ao_ranges_6030,
+	.ao_range_code = ao_range_code_6030,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6052",
-	      device_id:0x66,
-	      ai_se_chans:16,
-	      ai_bits:	16,
-	      ai_speed:3333,
-	      ao_nchan:2,
-	      ao_bits:	16,
-	      ao_scan_speed:3333,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_6052,
-	      ao_range_table:&ao_ranges_6030,
-	      ao_range_code:ao_range_code_6030,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6052",
+	.device_id = 0x66,
+	.ai_se_chans = 16,
+	.ai_bits = 16,
+	.ai_speed = 3333,
+	.ao_nchan = 2,
+	.ao_bits = 16,
+	.ao_scan_speed = 3333,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_6052,
+	.ao_range_table = &ao_ranges_6030,
+	.ao_range_code = ao_range_code_6030,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6070",
-	      device_id:0x67,
-	      ai_se_chans:16,
-	      ai_bits:	12,
-	      ai_speed:800,
-	      ao_nchan:2,
-	      ao_bits:	12,
-	      ao_scan_speed:1000,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_6052,
-	      ao_range_table:&ao_ranges_6030,
-	      ao_range_code:ao_range_code_6030,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6070",
+	.device_id = 0x67,
+	.ai_se_chans = 16,
+	.ai_bits = 12,
+	.ai_speed = 800,
+	.ao_nchan = 2,
+	.ao_bits = 12,
+	.ao_scan_speed = 1000,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_6052,
+	.ao_range_table = &ao_ranges_6030,
+	.ao_range_code = ao_range_code_6030,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das6071",
-	      device_id:0x68,
-	      ai_se_chans:64,
-	      ai_bits:	12,
-	      ai_speed:800,
-	      ao_nchan:2,
-	      ao_bits:	12,
-	      ao_scan_speed:1000,
-	      layout:	LAYOUT_60XX,
-	      ai_range_table:&ai_ranges_6052,
-	      ao_range_table:&ao_ranges_6030,
-	      ao_range_code:ao_range_code_6030,
-	      ai_fifo:	&ai_fifo_60xx,
-	      has_8255:0,
+	.name = "pci-das6071",
+	.device_id = 0x68,
+	.ai_se_chans = 64,
+	.ai_bits = 12,
+	.ai_speed = 800,
+	.ao_nchan = 2,
+	.ao_bits = 12,
+	.ao_scan_speed = 1000,
+	.layout = LAYOUT_60XX,
+	.ai_range_table = &ai_ranges_6052,
+	.ao_range_table = &ao_ranges_6030,
+	.ao_range_code = ao_range_code_6030,
+	.ai_fifo = &ai_fifo_60xx,
+	.has_8255 = 0,
 		},
 	{
-	      name:	"pci-das4020/12",
-	      device_id:0x52,
-	      ai_se_chans:4,
-	      ai_bits:	12,
-	      ai_speed:50,
-	      ao_bits:	12,
-	      ao_nchan:2,
-	      ao_scan_speed:0,	// no hardware pacing on ao
-	      layout:	LAYOUT_4020,
-	      ai_range_table:&ai_ranges_4020,
-	      ao_range_table:&ao_ranges_4020,
-	      ao_range_code:ao_range_code_4020,
-	      ai_fifo:	&ai_fifo_4020,
-	      has_8255:1,
+	.name = "pci-das4020/12",
+	.device_id = 0x52,
+	.ai_se_chans = 4,
+	.ai_bits = 12,
+	.ai_speed = 50,
+	.ao_bits = 12,
+	.ao_nchan = 2,
+	.ao_scan_speed = 0,	/*  no hardware pacing on ao */
+	.layout = LAYOUT_4020,
+	.ai_range_table = &ai_ranges_4020,
+	.ao_range_table = &ao_ranges_4020,
+	.ao_range_code = ao_range_code_4020,
+	.ai_fifo = &ai_fifo_4020,
+	.has_8255 = 1,
 		},
 #if 0
 	{
-	      name:	"pci-das6402/16/jr",
-	      device_id:0	// XXX,
-	      ai_se_chans:64,
-	      ai_bits:	16,
-	      ai_speed:5000,
-	      ao_nchan:0,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ai_fifo:	ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das6402/16/jr",
+	.device_id = 0	/*  XXX, */
+	.ai_se_chans = 64,
+	.ai_bits = 16,
+	.ai_speed = 5000,
+	.ao_nchan = 0,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ai_fifo = ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das64/m1/16/jr",
-	      device_id:0	// XXX,
-	      ai_se_chans:64,
-	      ai_bits:	16,
-	      ai_speed:1000,
-	      ao_nchan:0,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ai_fifo:	ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das64/m1/16/jr",
+	.device_id = 0	/*  XXX, */
+	.ai_se_chans = 64,
+	.ai_bits = 16,
+	.ai_speed = 1000,
+	.ao_nchan = 0,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ai_fifo = ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das64/m2/16/jr",
-	      device_id:0	// XXX,
-	      ai_se_chans:64,
-	      ai_bits:	16,
-	      ai_speed:500,
-	      ao_nchan:0,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ai_fifo:	ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das64/m2/16/jr",
+	.device_id = 0	/*  XXX, */
+	.ai_se_chans = 64,
+	.ai_bits = 16,
+	.ai_speed = 500,
+	.ao_nchan = 0,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ai_fifo = ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das64/m3/16/jr",
-	      device_id:0	// XXX,
-	      ai_se_chans:64,
-	      ai_bits:	16,
-	      ai_speed:333,
-	      ao_nchan:0,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ai_fifo:	ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das64/m3/16/jr",
+	.device_id = 0	/*  XXX, */
+	.ai_se_chans = 64,
+	.ai_bits = 16,
+	.ai_speed = 333,
+	.ao_nchan = 0,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ai_fifo = ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das64/m1/14",
-	      device_id:0,	// XXX
-	      ai_se_chans:64,
-	      ai_bits:	14,
-	      ai_speed:1000,
-	      ao_nchan:2,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ai_fifo:	ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das64/m1/14",
+	.device_id = 0,	/*  XXX */
+	.ai_se_chans = 64,
+	.ai_bits = 14,
+	.ai_speed = 1000,
+	.ao_nchan = 2,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ai_fifo = ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das64/m2/14",
-	      device_id:0,	// XXX
-	      ai_se_chans:64,
-	      ai_bits:	14,
-	      ai_speed:500,
-	      ao_nchan:2,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ai_fifo:	ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das64/m2/14",
+	.device_id = 0,	/*  XXX */
+	.ai_se_chans = 64,
+	.ai_bits = 14,
+	.ai_speed = 500,
+	.ao_nchan = 2,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ai_fifo = ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 	{
-	      name:	"pci-das64/m3/14",
-	      device_id:0,	// XXX
-	      ai_se_chans:64,
-	      ai_bits:	14,
-	      ai_speed:333,
-	      ao_nchan:2,
-	      ao_scan_speed:10000,
-	      layout:	LAYOUT_64XX,
-	      ai_range_table:&ai_ranges_64xx,
-	      ai_fifo:	ai_fifo_64xx,
-	      has_8255:1,
+	.name = "pci-das64/m3/14",
+	.device_id = 0,	/*  XXX */
+	.ai_se_chans = 64,
+	.ai_bits = 14,
+	.ai_speed = 333,
+	.ao_nchan = 2,
+	.ao_scan_speed = 10000,
+	.layout = LAYOUT_64XX,
+	.ai_range_table = &ai_ranges_64xx,
+	.ai_fifo = ai_fifo_64xx,
+	.has_8255 = 1,
 		},
 #endif
 };
 
-// Number of boards in cb_pcidas_boards
-static inline unsigned int num_boards(void)
-{
-	return sizeof(pcidas64_boards) / sizeof(struct pcidas64_board);
-}
-
 static DEFINE_PCI_DEVICE_TABLE(pcidas64_pci_table) = {
 	{PCI_VENDOR_ID_COMPUTERBOARDS, 0x001d, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
 	{PCI_VENDOR_ID_COMPUTERBOARDS, 0x001e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
@@ -1049,7 +1044,7 @@
 	return (struct pcidas64_board *) dev->board_ptr;
 }
 
-static inline unsigned short se_diff_bit_6xxx(struct comedi_device * dev,
+static inline unsigned short se_diff_bit_6xxx(struct comedi_device *dev,
 	int use_differential)
 {
 	if ((board(dev)->layout == LAYOUT_64XX && !use_differential) ||
@@ -1060,50 +1055,50 @@
 };
 
 struct ext_clock_info {
-	unsigned int divisor;	// master clock divisor to use for scans with external master clock
-	unsigned int chanspec;	// chanspec for master clock input when used as scan begin src
+	unsigned int divisor;	/*  master clock divisor to use for scans with external master clock */
+	unsigned int chanspec;	/*  chanspec for master clock input when used as scan begin src */
 };
 
 /* this structure is for data unique to this hardware driver. */
 struct pcidas64_private {
 
-	struct pci_dev *hw_dev;	// pointer to board's pci_dev struct
-	// base addresses (physical)
+	struct pci_dev *hw_dev;	/*  pointer to board's pci_dev struct */
+	/*  base addresses (physical) */
 	resource_size_t plx9080_phys_iobase;
 	resource_size_t main_phys_iobase;
 	resource_size_t dio_counter_phys_iobase;
-	// base addresses (ioremapped)
+	/*  base addresses (ioremapped) */
 	void *plx9080_iobase;
 	void *main_iobase;
 	void *dio_counter_iobase;
-	// local address (used by dma controller)
+	/*  local address (used by dma controller) */
 	uint32_t local0_iobase;
 	uint32_t local1_iobase;
-	volatile unsigned int ai_count;	// number of analog input samples remaining
-	uint16_t *ai_buffer[MAX_AI_DMA_RING_COUNT];	// dma buffers for analog input
-	dma_addr_t ai_buffer_bus_addr[MAX_AI_DMA_RING_COUNT];	// physical addresses of ai dma buffers
-	struct plx_dma_desc *ai_dma_desc;	// array of ai dma descriptors read by plx9080, allocated to get proper alignment
-	dma_addr_t ai_dma_desc_bus_addr;	// physical address of ai dma descriptor array
-	volatile unsigned int ai_dma_index;	// index of the ai dma descriptor/buffer that is currently being used
-	uint16_t *ao_buffer[AO_DMA_RING_COUNT];	// dma buffers for analog output
-	dma_addr_t ao_buffer_bus_addr[AO_DMA_RING_COUNT];	// physical addresses of ao dma buffers
+	volatile unsigned int ai_count;	/*  number of analog input samples remaining */
+	uint16_t *ai_buffer[MAX_AI_DMA_RING_COUNT];	/*  dma buffers for analog input */
+	dma_addr_t ai_buffer_bus_addr[MAX_AI_DMA_RING_COUNT];	/*  physical addresses of ai dma buffers */
+	struct plx_dma_desc *ai_dma_desc;	/*  array of ai dma descriptors read by plx9080, allocated to get proper alignment */
+	dma_addr_t ai_dma_desc_bus_addr;	/*  physical address of ai dma descriptor array */
+	volatile unsigned int ai_dma_index;	/*  index of the ai dma descriptor/buffer that is currently being used */
+	uint16_t *ao_buffer[AO_DMA_RING_COUNT];	/*  dma buffers for analog output */
+	dma_addr_t ao_buffer_bus_addr[AO_DMA_RING_COUNT];	/*  physical addresses of ao dma buffers */
 	struct plx_dma_desc *ao_dma_desc;
 	dma_addr_t ao_dma_desc_bus_addr;
-	volatile unsigned int ao_dma_index;	// keeps track of buffer where the next ao sample should go
-	volatile unsigned long ao_count;	// number of analog output samples remaining
-	volatile unsigned int ao_value[2];	// remember what the analog outputs are set to, to allow readback
-	unsigned int hw_revision;	// stc chip hardware revision number
-	volatile unsigned int intr_enable_bits;	// last bits sent to INTR_ENABLE_REG register
-	volatile uint16_t adc_control1_bits;	// last bits sent to ADC_CONTROL1_REG register
-	volatile uint16_t fifo_size_bits;	// last bits sent to FIFO_SIZE_REG register
-	volatile uint16_t hw_config_bits;	// last bits sent to HW_CONFIG_REG register
+	volatile unsigned int ao_dma_index;	/*  keeps track of buffer where the next ao sample should go */
+	volatile unsigned long ao_count;	/*  number of analog output samples remaining */
+	volatile unsigned int ao_value[2];	/*  remember what the analog outputs are set to, to allow readback */
+	unsigned int hw_revision;	/*  stc chip hardware revision number */
+	volatile unsigned int intr_enable_bits;	/*  last bits sent to INTR_ENABLE_REG register */
+	volatile uint16_t adc_control1_bits;	/*  last bits sent to ADC_CONTROL1_REG register */
+	volatile uint16_t fifo_size_bits;	/*  last bits sent to FIFO_SIZE_REG register */
+	volatile uint16_t hw_config_bits;	/*  last bits sent to HW_CONFIG_REG register */
 	volatile uint16_t dac_control1_bits;
-	volatile uint32_t plx_control_bits;	// last bits written to plx9080 control register
-	volatile uint32_t plx_intcsr_bits;	// last bits written to plx interrupt control and status register
-	volatile int calibration_source;	// index of calibration source readable through ai ch0
-	volatile uint8_t i2c_cal_range_bits;	// bits written to i2c calibration/range register
-	volatile unsigned int ext_trig_falling;	// configure digital triggers to trigger on falling edge
-	// states of various devices stored to enable read-back
+	volatile uint32_t plx_control_bits;	/*  last bits written to plx9080 control register */
+	volatile uint32_t plx_intcsr_bits;	/*  last bits written to plx interrupt control and status register */
+	volatile int calibration_source;	/*  index of calibration source readable through ai ch0 */
+	volatile uint8_t i2c_cal_range_bits;	/*  bits written to i2c calibration/range register */
+	volatile unsigned int ext_trig_falling;	/*  configure digital triggers to trigger on falling edge */
+	/*  states of various devices stored to enable read-back */
 	unsigned int ad8402_state[2];
 	unsigned int caldac_state[8];
 	volatile short ai_cmd_running;
@@ -1127,82 +1122,82 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int detach(struct comedi_device * dev);
+static int attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int detach(struct comedi_device *dev);
 static struct comedi_driver driver_cb_pcidas = {
-      driver_name:"cb_pcidas64",
-      module:THIS_MODULE,
-      attach:attach,
-      detach:detach,
+	.driver_name = "cb_pcidas64",
+	.module = THIS_MODULE,
+	.attach = attach,
+	.detach = detach,
 };
 
-static int ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ai_config_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ao_readback_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int ao_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int ao_inttrig(struct comedi_device * dev, struct comedi_subdevice * subdev,
+static int ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ai_config_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ao_readback_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int ao_inttrig(struct comedi_device *dev, struct comedi_subdevice *subdev,
 	unsigned int trig_num);
-static int ao_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static irqreturn_t handle_interrupt(int irq, void *d PT_REGS_ARG);
-static int ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static int ao_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
+static int ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static irqreturn_t handle_interrupt(int irq, void *d);
+static int ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static int ao_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
 static int dio_callback(int dir, int port, int data, unsigned long arg);
 static int dio_callback_4020(int dir, int port, int data, unsigned long arg);
-static int di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dio_60xx_config_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dio_60xx_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int calib_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int calib_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ad8402_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static void ad8402_write(struct comedi_device * dev, unsigned int channel,
+static int di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dio_60xx_config_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dio_60xx_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int calib_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int calib_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ad8402_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static void ad8402_write(struct comedi_device *dev, unsigned int channel,
 	unsigned int value);
-static int ad8402_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int eeprom_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static void check_adc_timing(struct comedi_device * dev, struct comedi_cmd * cmd);
+static int ad8402_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int eeprom_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static void check_adc_timing(struct comedi_device *dev, struct comedi_cmd *cmd);
 static unsigned int get_divisor(unsigned int ns, unsigned int flags);
-static void i2c_write(struct comedi_device * dev, unsigned int address,
-	const uint8_t * data, unsigned int length);
-static void caldac_write(struct comedi_device * dev, unsigned int channel,
+static void i2c_write(struct comedi_device *dev, unsigned int address,
+	const uint8_t *data, unsigned int length);
+static void caldac_write(struct comedi_device *dev, unsigned int channel,
 	unsigned int value);
-static int caldac_8800_write(struct comedi_device * dev, unsigned int address,
+static int caldac_8800_write(struct comedi_device *dev, unsigned int address,
 	uint8_t value);
-//static int dac_1590_write(struct comedi_device *dev, unsigned int dac_a, unsigned int dac_b);
-static int caldac_i2c_write(struct comedi_device * dev, unsigned int caldac_channel,
+/* static int dac_1590_write(struct comedi_device *dev, unsigned int dac_a, unsigned int dac_b); */
+static int caldac_i2c_write(struct comedi_device *dev, unsigned int caldac_channel,
 	unsigned int value);
-static void abort_dma(struct comedi_device * dev, unsigned int channel);
-static void disable_plx_interrupts(struct comedi_device * dev);
-static int set_ai_fifo_size(struct comedi_device * dev, unsigned int num_samples);
-static unsigned int ai_fifo_size(struct comedi_device * dev);
-static int set_ai_fifo_segment_length(struct comedi_device * dev,
+static void abort_dma(struct comedi_device *dev, unsigned int channel);
+static void disable_plx_interrupts(struct comedi_device *dev);
+static int set_ai_fifo_size(struct comedi_device *dev, unsigned int num_samples);
+static unsigned int ai_fifo_size(struct comedi_device *dev);
+static int set_ai_fifo_segment_length(struct comedi_device *dev,
 	unsigned int num_entries);
-static void disable_ai_pacing(struct comedi_device * dev);
-static void disable_ai_interrupts(struct comedi_device * dev);
-static void enable_ai_interrupts(struct comedi_device * dev, const struct comedi_cmd * cmd);
+static void disable_ai_pacing(struct comedi_device *dev);
+static void disable_ai_interrupts(struct comedi_device *dev);
+static void enable_ai_interrupts(struct comedi_device *dev, const struct comedi_cmd *cmd);
 static unsigned int get_ao_divisor(unsigned int ns, unsigned int flags);
-static void load_ao_dma(struct comedi_device * dev, const struct comedi_cmd * cmd);
+static void load_ao_dma(struct comedi_device *dev, const struct comedi_cmd *cmd);
 
 COMEDI_PCI_INITCLEANUP(driver_cb_pcidas, pcidas64_pci_table);
 
-static unsigned int ai_range_bits_6xxx(const struct comedi_device * dev,
+static unsigned int ai_range_bits_6xxx(const struct comedi_device *dev,
 	unsigned int range_index)
 {
 	const struct comedi_krange *range =
@@ -1246,7 +1241,7 @@
 	return bits;
 }
 
-static unsigned int hw_revision(const struct comedi_device * dev,
+static unsigned int hw_revision(const struct comedi_device *dev,
 	uint16_t hw_status_bits)
 {
 	if (board(dev)->layout == LAYOUT_4020)
@@ -1255,7 +1250,7 @@
 	return (hw_status_bits >> 12) & 0xf;
 }
 
-static void set_dac_range_bits(struct comedi_device * dev, volatile uint16_t * bits,
+static void set_dac_range_bits(struct comedi_device *dev, volatile uint16_t *bits,
 	unsigned int channel, unsigned int range)
 {
 	unsigned int code = board(dev)->ao_range_code[range];
@@ -1269,13 +1264,13 @@
 	*bits |= code << (2 * channel);
 };
 
-static inline int ao_cmd_is_supported(const struct pcidas64_board * board)
+static inline int ao_cmd_is_supported(const struct pcidas64_board *board)
 {
 	return board->ao_nchan && board->layout != LAYOUT_4020;
 }
 
-// initialize plx9080 chip
-static void init_plx9080(struct comedi_device * dev)
+/* initialize plx9080 chip */
+static void init_plx9080(struct comedi_device *dev)
 {
 	uint32_t bits;
 	void *plx_iobase = priv(dev)->plx9080_iobase;
@@ -1283,7 +1278,7 @@
 	priv(dev)->plx_control_bits =
 		readl(priv(dev)->plx9080_iobase + PLX_CONTROL_REG);
 
-	// plx9080 dump
+	/*  plx9080 dump */
 	DEBUG_PRINT(" plx interrupt status 0x%x\n",
 		readl(plx_iobase + PLX_INTRCS_REG));
 	DEBUG_PRINT(" plx id bits 0x%x\n", readl(plx_iobase + PLX_ID_REG));
@@ -1327,35 +1322,35 @@
 	abort_dma(dev, 0);
 	abort_dma(dev, 1);
 
-	// configure dma0 mode
+	/*  configure dma0 mode */
 	bits = 0;
-	// enable ready input, not sure if this is necessary
+	/*  enable ready input, not sure if this is necessary */
 	bits |= PLX_DMA_EN_READYIN_BIT;
-	// enable bterm, not sure if this is necessary
+	/*  enable bterm, not sure if this is necessary */
 	bits |= PLX_EN_BTERM_BIT;
-	// enable dma chaining
+	/*  enable dma chaining */
 	bits |= PLX_EN_CHAIN_BIT;
-	// enable interrupt on dma done (probably don't need this, since chain never finishes)
+	/*  enable interrupt on dma done (probably don't need this, since chain never finishes) */
 	bits |= PLX_EN_DMA_DONE_INTR_BIT;
-	// don't increment local address during transfers (we are transferring from a fixed fifo register)
+	/*  don't increment local address during transfers (we are transferring from a fixed fifo register) */
 	bits |= PLX_LOCAL_ADDR_CONST_BIT;
-	// route dma interrupt to pci bus
+	/*  route dma interrupt to pci bus */
 	bits |= PLX_DMA_INTR_PCI_BIT;
-	// enable demand mode
+	/*  enable demand mode */
 	bits |= PLX_DEMAND_MODE_BIT;
-	// enable local burst mode
+	/*  enable local burst mode */
 	bits |= PLX_DMA_LOCAL_BURST_EN_BIT;
-	// 4020 uses 32 bit dma
+	/*  4020 uses 32 bit dma */
 	if (board(dev)->layout == LAYOUT_4020) {
 		bits |= PLX_LOCAL_BUS_32_WIDE_BITS;
-	} else {		// localspace0 bus is 16 bits wide
+	} else {		/*  localspace0 bus is 16 bits wide */
 		bits |= PLX_LOCAL_BUS_16_WIDE_BITS;
 	}
 	writel(bits, plx_iobase + PLX_DMA1_MODE_REG);
 	if (ao_cmd_is_supported(board(dev)))
 		writel(bits, plx_iobase + PLX_DMA0_MODE_REG);
 
-	// enable interrupts on plx 9080
+	/*  enable interrupts on plx 9080 */
 	priv(dev)->plx_intcsr_bits |=
 		ICS_AERR | ICS_PERR | ICS_PIE | ICS_PLIE | ICS_PAIE | ICS_LIE |
 		ICS_DMA0_E | ICS_DMA1_E;
@@ -1365,7 +1360,7 @@
 
 /* Allocate and initialize the subdevice structures.
  */
-static int setup_subdevices(struct comedi_device * dev)
+static int setup_subdevices(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s;
 	void *dio_8255_iobase;
@@ -1396,9 +1391,9 @@
 	if (board(dev)->layout == LAYOUT_4020) {
 		unsigned int i;
 		uint8_t data;
-		// set adc to read from inputs (not internal calibration sources)
+		/*  set adc to read from inputs (not internal calibration sources) */
 		priv(dev)->i2c_cal_range_bits = adc_src_4020_bits(4);
-		// set channels to +-5 volt input ranges
+		/*  set channels to +-5 volt input ranges */
 		for (i = 0; i < s->n_chan; i++)
 			priv(dev)->i2c_cal_range_bits |= attenuate_bit(i);
 		data = priv(dev)->i2c_cal_range_bits;
@@ -1428,7 +1423,7 @@
 		s->type = COMEDI_SUBD_UNUSED;
 	}
 
-	// digital input
+	/*  digital input */
 	s = dev->subdevices + 2;
 	if (board(dev)->layout == LAYOUT_64XX) {
 		s->type = COMEDI_SUBD_DI;
@@ -1440,7 +1435,7 @@
 	} else
 		s->type = COMEDI_SUBD_UNUSED;
 
-	// digital output
+	/*  digital output */
 	if (board(dev)->layout == LAYOUT_64XX) {
 		s = dev->subdevices + 3;
 		s->type = COMEDI_SUBD_DO;
@@ -1469,7 +1464,7 @@
 	} else
 		s->type = COMEDI_SUBD_UNUSED;
 
-	// 8 channel dio for 60xx
+	/*  8 channel dio for 60xx */
 	s = dev->subdevices + 5;
 	if (board(dev)->layout == LAYOUT_60XX) {
 		s->type = COMEDI_SUBD_DIO;
@@ -1482,7 +1477,7 @@
 	} else
 		s->type = COMEDI_SUBD_UNUSED;
 
-	// caldac
+	/*  caldac */
 	s = dev->subdevices + 6;
 	s->type = COMEDI_SUBD_CALIB;
 	s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
@@ -1496,7 +1491,7 @@
 	for (i = 0; i < s->n_chan; i++)
 		caldac_write(dev, i, s->maxdata / 2);
 
-	// 2 channel ad8402 potentiometer
+	/*  2 channel ad8402 potentiometer */
 	s = dev->subdevices + 7;
 	if (board(dev)->layout == LAYOUT_64XX) {
 		s->type = COMEDI_SUBD_CALIB;
@@ -1510,7 +1505,7 @@
 	} else
 		s->type = COMEDI_SUBD_UNUSED;
 
-	//serial EEPROM, if present
+	/* serial EEPROM, if present */
 	s = dev->subdevices + 8;
 	if (readl(priv(dev)->plx9080_iobase + PLX_CONTROL_REG) & CTL_EECHK) {
 		s->type = COMEDI_SUBD_MEMORY;
@@ -1521,34 +1516,34 @@
 	} else
 		s->type = COMEDI_SUBD_UNUSED;
 
-	// user counter subd XXX
+	/*  user counter subd XXX */
 	s = dev->subdevices + 9;
 	s->type = COMEDI_SUBD_UNUSED;
 
 	return 0;
 }
 
-static void disable_plx_interrupts(struct comedi_device * dev)
+static void disable_plx_interrupts(struct comedi_device *dev)
 {
 	priv(dev)->plx_intcsr_bits = 0;
 	writel(priv(dev)->plx_intcsr_bits,
 		priv(dev)->plx9080_iobase + PLX_INTRCS_REG);
 }
 
-static void init_stc_registers(struct comedi_device * dev)
+static void init_stc_registers(struct comedi_device *dev)
 {
 	uint16_t bits;
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 
-	// bit should be set for 6025, although docs say boards with <= 16 chans should be cleared XXX
+	/*  bit should be set for 6025, although docs say boards with <= 16 chans should be cleared XXX */
 	if (1)
 		priv(dev)->adc_control1_bits |= ADC_QUEUE_CONFIG_BIT;
 	writew(priv(dev)->adc_control1_bits,
 		priv(dev)->main_iobase + ADC_CONTROL1_REG);
 
-	// 6402/16 manual says this register must be initialized to 0xff?
+	/*  6402/16 manual says this register must be initialized to 0xff? */
 	writew(0xff, priv(dev)->main_iobase + ADC_SAMPLE_INTERVAL_UPPER_REG);
 
 	bits = SLOW_DAC_BIT | DMA_CH_SELECT_BIT;
@@ -1561,9 +1556,9 @@
 	writew(0, priv(dev)->main_iobase + DAQ_SYNC_REG);
 	writew(0, priv(dev)->main_iobase + CALIBRATION_REG);
 
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// set fifos to maximum size
+	/*  set fifos to maximum size */
 	priv(dev)->fifo_size_bits |= DAC_FIFO_BITS;
 	set_ai_fifo_segment_length(dev,
 		board(dev)->ai_fifo->max_segment_length);
@@ -1577,11 +1572,11 @@
 	disable_ai_pacing(dev);
 };
 
-int alloc_and_init_dma_members(struct comedi_device * dev)
+int alloc_and_init_dma_members(struct comedi_device *dev)
 {
 	int i;
 
-	// alocate pci dma buffers
+	/*  alocate pci dma buffers */
 	for (i = 0; i < ai_dma_ring_count(board(dev)); i++) {
 		priv(dev)->ai_buffer[i] =
 			pci_alloc_consistent(priv(dev)->hw_dev, DMA_BUFFER_SIZE,
@@ -1601,7 +1596,7 @@
 			}
 		}
 	}
-	// allocate dma descriptors
+	/*  allocate dma descriptors */
 	priv(dev)->ai_dma_desc =
 		pci_alloc_consistent(priv(dev)->hw_dev,
 		sizeof(struct plx_dma_desc) * ai_dma_ring_count(board(dev)),
@@ -1622,7 +1617,7 @@
 		DEBUG_PRINT("ao dma descriptors start at bus addr 0x%x\n",
 			priv(dev)->ao_dma_desc_bus_addr);
 	}
-	// initialize dma descriptors
+	/*  initialize dma descriptors */
 	for (i = 0; i < ai_dma_ring_count(board(dev)); i++) {
 		priv(dev)->ai_dma_desc[i].pci_start_addr =
 			cpu_to_le32(priv(dev)->ai_buffer_bus_addr[i]);
@@ -1663,7 +1658,7 @@
 	return 0;
 }
 
-static inline void warn_external_queue(struct comedi_device * dev)
+static inline void warn_external_queue(struct comedi_device *dev)
 {
 	comedi_error(dev,
 		"AO command and AI external channel queue cannot be used simultaneously.");
@@ -1697,16 +1692,16 @@
 	for (pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL);
 		pcidev != NULL;
 		pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pcidev)) {
-		// is it not a computer boards card?
+		/*  is it not a computer boards card? */
 		if (pcidev->vendor != PCI_VENDOR_ID_COMPUTERBOARDS)
 			continue;
-		// loop through cards supported by this driver
-		for (index = 0; index < num_boards(); index++) {
+		/*  loop through cards supported by this driver */
+		for (index = 0; index < ARRAY_SIZE(pcidas64_boards); index++) {
 			if (pcidas64_boards[index].device_id != pcidev->device)
 				continue;
-			// was a particular bus/slot requested?
+			/*  was a particular bus/slot requested? */
 			if (it->options[0] || it->options[1]) {
-				// are we on the wrong bus/slot?
+				/*  are we on the wrong bus/slot? */
 				if (pcidev->bus->number != it->options[0] ||
 					PCI_SLOT(pcidev->devfn) !=
 					it->options[1]) {
@@ -1736,7 +1731,7 @@
 	}
 	pci_set_master(pcidev);
 
-	//Initialize dev->board_name
+	/* Initialize dev->board_name */
 	dev->board_name = board(dev)->name;
 
 	priv(dev)->plx9080_phys_iobase =
@@ -1746,7 +1741,7 @@
 	priv(dev)->dio_counter_phys_iobase =
 		pci_resource_start(pcidev, DIO_COUNTER_BADDRINDEX);
 
-	// remap, won't work with 2.0 kernels but who cares
+	/*  remap, won't work with 2.0 kernels but who cares */
 	priv(dev)->plx9080_iobase = ioremap(priv(dev)->plx9080_phys_iobase,
 		pci_resource_len(pcidev, PLX9080_BADDRINDEX));
 	priv(dev)->main_iobase = ioremap(priv(dev)->main_phys_iobase,
@@ -1766,7 +1761,7 @@
 	DEBUG_PRINT(" diocounter remapped to 0x%p\n",
 		priv(dev)->dio_counter_iobase);
 
-	// figure out what local addresses are
+	/*  figure out what local addresses are */
 	local_range =
 		readl(priv(dev)->plx9080_iobase +
 		PLX_LAS0RNG_REG) & LRNG_MEM_MASK;
@@ -1798,8 +1793,8 @@
 	printk(" stc hardware revision %i\n", priv(dev)->hw_revision);
 	init_plx9080(dev);
 	init_stc_registers(dev);
-	// get irq
-	if (comedi_request_irq(pcidev->irq, handle_interrupt, IRQF_SHARED,
+	/*  get irq */
+	if (request_irq(pcidev->irq, handle_interrupt, IRQF_SHARED,
 			"cb_pcidas64", dev)) {
 		printk(" unable to allocate irq %u\n", pcidev->irq);
 		return -EINVAL;
@@ -1823,14 +1818,14 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int detach(struct comedi_device * dev)
+static int detach(struct comedi_device *dev)
 {
 	unsigned int i;
 
 	printk("comedi%d: cb_pcidas: remove\n", dev->minor);
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	if (priv(dev)) {
 		if (priv(dev)->hw_dev) {
 			if (priv(dev)->plx9080_iobase) {
@@ -1841,7 +1836,7 @@
 				iounmap((void *)priv(dev)->main_iobase);
 			if (priv(dev)->dio_counter_iobase)
 				iounmap((void *)priv(dev)->dio_counter_iobase);
-			// free pci dma buffers
+			/*  free pci dma buffers */
 			for (i = 0; i < ai_dma_ring_count(board(dev)); i++) {
 				if (priv(dev)->ai_buffer[i])
 					pci_free_consistent(priv(dev)->hw_dev,
@@ -1858,7 +1853,7 @@
 						priv(dev)->
 						ao_buffer_bus_addr[i]);
 			}
-			// free dma descriptors
+			/*  free dma descriptors */
 			if (priv(dev)->ai_dma_desc)
 				pci_free_consistent(priv(dev)->hw_dev,
 					sizeof(struct plx_dma_desc) *
@@ -1883,8 +1878,8 @@
 	return 0;
 }
 
-static int ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int bits = 0, n, i;
 	unsigned int channel, range, aref;
@@ -1896,26 +1891,26 @@
 	range = CR_RANGE(insn->chanspec);
 	aref = CR_AREF(insn->chanspec);
 
-	// disable card's analog input interrupt sources and pacing
-	// 4020 generates dac done interrupts even though they are disabled
+	/*  disable card's analog input interrupt sources and pacing */
+	/*  4020 generates dac done interrupts even though they are disabled */
 	disable_ai_pacing(dev);
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	if (insn->chanspec & CR_ALT_FILTER)
 		priv(dev)->adc_control1_bits |= ADC_DITHER_BIT;
 	else
 		priv(dev)->adc_control1_bits &= ~ADC_DITHER_BIT;
 	writew(priv(dev)->adc_control1_bits,
 		priv(dev)->main_iobase + ADC_CONTROL1_REG);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	if (board(dev)->layout != LAYOUT_4020) {
-		// use internal queue
+		/*  use internal queue */
 		priv(dev)->hw_config_bits &= ~EXT_QUEUE_BIT;
 		writew(priv(dev)->hw_config_bits,
 			priv(dev)->main_iobase + HW_CONFIG_REG);
 
-		// ALT_SOURCE is internal calibration reference
+		/*  ALT_SOURCE is internal calibration reference */
 		if (insn->chanspec & CR_ALT_SOURCE) {
 			unsigned int cal_en_bit;
 
@@ -1924,27 +1919,27 @@
 				cal_en_bit = CAL_EN_60XX_BIT;
 			else
 				cal_en_bit = CAL_EN_64XX_BIT;
-			// select internal reference source to connect to channel 0
+			/*  select internal reference source to connect to channel 0 */
 			writew(cal_en_bit | adc_src_bits(priv(dev)->
 					calibration_source),
 				priv(dev)->main_iobase + CALIBRATION_REG);
 		} else {
-			// make sure internal calibration source is turned off
+			/*  make sure internal calibration source is turned off */
 			writew(0, priv(dev)->main_iobase + CALIBRATION_REG);
 		}
-		// load internal queue
+		/*  load internal queue */
 		bits = 0;
-		// set gain
+		/*  set gain */
 		bits |= ai_range_bits_6xxx(dev, CR_RANGE(insn->chanspec));
-		// set single-ended / differential
+		/*  set single-ended / differential */
 		bits |= se_diff_bit_6xxx(dev, aref == AREF_DIFF);
 		if (aref == AREF_COMMON)
 			bits |= ADC_COMMON_BIT;
 		bits |= adc_chan_bits(channel);
-		// set stop channel
+		/*  set stop channel */
 		writew(adc_chan_bits(channel),
 			priv(dev)->main_iobase + ADC_QUEUE_HIGH_REG);
-		// set start channel, and rest of settings
+		/*  set start channel, and rest of settings */
 		writew(bits, priv(dev)->main_iobase + ADC_QUEUE_LOAD_REG);
 	} else {
 		uint8_t old_cal_range_bits = priv(dev)->i2c_cal_range_bits;
@@ -1955,16 +1950,16 @@
 			priv(dev)->i2c_cal_range_bits |=
 				adc_src_4020_bits(priv(dev)->
 				calibration_source);
-		} else {	//select BNC inputs
+		} else {	/* select BNC inputs */
 			priv(dev)->i2c_cal_range_bits |= adc_src_4020_bits(4);
 		}
-		// select range
+		/*  select range */
 		if (range == 0)
 			priv(dev)->i2c_cal_range_bits |= attenuate_bit(channel);
 		else
 			priv(dev)->i2c_cal_range_bits &=
 				~attenuate_bit(channel);
-		// update calibration/range i2c register only if necessary, as it is very slow
+		/*  update calibration/range i2c register only if necessary, as it is very slow */
 		if (old_cal_range_bits != priv(dev)->i2c_cal_range_bits) {
 			uint8_t i2c_data = priv(dev)->i2c_cal_range_bits;
 			i2c_write(dev, RANGE_CAL_I2C_ADDR, &i2c_data,
@@ -1981,14 +1976,14 @@
 
 	for (n = 0; n < insn->n; n++) {
 
-		// clear adc buffer (inside loop for 4020 sake)
+		/*  clear adc buffer (inside loop for 4020 sake) */
 		writew(0, priv(dev)->main_iobase + ADC_BUFFER_CLEAR_REG);
 
 		/* trigger conversion, bits sent only matter for 4020 */
 		writew(adc_convert_chan_4020_bits(CR_CHAN(insn->chanspec)),
 			priv(dev)->main_iobase + ADC_CONVERT_REG);
 
-		// wait for data
+		/*  wait for data */
 		for (i = 0; i < timeout; i++) {
 			bits = readw(priv(dev)->main_iobase + HW_STATUS_REG);
 			DEBUG_PRINT(" pipe bits 0x%x\n", pipe_full_bits(bits));
@@ -2000,12 +1995,12 @@
 				if (pipe_full_bits(bits))
 					break;
 			}
-			comedi_udelay(1);
+			udelay(1);
 		}
 		DEBUG_PRINT(" looped %i times waiting for data\n", i);
 		if (i == timeout) {
 			comedi_error(dev, " analog input read insn timed out");
-			rt_printk(" status 0x%x\n", bits);
+			printk(" status 0x%x\n", bits);
 			return -ETIME;
 		}
 		if (board(dev)->layout == LAYOUT_4020)
@@ -2020,7 +2015,7 @@
 	return n;
 }
 
-static int ai_config_calibration_source(struct comedi_device * dev, unsigned int * data)
+static int ai_config_calibration_source(struct comedi_device *dev, unsigned int *data)
 {
 	unsigned int source = data[1];
 	int num_calibration_sources;
@@ -2040,7 +2035,7 @@
 	return 2;
 }
 
-static int ai_config_block_size(struct comedi_device * dev, unsigned int * data)
+static int ai_config_block_size(struct comedi_device *dev, unsigned int *data)
 {
 	int fifo_size;
 	const struct hw_fifo_info *const fifo = board(dev)->ai_fifo;
@@ -2067,7 +2062,7 @@
 	return 2;
 }
 
-static int ai_config_master_clock_4020(struct comedi_device * dev, unsigned int * data)
+static int ai_config_master_clock_4020(struct comedi_device *dev, unsigned int *data)
 {
 	unsigned int divisor = data[4];
 	int retval = 0;
@@ -2092,8 +2087,8 @@
 	return retval ? retval : 5;
 }
 
-// XXX could add support for 60xx series
-static int ai_config_master_clock(struct comedi_device * dev, unsigned int * data)
+/* XXX could add support for 60xx series */
+static int ai_config_master_clock(struct comedi_device *dev, unsigned int *data)
 {
 
 	switch (board(dev)->layout) {
@@ -2108,8 +2103,8 @@
 	return -EINVAL;
 }
 
-static int ai_config_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ai_config_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int id = data[0];
 
@@ -2130,8 +2125,8 @@
 	return -EINVAL;
 }
 
-static int ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -2182,7 +2177,7 @@
 
 	/* step 2: make sure trigger sources are unique and mutually compatible */
 
-	// uniqueness check
+	/*  uniqueness check */
 	if (cmd->start_src != TRIG_NOW && cmd->start_src != TRIG_EXT)
 		err++;
 	if (cmd->scan_begin_src != TRIG_TIMER &&
@@ -2196,7 +2191,7 @@
 		cmd->stop_src != TRIG_NONE && cmd->stop_src != TRIG_EXT)
 		err++;
 
-	// compatibility check
+	/*  compatibility check */
 	if (cmd->convert_src == TRIG_EXT && cmd->scan_begin_src == TRIG_TIMER)
 		err++;
 	if (cmd->stop_src != TRIG_COUNT &&
@@ -2220,7 +2215,7 @@
 				err++;
 			}
 			if (cmd->scan_begin_src == TRIG_TIMER) {
-				// if scans are timed faster than conversion rate allows
+				/*  if scans are timed faster than conversion rate allows */
 				if (cmd->convert_arg * cmd->chanlist_len >
 					cmd->scan_begin_arg) {
 					cmd->scan_begin_arg =
@@ -2278,7 +2273,7 @@
 	if (err)
 		return 4;
 
-	// make sure user is doesn't change analog reference mid chanlist
+	/*  make sure user is doesn't change analog reference mid chanlist */
 	if (cmd->chanlist) {
 		aref = CR_AREF(cmd->chanlist[0]);
 		for (i = 1; i < cmd->chanlist_len; i++) {
@@ -2289,7 +2284,7 @@
 				break;
 			}
 		}
-		// check 4020 chanlist
+		/*  check 4020 chanlist */
 		if (board(dev)->layout == LAYOUT_4020) {
 			unsigned int first_channel = CR_CHAN(cmd->chanlist[0]);
 			for (i = 1; i < cmd->chanlist_len; i++) {
@@ -2315,9 +2310,9 @@
 	return 0;
 }
 
-static int use_hw_sample_counter(struct comedi_cmd * cmd)
+static int use_hw_sample_counter(struct comedi_cmd *cmd)
 {
-// disable for now until I work out a race
+/* disable for now until I work out a race */
 	return 0;
 
 	if (cmd->stop_src == TRIG_COUNT && cmd->stop_arg <= max_counter_value)
@@ -2326,13 +2321,13 @@
 		return 0;
 }
 
-static void setup_sample_counters(struct comedi_device * dev, struct comedi_cmd * cmd)
+static void setup_sample_counters(struct comedi_device *dev, struct comedi_cmd *cmd)
 {
 	if (cmd->stop_src == TRIG_COUNT) {
-		// set software count
+		/*  set software count */
 		priv(dev)->ai_count = cmd->stop_arg * cmd->chanlist_len;
 	}
-	// load hardware conversion counter
+	/*  load hardware conversion counter */
 	if (use_hw_sample_counter(cmd)) {
 		writew(cmd->stop_arg & 0xffff,
 			priv(dev)->main_iobase + ADC_COUNT_LOWER_REG);
@@ -2343,7 +2338,7 @@
 	}
 }
 
-static inline unsigned int dma_transfer_size(struct comedi_device * dev)
+static inline unsigned int dma_transfer_size(struct comedi_device *dev)
 {
 	unsigned int num_samples;
 
@@ -2356,71 +2351,71 @@
 	return num_samples;
 }
 
-static void disable_ai_pacing(struct comedi_device * dev)
+static void disable_ai_pacing(struct comedi_device *dev)
 {
 	unsigned long flags;
 
 	disable_ai_interrupts(dev);
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	priv(dev)->adc_control1_bits &= ~ADC_SW_GATE_BIT;
 	writew(priv(dev)->adc_control1_bits,
 		priv(dev)->main_iobase + ADC_CONTROL1_REG);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	/* disable pacing, triggering, etc */
 	writew(ADC_DMA_DISABLE_BIT | ADC_SOFT_GATE_BITS | ADC_GATE_LEVEL_BIT,
 		priv(dev)->main_iobase + ADC_CONTROL0_REG);
 }
 
-static void disable_ai_interrupts(struct comedi_device * dev)
+static void disable_ai_interrupts(struct comedi_device *dev)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	priv(dev)->intr_enable_bits &=
 		~EN_ADC_INTR_SRC_BIT & ~EN_ADC_DONE_INTR_BIT &
 		~EN_ADC_ACTIVE_INTR_BIT & ~EN_ADC_STOP_INTR_BIT &
 		~EN_ADC_OVERRUN_BIT & ~ADC_INTR_SRC_MASK;
 	writew(priv(dev)->intr_enable_bits,
 		priv(dev)->main_iobase + INTR_ENABLE_REG);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	DEBUG_PRINT("intr enable bits 0x%x\n", priv(dev)->intr_enable_bits);
 }
 
-static void enable_ai_interrupts(struct comedi_device * dev, const struct comedi_cmd * cmd)
+static void enable_ai_interrupts(struct comedi_device *dev, const struct comedi_cmd *cmd)
 {
 	uint32_t bits;
 	unsigned long flags;
 
 	bits = EN_ADC_OVERRUN_BIT | EN_ADC_DONE_INTR_BIT |
 		EN_ADC_ACTIVE_INTR_BIT | EN_ADC_STOP_INTR_BIT;
-	// Use pio transfer and interrupt on end of conversion if TRIG_WAKE_EOS flag is set.
+	/*  Use pio transfer and interrupt on end of conversion if TRIG_WAKE_EOS flag is set. */
 	if (cmd->flags & TRIG_WAKE_EOS) {
-		// 4020 doesn't support pio transfers except for fifo dregs
+		/*  4020 doesn't support pio transfers except for fifo dregs */
 		if (board(dev)->layout != LAYOUT_4020)
 			bits |= ADC_INTR_EOSCAN_BITS | EN_ADC_INTR_SRC_BIT;
 	}
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	priv(dev)->intr_enable_bits |= bits;
 	writew(priv(dev)->intr_enable_bits,
 		priv(dev)->main_iobase + INTR_ENABLE_REG);
 	DEBUG_PRINT("intr enable bits 0x%x\n", priv(dev)->intr_enable_bits);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 }
 
-static uint32_t ai_convert_counter_6xxx(const struct comedi_device * dev,
-	const struct comedi_cmd * cmd)
+static uint32_t ai_convert_counter_6xxx(const struct comedi_device *dev,
+	const struct comedi_cmd *cmd)
 {
-	// supposed to load counter with desired divisor minus 3
+	/*  supposed to load counter with desired divisor minus 3 */
 	return cmd->convert_arg / TIMER_BASE - 3;
 }
 
-static uint32_t ai_scan_counter_6xxx(struct comedi_device * dev, struct comedi_cmd * cmd)
+static uint32_t ai_scan_counter_6xxx(struct comedi_device *dev, struct comedi_cmd *cmd)
 {
 	uint32_t count;
-	// figure out how long we need to delay at end of scan
+	/*  figure out how long we need to delay at end of scan */
 	switch (cmd->scan_begin_src) {
 	case TRIG_TIMER:
 		count = (cmd->scan_begin_arg -
@@ -2437,7 +2432,7 @@
 	return count - 3;
 }
 
-static uint32_t ai_convert_counter_4020(struct comedi_device * dev, struct comedi_cmd * cmd)
+static uint32_t ai_convert_counter_4020(struct comedi_device *dev, struct comedi_cmd *cmd)
 {
 	unsigned int divisor;
 
@@ -2448,20 +2443,20 @@
 	case TRIG_OTHER:
 		divisor = priv(dev)->ext_clock.divisor;
 		break;
-	default:		// should never happen
+	default:		/*  should never happen */
 		comedi_error(dev, "bug! failed to set ai pacing!");
 		divisor = 1000;
 		break;
 	}
 
-	// supposed to load counter with desired divisor minus 2 for 4020
+	/*  supposed to load counter with desired divisor minus 2 for 4020 */
 	return divisor - 2;
 }
 
-static void select_master_clock_4020(struct comedi_device * dev,
-	const struct comedi_cmd * cmd)
+static void select_master_clock_4020(struct comedi_device *dev,
+	const struct comedi_cmd *cmd)
 {
-	// select internal/external master clock
+	/*  select internal/external master clock */
 	priv(dev)->hw_config_bits &= ~MASTER_CLOCK_4020_MASK;
 	if (cmd->scan_begin_src == TRIG_OTHER) {
 		int chanspec = priv(dev)->ext_clock.chanspec;
@@ -2477,7 +2472,7 @@
 		priv(dev)->main_iobase + HW_CONFIG_REG);
 }
 
-static void select_master_clock(struct comedi_device * dev, const struct comedi_cmd * cmd)
+static void select_master_clock(struct comedi_device *dev, const struct comedi_cmd *cmd)
 {
 	switch (board(dev)->layout) {
 	case LAYOUT_4020:
@@ -2488,12 +2483,12 @@
 	}
 }
 
-static inline void dma_start_sync(struct comedi_device * dev, unsigned int channel)
+static inline void dma_start_sync(struct comedi_device *dev, unsigned int channel)
 {
 	unsigned long flags;
 
-	// spinlock for plx dma control/status reg
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  spinlock for plx dma control/status reg */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	if (channel)
 		writeb(PLX_DMA_EN_BIT | PLX_DMA_START_BIT |
 			PLX_CLEAR_DMA_INTR_BIT,
@@ -2502,10 +2497,10 @@
 		writeb(PLX_DMA_EN_BIT | PLX_DMA_START_BIT |
 			PLX_CLEAR_DMA_INTR_BIT,
 			priv(dev)->plx9080_iobase + PLX_DMA0_CS_REG);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 }
 
-static void set_ai_pacing(struct comedi_device * dev, struct comedi_cmd * cmd)
+static void set_ai_pacing(struct comedi_device *dev, struct comedi_cmd *cmd)
 {
 	uint32_t convert_counter = 0, scan_counter = 0;
 
@@ -2520,23 +2515,23 @@
 		scan_counter = ai_scan_counter_6xxx(dev, cmd);
 	}
 
-	// load lower 16 bits of convert interval
+	/*  load lower 16 bits of convert interval */
 	writew(convert_counter & 0xffff,
 		priv(dev)->main_iobase + ADC_SAMPLE_INTERVAL_LOWER_REG);
 	DEBUG_PRINT("convert counter 0x%x\n", convert_counter);
-	// load upper 8 bits of convert interval
+	/*  load upper 8 bits of convert interval */
 	writew((convert_counter >> 16) & 0xff,
 		priv(dev)->main_iobase + ADC_SAMPLE_INTERVAL_UPPER_REG);
-	// load lower 16 bits of scan delay
+	/*  load lower 16 bits of scan delay */
 	writew(scan_counter & 0xffff,
 		priv(dev)->main_iobase + ADC_DELAY_INTERVAL_LOWER_REG);
-	// load upper 8 bits of scan delay
+	/*  load upper 8 bits of scan delay */
 	writew((scan_counter >> 16) & 0xff,
 		priv(dev)->main_iobase + ADC_DELAY_INTERVAL_UPPER_REG);
 	DEBUG_PRINT("scan counter 0x%x\n", scan_counter);
 }
 
-static int use_internal_queue_6xxx(const struct comedi_cmd * cmd)
+static int use_internal_queue_6xxx(const struct comedi_cmd *cmd)
 {
 	int i;
 	for (i = 0; i + 1 < cmd->chanlist_len; i++) {
@@ -2552,7 +2547,7 @@
 	return 1;
 }
 
-static int setup_channel_queue(struct comedi_device * dev, const struct comedi_cmd * cmd)
+static int setup_channel_queue(struct comedi_device *dev, const struct comedi_cmd *cmd)
 {
 	unsigned short bits;
 	int i;
@@ -2563,25 +2558,25 @@
 			writew(priv(dev)->hw_config_bits,
 				priv(dev)->main_iobase + HW_CONFIG_REG);
 			bits = 0;
-			// set channel
+			/*  set channel */
 			bits |= adc_chan_bits(CR_CHAN(cmd->chanlist[0]));
-			// set gain
+			/*  set gain */
 			bits |= ai_range_bits_6xxx(dev,
 				CR_RANGE(cmd->chanlist[0]));
-			// set single-ended / differential
+			/*  set single-ended / differential */
 			bits |= se_diff_bit_6xxx(dev,
 				CR_AREF(cmd->chanlist[0]) == AREF_DIFF);
 			if (CR_AREF(cmd->chanlist[0]) == AREF_COMMON)
 				bits |= ADC_COMMON_BIT;
-			// set stop channel
+			/*  set stop channel */
 			writew(adc_chan_bits(CR_CHAN(cmd->chanlist[cmd->
 							chanlist_len - 1])),
 				priv(dev)->main_iobase + ADC_QUEUE_HIGH_REG);
-			// set start channel, and rest of settings
+			/*  set start channel, and rest of settings */
 			writew(bits,
 				priv(dev)->main_iobase + ADC_QUEUE_LOAD_REG);
 		} else {
-			// use external queue
+			/*  use external queue */
 			if (dev->write_subdev && dev->write_subdev->busy) {
 				warn_external_queue(dev);
 				return -EBUSY;
@@ -2589,26 +2584,26 @@
 			priv(dev)->hw_config_bits |= EXT_QUEUE_BIT;
 			writew(priv(dev)->hw_config_bits,
 				priv(dev)->main_iobase + HW_CONFIG_REG);
-			// clear DAC buffer to prevent weird interactions
+			/*  clear DAC buffer to prevent weird interactions */
 			writew(0,
 				priv(dev)->main_iobase + DAC_BUFFER_CLEAR_REG);
-			// clear queue pointer
+			/*  clear queue pointer */
 			writew(0, priv(dev)->main_iobase + ADC_QUEUE_CLEAR_REG);
-			// load external queue
+			/*  load external queue */
 			for (i = 0; i < cmd->chanlist_len; i++) {
 				bits = 0;
-				// set channel
+				/*  set channel */
 				bits |= adc_chan_bits(CR_CHAN(cmd->
 						chanlist[i]));
-				// set gain
+				/*  set gain */
 				bits |= ai_range_bits_6xxx(dev,
 					CR_RANGE(cmd->chanlist[i]));
-				// set single-ended / differential
+				/*  set single-ended / differential */
 				bits |= se_diff_bit_6xxx(dev,
 					CR_AREF(cmd->chanlist[i]) == AREF_DIFF);
 				if (CR_AREF(cmd->chanlist[i]) == AREF_COMMON)
 					bits |= ADC_COMMON_BIT;
-				// mark end of queue
+				/*  mark end of queue */
 				if (i == cmd->chanlist_len - 1)
 					bits |= QUEUE_EOSCAN_BIT |
 						QUEUE_EOSEQ_BIT;
@@ -2622,7 +2617,7 @@
 			/* doing a queue clear is not specified in board docs,
 			 * but required for reliable operation */
 			writew(0, priv(dev)->main_iobase + ADC_QUEUE_CLEAR_REG);
-			// prime queue holding register
+			/*  prime queue holding register */
 			writew(0, priv(dev)->main_iobase + ADC_QUEUE_LOAD_REG);
 		}
 	} else {
@@ -2630,9 +2625,9 @@
 			priv(dev)->i2c_cal_range_bits;
 
 		priv(dev)->i2c_cal_range_bits &= ~ADC_SRC_4020_MASK;
-		//select BNC inputs
+		/* select BNC inputs */
 		priv(dev)->i2c_cal_range_bits |= adc_src_4020_bits(4);
-		// select ranges
+		/*  select ranges */
 		for (i = 0; i < cmd->chanlist_len; i++) {
 			unsigned int channel = CR_CHAN(cmd->chanlist[i]);
 			unsigned int range = CR_RANGE(cmd->chanlist[i]);
@@ -2644,7 +2639,7 @@
 				priv(dev)->i2c_cal_range_bits &=
 					~attenuate_bit(channel);
 		}
-		// update calibration/range i2c register only if necessary, as it is very slow
+		/*  update calibration/range i2c register only if necessary, as it is very slow */
 		if (old_cal_range_bits != priv(dev)->i2c_cal_range_bits) {
 			uint8_t i2c_data = priv(dev)->i2c_cal_range_bits;
 			i2c_write(dev, RANGE_CAL_I2C_ADDR, &i2c_data,
@@ -2654,7 +2649,7 @@
 	return 0;
 }
 
-static inline void load_first_dma_descriptor(struct comedi_device * dev,
+static inline void load_first_dma_descriptor(struct comedi_device *dev,
 	unsigned int dma_channel, unsigned int descriptor_bits)
 {
 	/* The transfer size, pci address, and local address registers
@@ -2681,7 +2676,7 @@
 	}
 }
 
-static int ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_async *async = s->async;
 	struct comedi_cmd *cmd = &async->cmd;
@@ -2697,7 +2692,7 @@
 	if (retval < 0)
 		return retval;
 
-	// make sure internal calibration source is turned off
+	/*  make sure internal calibration source is turned off */
 	writew(0, priv(dev)->main_iobase + CALIBRATION_REG);
 
 	set_ai_pacing(dev, cmd);
@@ -2706,16 +2701,16 @@
 
 	enable_ai_interrupts(dev, cmd);
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	/* set mode, allow conversions through software gate */
 	priv(dev)->adc_control1_bits |= ADC_SW_GATE_BIT;
 	priv(dev)->adc_control1_bits &= ~ADC_DITHER_BIT;
 	if (board(dev)->layout != LAYOUT_4020) {
 		priv(dev)->adc_control1_bits &= ~ADC_MODE_MASK;
 		if (cmd->convert_src == TRIG_EXT)
-			priv(dev)->adc_control1_bits |= adc_mode_bits(13);	// good old mode 13
+			priv(dev)->adc_control1_bits |= adc_mode_bits(13);	/*  good old mode 13 */
 		else
-			priv(dev)->adc_control1_bits |= adc_mode_bits(8);	// mode 8.  What else could you need?
+			priv(dev)->adc_control1_bits |= adc_mode_bits(8);	/*  mode 8.  What else could you need? */
 	} else {
 		priv(dev)->adc_control1_bits &= ~CHANNEL_MODE_4020_MASK;
 		if (cmd->chanlist_len == 4)
@@ -2733,22 +2728,22 @@
 	writew(priv(dev)->adc_control1_bits,
 		priv(dev)->main_iobase + ADC_CONTROL1_REG);
 	DEBUG_PRINT("control1 bits 0x%x\n", priv(dev)->adc_control1_bits);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// clear adc buffer
+	/*  clear adc buffer */
 	writew(0, priv(dev)->main_iobase + ADC_BUFFER_CLEAR_REG);
 
 	if ((cmd->flags & TRIG_WAKE_EOS) == 0 ||
 		board(dev)->layout == LAYOUT_4020) {
 		priv(dev)->ai_dma_index = 0;
 
-		// set dma transfer size
+		/*  set dma transfer size */
 		for (i = 0; i < ai_dma_ring_count(board(dev)); i++)
 			priv(dev)->ai_dma_desc[i].transfer_size =
 				cpu_to_le32(dma_transfer_size(dev) *
 				sizeof(uint16_t));
 
-		// give location of first dma descriptor
+		/*  give location of first dma descriptor */
 		load_first_dma_descriptor(dev, 1,
 			priv(dev)->
 			ai_dma_desc_bus_addr | PLX_DESC_IN_PCI_BIT |
@@ -2767,13 +2762,13 @@
 		writew(bits, priv(dev)->main_iobase + DAQ_ATRIG_LOW_4020_REG);
 	}
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 
 	/* enable pacing, triggering, etc */
 	bits = ADC_ENABLE_BIT | ADC_SOFT_GATE_BITS | ADC_GATE_LEVEL_BIT;
 	if (cmd->flags & TRIG_WAKE_EOS)
 		bits |= ADC_DMA_DISABLE_BIT;
-	// set start trigger
+	/*  set start trigger */
 	if (cmd->start_src == TRIG_EXT) {
 		bits |= ADC_START_TRIG_EXT_BITS;
 		if (cmd->start_arg & CR_INVERT)
@@ -2787,9 +2782,9 @@
 
 	priv(dev)->ai_cmd_running = 1;
 
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// start aquisition
+	/*  start aquisition */
 	if (cmd->start_src == TRIG_NOW) {
 		writew(0, priv(dev)->main_iobase + ADC_START_REG);
 		DEBUG_PRINT("soft trig\n");
@@ -2798,8 +2793,8 @@
 	return 0;
 }
 
-// read num_samples from 16 bit wide ai fifo
-static void pio_drain_ai_fifo_16(struct comedi_device * dev)
+/* read num_samples from 16 bit wide ai fifo */
+static void pio_drain_ai_fifo_16(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s = dev->read_subdev;
 	struct comedi_async *async = s->async;
@@ -2810,7 +2805,7 @@
 	int num_samples;
 
 	do {
-		// get least significant 15 bits
+		/*  get least significant 15 bits */
 		read_index =
 			readw(priv(dev)->main_iobase +
 			ADC_READ_PNTR_REG) & 0x7fff;
@@ -2847,7 +2842,7 @@
 		}
 
 		if (num_samples < 0) {
-			rt_printk(" cb_pcidas64: bug! num_samples < 0\n");
+			printk(" cb_pcidas64: bug! num_samples < 0\n");
 			break;
 		}
 
@@ -2866,7 +2861,7 @@
  * dma transfers (it only supports the use of pio for draining the last remaining
  * points from the fifo when a data aquisition operation has completed).
  */
-static void pio_drain_ai_fifo_32(struct comedi_device * dev)
+static void pio_drain_ai_fifo_32(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s = dev->read_subdev;
 	struct comedi_async *async = s->async;
@@ -2899,8 +2894,8 @@
 	priv(dev)->ai_count -= i;
 }
 
-// empty fifo
-static void pio_drain_ai_fifo(struct comedi_device * dev)
+/* empty fifo */
+static void pio_drain_ai_fifo(struct comedi_device *dev)
 {
 	if (board(dev)->layout == LAYOUT_4020) {
 		pio_drain_ai_fifo_32(dev);
@@ -2908,7 +2903,7 @@
 		pio_drain_ai_fifo_16(dev);
 }
 
-static void drain_dma_buffers(struct comedi_device * dev, unsigned int channel)
+static void drain_dma_buffers(struct comedi_device *dev, unsigned int channel)
 {
 	struct comedi_async *async = dev->read_subdev->async;
 	uint32_t next_transfer_addr;
@@ -2923,7 +2918,7 @@
 		pci_addr_reg =
 			priv(dev)->plx9080_iobase + PLX_DMA0_PCI_ADDRESS_REG;
 
-	// loop until we have read all the full buffers
+	/*  loop until we have read all the full buffers */
 	for (j = 0, next_transfer_addr = readl(pci_addr_reg);
 		(next_transfer_addr <
 			priv(dev)->ai_buffer_bus_addr[priv(dev)->ai_dma_index]
@@ -2931,7 +2926,7 @@
 			priv(dev)->ai_buffer_bus_addr[priv(dev)->ai_dma_index] +
 			DMA_BUFFER_SIZE) && j < ai_dma_ring_count(board(dev));
 		j++) {
-		// transfer data from dma buffer to comedi buffer
+		/*  transfer data from dma buffer to comedi buffer */
 		num_samples = dma_transfer_size(dev);
 		if (async->cmd.stop_src == TRIG_COUNT) {
 			if (num_samples > priv(dev)->ai_count)
@@ -2954,7 +2949,7 @@
 	 * unused buffer) */
 }
 
-void handle_ai_interrupt(struct comedi_device * dev, unsigned short status,
+void handle_ai_interrupt(struct comedi_device *dev, unsigned short status,
 	unsigned int plx_status)
 {
 	struct comedi_subdevice *s = dev->read_subdev;
@@ -2963,15 +2958,15 @@
 	uint8_t dma1_status;
 	unsigned long flags;
 
-	// check for fifo overrun
+	/*  check for fifo overrun */
 	if (status & ADC_OVERRUN_BIT) {
 		comedi_error(dev, "fifo overrun");
 		async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
 	}
-	// spin lock makes sure noone else changes plx dma control reg
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  spin lock makes sure noone else changes plx dma control reg */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	dma1_status = readb(priv(dev)->plx9080_iobase + PLX_DMA1_CS_REG);
-	if (plx_status & ICS_DMA1_A) {	// dma chan 1 interrupt
+	if (plx_status & ICS_DMA1_A) {	/*  dma chan 1 interrupt */
 		writeb((dma1_status & PLX_DMA_EN_BIT) | PLX_CLEAR_DMA_INTR_BIT,
 			priv(dev)->plx9080_iobase + PLX_DMA1_CS_REG);
 		DEBUG_PRINT("dma1 status 0x%x\n", dma1_status);
@@ -2981,25 +2976,25 @@
 		}
 		DEBUG_PRINT(" cleared dma ch1 interrupt\n");
 	}
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	if (status & ADC_DONE_BIT)
 		DEBUG_PRINT("adc done interrupt\n");
 
-	// drain fifo with pio
+	/*  drain fifo with pio */
 	if ((status & ADC_DONE_BIT) ||
 		((cmd->flags & TRIG_WAKE_EOS) &&
 			(status & ADC_INTR_PENDING_BIT) &&
 			(board(dev)->layout != LAYOUT_4020))) {
 		DEBUG_PRINT("pio fifo drain\n");
-		comedi_spin_lock_irqsave(&dev->spinlock, flags);
+		spin_lock_irqsave(&dev->spinlock, flags);
 		if (priv(dev)->ai_cmd_running) {
-			comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+			spin_unlock_irqrestore(&dev->spinlock, flags);
 			pio_drain_ai_fifo(dev);
 		} else
-			comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+			spin_unlock_irqrestore(&dev->spinlock, flags);
 	}
-	// if we are have all the data, then quit
+	/*  if we are have all the data, then quit */
 	if ((cmd->stop_src == TRIG_COUNT && priv(dev)->ai_count <= 0) ||
 		(cmd->stop_src == TRIG_EXT && (status & ADC_STOP_BIT))) {
 		async->events |= COMEDI_CB_EOA;
@@ -3008,7 +3003,7 @@
 	cfc_handle_events(dev, s);
 }
 
-static inline unsigned int prev_ao_dma_index(struct comedi_device * dev)
+static inline unsigned int prev_ao_dma_index(struct comedi_device *dev)
 {
 	unsigned int buffer_index;
 
@@ -3019,7 +3014,7 @@
 	return buffer_index;
 }
 
-static int last_ao_dma_load_completed(struct comedi_device * dev)
+static int last_ao_dma_load_completed(struct comedi_device *dev)
 {
 	unsigned int buffer_index;
 	unsigned int transfer_address;
@@ -3038,7 +3033,7 @@
 	return 1;
 }
 
-static int ao_stopped_by_error(struct comedi_device * dev, const struct comedi_cmd * cmd)
+static int ao_stopped_by_error(struct comedi_device *dev, const struct comedi_cmd *cmd)
 {
 	if (cmd->stop_src == TRIG_NONE)
 		return 1;
@@ -3051,7 +3046,7 @@
 	return 0;
 }
 
-static inline int ao_dma_needs_restart(struct comedi_device * dev,
+static inline int ao_dma_needs_restart(struct comedi_device *dev,
 	unsigned short dma_status)
 {
 	if ((dma_status & PLX_DMA_DONE_BIT) == 0 ||
@@ -3063,7 +3058,7 @@
 	return 1;
 }
 
-static void restart_ao_dma(struct comedi_device * dev)
+static void restart_ao_dma(struct comedi_device *dev)
 {
 	unsigned int dma_desc_bits;
 
@@ -3076,7 +3071,7 @@
 	dma_start_sync(dev, 0);
 }
 
-static void handle_ao_interrupt(struct comedi_device * dev, unsigned short status,
+static void handle_ao_interrupt(struct comedi_device *dev, unsigned short status,
 	unsigned int plx_status)
 {
 	struct comedi_subdevice *s = dev->write_subdev;
@@ -3091,10 +3086,10 @@
 	async = s->async;
 	cmd = &async->cmd;
 
-	// spin lock makes sure noone else changes plx dma control reg
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  spin lock makes sure noone else changes plx dma control reg */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	dma0_status = readb(priv(dev)->plx9080_iobase + PLX_DMA0_CS_REG);
-	if (plx_status & ICS_DMA0_A) {	// dma chan 0 interrupt
+	if (plx_status & ICS_DMA0_A) {	/*  dma chan 0 interrupt */
 		if ((dma0_status & PLX_DMA_EN_BIT)
 			&& !(dma0_status & PLX_DMA_DONE_BIT))
 			writeb(PLX_DMA_EN_BIT | PLX_CLEAR_DMA_INTR_BIT,
@@ -3102,7 +3097,7 @@
 		else
 			writeb(PLX_CLEAR_DMA_INTR_BIT,
 				priv(dev)->plx9080_iobase + PLX_DMA0_CS_REG);
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 		DEBUG_PRINT("dma0 status 0x%x\n", dma0_status);
 		if (dma0_status & PLX_DMA_EN_BIT) {
 			load_ao_dma(dev, cmd);
@@ -3112,7 +3107,7 @@
 		}
 		DEBUG_PRINT(" cleared dma ch0 interrupt\n");
 	} else
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	if ((status & DAC_DONE_BIT)) {
 		async->events |= COMEDI_CB_EOA;
@@ -3128,7 +3123,7 @@
 	cfc_handle_events(dev, s);
 }
 
-static irqreturn_t handle_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t handle_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	unsigned short status;
@@ -3152,8 +3147,8 @@
 	handle_ai_interrupt(dev, status, plx_status);
 	handle_ao_interrupt(dev, status, plx_status);
 
-	// clear possible plx9080 interrupt sources
-	if (plx_status & ICS_LDIA) {	// clear local doorbell interrupt
+	/*  clear possible plx9080 interrupt sources */
+	if (plx_status & ICS_LDIA) {	/*  clear local doorbell interrupt */
 		plx_bits = readl(priv(dev)->plx9080_iobase + PLX_DBR_OUT_REG);
 		writel(plx_bits, priv(dev)->plx9080_iobase + PLX_DBR_OUT_REG);
 		DEBUG_PRINT(" cleared local doorbell bits 0x%x\n", plx_bits);
@@ -3164,29 +3159,29 @@
 	return IRQ_HANDLED;
 }
 
-void abort_dma(struct comedi_device * dev, unsigned int channel)
+void abort_dma(struct comedi_device *dev, unsigned int channel)
 {
 	unsigned long flags;
 
-	// spinlock for plx dma control/status reg
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  spinlock for plx dma control/status reg */
+	spin_lock_irqsave(&dev->spinlock, flags);
 
 	plx9080_abort_dma(priv(dev)->plx9080_iobase, channel);
 
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 }
 
-static int ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	if (priv(dev)->ai_cmd_running == 0) {
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 		return 0;
 	}
 	priv(dev)->ai_cmd_running = 0;
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	disable_ai_pacing(dev);
 
@@ -3196,21 +3191,21 @@
 	return 0;
 }
 
-static int ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 	int range = CR_RANGE(insn->chanspec);
 
-	// do some initializing
+	/*  do some initializing */
 	writew(0, priv(dev)->main_iobase + DAC_CONTROL0_REG);
 
-	// set range
+	/*  set range */
 	set_dac_range_bits(dev, &priv(dev)->dac_control1_bits, chan, range);
 	writew(priv(dev)->dac_control1_bits,
 		priv(dev)->main_iobase + DAC_CONTROL1_REG);
 
-	// write to channel
+	/*  write to channel */
 	if (board(dev)->layout == LAYOUT_4020) {
 		writew(data[0] & 0xff,
 			priv(dev)->main_iobase + dac_lsb_4020_reg(chan));
@@ -3220,21 +3215,21 @@
 		writew(data[0], priv(dev)->main_iobase + dac_convert_reg(chan));
 	}
 
-	// remember output value
+	/*  remember output value */
 	priv(dev)->ao_value[chan] = data[0];
 
 	return 1;
 }
 
-static int ao_readback_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ao_readback_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = priv(dev)->ao_value[CR_CHAN(insn->chanspec)];
 
 	return 1;
 }
 
-static void set_dac_control0_reg(struct comedi_device * dev, const struct comedi_cmd * cmd)
+static void set_dac_control0_reg(struct comedi_device *dev, const struct comedi_cmd *cmd)
 {
 	unsigned int bits = DAC_ENABLE_BIT | WAVEFORM_GATE_LEVEL_BIT |
 		WAVEFORM_GATE_ENABLE_BIT | WAVEFORM_GATE_SELECT_BIT;
@@ -3254,7 +3249,7 @@
 	writew(bits, priv(dev)->main_iobase + DAC_CONTROL0_REG);
 }
 
-static void set_dac_control1_reg(struct comedi_device * dev, const struct comedi_cmd * cmd)
+static void set_dac_control1_reg(struct comedi_device *dev, const struct comedi_cmd *cmd)
 {
 	int i;
 
@@ -3271,7 +3266,7 @@
 		priv(dev)->main_iobase + DAC_CONTROL1_REG);
 }
 
-static void set_dac_select_reg(struct comedi_device * dev, const struct comedi_cmd * cmd)
+static void set_dac_select_reg(struct comedi_device *dev, const struct comedi_cmd *cmd)
 {
 	uint16_t bits;
 	unsigned int first_channel, last_channel;
@@ -3286,7 +3281,7 @@
 	writew(bits, priv(dev)->main_iobase + DAC_SELECT_REG);
 }
 
-static void set_dac_interval_regs(struct comedi_device * dev, const struct comedi_cmd * cmd)
+static void set_dac_interval_regs(struct comedi_device *dev, const struct comedi_cmd *cmd)
 {
 	unsigned int divisor;
 
@@ -3304,8 +3299,8 @@
 		priv(dev)->main_iobase + DAC_SAMPLE_INTERVAL_UPPER_REG);
 }
 
-static unsigned int load_ao_dma_buffer(struct comedi_device * dev,
-	const struct comedi_cmd * cmd)
+static unsigned int load_ao_dma_buffer(struct comedi_device *dev,
+	const struct comedi_cmd *cmd)
 {
 	unsigned int num_bytes, buffer_index, prev_buffer_index;
 	unsigned int next_bits;
@@ -3348,7 +3343,7 @@
 	return num_bytes;
 }
 
-static void load_ao_dma(struct comedi_device * dev, const struct comedi_cmd * cmd)
+static void load_ao_dma(struct comedi_device *dev, const struct comedi_cmd *cmd)
 {
 	unsigned int num_bytes;
 	unsigned int next_transfer_addr;
@@ -3370,7 +3365,7 @@
 	} while (num_bytes >= DMA_BUFFER_SIZE);
 }
 
-static int prep_ao_dma(struct comedi_device * dev, const struct comedi_cmd * cmd)
+static int prep_ao_dma(struct comedi_device *dev, const struct comedi_cmd *cmd)
 {
 	unsigned int num_bytes;
 	int i;
@@ -3404,7 +3399,7 @@
 	return 0;
 }
 
-static inline int external_ai_queue_in_use(struct comedi_device * dev)
+static inline int external_ai_queue_in_use(struct comedi_device *dev)
 {
 	if (dev->read_subdev->busy)
 		return 0;
@@ -3415,7 +3410,7 @@
 	return 1;
 }
 
-static int ao_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 
@@ -3440,7 +3435,7 @@
 	return 0;
 }
 
-static int ao_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ao_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trig_num)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
@@ -3463,8 +3458,8 @@
 	return 0;
 }
 
-static int ao_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -3503,14 +3498,14 @@
 
 	/* step 2: make sure trigger sources are unique and mutually compatible */
 
-	// uniqueness check
+	/*  uniqueness check */
 	if (cmd->start_src != TRIG_INT && cmd->start_src != TRIG_EXT)
 		err++;
 	if (cmd->scan_begin_src != TRIG_TIMER &&
 		cmd->scan_begin_src != TRIG_EXT)
 		err++;
 
-	// compatibility check
+	/*  compatibility check */
 	if (cmd->convert_src == TRIG_EXT && cmd->scan_begin_src == TRIG_TIMER)
 		err++;
 	if (cmd->stop_src != TRIG_COUNT &&
@@ -3579,7 +3574,7 @@
 	return 0;
 }
 
-static int ao_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ao_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	writew(0x0, priv(dev)->main_iobase + DAC_CONTROL0_REG);
 	abort_dma(dev, 0);
@@ -3607,8 +3602,8 @@
 	}
 }
 
-static int di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int bits;
 
@@ -3620,13 +3615,13 @@
 	return 2;
 }
 
-static int do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] &= 0xf;
-	// zero bits we are going to change
+	/*  zero bits we are going to change */
 	s->state &= ~data[0];
-	// set new bits
+	/*  set new bits */
 	s->state |= data[0] & data[1];
 
 	writeb(s->state, priv(dev)->dio_counter_iobase + DO_REG);
@@ -3636,8 +3631,8 @@
 	return 2;
 }
 
-static int dio_60xx_config_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dio_60xx_config_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int mask;
 
@@ -3663,8 +3658,8 @@
 	return 1;
 }
 
-static int dio_60xx_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dio_60xx_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (data[0]) {
 		s->state &= ~data[0];
@@ -3678,7 +3673,7 @@
 	return 2;
 }
 
-static void caldac_write(struct comedi_device * dev, unsigned int channel,
+static void caldac_write(struct comedi_device *dev, unsigned int channel,
 	unsigned int value)
 {
 	priv(dev)->caldac_state[channel] = value;
@@ -3696,8 +3691,8 @@
 	}
 }
 
-static int calib_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int calib_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int channel = CR_CHAN(insn->chanspec);
 
@@ -3711,8 +3706,8 @@
 	return 1;
 }
 
-static int calib_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int calib_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int channel = CR_CHAN(insn->chanspec);
 
@@ -3721,18 +3716,18 @@
 	return 1;
 }
 
-static void ad8402_write(struct comedi_device * dev, unsigned int channel,
+static void ad8402_write(struct comedi_device *dev, unsigned int channel,
 	unsigned int value)
 {
 	static const int bitstream_length = 10;
 	unsigned int bit, register_bits;
 	unsigned int bitstream = ((channel & 0x3) << 8) | (value & 0xff);
-	static const int ad8402_comedi_udelay = 1;
+	static const int ad8402_udelay = 1;
 
 	priv(dev)->ad8402_state[channel] = value;
 
 	register_bits = SELECT_8402_64XX_BIT;
-	comedi_udelay(ad8402_comedi_udelay);
+	udelay(ad8402_udelay);
 	writew(register_bits, priv(dev)->main_iobase + CALIBRATION_REG);
 
 	for (bit = 1 << (bitstream_length - 1); bit; bit >>= 1) {
@@ -3740,20 +3735,20 @@
 			register_bits |= SERIAL_DATA_IN_BIT;
 		else
 			register_bits &= ~SERIAL_DATA_IN_BIT;
-		comedi_udelay(ad8402_comedi_udelay);
+		udelay(ad8402_udelay);
 		writew(register_bits, priv(dev)->main_iobase + CALIBRATION_REG);
-		comedi_udelay(ad8402_comedi_udelay);
+		udelay(ad8402_udelay);
 		writew(register_bits | SERIAL_CLOCK_BIT,
 			priv(dev)->main_iobase + CALIBRATION_REG);
 	}
 
-	comedi_udelay(ad8402_comedi_udelay);
+	udelay(ad8402_udelay);
 	writew(0, priv(dev)->main_iobase + CALIBRATION_REG);
 }
 
 /* for pci-das6402/16, channel 0 is analog input gain and channel 1 is offset */
-static int ad8402_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ad8402_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int channel = CR_CHAN(insn->chanspec);
 
@@ -3769,8 +3764,8 @@
 	return 1;
 }
 
-static int ad8402_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ad8402_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int channel = CR_CHAN(insn->chanspec);
 
@@ -3779,7 +3774,7 @@
 	return 1;
 }
 
-static uint16_t read_eeprom(struct comedi_device * dev, uint8_t address)
+static uint16_t read_eeprom(struct comedi_device *dev, uint8_t address)
 {
 	static const int bitstream_length = 11;
 	static const int read_command = 0x6;
@@ -3789,60 +3784,60 @@
 		priv(dev)->plx9080_iobase + PLX_CONTROL_REG;
 	uint16_t value;
 	static const int value_length = 16;
-	static const int eeprom_comedi_udelay = 1;
+	static const int eeprom_udelay = 1;
 
-	comedi_udelay(eeprom_comedi_udelay);
+	udelay(eeprom_udelay);
 	priv(dev)->plx_control_bits &= ~CTL_EE_CLK & ~CTL_EE_CS;
-	// make sure we don't send anything to the i2c bus on 4020
+	/*  make sure we don't send anything to the i2c bus on 4020 */
 	priv(dev)->plx_control_bits |= CTL_USERO;
 	writel(priv(dev)->plx_control_bits, plx_control_addr);
-	// activate serial eeprom
-	comedi_udelay(eeprom_comedi_udelay);
+	/*  activate serial eeprom */
+	udelay(eeprom_udelay);
 	priv(dev)->plx_control_bits |= CTL_EE_CS;
 	writel(priv(dev)->plx_control_bits, plx_control_addr);
 
-	// write read command and desired memory address
+	/*  write read command and desired memory address */
 	for (bit = 1 << (bitstream_length - 1); bit; bit >>= 1) {
-		// set bit to be written
-		comedi_udelay(eeprom_comedi_udelay);
+		/*  set bit to be written */
+		udelay(eeprom_udelay);
 		if (bitstream & bit)
 			priv(dev)->plx_control_bits |= CTL_EE_W;
 		else
 			priv(dev)->plx_control_bits &= ~CTL_EE_W;
 		writel(priv(dev)->plx_control_bits, plx_control_addr);
-		// clock in bit
-		comedi_udelay(eeprom_comedi_udelay);
+		/*  clock in bit */
+		udelay(eeprom_udelay);
 		priv(dev)->plx_control_bits |= CTL_EE_CLK;
 		writel(priv(dev)->plx_control_bits, plx_control_addr);
-		comedi_udelay(eeprom_comedi_udelay);
+		udelay(eeprom_udelay);
 		priv(dev)->plx_control_bits &= ~CTL_EE_CLK;
 		writel(priv(dev)->plx_control_bits, plx_control_addr);
 	}
-	// read back value from eeprom memory location
+	/*  read back value from eeprom memory location */
 	value = 0;
 	for (bit = 1 << (value_length - 1); bit; bit >>= 1) {
-		// clock out bit
-		comedi_udelay(eeprom_comedi_udelay);
+		/*  clock out bit */
+		udelay(eeprom_udelay);
 		priv(dev)->plx_control_bits |= CTL_EE_CLK;
 		writel(priv(dev)->plx_control_bits, plx_control_addr);
-		comedi_udelay(eeprom_comedi_udelay);
+		udelay(eeprom_udelay);
 		priv(dev)->plx_control_bits &= ~CTL_EE_CLK;
 		writel(priv(dev)->plx_control_bits, plx_control_addr);
-		comedi_udelay(eeprom_comedi_udelay);
+		udelay(eeprom_udelay);
 		if (readl(plx_control_addr) & CTL_EE_R)
 			value |= bit;
 	}
 
-	// deactivate eeprom serial input
-	comedi_udelay(eeprom_comedi_udelay);
+	/*  deactivate eeprom serial input */
+	udelay(eeprom_udelay);
 	priv(dev)->plx_control_bits &= ~CTL_EE_CS;
 	writel(priv(dev)->plx_control_bits, plx_control_addr);
 
 	return value;
 }
 
-static int eeprom_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int eeprom_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = read_eeprom(dev, CR_CHAN(insn->chanspec));
 
@@ -3880,7 +3875,7 @@
 	if (cmd->scan_begin_src == TRIG_TIMER) {
 		scan_divisor = get_divisor(cmd->scan_begin_arg, cmd->flags);
 		if (cmd->convert_src == TRIG_TIMER) {
-			// XXX check for integer overflows
+			/*  XXX check for integer overflows */
 			min_scan_divisor = convert_divisor * cmd->chanlist_len;
 			max_scan_divisor =
 				(convert_divisor * cmd->chanlist_len - 1) +
@@ -3926,8 +3921,8 @@
 	return get_divisor(ns, flags) - 2;
 }
 
-// adjusts the size of hardware fifo (which determines block size for dma xfers)
-static int set_ai_fifo_size(struct comedi_device * dev, unsigned int num_samples)
+/* adjusts the size of hardware fifo (which determines block size for dma xfers) */
+static int set_ai_fifo_size(struct comedi_device *dev, unsigned int num_samples)
 {
 	unsigned int num_fifo_entries;
 	int retval;
@@ -3947,15 +3942,15 @@
 	return num_samples;
 }
 
-// query length of fifo
-static unsigned int ai_fifo_size(struct comedi_device * dev)
+/* query length of fifo */
+static unsigned int ai_fifo_size(struct comedi_device *dev)
 {
 	return priv(dev)->ai_fifo_segment_length *
 		board(dev)->ai_fifo->num_segments *
 		board(dev)->ai_fifo->sample_packing_ratio;
 }
 
-static int set_ai_fifo_segment_length(struct comedi_device * dev,
+static int set_ai_fifo_segment_length(struct comedi_device *dev,
 	unsigned int num_entries)
 {
 	static const int increment_size = 0x100;
@@ -3968,7 +3963,7 @@
 	if (num_entries > fifo->max_segment_length)
 		num_entries = fifo->max_segment_length;
 
-	// 1 == 256 entries, 2 == 512 entries, etc
+	/*  1 == 256 entries, 2 == 512 entries, etc */
 	num_increments = (num_entries + increment_size / 2) / increment_size;
 
 	bits = (~(num_increments - 1)) & fifo->fifo_size_reg_mask;
@@ -4006,7 +4001,7 @@
  * address 7 == dac channel 1 fine offset
 */
 
-static int caldac_8800_write(struct comedi_device * dev, unsigned int address,
+static int caldac_8800_write(struct comedi_device *dev, unsigned int address,
 	uint8_t value)
 {
 	static const int num_caldac_channels = 8;
@@ -4023,28 +4018,28 @@
 		register_bits = 0;
 		if (bitstream & bit)
 			register_bits |= SERIAL_DATA_IN_BIT;
-		comedi_udelay(caldac_8800_udelay);
+		udelay(caldac_8800_udelay);
 		writew(register_bits, priv(dev)->main_iobase + CALIBRATION_REG);
 		register_bits |= SERIAL_CLOCK_BIT;
-		comedi_udelay(caldac_8800_udelay);
+		udelay(caldac_8800_udelay);
 		writew(register_bits, priv(dev)->main_iobase + CALIBRATION_REG);
 	}
-	comedi_udelay(caldac_8800_udelay);
+	udelay(caldac_8800_udelay);
 	writew(SELECT_8800_BIT, priv(dev)->main_iobase + CALIBRATION_REG);
-	comedi_udelay(caldac_8800_udelay);
+	udelay(caldac_8800_udelay);
 	writew(0, priv(dev)->main_iobase + CALIBRATION_REG);
-	comedi_udelay(caldac_8800_udelay);
+	udelay(caldac_8800_udelay);
 	return 0;
 }
 
-// 4020 caldacs
-static int caldac_i2c_write(struct comedi_device * dev, unsigned int caldac_channel,
+/* 4020 caldacs */
+static int caldac_i2c_write(struct comedi_device *dev, unsigned int caldac_channel,
 	unsigned int value)
 {
 	uint8_t serial_bytes[3];
 	uint8_t i2c_addr;
 	enum pointer_bits {
-		// manual has gain and offset bits switched
+		/*  manual has gain and offset bits switched */
 		OFFSET_0_2 = 0x1,
 		GAIN_0_2 = 0x2,
 		OFFSET_1_3 = 0x4,
@@ -4055,35 +4050,35 @@
 	};
 
 	switch (caldac_channel) {
-	case 0:		// chan 0 offset
+	case 0:		/*  chan 0 offset */
 		i2c_addr = CALDAC0_I2C_ADDR;
 		serial_bytes[0] = OFFSET_0_2;
 		break;
-	case 1:		// chan 1 offset
+	case 1:		/*  chan 1 offset */
 		i2c_addr = CALDAC0_I2C_ADDR;
 		serial_bytes[0] = OFFSET_1_3;
 		break;
-	case 2:		// chan 2 offset
+	case 2:		/*  chan 2 offset */
 		i2c_addr = CALDAC1_I2C_ADDR;
 		serial_bytes[0] = OFFSET_0_2;
 		break;
-	case 3:		// chan 3 offset
+	case 3:		/*  chan 3 offset */
 		i2c_addr = CALDAC1_I2C_ADDR;
 		serial_bytes[0] = OFFSET_1_3;
 		break;
-	case 4:		// chan 0 gain
+	case 4:		/*  chan 0 gain */
 		i2c_addr = CALDAC0_I2C_ADDR;
 		serial_bytes[0] = GAIN_0_2;
 		break;
-	case 5:		// chan 1 gain
+	case 5:		/*  chan 1 gain */
 		i2c_addr = CALDAC0_I2C_ADDR;
 		serial_bytes[0] = GAIN_1_3;
 		break;
-	case 6:		// chan 2 gain
+	case 6:		/*  chan 2 gain */
 		i2c_addr = CALDAC1_I2C_ADDR;
 		serial_bytes[0] = GAIN_0_2;
 		break;
-	case 7:		// chan 3 gain
+	case 7:		/*  chan 3 gain */
 		i2c_addr = CALDAC1_I2C_ADDR;
 		serial_bytes[0] = GAIN_1_3;
 		break;
@@ -4098,49 +4093,49 @@
 	return 0;
 }
 
-// Their i2c requires a huge delay on setting clock or data high for some reason
-static const int i2c_high_comedi_udelay = 1000;
-static const int i2c_low_comedi_udelay = 10;
+/* Their i2c requires a huge delay on setting clock or data high for some reason */
+static const int i2c_high_udelay = 1000;
+static const int i2c_low_udelay = 10;
 
-// set i2c data line high or low
-static void i2c_set_sda(struct comedi_device * dev, int state)
+/* set i2c data line high or low */
+static void i2c_set_sda(struct comedi_device *dev, int state)
 {
 	static const int data_bit = CTL_EE_W;
 	void *plx_control_addr = priv(dev)->plx9080_iobase + PLX_CONTROL_REG;
 
 	if (state) {
-		// set data line high
+		/*  set data line high */
 		priv(dev)->plx_control_bits &= ~data_bit;
 		writel(priv(dev)->plx_control_bits, plx_control_addr);
-		comedi_udelay(i2c_high_comedi_udelay);
-	} else			// set data line low
+		udelay(i2c_high_udelay);
+	} else			/*  set data line low */
 	{
 		priv(dev)->plx_control_bits |= data_bit;
 		writel(priv(dev)->plx_control_bits, plx_control_addr);
-		comedi_udelay(i2c_low_comedi_udelay);
+		udelay(i2c_low_udelay);
 	}
 }
 
-// set i2c clock line high or low
-static void i2c_set_scl(struct comedi_device * dev, int state)
+/* set i2c clock line high or low */
+static void i2c_set_scl(struct comedi_device *dev, int state)
 {
 	static const int clock_bit = CTL_USERO;
 	void *plx_control_addr = priv(dev)->plx9080_iobase + PLX_CONTROL_REG;
 
 	if (state) {
-		// set clock line high
+		/*  set clock line high */
 		priv(dev)->plx_control_bits &= ~clock_bit;
 		writel(priv(dev)->plx_control_bits, plx_control_addr);
-		comedi_udelay(i2c_high_comedi_udelay);
-	} else			// set clock line low
+		udelay(i2c_high_udelay);
+	} else			/*  set clock line low */
 	{
 		priv(dev)->plx_control_bits |= clock_bit;
 		writel(priv(dev)->plx_control_bits, plx_control_addr);
-		comedi_udelay(i2c_low_comedi_udelay);
+		udelay(i2c_low_udelay);
 	}
 }
 
-static void i2c_write_byte(struct comedi_device * dev, uint8_t byte)
+static void i2c_write_byte(struct comedi_device *dev, uint8_t byte)
 {
 	uint8_t bit;
 	unsigned int num_bits = 8;
@@ -4157,26 +4152,26 @@
 	}
 }
 
-// we can't really read the lines, so fake it
-static int i2c_read_ack(struct comedi_device * dev)
+/* we can't really read the lines, so fake it */
+static int i2c_read_ack(struct comedi_device *dev)
 {
 	i2c_set_scl(dev, 0);
 	i2c_set_sda(dev, 1);
 	i2c_set_scl(dev, 1);
 
-	return 0;		// return fake acknowledge bit
+	return 0;		/*  return fake acknowledge bit */
 }
 
-// send start bit
-static void i2c_start(struct comedi_device * dev)
+/* send start bit */
+static void i2c_start(struct comedi_device *dev)
 {
 	i2c_set_scl(dev, 1);
 	i2c_set_sda(dev, 1);
 	i2c_set_sda(dev, 0);
 }
 
-// send stop bit
-static void i2c_stop(struct comedi_device * dev)
+/* send stop bit */
+static void i2c_stop(struct comedi_device *dev)
 {
 	i2c_set_scl(dev, 0);
 	i2c_set_sda(dev, 0);
@@ -4184,32 +4179,32 @@
 	i2c_set_sda(dev, 1);
 }
 
-static void i2c_write(struct comedi_device * dev, unsigned int address,
-	const uint8_t * data, unsigned int length)
+static void i2c_write(struct comedi_device *dev, unsigned int address,
+	const uint8_t *data, unsigned int length)
 {
 	unsigned int i;
 	uint8_t bitstream;
 	static const int read_bit = 0x1;
 
-//XXX need mutex to prevent simultaneous attempts to access eeprom and i2c bus
+/* XXX need mutex to prevent simultaneous attempts to access eeprom and i2c bus */
 
-	// make sure we dont send anything to eeprom
+	/*  make sure we dont send anything to eeprom */
 	priv(dev)->plx_control_bits &= ~CTL_EE_CS;
 
 	i2c_stop(dev);
 	i2c_start(dev);
 
-	// send address and write bit
+	/*  send address and write bit */
 	bitstream = (address << 1) & ~read_bit;
 	i2c_write_byte(dev, bitstream);
 
-	// get acknowledge
+	/*  get acknowledge */
 	if (i2c_read_ack(dev) != 0) {
 		comedi_error(dev, "i2c write failed: no acknowledge");
 		i2c_stop(dev);
 		return;
 	}
-	// write data bytes
+	/*  write data bytes */
 	for (i = 0; i < length; i++) {
 		i2c_write_byte(dev, data[i]);
 		if (i2c_read_ack(dev) != 0) {
diff --git a/drivers/staging/comedi/drivers/cb_pcidda.c b/drivers/staging/comedi/drivers/cb_pcidda.c
index ed0a5eb..8f36294 100644
--- a/drivers/staging/comedi/drivers/cb_pcidda.c
+++ b/drivers/staging/comedi/drivers/cb_pcidda.c
@@ -51,66 +51,66 @@
 #include "comedi_pci.h"
 #include "8255.h"
 
-#define PCI_VENDOR_ID_CB	0x1307	// PCI vendor number of ComputerBoards
-#define N_BOARDS	10	// Number of boards in cb_pcidda_boards
-#define EEPROM_SIZE	128	// number of entries in eeprom
-#define MAX_AO_CHANNELS 8	// maximum number of ao channels for supported boards
+#define PCI_VENDOR_ID_CB	0x1307	/*  PCI vendor number of ComputerBoards */
+#define N_BOARDS	10	/*  Number of boards in cb_pcidda_boards */
+#define EEPROM_SIZE	128	/*  number of entries in eeprom */
+#define MAX_AO_CHANNELS 8	/*  maximum number of ao channels for supported boards */
 
 /* PCI-DDA base addresses */
 #define DIGITALIO_BADRINDEX	2
-	// DIGITAL I/O is pci_dev->resource[2]
+	/*  DIGITAL I/O is pci_dev->resource[2] */
 #define DIGITALIO_SIZE 8
-	// DIGITAL I/O uses 8 I/O port addresses
+	/*  DIGITAL I/O uses 8 I/O port addresses */
 #define DAC_BADRINDEX	3
-	// DAC is pci_dev->resource[3]
+	/*  DAC is pci_dev->resource[3] */
 
 /* Digital I/O registers */
-#define PORT1A 0		// PORT 1A DATA
+#define PORT1A 0		/*  PORT 1A DATA */
 
-#define PORT1B 1		// PORT 1B DATA
+#define PORT1B 1		/*  PORT 1B DATA */
 
-#define PORT1C 2		// PORT 1C DATA
+#define PORT1C 2		/*  PORT 1C DATA */
 
-#define CONTROL1 3		// CONTROL REGISTER 1
+#define CONTROL1 3		/*  CONTROL REGISTER 1 */
 
-#define PORT2A 4		// PORT 2A DATA
+#define PORT2A 4		/*  PORT 2A DATA */
 
-#define PORT2B 5		// PORT 2B DATA
+#define PORT2B 5		/*  PORT 2B DATA */
 
-#define PORT2C 6		// PORT 2C DATA
+#define PORT2C 6		/*  PORT 2C DATA */
 
-#define CONTROL2 7		// CONTROL REGISTER 2
+#define CONTROL2 7		/*  CONTROL REGISTER 2 */
 
 /* DAC registers */
-#define DACONTROL	0	// D/A CONTROL REGISTER
-#define	SU	0000001		// Simultaneous update enabled
-#define NOSU	0000000		// Simultaneous update disabled
-#define	ENABLEDAC	0000002	// Enable specified DAC
-#define	DISABLEDAC	0000000	// Disable specified DAC
-#define RANGE2V5	0000000	// 2.5V
-#define RANGE5V	0000200		// 5V
-#define RANGE10V	0000300	// 10V
-#define UNIP	0000400		// Unipolar outputs
-#define BIP	0000000		// Bipolar outputs
+#define DACONTROL	0	/*  D/A CONTROL REGISTER */
+#define	SU	0000001		/*  Simultaneous update enabled */
+#define NOSU	0000000		/*  Simultaneous update disabled */
+#define	ENABLEDAC	0000002	/*  Enable specified DAC */
+#define	DISABLEDAC	0000000	/*  Disable specified DAC */
+#define RANGE2V5	0000000	/*  2.5V */
+#define RANGE5V	0000200		/*  5V */
+#define RANGE10V	0000300	/*  10V */
+#define UNIP	0000400		/*  Unipolar outputs */
+#define BIP	0000000		/*  Bipolar outputs */
 
-#define DACALIBRATION1	4	// D/A CALIBRATION REGISTER 1
-//write bits
-#define	SERIAL_IN_BIT	0x1	// serial data input for eeprom, caldacs, reference dac
+#define DACALIBRATION1	4	/*  D/A CALIBRATION REGISTER 1 */
+/* write bits */
+#define	SERIAL_IN_BIT	0x1	/*  serial data input for eeprom, caldacs, reference dac */
 #define	CAL_CHANNEL_MASK	(0x7 << 1)
 #define	CAL_CHANNEL_BITS(channel)	(((channel) << 1) & CAL_CHANNEL_MASK)
-//read bits
+/* read bits */
 #define	CAL_COUNTER_MASK	0x1f
-#define	CAL_COUNTER_OVERFLOW_BIT	0x20	// calibration counter overflow status bit
-#define	AO_BELOW_REF_BIT	0x40	// analog output is less than reference dac voltage
-#define	SERIAL_OUT_BIT	0x80	// serial data out, for reading from eeprom
+#define	CAL_COUNTER_OVERFLOW_BIT	0x20	/*  calibration counter overflow status bit */
+#define	AO_BELOW_REF_BIT	0x40	/*  analog output is less than reference dac voltage */
+#define	SERIAL_OUT_BIT	0x80	/*  serial data out, for reading from eeprom */
 
-#define DACALIBRATION2	6	// D/A CALIBRATION REGISTER 2
-#define	SELECT_EEPROM_BIT	0x1	// send serial data in to eeprom
-#define	DESELECT_REF_DAC_BIT	0x2	// don't send serial data to MAX542 reference dac
-#define	DESELECT_CALDAC_BIT(n)	(0x4 << (n))	// don't send serial data to caldac n
-#define	DUMMY_BIT	0x40	// manual says to set this bit with no explanation
+#define DACALIBRATION2	6	/*  D/A CALIBRATION REGISTER 2 */
+#define	SELECT_EEPROM_BIT	0x1	/*  send serial data in to eeprom */
+#define	DESELECT_REF_DAC_BIT	0x2	/*  don't send serial data to MAX542 reference dac */
+#define	DESELECT_CALDAC_BIT(n)	(0x4 << (n))	/*  don't send serial data to caldac n */
+#define	DUMMY_BIT	0x40	/*  manual says to set this bit with no explanation */
 
-#define DADATA	8		// FIRST D/A DATA REGISTER (0)
+#define DADATA	8		/*  FIRST D/A DATA REGISTER (0) */
 
 static const struct comedi_lrange cb_pcidda_ranges = {
 	6,
@@ -131,63 +131,68 @@
  */
 struct cb_pcidda_board {
 	const char *name;
-	char status;		// Driver status:
-	// 0 - tested
-	// 1 - manual read, not tested
-	// 2 - manual not read
+	char status;		/*  Driver status: */
+
+	/*
+	 * 0 - tested
+	 * 1 - manual read, not tested
+	 * 2 - manual not read
+	 */
+
 	unsigned short device_id;
 	int ao_chans;
 	int ao_bits;
 	const struct comedi_lrange *ranges;
 };
+
 static const struct cb_pcidda_board cb_pcidda_boards[] = {
 	{
-	      name:	"pci-dda02/12",
-	      status:	1,
-	      device_id:0x20,
-	      ao_chans:2,
-	      ao_bits:	12,
-	      ranges:	&cb_pcidda_ranges,
+	.name = "pci-dda02/12",
+	.status = 1,
+	.device_id = 0x20,
+	.ao_chans = 2,
+	.ao_bits = 12,
+	.ranges = &cb_pcidda_ranges,
 		},
 	{
-	      name:	"pci-dda04/12",
-	      status:	1,
-	      device_id:0x21,
-	      ao_chans:4,
-	      ao_bits:	12,
-	      ranges:	&cb_pcidda_ranges,
+	.name = "pci-dda04/12",
+	.status = 1,
+	.device_id = 0x21,
+	.ao_chans = 4,
+	.ao_bits = 12,
+	.ranges = &cb_pcidda_ranges,
 		},
 	{
-	      name:	"pci-dda08/12",
-	      status:	0,
-	      device_id:0x22,
-	      ao_chans:8,
-	      ao_bits:	12,
-	      ranges:	&cb_pcidda_ranges,
+	.name = "pci-dda08/12",
+	.status = 0,
+	.device_id = 0x22,
+	.ao_chans = 8,
+	.ao_bits = 12,
+	.ranges = &cb_pcidda_ranges,
 		},
 	{
-	      name:	"pci-dda02/16",
-	      status:	2,
-	      device_id:0x23,
-	      ao_chans:2,
-	      ao_bits:	16,
-	      ranges:	&cb_pcidda_ranges,
+	.name = "pci-dda02/16",
+	.status = 2,
+	.device_id = 0x23,
+	.ao_chans = 2,
+	.ao_bits = 16,
+	.ranges = &cb_pcidda_ranges,
 		},
 	{
-	      name:	"pci-dda04/16",
-	      status:	2,
-	      device_id:0x24,
-	      ao_chans:4,
-	      ao_bits:	16,
-	      ranges:	&cb_pcidda_ranges,
+	.name = "pci-dda04/16",
+	.status = 2,
+	.device_id = 0x24,
+	.ao_chans = 4,
+	.ao_bits = 16,
+	.ranges = &cb_pcidda_ranges,
 		},
 	{
-	      name:	"pci-dda08/16",
-	      status:	0,
-	      device_id:0x25,
-	      ao_chans:8,
-	      ao_bits:	16,
-	      ranges:	&cb_pcidda_ranges,
+	.name = "pci-dda08/16",
+	.status = 0,
+	.device_id = 0x25,
+	.ao_chans = 8,
+	.ao_bits = 16,
+	.ranges = &cb_pcidda_ranges,
 		},
 };
 
@@ -219,11 +224,13 @@
 
 	unsigned long digitalio;
 	unsigned long dac;
-	//unsigned long control_status;
-	//unsigned long adc_fifo;
-	unsigned int dac_cal1_bits;	// bits last written to da calibration register 1
-	unsigned int ao_range[MAX_AO_CHANNELS];	// current range settings for output channels
-	u16 eeprom_data[EEPROM_SIZE];	// software copy of board's eeprom
+
+	/* unsigned long control_status; */
+	/* unsigned long adc_fifo; */
+
+	unsigned int dac_cal1_bits;	/*  bits last written to da calibration register 1 */
+	unsigned int ao_range[MAX_AO_CHANNELS];	/*  current range settings for output channels */
+	u16 eeprom_data[EEPROM_SIZE];	/*  software copy of board's eeprom */
 };
 
 /*
@@ -232,20 +239,22 @@
  */
 #define devpriv ((struct cb_pcidda_private *)dev->private)
 
-static int cb_pcidda_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int cb_pcidda_detach(struct comedi_device * dev);
-//static int cb_pcidda_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data);
-static int cb_pcidda_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-//static int cb_pcidda_ai_cmd(struct comedi_device *dev,struct comedi_subdevice *s);
-//static int cb_pcidda_ai_cmdtest(struct comedi_device *dev,struct comedi_subdevice *s, struct comedi_cmd *cmd);
-//static int cb_pcidda_ns_to_timer(unsigned int *ns,int round);
-static unsigned int cb_pcidda_serial_in(struct comedi_device * dev);
-static void cb_pcidda_serial_out(struct comedi_device * dev, unsigned int value,
+static int cb_pcidda_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int cb_pcidda_detach(struct comedi_device *dev);
+/* static int cb_pcidda_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data); */
+static int cb_pcidda_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+
+/* static int cb_pcidda_ai_cmd(struct comedi_device *dev, struct *comedi_subdevice *s);*/
+/* static int cb_pcidda_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_cmd *cmd); */
+/* static int cb_pcidda_ns_to_timer(unsigned int *ns,int *round); */
+
+static unsigned int cb_pcidda_serial_in(struct comedi_device *dev);
+static void cb_pcidda_serial_out(struct comedi_device *dev, unsigned int value,
 	unsigned int num_bits);
-static unsigned int cb_pcidda_read_eeprom(struct comedi_device * dev,
+static unsigned int cb_pcidda_read_eeprom(struct comedi_device *dev,
 	unsigned int address);
-static void cb_pcidda_calibrate(struct comedi_device * dev, unsigned int channel,
+static void cb_pcidda_calibrate(struct comedi_device *dev, unsigned int channel,
 	unsigned int range);
 
 /*
@@ -255,17 +264,17 @@
  * the device code.
  */
 static struct comedi_driver driver_cb_pcidda = {
-      driver_name:"cb_pcidda",
-      module:THIS_MODULE,
-      attach:cb_pcidda_attach,
-      detach:cb_pcidda_detach,
+	.driver_name = "cb_pcidda",
+	.module = THIS_MODULE,
+	.attach = cb_pcidda_attach,
+	.detach = cb_pcidda_detach,
 };
 
 /*
  * Attach is called by the Comedi core to configure the driver
  * for a particular board.
  */
-static int cb_pcidda_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int cb_pcidda_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	struct pci_dev *pcidev;
@@ -310,7 +319,7 @@
       found:
 	devpriv->pci_dev = pcidev;
 	dev->board_ptr = cb_pcidda_boards + index;
-	// "thisboard" macro can be used from here.
+	/*  "thisboard" macro can be used from here. */
 	printk("Found %s at requested position\n", thisboard->name);
 
 	/*
@@ -353,11 +362,12 @@
 	s->maxdata = (1 << thisboard->ao_bits) - 1;
 	s->range_table = thisboard->ranges;
 	s->insn_write = cb_pcidda_ao_winsn;
-//      s->subdev_flags |= SDF_CMD_READ;
-//      s->do_cmd = cb_pcidda_ai_cmd;
-//      s->do_cmdtest = cb_pcidda_ai_cmdtest;
 
-	// two 8255 digital io subdevices
+	/* s->subdev_flags |= SDF_CMD_READ; */
+	/* s->do_cmd = cb_pcidda_ai_cmd; */
+	/* s->do_cmdtest = cb_pcidda_ai_cmdtest; */
+
+	/*  two 8255 digital io subdevices */
 	s = dev->subdevices + 1;
 	subdev_8255_init(dev, s, NULL, devpriv->digitalio);
 	s = dev->subdevices + 2;
@@ -370,7 +380,7 @@
 	}
 	printk("\n");
 
-	// set calibrations dacs
+	/*  set calibrations dacs */
 	for (index = 0; index < thisboard->ao_chans; index++)
 		cb_pcidda_calibrate(dev, index, devpriv->ao_range[index]);
 
@@ -385,7 +395,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int cb_pcidda_detach(struct comedi_device * dev)
+static int cb_pcidda_detach(struct comedi_device *dev)
 {
 /*
  * Deallocate the I/O ports.
@@ -398,7 +408,7 @@
 			pci_dev_put(devpriv->pci_dev);
 		}
 	}
-	// cleanup 8255
+	/*  cleanup 8255 */
 	if (dev->subdevices) {
 		subdev_8255_cleanup(dev, dev->subdevices + 1);
 		subdev_8255_cleanup(dev, dev->subdevices + 2);
@@ -413,7 +423,7 @@
  * I will program this later... ;-)
  */
 #if 0
-static int cb_pcidda_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int cb_pcidda_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	printk("cb_pcidda_ai_cmd\n");
 	printk("subdev: %d\n", cmd->subdev);
@@ -432,8 +442,8 @@
 #endif
 
 #if 0
-static int cb_pcidda_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int cb_pcidda_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -598,8 +608,8 @@
 }
 #endif
 
-static int cb_pcidda_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int cb_pcidda_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int command;
 	unsigned int channel, range;
@@ -607,7 +617,7 @@
 	channel = CR_CHAN(insn->chanspec);
 	range = CR_RANGE(insn->chanspec);
 
-	// adjust calibration dacs if range has changed
+	/*  adjust calibration dacs if range has changed */
 	if (range != devpriv->ao_range[channel])
 		cb_pcidda_calibrate(dev, channel, range);
 
@@ -647,15 +657,15 @@
 	return 1;
 }
 
-// lowlevel read from eeprom
-static unsigned int cb_pcidda_serial_in(struct comedi_device * dev)
+/* lowlevel read from eeprom */
+static unsigned int cb_pcidda_serial_in(struct comedi_device *dev)
 {
 	unsigned int value = 0;
 	int i;
-	const int value_width = 16;	// number of bits wide values are
+	const int value_width = 16;	/*  number of bits wide values are */
 
 	for (i = 1; i <= value_width; i++) {
-		// read bits most significant bit first
+		/*  read bits most significant bit first */
 		if (inw_p(devpriv->dac + DACALIBRATION1) & SERIAL_OUT_BIT) {
 			value |= 1 << (value_width - i);
 		}
@@ -664,14 +674,14 @@
 	return value;
 }
 
-// lowlevel write to eeprom/dac
-static void cb_pcidda_serial_out(struct comedi_device * dev, unsigned int value,
+/* lowlevel write to eeprom/dac */
+static void cb_pcidda_serial_out(struct comedi_device *dev, unsigned int value,
 	unsigned int num_bits)
 {
 	int i;
 
 	for (i = 1; i <= num_bits; i++) {
-		// send bits most significant bit first
+		/*  send bits most significant bit first */
 		if (value & (1 << (num_bits - i)))
 			devpriv->dac_cal1_bits |= SERIAL_IN_BIT;
 		else
@@ -680,136 +690,137 @@
 	}
 }
 
-// reads a 16 bit value from board's eeprom
-static unsigned int cb_pcidda_read_eeprom(struct comedi_device * dev,
+/* reads a 16 bit value from board's eeprom */
+static unsigned int cb_pcidda_read_eeprom(struct comedi_device *dev,
 	unsigned int address)
 {
 	unsigned int i;
 	unsigned int cal2_bits;
 	unsigned int value;
-	const int max_num_caldacs = 4;	// one caldac for every two dac channels
-	const int read_instruction = 0x6;	// bits to send to tell eeprom we want to read
+	const int max_num_caldacs = 4;	/*  one caldac for every two dac channels */
+	const int read_instruction = 0x6;	/*  bits to send to tell eeprom we want to read */
 	const int instruction_length = 3;
 	const int address_length = 8;
 
-	// send serial output stream to eeprom
+	/*  send serial output stream to eeprom */
 	cal2_bits = SELECT_EEPROM_BIT | DESELECT_REF_DAC_BIT | DUMMY_BIT;
-	// deactivate caldacs (one caldac for every two channels)
+	/*  deactivate caldacs (one caldac for every two channels) */
 	for (i = 0; i < max_num_caldacs; i++) {
 		cal2_bits |= DESELECT_CALDAC_BIT(i);
 	}
 	outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
 
-	// tell eeprom we want to read
+	/*  tell eeprom we want to read */
 	cb_pcidda_serial_out(dev, read_instruction, instruction_length);
-	// send address we want to read from
+	/*  send address we want to read from */
 	cb_pcidda_serial_out(dev, address, address_length);
 
 	value = cb_pcidda_serial_in(dev);
 
-	// deactivate eeprom
+	/*  deactivate eeprom */
 	cal2_bits &= ~SELECT_EEPROM_BIT;
 	outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
 
 	return value;
 }
 
-// writes to 8 bit calibration dacs
-static void cb_pcidda_write_caldac(struct comedi_device * dev, unsigned int caldac,
+/* writes to 8 bit calibration dacs */
+static void cb_pcidda_write_caldac(struct comedi_device *dev, unsigned int caldac,
 	unsigned int channel, unsigned int value)
 {
 	unsigned int cal2_bits;
 	unsigned int i;
-	const int num_channel_bits = 3;	// caldacs use 3 bit channel specification
-	const int num_caldac_bits = 8;	// 8 bit calibration dacs
-	const int max_num_caldacs = 4;	// one caldac for every two dac channels
+	const int num_channel_bits = 3;	/*  caldacs use 3 bit channel specification */
+	const int num_caldac_bits = 8;	/*  8 bit calibration dacs */
+	const int max_num_caldacs = 4;	/*  one caldac for every two dac channels */
 
 	/* write 3 bit channel */
 	cb_pcidda_serial_out(dev, channel, num_channel_bits);
-	// write 8 bit caldac value
+	/*  write 8 bit caldac value */
 	cb_pcidda_serial_out(dev, value, num_caldac_bits);
 
-	// latch stream into appropriate caldac
-	// deselect reference dac
+/*
+* latch stream into appropriate caldac deselect reference dac
+*/
 	cal2_bits = DESELECT_REF_DAC_BIT | DUMMY_BIT;
-	// deactivate caldacs (one caldac for every two channels)
+	/*  deactivate caldacs (one caldac for every two channels) */
 	for (i = 0; i < max_num_caldacs; i++) {
 		cal2_bits |= DESELECT_CALDAC_BIT(i);
 	}
-	// activate the caldac we want
+	/*  activate the caldac we want */
 	cal2_bits &= ~DESELECT_CALDAC_BIT(caldac);
 	outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
-	// deactivate caldac
+	/*  deactivate caldac */
 	cal2_bits |= DESELECT_CALDAC_BIT(caldac);
 	outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
 }
 
-// returns caldac that calibrates given analog out channel
+/* returns caldac that calibrates given analog out channel */
 static unsigned int caldac_number(unsigned int channel)
 {
 	return channel / 2;
 }
 
-// returns caldac channel that provides fine gain for given ao channel
+/* returns caldac channel that provides fine gain for given ao channel */
 static unsigned int fine_gain_channel(unsigned int ao_channel)
 {
 	return 4 * (ao_channel % 2);
 }
 
-// returns caldac channel that provides coarse gain for given ao channel
+/* returns caldac channel that provides coarse gain for given ao channel */
 static unsigned int coarse_gain_channel(unsigned int ao_channel)
 {
 	return 1 + 4 * (ao_channel % 2);
 }
 
-// returns caldac channel that provides coarse offset for given ao channel
+/* returns caldac channel that provides coarse offset for given ao channel */
 static unsigned int coarse_offset_channel(unsigned int ao_channel)
 {
 	return 2 + 4 * (ao_channel % 2);
 }
 
-// returns caldac channel that provides fine offset for given ao channel
+/* returns caldac channel that provides fine offset for given ao channel */
 static unsigned int fine_offset_channel(unsigned int ao_channel)
 {
 	return 3 + 4 * (ao_channel % 2);
 }
 
-// returns eeprom address that provides offset for given ao channel and range
+/* returns eeprom address that provides offset for given ao channel and range */
 static unsigned int offset_eeprom_address(unsigned int ao_channel,
 	unsigned int range)
 {
 	return 0x7 + 2 * range + 12 * ao_channel;
 }
 
-// returns eeprom address that provides gain calibration for given ao channel and range
+/* returns eeprom address that provides gain calibration for given ao channel and range */
 static unsigned int gain_eeprom_address(unsigned int ao_channel,
 	unsigned int range)
 {
 	return 0x8 + 2 * range + 12 * ao_channel;
 }
 
-// returns upper byte of eeprom entry, which gives the coarse adjustment values
+/* returns upper byte of eeprom entry, which gives the coarse adjustment values */
 static unsigned int eeprom_coarse_byte(unsigned int word)
 {
 	return (word >> 8) & 0xff;
 }
 
-// returns lower byte of eeprom entry, which gives the fine adjustment values
+/* returns lower byte of eeprom entry, which gives the fine adjustment values */
 static unsigned int eeprom_fine_byte(unsigned int word)
 {
 	return word & 0xff;
 }
 
-// set caldacs to eeprom values for given channel and range
-static void cb_pcidda_calibrate(struct comedi_device * dev, unsigned int channel,
+/* set caldacs to eeprom values for given channel and range */
+static void cb_pcidda_calibrate(struct comedi_device *dev, unsigned int channel,
 	unsigned int range)
 {
 	unsigned int coarse_offset, fine_offset, coarse_gain, fine_gain;
 
-	// remember range so we can tell when we need to readjust calibration
+	/*  remember range so we can tell when we need to readjust calibration */
 	devpriv->ao_range[channel] = range;
 
-	// get values from eeprom data
+	/*  get values from eeprom data */
 	coarse_offset =
 		eeprom_coarse_byte(devpriv->
 		eeprom_data[offset_eeprom_address(channel, range)]);
@@ -823,7 +834,7 @@
 		eeprom_fine_byte(devpriv->
 		eeprom_data[gain_eeprom_address(channel, range)]);
 
-	// set caldacs
+	/*  set caldacs */
 	cb_pcidda_write_caldac(dev, caldac_number(channel),
 		coarse_offset_channel(channel), coarse_offset);
 	cb_pcidda_write_caldac(dev, caldac_number(channel),
diff --git a/drivers/staging/comedi/drivers/cb_pcidio.c b/drivers/staging/comedi/drivers/cb_pcidio.c
index 71a4b14..dc70127 100644
--- a/drivers/staging/comedi/drivers/cb_pcidio.c
+++ b/drivers/staging/comedi/drivers/cb_pcidio.c
@@ -53,32 +53,32 @@
  * Some drivers use arrays such as this, other do not.
  */
 struct pcidio_board {
-	const char *name;	// anme of the board
-	int n_8255;		// number of 8255 chips on board
+	const char *name;	/*  anme of the board */
+	int n_8255;		/*  number of 8255 chips on board */
 
-	// indices of base address regions
+	/*  indices of base address regions */
 	int pcicontroler_badrindex;
 	int dioregs_badrindex;
 };
 
 static const struct pcidio_board pcidio_boards[] = {
 	{
-	      name:	"pci-dio24",
-	      n_8255:	1,
-	      pcicontroler_badrindex:1,
-	      dioregs_badrindex:2,
+	.name = "pci-dio24",
+	.n_8255 = 1,
+	.pcicontroler_badrindex = 1,
+	.dioregs_badrindex = 2,
 		},
 	{
-	      name:	"pci-dio24h",
-	      n_8255:	1,
-	      pcicontroler_badrindex:1,
-	      dioregs_badrindex:2,
+	.name = "pci-dio24h",
+	.n_8255 = 1,
+	.pcicontroler_badrindex = 1,
+	.dioregs_badrindex = 2,
 		},
 	{
-	      name:	"pci-dio48h",
-	      n_8255:	2,
-	      pcicontroler_badrindex:0,
-	      dioregs_badrindex:1,
+	.name = "pci-dio48h",
+	.n_8255 = 2,
+	.pcicontroler_badrindex = 0,
+	.dioregs_badrindex = 1,
 		},
 };
 
@@ -104,7 +104,7 @@
    several hardware drivers keep similar information in this structure,
    feel free to suggest moving the variable to the struct comedi_device struct.  */
 struct pcidio_private {
-	int data;		// curently unused
+	int data;		/*  curently unused */
 
 	/* would be useful for a PCI device */
 	struct pci_dev *pci_dev;
@@ -112,7 +112,7 @@
 	/* used for DO readback, curently unused */
 	unsigned int do_readback[4];	/* up to 4 unsigned int suffice to hold 96 bits for PCI-DIO96 */
 
-	unsigned long dio_reg_base;	// address of port A of the first 8255 chip on board
+	unsigned long dio_reg_base;	/*  address of port A of the first 8255 chip on board */
 };
 
 /*
@@ -127,15 +127,17 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int pcidio_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcidio_detach(struct comedi_device * dev);
+static int pcidio_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcidio_detach(struct comedi_device *dev);
 static struct comedi_driver driver_cb_pcidio = {
-      driver_name:"cb_pcidio",
-      module:THIS_MODULE,
-      attach:pcidio_attach,
-      detach:pcidio_detach,
+	.driver_name = "cb_pcidio",
+	.module = THIS_MODULE,
+	.attach = pcidio_attach,
+	.detach = pcidio_detach,
+
 /* It is not necessary to implement the following members if you are
  * writing a driver for a ISA PnP or PCI card */
+
 	/* Most drivers will support multiple types of boards by
 	 * having an array of board structures.  These were defined
 	 * in pcidio_boards[] above.  Note that the element 'name'
@@ -152,10 +154,15 @@
 	 * the type of board in software.  ISA PnP, PCI, and PCMCIA
 	 * devices are such boards.
 	 */
-// The following fields should NOT be initialized if you are dealing with PCI devices
-//      board_name:     pcidio_boards,
-//      offset:         sizeof(struct pcidio_board),
-//      num_names:      sizeof(pcidio_boards) / sizeof(struct pcidio_board),
+
+/* The following fields should NOT be initialized if you are dealing
+ * with PCI devices
+ *
+ *	.board_name = pcidio_boards,
+ *	.offset = sizeof(struct pcidio_board),
+ *	.num_names = sizeof(pcidio_boards) / sizeof(structpcidio_board),
+ */
+
 };
 
 /*------------------------------- FUNCTIONS -----------------------------------*/
@@ -166,7 +173,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int pcidio_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcidio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct pci_dev *pcidev = NULL;
 	int index;
@@ -192,19 +199,19 @@
 	for (pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL);
 		pcidev != NULL;
 		pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pcidev)) {
-		// is it not a computer boards card?
+		/*  is it not a computer boards card? */
 		if (pcidev->vendor != PCI_VENDOR_ID_CB)
 			continue;
-		// loop through cards supported by this driver
+		/*  loop through cards supported by this driver */
 		for (index = 0;
-			index < sizeof pcidio_boards / sizeof(struct pcidio_board);
+			index < ARRAY_SIZE(pcidio_boards);
 			index++) {
 			if (pcidio_pci_table[index].device != pcidev->device)
 				continue;
 
-			// was a particular bus/slot requested?
+			/*  was a particular bus/slot requested? */
 			if (it->options[0] || it->options[1]) {
-				// are we on the wrong bus/slot?
+				/*  are we on the wrong bus/slot? */
 				if (pcidev->bus->number != it->options[0] ||
 					PCI_SLOT(pcidev->devfn) !=
 					it->options[1]) {
@@ -267,7 +274,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int pcidio_detach(struct comedi_device * dev)
+static int pcidio_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: cb_pcidio: remove\n", dev->minor);
 	if (devpriv) {
diff --git a/drivers/staging/comedi/drivers/cb_pcimdas.c b/drivers/staging/comedi/drivers/cb_pcimdas.c
index af705fa..57d250c 100644
--- a/drivers/staging/comedi/drivers/cb_pcimdas.c
+++ b/drivers/staging/comedi/drivers/cb_pcimdas.c
@@ -43,29 +43,30 @@
 #include "../comedidev.h"
 
 #include <linux/delay.h>
+#include <linux/interrupt.h>
 
 #include "comedi_pci.h"
 #include "plx9052.h"
 #include "8255.h"
 
-//#define CBPCIMDAS_DEBUG
+/* #define CBPCIMDAS_DEBUG */
 #undef CBPCIMDAS_DEBUG
 
 /* Registers for the PCIM-DAS1602/16 */
 
-// sizes of io regions (bytes)
-#define BADR0_SIZE 2		//??
+/* sizes of io regions (bytes) */
+#define BADR0_SIZE 2		/* ?? */
 #define BADR1_SIZE 4
 #define BADR2_SIZE 6
 #define BADR3_SIZE 16
 #define BADR4_SIZE 4
 
-//DAC Offsets
+/* DAC Offsets */
 #define ADC_TRIG 0
 #define DAC0_OFFSET 2
 #define DAC1_OFFSET 4
 
-//AI and Counter Constants
+/* AI and Counter Constants */
 #define MUX_LIMITS 0
 #define MAIN_CONN_DIO 1
 #define ADC_STAT 2
@@ -86,37 +87,37 @@
 struct cb_pcimdas_board {
 	const char *name;
 	unsigned short device_id;
-	int ai_se_chans;	// Inputs in single-ended mode
-	int ai_diff_chans;	// Inputs in differential mode
-	int ai_bits;		// analog input resolution
-	int ai_speed;		// fastest conversion period in ns
-	int ao_nchan;		// number of analog out channels
-	int ao_bits;		// analogue output resolution
-	int has_ao_fifo;	// analog output has fifo
-	int ao_scan_speed;	// analog output speed for 1602 series (for a scan, not conversion)
-	int fifo_size;		// number of samples fifo can hold
-	int dio_bits;		// number of dio bits
-	int has_dio;		// has DIO
+	int ai_se_chans;	/*  Inputs in single-ended mode */
+	int ai_diff_chans;	/*  Inputs in differential mode */
+	int ai_bits;		/*  analog input resolution */
+	int ai_speed;		/*  fastest conversion period in ns */
+	int ao_nchan;		/*  number of analog out channels */
+	int ao_bits;		/*  analogue output resolution */
+	int has_ao_fifo;	/*  analog output has fifo */
+	int ao_scan_speed;	/*  analog output speed for 1602 series (for a scan, not conversion) */
+	int fifo_size;		/*  number of samples fifo can hold */
+	int dio_bits;		/*  number of dio bits */
+	int has_dio;		/*  has DIO */
 	const struct comedi_lrange *ranges;
 };
 
 static const struct cb_pcimdas_board cb_pcimdas_boards[] = {
 	{
-	      name:	"PCIM-DAS1602/16",
-	      device_id:0x56,
-	      ai_se_chans:16,
-	      ai_diff_chans:8,
-	      ai_bits:	16,
-	      ai_speed:10000,	//??
-	      ao_nchan:2,
-	      ao_bits:	12,
-	      has_ao_fifo:0,	//??
-	      ao_scan_speed:10000,
-			//??
-	      fifo_size:1024,
-	      dio_bits:24,
-	      has_dio:	1,
-//              ranges:         &cb_pcimdas_ranges,
+	.name = "PCIM-DAS1602/16",
+	.device_id = 0x56,
+	.ai_se_chans = 16,
+	.ai_diff_chans = 8,
+	.ai_bits = 16,
+	.ai_speed = 10000,	/* ?? */
+	.ao_nchan = 2,
+	.ao_bits = 12,
+	.has_ao_fifo = 0,	/* ?? */
+	.ao_scan_speed = 10000,
+			/* ?? */
+	.fifo_size = 1024,
+	.dio_bits = 24,
+	.has_dio = 1,
+/*	.ranges = &cb_pcimdas_ranges, */
 		},
 };
 
@@ -129,7 +130,7 @@
 
 MODULE_DEVICE_TABLE(pci, cb_pcimdas_pci_table);
 
-#define N_BOARDS 1		// Max number of boards supported
+#define N_BOARDS 1		/*  Max number of boards supported */
 
 /*
  * Useful for shorthand access to the particular board structure
@@ -142,10 +143,10 @@
 struct cb_pcimdas_private {
 	int data;
 
-	// would be useful for a PCI device
+	/*  would be useful for a PCI device */
 	struct pci_dev *pci_dev;
 
-	//base addresses
+	/* base addresses */
 	unsigned long BADR0;
 	unsigned long BADR1;
 	unsigned long BADR2;
@@ -155,11 +156,11 @@
 	/* Used for AO readback */
 	unsigned int ao_readback[2];
 
-	// Used for DIO
-	unsigned short int port_a;	// copy of BADR4+0
-	unsigned short int port_b;	// copy of BADR4+1
-	unsigned short int port_c;	// copy of BADR4+2
-	unsigned short int dio_mode;	// copy of BADR4+3
+	/*  Used for DIO */
+	unsigned short int port_a;	/*  copy of BADR4+0 */
+	unsigned short int port_b;	/*  copy of BADR4+1 */
+	unsigned short int port_c;	/*  copy of BADR4+2 */
+	unsigned short int dio_mode;	/*  copy of BADR4+3 */
 
 };
 
@@ -175,21 +176,21 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int cb_pcimdas_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int cb_pcimdas_detach(struct comedi_device * dev);
+static int cb_pcimdas_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int cb_pcimdas_detach(struct comedi_device *dev);
 static struct comedi_driver driver_cb_pcimdas = {
-      driver_name:"cb_pcimdas",
-      module:THIS_MODULE,
-      attach:cb_pcimdas_attach,
-      detach:cb_pcimdas_detach,
+	.driver_name = "cb_pcimdas",
+	.module = THIS_MODULE,
+	.attach = cb_pcimdas_attach,
+	.detach = cb_pcimdas_detach,
 };
 
-static int cb_pcimdas_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int cb_pcimdas_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int cb_pcimdas_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int cb_pcimdas_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int cb_pcimdas_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int cb_pcimdas_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 /*
  * Attach is called by the Comedi core to configure the driver
@@ -197,12 +198,12 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int cb_pcimdas_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int cb_pcimdas_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	struct pci_dev *pcidev;
 	int index;
-	//int i;
+	/* int i; */
 
 	printk("comedi%d: cb_pcimdas: ", dev->minor);
 
@@ -220,17 +221,17 @@
 	for (pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL);
 		pcidev != NULL;
 		pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pcidev)) {
-		// is it not a computer boards card?
+		/*  is it not a computer boards card? */
 		if (pcidev->vendor != PCI_VENDOR_ID_COMPUTERBOARDS)
 			continue;
-		// loop through cards supported by this driver
+		/*  loop through cards supported by this driver */
 		for (index = 0; index < N_BOARDS; index++) {
 			if (cb_pcimdas_boards[index].device_id !=
 				pcidev->device)
 				continue;
-			// was a particular bus/slot requested?
+			/*  was a particular bus/slot requested? */
 			if (it->options[0] || it->options[1]) {
-				// are we on the wrong bus/slot?
+				/*  are we on the wrong bus/slot? */
 				if (pcidev->bus->number != it->options[0] ||
 					PCI_SLOT(pcidev->devfn) !=
 					it->options[1]) {
@@ -252,7 +253,7 @@
 	printk("Found %s on bus %i, slot %i\n", cb_pcimdas_boards[index].name,
 		pcidev->bus->number, PCI_SLOT(pcidev->devfn));
 
-	// Warn about non-tested features
+	/*  Warn about non-tested features */
 	switch (thisboard->device_id) {
 	case 0x56:
 		break;
@@ -280,16 +281,16 @@
 	printk("devpriv->BADR4 = 0x%lx\n", devpriv->BADR4);
 #endif
 
-// Dont support IRQ yet
-//      // get irq
-//      if(comedi_request_irq(devpriv->pci_dev->irq, cb_pcimdas_interrupt, IRQF_SHARED, "cb_pcimdas", dev ))
-//      {
-//              printk(" unable to allocate irq %u\n", devpriv->pci_dev->irq);
-//              return -EINVAL;
-//      }
-//      dev->irq = devpriv->pci_dev->irq;
+/* Dont support IRQ yet */
+/*  get irq */
+/* if(request_irq(devpriv->pci_dev->irq, cb_pcimdas_interrupt, IRQF_SHARED, "cb_pcimdas", dev )) */
+/* { */
+/* printk(" unable to allocate irq %u\n", devpriv->pci_dev->irq); */
+/* return -EINVAL; */
+/* } */
+/* dev->irq = devpriv->pci_dev->irq; */
 
-	//Initialize dev->board_name
+	/* Initialize dev->board_name */
 	dev->board_name = thisboard->name;
 
 /*
@@ -300,24 +301,24 @@
 		return -ENOMEM;
 
 	s = dev->subdevices + 0;
-	//dev->read_subdev=s;
-	// analog input subdevice
+	/* dev->read_subdev=s; */
+	/*  analog input subdevice */
 	s->type = COMEDI_SUBD_AI;
 	s->subdev_flags = SDF_READABLE | SDF_GROUND;
 	s->n_chan = thisboard->ai_se_chans;
 	s->maxdata = (1 << thisboard->ai_bits) - 1;
 	s->range_table = &range_unknown;
-	s->len_chanlist = 1;	// This is the maximum chanlist length that
-	// the board can handle
+	s->len_chanlist = 1;	/*  This is the maximum chanlist length that */
+	/*  the board can handle */
 	s->insn_read = cb_pcimdas_ai_rinsn;
 
 	s = dev->subdevices + 1;
-	// analog output subdevice
+	/*  analog output subdevice */
 	s->type = COMEDI_SUBD_AO;
 	s->subdev_flags = SDF_WRITABLE;
 	s->n_chan = thisboard->ao_nchan;
 	s->maxdata = 1 << thisboard->ao_bits;
-	s->range_table = &range_unknown;	//ranges are hardware settable, but not software readable.
+	s->range_table = &range_unknown;	/* ranges are hardware settable, but not software readable. */
 	s->insn_write = &cb_pcimdas_ao_winsn;
 	s->insn_read = &cb_pcimdas_ao_rinsn;
 
@@ -342,7 +343,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int cb_pcimdas_detach(struct comedi_device * dev)
+static int cb_pcimdas_detach(struct comedi_device *dev)
 {
 #ifdef CBPCIMDAS_DEBUG
 	if (devpriv) {
@@ -355,7 +356,7 @@
 #endif
 	printk("comedi%d: cb_pcimdas: remove\n", dev->minor);
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	if (devpriv) {
 		if (devpriv->pci_dev) {
 			if (devpriv->BADR0) {
@@ -372,8 +373,8 @@
  * "instructions" read/write data in "one-shot" or "software-triggered"
  * mode.
  */
-static int cb_pcimdas_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int cb_pcimdas_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, i;
 	unsigned int d;
@@ -382,27 +383,27 @@
 	unsigned short chanlims;
 	int maxchans;
 
-	// only support sw initiated reads from a single channel
+	/*  only support sw initiated reads from a single channel */
 
-	//check channel number
-	if ((inb(devpriv->BADR3 + 2) & 0x20) == 0)	//differential mode
+	/* check channel number */
+	if ((inb(devpriv->BADR3 + 2) & 0x20) == 0)	/* differential mode */
 		maxchans = thisboard->ai_diff_chans;
 	else
 		maxchans = thisboard->ai_se_chans;
 
 	if (chan > (maxchans - 1))
-		return -ETIMEDOUT;	//*** Wrong error code. Fixme.
+		return -ETIMEDOUT;	/* *** Wrong error code. Fixme. */
 
-	//configure for sw initiated read
+	/* configure for sw initiated read */
 	d = inb(devpriv->BADR3 + 5);
-	if ((d & 0x03) > 0) {	//only reset if needed.
+	if ((d & 0x03) > 0) {	/* only reset if needed. */
 		d = d & 0xfd;
 		outb(d, devpriv->BADR3 + 5);
 	}
-	outb(0x01, devpriv->BADR3 + 6);	//set bursting off, conversions on
-	outb(0x00, devpriv->BADR3 + 7);	//set range to 10V. UP/BP is controlled by a switch on the board
+	outb(0x01, devpriv->BADR3 + 6);	/* set bursting off, conversions on */
+	outb(0x00, devpriv->BADR3 + 7);	/* set range to 10V. UP/BP is controlled by a switch on the board */
 
-	// write channel limits to multiplexer, set Low (bits 0-3) and High (bits 4-7) channels to chan.
+	/*  write channel limits to multiplexer, set Low (bits 0-3) and High (bits 4-7) channels to chan. */
 	chanlims = chan | (chan << 4);
 	outb(chanlims, devpriv->BADR3 + 0);
 
@@ -411,8 +412,8 @@
 		/* trigger conversion */
 		outw(0, devpriv->BADR2 + 0);
 
-#define TIMEOUT 1000		//typically takes 5 loops on a lightly loaded Pentium 100MHz,
-		//this is likely to be 100 loops on a 2GHz machine, so set 1000 as the limit.
+#define TIMEOUT 1000		/* typically takes 5 loops on a lightly loaded Pentium 100MHz, */
+		/* this is likely to be 100 loops on a 2GHz machine, so set 1000 as the limit. */
 
 		/* wait for conversion to end */
 		for (i = 0; i < TIMEOUT; i++) {
@@ -428,7 +429,7 @@
 		d = inw(devpriv->BADR2 + 0);
 
 		/* mangle the data as necessary */
-		//d ^= 1<<(thisboard->ai_bits-1); // 16 bit data from ADC, so no mangle needed.
+		/* d ^= 1<<(thisboard->ai_bits-1); // 16 bit data from ADC, so no mangle needed. */
 
 		data[n] = d;
 	}
@@ -437,8 +438,8 @@
 	return n;
 }
 
-static int cb_pcimdas_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int cb_pcimdas_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -465,8 +466,8 @@
 
 /* AO subdevices should have a read insn as well as a write insn.
  * Usually this means copying a value stored in devpriv. */
-static int cb_pcimdas_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int cb_pcimdas_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
diff --git a/drivers/staging/comedi/drivers/cb_pcimdda.c b/drivers/staging/comedi/drivers/cb_pcimdda.c
index e4c5b46..57bb118 100644
--- a/drivers/staging/comedi/drivers/cb_pcimdda.c
+++ b/drivers/staging/comedi/drivers/cb_pcimdda.c
@@ -118,15 +118,15 @@
 
 static const struct board_struct boards[] = {
 	{
-	      name:	"cb_pcimdda06-16",
-	      device_id:PCI_ID_PCIM_DDA06_16,
-	      ao_chans:6,
-	      ao_bits:	16,
-	      dio_chans:24,
-	      dio_method:DIO_8255,
-	      dio_offset:12,
-	      regs_badrindex:3,
-	      reg_sz:	16,
+	.name = "cb_pcimdda06-16",
+	.device_id = PCI_ID_PCIM_DDA06_16,
+	.ao_chans = 6,
+	.ao_bits = 16,
+	.dio_chans = 24,
+	.dio_method = DIO_8255,
+	.dio_offset = 12,
+	.regs_badrindex = 3,
+	.reg_sz = 16,
 		}
 };
 
@@ -135,8 +135,6 @@
  */
 #define thisboard    ((const struct board_struct *)dev->board_ptr)
 
-/* Number of boards in boards[] */
-#define N_BOARDS	(sizeof(boards) / sizeof(struct board_struct))
 #define REG_SZ (thisboard->reg_sz)
 #define REGS_BADRINDEX (thisboard->regs_badrindex)
 
@@ -181,13 +179,13 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int detach(struct comedi_device * dev);
+static int attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int detach(struct comedi_device *dev);
 static struct comedi_driver cb_pcimdda_driver = {
-      driver_name:"cb_pcimdda",
-      module:THIS_MODULE,
-      attach:attach,
-      detach:detach,
+	.driver_name = "cb_pcimdda",
+	.module = THIS_MODULE,
+	.attach = attach,
+	.detach = detach,
 };
 
 MODULE_AUTHOR("Calin A. Culianu <calin@rtlab.org>");
@@ -197,10 +195,10 @@
 MODULE_LICENSE("GPL");
 COMEDI_PCI_INITCLEANUP_NOMODULE(cb_pcimdda_driver, pci_table);
 
-static int ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 /*---------------------------------------------------------------------------
   HELPER FUNCTION DECLARATIONS
@@ -209,7 +207,7 @@
 /* returns a maxdata value for a given n_bits */
 static inline unsigned int figure_out_maxdata(int bits)
 {
-	return (((unsigned int) 1 << bits) - 1);
+	return ((unsigned int) 1 << bits) - 1;
 }
 
 /*
@@ -226,7 +224,7 @@
  *
  *  Otherwise, returns a -errno on error
  */
-static int probe(struct comedi_device * dev, const struct comedi_devconfig * it);
+static int probe(struct comedi_device *dev, const struct comedi_devconfig *it);
 
 /*---------------------------------------------------------------------------
   FUNCTION DEFINITIONS
@@ -238,7 +236,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int err;
@@ -257,7 +255,8 @@
  * it is, this is the place to do it.  Otherwise, dev->board_ptr
  * should already be initialized.
  */
-	if ((err = probe(dev, it)))
+	err = probe(dev, it);
+	if (err)
 		return err;
 
 /* Output some info */
@@ -326,7 +325,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int detach(struct comedi_device * dev)
+static int detach(struct comedi_device *dev)
 {
 	if (devpriv) {
 
@@ -352,8 +351,8 @@
 	return 0;
 }
 
-static int ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -391,8 +390,8 @@
    all AO channels update simultaneously.  This is useful for some control
    applications, I would imagine.
 */
-static int ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -425,7 +424,7 @@
  *
  *  Otherwise, returns a -errno on error
  */
-static int probe(struct comedi_device * dev, const struct comedi_devconfig * it)
+static int probe(struct comedi_device *dev, const struct comedi_devconfig *it)
 {
 	struct pci_dev *pcidev;
 	int index;
@@ -434,16 +433,16 @@
 	for (pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL);
 		pcidev != NULL;
 		pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pcidev)) {
-		// is it not a computer boards card?
+		/*  is it not a computer boards card? */
 		if (pcidev->vendor != PCI_VENDOR_ID_COMPUTERBOARDS)
 			continue;
-		// loop through cards supported by this driver
-		for (index = 0; index < N_BOARDS; index++) {
+		/*  loop through cards supported by this driver */
+		for (index = 0; index < ARRAY_SIZE(boards); index++) {
 			if (boards[index].device_id != pcidev->device)
 				continue;
-			// was a particular bus/slot requested?
+			/*  was a particular bus/slot requested? */
 			if (it->options[0] || it->options[1]) {
-				// are we on the wrong bus/slot?
+				/*  are we on the wrong bus/slot? */
 				if (pcidev->bus->number != it->options[0] ||
 					PCI_SLOT(pcidev->devfn) !=
 					it->options[1]) {
diff --git a/drivers/staging/comedi/drivers/comedi_bond.c b/drivers/staging/comedi/drivers/comedi_bond.c
index 1ee4898..45cd41f 100644
--- a/drivers/staging/comedi/drivers/comedi_bond.c
+++ b/drivers/staging/comedi/drivers/comedi_bond.c
@@ -210,7 +210,7 @@
 	 */
       .board_name =	&bondingBoards[0].name,
       .offset =		sizeof(struct BondingBoard),
-      .num_names =	sizeof(bondingBoards) / sizeof(struct BondingBoard),
+      .num_names =	ARRAY_SIZE(bondingBoards),
 };
 
 static int bonding_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
diff --git a/drivers/staging/comedi/drivers/comedi_fc.c b/drivers/staging/comedi/drivers/comedi_fc.c
index 9fa4cdc..8ab8e73 100644
--- a/drivers/staging/comedi/drivers/comedi_fc.c
+++ b/drivers/staging/comedi/drivers/comedi_fc.c
@@ -53,7 +53,7 @@
 
 	retval = comedi_buf_write_alloc(async, num_bytes);
 	if (retval != num_bytes) {
-		rt_printk("comedi: buffer overrun\n");
+		printk("comedi: buffer overrun\n");
 		async->events |= COMEDI_CB_OVERFLOW;
 		return 0;
 	}
diff --git a/drivers/staging/comedi/drivers/comedi_parport.c b/drivers/staging/comedi/drivers/comedi_parport.c
index a233391..f42897d 100644
--- a/drivers/staging/comedi/drivers/comedi_parport.c
+++ b/drivers/staging/comedi/drivers/comedi_parport.c
@@ -82,6 +82,7 @@
  */
 
 #include "../comedidev.h"
+#include <linux/interrupt.h>
 #include <linux/ioport.h>
 
 #define PARPORT_SIZE 3
@@ -274,7 +275,7 @@
 	return 0;
 }
 
-static irqreturn_t parport_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t parport_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s = dev->subdevices + 3;
@@ -309,8 +310,8 @@
 	irq = it->options[1];
 	if (irq) {
 		printk(" irq=%u", irq);
-		ret = comedi_request_irq(irq, parport_interrupt, 0,
-			"comedi_parport", dev);
+		ret = request_irq(irq, parport_interrupt, 0, "comedi_parport",
+				  dev);
 		if (ret < 0) {
 			printk(" irq not available\n");
 			return -EINVAL;
@@ -384,7 +385,7 @@
 		release_region(dev->iobase, PARPORT_SIZE);
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	return 0;
 }
diff --git a/drivers/staging/comedi/drivers/comedi_rt_timer.c b/drivers/staging/comedi/drivers/comedi_rt_timer.c
deleted file mode 100644
index f40c8cf..0000000
--- a/drivers/staging/comedi/drivers/comedi_rt_timer.c
+++ /dev/null
@@ -1,728 +0,0 @@
-/*
-    comedi/drivers/comedi_rt_timer.c
-    virtual driver for using RTL timing sources
-
-    Authors: David A. Schleef, Frank M. Hess
-
-    COMEDI - Linux Control and Measurement Device Interface
-    Copyright (C) 1999,2001 David A. Schleef <ds@schleef.org>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program; if not, write to the Free Software
-    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
-**************************************************************************
-*/
-/*
-Driver: comedi_rt_timer
-Description: Command emulator using real-time tasks
-Author: ds, fmhess
-Devices:
-Status: works
-
-This driver requires RTAI or RTLinux to work correctly.  It doesn't
-actually drive hardware directly, but calls other drivers and uses
-a real-time task to emulate commands for drivers and devices that
-are incapable of native commands.  Thus, you can get accurately
-timed I/O on any device.
-
-Since the timing is all done in software, sampling jitter is much
-higher than with a device that has an on-board timer, and maximum
-sample rate is much lower.
-
-Configuration options:
-  [0] - minor number of device you wish to emulate commands for
-  [1] - subdevice number you wish to emulate commands for
-*/
-/*
-TODO:
-	Support for digital io commands could be added, except I can't see why
-		anyone would want to use them
-	What happens if device we are emulating for is de-configured?
-*/
-
-#include "../comedidev.h"
-#include "../comedilib.h"
-
-#include "comedi_fc.h"
-
-#ifdef CONFIG_COMEDI_RTL_V1
-#include <rtl_sched.h>
-#include <asm/rt_irq.h>
-#endif
-#ifdef CONFIG_COMEDI_RTL
-#include <rtl.h>
-#include <rtl_sched.h>
-#include <rtl_compat.h>
-#include <asm/div64.h>
-
-#ifndef RTLINUX_VERSION_CODE
-#define RTLINUX_VERSION_CODE 0
-#endif
-#ifndef RTLINUX_VERSION
-#define RTLINUX_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
-#endif
-
-// begin hack to workaround broken HRT_TO_8254() function on rtlinux
-#if RTLINUX_VERSION_CODE <= RTLINUX_VERSION(3,0,100)
-// this function sole purpose is to divide a long long by 838
-static inline RTIME nano2count(long long ns)
-{
-	do_div(ns, 838);
-	return ns;
-}
-
-#ifdef rt_get_time()
-#undef rt_get_time()
-#endif
-#define rt_get_time() nano2count(gethrtime())
-
-#else
-
-#define nano2count(x) HRT_TO_8254(x)
-#endif
-// end hack
-
-// rtl-rtai compatibility
-#define rt_task_wait_period() rt_task_wait()
-#define rt_pend_linux_srq(irq) rtl_global_pend_irq(irq)
-#define rt_free_srq(irq) rtl_free_soft_irq(irq)
-#define rt_request_srq(x,y,z) rtl_get_soft_irq(y,"timer")
-#define rt_task_init(a,b,c,d,e,f,g) rt_task_init(a,b,c,d,(e)+1)
-#define rt_task_resume(x) rt_task_wakeup(x)
-#define rt_set_oneshot_mode()
-#define start_rt_timer(x)
-#define stop_rt_timer()
-
-#endif
-#ifdef CONFIG_COMEDI_RTAI
-#include <rtai.h>
-#include <rtai_sched.h>
-
-#if RTAI_VERSION_CODE < RTAI_MANGLE_VERSION(3,3,0)
-#define comedi_rt_task_context_t	int
-#else
-#define comedi_rt_task_context_t	long
-#endif
-
-#endif
-
-/* This defines the fastest speed we will emulate.  Note that
- * without a watchdog (like in RTAI), we could easily overrun our
- * task period because analog input tends to be slow. */
-#define SPEED_LIMIT 100000	/* in nanoseconds */
-
-static int timer_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int timer_detach(struct comedi_device * dev);
-static int timer_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
-	unsigned int trig_num);
-static int timer_start_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-
-static struct comedi_driver driver_timer = {
-      module:THIS_MODULE,
-      driver_name:"comedi_rt_timer",
-      attach:timer_attach,
-      detach:timer_detach,
-//      open:           timer_open,
-};
-
-COMEDI_INITCLEANUP(driver_timer);
-
-struct timer_private {
-	comedi_t *device;	// device we are emulating commands for
-	int subd;		// subdevice we are emulating commands for
-	RT_TASK *rt_task;	// rt task that starts scans
-	RT_TASK *scan_task;	// rt task that controls conversion timing in a scan
-	/* io_function can point to either an input or output function
-	 * depending on what kind of subdevice we are emulating for */
-	int (*io_function) (struct comedi_device * dev, struct comedi_cmd * cmd,
-		unsigned int index);
-	// RTIME has units of 1 = 838 nanoseconds
-	// time at which first scan started, used to check scan timing
-	RTIME start;
-	// time between scans
-	RTIME scan_period;
-	// time between conversions in a scan
-	RTIME convert_period;
-	// flags
-	volatile int stop;	// indicates we should stop
-	volatile int rt_task_active;	// indicates rt_task is servicing a struct comedi_cmd
-	volatile int scan_task_active;	// indicates scan_task is servicing a struct comedi_cmd
-	unsigned timer_running:1;
-};
-#define devpriv ((struct timer_private *)dev->private)
-
-static int timer_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
-{
-	devpriv->stop = 1;
-
-	return 0;
-}
-
-// checks for scan timing error
-inline static int check_scan_timing(struct comedi_device * dev,
-	unsigned long long scan)
-{
-	RTIME now, timing_error;
-
-	now = rt_get_time();
-	timing_error = now - (devpriv->start + scan * devpriv->scan_period);
-	if (timing_error > devpriv->scan_period) {
-		comedi_error(dev, "timing error");
-		rt_printk("scan started %i ns late\n", timing_error * 838);
-		return -1;
-	}
-
-	return 0;
-}
-
-// checks for conversion timing error
-inline static int check_conversion_timing(struct comedi_device * dev,
-	RTIME scan_start, unsigned int conversion)
-{
-	RTIME now, timing_error;
-
-	now = rt_get_time();
-	timing_error =
-		now - (scan_start + conversion * devpriv->convert_period);
-	if (timing_error > devpriv->convert_period) {
-		comedi_error(dev, "timing error");
-		rt_printk("conversion started %i ns late\n",
-			timing_error * 838);
-		return -1;
-	}
-
-	return 0;
-}
-
-// devpriv->io_function for an input subdevice
-static int timer_data_read(struct comedi_device * dev, struct comedi_cmd * cmd,
-	unsigned int index)
-{
-	struct comedi_subdevice *s = dev->read_subdev;
-	int ret;
-	unsigned int data;
-
-	ret = comedi_data_read(devpriv->device, devpriv->subd,
-		CR_CHAN(cmd->chanlist[index]),
-		CR_RANGE(cmd->chanlist[index]),
-		CR_AREF(cmd->chanlist[index]), &data);
-	if (ret < 0) {
-		comedi_error(dev, "read error");
-		return -EIO;
-	}
-	if (s->flags & SDF_LSAMPL) {
-		cfc_write_long_to_buffer(s, data);
-	} else {
-		comedi_buf_put(s->async, data);
-	}
-
-	return 0;
-}
-
-// devpriv->io_function for an output subdevice
-static int timer_data_write(struct comedi_device * dev, struct comedi_cmd * cmd,
-	unsigned int index)
-{
-	struct comedi_subdevice *s = dev->write_subdev;
-	unsigned int num_bytes;
-	short data;
-	unsigned int long_data;
-	int ret;
-
-	if (s->flags & SDF_LSAMPL) {
-		num_bytes =
-			cfc_read_array_from_buffer(s, &long_data,
-			sizeof(long_data));
-	} else {
-		num_bytes = cfc_read_array_from_buffer(s, &data, sizeof(data));
-		long_data = data;
-	}
-
-	if (num_bytes == 0) {
-		comedi_error(dev, "buffer underrun");
-		return -EAGAIN;
-	}
-	ret = comedi_data_write(devpriv->device, devpriv->subd,
-		CR_CHAN(cmd->chanlist[index]),
-		CR_RANGE(cmd->chanlist[index]),
-		CR_AREF(cmd->chanlist[index]), long_data);
-	if (ret < 0) {
-		comedi_error(dev, "write error");
-		return -EIO;
-	}
-
-	return 0;
-}
-
-// devpriv->io_function for DIO subdevices
-static int timer_dio_read(struct comedi_device * dev, struct comedi_cmd * cmd,
-	unsigned int index)
-{
-	struct comedi_subdevice *s = dev->read_subdev;
-	int ret;
-	unsigned int data;
-
-	ret = comedi_dio_bitfield(devpriv->device, devpriv->subd, 0, &data);
-	if (ret < 0) {
-		comedi_error(dev, "read error");
-		return -EIO;
-	}
-
-	if (s->flags & SDF_LSAMPL)
-		cfc_write_long_to_buffer(s, data);
-	else
-		cfc_write_to_buffer(s, data);
-
-	return 0;
-}
-
-// performs scans
-static void scan_task_func(comedi_rt_task_context_t d)
-{
-	struct comedi_device *dev = (struct comedi_device *) d;
-	struct comedi_subdevice *s = dev->subdevices + 0;
-	struct comedi_async *async = s->async;
-	struct comedi_cmd *cmd = &async->cmd;
-	int i, ret;
-	unsigned long long n;
-	RTIME scan_start;
-
-	// every struct comedi_cmd causes one execution of while loop
-	while (1) {
-		devpriv->scan_task_active = 1;
-		// each for loop completes one scan
-		for (n = 0; n < cmd->stop_arg || cmd->stop_src == TRIG_NONE;
-			n++) {
-			if (n) {
-				// suspend task until next scan
-				ret = rt_task_suspend(devpriv->scan_task);
-				if (ret < 0) {
-					comedi_error(dev,
-						"error suspending scan task");
-					async->events |= COMEDI_CB_ERROR;
-					goto cleanup;
-				}
-			}
-			// check if stop flag was set (by timer_cancel())
-			if (devpriv->stop)
-				goto cleanup;
-			ret = check_scan_timing(dev, n);
-			if (ret < 0) {
-				async->events |= COMEDI_CB_ERROR;
-				goto cleanup;
-			}
-			scan_start = rt_get_time();
-			for (i = 0; i < cmd->scan_end_arg; i++) {
-				// conversion timing
-				if (cmd->convert_src == TRIG_TIMER && i) {
-					rt_task_wait_period();
-					ret = check_conversion_timing(dev,
-						scan_start, i);
-					if (ret < 0) {
-						async->events |=
-							COMEDI_CB_ERROR;
-						goto cleanup;
-					}
-				}
-				ret = devpriv->io_function(dev, cmd, i);
-				if (ret < 0) {
-					async->events |= COMEDI_CB_ERROR;
-					goto cleanup;
-				}
-			}
-			s->async->events |= COMEDI_CB_BLOCK;
-			comedi_event(dev, s);
-			s->async->events = 0;
-		}
-
-	      cleanup:
-
-		comedi_unlock(devpriv->device, devpriv->subd);
-		async->events |= COMEDI_CB_EOA;
-		comedi_event(dev, s);
-		async->events = 0;
-		devpriv->scan_task_active = 0;
-		// suspend task until next struct comedi_cmd
-		rt_task_suspend(devpriv->scan_task);
-	}
-}
-
-static void timer_task_func(comedi_rt_task_context_t d)
-{
-	struct comedi_device *dev = (struct comedi_device *) d;
-	struct comedi_subdevice *s = dev->subdevices + 0;
-	struct comedi_cmd *cmd = &s->async->cmd;
-	int ret;
-	unsigned long long n;
-
-	// every struct comedi_cmd causes one execution of while loop
-	while (1) {
-		devpriv->rt_task_active = 1;
-		devpriv->scan_task_active = 1;
-		devpriv->start = rt_get_time();
-
-		for (n = 0; n < cmd->stop_arg || cmd->stop_src == TRIG_NONE;
-			n++) {
-			// scan timing
-			if (n)
-				rt_task_wait_period();
-			if (devpriv->scan_task_active == 0) {
-				goto cleanup;
-			}
-			ret = rt_task_make_periodic(devpriv->scan_task,
-				devpriv->start + devpriv->scan_period * n,
-				devpriv->convert_period);
-			if (ret < 0) {
-				comedi_error(dev, "bug!");
-			}
-		}
-
-	      cleanup:
-
-		devpriv->rt_task_active = 0;
-		// suspend until next struct comedi_cmd
-		rt_task_suspend(devpriv->rt_task);
-	}
-}
-
-static int timer_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
-{
-	struct comedi_insn xinsn = *insn;
-
-	xinsn.data = data;
-	xinsn.subdev = devpriv->subd;
-
-	return comedi_do_insn(devpriv->device, &xinsn);
-}
-
-static int cmdtest_helper(struct comedi_cmd * cmd,
-	unsigned int start_src,
-	unsigned int scan_begin_src,
-	unsigned int convert_src,
-	unsigned int scan_end_src, unsigned int stop_src)
-{
-	int err = 0;
-	int tmp;
-
-	tmp = cmd->start_src;
-	cmd->start_src &= start_src;
-	if (!cmd->start_src || tmp != cmd->start_src)
-		err++;
-
-	tmp = cmd->scan_begin_src;
-	cmd->scan_begin_src &= scan_begin_src;
-	if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
-		err++;
-
-	tmp = cmd->convert_src;
-	cmd->convert_src &= convert_src;
-	if (!cmd->convert_src || tmp != cmd->convert_src)
-		err++;
-
-	tmp = cmd->scan_end_src;
-	cmd->scan_end_src &= scan_end_src;
-	if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
-		err++;
-
-	tmp = cmd->stop_src;
-	cmd->stop_src &= stop_src;
-	if (!cmd->stop_src || tmp != cmd->stop_src)
-		err++;
-
-	return err;
-}
-
-static int timer_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
-{
-	int err = 0;
-	unsigned int start_src = 0;
-
-	if (s->type == COMEDI_SUBD_AO)
-		start_src = TRIG_INT;
-	else
-		start_src = TRIG_NOW;
-
-	err = cmdtest_helper(cmd, start_src,	/* start_src */
-		TRIG_TIMER | TRIG_FOLLOW,	/* scan_begin_src */
-		TRIG_NOW | TRIG_TIMER,	/* convert_src */
-		TRIG_COUNT,	/* scan_end_src */
-		TRIG_COUNT | TRIG_NONE);	/* stop_src */
-	if (err)
-		return 1;
-
-	/* step 2: make sure trigger sources are unique and mutually
-	 * compatible */
-
-	if (cmd->start_src != TRIG_NOW && cmd->start_src != TRIG_INT)
-		err++;
-	if (cmd->scan_begin_src != TRIG_TIMER &&
-		cmd->scan_begin_src != TRIG_FOLLOW)
-		err++;
-	if (cmd->convert_src != TRIG_TIMER && cmd->convert_src != TRIG_NOW)
-		err++;
-	if (cmd->stop_src != TRIG_COUNT && cmd->stop_src != TRIG_NONE)
-		err++;
-	if (cmd->scan_begin_src == TRIG_FOLLOW
-		&& cmd->convert_src != TRIG_TIMER)
-		err++;
-	if (cmd->convert_src == TRIG_NOW && cmd->scan_begin_src != TRIG_TIMER)
-		err++;
-
-	if (err)
-		return 2;
-
-	/* step 3: make sure arguments are trivially compatible */
-	// limit frequency, this is fairly arbitrary
-	if (cmd->scan_begin_src == TRIG_TIMER) {
-		if (cmd->scan_begin_arg < SPEED_LIMIT) {
-			cmd->scan_begin_arg = SPEED_LIMIT;
-			err++;
-		}
-	}
-	if (cmd->convert_src == TRIG_TIMER) {
-		if (cmd->convert_arg < SPEED_LIMIT) {
-			cmd->convert_arg = SPEED_LIMIT;
-			err++;
-		}
-	}
-	// make sure conversion and scan frequencies are compatible
-	if (cmd->convert_src == TRIG_TIMER && cmd->scan_begin_src == TRIG_TIMER) {
-		if (cmd->convert_arg * cmd->scan_end_arg > cmd->scan_begin_arg) {
-			cmd->scan_begin_arg =
-				cmd->convert_arg * cmd->scan_end_arg;
-			err++;
-		}
-	}
-	if (err)
-		return 3;
-
-	/* step 4: fix up and arguments */
-	if (err)
-		return 4;
-
-	return 0;
-}
-
-static int timer_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
-{
-	int ret;
-	struct comedi_cmd *cmd = &s->async->cmd;
-
-	/* hack attack: drivers are not supposed to do this: */
-	dev->rt = 1;
-
-	// make sure tasks have finished cleanup of last struct comedi_cmd
-	if (devpriv->rt_task_active || devpriv->scan_task_active)
-		return -EBUSY;
-
-	ret = comedi_lock(devpriv->device, devpriv->subd);
-	if (ret < 0) {
-		comedi_error(dev, "failed to obtain lock");
-		return ret;
-	}
-	switch (cmd->scan_begin_src) {
-	case TRIG_TIMER:
-		devpriv->scan_period = nano2count(cmd->scan_begin_arg);
-		break;
-	case TRIG_FOLLOW:
-		devpriv->scan_period =
-			nano2count(cmd->convert_arg * cmd->scan_end_arg);
-		break;
-	default:
-		comedi_error(dev, "bug setting scan period!");
-		return -1;
-		break;
-	}
-	switch (cmd->convert_src) {
-	case TRIG_TIMER:
-		devpriv->convert_period = nano2count(cmd->convert_arg);
-		break;
-	case TRIG_NOW:
-		devpriv->convert_period = 1;
-		break;
-	default:
-		comedi_error(dev, "bug setting conversion period!");
-		return -1;
-		break;
-	}
-
-	if (cmd->start_src == TRIG_NOW)
-		return timer_start_cmd(dev, s);
-
-	s->async->inttrig = timer_inttrig;
-
-	return 0;
-}
-
-static int timer_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
-	unsigned int trig_num)
-{
-	if (trig_num != 0)
-		return -EINVAL;
-
-	s->async->inttrig = NULL;
-
-	return timer_start_cmd(dev, s);
-}
-
-static int timer_start_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
-{
-	struct comedi_async *async = s->async;
-	struct comedi_cmd *cmd = &async->cmd;
-	RTIME now, delay, period;
-	int ret;
-
-	devpriv->stop = 0;
-	s->async->events = 0;
-
-	if (cmd->start_src == TRIG_NOW)
-		delay = nano2count(cmd->start_arg);
-	else
-		delay = 0;
-
-	now = rt_get_time();
-	/* Using 'period' this way gets around some weird bug in gcc-2.95.2
-	 * that generates the compile error 'internal error--unrecognizable insn'
-	 * when rt_task_make_period() is called (observed with rtlinux-3.1, linux-2.2.19).
-	 *  - fmhess */
-	period = devpriv->scan_period;
-	ret = rt_task_make_periodic(devpriv->rt_task, now + delay, period);
-	if (ret < 0) {
-		comedi_error(dev, "error starting rt_task");
-		return ret;
-	}
-	return 0;
-}
-
-static int timer_attach(struct comedi_device * dev, struct comedi_devconfig * it)
-{
-	int ret;
-	struct comedi_subdevice *s, *emul_s;
-	struct comedi_device *emul_dev;
-	/* These should probably be devconfig options[] */
-	const int timer_priority = 4;
-	const int scan_priority = timer_priority + 1;
-	char path[20];
-
-	printk("comedi%d: timer: ", dev->minor);
-
-	dev->board_name = "timer";
-
-	if ((ret = alloc_subdevices(dev, 1)) < 0)
-		return ret;
-	if ((ret = alloc_private(dev, sizeof(struct timer_private))) < 0)
-		return ret;
-
-	sprintf(path, "/dev/comedi%d", it->options[0]);
-	devpriv->device = comedi_open(path);
-	devpriv->subd = it->options[1];
-
-	printk("emulating commands for minor %i, subdevice %d\n",
-		it->options[0], devpriv->subd);
-
-	emul_dev = devpriv->device;
-	emul_s = emul_dev->subdevices + devpriv->subd;
-
-	// input or output subdevice
-	s = dev->subdevices + 0;
-	s->type = emul_s->type;
-	s->subdev_flags = emul_s->subdev_flags;	/* SDF_GROUND (to fool check_driver) */
-	s->n_chan = emul_s->n_chan;
-	s->len_chanlist = 1024;
-	s->do_cmd = timer_cmd;
-	s->do_cmdtest = timer_cmdtest;
-	s->cancel = timer_cancel;
-	s->maxdata = emul_s->maxdata;
-	s->range_table = emul_s->range_table;
-	s->range_table_list = emul_s->range_table_list;
-	switch (emul_s->type) {
-	case COMEDI_SUBD_AI:
-		s->insn_read = timer_insn;
-		dev->read_subdev = s;
-		s->subdev_flags |= SDF_CMD_READ;
-		devpriv->io_function = timer_data_read;
-		break;
-	case COMEDI_SUBD_AO:
-		s->insn_write = timer_insn;
-		s->insn_read = timer_insn;
-		dev->write_subdev = s;
-		s->subdev_flags |= SDF_CMD_WRITE;
-		devpriv->io_function = timer_data_write;
-		break;
-	case COMEDI_SUBD_DIO:
-		s->insn_write = timer_insn;
-		s->insn_read = timer_insn;
-		s->insn_bits = timer_insn;
-		dev->read_subdev = s;
-		s->subdev_flags |= SDF_CMD_READ;
-		devpriv->io_function = timer_dio_read;
-		break;
-	default:
-		comedi_error(dev, "failed to determine subdevice type!");
-		return -EINVAL;
-	}
-
-	rt_set_oneshot_mode();
-	start_rt_timer(1);
-	devpriv->timer_running = 1;
-
-	devpriv->rt_task = kzalloc(sizeof(RT_TASK), GFP_KERNEL);
-
-	// initialize real-time tasks
-	ret = rt_task_init(devpriv->rt_task, timer_task_func,
-		(comedi_rt_task_context_t) dev, 3000, timer_priority, 0, 0);
-	if (ret < 0) {
-		comedi_error(dev, "error initalizing rt_task");
-		kfree(devpriv->rt_task);
-		devpriv->rt_task = 0;
-		return ret;
-	}
-
-	devpriv->scan_task = kzalloc(sizeof(RT_TASK), GFP_KERNEL);
-
-	ret = rt_task_init(devpriv->scan_task, scan_task_func,
-		(comedi_rt_task_context_t) dev, 3000, scan_priority, 0, 0);
-	if (ret < 0) {
-		comedi_error(dev, "error initalizing scan_task");
-		kfree(devpriv->scan_task);
-		devpriv->scan_task = 0;
-		return ret;
-	}
-
-	return 1;
-}
-
-// free allocated resources
-static int timer_detach(struct comedi_device * dev)
-{
-	printk("comedi%d: timer: remove\n", dev->minor);
-
-	if (devpriv) {
-		if (devpriv->rt_task) {
-			rt_task_delete(devpriv->rt_task);
-			kfree(devpriv->rt_task);
-		}
-		if (devpriv->scan_task) {
-			rt_task_delete(devpriv->scan_task);
-			kfree(devpriv->scan_task);
-		}
-		if (devpriv->timer_running)
-			stop_rt_timer();
-		if (devpriv->device)
-			comedi_close(devpriv->device);
-	}
-	return 0;
-}
diff --git a/drivers/staging/comedi/drivers/comedi_test.c b/drivers/staging/comedi/drivers/comedi_test.c
index e679328..9b8cf62 100644
--- a/drivers/staging/comedi/drivers/comedi_test.c
+++ b/drivers/staging/comedi/drivers/comedi_test.c
@@ -55,6 +55,7 @@
 #include <asm/div64.h>
 
 #include "comedi_fc.h"
+#include <linux/timer.h>
 
 /* Board descriptions */
 struct waveform_board {
@@ -102,7 +103,7 @@
       .detach =		waveform_detach,
       .board_name =	&waveform_boards[0].name,
       .offset =		sizeof(struct waveform_board),
-      .num_names =	sizeof(waveform_boards) / sizeof(struct waveform_board),
+      .num_names =	ARRAY_SIZE(waveform_boards),
 };
 
 COMEDI_INITCLEANUP(driver_waveform);
diff --git a/drivers/staging/comedi/drivers/contec_pci_dio.c b/drivers/staging/comedi/drivers/contec_pci_dio.c
index 1f194a0..6c58e99 100644
--- a/drivers/staging/comedi/drivers/contec_pci_dio.c
+++ b/drivers/staging/comedi/drivers/contec_pci_dio.c
@@ -75,29 +75,29 @@
 
 #define devpriv ((struct contec_private *)dev->private)
 
-static int contec_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int contec_detach(struct comedi_device * dev);
+static int contec_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int contec_detach(struct comedi_device *dev);
 static struct comedi_driver driver_contec = {
-      driver_name:"contec_pci_dio",
-      module:THIS_MODULE,
-      attach:contec_attach,
-      detach:contec_detach,
+	.driver_name = "contec_pci_dio",
+	.module = THIS_MODULE,
+	.attach = contec_attach,
+	.detach = contec_detach,
 };
 
 /* Classic digital IO */
-static int contec_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int contec_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int contec_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int contec_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 #if 0
-static int contec_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
+static int contec_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
 
 static int contec_ns_to_timer(unsigned int *ns, int round);
 #endif
 
-static int contec_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int contec_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct pci_dev *pcidev;
 	struct comedi_subdevice *s;
@@ -164,7 +164,7 @@
 	return -EIO;
 }
 
-static int contec_detach(struct comedi_device * dev)
+static int contec_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: contec: remove\n", dev->minor);
 
@@ -179,8 +179,8 @@
 }
 
 #if 0
-static int contec_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int contec_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	printk("contec_cmdtest called\n");
 	return 0;
@@ -192,8 +192,8 @@
 }
 #endif
 
-static int contec_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int contec_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
 	printk("contec_do_insn_bits called\n");
@@ -205,19 +205,19 @@
 	if (data[0]) {
 		s->state &= ~data[0];
 		s->state |= data[0] & data[1];
-		rt_printk("  out: %d on %lx\n", s->state,
+		printk("  out: %d on %lx\n", s->state,
 			dev->iobase + thisboard->out_offs);
 		outw(s->state, dev->iobase + thisboard->out_offs);
 	}
 	return 2;
 }
 
-static int contec_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int contec_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
-	rt_printk("contec_di_insn_bits called\n");
-	rt_printk(" data: %d %d\n", data[0], data[1]);
+	printk("contec_di_insn_bits called\n");
+	printk(" data: %d %d\n", data[0], data[1]);
 
 	if (insn->n != 2)
 		return -EINVAL;
diff --git a/drivers/staging/comedi/drivers/daqboard2000.c b/drivers/staging/comedi/drivers/daqboard2000.c
index 3b8444f..d4526c6 100644
--- a/drivers/staging/comedi/drivers/daqboard2000.c
+++ b/drivers/staging/comedi/drivers/daqboard2000.c
@@ -119,6 +119,7 @@
 #include "../comedidev.h"
 
 #include <linux/delay.h>
+#include <linux/interrupt.h>
 
 #include "comedi_pci.h"
 #include "8255.h"
@@ -129,7 +130,7 @@
 #define DAQBOARD2000_DAQ_SIZE 		0x1002
 #define DAQBOARD2000_PLX_SIZE 		0x100
 
-// Initialization bits for the Serial EEPROM Control Register
+/* Initialization bits for the Serial EEPROM Control Register */
 #define DAQBOARD2000_SECRProgPinHi      0x8001767e
 #define DAQBOARD2000_SECRProgPinLo      0x8000767e
 #define DAQBOARD2000_SECRLocalBusHi     0xc000767e
@@ -137,14 +138,14 @@
 #define DAQBOARD2000_SECRReloadHi       0xa000767e
 #define DAQBOARD2000_SECRReloadLo       0x8000767e
 
-// SECR status bits
+/* SECR status bits */
 #define DAQBOARD2000_EEPROM_PRESENT     0x10000000
 
-// CPLD status bits
+/* CPLD status bits */
 #define DAQBOARD2000_CPLD_INIT 		0x0002
 #define DAQBOARD2000_CPLD_DONE 		0x0004
 
-// Available ranges
+/* Available ranges */
 static const struct comedi_lrange range_daqboard2000_ai = { 13, {
 			RANGE(-10, 10),
 			RANGE(-5, 5),
@@ -168,65 +169,65 @@
 };
 
 struct daqboard2000_hw {
-	volatile u16 acqControl;	// 0x00
-	volatile u16 acqScanListFIFO;	// 0x02
-	volatile u32 acqPacerClockDivLow;	// 0x04
+	volatile u16 acqControl;	/*  0x00 */
+	volatile u16 acqScanListFIFO;	/*  0x02 */
+	volatile u32 acqPacerClockDivLow;	/*  0x04 */
 
-	volatile u16 acqScanCounter;	// 0x08
-	volatile u16 acqPacerClockDivHigh;	// 0x0a
-	volatile u16 acqTriggerCount;	// 0x0c
-	volatile u16 fill2;	// 0x0e
-	volatile u16 acqResultsFIFO;	// 0x10
-	volatile u16 fill3;	// 0x12
-	volatile u16 acqResultsShadow;	// 0x14
-	volatile u16 fill4;	// 0x16
-	volatile u16 acqAdcResult;	// 0x18
-	volatile u16 fill5;	// 0x1a
-	volatile u16 dacScanCounter;	// 0x1c
-	volatile u16 fill6;	// 0x1e
+	volatile u16 acqScanCounter;	/*  0x08 */
+	volatile u16 acqPacerClockDivHigh;	/*  0x0a */
+	volatile u16 acqTriggerCount;	/*  0x0c */
+	volatile u16 fill2;	/*  0x0e */
+	volatile u16 acqResultsFIFO;	/*  0x10 */
+	volatile u16 fill3;	/*  0x12 */
+	volatile u16 acqResultsShadow;	/*  0x14 */
+	volatile u16 fill4;	/*  0x16 */
+	volatile u16 acqAdcResult;	/*  0x18 */
+	volatile u16 fill5;	/*  0x1a */
+	volatile u16 dacScanCounter;	/*  0x1c */
+	volatile u16 fill6;	/*  0x1e */
 
-	volatile u16 dacControl;	// 0x20
-	volatile u16 fill7;	// 0x22
-	volatile s16 dacFIFO;	// 0x24
-	volatile u16 fill8[2];	// 0x26
-	volatile u16 dacPacerClockDiv;	// 0x2a
-	volatile u16 refDacs;	// 0x2c
-	volatile u16 fill9;	// 0x2e
+	volatile u16 dacControl;	/*  0x20 */
+	volatile u16 fill7;	/*  0x22 */
+	volatile s16 dacFIFO;	/*  0x24 */
+	volatile u16 fill8[2];	/*  0x26 */
+	volatile u16 dacPacerClockDiv;	/*  0x2a */
+	volatile u16 refDacs;	/*  0x2c */
+	volatile u16 fill9;	/*  0x2e */
 
-	volatile u16 dioControl;	// 0x30
-	volatile s16 dioP3hsioData;	// 0x32
-	volatile u16 dioP3Control;	// 0x34
-	volatile u16 calEepromControl;	// 0x36
-	volatile s16 dacSetting[4];	// 0x38
-	volatile s16 dioP2ExpansionIO8Bit[32];	// 0x40
+	volatile u16 dioControl;	/*  0x30 */
+	volatile s16 dioP3hsioData;	/*  0x32 */
+	volatile u16 dioP3Control;	/*  0x34 */
+	volatile u16 calEepromControl;	/*  0x36 */
+	volatile s16 dacSetting[4];	/*  0x38 */
+	volatile s16 dioP2ExpansionIO8Bit[32];	/*  0x40 */
 
-	volatile u16 ctrTmrControl;	// 0x80
-	volatile u16 fill10[3];	// 0x82
-	volatile s16 ctrInput[4];	// 0x88
-	volatile u16 fill11[8];	// 0x90
-	volatile u16 timerDivisor[2];	// 0xa0
-	volatile u16 fill12[6];	// 0xa4
+	volatile u16 ctrTmrControl;	/*  0x80 */
+	volatile u16 fill10[3];	/*  0x82 */
+	volatile s16 ctrInput[4];	/*  0x88 */
+	volatile u16 fill11[8];	/*  0x90 */
+	volatile u16 timerDivisor[2];	/*  0xa0 */
+	volatile u16 fill12[6];	/*  0xa4 */
 
-	volatile u16 dmaControl;	// 0xb0
-	volatile u16 trigControl;	// 0xb2
-	volatile u16 fill13[2];	// 0xb4
-	volatile u16 calEeprom;	// 0xb8
-	volatile u16 acqDigitalMark;	// 0xba
-	volatile u16 trigDacs;	// 0xbc
-	volatile u16 fill14;	// 0xbe
-	volatile s16 dioP2ExpansionIO16Bit[32];	// 0xc0
+	volatile u16 dmaControl;	/*  0xb0 */
+	volatile u16 trigControl;	/*  0xb2 */
+	volatile u16 fill13[2];	/*  0xb4 */
+	volatile u16 calEeprom;	/*  0xb8 */
+	volatile u16 acqDigitalMark;	/*  0xba */
+	volatile u16 trigDacs;	/*  0xbc */
+	volatile u16 fill14;	/*  0xbe */
+	volatile s16 dioP2ExpansionIO16Bit[32];	/*  0xc0 */
 };
 
 /* Scan Sequencer programming */
 #define DAQBOARD2000_SeqStartScanList            0x0011
 #define DAQBOARD2000_SeqStopScanList             0x0010
 
-// Prepare for acquisition
+/* Prepare for acquisition */
 #define DAQBOARD2000_AcqResetScanListFifo        0x0004
 #define DAQBOARD2000_AcqResetResultsFifo         0x0002
 #define DAQBOARD2000_AcqResetConfigPipe          0x0001
 
-// Acqusition status bits
+/* Acqusition status bits */
 #define DAQBOARD2000_AcqResultsFIFOMore1Sample   0x0001
 #define DAQBOARD2000_AcqResultsFIFOHasValidData  0x0002
 #define DAQBOARD2000_AcqResultsFIFOOverrun       0x0004
@@ -239,7 +240,7 @@
 #define DAQBOARD2000_DacPacerOverrun             0x0200
 #define DAQBOARD2000_AcqHardwareError            0x01c0
 
-// Scan Sequencer programming
+/* Scan Sequencer programming */
 #define DAQBOARD2000_SeqStartScanList            0x0011
 #define DAQBOARD2000_SeqStopScanList             0x0010
 
@@ -254,7 +255,7 @@
 #define DAQBOARD2000_AdcPacerInternalOutEnable   0x0008
 #define DAQBOARD2000_AdcPacerExternalRising      0x0100
 
-// DAC status
+/* DAC status */
 #define DAQBOARD2000_DacFull                     0x0001
 #define DAQBOARD2000_RefBusy                     0x0002
 #define DAQBOARD2000_TrgBusy                     0x0004
@@ -264,7 +265,7 @@
 #define DAQBOARD2000_Dac2Busy                    0x0040
 #define DAQBOARD2000_Dac3Busy                    0x0080
 
-// DAC control
+/* DAC control */
 #define DAQBOARD2000_Dac0Enable                  0x0021
 #define DAQBOARD2000_Dac1Enable                  0x0031
 #define DAQBOARD2000_Dac2Enable                  0x0041
@@ -292,18 +293,18 @@
 #define DAQBOARD2000_TrigEnable                  0x0001
 #define DAQBOARD2000_TrigDisable                 0x0000
 
-// Reference Dac Selection
+/* Reference Dac Selection */
 #define DAQBOARD2000_PosRefDacSelect             0x0100
 #define DAQBOARD2000_NegRefDacSelect             0x0000
 
-static int daqboard2000_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int daqboard2000_detach(struct comedi_device * dev);
+static int daqboard2000_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int daqboard2000_detach(struct comedi_device *dev);
 
 static struct comedi_driver driver_daqboard2000 = {
-      driver_name:"daqboard2000",
-      module:THIS_MODULE,
-      attach:daqboard2000_attach,
-      detach:daqboard2000_detach,
+	.driver_name = "daqboard2000",
+	.module = THIS_MODULE,
+	.attach = daqboard2000_attach,
+	.detach = daqboard2000_detach,
 };
 
 struct daq200_boardtype {
@@ -338,17 +339,17 @@
 
 #define devpriv ((struct daqboard2000_private *)dev->private)
 
-static void writeAcqScanListEntry(struct comedi_device * dev, u16 entry)
+static void writeAcqScanListEntry(struct comedi_device *dev, u16 entry)
 {
 	struct daqboard2000_hw *fpga = devpriv->daq;
 
-//  comedi_udelay(4);
+/* udelay(4); */
 	fpga->acqScanListFIFO = entry & 0x00ff;
-//  comedi_udelay(4);
+/* udelay(4); */
 	fpga->acqScanListFIFO = (entry >> 8) & 0x00ff;
 }
 
-static void setup_sampling(struct comedi_device * dev, int chan, int gain)
+static void setup_sampling(struct comedi_device *dev, int chan, int gain)
 {
 	u16 word0, word1, word2, word3;
 
@@ -393,8 +394,8 @@
 	writeAcqScanListEntry(dev, word3);
 }
 
-static int daqboard2000_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int daqboard2000_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	struct daqboard2000_hw *fpga = devpriv->daq;
@@ -425,14 +426,14 @@
 			if (fpga->acqControl & DAQBOARD2000_AcqConfigPipeFull) {
 				break;
 			}
-			//comedi_udelay(2);
+			/* udelay(2); */
 		}
 		fpga->acqControl = DAQBOARD2000_AdcPacerEnable;
 		for (timeout = 0; timeout < 20; timeout++) {
 			if (fpga->acqControl & DAQBOARD2000_AcqLogicScanning) {
 				break;
 			}
-			//comedi_udelay(2);
+			/* udelay(2); */
 		}
 		for (timeout = 0; timeout < 20; timeout++) {
 			if (fpga->
@@ -440,7 +441,7 @@
 				DAQBOARD2000_AcqResultsFIFOHasValidData) {
 				break;
 			}
-			//comedi_udelay(2);
+			/* udelay(2); */
 		}
 		data[i] = fpga->acqResultsFIFO;
 		fpga->acqControl = DAQBOARD2000_AdcPacerDisable;
@@ -450,8 +451,8 @@
 	return i;
 }
 
-static int daqboard2000_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int daqboard2000_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -463,8 +464,8 @@
 	return i;
 }
 
-static int daqboard2000_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int daqboard2000_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -476,54 +477,54 @@
 		 * OK, since it works OK without enabling the DAC's, let's keep
 		 * it as simple as possible...
 		 */
-		//fpga->dacControl = (chan + 2) * 0x0010 | 0x0001; comedi_udelay(1000);
+		/* fpga->dacControl = (chan + 2) * 0x0010 | 0x0001; udelay(1000); */
 		fpga->dacSetting[chan] = data[i];
 		for (timeout = 0; timeout < 20; timeout++) {
 			if ((fpga->dacControl & ((chan + 1) * 0x0010)) == 0) {
 				break;
 			}
-			//comedi_udelay(2);
+			/* udelay(2); */
 		}
 		devpriv->ao_readback[chan] = data[i];
 		/*
 		 * Since we never enabled the DAC's, we don't need to disable it...
-		 * fpga->dacControl = (chan + 2) * 0x0010 | 0x0000; comedi_udelay(1000);
+		 * fpga->dacControl = (chan + 2) * 0x0010 | 0x0000; udelay(1000);
 		 */
 	}
 
 	return i;
 }
 
-static void daqboard2000_resetLocalBus(struct comedi_device * dev)
+static void daqboard2000_resetLocalBus(struct comedi_device *dev)
 {
 	printk("daqboard2000_resetLocalBus\n");
 	writel(DAQBOARD2000_SECRLocalBusHi, devpriv->plx + 0x6c);
-	comedi_udelay(10000);
+	udelay(10000);
 	writel(DAQBOARD2000_SECRLocalBusLo, devpriv->plx + 0x6c);
-	comedi_udelay(10000);
+	udelay(10000);
 }
 
-static void daqboard2000_reloadPLX(struct comedi_device * dev)
+static void daqboard2000_reloadPLX(struct comedi_device *dev)
 {
 	printk("daqboard2000_reloadPLX\n");
 	writel(DAQBOARD2000_SECRReloadLo, devpriv->plx + 0x6c);
-	comedi_udelay(10000);
+	udelay(10000);
 	writel(DAQBOARD2000_SECRReloadHi, devpriv->plx + 0x6c);
-	comedi_udelay(10000);
+	udelay(10000);
 	writel(DAQBOARD2000_SECRReloadLo, devpriv->plx + 0x6c);
-	comedi_udelay(10000);
+	udelay(10000);
 }
 
-static void daqboard2000_pulseProgPin(struct comedi_device * dev)
+static void daqboard2000_pulseProgPin(struct comedi_device *dev)
 {
 	printk("daqboard2000_pulseProgPin 1\n");
 	writel(DAQBOARD2000_SECRProgPinHi, devpriv->plx + 0x6c);
-	comedi_udelay(10000);
+	udelay(10000);
 	writel(DAQBOARD2000_SECRProgPinLo, devpriv->plx + 0x6c);
-	comedi_udelay(10000);	/* Not in the original code, but I like symmetry... */
+	udelay(10000);	/* Not in the original code, but I like symmetry... */
 }
 
-static int daqboard2000_pollCPLD(struct comedi_device * dev, int mask)
+static int daqboard2000_pollCPLD(struct comedi_device *dev, int mask)
 {
 	int result = 0;
 	int i;
@@ -536,17 +537,17 @@
 			result = 1;
 			break;
 		}
-		comedi_udelay(100);
+		udelay(100);
 	}
-	comedi_udelay(5);
+	udelay(5);
 	return result;
 }
 
-static int daqboard2000_writeCPLD(struct comedi_device * dev, int data)
+static int daqboard2000_writeCPLD(struct comedi_device *dev, int data)
 {
 	int result = 0;
 
-	comedi_udelay(10);
+	udelay(10);
 	writew(data, devpriv->daq + 0x1000);
 	if ((readw(devpriv->daq + 0x1000) & DAQBOARD2000_CPLD_INIT) ==
 		DAQBOARD2000_CPLD_INIT) {
@@ -555,7 +556,7 @@
 	return result;
 }
 
-static int initialize_daqboard2000(struct comedi_device * dev,
+static int initialize_daqboard2000(struct comedi_device *dev,
 	unsigned char *cpld_array, int len)
 {
 	int result = -EIO;
@@ -613,75 +614,75 @@
 	return result;
 }
 
-static void daqboard2000_adcStopDmaTransfer(struct comedi_device * dev)
+static void daqboard2000_adcStopDmaTransfer(struct comedi_device *dev)
 {
 /*  printk("Implement: daqboard2000_adcStopDmaTransfer\n");*/
 }
 
-static void daqboard2000_adcDisarm(struct comedi_device * dev)
+static void daqboard2000_adcDisarm(struct comedi_device *dev)
 {
 	struct daqboard2000_hw *fpga = devpriv->daq;
 
 	/* Disable hardware triggers */
-	comedi_udelay(2);
+	udelay(2);
 	fpga->trigControl = DAQBOARD2000_TrigAnalog | DAQBOARD2000_TrigDisable;
-	comedi_udelay(2);
+	udelay(2);
 	fpga->trigControl = DAQBOARD2000_TrigTTL | DAQBOARD2000_TrigDisable;
 
 	/* Stop the scan list FIFO from loading the configuration pipe */
-	comedi_udelay(2);
+	udelay(2);
 	fpga->acqControl = DAQBOARD2000_SeqStopScanList;
 
 	/* Stop the pacer clock */
-	comedi_udelay(2);
+	udelay(2);
 	fpga->acqControl = DAQBOARD2000_AdcPacerDisable;
 
 	/* Stop the input dma (abort channel 1) */
 	daqboard2000_adcStopDmaTransfer(dev);
 }
 
-static void daqboard2000_activateReferenceDacs(struct comedi_device * dev)
+static void daqboard2000_activateReferenceDacs(struct comedi_device *dev)
 {
 	struct daqboard2000_hw *fpga = devpriv->daq;
 	int timeout;
 
-	// Set the + reference dac value in the FPGA
+	/*  Set the + reference dac value in the FPGA */
 	fpga->refDacs = 0x80 | DAQBOARD2000_PosRefDacSelect;
 	for (timeout = 0; timeout < 20; timeout++) {
 		if ((fpga->dacControl & DAQBOARD2000_RefBusy) == 0) {
 			break;
 		}
-		comedi_udelay(2);
+		udelay(2);
 	}
 /*  printk("DAQBOARD2000_PosRefDacSelect %d\n", timeout);*/
 
-	// Set the - reference dac value in the FPGA
+	/*  Set the - reference dac value in the FPGA */
 	fpga->refDacs = 0x80 | DAQBOARD2000_NegRefDacSelect;
 	for (timeout = 0; timeout < 20; timeout++) {
 		if ((fpga->dacControl & DAQBOARD2000_RefBusy) == 0) {
 			break;
 		}
-		comedi_udelay(2);
+		udelay(2);
 	}
 /*  printk("DAQBOARD2000_NegRefDacSelect %d\n", timeout);*/
 }
 
-static void daqboard2000_initializeCtrs(struct comedi_device * dev)
+static void daqboard2000_initializeCtrs(struct comedi_device *dev)
 {
 /*  printk("Implement: daqboard2000_initializeCtrs\n");*/
 }
 
-static void daqboard2000_initializeTmrs(struct comedi_device * dev)
+static void daqboard2000_initializeTmrs(struct comedi_device *dev)
 {
 /*  printk("Implement: daqboard2000_initializeTmrs\n");*/
 }
 
-static void daqboard2000_dacDisarm(struct comedi_device * dev)
+static void daqboard2000_dacDisarm(struct comedi_device *dev)
 {
 /*  printk("Implement: daqboard2000_dacDisarm\n");*/
 }
 
-static void daqboard2000_initializeAdc(struct comedi_device * dev)
+static void daqboard2000_initializeAdc(struct comedi_device *dev)
 {
 	daqboard2000_adcDisarm(dev);
 	daqboard2000_activateReferenceDacs(dev);
@@ -689,7 +690,7 @@
 	daqboard2000_initializeTmrs(dev);
 }
 
-static void daqboard2000_initializeDac(struct comedi_device * dev)
+static void daqboard2000_initializeDac(struct comedi_device *dev)
 {
 	daqboard2000_dacDisarm(dev);
 }
@@ -717,7 +718,7 @@
 	return result;
 }
 
-static int daqboard2000_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int daqboard2000_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int result = 0;
 	struct comedi_subdevice *s;
@@ -772,7 +773,8 @@
 		}
 	}
 
-	if ((result = comedi_pci_enable(card, "daqboard2000")) < 0) {
+	result = comedi_pci_enable(card, "daqboard2000");
+	if (result < 0) {
 		printk(" failed to enable PCI device and request regions\n");
 		return -EIO;
 	}
@@ -849,7 +851,7 @@
 	return result;
 }
 
-static int daqboard2000_detach(struct comedi_device * dev)
+static int daqboard2000_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: daqboard2000: remove\n", dev->minor);
 
diff --git a/drivers/staging/comedi/drivers/das08.c b/drivers/staging/comedi/drivers/das08.c
index e456333..c20cd8f 100644
--- a/drivers/staging/comedi/drivers/das08.c
+++ b/drivers/staging/comedi/drivers/das08.c
@@ -65,12 +65,12 @@
 #define PCI_DEVICE_ID_PCIDAS08 0x29
 #define PCIDAS08_SIZE 0x54
 
-// pci configuration registers
+/* pci configuration registers */
 #define INTCSR               0x4c
 #define   INTR1_ENABLE         0x1
 #define   INTR1_HIGH_POLARITY  0x2
 #define   PCI_INTR_ENABLE      0x40
-#define   INTR1_EDGE_TRIG      0x100	// requires high polarity
+#define   INTR1_EDGE_TRIG      0x100	/*  requires high polarity */
 #define CNTRL                0x50
 #define   CNTRL_DIR            0x2
 #define   CNTRL_INTR           0x4
@@ -154,20 +154,20 @@
 
 /* gainlist same as _pgx_ below */
 
-static int das08_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das08_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das08_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das08jr_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das08jr_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das08jr_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das08ao_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int das08_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das08_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das08_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das08jr_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das08jr_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das08jr_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das08ao_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 static void i8254_set_mode_low(unsigned int base, int channel,
 	unsigned int mode);
 
@@ -248,211 +248,211 @@
 
 static const struct das08_board_struct das08_boards[] = {
 	{
-	      name:	"isa-das08",	// cio-das08.pdf
-	      bustype:	isa,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_pg_none,
-	      ai_encoding:das08_encode12,
-	      ao:	NULL,
-	      ao_nbits:12,
-	      di:	das08_di_rbits,
-	      do_:	das08_do_wbits,
-	      do_nchan:4,
-	      i8255_offset:8,
-	      i8254_offset:4,
-	      iosize:	16,	// unchecked
+	.name = "isa-das08",	/*  cio-das08.pdf */
+	.bustype = isa,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_pg_none,
+	.ai_encoding = das08_encode12,
+	.ao = NULL,
+	.ao_nbits = 12,
+	.di = das08_di_rbits,
+	.do_ = das08_do_wbits,
+	.do_nchan = 4,
+	.i8255_offset = 8,
+	.i8254_offset = 4,
+	.iosize = 16,	/*  unchecked */
 		},
 	{
-	      name:	"das08-pgm",	// cio-das08pgx.pdf
-	      bustype:	isa,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_pgm,
-	      ai_encoding:das08_encode12,
-	      ao:	NULL,
-	      di:	das08_di_rbits,
-	      do_:	das08_do_wbits,
-	      do_nchan:4,
-	      i8255_offset:0,
-	      i8254_offset:0x04,
-	      iosize:	16,	// unchecked
+	.name = "das08-pgm",	/*  cio-das08pgx.pdf */
+	.bustype = isa,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_pgm,
+	.ai_encoding = das08_encode12,
+	.ao = NULL,
+	.di = das08_di_rbits,
+	.do_ = das08_do_wbits,
+	.do_nchan = 4,
+	.i8255_offset = 0,
+	.i8254_offset = 0x04,
+	.iosize = 16,	/*  unchecked */
 		},
 	{
-	      name:	"das08-pgh",	// cio-das08pgx.pdf
-	      bustype:	isa,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_pgh,
-	      ai_encoding:das08_encode12,
-	      ao:	NULL,
-	      di:	das08_di_rbits,
-	      do_:	das08_do_wbits,
-	      do_nchan:4,
-	      i8255_offset:0,
-	      i8254_offset:0x04,
-	      iosize:	16,	// unchecked
+	.name = "das08-pgh",	/*  cio-das08pgx.pdf */
+	.bustype = isa,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_pgh,
+	.ai_encoding = das08_encode12,
+	.ao = NULL,
+	.di = das08_di_rbits,
+	.do_ = das08_do_wbits,
+	.do_nchan = 4,
+	.i8255_offset = 0,
+	.i8254_offset = 0x04,
+	.iosize = 16,	/*  unchecked */
 		},
 	{
-	      name:	"das08-pgl",	// cio-das08pgx.pdf
-	      bustype:	isa,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_pgl,
-	      ai_encoding:das08_encode12,
-	      ao:	NULL,
-	      di:	das08_di_rbits,
-	      do_:	das08_do_wbits,
-	      do_nchan:4,
-	      i8255_offset:0,
-	      i8254_offset:0x04,
-	      iosize:	16,	// unchecked
+	.name = "das08-pgl",	/*  cio-das08pgx.pdf */
+	.bustype = isa,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_pgl,
+	.ai_encoding = das08_encode12,
+	.ao = NULL,
+	.di = das08_di_rbits,
+	.do_ = das08_do_wbits,
+	.do_nchan = 4,
+	.i8255_offset = 0,
+	.i8254_offset = 0x04,
+	.iosize = 16,	/*  unchecked */
 		},
 	{
-	      name:	"das08-aoh",	// cio-das08_aox.pdf
-	      bustype:	isa,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_pgh,
-	      ai_encoding:das08_encode12,
-	      ao:	das08ao_ao_winsn,	// 8
-	      ao_nbits:12,
-	      di:	das08_di_rbits,
-	      do_:	das08_do_wbits,
-	      do_nchan:4,
-	      i8255_offset:0x0c,
-	      i8254_offset:0x04,
-	      iosize:	16,	// unchecked
+	.name = "das08-aoh",	/*  cio-das08_aox.pdf */
+	.bustype = isa,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_pgh,
+	.ai_encoding = das08_encode12,
+	.ao = das08ao_ao_winsn,	/*  8 */
+	.ao_nbits = 12,
+	.di = das08_di_rbits,
+	.do_ = das08_do_wbits,
+	.do_nchan = 4,
+	.i8255_offset = 0x0c,
+	.i8254_offset = 0x04,
+	.iosize = 16,	/*  unchecked */
 		},
 	{
-	      name:	"das08-aol",	// cio-das08_aox.pdf
-	      bustype:	isa,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_pgl,
-	      ai_encoding:das08_encode12,
-	      ao:	das08ao_ao_winsn,	// 8
-	      ao_nbits:12,
-	      di:	das08_di_rbits,
-	      do_:	das08_do_wbits,
-	      do_nchan:4,
-	      i8255_offset:0x0c,
-	      i8254_offset:0x04,
-	      iosize:	16,	// unchecked
+	.name = "das08-aol",	/*  cio-das08_aox.pdf */
+	.bustype = isa,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_pgl,
+	.ai_encoding = das08_encode12,
+	.ao = das08ao_ao_winsn,	/*  8 */
+	.ao_nbits = 12,
+	.di = das08_di_rbits,
+	.do_ = das08_do_wbits,
+	.do_nchan = 4,
+	.i8255_offset = 0x0c,
+	.i8254_offset = 0x04,
+	.iosize = 16,	/*  unchecked */
 		},
 	{
-	      name:	"das08-aom",	// cio-das08_aox.pdf
-	      bustype:	isa,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_pgm,
-	      ai_encoding:das08_encode12,
-	      ao:	das08ao_ao_winsn,	// 8
-	      ao_nbits:12,
-	      di:	das08_di_rbits,
-	      do_:	das08_do_wbits,
-	      do_nchan:4,
-	      i8255_offset:0x0c,
-	      i8254_offset:0x04,
-	      iosize:	16,	// unchecked
+	.name = "das08-aom",	/*  cio-das08_aox.pdf */
+	.bustype = isa,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_pgm,
+	.ai_encoding = das08_encode12,
+	.ao = das08ao_ao_winsn,	/*  8 */
+	.ao_nbits = 12,
+	.di = das08_di_rbits,
+	.do_ = das08_do_wbits,
+	.do_nchan = 4,
+	.i8255_offset = 0x0c,
+	.i8254_offset = 0x04,
+	.iosize = 16,	/*  unchecked */
 		},
 	{
-	      name:	"das08/jr-ao",	// cio-das08-jr-ao.pdf
-	      bustype:	isa,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_pg_none,
-	      ai_encoding:das08_encode12,
-	      ao:	das08jr_ao_winsn,
-	      ao_nbits:12,
-	      di:	das08jr_di_rbits,
-	      do_:	das08jr_do_wbits,
-	      do_nchan:8,
-	      i8255_offset:0,
-	      i8254_offset:0,
-	      iosize:	16,	// unchecked
+	.name = "das08/jr-ao",	/*  cio-das08-jr-ao.pdf */
+	.bustype = isa,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_pg_none,
+	.ai_encoding = das08_encode12,
+	.ao = das08jr_ao_winsn,
+	.ao_nbits = 12,
+	.di = das08jr_di_rbits,
+	.do_ = das08jr_do_wbits,
+	.do_nchan = 8,
+	.i8255_offset = 0,
+	.i8254_offset = 0,
+	.iosize = 16,	/*  unchecked */
 		},
 	{
-	      name:	"das08jr-16-ao",	// cio-das08jr-16-ao.pdf
-	      bustype:	isa,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:16,
-	      ai_pg:	das08_pg_none,
-	      ai_encoding:das08_encode12,
-	      ao:	das08jr_ao_winsn,
-	      ao_nbits:16,
-	      di:	das08jr_di_rbits,
-	      do_:	das08jr_do_wbits,
-	      do_nchan:8,
-	      i8255_offset:0,
-	      i8254_offset:0x04,
-	      iosize:	16,	// unchecked
+	.name = "das08jr-16-ao",	/*  cio-das08jr-16-ao.pdf */
+	.bustype = isa,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 16,
+	.ai_pg = das08_pg_none,
+	.ai_encoding = das08_encode12,
+	.ao = das08jr_ao_winsn,
+	.ao_nbits = 16,
+	.di = das08jr_di_rbits,
+	.do_ = das08jr_do_wbits,
+	.do_nchan = 8,
+	.i8255_offset = 0,
+	.i8254_offset = 0x04,
+	.iosize = 16,	/*  unchecked */
 		},
 #ifdef CONFIG_COMEDI_PCI
 	{
-	      name:	"das08",	// pci-das08
-	      id:	PCI_DEVICE_ID_PCIDAS08,
-	      bustype:	pci,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_bipolar5,
-	      ai_encoding:das08_encode12,
-	      ao:	NULL,
-	      ao_nbits:0,
-	      di:	das08_di_rbits,
-	      do_:	das08_do_wbits,
-	      do_nchan:4,
-	      i8255_offset:0,
-	      i8254_offset:4,
-	      iosize:	8,
+	.name = "das08",	/*  pci-das08 */
+	.id = PCI_DEVICE_ID_PCIDAS08,
+	.bustype = pci,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_bipolar5,
+	.ai_encoding = das08_encode12,
+	.ao = NULL,
+	.ao_nbits = 0,
+	.di = das08_di_rbits,
+	.do_ = das08_do_wbits,
+	.do_nchan = 4,
+	.i8255_offset = 0,
+	.i8254_offset = 4,
+	.iosize = 8,
 		},
 #endif
 	{
-	      name:	"pc104-das08",
-	      bustype:	pc104,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_pg_none,
-	      ai_encoding:das08_encode12,
-	      ao:	NULL,
-	      ao_nbits:0,
-	      di:	das08_di_rbits,
-	      do_:	das08_do_wbits,
-	      do_nchan:4,
-	      i8255_offset:0,
-	      i8254_offset:4,
-	      iosize:	16,	// unchecked
+	.name = "pc104-das08",
+	.bustype = pc104,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_pg_none,
+	.ai_encoding = das08_encode12,
+	.ao = NULL,
+	.ao_nbits = 0,
+	.di = das08_di_rbits,
+	.do_ = das08_do_wbits,
+	.do_nchan = 4,
+	.i8255_offset = 0,
+	.i8254_offset = 4,
+	.iosize = 16,	/*  unchecked */
 		},
 #if 0
 	{
-	      name:	"das08/f",
+	.name = "das08/f",
 		},
 	{
-	      name:	"das08jr",
+	.name = "das08jr",
 		},
 #endif
 	{
-	      name:	"das08jr/16",
-	      bustype:	isa,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:16,
-	      ai_pg:	das08_pg_none,
-	      ai_encoding:das08_encode16,
-	      ao:	NULL,
-	      ao_nbits:0,
-	      di:	das08jr_di_rbits,
-	      do_:	das08jr_do_wbits,
-	      do_nchan:8,
-	      i8255_offset:0,
-	      i8254_offset:0,
-	      iosize:	16,	// unchecked
+	.name = "das08jr/16",
+	.bustype = isa,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 16,
+	.ai_pg = das08_pg_none,
+	.ai_encoding = das08_encode16,
+	.ao = NULL,
+	.ao_nbits = 0,
+	.di = das08jr_di_rbits,
+	.do_ = das08jr_do_wbits,
+	.do_nchan = 8,
+	.i8255_offset = 0,
+	.i8254_offset = 0,
+	.iosize = 16,	/*  unchecked */
 		},
 #if 0
 	{
-	      name:	"das48-pga",	// cio-das48-pga.pdf
+	.name = "das48-pga",	/*  cio-das48-pga.pdf */
 		},
 	{
-	      name:	"das08-pga-g2",	// a KM board
+	.name = "das08-pga-g2",	/*  a KM board */
 		},
 #endif
 };
@@ -460,39 +460,39 @@
 #ifdef CONFIG_COMEDI_PCMCIA
 struct das08_board_struct das08_cs_boards[NUM_DAS08_CS_BOARDS] = {
 	{
-	      name:	"pcm-das08",
-	      id:	0x0,	// XXX
-	      bustype:	pcmcia,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_bipolar5,
-	      ai_encoding:das08_pcm_encode12,
-	      ao:	NULL,
-	      ao_nbits:0,
-	      di:	das08_di_rbits,
-	      do_:	das08_do_wbits,
-	      do_nchan:3,
-	      i8255_offset:0,
-	      i8254_offset:0,
-	      iosize:	16,
+	.name = "pcm-das08",
+	.id = 0x0,	/*  XXX */
+	.bustype = pcmcia,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_bipolar5,
+	.ai_encoding = das08_pcm_encode12,
+	.ao = NULL,
+	.ao_nbits = 0,
+	.di = das08_di_rbits,
+	.do_ = das08_do_wbits,
+	.do_nchan = 3,
+	.i8255_offset = 0,
+	.i8254_offset = 0,
+	.iosize = 16,
 		},
-	// duplicate so driver name can be used also
+	/*  duplicate so driver name can be used also */
 	{
-	      name:	"das08_cs",
-	      id:	0x0,	// XXX
-	      bustype:	pcmcia,
-	      ai:	das08_ai_rinsn,
-	      ai_nbits:12,
-	      ai_pg:	das08_bipolar5,
-	      ai_encoding:das08_pcm_encode12,
-	      ao:	NULL,
-	      ao_nbits:0,
-	      di:	das08_di_rbits,
-	      do_:	das08_do_wbits,
-	      do_nchan:3,
-	      i8255_offset:0,
-	      i8254_offset:0,
-	      iosize:	16,
+	.name = "das08_cs",
+	.id = 0x0,	/*  XXX */
+	.bustype = pcmcia,
+	.ai = das08_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_pg = das08_bipolar5,
+	.ai_encoding = das08_pcm_encode12,
+	.ao = NULL,
+	.ao_nbits = 0,
+	.di = das08_di_rbits,
+	.do_ = das08_do_wbits,
+	.do_nchan = 3,
+	.i8255_offset = 0,
+	.i8254_offset = 0,
+	.iosize = 16,
 		},
 };
 #endif
@@ -512,8 +512,8 @@
 
 #define TIMEOUT 100000
 
-static int das08_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das08_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, n;
 	int chan;
@@ -528,7 +528,7 @@
 	inb(dev->iobase + DAS08_MSB);
 
 	/* set multiplexer */
-	spin_lock(&dev->spinlock);	// lock to prevent race with digital output
+	spin_lock(&dev->spinlock);	/*  lock to prevent race with digital output */
 	devpriv->do_mux_bits &= ~DAS08_MUX_MASK;
 	devpriv->do_mux_bits |= DAS08_MUX(chan);
 	outb(devpriv->do_mux_bits, dev->iobase + DAS08_CONTROL);
@@ -545,7 +545,7 @@
 		/* clear over-range bits for 16-bit boards */
 		if (thisboard->ai_nbits == 16)
 			if (inb(dev->iobase + DAS08_MSB) & 0x80)
-				rt_printk("das08: over-range\n");
+				printk("das08: over-range\n");
 
 		/* trigger conversion */
 		outb_p(0, dev->iobase + DAS08_TRIG_12BIT);
@@ -555,7 +555,7 @@
 				break;
 		}
 		if (i == TIMEOUT) {
-			rt_printk("das08: timeout\n");
+			printk("das08: timeout\n");
 			return -ETIME;
 		}
 		msb = inb(dev->iobase + DAS08_MSB);
@@ -579,8 +579,8 @@
 	return n;
 }
 
-static int das08_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das08_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = 0;
 	data[1] = DAS08_IP(inb(dev->iobase + DAS08_STATUS));
@@ -588,19 +588,19 @@
 	return 2;
 }
 
-static int das08_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das08_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int wbits;
 
-	// get current settings of digital output lines
+	/*  get current settings of digital output lines */
 	wbits = (devpriv->do_mux_bits >> 4) & 0xf;
-	// null bits we are going to set
+	/*  null bits we are going to set */
 	wbits &= ~data[0];
-	// set new bit values
+	/*  set new bit values */
 	wbits |= data[0] & data[1];
-	// remember digital output bits
-	spin_lock(&dev->spinlock);	// prevent race with setting of analog input mux
+	/*  remember digital output bits */
+	spin_lock(&dev->spinlock);	/*  prevent race with setting of analog input mux */
 	devpriv->do_mux_bits &= ~DAS08_DO_MASK;
 	devpriv->do_mux_bits |= DAS08_OP(wbits);
 	outb(devpriv->do_mux_bits, dev->iobase + DAS08_CONTROL);
@@ -611,8 +611,8 @@
 	return 2;
 }
 
-static int das08jr_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das08jr_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = 0;
 	data[1] = inb(dev->iobase + DAS08JR_DIO);
@@ -620,12 +620,12 @@
 	return 2;
 }
 
-static int das08jr_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das08jr_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	// null bits we are going to set
+	/*  null bits we are going to set */
 	devpriv->do_bits &= ~data[0];
-	// set new bit values
+	/*  set new bit values */
 	devpriv->do_bits |= data[0] & data[1];
 	outb(devpriv->do_bits, dev->iobase + DAS08JR_DIO);
 
@@ -634,8 +634,8 @@
 	return 2;
 }
 
-static int das08jr_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das08jr_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int lsb, msb;
@@ -668,8 +668,8 @@
  * a different method to force an update.
  *
  */
-static int das08ao_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das08ao_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int lsb, msb;
@@ -782,31 +782,31 @@
 	return i8254_read_status_low(st->iobase, chan);
 }
 
-static int das08_counter_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das08_counter_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = insn->chanspec;
 
-	//printk("Reading counter channel %d ",chan);
+	/* printk("Reading counter channel %d ",chan); */
 	data[0] = i8254_read_channel(&devpriv->i8254, chan);
-	//printk("=> 0x%08X\n",data[0]);
+	/* printk("=> 0x%08X\n",data[0]); */
 
 	return 1;
 }
 
-static int das08_counter_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das08_counter_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = insn->chanspec;
 
-	//printk("Writing counter channel %d with 0x%04X\n",chan,data[0]);
+	/* printk("Writing counter channel %d with 0x%04X\n",chan,data[0]); */
 	i8254_write_channel(&devpriv->i8254, chan, data[0]);
 
 	return 1;
 }
 
-static int das08_counter_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das08_counter_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = insn->chanspec;
 
@@ -827,25 +827,25 @@
 	return 2;
 }
 
-static int das08_attach(struct comedi_device * dev, struct comedi_devconfig * it);
+static int das08_attach(struct comedi_device *dev, struct comedi_devconfig *it);
 
 static struct comedi_driver driver_das08 = {
-      driver_name: DRV_NAME,
-      module:THIS_MODULE,
-      attach:das08_attach,
-      detach:das08_common_detach,
-      board_name:&das08_boards[0].name,
-      num_names:sizeof(das08_boards) /
+	.driver_name = DRV_NAME,
+	.module = THIS_MODULE,
+	.attach = das08_attach,
+	.detach = das08_common_detach,
+	.board_name = &das08_boards[0].name,
+	.num_names = sizeof(das08_boards) /
 		sizeof(struct das08_board_struct),
-      offset:sizeof(struct das08_board_struct),
+	.offset = sizeof(struct das08_board_struct),
 };
 
-int das08_common_attach(struct comedi_device * dev, unsigned long iobase)
+int das08_common_attach(struct comedi_device *dev, unsigned long iobase)
 {
 	struct comedi_subdevice *s;
 	int ret;
 
-	// allocate ioports for non-pcmcia, non-pci boards
+	/*  allocate ioports for non-pcmcia, non-pci boards */
 	if ((thisboard->bustype != pcmcia) && (thisboard->bustype != pci)) {
 		printk(" iobase 0x%lx\n", iobase);
 		if (!request_region(iobase, thisboard->iosize, DRV_NAME)) {
@@ -857,7 +857,8 @@
 
 	dev->board_name = thisboard->name;
 
-	if ((ret = alloc_subdevices(dev, 6)) < 0)
+	ret = alloc_subdevices(dev, 6);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -880,7 +881,7 @@
 	/* ao */
 	if (thisboard->ao) {
 		s->type = COMEDI_SUBD_AO;
-// XXX lacks read-back insn
+/* XXX lacks read-back insn */
 		s->subdev_flags = SDF_WRITABLE;
 		s->n_chan = 2;
 		s->maxdata = (1 << thisboard->ao_nbits) - 1;
@@ -952,7 +953,7 @@
 	return 0;
 }
 
-static int das08_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int das08_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int ret;
 	unsigned long iobase;
@@ -961,11 +962,12 @@
 	struct pci_dev *pdev;
 #endif
 
-	if ((ret = alloc_private(dev, sizeof(struct das08_private_struct))) < 0)
+	ret = alloc_private(dev, sizeof(struct das08_private_struct));
+	if (ret < 0)
 		return ret;
 
 	printk("comedi%d: das08: ", dev->minor);
-	// deal with a pci board
+	/*  deal with a pci board */
 	if (thisboard->bustype == pci) {
 #ifdef CONFIG_COMEDI_PCI
 		if (it->options[0] || it->options[1]) {
@@ -973,7 +975,7 @@
 				it->options[0], it->options[1]);
 		}
 		printk("\n");
-		// find card
+		/*  find card */
 		for (pdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL);
 			pdev != NULL;
 			pdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pdev)) {
@@ -995,12 +997,12 @@
 			return -EIO;
 		}
 		devpriv->pdev = pdev;
-		// enable PCI device and reserve I/O spaces
+		/*  enable PCI device and reserve I/O spaces */
 		if (comedi_pci_enable(pdev, DRV_NAME)) {
 			printk(" Error enabling PCI device and requesting regions\n");
 			return -EIO;
 		}
-		// read base addresses
+		/*  read base addresses */
 		pci_iobase = pci_resource_start(pdev, 1);
 		iobase = pci_resource_start(pdev, 2);
 		printk("pcibase 0x%lx  iobase 0x%lx\n", pci_iobase, iobase);
@@ -1028,14 +1030,14 @@
 	return das08_common_attach(dev, iobase);
 }
 
-int das08_common_detach(struct comedi_device * dev)
+int das08_common_detach(struct comedi_device *dev)
 {
 	printk(KERN_INFO "comedi%d: das08: remove\n", dev->minor);
 
 	if (dev->subdevices)
 		subdev_8255_cleanup(dev, dev->subdevices + 4);
 
-	// deallocate ioports for non-pcmcia, non-pci boards
+	/*  deallocate ioports for non-pcmcia, non-pci boards */
 	if ((thisboard->bustype != pcmcia) && (thisboard->bustype != pci)) {
 		if (dev->iobase)
 			release_region(dev->iobase, thisboard->iosize);
diff --git a/drivers/staging/comedi/drivers/das08.h b/drivers/staging/comedi/drivers/das08.h
index 69089ce..7cdb3fc 100644
--- a/drivers/staging/comedi/drivers/das08.h
+++ b/drivers/staging/comedi/drivers/das08.h
@@ -25,14 +25,14 @@
 #define _DAS08_H
 
 enum das08_bustype { isa, pci, pcmcia, pc104 };
-// different ways ai data is encoded in first two registers
+/* different ways ai data is encoded in first two registers */
 enum das08_ai_encoding { das08_encode12, das08_encode16, das08_pcm_encode12 };
 enum das08_lrange { das08_pg_none, das08_bipolar5, das08_pgh, das08_pgl,
 		das08_pgm };
 
 struct das08_board_struct {
 	const char *name;
-	unsigned int id;	// id for pci/pcmcia boards
+	unsigned int id;	/*  id for pci/pcmcia boards */
 	enum das08_bustype bustype;
 	void *ai;
 	unsigned int ai_nbits;
@@ -45,13 +45,13 @@
 	unsigned int do_nchan;
 	unsigned int i8255_offset;
 	unsigned int i8254_offset;
-	unsigned int iosize;	// number of ioports used
+	unsigned int iosize;	/*  number of ioports used */
 };
 
 struct i8254_struct {
-	int channels;		// available channels. Some could be used internally.
-	int logic2phys[3];	// to know which physical channel is.
-	int mode[3];		// the index is the real counter.
+	int channels;		/*  available channels. Some could be used internally. */
+	int logic2phys[3];	/*  to know which physical channel is. */
+	int mode[3];		/*  the index is the real counter. */
 	unsigned int iobase;
 };
 
@@ -61,18 +61,18 @@
 #define I8254_CTRL 3
 
 struct das08_private_struct {
-	unsigned int do_mux_bits;	// bits for do/mux register on boards without seperate do register
-	unsigned int do_bits;	// bits for do register on boards with register dedicated to digital out only
+	unsigned int do_mux_bits;	/*  bits for do/mux register on boards without seperate do register */
+	unsigned int do_bits;	/*  bits for do register on boards with register dedicated to digital out only */
 	const unsigned int *pg_gainlist;
-	struct pci_dev *pdev;	// struct for pci-das08
-	unsigned int pci_iobase;	// additional base address for pci-das08
+	struct pci_dev *pdev;	/*  struct for pci-das08 */
+	unsigned int pci_iobase;	/*  additional base address for pci-das08 */
 	struct i8254_struct i8254;
 };
 
 #define NUM_DAS08_CS_BOARDS 2
 extern struct das08_board_struct das08_cs_boards[NUM_DAS08_CS_BOARDS];
 
-int das08_common_attach(struct comedi_device * dev, unsigned long iobase);
-int das08_common_detach(struct comedi_device * dev);
+int das08_common_attach(struct comedi_device *dev, unsigned long iobase);
+int das08_common_detach(struct comedi_device *dev);
 
 #endif /* _DAS08_H */
diff --git a/drivers/staging/comedi/drivers/das08_cs.c b/drivers/staging/comedi/drivers/das08_cs.c
index be6c887..8e44641 100644
--- a/drivers/staging/comedi/drivers/das08_cs.c
+++ b/drivers/staging/comedi/drivers/das08_cs.c
@@ -46,7 +46,7 @@
 
 #include "das08.h"
 
-// pcmcia includes
+/* pcmcia includes */
 #include <pcmcia/cs_types.h>
 #include <pcmcia/cs.h>
 #include <pcmcia/cistpl.h>
@@ -56,30 +56,31 @@
 
 #define thisboard ((const struct das08_board_struct *)dev->board_ptr)
 
-static int das08_cs_attach(struct comedi_device * dev, struct comedi_devconfig * it);
+static int das08_cs_attach(struct comedi_device *dev, struct comedi_devconfig *it);
 
 static struct comedi_driver driver_das08_cs = {
-      driver_name:"das08_cs",
-      module:THIS_MODULE,
-      attach:das08_cs_attach,
-      detach:das08_common_detach,
-      board_name:&das08_cs_boards[0].name,
-      num_names:sizeof(das08_cs_boards) /
+	.driver_name = "das08_cs",
+	.module = THIS_MODULE,
+	.attach = das08_cs_attach,
+	.detach = das08_common_detach,
+	.board_name = &das08_cs_boards[0].name,
+	.num_names = sizeof(das08_cs_boards) /
 		sizeof(struct das08_board_struct),
-      offset:sizeof(struct das08_board_struct),
+	.offset = sizeof(struct das08_board_struct),
 };
 
-static int das08_cs_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int das08_cs_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int ret;
 	unsigned long iobase;
-	struct pcmcia_device *link = cur_dev;	// XXX hack
+	struct pcmcia_device *link = cur_dev;	/*  XXX hack */
 
-	if ((ret = alloc_private(dev, sizeof(struct das08_private_struct))) < 0)
+	ret = alloc_private(dev, sizeof(struct das08_private_struct));
+	if (ret < 0)
 		return ret;
 
 	printk("comedi%d: das08_cs: ", dev->minor);
-	// deal with a pci board
+	/*  deal with a pci board */
 
 	if (thisboard->bustype == pcmcia) {
 		if (link == NULL) {
@@ -264,14 +265,23 @@
 	tuple.TupleDataMax = sizeof(buf);
 	tuple.TupleOffset = 0;
 	last_fn = GetFirstTuple;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple)) != 0)
+
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret)
 		goto cs_failed;
+
 	last_fn = GetTupleData;
-	if ((last_ret = pcmcia_get_tuple_data(link, &tuple)) != 0)
+
+	last_ret = pcmcia_get_tuple_data(link, &tuple);
+	if (last_ret)
 		goto cs_failed;
+
 	last_fn = ParseTuple;
-	if ((last_ret = pcmcia_parse_tuple(&tuple, &parse)) != 0)
+
+	last_ret = pcmcia_parse_tuple(&tuple, &parse);
+	if (last_ret)
 		goto cs_failed;
+
 	link->conf.ConfigBase = parse.config.base;
 	link->conf.Present = parse.config.rmask[0];
 
@@ -289,13 +299,20 @@
 	 */
 	tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
 	last_fn = GetFirstTuple;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple)) != 0)
+
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret)
 		goto cs_failed;
+
 	while (1) {
 		cistpl_cftable_entry_t *cfg = &(parse.cftable_entry);
-		if ((last_ret = pcmcia_get_tuple_data(link, &tuple)) != 0)
+
+		last_ret = pcmcia_get_tuple_data(link, &tuple);
+		if (last_ret)
 			goto next_entry;
-		if ((last_ret = pcmcia_parse_tuple(&tuple, &parse)) != 0)
+
+		last_ret = pcmcia_parse_tuple(&tuple, &parse);
+		if (last_ret)
 			goto next_entry;
 
 		if (cfg->flags & CISTPL_CFTABLE_DEFAULT)
@@ -341,13 +358,16 @@
 
 	      next_entry:
 		last_fn = GetNextTuple;
-		if ((last_ret = pcmcia_get_next_tuple(link, &tuple)) != 0)
+
+		last_ret = pcmcia_get_next_tuple(link, &tuple);
+		if (last_ret)
 			goto cs_failed;
 	}
 
 	if (link->conf.Attributes & CONF_ENABLE_IRQ) {
 		last_fn = RequestIRQ;
-		if ((last_ret = pcmcia_request_irq(link, &link->irq)) != 0)
+		last_ret = pcmcia_request_irq(link, &link->irq);
+		if (last_ret)
 			goto cs_failed;
 	}
 
@@ -357,7 +377,8 @@
 	   card and host interface into "Memory and IO" mode.
 	 */
 	last_fn = RequestConfiguration;
-	if ((last_ret = pcmcia_request_configuration(link, &link->conf)) != 0)
+	last_ret = pcmcia_request_configuration(link, &link->conf);
+	if (last_ret)
 		goto cs_failed;
 
 	/*
diff --git a/drivers/staging/comedi/drivers/das16.c b/drivers/staging/comedi/drivers/das16.c
index 6b6b042..59af86a 100644
--- a/drivers/staging/comedi/drivers/das16.c
+++ b/drivers/staging/comedi/drivers/das16.c
@@ -79,6 +79,7 @@
 */
 
 #include <linux/pci.h>
+#include <linux/interrupt.h>
 #include <asm/dma.h>
 #include "../comedidev.h"
 
@@ -87,16 +88,16 @@
 #include "comedi_fc.h"
 
 #undef DEBUG
-//#define DEBUG
+/* #define DEBUG */
 
 #ifdef DEBUG
-#define DEBUG_PRINT(format, args...) rt_printk("das16: " format, ## args)
+#define DEBUG_PRINT(format, args...) printk("das16: " format, ## args)
 #else
 #define DEBUG_PRINT(format, args...)
 #endif
 
-#define DAS16_SIZE 20		// number of ioports
-#define DAS16_DMA_SIZE 0xff00	// size in bytes of allocated dma buffer
+#define DAS16_SIZE 20		/*  number of ioports */
+#define DAS16_DMA_SIZE 0xff00	/*  size in bytes of allocated dma buffer */
 
 /*
     cio-das16.pdf
@@ -184,7 +185,7 @@
 
 */
 
-static const int sample_size = 2;	// size in bytes of a sample from board
+static const int sample_size = 2;	/*  size in bytes of a sample from board */
 
 #define DAS16_TRIG		0
 #define DAS16_AI_LSB		0
@@ -265,7 +266,7 @@
 	}
 };
 static const struct comedi_lrange range_das16jr = { 9, {
-			// also used by 16/330
+			/*  also used by 16/330 */
 			BIP_RANGE(10),
 			BIP_RANGE(5),
 			BIP_RANGE(2.5),
@@ -326,40 +327,40 @@
 	unsigned have_byte:1;
 };
 
-static int das16_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das16_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das16_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das16_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int das16_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das16_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das16_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das16_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int das16_cmd_test(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int das16_cmd_exec(struct comedi_device * dev, struct comedi_subdevice * s);
-static int das16_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static void das16_ai_munge(struct comedi_device * dev, struct comedi_subdevice * s,
+static int das16_cmd_test(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int das16_cmd_exec(struct comedi_device *dev, struct comedi_subdevice *s);
+static int das16_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static void das16_ai_munge(struct comedi_device *dev, struct comedi_subdevice *s,
 	void *array, unsigned int num_bytes, unsigned int start_chan_index);
 
-static void das16_reset(struct comedi_device * dev);
-static irqreturn_t das16_dma_interrupt(int irq, void *d PT_REGS_ARG);
+static void das16_reset(struct comedi_device *dev);
+static irqreturn_t das16_dma_interrupt(int irq, void *d);
 static void das16_timer_interrupt(unsigned long arg);
-static void das16_interrupt(struct comedi_device * dev);
+static void das16_interrupt(struct comedi_device *dev);
 
-static unsigned int das16_set_pacer(struct comedi_device * dev, unsigned int ns,
+static unsigned int das16_set_pacer(struct comedi_device *dev, unsigned int ns,
 	int flags);
-static int das1600_mode_detect(struct comedi_device * dev);
-static unsigned int das16_suggest_transfer_size(struct comedi_device * dev,
+static int das1600_mode_detect(struct comedi_device *dev);
+static unsigned int das16_suggest_transfer_size(struct comedi_device *dev,
 	struct comedi_cmd cmd);
 
-static void reg_dump(struct comedi_device * dev);
+static void reg_dump(struct comedi_device *dev);
 
 struct das16_board {
 	const char *name;
 	void *ai;
 	unsigned int ai_nbits;
-	unsigned int ai_speed;	// max conversion speed in nanosec
+	unsigned int ai_speed;	/*  max conversion speed in nanosec */
 	unsigned int ai_pg;
 	void *ao;
 	unsigned int ao_nbits;
@@ -375,339 +376,337 @@
 
 static const struct das16_board das16_boards[] = {
 	{
-	      name:	"das-16",
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:15000,
-	      ai_pg:	das16_pg_none,
-	      ao:	das16_ao_winsn,
-	      ao_nbits:12,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x10,
-	      i8254_offset:0x0c,
-	      size:	0x14,
-	      id:	0x00,
+	.name = "das-16",
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 15000,
+	.ai_pg = das16_pg_none,
+	.ao = das16_ao_winsn,
+	.ao_nbits = 12,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x10,
+	.i8254_offset = 0x0c,
+	.size = 0x14,
+	.id = 0x00,
 		},
 	{
-	      name:	"das-16g",
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:15000,
-	      ai_pg:	das16_pg_none,
-	      ao:	das16_ao_winsn,
-	      ao_nbits:12,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x10,
-	      i8254_offset:0x0c,
-	      size:	0x14,
-	      id:	0x00,
+	.name = "das-16g",
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 15000,
+	.ai_pg = das16_pg_none,
+	.ao = das16_ao_winsn,
+	.ao_nbits = 12,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x10,
+	.i8254_offset = 0x0c,
+	.size = 0x14,
+	.id = 0x00,
 		},
 	{
-	      name:	"das-16f",
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:8500,
-	      ai_pg:	das16_pg_none,
-	      ao:	das16_ao_winsn,
-	      ao_nbits:12,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x10,
-	      i8254_offset:0x0c,
-	      size:	0x14,
-	      id:	0x00,
+	.name = "das-16f",
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 8500,
+	.ai_pg = das16_pg_none,
+	.ao = das16_ao_winsn,
+	.ao_nbits = 12,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x10,
+	.i8254_offset = 0x0c,
+	.size = 0x14,
+	.id = 0x00,
 		},
 	{
-	      name:	"cio-das16",	// cio-das16.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:20000,
-	      ai_pg:	das16_pg_none,
-	      ao:	das16_ao_winsn,
-	      ao_nbits:12,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x10,
-	      i8254_offset:0x0c,
-	      size:	0x14,
-	      id:	0x80,
+	.name = "cio-das16",	/*  cio-das16.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 20000,
+	.ai_pg = das16_pg_none,
+	.ao = das16_ao_winsn,
+	.ao_nbits = 12,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x10,
+	.i8254_offset = 0x0c,
+	.size = 0x14,
+	.id = 0x80,
 		},
 	{
-	      name:	"cio-das16/f",	// das16.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:10000,
-	      ai_pg:	das16_pg_none,
-	      ao:	das16_ao_winsn,
-	      ao_nbits:12,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x10,
-	      i8254_offset:0x0c,
-	      size:	0x14,
-	      id:	0x80,
+	.name = "cio-das16/f",	/*  das16.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 10000,
+	.ai_pg = das16_pg_none,
+	.ao = das16_ao_winsn,
+	.ao_nbits = 12,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x10,
+	.i8254_offset = 0x0c,
+	.size = 0x14,
+	.id = 0x80,
 		},
 	{
-	      name:	"cio-das16/jr",	// cio-das16jr.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:7692,
-	      ai_pg:	das16_pg_16jr,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0,
-	      i8254_offset:0x0c,
-	      size:	0x10,
-	      id:	0x00,
+	.name = "cio-das16/jr",	/*  cio-das16jr.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 7692,
+	.ai_pg = das16_pg_16jr,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0,
+	.i8254_offset = 0x0c,
+	.size = 0x10,
+	.id = 0x00,
 		},
 	{
-	      name:	"pc104-das16jr",	// pc104-das16jr_xx.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:3300,
-	      ai_pg:	das16_pg_16jr,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0,
-	      i8254_offset:0x0c,
-	      size:	0x10,
-	      id:	0x00,
+	.name = "pc104-das16jr",	/*  pc104-das16jr_xx.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 3300,
+	.ai_pg = das16_pg_16jr,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0,
+	.i8254_offset = 0x0c,
+	.size = 0x10,
+	.id = 0x00,
 		},
 	{
-	      name:	"cio-das16jr/16",	// cio-das16jr_16.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:16,
-	      ai_speed:10000,
-	      ai_pg:	das16_pg_16jr_16,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0,
-	      i8254_offset:0x0c,
-	      size:	0x10,
-	      id:	0x00,
+	.name = "cio-das16jr/16",	/*  cio-das16jr_16.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 16,
+	.ai_speed = 10000,
+	.ai_pg = das16_pg_16jr_16,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0,
+	.i8254_offset = 0x0c,
+	.size = 0x10,
+	.id = 0x00,
 		},
 	{
-	      name:	"pc104-das16jr/16",	// pc104-das16jr_xx.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:16,
-	      ai_speed:10000,
-	      ai_pg:	das16_pg_16jr_16,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0,
-	      i8254_offset:0x0c,
-	      size:	0x10,
-	      id:	0x00,
+	.name = "pc104-das16jr/16",	/*  pc104-das16jr_xx.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 16,
+	.ai_speed = 10000,
+	.ai_pg = das16_pg_16jr_16,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0,
+	.i8254_offset = 0x0c,
+	.size = 0x10,
+	.id = 0x00,
 		},
 	{
-	      name:	"das-1201",	// 4924.pdf (keithley user's manual)
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:20000,
-	      ai_pg:	das16_pg_none,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x400,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-	      id:	0x20,
+	.name = "das-1201",	/*  4924.pdf (keithley user's manual) */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 20000,
+	.ai_pg = das16_pg_none,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x400,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0x20,
 		},
 	{
-	      name:	"das-1202",	// 4924.pdf (keithley user's manual)
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:10000,
-	      ai_pg:	das16_pg_none,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x400,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-	      id:	0x20,
+	.name = "das-1202",	/*  4924.pdf (keithley user's manual) */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 10000,
+	.ai_pg = das16_pg_none,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x400,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0x20,
 		},
 	{
-	      name:	"das-1401",	// 4919.pdf and 4922.pdf (keithley user's manual)
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:10000,
-	      ai_pg:	das16_pg_1601,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x0,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-	      id:	0xc0	// 4919.pdf says id bits are 0xe0, 4922.pdf says 0xc0
+	.name = "das-1401",	/*  4919.pdf and 4922.pdf (keithley user's manual) */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 10000,
+	.ai_pg = das16_pg_1601,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x0,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0xc0	/*  4919.pdf says id bits are 0xe0, 4922.pdf says 0xc0 */
 		},
 	{
-	      name:	"das-1402",	// 4919.pdf and 4922.pdf (keithley user's manual)
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:10000,
-	      ai_pg:	das16_pg_1602,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x0,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-	      id:	0xc0	// 4919.pdf says id bits are 0xe0, 4922.pdf says 0xc0
+	.name = "das-1402",	/*  4919.pdf and 4922.pdf (keithley user's manual) */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 10000,
+	.ai_pg = das16_pg_1602,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x0,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0xc0	/*  4919.pdf says id bits are 0xe0, 4922.pdf says 0xc0 */
 		},
 	{
-	      name:	"das-1601",	// 4919.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:10000,
-	      ai_pg:	das16_pg_1601,
-	      ao:	das16_ao_winsn,
-	      ao_nbits:12,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x400,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-      id:	0xc0},
+	.name = "das-1601",	/*  4919.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 10000,
+	.ai_pg = das16_pg_1601,
+	.ao = das16_ao_winsn,
+	.ao_nbits = 12,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x400,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0xc0},
 	{
-	      name:	"das-1602",	// 4919.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:10000,
-	      ai_pg:	das16_pg_1602,
-	      ao:	das16_ao_winsn,
-	      ao_nbits:12,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x400,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-      id:	0xc0},
+	.name = "das-1602",	/*  4919.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 10000,
+	.ai_pg = das16_pg_1602,
+	.ao = das16_ao_winsn,
+	.ao_nbits = 12,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x400,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0xc0},
 	{
-	      name:	"cio-das1401/12",	// cio-das1400_series.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:6250,
-	      ai_pg:	das16_pg_1601,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-      id:	0xc0},
+	.name = "cio-das1401/12",	/*  cio-das1400_series.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 6250,
+	.ai_pg = das16_pg_1601,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0xc0},
 	{
-	      name:	"cio-das1402/12",	// cio-das1400_series.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:6250,
-	      ai_pg:	das16_pg_1602,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-      id:	0xc0},
+	.name = "cio-das1402/12",	/*  cio-das1400_series.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 6250,
+	.ai_pg = das16_pg_1602,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0xc0},
 	{
-	      name:	"cio-das1402/16",	// cio-das1400_series.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:16,
-	      ai_speed:10000,
-	      ai_pg:	das16_pg_1602,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-      id:	0xc0},
+	.name = "cio-das1402/16",	/*  cio-das1400_series.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 16,
+	.ai_speed = 10000,
+	.ai_pg = das16_pg_1602,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0xc0},
 	{
-	      name:	"cio-das1601/12",	// cio-das160x-1x.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:6250,
-	      ai_pg:	das16_pg_1601,
-	      ao:	das16_ao_winsn,
-	      ao_nbits:12,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x400,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-      id:	0xc0},
+	.name = "cio-das1601/12",	/*  cio-das160x-1x.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 6250,
+	.ai_pg = das16_pg_1601,
+	.ao = das16_ao_winsn,
+	.ao_nbits = 12,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x400,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0xc0},
 	{
-	      name:	"cio-das1602/12",	// cio-das160x-1x.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:10000,
-	      ai_pg:	das16_pg_1602,
-	      ao:	das16_ao_winsn,
-	      ao_nbits:12,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x400,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-      id:	0xc0},
+	.name = "cio-das1602/12",	/*  cio-das160x-1x.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 10000,
+	.ai_pg = das16_pg_1602,
+	.ao = das16_ao_winsn,
+	.ao_nbits = 12,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x400,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0xc0},
 	{
-	      name:	"cio-das1602/16",	// cio-das160x-1x.pdf
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:16,
-	      ai_speed:10000,
-	      ai_pg:	das16_pg_1602,
-	      ao:	das16_ao_winsn,
-	      ao_nbits:12,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0x400,
-	      i8254_offset:0x0c,
-	      size:	0x408,
-      id:	0xc0},
+	.name = "cio-das1602/16",	/*  cio-das160x-1x.pdf */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 16,
+	.ai_speed = 10000,
+	.ai_pg = das16_pg_1602,
+	.ao = das16_ao_winsn,
+	.ao_nbits = 12,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0x400,
+	.i8254_offset = 0x0c,
+	.size = 0x408,
+	.id = 0xc0},
 	{
-	      name:	"cio-das16/330",	// ?
-	      ai:	das16_ai_rinsn,
-	      ai_nbits:12,
-	      ai_speed:3030,
-	      ai_pg:	das16_pg_16jr,
-	      ao:	NULL,
-	      di:	das16_di_rbits,
-	      do_:	das16_do_wbits,
-	      i8255_offset:0,
-	      i8254_offset:0x0c,
-	      size:	0x14,
-      id:	0xf0},
+	.name = "cio-das16/330",	/*  ? */
+	.ai = das16_ai_rinsn,
+	.ai_nbits = 12,
+	.ai_speed = 3030,
+	.ai_pg = das16_pg_16jr,
+	.ao = NULL,
+	.di = das16_di_rbits,
+	.do_ = das16_do_wbits,
+	.i8255_offset = 0,
+	.i8254_offset = 0x0c,
+	.size = 0x14,
+	.id = 0xf0},
 #if 0
 	{
-	      name:	"das16/330i",	// ?
+	.name = "das16/330i",	/*  ? */
 		},
 	{
-	      name:	"das16/jr/ctr5",	// ?
+	.name = "das16/jr/ctr5",	/*  ? */
 		},
 	{
-	      name:	"cio-das16/m1/16",	// cio-das16_m1_16.pdf, this board is a bit quirky, no dma
+	.name = "cio-das16/m1/16",	/*  cio-das16_m1_16.pdf, this board is a bit quirky, no dma */
 		},
 #endif
 };
 
-#define n_das16_boards ((sizeof(das16_boards))/(sizeof(struct das16_board)))
-
-static int das16_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int das16_detach(struct comedi_device * dev);
+static int das16_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int das16_detach(struct comedi_device *dev);
 static struct comedi_driver driver_das16 = {
-      driver_name:"das16",
-      module:THIS_MODULE,
-      attach:das16_attach,
-      detach:das16_detach,
-      board_name:&das16_boards[0].name,
-      num_names:n_das16_boards,
-      offset:sizeof(das16_boards[0]),
+	.driver_name = "das16",
+	.module = THIS_MODULE,
+	.attach = das16_attach,
+	.detach = das16_detach,
+	.board_name = &das16_boards[0].name,
+	.num_names = ARRAY_SIZE(das16_boards),
+	.offset = sizeof(das16_boards[0]),
 };
 
 #define DAS16_TIMEOUT 1000
@@ -719,31 +718,31 @@
 	return HZ / 20;
 }
 struct das16_private_struct {
-	unsigned int ai_unipolar;	// unipolar flag
-	unsigned int ai_singleended;	// single ended flag
-	unsigned int clockbase;	// master clock speed in ns
-	volatile unsigned int control_state;	// dma, interrupt and trigger control bits
-	volatile unsigned long adc_byte_count;	// number of bytes remaining
-	unsigned int divisor1;	// divisor dividing master clock to get conversion frequency
-	unsigned int divisor2;	// divisor dividing master clock to get conversion frequency
-	unsigned int dma_chan;	// dma channel
+	unsigned int ai_unipolar;	/*  unipolar flag */
+	unsigned int ai_singleended;	/*  single ended flag */
+	unsigned int clockbase;	/*  master clock speed in ns */
+	volatile unsigned int control_state;	/*  dma, interrupt and trigger control bits */
+	volatile unsigned long adc_byte_count;	/*  number of bytes remaining */
+	unsigned int divisor1;	/*  divisor dividing master clock to get conversion frequency */
+	unsigned int divisor2;	/*  divisor dividing master clock to get conversion frequency */
+	unsigned int dma_chan;	/*  dma channel */
 	uint16_t *dma_buffer[2];
 	dma_addr_t dma_buffer_addr[2];
 	unsigned int current_buffer;
-	volatile unsigned int dma_transfer_size;	// target number of bytes to transfer per dma shot
-	// user-defined analog input and output ranges defined from config options
+	volatile unsigned int dma_transfer_size;	/*  target number of bytes to transfer per dma shot */
+	/*  user-defined analog input and output ranges defined from config options */
 	struct comedi_lrange *user_ai_range_table;
 	struct comedi_lrange *user_ao_range_table;
 
-	struct timer_list timer;	// for timed interrupt
+	struct timer_list timer;	/*  for timed interrupt */
 	volatile short timer_running;
-	volatile short timer_mode;	// true if using timer mode
+	volatile short timer_mode;	/*  true if using timer mode */
 };
 #define devpriv ((struct das16_private_struct *)(dev->private))
 #define thisboard ((struct das16_board *)(dev->board_ptr))
 
-static int das16_cmd_test(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int das16_cmd_test(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0, tmp;
 	int gain, start_chan, i;
@@ -757,7 +756,7 @@
 
 	tmp = cmd->scan_begin_src;
 	mask = TRIG_FOLLOW;
-	// if board supports burst mode
+	/*  if board supports burst mode */
 	if (thisboard->size > 0x400)
 		mask |= TRIG_TIMER | TRIG_EXT;
 	cmd->scan_begin_src &= mask;
@@ -766,7 +765,7 @@
 
 	tmp = cmd->convert_src;
 	mask = TRIG_TIMER | TRIG_EXT;
-	// if board supports burst mode
+	/*  if board supports burst mode */
 	if (thisboard->size > 0x400)
 		mask |= TRIG_NOW;
 	cmd->convert_src &= mask;
@@ -797,7 +796,7 @@
 	if (cmd->stop_src != TRIG_NONE && cmd->stop_src != TRIG_COUNT)
 		err++;
 
-	// make sure scan_begin_src and convert_src dont conflict
+	/*  make sure scan_begin_src and convert_src dont conflict */
 	if (cmd->scan_begin_src == TRIG_FOLLOW && cmd->convert_src == TRIG_NOW)
 		err++;
 	if (cmd->scan_begin_src != TRIG_FOLLOW && cmd->convert_src != TRIG_NOW)
@@ -824,7 +823,7 @@
 		cmd->scan_end_arg = cmd->chanlist_len;
 		err++;
 	}
-	// check against maximum frequency
+	/*  check against maximum frequency */
 	if (cmd->scan_begin_src == TRIG_TIMER) {
 		if (cmd->scan_begin_arg <
 			thisboard->ai_speed * cmd->chanlist_len) {
@@ -849,10 +848,10 @@
 	if (err)
 		return 3;
 
-	// step 4: fix up arguments
+	/*  step 4: fix up arguments */
 	if (cmd->scan_begin_src == TRIG_TIMER) {
 		unsigned int tmp = cmd->scan_begin_arg;
-		// set divisors, correct timing arguments
+		/*  set divisors, correct timing arguments */
 		i8253_cascade_ns_to_timer_2div(devpriv->clockbase,
 			&(devpriv->divisor1), &(devpriv->divisor2),
 			&(cmd->scan_begin_arg), cmd->flags & TRIG_ROUND_MASK);
@@ -860,7 +859,7 @@
 	}
 	if (cmd->convert_src == TRIG_TIMER) {
 		unsigned int tmp = cmd->convert_arg;
-		// set divisors, correct timing arguments
+		/*  set divisors, correct timing arguments */
 		i8253_cascade_ns_to_timer_2div(devpriv->clockbase,
 			&(devpriv->divisor1), &(devpriv->divisor2),
 			&(cmd->convert_arg), cmd->flags & TRIG_ROUND_MASK);
@@ -869,7 +868,7 @@
 	if (err)
 		return 4;
 
-	// check channel/gain list against card's limitations
+	/*  check channel/gain list against card's limitations */
 	if (cmd->chanlist) {
 		gain = CR_RANGE(cmd->chanlist[0]);
 		start_chan = CR_CHAN(cmd->chanlist[0]);
@@ -893,7 +892,7 @@
 	return 0;
 }
 
-static int das16_cmd_exec(struct comedi_device * dev, struct comedi_subdevice * s)
+static int das16_cmd_exec(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_async *async = s->async;
 	struct comedi_cmd *cmd = &async->cmd;
@@ -916,11 +915,11 @@
 	devpriv->adc_byte_count =
 		cmd->stop_arg * cmd->chanlist_len * sizeof(uint16_t);
 
-	// disable conversions for das1600 mode
+	/*  disable conversions for das1600 mode */
 	if (thisboard->size > 0x400) {
 		outb(DAS1600_CONV_DISABLE, dev->iobase + DAS1600_CONV);
 	}
-	// set scan limits
+	/*  set scan limits */
 	byte = CR_CHAN(cmd->chanlist[0]);
 	byte |= CR_CHAN(cmd->chanlist[cmd->chanlist_len - 1]) << 4;
 	outb(byte, dev->iobase + DAS16_MUX);
@@ -945,7 +944,7 @@
 	if (thisboard->size > 0x400) {
 		if (cmd->convert_src == TRIG_NOW) {
 			outb(DAS1600_BURST_VAL, dev->iobase + DAS1600_BURST);
-			// set burst length
+			/*  set burst length */
 			byte |= BURST_LEN_BITS(cmd->chanlist_len - 1);
 		} else {
 			outb(0, dev->iobase + DAS1600_BURST);
@@ -953,7 +952,7 @@
 	}
 	outb(byte, dev->iobase + DAS16_PACER);
 
-	// set up dma transfer
+	/*  set up dma transfer */
 	flags = claim_dma_lock();
 	disable_dma(devpriv->dma_chan);
 	/* clear flip-flop to make sure 2-byte registers for
@@ -962,13 +961,13 @@
 	devpriv->current_buffer = 0;
 	set_dma_addr(devpriv->dma_chan,
 		devpriv->dma_buffer_addr[devpriv->current_buffer]);
-	// set appropriate size of transfer
+	/*  set appropriate size of transfer */
 	devpriv->dma_transfer_size = das16_suggest_transfer_size(dev, *cmd);
 	set_dma_count(devpriv->dma_chan, devpriv->dma_transfer_size);
 	enable_dma(devpriv->dma_chan);
 	release_dma_lock(flags);
 
-	// set up interrupt
+	/*  set up interrupt */
 	if (devpriv->timer_mode) {
 		devpriv->timer_running = 1;
 		devpriv->timer.expires = jiffies + timer_period();
@@ -996,18 +995,18 @@
 	return 0;
 }
 
-static int das16_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int das16_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	/* disable interrupts, dma and pacer clocked conversions */
 	devpriv->control_state &= ~DAS16_INTE & ~PACING_MASK & ~DMA_ENABLE;
 	outb(devpriv->control_state, dev->iobase + DAS16_CONTROL);
 	if (devpriv->dma_chan)
 		disable_dma(devpriv->dma_chan);
 
-	// disable SW timer
+	/*  disable SW timer */
 	if (devpriv->timer_mode && devpriv->timer_running) {
 		devpriv->timer_running = 0;
 		del_timer(&devpriv->timer);
@@ -1018,12 +1017,12 @@
 		outb(0, dev->iobase + DAS1600_BURST);
 	}
 
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	return 0;
 }
 
-static void das16_reset(struct comedi_device * dev)
+static void das16_reset(struct comedi_device *dev)
 {
 	outb(0, dev->iobase + DAS16_STATUS);
 	outb(0, dev->iobase + DAS16_CONTROL);
@@ -1031,15 +1030,15 @@
 	outb(0, dev->iobase + DAS16_CNTR_CONTROL);
 }
 
-static int das16_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, n;
 	int range;
 	int chan;
 	int msb, lsb;
 
-	// disable interrupts and pacing
+	/*  disable interrupts and pacing */
 	devpriv->control_state &= ~DAS16_INTE & ~DMA_ENABLE & ~PACING_MASK;
 	outb(devpriv->control_state, dev->iobase + DAS16_CONTROL);
 
@@ -1064,7 +1063,7 @@
 				break;
 		}
 		if (i == DAS16_TIMEOUT) {
-			rt_printk("das16: timeout\n");
+			printk("das16: timeout\n");
 			return -ETIME;
 		}
 		msb = inb(dev->iobase + DAS16_AI_MSB);
@@ -1079,8 +1078,8 @@
 	return n;
 }
 
-static int das16_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int bits;
 
@@ -1091,17 +1090,17 @@
 	return 2;
 }
 
-static int das16_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int wbits;
 
-	// only set bits that have been masked
+	/*  only set bits that have been masked */
 	data[0] &= 0xf;
 	wbits = s->state;
-	// zero bits that have been masked
+	/*  zero bits that have been masked */
 	wbits &= ~data[0];
-	// set masked bits
+	/*  set masked bits */
 	wbits |= data[0] & data[1];
 	s->state = wbits;
 	data[1] = wbits;
@@ -1111,8 +1110,8 @@
 	return 2;
 }
 
-static int das16_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int lsb, msb;
@@ -1135,7 +1134,7 @@
 	return i;
 }
 
-static irqreturn_t das16_dma_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t das16_dma_interrupt(int irq, void *d)
 {
 	int status;
 	struct comedi_device *dev = d;
@@ -1169,7 +1168,7 @@
 	an even transfer count after disabling dma
 	channel.
 */
-static int disable_dma_on_even(struct comedi_device * dev)
+static int disable_dma_on_even(struct comedi_device *dev)
 {
 	int residue;
 	int i;
@@ -1182,7 +1181,7 @@
 		enable_dma(devpriv->dma_chan);
 		for (j = 0; j < enable_timeout; ++j) {
 			int new_residue;
-			comedi_udelay(2);
+			udelay(2);
 			new_residue = get_dma_residue(devpriv->dma_chan);
 			if (new_residue != residue)
 				break;
@@ -1197,7 +1196,7 @@
 	return residue;
 }
 
-static void das16_interrupt(struct comedi_device * dev)
+static void das16_interrupt(struct comedi_device *dev)
 {
 	unsigned long dma_flags, spin_flags;
 	struct comedi_subdevice *s = dev->read_subdev;
@@ -1210,7 +1209,7 @@
 		comedi_error(dev, "premature interrupt");
 		return;
 	}
-	// initialize async here to make sure it is not NULL
+	/*  initialize async here to make sure it is not NULL */
 	async = s->async;
 	cmd = &async->cmd;
 
@@ -1219,9 +1218,9 @@
 		return;
 	}
 
-	comedi_spin_lock_irqsave(&dev->spinlock, spin_flags);
+	spin_lock_irqsave(&dev->spinlock, spin_flags);
 	if ((devpriv->control_state & DMA_ENABLE) == 0) {
-		comedi_spin_unlock_irqrestore(&dev->spinlock, spin_flags);
+		spin_unlock_irqrestore(&dev->spinlock, spin_flags);
 		DEBUG_PRINT("interrupt while dma disabled?\n");
 		return;
 	}
@@ -1230,7 +1229,7 @@
 	clear_dma_ff(devpriv->dma_chan);
 	residue = disable_dma_on_even(dev);
 
-	// figure out how many points to read
+	/*  figure out how many points to read */
 	if (residue > devpriv->dma_transfer_size) {
 		comedi_error(dev, "residue > transfer size!\n");
 		async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
@@ -1247,12 +1246,12 @@
 	devpriv->current_buffer = (devpriv->current_buffer + 1) % 2;
 	devpriv->adc_byte_count -= num_bytes;
 
-	// figure out how many bytes for next transfer
+	/*  figure out how many bytes for next transfer */
 	if (cmd->stop_src == TRIG_COUNT && devpriv->timer_mode == 0 &&
 		devpriv->dma_transfer_size > devpriv->adc_byte_count)
 		devpriv->dma_transfer_size = devpriv->adc_byte_count;
 
-	// re-enable  dma
+	/*  re-enable  dma */
 	if ((async->events & COMEDI_CB_EOA) == 0) {
 		set_dma_addr(devpriv->dma_chan,
 			devpriv->dma_buffer_addr[devpriv->current_buffer]);
@@ -1265,7 +1264,7 @@
 	}
 	release_dma_lock(dma_flags);
 
-	comedi_spin_unlock_irqrestore(&dev->spinlock, spin_flags);
+	spin_unlock_irqrestore(&dev->spinlock, spin_flags);
 
 	cfc_write_array_to_buffer(s,
 		devpriv->dma_buffer[buffer_index], num_bytes);
@@ -1273,7 +1272,7 @@
 	cfc_handle_events(dev, s);
 }
 
-static unsigned int das16_set_pacer(struct comedi_device * dev, unsigned int ns,
+static unsigned int das16_set_pacer(struct comedi_device *dev, unsigned int ns,
 	int rounding_flags)
 {
 	i8253_cascade_ns_to_timer_2div(devpriv->clockbase, &(devpriv->divisor1),
@@ -1286,7 +1285,7 @@
 	return ns;
 }
 
-static void reg_dump(struct comedi_device * dev)
+static void reg_dump(struct comedi_device *dev)
 {
 	DEBUG_PRINT("********DAS1600 REGISTER DUMP********\n");
 	DEBUG_PRINT("DAS16_MUX: %x\n", inb(dev->iobase + DAS16_MUX));
@@ -1304,7 +1303,7 @@
 		inb(dev->iobase + DAS1600_STATUS_B));
 }
 
-static int das16_probe(struct comedi_device * dev, struct comedi_devconfig * it)
+static int das16_probe(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int status;
 	int diobits;
@@ -1338,7 +1337,7 @@
 	return 0;
 }
 
-static int das1600_mode_detect(struct comedi_device * dev)
+static int das1600_mode_detect(struct comedi_device *dev)
 {
 	int status = 0;
 
@@ -1366,7 +1365,7 @@
  *   3  Clock speed (in MHz)
  */
 
-static int das16_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int das16_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int ret;
@@ -1391,7 +1390,7 @@
 
 	printk("comedi%d: das16:", dev->minor);
 
-	// check that clock setting is valid
+	/*  check that clock setting is valid */
 	if (it->options[3]) {
 		if (it->options[3] != 0 &&
 			it->options[3] != 1 && it->options[3] != 10) {
@@ -1400,7 +1399,8 @@
 		}
 	}
 
-	if ((ret = alloc_private(dev, sizeof(struct das16_private_struct))) < 0)
+	ret = alloc_private(dev, sizeof(struct das16_private_struct));
+	if (ret < 0)
 		return ret;
 
 	if (thisboard->size < 0x400) {
@@ -1431,27 +1431,28 @@
 
 	dev->iobase = iobase;
 
-	// probe id bits to make sure they are consistent
+	/*  probe id bits to make sure they are consistent */
 	if (das16_probe(dev, it)) {
 		printk(" id bits do not match selected board, aborting\n");
 		return -EINVAL;
 	}
 	dev->board_name = thisboard->name;
 
-	// get master clock speed
+	/*  get master clock speed */
 	if (thisboard->size < 0x400) {
 		if (it->options[3])
 			devpriv->clockbase = 1000 / it->options[3];
 		else
-			devpriv->clockbase = 1000;	// 1 MHz default
+			devpriv->clockbase = 1000;	/*  1 MHz default */
 	} else {
 		das1600_mode_detect(dev);
 	}
 
 	/* now for the irq */
 	if (irq > 1 && irq < 8) {
-		if ((ret = comedi_request_irq(irq, das16_dma_interrupt, 0,
-					"das16", dev)) < 0)
+		ret = request_irq(irq, das16_dma_interrupt, 0, "das16", dev);
+
+		if (ret < 0)
 			return ret;
 		dev->irq = irq;
 		printk(" ( irq = %u )", irq);
@@ -1462,10 +1463,10 @@
 		return -EINVAL;
 	}
 
-	// initialize dma
+	/*  initialize dma */
 	dma_chan = it->options[2];
 	if (dma_chan == 1 || dma_chan == 3) {
-		// allocate dma buffers
+		/*  allocate dma buffers */
 		int i;
 		for (i = 0; i < 2; i++) {
 			devpriv->dma_buffer[i] = pci_alloc_consistent(NULL,
@@ -1491,27 +1492,27 @@
 		return -EINVAL;
 	}
 
-	// get any user-defined input range
+	/*  get any user-defined input range */
 	if (thisboard->ai_pg == das16_pg_none &&
 		(it->options[4] || it->options[5])) {
-		// allocate single-range range table
+		/*  allocate single-range range table */
 		devpriv->user_ai_range_table =
 			kmalloc(sizeof(struct comedi_lrange) + sizeof(struct comedi_krange),
 			GFP_KERNEL);
-		// initialize ai range
+		/*  initialize ai range */
 		devpriv->user_ai_range_table->length = 1;
 		user_ai_range = devpriv->user_ai_range_table->range;
 		user_ai_range->min = it->options[4];
 		user_ai_range->max = it->options[5];
 		user_ai_range->flags = UNIT_volt;
 	}
-	// get any user-defined output range
+	/*  get any user-defined output range */
 	if (it->options[6] || it->options[7]) {
-		// allocate single-range range table
+		/*  allocate single-range range table */
 		devpriv->user_ao_range_table =
 			kmalloc(sizeof(struct comedi_lrange) + sizeof(struct comedi_krange),
 			GFP_KERNEL);
-		// initialize ao range
+		/*  initialize ao range */
 		devpriv->user_ao_range_table->length = 1;
 		user_ao_range = devpriv->user_ao_range_table->range;
 		user_ao_range->min = it->options[6];
@@ -1526,7 +1527,8 @@
 	}
 	devpriv->timer_mode = timer_mode ? 1 : 0;
 
-	if ((ret = alloc_subdevices(dev, 5)) < 0)
+	ret = alloc_subdevices(dev, 5);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -1545,7 +1547,7 @@
 			s->subdev_flags |= SDF_DIFF;
 		}
 		s->maxdata = (1 << thisboard->ai_nbits) - 1;
-		if (devpriv->user_ai_range_table) {	// user defined ai range
+		if (devpriv->user_ai_range_table) {	/*  user defined ai range */
 			s->range_table = devpriv->user_ai_range_table;
 		} else if (devpriv->ai_unipolar) {
 			s->range_table = das16_ai_uni_lranges[thisboard->ai_pg];
@@ -1568,7 +1570,7 @@
 		s->subdev_flags = SDF_WRITABLE;
 		s->n_chan = 2;
 		s->maxdata = (1 << thisboard->ao_nbits) - 1;
-		if (devpriv->user_ao_range_table) {	// user defined ao range
+		if (devpriv->user_ao_range_table) {	/*  user defined ao range */
 			s->range_table = devpriv->user_ao_range_table;
 		} else {
 			s->range_table = &range_unknown;
@@ -1600,7 +1602,7 @@
 		s->maxdata = 1;
 		s->range_table = &range_digital;
 		s->insn_bits = thisboard->do_;
-		// initialize digital output lines
+		/*  initialize digital output lines */
 		outb(s->state, dev->iobase + DAS16_DIO);
 	} else {
 		s->type = COMEDI_SUBD_UNUSED;
@@ -1620,7 +1622,7 @@
 	devpriv->control_state = DAS16_IRQ(dev->irq);
 	outb(devpriv->control_state, dev->iobase + DAS16_CONTROL);
 
-	// turn on das1600 mode if available
+	/*  turn on das1600 mode if available */
 	if (thisboard->size > 0x400) {
 		outb(DAS1600_ENABLE_VAL, dev->iobase + DAS1600_ENABLE);
 		outb(0, dev->iobase + DAS1600_CONV);
@@ -1630,7 +1632,7 @@
 	return 0;
 }
 
-static int das16_detach(struct comedi_device * dev)
+static int das16_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: das16: remove\n", dev->minor);
 
@@ -1656,7 +1658,7 @@
 	}
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	if (dev->iobase) {
 		if (thisboard->size < 0x400) {
@@ -1673,8 +1675,8 @@
 
 COMEDI_INITCLEANUP(driver_das16);
 
-// utility function that suggests a dma transfer size in bytes
-static unsigned int das16_suggest_transfer_size(struct comedi_device * dev,
+/* utility function that suggests a dma transfer size in bytes */
+static unsigned int das16_suggest_transfer_size(struct comedi_device *dev,
 	struct comedi_cmd cmd)
 {
 	unsigned int size;
@@ -1692,18 +1694,18 @@
 		freq = 1000000000 / cmd.convert_arg;
 	else if (cmd.scan_begin_src == TRIG_TIMER)
 		freq = (1000000000 / cmd.scan_begin_arg) * cmd.chanlist_len;
-	// return some default value
+	/*  return some default value */
 	else
 		freq = 0xffffffff;
 
 	if (cmd.flags & TRIG_WAKE_EOS) {
 		size = sample_size * cmd.chanlist_len;
 	} else {
-		// make buffer fill in no more than 1/3 second
+		/*  make buffer fill in no more than 1/3 second */
 		size = (freq / 3) * sample_size;
 	}
 
-	// set a minimum and maximum size allowed
+	/*  set a minimum and maximum size allowed */
 	if (size > DAS16_DMA_SIZE)
 		size = DAS16_DMA_SIZE - DAS16_DMA_SIZE % sample_size;
 	else if (size < sample_size)
@@ -1715,7 +1717,7 @@
 	return size;
 }
 
-static void das16_ai_munge(struct comedi_device * dev, struct comedi_subdevice * s,
+static void das16_ai_munge(struct comedi_device *dev, struct comedi_subdevice *s,
 	void *array, unsigned int num_bytes, unsigned int start_chan_index)
 {
 	unsigned int i, num_samples = num_bytes / sizeof(short);
diff --git a/drivers/staging/comedi/drivers/das16m1.c b/drivers/staging/comedi/drivers/das16m1.c
index 0e423e1..3da8bf4 100644
--- a/drivers/staging/comedi/drivers/das16m1.c
+++ b/drivers/staging/comedi/drivers/das16m1.c
@@ -59,6 +59,7 @@
 */
 
 #include <linux/ioport.h>
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include "8255.h"
@@ -68,9 +69,9 @@
 #define DAS16M1_SIZE 16
 #define DAS16M1_SIZE2 8
 
-#define DAS16M1_XTAL 100	//10 MHz master clock
+#define DAS16M1_XTAL 100	/* 10 MHz master clock */
 
-#define FIFO_SIZE 1024		// 1024 sample fifo
+#define FIFO_SIZE 1024		/*  1024 sample fifo */
 
 /*
     CIO-DAS16_M1.pdf
@@ -92,7 +93,7 @@
 
 */
 
-#define DAS16M1_AI             0	// 16-bit wide register
+#define DAS16M1_AI             0	/*  16-bit wide register */
 #define   AI_CHAN(x)             ((x) & 0xf)
 #define DAS16M1_CS             2
 #define   EXT_TRIG_BIT           0x1
@@ -131,23 +132,23 @@
 		}
 };
 
-static int das16m1_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das16m1_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das16m1_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int das16m1_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das16m1_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das16m1_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int das16m1_cmd_test(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int das16m1_cmd_exec(struct comedi_device * dev, struct comedi_subdevice * s);
-static int das16m1_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
+static int das16m1_cmd_test(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int das16m1_cmd_exec(struct comedi_device *dev, struct comedi_subdevice *s);
+static int das16m1_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
 
-static int das16m1_poll(struct comedi_device * dev, struct comedi_subdevice * s);
-static irqreturn_t das16m1_interrupt(int irq, void *d PT_REGS_ARG);
-static void das16m1_handler(struct comedi_device * dev, unsigned int status);
+static int das16m1_poll(struct comedi_device *dev, struct comedi_subdevice *s);
+static irqreturn_t das16m1_interrupt(int irq, void *d);
+static void das16m1_handler(struct comedi_device *dev, unsigned int status);
 
-static unsigned int das16m1_set_pacer(struct comedi_device * dev, unsigned int ns,
+static unsigned int das16m1_set_pacer(struct comedi_device *dev, unsigned int ns,
 	int round_flag);
 
 static int das16m1_irq_bits(unsigned int irq);
@@ -159,36 +160,34 @@
 
 static const struct das16m1_board das16m1_boards[] = {
 	{
-	      name:	"cio-das16/m1",	// CIO-DAS16_M1.pdf
-	      ai_speed:1000,	// 1MHz max speed
+	.name = "cio-das16/m1",	/*  CIO-DAS16_M1.pdf */
+	.ai_speed = 1000,	/*  1MHz max speed */
 		},
 };
 
-#define das16m1_num_boards ((sizeof(das16m1_boards)) / (sizeof(das16m1_boards[0])))
-
-static int das16m1_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int das16m1_detach(struct comedi_device * dev);
+static int das16m1_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int das16m1_detach(struct comedi_device *dev);
 static struct comedi_driver driver_das16m1 = {
-      driver_name:"das16m1",
-      module:THIS_MODULE,
-      attach:das16m1_attach,
-      detach:das16m1_detach,
-      board_name:&das16m1_boards[0].name,
-      num_names:das16m1_num_boards,
-      offset:sizeof(das16m1_boards[0]),
+	.driver_name = "das16m1",
+	.module = THIS_MODULE,
+	.attach = das16m1_attach,
+	.detach = das16m1_detach,
+	.board_name = &das16m1_boards[0].name,
+	.num_names = ARRAY_SIZE(das16m1_boards),
+	.offset = sizeof(das16m1_boards[0]),
 };
 
 struct das16m1_private_struct {
 	unsigned int control_state;
-	volatile unsigned int adc_count;	// number of samples completed
+	volatile unsigned int adc_count;	/*  number of samples completed */
 	/* initial value in lower half of hardware conversion counter,
 	 * needed to keep track of whether new count has been loaded into
 	 * counter yet (loaded by first sample conversion) */
 	u16 initial_hw_count;
 	short ai_buffer[FIFO_SIZE];
-	unsigned int do_bits;	// saves status of digital output bits
-	unsigned int divisor1;	// divides master clock to obtain conversion speed
-	unsigned int divisor2;	// divides master clock to obtain conversion speed
+	unsigned int do_bits;	/*  saves status of digital output bits */
+	unsigned int divisor1;	/*  divides master clock to obtain conversion speed */
+	unsigned int divisor2;	/*  divides master clock to obtain conversion speed */
 };
 #define devpriv ((struct das16m1_private_struct *)(dev->private))
 #define thisboard ((const struct das16m1_board *)(dev->board_ptr))
@@ -200,8 +199,8 @@
 	return (data >> 4) & 0xfff;
 }
 
-static int das16m1_cmd_test(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int das16m1_cmd_test(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	unsigned int err = 0, tmp, i;
 
@@ -299,10 +298,10 @@
 	if (err)
 		return 4;
 
-	// check chanlist against board's peculiarities
+	/*  check chanlist against board's peculiarities */
 	if (cmd->chanlist && cmd->chanlist_len > 1) {
 		for (i = 0; i < cmd->chanlist_len; i++) {
-			// even/odd channels must go into even/odd queue addresses
+			/*  even/odd channels must go into even/odd queue addresses */
 			if ((i % 2) != (CR_CHAN(cmd->chanlist[i]) % 2)) {
 				comedi_error(dev, "bad chanlist:\n"
 					" even/odd channels must go have even/odd chanlist indices");
@@ -322,7 +321,7 @@
 	return 0;
 }
 
-static int das16m1_cmd_exec(struct comedi_device * dev, struct comedi_subdevice * s)
+static int das16m1_cmd_exec(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_async *async = s->async;
 	struct comedi_cmd *cmd = &async->cmd;
@@ -337,7 +336,7 @@
 	devpriv->control_state &= ~INTE & ~PACER_MASK;
 	outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);
 
-	// set software count
+	/*  set software count */
 	devpriv->adc_count = 0;
 	/* Initialize lower half of hardware counter, used to determine how
 	 * many samples are in fifo.  Value doesn't actually load into counter
@@ -361,7 +360,7 @@
 		das16m1_set_pacer(dev, cmd->convert_arg,
 		cmd->flags & TRIG_ROUND_MASK);
 
-	// set control & status register
+	/*  set control & status register */
 	byte = 0;
 	/* if we are using external start trigger (also board dislikes having
 	 * both start and conversion triggers external simultaneously) */
@@ -385,7 +384,7 @@
 	return 0;
 }
 
-static int das16m1_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int das16m1_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	devpriv->control_state &= ~INTE & ~PACER_MASK;
 	outb(devpriv->control_state, dev->iobase + DAS16M1_INTR_CONTROL);
@@ -393,8 +392,8 @@
 	return 0;
 }
 
-static int das16m1_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16m1_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, n;
 	int byte;
@@ -430,8 +429,8 @@
 	return n;
 }
 
-static int das16m1_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16m1_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int bits;
 
@@ -442,17 +441,17 @@
 	return 2;
 }
 
-static int das16m1_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das16m1_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int wbits;
 
-	// only set bits that have been masked
+	/*  only set bits that have been masked */
 	data[0] &= 0xf;
 	wbits = devpriv->do_bits;
-	// zero bits that have been masked
+	/*  zero bits that have been masked */
 	wbits &= ~data[0];
-	// set masked bits
+	/*  set masked bits */
 	wbits |= data[0] & data[1];
 	devpriv->do_bits = wbits;
 	data[1] = wbits;
@@ -462,21 +461,21 @@
 	return 2;
 }
 
-static int das16m1_poll(struct comedi_device * dev, struct comedi_subdevice * s)
+static int das16m1_poll(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 	unsigned int status;
 
-	// prevent race with interrupt handler
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  prevent race with interrupt handler */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	status = inb(dev->iobase + DAS16M1_CS);
 	das16m1_handler(dev, status);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	return s->async->buf_write_count - s->async->buf_read_count;
 }
 
-static irqreturn_t das16m1_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t das16m1_interrupt(int irq, void *d)
 {
 	int status;
 	struct comedi_device *dev = d;
@@ -485,7 +484,7 @@
 		comedi_error(dev, "premature interrupt");
 		return IRQ_HANDLED;
 	}
-	// prevent race with comedi_poll()
+	/*  prevent race with comedi_poll() */
 	spin_lock(&dev->spinlock);
 
 	status = inb(dev->iobase + DAS16M1_CS);
@@ -505,7 +504,7 @@
 	return IRQ_HANDLED;
 }
 
-static void munge_sample_array(short * array, unsigned int num_elements)
+static void munge_sample_array(short *array, unsigned int num_elements)
 {
 	unsigned int i;
 
@@ -514,7 +513,7 @@
 	}
 }
 
-static void das16m1_handler(struct comedi_device * dev, unsigned int status)
+static void das16m1_handler(struct comedi_device *dev, unsigned int status)
 {
 	struct comedi_subdevice *s;
 	struct comedi_async *async;
@@ -527,7 +526,7 @@
 	async->events = 0;
 	cmd = &async->cmd;
 
-	// figure out how many samples are in fifo
+	/*  figure out how many samples are in fifo */
 	hw_counter = i8254_read(dev->iobase + DAS16M1_8254_FIRST, 0, 1);
 	/* make sure hardware counter reading is not bogus due to initial value
 	 * not having been loaded yet */
@@ -542,12 +541,12 @@
 		 * hardware counter.  Work it out, and this is what you get. */
 		num_samples = -hw_counter - devpriv->adc_count;
 	}
-	// check if we only need some of the points
+	/*  check if we only need some of the points */
 	if (cmd->stop_src == TRIG_COUNT) {
 		if (num_samples > cmd->stop_arg * cmd->chanlist_len)
 			num_samples = cmd->stop_arg * cmd->chanlist_len;
 	}
-	// make sure we dont try to get too many points if fifo has overrun
+	/*  make sure we dont try to get too many points if fifo has overrun */
 	if (num_samples > FIFO_SIZE)
 		num_samples = FIFO_SIZE;
 	insw(dev->iobase, devpriv->ai_buffer, num_samples);
@@ -578,7 +577,7 @@
 /* This function takes a time in nanoseconds and sets the     *
  * 2 pacer clocks to the closest frequency possible. It also  *
  * returns the actual sampling period.                        */
-static unsigned int das16m1_set_pacer(struct comedi_device * dev, unsigned int ns,
+static unsigned int das16m1_set_pacer(struct comedi_device *dev, unsigned int ns,
 	int rounding_flags)
 {
 	i8253_cascade_ns_to_timer_2div(DAS16M1_XTAL, &(devpriv->divisor1),
@@ -626,7 +625,7 @@
 		return -1;
 		break;
 	}
-	return (ret << 4);
+	return ret << 4;
 }
 
 /*
@@ -635,7 +634,7 @@
  *   1  IRQ
  */
 
-static int das16m1_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int das16m1_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int ret;
@@ -646,8 +645,8 @@
 
 	printk("comedi%d: das16m1:", dev->minor);
 
-	if ((ret = alloc_private(dev,
-				sizeof(struct das16m1_private_struct))) < 0)
+	ret = alloc_private(dev, sizeof(struct das16m1_private_struct));
+	if (ret < 0)
 		return ret;
 
 	dev->board_name = thisboard->name;
@@ -669,10 +668,10 @@
 
 	/* now for the irq */
 	irq = it->options[1];
-	// make sure it is valid
+	/*  make sure it is valid */
 	if (das16m1_irq_bits(irq) >= 0) {
-		ret = comedi_request_irq(irq, das16m1_interrupt, 0,
-			driver_das16m1.driver_name, dev);
+		ret = request_irq(irq, das16m1_interrupt, 0,
+				  driver_das16m1.driver_name, dev);
 		if (ret < 0) {
 			printk(", irq unavailable\n");
 			return ret;
@@ -687,7 +686,8 @@
 		return -EINVAL;
 	}
 
-	if ((ret = alloc_subdevices(dev, 4)) < 0)
+	ret = alloc_subdevices(dev, 4);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -728,10 +728,10 @@
 	/* 8255 */
 	subdev_8255_init(dev, s, NULL, dev->iobase + DAS16M1_82C55);
 
-	// disable upper half of hardware conversion counter so it doesn't mess with us
+	/*  disable upper half of hardware conversion counter so it doesn't mess with us */
 	outb(TOTAL_CLEAR, dev->iobase + DAS16M1_8254_FIRST_CNTRL);
 
-	// initialize digital output lines
+	/*  initialize digital output lines */
 	outb(devpriv->do_bits, dev->iobase + DAS16M1_DIO);
 
 	/* set the interrupt level */
@@ -744,17 +744,17 @@
 	return 0;
 }
 
-static int das16m1_detach(struct comedi_device * dev)
+static int das16m1_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: das16m1: remove\n", dev->minor);
 
-//      das16m1_reset(dev);
+/* das16m1_reset(dev); */
 
 	if (dev->subdevices)
 		subdev_8255_cleanup(dev, dev->subdevices + 3);
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	if (dev->iobase) {
 		release_region(dev->iobase, DAS16M1_SIZE);
diff --git a/drivers/staging/comedi/drivers/das1800.c b/drivers/staging/comedi/drivers/das1800.c
index cd4cd4e..a343408 100644
--- a/drivers/staging/comedi/drivers/das1800.c
+++ b/drivers/staging/comedi/drivers/das1800.c
@@ -100,6 +100,7 @@
 	read insn for analog out
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -108,12 +109,12 @@
 #include "8253.h"
 #include "comedi_fc.h"
 
-// misc. defines
-#define DAS1800_SIZE           16	//uses 16 io addresses
-#define FIFO_SIZE              1024	// 1024 sample fifo
-#define TIMER_BASE             200	// 5 Mhz master clock
-#define UNIPOLAR               0x4	// bit that determines whether input range is uni/bipolar
-#define DMA_BUF_SIZE           0x1ff00	// size in bytes of dma buffers
+/* misc. defines */
+#define DAS1800_SIZE           16	/* uses 16 io addresses */
+#define FIFO_SIZE              1024	/*  1024 sample fifo */
+#define TIMER_BASE             200	/*  5 Mhz master clock */
+#define UNIPOLAR               0x4	/*  bit that determines whether input range is uni/bipolar */
+#define DMA_BUF_SIZE           0x1ff00	/*  size in bytes of dma buffers */
 
 /* Registers for the das1800 */
 #define DAS1800_FIFO            0x0
@@ -138,7 +139,7 @@
 #define   DMA_CH5_CH6             0x5
 #define   DMA_CH6_CH7             0x6
 #define   DMA_CH7_CH5             0x7
-#define   DMA_ENABLED             0x3	//mask used to determine if dma is enabled
+#define   DMA_ENABLED             0x3	/* mask used to determine if dma is enabled */
 #define   DMA_DUAL                0x4
 #define   IRQ3                    0x8
 #define   IRQ5                    0x10
@@ -156,7 +157,7 @@
 #define   SD                      0x40
 #define   UB                      0x80
 #define DAS1800_STATUS          0x7
-// bits that prevent interrupt status bits (and CVEN) from being cleared on write
+/* bits that prevent interrupt status bits (and CVEN) from being cleared on write */
 #define   CLEAR_INTR_MASK         (CVEN_MASK | 0x1f)
 #define   INT                     0x1
 #define   DMATC                   0x2
@@ -164,14 +165,14 @@
 #define   OVF                     0x10
 #define   FHF                     0x20
 #define   FNE                     0x40
-#define   CVEN_MASK               0x40	// masks CVEN on write
+#define   CVEN_MASK               0x40	/*  masks CVEN on write */
 #define   CVEN                    0x80
 #define DAS1800_BURST_LENGTH    0x8
 #define DAS1800_BURST_RATE      0x9
 #define DAS1800_QRAM_ADDRESS    0xa
 #define DAS1800_COUNTER         0xc
 
-#define IOBASE2                   0x400	//offset of additional ioports used on 'ao' cards
+#define IOBASE2                   0x400	/* offset of additional ioports used on 'ao' cards */
 
 enum {
 	das1701st, das1701st_da, das1702st, das1702st_da, das1702hr,
@@ -180,39 +181,39 @@
 	das1802hr, das1802hr_da, das1801hc, das1802hc, das1801ao, das1802ao
 };
 
-static int das1800_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int das1800_detach(struct comedi_device * dev);
-static int das1800_probe(struct comedi_device * dev);
-static int das1800_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static irqreturn_t das1800_interrupt(int irq, void *d PT_REGS_ARG);
-static int das1800_ai_poll(struct comedi_device * dev, struct comedi_subdevice * s);
-static void das1800_ai_handler(struct comedi_device * dev);
-static void das1800_handle_dma(struct comedi_device * dev, struct comedi_subdevice * s,
+static int das1800_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int das1800_detach(struct comedi_device *dev);
+static int das1800_probe(struct comedi_device *dev);
+static int das1800_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static irqreturn_t das1800_interrupt(int irq, void *d);
+static int das1800_ai_poll(struct comedi_device *dev, struct comedi_subdevice *s);
+static void das1800_ai_handler(struct comedi_device *dev);
+static void das1800_handle_dma(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int status);
-static void das1800_flush_dma(struct comedi_device * dev, struct comedi_subdevice * s);
-static void das1800_flush_dma_channel(struct comedi_device * dev, struct comedi_subdevice * s,
-	unsigned int channel, uint16_t * buffer);
-static void das1800_handle_fifo_half_full(struct comedi_device * dev,
-	struct comedi_subdevice * s);
-static void das1800_handle_fifo_not_empty(struct comedi_device * dev,
-	struct comedi_subdevice * s);
-static int das1800_ai_do_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int das1800_ai_do_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int das1800_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das1800_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das1800_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das1800_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static void das1800_flush_dma(struct comedi_device *dev, struct comedi_subdevice *s);
+static void das1800_flush_dma_channel(struct comedi_device *dev, struct comedi_subdevice *s,
+	unsigned int channel, uint16_t *buffer);
+static void das1800_handle_fifo_half_full(struct comedi_device *dev,
+	struct comedi_subdevice *s);
+static void das1800_handle_fifo_not_empty(struct comedi_device *dev,
+	struct comedi_subdevice *s);
+static int das1800_ai_do_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int das1800_ai_do_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int das1800_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das1800_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das1800_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das1800_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int das1800_set_frequency(struct comedi_device * dev);
+static int das1800_set_frequency(struct comedi_device *dev);
 static unsigned int burst_convert_arg(unsigned int convert_arg, int round_mode);
-static unsigned int suggest_transfer_size(struct comedi_cmd * cmd);
+static unsigned int suggest_transfer_size(struct comedi_cmd *cmd);
 
-// analog input ranges
+/* analog input ranges */
 static const struct comedi_lrange range_ai_das1801 = {
 	8,
 	{
@@ -259,202 +260,202 @@
  */
 static const struct das1800_board das1800_boards[] = {
 	{
-	      name:	"das-1701st",
-	      ai_speed:6250,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:0,
-	      ao_n_chan:0,
-	      range_ai:&range_ai_das1801,
+	.name = "das-1701st",
+	.ai_speed = 6250,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 0,
+	.ao_n_chan = 0,
+	.range_ai = &range_ai_das1801,
 		},
 	{
-	      name:	"das-1701st-da",
-	      ai_speed:6250,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:1,
-	      ao_n_chan:4,
-	      range_ai:&range_ai_das1801,
+	.name = "das-1701st-da",
+	.ai_speed = 6250,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 1,
+	.ao_n_chan = 4,
+	.range_ai = &range_ai_das1801,
 		},
 	{
-	      name:	"das-1702st",
-	      ai_speed:6250,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:0,
-	      ao_n_chan:0,
-	      range_ai:&range_ai_das1802,
+	.name = "das-1702st",
+	.ai_speed = 6250,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 0,
+	.ao_n_chan = 0,
+	.range_ai = &range_ai_das1802,
 		},
 	{
-	      name:	"das-1702st-da",
-	      ai_speed:6250,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:1,
-	      ao_n_chan:4,
-	      range_ai:&range_ai_das1802,
+	.name = "das-1702st-da",
+	.ai_speed = 6250,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 1,
+	.ao_n_chan = 4,
+	.range_ai = &range_ai_das1802,
 		},
 	{
-	      name:	"das-1702hr",
-	      ai_speed:20000,
-	      resolution:16,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:0,
-	      ao_n_chan:0,
-	      range_ai:&range_ai_das1802,
+	.name = "das-1702hr",
+	.ai_speed = 20000,
+	.resolution = 16,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 0,
+	.ao_n_chan = 0,
+	.range_ai = &range_ai_das1802,
 		},
 	{
-	      name:	"das-1702hr-da",
-	      ai_speed:20000,
-	      resolution:16,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:1,
-	      ao_n_chan:2,
-	      range_ai:&range_ai_das1802,
+	.name = "das-1702hr-da",
+	.ai_speed = 20000,
+	.resolution = 16,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 1,
+	.ao_n_chan = 2,
+	.range_ai = &range_ai_das1802,
 		},
 	{
-	      name:	"das-1701ao",
-	      ai_speed:6250,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:2,
-	      ao_n_chan:2,
-	      range_ai:&range_ai_das1801,
+	.name = "das-1701ao",
+	.ai_speed = 6250,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 2,
+	.ao_n_chan = 2,
+	.range_ai = &range_ai_das1801,
 		},
 	{
-	      name:	"das-1702ao",
-	      ai_speed:6250,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:2,
-	      ao_n_chan:2,
-	      range_ai:&range_ai_das1802,
+	.name = "das-1702ao",
+	.ai_speed = 6250,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 2,
+	.ao_n_chan = 2,
+	.range_ai = &range_ai_das1802,
 		},
 	{
-	      name:	"das-1801st",
-	      ai_speed:3000,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:0,
-	      ao_n_chan:0,
-	      range_ai:&range_ai_das1801,
+	.name = "das-1801st",
+	.ai_speed = 3000,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 0,
+	.ao_n_chan = 0,
+	.range_ai = &range_ai_das1801,
 		},
 	{
-	      name:	"das-1801st-da",
-	      ai_speed:3000,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:0,
-	      ao_n_chan:4,
-	      range_ai:&range_ai_das1801,
+	.name = "das-1801st-da",
+	.ai_speed = 3000,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 0,
+	.ao_n_chan = 4,
+	.range_ai = &range_ai_das1801,
 		},
 	{
-	      name:	"das-1802st",
-	      ai_speed:3000,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:0,
-	      ao_n_chan:0,
-	      range_ai:&range_ai_das1802,
+	.name = "das-1802st",
+	.ai_speed = 3000,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 0,
+	.ao_n_chan = 0,
+	.range_ai = &range_ai_das1802,
 		},
 	{
-	      name:	"das-1802st-da",
-	      ai_speed:3000,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:1,
-	      ao_n_chan:4,
-	      range_ai:&range_ai_das1802,
+	.name = "das-1802st-da",
+	.ai_speed = 3000,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 1,
+	.ao_n_chan = 4,
+	.range_ai = &range_ai_das1802,
 		},
 	{
-	      name:	"das-1802hr",
-	      ai_speed:10000,
-	      resolution:16,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:0,
-	      ao_n_chan:0,
-	      range_ai:&range_ai_das1802,
+	.name = "das-1802hr",
+	.ai_speed = 10000,
+	.resolution = 16,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 0,
+	.ao_n_chan = 0,
+	.range_ai = &range_ai_das1802,
 		},
 	{
-	      name:	"das-1802hr-da",
-	      ai_speed:10000,
-	      resolution:16,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:1,
-	      ao_n_chan:2,
-	      range_ai:&range_ai_das1802,
+	.name = "das-1802hr-da",
+	.ai_speed = 10000,
+	.resolution = 16,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 1,
+	.ao_n_chan = 2,
+	.range_ai = &range_ai_das1802,
 		},
 	{
-	      name:	"das-1801hc",
-	      ai_speed:3000,
-	      resolution:12,
-	      qram_len:64,
-	      common:	0,
-	      do_n_chan:8,
-	      ao_ability:1,
-	      ao_n_chan:2,
-	      range_ai:&range_ai_das1801,
+	.name = "das-1801hc",
+	.ai_speed = 3000,
+	.resolution = 12,
+	.qram_len = 64,
+	.common = 0,
+	.do_n_chan = 8,
+	.ao_ability = 1,
+	.ao_n_chan = 2,
+	.range_ai = &range_ai_das1801,
 		},
 	{
-	      name:	"das-1802hc",
-	      ai_speed:3000,
-	      resolution:12,
-	      qram_len:64,
-	      common:	0,
-	      do_n_chan:8,
-	      ao_ability:1,
-	      ao_n_chan:2,
-	      range_ai:&range_ai_das1802,
+	.name = "das-1802hc",
+	.ai_speed = 3000,
+	.resolution = 12,
+	.qram_len = 64,
+	.common = 0,
+	.do_n_chan = 8,
+	.ao_ability = 1,
+	.ao_n_chan = 2,
+	.range_ai = &range_ai_das1802,
 		},
 	{
-	      name:	"das-1801ao",
-	      ai_speed:3000,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:2,
-	      ao_n_chan:2,
-	      range_ai:&range_ai_das1801,
+	.name = "das-1801ao",
+	.ai_speed = 3000,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 2,
+	.ao_n_chan = 2,
+	.range_ai = &range_ai_das1801,
 		},
 	{
-	      name:	"das-1802ao",
-	      ai_speed:3000,
-	      resolution:12,
-	      qram_len:256,
-	      common:	1,
-	      do_n_chan:4,
-	      ao_ability:2,
-	      ao_n_chan:2,
-	      range_ai:&range_ai_das1802,
+	.name = "das-1802ao",
+	.ai_speed = 3000,
+	.resolution = 12,
+	.qram_len = 256,
+	.common = 1,
+	.do_n_chan = 4,
+	.ao_ability = 2,
+	.ao_n_chan = 2,
+	.range_ai = &range_ai_das1802,
 		},
 };
 
@@ -485,7 +486,7 @@
 
 #define devpriv ((struct das1800_private *)dev->private)
 
-// analog out range for boards with basic analog out
+/* analog out range for boards with basic analog out */
 static const struct comedi_lrange range_ao_1 = {
 	1,
 	{
@@ -493,7 +494,7 @@
 		}
 };
 
-// analog out range for 'ao' boards
+/* analog out range for 'ao' boards */
 /*
 static const struct comedi_lrange range_ao_2 = {
 	2,
@@ -505,13 +506,13 @@
 */
 
 static struct comedi_driver driver_das1800 = {
-      driver_name:"das1800",
-      module:THIS_MODULE,
-      attach:das1800_attach,
-      detach:das1800_detach,
-      num_names:sizeof(das1800_boards) / sizeof(struct das1800_board),
-      board_name:&das1800_boards[0].name,
-      offset:sizeof(struct das1800_board),
+	.driver_name = "das1800",
+	.module = THIS_MODULE,
+	.attach = das1800_attach,
+	.detach = das1800_detach,
+	.num_names = ARRAY_SIZE(das1800_boards),
+	.board_name = &das1800_boards[0].name,
+	.offset = sizeof(struct das1800_board),
 };
 
 /*
@@ -520,31 +521,31 @@
  */
 COMEDI_INITCLEANUP(driver_das1800);
 
-static int das1800_init_dma(struct comedi_device * dev, unsigned int dma0,
+static int das1800_init_dma(struct comedi_device *dev, unsigned int dma0,
 	unsigned int dma1)
 {
 	unsigned long flags;
 
-	// need an irq to do dma
+	/*  need an irq to do dma */
 	if (dev->irq && dma0) {
-		//encode dma0 and dma1 into 2 digit hexadecimal for switch
+		/* encode dma0 and dma1 into 2 digit hexadecimal for switch */
 		switch ((dma0 & 0x7) | (dma1 << 4)) {
-		case 0x5:	// dma0 == 5
+		case 0x5:	/*  dma0 == 5 */
 			devpriv->dma_bits |= DMA_CH5;
 			break;
-		case 0x6:	// dma0 == 6
+		case 0x6:	/*  dma0 == 6 */
 			devpriv->dma_bits |= DMA_CH6;
 			break;
-		case 0x7:	// dma0 == 7
+		case 0x7:	/*  dma0 == 7 */
 			devpriv->dma_bits |= DMA_CH7;
 			break;
-		case 0x65:	// dma0 == 5, dma1 == 6
+		case 0x65:	/*  dma0 == 5, dma1 == 6 */
 			devpriv->dma_bits |= DMA_CH5_CH6;
 			break;
-		case 0x76:	// dma0 == 6, dma1 == 7
+		case 0x76:	/*  dma0 == 6, dma1 == 7 */
 			devpriv->dma_bits |= DMA_CH6_CH7;
 			break;
-		case 0x57:	// dma0 == 7, dma1 == 5
+		case 0x57:	/*  dma0 == 7, dma1 == 5 */
 			devpriv->dma_bits |= DMA_CH7_CH5;
 			break;
 		default:
@@ -590,7 +591,7 @@
 	return 0;
 }
 
-static int das1800_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int das1800_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase = it->options[0];
@@ -638,7 +639,7 @@
 	dev->board_ptr = das1800_boards + board;
 	dev->board_name = thisboard->name;
 
-	// if it is an 'ao' board with fancy analog out then we need extra io ports
+	/*  if it is an 'ao' board with fancy analog out then we need extra io ports */
 	if (thisboard->ao_ability == 2) {
 		iobase2 = iobase + IOBASE2;
 		if (!request_region(iobase2, DAS1800_SIZE,
@@ -651,7 +652,7 @@
 
 	/* grab our IRQ */
 	if (irq) {
-		if (comedi_request_irq(irq, das1800_interrupt, 0,
+		if (request_irq(irq, das1800_interrupt, 0,
 				driver_das1800.driver_name, dev)) {
 			printk(" unable to allocate irq %u\n", irq);
 			return -EINVAL;
@@ -659,7 +660,7 @@
 	}
 	dev->irq = irq;
 
-	// set bits that tell card which irq to use
+	/*  set bits that tell card which irq to use */
 	switch (irq) {
 	case 0:
 		break;
@@ -751,12 +752,12 @@
 
 	das1800_cancel(dev, dev->read_subdev);
 
-	// initialize digital out channels
+	/*  initialize digital out channels */
 	outb(devpriv->do_bits, dev->iobase + DAS1800_DIGITAL);
 
-	// initialize analog out channels
+	/*  initialize analog out channels */
 	if (thisboard->ao_ability == 1) {
-		// select 'update' dac channel for baseAddress + 0x0
+		/*  select 'update' dac channel for baseAddress + 0x0 */
 		outb(DAC(thisboard->ao_n_chan - 1),
 			dev->iobase + DAS1800_SELECT);
 		outw(devpriv->ao_update_bits, dev->iobase + DAS1800_DAC);
@@ -765,13 +766,13 @@
 	return 0;
 };
 
-static int das1800_detach(struct comedi_device * dev)
+static int das1800_detach(struct comedi_device *dev)
 {
 	/* only free stuff if it has been allocated by _attach */
 	if (dev->iobase)
 		release_region(dev->iobase, DAS1800_SIZE);
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	if (dev->private) {
 		if (devpriv->iobase2)
 			release_region(devpriv->iobase2, DAS1800_SIZE);
@@ -793,7 +794,7 @@
 
 /* probes and checks das-1800 series board type
  */
-static int das1800_probe(struct comedi_device * dev)
+static int das1800_probe(struct comedi_device *dev)
 {
 	int id;
 	int board;
@@ -867,19 +868,19 @@
 	return -1;
 }
 
-static int das1800_ai_poll(struct comedi_device * dev, struct comedi_subdevice * s)
+static int das1800_ai_poll(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 
-	// prevent race with interrupt handler
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  prevent race with interrupt handler */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	das1800_ai_handler(dev);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	return s->async->buf_write_count - s->async->buf_read_count;
 }
 
-static irqreturn_t das1800_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t das1800_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	unsigned int status;
@@ -901,15 +902,15 @@
 	}
 	/* clear the interrupt status bit INT */
 	outb(CLEAR_INTR_MASK & ~INT, dev->iobase + DAS1800_STATUS);
-	// handle interrupt
+	/*  handle interrupt */
 	das1800_ai_handler(dev);
 
 	spin_unlock(&dev->spinlock);
 	return IRQ_HANDLED;
 }
 
-// the guts of the interrupt handler, that is shared with das1800_ai_poll
-static void das1800_ai_handler(struct comedi_device * dev)
+/* the guts of the interrupt handler, that is shared with das1800_ai_poll */
+static void das1800_ai_handler(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s = dev->subdevices + 0;	/* analog input subdevice */
 	struct comedi_async *async = s->async;
@@ -917,22 +918,22 @@
 	unsigned int status = inb(dev->iobase + DAS1800_STATUS);
 
 	async->events = 0;
-	// select adc for base address + 0
+	/*  select adc for base address + 0 */
 	outb(ADC, dev->iobase + DAS1800_SELECT);
-	// dma buffer full
+	/*  dma buffer full */
 	if (devpriv->irq_dma_bits & DMA_ENABLED) {
-		// look for data from dma transfer even if dma terminal count hasn't happened yet
+		/*  look for data from dma transfer even if dma terminal count hasn't happened yet */
 		das1800_handle_dma(dev, s, status);
-	} else if (status & FHF) {	// if fifo half full
+	} else if (status & FHF) {	/*  if fifo half full */
 		das1800_handle_fifo_half_full(dev, s);
-	} else if (status & FNE) {	// if fifo not empty
+	} else if (status & FNE) {	/*  if fifo not empty */
 		das1800_handle_fifo_not_empty(dev, s);
 	}
 
 	async->events |= COMEDI_CB_BLOCK;
 	/* if the card's fifo has overflowed */
 	if (status & OVF) {
-		// clear OVF interrupt bit
+		/*  clear OVF interrupt bit */
 		outb(CLEAR_INTR_MASK & ~OVF, dev->iobase + DAS1800_STATUS);
 		comedi_error(dev, "DAS1800 FIFO overflow");
 		das1800_cancel(dev, s);
@@ -940,19 +941,19 @@
 		comedi_event(dev, s);
 		return;
 	}
-	// stop taking data if appropriate
+	/*  stop taking data if appropriate */
 	/* stop_src TRIG_EXT */
 	if (status & CT0TC) {
-		// clear CT0TC interrupt bit
+		/*  clear CT0TC interrupt bit */
 		outb(CLEAR_INTR_MASK & ~CT0TC, dev->iobase + DAS1800_STATUS);
-		// make sure we get all remaining data from board before quitting
+		/*  make sure we get all remaining data from board before quitting */
 		if (devpriv->irq_dma_bits & DMA_ENABLED)
 			das1800_flush_dma(dev, s);
 		else
 			das1800_handle_fifo_not_empty(dev, s);
 		das1800_cancel(dev, s);	/* disable hardware conversions */
 		async->events |= COMEDI_CB_EOA;
-	} else if (cmd->stop_src == TRIG_COUNT && devpriv->count == 0) {	// stop_src TRIG_COUNT
+	} else if (cmd->stop_src == TRIG_COUNT && devpriv->count == 0) {	/*  stop_src TRIG_COUNT */
 		das1800_cancel(dev, s);	/* disable hardware conversions */
 		async->events |= COMEDI_CB_EOA;
 	}
@@ -962,7 +963,7 @@
 	return;
 }
 
-static void das1800_handle_dma(struct comedi_device * dev, struct comedi_subdevice * s,
+static void das1800_handle_dma(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int status)
 {
 	unsigned long flags;
@@ -971,7 +972,7 @@
 	flags = claim_dma_lock();
 	das1800_flush_dma_channel(dev, s, devpriv->dma_current,
 		devpriv->dma_current_buf);
-	// re-enable  dma channel
+	/*  re-enable  dma channel */
 	set_dma_addr(devpriv->dma_current,
 		virt_to_bus(devpriv->dma_current_buf));
 	set_dma_count(devpriv->dma_current, devpriv->dma_transfer_size);
@@ -979,11 +980,11 @@
 	release_dma_lock(flags);
 
 	if (status & DMATC) {
-		// clear DMATC interrupt bit
+		/*  clear DMATC interrupt bit */
 		outb(CLEAR_INTR_MASK & ~DMATC, dev->iobase + DAS1800_STATUS);
-		// switch dma channels for next time, if appropriate
+		/*  switch dma channels for next time, if appropriate */
 		if (dual_dma) {
-			// read data from the other channel next time
+			/*  read data from the other channel next time */
 			if (devpriv->dma_current == devpriv->dma0) {
 				devpriv->dma_current = devpriv->dma1;
 				devpriv->dma_current_buf = devpriv->ai_buf1;
@@ -997,14 +998,14 @@
 	return;
 }
 
-static inline uint16_t munge_bipolar_sample(const struct comedi_device * dev,
+static inline uint16_t munge_bipolar_sample(const struct comedi_device *dev,
 	uint16_t sample)
 {
 	sample += 1 << (thisboard->resolution - 1);
 	return sample;
 }
 
-static void munge_data(struct comedi_device * dev, uint16_t * array,
+static void munge_data(struct comedi_device *dev, uint16_t *array,
 	unsigned int num_elements)
 {
 	unsigned int i;
@@ -1023,8 +1024,8 @@
 
 /* Utility function used by das1800_flush_dma() and das1800_handle_dma().
  * Assumes dma lock is held */
-static void das1800_flush_dma_channel(struct comedi_device * dev, struct comedi_subdevice * s,
-	unsigned int channel, uint16_t * buffer)
+static void das1800_flush_dma_channel(struct comedi_device *dev, struct comedi_subdevice *s,
+	unsigned int channel, uint16_t *buffer)
 {
 	unsigned int num_bytes, num_samples;
 	struct comedi_cmd *cmd = &s->async->cmd;
@@ -1035,7 +1036,7 @@
 	 * get set correctly */
 	clear_dma_ff(channel);
 
-	// figure out how many points to read
+	/*  figure out how many points to read */
 	num_bytes = devpriv->dma_transfer_size - get_dma_residue(channel);
 	num_samples = num_bytes / sizeof(short);
 
@@ -1053,7 +1054,7 @@
 
 /* flushes remaining data from board when external trigger has stopped aquisition
  * and we are using dma transfers */
-static void das1800_flush_dma(struct comedi_device * dev, struct comedi_subdevice * s)
+static void das1800_flush_dma(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 	const int dual_dma = devpriv->irq_dma_bits & DMA_DUAL;
@@ -1063,7 +1064,7 @@
 		devpriv->dma_current_buf);
 
 	if (dual_dma) {
-		// switch to other channel and flush it
+		/*  switch to other channel and flush it */
 		if (devpriv->dma_current == devpriv->dma0) {
 			devpriv->dma_current = devpriv->dma1;
 			devpriv->dma_current_buf = devpriv->ai_buf1;
@@ -1077,14 +1078,14 @@
 
 	release_dma_lock(flags);
 
-	// get any remaining samples in fifo
+	/*  get any remaining samples in fifo */
 	das1800_handle_fifo_not_empty(dev, s);
 
 	return;
 }
 
-static void das1800_handle_fifo_half_full(struct comedi_device * dev,
-	struct comedi_subdevice * s)
+static void das1800_handle_fifo_half_full(struct comedi_device *dev,
+	struct comedi_subdevice *s)
 {
 	int numPoints = 0;	/* number of points to read */
 	struct comedi_cmd *cmd = &s->async->cmd;
@@ -1102,8 +1103,8 @@
 	return;
 }
 
-static void das1800_handle_fifo_not_empty(struct comedi_device * dev,
-	struct comedi_subdevice * s)
+static void das1800_handle_fifo_not_empty(struct comedi_device *dev,
+	struct comedi_subdevice *s)
 {
 	short dpnt;
 	int unipolar;
@@ -1126,7 +1127,7 @@
 	return;
 }
 
-static int das1800_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int das1800_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	outb(0x0, dev->iobase + DAS1800_STATUS);	/* disable conversions */
 	outb(0x0, dev->iobase + DAS1800_CONTROL_B);	/* disable interrupts and dma */
@@ -1139,8 +1140,8 @@
 }
 
 /* test analog input cmd */
-static int das1800_ai_do_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int das1800_ai_do_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -1180,7 +1181,7 @@
 
 	/* step 2: make sure trigger sources are unique and mutually compatible */
 
-	// uniqueness check
+	/*  uniqueness check */
 	if (cmd->start_src != TRIG_NOW && cmd->start_src != TRIG_EXT)
 		err++;
 	if (cmd->scan_begin_src != TRIG_FOLLOW &&
@@ -1192,7 +1193,7 @@
 	if (cmd->stop_src != TRIG_COUNT &&
 		cmd->stop_src != TRIG_NONE && cmd->stop_src != TRIG_EXT)
 		err++;
-	//compatibility check
+	/* compatibility check */
 	if (cmd->scan_begin_src != TRIG_FOLLOW &&
 		cmd->convert_src != TRIG_TIMER)
 		err++;
@@ -1244,7 +1245,7 @@
 	/* step 4: fix up any arguments */
 
 	if (cmd->convert_src == TRIG_TIMER) {
-		// if we are not in burst mode
+		/*  if we are not in burst mode */
 		if (cmd->scan_begin_src == TRIG_FOLLOW) {
 			tmp_arg = cmd->convert_arg;
 			/* calculate counter values that give desired timing */
@@ -1255,9 +1256,9 @@
 			if (tmp_arg != cmd->convert_arg)
 				err++;
 		}
-		// if we are in burst mode
+		/*  if we are in burst mode */
 		else {
-			// check that convert_arg is compatible
+			/*  check that convert_arg is compatible */
 			tmp_arg = cmd->convert_arg;
 			cmd->convert_arg =
 				burst_convert_arg(cmd->convert_arg,
@@ -1266,7 +1267,7 @@
 				err++;
 
 			if (cmd->scan_begin_src == TRIG_TIMER) {
-				// if scans are timed faster than conversion rate allows
+				/*  if scans are timed faster than conversion rate allows */
 				if (cmd->convert_arg * cmd->chanlist_len >
 					cmd->scan_begin_arg) {
 					cmd->scan_begin_arg =
@@ -1290,7 +1291,7 @@
 	if (err)
 		return 4;
 
-	// make sure user is not trying to mix unipolar and bipolar ranges
+	/*  make sure user is not trying to mix unipolar and bipolar ranges */
 	if (cmd->chanlist) {
 		unipolar = CR_RANGE(cmd->chanlist[0]) & UNIPOLAR;
 		for (i = 1; i < cmd->chanlist_len; i++) {
@@ -1311,14 +1312,14 @@
 
 /* analog input cmd interface */
 
-// first, some utility functions used in the main ai_do_cmd()
+/* first, some utility functions used in the main ai_do_cmd() */
 
-// returns appropriate bits for control register a, depending on command
+/* returns appropriate bits for control register a, depending on command */
 static int control_a_bits(struct comedi_cmd cmd)
 {
 	int control_a;
 
-	control_a = FFEN;	//enable fifo
+	control_a = FFEN;	/* enable fifo */
 	if (cmd.stop_src == TRIG_EXT) {
 		control_a |= ATEN;
 	}
@@ -1336,7 +1337,7 @@
 	return control_a;
 }
 
-// returns appropriate bits for control register c, depending on command
+/* returns appropriate bits for control register c, depending on command */
 static int control_c_bits(struct comedi_cmd cmd)
 {
 	int control_c;
@@ -1346,7 +1347,7 @@
 	 * select unipolar / bipolar
 	 */
 	aref = CR_AREF(cmd.chanlist[0]);
-	control_c = UQEN;	//enable upper qram addresses
+	control_c = UQEN;	/* enable upper qram addresses */
 	if (aref != AREF_DIFF)
 		control_c |= SD;
 	if (aref == AREF_COMMON)
@@ -1355,7 +1356,7 @@
 	if (CR_RANGE(cmd.chanlist[0]) & UNIPOLAR)
 		control_c |= UB;
 	switch (cmd.scan_begin_src) {
-	case TRIG_FOLLOW:	// not in burst mode
+	case TRIG_FOLLOW:	/*  not in burst mode */
 		switch (cmd.convert_src) {
 		case TRIG_TIMER:
 			/* trig on cascaded counters */
@@ -1370,11 +1371,11 @@
 		}
 		break;
 	case TRIG_TIMER:
-		// burst mode with internal pacer clock
+		/*  burst mode with internal pacer clock */
 		control_c |= BMDE | IPCLK;
 		break;
 	case TRIG_EXT:
-		// burst mode with external trigger
+		/*  burst mode with external trigger */
 		control_c |= BMDE | XPCLK;
 		break;
 	default:
@@ -1384,12 +1385,12 @@
 	return control_c;
 }
 
-// sets up counters
-static int setup_counters(struct comedi_device * dev, struct comedi_cmd cmd)
+/* sets up counters */
+static int setup_counters(struct comedi_device *dev, struct comedi_cmd cmd)
 {
-	// setup cascaded counters for conversion/scan frequency
+	/*  setup cascaded counters for conversion/scan frequency */
 	switch (cmd.scan_begin_src) {
-	case TRIG_FOLLOW:	// not in burst mode
+	case TRIG_FOLLOW:	/*  not in burst mode */
 		if (cmd.convert_src == TRIG_TIMER) {
 			/* set conversion frequency */
 			i8253_cascade_ns_to_timer_2div(TIMER_BASE,
@@ -1401,7 +1402,7 @@
 			}
 		}
 		break;
-	case TRIG_TIMER:	// in burst mode
+	case TRIG_TIMER:	/*  in burst mode */
 		/* set scan frequency */
 		i8253_cascade_ns_to_timer_2div(TIMER_BASE, &(devpriv->divisor1),
 			&(devpriv->divisor2), &(cmd.scan_begin_arg),
@@ -1414,17 +1415,17 @@
 		break;
 	}
 
-	// setup counter 0 for 'about triggering'
+	/*  setup counter 0 for 'about triggering' */
 	if (cmd.stop_src == TRIG_EXT) {
-		// load counter 0 in mode 0
+		/*  load counter 0 in mode 0 */
 		i8254_load(dev->iobase + DAS1800_COUNTER, 0, 0, 1, 0);
 	}
 
 	return 0;
 }
 
-// sets up dma
-static void setup_dma(struct comedi_device * dev, struct comedi_cmd cmd)
+/* sets up dma */
+static void setup_dma(struct comedi_device *dev, struct comedi_cmd cmd)
 {
 	unsigned long lock_flags;
 	const int dual_dma = devpriv->irq_dma_bits & DMA_DUAL;
@@ -1440,19 +1441,19 @@
 	 * count and address get set correctly */
 	clear_dma_ff(devpriv->dma0);
 	set_dma_addr(devpriv->dma0, virt_to_bus(devpriv->ai_buf0));
-	// set appropriate size of transfer
+	/*  set appropriate size of transfer */
 	set_dma_count(devpriv->dma0, devpriv->dma_transfer_size);
 	devpriv->dma_current = devpriv->dma0;
 	devpriv->dma_current_buf = devpriv->ai_buf0;
 	enable_dma(devpriv->dma0);
-	// set up dual dma if appropriate
+	/*  set up dual dma if appropriate */
 	if (dual_dma) {
 		disable_dma(devpriv->dma1);
 		/* clear flip-flop to make sure 2-byte registers for
 		 * count and address get set correctly */
 		clear_dma_ff(devpriv->dma1);
 		set_dma_addr(devpriv->dma1, virt_to_bus(devpriv->ai_buf1));
-		// set appropriate size of transfer
+		/*  set appropriate size of transfer */
 		set_dma_count(devpriv->dma1, devpriv->dma_transfer_size);
 		enable_dma(devpriv->dma1);
 	}
@@ -1461,17 +1462,17 @@
 	return;
 }
 
-// programs channel/gain list into card
-static void program_chanlist(struct comedi_device * dev, struct comedi_cmd cmd)
+/* programs channel/gain list into card */
+static void program_chanlist(struct comedi_device *dev, struct comedi_cmd cmd)
 {
 	int i, n, chan_range;
 	unsigned long irq_flags;
-	const int range_mask = 0x3;	//masks unipolar/bipolar bit off range
+	const int range_mask = 0x3;	/* masks unipolar/bipolar bit off range */
 	const int range_bitshift = 8;
 
 	n = cmd.chanlist_len;
-	// spinlock protects indirect addressing
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	/*  spinlock protects indirect addressing */
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 	outb(QRAM, dev->iobase + DAS1800_SELECT);	/* select QRAM for baseAddress + 0x0 */
 	outb(n - 1, dev->iobase + DAS1800_QRAM_ADDRESS);	/*set QRAM address start */
 	/* make channel / gain list */
@@ -1483,13 +1484,13 @@
 		outw(chan_range, dev->iobase + DAS1800_QRAM);
 	}
 	outb(n - 1, dev->iobase + DAS1800_QRAM_ADDRESS);	/*finish write to QRAM */
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 
 	return;
 }
 
-// analog input do_cmd
-static int das1800_ai_do_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+/* analog input do_cmd */
+static int das1800_ai_do_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int ret;
 	int control_a, control_c;
@@ -1509,22 +1510,22 @@
 	} else {
 		devpriv->irq_dma_bits |= devpriv->dma_bits;
 	}
-	// interrupt on end of conversion for TRIG_WAKE_EOS
+	/*  interrupt on end of conversion for TRIG_WAKE_EOS */
 	if (cmd.flags & TRIG_WAKE_EOS) {
-		// interrupt fifo not empty
+		/*  interrupt fifo not empty */
 		devpriv->irq_dma_bits &= ~FIMD;
 	} else {
-		// interrupt fifo half full
+		/*  interrupt fifo half full */
 		devpriv->irq_dma_bits |= FIMD;
 	}
-	// determine how many conversions we need
+	/*  determine how many conversions we need */
 	if (cmd.stop_src == TRIG_COUNT) {
 		devpriv->count = cmd.stop_arg * cmd.chanlist_len;
 	}
 
 	das1800_cancel(dev, s);
 
-	// determine proper bits for control registers
+	/*  determine proper bits for control registers */
 	control_a = control_a_bits(cmd);
 	control_c = control_c_bits(cmd);
 
@@ -1537,14 +1538,14 @@
 	}
 	setup_dma(dev, cmd);
 	outb(control_c, dev->iobase + DAS1800_CONTROL_C);
-	// set conversion rate and length for burst mode
+	/*  set conversion rate and length for burst mode */
 	if (control_c & BMDE) {
-		// program conversion period with number of microseconds minus 1
+		/*  program conversion period with number of microseconds minus 1 */
 		outb(cmd.convert_arg / 1000 - 1,
 			dev->iobase + DAS1800_BURST_RATE);
 		outb(cmd.chanlist_len - 1, dev->iobase + DAS1800_BURST_LENGTH);
 	}
-	outb(devpriv->irq_dma_bits, dev->iobase + DAS1800_CONTROL_B);	// enable irq/dma
+	outb(devpriv->irq_dma_bits, dev->iobase + DAS1800_CONTROL_B);	/*  enable irq/dma */
 	outb(control_a, dev->iobase + DAS1800_CONTROL_A);	/* enable fifo and triggering */
 	outb(CVEN, dev->iobase + DAS1800_STATUS);	/* enable conversions */
 
@@ -1552,8 +1553,8 @@
 }
 
 /* read analog input */
-static int das1800_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das1800_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, n;
 	int chan, range, aref, chan_range;
@@ -1582,7 +1583,7 @@
 	/* mask of unipolar/bipolar bit from range */
 	range = CR_RANGE(insn->chanspec) & 0x3;
 	chan_range = chan | (range << 8);
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 	outb(QRAM, dev->iobase + DAS1800_SELECT);	/* select QRAM for baseAddress + 0x0 */
 	outb(0x0, dev->iobase + DAS1800_QRAM_ADDRESS);	/* set QRAM address start */
 	outw(chan_range, dev->iobase + DAS1800_QRAM);
@@ -1606,43 +1607,43 @@
 			dpnt += 1 << (thisboard->resolution - 1);
 		data[n] = dpnt;
 	}
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 
 	return n;
 }
 
 /* writes to an analog output channel */
-static int das1800_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das1800_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
-//      int range = CR_RANGE(insn->chanspec);
+/* int range = CR_RANGE(insn->chanspec); */
 	int update_chan = thisboard->ao_n_chan - 1;
 	short output;
 	unsigned long irq_flags;
 
-	//  card expects two's complement data
+	/*   card expects two's complement data */
 	output = data[0] - (1 << (thisboard->resolution - 1));
-	// if the write is to the 'update' channel, we need to remember its value
+	/*  if the write is to the 'update' channel, we need to remember its value */
 	if (chan == update_chan)
 		devpriv->ao_update_bits = output;
-	// write to channel
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	/*  write to channel */
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 	outb(DAC(chan), dev->iobase + DAS1800_SELECT);	/* select dac channel for baseAddress + 0x0 */
 	outw(output, dev->iobase + DAS1800_DAC);
-	// now we need to write to 'update' channel to update all dac channels
+	/*  now we need to write to 'update' channel to update all dac channels */
 	if (chan != update_chan) {
 		outb(DAC(update_chan), dev->iobase + DAS1800_SELECT);	/* select 'update' channel for baseAddress + 0x0 */
 		outw(devpriv->ao_update_bits, dev->iobase + DAS1800_DAC);
 	}
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 
 	return 1;
 }
 
 /* reads from digital input channels */
-static int das1800_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das1800_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
 	data[1] = inb(dev->iobase + DAS1800_DIGITAL) & 0xf;
@@ -1652,12 +1653,12 @@
 }
 
 /* writes to digital output channels */
-static int das1800_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das1800_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int wbits;
 
-	// only set bits that have been masked
+	/*  only set bits that have been masked */
 	data[0] &= (1 << s->n_chan) - 1;
 	wbits = devpriv->do_bits;
 	wbits &= ~data[0];
@@ -1672,15 +1673,15 @@
 }
 
 /* loads counters with divisor1, divisor2 from private structure */
-static int das1800_set_frequency(struct comedi_device * dev)
+static int das1800_set_frequency(struct comedi_device *dev)
 {
 	int err = 0;
 
-	// counter 1, mode 2
+	/*  counter 1, mode 2 */
 	if (i8254_load(dev->iobase + DAS1800_COUNTER, 0, 1, devpriv->divisor1,
 			2))
 		err++;
-	// counter 2, mode 2
+	/*  counter 2, mode 2 */
 	if (i8254_load(dev->iobase + DAS1800_COUNTER, 0, 2, devpriv->divisor2,
 			2))
 		err++;
@@ -1697,11 +1698,11 @@
 {
 	unsigned int micro_sec;
 
-	// in burst mode, the maximum conversion time is 64 microseconds
+	/*  in burst mode, the maximum conversion time is 64 microseconds */
 	if (convert_arg > 64000)
 		convert_arg = 64000;
 
-	// the conversion time must be an integral number of microseconds
+	/*  the conversion time must be an integral number of microseconds */
 	switch (round_mode) {
 	case TRIG_ROUND_NEAREST:
 	default:
@@ -1715,21 +1716,21 @@
 		break;
 	}
 
-	// return number of nanoseconds
+	/*  return number of nanoseconds */
 	return micro_sec * 1000;
 }
 
-// utility function that suggests a dma transfer size based on the conversion period 'ns'
-static unsigned int suggest_transfer_size(struct comedi_cmd * cmd)
+/* utility function that suggests a dma transfer size based on the conversion period 'ns' */
+static unsigned int suggest_transfer_size(struct comedi_cmd *cmd)
 {
 	unsigned int size = DMA_BUF_SIZE;
-	static const int sample_size = 2;	// size in bytes of one sample from board
-	unsigned int fill_time = 300000000;	// target time in nanoseconds for filling dma buffer
-	unsigned int max_size;	// maximum size we will allow for a transfer
+	static const int sample_size = 2;	/*  size in bytes of one sample from board */
+	unsigned int fill_time = 300000000;	/*  target time in nanoseconds for filling dma buffer */
+	unsigned int max_size;	/*  maximum size we will allow for a transfer */
 
-	// make dma buffer fill in 0.3 seconds for timed modes
+	/*  make dma buffer fill in 0.3 seconds for timed modes */
 	switch (cmd->scan_begin_src) {
-	case TRIG_FOLLOW:	// not in burst mode
+	case TRIG_FOLLOW:	/*  not in burst mode */
 		if (cmd->convert_src == TRIG_TIMER)
 			size = (fill_time / cmd->convert_arg) * sample_size;
 		break;
@@ -1742,9 +1743,9 @@
 		break;
 	}
 
-	// set a minimum and maximum size allowed
+	/*  set a minimum and maximum size allowed */
 	max_size = DMA_BUF_SIZE;
-	// if we are taking limited number of conversions, limit transfer size to that
+	/*  if we are taking limited number of conversions, limit transfer size to that */
 	if (cmd->stop_src == TRIG_COUNT &&
 		cmd->stop_arg * cmd->chanlist_len * sample_size < max_size)
 		max_size = cmd->stop_arg * cmd->chanlist_len * sample_size;
diff --git a/drivers/staging/comedi/drivers/das6402.c b/drivers/staging/comedi/drivers/das6402.c
index 2a8ca05..0114eb9 100644
--- a/drivers/staging/comedi/drivers/das6402.c
+++ b/drivers/staging/comedi/drivers/das6402.c
@@ -38,6 +38,7 @@
 This driver has suffered bitrot.
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -98,13 +99,13 @@
 #define	C2 0x80
 #define	RWLH 0x30
 
-static int das6402_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int das6402_detach(struct comedi_device * dev);
+static int das6402_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int das6402_detach(struct comedi_device *dev);
 static struct comedi_driver driver_das6402 = {
-      driver_name:"das6402",
-      module:THIS_MODULE,
-      attach:das6402_attach,
-      detach:das6402_detach,
+	.driver_name = "das6402",
+	.module = THIS_MODULE,
+	.attach = das6402_attach,
+	.detach = das6402_detach,
 };
 
 COMEDI_INITCLEANUP(driver_das6402);
@@ -116,9 +117,9 @@
 };
 #define devpriv ((struct das6402_private *)dev->private)
 
-static void das6402_ai_fifo_dregs(struct comedi_device * dev, struct comedi_subdevice * s);
+static void das6402_ai_fifo_dregs(struct comedi_device *dev, struct comedi_subdevice *s);
 
-static void das6402_setcounter(struct comedi_device * dev)
+static void das6402_setcounter(struct comedi_device *dev)
 {
 	BYTE p;
 	unsigned short ctrlwrd;
@@ -151,7 +152,7 @@
 	outb_p(p, dev->iobase + 14);
 }
 
-static irqreturn_t intr_handler(int irq, void *d PT_REGS_ARG)
+static irqreturn_t intr_handler(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s = dev->subdevices;
@@ -186,7 +187,7 @@
 }
 
 #if 0
-static void das6402_ai_fifo_read(struct comedi_device * dev, short * data, int n)
+static void das6402_ai_fifo_read(struct comedi_device *dev, short *data, int n)
 {
 	int i;
 
@@ -195,7 +196,7 @@
 }
 #endif
 
-static void das6402_ai_fifo_dregs(struct comedi_device * dev, struct comedi_subdevice * s)
+static void das6402_ai_fifo_dregs(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	while (1) {
 		if (!(inb(dev->iobase + 8) & 0x01))
@@ -204,7 +205,7 @@
 	}
 }
 
-static int das6402_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int das6402_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	/*
 	 *  This function should reset the board from whatever condition it
@@ -226,8 +227,8 @@
 }
 
 #ifdef unused
-static int das6402_ai_mode2(struct comedi_device * dev, struct comedi_subdevice * s,
-	comedi_trig * it)
+static int das6402_ai_mode2(struct comedi_device *dev, struct comedi_subdevice *s,
+	comedi_trig *it)
 {
 	devpriv->das6402_ignoreirq = 1;
 
@@ -249,7 +250,7 @@
 }
 #endif
 
-static int board_init(struct comedi_device * dev)
+static int board_init(struct comedi_device *dev)
 {
 	BYTE b;
 
@@ -289,17 +290,17 @@
 	return 0;
 }
 
-static int das6402_detach(struct comedi_device * dev)
+static int das6402_detach(struct comedi_device *dev)
 {
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	if (dev->iobase)
 		release_region(dev->iobase, DAS6402_SIZE);
 
 	return 0;
 }
 
-static int das6402_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int das6402_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	unsigned int irq;
 	unsigned long iobase;
@@ -324,17 +325,19 @@
 
 	irq = it->options[0];
 	printk(" ( irq = %u )", irq);
-	ret = comedi_request_irq(irq, intr_handler, 0, "das6402", dev);
+	ret = request_irq(irq, intr_handler, 0, "das6402", dev);
 	if (ret < 0) {
 		printk("irq conflict\n");
 		return ret;
 	}
 	dev->irq = irq;
 
-	if ((ret = alloc_private(dev, sizeof(struct das6402_private))) < 0)
+	ret = alloc_private(dev, sizeof(struct das6402_private));
+	if (ret < 0)
 		return ret;
 
-	if ((ret = alloc_subdevices(dev, 1)) < 0)
+	ret = alloc_subdevices(dev, 1);
+	if (ret < 0)
 		return ret;
 
 	/* ai subdevice */
@@ -342,7 +345,7 @@
 	s->type = COMEDI_SUBD_AI;
 	s->subdev_flags = SDF_READABLE | SDF_GROUND;
 	s->n_chan = 8;
-	//s->trig[2]=das6402_ai_mode2;
+	/* s->trig[2]=das6402_ai_mode2; */
 	s->cancel = das6402_ai_cancel;
 	s->maxdata = (1 << 12) - 1;
 	s->len_chanlist = 16;	/* ? */
diff --git a/drivers/staging/comedi/drivers/das800.c b/drivers/staging/comedi/drivers/das800.c
index 7a6656b..70e9d69 100644
--- a/drivers/staging/comedi/drivers/das800.c
+++ b/drivers/staging/comedi/drivers/das800.c
@@ -62,6 +62,7 @@
 
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -72,7 +73,7 @@
 
 #define DAS800_SIZE           8
 #define TIMER_BASE            1000
-#define N_CHAN_AI             8	// number of analog input channels
+#define N_CHAN_AI             8	/*  number of analog input channels */
 
 /* Registers for the das800 */
 
@@ -94,8 +95,8 @@
 #define   IRQ                   0x8
 #define   BUSY                  0x80
 #define DAS800_GAIN           3
-#define   CIO_FFOV              0x8	// fifo overflow for cio-das802/16
-#define   CIO_ENHF              0x90	// interrupt fifo half full for cio-das802/16
+#define   CIO_FFOV              0x8	/*  fifo overflow for cio-das802/16 */
+#define   CIO_ENHF              0x90	/*  interrupt fifo half full for cio-das802/16 */
 #define   CONTROL1              0x80
 #define   CONV_CONTROL          0xa0
 #define   SCAN_LIMITS           0xc0
@@ -113,7 +114,7 @@
 	int resolution;
 };
 
-//analog input ranges
+/* analog input ranges */
 static const struct comedi_lrange range_das800_ai = {
 	1,
 	{
@@ -184,46 +185,46 @@
 
 static const struct das800_board das800_boards[] = {
 	{
-	      name:	"das-800",
-	      ai_speed:25000,
-	      ai_range:&range_das800_ai,
-	      resolution:12,
+	.name = "das-800",
+	.ai_speed = 25000,
+	.ai_range = &range_das800_ai,
+	.resolution = 12,
 		},
 	{
-	      name:	"cio-das800",
-	      ai_speed:20000,
-	      ai_range:&range_das800_ai,
-	      resolution:12,
+	.name = "cio-das800",
+	.ai_speed = 20000,
+	.ai_range = &range_das800_ai,
+	.resolution = 12,
 		},
 	{
-	      name:	"das-801",
-	      ai_speed:25000,
-	      ai_range:&range_das801_ai,
-	      resolution:12,
+	.name = "das-801",
+	.ai_speed = 25000,
+	.ai_range = &range_das801_ai,
+	.resolution = 12,
 		},
 	{
-	      name:	"cio-das801",
-	      ai_speed:20000,
-	      ai_range:&range_cio_das801_ai,
-	      resolution:12,
+	.name = "cio-das801",
+	.ai_speed = 20000,
+	.ai_range = &range_cio_das801_ai,
+	.resolution = 12,
 		},
 	{
-	      name:	"das-802",
-	      ai_speed:25000,
-	      ai_range:&range_das802_ai,
-	      resolution:12,
+	.name = "das-802",
+	.ai_speed = 25000,
+	.ai_range = &range_das802_ai,
+	.resolution = 12,
 		},
 	{
-	      name:	"cio-das802",
-	      ai_speed:20000,
-	      ai_range:&range_das802_ai,
-	      resolution:12,
+	.name = "cio-das802",
+	.ai_speed = 20000,
+	.ai_range = &range_das802_ai,
+	.resolution = 12,
 		},
 	{
-	      name:	"cio-das802/16",
-	      ai_speed:10000,
-	      ai_range:&range_das80216_ai,
-	      resolution:16,
+	.name = "cio-das802/16",
+	.ai_speed = 10000,
+	.ai_range = &range_das80216_ai,
+	.resolution = 16,
 		},
 };
 
@@ -242,47 +243,47 @@
 
 #define devpriv ((struct das800_private *)dev->private)
 
-static int das800_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int das800_detach(struct comedi_device * dev);
-static int das800_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
+static int das800_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int das800_detach(struct comedi_device *dev);
+static int das800_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
 
 static struct comedi_driver driver_das800 = {
-      driver_name:"das800",
-      module:THIS_MODULE,
-      attach:das800_attach,
-      detach:das800_detach,
-      num_names:sizeof(das800_boards) / sizeof(struct das800_board),
-      board_name:&das800_boards[0].name,
-      offset:sizeof(struct das800_board),
+	.driver_name = "das800",
+	.module = THIS_MODULE,
+	.attach = das800_attach,
+	.detach = das800_detach,
+	.num_names = ARRAY_SIZE(das800_boards),
+	.board_name = &das800_boards[0].name,
+	.offset = sizeof(struct das800_board),
 };
 
-static irqreturn_t das800_interrupt(int irq, void *d PT_REGS_ARG);
-static void enable_das800(struct comedi_device * dev);
-static void disable_das800(struct comedi_device * dev);
-static int das800_ai_do_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int das800_ai_do_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int das800_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das800_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das800_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int das800_probe(struct comedi_device * dev);
-static int das800_set_frequency(struct comedi_device * dev);
+static irqreturn_t das800_interrupt(int irq, void *d);
+static void enable_das800(struct comedi_device *dev);
+static void disable_das800(struct comedi_device *dev);
+static int das800_ai_do_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int das800_ai_do_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int das800_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das800_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das800_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int das800_probe(struct comedi_device *dev);
+static int das800_set_frequency(struct comedi_device *dev);
 
 /* checks and probes das-800 series board type */
-static int das800_probe(struct comedi_device * dev)
+static int das800_probe(struct comedi_device *dev)
 {
 	int id_bits;
 	unsigned long irq_flags;
 	int board;
 
-	// 'comedi spin lock irqsave' disables even rt interrupts, we use them to protect indirect addressing
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	/*  'comedi spin lock irqsave' disables even rt interrupts, we use them to protect indirect addressing */
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 	outb(ID, dev->iobase + DAS800_GAIN);	/* select base address + 7 to be ID register */
 	id_bits = inb(dev->iobase + DAS800_ID) & 0x3;	/* get id bits */
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 
 	board = thisboard - das800_boards;
 
@@ -343,7 +344,7 @@
 COMEDI_INITCLEANUP(driver_das800);
 
 /* interrupt service routine */
-static irqreturn_t das800_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t das800_interrupt(int irq, void *d)
 {
 	short i;		/* loop index */
 	short dataPoint = 0;
@@ -352,8 +353,8 @@
 	struct comedi_async *async;
 	int status;
 	unsigned long irq_flags;
-	static const int max_loops = 128;	// half-fifo size for cio-das802/16
-	// flags
+	static const int max_loops = 128;	/*  half-fifo size for cio-das802/16 */
+	/*  flags */
 	int fifo_empty = 0;
 	int fifo_overflow = 0;
 
@@ -369,13 +370,13 @@
 	 */
 	async = s->async;
 
-	// if hardware conversions are not enabled, then quit
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	/*  if hardware conversions are not enabled, then quit */
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 	outb(CONTROL1, dev->iobase + DAS800_GAIN);	/* select base address + 7 to be STATUS2 register */
 	status = inb(dev->iobase + DAS800_STATUS2) & STATUS2_HCEN;
 	/* don't release spinlock yet since we want to make sure noone else disables hardware conversions */
 	if (status == 0) {
-		comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+		spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 		return IRQ_HANDLED;
 	}
 
@@ -390,7 +391,7 @@
 			if (fifo_overflow)
 				break;
 		} else {
-			fifo_empty = 0;	// cio-das802/16 has no fifo empty status bit
+			fifo_empty = 0;	/*  cio-das802/16 has no fifo empty status bit */
 		}
 		if (fifo_empty) {
 			break;
@@ -410,12 +411,12 @@
 	/* check for fifo overflow */
 	if (thisboard->resolution == 12) {
 		fifo_overflow = dataPoint & FIFO_OVF;
-		// else cio-das802/16
+		/*  else cio-das802/16 */
 	} else {
 		fifo_overflow = inb(dev->iobase + DAS800_GAIN) & CIO_FFOV;
 	}
 	if (fifo_overflow) {
-		comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+		spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 		comedi_error(dev, "DAS800 FIFO overflow");
 		das800_cancel(dev, dev->subdevices + 0);
 		async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
@@ -429,10 +430,10 @@
 		outb(CONTROL1, dev->iobase + DAS800_GAIN);	/* select dev->iobase + 2 to be control register 1 */
 		outb(CONTROL1_INTE | devpriv->do_bits,
 			dev->iobase + DAS800_CONTROL1);
-		comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+		spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 		/* otherwise, stop taking data */
 	} else {
-		comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+		spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 		disable_das800(dev);	/* diable hardware triggered conversions */
 		async->events |= COMEDI_CB_EOA;
 	}
@@ -441,7 +442,7 @@
 	return IRQ_HANDLED;
 }
 
-static int das800_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int das800_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase = it->options[0];
@@ -484,7 +485,7 @@
 		return -EINVAL;
 	}
 	if (irq) {
-		if (comedi_request_irq(irq, das800_interrupt, 0, "das800", dev)) {
+		if (request_irq(irq, das800_interrupt, 0, "das800", dev)) {
 			printk("unable to allocate irq %u\n", irq);
 			return -EINVAL;
 		}
@@ -531,15 +532,15 @@
 	disable_das800(dev);
 
 	/* initialize digital out channels */
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 	outb(CONTROL1, dev->iobase + DAS800_GAIN);	/* select dev->iobase + 2 to be control register 1 */
 	outb(CONTROL1_INTE | devpriv->do_bits, dev->iobase + DAS800_CONTROL1);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 
 	return 0;
 };
 
-static int das800_detach(struct comedi_device * dev)
+static int das800_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: das800: remove\n", dev->minor);
 
@@ -547,11 +548,11 @@
 	if (dev->iobase)
 		release_region(dev->iobase, DAS800_SIZE);
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	return 0;
 };
 
-static int das800_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int das800_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	devpriv->forever = 0;
 	devpriv->count = 0;
@@ -560,32 +561,32 @@
 }
 
 /* enable_das800 makes the card start taking hardware triggered conversions */
-static void enable_das800(struct comedi_device * dev)
+static void enable_das800(struct comedi_device *dev)
 {
 	unsigned long irq_flags;
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
-	// enable fifo-half full interrupts for cio-das802/16
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
+	/*  enable fifo-half full interrupts for cio-das802/16 */
 	if (thisboard->resolution == 16)
 		outb(CIO_ENHF, dev->iobase + DAS800_GAIN);
 	outb(CONV_CONTROL, dev->iobase + DAS800_GAIN);	/* select dev->iobase + 2 to be conversion control register */
 	outb(CONV_HCEN, dev->iobase + DAS800_CONV_CONTROL);	/* enable hardware triggering */
 	outb(CONTROL1, dev->iobase + DAS800_GAIN);	/* select dev->iobase + 2 to be control register 1 */
 	outb(CONTROL1_INTE | devpriv->do_bits, dev->iobase + DAS800_CONTROL1);	/* enable card's interrupt */
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 }
 
 /* disable_das800 stops hardware triggered conversions */
-static void disable_das800(struct comedi_device * dev)
+static void disable_das800(struct comedi_device *dev)
 {
 	unsigned long irq_flags;
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 	outb(CONV_CONTROL, dev->iobase + DAS800_GAIN);	/* select dev->iobase + 2 to be conversion control register */
 	outb(0x0, dev->iobase + DAS800_CONV_CONTROL);	/* disable hardware triggering of conversions */
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 }
 
-static int das800_ai_do_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int das800_ai_do_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -684,7 +685,7 @@
 	if (err)
 		return 4;
 
-	// check channel/gain list against card's limitations
+	/*  check channel/gain list against card's limitations */
 	if (cmd->chanlist) {
 		gain = CR_RANGE(cmd->chanlist[0]);
 		startChan = CR_CHAN(cmd->chanlist[0]);
@@ -709,7 +710,7 @@
 	return 0;
 }
 
-static int das800_ai_do_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int das800_ai_do_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int startChan, endChan, scan, gain;
 	int conv_bits;
@@ -729,10 +730,10 @@
 	endChan = (startChan + async->cmd.chanlist_len - 1) % 8;
 	scan = (endChan << 3) | startChan;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 	outb(SCAN_LIMITS, dev->iobase + DAS800_GAIN);	/* select base address + 2 to be scan limits register */
 	outb(scan, dev->iobase + DAS800_SCAN_LIMITS);	/* set scan limits */
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 
 	/* set gain */
 	gain = CR_RANGE(async->cmd.chanlist[0]);
@@ -779,17 +780,17 @@
 		break;
 	}
 
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 	outb(CONV_CONTROL, dev->iobase + DAS800_GAIN);	/* select dev->iobase + 2 to be conversion control register */
 	outb(conv_bits, dev->iobase + DAS800_CONV_CONTROL);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 	async->events = 0;
 	enable_das800(dev);
 	return 0;
 }
 
-static int das800_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das800_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, n;
 	int chan;
@@ -803,10 +804,10 @@
 	/* set multiplexer */
 	chan = CR_CHAN(insn->chanspec);
 
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 	outb(CONTROL1, dev->iobase + DAS800_GAIN);	/* select dev->iobase + 2 to be control register 1 */
 	outb(chan | devpriv->do_bits, dev->iobase + DAS800_CONTROL1);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 
 	/* set gain / range */
 	range = CR_RANGE(insn->chanspec);
@@ -815,7 +816,7 @@
 	range &= 0xf;
 	outb(range, dev->iobase + DAS800_GAIN);
 
-	comedi_udelay(5);
+	udelay(5);
 
 	for (n = 0; n < insn->n; n++) {
 		/* trigger conversion */
@@ -842,8 +843,8 @@
 	return n;
 }
 
-static int das800_di_rbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das800_di_rbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int bits;
 
@@ -855,23 +856,23 @@
 	return 2;
 }
 
-static int das800_do_wbits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int das800_do_wbits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int wbits;
 	unsigned long irq_flags;
 
-	// only set bits that have been masked
+	/*  only set bits that have been masked */
 	data[0] &= 0xf;
 	wbits = devpriv->do_bits >> 4;
 	wbits &= ~data[0];
 	wbits |= data[0] & data[1];
 	devpriv->do_bits = wbits << 4;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, irq_flags);
+	spin_lock_irqsave(&dev->spinlock, irq_flags);
 	outb(CONTROL1, dev->iobase + DAS800_GAIN);	/* select dev->iobase + 2 to be control register 1 */
 	outb(devpriv->do_bits | CONTROL1_INTE, dev->iobase + DAS800_CONTROL1);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, irq_flags);
+	spin_unlock_irqrestore(&dev->spinlock, irq_flags);
 
 	data[1] = wbits;
 
@@ -879,7 +880,7 @@
 }
 
 /* loads counters with divisor1, divisor2 from private structure */
-static int das800_set_frequency(struct comedi_device * dev)
+static int das800_set_frequency(struct comedi_device *dev)
 {
 	int err = 0;
 
diff --git a/drivers/staging/comedi/drivers/dmm32at.c b/drivers/staging/comedi/drivers/dmm32at.c
index 829083651..573cbe7 100644
--- a/drivers/staging/comedi/drivers/dmm32at.c
+++ b/drivers/staging/comedi/drivers/dmm32at.c
@@ -74,6 +74,7 @@
  * options that are used with comedi_config.
  */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 #include <linux/ioport.h>
 
@@ -114,8 +115,8 @@
 #define DMM32AT_DIOC 0x0e
 #define DMM32AT_DIOCONF 0x0f
 
-#define dmm_inb(cdev,reg) inb((cdev->iobase)+reg)
-#define dmm_outb(cdev,reg,valu) outb(valu,(cdev->iobase)+reg)
+#define dmm_inb(cdev, reg) inb((cdev->iobase)+reg)
+#define dmm_outb(cdev, reg, valu) outb(valu, (cdev->iobase)+reg)
 
 /* Board register values. */
 
@@ -213,15 +214,15 @@
 };
 static const struct dmm32at_board dmm32at_boards[] = {
 	{
-	      name:	"dmm32at",
-	      ai_chans:32,
-	      ai_bits:	16,
-	      ai_ranges:&dmm32at_airanges,
-	      ao_chans:4,
-	      ao_bits:	12,
-	      ao_ranges:&dmm32at_aoranges,
-	      have_dio:1,
-	      dio_chans:24,
+	.name = "dmm32at",
+	.ai_chans = 32,
+	.ai_bits = 16,
+	.ai_ranges = &dmm32at_airanges,
+	.ao_chans = 4,
+	.ao_bits = 12,
+	.ao_ranges = &dmm32at_aoranges,
+	.have_dio = 1,
+	.dio_chans = 24,
 		},
 };
 
@@ -258,13 +259,13 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int dmm32at_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dmm32at_detach(struct comedi_device * dev);
+static int dmm32at_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dmm32at_detach(struct comedi_device *dev);
 static struct comedi_driver driver_dmm32at = {
-      driver_name:"dmm32at",
-      module:THIS_MODULE,
-      attach:dmm32at_attach,
-      detach:dmm32at_detach,
+	.driver_name = "dmm32at",
+	.module = THIS_MODULE,
+	.attach = dmm32at_attach,
+	.detach = dmm32at_detach,
 /* It is not necessary to implement the following members if you are
  * writing a driver for a ISA PnP or PCI card */
 /* Most drivers will support multiple types of boards by
@@ -283,29 +284,29 @@
  * the type of board in software.  ISA PnP, PCI, and PCMCIA
  * devices are such boards.
  */
-      board_name:&dmm32at_boards[0].name,
-      offset:sizeof(struct dmm32at_board),
-      num_names:sizeof(dmm32at_boards) / sizeof(struct dmm32at_board),
+	.board_name = &dmm32at_boards[0].name,
+	.offset = sizeof(struct dmm32at_board),
+	.num_names = ARRAY_SIZE(dmm32at_boards),
 };
 
 /* prototypes for driver functions below */
-static int dmm32at_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dmm32at_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dmm32at_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dmm32at_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dmm32at_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dmm32at_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int dmm32at_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int dmm32at_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
+static int dmm32at_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dmm32at_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dmm32at_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dmm32at_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dmm32at_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dmm32at_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int dmm32at_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int dmm32at_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
 static int dmm32at_ns_to_timer(unsigned int *ns, int round);
-static irqreturn_t dmm32at_isr(int irq, void *d PT_REGS_ARG);
-void dmm32at_setaitimer(struct comedi_device * dev, unsigned int nansec);
+static irqreturn_t dmm32at_isr(int irq, void *d);
+void dmm32at_setaitimer(struct comedi_device *dev, unsigned int nansec);
 
 /*
  * Attach is called by the Comedi core to configure the driver
@@ -313,7 +314,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int dmm32at_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dmm32at_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int ret;
 	struct comedi_subdevice *s;
@@ -380,8 +381,7 @@
 
 	/* board is there, register interrupt */
 	if (irq) {
-		ret = comedi_request_irq(irq, dmm32at_isr, 0, thisboard->name,
-			dev);
+		ret = request_irq(irq, dmm32at_isr, 0, thisboard->name, dev);
 		if (ret < 0) {
 			printk("irq conflict\n");
 			return ret;
@@ -394,7 +394,7 @@
  * it is, this is the place to do it.  Otherwise, dev->board_ptr
  * should already be initialized.
  */
-	//dev->board_ptr = dmm32at_probe(dev);
+	/* dev->board_ptr = dmm32at_probe(dev); */
 
 /*
  * Initialize dev->board_name.  Note that we can use the "thisboard"
@@ -481,11 +481,11 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int dmm32at_detach(struct comedi_device * dev)
+static int dmm32at_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: dmm32at: remove\n", dev->minor);
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	if (dev->iobase)
 		release_region(dev->iobase, DMM32AT_MEMSIZE);
 
@@ -497,8 +497,8 @@
  * mode.
  */
 
-static int dmm32at_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dmm32at_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, i;
 	unsigned int d;
@@ -512,7 +512,7 @@
 	chan = CR_CHAN(insn->chanspec) & (s->n_chan - 1);
 	range = CR_RANGE(insn->chanspec);
 
-	//printk("channel=0x%02x, range=%d\n",chan,range);
+	/* printk("channel=0x%02x, range=%d\n",chan,range); */
 
 	/* zero scan and fifo control and reset fifo */
 	dmm_outb(dev, DMM32AT_FIFOCNTRL, DMM32AT_FIFORESET);
@@ -568,14 +568,14 @@
 	return n;
 }
 
-static int dmm32at_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int dmm32at_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
 	int start_chan, gain, i;
 
-	//printk("dmmat32 in command test\n");
+	/* printk("dmmat32 in command test\n"); */
 
 	/* cmdtest tests a particular command to see if it is valid.
 	 * Using the cmdtest ioctl, a user can create a valid cmd
@@ -752,7 +752,7 @@
 	return 0;
 }
 
-static int dmm32at_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dmm32at_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	int i, range;
@@ -822,13 +822,13 @@
 
 }
 
-static int dmm32at_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dmm32at_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	devpriv->ai_scans_left = 1;
 	return 0;
 }
 
-static irqreturn_t dmm32at_isr(int irq, void *d PT_REGS_ARG)
+static irqreturn_t dmm32at_isr(int irq, void *d)
 {
 	unsigned char intstat;
 	unsigned int samp;
@@ -893,8 +893,8 @@
 	return *ns;
 }
 
-static int dmm32at_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dmm32at_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -910,7 +910,7 @@
 		lo = data[i] & 0x00ff;
 		/* high byte also contains channel number */
 		hi = (data[i] >> 8) + chan * (1 << 6);
-		//printk("writing 0x%02x  0x%02x\n",hi,lo);
+		/* printk("writing 0x%02x  0x%02x\n",hi,lo); */
 		/* write the low and high values to the board */
 		dmm_outb(dev, DMM32AT_DACLSB, lo);
 		dmm_outb(dev, DMM32AT_DACMSB, hi);
@@ -936,8 +936,8 @@
 
 /* AO subdevices should have a read insn as well as a write insn.
  * Usually this means copying a value stored in devpriv. */
-static int dmm32at_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dmm32at_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -953,8 +953,8 @@
  * useful to applications if you implement the insn_bits interface.
  * This allows packed reading/writing of the DIO channels.  The
  * comedi core can convert between insn_bits and insn_read/write */
-static int dmm32at_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dmm32at_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned char diobits;
 
@@ -967,7 +967,7 @@
 		s->state &= ~data[0];
 		s->state |= data[0] & data[1];
 		/* Write out the new digital output lines */
-		//outw(s->state,dev->iobase + DMM32AT_DIO);
+		/* outw(s->state,dev->iobase + DMM32AT_DIO); */
 	}
 
 	/* get access to the DIO regs */
@@ -998,16 +998,16 @@
 
 	/* on return, data[1] contains the value of the digital
 	 * input and output lines. */
-	//data[1]=inw(dev->iobase + DMM32AT_DIO);
+	/* data[1]=inw(dev->iobase + DMM32AT_DIO); */
 	/* or we could just return the software copy of the output values if
 	 * it was a purely digital output subdevice */
-	//data[1]=s->state;
+	/* data[1]=s->state; */
 
 	return 2;
 }
 
-static int dmm32at_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dmm32at_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned char chanbit;
 	int chan = CR_CHAN(insn->chanspec);
@@ -1043,7 +1043,7 @@
 	return 1;
 }
 
-void dmm32at_setaitimer(struct comedi_device * dev, unsigned int nansec)
+void dmm32at_setaitimer(struct comedi_device *dev, unsigned int nansec)
 {
 	unsigned char lo1, lo2, hi2;
 	unsigned short both2;
diff --git a/drivers/staging/comedi/drivers/dt2801.c b/drivers/staging/comedi/drivers/dt2801.c
index 5e0eed8..25a9b21 100644
--- a/drivers/staging/comedi/drivers/dt2801.c
+++ b/drivers/staging/comedi/drivers/dt2801.c
@@ -88,19 +88,19 @@
 #define DT2801_STATUS		1
 #define DT2801_CMD		1
 
-static int dt2801_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dt2801_detach(struct comedi_device * dev);
+static int dt2801_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dt2801_detach(struct comedi_device *dev);
 static struct comedi_driver driver_dt2801 = {
-      driver_name:"dt2801",
-      module:THIS_MODULE,
-      attach:dt2801_attach,
-      detach:dt2801_detach,
+	.driver_name = "dt2801",
+	.module = THIS_MODULE,
+	.attach = dt2801_attach,
+	.detach = dt2801_detach,
 };
 
 COMEDI_INITCLEANUP(driver_dt2801);
 
 #if 0
-// ignore 'defined but not used' warning
+/* ignore 'defined but not used' warning */
 static const struct comedi_lrange range_dt2801_ai_pgh_bipolar = { 4, {
 			RANGE(-10, 10),
 			RANGE(-5, 5),
@@ -118,7 +118,7 @@
 };
 
 #if 0
-// ignore 'defined but not used' warning
+/* ignore 'defined but not used' warning */
 static const struct comedi_lrange range_dt2801_ai_pgh_unipolar = { 4, {
 			RANGE(0, 10),
 			RANGE(0, 5),
@@ -152,72 +152,71 @@
    */
 static const struct dt2801_board boardtypes[] = {
 	{
-	      name:	"dt2801",
-	      boardcode:0x09,
-	      ad_diff:	2,
-	      ad_chan:	16,
-	      adbits:	12,
-	      adrangetype:0,
-      dabits:	12},
+	.name = "dt2801",
+	.boardcode = 0x09,
+	.ad_diff = 2,
+	.ad_chan = 16,
+	.adbits = 12,
+	.adrangetype = 0,
+	.dabits = 12},
 	{
-	      name:	"dt2801-a",
-	      boardcode:0x52,
-	      ad_diff:	2,
-	      ad_chan:	16,
-	      adbits:	12,
-	      adrangetype:0,
-      dabits:	12},
+	.name = "dt2801-a",
+	.boardcode = 0x52,
+	.ad_diff = 2,
+	.ad_chan = 16,
+	.adbits = 12,
+	.adrangetype = 0,
+	.dabits = 12},
 	{
-	      name:	"dt2801/5716a",
-	      boardcode:0x82,
-	      ad_diff:	1,
-	      ad_chan:	16,
-	      adbits:	16,
-	      adrangetype:1,
-      dabits:	12},
+	.name = "dt2801/5716a",
+	.boardcode = 0x82,
+	.ad_diff = 1,
+	.ad_chan = 16,
+	.adbits = 16,
+	.adrangetype = 1,
+	.dabits = 12},
 	{
-	      name:	"dt2805",
-	      boardcode:0x12,
-	      ad_diff:	1,
-	      ad_chan:	16,
-	      adbits:	12,
-	      adrangetype:0,
-      dabits:	12},
+	.name = "dt2805",
+	.boardcode = 0x12,
+	.ad_diff = 1,
+	.ad_chan = 16,
+	.adbits = 12,
+	.adrangetype = 0,
+	.dabits = 12},
 	{
-	      name:	"dt2805/5716a",
-	      boardcode:0x92,
-	      ad_diff:	1,
-	      ad_chan:	16,
-	      adbits:	16,
-	      adrangetype:1,
-      dabits:	12},
+	.name = "dt2805/5716a",
+	.boardcode = 0x92,
+	.ad_diff = 1,
+	.ad_chan = 16,
+	.adbits = 16,
+	.adrangetype = 1,
+	.dabits = 12},
 	{
-	      name:	"dt2808",
-	      boardcode:0x20,
-	      ad_diff:	0,
-	      ad_chan:	16,
-	      adbits:	12,
-	      adrangetype:2,
-      dabits:	8},
+	.name = "dt2808",
+	.boardcode = 0x20,
+	.ad_diff = 0,
+	.ad_chan = 16,
+	.adbits = 12,
+	.adrangetype = 2,
+	.dabits = 8},
 	{
-	      name:	"dt2818",
-	      boardcode:0xa2,
-	      ad_diff:	0,
-	      ad_chan:	4,
-	      adbits:	12,
-	      adrangetype:0,
-      dabits:	12},
+	.name = "dt2818",
+	.boardcode = 0xa2,
+	.ad_diff = 0,
+	.ad_chan = 4,
+	.adbits = 12,
+	.adrangetype = 0,
+	.dabits = 12},
 	{
-	      name:	"dt2809",
-	      boardcode:0xb0,
-	      ad_diff:	0,
-	      ad_chan:	8,
-	      adbits:	12,
-	      adrangetype:1,
-      dabits:	12},
+	.name = "dt2809",
+	.boardcode = 0xb0,
+	.ad_diff = 0,
+	.ad_chan = 8,
+	.adbits = 12,
+	.adrangetype = 1,
+	.dabits = 12},
 };
 
-#define n_boardtypes ((sizeof(boardtypes))/(sizeof(boardtypes[0])))
 #define boardtype (*(const struct dt2801_board *)dev->board_ptr)
 
 struct dt2801_private {
@@ -228,16 +227,16 @@
 
 #define devpriv ((struct dt2801_private *)dev->private)
 
-static int dt2801_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dt2801_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dt2801_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dt2801_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dt2801_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int dt2801_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dt2801_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dt2801_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dt2801_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dt2801_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 /* These are the low-level routines:
    writecommand: write a command to the board
@@ -248,7 +247,7 @@
 /* Only checks DataOutReady-flag, not the Ready-flag as it is done
    in the examples of the manual. I don't see why this should be
    necessary. */
-static int dt2801_readdata(struct comedi_device * dev, int *data)
+static int dt2801_readdata(struct comedi_device *dev, int *data)
 {
 	int stat = 0;
 	int timeout = DT2801_TIMEOUT;
@@ -267,7 +266,7 @@
 	return -ETIME;
 }
 
-static int dt2801_readdata2(struct comedi_device * dev, int *data)
+static int dt2801_readdata2(struct comedi_device *dev, int *data)
 {
 	int lb, hb;
 	int ret;
@@ -283,7 +282,7 @@
 	return 0;
 }
 
-static int dt2801_writedata(struct comedi_device * dev, unsigned int data)
+static int dt2801_writedata(struct comedi_device *dev, unsigned int data)
 {
 	int stat = 0;
 	int timeout = DT2801_TIMEOUT;
@@ -309,7 +308,7 @@
 	return -ETIME;
 }
 
-static int dt2801_writedata2(struct comedi_device * dev, unsigned int data)
+static int dt2801_writedata2(struct comedi_device *dev, unsigned int data)
 {
 	int ret;
 
@@ -323,7 +322,7 @@
 	return 0;
 }
 
-static int dt2801_wait_for_ready(struct comedi_device * dev)
+static int dt2801_wait_for_ready(struct comedi_device *dev)
 {
 	int timeout = DT2801_TIMEOUT;
 	int stat;
@@ -346,7 +345,7 @@
 	return -ETIME;
 }
 
-static int dt2801_writecmd(struct comedi_device * dev, int command)
+static int dt2801_writecmd(struct comedi_device *dev, int command)
 {
 	int stat;
 
@@ -364,7 +363,7 @@
 	return 0;
 }
 
-static int dt2801_reset(struct comedi_device * dev)
+static int dt2801_reset(struct comedi_device *dev)
 {
 	int board_code = 0;
 	unsigned int stat;
@@ -381,11 +380,11 @@
 	inb_p(dev->iobase + DT2801_DATA);
 
 	DPRINTK("dt2801: stop\n");
-	//dt2801_writecmd(dev,DT_C_STOP);
+	/* dt2801_writecmd(dev,DT_C_STOP); */
 	outb_p(DT_C_STOP, dev->iobase + DT2801_CMD);
 
-	//dt2801_wait_for_ready(dev);
-	comedi_udelay(100);
+	/* dt2801_wait_for_ready(dev); */
+	udelay(100);
 	timeout = 10000;
 	do {
 		stat = inb_p(dev->iobase + DT2801_STATUS);
@@ -395,14 +394,15 @@
 	if (!timeout) {
 		printk("dt2801: timeout 1 status=0x%02x\n", stat);
 	}
-	//printk("dt2801: reading dummy\n");
-	//dt2801_readdata(dev,&board_code);
+
+	/* printk("dt2801: reading dummy\n"); */
+	/* dt2801_readdata(dev,&board_code); */
 
 	DPRINTK("dt2801: reset\n");
 	outb_p(DT_C_RESET, dev->iobase + DT2801_CMD);
-	//dt2801_writecmd(dev,DT_C_RESET);
+	/* dt2801_writecmd(dev,DT_C_RESET); */
 
-	comedi_udelay(100);
+	udelay(100);
 	timeout = 10000;
 	do {
 		stat = inb_p(dev->iobase + DT2801_STATUS);
@@ -421,7 +421,7 @@
 	return board_code;
 }
 
-static int probe_number_of_ai_chans(struct comedi_device * dev)
+static int probe_number_of_ai_chans(struct comedi_device *dev)
 {
 	int n_chans;
 	int stat;
@@ -482,7 +482,7 @@
 	[4] - dac0 range 0=[-10,10], 1=[-5,5], 2=[-2.5,2.5] 3=[0,10], 4=[0,5]
 	[5] - dac1 range 0=[-10,10], 1=[-5,5], 2=[-2.5,2.5] 3=[0,10], 4=[0,5]
 */
-static int dt2801_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dt2801_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase;
@@ -505,7 +505,7 @@
 	if (!board_code)
 		board_code = dt2801_reset(dev);
 
-	for (type = 0; type < n_boardtypes; type++) {
+	for (type = 0; type < ARRAY_SIZE(boardtypes); type++) {
 		if (boardtypes[type].boardcode == board_code)
 			goto havetype;
 	}
@@ -520,10 +520,12 @@
 	n_ai_chans = probe_number_of_ai_chans(dev);
 	printk(" (ai channels = %d)", n_ai_chans);
 
-	if ((ret = alloc_subdevices(dev, 4)) < 0)
+	ret = alloc_subdevices(dev, 4);
+	if (ret < 0)
 		goto out;
 
-	if ((ret = alloc_private(dev, sizeof(struct dt2801_private))) < 0)
+	ret = alloc_private(dev, sizeof(struct dt2801_private));
+	if (ret < 0)
 		goto out;
 
 	dev->board_name = boardtype.name;
@@ -583,7 +585,7 @@
 	return ret;
 }
 
-static int dt2801_detach(struct comedi_device * dev)
+static int dt2801_detach(struct comedi_device *dev)
 {
 	if (dev->iobase)
 		release_region(dev->iobase, DT2801_IOSIZE);
@@ -591,7 +593,7 @@
 	return 0;
 }
 
-static int dt2801_error(struct comedi_device * dev, int stat)
+static int dt2801_error(struct comedi_device *dev, int stat)
 {
 	if (stat < 0) {
 		if (stat == -ETIME) {
@@ -609,8 +611,8 @@
 	return -EIO;
 }
 
-static int dt2801_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2801_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int d;
 	int stat;
@@ -631,16 +633,16 @@
 	return i;
 }
 
-static int dt2801_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2801_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->ao_readback[CR_CHAN(insn->chanspec)];
 
 	return 1;
 }
 
-static int dt2801_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2801_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	dt2801_writecmd(dev, DT_C_WRITE_DAIM);
 	dt2801_writedata(dev, CR_CHAN(insn->chanspec));
@@ -651,8 +653,8 @@
 	return 1;
 }
 
-static int dt2801_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2801_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int which = 0;
 
@@ -675,8 +677,8 @@
 	return 2;
 }
 
-static int dt2801_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2801_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int which = 0;
 
diff --git a/drivers/staging/comedi/drivers/dt2811.c b/drivers/staging/comedi/drivers/dt2811.c
index 795932e..7853902 100644
--- a/drivers/staging/comedi/drivers/dt2811.c
+++ b/drivers/staging/comedi/drivers/dt2811.c
@@ -45,6 +45,7 @@
   [4] - D/A 1 range (same choices)
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -214,30 +215,30 @@
 
 #define this_board ((const struct dt2811_board *)dev->board_ptr)
 
-static int dt2811_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dt2811_detach(struct comedi_device * dev);
+static int dt2811_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dt2811_detach(struct comedi_device *dev);
 static struct comedi_driver driver_dt2811 = {
-      driver_name:"dt2811",
-      module:THIS_MODULE,
-      attach:dt2811_attach,
-      detach:dt2811_detach,
-      board_name:&boardtypes[0].name,
-      num_names:sizeof(boardtypes) / sizeof(struct dt2811_board),
-      offset:sizeof(struct dt2811_board),
+	.driver_name = "dt2811",
+	.module = THIS_MODULE,
+	.attach = dt2811_attach,
+	.detach = dt2811_detach,
+	.board_name = &boardtypes[0].name,
+	.num_names = ARRAY_SIZE(boardtypes),
+	.offset = sizeof(struct dt2811_board),
 };
 
 COMEDI_INITCLEANUP(driver_dt2811);
 
-static int dt2811_ai_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dt2811_ao_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dt2811_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dt2811_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int dt2811_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int dt2811_ai_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dt2811_ao_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dt2811_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dt2811_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int dt2811_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 enum { card_2811_pgh, card_2811_pgl };
 
@@ -265,7 +266,7 @@
 #define DT2811_TIMEOUT 5
 
 #if 0
-static irqreturn_t dt2811_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t dt2811_interrupt(int irq, void *d)
 {
 	int lo, hi;
 	int data;
@@ -311,11 +312,12 @@
                  2 == unipolar 5V  (0V -- +5V)
 */
 
-static int dt2811_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dt2811_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
-	//int i, irq;
-	//unsigned long irqs;
-	//long flags;
+	/* int i, irq; */
+	/* unsigned long irqs; */
+	/* long flags; */
+
 	int ret;
 	struct comedi_subdevice *s;
 	unsigned long iobase;
@@ -334,7 +336,7 @@
 
 #if 0
 	outb(0, dev->iobase + DT2811_ADCSR);
-	comedi_udelay(100);
+	udelay(100);
 	i = inb(dev->iobase + DT2811_ADDATLO);
 	i = inb(dev->iobase + DT2811_ADDATHI);
 #endif
@@ -350,7 +352,7 @@
 			dev->iobase + DT2811_ADCSR);
 		outb(0, dev->iobase + DT2811_ADGCR);
 
-		comedi_udelay(100);
+		udelay(100);
 
 		irq = probe_irq_off(irqs);
 		restore_flags(flags);
@@ -365,7 +367,7 @@
 			i = inb(dev->iobase + DT2811_ADDATLO);
 			i = inb(dev->iobase + DT2811_ADDATHI);
 			printk("(irq = %d)\n", irq);
-			ret = comedi_request_irq(irq, dt2811_interrupt, 0,
+			ret = request_irq(irq, dt2811_interrupt, 0,
 				driver_name, dev);
 			if (ret < 0)
 				return -EIO;
@@ -378,10 +380,14 @@
 	}
 #endif
 
-	if ((ret = alloc_subdevices(dev, 4)) < 0)
+	ret = alloc_subdevices(dev, 4);
+	if (ret < 0)
 		return ret;
-	if ((ret = alloc_private(dev, sizeof(struct dt2811_private))) < 0)
+
+	ret = alloc_private(dev, sizeof(struct dt2811_private));
+	if (ret < 0)
 		return ret;
+
 	switch (it->options[2]) {
 	case 0:
 		devpriv->adc_mux = adc_singleended;
@@ -479,12 +485,12 @@
 	return 0;
 }
 
-static int dt2811_detach(struct comedi_device * dev)
+static int dt2811_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: dt2811: remove\n", dev->minor);
 
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 	if (dev->iobase) {
 		release_region(dev->iobase, DT2811_SIZE);
@@ -493,8 +499,8 @@
 	return 0;
 }
 
-static int dt2811_ai_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2811_ai_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 	int timeout = DT2811_TIMEOUT;
@@ -520,7 +526,7 @@
 #if 0
 /* Wow.  This is code from the Comedi stone age.  But it hasn't been
  * replaced, so I'll let it stay. */
-int dt2811_adtrig(kdev_t minor, comedi_adtrig * adtrig)
+int dt2811_adtrig(kdev_t minor, comedi_adtrig *adtrig)
 {
 	struct comedi_device *dev = comedi_devices + minor;
 
@@ -531,7 +537,7 @@
 	case COMEDI_MDEMAND:
 		dev->ntrig = adtrig->n - 1;
 		/*printk("dt2811: AD soft trigger\n"); */
-		/*outb(DT2811_CLRERROR|DT2811_INTENB,dev->iobase+DT2811_ADCSR); *//* not neccessary */
+		/*outb(DT2811_CLRERROR|DT2811_INTENB,dev->iobase+DT2811_ADCSR); */ /* not neccessary */
 		outb(dev->curadchan, dev->iobase + DT2811_ADGCR);
 		do_gettimeofday(&trigtime);
 		break;
@@ -544,8 +550,8 @@
 }
 #endif
 
-static int dt2811_ao_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2811_ao_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan;
@@ -562,8 +568,8 @@
 	return i;
 }
 
-static int dt2811_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2811_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan;
@@ -577,8 +583,8 @@
 	return i;
 }
 
-static int dt2811_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2811_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -588,8 +594,8 @@
 	return 2;
 }
 
-static int dt2811_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2811_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
diff --git a/drivers/staging/comedi/drivers/dt2814.c b/drivers/staging/comedi/drivers/dt2814.c
index 8320139..5906ddd 100644
--- a/drivers/staging/comedi/drivers/dt2814.c
+++ b/drivers/staging/comedi/drivers/dt2814.c
@@ -39,6 +39,7 @@
 addition, the clock does not seem to be very accurate.
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -59,18 +60,18 @@
 #define DT2814_ENB 0x10
 #define DT2814_CHANMASK 0x0f
 
-static int dt2814_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dt2814_detach(struct comedi_device * dev);
+static int dt2814_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dt2814_detach(struct comedi_device *dev);
 static struct comedi_driver driver_dt2814 = {
-      driver_name:"dt2814",
-      module:THIS_MODULE,
-      attach:dt2814_attach,
-      detach:dt2814_detach,
+	.driver_name = "dt2814",
+	.module = THIS_MODULE,
+	.attach = dt2814_attach,
+	.detach = dt2814_detach,
 };
 
 COMEDI_INITCLEANUP(driver_dt2814);
 
-static irqreturn_t dt2814_interrupt(int irq, void *dev PT_REGS_ARG);
+static irqreturn_t dt2814_interrupt(int irq, void *dev);
 
 struct dt2814_private {
 
@@ -83,8 +84,8 @@
 #define DT2814_TIMEOUT 10
 #define DT2814_MAX_SPEED 100000	/* Arbitrary 10 khz limit */
 
-static int dt2814_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2814_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, i, hi, lo;
 	int chan;
@@ -97,7 +98,7 @@
 		for (i = 0; i < DT2814_TIMEOUT; i++) {
 			status = inb(dev->iobase + DT2814_CSR);
 			printk("dt2814: status: %02x\n", status);
-			comedi_udelay(10);
+			udelay(10);
 			if (status & DT2814_FINISH)
 				break;
 		}
@@ -134,8 +135,8 @@
 	return i;
 }
 
-static int dt2814_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int dt2814_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -226,7 +227,7 @@
 	return 0;
 }
 
-static int dt2814_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dt2814_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	int chan;
@@ -245,7 +246,7 @@
 
 }
 
-static int dt2814_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dt2814_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int i, irq;
 	int ret;
@@ -262,7 +263,7 @@
 	dev->board_name = "dt2814";
 
 	outb(0, dev->iobase + DT2814_CSR);
-	comedi_udelay(100);
+	udelay(100);
 	if (inb(dev->iobase + DT2814_CSR) & DT2814_ERR) {
 		printk("reset error (fatal)\n");
 		return -EIO;
@@ -279,7 +280,7 @@
 
 		outb(0, dev->iobase + DT2814_CSR);
 
-		comedi_udelay(100);
+		udelay(100);
 
 		irq = probe_irq_off(irqs);
 		restore_flags(flags);
@@ -293,7 +294,7 @@
 #endif
 	dev->irq = 0;
 	if (irq > 0) {
-		if (comedi_request_irq(irq, dt2814_interrupt, 0, "dt2814", dev)) {
+		if (request_irq(irq, dt2814_interrupt, 0, "dt2814", dev)) {
 			printk("(irq %d unavailable)\n", irq);
 		} else {
 			printk("( irq = %d )\n", irq);
@@ -309,9 +310,12 @@
 #endif
 	}
 
-	if ((ret = alloc_subdevices(dev, 1)) < 0)
+	ret = alloc_subdevices(dev, 1);
+	if (ret < 0)
 		return ret;
-	if ((ret = alloc_private(dev, sizeof(struct dt2814_private))) < 0)
+
+	ret = alloc_private(dev, sizeof(struct dt2814_private));
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -329,12 +333,12 @@
 	return 0;
 }
 
-static int dt2814_detach(struct comedi_device * dev)
+static int dt2814_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: dt2814: remove\n", dev->minor);
 
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 	if (dev->iobase) {
 		release_region(dev->iobase, DT2814_SIZE);
@@ -343,7 +347,7 @@
 	return 0;
 }
 
-static irqreturn_t dt2814_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t dt2814_interrupt(int irq, void *d)
 {
 	int lo, hi;
 	struct comedi_device *dev = d;
diff --git a/drivers/staging/comedi/drivers/dt2815.c b/drivers/staging/comedi/drivers/dt2815.c
index fccec8a..b42dec6 100644
--- a/drivers/staging/comedi/drivers/dt2815.c
+++ b/drivers/staging/comedi/drivers/dt2815.c
@@ -75,18 +75,18 @@
 #define DT2815_DATA 0
 #define DT2815_STATUS 1
 
-static int dt2815_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dt2815_detach(struct comedi_device * dev);
+static int dt2815_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dt2815_detach(struct comedi_device *dev);
 static struct comedi_driver driver_dt2815 = {
-      driver_name:"dt2815",
-      module:THIS_MODULE,
-      attach:dt2815_attach,
-      detach:dt2815_detach,
+	.driver_name = "dt2815",
+	.module = THIS_MODULE,
+	.attach = dt2815_attach,
+	.detach = dt2815_detach,
 };
 
 COMEDI_INITCLEANUP(driver_dt2815);
 
-static void dt2815_free_resources(struct comedi_device * dev);
+static void dt2815_free_resources(struct comedi_device *dev);
 
 struct dt2815_private {
 
@@ -97,7 +97,7 @@
 
 #define devpriv ((struct dt2815_private *)dev->private)
 
-static int dt2815_wait_for_status(struct comedi_device * dev, int status)
+static int dt2815_wait_for_status(struct comedi_device *dev, int status)
 {
 	int i;
 
@@ -108,8 +108,8 @@
 	return status;
 }
 
-static int dt2815_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2815_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -121,8 +121,8 @@
 	return i;
 }
 
-static int dt2815_ao_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2815_ao_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -135,7 +135,7 @@
 
 		status = dt2815_wait_for_status(dev, 0x00);
 		if (status != 0) {
-			rt_printk
+			printk
 				("dt2815: failed to write low byte on %d reason %x\n",
 				chan, status);
 			return -EBUSY;
@@ -145,7 +145,7 @@
 
 		status = dt2815_wait_for_status(dev, 0x10);
 		if (status != 0x10) {
-			rt_printk
+			printk
 				("dt2815: failed to write high byte on %d reason %x\n",
 				chan, status);
 			return -EBUSY;
@@ -179,7 +179,7 @@
                  1 == current
  */
 
-static int dt2815_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dt2815_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int i;
@@ -226,7 +226,7 @@
 		/* This is incredibly slow (approx 20 ms) */
 		unsigned int status;
 
-		comedi_udelay(1000);
+		udelay(1000);
 		status = inb(dev->iobase + DT2815_STATUS);
 		if (status == 4) {
 			unsigned int program;
@@ -248,13 +248,13 @@
 	return 0;
 }
 
-static void dt2815_free_resources(struct comedi_device * dev)
+static void dt2815_free_resources(struct comedi_device *dev)
 {
 	if (dev->iobase)
 		release_region(dev->iobase, DT2815_SIZE);
 }
 
-static int dt2815_detach(struct comedi_device * dev)
+static int dt2815_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: dt2815: remove\n", dev->minor);
 
diff --git a/drivers/staging/comedi/drivers/dt2817.c b/drivers/staging/comedi/drivers/dt2817.c
index 2dc396a..b36f8563 100644
--- a/drivers/staging/comedi/drivers/dt2817.c
+++ b/drivers/staging/comedi/drivers/dt2817.c
@@ -47,19 +47,19 @@
 #define DT2817_CR 0
 #define DT2817_DATA 1
 
-static int dt2817_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dt2817_detach(struct comedi_device * dev);
+static int dt2817_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dt2817_detach(struct comedi_device *dev);
 static struct comedi_driver driver_dt2817 = {
-      driver_name:"dt2817",
-      module:THIS_MODULE,
-      attach:dt2817_attach,
-      detach:dt2817_detach,
+	.driver_name = "dt2817",
+	.module = THIS_MODULE,
+	.attach = dt2817_attach,
+	.detach = dt2817_detach,
 };
 
 COMEDI_INITCLEANUP(driver_dt2817);
 
-static int dt2817_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2817_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int mask;
 	int chan;
@@ -96,8 +96,8 @@
 	return 1;
 }
 
-static int dt2817_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt2817_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int changed;
 
@@ -131,7 +131,7 @@
 	return 2;
 }
 
-static int dt2817_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dt2817_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int ret;
 	struct comedi_subdevice *s;
@@ -146,7 +146,8 @@
 	dev->iobase = iobase;
 	dev->board_name = "dt2817";
 
-	if ((ret = alloc_subdevices(dev, 1)) < 0)
+	ret = alloc_subdevices(dev, 1);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -167,7 +168,7 @@
 	return 0;
 }
 
-static int dt2817_detach(struct comedi_device * dev)
+static int dt2817_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: dt2817: remove\n", dev->minor);
 
diff --git a/drivers/staging/comedi/drivers/dt282x.c b/drivers/staging/comedi/drivers/dt282x.c
index 4882c3e..22b7304 100644
--- a/drivers/staging/comedi/drivers/dt282x.c
+++ b/drivers/staging/comedi/drivers/dt282x.c
@@ -209,132 +209,132 @@
 };
 
 static const struct dt282x_board boardtypes[] = {
-      {name:"dt2821",
-	      adbits:	12,
-	      adchan_se:16,
-	      adchan_di:8,
-	      ai_speed:20000,
-	      ispgl:	0,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt2821-f",
-	      adbits:	12,
-	      adchan_se:16,
-	      adchan_di:8,
-	      ai_speed:6500,
-	      ispgl:	0,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt2821-g",
-	      adbits:	12,
-	      adchan_se:16,
-	      adchan_di:8,
-	      ai_speed:4000,
-	      ispgl:	0,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt2823",
-	      adbits:	16,
-	      adchan_se:0,
-	      adchan_di:4,
-	      ai_speed:10000,
-	      ispgl:	0,
-	      dachan:	2,
-	      dabits:	16,
-		},
-      {name:"dt2824-pgh",
-	      adbits:	12,
-	      adchan_se:16,
-	      adchan_di:8,
-	      ai_speed:20000,
-	      ispgl:	0,
-	      dachan:	0,
-	      dabits:	0,
-		},
-      {name:"dt2824-pgl",
-	      adbits:	12,
-	      adchan_se:16,
-	      adchan_di:8,
-	      ai_speed:20000,
-	      ispgl:	1,
-	      dachan:	0,
-	      dabits:	0,
-		},
-      {name:"dt2825",
-	      adbits:	12,
-	      adchan_se:16,
-	      adchan_di:8,
-	      ai_speed:20000,
-	      ispgl:	1,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt2827",
-	      adbits:	16,
-	      adchan_se:0,
-	      adchan_di:4,
-	      ai_speed:10000,
-	      ispgl:	0,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt2828",
-	      adbits:	12,
-	      adchan_se:4,
-	      adchan_di:0,
-	      ai_speed:10000,
-	      ispgl:	0,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt2829",
-	      adbits:	16,
-	      adchan_se:8,
-	      adchan_di:0,
-	      ai_speed:33250,
-	      ispgl:	0,
-	      dachan:	2,
-	      dabits:	16,
-		},
-      {name:"dt21-ez",
-	      adbits:	12,
-	      adchan_se:16,
-	      adchan_di:8,
-	      ai_speed:10000,
-	      ispgl:	0,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt23-ez",
-	      adbits:	16,
-	      adchan_se:16,
-	      adchan_di:8,
-	      ai_speed:10000,
-	      ispgl:	0,
-	      dachan:	0,
-	      dabits:	0,
-		},
-      {name:"dt24-ez",
-	      adbits:	12,
-	      adchan_se:16,
-	      adchan_di:8,
-	      ai_speed:10000,
-	      ispgl:	0,
-	      dachan:	0,
-	      dabits:	0,
-		},
-      {name:"dt24-ez-pgl",
-	      adbits:	12,
-	      adchan_se:16,
-	      adchan_di:8,
-	      ai_speed:10000,
-	      ispgl:	1,
-	      dachan:	0,
-	      dabits:	0,
-		},
+	{.name = "dt2821",
+	 .adbits = 12,
+	 .adchan_se = 16,
+	 .adchan_di = 8,
+	 .ai_speed = 20000,
+	 .ispgl = 0,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+	{.name = "dt2821-f",
+	 .adbits = 12,
+	 .adchan_se = 16,
+	 .adchan_di = 8,
+	 .ai_speed = 6500,
+	 .ispgl = 0,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+	{.name = "dt2821-g",
+	 .adbits = 12,
+	 .adchan_se = 16,
+	 .adchan_di = 8,
+	 .ai_speed = 4000,
+	 .ispgl = 0,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+	{.name = "dt2823",
+	 .adbits = 16,
+	 .adchan_se = 0,
+	 .adchan_di = 4,
+	 .ai_speed = 10000,
+	 .ispgl = 0,
+	 .dachan = 2,
+	 .dabits = 16,
+	},
+	{.name = "dt2824-pgh",
+	  .adbits = 12,
+	  .adchan_se = 16,
+	  .adchan_di = 8,
+	  .ai_speed = 20000,
+	  .ispgl = 0,
+	  .dachan = 0,
+	  .dabits = 0,
+	},
+	{.name = "dt2824-pgl",
+	 .adbits = 12,
+	 .adchan_se = 16,
+	 .adchan_di = 8,
+	 .ai_speed = 20000,
+	 .ispgl = 1,
+	 .dachan = 0,
+	 .dabits = 0,
+	},
+	{.name = "dt2825",
+	 .adbits = 12,
+	 .adchan_se = 16,
+	 .adchan_di = 8,
+	 .ai_speed = 20000,
+	 .ispgl = 1,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+	{.name = "dt2827",
+	 .adbits = 16,
+	 .adchan_se = 0,
+	 .adchan_di = 4,
+	 .ai_speed = 10000,
+	 .ispgl = 0,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+	{.name = "dt2828",
+	 .adbits = 12,
+	 .adchan_se = 4,
+	 .adchan_di = 0,
+	 .ai_speed = 10000,
+	 .ispgl = 0,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+	{.name = "dt2829",
+	 .adbits = 16,
+	 .adchan_se = 8,
+	 .adchan_di = 0,
+	 .ai_speed = 33250,
+	 .ispgl = 0,
+	 .dachan = 2,
+	 .dabits = 16,
+	},
+	{.name = "dt21-ez",
+	 .adbits = 12,
+	 .adchan_se = 16,
+	 .adchan_di = 8,
+	 .ai_speed = 10000,
+	 .ispgl = 0,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+	{.name = "dt23-ez",
+	 .adbits = 16,
+	 .adchan_se = 16,
+	 .adchan_di = 8,
+	 .ai_speed = 10000,
+	 .ispgl = 0,
+	 .dachan = 0,
+	 .dabits = 0,
+	},
+	{.name = "dt24-ez",
+	 .adbits = 12,
+	 .adchan_se = 16,
+	 .adchan_di = 8,
+	 .ai_speed = 10000,
+	 .ispgl = 0,
+	 .dachan = 0,
+	 .dabits = 0,
+	},
+	{.name = "dt24-ez-pgl",
+	 .adbits = 12,
+	 .adchan_se = 16,
+	 .adchan_di = 8,
+	 .ai_speed = 10000,
+	 .ispgl = 1,
+	 .dachan = 0,
+	 .dabits = 0,
+	},
 };
 
 #define n_boardtypes sizeof(boardtypes)/sizeof(struct dt282x_board)
@@ -374,51 +374,51 @@
  *    Some useless abstractions
  */
 #define chan_to_DAC(a)	((a)&1)
-#define update_dacsr(a)	outw(devpriv->dacsr|(a),dev->iobase+DT2821_DACSR)
-#define update_adcsr(a)	outw(devpriv->adcsr|(a),dev->iobase+DT2821_ADCSR)
+#define update_dacsr(a)	outw(devpriv->dacsr|(a), dev->iobase+DT2821_DACSR)
+#define update_adcsr(a)	outw(devpriv->adcsr|(a), dev->iobase+DT2821_ADCSR)
 #define mux_busy() (inw(dev->iobase+DT2821_ADCSR)&DT2821_MUXBUSY)
 #define ad_done() (inw(dev->iobase+DT2821_ADCSR)&DT2821_ADDONE)
-#define update_supcsr(a)	outw(devpriv->supcsr|(a),dev->iobase+DT2821_SUPCSR)
+#define update_supcsr(a)	outw(devpriv->supcsr|(a), dev->iobase+DT2821_SUPCSR)
 
 /*
  *    danger! macro abuse... a is the expression to wait on, and b is
  *      the statement(s) to execute if it doesn't happen.
  */
-#define wait_for(a,b)	 				\
+#define wait_for(a, b)	 				\
 	do{						\
 		int _i;					\
-		for(_i=0;_i<DT2821_TIMEOUT;_i++){	\
-			if(a){_i=0;break;}		\
-			comedi_udelay(5);			\
+		for (_i=0;_i<DT2821_TIMEOUT;_i++){	\
+			if (a){_i=0;break;}		\
+			udelay(5);			\
 		}					\
-		if(_i){b}				\
-	}while(0)
+		if (_i){b}				\
+	}while (0)
 
-static int dt282x_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dt282x_detach(struct comedi_device * dev);
+static int dt282x_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dt282x_detach(struct comedi_device *dev);
 static struct comedi_driver driver_dt282x = {
-      driver_name:"dt282x",
-      module:THIS_MODULE,
-      attach:dt282x_attach,
-      detach:dt282x_detach,
-      board_name:&boardtypes[0].name,
-      num_names:n_boardtypes,
-      offset:sizeof(struct dt282x_board),
+	.driver_name = "dt282x",
+	.module = THIS_MODULE,
+	.attach = dt282x_attach,
+	.detach = dt282x_detach,
+	.board_name = &boardtypes[0].name,
+	.num_names = n_boardtypes,
+	.offset = sizeof(struct dt282x_board),
 };
 
 COMEDI_INITCLEANUP(driver_dt282x);
 
-static void free_resources(struct comedi_device * dev);
-static int prep_ai_dma(struct comedi_device * dev, int chan, int size);
-static int prep_ao_dma(struct comedi_device * dev, int chan, int size);
-static int dt282x_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static int dt282x_ao_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
+static void free_resources(struct comedi_device *dev);
+static int prep_ai_dma(struct comedi_device *dev, int chan, int size);
+static int prep_ao_dma(struct comedi_device *dev, int chan, int size);
+static int dt282x_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static int dt282x_ao_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
 static int dt282x_ns_to_timer(int *nanosec, int round_mode);
-static void dt282x_disable_dma(struct comedi_device * dev);
+static void dt282x_disable_dma(struct comedi_device *dev);
 
-static int dt282x_grab_dma(struct comedi_device * dev, int dma1, int dma2);
+static int dt282x_grab_dma(struct comedi_device *dev, int dma1, int dma2);
 
-static void dt282x_munge(struct comedi_device * dev, short * buf,
+static void dt282x_munge(struct comedi_device *dev, short *buf,
 	unsigned int nbytes)
 {
 	unsigned int i;
@@ -440,7 +440,7 @@
 	}
 }
 
-static void dt282x_ao_dma_interrupt(struct comedi_device * dev)
+static void dt282x_ao_dma_interrupt(struct comedi_device *dev)
 {
 	void *ptr;
 	int size;
@@ -463,7 +463,7 @@
 
 	size = cfc_read_array_from_buffer(s, ptr, devpriv->dma_maxsize);
 	if (size == 0) {
-		rt_printk("dt282x: AO underrun\n");
+		printk("dt282x: AO underrun\n");
 		dt282x_ao_cancel(dev, s);
 		s->async->events |= COMEDI_CB_OVERFLOW;
 		return;
@@ -472,7 +472,7 @@
 	return;
 }
 
-static void dt282x_ai_dma_interrupt(struct comedi_device * dev)
+static void dt282x_ai_dma_interrupt(struct comedi_device *dev)
 {
 	void *ptr;
 	int size;
@@ -524,7 +524,7 @@
 	prep_ai_dma(dev, i, 0);
 }
 
-static int prep_ai_dma(struct comedi_device * dev, int dma_index, int n)
+static int prep_ai_dma(struct comedi_device *dev, int dma_index, int n)
 {
 	int dma_chan;
 	unsigned long dma_ptr;
@@ -555,7 +555,7 @@
 	return n;
 }
 
-static int prep_ao_dma(struct comedi_device * dev, int dma_index, int n)
+static int prep_ao_dma(struct comedi_device *dev, int dma_index, int n)
 {
 	int dma_chan;
 	unsigned long dma_ptr;
@@ -577,7 +577,7 @@
 	return n;
 }
 
-static irqreturn_t dt282x_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t dt282x_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s;
@@ -653,7 +653,7 @@
 	return IRQ_RETVAL(handled);
 }
 
-static void dt282x_load_changain(struct comedi_device * dev, int n,
+static void dt282x_load_changain(struct comedi_device *dev, int n,
 	unsigned int *chanlist)
 {
 	unsigned int i;
@@ -674,8 +674,8 @@
  *      - preload multiplexer
  *      - trigger conversion and wait for it to finish
  */
-static int dt282x_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt282x_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 
@@ -706,8 +706,8 @@
 	return i;
 }
 
-static int dt282x_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int dt282x_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -818,7 +818,7 @@
 	return 0;
 }
 
-static int dt282x_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dt282x_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	int timer;
@@ -879,7 +879,7 @@
 	return 0;
 }
 
-static void dt282x_disable_dma(struct comedi_device * dev)
+static void dt282x_disable_dma(struct comedi_device *dev)
 {
 	if (devpriv->usedma) {
 		disable_dma(devpriv->dma[0].chan);
@@ -887,7 +887,7 @@
 	}
 }
 
-static int dt282x_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dt282x_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	dt282x_disable_dma(dev);
 
@@ -937,16 +937,16 @@
  *      offset binary if necessary, loads the data into the DAC
  *      data register, and performs the conversion.
  */
-static int dt282x_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt282x_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->ao[CR_CHAN(insn->chanspec)];
 
 	return 1;
 }
 
-static int dt282x_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt282x_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	short d;
 	unsigned int chan;
@@ -978,8 +978,8 @@
 	return 1;
 }
 
-static int dt282x_ao_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int dt282x_ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -1029,7 +1029,7 @@
 		cmd->start_arg = 0;
 		err++;
 	}
-	if (cmd->scan_begin_arg < 5000 /* XXX unknown */ ) {
+	if (cmd->scan_begin_arg < 5000 /* XXX unknown */) {
 		cmd->scan_begin_arg = 5000;
 		err++;
 	}
@@ -1069,7 +1069,7 @@
 
 }
 
-static int dt282x_ao_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
+static int dt282x_ao_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int x)
 {
 	int size;
@@ -1080,7 +1080,7 @@
 	size = cfc_read_array_from_buffer(s, devpriv->dma[0].buf,
 		devpriv->dma_maxsize);
 	if (size == 0) {
-		rt_printk("dt282x: AO underrun\n");
+		printk("dt282x: AO underrun\n");
 		return -EPIPE;
 	}
 	prep_ao_dma(dev, 0, size);
@@ -1088,7 +1088,7 @@
 	size = cfc_read_array_from_buffer(s, devpriv->dma[1].buf,
 		devpriv->dma_maxsize);
 	if (size == 0) {
-		rt_printk("dt282x: AO underrun\n");
+		printk("dt282x: AO underrun\n");
 		return -EPIPE;
 	}
 	prep_ao_dma(dev, 1, size);
@@ -1099,7 +1099,7 @@
 	return 1;
 }
 
-static int dt282x_ao_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dt282x_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int timer;
 	struct comedi_cmd *cmd = &s->async->cmd;
@@ -1132,7 +1132,7 @@
 	return 0;
 }
 
-static int dt282x_ao_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dt282x_ao_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	dt282x_disable_dma(dev);
 
@@ -1145,8 +1145,8 @@
 	return 0;
 }
 
-static int dt282x_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt282x_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (data[0]) {
 		s->state &= ~data[0];
@@ -1159,8 +1159,8 @@
 	return 2;
 }
 
-static int dt282x_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt282x_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int mask;
 
@@ -1240,7 +1240,7 @@
    9	ao0 0=±10 V, 1=0-10 V, 2=±5 V, 3=0-5 V, 4=±2.5 V
    10	ao1 0=±10 V, 1=0-10 V, 2=±5 V, 3=0-5 V, 4=±2.5 V
  */
-static int dt282x_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dt282x_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int i, irq;
 	int ret;
@@ -1298,19 +1298,18 @@
 
 		/* trigger interrupt */
 
-		comedi_udelay(100);
+		udelay(100);
 
 		irq = probe_irq_off(irqs);
 		restore_flags(flags);
-		if (0 /* error */ ) {
+		if (0 /* error */) {
 			printk(" error probing irq (bad)");
 		}
 	}
 #endif
 	if (irq > 0) {
 		printk(" ( irq = %d )", irq);
-		ret = comedi_request_irq(irq, dt282x_interrupt, 0, "dt282x",
-			dev);
+		ret = request_irq(irq, dt282x_interrupt, 0, "dt282x", dev);
 		if (ret < 0) {
 			printk(" failed to get irq\n");
 			return -EIO;
@@ -1326,7 +1325,8 @@
 #endif
 	}
 
-	if ((ret = alloc_private(dev, sizeof(struct dt282x_private))) < 0)
+	ret = alloc_private(dev, sizeof(struct dt282x_private));
+	if (ret < 0)
 		return ret;
 
 	ret = dt282x_grab_dma(dev, it->options[opt_dma1],
@@ -1334,7 +1334,8 @@
 	if (ret < 0)
 		return ret;
 
-	if ((ret = alloc_subdevices(dev, 3)) < 0)
+	ret = alloc_subdevices(dev, 3);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -1358,7 +1359,9 @@
 	devpriv->ad_2scomp = it->options[opt_ai_twos];
 
 	s++;
-	if ((s->n_chan = boardtype.dachan)) {
+
+	s->n_chan = boardtype.dachan;
+	if (s->n_chan) {
 		/* ao subsystem */
 		s->type = COMEDI_SUBD_AO;
 		dev->write_subdev = s;
@@ -1396,10 +1399,10 @@
 	return 0;
 }
 
-static void free_resources(struct comedi_device * dev)
+static void free_resources(struct comedi_device *dev)
 {
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 	if (dev->iobase)
 		release_region(dev->iobase, DT2821_SIZE);
@@ -1415,7 +1418,7 @@
 	}
 }
 
-static int dt282x_detach(struct comedi_device * dev)
+static int dt282x_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: dt282x: remove\n", dev->minor);
 
@@ -1424,7 +1427,7 @@
 	return 0;
 }
 
-static int dt282x_grab_dma(struct comedi_device * dev, int dma1, int dma2)
+static int dt282x_grab_dma(struct comedi_device *dev, int dma1, int dma2)
 {
 	int ret;
 
diff --git a/drivers/staging/comedi/drivers/dt3000.c b/drivers/staging/comedi/drivers/dt3000.c
index d946798..2af8b59 100644
--- a/drivers/staging/comedi/drivers/dt3000.c
+++ b/drivers/staging/comedi/drivers/dt3000.c
@@ -59,6 +59,7 @@
 
 #define DEBUG 1
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 #include <linux/delay.h>
 
@@ -95,69 +96,69 @@
 
 
 static const struct dt3k_boardtype dt3k_boardtypes[] = {
-      {name:"dt3001",
-	      device_id:0x22,
-	      adchan:	16,
-	      adbits:	12,
-	      adrange:	&range_dt3000_ai,
-	      ai_speed:3000,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt3001-pgl",
-	      device_id:0x27,
-	      adchan:	16,
-	      adbits:	12,
-	      adrange:	&range_dt3000_ai_pgl,
-	      ai_speed:3000,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt3002",
-	      device_id:0x23,
-	      adchan:	32,
-	      adbits:	12,
-	      adrange:	&range_dt3000_ai,
-	      ai_speed:3000,
-	      dachan:	0,
-	      dabits:	0,
-		},
-      {name:"dt3003",
-	      device_id:0x24,
-	      adchan:	64,
-	      adbits:	12,
-	      adrange:	&range_dt3000_ai,
-	      ai_speed:3000,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt3003-pgl",
-	      device_id:0x28,
-	      adchan:	64,
-	      adbits:	12,
-	      adrange:	&range_dt3000_ai_pgl,
-	      ai_speed:3000,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt3004",
-	      device_id:0x25,
-	      adchan:	16,
-	      adbits:	16,
-	      adrange:	&range_dt3000_ai,
-	      ai_speed:10000,
-	      dachan:	2,
-	      dabits:	12,
-		},
-      {name:"dt3005",		/* a.k.a. 3004-200 */
-	      device_id:0x26,
-	      adchan:	16,
-	      adbits:	16,
-	      adrange:	&range_dt3000_ai,
-	      ai_speed:5000,
-	      dachan:	2,
-	      dabits:	12,
-		},
+	{.name = "dt3001",
+	 .device_id = 0x22,
+	 .adchan = 16,
+	 .adbits = 12,
+	 .adrange = &range_dt3000_ai,
+	 .ai_speed = 3000,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+	{.name = "dt3001-pgl",
+	 .device_id = 0x27,
+	 .adchan = 16,
+	 .adbits = 12,
+	 .adrange = &range_dt3000_ai_pgl,
+	 .ai_speed = 3000,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+	{.name = "dt3002",
+	 .device_id = 0x23,
+	 .adchan = 32,
+	 .adbits = 12,
+	 .adrange = &range_dt3000_ai,
+	 .ai_speed = 3000,
+	 .dachan = 0,
+	 .dabits = 0,
+	},
+	{.name = "dt3003",
+	 .device_id = 0x24,
+	 .adchan = 64,
+	 .adbits = 12,
+	 .adrange = &range_dt3000_ai,
+	 .ai_speed = 3000,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+	{.name = "dt3003-pgl",
+	 .device_id = 0x28,
+	 .adchan = 64,
+	 .adbits = 12,
+	 .adrange = &range_dt3000_ai_pgl,
+	 .ai_speed = 3000,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+	{.name = "dt3004",
+	 .device_id = 0x25,
+	 .adchan = 16,
+	 .adbits = 16,
+	 .adrange = &range_dt3000_ai,
+	 .ai_speed = 10000,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
+        {.name = "dt3005",		/* a.k.a. 3004-200 */
+	 .device_id = 0x26,
+	 .adchan = 16,
+	 .adbits = 16,
+	 .adrange = &range_dt3000_ai,
+	 .ai_speed = 5000,
+	 .dachan = 2,
+	 .dabits = 12,
+	},
 };
 
 #define n_dt3k_boards sizeof(dt3k_boardtypes)/sizeof(struct dt3k_boardtype)
@@ -275,28 +276,28 @@
 
 #define devpriv ((struct dt3k_private *)dev->private)
 
-static int dt3000_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dt3000_detach(struct comedi_device * dev);
+static int dt3000_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dt3000_detach(struct comedi_device *dev);
 static struct comedi_driver driver_dt3000 = {
-      driver_name:"dt3000",
-      module:THIS_MODULE,
-      attach:dt3000_attach,
-      detach:dt3000_detach,
+	.driver_name = "dt3000",
+	.module = THIS_MODULE,
+	.attach = dt3000_attach,
+	.detach = dt3000_detach,
 };
 
 COMEDI_PCI_INITCLEANUP(driver_dt3000, dt3k_pci_table);
 
-static void dt3k_ai_empty_fifo(struct comedi_device * dev, struct comedi_subdevice * s);
+static void dt3k_ai_empty_fifo(struct comedi_device *dev, struct comedi_subdevice *s);
 static int dt3k_ns_to_timer(unsigned int timer_base, unsigned int *arg,
 	unsigned int round_mode);
-static int dt3k_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
+static int dt3k_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
 #ifdef DEBUG
 static void debug_intr_flags(unsigned int flags);
 #endif
 
 #define TIMEOUT 100
 
-static int dt3k_send_cmd(struct comedi_device * dev, unsigned int cmd)
+static int dt3k_send_cmd(struct comedi_device *dev, unsigned int cmd)
 {
 	int i;
 	unsigned int status = 0;
@@ -307,7 +308,7 @@
 		status = readw(devpriv->io_addr + DPR_Command_Mbx);
 		if ((status & DT3000_COMPLETION_MASK) != DT3000_NOTPROCESSED)
 			break;
-		comedi_udelay(1);
+		udelay(1);
 	}
 	if ((status & DT3000_COMPLETION_MASK) == DT3000_NOERROR) {
 		return 0;
@@ -318,7 +319,7 @@
 	return -ETIME;
 }
 
-static unsigned int dt3k_readsingle(struct comedi_device * dev, unsigned int subsys,
+static unsigned int dt3k_readsingle(struct comedi_device *dev, unsigned int subsys,
 	unsigned int chan, unsigned int gain)
 {
 	writew(subsys, devpriv->io_addr + DPR_SubSys);
@@ -331,7 +332,7 @@
 	return readw(devpriv->io_addr + DPR_Params(2));
 }
 
-static void dt3k_writesingle(struct comedi_device * dev, unsigned int subsys,
+static void dt3k_writesingle(struct comedi_device *dev, unsigned int subsys,
 	unsigned int chan, unsigned int data)
 {
 	writew(subsys, devpriv->io_addr + DPR_SubSys);
@@ -345,9 +346,9 @@
 
 static int debug_n_ints = 0;
 
-// FIXME! Assumes shared interrupt is for this card.
-// What's this debug_n_ints stuff? Obviously needs some work...
-static irqreturn_t dt3k_interrupt(int irq, void *d PT_REGS_ARG)
+/* FIXME! Assumes shared interrupt is for this card. */
+/* What's this debug_n_ints stuff? Obviously needs some work... */
+static irqreturn_t dt3k_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s;
@@ -400,7 +401,7 @@
 }
 #endif
 
-static void dt3k_ai_empty_fifo(struct comedi_device * dev, struct comedi_subdevice * s)
+static void dt3k_ai_empty_fifo(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int front;
 	int rear;
@@ -429,8 +430,8 @@
 	writew(rear, devpriv->io_addr + DPR_AD_Buf_Rear);
 }
 
-static int dt3k_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int dt3k_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -591,7 +592,7 @@
 	return (prescale << 16) | (divider);
 }
 
-static int dt3k_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dt3k_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	int i;
@@ -659,7 +660,7 @@
 	return 0;
 }
 
-static int dt3k_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int dt3k_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int ret;
 
@@ -671,8 +672,8 @@
 	return 0;
 }
 
-static int dt3k_ai_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt3k_ai_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	unsigned int chan, gain, aref;
@@ -689,8 +690,8 @@
 	return i;
 }
 
-static int dt3k_ao_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt3k_ao_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	unsigned int chan;
@@ -704,8 +705,8 @@
 	return i;
 }
 
-static int dt3k_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt3k_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	unsigned int chan;
@@ -718,7 +719,7 @@
 	return i;
 }
 
-static void dt3k_dio_config(struct comedi_device * dev, int bits)
+static void dt3k_dio_config(struct comedi_device *dev, int bits)
 {
 	/* XXX */
 	writew(SUBS_DOUT, devpriv->io_addr + DPR_SubSys);
@@ -733,8 +734,8 @@
 	dt3k_send_cmd(dev, CMD_CONFIG);
 }
 
-static int dt3k_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt3k_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int mask;
 
@@ -764,8 +765,8 @@
 	return insn->n;
 }
 
-static int dt3k_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt3k_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -780,8 +781,8 @@
 	return 2;
 }
 
-static int dt3k_mem_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dt3k_mem_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int addr = CR_CHAN(insn->chanspec);
 	int i;
@@ -799,9 +800,9 @@
 	return i;
 }
 
-static int dt_pci_probe(struct comedi_device * dev, int bus, int slot);
+static int dt_pci_probe(struct comedi_device *dev, int bus, int slot);
 
-static int dt3000_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dt3000_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int bus, slot;
@@ -811,7 +812,8 @@
 	bus = it->options[0];
 	slot = it->options[1];
 
-	if ((ret = alloc_private(dev, sizeof(struct dt3k_private))) < 0)
+	ret = alloc_private(dev, sizeof(struct dt3k_private));
+	if (ret < 0)
 		return ret;
 
 	ret = dt_pci_probe(dev, bus, slot);
@@ -824,14 +826,15 @@
 
 	dev->board_name = this_board->name;
 
-	if (comedi_request_irq(devpriv->pci_dev->irq, dt3k_interrupt,
-			IRQF_SHARED, "dt3000", dev)) {
+	if (request_irq(devpriv->pci_dev->irq, dt3k_interrupt, IRQF_SHARED,
+			"dt3000", dev)) {
 		printk(" unable to allocate IRQ %u\n", devpriv->pci_dev->irq);
 		return -EINVAL;
 	}
 	dev->irq = devpriv->pci_dev->irq;
 
-	if ((ret = alloc_subdevices(dev, 4)) < 0)
+	ret = alloc_subdevices(dev, 4);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices;
@@ -890,10 +893,10 @@
 	return 0;
 }
 
-static int dt3000_detach(struct comedi_device * dev)
+static int dt3000_detach(struct comedi_device *dev)
 {
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	if (devpriv) {
 		if (devpriv->pci_dev) {
@@ -911,9 +914,9 @@
 }
 
 static struct pci_dev *dt_pci_find_device(struct pci_dev *from, int *board);
-static int setup_pci(struct comedi_device * dev);
+static int setup_pci(struct comedi_device *dev);
 
-static int dt_pci_probe(struct comedi_device * dev, int bus, int slot)
+static int dt_pci_probe(struct comedi_device *dev, int bus, int slot)
 {
 	int board;
 	int ret;
@@ -935,13 +938,14 @@
 	if (!devpriv->pci_dev)
 		return 0;
 
-	if ((ret = setup_pci(dev)) < 0)
+	ret = setup_pci(dev);
+	if (ret < 0)
 		return ret;
 
 	return 1;
 }
 
-static int setup_pci(struct comedi_device * dev)
+static int setup_pci(struct comedi_device *dev)
 {
 	resource_size_t addr;
 	int ret;
diff --git a/drivers/staging/comedi/drivers/fl512.c b/drivers/staging/comedi/drivers/fl512.c
index 6d7bb37..b8657c4 100644
--- a/drivers/staging/comedi/drivers/fl512.c
+++ b/drivers/staging/comedi/drivers/fl512.c
@@ -42,30 +42,30 @@
 	}
 };
 
-static int fl512_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int fl512_detach(struct comedi_device * dev);
+static int fl512_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int fl512_detach(struct comedi_device *dev);
 
 static struct comedi_driver driver_fl512 = {
-      driver_name:"fl512",
-      module:THIS_MODULE,
-      attach:fl512_attach,
-      detach:fl512_detach,
+	.driver_name = "fl512",
+	.module = THIS_MODULE,
+	.attach = fl512_attach,
+	.detach = fl512_detach,
 };
 
 COMEDI_INITCLEANUP(driver_fl512);
 
-static int fl512_ai_insn(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
-static int fl512_ao_insn(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
-static int fl512_ao_insn_readback(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
+static int fl512_ai_insn(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
+static int fl512_ao_insn(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
+static int fl512_ao_insn_readback(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
 
 /*
  * fl512_ai_insn : this is the analog input function
  */
-static int fl512_ai_insn(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int fl512_ai_insn(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	unsigned int lo_byte, hi_byte;
@@ -78,7 +78,7 @@
 		outb(chan, iobase + 2);	/* select chan */
 		outb(0, iobase + 3);	/* start conversion */
 		/* XXX should test "done" flag instead of delay */
-		comedi_udelay(30);	/* sleep 30 usec */
+		udelay(30);	/* sleep 30 usec */
 		lo_byte = inb(iobase + 2);	/* low 8 byte */
 		hi_byte = inb(iobase + 3) & 0xf;	/* high 4 bit and mask */
 		data[n] = lo_byte + (hi_byte << 8);
@@ -89,8 +89,8 @@
 /*
  * fl512_ao_insn : used to write to a DA port n times
  */
-static int fl512_ao_insn(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int fl512_ao_insn(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan = CR_CHAN(insn->chanspec);	/* get chan to write */
@@ -110,8 +110,8 @@
  * fl512_ao_insn_readback : used to read previous values written to
  * DA port
  */
-static int fl512_ao_insn_readback(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int fl512_ao_insn_readback(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan = CR_CHAN(insn->chanspec);
@@ -126,7 +126,7 @@
 /*
  * start attach
  */
-static int fl512_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int fl512_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	unsigned long iobase;
 	struct comedi_subdevice *s;	/* pointer to the subdevice:
@@ -177,7 +177,7 @@
 	return 1;
 }
 
-static int fl512_detach(struct comedi_device * dev)
+static int fl512_detach(struct comedi_device *dev)
 {
 	if (dev->iobase)
 		release_region(dev->iobase, FL512_SIZE);
diff --git a/drivers/staging/comedi/drivers/gsc_hpdi.c b/drivers/staging/comedi/drivers/gsc_hpdi.c
index 49e5c86..b156ae7 100644
--- a/drivers/staging/comedi/drivers/gsc_hpdi.c
+++ b/drivers/staging/comedi/drivers/gsc_hpdi.c
@@ -45,6 +45,7 @@
 
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 #include <linux/delay.h>
 
@@ -52,31 +53,31 @@
 #include "plx9080.h"
 #include "comedi_fc.h"
 
-static int hpdi_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int hpdi_detach(struct comedi_device * dev);
-void abort_dma(struct comedi_device * dev, unsigned int channel);
-static int hpdi_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int hpdi_cmd_test(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int hpdi_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static irqreturn_t handle_interrupt(int irq, void *d PT_REGS_ARG);
-static int dio_config_block_size(struct comedi_device * dev, unsigned int * data);
+static int hpdi_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int hpdi_detach(struct comedi_device *dev);
+void abort_dma(struct comedi_device *dev, unsigned int channel);
+static int hpdi_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int hpdi_cmd_test(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int hpdi_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static irqreturn_t handle_interrupt(int irq, void *d);
+static int dio_config_block_size(struct comedi_device *dev, unsigned int *data);
 
-#undef HPDI_DEBUG		// disable debugging messages
-//#define HPDI_DEBUG    // enable debugging code
+#undef HPDI_DEBUG		/*  disable debugging messages */
+/* #define HPDI_DEBUG      enable debugging code */
 
 #ifdef HPDI_DEBUG
-#define DEBUG_PRINT(format, args...)  rt_printk(format , ## args )
+#define DEBUG_PRINT(format, args...)  printk(format , ## args)
 #else
 #define DEBUG_PRINT(format, args...)
 #endif
 
-#define TIMER_BASE 50		// 20MHz master clock
+#define TIMER_BASE 50		/*  20MHz master clock */
 #define DMA_BUFFER_SIZE 0x10000
 #define NUM_DMA_BUFFERS 4
 #define NUM_DMA_DESCRIPTORS 256
 
-// indices of base address regions
+/* indices of base address regions */
 enum base_address_regions {
 	PLX9080_BADDRINDEX = 0,
 	HPDI_BADDRINDEX = 2,
@@ -109,13 +110,13 @@
 int command_channel_valid(unsigned int channel)
 {
 	if (channel == 0 || channel > 6) {
-		rt_printk("gsc_hpdi: bug! invalid cable command channel\n");
+		printk("gsc_hpdi: bug! invalid cable command channel\n");
 		return 0;
 	}
 	return 1;
 }
 
-// bit definitions
+/* bit definitions */
 
 enum firmware_revision_bits {
 	FEATURES_REG_PRESENT_BIT = 0x8000,
@@ -184,7 +185,7 @@
 
 uint32_t almost_full_bits(unsigned int num_words)
 {
-// XXX need to add or subtract one?
+/* XXX need to add or subtract one? */
 	return (num_words << 16) & 0xff0000;
 }
 
@@ -194,7 +195,7 @@
 }
 unsigned int almost_full_num_words(uint32_t bits)
 {
-// XXX need to add or subtract one?
+/* XXX need to add or subtract one? */
 	return (bits >> 16) & 0xffff;
 }
 unsigned int almost_empty_num_words(uint32_t bits)
@@ -263,31 +264,26 @@
 struct hpdi_board {
 
 	char *name;
-	int device_id;		// pci device id
-	int subdevice_id;	// pci subdevice id
+	int device_id;		/*  pci device id */
+	int subdevice_id;	/*  pci subdevice id */
 };
 
 
 static const struct hpdi_board hpdi_boards[] = {
 	{
-	      name:	"pci-hpdi32",
-	      device_id:PCI_DEVICE_ID_PLX_9080,
-	      subdevice_id:0x2400,
+	.name = "pci-hpdi32",
+	.device_id = PCI_DEVICE_ID_PLX_9080,
+	.subdevice_id = 0x2400,
 		},
 #if 0
 	{
-	      name:	"pxi-hpdi32",
-	      device_id:0x9656,
-	      subdevice_id:0x2705,
+	.name = "pxi-hpdi32",
+	.device_id = 0x9656,
+	.subdevice_id = 0x2705,
 		},
 #endif
 };
 
-static inline unsigned int num_boards(void)
-{
-	return sizeof(hpdi_boards) / sizeof(struct hpdi_board);
-}
-
 static DEFINE_PCI_DEVICE_TABLE(hpdi_pci_table) = {
 	{PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9080, PCI_VENDOR_ID_PLX, 0x2400,
 		0, 0, 0},
@@ -303,25 +299,25 @@
 
 struct hpdi_private {
 
-	struct pci_dev *hw_dev;	// pointer to board's pci_dev struct
-	// base addresses (physical)
+	struct pci_dev *hw_dev;	/*  pointer to board's pci_dev struct */
+	/*  base addresses (physical) */
 	resource_size_t plx9080_phys_iobase;
 	resource_size_t hpdi_phys_iobase;
-	// base addresses (ioremapped)
+	/*  base addresses (ioremapped) */
 	void *plx9080_iobase;
 	void *hpdi_iobase;
-	uint32_t *dio_buffer[NUM_DMA_BUFFERS];	// dma buffers
-	dma_addr_t dio_buffer_phys_addr[NUM_DMA_BUFFERS];	// physical addresses of dma buffers
-	struct plx_dma_desc *dma_desc;	// array of dma descriptors read by plx9080, allocated to get proper alignment
-	dma_addr_t dma_desc_phys_addr;	// physical address of dma descriptor array
+	uint32_t *dio_buffer[NUM_DMA_BUFFERS];	/*  dma buffers */
+	dma_addr_t dio_buffer_phys_addr[NUM_DMA_BUFFERS];	/*  physical addresses of dma buffers */
+	struct plx_dma_desc *dma_desc;	/*  array of dma descriptors read by plx9080, allocated to get proper alignment */
+	dma_addr_t dma_desc_phys_addr;	/*  physical address of dma descriptor array */
 	unsigned int num_dma_descriptors;
-	uint32_t *desc_dio_buffer[NUM_DMA_DESCRIPTORS];	// pointer to start of buffers indexed by descriptor
-	volatile unsigned int dma_desc_index;	// index of the dma descriptor that is currently being used
+	uint32_t *desc_dio_buffer[NUM_DMA_DESCRIPTORS];	/*  pointer to start of buffers indexed by descriptor */
+	volatile unsigned int dma_desc_index;	/*  index of the dma descriptor that is currently being used */
 	unsigned int tx_fifo_size;
 	unsigned int rx_fifo_size;
 	volatile unsigned long dio_count;
-	volatile uint32_t bits[24];	// software copies of values written to hpdi registers
-	volatile unsigned int block_size;	// number of bytes at which to generate COMEDI_CB_BLOCK events
+	volatile uint32_t bits[24];	/*  software copies of values written to hpdi registers */
+	volatile unsigned int block_size;	/*  number of bytes at which to generate COMEDI_CB_BLOCK events */
 	unsigned dio_config_output:1;
 };
 
@@ -332,16 +328,16 @@
 }
 
 static struct comedi_driver driver_hpdi = {
-      driver_name:"gsc_hpdi",
-      module:THIS_MODULE,
-      attach:hpdi_attach,
-      detach:hpdi_detach,
+	.driver_name = "gsc_hpdi",
+	.module = THIS_MODULE,
+	.attach = hpdi_attach,
+	.detach = hpdi_detach,
 };
 
 COMEDI_PCI_INITCLEANUP(driver_hpdi, hpdi_pci_table);
 
-static int dio_config_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dio_config_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	switch (data[0]) {
 	case INSN_CONFIG_DIO_OUTPUT:
@@ -368,18 +364,18 @@
 	return -EINVAL;
 }
 
-static void disable_plx_interrupts(struct comedi_device * dev)
+static void disable_plx_interrupts(struct comedi_device *dev)
 {
 	writel(0, priv(dev)->plx9080_iobase + PLX_INTRCS_REG);
 }
 
-// initialize plx9080 chip
-static void init_plx9080(struct comedi_device * dev)
+/* initialize plx9080 chip */
+static void init_plx9080(struct comedi_device *dev)
 {
 	uint32_t bits;
 	void *plx_iobase = priv(dev)->plx9080_iobase;
 
-	// plx9080 dump
+	/*  plx9080 dump */
 	DEBUG_PRINT(" plx interrupt status 0x%x\n",
 		readl(plx_iobase + PLX_INTRCS_REG));
 	DEBUG_PRINT(" plx id bits 0x%x\n", readl(plx_iobase + PLX_ID_REG));
@@ -417,21 +413,21 @@
 	abort_dma(dev, 0);
 	abort_dma(dev, 1);
 
-	// configure dma0 mode
+	/*  configure dma0 mode */
 	bits = 0;
-	// enable ready input
+	/*  enable ready input */
 	bits |= PLX_DMA_EN_READYIN_BIT;
-	// enable dma chaining
+	/*  enable dma chaining */
 	bits |= PLX_EN_CHAIN_BIT;
-	// enable interrupt on dma done (probably don't need this, since chain never finishes)
+	/*  enable interrupt on dma done (probably don't need this, since chain never finishes) */
 	bits |= PLX_EN_DMA_DONE_INTR_BIT;
-	// don't increment local address during transfers (we are transferring from a fixed fifo register)
+	/*  don't increment local address during transfers (we are transferring from a fixed fifo register) */
 	bits |= PLX_LOCAL_ADDR_CONST_BIT;
-	// route dma interrupt to pci bus
+	/*  route dma interrupt to pci bus */
 	bits |= PLX_DMA_INTR_PCI_BIT;
-	// enable demand mode
+	/*  enable demand mode */
 	bits |= PLX_DEMAND_MODE_BIT;
-	// enable local burst mode
+	/*  enable local burst mode */
 	bits |= PLX_DMA_LOCAL_BURST_EN_BIT;
 	bits |= PLX_LOCAL_BUS_32_WIDE_BITS;
 	writel(bits, plx_iobase + PLX_DMA0_MODE_REG);
@@ -439,7 +435,7 @@
 
 /* Allocate and initialize the subdevice structures.
  */
-static int setup_subdevices(struct comedi_device * dev)
+static int setup_subdevices(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s;
 
@@ -465,12 +461,12 @@
 	return 0;
 }
 
-static int init_hpdi(struct comedi_device * dev)
+static int init_hpdi(struct comedi_device *dev)
 {
 	uint32_t plx_intcsr_bits;
 
 	writel(BOARD_RESET_BIT, priv(dev)->hpdi_iobase + BOARD_CONTROL_REG);
-	comedi_udelay(10);
+	udelay(10);
 
 	writel(almost_empty_bits(32) | almost_full_bits(32),
 		priv(dev)->hpdi_iobase + RX_PROG_ALMOST_REG);
@@ -484,7 +480,7 @@
 
 	writel(0, priv(dev)->hpdi_iobase + INTERRUPT_CONTROL_REG);
 
-	// enable interrupts
+	/*  enable interrupts */
 	plx_intcsr_bits =
 		ICS_AERR | ICS_PERR | ICS_PIE | ICS_PLIE | ICS_PAIE | ICS_LIE |
 		ICS_DMA0_E;
@@ -493,8 +489,8 @@
 	return 0;
 }
 
-// setup dma descriptors so a link completes every 'transfer_size' bytes
-static int setup_dma_descriptors(struct comedi_device * dev,
+/* setup dma descriptors so a link completes every 'transfer_size' bytes */
+static int setup_dma_descriptors(struct comedi_device *dev,
 	unsigned int transfer_size)
 {
 	unsigned int buffer_index, buffer_offset;
@@ -545,7 +541,7 @@
 			(unsigned long)priv(dev)->dma_desc[i].next);
 	}
 	priv(dev)->num_dma_descriptors = i;
-	// fix last descriptor to point back to first
+	/*  fix last descriptor to point back to first */
 	priv(dev)->dma_desc[i - 1].next =
 		cpu_to_le32(priv(dev)->dma_desc_phys_addr | next_bits);
 	DEBUG_PRINT(" desc %i next fixup 0x%lx\n", i - 1,
@@ -556,7 +552,7 @@
 	return transfer_size;
 }
 
-static int hpdi_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int hpdi_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct pci_dev *pcidev;
 	int i;
@@ -568,14 +564,14 @@
 		return -ENOMEM;
 
 	pcidev = NULL;
-	for (i = 0; i < num_boards() && dev->board_ptr == NULL; i++) {
+	for (i = 0; i < ARRAY_SIZE(hpdi_boards) && dev->board_ptr == NULL; i++) {
 		do {
 			pcidev = pci_get_subsys(PCI_VENDOR_ID_PLX,
 				hpdi_boards[i].device_id, PCI_VENDOR_ID_PLX,
 				hpdi_boards[i].subdevice_id, pcidev);
-			// was a particular bus/slot requested?
+			/*  was a particular bus/slot requested? */
 			if (it->options[0] || it->options[1]) {
-				// are we on the wrong bus/slot?
+				/*  are we on the wrong bus/slot? */
 				if (pcidev->bus->number != it->options[0] ||
 					PCI_SLOT(pcidev->devfn) !=
 					it->options[1])
@@ -603,7 +599,7 @@
 	}
 	pci_set_master(pcidev);
 
-	//Initialize dev->board_name
+	/* Initialize dev->board_name */
 	dev->board_name = board(dev)->name;
 
 	priv(dev)->plx9080_phys_iobase =
@@ -611,7 +607,7 @@
 	priv(dev)->hpdi_phys_iobase =
 		pci_resource_start(pcidev, HPDI_BADDRINDEX);
 
-	// remap, won't work with 2.0 kernels but who cares
+	/*  remap, won't work with 2.0 kernels but who cares */
 	priv(dev)->plx9080_iobase = ioremap(priv(dev)->plx9080_phys_iobase,
 		pci_resource_len(pcidev, PLX9080_BADDRINDEX));
 	priv(dev)->hpdi_iobase = ioremap(priv(dev)->hpdi_phys_iobase,
@@ -626,8 +622,8 @@
 
 	init_plx9080(dev);
 
-	// get irq
-	if (comedi_request_irq(pcidev->irq, handle_interrupt, IRQF_SHARED,
+	/*  get irq */
+	if (request_irq(pcidev->irq, handle_interrupt, IRQF_SHARED,
 			driver_hpdi.driver_name, dev)) {
 		printk(" unable to allocate irq %u\n", pcidev->irq);
 		return -EINVAL;
@@ -636,7 +632,7 @@
 
 	printk(" irq %u\n", dev->irq);
 
-	// alocate pci dma buffers
+	/*  alocate pci dma buffers */
 	for (i = 0; i < NUM_DMA_BUFFERS; i++) {
 		priv(dev)->dio_buffer[i] =
 			pci_alloc_consistent(priv(dev)->hw_dev, DMA_BUFFER_SIZE,
@@ -645,7 +641,7 @@
 			priv(dev)->dio_buffer[i],
 			(unsigned long)priv(dev)->dio_buffer_phys_addr[i]);
 	}
-	// allocate dma descriptors
+	/*  allocate dma descriptors */
 	priv(dev)->dma_desc = pci_alloc_consistent(priv(dev)->hw_dev,
 		sizeof(struct plx_dma_desc) * NUM_DMA_DESCRIPTORS,
 		&priv(dev)->dma_desc_phys_addr);
@@ -665,14 +661,14 @@
 	return init_hpdi(dev);
 }
 
-static int hpdi_detach(struct comedi_device * dev)
+static int hpdi_detach(struct comedi_device *dev)
 {
 	unsigned int i;
 
 	printk("comedi%d: gsc_hpdi: remove\n", dev->minor);
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	if (priv(dev)) {
 		if (priv(dev)->hw_dev) {
 			if (priv(dev)->plx9080_iobase) {
@@ -681,7 +677,7 @@
 			}
 			if (priv(dev)->hpdi_iobase)
 				iounmap((void *)priv(dev)->hpdi_iobase);
-			// free pci dma buffers
+			/*  free pci dma buffers */
 			for (i = 0; i < NUM_DMA_BUFFERS; i++) {
 				if (priv(dev)->dio_buffer[i])
 					pci_free_consistent(priv(dev)->hw_dev,
@@ -690,7 +686,7 @@
 						priv(dev)->
 						dio_buffer_phys_addr[i]);
 			}
-			// free dma descriptors
+			/*  free dma descriptors */
 			if (priv(dev)->dma_desc)
 				pci_free_consistent(priv(dev)->hw_dev,
 					sizeof(struct plx_dma_desc) *
@@ -706,7 +702,7 @@
 	return 0;
 }
 
-static int dio_config_block_size(struct comedi_device * dev, unsigned int * data)
+static int dio_config_block_size(struct comedi_device *dev, unsigned int *data)
 {
 	unsigned int requested_block_size;
 	int retval;
@@ -722,8 +718,8 @@
 	return 2;
 }
 
-static int di_cmd_test(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int di_cmd_test(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -761,7 +757,7 @@
 
 	/* step 2: make sure trigger sources are unique and mutually compatible */
 
-	// uniqueness check
+	/*  uniqueness check */
 	if (cmd->stop_src != TRIG_COUNT && cmd->stop_src != TRIG_NONE)
 		err++;
 
@@ -807,7 +803,7 @@
 	if (cmd->chanlist) {
 		for (i = 1; i < cmd->chanlist_len; i++) {
 			if (CR_CHAN(cmd->chanlist[i]) != i) {
-				// XXX could support 8 channels or 16 channels
+				/*  XXX could support 8 channels or 16 channels */
 				comedi_error(dev,
 					"chanlist must be channels 0 to 31 in order");
 				err++;
@@ -822,8 +818,8 @@
 	return 0;
 }
 
-static int hpdi_cmd_test(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int hpdi_cmd_test(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	if (priv(dev)->dio_config_output) {
 		return -EINVAL;
@@ -831,14 +827,14 @@
 		return di_cmd_test(dev, s, cmd);
 }
 
-static inline void hpdi_writel(struct comedi_device * dev, uint32_t bits,
+static inline void hpdi_writel(struct comedi_device *dev, uint32_t bits,
 	unsigned int offset)
 {
 	writel(bits | priv(dev)->bits[offset / sizeof(uint32_t)],
 		priv(dev)->hpdi_iobase + offset);
 }
 
-static int di_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int di_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	uint32_t bits;
 	unsigned long flags;
@@ -860,28 +856,28 @@
 	writel(0, priv(dev)->plx9080_iobase + PLX_DMA0_TRANSFER_SIZE_REG);
 	writel(0, priv(dev)->plx9080_iobase + PLX_DMA0_PCI_ADDRESS_REG);
 	writel(0, priv(dev)->plx9080_iobase + PLX_DMA0_LOCAL_ADDRESS_REG);
-	// give location of first dma descriptor
+	/*  give location of first dma descriptor */
 	bits = priv(dev)->
 		dma_desc_phys_addr | PLX_DESC_IN_PCI_BIT | PLX_INTR_TERM_COUNT |
 		PLX_XFER_LOCAL_TO_PCI;
 	writel(bits, priv(dev)->plx9080_iobase + PLX_DMA0_DESCRIPTOR_REG);
 
-	// spinlock for plx dma control/status reg
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
-	// enable dma transfer
+	/*  spinlock for plx dma control/status reg */
+	spin_lock_irqsave(&dev->spinlock, flags);
+	/*  enable dma transfer */
 	writeb(PLX_DMA_EN_BIT | PLX_DMA_START_BIT | PLX_CLEAR_DMA_INTR_BIT,
 		priv(dev)->plx9080_iobase + PLX_DMA0_CS_REG);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	if (cmd->stop_src == TRIG_COUNT)
 		priv(dev)->dio_count = cmd->stop_arg;
 	else
 		priv(dev)->dio_count = 1;
 
-	// clear over/under run status flags
+	/*  clear over/under run status flags */
 	writel(RX_UNDERRUN_BIT | RX_OVERRUN_BIT,
 		priv(dev)->hpdi_iobase + BOARD_STATUS_REG);
-	// enable interrupts
+	/*  enable interrupts */
 	writel(intr_bit(RX_FULL_INTR),
 		priv(dev)->hpdi_iobase + INTERRUPT_CONTROL_REG);
 
@@ -891,7 +887,7 @@
 	return 0;
 }
 
-static int hpdi_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int hpdi_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	if (priv(dev)->dio_config_output) {
 		return -EINVAL;
@@ -899,7 +895,7 @@
 		return di_cmd(dev, s);
 }
 
-static void drain_dma_buffers(struct comedi_device * dev, unsigned int channel)
+static void drain_dma_buffers(struct comedi_device *dev, unsigned int channel)
 {
 	struct comedi_async *async = dev->read_subdev->async;
 	uint32_t next_transfer_addr;
@@ -914,7 +910,7 @@
 		pci_addr_reg =
 			priv(dev)->plx9080_iobase + PLX_DMA0_PCI_ADDRESS_REG;
 
-	// loop until we have read all the full buffers
+	/*  loop until we have read all the full buffers */
 	j = 0;
 	for (next_transfer_addr = readl(pci_addr_reg);
 		(next_transfer_addr <
@@ -925,7 +921,7 @@
 					dma_desc_index].pci_start_addr) +
 			priv(dev)->block_size)
 		&& j < priv(dev)->num_dma_descriptors; j++) {
-		// transfer data from dma buffer to comedi buffer
+		/*  transfer data from dma buffer to comedi buffer */
 		num_samples = priv(dev)->block_size / sizeof(uint32_t);
 		if (async->cmd.stop_src == TRIG_COUNT) {
 			if (num_samples > priv(dev)->dio_count)
@@ -942,10 +938,10 @@
 			priv(dev)->dma_desc[priv(dev)->dma_desc_index].next);
 		DEBUG_PRINT("pci addr reg 0x%x\n", next_transfer_addr);
 	}
-	// XXX check for buffer overrun somehow
+	/*  XXX check for buffer overrun somehow */
 }
 
-static irqreturn_t handle_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t handle_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s = dev->read_subdev;
@@ -975,10 +971,10 @@
 		writel(hpdi_intr_status,
 			priv(dev)->hpdi_iobase + INTERRUPT_STATUS_REG);
 	}
-	// spin lock makes sure noone else changes plx dma control reg
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  spin lock makes sure noone else changes plx dma control reg */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	dma0_status = readb(priv(dev)->plx9080_iobase + PLX_DMA0_CS_REG);
-	if (plx_status & ICS_DMA0_A) {	// dma chan 0 interrupt
+	if (plx_status & ICS_DMA0_A) {	/*  dma chan 0 interrupt */
 		writeb((dma0_status & PLX_DMA_EN_BIT) | PLX_CLEAR_DMA_INTR_BIT,
 			priv(dev)->plx9080_iobase + PLX_DMA0_CS_REG);
 
@@ -988,23 +984,23 @@
 		}
 		DEBUG_PRINT(" cleared dma ch0 interrupt\n");
 	}
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// spin lock makes sure noone else changes plx dma control reg
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  spin lock makes sure noone else changes plx dma control reg */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	dma1_status = readb(priv(dev)->plx9080_iobase + PLX_DMA1_CS_REG);
-	if (plx_status & ICS_DMA1_A)	// XXX
-	{			// dma chan 1 interrupt
+	if (plx_status & ICS_DMA1_A)	/*  XXX */
+	{			/*  dma chan 1 interrupt */
 		writeb((dma1_status & PLX_DMA_EN_BIT) | PLX_CLEAR_DMA_INTR_BIT,
 			priv(dev)->plx9080_iobase + PLX_DMA1_CS_REG);
 		DEBUG_PRINT("dma1 status 0x%x\n", dma1_status);
 
 		DEBUG_PRINT(" cleared dma ch1 interrupt\n");
 	}
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// clear possible plx9080 interrupt sources
-	if (plx_status & ICS_LDIA) {	// clear local doorbell interrupt
+	/*  clear possible plx9080 interrupt sources */
+	if (plx_status & ICS_LDIA) {	/*  clear local doorbell interrupt */
 		plx_bits = readl(priv(dev)->plx9080_iobase + PLX_DBR_OUT_REG);
 		writel(plx_bits, priv(dev)->plx9080_iobase + PLX_DBR_OUT_REG);
 		DEBUG_PRINT(" cleared local doorbell bits 0x%x\n", plx_bits);
@@ -1036,19 +1032,19 @@
 	return IRQ_HANDLED;
 }
 
-void abort_dma(struct comedi_device * dev, unsigned int channel)
+void abort_dma(struct comedi_device *dev, unsigned int channel)
 {
 	unsigned long flags;
 
-	// spinlock for plx dma control/status reg
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  spinlock for plx dma control/status reg */
+	spin_lock_irqsave(&dev->spinlock, flags);
 
 	plx9080_abort_dma(priv(dev)->plx9080_iobase, channel);
 
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 }
 
-static int hpdi_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int hpdi_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	hpdi_writel(dev, 0, BOARD_CONTROL_REG);
 
diff --git a/drivers/staging/comedi/drivers/icp_multi.c b/drivers/staging/comedi/drivers/icp_multi.c
index 15fce01..984f995 100644
--- a/drivers/staging/comedi/drivers/icp_multi.c
+++ b/drivers/staging/comedi/drivers/icp_multi.c
@@ -50,6 +50,7 @@
  [1] - PCI slot number
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/delay.h>
@@ -282,7 +283,7 @@
 			readw(devpriv->io_addr + ICP_MULTI_ADC_CSR));
 #endif
 
-		comedi_udelay(1);
+		udelay(1);
 
 #ifdef ICP_MULTI_EXTDEBUG
 		printk("icp multi C n=%d ST=%4x\n", n,
@@ -304,7 +305,7 @@
 						ICP_MULTI_ADC_CSR));
 #endif
 
-			comedi_udelay(1);
+			udelay(1);
 		}
 
 		/*  If we reach here, a timeout has occurred */
@@ -411,7 +412,7 @@
 						ICP_MULTI_DAC_CSR));
 #endif
 
-			comedi_udelay(1);
+			udelay(1);
 		}
 
 		/*  If we reach here, a timeout has occurred */
@@ -618,7 +619,7 @@
 
 ==============================================================================
 */
-static irqreturn_t interrupt_service_icp_multi(int irq, void *d PT_REGS_ARG)
+static irqreturn_t interrupt_service_icp_multi(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	int int_no;
@@ -842,7 +843,7 @@
 				devpriv->io_addr + ICP_MULTI_DAC_CSR);
 
 			/*  Delay to allow DAC time to recover */
-			comedi_udelay(1);
+			udelay(1);
 		}
 	/*  Digital outputs to 0 */
 	writew(0, devpriv->io_addr + ICP_MULTI_DO);
@@ -954,7 +955,7 @@
 
 	if (this_board->have_irq) {
 		if (irq) {
-			if (comedi_request_irq(irq, interrupt_service_icp_multi,
+			if (request_irq(irq, interrupt_service_icp_multi,
 					IRQF_SHARED, "Inova Icp Multi", dev)) {
 				printk(", unable to allocate IRQ %u, DISABLING IT", irq);
 				irq = 0;	/* Can't use IRQ */
@@ -1072,7 +1073,7 @@
 			icp_multi_reset(dev);
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	if (dev->private && devpriv->io_addr)
 		iounmap(devpriv->io_addr);
diff --git a/drivers/staging/comedi/drivers/icp_multi.h b/drivers/staging/comedi/drivers/icp_multi.h
index 21d8476..354ba8f 100644
--- a/drivers/staging/comedi/drivers/icp_multi.h
+++ b/drivers/staging/comedi/drivers/icp_multi.h
@@ -168,14 +168,14 @@
 	int i;
 
 	if (!inova) {
-		rt_printk(" - BUG!! inova is NULL!\n");
+		printk(" - BUG!! inova is NULL!\n");
 		return -1;
 	}
 
 	if (inova->used)
 		return 1;
 	if (comedi_pci_enable(inova->pcidev, "icp_multi")) {
-		rt_printk(" - Can't enable PCI device and request regions!\n");
+		printk(" - Can't enable PCI device and request regions!\n");
 		return -1;
 	}
 	/* Resources will be accurate now. */
@@ -248,19 +248,19 @@
 
 		card = find_free_pci_card_by_device(vendor_id, device_id);
 		if (card == NULL) {
-			rt_printk(" - Unused card not found in system!\n");
+			printk(" - Unused card not found in system!\n");
 			return NULL;
 		}
 	} else {
 		switch (find_free_pci_card_by_position(vendor_id, device_id,
 				pci_bus, pci_slot, &card)) {
 		case 1:
-			rt_printk
+			printk
 				(" - Card not found on requested position b:s %d:%d!\n",
 				pci_bus, pci_slot);
 			return NULL;
 		case 2:
-			rt_printk
+			printk
 				(" - Card on requested position is used b:s %d:%d!\n",
 				pci_bus, pci_slot);
 			return NULL;
@@ -270,7 +270,7 @@
 	err = pci_card_alloc(card);
 	if (err != 0) {
 		if (err > 0)
-			rt_printk(" - Can't allocate card!\n");
+			printk(" - Can't allocate card!\n");
 		/* else: error already printed. */
 		return NULL;
 	}
diff --git a/drivers/staging/comedi/drivers/ii_pci20kc.c b/drivers/staging/comedi/drivers/ii_pci20kc.c
index 80825ba..a90d65f 100644
--- a/drivers/staging/comedi/drivers/ii_pci20kc.c
+++ b/drivers/staging/comedi/drivers/ii_pci20kc.c
@@ -158,21 +158,21 @@
 #define devpriv ((struct pci20xxx_private *)dev->private)
 #define CHAN (CR_CHAN(it->chanlist[0]))
 
-static int pci20xxx_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pci20xxx_detach(struct comedi_device * dev);
+static int pci20xxx_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pci20xxx_detach(struct comedi_device *dev);
 
 static struct comedi_driver driver_pci20xxx = {
-      driver_name:"ii_pci20kc",
-      module:THIS_MODULE,
-      attach:pci20xxx_attach,
-      detach:pci20xxx_detach,
+	.driver_name = "ii_pci20kc",
+	.module = THIS_MODULE,
+	.attach = pci20xxx_attach,
+	.detach = pci20xxx_detach,
 };
 
-static int pci20006_init(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pci20006_init(struct comedi_device *dev, struct comedi_subdevice *s,
 	int opt0, int opt1);
-static int pci20341_init(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pci20341_init(struct comedi_device *dev, struct comedi_subdevice *s,
 	int opt0, int opt1);
-static int pci20xxx_dio_init(struct comedi_device * dev, struct comedi_subdevice * s);
+static int pci20xxx_dio_init(struct comedi_device *dev, struct comedi_subdevice *s);
 
 /*
   options[0]	Board base address
@@ -201,7 +201,7 @@
 		1 == unipolar 10V  (0V -- +10V)
 		2 == bipolar 5V  (-5V -- +5V)
 */
-static int pci20xxx_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pci20xxx_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	unsigned char i;
 	int ret;
@@ -209,9 +209,12 @@
 	struct comedi_subdevice *s;
 	union pci20xxx_subdev_private *sdp;
 
-	if ((ret = alloc_subdevices(dev, 1 + PCI20000_MODULES)) < 0)
+	ret = alloc_subdevices(dev, 1 + PCI20000_MODULES);
+	if (ret < 0)
 		return ret;
-	if ((ret = alloc_private(dev, sizeof(struct pci20xxx_private))) < 0)
+
+	ret = alloc_private(dev, sizeof(struct pci20xxx_private));
+	if (ret < 0)
 		return ret;
 
 	devpriv->ioaddr = (void *)(unsigned long)it->options[0];
@@ -263,7 +266,7 @@
 	return 1;
 }
 
-static int pci20xxx_detach(struct comedi_device * dev)
+static int pci20xxx_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: pci20xxx: remove\n", dev->minor);
 
@@ -272,10 +275,10 @@
 
 /* pci20006m */
 
-static int pci20006_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int pci20006_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int pci20006_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int pci20006_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 static const struct comedi_lrange *pci20006_range_list[] = {
 	&range_bipolar10,
@@ -283,7 +286,7 @@
 	&range_bipolar5,
 };
 
-static int pci20006_init(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pci20006_init(struct comedi_device *dev, struct comedi_subdevice *s,
 	int opt0, int opt1)
 {
 	union pci20xxx_subdev_private *sdp = s->private;
@@ -308,8 +311,8 @@
 	return 0;
 }
 
-static int pci20006_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci20006_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	union pci20xxx_subdev_private *sdp = s->private;
 
@@ -318,8 +321,8 @@
 	return 1;
 }
 
-static int pci20006_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci20006_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	union pci20xxx_subdev_private *sdp = s->private;
 	int hi, lo;
@@ -351,8 +354,8 @@
 
 /* PCI20341M */
 
-static int pci20341_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int pci20341_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 static const int pci20341_timebase[] = { 0x00, 0x00, 0x00, 0x04 };
 static const int pci20341_settling_time[] = { 0x58, 0x58, 0x93, 0x99 };
@@ -368,7 +371,7 @@
 	&range_bipolar0_025,
 };
 
-static int pci20341_init(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pci20341_init(struct comedi_device *dev, struct comedi_subdevice *s,
 	int opt0, int opt1)
 {
 	union pci20xxx_subdev_private *sdp = s->private;
@@ -399,8 +402,8 @@
 	return 0;
 }
 
-static int pci20341_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci20341_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
         union pci20xxx_subdev_private *sdp = s->private;
 	unsigned int i = 0, j = 0;
@@ -445,14 +448,14 @@
 
 /* native DIO */
 
-static void pci20xxx_dio_config(struct comedi_device * dev, struct comedi_subdevice * s);
-static int pci20xxx_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int pci20xxx_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static void pci20xxx_dio_config(struct comedi_device *dev, struct comedi_subdevice *s);
+static int pci20xxx_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int pci20xxx_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 /* initialize struct pci20xxx_private */
-static int pci20xxx_dio_init(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pci20xxx_dio_init(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 
 	s->type = COMEDI_SUBD_DIO;
@@ -471,8 +474,8 @@
 	return 0;
 }
 
-static int pci20xxx_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci20xxx_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int mask, bits;
 
@@ -496,8 +499,8 @@
 	return 1;
 }
 
-static int pci20xxx_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pci20xxx_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int mask = data[0];
 
@@ -526,7 +529,7 @@
 	return 2;
 }
 
-static void pci20xxx_dio_config(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pci20xxx_dio_config(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned char control_01;
 	unsigned char control_23;
@@ -582,7 +585,7 @@
 }
 
 #if 0
-static void pci20xxx_do(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pci20xxx_do(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	/* XXX if the channel is configured for input, does this
 	   do bad things? */
@@ -595,7 +598,7 @@
 	writeb((s->state >> 24) & 0xff, devpriv->ioaddr + PCI20000_DIO_3);
 }
 
-static unsigned int pci20xxx_di(struct comedi_device * dev, struct comedi_subdevice * s)
+static unsigned int pci20xxx_di(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	/* XXX same note as above */
 	unsigned int bits;
diff --git a/drivers/staging/comedi/drivers/jr3_pci.c b/drivers/staging/comedi/drivers/jr3_pci.c
index a3c887f..baf83c6 100644
--- a/drivers/staging/comedi/drivers/jr3_pci.c
+++ b/drivers/staging/comedi/drivers/jr3_pci.c
@@ -48,69 +48,20 @@
 #include "comedi_pci.h"
 #include "jr3_pci.h"
 
-/* Hotplug firmware loading stuff */
-
-static void comedi_fw_release(struct device *dev)
-{
-	printk(KERN_DEBUG "firmware_sample_driver: ghost_release\n");
-}
-
-static struct device comedi_fw_device = {
-	.init_name = "comedi",
-	.release = comedi_fw_release
-};
-
-typedef int comedi_firmware_callback(struct comedi_device * dev,
-	const u8 * data, size_t size);
-
-static int comedi_load_firmware(struct comedi_device * dev,
-	char *name, comedi_firmware_callback cb)
-{
-	int result = 0;
-	const struct firmware *fw;
-	char *firmware_path;
-	static const char *prefix = "comedi/";
-
-	firmware_path = kmalloc(strlen(prefix) + strlen(name) + 1, GFP_KERNEL);
-	if (!firmware_path) {
-		result = -ENOMEM;
-	} else {
-		firmware_path[0] = '\0';
-		strcat(firmware_path, prefix);
-		strcat(firmware_path, name);
-		result = device_register(&comedi_fw_device);
-		if (result == 0) {
-			result = request_firmware(&fw, firmware_path,
-				&comedi_fw_device);
-			if (result == 0) {
-				if (!cb) {
-					result = -EINVAL;
-				} else {
-					result = cb(dev, fw->data, fw->size);
-				}
-				release_firmware(fw);
-			}
-			device_unregister(&comedi_fw_device);
-		}
-		kfree(firmware_path);
-	}
-	return result;
-}
-
 #define PCI_VENDOR_ID_JR3 0x1762
 #define PCI_DEVICE_ID_JR3_1_CHANNEL 0x3111
 #define PCI_DEVICE_ID_JR3_2_CHANNEL 0x3112
 #define PCI_DEVICE_ID_JR3_3_CHANNEL 0x3113
 #define PCI_DEVICE_ID_JR3_4_CHANNEL 0x3114
 
-static int jr3_pci_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int jr3_pci_detach(struct comedi_device * dev);
+static int jr3_pci_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int jr3_pci_detach(struct comedi_device *dev);
 
 static struct comedi_driver driver_jr3_pci = {
-      driver_name:"jr3_pci",
-      module:THIS_MODULE,
-      attach:jr3_pci_attach,
-      detach:jr3_pci_detach,
+	.driver_name = "jr3_pci",
+	.module = THIS_MODULE,
+	.attach = jr3_pci_attach,
+	.detach = jr3_pci_detach,
 };
 
 static DEFINE_PCI_DEVICE_TABLE(jr3_pci_pci_table) = {
@@ -168,6 +119,41 @@
 	int retries;
 };
 
+/* Hotplug firmware loading stuff */
+
+typedef int comedi_firmware_callback(struct comedi_device *dev,
+				     const u8 *data, size_t size);
+
+static int comedi_load_firmware(struct comedi_device *dev, char *name,
+				comedi_firmware_callback cb)
+{
+	int result = 0;
+	const struct firmware *fw;
+	char *firmware_path;
+	static const char *prefix = "comedi/";
+	struct jr3_pci_dev_private *devpriv = dev->private;
+
+	firmware_path = kmalloc(strlen(prefix) + strlen(name) + 1, GFP_KERNEL);
+	if (!firmware_path) {
+		result = -ENOMEM;
+	} else {
+		firmware_path[0] = '\0';
+		strcat(firmware_path, prefix);
+		strcat(firmware_path, name);
+		result = request_firmware(&fw, firmware_path,
+			&devpriv->pci_dev->dev);
+		if (result == 0) {
+			if (!cb)
+				result = -EINVAL;
+			else
+				result = cb(dev, fw->data, fw->size);
+			release_firmware(fw);
+		}
+		kfree(firmware_path);
+	}
+	return result;
+}
+
 static struct poll_delay_t poll_delay_min_max(int min, int max)
 {
 	struct poll_delay_t result;
@@ -194,15 +180,15 @@
 {
 	int i;
 
-	num &= 0x000f;		// Make sure that 0 <= num <= 15
+	num &= 0x000f;		/*  Make sure that 0 <= num <= 15 */
 	for (i = 0; i < 8; i++) {
 
 		set_u16(&channel->transforms[num].link[i].link_type,
 			transf.link[i].link_type);
-		comedi_udelay(1);
+		udelay(1);
 		set_s16(&channel->transforms[num].link[i].link_amount,
 			transf.link[i].link_amount);
-		comedi_udelay(1);
+		udelay(1);
 		if (transf.link[i].link_type == end_x_form) {
 			break;
 		}
@@ -273,8 +259,8 @@
 	return result;
 }
 
-static int jr3_pci_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int jr3_pci_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int result;
 	struct jr3_pci_subdev_private *p;
@@ -389,7 +375,7 @@
 	return result;
 }
 
-static void jr3_pci_open(struct comedi_device * dev)
+static void jr3_pci_open(struct comedi_device *dev)
 {
 	int i;
 	struct jr3_pci_dev_private *devpriv = dev->private;
@@ -406,14 +392,14 @@
 	}
 }
 
-int read_idm_word(const u8 * data, size_t size, int *pos, unsigned int *val)
+int read_idm_word(const u8 *data, size_t size, int *pos, unsigned int *val)
 {
 	int result = 0;
 	if (pos != 0 && val != 0) {
-		// Skip over non hex
+		/*  Skip over non hex */
 		for (; *pos < size && !isxdigit(data[*pos]); (*pos)++) {
 		}
-		// Collect value
+		/*  Collect value */
 		*val = 0;
 		for (; *pos < size && isxdigit(data[*pos]); (*pos)++) {
 			char ch = tolower(data[*pos]);
@@ -428,7 +414,7 @@
 	return result;
 }
 
-static int jr3_download_firmware(struct comedi_device * dev, const u8 * data,
+static int jr3_download_firmware(struct comedi_device *dev, const u8 *data,
 	size_t size)
 {
 	/*
@@ -485,17 +471,17 @@
 					count, addr);
 				while (more && count > 0) {
 					if (addr & 0x4000) {
-						// 16 bit data, never seen in real life!!
+						/*  16 bit data, never seen in real life!! */
 						unsigned int data1;
 
 						more = more
 							&& read_idm_word(data,
 							size, &pos, &data1);
 						count--;
-						// printk("jr3_data, not tested\n");
-						//        jr3[addr + 0x20000 * pnum] = data1;
+						/* printk("jr3_data, not tested\n"); */
+						/* jr3[addr + 0x20000 * pnum] = data1; */
 					} else {
-						//  Download 24 bit program
+						/*   Download 24 bit program */
 						unsigned int data1, data2;
 
 						more = more
@@ -510,12 +496,12 @@
 								channel[i].
 								program_low
 								[addr], data1);
-							comedi_udelay(1);
+							udelay(1);
 							set_u16(&p->iobase->
 								channel[i].
 								program_high
 								[addr], data2);
-							comedi_udelay(1);
+							udelay(1);
 
 						}
 					}
@@ -527,7 +513,7 @@
 	return result;
 }
 
-static struct poll_delay_t jr3_pci_poll_subdevice(struct comedi_subdevice * s)
+static struct poll_delay_t jr3_pci_poll_subdevice(struct comedi_subdevice *s)
 {
 	struct poll_delay_t result = poll_delay_min_max(1000, 2000);
 	struct jr3_pci_subdev_private *p = s->private;
@@ -541,7 +527,7 @@
 			p->errors = errors;
 		}
 		if (errors & (watch_dog | watch_dog2 | sensor_change)) {
-			// Sensor communication lost, force poll mode
+			/*  Sensor communication lost, force poll mode */
 			p->state = state_jr3_poll;
 
 		}
@@ -551,9 +537,10 @@
 				u16 serial_no = get_u16(&channel->serial_no);
 				if ((errors & (watch_dog | watch_dog2)) ||
 					model_no == 0 || serial_no == 0) {
-					// Still no sensor, keep on polling. Since it takes up to
-					// 10 seconds for offsets to stabilize, polling each
-					// second should suffice.
+/*
+ * Still no sensor, keep on polling. Since it takes up to 10 seconds
+ * for offsets to stabilize, polling each second should suffice.
+ */
 					result = poll_delay_min_max(1000, 2000);
 				} else {
 					p->retries = 0;
@@ -566,7 +553,7 @@
 		case state_jr3_init_wait_for_offset:{
 				p->retries++;
 				if (p->retries < 10) {
-					// Wait for offeset to stabilize (< 10 s according to manual)
+					/*  Wait for offeset to stabilize (< 10 s according to manual) */
 					result = poll_delay_min_max(1000, 2000);
 				} else {
 					struct transform_t transf;
@@ -582,7 +569,7 @@
 					printk("Sensor Serial    = %i\n",
 						p->serial_no);
 
-					// Transformation all zeros
+					/*  Transformation all zeros */
 					transf.link[0].link_type =
 						(enum link_types)0;
 					transf.link[0].link_amount = 0;
@@ -600,7 +587,7 @@
 					use_transform(channel, 0);
 					p->state =
 						state_jr3_init_transform_complete;
-					result = poll_delay_min_max(20, 100);	// Allow 20 ms for completion
+					result = poll_delay_min_max(20, 100);	/*  Allow 20 ms for completion */
 				}
 			} break;
 		case state_jr3_init_transform_complete:{
@@ -608,7 +595,7 @@
 					printk("state_jr3_init_transform_complete complete = %d\n", is_complete(channel));
 					result = poll_delay_min_max(20, 100);
 				} else {
-					// Set full scale
+					/*  Set full scale */
 					struct six_axis_t min_full_scale;
 					struct six_axis_t max_full_scale;
 
@@ -639,7 +626,7 @@
 
 					p->state =
 						state_jr3_init_set_full_scale_complete;
-					result = poll_delay_min_max(20, 100);	// Allow 20 ms for completion
+					result = poll_delay_min_max(20, 100);	/*  Allow 20 ms for completion */
 				}
 			}
 			break;
@@ -650,7 +637,7 @@
 				} else {
 					volatile struct force_array *full_scale;
 
-					// Use ranges in kN or we will overflow arount 2000N!
+					/*  Use ranges in kN or we will overflow arount 2000N! */
 					full_scale = &channel->full_scale;
 					p->range[0].range.min =
 						-get_s16(&full_scale->fx) *
@@ -679,10 +666,10 @@
 						-get_s16(&full_scale->mz) * 100;
 					p->range[5].range.max =
 						get_s16(&full_scale->mz) * 100;
-					p->range[6].range.min = -get_s16(&full_scale->v1) * 100;	// ??
-					p->range[6].range.max = get_s16(&full_scale->v1) * 100;	// ??
-					p->range[7].range.min = -get_s16(&full_scale->v2) * 100;	// ??
-					p->range[7].range.max = get_s16(&full_scale->v2) * 100;	// ??
+					p->range[6].range.min = -get_s16(&full_scale->v1) * 100;	/*  ?? */
+					p->range[6].range.max = get_s16(&full_scale->v1) * 100;	/*  ?? */
+					p->range[7].range.min = -get_s16(&full_scale->v2) * 100;	/*  ?? */
+					p->range[7].range.max = get_s16(&full_scale->v2) * 100;	/*  ?? */
 					p->range[8].range.min = 0;
 					p->range[8].range.max = 65535;
 
@@ -701,7 +688,7 @@
 					use_offset(channel, 0);
 					p->state =
 						state_jr3_init_use_offset_complete;
-					result = poll_delay_min_max(40, 100);	// Allow 40 ms for completion
+					result = poll_delay_min_max(40, 100);	/*  Allow 40 ms for completion */
 				}
 			}
 			break;
@@ -747,10 +734,10 @@
 	int delay;
 	int i;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	delay = 1000;
 	now = jiffies;
-	// Poll all channels that are ready to be polled
+	/*  Poll all channels that are ready to be polled */
 	for (i = 0; i < devpriv->n_channels; i++) {
 		struct jr3_pci_subdev_private *subdevpriv = dev->subdevices[i].private;
 		if (now > subdevpriv->next_time_min) {
@@ -762,19 +749,21 @@
 			subdevpriv->next_time_max =
 				jiffies + msecs_to_jiffies(sub_delay.max);
 			if (sub_delay.max && sub_delay.max < delay) {
-				// Wake up as late as possible -> poll as many channels as
-				// possible at once
+/*
+* Wake up as late as possible -> poll as many channels as possible
+* at once
+*/
 				delay = sub_delay.max;
 			}
 		}
 	}
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	devpriv->timer.expires = jiffies + msecs_to_jiffies(delay);
 	add_timer(&devpriv->timer);
 }
 
-static int jr3_pci_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int jr3_pci_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int result = 0;
 	struct pci_dev *card = NULL;
@@ -845,9 +834,12 @@
 		devpriv->pci_dev = card;
 		dev->board_name = "jr3_pci";
 	}
-	if ((result = comedi_pci_enable(card, "jr3_pci")) < 0) {
+
+	result = comedi_pci_enable(card, "jr3_pci");
+	if (result < 0) {
 		return -EIO;
 	}
+
 	devpriv->pci_enabled = 1;
 	devpriv->iobase = ioremap(pci_resource_start(card, 0), sizeof(struct jr3_t));
 	result = alloc_subdevices(dev, devpriv->n_channels);
@@ -881,7 +873,7 @@
 				p->range[j].range.max = 1000000;
 				for (k = 0; k < 7; k++) {
 					p->range_table_list[j + k * 8] =
-						(struct comedi_lrange *) & p->range[j];
+						(struct comedi_lrange *) &p->range[j];
 					p->maxdata_list[j + k * 8] = 0x7fff;
 				}
 			}
@@ -890,12 +882,12 @@
 			p->range[8].range.max = 65536;
 
 			p->range_table_list[56] =
-				(struct comedi_lrange *) & p->range[8];
+				(struct comedi_lrange *) &p->range[8];
 			p->range_table_list[57] =
-				(struct comedi_lrange *) & p->range[8];
+				(struct comedi_lrange *) &p->range[8];
 			p->maxdata_list[56] = 0xffff;
 			p->maxdata_list[57] = 0xffff;
-			// Channel specific range and maxdata
+			/*  Channel specific range and maxdata */
 			dev->subdevices[i].range_table = 0;
 			dev->subdevices[i].range_table_list =
 				p->range_table_list;
@@ -904,7 +896,7 @@
 		}
 	}
 
-	// Reset DSP card
+	/*  Reset DSP card */
 	devpriv->iobase->channel[0].reset = 0;
 
 	result = comedi_load_firmware(dev, "jr3pci.idm", jr3_download_firmware);
@@ -913,13 +905,18 @@
 	if (result < 0) {
 		goto out;
 	}
-	// TODO: use firmware to load preferred offset tables. Suggested format:
-	// model serial Fx Fy Fz Mx My Mz\n
-	//
-	// comedi_load_firmware(dev, "jr3_offsets_table", jr3_download_firmware);
+/*
+ * TODO: use firmware to load preferred offset tables. Suggested
+ * format:
+ *     model serial Fx Fy Fz Mx My Mz\n
+ *
+ *     comedi_load_firmware(dev, "jr3_offsets_table", jr3_download_firmware);
+ */
 
-	// It takes a few milliseconds for software to settle
-	// as much as we can read firmware version
+/*
+ * It takes a few milliseconds for software to settle as much as we
+ * can read firmware version
+ */
 	msleep_interruptible(25);
 	for (i = 0; i < 0x18; i++) {
 		printk("%c",
@@ -927,7 +924,7 @@
 				copyright[i]) >> 8);
 	}
 
-	// Start card timer
+	/*  Start card timer */
 	for (i = 0; i < devpriv->n_channels; i++) {
 		struct jr3_pci_subdev_private *p = dev->subdevices[i].private;
 
@@ -944,7 +941,7 @@
 	return result;
 }
 
-static int jr3_pci_detach(struct comedi_device * dev)
+static int jr3_pci_detach(struct comedi_device *dev)
 {
 	int i;
 	struct jr3_pci_dev_private *devpriv = dev->private;
diff --git a/drivers/staging/comedi/drivers/jr3_pci.h b/drivers/staging/comedi/drivers/jr3_pci.h
index 3585f29..4f4bfb2 100644
--- a/drivers/staging/comedi/drivers/jr3_pci.h
+++ b/drivers/staging/comedi/drivers/jr3_pci.h
@@ -2,22 +2,22 @@
  * is 16 bits, but aligned on a 32 bit PCI boundary
  */
 
-static inline u16 get_u16(volatile const u32 * p)
+static inline u16 get_u16(volatile const u32 *p)
 {
 	return (u16) readl(p);
 }
 
-static inline void set_u16(volatile u32 * p, u16 val)
+static inline void set_u16(volatile u32 *p, u16 val)
 {
 	writel(val, p);
 }
 
-static inline s16 get_s16(volatile const s32 * p)
+static inline s16 get_s16(volatile const s32 *p)
 {
 	return (s16) readl(p);
 }
 
-static inline void set_s16(volatile s32 * p, s16 val)
+static inline void set_s16(volatile s32 *p, s16 val)
 {
 	writel(val, p);
 }
diff --git a/drivers/staging/comedi/drivers/ke_counter.c b/drivers/staging/comedi/drivers/ke_counter.c
index 79f6fe5..b49aed5 100644
--- a/drivers/staging/comedi/drivers/ke_counter.c
+++ b/drivers/staging/comedi/drivers/ke_counter.c
@@ -48,8 +48,8 @@
 
 /*-- function prototypes ----------------------------------------------------*/
 
-static int cnt_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int cnt_detach(struct comedi_device * dev);
+static int cnt_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int cnt_detach(struct comedi_device *dev);
 
 static DEFINE_PCI_DEVICE_TABLE(cnt_pci_table) = {
 	{PCI_VENDOR_ID_KOLTER, CNT_CARD_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID, 0, 0,
@@ -72,10 +72,10 @@
 
 static const struct cnt_board_struct cnt_boards[] = {
 	{
-	      name:	CNT_DRIVER_NAME,
-	      device_id:CNT_CARD_DEVICE_ID,
-	      cnt_channel_nbr:3,
-      cnt_bits:24}
+	.name = CNT_DRIVER_NAME,
+	.device_id = CNT_CARD_DEVICE_ID,
+	.cnt_channel_nbr = 3,
+	.cnt_bits = 24}
 };
 
 #define cnt_board_nbr (sizeof(cnt_boards)/sizeof(struct cnt_board_struct))
@@ -91,10 +91,10 @@
 #define devpriv ((struct cnt_device_private *)dev->private)
 
 static struct comedi_driver cnt_driver = {
-      driver_name:CNT_DRIVER_NAME,
-      module:THIS_MODULE,
-      attach:cnt_attach,
-      detach:cnt_detach,
+	.driver_name = CNT_DRIVER_NAME,
+	.module = THIS_MODULE,
+	.attach = cnt_attach,
+	.detach = cnt_detach,
 };
 
 COMEDI_PCI_INITCLEANUP(cnt_driver, cnt_pci_table);
@@ -103,8 +103,8 @@
 
 /* This should be used only for resetting the counters; maybe it is better
    to make a special command 'reset'. */
-static int cnt_winsn(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int cnt_winsn(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 
@@ -123,8 +123,8 @@
 
 /*-- counter read -----------------------------------------------------------*/
 
-static int cnt_rinsn(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int cnt_rinsn(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned char a0, a1, a2, a3, a4;
 	int chan = CR_CHAN(insn->chanspec);
@@ -148,7 +148,7 @@
 
 /*-- attach -----------------------------------------------------------------*/
 
-static int cnt_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int cnt_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *subdevice;
 	struct pci_dev *pci_device;
@@ -157,9 +157,9 @@
 	int error, i;
 
 	/* allocate device private structure */
-	if ((error = alloc_private(dev, sizeof(struct cnt_device_private))) < 0) {
+	error = alloc_private(dev, sizeof(struct cnt_device_private));
+	if (error < 0)
 		return error;
-	}
 
 	/* Probe the device to determine what device in the series it is. */
 	for (pci_device = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL);
@@ -203,7 +203,8 @@
 	dev->board_name = board->name;
 
 	/* enable PCI device and request regions */
-	if ((error = comedi_pci_enable(pci_device, CNT_DRIVER_NAME)) < 0) {
+	error = comedi_pci_enable(pci_device, CNT_DRIVER_NAME);
+	if (error < 0) {
 		printk("comedi%d: failed to enable PCI device and request regions!\n", dev->minor);
 		return error;
 	}
@@ -213,9 +214,9 @@
 	dev->iobase = io_base;
 
 	/* allocate the subdevice structures */
-	if ((error = alloc_subdevices(dev, 1)) < 0) {
+	error = alloc_subdevices(dev, 1);
+	if (error < 0)
 		return error;
-	}
 
 	subdevice = dev->subdevices + 0;
 	dev->read_subdev = subdevice;
@@ -227,10 +228,10 @@
 	subdevice->insn_read = cnt_rinsn;
 	subdevice->insn_write = cnt_winsn;
 
-	// select 20MHz clock
+	/*  select 20MHz clock */
 	outb(3, dev->iobase + 248);
 
-	// reset all counters
+	/*  reset all counters */
 	outb(0, dev->iobase);
 	outb(0, dev->iobase + 0x20);
 	outb(0, dev->iobase + 0x40);
@@ -241,7 +242,7 @@
 
 /*-- detach -----------------------------------------------------------------*/
 
-static int cnt_detach(struct comedi_device * dev)
+static int cnt_detach(struct comedi_device *dev)
 {
 	if (devpriv && devpriv->pcidev) {
 		if (dev->iobase) {
diff --git a/drivers/staging/comedi/drivers/me4000.c b/drivers/staging/comedi/drivers/me4000.c
index 12481a0..2368458 100644
--- a/drivers/staging/comedi/drivers/me4000.c
+++ b/drivers/staging/comedi/drivers/me4000.c
@@ -51,6 +51,7 @@
 
  */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/delay.h>
@@ -113,7 +114,7 @@
 	{0},
 };
 
-#define ME4000_BOARD_VERSIONS (sizeof(me4000_boards) / sizeof(struct me4000_board) - 1)
+#define ME4000_BOARD_VERSIONS (ARRAY_SIZE(me4000_boards) - 1)
 
 /*-----------------------------------------------------------------------------
   Comedi function prototypes
@@ -183,7 +184,7 @@
 static int ai_write_chanlist(struct comedi_device *dev,
 	struct comedi_subdevice *s, struct comedi_cmd *cmd);
 
-static irqreturn_t me4000_ai_isr(int irq, void *dev_id PT_REGS_ARG);
+static irqreturn_t me4000_ai_isr(int irq, void *dev_id);
 
 static int me4000_ai_do_cmd_test(struct comedi_device *dev,
 	struct comedi_subdevice *s, struct comedi_cmd *cmd);
@@ -283,7 +284,7 @@
 		s->insn_read = me4000_ai_insn_read;
 
 		if (info->irq > 0) {
-			if (comedi_request_irq(info->irq, me4000_ai_isr,
+			if (request_irq(info->irq, me4000_ai_isr,
 					IRQF_SHARED, "ME-4000", dev)) {
 				printk("comedi%d: me4000: me4000_attach(): Unable to allocate irq\n", dev->minor);
 			} else {
@@ -1740,7 +1741,7 @@
 	return 0;
 }
 
-static irqreturn_t me4000_ai_isr(int irq, void *dev_id PT_REGS_ARG)
+static irqreturn_t me4000_ai_isr(int irq, void *dev_id)
 {
 	unsigned int tmp;
 	struct comedi_device *dev = dev_id;
diff --git a/drivers/staging/comedi/drivers/me_daq.c b/drivers/staging/comedi/drivers/me_daq.c
index 0f023d00..f21cecaa 100644
--- a/drivers/staging/comedi/drivers/me_daq.c
+++ b/drivers/staging/comedi/drivers/me_daq.c
@@ -50,6 +50,7 @@
 
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include "comedi_pci.h"
diff --git a/drivers/staging/comedi/drivers/mite.c b/drivers/staging/comedi/drivers/mite.c
index ae90177..22a4029 100644
--- a/drivers/staging/comedi/drivers/mite.c
+++ b/drivers/staging/comedi/drivers/mite.c
@@ -258,7 +258,7 @@
 	struct mite_channel *channel = NULL;
 
 	/*  spin lock so mite_release_channel can be called safely from interrupts */
-	comedi_spin_lock_irqsave(&mite->lock, flags);
+	spin_lock_irqsave(&mite->lock, flags);
 	for (i = min_channel; i <= max_channel; ++i) {
 		if (mite->channel_allocated[i] == 0) {
 			mite->channel_allocated[i] = 1;
@@ -267,7 +267,7 @@
 			break;
 		}
 	}
-	comedi_spin_unlock_irqrestore(&mite->lock, flags);
+	spin_unlock_irqrestore(&mite->lock, flags);
 	return channel;
 }
 
@@ -277,7 +277,7 @@
 	unsigned long flags;
 
 	/*  spin lock to prevent races with mite_request_channel */
-	comedi_spin_lock_irqsave(&mite->lock, flags);
+	spin_lock_irqsave(&mite->lock, flags);
 	if (mite->channel_allocated[mite_chan->channel]) {
 		mite_dma_disarm(mite_chan);
 		mite_dma_reset(mite_chan);
@@ -292,7 +292,7 @@
 		mite_chan->ring = NULL;
 		mmiowb();
 	}
-	comedi_spin_unlock_irqrestore(&mite->lock, flags);
+	spin_unlock_irqrestore(&mite->lock, flags);
 }
 
 void mite_dma_arm(struct mite_channel *mite_chan)
@@ -307,11 +307,11 @@
 	smp_mb();
 	/* arm */
 	chor = CHOR_START;
-	comedi_spin_lock_irqsave(&mite->lock, flags);
+	spin_lock_irqsave(&mite->lock, flags);
 	mite_chan->done = 0;
 	writel(chor, mite->mite_io_addr + MITE_CHOR(mite_chan->channel));
 	mmiowb();
-	comedi_spin_unlock_irqrestore(&mite->lock, flags);
+	spin_unlock_irqrestore(&mite->lock, flags);
 /*       mite_dma_tcr(mite, channel); */
 }
 
@@ -413,7 +413,7 @@
 		mcr |= CR_PSIZE32;
 		break;
 	default:
-		rt_printk
+		printk
 			("mite: bug! invalid mem bit width for dma transfer\n");
 		break;
 	}
@@ -433,7 +433,7 @@
 		dcr |= CR_PSIZE32;
 		break;
 	default:
-		rt_printk
+		printk
 			("mite: bug! invalid dev bit width for dma transfer\n");
 		break;
 	}
@@ -539,7 +539,7 @@
 	nbytes = mite_bytes_written_to_memory_lb(mite_chan);
 	if ((int)(mite_bytes_written_to_memory_ub(mite_chan) -
 			old_alloc_count) > 0) {
-		rt_printk("mite: DMA overwrite of free area\n");
+		printk("mite: DMA overwrite of free area\n");
 		async->events |= COMEDI_CB_OVERFLOW;
 		return -1;
 	}
@@ -581,7 +581,7 @@
 		(int)(nbytes_ub - stop_count) > 0)
 		nbytes_ub = stop_count;
 	if ((int)(nbytes_ub - old_alloc_count) > 0) {
-		rt_printk("mite: DMA underrun\n");
+		printk("mite: DMA underrun\n");
 		async->events |= COMEDI_CB_OVERFLOW;
 		return -1;
 	}
@@ -602,7 +602,7 @@
 	unsigned status;
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&mite->lock, flags);
+	spin_lock_irqsave(&mite->lock, flags);
 	status = readl(mite->mite_io_addr + MITE_CHSR(mite_chan->channel));
 	if (status & CHSR_DONE) {
 		mite_chan->done = 1;
@@ -610,7 +610,7 @@
 			mite->mite_io_addr + MITE_CHOR(mite_chan->channel));
 	}
 	mmiowb();
-	comedi_spin_unlock_irqrestore(&mite->lock, flags);
+	spin_unlock_irqrestore(&mite->lock, flags);
 	return status;
 }
 
@@ -621,9 +621,9 @@
 	int done;
 
 	mite_get_status(mite_chan);
-	comedi_spin_lock_irqsave(&mite->lock, flags);
+	spin_lock_irqsave(&mite->lock, flags);
 	done = mite_chan->done;
-	comedi_spin_unlock_irqrestore(&mite->lock, flags);
+	spin_unlock_irqrestore(&mite->lock, flags);
 	return done;
 }
 
diff --git a/drivers/staging/comedi/drivers/mite.h b/drivers/staging/comedi/drivers/mite.h
index cdaf8a3..3194231 100644
--- a/drivers/staging/comedi/drivers/mite.h
+++ b/drivers/staging/comedi/drivers/mite.h
@@ -405,7 +405,7 @@
 		value++;
 	}
 	if (value > 0x7)
-		rt_printk("comedi: bug! retry_limit too large\n");
+		printk("comedi: bug! retry_limit too large\n");
 	return (value & 0x7) << 21;
 }
 
diff --git a/drivers/staging/comedi/drivers/mpc624.c b/drivers/staging/comedi/drivers/mpc624.c
index a151602..4a0e647 100644
--- a/drivers/staging/comedi/drivers/mpc624.c
+++ b/drivers/staging/comedi/drivers/mpc624.c
@@ -61,19 +61,19 @@
 #include <linux/ioport.h>
 #include <linux/delay.h>
 
-// Consecutive I/O port addresses
+/* Consecutive I/O port addresses */
 #define MPC624_SIZE             16
 
-// Offsets of different ports
-#define MPC624_MASTER_CONTROL	0	// not used
-#define MPC624_GNMUXCH          1	// Gain, Mux, Channel of ADC
-#define MPC624_ADC              2	// read/write to/from ADC
-#define MPC624_EE               3	// read/write to/from serial EEPROM via I2C
-#define MPC624_LEDS             4	// write to LEDs
-#define MPC624_DIO              5	// read/write to/from digital I/O ports
-#define MPC624_IRQ_MASK         6	// IRQ masking enable/disable
+/* Offsets of different ports */
+#define MPC624_MASTER_CONTROL	0	/*  not used */
+#define MPC624_GNMUXCH          1	/*  Gain, Mux, Channel of ADC */
+#define MPC624_ADC              2	/*  read/write to/from ADC */
+#define MPC624_EE               3	/*  read/write to/from serial EEPROM via I2C */
+#define MPC624_LEDS             4	/*  write to LEDs */
+#define MPC624_DIO              5	/*  read/write to/from digital I/O ports */
+#define MPC624_IRQ_MASK         6	/*  IRQ masking enable/disable */
 
-// Register bits' names
+/* Register bits' names */
 #define MPC624_ADBUSY           (1<<5)
 #define MPC624_ADSDO            (1<<4)
 #define MPC624_ADFO             (1<<3)
@@ -81,19 +81,19 @@
 #define MPC624_ADSCK            (1<<1)
 #define MPC624_ADSDI            (1<<0)
 
-// SDI Speed/Resolution Programming bits
+/* SDI Speed/Resolution Programming bits */
 #define MPC624_OSR4             (1<<31)
 #define MPC624_OSR3             (1<<30)
 #define MPC624_OSR2             (1<<29)
 #define MPC624_OSR1             (1<<28)
 #define MPC624_OSR0             (1<<27)
 
-// 32-bit output value bits' names
+/* 32-bit output value bits' names */
 #define MPC624_EOC_BIT          (1<<31)
 #define MPC624_DMY_BIT          (1<<30)
 #define MPC624_SGN_BIT          (1<<29)
 
-// Convertion speeds
+/* Convertion speeds */
 /* OSR4 OSR3 OSR2 OSR1 OSR0  Convertion rate  RMS noise  ENOB^
  *  X    0    0    0    1        3.52kHz        23uV      17
  *  X    0    0    1    0        1.76kHz       3.5uV      20
@@ -110,123 +110,123 @@
  */
 
 #define MPC624_SPEED_3_52_kHz   (MPC624_OSR4                                           | MPC624_OSR0)
-#define MPC624_SPEED_1_76_kHz   (MPC624_OSR4                             | MPC624_OSR1              )
+#define MPC624_SPEED_1_76_kHz   (MPC624_OSR4                             | MPC624_OSR1)
 #define MPC624_SPEED_880_Hz     (MPC624_OSR4                             | MPC624_OSR1 | MPC624_OSR0)
-#define MPC624_SPEED_440_Hz     (MPC624_OSR4               | MPC624_OSR2                            )
+#define MPC624_SPEED_440_Hz     (MPC624_OSR4               | MPC624_OSR2)
 #define MPC624_SPEED_220_Hz     (MPC624_OSR4               | MPC624_OSR2               | MPC624_OSR0)
-#define MPC624_SPEED_110_Hz     (MPC624_OSR4               | MPC624_OSR2 | MPC624_OSR1              )
+#define MPC624_SPEED_110_Hz     (MPC624_OSR4               | MPC624_OSR2 | MPC624_OSR1)
 #define MPC624_SPEED_55_Hz      (MPC624_OSR4               | MPC624_OSR2 | MPC624_OSR1 | MPC624_OSR0)
-#define MPC624_SPEED_27_5_Hz    (MPC624_OSR4 | MPC624_OSR3                                          )
+#define MPC624_SPEED_27_5_Hz    (MPC624_OSR4 | MPC624_OSR3)
 #define MPC624_SPEED_13_75_Hz   (MPC624_OSR4 | MPC624_OSR3                             | MPC624_OSR0)
 #define MPC624_SPEED_6_875_Hz   (MPC624_OSR4 | MPC624_OSR3 | MPC624_OSR2 | MPC624_OSR1 | MPC624_OSR0)
-//----------------------------------------------------------------------------
+/* ---------------------------------------------------------------------------- */
 struct skel_private {
 
-	unsigned long int ulConvertionRate;	// set by mpc624_attach() from driver's parameters
+	unsigned long int ulConvertionRate;	/*  set by mpc624_attach() from driver's parameters */
 };
 
 
 #define devpriv ((struct skel_private *)dev->private)
-//----------------------------------------------------------------------------
+/* ---------------------------------------------------------------------------- */
 static const struct comedi_lrange range_mpc624_bipolar1 = {
 	1,
 	{
-//    BIP_RANGE(1.01) // this is correct,
-			// but my MPC-624 actually seems to have a range of 2.02
+/* BIP_RANGE(1.01)  this is correct, */
+			/*  but my MPC-624 actually seems to have a range of 2.02 */
 			BIP_RANGE(2.02)
 		}
 };
 static const struct comedi_lrange range_mpc624_bipolar10 = {
 	1,
 	{
-//    BIP_RANGE(10.1) // this is correct,
-			// but my MPC-624 actually seems to have a range of 20.2
+/* BIP_RANGE(10.1)   this is correct, */
+			/*  but my MPC-624 actually seems to have a range of 20.2 */
 			BIP_RANGE(20.2)
 		}
 };
 
-//----------------------------------------------------------------------------
-static int mpc624_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int mpc624_detach(struct comedi_device * dev);
-//----------------------------------------------------------------------------
+/* ---------------------------------------------------------------------------- */
+static int mpc624_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int mpc624_detach(struct comedi_device *dev);
+/* ---------------------------------------------------------------------------- */
 static struct comedi_driver driver_mpc624 = {
-      driver_name:"mpc624",
-      module:THIS_MODULE,
-      attach:mpc624_attach,
-      detach:mpc624_detach
+	.driver_name = "mpc624",
+	.module = THIS_MODULE,
+	.attach = mpc624_attach,
+	.detach = mpc624_detach
 };
 
-//----------------------------------------------------------------------------
-static int mpc624_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-//----------------------------------------------------------------------------
-static int mpc624_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+/* ---------------------------------------------------------------------------- */
+static int mpc624_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+/* ---------------------------------------------------------------------------- */
+static int mpc624_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase;
 
 	iobase = it->options[0];
-	rt_printk("comedi%d: mpc624 [0x%04lx, ", dev->minor, iobase);
+	printk("comedi%d: mpc624 [0x%04lx, ", dev->minor, iobase);
 	if (request_region(iobase, MPC624_SIZE, "mpc624") == NULL) {
-		rt_printk("I/O port(s) in use\n");
+		printk("I/O port(s) in use\n");
 		return -EIO;
 	}
 
 	dev->iobase = iobase;
 	dev->board_name = "mpc624";
 
-	// Private structure initialization
+	/*  Private structure initialization */
 	if (alloc_private(dev, sizeof(struct skel_private)) < 0)
 		return -ENOMEM;
 
 	switch (it->options[1]) {
 	case 0:
 		devpriv->ulConvertionRate = MPC624_SPEED_3_52_kHz;
-		rt_printk("3.52 kHz, ");
+		printk("3.52 kHz, ");
 		break;
 	case 1:
 		devpriv->ulConvertionRate = MPC624_SPEED_1_76_kHz;
-		rt_printk("1.76 kHz, ");
+		printk("1.76 kHz, ");
 		break;
 	case 2:
 		devpriv->ulConvertionRate = MPC624_SPEED_880_Hz;
-		rt_printk("880 Hz, ");
+		printk("880 Hz, ");
 		break;
 	case 3:
 		devpriv->ulConvertionRate = MPC624_SPEED_440_Hz;
-		rt_printk("440 Hz, ");
+		printk("440 Hz, ");
 		break;
 	case 4:
 		devpriv->ulConvertionRate = MPC624_SPEED_220_Hz;
-		rt_printk("220 Hz, ");
+		printk("220 Hz, ");
 		break;
 	case 5:
 		devpriv->ulConvertionRate = MPC624_SPEED_110_Hz;
-		rt_printk("110 Hz, ");
+		printk("110 Hz, ");
 		break;
 	case 6:
 		devpriv->ulConvertionRate = MPC624_SPEED_55_Hz;
-		rt_printk("55 Hz, ");
+		printk("55 Hz, ");
 		break;
 	case 7:
 		devpriv->ulConvertionRate = MPC624_SPEED_27_5_Hz;
-		rt_printk("27.5 Hz, ");
+		printk("27.5 Hz, ");
 		break;
 	case 8:
 		devpriv->ulConvertionRate = MPC624_SPEED_13_75_Hz;
-		rt_printk("13.75 Hz, ");
+		printk("13.75 Hz, ");
 		break;
 	case 9:
 		devpriv->ulConvertionRate = MPC624_SPEED_6_875_Hz;
-		rt_printk("6.875 Hz, ");
+		printk("6.875 Hz, ");
 		break;
 	default:
-		rt_printk
+		printk
 			("illegal convertion rate setting! Valid numbers are 0..9. Using 9 => 6.875 Hz, ");
 		devpriv->ulConvertionRate = MPC624_SPEED_3_52_kHz;
 	}
 
-	// Subdevices structures
+	/*  Subdevices structures */
 	if (alloc_subdevices(dev, 1) < 0)
 		return -ENOMEM;
 
@@ -237,29 +237,29 @@
 	switch (it->options[1]) {
 	default:
 		s->maxdata = 0x3FFFFFFF;
-		rt_printk("30 bit, ");
+		printk("30 bit, ");
 	}
 
 	switch (it->options[1]) {
 	case 0:
 		s->range_table = &range_mpc624_bipolar1;
-		rt_printk("1.01V]: ");
+		printk("1.01V]: ");
 		break;
 	default:
 		s->range_table = &range_mpc624_bipolar10;
-		rt_printk("10.1V]: ");
+		printk("10.1V]: ");
 	}
 	s->len_chanlist = 1;
 	s->insn_read = mpc624_ai_rinsn;
 
-	rt_printk("attached\n");
+	printk("attached\n");
 
 	return 1;
 }
 
-static int mpc624_detach(struct comedi_device * dev)
+static int mpc624_detach(struct comedi_device *dev)
 {
-	rt_printk("comedi%d: mpc624: remove\n", dev->minor);
+	printk("comedi%d: mpc624: remove\n", dev->minor);
 
 	if (dev->iobase)
 		release_region(dev->iobase, MPC624_SIZE);
@@ -267,119 +267,119 @@
 	return 0;
 }
 
-// Timeout 200ms
+/* Timeout 200ms */
 #define TIMEOUT 200
 
-static int mpc624_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int mpc624_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, i;
 	unsigned long int data_in, data_out;
 	unsigned char ucPort;
 
-	// WARNING: We always write 0 to GNSWA bit, so the channel range is +-/10.1Vdc
+	/*  WARNING: We always write 0 to GNSWA bit, so the channel range is +-/10.1Vdc */
 	outb(insn->chanspec, dev->iobase + MPC624_GNMUXCH);
-//    rt_printk("Channel %d: \n", insn->chanspec);
+/* printk("Channel %d: \n", insn->chanspec); */
 	if (!insn->n) {
-		rt_printk("MPC624: Warning, no data to aquire\n");
+		printk("MPC624: Warning, no data to aquire\n");
 		return 0;
 	}
 
 	for (n = 0; n < insn->n; n++) {
-		// Trigger the convertion
+		/*  Trigger the convertion */
 		outb(MPC624_ADSCK, dev->iobase + MPC624_ADC);
-		comedi_udelay(1);
+		udelay(1);
 		outb(MPC624_ADCS | MPC624_ADSCK, dev->iobase + MPC624_ADC);
-		comedi_udelay(1);
+		udelay(1);
 		outb(0, dev->iobase + MPC624_ADC);
-		comedi_udelay(1);
+		udelay(1);
 
-		// Wait for the convertion to end
+		/*  Wait for the convertion to end */
 		for (i = 0; i < TIMEOUT; i++) {
 			ucPort = inb(dev->iobase + MPC624_ADC);
 			if (ucPort & MPC624_ADBUSY)
-				comedi_udelay(1000);
+				udelay(1000);
 			else
 				break;
 		}
 		if (i == TIMEOUT) {
-			rt_printk("MPC624: timeout (%dms)\n", TIMEOUT);
+			printk("MPC624: timeout (%dms)\n", TIMEOUT);
 			data[n] = 0;
 			return -ETIMEDOUT;
 		}
-		// Start reading data
+		/*  Start reading data */
 		data_in = 0;
 		data_out = devpriv->ulConvertionRate;
-		comedi_udelay(1);
+		udelay(1);
 		for (i = 0; i < 32; i++) {
-			// Set the clock low
+			/*  Set the clock low */
 			outb(0, dev->iobase + MPC624_ADC);
-			comedi_udelay(1);
+			udelay(1);
 
-			if (data_out & (1 << 31))	// the next bit is a 1
+			if (data_out & (1 << 31))	/*  the next bit is a 1 */
 			{
-				// Set the ADSDI line (send to MPC624)
+				/*  Set the ADSDI line (send to MPC624) */
 				outb(MPC624_ADSDI, dev->iobase + MPC624_ADC);
-				comedi_udelay(1);
-				// Set the clock high
+				udelay(1);
+				/*  Set the clock high */
 				outb(MPC624_ADSCK | MPC624_ADSDI,
 					dev->iobase + MPC624_ADC);
-			} else	// the next bit is a 0
+			} else	/*  the next bit is a 0 */
 			{
-				// Set the ADSDI line (send to MPC624)
+				/*  Set the ADSDI line (send to MPC624) */
 				outb(0, dev->iobase + MPC624_ADC);
-				comedi_udelay(1);
-				// Set the clock high
+				udelay(1);
+				/*  Set the clock high */
 				outb(MPC624_ADSCK, dev->iobase + MPC624_ADC);
 			}
-			// Read ADSDO on high clock (receive from MPC624)
-			comedi_udelay(1);
+			/*  Read ADSDO on high clock (receive from MPC624) */
+			udelay(1);
 			data_in <<= 1;
 			data_in |=
 				(inb(dev->iobase +
 					MPC624_ADC) & MPC624_ADSDO) >> 4;
-			comedi_udelay(1);
+			udelay(1);
 
 			data_out <<= 1;
 		}
 
-		// Received 32-bit long value consist of:
-		//   31: EOC (End Of Transmission) bit - should be 0
-		//   30: DMY (Dummy) bit               - should be 0
-		//   29: SIG (Sign) bit                - 1 if the voltage is positive, 0 if negative
-		//   28: MSB (Most Significant Bit)    - the first bit of convertion result
-		//   ....
-		//   05: LSB (Least Significant Bit)   - the last bit of convertion result
-		//   04: sub-LSB                       - sub-LSBs are basically noise, but when
-		//   03: sub-LSB                         averaged properly, they can increase convertion
-		//   02: sub-LSB                         precision up to 29 bits; they can be discarded
-		//   01: sub-LSB                         without loss of resolution.
-		//   00: sub-LSB
+		/*  Received 32-bit long value consist of: */
+		/*    31: EOC (End Of Transmission) bit - should be 0 */
+		/*    30: DMY (Dummy) bit               - should be 0 */
+		/*    29: SIG (Sign) bit                - 1 if the voltage is positive, 0 if negative */
+		/*    28: MSB (Most Significant Bit)    - the first bit of convertion result */
+		/*    .... */
+		/*    05: LSB (Least Significant Bit)   - the last bit of convertion result */
+		/*    04: sub-LSB                       - sub-LSBs are basically noise, but when */
+		/*    03: sub-LSB                         averaged properly, they can increase convertion */
+		/*    02: sub-LSB                         precision up to 29 bits; they can be discarded */
+		/*    01: sub-LSB                         without loss of resolution. */
+		/*    00: sub-LSB */
 
 		if (data_in & MPC624_EOC_BIT)
-			rt_printk("MPC624: EOC bit is set (data_in=%lu)!",
+			printk("MPC624: EOC bit is set (data_in=%lu)!",
 				data_in);
 		if (data_in & MPC624_DMY_BIT)
-			rt_printk("MPC624: DMY bit is set (data_in=%lu)!",
+			printk("MPC624: DMY bit is set (data_in=%lu)!",
 				data_in);
-		if (data_in & MPC624_SGN_BIT)	// check the sign bit
-		{		// The voltage is positive
-			data_in &= 0x3FFFFFFF;	// EOC and DMY should be 0, but we will mask them out just to be sure
-			data[n] = data_in;	// comedi operates on unsigned numbers, so we don't clear the SGN bit
-			// SGN bit is still set! It's correct, since we're converting to unsigned.
-		} else {	// The voltage is negative
-			// data_in contains a number in 30-bit two's complement code and we must deal with it
+		if (data_in & MPC624_SGN_BIT)	/*  check the sign bit */
+		{		/*  The voltage is positive */
+			data_in &= 0x3FFFFFFF;	/*  EOC and DMY should be 0, but we will mask them out just to be sure */
+			data[n] = data_in;	/*  comedi operates on unsigned numbers, so we don't clear the SGN bit */
+			/*  SGN bit is still set! It's correct, since we're converting to unsigned. */
+		} else {	/*  The voltage is negative */
+			/*  data_in contains a number in 30-bit two's complement code and we must deal with it */
 			data_in |= MPC624_SGN_BIT;
 			data_in = ~data_in;
 			data_in += 1;
 			data_in &= ~(MPC624_EOC_BIT | MPC624_DMY_BIT);
-			// clear EOC and DMY bits
+			/*  clear EOC and DMY bits */
 			data_in = 0x20000000 - data_in;
 			data[n] = data_in;
 		}
 	}
 
-	// Return the number of samples read/written
+	/*  Return the number of samples read/written */
 	return n;
 }
 
diff --git a/drivers/staging/comedi/drivers/mpc8260cpm.c b/drivers/staging/comedi/drivers/mpc8260cpm.c
index bac0a7b..c7ee3ef 100644
--- a/drivers/staging/comedi/drivers/mpc8260cpm.c
+++ b/drivers/staging/comedi/drivers/mpc8260cpm.c
@@ -46,23 +46,23 @@
 
 #define devpriv ((struct mpc8260cpm_private *)dev->private)
 
-static int mpc8260cpm_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int mpc8260cpm_detach(struct comedi_device * dev);
+static int mpc8260cpm_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int mpc8260cpm_detach(struct comedi_device *dev);
 static struct comedi_driver driver_mpc8260cpm = {
-      driver_name:"mpc8260cpm",
-      module:THIS_MODULE,
-      attach:mpc8260cpm_attach,
-      detach:mpc8260cpm_detach,
+	.driver_name = "mpc8260cpm",
+	.module = THIS_MODULE,
+	.attach = mpc8260cpm_attach,
+	.detach = mpc8260cpm_detach,
 };
 
 COMEDI_INITCLEANUP(driver_mpc8260cpm);
 
-static int mpc8260cpm_dio_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int mpc8260cpm_dio_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int mpc8260cpm_dio_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int mpc8260cpm_dio_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int mpc8260cpm_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int mpc8260cpm_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int i;
@@ -93,7 +93,7 @@
 	return 1;
 }
 
-static int mpc8260cpm_detach(struct comedi_device * dev)
+static int mpc8260cpm_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: mpc8260cpm: remove\n", dev->minor);
 
@@ -114,8 +114,8 @@
 	}
 }
 
-static int mpc8260cpm_dio_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int mpc8260cpm_dio_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	unsigned int d;
@@ -157,8 +157,8 @@
 	return 1;
 }
 
-static int mpc8260cpm_dio_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int mpc8260cpm_dio_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int port;
 	unsigned long *p;
diff --git a/drivers/staging/comedi/drivers/multiq3.c b/drivers/staging/comedi/drivers/multiq3.c
index 9e47574..f7cce6c 100644
--- a/drivers/staging/comedi/drivers/multiq3.c
+++ b/drivers/staging/comedi/drivers/multiq3.c
@@ -29,6 +29,7 @@
 
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -82,13 +83,13 @@
 
 #define MULTIQ3_TIMEOUT 30
 
-static int multiq3_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int multiq3_detach(struct comedi_device * dev);
+static int multiq3_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int multiq3_detach(struct comedi_device *dev);
 static struct comedi_driver driver_multiq3 = {
-      driver_name:"multiq3",
-      module:THIS_MODULE,
-      attach:multiq3_attach,
-      detach:multiq3_detach,
+	.driver_name = "multiq3",
+	.module = THIS_MODULE,
+	.attach = multiq3_attach,
+	.detach = multiq3_detach,
 };
 
 COMEDI_INITCLEANUP(driver_multiq3);
@@ -98,8 +99,8 @@
 };
 #define devpriv ((struct multiq3_private *)dev->private)
 
-static int multiq3_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int multiq3_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, n;
 	int chan;
@@ -134,8 +135,8 @@
 	return n;
 }
 
-static int multiq3_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int multiq3_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -147,8 +148,8 @@
 	return i;
 }
 
-static int multiq3_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int multiq3_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -165,8 +166,8 @@
 	return i;
 }
 
-static int multiq3_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int multiq3_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -176,8 +177,8 @@
 	return 2;
 }
 
-static int multiq3_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int multiq3_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -191,8 +192,8 @@
 	return 2;
 }
 
-static int multiq3_encoder_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int multiq3_encoder_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan = CR_CHAN(insn->chanspec);
@@ -212,7 +213,7 @@
 	return n;
 }
 
-static void encoder_reset(struct comedi_device * dev)
+static void encoder_reset(struct comedi_device *dev)
 {
 	int chan;
 	for (chan = 0; chan < dev->subdevices[4].n_chan; chan++) {
@@ -235,7 +236,7 @@
    options[2] - number of encoder chips installed
  */
 
-static int multiq3_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int multiq3_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int result = 0;
 	unsigned long iobase;
@@ -318,7 +319,7 @@
 	return 0;
 }
 
-static int multiq3_detach(struct comedi_device * dev)
+static int multiq3_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: multiq3: remove\n", dev->minor);
 
diff --git a/drivers/staging/comedi/drivers/ni_6527.c b/drivers/staging/comedi/drivers/ni_6527.c
index e01ecb6..67adc97 100644
--- a/drivers/staging/comedi/drivers/ni_6527.c
+++ b/drivers/staging/comedi/drivers/ni_6527.c
@@ -41,6 +41,7 @@
 #define DEBUG 1
 #define DEBUG_FLAGS
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include "mite.h"
@@ -75,13 +76,13 @@
 #define Rising_Edge_Detection_Enable(x)		(0x018+(x))
 #define Falling_Edge_Detection_Enable(x)	(0x020+(x))
 
-static int ni6527_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int ni6527_detach(struct comedi_device * dev);
+static int ni6527_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int ni6527_detach(struct comedi_device *dev);
 static struct comedi_driver driver_ni6527 = {
-      driver_name:"ni6527",
-      module:THIS_MODULE,
-      attach:ni6527_attach,
-      detach:ni6527_detach,
+	.driver_name = "ni6527",
+	.module = THIS_MODULE,
+	.attach = ni6527_attach,
+	.detach = ni6527_detach,
 };
 
 struct ni6527_board {
@@ -92,12 +93,12 @@
 
 static const struct ni6527_board ni6527_boards[] = {
 	{
-	      dev_id:	0x2b20,
-	      name:	"pci-6527",
+	.dev_id = 0x2b20,
+	.name = "pci-6527",
 		},
 	{
-	      dev_id:	0x2b10,
-	      name:	"pxi-6527",
+	.dev_id = 0x2b10,
+	.name = "pxi-6527",
 		},
 };
 
@@ -120,10 +121,10 @@
 
 #define devpriv ((struct ni6527_private *)dev->private)
 
-static int ni6527_find_device(struct comedi_device * dev, int bus, int slot);
+static int ni6527_find_device(struct comedi_device *dev, int bus, int slot);
 
-static int ni6527_di_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni6527_di_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 	unsigned int interval;
@@ -170,8 +171,8 @@
 	return 2;
 }
 
-static int ni6527_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni6527_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -183,8 +184,8 @@
 	return 2;
 }
 
-static int ni6527_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni6527_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -212,7 +213,7 @@
 	return 2;
 }
 
-static irqreturn_t ni6527_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t ni6527_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s = dev->subdevices + 2;
@@ -233,8 +234,8 @@
 	return IRQ_HANDLED;
 }
 
-static int ni6527_intr_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int ni6527_intr_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -309,9 +310,9 @@
 	return 0;
 }
 
-static int ni6527_intr_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni6527_intr_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
-	//struct comedi_cmd *cmd = &s->async->cmd;
+	/* struct comedi_cmd *cmd = &s->async->cmd; */
 
 	writeb(ClrEdge | ClrOverflow,
 		devpriv->mite->daq_io_addr + Clear_Register);
@@ -322,15 +323,15 @@
 	return 0;
 }
 
-static int ni6527_intr_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni6527_intr_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	writeb(0x00, devpriv->mite->daq_io_addr + Master_Interrupt_Control);
 
 	return 0;
 }
 
-static int ni6527_intr_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni6527_intr_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n < 1)
 		return -EINVAL;
@@ -339,8 +340,8 @@
 	return 2;
 }
 
-static int ni6527_intr_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni6527_intr_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n < 1)
 		return -EINVAL;
@@ -364,14 +365,15 @@
 	return 2;
 }
 
-static int ni6527_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int ni6527_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int ret;
 
 	printk("comedi%d: ni6527:", dev->minor);
 
-	if ((ret = alloc_private(dev, sizeof(struct ni6527_private))) < 0)
+	ret = alloc_private(dev, sizeof(struct ni6527_private));
+	if (ret < 0)
 		return ret;
 
 	ret = ni6527_find_device(dev, it->options[0], it->options[1]);
@@ -389,7 +391,8 @@
 
 	printk(" ID=0x%02x", readb(devpriv->mite->daq_io_addr + ID_Register));
 
-	if ((ret = alloc_subdevices(dev, 3)) < 0)
+	ret = alloc_subdevices(dev, 3);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -430,8 +433,8 @@
 		devpriv->mite->daq_io_addr + Clear_Register);
 	writeb(0x00, devpriv->mite->daq_io_addr + Master_Interrupt_Control);
 
-	ret = comedi_request_irq(mite_irq(devpriv->mite), ni6527_interrupt,
-		IRQF_SHARED, "ni6527", dev);
+	ret = request_irq(mite_irq(devpriv->mite), ni6527_interrupt,
+			  IRQF_SHARED, "ni6527", dev);
 	if (ret < 0) {
 		printk(" irq not available");
 	} else
@@ -442,7 +445,7 @@
 	return 0;
 }
 
-static int ni6527_detach(struct comedi_device * dev)
+static int ni6527_detach(struct comedi_device *dev)
 {
 	if (devpriv && devpriv->mite && devpriv->mite->daq_io_addr) {
 		writeb(0x00,
@@ -450,7 +453,7 @@
 	}
 
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 
 	if (devpriv && devpriv->mite) {
@@ -460,7 +463,7 @@
 	return 0;
 }
 
-static int ni6527_find_device(struct comedi_device * dev, int bus, int slot)
+static int ni6527_find_device(struct comedi_device *dev, int bus, int slot)
 {
 	struct mite_struct *mite;
 	int i;
diff --git a/drivers/staging/comedi/drivers/ni_65xx.c b/drivers/staging/comedi/drivers/ni_65xx.c
index 6e85da1..3570850 100644
--- a/drivers/staging/comedi/drivers/ni_65xx.c
+++ b/drivers/staging/comedi/drivers/ni_65xx.c
@@ -50,6 +50,7 @@
 #define _GNU_SOURCE
 #define DEBUG 1
 #define DEBUG_FLAGS
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include "mite.h"
@@ -102,13 +103,13 @@
 #define OverflowIntEnable		0x02
 #define EdgeIntEnable			0x01
 
-static int ni_65xx_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int ni_65xx_detach(struct comedi_device * dev);
+static int ni_65xx_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int ni_65xx_detach(struct comedi_device *dev);
 static struct comedi_driver driver_ni_65xx = {
-      driver_name:"ni_65xx",
-      module:THIS_MODULE,
-      attach:ni_65xx_attach,
-      detach:ni_65xx_detach,
+	.driver_name = "ni_65xx",
+	.module = THIS_MODULE,
+	.attach = ni_65xx_attach,
+	.detach = ni_65xx_detach,
 };
 
 struct ni_65xx_board {
@@ -123,120 +124,120 @@
 
 static const struct ni_65xx_board ni_65xx_boards[] = {
 	{
-	      dev_id:	0x7085,
-	      name:	"pci-6509",
-	      num_dio_ports:12,
-      invert_outputs:0},
+	.dev_id = 0x7085,
+	.name = "pci-6509",
+	.num_dio_ports = 12,
+	.invert_outputs = 0},
 	{
-	      dev_id:	0x1710,
-	      name:	"pxi-6509",
-	      num_dio_ports:12,
-      invert_outputs:0},
+	.dev_id = 0x1710,
+	.name = "pxi-6509",
+	.num_dio_ports = 12,
+	.invert_outputs = 0},
 	{
-	      dev_id:	0x7124,
-	      name:	"pci-6510",
-      num_di_ports:4},
+	.dev_id = 0x7124,
+	.name = "pci-6510",
+	.num_di_ports = 4},
 	{
-	      dev_id:	0x70c3,
-	      name:	"pci-6511",
-      num_di_ports:8},
+	.dev_id = 0x70c3,
+	.name = "pci-6511",
+	.num_di_ports = 8},
 	{
-	      dev_id:	0x70d3,
-	      name:	"pxi-6511",
-      num_di_ports:8},
+	.dev_id = 0x70d3,
+	.name = "pxi-6511",
+	.num_di_ports = 8},
 	{
-	      dev_id:	0x70cc,
-	      name:	"pci-6512",
-      num_do_ports:8},
+	.dev_id = 0x70cc,
+	.name = "pci-6512",
+	.num_do_ports = 8},
 	{
-	      dev_id:	0x70d2,
-	      name:	"pxi-6512",
-      num_do_ports:8},
+	.dev_id = 0x70d2,
+	.name = "pxi-6512",
+	.num_do_ports = 8},
 	{
-	      dev_id:	0x70c8,
-	      name:	"pci-6513",
-	      num_do_ports:8,
-      invert_outputs:1},
+	.dev_id = 0x70c8,
+	.name = "pci-6513",
+	.num_do_ports = 8,
+	.invert_outputs = 1},
 	{
-	      dev_id:	0x70d1,
-	      name:	"pxi-6513",
-	      num_do_ports:8,
-      invert_outputs:1},
+	.dev_id = 0x70d1,
+	.name = "pxi-6513",
+	.num_do_ports = 8,
+	.invert_outputs = 1},
 	{
-	      dev_id:	0x7088,
-	      name:	"pci-6514",
-	      num_di_ports:4,
-	      num_do_ports:4,
-      invert_outputs:1},
+	.dev_id = 0x7088,
+	.name = "pci-6514",
+	.num_di_ports = 4,
+	.num_do_ports = 4,
+	.invert_outputs = 1},
 	{
-	      dev_id:	0x70CD,
-	      name:	"pxi-6514",
-	      num_di_ports:4,
-	      num_do_ports:4,
-      invert_outputs:1},
+	.dev_id = 0x70CD,
+	.name = "pxi-6514",
+	.num_di_ports = 4,
+	.num_do_ports = 4,
+	.invert_outputs = 1},
 	{
-	      dev_id:	0x7087,
-	      name:	"pci-6515",
-	      num_di_ports:4,
-	      num_do_ports:4,
-      invert_outputs:1},
+	.dev_id = 0x7087,
+	.name = "pci-6515",
+	.num_di_ports = 4,
+	.num_do_ports = 4,
+	.invert_outputs = 1},
 	{
-	      dev_id:	0x70c9,
-	      name:	"pxi-6515",
-	      num_di_ports:4,
-	      num_do_ports:4,
-      invert_outputs:1},
+	.dev_id = 0x70c9,
+	.name = "pxi-6515",
+	.num_di_ports = 4,
+	.num_do_ports = 4,
+	.invert_outputs = 1},
 	{
-	      dev_id:	0x7125,
-	      name:	"pci-6516",
-	      num_do_ports:4,
-      invert_outputs:1},
+	.dev_id = 0x7125,
+	.name = "pci-6516",
+	.num_do_ports = 4,
+	.invert_outputs = 1},
 	{
-	      dev_id:	0x7126,
-	      name:	"pci-6517",
-	      num_do_ports:4,
-      invert_outputs:1},
+	.dev_id = 0x7126,
+	.name = "pci-6517",
+	.num_do_ports = 4,
+	.invert_outputs = 1},
 	{
-	      dev_id:	0x7127,
-	      name:	"pci-6518",
-	      num_di_ports:2,
-	      num_do_ports:2,
-      invert_outputs:1},
+	.dev_id = 0x7127,
+	.name = "pci-6518",
+	.num_di_ports = 2,
+	.num_do_ports = 2,
+	.invert_outputs = 1},
 	{
-	      dev_id:	0x7128,
-	      name:	"pci-6519",
-	      num_di_ports:2,
-	      num_do_ports:2,
-      invert_outputs:1},
+	.dev_id = 0x7128,
+	.name = "pci-6519",
+	.num_di_ports = 2,
+	.num_do_ports = 2,
+	.invert_outputs = 1},
 	{
-	      dev_id:	0x71c5,
-	      name:	"pci-6520",
-	      num_di_ports:1,
-	      num_do_ports:1,
+	.dev_id = 0x71c5,
+	.name = "pci-6520",
+	.num_di_ports = 1,
+	.num_do_ports = 1,
 		},
 	{
-	      dev_id:	0x718b,
-	      name:	"pci-6521",
-	      num_di_ports:1,
-	      num_do_ports:1,
+	.dev_id = 0x718b,
+	.name = "pci-6521",
+	.num_di_ports = 1,
+	.num_do_ports = 1,
 		},
 	{
-	      dev_id:	0x718c,
-	      name:	"pxi-6521",
-	      num_di_ports:1,
-	      num_do_ports:1,
+	.dev_id = 0x718c,
+	.name = "pxi-6521",
+	.num_di_ports = 1,
+	.num_do_ports = 1,
 		},
 	{
-	      dev_id:	0x70a9,
-	      name:	"pci-6528",
-	      num_di_ports:3,
-	      num_do_ports:3,
+	.dev_id = 0x70a9,
+	.name = "pci-6528",
+	.num_di_ports = 3,
+	.num_do_ports = 3,
 		},
 	{
-	      dev_id:	0x7086,
-	      name:	"pxi-6528",
-	      num_di_ports:3,
-	      num_do_ports:3,
+	.dev_id = 0x7086,
+	.name = "pxi-6528",
+	.num_di_ports = 3,
+	.num_do_ports = 3,
 		},
 };
 
@@ -249,7 +250,7 @@
 {
 	return channel / ni_65xx_channels_per_port;
 }
-static inline unsigned ni_65xx_total_num_ports(const struct ni_65xx_board * board)
+static inline unsigned ni_65xx_total_num_ports(const struct ni_65xx_board *board)
 {
 	return board->num_dio_ports + board->num_di_ports + board->num_do_ports;
 }
@@ -312,10 +313,10 @@
 	return subdev_private;
 }
 
-static int ni_65xx_find_device(struct comedi_device * dev, int bus, int slot);
+static int ni_65xx_find_device(struct comedi_device *dev, int bus, int slot);
 
-static int ni_65xx_config_filter(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_65xx_config_filter(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	const unsigned chan = CR_CHAN(insn->chanspec);
 	const unsigned port =
@@ -353,8 +354,8 @@
 	return 2;
 }
 
-static int ni_65xx_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_65xx_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned port;
 
@@ -392,8 +393,8 @@
 	return -EINVAL;
 }
 
-static int ni_65xx_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_65xx_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned base_bitfield_channel;
 	const unsigned max_ports_per_bitfield = 5;
@@ -437,12 +438,12 @@
 			writeb(bits,
 				private(dev)->mite->daq_io_addr +
 				Port_Data(port));
-//                      rt_printk("wrote 0x%x to port %i\n", bits, port);
+/* printk("wrote 0x%x to port %i\n", bits, port); */
 		}
 		port_read_bits =
 			readb(private(dev)->mite->daq_io_addr +
 			Port_Data(port));
-//              rt_printk("read 0x%x from port %i\n", port_read_bits, port);
+/* printk("read 0x%x from port %i\n", port_read_bits, port); */
 		if (bitshift > 0) {
 			port_read_bits <<= bitshift;
 		} else {
@@ -454,7 +455,7 @@
 	return insn->n;
 }
 
-static irqreturn_t ni_65xx_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t ni_65xx_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s = dev->subdevices + 2;
@@ -475,8 +476,8 @@
 	return IRQ_HANDLED;
 }
 
-static int ni_65xx_intr_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int ni_65xx_intr_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -551,9 +552,9 @@
 	return 0;
 }
 
-static int ni_65xx_intr_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_65xx_intr_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
-	//struct comedi_cmd *cmd = &s->async->cmd;
+	/* struct comedi_cmd *cmd = &s->async->cmd; */
 
 	writeb(ClrEdge | ClrOverflow,
 		private(dev)->mite->daq_io_addr + Clear_Register);
@@ -564,7 +565,7 @@
 	return 0;
 }
 
-static int ni_65xx_intr_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_65xx_intr_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	writeb(0x00,
 		private(dev)->mite->daq_io_addr + Master_Interrupt_Control);
@@ -572,8 +573,8 @@
 	return 0;
 }
 
-static int ni_65xx_intr_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_65xx_intr_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n < 1)
 		return -EINVAL;
@@ -582,8 +583,8 @@
 	return 2;
 }
 
-static int ni_65xx_intr_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_65xx_intr_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n < 1)
 		return -EINVAL;
@@ -619,7 +620,7 @@
 	return 2;
 }
 
-static int ni_65xx_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int ni_65xx_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned i;
@@ -627,7 +628,8 @@
 
 	printk("comedi%d: ni_65xx:", dev->minor);
 
-	if ((ret = alloc_private(dev, sizeof(struct ni_65xx_private))) < 0)
+	ret = alloc_private(dev, sizeof(struct ni_65xx_private));
+	if (ret < 0)
 		return ret;
 
 	ret = ni_65xx_find_device(dev, it->options[0], it->options[1]);
@@ -647,7 +649,8 @@
 	printk(" ID=0x%02x",
 		readb(private(dev)->mite->daq_io_addr + ID_Register));
 
-	if ((ret = alloc_subdevices(dev, 4)) < 0)
+	ret = alloc_subdevices(dev, 4);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -700,7 +703,7 @@
 			return -ENOMEM;
 		sprivate(s)->base_port = 0;
 		for (i = 0; i < board(dev)->num_dio_ports; ++i) {
-			// configure all ports for input
+			/*  configure all ports for input */
 			writeb(0x1,
 				private(dev)->mite->daq_io_addr +
 				Port_Select(i));
@@ -740,8 +743,8 @@
 	/* Set filter interval to 0  (32bit reg) */
 	writeb(0x00000000, private(dev)->mite->daq_io_addr + Filter_Interval);
 
-	ret = comedi_request_irq(dev->irq, ni_65xx_interrupt, IRQF_SHARED,
-		"ni_65xx", dev);
+	ret = request_irq(dev->irq, ni_65xx_interrupt, IRQF_SHARED,
+			  "ni_65xx", dev);
 	if (ret < 0) {
 		dev->irq = 0;
 		printk(" irq not available");
@@ -752,7 +755,7 @@
 	return 0;
 }
 
-static int ni_65xx_detach(struct comedi_device * dev)
+static int ni_65xx_detach(struct comedi_device *dev)
 {
 	if (private(dev) && private(dev)->mite
 		&& private(dev)->mite->daq_io_addr) {
@@ -762,7 +765,7 @@
 	}
 
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 
 	if (private(dev)) {
@@ -780,7 +783,7 @@
 	return 0;
 }
 
-static int ni_65xx_find_device(struct comedi_device * dev, int bus, int slot)
+static int ni_65xx_find_device(struct comedi_device *dev, int bus, int slot)
 {
 	struct mite_struct *mite;
 	int i;
diff --git a/drivers/staging/comedi/drivers/ni_660x.c b/drivers/staging/comedi/drivers/ni_660x.c
index 14e35ba..11e9b04 100644
--- a/drivers/staging/comedi/drivers/ni_660x.c
+++ b/drivers/staging/comedi/drivers/ni_660x.c
@@ -40,6 +40,7 @@
 
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 #include "mite.h"
 #include "ni_tio.h"
@@ -51,7 +52,7 @@
 };
 
 #define NUM_PFI_CHANNELS 40
-// really there are only up to 3 dma channels, but the register layout allows for 4
+/* really there are only up to 3 dma channels, but the register layout allows for 4 */
 #define MAX_DMA_CHANNEL 4
 
 /* See Register-Level Programmer Manual page 3.1 */
@@ -194,10 +195,10 @@
 
 struct NI_660xRegisterData {
 
-	const char *name;	// Register Name
-	int offset;		// Offset from base address from GPCT chip
+	const char *name;	/*  Register Name */
+	int offset;		/*  Offset from base address from GPCT chip */
 	enum ni_660x_register_direction direction;
-	enum ni_660x_register_width size;	// 1 byte, 2 bytes, or 4 bytes
+	enum ni_660x_register_width size;	/*  1 byte, 2 bytes, or 4 bytes */
 };
 
 
@@ -302,12 +303,12 @@
 	{"IO Config Register 38-39", 0x7A2, NI_660x_READ_WRITE, DATA_2B}
 };
 
-// kind of ENABLE for the second counter
+/* kind of ENABLE for the second counter */
 enum clock_config_register_bits {
 	CounterSwap = 0x1 << 21
 };
 
-// ioconfigreg
+/* ioconfigreg */
 static inline unsigned ioconfig_bitshift(unsigned pfi_channel)
 {
 	if (pfi_channel % 2)
@@ -334,7 +335,7 @@
 	return (input_select & 0x7) << (4 + ioconfig_bitshift(pfi_channel));
 }
 
-// dma configuration register bits
+/* dma configuration register bits */
 static inline unsigned dma_select_mask(unsigned dma_channel)
 {
 	BUG_ON(dma_channel >= MAX_DMA_CHANNEL);
@@ -374,7 +375,7 @@
 	Global_Int_Enable_Bit = 0x80000000
 };
 
-// Offset of the GPCT chips from the base-adress of the card
+/* Offset of the GPCT chips from the base-adress of the card */
 static const unsigned GPCT_OFFSET[2] = { 0x0, 0x800 };	/* First chip is at base-address +
 							   0x00, etc. */
 
@@ -387,24 +388,24 @@
 
 static const struct ni_660x_board ni_660x_boards[] = {
 	{
-	      dev_id:	0x2c60,
-	      name:	"PCI-6601",
-	      n_chips:	1,
+	.dev_id = 0x2c60,
+	.name = "PCI-6601",
+	.n_chips = 1,
 		},
 	{
-	      dev_id:	0x1310,
-	      name:	"PCI-6602",
-	      n_chips:	2,
+	.dev_id = 0x1310,
+	.name = "PCI-6602",
+	.n_chips = 2,
 		},
 	{
-	      dev_id:	0x1360,
-	      name:	"PXI-6602",
-	      n_chips:	2,
+	.dev_id = 0x1360,
+	.name = "PXI-6602",
+	.n_chips = 2,
 		},
 	{
-	      dev_id:	0x2cc0,
-	      name:	"PXI-6608",
-	      n_chips:	2,
+	.dev_id = 0x2cc0,
+	.name = "PXI-6608",
+	.n_chips = 2,
 		},
 };
 
@@ -428,6 +429,8 @@
 	struct mite_dma_descriptor_ring
 	*mite_rings[NI_660X_MAX_NUM_CHIPS][counters_per_chip];
 	spinlock_t mite_channel_lock;
+	/* interrupt_lock prevents races between interrupt and comedi_poll */
+	spinlock_t interrupt_lock;
 	unsigned dma_configuration_soft_copies[NI_660X_MAX_NUM_CHIPS];
 	spinlock_t soft_reg_copy_lock;
 	unsigned short pfi_output_selects[NUM_PFI_CHANNELS];
@@ -446,40 +449,40 @@
 
 #define n_ni_660x_boards (sizeof(ni_660x_boards)/sizeof(ni_660x_boards[0]))
 
-static int ni_660x_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int ni_660x_detach(struct comedi_device * dev);
-static void init_tio_chip(struct comedi_device * dev, int chipset);
-static void ni_660x_select_pfi_output(struct comedi_device * dev, unsigned pfi_channel,
+static int ni_660x_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int ni_660x_detach(struct comedi_device *dev);
+static void init_tio_chip(struct comedi_device *dev, int chipset);
+static void ni_660x_select_pfi_output(struct comedi_device *dev, unsigned pfi_channel,
 	unsigned output_select);
 
 static struct comedi_driver driver_ni_660x = {
-      driver_name:"ni_660x",
-      module:THIS_MODULE,
-      attach:ni_660x_attach,
-      detach:ni_660x_detach,
+	.driver_name = "ni_660x",
+	.module = THIS_MODULE,
+	.attach = ni_660x_attach,
+	.detach = ni_660x_detach,
 };
 
 COMEDI_PCI_INITCLEANUP(driver_ni_660x, ni_660x_pci_table);
 
-static int ni_660x_find_device(struct comedi_device * dev, int bus, int slot);
-static int ni_660x_set_pfi_routing(struct comedi_device * dev, unsigned chan,
+static int ni_660x_find_device(struct comedi_device *dev, int bus, int slot);
+static int ni_660x_set_pfi_routing(struct comedi_device *dev, unsigned chan,
 	unsigned source);
 
 /* Possible instructions for a GPCT */
-static int ni_660x_GPCT_rinsn(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
-static int ni_660x_GPCT_insn_config(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
-static int ni_660x_GPCT_winsn(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
+static int ni_660x_GPCT_rinsn(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
+static int ni_660x_GPCT_insn_config(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
+static int ni_660x_GPCT_winsn(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
 
 /* Possible instructions for Digital IO */
-static int ni_660x_dio_insn_config(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
-static int ni_660x_dio_insn_bits(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
+static int ni_660x_dio_insn_config(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
+static int ni_660x_dio_insn_bits(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
 
-static inline unsigned ni_660x_num_counters(struct comedi_device * dev)
+static inline unsigned ni_660x_num_counters(struct comedi_device *dev)
 {
 	return board(dev)->n_chips * counters_per_chip;
 }
@@ -693,8 +696,8 @@
 		ni_660x_register = G3InterruptEnable;
 		break;
 	default:
-		rt_printk("%s: unhandled register 0x%x in switch.\n",
-			__FUNCTION__, reg);
+		printk("%s: unhandled register 0x%x in switch.\n",
+			__func__, reg);
 		BUG();
 		return 0;
 		break;
@@ -702,7 +705,7 @@
 	return ni_660x_register;
 }
 
-static inline void ni_660x_write_register(struct comedi_device * dev,
+static inline void ni_660x_write_register(struct comedi_device *dev,
 	unsigned chip_index, unsigned bits, enum NI_660x_Register reg)
 {
 	void *const write_address =
@@ -717,14 +720,14 @@
 		writel(bits, write_address);
 		break;
 	default:
-		rt_printk("%s: %s: bug! unhandled case (reg=0x%x) in switch.\n",
-			__FILE__, __FUNCTION__, reg);
+		printk("%s: %s: bug! unhandled case (reg=0x%x) in switch.\n",
+			__FILE__, __func__, reg);
 		BUG();
 		break;
 	}
 }
 
-static inline unsigned ni_660x_read_register(struct comedi_device * dev,
+static inline unsigned ni_660x_read_register(struct comedi_device *dev,
 	unsigned chip_index, enum NI_660x_Register reg)
 {
 	void *const read_address =
@@ -739,8 +742,8 @@
 		return readl(read_address);
 		break;
 	default:
-		rt_printk("%s: %s: bug! unhandled case (reg=0x%x) in switch.\n",
-			__FILE__, __FUNCTION__, reg);
+		printk("%s: %s: bug! unhandled case (reg=0x%x) in switch.\n",
+			__FILE__, __func__, reg);
 		BUG();
 		break;
 	}
@@ -771,11 +774,11 @@
 	return priv->mite_rings[counter->chip_index][counter->counter_index];
 }
 
-static inline void ni_660x_set_dma_channel(struct comedi_device * dev,
+static inline void ni_660x_set_dma_channel(struct comedi_device *dev,
 	unsigned mite_channel, struct ni_gpct *counter)
 {
 	unsigned long flags;
-	comedi_spin_lock_irqsave(&private(dev)->soft_reg_copy_lock, flags);
+	spin_lock_irqsave(&private(dev)->soft_reg_copy_lock, flags);
 	private(dev)->dma_configuration_soft_copies[counter->chip_index] &=
 		~dma_select_mask(mite_channel);
 	private(dev)->dma_configuration_soft_copies[counter->chip_index] |=
@@ -786,14 +789,14 @@
 			chip_index] | dma_reset_bit(mite_channel),
 		DMAConfigRegister);
 	mmiowb();
-	comedi_spin_unlock_irqrestore(&private(dev)->soft_reg_copy_lock, flags);
+	spin_unlock_irqrestore(&private(dev)->soft_reg_copy_lock, flags);
 }
 
-static inline void ni_660x_unset_dma_channel(struct comedi_device * dev,
+static inline void ni_660x_unset_dma_channel(struct comedi_device *dev,
 	unsigned mite_channel, struct ni_gpct *counter)
 {
 	unsigned long flags;
-	comedi_spin_lock_irqsave(&private(dev)->soft_reg_copy_lock, flags);
+	spin_lock_irqsave(&private(dev)->soft_reg_copy_lock, flags);
 	private(dev)->dma_configuration_soft_copies[counter->chip_index] &=
 		~dma_select_mask(mite_channel);
 	private(dev)->dma_configuration_soft_copies[counter->chip_index] |=
@@ -802,22 +805,22 @@
 		private(dev)->dma_configuration_soft_copies[counter->
 			chip_index], DMAConfigRegister);
 	mmiowb();
-	comedi_spin_unlock_irqrestore(&private(dev)->soft_reg_copy_lock, flags);
+	spin_unlock_irqrestore(&private(dev)->soft_reg_copy_lock, flags);
 }
 
-static int ni_660x_request_mite_channel(struct comedi_device * dev,
+static int ni_660x_request_mite_channel(struct comedi_device *dev,
 	struct ni_gpct *counter, enum comedi_io_direction direction)
 {
 	unsigned long flags;
 	struct mite_channel *mite_chan;
 
-	comedi_spin_lock_irqsave(&private(dev)->mite_channel_lock, flags);
+	spin_lock_irqsave(&private(dev)->mite_channel_lock, flags);
 	BUG_ON(counter->mite_chan);
 	mite_chan =
 		mite_request_channel(private(dev)->mite, mite_ring(private(dev),
 			counter));
 	if (mite_chan == NULL) {
-		comedi_spin_unlock_irqrestore(&private(dev)->mite_channel_lock,
+		spin_unlock_irqrestore(&private(dev)->mite_channel_lock,
 			flags);
 		comedi_error(dev,
 			"failed to reserve mite dma channel for counter.");
@@ -826,15 +829,15 @@
 	mite_chan->dir = direction;
 	ni_tio_set_mite_channel(counter, mite_chan);
 	ni_660x_set_dma_channel(dev, mite_chan->channel, counter);
-	comedi_spin_unlock_irqrestore(&private(dev)->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&private(dev)->mite_channel_lock, flags);
 	return 0;
 }
 
-void ni_660x_release_mite_channel(struct comedi_device * dev, struct ni_gpct *counter)
+void ni_660x_release_mite_channel(struct comedi_device *dev, struct ni_gpct *counter)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&private(dev)->mite_channel_lock, flags);
+	spin_lock_irqsave(&private(dev)->mite_channel_lock, flags);
 	if (counter->mite_chan) {
 		struct mite_channel *mite_chan = counter->mite_chan;
 
@@ -842,15 +845,15 @@
 		ni_tio_set_mite_channel(counter, NULL);
 		mite_release_channel(mite_chan);
 	}
-	comedi_spin_unlock_irqrestore(&private(dev)->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&private(dev)->mite_channel_lock, flags);
 }
 
-static int ni_660x_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_660x_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int retval;
 
 	struct ni_gpct *counter = subdev_to_counter(s);
-//      const struct comedi_cmd *cmd = &s->async->cmd;
+/* const struct comedi_cmd *cmd = &s->async->cmd; */
 
 	retval = ni_660x_request_mite_channel(dev, counter, COMEDI_INPUT);
 	if (retval) {
@@ -864,15 +867,15 @@
 	return retval;
 }
 
-static int ni_660x_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int ni_660x_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	struct ni_gpct *counter = subdev_to_counter(s);
 
 	return ni_tio_cmdtest(counter, cmd);
 }
 
-static int ni_660x_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_660x_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct ni_gpct *counter = subdev_to_counter(s);
 	int retval;
@@ -882,7 +885,7 @@
 	return retval;
 }
 
-static void set_tio_counterswap(struct comedi_device * dev, int chipset)
+static void set_tio_counterswap(struct comedi_device *dev, int chipset)
 {
 	/* See P. 3.5 of the Register-Level Programming manual.  The
 	   CounterSwap bit has to be set on the second chip, otherwise
@@ -895,8 +898,8 @@
 		ni_660x_write_register(dev, chipset, 0, ClockConfigRegister);
 }
 
-static void ni_660x_handle_gpct_interrupt(struct comedi_device * dev,
-	struct comedi_subdevice * s)
+static void ni_660x_handle_gpct_interrupt(struct comedi_device *dev,
+	struct comedi_subdevice *s)
 {
 	ni_tio_handle_interrupt(subdev_to_counter(s), s);
 	if (s->async->events) {
@@ -909,23 +912,38 @@
 	}
 }
 
-static irqreturn_t ni_660x_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t ni_660x_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s;
 	unsigned i;
+	unsigned long flags;
 
 	if (dev->attached == 0)
 		return IRQ_NONE;
+	/* lock to avoid race with comedi_poll */
+	spin_lock_irqsave(&private(dev)->interrupt_lock, flags);
 	smp_mb();
 	for (i = 0; i < ni_660x_num_counters(dev); ++i) {
 		s = dev->subdevices + NI_660X_GPCT_SUBDEV(i);
 		ni_660x_handle_gpct_interrupt(dev, s);
 	}
+	spin_unlock_irqrestore(&private(dev)->interrupt_lock, flags);
 	return IRQ_HANDLED;
 }
 
-static int ni_660x_buf_change(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_660x_input_poll(struct comedi_device *dev,
+			      struct comedi_subdevice *s)
+{
+	unsigned long flags;
+	/* lock to avoid race with comedi_poll */
+	spin_lock_irqsave(&private(dev)->interrupt_lock, flags);
+	mite_sync_input_dma(subdev_to_counter(s)->mite_chan, s->async);
+	spin_unlock_irqrestore(&private(dev)->interrupt_lock, flags);
+	return comedi_buf_read_n_available(s->async);
+}
+
+static int ni_660x_buf_change(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long new_size)
 {
 	int ret;
@@ -938,14 +956,17 @@
 	return 0;
 }
 
-static int ni_660x_allocate_private(struct comedi_device * dev)
+static int ni_660x_allocate_private(struct comedi_device *dev)
 {
 	int retval;
 	unsigned i;
 
-	if ((retval = alloc_private(dev, sizeof(struct ni_660x_private))) < 0)
+	retval = alloc_private(dev, sizeof(struct ni_660x_private));
+	if (retval < 0)
 		return retval;
+
 	spin_lock_init(&private(dev)->mite_channel_lock);
+	spin_lock_init(&private(dev)->interrupt_lock);
 	spin_lock_init(&private(dev)->soft_reg_copy_lock);
 	for (i = 0; i < NUM_PFI_CHANNELS; ++i) {
 		private(dev)->pfi_output_selects[i] = pfi_output_select_counter;
@@ -953,7 +974,7 @@
 	return 0;
 }
 
-static int ni_660x_alloc_mite_rings(struct comedi_device * dev)
+static int ni_660x_alloc_mite_rings(struct comedi_device *dev)
 {
 	unsigned i;
 	unsigned j;
@@ -970,7 +991,7 @@
 	return 0;
 }
 
-static void ni_660x_free_mite_rings(struct comedi_device * dev)
+static void ni_660x_free_mite_rings(struct comedi_device *dev)
 {
 	unsigned i;
 	unsigned j;
@@ -982,7 +1003,7 @@
 	}
 }
 
-static int ni_660x_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int ni_660x_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int ret;
@@ -1031,7 +1052,7 @@
 	s->insn_bits = ni_660x_dio_insn_bits;
 	s->insn_config = ni_660x_dio_insn_config;
 	s->io_bits = 0;		/* all bits default to input */
-	// we use the ioconfig registers to control dio direction, so zero output enables in stc dio control reg
+	/*  we use the ioconfig registers to control dio direction, so zero output enables in stc dio control reg */
 	ni_660x_write_register(dev, 0, 0, STCDIOControl);
 
 	private(dev)->counter_dev = ni_gpct_device_construct(dev,
@@ -1055,6 +1076,7 @@
 			s->len_chanlist = 1;
 			s->do_cmdtest = &ni_660x_cmdtest;
 			s->cancel = &ni_660x_cancel;
+			s->poll = &ni_660x_input_poll;
 			s->async_dma_dir = DMA_BIDIRECTIONAL;
 			s->buf_change = &ni_660x_buf_change;
 			s->private = &private(dev)->counter_dev->counters[i];
@@ -1086,9 +1108,9 @@
 	for (i = 0; i < board(dev)->n_chips; ++i) {
 		set_tio_counterswap(dev, i);
 	}
-	if ((ret = comedi_request_irq(mite_irq(private(dev)->mite),
-				&ni_660x_interrupt, IRQF_SHARED, "ni_660x",
-				dev)) < 0) {
+	ret = request_irq(mite_irq(private(dev)->mite), ni_660x_interrupt,
+			  IRQF_SHARED, "ni_660x", dev);
+	if (ret < 0) {
 		printk(" irq not available\n");
 		return ret;
 	}
@@ -1102,13 +1124,13 @@
 	return 0;
 }
 
-static int ni_660x_detach(struct comedi_device * dev)
+static int ni_660x_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: ni_660x: remove\n", dev->minor);
 
 	/* Free irq */
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	if (dev->private) {
 		if (private(dev)->counter_dev)
@@ -1122,17 +1144,17 @@
 }
 
 static int
-ni_660x_GPCT_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+ni_660x_GPCT_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	return ni_tio_rinsn(subdev_to_counter(s), insn, data);
 }
 
-static void init_tio_chip(struct comedi_device * dev, int chipset)
+static void init_tio_chip(struct comedi_device *dev, int chipset)
 {
 	unsigned i;
 
-	// init dma configuration register
+	/*  init dma configuration register */
 	private(dev)->dma_configuration_soft_copies[chipset] = 0;
 	for (i = 0; i < MAX_DMA_CHANNEL; ++i) {
 		private(dev)->dma_configuration_soft_copies[chipset] |=
@@ -1142,26 +1164,26 @@
 	ni_660x_write_register(dev, chipset,
 		private(dev)->dma_configuration_soft_copies[chipset],
 		DMAConfigRegister);
-	for(i = 0; i < NUM_PFI_CHANNELS; ++i)
+	for (i = 0; i < NUM_PFI_CHANNELS; ++i)
 	{
 		ni_660x_write_register(dev, chipset, 0, IOConfigReg(i));
 	}
 }
 
 static int
-ni_660x_GPCT_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+ni_660x_GPCT_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	return ni_tio_insn_config(subdev_to_counter(s), insn, data);
 }
 
-static int ni_660x_GPCT_winsn(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int ni_660x_GPCT_winsn(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	return ni_tio_winsn(subdev_to_counter(s), insn, data);
 }
 
-static int ni_660x_find_device(struct comedi_device * dev, int bus, int slot)
+static int ni_660x_find_device(struct comedi_device *dev, int bus, int slot)
 {
 	struct mite_struct *mite;
 	int i;
@@ -1188,12 +1210,12 @@
 	return -EIO;
 }
 
-static int ni_660x_dio_insn_bits(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int ni_660x_dio_insn_bits(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned base_bitfield_channel = CR_CHAN(insn->chanspec);
 
-	// Check if we have to write some bits
+	/*  Check if we have to write some bits */
 	if (data[0]) {
 		s->state &= ~(data[0] << base_bitfield_channel);
 		s->state |= (data[0] & data[1]) << base_bitfield_channel;
@@ -1208,7 +1230,7 @@
 	return 2;
 }
 
-static void ni_660x_select_pfi_output(struct comedi_device * dev, unsigned pfi_channel,
+static void ni_660x_select_pfi_output(struct comedi_device *dev, unsigned pfi_channel,
 	unsigned output_select)
 {
 	static const unsigned counter_4_7_first_pfi = 8;
@@ -1218,8 +1240,8 @@
 	unsigned active_bits;
 	unsigned idle_bits;
 
-	if(board(dev)->n_chips > 1) {
-		if(output_select == pfi_output_select_counter &&
+	if (board (dev)->n_chips > 1) {
+		if (output_select == pfi_output_select_counter &&
 			pfi_channel >= counter_4_7_first_pfi &&
 			pfi_channel <= counter_4_7_last_pfi) {
 			active_chipset = 1;
@@ -1230,7 +1252,7 @@
 		}
 	}
 
-	if(idle_chipset != active_chipset) {
+	if (idle_chipset != active_chipset) {
 		idle_bits = ni_660x_read_register(dev, idle_chipset, IOConfigReg(pfi_channel));
 		idle_bits &= ~pfi_output_select_mask(pfi_channel);
 		idle_bits |= pfi_output_select_bits(pfi_channel, pfi_output_select_high_Z);
@@ -1243,7 +1265,7 @@
 	ni_660x_write_register(dev, active_chipset, active_bits, IOConfigReg(pfi_channel));
 }
 
-static int ni_660x_set_pfi_routing(struct comedi_device * dev, unsigned chan,
+static int ni_660x_set_pfi_routing(struct comedi_device *dev, unsigned chan,
 	unsigned source)
 {
 	if (source > num_pfi_output_selects)
@@ -1266,13 +1288,13 @@
 	return 0;
 }
 
-static unsigned ni_660x_get_pfi_routing(struct comedi_device * dev, unsigned chan)
+static unsigned ni_660x_get_pfi_routing(struct comedi_device *dev, unsigned chan)
 {
 	BUG_ON(chan >= NUM_PFI_CHANNELS);
 	return private(dev)->pfi_output_selects[chan];
 }
 
-static void ni660x_config_filter(struct comedi_device * dev, unsigned pfi_channel,
+static void ni660x_config_filter(struct comedi_device *dev, unsigned pfi_channel,
 	enum ni_gpct_filter_select filter)
 {
 	unsigned bits = ni_660x_read_register(dev, 0, IOConfigReg(pfi_channel));
@@ -1281,8 +1303,8 @@
 	ni_660x_write_register(dev, 0, bits, IOConfigReg(pfi_channel));
 }
 
-static int ni_660x_dio_insn_config(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int ni_660x_dio_insn_config(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 
diff --git a/drivers/staging/comedi/drivers/ni_670x.c b/drivers/staging/comedi/drivers/ni_670x.c
index d1312e0..71f7d3a 100644
--- a/drivers/staging/comedi/drivers/ni_670x.c
+++ b/drivers/staging/comedi/drivers/ni_670x.c
@@ -41,6 +41,7 @@
 
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include "mite.h"
@@ -69,29 +70,29 @@
 
 static const struct ni_670x_board ni_670x_boards[] = {
 	{
-	      dev_id:	0x2c90,
-	      name:	"PCI-6703",
-	      ao_chans:16,
-	      ao_bits:	16,
+	.dev_id = 0x2c90,
+	.name = "PCI-6703",
+	.ao_chans = 16,
+	.ao_bits = 16,
 		},
 	{
-	      dev_id:	0x1920,
-	      name:	"PXI-6704",
-	      ao_chans:32,
-	      ao_bits:	16,
+	.dev_id = 0x1920,
+	.name = "PXI-6704",
+	.ao_chans = 32,
+	.ao_bits = 16,
 		},
 	{
-	      dev_id:	0x1290,
-	      name:	"PCI-6704",
-	      ao_chans:32,
-	      ao_bits:	16,
+	.dev_id = 0x1290,
+	.name = "PCI-6704",
+	.ao_chans = 32,
+	.ao_bits = 16,
 		},
 };
 
 static DEFINE_PCI_DEVICE_TABLE(ni_670x_pci_table) = {
 	{PCI_VENDOR_ID_NATINST, 0x2c90, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
 	{PCI_VENDOR_ID_NATINST, 0x1920, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
-	//{ PCI_VENDOR_ID_NATINST, 0x0000, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
+	/* { PCI_VENDOR_ID_NATINST, 0x0000, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, */
 	{0}
 };
 
@@ -111,32 +112,32 @@
 #define devpriv ((struct ni_670x_private *)dev->private)
 #define n_ni_670x_boards (sizeof(ni_670x_boards)/sizeof(ni_670x_boards[0]))
 
-static int ni_670x_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int ni_670x_detach(struct comedi_device * dev);
+static int ni_670x_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int ni_670x_detach(struct comedi_device *dev);
 
 static struct comedi_driver driver_ni_670x = {
-      driver_name:"ni_670x",
-      module:THIS_MODULE,
-      attach:ni_670x_attach,
-      detach:ni_670x_detach,
+	.driver_name = "ni_670x",
+	.module = THIS_MODULE,
+	.attach = ni_670x_attach,
+	.detach = ni_670x_detach,
 };
 
 COMEDI_PCI_INITCLEANUP(driver_ni_670x, ni_670x_pci_table);
 
 static struct comedi_lrange range_0_20mA = { 1, {RANGE_mA(0, 20)} };
 
-static int ni_670x_find_device(struct comedi_device * dev, int bus, int slot);
+static int ni_670x_find_device(struct comedi_device *dev, int bus, int slot);
 
-static int ni_670x_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_670x_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_670x_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_670x_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int ni_670x_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_670x_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_670x_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_670x_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int ni_670x_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int ni_670x_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int ret;
@@ -144,7 +145,8 @@
 
 	printk("comedi%d: ni_670x: ", dev->minor);
 
-	if ((ret = alloc_private(dev, sizeof(struct ni_670x_private))) < 0)
+	ret = alloc_private(dev, sizeof(struct ni_670x_private));
+	if (ret < 0)
 		return ret;
 
 	ret = ni_670x_find_device(dev, it->options[0], it->options[1]);
@@ -205,7 +207,7 @@
 	return 1;
 }
 
-static int ni_670x_detach(struct comedi_device * dev)
+static int ni_670x_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: ni_670x: remove\n", dev->minor);
 
@@ -216,13 +218,13 @@
 		mite_unsetup(devpriv->mite);
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	return 0;
 }
 
-static int ni_670x_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_670x_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -247,8 +249,8 @@
 	return i;
 }
 
-static int ni_670x_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_670x_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -259,8 +261,8 @@
 	return i;
 }
 
-static int ni_670x_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_670x_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -281,8 +283,8 @@
 	return 2;
 }
 
-static int ni_670x_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_670x_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 
@@ -308,7 +310,7 @@
 	return insn->n;
 }
 
-static int ni_670x_find_device(struct comedi_device * dev, int bus, int slot)
+static int ni_670x_find_device(struct comedi_device *dev, int bus, int slot)
 {
 	struct mite_struct *mite;
 	int i;
diff --git a/drivers/staging/comedi/drivers/ni_at_a2150.c b/drivers/staging/comedi/drivers/ni_at_a2150.c
index 5d45bf2..45c6809 100644
--- a/drivers/staging/comedi/drivers/ni_at_a2150.c
+++ b/drivers/staging/comedi/drivers/ni_at_a2150.c
@@ -64,6 +64,7 @@
 
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -73,10 +74,10 @@
 #include "comedi_fc.h"
 
 #define A2150_SIZE           28
-#define A2150_DMA_BUFFER_SIZE	0xff00	// size in bytes of dma buffer
+#define A2150_DMA_BUFFER_SIZE	0xff00	/*  size in bytes of dma buffer */
 
-//#define A2150_DEBUG   // enable debugging code
-#undef A2150_DEBUG		// disable debugging code
+/* #define A2150_DEBUG     enable debugging code */
+#undef A2150_DEBUG		/*  disable debugging code */
 
 /* Registers and bits */
 #define CONFIG_REG		0x0
@@ -85,48 +86,48 @@
 #define   CLOCK_SELECT_BITS(x)		(((x) & 0x3) << 3)
 #define   CLOCK_DIVISOR_BITS(x)		(((x) & 0x3) << 5)
 #define   CLOCK_MASK		(0xf << 3)
-#define   ENABLE0_BIT		0x80	// enable (don't internally ground) channels 0 and 1
-#define   ENABLE1_BIT		0x100	// enable (don't internally ground) channels 2 and 3
-#define   AC0_BIT		0x200	// ac couple channels 0,1
-#define   AC1_BIT		0x400	// ac couple channels 2,3
-#define   APD_BIT		0x800	// analog power down
-#define   DPD_BIT		0x1000	// digital power down
-#define TRIGGER_REG		0x2	// trigger config register
+#define   ENABLE0_BIT		0x80	/*  enable (don't internally ground) channels 0 and 1 */
+#define   ENABLE1_BIT		0x100	/*  enable (don't internally ground) channels 2 and 3 */
+#define   AC0_BIT		0x200	/*  ac couple channels 0,1 */
+#define   AC1_BIT		0x400	/*  ac couple channels 2,3 */
+#define   APD_BIT		0x800	/*  analog power down */
+#define   DPD_BIT		0x1000	/*  digital power down */
+#define TRIGGER_REG		0x2	/*  trigger config register */
 #define   POST_TRIGGER_BITS		0x2
 #define   DELAY_TRIGGER_BITS		0x3
-#define   HW_TRIG_EN		0x10	// enable hardware trigger
-#define FIFO_START_REG		0x6	// software start aquistion trigger
-#define FIFO_RESET_REG		0x8	// clears fifo + fifo flags
-#define FIFO_DATA_REG		0xa	// read data
-#define DMA_TC_CLEAR_REG		0xe	// clear dma terminal count interrupt
-#define STATUS_REG		0x12	// read only
-#define   FNE_BIT		0x1	// fifo not empty
-#define   OVFL_BIT		0x8	// fifo overflow
-#define   EDAQ_BIT		0x10	// end of aquisition interrupt
-#define   DCAL_BIT		0x20	// offset calibration in progress
-#define   INTR_BIT		0x40	// interrupt has occured
-#define   DMA_TC_BIT		0x80	// dma terminal count interrupt has occured
+#define   HW_TRIG_EN		0x10	/*  enable hardware trigger */
+#define FIFO_START_REG		0x6	/*  software start aquistion trigger */
+#define FIFO_RESET_REG		0x8	/*  clears fifo + fifo flags */
+#define FIFO_DATA_REG		0xa	/*  read data */
+#define DMA_TC_CLEAR_REG		0xe	/*  clear dma terminal count interrupt */
+#define STATUS_REG		0x12	/*  read only */
+#define   FNE_BIT		0x1	/*  fifo not empty */
+#define   OVFL_BIT		0x8	/*  fifo overflow */
+#define   EDAQ_BIT		0x10	/*  end of aquisition interrupt */
+#define   DCAL_BIT		0x20	/*  offset calibration in progress */
+#define   INTR_BIT		0x40	/*  interrupt has occured */
+#define   DMA_TC_BIT		0x80	/*  dma terminal count interrupt has occured */
 #define   ID_BITS(x)	(((x) >> 8) & 0x3)
-#define IRQ_DMA_CNTRL_REG		0x12	// write only
-#define   DMA_CHAN_BITS(x)		((x) & 0x7)	// sets dma channel
-#define   DMA_EN_BIT		0x8	// enables dma
-#define   IRQ_LVL_BITS(x)		(((x) & 0xf) << 4)	// sets irq level
-#define   FIFO_INTR_EN_BIT		0x100	// enable fifo interrupts
-#define   FIFO_INTR_FHF_BIT		0x200	// interrupt fifo half full
-#define   DMA_INTR_EN_BIT 		0x800	// enable interrupt on dma terminal count
-#define   DMA_DEM_EN_BIT	0x1000	// enables demand mode dma
+#define IRQ_DMA_CNTRL_REG		0x12	/*  write only */
+#define   DMA_CHAN_BITS(x)		((x) & 0x7)	/*  sets dma channel */
+#define   DMA_EN_BIT		0x8	/*  enables dma */
+#define   IRQ_LVL_BITS(x)		(((x) & 0xf) << 4)	/*  sets irq level */
+#define   FIFO_INTR_EN_BIT		0x100	/*  enable fifo interrupts */
+#define   FIFO_INTR_FHF_BIT		0x200	/*  interrupt fifo half full */
+#define   DMA_INTR_EN_BIT 		0x800	/*  enable interrupt on dma terminal count */
+#define   DMA_DEM_EN_BIT	0x1000	/*  enables demand mode dma */
 #define I8253_BASE_REG		0x14
 #define I8253_MODE_REG		0x17
-#define   HW_COUNT_DISABLE		0x30	// disable hardware counting of conversions
+#define   HW_COUNT_DISABLE		0x30	/*  disable hardware counting of conversions */
 
 struct a2150_board {
 	const char *name;
-	int clock[4];		// master clock periods, in nanoseconds
-	int num_clocks;		// number of available master clock speeds
-	int ai_speed;		// maximum conversion rate in nanoseconds
+	int clock[4];		/*  master clock periods, in nanoseconds */
+	int num_clocks;		/*  number of available master clock speeds */
+	int ai_speed;		/*  maximum conversion rate in nanoseconds */
 };
 
-//analog input range
+/* analog input range */
 static const struct comedi_lrange range_a2150 = {
 	1,
 	{
@@ -134,20 +135,20 @@
 		}
 };
 
-// enum must match board indices
+/* enum must match board indices */
 enum { a2150_c, a2150_s };
 static const struct a2150_board a2150_boards[] = {
 	{
-	      name:	"at-a2150c",
-	      clock:	{31250, 22676, 20833, 19531},
-	      num_clocks:4,
-	      ai_speed:19531,
+	.name = "at-a2150c",
+	.clock = {31250, 22676, 20833, 19531},
+	.num_clocks = 4,
+	.ai_speed = 19531,
 		},
 	{
-	      name:	"at-a2150s",
-	      clock:	{62500, 50000, 41667, 0},
-	      num_clocks:3,
-	      ai_speed:41667,
+	.name = "at-a2150s",
+	.clock = {62500, 50000, 41667, 0},
+	.num_clocks = 3,
+	.ai_speed = 41667,
 		},
 };
 
@@ -159,37 +160,37 @@
 struct a2150_private {
 
 	volatile unsigned int count;	/* number of data points left to be taken */
-	unsigned int dma;	// dma channel
-	s16 *dma_buffer;	// dma buffer
-	unsigned int dma_transfer_size;	// size in bytes of dma transfers
-	int irq_dma_bits;	// irq/dma register bits
-	int config_bits;	// config register bits
+	unsigned int dma;	/*  dma channel */
+	s16 *dma_buffer;	/*  dma buffer */
+	unsigned int dma_transfer_size;	/*  size in bytes of dma transfers */
+	int irq_dma_bits;	/*  irq/dma register bits */
+	int config_bits;	/*  config register bits */
 };
 
 
 #define devpriv ((struct a2150_private *)dev->private)
 
-static int a2150_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int a2150_detach(struct comedi_device * dev);
-static int a2150_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
+static int a2150_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int a2150_detach(struct comedi_device *dev);
+static int a2150_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
 
 static struct comedi_driver driver_a2150 = {
-      driver_name:"ni_at_a2150",
-      module:THIS_MODULE,
-      attach:a2150_attach,
-      detach:a2150_detach,
+	.driver_name = "ni_at_a2150",
+	.module = THIS_MODULE,
+	.attach = a2150_attach,
+	.detach = a2150_detach,
 };
 
-static irqreturn_t a2150_interrupt(int irq, void *d PT_REGS_ARG);
-static int a2150_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int a2150_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int a2150_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int a2150_get_timing(struct comedi_device * dev, unsigned int *period,
+static irqreturn_t a2150_interrupt(int irq, void *d);
+static int a2150_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int a2150_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int a2150_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int a2150_get_timing(struct comedi_device *dev, unsigned int *period,
 	int flags);
-static int a2150_probe(struct comedi_device * dev);
-static int a2150_set_chanlist(struct comedi_device * dev, unsigned int start_channel,
+static int a2150_probe(struct comedi_device *dev);
+static int a2150_set_chanlist(struct comedi_device *dev, unsigned int start_channel,
 	unsigned int num_channels);
 /*
  * A convenient macro that defines init_module() and cleanup_module(),
@@ -199,17 +200,17 @@
 
 #ifdef A2150_DEBUG
 
-static void ni_dump_regs(struct comedi_device * dev)
+static void ni_dump_regs(struct comedi_device *dev)
 {
-	rt_printk("config bits 0x%x\n", devpriv->config_bits);
-	rt_printk("irq dma bits 0x%x\n", devpriv->irq_dma_bits);
-	rt_printk("status bits 0x%x\n", inw(dev->iobase + STATUS_REG));
+	printk("config bits 0x%x\n", devpriv->config_bits);
+	printk("irq dma bits 0x%x\n", devpriv->irq_dma_bits);
+	printk("status bits 0x%x\n", inw(dev->iobase + STATUS_REG));
 }
 
 #endif
 
 /* interrupt service routine */
-static irqreturn_t a2150_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t a2150_interrupt(int irq, void *d)
 {
 	int i;
 	int status;
@@ -226,7 +227,7 @@
 		comedi_error(dev, "premature interrupt");
 		return IRQ_HANDLED;
 	}
-	// initialize async here to make sure s is not NULL
+	/*  initialize async here to make sure s is not NULL */
 	async = s->async;
 	async->events = 0;
 	cmd = &async->cmd;
@@ -258,7 +259,7 @@
 	 * count and address get set correctly */
 	clear_dma_ff(devpriv->dma);
 
-	// figure out how many points to read
+	/*  figure out how many points to read */
 	max_points = devpriv->dma_transfer_size / sample_size;
 	/* residue is the number of points left to be done on the dma
 	 * transfer.  It should always be zero at this point unless
@@ -269,7 +270,7 @@
 	if (devpriv->count < num_points && cmd->stop_src == TRIG_COUNT)
 		num_points = devpriv->count;
 
-	// figure out how many points will be stored next time
+	/*  figure out how many points will be stored next time */
 	leftover = 0;
 	if (cmd->stop_src == TRIG_NONE) {
 		leftover = devpriv->dma_transfer_size / sample_size;
@@ -288,7 +289,7 @@
 	for (i = 0; i < num_points; i++) {
 		/* write data point to comedi buffer */
 		dpnt = devpriv->dma_buffer[i];
-		// convert from 2's complement to unsigned coding
+		/*  convert from 2's complement to unsigned coding */
 		dpnt ^= 0x8000;
 		cfc_write_to_buffer(s, dpnt);
 		if (cmd->stop_src == TRIG_COUNT) {
@@ -299,7 +300,7 @@
 			}
 		}
 	}
-	// re-enable  dma
+	/*  re-enable  dma */
 	if (leftover) {
 		set_dma_addr(devpriv->dma, virt_to_bus(devpriv->dma_buffer));
 		set_dma_count(devpriv->dma, leftover * sample_size);
@@ -317,14 +318,14 @@
 	return IRQ_HANDLED;
 }
 
-// probes board type, returns offset
-static int a2150_probe(struct comedi_device * dev)
+/* probes board type, returns offset */
+static int a2150_probe(struct comedi_device *dev)
 {
 	int status = inw(dev->iobase + STATUS_REG);
 	return ID_BITS(status);
 }
 
-static int a2150_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int a2150_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase = it->options[0];
@@ -365,12 +366,12 @@
 
 	/* grab our IRQ */
 	if (irq) {
-		// check that irq is supported
+		/*  check that irq is supported */
 		if (irq < 3 || irq == 8 || irq == 13 || irq > 15) {
 			printk(" invalid irq line %u\n", irq);
 			return -EINVAL;
 		}
-		if (comedi_request_irq(irq, a2150_interrupt, 0,
+		if (request_irq(irq, a2150_interrupt, 0,
 				driver_a2150.driver_name, dev)) {
 			printk("unable to allocate irq %u\n", irq);
 			return -EINVAL;
@@ -378,7 +379,7 @@
 		devpriv->irq_dma_bits |= IRQ_LVL_BITS(irq);
 		dev->irq = irq;
 	}
-	// initialize dma
+	/*  initialize dma */
 	if (dma) {
 		if (dma == 4 || dma > 7) {
 			printk(" invalid dma channel %u\n", dma);
@@ -424,20 +425,20 @@
 	 * prevent hardware count from stopping aquisition */
 	outw(HW_COUNT_DISABLE, dev->iobase + I8253_MODE_REG);
 
-	// set card's irq and dma levels
+	/*  set card's irq and dma levels */
 	outw(devpriv->irq_dma_bits, dev->iobase + IRQ_DMA_CNTRL_REG);
 
-	// reset and sync adc clock circuitry
+	/*  reset and sync adc clock circuitry */
 	outw_p(DPD_BIT | APD_BIT, dev->iobase + CONFIG_REG);
 	outw_p(DPD_BIT, dev->iobase + CONFIG_REG);
-	// initialize configuration register
+	/*  initialize configuration register */
 	devpriv->config_bits = 0;
 	outw(devpriv->config_bits, dev->iobase + CONFIG_REG);
-	// wait until offset calibration is done, then enable analog inputs
+	/*  wait until offset calibration is done, then enable analog inputs */
 	for (i = 0; i < timeout; i++) {
 		if ((DCAL_BIT & inw(dev->iobase + STATUS_REG)) == 0)
 			break;
-		comedi_udelay(1000);
+		udelay(1000);
 	}
 	if (i == timeout) {
 		printk(" timed out waiting for offset calibration to complete\n");
@@ -449,19 +450,19 @@
 	return 0;
 };
 
-static int a2150_detach(struct comedi_device * dev)
+static int a2150_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: %s: remove\n", dev->minor, driver_a2150.driver_name);
 
 	/* only free stuff if it has been allocated by _attach */
 	if (dev->iobase) {
-		// put board in power-down mode
+		/*  put board in power-down mode */
 		outw(APD_BIT | DPD_BIT, dev->iobase + CONFIG_REG);
 		release_region(dev->iobase, A2150_SIZE);
 	}
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	if (devpriv) {
 		if (devpriv->dma)
 			free_dma(devpriv->dma);
@@ -472,23 +473,23 @@
 	return 0;
 };
 
-static int a2150_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int a2150_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
-	// disable dma on card
+	/*  disable dma on card */
 	devpriv->irq_dma_bits &= ~DMA_INTR_EN_BIT & ~DMA_EN_BIT;
 	outw(devpriv->irq_dma_bits, dev->iobase + IRQ_DMA_CNTRL_REG);
 
-	// disable computer's dma
+	/*  disable computer's dma */
 	disable_dma(devpriv->dma);
 
-	// clear fifo and reset triggering circuitry
+	/*  clear fifo and reset triggering circuitry */
 	outw(0, dev->iobase + FIFO_RESET_REG);
 
 	return 0;
 }
 
-static int a2150_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int a2150_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -582,7 +583,7 @@
 	if (err)
 		return 4;
 
-	// check channel/gain list against card's limitations
+	/*  check channel/gain list against card's limitations */
 	if (cmd->chanlist) {
 		startChan = CR_CHAN(cmd->chanlist[0]);
 		for (i = 1; i < cmd->chanlist_len; i++) {
@@ -617,7 +618,7 @@
 	return 0;
 }
 
-static int a2150_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int a2150_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_async *async = s->async;
 	struct comedi_cmd *cmd = &async->cmd;
@@ -635,7 +636,7 @@
 			" dma incompatible with hard real-time interrupt (TRIG_RT), aborting");
 		return -1;
 	}
-	// clear fifo and reset triggering circuitry
+	/*  clear fifo and reset triggering circuitry */
 	outw(0, dev->iobase + FIFO_RESET_REG);
 
 	/* setup chanlist */
@@ -643,7 +644,7 @@
 			cmd->chanlist_len) < 0)
 		return -1;
 
-	// setup ac/dc coupling
+	/*  setup ac/dc coupling */
 	if (CR_AREF(cmd->chanlist[0]) == AREF_OTHER)
 		devpriv->config_bits |= AC0_BIT;
 	else
@@ -653,23 +654,23 @@
 	else
 		devpriv->config_bits &= ~AC1_BIT;
 
-	// setup timing
+	/*  setup timing */
 	a2150_get_timing(dev, &cmd->scan_begin_arg, cmd->flags);
 
-	// send timing, channel, config bits
+	/*  send timing, channel, config bits */
 	outw(devpriv->config_bits, dev->iobase + CONFIG_REG);
 
-	// initialize number of samples remaining
+	/*  initialize number of samples remaining */
 	devpriv->count = cmd->stop_arg * cmd->chanlist_len;
 
-	// enable computer's dma
+	/*  enable computer's dma */
 	lock_flags = claim_dma_lock();
 	disable_dma(devpriv->dma);
 	/* clear flip-flop to make sure 2-byte registers for
 	 * count and address get set correctly */
 	clear_dma_ff(devpriv->dma);
 	set_dma_addr(devpriv->dma, virt_to_bus(devpriv->dma_buffer));
-	// set size of transfer to fill in 1/3 second
+	/*  set size of transfer to fill in 1/3 second */
 #define ONE_THIRD_SECOND 333333333
 	devpriv->dma_transfer_size =
 		sizeof(devpriv->dma_buffer[0]) * cmd->chanlist_len *
@@ -688,36 +689,36 @@
 	 * one spurious interrupt that has been happening */
 	outw(0x00, dev->iobase + DMA_TC_CLEAR_REG);
 
-	// enable dma on card
+	/*  enable dma on card */
 	devpriv->irq_dma_bits |= DMA_INTR_EN_BIT | DMA_EN_BIT;
 	outw(devpriv->irq_dma_bits, dev->iobase + IRQ_DMA_CNTRL_REG);
 
-	// may need to wait 72 sampling periods if timing was changed
+	/*  may need to wait 72 sampling periods if timing was changed */
 	i8254_load(dev->iobase + I8253_BASE_REG, 0, 2, 72, 0);
 
-	// setup start triggering
+	/*  setup start triggering */
 	trigger_bits = 0;
-	// decide if we need to wait 72 periods for valid data
+	/*  decide if we need to wait 72 periods for valid data */
 	if (cmd->start_src == TRIG_NOW &&
 		(old_config_bits & CLOCK_MASK) !=
 		(devpriv->config_bits & CLOCK_MASK)) {
-		// set trigger source to delay trigger
+		/*  set trigger source to delay trigger */
 		trigger_bits |= DELAY_TRIGGER_BITS;
 	} else {
-		// otherwise no delay
+		/*  otherwise no delay */
 		trigger_bits |= POST_TRIGGER_BITS;
 	}
-	// enable external hardware trigger
+	/*  enable external hardware trigger */
 	if (cmd->start_src == TRIG_EXT) {
 		trigger_bits |= HW_TRIG_EN;
 	} else if (cmd->start_src == TRIG_OTHER) {
-		// XXX add support for level/slope start trigger using TRIG_OTHER
+		/*  XXX add support for level/slope start trigger using TRIG_OTHER */
 		comedi_error(dev, "you shouldn't see this?");
 	}
-	// send trigger config bits
+	/*  send trigger config bits */
 	outw(trigger_bits, dev->iobase + TRIGGER_REG);
 
-	// start aquisition for soft trigger
+	/*  start aquisition for soft trigger */
 	if (cmd->start_src == TRIG_NOW) {
 		outw(0, dev->iobase + FIFO_START_REG);
 	}
@@ -728,35 +729,35 @@
 	return 0;
 }
 
-static int a2150_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int a2150_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int i, n;
 	static const int timeout = 100000;
 	static const int filter_delay = 36;
 
-	// clear fifo and reset triggering circuitry
+	/*  clear fifo and reset triggering circuitry */
 	outw(0, dev->iobase + FIFO_RESET_REG);
 
 	/* setup chanlist */
 	if (a2150_set_chanlist(dev, CR_CHAN(insn->chanspec), 1) < 0)
 		return -1;
 
-	// set dc coupling
+	/*  set dc coupling */
 	devpriv->config_bits &= ~AC0_BIT;
 	devpriv->config_bits &= ~AC1_BIT;
 
-	// send timing, channel, config bits
+	/*  send timing, channel, config bits */
 	outw(devpriv->config_bits, dev->iobase + CONFIG_REG);
 
-	// disable dma on card
+	/*  disable dma on card */
 	devpriv->irq_dma_bits &= ~DMA_INTR_EN_BIT & ~DMA_EN_BIT;
 	outw(devpriv->irq_dma_bits, dev->iobase + IRQ_DMA_CNTRL_REG);
 
-	// setup start triggering
+	/*  setup start triggering */
 	outw(0, dev->iobase + TRIGGER_REG);
 
-	// start aquisition for soft trigger
+	/*  start aquisition for soft trigger */
 	outw(0, dev->iobase + FIFO_START_REG);
 
 	/* there is a 35.6 sample delay for data to get through the antialias filter */
@@ -764,7 +765,7 @@
 		for (i = 0; i < timeout; i++) {
 			if (inw(dev->iobase + STATUS_REG) & FNE_BIT)
 				break;
-			comedi_udelay(1);
+			udelay(1);
 		}
 		if (i == timeout) {
 			comedi_error(dev, "timeout");
@@ -773,12 +774,12 @@
 		inw(dev->iobase + FIFO_DATA_REG);
 	}
 
-	// read data
+	/*  read data */
 	for (n = 0; n < insn->n; n++) {
 		for (i = 0; i < timeout; i++) {
 			if (inw(dev->iobase + STATUS_REG) & FNE_BIT)
 				break;
-			comedi_udelay(1);
+			udelay(1);
 		}
 		if (i == timeout) {
 			comedi_error(dev, "timeout");
@@ -789,12 +790,12 @@
 #endif
 		data[n] = inw(dev->iobase + FIFO_DATA_REG);
 #ifdef A2150_DEBUG
-		rt_printk(" data is %i\n", data[n]);
+		printk(" data is %i\n", data[n]);
 #endif
 		data[n] ^= 0x8000;
 	}
 
-	// clear fifo and reset triggering circuitry
+	/*  clear fifo and reset triggering circuitry */
 	outw(0, dev->iobase + FIFO_RESET_REG);
 
 	return n;
@@ -802,14 +803,14 @@
 
 /* sets bits in devpriv->clock_bits to nearest approximation of requested period,
  * adjusts requested period to actual timing. */
-static int a2150_get_timing(struct comedi_device * dev, unsigned int *period,
+static int a2150_get_timing(struct comedi_device *dev, unsigned int *period,
 	int flags)
 {
 	int lub, glb, temp;
 	int lub_divisor_shift, lub_index, glb_divisor_shift, glb_index;
 	int i, j;
 
-	// initialize greatest lower and least upper bounds
+	/*  initialize greatest lower and least upper bounds */
 	lub_divisor_shift = 3;
 	lub_index = 0;
 	lub = thisboard->clock[lub_index] * (1 << lub_divisor_shift);
@@ -817,19 +818,19 @@
 	glb_index = thisboard->num_clocks - 1;
 	glb = thisboard->clock[glb_index] * (1 << glb_divisor_shift);
 
-	// make sure period is in available range
+	/*  make sure period is in available range */
 	if (*period < glb)
 		*period = glb;
 	if (*period > lub)
 		*period = lub;
 
-	// we can multiply period by 1, 2, 4, or 8, using (1 << i)
+	/*  we can multiply period by 1, 2, 4, or 8, using (1 << i) */
 	for (i = 0; i < 4; i++) {
-		// there are a maximum of 4 master clocks
+		/*  there are a maximum of 4 master clocks */
 		for (j = 0; j < thisboard->num_clocks; j++) {
-			// temp is the period in nanosec we are evaluating
+			/*  temp is the period in nanosec we are evaluating */
 			temp = thisboard->clock[j] * (1 << i);
-			// if it is the best match yet
+			/*  if it is the best match yet */
 			if (temp < lub && temp >= *period) {
 				lub_divisor_shift = i;
 				lub_index = j;
@@ -846,7 +847,7 @@
 	switch (flags) {
 	case TRIG_ROUND_NEAREST:
 	default:
-		// if least upper bound is better approximation
+		/*  if least upper bound is better approximation */
 		if (lub - *period < *period - glb) {
 			*period = lub;
 		} else {
@@ -861,7 +862,7 @@
 		break;
 	}
 
-	// set clock bits for config register appropriately
+	/*  set clock bits for config register appropriately */
 	devpriv->config_bits &= ~CLOCK_MASK;
 	if (*period == lub) {
 		devpriv->config_bits |=
@@ -876,7 +877,7 @@
 	return 0;
 }
 
-static int a2150_set_chanlist(struct comedi_device * dev, unsigned int start_channel,
+static int a2150_set_chanlist(struct comedi_device *dev, unsigned int start_channel,
 	unsigned int num_channels)
 {
 	if (start_channel + num_channels > 4)
diff --git a/drivers/staging/comedi/drivers/ni_at_ao.c b/drivers/staging/comedi/drivers/ni_at_ao.c
index 2cc46b6..4e8bf9e 100644
--- a/drivers/staging/comedi/drivers/ni_at_ao.c
+++ b/drivers/staging/comedi/drivers/ni_at_ao.c
@@ -158,12 +158,12 @@
 
 static const struct atao_board atao_boards[] = {
 	{
-	      name:	"ai-ao-6",
-	      n_ao_chans:6,
+	.name = "ai-ao-6",
+	.n_ao_chans = 6,
 		},
 	{
-	      name:	"ai-ao-10",
-	      n_ao_chans:10,
+	.name = "ai-ao-10",
+	.n_ao_chans = 10,
 		},
 };
 
@@ -181,36 +181,36 @@
 
 #define devpriv ((struct atao_private *)dev->private)
 
-static int atao_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int atao_detach(struct comedi_device * dev);
+static int atao_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int atao_detach(struct comedi_device *dev);
 static struct comedi_driver driver_atao = {
-      driver_name:"ni_at_ao",
-      module:THIS_MODULE,
-      attach:atao_attach,
-      detach:atao_detach,
-      board_name:&atao_boards[0].name,
-      offset:sizeof(struct atao_board),
-      num_names:sizeof(atao_boards) / sizeof(struct atao_board),
+	.driver_name = "ni_at_ao",
+	.module = THIS_MODULE,
+	.attach = atao_attach,
+	.detach = atao_detach,
+	.board_name = &atao_boards[0].name,
+	.offset = sizeof(struct atao_board),
+	.num_names = ARRAY_SIZE(atao_boards),
 };
 
 COMEDI_INITCLEANUP(driver_atao);
 
-static void atao_reset(struct comedi_device * dev);
+static void atao_reset(struct comedi_device *dev);
 
-static int atao_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int atao_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int atao_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int atao_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int atao_calib_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int atao_calib_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int atao_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int atao_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int atao_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int atao_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int atao_calib_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int atao_calib_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int atao_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int atao_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase;
@@ -229,7 +229,7 @@
 	}
 	dev->iobase = iobase;
 
-	//dev->board_ptr = atao_probe(dev);
+	/* dev->board_ptr = atao_probe(dev); */
 
 	dev->board_name = thisboard->name;
 
@@ -273,7 +273,7 @@
 
 	s = dev->subdevices + 3;
 	/* eeprom subdevice */
-	//s->type=COMEDI_SUBD_EEPROM;
+	/* s->type=COMEDI_SUBD_EEPROM; */
 	s->type = COMEDI_SUBD_UNUSED;
 
 	atao_reset(dev);
@@ -283,7 +283,7 @@
 	return 0;
 }
 
-static int atao_detach(struct comedi_device * dev)
+static int atao_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: atao: remove\n", dev->minor);
 
@@ -293,7 +293,7 @@
 	return 0;
 }
 
-static void atao_reset(struct comedi_device * dev)
+static void atao_reset(struct comedi_device *dev)
 {
 	/* This is the reset sequence described in the manual */
 
@@ -323,8 +323,8 @@
 	outw(devpriv->cfg1, dev->iobase + ATAO_CFG1);
 }
 
-static int atao_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int atao_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -347,8 +347,8 @@
 	return i;
 }
 
-static int atao_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int atao_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -359,8 +359,8 @@
 	return i;
 }
 
-static int atao_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int atao_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -376,8 +376,8 @@
 	return 2;
 }
 
-static int atao_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int atao_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 	unsigned int mask, bit;
@@ -421,8 +421,8 @@
  * DACs.  It is not explicitly stated in the manual how to access
  * the caldacs, but we can guess.
  */
-static int atao_calib_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int atao_calib_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	for (i = 0; i < insn->n; i++) {
@@ -431,8 +431,8 @@
 	return insn->n;
 }
 
-static int atao_calib_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int atao_calib_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int bitstring, bit;
 	unsigned int chan = CR_CHAN(insn->chanspec);
diff --git a/drivers/staging/comedi/drivers/ni_atmio.c b/drivers/staging/comedi/drivers/ni_atmio.c
index fcc3853..8839447 100644
--- a/drivers/staging/comedi/drivers/ni_atmio.c
+++ b/drivers/staging/comedi/drivers/ni_atmio.c
@@ -93,6 +93,7 @@
 
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/delay.h>
@@ -114,156 +115,156 @@
 
 #define MAX_N_CALDACS 32
 
-static const ni_board ni_boards[] = {
-      {device_id:44,
-	      isapnp_id:0x0000,/* XXX unknown */
-	      name:	"at-mio-16e-1",
-	      n_adchan:16,
-	      adbits:	12,
-	      ai_fifo_depth:8192,
-	      alwaysdither:0,
-	      gainlkup:ai_gain_16,
-	      ai_speed:800,
-	      n_aochan:2,
-	      aobits:	12,
-	      ao_fifo_depth:2048,
+static const struct ni_board_struct ni_boards[] = {
+	{.device_id = 44,
+	.isapnp_id = 0x0000,/* XXX unknown */
+	.name = "at-mio-16e-1",
+	.n_adchan = 16,
+	.adbits = 12,
+	.ai_fifo_depth = 8192,
+	.alwaysdither = 0,
+	.gainlkup = ai_gain_16,
+	.ai_speed = 800,
+	.n_aochan = 2,
+	.aobits = 12,
+	.ao_fifo_depth = 2048,
 			.ao_range_table = &range_ni_E_ao_ext,
-	      ao_unipolar:1,
-	      ao_speed:1000,
-	      has_8255:0,
+	.ao_unipolar = 1,
+	.ao_speed = 1000,
+	.has_8255 = 0,
 			.num_p0_dio_channels = 8,
-	      caldac:	{mb88341},
+	.caldac = {mb88341},
 		},
-      {device_id:25,
-	      isapnp_id:0x1900,
-	      name:	"at-mio-16e-2",
-	      n_adchan:16,
-	      adbits:	12,
-	      ai_fifo_depth:2048,
-	      alwaysdither:0,
-	      gainlkup:ai_gain_16,
-	      ai_speed:2000,
-	      n_aochan:2,
-	      aobits:	12,
-	      ao_fifo_depth:2048,
+	{.device_id = 25,
+	.isapnp_id = 0x1900,
+	.name = "at-mio-16e-2",
+	.n_adchan = 16,
+	.adbits = 12,
+	.ai_fifo_depth = 2048,
+	.alwaysdither = 0,
+	.gainlkup = ai_gain_16,
+	.ai_speed = 2000,
+	.n_aochan = 2,
+	.aobits = 12,
+	.ao_fifo_depth = 2048,
 			.ao_range_table = &range_ni_E_ao_ext,
-	      ao_unipolar:1,
-	      ao_speed:1000,
-	      has_8255:0,
+	.ao_unipolar = 1,
+	.ao_speed = 1000,
+	.has_8255 = 0,
 			.num_p0_dio_channels = 8,
-	      caldac:	{mb88341},
+	.caldac = {mb88341},
 		},
-      {device_id:36,
-	      isapnp_id:0x2400,
-	      name:	"at-mio-16e-10",
-	      n_adchan:16,
-	      adbits:	12,
-	      ai_fifo_depth:512,
-	      alwaysdither:0,
-	      gainlkup:ai_gain_16,
-	      ai_speed:10000,
-	      n_aochan:2,
-	      aobits:	12,
-	      ao_fifo_depth:0,
+	{.device_id = 36,
+	.isapnp_id = 0x2400,
+	.name = "at-mio-16e-10",
+	.n_adchan = 16,
+	.adbits = 12,
+	.ai_fifo_depth = 512,
+	.alwaysdither = 0,
+	.gainlkup = ai_gain_16,
+	.ai_speed = 10000,
+	.n_aochan = 2,
+	.aobits = 12,
+	.ao_fifo_depth = 0,
 			.ao_range_table = &range_ni_E_ao_ext,
-	      ao_unipolar:1,
-	      ao_speed:10000,
+	.ao_unipolar = 1,
+	.ao_speed = 10000,
 			.num_p0_dio_channels = 8,
-	      caldac:	{ad8804_debug},
-	      has_8255:0,
+	.caldac = {ad8804_debug},
+	.has_8255 = 0,
 		},
-      {device_id:37,
-	      isapnp_id:0x2500,
-	      name:	"at-mio-16de-10",
-	      n_adchan:16,
-	      adbits:	12,
-	      ai_fifo_depth:512,
-	      alwaysdither:0,
-	      gainlkup:ai_gain_16,
-	      ai_speed:10000,
-	      n_aochan:2,
-	      aobits:	12,
-	      ao_fifo_depth:0,
+	{.device_id = 37,
+	.isapnp_id = 0x2500,
+	.name = "at-mio-16de-10",
+	.n_adchan = 16,
+	.adbits = 12,
+	.ai_fifo_depth = 512,
+	.alwaysdither = 0,
+	.gainlkup = ai_gain_16,
+	.ai_speed = 10000,
+	.n_aochan = 2,
+	.aobits = 12,
+	.ao_fifo_depth = 0,
 			.ao_range_table = &range_ni_E_ao_ext,
-	      ao_unipolar:1,
-	      ao_speed:10000,
+	.ao_unipolar = 1,
+	.ao_speed = 10000,
 			.num_p0_dio_channels = 8,
-	      caldac:	{ad8804_debug},
-	      has_8255:1,
+	.caldac = {ad8804_debug},
+	.has_8255 = 1,
 		},
-      {device_id:38,
-	      isapnp_id:0x2600,
-	      name:	"at-mio-64e-3",
-	      n_adchan:64,
-	      adbits:	12,
-	      ai_fifo_depth:2048,
-	      alwaysdither:0,
-	      gainlkup:ai_gain_16,
-	      ai_speed:2000,
-	      n_aochan:2,
-	      aobits:	12,
-	      ao_fifo_depth:2048,
+	{.device_id = 38,
+	.isapnp_id = 0x2600,
+	.name = "at-mio-64e-3",
+	.n_adchan = 64,
+	.adbits = 12,
+	.ai_fifo_depth = 2048,
+	.alwaysdither = 0,
+	.gainlkup = ai_gain_16,
+	.ai_speed = 2000,
+	.n_aochan = 2,
+	.aobits = 12,
+	.ao_fifo_depth = 2048,
 			.ao_range_table = &range_ni_E_ao_ext,
-	      ao_unipolar:1,
-	      ao_speed:1000,
-	      has_8255:0,
+	.ao_unipolar = 1,
+	.ao_speed = 1000,
+	.has_8255 = 0,
 			.num_p0_dio_channels = 8,
-	      caldac:	{ad8804_debug},
+	.caldac = {ad8804_debug},
 		},
-      {device_id:39,
-	      isapnp_id:0x2700,
-	      name:	"at-mio-16xe-50",
-	      n_adchan:16,
-	      adbits:	16,
-	      ai_fifo_depth:512,
-	      alwaysdither:1,
-	      gainlkup:ai_gain_8,
-	      ai_speed:50000,
-	      n_aochan:2,
-	      aobits:	12,
-	      ao_fifo_depth:0,
+	{.device_id = 39,
+	.isapnp_id = 0x2700,
+	.name = "at-mio-16xe-50",
+	.n_adchan = 16,
+	.adbits = 16,
+	.ai_fifo_depth = 512,
+	.alwaysdither = 1,
+	.gainlkup = ai_gain_8,
+	.ai_speed = 50000,
+	.n_aochan = 2,
+	.aobits = 12,
+	.ao_fifo_depth = 0,
 			.ao_range_table = &range_bipolar10,
-	      ao_unipolar:0,
-	      ao_speed:50000,
+	.ao_unipolar = 0,
+	.ao_speed = 50000,
 			.num_p0_dio_channels = 8,
-	      caldac:	{dac8800, dac8043},
-	      has_8255:0,
+	.caldac = {dac8800, dac8043},
+	.has_8255 = 0,
 		},
-      {device_id:50,
-	      isapnp_id:0x0000,/* XXX unknown */
-	      name:	"at-mio-16xe-10",
-	      n_adchan:16,
-	      adbits:	16,
-	      ai_fifo_depth:512,
-	      alwaysdither:1,
-	      gainlkup:ai_gain_14,
-	      ai_speed:10000,
-	      n_aochan:2,
-	      aobits:	16,
-	      ao_fifo_depth:2048,
+	{.device_id = 50,
+	.isapnp_id = 0x0000,/* XXX unknown */
+	.name = "at-mio-16xe-10",
+	.n_adchan = 16,
+	.adbits = 16,
+	.ai_fifo_depth = 512,
+	.alwaysdither = 1,
+	.gainlkup = ai_gain_14,
+	.ai_speed = 10000,
+	.n_aochan = 2,
+	.aobits = 16,
+	.ao_fifo_depth = 2048,
 			.ao_range_table = &range_ni_E_ao_ext,
-	      ao_unipolar:1,
-	      ao_speed:1000,
+	.ao_unipolar = 1,
+	.ao_speed = 1000,
 			.num_p0_dio_channels = 8,
-	      caldac:	{dac8800, dac8043, ad8522},
-	      has_8255:0,
+	.caldac = {dac8800, dac8043, ad8522},
+	.has_8255 = 0,
 		},
-      {device_id:51,
-	      isapnp_id:0x0000,/* XXX unknown */
-	      name:	"at-ai-16xe-10",
-	      n_adchan:16,
-	      adbits:	16,
-	      ai_fifo_depth:512,
-	      alwaysdither:1,	/* unknown */
-	      gainlkup:ai_gain_14,
-	      ai_speed:10000,
-	      n_aochan:0,
-	      aobits:	0,
-	      ao_fifo_depth:0,
-	      ao_unipolar:0,
+	{.device_id = 51,
+	.isapnp_id = 0x0000,/* XXX unknown */
+	.name = "at-ai-16xe-10",
+	.n_adchan = 16,
+	.adbits = 16,
+	.ai_fifo_depth = 512,
+	.alwaysdither = 1,	/* unknown */
+	.gainlkup = ai_gain_14,
+	.ai_speed = 10000,
+	.n_aochan = 0,
+	.aobits = 0,
+	.ao_fifo_depth = 0,
+	.ao_unipolar = 0,
 			.num_p0_dio_channels = 8,
-	      caldac:	{dac8800, dac8043, ad8522},
-	      has_8255:0,
+	.caldac = {dac8800, dac8043, ad8522},
+	.has_8255 = 0,
 		}
 };
 
@@ -276,18 +277,19 @@
 
 #define NI_E_IRQ_FLAGS		0
 
-typedef struct {
+struct ni_private {
 	struct pnp_dev *isapnp_dev;
- NI_PRIVATE_COMMON} ni_private;
-#define devpriv ((ni_private *)dev->private)
+	NI_PRIVATE_COMMON
+};
+#define devpriv ((struct ni_private *)dev->private)
 
 /* How we access registers */
 
-#define ni_writel(a,b)		(outl((a),(b)+dev->iobase))
+#define ni_writel(a, b)		(outl((a), (b)+dev->iobase))
 #define ni_readl(a)		(inl((a)+dev->iobase))
-#define ni_writew(a,b)		(outw((a),(b)+dev->iobase))
+#define ni_writew(a, b)		(outw((a), (b)+dev->iobase))
 #define ni_readw(a)		(inw((a)+dev->iobase))
-#define ni_writeb(a,b)		(outb((a),(b)+dev->iobase))
+#define ni_writeb(a, b)		(outb((a), (b)+dev->iobase))
 #define ni_readb(a)		(inb((a)+dev->iobase))
 
 /* How we access windowed registers */
@@ -296,72 +298,72 @@
  * read/written directly in the I/O space of the board.  The
  * AT-MIO devices map the low 8 STC registers to iobase+addr*2. */
 
-static void ni_atmio_win_out(struct comedi_device * dev, uint16_t data, int addr)
+static void ni_atmio_win_out(struct comedi_device *dev, uint16_t data, int addr)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->window_lock, flags);
+	spin_lock_irqsave(&devpriv->window_lock, flags);
 	if ((addr) < 8) {
 		ni_writew(data, addr * 2);
 	} else {
 		ni_writew(addr, Window_Address);
 		ni_writew(data, Window_Data);
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->window_lock, flags);
+	spin_unlock_irqrestore(&devpriv->window_lock, flags);
 }
 
-static uint16_t ni_atmio_win_in(struct comedi_device * dev, int addr)
+static uint16_t ni_atmio_win_in(struct comedi_device *dev, int addr)
 {
 	unsigned long flags;
 	uint16_t ret;
 
-	comedi_spin_lock_irqsave(&devpriv->window_lock, flags);
+	spin_lock_irqsave(&devpriv->window_lock, flags);
 	if (addr < 8) {
 		ret = ni_readw(addr * 2);
 	} else {
 		ni_writew(addr, Window_Address);
 		ret = ni_readw(Window_Data);
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->window_lock, flags);
+	spin_unlock_irqrestore(&devpriv->window_lock, flags);
 
 	return ret;
 }
 
 static struct pnp_device_id device_ids[] = {
-	{.id = "NIC1900",.driver_data = 0},
-	{.id = "NIC2400",.driver_data = 0},
-	{.id = "NIC2500",.driver_data = 0},
-	{.id = "NIC2600",.driver_data = 0},
-	{.id = "NIC2700",.driver_data = 0},
+	{.id = "NIC1900", .driver_data = 0},
+	{.id = "NIC2400", .driver_data = 0},
+	{.id = "NIC2500", .driver_data = 0},
+	{.id = "NIC2600", .driver_data = 0},
+	{.id = "NIC2700", .driver_data = 0},
 	{.id = ""}
 };
 
 MODULE_DEVICE_TABLE(pnp, device_ids);
 
-static int ni_atmio_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int ni_atmio_detach(struct comedi_device * dev);
+static int ni_atmio_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int ni_atmio_detach(struct comedi_device *dev);
 static struct comedi_driver driver_atmio = {
-      driver_name:"ni_atmio",
-      module:THIS_MODULE,
-      attach:ni_atmio_attach,
-      detach:ni_atmio_detach,
+	.driver_name = "ni_atmio",
+	.module = THIS_MODULE,
+	.attach = ni_atmio_attach,
+	.detach = ni_atmio_detach,
 };
 
 COMEDI_INITCLEANUP(driver_atmio);
 
 #include "ni_mio_common.c"
 
-static int ni_getboardtype(struct comedi_device * dev);
+static int ni_getboardtype(struct comedi_device *dev);
 
 /* clean up allocated resources */
-static int ni_atmio_detach(struct comedi_device * dev)
+static int ni_atmio_detach(struct comedi_device *dev)
 {
 	mio_common_detach(dev);
 
 	if (dev->iobase)
 		release_region(dev->iobase, NI_SIZE);
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 	if (devpriv->isapnp_dev)
 		pnp_device_detach(devpriv->isapnp_dev);
@@ -404,7 +406,7 @@
 	return 0;
 }
 
-static int ni_atmio_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int ni_atmio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct pnp_dev *isapnp_dev;
 	int ret;
@@ -413,8 +415,10 @@
 	unsigned int irq;
 
 	/* allocate private area */
-	if ((ret = ni_alloc_private(dev)) < 0)
+	ret = ni_alloc_private(dev);
+	if (ret < 0)
 		return ret;
+
 	devpriv->stc_writew = &ni_atmio_win_out;
 	devpriv->stc_readw = &ni_atmio_win_in;
 	devpriv->stc_writel = &win_out2;
@@ -475,8 +479,10 @@
 			return -EINVAL;
 		}
 		printk(" ( irq = %u )", irq);
-		if ((ret = comedi_request_irq(irq, ni_E_interrupt,
-					NI_E_IRQ_FLAGS, "ni_atmio", dev)) < 0) {
+		ret = request_irq(irq, ni_E_interrupt, NI_E_IRQ_FLAGS,
+				  "ni_atmio", dev);
+
+		if (ret < 0) {
 			printk(" irq not available\n");
 			return -EINVAL;
 		}
@@ -485,14 +491,15 @@
 
 	/* generic E series stuff in ni_mio_common.c */
 
-	if ((ret = ni_E_init(dev, it)) < 0) {
+	ret = ni_E_init(dev, it);
+	if (ret < 0) {
 		return ret;
 	}
 
 	return 0;
 }
 
-static int ni_getboardtype(struct comedi_device * dev)
+static int ni_getboardtype(struct comedi_device *dev)
 {
 	int device_id = ni_read_eeprom(dev, 511);
 	int i;
diff --git a/drivers/staging/comedi/drivers/ni_atmio16d.c b/drivers/staging/comedi/drivers/ni_atmio16d.c
index 35fcd17..1a8c2ab 100644
--- a/drivers/staging/comedi/drivers/ni_atmio16d.c
+++ b/drivers/staging/comedi/drivers/ni_atmio16d.c
@@ -35,6 +35,7 @@
  *
  */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -111,12 +112,12 @@
 
 static const struct atmio16_board_t atmio16_boards[] = {
 	{
-	      name:	"atmio16",
-	      has_8255:0,
+	.name = "atmio16",
+	.has_8255 = 0,
 		},
 	{
-	      name:	"atmio16d",
-	      has_8255:1,
+	.name = "atmio16d",
+	.has_8255 = 1,
 		},
 };
 
@@ -125,25 +126,25 @@
 #define boardtype ((const struct atmio16_board_t *)dev->board_ptr)
 
 /* function prototypes */
-static int atmio16d_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int atmio16d_detach(struct comedi_device * dev);
-static irqreturn_t atmio16d_interrupt(int irq, void *d PT_REGS_ARG);
-static int atmio16d_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int atmio16d_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int atmio16d_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static void reset_counters(struct comedi_device * dev);
-static void reset_atmio16d(struct comedi_device * dev);
+static int atmio16d_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int atmio16d_detach(struct comedi_device *dev);
+static irqreturn_t atmio16d_interrupt(int irq, void *d);
+static int atmio16d_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int atmio16d_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int atmio16d_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static void reset_counters(struct comedi_device *dev);
+static void reset_atmio16d(struct comedi_device *dev);
 
 /* main driver struct */
 static struct comedi_driver driver_atmio16d = {
-      driver_name:"atmio16",
-      module:THIS_MODULE,
-      attach:atmio16d_attach,
-      detach:atmio16d_detach,
-      board_name:&atmio16_boards[0].name,
-      num_names:n_atmio16_boards,
-      offset:sizeof(struct atmio16_board_t),
+	.driver_name = "atmio16",
+	.module = THIS_MODULE,
+	.attach = atmio16d_attach,
+	.detach = atmio16d_detach,
+	.board_name = &atmio16_boards[0].name,
+	.num_names = n_atmio16_boards,
+	.offset = sizeof(struct atmio16_board_t),
 };
 
 COMEDI_INITCLEANUP(driver_atmio16d);
@@ -187,7 +188,7 @@
 	unsigned int com_reg_2_state;	/* current state of command register 2 */
 };
 
-static void reset_counters(struct comedi_device * dev)
+static void reset_counters(struct comedi_device *dev)
 {
 	/* Counter 2 */
 	outw(0xFFC2, dev->iobase + AM9513A_COM_REG);
@@ -225,7 +226,7 @@
 	outw(0, dev->iobase + AD_CLEAR_REG);
 }
 
-static void reset_atmio16d(struct comedi_device * dev)
+static void reset_atmio16d(struct comedi_device *dev)
 {
 	int i;
 
@@ -257,12 +258,12 @@
 	outw(2048, dev->iobase + DAC1_REG);
 }
 
-static irqreturn_t atmio16d_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t atmio16d_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s = dev->subdevices + 0;
 
-//      printk("atmio16d_interrupt!\n");
+/* printk("atmio16d_interrupt!\n"); */
 
 	comedi_buf_put(s->async, inw(dev->iobase + AD_FIFO_REG));
 
@@ -270,8 +271,8 @@
 	return IRQ_HANDLED;
 }
 
-static int atmio16d_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int atmio16d_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0, tmp;
 #ifdef DEBUG1
@@ -371,7 +372,7 @@
 	return 0;
 }
 
-static int atmio16d_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int atmio16d_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	unsigned int timer, base_clock;
@@ -417,10 +418,10 @@
 	} else if (cmd->convert_arg < 655360000) {
 		base_clock = CLOCK_100_KHZ;
 		timer = cmd->convert_arg / 10000;
-	} else if (cmd->convert_arg <= 0xffffffff /* 6553600000 */ ) {
+	} else if (cmd->convert_arg <= 0xffffffff /* 6553600000 */) {
 		base_clock = CLOCK_10_KHZ;
 		timer = cmd->convert_arg / 100000;
-	} else if (cmd->convert_arg <= 0xffffffff /* 65536000000 */ ) {
+	} else if (cmd->convert_arg <= 0xffffffff /* 65536000000 */) {
 		base_clock = CLOCK_1_KHZ;
 		timer = cmd->convert_arg / 1000000;
 	}
@@ -449,11 +450,13 @@
 		outw(devpriv->com_reg_1_state, dev->iobase + COM_REG_1);
 	} else {
 		/* Counter 4 and 5 are needed */
-		if ((tmp = sample_count & 0xFFFF)) {
+
+		tmp = sample_count & 0xFFFF;
+		if (tmp)
 			outw(tmp - 1, dev->iobase + AM9513A_DATA_REG);
-		} else {
+		else
 			outw(0xFFFF, dev->iobase + AM9513A_DATA_REG);
-		}
+
 		outw(0xFF48, dev->iobase + AM9513A_COM_REG);
 		outw(0, dev->iobase + AM9513A_DATA_REG);
 		outw(0xFF28, dev->iobase + AM9513A_COM_REG);
@@ -483,10 +486,10 @@
 		} else if (cmd->scan_begin_arg < 655360000) {
 			base_clock = CLOCK_100_KHZ;
 			timer = cmd->scan_begin_arg / 10000;
-		} else if (cmd->scan_begin_arg < 0xffffffff /* 6553600000 */ ) {
+		} else if (cmd->scan_begin_arg < 0xffffffff /* 6553600000 */) {
 			base_clock = CLOCK_10_KHZ;
 			timer = cmd->scan_begin_arg / 100000;
-		} else if (cmd->scan_begin_arg < 0xffffffff /* 65536000000 */ ) {
+		} else if (cmd->scan_begin_arg < 0xffffffff /* 65536000000 */) {
 			base_clock = CLOCK_1_KHZ;
 			timer = cmd->scan_begin_arg / 1000000;
 		}
@@ -519,7 +522,7 @@
 }
 
 /* This will cancel a running acquisition operation */
-static int atmio16d_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int atmio16d_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	reset_atmio16d(dev);
 
@@ -527,8 +530,8 @@
 }
 
 /* Mode 0 is used to get a single conversion on demand */
-static int atmio16d_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int atmio16d_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, t;
 	int chan;
@@ -542,9 +545,9 @@
 	gain = CR_RANGE(insn->chanspec);
 
 	/* reset the Analog input circuitry */
-	//outw( 0, dev->iobase+AD_CLEAR_REG );
+	/* outw( 0, dev->iobase+AD_CLEAR_REG ); */
 	/* reset the Analog Input MUX Counter to 0 */
-	//outw( 0, dev->iobase+MUX_CNTR_REG );
+	/* outw( 0, dev->iobase+MUX_CNTR_REG ); */
 
 	/* set the Input MUX gain */
 	outw(chan | (gain << 6), dev->iobase + MUX_GAIN_REG);
@@ -577,7 +580,7 @@
 		}
 		/* end waiting, now check if it timed out */
 		if (t == ATMIO16D_TIMEOUT) {
-			rt_printk("atmio16d: timeout\n");
+			printk("atmio16d: timeout\n");
 
 			return -ETIME;
 		}
@@ -586,8 +589,8 @@
 	return i;
 }
 
-static int atmio16d_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int atmio16d_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 #ifdef DEBUG1
@@ -601,8 +604,8 @@
 	return i;
 }
 
-static int atmio16d_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int atmio16d_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan;
@@ -636,8 +639,8 @@
 	return i;
 }
 
-static int atmio16d_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int atmio16d_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -652,8 +655,8 @@
 	return 2;
 }
 
-static int atmio16d_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int atmio16d_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int mask;
@@ -706,7 +709,7 @@
    options[12] - dac1 coding
  */
 
-static int atmio16d_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int atmio16d_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	unsigned int irq;
 	unsigned long iobase;
@@ -726,9 +729,12 @@
 	/* board name */
 	dev->board_name = boardtype->name;
 
-	if ((ret = alloc_subdevices(dev, 4)) < 0)
+	ret = alloc_subdevices(dev, 4);
+	if (ret < 0)
 		return ret;
-	if ((ret = alloc_private(dev, sizeof(struct atmio16d_private))) < 0)
+
+	ret = alloc_private(dev, sizeof(struct atmio16d_private));
+	if (ret < 0)
 		return ret;
 
 	/* reset the atmio16d hardware */
@@ -737,8 +743,9 @@
 	/* check if our interrupt is available and get it */
 	irq = it->options[1];
 	if (irq) {
-		if ((ret = comedi_request_irq(irq, atmio16d_interrupt,
-					0, "atmio16d", dev)) < 0) {
+
+		ret = request_irq(irq, atmio16d_interrupt, 0, "atmio16d", dev);
+		if (ret < 0) {
 			printk("failed to allocate irq %u\n", irq);
 			return ret;
 		}
@@ -841,7 +848,7 @@
 	return 0;
 }
 
-static int atmio16d_detach(struct comedi_device * dev)
+static int atmio16d_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: atmio16d: remove\n", dev->minor);
 
@@ -849,7 +856,7 @@
 		subdev_8255_cleanup(dev, dev->subdevices + 3);
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	reset_atmio16d(dev);
 
diff --git a/drivers/staging/comedi/drivers/ni_daq_700.c b/drivers/staging/comedi/drivers/ni_daq_700.c
index 61a31ad..e349482 100644
--- a/drivers/staging/comedi/drivers/ni_daq_700.c
+++ b/drivers/staging/comedi/drivers/ni_daq_700.c
@@ -41,6 +41,7 @@
 IRQ is assigned but not used.
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -53,36 +54,36 @@
 
 static struct pcmcia_device *pcmcia_cur_dev = NULL;
 
-#define DIO700_SIZE 8		// size of io region used by board
+#define DIO700_SIZE 8		/*  size of io region used by board */
 
-static int dio700_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dio700_detach(struct comedi_device * dev);
+static int dio700_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dio700_detach(struct comedi_device *dev);
 
 enum dio700_bustype { pcmcia_bustype };
 
 struct dio700_board {
 	const char *name;
-	int device_id;		// device id for pcmcia board
-	enum dio700_bustype bustype;	// PCMCIA
-	int have_dio;		// have daqcard-700 dio
-	// function pointers so we can use inb/outb or readb/writeb
-	// as appropriate
+	int device_id;		/*  device id for pcmcia board */
+	enum dio700_bustype bustype;	/*  PCMCIA */
+	int have_dio;		/*  have daqcard-700 dio */
+	/*  function pointers so we can use inb/outb or readb/writeb */
+	/*  as appropriate */
 	unsigned int (*read_byte) (unsigned int address);
 	void (*write_byte) (unsigned int byte, unsigned int address);
 };
 
 static const struct dio700_board dio700_boards[] = {
 	{
-	      name:	"daqcard-700",
-	      device_id:0x4743,// 0x10b is manufacturer id, 0x4743 is device id
-	      bustype:	pcmcia_bustype,
-	      have_dio:1,
+	.name = "daqcard-700",
+	.device_id = 0x4743,/*  0x10b is manufacturer id, 0x4743 is device id */
+	.bustype = pcmcia_bustype,
+	.have_dio = 1,
 		},
 	{
-	      name:	"ni_daq_700",
-	      device_id:0x4743,// 0x10b is manufacturer id, 0x4743 is device id
-	      bustype:	pcmcia_bustype,
-	      have_dio:1,
+	.name = "ni_daq_700",
+	.device_id = 0x4743,/*  0x10b is manufacturer id, 0x4743 is device id */
+	.bustype = pcmcia_bustype,
+	.have_dio = 1,
 		},
 };
 
@@ -100,13 +101,13 @@
 #define devpriv ((struct dio700_private *)dev->private)
 
 static struct comedi_driver driver_dio700 = {
-      driver_name:"ni_daq_700",
-      module:THIS_MODULE,
-      attach:dio700_attach,
-      detach:dio700_detach,
-      num_names:sizeof(dio700_boards) / sizeof(struct dio700_board),
-      board_name:&dio700_boards[0].name,
-      offset:sizeof(struct dio700_board),
+	.driver_name = "ni_daq_700",
+	.module = THIS_MODULE,
+	.attach = dio700_attach,
+	.detach = dio700_detach,
+	.num_names = ARRAY_SIZE(dio700_boards),
+	.board_name = &dio700_boards[0].name,
+	.offset = sizeof(struct dio700_board),
 };
 
 /*	the real driver routines	*/
@@ -128,9 +129,9 @@
 #define CALLBACK_FUNC	(((struct subdev_700_struct *)s->private)->cb_func)
 #define subdevpriv	((struct subdev_700_struct *)s->private)
 
-static void do_config(struct comedi_device * dev, struct comedi_subdevice * s);
+static void do_config(struct comedi_device *dev, struct comedi_subdevice *s);
 
-void subdev_700_interrupt(struct comedi_device * dev, struct comedi_subdevice * s)
+void subdev_700_interrupt(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	short d;
 
@@ -155,8 +156,8 @@
 	}
 }
 
-static int subdev_700_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int subdev_700_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (data[0]) {
 		s->state &= ~data[0];
@@ -173,8 +174,8 @@
 	return 2;
 }
 
-static int subdev_700_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int subdev_700_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 
 	switch (data[0]) {
@@ -196,13 +197,13 @@
 	return 1;
 }
 
-static void do_config(struct comedi_device * dev, struct comedi_subdevice * s)
+static void do_config(struct comedi_device *dev, struct comedi_subdevice *s)
 {				/* use powerup defaults */
 	return;
 }
 
-static int subdev_700_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int subdev_700_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	unsigned int tmp;
@@ -276,21 +277,21 @@
 	return 0;
 }
 
-static int subdev_700_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int subdev_700_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	/* FIXME */
 
 	return 0;
 }
 
-static int subdev_700_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int subdev_700_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	/* FIXME */
 
 	return 0;
 }
 
-int subdev_700_init(struct comedi_device * dev, struct comedi_subdevice * s, int (*cb) (int,
+int subdev_700_init(struct comedi_device *dev, struct comedi_subdevice *s, int (*cb) (int,
 		int, int, unsigned long), unsigned long arg)
 {
 	s->type = COMEDI_SUBD_DIO;
@@ -319,7 +320,7 @@
 	return 0;
 }
 
-int subdev_700_init_irq(struct comedi_device * dev, struct comedi_subdevice * s,
+int subdev_700_init_irq(struct comedi_device *dev, struct comedi_subdevice *s,
 	int (*cb) (int, int, int, unsigned long), unsigned long arg)
 {
 	int ret;
@@ -337,7 +338,7 @@
 	return 0;
 }
 
-void subdev_700_cleanup(struct comedi_device * dev, struct comedi_subdevice * s)
+void subdev_700_cleanup(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	if (s->private) {
 		if (subdevpriv->have_irq) {
@@ -352,7 +353,7 @@
 EXPORT_SYMBOL(subdev_700_cleanup);
 EXPORT_SYMBOL(subdev_700_interrupt);
 
-static int dio700_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dio700_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase = 0;
@@ -365,7 +366,7 @@
 	if (alloc_private(dev, sizeof(struct dio700_private)) < 0)
 		return -ENOMEM;
 
-	// get base address, irq etc. based on bustype
+	/*  get base address, irq etc. based on bustype */
 	switch (thisboard->bustype) {
 	case pcmcia_bustype:
 		link = pcmcia_cur_dev;	/* XXX hack */
@@ -415,7 +416,7 @@
 	return 0;
 };
 
-static int dio700_detach(struct comedi_device * dev)
+static int dio700_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: ni_daq_700: cs-remove\n", dev->minor);
 
@@ -425,12 +426,12 @@
 	if (thisboard->bustype != pcmcia_bustype && dev->iobase)
 		release_region(dev->iobase, DIO700_SIZE);
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	return 0;
 };
 
-// PCMCIA crap
+/* PCMCIA crap */
 
 /*
    All the PCMCIA modules use PCMCIA_DEBUG to control debugging.  If
@@ -594,15 +595,21 @@
 	tuple.TupleData = buf;
 	tuple.TupleDataMax = sizeof(buf);
 	tuple.TupleOffset = 0;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple)) != 0) {
+
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret) {
 		cs_error(link, GetFirstTuple, last_ret);
 		goto cs_failed;
 	}
-	if ((last_ret = pcmcia_get_tuple_data(link, &tuple)) != 0) {
+
+	last_ret = pcmcia_get_tuple_data(link, &tuple);
+	if (last_ret) {
 		cs_error(link, GetTupleData, last_ret);
 		goto cs_failed;
 	}
-	if ((last_ret = pcmcia_parse_tuple(&tuple, &parse)) != 0) {
+
+	last_ret = pcmcia_parse_tuple(&tuple, &parse);
+	 if (last_ret) {
 		cs_error(link, ParseTuple, last_ret);
 		goto cs_failed;
 	}
@@ -622,7 +629,8 @@
 	   will only use the CIS to fill in implementation-defined details.
 	 */
 	tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple)) != 0) {
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret != 0) {
 		cs_error(link, GetFirstTuple, last_ret);
 		goto cs_failed;
 	}
@@ -692,7 +700,9 @@
 		break;
 
 	      next_entry:
-		if ((last_ret = pcmcia_get_next_tuple(link, &tuple)) != 0) {
+
+		last_ret = pcmcia_get_next_tuple(link, &tuple);
+		if (last_ret) {
 			cs_error(link, GetNextTuple, last_ret);
 			goto cs_failed;
 		}
@@ -703,18 +713,21 @@
 	   handler to the interrupt, unless the 'Handler' member of the
 	   irq structure is initialized.
 	 */
-	if (link->conf.Attributes & CONF_ENABLE_IRQ)
-		if ((last_ret = pcmcia_request_irq(link, &link->irq)) != 0) {
+	if (link->conf.Attributes & CONF_ENABLE_IRQ) {
+		last_ret = pcmcia_request_irq(link, &link->irq);
+		if (last_ret) {
 			cs_error(link, RequestIRQ, last_ret);
 			goto cs_failed;
 		}
+	}
 
 	/*
 	   This actually configures the PCMCIA socket -- setting up
 	   the I/O windows and the interrupt mapping, and putting the
 	   card and host interface into "Memory and IO" mode.
 	 */
-	if ((last_ret = pcmcia_request_configuration(link, &link->conf)) != 0) {
+	last_ret = pcmcia_request_configuration(link, &link->conf);
+	if (last_ret != 0) {
 		cs_error(link, RequestConfiguration, last_ret);
 		goto cs_failed;
 	}
diff --git a/drivers/staging/comedi/drivers/ni_daq_dio24.c b/drivers/staging/comedi/drivers/ni_daq_dio24.c
index daec5c4..a8ac02f 100644
--- a/drivers/staging/comedi/drivers/ni_daq_dio24.c
+++ b/drivers/staging/comedi/drivers/ni_daq_dio24.c
@@ -37,9 +37,10 @@
 the PCMCIA interface.
 */
 
-//#define LABPC_DEBUG   // enable debugging messages
+/* #define LABPC_DEBUG */   /*  enable debugging messages */
 #undef LABPC_DEBUG
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -54,42 +55,42 @@
 
 static struct pcmcia_device *pcmcia_cur_dev = NULL;
 
-#define DIO24_SIZE 4		// size of io region used by board
+#define DIO24_SIZE 4		/*  size of io region used by board */
 
-static int dio24_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dio24_detach(struct comedi_device * dev);
+static int dio24_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dio24_detach(struct comedi_device *dev);
 
 enum dio24_bustype { pcmcia_bustype };
 
-typedef struct dio24_board_struct {
+struct dio24_board_struct {
 	const char *name;
-	int device_id;		// device id for pcmcia board
-	enum dio24_bustype bustype;	// PCMCIA
-	int have_dio;		// have 8255 chip
-	// function pointers so we can use inb/outb or readb/writeb as appropriate
+	int device_id;		/*  device id for pcmcia board */
+	enum dio24_bustype bustype;	/*  PCMCIA */
+	int have_dio;		/*  have 8255 chip */
+	/*  function pointers so we can use inb/outb or readb/writeb as appropriate */
 	unsigned int (*read_byte) (unsigned int address);
 	void (*write_byte) (unsigned int byte, unsigned int address);
-} dio24_board;
+};
 
-static const dio24_board dio24_boards[] = {
+static const struct dio24_board_struct dio24_boards[] = {
 	{
-	      name:	"daqcard-dio24",
-	      device_id:0x475c,// 0x10b is manufacturer id, 0x475c is device id
-	      bustype:	pcmcia_bustype,
-	      have_dio:1,
+	.name = "daqcard-dio24",
+	.device_id = 0x475c,/*  0x10b is manufacturer id, 0x475c is device id */
+	.bustype = pcmcia_bustype,
+	.have_dio = 1,
 		},
 	{
-	      name:	"ni_daq_dio24",
-	      device_id:0x475c,// 0x10b is manufacturer id, 0x475c is device id
-	      bustype:	pcmcia_bustype,
-	      have_dio:1,
+	.name = "ni_daq_dio24",
+	.device_id = 0x475c,/*  0x10b is manufacturer id, 0x475c is device id */
+	.bustype = pcmcia_bustype,
+	.have_dio = 1,
 		},
 };
 
 /*
  * Useful for shorthand access to the particular board structure
  */
-#define thisboard ((const dio24_board *)dev->board_ptr)
+#define thisboard ((const struct dio24_board_struct *)dev->board_ptr)
 
 struct dio24_private {
 
@@ -100,16 +101,16 @@
 #define devpriv ((struct dio24_private *)dev->private)
 
 static struct comedi_driver driver_dio24 = {
-      driver_name:"ni_daq_dio24",
-      module:THIS_MODULE,
-      attach:dio24_attach,
-      detach:dio24_detach,
-      num_names:sizeof(dio24_boards) / sizeof(dio24_board),
-      board_name:&dio24_boards[0].name,
-      offset:sizeof(dio24_board),
+	.driver_name = "ni_daq_dio24",
+	.module = THIS_MODULE,
+	.attach = dio24_attach,
+	.detach = dio24_detach,
+	.num_names = ARRAY_SIZE(dio24_boards),
+	.board_name = &dio24_boards[0].name,
+	.offset = sizeof(struct dio24_board_struct),
 };
 
-static int dio24_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dio24_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase = 0;
@@ -122,7 +123,7 @@
 	if (alloc_private(dev, sizeof(struct dio24_private)) < 0)
 		return -ENOMEM;
 
-	// get base address, irq etc. based on bustype
+	/*  get base address, irq etc. based on bustype */
 	switch (thisboard->bustype) {
 	case pcmcia_bustype:
 		link = pcmcia_cur_dev;	/* XXX hack */
@@ -172,7 +173,7 @@
 	return 0;
 };
 
-static int dio24_detach(struct comedi_device * dev)
+static int dio24_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: ni_daq_dio24: remove\n", dev->minor);
 
@@ -182,12 +183,12 @@
 	if (thisboard->bustype != pcmcia_bustype && dev->iobase)
 		release_region(dev->iobase, DIO24_SIZE);
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	return 0;
 };
 
-// PCMCIA crap
+/* PCMCIA crap */
 
 /*
    All the PCMCIA modules use PCMCIA_DEBUG to control debugging.  If
@@ -236,12 +237,12 @@
 
 static const dev_info_t dev_info = "ni_daq_dio24";
 
-typedef struct local_info_t {
+struct local_info_t {
 	struct pcmcia_device *link;
 	dev_node_t node;
 	int stop;
 	struct bus_operations *bus;
-} local_info_t;
+};
 
 /*======================================================================
 
@@ -257,14 +258,14 @@
 
 static int dio24_cs_attach(struct pcmcia_device *link)
 {
-	local_info_t *local;
+	struct local_info_t *local;
 
 	printk(KERN_INFO "ni_daq_dio24: HOLA SOY YO - CS-attach!\n");
 
 	DEBUG(0, "dio24_cs_attach()\n");
 
 	/* Allocate space for private device-specific data */
-	local = kzalloc(sizeof(local_info_t), GFP_KERNEL);
+	local = kzalloc(sizeof(struct local_info_t), GFP_KERNEL);
 	if (!local)
 		return -ENOMEM;
 	local->link = link;
@@ -309,7 +310,7 @@
 	DEBUG(0, "dio24_cs_detach(0x%p)\n", link);
 
 	if (link->dev_node) {
-		((local_info_t *) link->priv)->stop = 1;
+		((struct local_info_t *) link->priv)->stop = 1;
 		dio24_release(link);
 	}
 
@@ -329,7 +330,7 @@
 
 static void dio24_config(struct pcmcia_device *link)
 {
-	local_info_t *dev = link->priv;
+	struct local_info_t *dev = link->priv;
 	tuple_t tuple;
 	cisparse_t parse;
 	int last_ret;
@@ -351,15 +352,21 @@
 	tuple.TupleData = buf;
 	tuple.TupleDataMax = sizeof(buf);
 	tuple.TupleOffset = 0;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple)) != 0) {
+
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret) {
 		cs_error(link, GetFirstTuple, last_ret);
 		goto cs_failed;
 	}
-	if ((last_ret = pcmcia_get_tuple_data(link, &tuple)) != 0) {
+
+	last_ret = pcmcia_get_tuple_data(link, &tuple);
+	if (last_ret) {
 		cs_error(link, GetTupleData, last_ret);
 		goto cs_failed;
 	}
-	if ((last_ret = pcmcia_parse_tuple(&tuple, &parse)) != 0) {
+
+	last_ret = pcmcia_parse_tuple(&tuple, &parse);
+	if (last_ret) {
 		cs_error(link, ParseTuple, last_ret);
 		goto cs_failed;
 	}
@@ -379,7 +386,9 @@
 	   will only use the CIS to fill in implementation-defined details.
 	 */
 	tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple)) != 0) {
+
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret) {
 		cs_error(link, GetFirstTuple, last_ret);
 		goto cs_failed;
 	}
@@ -449,7 +458,9 @@
 		break;
 
 	      next_entry:
-		if ((last_ret = pcmcia_get_next_tuple(link, &tuple)) != 0) {
+
+		last_ret = pcmcia_get_next_tuple(link, &tuple);
+		if (last_ret) {
 			cs_error(link, GetNextTuple, last_ret);
 			goto cs_failed;
 		}
@@ -460,18 +471,21 @@
 	   handler to the interrupt, unless the 'Handler' member of the
 	   irq structure is initialized.
 	 */
-	if (link->conf.Attributes & CONF_ENABLE_IRQ)
-		if ((last_ret = pcmcia_request_irq(link, &link->irq)) != 0) {
+	if (link->conf.Attributes & CONF_ENABLE_IRQ) {
+		last_ret = pcmcia_request_irq(link, &link->irq);
+		if (last_ret) {
 			cs_error(link, RequestIRQ, last_ret);
 			goto cs_failed;
 		}
+	}
 
 	/*
 	   This actually configures the PCMCIA socket -- setting up
 	   the I/O windows and the interrupt mapping, and putting the
 	   card and host interface into "Memory and IO" mode.
 	 */
-	if ((last_ret = pcmcia_request_configuration(link, &link->conf)) != 0) {
+	last_ret = pcmcia_request_configuration(link, &link->conf);
+	if (last_ret) {
 		cs_error(link, RequestConfiguration, last_ret);
 		goto cs_failed;
 	}
@@ -529,7 +543,7 @@
 
 static int dio24_cs_suspend(struct pcmcia_device *link)
 {
-	local_info_t *local = link->priv;
+	struct local_info_t *local = link->priv;
 
 	/* Mark the device as stopped, to block IO until later */
 	local->stop = 1;
@@ -538,7 +552,7 @@
 
 static int dio24_cs_resume(struct pcmcia_device *link)
 {
-	local_info_t *local = link->priv;
+	struct local_info_t *local = link->priv;
 
 	local->stop = 0;
 	return 0;
diff --git a/drivers/staging/comedi/drivers/ni_labpc.c b/drivers/staging/comedi/drivers/ni_labpc.c
index 37898d8..30e11f4 100644
--- a/drivers/staging/comedi/drivers/ni_labpc.c
+++ b/drivers/staging/comedi/drivers/ni_labpc.c
@@ -74,8 +74,9 @@
 */
 
 #undef LABPC_DEBUG
-//#define LABPC_DEBUG   // enable debugging messages
+/* #define LABPC_DEBUG    enable debugging messages */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/delay.h>
@@ -89,120 +90,120 @@
 
 #define DRV_NAME "ni_labpc"
 
-#define LABPC_SIZE           32	// size of io region used by board
-#define LABPC_TIMER_BASE            500	// 2 MHz master clock
+#define LABPC_SIZE           32	/*  size of io region used by board */
+#define LABPC_TIMER_BASE            500	/*  2 MHz master clock */
 
 /* Registers for the lab-pc+ */
 
-//write-only registers
+/* write-only registers */
 #define COMMAND1_REG	0x0
 #define   ADC_GAIN_MASK	(0x7 << 4)
 #define   ADC_CHAN_BITS(x)	((x) & 0x7)
-#define   ADC_SCAN_EN_BIT	0x80	// enables multi channel scans
+#define   ADC_SCAN_EN_BIT	0x80	/*  enables multi channel scans */
 #define COMMAND2_REG	0x1
-#define   PRETRIG_BIT	0x1	// enable pretriggering (used in conjunction with SWTRIG)
-#define   HWTRIG_BIT	0x2	// enable paced conversions on external trigger
-#define   SWTRIG_BIT	0x4	// enable paced conversions
-#define   CASCADE_BIT	0x8	// use two cascaded counters for pacing
+#define   PRETRIG_BIT	0x1	/*  enable pretriggering (used in conjunction with SWTRIG) */
+#define   HWTRIG_BIT	0x2	/*  enable paced conversions on external trigger */
+#define   SWTRIG_BIT	0x4	/*  enable paced conversions */
+#define   CASCADE_BIT	0x8	/*  use two cascaded counters for pacing */
 #define   DAC_PACED_BIT(channel)	(0x40 << ((channel) & 0x1))
 #define COMMAND3_REG	0x2
-#define   DMA_EN_BIT	0x1	// enable dma transfers
-#define   DIO_INTR_EN_BIT	0x2	// enable interrupts for 8255
-#define   DMATC_INTR_EN_BIT	0x4	// enable dma terminal count interrupt
-#define   TIMER_INTR_EN_BIT	0x8	// enable timer interrupt
-#define   ERR_INTR_EN_BIT	0x10	// enable error interrupt
-#define   ADC_FNE_INTR_EN_BIT	0x20	// enable fifo not empty interrupt
+#define   DMA_EN_BIT	0x1	/*  enable dma transfers */
+#define   DIO_INTR_EN_BIT	0x2	/*  enable interrupts for 8255 */
+#define   DMATC_INTR_EN_BIT	0x4	/*  enable dma terminal count interrupt */
+#define   TIMER_INTR_EN_BIT	0x8	/*  enable timer interrupt */
+#define   ERR_INTR_EN_BIT	0x10	/*  enable error interrupt */
+#define   ADC_FNE_INTR_EN_BIT	0x20	/*  enable fifo not empty interrupt */
 #define ADC_CONVERT_REG	0x3
 #define DAC_LSB_REG(channel)	(0x4 + 2 * ((channel) & 0x1))
 #define DAC_MSB_REG(channel)	(0x5 + 2 * ((channel) & 0x1))
 #define ADC_CLEAR_REG	0x8
 #define DMATC_CLEAR_REG	0xa
 #define TIMER_CLEAR_REG	0xc
-#define COMMAND6_REG	0xe	// 1200 boards only
-#define   ADC_COMMON_BIT	0x1	// select ground or common-mode reference
-#define   ADC_UNIP_BIT	0x2	// adc unipolar
-#define   DAC_UNIP_BIT(channel)	(0x4 << ((channel) & 0x1))	// dac unipolar
-#define   ADC_FHF_INTR_EN_BIT	0x20	// enable fifo half full interrupt
-#define   A1_INTR_EN_BIT	0x40	// enable interrupt on end of hardware count
-#define   ADC_SCAN_UP_BIT 0x80	// scan up from channel zero instead of down to zero
+#define COMMAND6_REG	0xe	/*  1200 boards only */
+#define   ADC_COMMON_BIT	0x1	/*  select ground or common-mode reference */
+#define   ADC_UNIP_BIT	0x2	/*  adc unipolar */
+#define   DAC_UNIP_BIT(channel)	(0x4 << ((channel) & 0x1))	/*  dac unipolar */
+#define   ADC_FHF_INTR_EN_BIT	0x20	/*  enable fifo half full interrupt */
+#define   A1_INTR_EN_BIT	0x40	/*  enable interrupt on end of hardware count */
+#define   ADC_SCAN_UP_BIT 0x80	/*  scan up from channel zero instead of down to zero */
 #define COMMAND4_REG	0xf
-#define   INTERVAL_SCAN_EN_BIT	0x1	// enables 'interval' scanning
-#define   EXT_SCAN_EN_BIT	0x2	// enables external signal on counter b1 output to trigger scan
-#define   EXT_CONVERT_OUT_BIT	0x4	// chooses direction (output or input) for EXTCONV* line
-#define   ADC_DIFF_BIT	0x8	// chooses differential inputs for adc (in conjunction with board jumper)
+#define   INTERVAL_SCAN_EN_BIT	0x1	/*  enables 'interval' scanning */
+#define   EXT_SCAN_EN_BIT	0x2	/*  enables external signal on counter b1 output to trigger scan */
+#define   EXT_CONVERT_OUT_BIT	0x4	/*  chooses direction (output or input) for EXTCONV* line */
+#define   ADC_DIFF_BIT	0x8	/*  chooses differential inputs for adc (in conjunction with board jumper) */
 #define   EXT_CONVERT_DISABLE_BIT	0x10
-#define COMMAND5_REG	0x1c	// 1200 boards only, calibration stuff
-#define   EEPROM_WRITE_UNPROTECT_BIT	0x4	// enable eeprom for write
-#define   DITHER_EN_BIT	0x8	// enable dithering
-#define   CALDAC_LOAD_BIT	0x10	// load calibration dac
-#define   SCLOCK_BIT	0x20	// serial clock - rising edge writes, falling edge reads
-#define   SDATA_BIT	0x40	// serial data bit for writing to eeprom or calibration dacs
-#define   EEPROM_EN_BIT	0x80	// enable eeprom for read/write
+#define COMMAND5_REG	0x1c	/*  1200 boards only, calibration stuff */
+#define   EEPROM_WRITE_UNPROTECT_BIT	0x4	/*  enable eeprom for write */
+#define   DITHER_EN_BIT	0x8	/*  enable dithering */
+#define   CALDAC_LOAD_BIT	0x10	/*  load calibration dac */
+#define   SCLOCK_BIT	0x20	/*  serial clock - rising edge writes, falling edge reads */
+#define   SDATA_BIT	0x40	/*  serial data bit for writing to eeprom or calibration dacs */
+#define   EEPROM_EN_BIT	0x80	/*  enable eeprom for read/write */
 #define INTERVAL_COUNT_REG	0x1e
 #define INTERVAL_LOAD_REG	0x1f
 #define   INTERVAL_LOAD_BITS	0x1
 
-// read-only registers
+/* read-only registers */
 #define STATUS1_REG	0x0
-#define   DATA_AVAIL_BIT	0x1	// data is available in fifo
-#define   OVERRUN_BIT	0x2	// overrun has occurred
-#define   OVERFLOW_BIT	0x4	// fifo overflow
-#define   TIMER_BIT	0x8	// timer interrupt has occured
-#define   DMATC_BIT	0x10	// dma terminal count has occured
-#define   EXT_TRIG_BIT	0x40	// external trigger has occured
-#define STATUS2_REG	0x1d	// 1200 boards only
-#define   EEPROM_OUT_BIT	0x1	// programmable eeprom serial output
-#define   A1_TC_BIT	0x2	// counter A1 terminal count
-#define   FNHF_BIT	0x4	// fifo not half full
+#define   DATA_AVAIL_BIT	0x1	/*  data is available in fifo */
+#define   OVERRUN_BIT	0x2	/*  overrun has occurred */
+#define   OVERFLOW_BIT	0x4	/*  fifo overflow */
+#define   TIMER_BIT	0x8	/*  timer interrupt has occured */
+#define   DMATC_BIT	0x10	/*  dma terminal count has occured */
+#define   EXT_TRIG_BIT	0x40	/*  external trigger has occured */
+#define STATUS2_REG	0x1d	/*  1200 boards only */
+#define   EEPROM_OUT_BIT	0x1	/*  programmable eeprom serial output */
+#define   A1_TC_BIT	0x2	/*  counter A1 terminal count */
+#define   FNHF_BIT	0x4	/*  fifo not half full */
 #define ADC_FIFO_REG	0xa
 
 #define DIO_BASE_REG	0x10
 #define COUNTER_A_BASE_REG	0x14
 #define COUNTER_A_CONTROL_REG	(COUNTER_A_BASE_REG + 0x3)
-#define   INIT_A0_BITS	0x14	// check modes put conversion pacer output in harmless state (a0 mode 2)
-#define   INIT_A1_BITS	0x70	// put hardware conversion counter output in harmless state (a1 mode 0)
+#define   INIT_A0_BITS	0x14	/*  check modes put conversion pacer output in harmless state (a0 mode 2) */
+#define   INIT_A1_BITS	0x70	/*  put hardware conversion counter output in harmless state (a1 mode 0) */
 #define COUNTER_B_BASE_REG	0x18
 
-static int labpc_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int labpc_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static irqreturn_t labpc_interrupt(int irq, void *d PT_REGS_ARG);
-static int labpc_drain_fifo(struct comedi_device * dev);
-static void labpc_drain_dma(struct comedi_device * dev);
-static void handle_isa_dma(struct comedi_device * dev);
-static void labpc_drain_dregs(struct comedi_device * dev);
-static int labpc_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int labpc_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int labpc_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int labpc_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int labpc_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int labpc_calib_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int labpc_calib_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int labpc_eeprom_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int labpc_eeprom_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int labpc_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int labpc_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static irqreturn_t labpc_interrupt(int irq, void *d);
+static int labpc_drain_fifo(struct comedi_device *dev);
+static void labpc_drain_dma(struct comedi_device *dev);
+static void handle_isa_dma(struct comedi_device *dev);
+static void labpc_drain_dregs(struct comedi_device *dev);
+static int labpc_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int labpc_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int labpc_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int labpc_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int labpc_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int labpc_calib_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int labpc_calib_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int labpc_eeprom_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int labpc_eeprom_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 static unsigned int labpc_suggest_transfer_size(struct comedi_cmd cmd);
-static void labpc_adc_timing(struct comedi_device * dev, struct comedi_cmd * cmd);
+static void labpc_adc_timing(struct comedi_device *dev, struct comedi_cmd *cmd);
 #ifdef CONFIG_COMEDI_PCI
 static int labpc_find_device(struct comedi_device *dev, int bus, int slot);
 #endif
 static int labpc_dio_mem_callback(int dir, int port, int data,
 	unsigned long arg);
-static void labpc_serial_out(struct comedi_device * dev, unsigned int value,
+static void labpc_serial_out(struct comedi_device *dev, unsigned int value,
 	unsigned int num_bits);
-static unsigned int labpc_serial_in(struct comedi_device * dev);
-static unsigned int labpc_eeprom_read(struct comedi_device * dev,
+static unsigned int labpc_serial_in(struct comedi_device *dev);
+static unsigned int labpc_eeprom_read(struct comedi_device *dev,
 	unsigned int address);
-static unsigned int labpc_eeprom_read_status(struct comedi_device * dev);
-static unsigned int labpc_eeprom_write(struct comedi_device * dev,
+static unsigned int labpc_eeprom_read_status(struct comedi_device *dev);
+static unsigned int labpc_eeprom_write(struct comedi_device *dev,
 	unsigned int address, unsigned int value);
-static void write_caldac(struct comedi_device * dev, unsigned int channel,
+static void write_caldac(struct comedi_device *dev, unsigned int channel,
 	unsigned int value);
 
 enum scan_mode {
@@ -212,9 +213,9 @@
 	MODE_MULT_CHAN_DOWN,
 };
 
-//analog input ranges
+/* analog input ranges */
 #define NUM_LABPC_PLUS_AI_RANGES 16
-// indicates unipolar ranges
+/* indicates unipolar ranges */
 static const int labpc_plus_is_unipolar[NUM_LABPC_PLUS_AI_RANGES] = {
 	0,
 	0,
@@ -234,7 +235,7 @@
 	1,
 };
 
-// map range index to gain bits
+/* map range index to gain bits */
 static const int labpc_plus_ai_gain_bits[NUM_LABPC_PLUS_AI_RANGES] = {
 	0x00,
 	0x10,
@@ -276,7 +277,7 @@
 };
 
 #define NUM_LABPC_1200_AI_RANGES 14
-// indicates unipolar ranges
+/* indicates unipolar ranges */
 const int labpc_1200_is_unipolar[NUM_LABPC_1200_AI_RANGES] = {
 	0,
 	0,
@@ -294,7 +295,7 @@
 	1,
 };
 
-// map range index to gain bits
+/* map range index to gain bits */
 const int labpc_1200_ai_gain_bits[NUM_LABPC_1200_AI_RANGES] = {
 	0x00,
 	0x20,
@@ -331,7 +332,7 @@
 		}
 };
 
-//analog output ranges
+/* analog output ranges */
 #define AO_RANGE_IS_UNIPOLAR 0x1
 static const struct comedi_lrange range_labpc_ao = {
 	2,
@@ -360,58 +361,58 @@
 	writeb(byte, (void *)address);
 }
 
-static const labpc_board labpc_boards[] = {
+static const struct labpc_board_struct labpc_boards[] = {
 	{
-	      name:	"lab-pc-1200",
-	      ai_speed:10000,
-	      bustype:	isa_bustype,
-	      register_layout:labpc_1200_layout,
-	      has_ao:	1,
-	      ai_range_table:&range_labpc_1200_ai,
-	      ai_range_code:labpc_1200_ai_gain_bits,
-	      ai_range_is_unipolar:labpc_1200_is_unipolar,
-	      ai_scan_up:1,
-	      memory_mapped_io:0,
+	.name = "lab-pc-1200",
+	.ai_speed = 10000,
+	.bustype = isa_bustype,
+	.register_layout = labpc_1200_layout,
+	.has_ao = 1,
+	.ai_range_table = &range_labpc_1200_ai,
+	.ai_range_code = labpc_1200_ai_gain_bits,
+	.ai_range_is_unipolar = labpc_1200_is_unipolar,
+	.ai_scan_up = 1,
+	.memory_mapped_io = 0,
 		},
 	{
-	      name:	"lab-pc-1200ai",
-	      ai_speed:10000,
-	      bustype:	isa_bustype,
-	      register_layout:labpc_1200_layout,
-	      has_ao:	0,
-	      ai_range_table:&range_labpc_1200_ai,
-	      ai_range_code:labpc_1200_ai_gain_bits,
-	      ai_range_is_unipolar:labpc_1200_is_unipolar,
-	      ai_scan_up:1,
-	      memory_mapped_io:0,
+	.name = "lab-pc-1200ai",
+	.ai_speed = 10000,
+	.bustype = isa_bustype,
+	.register_layout = labpc_1200_layout,
+	.has_ao = 0,
+	.ai_range_table = &range_labpc_1200_ai,
+	.ai_range_code = labpc_1200_ai_gain_bits,
+	.ai_range_is_unipolar = labpc_1200_is_unipolar,
+	.ai_scan_up = 1,
+	.memory_mapped_io = 0,
 		},
 	{
-	      name:	"lab-pc+",
-	      ai_speed:12000,
-	      bustype:	isa_bustype,
-	      register_layout:labpc_plus_layout,
-	      has_ao:	1,
-	      ai_range_table:&range_labpc_plus_ai,
-	      ai_range_code:labpc_plus_ai_gain_bits,
-	      ai_range_is_unipolar:labpc_plus_is_unipolar,
-	      ai_scan_up:0,
-	      memory_mapped_io:0,
+	.name = "lab-pc+",
+	.ai_speed = 12000,
+	.bustype = isa_bustype,
+	.register_layout = labpc_plus_layout,
+	.has_ao = 1,
+	.ai_range_table = &range_labpc_plus_ai,
+	.ai_range_code = labpc_plus_ai_gain_bits,
+	.ai_range_is_unipolar = labpc_plus_is_unipolar,
+	.ai_scan_up = 0,
+	.memory_mapped_io = 0,
 		},
 #ifdef CONFIG_COMEDI_PCI
 	{
-		name:	"pci-1200",
-		device_id:0x161,
-		ai_speed:10000,
-		bustype:	pci_bustype,
-		register_layout:labpc_1200_layout,
-		has_ao:	1,
-		ai_range_table:&range_labpc_1200_ai,
-		ai_range_code:labpc_1200_ai_gain_bits,
-		ai_range_is_unipolar:labpc_1200_is_unipolar,
-		ai_scan_up:1,
-		memory_mapped_io:1,
+	.name = "pci-1200",
+	.device_id = 0x161,
+	.ai_speed = 10000,
+	.bustype = pci_bustype,
+	.register_layout = labpc_1200_layout,
+	.has_ao = 1,
+	.ai_range_table = &range_labpc_1200_ai,
+	.ai_range_code = labpc_1200_ai_gain_bits,
+	.ai_range_is_unipolar = labpc_1200_is_unipolar,
+	.ai_scan_up = 1,
+	.memory_mapped_io = 1,
 		},
-	// dummy entry so pci board works when comedi_config is passed driver name
+	/*  dummy entry so pci board works when comedi_config is passed driver name */
 	{
 		.name = DRV_NAME,
 		.bustype = pci_bustype,
@@ -422,21 +423,21 @@
 /*
  * Useful for shorthand access to the particular board structure
  */
-#define thisboard ((labpc_board *)dev->board_ptr)
+#define thisboard ((struct labpc_board_struct *)dev->board_ptr)
 
-static const int dma_buffer_size = 0xff00;	// size in bytes of dma buffer
-static const int sample_size = 2;	// 2 bytes per sample
+static const int dma_buffer_size = 0xff00;	/*  size in bytes of dma buffer */
+static const int sample_size = 2;	/*  2 bytes per sample */
 
-#define devpriv ((labpc_private *)dev->private)
+#define devpriv ((struct labpc_private *)dev->private)
 
 static struct comedi_driver driver_labpc = {
 	.driver_name = DRV_NAME,
 	.module = THIS_MODULE,
 	.attach = labpc_attach,
 	.detach = labpc_common_detach,
-	.num_names = sizeof(labpc_boards) / sizeof(labpc_board),
+	.num_names = ARRAY_SIZE(labpc_boards),
 	.board_name = &labpc_boards[0].name,
-	.offset = sizeof(labpc_board),
+	.offset = sizeof(struct labpc_board_struct),
 };
 
 #ifdef CONFIG_COMEDI_PCI
@@ -448,7 +449,7 @@
 MODULE_DEVICE_TABLE(pci, labpc_pci_table);
 #endif /* CONFIG_COMEDI_PCI */
 
-static inline int labpc_counter_load(struct comedi_device * dev,
+static inline int labpc_counter_load(struct comedi_device *dev,
 	unsigned long base_address, unsigned int counter_number,
 	unsigned int count, unsigned int mode)
 {
@@ -459,7 +460,7 @@
 		return i8254_load(base_address, 0, counter_number, count, mode);
 }
 
-int labpc_common_attach(struct comedi_device * dev, unsigned long iobase,
+int labpc_common_attach(struct comedi_device *dev, unsigned long iobase,
 	unsigned int irq, unsigned int dma_chan)
 {
 	struct comedi_subdevice *s;
@@ -481,7 +482,7 @@
 		printk("io base address is zero!\n");
 		return -EINVAL;
 	}
-	// request io regions for isa boards
+	/*  request io regions for isa boards */
 	if (thisboard->bustype == isa_bustype) {
 		/* check if io addresses are available */
 		if (!request_region(iobase, LABPC_SIZE,
@@ -499,7 +500,7 @@
 		devpriv->read_byte = labpc_inb;
 		devpriv->write_byte = labpc_outb;
 	}
-	// initialize board's command registers
+	/*  initialize board's command registers */
 	devpriv->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
 	devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
 	devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
@@ -516,7 +517,7 @@
 		isr_flags = 0;
 		if (thisboard->bustype == pci_bustype)
 			isr_flags |= IRQF_SHARED;
-		if (comedi_request_irq(irq, labpc_interrupt, isr_flags,
+		if (request_irq(irq, labpc_interrupt, isr_flags,
 				driver_labpc.driver_name, dev)) {
 			printk("unable to allocate irq %u\n", irq);
 			return -EINVAL;
@@ -524,12 +525,12 @@
 	}
 	dev->irq = irq;
 
-	// grab dma channel
+	/*  grab dma channel */
 	if (dma_chan > 3) {
 		printk(" invalid dma channel %u\n", dma_chan);
 		return -EINVAL;
 	} else if (dma_chan) {
-		// allocate dma buffer
+		/*  allocate dma buffer */
 		devpriv->dma_buffer =
 			kmalloc(dma_buffer_size, GFP_KERNEL | GFP_DMA);
 		if (devpriv->dma_buffer == NULL) {
@@ -562,7 +563,7 @@
 		SDF_CMD_READ;
 	s->n_chan = 8;
 	s->len_chanlist = 8;
-	s->maxdata = (1 << 12) - 1;	// 12 bit resolution
+	s->maxdata = (1 << 12) - 1;	/*  12 bit resolution */
 	s->range_table = thisboard->ai_range_table;
 	s->do_cmd = labpc_ai_cmd;
 	s->do_cmdtest = labpc_ai_cmdtest;
@@ -577,7 +578,7 @@
 		s->type = COMEDI_SUBD_AO;
 		s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_GROUND;
 		s->n_chan = NUM_AO_CHAN;
-		s->maxdata = (1 << 12) - 1;	// 12 bit resolution
+		s->maxdata = (1 << 12) - 1;	/*  12 bit resolution */
 		s->range_table = &range_labpc_ao;
 		s->insn_read = labpc_ao_rinsn;
 		s->insn_write = labpc_ao_winsn;
@@ -595,14 +596,14 @@
 
 	/* 8255 dio */
 	s = dev->subdevices + 2;
-	// if board uses io memory we have to give a custom callback function to the 8255 driver
+	/*  if board uses io memory we have to give a custom callback function to the 8255 driver */
 	if (thisboard->memory_mapped_io)
 		subdev_8255_init(dev, s, labpc_dio_mem_callback,
 			(unsigned long)(dev->iobase + DIO_BASE_REG));
 	else
 		subdev_8255_init(dev, s, NULL, dev->iobase + DIO_BASE_REG);
 
-	// calibration subdevices for boards that have one
+	/*  calibration subdevices for boards that have one */
 	s = dev->subdevices + 3;
 	if (thisboard->register_layout == labpc_1200_layout) {
 		s->type = COMEDI_SUBD_CALIB;
@@ -643,7 +644,7 @@
 	return 0;
 }
 
-static int labpc_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int labpc_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	unsigned long iobase = 0;
 	unsigned int irq = 0;
@@ -653,10 +654,10 @@
 #endif
 
 	/* allocate and initialize dev->private */
-	if (alloc_private(dev, sizeof(labpc_private)) < 0)
+	if (alloc_private(dev, sizeof(struct labpc_private)) < 0)
 		return -ENOMEM;
 
-	// get base address, irq etc. based on bustype
+	/*  get base address, irq etc. based on bustype */
 	switch (thisboard->bustype) {
 	case isa_bustype:
 		iobase = it->options[0];
@@ -692,7 +693,7 @@
 	return labpc_common_attach(dev, iobase, irq, dma_chan);
 }
 
-// adapted from ni_pcimio for finding mite based boards (pc-1200)
+/* adapted from ni_pcimio for finding mite based boards (pc-1200) */
 #ifdef CONFIG_COMEDI_PCI
 static int labpc_find_device(struct comedi_device *dev, int bus, int slot)
 {
@@ -701,7 +702,7 @@
 	for (mite = mite_devices; mite; mite = mite->next) {
 		if (mite->used)
 			continue;
-		// if bus/slot are specified then make sure we have the right bus/slot
+		/*  if bus/slot are specified then make sure we have the right bus/slot */
 		if (bus || slot) {
 			if (bus != mite->pcidev->bus->number
 				|| slot != PCI_SLOT(mite->pcidev->devfn))
@@ -712,7 +713,7 @@
 				continue;
 			if (mite_device_id(mite) == labpc_boards[i].device_id) {
 				devpriv->mite = mite;
-				// fixup board pointer, in case we were using the dummy "ni_labpc" entry
+				/*  fixup board pointer, in case we were using the dummy "ni_labpc" entry */
 				dev->board_ptr = &labpc_boards[i];
 				return 0;
 			}
@@ -724,7 +725,7 @@
 }
 #endif
 
-int labpc_common_detach(struct comedi_device * dev)
+int labpc_common_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: ni_labpc: detach\n", dev->minor);
 
@@ -737,7 +738,7 @@
 	if (devpriv->dma_chan)
 		free_dma(devpriv->dma_chan);
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	if (thisboard->bustype == isa_bustype && dev->iobase)
 		release_region(dev->iobase, LABPC_SIZE);
 #ifdef CONFIG_COMEDI_PCI
@@ -748,21 +749,21 @@
 	return 0;
 };
 
-static void labpc_clear_adc_fifo(const struct comedi_device * dev)
+static void labpc_clear_adc_fifo(const struct comedi_device *dev)
 {
 	devpriv->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
 	devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
 	devpriv->read_byte(dev->iobase + ADC_FIFO_REG);
 }
 
-static int labpc_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int labpc_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
 	devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	devpriv->command3_bits = 0;
 	devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
@@ -770,7 +771,7 @@
 	return 0;
 }
 
-static enum scan_mode labpc_ai_scan_mode(const struct comedi_cmd * cmd)
+static enum scan_mode labpc_ai_scan_mode(const struct comedi_cmd *cmd)
 {
 	if (cmd->chanlist_len == 1)
 		return MODE_SINGLE_CHAN;
@@ -788,13 +789,13 @@
 	if (CR_CHAN(cmd->chanlist[0]) > CR_CHAN(cmd->chanlist[1]))
 		return MODE_MULT_CHAN_DOWN;
 
-	rt_printk("ni_labpc: bug! this should never happen\n");
+	printk("ni_labpc: bug! this should never happen\n");
 
 	return 0;
 }
 
-static int labpc_ai_chanlist_invalid(const struct comedi_device * dev,
-	const struct comedi_cmd * cmd)
+static int labpc_ai_chanlist_invalid(const struct comedi_device *dev,
+	const struct comedi_cmd *cmd)
 {
 	int mode, channel, range, aref, i;
 
@@ -844,7 +845,7 @@
 			}
 			break;
 		default:
-			rt_printk("ni_labpc: bug! in chanlist check\n");
+			printk("ni_labpc: bug! in chanlist check\n");
 			return 1;
 			break;
 		}
@@ -865,7 +866,7 @@
 	return 0;
 }
 
-static int labpc_use_continuous_mode(const struct comedi_cmd * cmd)
+static int labpc_use_continuous_mode(const struct comedi_cmd *cmd)
 {
 	if (labpc_ai_scan_mode(cmd) == MODE_SINGLE_CHAN)
 		return 1;
@@ -876,7 +877,7 @@
 	return 0;
 }
 
-static unsigned int labpc_ai_convert_period(const struct comedi_cmd * cmd)
+static unsigned int labpc_ai_convert_period(const struct comedi_cmd *cmd)
 {
 	if (cmd->convert_src != TRIG_TIMER)
 		return 0;
@@ -888,7 +889,7 @@
 	return cmd->convert_arg;
 }
 
-static void labpc_set_ai_convert_period(struct comedi_cmd * cmd, unsigned int ns)
+static void labpc_set_ai_convert_period(struct comedi_cmd *cmd, unsigned int ns)
 {
 	if (cmd->convert_src != TRIG_TIMER)
 		return;
@@ -902,7 +903,7 @@
 		cmd->convert_arg = ns;
 }
 
-static unsigned int labpc_ai_scan_period(const struct comedi_cmd * cmd)
+static unsigned int labpc_ai_scan_period(const struct comedi_cmd *cmd)
 {
 	if (cmd->scan_begin_src != TRIG_TIMER)
 		return 0;
@@ -914,7 +915,7 @@
 	return cmd->scan_begin_arg;
 }
 
-static void labpc_set_ai_scan_period(struct comedi_cmd * cmd, unsigned int ns)
+static void labpc_set_ai_scan_period(struct comedi_cmd *cmd, unsigned int ns)
 {
 	if (cmd->scan_begin_src != TRIG_TIMER)
 		return;
@@ -926,8 +927,8 @@
 	cmd->scan_begin_arg = ns;
 }
 
-static int labpc_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int labpc_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp, tmp2;
@@ -980,7 +981,7 @@
 		cmd->stop_src != TRIG_EXT && cmd->stop_src != TRIG_NONE)
 		err++;
 
-	// can't have external stop and start triggers at once
+	/*  can't have external stop and start triggers at once */
 	if (cmd->start_src == TRIG_EXT && cmd->stop_src == TRIG_EXT)
 		err++;
 
@@ -1008,7 +1009,7 @@
 			err++;
 		}
 	}
-	// make sure scan timing is not too fast
+	/*  make sure scan timing is not too fast */
 	if (cmd->scan_begin_src == TRIG_TIMER) {
 		if (cmd->convert_src == TRIG_TIMER &&
 			cmd->scan_begin_arg <
@@ -1024,7 +1025,7 @@
 			err++;
 		}
 	}
-	// stop source
+	/*  stop source */
 	switch (cmd->stop_src) {
 	case TRIG_COUNT:
 		if (!cmd->stop_arg) {
@@ -1038,7 +1039,7 @@
 			err++;
 		}
 		break;
-		// TRIG_EXT doesn't care since it doesn't trigger off a numbered channel
+		/*  TRIG_EXT doesn't care since it doesn't trigger off a numbered channel */
 	default:
 		break;
 	}
@@ -1063,7 +1064,7 @@
 	return 0;
 }
 
-static int labpc_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int labpc_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int channel, range, aref;
 	unsigned long irq_flags;
@@ -1081,77 +1082,77 @@
 	range = CR_RANGE(cmd->chanlist[0]);
 	aref = CR_AREF(cmd->chanlist[0]);
 
-	// make sure board is disabled before setting up aquisition
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  make sure board is disabled before setting up aquisition */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
 	devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	devpriv->command3_bits = 0;
 	devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
 
-	// initialize software conversion count
+	/*  initialize software conversion count */
 	if (cmd->stop_src == TRIG_COUNT) {
 		devpriv->count = cmd->stop_arg * cmd->chanlist_len;
 	}
-	// setup hardware conversion counter
+	/*  setup hardware conversion counter */
 	if (cmd->stop_src == TRIG_EXT) {
-		// load counter a1 with count of 3 (pc+ manual says this is minimum allowed) using mode 0
+		/*  load counter a1 with count of 3 (pc+ manual says this is minimum allowed) using mode 0 */
 		ret = labpc_counter_load(dev, dev->iobase + COUNTER_A_BASE_REG,
 			1, 3, 0);
 		if (ret < 0) {
 			comedi_error(dev, "error loading counter a1");
 			return -1;
 		}
-	} else			// otherwise, just put a1 in mode 0 with no count to set its output low
+	} else			/*  otherwise, just put a1 in mode 0 with no count to set its output low */
 		devpriv->write_byte(INIT_A1_BITS,
 			dev->iobase + COUNTER_A_CONTROL_REG);
 
-	// figure out what method we will use to transfer data
-	if (devpriv->dma_chan &&	// need a dma channel allocated
-		// dma unsafe at RT priority, and too much setup time for TRIG_WAKE_EOS for
+	/*  figure out what method we will use to transfer data */
+	if (devpriv->dma_chan &&	/*  need a dma channel allocated */
+		/*  dma unsafe at RT priority, and too much setup time for TRIG_WAKE_EOS for */
 		(cmd->flags & (TRIG_WAKE_EOS | TRIG_RT)) == 0 &&
-		// only available on the isa boards
+		/*  only available on the isa boards */
 		thisboard->bustype == isa_bustype) {
 		xfer = isa_dma_transfer;
-	} else if (thisboard->register_layout == labpc_1200_layout &&	// pc-plus has no fifo-half full interrupt
-		// wake-end-of-scan should interrupt on fifo not empty
+	} else if (thisboard->register_layout == labpc_1200_layout &&	/*  pc-plus has no fifo-half full interrupt */
+		/*  wake-end-of-scan should interrupt on fifo not empty */
 		(cmd->flags & TRIG_WAKE_EOS) == 0 &&
-		// make sure we are taking more than just a few points
+		/*  make sure we are taking more than just a few points */
 		(cmd->stop_src != TRIG_COUNT || devpriv->count > 256)) {
 		xfer = fifo_half_full_transfer;
 	} else
 		xfer = fifo_not_empty_transfer;
 	devpriv->current_transfer = xfer;
 
-	// setup command6 register for 1200 boards
+	/*  setup command6 register for 1200 boards */
 	if (thisboard->register_layout == labpc_1200_layout) {
-		// reference inputs to ground or common?
+		/*  reference inputs to ground or common? */
 		if (aref != AREF_GROUND)
 			devpriv->command6_bits |= ADC_COMMON_BIT;
 		else
 			devpriv->command6_bits &= ~ADC_COMMON_BIT;
-		// bipolar or unipolar range?
+		/*  bipolar or unipolar range? */
 		if (thisboard->ai_range_is_unipolar[range])
 			devpriv->command6_bits |= ADC_UNIP_BIT;
 		else
 			devpriv->command6_bits &= ~ADC_UNIP_BIT;
-		// interrupt on fifo half full?
+		/*  interrupt on fifo half full? */
 		if (xfer == fifo_half_full_transfer)
 			devpriv->command6_bits |= ADC_FHF_INTR_EN_BIT;
 		else
 			devpriv->command6_bits &= ~ADC_FHF_INTR_EN_BIT;
-		// enable interrupt on counter a1 terminal count?
+		/*  enable interrupt on counter a1 terminal count? */
 		if (cmd->stop_src == TRIG_EXT)
 			devpriv->command6_bits |= A1_INTR_EN_BIT;
 		else
 			devpriv->command6_bits &= ~A1_INTR_EN_BIT;
-		// are we scanning up or down through channels?
+		/*  are we scanning up or down through channels? */
 		if (labpc_ai_scan_mode(cmd) == MODE_MULT_CHAN_UP)
 			devpriv->command6_bits |= ADC_SCAN_UP_BIT;
 		else
 			devpriv->command6_bits &= ~ADC_SCAN_UP_BIT;
-		// write to register
+		/*  write to register */
 		devpriv->write_byte(devpriv->command6_bits,
 			dev->iobase + COMMAND6_REG);
 	}
@@ -1162,23 +1163,23 @@
 		channel = CR_CHAN(cmd->chanlist[cmd->chanlist_len - 1]);
 	else
 		channel = CR_CHAN(cmd->chanlist[0]);
-	// munge channel bits for differential / scan disabled mode
+	/*  munge channel bits for differential / scan disabled mode */
 	if (labpc_ai_scan_mode(cmd) != MODE_SINGLE_CHAN && aref == AREF_DIFF)
 		channel *= 2;
 	devpriv->command1_bits |= ADC_CHAN_BITS(channel);
 	devpriv->command1_bits |= thisboard->ai_range_code[range];
 	devpriv->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
-	// manual says to set scan enable bit on second pass
+	/*  manual says to set scan enable bit on second pass */
 	if (labpc_ai_scan_mode(cmd) == MODE_MULT_CHAN_UP ||
 		labpc_ai_scan_mode(cmd) == MODE_MULT_CHAN_DOWN) {
 		devpriv->command1_bits |= ADC_SCAN_EN_BIT;
 		/* need a brief delay before enabling scan, or scan list will get screwed when you switch
 		 * between scan up to scan down mode - dunno why */
-		comedi_udelay(1);
+		udelay(1);
 		devpriv->write_byte(devpriv->command1_bits,
 			dev->iobase + COMMAND1_REG);
 	}
-	// setup any external triggering/pacing (command4 register)
+	/*  setup any external triggering/pacing (command4 register) */
 	devpriv->command4_bits = 0;
 	if (cmd->convert_src != TRIG_EXT)
 		devpriv->command4_bits |= EXT_CONVERT_DISABLE_BIT;
@@ -1189,21 +1190,21 @@
 		if (cmd->scan_begin_src == TRIG_EXT)
 			devpriv->command4_bits |= EXT_SCAN_EN_BIT;
 	}
-	// single-ended/differential
+	/*  single-ended/differential */
 	if (aref == AREF_DIFF)
 		devpriv->command4_bits |= ADC_DIFF_BIT;
 	devpriv->write_byte(devpriv->command4_bits, dev->iobase + COMMAND4_REG);
 
 	devpriv->write_byte(cmd->chanlist_len,
 		dev->iobase + INTERVAL_COUNT_REG);
-	// load count
+	/*  load count */
 	devpriv->write_byte(INTERVAL_LOAD_BITS,
 		dev->iobase + INTERVAL_LOAD_REG);
 
 	if (cmd->convert_src == TRIG_TIMER || cmd->scan_begin_src == TRIG_TIMER) {
-		// set up pacing
+		/*  set up pacing */
 		labpc_adc_timing(dev, cmd);
-		// load counter b0 in mode 3
+		/*  load counter b0 in mode 3 */
 		ret = labpc_counter_load(dev, dev->iobase + COUNTER_B_BASE_REG,
 			0, devpriv->divisor_b0, 3);
 		if (ret < 0) {
@@ -1211,9 +1212,9 @@
 			return -1;
 		}
 	}
-	// set up conversion pacing
+	/*  set up conversion pacing */
 	if (labpc_ai_convert_period(cmd)) {
-		// load counter a0 in mode 2
+		/*  load counter a0 in mode 2 */
 		ret = labpc_counter_load(dev, dev->iobase + COUNTER_A_BASE_REG,
 			0, devpriv->divisor_a0, 2);
 		if (ret < 0) {
@@ -1224,9 +1225,9 @@
 		devpriv->write_byte(INIT_A0_BITS,
 			dev->iobase + COUNTER_A_CONTROL_REG);
 
-	// set up scan pacing
+	/*  set up scan pacing */
 	if (labpc_ai_scan_period(cmd)) {
-		// load counter b1 in mode 2
+		/*  load counter b1 in mode 2 */
 		ret = labpc_counter_load(dev, dev->iobase + COUNTER_B_BASE_REG,
 			1, devpriv->divisor_b1, 2);
 		if (ret < 0) {
@@ -1237,7 +1238,7 @@
 
 	labpc_clear_adc_fifo(dev);
 
-	// set up dma transfer
+	/*  set up dma transfer */
 	if (xfer == isa_dma_transfer) {
 		irq_flags = claim_dma_lock();
 		disable_dma(devpriv->dma_chan);
@@ -1246,7 +1247,7 @@
 		clear_dma_ff(devpriv->dma_chan);
 		set_dma_addr(devpriv->dma_chan,
 			virt_to_bus(devpriv->dma_buffer));
-		// set appropriate size of transfer
+		/*  set appropriate size of transfer */
 		devpriv->dma_transfer_size = labpc_suggest_transfer_size(*cmd);
 		if (cmd->stop_src == TRIG_COUNT &&
 			devpriv->count * sample_size <
@@ -1257,25 +1258,25 @@
 		set_dma_count(devpriv->dma_chan, devpriv->dma_transfer_size);
 		enable_dma(devpriv->dma_chan);
 		release_dma_lock(irq_flags);
-		// enable board's dma
+		/*  enable board's dma */
 		devpriv->command3_bits |= DMA_EN_BIT | DMATC_INTR_EN_BIT;
 	} else
 		devpriv->command3_bits &= ~DMA_EN_BIT & ~DMATC_INTR_EN_BIT;
 
-	// enable error interrupts
+	/*  enable error interrupts */
 	devpriv->command3_bits |= ERR_INTR_EN_BIT;
-	// enable fifo not empty interrupt?
+	/*  enable fifo not empty interrupt? */
 	if (xfer == fifo_not_empty_transfer)
 		devpriv->command3_bits |= ADC_FNE_INTR_EN_BIT;
 	else
 		devpriv->command3_bits &= ~ADC_FNE_INTR_EN_BIT;
 	devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
 
-	// startup aquisition
+	/*  startup aquisition */
 
-	// command2 reg
-	// use 2 cascaded counters for pacing
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  command2 reg */
+	/*  use 2 cascaded counters for pacing */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	devpriv->command2_bits |= CASCADE_BIT;
 	switch (cmd->start_src) {
 	case TRIG_EXT:
@@ -1303,13 +1304,13 @@
 		return -1;
 	}
 	devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	return 0;
 }
 
 /* interrupt service routine */
-static irqreturn_t labpc_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t labpc_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s = dev->read_subdev;
@@ -1325,7 +1326,7 @@
 	cmd = &async->cmd;
 	async->events = 0;
 
-	// read board status
+	/*  read board status */
 	devpriv->status1_bits = devpriv->read_byte(dev->iobase + STATUS1_REG);
 	if (thisboard->register_layout == labpc_1200_layout)
 		devpriv->status2_bits =
@@ -1339,7 +1340,7 @@
 	}
 
 	if (devpriv->status1_bits & OVERRUN_BIT) {
-		// clear error interrupt
+		/*  clear error interrupt */
 		devpriv->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
 		async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
 		comedi_event(dev, s);
@@ -1348,7 +1349,7 @@
 	}
 
 	if (devpriv->current_transfer == isa_dma_transfer) {
-		// if a dma terminal count of external stop trigger has occurred
+		/*  if a dma terminal count of external stop trigger has occurred */
 		if (devpriv->status1_bits & DMATC_BIT ||
 			(thisboard->register_layout == labpc_1200_layout
 				&& devpriv->status2_bits & A1_TC_BIT)) {
@@ -1359,19 +1360,19 @@
 
 	if (devpriv->status1_bits & TIMER_BIT) {
 		comedi_error(dev, "handled timer interrupt?");
-		// clear it
+		/*  clear it */
 		devpriv->write_byte(0x1, dev->iobase + TIMER_CLEAR_REG);
 	}
 
 	if (devpriv->status1_bits & OVERFLOW_BIT) {
-		// clear error interrupt
+		/*  clear error interrupt */
 		devpriv->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
 		async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
 		comedi_event(dev, s);
 		comedi_error(dev, "overflow");
 		return IRQ_HANDLED;
 	}
-	// handle external stop trigger
+	/*  handle external stop trigger */
 	if (cmd->stop_src == TRIG_EXT) {
 		if (devpriv->status2_bits & A1_TC_BIT) {
 			labpc_drain_dregs(dev);
@@ -1392,8 +1393,8 @@
 	return IRQ_HANDLED;
 }
 
-// read all available samples from ai fifo
-static int labpc_drain_fifo(struct comedi_device * dev)
+/* read all available samples from ai fifo */
+static int labpc_drain_fifo(struct comedi_device *dev)
 {
 	unsigned int lsb, msb;
 	short data;
@@ -1405,7 +1406,7 @@
 
 	for (i = 0; (devpriv->status1_bits & DATA_AVAIL_BIT) && i < timeout;
 		i++) {
-		// quit if we have all the data we want
+		/*  quit if we have all the data we want */
 		if (async->cmd.stop_src == TRIG_COUNT) {
 			if (devpriv->count == 0)
 				break;
@@ -1427,7 +1428,7 @@
 	return 0;
 }
 
-static void labpc_drain_dma(struct comedi_device * dev)
+static void labpc_drain_dma(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s = dev->read_subdev;
 	struct comedi_async *async = s->async;
@@ -1444,7 +1445,7 @@
 	 * count and address get set correctly */
 	clear_dma_ff(devpriv->dma_chan);
 
-	// figure out how many points to read
+	/*  figure out how many points to read */
 	max_points = devpriv->dma_transfer_size / sample_size;
 	/* residue is the number of points left to be done on the dma
 	 * transfer.  It should always be zero at this point unless
@@ -1455,7 +1456,7 @@
 	if (devpriv->count < num_points && async->cmd.stop_src == TRIG_COUNT)
 		num_points = devpriv->count;
 
-	// figure out how many points will be stored next time
+	/*  figure out how many points will be stored next time */
 	leftover = 0;
 	if (async->cmd.stop_src != TRIG_COUNT) {
 		leftover = devpriv->dma_transfer_size / sample_size;
@@ -1472,7 +1473,7 @@
 	if (async->cmd.stop_src == TRIG_COUNT)
 		devpriv->count -= num_points;
 
-	// set address and count for next transfer
+	/*  set address and count for next transfer */
 	set_dma_addr(devpriv->dma_chan, virt_to_bus(devpriv->dma_buffer));
 	set_dma_count(devpriv->dma_chan, leftover * sample_size);
 	release_dma_lock(flags);
@@ -1480,19 +1481,19 @@
 	async->events |= COMEDI_CB_BLOCK;
 }
 
-static void handle_isa_dma(struct comedi_device * dev)
+static void handle_isa_dma(struct comedi_device *dev)
 {
 	labpc_drain_dma(dev);
 
 	enable_dma(devpriv->dma_chan);
 
-	// clear dma tc interrupt
+	/*  clear dma tc interrupt */
 	devpriv->write_byte(0x1, dev->iobase + DMATC_CLEAR_REG);
 }
 
 /* makes sure all data aquired by board is transfered to comedi (used
  * when aquisition is terminated by stop_src == TRIG_EXT). */
-static void labpc_drain_dregs(struct comedi_device * dev)
+static void labpc_drain_dregs(struct comedi_device *dev)
 {
 	if (devpriv->current_transfer == isa_dma_transfer)
 		labpc_drain_dma(dev);
@@ -1500,8 +1501,8 @@
 	labpc_drain_fifo(dev);
 }
 
-static int labpc_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int labpc_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, n;
 	int chan, range;
@@ -1509,13 +1510,13 @@
 	int timeout = 1000;
 	unsigned long flags;
 
-	// disable timed conversions
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  disable timed conversions */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
 	devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// disable interrupt generation and dma
+	/*  disable interrupt generation and dma */
 	devpriv->command3_bits = 0;
 	devpriv->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
 
@@ -1524,41 +1525,41 @@
 	chan = CR_CHAN(insn->chanspec);
 	range = CR_RANGE(insn->chanspec);
 	devpriv->command1_bits |= thisboard->ai_range_code[range];
-	// munge channel bits for differential/scan disabled mode
+	/*  munge channel bits for differential/scan disabled mode */
 	if (CR_AREF(insn->chanspec) == AREF_DIFF)
 		chan *= 2;
 	devpriv->command1_bits |= ADC_CHAN_BITS(chan);
 	devpriv->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
 
-	// setup command6 register for 1200 boards
+	/*  setup command6 register for 1200 boards */
 	if (thisboard->register_layout == labpc_1200_layout) {
-		// reference inputs to ground or common?
+		/*  reference inputs to ground or common? */
 		if (CR_AREF(insn->chanspec) != AREF_GROUND)
 			devpriv->command6_bits |= ADC_COMMON_BIT;
 		else
 			devpriv->command6_bits &= ~ADC_COMMON_BIT;
-		// bipolar or unipolar range?
+		/*  bipolar or unipolar range? */
 		if (thisboard->ai_range_is_unipolar[range])
 			devpriv->command6_bits |= ADC_UNIP_BIT;
 		else
 			devpriv->command6_bits &= ~ADC_UNIP_BIT;
-		// don't interrupt on fifo half full
+		/*  don't interrupt on fifo half full */
 		devpriv->command6_bits &= ~ADC_FHF_INTR_EN_BIT;
-		// don't enable interrupt on counter a1 terminal count?
+		/*  don't enable interrupt on counter a1 terminal count? */
 		devpriv->command6_bits &= ~A1_INTR_EN_BIT;
-		// write to register
+		/*  write to register */
 		devpriv->write_byte(devpriv->command6_bits,
 			dev->iobase + COMMAND6_REG);
 	}
-	// setup command4 register
+	/*  setup command4 register */
 	devpriv->command4_bits = 0;
 	devpriv->command4_bits |= EXT_CONVERT_DISABLE_BIT;
-	// single-ended/differential
+	/*  single-ended/differential */
 	if (CR_AREF(insn->chanspec) == AREF_DIFF)
 		devpriv->command4_bits |= ADC_DIFF_BIT;
 	devpriv->write_byte(devpriv->command4_bits, dev->iobase + COMMAND4_REG);
 
-	// initialize pacer counter output to make sure it doesn't cause any problems
+	/*  initialize pacer counter output to make sure it doesn't cause any problems */
 	devpriv->write_byte(INIT_A0_BITS, dev->iobase + COUNTER_A_CONTROL_REG);
 
 	labpc_clear_adc_fifo(dev);
@@ -1571,7 +1572,7 @@
 			if (devpriv->read_byte(dev->iobase +
 					STATUS1_REG) & DATA_AVAIL_BIT)
 				break;
-			comedi_udelay(1);
+			udelay(1);
 		}
 		if (i == timeout) {
 			comedi_error(dev, "timeout");
@@ -1585,9 +1586,9 @@
 	return n;
 }
 
-// analog output insn
-static int labpc_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+/* analog output insn */
+static int labpc_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int channel, range;
 	unsigned long flags;
@@ -1595,56 +1596,56 @@
 
 	channel = CR_CHAN(insn->chanspec);
 
-	// turn off pacing of analog output channel
+	/*  turn off pacing of analog output channel */
 	/* note: hardware bug in daqcard-1200 means pacing cannot
 	 * be independently enabled/disabled for its the two channels */
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 	devpriv->command2_bits &= ~DAC_PACED_BIT(channel);
 	devpriv->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
-	// set range
+	/*  set range */
 	if (thisboard->register_layout == labpc_1200_layout) {
 		range = CR_RANGE(insn->chanspec);
 		if (range & AO_RANGE_IS_UNIPOLAR)
 			devpriv->command6_bits |= DAC_UNIP_BIT(channel);
 		else
 			devpriv->command6_bits &= ~DAC_UNIP_BIT(channel);
-		// write to register
+		/*  write to register */
 		devpriv->write_byte(devpriv->command6_bits,
 			dev->iobase + COMMAND6_REG);
 	}
-	// send data
+	/*  send data */
 	lsb = data[0] & 0xff;
 	msb = (data[0] >> 8) & 0xff;
 	devpriv->write_byte(lsb, dev->iobase + DAC_LSB_REG(channel));
 	devpriv->write_byte(msb, dev->iobase + DAC_MSB_REG(channel));
 
-	// remember value for readback
+	/*  remember value for readback */
 	devpriv->ao_value[channel] = data[0];
 
 	return 1;
 }
 
-// analog output readback insn
-static int labpc_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+/* analog output readback insn */
+static int labpc_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->ao_value[CR_CHAN(insn->chanspec)];
 
 	return 1;
 }
 
-static int labpc_calib_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int labpc_calib_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->caldac[CR_CHAN(insn->chanspec)];
 
 	return 1;
 }
 
-static int labpc_calib_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int labpc_calib_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int channel = CR_CHAN(insn->chanspec);
 
@@ -1652,21 +1653,21 @@
 	return 1;
 }
 
-static int labpc_eeprom_read_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int labpc_eeprom_read_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->eeprom_data[CR_CHAN(insn->chanspec)];
 
 	return 1;
 }
 
-static int labpc_eeprom_write_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int labpc_eeprom_write_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int channel = CR_CHAN(insn->chanspec);
 	int ret;
 
-	// only allow writes to user area of eeprom
+	/*  only allow writes to user area of eeprom */
 	if (channel < 16 || channel > 127) {
 		printk("eeprom writes are only allowed to channels 16 through 127 (the pointer and user areas)");
 		return -EINVAL;
@@ -1679,7 +1680,7 @@
 	return 1;
 }
 
-// utility function that suggests a dma transfer size in bytes
+/* utility function that suggests a dma transfer size in bytes */
 static unsigned int labpc_suggest_transfer_size(struct comedi_cmd cmd)
 {
 	unsigned int size;
@@ -1687,14 +1688,14 @@
 
 	if (cmd.convert_src == TRIG_TIMER)
 		freq = 1000000000 / cmd.convert_arg;
-	// return some default value
+	/*  return some default value */
 	else
 		freq = 0xffffffff;
 
-	// make buffer fill in no more than 1/3 second
+	/*  make buffer fill in no more than 1/3 second */
 	size = (freq / 3) * sample_size;
 
-	// set a minimum and maximum size allowed
+	/*  set a minimum and maximum size allowed */
 	if (size > dma_buffer_size)
 		size = dma_buffer_size - dma_buffer_size % sample_size;
 	else if (size < sample_size)
@@ -1703,16 +1704,16 @@
 	return size;
 }
 
-// figures out what counter values to use based on command
-static void labpc_adc_timing(struct comedi_device * dev, struct comedi_cmd * cmd)
+/* figures out what counter values to use based on command */
+static void labpc_adc_timing(struct comedi_device *dev, struct comedi_cmd *cmd)
 {
-	const int max_counter_value = 0x10000;	// max value for 16 bit counter in mode 2
-	const int min_counter_value = 2;	// min value for 16 bit counter in mode 2
+	const int max_counter_value = 0x10000;	/*  max value for 16 bit counter in mode 2 */
+	const int min_counter_value = 2;	/*  min value for 16 bit counter in mode 2 */
 	unsigned int base_period;
 
-	// if both convert and scan triggers are TRIG_TIMER, then they both rely on counter b0
+	/*  if both convert and scan triggers are TRIG_TIMER, then they both rely on counter b0 */
 	if (labpc_ai_convert_period(cmd) && labpc_ai_scan_period(cmd)) {
-		// pick the lowest b0 divisor value we can (for maximum input clock speed on convert and scan counters)
+		/*  pick the lowest b0 divisor value we can (for maximum input clock speed on convert and scan counters) */
 		devpriv->divisor_b0 = (labpc_ai_scan_period(cmd) - 1) /
 			(LABPC_TIMER_BASE * max_counter_value) + 1;
 		if (devpriv->divisor_b0 < min_counter_value)
@@ -1722,7 +1723,7 @@
 
 		base_period = LABPC_TIMER_BASE * devpriv->divisor_b0;
 
-		// set a0 for conversion frequency and b1 for scan frequency
+		/*  set a0 for conversion frequency and b1 for scan frequency */
 		switch (cmd->flags & TRIG_ROUND_MASK) {
 		default:
 		case TRIG_ROUND_NEAREST:
@@ -1748,7 +1749,7 @@
 				labpc_ai_scan_period(cmd) / base_period;
 			break;
 		}
-		// make sure a0 and b1 values are acceptable
+		/*  make sure a0 and b1 values are acceptable */
 		if (devpriv->divisor_a0 < min_counter_value)
 			devpriv->divisor_a0 = min_counter_value;
 		if (devpriv->divisor_a0 > max_counter_value)
@@ -1757,12 +1758,12 @@
 			devpriv->divisor_b1 = min_counter_value;
 		if (devpriv->divisor_b1 > max_counter_value)
 			devpriv->divisor_b1 = max_counter_value;
-		// write corrected timings to command
+		/*  write corrected timings to command */
 		labpc_set_ai_convert_period(cmd,
 			base_period * devpriv->divisor_a0);
 		labpc_set_ai_scan_period(cmd,
 			base_period * devpriv->divisor_b1);
-		// if only one TRIG_TIMER is used, we can employ the generic cascaded timing functions
+		/*  if only one TRIG_TIMER is used, we can employ the generic cascaded timing functions */
 	} else if (labpc_ai_scan_period(cmd)) {
 		unsigned int scan_period;
 
@@ -1795,51 +1796,51 @@
 	}
 }
 
-// lowlevel write to eeprom/dac
-static void labpc_serial_out(struct comedi_device * dev, unsigned int value,
+/* lowlevel write to eeprom/dac */
+static void labpc_serial_out(struct comedi_device *dev, unsigned int value,
 	unsigned int value_width)
 {
 	int i;
 
 	for (i = 1; i <= value_width; i++) {
-		// clear serial clock
+		/*  clear serial clock */
 		devpriv->command5_bits &= ~SCLOCK_BIT;
-		// send bits most significant bit first
+		/*  send bits most significant bit first */
 		if (value & (1 << (value_width - i)))
 			devpriv->command5_bits |= SDATA_BIT;
 		else
 			devpriv->command5_bits &= ~SDATA_BIT;
-		comedi_udelay(1);
+		udelay(1);
 		devpriv->write_byte(devpriv->command5_bits,
 			dev->iobase + COMMAND5_REG);
-		// set clock to load bit
+		/*  set clock to load bit */
 		devpriv->command5_bits |= SCLOCK_BIT;
-		comedi_udelay(1);
+		udelay(1);
 		devpriv->write_byte(devpriv->command5_bits,
 			dev->iobase + COMMAND5_REG);
 	}
 }
 
-// lowlevel read from eeprom
-static unsigned int labpc_serial_in(struct comedi_device * dev)
+/* lowlevel read from eeprom */
+static unsigned int labpc_serial_in(struct comedi_device *dev)
 {
 	unsigned int value = 0;
 	int i;
-	const int value_width = 8;	// number of bits wide values are
+	const int value_width = 8;	/*  number of bits wide values are */
 
 	for (i = 1; i <= value_width; i++) {
-		// set serial clock
+		/*  set serial clock */
 		devpriv->command5_bits |= SCLOCK_BIT;
-		comedi_udelay(1);
+		udelay(1);
 		devpriv->write_byte(devpriv->command5_bits,
 			dev->iobase + COMMAND5_REG);
-		// clear clock bit
+		/*  clear clock bit */
 		devpriv->command5_bits &= ~SCLOCK_BIT;
-		comedi_udelay(1);
+		udelay(1);
 		devpriv->write_byte(devpriv->command5_bits,
 			dev->iobase + COMMAND5_REG);
-		// read bits most significant bit first
-		comedi_udelay(1);
+		/*  read bits most significant bit first */
+		udelay(1);
 		devpriv->status2_bits =
 			devpriv->read_byte(dev->iobase + STATUS2_REG);
 		if (devpriv->status2_bits & EEPROM_OUT_BIT) {
@@ -1850,46 +1851,46 @@
 	return value;
 }
 
-static unsigned int labpc_eeprom_read(struct comedi_device * dev, unsigned int address)
+static unsigned int labpc_eeprom_read(struct comedi_device *dev, unsigned int address)
 {
 	unsigned int value;
-	const int read_instruction = 0x3;	// bits to tell eeprom to expect a read
-	const int write_length = 8;	// 8 bit write lengths to eeprom
+	const int read_instruction = 0x3;	/*  bits to tell eeprom to expect a read */
+	const int write_length = 8;	/*  8 bit write lengths to eeprom */
 
-	// enable read/write to eeprom
+	/*  enable read/write to eeprom */
 	devpriv->command5_bits &= ~EEPROM_EN_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 	devpriv->command5_bits |= EEPROM_EN_BIT | EEPROM_WRITE_UNPROTECT_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 
-	// send read instruction
+	/*  send read instruction */
 	labpc_serial_out(dev, read_instruction, write_length);
-	// send 8 bit address to read from
+	/*  send 8 bit address to read from */
 	labpc_serial_out(dev, address, write_length);
-	// read result
+	/*  read result */
 	value = labpc_serial_in(dev);
 
-	// disable read/write to eeprom
+	/*  disable read/write to eeprom */
 	devpriv->command5_bits &= ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 
 	return value;
 }
 
-static unsigned int labpc_eeprom_write(struct comedi_device * dev,
+static unsigned int labpc_eeprom_write(struct comedi_device *dev,
 	unsigned int address, unsigned int value)
 {
 	const int write_enable_instruction = 0x6;
 	const int write_instruction = 0x2;
-	const int write_length = 8;	// 8 bit write lengths to eeprom
+	const int write_length = 8;	/*  8 bit write lengths to eeprom */
 	const int write_in_progress_bit = 0x1;
 	const int timeout = 10000;
 	int i;
 
-	// make sure there isn't already a write in progress
+	/*  make sure there isn't already a write in progress */
 	for (i = 0; i < timeout; i++) {
 		if ((labpc_eeprom_read_status(dev) & write_in_progress_bit) ==
 			0)
@@ -1899,96 +1900,96 @@
 		comedi_error(dev, "eeprom write timed out");
 		return -ETIME;
 	}
-	// update software copy of eeprom
+	/*  update software copy of eeprom */
 	devpriv->eeprom_data[address] = value;
 
-	// enable read/write to eeprom
+	/*  enable read/write to eeprom */
 	devpriv->command5_bits &= ~EEPROM_EN_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 	devpriv->command5_bits |= EEPROM_EN_BIT | EEPROM_WRITE_UNPROTECT_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 
-	// send write_enable instruction
+	/*  send write_enable instruction */
 	labpc_serial_out(dev, write_enable_instruction, write_length);
 	devpriv->command5_bits &= ~EEPROM_EN_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 
-	// send write instruction
+	/*  send write instruction */
 	devpriv->command5_bits |= EEPROM_EN_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 	labpc_serial_out(dev, write_instruction, write_length);
-	// send 8 bit address to write to
+	/*  send 8 bit address to write to */
 	labpc_serial_out(dev, address, write_length);
-	// write value
+	/*  write value */
 	labpc_serial_out(dev, value, write_length);
 	devpriv->command5_bits &= ~EEPROM_EN_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 
-	// disable read/write to eeprom
+	/*  disable read/write to eeprom */
 	devpriv->command5_bits &= ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 
 	return 0;
 }
 
-static unsigned int labpc_eeprom_read_status(struct comedi_device * dev)
+static unsigned int labpc_eeprom_read_status(struct comedi_device *dev)
 {
 	unsigned int value;
 	const int read_status_instruction = 0x5;
-	const int write_length = 8;	// 8 bit write lengths to eeprom
+	const int write_length = 8;	/*  8 bit write lengths to eeprom */
 
-	// enable read/write to eeprom
+	/*  enable read/write to eeprom */
 	devpriv->command5_bits &= ~EEPROM_EN_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 	devpriv->command5_bits |= EEPROM_EN_BIT | EEPROM_WRITE_UNPROTECT_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 
-	// send read status instruction
+	/*  send read status instruction */
 	labpc_serial_out(dev, read_status_instruction, write_length);
-	// read result
+	/*  read result */
 	value = labpc_serial_in(dev);
 
-	// disable read/write to eeprom
+	/*  disable read/write to eeprom */
 	devpriv->command5_bits &= ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 
 	return value;
 }
 
-// writes to 8 bit calibration dacs
-static void write_caldac(struct comedi_device * dev, unsigned int channel,
+/* writes to 8 bit calibration dacs */
+static void write_caldac(struct comedi_device *dev, unsigned int channel,
 	unsigned int value)
 {
 	if (value == devpriv->caldac[channel])
 		return;
 	devpriv->caldac[channel] = value;
 
-	// clear caldac load bit and make sure we don't write to eeprom
+	/*  clear caldac load bit and make sure we don't write to eeprom */
 	devpriv->command5_bits &=
 		~CALDAC_LOAD_BIT & ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 
-	// write 4 bit channel
+	/*  write 4 bit channel */
 	labpc_serial_out(dev, channel, 4);
-	// write 8 bit caldac value
+	/*  write 8 bit caldac value */
 	labpc_serial_out(dev, value, 8);
 
-	// set and clear caldac bit to load caldac value
+	/*  set and clear caldac bit to load caldac value */
 	devpriv->command5_bits |= CALDAC_LOAD_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 	devpriv->command5_bits &= ~CALDAC_LOAD_BIT;
-	comedi_udelay(1);
+	udelay(1);
 	devpriv->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
 }
 
diff --git a/drivers/staging/comedi/drivers/ni_labpc.h b/drivers/staging/comedi/drivers/ni_labpc.h
index b44b0d3..c5d2d21 100644
--- a/drivers/staging/comedi/drivers/ni_labpc.h
+++ b/drivers/staging/comedi/drivers/ni_labpc.h
@@ -24,59 +24,59 @@
 #ifndef _NI_LABPC_H
 #define _NI_LABPC_H
 
-#define EEPROM_SIZE	256	// 256 byte eeprom
-#define NUM_AO_CHAN	2	// boards have two analog output channels
+#define EEPROM_SIZE	256	/*  256 byte eeprom */
+#define NUM_AO_CHAN	2	/*  boards have two analog output channels */
 
 enum labpc_bustype { isa_bustype, pci_bustype, pcmcia_bustype };
 enum labpc_register_layout { labpc_plus_layout, labpc_1200_layout };
 enum transfer_type { fifo_not_empty_transfer, fifo_half_full_transfer,
 		isa_dma_transfer };
 
-typedef struct labpc_board_struct {
+struct labpc_board_struct {
 	const char *name;
-	int device_id;		// device id for pci and pcmcia boards
-	int ai_speed;		// maximum input speed in nanoseconds
-	enum labpc_bustype bustype;	// ISA/PCI/etc.
-	enum labpc_register_layout register_layout;	// 1200 has extra registers compared to pc+
-	int has_ao;		// has analog output true/false
+	int device_id;		/*  device id for pci and pcmcia boards */
+	int ai_speed;		/*  maximum input speed in nanoseconds */
+	enum labpc_bustype bustype;	/*  ISA/PCI/etc. */
+	enum labpc_register_layout register_layout;	/*  1200 has extra registers compared to pc+ */
+	int has_ao;		/*  has analog output true/false */
 	const struct comedi_lrange *ai_range_table;
 	const int *ai_range_code;
 	const int *ai_range_is_unipolar;
-	unsigned ai_scan_up:1;	// board can auto scan up in ai channels, not just down
+	unsigned ai_scan_up:1;	/*  board can auto scan up in ai channels, not just down */
 	unsigned memory_mapped_io:1;	/* uses memory mapped io instead of ioports */
-} labpc_board;
+};
 
-typedef struct {
-	struct mite_struct *mite;	// for mite chip on pci-1200
+struct labpc_private {
+	struct mite_struct *mite;	/*  for mite chip on pci-1200 */
 	volatile unsigned long long count;	/* number of data points left to be taken */
-	unsigned int ao_value[NUM_AO_CHAN];	// software copy of analog output values
-	// software copys of bits written to command registers
+	unsigned int ao_value[NUM_AO_CHAN];	/*  software copy of analog output values */
+	/*  software copys of bits written to command registers */
 	volatile unsigned int command1_bits;
 	volatile unsigned int command2_bits;
 	volatile unsigned int command3_bits;
 	volatile unsigned int command4_bits;
 	volatile unsigned int command5_bits;
 	volatile unsigned int command6_bits;
-	// store last read of board status registers
+	/*  store last read of board status registers */
 	volatile unsigned int status1_bits;
 	volatile unsigned int status2_bits;
 	unsigned int divisor_a0;	/* value to load into board's counter a0 (conversion pacing) for timed conversions */
 	unsigned int divisor_b0;	/* value to load into board's counter b0 (master) for timed conversions */
 	unsigned int divisor_b1;	/* value to load into board's counter b1 (scan pacing) for timed conversions */
-	unsigned int dma_chan;	// dma channel to use
-	u16 *dma_buffer;	// buffer ai will dma into
-	unsigned int dma_transfer_size;	// transfer size in bytes for current transfer
-	enum transfer_type current_transfer;	// we are using dma/fifo-half-full/etc.
-	unsigned int eeprom_data[EEPROM_SIZE];	// stores contents of board's eeprom
-	unsigned int caldac[16];	// stores settings of calibration dacs
-	// function pointers so we can use inb/outb or readb/writeb as appropriate
+	unsigned int dma_chan;	/*  dma channel to use */
+	u16 *dma_buffer;	/*  buffer ai will dma into */
+	unsigned int dma_transfer_size;	/*  transfer size in bytes for current transfer */
+	enum transfer_type current_transfer;	/*  we are using dma/fifo-half-full/etc. */
+	unsigned int eeprom_data[EEPROM_SIZE];	/*  stores contents of board's eeprom */
+	unsigned int caldac[16];	/*  stores settings of calibration dacs */
+	/*  function pointers so we can use inb/outb or readb/writeb as appropriate */
 	unsigned int (*read_byte) (unsigned long address);
 	void (*write_byte) (unsigned int byte, unsigned long address);
-} labpc_private;
+};
 
-int labpc_common_attach(struct comedi_device * dev, unsigned long iobase,
+int labpc_common_attach(struct comedi_device *dev, unsigned long iobase,
 	unsigned int irq, unsigned int dma);
-int labpc_common_detach(struct comedi_device * dev);
+int labpc_common_detach(struct comedi_device *dev);
 
 extern const int labpc_1200_is_unipolar[];
 extern const int labpc_1200_ai_gain_bits[];
diff --git a/drivers/staging/comedi/drivers/ni_labpc_cs.c b/drivers/staging/comedi/drivers/ni_labpc_cs.c
index ac0ce2f..fb56c03 100644
--- a/drivers/staging/comedi/drivers/ni_labpc_cs.c
+++ b/drivers/staging/comedi/drivers/ni_labpc_cs.c
@@ -60,7 +60,7 @@
 */
 
 #undef LABPC_DEBUG
-//#define LABPC_DEBUG   // enable debugging messages
+/* #define LABPC_DEBUG */   /*  enable debugging messages */
 
 #include "../comedidev.h"
 
@@ -79,64 +79,64 @@
 
 static struct pcmcia_device *pcmcia_cur_dev = NULL;
 
-static int labpc_attach(struct comedi_device * dev, struct comedi_devconfig * it);
+static int labpc_attach(struct comedi_device *dev, struct comedi_devconfig *it);
 
-static const labpc_board labpc_cs_boards[] = {
+static const struct labpc_board_struct labpc_cs_boards[] = {
 	{
-	      name:	"daqcard-1200",
-	      device_id:0x103,	// 0x10b is manufacturer id, 0x103 is device id
-	      ai_speed:10000,
-	      bustype:	pcmcia_bustype,
-	      register_layout:labpc_1200_layout,
-	      has_ao:	1,
-	      ai_range_table:&range_labpc_1200_ai,
-	      ai_range_code:labpc_1200_ai_gain_bits,
-	      ai_range_is_unipolar:labpc_1200_is_unipolar,
-	      ai_scan_up:0,
-	      memory_mapped_io:0,
+	.name = "daqcard-1200",
+	.device_id = 0x103,	/*  0x10b is manufacturer id, 0x103 is device id */
+	.ai_speed = 10000,
+	.bustype = pcmcia_bustype,
+	.register_layout = labpc_1200_layout,
+	.has_ao = 1,
+	.ai_range_table = &range_labpc_1200_ai,
+	.ai_range_code = labpc_1200_ai_gain_bits,
+	.ai_range_is_unipolar = labpc_1200_is_unipolar,
+	.ai_scan_up = 0,
+	.memory_mapped_io = 0,
 		},
 	/* duplicate entry, to support using alternate name */
 	{
-	      name:	"ni_labpc_cs",
-	      device_id:0x103,
-	      ai_speed:10000,
-	      bustype:	pcmcia_bustype,
-	      register_layout:labpc_1200_layout,
-	      has_ao:	1,
-	      ai_range_table:&range_labpc_1200_ai,
-	      ai_range_code:labpc_1200_ai_gain_bits,
-	      ai_range_is_unipolar:labpc_1200_is_unipolar,
-	      ai_scan_up:0,
-	      memory_mapped_io:0,
+	.name = "ni_labpc_cs",
+	.device_id = 0x103,
+	.ai_speed = 10000,
+	.bustype = pcmcia_bustype,
+	.register_layout = labpc_1200_layout,
+	.has_ao = 1,
+	.ai_range_table = &range_labpc_1200_ai,
+	.ai_range_code = labpc_1200_ai_gain_bits,
+	.ai_range_is_unipolar = labpc_1200_is_unipolar,
+	.ai_scan_up = 0,
+	.memory_mapped_io = 0,
 		},
 };
 
 /*
  * Useful for shorthand access to the particular board structure
  */
-#define thisboard ((const labpc_board *)dev->board_ptr)
+#define thisboard ((const struct labpc_board_struct *)dev->board_ptr)
 
 static struct comedi_driver driver_labpc_cs = {
 	.driver_name = "ni_labpc_cs",
 	.module = THIS_MODULE,
 	.attach = &labpc_attach,
 	.detach = &labpc_common_detach,
-	.num_names = sizeof(labpc_cs_boards) / sizeof(labpc_board),
+	.num_names = ARRAY_SIZE(labpc_cs_boards),
 	.board_name = &labpc_cs_boards[0].name,
-	.offset = sizeof(labpc_board),
+	.offset = sizeof(struct labpc_board_struct),
 };
 
-static int labpc_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int labpc_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	unsigned long iobase = 0;
 	unsigned int irq = 0;
 	struct pcmcia_device *link;
 
 	/* allocate and initialize dev->private */
-	if (alloc_private(dev, sizeof(labpc_private)) < 0)
+	if (alloc_private(dev, sizeof(struct labpc_private)) < 0)
 		return -ENOMEM;
 
-	// get base address, irq etc. based on bustype
+	/*  get base address, irq etc. based on bustype */
 	switch (thisboard->bustype) {
 	case pcmcia_bustype:
 		link = pcmcia_cur_dev;	/* XXX hack */
@@ -213,12 +213,12 @@
 
 static const dev_info_t dev_info = "daqcard-1200";
 
-typedef struct local_info_t {
+struct local_info_t {
 	struct pcmcia_device *link;
 	dev_node_t node;
 	int stop;
 	struct bus_operations *bus;
-} local_info_t;
+};
 
 /*======================================================================
 
@@ -234,12 +234,12 @@
 
 static int labpc_cs_attach(struct pcmcia_device *link)
 {
-	local_info_t *local;
+	struct local_info_t *local;
 
 	DEBUG(0, "labpc_cs_attach()\n");
 
 	/* Allocate space for private device-specific data */
-	local = kzalloc(sizeof(local_info_t), GFP_KERNEL);
+	local = kzalloc(sizeof(struct local_info_t), GFP_KERNEL);
 	if (!local)
 		return -ENOMEM;
 	local->link = link;
@@ -287,7 +287,7 @@
 	   detach().
 	 */
 	if (link->dev_node) {
-		((local_info_t *) link->priv)->stop = 1;
+		((struct local_info_t *) link->priv)->stop = 1;
 		labpc_release(link);
 	}
 
@@ -307,7 +307,7 @@
 
 static void labpc_config(struct pcmcia_device *link)
 {
-	local_info_t *dev = link->priv;
+	struct local_info_t *dev = link->priv;
 	tuple_t tuple;
 	cisparse_t parse;
 	int last_ret;
@@ -327,15 +327,21 @@
 	tuple.TupleData = buf;
 	tuple.TupleDataMax = sizeof(buf);
 	tuple.TupleOffset = 0;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple))) {
+
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret) {
 		cs_error(link, GetFirstTuple, last_ret);
 		goto cs_failed;
 	}
-	if ((last_ret = pcmcia_get_tuple_data(link, &tuple))) {
+
+	last_ret = pcmcia_get_tuple_data(link, &tuple);
+	if (last_ret) {
 		cs_error(link, GetTupleData, last_ret);
 		goto cs_failed;
 	}
-	if ((last_ret = pcmcia_parse_tuple(&tuple, &parse))) {
+
+	last_ret = pcmcia_parse_tuple(&tuple, &parse);
+	if (last_ret) {
 		cs_error(link, ParseTuple, last_ret);
 		goto cs_failed;
 	}
@@ -355,7 +361,8 @@
 	   will only use the CIS to fill in implementation-defined details.
 	 */
 	tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple))) {
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret) {
 		cs_error(link, GetFirstTuple, last_ret);
 		goto cs_failed;
 	}
@@ -422,7 +429,8 @@
 		break;
 
 	      next_entry:
-		if ((last_ret = pcmcia_get_next_tuple(link, &tuple))) {
+		last_ret = pcmcia_get_next_tuple(link, &tuple);
+		if (last_ret) {
 			cs_error(link, GetNextTuple, last_ret);
 			goto cs_failed;
 		}
@@ -433,18 +441,21 @@
 	   handler to the interrupt, unless the 'Handler' member of the
 	   irq structure is initialized.
 	 */
-	if (link->conf.Attributes & CONF_ENABLE_IRQ)
-		if ((last_ret = pcmcia_request_irq(link, &link->irq))) {
+	if (link->conf.Attributes & CONF_ENABLE_IRQ) {
+		last_ret = pcmcia_request_irq(link, &link->irq);
+		if (last_ret) {
 			cs_error(link, RequestIRQ, last_ret);
 			goto cs_failed;
 		}
+	}
 
 	/*
 	   This actually configures the PCMCIA socket -- setting up
 	   the I/O windows and the interrupt mapping, and putting the
 	   card and host interface into "Memory and IO" mode.
 	 */
-	if ((last_ret = pcmcia_request_configuration(link, &link->conf))) {
+	last_ret = pcmcia_request_configuration(link, &link->conf);
+	if (last_ret) {
 		cs_error(link, RequestConfiguration, last_ret);
 		goto cs_failed;
 	}
@@ -501,7 +512,7 @@
 
 static int labpc_cs_suspend(struct pcmcia_device *link)
 {
-	local_info_t *local = link->priv;
+	struct local_info_t *local = link->priv;
 
 	/* Mark the device as stopped, to block IO until later */
 	local->stop = 1;
@@ -510,7 +521,7 @@
 
 static int labpc_cs_resume(struct pcmcia_device *link)
 {
-	local_info_t *local = link->priv;
+	struct local_info_t *local = link->priv;
 
 	local->stop = 0;
 	return 0;
diff --git a/drivers/staging/comedi/drivers/ni_mio_common.c b/drivers/staging/comedi/drivers/ni_mio_common.c
index 542bd0d..d727d75 100644
--- a/drivers/staging/comedi/drivers/ni_mio_common.c
+++ b/drivers/staging/comedi/drivers/ni_mio_common.c
@@ -57,16 +57,17 @@
 		fully tested as yet. Terry Barnaby, BEAM Ltd.
 */
 
-//#define DEBUG_INTERRUPT
-//#define DEBUG_STATUS_A
-//#define DEBUG_STATUS_B
+/* #define DEBUG_INTERRUPT */
+/* #define DEBUG_STATUS_A */
+/* #define DEBUG_STATUS_B */
 
+#include <linux/interrupt.h>
 #include "8255.h"
 #include "mite.h"
 #include "comedi_fc.h"
 
 #ifndef MDPRINTK
-#define MDPRINTK(format,args...)
+#define MDPRINTK(format, args...)
 #endif
 
 /* A timeout count */
@@ -193,49 +194,49 @@
 	[ai_gain_6143] = &range_ni_S_ai_6143
 };
 
-static int ni_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_cdio_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int ni_cdio_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int ni_cdio_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static void handle_cdio_interrupt(struct comedi_device * dev);
-static int ni_cdo_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_cdio_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int ni_cdio_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int ni_cdio_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static void handle_cdio_interrupt(struct comedi_device *dev);
+static int ni_cdo_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum);
 
-static int ni_serial_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_serial_hw_readwrite8(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_serial_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_serial_hw_readwrite8(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned char data_out, unsigned char *data_in);
-static int ni_serial_sw_readwrite8(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_serial_sw_readwrite8(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned char data_out, unsigned char *data_in);
 
-static int ni_calib_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_calib_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int ni_calib_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_calib_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int ni_eeprom_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_m_series_eeprom_insn_read(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
+static int ni_eeprom_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_m_series_eeprom_insn_read(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
 
-static int ni_pfi_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_pfi_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static unsigned ni_old_get_pfi_routing(struct comedi_device * dev, unsigned chan);
+static int ni_pfi_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_pfi_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static unsigned ni_old_get_pfi_routing(struct comedi_device *dev, unsigned chan);
 
-static void ni_rtsi_init(struct comedi_device * dev);
-static int ni_rtsi_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_rtsi_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static void ni_rtsi_init(struct comedi_device *dev);
+static int ni_rtsi_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_rtsi_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static void caldac_setup(struct comedi_device * dev, struct comedi_subdevice * s);
-static int ni_read_eeprom(struct comedi_device * dev, int addr);
+static void caldac_setup(struct comedi_device *dev, struct comedi_subdevice *s);
+static int ni_read_eeprom(struct comedi_device *dev, int addr);
 
 #ifdef DEBUG_STATUS_A
 static void ni_mio_print_status_a(int status);
@@ -248,58 +249,58 @@
 #define ni_mio_print_status_b(a)
 #endif
 
-static int ni_ai_reset(struct comedi_device * dev, struct comedi_subdevice * s);
+static int ni_ai_reset(struct comedi_device *dev, struct comedi_subdevice *s);
 #ifndef PCIDMA
-static void ni_handle_fifo_half_full(struct comedi_device * dev);
-static int ni_ao_fifo_half_empty(struct comedi_device * dev, struct comedi_subdevice * s);
+static void ni_handle_fifo_half_full(struct comedi_device *dev);
+static int ni_ao_fifo_half_empty(struct comedi_device *dev, struct comedi_subdevice *s);
 #endif
-static void ni_handle_fifo_dregs(struct comedi_device * dev);
-static int ni_ai_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
+static void ni_handle_fifo_dregs(struct comedi_device *dev);
+static int ni_ai_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum);
-static void ni_load_channelgain_list(struct comedi_device * dev, unsigned int n_chan,
+static void ni_load_channelgain_list(struct comedi_device *dev, unsigned int n_chan,
 	unsigned int *list);
-static void shutdown_ai_command(struct comedi_device * dev);
+static void shutdown_ai_command(struct comedi_device *dev);
 
-static int ni_ao_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_ao_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum);
 
-static int ni_ao_reset(struct comedi_device * dev, struct comedi_subdevice * s);
+static int ni_ao_reset(struct comedi_device *dev, struct comedi_subdevice *s);
 
 static int ni_8255_callback(int dir, int port, int data, unsigned long arg);
 
-static int ni_gpct_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_gpct_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_gpct_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_gpct_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int ni_gpct_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int ni_gpct_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static void handle_gpct_interrupt(struct comedi_device * dev,
+static int ni_gpct_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_gpct_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_gpct_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_gpct_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int ni_gpct_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int ni_gpct_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static void handle_gpct_interrupt(struct comedi_device *dev,
 	unsigned short counter_index);
 
-static int init_cs5529(struct comedi_device * dev);
-static int cs5529_do_conversion(struct comedi_device * dev, unsigned short *data);
-static int cs5529_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int init_cs5529(struct comedi_device *dev);
+static int cs5529_do_conversion(struct comedi_device *dev, unsigned short *data);
+static int cs5529_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 #ifdef NI_CS5529_DEBUG
-static unsigned int cs5529_config_read(struct comedi_device * dev,
+static unsigned int cs5529_config_read(struct comedi_device *dev,
 	unsigned int reg_select_bits);
 #endif
-static void cs5529_config_write(struct comedi_device * dev, unsigned int value,
+static void cs5529_config_write(struct comedi_device *dev, unsigned int value,
 	unsigned int reg_select_bits);
 
-static int ni_m_series_pwm_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ni_6143_pwm_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int ni_m_series_pwm_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ni_6143_pwm_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int ni_set_master_clock(struct comedi_device * dev, unsigned source,
+static int ni_set_master_clock(struct comedi_device *dev, unsigned source,
 	unsigned period_ns);
-static void ack_a_interrupt(struct comedi_device * dev, unsigned short a_status);
-static void ack_b_interrupt(struct comedi_device * dev, unsigned short b_status);
+static void ack_a_interrupt(struct comedi_device *dev, unsigned short a_status);
+static void ack_b_interrupt(struct comedi_device *dev, unsigned short b_status);
 
 enum aimodes {
 	AIMODE_NONE = 0,
@@ -353,19 +354,19 @@
 
 static const int num_adc_stages_611x = 3;
 
-static void handle_a_interrupt(struct comedi_device * dev, unsigned short status,
+static void handle_a_interrupt(struct comedi_device *dev, unsigned short status,
 	unsigned ai_mite_status);
-static void handle_b_interrupt(struct comedi_device * dev, unsigned short status,
+static void handle_b_interrupt(struct comedi_device *dev, unsigned short status,
 	unsigned ao_mite_status);
-static void get_last_sample_611x(struct comedi_device * dev);
-static void get_last_sample_6143(struct comedi_device * dev);
+static void get_last_sample_611x(struct comedi_device *dev);
+static void get_last_sample_6143(struct comedi_device *dev);
 
-static inline void ni_set_bitfield(struct comedi_device * dev, int reg,
+static inline void ni_set_bitfield(struct comedi_device *dev, int reg,
 	unsigned bit_mask, unsigned bit_values)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->soft_reg_copy_lock, flags);
+	spin_lock_irqsave(&devpriv->soft_reg_copy_lock, flags);
 	switch (reg) {
 	case Interrupt_A_Enable_Register:
 		devpriv->int_a_enable_reg &= ~bit_mask;
@@ -396,22 +397,22 @@
 		ni_writeb(devpriv->g0_g1_select_reg, G0_G1_Select);
 		break;
 	default:
-		rt_printk("Warning %s() called with invalid register\n",
-			__FUNCTION__);
-		rt_printk("reg is %d\n", reg);
+		printk("Warning %s() called with invalid register\n",
+			__func__);
+		printk("reg is %d\n", reg);
 		break;
 	}
 	mmiowb();
-	comedi_spin_unlock_irqrestore(&devpriv->soft_reg_copy_lock, flags);
+	spin_unlock_irqrestore(&devpriv->soft_reg_copy_lock, flags);
 }
 
 #ifdef PCIDMA
-static int ni_ai_drain_dma(struct comedi_device * dev);
+static int ni_ai_drain_dma(struct comedi_device *dev);
 
 /* DMA channel setup */
 
-// negative channel means no channel
-static inline void ni_set_ai_dma_channel(struct comedi_device * dev, int channel)
+/* negative channel means no channel */
+static inline void ni_set_ai_dma_channel(struct comedi_device *dev, int channel)
 {
 	unsigned bitfield;
 
@@ -425,8 +426,8 @@
 	ni_set_bitfield(dev, AI_AO_Select, AI_DMA_Select_Mask, bitfield);
 }
 
-// negative channel means no channel
-static inline void ni_set_ao_dma_channel(struct comedi_device * dev, int channel)
+/* negative channel means no channel */
+static inline void ni_set_ao_dma_channel(struct comedi_device *dev, int channel)
 {
 	unsigned bitfield;
 
@@ -440,8 +441,8 @@
 	ni_set_bitfield(dev, AI_AO_Select, AO_DMA_Select_Mask, bitfield);
 }
 
-// negative mite_channel means no channel
-static inline void ni_set_gpct_dma_channel(struct comedi_device * dev,
+/* negative mite_channel means no channel */
+static inline void ni_set_gpct_dma_channel(struct comedi_device *dev,
 	unsigned gpct_index, int mite_channel)
 {
 	unsigned bitfield;
@@ -455,12 +456,12 @@
 		bitfield);
 }
 
-// negative mite_channel means no channel
-static inline void ni_set_cdo_dma_channel(struct comedi_device * dev, int mite_channel)
+/* negative mite_channel means no channel */
+static inline void ni_set_cdo_dma_channel(struct comedi_device *dev, int mite_channel)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->soft_reg_copy_lock, flags);
+	spin_lock_irqsave(&devpriv->soft_reg_copy_lock, flags);
 	devpriv->cdio_dma_select_reg &= ~CDO_DMA_Select_Mask;
 	if (mite_channel >= 0) {
 		/*XXX just guessing ni_stc_dma_channel_select_bitfield() returns the right bits,
@@ -472,19 +473,19 @@
 	}
 	ni_writeb(devpriv->cdio_dma_select_reg, M_Offset_CDIO_DMA_Select);
 	mmiowb();
-	comedi_spin_unlock_irqrestore(&devpriv->soft_reg_copy_lock, flags);
+	spin_unlock_irqrestore(&devpriv->soft_reg_copy_lock, flags);
 }
 
-static int ni_request_ai_mite_channel(struct comedi_device * dev)
+static int ni_request_ai_mite_channel(struct comedi_device *dev)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	BUG_ON(devpriv->ai_mite_chan);
 	devpriv->ai_mite_chan =
 		mite_request_channel(devpriv->mite, devpriv->ai_mite_ring);
 	if (devpriv->ai_mite_chan == NULL) {
-		comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock,
+		spin_unlock_irqrestore(&devpriv->mite_channel_lock,
 			flags);
 		comedi_error(dev,
 			"failed to reserve mite dma channel for analog input.");
@@ -492,20 +493,20 @@
 	}
 	devpriv->ai_mite_chan->dir = COMEDI_INPUT;
 	ni_set_ai_dma_channel(dev, devpriv->ai_mite_chan->channel);
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 	return 0;
 }
 
-static int ni_request_ao_mite_channel(struct comedi_device * dev)
+static int ni_request_ao_mite_channel(struct comedi_device *dev)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	BUG_ON(devpriv->ao_mite_chan);
 	devpriv->ao_mite_chan =
 		mite_request_channel(devpriv->mite, devpriv->ao_mite_ring);
 	if (devpriv->ao_mite_chan == NULL) {
-		comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock,
+		spin_unlock_irqrestore(&devpriv->mite_channel_lock,
 			flags);
 		comedi_error(dev,
 			"failed to reserve mite dma channel for analog outut.");
@@ -513,24 +514,24 @@
 	}
 	devpriv->ao_mite_chan->dir = COMEDI_OUTPUT;
 	ni_set_ao_dma_channel(dev, devpriv->ao_mite_chan->channel);
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 	return 0;
 }
 
-static int ni_request_gpct_mite_channel(struct comedi_device * dev,
+static int ni_request_gpct_mite_channel(struct comedi_device *dev,
 	unsigned gpct_index, enum comedi_io_direction direction)
 {
 	unsigned long flags;
 	struct mite_channel *mite_chan;
 
 	BUG_ON(gpct_index >= NUM_GPCT);
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	BUG_ON(devpriv->counter_dev->counters[gpct_index].mite_chan);
 	mite_chan =
 		mite_request_channel(devpriv->mite,
 		devpriv->gpct_mite_ring[gpct_index]);
 	if (mite_chan == NULL) {
-		comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock,
+		spin_unlock_irqrestore(&devpriv->mite_channel_lock,
 			flags);
 		comedi_error(dev,
 			"failed to reserve mite dma channel for counter.");
@@ -540,23 +541,23 @@
 	ni_tio_set_mite_channel(&devpriv->counter_dev->counters[gpct_index],
 		mite_chan);
 	ni_set_gpct_dma_channel(dev, gpct_index, mite_chan->channel);
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 	return 0;
 }
 
-#endif // PCIDMA
+#endif /*  PCIDMA */
 
-static int ni_request_cdo_mite_channel(struct comedi_device * dev)
+static int ni_request_cdo_mite_channel(struct comedi_device *dev)
 {
 #ifdef PCIDMA
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	BUG_ON(devpriv->cdo_mite_chan);
 	devpriv->cdo_mite_chan =
 		mite_request_channel(devpriv->mite, devpriv->cdo_mite_ring);
 	if (devpriv->cdo_mite_chan == NULL) {
-		comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock,
+		spin_unlock_irqrestore(&devpriv->mite_channel_lock,
 			flags);
 		comedi_error(dev,
 			"failed to reserve mite dma channel for correlated digital outut.");
@@ -564,48 +565,48 @@
 	}
 	devpriv->cdo_mite_chan->dir = COMEDI_OUTPUT;
 	ni_set_cdo_dma_channel(dev, devpriv->cdo_mite_chan->channel);
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
-#endif // PCIDMA
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+#endif /*  PCIDMA */
 	return 0;
 }
 
-static void ni_release_ai_mite_channel(struct comedi_device * dev)
+static void ni_release_ai_mite_channel(struct comedi_device *dev)
 {
 #ifdef PCIDMA
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	if (devpriv->ai_mite_chan) {
 		ni_set_ai_dma_channel(dev, -1);
 		mite_release_channel(devpriv->ai_mite_chan);
 		devpriv->ai_mite_chan = NULL;
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
-#endif // PCIDMA
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+#endif /*  PCIDMA */
 }
 
-static void ni_release_ao_mite_channel(struct comedi_device * dev)
+static void ni_release_ao_mite_channel(struct comedi_device *dev)
 {
 #ifdef PCIDMA
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	if (devpriv->ao_mite_chan) {
 		ni_set_ao_dma_channel(dev, -1);
 		mite_release_channel(devpriv->ao_mite_chan);
 		devpriv->ao_mite_chan = NULL;
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
-#endif // PCIDMA
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+#endif /*  PCIDMA */
 }
 
-void ni_release_gpct_mite_channel(struct comedi_device * dev, unsigned gpct_index)
+void ni_release_gpct_mite_channel(struct comedi_device *dev, unsigned gpct_index)
 {
 #ifdef PCIDMA
 	unsigned long flags;
 
 	BUG_ON(gpct_index >= NUM_GPCT);
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	if (devpriv->counter_dev->counters[gpct_index].mite_chan) {
 		struct mite_channel *mite_chan =
 			devpriv->counter_dev->counters[gpct_index].mite_chan;
@@ -615,28 +616,28 @@
 			counters[gpct_index], NULL);
 		mite_release_channel(mite_chan);
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
-#endif // PCIDMA
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+#endif /*  PCIDMA */
 }
 
-static void ni_release_cdo_mite_channel(struct comedi_device * dev)
+static void ni_release_cdo_mite_channel(struct comedi_device *dev)
 {
 #ifdef PCIDMA
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	if (devpriv->cdo_mite_chan) {
 		ni_set_cdo_dma_channel(dev, -1);
 		mite_release_channel(devpriv->cdo_mite_chan);
 		devpriv->cdo_mite_chan = NULL;
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
-#endif // PCIDMA
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+#endif /*  PCIDMA */
 }
 
-// e-series boards use the second irq signals to generate dma requests for their counters
+/* e-series boards use the second irq signals to generate dma requests for their counters */
 #ifdef PCIDMA
-static void ni_e_series_enable_second_irq(struct comedi_device * dev,
+static void ni_e_series_enable_second_irq(struct comedi_device *dev,
 	unsigned gpct_index, short enable)
 {
 	if (boardtype.reg_type & ni_reg_m_series_mask)
@@ -665,15 +666,15 @@
 		break;
 	}
 }
-#endif // PCIDMA
+#endif /*  PCIDMA */
 
-static void ni_clear_ai_fifo(struct comedi_device * dev)
+static void ni_clear_ai_fifo(struct comedi_device *dev)
 {
 	if (boardtype.reg_type == ni_reg_6143) {
-		// Flush the 6143 data FIFO
-		ni_writel(0x10, AIFIFO_Control_6143);	// Flush fifo
-		ni_writel(0x00, AIFIFO_Control_6143);	// Flush fifo
-		while (ni_readl(AIFIFO_Status_6143) & 0x10) ;	// Wait for complete
+		/*  Flush the 6143 data FIFO */
+		ni_writel(0x10, AIFIFO_Control_6143);	/*  Flush fifo */
+		ni_writel(0x00, AIFIFO_Control_6143);	/*  Flush fifo */
+		while (ni_readl(AIFIFO_Status_6143) & 0x10) ;	/*  Wait for complete */
 	} else {
 		devpriv->stc_writew(dev, 1, ADC_FIFO_Clear);
 		if (boardtype.reg_type == ni_reg_625x) {
@@ -693,13 +694,13 @@
 	}
 }
 
-static void win_out2(struct comedi_device * dev, uint32_t data, int reg)
+static void win_out2(struct comedi_device *dev, uint32_t data, int reg)
 {
 	devpriv->stc_writew(dev, data >> 16, reg);
 	devpriv->stc_writew(dev, data & 0xffff, reg + 1);
 }
 
-static uint32_t win_in2(struct comedi_device * dev, int reg)
+static uint32_t win_in2(struct comedi_device *dev, int reg)
 {
 	uint32_t bits;
 	bits = devpriv->stc_readw(dev, reg) << 16;
@@ -707,36 +708,36 @@
 	return bits;
 }
 
-#define ao_win_out(data,addr) ni_ao_win_outw(dev,data,addr)
-static inline void ni_ao_win_outw(struct comedi_device * dev, uint16_t data, int addr)
+#define ao_win_out(data, addr) ni_ao_win_outw(dev, data, addr)
+static inline void ni_ao_win_outw(struct comedi_device *dev, uint16_t data, int addr)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->window_lock, flags);
+	spin_lock_irqsave(&devpriv->window_lock, flags);
 	ni_writew(addr, AO_Window_Address_611x);
 	ni_writew(data, AO_Window_Data_611x);
-	comedi_spin_unlock_irqrestore(&devpriv->window_lock, flags);
+	spin_unlock_irqrestore(&devpriv->window_lock, flags);
 }
 
-static inline void ni_ao_win_outl(struct comedi_device * dev, uint32_t data, int addr)
+static inline void ni_ao_win_outl(struct comedi_device *dev, uint32_t data, int addr)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->window_lock, flags);
+	spin_lock_irqsave(&devpriv->window_lock, flags);
 	ni_writew(addr, AO_Window_Address_611x);
 	ni_writel(data, AO_Window_Data_611x);
-	comedi_spin_unlock_irqrestore(&devpriv->window_lock, flags);
+	spin_unlock_irqrestore(&devpriv->window_lock, flags);
 }
 
-static inline unsigned short ni_ao_win_inw(struct comedi_device * dev, int addr)
+static inline unsigned short ni_ao_win_inw(struct comedi_device *dev, int addr)
 {
 	unsigned long flags;
 	unsigned short data;
 
-	comedi_spin_lock_irqsave(&devpriv->window_lock, flags);
+	spin_lock_irqsave(&devpriv->window_lock, flags);
 	ni_writew(addr, AO_Window_Address_611x);
 	data = ni_readw(AO_Window_Data_611x);
-	comedi_spin_unlock_irqrestore(&devpriv->window_lock, flags);
+	spin_unlock_irqrestore(&devpriv->window_lock, flags);
 	return data;
 }
 
@@ -750,7 +751,7 @@
 *
 * value should only be 1 or 0.
 */
-static inline void ni_set_bits(struct comedi_device * dev, int reg, unsigned bits,
+static inline void ni_set_bits(struct comedi_device *dev, int reg, unsigned bits,
 	unsigned value)
 {
 	unsigned bit_values;
@@ -762,7 +763,7 @@
 	ni_set_bitfield(dev, reg, bits, bit_values);
 }
 
-static irqreturn_t ni_E_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t ni_E_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	unsigned short a_status;
@@ -776,18 +777,17 @@
 
 	if (dev->attached == 0)
 		return IRQ_NONE;
-	smp_mb();		// make sure dev->attached is checked before handler does anything else.
+	smp_mb();		/*  make sure dev->attached is checked before handler does anything else. */
 
-	// lock to avoid race with comedi_poll
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	/*  lock to avoid race with comedi_poll */
+	spin_lock_irqsave(&dev->spinlock, flags);
 	a_status = devpriv->stc_readw(dev, AI_Status_1_Register);
 	b_status = devpriv->stc_readw(dev, AO_Status_1_Register);
 #ifdef PCIDMA
 	if (mite) {
 		unsigned long flags_too;
 
-		comedi_spin_lock_irqsave(&devpriv->mite_channel_lock,
-			flags_too);
+		spin_lock_irqsave(&devpriv->mite_channel_lock, flags_too);
 		if (devpriv->ai_mite_chan) {
 			ai_mite_status = mite_get_status(devpriv->ai_mite_chan);
 			if (ai_mite_status & CHSR_LINKC)
@@ -804,8 +804,7 @@
 					MITE_CHOR(devpriv->ao_mite_chan->
 						channel));
 		}
-		comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock,
-			flags_too);
+		spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags_too);
 	}
 #endif
 	ack_a_interrupt(dev, a_status);
@@ -818,20 +817,20 @@
 	handle_gpct_interrupt(dev, 1);
 	handle_cdio_interrupt(dev);
 
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 	return IRQ_HANDLED;
 }
 
 #ifdef PCIDMA
-static void ni_sync_ai_dma(struct comedi_device * dev)
+static void ni_sync_ai_dma(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s = dev->subdevices + NI_AI_SUBDEV;
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	if (devpriv->ai_mite_chan)
 		mite_sync_input_dma(devpriv->ai_mite_chan, s->async);
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 }
 
 static void mite_handle_b_linkc(struct mite_struct *mite, struct comedi_device * dev)
@@ -839,14 +838,14 @@
 	struct comedi_subdevice *s = dev->subdevices + NI_AO_SUBDEV;
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	if (devpriv->ao_mite_chan) {
 		mite_sync_output_dma(devpriv->ao_mite_chan, s->async);
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 }
 
-static int ni_ao_wait_for_dma_load(struct comedi_device * dev)
+static int ni_ao_wait_for_dma_load(struct comedi_device *dev)
 {
 	static const int timeout = 10000;
 	int i;
@@ -858,7 +857,7 @@
 			break;
 		/* if we poll too often, the pci bus activity seems
 		   to slow the dma transfer down */
-		comedi_udelay(10);
+		udelay(10);
 	}
 	if (i == timeout) {
 		comedi_error(dev, "timed out waiting for dma load");
@@ -867,8 +866,8 @@
 	return 0;
 }
 
-#endif //PCIDMA
-static void ni_handle_eos(struct comedi_device * dev, struct comedi_subdevice * s)
+#endif /* PCIDMA */
+static void ni_handle_eos(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	if (devpriv->aimode == AIMODE_SCAN) {
 #ifdef PCIDMA
@@ -879,7 +878,7 @@
 			ni_sync_ai_dma(dev);
 			if ((s->async->events & COMEDI_CB_EOS))
 				break;
-			comedi_udelay(1);
+			udelay(1);
 		}
 #else
 		ni_handle_fifo_dregs(dev);
@@ -892,7 +891,7 @@
 	}
 }
 
-static void shutdown_ai_command(struct comedi_device * dev)
+static void shutdown_ai_command(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s = dev->subdevices + NI_AI_SUBDEV;
 
@@ -906,7 +905,7 @@
 	s->async->events |= COMEDI_CB_EOA;
 }
 
-static void ni_event(struct comedi_device * dev, struct comedi_subdevice * s)
+static void ni_event(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	if (s->async->
 		events & (COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW | COMEDI_CB_EOA))
@@ -932,7 +931,7 @@
 	comedi_event(dev, s);
 }
 
-static void handle_gpct_interrupt(struct comedi_device * dev,
+static void handle_gpct_interrupt(struct comedi_device *dev,
 	unsigned short counter_index)
 {
 #ifdef PCIDMA
@@ -945,7 +944,7 @@
 #endif
 }
 
-static void ack_a_interrupt(struct comedi_device * dev, unsigned short a_status)
+static void ack_a_interrupt(struct comedi_device *dev, unsigned short a_status)
 {
 	unsigned short ack = 0;
 
@@ -966,17 +965,17 @@
 		devpriv->stc_writew(dev, ack, Interrupt_A_Ack_Register);
 }
 
-static void handle_a_interrupt(struct comedi_device * dev, unsigned short status,
+static void handle_a_interrupt(struct comedi_device *dev, unsigned short status,
 	unsigned ai_mite_status)
 {
 	struct comedi_subdevice *s = dev->subdevices + NI_AI_SUBDEV;
 
-	//67xx boards don't have ai subdevice, but their gpct0 might generate an a interrupt
+	/* 67xx boards don't have ai subdevice, but their gpct0 might generate an a interrupt */
 	if (s->type == COMEDI_SUBD_UNUSED)
 		return;
 
 #ifdef DEBUG_INTERRUPT
-	rt_printk
+	printk
 		("ni_mio_common: interrupt: a_status=%04x ai_mite_status=%08x\n",
 		status, ai_mite_status);
 	ni_mio_print_status_a(status);
@@ -989,12 +988,12 @@
 	if (ai_mite_status & ~(CHSR_INT | CHSR_LINKC | CHSR_DONE | CHSR_MRDY |
 			CHSR_DRDY | CHSR_DRQ1 | CHSR_DRQ0 | CHSR_ERROR |
 			CHSR_SABORT | CHSR_XFERR | CHSR_LxERR_mask)) {
-		rt_printk
+		printk
 			("unknown mite interrupt, ack! (ai_mite_status=%08x)\n",
 			ai_mite_status);
-		//mite_print_chsr(ai_mite_status);
+		/* mite_print_chsr(ai_mite_status); */
 		s->async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
-		//disable_irq(dev->irq);
+		/* disable_irq(dev->irq); */
 	}
 #endif
 
@@ -1002,7 +1001,7 @@
 	if (status & (AI_Overrun_St | AI_Overflow_St | AI_SC_TC_Error_St |
 			AI_SC_TC_St | AI_START1_St)) {
 		if (status == 0xffff) {
-			rt_printk
+			printk
 				("ni_mio_common: a_status=0xffff.  Card removed?\n");
 			/* we probably aren't even running a command now,
 			 * so it's a good idea to be careful. */
@@ -1015,7 +1014,7 @@
 		}
 		if (status & (AI_Overrun_St | AI_Overflow_St |
 				AI_SC_TC_Error_St)) {
-			rt_printk("ni_mio_common: ai error a_status=%04x\n",
+			printk("ni_mio_common: ai error a_status=%04x\n",
 				status);
 			ni_mio_print_status_a(status);
 
@@ -1031,7 +1030,7 @@
 		}
 		if (status & AI_SC_TC_St) {
 #ifdef DEBUG_INTERRUPT
-			rt_printk("ni_mio_common: SC_TC interrupt\n");
+			printk("ni_mio_common: SC_TC interrupt\n");
 #endif
 			if (!devpriv->ai_continuous) {
 				shutdown_ai_command(dev);
@@ -1052,7 +1051,7 @@
 				break;
 		}
 	}
-#endif // !PCIDMA
+#endif /*  !PCIDMA */
 
 	if ((status & AI_STOP_St)) {
 		ni_handle_eos(dev, s);
@@ -1063,14 +1062,14 @@
 #ifdef DEBUG_INTERRUPT
 	status = devpriv->stc_readw(dev, AI_Status_1_Register);
 	if (status & Interrupt_A_St) {
-		rt_printk
+		printk
 			("handle_a_interrupt: didn't clear interrupt? status=0x%x\n",
 			status);
 	}
 #endif
 }
 
-static void ack_b_interrupt(struct comedi_device * dev, unsigned short b_status)
+static void ack_b_interrupt(struct comedi_device *dev, unsigned short b_status)
 {
 	unsigned short ack = 0;
 	if (b_status & AO_BC_TC_St) {
@@ -1098,13 +1097,13 @@
 		devpriv->stc_writew(dev, ack, Interrupt_B_Ack_Register);
 }
 
-static void handle_b_interrupt(struct comedi_device * dev, unsigned short b_status,
+static void handle_b_interrupt(struct comedi_device *dev, unsigned short b_status,
 	unsigned ao_mite_status)
 {
 	struct comedi_subdevice *s = dev->subdevices + NI_AO_SUBDEV;
-	//unsigned short ack=0;
+	/* unsigned short ack=0; */
 #ifdef DEBUG_INTERRUPT
-	rt_printk("ni_mio_common: interrupt: b_status=%04x m1_status=%08x\n",
+	printk("ni_mio_common: interrupt: b_status=%04x m1_status=%08x\n",
 		b_status, ao_mite_status);
 	ni_mio_print_status_b(b_status);
 #endif
@@ -1118,10 +1117,10 @@
 	if (ao_mite_status & ~(CHSR_INT | CHSR_LINKC | CHSR_DONE | CHSR_MRDY |
 			CHSR_DRDY | CHSR_DRQ1 | CHSR_DRQ0 | CHSR_ERROR |
 			CHSR_SABORT | CHSR_XFERR | CHSR_LxERR_mask)) {
-		rt_printk
+		printk
 			("unknown mite interrupt, ack! (ao_mite_status=%08x)\n",
 			ao_mite_status);
-		//mite_print_chsr(ao_mite_status);
+		/* mite_print_chsr(ao_mite_status); */
 		s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
 	}
 #endif
@@ -1129,7 +1128,7 @@
 	if (b_status == 0xffff)
 		return;
 	if (b_status & AO_Overrun_St) {
-		rt_printk
+		printk
 			("ni_mio_common: AO FIFO underrun status=0x%04x status2=0x%04x\n",
 			b_status, devpriv->stc_readw(dev,
 				AO_Status_2_Register));
@@ -1146,7 +1145,7 @@
 
 		ret = ni_ao_fifo_half_empty(dev, s);
 		if (!ret) {
-			rt_printk("ni_mio_common: AO buffer underrun\n");
+			printk("ni_mio_common: AO buffer underrun\n");
 			ni_set_bits(dev, Interrupt_B_Enable_Register,
 				AO_FIFO_Interrupt_Enable |
 				AO_Error_Interrupt_Enable, 0);
@@ -1170,13 +1169,13 @@
 {
 	int i;
 
-	rt_printk("A status:");
+	printk("A status:");
 	for (i = 15; i >= 0; i--) {
 		if (status & (1 << i)) {
-			rt_printk(" %s", status_a_strings[i]);
+			printk(" %s", status_a_strings[i]);
 		}
 	}
-	rt_printk("\n");
+	printk("\n");
 }
 #endif
 
@@ -1192,19 +1191,19 @@
 {
 	int i;
 
-	rt_printk("B status:");
+	printk("B status:");
 	for (i = 15; i >= 0; i--) {
 		if (status & (1 << i)) {
-			rt_printk(" %s", status_b_strings[i]);
+			printk(" %s", status_b_strings[i]);
 		}
 	}
-	rt_printk("\n");
+	printk("\n");
 }
 #endif
 
 #ifndef PCIDMA
 
-static void ni_ao_fifo_load(struct comedi_device * dev, struct comedi_subdevice * s, int n)
+static void ni_ao_fifo_load(struct comedi_device *dev, struct comedi_subdevice *s, int n)
 {
 	struct comedi_async *async = s->async;
 	struct comedi_cmd *cmd = &async->cmd;
@@ -1263,7 +1262,7 @@
  *  RT code, as RT code might purposely be running close to the
  *  metal.  Needs to be fixed eventually.
  */
-static int ni_ao_fifo_half_empty(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_ao_fifo_half_empty(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int n;
 
@@ -1284,7 +1283,7 @@
 	return 1;
 }
 
-static int ni_ao_prep_fifo(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_ao_prep_fifo(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int n;
 
@@ -1307,7 +1306,7 @@
 	return n;
 }
 
-static void ni_ai_fifo_read(struct comedi_device * dev, struct comedi_subdevice * s, int n)
+static void ni_ai_fifo_read(struct comedi_device *dev, struct comedi_subdevice *s, int n)
 {
 	struct comedi_async *async = s->async;
 	int i;
@@ -1333,7 +1332,7 @@
 		short data[2];
 		u32 dl;
 
-		// This just reads the FIFO assuming the data is present, no checks on the FIFO status are performed
+		/*  This just reads the FIFO assuming the data is present, no checks on the FIFO status are performed */
 		for (i = 0; i < n / 2; i++) {
 			dl = ni_readl(AIFIFO_Data_6143);
 
@@ -1343,7 +1342,7 @@
 		}
 		if (n % 2) {
 			/* Assume there is a single sample stuck in the FIFO */
-			ni_writel(0x01, AIFIFO_Control_6143);	// Get stranded sample into FIFO
+			ni_writel(0x01, AIFIFO_Control_6143);	/*  Get stranded sample into FIFO */
 			dl = ni_readl(AIFIFO_Data_6143);
 			data[0] = (dl >> 16) & 0xffff;
 			cfc_write_to_buffer(s, data[0]);
@@ -1364,7 +1363,7 @@
 	}
 }
 
-static void ni_handle_fifo_half_full(struct comedi_device * dev)
+static void ni_handle_fifo_half_full(struct comedi_device *dev)
 {
 	int n;
 	struct comedi_subdevice *s = dev->subdevices + NI_AI_SUBDEV;
@@ -1376,14 +1375,14 @@
 #endif
 
 #ifdef PCIDMA
-static int ni_ai_drain_dma(struct comedi_device * dev)
+static int ni_ai_drain_dma(struct comedi_device *dev)
 {
 	int i;
 	static const int timeout = 10000;
 	unsigned long flags;
 	int retval = 0;
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	if (devpriv->ai_mite_chan) {
 		for (i = 0; i < timeout; i++) {
 			if ((devpriv->stc_readw(dev,
@@ -1392,19 +1391,19 @@
 				&& mite_bytes_in_transit(devpriv->
 					ai_mite_chan) == 0)
 				break;
-			comedi_udelay(5);
+			udelay(5);
 		}
 		if (i == timeout) {
-			rt_printk
+			printk
 				("ni_mio_common: wait for dma drain timed out\n");
-			rt_printk
+			printk
 				("mite_bytes_in_transit=%i, AI_Status1_Register=0x%x\n",
 				mite_bytes_in_transit(devpriv->ai_mite_chan),
 				devpriv->stc_readw(dev, AI_Status_1_Register));
 			retval = -1;
 		}
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 
 	ni_sync_ai_dma(dev);
 
@@ -1414,7 +1413,7 @@
 /*
    Empties the AI fifo
 */
-static void ni_handle_fifo_dregs(struct comedi_device * dev)
+static void ni_handle_fifo_dregs(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s = dev->subdevices + NI_AI_SUBDEV;
 	short data[2];
@@ -1444,9 +1443,9 @@
 			cfc_write_array_to_buffer(s, data, sizeof(data));
 			i += 2;
 		}
-		// Check if stranded sample is present
+		/*  Check if stranded sample is present */
 		if (ni_readl(AIFIFO_Status_6143) & 0x01) {
-			ni_writel(0x01, AIFIFO_Control_6143);	// Get stranded sample into FIFO
+			ni_writel(0x01, AIFIFO_Control_6143);	/*  Get stranded sample into FIFO */
 			dl = ni_readl(AIFIFO_Data_6143);
 			data[0] = (dl >> 16) & 0xffff;
 			cfc_write_to_buffer(s, data[0]);
@@ -1476,7 +1475,7 @@
 	}
 }
 
-static void get_last_sample_611x(struct comedi_device * dev)
+static void get_last_sample_611x(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s = dev->subdevices + NI_AI_SUBDEV;
 	short data;
@@ -1493,7 +1492,7 @@
 	}
 }
 
-static void get_last_sample_6143(struct comedi_device * dev)
+static void get_last_sample_6143(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s = dev->subdevices + NI_AI_SUBDEV;
 	short data;
@@ -1504,7 +1503,7 @@
 
 	/* Check if there's a single sample stuck in the FIFO */
 	if (ni_readl(AIFIFO_Status_6143) & 0x01) {
-		ni_writel(0x01, AIFIFO_Control_6143);	// Get stranded sample into FIFO
+		ni_writel(0x01, AIFIFO_Control_6143);	/*  Get stranded sample into FIFO */
 		dl = ni_readl(AIFIFO_Data_6143);
 
 		/* This may get the hi/lo data in the wrong order */
@@ -1513,7 +1512,7 @@
 	}
 }
 
-static void ni_ai_munge(struct comedi_device * dev, struct comedi_subdevice * s,
+static void ni_ai_munge(struct comedi_device *dev, struct comedi_subdevice *s,
 	void *data, unsigned int num_bytes, unsigned int chan_index)
 {
 	struct comedi_async *async = s->async;
@@ -1539,7 +1538,7 @@
 
 #ifdef PCIDMA
 
-static int ni_ai_setup_MITE_dma(struct comedi_device * dev)
+static int ni_ai_setup_MITE_dma(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s = dev->subdevices + NI_AI_SUBDEV;
 	int retval;
@@ -1548,15 +1547,14 @@
 	retval = ni_request_ai_mite_channel(dev);
 	if (retval)
 		return retval;
-//      rt_printk("comedi_debug: using mite channel %i for ai.\n", devpriv->ai_mite_chan->channel);
+/* printk("comedi_debug: using mite channel %i for ai.\n", devpriv->ai_mite_chan->channel); */
 
 	/* write alloc the entire buffer */
 	comedi_buf_write_alloc(s->async, s->async->prealloc_bufsz);
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
-	if(devpriv->ai_mite_chan == NULL)
-	{
-		comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	if (devpriv->ai_mite_chan == NULL) {
+		spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 		return -EIO;
 	}
 
@@ -1574,12 +1572,12 @@
 	};
 	/*start the MITE */
 	mite_dma_arm(devpriv->ai_mite_chan);
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 
 	return 0;
 }
 
-static int ni_ao_setup_MITE_dma(struct comedi_device * dev)
+static int ni_ao_setup_MITE_dma(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s = dev->subdevices + NI_AO_SUBDEV;
 	int retval;
@@ -1592,7 +1590,7 @@
 	/* read alloc the entire buffer */
 	comedi_buf_read_alloc(s->async, s->async->prealloc_bufsz);
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	if (devpriv->ao_mite_chan) {
 		if (boardtype.reg_type & (ni_reg_611x | ni_reg_6713)) {
 			mite_prep_dma(devpriv->ao_mite_chan, 32, 32);
@@ -1604,12 +1602,12 @@
 		mite_dma_arm(devpriv->ao_mite_chan);
 	} else
 		retval = -EIO;
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 
 	return retval;
 }
 
-#endif // PCIDMA
+#endif /*  PCIDMA */
 
 /*
    used for both cancel ioctl and board initialization
@@ -1617,7 +1615,7 @@
    this is pretty harsh for a cancel, but it works...
  */
 
-static int ni_ai_reset(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_ai_reset(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	ni_release_ai_mite_channel(dev);
 	/* ai configuration */
@@ -1698,14 +1696,14 @@
 	return 0;
 }
 
-static int ni_ai_poll(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_ai_poll(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags = 0;
 	int count;
 
-	// lock to avoid race with interrupt handler
+	/*  lock to avoid race with interrupt handler */
 	if (in_interrupt() == 0)
-		comedi_spin_lock_irqsave(&dev->spinlock, flags);
+		spin_lock_irqsave(&dev->spinlock, flags);
 #ifndef PCIDMA
 	ni_handle_fifo_dregs(dev);
 #else
@@ -1713,13 +1711,13 @@
 #endif
 	count = s->async->buf_write_count - s->async->buf_read_count;
 	if (in_interrupt() == 0)
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	return count;
 }
 
-static int ni_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, n;
 	const unsigned int mask = (1 << boardtype.adbits) - 1;
@@ -1736,7 +1734,7 @@
 		for (n = 0; n < num_adc_stages_611x; n++) {
 			devpriv->stc_writew(dev, AI_CONVERT_Pulse,
 				AI_Command_1_Register);
-			comedi_udelay(1);
+			udelay(1);
 		}
 		for (n = 0; n < insn->n; n++) {
 			devpriv->stc_writew(dev, AI_CONVERT_Pulse,
@@ -1758,7 +1756,7 @@
 				}
 			}
 			if (i == NI_TIMEOUT) {
-				rt_printk
+				printk
 					("ni_mio_common: timeout in 611x ni_ai_insn_read\n");
 				return -ETIME;
 			}
@@ -1774,13 +1772,13 @@
 			dl = 0;
 			for (i = 0; i < NI_TIMEOUT; i++) {
 				if (ni_readl(AIFIFO_Status_6143) & 0x01) {
-					ni_writel(0x01, AIFIFO_Control_6143);	// Get stranded sample into FIFO
+					ni_writel(0x01, AIFIFO_Control_6143);	/*  Get stranded sample into FIFO */
 					dl = ni_readl(AIFIFO_Data_6143);
 					break;
 				}
 			}
 			if (i == NI_TIMEOUT) {
-				rt_printk
+				printk
 					("ni_mio_common: timeout in 6143 ni_ai_insn_read\n");
 				return -ETIME;
 			}
@@ -1797,7 +1795,7 @@
 					break;
 			}
 			if (i == NI_TIMEOUT) {
-				rt_printk
+				printk
 					("ni_mio_common: timeout in ni_ai_insn_read\n");
 				return -ETIME;
 			}
@@ -1814,7 +1812,7 @@
 	return insn->n;
 }
 
-void ni_prime_channelgain_list(struct comedi_device * dev)
+void ni_prime_channelgain_list(struct comedi_device *dev)
 {
 	int i;
 	devpriv->stc_writew(dev, AI_CONVERT_Pulse, AI_Command_1_Register);
@@ -1825,12 +1823,12 @@
 			devpriv->stc_writew(dev, 1, ADC_FIFO_Clear);
 			return;
 		}
-		comedi_udelay(1);
+		udelay(1);
 	}
-	rt_printk("ni_mio_common: timeout loading channel/gain list\n");
+	printk("ni_mio_common: timeout loading channel/gain list\n");
 }
 
-static void ni_m_series_load_channelgain_list(struct comedi_device * dev,
+static void ni_m_series_load_channelgain_list(struct comedi_device *dev,
 	unsigned int n_chan, unsigned int *list)
 {
 	unsigned int chan, range, aref;
@@ -1841,7 +1839,7 @@
 
 	devpriv->stc_writew(dev, 1, Configuration_Memory_Clear);
 
-//      offset = 1 << (boardtype.adbits - 1);
+/* offset = 1 << (boardtype.adbits - 1); */
 	if ((list[0] & CR_ALT_SOURCE)) {
 		unsigned bypass_bits;
 		chan = CR_CHAN(list[0]);
@@ -1859,7 +1857,7 @@
 		bypass_bits |= MSeries_AI_Bypass_Gain_Bits(range_code);
 		if (dither)
 			bypass_bits |= MSeries_AI_Bypass_Dither_Bit;
-		// don't use 2's complement encoding
+		/*  don't use 2's complement encoding */
 		bypass_bits |= MSeries_AI_Bypass_Polarity_Bit;
 		ni_writel(bypass_bits, M_Offset_AI_Config_FIFO_Bypass);
 	} else {
@@ -1899,7 +1897,7 @@
 			config_bits |= MSeries_AI_Config_Last_Channel_Bit;
 		if (dither)
 			config_bits |= MSeries_AI_Config_Dither_Bit;
-		// don't use 2's complement encoding
+		/*  don't use 2's complement encoding */
 		config_bits |= MSeries_AI_Config_Polarity_Bit;
 		ni_writew(config_bits, M_Offset_AI_Config_FIFO_Data);
 	}
@@ -1935,7 +1933,7 @@
  *   bits 0-2: channel
  *       valid channels are 0-3
  */
-static void ni_load_channelgain_list(struct comedi_device * dev, unsigned int n_chan,
+static void ni_load_channelgain_list(struct comedi_device *dev, unsigned int n_chan,
 	unsigned int *list)
 {
 	unsigned int chan, range, aref;
@@ -1952,7 +1950,7 @@
 		&& (boardtype.reg_type != ni_reg_6143)) {
 		if (devpriv->changain_state
 			&& devpriv->changain_spec == list[0]) {
-			// ready to go.
+			/*  ready to go. */
 			return;
 		}
 		devpriv->changain_state = 1;
@@ -1963,11 +1961,11 @@
 
 	devpriv->stc_writew(dev, 1, Configuration_Memory_Clear);
 
-	// Set up Calibration mode if required
+	/*  Set up Calibration mode if required */
 	if (boardtype.reg_type == ni_reg_6143) {
 		if ((list[0] & CR_ALT_SOURCE)
 			&& !devpriv->ai_calib_source_enabled) {
-			// Strobe Relay enable bit
+			/*  Strobe Relay enable bit */
 			ni_writew(devpriv->
 				ai_calib_source |
 				Calibration_Channel_6143_RelayOn,
@@ -1975,10 +1973,10 @@
 			ni_writew(devpriv->ai_calib_source,
 				Calibration_Channel_6143);
 			devpriv->ai_calib_source_enabled = 1;
-			msleep_interruptible(100);	// Allow relays to change
+			msleep_interruptible(100);	/*  Allow relays to change */
 		} else if (!(list[0] & CR_ALT_SOURCE)
 			&& devpriv->ai_calib_source_enabled) {
-			// Strobe Relay disable bit
+			/*  Strobe Relay disable bit */
 			ni_writew(devpriv->
 				ai_calib_source |
 				Calibration_Channel_6143_RelayOff,
@@ -1986,7 +1984,7 @@
 			ni_writew(devpriv->ai_calib_source,
 				Calibration_Channel_6143);
 			devpriv->ai_calib_source_enabled = 0;
-			msleep_interruptible(100);	// Allow relays to change
+			msleep_interruptible(100);	/*  Allow relays to change */
 		}
 	}
 
@@ -2055,7 +2053,7 @@
 	}
 }
 
-static int ni_ns_to_timer(const struct comedi_device * dev, unsigned nanosec,
+static int ni_ns_to_timer(const struct comedi_device *dev, unsigned nanosec,
 	int round_mode)
 {
 	int divider;
@@ -2074,29 +2072,29 @@
 	return divider - 1;
 }
 
-static unsigned ni_timer_to_ns(const struct comedi_device * dev, int timer)
+static unsigned ni_timer_to_ns(const struct comedi_device *dev, int timer)
 {
 	return devpriv->clock_ns * (timer + 1);
 }
 
-static unsigned ni_min_ai_scan_period_ns(struct comedi_device * dev,
+static unsigned ni_min_ai_scan_period_ns(struct comedi_device *dev,
 	unsigned num_channels)
 {
 	switch (boardtype.reg_type) {
 	case ni_reg_611x:
 	case ni_reg_6143:
-		// simultaneously-sampled inputs
+		/*  simultaneously-sampled inputs */
 		return boardtype.ai_speed;
 		break;
 	default:
-		// multiplexed inputs
+		/*  multiplexed inputs */
 		break;
 	};
 	return boardtype.ai_speed * num_channels;
 }
 
-static int ni_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int ni_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -2308,7 +2306,7 @@
 	return 0;
 }
 
-static int ni_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	const struct comedi_cmd *cmd = &s->async->cmd;
 	int timer;
@@ -2367,10 +2365,10 @@
 	if (cmd->chanlist_len == 1 || (boardtype.reg_type == ni_reg_611x)
 		|| (boardtype.reg_type == ni_reg_6143)) {
 		start_stop_select |= AI_STOP_Polarity;
-		start_stop_select |= AI_STOP_Select(31);	// logic low
+		start_stop_select |= AI_STOP_Select(31);	/*  logic low */
 		start_stop_select |= AI_STOP_Sync;
 	} else {
-		start_stop_select |= AI_STOP_Select(19);	// ai configuration memory
+		start_stop_select |= AI_STOP_Select(19);	/*  ai configuration memory */
 	}
 	devpriv->stc_writew(dev, start_stop_select,
 		AI_START_STOP_Select_Register);
@@ -2381,7 +2379,7 @@
 		stop_count = cmd->stop_arg - 1;
 
 		if (boardtype.reg_type == ni_reg_611x) {
-			// have to take 3 stage adc pipeline into account
+			/*  have to take 3 stage adc pipeline into account */
 			stop_count += num_adc_stages_611x;
 		}
 		/* stage number of scans */
@@ -2396,7 +2394,7 @@
 		if (stop_count == 0) {
 			devpriv->ai_cmd2 |= AI_End_On_End_Of_Scan;
 			interrupt_a_enable |= AI_STOP_Interrupt_Enable;
-			// this is required to get the last sample for chanlist_len > 1, not sure why
+			/*  this is required to get the last sample for chanlist_len > 1, not sure why */
 			if (cmd->chanlist_len > 1)
 				start_stop_select |=
 					AI_STOP_Polarity | AI_STOP_Edge;
@@ -2440,7 +2438,7 @@
 		mode2 |= AI_SI_Reload_Mode(0);
 		/* AI_SI_Initial_Load_Source=A */
 		mode2 &= ~AI_SI_Initial_Load_Source;
-		//mode2 |= AI_SC_Reload_Mode;
+		/* mode2 |= AI_SC_Reload_Mode; */
 		devpriv->stc_writew(dev, mode2, AI_Mode_2_Register);
 
 		/* load SI */
@@ -2486,8 +2484,8 @@
 		/* AI_SI2_Load */
 		devpriv->stc_writew(dev, AI_SI2_Load, AI_Command_1_Register);
 
-		mode2 |= AI_SI2_Reload_Mode;	// alternate
-		mode2 |= AI_SI2_Initial_Load_Source;	// B
+		mode2 |= AI_SI2_Reload_Mode;	/*  alternate */
+		mode2 |= AI_SI2_Initial_Load_Source;	/*  B */
 
 		devpriv->stc_writew(dev, mode2, AI_Mode_2_Register);
 		break;
@@ -2589,7 +2587,7 @@
 		if (retval)
 			return retval;
 	}
-	//mite_dump_regs(devpriv->mite);
+	/* mite_dump_regs(devpriv->mite); */
 #endif
 
 	switch (cmd->start_src) {
@@ -2612,7 +2610,7 @@
 	return 0;
 }
 
-static int ni_ai_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_ai_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum)
 {
 	if (trignum != 0)
@@ -2625,11 +2623,11 @@
 	return 1;
 }
 
-static int ni_ai_config_analog_trig(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int ni_ai_config_analog_trig(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int ni_ai_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_ai_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n < 1)
 		return -EINVAL;
@@ -2679,8 +2677,8 @@
 	return -EINVAL;
 }
 
-static int ni_ai_config_analog_trig(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_ai_config_analog_trig(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int a, b, modebits;
 	int err = 0;
@@ -2777,7 +2775,7 @@
 }
 
 /* munge data from unsigned to 2's complement for analog output bipolar modes */
-static void ni_ao_munge(struct comedi_device * dev, struct comedi_subdevice * s,
+static void ni_ao_munge(struct comedi_device *dev, struct comedi_subdevice *s,
 	void *data, unsigned int num_bytes, unsigned int chan_index)
 {
 	struct comedi_async *async = s->async;
@@ -2800,8 +2798,8 @@
 	}
 }
 
-static int ni_m_series_ao_config_chanlist(struct comedi_device * dev,
-	struct comedi_subdevice * s, unsigned int chanspec[], unsigned int n_chans,
+static int ni_m_series_ao_config_chanlist(struct comedi_device *dev,
+	struct comedi_subdevice *s, unsigned int chanspec[], unsigned int n_chans,
 	int timed)
 {
 	unsigned int range;
@@ -2810,7 +2808,7 @@
 	int i;
 	int invert = 0;
 
-	if(timed) {
+	if (timed) {
 		for (i = 0; i < boardtype.n_aochan; ++i) {
 			devpriv->ao_conf[i] &= ~MSeries_AO_Update_Timed_Bit;
 			ni_writeb(devpriv->ao_conf[i], M_Offset_AO_Config_Bank(i));
@@ -2844,8 +2842,8 @@
 				M_Offset_AO_Reference_Attenuation(chan));
 			break;
 		default:
-			rt_printk("%s: bug! unhandled ao reference voltage\n",
-				__FUNCTION__);
+			printk("%s: bug! unhandled ao reference voltage\n",
+				__func__);
 			break;
 		}
 		switch (krange->max + krange->min) {
@@ -2856,8 +2854,8 @@
 			conf |= MSeries_AO_DAC_Offset_5V_Bits;
 			break;
 		default:
-			rt_printk("%s: bug! unhandled ao offset voltage\n",
-				__FUNCTION__);
+			printk("%s: bug! unhandled ao offset voltage\n",
+				__func__);
 			break;
 		}
 		if (timed)
@@ -2869,7 +2867,7 @@
 	return invert;
 }
 
-static int ni_old_ao_config_chanlist(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_old_ao_config_chanlist(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int chanspec[], unsigned int n_chans)
 {
 	unsigned int range;
@@ -2912,7 +2910,7 @@
 	return invert;
 }
 
-static int ni_ao_config_chanlist(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_ao_config_chanlist(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int chanspec[], unsigned int n_chans, int timed)
 {
 	if (boardtype.reg_type & ni_reg_m_series_mask)
@@ -2921,16 +2919,16 @@
 	else
 		return ni_old_ao_config_chanlist(dev, s, chanspec, n_chans);
 }
-static int ni_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->ao[CR_CHAN(insn->chanspec)];
 
 	return 1;
 }
 
-static int ni_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int chan = CR_CHAN(insn->chanspec);
 	unsigned int invert;
@@ -2948,8 +2946,8 @@
 	return 1;
 }
 
-static int ni_ao_insn_write_671x(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_ao_insn_write_671x(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int chan = CR_CHAN(insn->chanspec);
 	unsigned int invert;
@@ -2965,16 +2963,16 @@
 	return 1;
 }
 
-static int ni_ao_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_ao_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	switch (data[0]) {
 	case INSN_CONFIG_GET_HARDWARE_BUFFER_SIZE:
-		switch(data[1])
+		switch (data[1])
 		{
 		case COMEDI_OUTPUT:
 			data[2] = 1 + boardtype.ao_fifo_depth * sizeof(short);
-			if(devpriv->mite) data[2] += devpriv->mite->fifo_size;
+			if (devpriv->mite) data[2] += devpriv->mite->fifo_size;
 			break;
 		case COMEDI_INPUT:
 			data[2] = 0;
@@ -2991,7 +2989,7 @@
 	return -EINVAL;
 }
 
-static int ni_ao_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_ao_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum)
 {
 	int ret;
@@ -3033,7 +3031,7 @@
 	devpriv->stc_writew(dev, devpriv->ao_mode3, AO_Mode_3_Register);
 	/* wait for DACs to be loaded */
 	for (i = 0; i < timeout; i++) {
-		comedi_udelay(1);
+		udelay(1);
 		if ((devpriv->stc_readw(dev,
 					Joint_Status_2_Register) &
 				AO_TMRDACWRs_In_Progress_St) == 0)
@@ -3044,7 +3042,7 @@
 			"timed out waiting for AO_TMRDACWRs_In_Progress_St to clear");
 		return -EIO;
 	}
-	// stc manual says we are need to clear error interrupt after AO_TMRDACWRs_In_Progress_St clears
+	/*  stc manual says we are need to clear error interrupt after AO_TMRDACWRs_In_Progress_St clears */
 	devpriv->stc_writew(dev, AO_Error_Interrupt_Ack,
 		Interrupt_B_Ack_Register);
 
@@ -3062,7 +3060,7 @@
 	return 0;
 }
 
-static int ni_ao_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	const struct comedi_cmd *cmd = &s->async->cmd;
 	int bits;
@@ -3114,9 +3112,9 @@
 	case TRIG_EXT:
                 devpriv->ao_trigger_select = AO_START1_Select(CR_CHAN(cmd->start_arg)+1);
 		if (cmd->start_arg & CR_INVERT)
-			devpriv->ao_trigger_select |= AO_START1_Polarity;  // 0=active high, 1=active low. see daq-stc 3-24 (p186)
+			devpriv->ao_trigger_select |= AO_START1_Polarity;  /*  0=active high, 1=active low. see daq-stc 3-24 (p186) */
 		if (cmd->start_arg & CR_EDGE)
-			devpriv->ao_trigger_select |= AO_START1_Edge;      // 0=edge detection disabled, 1=enabled
+			devpriv->ao_trigger_select |= AO_START1_Edge;      /*  0=edge detection disabled, 1=enabled */
 		devpriv->stc_writew(dev, devpriv->ao_trigger_select, AO_Trigger_Select_Register);
 		break;
 	default:
@@ -3139,9 +3137,9 @@
 	devpriv->stc_writew(dev, devpriv->ao_mode2, AO_Mode_2_Register);
 	switch (cmd->stop_src) {
 	case TRIG_COUNT:
-		if(boardtype.reg_type & ni_reg_m_series_mask)
+		if (boardtype.reg_type & ni_reg_m_series_mask)
 		{
-			// this is how the NI example code does it for m-series boards, verified correct with 6259
+			/*  this is how the NI example code does it for m-series boards, verified correct with 6259 */
 			devpriv->stc_writel(dev, cmd->stop_arg - 1, AO_UC_Load_A_Register);
 			devpriv->stc_writew(dev, AO_UC_Load, AO_Command_1_Register);
 		}else
@@ -3244,7 +3242,7 @@
 		bits |= AO_Number_Of_DAC_Packages;
 #endif
 	devpriv->stc_writew(dev, bits, AO_Personal_Register);
-	// enable sending of ao dma requests
+	/*  enable sending of ao dma requests */
 	devpriv->stc_writew(dev, AO_AOFREQ_Enable, AO_Start_Select_Register);
 
 	devpriv->stc_writew(dev, AO_Configuration_End, Joint_Reset_Register);
@@ -3261,8 +3259,8 @@
 	return 0;
 }
 
-static int ni_ao_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int ni_ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -3384,13 +3382,13 @@
 	return 0;
 }
 
-static int ni_ao_reset(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_ao_reset(struct comedi_device *dev, struct comedi_subdevice *s)
 {
-	//devpriv->ao0p=0x0000;
-	//ni_writew(devpriv->ao0p,AO_Configuration);
+	/* devpriv->ao0p=0x0000; */
+	/* ni_writew(devpriv->ao0p,AO_Configuration); */
 
-	//devpriv->ao1p=AO_Channel(1);
-	//ni_writew(devpriv->ao1p,AO_Configuration);
+	/* devpriv->ao1p=AO_Channel(1); */
+	/* ni_writew(devpriv->ao1p,AO_Configuration); */
 
 	ni_release_ao_mite_channel(dev);
 
@@ -3422,7 +3420,7 @@
 	if (boardtype.reg_type & ni_reg_6xxx_mask) {
 		unsigned immediate_bits = 0;
 		unsigned i;
-		for(i = 0; i < s->n_chan; ++i)
+		for (i = 0; i < s->n_chan; ++i)
 		{
 			immediate_bits |= 1 << i;
 		}
@@ -3434,13 +3432,13 @@
 	return 0;
 }
 
-// digital io
+/* digital io */
 
-static int ni_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 #ifdef DEBUG_DIO
-	rt_printk("ni_dio_insn_config() chan=%d io=%d\n",
+	printk("ni_dio_insn_config() chan=%d io=%d\n",
 		CR_CHAN(insn->chanspec), data[0]);
 #endif
 	switch (data[0]) {
@@ -3468,11 +3466,11 @@
 	return 1;
 }
 
-static int ni_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 #ifdef DEBUG_DIO
-	rt_printk("ni_dio_insn_bits() mask=0x%x bits=0x%x\n", data[0], data[1]);
+	printk("ni_dio_insn_bits() mask=0x%x bits=0x%x\n", data[0], data[1]);
 #endif
 	if (insn->n != 2)
 		return -EINVAL;
@@ -3495,11 +3493,11 @@
 	return 2;
 }
 
-static int ni_m_series_dio_insn_config(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int ni_m_series_dio_insn_config(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 #ifdef DEBUG_DIO
-	rt_printk("ni_m_series_dio_insn_config() chan=%d io=%d\n",
+	printk("ni_m_series_dio_insn_config() chan=%d io=%d\n",
 		CR_CHAN(insn->chanspec), data[0]);
 #endif
 	switch (data[0]) {
@@ -3525,11 +3523,11 @@
 	return 1;
 }
 
-static int ni_m_series_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_m_series_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 #ifdef DEBUG_DIO
-	rt_printk("ni_m_series_dio_insn_bits() mask=0x%x bits=0x%x\n", data[0],
+	printk("ni_m_series_dio_insn_bits() mask=0x%x bits=0x%x\n", data[0],
 		data[1]);
 #endif
 	if (insn->n != 2)
@@ -3544,8 +3542,8 @@
 	return 2;
 }
 
-static int ni_cdio_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int ni_cdio_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -3653,7 +3651,7 @@
 	return 0;
 }
 
-static int ni_cdio_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_cdio_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	const struct comedi_cmd *cmd = &s->async->cmd;
 	unsigned cdo_mode_bits = CDO_FIFO_Mode_Bit | CDO_Halt_On_Error_Bit;
@@ -3690,7 +3688,7 @@
 	return 0;
 }
 
-static int ni_cdo_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_cdo_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum)
 {
 #ifdef PCIDMA
@@ -3706,7 +3704,7 @@
 	comedi_buf_read_alloc(s->async, s->async->prealloc_bufsz);
 
 #ifdef PCIDMA
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	if (devpriv->cdo_mite_chan) {
 		mite_prep_dma(devpriv->cdo_mite_chan, 32, 32);
 		mite_dma_arm(devpriv->cdo_mite_chan);
@@ -3714,17 +3712,19 @@
 		comedi_error(dev, "BUG: no cdo mite channel?");
 		retval = -EIO;
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 	if (retval < 0)
 		return retval;
 #endif
-// XXX not sure what interrupt C group does
-//      ni_writeb(Interrupt_Group_C_Enable_Bit, M_Offset_Interrupt_C_Enable);
-	//wait for dma to fill output fifo
+/*
+* XXX not sure what interrupt C group does
+* ni_writeb(Interrupt_Group_C_Enable_Bit,
+* M_Offset_Interrupt_C_Enable); wait for dma to fill output fifo
+*/
 	for (i = 0; i < timeout; ++i) {
 		if (ni_readl(M_Offset_CDIO_Status) & CDO_FIFO_Full_Bit)
 			break;
-		comedi_udelay(10);
+		udelay(10);
 	}
 	if (i == timeout) {
 		comedi_error(dev, "dma failed to fill cdo fifo!");
@@ -3736,20 +3736,22 @@
 	return retval;
 }
 
-static int ni_cdio_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_cdio_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	ni_writel(CDO_Disarm_Bit | CDO_Error_Interrupt_Enable_Clear_Bit |
 		CDO_Empty_FIFO_Interrupt_Enable_Clear_Bit |
 		CDO_FIFO_Request_Interrupt_Enable_Clear_Bit,
 		M_Offset_CDIO_Command);
-// XXX not sure what interrupt C group does
-//      ni_writeb(0, M_Offset_Interrupt_C_Enable);
+/*
+* XXX not sure what interrupt C group does ni_writeb(0,
+* M_Offset_Interrupt_C_Enable);
+*/
 	ni_writel(0, M_Offset_CDO_Mask_Enable);
 	ni_release_cdo_mite_channel(dev);
 	return 0;
 }
 
-static void handle_cdio_interrupt(struct comedi_device * dev)
+static void handle_cdio_interrupt(struct comedi_device *dev)
 {
 	unsigned cdio_status;
 	struct comedi_subdevice *s = dev->subdevices + NI_DIO_SUBDEV;
@@ -3761,7 +3763,7 @@
 		return;
 	}
 #ifdef PCIDMA
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	if (devpriv->cdo_mite_chan) {
 		unsigned cdo_mite_status =
 			mite_get_status(devpriv->cdo_mite_chan);
@@ -3772,26 +3774,26 @@
 		}
 		mite_sync_output_dma(devpriv->cdo_mite_chan, s->async);
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 #endif
 
 	cdio_status = ni_readl(M_Offset_CDIO_Status);
 	if (cdio_status & (CDO_Overrun_Bit | CDO_Underflow_Bit)) {
-//              rt_printk("cdio error: statux=0x%x\n", cdio_status);
-		ni_writel(CDO_Error_Interrupt_Confirm_Bit, M_Offset_CDIO_Command);	// XXX just guessing this is needed and does something useful
+/* printk("cdio error: statux=0x%x\n", cdio_status); */
+		ni_writel(CDO_Error_Interrupt_Confirm_Bit, M_Offset_CDIO_Command);	/*  XXX just guessing this is needed and does something useful */
 		s->async->events |= COMEDI_CB_OVERFLOW;
 	}
 	if (cdio_status & CDO_FIFO_Empty_Bit) {
-//              rt_printk("cdio fifo empty\n");
+/* printk("cdio fifo empty\n"); */
 		ni_writel(CDO_Empty_FIFO_Interrupt_Enable_Clear_Bit,
 			M_Offset_CDIO_Command);
-//              s->async->events |= COMEDI_CB_EOA;
+/* s->async->events |= COMEDI_CB_EOA; */
 	}
 	ni_event(dev, s);
 }
 
-static int ni_serial_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_serial_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int err = insn->n;
 	unsigned char byte_out, byte_in = 0;
@@ -3803,7 +3805,7 @@
 	case INSN_CONFIG_SERIAL_CLOCK:
 
 #ifdef DEBUG_DIO
-		rt_printk("SPI serial clock Config cd\n", data[1]);
+		printk("SPI serial clock Config cd\n", data[1]);
 #endif
 		devpriv->serial_hw_mode = 1;
 		devpriv->dio_control |= DIO_HW_Serial_Enable;
@@ -3869,7 +3871,7 @@
 			err = ni_serial_sw_readwrite8(dev, s, byte_out,
 				&byte_in);
 		} else {
-			rt_printk("ni_serial_insn_config: serial disabled!\n");
+			printk("ni_serial_insn_config: serial disabled!\n");
 			return -EINVAL;
 		}
 		if (err < 0)
@@ -3884,14 +3886,14 @@
 
 }
 
-static int ni_serial_hw_readwrite8(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_serial_hw_readwrite8(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned char data_out, unsigned char *data_in)
 {
 	unsigned int status1;
 	int err = 0, count = 20;
 
 #ifdef DEBUG_DIO
-	rt_printk("ni_serial_hw_readwrite8: outputting 0x%x\n", data_out);
+	printk("ni_serial_hw_readwrite8: outputting 0x%x\n", data_out);
 #endif
 
 	devpriv->dio_output &= ~DIO_Serial_Data_Mask;
@@ -3914,9 +3916,9 @@
 				Joint_Status_1_Register)) &
 		DIO_Serial_IO_In_Progress_St) {
 		/* Delay one bit per loop */
-		comedi_udelay((devpriv->serial_interval_ns + 999) / 1000);
+		udelay((devpriv->serial_interval_ns + 999) / 1000);
 		if (--count < 0) {
-			rt_printk
+			printk
 				("ni_serial_hw_readwrite8: SPI serial I/O didn't finish in time!\n");
 			err = -ETIME;
 			goto Error;
@@ -3925,12 +3927,12 @@
 
 	/* Delay for last bit. This delay is absolutely necessary, because
 	   DIO_Serial_IO_In_Progress_St goes high one bit too early. */
-	comedi_udelay((devpriv->serial_interval_ns + 999) / 1000);
+	udelay((devpriv->serial_interval_ns + 999) / 1000);
 
 	if (data_in != NULL) {
 		*data_in = devpriv->stc_readw(dev, DIO_Serial_Input_Register);
 #ifdef DEBUG_DIO
-		rt_printk("ni_serial_hw_readwrite8: inputted 0x%x\n", *data_in);
+		printk("ni_serial_hw_readwrite8: inputted 0x%x\n", *data_in);
 #endif
 	}
 
@@ -3940,17 +3942,17 @@
 	return err;
 }
 
-static int ni_serial_sw_readwrite8(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_serial_sw_readwrite8(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned char data_out, unsigned char *data_in)
 {
 	unsigned char mask, input = 0;
 
 #ifdef DEBUG_DIO
-	rt_printk("ni_serial_sw_readwrite8: outputting 0x%x\n", data_out);
+	printk("ni_serial_sw_readwrite8: outputting 0x%x\n", data_out);
 #endif
 
 	/* Wait for one bit before transfer */
-	comedi_udelay((devpriv->serial_interval_ns + 999) / 1000);
+	udelay((devpriv->serial_interval_ns + 999) / 1000);
 
 	for (mask = 0x80; mask; mask >>= 1) {
 		/* Output current bit; note that we cannot touch s->state
@@ -3969,23 +3971,23 @@
 		devpriv->stc_writew(dev, devpriv->dio_control,
 			DIO_Control_Register);
 
-		comedi_udelay((devpriv->serial_interval_ns + 999) / 2000);
+		udelay((devpriv->serial_interval_ns + 999) / 2000);
 
 		devpriv->dio_control &= ~DIO_Software_Serial_Control;
 		devpriv->stc_writew(dev, devpriv->dio_control,
 			DIO_Control_Register);
 
-		comedi_udelay((devpriv->serial_interval_ns + 999) / 2000);
+		udelay((devpriv->serial_interval_ns + 999) / 2000);
 
 		/* Input current bit */
 		if (devpriv->stc_readw(dev,
 				DIO_Parallel_Input_Register) & DIO_SDIN) {
-/*			rt_printk("DIO_P_I_R: 0x%x\n", devpriv->stc_readw(dev, DIO_Parallel_Input_Register)); */
+/*			printk("DIO_P_I_R: 0x%x\n", devpriv->stc_readw(dev, DIO_Parallel_Input_Register)); */
 			input |= mask;
 		}
 	}
 #ifdef DEBUG_DIO
-	rt_printk("ni_serial_sw_readwrite8: inputted 0x%x\n", input);
+	printk("ni_serial_sw_readwrite8: inputted 0x%x\n", input);
 #endif
 	if (data_in)
 		*data_in = input;
@@ -3993,7 +3995,7 @@
 	return 0;
 }
 
-static void mio_common_detach(struct comedi_device * dev)
+static void mio_common_detach(struct comedi_device *dev)
 {
 	if (dev->private) {
 		if (devpriv->counter_dev) {
@@ -4004,7 +4006,7 @@
 		subdev_8255_cleanup(dev, dev->subdevices + NI_8255_DIO_SUBDEV);
 }
 
-static void init_ao_67xx(struct comedi_device * dev, struct comedi_subdevice * s)
+static void init_ao_67xx(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int i;
 
@@ -4099,8 +4101,8 @@
 		stc_register = Interrupt_B_Enable_Register;
 		break;
 	default:
-		rt_printk("%s: unhandled register 0x%x in switch.\n",
-			__FUNCTION__, reg);
+		printk("%s: unhandled register 0x%x in switch.\n",
+			__func__, reg);
 		BUG();
 		return 0;
 		break;
@@ -4208,15 +4210,15 @@
 	return 0;
 }
 
-static int ni_freq_out_insn_read(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int ni_freq_out_insn_read(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->clock_and_fout & FOUT_Divider_mask;
 	return 1;
 }
 
-static int ni_freq_out_insn_write(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int ni_freq_out_insn_write(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	devpriv->clock_and_fout &= ~FOUT_Enable;
 	devpriv->stc_writew(dev, devpriv->clock_and_fout,
@@ -4229,7 +4231,7 @@
 	return insn->n;
 }
 
-static int ni_set_freq_out_clock(struct comedi_device * dev, unsigned int clock_source)
+static int ni_set_freq_out_clock(struct comedi_device *dev, unsigned int clock_source)
 {
 	switch (clock_source) {
 	case NI_FREQ_OUT_TIMEBASE_1_DIV_2_CLOCK_SRC:
@@ -4246,8 +4248,8 @@
 	return 3;
 }
 
-static void ni_get_freq_out_clock(struct comedi_device * dev, unsigned int * clock_source,
-	unsigned int * clock_period_ns)
+static void ni_get_freq_out_clock(struct comedi_device *dev, unsigned int *clock_source,
+	unsigned int *clock_period_ns)
 {
 	if (devpriv->clock_and_fout & FOUT_Timebase_Select) {
 		*clock_source = NI_FREQ_OUT_TIMEBASE_2_CLOCK_SRC;
@@ -4258,8 +4260,8 @@
 	}
 }
 
-static int ni_freq_out_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_freq_out_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	switch (data[0]) {
 	case INSN_CONFIG_SET_CLOCK_SRC:
@@ -4274,11 +4276,11 @@
 	return -EINVAL;
 }
 
-static int ni_alloc_private(struct comedi_device * dev)
+static int ni_alloc_private(struct comedi_device *dev)
 {
 	int ret;
 
-	ret = alloc_private(dev, sizeof(ni_private));
+	ret = alloc_private(dev, sizeof(struct ni_private));
 	if (ret < 0)
 		return ret;
 
@@ -4289,7 +4291,7 @@
 	return 0;
 };
 
-static int ni_E_init(struct comedi_device * dev, struct comedi_devconfig * it)
+static int ni_E_init(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned j;
@@ -4419,14 +4421,14 @@
 	s = dev->subdevices + NI_CALIBRATION_SUBDEV;
 	s->type = COMEDI_SUBD_CALIB;
 	if (boardtype.reg_type & ni_reg_m_series_mask) {
-		// internal PWM analog output used for AI nonlinearity calibration
+		/*  internal PWM analog output used for AI nonlinearity calibration */
 		s->subdev_flags = SDF_INTERNAL;
 		s->insn_config = &ni_m_series_pwm_config;
 		s->n_chan = 1;
 		s->maxdata = 0;
 		ni_writel(0x0, M_Offset_Cal_PWM);
 	} else if (boardtype.reg_type == ni_reg_6143) {
-		// internal PWM analog output used for AI nonlinearity calibration
+		/*  internal PWM analog output used for AI nonlinearity calibration */
 		s->subdev_flags = SDF_INTERNAL;
 		s->insn_config = &ni_6143_pwm_config;
 		s->n_chan = 1;
@@ -4478,7 +4480,7 @@
 	if (boardtype.reg_type & ni_reg_67xx_mask) {
 		s->type = COMEDI_SUBD_AI;
 		s->subdev_flags = SDF_READABLE | SDF_DIFF | SDF_INTERNAL;
-		// one channel for each analog output channel
+		/*  one channel for each analog output channel */
 		s->n_chan = boardtype.n_aochan;
 		s->maxdata = (1 << 16) - 1;
 		s->range_table = &range_unknown;	/* XXX */
@@ -4557,7 +4559,7 @@
 	/* ai configuration */
 	ni_ai_reset(dev, dev->subdevices + NI_AI_SUBDEV);
 	if ((boardtype.reg_type & ni_reg_6xxx_mask) == 0) {
-		// BEAM is this needed for PCI-6143 ??
+		/*  BEAM is this needed for PCI-6143 ?? */
 		devpriv->clock_and_fout =
 			Slow_Internal_Time_Divide_By_2 |
 			Slow_Internal_Timebase |
@@ -4623,8 +4625,8 @@
 	presents the EEPROM as a subdevice
 */
 
-static int ni_eeprom_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_eeprom_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = ni_read_eeprom(dev, CR_CHAN(insn->chanspec));
 
@@ -4635,7 +4637,7 @@
 	reads bytes out of eeprom
 */
 
-static int ni_read_eeprom(struct comedi_device * dev, int addr)
+static int ni_read_eeprom(struct comedi_device *dev, int addr)
 {
 	int bit;
 	int bitstring;
@@ -4659,23 +4661,23 @@
 	return bitstring;
 }
 
-static int ni_m_series_eeprom_insn_read(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int ni_m_series_eeprom_insn_read(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->eeprom_buffer[CR_CHAN(insn->chanspec)];
 
 	return 1;
 }
 
-static int ni_get_pwm_config(struct comedi_device * dev, unsigned int * data)
+static int ni_get_pwm_config(struct comedi_device *dev, unsigned int *data)
 {
 	data[1] = devpriv->pwm_up_count * devpriv->clock_ns;
 	data[2] = devpriv->pwm_down_count * devpriv->clock_ns;
 	return 3;
 }
 
-static int ni_m_series_pwm_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_m_series_pwm_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned up_count, down_count;
 	switch (data[0]) {
@@ -4739,8 +4741,8 @@
 	return 0;
 }
 
-static int ni_6143_pwm_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_6143_pwm_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned up_count, down_count;
 	switch (data[0]) {
@@ -4802,20 +4804,20 @@
 	return 0;
 }
 
-static void ni_write_caldac(struct comedi_device * dev, int addr, int val);
+static void ni_write_caldac(struct comedi_device *dev, int addr, int val);
 /*
 	calibration subdevice
 */
-static int ni_calib_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_calib_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	ni_write_caldac(dev, CR_CHAN(insn->chanspec), data[0]);
 
 	return 1;
 }
 
-static int ni_calib_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_calib_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	data[0] = devpriv->caldacs[CR_CHAN(insn->chanspec)];
 
@@ -4845,7 +4847,7 @@
 	[ad8804_debug] = {16, 8, pack_ad8804},
 };
 
-static void caldac_setup(struct comedi_device * dev, struct comedi_subdevice * s)
+static void caldac_setup(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int i, j;
 	int n_dacs;
@@ -4898,13 +4900,13 @@
 	}
 }
 
-static void ni_write_caldac(struct comedi_device * dev, int addr, int val)
+static void ni_write_caldac(struct comedi_device *dev, int addr, int val)
 {
 	unsigned int loadbit = 0, bits = 0, bit, bitstring = 0;
 	int i;
 	int type;
 
-	//printk("ni_write_caldac: chan=%d val=%d\n",addr,val);
+	/* printk("ni_write_caldac: chan=%d val=%d\n",addr,val); */
 	if (devpriv->caldacs[addr] == val)
 		return;
 	devpriv->caldacs[addr] = val;
@@ -4916,7 +4918,7 @@
 		if (addr < caldacs[type].n_chans) {
 			bits = caldacs[type].packbits(addr, val, &bitstring);
 			loadbit = SerDacLd(i);
-			//printk("caldac: using i=%d addr=%d %x\n",i,addr,bitstring);
+			/* printk("caldac: using i=%d addr=%d %x\n",i,addr,bitstring); */
 			break;
 		}
 		addr -= caldacs[type].n_chans;
@@ -4924,12 +4926,12 @@
 
 	for (bit = 1 << (bits - 1); bit; bit >>= 1) {
 		ni_writeb(((bit & bitstring) ? 0x02 : 0), Serial_Command);
-		comedi_udelay(1);
+		udelay(1);
 		ni_writeb(1 | ((bit & bitstring) ? 0x02 : 0), Serial_Command);
-		comedi_udelay(1);
+		udelay(1);
 	}
 	ni_writeb(loadbit, Serial_Command);
-	comedi_udelay(1);
+	udelay(1);
 	ni_writeb(0, Serial_Command);
 }
 
@@ -4985,7 +4987,7 @@
 /*
  *	Read the GPCTs current value.
  */
-static int GPCT_G_Watch(struct comedi_device * dev, int chan)
+static int GPCT_G_Watch(struct comedi_device *dev, int chan)
 {
 	unsigned int hi1, hi2, lo;
 
@@ -5008,11 +5010,11 @@
 	return (hi1 << 16) | lo;
 }
 
-static void GPCT_Reset(struct comedi_device * dev, int chan)
+static void GPCT_Reset(struct comedi_device *dev, int chan)
 {
 	int temp_ack_reg = 0;
 
-	//printk("GPCT_Reset...");
+	/* printk("GPCT_Reset..."); */
 	devpriv->gpct_cur_operation[chan] = GPCT_RESET;
 
 	switch (chan) {
@@ -5029,7 +5031,7 @@
 		devpriv->stc_writew(dev, temp_ack_reg,
 			Interrupt_A_Ack_Register);
 
-		//problem...this interferes with the other ctr...
+		/* problem...this interferes with the other ctr... */
 		devpriv->an_trig_etc_reg |= GPFO_0_Output_Enable;
 		devpriv->stc_writew(dev, devpriv->an_trig_etc_reg,
 			Analog_Trigger_Etc_Register);
@@ -5065,38 +5067,38 @@
 		G_Input_Select_Register(chan));
 	devpriv->stc_writew(dev, 0, G_Autoincrement_Register(chan));
 
-	//printk("exit GPCT_Reset\n");
+	/* printk("exit GPCT_Reset\n"); */
 }
 
 #endif
 
-static int ni_gpct_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_gpct_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct ni_gpct *counter = s->private;
 	return ni_tio_insn_config(counter, insn, data);
 }
 
-static int ni_gpct_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_gpct_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct ni_gpct *counter = s->private;
 	return ni_tio_rinsn(counter, insn, data);
 }
 
-static int ni_gpct_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_gpct_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct ni_gpct *counter = s->private;
 	return ni_tio_winsn(counter, insn, data);
 }
 
-static int ni_gpct_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_gpct_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int retval;
 #ifdef PCIDMA
 	struct ni_gpct *counter = s->private;
-//      const struct comedi_cmd *cmd = &s->async->cmd;
+/* const struct comedi_cmd *cmd = &s->async->cmd; */
 
 	retval = ni_request_gpct_mite_channel(dev, counter->counter_index,
 		COMEDI_INPUT);
@@ -5114,8 +5116,8 @@
 	return retval;
 }
 
-static int ni_gpct_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int ni_gpct_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 #ifdef PCIDMA
 	struct ni_gpct *counter = s->private;
@@ -5126,7 +5128,7 @@
 #endif
 }
 
-static int ni_gpct_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ni_gpct_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 #ifdef PCIDMA
 	struct ni_gpct *counter = s->private;
@@ -5147,7 +5149,7 @@
  *
  */
 
-static int ni_m_series_set_pfi_routing(struct comedi_device * dev, unsigned chan,
+static int ni_m_series_set_pfi_routing(struct comedi_device *dev, unsigned chan,
 	unsigned source)
 {
 	unsigned pfi_reg_index;
@@ -5165,16 +5167,16 @@
 	return 2;
 }
 
-static int ni_old_set_pfi_routing(struct comedi_device * dev, unsigned chan,
+static int ni_old_set_pfi_routing(struct comedi_device *dev, unsigned chan,
 	unsigned source)
 {
-	// pre-m-series boards have fixed signals on pfi pins
+	/*  pre-m-series boards have fixed signals on pfi pins */
 	if (source != ni_old_get_pfi_routing(dev, chan))
 		return -EINVAL;
 	return 2;
 }
 
-static int ni_set_pfi_routing(struct comedi_device * dev, unsigned chan,
+static int ni_set_pfi_routing(struct comedi_device *dev, unsigned chan,
 	unsigned source)
 {
 	if (boardtype.reg_type & ni_reg_m_series_mask)
@@ -5183,16 +5185,16 @@
 		return ni_old_set_pfi_routing(dev, chan, source);
 }
 
-static unsigned ni_m_series_get_pfi_routing(struct comedi_device * dev, unsigned chan)
+static unsigned ni_m_series_get_pfi_routing(struct comedi_device *dev, unsigned chan)
 {
 	const unsigned array_offset = chan / 3;
 	return MSeries_PFI_Output_Select_Source(chan,
 		devpriv->pfi_output_select_reg[array_offset]);
 }
 
-static unsigned ni_old_get_pfi_routing(struct comedi_device * dev, unsigned chan)
+static unsigned ni_old_get_pfi_routing(struct comedi_device *dev, unsigned chan)
 {
-	// pre-m-series boards have fixed signals on pfi pins
+	/*  pre-m-series boards have fixed signals on pfi pins */
 	switch (chan) {
 	case 0:
 		return NI_PFI_OUTPUT_AI_START1;
@@ -5225,13 +5227,13 @@
 		return NI_PFI_OUTPUT_G_GATE0;
 		break;
 	default:
-		rt_printk("%s: bug, unhandled case in switch.\n", __FUNCTION__);
+		printk("%s: bug, unhandled case in switch.\n", __func__);
 		break;
 	}
 	return 0;
 }
 
-static unsigned ni_get_pfi_routing(struct comedi_device * dev, unsigned chan)
+static unsigned ni_get_pfi_routing(struct comedi_device *dev, unsigned chan)
 {
 	if (boardtype.reg_type & ni_reg_m_series_mask)
 		return ni_m_series_get_pfi_routing(dev, chan);
@@ -5239,7 +5241,7 @@
 		return ni_old_get_pfi_routing(dev, chan);
 }
 
-static int ni_config_filter(struct comedi_device * dev, unsigned pfi_channel,
+static int ni_config_filter(struct comedi_device *dev, unsigned pfi_channel,
 	enum ni_pfi_filter_select filter)
 {
 	unsigned bits;
@@ -5253,8 +5255,8 @@
 	return 0;
 }
 
-static int ni_pfi_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_pfi_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if ((boardtype.reg_type & ni_reg_m_series_mask) == 0) {
 		return -ENOTSUPP;
@@ -5268,8 +5270,8 @@
 	return 2;
 }
 
-static int ni_pfi_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_pfi_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int chan;
 
@@ -5312,16 +5314,16 @@
  *  NI RTSI Bus Functions
  *
  */
-static void ni_rtsi_init(struct comedi_device * dev)
+static void ni_rtsi_init(struct comedi_device *dev)
 {
-	// Initialises the RTSI bus signal switch to a default state
+	/*  Initialises the RTSI bus signal switch to a default state */
 
-	// Set clock mode to internal
+	/*  Set clock mode to internal */
 	devpriv->clock_and_fout2 = MSeries_RTSI_10MHz_Bit;
 	if (ni_set_master_clock(dev, NI_MIO_INTERNAL_CLOCK, 0) < 0) {
-		rt_printk("ni_set_master_clock failed, bug?");
+		printk("ni_set_master_clock failed, bug?");
 	}
-	// default internal lines routing to RTSI bus lines
+	/*  default internal lines routing to RTSI bus lines */
 	devpriv->rtsi_trig_a_output_reg =
 		RTSI_Trig_Output_Bits(0,
 		NI_RTSI_OUTPUT_ADR_START1) | RTSI_Trig_Output_Bits(1,
@@ -5341,12 +5343,14 @@
 	devpriv->stc_writew(dev, devpriv->rtsi_trig_b_output_reg,
 		RTSI_Trig_B_Output_Register);
 
-	// Sets the source and direction of the 4 on board lines
-//      devpriv->stc_writew(dev, 0x0000, RTSI_Board_Register);
+/*
+* Sets the source and direction of the 4 on board lines
+* devpriv->stc_writew(dev, 0x0000, RTSI_Board_Register);
+*/
 }
 
-static int ni_rtsi_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_rtsi_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -5389,8 +5393,8 @@
 		}
 	}
 	if (best_period_picosec == 0) {
-		rt_printk("%s: bug, failed to find pll parameters\n",
-			__FUNCTION__);
+		printk("%s: bug, failed to find pll parameters\n",
+			__func__);
 		return -EIO;
 	}
 	*freq_divider = best_div;
@@ -5401,7 +5405,7 @@
 	return 0;
 }
 
-static inline unsigned num_configurable_rtsi_channels(struct comedi_device * dev)
+static inline unsigned num_configurable_rtsi_channels(struct comedi_device *dev)
 {
 	if (boardtype.reg_type & ni_reg_m_series_mask)
 		return 8;
@@ -5409,7 +5413,7 @@
 		return 7;
 }
 
-static int ni_mseries_set_pll_master_clock(struct comedi_device * dev, unsigned source,
+static int ni_mseries_set_pll_master_clock(struct comedi_device *dev, unsigned source,
 	unsigned period_ns)
 {
 	static const unsigned min_period_ns = 50;
@@ -5422,11 +5426,11 @@
 	int retval;
 	if (source == NI_MIO_PLL_PXI10_CLOCK)
 		period_ns = 100;
-	// these limits are somewhat arbitrary, but NI advertises 1 to 20MHz range so we'll use that
+	/*  these limits are somewhat arbitrary, but NI advertises 1 to 20MHz range so we'll use that */
 	if (period_ns < min_period_ns || period_ns > max_period_ns) {
-		rt_printk
+		printk
 			("%s: you must specify an input clock frequency between %i and %i nanosec "
-			"for the phased-lock loop.\n", __FUNCTION__,
+			"for the phased-lock loop.\n", __func__,
 			min_period_ns, max_period_ns);
 		return -EINVAL;
 	}
@@ -5484,8 +5488,10 @@
 	pll_control_bits |=
 		MSeries_PLL_Divisor_Bits(freq_divider) |
 		MSeries_PLL_Multiplier_Bits(freq_multiplier);
-//      rt_printk("using divider=%i, multiplier=%i for PLL.  pll_control_bits = 0x%x\n", freq_divider, freq_multiplier, pll_control_bits);
-//      rt_printk("clock_ns=%d\n", devpriv->clock_ns);
+
+	/* printk("using divider=%i, multiplier=%i for PLL. pll_control_bits = 0x%x\n",
+	 * freq_divider, freq_multiplier, pll_control_bits); */
+	/* printk("clock_ns=%d\n", devpriv->clock_ns); */
 	ni_writew(pll_control_bits, M_Offset_PLL_Control);
 	devpriv->clock_source = source;
 	/* it seems to typically take a few hundred microseconds for PLL to lock */
@@ -5496,15 +5502,15 @@
 		udelay(1);
 	}
 	if (i == timeout) {
-		rt_printk
+		printk
 			("%s: timed out waiting for PLL to lock to reference clock source %i with period %i ns.\n",
-			__FUNCTION__, source, period_ns);
+			__func__, source, period_ns);
 		return -ETIMEDOUT;
 	}
 	return 3;
 }
 
-static int ni_set_master_clock(struct comedi_device * dev, unsigned source,
+static int ni_set_master_clock(struct comedi_device *dev, unsigned source,
 	unsigned period_ns)
 {
 	if (source == NI_MIO_INTERNAL_CLOCK) {
@@ -5533,9 +5539,9 @@
 					devpriv->rtsi_trig_direction_reg,
 					RTSI_Trig_Direction_Register);
 				if (period_ns == 0) {
-					rt_printk
+					printk
 						("%s: we don't handle an unspecified clock period correctly yet, returning error.\n",
-						__FUNCTION__);
+						__func__);
 					return -EINVAL;
 				} else {
 					devpriv->clock_ns = period_ns;
@@ -5548,7 +5554,7 @@
 	return 3;
 }
 
-static int ni_valid_rtsi_output_source(struct comedi_device * dev, unsigned chan,
+static int ni_valid_rtsi_output_source(struct comedi_device *dev, unsigned chan,
 	unsigned source)
 {
 	if (chan >= num_configurable_rtsi_channels(dev)) {
@@ -5556,9 +5562,9 @@
 			if (source == NI_RTSI_OUTPUT_RTSI_OSC)
 				return 1;
 			else {
-				rt_printk
+				printk
 					("%s: invalid source for channel=%i, channel %i is always the RTSI clock for pre-m-series boards.\n",
-					__FUNCTION__, chan,
+					__func__, chan,
 					old_RTSI_clock_channel);
 				return 0;
 			}
@@ -5589,7 +5595,7 @@
 	}
 }
 
-static int ni_set_rtsi_routing(struct comedi_device * dev, unsigned chan,
+static int ni_set_rtsi_routing(struct comedi_device *dev, unsigned chan,
 	unsigned source)
 {
 	if (ni_valid_rtsi_output_source(dev, chan, source) == 0)
@@ -5610,7 +5616,7 @@
 	return 2;
 }
 
-static unsigned ni_get_rtsi_routing(struct comedi_device * dev, unsigned chan)
+static unsigned ni_get_rtsi_routing(struct comedi_device *dev, unsigned chan)
 {
 	if (chan < 4) {
 		return RTSI_Trig_Output_Source(chan,
@@ -5621,13 +5627,13 @@
 	} else {
 		if (chan == old_RTSI_clock_channel)
 			return NI_RTSI_OUTPUT_RTSI_OSC;
-		rt_printk("%s: bug! should never get here?\n", __FUNCTION__);
+		printk("%s: bug! should never get here?\n", __func__);
 		return 0;
 	}
 }
 
-static int ni_rtsi_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ni_rtsi_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int chan = CR_CHAN(insn->chanspec);
 	switch (data[0]) {
@@ -5698,7 +5704,7 @@
 	return 1;
 }
 
-static int cs5529_wait_for_idle(struct comedi_device * dev)
+static int cs5529_wait_for_idle(struct comedi_device *dev)
 {
 	unsigned short status;
 	const int timeout = HZ;
@@ -5714,15 +5720,15 @@
 			return -EIO;
 		}
 	}
-//printk("looped %i times waiting for idle\n", i);
+/* printk("looped %i times waiting for idle\n", i); */
 	if (i == timeout) {
-		rt_printk("%s: %s: timeout\n", __FILE__, __FUNCTION__);
+		printk("%s: %s: timeout\n", __FILE__, __func__);
 		return -ETIME;
 	}
 	return 0;
 }
 
-static void cs5529_command(struct comedi_device * dev, unsigned short value)
+static void cs5529_command(struct comedi_device *dev, unsigned short value)
 {
 	static const int timeout = 100;
 	int i;
@@ -5735,16 +5741,16 @@
 	for (i = 0; i < timeout; i++) {
 		if ((ni_ao_win_inw(dev, CAL_ADC_Status_67xx) & CSS_ADC_BUSY))
 			break;
-		comedi_udelay(1);
+		udelay(1);
 	}
-//printk("looped %i times writing command to cs5529\n", i);
+/* printk("looped %i times writing command to cs5529\n", i); */
 	if (i == timeout) {
 		comedi_error(dev, "possible problem - never saw adc go busy?");
 	}
 }
 
 /* write to cs5529 register */
-static void cs5529_config_write(struct comedi_device * dev, unsigned int value,
+static void cs5529_config_write(struct comedi_device *dev, unsigned int value,
 	unsigned int reg_select_bits)
 {
 	ni_ao_win_outw(dev, ((value >> 16) & 0xff),
@@ -5759,7 +5765,7 @@
 
 #ifdef NI_CS5529_DEBUG
 /* read from cs5529 register */
-static unsigned int cs5529_config_read(struct comedi_device * dev,
+static unsigned int cs5529_config_read(struct comedi_device *dev,
 	unsigned int reg_select_bits)
 {
 	unsigned int value;
@@ -5775,7 +5781,7 @@
 }
 #endif
 
-static int cs5529_do_conversion(struct comedi_device * dev, unsigned short *data)
+static int cs5529_do_conversion(struct comedi_device *dev, unsigned short *data)
 {
 	int retval;
 	unsigned short status;
@@ -5789,12 +5795,12 @@
 	}
 	status = ni_ao_win_inw(dev, CAL_ADC_Status_67xx);
 	if (status & CSS_OSC_DETECT) {
-		rt_printk
+		printk
 			("ni_mio_common: cs5529 conversion error, status CSS_OSC_DETECT\n");
 		return -EIO;
 	}
 	if (status & CSS_OVERRANGE) {
-		rt_printk
+		printk
 			("ni_mio_common: cs5529 conversion error, overrange (ignoring)\n");
 	}
 	if (data) {
@@ -5805,8 +5811,8 @@
 	return 0;
 }
 
-static int cs5529_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int cs5529_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, retval;
 	unsigned short sample;
@@ -5831,7 +5837,7 @@
 	return insn->n;
 }
 
-static int init_cs5529(struct comedi_device * dev)
+static int init_cs5529(struct comedi_device *dev)
 {
 	unsigned int config_bits =
 		CSCFG_PORT_MODE | CSCFG_WORD_RATE_2180_CYCLES;
@@ -5851,11 +5857,11 @@
 		comedi_error(dev, "timeout or signal in init_cs5529()\n");
 #endif
 #ifdef NI_CS5529_DEBUG
-	rt_printk("config: 0x%x\n", cs5529_config_read(dev,
+	printk("config: 0x%x\n", cs5529_config_read(dev,
 		CSCMD_CONFIG_REGISTER));
-	rt_printk("gain: 0x%x\n", cs5529_config_read(dev,
+	printk("gain: 0x%x\n", cs5529_config_read(dev,
 		CSCMD_GAIN_REGISTER));
-	rt_printk("offset: 0x%x\n", cs5529_config_read(dev,
+	printk("offset: 0x%x\n", cs5529_config_read(dev,
 		CSCMD_OFFSET_REGISTER));
 #endif
 	return 0;
diff --git a/drivers/staging/comedi/drivers/ni_mio_cs.c b/drivers/staging/comedi/drivers/ni_mio_cs.c
index d6357c2..4d408d4 100644
--- a/drivers/staging/comedi/drivers/ni_mio_cs.c
+++ b/drivers/staging/comedi/drivers/ni_mio_cs.c
@@ -66,103 +66,103 @@
 
 #define MAX_N_CALDACS 32
 
-static const ni_board ni_boards[] = {
-      {device_id:0x010d,
-	      name:	"DAQCard-ai-16xe-50",
-	      n_adchan:16,
-	      adbits:	16,
-	      ai_fifo_depth:1024,
-	      alwaysdither:0,
-	      gainlkup:ai_gain_8,
-	      ai_speed:5000,
-	      n_aochan:0,
-	      aobits:	0,
-	      ao_fifo_depth:0,
-	      ao_unipolar:0,
-	      num_p0_dio_channels:8,
-	      has_8255:0,
-	      caldac:	{dac8800, dac8043},
-		},
-      {device_id:0x010c,
-	      name:	"DAQCard-ai-16e-4",
-	      n_adchan:16,
-	      adbits:	12,
-	      ai_fifo_depth:1024,
-	      alwaysdither:0,
-	      gainlkup:ai_gain_16,
-	      ai_speed:4000,
-	      n_aochan:0,
-	      aobits:	0,
-	      ao_fifo_depth:0,
-	      ao_unipolar:0,
-	      num_p0_dio_channels:8,
-	      has_8255:0,
-	      caldac:	{mb88341},	/* verified */
-		},
-      {device_id:0x02c4,
-	      name:	"DAQCard-6062E",
-	      n_adchan:16,
-	      adbits:	12,
-	      ai_fifo_depth:8192,
-	      alwaysdither:0,
-	      gainlkup:ai_gain_16,
-	      ai_speed:2000,
-	      n_aochan:2,
-	      aobits:	12,
-	      ao_fifo_depth:2048,
-	      ao_range_table:&range_bipolar10,
-	      ao_unipolar:0,
-	      ao_speed:1176,
-	      num_p0_dio_channels:8,
-	      has_8255:0,
-	      caldac:	{ad8804_debug},	/* verified */
-		},
-      {device_id:0x075e,
-	      name:	"DAQCard-6024E",	/* specs incorrect! */
-	      n_adchan:16,
-	      adbits:	12,
-	      ai_fifo_depth:1024,
-	      alwaysdither:0,
-	      gainlkup:ai_gain_16,
-	      ai_speed:5000,
-	      n_aochan:2,
-	      aobits:	12,
-	      ao_fifo_depth:0,
-	      ao_range_table:&range_bipolar10,
-	      ao_unipolar:0,
-	      ao_speed:1000000,
-	      num_p0_dio_channels:8,
-	      has_8255:0,
-	      caldac:	{ad8804_debug},
-		},
-      {device_id:0x0245,
-	      name:	"DAQCard-6036E",	/* specs incorrect! */
-	      n_adchan:16,
-	      adbits:	16,
-	      ai_fifo_depth:1024,
-	      alwaysdither:1,
-	      gainlkup:ai_gain_4,
-	      ai_speed:5000,
-	      n_aochan:2,
-	      aobits:	16,
-	      ao_fifo_depth:0,
-	      ao_range_table:&range_bipolar10,
-	      ao_unipolar:0,
-	      ao_speed:1000000,
-	      num_p0_dio_channels:8,
-	      has_8255:0,
-	      caldac:	{ad8804_debug},
-		},
+static const struct ni_board_struct ni_boards[] = {
+	{.device_id = 0x010d,
+	 .name = "DAQCard-ai-16xe-50",
+	 .n_adchan = 16,
+	 .adbits = 16,
+	 .ai_fifo_depth = 1024,
+	 .alwaysdither = 0,
+	 .gainlkup = ai_gain_8,
+	 .ai_speed = 5000,
+	 .n_aochan = 0,
+	 .aobits = 0,
+	 .ao_fifo_depth = 0,
+	 .ao_unipolar = 0,
+	 .num_p0_dio_channels = 8,
+	 .has_8255 = 0,
+	 .caldac = {dac8800, dac8043},
+	},
+	{.device_id = 0x010c,
+	 .name = "DAQCard-ai-16e-4",
+	 .n_adchan = 16,
+	 .adbits = 12,
+	 .ai_fifo_depth = 1024,
+	 .alwaysdither = 0,
+	 .gainlkup = ai_gain_16,
+	 .ai_speed = 4000,
+	 .n_aochan = 0,
+	 .aobits = 0,
+	 .ao_fifo_depth = 0,
+	 .ao_unipolar = 0,
+	 .num_p0_dio_channels = 8,
+	 .has_8255 = 0,
+	 .caldac = {mb88341},	/* verified */
+	},
+	{.device_id = 0x02c4,
+	 .name = "DAQCard-6062E",
+	 .n_adchan = 16,
+	 .adbits = 12,
+	 .ai_fifo_depth = 8192,
+	 .alwaysdither = 0,
+	 .gainlkup = ai_gain_16,
+	 .ai_speed = 2000,
+	 .n_aochan = 2,
+	 .aobits = 12,
+	 .ao_fifo_depth = 2048,
+	 .ao_range_table = &range_bipolar10,
+	 .ao_unipolar = 0,
+	 .ao_speed = 1176,
+	 .num_p0_dio_channels = 8,
+	 .has_8255 = 0,
+	 .caldac = {ad8804_debug},	/* verified */
+	},
+	{.device_id = 0x075e,
+	 .name = "DAQCard-6024E",	/* specs incorrect! */
+	 .n_adchan = 16,
+	 .adbits = 12,
+	 .ai_fifo_depth = 1024,
+	 .alwaysdither = 0,
+	 .gainlkup = ai_gain_16,
+	 .ai_speed = 5000,
+	 .n_aochan = 2,
+	 .aobits = 12,
+	 .ao_fifo_depth = 0,
+	 .ao_range_table = &range_bipolar10,
+	 .ao_unipolar = 0,
+	 .ao_speed = 1000000,
+	 .num_p0_dio_channels = 8,
+	 .has_8255 = 0,
+	 .caldac = {ad8804_debug},
+	},
+	{.device_id = 0x0245,
+	 .name = "DAQCard-6036E",	/* specs incorrect! */
+	 .n_adchan = 16,
+	 .adbits = 16,
+	 .ai_fifo_depth = 1024,
+	 .alwaysdither = 1,
+	 .gainlkup = ai_gain_4,
+	 .ai_speed = 5000,
+	 .n_aochan = 2,
+	 .aobits = 16,
+	 .ao_fifo_depth = 0,
+	 .ao_range_table = &range_bipolar10,
+	 .ao_unipolar = 0,
+	 .ao_speed = 1000000,
+	 .num_p0_dio_channels = 8,
+	 .has_8255 = 0,
+	 .caldac = {ad8804_debug},
+	},
 #if 0
-      {device_id:0x0000,	/* unknown */
-	      name:	"DAQCard-6715",
-	      n_adchan:0,
-	      n_aochan:8,
-	      aobits:	12,
-	      ao_671x:	8192,
-	      num_p0_dio_channels:8,
-	      caldac:	{mb88341, mb88341},
-		},
+	{.device_id = 0x0000,	/* unknown */
+	 .name = "DAQCard-6715",
+	 .n_adchan = 0,
+	 .n_aochan = 8,
+	 .aobits = 12,
+	 .ao_671x = 8192,
+	 .num_p0_dio_channels = 8,
+	 .caldac = {mb88341, mb88341},
+	},
 #endif
 	/* N.B. Update ni_mio_cs_ids[] when entries added above. */
 };
@@ -183,11 +183,11 @@
 
 /* How we access registers */
 
-#define ni_writel(a,b)		(outl((a),(b)+dev->iobase))
+#define ni_writel(a, b)		(outl((a), (b)+dev->iobase))
 #define ni_readl(a)		(inl((a)+dev->iobase))
-#define ni_writew(a,b)		(outw((a),(b)+dev->iobase))
+#define ni_writew(a, b)		(outw((a), (b)+dev->iobase))
 #define ni_readw(a)		(inw((a)+dev->iobase))
-#define ni_writeb(a,b)		(outb((a),(b)+dev->iobase))
+#define ni_writeb(a, b)		(outb((a), (b)+dev->iobase))
 #define ni_readb(a)		(inb((a)+dev->iobase))
 
 /* How we access windowed registers */
@@ -196,60 +196,60 @@
  * read/written directly in the I/O space of the board.  The
  * DAQCard devices map the low 8 STC registers to iobase+addr*2. */
 
-static void mio_cs_win_out(struct comedi_device * dev, uint16_t data, int addr)
+static void mio_cs_win_out(struct comedi_device *dev, uint16_t data, int addr)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->window_lock, flags);
+	spin_lock_irqsave(&devpriv->window_lock, flags);
 	if (addr < 8) {
 		ni_writew(data, addr * 2);
 	} else {
 		ni_writew(addr, Window_Address);
 		ni_writew(data, Window_Data);
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->window_lock, flags);
+	spin_unlock_irqrestore(&devpriv->window_lock, flags);
 }
 
-static uint16_t mio_cs_win_in(struct comedi_device * dev, int addr)
+static uint16_t mio_cs_win_in(struct comedi_device *dev, int addr)
 {
 	unsigned long flags;
 	uint16_t ret;
 
-	comedi_spin_lock_irqsave(&devpriv->window_lock, flags);
+	spin_lock_irqsave(&devpriv->window_lock, flags);
 	if (addr < 8) {
 		ret = ni_readw(addr * 2);
 	} else {
 		ni_writew(addr, Window_Address);
 		ret = ni_readw(Window_Data);
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->window_lock, flags);
+	spin_unlock_irqrestore(&devpriv->window_lock, flags);
 
 	return ret;
 }
 
-static int mio_cs_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int mio_cs_detach(struct comedi_device * dev);
+static int mio_cs_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int mio_cs_detach(struct comedi_device *dev);
 static struct comedi_driver driver_ni_mio_cs = {
-      driver_name:"ni_mio_cs",
-      module:THIS_MODULE,
-      attach:mio_cs_attach,
-      detach:mio_cs_detach,
+	.driver_name = "ni_mio_cs",
+	.module = THIS_MODULE,
+	.attach = mio_cs_attach,
+	.detach = mio_cs_detach,
 };
 
 #include "ni_mio_common.c"
 
-static int ni_getboardtype(struct comedi_device * dev, struct pcmcia_device *link);
+static int ni_getboardtype(struct comedi_device *dev, struct pcmcia_device *link);
 
 /* clean up allocated resources */
 /* called when driver is removed */
-static int mio_cs_detach(struct comedi_device * dev)
+static int mio_cs_detach(struct comedi_device *dev)
 {
 	mio_common_detach(dev);
 
 	/* PCMCIA layer frees the IO region */
 
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 
 	return 0;
@@ -344,7 +344,7 @@
 		manfid = le16_to_cpu(buf[0]);
 		prodid = le16_to_cpu(buf[1]);
 	}
-	//printk("manfid = 0x%04x, 0x%04x\n",manfid,prodid);
+	/* printk("manfid = 0x%04x, 0x%04x\n",manfid,prodid); */
 
 	tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
 	tuple.Attributes = 0;
@@ -381,7 +381,7 @@
 		for (base = 0x000; base < 0x400; base += 0x20) {
 			link->io.BasePort1 = base;
 			ret = pcmcia_request_io(link, &link->io);
-			//printk("RequestIO 0x%02x\n",ret);
+			/* printk("RequestIO 0x%02x\n",ret); */
 			if (!ret)
 				break;
 		}
@@ -393,17 +393,17 @@
 	if (ret) {
 		printk("pcmcia_request_irq() returned error: %i\n", ret);
 	}
-	//printk("RequestIRQ 0x%02x\n",ret);
+	/* printk("RequestIRQ 0x%02x\n",ret); */
 
 	link->conf.ConfigIndex = 1;
 
 	ret = pcmcia_request_configuration(link, &link->conf);
-	//printk("RequestConfiguration %d\n",ret);
+	/* printk("RequestConfiguration %d\n",ret); */
 
 	link->dev_node = &dev_node;
 }
 
-static int mio_cs_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int mio_cs_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct pcmcia_device *link;
 	unsigned int irq;
@@ -446,29 +446,33 @@
 	printk(" %s", boardtype.name);
 	dev->board_name = boardtype.name;
 
-	if ((ret = comedi_request_irq(irq, ni_E_interrupt, NI_E_IRQ_FLAGS,
-				"ni_mio_cs", dev)) < 0) {
+	ret = request_irq(irq, ni_E_interrupt, NI_E_IRQ_FLAGS,
+				 "ni_mio_cs", dev);
+	if (ret < 0) {
 		printk(" irq not available\n");
 		return -EINVAL;
 	}
 	dev->irq = irq;
 
 	/* allocate private area */
-	if ((ret = ni_alloc_private(dev)) < 0)
+	ret = ni_alloc_private(dev);
+	if (ret < 0)
 		return ret;
+
 	devpriv->stc_writew = &mio_cs_win_out;
 	devpriv->stc_readw = &mio_cs_win_in;
 	devpriv->stc_writel = &win_out2;
 	devpriv->stc_readl = &win_in2;
 
-	if ((ret = ni_E_init(dev, it)) < 0) {
+	ret = ni_E_init(dev, it);
+
+	if (ret < 0)
 		return ret;
-	}
 
 	return 0;
 }
 
-static int get_prodid(struct comedi_device * dev, struct pcmcia_device *link)
+static int get_prodid(struct comedi_device *dev, struct pcmcia_device *link)
 {
 	tuple_t tuple;
 	u_short buf[128];
@@ -487,7 +491,7 @@
 	return prodid;
 }
 
-static int ni_getboardtype(struct comedi_device * dev, struct pcmcia_device *link)
+static int ni_getboardtype(struct comedi_device *dev, struct pcmcia_device *link)
 {
 	int id;
 	int i;
diff --git a/drivers/staging/comedi/drivers/ni_pcidio.c b/drivers/staging/comedi/drivers/ni_pcidio.c
index 87def2c..6b86a39 100644
--- a/drivers/staging/comedi/drivers/ni_pcidio.c
+++ b/drivers/staging/comedi/drivers/ni_pcidio.c
@@ -66,9 +66,10 @@
  */
 
 #define USE_DMA
-//#define DEBUG 1
-//#define DEBUG_FLAGS
+/* #define DEBUG 1 */
+/* #define DEBUG_FLAGS */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include "mite.h"
@@ -117,9 +118,9 @@
 #define Waited				(1<<5)
 #define PrimaryTC				(1<<6)
 #define SecondaryTC				(1<<7)
-  //#define SerialRose
-  //#define ReqRose
-  //#define Paused
+  /* #define SerialRose */
+  /* #define ReqRose */
+  /* #define Paused */
 
 #define Group_1_First_Clear		6	/* W */
 #define Group_2_First_Clear		7	/* W */
@@ -206,7 +207,7 @@
 
 #define DMA_Line_Control_Group1		76
 #define DMA_Line_Control_Group2		108
-// channel zero is none
+/* channel zero is none */
 static inline unsigned primary_DMAChannel_bits(unsigned channel)
 {
 	return channel & 0x3;
@@ -287,15 +288,15 @@
 #define IntEn (TransferReady|CountExpired|Waited|PrimaryTC|SecondaryTC)
 #endif
 
-static int nidio_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int nidio_detach(struct comedi_device * dev);
-static int ni_pcidio_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
+static int nidio_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int nidio_detach(struct comedi_device *dev);
+static int ni_pcidio_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
 
 static struct comedi_driver driver_pcidio = {
-      driver_name:"ni_pcidio",
-      module:THIS_MODULE,
-      attach:nidio_attach,
-      detach:nidio_detach,
+	.driver_name = "ni_pcidio",
+	.module = THIS_MODULE,
+	.attach = nidio_attach,
+	.detach = nidio_detach,
 };
 
 struct nidio_board {
@@ -309,65 +310,65 @@
 
 static const struct nidio_board nidio_boards[] = {
 	{
-	      dev_id:	0x1150,
-	      name:	"pci-dio-32hs",
-	      n_8255:	0,
-	      is_diodaq:1,
+	.dev_id = 0x1150,
+	.name = "pci-dio-32hs",
+	.n_8255 = 0,
+	.is_diodaq = 1,
 		},
 	{
-	      dev_id:	0x1320,
-	      name:	"pxi-6533",
-	      n_8255:	0,
-	      is_diodaq:1,
+	.dev_id = 0x1320,
+	.name = "pxi-6533",
+	.n_8255 = 0,
+	.is_diodaq = 1,
 		},
 	{
-	      dev_id:	0x12b0,
-	      name:	"pci-6534",
-	      n_8255:	0,
-	      is_diodaq:1,
-	      uses_firmware:1,
+	.dev_id = 0x12b0,
+	.name = "pci-6534",
+	.n_8255 = 0,
+	.is_diodaq = 1,
+	.uses_firmware = 1,
 		},
 	{
-	      dev_id:	0x0160,
-	      name:	"pci-dio-96",
-	      n_8255:	4,
-	      is_diodaq:0,
+	.dev_id = 0x0160,
+	.name = "pci-dio-96",
+	.n_8255 = 4,
+	.is_diodaq = 0,
 		},
 	{
-	      dev_id:	0x1630,
-	      name:	"pci-dio-96b",
-	      n_8255:	4,
-	      is_diodaq:0,
+	.dev_id = 0x1630,
+	.name = "pci-dio-96b",
+	.n_8255 = 4,
+	.is_diodaq = 0,
 		},
 	{
-	      dev_id:	0x13c0,
-	      name:	"pxi-6508",
-	      n_8255:	4,
-	      is_diodaq:0,
+	.dev_id = 0x13c0,
+	.name = "pxi-6508",
+	.n_8255 = 4,
+	.is_diodaq = 0,
 		},
 	{
-	      dev_id:	0x0400,
-	      name:	"pci-6503",
-	      n_8255:	1,
-	      is_diodaq:0,
+	.dev_id = 0x0400,
+	.name = "pci-6503",
+	.n_8255 = 1,
+	.is_diodaq = 0,
 		},
 	{
-	      dev_id:	0x1250,
-	      name:	"pci-6503b",
-	      n_8255:	1,
-	      is_diodaq:0,
+	.dev_id = 0x1250,
+	.name = "pci-6503b",
+	.n_8255 = 1,
+	.is_diodaq = 0,
 		},
 	{
-	      dev_id:	0x17d0,
-	      name:	"pci-6503x",
-	      n_8255:	1,
-	      is_diodaq:0,
+	.dev_id = 0x17d0,
+	.name = "pci-6503x",
+	.n_8255 = 1,
+	.is_diodaq = 0,
 		},
 	{
-	      dev_id:	0x1800,
-	      name:	"pxi-6503",
-	      n_8255:	1,
-	      is_diodaq:0,
+	.dev_id = 0x1800,
+	.name = "pxi-6503",
+	.n_8255 = 1,
+	.is_diodaq = 0,
 		},
 };
 
@@ -401,14 +402,14 @@
 };
 #define devpriv ((struct nidio96_private *)dev->private)
 
-static int ni_pcidio_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int ni_pcidio_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int ni_pcidio_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_pcidio_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int ni_pcidio_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int ni_pcidio_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum);
-static int nidio_find_device(struct comedi_device * dev, int bus, int slot);
+static int nidio_find_device(struct comedi_device *dev, int bus, int slot);
 static int ni_pcidio_ns_to_timer(int *nanosec, int round_mode);
-static int setup_mite_dma(struct comedi_device * dev, struct comedi_subdevice * s);
+static int setup_mite_dma(struct comedi_device *dev, struct comedi_subdevice *s);
 
 #ifdef DEBUG_FLAGS
 static void ni_pcidio_print_flags(unsigned int flags);
@@ -418,18 +419,17 @@
 #define ni_pcidio_print_status(x)
 #endif
 
-static int ni_pcidio_request_di_mite_channel(struct comedi_device * dev)
+static int ni_pcidio_request_di_mite_channel(struct comedi_device *dev)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	BUG_ON(devpriv->di_mite_chan);
 	devpriv->di_mite_chan =
 		mite_request_channel_in_range(devpriv->mite,
 		devpriv->di_mite_ring, 1, 2);
 	if (devpriv->di_mite_chan == NULL) {
-		comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock,
-			flags);
+		spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 		comedi_error(dev, "failed to reserve mite dma channel.");
 		return -EBUSY;
 	}
@@ -437,15 +437,15 @@
 		secondary_DMAChannel_bits(devpriv->di_mite_chan->channel),
 		devpriv->mite->daq_io_addr + DMA_Line_Control_Group1);
 	mmiowb();
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 	return 0;
 }
 
-static void ni_pcidio_release_di_mite_channel(struct comedi_device * dev)
+static void ni_pcidio_release_di_mite_channel(struct comedi_device *dev)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
 	if (devpriv->di_mite_chan) {
 		mite_dma_disarm(devpriv->di_mite_chan);
 		mite_dma_reset(devpriv->di_mite_chan);
@@ -456,7 +456,7 @@
 			devpriv->mite->daq_io_addr + DMA_Line_Control_Group1);
 		mmiowb();
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
 }
 
 static int nidio96_8255_cb(int dir, int port, int data, unsigned long iobase)
@@ -469,7 +469,7 @@
 	}
 }
 
-void ni_pcidio_event(struct comedi_device * dev, struct comedi_subdevice * s)
+void ni_pcidio_event(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	if (s->async->
 		events & (COMEDI_CB_EOA | COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW))
@@ -479,14 +479,14 @@
 	comedi_event(dev, s);
 }
 
-static irqreturn_t nidio_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t nidio_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s = dev->subdevices;
 	struct comedi_async *async = s->async;
 	struct mite_struct *mite = devpriv->mite;
 
-	//int i, j;
+	/* int i, j; */
 	long int AuxData = 0;
 	short data1 = 0;
 	short data2 = 0;
@@ -496,9 +496,9 @@
 	unsigned int m_status = 0;
 	unsigned long irq_flags;
 
-	//interrupcions parasites
+	/* interrupcions parasites */
 	if (dev->attached == 0) {
-		// assume it's from another card
+		/* assume it's from another card */
 		return IRQ_NONE;
 	}
 
@@ -511,17 +511,17 @@
 	ni_pcidio_print_flags(flags);
 	ni_pcidio_print_status(status);
 
-	//printk("buf[0]=%08x\n",*(unsigned int *)async->prealloc_buf);
-	//printk("buf[4096]=%08x\n",*(unsigned int *)(async->prealloc_buf+4096));
+	/* printk("buf[0]=%08x\n",*(unsigned int *)async->prealloc_buf); */
+	/* printk("buf[4096]=%08x\n",*(unsigned int *)(async->prealloc_buf+4096)); */
 
-	comedi_spin_lock_irqsave(&devpriv->mite_channel_lock, irq_flags);
+	spin_lock_irqsave(&devpriv->mite_channel_lock, irq_flags);
 	if (devpriv->di_mite_chan)
 		m_status = mite_get_status(devpriv->di_mite_chan);
 #ifdef MITE_DEBUG
 	mite_print_chsr(m_status);
 #endif
-	//printk("mite_bytes_transferred: %d\n",mite_bytes_transferred(mite,DI_DMA_CHAN));
-	//mite_dump_regs(mite);
+	/* printk("mite_bytes_transferred: %d\n",mite_bytes_transferred(mite,DI_DMA_CHAN)); */
+	/* mite_dump_regs(mite); */
 	if (m_status & CHSR_INT) {
 		if (m_status & CHSR_LINKC) {
 			writel(CHOR_CLRLC,
@@ -537,7 +537,7 @@
 			disable_irq(dev->irq);
 		}
 	}
-	comedi_spin_unlock_irqrestore(&devpriv->mite_channel_lock, irq_flags);
+	spin_unlock_irqrestore(&devpriv->mite_channel_lock, irq_flags);
 
 	while (status & DataLeft) {
 		work++;
@@ -552,7 +552,7 @@
 		flags &= IntEn;
 
 		if (flags & TransferReady) {
-			//DPRINTK("TransferReady\n");
+			/* DPRINTK("TransferReady\n"); */
 			while (flags & TransferReady) {
 				work++;
 				if (work > 100) {
@@ -569,14 +569,14 @@
 				data2 = (AuxData & 0xffff0000) >> 16;
 				comedi_buf_put(async, data1);
 				comedi_buf_put(async, data2);
-				//DPRINTK("read:%d, %d\n",data1,data2);
+				/* DPRINTK("read:%d, %d\n",data1,data2); */
 				flags = readb(devpriv->mite->daq_io_addr +
 					Group_1_Flags);
 			}
-			//DPRINTK("buf_int_count: %d\n",async->buf_int_count);
-			//DPRINTK("1) IntEn=%d,flags=%d,status=%d\n",IntEn,flags,status);
-			//ni_pcidio_print_flags(flags);
-			//ni_pcidio_print_status(status);
+			/* DPRINTK("buf_int_count: %d\n",async->buf_int_count); */
+			/* DPRINTK("1) IntEn=%d,flags=%d,status=%d\n",IntEn,flags,status); */
+			/* ni_pcidio_print_flags(flags); */
+			/* ni_pcidio_print_status(status); */
 			async->events |= COMEDI_CB_BLOCK;
 		}
 
@@ -621,10 +621,10 @@
 		flags = readb(devpriv->mite->daq_io_addr + Group_1_Flags);
 		status = readb(devpriv->mite->daq_io_addr +
 			Interrupt_And_Window_Status);
-		//DPRINTK("loop end: IntEn=0x%02x,flags=0x%02x,status=0x%02x\n",
-		//      IntEn,flags,status);
-		//ni_pcidio_print_flags(flags);
-		//ni_pcidio_print_status(status);
+		/* DPRINTK("loop end: IntEn=0x%02x,flags=0x%02x,status=0x%02x\n", */
+		/* IntEn,flags,status); */
+		/* ni_pcidio_print_flags(flags); */
+		/* ni_pcidio_print_status(status); */
 	}
 
       out:
@@ -963,7 +963,7 @@
 
 	/* clear and enable interrupts */
 	writeb(0xff, devpriv->mite->daq_io_addr + Group_1_First_Clear);
-	//writeb(ClearExpired,devpriv->mite->daq_io_addr+Group_1_Second_Clear);
+	/* writeb(ClearExpired,devpriv->mite->daq_io_addr+Group_1_Second_Clear); */
 
 	writeb(IntEn, devpriv->mite->daq_io_addr + Interrupt_Control);
 	writeb(0x03,
@@ -971,7 +971,7 @@
 
 	if (cmd->stop_src == TRIG_NONE) {
 		devpriv->OpModeBits = DataLatching(0) | RunMode(7);
-	} else {		// TRIG_TIMER
+	} else {		/* TRIG_TIMER */
 		devpriv->OpModeBits = Numbered | RunMode(7);
 	}
 	if (cmd->start_src == TRIG_NOW) {
@@ -1235,8 +1235,8 @@
 			devpriv->mite->daq_io_addr +
 			Master_DMA_And_Interrupt_Control);
 
-		ret = comedi_request_irq(irq, nidio_interrupt, IRQF_SHARED,
-			"ni_pcidio", dev);
+		ret = request_irq(irq, nidio_interrupt, IRQF_SHARED,
+				  "ni_pcidio", dev);
 		if (ret < 0) {
 			printk(" irq not available");
 		}
@@ -1259,7 +1259,7 @@
 	}
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	if (devpriv) {
 		if (devpriv->di_mite_ring) {
diff --git a/drivers/staging/comedi/drivers/ni_pcimio.c b/drivers/staging/comedi/drivers/ni_pcimio.c
index 3a2aba7..1d04b75 100644
--- a/drivers/staging/comedi/drivers/ni_pcimio.c
+++ b/drivers/staging/comedi/drivers/ni_pcimio.c
@@ -101,7 +101,7 @@
 
 	need to slow down DAC loading.  I don't trust NI's claim that
 	two writes to the PCI bus slows IO enough.  I would prefer to
-	use comedi_udelay().  Timing specs: (clock)
+	use udelay().  Timing specs: (clock)
 		AD8522		30ns
 		DAC8043		120ns
 		DAC8800		60ns
@@ -117,7 +117,7 @@
 #include "ni_stc.h"
 #include "mite.h"
 
-//#define PCI_DEBUG
+/* #define PCI_DEBUG */
 
 #define PCIDMA
 
@@ -216,9 +216,9 @@
 	}
 };
 
-static const ni_board ni_boards[] = {
+static const struct ni_board_struct ni_boards[] = {
 	{
-			.device_id = 0x0162,	// NI also says 0x1620.  typo?
+			.device_id = 0x0162,	/*  NI also says 0x1620.  typo? */
 			.name = "pci-mio-16xe-50",
 			.n_adchan = 16,
 			.adbits = 16,
@@ -238,7 +238,7 @@
 		},
 	{
 			.device_id = 0x1170,
-			.name = "pci-mio-16xe-10",	// aka pci-6030E
+			.name = "pci-mio-16xe-10",	/*  aka pci-6030E */
 			.n_adchan = 16,
 			.adbits = 16,
 			.ai_fifo_depth = 512,
@@ -320,7 +320,7 @@
 			.ai_fifo_depth = 512,
 			.alwaysdither = 0,
 			.gainlkup = ai_gain_16,
-			/* Note: there have been reported problems with full speed
+			/*	.Note = there have been reported problems with full speed
 			 * on this board */
 			.ai_speed = 2000,
 			.n_aochan = 2,
@@ -330,7 +330,7 @@
 			.ao_unipolar = 1,
 			.ao_speed = 1000,
 			.num_p0_dio_channels = 8,
-			.caldac = {ad8804_debug},	// doc says mb88341
+			.caldac = {ad8804_debug},	/*  doc says mb88341 */
 			.has_8255 = 0,
 		},
 	{
@@ -846,7 +846,7 @@
 			.n_adchan = 16,
 			.adbits = 16,
 			.ai_fifo_depth = 512,
-			//FIXME:  guess
+			/*	.FIXME = guess */
 			.gainlkup = ai_gain_622x,
 			.ai_speed = 4000,
 			.n_aochan = 0,
@@ -1207,28 +1207,29 @@
 
 #define n_pcimio_boards ((sizeof(ni_boards)/sizeof(ni_boards[0])))
 
-static int pcimio_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcimio_detach(struct comedi_device * dev);
+static int pcimio_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcimio_detach(struct comedi_device *dev);
 static struct comedi_driver driver_pcimio = {
-	driver_name: DRV_NAME,
-	module:THIS_MODULE,
-	attach:pcimio_attach,
-	detach:pcimio_detach,
+	.driver_name = DRV_NAME,
+	.module = THIS_MODULE,
+	.attach = pcimio_attach,
+	.detach = pcimio_detach,
 };
 
 COMEDI_PCI_INITCLEANUP(driver_pcimio, ni_pci_table)
 
-typedef struct {
-NI_PRIVATE_COMMON} ni_private;
-#define devpriv ((ni_private *)dev->private)
+struct ni_private {
+	NI_PRIVATE_COMMON
+};
+#define devpriv ((struct ni_private *)dev->private)
 
 /* How we access registers */
 
-#define ni_writel(a,b)	(writel((a), devpriv->mite->daq_io_addr + (b)))
+#define ni_writel(a, b)	(writel((a), devpriv->mite->daq_io_addr + (b)))
 #define ni_readl(a)	(readl(devpriv->mite->daq_io_addr + (a)))
-#define ni_writew(a,b)	(writew((a), devpriv->mite->daq_io_addr + (b)))
+#define ni_writew(a, b)	(writew((a), devpriv->mite->daq_io_addr + (b)))
 #define ni_readw(a)	(readw(devpriv->mite->daq_io_addr + (a)))
-#define ni_writeb(a,b)	(writeb((a), devpriv->mite->daq_io_addr + (b)))
+#define ni_writeb(a, b)	(writeb((a), devpriv->mite->daq_io_addr + (b)))
 #define ni_readb(a)	(readb(devpriv->mite->daq_io_addr + (a)))
 
 /* How we access STC registers */
@@ -1241,30 +1242,30 @@
 /* However, the 611x boards still aren't working, so I'm disabling
  * non-windowed STC access temporarily */
 
-static void e_series_win_out(struct comedi_device * dev, uint16_t data, int reg)
+static void e_series_win_out(struct comedi_device *dev, uint16_t data, int reg)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&devpriv->window_lock, flags);
+	spin_lock_irqsave(&devpriv->window_lock, flags);
 	ni_writew(reg, Window_Address);
 	ni_writew(data, Window_Data);
-	comedi_spin_unlock_irqrestore(&devpriv->window_lock, flags);
+	spin_unlock_irqrestore(&devpriv->window_lock, flags);
 }
 
-static uint16_t e_series_win_in(struct comedi_device * dev, int reg)
+static uint16_t e_series_win_in(struct comedi_device *dev, int reg)
 {
 	unsigned long flags;
 	uint16_t ret;
 
-	comedi_spin_lock_irqsave(&devpriv->window_lock, flags);
+	spin_lock_irqsave(&devpriv->window_lock, flags);
 	ni_writew(reg, Window_Address);
 	ret = ni_readw(Window_Data);
-	comedi_spin_unlock_irqrestore(&devpriv->window_lock, flags);
+	spin_unlock_irqrestore(&devpriv->window_lock, flags);
 
 	return ret;
 }
 
-static void m_series_stc_writew(struct comedi_device * dev, uint16_t data, int reg)
+static void m_series_stc_writew(struct comedi_device *dev, uint16_t data, int reg)
 {
 	unsigned offset;
 	switch (reg) {
@@ -1293,12 +1294,12 @@
 		offset = M_Offset_AI_Personal;
 		break;
 	case AI_SI2_Load_A_Register:
-		// this is actually a 32 bit register on m series boards
+		/*  this is actually a 32 bit register on m series boards */
 		ni_writel(data, M_Offset_AI_SI2_Load_A);
 		return;
 		break;
 	case AI_SI2_Load_B_Register:
-		// this is actually a 32 bit register on m series boards
+		/*  this is actually a 32 bit register on m series boards */
 		ni_writel(data, M_Offset_AI_SI2_Load_B);
 		return;
 		break;
@@ -1348,9 +1349,9 @@
 		offset = M_Offset_AO_FIFO_Clear;
 		break;
 	case DIO_Control_Register:
-		rt_printk
+		printk
 			("%s: FIXME: register 0x%x does not map cleanly on to m-series boards.\n",
-			__FUNCTION__, reg);
+			__func__, reg);
 		return;
 		break;
 	case G_Autoincrement_Register(0):
@@ -1410,8 +1411,8 @@
 		/* FIXME: DIO_Output_Register (16 bit reg) is replaced by M_Offset_Static_Digital_Output (32 bit)
 		   and M_Offset_SCXI_Serial_Data_Out (8 bit) */
 	default:
-		rt_printk("%s: bug! unhandled register=0x%x in switch.\n",
-			__FUNCTION__, reg);
+		printk("%s: bug! unhandled register=0x%x in switch.\n",
+			__func__, reg);
 		BUG();
 		return;
 		break;
@@ -1419,7 +1420,7 @@
 	ni_writew(data, offset);
 }
 
-static uint16_t m_series_stc_readw(struct comedi_device * dev, int reg)
+static uint16_t m_series_stc_readw(struct comedi_device *dev, int reg)
 {
 	unsigned offset;
 	switch (reg) {
@@ -1445,8 +1446,8 @@
 		offset = M_Offset_G01_Status;
 		break;
 	default:
-		rt_printk("%s: bug! unhandled register=0x%x in switch.\n",
-			__FUNCTION__, reg);
+		printk("%s: bug! unhandled register=0x%x in switch.\n",
+			__func__, reg);
 		BUG();
 		return 0;
 		break;
@@ -1454,7 +1455,7 @@
 	return ni_readw(offset);
 }
 
-static void m_series_stc_writel(struct comedi_device * dev, uint32_t data, int reg)
+static void m_series_stc_writel(struct comedi_device *dev, uint32_t data, int reg)
 {
 	unsigned offset;
 	switch (reg) {
@@ -1486,8 +1487,8 @@
 		offset = M_Offset_G1_Load_B;
 		break;
 	default:
-		rt_printk("%s: bug! unhandled register=0x%x in switch.\n",
-			__FUNCTION__, reg);
+		printk("%s: bug! unhandled register=0x%x in switch.\n",
+			__func__, reg);
 		BUG();
 		return;
 		break;
@@ -1495,7 +1496,7 @@
 	ni_writel(data, offset);
 }
 
-static uint32_t m_series_stc_readl(struct comedi_device * dev, int reg)
+static uint32_t m_series_stc_readl(struct comedi_device *dev, int reg)
 {
 	unsigned offset;
 	switch (reg) {
@@ -1512,8 +1513,8 @@
 		offset = M_Offset_G1_Save;
 		break;
 	default:
-		rt_printk("%s: bug! unhandled register=0x%x in switch.\n",
-			__FUNCTION__, reg);
+		printk("%s: bug! unhandled register=0x%x in switch.\n",
+			__func__, reg);
 		BUG();
 		return 0;
 		break;
@@ -1528,19 +1529,19 @@
 
 #include "ni_mio_common.c"
 
-static int pcimio_find_device(struct comedi_device * dev, int bus, int slot);
-static int pcimio_ai_change(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pcimio_find_device(struct comedi_device *dev, int bus, int slot);
+static int pcimio_ai_change(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long new_size);
-static int pcimio_ao_change(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pcimio_ao_change(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long new_size);
-static int pcimio_gpct0_change(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pcimio_gpct0_change(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long new_size);
-static int pcimio_gpct1_change(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pcimio_gpct1_change(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long new_size);
-static int pcimio_dio_change(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pcimio_dio_change(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long new_size);
 
-static void m_series_init_eeprom_buffer(struct comedi_device * dev)
+static void m_series_init_eeprom_buffer(struct comedi_device *dev)
 {
 	static const int Start_Cal_EEPROM = 0x400;
 	static const unsigned window_size = 10;
@@ -1577,19 +1578,19 @@
 	writel(0x0, devpriv->mite->mite_io_addr + 0x30);
 }
 
-static void init_6143(struct comedi_device * dev)
+static void init_6143(struct comedi_device *dev)
 {
-	// Disable interrupts
+	/*  Disable interrupts */
 	devpriv->stc_writew(dev, 0, Interrupt_Control_Register);
 
-	// Initialise 6143 AI specific bits
-	ni_writeb(0x00, Magic_6143);	// Set G0,G1 DMA mode to E series version
-	ni_writeb(0x80, PipelineDelay_6143);	// Set EOCMode, ADCMode and pipelinedelay
-	ni_writeb(0x00, EOC_Set_6143);	// Set EOC Delay
+	/*  Initialise 6143 AI specific bits */
+	ni_writeb(0x00, Magic_6143);	/*  Set G0,G1 DMA mode to E series version */
+	ni_writeb(0x80, PipelineDelay_6143);	/*  Set EOCMode, ADCMode and pipelinedelay */
+	ni_writeb(0x00, EOC_Set_6143);	/*  Set EOC Delay */
 
-	ni_writel(boardtype.ai_fifo_depth / 2, AIFIFO_Flag_6143);	// Set the FIFO half full level
+	ni_writel(boardtype.ai_fifo_depth / 2, AIFIFO_Flag_6143);	/*  Set the FIFO half full level */
 
-	// Strobe Relay disable bit
+	/*  Strobe Relay disable bit */
 	devpriv->ai_calib_source_enabled = 0;
 	ni_writew(devpriv->ai_calib_source | Calibration_Channel_6143_RelayOff,
 		Calibration_Channel_6143);
@@ -1597,11 +1598,11 @@
 }
 
 /* cleans up allocated resources */
-static int pcimio_detach(struct comedi_device * dev)
+static int pcimio_detach(struct comedi_device *dev)
 {
 	mio_common_detach(dev);
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 	if (dev->private) {
 		mite_free_ring(devpriv->ai_mite_ring);
@@ -1616,7 +1617,7 @@
 	return 0;
 }
 
-static int pcimio_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcimio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int ret;
 
@@ -1678,9 +1679,9 @@
 		printk(" unknown irq (bad)\n");
 	} else {
 		printk(" ( irq = %u )", dev->irq);
-		if ((ret = comedi_request_irq(dev->irq, ni_E_interrupt,
-					NI_E_IRQ_FLAGS, DRV_NAME,
-					dev)) < 0) {
+		ret = request_irq(dev->irq, ni_E_interrupt, NI_E_IRQ_FLAGS,
+				  DRV_NAME, dev);
+		if (ret < 0) {
 			printk(" irq not available\n");
 			dev->irq = 0;
 		}
@@ -1699,7 +1700,7 @@
 	return ret;
 }
 
-static int pcimio_find_device(struct comedi_device * dev, int bus, int slot)
+static int pcimio_find_device(struct comedi_device *dev, int bus, int slot)
 {
 	struct mite_struct *mite;
 	int i;
@@ -1727,7 +1728,7 @@
 	return -EIO;
 }
 
-static int pcimio_ai_change(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pcimio_ai_change(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long new_size)
 {
 	int ret;
@@ -1739,7 +1740,7 @@
 	return 0;
 }
 
-static int pcimio_ao_change(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pcimio_ao_change(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long new_size)
 {
 	int ret;
@@ -1751,7 +1752,7 @@
 	return 0;
 }
 
-static int pcimio_gpct0_change(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pcimio_gpct0_change(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long new_size)
 {
 	int ret;
@@ -1763,7 +1764,7 @@
 	return 0;
 }
 
-static int pcimio_gpct1_change(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pcimio_gpct1_change(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long new_size)
 {
 	int ret;
@@ -1775,7 +1776,7 @@
 	return 0;
 }
 
-static int pcimio_dio_change(struct comedi_device * dev, struct comedi_subdevice * s,
+static int pcimio_dio_change(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned long new_size)
 {
 	int ret;
diff --git a/drivers/staging/comedi/drivers/ni_stc.h b/drivers/staging/comedi/drivers/ni_stc.h
index 1ebf521..fcaedb3 100644
--- a/drivers/staging/comedi/drivers/ni_stc.h
+++ b/drivers/staging/comedi/drivers/ni_stc.h
@@ -262,7 +262,7 @@
 #define AO_Trigger_Once				_bit0
 
 #define AO_Mode_2_Register		39
-#define AO_FIFO_Mode_Mask ( 0x3 << 14 )
+#define AO_FIFO_Mode_Mask (0x3 << 14)
 enum AO_FIFO_Mode_Bits {
 	AO_FIFO_Mode_HF_to_F = (3 << 14),
 	AO_FIFO_Mode_F = (2 << 14),
@@ -318,7 +318,7 @@
 };
 static inline unsigned FOUT_Divider(unsigned divider)
 {
-	return (divider & FOUT_Divider_mask);
+	return divider & FOUT_Divider_mask;
 }
 
 #define IO_Bidirection_Pin_Register	57
@@ -339,7 +339,7 @@
 		max_channel = 6;
 	}
 	if (channel > max_channel) {
-		rt_printk("%s: bug, invalid RTSI_channel=%i\n", __FUNCTION__,
+		printk("%s: bug, invalid RTSI_channel=%i\n", __func__,
 			channel);
 		return 0;
 	}
@@ -521,13 +521,13 @@
 	AO_FIFO_Flags_Polarity = 1 << 11,	/* M Series: reserved */
 	AO_TMRDACWR_Pulse_Width = 1 << 12,
 	AO_Fast_CPU = 1 << 13,	/* M Series: reserved */
-	AO_Number_Of_DAC_Packages = 1 << 14,	// 1 for "single" mode, 0 for "dual"
-	AO_Multiple_DACS_Per_Package = 1 << 15	// m-series only
+	AO_Number_Of_DAC_Packages = 1 << 14,	/*  1 for "single" mode, 0 for "dual" */
+	AO_Multiple_DACS_Per_Package = 1 << 15	/*  m-series only */
 };
 #define	RTSI_Trig_A_Output_Register	79
 #define	RTSI_Trig_B_Output_Register	80
 enum RTSI_Trig_B_Output_Bits {
-	RTSI_Sub_Selection_1_Bit = 0x8000	// not for m-series
+	RTSI_Sub_Selection_1_Bit = 0x8000	/*  not for m-series */
 };
 static inline unsigned RTSI_Trig_Output_Bits(unsigned rtsi_channel,
 	unsigned source)
@@ -539,7 +539,7 @@
 	return 0xf << ((rtsi_channel % 4) * 4);
 };
 
-// inverse to RTSI_Trig_Output_Bits()
+/* inverse to RTSI_Trig_Output_Bits() */
 static inline unsigned RTSI_Trig_Output_Source(unsigned rtsi_channel,
 	unsigned bits)
 {
@@ -759,7 +759,7 @@
 };
 static inline unsigned int AI_CONFIG_CHANNEL(unsigned int channel)
 {
-	return (channel & 0x3f);
+	return channel & 0x3f;
 }
 
 #define ADC_FIFO_Data_Register		0x1c
@@ -920,42 +920,42 @@
 static const struct comedi_lrange range_ni_E_ao_ext;
 
 enum m_series_register_offsets {
-	M_Offset_CDIO_DMA_Select = 0x7,	// write
-	M_Offset_SCXI_Status = 0x7,	// read
-	M_Offset_AI_AO_Select = 0x9,	// write, same offset as e-series
-	M_Offset_SCXI_Serial_Data_In = 0x9,	// read
-	M_Offset_G0_G1_Select = 0xb,	// write, same offset as e-series
+	M_Offset_CDIO_DMA_Select = 0x7,	/*  write */
+	M_Offset_SCXI_Status = 0x7,	/*  read */
+	M_Offset_AI_AO_Select = 0x9,	/*  write, same offset as e-series */
+	M_Offset_SCXI_Serial_Data_In = 0x9,	/*  read */
+	M_Offset_G0_G1_Select = 0xb,	/*  write, same offset as e-series */
 	M_Offset_Misc_Command = 0xf,
 	M_Offset_SCXI_Serial_Data_Out = 0x11,
 	M_Offset_SCXI_Control = 0x13,
 	M_Offset_SCXI_Output_Enable = 0x15,
 	M_Offset_AI_FIFO_Data = 0x1c,
-	M_Offset_Static_Digital_Output = 0x24,	// write
-	M_Offset_Static_Digital_Input = 0x24,	// read
+	M_Offset_Static_Digital_Output = 0x24,	/*  write */
+	M_Offset_Static_Digital_Input = 0x24,	/*  read */
 	M_Offset_DIO_Direction = 0x28,
 	M_Offset_Cal_PWM = 0x40,
 	M_Offset_AI_Config_FIFO_Data = 0x5e,
-	M_Offset_Interrupt_C_Enable = 0x88,	// write
-	M_Offset_Interrupt_C_Status = 0x88,	// read
+	M_Offset_Interrupt_C_Enable = 0x88,	/*  write */
+	M_Offset_Interrupt_C_Status = 0x88,	/*  read */
 	M_Offset_Analog_Trigger_Control = 0x8c,
 	M_Offset_AO_Serial_Interrupt_Enable = 0xa0,
-	M_Offset_AO_Serial_Interrupt_Ack = 0xa1,	// write
-	M_Offset_AO_Serial_Interrupt_Status = 0xa1,	// read
+	M_Offset_AO_Serial_Interrupt_Ack = 0xa1,	/*  write */
+	M_Offset_AO_Serial_Interrupt_Status = 0xa1,	/*  read */
 	M_Offset_AO_Calibration = 0xa3,
 	M_Offset_AO_FIFO_Data = 0xa4,
 	M_Offset_PFI_Filter = 0xb0,
 	M_Offset_RTSI_Filter = 0xb4,
 	M_Offset_SCXI_Legacy_Compatibility = 0xbc,
-	M_Offset_Interrupt_A_Ack = 0x104,	// write
-	M_Offset_AI_Status_1 = 0x104,	// read
-	M_Offset_Interrupt_B_Ack = 0x106,	// write
-	M_Offset_AO_Status_1 = 0x106,	// read
-	M_Offset_AI_Command_2 = 0x108,	// write
-	M_Offset_G01_Status = 0x108,	// read
+	M_Offset_Interrupt_A_Ack = 0x104,	/*  write */
+	M_Offset_AI_Status_1 = 0x104,	/*  read */
+	M_Offset_Interrupt_B_Ack = 0x106,	/*  write */
+	M_Offset_AO_Status_1 = 0x106,	/*  read */
+	M_Offset_AI_Command_2 = 0x108,	/*  write */
+	M_Offset_G01_Status = 0x108,	/*  read */
 	M_Offset_AO_Command_2 = 0x10a,
-	M_Offset_AO_Status_2 = 0x10c,	// read
-	M_Offset_G0_Command = 0x10c,	// write
-	M_Offset_G1_Command = 0x10e,	// write
+	M_Offset_AO_Status_2 = 0x10c,	/*  read */
+	M_Offset_G0_Command = 0x10c,	/*  write */
+	M_Offset_G1_Command = 0x10e,	/*  write */
 	M_Offset_G0_HW_Save = 0x110,
 	M_Offset_G0_HW_Save_High = 0x110,
 	M_Offset_AI_Command_1 = 0x110,
@@ -973,17 +973,17 @@
 	M_Offset_G1_Save = 0x11c,
 	M_Offset_G1_Save_High = 0x11c,
 	M_Offset_G1_Save_Low = 0x11e,
-	M_Offset_AI_SI_Load_B = 0x120,	// write
-	M_Offset_AO_UI_Save = 0x120,	// read
-	M_Offset_AI_SC_Load_A = 0x124,	// write
-	M_Offset_AO_BC_Save = 0x124,	// read
-	M_Offset_AI_SC_Load_B = 0x128,	// write
-	M_Offset_AO_UC_Save = 0x128,	//read
+	M_Offset_AI_SI_Load_B = 0x120,	/*  write */
+	M_Offset_AO_UI_Save = 0x120,	/*  read */
+	M_Offset_AI_SC_Load_A = 0x124,	/*  write */
+	M_Offset_AO_BC_Save = 0x124,	/*  read */
+	M_Offset_AI_SC_Load_B = 0x128,	/*  write */
+	M_Offset_AO_UC_Save = 0x128,	/* read */
 	M_Offset_AI_SI2_Load_A = 0x12c,
 	M_Offset_AI_SI2_Load_B = 0x130,
 	M_Offset_G0_Mode = 0x134,
-	M_Offset_G1_Mode = 0x136,	// write
-	M_Offset_Joint_Status_1 = 0x136,	// read
+	M_Offset_G1_Mode = 0x136,	/*  write */
+	M_Offset_Joint_Status_1 = 0x136,	/*  read */
 	M_Offset_G0_Load_A = 0x138,
 	M_Offset_Joint_Status_2 = 0x13a,
 	M_Offset_G0_Load_B = 0x13c,
@@ -1007,10 +1007,10 @@
 	M_Offset_Analog_Trigger_Etc = 0x17a,
 	M_Offset_AI_START_STOP_Select = 0x17c,
 	M_Offset_AI_Trigger_Select = 0x17e,
-	M_Offset_AI_SI_Save = 0x180,	// read
-	M_Offset_AI_DIV_Load_A = 0x180,	// write
-	M_Offset_AI_SC_Save = 0x184,	// read
-	M_Offset_AO_Start_Select = 0x184,	// write
+	M_Offset_AI_SI_Save = 0x180,	/*  read */
+	M_Offset_AI_DIV_Load_A = 0x180,	/*  write */
+	M_Offset_AI_SC_Save = 0x184,	/*  read */
+	M_Offset_AO_Start_Select = 0x184,	/*  write */
 	M_Offset_AO_Trigger_Select = 0x186,
 	M_Offset_AO_Mode_3 = 0x18c,
 	M_Offset_G0_Autoincrement = 0x188,
@@ -1032,10 +1032,10 @@
 	M_Offset_G1_Counting_Mode = 0x1b2,
 	M_Offset_G0_Second_Gate = 0x1b4,
 	M_Offset_G1_Second_Gate = 0x1b6,
-	M_Offset_G0_DMA_Config = 0x1b8,	// write
-	M_Offset_G0_DMA_Status = 0x1b8,	// read
-	M_Offset_G1_DMA_Config = 0x1ba,	// write
-	M_Offset_G1_DMA_Status = 0x1ba,	// read
+	M_Offset_G0_DMA_Config = 0x1b8,	/*  write */
+	M_Offset_G0_DMA_Status = 0x1b8,	/*  read */
+	M_Offset_G1_DMA_Config = 0x1ba,	/*  write */
+	M_Offset_G1_DMA_Status = 0x1ba,	/*  read */
 	M_Offset_G0_MSeries_ABZ = 0x1c0,
 	M_Offset_G1_MSeries_ABZ = 0x1c2,
 	M_Offset_Clock_and_Fout2 = 0x1c4,
@@ -1051,10 +1051,10 @@
 	M_Offset_PFI_DO = 0x1de,
 	M_Offset_AI_Config_FIFO_Bypass = 0x218,
 	M_Offset_SCXI_DIO_Enable = 0x21c,
-	M_Offset_CDI_FIFO_Data = 0x220,	// read
-	M_Offset_CDO_FIFO_Data = 0x220,	// write
-	M_Offset_CDIO_Status = 0x224,	// read
-	M_Offset_CDIO_Command = 0x224,	// write
+	M_Offset_CDI_FIFO_Data = 0x220,	/*  read */
+	M_Offset_CDO_FIFO_Data = 0x220,	/*  write */
+	M_Offset_CDIO_Status = 0x224,	/*  read */
+	M_Offset_CDIO_Command = 0x224,	/*  write */
 	M_Offset_CDI_Mode = 0x228,
 	M_Offset_CDO_Mode = 0x22c,
 	M_Offset_CDI_Mask_Enable = 0x230,
@@ -1084,8 +1084,8 @@
 		0x262,
 		0x263,
 	};
-	if (((unsigned)i) >= sizeof(offset) / sizeof(offset[0])) {
-		rt_printk("%s: invalid channel=%i\n", __FUNCTION__, i);
+	if (((unsigned)i) >= ARRAY_SIZE(offset)) {
+		printk("%s: invalid channel=%i\n", __func__, i);
 		return offset[0];
 	}
 	return offset[i];
@@ -1098,8 +1098,8 @@
 		0x266,
 		0x267
 	};
-	if (((unsigned)channel) >= sizeof(offset) / sizeof(offset[0])) {
-		rt_printk("%s: invalid channel=%i\n", __FUNCTION__, channel);
+	if (((unsigned)channel) >= ARRAY_SIZE(offset)) {
+		printk("%s: invalid channel=%i\n", __func__, channel);
 		return offset[0];
 	}
 	return offset[channel];
@@ -1107,8 +1107,8 @@
 static inline unsigned M_Offset_PFI_Output_Select(unsigned n)
 {
 	if (n < 1 || n > NUM_PFI_OUTPUT_SELECT_REGS) {
-		rt_printk("%s: invalid pfi output select register=%i\n",
-			__FUNCTION__, n);
+		printk("%s: invalid pfi output select register=%i\n",
+			__func__, n);
 		return M_Offset_PFI_Output_Select_1;
 	}
 	return M_Offset_PFI_Output_Select_1 + (n - 1) * 2;
@@ -1122,7 +1122,7 @@
 	MSeries_AI_Config_Channel_Type_Ground_Ref_Bits = 0x3 << 6,
 	MSeries_AI_Config_Channel_Type_Aux_Bits = 0x5 << 6,
 	MSeries_AI_Config_Channel_Type_Ghost_Bits = 0x7 << 6,
-	MSeries_AI_Config_Polarity_Bit = 0x1000,	// 0 for 2's complement encoding
+	MSeries_AI_Config_Polarity_Bit = 0x1000,	/*  0 for 2's complement encoding */
 	MSeries_AI_Config_Dither_Bit = 0x2000,
 	MSeries_AI_Config_Last_Channel_Bit = 0x4000,
 };
@@ -1151,8 +1151,8 @@
 	MSeries_PLL_In_Source_Select_RTSI7_Bits = 0x1b,
 	MSeries_PLL_In_Source_Select_PXI_Clock10 = 0x1d,
 	MSeries_PLL_In_Source_Select_Mask = 0x1f,
-	MSeries_Timebase1_Select_Bit = 0x20,	// use PLL for timebase 1
-	MSeries_Timebase3_Select_Bit = 0x40,	// use PLL for timebase 3
+	MSeries_Timebase1_Select_Bit = 0x20,	/*  use PLL for timebase 1 */
+	MSeries_Timebase3_Select_Bit = 0x40,	/*  use PLL for timebase 3 */
 	/* use 10MHz instead of 20MHz for RTSI clock frequency.  Appears
 	   to have no effect, at least on pxi-6281, which always uses
 	   20MHz rtsi clock frequency */
@@ -1162,7 +1162,7 @@
 	RTSI_channel)
 {
 	if (RTSI_channel > 7) {
-		rt_printk("%s: bug, invalid RTSI_channel=%i\n", __FUNCTION__,
+		printk("%s: bug, invalid RTSI_channel=%i\n", __func__,
 			RTSI_channel);
 		return 0;
 	}
@@ -1183,7 +1183,7 @@
 {
 	static const unsigned max_divisor = 0x10;
 	if (divisor < 1 || divisor > max_divisor) {
-		rt_printk("%s: bug, invalid divisor=%i\n", __FUNCTION__,
+		printk("%s: bug, invalid divisor=%i\n", __func__,
 			divisor);
 		return 0;
 	}
@@ -1193,7 +1193,7 @@
 {
 	static const unsigned max_multiplier = 0x100;
 	if (multiplier < 1 || multiplier > max_multiplier) {
-		rt_printk("%s: bug, invalid multiplier=%i\n", __FUNCTION__,
+		printk("%s: bug, invalid multiplier=%i\n", __func__,
 			multiplier);
 		return 0;
 	}
@@ -1213,7 +1213,7 @@
 	MSeries_AO_Bypass_AO_Cal_Sel_Mask = 0x38000,
 	MSeries_AI_Bypass_Gain_Mask = 0x1c0000,
 	MSeries_AI_Bypass_Dither_Bit = 0x200000,
-	MSeries_AI_Bypass_Polarity_Bit = 0x400000,	// 0 for 2's complement encoding
+	MSeries_AI_Bypass_Polarity_Bit = 0x400000,	/*  0 for 2's complement encoding */
 	MSeries_AI_Bypass_Config_FIFO_Bit = 0x80000000
 };
 static inline unsigned MSeries_AI_Bypass_Cal_Sel_Pos_Bits(int
@@ -1239,7 +1239,7 @@
 	MSeries_AO_DAC_Reference_10V_Internal_Bits = 0x0,
 	MSeries_AO_DAC_Reference_5V_Internal_Bits = 0x8,
 	MSeries_AO_Update_Timed_Bit = 0x40,
-	MSeries_AO_Bipolar_Bit = 0x80	// turns on 2's complement encoding
+	MSeries_AO_Bipolar_Bit = 0x80	/*  turns on 2's complement encoding */
 };
 
 enum MSeries_AO_Reference_Attenuation_Bits {
@@ -1266,7 +1266,7 @@
 	return (source & 0x1f) << ((channel % 3) * 5);
 };
 
-// inverse to MSeries_PFI_Output_Select_Bits
+/* inverse to MSeries_PFI_Output_Select_Bits */
 static inline unsigned MSeries_PFI_Output_Select_Source(unsigned channel,
 	unsigned bits)
 {
@@ -1338,9 +1338,9 @@
 enum CDI_Mode_Bits {
 	CDI_Sample_Source_Select_Mask = 0x3f,
 	CDI_Halt_On_Error_Bit = 0x200,
-	CDI_Polarity_Bit = 0x400,	// sample clock on falling edge
-	CDI_FIFO_Mode_Bit = 0x800,	// set for half full mode, clear for not empty mode
-	CDI_Data_Lane_Mask = 0x3000,	// data lanes specify which dio channels map to byte or word accesses to the dio fifos
+	CDI_Polarity_Bit = 0x400,	/*  sample clock on falling edge */
+	CDI_FIFO_Mode_Bit = 0x800,	/*  set for half full mode, clear for not empty mode */
+	CDI_Data_Lane_Mask = 0x3000,	/*  data lanes specify which dio channels map to byte or word accesses to the dio fifos */
 	CDI_Data_Lane_0_15_Bits = 0x0,
 	CDI_Data_Lane_16_31_Bits = 0x1000,
 	CDI_Data_Lane_0_7_Bits = 0x0,
@@ -1353,9 +1353,9 @@
 	CDO_Sample_Source_Select_Mask = 0x3f,
 	CDO_Retransmit_Bit = 0x100,
 	CDO_Halt_On_Error_Bit = 0x200,
-	CDO_Polarity_Bit = 0x400,	// sample clock on falling edge
-	CDO_FIFO_Mode_Bit = 0x800,	// set for half full mode, clear for not full mode
-	CDO_Data_Lane_Mask = 0x3000,	// data lanes specify which dio channels map to byte or word accesses to the dio fifos
+	CDO_Polarity_Bit = 0x400,	/*  sample clock on falling edge */
+	CDO_FIFO_Mode_Bit = 0x800,	/*  set for half full mode, clear for not full mode */
+	CDO_Data_Lane_Mask = 0x3000,	/*  data lanes specify which dio channels map to byte or word accesses to the dio fifos */
 	CDO_Data_Lane_0_15_Bits = 0x0,
 	CDO_Data_Lane_16_31_Bits = 0x1000,
 	CDO_Data_Lane_0_7_Bits = 0x0,
@@ -1374,7 +1374,7 @@
 
 #define M_SERIES_EEPROM_SIZE 1024
 
-typedef struct ni_board_struct {
+struct ni_board_struct {
 	int device_id;
 	int isapnp_id;
 	char *name;
@@ -1401,11 +1401,11 @@
 	unsigned int has_analog_trig:1;
 
 	enum caldac_enum caldac[3];
-} ni_board;
+};
 
-#define n_ni_boards  (sizeof(ni_boards)/sizeof(ni_board))
+#define n_ni_boards  (sizeof(ni_boards)/sizeof(struct ni_board_struct))
 
-#define boardtype (*(ni_board *)dev->board_ptr)
+#define boardtype (*(struct ni_board_struct *)dev->board_ptr)
 
 #define MAX_N_AO_CHAN 8
 #define NUM_GPCT 2
@@ -1418,7 +1418,7 @@
 	\
 	unsigned short dio_output;				\
 	unsigned short dio_control;				\
-	int ao0p,ao1p;						\
+	int ao0p, ao1p;						\
 	int lastchan;						\
 	int last_do;						\
 	int rt_irq;						\
diff --git a/drivers/staging/comedi/drivers/ni_tio.c b/drivers/staging/comedi/drivers/ni_tio.c
index 05a9575..785553d 100644
--- a/drivers/staging/comedi/drivers/ni_tio.c
+++ b/drivers/staging/comedi/drivers/ni_tio.c
@@ -149,13 +149,13 @@
 static inline unsigned NI_660x_RTSI_Clock(unsigned n)
 {
 	BUG_ON(n > ni_660x_max_rtsi_channel);
-	return (0xb + n);
+	return 0xb + n;
 }
 static const unsigned ni_660x_max_source_pin = 7;
 static inline unsigned NI_660x_Source_Pin_Clock(unsigned n)
 {
 	BUG_ON(n > ni_660x_max_source_pin);
-	return (0x2 + n);
+	return 0x2 + n;
 }
 
 /* clock sources for ni e and m series boards, get bits with Gi_Source_Select_Bits() */
@@ -279,9 +279,9 @@
 module_exit(ni_tio_cleanup_module);
 
 struct ni_gpct_device *ni_gpct_device_construct(struct comedi_device * dev,
-	void (*write_register) (struct ni_gpct * counter, unsigned bits,
+	void (*write_register) (struct ni_gpct *counter, unsigned bits,
 		enum ni_gpct_register reg),
-	unsigned (*read_register) (struct ni_gpct * counter,
+	unsigned (*read_register) (struct ni_gpct *counter,
 		enum ni_gpct_register reg), enum ni_gpct_variant variant,
 	unsigned num_counters)
 {
@@ -669,7 +669,7 @@
 		}
 		if (i <= ni_m_series_max_pfi_channel)
 			break;
-		rt_printk("invalid clock source 0x%lx\n",
+		printk("invalid clock source 0x%lx\n",
 			(unsigned long)clock_source);
 		BUG();
 		ni_m_series_clock = 0;
@@ -965,7 +965,7 @@
 }
 
 static void ni_tio_get_clock_src(struct ni_gpct *counter,
-	unsigned int * clock_source, unsigned int * period_ns)
+	unsigned int *clock_source, unsigned int *period_ns)
 {
 	static const unsigned pico_per_nano = 1000;
 	uint64_t temp64;
@@ -1273,7 +1273,7 @@
 		counter_dev->regs[abz_reg] &= ~mask;
 		counter_dev->regs[abz_reg] |= (source << shift) & mask;
 		write_register(counter, counter_dev->regs[abz_reg], abz_reg);
-//              rt_printk("%s %x %d %d\n", __FUNCTION__, counter_dev->regs[abz_reg], index, source);
+/* printk("%s %x %d %d\n", __func__, counter_dev->regs[abz_reg], index, source); */
 		return 0;
 	}
 	return -EINVAL;
@@ -1442,7 +1442,7 @@
 };
 
 static int ni_tio_get_gate_src(struct ni_gpct *counter, unsigned gate_index,
-	unsigned int * gate_source)
+	unsigned int *gate_source)
 {
 	struct ni_gpct_device *counter_dev = counter->counter_dev;
 	const unsigned mode_bits = ni_tio_get_soft_copy(counter,
@@ -1534,7 +1534,7 @@
 }
 
 int ni_tio_insn_config(struct ni_gpct *counter,
-	struct comedi_insn * insn, unsigned int * data)
+	struct comedi_insn *insn, unsigned int *data)
 {
 	switch (data[0]) {
 	case INSN_CONFIG_SET_COUNTER_MODE:
diff --git a/drivers/staging/comedi/drivers/ni_tio.h b/drivers/staging/comedi/drivers/ni_tio.h
index 0729d60..3aacfe2 100644
--- a/drivers/staging/comedi/drivers/ni_tio.h
+++ b/drivers/staging/comedi/drivers/ni_tio.h
@@ -25,7 +25,7 @@
 
 #include "../comedidev.h"
 
-// forward declarations
+/* forward declarations */
 struct mite_struct;
 struct ni_gpct_device;
 
@@ -120,9 +120,9 @@
 
 struct ni_gpct_device {
 	struct comedi_device *dev;
-	void (*write_register) (struct ni_gpct * counter, unsigned bits,
+	void (*write_register) (struct ni_gpct *counter, unsigned bits,
 		enum ni_gpct_register reg);
-	unsigned (*read_register) (struct ni_gpct * counter,
+	unsigned (*read_register) (struct ni_gpct *counter,
 		enum ni_gpct_register reg);
 	enum ni_gpct_variant variant;
 	struct ni_gpct *counters;
@@ -132,24 +132,24 @@
 };
 
 extern struct ni_gpct_device *ni_gpct_device_construct(struct comedi_device * dev,
-	void (*write_register) (struct ni_gpct * counter, unsigned bits,
+	void (*write_register) (struct ni_gpct *counter, unsigned bits,
 		enum ni_gpct_register reg),
-	unsigned (*read_register) (struct ni_gpct * counter,
+	unsigned (*read_register) (struct ni_gpct *counter,
 		enum ni_gpct_register reg), enum ni_gpct_variant variant,
 	unsigned num_counters);
 extern void ni_gpct_device_destroy(struct ni_gpct_device *counter_dev);
 extern void ni_tio_init_counter(struct ni_gpct *counter);
 extern int ni_tio_rinsn(struct ni_gpct *counter,
-	struct comedi_insn * insn, unsigned int * data);
+	struct comedi_insn *insn, unsigned int *data);
 extern int ni_tio_insn_config(struct ni_gpct *counter,
-	struct comedi_insn * insn, unsigned int * data);
+	struct comedi_insn *insn, unsigned int *data);
 extern int ni_tio_winsn(struct ni_gpct *counter,
-	struct comedi_insn * insn, unsigned int * data);
+	struct comedi_insn *insn, unsigned int *data);
 extern int ni_tio_cmd(struct ni_gpct *counter, struct comedi_async *async);
 extern int ni_tio_cmdtest(struct ni_gpct *counter, struct comedi_cmd * cmd);
 extern int ni_tio_cancel(struct ni_gpct *counter);
 extern void ni_tio_handle_interrupt(struct ni_gpct *counter,
-	struct comedi_subdevice * s);
+	struct comedi_subdevice *s);
 extern void ni_tio_set_mite_channel(struct ni_gpct *counter,
 	struct mite_channel *mite_chan);
 extern void ni_tio_acknowledge_and_confirm(struct ni_gpct *counter,
diff --git a/drivers/staging/comedi/drivers/ni_tio_internal.h b/drivers/staging/comedi/drivers/ni_tio_internal.h
index ac5b171..920dd22 100644
--- a/drivers/staging/comedi/drivers/ni_tio_internal.h
+++ b/drivers/staging/comedi/drivers/ni_tio_internal.h
@@ -487,8 +487,8 @@
 #define Gi_Source_Select_Shift 2
 #define Gi_Gate_Select_Shift 7
 enum Gi_Input_Select_Bits {
-	Gi_Read_Acknowledges_Irq = 0x1,	// not present on 660x
-	Gi_Write_Acknowledges_Irq = 0x2,	// not present on 660x
+	Gi_Read_Acknowledges_Irq = 0x1,	/*  not present on 660x */
+	Gi_Write_Acknowledges_Irq = 0x2,	/*  not present on 660x */
 	Gi_Source_Select_Mask = 0x7c,
 	Gi_Gate_Select_Mask = 0x1f << Gi_Gate_Select_Shift,
 	Gi_Gate_Select_Load_Source_Bit = 0x1000,
@@ -656,7 +656,7 @@
 	return G0_TC_Error_Confirm_Bit;
 }
 
-// bits that are the same in G0/G2 and G1/G3 interrupt acknowledge registers
+/* bits that are the same in G0/G2 and G1/G3 interrupt acknowledge registers */
 enum Gxx_Interrupt_Acknowledge_Bits {
 	Gi_TC_Interrupt_Ack_Bit = 0x4000,
 	Gi_Gate_Interrupt_Ack_Bit = 0x8000
@@ -728,14 +728,14 @@
 	unsigned long flags;
 
 	BUG_ON(register_index >= NITIO_Num_Registers);
-	comedi_spin_lock_irqsave(&counter_dev->regs_lock, flags);
+	spin_lock_irqsave(&counter_dev->regs_lock, flags);
 	counter_dev->regs[register_index] &= ~bit_mask;
 	counter_dev->regs[register_index] |= (bit_values & bit_mask);
 	write_register(counter,
 		counter_dev->regs[register_index] | transient_bit_values,
 		register_index);
 	mmiowb();
-	comedi_spin_unlock_irqrestore(&counter_dev->regs_lock, flags);
+	spin_unlock_irqrestore(&counter_dev->regs_lock, flags);
 }
 
 /* ni_tio_set_bits( ) is for safely writing to registers whose bits may be
@@ -761,9 +761,9 @@
 	unsigned value;
 
 	BUG_ON(register_index >= NITIO_Num_Registers);
-	comedi_spin_lock_irqsave(&counter_dev->regs_lock, flags);
+	spin_lock_irqsave(&counter_dev->regs_lock, flags);
 	value = counter_dev->regs[register_index];
-	comedi_spin_unlock_irqrestore(&counter_dev->regs_lock, flags);
+	spin_unlock_irqrestore(&counter_dev->regs_lock, flags);
 	return value;
 }
 
diff --git a/drivers/staging/comedi/drivers/ni_tiocmd.c b/drivers/staging/comedi/drivers/ni_tiocmd.c
index 16a26e7..5be1e1a 100644
--- a/drivers/staging/comedi/drivers/ni_tiocmd.c
+++ b/drivers/staging/comedi/drivers/ni_tiocmd.c
@@ -96,7 +96,7 @@
 	}
 }
 
-static int ni_tio_input_inttrig(struct comedi_device * dev, struct comedi_subdevice * s,
+static int ni_tio_input_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum)
 {
 	unsigned long flags;
@@ -107,12 +107,12 @@
 	if (trignum != 0)
 		return -EINVAL;
 
-	comedi_spin_lock_irqsave(&counter->lock, flags);
+	spin_lock_irqsave(&counter->lock, flags);
 	if (counter->mite_chan)
 		mite_dma_arm(counter->mite_chan);
 	else
 		retval = -EIO;
-	comedi_spin_unlock_irqrestore(&counter->lock, flags);
+	spin_unlock_irqrestore(&counter->lock, flags);
 	if (retval < 0)
 		return retval;
 	retval = ni_tio_arm(counter, 1, NI_GPCT_ARM_IMMEDIATE);
@@ -171,7 +171,7 @@
 
 static int ni_tio_output_cmd(struct ni_gpct *counter, struct comedi_async *async)
 {
-	rt_printk("ni_tio: output commands not yet implemented.\n");
+	printk("ni_tio: output commands not yet implemented.\n");
 	return -ENOTSUPP;
 
 	counter->mite_chan->dir = COMEDI_OUTPUT;
@@ -213,9 +213,9 @@
 	int retval = 0;
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&counter->lock, flags);
+	spin_lock_irqsave(&counter->lock, flags);
 	if (counter->mite_chan == NULL) {
-		rt_printk
+		printk
 			("ni_tio: commands only supported with DMA.  Interrupt-driven commands not yet implemented.\n");
 		retval = -EIO;
 	} else {
@@ -228,7 +228,7 @@
 			}
 		}
 	}
-	comedi_spin_unlock_irqrestore(&counter->lock, flags);
+	spin_unlock_irqrestore(&counter->lock, flags);
 	return retval;
 }
 
@@ -342,11 +342,11 @@
 	unsigned long flags;
 
 	ni_tio_arm(counter, 0, 0);
-	comedi_spin_lock_irqsave(&counter->lock, flags);
+	spin_lock_irqsave(&counter->lock, flags);
 	if (counter->mite_chan) {
 		mite_dma_disarm(counter->mite_chan);
 	}
-	comedi_spin_unlock_irqrestore(&counter->lock, flags);
+	spin_unlock_irqrestore(&counter->lock, flags);
 	ni_tio_configure_dma(counter, 0, 0);
 
 	ni_tio_set_bits(counter,
@@ -365,11 +365,11 @@
 
 	switch (counter->counter_dev->variant) {
 	case ni_gpct_variant_m_series:
-	case ni_gpct_variant_660x:	// not sure if 660x really supports gate interrupts (the bits are not listed in register-level manual)
+	case ni_gpct_variant_660x:	/*  not sure if 660x really supports gate interrupts (the bits are not listed in register-level manual) */
 		return 1;
 		break;
 	case ni_gpct_variant_e_series:
-		comedi_spin_lock_irqsave(&counter->lock, flags);
+		spin_lock_irqsave(&counter->lock, flags);
 		{
 			if (counter->mite_chan == NULL ||
 				counter->mite_chan->dir != COMEDI_INPUT ||
@@ -377,7 +377,7 @@
 				retval = 1;
 			}
 		}
-		comedi_spin_unlock_irqrestore(&counter->lock, flags);
+		spin_unlock_irqrestore(&counter->lock, flags);
 		break;
 	}
 	return retval;
@@ -439,7 +439,7 @@
 				NITIO_Gxx_Joint_Status2_Reg(counter->
 					counter_index)) &
 			Gi_Permanent_Stale_Bit(counter->counter_index)) {
-			rt_printk("%s: Gi_Permanent_Stale_Data detected.\n",
+			printk("%s: Gi_Permanent_Stale_Data detected.\n",
 				__FUNCTION__);
 			if (perm_stale_data)
 				*perm_stale_data = 1;
@@ -458,7 +458,7 @@
 	ni_tio_acknowledge_and_confirm(counter, &gate_error, &tc_error,
 		&perm_stale_data, NULL);
 	if (gate_error) {
-		rt_printk("%s: Gi_Gate_Error detected.\n", __FUNCTION__);
+		printk("%s: Gi_Gate_Error detected.\n", __FUNCTION__);
 		s->async->events |= COMEDI_CB_OVERFLOW;
 	}
 	if (perm_stale_data) {
@@ -470,16 +470,16 @@
 		if (read_register(counter,
 				NITIO_Gi_DMA_Status_Reg(counter->
 					counter_index)) & Gi_DRQ_Error_Bit) {
-			rt_printk("%s: Gi_DRQ_Error detected.\n", __FUNCTION__);
+			printk("%s: Gi_DRQ_Error detected.\n", __FUNCTION__);
 			s->async->events |= COMEDI_CB_OVERFLOW;
 		}
 		break;
 	case ni_gpct_variant_e_series:
 		break;
 	}
-	comedi_spin_lock_irqsave(&counter->lock, flags);
+	spin_lock_irqsave(&counter->lock, flags);
 	if (counter->mite_chan == NULL) {
-		comedi_spin_unlock_irqrestore(&counter->lock, flags);
+		spin_unlock_irqrestore(&counter->lock, flags);
 		return;
 	}
 	gpct_mite_status = mite_get_status(counter->mite_chan);
@@ -489,7 +489,7 @@
 			MITE_CHOR(counter->mite_chan->channel));
 	}
 	mite_sync_input_dma(counter->mite_chan, s->async);
-	comedi_spin_unlock_irqrestore(&counter->lock, flags);
+	spin_unlock_irqrestore(&counter->lock, flags);
 }
 
 void ni_tio_set_mite_channel(struct ni_gpct *counter,
@@ -497,9 +497,9 @@
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&counter->lock, flags);
+	spin_lock_irqsave(&counter->lock, flags);
 	counter->mite_chan = mite_chan;
-	comedi_spin_unlock_irqrestore(&counter->lock, flags);
+	spin_unlock_irqrestore(&counter->lock, flags);
 }
 
 static int __init ni_tiocmd_init_module(void)
diff --git a/drivers/staging/comedi/drivers/pcl711.c b/drivers/staging/comedi/drivers/pcl711.c
index ce42506..7b72b7a 100644
--- a/drivers/staging/comedi/drivers/pcl711.c
+++ b/drivers/staging/comedi/drivers/pcl711.c
@@ -58,6 +58,7 @@
 
  */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -156,16 +157,16 @@
 #define n_boardtypes (sizeof(boardtypes)/sizeof(struct pcl711_board))
 #define this_board ((const struct pcl711_board *)dev->board_ptr)
 
-static int pcl711_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcl711_detach(struct comedi_device * dev);
+static int pcl711_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcl711_detach(struct comedi_device *dev);
 static struct comedi_driver driver_pcl711 = {
-      driver_name:"pcl711",
-      module:THIS_MODULE,
-      attach:pcl711_attach,
-      detach:pcl711_detach,
-      board_name:&boardtypes[0].name,
-      num_names:n_boardtypes,
-      offset:sizeof(struct pcl711_board),
+	.driver_name = "pcl711",
+	.module = THIS_MODULE,
+	.attach = pcl711_attach,
+	.detach = pcl711_detach,
+	.board_name = &boardtypes[0].name,
+	.num_names = n_boardtypes,
+	.offset = sizeof(struct pcl711_board),
 };
 
 COMEDI_INITCLEANUP(driver_pcl711);
@@ -185,7 +186,7 @@
 
 #define devpriv ((struct pcl711_private *)dev->private)
 
-static irqreturn_t pcl711_interrupt(int irq, void *d PT_REGS_ARG)
+static irqreturn_t pcl711_interrupt(int irq, void *d)
 {
 	int lo, hi;
 	int data;
@@ -217,7 +218,7 @@
 	return IRQ_HANDLED;
 }
 
-static void pcl711_set_changain(struct comedi_device * dev, int chan)
+static void pcl711_set_changain(struct comedi_device *dev, int chan)
 {
 	int chan_register;
 
@@ -244,8 +245,8 @@
 	}
 }
 
-static int pcl711_ai_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl711_ai_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, n;
 	int hi, lo;
@@ -269,9 +270,9 @@
 			hi = inb(dev->iobase + PCL711_AD_HI);
 			if (!(hi & PCL711_DRDY))
 				goto ok;
-			comedi_udelay(1);
+			udelay(1);
 		}
-		rt_printk("comedi%d: pcl711: A/D timeout\n", dev->minor);
+		printk("comedi%d: pcl711: A/D timeout\n", dev->minor);
 		return -ETIME;
 
 	      ok:
@@ -283,8 +284,8 @@
 	return n;
 }
 
-static int pcl711_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int pcl711_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int tmp;
 	int err = 0;
@@ -385,7 +386,7 @@
 	return 0;
 }
 
-static int pcl711_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcl711_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int timer1, timer2;
 	struct comedi_cmd *cmd = &s->async->cmd;
@@ -431,8 +432,8 @@
 /*
    analog output
 */
-static int pcl711_ao_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl711_ao_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan = CR_CHAN(insn->chanspec);
@@ -449,8 +450,8 @@
 	return n;
 }
 
-static int pcl711_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl711_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan = CR_CHAN(insn->chanspec);
@@ -464,8 +465,8 @@
 }
 
 /* Digital port read - Untested on 8112 */
-static int pcl711_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl711_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -477,8 +478,8 @@
 }
 
 /* Digital port write - Untested on 8112 */
-static int pcl711_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl711_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -498,12 +499,12 @@
 }
 
 /*  Free any resources that we have claimed  */
-static int pcl711_detach(struct comedi_device * dev)
+static int pcl711_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: pcl711: remove\n", dev->minor);
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	if (dev->iobase)
 		release_region(dev->iobase, PCL711_SIZE);
@@ -512,7 +513,7 @@
 }
 
 /*  Initialization */
-static int pcl711_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcl711_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int ret;
 	unsigned long iobase;
@@ -541,7 +542,7 @@
 		return -EINVAL;
 	}
 	if (irq) {
-		if (comedi_request_irq(irq, pcl711_interrupt, 0, "pcl711", dev)) {
+		if (request_irq(irq, pcl711_interrupt, 0, "pcl711", dev)) {
 			printk("unable to allocate irq %u\n", irq);
 			return -EINVAL;
 		} else {
@@ -550,9 +551,12 @@
 	}
 	dev->irq = irq;
 
-	if ((ret = alloc_subdevices(dev, 4)) < 0)
+	ret = alloc_subdevices(dev, 4);
+	if (ret < 0)
 		return ret;
-	if ((ret = alloc_private(dev, sizeof(struct pcl711_private))) < 0)
+
+	ret = alloc_private(dev, sizeof(struct pcl711_private));
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
diff --git a/drivers/staging/comedi/drivers/pcl724.c b/drivers/staging/comedi/drivers/pcl724.c
index cd1e784..699daff 100644
--- a/drivers/staging/comedi/drivers/pcl724.c
+++ b/drivers/staging/comedi/drivers/pcl724.c
@@ -54,18 +54,18 @@
 
 #define SIZE_8255	4
 
-// #define PCL724_IRQ   1  /* no IRQ support now */
+/* #define PCL724_IRQ   1  no IRQ support now */
 
-static int pcl724_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcl724_detach(struct comedi_device * dev);
+static int pcl724_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcl724_detach(struct comedi_device *dev);
 
 struct pcl724_board {
 
-	const char *name;	// board name
-	int dio;		// num of DIO
-	int numofports;		// num of 8255 subdevices
-	unsigned int IRQbits;	// allowed interrupts
-	unsigned int io_range;	// len of IO space
+	const char *name;	/*  board name */
+	int dio;		/*  num of DIO */
+	int numofports;		/*  num of 8255 subdevices */
+	unsigned int IRQbits;	/*  allowed interrupts */
+	unsigned int io_range;	/*  len of IO space */
 	char can_have96;
 	char is_pet48;
 };
@@ -84,13 +84,13 @@
 #define this_board ((const struct pcl724_board *)dev->board_ptr)
 
 static struct comedi_driver driver_pcl724 = {
-      driver_name:"pcl724",
-      module:THIS_MODULE,
-      attach:pcl724_attach,
-      detach:pcl724_detach,
-      board_name:&boardtypes[0].name,
-      num_names:n_boardtypes,
-      offset:sizeof(struct pcl724_board),
+	.driver_name = "pcl724",
+	.module = THIS_MODULE,
+	.attach = pcl724_attach,
+	.detach = pcl724_detach,
+	.board_name = &boardtypes[0].name,
+	.num_names = n_boardtypes,
+	.offset = sizeof(struct pcl724_board),
 };
 
 COMEDI_INITCLEANUP(driver_pcl724);
@@ -124,7 +124,7 @@
 	}
 }
 
-static int pcl724_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcl724_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	unsigned long iobase;
 	unsigned int iorange;
@@ -137,7 +137,7 @@
 	iorange = this_board->io_range;
 	if ((this_board->can_have96) && ((it->options[1] == 1)
 			|| (it->options[1] == 96)))
-		iorange = PCL722_96_SIZE;	// PCL-724 in 96 DIO configuration
+		iorange = PCL722_96_SIZE;	/*  PCL-724 in 96 DIO configuration */
 	printk("comedi%d: pcl724: board=%s, 0x%03lx ", dev->minor,
 		this_board->name, iobase);
 	if (!request_region(iobase, iorange, "pcl724")) {
@@ -155,19 +155,18 @@
 		irq = it->options[1];
 		if (irq) {	/* we want to use IRQ */
 			if (((1 << irq) & this_board->IRQbits) == 0) {
-				rt_printk
+				printk
 					(", IRQ %u is out of allowed range, DISABLING IT",
 					irq);
 				irq = 0;	/* Bad IRQ */
 			} else {
-				if (comedi_request_irq(irq, interrupt_pcl724, 0,
-						"pcl724", dev)) {
-					rt_printk
+				if (request_irq(irq, interrupt_pcl724, 0, "pcl724", dev)) {
+					printk
 						(", unable to allocate IRQ %u, DISABLING IT",
 						irq);
 					irq = 0;	/* Can't use IRQ */
 				} else {
-					rt_printk(", irq=%u", irq);
+					printk(", irq=%u", irq);
 				}
 			}
 		}
@@ -181,9 +180,10 @@
 	n_subdevices = this_board->numofports;
 	if ((this_board->can_have96) && ((it->options[1] == 1)
 			|| (it->options[1] == 96)))
-		n_subdevices = 4;	// PCL-724 in 96 DIO configuration
+		n_subdevices = 4;	/*  PCL-724 in 96 DIO configuration */
 
-	if ((ret = alloc_subdevices(dev, n_subdevices)) < 0)
+	ret = alloc_subdevices(dev, n_subdevices);
+	if (ret < 0)
 		return ret;
 
 	for (i = 0; i < dev->n_subdevices; i++) {
@@ -200,11 +200,11 @@
 	return 0;
 }
 
-static int pcl724_detach(struct comedi_device * dev)
+static int pcl724_detach(struct comedi_device *dev)
 {
 	int i;
 
-//      printk("comedi%d: pcl724: remove\n",dev->minor);
+/* printk("comedi%d: pcl724: remove\n",dev->minor); */
 
 	for (i = 0; i < dev->n_subdevices; i++) {
 		subdev_8255_cleanup(dev, dev->subdevices + i);
@@ -212,7 +212,7 @@
 
 #ifdef PCL724_IRQ
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 #endif
 
diff --git a/drivers/staging/comedi/drivers/pcl725.c b/drivers/staging/comedi/drivers/pcl725.c
index 0766ba0..1347624 100644
--- a/drivers/staging/comedi/drivers/pcl725.c
+++ b/drivers/staging/comedi/drivers/pcl725.c
@@ -20,19 +20,19 @@
 #define PCL725_DO 0
 #define PCL725_DI 1
 
-static int pcl725_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcl725_detach(struct comedi_device * dev);
+static int pcl725_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcl725_detach(struct comedi_device *dev);
 static struct comedi_driver driver_pcl725 = {
-      driver_name:"pcl725",
-      module:THIS_MODULE,
-      attach:pcl725_attach,
-      detach:pcl725_detach,
+	.driver_name = "pcl725",
+	.module = THIS_MODULE,
+	.attach = pcl725_attach,
+	.detach = pcl725_detach,
 };
 
 COMEDI_INITCLEANUP(driver_pcl725);
 
-static int pcl725_do_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl725_do_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -48,8 +48,8 @@
 	return 2;
 }
 
-static int pcl725_di_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl725_di_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -59,7 +59,7 @@
 	return 2;
 }
 
-static int pcl725_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcl725_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase;
@@ -100,7 +100,7 @@
 	return 0;
 }
 
-static int pcl725_detach(struct comedi_device * dev)
+static int pcl725_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: pcl725: remove\n", dev->minor);
 
diff --git a/drivers/staging/comedi/drivers/pcl726.c b/drivers/staging/comedi/drivers/pcl726.c
index 6dbd33d..149e75f 100644
--- a/drivers/staging/comedi/drivers/pcl726.c
+++ b/drivers/staging/comedi/drivers/pcl726.c
@@ -111,22 +111,22 @@
 	&range_4_20mA, &range_0_20mA
 };
 
-static int pcl726_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcl726_detach(struct comedi_device * dev);
+static int pcl726_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcl726_detach(struct comedi_device *dev);
 
 struct pcl726_board {
 
-	const char *name;	// driver name
-	int n_aochan;		// num of D/A chans
-	int num_of_ranges;	// num of ranges
-	unsigned int IRQbits;	// allowed interrupts
-	unsigned int io_range;	// len of IO space
-	char have_dio;		// 1=card have DI/DO ports
-	int di_hi;		// ports for DI/DO operations
+	const char *name;	/*  driver name */
+	int n_aochan;		/*  num of D/A chans */
+	int num_of_ranges;	/*  num of ranges */
+	unsigned int IRQbits;	/*  allowed interrupts */
+	unsigned int io_range;	/*  len of IO space */
+	char have_dio;		/*  1=card have DI/DO ports */
+	int di_hi;		/*  ports for DI/DO operations */
 	int di_lo;
 	int do_hi;
 	int do_lo;
-	const struct comedi_lrange *const *range_type_list;	// list of supported ranges
+	const struct comedi_lrange *const *range_type_list;	/*  list of supported ranges */
 };
 
 
@@ -152,13 +152,13 @@
 #define this_board ((const struct pcl726_board *)dev->board_ptr)
 
 static struct comedi_driver driver_pcl726 = {
-      driver_name:"pcl726",
-      module:THIS_MODULE,
-      attach:pcl726_attach,
-      detach:pcl726_detach,
-      board_name:&boardtypes[0].name,
-      num_names:n_boardtypes,
-      offset:sizeof(struct pcl726_board),
+	.driver_name = "pcl726",
+	.module = THIS_MODULE,
+	.attach = pcl726_attach,
+	.detach = pcl726_detach,
+	.board_name = &boardtypes[0].name,
+	.num_names = n_boardtypes,
+	.offset = sizeof(struct pcl726_board),
 };
 
 COMEDI_INITCLEANUP(driver_pcl726);
@@ -172,8 +172,8 @@
 
 #define devpriv ((struct pcl726_private *)dev->private)
 
-static int pcl726_ao_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl726_ao_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int hi, lo;
 	int n;
@@ -197,8 +197,8 @@
 	return n;
 }
 
-static int pcl726_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl726_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 	int n;
@@ -209,8 +209,8 @@
 	return n;
 }
 
-static int pcl726_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl726_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -221,8 +221,8 @@
 	return 2;
 }
 
-static int pcl726_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl726_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -241,7 +241,7 @@
 	return 2;
 }
 
-static int pcl726_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcl726_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase;
@@ -264,7 +264,8 @@
 
 	dev->board_name = this_board->name;
 
-	if ((ret = alloc_private(dev, sizeof(struct pcl726_private))) < 0)
+	ret = alloc_private(dev, sizeof(struct pcl726_private));
+	if (ret < 0)
 		return -ENOMEM;
 
 	for (i = 0; i < 12; i++) {
@@ -279,19 +280,19 @@
 		devpriv->first_chan = 2;
 		if (irq) {	/* we want to use IRQ */
 			if (((1 << irq) & boardtypes[board].IRQbits) == 0) {
-				rt_printk
+				printk
 					(", IRQ %d is out of allowed range, DISABLING IT",
 					irq);
 				irq = 0;	/* Bad IRQ */
 			} else {
-				if (comedi_request_irq(irq, interrupt_pcl818, 0,
+				if (request_irq(irq, interrupt_pcl818, 0,
 						"pcl726", dev)) {
-					rt_printk
+					printk
 						(", unable to allocate IRQ %d, DISABLING IT",
 						irq);
 					irq = 0;	/* Can't use IRQ */
 				} else {
-					rt_printk(", irq=%d", irq);
+					printk(", irq=%d", irq);
 				}
 			}
 		}
@@ -302,7 +303,8 @@
 
 	printk("\n");
 
-	if ((ret = alloc_subdevices(dev, 3)) < 0)
+	ret = alloc_subdevices(dev, 3);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -360,13 +362,13 @@
 	return 0;
 }
 
-static int pcl726_detach(struct comedi_device * dev)
+static int pcl726_detach(struct comedi_device *dev)
 {
-//      printk("comedi%d: pcl726: remove\n",dev->minor);
+/* printk("comedi%d: pcl726: remove\n",dev->minor); */
 
 #ifdef ACL6126_IRQ
 	if (dev->irq) {
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 #endif
 
diff --git a/drivers/staging/comedi/drivers/pcl730.c b/drivers/staging/comedi/drivers/pcl730.c
index f2c6d7c..408cbff 100644
--- a/drivers/staging/comedi/drivers/pcl730.c
+++ b/drivers/staging/comedi/drivers/pcl730.c
@@ -26,13 +26,13 @@
 #define PCL730_DIO_LO	2	/* TTL Digital I/O low byte (D0-D7) */
 #define PCL730_DIO_HI	3	/* TTL Digital I/O high byte (D8-D15) */
 
-static int pcl730_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcl730_detach(struct comedi_device * dev);
+static int pcl730_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcl730_detach(struct comedi_device *dev);
 
 struct pcl730_board {
 
-	const char *name;	// board name
-	unsigned int io_range;	// len of I/O space
+	const char *name;	/*  board name */
+	unsigned int io_range;	/*  len of I/O space */
 };
 
 
@@ -46,19 +46,19 @@
 #define this_board ((const struct pcl730_board *)dev->board_ptr)
 
 static struct comedi_driver driver_pcl730 = {
-      driver_name:"pcl730",
-      module:THIS_MODULE,
-      attach:pcl730_attach,
-      detach:pcl730_detach,
-      board_name:&boardtypes[0].name,
-      num_names:n_boardtypes,
-      offset:sizeof(struct pcl730_board),
+	.driver_name = "pcl730",
+	.module = THIS_MODULE,
+	.attach = pcl730_attach,
+	.detach = pcl730_detach,
+	.board_name = &boardtypes[0].name,
+	.num_names = n_boardtypes,
+	.offset = sizeof(struct pcl730_board),
 };
 
 COMEDI_INITCLEANUP(driver_pcl730);
 
-static int pcl730_do_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl730_do_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -79,8 +79,8 @@
 	return 2;
 }
 
-static int pcl730_di_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl730_di_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -91,7 +91,7 @@
 	return 2;
 }
 
-static int pcl730_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcl730_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase;
@@ -157,7 +157,7 @@
 	return 0;
 }
 
-static int pcl730_detach(struct comedi_device * dev)
+static int pcl730_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: pcl730: remove\n", dev->minor);
 
diff --git a/drivers/staging/comedi/drivers/pcl812.c b/drivers/staging/comedi/drivers/pcl812.c
index 11dfd23..dd91fe9 100644
--- a/drivers/staging/comedi/drivers/pcl812.c
+++ b/drivers/staging/comedi/drivers/pcl812.c
@@ -107,6 +107,7 @@
         3= 20V unipolar inputs
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/delay.h>
@@ -117,7 +118,7 @@
 
 #undef PCL812_EXTDEBUG		/* if this is defined then a lot of messages is printed */
 
-// hardware types of the cards
+/* hardware types of the cards */
 #define boardPCL812PG 		 0	/* and ACL-8112PG */
 #define boardPCL813B 		 1
 #define boardPCL812		 2
@@ -292,27 +293,27 @@
 	}
 };
 
-static int pcl812_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcl812_detach(struct comedi_device * dev);
+static int pcl812_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcl812_detach(struct comedi_device *dev);
 
 struct pcl812_board {
 
-	const char *name;	// board name
-	int board_type;		// type of this board
-	int n_aichan;		// num of AI chans in S.E.
-	int n_aichan_diff;	// DIFF num of chans
-	int n_aochan;		// num of DA chans
-	int n_dichan;		// DI and DO chans
+	const char *name;	/*  board name */
+	int board_type;		/*  type of this board */
+	int n_aichan;		/*  num of AI chans in S.E. */
+	int n_aichan_diff;	/*  DIFF num of chans */
+	int n_aochan;		/*  num of DA chans */
+	int n_dichan;		/*  DI and DO chans */
 	int n_dochan;
-	int ai_maxdata;		// AI resolution
-	unsigned int ai_ns_min;	// max sample speed of card v ns
-	unsigned int i8254_osc_base;	// clock base
-	const struct comedi_lrange *rangelist_ai;	// rangelist for A/D
-	const struct comedi_lrange *rangelist_ao;	// rangelist for D/A
-	unsigned int IRQbits;	// allowed IRQ
-	unsigned char DMAbits;	// allowed DMA chans
-	unsigned char io_range;	// iorange for this board
-	unsigned char haveMPC508;	// 1=board use MPC508A multiplexor
+	int ai_maxdata;		/*  AI resolution */
+	unsigned int ai_ns_min;	/*  max sample speed of card v ns */
+	unsigned int i8254_osc_base;	/*  clock base */
+	const struct comedi_lrange *rangelist_ai;	/*  rangelist for A/D */
+	const struct comedi_lrange *rangelist_ao;	/*  rangelist for D/A */
+	unsigned int IRQbits;	/*  allowed IRQ */
+	unsigned char DMAbits;	/*  allowed DMA chans */
+	unsigned char io_range;	/*  iorange for this board */
+	unsigned char haveMPC508;	/*  1=board use MPC508A multiplexor */
 };
 
 
@@ -377,50 +378,50 @@
 #define this_board ((const struct pcl812_board *)dev->board_ptr)
 
 static struct comedi_driver driver_pcl812 = {
-      driver_name:"pcl812",
-      module:THIS_MODULE,
-      attach:pcl812_attach,
-      detach:pcl812_detach,
-      board_name:&boardtypes[0].name,
-      num_names:n_boardtypes,
-      offset:sizeof(struct pcl812_board),
+	.driver_name = "pcl812",
+	.module = THIS_MODULE,
+	.attach = pcl812_attach,
+	.detach = pcl812_detach,
+	.board_name = &boardtypes[0].name,
+	.num_names = n_boardtypes,
+	.offset = sizeof(struct pcl812_board),
 };
 
 COMEDI_INITCLEANUP(driver_pcl812);
 
 struct pcl812_private {
 
-	unsigned char valid;	// =1 device is OK
-	unsigned char dma;	// >0 use dma ( usedDMA channel)
-	unsigned char use_diff;	// =1 diff inputs
-	unsigned char use_MPC;	// 1=board uses MPC508A multiplexor
-	unsigned char use_ext_trg;	// 1=board uses external trigger
-	unsigned char range_correction;	// =1 we must add 1 to range number
-	unsigned char old_chan_reg;	// lastly used chan/gain pair
+	unsigned char valid;	/*  =1 device is OK */
+	unsigned char dma;	/*  >0 use dma ( usedDMA channel) */
+	unsigned char use_diff;	/*  =1 diff inputs */
+	unsigned char use_MPC;	/*  1=board uses MPC508A multiplexor */
+	unsigned char use_ext_trg;	/*  1=board uses external trigger */
+	unsigned char range_correction;	/*  =1 we must add 1 to range number */
+	unsigned char old_chan_reg;	/*  lastly used chan/gain pair */
 	unsigned char old_gain_reg;
-	unsigned char mode_reg_int;	// there is stored INT number for some card
-	unsigned char ai_neverending;	// =1 we do unlimited AI
-	unsigned char ai_eos;	// 1=EOS wake up
-	unsigned char ai_dma;	// =1 we use DMA
-	unsigned int ai_poll_ptr;	// how many sampes transfer poll
-	unsigned int ai_scans;	// len of scanlist
-	unsigned int ai_act_scan;	// how many scans we finished
-	unsigned int ai_chanlist[MAX_CHANLIST_LEN];	// our copy of channel/range list
-	unsigned int ai_n_chan;	// how many channels is measured
-	unsigned int ai_flags;	// flaglist
-	unsigned int ai_data_len;	// len of data buffer
-	short *ai_data;	// data buffer
-	unsigned int ai_is16b;	// =1 we have 16 bit card
-	unsigned long dmabuf[2];	// PTR to DMA buf
-	unsigned int dmapages[2];	// how many pages we have allocated
-	unsigned int hwdmaptr[2];	// HW PTR to DMA buf
-	unsigned int hwdmasize[2];	// DMA buf size in bytes
-	unsigned int dmabytestomove[2];	// how many bytes DMA transfer
-	int next_dma_buf;	// which buffer is next to use
-	unsigned int dma_runs_to_end;	// how many times we must switch DMA buffers
-	unsigned int last_dma_run;	// how many bytes to transfer on last DMA buffer
-	unsigned int max_812_ai_mode0_rangewait;	// setling time for gain
-	unsigned int ao_readback[2];	// data for AO readback
+	unsigned char mode_reg_int;	/*  there is stored INT number for some card */
+	unsigned char ai_neverending;	/*  =1 we do unlimited AI */
+	unsigned char ai_eos;	/*  1=EOS wake up */
+	unsigned char ai_dma;	/*  =1 we use DMA */
+	unsigned int ai_poll_ptr;	/*  how many sampes transfer poll */
+	unsigned int ai_scans;	/*  len of scanlist */
+	unsigned int ai_act_scan;	/*  how many scans we finished */
+	unsigned int ai_chanlist[MAX_CHANLIST_LEN];	/*  our copy of channel/range list */
+	unsigned int ai_n_chan;	/*  how many channels is measured */
+	unsigned int ai_flags;	/*  flaglist */
+	unsigned int ai_data_len;	/*  len of data buffer */
+	short *ai_data;	/*  data buffer */
+	unsigned int ai_is16b;	/*  =1 we have 16 bit card */
+	unsigned long dmabuf[2];	/*  PTR to DMA buf */
+	unsigned int dmapages[2];	/*  how many pages we have allocated */
+	unsigned int hwdmaptr[2];	/*  HW PTR to DMA buf */
+	unsigned int hwdmasize[2];	/*  DMA buf size in bytes */
+	unsigned int dmabytestomove[2];	/*  how many bytes DMA transfer */
+	int next_dma_buf;	/*  which buffer is next to use */
+	unsigned int dma_runs_to_end;	/*  how many times we must switch DMA buffers */
+	unsigned int last_dma_run;	/*  how many bytes to transfer on last DMA buffer */
+	unsigned int max_812_ai_mode0_rangewait;	/*  setling time for gain */
+	unsigned int ao_readback[2];	/*  data for AO readback */
 };
 
 
@@ -429,33 +430,33 @@
 /*
 ==============================================================================
 */
-static void start_pacer(struct comedi_device * dev, int mode, unsigned int divisor1,
+static void start_pacer(struct comedi_device *dev, int mode, unsigned int divisor1,
 	unsigned int divisor2);
-static void setup_range_channel(struct comedi_device * dev, struct comedi_subdevice * s,
+static void setup_range_channel(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int rangechan, char wait);
-static int pcl812_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
+static int pcl812_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
 /*
 ==============================================================================
 */
-static int pcl812_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl812_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int timeout, hi;
 
 	outb(devpriv->mode_reg_int | 1, dev->iobase + PCL812_MODE);	/* select software trigger */
-	setup_range_channel(dev, s, insn->chanspec, 1);	// select channel and renge
+	setup_range_channel(dev, s, insn->chanspec, 1);	/*  select channel and renge */
 	for (n = 0; n < insn->n; n++) {
 		outb(255, dev->iobase + PCL812_SOFTTRIG);	/* start conversion */
-		comedi_udelay(5);
+		udelay(5);
 		timeout = 50;	/* wait max 50us, it must finish under 33us */
 		while (timeout--) {
 			hi = inb(dev->iobase + PCL812_AD_HI);
 			if (!(hi & PCL812_DRDY))
 				goto conv_finish;
-			comedi_udelay(1);
+			udelay(1);
 		}
-		rt_printk
+		printk
 			("comedi%d: pcl812: (%s at 0x%lx) A/D insn read timeout\n",
 			dev->minor, dev->board_name, dev->iobase);
 		outb(devpriv->mode_reg_int | 0, dev->iobase + PCL812_MODE);
@@ -471,24 +472,24 @@
 /*
 ==============================================================================
 */
-static int acl8216_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int acl8216_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int timeout;
 
 	outb(1, dev->iobase + PCL812_MODE);	/* select software trigger */
-	setup_range_channel(dev, s, insn->chanspec, 1);	// select channel and renge
+	setup_range_channel(dev, s, insn->chanspec, 1);	/*  select channel and renge */
 	for (n = 0; n < insn->n; n++) {
 		outb(255, dev->iobase + PCL812_SOFTTRIG);	/* start conversion */
-		comedi_udelay(5);
+		udelay(5);
 		timeout = 50;	/* wait max 50us, it must finish under 33us */
 		while (timeout--) {
 			if (!(inb(dev->iobase + ACL8216_STATUS) & ACL8216_DRDY))
 				goto conv_finish;
-			comedi_udelay(1);
+			udelay(1);
 		}
-		rt_printk
+		printk
 			("comedi%d: pcl812: (%s at 0x%lx) A/D insn read timeout\n",
 			dev->minor, dev->board_name, dev->iobase);
 		outb(0, dev->iobase + PCL812_MODE);
@@ -507,8 +508,8 @@
 /*
 ==============================================================================
 */
-static int pcl812_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl812_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 	int i;
@@ -527,8 +528,8 @@
 /*
 ==============================================================================
 */
-static int pcl812_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl812_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 	int i;
@@ -543,8 +544,8 @@
 /*
 ==============================================================================
 */
-static int pcl812_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl812_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -558,8 +559,8 @@
 /*
 ==============================================================================
 */
-static int pcl812_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl812_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -579,15 +580,15 @@
 /*
 ==============================================================================
 */
-static void pcl812_cmdtest_out(int e, struct comedi_cmd * cmd)
+static void pcl812_cmdtest_out(int e, struct comedi_cmd *cmd)
 {
-	rt_printk("pcl812 e=%d startsrc=%x scansrc=%x convsrc=%x\n", e,
+	printk("pcl812 e=%d startsrc=%x scansrc=%x convsrc=%x\n", e,
 		cmd->start_src, cmd->scan_begin_src, cmd->convert_src);
-	rt_printk("pcl812 e=%d startarg=%d scanarg=%d convarg=%d\n", e,
+	printk("pcl812 e=%d startarg=%d scanarg=%d convarg=%d\n", e,
 		cmd->start_arg, cmd->scan_begin_arg, cmd->convert_arg);
-	rt_printk("pcl812 e=%d stopsrc=%x scanend=%x\n", e, cmd->stop_src,
+	printk("pcl812 e=%d stopsrc=%x scanend=%x\n", e, cmd->stop_src,
 		cmd->scan_end_src);
-	rt_printk("pcl812 e=%d stoparg=%d scanendarg=%d chanlistlen=%d\n", e,
+	printk("pcl812 e=%d stoparg=%d scanendarg=%d chanlistlen=%d\n", e,
 		cmd->stop_arg, cmd->scan_end_arg, cmd->chanlist_len);
 }
 #endif
@@ -595,14 +596,14 @@
 /*
 ==============================================================================
 */
-static int pcl812_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int pcl812_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp, divisor1, divisor2;
 
 #ifdef PCL812_EXTDEBUG
-	rt_printk("pcl812 EDBG: BGN: pcl812_ai_cmdtest(...)\n");
+	printk("pcl812 EDBG: BGN: pcl812_ai_cmdtest(...)\n");
 	pcl812_cmdtest_out(-1, cmd);
 #endif
 	/* step 1: make sure trigger sources are trivially valid */
@@ -639,7 +640,7 @@
 	if (err) {
 #ifdef PCL812_EXTDEBUG
 		pcl812_cmdtest_out(1, cmd);
-		rt_printk
+		printk
 			("pcl812 EDBG: BGN: pcl812_ai_cmdtest(...) err=%d ret=1\n",
 			err);
 #endif
@@ -681,7 +682,7 @@
 	if (err) {
 #ifdef PCL812_EXTDEBUG
 		pcl812_cmdtest_out(2, cmd);
-		rt_printk
+		printk
 			("pcl812 EDBG: BGN: pcl812_ai_cmdtest(...) err=%d ret=2\n",
 			err);
 #endif
@@ -739,7 +740,7 @@
 	if (err) {
 #ifdef PCL812_EXTDEBUG
 		pcl812_cmdtest_out(3, cmd);
-		rt_printk
+		printk
 			("pcl812 EDBG: BGN: pcl812_ai_cmdtest(...) err=%d ret=3\n",
 			err);
 #endif
@@ -761,7 +762,7 @@
 
 	if (err) {
 #ifdef PCL812_EXTDEBUG
-		rt_printk
+		printk
 			("pcl812 EDBG: BGN: pcl812_ai_cmdtest(...) err=%d ret=4\n",
 			err);
 #endif
@@ -774,13 +775,13 @@
 /*
 ==============================================================================
 */
-static int pcl812_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcl812_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned int divisor1 = 0, divisor2 = 0, i, dma_flags, bytes;
 	struct comedi_cmd *cmd = &s->async->cmd;
 
 #ifdef PCL812_EXTDEBUG
-	rt_printk("pcl812 EDBG: BGN: pcl812_ai_cmd(...)\n");
+	printk("pcl812 EDBG: BGN: pcl812_ai_cmd(...)\n");
 #endif
 
 	if (cmd->start_src != TRIG_NOW)
@@ -809,18 +810,18 @@
 			cmd->flags & TRIG_ROUND_MASK);
 	}
 
-	start_pacer(dev, -1, 0, 0);	// stop pacer
+	start_pacer(dev, -1, 0, 0);	/*  stop pacer */
 
 	devpriv->ai_n_chan = cmd->chanlist_len;
 	memcpy(devpriv->ai_chanlist, cmd->chanlist,
 		sizeof(unsigned int) * cmd->scan_end_arg);
-	setup_range_channel(dev, s, devpriv->ai_chanlist[0], 1);	// select first channel and range
+	setup_range_channel(dev, s, devpriv->ai_chanlist[0], 1);	/*  select first channel and range */
 
-	if (devpriv->dma) {	// check if we can use DMA transfer
+	if (devpriv->dma) {	/*  check if we can use DMA transfer */
 		devpriv->ai_dma = 1;
 		for (i = 1; i < devpriv->ai_n_chan; i++)
 			if (devpriv->ai_chanlist[0] != devpriv->ai_chanlist[i]) {
-				devpriv->ai_dma = 0;	// we cann't use DMA :-(
+				devpriv->ai_dma = 0;	/*  we cann't use DMA :-( */
 				break;
 			}
 	} else
@@ -841,14 +842,14 @@
 	devpriv->ai_poll_ptr = 0;
 	s->async->cur_chan = 0;
 
-	if ((devpriv->ai_flags & TRIG_WAKE_EOS)) {	// don't we want wake up every scan?
+	if ((devpriv->ai_flags & TRIG_WAKE_EOS)) {	/*  don't we want wake up every scan? */
 		devpriv->ai_eos = 1;
 		if (devpriv->ai_n_chan == 1)
-			devpriv->ai_dma = 0;	// DMA is useless for this situation
+			devpriv->ai_dma = 0;	/*  DMA is useless for this situation */
 	}
 
 	if (devpriv->ai_dma) {
-		if (devpriv->ai_eos) {	// we use EOS, so adapt DMA buffer to one scan
+		if (devpriv->ai_eos) {	/*  we use EOS, so adapt DMA buffer to one scan */
 			devpriv->dmabytestomove[0] =
 				devpriv->ai_n_chan * sizeof(short);
 			devpriv->dmabytestomove[1] =
@@ -866,9 +867,9 @@
 			if (devpriv->ai_neverending) {
 				devpriv->dma_runs_to_end = 1;
 			} else {
-				bytes = devpriv->ai_n_chan * devpriv->ai_scans * sizeof(short);	// how many samples we must transfer?
-				devpriv->dma_runs_to_end = bytes / devpriv->dmabytestomove[0];	// how many DMA pages we must fill
-				devpriv->last_dma_run = bytes % devpriv->dmabytestomove[0];	//on last dma transfer must be moved
+				bytes = devpriv->ai_n_chan * devpriv->ai_scans * sizeof(short);	/*  how many samples we must transfer? */
+				devpriv->dma_runs_to_end = bytes / devpriv->dmabytestomove[0];	/*  how many DMA pages we must fill */
+				devpriv->last_dma_run = bytes % devpriv->dmabytestomove[0];	/* on last dma transfer must be moved */
 				if (devpriv->dma_runs_to_end == 0)
 					devpriv->dmabytestomove[0] =
 						devpriv->last_dma_run;
@@ -892,7 +893,7 @@
 		release_dma_lock(dma_flags);
 		enable_dma(devpriv->dma);
 #ifdef PCL812_EXTDEBUG
-		rt_printk
+		printk
 			("pcl812 EDBG:   DMA %d PTR 0x%0x/0x%0x LEN %u/%u EOS %d\n",
 			devpriv->dma, devpriv->hwdmaptr[0],
 			devpriv->hwdmaptr[1], devpriv->dmabytestomove[0],
@@ -907,13 +908,13 @@
 	}
 
 	if (devpriv->ai_dma) {
-		outb(devpriv->mode_reg_int | 2, dev->iobase + PCL812_MODE);	// let's go!
+		outb(devpriv->mode_reg_int | 2, dev->iobase + PCL812_MODE);	/*  let's go! */
 	} else {
-		outb(devpriv->mode_reg_int | 6, dev->iobase + PCL812_MODE);	// let's go!
+		outb(devpriv->mode_reg_int | 6, dev->iobase + PCL812_MODE);	/*  let's go! */
 	}
 
 #ifdef PCL812_EXTDEBUG
-	rt_printk("pcl812 EDBG: END: pcl812_ai_cmd(...)\n");
+	printk("pcl812 EDBG: END: pcl812_ai_cmd(...)\n");
 #endif
 
 	return 0;
@@ -939,7 +940,7 @@
 				err = 0;
 				break;
 			}
-			comedi_udelay(1);
+			udelay(1);
 		}
 	} else {
 		mask = 0x0fff;
@@ -948,12 +949,12 @@
 				err = 0;
 				break;
 			}
-			comedi_udelay(1);
+			udelay(1);
 		}
 	}
 
 	if (err) {
-		rt_printk
+		printk
 			("comedi%d: pcl812: (%s at 0x%lx) A/D cmd IRQ without DRDY!\n",
 			dev->minor, dev->board_name, dev->iobase);
 		pcl812_ai_cancel(dev, s);
@@ -984,14 +985,14 @@
 /*
 ==============================================================================
 */
-static void transfer_from_dma_buf(struct comedi_device * dev, struct comedi_subdevice * s,
-	short * ptr, unsigned int bufptr, unsigned int len)
+static void transfer_from_dma_buf(struct comedi_device *dev, struct comedi_subdevice *s,
+	short *ptr, unsigned int bufptr, unsigned int len)
 {
 	unsigned int i;
 
 	s->async->events = 0;
 	for (i = len; i; i--) {
-		comedi_buf_put(s->async, ptr[bufptr++]);	// get one sample
+		comedi_buf_put(s->async, ptr[bufptr++]);	/*  get one sample */
 
 		if (s->async->cur_chan == 0) {
 			devpriv->ai_act_scan++;
@@ -1019,7 +1020,7 @@
 	short *ptr;
 
 #ifdef PCL812_EXTDEBUG
-	rt_printk("pcl812 EDBG: BGN: interrupt_pcl812_ai_dma(...)\n");
+	printk("pcl812 EDBG: BGN: interrupt_pcl812_ai_dma(...)\n");
 #endif
 	ptr = (short *) devpriv->dmabuf[devpriv->next_dma_buf];
 	len = (devpriv->dmabytestomove[devpriv->next_dma_buf] >> 1) -
@@ -1053,7 +1054,7 @@
 	transfer_from_dma_buf(dev, s, ptr, bufptr, len);
 
 #ifdef PCL812_EXTDEBUG
-	rt_printk("pcl812 EDBG: END: interrupt_pcl812_ai_dma(...)\n");
+	printk("pcl812 EDBG: END: interrupt_pcl812_ai_dma(...)\n");
 #endif
 	return IRQ_HANDLED;
 }
@@ -1061,7 +1062,7 @@
 /*
 ==============================================================================
 */
-static irqreturn_t interrupt_pcl812(int irq, void *d PT_REGS_ARG)
+static irqreturn_t interrupt_pcl812(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 
@@ -1079,33 +1080,33 @@
 /*
 ==============================================================================
 */
-static int pcl812_ai_poll(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcl812_ai_poll(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 	unsigned int top1, top2, i;
 
 	if (!devpriv->ai_dma)
-		return 0;	// poll is valid only for DMA transfer
+		return 0;	/*  poll is valid only for DMA transfer */
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 
 	for (i = 0; i < 10; i++) {
-		top1 = get_dma_residue(devpriv->ai_dma);	// where is now DMA
+		top1 = get_dma_residue(devpriv->ai_dma);	/*  where is now DMA */
 		top2 = get_dma_residue(devpriv->ai_dma);
 		if (top1 == top2)
 			break;
 	}
 
 	if (top1 != top2) {
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 		return 0;
 	}
 
-	top1 = devpriv->dmabytestomove[1 - devpriv->next_dma_buf] - top1;	// where is now DMA in buffer
-	top1 >>= 1;		// sample position
+	top1 = devpriv->dmabytestomove[1 - devpriv->next_dma_buf] - top1;	/*  where is now DMA in buffer */
+	top1 >>= 1;		/*  sample position */
 	top2 = top1 - devpriv->ai_poll_ptr;
-	if (top2 < 1) {		// no new samples
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	if (top2 < 1) {		/*  no new samples */
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 		return 0;
 	}
 
@@ -1113,9 +1114,9 @@
 		(void *)devpriv->dmabuf[1 - devpriv->next_dma_buf],
 		devpriv->ai_poll_ptr, top2);
 
-	devpriv->ai_poll_ptr = top1;	// new buffer position
+	devpriv->ai_poll_ptr = top1;	/*  new buffer position */
 
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	return s->async->buf_write_count - s->async->buf_read_count;
 }
@@ -1123,27 +1124,27 @@
 /*
 ==============================================================================
 */
-static void setup_range_channel(struct comedi_device * dev, struct comedi_subdevice * s,
+static void setup_range_channel(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int rangechan, char wait)
 {
-	unsigned char chan_reg = CR_CHAN(rangechan);	// normal board
-	unsigned char gain_reg = CR_RANGE(rangechan) + devpriv->range_correction;	// gain index
+	unsigned char chan_reg = CR_CHAN(rangechan);	/*  normal board */
+	unsigned char gain_reg = CR_RANGE(rangechan) + devpriv->range_correction;	/*  gain index */
 
 	if ((chan_reg == devpriv->old_chan_reg)
 		&& (gain_reg == devpriv->old_gain_reg))
-		return;		// we can return, no change
+		return;		/*  we can return, no change */
 
 	devpriv->old_chan_reg = chan_reg;
 	devpriv->old_gain_reg = gain_reg;
 
 	if (devpriv->use_MPC) {
 		if (devpriv->use_diff) {
-			chan_reg = chan_reg | 0x30;	// DIFF inputs
+			chan_reg = chan_reg | 0x30;	/*  DIFF inputs */
 		} else {
 			if (chan_reg & 0x80) {
-				chan_reg = chan_reg | 0x20;	// SE inputs 8-15
+				chan_reg = chan_reg | 0x20;	/*  SE inputs 8-15 */
 			} else {
-				chan_reg = chan_reg | 0x10;	// SE inputs 0-7
+				chan_reg = chan_reg | 0x10;	/*  SE inputs 0-7 */
 			}
 		}
 	}
@@ -1152,23 +1153,23 @@
 	outb(gain_reg, dev->iobase + PCL812_GAIN);	/* select gain */
 
 	if (wait) {
-		comedi_udelay(devpriv->max_812_ai_mode0_rangewait);	// XXX this depends on selected range and can be very long for some high gain ranges!
+		udelay(devpriv->max_812_ai_mode0_rangewait);	/*  XXX this depends on selected range and can be very long for some high gain ranges! */
 	}
 }
 
 /*
 ==============================================================================
 */
-static void start_pacer(struct comedi_device * dev, int mode, unsigned int divisor1,
+static void start_pacer(struct comedi_device *dev, int mode, unsigned int divisor1,
 	unsigned int divisor2)
 {
 #ifdef PCL812_EXTDEBUG
-	rt_printk("pcl812 EDBG: BGN: start_pacer(%d,%u,%u)\n", mode, divisor1,
+	printk("pcl812 EDBG: BGN: start_pacer(%d,%u,%u)\n", mode, divisor1,
 		divisor2);
 #endif
 	outb(0xb4, dev->iobase + PCL812_CTRCTL);
 	outb(0x74, dev->iobase + PCL812_CTRCTL);
-	comedi_udelay(1);
+	udelay(1);
 
 	if (mode == 1) {
 		outb(divisor2 & 0xff, dev->iobase + PCL812_CTR2);
@@ -1177,14 +1178,14 @@
 		outb((divisor1 >> 8) & 0xff, dev->iobase + PCL812_CTR1);
 	}
 #ifdef PCL812_EXTDEBUG
-	rt_printk("pcl812 EDBG: END: start_pacer(...)\n");
+	printk("pcl812 EDBG: END: start_pacer(...)\n");
 #endif
 }
 
 /*
 ==============================================================================
 */
-static void free_resources(struct comedi_device * dev)
+static void free_resources(struct comedi_device *dev)
 {
 
 	if (dev->private) {
@@ -1196,7 +1197,7 @@
 			free_dma(devpriv->dma);
 	}
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	if (dev->iobase)
 		release_region(dev->iobase, this_board->io_range);
 }
@@ -1204,19 +1205,19 @@
 /*
 ==============================================================================
 */
-static int pcl812_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcl812_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 #ifdef PCL812_EXTDEBUG
-	rt_printk("pcl812 EDBG: BGN: pcl812_ai_cancel(...)\n");
+	printk("pcl812 EDBG: BGN: pcl812_ai_cancel(...)\n");
 #endif
 	if (devpriv->ai_dma)
 		disable_dma(devpriv->dma);
 	outb(0, dev->iobase + PCL812_CLRINT);	/* clear INT request */
 	outb(devpriv->mode_reg_int | 0, dev->iobase + PCL812_MODE);	/* Stop A/D */
-	start_pacer(dev, -1, 0, 0);	// stop 8254
+	start_pacer(dev, -1, 0, 0);	/*  stop 8254 */
 	outb(0, dev->iobase + PCL812_CLRINT);	/* clear INT request */
 #ifdef PCL812_EXTDEBUG
-	rt_printk("pcl812 EDBG: END: pcl812_ai_cancel(...)\n");
+	printk("pcl812 EDBG: END: pcl812_ai_cancel(...)\n");
 #endif
 	return 0;
 }
@@ -1224,14 +1225,14 @@
 /*
 ==============================================================================
 */
-static void pcl812_reset(struct comedi_device * dev)
+static void pcl812_reset(struct comedi_device *dev)
 {
 #ifdef PCL812_EXTDEBUG
-	rt_printk("pcl812 EDBG: BGN: pcl812_reset(...)\n");
+	printk("pcl812 EDBG: BGN: pcl812_reset(...)\n");
 #endif
 	outb(0, dev->iobase + PCL812_MUX);
 	outb(0 + devpriv->range_correction, dev->iobase + PCL812_GAIN);
-	devpriv->old_chan_reg = -1;	// invalidate chain/gain memory
+	devpriv->old_chan_reg = -1;	/*  invalidate chain/gain memory */
 	devpriv->old_gain_reg = -1;
 
 	switch (this_board->board_type) {
@@ -1244,7 +1245,7 @@
 	case boardA821:
 		outb(0, dev->iobase + PCL812_DA1_LO);
 		outb(0, dev->iobase + PCL812_DA1_HI);
-		start_pacer(dev, -1, 0, 0);	// stop 8254
+		start_pacer(dev, -1, 0, 0);	/*  stop 8254 */
 		outb(0, dev->iobase + PCL812_DO_HI);
 		outb(0, dev->iobase + PCL812_DO_LO);
 		outb(devpriv->mode_reg_int | 0, dev->iobase + PCL812_MODE);
@@ -1254,19 +1255,19 @@
 	case boardPCL813:
 	case boardISO813:
 	case boardACL8113:
-		comedi_udelay(5);
+		udelay(5);
 		break;
 	}
-	comedi_udelay(5);
+	udelay(5);
 #ifdef PCL812_EXTDEBUG
-	rt_printk("pcl812 EDBG: END: pcl812_reset(...)\n");
+	printk("pcl812 EDBG: END: pcl812_reset(...)\n");
 #endif
 }
 
 /*
 ==============================================================================
 */
-static int pcl812_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcl812_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int ret, subdev;
 	unsigned long iobase;
@@ -1286,7 +1287,8 @@
 	}
 	dev->iobase = iobase;
 
-	if ((ret = alloc_private(dev, sizeof(struct pcl812_private))) < 0) {
+	ret = alloc_private(dev, sizeof(struct pcl812_private));
+	if (ret < 0) {
 		free_resources(dev);
 		return ret;	/* Can't alloc mem */
 	}
@@ -1301,8 +1303,7 @@
 				printk(", IRQ %u is out of allowed range, DISABLING IT", irq);
 				irq = 0;	/* Bad IRQ */
 			} else {
-				if (comedi_request_irq(irq, interrupt_pcl812, 0,
-						"pcl812", dev)) {
+				if (request_irq(irq, interrupt_pcl812, 0, "pcl812", dev)) {
 					printk(", unable to allocate IRQ %u, DISABLING IT", irq);
 					irq = 0;	/* Can't use IRQ */
 				} else {
@@ -1364,7 +1365,8 @@
 	if (this_board->n_dochan > 0)
 		n_subdevices++;
 
-	if ((ret = alloc_subdevices(dev, n_subdevices)) < 0) {
+	ret = alloc_subdevices(dev, n_subdevices);
+	if (ret < 0) {
 		free_resources(dev);
 		return ret;
 	}
@@ -1570,7 +1572,7 @@
 	case boardACL8112:
 		devpriv->max_812_ai_mode0_rangewait = 1;
 		if (it->options[3] > 0)
-			devpriv->use_ext_trg = 1;	// we use external trigger
+			devpriv->use_ext_trg = 1;	/*  we use external trigger */
 	case boardA821:
 		devpriv->max_812_ai_mode0_rangewait = 1;
 		devpriv->mode_reg_int = (irq << 4) & 0xf0;
@@ -1594,11 +1596,11 @@
 /*
 ==============================================================================
  */
-static int pcl812_detach(struct comedi_device * dev)
+static int pcl812_detach(struct comedi_device *dev)
 {
 
 #ifdef PCL812_EXTDEBUG
-	rt_printk("comedi%d: pcl812: remove\n", dev->minor);
+	printk("comedi%d: pcl812: remove\n", dev->minor);
 #endif
 	free_resources(dev);
 	return 0;
diff --git a/drivers/staging/comedi/drivers/pcl816.c b/drivers/staging/comedi/drivers/pcl816.c
index 515ba74..19465c1 100644
--- a/drivers/staging/comedi/drivers/pcl816.c
+++ b/drivers/staging/comedi/drivers/pcl816.c
@@ -43,38 +43,38 @@
 
 #define DEBUG(x) x
 
-// boards constants
-// IO space len
+/* boards constants */
+/* IO space len */
 #define PCLx1x_RANGE 16
 
-//#define outb(x,y)  printk("OUTB(%x, 200+%d)\n", x,y-0x200); outb(x,y)
+/* #define outb(x,y)  printk("OUTB(%x, 200+%d)\n", x,y-0x200); outb(x,y) */
 
-// INTEL 8254 counters
+/* INTEL 8254 counters */
 #define PCL816_CTR0 4
 #define PCL816_CTR1 5
 #define PCL816_CTR2 6
-// R: counter read-back register W: counter control
+/* R: counter read-back register W: counter control */
 #define PCL816_CTRCTL 7
 
-// R: A/D high byte W: A/D range control
+/* R: A/D high byte W: A/D range control */
 #define PCL816_RANGE 9
-// W: clear INT request
+/* W: clear INT request */
 #define PCL816_CLRINT 10
-// R: next mux scan channel W: mux scan channel & range control pointer
+/* R: next mux scan channel W: mux scan channel & range control pointer */
 #define PCL816_MUX 11
-// R/W: operation control register
+/* R/W: operation control register */
 #define PCL816_CONTROL 12
 
-// R: return status byte  W: set DMA/IRQ
+/* R: return status byte  W: set DMA/IRQ */
 #define PCL816_STATUS 13
 #define PCL816_STATUS_DRDY_MASK 0x80
 
-// R: low byte of A/D W: soft A/D trigger
+/* R: low byte of A/D W: soft A/D trigger */
 #define PCL816_AD_LO 8
-// R: high byte of A/D W: A/D range control
+/* R: high byte of A/D W: A/D range control */
 #define PCL816_AD_HI 9
 
-// type of interrupt handler
+/* type of interrupt handler */
 #define INT_TYPE_AI1_INT 1
 #define INT_TYPE_AI1_DMA 2
 #define INT_TYPE_AI3_INT 4
@@ -83,7 +83,7 @@
 #define INT_TYPE_AI1_DMA_RTC 9
 #define INT_TYPE_AI3_DMA_RTC 10
 
-// RTC stuff...
+/* RTC stuff... */
 #define RTC_IRQ 	8
 #define RTC_IO_EXTENT	0x10
 #endif
@@ -103,35 +103,35 @@
 };
 struct pcl816_board {
 
-	const char *name;	// board name
-	int n_ranges;		// len of range list
-	int n_aichan;		// num of A/D chans in diferencial mode
-	unsigned int ai_ns_min;	// minimal alllowed delay between samples (in ns)
-	int n_aochan;		// num of D/A chans
-	int n_dichan;		// num of DI chans
-	int n_dochan;		// num of DO chans
-	const struct comedi_lrange *ai_range_type;	// default A/D rangelist
-	const struct comedi_lrange *ao_range_type;	// dafault D/A rangelist
-	unsigned int io_range;	// len of IO space
-	unsigned int IRQbits;	// allowed interrupts
-	unsigned int DMAbits;	// allowed DMA chans
-	int ai_maxdata;		// maxdata for A/D
-	int ao_maxdata;		// maxdata for D/A
-	int ai_chanlist;	// allowed len of channel list A/D
-	int ao_chanlist;	// allowed len of channel list D/A
-	int i8254_osc_base;	// 1/frequency of on board oscilator in ns
+	const char *name;	/*  board name */
+	int n_ranges;		/*  len of range list */
+	int n_aichan;		/*  num of A/D chans in diferencial mode */
+	unsigned int ai_ns_min;	/*  minimal alllowed delay between samples (in ns) */
+	int n_aochan;		/*  num of D/A chans */
+	int n_dichan;		/*  num of DI chans */
+	int n_dochan;		/*  num of DO chans */
+	const struct comedi_lrange *ai_range_type;	/*  default A/D rangelist */
+	const struct comedi_lrange *ao_range_type;	/*  dafault D/A rangelist */
+	unsigned int io_range;	/*  len of IO space */
+	unsigned int IRQbits;	/*  allowed interrupts */
+	unsigned int DMAbits;	/*  allowed DMA chans */
+	int ai_maxdata;		/*  maxdata for A/D */
+	int ao_maxdata;		/*  maxdata for D/A */
+	int ai_chanlist;	/*  allowed len of channel list A/D */
+	int ao_chanlist;	/*  allowed len of channel list D/A */
+	int i8254_osc_base;	/*  1/frequency of on board oscilator in ns */
 };
 
 
 static const struct pcl816_board boardtypes[] = {
 	{"pcl816", 8, 16, 10000, 1, 16, 16, &range_pcl816,
 			&range_pcl816, PCLx1x_RANGE,
-			0x00fc,	// IRQ mask
-			0x0a,	// DMA mask
-			0xffff,	// 16-bit card
-			0xffff,	// D/A maxdata
+			0x00fc,	/*  IRQ mask */
+			0x0a,	/*  DMA mask */
+			0xffff,	/*  16-bit card */
+			0xffff,	/*  D/A maxdata */
 			1024,
-			1,	// ao chan list
+			1,	/*  ao chan list */
 		100},
 	{"pcl814b", 8, 16, 10000, 1, 16, 16, &range_pcl816,
 			&range_pcl816, PCLx1x_RANGE,
@@ -148,8 +148,8 @@
 #define devpriv ((struct pcl816_private *)dev->private)
 #define this_board ((const struct pcl816_board *)dev->board_ptr)
 
-static int pcl816_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcl816_detach(struct comedi_device * dev);
+static int pcl816_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcl816_detach(struct comedi_device *dev);
 
 #ifdef unused
 static int RTC_lock = 0;	/* RTC lock */
@@ -157,55 +157,55 @@
 #endif
 
 static struct comedi_driver driver_pcl816 = {
-      driver_name:"pcl816",
-      module:THIS_MODULE,
-      attach:pcl816_attach,
-      detach:pcl816_detach,
-      board_name:&boardtypes[0].name,
-      num_names:n_boardtypes,
-      offset:sizeof(struct pcl816_board),
+	.driver_name = "pcl816",
+	.module = THIS_MODULE,
+	.attach = pcl816_attach,
+	.detach = pcl816_detach,
+	.board_name = &boardtypes[0].name,
+	.num_names = n_boardtypes,
+	.offset = sizeof(struct pcl816_board),
 };
 
 COMEDI_INITCLEANUP(driver_pcl816);
 
 struct pcl816_private {
 
-	unsigned int dma;	// used DMA, 0=don't use DMA
-	int dma_rtc;		// 1=RTC used with DMA, 0=no RTC alloc
+	unsigned int dma;	/*  used DMA, 0=don't use DMA */
+	int dma_rtc;		/*  1=RTC used with DMA, 0=no RTC alloc */
 #ifdef unused
-	unsigned long rtc_iobase;	// RTC port region
+	unsigned long rtc_iobase;	/*  RTC port region */
 	unsigned int rtc_iosize;
 	unsigned int rtc_irq;
 #endif
-	unsigned long dmabuf[2];	// pointers to begin of DMA buffers
-	unsigned int dmapages[2];	// len of DMA buffers in PAGE_SIZEs
-	unsigned int hwdmaptr[2];	// hardware address of DMA buffers
-	unsigned int hwdmasize[2];	// len of DMA buffers in Bytes
-	unsigned int dmasamplsize;	// size in samples hwdmasize[0]/2
-	unsigned int last_top_dma;	// DMA pointer in last RTC int
-	int next_dma_buf;	// which DMA buffer will be used next round
-	long dma_runs_to_end;	// how many we must permorm DMA transfer to end of record
-	unsigned long last_dma_run;	// how many bytes we must transfer on last DMA page
+	unsigned long dmabuf[2];	/*  pointers to begin of DMA buffers */
+	unsigned int dmapages[2];	/*  len of DMA buffers in PAGE_SIZEs */
+	unsigned int hwdmaptr[2];	/*  hardware address of DMA buffers */
+	unsigned int hwdmasize[2];	/*  len of DMA buffers in Bytes */
+	unsigned int dmasamplsize;	/*  size in samples hwdmasize[0]/2 */
+	unsigned int last_top_dma;	/*  DMA pointer in last RTC int */
+	int next_dma_buf;	/*  which DMA buffer will be used next round */
+	long dma_runs_to_end;	/*  how many we must permorm DMA transfer to end of record */
+	unsigned long last_dma_run;	/*  how many bytes we must transfer on last DMA page */
 
-	unsigned int ai_scans;	// len of scanlist
-	unsigned char ai_neverending;	// if=1, then we do neverending record (you must use cancel())
-	int irq_free;		// 1=have allocated IRQ
-	int irq_blocked;	// 1=IRQ now uses any subdev
+	unsigned int ai_scans;	/*  len of scanlist */
+	unsigned char ai_neverending;	/*  if=1, then we do neverending record (you must use cancel()) */
+	int irq_free;		/*  1=have allocated IRQ */
+	int irq_blocked;	/*  1=IRQ now uses any subdev */
 #ifdef unused
-	int rtc_irq_blocked;	// 1=we now do AI with DMA&RTC
+	int rtc_irq_blocked;	/*  1=we now do AI with DMA&RTC */
 #endif
-	int irq_was_now_closed;	// when IRQ finish, there's stored int816_mode for last interrupt
-	int int816_mode;	// who now uses IRQ - 1=AI1 int, 2=AI1 dma, 3=AI3 int, 4AI3 dma
-	struct comedi_subdevice *last_int_sub;	// ptr to subdevice which now finish
-	int ai_act_scan;	// how many scans we finished
-	unsigned int ai_act_chanlist[16];	// MUX setting for actual AI operations
-	unsigned int ai_act_chanlist_len;	// how long is actual MUX list
-	unsigned int ai_act_chanlist_pos;	// actual position in MUX list
-	unsigned int ai_poll_ptr;	// how many sampes transfer poll
-	struct comedi_subdevice *sub_ai;	// ptr to AI subdevice
+	int irq_was_now_closed;	/*  when IRQ finish, there's stored int816_mode for last interrupt */
+	int int816_mode;	/*  who now uses IRQ - 1=AI1 int, 2=AI1 dma, 3=AI3 int, 4AI3 dma */
+	struct comedi_subdevice *last_int_sub;	/*  ptr to subdevice which now finish */
+	int ai_act_scan;	/*  how many scans we finished */
+	unsigned int ai_act_chanlist[16];	/*  MUX setting for actual AI operations */
+	unsigned int ai_act_chanlist_len;	/*  how long is actual MUX list */
+	unsigned int ai_act_chanlist_pos;	/*  actual position in MUX list */
+	unsigned int ai_poll_ptr;	/*  how many sampes transfer poll */
+	struct comedi_subdevice *sub_ai;	/*  ptr to AI subdevice */
 #ifdef unused
-	struct timer_list rtc_irq_timer;	// timer for RTC sanity check
-	unsigned long rtc_freq;	// RTC int freq
+	struct timer_list rtc_irq_timer;	/*  timer for RTC sanity check */
+	unsigned long rtc_freq;	/*  RTC int freq */
 #endif
 };
 
@@ -213,36 +213,36 @@
 /*
 ==============================================================================
 */
-static int check_and_setup_channel_list(struct comedi_device * dev,
-	struct comedi_subdevice * s, unsigned int *chanlist, int chanlen);
-static int pcl816_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static void start_pacer(struct comedi_device * dev, int mode, unsigned int divisor1,
+static int check_and_setup_channel_list(struct comedi_device *dev,
+	struct comedi_subdevice *s, unsigned int *chanlist, int chanlen);
+static int pcl816_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static void start_pacer(struct comedi_device *dev, int mode, unsigned int divisor1,
 	unsigned int divisor2);
 #ifdef unused
 static int set_rtc_irq_bit(unsigned char bit);
 #endif
 
-static int pcl816_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
-static int pcl816_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
+static int pcl816_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
+static int pcl816_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
 
 /*
 ==============================================================================
    ANALOG INPUT MODE0, 816 cards, slow version
 */
-static int pcl816_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl816_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int timeout;
 
 	DPRINTK("mode 0 analog input\n");
-	// software trigger, DMA and INT off
+	/*  software trigger, DMA and INT off */
 	outb(0, dev->iobase + PCL816_CONTROL);
-	// clear INT (conversion end) flag
+	/*  clear INT (conversion end) flag */
 	outb(0, dev->iobase + PCL816_CLRINT);
 
-	// Set the input channel
+	/*  Set the input channel */
 	outb(CR_CHAN(insn->chanspec) & 0xf, dev->iobase + PCL816_MUX);
 	outb(CR_RANGE(insn->chanspec), dev->iobase + PCL816_RANGE);	/* select gain */
 
@@ -254,7 +254,7 @@
 		while (timeout--) {
 			if (!(inb(dev->iobase + PCL816_STATUS) &
 					PCL816_STATUS_DRDY_MASK)) {
-				// return read value
+				/*  return read value */
 				data[n] =
 					((inb(dev->iobase +
 							PCL816_AD_HI) << 8) |
@@ -263,9 +263,9 @@
 				outb(0, dev->iobase + PCL816_CLRINT);	/* clear INT (conversion end) flag */
 				break;
 			}
-			comedi_udelay(1);
+			udelay(1);
 		}
-		// Return timeout error
+		/*  Return timeout error */
 		if (!timeout) {
 			comedi_error(dev, "A/D insn timeout\n");
 			data[0] = 0;
@@ -293,9 +293,9 @@
 		if (!(inb(dev->iobase + PCL816_STATUS) &
 				PCL816_STATUS_DRDY_MASK))
 			break;
-		comedi_udelay(1);
+		udelay(1);
 	}
-	if (!timeout) {		// timeout, bail error
+	if (!timeout) {		/*  timeout, bail error */
 		outb(0, dev->iobase + PCL816_CLRINT);	/* clear INT request */
 		comedi_error(dev, "A/D mode1/3 IRQ without DRDY!");
 		pcl816_ai_cancel(dev, s);
@@ -305,7 +305,7 @@
 
 	}
 
-	// get the sample
+	/*  get the sample */
 	low = inb(dev->iobase + PCL816_AD_LO);
 	hi = inb(dev->iobase + PCL816_AD_HI);
 
@@ -334,8 +334,8 @@
 ==============================================================================
    analog input dma mode 1 & 3, 816 cards
 */
-static void transfer_from_dma_buf(struct comedi_device * dev, struct comedi_subdevice * s,
-	short * ptr, unsigned int bufptr, unsigned int len)
+static void transfer_from_dma_buf(struct comedi_device *dev, struct comedi_subdevice *s,
+	short *ptr, unsigned int bufptr, unsigned int len)
 {
 	int i;
 
@@ -352,7 +352,7 @@
 		}
 
 		if (!devpriv->ai_neverending)
-			if (devpriv->ai_act_scan >= devpriv->ai_scans) {	// all data sampled
+			if (devpriv->ai_act_scan >= devpriv->ai_scans) {	/*  all data sampled */
 				pcl816_ai_cancel(dev, s);
 				s->async->events |= COMEDI_CB_EOA;
 				s->async->events |= COMEDI_CB_BLOCK;
@@ -374,12 +374,12 @@
 	disable_dma(devpriv->dma);
 	this_dma_buf = devpriv->next_dma_buf;
 
-	if ((devpriv->dma_runs_to_end > -1) || devpriv->ai_neverending) {	// switch dma bufs
+	if ((devpriv->dma_runs_to_end > -1) || devpriv->ai_neverending) {	/*  switch dma bufs */
 
 		devpriv->next_dma_buf = 1 - devpriv->next_dma_buf;
 		set_dma_mode(devpriv->dma, DMA_MODE_READ);
 		dma_flags = claim_dma_lock();
-//  clear_dma_ff (devpriv->dma);
+/* clear_dma_ff (devpriv->dma); */
 		set_dma_addr(devpriv->dma,
 			devpriv->hwdmaptr[devpriv->next_dma_buf]);
 		if (devpriv->dma_runs_to_end) {
@@ -409,7 +409,7 @@
 ==============================================================================
     INT procedure
 */
-static irqreturn_t interrupt_pcl816(int irq, void *d PT_REGS_ARG)
+static irqreturn_t interrupt_pcl816(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	DPRINTK("<I>");
@@ -433,7 +433,7 @@
 		(!devpriv->int816_mode)) {
 		if (devpriv->irq_was_now_closed) {
 			devpriv->irq_was_now_closed = 0;
-			// comedi_error(dev,"last IRQ..");
+			/*  comedi_error(dev,"last IRQ.."); */
 			return IRQ_HANDLED;
 		}
 		comedi_error(dev, "bad IRQ!");
@@ -447,28 +447,28 @@
 ==============================================================================
    COMMAND MODE
 */
-static void pcl816_cmdtest_out(int e, struct comedi_cmd * cmd)
+static void pcl816_cmdtest_out(int e, struct comedi_cmd *cmd)
 {
-	rt_printk("pcl816 e=%d startsrc=%x scansrc=%x convsrc=%x\n", e,
+	printk("pcl816 e=%d startsrc=%x scansrc=%x convsrc=%x\n", e,
 		cmd->start_src, cmd->scan_begin_src, cmd->convert_src);
-	rt_printk("pcl816 e=%d startarg=%d scanarg=%d convarg=%d\n", e,
+	printk("pcl816 e=%d startarg=%d scanarg=%d convarg=%d\n", e,
 		cmd->start_arg, cmd->scan_begin_arg, cmd->convert_arg);
-	rt_printk("pcl816 e=%d stopsrc=%x scanend=%x\n", e, cmd->stop_src,
+	printk("pcl816 e=%d stopsrc=%x scanend=%x\n", e, cmd->stop_src,
 		cmd->scan_end_src);
-	rt_printk("pcl816 e=%d stoparg=%d scanendarg=%d chanlistlen=%d\n", e,
+	printk("pcl816 e=%d stoparg=%d scanendarg=%d chanlistlen=%d\n", e,
 		cmd->stop_arg, cmd->scan_end_arg, cmd->chanlist_len);
 }
 
 /*
 ==============================================================================
 */
-static int pcl816_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int pcl816_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp, divisor1, divisor2;
 
-	DEBUG(rt_printk("pcl816 pcl812_ai_cmdtest\n");
+	DEBUG(printk("pcl816 pcl812_ai_cmdtest\n");
 		pcl816_cmdtest_out(-1, cmd););
 
 	/* step 1: make sure trigger sources are trivially valid */
@@ -482,7 +482,7 @@
 	if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
 		err++;
 
-	if (!cmd->convert_src & (TRIG_EXT | TRIG_TIMER))
+	if (!(cmd->convert_src & (TRIG_EXT | TRIG_TIMER)))
 		err++;
 
 	tmp = cmd->scan_end_src;
@@ -597,7 +597,7 @@
 	return 0;
 }
 
-static int pcl816_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcl816_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned int divisor1 = 0, divisor2 = 0, dma_flags, bytes, dmairq;
 	struct comedi_cmd *cmd = &s->async->cmd;
@@ -610,7 +610,7 @@
 		return -EINVAL;
 	if (cmd->scan_end_arg != cmd->chanlist_len)
 		return -EINVAL;
-//      if(cmd->chanlist_len>MAX_CHANLIST_LEN) return -EINVAL;
+/* if(cmd->chanlist_len>MAX_CHANLIST_LEN) return -EINVAL; */
 	if (devpriv->irq_blocked)
 		return -EBUSY;
 
@@ -621,7 +621,7 @@
 		i8253_cascade_ns_to_timer(this_board->i8254_osc_base, &divisor1,
 			&divisor2, &cmd->convert_arg,
 			cmd->flags & TRIG_ROUND_MASK);
-		if (divisor1 == 1) {	// PCL816 crash if any divisor is set to 1
+		if (divisor1 == 1) {	/*  PCL816 crash if any divisor is set to 1 */
 			divisor1 = 2;
 			divisor2 /= 2;
 		}
@@ -631,12 +631,12 @@
 		}
 	}
 
-	start_pacer(dev, -1, 0, 0);	// stop pacer
+	start_pacer(dev, -1, 0, 0);	/*  stop pacer */
 
 	if (!check_and_setup_channel_list(dev, s, cmd->chanlist,
 			cmd->chanlist_len))
 		return -EINVAL;
-	comedi_udelay(1);
+	udelay(1);
 
 	devpriv->ai_act_scan = 0;
 	s->async->cur_chan = 0;
@@ -652,19 +652,19 @@
 		devpriv->ai_neverending = 1;
 	}
 
-	if ((cmd->flags & TRIG_WAKE_EOS)) {	// don't we want wake up every scan?
+	if ((cmd->flags & TRIG_WAKE_EOS)) {	/*  don't we want wake up every scan? */
 		printk("pl816: You wankt WAKE_EOS but I dont want handle it");
-		//              devpriv->ai_eos=1;
-		//if (devpriv->ai_n_chan==1)
-		//      devpriv->dma=0; // DMA is useless for this situation
+		/*               devpriv->ai_eos=1; */
+		/* if (devpriv->ai_n_chan==1) */
+		/*       devpriv->dma=0; // DMA is useless for this situation */
 	}
 
 	if (devpriv->dma) {
 		bytes = devpriv->hwdmasize[0];
 		if (!devpriv->ai_neverending) {
-			bytes = s->async->cmd.chanlist_len * s->async->cmd.chanlist_len * sizeof(short);	// how many
-			devpriv->dma_runs_to_end = bytes / devpriv->hwdmasize[0];	// how many DMA pages we must fill
-			devpriv->last_dma_run = bytes % devpriv->hwdmasize[0];	//on last dma transfer must be moved
+			bytes = s->async->cmd.chanlist_len * s->async->cmd.chanlist_len * sizeof(short);	/*  how many */
+			devpriv->dma_runs_to_end = bytes / devpriv->hwdmasize[0];	/*  how many DMA pages we must fill */
+			devpriv->last_dma_run = bytes % devpriv->hwdmasize[0];	/* on last dma transfer must be moved */
 			devpriv->dma_runs_to_end--;
 			if (devpriv->dma_runs_to_end >= 0)
 				bytes = devpriv->hwdmasize[0];
@@ -687,14 +687,14 @@
 	switch (cmd->convert_src) {
 	case TRIG_TIMER:
 		devpriv->int816_mode = INT_TYPE_AI1_DMA;
-		outb(0x32, dev->iobase + PCL816_CONTROL);	// Pacer+IRQ+DMA
-		outb(dmairq, dev->iobase + PCL816_STATUS);	// write irq and DMA to card
+		outb(0x32, dev->iobase + PCL816_CONTROL);	/*  Pacer+IRQ+DMA */
+		outb(dmairq, dev->iobase + PCL816_STATUS);	/*  write irq and DMA to card */
 		break;
 
 	default:
 		devpriv->int816_mode = INT_TYPE_AI3_DMA;
-		outb(0x34, dev->iobase + PCL816_CONTROL);	// Ext trig+IRQ+DMA
-		outb(dmairq, dev->iobase + PCL816_STATUS);	// write irq to card
+		outb(0x34, dev->iobase + PCL816_CONTROL);	/*  Ext trig+IRQ+DMA */
+		outb(dmairq, dev->iobase + PCL816_STATUS);	/*  write irq to card */
 		break;
 	}
 
@@ -702,32 +702,32 @@
 	return 0;
 }
 
-static int pcl816_ai_poll(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcl816_ai_poll(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 	unsigned int top1, top2, i;
 
 	if (!devpriv->dma)
-		return 0;	// poll is valid only for DMA transfer
+		return 0;	/*  poll is valid only for DMA transfer */
 
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 
 	for (i = 0; i < 20; i++) {
-		top1 = get_dma_residue(devpriv->dma);	// where is now DMA
+		top1 = get_dma_residue(devpriv->dma);	/*  where is now DMA */
 		top2 = get_dma_residue(devpriv->dma);
 		if (top1 == top2)
 			break;
 	}
 	if (top1 != top2) {
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 		return 0;
 	}
 
-	top1 = devpriv->hwdmasize[0] - top1;	// where is now DMA in buffer
-	top1 >>= 1;		// sample position
+	top1 = devpriv->hwdmasize[0] - top1;	/*  where is now DMA in buffer */
+	top1 >>= 1;		/*  sample position */
 	top2 = top1 - devpriv->ai_poll_ptr;
-	if (top2 < 1) {		// no new samples
-		comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	if (top2 < 1) {		/*  no new samples */
+		spin_unlock_irqrestore(&dev->spinlock, flags);
 		return 0;
 	}
 
@@ -735,8 +735,8 @@
 		(short *) devpriv->dmabuf[devpriv->next_dma_buf],
 		devpriv->ai_poll_ptr, top2);
 
-	devpriv->ai_poll_ptr = top1;	// new buffer position
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	devpriv->ai_poll_ptr = top1;	/*  new buffer position */
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 
 	return s->async->buf_write_count - s->async->buf_read_count;
 }
@@ -745,16 +745,16 @@
 ==============================================================================
  cancel any mode 1-4 AI
 */
-static int pcl816_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcl816_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
-//  DEBUG(rt_printk("pcl816_ai_cancel()\n");)
+/* DEBUG(printk("pcl816_ai_cancel()\n");) */
 
 	if (devpriv->irq_blocked > 0) {
 		switch (devpriv->int816_mode) {
 #ifdef unused
 		case INT_TYPE_AI1_DMA_RTC:
 		case INT_TYPE_AI3_DMA_RTC:
-			set_rtc_irq_bit(0);	// stop RTC
+			set_rtc_irq_bit(0);	/*  stop RTC */
 			del_timer(&devpriv->rtc_irq_timer);
 #endif
 		case INT_TYPE_AI1_DMA:
@@ -763,7 +763,7 @@
 		case INT_TYPE_AI1_INT:
 		case INT_TYPE_AI3_INT:
 			outb(inb(dev->iobase + PCL816_CONTROL) & 0x73, dev->iobase + PCL816_CONTROL);	/* Stop A/D */
-			comedi_udelay(1);
+			udelay(1);
 			outb(0, dev->iobase + PCL816_CONTROL);	/* Stop A/D */
 			outb(0xb0, dev->iobase + PCL816_CTRCTL);	/* Stop pacer */
 			outb(0x70, dev->iobase + PCL816_CTRCTL);
@@ -776,12 +776,12 @@
 			devpriv->irq_was_now_closed = devpriv->int816_mode;
 			devpriv->int816_mode = 0;
 			devpriv->last_int_sub = s;
-//        s->busy = 0;
+/* s->busy = 0; */
 			break;
 		}
 	}
 
-	DEBUG(rt_printk("comedi: pcl816_ai_cancel() successful\n");
+	DEBUG(printk("comedi: pcl816_ai_cancel() successful\n");
 		)
 		return 0;
 }
@@ -793,34 +793,34 @@
 static int pcl816_check(unsigned long iobase)
 {
 	outb(0x00, iobase + PCL816_MUX);
-	comedi_udelay(1);
+	udelay(1);
 	if (inb(iobase + PCL816_MUX) != 0x00)
-		return 1;	//there isn't card
+		return 1;	/* there isn't card */
 	outb(0x55, iobase + PCL816_MUX);
-	comedi_udelay(1);
+	udelay(1);
 	if (inb(iobase + PCL816_MUX) != 0x55)
-		return 1;	//there isn't card
+		return 1;	/* there isn't card */
 	outb(0x00, iobase + PCL816_MUX);
-	comedi_udelay(1);
+	udelay(1);
 	outb(0x18, iobase + PCL816_CONTROL);
-	comedi_udelay(1);
+	udelay(1);
 	if (inb(iobase + PCL816_CONTROL) != 0x18)
-		return 1;	//there isn't card
-	return 0;		// ok, card exist
+		return 1;	/* there isn't card */
+	return 0;		/*  ok, card exist */
 }
 
 /*
 ==============================================================================
  reset whole PCL-816 cards
 */
-static void pcl816_reset(struct comedi_device * dev)
+static void pcl816_reset(struct comedi_device *dev)
 {
-//  outb (0, dev->iobase + PCL818_DA_LO);       // DAC=0V
-//  outb (0, dev->iobase + PCL818_DA_HI);
-//  comedi_udelay (1);
-//  outb (0, dev->iobase + PCL818_DO_HI);       // DO=$0000
-//  outb (0, dev->iobase + PCL818_DO_LO);
-//  comedi_udelay (1);
+/* outb (0, dev->iobase + PCL818_DA_LO);         DAC=0V */
+/* outb (0, dev->iobase + PCL818_DA_HI); */
+/* udelay (1); */
+/* outb (0, dev->iobase + PCL818_DO_HI);        DO=$0000 */
+/* outb (0, dev->iobase + PCL818_DO_LO); */
+/* udelay (1); */
 	outb(0, dev->iobase + PCL816_CONTROL);
 	outb(0, dev->iobase + PCL816_MUX);
 	outb(0, dev->iobase + PCL816_CLRINT);
@@ -835,16 +835,16 @@
  Start/stop pacer onboard pacer
 */
 static void
-start_pacer(struct comedi_device * dev, int mode, unsigned int divisor1,
+start_pacer(struct comedi_device *dev, int mode, unsigned int divisor1,
 	unsigned int divisor2)
 {
 	outb(0x32, dev->iobase + PCL816_CTRCTL);
 	outb(0xff, dev->iobase + PCL816_CTR0);
 	outb(0x00, dev->iobase + PCL816_CTR0);
-	comedi_udelay(1);
-	outb(0xb4, dev->iobase + PCL816_CTRCTL);	// set counter 2 as mode 3
-	outb(0x74, dev->iobase + PCL816_CTRCTL);	// set counter 1 as mode 3
-	comedi_udelay(1);
+	udelay(1);
+	outb(0xb4, dev->iobase + PCL816_CTRCTL);	/*  set counter 2 as mode 3 */
+	outb(0x74, dev->iobase + PCL816_CTRCTL);	/*  set counter 1 as mode 3 */
+	udelay(1);
 
 	if (mode == 1) {
 		DPRINTK("mode %d, divisor1 %d, divisor2 %d\n", mode, divisor1,
@@ -856,7 +856,7 @@
 	}
 
 	/* clear pending interrupts (just in case) */
-//      outb(0, dev->iobase + PCL816_CLRINT);
+/* outb(0, dev->iobase + PCL816_CLRINT); */
 }
 
 /*
@@ -865,49 +865,49 @@
  If it's ok, then program scan/gain logic
 */
 static int
-check_and_setup_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+check_and_setup_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int *chanlist, int chanlen)
 {
 	unsigned int chansegment[16];
 	unsigned int i, nowmustbechan, seglen, segpos;
 
-	// correct channel and range number check itself comedi/range.c
+	/*  correct channel and range number check itself comedi/range.c */
 	if (chanlen < 1) {
 		comedi_error(dev, "range/channel list is empty!");
 		return 0;
 	}
 
 	if (chanlen > 1) {
-		chansegment[0] = chanlist[0];	// first channel is everytime ok
+		chansegment[0] = chanlist[0];	/*  first channel is everytime ok */
 		for (i = 1, seglen = 1; i < chanlen; i++, seglen++) {
-			// build part of chanlist
-			DEBUG(rt_printk("%d. %d %d\n", i, CR_CHAN(chanlist[i]),
+			/*  build part of chanlist */
+			DEBUG(printk("%d. %d %d\n", i, CR_CHAN(chanlist[i]),
 					CR_RANGE(chanlist[i]));
 				)
 				if (chanlist[0] == chanlist[i])
-				break;	// we detect loop, this must by finish
+				break;	/*  we detect loop, this must by finish */
 			nowmustbechan =
 				(CR_CHAN(chansegment[i - 1]) + 1) % chanlen;
 			if (nowmustbechan != CR_CHAN(chanlist[i])) {
-				// channel list isn't continous :-(
-				rt_printk
+				/*  channel list isn't continous :-( */
+				printk
 					("comedi%d: pcl816: channel list must be continous! chanlist[%i]=%d but must be %d or %d!\n",
 					dev->minor, i, CR_CHAN(chanlist[i]),
 					nowmustbechan, CR_CHAN(chanlist[0]));
 				return 0;
 			}
-			chansegment[i] = chanlist[i];	// well, this is next correct channel in list
+			chansegment[i] = chanlist[i];	/*  well, this is next correct channel in list */
 		}
 
-		for (i = 0, segpos = 0; i < chanlen; i++) {	// check whole chanlist
-			DEBUG(rt_printk("%d %d=%d %d\n",
+		for (i = 0, segpos = 0; i < chanlen; i++) {	/*  check whole chanlist */
+			DEBUG(printk("%d %d=%d %d\n",
 					CR_CHAN(chansegment[i % seglen]),
 					CR_RANGE(chansegment[i % seglen]),
 					CR_CHAN(chanlist[i]),
 					CR_RANGE(chanlist[i]));
 				)
 				if (chanlist[i] != chansegment[i % seglen]) {
-				rt_printk
+				printk
 					("comedi%d: pcl816: bad channel or range number! chanlist[%i]=%d,%d,%d and not %d,%d,%d!\n",
 					dev->minor, i, CR_CHAN(chansegment[i]),
 					CR_RANGE(chansegment[i]),
@@ -915,7 +915,7 @@
 					CR_CHAN(chanlist[i % seglen]),
 					CR_RANGE(chanlist[i % seglen]),
 					CR_AREF(chansegment[i % seglen]));
-				return 0;	// chan/gain list is strange
+				return 0;	/*  chan/gain list is strange */
 			}
 		}
 	} else {
@@ -925,17 +925,17 @@
 	devpriv->ai_act_chanlist_len = seglen;
 	devpriv->ai_act_chanlist_pos = 0;
 
-	for (i = 0; i < seglen; i++) {	// store range list to card
+	for (i = 0; i < seglen; i++) {	/*  store range list to card */
 		devpriv->ai_act_chanlist[i] = CR_CHAN(chanlist[i]);
 		outb(CR_CHAN(chanlist[0]) & 0xf, dev->iobase + PCL816_MUX);
 		outb(CR_RANGE(chanlist[0]), dev->iobase + PCL816_RANGE);	/* select gain */
 	}
 
-	comedi_udelay(1);
+	udelay(1);
 
 	outb(devpriv->ai_act_chanlist[0] | (devpriv->ai_act_chanlist[seglen - 1] << 4), dev->iobase + PCL816_MUX);	/* select channel interval to scan */
 
-	return 1;		// we can serve this with MUX logic
+	return 1;		/*  we can serve this with MUX logic */
 }
 
 #ifdef unused
@@ -979,9 +979,9 @@
 ==============================================================================
   Free any resources that we have claimed
 */
-static void free_resources(struct comedi_device * dev)
+static void free_resources(struct comedi_device *dev)
 {
-	//rt_printk("free_resource()\n");
+	/* printk("free_resource()\n"); */
 	if (dev->private) {
 		pcl816_ai_cancel(dev, devpriv->sub_ai);
 		pcl816_reset(dev);
@@ -993,7 +993,7 @@
 			free_pages(devpriv->dmabuf[1], devpriv->dmapages[1]);
 #ifdef unused
 		if (devpriv->rtc_irq)
-			comedi_free_irq(devpriv->rtc_irq, dev);
+			free_irq(devpriv->rtc_irq, dev);
 		if ((devpriv->dma_rtc) && (RTC_lock == 1)) {
 			if (devpriv->rtc_iobase)
 				release_region(devpriv->rtc_iobase,
@@ -1006,7 +1006,7 @@
 		free_irq(dev->irq, dev);
 	if (dev->iobase)
 		release_region(dev->iobase, this_board->io_range);
-	//rt_printk("free_resource() end\n");
+	/* printk("free_resource() end\n"); */
 }
 
 /*
@@ -1015,13 +1015,13 @@
    Initialization
 
 */
-static int pcl816_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcl816_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int ret;
 	unsigned long iobase;
 	unsigned int irq, dma;
 	unsigned long pages;
-	//int i;
+	/* int i; */
 	struct comedi_subdevice *s;
 
 	/* claim our I/O space */
@@ -1030,18 +1030,19 @@
 		this_board->name, iobase);
 
 	if (!request_region(iobase, this_board->io_range, "pcl816")) {
-		rt_printk("I/O port conflict\n");
+		printk("I/O port conflict\n");
 		return -EIO;
 	}
 
 	dev->iobase = iobase;
 
 	if (pcl816_check(iobase)) {
-		rt_printk(", I cann't detect board. FAIL!\n");
+		printk(", I cann't detect board. FAIL!\n");
 		return -EIO;
 	}
 
-	if ((ret = alloc_private(dev, sizeof(struct pcl816_private))) < 0)
+	ret = alloc_private(dev, sizeof(struct pcl816_private));
+	if (ret < 0)
 		return ret;	/* Can't alloc mem */
 
 	/* set up some name stuff */
@@ -1053,19 +1054,18 @@
 		irq = it->options[1];
 		if (irq) {	/* we want to use IRQ */
 			if (((1 << irq) & this_board->IRQbits) == 0) {
-				rt_printk
+				printk
 					(", IRQ %u is out of allowed range, DISABLING IT",
 					irq);
 				irq = 0;	/* Bad IRQ */
 			} else {
-				if (comedi_request_irq(irq, interrupt_pcl816, 0,
-						"pcl816", dev)) {
-					rt_printk
+				if (request_irq(irq, interrupt_pcl816, 0, "pcl816", dev)) {
+					printk
 						(", unable to allocate IRQ %u, DISABLING IT",
 						irq);
 					irq = 0;	/* Can't use IRQ */
 				} else {
-					rt_printk(", irq=%u", irq);
+					printk(", irq=%u", irq);
 				}
 			}
 		}
@@ -1084,7 +1084,7 @@
 #ifdef unused
 	/* grab RTC for DMA operations */
 	devpriv->dma_rtc = 0;
-	if (it->options[2] > 0) {	// we want to use DMA
+	if (it->options[2] > 0) {	/*  we want to use DMA */
 		if (RTC_lock == 0) {
 			if (!request_region(RTC_PORT(0), RTC_IO_EXTENT,
 					"pcl816 (RTC)"))
@@ -1094,12 +1094,11 @@
 		devpriv->rtc_iosize = RTC_IO_EXTENT;
 		RTC_lock++;
 #ifdef UNTESTED_CODE
-		if (!comedi_request_irq(RTC_IRQ,
-				interrupt_pcl816_ai_mode13_dma_rtc, 0,
+		if (!request_irq(RTC_IRQ, interrupt_pcl816_ai_mode13_dma_rtc, 0,
 				"pcl816 DMA (RTC)", dev)) {
 			devpriv->dma_rtc = 1;
 			devpriv->rtc_irq = RTC_IRQ;
-			rt_printk(", dma_irq=%u", devpriv->rtc_irq);
+			printk(", dma_irq=%u", devpriv->rtc_irq);
 		} else {
 			RTC_lock--;
 			if (RTC_lock == 0) {
@@ -1130,34 +1129,34 @@
 			goto no_dma;	/* DMA disabled */
 
 		if (((1 << dma) & this_board->DMAbits) == 0) {
-			rt_printk(", DMA is out of allowed range, FAIL!\n");
+			printk(", DMA is out of allowed range, FAIL!\n");
 			return -EINVAL;	/* Bad DMA */
 		}
 		ret = request_dma(dma, "pcl816");
 		if (ret) {
-			rt_printk(", unable to allocate DMA %u, FAIL!\n", dma);
+			printk(", unable to allocate DMA %u, FAIL!\n", dma);
 			return -EBUSY;	/* DMA isn't free */
 		}
 
 		devpriv->dma = dma;
-		rt_printk(", dma=%u", dma);
+		printk(", dma=%u", dma);
 		pages = 2;	/* we need 16KB */
 		devpriv->dmabuf[0] = __get_dma_pages(GFP_KERNEL, pages);
 
 		if (!devpriv->dmabuf[0]) {
-			rt_printk(", unable to allocate DMA buffer, FAIL!\n");
+			printk(", unable to allocate DMA buffer, FAIL!\n");
 			/* maybe experiment with try_to_free_pages() will help .... */
 			return -EBUSY;	/* no buffer :-( */
 		}
 		devpriv->dmapages[0] = pages;
 		devpriv->hwdmaptr[0] = virt_to_bus((void *)devpriv->dmabuf[0]);
 		devpriv->hwdmasize[0] = (1 << pages) * PAGE_SIZE;
-		//rt_printk("%d %d %ld, ",devpriv->dmapages[0],devpriv->hwdmasize[0],PAGE_SIZE);
+		/* printk("%d %d %ld, ",devpriv->dmapages[0],devpriv->hwdmasize[0],PAGE_SIZE); */
 
-		if (devpriv->dma_rtc == 0) {	// we must do duble buff :-(
+		if (devpriv->dma_rtc == 0) {	/*  we must do duble buff :-( */
 			devpriv->dmabuf[1] = __get_dma_pages(GFP_KERNEL, pages);
 			if (!devpriv->dmabuf[1]) {
-				rt_printk
+				printk
 					(", unable to allocate DMA buffer, FAIL!\n");
 				return -EBUSY;
 			}
@@ -1177,7 +1176,9 @@
   if (this_board->n_dochan > 0)
     subdevs[3] = COMEDI_SUBD_DO;
 */
-	if ((ret = alloc_subdevices(dev, 1)) < 0)
+
+	ret = alloc_subdevices(dev, 1);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -1188,7 +1189,7 @@
 		s->subdev_flags = SDF_READABLE | SDF_CMD_READ;
 		s->n_chan = this_board->n_aichan;
 		s->subdev_flags |= SDF_DIFF;
-		//printk (", %dchans DIFF DAC - %d", s->n_chan, i);
+		/* printk (", %dchans DIFF DAC - %d", s->n_chan, i); */
 		s->maxdata = this_board->ai_maxdata;
 		s->len_chanlist = this_board->ai_chanlist;
 		s->range_table = this_board->ai_range_type;
@@ -1229,7 +1230,7 @@
 
 	pcl816_reset(dev);
 
-	rt_printk("\n");
+	printk("\n");
 
 	return 0;
 }
@@ -1238,9 +1239,9 @@
 ==============================================================================
   Removes device
  */
-static int pcl816_detach(struct comedi_device * dev)
+static int pcl816_detach(struct comedi_device *dev)
 {
-	DEBUG(rt_printk("comedi%d: pcl816: remove\n", dev->minor);
+	DEBUG(printk("comedi%d: pcl816: remove\n", dev->minor);
 		)
 		free_resources(dev);
 #ifdef unused
diff --git a/drivers/staging/comedi/drivers/pcl818.c b/drivers/staging/comedi/drivers/pcl818.c
index 43a9d56..039a77a 100644
--- a/drivers/staging/comedi/drivers/pcl818.c
+++ b/drivers/staging/comedi/drivers/pcl818.c
@@ -107,9 +107,9 @@
 
 #include "8253.h"
 
-// #define PCL818_MODE13_AO 1
+/* #define PCL818_MODE13_AO 1 */
 
-// boards constants
+/* boards constants */
 
 #define boardPCL818L 0
 #define boardPCL818H 1
@@ -118,60 +118,60 @@
 #define boardPCL818 4
 #define boardPCL718 5
 
-// IO space len
+/* IO space len */
 #define PCLx1x_RANGE 16
-// IO space len if we use FIFO
+/* IO space len if we use FIFO */
 #define PCLx1xFIFO_RANGE 32
 
-// W: clear INT request
+/* W: clear INT request */
 #define PCL818_CLRINT 8
-// R: return status byte
+/* R: return status byte */
 #define PCL818_STATUS 8
-// R: A/D high byte W: A/D range control
+/* R: A/D high byte W: A/D range control */
 #define PCL818_RANGE 1
-// R: next mux scan channel W: mux scan channel & range control pointer
+/* R: next mux scan channel W: mux scan channel & range control pointer */
 #define PCL818_MUX 2
-// R/W: operation control register
+/* R/W: operation control register */
 #define PCL818_CONTROL 9
-// W: counter enable
+/* W: counter enable */
 #define PCL818_CNTENABLE 10
 
-// R: low byte of A/D W: soft A/D trigger
+/* R: low byte of A/D W: soft A/D trigger */
 #define PCL818_AD_LO 0
-// R: high byte of A/D W: A/D range control
+/* R: high byte of A/D W: A/D range control */
 #define PCL818_AD_HI 1
-// W: D/A low&high byte
+/* W: D/A low&high byte */
 #define PCL818_DA_LO 4
 #define PCL818_DA_HI 5
-// R: low&high byte of DI
+/* R: low&high byte of DI */
 #define PCL818_DI_LO 3
 #define PCL818_DI_HI 11
-// W: low&high byte of DO
+/* W: low&high byte of DO */
 #define PCL818_DO_LO 3
 #define PCL818_DO_HI 11
-// W: PCL718 second D/A
+/* W: PCL718 second D/A */
 #define PCL718_DA2_LO 6
 #define PCL718_DA2_HI 7
-// counters
+/* counters */
 #define PCL818_CTR0 12
 #define PCL818_CTR1 13
 #define PCL818_CTR2 14
-// W: counter control
+/* W: counter control */
 #define PCL818_CTRCTL 15
 
-// W: fifo enable/disable
+/* W: fifo enable/disable */
 #define PCL818_FI_ENABLE 6
-// W: fifo interrupt clear
+/* W: fifo interrupt clear */
 #define PCL818_FI_INTCLR 20
-// W: fifo interrupt clear
+/* W: fifo interrupt clear */
 #define PCL818_FI_FLUSH 25
-// R: fifo status
+/* R: fifo status */
 #define PCL818_FI_STATUS 25
-// R: one record from FIFO
+/* R: one record from FIFO */
 #define PCL818_FI_DATALO 23
 #define PCL818_FI_DATAHI 23
 
-// type of interrupt handler
+/* type of interrupt handler */
 #define INT_TYPE_AI1_INT 1
 #define INT_TYPE_AI1_DMA 2
 #define INT_TYPE_AI1_FIFO 3
@@ -184,7 +184,7 @@
 #endif
 
 #ifdef unused
-// RTC stuff...
+/* RTC stuff... */
 #define INT_TYPE_AI1_DMA_RTC 9
 #define INT_TYPE_AI3_DMA_RTC 10
 
@@ -244,8 +244,8 @@
 static const struct comedi_lrange range718_unipolar2 = { 1, {UNI_RANGE(2),} };
 static const struct comedi_lrange range718_unipolar1 = { 1, {BIP_RANGE(1),} };
 
-static int pcl818_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcl818_detach(struct comedi_device * dev);
+static int pcl818_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcl818_detach(struct comedi_device *dev);
 
 #ifdef unused
 static int RTC_lock = 0;	/* RTC lock */
@@ -254,22 +254,22 @@
 
 struct pcl818_board {
 
-	const char *name;	// driver name
-	int n_ranges;		// len of range list
-	int n_aichan_se;	// num of A/D chans in single ended  mode
-	int n_aichan_diff;	// num of A/D chans in diferencial mode
-	unsigned int ns_min;	// minimal alllowed delay between samples (in ns)
-	int n_aochan;		// num of D/A chans
-	int n_dichan;		// num of DI chans
-	int n_dochan;		// num of DO chans
-	const struct comedi_lrange *ai_range_type;	// default A/D rangelist
-	const struct comedi_lrange *ao_range_type;	// default D/A rangelist
-	unsigned int io_range;	// len of IO space
-	unsigned int IRQbits;	// allowed interrupts
-	unsigned int DMAbits;	// allowed DMA chans
-	int ai_maxdata;		// maxdata for A/D
-	int ao_maxdata;		// maxdata for D/A
-	unsigned char fifo;	// 1=board has FIFO
+	const char *name;	/*  driver name */
+	int n_ranges;		/*  len of range list */
+	int n_aichan_se;	/*  num of A/D chans in single ended  mode */
+	int n_aichan_diff;	/*  num of A/D chans in diferencial mode */
+	unsigned int ns_min;	/*  minimal alllowed delay between samples (in ns) */
+	int n_aochan;		/*  num of D/A chans */
+	int n_dichan;		/*  num of DI chans */
+	int n_dochan;		/*  num of DO chans */
+	const struct comedi_lrange *ai_range_type;	/*  default A/D rangelist */
+	const struct comedi_lrange *ao_range_type;	/*  default D/A rangelist */
+	unsigned int io_range;	/*  len of IO space */
+	unsigned int IRQbits;	/*  allowed interrupts */
+	unsigned int DMAbits;	/*  allowed DMA chans */
+	int ai_maxdata;		/*  maxdata for A/D */
+	int ao_maxdata;		/*  maxdata for D/A */
+	unsigned char fifo;	/*  1=board has FIFO */
 	int is_818;
 };
 
@@ -302,67 +302,67 @@
 #define n_boardtypes (sizeof(boardtypes)/sizeof(struct pcl818_board))
 
 static struct comedi_driver driver_pcl818 = {
-      driver_name:"pcl818",
-      module:THIS_MODULE,
-      attach:pcl818_attach,
-      detach:pcl818_detach,
-      board_name:&boardtypes[0].name,
-      num_names:n_boardtypes,
-      offset:sizeof(struct pcl818_board),
+	.driver_name = "pcl818",
+	.module = THIS_MODULE,
+	.attach = pcl818_attach,
+	.detach = pcl818_detach,
+	.board_name = &boardtypes[0].name,
+	.num_names = n_boardtypes,
+	.offset = sizeof(struct pcl818_board),
 };
 
 COMEDI_INITCLEANUP(driver_pcl818);
 
 struct pcl818_private {
 
-	unsigned int dma;	// used DMA, 0=don't use DMA
-	int dma_rtc;		// 1=RTC used with DMA, 0=no RTC alloc
+	unsigned int dma;	/*  used DMA, 0=don't use DMA */
+	int dma_rtc;		/*  1=RTC used with DMA, 0=no RTC alloc */
 	unsigned int io_range;
 #ifdef unused
-	unsigned long rtc_iobase;	// RTC port region
+	unsigned long rtc_iobase;	/*  RTC port region */
 	unsigned int rtc_iosize;
 	unsigned int rtc_irq;
-	struct timer_list rtc_irq_timer;	// timer for RTC sanity check
-	unsigned long rtc_freq;	// RTC int freq
-	int rtc_irq_blocked;	// 1=we now do AI with DMA&RTC
+	struct timer_list rtc_irq_timer;	/*  timer for RTC sanity check */
+	unsigned long rtc_freq;	/*  RTC int freq */
+	int rtc_irq_blocked;	/*  1=we now do AI with DMA&RTC */
 #endif
-	unsigned long dmabuf[2];	// pointers to begin of DMA buffers
-	unsigned int dmapages[2];	// len of DMA buffers in PAGE_SIZEs
-	unsigned int hwdmaptr[2];	// hardware address of DMA buffers
-	unsigned int hwdmasize[2];	// len of DMA buffers in Bytes
-	unsigned int dmasamplsize;	// size in samples hwdmasize[0]/2
-	unsigned int last_top_dma;	// DMA pointer in last RTC int
-	int next_dma_buf;	// which DMA buffer will be used next round
-	long dma_runs_to_end;	// how many we must permorm DMA transfer to end of record
-	unsigned long last_dma_run;	// how many bytes we must transfer on last DMA page
-	unsigned char neverending_ai;	// if=1, then we do neverending record (you must use cancel())
-	unsigned int ns_min;	// manimal alllowed delay between samples (in us) for actual card
-	int i8253_osc_base;	// 1/frequency of on board oscilator in ns
-	int irq_free;		// 1=have allocated IRQ
-	int irq_blocked;	// 1=IRQ now uses any subdev
-	int irq_was_now_closed;	// when IRQ finish, there's stored int818_mode for last interrupt
-	int ai_mode;		// who now uses IRQ - 1=AI1 int, 2=AI1 dma, 3=AI3 int, 4AI3 dma
-	struct comedi_subdevice *last_int_sub;	// ptr to subdevice which now finish
-	int ai_act_scan;	// how many scans we finished
-	int ai_act_chan;	// actual position in actual scan
-	unsigned int act_chanlist[16];	// MUX setting for actual AI operations
-	unsigned int act_chanlist_len;	// how long is actual MUX list
-	unsigned int act_chanlist_pos;	// actual position in MUX list
-	unsigned int ai_scans;	// len of scanlist
-	unsigned int ai_n_chan;	// how many channels is measured
-	unsigned int *ai_chanlist;	// actaul chanlist
-	unsigned int ai_flags;	// flaglist
-	unsigned int ai_data_len;	// len of data buffer
-	short *ai_data;	// data buffer
-	unsigned int ai_timer1;	// timers
+	unsigned long dmabuf[2];	/*  pointers to begin of DMA buffers */
+	unsigned int dmapages[2];	/*  len of DMA buffers in PAGE_SIZEs */
+	unsigned int hwdmaptr[2];	/*  hardware address of DMA buffers */
+	unsigned int hwdmasize[2];	/*  len of DMA buffers in Bytes */
+	unsigned int dmasamplsize;	/*  size in samples hwdmasize[0]/2 */
+	unsigned int last_top_dma;	/*  DMA pointer in last RTC int */
+	int next_dma_buf;	/*  which DMA buffer will be used next round */
+	long dma_runs_to_end;	/*  how many we must permorm DMA transfer to end of record */
+	unsigned long last_dma_run;	/*  how many bytes we must transfer on last DMA page */
+	unsigned char neverending_ai;	/*  if=1, then we do neverending record (you must use cancel()) */
+	unsigned int ns_min;	/*  manimal alllowed delay between samples (in us) for actual card */
+	int i8253_osc_base;	/*  1/frequency of on board oscilator in ns */
+	int irq_free;		/*  1=have allocated IRQ */
+	int irq_blocked;	/*  1=IRQ now uses any subdev */
+	int irq_was_now_closed;	/*  when IRQ finish, there's stored int818_mode for last interrupt */
+	int ai_mode;		/*  who now uses IRQ - 1=AI1 int, 2=AI1 dma, 3=AI3 int, 4AI3 dma */
+	struct comedi_subdevice *last_int_sub;	/*  ptr to subdevice which now finish */
+	int ai_act_scan;	/*  how many scans we finished */
+	int ai_act_chan;	/*  actual position in actual scan */
+	unsigned int act_chanlist[16];	/*  MUX setting for actual AI operations */
+	unsigned int act_chanlist_len;	/*  how long is actual MUX list */
+	unsigned int act_chanlist_pos;	/*  actual position in MUX list */
+	unsigned int ai_scans;	/*  len of scanlist */
+	unsigned int ai_n_chan;	/*  how many channels is measured */
+	unsigned int *ai_chanlist;	/*  actaul chanlist */
+	unsigned int ai_flags;	/*  flaglist */
+	unsigned int ai_data_len;	/*  len of data buffer */
+	short *ai_data;	/*  data buffer */
+	unsigned int ai_timer1;	/*  timers */
 	unsigned int ai_timer2;
-	struct comedi_subdevice *sub_ai;	// ptr to AI subdevice
-	unsigned char usefifo;	// 1=use fifo
+	struct comedi_subdevice *sub_ai;	/*  ptr to AI subdevice */
+	unsigned char usefifo;	/*  1=use fifo */
 	unsigned int ao_readback[2];
 };
 
 
-static const unsigned int muxonechan[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,	// used for gain list programming
+static const unsigned int muxonechan[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,	/*  used for gain list programming */
 	0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff
 };
 
@@ -372,13 +372,13 @@
 /*
 ==============================================================================
 */
-static void setup_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static void setup_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int *chanlist, unsigned int n_chan, unsigned int seglen);
-static int check_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static int check_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int *chanlist, unsigned int n_chan);
 
-static int pcl818_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static void start_pacer(struct comedi_device * dev, int mode, unsigned int divisor1,
+static int pcl818_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static void start_pacer(struct comedi_device *dev, int mode, unsigned int divisor1,
 	unsigned int divisor2);
 
 #ifdef unused
@@ -391,8 +391,8 @@
 ==============================================================================
    ANALOG INPUT MODE0, 818 cards, slow version
 */
-static int pcl818_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl818_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int timeout;
@@ -418,7 +418,7 @@
 		while (timeout--) {
 			if (inb(dev->iobase + PCL818_STATUS) & 0x10)
 				goto conv_finish;
-			comedi_udelay(1);
+			udelay(1);
 		}
 		comedi_error(dev, "A/D insn timeout");
 		/* clear INT (conversion end) flag */
@@ -438,8 +438,8 @@
    ANALOG OUTPUT MODE0, 818 cards
    only one sample per call is supported
 */
-static int pcl818_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl818_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan = CR_CHAN(insn->chanspec);
@@ -451,8 +451,8 @@
 	return n;
 }
 
-static int pcl818_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl818_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan = CR_CHAN(insn->chanspec);
@@ -460,9 +460,9 @@
 	for (n = 0; n < insn->n; n++) {
 		devpriv->ao_readback[chan] = data[n];
 		outb((data[n] & 0x000f) << 4, dev->iobase +
-			(chan) ? PCL718_DA2_LO : PCL818_DA_LO);
+			(chan ? PCL718_DA2_LO : PCL818_DA_LO));
 		outb((data[n] & 0x0ff0) >> 4, dev->iobase +
-			(chan) ? PCL718_DA2_HI : PCL818_DA_HI);
+			(chan ? PCL718_DA2_HI : PCL818_DA_HI));
 	}
 
 	return n;
@@ -474,8 +474,8 @@
 
    only one sample per call is supported
 */
-static int pcl818_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl818_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -492,8 +492,8 @@
 
    only one sample per call is supported
 */
-static int pcl818_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl818_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -524,7 +524,7 @@
 	while (timeout--) {
 		if (inb(dev->iobase + PCL818_STATUS) & 0x10)
 			goto conv_finish;
-		comedi_udelay(1);
+		udelay(1);
 	}
 	outb(0, dev->iobase + PCL818_STATUS);	/* clear INT request */
 	comedi_error(dev, "A/D mode1/3 IRQ without DRDY!");
@@ -535,11 +535,11 @@
 
       conv_finish:
 	low = inb(dev->iobase + PCL818_AD_LO);
-	comedi_buf_put(s->async, ((inb(dev->iobase + PCL818_AD_HI) << 4) | (low >> 4)));	// get one sample
+	comedi_buf_put(s->async, ((inb(dev->iobase + PCL818_AD_HI) << 4) | (low >> 4)));	/*  get one sample */
 	outb(0, dev->iobase + PCL818_CLRINT);	/* clear INT request */
 
-	if ((low & 0xf) != devpriv->act_chanlist[devpriv->act_chanlist_pos]) {	// dropout!
-		rt_printk
+	if ((low & 0xf) != devpriv->act_chanlist[devpriv->act_chanlist_pos]) {	/*  dropout! */
+		printk
 			("comedi: A/D mode1/3 IRQ - channel dropout %x!=%x !\n",
 			(low & 0xf),
 			devpriv->act_chanlist[devpriv->act_chanlist_pos]);
@@ -549,7 +549,7 @@
 		return IRQ_HANDLED;
 	}
 	if (s->async->cur_chan == 0) {
-		// rt_printk("E");
+		/*  printk("E"); */
 		devpriv->ai_act_scan--;
 	}
 
@@ -577,7 +577,7 @@
 
 	disable_dma(devpriv->dma);
 	devpriv->next_dma_buf = 1 - devpriv->next_dma_buf;
-	if ((devpriv->dma_runs_to_end) > -1 || devpriv->neverending_ai) {	// switch dma bufs
+	if ((devpriv->dma_runs_to_end) > -1 || devpriv->neverending_ai) {	/*  switch dma bufs */
 		set_dma_mode(devpriv->dma, DMA_MODE_READ);
 		flags = claim_dma_lock();
 		set_dma_addr(devpriv->dma,
@@ -591,7 +591,7 @@
 		release_dma_lock(flags);
 		enable_dma(devpriv->dma);
 	}
-	rt_printk("comedi: A/D mode1/3 IRQ \n");
+	printk("comedi: A/D mode1/3 IRQ \n");
 
 	devpriv->dma_runs_to_end--;
 	outb(0, dev->iobase + PCL818_CLRINT);	/* clear INT request */
@@ -601,8 +601,8 @@
 	bufptr = 0;
 
 	for (i = 0; i < len; i++) {
-		if ((ptr[bufptr] & 0xf) != devpriv->act_chanlist[devpriv->act_chanlist_pos]) {	// dropout!
-			rt_printk
+		if ((ptr[bufptr] & 0xf) != devpriv->act_chanlist[devpriv->act_chanlist_pos]) {	/*  dropout! */
+			printk
 				("comedi: A/D mode1/3 DMA - channel dropout %d(card)!=%d(chanlist) at %d !\n",
 				(ptr[bufptr] & 0xf),
 				devpriv->act_chanlist[devpriv->
@@ -614,7 +614,7 @@
 			return IRQ_HANDLED;
 		}
 
-		comedi_buf_put(s->async, ptr[bufptr++] >> 4);	// get one sample
+		comedi_buf_put(s->async, ptr[bufptr++] >> 4);	/*  get one sample */
 
 		devpriv->act_chanlist_pos++;
 		if (devpriv->act_chanlist_pos >= devpriv->act_chanlist_len) {
@@ -627,7 +627,7 @@
 				pcl818_ai_cancel(dev, s);
 				s->async->events |= COMEDI_CB_EOA;
 				comedi_event(dev, s);
-				// printk("done int ai13 dma\n");
+				/*  printk("done int ai13 dma\n"); */
 				return IRQ_HANDLED;
 			}
 	}
@@ -651,7 +651,7 @@
 	long ofs_dats;
 	short *dmabuf = (short *) devpriv->dmabuf[0];
 
-	//outb(2,0x378);
+	/* outb(2,0x378); */
 	switch (devpriv->ai_mode) {
 	case INT_TYPE_AI1_DMA_RTC:
 	case INT_TYPE_AI3_DMA_RTC:
@@ -668,32 +668,32 @@
 
 		if (top1 != top2)
 			return IRQ_HANDLED;
-		top1 = devpriv->hwdmasize[0] - top1;	// where is now DMA in buffer
+		top1 = devpriv->hwdmasize[0] - top1;	/*  where is now DMA in buffer */
 		top1 >>= 1;
-		ofs_dats = top1 - devpriv->last_top_dma;	// new samples from last call
+		ofs_dats = top1 - devpriv->last_top_dma;	/*  new samples from last call */
 		if (ofs_dats < 0)
 			ofs_dats = (devpriv->dmasamplsize) + ofs_dats;
 		if (!ofs_dats)
-			return IRQ_HANDLED;	// exit=no new samples from last call
-		// obsluz data
+			return IRQ_HANDLED;	/*  exit=no new samples from last call */
+		/*  obsluz data */
 		i = devpriv->last_top_dma - 1;
 		i &= (devpriv->dmasamplsize - 1);
 
-		if (dmabuf[i] != MAGIC_DMA_WORD) {	// DMA overflow!
+		if (dmabuf[i] != MAGIC_DMA_WORD) {	/*  DMA overflow! */
 			comedi_error(dev, "A/D mode1/3 DMA buffer overflow!");
-			//rt_printk("I %d dmabuf[i] %d %d\n",i,dmabuf[i],devpriv->dmasamplsize);
+			/* printk("I %d dmabuf[i] %d %d\n",i,dmabuf[i],devpriv->dmasamplsize); */
 			pcl818_ai_cancel(dev, s);
 			s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
 			comedi_event(dev, s);
 			return IRQ_HANDLED;
 		}
-		//rt_printk("r %ld ",ofs_dats);
+		/* printk("r %ld ",ofs_dats); */
 
 		bufptr = devpriv->last_top_dma;
 
 		for (i = 0; i < ofs_dats; i++) {
-			if ((dmabuf[bufptr] & 0xf) != devpriv->act_chanlist[devpriv->act_chanlist_pos]) {	// dropout!
-				rt_printk
+			if ((dmabuf[bufptr] & 0xf) != devpriv->act_chanlist[devpriv->act_chanlist_pos]) {	/*  dropout! */
+				printk
 					("comedi: A/D mode1/3 DMA - channel dropout %d!=%d !\n",
 					(dmabuf[bufptr] & 0xf),
 					devpriv->act_chanlist[devpriv->
@@ -705,7 +705,7 @@
 				return IRQ_HANDLED;
 			}
 
-			comedi_buf_put(s->async, dmabuf[bufptr++] >> 4);	// get one sample
+			comedi_buf_put(s->async, dmabuf[bufptr++] >> 4);	/*  get one sample */
 			bufptr &= (devpriv->dmasamplsize - 1);
 
 			if (s->async->cur_chan == 0) {
@@ -717,7 +717,7 @@
 					pcl818_ai_cancel(dev, s);
 					s->async->events |= COMEDI_CB_EOA;
 					comedi_event(dev, s);
-					//printk("done int ai13 dma\n");
+					/* printk("done int ai13 dma\n"); */
 					return IRQ_HANDLED;
 				}
 		}
@@ -727,11 +727,11 @@
 		bufptr &= (devpriv->dmasamplsize - 1);
 		dmabuf[bufptr] = MAGIC_DMA_WORD;
 		comedi_event(dev, s);
-		//outb(0,0x378);
+		/* outb(0,0x378); */
 		return IRQ_HANDLED;
 	}
 
-	//outb(0,0x378);
+	/* outb(0,0x378); */
 	return IRQ_HANDLED;
 }
 #endif
@@ -746,7 +746,7 @@
 	struct comedi_subdevice *s = dev->subdevices + 0;
 	int i, len, lo;
 
-	outb(0, dev->iobase + PCL818_FI_INTCLR);	// clear fifo int request
+	outb(0, dev->iobase + PCL818_FI_INTCLR);	/*  clear fifo int request */
 
 	lo = inb(dev->iobase + PCL818_FI_STATUS);
 
@@ -774,8 +774,8 @@
 
 	for (i = 0; i < len; i++) {
 		lo = inb(dev->iobase + PCL818_FI_DATALO);
-		if ((lo & 0xf) != devpriv->act_chanlist[devpriv->act_chanlist_pos]) {	// dropout!
-			rt_printk
+		if ((lo & 0xf) != devpriv->act_chanlist[devpriv->act_chanlist_pos]) {	/*  dropout! */
+			printk
 				("comedi: A/D mode1/3 FIFO - channel dropout %d!=%d !\n",
 				(lo & 0xf),
 				devpriv->act_chanlist[devpriv->
@@ -786,7 +786,7 @@
 			return IRQ_HANDLED;
 		}
 
-		comedi_buf_put(s->async, (lo >> 4) | (inb(dev->iobase + PCL818_FI_DATAHI) << 4));	// get one sample
+		comedi_buf_put(s->async, (lo >> 4) | (inb(dev->iobase + PCL818_FI_DATAHI) << 4));	/*  get one sample */
 
 		if (s->async->cur_chan == 0) {
 			devpriv->ai_act_scan--;
@@ -810,7 +810,7 @@
 ==============================================================================
     INT procedure
 */
-static irqreturn_t interrupt_pcl818(int irq, void *d PT_REGS_ARG)
+static irqreturn_t interrupt_pcl818(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 
@@ -818,7 +818,28 @@
 		comedi_error(dev, "premature interrupt");
 		return IRQ_HANDLED;
 	}
-	//rt_printk("I\n");
+	/* printk("I\n"); */
+
+	if (devpriv->irq_blocked && devpriv->irq_was_now_closed) {
+		if ((devpriv->neverending_ai || (!devpriv->neverending_ai &&
+						devpriv->ai_act_scan > 0)) &&
+				(devpriv->ai_mode == INT_TYPE_AI1_DMA ||
+				 devpriv->ai_mode == INT_TYPE_AI3_DMA)) {
+			/* The cleanup from ai_cancel() has been delayed
+			   until now because the card doesn't seem to like
+			   being reprogrammed while a DMA transfer is in
+			   progress.
+			 */
+			struct comedi_subdevice *s = dev->subdevices + 0;
+			devpriv->ai_act_scan = 0;
+			devpriv->neverending_ai = 0;
+			pcl818_ai_cancel(dev, s);
+		}
+
+		outb(0, dev->iobase + PCL818_CLRINT);	/* clear INT request */
+
+		return IRQ_HANDLED;
+	}
 
 	switch (devpriv->ai_mode) {
 	case INT_TYPE_AI1_DMA:
@@ -843,25 +864,6 @@
 
 	if ((!dev->irq) || (!devpriv->irq_free) || (!devpriv->irq_blocked)
 		|| (!devpriv->ai_mode)) {
-		if (devpriv->irq_was_now_closed) {
-			if (devpriv->neverending_ai &&
-				(devpriv->ai_mode == INT_TYPE_AI1_DMA
-					|| devpriv->ai_mode ==
-					INT_TYPE_AI3_DMA)) {
-				/* we had neverending ai but ai_cancel() has been called
-				   the cleanup from ai_cancel() has been delayed until know
-				   because the card doesn't seem to like being reprogrammed
-				   while a DMA transfer is in progress
-				 */
-				struct comedi_subdevice *s = dev->subdevices + 0;
-				devpriv->ai_mode = devpriv->irq_was_now_closed;
-				devpriv->irq_was_now_closed = 0;
-				devpriv->neverending_ai = 0;
-				pcl818_ai_cancel(dev, s);
-			}
-			devpriv->irq_was_now_closed = 0;
-			return IRQ_HANDLED;
-		}
 		comedi_error(dev, "bad IRQ!");
 		return IRQ_NONE;
 	}
@@ -874,19 +876,19 @@
 ==============================================================================
    ANALOG INPUT MODE 1 or 3 DMA , 818 cards
 */
-static void pcl818_ai_mode13dma_int(int mode, struct comedi_device * dev,
-	struct comedi_subdevice * s)
+static void pcl818_ai_mode13dma_int(int mode, struct comedi_device *dev,
+	struct comedi_subdevice *s)
 {
 	unsigned int flags;
 	unsigned int bytes;
 
-	rt_printk("mode13dma_int, mode: %d\n", mode);
-	disable_dma(devpriv->dma);	// disable dma
+	printk("mode13dma_int, mode: %d\n", mode);
+	disable_dma(devpriv->dma);	/*  disable dma */
 	bytes = devpriv->hwdmasize[0];
 	if (!devpriv->neverending_ai) {
-		bytes = devpriv->ai_n_chan * devpriv->ai_scans * sizeof(short);	// how many
-		devpriv->dma_runs_to_end = bytes / devpriv->hwdmasize[0];	// how many DMA pages we must fiil
-		devpriv->last_dma_run = bytes % devpriv->hwdmasize[0];	//on last dma transfer must be moved
+		bytes = devpriv->ai_n_chan * devpriv->ai_scans * sizeof(short);	/*  how many */
+		devpriv->dma_runs_to_end = bytes / devpriv->hwdmasize[0];	/*  how many DMA pages we must fiil */
+		devpriv->last_dma_run = bytes % devpriv->hwdmasize[0];	/* on last dma transfer must be moved */
 		devpriv->dma_runs_to_end--;
 		if (devpriv->dma_runs_to_end >= 0)
 			bytes = devpriv->hwdmasize[0];
@@ -915,8 +917,8 @@
 ==============================================================================
    ANALOG INPUT MODE 1 or 3 DMA rtc, 818 cards
 */
-static void pcl818_ai_mode13dma_rtc(int mode, struct comedi_device * dev,
-	struct comedi_subdevice * s)
+static void pcl818_ai_mode13dma_rtc(int mode, struct comedi_device *dev,
+	struct comedi_subdevice *s)
 {
 	unsigned int flags;
 	short *pole;
@@ -928,7 +930,7 @@
 	set_dma_count(devpriv->dma, devpriv->hwdmasize[0]);
 	release_dma_lock(flags);
 	enable_dma(devpriv->dma);
-	devpriv->last_top_dma = 0;	//devpriv->hwdmasize[0];
+	devpriv->last_top_dma = 0;	/* devpriv->hwdmasize[0]; */
 	pole = (short *) devpriv->dmabuf[0];
 	devpriv->dmasamplsize = devpriv->hwdmasize[0] / 2;
 	pole[devpriv->dmasamplsize - 1] = MAGIC_DMA_WORD;
@@ -956,14 +958,14 @@
 ==============================================================================
    ANALOG INPUT MODE 1 or 3, 818 cards
 */
-static int pcl818_ai_cmd_mode(int mode, struct comedi_device * dev,
-	struct comedi_subdevice * s)
+static int pcl818_ai_cmd_mode(int mode, struct comedi_device *dev,
+	struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	int divisor1, divisor2;
 	unsigned int seglen;
 
-	rt_printk("pcl818_ai_cmd_mode()\n");
+	printk("pcl818_ai_cmd_mode()\n");
 	if ((!dev->irq) && (!devpriv->dma_rtc)) {
 		comedi_error(dev, "IRQ not defined!");
 		return -EINVAL;
@@ -972,7 +974,7 @@
 	if (devpriv->irq_blocked)
 		return -EBUSY;
 
-	start_pacer(dev, -1, 0, 0);	// stop pacer
+	start_pacer(dev, -1, 0, 0);	/*  stop pacer */
 
 	seglen = check_channel_list(dev, s, devpriv->ai_chanlist,
 		devpriv->ai_n_chan);
@@ -981,7 +983,7 @@
 	setup_channel_list(dev, s, devpriv->ai_chanlist,
 		devpriv->ai_n_chan, seglen);
 
-	comedi_udelay(1);
+	udelay(1);
 
 	devpriv->ai_act_scan = devpriv->ai_scans;
 	devpriv->ai_act_chan = 0;
@@ -992,7 +994,7 @@
 	devpriv->dma_runs_to_end = 0;
 
 	if ((devpriv->ai_scans == 0) || (devpriv->ai_scans == -1))
-		devpriv->neverending_ai = 1;	//well, user want neverending
+		devpriv->neverending_ai = 1;	/* well, user want neverending */
 
 	if (mode == 1) {
 		i8253_cascade_ns_to_timer(devpriv->i8253_osc_base, &divisor1,
@@ -1010,7 +1012,7 @@
 	outb(0, dev->iobase + PCL818_CNTENABLE);	/* enable pacer */
 
 	switch (devpriv->dma) {
-	case 1:		// DMA
+	case 1:		/*  DMA */
 	case 3:
 		if (devpriv->dma_rtc == 0) {
 			pcl818_ai_mode13dma_int(mode, dev, s);
@@ -1025,26 +1027,32 @@
 		}
 #endif
 		break;
-	case 0:		// IRQ
-		// rt_printk("IRQ\n");
-		if (mode == 1) {
-			devpriv->ai_mode = INT_TYPE_AI1_INT;
-			outb(0x83 | (dev->irq << 4), dev->iobase + PCL818_CONTROL);	/* Pacer+IRQ */
+	case 0:
+		if (!devpriv->usefifo) {
+			/* IRQ */
+			/* printk("IRQ\n"); */
+			if (mode == 1) {
+				devpriv->ai_mode = INT_TYPE_AI1_INT;
+				/* Pacer+IRQ */
+				outb(0x83 | (dev->irq << 4), dev->iobase + PCL818_CONTROL);
+			} else {
+				devpriv->ai_mode = INT_TYPE_AI3_INT;
+				/* Ext trig+IRQ */
+				outb(0x82 | (dev->irq << 4), dev->iobase + PCL818_CONTROL);
+			}
 		} else {
-			devpriv->ai_mode = INT_TYPE_AI3_INT;
-			outb(0x82 | (dev->irq << 4), dev->iobase + PCL818_CONTROL);	/* Ext trig+IRQ */
-		};
-		break;
-	case -1:		// FIFO
-		outb(1, dev->iobase + PCL818_FI_ENABLE);	// enable FIFO
-		if (mode == 1) {
-			devpriv->ai_mode = INT_TYPE_AI1_FIFO;
-			outb(0x03, dev->iobase + PCL818_CONTROL);	/* Pacer */
-		} else {
-			devpriv->ai_mode = INT_TYPE_AI3_FIFO;
-			outb(0x02, dev->iobase + PCL818_CONTROL);
-		};		/* Ext trig */
-		break;
+			/* FIFO */
+			/* enable FIFO */
+			outb(1, dev->iobase + PCL818_FI_ENABLE);
+			if (mode == 1) {
+				devpriv->ai_mode = INT_TYPE_AI1_FIFO;
+				/* Pacer */
+				outb(0x03, dev->iobase + PCL818_CONTROL);
+			} else {
+				devpriv->ai_mode = INT_TYPE_AI3_FIFO;
+				outb(0x02, dev->iobase + PCL818_CONTROL);
+			}
+		}
 	}
 
 	start_pacer(dev, mode, divisor1, divisor2);
@@ -1057,7 +1065,7 @@
 		break;
 	}
 #endif
-	rt_printk("pcl818_ai_cmd_mode() end\n");
+	printk("pcl818_ai_cmd_mode() end\n");
 	return 0;
 }
 
@@ -1067,8 +1075,8 @@
    ANALOG OUTPUT MODE 1 or 3, 818 cards
 */
 #ifdef PCL818_MODE13_AO
-static int pcl818_ao_mode13(int mode, struct comedi_device * dev, struct comedi_subdevice * s,
-	comedi_trig * it)
+static int pcl818_ao_mode13(int mode, struct comedi_device *dev, struct comedi_subdevice *s,
+	comedi_trig *it)
 {
 	int divisor1, divisor2;
 
@@ -1080,7 +1088,7 @@
 	if (devpriv->irq_blocked)
 		return -EBUSY;
 
-	start_pacer(dev, -1, 0, 0);	// stop pacer
+	start_pacer(dev, -1, 0, 0);	/*  stop pacer */
 
 	devpriv->int13_act_scan = it->n;
 	devpriv->int13_act_chan = 0;
@@ -1120,8 +1128,8 @@
 ==============================================================================
    ANALOG OUTPUT MODE 1, 818 cards
 */
-static int pcl818_ao_mode1(struct comedi_device * dev, struct comedi_subdevice * s,
-	comedi_trig * it)
+static int pcl818_ao_mode1(struct comedi_device *dev, struct comedi_subdevice *s,
+	comedi_trig *it)
 {
 	return pcl818_ao_mode13(1, dev, s, it);
 }
@@ -1130,8 +1138,8 @@
 ==============================================================================
    ANALOG OUTPUT MODE 3, 818 cards
 */
-static int pcl818_ao_mode3(struct comedi_device * dev, struct comedi_subdevice * s,
-	comedi_trig * it)
+static int pcl818_ao_mode3(struct comedi_device *dev, struct comedi_subdevice *s,
+	comedi_trig *it)
 {
 	return pcl818_ao_mode13(3, dev, s, it);
 }
@@ -1142,12 +1150,12 @@
 ==============================================================================
  Start/stop pacer onboard pacer
 */
-static void start_pacer(struct comedi_device * dev, int mode, unsigned int divisor1,
+static void start_pacer(struct comedi_device *dev, int mode, unsigned int divisor1,
 	unsigned int divisor2)
 {
 	outb(0xb4, dev->iobase + PCL818_CTRCTL);
 	outb(0x74, dev->iobase + PCL818_CTRCTL);
-	comedi_udelay(1);
+	udelay(1);
 
 	if (mode == 1) {
 		outb(divisor2 & 0xff, dev->iobase + PCL818_CTR2);
@@ -1162,7 +1170,7 @@
  Check if channel list from user is builded correctly
  If it's ok, then program scan/gain logic
 */
-static int check_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static int check_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int *chanlist, unsigned int n_chan)
 {
 	unsigned int chansegment[16];
@@ -1175,32 +1183,36 @@
 	}
 
 	if (n_chan > 1) {
-		// first channel is everytime ok
+		/*  first channel is everytime ok */
 		chansegment[0] = chanlist[0];
-		// build part of chanlist
+		/*  build part of chanlist */
 		for (i = 1, seglen = 1; i < n_chan; i++, seglen++) {
-			// rt_printk("%d. %d %d\n",i,CR_CHAN(it->chanlist[i]),CR_RANGE(it->chanlist[i]));
-			// we detect loop, this must by finish
+
+			/* printk("%d. %d * %d\n",i,
+			 * CR_CHAN(it->chanlist[i]),CR_RANGE(it->chanlist[i]));*/
+
+			/* we detect loop, this must by finish */
+
 			if (chanlist[0] == chanlist[i])
 				break;
 			nowmustbechan =
 				(CR_CHAN(chansegment[i - 1]) + 1) % s->n_chan;
-			if (nowmustbechan != CR_CHAN(chanlist[i])) {	// channel list isn't continous :-(
-				rt_printk
+			if (nowmustbechan != CR_CHAN(chanlist[i])) {	/*  channel list isn't continous :-( */
+				printk
 					("comedi%d: pcl818: channel list must be continous! chanlist[%i]=%d but must be %d or %d!\n",
 					dev->minor, i, CR_CHAN(chanlist[i]),
 					nowmustbechan, CR_CHAN(chanlist[0]));
 				return 0;
 			}
-			// well, this is next correct channel in list
+			/*  well, this is next correct channel in list */
 			chansegment[i] = chanlist[i];
 		}
 
-		// check whole chanlist
+		/*  check whole chanlist */
 		for (i = 0, segpos = 0; i < n_chan; i++) {
-			//rt_printk("%d %d=%d %d\n",CR_CHAN(chansegment[i%seglen]),CR_RANGE(chansegment[i%seglen]),CR_CHAN(it->chanlist[i]),CR_RANGE(it->chanlist[i]));
+			/* printk("%d %d=%d %d\n",CR_CHAN(chansegment[i%seglen]),CR_RANGE(chansegment[i%seglen]),CR_CHAN(it->chanlist[i]),CR_RANGE(it->chanlist[i])); */
 			if (chanlist[i] != chansegment[i % seglen]) {
-				rt_printk
+				printk
 					("comedi%d: pcl818: bad channel or range number! chanlist[%i]=%d,%d,%d and not %d,%d,%d!\n",
 					dev->minor, i, CR_CHAN(chansegment[i]),
 					CR_RANGE(chansegment[i]),
@@ -1208,17 +1220,17 @@
 					CR_CHAN(chanlist[i % seglen]),
 					CR_RANGE(chanlist[i % seglen]),
 					CR_AREF(chansegment[i % seglen]));
-				return 0;	// chan/gain list is strange
+				return 0;	/*  chan/gain list is strange */
 			}
 		}
 	} else {
 		seglen = 1;
 	}
-	rt_printk("check_channel_list: seglen %d\n", seglen);
+	printk("check_channel_list: seglen %d\n", seglen);
 	return seglen;
 }
 
-static void setup_channel_list(struct comedi_device * dev, struct comedi_subdevice * s,
+static void setup_channel_list(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int *chanlist, unsigned int n_chan, unsigned int seglen)
 {
 	int i;
@@ -1226,13 +1238,13 @@
 	devpriv->act_chanlist_len = seglen;
 	devpriv->act_chanlist_pos = 0;
 
-	for (i = 0; i < seglen; i++) {	// store range list to card
+	for (i = 0; i < seglen; i++) {	/*  store range list to card */
 		devpriv->act_chanlist[i] = CR_CHAN(chanlist[i]);
 		outb(muxonechan[CR_CHAN(chanlist[i])], dev->iobase + PCL818_MUX);	/* select channel */
 		outb(CR_RANGE(chanlist[i]), dev->iobase + PCL818_RANGE);	/* select gain */
 	}
 
-	comedi_udelay(1);
+	udelay(1);
 
 	/* select channel interval to scan */
 	outb(devpriv->act_chanlist[0] | (devpriv->act_chanlist[seglen -
@@ -1255,8 +1267,8 @@
 /*
 ==============================================================================
 */
-static int ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp, divisor1, divisor2;
@@ -1391,7 +1403,7 @@
 	if (cmd->chanlist) {
 		if (!check_channel_list(dev, s, cmd->chanlist,
 				cmd->chanlist_len))
-			return 5;	// incorrect channels list
+			return 5;	/*  incorrect channels list */
 	}
 
 	return 0;
@@ -1400,12 +1412,12 @@
 /*
 ==============================================================================
 */
-static int ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	int retval;
 
-	rt_printk("pcl818_ai_cmd()\n");
+	printk("pcl818_ai_cmd()\n");
 	devpriv->ai_n_chan = cmd->chanlist_len;
 	devpriv->ai_chanlist = cmd->chanlist;
 	devpriv->ai_flags = cmd->flags;
@@ -1420,14 +1432,14 @@
 		devpriv->ai_scans = 0;
 	}
 
-	if (cmd->scan_begin_src == TRIG_FOLLOW) {	// mode 1, 3
-		if (cmd->convert_src == TRIG_TIMER) {	// mode 1
+	if (cmd->scan_begin_src == TRIG_FOLLOW) {	/*  mode 1, 3 */
+		if (cmd->convert_src == TRIG_TIMER) {	/*  mode 1 */
 			devpriv->ai_timer1 = cmd->convert_arg;
 			retval = pcl818_ai_cmd_mode(1, dev, s);
-			rt_printk("pcl818_ai_cmd() end\n");
+			printk("pcl818_ai_cmd() end\n");
 			return retval;
 		}
-		if (cmd->convert_src == TRIG_EXT) {	// mode 3
+		if (cmd->convert_src == TRIG_EXT) {	/*  mode 3 */
 			return pcl818_ai_cmd_mode(3, dev, s);
 		}
 	}
@@ -1439,23 +1451,24 @@
 ==============================================================================
  cancel any mode 1-4 AI
 */
-static int pcl818_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcl818_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	if (devpriv->irq_blocked > 0) {
-		rt_printk("pcl818_ai_cancel()\n");
-		devpriv->irq_was_now_closed = devpriv->ai_mode;
-		devpriv->ai_mode = 0;
+		printk("pcl818_ai_cancel()\n");
+		devpriv->irq_was_now_closed = 1;
 
-		switch (devpriv->irq_was_now_closed) {
+		switch (devpriv->ai_mode) {
 #ifdef unused
 		case INT_TYPE_AI1_DMA_RTC:
 		case INT_TYPE_AI3_DMA_RTC:
-			set_rtc_irq_bit(0);	// stop RTC
+			set_rtc_irq_bit(0);	/*  stop RTC */
 			del_timer(&devpriv->rtc_irq_timer);
 #endif
 		case INT_TYPE_AI1_DMA:
 		case INT_TYPE_AI3_DMA:
-			if (devpriv->neverending_ai) {
+			if (devpriv->neverending_ai ||
+					(!devpriv->neverending_ai &&
+					 devpriv->ai_act_scan > 0)) {
 				/* wait for running dma transfer to end, do cleanup in interrupt */
 				goto end;
 			}
@@ -1469,14 +1482,14 @@
 		case INT_TYPE_AO3_INT:
 #endif
 			outb(inb(dev->iobase + PCL818_CONTROL) & 0x73, dev->iobase + PCL818_CONTROL);	/* Stop A/D */
-			comedi_udelay(1);
+			udelay(1);
 			start_pacer(dev, -1, 0, 0);
 			outb(0, dev->iobase + PCL818_AD_LO);
 			inb(dev->iobase + PCL818_AD_LO);
 			inb(dev->iobase + PCL818_AD_HI);
 			outb(0, dev->iobase + PCL818_CLRINT);	/* clear INT request */
 			outb(0, dev->iobase + PCL818_CONTROL);	/* Stop A/D */
-			if (devpriv->usefifo) {	// FIFO shutdown
+			if (devpriv->usefifo) {	/*  FIFO shutdown */
 				outb(0, dev->iobase + PCL818_FI_INTCLR);
 				outb(0, dev->iobase + PCL818_FI_FLUSH);
 				outb(0, dev->iobase + PCL818_FI_ENABLE);
@@ -1484,12 +1497,14 @@
 			devpriv->irq_blocked = 0;
 			devpriv->last_int_sub = s;
 			devpriv->neverending_ai = 0;
+			devpriv->ai_mode = 0;
+			devpriv->irq_was_now_closed = 0;
 			break;
 		}
 	}
 
       end:
-	rt_printk("pcl818_ai_cancel() end\n");
+	printk("pcl818_ai_cancel() end\n");
 	return 0;
 }
 
@@ -1500,39 +1515,39 @@
 static int pcl818_check(unsigned long iobase)
 {
 	outb(0x00, iobase + PCL818_MUX);
-	comedi_udelay(1);
+	udelay(1);
 	if (inb(iobase + PCL818_MUX) != 0x00)
-		return 1;	//there isn't card
+		return 1;	/* there isn't card */
 	outb(0x55, iobase + PCL818_MUX);
-	comedi_udelay(1);
+	udelay(1);
 	if (inb(iobase + PCL818_MUX) != 0x55)
-		return 1;	//there isn't card
+		return 1;	/* there isn't card */
 	outb(0x00, iobase + PCL818_MUX);
-	comedi_udelay(1);
+	udelay(1);
 	outb(0x18, iobase + PCL818_CONTROL);
-	comedi_udelay(1);
+	udelay(1);
 	if (inb(iobase + PCL818_CONTROL) != 0x18)
-		return 1;	//there isn't card
-	return 0;		// ok, card exist
+		return 1;	/* there isn't card */
+	return 0;		/*  ok, card exist */
 }
 
 /*
 ==============================================================================
  reset whole PCL-818 cards
 */
-static void pcl818_reset(struct comedi_device * dev)
+static void pcl818_reset(struct comedi_device *dev)
 {
-	if (devpriv->usefifo) {	// FIFO shutdown
+	if (devpriv->usefifo) {	/*  FIFO shutdown */
 		outb(0, dev->iobase + PCL818_FI_INTCLR);
 		outb(0, dev->iobase + PCL818_FI_FLUSH);
 		outb(0, dev->iobase + PCL818_FI_ENABLE);
 	}
-	outb(0, dev->iobase + PCL818_DA_LO);	// DAC=0V
+	outb(0, dev->iobase + PCL818_DA_LO);	/*  DAC=0V */
 	outb(0, dev->iobase + PCL818_DA_HI);
-	comedi_udelay(1);
-	outb(0, dev->iobase + PCL818_DO_HI);	// DO=$0000
+	udelay(1);
+	outb(0, dev->iobase + PCL818_DO_HI);	/*  DO=$0000 */
 	outb(0, dev->iobase + PCL818_DO_LO);
-	comedi_udelay(1);
+	udelay(1);
 	outb(0, dev->iobase + PCL818_CONTROL);
 	outb(0, dev->iobase + PCL818_CNTENABLE);
 	outb(0, dev->iobase + PCL818_MUX);
@@ -1641,9 +1656,9 @@
 ==============================================================================
   Free any resources that we have claimed
 */
-static void free_resources(struct comedi_device * dev)
+static void free_resources(struct comedi_device *dev)
 {
-	//rt_printk("free_resource()\n");
+	/* printk("free_resource()\n"); */
 	if (dev->private) {
 		pcl818_ai_cancel(dev, devpriv->sub_ai);
 		pcl818_reset(dev);
@@ -1655,7 +1670,7 @@
 			free_pages(devpriv->dmabuf[1], devpriv->dmapages[1]);
 #ifdef unused
 		if (devpriv->rtc_irq)
-			comedi_free_irq(devpriv->rtc_irq, dev);
+			free_irq(devpriv->rtc_irq, dev);
 		if ((devpriv->dma_rtc) && (RTC_lock == 1)) {
 			if (devpriv->rtc_iobase)
 				release_region(devpriv->rtc_iobase,
@@ -1670,7 +1685,7 @@
 		free_irq(dev->irq, dev);
 	if (dev->iobase)
 		release_region(dev->iobase, devpriv->io_range);
-	//rt_printk("free_resource() end\n");
+	/* printk("free_resource() end\n"); */
 }
 
 /*
@@ -1679,15 +1694,17 @@
    Initialization
 
 */
-static int pcl818_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcl818_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int ret;
 	unsigned long iobase;
-	unsigned int irq, dma;
+	unsigned int irq;
+	int dma;
 	unsigned long pages;
 	struct comedi_subdevice *s;
 
-	if ((ret = alloc_private(dev, sizeof(struct pcl818_private))) < 0)
+	ret = alloc_private(dev, sizeof(struct pcl818_private));
+	if (ret < 0)
 		return ret;	/* Can't alloc mem */
 
 	/* claim our I/O space */
@@ -1695,19 +1712,19 @@
 	printk("comedi%d: pcl818:  board=%s, ioport=0x%03lx",
 		dev->minor, this_board->name, iobase);
 	devpriv->io_range = this_board->io_range;
-	if ((this_board->fifo) && (it->options[2] == -1)) {	// we've board with FIFO and we want to use FIFO
+	if ((this_board->fifo) && (it->options[2] == -1)) {	/*  we've board with FIFO and we want to use FIFO */
 		devpriv->io_range = PCLx1xFIFO_RANGE;
 		devpriv->usefifo = 1;
 	}
 	if (!request_region(iobase, devpriv->io_range, "pcl818")) {
-		rt_printk("I/O port conflict\n");
+		printk("I/O port conflict\n");
 		return -EIO;
 	}
 
 	dev->iobase = iobase;
 
 	if (pcl818_check(iobase)) {
-		rt_printk(", I can't detect board. FAIL!\n");
+		printk(", I can't detect board. FAIL!\n");
 		return -EIO;
 	}
 
@@ -1719,19 +1736,18 @@
 		irq = it->options[1];
 		if (irq) {	/* we want to use IRQ */
 			if (((1 << irq) & this_board->IRQbits) == 0) {
-				rt_printk
+				printk
 					(", IRQ %u is out of allowed range, DISABLING IT",
 					irq);
 				irq = 0;	/* Bad IRQ */
 			} else {
-				if (comedi_request_irq(irq, interrupt_pcl818, 0,
-						"pcl818", dev)) {
-					rt_printk
+				if (request_irq(irq, interrupt_pcl818, 0, "pcl818", dev)) {
+					printk
 						(", unable to allocate IRQ %u, DISABLING IT",
 						irq);
 					irq = 0;	/* Can't use IRQ */
 				} else {
-					rt_printk(", irq=%u", irq);
+					printk(", irq=%u", irq);
 				}
 			}
 		}
@@ -1750,7 +1766,7 @@
 #ifdef unused
 	/* grab RTC for DMA operations */
 	devpriv->dma_rtc = 0;
-	if (it->options[2] > 0) {	// we want to use DMA
+	if (it->options[2] > 0) {	/*  we want to use DMA */
 		if (RTC_lock == 0) {
 			if (!request_region(RTC_PORT(0), RTC_IO_EXTENT,
 					"pcl818 (RTC)"))
@@ -1759,12 +1775,11 @@
 		devpriv->rtc_iobase = RTC_PORT(0);
 		devpriv->rtc_iosize = RTC_IO_EXTENT;
 		RTC_lock++;
-		if (!comedi_request_irq(RTC_IRQ,
-				interrupt_pcl818_ai_mode13_dma_rtc, 0,
+		if (!request_irq(RTC_IRQ, interrupt_pcl818_ai_mode13_dma_rtc, 0,
 				"pcl818 DMA (RTC)", dev)) {
 			devpriv->dma_rtc = 1;
 			devpriv->rtc_irq = RTC_IRQ;
-			rt_printk(", dma_irq=%u", devpriv->rtc_irq);
+			printk(", dma_irq=%u", devpriv->rtc_irq);
 		} else {
 			RTC_lock--;
 			if (RTC_lock == 0) {
@@ -1789,31 +1804,31 @@
 		if (dma < 1)
 			goto no_dma;	/* DMA disabled */
 		if (((1 << dma) & this_board->DMAbits) == 0) {
-			rt_printk(", DMA is out of allowed range, FAIL!\n");
+			printk(", DMA is out of allowed range, FAIL!\n");
 			return -EINVAL;	/* Bad DMA */
 		}
 		ret = request_dma(dma, "pcl818");
 		if (ret) {
-			rt_printk(", unable to allocate DMA %u, FAIL!\n", dma);
+			printk(", unable to allocate DMA %u, FAIL!\n", dma);
 			return -EBUSY;	/* DMA isn't free */
 		}
 		devpriv->dma = dma;
-		rt_printk(", dma=%u", dma);
+		printk(", dma=%u", dma);
 		pages = 2;	/* we need 16KB */
 		devpriv->dmabuf[0] = __get_dma_pages(GFP_KERNEL, pages);
 		if (!devpriv->dmabuf[0]) {
-			rt_printk(", unable to allocate DMA buffer, FAIL!\n");
+			printk(", unable to allocate DMA buffer, FAIL!\n");
 			/* maybe experiment with try_to_free_pages() will help .... */
 			return -EBUSY;	/* no buffer :-( */
 		}
 		devpriv->dmapages[0] = pages;
 		devpriv->hwdmaptr[0] = virt_to_bus((void *)devpriv->dmabuf[0]);
 		devpriv->hwdmasize[0] = (1 << pages) * PAGE_SIZE;
-		//rt_printk("%d %d %ld, ",devpriv->dmapages[0],devpriv->hwdmasize[0],PAGE_SIZE);
-		if (devpriv->dma_rtc == 0) {	// we must do duble buff :-(
+		/* printk("%d %d %ld, ",devpriv->dmapages[0],devpriv->hwdmasize[0],PAGE_SIZE); */
+		if (devpriv->dma_rtc == 0) {	/*  we must do duble buff :-( */
 			devpriv->dmabuf[1] = __get_dma_pages(GFP_KERNEL, pages);
 			if (!devpriv->dmabuf[1]) {
-				rt_printk
+				printk
 					(", unable to allocate DMA buffer, FAIL!\n");
 				return -EBUSY;
 			}
@@ -1826,7 +1841,8 @@
 
       no_dma:
 
-	if ((ret = alloc_subdevices(dev, 4)) < 0)
+	ret = alloc_subdevices(dev, 4);
+	if (ret < 0)
 		return ret;
 
 	s = dev->subdevices + 0;
@@ -1858,7 +1874,7 @@
 		}
 		if (this_board->is_818) {
 			if ((it->options[4] == 1) || (it->options[4] == 10))
-				s->range_table = &range_pcl818l_h_ai;	// secondary range list jumper selectable
+				s->range_table = &range_pcl818l_h_ai;	/*  secondary range list jumper selectable */
 		} else {
 			switch (it->options[4]) {
 			case 0:
@@ -1971,7 +1987,7 @@
 
 	pcl818_reset(dev);
 
-	rt_printk("\n");
+	printk("\n");
 
 	return 0;
 }
@@ -1980,9 +1996,9 @@
 ==============================================================================
   Removes device
  */
-static int pcl818_detach(struct comedi_device * dev)
+static int pcl818_detach(struct comedi_device *dev)
 {
-	//  rt_printk("comedi%d: pcl818: remove\n", dev->minor);
+	/*   printk("comedi%d: pcl818: remove\n", dev->minor); */
 	free_resources(dev);
 	return 0;
 }
diff --git a/drivers/staging/comedi/drivers/pcm3724.c b/drivers/staging/comedi/drivers/pcm3724.c
index a3ed3a0..a5d6b1d 100644
--- a/drivers/staging/comedi/drivers/pcm3724.c
+++ b/drivers/staging/comedi/drivers/pcm3724.c
@@ -62,18 +62,18 @@
 #define CR_A_MODE(a)	((a)<<5)
 #define CR_CW		0x80
 
-static int pcm3724_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcm3724_detach(struct comedi_device * dev);
+static int pcm3724_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcm3724_detach(struct comedi_device *dev);
 
 struct pcm3724_board {
-	const char *name;	// driver name
-	int dio;		// num of DIO
-	int numofports;		// num of 8255 subdevices
-	unsigned int IRQbits;	// allowed interrupts
-	unsigned int io_range;	// len of IO space
+	const char *name;	/*  driver name */
+	int dio;		/*  num of DIO */
+	int numofports;		/*  num of 8255 subdevices */
+	unsigned int IRQbits;	/*  allowed interrupts */
+	unsigned int io_range;	/*  len of IO space */
 };
 
-//used to track configured dios
+/* used to track configured dios */
 struct priv_pcm3724 {
 	int dio_1;
 	int dio_2;
@@ -87,36 +87,36 @@
 #define this_board ((const struct pcm3724_board *)dev->board_ptr)
 
 static struct comedi_driver driver_pcm3724 = {
-      driver_name:"pcm3724",
-      module:THIS_MODULE,
-      attach:pcm3724_attach,
-      detach:pcm3724_detach,
-      board_name:&boardtypes[0].name,
-      num_names:n_boardtypes,
-      offset:sizeof(struct pcm3724_board),
+	.driver_name = "pcm3724",
+	.module = THIS_MODULE,
+	.attach = pcm3724_attach,
+	.detach = pcm3724_detach,
+	.board_name = &boardtypes[0].name,
+	.num_names = n_boardtypes,
+	.offset = sizeof(struct pcm3724_board),
 };
 
 COMEDI_INITCLEANUP(driver_pcm3724);
 
-//          (setq c-basic-offset 8)
+/* (setq c-basic-offset 8) */
 
 static int subdev_8255_cb(int dir, int port, int data, unsigned long arg)
 {
 	unsigned long iobase = arg;
 	unsigned char inbres;
-	//printk("8255cb %d %d %d %lx\n", dir,port,data,arg);
+	/* printk("8255cb %d %d %d %lx\n", dir,port,data,arg); */
 	if (dir) {
-		//printk("8255 cb   outb(%x, %lx)\n", data, iobase+port);
+		/* printk("8255 cb   outb(%x, %lx)\n", data, iobase+port); */
 		outb(data, iobase + port);
 		return 0;
 	} else {
 		inbres = inb(iobase + port);
-		//printk("8255 cb   inb(%lx) = %x\n", iobase+port, inbres);
+		/* printk("8255 cb   inb(%lx) = %x\n", iobase+port, inbres); */
 		return inbres;
 	}
 }
 
-static int compute_buffer(int config, int devno, struct comedi_subdevice * s)
+static int compute_buffer(int config, int devno, struct comedi_subdevice *s)
 {
 	/* 1 in io_bits indicates output */
 	if (s->io_bits & 0x0000ff) {
@@ -143,7 +143,7 @@
 	return config;
 }
 
-static void do_3724_config(struct comedi_device * dev, struct comedi_subdevice * s,
+static void do_3724_config(struct comedi_device *dev, struct comedi_subdevice *s,
 	int chanspec)
 {
 	int config;
@@ -173,11 +173,11 @@
 		port_8255_cfg = dev->iobase + SIZE_8255 + _8255_CR;
 	}
 	outb(buffer_config, dev->iobase + 8);	/* update buffer register */
-	//printk("pcm3724 buffer_config (%lx) %d, %x\n", dev->iobase + _8255_CR, chanspec, buffer_config);
+	/* printk("pcm3724 buffer_config (%lx) %d, %x\n", dev->iobase + _8255_CR, chanspec, buffer_config); */
 	outb(config, port_8255_cfg);
 }
 
-static void enable_chan(struct comedi_device * dev, struct comedi_subdevice * s, int chanspec)
+static void enable_chan(struct comedi_device *dev, struct comedi_subdevice *s, int chanspec)
 {
 	unsigned int mask;
 	int gatecfg;
@@ -187,9 +187,9 @@
 	priv = (struct priv_pcm3724 *) (dev->private);
 
 	mask = 1 << CR_CHAN(chanspec);
-	if (s == dev->subdevices) {	// subdev 0
+	if (s == dev->subdevices) {	/*  subdev 0 */
 		priv->dio_1 |= mask;
-	} else {		//subdev 1
+	} else {		/* subdev 1 */
 		priv->dio_2 |= mask;
 	}
 	if (priv->dio_1 & 0xff0000) {
@@ -210,13 +210,13 @@
 	if (priv->dio_2 & 0xff) {
 		gatecfg |= GATE_A1;
 	}
-	//      printk("gate control %x\n", gatecfg);
+	/*       printk("gate control %x\n", gatecfg); */
 	outb(gatecfg, dev->iobase + 9);
 }
 
 /* overriding the 8255 insn config */
-static int subdev_3724_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int subdev_3724_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	unsigned int mask;
 	unsigned int bits;
@@ -252,7 +252,7 @@
 	return 1;
 }
 
-static int pcm3724_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcm3724_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	unsigned long iobase;
 	unsigned int iorange;
@@ -260,7 +260,9 @@
 
 	iobase = it->options[0];
 	iorange = this_board->io_range;
-	if ((ret = alloc_private(dev, sizeof(struct priv_pcm3724))) < 0)
+
+	ret = alloc_private(dev, sizeof(struct priv_pcm3724));
+	if (ret < 0)
 		return -ENOMEM;
 
 	((struct priv_pcm3724 *) (dev->private))->dio_1 = 0;
@@ -279,7 +281,8 @@
 
 	n_subdevices = this_board->numofports;
 
-	if ((ret = alloc_subdevices(dev, n_subdevices)) < 0)
+	ret = alloc_subdevices(dev, n_subdevices);
+	if (ret < 0)
 		return ret;
 
 	for (i = 0; i < dev->n_subdevices; i++) {
@@ -290,7 +293,7 @@
 	return 0;
 }
 
-static int pcm3724_detach(struct comedi_device * dev)
+static int pcm3724_detach(struct comedi_device *dev)
 {
 	int i;
 
diff --git a/drivers/staging/comedi/drivers/pcm3730.c b/drivers/staging/comedi/drivers/pcm3730.c
index 1de555f..ae90ea4 100644
--- a/drivers/staging/comedi/drivers/pcm3730.c
+++ b/drivers/staging/comedi/drivers/pcm3730.c
@@ -19,28 +19,28 @@
 
 #include <linux/ioport.h>
 
-#define PCM3730_SIZE 4		// consecutive io port addresses
+#define PCM3730_SIZE 4		/*  consecutive io port addresses */
 
-#define PCM3730_DOA 0		// offsets for each port
+#define PCM3730_DOA 0		/*  offsets for each port */
 #define PCM3730_DOB 2
 #define PCM3730_DOC 3
 #define PCM3730_DIA 0
 #define PCM3730_DIB 2
 #define PCM3730_DIC 3
 
-static int pcm3730_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcm3730_detach(struct comedi_device * dev);
+static int pcm3730_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcm3730_detach(struct comedi_device *dev);
 static struct comedi_driver driver_pcm3730 = {
-      driver_name:"pcm3730",
-      module:THIS_MODULE,
-      attach:pcm3730_attach,
-      detach:pcm3730_detach,
+	.driver_name = "pcm3730",
+	.module = THIS_MODULE,
+	.attach = pcm3730_attach,
+	.detach = pcm3730_detach,
 };
 
 COMEDI_INITCLEANUP(driver_pcm3730);
 
-static int pcm3730_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcm3730_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -54,8 +54,8 @@
 	return 2;
 }
 
-static int pcm3730_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcm3730_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -63,7 +63,7 @@
 	return 2;
 }
 
-static int pcm3730_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcm3730_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase;
@@ -141,7 +141,7 @@
 	return 0;
 }
 
-static int pcm3730_detach(struct comedi_device * dev)
+static int pcm3730_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: pcm3730: remove\n", dev->minor);
 
diff --git a/drivers/staging/comedi/drivers/pcm_common.c b/drivers/staging/comedi/drivers/pcm_common.c
new file mode 100644
index 0000000..ebd9838
--- /dev/null
+++ b/drivers/staging/comedi/drivers/pcm_common.c
@@ -0,0 +1,111 @@
+#include "../comedidev.h"
+#include "pcm_common.h"
+
+/*
+ * 'do_cmdtest' function for an 'INTERRUPT' subdevice.  This is for
+ * the PCM drivers.
+ */
+int comedi_pcm_cmdtest(struct comedi_device *dev,
+		       struct comedi_subdevice *s, struct comedi_cmd *cmd)
+{
+	int err = 0;
+	unsigned int tmp;
+
+	/* step 1: make sure trigger sources are trivially valid */
+
+	tmp = cmd->start_src;
+	cmd->start_src &= (TRIG_NOW | TRIG_INT);
+	if (!cmd->start_src || tmp != cmd->start_src)
+		err++;
+
+	tmp = cmd->scan_begin_src;
+	cmd->scan_begin_src &= TRIG_EXT;
+	if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
+		err++;
+
+	tmp = cmd->convert_src;
+	cmd->convert_src &= TRIG_NOW;
+	if (!cmd->convert_src || tmp != cmd->convert_src)
+		err++;
+
+	tmp = cmd->scan_end_src;
+	cmd->scan_end_src &= TRIG_COUNT;
+	if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
+		err++;
+
+	tmp = cmd->stop_src;
+	cmd->stop_src &= (TRIG_COUNT | TRIG_NONE);
+	if (!cmd->stop_src || tmp != cmd->stop_src)
+		err++;
+
+	if (err)
+		return 1;
+
+	/* step 2: make sure trigger sources are unique and mutually compatible */
+
+	/* these tests are true if more than one _src bit is set */
+	if ((cmd->start_src & (cmd->start_src - 1)) != 0)
+		err++;
+	if ((cmd->scan_begin_src & (cmd->scan_begin_src - 1)) != 0)
+		err++;
+	if ((cmd->convert_src & (cmd->convert_src - 1)) != 0)
+		err++;
+	if ((cmd->scan_end_src & (cmd->scan_end_src - 1)) != 0)
+		err++;
+	if ((cmd->stop_src & (cmd->stop_src - 1)) != 0)
+		err++;
+
+	if (err)
+		return 2;
+
+	/* step 3: make sure arguments are trivially compatible */
+
+	/* cmd->start_src == TRIG_NOW || cmd->start_src == TRIG_INT */
+	if (cmd->start_arg != 0) {
+		cmd->start_arg = 0;
+		err++;
+	}
+
+	/* cmd->scan_begin_src == TRIG_EXT */
+	if (cmd->scan_begin_arg != 0) {
+		cmd->scan_begin_arg = 0;
+		err++;
+	}
+
+	/* cmd->convert_src == TRIG_NOW */
+	if (cmd->convert_arg != 0) {
+		cmd->convert_arg = 0;
+		err++;
+	}
+
+	/* cmd->scan_end_src == TRIG_COUNT */
+	if (cmd->scan_end_arg != cmd->chanlist_len) {
+		cmd->scan_end_arg = cmd->chanlist_len;
+		err++;
+	}
+
+	switch (cmd->stop_src) {
+	case TRIG_COUNT:
+		/* any count allowed */
+		break;
+	case TRIG_NONE:
+		if (cmd->stop_arg != 0) {
+			cmd->stop_arg = 0;
+			err++;
+		}
+		break;
+	default:
+		break;
+	}
+
+	if (err)
+		return 3;
+
+	/* step 4: fix up any arguments */
+
+	/* if (err) return 4; */
+
+	return 0;
+}
+
+EXPORT_SYMBOL(comedi_pcm_cmdtest);
diff --git a/drivers/staging/comedi/drivers/pcm_common.h b/drivers/staging/comedi/drivers/pcm_common.h
new file mode 100644
index 0000000..cd4840c
--- /dev/null
+++ b/drivers/staging/comedi/drivers/pcm_common.h
@@ -0,0 +1,8 @@
+#ifndef _comedi_common_H
+#define _comedi_common_H
+
+extern int comedi_pcm_cmdtest(struct comedi_device *dev,
+			      struct comedi_subdevice *s,
+			      struct comedi_cmd *cmd);
+
+#endif
diff --git a/drivers/staging/comedi/drivers/pcmad.c b/drivers/staging/comedi/drivers/pcmad.c
index fc2a73d..9bb2669 100644
--- a/drivers/staging/comedi/drivers/pcmad.c
+++ b/drivers/staging/comedi/drivers/pcmad.c
@@ -41,6 +41,7 @@
           1 = two's complement
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -58,12 +59,12 @@
 };
 static const struct pcmad_board_struct pcmad_boards[] = {
 	{
-	      name:	"pcmad12",
-	      n_ai_bits:12,
+	.name = "pcmad12",
+	.n_ai_bits = 12,
 		},
 	{
-	      name:	"pcmad16",
-	      n_ai_bits:16,
+	.name = "pcmad16",
+	.n_ai_bits = 16,
 		},
 };
 
@@ -76,24 +77,24 @@
 };
 #define devpriv ((struct pcmad_priv_struct *)dev->private)
 
-static int pcmad_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcmad_detach(struct comedi_device * dev);
+static int pcmad_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcmad_detach(struct comedi_device *dev);
 static struct comedi_driver driver_pcmad = {
-      driver_name:"pcmad",
-      module:THIS_MODULE,
-      attach:pcmad_attach,
-      detach:pcmad_detach,
-      board_name:&pcmad_boards[0].name,
-      num_names:n_pcmad_boards,
-      offset:sizeof(pcmad_boards[0]),
+	.driver_name = "pcmad",
+	.module = THIS_MODULE,
+	.attach = pcmad_attach,
+	.detach = pcmad_detach,
+	.board_name = &pcmad_boards[0].name,
+	.num_names = n_pcmad_boards,
+	.offset = sizeof(pcmad_boards[0]),
 };
 
 COMEDI_INITCLEANUP(driver_pcmad);
 
 #define TIMEOUT	100
 
-static int pcmad_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcmad_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan;
@@ -126,7 +127,7 @@
  * 2	0=single ended 1=differential
  * 3	0=straight binary 1=two's comp
  */
-static int pcmad_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcmad_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int ret;
 	struct comedi_subdevice *s;
@@ -140,9 +141,12 @@
 	}
 	dev->iobase = iobase;
 
-	if ((ret = alloc_subdevices(dev, 1)) < 0)
+	ret = alloc_subdevices(dev, 1);
+	if (ret < 0)
 		return ret;
-	if ((ret = alloc_private(dev, sizeof(struct pcmad_priv_struct))) < 0)
+
+	ret = alloc_private(dev, sizeof(struct pcmad_priv_struct));
+	if (ret < 0)
 		return ret;
 
 	dev->board_name = this_board->name;
@@ -159,7 +163,7 @@
 	return 0;
 }
 
-static int pcmad_detach(struct comedi_device * dev)
+static int pcmad_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: pcmad: remove\n", dev->minor);
 
diff --git a/drivers/staging/comedi/drivers/pcmda12.c b/drivers/staging/comedi/drivers/pcmda12.c
index 2a1ff46..6e172a6 100644
--- a/drivers/staging/comedi/drivers/pcmda12.c
+++ b/drivers/staging/comedi/drivers/pcmda12.c
@@ -55,7 +55,6 @@
 
 #include <linux/pci.h>		/* for PCI devices */
 
-#define MIN(a,b) ( ((a) < (b)) ? (a) : (b) )
 #define SDEV_NO ((int)(s - dev->subdevices))
 #define CHANS 8
 #define IOSIZE 16
@@ -83,7 +82,7 @@
 
 static const struct pcmda12_board pcmda12_boards[] = {
 	{
-	      name:	"pcmda12",
+	.name = "pcmda12",
 		},
 };
 
@@ -107,16 +106,16 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int pcmda12_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcmda12_detach(struct comedi_device * dev);
+static int pcmda12_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcmda12_detach(struct comedi_device *dev);
 
-static void zero_chans(struct comedi_device * dev);
+static void zero_chans(struct comedi_device *dev);
 
 static struct comedi_driver driver = {
-      driver_name:"pcmda12",
-      module:THIS_MODULE,
-      attach:pcmda12_attach,
-      detach:pcmda12_detach,
+	.driver_name = "pcmda12",
+	.module = THIS_MODULE,
+	.attach = pcmda12_attach,
+	.detach = pcmda12_detach,
 /* It is not necessary to implement the following members if you are
  * writing a driver for a ISA PnP or PCI card */
 	/* Most drivers will support multiple types of boards by
@@ -135,15 +134,15 @@
 	 * the type of board in software.  ISA PnP, PCI, and PCMCIA
 	 * devices are such boards.
 	 */
-      board_name:&pcmda12_boards[0].name,
-      offset:sizeof(struct pcmda12_board),
-      num_names:sizeof(pcmda12_boards) / sizeof(struct pcmda12_board),
+	.board_name = &pcmda12_boards[0].name,
+	.offset = sizeof(struct pcmda12_board),
+	.num_names = ARRAY_SIZE(pcmda12_boards),
 };
 
-static int ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 /*
  * Attach is called by the Comedi core to configure the driver
@@ -151,7 +150,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int pcmda12_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcmda12_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase;
@@ -220,7 +219,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int pcmda12_detach(struct comedi_device * dev)
+static int pcmda12_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: %s: remove\n", dev->minor, driver.driver_name);
 	if (dev->iobase)
@@ -228,7 +227,7 @@
 	return 0;
 }
 
-static void zero_chans(struct comedi_device * dev)
+static void zero_chans(struct comedi_device *dev)
 {				/* sets up an
 				   ASIC chip to defaults */
 	int i;
@@ -241,8 +240,8 @@
 	inb(LSB_PORT(0));	/* update chans. */
 }
 
-static int ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -283,8 +282,8 @@
    DAC outputs, which makes all AO channels update simultaneously.
    This is useful for some control applications, I would imagine.
 */
-static int ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
diff --git a/drivers/staging/comedi/drivers/pcmmio.c b/drivers/staging/comedi/drivers/pcmmio.c
index 01e40f1..cdf501a 100644
--- a/drivers/staging/comedi/drivers/pcmmio.c
+++ b/drivers/staging/comedi/drivers/pcmmio.c
@@ -73,11 +73,11 @@
   [1] - IRQ (optional -- for edge-detect interrupt support only, leave out if you don't need this feature)
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
+#include "pcm_common.h"
 #include <linux/pci.h>		/* for PCI devices */
 
-#define MIN(a,b) ( ((a) < (b)) ? (a) : (b) )
-
 /* This stuff is all from pcmuio.c -- it refers to the DIO subdevices only */
 #define CHANS_PER_PORT   8
 #define PORTS_PER_ASIC   6
@@ -179,19 +179,19 @@
 
 static const struct pcmmio_board pcmmio_boards[] = {
 	{
-	      name:	"pcmmio",
-	      dio_num_asics:1,
-	      dio_num_ports:6,
-	      total_iosize:32,
-	      ai_bits:	16,
-	      ao_bits:	16,
-	      n_ai_chans:16,
-	      n_ao_chans:8,
-	      ai_range_table:&ranges_ai,
-	      ao_range_table:&ranges_ao,
-	      ai_rinsn:ai_rinsn,
-	      ao_rinsn:ao_rinsn,
-      ao_winsn:ao_winsn},
+	.name = "pcmmio",
+	.dio_num_asics = 1,
+	.dio_num_ports = 6,
+	.total_iosize = 32,
+	.ai_bits = 16,
+	.ao_bits = 16,
+	.n_ai_chans = 16,
+	.n_ao_chans = 8,
+	.ai_range_table = &ranges_ai,
+	.ao_range_table = &ranges_ao,
+	.ai_rinsn = ai_rinsn,
+	.ao_rinsn = ao_rinsn,
+	.ao_winsn = ao_winsn},
 };
 
 /*
@@ -264,14 +264,14 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int pcmmio_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcmmio_detach(struct comedi_device * dev);
+static int pcmmio_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcmmio_detach(struct comedi_device *dev);
 
 static struct comedi_driver driver = {
-      driver_name:"pcmmio",
-      module:THIS_MODULE,
-      attach:pcmmio_attach,
-      detach:pcmmio_detach,
+	.driver_name = "pcmmio",
+	.module = THIS_MODULE,
+	.attach = pcmmio_attach,
+	.detach = pcmmio_detach,
 /* It is not necessary to implement the following members if you are
  * writing a driver for a ISA PnP or PCI card */
 	/* Most drivers will support multiple types of boards by
@@ -290,29 +290,29 @@
 	 * the type of board in software.  ISA PnP, PCI, and PCMCIA
 	 * devices are such boards.
 	 */
-      board_name:&pcmmio_boards[0].name,
-      offset:sizeof(struct pcmmio_board),
-      num_names:sizeof(pcmmio_boards) / sizeof(struct pcmmio_board),
+	.board_name = &pcmmio_boards[0].name,
+	.offset = sizeof(struct pcmmio_board),
+	.num_names = ARRAY_SIZE(pcmmio_boards),
 };
 
-static int pcmmio_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int pcmmio_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int pcmmio_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int pcmmio_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static irqreturn_t interrupt_pcmmio(int irq, void *d PT_REGS_ARG);
+static irqreturn_t interrupt_pcmmio(int irq, void *d);
 static void pcmmio_stop_intr(struct comedi_device *, struct comedi_subdevice *);
-static int pcmmio_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static int pcmmio_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int pcmmio_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
+static int pcmmio_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static int pcmmio_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int pcmmio_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
 
 /* some helper functions to deal with specifics of this device's registers */
-static void init_asics(struct comedi_device * dev);	/* sets up/clears ASIC chips to defaults */
-static void switch_page(struct comedi_device * dev, int asic, int page);
+static void init_asics(struct comedi_device *dev);	/* sets up/clears ASIC chips to defaults */
+static void switch_page(struct comedi_device *dev, int asic, int page);
 #ifdef notused
-static void lock_port(struct comedi_device * dev, int asic, int port);
-static void unlock_port(struct comedi_device * dev, int asic, int port);
+static void lock_port(struct comedi_device *dev, int asic, int port);
+static void unlock_port(struct comedi_device *dev, int asic, int port);
 #endif
 
 /*
@@ -321,7 +321,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int pcmmio_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcmmio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int sdev_no, chans_left, n_dio_subdevs, n_subdevs, port, asic,
@@ -364,7 +364,7 @@
 			dev->iobase + 16 + asic * ASIC_IOSIZE;
 		devpriv->asics[asic].irq = 0;	/* this gets actually set at the end of
 						   this function when we
-						   comedi_request_irqs */
+						   request_irqs */
 		spin_lock_init(&devpriv->asics[asic].spinlock);
 	}
 
@@ -435,7 +435,7 @@
 		s->type = COMEDI_SUBD_DIO;
 		s->insn_bits = pcmmio_dio_insn_bits;
 		s->insn_config = pcmmio_dio_insn_config;
-		s->n_chan = MIN(chans_left, MAX_CHANS_PER_SUBDEV);
+		s->n_chan = min(chans_left, MAX_CHANS_PER_SUBDEV);
 		subpriv->dio.intr.asic = -1;
 		subpriv->dio.intr.first_chan = -1;
 		subpriv->dio.intr.asic_chan = -1;
@@ -489,12 +489,12 @@
 
 	for (asic = 0; irq[0] && asic < MAX_ASICS; ++asic) {
 		if (irq[asic]
-			&& comedi_request_irq(irq[asic], interrupt_pcmmio,
+			&& request_irq(irq[asic], interrupt_pcmmio,
 				IRQF_SHARED, thisboard->name, dev)) {
 			int i;
 			/* unroll the allocated irqs.. */
 			for (i = asic - 1; i >= 0; --i) {
-				comedi_free_irq(irq[i], dev);
+				free_irq(irq[i], dev);
 				devpriv->asics[i].irq = irq[i] = 0;
 			}
 			irq[asic] = 0;
@@ -526,7 +526,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int pcmmio_detach(struct comedi_device * dev)
+static int pcmmio_detach(struct comedi_device *dev)
 {
 	int i;
 
@@ -536,7 +536,7 @@
 
 	for (i = 0; i < MAX_ASICS; ++i) {
 		if (devpriv && devpriv->asics[i].irq)
-			comedi_free_irq(devpriv->asics[i].irq, dev);
+			free_irq(devpriv->asics[i].irq, dev);
 	}
 
 	if (devpriv && devpriv->sprivs)
@@ -550,8 +550,8 @@
  * useful to applications if you implement the insn_bits interface.
  * This allows packed reading/writing of the DIO channels.  The
  * comedi core can convert between insn_bits and insn_read/write */
-static int pcmmio_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcmmio_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int byte_no;
 	if (insn->n != 2)
@@ -624,8 +624,8 @@
  * configured by a special insn_config instruction.  chanspec
  * contains the channel to be changed, and data[0] contains the
  * value COMEDI_INPUT or COMEDI_OUTPUT. */
-static int pcmmio_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcmmio_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec), byte_no = chan / 8, bit_no =
 		chan % 8;
@@ -685,7 +685,7 @@
 	return insn->n;
 }
 
-static void init_asics(struct comedi_device * dev)
+static void init_asics(struct comedi_device *dev)
 {				/* sets up an
 				   ASIC chip to defaults */
 	int asic;
@@ -722,7 +722,7 @@
 	}
 }
 
-static void switch_page(struct comedi_device * dev, int asic, int page)
+static void switch_page(struct comedi_device *dev, int asic, int page)
 {
 	if (asic < 0 || asic >= thisboard->dio_num_asics)
 		return;		/* paranoia */
@@ -738,7 +738,7 @@
 }
 
 #ifdef notused
-static void lock_port(struct comedi_device * dev, int asic, int port)
+static void lock_port(struct comedi_device *dev, int asic, int port)
 {
 	if (asic < 0 || asic >= thisboard->dio_num_asics)
 		return;		/* paranoia */
@@ -752,7 +752,7 @@
 	return;
 }
 
-static void unlock_port(struct comedi_device * dev, int asic, int port)
+static void unlock_port(struct comedi_device *dev, int asic, int port)
 {
 	if (asic < 0 || asic >= thisboard->dio_num_asics)
 		return;		/* paranoia */
@@ -765,7 +765,7 @@
 }
 #endif /* notused */
 
-static irqreturn_t interrupt_pcmmio(int irq, void *d PT_REGS_ARG)
+static irqreturn_t interrupt_pcmmio(int irq, void *d)
 {
 	int asic, got1 = 0;
 	struct comedi_device *dev = (struct comedi_device *) d;
@@ -778,8 +778,7 @@
 			/* it is an interrupt for ASIC #asic */
 			unsigned char int_pend;
 
-			comedi_spin_lock_irqsave(&devpriv->asics[asic].spinlock,
-				flags);
+			spin_lock_irqsave(&devpriv->asics[asic].spinlock, flags);
 
 			int_pend = inb(iobase + REG_INT_PENDING) & 0x07;
 
@@ -811,8 +810,7 @@
 				++got1;
 			}
 
-			comedi_spin_unlock_irqrestore(&devpriv->asics[asic].
-				spinlock, flags);
+			spin_unlock_irqrestore(&devpriv->asics[asic].  spinlock, flags);
 
 			if (triggered) {
 				struct comedi_subdevice *s;
@@ -825,9 +823,7 @@
 						unsigned long flags;
 						unsigned oldevents;
 
-						comedi_spin_lock_irqsave
-							(&subpriv->dio.intr.
-							spinlock, flags);
+						spin_lock_irqsave(&subpriv->dio.intr.spinlock, flags);
 
 						oldevents = s->async->events;
 
@@ -859,10 +855,10 @@
 									}
 								}
 								/* Write the scan to the buffer. */
-								if (comedi_buf_put(s->async, ((short *) & val)[0])
+								if (comedi_buf_put(s->async, ((short *) &val)[0])
 									&&
 									comedi_buf_put
-									(s->async, ((short *) & val)[1])) {
+									(s->async, ((short *) &val)[1])) {
 									s->async->events |= (COMEDI_CB_BLOCK | COMEDI_CB_EOS);
 								} else {
 									/* Overflow! Stop acquisition!! */
@@ -896,9 +892,7 @@
 							}
 						}
 
-						comedi_spin_unlock_irqrestore
-							(&subpriv->dio.intr.
-							spinlock, flags);
+						spin_unlock_irqrestore(&subpriv->dio.intr.spinlock, flags);
 
 						if (oldevents !=
 							s->async->events) {
@@ -917,11 +911,12 @@
 	return IRQ_HANDLED;
 }
 
-static void pcmmio_stop_intr(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pcmmio_stop_intr(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int nports, firstport, asic, port;
 
-	if ((asic = subpriv->dio.intr.asic) < 0)
+	asic = subpriv->dio.intr.asic;
+	if (asic < 0)
 		return;		/* not an interrupt subdev */
 
 	subpriv->dio.intr.enabled_mask = 0;
@@ -936,7 +931,7 @@
 	}
 }
 
-static int pcmmio_start_intr(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcmmio_start_intr(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	if (!subpriv->dio.intr.continuous && subpriv->dio.intr.stop_count == 0) {
 		/* An empty acquisition! */
@@ -948,7 +943,8 @@
 		int nports, firstport, asic, port;
 		struct comedi_cmd *cmd = &s->async->cmd;
 
-		if ((asic = subpriv->dio.intr.asic) < 0)
+		asic = subpriv->dio.intr.asic;
+		if (asic  < 0)
 			return 1;	/* not an interrupt
 					   subdev */
 		subpriv->dio.intr.enabled_mask = 0;
@@ -995,14 +991,14 @@
 	return 0;
 }
 
-static int pcmmio_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcmmio_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&subpriv->dio.intr.spinlock, flags);
+	spin_lock_irqsave(&subpriv->dio.intr.spinlock, flags);
 	if (subpriv->dio.intr.active)
 		pcmmio_stop_intr(dev, s);
-	comedi_spin_unlock_irqrestore(&subpriv->dio.intr.spinlock, flags);
+	spin_unlock_irqrestore(&subpriv->dio.intr.spinlock, flags);
 
 	return 0;
 }
@@ -1011,7 +1007,7 @@
  * Internal trigger function to start acquisition for an 'INTERRUPT' subdevice.
  */
 static int
-pcmmio_inttrig_start_intr(struct comedi_device * dev, struct comedi_subdevice * s,
+pcmmio_inttrig_start_intr(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum)
 {
 	unsigned long flags;
@@ -1020,12 +1016,12 @@
 	if (trignum != 0)
 		return -EINVAL;
 
-	comedi_spin_lock_irqsave(&subpriv->dio.intr.spinlock, flags);
+	spin_lock_irqsave(&subpriv->dio.intr.spinlock, flags);
 	s->async->inttrig = 0;
 	if (subpriv->dio.intr.active) {
 		event = pcmmio_start_intr(dev, s);
 	}
-	comedi_spin_unlock_irqrestore(&subpriv->dio.intr.spinlock, flags);
+	spin_unlock_irqrestore(&subpriv->dio.intr.spinlock, flags);
 
 	if (event) {
 		comedi_event(dev, s);
@@ -1037,13 +1033,13 @@
 /*
  * 'do_cmd' function for an 'INTERRUPT' subdevice.
  */
-static int pcmmio_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcmmio_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	unsigned long flags;
 	int event = 0;
 
-	comedi_spin_lock_irqsave(&subpriv->dio.intr.spinlock, flags);
+	spin_lock_irqsave(&subpriv->dio.intr.spinlock, flags);
 	subpriv->dio.intr.active = 1;
 
 	/* Set up end of acquisition. */
@@ -1069,7 +1065,7 @@
 		event = pcmmio_start_intr(dev, s);
 		break;
 	}
-	comedi_spin_unlock_irqrestore(&subpriv->dio.intr.spinlock, flags);
+	spin_unlock_irqrestore(&subpriv->dio.intr.spinlock, flags);
 
 	if (event) {
 		comedi_event(dev, s);
@@ -1078,110 +1074,10 @@
 	return 0;
 }
 
-/*
- * 'do_cmdtest' function for an 'INTERRUPT' subdevice.
- */
 static int
-pcmmio_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s, struct comedi_cmd * cmd)
+pcmmio_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_cmd *cmd)
 {
-	int err = 0;
-	unsigned int tmp;
-
-	/* step 1: make sure trigger sources are trivially valid */
-
-	tmp = cmd->start_src;
-	cmd->start_src &= (TRIG_NOW | TRIG_INT);
-	if (!cmd->start_src || tmp != cmd->start_src)
-		err++;
-
-	tmp = cmd->scan_begin_src;
-	cmd->scan_begin_src &= TRIG_EXT;
-	if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
-		err++;
-
-	tmp = cmd->convert_src;
-	cmd->convert_src &= TRIG_NOW;
-	if (!cmd->convert_src || tmp != cmd->convert_src)
-		err++;
-
-	tmp = cmd->scan_end_src;
-	cmd->scan_end_src &= TRIG_COUNT;
-	if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
-		err++;
-
-	tmp = cmd->stop_src;
-	cmd->stop_src &= (TRIG_COUNT | TRIG_NONE);
-	if (!cmd->stop_src || tmp != cmd->stop_src)
-		err++;
-
-	if (err)
-		return 1;
-
-	/* step 2: make sure trigger sources are unique and mutually compatible */
-
-	/* these tests are true if more than one _src bit is set */
-	if ((cmd->start_src & (cmd->start_src - 1)) != 0)
-		err++;
-	if ((cmd->scan_begin_src & (cmd->scan_begin_src - 1)) != 0)
-		err++;
-	if ((cmd->convert_src & (cmd->convert_src - 1)) != 0)
-		err++;
-	if ((cmd->scan_end_src & (cmd->scan_end_src - 1)) != 0)
-		err++;
-	if ((cmd->stop_src & (cmd->stop_src - 1)) != 0)
-		err++;
-
-	if (err)
-		return 2;
-
-	/* step 3: make sure arguments are trivially compatible */
-
-	/* cmd->start_src == TRIG_NOW || cmd->start_src == TRIG_INT */
-	if (cmd->start_arg != 0) {
-		cmd->start_arg = 0;
-		err++;
-	}
-
-	/* cmd->scan_begin_src == TRIG_EXT */
-	if (cmd->scan_begin_arg != 0) {
-		cmd->scan_begin_arg = 0;
-		err++;
-	}
-
-	/* cmd->convert_src == TRIG_NOW */
-	if (cmd->convert_arg != 0) {
-		cmd->convert_arg = 0;
-		err++;
-	}
-
-	/* cmd->scan_end_src == TRIG_COUNT */
-	if (cmd->scan_end_arg != cmd->chanlist_len) {
-		cmd->scan_end_arg = cmd->chanlist_len;
-		err++;
-	}
-
-	switch (cmd->stop_src) {
-	case TRIG_COUNT:
-		/* any count allowed */
-		break;
-	case TRIG_NONE:
-		if (cmd->stop_arg != 0) {
-			cmd->stop_arg = 0;
-			err++;
-		}
-		break;
-	default:
-		break;
-	}
-
-	if (err)
-		return 3;
-
-	/* step 4: fix up any arguments */
-
-	/* if (err) return 4; */
-
-	return 0;
+	return comedi_pcm_cmdtest(dev, s, cmd);
 }
 
 static int adc_wait_ready(unsigned long iobase)
@@ -1194,8 +1090,8 @@
 }
 
 /* All this is for AI and AO */
-static int ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	unsigned long iobase = subpriv->iobase;
@@ -1258,8 +1154,8 @@
 	return n;
 }
 
-static int ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	for (n = 0; n < insn->n; n++) {
@@ -1288,8 +1184,8 @@
 	return 1;
 }
 
-static int ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	unsigned iobase = subpriv->iobase, iooffset = 0;
diff --git a/drivers/staging/comedi/drivers/pcmuio.c b/drivers/staging/comedi/drivers/pcmuio.c
index 4e7d8b6..81ee7cd 100644
--- a/drivers/staging/comedi/drivers/pcmuio.c
+++ b/drivers/staging/comedi/drivers/pcmuio.c
@@ -75,11 +75,12 @@
   [2] - IRQ for second ASIC (pcmuio96 only - IRQ for chans 48-72 .. can be the same as first irq!)
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
+#include "pcm_common.h"
 
 #include <linux/pci.h>		/* for PCI devices */
 
-#define MIN(a,b) ( ((a) < (b)) ? (a) : (b) )
 #define CHANS_PER_PORT   8
 #define PORTS_PER_ASIC   6
 #define INTR_PORTS_PER_ASIC   3
@@ -155,14 +156,14 @@
 
 static const struct pcmuio_board pcmuio_boards[] = {
 	{
-	      name:	"pcmuio48",
-	      num_asics:1,
-	      num_ports:6,
+	.name = "pcmuio48",
+	.num_asics = 1,
+	.num_ports = 6,
 		},
 	{
-	      name:	"pcmuio96",
-	      num_asics:2,
-	      num_ports:12,
+	.name = "pcmuio96",
+	.num_asics = 2,
+	.num_ports = 12,
 		},
 };
 
@@ -222,14 +223,14 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int pcmuio_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int pcmuio_detach(struct comedi_device * dev);
+static int pcmuio_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int pcmuio_detach(struct comedi_device *dev);
 
 static struct comedi_driver driver = {
-      driver_name:"pcmuio",
-      module:THIS_MODULE,
-      attach:pcmuio_attach,
-      detach:pcmuio_detach,
+	.driver_name = "pcmuio",
+	.module = THIS_MODULE,
+	.attach = pcmuio_attach,
+	.detach = pcmuio_detach,
 /* It is not necessary to implement the following members if you are
  * writing a driver for a ISA PnP or PCI card */
 	/* Most drivers will support multiple types of boards by
@@ -248,29 +249,29 @@
 	 * the type of board in software.  ISA PnP, PCI, and PCMCIA
 	 * devices are such boards.
 	 */
-      board_name:&pcmuio_boards[0].name,
-      offset:sizeof(struct pcmuio_board),
-      num_names:sizeof(pcmuio_boards) / sizeof(struct pcmuio_board),
+	.board_name = &pcmuio_boards[0].name,
+	.offset = sizeof(struct pcmuio_board),
+	.num_names = ARRAY_SIZE(pcmuio_boards),
 };
 
-static int pcmuio_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int pcmuio_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int pcmuio_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int pcmuio_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static irqreturn_t interrupt_pcmuio(int irq, void *d PT_REGS_ARG);
+static irqreturn_t interrupt_pcmuio(int irq, void *d);
 static void pcmuio_stop_intr(struct comedi_device *, struct comedi_subdevice *);
-static int pcmuio_cancel(struct comedi_device * dev, struct comedi_subdevice * s);
-static int pcmuio_cmd(struct comedi_device * dev, struct comedi_subdevice * s);
-static int pcmuio_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
+static int pcmuio_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
+static int pcmuio_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
+static int pcmuio_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
 
 /* some helper functions to deal with specifics of this device's registers */
-static void init_asics(struct comedi_device * dev);	/* sets up/clears ASIC chips to defaults */
-static void switch_page(struct comedi_device * dev, int asic, int page);
+static void init_asics(struct comedi_device *dev);	/* sets up/clears ASIC chips to defaults */
+static void switch_page(struct comedi_device *dev, int asic, int page);
 #ifdef notused
-static void lock_port(struct comedi_device * dev, int asic, int port);
-static void unlock_port(struct comedi_device * dev, int asic, int port);
+static void lock_port(struct comedi_device *dev, int asic, int port);
+static void unlock_port(struct comedi_device *dev, int asic, int port);
 #endif
 
 /*
@@ -279,7 +280,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int pcmuio_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int pcmuio_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int sdev_no, chans_left, n_subdevs, port, asic, thisasic_chanct = 0;
@@ -322,7 +323,7 @@
 		devpriv->asics[asic].iobase = dev->iobase + asic * ASIC_IOSIZE;
 		devpriv->asics[asic].irq = 0;	/* this gets actually set at the end of
 						   this function when we
-						   comedi_request_irqs */
+						   request_irqs */
 		spin_lock_init(&devpriv->asics[asic].spinlock);
 	}
 
@@ -359,7 +360,7 @@
 		s->type = COMEDI_SUBD_DIO;
 		s->insn_bits = pcmuio_dio_insn_bits;
 		s->insn_config = pcmuio_dio_insn_config;
-		s->n_chan = MIN(chans_left, MAX_CHANS_PER_SUBDEV);
+		s->n_chan = min(chans_left, MAX_CHANS_PER_SUBDEV);
 		subpriv->intr.asic = -1;
 		subpriv->intr.first_chan = -1;
 		subpriv->intr.asic_chan = -1;
@@ -413,12 +414,12 @@
 
 	for (asic = 0; irq[0] && asic < MAX_ASICS; ++asic) {
 		if (irq[asic]
-			&& comedi_request_irq(irq[asic], interrupt_pcmuio,
+			&& request_irq(irq[asic], interrupt_pcmuio,
 				IRQF_SHARED, thisboard->name, dev)) {
 			int i;
 			/* unroll the allocated irqs.. */
 			for (i = asic - 1; i >= 0; --i) {
-				comedi_free_irq(irq[i], dev);
+				free_irq(irq[i], dev);
 				devpriv->asics[i].irq = irq[i] = 0;
 			}
 			irq[asic] = 0;
@@ -450,7 +451,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int pcmuio_detach(struct comedi_device * dev)
+static int pcmuio_detach(struct comedi_device *dev)
 {
 	int i;
 
@@ -460,7 +461,7 @@
 
 	for (i = 0; i < MAX_ASICS; ++i) {
 		if (devpriv->asics[i].irq)
-			comedi_free_irq(devpriv->asics[i].irq, dev);
+			free_irq(devpriv->asics[i].irq, dev);
 	}
 
 	if (devpriv && devpriv->sprivs)
@@ -474,8 +475,8 @@
  * useful to applications if you implement the insn_bits interface.
  * This allows packed reading/writing of the DIO channels.  The
  * comedi core can convert between insn_bits and insn_read/write */
-static int pcmuio_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcmuio_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int byte_no;
 	if (insn->n != 2)
@@ -548,8 +549,8 @@
  * configured by a special insn_config instruction.  chanspec
  * contains the channel to be changed, and data[0] contains the
  * value COMEDI_INPUT or COMEDI_OUTPUT. */
-static int pcmuio_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcmuio_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec), byte_no = chan / 8, bit_no =
 		chan % 8;
@@ -609,7 +610,7 @@
 	return insn->n;
 }
 
-static void init_asics(struct comedi_device * dev)
+static void init_asics(struct comedi_device *dev)
 {				/* sets up an
 				   ASIC chip to defaults */
 	int asic;
@@ -646,7 +647,7 @@
 	}
 }
 
-static void switch_page(struct comedi_device * dev, int asic, int page)
+static void switch_page(struct comedi_device *dev, int asic, int page)
 {
 	if (asic < 0 || asic >= thisboard->num_asics)
 		return;		/* paranoia */
@@ -662,7 +663,7 @@
 }
 
 #ifdef notused
-static void lock_port(struct comedi_device * dev, int asic, int port)
+static void lock_port(struct comedi_device *dev, int asic, int port)
 {
 	if (asic < 0 || asic >= thisboard->num_asics)
 		return;		/* paranoia */
@@ -675,7 +676,7 @@
 		dev->iobase + ASIC_IOSIZE * asic + REG_PAGELOCK);
 }
 
-static void unlock_port(struct comedi_device * dev, int asic, int port)
+static void unlock_port(struct comedi_device *dev, int asic, int port)
 {
 	if (asic < 0 || asic >= thisboard->num_asics)
 		return;		/* paranoia */
@@ -688,7 +689,7 @@
 }
 #endif /* notused */
 
-static irqreturn_t interrupt_pcmuio(int irq, void *d PT_REGS_ARG)
+static irqreturn_t interrupt_pcmuio(int irq, void *d)
 {
 	int asic, got1 = 0;
 	struct comedi_device *dev = (struct comedi_device *) d;
@@ -701,8 +702,7 @@
 			/* it is an interrupt for ASIC #asic */
 			unsigned char int_pend;
 
-			comedi_spin_lock_irqsave(&devpriv->asics[asic].spinlock,
-				flags);
+			spin_lock_irqsave(&devpriv->asics[asic].spinlock, flags);
 
 			int_pend = inb(iobase + REG_INT_PENDING) & 0x07;
 
@@ -734,8 +734,7 @@
 				++got1;
 			}
 
-			comedi_spin_unlock_irqrestore(&devpriv->asics[asic].
-				spinlock, flags);
+			spin_unlock_irqrestore(&devpriv->asics[asic].spinlock, flags);
 
 			if (triggered) {
 				struct comedi_subdevice *s;
@@ -748,9 +747,7 @@
 						unsigned long flags;
 						unsigned oldevents;
 
-						comedi_spin_lock_irqsave
-							(&subpriv->intr.
-							spinlock, flags);
+						spin_lock_irqsave (&subpriv->intr.spinlock, flags);
 
 						oldevents = s->async->events;
 
@@ -781,10 +778,10 @@
 									}
 								}
 								/* Write the scan to the buffer. */
-								if (comedi_buf_put(s->async, ((short *) & val)[0])
+								if (comedi_buf_put(s->async, ((short *) &val)[0])
 									&&
 									comedi_buf_put
-									(s->async, ((short *) & val)[1])) {
+									(s->async, ((short *) &val)[1])) {
 									s->async->events |= (COMEDI_CB_BLOCK | COMEDI_CB_EOS);
 								} else {
 									/* Overflow! Stop acquisition!! */
@@ -816,9 +813,7 @@
 							}
 						}
 
-						comedi_spin_unlock_irqrestore
-							(&subpriv->intr.
-							spinlock, flags);
+						spin_unlock_irqrestore(&subpriv->intr.spinlock, flags);
 
 						if (oldevents !=
 							s->async->events) {
@@ -837,11 +832,12 @@
 	return IRQ_HANDLED;
 }
 
-static void pcmuio_stop_intr(struct comedi_device * dev, struct comedi_subdevice * s)
+static void pcmuio_stop_intr(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	int nports, firstport, asic, port;
 
-	if ((asic = subpriv->intr.asic) < 0)
+	asic = subpriv->intr.asic;
+	if (asic < 0)
 		return;		/* not an interrupt subdev */
 
 	subpriv->intr.enabled_mask = 0;
@@ -856,7 +852,7 @@
 	}
 }
 
-static int pcmuio_start_intr(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcmuio_start_intr(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	if (!subpriv->intr.continuous && subpriv->intr.stop_count == 0) {
 		/* An empty acquisition! */
@@ -868,7 +864,8 @@
 		int nports, firstport, asic, port;
 		struct comedi_cmd *cmd = &s->async->cmd;
 
-		if ((asic = subpriv->intr.asic) < 0)
+		asic = subpriv->intr.asic;
+		if (asic < 0)
 			return 1;	/* not an interrupt
 					   subdev */
 		subpriv->intr.enabled_mask = 0;
@@ -905,14 +902,14 @@
 	return 0;
 }
 
-static int pcmuio_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcmuio_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	unsigned long flags;
 
-	comedi_spin_lock_irqsave(&subpriv->intr.spinlock, flags);
+	spin_lock_irqsave(&subpriv->intr.spinlock, flags);
 	if (subpriv->intr.active)
 		pcmuio_stop_intr(dev, s);
-	comedi_spin_unlock_irqrestore(&subpriv->intr.spinlock, flags);
+	spin_unlock_irqrestore(&subpriv->intr.spinlock, flags);
 
 	return 0;
 }
@@ -921,7 +918,7 @@
  * Internal trigger function to start acquisition for an 'INTERRUPT' subdevice.
  */
 static int
-pcmuio_inttrig_start_intr(struct comedi_device * dev, struct comedi_subdevice * s,
+pcmuio_inttrig_start_intr(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum)
 {
 	unsigned long flags;
@@ -930,12 +927,12 @@
 	if (trignum != 0)
 		return -EINVAL;
 
-	comedi_spin_lock_irqsave(&subpriv->intr.spinlock, flags);
+	spin_lock_irqsave(&subpriv->intr.spinlock, flags);
 	s->async->inttrig = 0;
 	if (subpriv->intr.active) {
 		event = pcmuio_start_intr(dev, s);
 	}
-	comedi_spin_unlock_irqrestore(&subpriv->intr.spinlock, flags);
+	spin_unlock_irqrestore(&subpriv->intr.spinlock, flags);
 
 	if (event) {
 		comedi_event(dev, s);
@@ -947,13 +944,13 @@
 /*
  * 'do_cmd' function for an 'INTERRUPT' subdevice.
  */
-static int pcmuio_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int pcmuio_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct comedi_cmd *cmd = &s->async->cmd;
 	unsigned long flags;
 	int event = 0;
 
-	comedi_spin_lock_irqsave(&subpriv->intr.spinlock, flags);
+	spin_lock_irqsave(&subpriv->intr.spinlock, flags);
 	subpriv->intr.active = 1;
 
 	/* Set up end of acquisition. */
@@ -979,7 +976,7 @@
 		event = pcmuio_start_intr(dev, s);
 		break;
 	}
-	comedi_spin_unlock_irqrestore(&subpriv->intr.spinlock, flags);
+	spin_unlock_irqrestore(&subpriv->intr.spinlock, flags);
 
 	if (event) {
 		comedi_event(dev, s);
@@ -988,110 +985,10 @@
 	return 0;
 }
 
-/*
- * 'do_cmdtest' function for an 'INTERRUPT' subdevice.
- */
 static int
-pcmuio_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s, struct comedi_cmd * cmd)
+pcmuio_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_cmd *cmd)
 {
-	int err = 0;
-	unsigned int tmp;
-
-	/* step 1: make sure trigger sources are trivially valid */
-
-	tmp = cmd->start_src;
-	cmd->start_src &= (TRIG_NOW | TRIG_INT);
-	if (!cmd->start_src || tmp != cmd->start_src)
-		err++;
-
-	tmp = cmd->scan_begin_src;
-	cmd->scan_begin_src &= TRIG_EXT;
-	if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
-		err++;
-
-	tmp = cmd->convert_src;
-	cmd->convert_src &= TRIG_NOW;
-	if (!cmd->convert_src || tmp != cmd->convert_src)
-		err++;
-
-	tmp = cmd->scan_end_src;
-	cmd->scan_end_src &= TRIG_COUNT;
-	if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
-		err++;
-
-	tmp = cmd->stop_src;
-	cmd->stop_src &= (TRIG_COUNT | TRIG_NONE);
-	if (!cmd->stop_src || tmp != cmd->stop_src)
-		err++;
-
-	if (err)
-		return 1;
-
-	/* step 2: make sure trigger sources are unique and mutually compatible */
-
-	/* these tests are true if more than one _src bit is set */
-	if ((cmd->start_src & (cmd->start_src - 1)) != 0)
-		err++;
-	if ((cmd->scan_begin_src & (cmd->scan_begin_src - 1)) != 0)
-		err++;
-	if ((cmd->convert_src & (cmd->convert_src - 1)) != 0)
-		err++;
-	if ((cmd->scan_end_src & (cmd->scan_end_src - 1)) != 0)
-		err++;
-	if ((cmd->stop_src & (cmd->stop_src - 1)) != 0)
-		err++;
-
-	if (err)
-		return 2;
-
-	/* step 3: make sure arguments are trivially compatible */
-
-	/* cmd->start_src == TRIG_NOW || cmd->start_src == TRIG_INT */
-	if (cmd->start_arg != 0) {
-		cmd->start_arg = 0;
-		err++;
-	}
-
-	/* cmd->scan_begin_src == TRIG_EXT */
-	if (cmd->scan_begin_arg != 0) {
-		cmd->scan_begin_arg = 0;
-		err++;
-	}
-
-	/* cmd->convert_src == TRIG_NOW */
-	if (cmd->convert_arg != 0) {
-		cmd->convert_arg = 0;
-		err++;
-	}
-
-	/* cmd->scan_end_src == TRIG_COUNT */
-	if (cmd->scan_end_arg != cmd->chanlist_len) {
-		cmd->scan_end_arg = cmd->chanlist_len;
-		err++;
-	}
-
-	switch (cmd->stop_src) {
-	case TRIG_COUNT:
-		/* any count allowed */
-		break;
-	case TRIG_NONE:
-		if (cmd->stop_arg != 0) {
-			cmd->stop_arg = 0;
-			err++;
-		}
-		break;
-	default:
-		break;
-	}
-
-	if (err)
-		return 3;
-
-	/* step 4: fix up any arguments */
-
-	/* if (err) return 4; */
-
-	return 0;
+	return comedi_pcm_cmdtest(dev, s, cmd);
 }
 
 /*
diff --git a/drivers/staging/comedi/drivers/plx9080.h b/drivers/staging/comedi/drivers/plx9080.h
index 9231ba8..e4bbd5d 100644
--- a/drivers/staging/comedi/drivers/plx9080.h
+++ b/drivers/staging/comedi/drivers/plx9080.h
@@ -399,11 +399,11 @@
 
 	/*  wait to make sure done bit is zero */
 	for (i = 0; (dma_status & PLX_DMA_DONE_BIT) && i < timeout; i++) {
-		comedi_udelay(1);
+		udelay(1);
 		dma_status = readb(dma_cs_addr);
 	}
 	if (i == timeout) {
-		rt_printk
+		printk
 			("plx9080: cancel() timed out waiting for dma %i done clear\n",
 			channel);
 		return -ETIMEDOUT;
@@ -413,11 +413,11 @@
 	/*  wait for dma done bit */
 	dma_status = readb(dma_cs_addr);
 	for (i = 0; (dma_status & PLX_DMA_DONE_BIT) == 0 && i < timeout; i++) {
-		comedi_udelay(1);
+		udelay(1);
 		dma_status = readb(dma_cs_addr);
 	}
 	if (i == timeout) {
-		rt_printk
+		printk
 			("plx9080: cancel() timed out waiting for dma %i done set\n",
 			channel);
 		return -ETIMEDOUT;
diff --git a/drivers/staging/comedi/drivers/poc.c b/drivers/staging/comedi/drivers/poc.c
index 8a0bf68..47850bd 100644
--- a/drivers/staging/comedi/drivers/poc.c
+++ b/drivers/staging/comedi/drivers/poc.c
@@ -41,17 +41,17 @@
 
 #include <linux/ioport.h>
 
-static int poc_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int poc_detach(struct comedi_device * dev);
-static int readback_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int poc_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int poc_detach(struct comedi_device *dev);
+static int readback_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
-static int dac02_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int pcl733_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int pcl734_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int dac02_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int pcl733_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int pcl734_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 struct boarddef_struct {
 	const char *name;
@@ -70,33 +70,33 @@
 };
 static const struct boarddef_struct boards[] = {
 	{
-	      name:	"dac02",
-	      iosize:	8,
-			//setup:                dac02_setup,
-	      type:	COMEDI_SUBD_AO,
-	      n_chan:	2,
-	      n_bits:	12,
-	      winsn:	dac02_ao_winsn,
-	      rinsn:	readback_insn,
-	      range:	&range_unknown,
+	.name = "dac02",
+	.iosize = 8,
+			/*	.setup = dac02_setup, */
+	.type = COMEDI_SUBD_AO,
+	.n_chan = 2,
+	.n_bits = 12,
+	.winsn = dac02_ao_winsn,
+	.rinsn = readback_insn,
+	.range = &range_unknown,
 		},
 	{
-	      name:	"pcl733",
-	      iosize:	4,
-	      type:	COMEDI_SUBD_DI,
-	      n_chan:	32,
-	      n_bits:	1,
-	      insnbits:pcl733_insn_bits,
-	      range:	&range_digital,
+	.name = "pcl733",
+	.iosize = 4,
+	.type = COMEDI_SUBD_DI,
+	.n_chan = 32,
+	.n_bits = 1,
+	.insnbits = pcl733_insn_bits,
+	.range = &range_digital,
 		},
 	{
-	      name:	"pcl734",
-	      iosize:	4,
-	      type:	COMEDI_SUBD_DO,
-	      n_chan:	32,
-	      n_bits:	1,
-	      insnbits:pcl734_insn_bits,
-	      range:	&range_digital,
+	.name = "pcl734",
+	.iosize = 4,
+	.type = COMEDI_SUBD_DO,
+	.n_chan = 32,
+	.n_bits = 1,
+	.insnbits = pcl734_insn_bits,
+	.range = &range_digital,
 		},
 };
 
@@ -104,16 +104,16 @@
 #define this_board ((const struct boarddef_struct *)dev->board_ptr)
 
 static struct comedi_driver driver_poc = {
-      driver_name:"poc",
-      module:THIS_MODULE,
-      attach:poc_attach,
-      detach:poc_detach,
-      board_name:&boards[0].name,
-      num_names:n_boards,
-      offset:sizeof(boards[0]),
+	.driver_name = "poc",
+	.module = THIS_MODULE,
+	.attach = poc_attach,
+	.detach = poc_detach,
+	.board_name = &boards[0].name,
+	.num_names = n_boards,
+	.offset = sizeof(boards[0]),
 };
 
-static int poc_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int poc_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	unsigned long iobase;
@@ -159,7 +159,7 @@
 	return 0;
 }
 
-static int poc_detach(struct comedi_device * dev)
+static int poc_detach(struct comedi_device *dev)
 {
 	/* only free stuff if it has been allocated by _attach */
 	if (dev->iobase)
@@ -170,8 +170,8 @@
 	return 0;
 }
 
-static int readback_insn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int readback_insn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan;
 
@@ -185,8 +185,8 @@
 #define DAC02_LSB(a)	(2 * a)
 #define DAC02_MSB(a)	(2 * a + 1)
 
-static int dac02_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int dac02_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int temp;
 	int chan;
@@ -196,7 +196,7 @@
 	((unsigned int *) dev->private)[chan] = data[0];
 	output = data[0];
 #ifdef wrong
-	// convert to complementary binary if range is bipolar
+	/*  convert to complementary binary if range is bipolar */
 	if ((CR_RANGE(insn->chanspec) & 0x2) == 0)
 		output = ~output;
 #endif
@@ -208,8 +208,8 @@
 	return 1;
 }
 
-static int pcl733_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl733_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -222,8 +222,8 @@
 	return 2;
 }
 
-static int pcl734_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int pcl734_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
diff --git a/drivers/staging/comedi/drivers/quatech_daqp_cs.c b/drivers/staging/comedi/drivers/quatech_daqp_cs.c
index 795c452..85b53c9 100644
--- a/drivers/staging/comedi/drivers/quatech_daqp_cs.c
+++ b/drivers/staging/comedi/drivers/quatech_daqp_cs.c
@@ -179,8 +179,8 @@
 #define DAQP_AUX_FIFO_EMPTY		0x01
 
 /* These range structures tell COMEDI how the sample values map to
- * voltages.  The A/D converter has four ranges: +/- 10V through
- * +/- 1.25V, and the D/A converter has only one: +/- 5V.
+ * voltages.  The A/D converter has four	.ranges = +/- 10V through
+ * +/- 1.25V, and the D/A converter has only	.one = +/- 5V.
  */
 
 static const struct comedi_lrange range_daqp_ai = { 4, {
@@ -197,18 +197,18 @@
 
 /* comedi interface code */
 
-static int daqp_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int daqp_detach(struct comedi_device * dev);
+static int daqp_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int daqp_detach(struct comedi_device *dev);
 static struct comedi_driver driver_daqp = {
-      driver_name:"quatech_daqp_cs",
-      module:THIS_MODULE,
-      attach:daqp_attach,
-      detach:daqp_detach,
+	.driver_name = "quatech_daqp_cs",
+	.module = THIS_MODULE,
+	.attach = daqp_attach,
+	.detach = daqp_detach,
 };
 
 #ifdef DAQP_DEBUG
 
-static void daqp_dump(struct comedi_device * dev)
+static void daqp_dump(struct comedi_device *dev)
 {
 	printk("DAQP: status %02x; aux status %02x\n",
 		inb(dev->iobase + DAQP_STATUS), inb(dev->iobase + DAQP_AUX));
@@ -234,7 +234,7 @@
 
 /* Cancel a running acquisition */
 
-static int daqp_ai_cancel(struct comedi_device * dev, struct comedi_subdevice * s)
+static int daqp_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct local_info_t *local = (struct local_info_t *) s->private;
 
@@ -262,7 +262,7 @@
  * which run pretty quick.
  */
 
-static void daqp_interrupt(int irq, void *dev_id PT_REGS_ARG)
+static void daqp_interrupt(int irq, void *dev_id)
 {
 	struct local_info_t *local = (struct local_info_t *) dev_id;
 	struct comedi_device *dev;
@@ -361,8 +361,8 @@
 
 /* One-shot analog data acquisition routine */
 
-static int daqp_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int daqp_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct local_info_t *local = (struct local_info_t *) s->private;
 	int i;
@@ -467,8 +467,8 @@
  * the command passes.
  */
 
-static int daqp_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int daqp_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -593,7 +593,7 @@
 	return 0;
 }
 
-static int daqp_ai_cmd(struct comedi_device * dev, struct comedi_subdevice * s)
+static int daqp_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	struct local_info_t *local = (struct local_info_t *) s->private;
 	struct comedi_cmd *cmd = &s->async->cmd;
@@ -793,8 +793,8 @@
 
 /* Single-shot analog output routine */
 
-static int daqp_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int daqp_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct local_info_t *local = (struct local_info_t *) s->private;
 	int d;
@@ -820,8 +820,8 @@
 
 /* Digital input routine */
 
-static int daqp_di_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int daqp_di_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct local_info_t *local = (struct local_info_t *) s->private;
 
@@ -836,8 +836,8 @@
 
 /* Digital output routine */
 
-static int daqp_do_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int daqp_do_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct local_info_t *local = (struct local_info_t *) s->private;
 
@@ -856,7 +856,7 @@
  * when it is inserted.
  */
 
-static int daqp_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int daqp_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int ret;
 	struct local_info_t *local = dev_table[it->options[0]];
@@ -908,7 +908,8 @@
 
 	dev->iobase = local->link->io.BasePort1;
 
-	if ((ret = alloc_subdevices(dev, 4)) < 0)
+	ret = alloc_subdevices(dev, 4);
+	if (ret < 0)
 		return ret;
 
 	printk("comedi%d: attaching daqp%d (io 0x%04lx)\n",
@@ -962,7 +963,7 @@
  * card is removed, daqp_cs_detach() is called by the pcmcia subsystem.
  */
 
-static int daqp_detach(struct comedi_device * dev)
+static int daqp_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: detaching daqp\n", dev->minor);
 
@@ -1149,15 +1150,21 @@
 	tuple.TupleData = buf;
 	tuple.TupleDataMax = sizeof(buf);
 	tuple.TupleOffset = 0;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple))) {
+
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret) {
 		cs_error(link, GetFirstTuple, last_ret);
 		goto cs_failed;
 	}
-	if ((last_ret = pcmcia_get_tuple_data(link, &tuple))) {
+
+	last_ret = pcmcia_get_tuple_data(link, &tuple);
+	if (last_ret) {
 		cs_error(link, GetTupleData, last_ret);
 		goto cs_failed;
 	}
-	if ((last_ret = pcmcia_parse_tuple(&tuple, &parse))) {
+
+	last_ret = pcmcia_parse_tuple(&tuple, &parse);
+	if (last_ret) {
 		cs_error(link, ParseTuple, last_ret);
 		goto cs_failed;
 	}
@@ -1177,10 +1184,12 @@
 	   will only use the CIS to fill in implementation-defined details.
 	 */
 	tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
-	if ((last_ret = pcmcia_get_first_tuple(link, &tuple))) {
+	last_ret = pcmcia_get_first_tuple(link, &tuple);
+	if (last_ret) {
 		cs_error(link, GetFirstTuple, last_ret);
 		goto cs_failed;
 	}
+
 	while (1) {
 		cistpl_cftable_entry_t dflt = { 0 };
 		cistpl_cftable_entry_t *cfg = &(parse.cftable_entry);
@@ -1226,7 +1235,8 @@
 		break;
 
 	      next_entry:
-		if ((last_ret = pcmcia_get_next_tuple(link, &tuple))) {
+		last_ret = pcmcia_get_next_tuple(link, &tuple);
+		if (last_ret) {
 			cs_error(link, GetNextTuple, last_ret);
 			goto cs_failed;
 		}
@@ -1237,18 +1247,21 @@
 	   handler to the interrupt, unless the 'Handler' member of the
 	   irq structure is initialized.
 	 */
-	if (link->conf.Attributes & CONF_ENABLE_IRQ)
-		if ((last_ret = pcmcia_request_irq(link, &link->irq))) {
+	if (link->conf.Attributes & CONF_ENABLE_IRQ) {
+		last_ret = pcmcia_request_irq(link, &link->irq);
+		if (last_ret) {
 			cs_error(link, RequestIRQ, last_ret);
 			goto cs_failed;
 		}
+	}
 
 	/*
 	   This actually configures the PCMCIA socket -- setting up
 	   the I/O windows and the interrupt mapping, and putting the
 	   card and host interface into "Memory and IO" mode.
 	 */
-	if ((last_ret = pcmcia_request_configuration(link, &link->conf))) {
+	last_ret = pcmcia_request_configuration(link, &link->conf);
+	if (last_ret) {
 		cs_error(link, RequestConfiguration, last_ret);
 		goto cs_failed;
 	}
diff --git a/drivers/staging/comedi/drivers/rtd520.c b/drivers/staging/comedi/drivers/rtd520.c
index ca347f2..243ee76 100644
--- a/drivers/staging/comedi/drivers/rtd520.c
+++ b/drivers/staging/comedi/drivers/rtd520.c
@@ -101,6 +101,7 @@
 
 */
 
+#include <linux/interrupt.h>
 #include <linux/delay.h>
 
 #include "../comedidev.h"
@@ -135,7 +136,7 @@
 #define RTD_DMA_TIMEOUT	33000	/* 1 msec */
 #else
 /* by delaying, power and electrical noise are reduced somewhat */
-#define WAIT_QUIETLY	comedi_udelay (1)
+#define WAIT_QUIETLY	udelay (1)
 #define RTD_ADC_TIMEOUT	2000	/* in usec */
 #define RTD_DAC_TIMEOUT	2000	/* in usec */
 #define RTD_DMA_TIMEOUT	1000	/* in usec */
@@ -278,22 +279,22 @@
 
 static const struct rtdBoard rtd520Boards[] = {
 	{
-	      name:	"DM7520",
-	      device_id : 0x7520,
-	      aiChans:	16,
-	      aiBits:	12,
-	      aiMaxGain:32,
-	      range10Start:6,
-	      rangeUniStart:12,
+	.name = "DM7520",
+	.device_id = 0x7520,
+	.aiChans = 16,
+	.aiBits = 12,
+	.aiMaxGain = 32,
+	.range10Start = 6,
+	.rangeUniStart = 12,
 		},
 	{
-	      name:	"PCI4520",
-	      device_id : 0x4520,
-	      aiChans:	16,
-	      aiBits:	12,
-	      aiMaxGain:128,
-	      range10Start:8,
-	      rangeUniStart:16,
+	.name = "PCI4520",
+	.device_id = 0x4520,
+	.aiChans = 16,
+	.aiBits = 12,
+	.aiMaxGain = 128,
+	.range10Start = 8,
+	.rangeUniStart = 16,
 		},
 };
 
@@ -684,10 +685,10 @@
 static int rtd_detach(struct comedi_device *dev);
 
 static struct comedi_driver rtd520Driver = {
-      driver_name: DRV_NAME,
-      module : THIS_MODULE,
-      attach : rtd_attach,
-      detach : rtd_detach,
+	.driver_name = DRV_NAME,
+	.module = THIS_MODULE,
+	.attach = rtd_attach,
+	.detach = rtd_detach,
 };
 
 static int rtd_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
@@ -706,7 +707,7 @@
 static int rtd_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s);
 /* static int rtd_ai_poll (struct comedi_device *dev,struct comedi_subdevice *s); */
 static int rtd_ns_to_timer(unsigned int *ns, int roundMode);
-static irqreturn_t rtd_interrupt(int irq, void *d PT_REGS_ARG);
+static irqreturn_t rtd_interrupt(int irq, void *d);
 static int rtd520_probe_fifo_depth(struct comedi_device *dev);
 
 /*
@@ -757,15 +758,15 @@
 				continue;
 			}
 		}
-		for(i = 0; i < sizeof(rtd520Boards) / sizeof(rtd520Boards[0]); ++i)
+		for (i = 0; i < ARRAY_SIZE(rtd520Boards); ++i)
 		{
-			if(pcidev->device == rtd520Boards[i].device_id)
+			if (pcidev->device == rtd520Boards[i].device_id)
 			{
 				dev->board_ptr = &rtd520Boards[i];
 				break;
 			}
 		}
-		if(dev->board_ptr) break;	/* found one */
+		if (dev->board_ptr) break;	/* found one */
 	}
 	if (!pcidev) {
 		if (it->options[0] && it->options[1]) {
@@ -900,7 +901,7 @@
 	/* initialize board, per RTD spec */
 	/* also, initialize shadow registers */
 	RtdResetBoard(dev);
-	comedi_udelay(100);	/* needed? */
+	udelay(100);	/* needed? */
 	RtdPlxInterruptWrite(dev, 0);
 	RtdInterruptMask(dev, 0);	/* and sets shadow */
 	RtdInterruptClearMask(dev, ~0);	/* and sets shadow */
@@ -919,7 +920,7 @@
 	/* TODO: set user out source ??? */
 
 	/* check if our interrupt is available and get it */
-	ret = comedi_request_irq(devpriv->pci_dev->irq, rtd_interrupt,
+	ret = request_irq(devpriv->pci_dev->irq, rtd_interrupt,
 				 IRQF_SHARED, DRV_NAME, dev);
 
 	if (ret < 0) {
@@ -931,7 +932,7 @@
 	printk("( irq=%u )", dev->irq);
 
 	ret = rtd520_probe_fifo_depth(dev);
-	if(ret < 0) {
+	if (ret < 0) {
 		return ret;
 	}
 	devpriv->fifoLen = ret;
@@ -1032,7 +1033,7 @@
 		/* disable interrupt controller */
 		RtdPlxInterruptWrite(dev, RtdPlxInterruptRead(dev)
 			& ~(ICS_PLIE | ICS_DMA0_E | ICS_DMA1_E));
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 	}
 
 	/* release all regions that were allocated */
@@ -1111,7 +1112,7 @@
 			/* disable interrupt controller */
 			RtdPlxInterruptWrite(dev, RtdPlxInterruptRead(dev)
 				& ~(ICS_PLIE | ICS_DMA0_E | ICS_DMA1_E));
-			comedi_free_irq(dev->irq, dev);
+			free_irq(dev->irq, dev);
 		}
 
 		/* release all regions that were allocated */
@@ -1224,22 +1225,22 @@
 		unsigned fifo_status;
 		/* trigger conversion */
 		RtdAdcStart(dev);
-		comedi_udelay(1);
+		udelay(1);
 		fifo_status = RtdFifoStatus(dev);
-		if((fifo_status & FS_ADC_HEMPTY) == 0) {
+		if ((fifo_status & FS_ADC_HEMPTY) == 0) {
 			fifo_size = 2 * i;
 			break;
 		}
 	}
-	if(i == limit)
+	if (i == limit)
 	{
-		rt_printk("\ncomedi: %s: failed to probe fifo size.\n", DRV_NAME);
+		printk("\ncomedi: %s: failed to probe fifo size.\n", DRV_NAME);
 		return -EIO;
 	}
 	RtdAdcClearFifo(dev);
-	if(fifo_size != 0x400 && fifo_size != 0x2000)
+	if (fifo_size != 0x400 && fifo_size != 0x2000)
 	{
-		rt_printk("\ncomedi: %s: unexpected fifo size of %i, expected 1024 or 8192.\n",
+		printk("\ncomedi: %s: unexpected fifo size of %i, expected 1024 or 8192.\n",
 			DRV_NAME, fifo_size);
 		return -EIO;
 	}
@@ -1386,7 +1387,7 @@
 		+ ((channel == 0) ? LCFG_DMACSR0 : LCFG_DMACSR1);
 
 	/*  spinlock for plx dma control/status reg */
-	/* comedi_spin_lock_irqsave( &dev->spinlock, flags ); */
+	/* spin_lock_irqsave( &dev->spinlock, flags ); */
 
 	/*  abort dma transfer if necessary */
 	status = readb(dma_cs_addr);
@@ -1409,7 +1410,7 @@
 
 	/* disable channel (required) */
 	writeb(0, dma_cs_addr);
-	comedi_udelay(1);	/* needed?? */
+	udelay(1);	/* needed?? */
 	/* set abort bit for channel */
 	writeb(PLX_DMA_ABORT_BIT, dma_cs_addr);
 
@@ -1427,7 +1428,7 @@
 	}
 
       abortDmaExit:
-	/* comedi_spin_unlock_irqrestore( &dev->spinlock, flags ); */
+	/* spin_unlock_irqrestore( &dev->spinlock, flags ); */
 }
 
 /*
@@ -1494,8 +1495,7 @@
   The data conversion may someday happen in a "bottom half".
 */
 static irqreturn_t rtd_interrupt(int irq,	/* interrupt number (ignored) */
-	void *d			/* our data */
-	PT_REGS_ARG)
+	void *d)		/* our data */
 {				/* cpu context (ignored) */
 	struct comedi_device *dev = d;	/* must be called "dev" for devpriv */
 	u16 status;
diff --git a/drivers/staging/comedi/drivers/rti800.c b/drivers/staging/comedi/drivers/rti800.c
index 334ac57..f1b7e02 100644
--- a/drivers/staging/comedi/drivers/rti800.c
+++ b/drivers/staging/comedi/drivers/rti800.c
@@ -52,6 +52,7 @@
   [8] - DAC 1 encoding (same as DAC 0)
 */
 
+#include <linux/interrupt.h>
 #include "../comedidev.h"
 
 #include <linux/ioport.h>
@@ -89,8 +90,8 @@
 
 #define Am9513_8BITBUS
 
-#define Am9513_output_control(a)	outb(a,dev->iobase+RTI800_9513A_CNTRL)
-#define Am9513_output_data(a)		outb(a,dev->iobase+RTI800_9513A_DATA)
+#define Am9513_output_control(a)	outb(a, dev->iobase+RTI800_9513A_CNTRL)
+#define Am9513_output_data(a)		outb(a, dev->iobase+RTI800_9513A_DATA)
 #define Am9513_input_data()		inb(dev->iobase+RTI800_9513A_DATA)
 #define Am9513_input_status()		inb(dev->iobase+RTI800_9513A_STATUS)
 
@@ -131,21 +132,21 @@
 
 #define this_board ((const struct rti800_board *)dev->board_ptr)
 
-static int rti800_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int rti800_detach(struct comedi_device * dev);
+static int rti800_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int rti800_detach(struct comedi_device *dev);
 static struct comedi_driver driver_rti800 = {
-      driver_name:"rti800",
-      module:THIS_MODULE,
-      attach:rti800_attach,
-      detach:rti800_detach,
-      num_names:sizeof(boardtypes) / sizeof(struct rti800_board),
-      board_name:&boardtypes[0].name,
-      offset:sizeof(struct rti800_board),
+	.driver_name = "rti800",
+	.module = THIS_MODULE,
+	.attach = rti800_attach,
+	.detach = rti800_detach,
+	.num_names = ARRAY_SIZE(boardtypes),
+	.board_name = &boardtypes[0].name,
+	.offset = sizeof(struct rti800_board),
 };
 
 COMEDI_INITCLEANUP(driver_rti800);
 
-static irqreturn_t rti800_interrupt(int irq, void *dev PT_REGS_ARG);
+static irqreturn_t rti800_interrupt(int irq, void *dev);
 
 struct rti800_private {
 	enum {
@@ -172,16 +173,16 @@
 
 #define RTI800_TIMEOUT 100
 
-static irqreturn_t rti800_interrupt(int irq, void *dev PT_REGS_ARG)
+static irqreturn_t rti800_interrupt(int irq, void *dev)
 {
 	return IRQ_HANDLED;
 }
 
-// settling delay times in usec for different gains
+/* settling delay times in usec for different gains */
 static const int gaindelay[] = { 10, 20, 40, 80 };
 
-static int rti800_ai_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int rti800_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, t;
 	int status;
@@ -199,9 +200,8 @@
 		/* without a delay here, the RTI_OVERRUN bit
 		 * gets set, and you will have an error. */
 		if (insn->n > 0) {
-			BUG_ON(gain >=
-				sizeof(gaindelay) / sizeof(gaindelay[0]));
-			comedi_udelay(gaindelay[gain]);
+			BUG_ON(gain >= ARRAY_SIZE(gaindelay));
+			udelay(gaindelay[gain]);
 		}
 	}
 
@@ -210,16 +210,16 @@
 		for (t = RTI800_TIMEOUT; t; t--) {
 			status = inb(dev->iobase + RTI800_CSR);
 			if (status & RTI800_OVERRUN) {
-				rt_printk("rti800: a/d overrun\n");
+				printk("rti800: a/d overrun\n");
 				outb(0, dev->iobase + RTI800_CLRFLAGS);
 				return -EIO;
 			}
 			if (status & RTI800_DONE)
 				break;
-			comedi_udelay(1);
+			udelay(1);
 		}
 		if (t == 0) {
-			rt_printk("rti800: timeout\n");
+			printk("rti800: timeout\n");
 			return -ETIME;
 		}
 		data[i] = inb(dev->iobase + RTI800_ADCLO);
@@ -233,8 +233,8 @@
 	return i;
 }
 
-static int rti800_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int rti800_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -245,8 +245,8 @@
 	return i;
 }
 
-static int rti800_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int rti800_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 	int d;
@@ -265,8 +265,8 @@
 	return i;
 }
 
-static int rti800_di_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int rti800_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -274,8 +274,8 @@
 	return 2;
 }
 
-static int rti800_do_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int rti800_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -309,7 +309,7 @@
    options[8] - dac1 coding
  */
 
-static int rti800_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int rti800_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	unsigned int irq;
 	unsigned long iobase;
@@ -339,8 +339,8 @@
 	irq = it->options[1];
 	if (irq) {
 		printk("( irq = %u )", irq);
-		if ((ret = comedi_request_irq(irq, rti800_interrupt, 0,
-					"rti800", dev)) < 0) {
+		ret = request_irq(irq, rti800_interrupt, 0, "rti800", dev);
+		if (ret < 0) {
 			printk(" Failed to allocate IRQ\n");
 			return ret;
 		}
@@ -351,9 +351,12 @@
 
 	dev->board_name = this_board->name;
 
-	if ((ret = alloc_subdevices(dev, 4)) < 0)
+	ret = alloc_subdevices(dev, 4);
+	if (ret < 0)
 		return ret;
-	if ((ret = alloc_private(dev, sizeof(struct rti800_private))) < 0)
+
+	ret = alloc_private(dev, sizeof(struct rti800_private));
+	if (ret < 0)
 		return ret;
 
 	devpriv->adc_mux = it->options[2];
@@ -444,7 +447,7 @@
 	return 0;
 }
 
-static int rti800_detach(struct comedi_device * dev)
+static int rti800_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: rti800: remove\n", dev->minor);
 
@@ -452,7 +455,7 @@
 		release_region(dev->iobase, RTI800_SIZE);
 
 	if (dev->irq)
-		comedi_free_irq(dev->irq, dev);
+		free_irq(dev->irq, dev);
 
 	return 0;
 }
diff --git a/drivers/staging/comedi/drivers/rti802.c b/drivers/staging/comedi/drivers/rti802.c
index cc2c385..fffde45 100644
--- a/drivers/staging/comedi/drivers/rti802.c
+++ b/drivers/staging/comedi/drivers/rti802.c
@@ -47,13 +47,13 @@
 #define RTI802_DATALOW 1
 #define RTI802_DATAHIGH 2
 
-static int rti802_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int rti802_detach(struct comedi_device * dev);
+static int rti802_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int rti802_detach(struct comedi_device *dev);
 static struct comedi_driver driver_rti802 = {
-      driver_name:"rti802",
-      module:THIS_MODULE,
-      attach:rti802_attach,
-      detach:rti802_detach,
+	.driver_name = "rti802",
+	.module = THIS_MODULE,
+	.attach = rti802_attach,
+	.detach = rti802_detach,
 };
 
 COMEDI_INITCLEANUP(driver_rti802);
@@ -68,8 +68,8 @@
 
 #define devpriv ((struct rti802_private *)dev->private)
 
-static int rti802_ao_insn_read(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int rti802_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 
@@ -79,8 +79,8 @@
 	return i;
 }
 
-static int rti802_ao_insn_write(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int rti802_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i, d;
 	int chan = CR_CHAN(insn->chanspec);
@@ -96,7 +96,7 @@
 	return i;
 }
 
-static int rti802_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int rti802_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int i;
@@ -140,7 +140,7 @@
 	return 0;
 }
 
-static int rti802_detach(struct comedi_device * dev)
+static int rti802_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: rti802: remove\n", dev->minor);
 
diff --git a/drivers/staging/comedi/drivers/s526.c b/drivers/staging/comedi/drivers/s526.c
index a7b6f71..d9509d7 100644
--- a/drivers/staging/comedi/drivers/s526.c
+++ b/drivers/staging/comedi/drivers/s526.c
@@ -169,14 +169,14 @@
 
 static const struct s526_board s526_boards[] = {
 	{
-	      name:	"s526",
-	      gpct_chans:4,
-	      gpct_bits:24,
-	      ad_chans:8,
-	      ad_bits:	16,
-	      da_chans:4,
-	      da_bits:	16,
-	      have_dio:1,
+	.name = "s526",
+	.gpct_chans = 4,
+	.gpct_bits = 24,
+	.ad_chans = 8,
+	.ad_bits = 16,
+	.da_chans = 4,
+	.da_bits = 16,
+	.have_dio = 1,
 		}
 };
 
@@ -217,13 +217,13 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int s526_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int s526_detach(struct comedi_device * dev);
+static int s526_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int s526_detach(struct comedi_device *dev);
 static struct comedi_driver driver_s526 = {
-      driver_name:"s526",
-      module:THIS_MODULE,
-      attach:s526_attach,
-      detach:s526_detach,
+	.driver_name = "s526",
+	.module = THIS_MODULE,
+	.attach = s526_attach,
+	.detach = s526_detach,
 /* It is not necessary to implement the following members if you are
  * writing a driver for a ISA PnP or PCI card */
 	/* Most drivers will support multiple types of boards by
@@ -242,29 +242,29 @@
 	 * the type of board in software.  ISA PnP, PCI, and PCMCIA
 	 * devices are such boards.
 	 */
-      board_name:&s526_boards[0].name,
-      offset:sizeof(struct s526_board),
-      num_names:sizeof(s526_boards) / sizeof(struct s526_board),
+	.board_name = &s526_boards[0].name,
+	.offset = sizeof(struct s526_board),
+	.num_names = ARRAY_SIZE(s526_boards),
 };
 
-static int s526_gpct_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int s526_gpct_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int s526_gpct_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int s526_ai_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int s526_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int s526_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int s526_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int s526_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int s526_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int s526_gpct_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int s526_gpct_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int s526_gpct_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int s526_ai_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int s526_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int s526_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int s526_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int s526_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int s526_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 /*
  * Attach is called by the Comedi core to configure the driver
@@ -272,13 +272,13 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int s526_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int s526_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 	int iobase;
 	int i, n;
-//      short value;
-//      int subdev_channel = 0;
+/* short value; */
+/* int subdev_channel = 0; */
 
 	printk("comedi%d: s526: ", dev->minor);
 
@@ -334,12 +334,12 @@
 	/* Command are not implemented yet, however they are necessary to
 	   allocate the necessary memory for the comedi_async struct (used
 	   to trigger the GPCT in case of pulsegenerator function */
-	//s->do_cmd = s526_gpct_cmd;
-	//s->do_cmdtest = s526_gpct_cmdtest;
-	//s->cancel = s526_gpct_cancel;
+	/* s->do_cmd = s526_gpct_cmd; */
+	/* s->do_cmdtest = s526_gpct_cmdtest; */
+	/* s->cancel = s526_gpct_cancel; */
 
 	s = dev->subdevices + 1;
-	//dev->read_subdev=s;
+	/* dev->read_subdev=s; */
 	/* analog input subdevice */
 	s->type = COMEDI_SUBD_AI;
 	/* we support differential */
@@ -383,18 +383,18 @@
 	return 1;
 
 #if 0
-	// Example of Counter Application
-	//One-shot (software trigger)
-	cmReg.reg.coutSource = 0;	// out RCAP
-	cmReg.reg.coutPolarity = 1;	// Polarity inverted
-	cmReg.reg.autoLoadResetRcap = 1;	// Auto load 0:disabled, 1:enabled
-	cmReg.reg.hwCtEnableSource = 3;	// NOT RCAP
-	cmReg.reg.ctEnableCtrl = 2;	// Hardware
-	cmReg.reg.clockSource = 2;	// Internal
-	cmReg.reg.countDir = 1;	// Down
-	cmReg.reg.countDirCtrl = 1;	// Software
-	cmReg.reg.outputRegLatchCtrl = 0;	// latch on read
-	cmReg.reg.preloadRegSel = 0;	// PR0
+	/*  Example of Counter Application */
+	/* One-shot (software trigger) */
+	cmReg.reg.coutSource = 0;	/*  out RCAP */
+	cmReg.reg.coutPolarity = 1;	/*  Polarity inverted */
+	cmReg.reg.autoLoadResetRcap = 1;	/*  Auto load 0:disabled, 1:enabled */
+	cmReg.reg.hwCtEnableSource = 3;	/*  NOT RCAP */
+	cmReg.reg.ctEnableCtrl = 2;	/*  Hardware */
+	cmReg.reg.clockSource = 2;	/*  Internal */
+	cmReg.reg.countDir = 1;	/*  Down */
+	cmReg.reg.countDirCtrl = 1;	/*  Software */
+	cmReg.reg.outputRegLatchCtrl = 0;	/*  latch on read */
+	cmReg.reg.preloadRegSel = 0;	/*  PR0 */
 	cmReg.reg.reserved = 0;
 
 	outw(cmReg.value, ADDR_CHAN_REG(REG_C0M, subdev_channel));
@@ -402,24 +402,24 @@
 	outw(0x0001, ADDR_CHAN_REG(REG_C0H, subdev_channel));
 	outw(0x3C68, ADDR_CHAN_REG(REG_C0L, subdev_channel));
 
-	outw(0x8000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	// Reset the counter
-	outw(0x4000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	// Load the counter from PR0
+	outw(0x8000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	/*  Reset the counter */
+	outw(0x4000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	/*  Load the counter from PR0 */
 
-	outw(0x0008, ADDR_CHAN_REG(REG_C0C, subdev_channel));	// Reset RCAP (fires one-shot)
+	outw(0x0008, ADDR_CHAN_REG(REG_C0C, subdev_channel));	/*  Reset RCAP (fires one-shot) */
 
 #else
 
-	// Set Counter Mode Register
-	cmReg.reg.coutSource = 0;	// out RCAP
-	cmReg.reg.coutPolarity = 0;	// Polarity inverted
-	cmReg.reg.autoLoadResetRcap = 0;	// Auto load disabled
-	cmReg.reg.hwCtEnableSource = 2;	// NOT RCAP
-	cmReg.reg.ctEnableCtrl = 1;	// 1: Software,  >1 : Hardware
-	cmReg.reg.clockSource = 3;	// x4
-	cmReg.reg.countDir = 0;	// up
-	cmReg.reg.countDirCtrl = 0;	// quadrature
-	cmReg.reg.outputRegLatchCtrl = 0;	// latch on read
-	cmReg.reg.preloadRegSel = 0;	// PR0
+	/*  Set Counter Mode Register */
+	cmReg.reg.coutSource = 0;	/*  out RCAP */
+	cmReg.reg.coutPolarity = 0;	/*  Polarity inverted */
+	cmReg.reg.autoLoadResetRcap = 0;	/*  Auto load disabled */
+	cmReg.reg.hwCtEnableSource = 2;	/*  NOT RCAP */
+	cmReg.reg.ctEnableCtrl = 1;	/*  1: Software,  >1 : Hardware */
+	cmReg.reg.clockSource = 3;	/*  x4 */
+	cmReg.reg.countDir = 0;	/*  up */
+	cmReg.reg.countDirCtrl = 0;	/*  quadrature */
+	cmReg.reg.outputRegLatchCtrl = 0;	/*  latch on read */
+	cmReg.reg.preloadRegSel = 0;	/*  PR0 */
 	cmReg.reg.reserved = 0;
 
 	n = 0;
@@ -429,21 +429,21 @@
 	udelay(1000);
 	printk("Read back mode reg=0x%04x\n", inw(ADDR_CHAN_REG(REG_C0M, n)));
 
-	// Load the pre-laod register high word
-//                      value = (short) (0x55);
-//                      outw(value, ADDR_CHAN_REG(REG_C0H, n));
+	/*  Load the pre-laod register high word */
+/* value = (short) (0x55); */
+/* outw(value, ADDR_CHAN_REG(REG_C0H, n)); */
 
-	// Load the pre-laod register low word
-//                      value = (short)(0xaa55);
-//                      outw(value, ADDR_CHAN_REG(REG_C0L, n));
+	/*  Load the pre-laod register low word */
+/* value = (short)(0xaa55); */
+/* outw(value, ADDR_CHAN_REG(REG_C0L, n)); */
 
-	// Write the Counter Control Register
-//                      outw(value, ADDR_CHAN_REG(REG_C0C, 0));
+	/*  Write the Counter Control Register */
+/* outw(value, ADDR_CHAN_REG(REG_C0C, 0)); */
 
-	// Reset the counter if it is software preload
+	/*  Reset the counter if it is software preload */
 	if (cmReg.reg.autoLoadResetRcap == 0) {
-		outw(0x8000, ADDR_CHAN_REG(REG_C0C, n));	// Reset the counter
-		outw(0x4000, ADDR_CHAN_REG(REG_C0C, n));	// Load the counter from PR0
+		outw(0x8000, ADDR_CHAN_REG(REG_C0C, n));	/*  Reset the counter */
+		outw(0x4000, ADDR_CHAN_REG(REG_C0C, n));	/*  Load the counter from PR0 */
 	}
 
 	outw(cmReg.value, ADDR_CHAN_REG(REG_C0M, n));
@@ -468,7 +468,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int s526_detach(struct comedi_device * dev)
+static int s526_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: s526: remove\n", dev->minor);
 
@@ -478,47 +478,47 @@
 	return 0;
 }
 
-static int s526_gpct_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int s526_gpct_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	int i;			// counts the Data
+	int i;			/*  counts the Data */
 	int counter_channel = CR_CHAN(insn->chanspec);
 	unsigned short datalow;
 	unsigned short datahigh;
 
-	// Check if (n > 0)
+	/*  Check if (n > 0) */
 	if (insn->n <= 0) {
 		printk("s526: INSN_READ: n should be > 0\n");
 		return -EINVAL;
 	}
-	// Read the low word first
+	/*  Read the low word first */
 	for (i = 0; i < insn->n; i++) {
 		datalow = inw(ADDR_CHAN_REG(REG_C0L, counter_channel));
 		datahigh = inw(ADDR_CHAN_REG(REG_C0H, counter_channel));
 		data[i] = (int)(datahigh & 0x00FF);
 		data[i] = (data[i] << 16) | (datalow & 0xFFFF);
-//              printk("s526 GPCT[%d]: %x(0x%04x, 0x%04x)\n", counter_channel, data[i], datahigh, datalow);
+/* printk("s526 GPCT[%d]: %x(0x%04x, 0x%04x)\n", counter_channel, data[i], datahigh, datalow); */
 	}
 	return i;
 }
 
-static int s526_gpct_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int s526_gpct_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	int subdev_channel = CR_CHAN(insn->chanspec);	// Unpack chanspec
+	int subdev_channel = CR_CHAN(insn->chanspec);	/*  Unpack chanspec */
 	int i;
 	short value;
 
-//        printk("s526: GPCT_INSN_CONFIG: Configuring Channel %d\n", subdev_channel);
+/* printk("s526: GPCT_INSN_CONFIG: Configuring Channel %d\n", subdev_channel); */
 
 	for (i = 0; i < MAX_GPCT_CONFIG_DATA; i++) {
 		devpriv->s526_gpct_config[subdev_channel].data[i] =
 			insn->data[i];
-//              printk("data[%d]=%x\n", i, insn->data[i]);
+/* printk("data[%d]=%x\n", i, insn->data[i]); */
 	}
 
-	// Check what type of Counter the user requested, data[0] contains
-	// the Application type
+	/*  Check what type of Counter the user requested, data[0] contains */
+	/*  the Application type */
 	switch (insn->data[0]) {
 	case INSN_CONFIG_GPCT_QUADRATURE_ENCODER:
 		/*
@@ -531,19 +531,19 @@
 		devpriv->s526_gpct_config[subdev_channel].app =
 			PositionMeasurement;
 
-/*
-			// Example of Counter Application
-			//One-shot (software trigger)
-			cmReg.reg.coutSource		= 0; // out RCAP
-			cmReg.reg.coutPolarity		= 1; // Polarity inverted
-			cmReg.reg.autoLoadResetRcap	= 0; // Auto load disabled
-			cmReg.reg.hwCtEnableSource	= 3; // NOT RCAP
-			cmReg.reg.ctEnableCtrl		= 2; // Hardware
-			cmReg.reg.clockSource		= 2; // Internal
-			cmReg.reg.countDir		= 1; // Down
-			cmReg.reg.countDirCtrl		= 1; // Software
-			cmReg.reg.outputRegLatchCtrl	= 0; // latch on read
-			cmReg.reg.preloadRegSel		= 0; // PR0
+#if 0
+			/*  Example of Counter Application */
+			/* One-shot (software trigger) */
+			cmReg.reg.coutSource		= 0; /*  out RCAP */
+			cmReg.reg.coutPolarity		= 1; /*  Polarity inverted */
+			cmReg.reg.autoLoadResetRcap	= 0; /*  Auto load disabled */
+			cmReg.reg.hwCtEnableSource	= 3; /*  NOT RCAP */
+			cmReg.reg.ctEnableCtrl		= 2; /*  Hardware */
+			cmReg.reg.clockSource		= 2; /*  Internal */
+			cmReg.reg.countDir		= 1; /*  Down */
+			cmReg.reg.countDirCtrl		= 1; /*  Software */
+			cmReg.reg.outputRegLatchCtrl	= 0; /*  latch on read */
+			cmReg.reg.preloadRegSel		= 0; /*  PR0 */
 			cmReg.reg.reserved		= 0;
 
 			outw(cmReg.value, ADDR_CHAN_REG(REG_C0M, subdev_channel));
@@ -551,40 +551,40 @@
 			outw(0x0001, ADDR_CHAN_REG(REG_C0H, subdev_channel));
 			outw(0x3C68, ADDR_CHAN_REG(REG_C0L, subdev_channel));
 
-			outw(0x8000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	// Reset the counter
-			outw(0x4000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	// Load the counter from PR0
+			outw(0x8000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	/*  Reset the counter */
+			outw(0x4000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	/*  Load the counter from PR0 */
 
-			outw(0x0008, ADDR_CHAN_REG(REG_C0C, subdev_channel));  // Reset RCAP (fires one-shot)
+			outw(0x0008, ADDR_CHAN_REG(REG_C0C, subdev_channel));  /*  Reset RCAP (fires one-shot) */
 
-*/
+#endif
 
 #if 1
-		// Set Counter Mode Register
-		cmReg.reg.coutSource = 0;	// out RCAP
-		cmReg.reg.coutPolarity = 0;	// Polarity inverted
-		cmReg.reg.autoLoadResetRcap = 0;	// Auto load disabled
-		cmReg.reg.hwCtEnableSource = 2;	// NOT RCAP
-		cmReg.reg.ctEnableCtrl = 1;	// 1: Software,  >1 : Hardware
-		cmReg.reg.clockSource = 3;	// x4
-		cmReg.reg.countDir = 0;	// up
-		cmReg.reg.countDirCtrl = 0;	// quadrature
-		cmReg.reg.outputRegLatchCtrl = 0;	// latch on read
-		cmReg.reg.preloadRegSel = 0;	// PR0
+		/*  Set Counter Mode Register */
+		cmReg.reg.coutSource = 0;	/*  out RCAP */
+		cmReg.reg.coutPolarity = 0;	/*  Polarity inverted */
+		cmReg.reg.autoLoadResetRcap = 0;	/*  Auto load disabled */
+		cmReg.reg.hwCtEnableSource = 2;	/*  NOT RCAP */
+		cmReg.reg.ctEnableCtrl = 1;	/*  1: Software,  >1 : Hardware */
+		cmReg.reg.clockSource = 3;	/*  x4 */
+		cmReg.reg.countDir = 0;	/*  up */
+		cmReg.reg.countDirCtrl = 0;	/*  quadrature */
+		cmReg.reg.outputRegLatchCtrl = 0;	/*  latch on read */
+		cmReg.reg.preloadRegSel = 0;	/*  PR0 */
 		cmReg.reg.reserved = 0;
 
-		// Set Counter Mode Register
-//                      printk("s526: Counter Mode register=%x\n", cmReg.value);
+		/*  Set Counter Mode Register */
+/* printk("s526: Counter Mode register=%x\n", cmReg.value); */
 		outw(cmReg.value, ADDR_CHAN_REG(REG_C0M, subdev_channel));
 
-		// Reset the counter if it is software preload
+		/*  Reset the counter if it is software preload */
 		if (cmReg.reg.autoLoadResetRcap == 0) {
-			outw(0x8000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	// Reset the counter
-//                              outw(0x4000, ADDR_CHAN_REG(REG_C0C, subdev_channel));   // Load the counter from PR0
+			outw(0x8000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	/*  Reset the counter */
+/* outw(0x4000, ADDR_CHAN_REG(REG_C0C, subdev_channel));    Load the counter from PR0 */
 		}
 #else
-		cmReg.reg.countDirCtrl = 0;	// 0 quadrature, 1 software control
+		cmReg.reg.countDirCtrl = 0;	/*  0 quadrature, 1 software control */
 
-		// data[1] contains GPCT_X1, GPCT_X2 or GPCT_X4
+		/*  data[1] contains GPCT_X1, GPCT_X2 or GPCT_X4 */
 		if (insn->data[1] == GPCT_X2) {
 			cmReg.reg.clockSource = 1;
 		} else if (insn->data[1] == GPCT_X4) {
@@ -593,37 +593,37 @@
 			cmReg.reg.clockSource = 0;
 		}
 
-		// When to take into account the indexpulse:
+		/*  When to take into account the indexpulse: */
 		if (insn->data[2] == GPCT_IndexPhaseLowLow) {
 		} else if (insn->data[2] == GPCT_IndexPhaseLowHigh) {
 		} else if (insn->data[2] == GPCT_IndexPhaseHighLow) {
 		} else if (insn->data[2] == GPCT_IndexPhaseHighHigh) {
 		}
-		// Take into account the index pulse?
+		/*  Take into account the index pulse? */
 		if (insn->data[3] == GPCT_RESET_COUNTER_ON_INDEX)
-			cmReg.reg.autoLoadResetRcap = 4;	// Auto load with INDEX^
+			cmReg.reg.autoLoadResetRcap = 4;	/*  Auto load with INDEX^ */
 
-		// Set Counter Mode Register
+		/*  Set Counter Mode Register */
 		cmReg.value = (short) (insn->data[1] & 0xFFFF);
 		outw(cmReg.value, ADDR_CHAN_REG(REG_C0M, subdev_channel));
 
-		// Load the pre-laod register high word
+		/*  Load the pre-laod register high word */
 		value = (short) ((insn->data[2] >> 16) & 0xFFFF);
 		outw(value, ADDR_CHAN_REG(REG_C0H, subdev_channel));
 
-		// Load the pre-laod register low word
+		/*  Load the pre-laod register low word */
 		value = (short) (insn->data[2] & 0xFFFF);
 		outw(value, ADDR_CHAN_REG(REG_C0L, subdev_channel));
 
-		// Write the Counter Control Register
+		/*  Write the Counter Control Register */
 		if (insn->data[3] != 0) {
 			value = (short) (insn->data[3] & 0xFFFF);
 			outw(value, ADDR_CHAN_REG(REG_C0C, subdev_channel));
 		}
-		// Reset the counter if it is software preload
+		/*  Reset the counter if it is software preload */
 		if (cmReg.reg.autoLoadResetRcap == 0) {
-			outw(0x8000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	// Reset the counter
-			outw(0x4000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	// Load the counter from PR0
+			outw(0x8000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	/*  Reset the counter */
+			outw(0x4000, ADDR_CHAN_REG(REG_C0C, subdev_channel));	/*  Load the counter from PR0 */
 		}
 #endif
 		break;
@@ -640,33 +640,33 @@
 		devpriv->s526_gpct_config[subdev_channel].app =
 			SinglePulseGeneration;
 
-		// Set Counter Mode Register
+		/*  Set Counter Mode Register */
 		cmReg.value = (short) (insn->data[1] & 0xFFFF);
-		cmReg.reg.preloadRegSel = 0;	// PR0
+		cmReg.reg.preloadRegSel = 0;	/*  PR0 */
 		outw(cmReg.value, ADDR_CHAN_REG(REG_C0M, subdev_channel));
 
-		// Load the pre-laod register 0 high word
+		/*  Load the pre-laod register 0 high word */
 		value = (short) ((insn->data[2] >> 16) & 0xFFFF);
 		outw(value, ADDR_CHAN_REG(REG_C0H, subdev_channel));
 
-		// Load the pre-laod register 0 low word
+		/*  Load the pre-laod register 0 low word */
 		value = (short) (insn->data[2] & 0xFFFF);
 		outw(value, ADDR_CHAN_REG(REG_C0L, subdev_channel));
 
-		// Set Counter Mode Register
+		/*  Set Counter Mode Register */
 		cmReg.value = (short) (insn->data[1] & 0xFFFF);
-		cmReg.reg.preloadRegSel = 1;	// PR1
+		cmReg.reg.preloadRegSel = 1;	/*  PR1 */
 		outw(cmReg.value, ADDR_CHAN_REG(REG_C0M, subdev_channel));
 
-		// Load the pre-laod register 1 high word
+		/*  Load the pre-laod register 1 high word */
 		value = (short) ((insn->data[3] >> 16) & 0xFFFF);
 		outw(value, ADDR_CHAN_REG(REG_C0H, subdev_channel));
 
-		// Load the pre-laod register 1 low word
+		/*  Load the pre-laod register 1 low word */
 		value = (short) (insn->data[3] & 0xFFFF);
 		outw(value, ADDR_CHAN_REG(REG_C0L, subdev_channel));
 
-		// Write the Counter Control Register
+		/*  Write the Counter Control Register */
 		if (insn->data[3] != 0) {
 			value = (short) (insn->data[3] & 0xFFFF);
 			outw(value, ADDR_CHAN_REG(REG_C0C, subdev_channel));
@@ -685,33 +685,33 @@
 		devpriv->s526_gpct_config[subdev_channel].app =
 			PulseTrainGeneration;
 
-		// Set Counter Mode Register
+		/*  Set Counter Mode Register */
 		cmReg.value = (short) (insn->data[1] & 0xFFFF);
-		cmReg.reg.preloadRegSel = 0;	// PR0
+		cmReg.reg.preloadRegSel = 0;	/*  PR0 */
 		outw(cmReg.value, ADDR_CHAN_REG(REG_C0M, subdev_channel));
 
-		// Load the pre-laod register 0 high word
+		/*  Load the pre-laod register 0 high word */
 		value = (short) ((insn->data[2] >> 16) & 0xFFFF);
 		outw(value, ADDR_CHAN_REG(REG_C0H, subdev_channel));
 
-		// Load the pre-laod register 0 low word
+		/*  Load the pre-laod register 0 low word */
 		value = (short) (insn->data[2] & 0xFFFF);
 		outw(value, ADDR_CHAN_REG(REG_C0L, subdev_channel));
 
-		// Set Counter Mode Register
+		/*  Set Counter Mode Register */
 		cmReg.value = (short) (insn->data[1] & 0xFFFF);
-		cmReg.reg.preloadRegSel = 1;	// PR1
+		cmReg.reg.preloadRegSel = 1;	/*  PR1 */
 		outw(cmReg.value, ADDR_CHAN_REG(REG_C0M, subdev_channel));
 
-		// Load the pre-laod register 1 high word
+		/*  Load the pre-laod register 1 high word */
 		value = (short) ((insn->data[3] >> 16) & 0xFFFF);
 		outw(value, ADDR_CHAN_REG(REG_C0H, subdev_channel));
 
-		// Load the pre-laod register 1 low word
+		/*  Load the pre-laod register 1 low word */
 		value = (short) (insn->data[3] & 0xFFFF);
 		outw(value, ADDR_CHAN_REG(REG_C0L, subdev_channel));
 
-		// Write the Counter Control Register
+		/*  Write the Counter Control Register */
 		if (insn->data[3] != 0) {
 			value = (short) (insn->data[3] & 0xFFFF);
 			outw(value, ADDR_CHAN_REG(REG_C0C, subdev_channel));
@@ -727,16 +727,16 @@
 	return insn->n;
 }
 
-static int s526_gpct_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int s526_gpct_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
-	int subdev_channel = CR_CHAN(insn->chanspec);	// Unpack chanspec
+	int subdev_channel = CR_CHAN(insn->chanspec);	/*  Unpack chanspec */
 	short value;
 
 	printk("s526: GPCT_INSN_WRITE on channel %d\n", subdev_channel);
 	cmReg.value = inw(ADDR_CHAN_REG(REG_C0M, subdev_channel));
 	printk("s526: Counter Mode Register: %x\n", cmReg.value);
-	// Check what Application of Counter this channel is configured for
+	/*  Check what Application of Counter this channel is configured for */
 	switch (devpriv->s526_gpct_config[subdev_channel].app) {
 	case PositionMeasurement:
 		printk("S526: INSN_WRITE: PM\n");
@@ -776,18 +776,18 @@
 		value = (short) (*data & 0xFFFF);
 		outw(value, ADDR_CHAN_REG(REG_C0L, subdev_channel));
 		break;
-	default:		// Impossible
+	default:		/*  Impossible */
 		printk("s526: INSN_WRITE: Functionality %d not implemented yet\n", devpriv->s526_gpct_config[subdev_channel].app);
 		return -EINVAL;
 		break;
 	}
-	// return the number of samples written
+	/*  return the number of samples written */
 	return insn->n;
 }
 
 #define ISR_ADC_DONE 0x4
-static int s526_ai_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int s526_ai_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int result = -EINVAL;
 
@@ -803,14 +803,14 @@
 	 * enable channels here.  The channel should be enabled in the
 	 * INSN_READ handler. */
 
-	// Enable ADC interrupt
+	/*  Enable ADC interrupt */
 	outw(ISR_ADC_DONE, ADDR_REG(REG_IER));
-//      printk("s526: ADC current value: 0x%04x\n", inw(ADDR_REG(REG_ADC)));
+/* printk("s526: ADC current value: 0x%04x\n", inw(ADDR_REG(REG_ADC))); */
 	devpriv->s526_ai_config = (data[0] & 0x3FF) << 5;
 	if (data[1] > 0)
-		devpriv->s526_ai_config |= 0x8000;	//set the delay
+		devpriv->s526_ai_config |= 0x8000;	/* set the delay */
 
-	devpriv->s526_ai_config |= 0x0001;	// ADC start bit.
+	devpriv->s526_ai_config |= 0x0001;	/*  ADC start bit. */
 
 	return result;
 }
@@ -819,8 +819,8 @@
  * "instructions" read/write data in "one-shot" or "software-triggered"
  * mode.
  */
-static int s526_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int s526_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -837,8 +837,8 @@
 	for (n = 0; n < insn->n; n++) {
 		/* trigger conversion */
 		outw(value, ADDR_REG(REG_ADC));
-//              printk("s526: Wrote 0x%04x to ADC\n", value);
-//              printk("s526: ADC reg=0x%04x\n", inw(ADDR_REG(REG_ADC)));
+/* printk("s526: Wrote 0x%04x to ADC\n", value); */
+/* printk("s526: ADC reg=0x%04x\n", inw(ADDR_REG(REG_ADC))); */
 
 #define TIMEOUT 100
 		/* wait for conversion to end */
@@ -850,16 +850,16 @@
 			}
 		}
 		if (i == TIMEOUT) {
-			/* rt_printk() should be used instead of printk()
+			/* printk() should be used instead of printk()
 			 * whenever the code can be called from real-time. */
-			rt_printk("s526: ADC(0x%04x) timeout\n",
+			printk("s526: ADC(0x%04x) timeout\n",
 				inw(ADDR_REG(REG_ISR)));
 			return -ETIMEDOUT;
 		}
 
 		/* read data */
 		d = inw(ADDR_REG(REG_ADD));
-//              printk("AI[%d]=0x%04x\n", n, (unsigned short)(d & 0xFFFF));
+/* printk("AI[%d]=0x%04x\n", n, (unsigned short)(d & 0xFFFF)); */
 
 		/* munge data */
 		data[n] = d ^ 0x8000;
@@ -869,27 +869,27 @@
 	return n;
 }
 
-static int s526_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int s526_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
 	unsigned short val;
 
-//      printk("s526_ao_winsn\n");
+/* printk("s526_ao_winsn\n"); */
 	val = chan << 1;
-//      outw(val, dev->iobase + REG_DAC);
+/* outw(val, dev->iobase + REG_DAC); */
 	outw(val, ADDR_REG(REG_DAC));
 
 	/* Writing a list of values to an AO channel is probably not
 	 * very useful, but that's how the interface is defined. */
 	for (i = 0; i < insn->n; i++) {
 		/* a typical programming sequence */
-//              outw(data[i], dev->iobase + REG_ADD);  // write the data to preload register
-		outw(data[i], ADDR_REG(REG_ADD));	// write the data to preload register
+/* outw(data[i], dev->iobase + REG_ADD);    write the data to preload register */
+		outw(data[i], ADDR_REG(REG_ADD));	/*  write the data to preload register */
 		devpriv->ao_readback[chan] = data[i];
-//              outw(val + 1, dev->iobase + REG_DAC); // starts the D/A conversion.
-		outw(val + 1, ADDR_REG(REG_DAC));	// starts the D/A conversion.
+/* outw(val + 1, dev->iobase + REG_DAC);  starts the D/A conversion. */
+		outw(val + 1, ADDR_REG(REG_DAC));	/*  starts the D/A conversion. */
 	}
 
 	/* return the number of samples read/written */
@@ -898,8 +898,8 @@
 
 /* AO subdevices should have a read insn as well as a write insn.
  * Usually this means copying a value stored in devpriv. */
-static int s526_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int s526_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -915,8 +915,8 @@
  * useful to applications if you implement the insn_bits interface.
  * This allows packed reading/writing of the DIO channels.  The
  * comedi core can convert between insn_bits and insn_read/write */
-static int s526_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int s526_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -932,16 +932,16 @@
 
 	/* on return, data[1] contains the value of the digital
 	 * input and output lines. */
-	data[1] = inw(ADDR_REG(REG_DIO)) & 0xFF;	// low 8 bits are the data
+	data[1] = inw(ADDR_REG(REG_DIO)) & 0xFF;	/*  low 8 bits are the data */
 	/* or we could just return the software copy of the output values if
 	 * it was a purely digital output subdevice */
-	//data[1]=s->state;
+	/* data[1]=s->state; */
 
 	return 2;
 }
 
-static int s526_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int s526_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 	short value;
@@ -959,10 +959,10 @@
 	 * value COMEDI_INPUT or COMEDI_OUTPUT. */
 
 	if (data[0] == COMEDI_OUTPUT) {
-		value |= 1 << (chan + 10);	// bit 10/11 set the group 1/2's mode
+		value |= 1 << (chan + 10);	/*  bit 10/11 set the group 1/2's mode */
 		s->io_bits |= (0xF << chan);
 	} else {
-		value &= ~(1 << (chan + 10));	// 1 is output, 0 is input.
+		value &= ~(1 << (chan + 10));	/*  1 is output, 0 is input. */
 		s->io_bits &= ~(0xF << chan);
 	}
 	outw(value, ADDR_REG(REG_DIO));
diff --git a/drivers/staging/comedi/drivers/s626.c b/drivers/staging/comedi/drivers/s626.c
index 30dec9d..92121cf 100644
--- a/drivers/staging/comedi/drivers/s626.c
+++ b/drivers/staging/comedi/drivers/s626.c
@@ -68,6 +68,7 @@
    comedi_do_insn(cf,&insn); //executing configuration
 */
 
+#include <linux/interrupt.h>
 #include <linux/kernel.h>
 #include <linux/types.h>
 
@@ -95,14 +96,14 @@
 
 static const struct s626_board s626_boards[] = {
 	{
-	      name:	"s626",
-	      ai_chans : S626_ADC_CHANNELS,
-	      ai_bits:	14,
-	      ao_chans : S626_DAC_CHANNELS,
-	      ao_bits:	13,
-	      dio_chans : S626_DIO_CHANNELS,
-	      dio_banks : S626_DIO_BANKS,
-	      enc_chans : S626_ENCODER_CHANNELS,
+	.name = "s626",
+	.ai_chans = S626_ADC_CHANNELS,
+	.ai_bits = 14,
+	.ao_chans = S626_DAC_CHANNELS,
+	.ao_bits = 13,
+	.dio_chans = S626_DIO_CHANNELS,
+	.dio_banks = S626_DIO_BANKS,
+	.enc_chans = S626_ENCODER_CHANNELS,
 		}
 };
 
@@ -122,10 +123,10 @@
 static int s626_detach(struct comedi_device *dev);
 
 static struct comedi_driver driver_s626 = {
-      driver_name:"s626",
-      module : THIS_MODULE,
-      attach : s626_attach,
-      detach : s626_detach,
+	.driver_name = "s626",
+	.module = THIS_MODULE,
+	.attach = s626_attach,
+	.detach = s626_detach,
 };
 
 struct s626_private {
@@ -173,39 +174,39 @@
 };
 
 static struct dio_private dio_private_A = {
-      RDDIn:LP_RDDINA,
-      WRDOut : LP_WRDOUTA,
-      RDEdgSel : LP_RDEDGSELA,
-      WREdgSel : LP_WREDGSELA,
-      RDCapSel : LP_RDCAPSELA,
-      WRCapSel : LP_WRCAPSELA,
-      RDCapFlg : LP_RDCAPFLGA,
-      RDIntSel : LP_RDINTSELA,
-      WRIntSel : LP_WRINTSELA,
+	.RDDIn = LP_RDDINA,
+	.WRDOut = LP_WRDOUTA,
+	.RDEdgSel = LP_RDEDGSELA,
+	.WREdgSel = LP_WREDGSELA,
+	.RDCapSel = LP_RDCAPSELA,
+	.WRCapSel = LP_WRCAPSELA,
+	.RDCapFlg = LP_RDCAPFLGA,
+	.RDIntSel = LP_RDINTSELA,
+	.WRIntSel = LP_WRINTSELA,
 };
 
 static struct dio_private dio_private_B = {
-      RDDIn:LP_RDDINB,
-      WRDOut : LP_WRDOUTB,
-      RDEdgSel : LP_RDEDGSELB,
-      WREdgSel : LP_WREDGSELB,
-      RDCapSel : LP_RDCAPSELB,
-      WRCapSel : LP_WRCAPSELB,
-      RDCapFlg : LP_RDCAPFLGB,
-      RDIntSel : LP_RDINTSELB,
-      WRIntSel : LP_WRINTSELB,
+	.RDDIn = LP_RDDINB,
+	.WRDOut = LP_WRDOUTB,
+	.RDEdgSel = LP_RDEDGSELB,
+	.WREdgSel = LP_WREDGSELB,
+	.RDCapSel = LP_RDCAPSELB,
+	.WRCapSel = LP_WRCAPSELB,
+	.RDCapFlg = LP_RDCAPFLGB,
+	.RDIntSel = LP_RDINTSELB,
+	.WRIntSel = LP_WRINTSELB,
 };
 
 static struct dio_private dio_private_C = {
-      RDDIn:LP_RDDINC,
-      WRDOut : LP_WRDOUTC,
-      RDEdgSel : LP_RDEDGSELC,
-      WREdgSel : LP_WREDGSELC,
-      RDCapSel : LP_RDCAPSELC,
-      WRCapSel : LP_WRCAPSELC,
-      RDCapFlg : LP_RDCAPFLGC,
-      RDIntSel : LP_RDINTSELC,
-      WRIntSel : LP_WRINTSELC,
+	.RDDIn = LP_RDDINC,
+	.WRDOut = LP_WRDOUTC,
+	.RDEdgSel = LP_RDEDGSELC,
+	.WREdgSel = LP_WREDGSELC,
+	.RDCapSel = LP_RDCAPSELC,
+	.WRCapSel = LP_WRCAPSELC,
+	.RDCapFlg = LP_RDCAPFLGC,
+	.RDIntSel = LP_RDINTSELC,
+	.WRIntSel = LP_WRINTSELC,
 };
 
 /* to group dio devices (48 bits mask and data are not allowed ???)
@@ -253,7 +254,7 @@
 static int s626_ai_load_polllist(uint8_t *ppl, struct comedi_cmd *cmd);
 static int s626_ai_inttrig(struct comedi_device *dev, struct comedi_subdevice *s,
 	unsigned int trignum);
-static irqreturn_t s626_irq_handler(int irq, void *d PT_REGS_ARG);
+static irqreturn_t s626_irq_handler(int irq, void *d);
 static unsigned int s626_ai_reg_to_uint(int data);
 /* static unsigned int s626_uint_to_reg(struct comedi_subdevice *s, int data); */
 
@@ -355,100 +356,100 @@
 /* struct enc_private; */
 static struct enc_private enc_private_data[] = {
 	{
-	      GetEnable:GetEnable_A,
-	      GetIntSrc : GetIntSrc_A,
-	      GetLoadTrig : GetLoadTrig_A,
-	      GetMode :	GetMode_A,
-	      PulseIndex : PulseIndex_A,
-	      SetEnable : SetEnable_A,
-	      SetIntSrc : SetIntSrc_A,
-	      SetLoadTrig : SetLoadTrig_A,
-	      SetMode :	SetMode_A,
-	      ResetCapFlags : ResetCapFlags_A,
-	      MyCRA :	LP_CR0A,
-	      MyCRB :	LP_CR0B,
-	      MyLatchLsw : LP_CNTR0ALSW,
-	      MyEventBits : EVBITS(0),
+	.GetEnable = GetEnable_A,
+	.GetIntSrc = GetIntSrc_A,
+	.GetLoadTrig = GetLoadTrig_A,
+	.GetMode = GetMode_A,
+	.PulseIndex = PulseIndex_A,
+	.SetEnable = SetEnable_A,
+	.SetIntSrc = SetIntSrc_A,
+	.SetLoadTrig = SetLoadTrig_A,
+	.SetMode = SetMode_A,
+	.ResetCapFlags = ResetCapFlags_A,
+	.MyCRA = LP_CR0A,
+	.MyCRB = LP_CR0B,
+	.MyLatchLsw = LP_CNTR0ALSW,
+	.MyEventBits = EVBITS(0),
 		},
 	{
-	      GetEnable:GetEnable_A,
-	      GetIntSrc : GetIntSrc_A,
-	      GetLoadTrig : GetLoadTrig_A,
-	      GetMode :	GetMode_A,
-	      PulseIndex : PulseIndex_A,
-	      SetEnable : SetEnable_A,
-	      SetIntSrc : SetIntSrc_A,
-	      SetLoadTrig : SetLoadTrig_A,
-	      SetMode :	SetMode_A,
-	      ResetCapFlags : ResetCapFlags_A,
-	      MyCRA :	LP_CR1A,
-	      MyCRB :	LP_CR1B,
-	      MyLatchLsw : LP_CNTR1ALSW,
-	      MyEventBits : EVBITS(1),
+	.GetEnable = GetEnable_A,
+	.GetIntSrc = GetIntSrc_A,
+	.GetLoadTrig = GetLoadTrig_A,
+	.GetMode = GetMode_A,
+	.PulseIndex = PulseIndex_A,
+	.SetEnable = SetEnable_A,
+	.SetIntSrc = SetIntSrc_A,
+	.SetLoadTrig = SetLoadTrig_A,
+	.SetMode = SetMode_A,
+	.ResetCapFlags = ResetCapFlags_A,
+	.MyCRA = LP_CR1A,
+	.MyCRB = LP_CR1B,
+	.MyLatchLsw = LP_CNTR1ALSW,
+	.MyEventBits = EVBITS(1),
 		},
 	{
-	      GetEnable:GetEnable_A,
-	      GetIntSrc : GetIntSrc_A,
-	      GetLoadTrig : GetLoadTrig_A,
-	      GetMode :	GetMode_A,
-	      PulseIndex : PulseIndex_A,
-	      SetEnable : SetEnable_A,
-	      SetIntSrc : SetIntSrc_A,
-	      SetLoadTrig : SetLoadTrig_A,
-	      SetMode :	SetMode_A,
-	      ResetCapFlags : ResetCapFlags_A,
-	      MyCRA :	LP_CR2A,
-	      MyCRB :	LP_CR2B,
-	      MyLatchLsw : LP_CNTR2ALSW,
-	      MyEventBits : EVBITS(2),
+	.GetEnable = GetEnable_A,
+	.GetIntSrc = GetIntSrc_A,
+	.GetLoadTrig = GetLoadTrig_A,
+	.GetMode = GetMode_A,
+	.PulseIndex = PulseIndex_A,
+	.SetEnable = SetEnable_A,
+	.SetIntSrc = SetIntSrc_A,
+	.SetLoadTrig = SetLoadTrig_A,
+	.SetMode = SetMode_A,
+	.ResetCapFlags = ResetCapFlags_A,
+	.MyCRA = LP_CR2A,
+	.MyCRB = LP_CR2B,
+	.MyLatchLsw = LP_CNTR2ALSW,
+	.MyEventBits = EVBITS(2),
 		},
 	{
-	      GetEnable:GetEnable_B,
-	      GetIntSrc : GetIntSrc_B,
-	      GetLoadTrig : GetLoadTrig_B,
-	      GetMode :	GetMode_B,
-	      PulseIndex : PulseIndex_B,
-	      SetEnable : SetEnable_B,
-	      SetIntSrc : SetIntSrc_B,
-	      SetLoadTrig : SetLoadTrig_B,
-	      SetMode :	SetMode_B,
-	      ResetCapFlags : ResetCapFlags_B,
-	      MyCRA :	LP_CR0A,
-	      MyCRB :	LP_CR0B,
-	      MyLatchLsw : LP_CNTR0BLSW,
-	      MyEventBits : EVBITS(3),
+	.GetEnable = GetEnable_B,
+	.GetIntSrc = GetIntSrc_B,
+	.GetLoadTrig = GetLoadTrig_B,
+	.GetMode = GetMode_B,
+	.PulseIndex = PulseIndex_B,
+	.SetEnable = SetEnable_B,
+	.SetIntSrc = SetIntSrc_B,
+	.SetLoadTrig = SetLoadTrig_B,
+	.SetMode = SetMode_B,
+	.ResetCapFlags = ResetCapFlags_B,
+	.MyCRA = LP_CR0A,
+	.MyCRB = LP_CR0B,
+	.MyLatchLsw = LP_CNTR0BLSW,
+	.MyEventBits = EVBITS(3),
 		},
 	{
-	      GetEnable:GetEnable_B,
-	      GetIntSrc : GetIntSrc_B,
-	      GetLoadTrig : GetLoadTrig_B,
-	      GetMode :	GetMode_B,
-	      PulseIndex : PulseIndex_B,
-	      SetEnable : SetEnable_B,
-	      SetIntSrc : SetIntSrc_B,
-	      SetLoadTrig : SetLoadTrig_B,
-	      SetMode :	SetMode_B,
-	      ResetCapFlags : ResetCapFlags_B,
-	      MyCRA :	LP_CR1A,
-	      MyCRB :	LP_CR1B,
-	      MyLatchLsw : LP_CNTR1BLSW,
-	      MyEventBits : EVBITS(4),
+	.GetEnable = GetEnable_B,
+	.GetIntSrc = GetIntSrc_B,
+	.GetLoadTrig = GetLoadTrig_B,
+	.GetMode = GetMode_B,
+	.PulseIndex = PulseIndex_B,
+	.SetEnable = SetEnable_B,
+	.SetIntSrc = SetIntSrc_B,
+	.SetLoadTrig = SetLoadTrig_B,
+	.SetMode = SetMode_B,
+	.ResetCapFlags = ResetCapFlags_B,
+	.MyCRA = LP_CR1A,
+	.MyCRB = LP_CR1B,
+	.MyLatchLsw = LP_CNTR1BLSW,
+	.MyEventBits = EVBITS(4),
 		},
 	{
-	      GetEnable:GetEnable_B,
-	      GetIntSrc : GetIntSrc_B,
-	      GetLoadTrig : GetLoadTrig_B,
-	      GetMode :	GetMode_B,
-	      PulseIndex : PulseIndex_B,
-	      SetEnable : SetEnable_B,
-	      SetIntSrc : SetIntSrc_B,
-	      SetLoadTrig : SetLoadTrig_B,
-	      SetMode :	SetMode_B,
-	      ResetCapFlags : ResetCapFlags_B,
-	      MyCRA :	LP_CR2A,
-	      MyCRB :	LP_CR2B,
-	      MyLatchLsw : LP_CNTR2BLSW,
-	      MyEventBits : EVBITS(5),
+	.GetEnable = GetEnable_B,
+	.GetIntSrc = GetIntSrc_B,
+	.GetLoadTrig = GetLoadTrig_B,
+	.GetMode = GetMode_B,
+	.PulseIndex = PulseIndex_B,
+	.SetEnable = SetEnable_B,
+	.SetIntSrc = SetIntSrc_B,
+	.SetLoadTrig = SetLoadTrig_B,
+	.SetMode = SetMode_B,
+	.ResetCapFlags = ResetCapFlags_B,
+	.MyCRA = LP_CR2A,
+	.MyCRB = LP_CR2B,
+	.MyLatchLsw = LP_CNTR2BLSW,
+	.MyEventBits = EVBITS(5),
 		},
 };
 
@@ -596,8 +597,8 @@
 	if (dev->irq == 0) {
 		printk(" unknown irq (bad)\n");
 	} else {
-		ret = comedi_request_irq(dev->irq, s626_irq_handler,
-					 IRQF_SHARED, "s626", dev);
+		ret = request_irq(dev->irq, s626_irq_handler, IRQF_SHARED,
+				  "s626", dev);
 
 		if (ret < 0) {
 			printk(" irq not available\n");
@@ -968,7 +969,7 @@
 /*   return 0; */
 /* } */
 
-static irqreturn_t s626_irq_handler(int irq, void *d PT_REGS_ARG)
+static irqreturn_t s626_irq_handler(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s;
@@ -987,7 +988,7 @@
 	if (dev->attached == 0)
 		return IRQ_NONE;
 	/*  lock to avoid race with comedi_poll */
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
+	spin_lock_irqsave(&dev->spinlock, flags);
 
 	/* save interrupt enable register state */
 	irqstatus = readl(devpriv->base_addr + P_IER);
@@ -1264,7 +1265,7 @@
 
 	DEBUG("s626_irq_handler: exit interrupt service routine.\n");
 
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
+	spin_unlock_irqrestore(&dev->spinlock, flags);
 	return IRQ_HANDLED;
 }
 
@@ -1291,7 +1292,7 @@
 		}
 
 		if (dev->irq)
-			comedi_free_irq(dev->irq, dev);
+			free_irq(dev->irq, dev);
 
 		if (devpriv->base_addr)
 			iounmap(devpriv->base_addr);
@@ -1574,7 +1575,7 @@
 	for (n = 0; n < insn->n; n++) {
 
 		/*  Delay 10 microseconds for analog input settling. */
-		comedi_udelay(10);
+		udelay(10);
 
 		/*  Start ADC by pulsing GPIO1 low. */
 		GpioImage = RR7146(P_GPIO);
@@ -1606,7 +1607,7 @@
 		 * data value is sometimes set to the previous
 		 * conversion's data value.
 		 */
-		comedi_udelay(4);
+		udelay(4);
 	}
 
 	/* Start a dummy conversion to cause the data from the
@@ -1886,31 +1887,16 @@
 		err++;
 	}
 
-	if (cmd->start_src == TRIG_EXT && cmd->start_arg < 0) {
-		cmd->start_arg = 0;
-		err++;
-	}
-
 	if (cmd->start_src == TRIG_EXT && cmd->start_arg > 39) {
 		cmd->start_arg = 39;
 		err++;
 	}
 
-	if (cmd->scan_begin_src == TRIG_EXT && cmd->scan_begin_arg < 0) {
-		cmd->scan_begin_arg = 0;
-		err++;
-	}
-
 	if (cmd->scan_begin_src == TRIG_EXT && cmd->scan_begin_arg > 39) {
 		cmd->scan_begin_arg = 39;
 		err++;
 	}
 
-	if (cmd->convert_src == TRIG_EXT && cmd->convert_arg < 0) {
-		cmd->convert_arg = 0;
-		err++;
-	}
-
 	if (cmd->convert_src == TRIG_EXT && cmd->convert_arg > 39) {
 		cmd->convert_arg = 39;
 		err++;
@@ -2373,7 +2359,7 @@
 	register uint8_t i;
 
 	/*  Copy TrimDac setpoint values from EEPROM to TrimDacs. */
-	for (i = 0; i < (sizeof(trimchan) / sizeof(trimchan[0])); i++)
+	for (i = 0; i < ARRAY_SIZE(trimchan); i++)
 		WriteTrimDAC(dev, i, I2Cread(dev, trimadrs[i]));
 }
 
diff --git a/drivers/staging/comedi/drivers/s626.h b/drivers/staging/comedi/drivers/s626.h
index 891126f..27ae02b 100644
--- a/drivers/staging/comedi/drivers/s626.h
+++ b/drivers/staging/comedi/drivers/s626.h
@@ -63,7 +63,7 @@
 */
 
 #ifdef _DEBUG_
-#define DEBUG(...);        rt_printk(__VA_ARGS__);
+#define DEBUG(...);        printk(__VA_ARGS__);
 #else
 #define DEBUG(...)
 #endif
diff --git a/drivers/staging/comedi/drivers/serial2002.c b/drivers/staging/comedi/drivers/serial2002.c
index 844fd5e..db18b11 100644
--- a/drivers/staging/comedi/drivers/serial2002.c
+++ b/drivers/staging/comedi/drivers/serial2002.c
@@ -52,7 +52,7 @@
 
 static const struct serial2002_board serial2002_boards[] = {
 	{
-      name:	"serial2002"}
+	.name = "serial2002"}
 };
 
 /*
@@ -62,7 +62,7 @@
 
 struct serial2002_range_table_t {
 
-	// HACK...
+	/*  HACK... */
 	int length;
 	struct comedi_krange range;
 };
@@ -70,8 +70,8 @@
 
 struct serial2002_private {
 
-	int port;		// /dev/ttyS<port>
-	int speed;		// baudrate
+	int port;		/*  /dev/ttyS<port> */
+	int speed;		/*  baudrate */
 	struct file *tty;
 	unsigned int ao_readback[32];
 	unsigned char digital_in_mapping[32];
@@ -89,28 +89,28 @@
  */
 #define devpriv ((struct serial2002_private *)dev->private)
 
-static int serial2002_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int serial2002_detach(struct comedi_device * dev);
+static int serial2002_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int serial2002_detach(struct comedi_device *dev);
 struct comedi_driver driver_serial2002 = {
-      driver_name:"serial2002",
-      module:THIS_MODULE,
-      attach:serial2002_attach,
-      detach:serial2002_detach,
-      board_name:&serial2002_boards[0].name,
-      offset:sizeof(struct serial2002_board),
-      num_names:sizeof(serial2002_boards) / sizeof(struct serial2002_board),
+	.driver_name = "serial2002",
+	.module = THIS_MODULE,
+	.attach = serial2002_attach,
+	.detach = serial2002_detach,
+	.board_name = &serial2002_boards[0].name,
+	.offset = sizeof(struct serial2002_board),
+	.num_names = ARRAY_SIZE(serial2002_boards),
 };
 
-static int serial2002_di_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int serial2002_do_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int serial2002_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int serial2002_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int serial2002_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
+static int serial2002_di_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int serial2002_do_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int serial2002_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int serial2002_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int serial2002_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
 
 struct serial_data {
 	enum { is_invalid, is_digital, is_channel } kind;
@@ -121,12 +121,12 @@
 static long tty_ioctl(struct file *f, unsigned op, unsigned long param)
 {
 #ifdef HAVE_UNLOCKED_IOCTL
-  	if (f->f_op->unlocked_ioctl) {
+	if (f->f_op->unlocked_ioctl) {
 		return f->f_op->unlocked_ioctl(f, op, param);
 	}
 #endif
 	if (f->f_op->ioctl) {
-	  	return f->f_op->ioctl(f->f_dentry->d_inode, f, op, param);
+		return f->f_op->ioctl(f->f_dentry->d_inode, f, op, param);
 	}
 	return -ENOSYS;
 }
@@ -211,7 +211,7 @@
 			/* Device does not support poll, busy wait */
 			int retries = 0;
 			while (1) {
-			  	unsigned char ch;
+				unsigned char ch;
 
 				retries++;
 				if (retries >= timeout) {
@@ -220,10 +220,10 @@
 
 				f->f_pos = 0;
 				if (f->f_op->read(f, &ch, 1, &f->f_pos) == 1) {
-				  	result = ch;
+					result = ch;
 					break;
 				}
-				comedi_udelay(100);
+				udelay(100);
 			}
 		}
 		set_fs(oldfs);
@@ -238,11 +238,11 @@
 	oldfs = get_fs();
 	set_fs(KERNEL_DS);
 	{
-		// Set speed
+		/*  Set speed */
 		struct termios settings;
 
 		tty_ioctl(f, TCGETS, (unsigned long)&settings);
-//    printk("Speed: %d\n", settings.c_cflag & (CBAUD | CBAUDEX));
+/* printk("Speed: %d\n", settings.c_cflag & (CBAUD | CBAUDEX)); */
 		settings.c_iflag = 0;
 		settings.c_oflag = 0;
 		settings.c_lflag = 0;
@@ -284,10 +284,10 @@
 			break;
 		}
 		tty_ioctl(f, TCSETS, (unsigned long)&settings);
-//    printk("Speed: %d\n", settings.c_cflag & (CBAUD | CBAUDEX));
+/* printk("Speed: %d\n", settings.c_cflag & (CBAUD | CBAUDEX)); */
 	}
 	{
-		// Set low latency
+		/*  Set low latency */
 		struct serial_struct settings;
 
 		tty_ioctl(f, TIOCGSERIAL, (unsigned long)&settings);
@@ -393,7 +393,7 @@
 	}
 }
 
-static void serial_2002_open(struct comedi_device * dev)
+static void serial_2002_open(struct comedi_device *dev)
 {
 	char port[20];
 
@@ -437,7 +437,7 @@
 		}
 
 		tty_setspeed(devpriv->tty, devpriv->speed);
-		poll_channel(devpriv->tty, 31);	// Start reading configuration
+		poll_channel(devpriv->tty, 31);	/*  Start reading configuration */
 		while (1) {
 			struct serial_data data;
 
@@ -557,7 +557,7 @@
 			}
 		}
 		for (i = 0; i <= 4; i++) {
-			// Fill in subdev data
+			/*  Fill in subdev data */
 			struct config_t *c;
 			unsigned char *mapping = 0;
 			struct serial2002_range_table_t *range = 0;
@@ -659,15 +659,15 @@
 	}
 }
 
-static void serial_2002_close(struct comedi_device * dev)
+static void serial_2002_close(struct comedi_device *dev)
 {
 	if (!IS_ERR(devpriv->tty) && (devpriv->tty != 0)) {
 		filp_close(devpriv->tty, 0);
 	}
 }
 
-static int serial2002_di_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int serial2002_di_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan;
@@ -688,8 +688,8 @@
 	return n;
 }
 
-static int serial2002_do_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int serial2002_do_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan;
@@ -706,8 +706,8 @@
 	return n;
 }
 
-static int serial2002_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int serial2002_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan;
@@ -728,8 +728,8 @@
 	return n;
 }
 
-static int serial2002_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int serial2002_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan;
@@ -747,8 +747,8 @@
 	return n;
 }
 
-static int serial2002_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int serial2002_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan = CR_CHAN(insn->chanspec);
@@ -760,8 +760,8 @@
 	return n;
 }
 
-static int serial2002_ei_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int serial2002_ei_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n;
 	int chan;
@@ -782,7 +782,7 @@
 	return n;
 }
 
-static int serial2002_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int serial2002_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 
@@ -849,7 +849,7 @@
 	return 1;
 }
 
-static int serial2002_detach(struct comedi_device * dev)
+static int serial2002_detach(struct comedi_device *dev)
 {
 	struct comedi_subdevice *s;
 	int i;
diff --git a/drivers/staging/comedi/drivers/skel.c b/drivers/staging/comedi/drivers/skel.c
index c7700d1..07f580a 100644
--- a/drivers/staging/comedi/drivers/skel.c
+++ b/drivers/staging/comedi/drivers/skel.c
@@ -97,16 +97,16 @@
 
 static const struct skel_board skel_boards[] = {
 	{
-	      name:	"skel-100",
-	      ai_chans:16,
-	      ai_bits:	12,
-	      have_dio:1,
+	.name = "skel-100",
+	.ai_chans = 16,
+	.ai_bits = 12,
+	.have_dio = 1,
 		},
 	{
-	      name:	"skel-200",
-	      ai_chans:8,
-	      ai_bits:	16,
-	      have_dio:0,
+	.name = "skel-200",
+	.ai_chans = 8,
+	.ai_bits = 16,
+	.have_dio = 0,
 		},
 };
 
@@ -154,13 +154,13 @@
  * the board, and also about the kernel module that contains
  * the device code.
  */
-static int skel_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int skel_detach(struct comedi_device * dev);
+static int skel_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int skel_detach(struct comedi_device *dev);
 static struct comedi_driver driver_skel = {
-      driver_name:"dummy",
-      module:THIS_MODULE,
-      attach:skel_attach,
-      detach:skel_detach,
+	.driver_name = "dummy",
+	.module = THIS_MODULE,
+	.attach = skel_attach,
+	.detach = skel_detach,
 /* It is not necessary to implement the following members if you are
  * writing a driver for a ISA PnP or PCI card */
 	/* Most drivers will support multiple types of boards by
@@ -179,23 +179,23 @@
 	 * the type of board in software.  ISA PnP, PCI, and PCMCIA
 	 * devices are such boards.
 	 */
-      board_name:&skel_boards[0].name,
-      offset:sizeof(struct skel_board),
-      num_names:sizeof(skel_boards) / sizeof(struct skel_board),
+	.board_name = &skel_boards[0].name,
+	.offset = sizeof(struct skel_board),
+	.num_names = ARRAY_SIZE(skel_boards),
 };
 
-static int skel_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int skel_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int skel_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int skel_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int skel_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data);
-static int skel_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd);
+static int skel_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int skel_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int skel_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int skel_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int skel_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data);
+static int skel_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd);
 static int skel_ns_to_timer(unsigned int *ns, int round);
 
 /*
@@ -204,7 +204,7 @@
  * in the driver structure, dev->board_ptr contains that
  * address.
  */
-static int skel_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int skel_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	struct comedi_subdevice *s;
 
@@ -292,7 +292,7 @@
  * allocated by _attach().  dev->private and dev->subdevices are
  * deallocated automatically by the core.
  */
-static int skel_detach(struct comedi_device * dev)
+static int skel_detach(struct comedi_device *dev)
 {
 	printk("comedi%d: skel: remove\n", dev->minor);
 
@@ -303,8 +303,8 @@
  * "instructions" read/write data in "one-shot" or "software-triggered"
  * mode.
  */
-static int skel_ai_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int skel_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int n, i;
 	unsigned int d;
@@ -331,9 +331,9 @@
 				break;
 		}
 		if (i == TIMEOUT) {
-			/* rt_printk() should be used instead of printk()
+			/* printk() should be used instead of printk()
 			 * whenever the code can be called from real-time. */
-			rt_printk("timeout\n");
+			printk("timeout\n");
 			return -ETIMEDOUT;
 		}
 
@@ -351,8 +351,8 @@
 	return n;
 }
 
-static int skel_ai_cmdtest(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_cmd * cmd)
+static int skel_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_cmd *cmd)
 {
 	int err = 0;
 	int tmp;
@@ -520,8 +520,8 @@
 	return *ns;
 }
 
-static int skel_ao_winsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int skel_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -541,8 +541,8 @@
 
 /* AO subdevices should have a read insn as well as a write insn.
  * Usually this means copying a value stored in devpriv. */
-static int skel_ao_rinsn(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int skel_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int i;
 	int chan = CR_CHAN(insn->chanspec);
@@ -558,8 +558,8 @@
  * useful to applications if you implement the insn_bits interface.
  * This allows packed reading/writing of the DIO channels.  The
  * comedi core can convert between insn_bits and insn_read/write */
-static int skel_dio_insn_bits(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int skel_dio_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	if (insn->n != 2)
 		return -EINVAL;
@@ -583,8 +583,8 @@
 	return 2;
 }
 
-static int skel_dio_insn_config(struct comedi_device * dev, struct comedi_subdevice * s,
-	struct comedi_insn * insn, unsigned int * data)
+static int skel_dio_insn_config(struct comedi_device *dev, struct comedi_subdevice *s,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int chan = CR_CHAN(insn->chanspec);
 
diff --git a/drivers/staging/comedi/drivers/ssv_dnp.c b/drivers/staging/comedi/drivers/ssv_dnp.c
index 1628d21..13c29bb 100644
--- a/drivers/staging/comedi/drivers/ssv_dnp.c
+++ b/drivers/staging/comedi/drivers/ssv_dnp.c
@@ -61,10 +61,10 @@
 
 static const struct dnp_board dnp_boards[] = {	/* we only support one DNP 'board'   */
 	{			/* variant at the moment             */
-	      name:	"dnp-1486",
-	      ai_chans:16,
-	      ai_bits:	12,
-	      have_dio:1,
+	.name = "dnp-1486",
+	.ai_chans = 16,
+	.ai_bits = 12,
+	.have_dio = 1,
 		},
 };
 
@@ -74,7 +74,6 @@
 /* This structure is for data unique to the DNP driver --------------------- */
 struct dnp_private_data {
 
-	//
 };
 
 
@@ -89,27 +88,27 @@
 /* In the following section we define the API of this driver.                */
 /* ------------------------------------------------------------------------- */
 
-static int dnp_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int dnp_detach(struct comedi_device * dev);
+static int dnp_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int dnp_detach(struct comedi_device *dev);
 
 static struct comedi_driver driver_dnp = {
-      driver_name:"ssv_dnp",
-      module:THIS_MODULE,
-      attach:dnp_attach,
-      detach:dnp_detach,
-      board_name:&dnp_boards[0].name,
+	.driver_name = "ssv_dnp",
+	.module = THIS_MODULE,
+	.attach = dnp_attach,
+	.detach = dnp_detach,
+	.board_name = &dnp_boards[0].name,
 	/* only necessary for non-PnP devs   */
-      offset:sizeof(struct dnp_board),/* like ISA-PnP, PCI or PCMCIA.      */
-      num_names:sizeof(dnp_boards) / sizeof(struct dnp_board),
+	.offset = sizeof(struct dnp_board),/* like ISA-PnP, PCI or PCMCIA.      */
+	.num_names = ARRAY_SIZE(dnp_boards),
 };
 
 COMEDI_INITCLEANUP(driver_dnp);
 
-static int dnp_dio_insn_bits(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
+static int dnp_dio_insn_bits(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
 
-static int dnp_dio_insn_config(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data);
+static int dnp_dio_insn_config(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data);
 
 /* ------------------------------------------------------------------------- */
 /* Attach is called by comedi core to configure the driver for a particular  */
@@ -117,7 +116,7 @@
 /* dev->board_ptr contains that address.                                     */
 /* ------------------------------------------------------------------------- */
 
-static int dnp_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int dnp_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 
 	struct comedi_subdevice *s;
@@ -126,7 +125,7 @@
 
 	/* Autoprobing: this should find out which board we have. Currently only   */
 	/* the 1486 board is supported and autoprobing is not implemented :-)      */
-	//dev->board_ptr = dnp_probe(dev);
+	/* dev->board_ptr = dnp_probe(dev); */
 
 	/* Initialize the name of the board. We can use the "thisboard" macro now. */
 	dev->board_name = thisboard->name;
@@ -178,7 +177,7 @@
 /* deallocated automatically by the core.                                    */
 /* ------------------------------------------------------------------------- */
 
-static int dnp_detach(struct comedi_device * dev)
+static int dnp_detach(struct comedi_device *dev)
 {
 
 	/* configure all ports as input (default)                                  */
@@ -202,8 +201,8 @@
 /* are able to use these instructions as well.                               */
 /* ------------------------------------------------------------------------- */
 
-static int dnp_dio_insn_bits(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int dnp_dio_insn_bits(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 
 	if (insn->n != 2)
@@ -252,8 +251,8 @@
 /* COMEDI_INPUT or COMEDI_OUTPUT.                                            */
 /* ------------------------------------------------------------------------- */
 
-static int dnp_dio_insn_config(struct comedi_device * dev,
-	struct comedi_subdevice * s, struct comedi_insn * insn, unsigned int * data)
+static int dnp_dio_insn_config(struct comedi_device *dev,
+	struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
 {
 
 	u8 register_buffer;
diff --git a/drivers/staging/comedi/drivers/unioxx5.c b/drivers/staging/comedi/drivers/unioxx5.c
index dd3b111..96bb15c 100644
--- a/drivers/staging/comedi/drivers/unioxx5.c
+++ b/drivers/staging/comedi/drivers/unioxx5.c
@@ -80,38 +80,38 @@
 	unsigned char usp_prev_cn_val[3];	/* previous channel value */
 };
 
-static int unioxx5_attach(struct comedi_device * dev, struct comedi_devconfig * it);
-static int unioxx5_subdev_write(struct comedi_device * dev, struct comedi_subdevice * subdev,
-	struct comedi_insn * insn, unsigned int * data);
-static int unioxx5_subdev_read(struct comedi_device * dev, struct comedi_subdevice * subdev,
-	struct comedi_insn * insn, unsigned int * data);
-static int unioxx5_insn_config(struct comedi_device * dev, struct comedi_subdevice * subdev,
-	struct comedi_insn * insn, unsigned int * data);
-static int unioxx5_detach(struct comedi_device * dev);
-static int __unioxx5_subdev_init(struct comedi_subdevice * subdev, int subdev_iobase,
+static int unioxx5_attach(struct comedi_device *dev, struct comedi_devconfig *it);
+static int unioxx5_subdev_write(struct comedi_device *dev, struct comedi_subdevice *subdev,
+	struct comedi_insn *insn, unsigned int *data);
+static int unioxx5_subdev_read(struct comedi_device *dev, struct comedi_subdevice *subdev,
+	struct comedi_insn *insn, unsigned int *data);
+static int unioxx5_insn_config(struct comedi_device *dev, struct comedi_subdevice *subdev,
+	struct comedi_insn *insn, unsigned int *data);
+static int unioxx5_detach(struct comedi_device *dev);
+static int __unioxx5_subdev_init(struct comedi_subdevice *subdev, int subdev_iobase,
 	int minor);
-static int __unioxx5_digital_write(struct unioxx5_subd_priv * usp, unsigned int * data,
+static int __unioxx5_digital_write(struct unioxx5_subd_priv *usp, unsigned int *data,
 	int channel, int minor);
-static int __unioxx5_digital_read(struct unioxx5_subd_priv * usp, unsigned int * data,
+static int __unioxx5_digital_read(struct unioxx5_subd_priv *usp, unsigned int *data,
 	int channel, int minor);
-//static void __unioxx5_digital_config(struct unioxx5_subd_priv* usp, int mode);
-static int __unioxx5_analog_write(struct unioxx5_subd_priv * usp, unsigned int * data,
+/* static void __unioxx5_digital_config(struct unioxx5_subd_priv* usp, int mode); */
+static int __unioxx5_analog_write(struct unioxx5_subd_priv *usp, unsigned int *data,
 	int channel, int minor);
-static int __unioxx5_analog_read(struct unioxx5_subd_priv * usp, unsigned int * data,
+static int __unioxx5_analog_read(struct unioxx5_subd_priv *usp, unsigned int *data,
 	int channel, int minor);
 static int __unioxx5_define_chan_offset(int chan_num);
-static void __unioxx5_analog_config(struct unioxx5_subd_priv * usp, int channel);
+static void __unioxx5_analog_config(struct unioxx5_subd_priv *usp, int channel);
 
 static struct comedi_driver unioxx5_driver = {
-      driver_name:DRIVER_NAME,
-      module:THIS_MODULE,
-      attach:unioxx5_attach,
-      detach:unioxx5_detach
+	.driver_name = DRIVER_NAME,
+	.module = THIS_MODULE,
+	.attach = unioxx5_attach,
+	.detach = unioxx5_detach
 };
 
 COMEDI_INITCLEANUP(unioxx5_driver);
 
-static int unioxx5_attach(struct comedi_device * dev, struct comedi_devconfig * it)
+static int unioxx5_attach(struct comedi_device *dev, struct comedi_devconfig *it)
 {
 	int iobase, i, n_subd;
 	int id, num, ba;
@@ -156,8 +156,8 @@
 	return 0;
 }
 
-static int unioxx5_subdev_read(struct comedi_device * dev, struct comedi_subdevice * subdev,
-	struct comedi_insn * insn, unsigned int * data)
+static int unioxx5_subdev_read(struct comedi_device *dev, struct comedi_subdevice *subdev,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct unioxx5_subd_priv *usp = subdev->private;
 	int channel, type;
@@ -176,8 +176,8 @@
 	return 1;
 }
 
-static int unioxx5_subdev_write(struct comedi_device * dev, struct comedi_subdevice * subdev,
-	struct comedi_insn * insn, unsigned int * data)
+static int unioxx5_subdev_write(struct comedi_device *dev, struct comedi_subdevice *subdev,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	struct unioxx5_subd_priv *usp = subdev->private;
 	int channel, type;
@@ -197,8 +197,8 @@
 }
 
 /* for digital modules only */
-static int unioxx5_insn_config(struct comedi_device * dev, struct comedi_subdevice * subdev,
-	struct comedi_insn * insn, unsigned int * data)
+static int unioxx5_insn_config(struct comedi_device *dev, struct comedi_subdevice *subdev,
+	struct comedi_insn *insn, unsigned int *data)
 {
 	int channel_offset, flags, channel = CR_CHAN(insn->chanspec), type;
 	struct unioxx5_subd_priv *usp = subdev->private;
@@ -213,7 +213,8 @@
 		return -1;
 	}
 
-	if ((channel_offset = __unioxx5_define_chan_offset(channel)) < 0) {
+	channel_offset = __unioxx5_define_chan_offset(channel);
+	if (channel_offset < 0) {
 		printk(KERN_ERR
 			"comedi%d: undefined channel %d. channel range is 0 .. 23\n",
 			dev->minor, channel);
@@ -247,7 +248,7 @@
 	return 0;
 }
 
-static int unioxx5_detach(struct comedi_device * dev)
+static int unioxx5_detach(struct comedi_device *dev)
 {
 	int i;
 	struct comedi_subdevice *subdev;
@@ -264,7 +265,7 @@
 }
 
 /* initializing subdevice with given address */
-static int __unioxx5_subdev_init(struct comedi_subdevice * subdev, int subdev_iobase,
+static int __unioxx5_subdev_init(struct comedi_subdevice *subdev, int subdev_iobase,
 	int minor)
 {
 	struct unioxx5_subd_priv *usp;
@@ -275,8 +276,9 @@
 		return -EIO;
 	}
 
-	if ((usp = (struct unioxx5_subd_priv *) kzalloc(sizeof(*usp),
-				GFP_KERNEL)) == NULL) {
+	usp = (struct unioxx5_subd_priv *) kzalloc(sizeof(*usp), GFP_KERNEL);
+
+	if (usp == NULL) {
 		printk(KERN_ERR "comedi%d: erorr! --> out of memory!\n", minor);
 		return -1;
 	}
@@ -309,7 +311,7 @@
 			usp->usp_module_type[i] = inb(subdev_iobase + 6);
 
 		printk(" [%d] 0x%02x |", i, usp->usp_module_type[i]);
-		comedi_udelay(1);
+		udelay(1);
 	}
 
 	printk("\n");
@@ -330,13 +332,14 @@
 	return 0;
 }
 
-static int __unioxx5_digital_write(struct unioxx5_subd_priv * usp, unsigned int * data,
+static int __unioxx5_digital_write(struct unioxx5_subd_priv *usp, unsigned int *data,
 	int channel, int minor)
 {
 	int channel_offset, val;
 	int mask = 1 << (channel & 0x07);
 
-	if ((channel_offset = __unioxx5_define_chan_offset(channel)) < 0) {
+	channel_offset = __unioxx5_define_chan_offset(channel);
+	if (channel_offset < 0) {
 		printk(KERN_ERR
 			"comedi%d: undefined channel %d. channel range is 0 .. 23\n",
 			minor, channel);
@@ -357,12 +360,13 @@
 }
 
 /* function for digital reading */
-static int __unioxx5_digital_read(struct unioxx5_subd_priv * usp, unsigned int * data,
+static int __unioxx5_digital_read(struct unioxx5_subd_priv *usp, unsigned int *data,
 	int channel, int minor)
 {
 	int channel_offset, mask = 1 << (channel & 0x07);
 
-	if ((channel_offset = __unioxx5_define_chan_offset(channel)) < 0) {
+	channel_offset = __unioxx5_define_chan_offset(channel);
+	if (channel_offset < 0) {
 		printk(KERN_ERR
 			"comedi%d: undefined channel %d. channel range is 0 .. 23\n",
 			minor, channel);
@@ -380,7 +384,7 @@
 }
 
 #if 0				/* not used? */
-static void __unioxx5_digital_config(struct unioxx5_subd_priv * usp, int mode)
+static void __unioxx5_digital_config(struct unioxx5_subd_priv *usp, int mode)
 {
 	int i, mask;
 
@@ -396,7 +400,7 @@
 }
 #endif
 
-static int __unioxx5_analog_write(struct unioxx5_subd_priv * usp, unsigned int * data,
+static int __unioxx5_analog_write(struct unioxx5_subd_priv *usp, unsigned int *data,
 	int channel, int minor)
 {
 	int module, i;
@@ -418,7 +422,7 @@
 	/* saving major byte */
 	usp->usp_extra_data[module][i] = (unsigned char)((*data & 0xFF00) >> 8);
 
-	//while(!((inb(usp->usp_iobase + 0)) & TxBE));
+	/* while(!((inb(usp->usp_iobase + 0)) & TxBE)); */
 	outb(module + 1, usp->usp_iobase + 5);	/* sending module number to card(1 .. 12) */
 	outb('W', usp->usp_iobase + 6);	/* sends (W)rite command to module */
 
@@ -431,7 +435,7 @@
 	return 1;
 }
 
-static int __unioxx5_analog_read(struct unioxx5_subd_priv * usp, unsigned int * data,
+static int __unioxx5_analog_read(struct unioxx5_subd_priv *usp, unsigned int *data,
 	int channel, int minor)
 {
 	int module_no, read_ch;
@@ -471,7 +475,7 @@
 }
 
 /* configure channels for analog i/o (even to output, odd to input) */
-static void __unioxx5_analog_config(struct unioxx5_subd_priv * usp, int channel)
+static void __unioxx5_analog_config(struct unioxx5_subd_priv *usp, int channel)
 {
 	int chan_a, chan_b, conf, channel_offset;
 
diff --git a/drivers/staging/comedi/drivers/usbdux.c b/drivers/staging/comedi/drivers/usbdux.c
index d0b59e9..171a6f2 100644
--- a/drivers/staging/comedi/drivers/usbdux.c
+++ b/drivers/staging/comedi/drivers/usbdux.c
@@ -509,14 +509,19 @@
 	for (i = 0; i < n; i++) {
 		/* transfer data */
 		if (CR_RANGE(s->async->cmd.chanlist[i]) <= 1) {
-			comedi_buf_put
+			err = comedi_buf_put
 				(s->async,
-				le16_to_cpu(this_usbduxsub->
-					inBuffer[i]) ^ 0x800);
+				 le16_to_cpu(this_usbduxsub->
+					     inBuffer[i]) ^ 0x800);
 		} else {
-			comedi_buf_put
+			err = comedi_buf_put
 				(s->async,
-				le16_to_cpu(this_usbduxsub->inBuffer[i]));
+				 le16_to_cpu(this_usbduxsub->inBuffer[i]));
+		}
+		if (unlikely(err == 0)) {
+			/* buffer overflow */
+			usbdux_ai_stop(this_usbduxsub, 0);
+			return;
 		}
 	}
 	/* tell comedi that data is there */
@@ -809,32 +814,56 @@
 	return 0;
 }
 
-static int firmwareUpload(struct usbduxsub *usbduxsub, uint8_t *firmwareBinary,
+#define FIRMWARE_MAX_LEN 0x2000
+
+static int firmwareUpload(struct usbduxsub *usbduxsub,
+			  const u8 *firmwareBinary,
 			  int sizeFirmware)
 {
 	int ret;
+	uint8_t *fwBuf;
 
 	if (!firmwareBinary)
 		return 0;
 
+	if (sizeFirmware>FIRMWARE_MAX_LEN) {
+		dev_err(&usbduxsub->interface->dev,
+			"comedi_: usbdux firmware binary it too large for FX2.\n");
+		return -ENOMEM;
+	}
+
+	/* we generate a local buffer for the firmware */
+	fwBuf = kzalloc(sizeFirmware, GFP_KERNEL);
+	if (!fwBuf) {
+		dev_err(&usbduxsub->interface->dev,
+			"comedi_: mem alloc for firmware failed\n");
+		return -ENOMEM;
+	}
+	memcpy(fwBuf,firmwareBinary,sizeFirmware);
+
 	ret = usbduxsub_stop(usbduxsub);
 	if (ret < 0) {
 		dev_err(&usbduxsub->interface->dev,
 			"comedi_: can not stop firmware\n");
+		kfree(fwBuf);
 		return ret;
 	}
-	ret = usbduxsub_upload(usbduxsub, firmwareBinary, 0, sizeFirmware);
+
+	ret = usbduxsub_upload(usbduxsub, fwBuf, 0, sizeFirmware);
 	if (ret < 0) {
 		dev_err(&usbduxsub->interface->dev,
 			"comedi_: firmware upload failed\n");
+		kfree(fwBuf);
 		return ret;
 	}
 	ret = usbduxsub_start(usbduxsub);
 	if (ret < 0) {
 		dev_err(&usbduxsub->interface->dev,
 			"comedi_: can not start firmware\n");
+		kfree(fwBuf);
 		return ret;
 	}
+	kfree(fwBuf);
 	return 0;
 }
 
@@ -2260,134 +2289,6 @@
 	usbduxsub_tmp->pwm_cmd_running = 0;
 }
 
-static unsigned hex2unsigned(char *h)
-{
-	unsigned hi, lo;
-
-	if (h[0] > '9')
-		hi = h[0] - 'A' + 0x0a;
-	else
-		hi = h[0] - '0';
-
-	if (h[1] > '9')
-		lo = h[1] - 'A' + 0x0a;
-	else
-		lo = h[1] - '0';
-
-	return hi * 0x10 + lo;
-}
-
-/* for FX2 */
-#define FIRMWARE_MAX_LEN 0x2000
-
-/* taken from David Brownell's fxload and adjusted for this driver */
-static int read_firmware(struct usbduxsub *usbduxsub, const void *firmwarePtr,
-			 long size)
-{
-	struct device *dev = &usbduxsub->interface->dev;
-	int i = 0;
-	unsigned char *fp = (char *)firmwarePtr;
-	unsigned char *firmwareBinary;
-	int res = 0;
-	int maxAddr = 0;
-
-	firmwareBinary = kzalloc(FIRMWARE_MAX_LEN, GFP_KERNEL);
-	if (!firmwareBinary) {
-		dev_err(dev, "comedi_: mem alloc for firmware failed\n");
-		return -ENOMEM;
-	}
-
-	for (;;) {
-		char buf[256], *cp;
-		char type;
-		int len;
-		int idx, off;
-		int j = 0;
-
-		/* get one line */
-		while ((i < size) && (fp[i] != 13) && (fp[i] != 10)) {
-			buf[j] = fp[i];
-			i++;
-			j++;
-			if (j >= sizeof(buf)) {
-				dev_err(dev, "comedi_: bogus firmware file!\n");
-				kfree(firmwareBinary);
-				return -1;
-			}
-		}
-		/* get rid of LF/CR/... */
-		while ((i < size) && ((fp[i] == 13) || (fp[i] == 10)
-				|| (fp[i] == 0))) {
-			i++;
-		}
-
-		buf[j] = 0;
-		/* dev_dbg(dev, "comedi_: buf=%s\n", buf); */
-
-		/*
-		 * EXTENSION:
-		 * "# comment-till-end-of-line", for copyrights etc
-		 */
-		if (buf[0] == '#')
-			continue;
-
-		if (buf[0] != ':') {
-			dev_err(dev, "comedi_: upload: not an ihex record: %s",
-				buf);
-			kfree(firmwareBinary);
-			return -EFAULT;
-		}
-
-		/* Read the length field (up to 16 bytes) */
-		len = hex2unsigned(buf + 1);
-
-		/* Read the target offset */
-		off = (hex2unsigned(buf + 3) * 0x0100) + hex2unsigned(buf + 5);
-
-		if ((off + len) > maxAddr)
-			maxAddr = off + len;
-
-
-		if (maxAddr >= FIRMWARE_MAX_LEN) {
-			dev_err(dev, "comedi_: firmware upload goes "
-				"beyond FX2 RAM boundaries.\n");
-			kfree(firmwareBinary);
-			return -EFAULT;
-		}
-		/* dev_dbg(dev, "comedi_: off=%x, len=%x:\n", off, len); */
-
-		/* Read the record type */
-		type = hex2unsigned(buf + 7);
-
-		/* If this is an EOF record, then make it so. */
-		if (type == 1)
-			break;
-
-
-		if (type != 0) {
-			dev_err(dev, "comedi_: unsupported record type: %u\n",
-				type);
-			kfree(firmwareBinary);
-			return -EFAULT;
-		}
-
-		for (idx = 0, cp = buf + 9; idx < len; idx += 1, cp += 2) {
-			firmwareBinary[idx + off] = hex2unsigned(cp);
-			/*printk("%02x ",firmwareBinary[idx+off]); */
-		}
-		/*printk("\n"); */
-
-		if (i >= size) {
-			dev_err(dev, "comedi_: unexpected end of hex file\n");
-			break;
-		}
-
-	}
-	res = firmwareUpload(usbduxsub, firmwareBinary, maxAddr + 1);
-	kfree(firmwareBinary);
-	return res;
-}
-
 static void usbdux_firmware_request_complete_handler(const struct firmware *fw,
 						     void *context)
 {
@@ -2405,7 +2306,7 @@
 	 * we need to upload the firmware here because fw will be
 	 * freed once we've left this function
 	 */
-	ret = read_firmware(usbduxsub_tmp, fw->data, fw->size);
+	ret = firmwareUpload(usbduxsub_tmp, fw->data, fw->size);
 
 	if (ret) {
 		dev_err(&usbdev->dev,
@@ -2662,11 +2563,13 @@
 
 	ret = request_firmware_nowait(THIS_MODULE,
 				      FW_ACTION_HOTPLUG,
-				      "usbdux_firmware.hex",
+				      "usbdux_firmware.bin",
 				      &udev->dev,
 				      usbduxsub + index,
 				      usbdux_firmware_request_complete_handler);
 
+
+
 	if (ret) {
 		dev_err(dev, "Could not load firmware (err=%d)\n", ret);
 		return ret;
@@ -2739,8 +2642,8 @@
 	/* trying to upload the firmware into the chip */
 	if (comedi_aux_data(it->options, 0) &&
 		it->options[COMEDI_DEVCONF_AUX_DATA_LENGTH]) {
-		read_firmware(udev, comedi_aux_data(it->options, 0),
-			      it->options[COMEDI_DEVCONF_AUX_DATA_LENGTH]);
+		firmwareUpload(udev, comedi_aux_data(it->options, 0),
+			       it->options[COMEDI_DEVCONF_AUX_DATA_LENGTH]);
 	}
 
 	dev->board_name = BOARDNAME;
diff --git a/drivers/staging/comedi/drivers/usbduxfast.c b/drivers/staging/comedi/drivers/usbduxfast.c
index 2fb64de..939b53f 100644
--- a/drivers/staging/comedi/drivers/usbduxfast.c
+++ b/drivers/staging/comedi/drivers/usbduxfast.c
@@ -314,7 +314,7 @@
  * analogue IN
  * interrupt service routine
  */
-static void usbduxfastsub_ai_Irq(struct urb *urb PT_REGS_ARG)
+static void usbduxfastsub_ai_Irq(struct urb *urb)
 {
 	int n, err;
 	struct usbduxfastsub_s *udfs;
@@ -406,7 +406,7 @@
 					udfs->ai_sample_count
 					* sizeof(uint16_t));
 				usbduxfast_ai_stop(udfs, 0);
-				/* say comedi that the acquistion is over */
+				/* tell comedi that the acquistion is over */
 				s->async->events |= COMEDI_CB_EOA;
 				comedi_event(udfs->comedidev, s);
 				return;
@@ -414,8 +414,13 @@
 			udfs->ai_sample_count -= n;
 		}
 		/* write the full buffer to comedi */
-		cfc_write_array_to_buffer(s, urb->transfer_buffer,
-					  urb->actual_length);
+		err = cfc_write_array_to_buffer(s, urb->transfer_buffer,
+						urb->actual_length);
+		if (unlikely(err == 0)) {
+			/* buffer overflow */
+			usbduxfast_ai_stop(udfs, 0);
+			return;
+		}
 
 		/* tell comedi that data is there */
 		comedi_event(udfs->comedidev, s);
@@ -524,33 +529,6 @@
 	return 0;
 }
 
-int firmwareUpload(struct usbduxfastsub_s *udfs, unsigned char *firmwareBinary,
-		   int sizeFirmware)
-{
-	int ret;
-
-	if (!firmwareBinary)
-		return 0;
-
-	ret = usbduxfastsub_stop(udfs);
-	if (ret < 0) {
-		printk(KERN_ERR "comedi_: usbduxfast: can not stop firmware\n");
-		return ret;
-	}
-	ret = usbduxfastsub_upload(udfs, firmwareBinary, 0, sizeFirmware);
-	if (ret < 0) {
-		printk(KERN_ERR "comedi_: usbduxfast: firmware upload failed\n");
-		return ret;
-	}
-	ret = usbduxfastsub_start(udfs);
-	if (ret < 0) {
-		printk(KERN_ERR "comedi_: usbduxfast: can not start firmware\n");
-		return ret;
-	}
-
-	return 0;
-}
-
 int usbduxfastsub_submit_InURBs(struct usbduxfastsub_s *udfs)
 {
 	int ret;
@@ -1365,136 +1343,61 @@
 	return i;
 }
 
-static unsigned hex2unsigned(char *h)
-{
-	unsigned hi, lo;
-
-	if (h[0] > '9')
-		hi = h[0] - 'A' + 0x0a;
-	else
-		hi = h[0] - '0';
-
-	if (h[1] > '9')
-		lo = h[1] - 'A' + 0x0a;
-	else
-		lo = h[1] - '0';
-
-	return hi * 0x10 + lo;
-}
-
-/* for FX2 */
 #define FIRMWARE_MAX_LEN 0x2000
 
-/*
- * taken from David Brownell's fxload and adjusted for this driver
- */
-static int read_firmware(struct usbduxfastsub_s *udfs, const void *firmwarePtr,
-			 long size)
+static int firmwareUpload(struct usbduxfastsub_s *usbduxfastsub,
+			  const u8 *firmwareBinary,
+			  int sizeFirmware)
 {
-	int i = 0;
-	unsigned char *fp = (char *)firmwarePtr;
-	unsigned char *firmwareBinary;
-	int res = 0;
-	int maxAddr = 0;
+	int ret;
+	uint8_t *fwBuf;
 
-	firmwareBinary = kmalloc(FIRMWARE_MAX_LEN, GFP_KERNEL);
-	if (!firmwareBinary) {
-		printk(KERN_ERR "comedi_: usbduxfast: mem alloc for firmware "
-		       " failed\n");
+	if (!firmwareBinary)
+		return 0;
+
+	if (sizeFirmware>FIRMWARE_MAX_LEN) {
+		dev_err(&usbduxfastsub->interface->dev,
+			"comedi_: usbduxfast firmware binary it too large for FX2.\n");
 		return -ENOMEM;
 	}
 
-	for (;;) {
-		char buf[256], *cp;
-		char type;
-		int len;
-		int idx, off;
-		int j = 0;
-
-		/* get one line */
-		while ((i < size) && (fp[i] != 13) && (fp[i] != 10)) {
-			buf[j] = fp[i];
-			i++;
-			j++;
-			if (j >= sizeof(buf)) {
-				printk(KERN_ERR "comedi_: usbduxfast: bogus "
-				       "firmware file!\n");
-				kfree(firmwareBinary);
-				return -1;
-			}
-		}
-		/* get rid of LF/CR/... */
-		while ((i < size) && ((fp[i] == 13) || (fp[i] == 10)
-					|| (fp[i] == 0)))
-			i++;
-
-		buf[j] = 0;
-		/* printk("comedi_: buf=%s\n",buf); */
-
-		/*
-		 * EXTENSION: "# comment-till-end-of-line",
-		 * for copyrights etc
-		 */
-		if (buf[0] == '#')
-			continue;
-
-		if (buf[0] != ':') {
-			printk(KERN_ERR "comedi_: usbduxfast: upload: not an "
-			       "ihex record: %s", buf);
-			kfree(firmwareBinary);
-			return -EFAULT;
-		}
-
-		/* Read the length field (up to 16 bytes) */
-		len = hex2unsigned(buf + 1);
-
-		/* Read the target offset */
-		off = (hex2unsigned(buf + 3) * 0x0100) + hex2unsigned(buf + 5);
-
-		if ((off + len) > maxAddr)
-			maxAddr = off + len;
-
-		if (maxAddr >= FIRMWARE_MAX_LEN) {
-			printk(KERN_ERR "comedi_: usbduxfast: firmware upload "
-			       "goes beyond FX2 RAM boundaries.");
-			kfree(firmwareBinary);
-			return -EFAULT;
-		}
-		/* printk("comedi_: usbduxfast: off=%x, len=%x:",off,len); */
-
-		/* Read the record type */
-		type = hex2unsigned(buf + 7);
-
-		/* If this is an EOF record, then make it so. */
-		if (type == 1)
-			break;
-
-		if (type != 0) {
-			printk(KERN_ERR "comedi_: usbduxfast: unsupported "
-			       "record type: %u\n", type);
-			kfree(firmwareBinary);
-			return -EFAULT;
-		}
-
-		for (idx = 0, cp = buf + 9; idx < len; idx += 1, cp += 2) {
-			firmwareBinary[idx + off] = hex2unsigned(cp);
-			/* printk("%02x ",firmwareBinary[idx+off]); */
-		}
-
-		/* printk("\n"); */
-
-		if (i >= size) {
-			printk(KERN_ERR "comedi_: usbduxfast: unexpected end "
-			       "of hex file\n");
-			break;
-		}
-
+	/* we generate a local buffer for the firmware */
+	fwBuf = kzalloc(sizeFirmware, GFP_KERNEL);
+	if (!fwBuf) {
+		dev_err(&usbduxfastsub->interface->dev,
+			"comedi_: mem alloc for firmware failed\n");
+		return -ENOMEM;
 	}
-	res = firmwareUpload(udfs, firmwareBinary, maxAddr + 1);
-	kfree(firmwareBinary);
-	return res;
+	memcpy(fwBuf,firmwareBinary,sizeFirmware);
+
+	ret = usbduxfastsub_stop(usbduxfastsub);
+	if (ret < 0) {
+		dev_err(&usbduxfastsub->interface->dev,
+			"comedi_: can not stop firmware\n");
+		kfree(fwBuf);
+		return ret;
+	}
+
+	ret = usbduxfastsub_upload(usbduxfastsub, fwBuf, 0, sizeFirmware);
+	if (ret < 0) {
+		dev_err(&usbduxfastsub->interface->dev,
+			"comedi_: firmware upload failed\n");
+		kfree(fwBuf);
+		return ret;
+	}
+	ret = usbduxfastsub_start(usbduxfastsub);
+	if (ret < 0) {
+		dev_err(&usbduxfastsub->interface->dev,
+			"comedi_: can not start firmware\n");
+		kfree(fwBuf);
+		return ret;
+	}
+	kfree(fwBuf);
+	return 0;
 }
 
+
+
 static void tidy_up(struct usbduxfastsub_s *udfs)
 {
 #ifdef CONFIG_COMEDI_DEBUG
@@ -1544,7 +1447,7 @@
 	 * we need to upload the firmware here because fw will be
 	 * freed once we've left this function
 	 */
-	ret = read_firmware(usbduxfastsub_tmp, fw->data, fw->size);
+	ret = firmwareUpload(usbduxfastsub_tmp, fw->data, fw->size);
 
 	if (ret) {
 		dev_err(&usbdev->dev,
@@ -1666,7 +1569,7 @@
 
 	ret = request_firmware_nowait(THIS_MODULE,
 				      FW_ACTION_HOTPLUG,
-				      "usbduxfast_firmware.hex",
+				      "usbduxfast_firmware.bin",
 				      &udev->dev,
 				      usbduxfastsub + index,
 				      usbduxfast_firmware_request_complete_handler);
@@ -1751,9 +1654,9 @@
 	/* trying to upload the firmware into the chip */
 	if (comedi_aux_data(it->options, 0) &&
 	    it->options[COMEDI_DEVCONF_AUX_DATA_LENGTH]) {
-		read_firmware(&usbduxfastsub[index],
-			      comedi_aux_data(it->options, 0),
-			      it->options[COMEDI_DEVCONF_AUX_DATA_LENGTH]);
+		firmwareUpload(&usbduxfastsub[index],
+			       comedi_aux_data(it->options, 0),
+			       it->options[COMEDI_DEVCONF_AUX_DATA_LENGTH]);
 	}
 
 	dev->board_name = BOARDNAME;
diff --git a/drivers/staging/comedi/drivers/vmk80xx.c b/drivers/staging/comedi/drivers/vmk80xx.c
new file mode 100644
index 0000000..9de43b5
--- /dev/null
+++ b/drivers/staging/comedi/drivers/vmk80xx.c
@@ -0,0 +1,1399 @@
+/*
+    comedi/drivers/vmk80xx.c
+    Velleman USB Board Low-Level Driver
+
+    Copyright (C) 2009 Manuel Gebele <forensixs@gmx.de>, Germany
+
+    COMEDI - Linux Control and Measurement Device Interface
+    Copyright (C) 2000 David A. Schleef <ds@schleef.org>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+*/
+/*
+Driver: vmk80xx
+Description: Velleman USB Board Low-Level Driver
+Devices: K8055/K8061 aka VM110/VM140
+Author: Manuel Gebele <forensixs@gmx.de>
+Updated: Sun, 10 May 2009 11:14:59 +0200
+Status: works
+
+Supports:
+ - analog input
+ - analog output
+ - digital input
+ - digital output
+ - counter
+ - pwm
+*/
+/*
+Changelog:
+
+0.8.81	-3-  code completely rewritten (adjust driver logic)
+0.8.81  -2-  full support for K8061
+0.8.81  -1-  fix some mistaken among others the number of
+	     supported boards and I/O handling
+
+0.7.76  -4-  renamed to vmk80xx
+0.7.76  -3-  detect K8061 (only theoretically supported)
+0.7.76  -2-  code completely rewritten (adjust driver logic)
+0.7.76  -1-  support for digital and counter subdevice
+*/
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/mutex.h>
+#include <linux/errno.h>
+#include <linux/input.h>
+#include <linux/slab.h>
+#include <linux/poll.h>
+#include <linux/usb.h>
+#include <linux/uaccess.h>
+
+#include "../comedidev.h"
+
+MODULE_AUTHOR("Manuel Gebele <forensixs@gmx.de>");
+MODULE_DESCRIPTION("Velleman USB Board Low-Level Driver");
+MODULE_SUPPORTED_DEVICE("K8055/K8061 aka VM110/VM140");
+MODULE_VERSION("0.8.01");
+MODULE_LICENSE("GPL");
+
+enum {
+	DEVICE_VMK8055,
+	DEVICE_VMK8061
+};
+
+static struct usb_device_id vmk80xx_id_table[] = {
+	{ USB_DEVICE(0x10cf, 0x5500), .driver_info = DEVICE_VMK8055 },
+	{ USB_DEVICE(0x10cf, 0x5501), .driver_info = DEVICE_VMK8055 },
+	{ USB_DEVICE(0x10cf, 0x5502), .driver_info = DEVICE_VMK8055 },
+	{ USB_DEVICE(0x10cf, 0x5503), .driver_info = DEVICE_VMK8055 },
+	{ USB_DEVICE(0x10cf, 0x8061), .driver_info = DEVICE_VMK8061 },
+	{ USB_DEVICE(0x10cf, 0x8062), .driver_info = DEVICE_VMK8061 },
+	{ USB_DEVICE(0x10cf, 0x8063), .driver_info = DEVICE_VMK8061 },
+	{ USB_DEVICE(0x10cf, 0x8064), .driver_info = DEVICE_VMK8061 },
+	{ USB_DEVICE(0x10cf, 0x8065), .driver_info = DEVICE_VMK8061 },
+	{ USB_DEVICE(0x10cf, 0x8066), .driver_info = DEVICE_VMK8061 },
+	{ USB_DEVICE(0x10cf, 0x8067), .driver_info = DEVICE_VMK8061 },
+	{ USB_DEVICE(0x10cf, 0x8068), .driver_info = DEVICE_VMK8061 },
+	{ } /* terminating entry */
+};
+
+MODULE_DEVICE_TABLE(usb, vmk80xx_id_table);
+
+#define VMK8055_DI_REG          0x00
+#define VMK8055_DO_REG          0x01
+#define VMK8055_AO1_REG         0x02
+#define VMK8055_AO2_REG         0x03
+#define VMK8055_AI1_REG         0x02
+#define VMK8055_AI2_REG         0x03
+#define VMK8055_CNT1_REG        0x04
+#define VMK8055_CNT2_REG        0x06
+
+#define VMK8061_CH_REG          0x01
+#define VMK8061_DI_REG          0x01
+#define VMK8061_DO_REG          0x01
+#define VMK8061_PWM_REG1        0x01
+#define VMK8061_PWM_REG2        0x02
+#define VMK8061_CNT_REG         0x02
+#define VMK8061_AO_REG          0x02
+#define VMK8061_AI_REG1         0x02
+#define VMK8061_AI_REG2         0x03
+
+#define VMK8055_CMD_RST         0x00
+#define VMK8055_CMD_DEB1_TIME   0x01
+#define VMK8055_CMD_DEB2_TIME   0x02
+#define VMK8055_CMD_RST_CNT1    0x03
+#define VMK8055_CMD_RST_CNT2    0x04
+#define VMK8055_CMD_WRT_AD      0x05
+
+#define VMK8061_CMD_RD_AI       0x00
+#define VMK8061_CMR_RD_ALL_AI   0x01    /* !non-active! */
+#define VMK8061_CMD_SET_AO      0x02
+#define VMK8061_CMD_SET_ALL_AO  0x03    /* !non-active! */
+#define VMK8061_CMD_OUT_PWM     0x04
+#define VMK8061_CMD_RD_DI       0x05
+#define VMK8061_CMD_DO          0x06    /* !non-active! */
+#define VMK8061_CMD_CLR_DO      0x07
+#define VMK8061_CMD_SET_DO      0x08
+#define VMK8061_CMD_RD_CNT      0x09    /* TODO: completely pointless? */
+#define VMK8061_CMD_RST_CNT     0x0a    /* TODO: completely pointless? */
+#define VMK8061_CMD_RD_VERSION  0x0b    /* internal usage */
+#define VMK8061_CMD_RD_JMP_STAT 0x0c    /* TODO: not implemented yet */
+#define VMK8061_CMD_RD_PWR_STAT 0x0d    /* internal usage */
+#define VMK8061_CMD_RD_DO       0x0e
+#define VMK8061_CMD_RD_AO       0x0f
+#define VMK8061_CMD_RD_PWM      0x10
+
+#define VMK80XX_MAX_BOARDS      COMEDI_NUM_BOARD_MINORS
+
+#define TRANS_OUT_BUSY          1
+#define TRANS_IN_BUSY           2
+#define TRANS_IN_RUNNING        3
+
+#define IC3_VERSION             (1 << 0)
+#define IC6_VERSION             (1 << 1)
+
+#define URB_RCV_FLAG            (1 << 0)
+#define URB_SND_FLAG            (1 << 1)
+
+#define CONFIG_VMK80XX_DEBUG
+#undef CONFIG_VMK80XX_DEBUG
+
+#ifdef CONFIG_VMK80XX_DEBUG
+ static int dbgvm = 1;
+#else
+ static int dbgvm;
+#endif
+
+#ifdef CONFIG_COMEDI_DEBUG
+ static int dbgcm = 1;
+#else
+ static int dbgcm;
+#endif
+
+#define dbgvm(fmt, arg...)                     \
+do {                                           \
+	if (dbgvm)                             \
+		printk(KERN_DEBUG fmt, ##arg); \
+} while (0)
+
+#define dbgcm(fmt, arg...)                     \
+do {                                           \
+	if (dbgcm)                             \
+		printk(KERN_DEBUG fmt, ##arg); \
+} while (0)
+
+enum vmk80xx_model {
+	VMK8055_MODEL,
+	VMK8061_MODEL
+};
+
+struct firmware_version {
+	unsigned char ic3_vers[32]; /* USB-Controller */
+	unsigned char ic6_vers[32]; /* CPU */
+};
+
+static const struct comedi_lrange vmk8055_range = {
+	1, { UNI_RANGE(5) }
+};
+
+static const struct comedi_lrange vmk8061_range = {
+	2, { UNI_RANGE(5), UNI_RANGE(10) }
+};
+
+struct vmk80xx_board {
+	const char *name;
+	enum vmk80xx_model model;
+	const struct comedi_lrange *range;
+	__u8   ai_chans;
+	__le16 ai_bits;
+	__u8   ao_chans;
+	__le16 ao_bits;
+	__u8   di_chans;
+	__le16 di_bits;
+	__u8   do_chans;
+	__le16 do_bits;
+	__u8   cnt_chans;
+	__le16 cnt_bits;
+	__u8   pwm_chans;
+	__le16 pwm_bits;
+};
+
+enum {
+	VMK80XX_SUBD_AI,
+	VMK80XX_SUBD_AO,
+	VMK80XX_SUBD_DI,
+	VMK80XX_SUBD_DO,
+	VMK80XX_SUBD_CNT,
+	VMK80XX_SUBD_PWM,
+};
+
+struct vmk80xx_usb {
+	struct usb_device *udev;
+	struct usb_interface *intf;
+	struct usb_endpoint_descriptor *ep_rx;
+	struct usb_endpoint_descriptor *ep_tx;
+	struct usb_anchor rx_anchor;
+	struct usb_anchor tx_anchor;
+	struct vmk80xx_board board;
+	struct firmware_version fw;
+	struct semaphore limit_sem;
+	wait_queue_head_t read_wait;
+	wait_queue_head_t write_wait;
+	unsigned char *usb_rx_buf;
+	unsigned char *usb_tx_buf;
+	unsigned long flags;
+	int probed;
+	int attached;
+	int count;
+};
+
+static struct vmk80xx_usb vmb[VMK80XX_MAX_BOARDS];
+
+static DEFINE_MUTEX(glb_mutex);
+
+static void vmk80xx_tx_callback(struct urb *urb)
+{
+	struct vmk80xx_usb *dev = urb->context;
+	int stat = urb->status;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	if (stat && !(stat == -ENOENT
+		 ||   stat == -ECONNRESET
+		 ||   stat == -ESHUTDOWN))
+		dbgcm("comedi#: vmk80xx: %s - nonzero urb status (%d)\n",
+		      __func__, stat);
+
+	if (!test_bit(TRANS_OUT_BUSY, &dev->flags))
+		return;
+
+	clear_bit(TRANS_OUT_BUSY, &dev->flags);
+
+	wake_up_interruptible(&dev->write_wait);
+}
+
+static void vmk80xx_rx_callback(struct urb *urb)
+{
+	struct vmk80xx_usb *dev = urb->context;
+	int stat = urb->status;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	switch (stat) {
+	case 0:
+		break;
+	case -ENOENT:
+	case -ECONNRESET:
+	case -ESHUTDOWN:
+		break;
+	default:
+		dbgcm("comedi#: vmk80xx: %s - nonzero urb status (%d)\n",
+		      __func__, stat);
+		goto resubmit;
+	}
+
+	goto exit;
+resubmit:
+	if (test_bit(TRANS_IN_RUNNING, &dev->flags) && dev->intf) {
+		usb_anchor_urb(urb, &dev->rx_anchor);
+
+		if (!usb_submit_urb(urb, GFP_KERNEL))
+			goto exit;
+
+		err("comedi#: vmk80xx: %s - submit urb failed\n", __func__);
+
+		usb_unanchor_urb(urb);
+	}
+exit:
+	clear_bit(TRANS_IN_BUSY, &dev->flags);
+
+	wake_up_interruptible(&dev->read_wait);
+}
+
+static int vmk80xx_check_data_link(struct vmk80xx_usb *dev)
+{
+	unsigned int tx_pipe, rx_pipe;
+	unsigned char tx[1], rx[2];
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	tx_pipe = usb_sndbulkpipe(dev->udev, 0x01);
+	rx_pipe = usb_rcvbulkpipe(dev->udev, 0x81);
+
+	tx[0] = VMK8061_CMD_RD_PWR_STAT;
+
+	/* Check that IC6 (PIC16F871) is powered and
+	 * running and the data link between IC3 and
+	 * IC6 is working properly */
+	usb_bulk_msg(dev->udev, tx_pipe, tx, 1, NULL,
+		     dev->ep_tx->bInterval);
+	usb_bulk_msg(dev->udev, rx_pipe, rx, 2, NULL,
+		     HZ * 10);
+
+	return (int)rx[1];
+}
+
+static void vmk80xx_read_eeprom(struct vmk80xx_usb *dev, int flag)
+{
+	unsigned int tx_pipe, rx_pipe;
+	unsigned char tx[1], rx[64];
+	int cnt;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	tx_pipe = usb_sndbulkpipe(dev->udev, 0x01);
+	rx_pipe = usb_rcvbulkpipe(dev->udev, 0x81);
+
+	tx[0] = VMK8061_CMD_RD_VERSION;
+
+	/* Read the firmware version info of IC3 and
+	 * IC6 from the internal EEPROM of the IC */
+	usb_bulk_msg(dev->udev, tx_pipe, tx,  1, NULL,
+		     dev->ep_tx->bInterval);
+	usb_bulk_msg(dev->udev, rx_pipe, rx, 64, &cnt,
+		     HZ * 10);
+
+	rx[cnt] = '\0';
+
+	if (flag & IC3_VERSION)
+		strncpy(dev->fw.ic3_vers, rx +  1, 24);
+	else /* IC6_VERSION */
+		strncpy(dev->fw.ic6_vers, rx + 25, 24);
+}
+
+static int vmk80xx_reset_device(struct vmk80xx_usb *dev)
+{
+	struct urb *urb;
+	unsigned int tx_pipe;
+	int ival;
+	size_t size;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	urb = usb_alloc_urb(0, GFP_KERNEL);
+	if (!urb)
+		return -ENOMEM;
+
+	tx_pipe = usb_sndintpipe(dev->udev, 0x01);
+
+	ival = dev->ep_tx->bInterval;
+	size = le16_to_cpu(dev->ep_tx->wMaxPacketSize);
+
+	dev->usb_tx_buf[0] = VMK8055_CMD_RST;
+	dev->usb_tx_buf[1] = 0x00;
+	dev->usb_tx_buf[2] = 0x00;
+	dev->usb_tx_buf[3] = 0x00;
+	dev->usb_tx_buf[4] = 0x00;
+	dev->usb_tx_buf[5] = 0x00;
+	dev->usb_tx_buf[6] = 0x00;
+	dev->usb_tx_buf[7] = 0x00;
+
+	usb_fill_int_urb(urb, dev->udev, tx_pipe, dev->usb_tx_buf,
+			 size, vmk80xx_tx_callback, dev, ival);
+
+	usb_anchor_urb(urb, &dev->tx_anchor);
+
+	return usb_submit_urb(urb, GFP_KERNEL);
+}
+
+static void vmk80xx_build_int_urb(struct urb *urb, int flag)
+{
+	struct vmk80xx_usb *dev = urb->context;
+	__u8 rx_addr, tx_addr;
+	unsigned int pipe;
+	unsigned char *buf;
+	size_t size;
+	void (*callback)(struct urb *);
+	int ival;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	if (flag & URB_RCV_FLAG) {
+		rx_addr = dev->ep_rx->bEndpointAddress;
+		pipe = usb_rcvintpipe(dev->udev, rx_addr);
+		buf = dev->usb_rx_buf;
+		size = le16_to_cpu(dev->ep_rx->wMaxPacketSize);
+		callback = vmk80xx_rx_callback;
+		ival = dev->ep_rx->bInterval;
+	} else { /* URB_SND_FLAG */
+		tx_addr = dev->ep_tx->bEndpointAddress;
+		pipe = usb_sndintpipe(dev->udev, tx_addr);
+		buf = dev->usb_tx_buf;
+		size = le16_to_cpu(dev->ep_tx->wMaxPacketSize);
+		callback = vmk80xx_tx_callback;
+		ival = dev->ep_tx->bInterval;
+	}
+
+	usb_fill_int_urb(urb, dev->udev, pipe, buf,
+			 size, callback, dev, ival);
+}
+
+static void vmk80xx_do_bulk_msg(struct vmk80xx_usb *dev)
+{
+	__u8 tx_addr, rx_addr;
+	unsigned int tx_pipe, rx_pipe;
+	size_t size;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	set_bit(TRANS_IN_BUSY, &dev->flags);
+	set_bit(TRANS_OUT_BUSY, &dev->flags);
+
+	tx_addr = dev->ep_tx->bEndpointAddress;
+	rx_addr = dev->ep_rx->bEndpointAddress;
+	tx_pipe = usb_sndbulkpipe(dev->udev, tx_addr);
+	rx_pipe = usb_rcvbulkpipe(dev->udev, rx_addr);
+
+	/* The max packet size attributes of the K8061
+	 * input/output endpoints are identical */
+	size = le16_to_cpu(dev->ep_tx->wMaxPacketSize);
+
+	usb_bulk_msg(dev->udev, tx_pipe, dev->usb_tx_buf,
+		     size, NULL, dev->ep_tx->bInterval);
+	usb_bulk_msg(dev->udev, rx_pipe, dev->usb_rx_buf,
+		     size, NULL, HZ * 10);
+
+	clear_bit(TRANS_OUT_BUSY, &dev->flags);
+	clear_bit(TRANS_IN_BUSY, &dev->flags);
+}
+
+static int vmk80xx_read_packet(struct vmk80xx_usb *dev)
+{
+	struct urb *urb;
+	int retval;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	if (!dev->intf)
+		return -ENODEV;
+
+	/* Only useful for interrupt transfers */
+	if (test_bit(TRANS_IN_BUSY, &dev->flags))
+		if (wait_event_interruptible(dev->read_wait,
+			!test_bit(TRANS_IN_BUSY, &dev->flags)))
+			return -ERESTART;
+
+	if (dev->board.model == VMK8061_MODEL) {
+		vmk80xx_do_bulk_msg(dev);
+
+		return 0;
+	}
+
+	urb = usb_alloc_urb(0, GFP_KERNEL);
+	if (!urb)
+		return -ENOMEM;
+
+	urb->context = dev;
+	vmk80xx_build_int_urb(urb, URB_RCV_FLAG);
+
+	set_bit(TRANS_IN_RUNNING, &dev->flags);
+	set_bit(TRANS_IN_BUSY, &dev->flags);
+
+	usb_anchor_urb(urb, &dev->rx_anchor);
+
+	retval = usb_submit_urb(urb, GFP_KERNEL);
+	if (!retval)
+		goto exit;
+
+	clear_bit(TRANS_IN_RUNNING, &dev->flags);
+	usb_unanchor_urb(urb);
+
+exit:
+	usb_free_urb(urb);
+
+	return retval;
+}
+
+static int vmk80xx_write_packet(struct vmk80xx_usb *dev, int cmd)
+{
+	struct urb *urb;
+	int retval;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	if (!dev->intf)
+		return -ENODEV;
+
+	if (test_bit(TRANS_OUT_BUSY, &dev->flags))
+		if (wait_event_interruptible(dev->write_wait,
+			!test_bit(TRANS_OUT_BUSY, &dev->flags)))
+			return -ERESTART;
+
+	if (dev->board.model == VMK8061_MODEL) {
+		dev->usb_tx_buf[0] = cmd;
+		vmk80xx_do_bulk_msg(dev);
+
+		return 0;
+	}
+
+	urb = usb_alloc_urb(0, GFP_KERNEL);
+	if (!urb)
+		return -ENOMEM;
+
+	urb->context = dev;
+	vmk80xx_build_int_urb(urb, URB_SND_FLAG);
+
+	set_bit(TRANS_OUT_BUSY, &dev->flags);
+
+	usb_anchor_urb(urb, &dev->tx_anchor);
+
+	dev->usb_tx_buf[0] = cmd;
+
+	retval = usb_submit_urb(urb, GFP_KERNEL);
+	if (!retval)
+		goto exit;
+
+	clear_bit(TRANS_OUT_BUSY, &dev->flags);
+	usb_unanchor_urb(urb);
+
+exit:
+	usb_free_urb(urb);
+
+	return retval;
+}
+
+#define DIR_IN  1
+#define DIR_OUT 2
+
+#define rudimentary_check(dir)                             \
+do {                                                       \
+	if (!dev)                                          \
+		return -EFAULT;                            \
+	if (!dev->probed)                                  \
+		return -ENODEV;                            \
+	if (!dev->attached)                                \
+		return -ENODEV;                            \
+	if ((dir) & DIR_IN) {                              \
+		if (test_bit(TRANS_IN_BUSY, &dev->flags))  \
+			return -EBUSY;                     \
+	} else {  /* DIR_OUT */                            \
+		if (test_bit(TRANS_OUT_BUSY, &dev->flags)) \
+			return -EBUSY;                     \
+	}                                                  \
+} while (0)
+
+static int vmk80xx_ai_rinsn(struct comedi_device *cdev,
+			    struct comedi_subdevice *s,
+			    struct comedi_insn *insn, unsigned int *data)
+{
+	struct vmk80xx_usb *dev = cdev->private;
+	int chan, reg[2];
+	int n;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	rudimentary_check(DIR_IN);
+
+	down(&dev->limit_sem);
+	chan = CR_CHAN(insn->chanspec);
+
+	switch (dev->board.model) {
+	case VMK8055_MODEL:
+		if (!chan)
+			reg[0] = VMK8055_AI1_REG;
+		else
+			reg[0] = VMK8055_AI2_REG;
+		break;
+	case VMK8061_MODEL:
+		reg[0] = VMK8061_AI_REG1;
+		reg[1] = VMK8061_AI_REG2;
+		dev->usb_tx_buf[0] = VMK8061_CMD_RD_AI;
+		dev->usb_tx_buf[VMK8061_CH_REG] = chan;
+		break;
+	}
+
+	for (n = 0; n < insn->n; n++) {
+		if (vmk80xx_read_packet(dev))
+			break;
+
+		if (dev->board.model == VMK8055_MODEL) {
+			data[n] = dev->usb_rx_buf[reg[0]];
+			continue;
+		}
+
+		/* VMK8061_MODEL */
+		data[n] = dev->usb_rx_buf[reg[0]] + 256 *
+			  dev->usb_rx_buf[reg[1]];
+	}
+
+	up(&dev->limit_sem);
+
+	return n;
+}
+
+static int vmk80xx_ao_winsn(struct comedi_device *cdev,
+			    struct comedi_subdevice *s,
+			    struct comedi_insn *insn, unsigned int *data)
+{
+	struct vmk80xx_usb *dev = cdev->private;
+	int chan, cmd, reg;
+	int n;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	rudimentary_check(DIR_OUT);
+
+	down(&dev->limit_sem);
+	chan = CR_CHAN(insn->chanspec);
+
+	switch (dev->board.model) {
+	case VMK8055_MODEL:
+		cmd = VMK8055_CMD_WRT_AD;
+		if (!chan)
+			reg = VMK8055_AO1_REG;
+		else
+			reg = VMK8055_AO2_REG;
+		break;
+	default: /* NOTE: avoid compiler warnings */
+		cmd = VMK8061_CMD_SET_AO;
+		reg = VMK8061_AO_REG;
+		dev->usb_tx_buf[VMK8061_CH_REG] = chan;
+		break;
+	}
+
+	for (n = 0; n < insn->n; n++) {
+		dev->usb_tx_buf[reg] = data[n];
+
+		if (vmk80xx_write_packet(dev, cmd))
+			break;
+	}
+
+	up(&dev->limit_sem);
+
+	return n;
+}
+
+static int vmk80xx_ao_rinsn(struct comedi_device *cdev,
+			    struct comedi_subdevice *s,
+			    struct comedi_insn *insn, unsigned int *data)
+{
+	struct vmk80xx_usb *dev = cdev->private;
+	int chan, reg;
+	int n;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	rudimentary_check(DIR_IN);
+
+	down(&dev->limit_sem);
+	chan = CR_CHAN(insn->chanspec);
+
+	reg = VMK8061_AO_REG - 1;
+
+	dev->usb_tx_buf[0] = VMK8061_CMD_RD_AO;
+
+	for (n = 0; n < insn->n; n++) {
+		if (vmk80xx_read_packet(dev))
+			break;
+
+		data[n] = dev->usb_rx_buf[reg+chan];
+	}
+
+	up(&dev->limit_sem);
+
+	return n;
+}
+
+static int vmk80xx_di_rinsn(struct comedi_device *cdev,
+			    struct comedi_subdevice *s,
+			    struct comedi_insn *insn, unsigned int *data)
+{
+	struct vmk80xx_usb *dev = cdev->private;
+	int chan;
+	unsigned char *rx_buf;
+	int reg, inp;
+	int n;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	rudimentary_check(DIR_IN);
+
+	down(&dev->limit_sem);
+	chan = CR_CHAN(insn->chanspec);
+
+	rx_buf = dev->usb_rx_buf;
+
+	if (dev->board.model == VMK8061_MODEL) {
+		reg = VMK8061_DI_REG;
+		dev->usb_tx_buf[0] = VMK8061_CMD_RD_DI;
+	} else
+		reg = VMK8055_DI_REG;
+
+	for (n = 0; n < insn->n; n++) {
+		if (vmk80xx_read_packet(dev))
+			break;
+
+		if (dev->board.model == VMK8055_MODEL)
+			inp = (((rx_buf[reg] >> 4) & 0x03) |
+			       ((rx_buf[reg] << 2) & 0x04) |
+			       ((rx_buf[reg] >> 3) & 0x18));
+		else
+			inp = rx_buf[reg];
+
+		data[n] = ((inp & (1 << chan)) > 0);
+	}
+
+	up(&dev->limit_sem);
+
+	return n;
+}
+
+static int vmk80xx_do_winsn(struct comedi_device *cdev,
+			    struct comedi_subdevice *s,
+			    struct comedi_insn *insn, unsigned int *data)
+{
+
+	struct vmk80xx_usb *dev = cdev->private;
+	int chan;
+	unsigned char *tx_buf;
+	int reg, cmd;
+	int n;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	rudimentary_check(DIR_OUT);
+
+	down(&dev->limit_sem);
+	chan = CR_CHAN(insn->chanspec);
+
+	tx_buf = dev->usb_tx_buf;
+
+	for (n = 0; n < insn->n; n++) {
+		if (dev->board.model == VMK8055_MODEL) {
+			reg = VMK8055_DO_REG;
+			cmd = VMK8055_CMD_WRT_AD;
+			if (data[n] == 1)
+				tx_buf[reg] |= (1 << chan);
+			else
+				tx_buf[reg] ^= (1 << chan);
+
+			goto write_packet;
+		}
+
+		/* VMK8061_MODEL */
+		reg = VMK8061_DO_REG;
+		if (data[n] == 1) {
+			cmd = VMK8061_CMD_SET_DO;
+			tx_buf[reg] = 1 << chan;
+		} else {
+			cmd = VMK8061_CMD_CLR_DO;
+			tx_buf[reg] = 0xff - (1 << chan);
+		}
+
+write_packet:
+		if (vmk80xx_write_packet(dev, cmd))
+			break;
+	}
+
+	up(&dev->limit_sem);
+
+	return n;
+}
+
+static int vmk80xx_do_rinsn(struct comedi_device *cdev,
+			    struct comedi_subdevice *s,
+			    struct comedi_insn *insn, unsigned int *data)
+{
+	struct vmk80xx_usb *dev = cdev->private;
+	int chan, reg, mask;
+	int n;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	rudimentary_check(DIR_IN);
+
+	down(&dev->limit_sem);
+	chan = CR_CHAN(insn->chanspec);
+
+	reg = VMK8061_DO_REG;
+	mask = 1 << chan;
+
+	dev->usb_tx_buf[0] = VMK8061_CMD_RD_DO;
+
+	for (n = 0; n < insn->n; n++) {
+		if (vmk80xx_read_packet(dev))
+			break;
+
+		data[n] = (dev->usb_rx_buf[reg] & mask) >> chan;
+	}
+
+	up(&dev->limit_sem);
+
+	return n;
+}
+
+static int vmk80xx_cnt_rinsn(struct comedi_device *cdev,
+			     struct comedi_subdevice *s,
+			     struct comedi_insn *insn, unsigned int *data)
+{
+	struct vmk80xx_usb *dev = cdev->private;
+	int chan, reg[2];
+	int n;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	rudimentary_check(DIR_IN);
+
+	down(&dev->limit_sem);
+	chan = CR_CHAN(insn->chanspec);
+
+	switch (dev->board.model) {
+	case VMK8055_MODEL:
+		if (!chan)
+			reg[0] = VMK8055_CNT1_REG;
+		else
+			reg[0] = VMK8055_CNT2_REG;
+		break;
+	case VMK8061_MODEL:
+		reg[0] = VMK8061_CNT_REG;
+		reg[1] = VMK8061_CNT_REG;
+		dev->usb_tx_buf[0] = VMK8061_CMD_RD_CNT;
+		break;
+	}
+
+	for (n = 0; n < insn->n; n++) {
+		if (vmk80xx_read_packet(dev))
+			break;
+
+		if (dev->board.model == VMK8055_MODEL) {
+			data[n] = dev->usb_rx_buf[reg[0]];
+			continue;
+		}
+
+		/* VMK8061_MODEL */
+		data[n] = dev->usb_rx_buf[reg[0]*(chan+1)+1]
+		  + 256 * dev->usb_rx_buf[reg[1]*2+2];
+	}
+
+	up(&dev->limit_sem);
+
+	return n;
+}
+
+static int vmk80xx_cnt_cinsn(struct comedi_device *cdev,
+			     struct comedi_subdevice *s,
+			     struct comedi_insn *insn, unsigned int *data)
+{
+	struct vmk80xx_usb *dev = cdev->private;
+	unsigned int insn_cmd;
+	int chan, cmd, reg;
+	int n;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	rudimentary_check(DIR_OUT);
+
+	down(&dev->limit_sem);
+
+	insn_cmd = data[0];
+	if (insn_cmd != INSN_CONFIG_RESET && insn_cmd != GPCT_RESET)
+		return -EINVAL;
+
+	chan = CR_CHAN(insn->chanspec);
+
+	if (dev->board.model == VMK8055_MODEL) {
+		if (!chan) {
+			cmd = VMK8055_CMD_RST_CNT1;
+			reg = VMK8055_CNT1_REG;
+		} else {
+			cmd = VMK8055_CMD_RST_CNT2;
+			reg = VMK8055_CNT2_REG;
+		}
+
+		dev->usb_tx_buf[reg] = 0x00;
+	} else
+		cmd = VMK8061_CMD_RST_CNT;
+
+	for (n = 0; n < insn->n; n++)
+		if (vmk80xx_write_packet(dev, cmd))
+			break;
+
+	up(&dev->limit_sem);
+
+	return n;
+}
+
+static int vmk80xx_cnt_winsn(struct comedi_device *cdev,
+			     struct comedi_subdevice *s,
+			     struct comedi_insn *insn, unsigned int *data)
+{
+	struct vmk80xx_usb *dev = cdev->private;
+	unsigned long debtime, val;
+	int chan, cmd;
+	int n;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	rudimentary_check(DIR_OUT);
+
+	down(&dev->limit_sem);
+	chan = CR_CHAN(insn->chanspec);
+
+	if (!chan)
+		cmd = VMK8055_CMD_DEB1_TIME;
+	else
+		cmd = VMK8055_CMD_DEB2_TIME;
+
+	for (n = 0; n < insn->n; n++) {
+		debtime = data[n];
+		if (debtime == 0)
+			debtime = 1;
+
+		/* TODO: Prevent overflows */
+		if (debtime > 7450)
+			debtime = 7450;
+
+		val = int_sqrt(debtime * 1000 / 115);
+		if (((val + 1) * val) < debtime * 1000 / 115)
+			val += 1;
+
+		dev->usb_tx_buf[6+chan] = val;
+
+		if (vmk80xx_write_packet(dev, cmd))
+			break;
+	}
+
+	up(&dev->limit_sem);
+
+	return n;
+}
+
+static int vmk80xx_pwm_rinsn(struct comedi_device *cdev,
+			     struct comedi_subdevice *s,
+			     struct comedi_insn *insn, unsigned int *data)
+{
+	struct vmk80xx_usb *dev = cdev->private;
+	int reg[2];
+	int n;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	rudimentary_check(DIR_IN);
+
+	down(&dev->limit_sem);
+
+	reg[0] = VMK8061_PWM_REG1;
+	reg[1] = VMK8061_PWM_REG2;
+
+	dev->usb_tx_buf[0] = VMK8061_CMD_RD_PWM;
+
+	for (n = 0; n < insn->n; n++) {
+		if (vmk80xx_read_packet(dev))
+			break;
+
+		data[n] = dev->usb_rx_buf[reg[0]] + 4 *
+			  dev->usb_rx_buf[reg[1]];
+	}
+
+	up(&dev->limit_sem);
+
+	return n;
+}
+
+static int vmk80xx_pwm_winsn(struct comedi_device *cdev,
+			     struct comedi_subdevice *s,
+			     struct comedi_insn *insn, unsigned int *data)
+{
+	struct vmk80xx_usb *dev = cdev->private;
+	unsigned char *tx_buf;
+	int reg[2], cmd;
+	int n;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	rudimentary_check(DIR_OUT);
+
+	down(&dev->limit_sem);
+
+	tx_buf = dev->usb_tx_buf;
+
+	reg[0] = VMK8061_PWM_REG1;
+	reg[1] = VMK8061_PWM_REG2;
+
+	cmd = VMK8061_CMD_OUT_PWM;
+
+	/*
+	 * The followin piece of code was translated from the inline
+	 * assembler code in the DLL source code.
+	 *
+	 * asm
+	 *   mov eax, k  ; k is the value (data[n])
+	 *   and al, 03h ; al are the lower 8 bits of eax
+	 *   mov lo, al  ; lo is the low part (tx_buf[reg[0]])
+	 *   mov eax, k
+	 *   shr eax, 2  ; right shift eax register by 2
+	 *   mov hi, al  ; hi is the high part (tx_buf[reg[1]])
+	 * end;
+	 */
+	for (n = 0; n < insn->n; n++) {
+		tx_buf[reg[0]] = (unsigned char)(data[n] & 0x03);
+		tx_buf[reg[1]] = (unsigned char)(data[n] >> 2) & 0xff;
+
+		if (vmk80xx_write_packet(dev, cmd))
+			break;
+	}
+
+	up(&dev->limit_sem);
+
+	return n;
+}
+
+static int
+vmk80xx_attach(struct comedi_device *cdev, struct comedi_devconfig *it)
+{
+	int i;
+	struct vmk80xx_usb *dev;
+	int n_subd;
+	struct comedi_subdevice *s;
+	int minor;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	mutex_lock(&glb_mutex);
+
+	for (i = 0; i < VMK80XX_MAX_BOARDS; i++)
+		if (vmb[i].probed && !vmb[i].attached)
+			break;
+
+	if (i == VMK80XX_MAX_BOARDS) {
+		mutex_unlock(&glb_mutex);
+		return -ENODEV;
+	}
+
+	dev = &vmb[i];
+
+	down(&dev->limit_sem);
+
+	cdev->board_name = dev->board.name;
+	cdev->private = dev;
+
+	if (dev->board.model == VMK8055_MODEL)
+		n_subd = 5;
+	else
+		n_subd = 6;
+
+	if (alloc_subdevices(cdev, n_subd) < 0) {
+		up(&dev->limit_sem);
+		mutex_unlock(&glb_mutex);
+		return -ENOMEM;
+	}
+
+	/* Analog input subdevice */
+	s = cdev->subdevices + VMK80XX_SUBD_AI;
+	s->type = COMEDI_SUBD_AI;
+	s->subdev_flags = SDF_READABLE | SDF_GROUND;
+	s->n_chan = dev->board.ai_chans;
+	s->maxdata = (1 << dev->board.ai_bits) - 1;
+	s->range_table = dev->board.range;
+	s->insn_read = vmk80xx_ai_rinsn;
+
+	/* Analog output subdevice */
+	s = cdev->subdevices + VMK80XX_SUBD_AO;
+	s->type = COMEDI_SUBD_AO;
+	s->subdev_flags = SDF_WRITEABLE | SDF_GROUND;
+	s->n_chan = dev->board.ao_chans;
+	s->maxdata = (1 << dev->board.ao_bits) - 1;
+	s->range_table = dev->board.range;
+	s->insn_write = vmk80xx_ao_winsn;
+
+	if (dev->board.model == VMK8061_MODEL) {
+		s->subdev_flags |= SDF_READABLE;
+		s->insn_read = vmk80xx_ao_rinsn;
+	}
+
+	/* Digital input subdevice */
+	s = cdev->subdevices + VMK80XX_SUBD_DI;
+	s->type = COMEDI_SUBD_DI;
+	s->subdev_flags = SDF_READABLE | SDF_GROUND;
+	s->n_chan = dev->board.di_chans;
+	s->maxdata = (1 << dev->board.di_bits) - 1;
+	s->insn_read = vmk80xx_di_rinsn;
+
+	/* Digital output subdevice */
+	s = cdev->subdevices + VMK80XX_SUBD_DO;
+	s->type = COMEDI_SUBD_DO;
+	s->subdev_flags = SDF_WRITEABLE | SDF_GROUND;
+	s->n_chan = dev->board.do_chans;
+	s->maxdata = (1 << dev->board.do_bits) - 1;
+	s->insn_write = vmk80xx_do_winsn;
+
+	if (dev->board.model == VMK8061_MODEL) {
+		s->subdev_flags |= SDF_READABLE;
+		s->insn_read = vmk80xx_do_rinsn;
+	}
+
+	/* Counter subdevice */
+	s = cdev->subdevices + VMK80XX_SUBD_CNT;
+	s->type = COMEDI_SUBD_COUNTER;
+	s->subdev_flags = SDF_READABLE;
+	s->n_chan = dev->board.cnt_chans;
+	s->insn_read = vmk80xx_cnt_rinsn;
+	s->insn_config = vmk80xx_cnt_cinsn;
+
+	if (dev->board.model == VMK8055_MODEL) {
+		s->subdev_flags |= SDF_WRITEABLE;
+		s->maxdata = (1 << dev->board.cnt_bits) - 1;
+		s->insn_write = vmk80xx_cnt_winsn;
+	}
+
+	/* PWM subdevice */
+	if (dev->board.model == VMK8061_MODEL) {
+		s = cdev->subdevices + VMK80XX_SUBD_PWM;
+		s->type = COMEDI_SUBD_PWM;
+		s->subdev_flags = SDF_READABLE | SDF_WRITEABLE;
+		s->n_chan = dev->board.pwm_chans;
+		s->maxdata = (1 << dev->board.pwm_bits) - 1;
+		s->insn_read = vmk80xx_pwm_rinsn;
+		s->insn_write = vmk80xx_pwm_winsn;
+	}
+
+	dev->attached = 1;
+
+	minor = cdev->minor;
+
+	printk(KERN_INFO
+	       "comedi%d: vmk80xx: board #%d [%s] attached to comedi\n",
+	       minor, dev->count, dev->board.name);
+
+	up(&dev->limit_sem);
+	mutex_unlock(&glb_mutex);
+
+	return 0;
+}
+
+static int vmk80xx_detach(struct comedi_device *cdev)
+{
+	struct vmk80xx_usb *dev;
+	int minor;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	if (!cdev)
+		return -EFAULT;
+
+	dev = cdev->private;
+	if (!dev)
+		return -EFAULT;
+
+	down(&dev->limit_sem);
+
+	cdev->private = NULL;
+	dev->attached = 0;
+
+	minor = cdev->minor;
+
+	printk(KERN_INFO
+	       "comedi%d: vmk80xx: board #%d [%s] detached from comedi\n",
+	       minor, dev->count, dev->board.name);
+
+	up(&dev->limit_sem);
+
+	return 0;
+}
+
+static int
+vmk80xx_probe(struct usb_interface *intf, const struct usb_device_id *id)
+{
+	int i;
+	struct vmk80xx_usb *dev;
+	struct usb_host_interface *iface_desc;
+	struct usb_endpoint_descriptor *ep_desc;
+	size_t size;
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	mutex_lock(&glb_mutex);
+
+	for (i = 0; i < VMK80XX_MAX_BOARDS; i++)
+		if (!vmb[i].probed)
+			break;
+
+	if (i == VMK80XX_MAX_BOARDS) {
+		mutex_unlock(&glb_mutex);
+		return -EMFILE;
+	}
+
+	dev = &vmb[i];
+
+	memset(dev, 0x00, sizeof(struct vmk80xx_usb));
+	dev->count = i;
+
+	iface_desc = intf->cur_altsetting;
+	if (iface_desc->desc.bNumEndpoints != 2)
+		goto error;
+
+	for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
+		ep_desc = &iface_desc->endpoint[i].desc;
+
+		if (usb_endpoint_is_int_in(ep_desc)) {
+			dev->ep_rx = ep_desc;
+			continue;
+		}
+
+		if (usb_endpoint_is_int_out(ep_desc)) {
+			dev->ep_tx = ep_desc;
+			continue;
+		}
+
+		if (usb_endpoint_is_bulk_in(ep_desc)) {
+			dev->ep_rx = ep_desc;
+			continue;
+		}
+
+		if (usb_endpoint_is_bulk_out(ep_desc)) {
+			dev->ep_tx = ep_desc;
+			continue;
+		}
+	}
+
+	if (!dev->ep_rx || !dev->ep_tx)
+		goto error;
+
+	size = le16_to_cpu(dev->ep_rx->wMaxPacketSize);
+	dev->usb_rx_buf = kmalloc(size, GFP_KERNEL);
+	if (!dev->usb_rx_buf) {
+		mutex_unlock(&glb_mutex);
+		return -ENOMEM;
+	}
+
+	size = le16_to_cpu(dev->ep_tx->wMaxPacketSize);
+	dev->usb_tx_buf = kmalloc(size, GFP_KERNEL);
+	if (!dev->usb_tx_buf) {
+		kfree(dev->usb_rx_buf);
+		mutex_unlock(&glb_mutex);
+		return -ENOMEM;
+	}
+
+	dev->udev = interface_to_usbdev(intf);
+	dev->intf = intf;
+
+	sema_init(&dev->limit_sem, 8);
+	init_waitqueue_head(&dev->read_wait);
+	init_waitqueue_head(&dev->write_wait);
+
+	init_usb_anchor(&dev->rx_anchor);
+	init_usb_anchor(&dev->tx_anchor);
+
+	usb_set_intfdata(intf, dev);
+
+	switch (id->driver_info) {
+	case DEVICE_VMK8055:
+		dev->board.name = "K8055 (VM110)";
+		dev->board.model = VMK8055_MODEL;
+		dev->board.range = &vmk8055_range;
+		dev->board.ai_chans = 2;
+		dev->board.ai_bits = 8;
+		dev->board.ao_chans = 2;
+		dev->board.ao_bits = 8;
+		dev->board.di_chans = 5;
+		dev->board.di_bits = 1;
+		dev->board.do_chans = 8;
+		dev->board.do_bits = 1;
+		dev->board.cnt_chans = 2;
+		dev->board.cnt_bits = 16;
+		dev->board.pwm_chans = 0;
+		dev->board.pwm_bits = 0;
+		break;
+	case DEVICE_VMK8061:
+		dev->board.name = "K8061 (VM140)";
+		dev->board.model = VMK8061_MODEL;
+		dev->board.range = &vmk8061_range;
+		dev->board.ai_chans = 8;
+		dev->board.ai_bits = 10;
+		dev->board.ao_chans = 8;
+		dev->board.ao_bits = 8;
+		dev->board.di_chans = 8;
+		dev->board.di_bits = 1;
+		dev->board.do_chans = 8;
+		dev->board.do_bits = 1;
+		dev->board.cnt_chans = 2;
+		dev->board.cnt_bits = 0;
+		dev->board.pwm_chans = 1;
+		dev->board.pwm_bits = 10;
+		break;
+	}
+
+	if (dev->board.model == VMK8061_MODEL) {
+		vmk80xx_read_eeprom(dev, IC3_VERSION);
+		printk(KERN_INFO "comedi#: vmk80xx: %s\n",
+		       dev->fw.ic3_vers);
+
+		if (vmk80xx_check_data_link(dev)) {
+			vmk80xx_read_eeprom(dev, IC6_VERSION);
+			printk(KERN_INFO "comedi#: vmk80xx: %s\n",
+			       dev->fw.ic6_vers);
+		} else
+			dbgcm("comedi#: vmk80xx: no conn. to CPU\n");
+	}
+
+	if (dev->board.model == VMK8055_MODEL)
+		vmk80xx_reset_device(dev);
+
+	dev->probed = 1;
+
+	printk(KERN_INFO "comedi#: vmk80xx: board #%d [%s] now attached\n",
+	       dev->count, dev->board.name);
+
+	mutex_unlock(&glb_mutex);
+
+	return 0;
+error:
+	mutex_unlock(&glb_mutex);
+
+	return -ENODEV;
+}
+
+static void vmk80xx_disconnect(struct usb_interface *intf)
+{
+	struct vmk80xx_usb *dev = usb_get_intfdata(intf);
+
+	dbgvm("vmk80xx: %s\n", __func__);
+
+	if (!dev)
+		return;
+
+	mutex_lock(&glb_mutex);
+	down(&dev->limit_sem);
+
+	dev->probed = 0;
+	usb_set_intfdata(dev->intf, NULL);
+
+	usb_kill_anchored_urbs(&dev->rx_anchor);
+	usb_kill_anchored_urbs(&dev->tx_anchor);
+
+	kfree(dev->usb_rx_buf);
+	kfree(dev->usb_tx_buf);
+
+	printk(KERN_INFO "comedi#: vmk80xx: board #%d [%s] now detached\n",
+	       dev->count, dev->board.name);
+
+	up(&dev->limit_sem);
+	mutex_unlock(&glb_mutex);
+}
+
+/* TODO: Add support for suspend, resume, pre_reset,
+ * post_reset and flush */
+static struct usb_driver vmk80xx_driver = {
+	.name       = "vmk80xx",
+	.probe      = vmk80xx_probe,
+	.disconnect = vmk80xx_disconnect,
+	.id_table   = vmk80xx_id_table
+};
+
+static struct comedi_driver driver_vmk80xx = {
+	.module      = THIS_MODULE,
+	.driver_name = "vmk80xx",
+	.attach      = vmk80xx_attach,
+	.detach      = vmk80xx_detach
+};
+
+static int __init vmk80xx_init(void)
+{
+	printk(KERN_INFO "vmk80xx: version 0.8.01 "
+	       "Manuel Gebele <forensixs@gmx.de>\n");
+	usb_register(&vmk80xx_driver);
+	return comedi_driver_register(&driver_vmk80xx);
+}
+
+static void __exit vmk80xx_exit(void)
+{
+	comedi_driver_unregister(&driver_vmk80xx);
+	usb_deregister(&vmk80xx_driver);
+}
+
+module_init(vmk80xx_init);
+module_exit(vmk80xx_exit);
diff --git a/drivers/staging/comedi/interrupt.h b/drivers/staging/comedi/interrupt.h
deleted file mode 100644
index d1f0989..0000000
--- a/drivers/staging/comedi/interrupt.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
-    linux/interrupt.h compatibility header
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program; if not, write to the Free Software
-    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#ifndef __COMPAT_LINUX_INTERRUPT_H_
-#define __COMPAT_LINUX_INTERRUPT_H_
-
-#include <linux/interrupt.h>
-
-#ifndef IRQF_DISABLED
-#define IRQF_DISABLED           SA_INTERRUPT
-#define IRQF_SAMPLE_RANDOM      SA_SAMPLE_RANDOM
-#define IRQF_SHARED             SA_SHIRQ
-#define IRQF_PROBE_SHARED       SA_PROBEIRQ
-#define IRQF_PERCPU             SA_PERCPU
-#ifdef SA_TRIGGER_MASK
-#define IRQF_TRIGGER_NONE       0
-#define IRQF_TRIGGER_LOW        SA_TRIGGER_LOW
-#define IRQF_TRIGGER_HIGH       SA_TRIGGER_HIGH
-#define IRQF_TRIGGER_FALLING    SA_TRIGGER_FALLING
-#define IRQF_TRIGGER_RISING     SA_TRIGGER_RISING
-#define IRQF_TRIGGER_MASK       SA_TRIGGER_MASK
-#else
-#define IRQF_TRIGGER_NONE       0
-#define IRQF_TRIGGER_LOW        0
-#define IRQF_TRIGGER_HIGH       0
-#define IRQF_TRIGGER_FALLING    0
-#define IRQF_TRIGGER_RISING     0
-#define IRQF_TRIGGER_MASK       0
-#endif
-#endif
-
-#define PT_REGS_ARG
-#define PT_REGS_CALL
-#define PT_REGS_NULL
-
-#endif
diff --git a/drivers/staging/comedi/kcomedilib/data.c b/drivers/staging/comedi/kcomedilib/data.c
index 9797e13..d808556 100644
--- a/drivers/staging/comedi/kcomedilib/data.c
+++ b/drivers/staging/comedi/kcomedilib/data.c
@@ -23,9 +23,10 @@
 
 #include "../comedi.h"
 #include "../comedilib.h"
-#include "../comedidev.h"	/* for comedi_udelay() */
+#include "../comedidev.h"
 
 #include <linux/string.h>
+#include <linux/delay.h>
 
 int comedi_data_write(void *dev, unsigned int subdev, unsigned int chan,
 	unsigned int range, unsigned int aref, unsigned int data)
@@ -83,7 +84,7 @@
 	if (retval < 0)
 		return retval;
 
-	comedi_udelay((nano_sec + 999) / 1000);
+	udelay((nano_sec + 999) / 1000);
 
 	return comedi_data_read(dev, subdev, chan, range, aref, data);
 }
diff --git a/drivers/staging/comedi/kcomedilib/kcomedilib_main.c b/drivers/staging/comedi/kcomedilib/kcomedilib_main.c
index a4fa957..b39ea7c 100644
--- a/drivers/staging/comedi/kcomedilib/kcomedilib_main.c
+++ b/drivers/staging/comedi/kcomedilib/kcomedilib_main.c
@@ -105,7 +105,7 @@
 
 void comedi_perror(const char *message)
 {
-	rt_printk("%s: unknown error\n", message);
+	printk("%s: unknown error\n", message);
 }
 
 char *comedi_strerror(int err)
@@ -150,10 +150,6 @@
 
 	runflags = SRF_RUNNING;
 
-#ifdef CONFIG_COMEDI_RT
-	if (comedi_switch_to_rt(dev) == 0)
-		runflags |= SRF_RT;
-#endif
 	comedi_set_subdevice_runflags(s, ~0, runflags);
 
 	comedi_reset_async_buf(async);
@@ -208,7 +204,7 @@
 				ret = -EINVAL;
 				break;
 			}
-			comedi_udelay(insn->data[0]);
+			udelay(insn->data[0]);
 			ret = 1;
 			break;
 		case INSN_INTTRIG:
@@ -217,19 +213,19 @@
 				break;
 			}
 			if (insn->subdev >= dev->n_subdevices) {
-				rt_printk("%d not usable subdevice\n",
+				printk("%d not usable subdevice\n",
 					insn->subdev);
 				ret = -EINVAL;
 				break;
 			}
 			s = dev->subdevices + insn->subdev;
 			if (!s->async) {
-				rt_printk("no async\n");
+				printk("no async\n");
 				ret = -EINVAL;
 				break;
 			}
 			if (!s->async->inttrig) {
-				rt_printk("no inttrig\n");
+				printk("no inttrig\n");
 				ret = -EAGAIN;
 				break;
 			}
@@ -249,7 +245,7 @@
 		s = dev->subdevices + insn->subdev;
 
 		if (s->type == COMEDI_SUBD_UNUSED) {
-			rt_printk("%d not useable subdevice\n", insn->subdev);
+			printk("%d not useable subdevice\n", insn->subdev);
 			ret = -EIO;
 			goto error;
 		}
@@ -258,7 +254,7 @@
 
 		ret = check_chanlist(s, 1, &insn->chanspec);
 		if (ret < 0) {
-			rt_printk("bad chanspec\n");
+			printk("bad chanspec\n");
 			ret = -EINVAL;
 			goto error;
 		}
@@ -295,7 +291,7 @@
 #if 0
 	/* XXX do we want this? -- abbotti #if'ed it out for now. */
 	if (ret != insn->n) {
-		rt_printk("BUG: result of insn != insn.n\n");
+		printk("BUG: result of insn != insn.n\n");
 		ret = -EINVAL;
 		goto error;
 	}
@@ -336,7 +332,7 @@
 
 	s = dev->subdevices + subdevice;
 
-	comedi_spin_lock_irqsave(&s->spin_lock, flags);
+	spin_lock_irqsave(&s->spin_lock, flags);
 
 	if (s->busy) {
 		ret = -EBUSY;
@@ -348,7 +344,7 @@
 		}
 	}
 
-	comedi_spin_unlock_irqrestore(&s->spin_lock, flags);
+	spin_unlock_irqrestore(&s->spin_lock, flags);
 
 	return ret;
 }
@@ -382,7 +378,7 @@
 
 	async = s->async;
 
-	comedi_spin_lock_irqsave(&s->spin_lock, flags);
+	spin_lock_irqsave(&s->spin_lock, flags);
 
 	if (s->busy) {
 		ret = -EBUSY;
@@ -400,7 +396,7 @@
 		ret = 0;
 	}
 
-	comedi_spin_unlock_irqrestore(&s->spin_lock, flags);
+	spin_unlock_irqrestore(&s->spin_lock, flags);
 
 	return ret;
 }
@@ -449,11 +445,6 @@
 	if (ret)
 		return ret;
 
-#ifdef CONFIG_COMEDI_RT
-	if (comedi_get_subdevice_runflags(s) & SRF_RT)
-		comedi_switch_to_non_rt(dev);
-
-#endif
 	comedi_set_subdevice_runflags(s, SRF_RUNNING | SRF_RT, 0);
 	s->async->inttrig = NULL;
 	s->busy = NULL;
diff --git a/drivers/staging/comedi/kcomedilib/ksyms.c b/drivers/staging/comedi/kcomedilib/ksyms.c
index 3db86da..314765d 100644
--- a/drivers/staging/comedi/kcomedilib/ksyms.c
+++ b/drivers/staging/comedi/kcomedilib/ksyms.c
@@ -59,7 +59,7 @@
 EXPORT_SYMBOL(comedi_loglevel);
 EXPORT_SYMBOL(comedi_perror);
 EXPORT_SYMBOL(comedi_strerror);
-//EXPORT_SYMBOL(comedi_errno);
+/* EXPORT_SYMBOL(comedi_errno); */
 EXPORT_SYMBOL(comedi_fileno);
 
 /* device queries */
@@ -73,8 +73,10 @@
 EXPORT_SYMBOL(comedi_find_subdevice_by_type);
 EXPORT_SYMBOL(comedi_get_subdevice_flags);
 EXPORT_SYMBOL(comedi_get_n_channels);
-//EXPORT_SYMBOL(comedi_range_is_chan_specific);
-//EXPORT_SYMBOL(comedi_maxdata_is_chan_specific);
+/*
+* EXPORT_SYMBOL(comedi_range_is_chan_specific);
+* EXPORT_SYMBOL(comedi_maxdata_is_chan_specific);
+*/
 
 /* channel queries */
 EXPORT_SYMBOL(comedi_get_maxdata);
@@ -82,25 +84,29 @@
 EXPORT_SYMBOL(comedi_get_rangetype);
 #endif
 EXPORT_SYMBOL(comedi_get_n_ranges);
-//EXPORT_SYMBOL(comedi_find_range);
+/* EXPORT_SYMBOL(comedi_find_range); */
 
 /* buffer queries */
 EXPORT_SYMBOL(comedi_get_buffer_size);
-//EXPORT_SYMBOL(comedi_get_max_buffer_size);
-//EXPORT_SYMBOL(comedi_set_buffer_size);
+/*
+* EXPORT_SYMBOL(comedi_get_max_buffer_size);
+* EXPORT_SYMBOL(comedi_set_buffer_size);
+*/
 EXPORT_SYMBOL(comedi_get_buffer_contents);
 EXPORT_SYMBOL(comedi_get_buffer_offset);
 
 /* low-level stuff */
-//EXPORT_SYMBOL(comedi_trigger);
-//EXPORT_SYMBOL(comedi_do_insnlist);
+/*
+* EXPORT_SYMBOL(comedi_trigger); EXPORT_SYMBOL(comedi_do_insnlist);
+*/
 EXPORT_SYMBOL(comedi_do_insn);
 EXPORT_SYMBOL(comedi_lock);
 EXPORT_SYMBOL(comedi_unlock);
 
 /* physical units */
-//EXPORT_SYMBOL(comedi_to_phys);
-//EXPORT_SYMBOL(comedi_from_phys);
+/*
+* EXPORT_SYMBOL(comedi_to_phys); EXPORT_SYMBOL(comedi_from_phys);
+*/
 
 /* synchronous stuff */
 EXPORT_SYMBOL(comedi_data_read);
@@ -113,13 +119,16 @@
 EXPORT_SYMBOL(comedi_dio_bitfield);
 
 /* slowly varying stuff */
-//EXPORT_SYMBOL(comedi_sv_init);
-//EXPORT_SYMBOL(comedi_sv_update);
-//EXPORT_SYMBOL(comedi_sv_measure);
+/*
+* EXPORT_SYMBOL(comedi_sv_init); EXPORT_SYMBOL(comedi_sv_update);
+* EXPORT_SYMBOL(comedi_sv_measure);
+*/
 
 /* commands */
-//EXPORT_SYMBOL(comedi_get_cmd_src_mask);
-//EXPORT_SYMBOL(comedi_get_cmd_generic_timed);
+/*
+* EXPORT_SYMBOL(comedi_get_cmd_src_mask);
+* EXPORT_SYMBOL(comedi_get_cmd_generic_timed);
+*/
 EXPORT_SYMBOL(comedi_cancel);
 EXPORT_SYMBOL(comedi_command);
 EXPORT_SYMBOL(comedi_command_test);
@@ -129,12 +138,14 @@
 EXPORT_SYMBOL(comedi_mark_buffer_read);
 EXPORT_SYMBOL(comedi_mark_buffer_written);
 
-//EXPORT_SYMBOL(comedi_get_range);
+/* EXPORT_SYMBOL(comedi_get_range); */
 EXPORT_SYMBOL(comedi_get_len_chanlist);
 
 /* deprecated */
-//EXPORT_SYMBOL(comedi_get_timer);
-//EXPORT_SYMBOL(comedi_timed_1chan);
+/*
+* EXPORT_SYMBOL(comedi_get_timer);
+* EXPORT_SYMBOL(comedi_timed_1chan);
+*/
 
 /* alpha */
-//EXPORT_SYMBOL(comedi_set_global_oor_behavior);
+/* EXPORT_SYMBOL(comedi_set_global_oor_behavior); */
diff --git a/drivers/staging/comedi/range.c b/drivers/staging/comedi/range.c
index ac200d9..445909e 100644
--- a/drivers/staging/comedi/range.c
+++ b/drivers/staging/comedi/range.c
@@ -32,7 +32,7 @@
 const struct comedi_lrange range_unknown = { 1, {{0, 1000000, UNIT_none}} };
 
 /*
-   	COMEDI_RANGEINFO
+	COMEDI_RANGEINFO
 	range information ioctl
 
 	arg:
@@ -130,8 +130,7 @@
 			if (CR_CHAN(chanlist[i]) >= s->n_chan ||
 				CR_RANGE(chanlist[i]) >= s->range_table->length
 				|| aref_invalid(s, chanlist[i])) {
-				rt_printk
-					("bad chanlist[%d]=0x%08x n_chan=%d range length=%d\n",
+				printk("bad chanlist[%d]=0x%08x n_chan=%d range length=%d\n",
 					i, chanlist[i], s->n_chan,
 					s->range_table->length);
 #if 0
@@ -147,13 +146,13 @@
 				CR_RANGE(chanlist[i]) >=
 				s->range_table_list[chan]->length
 				|| aref_invalid(s, chanlist[i])) {
-				rt_printk("bad chanlist[%d]=0x%08x\n", i,
+				printk("bad chanlist[%d]=0x%08x\n", i,
 					chanlist[i]);
 				return -EINVAL;
 			}
 		}
 	} else {
-		rt_printk("comedi: (bug) no range type list!\n");
+		printk("comedi: (bug) no range type list!\n");
 		return -EINVAL;
 	}
 	return 0;
diff --git a/drivers/staging/comedi/rt.c b/drivers/staging/comedi/rt.c
deleted file mode 100644
index e9f5777..0000000
--- a/drivers/staging/comedi/rt.c
+++ /dev/null
@@ -1,411 +0,0 @@
-/*
-    comedi/rt.c
-    comedi kernel module
-
-    COMEDI - Linux Control and Measurement Device Interface
-    Copyright (C) 1997-2000 David A. Schleef <ds@schleef.org>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program; if not, write to the Free Software
-    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
-*/
-
-#undef DEBUG
-
-#define __NO_VERSION__
-#include <linux/comedidev.h>
-
-#include <linux/errno.h>
-#include <linux/kernel.h>
-#include <linux/sched.h>
-#include <linux/fcntl.h>
-#include <linux/delay.h>
-#include <linux/ioport.h>
-#include <linux/mm.h>
-#include <linux/slab.h>
-#include <asm/io.h>
-
-#include "rt_pend_tq.h"
-
-#ifdef CONFIG_COMEDI_RTAI
-#include <rtai.h>
-#endif
-
-#ifdef CONFIG_COMEDI_FUSION
-#include <nucleus/asm/hal.h>
-#endif
-
-#ifdef CONFIG_COMEDI_RTL
-#include <rtl_core.h>
-#include <rtl_sync.h>
-#endif
-
-struct comedi_irq_struct {
-	int rt;
-	int irq;
-	 irqreturn_t(*handler) (int irq, void *dev_id PT_REGS_ARG);
-	unsigned long flags;
-	const char *device;
-	struct comedi_device *dev_id;
-};
-
-static int comedi_rt_get_irq(struct comedi_irq_struct *it);
-static int comedi_rt_release_irq(struct comedi_irq_struct *it);
-
-static struct comedi_irq_struct *comedi_irqs[NR_IRQS];
-
-int comedi_request_irq(unsigned irq, irqreturn_t(*handler) (int,
-		void *PT_REGS_ARG), unsigned long flags, const char *device,
-	struct comedi_device *dev_id)
-{
-	struct comedi_irq_struct *it;
-	int ret;
-	/* null shared interrupt flag, since rt interrupt handlers do not
-	 * support it, and this version of comedi_request_irq() is only
-	 * called for kernels with rt support */
-	unsigned long unshared_flags = flags & ~IRQF_SHARED;
-
-	ret = request_irq(irq, handler, unshared_flags, device, dev_id);
-	if (ret < 0) {
-		/*  we failed, so fall back on allowing shared interrupt (which we won't ever make RT) */
-		if (flags & IRQF_SHARED) {
-			rt_printk
-				("comedi: cannot get unshared interrupt, will not use RT interrupts.\n");
-			ret = request_irq(irq, handler, flags, device, dev_id);
-		}
-		if (ret < 0)
-			return ret;
-
-	} else {
-		it = kzalloc(sizeof(struct comedi_irq_struct), GFP_KERNEL);
-		if (!it)
-			return -ENOMEM;
-
-		it->handler = handler;
-		it->irq = irq;
-		it->dev_id = dev_id;
-		it->device = device;
-		it->flags = unshared_flags;
-		comedi_irqs[irq] = it;
-	}
-	return 0;
-}
-
-void comedi_free_irq(unsigned int irq, struct comedi_device *dev_id)
-{
-	struct comedi_irq_struct *it;
-
-	free_irq(irq, dev_id);
-
-	it = comedi_irqs[irq];
-	if (it == NULL)
-		return;
-
-	if (it->rt) {
-		printk("real-time IRQ allocated at board removal (ignore)\n");
-		comedi_rt_release_irq(it);
-	}
-
-	kfree(it);
-	comedi_irqs[irq] = NULL;
-}
-
-int comedi_switch_to_rt(struct comedi_device *dev)
-{
-	struct comedi_irq_struct *it;
-	unsigned long flags;
-
-	it = comedi_irqs[dev->irq];
-	/* drivers might not be using an interrupt for commands,
-	   or we might not have been able to get an unshared irq */
-	if (it == NULL)
-		return -1;
-
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
-
-	if (!dev->rt)
-		comedi_rt_get_irq(it);
-
-	dev->rt++;
-	it->rt = 1;
-
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
-
-	return 0;
-}
-
-void comedi_switch_to_non_rt(struct comedi_device *dev)
-{
-	struct comedi_irq_struct *it;
-	unsigned long flags;
-
-	it = comedi_irqs[dev->irq];
-	if (it == NULL)
-		return;
-
-	comedi_spin_lock_irqsave(&dev->spinlock, flags);
-
-	dev->rt--;
-	if (!dev->rt)
-		comedi_rt_release_irq(it);
-
-	it->rt = 0;
-
-	comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
-}
-
-void wake_up_int_handler(int arg1, void *arg2)
-{
-	wake_up_interruptible((wait_queue_head_t *) arg2);
-}
-
-void comedi_rt_pend_wakeup(wait_queue_head_t *q)
-{
-	rt_pend_call(wake_up_int_handler, 0, q);
-}
-
-/* RTAI section */
-#ifdef CONFIG_COMEDI_RTAI
-
-#ifndef HAVE_RT_REQUEST_IRQ_WITH_ARG
-#define DECLARE_VOID_IRQ(irq) \
-static void handle_void_irq_ ## irq (void){ handle_void_irq(irq); }
-
-static void handle_void_irq(int irq)
-{
-	struct comedi_irq_struct *it;
-
-	it = comedi_irqs[irq];
-	if (it == NULL) {
-		rt_printk("comedi: null irq struct?\n");
-		return;
-	}
-	it->handler(irq, it->dev_id PT_REGS_NULL);
-	rt_enable_irq(irq);	/* needed by rtai-adeos, seems like it shouldn't hurt earlier versions */
-}
-
-DECLARE_VOID_IRQ(0);
-DECLARE_VOID_IRQ(1);
-DECLARE_VOID_IRQ(2);
-DECLARE_VOID_IRQ(3);
-DECLARE_VOID_IRQ(4);
-DECLARE_VOID_IRQ(5);
-DECLARE_VOID_IRQ(6);
-DECLARE_VOID_IRQ(7);
-DECLARE_VOID_IRQ(8);
-DECLARE_VOID_IRQ(9);
-DECLARE_VOID_IRQ(10);
-DECLARE_VOID_IRQ(11);
-DECLARE_VOID_IRQ(12);
-DECLARE_VOID_IRQ(13);
-DECLARE_VOID_IRQ(14);
-DECLARE_VOID_IRQ(15);
-DECLARE_VOID_IRQ(16);
-DECLARE_VOID_IRQ(17);
-DECLARE_VOID_IRQ(18);
-DECLARE_VOID_IRQ(19);
-DECLARE_VOID_IRQ(20);
-DECLARE_VOID_IRQ(21);
-DECLARE_VOID_IRQ(22);
-DECLARE_VOID_IRQ(23);
-
-static void handle_void_irq_ptrs[] = {
-	handle_void_irq_0,
-	handle_void_irq_1,
-	handle_void_irq_2,
-	handle_void_irq_3,
-	handle_void_irq_4,
-	handle_void_irq_5,
-	handle_void_irq_6,
-	handle_void_irq_7,
-	handle_void_irq_8,
-	handle_void_irq_9,
-	handle_void_irq_10,
-	handle_void_irq_11,
-	handle_void_irq_12,
-	handle_void_irq_13,
-	handle_void_irq_14,
-	handle_void_irq_15,
-	handle_void_irq_16,
-	handle_void_irq_17,
-	handle_void_irq_18,
-	handle_void_irq_19,
-	handle_void_irq_20,
-	handle_void_irq_21,
-	handle_void_irq_22,
-	handle_void_irq_23,
-};
-
-static int comedi_rt_get_irq(struct comedi_irq_struct *it)
-{
-	rt_request_global_irq(it->irq, handle_void_irq_ptrs[it->irq]);
-	rt_startup_irq(it->irq);
-
-	return 0;
-}
-
-static int comedi_rt_release_irq(struct comedi_irq_struct *it)
-{
-	rt_shutdown_irq(it->irq);
-	rt_free_global_irq(it->irq);
-	return 0;
-}
-#else
-
-static int comedi_rt_get_irq(struct comedi_irq_struct *it)
-{
-	int ret;
-
-	ret = rt_request_global_irq_arg(it->irq, it->handler, it->flags,
-		it->device, it->dev_id);
-	if (ret < 0) {
-		rt_printk("rt_request_global_irq_arg() returned %d\n", ret);
-		return ret;
-	}
-	rt_startup_irq(it->irq);
-
-	return 0;
-}
-
-static int comedi_rt_release_irq(struct comedi_irq_struct *it)
-{
-	rt_shutdown_irq(it->irq);
-	rt_free_global_irq(it->irq);
-	return 0;
-}
-#endif
-
-void comedi_rt_init(void)
-{
-	rt_mount_rtai();
-	rt_pend_tq_init();
-}
-
-void comedi_rt_cleanup(void)
-{
-	rt_umount_rtai();
-	rt_pend_tq_cleanup();
-}
-
-#endif
-
-/* Fusion section */
-#ifdef CONFIG_COMEDI_FUSION
-
-static void fusion_handle_irq(unsigned int irq, void *cookie)
-{
-	struct comedi_irq_struct *it = cookie;
-
-	it->handler(irq, it->dev_id PT_REGS_NULL);
-	rthal_irq_enable(irq);
-}
-
-static int comedi_rt_get_irq(struct comedi_irq_struct *it)
-{
-	rthal_irq_request(it->irq, fusion_handle_irq, it);
-	rthal_irq_enable(it->irq);
-	return 0;
-}
-
-static int comedi_rt_release_irq(struct comedi_irq_struct *it)
-{
-	rthal_irq_disable(it->irq);
-	rthal_irq_release(it->irq);
-	return 0;
-}
-
-void comedi_rt_init(void)
-{
-	rt_pend_tq_init();
-}
-
-void comedi_rt_cleanup(void)
-{
-	rt_pend_tq_cleanup();
-}
-
-#endif /*CONFIG_COMEDI_FUSION */
-
-/* RTLinux section */
-#ifdef CONFIG_COMEDI_RTL
-
-static unsigned int handle_rtl_irq(unsigned int irq PT_REGS_ARG)
-{
-	struct comedi_irq_struct *it;
-
-	it = comedi_irqs[irq];
-	if (it == NULL)
-		return 0;
-	it->handler(irq, it->dev_id PT_REGS_NULL);
-	rtl_hard_enable_irq(irq);
-	return 0;
-}
-
-static int comedi_rt_get_irq(struct comedi_irq_struct *it)
-{
-	rtl_request_global_irq(it->irq, handle_rtl_irq);
-	return 0;
-}
-
-static int comedi_rt_release_irq(struct comedi_irq_struct *it)
-{
-	rtl_free_global_irq(it->irq);
-	return 0;
-}
-
-void comedi_rt_init(void)
-{
-	rt_pend_tq_init();
-}
-
-void comedi_rt_cleanup(void)
-{
-	rt_pend_tq_cleanup();
-}
-
-#endif
-
-#ifdef CONFIG_COMEDI_PIRQ
-static int comedi_rt_get_irq(struct comedi_irq_struct *it)
-{
-	int ret;
-
-	free_irq(it->irq, it->dev_id);
-	ret = request_irq(it->irq, it->handler, it->flags | SA_PRIORITY,
-		it->device, it->dev_id);
-
-	return ret;
-}
-
-static int comedi_rt_release_irq(struct comedi_irq_struct *it)
-{
-	int ret;
-
-	free_irq(it->irq, it->dev_id);
-	ret = request_irq(it->irq, it->handler, it->flags,
-		it->device, it->dev_id);
-
-	return ret;
-}
-
-void comedi_rt_init(void)
-{
-	/* rt_pend_tq_init(); */
-}
-
-void comedi_rt_cleanup(void)
-{
-	/* rt_pend_tq_cleanup(); */
-}
-#endif
diff --git a/drivers/staging/comedi/rt_pend_tq.c b/drivers/staging/comedi/rt_pend_tq.c
deleted file mode 100644
index f9dfd9d..0000000
--- a/drivers/staging/comedi/rt_pend_tq.c
+++ /dev/null
@@ -1,113 +0,0 @@
-#define __NO_VERSION__
-/* rt_pend_tq.c */
-#include <linux/kernel.h>
-#include <linux/errno.h>
-#include <linux/sched.h>
-#include "comedidev.h"	/* for rt spinlocks */
-#include "rt_pend_tq.h"
-#ifdef CONFIG_COMEDI_RTAI
-#include <rtai.h>
-#endif
-#ifdef CONFIG_COMEDI_FUSION
-#include <nucleus/asm/hal.h>
-#endif
-#ifdef CONFIG_COMEDI_RTL
-#include <rtl_core.h>
-#endif
-
-#ifdef standalone
-#include <linux/module.h>
-#define rt_pend_tq_init init_module
-#define rt_pend_tq_cleanup cleanup_module
-#endif
-
-volatile static struct rt_pend_tq rt_pend_tq[RT_PEND_TQ_SIZE];
-volatile static struct rt_pend_tq *volatile rt_pend_head = rt_pend_tq,
-	*volatile rt_pend_tail = rt_pend_tq;
-int rt_pend_tq_irq = 0;
-DEFINE_SPINLOCK(rt_pend_tq_lock);
-
-/* WARNING: following code not checked against race conditions yet. */
-#define INC_CIRCULAR_PTR(ptr,begin,size) do {if(++(ptr)>=(begin)+(size)) (ptr)=(begin); } while(0)
-#define DEC_CIRCULAR_PTR(ptr,begin,size) do {if(--(ptr)<(begin)) (ptr)=(begin)+(size)-1; } while(0)
-
-int rt_pend_call(void (*func) (int arg1, void *arg2), int arg1, void *arg2)
-{
-	unsigned long flags;
-
-	if (func == NULL)
-		return -EINVAL;
-	if (rt_pend_tq_irq <= 0)
-		return -ENODEV;
-	comedi_spin_lock_irqsave(&rt_pend_tq_lock, flags);
-	INC_CIRCULAR_PTR(rt_pend_head, rt_pend_tq, RT_PEND_TQ_SIZE);
-	if (rt_pend_head == rt_pend_tail) {
-		/* overflow, we just refuse to take this request */
-		DEC_CIRCULAR_PTR(rt_pend_head, rt_pend_tq, RT_PEND_TQ_SIZE);
-		comedi_spin_unlock_irqrestore(&rt_pend_tq_lock, flags);
-		return -EAGAIN;
-	}
-	rt_pend_head->func = func;
-	rt_pend_head->arg1 = arg1;
-	rt_pend_head->arg2 = arg2;
-	comedi_spin_unlock_irqrestore(&rt_pend_tq_lock, flags);
-#ifdef CONFIG_COMEDI_RTAI
-	rt_pend_linux_srq(rt_pend_tq_irq);
-#endif
-#ifdef CONFIG_COMEDI_FUSION
-	rthal_apc_schedule(rt_pend_tq_irq);
-#endif
-#ifdef CONFIG_COMEDI_RTL
-	rtl_global_pend_irq(rt_pend_tq_irq);
-
-#endif
-	return 0;
-}
-
-#ifdef CONFIG_COMEDI_RTAI
-void rt_pend_irq_handler(void)
-#elif defined(CONFIG_COMEDI_FUSION)
-void rt_pend_irq_handler(void *cookie)
-#elif defined(CONFIG_COMEDI_RTL)
-void rt_pend_irq_handler(int irq, void *dev PT_REGS_ARG)
-#endif
-{
-	while (rt_pend_head != rt_pend_tail) {
-		INC_CIRCULAR_PTR(rt_pend_tail, rt_pend_tq, RT_PEND_TQ_SIZE);
-		rt_pend_tail->func(rt_pend_tail->arg1, rt_pend_tail->arg2);
-	}
-}
-
-int rt_pend_tq_init(void)
-{
-	rt_pend_head = rt_pend_tail = rt_pend_tq;
-#ifdef CONFIG_COMEDI_RTAI
-	rt_pend_tq_irq = rt_request_srq(0, rt_pend_irq_handler, NULL);
-#endif
-#ifdef CONFIG_COMEDI_FUSION
-	rt_pend_tq_irq =
-		rthal_apc_alloc("comedi APC", rt_pend_irq_handler, NULL);
-#endif
-#ifdef CONFIG_COMEDI_RTL
-	rt_pend_tq_irq = rtl_get_soft_irq(rt_pend_irq_handler, "rt_pend_irq");
-#endif
-	if (rt_pend_tq_irq > 0)
-		printk("rt_pend_tq: RT bottom half scheduler initialized OK\n");
-	else
-		printk("rt_pend_tq: rtl_get_soft_irq failed\n");
-	return 0;
-}
-
-void rt_pend_tq_cleanup(void)
-{
-	printk("rt_pend_tq: unloading\n");
-#ifdef CONFIG_COMEDI_RTAI
-	rt_free_srq(rt_pend_tq_irq);
-#endif
-#ifdef CONFIG_COMEDI_FUSION
-	rthal_apc_free(rt_pend_tq_irq);
-#endif
-#ifdef CONFIG_COMEDI_RTL
-	free_irq(rt_pend_tq_irq, NULL);
-#endif
-}
diff --git a/drivers/staging/comedi/rt_pend_tq.h b/drivers/staging/comedi/rt_pend_tq.h
deleted file mode 100644
index 01ed71b..0000000
--- a/drivers/staging/comedi/rt_pend_tq.h
+++ /dev/null
@@ -1,10 +0,0 @@
-#define RT_PEND_TQ_SIZE 16
-struct rt_pend_tq {
-	void (*func) (int arg1, void *arg2);
-	int arg1;
-	void *arg2;
-};
-extern int rt_pend_call(void (*func) (int arg1, void *arg2), int arg1,
-	void *arg2);
-extern int rt_pend_tq_init(void);
-extern void rt_pend_tq_cleanup(void);
diff --git a/drivers/staging/cpc-usb/Kconfig b/drivers/staging/cpc-usb/Kconfig
new file mode 100644
index 0000000..2be0bc9
--- /dev/null
+++ b/drivers/staging/cpc-usb/Kconfig
@@ -0,0 +1,4 @@
+config USB_CPC
+	tristate "CPC CAN USB driver"
+	depends on USB && PROC_FS
+	default n
diff --git a/drivers/staging/cpc-usb/Makefile b/drivers/staging/cpc-usb/Makefile
new file mode 100644
index 0000000..3f83170
--- /dev/null
+++ b/drivers/staging/cpc-usb/Makefile
@@ -0,0 +1,3 @@
+obj-$(CONFIG_USB_CPC)	+= cpc-usb.o
+
+cpc-usb-y := cpc-usb_drv.o sja2m16c_2.o
diff --git a/drivers/staging/serqt_usb/TODO b/drivers/staging/cpc-usb/TODO
similarity index 63%
rename from drivers/staging/serqt_usb/TODO
rename to drivers/staging/cpc-usb/TODO
index 34ecca8..000e8bb 100644
--- a/drivers/staging/serqt_usb/TODO
+++ b/drivers/staging/cpc-usb/TODO
@@ -2,7 +2,8 @@
 kernel:
 	- checkpatch cleanups
 	- sparse clean
-	- port to the usb-serial layer instead of doing it all on its
-	  own.
+	- remove proc code
+	- tie into CAN socket interfaces if possible
+	- figure out sane userspace api
 
 Send patches to Greg Kroah-Hartman <greg@kroah.com>
diff --git a/drivers/staging/cpc-usb/cpc-usb_drv.c b/drivers/staging/cpc-usb/cpc-usb_drv.c
new file mode 100644
index 0000000..9bf3f98
--- /dev/null
+++ b/drivers/staging/cpc-usb/cpc-usb_drv.c
@@ -0,0 +1,1185 @@
+/*
+ * CPC-USB CAN Interface Kernel Driver
+ *
+ * Copyright (C) 2004-2009 EMS Dr. Thomas Wuensche
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published
+ * by the Free Software Foundation; version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+#include <linux/kernel.h>
+#include <linux/errno.h>
+#include <linux/init.h>
+#include <linux/slab.h>
+#include <linux/vmalloc.h>
+#include <linux/module.h>
+#include <linux/poll.h>
+#include <linux/smp_lock.h>
+#include <linux/completion.h>
+#include <asm/uaccess.h>
+#include <linux/usb.h>
+
+#include <linux/version.h>
+
+#include <linux/proc_fs.h>
+
+#include "cpc.h"
+
+#include "cpc_int.h"
+#include "cpcusb.h"
+
+#include "sja2m16c.h"
+
+/* Version Information */
+#define DRIVER_AUTHOR  "Sebastian Haas <haas@ems-wuensche.com>"
+#define DRIVER_DESC    "CPC-USB Driver for Linux Kernel 2.6"
+#define DRIVER_VERSION CPC_DRIVER_VERSION
+
+MODULE_AUTHOR(DRIVER_AUTHOR);
+MODULE_DESCRIPTION(DRIVER_DESC);
+MODULE_VERSION(DRIVER_VERSION);
+MODULE_LICENSE("GPL v2");
+
+/* Define these values to match your devices */
+#define USB_CPCUSB_VENDOR_ID	0x12D6
+
+#define USB_CPCUSB_M16C_PRODUCT_ID    0x0888
+#define USB_CPCUSB_LPC2119_PRODUCT_ID 0x0444
+
+#define CPC_USB_PROC_DIR     CPC_PROC_DIR "cpc-usb"
+
+static struct proc_dir_entry *procDir;
+static struct proc_dir_entry *procEntry;
+
+/* Module parameters */
+static int debug;
+module_param(debug, int, S_IRUGO);
+
+/* table of devices that work with this driver */
+static struct usb_device_id cpcusb_table[] = {
+	{USB_DEVICE(USB_CPCUSB_VENDOR_ID, USB_CPCUSB_M16C_PRODUCT_ID)},
+	{USB_DEVICE(USB_CPCUSB_VENDOR_ID, USB_CPCUSB_LPC2119_PRODUCT_ID)},
+	{}			/* Terminating entry */
+};
+
+MODULE_DEVICE_TABLE(usb, cpcusb_table);
+
+/* use to prevent kernel panic if driver is unloaded
+ * while a programm has still open the device
+ */
+DECLARE_WAIT_QUEUE_HEAD(rmmodWq);
+atomic_t useCount;
+
+static CPC_USB_T *CPCUSB_Table[CPC_USB_CARD_CNT] = { 0 };
+static unsigned int CPCUsbCnt;
+
+/* prevent races between open() and disconnect() */
+static DECLARE_MUTEX(disconnect_sem);
+
+/* local function prototypes */
+static ssize_t cpcusb_read(struct file *file, char *buffer, size_t count,
+			   loff_t *ppos);
+static ssize_t cpcusb_write(struct file *file, const char *buffer,
+			    size_t count, loff_t *ppos);
+static unsigned int cpcusb_poll(struct file *file, poll_table * wait);
+static int cpcusb_open(struct inode *inode, struct file *file);
+static int cpcusb_release(struct inode *inode, struct file *file);
+
+static int cpcusb_probe(struct usb_interface *interface,
+			const struct usb_device_id *id);
+static void cpcusb_disconnect(struct usb_interface *interface);
+
+static void cpcusb_read_bulk_callback(struct urb *urb);
+static void cpcusb_write_bulk_callback(struct urb *urb);
+static void cpcusb_read_interrupt_callback(struct urb *urb);
+
+static int cpcusb_setup_intrep(CPC_USB_T *card);
+
+static struct file_operations cpcusb_fops = {
+	/*
+	 * The owner field is part of the module-locking
+	 * mechanism. The idea is that the kernel knows
+	 * which module to increment the use-counter of
+	 * BEFORE it calls the device's open() function.
+	 * This also means that the kernel can decrement
+	 * the use-counter again before calling release()
+	 * or should the open() function fail.
+	 */
+	.owner = THIS_MODULE,
+
+	.read = cpcusb_read,
+	.write = cpcusb_write,
+	.poll = cpcusb_poll,
+	.open = cpcusb_open,
+	.release = cpcusb_release,
+};
+
+/*
+ * usb class driver info in order to get a minor number from the usb core,
+ * and to have the device registered with devfs and the driver core
+ */
+static struct usb_class_driver cpcusb_class = {
+	.name = "usb/cpc_usb%d",
+	.fops = &cpcusb_fops,
+	.minor_base = CPC_USB_BASE_MNR,
+};
+
+/* usb specific object needed to register this driver with the usb subsystem */
+static struct usb_driver cpcusb_driver = {
+	.name = "cpc-usb",
+	.probe = cpcusb_probe,
+	.disconnect = cpcusb_disconnect,
+	.id_table = cpcusb_table,
+};
+
+static int cpcusb_create_info_output(char *buf)
+{
+	int i = 0, j;
+
+	for (j = 0; j < CPC_USB_CARD_CNT; j++) {
+		if (CPCUSB_Table[j]) {
+			CPC_USB_T *card = CPCUSB_Table[j];
+			CPC_CHAN_T *chan = card->chan;
+
+			/* MINOR CHANNELNO BUSNO SLOTNO */
+			i += sprintf(&buf[i], "%d %s\n", chan->minor,
+				     card->serialNumber);
+		}
+	}
+
+	return i;
+}
+
+static int cpcusb_proc_read_info(char *page, char **start, off_t off,
+				 int count, int *eof, void *data)
+{
+	int len = cpcusb_create_info_output(page);
+
+	if (len <= off + count)
+		*eof = 1;
+	*start = page + off;
+	len -= off;
+	if (len > count)
+		len = count;
+	if (len < 0)
+		len = 0;
+
+	return len;
+}
+
+/*
+ * Remove CPC-USB and cleanup
+ */
+static inline void cpcusb_delete(CPC_USB_T *card)
+{
+	if (card) {
+		if (card->chan) {
+			if (card->chan->buf)
+				vfree(card->chan->buf);
+
+			if (card->chan->CPCWait_q)
+				kfree(card->chan->CPCWait_q);
+
+			kfree(card->chan);
+		}
+
+		CPCUSB_Table[card->idx] = NULL;
+		kfree(card);
+	}
+}
+
+/*
+ * setup the interrupt IN endpoint of a specific CPC-USB device
+ */
+static int cpcusb_setup_intrep(CPC_USB_T *card)
+{
+	int retval = 0;
+	struct usb_endpoint_descriptor *ep;
+
+	ep = &card->interface->altsetting[0].endpoint[card->num_intr_in].desc;
+
+	card->intr_in_buffer[0] = 0;
+	card->free_slots = 15;	/* initial size */
+
+	/* setup the urb */
+	usb_fill_int_urb(card->intr_in_urb, card->udev,
+			 usb_rcvintpipe(card->udev, card->num_intr_in),
+			 card->intr_in_buffer,
+			 sizeof(card->intr_in_buffer),
+			 cpcusb_read_interrupt_callback,
+			 card,
+			 ep->bInterval);
+
+	card->intr_in_urb->status = 0;	/* needed! */
+
+	/* submit the urb */
+	retval = usb_submit_urb(card->intr_in_urb, GFP_KERNEL);
+
+	if (retval)
+		err("%s - failed submitting intr urb, error %d", __func__,
+		    retval);
+
+	return retval;
+}
+
+static int cpcusb_open(struct inode *inode, struct file *file)
+{
+	CPC_USB_T *card = NULL;
+	struct usb_interface *interface;
+	int subminor;
+	int j, retval = 0;
+
+	subminor = iminor(inode);
+
+	/* prevent disconnects */
+	down(&disconnect_sem);
+
+	interface = usb_find_interface(&cpcusb_driver, subminor);
+	if (!interface) {
+		err("%s - error, can't find device for minor %d",
+				__func__, subminor);
+		retval = CPC_ERR_NO_INTERFACE_PRESENT;
+		goto exit_no_device;
+	}
+
+	card = usb_get_intfdata(interface);
+	if (!card) {
+		retval = CPC_ERR_NO_INTERFACE_PRESENT;
+		goto exit_no_device;
+	}
+
+	/* lock this device */
+	down(&card->sem);
+
+	/* increment our usage count for the driver */
+	if (card->open) {
+		dbg("device already opened");
+		retval = CPC_ERR_CHANNEL_ALREADY_OPEN;
+		goto exit_on_error;
+	}
+
+	/* save our object in the file's private structure */
+	file->private_data = card;
+	for (j = 0; j < CPC_USB_URB_CNT; j++) {
+		usb_fill_bulk_urb(card->urbs[j].urb, card->udev,
+				  usb_rcvbulkpipe(card->udev, card->num_bulk_in),
+				  card->urbs[j].buffer, card->urbs[j].size,
+				  cpcusb_read_bulk_callback, card);
+
+		retval = usb_submit_urb(card->urbs[j].urb, GFP_KERNEL);
+
+		if (retval) {
+			err("%s - failed submitting read urb, error %d",
+			    __func__, retval);
+			retval = CPC_ERR_TRANSMISSION_FAILED;
+			goto exit_on_error;
+		}
+	}
+
+	info("%s - %d URB's submitted", __func__, j);
+
+	ResetBuffer(card->chan);
+
+	cpcusb_setup_intrep(card);
+	card->open = 1;
+
+	atomic_inc(&useCount);
+
+exit_on_error:
+	/* unlock this device */
+	up(&card->sem);
+
+exit_no_device:
+	up(&disconnect_sem);
+
+	return retval;
+}
+
+static unsigned int cpcusb_poll(struct file *file, poll_table * wait)
+{
+	CPC_USB_T *card = (CPC_USB_T *) file->private_data;
+	unsigned int retval = 0;
+
+	if (!card) {
+		err("%s - device object lost", __func__);
+		return -EIO;
+	}
+
+	poll_wait(file, card->chan->CPCWait_q, wait);
+
+	if (IsBufferNotEmpty(card->chan) || !(card->present))
+		retval |= (POLLIN | POLLRDNORM);
+
+	if (card->free_slots)
+		retval |= (POLLOUT | POLLWRNORM);
+
+	return retval;
+}
+
+static int cpcusb_release(struct inode *inode, struct file *file)
+{
+	CPC_USB_T *card = (CPC_USB_T *) file->private_data;
+	int j, retval = 0;
+
+	if (card == NULL) {
+		dbg("%s - object is NULL", __func__);
+		return CPC_ERR_NO_INTERFACE_PRESENT;
+	}
+
+	/* lock our device */
+	down(&card->sem);
+
+	if (!card->open) {
+		dbg("%s - device not opened", __func__);
+		retval = CPC_ERR_NO_INTERFACE_PRESENT;
+		goto exit_not_opened;
+	}
+
+	/* if device wasn't unplugged kill all urbs */
+	if (card->present) {
+		/* kill read urbs */
+		for (j = 0; j < CPC_USB_URB_CNT; j++) {
+			usb_kill_urb(card->urbs[j].urb);
+		}
+
+		/* kill irq urb */
+		usb_kill_urb(card->intr_in_urb);
+
+		/* kill write urbs */
+		for (j = 0; j < CPC_USB_URB_CNT; j++) {
+			if (atomic_read(&card->wrUrbs[j].busy)) {
+				usb_kill_urb(card->wrUrbs[j].urb);
+				wait_for_completion(&card->wrUrbs[j].finished);
+			}
+		}
+	}
+
+	atomic_dec(&useCount);
+
+	/* last process detached */
+	if (atomic_read(&useCount) == 0) {
+		wake_up(&rmmodWq);
+	}
+
+	if (!card->present && card->open) {
+		/* the device was unplugged before the file was released */
+		up(&card->sem);
+		cpcusb_delete(card);
+		return 0;
+	}
+
+	card->open = 0;
+
+exit_not_opened:
+	up(&card->sem);
+
+	return 0;
+}
+
+static ssize_t cpcusb_read(struct file *file, char *buffer, size_t count,
+			   loff_t *ppos)
+{
+	CPC_USB_T *card = (CPC_USB_T *) file->private_data;
+	CPC_CHAN_T *chan;
+	int retval = 0;
+
+	if (count < sizeof(CPC_MSG_T))
+		return CPC_ERR_UNKNOWN;
+
+	/* check if can read from the given address */
+	if (!access_ok(VERIFY_WRITE, buffer, count))
+		return CPC_ERR_UNKNOWN;
+
+	/* lock this object */
+	down(&card->sem);
+
+	/* verify that the device wasn't unplugged */
+	if (!card->present) {
+		up(&card->sem);
+		return CPC_ERR_NO_INTERFACE_PRESENT;
+	}
+
+	if (IsBufferEmpty(card->chan)) {
+		retval = 0;
+	} else {
+		chan = card->chan;
+
+#if 0
+		/* convert LPC2119 params back to SJA1000 params */
+		if (card->deviceRevision >= 0x0200
+		    && chan->buf[chan->oidx].type == CPC_MSG_T_CAN_PRMS) {
+			LPC2119_TO_SJA1000_Params(&chan->buf[chan->oidx]);
+		}
+#endif
+
+		if (copy_to_user(buffer, &chan->buf[chan->oidx], count) != 0) {
+			retval = CPC_ERR_IO_TRANSFER;
+		} else {
+			chan->oidx = (chan->oidx + 1) % CPC_MSG_BUF_CNT;
+			chan->WnR = 1;
+			retval = sizeof(CPC_MSG_T);
+		}
+	}
+/*	spin_unlock_irqrestore(&card->slock, flags); */
+
+	/* unlock the device */
+	up(&card->sem);
+
+	return retval;
+}
+
+#define SHIFT  1
+static inline void cpcusb_align_buffer_alignment(unsigned char *buf)
+{
+	/* CPC-USB uploads packed bytes. */
+	CPC_MSG_T *cpc = (CPC_MSG_T *) buf;
+	unsigned int i;
+
+	for (i = 0; i < cpc->length + (2 * sizeof(unsigned long)); i++) {
+		((unsigned char *) &cpc->msgid)[1 + i] =
+		    ((unsigned char *) &cpc->msgid)[1 + SHIFT + i];
+	}
+}
+
+static int cpc_get_buffer_count(CPC_CHAN_T *chan)
+{
+	/* check the buffer parameters */
+	if (chan->iidx == chan->oidx)
+		return !chan->WnR ? CPC_MSG_BUF_CNT : 0;
+	else if (chan->iidx >= chan->oidx)
+		return (chan->iidx - chan->oidx) % CPC_MSG_BUF_CNT;
+
+	return (chan->iidx + CPC_MSG_BUF_CNT - chan->oidx) % CPC_MSG_BUF_CNT;
+}
+
+static ssize_t cpcusb_write(struct file *file, const char *buffer,
+			    size_t count, loff_t *ppos)
+{
+	CPC_USB_T *card = (CPC_USB_T *) file->private_data;
+	CPC_USB_WRITE_URB_T *wrUrb = NULL;
+
+	ssize_t bytes_written = 0;
+	int retval = 0;
+	int j;
+
+	unsigned char *obuf = NULL;
+	unsigned char type = 0;
+	CPC_MSG_T *info = NULL;
+
+	dbg("%s - entered minor %d, count = %zu, present = %d",
+	    __func__, card->minor, count, card->present);
+
+	if (count > sizeof(CPC_MSG_T))
+		return CPC_ERR_UNKNOWN;
+
+	/* check if can read from the given address */
+	if (!access_ok(VERIFY_READ, buffer, count))
+		return CPC_ERR_UNKNOWN;
+
+	/* lock this object */
+	down(&card->sem);
+
+	/* verify that the device wasn't unplugged */
+	if (!card->present) {
+		retval = CPC_ERR_NO_INTERFACE_PRESENT;
+		goto exit;
+	}
+
+	/* verify that we actually have some data to write */
+	if (count == 0) {
+		dbg("%s - write request of 0 bytes", __func__);
+		goto exit;
+	}
+
+	if (card->free_slots <= 5) {
+		info = (CPC_MSG_T *) buffer;
+
+		if (info->type != CPC_CMD_T_CLEAR_CMD_QUEUE
+		    || card->free_slots <= 0) {
+			dbg("%s - send buffer full please try again %d",
+			    __func__, card->free_slots);
+			retval = CPC_ERR_CAN_NO_TRANSMIT_BUF;
+			goto exit;
+		}
+	}
+
+	/* Find a free write urb */
+	for (j = 0; j < CPC_USB_URB_CNT; j++) {
+		if (!atomic_read(&card->wrUrbs[j].busy)) {
+			wrUrb = &card->wrUrbs[j];	/* remember found URB */
+			atomic_set(&wrUrb->busy, 1);	/* lock this URB      */
+			init_completion(&wrUrb->finished);	/* init completion    */
+			dbg("WR URB no. %d started", j);
+			break;
+		}
+	}
+
+	/* don't found write urb say error */
+	if (!wrUrb) {
+		dbg("%s - no free send urb available", __func__);
+		retval = CPC_ERR_CAN_NO_TRANSMIT_BUF;
+		goto exit;
+	}
+	dbg("URB write req");
+
+	obuf = (unsigned char *) wrUrb->urb->transfer_buffer;
+
+	/* copy the data from userspace into our transfer buffer;
+	 * this is the only copy required.
+	 */
+	if (copy_from_user(&obuf[4], buffer, count) != 0) {
+		atomic_set(&wrUrb->busy, 0);	/* release urb */
+		retval = CPC_ERR_IO_TRANSFER;
+		goto exit;
+	}
+
+	/* check if it is a DRIVER information message, so we can
+	 * response to that message and not the USB
+	 */
+	info = (CPC_MSG_T *) &obuf[4];
+
+	bytes_written = 11 + info->length;
+	if (bytes_written >= wrUrb->size) {
+		retval = CPC_ERR_IO_TRANSFER;
+		goto exit;
+	}
+
+	switch (info->type) {
+	case CPC_CMD_T_CLEAR_MSG_QUEUE:
+		ResetBuffer(card->chan);
+		break;
+
+	case CPC_CMD_T_INQ_MSG_QUEUE_CNT:
+		retval = cpc_get_buffer_count(card->chan);
+		atomic_set(&wrUrb->busy, 0);
+
+		goto exit;
+
+	case CPC_CMD_T_INQ_INFO:
+		if (info->msg.info.source == CPC_INFOMSG_T_DRIVER) {
+			/* release urb cause we'll use it for driver
+			 * information
+			 */
+			atomic_set(&wrUrb->busy, 0);
+			if (IsBufferFull(card->chan)) {
+				retval = CPC_ERR_IO_TRANSFER;
+				goto exit;
+			}
+
+			/* it is a driver information request message and we have
+			 * free rx slots to store the response
+			 */
+			type = info->msg.info.type;
+			info = &card->chan->buf[card->chan->iidx];
+
+			info->type = CPC_MSG_T_INFO;
+			info->msg.info.source = CPC_INFOMSG_T_DRIVER;
+			info->msg.info.type = type;
+
+			switch (type) {
+			case CPC_INFOMSG_T_VERSION:
+				info->length = strlen(CPC_DRIVER_VERSION) + 2;
+				sprintf(info->msg.info.msg, "%s\n",
+					CPC_DRIVER_VERSION);
+				break;
+
+			case CPC_INFOMSG_T_SERIAL:
+				info->length = strlen(CPC_DRIVER_SERIAL) + 2;
+				sprintf(info->msg.info.msg, "%s\n",
+					CPC_DRIVER_SERIAL);
+				break;
+
+			default:
+				info->length = 2;
+				info->msg.info.type =
+				    CPC_INFOMSG_T_UNKNOWN_TYPE;
+			}
+
+			card->chan->WnR = 0;
+			card->chan->iidx =
+			    (card->chan->iidx + 1) % CPC_MSG_BUF_CNT;
+
+			retval = info->length;
+			goto exit;
+		}
+		break;
+	case CPC_CMD_T_CAN_PRMS:
+		/* Check the controller type. If it's the new CPC-USB, make sure if these are SJA1000 params */
+		if (info->msg.canparams.cc_type != SJA1000
+		    && info->msg.canparams.cc_type != M16C_BASIC
+		    && (card->productId == USB_CPCUSB_LPC2119_PRODUCT_ID
+			&& info->msg.canparams.cc_type != SJA1000)) {
+			/* don't forget to release the urb */
+			atomic_set(&wrUrb->busy, 0);
+			retval = CPC_ERR_WRONG_CONTROLLER_TYPE;
+			goto exit;
+		}
+		break;
+	}
+
+	/* just convert the params if it is an old CPC-USB with M16C controller */
+	if (card->productId == USB_CPCUSB_M16C_PRODUCT_ID) {
+		/* if it is a parameter message convert it from SJA1000 controller
+		 * settings to M16C Basic controller settings
+		 */
+		SJA1000_TO_M16C_BASIC_Params((CPC_MSG_T *) &obuf[4]);
+	}
+
+	/* don't forget the byte alignment */
+	cpcusb_align_buffer_alignment(&obuf[4]);
+
+	/* setup a the 4 byte header */
+	obuf[0] = obuf[1] = obuf[2] = obuf[3] = 0;
+
+	/* this urb was already set up, except for this write size */
+	wrUrb->urb->transfer_buffer_length = bytes_written + 4;
+
+	/* send the data out the bulk port */
+	/* a character device write uses GFP_KERNEL,
+	   unless a spinlock is held */
+	retval = usb_submit_urb(wrUrb->urb, GFP_KERNEL);
+	if (retval) {
+		atomic_set(&wrUrb->busy, 0);	/* release urb */
+		err("%s - failed submitting write urb, error %d",
+		    __func__, retval);
+	} else {
+		retval = bytes_written;
+	}
+
+exit:
+	/* unlock the device */
+	up(&card->sem);
+
+	dbg("%s - leaved", __func__);
+
+	return retval;
+}
+
+/*
+ * callback for interrupt IN urb
+ */
+static void cpcusb_read_interrupt_callback(struct urb *urb)
+{
+	CPC_USB_T *card = (CPC_USB_T *) urb->context;
+	int retval;
+	unsigned long flags;
+
+	spin_lock_irqsave(&card->slock, flags);
+
+	if (!card->present) {
+		spin_unlock_irqrestore(&card->slock, flags);
+		info("%s - no such device", __func__);
+		return;
+	}
+
+	switch (urb->status) {
+	case 0: /* success */
+		card->free_slots = card->intr_in_buffer[1];
+		break;
+	case -ECONNRESET:
+	case -ENOENT:
+	case -ESHUTDOWN:
+		/* urb was killed */
+		spin_unlock_irqrestore(&card->slock, flags);
+		dbg("%s - intr urb killed", __func__);
+		return;
+	default:
+		info("%s - nonzero urb status %d", __func__, urb->status);
+		break;
+	}
+
+	retval = usb_submit_urb(urb, GFP_ATOMIC);
+	if (retval) {
+		err("%s - failed resubmitting intr urb, error %d",
+		    __func__, retval);
+	}
+
+	spin_unlock_irqrestore(&card->slock, flags);
+	wake_up_interruptible(card->chan->CPCWait_q);
+
+	return;
+}
+
+#define UN_SHIFT  1
+#define CPCMSG_HEADER_LEN_FIRMWARE   11
+static inline int cpcusb_unalign_and_copy_buffy(unsigned char *out,
+						unsigned char *in)
+{
+	unsigned int i, j;
+
+	for (i = 0; i < 3; i++)
+		out[i] = in[i];
+
+	for (j = 0; j < (in[1] + (CPCMSG_HEADER_LEN_FIRMWARE - 3)); j++)
+		out[j + i + UN_SHIFT] = in[j + i];
+
+	return i + j;
+}
+
+/*
+ * callback for bulk IN urb
+ */
+static void cpcusb_read_bulk_callback(struct urb *urb)
+{
+	CPC_USB_T *card = (CPC_USB_T *) urb->context;
+	CPC_CHAN_T *chan;
+	unsigned char *ibuf = urb->transfer_buffer;
+	int retval, msgCnt, start, again = 0;
+	unsigned long flags;
+
+	if (!card) {
+		err("%s - device object lost", __func__);
+		return;
+	}
+
+	spin_lock_irqsave(&card->slock, flags);
+
+	if (!card->present) {
+		spin_unlock_irqrestore(&card->slock, flags);
+		info("%s - no such device", __func__);
+		return;
+	}
+
+	switch (urb->status) {
+	case 0:		/* success */
+		break;
+	case -ECONNRESET:
+	case -ENOENT:
+	case -ESHUTDOWN:
+		/* urb was killed */
+		spin_unlock_irqrestore(&card->slock, flags);
+		dbg("%s - read urb killed", __func__);
+		return;
+	default:
+		info("%s - nonzero urb status %d", __func__, urb->status);
+		break;
+	}
+
+	if (urb->actual_length) {
+		msgCnt = ibuf[0] & ~0x80;
+		again = ibuf[0] & 0x80;
+
+		/* we have a 4 byte header */
+		start = 4;
+		chan = card->chan;
+		while (msgCnt) {
+			if (!(IsBufferFull(card->chan))) {
+				start +=
+				    cpcusb_unalign_and_copy_buffy((unsigned char *)
+							  &chan->buf[chan->iidx], &ibuf[start]);
+
+				if (start > urb->transfer_buffer_length) {
+					err("%d > %d", start, urb->transfer_buffer_length);
+					break;
+				}
+
+				chan->WnR = 0;
+				chan->iidx = (chan->iidx + 1) % CPC_MSG_BUF_CNT;
+				msgCnt--;
+			} else {
+				break;
+			}
+		}
+	}
+
+	usb_fill_bulk_urb(urb, card->udev,
+			  usb_rcvbulkpipe(card->udev, card->num_bulk_in),
+			  urb->transfer_buffer,
+			  urb->transfer_buffer_length,
+			  cpcusb_read_bulk_callback, card);
+
+	retval = usb_submit_urb(urb, GFP_ATOMIC);
+
+	if (retval) {
+		err("%s - failed resubmitting read urb, error %d", __func__, retval);
+	}
+
+	spin_unlock_irqrestore(&card->slock, flags);
+
+	wake_up_interruptible(card->chan->CPCWait_q);
+}
+
+/*
+ * callback for bulk IN urb
+ */
+static void cpcusb_write_bulk_callback(struct urb *urb)
+{
+	CPC_USB_T *card = (CPC_USB_T *) urb->context;
+	unsigned long flags;
+	int j;
+
+	spin_lock_irqsave(&card->slock, flags);
+
+	/* find this urb */
+	for (j = 0; j < CPC_USB_URB_CNT; j++) {
+		if (card->wrUrbs[j].urb == urb) {
+			dbg("URB found no. %d", j);
+			/* notify anyone waiting that the write has finished */
+			complete(&card->wrUrbs[j].finished);
+			atomic_set(&card->wrUrbs[j].busy, 0);
+			break;
+		}
+	}
+
+	switch (urb->status) {
+	case 0:		/* success */
+		break;
+	case -ECONNRESET:
+	case -ENOENT:
+	case -ESHUTDOWN:
+		/* urb was killed */
+		spin_unlock_irqrestore(&card->slock, flags);
+		dbg("%s - write urb no. %d killed", __func__, j);
+		return;
+	default:
+		info("%s - nonzero urb status %d", __func__, urb->status);
+		break;
+	}
+
+	spin_unlock_irqrestore(&card->slock, flags);
+
+	wake_up_interruptible(card->chan->CPCWait_q);
+}
+
+static inline int cpcusb_get_free_slot(void)
+{
+	int i;
+
+	for (i = 0; i < CPC_USB_CARD_CNT; i++) {
+		if (!CPCUSB_Table[i])
+			return i;
+	}
+
+	return -1;
+}
+
+/*
+ * probe function for new CPC-USB devices
+ */
+static int cpcusb_probe(struct usb_interface *interface,
+			const struct usb_device_id *id)
+{
+	CPC_USB_T *card = NULL;
+	CPC_CHAN_T *chan = NULL;
+
+	struct usb_device *udev = interface_to_usbdev(interface);
+	struct usb_host_interface *iface_desc;
+	struct usb_endpoint_descriptor *endpoint;
+
+	int i, j, retval = -ENOMEM, slot;
+
+	slot = cpcusb_get_free_slot();
+	if (slot < 0) {
+		info("No more devices supported");
+		return -ENOMEM;
+	}
+
+	/* allocate memory for our device state and initialize it */
+	card = kzalloc(sizeof(CPC_USB_T), GFP_KERNEL);
+	if (!card) {
+		err("Out of memory");
+		return -ENOMEM;
+	}
+	CPCUSB_Table[slot] = card;
+
+	/* allocate and initialize the channel struct */
+	card->chan = kmalloc(sizeof(CPC_CHAN_T), GFP_KERNEL);
+	if (!card->chan) {
+		kfree(card);
+		err("Out of memory");
+		return -ENOMEM;
+	}
+
+	chan = card->chan;
+	memset(chan, 0, sizeof(CPC_CHAN_T));
+	ResetBuffer(chan);
+
+	init_MUTEX(&card->sem);
+	spin_lock_init(&card->slock);
+
+	card->udev = udev;
+	card->interface = interface;
+	if (udev->descriptor.iSerialNumber) {
+		usb_string(udev, udev->descriptor.iSerialNumber, card->serialNumber,
+				   128);
+		info("Serial %s", card->serialNumber);
+	}
+
+	card->productId = udev->descriptor.idProduct;
+	info("Product %s",
+	     card->productId == USB_CPCUSB_LPC2119_PRODUCT_ID ?
+			 "CPC-USB/ARM7" : "CPC-USB/M16C");
+
+	/* set up the endpoint information */
+	/* check out the endpoints */
+	/* use only the first bulk-in and bulk-out endpoints */
+	iface_desc = &interface->altsetting[0];
+	for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
+		endpoint = &iface_desc->endpoint[i].desc;
+
+		if (!card->num_intr_in &&
+		    (endpoint->bEndpointAddress & USB_DIR_IN) &&
+		    ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
+		     == USB_ENDPOINT_XFER_INT)) {
+			card->intr_in_urb = usb_alloc_urb(0, GFP_KERNEL);
+			card->num_intr_in = 1;
+
+			if (!card->intr_in_urb) {
+				err("No free urbs available");
+				goto error;
+			}
+
+			dbg("intr_in urb %d", card->num_intr_in);
+		}
+
+		if (!card->num_bulk_in &&
+		    (endpoint->bEndpointAddress & USB_DIR_IN) &&
+		    ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
+		     == USB_ENDPOINT_XFER_BULK)) {
+			card->num_bulk_in = 2;
+			for (j = 0; j < CPC_USB_URB_CNT; j++) {
+				card->urbs[j].size = endpoint->wMaxPacketSize;
+				card->urbs[j].urb = usb_alloc_urb(0, GFP_KERNEL);
+				if (!card->urbs[j].urb) {
+					err("No free urbs available");
+					goto error;
+				}
+				card->urbs[j].buffer =
+				    usb_buffer_alloc(udev,
+						     card->urbs[j].size,
+						     GFP_KERNEL,
+						     &card->urbs[j].urb->transfer_dma);
+				if (!card->urbs[j].buffer) {
+					err("Couldn't allocate bulk_in_buffer");
+					goto error;
+				}
+			}
+			info("%s - %d reading URB's allocated",
+			     __func__, CPC_USB_URB_CNT);
+		}
+
+		if (!card->num_bulk_out &&
+		    !(endpoint->bEndpointAddress & USB_DIR_IN) &&
+		    ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
+		     == USB_ENDPOINT_XFER_BULK)) {
+
+			card->num_bulk_out = 2;
+
+			for (j = 0; j < CPC_USB_URB_CNT; j++) {
+				card->wrUrbs[j].size =
+				    endpoint->wMaxPacketSize;
+				card->wrUrbs[j].urb =
+				    usb_alloc_urb(0, GFP_KERNEL);
+				if (!card->wrUrbs[j].urb) {
+					err("No free urbs available");
+					goto error;
+				}
+				card->wrUrbs[j].buffer = usb_buffer_alloc(udev,
+							       card->wrUrbs[j].size, GFP_KERNEL,
+							       &card->wrUrbs[j].urb->transfer_dma);
+
+				if (!card->wrUrbs[j].buffer) {
+					err("Couldn't allocate bulk_out_buffer");
+					goto error;
+				}
+
+				usb_fill_bulk_urb(card->wrUrbs[j].urb, udev,
+						usb_sndbulkpipe(udev, endpoint->bEndpointAddress),
+						card->wrUrbs[j].buffer,
+						card->wrUrbs[j].size,
+						cpcusb_write_bulk_callback,
+						card);
+			}
+
+			info("%s - %d writing URB's allocated", __func__, CPC_USB_URB_CNT);
+		}
+	}
+
+	if (!(card->num_bulk_in && card->num_bulk_out)) {
+		err("Couldn't find both bulk-in and bulk-out endpoints");
+		goto error;
+	}
+
+	/* allow device read, write and ioctl */
+	card->present = 1;
+
+	/* we can register the device now, as it is ready */
+	usb_set_intfdata(interface, card);
+	retval = usb_register_dev(interface, &cpcusb_class);
+
+	if (retval) {
+		/* something prevented us from registering this driver */
+		err("Not able to get a minor for this device.");
+		usb_set_intfdata(interface, NULL);
+		goto error;
+	}
+
+	card->chan->minor = card->minor = interface->minor;
+
+	chan->buf = vmalloc(sizeof(CPC_MSG_T) * CPC_MSG_BUF_CNT);
+	if (chan->buf == NULL) {
+		err("Out of memory");
+		retval = -ENOMEM;
+		goto error;
+	}
+	info("Allocated memory for %d messages (%lu kbytes)",
+	     CPC_MSG_BUF_CNT, (long unsigned int)(sizeof(CPC_MSG_T) * CPC_MSG_BUF_CNT) / 1000);
+	memset(chan->buf, 0, sizeof(CPC_MSG_T) * CPC_MSG_BUF_CNT);
+
+	ResetBuffer(chan);
+
+	card->chan->CPCWait_q = kmalloc(sizeof(wait_queue_head_t), GFP_KERNEL);
+	if (!card->chan->CPCWait_q) {
+		err("Out of memory");
+		retval = -ENOMEM;
+		goto error;
+	}
+	init_waitqueue_head(card->chan->CPCWait_q);
+
+	CPCUSB_Table[slot] = card;
+	card->idx = slot;
+	CPCUsbCnt++;
+
+	/* let the user know what node this device is now attached to */
+	info("Device now attached to USB-%d", card->minor);
+	return 0;
+
+error:
+	for (j = 0; j < CPC_USB_URB_CNT; j++) {
+		if (card->urbs[j].buffer) {
+			usb_buffer_free(card->udev, card->urbs[j].size,
+					card->urbs[j].buffer,
+					card->urbs[j].urb->transfer_dma);
+			card->urbs[j].buffer = NULL;
+		}
+		if (card->urbs[j].urb) {
+			usb_free_urb(card->urbs[j].urb);
+			card->urbs[j].urb = NULL;
+		}
+	}
+
+	cpcusb_delete(card);
+	return retval;
+}
+
+/*
+ * called by the usb core when the device is removed from the system
+ */
+static void cpcusb_disconnect(struct usb_interface *interface)
+{
+	CPC_USB_T *card = NULL;
+	int minor, j;
+
+	/* prevent races with open() */
+	down(&disconnect_sem);
+
+	card = usb_get_intfdata(interface);
+	usb_set_intfdata(interface, NULL);
+
+	down(&card->sem);
+
+	/* prevent device read, write and ioctl */
+	card->present = 0;
+
+	minor = card->minor;
+
+	/* free all urbs and their buffers */
+	for (j = 0; j < CPC_USB_URB_CNT; j++) {
+		/* terminate an ongoing write */
+		if (atomic_read(&card->wrUrbs[j].busy)) {
+			usb_kill_urb(card->wrUrbs[j].urb);
+			wait_for_completion(&card->wrUrbs[j].finished);
+		}
+		usb_buffer_free(card->udev, card->wrUrbs[j].size,
+				card->wrUrbs[j].buffer,
+				card->wrUrbs[j].urb->transfer_dma);
+		usb_free_urb(card->wrUrbs[j].urb);
+	}
+	info("%d write URBs freed", CPC_USB_URB_CNT);
+
+	/* free all urbs and their buffers */
+	for (j = 0; j < CPC_USB_URB_CNT; j++) {
+		usb_buffer_free(card->udev, card->urbs[j].size,
+				card->urbs[j].buffer,
+				card->urbs[j].urb->transfer_dma);
+		usb_free_urb(card->urbs[j].urb);
+	}
+	info("%d read URBs freed", CPC_USB_URB_CNT);
+	usb_free_urb(card->intr_in_urb);
+
+	/* give back our minor */
+	usb_deregister_dev(interface, &cpcusb_class);
+
+	up(&card->sem);
+
+	/* if the device is opened, cpcusb_release will clean this up */
+	if (!card->open)
+		cpcusb_delete(card);
+	else
+		wake_up_interruptible(card->chan->CPCWait_q);
+
+	up(&disconnect_sem);
+
+	CPCUsbCnt--;
+	info("USB-%d now disconnected", minor);
+}
+
+static int __init CPCUsb_Init(void)
+{
+	int result, i;
+
+	info(DRIVER_DESC " v" DRIVER_VERSION);
+	info("Build on " __DATE__ " at " __TIME__);
+
+	for (i = 0; i < CPC_USB_CARD_CNT; i++)
+		CPCUSB_Table[i] = 0;
+
+	/* register this driver with the USB subsystem */
+	result = usb_register(&cpcusb_driver);
+	if (result) {
+		err("usb_register failed. Error number %d", result);
+		return result;
+	}
+
+	procDir = proc_mkdir(CPC_USB_PROC_DIR, NULL);
+	if (!procDir) {
+		err("Could not create proc entry");
+	} else {
+		procEntry = create_proc_read_entry("info", 0444, procDir,
+						   cpcusb_proc_read_info,
+						   NULL);
+		if (!procEntry) {
+			err("Could not create proc entry %s", CPC_USB_PROC_DIR "/info");
+			remove_proc_entry(CPC_USB_PROC_DIR, NULL);
+			procDir = NULL;
+		}
+	}
+
+	return 0;
+}
+
+static void __exit CPCUsb_Exit(void)
+{
+	wait_event(rmmodWq, !atomic_read(&useCount));
+
+	/* deregister this driver with the USB subsystem */
+	usb_deregister(&cpcusb_driver);
+
+	if (procDir) {
+		if (procEntry)
+			remove_proc_entry("info", procDir);
+		remove_proc_entry(CPC_USB_PROC_DIR, NULL);
+	}
+}
+
+module_init(CPCUsb_Init);
+module_exit(CPCUsb_Exit);
diff --git a/drivers/staging/cpc-usb/cpc.h b/drivers/staging/cpc-usb/cpc.h
new file mode 100644
index 0000000..ed8cb34
--- /dev/null
+++ b/drivers/staging/cpc-usb/cpc.h
@@ -0,0 +1,440 @@
+/*
+ * CPC CAN Interface Definitions
+ *
+ * Copyright (C) 2000-2008 EMS Dr. Thomas Wuensche
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+#ifndef CPC_HEADER
+#define CPC_HEADER
+
+// the maximum length of the union members within a CPC_MSG
+// this value can be defined by the customer, but has to be
+// >= 64 bytes
+// however, if not defined before, we set a length of 64 byte
+#if !defined(CPC_MSG_LEN) || (CPC_MSG_LEN < 64)
+#undef CPC_MSG_LEN
+#define CPC_MSG_LEN 64
+#endif
+
+// check the operating system used
+#ifdef _WIN32 // running a Windows OS
+
+// define basic types on Windows platforms
+#ifdef _MSC_VER // Visual Studio
+	typedef unsigned __int8 u8;
+	typedef unsigned __int16 u16;
+	typedef unsigned __int32 u32;
+#else // Borland Compiler
+	typedef unsigned char u8;
+	typedef unsigned short u16;
+	typedef unsigned int u32;
+#endif
+	// on Windows OS we use a byte alignment of 1
+	#pragma pack(push, 1)
+
+	// set the calling conventions for the library function calls
+	#define CALL_CONV __stdcall
+#else
+	// Kernel headers already define this types
+	#ifndef __KERNEL__
+		// define basic types
+		typedef unsigned char u8;
+		typedef unsigned short u16;
+		typedef unsigned int u32;
+	#endif
+
+	// Linux does not use this calling convention
+	#define CALL_CONV
+#endif
+
+// Transmission of events from CPC interfaces to PC can be individually
+// controlled per event type. Default state is: don't transmit
+// Control values are constructed by bit-or of Subject and Action
+// and passed to CPC_Control()
+
+// Control-Values for CPC_Control() Command Subject Selection
+#define CONTR_CAN_Message 0x04
+#define CONTR_Busload	  0x08
+#define	CONTR_CAN_State	  0x0C
+#define	CONTR_SendAck	  0x10
+#define	CONTR_Filter	  0x14
+#define CONTR_CmdQueue    0x18	// reserved, do not use
+#define CONTR_BusError    0x1C
+
+// Control Command Actions
+#define CONTR_CONT_OFF    0
+#define CONTR_CONT_ON     1
+#define CONTR_SING_ON     2
+// CONTR_SING_ON doesn't change CONTR_CONT_ON state, so it should be
+// read as: transmit at least once
+
+// defines for confirmed request
+#define DO_NOT_CONFIRM 0
+#define DO_CONFIRM     1
+
+// event flags
+#define EVENT_READ 0x01
+#define EVENT_WRITE 0x02
+
+// Messages from CPC to PC contain a message object type field.
+// The following message types are sent by CPC and can be used in
+// handlers, others should be ignored.
+#define CPC_MSG_T_RESYNC        0 // Normally to be ignored
+#define CPC_MSG_T_CAN           1 // CAN data frame
+#define CPC_MSG_T_BUSLOAD       2 // Busload message
+#define CPC_MSG_T_STRING        3 // Normally to be ignored
+#define CPC_MSG_T_CONTI         4 // Normally to be ignored
+#define CPC_MSG_T_MEM           7 // Normally not to be handled
+#define	CPC_MSG_T_RTR           8 // CAN remote frame
+#define CPC_MSG_T_TXACK	        9 // Send acknowledge
+#define CPC_MSG_T_POWERUP      10 // Power-up message
+#define	CPC_MSG_T_CMD_NO       11 // Normally to be ignored
+#define	CPC_MSG_T_CAN_PRMS     12 // Actual CAN parameters
+#define	CPC_MSG_T_ABORTED      13 // Command aborted message
+#define	CPC_MSG_T_CANSTATE     14 // CAN state message
+#define CPC_MSG_T_RESET        15 // used to reset CAN-Controller
+#define	CPC_MSG_T_XCAN         16 // XCAN data frame
+#define CPC_MSG_T_XRTR         17 // XCAN remote frame
+#define CPC_MSG_T_INFO         18 // information strings
+#define CPC_MSG_T_CONTROL      19 // used for control of interface/driver behaviour
+#define CPC_MSG_T_CONFIRM      20 // response type for confirmed requests
+#define CPC_MSG_T_OVERRUN      21 // response type for overrun conditions
+#define CPC_MSG_T_KEEPALIVE    22 // response type for keep alive conditions
+#define CPC_MSG_T_CANERROR     23 // response type for bus error conditions
+#define CPC_MSG_T_DISCONNECTED 24 // response type for a disconnected interface
+#define CPC_MSG_T_ERR_COUNTER  25 // RX/TX error counter of CAN controller
+
+#define CPC_MSG_T_FIRMWARE    100 // response type for USB firmware download
+
+// Messages from the PC to the CPC interface contain a command field
+// Most of the command types are wrapped by the library functions and have therefore
+// normally not to be used.
+// However, programmers who wish to circumvent the library and talk directly
+// to the drivers (mainly Linux programmers) can use the following
+// command types:
+
+#define CPC_CMD_T_CAN                 1	// CAN data frame
+#define CPC_CMD_T_CONTROL             3	// used for control of interface/driver behaviour
+#define	CPC_CMD_T_CAN_PRMS            6	// set CAN parameters
+#define	CPC_CMD_T_CLEARBUF            8	// clears input queue; this is depricated, use CPC_CMD_T_CLEAR_MSG_QUEUE instead
+#define	CPC_CMD_T_INQ_CAN_PARMS      11	// inquire actual CAN parameters
+#define	CPC_CMD_T_FILTER_PRMS        12	// set filter parameter
+#define	CPC_CMD_T_RTR                13	// CAN remote frame
+#define	CPC_CMD_T_CANSTATE           14	// CAN state message
+#define	CPC_CMD_T_XCAN               15	// XCAN data frame
+#define CPC_CMD_T_XRTR               16	// XCAN remote frame
+#define CPC_CMD_T_RESET              17	// used to reset CAN-Controller
+#define CPC_CMD_T_INQ_INFO           18	// miscellanous information strings
+#define CPC_CMD_T_OPEN_CHAN          19	// open a channel
+#define CPC_CMD_T_CLOSE_CHAN         20	// close a channel
+#define CPC_CMD_T_CNTBUF             21	// this is depricated, use CPC_CMD_T_INQ_MSG_QUEUE_CNT instead
+#define CPC_CMD_T_CAN_EXIT          200 // exit the CAN (disable interrupts; reset bootrate; reset output_cntr; mode = 1)
+
+#define CPC_CMD_T_INQ_MSG_QUEUE_CNT  CPC_CMD_T_CNTBUF   // inquires the count of elements in the message queue
+#define CPC_CMD_T_INQ_ERR_COUNTER    25	                // request the CAN controllers error counter
+#define	CPC_CMD_T_CLEAR_MSG_QUEUE    CPC_CMD_T_CLEARBUF // clear CPC_MSG queue
+#define	CPC_CMD_T_CLEAR_CMD_QUEUE    28	                // clear CPC_CMD queue
+#define CPC_CMD_T_FIRMWARE          100                 // reserved, must not be used
+#define CPC_CMD_T_USB_RESET         101                 // reserved, must not be used
+#define CPC_CMD_T_WAIT_NOTIFY       102                 // reserved, must not be used
+#define CPC_CMD_T_WAIT_SETUP        103                 // reserved, must not be used
+#define	CPC_CMD_T_ABORT             255                 // Normally not to be used
+
+// definitions for CPC_MSG_T_INFO
+// information sources
+#define CPC_INFOMSG_T_UNKNOWN_SOURCE 0
+#define CPC_INFOMSG_T_INTERFACE      1
+#define CPC_INFOMSG_T_DRIVER         2
+#define CPC_INFOMSG_T_LIBRARY        3
+
+// information types
+#define CPC_INFOMSG_T_UNKNOWN_TYPE   0
+#define CPC_INFOMSG_T_VERSION        1
+#define CPC_INFOMSG_T_SERIAL         2
+
+// definitions for controller types
+#define PCA82C200   1 // Philips basic CAN controller, replaced by SJA1000
+#define SJA1000     2 // Philips basic CAN controller
+#define AN82527     3 // Intel full CAN controller
+#define M16C_BASIC  4 // M16C controller running in basic CAN (not full CAN) mode
+
+// channel open error codes
+#define CPC_ERR_NO_FREE_CHANNEL            -1	// no more free space within the channel array
+#define CPC_ERR_CHANNEL_ALREADY_OPEN       -2	// the channel is already open
+#define CPC_ERR_CHANNEL_NOT_ACTIVE         -3	// access to a channel not active failed
+#define CPC_ERR_NO_DRIVER_PRESENT          -4	// no driver at the location searched by the library
+#define CPC_ERR_NO_INIFILE_PRESENT         -5	// the library could not find the inifile
+#define CPC_ERR_WRONG_PARAMETERS           -6	// wrong parameters in the inifile
+#define CPC_ERR_NO_INTERFACE_PRESENT       -7	// 1. The specified interface is not connected
+						// 2. The interface (mostly CPC-USB) was disconnected upon operation
+#define CPC_ERR_NO_MATCHING_CHANNEL        -8	// the driver couldn't find a matching channel
+#define CPC_ERR_NO_BUFFER_AVAILABLE        -9	// the driver couldn't allocate buffer for messages
+#define CPC_ERR_NO_INTERRUPT               -10	// the requested interrupt couldn't be claimed
+#define CPC_ERR_NO_MATCHING_INTERFACE      -11	// no interface type related to this channel was found
+#define CPC_ERR_NO_RESOURCES               -12	// the requested resources could not be claimed
+#define CPC_ERR_SOCKET                     -13	// error concerning TCP sockets
+
+// init error codes
+#define CPC_ERR_WRONG_CONTROLLER_TYPE      -14	// wrong CAN controller type within initialization
+#define CPC_ERR_NO_RESET_MODE              -15	// the controller could not be set into reset mode
+#define CPC_ERR_NO_CAN_ACCESS              -16	// the CAN controller could not be accessed
+
+// transmit error codes
+#define CPC_ERR_CAN_WRONG_ID               -20	// the provided CAN id is too big
+#define CPC_ERR_CAN_WRONG_LENGTH           -21	// the provided CAN length is too long
+#define CPC_ERR_CAN_NO_TRANSMIT_BUF        -22	// the transmit buffer was occupied
+#define CPC_ERR_CAN_TRANSMIT_TIMEOUT       -23	// The message could not be sent within a
+						// specified time
+
+// other error codes
+#define CPC_ERR_SERVICE_NOT_SUPPORTED      -30	// the requested service is not supported by the interface
+#define CPC_ERR_IO_TRANSFER                -31	// a transmission error down to the driver occurred
+#define CPC_ERR_TRANSMISSION_FAILED        -32	// a transmission error down to the interface occurred
+#define CPC_ERR_TRANSMISSION_TIMEOUT       -33	// a timeout occurred within transmission to the interface
+#define CPC_ERR_OP_SYS_NOT_SUPPORTED       -35	// the operating system is not supported
+#define CPC_ERR_UNKNOWN                    -40	// an unknown error ocurred (mostly IOCTL errors)
+
+#define CPC_ERR_LOADING_DLL                -50	// the library 'cpcwin.dll' could not be loaded
+#define CPC_ERR_ASSIGNING_FUNCTION         -51	// the specified function could not be assigned
+#define CPC_ERR_DLL_INITIALIZATION         -52	// the DLL was not initialized correctly
+#define CPC_ERR_MISSING_LICFILE            -55	// the file containing the licenses does not exist
+#define CPC_ERR_MISSING_LICENSE            -56	// a required license was not found
+
+// CAN state bit values. Ignore any bits not listed
+#define CPC_CAN_STATE_BUSOFF     0x80
+#define CPC_CAN_STATE_ERROR      0x40
+
+// Mask to help ignore undefined bits
+#define CPC_CAN_STATE_MASK       0xc0
+
+// CAN-Message representation in a CPC_MSG
+// Message object type is CPC_MSG_T_CAN or CPC_MSG_T_RTR
+// or CPC_MSG_T_XCAN or CPC_MSG_T_XRTR
+typedef struct CPC_CAN_MSG {
+	u32 id;
+	u8 length;
+	u8 msg[8];
+} CPC_CAN_MSG_T;
+
+
+// representation of the CAN parameters for the PCA82C200 controller
+typedef struct CPC_PCA82C200_PARAMS {
+	u8 acc_code;	// Acceptance-code for receive, Standard: 0
+	u8 acc_mask;	// Acceptance-mask for receive, Standard: 0xff (everything)
+	u8 btr0;	// Bus-timing register 0
+	u8 btr1;	// Bus-timing register 1
+	u8 outp_contr;	// Output-control register
+} CPC_PCA82C200_PARAMS_T;
+
+// representation of the CAN parameters for the SJA1000 controller
+typedef struct CPC_SJA1000_PARAMS {
+	u8 mode;	// enables single or dual acceptance filtering
+	u8 acc_code0;	// Acceptance-code for receive, Standard: 0
+	u8 acc_code1;
+	u8 acc_code2;
+	u8 acc_code3;
+	u8 acc_mask0;	// Acceptance-mask for receive, Standard: 0xff (everything)
+	u8 acc_mask1;
+	u8 acc_mask2;
+	u8 acc_mask3;
+	u8 btr0;	// Bus-timing register 0
+	u8 btr1;	// Bus-timing register 1
+	u8 outp_contr;	// Output-control register
+} CPC_SJA1000_PARAMS_T;
+
+// representation of the CAN parameters for the M16C controller
+// in basic CAN mode (means no full CAN)
+typedef struct CPC_M16C_BASIC_PARAMS {
+	u8 con0;
+	u8 con1;
+	u8 ctlr0;
+	u8 ctlr1;
+	u8 clk;
+	u8 acc_std_code0;
+	u8 acc_std_code1;
+	u8 acc_ext_code0;
+	u8 acc_ext_code1;
+	u8 acc_ext_code2;
+	u8 acc_ext_code3;
+	u8 acc_std_mask0;
+	u8 acc_std_mask1;
+	u8 acc_ext_mask0;
+	u8 acc_ext_mask1;
+	u8 acc_ext_mask2;
+	u8 acc_ext_mask3;
+} CPC_M16C_BASIC_PARAMS_T;
+
+// CAN params message representation
+typedef struct CPC_CAN_PARAMS {
+	u8 cc_type;	// represents the controller type
+	union {
+		CPC_M16C_BASIC_PARAMS_T m16c_basic;
+		CPC_SJA1000_PARAMS_T sja1000;
+		CPC_PCA82C200_PARAMS_T pca82c200;
+	} cc_params;
+} CPC_CAN_PARAMS_T;
+
+// the following structures are slightly different for Windows and Linux
+// To be able to use the 'Select' mechanism with Linux the application
+// needs to know the devices file desciptor.
+// This mechanism is not implemented within Windows and the file descriptor
+// is therefore not needed
+#ifdef _WIN32
+
+// CAN init params message representation
+typedef struct CPC_INIT_PARAMS {
+	CPC_CAN_PARAMS_T canparams;
+} CPC_INIT_PARAMS_T;
+
+#else// Linux
+
+// CHAN init params representation
+typedef struct CPC_CHAN_PARAMS {
+	int fd;
+} CPC_CHAN_PARAMS_T;
+
+// CAN init params message representation
+typedef struct CPC_INIT_PARAMS {
+	CPC_CHAN_PARAMS_T chanparams;
+	CPC_CAN_PARAMS_T canparams;
+} CPC_INIT_PARAMS_T;
+
+#endif
+
+// structure for confirmed message handling
+typedef struct CPC_CONFIRM {
+	u8 result; // error code
+} CPC_CONFIRM_T;
+
+// structure for information requests
+typedef struct CPC_INFO {
+	u8 source;                 // interface, driver or library
+	u8 type;                   // version or serial number
+	char msg[CPC_MSG_LEN - 2]; // string holding the requested information
+} CPC_INFO_T;
+
+// OVERRUN ///////////////////////////////////////
+// In general two types of overrun may occur.
+// A hardware overrun, where the CAN controller
+// lost a message, because the interrupt was
+// not handled before the next messgae comes in.
+// Or a software overrun, where i.e. a received
+// message could not be stored in the CPC_MSG
+// buffer.
+
+// After a software overrun has occurred
+// we wait until we have CPC_OVR_GAP slots
+// free in the CPC_MSG buffer.
+#define CPC_OVR_GAP               10
+
+// Two types of software overrun may occur.
+// A received CAN message or a CAN state event
+// can cause an overrun.
+// Note: A CPC_CMD which would normally store
+// its result immediately in the CPC_MSG
+// queue may fail, because the message queue is full.
+// This will not generate an overrun message, but
+// will halt command execution, until this command
+// is able to store its message in the message queue.
+#define CPC_OVR_EVENT_CAN       0x01
+#define CPC_OVR_EVENT_CANSTATE  0x02
+#define CPC_OVR_EVENT_BUSERROR  0x04
+
+// If the CAN controller lost a message
+// we indicate it with the highest bit
+// set in the count field.
+#define CPC_OVR_HW              0x80
+
+// structure for overrun conditions
+typedef struct {
+	u8 event;
+	u8 count;
+} CPC_OVERRUN_T;
+
+// CAN errors ////////////////////////////////////
+// Each CAN controller type has different
+// registers to record errors.
+// Therefor a structure containing the specific
+// errors is set up for each controller here
+
+// SJA1000 error structure
+// see the SJA1000 datasheet for detailed
+// explanation of the registers
+typedef struct CPC_SJA1000_CAN_ERROR {
+	u8 ecc;   // error capture code register
+	u8 rxerr; // RX error counter register
+	u8 txerr; // TX error counter register
+} CPC_SJA1000_CAN_ERROR_T;
+
+// M16C error structure
+// see the M16C datasheet for detailed
+// explanation of the registers
+typedef struct CPC_M16C_CAN_ERROR {
+	u8 tbd;	// to be defined
+} CPC_M16C_CAN_ERROR_T;
+
+// structure for CAN error conditions
+#define  CPC_CAN_ECODE_ERRFRAME   0x01
+typedef struct CPC_CAN_ERROR {
+	u8 ecode;
+	struct {
+		u8 cc_type; // CAN controller type
+		union {
+			CPC_SJA1000_CAN_ERROR_T sja1000;
+			CPC_M16C_CAN_ERROR_T m16c;
+		} regs;
+	} cc;
+} CPC_CAN_ERROR_T;
+
+// Structure containing RX/TX error counter.
+// This structure is used to request the
+// values of the CAN controllers TX and RX
+// error counter.
+typedef struct CPC_CAN_ERR_COUNTER {
+	u8 rx;
+	u8 tx;
+} CPC_CAN_ERR_COUNTER_T;
+
+// If this flag is set, transmissions from PC to CPC are protected against loss
+#define CPC_SECURE_TO_CPC	0x01
+
+// If this flag is set, transmissions from CPC to PC are protected against loss
+#define CPC_SECURE_TO_PC	0x02
+
+// If this flag is set, the CAN-transmit buffer is checked to be free before sending a message
+#define CPC_SECURE_SEND		0x04
+
+// If this flag is set, the transmission complete flag is checked
+// after sending a message
+// THIS IS CURRENTLY ONLY IMPLEMENTED IN THE PASSIVE INTERFACE DRIVERS
+#define CPC_SECURE_TRANSMIT	0x08
+
+// main message type used between library and application
+typedef struct CPC_MSG {
+	u8 type;	// type of message
+	u8 length;	// length of data within union 'msg'
+	u8 msgid;	// confirmation handle
+	u32 ts_sec;	// timestamp in seconds
+	u32 ts_nsec;	// timestamp in nano seconds
+	union {
+		u8 generic[CPC_MSG_LEN];
+		CPC_CAN_MSG_T canmsg;
+		CPC_CAN_PARAMS_T canparams;
+		CPC_CONFIRM_T confirmation;
+		CPC_INFO_T info;
+		CPC_OVERRUN_T overrun;
+		CPC_CAN_ERROR_T error;
+		CPC_CAN_ERR_COUNTER_T err_counter;
+		u8 busload;
+		u8 canstate;
+	} msg;
+} CPC_MSG_T;
+
+#ifdef _WIN32
+#pragma pack(pop)		// reset the byte alignment
+#endif
+
+#endif				// CPC_HEADER
diff --git a/drivers/staging/cpc-usb/cpc_int.h b/drivers/staging/cpc-usb/cpc_int.h
new file mode 100644
index 0000000..a0d60c0
--- /dev/null
+++ b/drivers/staging/cpc-usb/cpc_int.h
@@ -0,0 +1,83 @@
+/*
+ * CPCLIB
+ *
+ * Copyright (C) 2000-2008 EMS Dr. Thomas Wuensche
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ */
+#ifndef CPC_INT_H
+#define CPC_INT_H
+
+#include <linux/wait.h>
+
+#define CPC_MSG_BUF_CNT	1500
+
+#define CPC_PROC_DIR "driver/"
+
+#undef dbg
+#undef err
+#undef info
+
+/* Use our own dbg macro */
+#define dbg(format, arg...) do { if (debug) printk( KERN_INFO format "\n" , ## arg); } while (0)
+#define err(format, arg...) do { printk( KERN_INFO "ERROR " format "\n" , ## arg); } while (0)
+#define info(format, arg...) do { printk( KERN_INFO format "\n" , ## arg); } while (0)
+
+/* Macros help using of our buffers */
+#define IsBufferFull(x)     (!(x)->WnR) && ((x)->iidx == (x)->oidx)
+#define IsBufferEmpty(x)    ((x)->WnR) && ((x)->iidx == (x)->oidx)
+#define IsBufferNotEmpty(x) (!(x)->WnR) || ((x)->iidx != (x)->oidx)
+#define ResetBuffer(x)      do { (x)->oidx = (x)->iidx=0; (x)->WnR = 1; } while(0);
+
+#define CPC_BufWriteAllowed ((chan->oidx != chan->iidx) || chan->WnR)
+
+typedef void (*chan_write_byte_t) (void *chan, unsigned int reg,
+				   unsigned char val);
+typedef unsigned char (*chan_read_byte_t) (void *chan, unsigned int reg);
+
+typedef struct CPC_CHAN {
+	void __iomem * canBase;	// base address of SJA1000
+	chan_read_byte_t read_byte;	// CAN controller read access routine
+	chan_write_byte_t write_byte;	// CAN controller write access routine
+	CPC_MSG_T *buf;		// buffer for CPC msg
+	unsigned int iidx;
+	unsigned int oidx;
+	unsigned int WnR;
+	unsigned int minor;
+	unsigned int locked;
+	unsigned int irqDisabled;
+
+	unsigned char cpcCtrlCANMessage;
+	unsigned char cpcCtrlCANState;
+	unsigned char cpcCtrlBUSState;
+
+	unsigned char controllerType;
+
+	unsigned long ovrTimeSec;
+	unsigned long ovrTimeNSec;
+	unsigned long ovrLockedBuffer;
+	CPC_OVERRUN_T ovr;
+
+	/* for debugging only */
+	unsigned int handledIrqs;
+	unsigned int lostMessages;
+
+	unsigned int sentStdCan;
+	unsigned int sentExtCan;
+	unsigned int sentStdRtr;
+	unsigned int sentExtRtr;
+
+	unsigned int recvStdCan;
+	unsigned int recvExtCan;
+	unsigned int recvStdRtr;
+	unsigned int recvExtRtr;
+
+	wait_queue_head_t *CPCWait_q;
+
+	void *private;
+} CPC_CHAN_T;
+
+#endif
diff --git a/drivers/staging/cpc-usb/cpcusb.h b/drivers/staging/cpc-usb/cpcusb.h
new file mode 100644
index 0000000..e5273dd
--- /dev/null
+++ b/drivers/staging/cpc-usb/cpcusb.h
@@ -0,0 +1,86 @@
+/* Header for CPC-USB Driver ********************
+ * Copyright 1999, 2000, 2001
+ *
+ * Company:  EMS Dr. Thomas Wuensche
+ *           Sonnenhang 3
+ *           85304 Ilmmuenster
+ *           Phone: +49-8441-490260
+ *           Fax:   +49-8441-81860
+ *           email: support@ems-wuensche.com
+ *           WWW:   www.ems-wuensche.com
+ */
+
+#ifndef CPCUSB_H
+#define CPCUSB_H
+
+#undef err
+#undef dbg
+#undef info
+
+/* Use our own dbg macro */
+#define dbg(format, arg...) do { if (debug) printk(KERN_INFO "CPC-USB: " format "\n" , ## arg); } while (0)
+#define info(format, arg...) do { printk(KERN_INFO "CPC-USB: " format "\n" , ## arg); } while (0)
+#define err(format, arg...) do { printk(KERN_INFO "CPC-USB(ERROR): " format "\n" , ## arg); } while (0)
+
+#define CPC_USB_CARD_CNT      4
+
+typedef struct CPC_USB_READ_URB {
+	unsigned char *buffer;	/* the buffer to send data */
+	size_t size;		/* the size of the send buffer */
+	struct urb *urb;	/* the urb used to send data */
+} CPC_USB_READ_URB_T;
+
+typedef struct CPC_USB_WRITE_URB {
+	unsigned char *buffer;	/* the buffer to send data */
+	size_t size;		/* the size of the send buffer */
+	struct urb *urb;	/* the urb used to send data */
+	atomic_t busy;		/* true if write urb is busy */
+	struct completion finished;	/* wait for the write to finish */
+} CPC_USB_WRITE_URB_T;
+
+#define CPC_USB_URB_CNT  10
+
+typedef struct CPC_USB {
+	struct usb_device *udev;	/* save off the usb device pointer */
+	struct usb_interface *interface;	/* the interface for this device */
+	unsigned char minor;	/* the starting minor number for this device */
+	unsigned char num_ports;	/* the number of ports this device has */
+	int num_intr_in;	/* number of interrupt in endpoints we have */
+	int num_bulk_in;	/* number of bulk in endpoints we have */
+	int num_bulk_out;	/* number of bulk out endpoints we have */
+
+	CPC_USB_READ_URB_T urbs[CPC_USB_URB_CNT];
+
+	unsigned char intr_in_buffer[4];	/* interrupt transfer buffer */
+	struct urb *intr_in_urb;	/* interrupt transfer urb */
+
+	CPC_USB_WRITE_URB_T wrUrbs[CPC_USB_URB_CNT];
+
+	int open;		/* if the port is open or not */
+	int present;		/* if the device is not disconnected */
+	struct semaphore sem;	/* locks this structure */
+
+	int free_slots;		/* free send slots of CPC-USB */
+	int idx;
+
+	spinlock_t slock;
+
+	char serialNumber[128];	/* serial number */
+	int productId;		/* product id to differ between M16C and LPC2119 */
+	CPC_CHAN_T *chan;
+} CPC_USB_T;
+
+#define CPCTable               CPCUSB_Table
+
+#define CPC_DRIVER_VERSION "0.724"
+#define CPC_DRIVER_SERIAL  "not applicable"
+
+#define OBUF_SIZE 255		// 4096
+
+/* read timeouts -- RD_NAK_TIMEOUT * RD_EXPIRE = Number of seconds */
+#define RD_NAK_TIMEOUT (10*HZ)	/* Default number of X seconds to wait */
+#define RD_EXPIRE 12		/* Number of attempts to wait X seconds */
+
+#define CPC_USB_BASE_MNR 0	/* CPC-USB start at minor 0  */
+
+#endif
diff --git a/drivers/staging/cpc-usb/sja2m16c.h b/drivers/staging/cpc-usb/sja2m16c.h
new file mode 100644
index 0000000..654bd3f
--- /dev/null
+++ b/drivers/staging/cpc-usb/sja2m16c.h
@@ -0,0 +1,41 @@
+#ifndef _SJA2M16C_H
+#define _SJA2M16C_H
+
+#include "cpc.h"
+
+#define BAUDRATE_TOLERANCE_PERCENT	1
+#define SAMPLEPOINT_TOLERANCE_PERCENT	5
+#define SAMPLEPOINT_UPPER_LIMIT		88
+
+/* M16C parameters */
+struct FIELD_C0CONR {
+	unsigned int brp:4;
+	unsigned int sam:1;
+	unsigned int pr:3;
+	unsigned int dummy:8;
+};
+struct FIELD_C1CONR {
+	unsigned int ph1:3;
+	unsigned int ph2:3;
+	unsigned int sjw:2;
+	unsigned int dummy:8;
+};
+typedef union C0CONR {
+	unsigned char c0con;
+	struct FIELD_C0CONR bc0con;
+} C0CONR_T;
+typedef union C1CONR {
+	unsigned char c1con;
+	struct FIELD_C1CONR bc1con;
+} C1CONR_T;
+
+#define SJA_TSEG1	((pParams->btr1 & 0x0f)+1)
+#define SJA_TSEG2	(((pParams->btr1 & 0x70)>>4)+1)
+#define SJA_BRP		((pParams->btr0 & 0x3f)+1)
+#define SJA_SJW		((pParams->btr0 & 0xc0)>>6)
+#define SJA_SAM		((pParams->btr1 & 0x80)>>7)
+int baudrate_m16c(int clk, int brp, int pr, int ph1, int ph2);
+int samplepoint_m16c(int brp, int pr, int ph1, int ph2);
+int SJA1000_TO_M16C_BASIC_Params(CPC_MSG_T *pMsg);
+
+#endif
diff --git a/drivers/staging/cpc-usb/sja2m16c_2.c b/drivers/staging/cpc-usb/sja2m16c_2.c
new file mode 100644
index 0000000..bf0230f
--- /dev/null
+++ b/drivers/staging/cpc-usb/sja2m16c_2.c
@@ -0,0 +1,452 @@
+/****************************************************************************
+*
+*      Copyright (c) 2003,2004 by EMS Dr. Thomas Wuensche
+*
+*                  - All rights reserved -
+*
+* This code is provided "as is" without warranty of any kind, either
+* expressed or implied, including but not limited to the liability
+* concerning the freedom from material defects, the fitness for parti-
+* cular purposes or the freedom of proprietary rights of third parties.
+*
+*****************************************************************************
+* Module name.: cpcusb
+*****************************************************************************
+* Include file: cpc.h
+*****************************************************************************
+* Project.....: Windows Driver Development Kit
+* Filename....: sja2m16c.cpp
+* Authors.....: (GU) Gerhard Uttenthaler
+*               (CS) Christian Schoett
+*****************************************************************************
+* Short descr.: converts baudrate between SJA1000 and M16C
+*****************************************************************************
+* Description.: handles the baudrate conversion from SJA1000 parameters to
+*               M16C parameters
+*****************************************************************************
+* Address     : EMS Dr. Thomas Wuensche
+*               Sonnenhang 3
+*               D-85304 Ilmmuenster
+*               Tel. : +49-8441-490260
+*               Fax. : +49-8441-81860
+*               email: support@ems-wuensche.com
+*****************************************************************************
+*                            History
+*****************************************************************************
+* Version  Date        Auth Remark
+*
+* 01.00    ??          GU   - initial release
+* 01.10    ??????????  CS   - adapted to fit into the USB Windows driver
+* 02.00    18.08.2004  GU   - improved the baudrate calculating algorithm
+*                           - implemented acceptance filtering
+* 02.10    10.09.2004  CS   - adapted to fit into the USB Windows driver
+*****************************************************************************
+*                            ToDo's
+*****************************************************************************
+*/
+
+/****************************************************************************/
+/*     I N C L U D E S
+*/
+#include <linux/kernel.h>
+#include <linux/errno.h>
+#include <linux/init.h>
+#include <linux/slab.h>
+#include <linux/vmalloc.h>
+#include <linux/module.h>
+#include <linux/poll.h>
+#include <linux/smp_lock.h>
+#include <linux/completion.h>
+#include <asm/uaccess.h>
+#include <linux/usb.h>
+
+#include "cpc.h"
+#include "cpc_int.h"
+#include "cpcusb.h"
+
+#include "sja2m16c.h"
+
+/*********************************************************************/
+int baudrate_m16c(int clk, int brp, int pr, int ph1, int ph2)
+{
+	return (16000000 / (1 << clk)) / 2 / (brp + 1) / (1 + pr + 1 +
+							    ph1 + 1 + ph2 +
+							    1);
+}
+
+
+/*********************************************************************/
+int samplepoint_m16c(int brp, int pr, int ph1, int ph2)
+{
+	return (100 * (1 + pr + 1 + ph1 + 1)) / (1 + pr + 1 + ph1 + 1 +
+						  ph2 + 1);
+}
+
+
+/****************************************************************************
+* Function.....: SJA1000_TO_M16C_BASIC_Params
+*
+* Task.........: This routine converts SJA1000 CAN btr parameters into M16C
+*                parameters based on the sample point and the error. In
+*                addition it converts the acceptance filter parameters to
+*                suit the M16C parameters
+*
+* Parameters...: None
+*
+* Return values: None
+*
+* Comments.....:
+*****************************************************************************
+*                History
+*****************************************************************************
+* 19.01.2005  CS   - modifed the conversion of SJA1000 filter params into
+*                    M16C params. Due to compatibility reasons with the
+*                    older 82C200 CAN controller the SJA1000
+****************************************************************************/
+int SJA1000_TO_M16C_BASIC_Params(CPC_MSG_T * in)
+{
+	int sjaBaudrate;
+	int sjaSamplepoint;
+	int *baudrate_error;	// BRP[0..15], PR[0..7], PH1[0..7], PH2[0..7]
+	int *samplepoint_error;	// BRP[0..15], PR[0..7], PH1[0..7], PH2[0..7]
+	int baudrate_error_merk;
+	int clk, brp, pr, ph1, ph2;
+	int clk_merk, brp_merk, pr_merk, ph1_merk, ph2_merk;
+	int index;
+	unsigned char acc_code0, acc_code1, acc_code2, acc_code3;
+	unsigned char acc_mask0, acc_mask1, acc_mask2, acc_mask3;
+	CPC_MSG_T * out;
+	C0CONR_T c0con;
+	C1CONR_T c1con;
+	int tmpAccCode;
+	int tmpAccMask;
+
+	    // we have to convert the parameters into M16C parameters
+	    CPC_SJA1000_PARAMS_T * pParams;
+
+	    // check if the type is CAN parameters and if we have to convert the given params
+	    if (in->type != CPC_CMD_T_CAN_PRMS
+		|| in->msg.canparams.cc_type != SJA1000)
+		return 0;
+	pParams =
+	    (CPC_SJA1000_PARAMS_T *) & in->msg.canparams.cc_params.sja1000;
+	acc_code0 = pParams->acc_code0;
+	acc_code1 = pParams->acc_code1;
+	acc_code2 = pParams->acc_code2;
+	acc_code3 = pParams->acc_code3;
+	acc_mask0 = pParams->acc_mask0;
+	acc_mask1 = pParams->acc_mask1;
+	acc_mask2 = pParams->acc_mask2;
+	acc_mask3 = pParams->acc_mask3;
+
+#ifdef _DEBUG_OUTPUT_CAN_PARAMS
+	    info("acc_code0: %2.2Xh\n", acc_code0);
+	info("acc_code1: %2.2Xh\n", acc_code1);
+	info("acc_code2: %2.2Xh\n", acc_code2);
+	info("acc_code3: %2.2Xh\n", acc_code3);
+	info("acc_mask0: %2.2Xh\n", acc_mask0);
+	info("acc_mask1: %2.2Xh\n", acc_mask1);
+	info("acc_mask2: %2.2Xh\n", acc_mask2);
+	info("acc_mask3: %2.2Xh\n", acc_mask3);
+
+#endif	/*  */
+	    if (!
+		 (baudrate_error =
+		  (int *) vmalloc(sizeof(int) * 16 * 8 * 8 * 8 * 5))) {
+		err("Could not allocate memory\n");
+		return -3;
+	}
+	if (!
+	      (samplepoint_error =
+	       (int *) vmalloc(sizeof(int) * 16 * 8 * 8 * 8 * 5))) {
+		err("Could not allocate memory\n");
+		vfree(baudrate_error);
+		return -3;
+	}
+	memset(baudrate_error, 0xff, sizeof(baudrate_error));
+	memset(samplepoint_error, 0xff, sizeof(baudrate_error));
+	sjaBaudrate =
+	    16000000 / 2 / SJA_BRP / (1 + SJA_TSEG1 + SJA_TSEG2);
+	sjaSamplepoint =
+	    100 * (1 + SJA_TSEG1) / (1 + SJA_TSEG1 + SJA_TSEG2);
+	if (sjaBaudrate == 0) {
+		vfree(baudrate_error);
+		vfree(samplepoint_error);
+		return -2;
+	}
+
+#ifdef _DEBUG_OUTPUT_CAN_PARAMS
+	    info("\nStarting SJA CAN params\n");
+	info("-------------------------\n");
+	info("TS1     : %2.2Xh TS2 : %2.2Xh\n", SJA_TSEG1, SJA_TSEG2);
+	info("BTR0    : %2.2Xh BTR1: %2.2Xh\n", pParams->btr0,
+	      pParams->btr1);
+	info("Baudrate: %d.%dkBaud\n", sjaBaudrate / 1000,
+	      sjaBaudrate % 1000);
+	info("Sample P: 0.%d\n", sjaSamplepoint);
+	info("\n");
+
+#endif	/*  */
+	    c0con.bc0con.sam = SJA_SAM;
+	c1con.bc1con.sjw = SJA_SJW;
+
+	    // calculate errors for all baudrates
+	    index = 0;
+	for (clk = 0; clk < 5; clk++) {
+		for (brp = 0; brp < 16; brp++) {
+			for (pr = 0; pr < 8; pr++) {
+				for (ph1 = 0; ph1 < 8; ph1++) {
+					for (ph2 = 0; ph2 < 8; ph2++) {
+						baudrate_error[index] =
+						    100 *
+						    abs(baudrate_m16c
+							(clk, brp, pr, ph1,
+							 ph2) -
+							sjaBaudrate) /
+						    sjaBaudrate;
+						samplepoint_error[index] =
+						    abs(samplepoint_m16c
+							(brp, pr, ph1,
+							 ph2) -
+							sjaSamplepoint);
+
+#if 0
+						    info
+						    ("Baudrate      : %d kBaud\n",
+						     baudrate_m16c(clk,
+								   brp, pr,
+								   ph1,
+								   ph2));
+						info
+						    ("Baudrate Error: %d\n",
+						     baudrate_error
+						     [index]);
+						info
+						    ("Sample P Error: %d\n",
+						     samplepoint_error
+						     [index]);
+						info
+						    ("clk           : %d\n",
+						     clk);
+
+#endif	/*  */
+						    index++;
+					}
+				}
+			}
+		}
+	}
+
+	    // mark all baudrate_error entries which are outer limits
+	    index = 0;
+	for (clk = 0; clk < 5; clk++) {
+		for (brp = 0; brp < 16; brp++) {
+			for (pr = 0; pr < 8; pr++) {
+				for (ph1 = 0; ph1 < 8; ph1++) {
+					for (ph2 = 0; ph2 < 8; ph2++) {
+						if ((baudrate_error[index]
+						      >
+						      BAUDRATE_TOLERANCE_PERCENT)
+						     ||
+						     (samplepoint_error
+						       [index] >
+						       SAMPLEPOINT_TOLERANCE_PERCENT)
+						     ||
+						     (samplepoint_m16c
+						       (brp, pr, ph1,
+							ph2) >
+						       SAMPLEPOINT_UPPER_LIMIT))
+						{
+							baudrate_error
+							    [index] = -1;
+						} else
+						    if (((1 + pr + 1 +
+							  ph1 + 1 + ph2 +
+							  1) < 8)
+							||
+							((1 + pr + 1 +
+							  ph1 + 1 + ph2 +
+							  1) > 25)) {
+							baudrate_error
+							    [index] = -1;
+						}
+
+#if 0
+						    else {
+							info
+							    ("Baudrate      : %d kBaud\n",
+							     baudrate_m16c
+							     (clk, brp, pr,
+							      ph1, ph2));
+							info
+							    ("Baudrate Error: %d\n",
+							     baudrate_error
+							     [index]);
+							info
+							    ("Sample P Error: %d\n",
+							     samplepoint_error
+							     [index]);
+						}
+
+#endif	/*  */
+						    index++;
+					}
+				}
+			}
+		}
+	}
+
+	    // find list of minimum of baudrate_error within unmarked entries
+	    clk_merk = brp_merk = pr_merk = ph1_merk = ph2_merk = 0;
+	baudrate_error_merk = 100;
+	index = 0;
+	for (clk = 0; clk < 5; clk++) {
+		for (brp = 0; brp < 16; brp++) {
+			for (pr = 0; pr < 8; pr++) {
+				for (ph1 = 0; ph1 < 8; ph1++) {
+					for (ph2 = 0; ph2 < 8; ph2++) {
+						if (baudrate_error[index]
+						     != -1) {
+							if (baudrate_error
+							     [index] <
+							     baudrate_error_merk)
+							{
+								baudrate_error_merk
+								    =
+								    baudrate_error
+								    [index];
+								brp_merk =
+								    brp;
+								pr_merk =
+								    pr;
+								ph1_merk =
+								    ph1;
+								ph2_merk =
+								    ph2;
+								clk_merk =
+								    clk;
+
+#if 0
+								    info
+								    ("brp: %2.2Xh pr: %2.2Xh ph1: %2.2Xh ph2: %2.2Xh\n",
+								     brp,
+								     pr,
+								     ph1,
+								     ph2);
+								info
+								    ("Baudrate      : %d kBaud\n",
+								     baudrate_m16c
+								     (clk,
+								      brp,
+								      pr,
+								      ph1,
+								      ph2));
+								info
+								    ("Baudrate Error: %d\n",
+								     baudrate_error
+								     [index]);
+								info
+								    ("Sample P Error: %d\n",
+								     samplepoint_error
+								     [index]);
+
+#endif	/*  */
+							}
+						}
+						index++;
+					}
+				}
+			}
+		}
+	}
+	if (baudrate_error_merk == 100) {
+		info("ERROR: Could not convert CAN init parameter\n");
+		vfree(baudrate_error);
+		vfree(samplepoint_error);
+		return -1;
+	}
+
+	    // setting m16c CAN parameter
+	    c0con.bc0con.brp = brp_merk;
+	c0con.bc0con.pr = pr_merk;
+	c1con.bc1con.ph1 = ph1_merk;
+	c1con.bc1con.ph2 = ph2_merk;
+
+#ifdef _DEBUG_OUTPUT_CAN_PARAMS
+	    info("\nResulting M16C CAN params\n");
+	info("-------------------------\n");
+	info("clk     : %2.2Xh\n", clk_merk);
+	info("ph1     : %2.2Xh ph2: %2.2Xh\n", c1con.bc1con.ph1 + 1,
+	      c1con.bc1con.ph2 + 1);
+	info("pr      : %2.2Xh brp: %2.2Xh\n", c0con.bc0con.pr + 1,
+	      c0con.bc0con.brp + 1);
+	info("sjw     : %2.2Xh sam: %2.2Xh\n", c1con.bc1con.sjw,
+	      c0con.bc0con.sam);
+	info("co1     : %2.2Xh co0: %2.2Xh\n", c1con.c1con, c0con.c0con);
+	info("Baudrate: %d.%dBaud\n",
+	       baudrate_m16c(clk_merk, c0con.bc0con.brp, c0con.bc0con.pr,
+			     c1con.bc1con.ph1, c1con.bc1con.ph2) / 1000,
+	       baudrate_m16c(clk_merk, c0con.bc0con.brp, c0con.bc0con.pr,
+			      c1con.bc1con.ph1, c1con.bc1con.ph2) % 1000);
+	info("Sample P: 0.%d\n",
+	      samplepoint_m16c(c0con.bc0con.brp, c0con.bc0con.pr,
+			       c1con.bc1con.ph1, c1con.bc1con.ph2));
+	info("\n");
+
+#endif	/*  */
+	    out = in;
+	out->type = 6;
+	out->length = sizeof(CPC_M16C_BASIC_PARAMS_T) + 1;
+	out->msg.canparams.cc_type = M16C_BASIC;
+	out->msg.canparams.cc_params.m16c_basic.con0 = c0con.c0con;
+	out->msg.canparams.cc_params.m16c_basic.con1 = c1con.c1con;
+	out->msg.canparams.cc_params.m16c_basic.ctlr0 = 0x4C;
+	out->msg.canparams.cc_params.m16c_basic.ctlr1 = 0x00;
+	out->msg.canparams.cc_params.m16c_basic.clk = clk_merk;
+	out->msg.canparams.cc_params.m16c_basic.acc_std_code0 =
+	    acc_code0;
+	out->msg.canparams.cc_params.m16c_basic.acc_std_code1 = acc_code1;
+
+//      info("code0: 0x%2.2X, code1: 0x%2.2X\n", out->msg.canparams.cc_params.m16c_basic.acc_std_code0, out->msg.canparams.cc_params.m16c_basic.acc_std_code1);
+	    tmpAccCode = (acc_code1 >> 5) + (acc_code0 << 3);
+	out->msg.canparams.cc_params.m16c_basic.acc_std_code0 =
+	    (unsigned char) tmpAccCode;
+	out->msg.canparams.cc_params.m16c_basic.acc_std_code1 =
+	    (unsigned char) (tmpAccCode >> 8);
+
+//      info("code0: 0x%2.2X, code1: 0x%2.2X\n", out->msg.canparams.cc_params.m16c_basic.acc_std_code0, out->msg.canparams.cc_params.m16c_basic.acc_std_code1);
+	    out->msg.canparams.cc_params.m16c_basic.acc_std_mask0 =
+	    ~acc_mask0;
+	out->msg.canparams.cc_params.m16c_basic.acc_std_mask1 =
+	    ~acc_mask1;
+
+//      info("mask0: 0x%2.2X, mask1: 0x%2.2X\n", out->msg.canparams.cc_params.m16c_basic.acc_std_mask0, out->msg.canparams.cc_params.m16c_basic.acc_std_mask1);
+	    tmpAccMask = ((acc_mask1) >> 5) + ((acc_mask0) << 3);
+
+//      info("tmpAccMask: 0x%4.4X\n", tmpAccMask);
+	    out->msg.canparams.cc_params.m16c_basic.acc_std_mask0 =
+	    (unsigned char) ~tmpAccMask;
+	out->msg.canparams.cc_params.m16c_basic.acc_std_mask1 =
+	    (unsigned char) ~(tmpAccMask >> 8);
+
+//      info("mask0: 0x%2.2X, mask1: 0x%2.2X\n", out->msg.canparams.cc_params.m16c_basic.acc_std_mask0, out->msg.canparams.cc_params.m16c_basic.acc_std_mask1);
+	    out->msg.canparams.cc_params.m16c_basic.acc_ext_code0 =
+	    (unsigned char) tmpAccCode;
+	out->msg.canparams.cc_params.m16c_basic.acc_ext_code1 =
+	    (unsigned char) (tmpAccCode >> 8);
+	out->msg.canparams.cc_params.m16c_basic.acc_ext_code2 = acc_code2;
+	out->msg.canparams.cc_params.m16c_basic.acc_ext_code3 = acc_code3;
+	out->msg.canparams.cc_params.m16c_basic.acc_ext_mask0 =
+	    (unsigned char) ~tmpAccMask;
+	out->msg.canparams.cc_params.m16c_basic.acc_ext_mask1 =
+	    (unsigned char) ~(tmpAccMask >> 8);
+	out->msg.canparams.cc_params.m16c_basic.acc_ext_mask2 =
+	    ~acc_mask2;
+	out->msg.canparams.cc_params.m16c_basic.acc_ext_mask3 =
+	    ~acc_mask3;
+	vfree(baudrate_error);
+	vfree(samplepoint_error);
+	return 0;
+}
+
+
diff --git a/drivers/staging/echo/echo.c b/drivers/staging/echo/echo.c
index 6d7217e..79d15c6 100644
--- a/drivers/staging/echo/echo.c
+++ b/drivers/staging/echo/echo.c
@@ -395,7 +395,7 @@
 		old = (int)ec->fir_state.history[ec->fir_state.curr_pos] *
 		    (int)ec->fir_state.history[ec->fir_state.curr_pos];
 		ec->Pstates +=
-		    ((new - old) + (1 << ec->log2taps)) >> ec->log2taps;
+		    ((new - old) + (1 << (ec->log2taps-1))) >> ec->log2taps;
 		if (ec->Pstates < 0)
 			ec->Pstates = 0;
 	}
diff --git a/drivers/staging/epl/EplSdoUdpu.c b/drivers/staging/epl/EplSdoUdpu.c
index b409c9b..c8e950f 100644
--- a/drivers/staging/epl/EplSdoUdpu.c
+++ b/drivers/staging/epl/EplSdoUdpu.c
@@ -334,7 +334,8 @@
 	}
 	// create Listen-Thread
 	SdoUdpInstance_g.m_ThreadHandle =
-	    kernel_thread(EplSdoUdpThread, &SdoUdpInstance_g, CLONE_KERNEL);
+		kernel_thread(EplSdoUdpThread, &SdoUdpInstance_g,
+				CLONE_FS | CLONE_FILES);
 	if (SdoUdpInstance_g.m_ThreadHandle == 0) {
 		Ret = kEplSdoUdpThreadError;
 		goto Exit;
diff --git a/drivers/staging/epl/ShbIpc-LinuxKernel.c b/drivers/staging/epl/ShbIpc-LinuxKernel.c
index 497938b..12d1ecc 100644
--- a/drivers/staging/epl/ShbIpc-LinuxKernel.c
+++ b/drivers/staging/epl/ShbIpc-LinuxKernel.c
@@ -532,8 +532,8 @@
 
 	//create thread for signalling new data
 	pShbMemInst->m_tThreadNewDataId =
-	    kernel_thread(ShbIpcThreadSignalNewData, pShbInstance_p,
-			  CLONE_KERNEL);
+		kernel_thread(ShbIpcThreadSignalNewData, pShbInstance_p,
+				CLONE_FS | CLONE_FILES);
 
       Exit:
 	return ShbError;
@@ -636,8 +636,8 @@
 	pShbMemHeader->m_fJobReady = FALSE;
 	//create thread for signalling new data
 	pShbMemInst->m_tThreadJobReadyId =
-	    kernel_thread(ShbIpcThreadSignalJobReady, pShbInstance_p,
-			  CLONE_KERNEL);
+		kernel_thread(ShbIpcThreadSignalJobReady, pShbInstance_p,
+				CLONE_FS | CLONE_FILES);
       Exit:
 	return ShbError;
 }
diff --git a/drivers/staging/frontier/alphatrack.c b/drivers/staging/frontier/alphatrack.c
index bcba17e..15aed87 100644
--- a/drivers/staging/frontier/alphatrack.c
+++ b/drivers/staging/frontier/alphatrack.c
@@ -39,7 +39,6 @@
 #include <linux/module.h>
 #include <linux/kobject.h>
 #include <linux/mutex.h>
-#include <linux/version.h>
 
 #include <linux/uaccess.h>
 #include <linux/input.h>
diff --git a/drivers/staging/frontier/tranzport.c b/drivers/staging/frontier/tranzport.c
index 274b82b..ef8fcc8 100644
--- a/drivers/staging/frontier/tranzport.c
+++ b/drivers/staging/frontier/tranzport.c
@@ -38,7 +38,6 @@
 #include <linux/slab.h>
 #include <linux/module.h>
 #include <linux/mutex.h>
-#include <linux/version.h>
 
 #include <linux/uaccess.h>
 #include <linux/input.h>
diff --git a/drivers/staging/go7007/wis-sony-tuner.c b/drivers/staging/go7007/wis-sony-tuner.c
index c965c60..086896c 100644
--- a/drivers/staging/go7007/wis-sony-tuner.c
+++ b/drivers/staging/go7007/wis-sony-tuner.c
@@ -370,7 +370,7 @@
 	i2c_transfer(client->adapter, &msg, 1);
 
 	/* Select MPX mode if not forced by the user */
-	if (force_mpx_mode >= 0 || force_mpx_mode < MPX_NUM_MODES)
+	if (force_mpx_mode >= 0 && force_mpx_mode < MPX_NUM_MODES)
 		t->mpxmode = force_mpx_mode;
 	else
 		t->mpxmode = default_mpx_mode;
diff --git a/drivers/staging/heci/heci.h b/drivers/staging/heci/heci.h
index 14192e0..48f120d 100644
--- a/drivers/staging/heci/heci.h
+++ b/drivers/staging/heci/heci.h
@@ -41,7 +41,6 @@
 #ifndef _HECI_H_
 #define _HECI_H_
 
-#include <linux/version.h>
 #include <linux/spinlock.h>
 #include <linux/list.h>
 #include <linux/pci.h>
diff --git a/drivers/staging/heci/heci_data_structures.h b/drivers/staging/heci/heci_data_structures.h
index 575e8f8..ff30386 100644
--- a/drivers/staging/heci/heci_data_structures.h
+++ b/drivers/staging/heci/heci_data_structures.h
@@ -41,7 +41,6 @@
 #ifndef _HECI_DATA_STRUCTURES_H_
 #define _HECI_DATA_STRUCTURES_H_
 
-#include <linux/version.h>
 #include <linux/spinlock.h>
 #include <linux/list.h>
 #include <linux/pci.h>
diff --git a/drivers/staging/heci/heci_init.c b/drivers/staging/heci/heci_init.c
index a8a0da9..31fd891 100644
--- a/drivers/staging/heci/heci_init.c
+++ b/drivers/staging/heci/heci_init.c
@@ -249,7 +249,7 @@
 
 	if ((dev->host_hw_state & H_IS) == H_IS) {
 		/* acknowledge interrupt and stop interupts */
-		heci_set_csr_register(dev);
+		heci_csr_clear_his(dev);
 	}
 	dev->recvd_msg = 0;
 	DBG("reset in start the heci device.\n");
@@ -354,7 +354,7 @@
 	dev->host_hw_state &= ~H_RST;
 	dev->host_hw_state |= H_IG;
 
-	write_heci_register(dev, H_CSR, dev->host_hw_state);
+	heci_set_csr_register(dev);
 
 	DBG("currently saved host_hw_state = 0x%08x.\n",
 	    dev->host_hw_state);
@@ -998,8 +998,12 @@
 	if ((!dev) || (!file_ext))
 		return -ENODEV;
 
-	if (file_ext->state != HECI_FILE_DISCONNECTING)
+	spin_lock_bh(&dev->device_lock);
+	if (file_ext->state != HECI_FILE_DISCONNECTING) {
+		spin_unlock_bh(&dev->device_lock);
 		return 0;
+	}
+	spin_unlock_bh(&dev->device_lock);
 
 	priv_cb = kzalloc(sizeof(struct heci_cb_private), GFP_KERNEL);
 	if (!priv_cb)
@@ -1012,6 +1016,7 @@
 	if (dev->host_buffer_is_empty) {
 		dev->host_buffer_is_empty = 0;
 		if (heci_disconnect(dev, file_ext)) {
+			mdelay(10); /* Wait for hardware disconnection ready */
 			list_add_tail(&priv_cb->cb_list,
 				&dev->ctrl_rd_list.heci_cb.cb_list);
 		} else {
@@ -1030,6 +1035,8 @@
 	err = wait_event_timeout(dev->wait_recvd_msg,
 		 (HECI_FILE_DISCONNECTED == file_ext->state),
 		 timeout * HZ);
+
+	spin_lock_bh(&dev->device_lock);
 	if (HECI_FILE_DISCONNECTED == file_ext->state) {
 		rets = 0;
 		DBG("successfully disconnected from fw client.\n");
@@ -1044,7 +1051,6 @@
 		DBG("failed to disconnect from fw client.\n");
 	}
 
-	spin_lock_bh(&dev->device_lock);
 	heci_flush_list(&dev->ctrl_rd_list, file_ext);
 	heci_flush_list(&dev->ctrl_wr_list, file_ext);
 	spin_unlock_bh(&dev->device_lock);
diff --git a/drivers/staging/heci/heci_interface.c b/drivers/staging/heci/heci_interface.c
index c5f51a7..03e1df1 100644
--- a/drivers/staging/heci/heci_interface.c
+++ b/drivers/staging/heci/heci_interface.c
@@ -44,12 +44,15 @@
 
 
 /**
- * heci_set_csr_register - write H_CSR register to the heci device
+ * heci_set_csr_register - write H_CSR register to the heci device,
+ * and ignore the H_IS bit for it is write-one-to-zero.
  *
  * @dev: device object for our driver
  */
 void heci_set_csr_register(struct iamt_heci_device *dev)
 {
+	if ((dev->host_hw_state & H_IS) == H_IS)
+		dev->host_hw_state &= ~H_IS;
 	write_heci_register(dev, H_CSR, dev->host_hw_state);
 	dev->host_hw_state = read_heci_register(dev, H_CSR);
 }
@@ -76,6 +79,16 @@
 	heci_set_csr_register(dev);
 }
 
+/**
+ * heci_csr_clear_his - clear H_IS bit in H_CSR
+ *
+ * @dev: device object for our driver
+ */
+void heci_csr_clear_his(struct iamt_heci_device *dev)
+{
+	write_heci_register(dev, H_CSR, dev->host_hw_state);
+	dev->host_hw_state = read_heci_register(dev, H_CSR);
+}
 
 /**
  * _host_get_filled_slots - get number of device filled buffer slots
@@ -185,7 +198,7 @@
 	}
 
 	dev->host_hw_state |= H_IG;
-	write_heci_register(dev, H_CSR, dev->host_hw_state);
+	heci_set_csr_register(dev);
 	dev->me_hw_state = read_heci_register(dev, ME_CSR_HA);
 	if ((dev->me_hw_state & ME_RDY_HRA) != ME_RDY_HRA)
 		return 0;
diff --git a/drivers/staging/heci/heci_interface.h b/drivers/staging/heci/heci_interface.h
index 37336eb..34db7e5 100644
--- a/drivers/staging/heci/heci_interface.h
+++ b/drivers/staging/heci/heci_interface.h
@@ -42,7 +42,6 @@
 #ifndef _HECI_INTERFACE_H_
 #define _HECI_INTERFACE_H_
 
-#include <linux/version.h>
 #include <linux/spinlock.h>
 #include <linux/list.h>
 #include <linux/pci.h>
@@ -134,6 +133,7 @@
 void heci_set_csr_register(struct iamt_heci_device *dev);
 void heci_csr_enable_interrupts(struct iamt_heci_device *dev);
 void heci_csr_disable_interrupts(struct iamt_heci_device *dev);
+void heci_csr_clear_his(struct iamt_heci_device *dev);
 
 void heci_read_slots(struct iamt_heci_device *dev,
 		     unsigned char *buffer, unsigned long buffer_length);
diff --git a/drivers/staging/heci/heci_main.c b/drivers/staging/heci/heci_main.c
index 00e44c7..ddf4822 100644
--- a/drivers/staging/heci/heci_main.c
+++ b/drivers/staging/heci/heci_main.c
@@ -751,7 +751,9 @@
 		(1 << (file_ext->host_client_id % 8));
 	spin_unlock_bh(&dev->device_lock);
 	spin_lock(&file_ext->file_lock);
+	spin_lock_bh(&dev->device_lock);
 	file_ext->state = HECI_FILE_INITIALIZING;
+	spin_unlock_bh(&dev->device_lock);
 	file_ext->sm_state = 0;
 
 	file->private_data = file_ext;
@@ -785,8 +787,10 @@
 
 	if (file_ext != &dev->iamthif_file_ext) {
 		spin_lock(&file_ext->file_lock);
+		spin_lock_bh(&dev->device_lock);
 		if (file_ext->state == HECI_FILE_CONNECTED) {
 			file_ext->state = HECI_FILE_DISCONNECTING;
+			spin_unlock_bh(&dev->device_lock);
 			spin_unlock(&file_ext->file_lock);
 			DBG("disconnecting client host client = %d, "
 			    "ME client = %d\n",
@@ -794,8 +798,8 @@
 			    file_ext->me_client_id);
 			rets = heci_disconnect_host_client(dev, file_ext);
 			spin_lock(&file_ext->file_lock);
+			spin_lock_bh(&dev->device_lock);
 		}
-		spin_lock_bh(&dev->device_lock);
 		heci_flush_queues(dev, file_ext);
 		DBG("remove client host client = %d, ME client = %d\n",
 		    file_ext->host_client_id,
@@ -954,11 +958,11 @@
 		goto out;
 	}
 
-	spin_lock(&file_ext->read_io_lock);
 	err = heci_start_read(dev, if_num, file_ext);
+	spin_lock_bh(&file_ext->read_io_lock);
 	if (err != 0 && err != -EBUSY) {
 		DBG("heci start read failure with status = %d\n", err);
-		spin_unlock(&file_ext->read_io_lock);
+		spin_unlock_bh(&file_ext->read_io_lock);
 		rets = err;
 		goto out;
 	}
@@ -966,10 +970,10 @@
 			&& !waitqueue_active(&file_ext->rx_wait)) {
 		if (file->f_flags & O_NONBLOCK) {
 			rets = -EAGAIN;
-			spin_unlock(&file_ext->read_io_lock);
+			spin_unlock_bh(&file_ext->read_io_lock);
 			goto out;
 		}
-		spin_unlock(&file_ext->read_io_lock);
+		spin_unlock_bh(&file_ext->read_io_lock);
 
 		if (wait_event_interruptible(file_ext->rx_wait,
 			(HECI_READ_COMPLETE == file_ext->reading_state
@@ -983,26 +987,29 @@
 			return -ERESTARTSYS;
 		}
 
+		spin_lock_bh(&dev->device_lock);
 		if (HECI_FILE_INITIALIZING == file_ext->state ||
 		    HECI_FILE_DISCONNECTED == file_ext->state ||
 		    HECI_FILE_DISCONNECTING == file_ext->state) {
+			spin_unlock_bh(&dev->device_lock);
 			rets = -EBUSY;
 			goto out;
 		}
-		spin_lock(&file_ext->read_io_lock);
+		spin_unlock_bh(&dev->device_lock);
+		spin_lock_bh(&file_ext->read_io_lock);
 	}
 
 	priv_cb = file_ext->read_cb;
 
 	if (!priv_cb) {
-		spin_unlock(&file_ext->read_io_lock);
+		spin_unlock_bh(&file_ext->read_io_lock);
 		return -ENODEV;
 	}
 	if (file_ext->reading_state != HECI_READ_COMPLETE) {
-		spin_unlock(&file_ext->read_io_lock);
+		spin_unlock_bh(&file_ext->read_io_lock);
 		return 0;
 	}
-	spin_unlock(&file_ext->read_io_lock);
+	spin_unlock_bh(&file_ext->read_io_lock);
 	/* now copy the data to user space */
 copy_buffer:
 	DBG("priv_cb->response_buffer size - %d\n",
@@ -1040,11 +1047,11 @@
 		list_del(&priv_cb_pos->cb_list);
 	spin_unlock_bh(&dev->device_lock);
 	heci_free_cb_private(priv_cb);
-	spin_lock(&file_ext->read_io_lock);
+	spin_lock_bh(&file_ext->read_io_lock);
 	file_ext->reading_state = HECI_IDLE;
 	file_ext->read_cb = NULL;
 	file_ext->read_pending = 0;
-	spin_unlock(&file_ext->read_io_lock);
+	spin_unlock_bh(&file_ext->read_io_lock);
 out:	DBG("end heci read rets= %d\n", rets);
 	return rets;
 }
@@ -1088,7 +1095,7 @@
 	if (file_ext == &dev->iamthif_file_ext) {
 		priv_write_cb = find_pthi_read_list_entry(dev, file);
 		if ((priv_write_cb != NULL) &&
-		     (((currtime - priv_write_cb->read_time) >
+		     (((currtime - priv_write_cb->read_time) >=
 			    IAMTHIF_READ_TIMER) ||
 		      (file_ext->reading_state == HECI_READ_COMPLETE))) {
 			(*offset) = 0;
@@ -1106,11 +1113,11 @@
 			list_del(&priv_write_cb->cb_list);
 			heci_free_cb_private(priv_write_cb);
 			priv_write_cb = NULL;
-			spin_lock(&file_ext->read_io_lock);
+			spin_lock_bh(&file_ext->read_io_lock);
 			file_ext->reading_state = HECI_IDLE;
 			file_ext->read_cb = NULL;
 			file_ext->read_pending = 0;
-			spin_unlock(&file_ext->read_io_lock);
+			spin_unlock_bh(&file_ext->read_io_lock);
 		}
 	} else if (file_ext->reading_state == HECI_IDLE &&
 			file_ext->read_pending == 0)
@@ -1140,9 +1147,12 @@
 	spin_lock(&file_ext->file_lock);
 	file_ext->sm_state = 0;
 	if ((length == 4) &&
-	    ((memcmp(heci_wd_state_independence_msg[0], ubuf, 4) == 0) ||
-	     (memcmp(heci_wd_state_independence_msg[1], ubuf, 4) == 0) ||
-	     (memcmp(heci_wd_state_independence_msg[2], ubuf, 4) == 0)))
+	    ((memcmp(heci_wd_state_independence_msg[0],
+				 priv_write_cb->request_buffer.data, 4) == 0) ||
+	     (memcmp(heci_wd_state_independence_msg[1],
+				 priv_write_cb->request_buffer.data, 4) == 0) ||
+	     (memcmp(heci_wd_state_independence_msg[2],
+				 priv_write_cb->request_buffer.data, 4) == 0)))
 		file_ext->sm_state |= HECI_WD_STATE_INDEPENDENCE_MSG_SENT;
 	spin_unlock(&file_ext->file_lock);
 
@@ -1222,6 +1232,7 @@
 	priv_write_cb->request_buffer.size = length;
 
 	spin_lock(&file_ext->write_io_lock);
+	spin_lock_bh(&dev->device_lock);
 	DBG("host client = %d, ME client = %d\n",
 	    file_ext->host_client_id, file_ext->me_client_id);
 	if (file_ext->state != HECI_FILE_CONNECTED) {
@@ -1229,7 +1240,7 @@
 		DBG("host client = %d,  is not connected to ME client = %d",
 		    file_ext->host_client_id,
 		    file_ext->me_client_id);
-
+		spin_unlock_bh(&dev->device_lock);
 		goto unlock;
 	}
 	for (i = 0; i < dev->num_heci_me_clients; i++) {
@@ -1240,15 +1251,16 @@
 	BUG_ON(dev->me_clients[i].client_id != file_ext->me_client_id);
 	if (i == dev->num_heci_me_clients) {
 		rets = -ENODEV;
+		spin_unlock_bh(&dev->device_lock);
 		goto unlock;
 	}
 	if (length > dev->me_clients[i].props.max_msg_length || length <= 0) {
 		rets = -EINVAL;
+		spin_unlock_bh(&dev->device_lock);
 		goto unlock;
 	}
 	priv_write_cb->file_private = file_ext;
 
-	spin_lock_bh(&dev->device_lock);
 	if (flow_ctrl_creds(dev, file_ext) &&
 		dev->host_buffer_is_empty) {
 		spin_unlock_bh(&dev->device_lock);
diff --git a/drivers/staging/heci/interrupt.c b/drivers/staging/heci/interrupt.c
index aacd262..2a3a01a 100644
--- a/drivers/staging/heci/interrupt.c
+++ b/drivers/staging/heci/interrupt.c
@@ -92,6 +92,9 @@
 	/* disable interrupts */
 	heci_csr_disable_interrupts(dev);
 
+	/* clear H_IS bit in H_CSR */
+	heci_csr_clear_his(dev);
+
 	/*
 	 * Our device interrupted, schedule work the heci_bh_handler
 	 * to handle the interrupt processing. This needs to be a
@@ -100,10 +103,8 @@
 	PREPARE_WORK(&dev->work, heci_bh_handler);
 	DBG("schedule work the heci_bh_handler.\n");
 	err = schedule_work(&dev->work);
-	if (!err) {
-		printk(KERN_ERR "heci: schedule the heci_bh_handler"
-		       " failed error=%x\n", err);
-	}
+	if (!err)
+		DBG("heci_bh_handler was already on the workqueue.\n");
 	return IRQ_HANDLED;
 }
 
@@ -251,13 +252,14 @@
 		/* acknowledge interrupt and disable interrupts */
 		heci_csr_disable_interrupts(dev);
 
+		/* clear H_IS bit in H_CSR */
+		heci_csr_clear_his(dev);
+
 		PREPARE_WORK(&dev->work, heci_bh_handler);
 		DBG("schedule work the heci_bh_handler.\n");
 		rets = schedule_work(&dev->work);
-		if (!rets) {
-			printk(KERN_ERR "heci: schedule the heci_bh_handler"
-			       " failed error=%x\n", rets);
-		}
+		if (!rets)
+			DBG("heci_bh_handler was already queued.\n");
 	} else {
 		heci_csr_enable_interrupts(dev);
 	}
@@ -622,7 +624,7 @@
 				priv_cb_pos->file_private;
 		if ((file_ext != NULL) &&
 		    (_heci_bh_state_ok(file_ext, heci_hdr))) {
-			spin_lock(&file_ext->read_io_lock);
+			spin_lock_bh(&file_ext->read_io_lock);
 			file_ext->reading_state = HECI_READING;
 			buffer = (unsigned char *)
 				(priv_cb_pos->response_buffer.data +
@@ -636,7 +638,7 @@
 					priv_cb_pos->information) {
 				DBG("message overflow.\n");
 				list_del(&priv_cb_pos->cb_list);
-				spin_unlock(&file_ext->read_io_lock);
+				spin_unlock_bh(&file_ext->read_io_lock);
 				return -ENOMEM;
 			}
 			if (buffer) {
@@ -647,7 +649,7 @@
 			if (heci_hdr->msg_complete) {
 				file_ext->status = 0;
 				list_del(&priv_cb_pos->cb_list);
-				spin_unlock(&file_ext->read_io_lock);
+				spin_unlock_bh(&file_ext->read_io_lock);
 				DBG("completed read host client = %d,"
 					"ME client = %d, "
 					"data length = %lu\n",
@@ -662,7 +664,7 @@
 				list_add_tail(&priv_cb_pos->cb_list,
 					&complete_list->heci_cb.cb_list);
 			} else {
-				spin_unlock(&file_ext->read_io_lock);
+				spin_unlock_bh(&file_ext->read_io_lock);
 			}
 
 			break;
@@ -1054,7 +1056,7 @@
 				list_del(&priv_cb_pos->cb_list);
 				if ((HECI_WRITING == file_ext->writing_state) &&
 					(priv_cb_pos->major_file_operations ==
-						HECI_WRITING) &&
+						HECI_WRITE) &&
 					(file_ext != &dev->iamthif_file_ext)) {
 					DBG("HECI WRITE COMPLETE\n");
 					file_ext->writing_state =
diff --git a/drivers/staging/heci/io_heci.c b/drivers/staging/heci/io_heci.c
index f7544a7..1a6faf8 100644
--- a/drivers/staging/heci/io_heci.c
+++ b/drivers/staging/heci/io_heci.c
@@ -111,7 +111,7 @@
 
 	rets = file_ext->status;
 	/* now copy the data to user space */
-	if (copy_to_user(k_msg.data, res_msg.data, res_msg.size)) {
+	if (copy_to_user((void __user *)k_msg.data, res_msg.data, res_msg.size)) {
 		rets = -EFAULT;
 		goto end;
 	}
@@ -188,7 +188,7 @@
 	/* copy the message to kernel space -
 	 * use a pointer already copied into kernel space
 	 */
-	if (copy_from_user(req_msg.data, k_msg.data, k_msg.size)) {
+	if (copy_from_user(req_msg.data, (void __user *)k_msg.data, k_msg.size)) {
 		rets = -EFAULT;
 		goto end;
 	}
@@ -266,7 +266,8 @@
 		spin_unlock_bh(&dev->device_lock);
 
 		/* now copy the data to user space */
-		if (copy_to_user(k_msg.data, res_msg.data, res_msg.size)) {
+		if (copy_to_user((void __user *)k_msg.data,
+					res_msg.data, res_msg.size)) {
 			rets = -EFAULT;
 			goto end;
 		}
@@ -276,14 +277,16 @@
 		}
 		goto end;
 	}
+	spin_unlock_bh(&dev->device_lock);
+
 	spin_lock(&file_ext->file_lock);
+	spin_lock_bh(&dev->device_lock);
 	if (file_ext->state != HECI_FILE_CONNECTING) {
 		rets = -ENODEV;
-		spin_unlock(&file_ext->file_lock);
 		spin_unlock_bh(&dev->device_lock);
+		spin_unlock(&file_ext->file_lock);
 		goto end;
 	}
-	spin_unlock(&file_ext->file_lock);
 	/* prepare the output buffer */
 	client = (struct heci_client *) res_msg.data;
 	client->max_msg_length = dev->me_clients[i].props.max_msg_length;
@@ -294,6 +297,7 @@
 		if (!heci_connect(dev, file_ext)) {
 			rets = -ENODEV;
 			spin_unlock_bh(&dev->device_lock);
+			spin_unlock(&file_ext->file_lock);
 			goto end;
 		} else {
 			file_ext->timer_count = HECI_CONNECT_TIMEOUT;
@@ -311,16 +315,20 @@
 			      &dev->ctrl_wr_list.heci_cb.cb_list);
 	}
 	spin_unlock_bh(&dev->device_lock);
+	spin_unlock(&file_ext->file_lock);
 	err = wait_event_timeout(dev->wait_recvd_msg,
 			(HECI_FILE_CONNECTED == file_ext->state
 			 || HECI_FILE_DISCONNECTED == file_ext->state),
 			timeout * HZ);
 
+	spin_lock_bh(&dev->device_lock);
 	if (HECI_FILE_CONNECTED == file_ext->state) {
+		spin_unlock_bh(&dev->device_lock);
 		DBG("successfully connected to FW client.\n");
 		rets = file_ext->status;
 		/* now copy the data to user space */
-		if (copy_to_user(k_msg.data, res_msg.data, res_msg.size)) {
+		if (copy_to_user((void __user *)k_msg.data,
+					res_msg.data, res_msg.size)) {
 			rets = -EFAULT;
 			goto end;
 		}
@@ -332,6 +340,7 @@
 	} else {
 		DBG("failed to connect to FW client.file_ext->state = %d.\n",
 		    file_ext->state);
+		spin_unlock_bh(&dev->device_lock);
 		if (!err) {
 			DBG("wait_event_interruptible_timeout failed on client"
 			    " connect message fw response message.\n");
@@ -394,7 +403,8 @@
 	/* copy the message to kernel space - use a pointer already
 	 * copied into kernel space
 	 */
-	if (copy_from_user(req_msg.data, k_msg.data, req_msg.size)) {
+	if (copy_from_user(req_msg.data,
+				(void __user *)k_msg.data, req_msg.size)) {
 		rets = -EFAULT;
 		goto end;
 	}
@@ -464,7 +474,7 @@
 		return -EMSGSIZE;
 	}
 	spin_unlock(&file_ext->file_lock);
-	if (copy_from_user(&flag, k_msg.data, 1)) {
+	if (copy_from_user(&flag, (void __user *)k_msg.data, 1)) {
 		rets = -EFAULT;
 		goto end;
 	}
@@ -631,28 +641,39 @@
 		DBG("received wrong function input param.\n");
 		return -ENODEV;
 	}
-	if (file_ext->state != HECI_FILE_CONNECTED)
-		return -ENODEV;
 
 	spin_lock_bh(&dev->device_lock);
+	if (file_ext->state != HECI_FILE_CONNECTED) {
+		spin_unlock_bh(&dev->device_lock);
+		return -ENODEV;
+	}
+
 	if (dev->heci_state != HECI_ENABLED) {
 		spin_unlock_bh(&dev->device_lock);
 		return -ENODEV;
 	}
 	spin_unlock_bh(&dev->device_lock);
 	DBG("check if read is pending.\n");
+	spin_lock_bh(&file_ext->read_io_lock);
 	if ((file_ext->read_pending) || (file_ext->read_cb != NULL)) {
 		DBG("read is pending.\n");
+		spin_unlock_bh(&file_ext->read_io_lock);
 		return -EBUSY;
 	}
+	spin_unlock_bh(&file_ext->read_io_lock);
+
 	priv_cb = kzalloc(sizeof(struct heci_cb_private), GFP_KERNEL);
 	if (!priv_cb)
 		return -ENOMEM;
 
+	spin_lock_bh(&file_ext->read_io_lock);
 	DBG("allocation call back success\n"
 	    "host client = %d, ME client = %d\n",
 	    file_ext->host_client_id, file_ext->me_client_id);
+	spin_unlock_bh(&file_ext->read_io_lock);
+
 	spin_lock_bh(&dev->device_lock);
+	spin_lock_bh(&file_ext->read_io_lock);
 	for (i = 0; i < dev->num_heci_me_clients; i++) {
 		if (dev->me_clients[i].client_id == file_ext->me_client_id)
 			break;
@@ -660,6 +681,7 @@
 	}
 
 	BUG_ON(dev->me_clients[i].client_id != file_ext->me_client_id);
+	spin_unlock_bh(&file_ext->read_io_lock);
 	if (i == dev->num_heci_me_clients) {
 		rets = -ENODEV;
 		goto unlock;
@@ -678,12 +700,14 @@
 	/* make sure information is zero before we start */
 	priv_cb->information = 0;
 	priv_cb->file_private = (void *) file_ext;
-	file_ext->read_cb = priv_cb;
 	spin_lock_bh(&dev->device_lock);
+	spin_lock_bh(&file_ext->read_io_lock);
+	file_ext->read_cb = priv_cb;
 	if (dev->host_buffer_is_empty) {
 		dev->host_buffer_is_empty = 0;
 		if (!heci_send_flow_control(dev, file_ext)) {
 			rets = -ENODEV;
+			spin_unlock_bh(&file_ext->read_io_lock);
 			goto unlock;
 		} else {
 			list_add_tail(&priv_cb->cb_list,
@@ -693,6 +717,7 @@
 		list_add_tail(&priv_cb->cb_list,
 			      &dev->ctrl_wr_list.heci_cb.cb_list);
 	}
+	spin_unlock_bh(&file_ext->read_io_lock);
 	spin_unlock_bh(&dev->device_lock);
 	return rets;
 unlock:
diff --git a/drivers/staging/meilhaus/me0600_ext_irq.c b/drivers/staging/meilhaus/me0600_ext_irq.c
index 2f6fedc..1d09842 100644
--- a/drivers/staging/meilhaus/me0600_ext_irq.c
+++ b/drivers/staging/meilhaus/me0600_ext_irq.c
@@ -32,7 +32,6 @@
 /*
  * Includes
  */
-#include <linux/version.h>
 #include <linux/module.h>
 
 #include <linux/slab.h>
@@ -434,11 +433,7 @@
 	subdevice->irq = irq;
 
 	err = request_irq(subdevice->irq, me0600_isr,
-#ifdef IRQF_DISABLED
 			  IRQF_DISABLED | IRQF_SHARED,
-#else
-			  SA_INTERRUPT | SA_SHIRQ,
-#endif
 			  ME0600_NAME, (void *)subdevice);
 
 	if (err) {
diff --git a/drivers/staging/meilhaus/me0900_di.c b/drivers/staging/meilhaus/me0900_di.c
index 4665b2a..b8c448f 100644
--- a/drivers/staging/meilhaus/me0900_di.c
+++ b/drivers/staging/meilhaus/me0900_di.c
@@ -38,7 +38,6 @@
 #include <linux/io.h>
 #include <linux/types.h>
 #include <linux/interrupt.h>
-#include <linux/version.h>
 
 #include "medefines.h"
 #include "meinternal.h"
diff --git a/drivers/staging/meilhaus/me1400_device.c b/drivers/staging/meilhaus/me1400_device.c
index ca7498b..a018b5f 100644
--- a/drivers/staging/meilhaus/me1400_device.c
+++ b/drivers/staging/meilhaus/me1400_device.c
@@ -47,7 +47,6 @@
 #include <linux/slab.h>
 #include <linux/sched.h>
 #include <linux/interrupt.h>
-#include <linux/version.h>
 
 #include "meids.h"
 #include "meerror.h"
diff --git a/drivers/staging/meilhaus/me1400_ext_irq.c b/drivers/staging/meilhaus/me1400_ext_irq.c
index 0dc6b45..6841f41 100644
--- a/drivers/staging/meilhaus/me1400_ext_irq.c
+++ b/drivers/staging/meilhaus/me1400_ext_irq.c
@@ -32,7 +32,6 @@
 /*
  * Includes
  */
-#include <linux/version.h>
 #include <linux/module.h>
 
 #include <linux/slab.h>
@@ -458,11 +457,7 @@
 	subdevice->irq = irq;
 
 	err = request_irq(irq, me1400_ext_irq_isr,
-#ifdef IRQF_DISABLED
 			  IRQF_DISABLED | IRQF_SHARED,
-#else
-			  SA_INTERRUPT | SA_SHIRQ,
-#endif
 			  ME1400_NAME, (void *)subdevice);
 
 	if (err) {
diff --git a/drivers/staging/meilhaus/me4600_ai.c b/drivers/staging/meilhaus/me4600_ai.c
index a3cfef0..e496d0c 100644
--- a/drivers/staging/meilhaus/me4600_ai.c
+++ b/drivers/staging/meilhaus/me4600_ai.c
@@ -299,11 +299,7 @@
 	// Register interrupt service routine.
 	subdevice->irq = irq;
 	if (request_irq(subdevice->irq, me4600_ai_isr,
-#ifdef IRQF_DISABLED
 			IRQF_DISABLED | IRQF_SHARED,
-#else
-			SA_INTERRUPT | SA_SHIRQ,
-#endif
 			ME4600_NAME, subdevice)) {
 		PERROR("Cannot register interrupt service routine.\n");
 		me_subdevice_deinit((me_subdevice_t *) subdevice);
diff --git a/drivers/staging/meilhaus/me4600_ai.h b/drivers/staging/meilhaus/me4600_ai.h
index 106e195..7055e44 100644
--- a/drivers/staging/meilhaus/me4600_ai.h
+++ b/drivers/staging/meilhaus/me4600_ai.h
@@ -28,7 +28,6 @@
 #ifndef _ME4600_AI_H_
 #define _ME4600_AI_H_
 
-#include <linux/version.h>
 #include "mesubdevice.h"
 #include "meioctl.h"
 #include "mecirc_buf.h"
diff --git a/drivers/staging/meilhaus/me4600_ao.c b/drivers/staging/meilhaus/me4600_ao.c
index eb47269..4000dac 100644
--- a/drivers/staging/meilhaus/me4600_ao.c
+++ b/drivers/staging/meilhaus/me4600_ao.c
@@ -2567,11 +2567,7 @@
 	if (subdevice->fifo) {
 		subdevice->irq = irq;
 		if (request_irq(subdevice->irq, me4600_ao_isr,
-#ifdef IRQF_DISABLED
 				IRQF_DISABLED | IRQF_SHARED,
-#else
-				SA_INTERRUPT | SA_SHIRQ,
-#endif
 				ME4600_NAME, subdevice)) {
 			PERROR("Cannot get interrupt line.\n");
 			PDEBUG("free circ_buf = %p size=%d",
@@ -5737,7 +5733,7 @@
 	subdevice->irq = irq;
 
 	if (request_irq
-	    (subdevice->irq, me4600_ao_isr, SA_INTERRUPT | SA_SHIRQ,
+	    (subdevice->irq, me4600_ao_isr, IRQF_DISABLED | IRQF_SHARED,
 	     ME4600_NAME, subdevice)) {
 		PERROR("Cannot get interrupt line.\n");
 		me_subdevice_deinit((me_subdevice_t *) subdevice);
diff --git a/drivers/staging/meilhaus/me4600_ext_irq.c b/drivers/staging/meilhaus/me4600_ext_irq.c
index 6b33cba..cfb4adb 100644
--- a/drivers/staging/meilhaus/me4600_ext_irq.c
+++ b/drivers/staging/meilhaus/me4600_ext_irq.c
@@ -39,7 +39,6 @@
 #include <linux/interrupt.h>
 #include <linux/io.h>
 #include <linux/types.h>
-#include <linux/version.h>
 
 #include "medefines.h"
 #include "meinternal.h"
@@ -420,11 +419,7 @@
 	subdevice->irq = irq;
 
 	if (request_irq(subdevice->irq, me4600_ext_irq_isr,
-#ifdef IRQF_DISABLED
 			IRQF_DISABLED | IRQF_SHARED,
-#else
-			SA_INTERRUPT | SA_SHIRQ,
-#endif
 			ME4600_NAME, subdevice)) {
 		PERROR("Cannot register interrupt.\n");
 		kfree(subdevice);
diff --git a/drivers/staging/meilhaus/me6000_ao.c b/drivers/staging/meilhaus/me6000_ao.c
index f7abdbd..66652dc 100644
--- a/drivers/staging/meilhaus/me6000_ao.c
+++ b/drivers/staging/meilhaus/me6000_ao.c
@@ -2627,11 +2627,7 @@
 	if (subdevice->fifo & ME6000_AO_HAS_FIFO) {
 		subdevice->irq = irq;
 		if (request_irq(subdevice->irq, me6000_ao_isr,
-#ifdef IRQF_DISABLED
 				IRQF_DISABLED | IRQF_SHARED,
-#else
-				SA_INTERRUPT | SA_SHIRQ,
-#endif
 				ME6000_NAME, subdevice)) {
 			PERROR("Cannot get interrupt line.\n");
 			PDEBUG("free circ_buf = %p size=%d",
diff --git a/drivers/staging/meilhaus/me6000_ao.h b/drivers/staging/meilhaus/me6000_ao.h
index ef4d018..d86fb29 100644
--- a/drivers/staging/meilhaus/me6000_ao.h
+++ b/drivers/staging/meilhaus/me6000_ao.h
@@ -27,7 +27,6 @@
 #ifndef _ME6000_AO_H_
 #define _ME6000_AO_H_
 
-#include <linux/version.h>
 #include "mesubdevice.h"
 #include "mecirc_buf.h"
 #include "meioctl.h"
diff --git a/drivers/staging/meilhaus/me8100_di.c b/drivers/staging/meilhaus/me8100_di.c
index 301dbd8..1a3f269 100644
--- a/drivers/staging/meilhaus/me8100_di.c
+++ b/drivers/staging/meilhaus/me8100_di.c
@@ -39,7 +39,6 @@
 #include <linux/io.h>
 #include <linux/types.h>
 #include <linux/interrupt.h>
-#include <linux/version.h>
 
 #include "medefines.h"
 #include "meerror.h"
@@ -633,11 +632,7 @@
 	/* Register interrupt service routine. */
 	subdevice->irq = irq;
 	err = request_irq(subdevice->irq, me8100_isr,
-#ifdef IRQF_DISABLED
 			  IRQF_DISABLED | IRQF_SHARED,
-#else
-			  SA_INTERRUPT | SA_SHIRQ,
-#endif
 			  ME8100_NAME, (void *)subdevice);
 
 	if (err) {
diff --git a/drivers/staging/meilhaus/me8200_di.c b/drivers/staging/meilhaus/me8200_di.c
index a931fb8..fd1af0f 100644
--- a/drivers/staging/meilhaus/me8200_di.c
+++ b/drivers/staging/meilhaus/me8200_di.c
@@ -37,7 +37,6 @@
 #include <linux/io.h>
 #include <linux/types.h>
 #include <linux/interrupt.h>
-#include <linux/version.h>
 
 #include "medefines.h"
 #include "meerror.h"
@@ -801,19 +800,11 @@
 	subdevice->irq = irq;
 	if (subdevice->version > 0) {	// NEW
 		err = request_irq(subdevice->irq, me8200_isr_EX,
-#ifdef IRQF_DISABLED
 				  IRQF_DISABLED | IRQF_SHARED,
-#else
-				  SA_INTERRUPT | SA_SHIRQ,
-#endif
 				  ME8200_NAME, (void *)subdevice);
 	} else {		//OLD
 		err = request_irq(subdevice->irq, me8200_isr,
-#ifdef IRQF_DISABLED
 				  IRQF_DISABLED | IRQF_SHARED,
-#else
-				  SA_INTERRUPT | SA_SHIRQ,
-#endif
 				  ME8200_NAME, (void *)subdevice);
 	}
 
diff --git a/drivers/staging/meilhaus/me8200_do.c b/drivers/staging/meilhaus/me8200_do.c
index 40d536c..e42a137 100644
--- a/drivers/staging/meilhaus/me8200_do.c
+++ b/drivers/staging/meilhaus/me8200_do.c
@@ -39,7 +39,6 @@
 #include <linux/interrupt.h>
 #include <linux/io.h>
 #include <linux/types.h>
-#include <linux/version.h>
 
 #include "medefines.h"
 #include "meinternal.h"
@@ -556,11 +555,7 @@
 
 	/* Request the interrupt line */
 	err = request_irq(irq, me8200_do_isr,
-#ifdef IRQF_DISABLED
 			  IRQF_DISABLED | IRQF_SHARED,
-#else
-			  SA_INTERRUPT | SA_SHIRQ,
-#endif
 			  ME8200_NAME, (void *)subdevice);
 
 	if (err) {
diff --git a/drivers/staging/meilhaus/memain.c b/drivers/staging/meilhaus/memain.c
index fd9f079..c490854 100644
--- a/drivers/staging/meilhaus/memain.c
+++ b/drivers/staging/meilhaus/memain.c
@@ -38,7 +38,7 @@
 //#include <linux/usb.h>
 #include <linux/errno.h>
 #include <linux/uaccess.h>
-#include <linux/cdev.h>
+#include <linux/miscdevice.h>
 #include <linux/rwsem.h>
 
 #include "medefines.h"
@@ -68,13 +68,6 @@
 		 "Flags which signals the ME-4600 driver to load the bosch firmware (default = 0).");
 #endif //BOSCH
 
-static unsigned int major = 0;
-#ifdef module_param
-module_param(major, int, S_IRUGO);
-#else
-MODULE_PARM(major, "i");
-#endif
-
 /* Global Driver Lock
 */
 
@@ -100,29 +93,131 @@
 //static int me_probe_usb(struct usb_interface *interface, const struct usb_device_id *id);
 //static void me_disconnect_usb(struct usb_interface *interface);
 
-/* Character device structure
-*/
-
-static struct cdev *cdevp;
-
 /* File operations provided by the module
 */
 
-static struct file_operations me_file_operations = {
+static const struct file_operations me_file_operations = {
 	.owner = THIS_MODULE,
 	.ioctl = me_ioctl,
 	.open = me_open,
 	.release = me_release,
 };
 
-struct pci_driver me_pci_driver = {
+static const struct pci_device_id me_pci_table[] = {
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1000) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1000_A) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1000_B) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1400) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME140A) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME140B) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME14E0) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME14EA) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME14EB) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME140C) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME140D) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1600_4U) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1600_8U) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1600_12U) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1600_16U) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1600_16U_8I) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4610) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4650) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4660) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4660I) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4670) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4670I) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4670S) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4670IS) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4680) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4680I) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4680S) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4680IS) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6004) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6008) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME600F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6014) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6018) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME601F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6034) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6038) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME603F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6104) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6108) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME610F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6114) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6118) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME611F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6134) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6138) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME613F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6044) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6048) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME604F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6054) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6058) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME605F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6074) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6078) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME607F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6144) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6148) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME614F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6154) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6158) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME615F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6174) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6178) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME617F) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6259) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6359) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME0630) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME8100_A) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME8100_B) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME8200_A) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME8200_B) },
+
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME0940) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME0950) },
+	{ PCI_VDEVICE(MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME0960) },
+
+	{ }
+};
+MODULE_DEVICE_TABLE(pci, me_pci_table);
+
+static struct pci_driver me_pci_driver = {
 	.name = MEMAIN_NAME,
 	.id_table = me_pci_table,
 	.probe = me_probe_pci,
-	.remove = me_remove_pci
+	.remove = __devexit_p(me_remove_pci),
 };
 
-/* //me_usb_driver
+/*
+static struct usb_device_id me_usb_table[] = {
+	{ USB_DEVICE(USB_VENDOR_ID_MEPHISTO_S1, USB_DEVICE_ID_MEPHISTO_S1) },
+	{ 0 }
+};
+MODULE_DEVICE_TABLE (usb, me_usb_table);
+
 static struct usb_driver me_usb_driver =
 {
 	.name = MEMAIN_NAME,
@@ -396,7 +491,8 @@
 	return instance;
 }
 
-static int me_probe_pci(struct pci_dev *dev, const struct pci_device_id *id)
+static int __devinit me_probe_pci(struct pci_dev *dev,
+		const struct pci_device_id *id)
 {
 	int err;
 	me_pci_constructor_t constructor = NULL;
@@ -424,7 +520,7 @@
 
 	if ((constructor =
 	     (me_pci_constructor_t) symbol_get(constructor_name)) == NULL) {
-		if (request_module(module_name)) {
+		if (request_module("%s", module_name)) {
 			PERROR("Error while request for module %s.\n",
 			       module_name);
 			return -ENODEV;
@@ -594,7 +690,7 @@
 	return 0;
 }
 
-static void me_remove_pci(struct pci_dev *dev)
+static void __devexit me_remove_pci(struct pci_dev *dev)
 {
 	int vendor_id = dev->vendor;
 	int device_id = dev->device;
@@ -1910,11 +2006,16 @@
 	return -ENOTTY;
 }
 
+static struct miscdevice me_miscdev = {
+	.minor = MISC_DYNAMIC_MINOR,
+	.name = MEMAIN_NAME,
+	.fops = &me_file_operations,
+};
+
 // Init and exit of module.
 static int memain_init(void)
 {
 	int result = 0;
-	dev_t dev = MKDEV(major, 0);
 
 	PDEBUG("executed.\n");
 
@@ -1943,46 +2044,14 @@
 		}
 	}
 */
-	// Register the character device.
-	if (major) {
-		result = register_chrdev_region(dev, 1, MEMAIN_NAME);
-	} else {
-		result = alloc_chrdev_region(&dev, 0, 1, MEMAIN_NAME);
-		major = MAJOR(dev);
-	}
-
+	result = misc_register(&me_miscdev);
 	if (result < 0) {
-		PERROR("Can't get major driver no.\n");
+		printk(KERN_ERR MEMAIN_NAME ": can't register misc device\n");
 		goto INIT_ERROR_3;
 	}
 
-	cdevp = cdev_alloc();
-
-	if (!cdevp) {
-		PERROR("Can't get character device structure.\n");
-		result = -ENOMEM;
-		goto INIT_ERROR_4;
-	}
-
-	cdevp->ops = &me_file_operations;
-
-	cdevp->owner = THIS_MODULE;
-
-	result = cdev_add(cdevp, dev, 1);
-
-	if (result < 0) {
-		PERROR("Cannot add character device structure.\n");
-		goto INIT_ERROR_5;
-	}
-
 	return 0;
 
-      INIT_ERROR_5:
-	cdev_del(cdevp);
-
-      INIT_ERROR_4:
-	unregister_chrdev_region(dev, 1);
-
       INIT_ERROR_3:
 //      usb_deregister(&me_usb_driver);
 
@@ -1996,12 +2065,9 @@
 
 static void __exit memain_exit(void)
 {
-	dev_t dev = MKDEV(major, 0);
-
 	PDEBUG("executed.\n");
 
-	cdev_del(cdevp);
-	unregister_chrdev_region(dev, 1);
+	misc_deregister(&me_miscdev);
 	pci_unregister_driver(&me_pci_driver);
 //      usb_deregister(&me_usb_driver);
 	clear_device_list();
diff --git a/drivers/staging/meilhaus/memain.h b/drivers/staging/meilhaus/memain.h
index 7616ff7..48f8367 100644
--- a/drivers/staging/meilhaus/memain.h
+++ b/drivers/staging/meilhaus/memain.h
@@ -28,200 +28,6 @@
 #ifdef __KERNEL__
 
 /*=============================================================================
-  PCI device table.
-  This is used by modprobe to translate PCI IDs to drivers.
-  ===========================================================================*/
-
-static struct pci_device_id me_pci_table[] __devinitdata = {
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1000, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1000_A, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1000_B, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1400, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME140A, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME140B, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME14E0, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME14EA, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME14EB, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME140C, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME140D, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1600_4U, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1600_8U, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1600_12U, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1600_16U, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME1600_16U_8I,
-	 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4610, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4650, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4660, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4660I, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4670, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4670I, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4670S, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4670IS, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4680, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4680I, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4680S, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME4680IS, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6004, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6008, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME600F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6014, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6018, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME601F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6034, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6038, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME603F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6104, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6108, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME610F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6114, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6118, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME611F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6134, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6138, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME613F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6044, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6048, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME604F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6054, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6058, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME605F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6074, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6078, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME607F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6144, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6148, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME614F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6154, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6158, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME615F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6174, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6178, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME617F, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6259, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME6359, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME0630, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME8100_A, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME8100_B, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME8200_A, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME8200_B, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME0940, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME0950, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-	{PCI_VENDOR_ID_MEILHAUS, PCI_DEVICE_ID_MEILHAUS_ME0960, PCI_ANY_ID,
-	 PCI_ANY_ID, 0, 0, 0},
-
-	{0}
-};
-
-MODULE_DEVICE_TABLE(pci, me_pci_table);
-
-/*=============================================================================
-  USB device table.
-  This is used by modprobe to translate USB IDs to drivers.
-  ===========================================================================*/
-/*
-static struct usb_device_id me_usb_table[] __devinitdata = {
-	{ USB_DEVICE(USB_VENDOR_ID_MEPHISTO_S1, USB_DEVICE_ID_MEPHISTO_S1) },
-	{ 0 }
-};
-
-MODULE_DEVICE_TABLE (usb, me_usb_table);
-*/
-
-/*=============================================================================
   Templates
   ===========================================================================*/
 
diff --git a/drivers/staging/octeon/Kconfig b/drivers/staging/octeon/Kconfig
new file mode 100644
index 0000000..536e238
--- /dev/null
+++ b/drivers/staging/octeon/Kconfig
@@ -0,0 +1,12 @@
+config OCTEON_ETHERNET
+	tristate "Cavium Networks Octeon Ethernet support"
+	depends on CPU_CAVIUM_OCTEON
+	select MII
+	help
+	  This driver supports the builtin ethernet ports on Cavium
+	  Networks' products in the Octeon family. This driver supports the
+	  CN3XXX and CN5XXX Octeon processors.
+
+	  To compile this driver as a module, choose M here.  The module
+	  will be called octeon-ethernet.
+
diff --git a/drivers/staging/octeon/Makefile b/drivers/staging/octeon/Makefile
new file mode 100644
index 0000000..3c839e3
--- /dev/null
+++ b/drivers/staging/octeon/Makefile
@@ -0,0 +1,30 @@
+# This file is subject to the terms and conditions of the GNU General Public
+# License.  See the file "COPYING" in the main directory of this archive
+# for more details.
+#
+# Copyright (C) 2005-2009 Cavium Networks
+#
+
+#
+# Makefile for Cavium OCTEON on-board ethernet driver
+#
+
+obj-${CONFIG_OCTEON_ETHERNET} :=  octeon-ethernet.o
+
+octeon-ethernet-objs := ethernet.o
+octeon-ethernet-objs += ethernet-common.o
+octeon-ethernet-objs += ethernet-mdio.o
+octeon-ethernet-objs += ethernet-mem.o
+octeon-ethernet-objs += ethernet-proc.o
+octeon-ethernet-objs += ethernet-rgmii.o
+octeon-ethernet-objs += ethernet-rx.o
+octeon-ethernet-objs += ethernet-sgmii.o
+octeon-ethernet-objs += ethernet-spi.o
+octeon-ethernet-objs += ethernet-tx.o
+octeon-ethernet-objs += ethernet-xaui.o
+octeon-ethernet-objs += cvmx-pko.o cvmx-spi.o cvmx-cmd-queue.o \
+	cvmx-helper-board.o cvmx-helper.o cvmx-helper-xaui.o \
+	cvmx-helper-rgmii.o cvmx-helper-sgmii.o cvmx-helper-npi.o \
+	cvmx-helper-loop.o cvmx-helper-spi.o cvmx-helper-util.o \
+	cvmx-interrupt-decodes.o cvmx-interrupt-rsl.o
+
diff --git a/drivers/staging/octeon/cvmx-address.h b/drivers/staging/octeon/cvmx-address.h
new file mode 100644
index 0000000..3c74d82
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-address.h
@@ -0,0 +1,274 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2009 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * Typedefs and defines for working with Octeon physical addresses.
+ *
+ */
+#ifndef __CVMX_ADDRESS_H__
+#define __CVMX_ADDRESS_H__
+
+#if 0
+typedef enum {
+	CVMX_MIPS_SPACE_XKSEG = 3LL,
+	CVMX_MIPS_SPACE_XKPHYS = 2LL,
+	CVMX_MIPS_SPACE_XSSEG = 1LL,
+	CVMX_MIPS_SPACE_XUSEG = 0LL
+} cvmx_mips_space_t;
+#endif
+
+typedef enum {
+	CVMX_MIPS_XKSEG_SPACE_KSEG0 = 0LL,
+	CVMX_MIPS_XKSEG_SPACE_KSEG1 = 1LL,
+	CVMX_MIPS_XKSEG_SPACE_SSEG = 2LL,
+	CVMX_MIPS_XKSEG_SPACE_KSEG3 = 3LL
+} cvmx_mips_xkseg_space_t;
+
+/* decodes <14:13> of a kseg3 window address */
+typedef enum {
+	CVMX_ADD_WIN_SCR = 0L,
+	/* see cvmx_add_win_dma_dec_t for further decode */
+	CVMX_ADD_WIN_DMA = 1L,
+	CVMX_ADD_WIN_UNUSED = 2L,
+	CVMX_ADD_WIN_UNUSED2 = 3L
+} cvmx_add_win_dec_t;
+
+/* decode within DMA space */
+typedef enum {
+	/*
+	 * Add store data to the write buffer entry, allocating it if
+	 * necessary.
+	 */
+	CVMX_ADD_WIN_DMA_ADD = 0L,
+	/* send out the write buffer entry to DRAM */
+	CVMX_ADD_WIN_DMA_SENDMEM = 1L,
+	/* store data must be normal DRAM memory space address in this case */
+	/* send out the write buffer entry as an IOBDMA command */
+	CVMX_ADD_WIN_DMA_SENDDMA = 2L,
+	/* see CVMX_ADD_WIN_DMA_SEND_DEC for data contents */
+	/* send out the write buffer entry as an IO write */
+	CVMX_ADD_WIN_DMA_SENDIO = 3L,
+	/* store data must be normal IO space address in this case */
+	/* send out a single-tick command on the NCB bus */
+	CVMX_ADD_WIN_DMA_SENDSINGLE = 4L,
+	/* no write buffer data needed/used */
+} cvmx_add_win_dma_dec_t;
+
+/*
+ *   Physical Address Decode
+ *
+ * Octeon-I HW never interprets this X (<39:36> reserved
+ * for future expansion), software should set to 0.
+ *
+ *  - 0x0 XXX0 0000 0000 to      DRAM         Cached
+ *  - 0x0 XXX0 0FFF FFFF
+ *
+ *  - 0x0 XXX0 1000 0000 to      Boot Bus     Uncached  (Converted to 0x1 00X0 1000 0000
+ *  - 0x0 XXX0 1FFF FFFF         + EJTAG                           to 0x1 00X0 1FFF FFFF)
+ *
+ *  - 0x0 XXX0 2000 0000 to      DRAM         Cached
+ *  - 0x0 XXXF FFFF FFFF
+ *
+ *  - 0x1 00X0 0000 0000 to      Boot Bus     Uncached
+ *  - 0x1 00XF FFFF FFFF
+ *
+ *  - 0x1 01X0 0000 0000 to      Other NCB    Uncached
+ *  - 0x1 FFXF FFFF FFFF         devices
+ *
+ * Decode of all Octeon addresses
+ */
+typedef union {
+
+	uint64_t u64;
+	/* mapped or unmapped virtual address */
+	struct {
+		uint64_t R:2;
+		uint64_t offset:62;
+	} sva;
+
+	/* mapped USEG virtual addresses (typically) */
+	struct {
+		uint64_t zeroes:33;
+		uint64_t offset:31;
+	} suseg;
+
+	/* mapped or unmapped virtual address */
+	struct {
+		uint64_t ones:33;
+		uint64_t sp:2;
+		uint64_t offset:29;
+	} sxkseg;
+
+	/*
+	 * physical address accessed through xkphys unmapped virtual
+	 * address.
+	 */
+	struct {
+		uint64_t R:2;	/* CVMX_MIPS_SPACE_XKPHYS in this case */
+		uint64_t cca:3;	/* ignored by octeon */
+		uint64_t mbz:10;
+		uint64_t pa:49;	/* physical address */
+	} sxkphys;
+
+	/* physical address */
+	struct {
+		uint64_t mbz:15;
+		/* if set, the address is uncached and resides on MCB bus */
+		uint64_t is_io:1;
+		/*
+		 * the hardware ignores this field when is_io==0, else
+		 * device ID.
+		 */
+		uint64_t did:8;
+		/* the hardware ignores <39:36> in Octeon I */
+		uint64_t unaddr:4;
+		uint64_t offset:36;
+	} sphys;
+
+	/* physical mem address */
+	struct {
+		/* techically, <47:40> are dont-cares */
+		uint64_t zeroes:24;
+		/* the hardware ignores <39:36> in Octeon I */
+		uint64_t unaddr:4;
+		uint64_t offset:36;
+	} smem;
+
+	/* physical IO address */
+	struct {
+		uint64_t mem_region:2;
+		uint64_t mbz:13;
+		/* 1 in this case */
+		uint64_t is_io:1;
+		/*
+		 * The hardware ignores this field when is_io==0, else
+		 * device ID.
+		 */
+		uint64_t did:8;
+		/* the hardware ignores <39:36> in Octeon I */
+		uint64_t unaddr:4;
+		uint64_t offset:36;
+	} sio;
+
+	/*
+	 * Scratchpad virtual address - accessed through a window at
+	 * the end of kseg3
+	 */
+	struct {
+		uint64_t ones:49;
+		/* CVMX_ADD_WIN_SCR (0) in this case */
+		cvmx_add_win_dec_t csrdec:2;
+		uint64_t addr:13;
+	} sscr;
+
+	/* there should only be stores to IOBDMA space, no loads */
+	/*
+	 * IOBDMA virtual address - accessed through a window at the
+	 * end of kseg3
+	 */
+	struct {
+		uint64_t ones:49;
+		uint64_t csrdec:2;	/* CVMX_ADD_WIN_DMA (1) in this case */
+		uint64_t unused2:3;
+		uint64_t type:3;
+		uint64_t addr:7;
+	} sdma;
+
+	struct {
+		uint64_t didspace:24;
+		uint64_t unused:40;
+	} sfilldidspace;
+
+} cvmx_addr_t;
+
+/* These macros for used by 32 bit applications */
+
+#define CVMX_MIPS32_SPACE_KSEG0 1l
+#define CVMX_ADD_SEG32(segment, add) \
+	(((int32_t)segment << 31) | (int32_t)(add))
+
+/*
+ * Currently all IOs are performed using XKPHYS addressing. Linux uses
+ * the CvmMemCtl register to enable XKPHYS addressing to IO space from
+ * user mode.  Future OSes may need to change the upper bits of IO
+ * addresses. The following define controls the upper two bits for all
+ * IO addresses generated by the simple executive library.
+ */
+#define CVMX_IO_SEG CVMX_MIPS_SPACE_XKPHYS
+
+/* These macros simplify the process of creating common IO addresses */
+#define CVMX_ADD_SEG(segment, add) ((((uint64_t)segment) << 62) | (add))
+#ifndef CVMX_ADD_IO_SEG
+#define CVMX_ADD_IO_SEG(add) CVMX_ADD_SEG(CVMX_IO_SEG, (add))
+#endif
+#define CVMX_ADDR_DIDSPACE(did) (((CVMX_IO_SEG) << 22) | ((1ULL) << 8) | (did))
+#define CVMX_ADDR_DID(did) (CVMX_ADDR_DIDSPACE(did) << 40)
+#define CVMX_FULL_DID(did, subdid) (((did) << 3) | (subdid))
+
+  /* from include/ncb_rsl_id.v */
+#define CVMX_OCT_DID_MIS 0ULL	/* misc stuff */
+#define CVMX_OCT_DID_GMX0 1ULL
+#define CVMX_OCT_DID_GMX1 2ULL
+#define CVMX_OCT_DID_PCI 3ULL
+#define CVMX_OCT_DID_KEY 4ULL
+#define CVMX_OCT_DID_FPA 5ULL
+#define CVMX_OCT_DID_DFA 6ULL
+#define CVMX_OCT_DID_ZIP 7ULL
+#define CVMX_OCT_DID_RNG 8ULL
+#define CVMX_OCT_DID_IPD 9ULL
+#define CVMX_OCT_DID_PKT 10ULL
+#define CVMX_OCT_DID_TIM 11ULL
+#define CVMX_OCT_DID_TAG 12ULL
+  /* the rest are not on the IO bus */
+#define CVMX_OCT_DID_L2C 16ULL
+#define CVMX_OCT_DID_LMC 17ULL
+#define CVMX_OCT_DID_SPX0 18ULL
+#define CVMX_OCT_DID_SPX1 19ULL
+#define CVMX_OCT_DID_PIP 20ULL
+#define CVMX_OCT_DID_ASX0 22ULL
+#define CVMX_OCT_DID_ASX1 23ULL
+#define CVMX_OCT_DID_IOB 30ULL
+
+#define CVMX_OCT_DID_PKT_SEND       CVMX_FULL_DID(CVMX_OCT_DID_PKT, 2ULL)
+#define CVMX_OCT_DID_TAG_SWTAG      CVMX_FULL_DID(CVMX_OCT_DID_TAG, 0ULL)
+#define CVMX_OCT_DID_TAG_TAG1       CVMX_FULL_DID(CVMX_OCT_DID_TAG, 1ULL)
+#define CVMX_OCT_DID_TAG_TAG2       CVMX_FULL_DID(CVMX_OCT_DID_TAG, 2ULL)
+#define CVMX_OCT_DID_TAG_TAG3       CVMX_FULL_DID(CVMX_OCT_DID_TAG, 3ULL)
+#define CVMX_OCT_DID_TAG_NULL_RD    CVMX_FULL_DID(CVMX_OCT_DID_TAG, 4ULL)
+#define CVMX_OCT_DID_TAG_CSR        CVMX_FULL_DID(CVMX_OCT_DID_TAG, 7ULL)
+#define CVMX_OCT_DID_FAU_FAI        CVMX_FULL_DID(CVMX_OCT_DID_IOB, 0ULL)
+#define CVMX_OCT_DID_TIM_CSR        CVMX_FULL_DID(CVMX_OCT_DID_TIM, 0ULL)
+#define CVMX_OCT_DID_KEY_RW         CVMX_FULL_DID(CVMX_OCT_DID_KEY, 0ULL)
+#define CVMX_OCT_DID_PCI_6          CVMX_FULL_DID(CVMX_OCT_DID_PCI, 6ULL)
+#define CVMX_OCT_DID_MIS_BOO        CVMX_FULL_DID(CVMX_OCT_DID_MIS, 0ULL)
+#define CVMX_OCT_DID_PCI_RML        CVMX_FULL_DID(CVMX_OCT_DID_PCI, 0ULL)
+#define CVMX_OCT_DID_IPD_CSR        CVMX_FULL_DID(CVMX_OCT_DID_IPD, 7ULL)
+#define CVMX_OCT_DID_DFA_CSR        CVMX_FULL_DID(CVMX_OCT_DID_DFA, 7ULL)
+#define CVMX_OCT_DID_MIS_CSR        CVMX_FULL_DID(CVMX_OCT_DID_MIS, 7ULL)
+#define CVMX_OCT_DID_ZIP_CSR        CVMX_FULL_DID(CVMX_OCT_DID_ZIP, 0ULL)
+
+#endif /* __CVMX_ADDRESS_H__ */
diff --git a/drivers/staging/octeon/cvmx-asxx-defs.h b/drivers/staging/octeon/cvmx-asxx-defs.h
new file mode 100644
index 0000000..91415a8
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-asxx-defs.h
@@ -0,0 +1,475 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_ASXX_DEFS_H__
+#define __CVMX_ASXX_DEFS_H__
+
+#define CVMX_ASXX_GMII_RX_CLK_SET(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000180ull + (((block_id) & 0) * 0x8000000ull))
+#define CVMX_ASXX_GMII_RX_DAT_SET(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000188ull + (((block_id) & 0) * 0x8000000ull))
+#define CVMX_ASXX_INT_EN(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000018ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_INT_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000010ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_MII_RX_DAT_SET(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000190ull + (((block_id) & 0) * 0x8000000ull))
+#define CVMX_ASXX_PRT_LOOP(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000040ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RLD_BYPASS(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000248ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RLD_BYPASS_SETTING(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000250ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RLD_COMP(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000220ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RLD_DATA_DRV(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000218ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RLD_FCRAM_MODE(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000210ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RLD_NCTL_STRONG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000230ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RLD_NCTL_WEAK(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000240ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RLD_PCTL_STRONG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000228ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RLD_PCTL_WEAK(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000238ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RLD_SETTING(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000258ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RX_CLK_SETX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000020ull + (((offset) & 3) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RX_PRT_EN(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000000ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RX_WOL(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000100ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RX_WOL_MSK(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000108ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RX_WOL_POWOK(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000118ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_RX_WOL_SIG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000110ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_TX_CLK_SETX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000048ull + (((offset) & 3) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_TX_COMP_BYP(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000068ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_TX_HI_WATERX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000080ull + (((offset) & 3) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_ASXX_TX_PRT_EN(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000008ull + (((block_id) & 1) * 0x8000000ull))
+
+union cvmx_asxx_gmii_rx_clk_set {
+	uint64_t u64;
+	struct cvmx_asxx_gmii_rx_clk_set_s {
+		uint64_t reserved_5_63:59;
+		uint64_t setting:5;
+	} s;
+	struct cvmx_asxx_gmii_rx_clk_set_s cn30xx;
+	struct cvmx_asxx_gmii_rx_clk_set_s cn31xx;
+	struct cvmx_asxx_gmii_rx_clk_set_s cn50xx;
+};
+
+union cvmx_asxx_gmii_rx_dat_set {
+	uint64_t u64;
+	struct cvmx_asxx_gmii_rx_dat_set_s {
+		uint64_t reserved_5_63:59;
+		uint64_t setting:5;
+	} s;
+	struct cvmx_asxx_gmii_rx_dat_set_s cn30xx;
+	struct cvmx_asxx_gmii_rx_dat_set_s cn31xx;
+	struct cvmx_asxx_gmii_rx_dat_set_s cn50xx;
+};
+
+union cvmx_asxx_int_en {
+	uint64_t u64;
+	struct cvmx_asxx_int_en_s {
+		uint64_t reserved_12_63:52;
+		uint64_t txpsh:4;
+		uint64_t txpop:4;
+		uint64_t ovrflw:4;
+	} s;
+	struct cvmx_asxx_int_en_cn30xx {
+		uint64_t reserved_11_63:53;
+		uint64_t txpsh:3;
+		uint64_t reserved_7_7:1;
+		uint64_t txpop:3;
+		uint64_t reserved_3_3:1;
+		uint64_t ovrflw:3;
+	} cn30xx;
+	struct cvmx_asxx_int_en_cn30xx cn31xx;
+	struct cvmx_asxx_int_en_s cn38xx;
+	struct cvmx_asxx_int_en_s cn38xxp2;
+	struct cvmx_asxx_int_en_cn30xx cn50xx;
+	struct cvmx_asxx_int_en_s cn58xx;
+	struct cvmx_asxx_int_en_s cn58xxp1;
+};
+
+union cvmx_asxx_int_reg {
+	uint64_t u64;
+	struct cvmx_asxx_int_reg_s {
+		uint64_t reserved_12_63:52;
+		uint64_t txpsh:4;
+		uint64_t txpop:4;
+		uint64_t ovrflw:4;
+	} s;
+	struct cvmx_asxx_int_reg_cn30xx {
+		uint64_t reserved_11_63:53;
+		uint64_t txpsh:3;
+		uint64_t reserved_7_7:1;
+		uint64_t txpop:3;
+		uint64_t reserved_3_3:1;
+		uint64_t ovrflw:3;
+	} cn30xx;
+	struct cvmx_asxx_int_reg_cn30xx cn31xx;
+	struct cvmx_asxx_int_reg_s cn38xx;
+	struct cvmx_asxx_int_reg_s cn38xxp2;
+	struct cvmx_asxx_int_reg_cn30xx cn50xx;
+	struct cvmx_asxx_int_reg_s cn58xx;
+	struct cvmx_asxx_int_reg_s cn58xxp1;
+};
+
+union cvmx_asxx_mii_rx_dat_set {
+	uint64_t u64;
+	struct cvmx_asxx_mii_rx_dat_set_s {
+		uint64_t reserved_5_63:59;
+		uint64_t setting:5;
+	} s;
+	struct cvmx_asxx_mii_rx_dat_set_s cn30xx;
+	struct cvmx_asxx_mii_rx_dat_set_s cn50xx;
+};
+
+union cvmx_asxx_prt_loop {
+	uint64_t u64;
+	struct cvmx_asxx_prt_loop_s {
+		uint64_t reserved_8_63:56;
+		uint64_t ext_loop:4;
+		uint64_t int_loop:4;
+	} s;
+	struct cvmx_asxx_prt_loop_cn30xx {
+		uint64_t reserved_7_63:57;
+		uint64_t ext_loop:3;
+		uint64_t reserved_3_3:1;
+		uint64_t int_loop:3;
+	} cn30xx;
+	struct cvmx_asxx_prt_loop_cn30xx cn31xx;
+	struct cvmx_asxx_prt_loop_s cn38xx;
+	struct cvmx_asxx_prt_loop_s cn38xxp2;
+	struct cvmx_asxx_prt_loop_cn30xx cn50xx;
+	struct cvmx_asxx_prt_loop_s cn58xx;
+	struct cvmx_asxx_prt_loop_s cn58xxp1;
+};
+
+union cvmx_asxx_rld_bypass {
+	uint64_t u64;
+	struct cvmx_asxx_rld_bypass_s {
+		uint64_t reserved_1_63:63;
+		uint64_t bypass:1;
+	} s;
+	struct cvmx_asxx_rld_bypass_s cn38xx;
+	struct cvmx_asxx_rld_bypass_s cn38xxp2;
+	struct cvmx_asxx_rld_bypass_s cn58xx;
+	struct cvmx_asxx_rld_bypass_s cn58xxp1;
+};
+
+union cvmx_asxx_rld_bypass_setting {
+	uint64_t u64;
+	struct cvmx_asxx_rld_bypass_setting_s {
+		uint64_t reserved_5_63:59;
+		uint64_t setting:5;
+	} s;
+	struct cvmx_asxx_rld_bypass_setting_s cn38xx;
+	struct cvmx_asxx_rld_bypass_setting_s cn38xxp2;
+	struct cvmx_asxx_rld_bypass_setting_s cn58xx;
+	struct cvmx_asxx_rld_bypass_setting_s cn58xxp1;
+};
+
+union cvmx_asxx_rld_comp {
+	uint64_t u64;
+	struct cvmx_asxx_rld_comp_s {
+		uint64_t reserved_9_63:55;
+		uint64_t pctl:5;
+		uint64_t nctl:4;
+	} s;
+	struct cvmx_asxx_rld_comp_cn38xx {
+		uint64_t reserved_8_63:56;
+		uint64_t pctl:4;
+		uint64_t nctl:4;
+	} cn38xx;
+	struct cvmx_asxx_rld_comp_cn38xx cn38xxp2;
+	struct cvmx_asxx_rld_comp_s cn58xx;
+	struct cvmx_asxx_rld_comp_s cn58xxp1;
+};
+
+union cvmx_asxx_rld_data_drv {
+	uint64_t u64;
+	struct cvmx_asxx_rld_data_drv_s {
+		uint64_t reserved_8_63:56;
+		uint64_t pctl:4;
+		uint64_t nctl:4;
+	} s;
+	struct cvmx_asxx_rld_data_drv_s cn38xx;
+	struct cvmx_asxx_rld_data_drv_s cn38xxp2;
+	struct cvmx_asxx_rld_data_drv_s cn58xx;
+	struct cvmx_asxx_rld_data_drv_s cn58xxp1;
+};
+
+union cvmx_asxx_rld_fcram_mode {
+	uint64_t u64;
+	struct cvmx_asxx_rld_fcram_mode_s {
+		uint64_t reserved_1_63:63;
+		uint64_t mode:1;
+	} s;
+	struct cvmx_asxx_rld_fcram_mode_s cn38xx;
+	struct cvmx_asxx_rld_fcram_mode_s cn38xxp2;
+};
+
+union cvmx_asxx_rld_nctl_strong {
+	uint64_t u64;
+	struct cvmx_asxx_rld_nctl_strong_s {
+		uint64_t reserved_5_63:59;
+		uint64_t nctl:5;
+	} s;
+	struct cvmx_asxx_rld_nctl_strong_s cn38xx;
+	struct cvmx_asxx_rld_nctl_strong_s cn38xxp2;
+	struct cvmx_asxx_rld_nctl_strong_s cn58xx;
+	struct cvmx_asxx_rld_nctl_strong_s cn58xxp1;
+};
+
+union cvmx_asxx_rld_nctl_weak {
+	uint64_t u64;
+	struct cvmx_asxx_rld_nctl_weak_s {
+		uint64_t reserved_5_63:59;
+		uint64_t nctl:5;
+	} s;
+	struct cvmx_asxx_rld_nctl_weak_s cn38xx;
+	struct cvmx_asxx_rld_nctl_weak_s cn38xxp2;
+	struct cvmx_asxx_rld_nctl_weak_s cn58xx;
+	struct cvmx_asxx_rld_nctl_weak_s cn58xxp1;
+};
+
+union cvmx_asxx_rld_pctl_strong {
+	uint64_t u64;
+	struct cvmx_asxx_rld_pctl_strong_s {
+		uint64_t reserved_5_63:59;
+		uint64_t pctl:5;
+	} s;
+	struct cvmx_asxx_rld_pctl_strong_s cn38xx;
+	struct cvmx_asxx_rld_pctl_strong_s cn38xxp2;
+	struct cvmx_asxx_rld_pctl_strong_s cn58xx;
+	struct cvmx_asxx_rld_pctl_strong_s cn58xxp1;
+};
+
+union cvmx_asxx_rld_pctl_weak {
+	uint64_t u64;
+	struct cvmx_asxx_rld_pctl_weak_s {
+		uint64_t reserved_5_63:59;
+		uint64_t pctl:5;
+	} s;
+	struct cvmx_asxx_rld_pctl_weak_s cn38xx;
+	struct cvmx_asxx_rld_pctl_weak_s cn38xxp2;
+	struct cvmx_asxx_rld_pctl_weak_s cn58xx;
+	struct cvmx_asxx_rld_pctl_weak_s cn58xxp1;
+};
+
+union cvmx_asxx_rld_setting {
+	uint64_t u64;
+	struct cvmx_asxx_rld_setting_s {
+		uint64_t reserved_13_63:51;
+		uint64_t dfaset:5;
+		uint64_t dfalag:1;
+		uint64_t dfalead:1;
+		uint64_t dfalock:1;
+		uint64_t setting:5;
+	} s;
+	struct cvmx_asxx_rld_setting_cn38xx {
+		uint64_t reserved_5_63:59;
+		uint64_t setting:5;
+	} cn38xx;
+	struct cvmx_asxx_rld_setting_cn38xx cn38xxp2;
+	struct cvmx_asxx_rld_setting_s cn58xx;
+	struct cvmx_asxx_rld_setting_s cn58xxp1;
+};
+
+union cvmx_asxx_rx_clk_setx {
+	uint64_t u64;
+	struct cvmx_asxx_rx_clk_setx_s {
+		uint64_t reserved_5_63:59;
+		uint64_t setting:5;
+	} s;
+	struct cvmx_asxx_rx_clk_setx_s cn30xx;
+	struct cvmx_asxx_rx_clk_setx_s cn31xx;
+	struct cvmx_asxx_rx_clk_setx_s cn38xx;
+	struct cvmx_asxx_rx_clk_setx_s cn38xxp2;
+	struct cvmx_asxx_rx_clk_setx_s cn50xx;
+	struct cvmx_asxx_rx_clk_setx_s cn58xx;
+	struct cvmx_asxx_rx_clk_setx_s cn58xxp1;
+};
+
+union cvmx_asxx_rx_prt_en {
+	uint64_t u64;
+	struct cvmx_asxx_rx_prt_en_s {
+		uint64_t reserved_4_63:60;
+		uint64_t prt_en:4;
+	} s;
+	struct cvmx_asxx_rx_prt_en_cn30xx {
+		uint64_t reserved_3_63:61;
+		uint64_t prt_en:3;
+	} cn30xx;
+	struct cvmx_asxx_rx_prt_en_cn30xx cn31xx;
+	struct cvmx_asxx_rx_prt_en_s cn38xx;
+	struct cvmx_asxx_rx_prt_en_s cn38xxp2;
+	struct cvmx_asxx_rx_prt_en_cn30xx cn50xx;
+	struct cvmx_asxx_rx_prt_en_s cn58xx;
+	struct cvmx_asxx_rx_prt_en_s cn58xxp1;
+};
+
+union cvmx_asxx_rx_wol {
+	uint64_t u64;
+	struct cvmx_asxx_rx_wol_s {
+		uint64_t reserved_2_63:62;
+		uint64_t status:1;
+		uint64_t enable:1;
+	} s;
+	struct cvmx_asxx_rx_wol_s cn38xx;
+	struct cvmx_asxx_rx_wol_s cn38xxp2;
+};
+
+union cvmx_asxx_rx_wol_msk {
+	uint64_t u64;
+	struct cvmx_asxx_rx_wol_msk_s {
+		uint64_t msk:64;
+	} s;
+	struct cvmx_asxx_rx_wol_msk_s cn38xx;
+	struct cvmx_asxx_rx_wol_msk_s cn38xxp2;
+};
+
+union cvmx_asxx_rx_wol_powok {
+	uint64_t u64;
+	struct cvmx_asxx_rx_wol_powok_s {
+		uint64_t reserved_1_63:63;
+		uint64_t powerok:1;
+	} s;
+	struct cvmx_asxx_rx_wol_powok_s cn38xx;
+	struct cvmx_asxx_rx_wol_powok_s cn38xxp2;
+};
+
+union cvmx_asxx_rx_wol_sig {
+	uint64_t u64;
+	struct cvmx_asxx_rx_wol_sig_s {
+		uint64_t reserved_32_63:32;
+		uint64_t sig:32;
+	} s;
+	struct cvmx_asxx_rx_wol_sig_s cn38xx;
+	struct cvmx_asxx_rx_wol_sig_s cn38xxp2;
+};
+
+union cvmx_asxx_tx_clk_setx {
+	uint64_t u64;
+	struct cvmx_asxx_tx_clk_setx_s {
+		uint64_t reserved_5_63:59;
+		uint64_t setting:5;
+	} s;
+	struct cvmx_asxx_tx_clk_setx_s cn30xx;
+	struct cvmx_asxx_tx_clk_setx_s cn31xx;
+	struct cvmx_asxx_tx_clk_setx_s cn38xx;
+	struct cvmx_asxx_tx_clk_setx_s cn38xxp2;
+	struct cvmx_asxx_tx_clk_setx_s cn50xx;
+	struct cvmx_asxx_tx_clk_setx_s cn58xx;
+	struct cvmx_asxx_tx_clk_setx_s cn58xxp1;
+};
+
+union cvmx_asxx_tx_comp_byp {
+	uint64_t u64;
+	struct cvmx_asxx_tx_comp_byp_s {
+		uint64_t reserved_0_63:64;
+	} s;
+	struct cvmx_asxx_tx_comp_byp_cn30xx {
+		uint64_t reserved_9_63:55;
+		uint64_t bypass:1;
+		uint64_t pctl:4;
+		uint64_t nctl:4;
+	} cn30xx;
+	struct cvmx_asxx_tx_comp_byp_cn30xx cn31xx;
+	struct cvmx_asxx_tx_comp_byp_cn38xx {
+		uint64_t reserved_8_63:56;
+		uint64_t pctl:4;
+		uint64_t nctl:4;
+	} cn38xx;
+	struct cvmx_asxx_tx_comp_byp_cn38xx cn38xxp2;
+	struct cvmx_asxx_tx_comp_byp_cn50xx {
+		uint64_t reserved_17_63:47;
+		uint64_t bypass:1;
+		uint64_t reserved_13_15:3;
+		uint64_t pctl:5;
+		uint64_t reserved_5_7:3;
+		uint64_t nctl:5;
+	} cn50xx;
+	struct cvmx_asxx_tx_comp_byp_cn58xx {
+		uint64_t reserved_13_63:51;
+		uint64_t pctl:5;
+		uint64_t reserved_5_7:3;
+		uint64_t nctl:5;
+	} cn58xx;
+	struct cvmx_asxx_tx_comp_byp_cn58xx cn58xxp1;
+};
+
+union cvmx_asxx_tx_hi_waterx {
+	uint64_t u64;
+	struct cvmx_asxx_tx_hi_waterx_s {
+		uint64_t reserved_4_63:60;
+		uint64_t mark:4;
+	} s;
+	struct cvmx_asxx_tx_hi_waterx_cn30xx {
+		uint64_t reserved_3_63:61;
+		uint64_t mark:3;
+	} cn30xx;
+	struct cvmx_asxx_tx_hi_waterx_cn30xx cn31xx;
+	struct cvmx_asxx_tx_hi_waterx_s cn38xx;
+	struct cvmx_asxx_tx_hi_waterx_s cn38xxp2;
+	struct cvmx_asxx_tx_hi_waterx_cn30xx cn50xx;
+	struct cvmx_asxx_tx_hi_waterx_s cn58xx;
+	struct cvmx_asxx_tx_hi_waterx_s cn58xxp1;
+};
+
+union cvmx_asxx_tx_prt_en {
+	uint64_t u64;
+	struct cvmx_asxx_tx_prt_en_s {
+		uint64_t reserved_4_63:60;
+		uint64_t prt_en:4;
+	} s;
+	struct cvmx_asxx_tx_prt_en_cn30xx {
+		uint64_t reserved_3_63:61;
+		uint64_t prt_en:3;
+	} cn30xx;
+	struct cvmx_asxx_tx_prt_en_cn30xx cn31xx;
+	struct cvmx_asxx_tx_prt_en_s cn38xx;
+	struct cvmx_asxx_tx_prt_en_s cn38xxp2;
+	struct cvmx_asxx_tx_prt_en_cn30xx cn50xx;
+	struct cvmx_asxx_tx_prt_en_s cn58xx;
+	struct cvmx_asxx_tx_prt_en_s cn58xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-cmd-queue.c b/drivers/staging/octeon/cvmx-cmd-queue.c
new file mode 100644
index 0000000..976227b
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-cmd-queue.c
@@ -0,0 +1,306 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Support functions for managing command queues used for
+ * various hardware blocks.
+ */
+
+#include <linux/kernel.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-config.h"
+#include "cvmx-fpa.h"
+#include "cvmx-cmd-queue.h"
+
+#include <asm/octeon/cvmx-npei-defs.h>
+#include <asm/octeon/cvmx-pexp-defs.h>
+#include "cvmx-pko-defs.h"
+
+/**
+ * This application uses this pointer to access the global queue
+ * state. It points to a bootmem named block.
+ */
+__cvmx_cmd_queue_all_state_t *__cvmx_cmd_queue_state_ptr;
+
+/**
+ * Initialize the Global queue state pointer.
+ *
+ * Returns CVMX_CMD_QUEUE_SUCCESS or a failure code
+ */
+static cvmx_cmd_queue_result_t __cvmx_cmd_queue_init_state_ptr(void)
+{
+	char *alloc_name = "cvmx_cmd_queues";
+#if defined(CONFIG_CAVIUM_RESERVE32) && CONFIG_CAVIUM_RESERVE32
+	extern uint64_t octeon_reserve32_memory;
+#endif
+
+	if (likely(__cvmx_cmd_queue_state_ptr))
+		return CVMX_CMD_QUEUE_SUCCESS;
+
+#if defined(CONFIG_CAVIUM_RESERVE32) && CONFIG_CAVIUM_RESERVE32
+	if (octeon_reserve32_memory)
+		__cvmx_cmd_queue_state_ptr =
+		    cvmx_bootmem_alloc_named_range(sizeof(*__cvmx_cmd_queue_state_ptr),
+						   octeon_reserve32_memory,
+						   octeon_reserve32_memory +
+						   (CONFIG_CAVIUM_RESERVE32 <<
+						    20) - 1, 128, alloc_name);
+	else
+#endif
+		__cvmx_cmd_queue_state_ptr =
+		    cvmx_bootmem_alloc_named(sizeof(*__cvmx_cmd_queue_state_ptr),
+					    128,
+					    alloc_name);
+	if (__cvmx_cmd_queue_state_ptr)
+		memset(__cvmx_cmd_queue_state_ptr, 0,
+		       sizeof(*__cvmx_cmd_queue_state_ptr));
+	else {
+		struct cvmx_bootmem_named_block_desc *block_desc =
+		    cvmx_bootmem_find_named_block(alloc_name);
+		if (block_desc)
+			__cvmx_cmd_queue_state_ptr =
+			    cvmx_phys_to_ptr(block_desc->base_addr);
+		else {
+			cvmx_dprintf
+			    ("ERROR: cvmx_cmd_queue_initialize: Unable to get named block %s.\n",
+			     alloc_name);
+			return CVMX_CMD_QUEUE_NO_MEMORY;
+		}
+	}
+	return CVMX_CMD_QUEUE_SUCCESS;
+}
+
+/**
+ * Initialize a command queue for use. The initial FPA buffer is
+ * allocated and the hardware unit is configured to point to the
+ * new command queue.
+ *
+ * @queue_id:  Hardware command queue to initialize.
+ * @max_depth: Maximum outstanding commands that can be queued.
+ * @fpa_pool:  FPA pool the command queues should come from.
+ * @pool_size: Size of each buffer in the FPA pool (bytes)
+ *
+ * Returns CVMX_CMD_QUEUE_SUCCESS or a failure code
+ */
+cvmx_cmd_queue_result_t cvmx_cmd_queue_initialize(cvmx_cmd_queue_id_t queue_id,
+						  int max_depth, int fpa_pool,
+						  int pool_size)
+{
+	__cvmx_cmd_queue_state_t *qstate;
+	cvmx_cmd_queue_result_t result = __cvmx_cmd_queue_init_state_ptr();
+	if (result != CVMX_CMD_QUEUE_SUCCESS)
+		return result;
+
+	qstate = __cvmx_cmd_queue_get_state(queue_id);
+	if (qstate == NULL)
+		return CVMX_CMD_QUEUE_INVALID_PARAM;
+
+	/*
+	 * We artificially limit max_depth to 1<<20 words. It is an
+	 * arbitrary limit.
+	 */
+	if (CVMX_CMD_QUEUE_ENABLE_MAX_DEPTH) {
+		if ((max_depth < 0) || (max_depth > 1 << 20))
+			return CVMX_CMD_QUEUE_INVALID_PARAM;
+	} else if (max_depth != 0)
+		return CVMX_CMD_QUEUE_INVALID_PARAM;
+
+	if ((fpa_pool < 0) || (fpa_pool > 7))
+		return CVMX_CMD_QUEUE_INVALID_PARAM;
+	if ((pool_size < 128) || (pool_size > 65536))
+		return CVMX_CMD_QUEUE_INVALID_PARAM;
+
+	/* See if someone else has already initialized the queue */
+	if (qstate->base_ptr_div128) {
+		if (max_depth != (int)qstate->max_depth) {
+			cvmx_dprintf("ERROR: cvmx_cmd_queue_initialize: "
+				"Queue already initalized with different "
+				"max_depth (%d).\n",
+			     (int)qstate->max_depth);
+			return CVMX_CMD_QUEUE_INVALID_PARAM;
+		}
+		if (fpa_pool != qstate->fpa_pool) {
+			cvmx_dprintf("ERROR: cvmx_cmd_queue_initialize: "
+				"Queue already initalized with different "
+				"FPA pool (%u).\n",
+			     qstate->fpa_pool);
+			return CVMX_CMD_QUEUE_INVALID_PARAM;
+		}
+		if ((pool_size >> 3) - 1 != qstate->pool_size_m1) {
+			cvmx_dprintf("ERROR: cvmx_cmd_queue_initialize: "
+				"Queue already initalized with different "
+				"FPA pool size (%u).\n",
+			     (qstate->pool_size_m1 + 1) << 3);
+			return CVMX_CMD_QUEUE_INVALID_PARAM;
+		}
+		CVMX_SYNCWS;
+		return CVMX_CMD_QUEUE_ALREADY_SETUP;
+	} else {
+		union cvmx_fpa_ctl_status status;
+		void *buffer;
+
+		status.u64 = cvmx_read_csr(CVMX_FPA_CTL_STATUS);
+		if (!status.s.enb) {
+			cvmx_dprintf("ERROR: cvmx_cmd_queue_initialize: "
+				     "FPA is not enabled.\n");
+			return CVMX_CMD_QUEUE_NO_MEMORY;
+		}
+		buffer = cvmx_fpa_alloc(fpa_pool);
+		if (buffer == NULL) {
+			cvmx_dprintf("ERROR: cvmx_cmd_queue_initialize: "
+				     "Unable to allocate initial buffer.\n");
+			return CVMX_CMD_QUEUE_NO_MEMORY;
+		}
+
+		memset(qstate, 0, sizeof(*qstate));
+		qstate->max_depth = max_depth;
+		qstate->fpa_pool = fpa_pool;
+		qstate->pool_size_m1 = (pool_size >> 3) - 1;
+		qstate->base_ptr_div128 = cvmx_ptr_to_phys(buffer) / 128;
+		/*
+		 * We zeroed the now serving field so we need to also
+		 * zero the ticket.
+		 */
+		__cvmx_cmd_queue_state_ptr->
+		    ticket[__cvmx_cmd_queue_get_index(queue_id)] = 0;
+		CVMX_SYNCWS;
+		return CVMX_CMD_QUEUE_SUCCESS;
+	}
+}
+
+/**
+ * Shutdown a queue a free it's command buffers to the FPA. The
+ * hardware connected to the queue must be stopped before this
+ * function is called.
+ *
+ * @queue_id: Queue to shutdown
+ *
+ * Returns CVMX_CMD_QUEUE_SUCCESS or a failure code
+ */
+cvmx_cmd_queue_result_t cvmx_cmd_queue_shutdown(cvmx_cmd_queue_id_t queue_id)
+{
+	__cvmx_cmd_queue_state_t *qptr = __cvmx_cmd_queue_get_state(queue_id);
+	if (qptr == NULL) {
+		cvmx_dprintf("ERROR: cvmx_cmd_queue_shutdown: Unable to "
+			     "get queue information.\n");
+		return CVMX_CMD_QUEUE_INVALID_PARAM;
+	}
+
+	if (cvmx_cmd_queue_length(queue_id) > 0) {
+		cvmx_dprintf("ERROR: cvmx_cmd_queue_shutdown: Queue still "
+			     "has data in it.\n");
+		return CVMX_CMD_QUEUE_FULL;
+	}
+
+	__cvmx_cmd_queue_lock(queue_id, qptr);
+	if (qptr->base_ptr_div128) {
+		cvmx_fpa_free(cvmx_phys_to_ptr
+			      ((uint64_t) qptr->base_ptr_div128 << 7),
+			      qptr->fpa_pool, 0);
+		qptr->base_ptr_div128 = 0;
+	}
+	__cvmx_cmd_queue_unlock(qptr);
+
+	return CVMX_CMD_QUEUE_SUCCESS;
+}
+
+/**
+ * Return the number of command words pending in the queue. This
+ * function may be relatively slow for some hardware units.
+ *
+ * @queue_id: Hardware command queue to query
+ *
+ * Returns Number of outstanding commands
+ */
+int cvmx_cmd_queue_length(cvmx_cmd_queue_id_t queue_id)
+{
+	if (CVMX_ENABLE_PARAMETER_CHECKING) {
+		if (__cvmx_cmd_queue_get_state(queue_id) == NULL)
+			return CVMX_CMD_QUEUE_INVALID_PARAM;
+	}
+
+	/*
+	 * The cast is here so gcc with check that all values in the
+	 * cvmx_cmd_queue_id_t enumeration are here.
+	 */
+	switch ((cvmx_cmd_queue_id_t) (queue_id & 0xff0000)) {
+	case CVMX_CMD_QUEUE_PKO_BASE:
+		/*
+		 * FIXME: Need atomic lock on
+		 * CVMX_PKO_REG_READ_IDX. Right now we are normally
+		 * called with the queue lock, so that is a SLIGHT
+		 * amount of protection.
+		 */
+		cvmx_write_csr(CVMX_PKO_REG_READ_IDX, queue_id & 0xffff);
+		if (OCTEON_IS_MODEL(OCTEON_CN3XXX)) {
+			union cvmx_pko_mem_debug9 debug9;
+			debug9.u64 = cvmx_read_csr(CVMX_PKO_MEM_DEBUG9);
+			return debug9.cn38xx.doorbell;
+		} else {
+			union cvmx_pko_mem_debug8 debug8;
+			debug8.u64 = cvmx_read_csr(CVMX_PKO_MEM_DEBUG8);
+			return debug8.cn58xx.doorbell;
+		}
+	case CVMX_CMD_QUEUE_ZIP:
+	case CVMX_CMD_QUEUE_DFA:
+	case CVMX_CMD_QUEUE_RAID:
+		/* FIXME: Implement other lengths */
+		return 0;
+	case CVMX_CMD_QUEUE_DMA_BASE:
+		{
+			union cvmx_npei_dmax_counts dmax_counts;
+			dmax_counts.u64 =
+			    cvmx_read_csr(CVMX_PEXP_NPEI_DMAX_COUNTS
+					  (queue_id & 0x7));
+			return dmax_counts.s.dbell;
+		}
+	case CVMX_CMD_QUEUE_END:
+		return CVMX_CMD_QUEUE_INVALID_PARAM;
+	}
+	return CVMX_CMD_QUEUE_INVALID_PARAM;
+}
+
+/**
+ * Return the command buffer to be written to. The purpose of this
+ * function is to allow CVMX routine access t othe low level buffer
+ * for initial hardware setup. User applications should not call this
+ * function directly.
+ *
+ * @queue_id: Command queue to query
+ *
+ * Returns Command buffer or NULL on failure
+ */
+void *cvmx_cmd_queue_buffer(cvmx_cmd_queue_id_t queue_id)
+{
+	__cvmx_cmd_queue_state_t *qptr = __cvmx_cmd_queue_get_state(queue_id);
+	if (qptr && qptr->base_ptr_div128)
+		return cvmx_phys_to_ptr((uint64_t) qptr->base_ptr_div128 << 7);
+	else
+		return NULL;
+}
diff --git a/drivers/staging/octeon/cvmx-cmd-queue.h b/drivers/staging/octeon/cvmx-cmd-queue.h
new file mode 100644
index 0000000..f0cb20f
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-cmd-queue.h
@@ -0,0 +1,617 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ *
+ * Support functions for managing command queues used for
+ * various hardware blocks.
+ *
+ * The common command queue infrastructure abstracts out the
+ * software necessary for adding to Octeon's chained queue
+ * structures. These structures are used for commands to the
+ * PKO, ZIP, DFA, RAID, and DMA engine blocks. Although each
+ * hardware unit takes commands and CSRs of different types,
+ * they all use basic linked command buffers to store the
+ * pending request. In general, users of the CVMX API don't
+ * call cvmx-cmd-queue functions directly. Instead the hardware
+ * unit specific wrapper should be used. The wrappers perform
+ * unit specific validation and CSR writes to submit the
+ * commands.
+ *
+ * Even though most software will never directly interact with
+ * cvmx-cmd-queue, knowledge of its internal working can help
+ * in diagnosing performance problems and help with debugging.
+ *
+ * Command queue pointers are stored in a global named block
+ * called "cvmx_cmd_queues". Except for the PKO queues, each
+ * hardware queue is stored in its own cache line to reduce SMP
+ * contention on spin locks. The PKO queues are stored such that
+ * every 16th queue is next to each other in memory. This scheme
+ * allows for queues being in separate cache lines when there
+ * are low number of queues per port. With 16 queues per port,
+ * the first queue for each port is in the same cache area. The
+ * second queues for each port are in another area, etc. This
+ * allows software to implement very efficient lockless PKO with
+ * 16 queues per port using a minimum of cache lines per core.
+ * All queues for a given core will be isolated in the same
+ * cache area.
+ *
+ * In addition to the memory pointer layout, cvmx-cmd-queue
+ * provides an optimized fair ll/sc locking mechanism for the
+ * queues. The lock uses a "ticket / now serving" model to
+ * maintain fair order on contended locks. In addition, it uses
+ * predicted locking time to limit cache contention. When a core
+ * know it must wait in line for a lock, it spins on the
+ * internal cycle counter to completely eliminate any causes of
+ * bus traffic.
+ *
+ */
+
+#ifndef __CVMX_CMD_QUEUE_H__
+#define __CVMX_CMD_QUEUE_H__
+
+#include <linux/prefetch.h>
+
+#include "cvmx-fpa.h"
+/**
+ * By default we disable the max depth support. Most programs
+ * don't use it and it slows down the command queue processing
+ * significantly.
+ */
+#ifndef CVMX_CMD_QUEUE_ENABLE_MAX_DEPTH
+#define CVMX_CMD_QUEUE_ENABLE_MAX_DEPTH 0
+#endif
+
+/**
+ * Enumeration representing all hardware blocks that use command
+ * queues. Each hardware block has up to 65536 sub identifiers for
+ * multiple command queues. Not all chips support all hardware
+ * units.
+ */
+typedef enum {
+	CVMX_CMD_QUEUE_PKO_BASE = 0x00000,
+
+#define CVMX_CMD_QUEUE_PKO(queue) \
+	((cvmx_cmd_queue_id_t)(CVMX_CMD_QUEUE_PKO_BASE + (0xffff&(queue))))
+
+	CVMX_CMD_QUEUE_ZIP = 0x10000,
+	CVMX_CMD_QUEUE_DFA = 0x20000,
+	CVMX_CMD_QUEUE_RAID = 0x30000,
+	CVMX_CMD_QUEUE_DMA_BASE = 0x40000,
+
+#define CVMX_CMD_QUEUE_DMA(queue) \
+	((cvmx_cmd_queue_id_t)(CVMX_CMD_QUEUE_DMA_BASE + (0xffff&(queue))))
+
+	CVMX_CMD_QUEUE_END = 0x50000,
+} cvmx_cmd_queue_id_t;
+
+/**
+ * Command write operations can fail if the comamnd queue needs
+ * a new buffer and the associated FPA pool is empty. It can also
+ * fail if the number of queued command words reaches the maximum
+ * set at initialization.
+ */
+typedef enum {
+	CVMX_CMD_QUEUE_SUCCESS = 0,
+	CVMX_CMD_QUEUE_NO_MEMORY = -1,
+	CVMX_CMD_QUEUE_FULL = -2,
+	CVMX_CMD_QUEUE_INVALID_PARAM = -3,
+	CVMX_CMD_QUEUE_ALREADY_SETUP = -4,
+} cvmx_cmd_queue_result_t;
+
+typedef struct {
+	/* You have lock when this is your ticket */
+	uint8_t now_serving;
+	uint64_t unused1:24;
+	/* Maximum outstanding command words */
+	uint32_t max_depth;
+	/* FPA pool buffers come from */
+	uint64_t fpa_pool:3;
+	/* Top of command buffer pointer shifted 7 */
+	uint64_t base_ptr_div128:29;
+	uint64_t unused2:6;
+	/* FPA buffer size in 64bit words minus 1 */
+	uint64_t pool_size_m1:13;
+	/* Number of comamnds already used in buffer */
+	uint64_t index:13;
+} __cvmx_cmd_queue_state_t;
+
+/**
+ * This structure contains the global state of all comamnd queues.
+ * It is stored in a bootmem named block and shared by all
+ * applications running on Octeon. Tickets are stored in a differnet
+ * cahce line that queue information to reduce the contention on the
+ * ll/sc used to get a ticket. If this is not the case, the update
+ * of queue state causes the ll/sc to fail quite often.
+ */
+typedef struct {
+	uint64_t ticket[(CVMX_CMD_QUEUE_END >> 16) * 256];
+	__cvmx_cmd_queue_state_t state[(CVMX_CMD_QUEUE_END >> 16) * 256];
+} __cvmx_cmd_queue_all_state_t;
+
+/**
+ * Initialize a command queue for use. The initial FPA buffer is
+ * allocated and the hardware unit is configured to point to the
+ * new command queue.
+ *
+ * @queue_id:  Hardware command queue to initialize.
+ * @max_depth: Maximum outstanding commands that can be queued.
+ * @fpa_pool:  FPA pool the command queues should come from.
+ * @pool_size: Size of each buffer in the FPA pool (bytes)
+ *
+ * Returns CVMX_CMD_QUEUE_SUCCESS or a failure code
+ */
+cvmx_cmd_queue_result_t cvmx_cmd_queue_initialize(cvmx_cmd_queue_id_t queue_id,
+						  int max_depth, int fpa_pool,
+						  int pool_size);
+
+/**
+ * Shutdown a queue a free it's command buffers to the FPA. The
+ * hardware connected to the queue must be stopped before this
+ * function is called.
+ *
+ * @queue_id: Queue to shutdown
+ *
+ * Returns CVMX_CMD_QUEUE_SUCCESS or a failure code
+ */
+cvmx_cmd_queue_result_t cvmx_cmd_queue_shutdown(cvmx_cmd_queue_id_t queue_id);
+
+/**
+ * Return the number of command words pending in the queue. This
+ * function may be relatively slow for some hardware units.
+ *
+ * @queue_id: Hardware command queue to query
+ *
+ * Returns Number of outstanding commands
+ */
+int cvmx_cmd_queue_length(cvmx_cmd_queue_id_t queue_id);
+
+/**
+ * Return the command buffer to be written to. The purpose of this
+ * function is to allow CVMX routine access t othe low level buffer
+ * for initial hardware setup. User applications should not call this
+ * function directly.
+ *
+ * @queue_id: Command queue to query
+ *
+ * Returns Command buffer or NULL on failure
+ */
+void *cvmx_cmd_queue_buffer(cvmx_cmd_queue_id_t queue_id);
+
+/**
+ * Get the index into the state arrays for the supplied queue id.
+ *
+ * @queue_id: Queue ID to get an index for
+ *
+ * Returns Index into the state arrays
+ */
+static inline int __cvmx_cmd_queue_get_index(cvmx_cmd_queue_id_t queue_id)
+{
+	/*
+	 * Warning: This code currently only works with devices that
+	 * have 256 queues or less. Devices with more than 16 queues
+	 * are layed out in memory to allow cores quick access to
+	 * every 16th queue. This reduces cache thrashing when you are
+	 * running 16 queues per port to support lockless operation.
+	 */
+	int unit = queue_id >> 16;
+	int q = (queue_id >> 4) & 0xf;
+	int core = queue_id & 0xf;
+	return unit * 256 + core * 16 + q;
+}
+
+/**
+ * Lock the supplied queue so nobody else is updating it at the same
+ * time as us.
+ *
+ * @queue_id: Queue ID to lock
+ * @qptr:     Pointer to the queue's global state
+ */
+static inline void __cvmx_cmd_queue_lock(cvmx_cmd_queue_id_t queue_id,
+					 __cvmx_cmd_queue_state_t *qptr)
+{
+	extern __cvmx_cmd_queue_all_state_t
+	    *__cvmx_cmd_queue_state_ptr;
+	int tmp;
+	int my_ticket;
+	prefetch(qptr);
+	asm volatile (
+		".set push\n"
+		".set noreorder\n"
+		"1:\n"
+		/* Atomic add one to ticket_ptr */
+		"ll     %[my_ticket], %[ticket_ptr]\n"
+		/* and store the original value */
+		"li     %[ticket], 1\n"
+		/* in my_ticket */
+		"baddu  %[ticket], %[my_ticket]\n"
+		"sc     %[ticket], %[ticket_ptr]\n"
+		"beqz   %[ticket], 1b\n"
+		" nop\n"
+		/* Load the current now_serving ticket */
+		"lbu    %[ticket], %[now_serving]\n"
+		"2:\n"
+		/* Jump out if now_serving == my_ticket */
+		"beq    %[ticket], %[my_ticket], 4f\n"
+		/* Find out how many tickets are in front of me */
+		" subu   %[ticket], %[my_ticket], %[ticket]\n"
+		/* Use tickets in front of me minus one to delay */
+		"subu  %[ticket], 1\n"
+		/* Delay will be ((tickets in front)-1)*32 loops */
+		"cins   %[ticket], %[ticket], 5, 7\n"
+		"3:\n"
+		/* Loop here until our ticket might be up */
+		"bnez   %[ticket], 3b\n"
+		" subu  %[ticket], 1\n"
+		/* Jump back up to check out ticket again */
+		"b      2b\n"
+		/* Load the current now_serving ticket */
+		" lbu   %[ticket], %[now_serving]\n"
+		"4:\n"
+		".set pop\n" :
+		[ticket_ptr] "=m"(__cvmx_cmd_queue_state_ptr->ticket[__cvmx_cmd_queue_get_index(queue_id)]),
+		[now_serving] "=m"(qptr->now_serving), [ticket] "=r"(tmp),
+		[my_ticket] "=r"(my_ticket)
+	    );
+}
+
+/**
+ * Unlock the queue, flushing all writes.
+ *
+ * @qptr:   Queue to unlock
+ */
+static inline void __cvmx_cmd_queue_unlock(__cvmx_cmd_queue_state_t *qptr)
+{
+	qptr->now_serving++;
+	CVMX_SYNCWS;
+}
+
+/**
+ * Get the queue state structure for the given queue id
+ *
+ * @queue_id: Queue id to get
+ *
+ * Returns Queue structure or NULL on failure
+ */
+static inline __cvmx_cmd_queue_state_t
+    *__cvmx_cmd_queue_get_state(cvmx_cmd_queue_id_t queue_id)
+{
+	extern __cvmx_cmd_queue_all_state_t
+	    *__cvmx_cmd_queue_state_ptr;
+	return &__cvmx_cmd_queue_state_ptr->
+	    state[__cvmx_cmd_queue_get_index(queue_id)];
+}
+
+/**
+ * Write an arbitrary number of command words to a command queue.
+ * This is a generic function; the fixed number of comamnd word
+ * functions yield higher performance.
+ *
+ * @queue_id:  Hardware command queue to write to
+ * @use_locking:
+ *                  Use internal locking to ensure exclusive access for queue
+ *                  updates. If you don't use this locking you must ensure
+ *                  exclusivity some other way. Locking is strongly recommended.
+ * @cmd_count: Number of command words to write
+ * @cmds:      Array of comamnds to write
+ *
+ * Returns CVMX_CMD_QUEUE_SUCCESS or a failure code
+ */
+static inline cvmx_cmd_queue_result_t cvmx_cmd_queue_write(cvmx_cmd_queue_id_t
+							   queue_id,
+							   int use_locking,
+							   int cmd_count,
+							   uint64_t *cmds)
+{
+	__cvmx_cmd_queue_state_t *qptr = __cvmx_cmd_queue_get_state(queue_id);
+
+	/* Make sure nobody else is updating the same queue */
+	if (likely(use_locking))
+		__cvmx_cmd_queue_lock(queue_id, qptr);
+
+	/*
+	 * If a max queue length was specified then make sure we don't
+	 * exceed it. If any part of the command would be below the
+	 * limit we allow it.
+	 */
+	if (CVMX_CMD_QUEUE_ENABLE_MAX_DEPTH && unlikely(qptr->max_depth)) {
+		if (unlikely
+		    (cvmx_cmd_queue_length(queue_id) > (int)qptr->max_depth)) {
+			if (likely(use_locking))
+				__cvmx_cmd_queue_unlock(qptr);
+			return CVMX_CMD_QUEUE_FULL;
+		}
+	}
+
+	/*
+	 * Normally there is plenty of room in the current buffer for
+	 * the command.
+	 */
+	if (likely(qptr->index + cmd_count < qptr->pool_size_m1)) {
+		uint64_t *ptr =
+		    (uint64_t *) cvmx_phys_to_ptr((uint64_t) qptr->
+						  base_ptr_div128 << 7);
+		ptr += qptr->index;
+		qptr->index += cmd_count;
+		while (cmd_count--)
+			*ptr++ = *cmds++;
+	} else {
+		uint64_t *ptr;
+		int count;
+		/*
+		 * We need a new comamnd buffer. Fail if there isn't
+		 * one available.
+		 */
+		uint64_t *new_buffer =
+		    (uint64_t *) cvmx_fpa_alloc(qptr->fpa_pool);
+		if (unlikely(new_buffer == NULL)) {
+			if (likely(use_locking))
+				__cvmx_cmd_queue_unlock(qptr);
+			return CVMX_CMD_QUEUE_NO_MEMORY;
+		}
+		ptr =
+		    (uint64_t *) cvmx_phys_to_ptr((uint64_t) qptr->
+						  base_ptr_div128 << 7);
+		/*
+		 * Figure out how many command words will fit in this
+		 * buffer. One location will be needed for the next
+		 * buffer pointer.
+		 */
+		count = qptr->pool_size_m1 - qptr->index;
+		ptr += qptr->index;
+		cmd_count -= count;
+		while (count--)
+			*ptr++ = *cmds++;
+		*ptr = cvmx_ptr_to_phys(new_buffer);
+		/*
+		 * The current buffer is full and has a link to the
+		 * next buffer. Time to write the rest of the commands
+		 * into the new buffer.
+		 */
+		qptr->base_ptr_div128 = *ptr >> 7;
+		qptr->index = cmd_count;
+		ptr = new_buffer;
+		while (cmd_count--)
+			*ptr++ = *cmds++;
+	}
+
+	/* All updates are complete. Release the lock and return */
+	if (likely(use_locking))
+		__cvmx_cmd_queue_unlock(qptr);
+	return CVMX_CMD_QUEUE_SUCCESS;
+}
+
+/**
+ * Simple function to write two command words to a command
+ * queue.
+ *
+ * @queue_id: Hardware command queue to write to
+ * @use_locking:
+ *                 Use internal locking to ensure exclusive access for queue
+ *                 updates. If you don't use this locking you must ensure
+ *                 exclusivity some other way. Locking is strongly recommended.
+ * @cmd1:     Command
+ * @cmd2:     Command
+ *
+ * Returns CVMX_CMD_QUEUE_SUCCESS or a failure code
+ */
+static inline cvmx_cmd_queue_result_t cvmx_cmd_queue_write2(cvmx_cmd_queue_id_t
+							    queue_id,
+							    int use_locking,
+							    uint64_t cmd1,
+							    uint64_t cmd2)
+{
+	__cvmx_cmd_queue_state_t *qptr = __cvmx_cmd_queue_get_state(queue_id);
+
+	/* Make sure nobody else is updating the same queue */
+	if (likely(use_locking))
+		__cvmx_cmd_queue_lock(queue_id, qptr);
+
+	/*
+	 * If a max queue length was specified then make sure we don't
+	 * exceed it. If any part of the command would be below the
+	 * limit we allow it.
+	 */
+	if (CVMX_CMD_QUEUE_ENABLE_MAX_DEPTH && unlikely(qptr->max_depth)) {
+		if (unlikely
+		    (cvmx_cmd_queue_length(queue_id) > (int)qptr->max_depth)) {
+			if (likely(use_locking))
+				__cvmx_cmd_queue_unlock(qptr);
+			return CVMX_CMD_QUEUE_FULL;
+		}
+	}
+
+	/*
+	 * Normally there is plenty of room in the current buffer for
+	 * the command.
+	 */
+	if (likely(qptr->index + 2 < qptr->pool_size_m1)) {
+		uint64_t *ptr =
+		    (uint64_t *) cvmx_phys_to_ptr((uint64_t) qptr->
+						  base_ptr_div128 << 7);
+		ptr += qptr->index;
+		qptr->index += 2;
+		ptr[0] = cmd1;
+		ptr[1] = cmd2;
+	} else {
+		uint64_t *ptr;
+		/*
+		 * Figure out how many command words will fit in this
+		 * buffer. One location will be needed for the next
+		 * buffer pointer.
+		 */
+		int count = qptr->pool_size_m1 - qptr->index;
+		/*
+		 * We need a new comamnd buffer. Fail if there isn't
+		 * one available.
+		 */
+		uint64_t *new_buffer =
+		    (uint64_t *) cvmx_fpa_alloc(qptr->fpa_pool);
+		if (unlikely(new_buffer == NULL)) {
+			if (likely(use_locking))
+				__cvmx_cmd_queue_unlock(qptr);
+			return CVMX_CMD_QUEUE_NO_MEMORY;
+		}
+		count--;
+		ptr =
+		    (uint64_t *) cvmx_phys_to_ptr((uint64_t) qptr->
+						  base_ptr_div128 << 7);
+		ptr += qptr->index;
+		*ptr++ = cmd1;
+		if (likely(count))
+			*ptr++ = cmd2;
+		*ptr = cvmx_ptr_to_phys(new_buffer);
+		/*
+		 * The current buffer is full and has a link to the
+		 * next buffer. Time to write the rest of the commands
+		 * into the new buffer.
+		 */
+		qptr->base_ptr_div128 = *ptr >> 7;
+		qptr->index = 0;
+		if (unlikely(count == 0)) {
+			qptr->index = 1;
+			new_buffer[0] = cmd2;
+		}
+	}
+
+	/* All updates are complete. Release the lock and return */
+	if (likely(use_locking))
+		__cvmx_cmd_queue_unlock(qptr);
+	return CVMX_CMD_QUEUE_SUCCESS;
+}
+
+/**
+ * Simple function to write three command words to a command
+ * queue.
+ *
+ * @queue_id: Hardware command queue to write to
+ * @use_locking:
+ *                 Use internal locking to ensure exclusive access for queue
+ *                 updates. If you don't use this locking you must ensure
+ *                 exclusivity some other way. Locking is strongly recommended.
+ * @cmd1:     Command
+ * @cmd2:     Command
+ * @cmd3:     Command
+ *
+ * Returns CVMX_CMD_QUEUE_SUCCESS or a failure code
+ */
+static inline cvmx_cmd_queue_result_t cvmx_cmd_queue_write3(cvmx_cmd_queue_id_t
+							    queue_id,
+							    int use_locking,
+							    uint64_t cmd1,
+							    uint64_t cmd2,
+							    uint64_t cmd3)
+{
+	__cvmx_cmd_queue_state_t *qptr = __cvmx_cmd_queue_get_state(queue_id);
+
+	/* Make sure nobody else is updating the same queue */
+	if (likely(use_locking))
+		__cvmx_cmd_queue_lock(queue_id, qptr);
+
+	/*
+	 * If a max queue length was specified then make sure we don't
+	 * exceed it. If any part of the command would be below the
+	 * limit we allow it.
+	 */
+	if (CVMX_CMD_QUEUE_ENABLE_MAX_DEPTH && unlikely(qptr->max_depth)) {
+		if (unlikely
+		    (cvmx_cmd_queue_length(queue_id) > (int)qptr->max_depth)) {
+			if (likely(use_locking))
+				__cvmx_cmd_queue_unlock(qptr);
+			return CVMX_CMD_QUEUE_FULL;
+		}
+	}
+
+	/*
+	 * Normally there is plenty of room in the current buffer for
+	 * the command.
+	 */
+	if (likely(qptr->index + 3 < qptr->pool_size_m1)) {
+		uint64_t *ptr =
+		    (uint64_t *) cvmx_phys_to_ptr((uint64_t) qptr->
+						  base_ptr_div128 << 7);
+		ptr += qptr->index;
+		qptr->index += 3;
+		ptr[0] = cmd1;
+		ptr[1] = cmd2;
+		ptr[2] = cmd3;
+	} else {
+		uint64_t *ptr;
+		/*
+		 * Figure out how many command words will fit in this
+		 * buffer. One location will be needed for the next
+		 * buffer pointer
+		 */
+		int count = qptr->pool_size_m1 - qptr->index;
+		/*
+		 * We need a new comamnd buffer. Fail if there isn't
+		 * one available
+		 */
+		uint64_t *new_buffer =
+		    (uint64_t *) cvmx_fpa_alloc(qptr->fpa_pool);
+		if (unlikely(new_buffer == NULL)) {
+			if (likely(use_locking))
+				__cvmx_cmd_queue_unlock(qptr);
+			return CVMX_CMD_QUEUE_NO_MEMORY;
+		}
+		count--;
+		ptr =
+		    (uint64_t *) cvmx_phys_to_ptr((uint64_t) qptr->
+						  base_ptr_div128 << 7);
+		ptr += qptr->index;
+		*ptr++ = cmd1;
+		if (count) {
+			*ptr++ = cmd2;
+			if (count > 1)
+				*ptr++ = cmd3;
+		}
+		*ptr = cvmx_ptr_to_phys(new_buffer);
+		/*
+		 * The current buffer is full and has a link to the
+		 * next buffer. Time to write the rest of the commands
+		 * into the new buffer.
+		 */
+		qptr->base_ptr_div128 = *ptr >> 7;
+		qptr->index = 0;
+		ptr = new_buffer;
+		if (count == 0) {
+			*ptr++ = cmd2;
+			qptr->index++;
+		}
+		if (count < 2) {
+			*ptr++ = cmd3;
+			qptr->index++;
+		}
+	}
+
+	/* All updates are complete. Release the lock and return */
+	if (likely(use_locking))
+		__cvmx_cmd_queue_unlock(qptr);
+	return CVMX_CMD_QUEUE_SUCCESS;
+}
+
+#endif /* __CVMX_CMD_QUEUE_H__ */
diff --git a/drivers/staging/octeon/cvmx-config.h b/drivers/staging/octeon/cvmx-config.h
new file mode 100644
index 0000000..078a520
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-config.h
@@ -0,0 +1,169 @@
+#ifndef __CVMX_CONFIG_H__
+#define __CVMX_CONFIG_H__
+
+/************************* Config Specific Defines ************************/
+#define CVMX_LLM_NUM_PORTS 1
+#define CVMX_NULL_POINTER_PROTECT 1
+#define CVMX_ENABLE_DEBUG_PRINTS 1
+/* PKO queues per port for interface 0 (ports 0-15) */
+#define CVMX_PKO_QUEUES_PER_PORT_INTERFACE0 1
+/* PKO queues per port for interface 1 (ports 16-31) */
+#define CVMX_PKO_QUEUES_PER_PORT_INTERFACE1 1
+/* Limit on the number of PKO ports enabled for interface 0 */
+#define CVMX_PKO_MAX_PORTS_INTERFACE0 CVMX_HELPER_PKO_MAX_PORTS_INTERFACE0
+/* Limit on the number of PKO ports enabled for interface 1 */
+#define CVMX_PKO_MAX_PORTS_INTERFACE1 CVMX_HELPER_PKO_MAX_PORTS_INTERFACE1
+/* PKO queues per port for PCI (ports 32-35) */
+#define CVMX_PKO_QUEUES_PER_PORT_PCI 1
+/* PKO queues per port for Loop devices (ports 36-39) */
+#define CVMX_PKO_QUEUES_PER_PORT_LOOP 1
+
+/************************* FPA allocation *********************************/
+/* Pool sizes in bytes, must be multiple of a cache line */
+#define CVMX_FPA_POOL_0_SIZE (16 * CVMX_CACHE_LINE_SIZE)
+#define CVMX_FPA_POOL_1_SIZE (1 * CVMX_CACHE_LINE_SIZE)
+#define CVMX_FPA_POOL_2_SIZE (8 * CVMX_CACHE_LINE_SIZE)
+#define CVMX_FPA_POOL_3_SIZE (0 * CVMX_CACHE_LINE_SIZE)
+#define CVMX_FPA_POOL_4_SIZE (0 * CVMX_CACHE_LINE_SIZE)
+#define CVMX_FPA_POOL_5_SIZE (0 * CVMX_CACHE_LINE_SIZE)
+#define CVMX_FPA_POOL_6_SIZE (0 * CVMX_CACHE_LINE_SIZE)
+#define CVMX_FPA_POOL_7_SIZE (0 * CVMX_CACHE_LINE_SIZE)
+
+/* Pools in use */
+/* Packet buffers */
+#define CVMX_FPA_PACKET_POOL                (0)
+#define CVMX_FPA_PACKET_POOL_SIZE           CVMX_FPA_POOL_0_SIZE
+/* Work queue entrys */
+#define CVMX_FPA_WQE_POOL                   (1)
+#define CVMX_FPA_WQE_POOL_SIZE              CVMX_FPA_POOL_1_SIZE
+/* PKO queue command buffers */
+#define CVMX_FPA_OUTPUT_BUFFER_POOL         (2)
+#define CVMX_FPA_OUTPUT_BUFFER_POOL_SIZE    CVMX_FPA_POOL_2_SIZE
+
+/*************************  FAU allocation ********************************/
+/* The fetch and add registers are allocated here.  They are arranged
+ * in order of descending size so that all alignment constraints are
+ * automatically met.  The enums are linked so that the following enum
+ * continues allocating where the previous one left off, so the
+ * numbering within each enum always starts with zero.  The macros
+ * take care of the address increment size, so the values entered
+ * always increase by 1.  FAU registers are accessed with byte
+ * addresses.
+ */
+
+#define CVMX_FAU_REG_64_ADDR(x) ((x << 3) + CVMX_FAU_REG_64_START)
+typedef enum {
+	CVMX_FAU_REG_64_START	= 0,
+	CVMX_FAU_REG_64_END	= CVMX_FAU_REG_64_ADDR(0),
+} cvmx_fau_reg_64_t;
+
+#define CVMX_FAU_REG_32_ADDR(x) ((x << 2) + CVMX_FAU_REG_32_START)
+typedef enum {
+	CVMX_FAU_REG_32_START	= CVMX_FAU_REG_64_END,
+	CVMX_FAU_REG_32_END	= CVMX_FAU_REG_32_ADDR(0),
+} cvmx_fau_reg_32_t;
+
+#define CVMX_FAU_REG_16_ADDR(x) ((x << 1) + CVMX_FAU_REG_16_START)
+typedef enum {
+	CVMX_FAU_REG_16_START	= CVMX_FAU_REG_32_END,
+	CVMX_FAU_REG_16_END	= CVMX_FAU_REG_16_ADDR(0),
+} cvmx_fau_reg_16_t;
+
+#define CVMX_FAU_REG_8_ADDR(x) ((x) + CVMX_FAU_REG_8_START)
+typedef enum {
+	CVMX_FAU_REG_8_START	= CVMX_FAU_REG_16_END,
+	CVMX_FAU_REG_8_END	= CVMX_FAU_REG_8_ADDR(0),
+} cvmx_fau_reg_8_t;
+
+/*
+ * The name CVMX_FAU_REG_AVAIL_BASE is provided to indicate the first
+ * available FAU address that is not allocated in cvmx-config.h. This
+ * is 64 bit aligned.
+ */
+#define CVMX_FAU_REG_AVAIL_BASE ((CVMX_FAU_REG_8_END + 0x7) & (~0x7ULL))
+#define CVMX_FAU_REG_END (2048)
+
+/********************** scratch memory allocation *************************/
+/* Scratchpad memory allocation.  Note that these are byte memory
+ * addresses.  Some uses of scratchpad (IOBDMA for example) require
+ * the use of 8-byte aligned addresses, so proper alignment needs to
+ * be taken into account.
+ */
+/* Generic scratch iobdma area */
+#define CVMX_SCR_SCRATCH               (0)
+/* First location available after cvmx-config.h allocated region. */
+#define CVMX_SCR_REG_AVAIL_BASE        (8)
+
+/*
+ * CVMX_HELPER_FIRST_MBUFF_SKIP is the number of bytes to reserve
+ * before the beginning of the packet. If necessary, override the
+ * default here.  See the IPD section of the hardware manual for MBUFF
+ * SKIP details.
+ */
+#define CVMX_HELPER_FIRST_MBUFF_SKIP 184
+
+/*
+ * CVMX_HELPER_NOT_FIRST_MBUFF_SKIP is the number of bytes to reserve
+ * in each chained packet element. If necessary, override the default
+ * here.
+ */
+#define CVMX_HELPER_NOT_FIRST_MBUFF_SKIP 0
+
+/*
+ * CVMX_HELPER_ENABLE_BACK_PRESSURE controls whether back pressure is
+ * enabled for all input ports. This controls if IPD sends
+ * backpressure to all ports if Octeon's FPA pools don't have enough
+ * packet or work queue entries. Even when this is off, it is still
+ * possible to get backpressure from individual hardware ports. When
+ * configuring backpressure, also check
+ * CVMX_HELPER_DISABLE_*_BACKPRESSURE below. If necessary, override
+ * the default here.
+ */
+#define CVMX_HELPER_ENABLE_BACK_PRESSURE 1
+
+/*
+ * CVMX_HELPER_ENABLE_IPD controls if the IPD is enabled in the helper
+ * function. Once it is enabled the hardware starts accepting
+ * packets. You might want to skip the IPD enable if configuration
+ * changes are need from the default helper setup. If necessary,
+ * override the default here.
+ */
+#define CVMX_HELPER_ENABLE_IPD 0
+
+/*
+ * CVMX_HELPER_INPUT_TAG_TYPE selects the type of tag that the IPD assigns
+ * to incoming packets.
+ */
+#define CVMX_HELPER_INPUT_TAG_TYPE CVMX_POW_TAG_TYPE_ORDERED
+
+#define CVMX_ENABLE_PARAMETER_CHECKING 0
+
+/*
+ * The following select which fields are used by the PIP to generate
+ * the tag on INPUT
+ * 0: don't include
+ * 1: include
+ */
+#define CVMX_HELPER_INPUT_TAG_IPV6_SRC_IP	0
+#define CVMX_HELPER_INPUT_TAG_IPV6_DST_IP   	0
+#define CVMX_HELPER_INPUT_TAG_IPV6_SRC_PORT 	0
+#define CVMX_HELPER_INPUT_TAG_IPV6_DST_PORT 	0
+#define CVMX_HELPER_INPUT_TAG_IPV6_NEXT_HEADER 	0
+#define CVMX_HELPER_INPUT_TAG_IPV4_SRC_IP	0
+#define CVMX_HELPER_INPUT_TAG_IPV4_DST_IP   	0
+#define CVMX_HELPER_INPUT_TAG_IPV4_SRC_PORT 	0
+#define CVMX_HELPER_INPUT_TAG_IPV4_DST_PORT 	0
+#define CVMX_HELPER_INPUT_TAG_IPV4_PROTOCOL	0
+#define CVMX_HELPER_INPUT_TAG_INPUT_PORT	1
+
+/* Select skip mode for input ports */
+#define CVMX_HELPER_INPUT_PORT_SKIP_MODE	CVMX_PIP_PORT_CFG_MODE_SKIPL2
+
+/*
+ * Force backpressure to be disabled.  This overrides all other
+ * backpressure configuration.
+ */
+#define CVMX_HELPER_DISABLE_RGMII_BACKPRESSURE 0
+
+#endif /* __CVMX_CONFIG_H__ */
+
diff --git a/drivers/staging/octeon/cvmx-dbg-defs.h b/drivers/staging/octeon/cvmx-dbg-defs.h
new file mode 100644
index 0000000..abbf42d
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-dbg-defs.h
@@ -0,0 +1,72 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_DBG_DEFS_H__
+#define __CVMX_DBG_DEFS_H__
+
+#define CVMX_DBG_DATA \
+	 CVMX_ADD_IO_SEG(0x00011F00000001E8ull)
+
+union cvmx_dbg_data {
+	uint64_t u64;
+	struct cvmx_dbg_data_s {
+		uint64_t reserved_23_63:41;
+		uint64_t c_mul:5;
+		uint64_t dsel_ext:1;
+		uint64_t data:17;
+	} s;
+	struct cvmx_dbg_data_cn30xx {
+		uint64_t reserved_31_63:33;
+		uint64_t pll_mul:3;
+		uint64_t reserved_23_27:5;
+		uint64_t c_mul:5;
+		uint64_t dsel_ext:1;
+		uint64_t data:17;
+	} cn30xx;
+	struct cvmx_dbg_data_cn30xx cn31xx;
+	struct cvmx_dbg_data_cn38xx {
+		uint64_t reserved_29_63:35;
+		uint64_t d_mul:4;
+		uint64_t dclk_mul2:1;
+		uint64_t cclk_div2:1;
+		uint64_t c_mul:5;
+		uint64_t dsel_ext:1;
+		uint64_t data:17;
+	} cn38xx;
+	struct cvmx_dbg_data_cn38xx cn38xxp2;
+	struct cvmx_dbg_data_cn30xx cn50xx;
+	struct cvmx_dbg_data_cn58xx {
+		uint64_t reserved_29_63:35;
+		uint64_t rem:6;
+		uint64_t c_mul:5;
+		uint64_t dsel_ext:1;
+		uint64_t data:17;
+	} cn58xx;
+	struct cvmx_dbg_data_cn58xx cn58xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-fau.h b/drivers/staging/octeon/cvmx-fau.h
new file mode 100644
index 0000000..29bdce6
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-fau.h
@@ -0,0 +1,597 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Interface to the hardware Fetch and Add Unit.
+ */
+
+#ifndef __CVMX_FAU_H__
+#define __CVMX_FAU_H__
+
+/*
+ * Octeon Fetch and Add Unit (FAU)
+ */
+
+#define CVMX_FAU_LOAD_IO_ADDRESS    cvmx_build_io_address(0x1e, 0)
+#define CVMX_FAU_BITS_SCRADDR       63, 56
+#define CVMX_FAU_BITS_LEN           55, 48
+#define CVMX_FAU_BITS_INEVAL        35, 14
+#define CVMX_FAU_BITS_TAGWAIT       13, 13
+#define CVMX_FAU_BITS_NOADD         13, 13
+#define CVMX_FAU_BITS_SIZE          12, 11
+#define CVMX_FAU_BITS_REGISTER      10, 0
+
+typedef enum {
+	CVMX_FAU_OP_SIZE_8 = 0,
+	CVMX_FAU_OP_SIZE_16 = 1,
+	CVMX_FAU_OP_SIZE_32 = 2,
+	CVMX_FAU_OP_SIZE_64 = 3
+} cvmx_fau_op_size_t;
+
+/**
+ * Tagwait return definition. If a timeout occurs, the error
+ * bit will be set. Otherwise the value of the register before
+ * the update will be returned.
+ */
+typedef struct {
+	uint64_t error:1;
+	int64_t value:63;
+} cvmx_fau_tagwait64_t;
+
+/**
+ * Tagwait return definition. If a timeout occurs, the error
+ * bit will be set. Otherwise the value of the register before
+ * the update will be returned.
+ */
+typedef struct {
+	uint64_t error:1;
+	int32_t value:31;
+} cvmx_fau_tagwait32_t;
+
+/**
+ * Tagwait return definition. If a timeout occurs, the error
+ * bit will be set. Otherwise the value of the register before
+ * the update will be returned.
+ */
+typedef struct {
+	uint64_t error:1;
+	int16_t value:15;
+} cvmx_fau_tagwait16_t;
+
+/**
+ * Tagwait return definition. If a timeout occurs, the error
+ * bit will be set. Otherwise the value of the register before
+ * the update will be returned.
+ */
+typedef struct {
+	uint64_t error:1;
+	int8_t value:7;
+} cvmx_fau_tagwait8_t;
+
+/**
+ * Asynchronous tagwait return definition. If a timeout occurs,
+ * the error bit will be set. Otherwise the value of the
+ * register before the update will be returned.
+ */
+typedef union {
+	uint64_t u64;
+	struct {
+		uint64_t invalid:1;
+		uint64_t data:63;	/* unpredictable if invalid is set */
+	} s;
+} cvmx_fau_async_tagwait_result_t;
+
+/**
+ * Builds a store I/O address for writing to the FAU
+ *
+ * @noadd:  0 = Store value is atomically added to the current value
+ *               1 = Store value is atomically written over the current value
+ * @reg:    FAU atomic register to access. 0 <= reg < 2048.
+ *               - Step by 2 for 16 bit access.
+ *               - Step by 4 for 32 bit access.
+ *               - Step by 8 for 64 bit access.
+ * Returns Address to store for atomic update
+ */
+static inline uint64_t __cvmx_fau_store_address(uint64_t noadd, uint64_t reg)
+{
+	return CVMX_ADD_IO_SEG(CVMX_FAU_LOAD_IO_ADDRESS) |
+	       cvmx_build_bits(CVMX_FAU_BITS_NOADD, noadd) |
+	       cvmx_build_bits(CVMX_FAU_BITS_REGISTER, reg);
+}
+
+/**
+ * Builds a I/O address for accessing the FAU
+ *
+ * @tagwait: Should the atomic add wait for the current tag switch
+ *                operation to complete.
+ *                - 0 = Don't wait
+ *                - 1 = Wait for tag switch to complete
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 2 for 16 bit access.
+ *                - Step by 4 for 32 bit access.
+ *                - Step by 8 for 64 bit access.
+ * @value:   Signed value to add.
+ *                Note: When performing 32 and 64 bit access, only the low
+ *                22 bits are available.
+ * Returns Address to read from for atomic update
+ */
+static inline uint64_t __cvmx_fau_atomic_address(uint64_t tagwait, uint64_t reg,
+						 int64_t value)
+{
+	return CVMX_ADD_IO_SEG(CVMX_FAU_LOAD_IO_ADDRESS) |
+	       cvmx_build_bits(CVMX_FAU_BITS_INEVAL, value) |
+	       cvmx_build_bits(CVMX_FAU_BITS_TAGWAIT, tagwait) |
+	       cvmx_build_bits(CVMX_FAU_BITS_REGISTER, reg);
+}
+
+/**
+ * Perform an atomic 64 bit add
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 8 for 64 bit access.
+ * @value:   Signed value to add.
+ *                Note: Only the low 22 bits are available.
+ * Returns Value of the register before the update
+ */
+static inline int64_t cvmx_fau_fetch_and_add64(cvmx_fau_reg_64_t reg,
+					       int64_t value)
+{
+	return cvmx_read64_int64(__cvmx_fau_atomic_address(0, reg, value));
+}
+
+/**
+ * Perform an atomic 32 bit add
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 4 for 32 bit access.
+ * @value:   Signed value to add.
+ *                Note: Only the low 22 bits are available.
+ * Returns Value of the register before the update
+ */
+static inline int32_t cvmx_fau_fetch_and_add32(cvmx_fau_reg_32_t reg,
+					       int32_t value)
+{
+	return cvmx_read64_int32(__cvmx_fau_atomic_address(0, reg, value));
+}
+
+/**
+ * Perform an atomic 16 bit add
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 2 for 16 bit access.
+ * @value:   Signed value to add.
+ * Returns Value of the register before the update
+ */
+static inline int16_t cvmx_fau_fetch_and_add16(cvmx_fau_reg_16_t reg,
+					       int16_t value)
+{
+	return cvmx_read64_int16(__cvmx_fau_atomic_address(0, reg, value));
+}
+
+/**
+ * Perform an atomic 8 bit add
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ * @value:   Signed value to add.
+ * Returns Value of the register before the update
+ */
+static inline int8_t cvmx_fau_fetch_and_add8(cvmx_fau_reg_8_t reg, int8_t value)
+{
+	return cvmx_read64_int8(__cvmx_fau_atomic_address(0, reg, value));
+}
+
+/**
+ * Perform an atomic 64 bit add after the current tag switch
+ * completes
+ *
+ * @reg:    FAU atomic register to access. 0 <= reg < 2048.
+ *               - Step by 8 for 64 bit access.
+ * @value:  Signed value to add.
+ *               Note: Only the low 22 bits are available.
+ * Returns If a timeout occurs, the error bit will be set. Otherwise
+ *         the value of the register before the update will be
+ *         returned
+ */
+static inline cvmx_fau_tagwait64_t
+cvmx_fau_tagwait_fetch_and_add64(cvmx_fau_reg_64_t reg, int64_t value)
+{
+	union {
+		uint64_t i64;
+		cvmx_fau_tagwait64_t t;
+	} result;
+	result.i64 =
+	    cvmx_read64_int64(__cvmx_fau_atomic_address(1, reg, value));
+	return result.t;
+}
+
+/**
+ * Perform an atomic 32 bit add after the current tag switch
+ * completes
+ *
+ * @reg:    FAU atomic register to access. 0 <= reg < 2048.
+ *               - Step by 4 for 32 bit access.
+ * @value:  Signed value to add.
+ *               Note: Only the low 22 bits are available.
+ * Returns If a timeout occurs, the error bit will be set. Otherwise
+ *         the value of the register before the update will be
+ *         returned
+ */
+static inline cvmx_fau_tagwait32_t
+cvmx_fau_tagwait_fetch_and_add32(cvmx_fau_reg_32_t reg, int32_t value)
+{
+	union {
+		uint64_t i32;
+		cvmx_fau_tagwait32_t t;
+	} result;
+	result.i32 =
+	    cvmx_read64_int32(__cvmx_fau_atomic_address(1, reg, value));
+	return result.t;
+}
+
+/**
+ * Perform an atomic 16 bit add after the current tag switch
+ * completes
+ *
+ * @reg:    FAU atomic register to access. 0 <= reg < 2048.
+ *               - Step by 2 for 16 bit access.
+ * @value:  Signed value to add.
+ * Returns If a timeout occurs, the error bit will be set. Otherwise
+ *         the value of the register before the update will be
+ *         returned
+ */
+static inline cvmx_fau_tagwait16_t
+cvmx_fau_tagwait_fetch_and_add16(cvmx_fau_reg_16_t reg, int16_t value)
+{
+	union {
+		uint64_t i16;
+		cvmx_fau_tagwait16_t t;
+	} result;
+	result.i16 =
+	    cvmx_read64_int16(__cvmx_fau_atomic_address(1, reg, value));
+	return result.t;
+}
+
+/**
+ * Perform an atomic 8 bit add after the current tag switch
+ * completes
+ *
+ * @reg:    FAU atomic register to access. 0 <= reg < 2048.
+ * @value:  Signed value to add.
+ * Returns If a timeout occurs, the error bit will be set. Otherwise
+ *         the value of the register before the update will be
+ *         returned
+ */
+static inline cvmx_fau_tagwait8_t
+cvmx_fau_tagwait_fetch_and_add8(cvmx_fau_reg_8_t reg, int8_t value)
+{
+	union {
+		uint64_t i8;
+		cvmx_fau_tagwait8_t t;
+	} result;
+	result.i8 = cvmx_read64_int8(__cvmx_fau_atomic_address(1, reg, value));
+	return result.t;
+}
+
+/**
+ * Builds I/O data for async operations
+ *
+ * @scraddr: Scratch pad byte addres to write to.  Must be 8 byte aligned
+ * @value:   Signed value to add.
+ *                Note: When performing 32 and 64 bit access, only the low
+ *                22 bits are available.
+ * @tagwait: Should the atomic add wait for the current tag switch
+ *                operation to complete.
+ *                - 0 = Don't wait
+ *                - 1 = Wait for tag switch to complete
+ * @size:    The size of the operation:
+ *                - CVMX_FAU_OP_SIZE_8  (0) = 8 bits
+ *                - CVMX_FAU_OP_SIZE_16 (1) = 16 bits
+ *                - CVMX_FAU_OP_SIZE_32 (2) = 32 bits
+ *                - CVMX_FAU_OP_SIZE_64 (3) = 64 bits
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 2 for 16 bit access.
+ *                - Step by 4 for 32 bit access.
+ *                - Step by 8 for 64 bit access.
+ * Returns Data to write using cvmx_send_single
+ */
+static inline uint64_t __cvmx_fau_iobdma_data(uint64_t scraddr, int64_t value,
+					      uint64_t tagwait,
+					      cvmx_fau_op_size_t size,
+					      uint64_t reg)
+{
+	return CVMX_FAU_LOAD_IO_ADDRESS |
+	       cvmx_build_bits(CVMX_FAU_BITS_SCRADDR, scraddr >> 3) |
+	       cvmx_build_bits(CVMX_FAU_BITS_LEN, 1) |
+	       cvmx_build_bits(CVMX_FAU_BITS_INEVAL, value) |
+	       cvmx_build_bits(CVMX_FAU_BITS_TAGWAIT, tagwait) |
+	       cvmx_build_bits(CVMX_FAU_BITS_SIZE, size) |
+	       cvmx_build_bits(CVMX_FAU_BITS_REGISTER, reg);
+}
+
+/**
+ * Perform an async atomic 64 bit add. The old value is
+ * placed in the scratch memory at byte address scraddr.
+ *
+ * @scraddr: Scratch memory byte address to put response in.
+ *                Must be 8 byte aligned.
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 8 for 64 bit access.
+ * @value:   Signed value to add.
+ *                Note: Only the low 22 bits are available.
+ * Returns Placed in the scratch pad register
+ */
+static inline void cvmx_fau_async_fetch_and_add64(uint64_t scraddr,
+						  cvmx_fau_reg_64_t reg,
+						  int64_t value)
+{
+	cvmx_send_single(__cvmx_fau_iobdma_data
+			 (scraddr, value, 0, CVMX_FAU_OP_SIZE_64, reg));
+}
+
+/**
+ * Perform an async atomic 32 bit add. The old value is
+ * placed in the scratch memory at byte address scraddr.
+ *
+ * @scraddr: Scratch memory byte address to put response in.
+ *                Must be 8 byte aligned.
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 4 for 32 bit access.
+ * @value:   Signed value to add.
+ *                Note: Only the low 22 bits are available.
+ * Returns Placed in the scratch pad register
+ */
+static inline void cvmx_fau_async_fetch_and_add32(uint64_t scraddr,
+						  cvmx_fau_reg_32_t reg,
+						  int32_t value)
+{
+	cvmx_send_single(__cvmx_fau_iobdma_data
+			 (scraddr, value, 0, CVMX_FAU_OP_SIZE_32, reg));
+}
+
+/**
+ * Perform an async atomic 16 bit add. The old value is
+ * placed in the scratch memory at byte address scraddr.
+ *
+ * @scraddr: Scratch memory byte address to put response in.
+ *                Must be 8 byte aligned.
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 2 for 16 bit access.
+ * @value:   Signed value to add.
+ * Returns Placed in the scratch pad register
+ */
+static inline void cvmx_fau_async_fetch_and_add16(uint64_t scraddr,
+						  cvmx_fau_reg_16_t reg,
+						  int16_t value)
+{
+	cvmx_send_single(__cvmx_fau_iobdma_data
+			 (scraddr, value, 0, CVMX_FAU_OP_SIZE_16, reg));
+}
+
+/**
+ * Perform an async atomic 8 bit add. The old value is
+ * placed in the scratch memory at byte address scraddr.
+ *
+ * @scraddr: Scratch memory byte address to put response in.
+ *                Must be 8 byte aligned.
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ * @value:   Signed value to add.
+ * Returns Placed in the scratch pad register
+ */
+static inline void cvmx_fau_async_fetch_and_add8(uint64_t scraddr,
+						 cvmx_fau_reg_8_t reg,
+						 int8_t value)
+{
+	cvmx_send_single(__cvmx_fau_iobdma_data
+			 (scraddr, value, 0, CVMX_FAU_OP_SIZE_8, reg));
+}
+
+/**
+ * Perform an async atomic 64 bit add after the current tag
+ * switch completes.
+ *
+ * @scraddr: Scratch memory byte address to put response in.  Must be
+ *           8 byte aligned.  If a timeout occurs, the error bit (63)
+ *           will be set. Otherwise the value of the register before
+ *           the update will be returned
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 8 for 64 bit access.
+ * @value:   Signed value to add.
+ *                Note: Only the low 22 bits are available.
+ * Returns Placed in the scratch pad register
+ */
+static inline void cvmx_fau_async_tagwait_fetch_and_add64(uint64_t scraddr,
+							  cvmx_fau_reg_64_t reg,
+							  int64_t value)
+{
+	cvmx_send_single(__cvmx_fau_iobdma_data
+			 (scraddr, value, 1, CVMX_FAU_OP_SIZE_64, reg));
+}
+
+/**
+ * Perform an async atomic 32 bit add after the current tag
+ * switch completes.
+ *
+ * @scraddr: Scratch memory byte address to put response in.  Must be
+ *           8 byte aligned.  If a timeout occurs, the error bit (63)
+ *           will be set. Otherwise the value of the register before
+ *           the update will be returned
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 4 for 32 bit access.
+ * @value:   Signed value to add.
+ *                Note: Only the low 22 bits are available.
+ * Returns Placed in the scratch pad register
+ */
+static inline void cvmx_fau_async_tagwait_fetch_and_add32(uint64_t scraddr,
+							  cvmx_fau_reg_32_t reg,
+							  int32_t value)
+{
+	cvmx_send_single(__cvmx_fau_iobdma_data
+			 (scraddr, value, 1, CVMX_FAU_OP_SIZE_32, reg));
+}
+
+/**
+ * Perform an async atomic 16 bit add after the current tag
+ * switch completes.
+ *
+ * @scraddr: Scratch memory byte address to put response in.  Must be
+ *           8 byte aligned.  If a timeout occurs, the error bit (63)
+ *           will be set. Otherwise the value of the register before
+ *           the update will be returned
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 2 for 16 bit access.
+ * @value:   Signed value to add.
+ *
+ * Returns Placed in the scratch pad register
+ */
+static inline void cvmx_fau_async_tagwait_fetch_and_add16(uint64_t scraddr,
+							  cvmx_fau_reg_16_t reg,
+							  int16_t value)
+{
+	cvmx_send_single(__cvmx_fau_iobdma_data
+			 (scraddr, value, 1, CVMX_FAU_OP_SIZE_16, reg));
+}
+
+/**
+ * Perform an async atomic 8 bit add after the current tag
+ * switch completes.
+ *
+ * @scraddr: Scratch memory byte address to put response in.  Must be
+ *           8 byte aligned.  If a timeout occurs, the error bit (63)
+ *           will be set. Otherwise the value of the register before
+ *           the update will be returned
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ * @value:   Signed value to add.
+ *
+ * Returns Placed in the scratch pad register
+ */
+static inline void cvmx_fau_async_tagwait_fetch_and_add8(uint64_t scraddr,
+							 cvmx_fau_reg_8_t reg,
+							 int8_t value)
+{
+	cvmx_send_single(__cvmx_fau_iobdma_data
+			 (scraddr, value, 1, CVMX_FAU_OP_SIZE_8, reg));
+}
+
+/**
+ * Perform an atomic 64 bit add
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 8 for 64 bit access.
+ * @value:   Signed value to add.
+ */
+static inline void cvmx_fau_atomic_add64(cvmx_fau_reg_64_t reg, int64_t value)
+{
+	cvmx_write64_int64(__cvmx_fau_store_address(0, reg), value);
+}
+
+/**
+ * Perform an atomic 32 bit add
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 4 for 32 bit access.
+ * @value:   Signed value to add.
+ */
+static inline void cvmx_fau_atomic_add32(cvmx_fau_reg_32_t reg, int32_t value)
+{
+	cvmx_write64_int32(__cvmx_fau_store_address(0, reg), value);
+}
+
+/**
+ * Perform an atomic 16 bit add
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 2 for 16 bit access.
+ * @value:   Signed value to add.
+ */
+static inline void cvmx_fau_atomic_add16(cvmx_fau_reg_16_t reg, int16_t value)
+{
+	cvmx_write64_int16(__cvmx_fau_store_address(0, reg), value);
+}
+
+/**
+ * Perform an atomic 8 bit add
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ * @value:   Signed value to add.
+ */
+static inline void cvmx_fau_atomic_add8(cvmx_fau_reg_8_t reg, int8_t value)
+{
+	cvmx_write64_int8(__cvmx_fau_store_address(0, reg), value);
+}
+
+/**
+ * Perform an atomic 64 bit write
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 8 for 64 bit access.
+ * @value:   Signed value to write.
+ */
+static inline void cvmx_fau_atomic_write64(cvmx_fau_reg_64_t reg, int64_t value)
+{
+	cvmx_write64_int64(__cvmx_fau_store_address(1, reg), value);
+}
+
+/**
+ * Perform an atomic 32 bit write
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 4 for 32 bit access.
+ * @value:   Signed value to write.
+ */
+static inline void cvmx_fau_atomic_write32(cvmx_fau_reg_32_t reg, int32_t value)
+{
+	cvmx_write64_int32(__cvmx_fau_store_address(1, reg), value);
+}
+
+/**
+ * Perform an atomic 16 bit write
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ *                - Step by 2 for 16 bit access.
+ * @value:   Signed value to write.
+ */
+static inline void cvmx_fau_atomic_write16(cvmx_fau_reg_16_t reg, int16_t value)
+{
+	cvmx_write64_int16(__cvmx_fau_store_address(1, reg), value);
+}
+
+/**
+ * Perform an atomic 8 bit write
+ *
+ * @reg:     FAU atomic register to access. 0 <= reg < 2048.
+ * @value:   Signed value to write.
+ */
+static inline void cvmx_fau_atomic_write8(cvmx_fau_reg_8_t reg, int8_t value)
+{
+	cvmx_write64_int8(__cvmx_fau_store_address(1, reg), value);
+}
+
+#endif /* __CVMX_FAU_H__ */
diff --git a/drivers/staging/octeon/cvmx-fpa-defs.h b/drivers/staging/octeon/cvmx-fpa-defs.h
new file mode 100644
index 0000000..bf5546b
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-fpa-defs.h
@@ -0,0 +1,403 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_FPA_DEFS_H__
+#define __CVMX_FPA_DEFS_H__
+
+#define CVMX_FPA_BIST_STATUS \
+	 CVMX_ADD_IO_SEG(0x00011800280000E8ull)
+#define CVMX_FPA_CTL_STATUS \
+	 CVMX_ADD_IO_SEG(0x0001180028000050ull)
+#define CVMX_FPA_FPF0_MARKS \
+	 CVMX_ADD_IO_SEG(0x0001180028000000ull)
+#define CVMX_FPA_FPF0_SIZE \
+	 CVMX_ADD_IO_SEG(0x0001180028000058ull)
+#define CVMX_FPA_FPF1_MARKS \
+	 CVMX_ADD_IO_SEG(0x0001180028000008ull)
+#define CVMX_FPA_FPF2_MARKS \
+	 CVMX_ADD_IO_SEG(0x0001180028000010ull)
+#define CVMX_FPA_FPF3_MARKS \
+	 CVMX_ADD_IO_SEG(0x0001180028000018ull)
+#define CVMX_FPA_FPF4_MARKS \
+	 CVMX_ADD_IO_SEG(0x0001180028000020ull)
+#define CVMX_FPA_FPF5_MARKS \
+	 CVMX_ADD_IO_SEG(0x0001180028000028ull)
+#define CVMX_FPA_FPF6_MARKS \
+	 CVMX_ADD_IO_SEG(0x0001180028000030ull)
+#define CVMX_FPA_FPF7_MARKS \
+	 CVMX_ADD_IO_SEG(0x0001180028000038ull)
+#define CVMX_FPA_FPFX_MARKS(offset) \
+	 CVMX_ADD_IO_SEG(0x0001180028000008ull + (((offset) & 7) * 8) - 8 * 1)
+#define CVMX_FPA_FPFX_SIZE(offset) \
+	 CVMX_ADD_IO_SEG(0x0001180028000060ull + (((offset) & 7) * 8) - 8 * 1)
+#define CVMX_FPA_INT_ENB \
+	 CVMX_ADD_IO_SEG(0x0001180028000048ull)
+#define CVMX_FPA_INT_SUM \
+	 CVMX_ADD_IO_SEG(0x0001180028000040ull)
+#define CVMX_FPA_QUE0_PAGE_INDEX \
+	 CVMX_ADD_IO_SEG(0x00011800280000F0ull)
+#define CVMX_FPA_QUE1_PAGE_INDEX \
+	 CVMX_ADD_IO_SEG(0x00011800280000F8ull)
+#define CVMX_FPA_QUE2_PAGE_INDEX \
+	 CVMX_ADD_IO_SEG(0x0001180028000100ull)
+#define CVMX_FPA_QUE3_PAGE_INDEX \
+	 CVMX_ADD_IO_SEG(0x0001180028000108ull)
+#define CVMX_FPA_QUE4_PAGE_INDEX \
+	 CVMX_ADD_IO_SEG(0x0001180028000110ull)
+#define CVMX_FPA_QUE5_PAGE_INDEX \
+	 CVMX_ADD_IO_SEG(0x0001180028000118ull)
+#define CVMX_FPA_QUE6_PAGE_INDEX \
+	 CVMX_ADD_IO_SEG(0x0001180028000120ull)
+#define CVMX_FPA_QUE7_PAGE_INDEX \
+	 CVMX_ADD_IO_SEG(0x0001180028000128ull)
+#define CVMX_FPA_QUEX_AVAILABLE(offset) \
+	 CVMX_ADD_IO_SEG(0x0001180028000098ull + (((offset) & 7) * 8))
+#define CVMX_FPA_QUEX_PAGE_INDEX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800280000F0ull + (((offset) & 7) * 8))
+#define CVMX_FPA_QUE_ACT \
+	 CVMX_ADD_IO_SEG(0x0001180028000138ull)
+#define CVMX_FPA_QUE_EXP \
+	 CVMX_ADD_IO_SEG(0x0001180028000130ull)
+#define CVMX_FPA_WART_CTL \
+	 CVMX_ADD_IO_SEG(0x00011800280000D8ull)
+#define CVMX_FPA_WART_STATUS \
+	 CVMX_ADD_IO_SEG(0x00011800280000E0ull)
+
+union cvmx_fpa_bist_status {
+	uint64_t u64;
+	struct cvmx_fpa_bist_status_s {
+		uint64_t reserved_5_63:59;
+		uint64_t frd:1;
+		uint64_t fpf0:1;
+		uint64_t fpf1:1;
+		uint64_t ffr:1;
+		uint64_t fdr:1;
+	} s;
+	struct cvmx_fpa_bist_status_s cn30xx;
+	struct cvmx_fpa_bist_status_s cn31xx;
+	struct cvmx_fpa_bist_status_s cn38xx;
+	struct cvmx_fpa_bist_status_s cn38xxp2;
+	struct cvmx_fpa_bist_status_s cn50xx;
+	struct cvmx_fpa_bist_status_s cn52xx;
+	struct cvmx_fpa_bist_status_s cn52xxp1;
+	struct cvmx_fpa_bist_status_s cn56xx;
+	struct cvmx_fpa_bist_status_s cn56xxp1;
+	struct cvmx_fpa_bist_status_s cn58xx;
+	struct cvmx_fpa_bist_status_s cn58xxp1;
+};
+
+union cvmx_fpa_ctl_status {
+	uint64_t u64;
+	struct cvmx_fpa_ctl_status_s {
+		uint64_t reserved_18_63:46;
+		uint64_t reset:1;
+		uint64_t use_ldt:1;
+		uint64_t use_stt:1;
+		uint64_t enb:1;
+		uint64_t mem1_err:7;
+		uint64_t mem0_err:7;
+	} s;
+	struct cvmx_fpa_ctl_status_s cn30xx;
+	struct cvmx_fpa_ctl_status_s cn31xx;
+	struct cvmx_fpa_ctl_status_s cn38xx;
+	struct cvmx_fpa_ctl_status_s cn38xxp2;
+	struct cvmx_fpa_ctl_status_s cn50xx;
+	struct cvmx_fpa_ctl_status_s cn52xx;
+	struct cvmx_fpa_ctl_status_s cn52xxp1;
+	struct cvmx_fpa_ctl_status_s cn56xx;
+	struct cvmx_fpa_ctl_status_s cn56xxp1;
+	struct cvmx_fpa_ctl_status_s cn58xx;
+	struct cvmx_fpa_ctl_status_s cn58xxp1;
+};
+
+union cvmx_fpa_fpfx_marks {
+	uint64_t u64;
+	struct cvmx_fpa_fpfx_marks_s {
+		uint64_t reserved_22_63:42;
+		uint64_t fpf_wr:11;
+		uint64_t fpf_rd:11;
+	} s;
+	struct cvmx_fpa_fpfx_marks_s cn38xx;
+	struct cvmx_fpa_fpfx_marks_s cn38xxp2;
+	struct cvmx_fpa_fpfx_marks_s cn56xx;
+	struct cvmx_fpa_fpfx_marks_s cn56xxp1;
+	struct cvmx_fpa_fpfx_marks_s cn58xx;
+	struct cvmx_fpa_fpfx_marks_s cn58xxp1;
+};
+
+union cvmx_fpa_fpfx_size {
+	uint64_t u64;
+	struct cvmx_fpa_fpfx_size_s {
+		uint64_t reserved_11_63:53;
+		uint64_t fpf_siz:11;
+	} s;
+	struct cvmx_fpa_fpfx_size_s cn38xx;
+	struct cvmx_fpa_fpfx_size_s cn38xxp2;
+	struct cvmx_fpa_fpfx_size_s cn56xx;
+	struct cvmx_fpa_fpfx_size_s cn56xxp1;
+	struct cvmx_fpa_fpfx_size_s cn58xx;
+	struct cvmx_fpa_fpfx_size_s cn58xxp1;
+};
+
+union cvmx_fpa_fpf0_marks {
+	uint64_t u64;
+	struct cvmx_fpa_fpf0_marks_s {
+		uint64_t reserved_24_63:40;
+		uint64_t fpf_wr:12;
+		uint64_t fpf_rd:12;
+	} s;
+	struct cvmx_fpa_fpf0_marks_s cn38xx;
+	struct cvmx_fpa_fpf0_marks_s cn38xxp2;
+	struct cvmx_fpa_fpf0_marks_s cn56xx;
+	struct cvmx_fpa_fpf0_marks_s cn56xxp1;
+	struct cvmx_fpa_fpf0_marks_s cn58xx;
+	struct cvmx_fpa_fpf0_marks_s cn58xxp1;
+};
+
+union cvmx_fpa_fpf0_size {
+	uint64_t u64;
+	struct cvmx_fpa_fpf0_size_s {
+		uint64_t reserved_12_63:52;
+		uint64_t fpf_siz:12;
+	} s;
+	struct cvmx_fpa_fpf0_size_s cn38xx;
+	struct cvmx_fpa_fpf0_size_s cn38xxp2;
+	struct cvmx_fpa_fpf0_size_s cn56xx;
+	struct cvmx_fpa_fpf0_size_s cn56xxp1;
+	struct cvmx_fpa_fpf0_size_s cn58xx;
+	struct cvmx_fpa_fpf0_size_s cn58xxp1;
+};
+
+union cvmx_fpa_int_enb {
+	uint64_t u64;
+	struct cvmx_fpa_int_enb_s {
+		uint64_t reserved_28_63:36;
+		uint64_t q7_perr:1;
+		uint64_t q7_coff:1;
+		uint64_t q7_und:1;
+		uint64_t q6_perr:1;
+		uint64_t q6_coff:1;
+		uint64_t q6_und:1;
+		uint64_t q5_perr:1;
+		uint64_t q5_coff:1;
+		uint64_t q5_und:1;
+		uint64_t q4_perr:1;
+		uint64_t q4_coff:1;
+		uint64_t q4_und:1;
+		uint64_t q3_perr:1;
+		uint64_t q3_coff:1;
+		uint64_t q3_und:1;
+		uint64_t q2_perr:1;
+		uint64_t q2_coff:1;
+		uint64_t q2_und:1;
+		uint64_t q1_perr:1;
+		uint64_t q1_coff:1;
+		uint64_t q1_und:1;
+		uint64_t q0_perr:1;
+		uint64_t q0_coff:1;
+		uint64_t q0_und:1;
+		uint64_t fed1_dbe:1;
+		uint64_t fed1_sbe:1;
+		uint64_t fed0_dbe:1;
+		uint64_t fed0_sbe:1;
+	} s;
+	struct cvmx_fpa_int_enb_s cn30xx;
+	struct cvmx_fpa_int_enb_s cn31xx;
+	struct cvmx_fpa_int_enb_s cn38xx;
+	struct cvmx_fpa_int_enb_s cn38xxp2;
+	struct cvmx_fpa_int_enb_s cn50xx;
+	struct cvmx_fpa_int_enb_s cn52xx;
+	struct cvmx_fpa_int_enb_s cn52xxp1;
+	struct cvmx_fpa_int_enb_s cn56xx;
+	struct cvmx_fpa_int_enb_s cn56xxp1;
+	struct cvmx_fpa_int_enb_s cn58xx;
+	struct cvmx_fpa_int_enb_s cn58xxp1;
+};
+
+union cvmx_fpa_int_sum {
+	uint64_t u64;
+	struct cvmx_fpa_int_sum_s {
+		uint64_t reserved_28_63:36;
+		uint64_t q7_perr:1;
+		uint64_t q7_coff:1;
+		uint64_t q7_und:1;
+		uint64_t q6_perr:1;
+		uint64_t q6_coff:1;
+		uint64_t q6_und:1;
+		uint64_t q5_perr:1;
+		uint64_t q5_coff:1;
+		uint64_t q5_und:1;
+		uint64_t q4_perr:1;
+		uint64_t q4_coff:1;
+		uint64_t q4_und:1;
+		uint64_t q3_perr:1;
+		uint64_t q3_coff:1;
+		uint64_t q3_und:1;
+		uint64_t q2_perr:1;
+		uint64_t q2_coff:1;
+		uint64_t q2_und:1;
+		uint64_t q1_perr:1;
+		uint64_t q1_coff:1;
+		uint64_t q1_und:1;
+		uint64_t q0_perr:1;
+		uint64_t q0_coff:1;
+		uint64_t q0_und:1;
+		uint64_t fed1_dbe:1;
+		uint64_t fed1_sbe:1;
+		uint64_t fed0_dbe:1;
+		uint64_t fed0_sbe:1;
+	} s;
+	struct cvmx_fpa_int_sum_s cn30xx;
+	struct cvmx_fpa_int_sum_s cn31xx;
+	struct cvmx_fpa_int_sum_s cn38xx;
+	struct cvmx_fpa_int_sum_s cn38xxp2;
+	struct cvmx_fpa_int_sum_s cn50xx;
+	struct cvmx_fpa_int_sum_s cn52xx;
+	struct cvmx_fpa_int_sum_s cn52xxp1;
+	struct cvmx_fpa_int_sum_s cn56xx;
+	struct cvmx_fpa_int_sum_s cn56xxp1;
+	struct cvmx_fpa_int_sum_s cn58xx;
+	struct cvmx_fpa_int_sum_s cn58xxp1;
+};
+
+union cvmx_fpa_quex_available {
+	uint64_t u64;
+	struct cvmx_fpa_quex_available_s {
+		uint64_t reserved_29_63:35;
+		uint64_t que_siz:29;
+	} s;
+	struct cvmx_fpa_quex_available_s cn30xx;
+	struct cvmx_fpa_quex_available_s cn31xx;
+	struct cvmx_fpa_quex_available_s cn38xx;
+	struct cvmx_fpa_quex_available_s cn38xxp2;
+	struct cvmx_fpa_quex_available_s cn50xx;
+	struct cvmx_fpa_quex_available_s cn52xx;
+	struct cvmx_fpa_quex_available_s cn52xxp1;
+	struct cvmx_fpa_quex_available_s cn56xx;
+	struct cvmx_fpa_quex_available_s cn56xxp1;
+	struct cvmx_fpa_quex_available_s cn58xx;
+	struct cvmx_fpa_quex_available_s cn58xxp1;
+};
+
+union cvmx_fpa_quex_page_index {
+	uint64_t u64;
+	struct cvmx_fpa_quex_page_index_s {
+		uint64_t reserved_25_63:39;
+		uint64_t pg_num:25;
+	} s;
+	struct cvmx_fpa_quex_page_index_s cn30xx;
+	struct cvmx_fpa_quex_page_index_s cn31xx;
+	struct cvmx_fpa_quex_page_index_s cn38xx;
+	struct cvmx_fpa_quex_page_index_s cn38xxp2;
+	struct cvmx_fpa_quex_page_index_s cn50xx;
+	struct cvmx_fpa_quex_page_index_s cn52xx;
+	struct cvmx_fpa_quex_page_index_s cn52xxp1;
+	struct cvmx_fpa_quex_page_index_s cn56xx;
+	struct cvmx_fpa_quex_page_index_s cn56xxp1;
+	struct cvmx_fpa_quex_page_index_s cn58xx;
+	struct cvmx_fpa_quex_page_index_s cn58xxp1;
+};
+
+union cvmx_fpa_que_act {
+	uint64_t u64;
+	struct cvmx_fpa_que_act_s {
+		uint64_t reserved_29_63:35;
+		uint64_t act_que:3;
+		uint64_t act_indx:26;
+	} s;
+	struct cvmx_fpa_que_act_s cn30xx;
+	struct cvmx_fpa_que_act_s cn31xx;
+	struct cvmx_fpa_que_act_s cn38xx;
+	struct cvmx_fpa_que_act_s cn38xxp2;
+	struct cvmx_fpa_que_act_s cn50xx;
+	struct cvmx_fpa_que_act_s cn52xx;
+	struct cvmx_fpa_que_act_s cn52xxp1;
+	struct cvmx_fpa_que_act_s cn56xx;
+	struct cvmx_fpa_que_act_s cn56xxp1;
+	struct cvmx_fpa_que_act_s cn58xx;
+	struct cvmx_fpa_que_act_s cn58xxp1;
+};
+
+union cvmx_fpa_que_exp {
+	uint64_t u64;
+	struct cvmx_fpa_que_exp_s {
+		uint64_t reserved_29_63:35;
+		uint64_t exp_que:3;
+		uint64_t exp_indx:26;
+	} s;
+	struct cvmx_fpa_que_exp_s cn30xx;
+	struct cvmx_fpa_que_exp_s cn31xx;
+	struct cvmx_fpa_que_exp_s cn38xx;
+	struct cvmx_fpa_que_exp_s cn38xxp2;
+	struct cvmx_fpa_que_exp_s cn50xx;
+	struct cvmx_fpa_que_exp_s cn52xx;
+	struct cvmx_fpa_que_exp_s cn52xxp1;
+	struct cvmx_fpa_que_exp_s cn56xx;
+	struct cvmx_fpa_que_exp_s cn56xxp1;
+	struct cvmx_fpa_que_exp_s cn58xx;
+	struct cvmx_fpa_que_exp_s cn58xxp1;
+};
+
+union cvmx_fpa_wart_ctl {
+	uint64_t u64;
+	struct cvmx_fpa_wart_ctl_s {
+		uint64_t reserved_16_63:48;
+		uint64_t ctl:16;
+	} s;
+	struct cvmx_fpa_wart_ctl_s cn30xx;
+	struct cvmx_fpa_wart_ctl_s cn31xx;
+	struct cvmx_fpa_wart_ctl_s cn38xx;
+	struct cvmx_fpa_wart_ctl_s cn38xxp2;
+	struct cvmx_fpa_wart_ctl_s cn50xx;
+	struct cvmx_fpa_wart_ctl_s cn52xx;
+	struct cvmx_fpa_wart_ctl_s cn52xxp1;
+	struct cvmx_fpa_wart_ctl_s cn56xx;
+	struct cvmx_fpa_wart_ctl_s cn56xxp1;
+	struct cvmx_fpa_wart_ctl_s cn58xx;
+	struct cvmx_fpa_wart_ctl_s cn58xxp1;
+};
+
+union cvmx_fpa_wart_status {
+	uint64_t u64;
+	struct cvmx_fpa_wart_status_s {
+		uint64_t reserved_32_63:32;
+		uint64_t status:32;
+	} s;
+	struct cvmx_fpa_wart_status_s cn30xx;
+	struct cvmx_fpa_wart_status_s cn31xx;
+	struct cvmx_fpa_wart_status_s cn38xx;
+	struct cvmx_fpa_wart_status_s cn38xxp2;
+	struct cvmx_fpa_wart_status_s cn50xx;
+	struct cvmx_fpa_wart_status_s cn52xx;
+	struct cvmx_fpa_wart_status_s cn52xxp1;
+	struct cvmx_fpa_wart_status_s cn56xx;
+	struct cvmx_fpa_wart_status_s cn56xxp1;
+	struct cvmx_fpa_wart_status_s cn58xx;
+	struct cvmx_fpa_wart_status_s cn58xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-fpa.c b/drivers/staging/octeon/cvmx-fpa.c
new file mode 100644
index 0000000..55d9147
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-fpa.c
@@ -0,0 +1,183 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * @file
+ *
+ * Support library for the hardware Free Pool Allocator.
+ *
+ *
+ */
+
+#include "cvmx-config.h"
+#include "cvmx.h"
+#include "cvmx-fpa.h"
+#include "cvmx-ipd.h"
+
+/**
+ * Current state of all the pools. Use access functions
+ * instead of using it directly.
+ */
+CVMX_SHARED cvmx_fpa_pool_info_t cvmx_fpa_pool_info[CVMX_FPA_NUM_POOLS];
+
+/**
+ * Setup a FPA pool to control a new block of memory. The
+ * buffer pointer must be a physical address.
+ *
+ * @pool:       Pool to initialize
+ *                   0 <= pool < 8
+ * @name:       Constant character string to name this pool.
+ *                   String is not copied.
+ * @buffer:     Pointer to the block of memory to use. This must be
+ *                   accessable by all processors and external hardware.
+ * @block_size: Size for each block controlled by the FPA
+ * @num_blocks: Number of blocks
+ *
+ * Returns 0 on Success,
+ *         -1 on failure
+ */
+int cvmx_fpa_setup_pool(uint64_t pool, const char *name, void *buffer,
+			uint64_t block_size, uint64_t num_blocks)
+{
+	char *ptr;
+	if (!buffer) {
+		cvmx_dprintf
+		    ("ERROR: cvmx_fpa_setup_pool: NULL buffer pointer!\n");
+		return -1;
+	}
+	if (pool >= CVMX_FPA_NUM_POOLS) {
+		cvmx_dprintf("ERROR: cvmx_fpa_setup_pool: Illegal pool!\n");
+		return -1;
+	}
+
+	if (block_size < CVMX_FPA_MIN_BLOCK_SIZE) {
+		cvmx_dprintf
+		    ("ERROR: cvmx_fpa_setup_pool: Block size too small.\n");
+		return -1;
+	}
+
+	if (((unsigned long)buffer & (CVMX_FPA_ALIGNMENT - 1)) != 0) {
+		cvmx_dprintf
+		    ("ERROR: cvmx_fpa_setup_pool: Buffer not aligned properly.\n");
+		return -1;
+	}
+
+	cvmx_fpa_pool_info[pool].name = name;
+	cvmx_fpa_pool_info[pool].size = block_size;
+	cvmx_fpa_pool_info[pool].starting_element_count = num_blocks;
+	cvmx_fpa_pool_info[pool].base = buffer;
+
+	ptr = (char *)buffer;
+	while (num_blocks--) {
+		cvmx_fpa_free(ptr, pool, 0);
+		ptr += block_size;
+	}
+	return 0;
+}
+
+/**
+ * Shutdown a Memory pool and validate that it had all of
+ * the buffers originally placed in it.
+ *
+ * @pool:   Pool to shutdown
+ * Returns Zero on success
+ *         - Positive is count of missing buffers
+ *         - Negative is too many buffers or corrupted pointers
+ */
+uint64_t cvmx_fpa_shutdown_pool(uint64_t pool)
+{
+	uint64_t errors = 0;
+	uint64_t count = 0;
+	uint64_t base = cvmx_ptr_to_phys(cvmx_fpa_pool_info[pool].base);
+	uint64_t finish =
+	    base +
+	    cvmx_fpa_pool_info[pool].size *
+	    cvmx_fpa_pool_info[pool].starting_element_count;
+	void *ptr;
+	uint64_t address;
+
+	count = 0;
+	do {
+		ptr = cvmx_fpa_alloc(pool);
+		if (ptr)
+			address = cvmx_ptr_to_phys(ptr);
+		else
+			address = 0;
+		if (address) {
+			if ((address >= base) && (address < finish) &&
+			    (((address -
+			       base) % cvmx_fpa_pool_info[pool].size) == 0)) {
+				count++;
+			} else {
+				cvmx_dprintf
+				    ("ERROR: cvmx_fpa_shutdown_pool: Illegal address 0x%llx in pool %s(%d)\n",
+				     (unsigned long long)address,
+				     cvmx_fpa_pool_info[pool].name, (int)pool);
+				errors++;
+			}
+		}
+	} while (address);
+
+#ifdef CVMX_ENABLE_PKO_FUNCTIONS
+	if (pool == 0)
+		cvmx_ipd_free_ptr();
+#endif
+
+	if (errors) {
+		cvmx_dprintf
+		    ("ERROR: cvmx_fpa_shutdown_pool: Pool %s(%d) started at 0x%llx, ended at 0x%llx, with a step of 0x%llx\n",
+		     cvmx_fpa_pool_info[pool].name, (int)pool,
+		     (unsigned long long)base, (unsigned long long)finish,
+		     (unsigned long long)cvmx_fpa_pool_info[pool].size);
+		return -errors;
+	} else
+		return 0;
+}
+
+uint64_t cvmx_fpa_get_block_size(uint64_t pool)
+{
+	switch (pool) {
+	case 0:
+		return CVMX_FPA_POOL_0_SIZE;
+	case 1:
+		return CVMX_FPA_POOL_1_SIZE;
+	case 2:
+		return CVMX_FPA_POOL_2_SIZE;
+	case 3:
+		return CVMX_FPA_POOL_3_SIZE;
+	case 4:
+		return CVMX_FPA_POOL_4_SIZE;
+	case 5:
+		return CVMX_FPA_POOL_5_SIZE;
+	case 6:
+		return CVMX_FPA_POOL_6_SIZE;
+	case 7:
+		return CVMX_FPA_POOL_7_SIZE;
+	default:
+		return 0;
+	}
+}
diff --git a/drivers/staging/octeon/cvmx-fpa.h b/drivers/staging/octeon/cvmx-fpa.h
new file mode 100644
index 0000000..1d7788f
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-fpa.h
@@ -0,0 +1,299 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * @file
+ *
+ * Interface to the hardware Free Pool Allocator.
+ *
+ *
+ */
+
+#ifndef __CVMX_FPA_H__
+#define __CVMX_FPA_H__
+
+#include "cvmx-address.h"
+#include "cvmx-fpa-defs.h"
+
+#define CVMX_FPA_NUM_POOLS      8
+#define CVMX_FPA_MIN_BLOCK_SIZE 128
+#define CVMX_FPA_ALIGNMENT      128
+
+/**
+ * Structure describing the data format used for stores to the FPA.
+ */
+typedef union {
+	uint64_t u64;
+	struct {
+		/*
+		 * the (64-bit word) location in scratchpad to write
+		 * to (if len != 0)
+		 */
+		uint64_t scraddr:8;
+		/* the number of words in the response (0 => no response) */
+		uint64_t len:8;
+		/* the ID of the device on the non-coherent bus */
+		uint64_t did:8;
+		/*
+		 * the address that will appear in the first tick on
+		 * the NCB bus.
+		 */
+		uint64_t addr:40;
+	} s;
+} cvmx_fpa_iobdma_data_t;
+
+/**
+ * Structure describing the current state of a FPA pool.
+ */
+typedef struct {
+	/* Name it was created under */
+	const char *name;
+	/* Size of each block */
+	uint64_t size;
+	/* The base memory address of whole block */
+	void *base;
+	/* The number of elements in the pool at creation */
+	uint64_t starting_element_count;
+} cvmx_fpa_pool_info_t;
+
+/**
+ * Current state of all the pools. Use access functions
+ * instead of using it directly.
+ */
+extern cvmx_fpa_pool_info_t cvmx_fpa_pool_info[CVMX_FPA_NUM_POOLS];
+
+/* CSR typedefs have been moved to cvmx-csr-*.h */
+
+/**
+ * Return the name of the pool
+ *
+ * @pool:   Pool to get the name of
+ * Returns The name
+ */
+static inline const char *cvmx_fpa_get_name(uint64_t pool)
+{
+	return cvmx_fpa_pool_info[pool].name;
+}
+
+/**
+ * Return the base of the pool
+ *
+ * @pool:   Pool to get the base of
+ * Returns The base
+ */
+static inline void *cvmx_fpa_get_base(uint64_t pool)
+{
+	return cvmx_fpa_pool_info[pool].base;
+}
+
+/**
+ * Check if a pointer belongs to an FPA pool. Return non-zero
+ * if the supplied pointer is inside the memory controlled by
+ * an FPA pool.
+ *
+ * @pool:   Pool to check
+ * @ptr:    Pointer to check
+ * Returns Non-zero if pointer is in the pool. Zero if not
+ */
+static inline int cvmx_fpa_is_member(uint64_t pool, void *ptr)
+{
+	return ((ptr >= cvmx_fpa_pool_info[pool].base) &&
+		((char *)ptr <
+		 ((char *)(cvmx_fpa_pool_info[pool].base)) +
+		 cvmx_fpa_pool_info[pool].size *
+		 cvmx_fpa_pool_info[pool].starting_element_count));
+}
+
+/**
+ * Enable the FPA for use. Must be performed after any CSR
+ * configuration but before any other FPA functions.
+ */
+static inline void cvmx_fpa_enable(void)
+{
+	union cvmx_fpa_ctl_status status;
+
+	status.u64 = cvmx_read_csr(CVMX_FPA_CTL_STATUS);
+	if (status.s.enb) {
+		cvmx_dprintf
+		    ("Warning: Enabling FPA when FPA already enabled.\n");
+	}
+
+	/*
+	 * Do runtime check as we allow pass1 compiled code to run on
+	 * pass2 chips.
+	 */
+	if (cvmx_octeon_is_pass1()) {
+		union cvmx_fpa_fpfx_marks marks;
+		int i;
+		for (i = 1; i < 8; i++) {
+			marks.u64 =
+			    cvmx_read_csr(CVMX_FPA_FPF1_MARKS + (i - 1) * 8ull);
+			marks.s.fpf_wr = 0xe0;
+			cvmx_write_csr(CVMX_FPA_FPF1_MARKS + (i - 1) * 8ull,
+				       marks.u64);
+		}
+
+		/* Enforce a 10 cycle delay between config and enable */
+		cvmx_wait(10);
+	}
+
+	/* FIXME: CVMX_FPA_CTL_STATUS read is unmodelled */
+	status.u64 = 0;
+	status.s.enb = 1;
+	cvmx_write_csr(CVMX_FPA_CTL_STATUS, status.u64);
+}
+
+/**
+ * Get a new block from the FPA
+ *
+ * @pool:   Pool to get the block from
+ * Returns Pointer to the block or NULL on failure
+ */
+static inline void *cvmx_fpa_alloc(uint64_t pool)
+{
+	uint64_t address =
+	    cvmx_read_csr(CVMX_ADDR_DID(CVMX_FULL_DID(CVMX_OCT_DID_FPA, pool)));
+	if (address)
+		return cvmx_phys_to_ptr(address);
+	else
+		return NULL;
+}
+
+/**
+ * Asynchronously get a new block from the FPA
+ *
+ * @scr_addr: Local scratch address to put response in.  This is a byte address,
+ *                  but must be 8 byte aligned.
+ * @pool:      Pool to get the block from
+ */
+static inline void cvmx_fpa_async_alloc(uint64_t scr_addr, uint64_t pool)
+{
+	cvmx_fpa_iobdma_data_t data;
+
+	/*
+	 * Hardware only uses 64 bit alligned locations, so convert
+	 * from byte address to 64-bit index
+	 */
+	data.s.scraddr = scr_addr >> 3;
+	data.s.len = 1;
+	data.s.did = CVMX_FULL_DID(CVMX_OCT_DID_FPA, pool);
+	data.s.addr = 0;
+	cvmx_send_single(data.u64);
+}
+
+/**
+ * Free a block allocated with a FPA pool.  Does NOT provide memory
+ * ordering in cases where the memory block was modified by the core.
+ *
+ * @ptr:    Block to free
+ * @pool:   Pool to put it in
+ * @num_cache_lines:
+ *               Cache lines to invalidate
+ */
+static inline void cvmx_fpa_free_nosync(void *ptr, uint64_t pool,
+					uint64_t num_cache_lines)
+{
+	cvmx_addr_t newptr;
+	newptr.u64 = cvmx_ptr_to_phys(ptr);
+	newptr.sfilldidspace.didspace =
+	    CVMX_ADDR_DIDSPACE(CVMX_FULL_DID(CVMX_OCT_DID_FPA, pool));
+	/* Prevent GCC from reordering around free */
+	barrier();
+	/* value written is number of cache lines not written back */
+	cvmx_write_io(newptr.u64, num_cache_lines);
+}
+
+/**
+ * Free a block allocated with a FPA pool.  Provides required memory
+ * ordering in cases where memory block was modified by core.
+ *
+ * @ptr:    Block to free
+ * @pool:   Pool to put it in
+ * @num_cache_lines:
+ *               Cache lines to invalidate
+ */
+static inline void cvmx_fpa_free(void *ptr, uint64_t pool,
+				 uint64_t num_cache_lines)
+{
+	cvmx_addr_t newptr;
+	newptr.u64 = cvmx_ptr_to_phys(ptr);
+	newptr.sfilldidspace.didspace =
+	    CVMX_ADDR_DIDSPACE(CVMX_FULL_DID(CVMX_OCT_DID_FPA, pool));
+	/*
+	 * Make sure that any previous writes to memory go out before
+	 * we free this buffer.  This also serves as a barrier to
+	 * prevent GCC from reordering operations to after the
+	 * free.
+	 */
+	CVMX_SYNCWS;
+	/* value written is number of cache lines not written back */
+	cvmx_write_io(newptr.u64, num_cache_lines);
+}
+
+/**
+ * Setup a FPA pool to control a new block of memory.
+ * This can only be called once per pool. Make sure proper
+ * locking enforces this.
+ *
+ * @pool:       Pool to initialize
+ *                   0 <= pool < 8
+ * @name:       Constant character string to name this pool.
+ *                   String is not copied.
+ * @buffer:     Pointer to the block of memory to use. This must be
+ *                   accessable by all processors and external hardware.
+ * @block_size: Size for each block controlled by the FPA
+ * @num_blocks: Number of blocks
+ *
+ * Returns 0 on Success,
+ *         -1 on failure
+ */
+extern int cvmx_fpa_setup_pool(uint64_t pool, const char *name, void *buffer,
+			       uint64_t block_size, uint64_t num_blocks);
+
+/**
+ * Shutdown a Memory pool and validate that it had all of
+ * the buffers originally placed in it. This should only be
+ * called by one processor after all hardware has finished
+ * using the pool.
+ *
+ * @pool:   Pool to shutdown
+ * Returns Zero on success
+ *         - Positive is count of missing buffers
+ *         - Negative is too many buffers or corrupted pointers
+ */
+extern uint64_t cvmx_fpa_shutdown_pool(uint64_t pool);
+
+/**
+ * Get the size of blocks controlled by the pool
+ * This is resolved to a constant at compile time.
+ *
+ * @pool:   Pool to access
+ * Returns Size of the block in bytes
+ */
+uint64_t cvmx_fpa_get_block_size(uint64_t pool);
+
+#endif /*  __CVM_FPA_H__ */
diff --git a/drivers/staging/octeon/cvmx-gmxx-defs.h b/drivers/staging/octeon/cvmx-gmxx-defs.h
new file mode 100644
index 0000000..946a43a
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-gmxx-defs.h
@@ -0,0 +1,2529 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_GMXX_DEFS_H__
+#define __CVMX_GMXX_DEFS_H__
+
+#define CVMX_GMXX_BAD_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000518ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_BIST(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000400ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_CLK_EN(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080007F0ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_HG2_CONTROL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000550ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_INF_MODE(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080007F8ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_NXA_ADR(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000510ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_PRTX_CBFC_CTL(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000580ull + (((offset) & 0) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_PRTX_CFG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000010ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_ADR_CAM0(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000180ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_ADR_CAM1(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000188ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_ADR_CAM2(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000190ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_ADR_CAM3(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000198ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_ADR_CAM4(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080001A0ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_ADR_CAM5(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080001A8ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_ADR_CAM_EN(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000108ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_ADR_CTL(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000100ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_DECISION(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000040ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_FRM_CHK(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000020ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_FRM_CTL(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000018ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_FRM_MAX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000030ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_FRM_MIN(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000028ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_IFG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000058ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_INT_EN(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000008ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_INT_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000000ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_JABBER(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000038ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_PAUSE_DROP_TIME(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000068ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_RX_INBND(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000060ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_STATS_CTL(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000050ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_STATS_OCTS(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000088ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_STATS_OCTS_CTL(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000098ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_STATS_OCTS_DMAC(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080000A8ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_STATS_OCTS_DRP(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080000B8ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_STATS_PKTS(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000080ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_STATS_PKTS_BAD(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080000C0ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_STATS_PKTS_CTL(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000090ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_STATS_PKTS_DMAC(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080000A0ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_STATS_PKTS_DRP(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080000B0ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RXX_UDD_SKP(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000048ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RX_BP_DROPX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000420ull + (((offset) & 3) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RX_BP_OFFX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000460ull + (((offset) & 3) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RX_BP_ONX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000440ull + (((offset) & 3) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RX_HG2_STATUS(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000548ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RX_PASS_EN(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080005F8ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RX_PASS_MAPX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000600ull + (((offset) & 15) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RX_PRTS(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000410ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RX_PRT_INFO(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080004E8ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RX_TX_STATUS(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080007E8ull + (((block_id) & 0) * 0x8000000ull))
+#define CVMX_GMXX_RX_XAUI_BAD_COL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000538ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_RX_XAUI_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000530ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_SMACX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000230ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_STAT_BP(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000520ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_APPEND(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000218ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_BURST(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000228ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_CBFC_XOFF(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080005A0ull + (((offset) & 0) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_CBFC_XON(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080005C0ull + (((offset) & 0) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_CLK(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000208ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_CTL(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000270ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_MIN_PKT(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000240ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_PAUSE_PKT_INTERVAL(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000248ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_PAUSE_PKT_TIME(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000238ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_PAUSE_TOGO(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000258ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_PAUSE_ZERO(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000260ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_SGMII_CTL(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000300ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_SLOT(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000220ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_SOFT_PAUSE(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000250ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_STAT0(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000280ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_STAT1(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000288ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_STAT2(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000290ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_STAT3(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000298ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_STAT4(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080002A0ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_STAT5(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080002A8ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_STAT6(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080002B0ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_STAT7(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080002B8ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_STAT8(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080002C0ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_STAT9(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080002C8ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_STATS_CTL(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000268ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TXX_THRESH(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000210ull + (((offset) & 3) * 2048) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_BP(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080004D0ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_CLK_MSKX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000780ull + (((offset) & 1) * 8) + (((block_id) & 0) * 0x0ull))
+#define CVMX_GMXX_TX_COL_ATTEMPT(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000498ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_CORRUPT(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080004D8ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_HG2_REG1(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000558ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_HG2_REG2(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000560ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_IFG(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000488ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_INT_EN(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000508ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_INT_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000500ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_JAM(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000490ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_LFSR(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080004F8ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_OVR_BP(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080004C8ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_PAUSE_PKT_DMAC(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080004A0ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_PAUSE_PKT_TYPE(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080004A8ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_PRTS(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000480ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_SPI_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080004C0ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_SPI_DRAIN(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080004E0ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_SPI_MAX(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080004B0ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_SPI_ROUNDX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000680ull + (((offset) & 31) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_SPI_THRESH(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800080004B8ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_TX_XAUI_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000528ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_GMXX_XAUI_EXT_LOOPBACK(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180008000540ull + (((block_id) & 1) * 0x8000000ull))
+
+union cvmx_gmxx_bad_reg {
+	uint64_t u64;
+	struct cvmx_gmxx_bad_reg_s {
+		uint64_t reserved_31_63:33;
+		uint64_t inb_nxa:4;
+		uint64_t statovr:1;
+		uint64_t loststat:4;
+		uint64_t reserved_18_21:4;
+		uint64_t out_ovr:16;
+		uint64_t ncb_ovr:1;
+		uint64_t out_col:1;
+	} s;
+	struct cvmx_gmxx_bad_reg_cn30xx {
+		uint64_t reserved_31_63:33;
+		uint64_t inb_nxa:4;
+		uint64_t statovr:1;
+		uint64_t reserved_25_25:1;
+		uint64_t loststat:3;
+		uint64_t reserved_5_21:17;
+		uint64_t out_ovr:3;
+		uint64_t reserved_0_1:2;
+	} cn30xx;
+	struct cvmx_gmxx_bad_reg_cn30xx cn31xx;
+	struct cvmx_gmxx_bad_reg_s cn38xx;
+	struct cvmx_gmxx_bad_reg_s cn38xxp2;
+	struct cvmx_gmxx_bad_reg_cn30xx cn50xx;
+	struct cvmx_gmxx_bad_reg_cn52xx {
+		uint64_t reserved_31_63:33;
+		uint64_t inb_nxa:4;
+		uint64_t statovr:1;
+		uint64_t loststat:4;
+		uint64_t reserved_6_21:16;
+		uint64_t out_ovr:4;
+		uint64_t reserved_0_1:2;
+	} cn52xx;
+	struct cvmx_gmxx_bad_reg_cn52xx cn52xxp1;
+	struct cvmx_gmxx_bad_reg_cn52xx cn56xx;
+	struct cvmx_gmxx_bad_reg_cn52xx cn56xxp1;
+	struct cvmx_gmxx_bad_reg_s cn58xx;
+	struct cvmx_gmxx_bad_reg_s cn58xxp1;
+};
+
+union cvmx_gmxx_bist {
+	uint64_t u64;
+	struct cvmx_gmxx_bist_s {
+		uint64_t reserved_17_63:47;
+		uint64_t status:17;
+	} s;
+	struct cvmx_gmxx_bist_cn30xx {
+		uint64_t reserved_10_63:54;
+		uint64_t status:10;
+	} cn30xx;
+	struct cvmx_gmxx_bist_cn30xx cn31xx;
+	struct cvmx_gmxx_bist_cn30xx cn38xx;
+	struct cvmx_gmxx_bist_cn30xx cn38xxp2;
+	struct cvmx_gmxx_bist_cn50xx {
+		uint64_t reserved_12_63:52;
+		uint64_t status:12;
+	} cn50xx;
+	struct cvmx_gmxx_bist_cn52xx {
+		uint64_t reserved_16_63:48;
+		uint64_t status:16;
+	} cn52xx;
+	struct cvmx_gmxx_bist_cn52xx cn52xxp1;
+	struct cvmx_gmxx_bist_cn52xx cn56xx;
+	struct cvmx_gmxx_bist_cn52xx cn56xxp1;
+	struct cvmx_gmxx_bist_s cn58xx;
+	struct cvmx_gmxx_bist_s cn58xxp1;
+};
+
+union cvmx_gmxx_clk_en {
+	uint64_t u64;
+	struct cvmx_gmxx_clk_en_s {
+		uint64_t reserved_1_63:63;
+		uint64_t clk_en:1;
+	} s;
+	struct cvmx_gmxx_clk_en_s cn52xx;
+	struct cvmx_gmxx_clk_en_s cn52xxp1;
+	struct cvmx_gmxx_clk_en_s cn56xx;
+	struct cvmx_gmxx_clk_en_s cn56xxp1;
+};
+
+union cvmx_gmxx_hg2_control {
+	uint64_t u64;
+	struct cvmx_gmxx_hg2_control_s {
+		uint64_t reserved_19_63:45;
+		uint64_t hg2tx_en:1;
+		uint64_t hg2rx_en:1;
+		uint64_t phys_en:1;
+		uint64_t logl_en:16;
+	} s;
+	struct cvmx_gmxx_hg2_control_s cn52xx;
+	struct cvmx_gmxx_hg2_control_s cn52xxp1;
+	struct cvmx_gmxx_hg2_control_s cn56xx;
+};
+
+union cvmx_gmxx_inf_mode {
+	uint64_t u64;
+	struct cvmx_gmxx_inf_mode_s {
+		uint64_t reserved_10_63:54;
+		uint64_t speed:2;
+		uint64_t reserved_6_7:2;
+		uint64_t mode:2;
+		uint64_t reserved_3_3:1;
+		uint64_t p0mii:1;
+		uint64_t en:1;
+		uint64_t type:1;
+	} s;
+	struct cvmx_gmxx_inf_mode_cn30xx {
+		uint64_t reserved_3_63:61;
+		uint64_t p0mii:1;
+		uint64_t en:1;
+		uint64_t type:1;
+	} cn30xx;
+	struct cvmx_gmxx_inf_mode_cn31xx {
+		uint64_t reserved_2_63:62;
+		uint64_t en:1;
+		uint64_t type:1;
+	} cn31xx;
+	struct cvmx_gmxx_inf_mode_cn31xx cn38xx;
+	struct cvmx_gmxx_inf_mode_cn31xx cn38xxp2;
+	struct cvmx_gmxx_inf_mode_cn30xx cn50xx;
+	struct cvmx_gmxx_inf_mode_cn52xx {
+		uint64_t reserved_10_63:54;
+		uint64_t speed:2;
+		uint64_t reserved_6_7:2;
+		uint64_t mode:2;
+		uint64_t reserved_2_3:2;
+		uint64_t en:1;
+		uint64_t type:1;
+	} cn52xx;
+	struct cvmx_gmxx_inf_mode_cn52xx cn52xxp1;
+	struct cvmx_gmxx_inf_mode_cn52xx cn56xx;
+	struct cvmx_gmxx_inf_mode_cn52xx cn56xxp1;
+	struct cvmx_gmxx_inf_mode_cn31xx cn58xx;
+	struct cvmx_gmxx_inf_mode_cn31xx cn58xxp1;
+};
+
+union cvmx_gmxx_nxa_adr {
+	uint64_t u64;
+	struct cvmx_gmxx_nxa_adr_s {
+		uint64_t reserved_6_63:58;
+		uint64_t prt:6;
+	} s;
+	struct cvmx_gmxx_nxa_adr_s cn30xx;
+	struct cvmx_gmxx_nxa_adr_s cn31xx;
+	struct cvmx_gmxx_nxa_adr_s cn38xx;
+	struct cvmx_gmxx_nxa_adr_s cn38xxp2;
+	struct cvmx_gmxx_nxa_adr_s cn50xx;
+	struct cvmx_gmxx_nxa_adr_s cn52xx;
+	struct cvmx_gmxx_nxa_adr_s cn52xxp1;
+	struct cvmx_gmxx_nxa_adr_s cn56xx;
+	struct cvmx_gmxx_nxa_adr_s cn56xxp1;
+	struct cvmx_gmxx_nxa_adr_s cn58xx;
+	struct cvmx_gmxx_nxa_adr_s cn58xxp1;
+};
+
+union cvmx_gmxx_prtx_cbfc_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_prtx_cbfc_ctl_s {
+		uint64_t phys_en:16;
+		uint64_t logl_en:16;
+		uint64_t phys_bp:16;
+		uint64_t reserved_4_15:12;
+		uint64_t bck_en:1;
+		uint64_t drp_en:1;
+		uint64_t tx_en:1;
+		uint64_t rx_en:1;
+	} s;
+	struct cvmx_gmxx_prtx_cbfc_ctl_s cn52xx;
+	struct cvmx_gmxx_prtx_cbfc_ctl_s cn56xx;
+};
+
+union cvmx_gmxx_prtx_cfg {
+	uint64_t u64;
+	struct cvmx_gmxx_prtx_cfg_s {
+		uint64_t reserved_14_63:50;
+		uint64_t tx_idle:1;
+		uint64_t rx_idle:1;
+		uint64_t reserved_9_11:3;
+		uint64_t speed_msb:1;
+		uint64_t reserved_4_7:4;
+		uint64_t slottime:1;
+		uint64_t duplex:1;
+		uint64_t speed:1;
+		uint64_t en:1;
+	} s;
+	struct cvmx_gmxx_prtx_cfg_cn30xx {
+		uint64_t reserved_4_63:60;
+		uint64_t slottime:1;
+		uint64_t duplex:1;
+		uint64_t speed:1;
+		uint64_t en:1;
+	} cn30xx;
+	struct cvmx_gmxx_prtx_cfg_cn30xx cn31xx;
+	struct cvmx_gmxx_prtx_cfg_cn30xx cn38xx;
+	struct cvmx_gmxx_prtx_cfg_cn30xx cn38xxp2;
+	struct cvmx_gmxx_prtx_cfg_cn30xx cn50xx;
+	struct cvmx_gmxx_prtx_cfg_s cn52xx;
+	struct cvmx_gmxx_prtx_cfg_s cn52xxp1;
+	struct cvmx_gmxx_prtx_cfg_s cn56xx;
+	struct cvmx_gmxx_prtx_cfg_s cn56xxp1;
+	struct cvmx_gmxx_prtx_cfg_cn30xx cn58xx;
+	struct cvmx_gmxx_prtx_cfg_cn30xx cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_adr_cam0 {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_adr_cam0_s {
+		uint64_t adr:64;
+	} s;
+	struct cvmx_gmxx_rxx_adr_cam0_s cn30xx;
+	struct cvmx_gmxx_rxx_adr_cam0_s cn31xx;
+	struct cvmx_gmxx_rxx_adr_cam0_s cn38xx;
+	struct cvmx_gmxx_rxx_adr_cam0_s cn38xxp2;
+	struct cvmx_gmxx_rxx_adr_cam0_s cn50xx;
+	struct cvmx_gmxx_rxx_adr_cam0_s cn52xx;
+	struct cvmx_gmxx_rxx_adr_cam0_s cn52xxp1;
+	struct cvmx_gmxx_rxx_adr_cam0_s cn56xx;
+	struct cvmx_gmxx_rxx_adr_cam0_s cn56xxp1;
+	struct cvmx_gmxx_rxx_adr_cam0_s cn58xx;
+	struct cvmx_gmxx_rxx_adr_cam0_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_adr_cam1 {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_adr_cam1_s {
+		uint64_t adr:64;
+	} s;
+	struct cvmx_gmxx_rxx_adr_cam1_s cn30xx;
+	struct cvmx_gmxx_rxx_adr_cam1_s cn31xx;
+	struct cvmx_gmxx_rxx_adr_cam1_s cn38xx;
+	struct cvmx_gmxx_rxx_adr_cam1_s cn38xxp2;
+	struct cvmx_gmxx_rxx_adr_cam1_s cn50xx;
+	struct cvmx_gmxx_rxx_adr_cam1_s cn52xx;
+	struct cvmx_gmxx_rxx_adr_cam1_s cn52xxp1;
+	struct cvmx_gmxx_rxx_adr_cam1_s cn56xx;
+	struct cvmx_gmxx_rxx_adr_cam1_s cn56xxp1;
+	struct cvmx_gmxx_rxx_adr_cam1_s cn58xx;
+	struct cvmx_gmxx_rxx_adr_cam1_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_adr_cam2 {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_adr_cam2_s {
+		uint64_t adr:64;
+	} s;
+	struct cvmx_gmxx_rxx_adr_cam2_s cn30xx;
+	struct cvmx_gmxx_rxx_adr_cam2_s cn31xx;
+	struct cvmx_gmxx_rxx_adr_cam2_s cn38xx;
+	struct cvmx_gmxx_rxx_adr_cam2_s cn38xxp2;
+	struct cvmx_gmxx_rxx_adr_cam2_s cn50xx;
+	struct cvmx_gmxx_rxx_adr_cam2_s cn52xx;
+	struct cvmx_gmxx_rxx_adr_cam2_s cn52xxp1;
+	struct cvmx_gmxx_rxx_adr_cam2_s cn56xx;
+	struct cvmx_gmxx_rxx_adr_cam2_s cn56xxp1;
+	struct cvmx_gmxx_rxx_adr_cam2_s cn58xx;
+	struct cvmx_gmxx_rxx_adr_cam2_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_adr_cam3 {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_adr_cam3_s {
+		uint64_t adr:64;
+	} s;
+	struct cvmx_gmxx_rxx_adr_cam3_s cn30xx;
+	struct cvmx_gmxx_rxx_adr_cam3_s cn31xx;
+	struct cvmx_gmxx_rxx_adr_cam3_s cn38xx;
+	struct cvmx_gmxx_rxx_adr_cam3_s cn38xxp2;
+	struct cvmx_gmxx_rxx_adr_cam3_s cn50xx;
+	struct cvmx_gmxx_rxx_adr_cam3_s cn52xx;
+	struct cvmx_gmxx_rxx_adr_cam3_s cn52xxp1;
+	struct cvmx_gmxx_rxx_adr_cam3_s cn56xx;
+	struct cvmx_gmxx_rxx_adr_cam3_s cn56xxp1;
+	struct cvmx_gmxx_rxx_adr_cam3_s cn58xx;
+	struct cvmx_gmxx_rxx_adr_cam3_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_adr_cam4 {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_adr_cam4_s {
+		uint64_t adr:64;
+	} s;
+	struct cvmx_gmxx_rxx_adr_cam4_s cn30xx;
+	struct cvmx_gmxx_rxx_adr_cam4_s cn31xx;
+	struct cvmx_gmxx_rxx_adr_cam4_s cn38xx;
+	struct cvmx_gmxx_rxx_adr_cam4_s cn38xxp2;
+	struct cvmx_gmxx_rxx_adr_cam4_s cn50xx;
+	struct cvmx_gmxx_rxx_adr_cam4_s cn52xx;
+	struct cvmx_gmxx_rxx_adr_cam4_s cn52xxp1;
+	struct cvmx_gmxx_rxx_adr_cam4_s cn56xx;
+	struct cvmx_gmxx_rxx_adr_cam4_s cn56xxp1;
+	struct cvmx_gmxx_rxx_adr_cam4_s cn58xx;
+	struct cvmx_gmxx_rxx_adr_cam4_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_adr_cam5 {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_adr_cam5_s {
+		uint64_t adr:64;
+	} s;
+	struct cvmx_gmxx_rxx_adr_cam5_s cn30xx;
+	struct cvmx_gmxx_rxx_adr_cam5_s cn31xx;
+	struct cvmx_gmxx_rxx_adr_cam5_s cn38xx;
+	struct cvmx_gmxx_rxx_adr_cam5_s cn38xxp2;
+	struct cvmx_gmxx_rxx_adr_cam5_s cn50xx;
+	struct cvmx_gmxx_rxx_adr_cam5_s cn52xx;
+	struct cvmx_gmxx_rxx_adr_cam5_s cn52xxp1;
+	struct cvmx_gmxx_rxx_adr_cam5_s cn56xx;
+	struct cvmx_gmxx_rxx_adr_cam5_s cn56xxp1;
+	struct cvmx_gmxx_rxx_adr_cam5_s cn58xx;
+	struct cvmx_gmxx_rxx_adr_cam5_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_adr_cam_en {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_adr_cam_en_s {
+		uint64_t reserved_8_63:56;
+		uint64_t en:8;
+	} s;
+	struct cvmx_gmxx_rxx_adr_cam_en_s cn30xx;
+	struct cvmx_gmxx_rxx_adr_cam_en_s cn31xx;
+	struct cvmx_gmxx_rxx_adr_cam_en_s cn38xx;
+	struct cvmx_gmxx_rxx_adr_cam_en_s cn38xxp2;
+	struct cvmx_gmxx_rxx_adr_cam_en_s cn50xx;
+	struct cvmx_gmxx_rxx_adr_cam_en_s cn52xx;
+	struct cvmx_gmxx_rxx_adr_cam_en_s cn52xxp1;
+	struct cvmx_gmxx_rxx_adr_cam_en_s cn56xx;
+	struct cvmx_gmxx_rxx_adr_cam_en_s cn56xxp1;
+	struct cvmx_gmxx_rxx_adr_cam_en_s cn58xx;
+	struct cvmx_gmxx_rxx_adr_cam_en_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_adr_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_adr_ctl_s {
+		uint64_t reserved_4_63:60;
+		uint64_t cam_mode:1;
+		uint64_t mcst:2;
+		uint64_t bcst:1;
+	} s;
+	struct cvmx_gmxx_rxx_adr_ctl_s cn30xx;
+	struct cvmx_gmxx_rxx_adr_ctl_s cn31xx;
+	struct cvmx_gmxx_rxx_adr_ctl_s cn38xx;
+	struct cvmx_gmxx_rxx_adr_ctl_s cn38xxp2;
+	struct cvmx_gmxx_rxx_adr_ctl_s cn50xx;
+	struct cvmx_gmxx_rxx_adr_ctl_s cn52xx;
+	struct cvmx_gmxx_rxx_adr_ctl_s cn52xxp1;
+	struct cvmx_gmxx_rxx_adr_ctl_s cn56xx;
+	struct cvmx_gmxx_rxx_adr_ctl_s cn56xxp1;
+	struct cvmx_gmxx_rxx_adr_ctl_s cn58xx;
+	struct cvmx_gmxx_rxx_adr_ctl_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_decision {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_decision_s {
+		uint64_t reserved_5_63:59;
+		uint64_t cnt:5;
+	} s;
+	struct cvmx_gmxx_rxx_decision_s cn30xx;
+	struct cvmx_gmxx_rxx_decision_s cn31xx;
+	struct cvmx_gmxx_rxx_decision_s cn38xx;
+	struct cvmx_gmxx_rxx_decision_s cn38xxp2;
+	struct cvmx_gmxx_rxx_decision_s cn50xx;
+	struct cvmx_gmxx_rxx_decision_s cn52xx;
+	struct cvmx_gmxx_rxx_decision_s cn52xxp1;
+	struct cvmx_gmxx_rxx_decision_s cn56xx;
+	struct cvmx_gmxx_rxx_decision_s cn56xxp1;
+	struct cvmx_gmxx_rxx_decision_s cn58xx;
+	struct cvmx_gmxx_rxx_decision_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_frm_chk {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_frm_chk_s {
+		uint64_t reserved_10_63:54;
+		uint64_t niberr:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t lenerr:1;
+		uint64_t alnerr:1;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t maxerr:1;
+		uint64_t carext:1;
+		uint64_t minerr:1;
+	} s;
+	struct cvmx_gmxx_rxx_frm_chk_s cn30xx;
+	struct cvmx_gmxx_rxx_frm_chk_s cn31xx;
+	struct cvmx_gmxx_rxx_frm_chk_s cn38xx;
+	struct cvmx_gmxx_rxx_frm_chk_s cn38xxp2;
+	struct cvmx_gmxx_rxx_frm_chk_cn50xx {
+		uint64_t reserved_10_63:54;
+		uint64_t niberr:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t reserved_6_6:1;
+		uint64_t alnerr:1;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t reserved_2_2:1;
+		uint64_t carext:1;
+		uint64_t reserved_0_0:1;
+	} cn50xx;
+	struct cvmx_gmxx_rxx_frm_chk_cn52xx {
+		uint64_t reserved_9_63:55;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t reserved_5_6:2;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t reserved_2_2:1;
+		uint64_t carext:1;
+		uint64_t reserved_0_0:1;
+	} cn52xx;
+	struct cvmx_gmxx_rxx_frm_chk_cn52xx cn52xxp1;
+	struct cvmx_gmxx_rxx_frm_chk_cn52xx cn56xx;
+	struct cvmx_gmxx_rxx_frm_chk_cn52xx cn56xxp1;
+	struct cvmx_gmxx_rxx_frm_chk_s cn58xx;
+	struct cvmx_gmxx_rxx_frm_chk_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_frm_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_frm_ctl_s {
+		uint64_t reserved_11_63:53;
+		uint64_t null_dis:1;
+		uint64_t pre_align:1;
+		uint64_t pad_len:1;
+		uint64_t vlan_len:1;
+		uint64_t pre_free:1;
+		uint64_t ctl_smac:1;
+		uint64_t ctl_mcst:1;
+		uint64_t ctl_bck:1;
+		uint64_t ctl_drp:1;
+		uint64_t pre_strp:1;
+		uint64_t pre_chk:1;
+	} s;
+	struct cvmx_gmxx_rxx_frm_ctl_cn30xx {
+		uint64_t reserved_9_63:55;
+		uint64_t pad_len:1;
+		uint64_t vlan_len:1;
+		uint64_t pre_free:1;
+		uint64_t ctl_smac:1;
+		uint64_t ctl_mcst:1;
+		uint64_t ctl_bck:1;
+		uint64_t ctl_drp:1;
+		uint64_t pre_strp:1;
+		uint64_t pre_chk:1;
+	} cn30xx;
+	struct cvmx_gmxx_rxx_frm_ctl_cn31xx {
+		uint64_t reserved_8_63:56;
+		uint64_t vlan_len:1;
+		uint64_t pre_free:1;
+		uint64_t ctl_smac:1;
+		uint64_t ctl_mcst:1;
+		uint64_t ctl_bck:1;
+		uint64_t ctl_drp:1;
+		uint64_t pre_strp:1;
+		uint64_t pre_chk:1;
+	} cn31xx;
+	struct cvmx_gmxx_rxx_frm_ctl_cn30xx cn38xx;
+	struct cvmx_gmxx_rxx_frm_ctl_cn31xx cn38xxp2;
+	struct cvmx_gmxx_rxx_frm_ctl_cn50xx {
+		uint64_t reserved_11_63:53;
+		uint64_t null_dis:1;
+		uint64_t pre_align:1;
+		uint64_t reserved_7_8:2;
+		uint64_t pre_free:1;
+		uint64_t ctl_smac:1;
+		uint64_t ctl_mcst:1;
+		uint64_t ctl_bck:1;
+		uint64_t ctl_drp:1;
+		uint64_t pre_strp:1;
+		uint64_t pre_chk:1;
+	} cn50xx;
+	struct cvmx_gmxx_rxx_frm_ctl_cn50xx cn52xx;
+	struct cvmx_gmxx_rxx_frm_ctl_cn50xx cn52xxp1;
+	struct cvmx_gmxx_rxx_frm_ctl_cn50xx cn56xx;
+	struct cvmx_gmxx_rxx_frm_ctl_cn56xxp1 {
+		uint64_t reserved_10_63:54;
+		uint64_t pre_align:1;
+		uint64_t reserved_7_8:2;
+		uint64_t pre_free:1;
+		uint64_t ctl_smac:1;
+		uint64_t ctl_mcst:1;
+		uint64_t ctl_bck:1;
+		uint64_t ctl_drp:1;
+		uint64_t pre_strp:1;
+		uint64_t pre_chk:1;
+	} cn56xxp1;
+	struct cvmx_gmxx_rxx_frm_ctl_s cn58xx;
+	struct cvmx_gmxx_rxx_frm_ctl_cn30xx cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_frm_max {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_frm_max_s {
+		uint64_t reserved_16_63:48;
+		uint64_t len:16;
+	} s;
+	struct cvmx_gmxx_rxx_frm_max_s cn30xx;
+	struct cvmx_gmxx_rxx_frm_max_s cn31xx;
+	struct cvmx_gmxx_rxx_frm_max_s cn38xx;
+	struct cvmx_gmxx_rxx_frm_max_s cn38xxp2;
+	struct cvmx_gmxx_rxx_frm_max_s cn58xx;
+	struct cvmx_gmxx_rxx_frm_max_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_frm_min {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_frm_min_s {
+		uint64_t reserved_16_63:48;
+		uint64_t len:16;
+	} s;
+	struct cvmx_gmxx_rxx_frm_min_s cn30xx;
+	struct cvmx_gmxx_rxx_frm_min_s cn31xx;
+	struct cvmx_gmxx_rxx_frm_min_s cn38xx;
+	struct cvmx_gmxx_rxx_frm_min_s cn38xxp2;
+	struct cvmx_gmxx_rxx_frm_min_s cn58xx;
+	struct cvmx_gmxx_rxx_frm_min_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_ifg {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_ifg_s {
+		uint64_t reserved_4_63:60;
+		uint64_t ifg:4;
+	} s;
+	struct cvmx_gmxx_rxx_ifg_s cn30xx;
+	struct cvmx_gmxx_rxx_ifg_s cn31xx;
+	struct cvmx_gmxx_rxx_ifg_s cn38xx;
+	struct cvmx_gmxx_rxx_ifg_s cn38xxp2;
+	struct cvmx_gmxx_rxx_ifg_s cn50xx;
+	struct cvmx_gmxx_rxx_ifg_s cn52xx;
+	struct cvmx_gmxx_rxx_ifg_s cn52xxp1;
+	struct cvmx_gmxx_rxx_ifg_s cn56xx;
+	struct cvmx_gmxx_rxx_ifg_s cn56xxp1;
+	struct cvmx_gmxx_rxx_ifg_s cn58xx;
+	struct cvmx_gmxx_rxx_ifg_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_int_en {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_int_en_s {
+		uint64_t reserved_29_63:35;
+		uint64_t hg2cc:1;
+		uint64_t hg2fld:1;
+		uint64_t undat:1;
+		uint64_t uneop:1;
+		uint64_t unsop:1;
+		uint64_t bad_term:1;
+		uint64_t bad_seq:1;
+		uint64_t rem_fault:1;
+		uint64_t loc_fault:1;
+		uint64_t pause_drp:1;
+		uint64_t phy_dupx:1;
+		uint64_t phy_spd:1;
+		uint64_t phy_link:1;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t niberr:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t lenerr:1;
+		uint64_t alnerr:1;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t maxerr:1;
+		uint64_t carext:1;
+		uint64_t minerr:1;
+	} s;
+	struct cvmx_gmxx_rxx_int_en_cn30xx {
+		uint64_t reserved_19_63:45;
+		uint64_t phy_dupx:1;
+		uint64_t phy_spd:1;
+		uint64_t phy_link:1;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t niberr:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t lenerr:1;
+		uint64_t alnerr:1;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t maxerr:1;
+		uint64_t carext:1;
+		uint64_t minerr:1;
+	} cn30xx;
+	struct cvmx_gmxx_rxx_int_en_cn30xx cn31xx;
+	struct cvmx_gmxx_rxx_int_en_cn30xx cn38xx;
+	struct cvmx_gmxx_rxx_int_en_cn30xx cn38xxp2;
+	struct cvmx_gmxx_rxx_int_en_cn50xx {
+		uint64_t reserved_20_63:44;
+		uint64_t pause_drp:1;
+		uint64_t phy_dupx:1;
+		uint64_t phy_spd:1;
+		uint64_t phy_link:1;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t niberr:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t reserved_6_6:1;
+		uint64_t alnerr:1;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t reserved_2_2:1;
+		uint64_t carext:1;
+		uint64_t reserved_0_0:1;
+	} cn50xx;
+	struct cvmx_gmxx_rxx_int_en_cn52xx {
+		uint64_t reserved_29_63:35;
+		uint64_t hg2cc:1;
+		uint64_t hg2fld:1;
+		uint64_t undat:1;
+		uint64_t uneop:1;
+		uint64_t unsop:1;
+		uint64_t bad_term:1;
+		uint64_t bad_seq:1;
+		uint64_t rem_fault:1;
+		uint64_t loc_fault:1;
+		uint64_t pause_drp:1;
+		uint64_t reserved_16_18:3;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t reserved_9_9:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t reserved_5_6:2;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t reserved_2_2:1;
+		uint64_t carext:1;
+		uint64_t reserved_0_0:1;
+	} cn52xx;
+	struct cvmx_gmxx_rxx_int_en_cn52xx cn52xxp1;
+	struct cvmx_gmxx_rxx_int_en_cn52xx cn56xx;
+	struct cvmx_gmxx_rxx_int_en_cn56xxp1 {
+		uint64_t reserved_27_63:37;
+		uint64_t undat:1;
+		uint64_t uneop:1;
+		uint64_t unsop:1;
+		uint64_t bad_term:1;
+		uint64_t bad_seq:1;
+		uint64_t rem_fault:1;
+		uint64_t loc_fault:1;
+		uint64_t pause_drp:1;
+		uint64_t reserved_16_18:3;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t reserved_9_9:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t reserved_5_6:2;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t reserved_2_2:1;
+		uint64_t carext:1;
+		uint64_t reserved_0_0:1;
+	} cn56xxp1;
+	struct cvmx_gmxx_rxx_int_en_cn58xx {
+		uint64_t reserved_20_63:44;
+		uint64_t pause_drp:1;
+		uint64_t phy_dupx:1;
+		uint64_t phy_spd:1;
+		uint64_t phy_link:1;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t niberr:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t lenerr:1;
+		uint64_t alnerr:1;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t maxerr:1;
+		uint64_t carext:1;
+		uint64_t minerr:1;
+	} cn58xx;
+	struct cvmx_gmxx_rxx_int_en_cn58xx cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_int_reg {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_int_reg_s {
+		uint64_t reserved_29_63:35;
+		uint64_t hg2cc:1;
+		uint64_t hg2fld:1;
+		uint64_t undat:1;
+		uint64_t uneop:1;
+		uint64_t unsop:1;
+		uint64_t bad_term:1;
+		uint64_t bad_seq:1;
+		uint64_t rem_fault:1;
+		uint64_t loc_fault:1;
+		uint64_t pause_drp:1;
+		uint64_t phy_dupx:1;
+		uint64_t phy_spd:1;
+		uint64_t phy_link:1;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t niberr:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t lenerr:1;
+		uint64_t alnerr:1;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t maxerr:1;
+		uint64_t carext:1;
+		uint64_t minerr:1;
+	} s;
+	struct cvmx_gmxx_rxx_int_reg_cn30xx {
+		uint64_t reserved_19_63:45;
+		uint64_t phy_dupx:1;
+		uint64_t phy_spd:1;
+		uint64_t phy_link:1;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t niberr:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t lenerr:1;
+		uint64_t alnerr:1;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t maxerr:1;
+		uint64_t carext:1;
+		uint64_t minerr:1;
+	} cn30xx;
+	struct cvmx_gmxx_rxx_int_reg_cn30xx cn31xx;
+	struct cvmx_gmxx_rxx_int_reg_cn30xx cn38xx;
+	struct cvmx_gmxx_rxx_int_reg_cn30xx cn38xxp2;
+	struct cvmx_gmxx_rxx_int_reg_cn50xx {
+		uint64_t reserved_20_63:44;
+		uint64_t pause_drp:1;
+		uint64_t phy_dupx:1;
+		uint64_t phy_spd:1;
+		uint64_t phy_link:1;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t niberr:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t reserved_6_6:1;
+		uint64_t alnerr:1;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t reserved_2_2:1;
+		uint64_t carext:1;
+		uint64_t reserved_0_0:1;
+	} cn50xx;
+	struct cvmx_gmxx_rxx_int_reg_cn52xx {
+		uint64_t reserved_29_63:35;
+		uint64_t hg2cc:1;
+		uint64_t hg2fld:1;
+		uint64_t undat:1;
+		uint64_t uneop:1;
+		uint64_t unsop:1;
+		uint64_t bad_term:1;
+		uint64_t bad_seq:1;
+		uint64_t rem_fault:1;
+		uint64_t loc_fault:1;
+		uint64_t pause_drp:1;
+		uint64_t reserved_16_18:3;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t reserved_9_9:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t reserved_5_6:2;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t reserved_2_2:1;
+		uint64_t carext:1;
+		uint64_t reserved_0_0:1;
+	} cn52xx;
+	struct cvmx_gmxx_rxx_int_reg_cn52xx cn52xxp1;
+	struct cvmx_gmxx_rxx_int_reg_cn52xx cn56xx;
+	struct cvmx_gmxx_rxx_int_reg_cn56xxp1 {
+		uint64_t reserved_27_63:37;
+		uint64_t undat:1;
+		uint64_t uneop:1;
+		uint64_t unsop:1;
+		uint64_t bad_term:1;
+		uint64_t bad_seq:1;
+		uint64_t rem_fault:1;
+		uint64_t loc_fault:1;
+		uint64_t pause_drp:1;
+		uint64_t reserved_16_18:3;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t reserved_9_9:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t reserved_5_6:2;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t reserved_2_2:1;
+		uint64_t carext:1;
+		uint64_t reserved_0_0:1;
+	} cn56xxp1;
+	struct cvmx_gmxx_rxx_int_reg_cn58xx {
+		uint64_t reserved_20_63:44;
+		uint64_t pause_drp:1;
+		uint64_t phy_dupx:1;
+		uint64_t phy_spd:1;
+		uint64_t phy_link:1;
+		uint64_t ifgerr:1;
+		uint64_t coldet:1;
+		uint64_t falerr:1;
+		uint64_t rsverr:1;
+		uint64_t pcterr:1;
+		uint64_t ovrerr:1;
+		uint64_t niberr:1;
+		uint64_t skperr:1;
+		uint64_t rcverr:1;
+		uint64_t lenerr:1;
+		uint64_t alnerr:1;
+		uint64_t fcserr:1;
+		uint64_t jabber:1;
+		uint64_t maxerr:1;
+		uint64_t carext:1;
+		uint64_t minerr:1;
+	} cn58xx;
+	struct cvmx_gmxx_rxx_int_reg_cn58xx cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_jabber {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_jabber_s {
+		uint64_t reserved_16_63:48;
+		uint64_t cnt:16;
+	} s;
+	struct cvmx_gmxx_rxx_jabber_s cn30xx;
+	struct cvmx_gmxx_rxx_jabber_s cn31xx;
+	struct cvmx_gmxx_rxx_jabber_s cn38xx;
+	struct cvmx_gmxx_rxx_jabber_s cn38xxp2;
+	struct cvmx_gmxx_rxx_jabber_s cn50xx;
+	struct cvmx_gmxx_rxx_jabber_s cn52xx;
+	struct cvmx_gmxx_rxx_jabber_s cn52xxp1;
+	struct cvmx_gmxx_rxx_jabber_s cn56xx;
+	struct cvmx_gmxx_rxx_jabber_s cn56xxp1;
+	struct cvmx_gmxx_rxx_jabber_s cn58xx;
+	struct cvmx_gmxx_rxx_jabber_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_pause_drop_time {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_pause_drop_time_s {
+		uint64_t reserved_16_63:48;
+		uint64_t status:16;
+	} s;
+	struct cvmx_gmxx_rxx_pause_drop_time_s cn50xx;
+	struct cvmx_gmxx_rxx_pause_drop_time_s cn52xx;
+	struct cvmx_gmxx_rxx_pause_drop_time_s cn52xxp1;
+	struct cvmx_gmxx_rxx_pause_drop_time_s cn56xx;
+	struct cvmx_gmxx_rxx_pause_drop_time_s cn56xxp1;
+	struct cvmx_gmxx_rxx_pause_drop_time_s cn58xx;
+	struct cvmx_gmxx_rxx_pause_drop_time_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_rx_inbnd {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_rx_inbnd_s {
+		uint64_t reserved_4_63:60;
+		uint64_t duplex:1;
+		uint64_t speed:2;
+		uint64_t status:1;
+	} s;
+	struct cvmx_gmxx_rxx_rx_inbnd_s cn30xx;
+	struct cvmx_gmxx_rxx_rx_inbnd_s cn31xx;
+	struct cvmx_gmxx_rxx_rx_inbnd_s cn38xx;
+	struct cvmx_gmxx_rxx_rx_inbnd_s cn38xxp2;
+	struct cvmx_gmxx_rxx_rx_inbnd_s cn50xx;
+	struct cvmx_gmxx_rxx_rx_inbnd_s cn58xx;
+	struct cvmx_gmxx_rxx_rx_inbnd_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_stats_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_stats_ctl_s {
+		uint64_t reserved_1_63:63;
+		uint64_t rd_clr:1;
+	} s;
+	struct cvmx_gmxx_rxx_stats_ctl_s cn30xx;
+	struct cvmx_gmxx_rxx_stats_ctl_s cn31xx;
+	struct cvmx_gmxx_rxx_stats_ctl_s cn38xx;
+	struct cvmx_gmxx_rxx_stats_ctl_s cn38xxp2;
+	struct cvmx_gmxx_rxx_stats_ctl_s cn50xx;
+	struct cvmx_gmxx_rxx_stats_ctl_s cn52xx;
+	struct cvmx_gmxx_rxx_stats_ctl_s cn52xxp1;
+	struct cvmx_gmxx_rxx_stats_ctl_s cn56xx;
+	struct cvmx_gmxx_rxx_stats_ctl_s cn56xxp1;
+	struct cvmx_gmxx_rxx_stats_ctl_s cn58xx;
+	struct cvmx_gmxx_rxx_stats_ctl_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_stats_octs {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_stats_octs_s {
+		uint64_t reserved_48_63:16;
+		uint64_t cnt:48;
+	} s;
+	struct cvmx_gmxx_rxx_stats_octs_s cn30xx;
+	struct cvmx_gmxx_rxx_stats_octs_s cn31xx;
+	struct cvmx_gmxx_rxx_stats_octs_s cn38xx;
+	struct cvmx_gmxx_rxx_stats_octs_s cn38xxp2;
+	struct cvmx_gmxx_rxx_stats_octs_s cn50xx;
+	struct cvmx_gmxx_rxx_stats_octs_s cn52xx;
+	struct cvmx_gmxx_rxx_stats_octs_s cn52xxp1;
+	struct cvmx_gmxx_rxx_stats_octs_s cn56xx;
+	struct cvmx_gmxx_rxx_stats_octs_s cn56xxp1;
+	struct cvmx_gmxx_rxx_stats_octs_s cn58xx;
+	struct cvmx_gmxx_rxx_stats_octs_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_stats_octs_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s {
+		uint64_t reserved_48_63:16;
+		uint64_t cnt:48;
+	} s;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s cn30xx;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s cn31xx;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s cn38xx;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s cn38xxp2;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s cn50xx;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s cn52xx;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s cn52xxp1;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s cn56xx;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s cn56xxp1;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s cn58xx;
+	struct cvmx_gmxx_rxx_stats_octs_ctl_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_stats_octs_dmac {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s {
+		uint64_t reserved_48_63:16;
+		uint64_t cnt:48;
+	} s;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s cn30xx;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s cn31xx;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s cn38xx;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s cn38xxp2;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s cn50xx;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s cn52xx;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s cn52xxp1;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s cn56xx;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s cn56xxp1;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s cn58xx;
+	struct cvmx_gmxx_rxx_stats_octs_dmac_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_stats_octs_drp {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s {
+		uint64_t reserved_48_63:16;
+		uint64_t cnt:48;
+	} s;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s cn30xx;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s cn31xx;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s cn38xx;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s cn38xxp2;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s cn50xx;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s cn52xx;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s cn52xxp1;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s cn56xx;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s cn56xxp1;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s cn58xx;
+	struct cvmx_gmxx_rxx_stats_octs_drp_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_stats_pkts {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_stats_pkts_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_gmxx_rxx_stats_pkts_s cn30xx;
+	struct cvmx_gmxx_rxx_stats_pkts_s cn31xx;
+	struct cvmx_gmxx_rxx_stats_pkts_s cn38xx;
+	struct cvmx_gmxx_rxx_stats_pkts_s cn38xxp2;
+	struct cvmx_gmxx_rxx_stats_pkts_s cn50xx;
+	struct cvmx_gmxx_rxx_stats_pkts_s cn52xx;
+	struct cvmx_gmxx_rxx_stats_pkts_s cn52xxp1;
+	struct cvmx_gmxx_rxx_stats_pkts_s cn56xx;
+	struct cvmx_gmxx_rxx_stats_pkts_s cn56xxp1;
+	struct cvmx_gmxx_rxx_stats_pkts_s cn58xx;
+	struct cvmx_gmxx_rxx_stats_pkts_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_stats_pkts_bad {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s cn30xx;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s cn31xx;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s cn38xx;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s cn38xxp2;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s cn50xx;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s cn52xx;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s cn52xxp1;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s cn56xx;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s cn56xxp1;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s cn58xx;
+	struct cvmx_gmxx_rxx_stats_pkts_bad_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_stats_pkts_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s cn30xx;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s cn31xx;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s cn38xx;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s cn38xxp2;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s cn50xx;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s cn52xx;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s cn52xxp1;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s cn56xx;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s cn56xxp1;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s cn58xx;
+	struct cvmx_gmxx_rxx_stats_pkts_ctl_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_stats_pkts_dmac {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s cn30xx;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s cn31xx;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s cn38xx;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s cn38xxp2;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s cn50xx;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s cn52xx;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s cn52xxp1;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s cn56xx;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s cn56xxp1;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s cn58xx;
+	struct cvmx_gmxx_rxx_stats_pkts_dmac_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_stats_pkts_drp {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s cn30xx;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s cn31xx;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s cn38xx;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s cn38xxp2;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s cn50xx;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s cn52xx;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s cn52xxp1;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s cn56xx;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s cn56xxp1;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s cn58xx;
+	struct cvmx_gmxx_rxx_stats_pkts_drp_s cn58xxp1;
+};
+
+union cvmx_gmxx_rxx_udd_skp {
+	uint64_t u64;
+	struct cvmx_gmxx_rxx_udd_skp_s {
+		uint64_t reserved_9_63:55;
+		uint64_t fcssel:1;
+		uint64_t reserved_7_7:1;
+		uint64_t len:7;
+	} s;
+	struct cvmx_gmxx_rxx_udd_skp_s cn30xx;
+	struct cvmx_gmxx_rxx_udd_skp_s cn31xx;
+	struct cvmx_gmxx_rxx_udd_skp_s cn38xx;
+	struct cvmx_gmxx_rxx_udd_skp_s cn38xxp2;
+	struct cvmx_gmxx_rxx_udd_skp_s cn50xx;
+	struct cvmx_gmxx_rxx_udd_skp_s cn52xx;
+	struct cvmx_gmxx_rxx_udd_skp_s cn52xxp1;
+	struct cvmx_gmxx_rxx_udd_skp_s cn56xx;
+	struct cvmx_gmxx_rxx_udd_skp_s cn56xxp1;
+	struct cvmx_gmxx_rxx_udd_skp_s cn58xx;
+	struct cvmx_gmxx_rxx_udd_skp_s cn58xxp1;
+};
+
+union cvmx_gmxx_rx_bp_dropx {
+	uint64_t u64;
+	struct cvmx_gmxx_rx_bp_dropx_s {
+		uint64_t reserved_6_63:58;
+		uint64_t mark:6;
+	} s;
+	struct cvmx_gmxx_rx_bp_dropx_s cn30xx;
+	struct cvmx_gmxx_rx_bp_dropx_s cn31xx;
+	struct cvmx_gmxx_rx_bp_dropx_s cn38xx;
+	struct cvmx_gmxx_rx_bp_dropx_s cn38xxp2;
+	struct cvmx_gmxx_rx_bp_dropx_s cn50xx;
+	struct cvmx_gmxx_rx_bp_dropx_s cn52xx;
+	struct cvmx_gmxx_rx_bp_dropx_s cn52xxp1;
+	struct cvmx_gmxx_rx_bp_dropx_s cn56xx;
+	struct cvmx_gmxx_rx_bp_dropx_s cn56xxp1;
+	struct cvmx_gmxx_rx_bp_dropx_s cn58xx;
+	struct cvmx_gmxx_rx_bp_dropx_s cn58xxp1;
+};
+
+union cvmx_gmxx_rx_bp_offx {
+	uint64_t u64;
+	struct cvmx_gmxx_rx_bp_offx_s {
+		uint64_t reserved_6_63:58;
+		uint64_t mark:6;
+	} s;
+	struct cvmx_gmxx_rx_bp_offx_s cn30xx;
+	struct cvmx_gmxx_rx_bp_offx_s cn31xx;
+	struct cvmx_gmxx_rx_bp_offx_s cn38xx;
+	struct cvmx_gmxx_rx_bp_offx_s cn38xxp2;
+	struct cvmx_gmxx_rx_bp_offx_s cn50xx;
+	struct cvmx_gmxx_rx_bp_offx_s cn52xx;
+	struct cvmx_gmxx_rx_bp_offx_s cn52xxp1;
+	struct cvmx_gmxx_rx_bp_offx_s cn56xx;
+	struct cvmx_gmxx_rx_bp_offx_s cn56xxp1;
+	struct cvmx_gmxx_rx_bp_offx_s cn58xx;
+	struct cvmx_gmxx_rx_bp_offx_s cn58xxp1;
+};
+
+union cvmx_gmxx_rx_bp_onx {
+	uint64_t u64;
+	struct cvmx_gmxx_rx_bp_onx_s {
+		uint64_t reserved_9_63:55;
+		uint64_t mark:9;
+	} s;
+	struct cvmx_gmxx_rx_bp_onx_s cn30xx;
+	struct cvmx_gmxx_rx_bp_onx_s cn31xx;
+	struct cvmx_gmxx_rx_bp_onx_s cn38xx;
+	struct cvmx_gmxx_rx_bp_onx_s cn38xxp2;
+	struct cvmx_gmxx_rx_bp_onx_s cn50xx;
+	struct cvmx_gmxx_rx_bp_onx_s cn52xx;
+	struct cvmx_gmxx_rx_bp_onx_s cn52xxp1;
+	struct cvmx_gmxx_rx_bp_onx_s cn56xx;
+	struct cvmx_gmxx_rx_bp_onx_s cn56xxp1;
+	struct cvmx_gmxx_rx_bp_onx_s cn58xx;
+	struct cvmx_gmxx_rx_bp_onx_s cn58xxp1;
+};
+
+union cvmx_gmxx_rx_hg2_status {
+	uint64_t u64;
+	struct cvmx_gmxx_rx_hg2_status_s {
+		uint64_t reserved_48_63:16;
+		uint64_t phtim2go:16;
+		uint64_t xof:16;
+		uint64_t lgtim2go:16;
+	} s;
+	struct cvmx_gmxx_rx_hg2_status_s cn52xx;
+	struct cvmx_gmxx_rx_hg2_status_s cn52xxp1;
+	struct cvmx_gmxx_rx_hg2_status_s cn56xx;
+};
+
+union cvmx_gmxx_rx_pass_en {
+	uint64_t u64;
+	struct cvmx_gmxx_rx_pass_en_s {
+		uint64_t reserved_16_63:48;
+		uint64_t en:16;
+	} s;
+	struct cvmx_gmxx_rx_pass_en_s cn38xx;
+	struct cvmx_gmxx_rx_pass_en_s cn38xxp2;
+	struct cvmx_gmxx_rx_pass_en_s cn58xx;
+	struct cvmx_gmxx_rx_pass_en_s cn58xxp1;
+};
+
+union cvmx_gmxx_rx_pass_mapx {
+	uint64_t u64;
+	struct cvmx_gmxx_rx_pass_mapx_s {
+		uint64_t reserved_4_63:60;
+		uint64_t dprt:4;
+	} s;
+	struct cvmx_gmxx_rx_pass_mapx_s cn38xx;
+	struct cvmx_gmxx_rx_pass_mapx_s cn38xxp2;
+	struct cvmx_gmxx_rx_pass_mapx_s cn58xx;
+	struct cvmx_gmxx_rx_pass_mapx_s cn58xxp1;
+};
+
+union cvmx_gmxx_rx_prt_info {
+	uint64_t u64;
+	struct cvmx_gmxx_rx_prt_info_s {
+		uint64_t reserved_32_63:32;
+		uint64_t drop:16;
+		uint64_t commit:16;
+	} s;
+	struct cvmx_gmxx_rx_prt_info_cn30xx {
+		uint64_t reserved_19_63:45;
+		uint64_t drop:3;
+		uint64_t reserved_3_15:13;
+		uint64_t commit:3;
+	} cn30xx;
+	struct cvmx_gmxx_rx_prt_info_cn30xx cn31xx;
+	struct cvmx_gmxx_rx_prt_info_s cn38xx;
+	struct cvmx_gmxx_rx_prt_info_cn30xx cn50xx;
+	struct cvmx_gmxx_rx_prt_info_cn52xx {
+		uint64_t reserved_20_63:44;
+		uint64_t drop:4;
+		uint64_t reserved_4_15:12;
+		uint64_t commit:4;
+	} cn52xx;
+	struct cvmx_gmxx_rx_prt_info_cn52xx cn52xxp1;
+	struct cvmx_gmxx_rx_prt_info_cn52xx cn56xx;
+	struct cvmx_gmxx_rx_prt_info_cn52xx cn56xxp1;
+	struct cvmx_gmxx_rx_prt_info_s cn58xx;
+	struct cvmx_gmxx_rx_prt_info_s cn58xxp1;
+};
+
+union cvmx_gmxx_rx_prts {
+	uint64_t u64;
+	struct cvmx_gmxx_rx_prts_s {
+		uint64_t reserved_3_63:61;
+		uint64_t prts:3;
+	} s;
+	struct cvmx_gmxx_rx_prts_s cn30xx;
+	struct cvmx_gmxx_rx_prts_s cn31xx;
+	struct cvmx_gmxx_rx_prts_s cn38xx;
+	struct cvmx_gmxx_rx_prts_s cn38xxp2;
+	struct cvmx_gmxx_rx_prts_s cn50xx;
+	struct cvmx_gmxx_rx_prts_s cn52xx;
+	struct cvmx_gmxx_rx_prts_s cn52xxp1;
+	struct cvmx_gmxx_rx_prts_s cn56xx;
+	struct cvmx_gmxx_rx_prts_s cn56xxp1;
+	struct cvmx_gmxx_rx_prts_s cn58xx;
+	struct cvmx_gmxx_rx_prts_s cn58xxp1;
+};
+
+union cvmx_gmxx_rx_tx_status {
+	uint64_t u64;
+	struct cvmx_gmxx_rx_tx_status_s {
+		uint64_t reserved_7_63:57;
+		uint64_t tx:3;
+		uint64_t reserved_3_3:1;
+		uint64_t rx:3;
+	} s;
+	struct cvmx_gmxx_rx_tx_status_s cn30xx;
+	struct cvmx_gmxx_rx_tx_status_s cn31xx;
+	struct cvmx_gmxx_rx_tx_status_s cn50xx;
+};
+
+union cvmx_gmxx_rx_xaui_bad_col {
+	uint64_t u64;
+	struct cvmx_gmxx_rx_xaui_bad_col_s {
+		uint64_t reserved_40_63:24;
+		uint64_t val:1;
+		uint64_t state:3;
+		uint64_t lane_rxc:4;
+		uint64_t lane_rxd:32;
+	} s;
+	struct cvmx_gmxx_rx_xaui_bad_col_s cn52xx;
+	struct cvmx_gmxx_rx_xaui_bad_col_s cn52xxp1;
+	struct cvmx_gmxx_rx_xaui_bad_col_s cn56xx;
+	struct cvmx_gmxx_rx_xaui_bad_col_s cn56xxp1;
+};
+
+union cvmx_gmxx_rx_xaui_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_rx_xaui_ctl_s {
+		uint64_t reserved_2_63:62;
+		uint64_t status:2;
+	} s;
+	struct cvmx_gmxx_rx_xaui_ctl_s cn52xx;
+	struct cvmx_gmxx_rx_xaui_ctl_s cn52xxp1;
+	struct cvmx_gmxx_rx_xaui_ctl_s cn56xx;
+	struct cvmx_gmxx_rx_xaui_ctl_s cn56xxp1;
+};
+
+union cvmx_gmxx_smacx {
+	uint64_t u64;
+	struct cvmx_gmxx_smacx_s {
+		uint64_t reserved_48_63:16;
+		uint64_t smac:48;
+	} s;
+	struct cvmx_gmxx_smacx_s cn30xx;
+	struct cvmx_gmxx_smacx_s cn31xx;
+	struct cvmx_gmxx_smacx_s cn38xx;
+	struct cvmx_gmxx_smacx_s cn38xxp2;
+	struct cvmx_gmxx_smacx_s cn50xx;
+	struct cvmx_gmxx_smacx_s cn52xx;
+	struct cvmx_gmxx_smacx_s cn52xxp1;
+	struct cvmx_gmxx_smacx_s cn56xx;
+	struct cvmx_gmxx_smacx_s cn56xxp1;
+	struct cvmx_gmxx_smacx_s cn58xx;
+	struct cvmx_gmxx_smacx_s cn58xxp1;
+};
+
+union cvmx_gmxx_stat_bp {
+	uint64_t u64;
+	struct cvmx_gmxx_stat_bp_s {
+		uint64_t reserved_17_63:47;
+		uint64_t bp:1;
+		uint64_t cnt:16;
+	} s;
+	struct cvmx_gmxx_stat_bp_s cn30xx;
+	struct cvmx_gmxx_stat_bp_s cn31xx;
+	struct cvmx_gmxx_stat_bp_s cn38xx;
+	struct cvmx_gmxx_stat_bp_s cn38xxp2;
+	struct cvmx_gmxx_stat_bp_s cn50xx;
+	struct cvmx_gmxx_stat_bp_s cn52xx;
+	struct cvmx_gmxx_stat_bp_s cn52xxp1;
+	struct cvmx_gmxx_stat_bp_s cn56xx;
+	struct cvmx_gmxx_stat_bp_s cn56xxp1;
+	struct cvmx_gmxx_stat_bp_s cn58xx;
+	struct cvmx_gmxx_stat_bp_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_append {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_append_s {
+		uint64_t reserved_4_63:60;
+		uint64_t force_fcs:1;
+		uint64_t fcs:1;
+		uint64_t pad:1;
+		uint64_t preamble:1;
+	} s;
+	struct cvmx_gmxx_txx_append_s cn30xx;
+	struct cvmx_gmxx_txx_append_s cn31xx;
+	struct cvmx_gmxx_txx_append_s cn38xx;
+	struct cvmx_gmxx_txx_append_s cn38xxp2;
+	struct cvmx_gmxx_txx_append_s cn50xx;
+	struct cvmx_gmxx_txx_append_s cn52xx;
+	struct cvmx_gmxx_txx_append_s cn52xxp1;
+	struct cvmx_gmxx_txx_append_s cn56xx;
+	struct cvmx_gmxx_txx_append_s cn56xxp1;
+	struct cvmx_gmxx_txx_append_s cn58xx;
+	struct cvmx_gmxx_txx_append_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_burst {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_burst_s {
+		uint64_t reserved_16_63:48;
+		uint64_t burst:16;
+	} s;
+	struct cvmx_gmxx_txx_burst_s cn30xx;
+	struct cvmx_gmxx_txx_burst_s cn31xx;
+	struct cvmx_gmxx_txx_burst_s cn38xx;
+	struct cvmx_gmxx_txx_burst_s cn38xxp2;
+	struct cvmx_gmxx_txx_burst_s cn50xx;
+	struct cvmx_gmxx_txx_burst_s cn52xx;
+	struct cvmx_gmxx_txx_burst_s cn52xxp1;
+	struct cvmx_gmxx_txx_burst_s cn56xx;
+	struct cvmx_gmxx_txx_burst_s cn56xxp1;
+	struct cvmx_gmxx_txx_burst_s cn58xx;
+	struct cvmx_gmxx_txx_burst_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_cbfc_xoff {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_cbfc_xoff_s {
+		uint64_t reserved_16_63:48;
+		uint64_t xoff:16;
+	} s;
+	struct cvmx_gmxx_txx_cbfc_xoff_s cn52xx;
+	struct cvmx_gmxx_txx_cbfc_xoff_s cn56xx;
+};
+
+union cvmx_gmxx_txx_cbfc_xon {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_cbfc_xon_s {
+		uint64_t reserved_16_63:48;
+		uint64_t xon:16;
+	} s;
+	struct cvmx_gmxx_txx_cbfc_xon_s cn52xx;
+	struct cvmx_gmxx_txx_cbfc_xon_s cn56xx;
+};
+
+union cvmx_gmxx_txx_clk {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_clk_s {
+		uint64_t reserved_6_63:58;
+		uint64_t clk_cnt:6;
+	} s;
+	struct cvmx_gmxx_txx_clk_s cn30xx;
+	struct cvmx_gmxx_txx_clk_s cn31xx;
+	struct cvmx_gmxx_txx_clk_s cn38xx;
+	struct cvmx_gmxx_txx_clk_s cn38xxp2;
+	struct cvmx_gmxx_txx_clk_s cn50xx;
+	struct cvmx_gmxx_txx_clk_s cn58xx;
+	struct cvmx_gmxx_txx_clk_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_ctl_s {
+		uint64_t reserved_2_63:62;
+		uint64_t xsdef_en:1;
+		uint64_t xscol_en:1;
+	} s;
+	struct cvmx_gmxx_txx_ctl_s cn30xx;
+	struct cvmx_gmxx_txx_ctl_s cn31xx;
+	struct cvmx_gmxx_txx_ctl_s cn38xx;
+	struct cvmx_gmxx_txx_ctl_s cn38xxp2;
+	struct cvmx_gmxx_txx_ctl_s cn50xx;
+	struct cvmx_gmxx_txx_ctl_s cn52xx;
+	struct cvmx_gmxx_txx_ctl_s cn52xxp1;
+	struct cvmx_gmxx_txx_ctl_s cn56xx;
+	struct cvmx_gmxx_txx_ctl_s cn56xxp1;
+	struct cvmx_gmxx_txx_ctl_s cn58xx;
+	struct cvmx_gmxx_txx_ctl_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_min_pkt {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_min_pkt_s {
+		uint64_t reserved_8_63:56;
+		uint64_t min_size:8;
+	} s;
+	struct cvmx_gmxx_txx_min_pkt_s cn30xx;
+	struct cvmx_gmxx_txx_min_pkt_s cn31xx;
+	struct cvmx_gmxx_txx_min_pkt_s cn38xx;
+	struct cvmx_gmxx_txx_min_pkt_s cn38xxp2;
+	struct cvmx_gmxx_txx_min_pkt_s cn50xx;
+	struct cvmx_gmxx_txx_min_pkt_s cn52xx;
+	struct cvmx_gmxx_txx_min_pkt_s cn52xxp1;
+	struct cvmx_gmxx_txx_min_pkt_s cn56xx;
+	struct cvmx_gmxx_txx_min_pkt_s cn56xxp1;
+	struct cvmx_gmxx_txx_min_pkt_s cn58xx;
+	struct cvmx_gmxx_txx_min_pkt_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_pause_pkt_interval {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s {
+		uint64_t reserved_16_63:48;
+		uint64_t interval:16;
+	} s;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s cn30xx;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s cn31xx;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s cn38xx;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s cn38xxp2;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s cn50xx;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s cn52xx;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s cn52xxp1;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s cn56xx;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s cn56xxp1;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s cn58xx;
+	struct cvmx_gmxx_txx_pause_pkt_interval_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_pause_pkt_time {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_pause_pkt_time_s {
+		uint64_t reserved_16_63:48;
+		uint64_t time:16;
+	} s;
+	struct cvmx_gmxx_txx_pause_pkt_time_s cn30xx;
+	struct cvmx_gmxx_txx_pause_pkt_time_s cn31xx;
+	struct cvmx_gmxx_txx_pause_pkt_time_s cn38xx;
+	struct cvmx_gmxx_txx_pause_pkt_time_s cn38xxp2;
+	struct cvmx_gmxx_txx_pause_pkt_time_s cn50xx;
+	struct cvmx_gmxx_txx_pause_pkt_time_s cn52xx;
+	struct cvmx_gmxx_txx_pause_pkt_time_s cn52xxp1;
+	struct cvmx_gmxx_txx_pause_pkt_time_s cn56xx;
+	struct cvmx_gmxx_txx_pause_pkt_time_s cn56xxp1;
+	struct cvmx_gmxx_txx_pause_pkt_time_s cn58xx;
+	struct cvmx_gmxx_txx_pause_pkt_time_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_pause_togo {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_pause_togo_s {
+		uint64_t reserved_32_63:32;
+		uint64_t msg_time:16;
+		uint64_t time:16;
+	} s;
+	struct cvmx_gmxx_txx_pause_togo_cn30xx {
+		uint64_t reserved_16_63:48;
+		uint64_t time:16;
+	} cn30xx;
+	struct cvmx_gmxx_txx_pause_togo_cn30xx cn31xx;
+	struct cvmx_gmxx_txx_pause_togo_cn30xx cn38xx;
+	struct cvmx_gmxx_txx_pause_togo_cn30xx cn38xxp2;
+	struct cvmx_gmxx_txx_pause_togo_cn30xx cn50xx;
+	struct cvmx_gmxx_txx_pause_togo_s cn52xx;
+	struct cvmx_gmxx_txx_pause_togo_s cn52xxp1;
+	struct cvmx_gmxx_txx_pause_togo_s cn56xx;
+	struct cvmx_gmxx_txx_pause_togo_cn30xx cn56xxp1;
+	struct cvmx_gmxx_txx_pause_togo_cn30xx cn58xx;
+	struct cvmx_gmxx_txx_pause_togo_cn30xx cn58xxp1;
+};
+
+union cvmx_gmxx_txx_pause_zero {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_pause_zero_s {
+		uint64_t reserved_1_63:63;
+		uint64_t send:1;
+	} s;
+	struct cvmx_gmxx_txx_pause_zero_s cn30xx;
+	struct cvmx_gmxx_txx_pause_zero_s cn31xx;
+	struct cvmx_gmxx_txx_pause_zero_s cn38xx;
+	struct cvmx_gmxx_txx_pause_zero_s cn38xxp2;
+	struct cvmx_gmxx_txx_pause_zero_s cn50xx;
+	struct cvmx_gmxx_txx_pause_zero_s cn52xx;
+	struct cvmx_gmxx_txx_pause_zero_s cn52xxp1;
+	struct cvmx_gmxx_txx_pause_zero_s cn56xx;
+	struct cvmx_gmxx_txx_pause_zero_s cn56xxp1;
+	struct cvmx_gmxx_txx_pause_zero_s cn58xx;
+	struct cvmx_gmxx_txx_pause_zero_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_sgmii_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_sgmii_ctl_s {
+		uint64_t reserved_1_63:63;
+		uint64_t align:1;
+	} s;
+	struct cvmx_gmxx_txx_sgmii_ctl_s cn52xx;
+	struct cvmx_gmxx_txx_sgmii_ctl_s cn52xxp1;
+	struct cvmx_gmxx_txx_sgmii_ctl_s cn56xx;
+	struct cvmx_gmxx_txx_sgmii_ctl_s cn56xxp1;
+};
+
+union cvmx_gmxx_txx_slot {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_slot_s {
+		uint64_t reserved_10_63:54;
+		uint64_t slot:10;
+	} s;
+	struct cvmx_gmxx_txx_slot_s cn30xx;
+	struct cvmx_gmxx_txx_slot_s cn31xx;
+	struct cvmx_gmxx_txx_slot_s cn38xx;
+	struct cvmx_gmxx_txx_slot_s cn38xxp2;
+	struct cvmx_gmxx_txx_slot_s cn50xx;
+	struct cvmx_gmxx_txx_slot_s cn52xx;
+	struct cvmx_gmxx_txx_slot_s cn52xxp1;
+	struct cvmx_gmxx_txx_slot_s cn56xx;
+	struct cvmx_gmxx_txx_slot_s cn56xxp1;
+	struct cvmx_gmxx_txx_slot_s cn58xx;
+	struct cvmx_gmxx_txx_slot_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_soft_pause {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_soft_pause_s {
+		uint64_t reserved_16_63:48;
+		uint64_t time:16;
+	} s;
+	struct cvmx_gmxx_txx_soft_pause_s cn30xx;
+	struct cvmx_gmxx_txx_soft_pause_s cn31xx;
+	struct cvmx_gmxx_txx_soft_pause_s cn38xx;
+	struct cvmx_gmxx_txx_soft_pause_s cn38xxp2;
+	struct cvmx_gmxx_txx_soft_pause_s cn50xx;
+	struct cvmx_gmxx_txx_soft_pause_s cn52xx;
+	struct cvmx_gmxx_txx_soft_pause_s cn52xxp1;
+	struct cvmx_gmxx_txx_soft_pause_s cn56xx;
+	struct cvmx_gmxx_txx_soft_pause_s cn56xxp1;
+	struct cvmx_gmxx_txx_soft_pause_s cn58xx;
+	struct cvmx_gmxx_txx_soft_pause_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_stat0 {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_stat0_s {
+		uint64_t xsdef:32;
+		uint64_t xscol:32;
+	} s;
+	struct cvmx_gmxx_txx_stat0_s cn30xx;
+	struct cvmx_gmxx_txx_stat0_s cn31xx;
+	struct cvmx_gmxx_txx_stat0_s cn38xx;
+	struct cvmx_gmxx_txx_stat0_s cn38xxp2;
+	struct cvmx_gmxx_txx_stat0_s cn50xx;
+	struct cvmx_gmxx_txx_stat0_s cn52xx;
+	struct cvmx_gmxx_txx_stat0_s cn52xxp1;
+	struct cvmx_gmxx_txx_stat0_s cn56xx;
+	struct cvmx_gmxx_txx_stat0_s cn56xxp1;
+	struct cvmx_gmxx_txx_stat0_s cn58xx;
+	struct cvmx_gmxx_txx_stat0_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_stat1 {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_stat1_s {
+		uint64_t scol:32;
+		uint64_t mcol:32;
+	} s;
+	struct cvmx_gmxx_txx_stat1_s cn30xx;
+	struct cvmx_gmxx_txx_stat1_s cn31xx;
+	struct cvmx_gmxx_txx_stat1_s cn38xx;
+	struct cvmx_gmxx_txx_stat1_s cn38xxp2;
+	struct cvmx_gmxx_txx_stat1_s cn50xx;
+	struct cvmx_gmxx_txx_stat1_s cn52xx;
+	struct cvmx_gmxx_txx_stat1_s cn52xxp1;
+	struct cvmx_gmxx_txx_stat1_s cn56xx;
+	struct cvmx_gmxx_txx_stat1_s cn56xxp1;
+	struct cvmx_gmxx_txx_stat1_s cn58xx;
+	struct cvmx_gmxx_txx_stat1_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_stat2 {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_stat2_s {
+		uint64_t reserved_48_63:16;
+		uint64_t octs:48;
+	} s;
+	struct cvmx_gmxx_txx_stat2_s cn30xx;
+	struct cvmx_gmxx_txx_stat2_s cn31xx;
+	struct cvmx_gmxx_txx_stat2_s cn38xx;
+	struct cvmx_gmxx_txx_stat2_s cn38xxp2;
+	struct cvmx_gmxx_txx_stat2_s cn50xx;
+	struct cvmx_gmxx_txx_stat2_s cn52xx;
+	struct cvmx_gmxx_txx_stat2_s cn52xxp1;
+	struct cvmx_gmxx_txx_stat2_s cn56xx;
+	struct cvmx_gmxx_txx_stat2_s cn56xxp1;
+	struct cvmx_gmxx_txx_stat2_s cn58xx;
+	struct cvmx_gmxx_txx_stat2_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_stat3 {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_stat3_s {
+		uint64_t reserved_32_63:32;
+		uint64_t pkts:32;
+	} s;
+	struct cvmx_gmxx_txx_stat3_s cn30xx;
+	struct cvmx_gmxx_txx_stat3_s cn31xx;
+	struct cvmx_gmxx_txx_stat3_s cn38xx;
+	struct cvmx_gmxx_txx_stat3_s cn38xxp2;
+	struct cvmx_gmxx_txx_stat3_s cn50xx;
+	struct cvmx_gmxx_txx_stat3_s cn52xx;
+	struct cvmx_gmxx_txx_stat3_s cn52xxp1;
+	struct cvmx_gmxx_txx_stat3_s cn56xx;
+	struct cvmx_gmxx_txx_stat3_s cn56xxp1;
+	struct cvmx_gmxx_txx_stat3_s cn58xx;
+	struct cvmx_gmxx_txx_stat3_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_stat4 {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_stat4_s {
+		uint64_t hist1:32;
+		uint64_t hist0:32;
+	} s;
+	struct cvmx_gmxx_txx_stat4_s cn30xx;
+	struct cvmx_gmxx_txx_stat4_s cn31xx;
+	struct cvmx_gmxx_txx_stat4_s cn38xx;
+	struct cvmx_gmxx_txx_stat4_s cn38xxp2;
+	struct cvmx_gmxx_txx_stat4_s cn50xx;
+	struct cvmx_gmxx_txx_stat4_s cn52xx;
+	struct cvmx_gmxx_txx_stat4_s cn52xxp1;
+	struct cvmx_gmxx_txx_stat4_s cn56xx;
+	struct cvmx_gmxx_txx_stat4_s cn56xxp1;
+	struct cvmx_gmxx_txx_stat4_s cn58xx;
+	struct cvmx_gmxx_txx_stat4_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_stat5 {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_stat5_s {
+		uint64_t hist3:32;
+		uint64_t hist2:32;
+	} s;
+	struct cvmx_gmxx_txx_stat5_s cn30xx;
+	struct cvmx_gmxx_txx_stat5_s cn31xx;
+	struct cvmx_gmxx_txx_stat5_s cn38xx;
+	struct cvmx_gmxx_txx_stat5_s cn38xxp2;
+	struct cvmx_gmxx_txx_stat5_s cn50xx;
+	struct cvmx_gmxx_txx_stat5_s cn52xx;
+	struct cvmx_gmxx_txx_stat5_s cn52xxp1;
+	struct cvmx_gmxx_txx_stat5_s cn56xx;
+	struct cvmx_gmxx_txx_stat5_s cn56xxp1;
+	struct cvmx_gmxx_txx_stat5_s cn58xx;
+	struct cvmx_gmxx_txx_stat5_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_stat6 {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_stat6_s {
+		uint64_t hist5:32;
+		uint64_t hist4:32;
+	} s;
+	struct cvmx_gmxx_txx_stat6_s cn30xx;
+	struct cvmx_gmxx_txx_stat6_s cn31xx;
+	struct cvmx_gmxx_txx_stat6_s cn38xx;
+	struct cvmx_gmxx_txx_stat6_s cn38xxp2;
+	struct cvmx_gmxx_txx_stat6_s cn50xx;
+	struct cvmx_gmxx_txx_stat6_s cn52xx;
+	struct cvmx_gmxx_txx_stat6_s cn52xxp1;
+	struct cvmx_gmxx_txx_stat6_s cn56xx;
+	struct cvmx_gmxx_txx_stat6_s cn56xxp1;
+	struct cvmx_gmxx_txx_stat6_s cn58xx;
+	struct cvmx_gmxx_txx_stat6_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_stat7 {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_stat7_s {
+		uint64_t hist7:32;
+		uint64_t hist6:32;
+	} s;
+	struct cvmx_gmxx_txx_stat7_s cn30xx;
+	struct cvmx_gmxx_txx_stat7_s cn31xx;
+	struct cvmx_gmxx_txx_stat7_s cn38xx;
+	struct cvmx_gmxx_txx_stat7_s cn38xxp2;
+	struct cvmx_gmxx_txx_stat7_s cn50xx;
+	struct cvmx_gmxx_txx_stat7_s cn52xx;
+	struct cvmx_gmxx_txx_stat7_s cn52xxp1;
+	struct cvmx_gmxx_txx_stat7_s cn56xx;
+	struct cvmx_gmxx_txx_stat7_s cn56xxp1;
+	struct cvmx_gmxx_txx_stat7_s cn58xx;
+	struct cvmx_gmxx_txx_stat7_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_stat8 {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_stat8_s {
+		uint64_t mcst:32;
+		uint64_t bcst:32;
+	} s;
+	struct cvmx_gmxx_txx_stat8_s cn30xx;
+	struct cvmx_gmxx_txx_stat8_s cn31xx;
+	struct cvmx_gmxx_txx_stat8_s cn38xx;
+	struct cvmx_gmxx_txx_stat8_s cn38xxp2;
+	struct cvmx_gmxx_txx_stat8_s cn50xx;
+	struct cvmx_gmxx_txx_stat8_s cn52xx;
+	struct cvmx_gmxx_txx_stat8_s cn52xxp1;
+	struct cvmx_gmxx_txx_stat8_s cn56xx;
+	struct cvmx_gmxx_txx_stat8_s cn56xxp1;
+	struct cvmx_gmxx_txx_stat8_s cn58xx;
+	struct cvmx_gmxx_txx_stat8_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_stat9 {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_stat9_s {
+		uint64_t undflw:32;
+		uint64_t ctl:32;
+	} s;
+	struct cvmx_gmxx_txx_stat9_s cn30xx;
+	struct cvmx_gmxx_txx_stat9_s cn31xx;
+	struct cvmx_gmxx_txx_stat9_s cn38xx;
+	struct cvmx_gmxx_txx_stat9_s cn38xxp2;
+	struct cvmx_gmxx_txx_stat9_s cn50xx;
+	struct cvmx_gmxx_txx_stat9_s cn52xx;
+	struct cvmx_gmxx_txx_stat9_s cn52xxp1;
+	struct cvmx_gmxx_txx_stat9_s cn56xx;
+	struct cvmx_gmxx_txx_stat9_s cn56xxp1;
+	struct cvmx_gmxx_txx_stat9_s cn58xx;
+	struct cvmx_gmxx_txx_stat9_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_stats_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_stats_ctl_s {
+		uint64_t reserved_1_63:63;
+		uint64_t rd_clr:1;
+	} s;
+	struct cvmx_gmxx_txx_stats_ctl_s cn30xx;
+	struct cvmx_gmxx_txx_stats_ctl_s cn31xx;
+	struct cvmx_gmxx_txx_stats_ctl_s cn38xx;
+	struct cvmx_gmxx_txx_stats_ctl_s cn38xxp2;
+	struct cvmx_gmxx_txx_stats_ctl_s cn50xx;
+	struct cvmx_gmxx_txx_stats_ctl_s cn52xx;
+	struct cvmx_gmxx_txx_stats_ctl_s cn52xxp1;
+	struct cvmx_gmxx_txx_stats_ctl_s cn56xx;
+	struct cvmx_gmxx_txx_stats_ctl_s cn56xxp1;
+	struct cvmx_gmxx_txx_stats_ctl_s cn58xx;
+	struct cvmx_gmxx_txx_stats_ctl_s cn58xxp1;
+};
+
+union cvmx_gmxx_txx_thresh {
+	uint64_t u64;
+	struct cvmx_gmxx_txx_thresh_s {
+		uint64_t reserved_9_63:55;
+		uint64_t cnt:9;
+	} s;
+	struct cvmx_gmxx_txx_thresh_cn30xx {
+		uint64_t reserved_7_63:57;
+		uint64_t cnt:7;
+	} cn30xx;
+	struct cvmx_gmxx_txx_thresh_cn30xx cn31xx;
+	struct cvmx_gmxx_txx_thresh_s cn38xx;
+	struct cvmx_gmxx_txx_thresh_s cn38xxp2;
+	struct cvmx_gmxx_txx_thresh_cn30xx cn50xx;
+	struct cvmx_gmxx_txx_thresh_s cn52xx;
+	struct cvmx_gmxx_txx_thresh_s cn52xxp1;
+	struct cvmx_gmxx_txx_thresh_s cn56xx;
+	struct cvmx_gmxx_txx_thresh_s cn56xxp1;
+	struct cvmx_gmxx_txx_thresh_s cn58xx;
+	struct cvmx_gmxx_txx_thresh_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_bp {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_bp_s {
+		uint64_t reserved_4_63:60;
+		uint64_t bp:4;
+	} s;
+	struct cvmx_gmxx_tx_bp_cn30xx {
+		uint64_t reserved_3_63:61;
+		uint64_t bp:3;
+	} cn30xx;
+	struct cvmx_gmxx_tx_bp_cn30xx cn31xx;
+	struct cvmx_gmxx_tx_bp_s cn38xx;
+	struct cvmx_gmxx_tx_bp_s cn38xxp2;
+	struct cvmx_gmxx_tx_bp_cn30xx cn50xx;
+	struct cvmx_gmxx_tx_bp_s cn52xx;
+	struct cvmx_gmxx_tx_bp_s cn52xxp1;
+	struct cvmx_gmxx_tx_bp_s cn56xx;
+	struct cvmx_gmxx_tx_bp_s cn56xxp1;
+	struct cvmx_gmxx_tx_bp_s cn58xx;
+	struct cvmx_gmxx_tx_bp_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_clk_mskx {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_clk_mskx_s {
+		uint64_t reserved_1_63:63;
+		uint64_t msk:1;
+	} s;
+	struct cvmx_gmxx_tx_clk_mskx_s cn30xx;
+	struct cvmx_gmxx_tx_clk_mskx_s cn50xx;
+};
+
+union cvmx_gmxx_tx_col_attempt {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_col_attempt_s {
+		uint64_t reserved_5_63:59;
+		uint64_t limit:5;
+	} s;
+	struct cvmx_gmxx_tx_col_attempt_s cn30xx;
+	struct cvmx_gmxx_tx_col_attempt_s cn31xx;
+	struct cvmx_gmxx_tx_col_attempt_s cn38xx;
+	struct cvmx_gmxx_tx_col_attempt_s cn38xxp2;
+	struct cvmx_gmxx_tx_col_attempt_s cn50xx;
+	struct cvmx_gmxx_tx_col_attempt_s cn52xx;
+	struct cvmx_gmxx_tx_col_attempt_s cn52xxp1;
+	struct cvmx_gmxx_tx_col_attempt_s cn56xx;
+	struct cvmx_gmxx_tx_col_attempt_s cn56xxp1;
+	struct cvmx_gmxx_tx_col_attempt_s cn58xx;
+	struct cvmx_gmxx_tx_col_attempt_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_corrupt {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_corrupt_s {
+		uint64_t reserved_4_63:60;
+		uint64_t corrupt:4;
+	} s;
+	struct cvmx_gmxx_tx_corrupt_cn30xx {
+		uint64_t reserved_3_63:61;
+		uint64_t corrupt:3;
+	} cn30xx;
+	struct cvmx_gmxx_tx_corrupt_cn30xx cn31xx;
+	struct cvmx_gmxx_tx_corrupt_s cn38xx;
+	struct cvmx_gmxx_tx_corrupt_s cn38xxp2;
+	struct cvmx_gmxx_tx_corrupt_cn30xx cn50xx;
+	struct cvmx_gmxx_tx_corrupt_s cn52xx;
+	struct cvmx_gmxx_tx_corrupt_s cn52xxp1;
+	struct cvmx_gmxx_tx_corrupt_s cn56xx;
+	struct cvmx_gmxx_tx_corrupt_s cn56xxp1;
+	struct cvmx_gmxx_tx_corrupt_s cn58xx;
+	struct cvmx_gmxx_tx_corrupt_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_hg2_reg1 {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_hg2_reg1_s {
+		uint64_t reserved_16_63:48;
+		uint64_t tx_xof:16;
+	} s;
+	struct cvmx_gmxx_tx_hg2_reg1_s cn52xx;
+	struct cvmx_gmxx_tx_hg2_reg1_s cn52xxp1;
+	struct cvmx_gmxx_tx_hg2_reg1_s cn56xx;
+};
+
+union cvmx_gmxx_tx_hg2_reg2 {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_hg2_reg2_s {
+		uint64_t reserved_16_63:48;
+		uint64_t tx_xon:16;
+	} s;
+	struct cvmx_gmxx_tx_hg2_reg2_s cn52xx;
+	struct cvmx_gmxx_tx_hg2_reg2_s cn52xxp1;
+	struct cvmx_gmxx_tx_hg2_reg2_s cn56xx;
+};
+
+union cvmx_gmxx_tx_ifg {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_ifg_s {
+		uint64_t reserved_8_63:56;
+		uint64_t ifg2:4;
+		uint64_t ifg1:4;
+	} s;
+	struct cvmx_gmxx_tx_ifg_s cn30xx;
+	struct cvmx_gmxx_tx_ifg_s cn31xx;
+	struct cvmx_gmxx_tx_ifg_s cn38xx;
+	struct cvmx_gmxx_tx_ifg_s cn38xxp2;
+	struct cvmx_gmxx_tx_ifg_s cn50xx;
+	struct cvmx_gmxx_tx_ifg_s cn52xx;
+	struct cvmx_gmxx_tx_ifg_s cn52xxp1;
+	struct cvmx_gmxx_tx_ifg_s cn56xx;
+	struct cvmx_gmxx_tx_ifg_s cn56xxp1;
+	struct cvmx_gmxx_tx_ifg_s cn58xx;
+	struct cvmx_gmxx_tx_ifg_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_int_en {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_int_en_s {
+		uint64_t reserved_20_63:44;
+		uint64_t late_col:4;
+		uint64_t xsdef:4;
+		uint64_t xscol:4;
+		uint64_t reserved_6_7:2;
+		uint64_t undflw:4;
+		uint64_t ncb_nxa:1;
+		uint64_t pko_nxa:1;
+	} s;
+	struct cvmx_gmxx_tx_int_en_cn30xx {
+		uint64_t reserved_19_63:45;
+		uint64_t late_col:3;
+		uint64_t reserved_15_15:1;
+		uint64_t xsdef:3;
+		uint64_t reserved_11_11:1;
+		uint64_t xscol:3;
+		uint64_t reserved_5_7:3;
+		uint64_t undflw:3;
+		uint64_t reserved_1_1:1;
+		uint64_t pko_nxa:1;
+	} cn30xx;
+	struct cvmx_gmxx_tx_int_en_cn31xx {
+		uint64_t reserved_15_63:49;
+		uint64_t xsdef:3;
+		uint64_t reserved_11_11:1;
+		uint64_t xscol:3;
+		uint64_t reserved_5_7:3;
+		uint64_t undflw:3;
+		uint64_t reserved_1_1:1;
+		uint64_t pko_nxa:1;
+	} cn31xx;
+	struct cvmx_gmxx_tx_int_en_s cn38xx;
+	struct cvmx_gmxx_tx_int_en_cn38xxp2 {
+		uint64_t reserved_16_63:48;
+		uint64_t xsdef:4;
+		uint64_t xscol:4;
+		uint64_t reserved_6_7:2;
+		uint64_t undflw:4;
+		uint64_t ncb_nxa:1;
+		uint64_t pko_nxa:1;
+	} cn38xxp2;
+	struct cvmx_gmxx_tx_int_en_cn30xx cn50xx;
+	struct cvmx_gmxx_tx_int_en_cn52xx {
+		uint64_t reserved_20_63:44;
+		uint64_t late_col:4;
+		uint64_t xsdef:4;
+		uint64_t xscol:4;
+		uint64_t reserved_6_7:2;
+		uint64_t undflw:4;
+		uint64_t reserved_1_1:1;
+		uint64_t pko_nxa:1;
+	} cn52xx;
+	struct cvmx_gmxx_tx_int_en_cn52xx cn52xxp1;
+	struct cvmx_gmxx_tx_int_en_cn52xx cn56xx;
+	struct cvmx_gmxx_tx_int_en_cn52xx cn56xxp1;
+	struct cvmx_gmxx_tx_int_en_s cn58xx;
+	struct cvmx_gmxx_tx_int_en_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_int_reg {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_int_reg_s {
+		uint64_t reserved_20_63:44;
+		uint64_t late_col:4;
+		uint64_t xsdef:4;
+		uint64_t xscol:4;
+		uint64_t reserved_6_7:2;
+		uint64_t undflw:4;
+		uint64_t ncb_nxa:1;
+		uint64_t pko_nxa:1;
+	} s;
+	struct cvmx_gmxx_tx_int_reg_cn30xx {
+		uint64_t reserved_19_63:45;
+		uint64_t late_col:3;
+		uint64_t reserved_15_15:1;
+		uint64_t xsdef:3;
+		uint64_t reserved_11_11:1;
+		uint64_t xscol:3;
+		uint64_t reserved_5_7:3;
+		uint64_t undflw:3;
+		uint64_t reserved_1_1:1;
+		uint64_t pko_nxa:1;
+	} cn30xx;
+	struct cvmx_gmxx_tx_int_reg_cn31xx {
+		uint64_t reserved_15_63:49;
+		uint64_t xsdef:3;
+		uint64_t reserved_11_11:1;
+		uint64_t xscol:3;
+		uint64_t reserved_5_7:3;
+		uint64_t undflw:3;
+		uint64_t reserved_1_1:1;
+		uint64_t pko_nxa:1;
+	} cn31xx;
+	struct cvmx_gmxx_tx_int_reg_s cn38xx;
+	struct cvmx_gmxx_tx_int_reg_cn38xxp2 {
+		uint64_t reserved_16_63:48;
+		uint64_t xsdef:4;
+		uint64_t xscol:4;
+		uint64_t reserved_6_7:2;
+		uint64_t undflw:4;
+		uint64_t ncb_nxa:1;
+		uint64_t pko_nxa:1;
+	} cn38xxp2;
+	struct cvmx_gmxx_tx_int_reg_cn30xx cn50xx;
+	struct cvmx_gmxx_tx_int_reg_cn52xx {
+		uint64_t reserved_20_63:44;
+		uint64_t late_col:4;
+		uint64_t xsdef:4;
+		uint64_t xscol:4;
+		uint64_t reserved_6_7:2;
+		uint64_t undflw:4;
+		uint64_t reserved_1_1:1;
+		uint64_t pko_nxa:1;
+	} cn52xx;
+	struct cvmx_gmxx_tx_int_reg_cn52xx cn52xxp1;
+	struct cvmx_gmxx_tx_int_reg_cn52xx cn56xx;
+	struct cvmx_gmxx_tx_int_reg_cn52xx cn56xxp1;
+	struct cvmx_gmxx_tx_int_reg_s cn58xx;
+	struct cvmx_gmxx_tx_int_reg_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_jam {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_jam_s {
+		uint64_t reserved_8_63:56;
+		uint64_t jam:8;
+	} s;
+	struct cvmx_gmxx_tx_jam_s cn30xx;
+	struct cvmx_gmxx_tx_jam_s cn31xx;
+	struct cvmx_gmxx_tx_jam_s cn38xx;
+	struct cvmx_gmxx_tx_jam_s cn38xxp2;
+	struct cvmx_gmxx_tx_jam_s cn50xx;
+	struct cvmx_gmxx_tx_jam_s cn52xx;
+	struct cvmx_gmxx_tx_jam_s cn52xxp1;
+	struct cvmx_gmxx_tx_jam_s cn56xx;
+	struct cvmx_gmxx_tx_jam_s cn56xxp1;
+	struct cvmx_gmxx_tx_jam_s cn58xx;
+	struct cvmx_gmxx_tx_jam_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_lfsr {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_lfsr_s {
+		uint64_t reserved_16_63:48;
+		uint64_t lfsr:16;
+	} s;
+	struct cvmx_gmxx_tx_lfsr_s cn30xx;
+	struct cvmx_gmxx_tx_lfsr_s cn31xx;
+	struct cvmx_gmxx_tx_lfsr_s cn38xx;
+	struct cvmx_gmxx_tx_lfsr_s cn38xxp2;
+	struct cvmx_gmxx_tx_lfsr_s cn50xx;
+	struct cvmx_gmxx_tx_lfsr_s cn52xx;
+	struct cvmx_gmxx_tx_lfsr_s cn52xxp1;
+	struct cvmx_gmxx_tx_lfsr_s cn56xx;
+	struct cvmx_gmxx_tx_lfsr_s cn56xxp1;
+	struct cvmx_gmxx_tx_lfsr_s cn58xx;
+	struct cvmx_gmxx_tx_lfsr_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_ovr_bp {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_ovr_bp_s {
+		uint64_t reserved_48_63:16;
+		uint64_t tx_prt_bp:16;
+		uint64_t reserved_12_31:20;
+		uint64_t en:4;
+		uint64_t bp:4;
+		uint64_t ign_full:4;
+	} s;
+	struct cvmx_gmxx_tx_ovr_bp_cn30xx {
+		uint64_t reserved_11_63:53;
+		uint64_t en:3;
+		uint64_t reserved_7_7:1;
+		uint64_t bp:3;
+		uint64_t reserved_3_3:1;
+		uint64_t ign_full:3;
+	} cn30xx;
+	struct cvmx_gmxx_tx_ovr_bp_cn30xx cn31xx;
+	struct cvmx_gmxx_tx_ovr_bp_cn38xx {
+		uint64_t reserved_12_63:52;
+		uint64_t en:4;
+		uint64_t bp:4;
+		uint64_t ign_full:4;
+	} cn38xx;
+	struct cvmx_gmxx_tx_ovr_bp_cn38xx cn38xxp2;
+	struct cvmx_gmxx_tx_ovr_bp_cn30xx cn50xx;
+	struct cvmx_gmxx_tx_ovr_bp_s cn52xx;
+	struct cvmx_gmxx_tx_ovr_bp_s cn52xxp1;
+	struct cvmx_gmxx_tx_ovr_bp_s cn56xx;
+	struct cvmx_gmxx_tx_ovr_bp_s cn56xxp1;
+	struct cvmx_gmxx_tx_ovr_bp_cn38xx cn58xx;
+	struct cvmx_gmxx_tx_ovr_bp_cn38xx cn58xxp1;
+};
+
+union cvmx_gmxx_tx_pause_pkt_dmac {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s {
+		uint64_t reserved_48_63:16;
+		uint64_t dmac:48;
+	} s;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s cn30xx;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s cn31xx;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s cn38xx;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s cn38xxp2;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s cn50xx;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s cn52xx;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s cn52xxp1;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s cn56xx;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s cn56xxp1;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s cn58xx;
+	struct cvmx_gmxx_tx_pause_pkt_dmac_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_pause_pkt_type {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_pause_pkt_type_s {
+		uint64_t reserved_16_63:48;
+		uint64_t type:16;
+	} s;
+	struct cvmx_gmxx_tx_pause_pkt_type_s cn30xx;
+	struct cvmx_gmxx_tx_pause_pkt_type_s cn31xx;
+	struct cvmx_gmxx_tx_pause_pkt_type_s cn38xx;
+	struct cvmx_gmxx_tx_pause_pkt_type_s cn38xxp2;
+	struct cvmx_gmxx_tx_pause_pkt_type_s cn50xx;
+	struct cvmx_gmxx_tx_pause_pkt_type_s cn52xx;
+	struct cvmx_gmxx_tx_pause_pkt_type_s cn52xxp1;
+	struct cvmx_gmxx_tx_pause_pkt_type_s cn56xx;
+	struct cvmx_gmxx_tx_pause_pkt_type_s cn56xxp1;
+	struct cvmx_gmxx_tx_pause_pkt_type_s cn58xx;
+	struct cvmx_gmxx_tx_pause_pkt_type_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_prts {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_prts_s {
+		uint64_t reserved_5_63:59;
+		uint64_t prts:5;
+	} s;
+	struct cvmx_gmxx_tx_prts_s cn30xx;
+	struct cvmx_gmxx_tx_prts_s cn31xx;
+	struct cvmx_gmxx_tx_prts_s cn38xx;
+	struct cvmx_gmxx_tx_prts_s cn38xxp2;
+	struct cvmx_gmxx_tx_prts_s cn50xx;
+	struct cvmx_gmxx_tx_prts_s cn52xx;
+	struct cvmx_gmxx_tx_prts_s cn52xxp1;
+	struct cvmx_gmxx_tx_prts_s cn56xx;
+	struct cvmx_gmxx_tx_prts_s cn56xxp1;
+	struct cvmx_gmxx_tx_prts_s cn58xx;
+	struct cvmx_gmxx_tx_prts_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_spi_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_spi_ctl_s {
+		uint64_t reserved_2_63:62;
+		uint64_t tpa_clr:1;
+		uint64_t cont_pkt:1;
+	} s;
+	struct cvmx_gmxx_tx_spi_ctl_s cn38xx;
+	struct cvmx_gmxx_tx_spi_ctl_s cn38xxp2;
+	struct cvmx_gmxx_tx_spi_ctl_s cn58xx;
+	struct cvmx_gmxx_tx_spi_ctl_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_spi_drain {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_spi_drain_s {
+		uint64_t reserved_16_63:48;
+		uint64_t drain:16;
+	} s;
+	struct cvmx_gmxx_tx_spi_drain_s cn38xx;
+	struct cvmx_gmxx_tx_spi_drain_s cn58xx;
+	struct cvmx_gmxx_tx_spi_drain_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_spi_max {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_spi_max_s {
+		uint64_t reserved_23_63:41;
+		uint64_t slice:7;
+		uint64_t max2:8;
+		uint64_t max1:8;
+	} s;
+	struct cvmx_gmxx_tx_spi_max_cn38xx {
+		uint64_t reserved_16_63:48;
+		uint64_t max2:8;
+		uint64_t max1:8;
+	} cn38xx;
+	struct cvmx_gmxx_tx_spi_max_cn38xx cn38xxp2;
+	struct cvmx_gmxx_tx_spi_max_s cn58xx;
+	struct cvmx_gmxx_tx_spi_max_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_spi_roundx {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_spi_roundx_s {
+		uint64_t reserved_16_63:48;
+		uint64_t round:16;
+	} s;
+	struct cvmx_gmxx_tx_spi_roundx_s cn58xx;
+	struct cvmx_gmxx_tx_spi_roundx_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_spi_thresh {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_spi_thresh_s {
+		uint64_t reserved_6_63:58;
+		uint64_t thresh:6;
+	} s;
+	struct cvmx_gmxx_tx_spi_thresh_s cn38xx;
+	struct cvmx_gmxx_tx_spi_thresh_s cn38xxp2;
+	struct cvmx_gmxx_tx_spi_thresh_s cn58xx;
+	struct cvmx_gmxx_tx_spi_thresh_s cn58xxp1;
+};
+
+union cvmx_gmxx_tx_xaui_ctl {
+	uint64_t u64;
+	struct cvmx_gmxx_tx_xaui_ctl_s {
+		uint64_t reserved_11_63:53;
+		uint64_t hg_pause_hgi:2;
+		uint64_t hg_en:1;
+		uint64_t reserved_7_7:1;
+		uint64_t ls_byp:1;
+		uint64_t ls:2;
+		uint64_t reserved_2_3:2;
+		uint64_t uni_en:1;
+		uint64_t dic_en:1;
+	} s;
+	struct cvmx_gmxx_tx_xaui_ctl_s cn52xx;
+	struct cvmx_gmxx_tx_xaui_ctl_s cn52xxp1;
+	struct cvmx_gmxx_tx_xaui_ctl_s cn56xx;
+	struct cvmx_gmxx_tx_xaui_ctl_s cn56xxp1;
+};
+
+union cvmx_gmxx_xaui_ext_loopback {
+	uint64_t u64;
+	struct cvmx_gmxx_xaui_ext_loopback_s {
+		uint64_t reserved_5_63:59;
+		uint64_t en:1;
+		uint64_t thresh:4;
+	} s;
+	struct cvmx_gmxx_xaui_ext_loopback_s cn52xx;
+	struct cvmx_gmxx_xaui_ext_loopback_s cn52xxp1;
+	struct cvmx_gmxx_xaui_ext_loopback_s cn56xx;
+	struct cvmx_gmxx_xaui_ext_loopback_s cn56xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-helper-board.c b/drivers/staging/octeon/cvmx-helper-board.c
new file mode 100644
index 0000000..3085e38
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-board.c
@@ -0,0 +1,706 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ *
+ * Helper functions to abstract board specific data about
+ * network ports from the rest of the cvmx-helper files.
+ */
+
+#include <asm/octeon/octeon.h>
+#include <asm/octeon/cvmx-bootinfo.h>
+
+#include "cvmx-config.h"
+
+#include "cvmx-mdio.h"
+
+#include "cvmx-helper.h"
+#include "cvmx-helper-util.h"
+#include "cvmx-helper-board.h"
+
+#include "cvmx-gmxx-defs.h"
+#include "cvmx-asxx-defs.h"
+
+/**
+ * cvmx_override_board_link_get(int ipd_port) is a function
+ * pointer. It is meant to allow customization of the process of
+ * talking to a PHY to determine link speed. It is called every
+ * time a PHY must be polled for link status. Users should set
+ * this pointer to a function before calling any cvmx-helper
+ * operations.
+ */
+cvmx_helper_link_info_t(*cvmx_override_board_link_get) (int ipd_port) =
+    NULL;
+
+/**
+ * Return the MII PHY address associated with the given IPD
+ * port. A result of -1 means there isn't a MII capable PHY
+ * connected to this port. On chips supporting multiple MII
+ * busses the bus number is encoded in bits <15:8>.
+ *
+ * This function must be modified for every new Octeon board.
+ * Internally it uses switch statements based on the cvmx_sysinfo
+ * data to determine board types and revisions. It replies on the
+ * fact that every Octeon board receives a unique board type
+ * enumeration from the bootloader.
+ *
+ * @ipd_port: Octeon IPD port to get the MII address for.
+ *
+ * Returns MII PHY address and bus number or -1.
+ */
+int cvmx_helper_board_get_mii_address(int ipd_port)
+{
+	switch (cvmx_sysinfo_get()->board_type) {
+	case CVMX_BOARD_TYPE_SIM:
+		/* Simulator doesn't have MII */
+		return -1;
+	case CVMX_BOARD_TYPE_EBT3000:
+	case CVMX_BOARD_TYPE_EBT5800:
+	case CVMX_BOARD_TYPE_THUNDER:
+	case CVMX_BOARD_TYPE_NICPRO2:
+		/* Interface 0 is SPI4, interface 1 is RGMII */
+		if ((ipd_port >= 16) && (ipd_port < 20))
+			return ipd_port - 16;
+		else
+			return -1;
+	case CVMX_BOARD_TYPE_KODAMA:
+	case CVMX_BOARD_TYPE_EBH3100:
+	case CVMX_BOARD_TYPE_HIKARI:
+	case CVMX_BOARD_TYPE_CN3010_EVB_HS5:
+	case CVMX_BOARD_TYPE_CN3005_EVB_HS5:
+	case CVMX_BOARD_TYPE_CN3020_EVB_HS5:
+		/*
+		 * Port 0 is WAN connected to a PHY, Port 1 is GMII
+		 * connected to a switch
+		 */
+		if (ipd_port == 0)
+			return 4;
+		else if (ipd_port == 1)
+			return 9;
+		else
+			return -1;
+	case CVMX_BOARD_TYPE_NAC38:
+		/* Board has 8 RGMII ports PHYs are 0-7 */
+		if ((ipd_port >= 0) && (ipd_port < 4))
+			return ipd_port;
+		else if ((ipd_port >= 16) && (ipd_port < 20))
+			return ipd_port - 16 + 4;
+		else
+			return -1;
+	case CVMX_BOARD_TYPE_EBH3000:
+		/* Board has dual SPI4 and no PHYs */
+		return -1;
+	case CVMX_BOARD_TYPE_EBH5200:
+	case CVMX_BOARD_TYPE_EBH5201:
+	case CVMX_BOARD_TYPE_EBT5200:
+		/*
+		 * Board has 4 SGMII ports. The PHYs start right after the MII
+		 * ports MII0 = 0, MII1 = 1, SGMII = 2-5.
+		 */
+		if ((ipd_port >= 0) && (ipd_port < 4))
+			return ipd_port + 2;
+		else
+			return -1;
+	case CVMX_BOARD_TYPE_EBH5600:
+	case CVMX_BOARD_TYPE_EBH5601:
+	case CVMX_BOARD_TYPE_EBH5610:
+		/*
+		 * Board has 8 SGMII ports. 4 connect out, two connect
+		 * to a switch, and 2 loop to each other
+		 */
+		if ((ipd_port >= 0) && (ipd_port < 4))
+			return ipd_port + 1;
+		else
+			return -1;
+	case CVMX_BOARD_TYPE_CUST_NB5:
+		if (ipd_port == 2)
+			return 4;
+		else
+			return -1;
+	case CVMX_BOARD_TYPE_NIC_XLE_4G:
+		/* Board has 4 SGMII ports. connected QLM3(interface 1) */
+		if ((ipd_port >= 16) && (ipd_port < 20))
+			return ipd_port - 16 + 1;
+		else
+			return -1;
+	case CVMX_BOARD_TYPE_BBGW_REF:
+		/*
+		 * No PHYs are connected to Octeon, everything is
+		 * through switch.
+		 */
+		return -1;
+	}
+
+	/* Some unknown board. Somebody forgot to update this function... */
+	cvmx_dprintf
+	    ("cvmx_helper_board_get_mii_address: Unknown board type %d\n",
+	     cvmx_sysinfo_get()->board_type);
+	return -1;
+}
+
+/**
+ * This function is the board specific method of determining an
+ * ethernet ports link speed. Most Octeon boards have Marvell PHYs
+ * and are handled by the fall through case. This function must be
+ * updated for boards that don't have the normal Marvell PHYs.
+ *
+ * This function must be modified for every new Octeon board.
+ * Internally it uses switch statements based on the cvmx_sysinfo
+ * data to determine board types and revisions. It relies on the
+ * fact that every Octeon board receives a unique board type
+ * enumeration from the bootloader.
+ *
+ * @ipd_port: IPD input port associated with the port we want to get link
+ *                 status for.
+ *
+ * Returns The ports link status. If the link isn't fully resolved, this must
+ *         return zero.
+ */
+cvmx_helper_link_info_t __cvmx_helper_board_link_get(int ipd_port)
+{
+	cvmx_helper_link_info_t result;
+	int phy_addr;
+	int is_broadcom_phy = 0;
+
+	/* Give the user a chance to override the processing of this function */
+	if (cvmx_override_board_link_get)
+		return cvmx_override_board_link_get(ipd_port);
+
+	/* Unless we fix it later, all links are defaulted to down */
+	result.u64 = 0;
+
+	/*
+	 * This switch statement should handle all ports that either don't use
+	 * Marvell PHYS, or don't support in-band status.
+	 */
+	switch (cvmx_sysinfo_get()->board_type) {
+	case CVMX_BOARD_TYPE_SIM:
+		/* The simulator gives you a simulated 1Gbps full duplex link */
+		result.s.link_up = 1;
+		result.s.full_duplex = 1;
+		result.s.speed = 1000;
+		return result;
+	case CVMX_BOARD_TYPE_EBH3100:
+	case CVMX_BOARD_TYPE_CN3010_EVB_HS5:
+	case CVMX_BOARD_TYPE_CN3005_EVB_HS5:
+	case CVMX_BOARD_TYPE_CN3020_EVB_HS5:
+		/* Port 1 on these boards is always Gigabit */
+		if (ipd_port == 1) {
+			result.s.link_up = 1;
+			result.s.full_duplex = 1;
+			result.s.speed = 1000;
+			return result;
+		}
+		/* Fall through to the generic code below */
+		break;
+	case CVMX_BOARD_TYPE_CUST_NB5:
+		/* Port 1 on these boards is always Gigabit */
+		if (ipd_port == 1) {
+			result.s.link_up = 1;
+			result.s.full_duplex = 1;
+			result.s.speed = 1000;
+			return result;
+		} else		/* The other port uses a broadcom PHY */
+			is_broadcom_phy = 1;
+		break;
+	case CVMX_BOARD_TYPE_BBGW_REF:
+		/* Port 1 on these boards is always Gigabit */
+		if (ipd_port == 2) {
+			/* Port 2 is not hooked up */
+			result.u64 = 0;
+			return result;
+		} else {
+			/* Ports 0 and 1 connect to the switch */
+			result.s.link_up = 1;
+			result.s.full_duplex = 1;
+			result.s.speed = 1000;
+			return result;
+		}
+		break;
+	}
+
+	phy_addr = cvmx_helper_board_get_mii_address(ipd_port);
+	if (phy_addr != -1) {
+		if (is_broadcom_phy) {
+			/*
+			 * Below we are going to read SMI/MDIO
+			 * register 0x19 which works on Broadcom
+			 * parts
+			 */
+			int phy_status =
+			    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+					   0x19);
+			switch ((phy_status >> 8) & 0x7) {
+			case 0:
+				result.u64 = 0;
+				break;
+			case 1:
+				result.s.link_up = 1;
+				result.s.full_duplex = 0;
+				result.s.speed = 10;
+				break;
+			case 2:
+				result.s.link_up = 1;
+				result.s.full_duplex = 1;
+				result.s.speed = 10;
+				break;
+			case 3:
+				result.s.link_up = 1;
+				result.s.full_duplex = 0;
+				result.s.speed = 100;
+				break;
+			case 4:
+				result.s.link_up = 1;
+				result.s.full_duplex = 1;
+				result.s.speed = 100;
+				break;
+			case 5:
+				result.s.link_up = 1;
+				result.s.full_duplex = 1;
+				result.s.speed = 100;
+				break;
+			case 6:
+				result.s.link_up = 1;
+				result.s.full_duplex = 0;
+				result.s.speed = 1000;
+				break;
+			case 7:
+				result.s.link_up = 1;
+				result.s.full_duplex = 1;
+				result.s.speed = 1000;
+				break;
+			}
+		} else {
+			/*
+			 * This code assumes we are using a Marvell
+			 * Gigabit PHY. All the speed information can
+			 * be read from register 17 in one
+			 * go. Somebody using a different PHY will
+			 * need to handle it above in the board
+			 * specific area.
+			 */
+			int phy_status =
+			    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff, 17);
+
+			/*
+			 * If the resolve bit 11 isn't set, see if
+			 * autoneg is turned off (bit 12, reg 0). The
+			 * resolve bit doesn't get set properly when
+			 * autoneg is off, so force it.
+			 */
+			if ((phy_status & (1 << 11)) == 0) {
+				int auto_status =
+				    cvmx_mdio_read(phy_addr >> 8,
+						   phy_addr & 0xff, 0);
+				if ((auto_status & (1 << 12)) == 0)
+					phy_status |= 1 << 11;
+			}
+
+			/*
+			 * Only return a link if the PHY has finished
+			 * auto negotiation and set the resolved bit
+			 * (bit 11)
+			 */
+			if (phy_status & (1 << 11)) {
+				result.s.link_up = 1;
+				result.s.full_duplex = ((phy_status >> 13) & 1);
+				switch ((phy_status >> 14) & 3) {
+				case 0:	/* 10 Mbps */
+					result.s.speed = 10;
+					break;
+				case 1:	/* 100 Mbps */
+					result.s.speed = 100;
+					break;
+				case 2:	/* 1 Gbps */
+					result.s.speed = 1000;
+					break;
+				case 3:	/* Illegal */
+					result.u64 = 0;
+					break;
+				}
+			}
+		}
+	} else if (OCTEON_IS_MODEL(OCTEON_CN3XXX)
+		   || OCTEON_IS_MODEL(OCTEON_CN58XX)
+		   || OCTEON_IS_MODEL(OCTEON_CN50XX)) {
+		/*
+		 * We don't have a PHY address, so attempt to use
+		 * in-band status. It is really important that boards
+		 * not supporting in-band status never get
+		 * here. Reading broken in-band status tends to do bad
+		 * things
+		 */
+		union cvmx_gmxx_rxx_rx_inbnd inband_status;
+		int interface = cvmx_helper_get_interface_num(ipd_port);
+		int index = cvmx_helper_get_interface_index_num(ipd_port);
+		inband_status.u64 =
+		    cvmx_read_csr(CVMX_GMXX_RXX_RX_INBND(index, interface));
+
+		result.s.link_up = inband_status.s.status;
+		result.s.full_duplex = inband_status.s.duplex;
+		switch (inband_status.s.speed) {
+		case 0:	/* 10 Mbps */
+			result.s.speed = 10;
+			break;
+		case 1:	/* 100 Mbps */
+			result.s.speed = 100;
+			break;
+		case 2:	/* 1 Gbps */
+			result.s.speed = 1000;
+			break;
+		case 3:	/* Illegal */
+			result.u64 = 0;
+			break;
+		}
+	} else {
+		/*
+		 * We don't have a PHY address and we don't have
+		 * in-band status. There is no way to determine the
+		 * link speed. Return down assuming this port isn't
+		 * wired
+		 */
+		result.u64 = 0;
+	}
+
+	/* If link is down, return all fields as zero. */
+	if (!result.s.link_up)
+		result.u64 = 0;
+
+	return result;
+}
+
+/**
+ * This function as a board specific method of changing the PHY
+ * speed, duplex, and auto-negotiation. This programs the PHY and
+ * not Octeon. This can be used to force Octeon's links to
+ * specific settings.
+ *
+ * @phy_addr:  The address of the PHY to program
+ * @enable_autoneg:
+ *                  Non zero if you want to enable auto-negotiation.
+ * @link_info: Link speed to program. If the speed is zero and auto-negotiation
+ *                  is enabled, all possible negotiation speeds are advertised.
+ *
+ * Returns Zero on success, negative on failure
+ */
+int cvmx_helper_board_link_set_phy(int phy_addr,
+				   cvmx_helper_board_set_phy_link_flags_types_t
+				   link_flags,
+				   cvmx_helper_link_info_t link_info)
+{
+
+	/* Set the flow control settings based on link_flags */
+	if ((link_flags & set_phy_link_flags_flow_control_mask) !=
+	    set_phy_link_flags_flow_control_dont_touch) {
+		cvmx_mdio_phy_reg_autoneg_adver_t reg_autoneg_adver;
+		reg_autoneg_adver.u16 =
+		    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+				   CVMX_MDIO_PHY_REG_AUTONEG_ADVER);
+		reg_autoneg_adver.s.asymmetric_pause =
+		    (link_flags & set_phy_link_flags_flow_control_mask) ==
+		    set_phy_link_flags_flow_control_enable;
+		reg_autoneg_adver.s.pause =
+		    (link_flags & set_phy_link_flags_flow_control_mask) ==
+		    set_phy_link_flags_flow_control_enable;
+		cvmx_mdio_write(phy_addr >> 8, phy_addr & 0xff,
+				CVMX_MDIO_PHY_REG_AUTONEG_ADVER,
+				reg_autoneg_adver.u16);
+	}
+
+	/* If speed isn't set and autoneg is on advertise all supported modes */
+	if ((link_flags & set_phy_link_flags_autoneg)
+	    && (link_info.s.speed == 0)) {
+		cvmx_mdio_phy_reg_control_t reg_control;
+		cvmx_mdio_phy_reg_status_t reg_status;
+		cvmx_mdio_phy_reg_autoneg_adver_t reg_autoneg_adver;
+		cvmx_mdio_phy_reg_extended_status_t reg_extended_status;
+		cvmx_mdio_phy_reg_control_1000_t reg_control_1000;
+
+		reg_status.u16 =
+		    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+				   CVMX_MDIO_PHY_REG_STATUS);
+		reg_autoneg_adver.u16 =
+		    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+				   CVMX_MDIO_PHY_REG_AUTONEG_ADVER);
+		reg_autoneg_adver.s.advert_100base_t4 =
+		    reg_status.s.capable_100base_t4;
+		reg_autoneg_adver.s.advert_10base_tx_full =
+		    reg_status.s.capable_10_full;
+		reg_autoneg_adver.s.advert_10base_tx_half =
+		    reg_status.s.capable_10_half;
+		reg_autoneg_adver.s.advert_100base_tx_full =
+		    reg_status.s.capable_100base_x_full;
+		reg_autoneg_adver.s.advert_100base_tx_half =
+		    reg_status.s.capable_100base_x_half;
+		cvmx_mdio_write(phy_addr >> 8, phy_addr & 0xff,
+				CVMX_MDIO_PHY_REG_AUTONEG_ADVER,
+				reg_autoneg_adver.u16);
+		if (reg_status.s.capable_extended_status) {
+			reg_extended_status.u16 =
+			    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+					   CVMX_MDIO_PHY_REG_EXTENDED_STATUS);
+			reg_control_1000.u16 =
+			    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+					   CVMX_MDIO_PHY_REG_CONTROL_1000);
+			reg_control_1000.s.advert_1000base_t_full =
+			    reg_extended_status.s.capable_1000base_t_full;
+			reg_control_1000.s.advert_1000base_t_half =
+			    reg_extended_status.s.capable_1000base_t_half;
+			cvmx_mdio_write(phy_addr >> 8, phy_addr & 0xff,
+					CVMX_MDIO_PHY_REG_CONTROL_1000,
+					reg_control_1000.u16);
+		}
+		reg_control.u16 =
+		    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+				   CVMX_MDIO_PHY_REG_CONTROL);
+		reg_control.s.autoneg_enable = 1;
+		reg_control.s.restart_autoneg = 1;
+		cvmx_mdio_write(phy_addr >> 8, phy_addr & 0xff,
+				CVMX_MDIO_PHY_REG_CONTROL, reg_control.u16);
+	} else if ((link_flags & set_phy_link_flags_autoneg)) {
+		cvmx_mdio_phy_reg_control_t reg_control;
+		cvmx_mdio_phy_reg_status_t reg_status;
+		cvmx_mdio_phy_reg_autoneg_adver_t reg_autoneg_adver;
+		cvmx_mdio_phy_reg_extended_status_t reg_extended_status;
+		cvmx_mdio_phy_reg_control_1000_t reg_control_1000;
+
+		reg_status.u16 =
+		    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+				   CVMX_MDIO_PHY_REG_STATUS);
+		reg_autoneg_adver.u16 =
+		    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+				   CVMX_MDIO_PHY_REG_AUTONEG_ADVER);
+		reg_autoneg_adver.s.advert_100base_t4 = 0;
+		reg_autoneg_adver.s.advert_10base_tx_full = 0;
+		reg_autoneg_adver.s.advert_10base_tx_half = 0;
+		reg_autoneg_adver.s.advert_100base_tx_full = 0;
+		reg_autoneg_adver.s.advert_100base_tx_half = 0;
+		if (reg_status.s.capable_extended_status) {
+			reg_extended_status.u16 =
+			    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+					   CVMX_MDIO_PHY_REG_EXTENDED_STATUS);
+			reg_control_1000.u16 =
+			    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+					   CVMX_MDIO_PHY_REG_CONTROL_1000);
+			reg_control_1000.s.advert_1000base_t_full = 0;
+			reg_control_1000.s.advert_1000base_t_half = 0;
+		}
+		switch (link_info.s.speed) {
+		case 10:
+			reg_autoneg_adver.s.advert_10base_tx_full =
+			    link_info.s.full_duplex;
+			reg_autoneg_adver.s.advert_10base_tx_half =
+			    !link_info.s.full_duplex;
+			break;
+		case 100:
+			reg_autoneg_adver.s.advert_100base_tx_full =
+			    link_info.s.full_duplex;
+			reg_autoneg_adver.s.advert_100base_tx_half =
+			    !link_info.s.full_duplex;
+			break;
+		case 1000:
+			reg_control_1000.s.advert_1000base_t_full =
+			    link_info.s.full_duplex;
+			reg_control_1000.s.advert_1000base_t_half =
+			    !link_info.s.full_duplex;
+			break;
+		}
+		cvmx_mdio_write(phy_addr >> 8, phy_addr & 0xff,
+				CVMX_MDIO_PHY_REG_AUTONEG_ADVER,
+				reg_autoneg_adver.u16);
+		if (reg_status.s.capable_extended_status)
+			cvmx_mdio_write(phy_addr >> 8, phy_addr & 0xff,
+					CVMX_MDIO_PHY_REG_CONTROL_1000,
+					reg_control_1000.u16);
+		reg_control.u16 =
+		    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+				   CVMX_MDIO_PHY_REG_CONTROL);
+		reg_control.s.autoneg_enable = 1;
+		reg_control.s.restart_autoneg = 1;
+		cvmx_mdio_write(phy_addr >> 8, phy_addr & 0xff,
+				CVMX_MDIO_PHY_REG_CONTROL, reg_control.u16);
+	} else {
+		cvmx_mdio_phy_reg_control_t reg_control;
+		reg_control.u16 =
+		    cvmx_mdio_read(phy_addr >> 8, phy_addr & 0xff,
+				   CVMX_MDIO_PHY_REG_CONTROL);
+		reg_control.s.autoneg_enable = 0;
+		reg_control.s.restart_autoneg = 1;
+		reg_control.s.duplex = link_info.s.full_duplex;
+		if (link_info.s.speed == 1000) {
+			reg_control.s.speed_msb = 1;
+			reg_control.s.speed_lsb = 0;
+		} else if (link_info.s.speed == 100) {
+			reg_control.s.speed_msb = 0;
+			reg_control.s.speed_lsb = 1;
+		} else if (link_info.s.speed == 10) {
+			reg_control.s.speed_msb = 0;
+			reg_control.s.speed_lsb = 0;
+		}
+		cvmx_mdio_write(phy_addr >> 8, phy_addr & 0xff,
+				CVMX_MDIO_PHY_REG_CONTROL, reg_control.u16);
+	}
+	return 0;
+}
+
+/**
+ * This function is called by cvmx_helper_interface_probe() after it
+ * determines the number of ports Octeon can support on a specific
+ * interface. This function is the per board location to override
+ * this value. It is called with the number of ports Octeon might
+ * support and should return the number of actual ports on the
+ * board.
+ *
+ * This function must be modifed for every new Octeon board.
+ * Internally it uses switch statements based on the cvmx_sysinfo
+ * data to determine board types and revisions. It relys on the
+ * fact that every Octeon board receives a unique board type
+ * enumeration from the bootloader.
+ *
+ * @interface: Interface to probe
+ * @supported_ports:
+ *                  Number of ports Octeon supports.
+ *
+ * Returns Number of ports the actual board supports. Many times this will
+ *         simple be "support_ports".
+ */
+int __cvmx_helper_board_interface_probe(int interface, int supported_ports)
+{
+	switch (cvmx_sysinfo_get()->board_type) {
+	case CVMX_BOARD_TYPE_CN3005_EVB_HS5:
+		if (interface == 0)
+			return 2;
+		break;
+	case CVMX_BOARD_TYPE_BBGW_REF:
+		if (interface == 0)
+			return 2;
+		break;
+	case CVMX_BOARD_TYPE_NIC_XLE_4G:
+		if (interface == 0)
+			return 0;
+		break;
+		/* The 2nd interface on the EBH5600 is connected to the Marvel switch,
+		   which we don't support. Disable ports connected to it */
+	case CVMX_BOARD_TYPE_EBH5600:
+		if (interface == 1)
+			return 0;
+		break;
+	}
+	return supported_ports;
+}
+
+/**
+ * Enable packet input/output from the hardware. This function is
+ * called after by cvmx_helper_packet_hardware_enable() to
+ * perform board specific initialization. For most boards
+ * nothing is needed.
+ *
+ * @interface: Interface to enable
+ *
+ * Returns Zero on success, negative on failure
+ */
+int __cvmx_helper_board_hardware_enable(int interface)
+{
+	if (cvmx_sysinfo_get()->board_type == CVMX_BOARD_TYPE_CN3005_EVB_HS5) {
+		if (interface == 0) {
+			/* Different config for switch port */
+			cvmx_write_csr(CVMX_ASXX_TX_CLK_SETX(1, interface), 0);
+			cvmx_write_csr(CVMX_ASXX_RX_CLK_SETX(1, interface), 0);
+			/*
+			 * Boards with gigabit WAN ports need a
+			 * different setting that is compatible with
+			 * 100 Mbit settings
+			 */
+			cvmx_write_csr(CVMX_ASXX_TX_CLK_SETX(0, interface),
+				       0xc);
+			cvmx_write_csr(CVMX_ASXX_RX_CLK_SETX(0, interface),
+				       0xc);
+		}
+	} else if (cvmx_sysinfo_get()->board_type ==
+		   CVMX_BOARD_TYPE_CN3010_EVB_HS5) {
+		/*
+		 * Broadcom PHYs require differnet ASX
+		 * clocks. Unfortunately many boards don't define a
+		 * new board Id and simply mangle the
+		 * CN3010_EVB_HS5
+		 */
+		if (interface == 0) {
+			/*
+			 * Some boards use a hacked up bootloader that
+			 * identifies them as CN3010_EVB_HS5
+			 * evaluation boards.  This leads to all kinds
+			 * of configuration problems.  Detect one
+			 * case, and print warning, while trying to do
+			 * the right thing.
+			 */
+			int phy_addr = cvmx_helper_board_get_mii_address(0);
+			if (phy_addr != -1) {
+				int phy_identifier =
+				    cvmx_mdio_read(phy_addr >> 8,
+						   phy_addr & 0xff, 0x2);
+				/* Is it a Broadcom PHY? */
+				if (phy_identifier == 0x0143) {
+					cvmx_dprintf("\n");
+					cvmx_dprintf("ERROR:\n");
+					cvmx_dprintf
+					    ("ERROR: Board type is CVMX_BOARD_TYPE_CN3010_EVB_HS5, but Broadcom PHY found.\n");
+					cvmx_dprintf
+					    ("ERROR: The board type is mis-configured, and software malfunctions are likely.\n");
+					cvmx_dprintf
+					    ("ERROR: All boards require a unique board type to identify them.\n");
+					cvmx_dprintf("ERROR:\n");
+					cvmx_dprintf("\n");
+					cvmx_wait(1000000000);
+					cvmx_write_csr(CVMX_ASXX_RX_CLK_SETX
+						       (0, interface), 5);
+					cvmx_write_csr(CVMX_ASXX_TX_CLK_SETX
+						       (0, interface), 5);
+				}
+			}
+		}
+	}
+	return 0;
+}
+
+cvmx_helper_board_usb_clock_types_t __cvmx_helper_board_usb_get_clock_type(void)
+{
+	switch (cvmx_sysinfo_get()->board_type) {
+	case CVMX_BOARD_TYPE_BBGW_REF:
+		return USB_CLOCK_TYPE_CRYSTAL_12;
+	}
+	return USB_CLOCK_TYPE_REF_48;
+}
+
+int __cvmx_helper_board_usb_get_num_ports(int supported_ports)
+{
+	switch (cvmx_sysinfo_get()->board_type) {
+	case CVMX_BOARD_TYPE_NIC_XLE_4G:
+		return 0;
+	}
+
+	return supported_ports;
+}
diff --git a/drivers/staging/octeon/cvmx-helper-board.h b/drivers/staging/octeon/cvmx-helper-board.h
new file mode 100644
index 0000000..dc20b01
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-board.h
@@ -0,0 +1,180 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ *
+ * Helper functions to abstract board specific data about
+ * network ports from the rest of the cvmx-helper files.
+ *
+ */
+#ifndef __CVMX_HELPER_BOARD_H__
+#define __CVMX_HELPER_BOARD_H__
+
+#include "cvmx-helper.h"
+
+typedef enum {
+	USB_CLOCK_TYPE_REF_12,
+	USB_CLOCK_TYPE_REF_24,
+	USB_CLOCK_TYPE_REF_48,
+	USB_CLOCK_TYPE_CRYSTAL_12,
+} cvmx_helper_board_usb_clock_types_t;
+
+typedef enum {
+	set_phy_link_flags_autoneg = 0x1,
+	set_phy_link_flags_flow_control_dont_touch = 0x0 << 1,
+	set_phy_link_flags_flow_control_enable = 0x1 << 1,
+	set_phy_link_flags_flow_control_disable = 0x2 << 1,
+	set_phy_link_flags_flow_control_mask = 0x3 << 1,	/* Mask for 2 bit wide flow control field */
+} cvmx_helper_board_set_phy_link_flags_types_t;
+
+/**
+ * cvmx_override_board_link_get(int ipd_port) is a function
+ * pointer. It is meant to allow customization of the process of
+ * talking to a PHY to determine link speed. It is called every
+ * time a PHY must be polled for link status. Users should set
+ * this pointer to a function before calling any cvmx-helper
+ * operations.
+ */
+extern cvmx_helper_link_info_t(*cvmx_override_board_link_get) (int ipd_port);
+
+/**
+ * Return the MII PHY address associated with the given IPD
+ * port. A result of -1 means there isn't a MII capable PHY
+ * connected to this port. On chips supporting multiple MII
+ * busses the bus number is encoded in bits <15:8>.
+ *
+ * This function must be modifed for every new Octeon board.
+ * Internally it uses switch statements based on the cvmx_sysinfo
+ * data to determine board types and revisions. It relys on the
+ * fact that every Octeon board receives a unique board type
+ * enumeration from the bootloader.
+ *
+ * @ipd_port: Octeon IPD port to get the MII address for.
+ *
+ * Returns MII PHY address and bus number or -1.
+ */
+extern int cvmx_helper_board_get_mii_address(int ipd_port);
+
+/**
+ * This function as a board specific method of changing the PHY
+ * speed, duplex, and autonegotiation. This programs the PHY and
+ * not Octeon. This can be used to force Octeon's links to
+ * specific settings.
+ *
+ * @phy_addr:  The address of the PHY to program
+ * @link_flags:
+ *                  Flags to control autonegotiation.  Bit 0 is autonegotiation
+ *                  enable/disable to maintain backware compatability.
+ * @link_info: Link speed to program. If the speed is zero and autonegotiation
+ *                  is enabled, all possible negotiation speeds are advertised.
+ *
+ * Returns Zero on success, negative on failure
+ */
+int cvmx_helper_board_link_set_phy(int phy_addr,
+				   cvmx_helper_board_set_phy_link_flags_types_t
+				   link_flags,
+				   cvmx_helper_link_info_t link_info);
+
+/**
+ * This function is the board specific method of determining an
+ * ethernet ports link speed. Most Octeon boards have Marvell PHYs
+ * and are handled by the fall through case. This function must be
+ * updated for boards that don't have the normal Marvell PHYs.
+ *
+ * This function must be modifed for every new Octeon board.
+ * Internally it uses switch statements based on the cvmx_sysinfo
+ * data to determine board types and revisions. It relys on the
+ * fact that every Octeon board receives a unique board type
+ * enumeration from the bootloader.
+ *
+ * @ipd_port: IPD input port associated with the port we want to get link
+ *                 status for.
+ *
+ * Returns The ports link status. If the link isn't fully resolved, this must
+ *         return zero.
+ */
+extern cvmx_helper_link_info_t __cvmx_helper_board_link_get(int ipd_port);
+
+/**
+ * This function is called by cvmx_helper_interface_probe() after it
+ * determines the number of ports Octeon can support on a specific
+ * interface. This function is the per board location to override
+ * this value. It is called with the number of ports Octeon might
+ * support and should return the number of actual ports on the
+ * board.
+ *
+ * This function must be modifed for every new Octeon board.
+ * Internally it uses switch statements based on the cvmx_sysinfo
+ * data to determine board types and revisions. It relys on the
+ * fact that every Octeon board receives a unique board type
+ * enumeration from the bootloader.
+ *
+ * @interface: Interface to probe
+ * @supported_ports:
+ *                  Number of ports Octeon supports.
+ *
+ * Returns Number of ports the actual board supports. Many times this will
+ *         simple be "support_ports".
+ */
+extern int __cvmx_helper_board_interface_probe(int interface,
+					       int supported_ports);
+
+/**
+ * Enable packet input/output from the hardware. This function is
+ * called after by cvmx_helper_packet_hardware_enable() to
+ * perform board specific initialization. For most boards
+ * nothing is needed.
+ *
+ * @interface: Interface to enable
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int __cvmx_helper_board_hardware_enable(int interface);
+
+/**
+ * Gets the clock type used for the USB block based on board type.
+ * Used by the USB code for auto configuration of clock type.
+ *
+ * Returns USB clock type enumeration
+ */
+cvmx_helper_board_usb_clock_types_t
+__cvmx_helper_board_usb_get_clock_type(void);
+
+/**
+ * Adjusts the number of available USB ports on Octeon based on board
+ * specifics.
+ *
+ * @supported_ports: expected number of ports based on chip type;
+ *
+ *
+ * Returns number of available usb ports, based on board specifics.
+ *         Return value is supported_ports if function does not
+ *         override.
+ */
+int __cvmx_helper_board_usb_get_num_ports(int supported_ports);
+
+#endif /* __CVMX_HELPER_BOARD_H__ */
diff --git a/drivers/staging/octeon/cvmx-helper-fpa.c b/drivers/staging/octeon/cvmx-helper-fpa.c
new file mode 100644
index 0000000..c239e5f
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-fpa.c
@@ -0,0 +1,243 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * @file
+ *
+ * Helper functions for FPA setup.
+ *
+ */
+#include "executive-config.h"
+#include "cvmx-config.h"
+#include "cvmx.h"
+#include "cvmx-bootmem.h"
+#include "cvmx-fpa.h"
+#include "cvmx-helper-fpa.h"
+
+/**
+ * Allocate memory for and initialize a single FPA pool.
+ *
+ * @pool:    Pool to initialize
+ * @buffer_size:  Size of buffers to allocate in bytes
+ * @buffers: Number of buffers to put in the pool. Zero is allowed
+ * @name:    String name of the pool for debugging purposes
+ * Returns Zero on success, non-zero on failure
+ */
+static int __cvmx_helper_initialize_fpa_pool(int pool, uint64_t buffer_size,
+					     uint64_t buffers, const char *name)
+{
+	uint64_t current_num;
+	void *memory;
+	uint64_t align = CVMX_CACHE_LINE_SIZE;
+
+	/*
+	 * Align the allocation so that power of 2 size buffers are
+	 * naturally aligned.
+	 */
+	while (align < buffer_size)
+		align = align << 1;
+
+	if (buffers == 0)
+		return 0;
+
+	current_num = cvmx_read_csr(CVMX_FPA_QUEX_AVAILABLE(pool));
+	if (current_num) {
+		cvmx_dprintf("Fpa pool %d(%s) already has %llu buffers. "
+			     "Skipping setup.\n",
+		     pool, name, (unsigned long long)current_num);
+		return 0;
+	}
+
+	memory = cvmx_bootmem_alloc(buffer_size * buffers, align);
+	if (memory == NULL) {
+		cvmx_dprintf("Out of memory initializing fpa pool %d(%s).\n",
+			     pool, name);
+		return -1;
+	}
+	cvmx_fpa_setup_pool(pool, name, memory, buffer_size, buffers);
+	return 0;
+}
+
+/**
+ * Allocate memory and initialize the FPA pools using memory
+ * from cvmx-bootmem. Specifying zero for the number of
+ * buffers will cause that FPA pool to not be setup. This is
+ * useful if you aren't using some of the hardware and want
+ * to save memory. Use cvmx_helper_initialize_fpa instead of
+ * this function directly.
+ *
+ * @pip_pool: Should always be CVMX_FPA_PACKET_POOL
+ * @pip_size: Should always be CVMX_FPA_PACKET_POOL_SIZE
+ * @pip_buffers:
+ *                 Number of packet buffers.
+ * @wqe_pool: Should always be CVMX_FPA_WQE_POOL
+ * @wqe_size: Should always be CVMX_FPA_WQE_POOL_SIZE
+ * @wqe_entries:
+ *                 Number of work queue entries
+ * @pko_pool: Should always be CVMX_FPA_OUTPUT_BUFFER_POOL
+ * @pko_size: Should always be CVMX_FPA_OUTPUT_BUFFER_POOL_SIZE
+ * @pko_buffers:
+ *                 PKO Command buffers. You should at minimum have two per
+ *                 each PKO queue.
+ * @tim_pool: Should always be CVMX_FPA_TIMER_POOL
+ * @tim_size: Should always be CVMX_FPA_TIMER_POOL_SIZE
+ * @tim_buffers:
+ *                 TIM ring buffer command queues. At least two per timer bucket
+ *                 is recommened.
+ * @dfa_pool: Should always be CVMX_FPA_DFA_POOL
+ * @dfa_size: Should always be CVMX_FPA_DFA_POOL_SIZE
+ * @dfa_buffers:
+ *                 DFA command buffer. A relatively small (32 for example)
+ *                 number should work.
+ * Returns Zero on success, non-zero if out of memory
+ */
+static int __cvmx_helper_initialize_fpa(int pip_pool, int pip_size,
+					int pip_buffers, int wqe_pool,
+					int wqe_size, int wqe_entries,
+					int pko_pool, int pko_size,
+					int pko_buffers, int tim_pool,
+					int tim_size, int tim_buffers,
+					int dfa_pool, int dfa_size,
+					int dfa_buffers)
+{
+	int status;
+
+	cvmx_fpa_enable();
+
+	if ((pip_buffers > 0) && (pip_buffers <= 64))
+		cvmx_dprintf
+		    ("Warning: %d packet buffers may not be enough for hardware"
+		     " prefetch. 65 or more is recommended.\n", pip_buffers);
+
+	if (pip_pool >= 0) {
+		status =
+		    __cvmx_helper_initialize_fpa_pool(pip_pool, pip_size,
+						      pip_buffers,
+						      "Packet Buffers");
+		if (status)
+			return status;
+	}
+
+	if (wqe_pool >= 0) {
+		status =
+		    __cvmx_helper_initialize_fpa_pool(wqe_pool, wqe_size,
+						      wqe_entries,
+						      "Work Queue Entries");
+		if (status)
+			return status;
+	}
+
+	if (pko_pool >= 0) {
+		status =
+		    __cvmx_helper_initialize_fpa_pool(pko_pool, pko_size,
+						      pko_buffers,
+						      "PKO Command Buffers");
+		if (status)
+			return status;
+	}
+
+	if (tim_pool >= 0) {
+		status =
+		    __cvmx_helper_initialize_fpa_pool(tim_pool, tim_size,
+						      tim_buffers,
+						      "TIM Command Buffers");
+		if (status)
+			return status;
+	}
+
+	if (dfa_pool >= 0) {
+		status =
+		    __cvmx_helper_initialize_fpa_pool(dfa_pool, dfa_size,
+						      dfa_buffers,
+						      "DFA Command Buffers");
+		if (status)
+			return status;
+	}
+
+	return 0;
+}
+
+/**
+ * Allocate memory and initialize the FPA pools using memory
+ * from cvmx-bootmem. Sizes of each element in the pools is
+ * controlled by the cvmx-config.h header file. Specifying
+ * zero for any parameter will cause that FPA pool to not be
+ * setup. This is useful if you aren't using some of the
+ * hardware and want to save memory.
+ *
+ * @packet_buffers:
+ *               Number of packet buffers to allocate
+ * @work_queue_entries:
+ *               Number of work queue entries
+ * @pko_buffers:
+ *               PKO Command buffers. You should at minimum have two per
+ *               each PKO queue.
+ * @tim_buffers:
+ *               TIM ring buffer command queues. At least two per timer bucket
+ *               is recommened.
+ * @dfa_buffers:
+ *               DFA command buffer. A relatively small (32 for example)
+ *               number should work.
+ * Returns Zero on success, non-zero if out of memory
+ */
+int cvmx_helper_initialize_fpa(int packet_buffers, int work_queue_entries,
+			       int pko_buffers, int tim_buffers,
+			       int dfa_buffers)
+{
+#ifndef CVMX_FPA_PACKET_POOL
+#define CVMX_FPA_PACKET_POOL -1
+#define CVMX_FPA_PACKET_POOL_SIZE 0
+#endif
+#ifndef CVMX_FPA_WQE_POOL
+#define CVMX_FPA_WQE_POOL -1
+#define CVMX_FPA_WQE_POOL_SIZE 0
+#endif
+#ifndef CVMX_FPA_OUTPUT_BUFFER_POOL
+#define CVMX_FPA_OUTPUT_BUFFER_POOL -1
+#define CVMX_FPA_OUTPUT_BUFFER_POOL_SIZE 0
+#endif
+#ifndef CVMX_FPA_TIMER_POOL
+#define CVMX_FPA_TIMER_POOL -1
+#define CVMX_FPA_TIMER_POOL_SIZE 0
+#endif
+#ifndef CVMX_FPA_DFA_POOL
+#define CVMX_FPA_DFA_POOL -1
+#define CVMX_FPA_DFA_POOL_SIZE 0
+#endif
+	return __cvmx_helper_initialize_fpa(CVMX_FPA_PACKET_POOL,
+					    CVMX_FPA_PACKET_POOL_SIZE,
+					    packet_buffers, CVMX_FPA_WQE_POOL,
+					    CVMX_FPA_WQE_POOL_SIZE,
+					    work_queue_entries,
+					    CVMX_FPA_OUTPUT_BUFFER_POOL,
+					    CVMX_FPA_OUTPUT_BUFFER_POOL_SIZE,
+					    pko_buffers, CVMX_FPA_TIMER_POOL,
+					    CVMX_FPA_TIMER_POOL_SIZE,
+					    tim_buffers, CVMX_FPA_DFA_POOL,
+					    CVMX_FPA_DFA_POOL_SIZE,
+					    dfa_buffers);
+}
diff --git a/drivers/staging/octeon/cvmx-helper-fpa.h b/drivers/staging/octeon/cvmx-helper-fpa.h
new file mode 100644
index 0000000..5ff8c93
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-fpa.h
@@ -0,0 +1,64 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * @file
+ *
+ * Helper functions for FPA setup.
+ *
+ */
+#ifndef __CVMX_HELPER_H_FPA__
+#define __CVMX_HELPER_H_FPA__
+
+/**
+ * Allocate memory and initialize the FPA pools using memory
+ * from cvmx-bootmem. Sizes of each element in the pools is
+ * controlled by the cvmx-config.h header file. Specifying
+ * zero for any parameter will cause that FPA pool to not be
+ * setup. This is useful if you aren't using some of the
+ * hardware and want to save memory.
+ *
+ * @packet_buffers:
+ *               Number of packet buffers to allocate
+ * @work_queue_entries:
+ *               Number of work queue entries
+ * @pko_buffers:
+ *               PKO Command buffers. You should at minimum have two per
+ *               each PKO queue.
+ * @tim_buffers:
+ *               TIM ring buffer command queues. At least two per timer bucket
+ *               is recommened.
+ * @dfa_buffers:
+ *               DFA command buffer. A relatively small (32 for example)
+ *               number should work.
+ * Returns Zero on success, non-zero if out of memory
+ */
+extern int cvmx_helper_initialize_fpa(int packet_buffers,
+				      int work_queue_entries, int pko_buffers,
+				      int tim_buffers, int dfa_buffers);
+
+#endif /* __CVMX_HELPER_H__ */
diff --git a/drivers/staging/octeon/cvmx-helper-loop.c b/drivers/staging/octeon/cvmx-helper-loop.c
new file mode 100644
index 0000000..55a571a
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-loop.c
@@ -0,0 +1,85 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Functions for LOOP initialization, configuration,
+ * and monitoring.
+ */
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-config.h"
+
+#include "cvmx-helper.h"
+#include "cvmx-pip-defs.h"
+
+/**
+ * Probe a LOOP interface and determine the number of ports
+ * connected to it. The LOOP interface should still be down
+ * after this call.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of ports on the interface. Zero to disable.
+ */
+int __cvmx_helper_loop_probe(int interface)
+{
+	union cvmx_ipd_sub_port_fcs ipd_sub_port_fcs;
+	int num_ports = 4;
+	int port;
+
+	/* We need to disable length checking so packet < 64 bytes and jumbo
+	   frames don't get errors */
+	for (port = 0; port < num_ports; port++) {
+		union cvmx_pip_prt_cfgx port_cfg;
+		int ipd_port = cvmx_helper_get_ipd_port(interface, port);
+		port_cfg.u64 = cvmx_read_csr(CVMX_PIP_PRT_CFGX(ipd_port));
+		port_cfg.s.maxerr_en = 0;
+		port_cfg.s.minerr_en = 0;
+		cvmx_write_csr(CVMX_PIP_PRT_CFGX(ipd_port), port_cfg.u64);
+	}
+
+	/* Disable FCS stripping for loopback ports */
+	ipd_sub_port_fcs.u64 = cvmx_read_csr(CVMX_IPD_SUB_PORT_FCS);
+	ipd_sub_port_fcs.s.port_bit2 = 0;
+	cvmx_write_csr(CVMX_IPD_SUB_PORT_FCS, ipd_sub_port_fcs.u64);
+	return num_ports;
+}
+
+/**
+ * Bringup and enable a LOOP interface. After this call packet
+ * I/O should be fully functional. This is called with IPD
+ * enabled but PKO disabled.
+ *
+ * @interface: Interface to bring up
+ *
+ * Returns Zero on success, negative on failure
+ */
+int __cvmx_helper_loop_enable(int interface)
+{
+	/* Do nothing. */
+	return 0;
+}
diff --git a/drivers/staging/octeon/cvmx-helper-loop.h b/drivers/staging/octeon/cvmx-helper-loop.h
new file mode 100644
index 0000000..e646a6c
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-loop.h
@@ -0,0 +1,59 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as published by
+ * the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful,
+ * but AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
+ * See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * @file
+ *
+ * Functions for LOOP initialization, configuration,
+ * and monitoring.
+ *
+ */
+#ifndef __CVMX_HELPER_LOOP_H__
+#define __CVMX_HELPER_LOOP_H__
+
+/**
+ * Probe a LOOP interface and determine the number of ports
+ * connected to it. The LOOP interface should still be down after
+ * this call.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of ports on the interface. Zero to disable.
+ */
+extern int __cvmx_helper_loop_probe(int interface);
+
+/**
+ * Bringup and enable a LOOP interface. After this call packet
+ * I/O should be fully functional. This is called with IPD
+ * enabled but PKO disabled.
+ *
+ * @interface: Interface to bring up
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int __cvmx_helper_loop_enable(int interface);
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-helper-npi.c b/drivers/staging/octeon/cvmx-helper-npi.c
new file mode 100644
index 0000000..7388a1e
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-npi.c
@@ -0,0 +1,113 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Functions for NPI initialization, configuration,
+ * and monitoring.
+ */
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-config.h"
+
+#include "cvmx-helper.h"
+
+#include "cvmx-pip-defs.h"
+
+/**
+ * Probe a NPI interface and determine the number of ports
+ * connected to it. The NPI interface should still be down
+ * after this call.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of ports on the interface. Zero to disable.
+ */
+int __cvmx_helper_npi_probe(int interface)
+{
+#if CVMX_PKO_QUEUES_PER_PORT_PCI > 0
+	if (OCTEON_IS_MODEL(OCTEON_CN38XX) || OCTEON_IS_MODEL(OCTEON_CN58XX))
+		return 4;
+	else if (OCTEON_IS_MODEL(OCTEON_CN56XX)
+		 && !OCTEON_IS_MODEL(OCTEON_CN56XX_PASS1_X))
+		/* The packet engines didn't exist before pass 2 */
+		return 4;
+	else if (OCTEON_IS_MODEL(OCTEON_CN52XX)
+		 && !OCTEON_IS_MODEL(OCTEON_CN52XX_PASS1_X))
+		/* The packet engines didn't exist before pass 2 */
+		return 4;
+#if 0
+	/*
+	 * Technically CN30XX, CN31XX, and CN50XX contain packet
+	 * engines, but nobody ever uses them. Since this is the case,
+	 * we disable them here.
+	 */
+	else if (OCTEON_IS_MODEL(OCTEON_CN31XX)
+		 || OCTEON_IS_MODEL(OCTEON_CN50XX))
+		return 2;
+	else if (OCTEON_IS_MODEL(OCTEON_CN30XX))
+		return 1;
+#endif
+#endif
+	return 0;
+}
+
+/**
+ * Bringup and enable a NPI interface. After this call packet
+ * I/O should be fully functional. This is called with IPD
+ * enabled but PKO disabled.
+ *
+ * @interface: Interface to bring up
+ *
+ * Returns Zero on success, negative on failure
+ */
+int __cvmx_helper_npi_enable(int interface)
+{
+	/*
+	 * On CN50XX, CN52XX, and CN56XX we need to disable length
+	 * checking so packet < 64 bytes and jumbo frames don't get
+	 * errors.
+	 */
+	if (!OCTEON_IS_MODEL(OCTEON_CN3XXX) &&
+	    !OCTEON_IS_MODEL(OCTEON_CN58XX)) {
+		int num_ports = cvmx_helper_ports_on_interface(interface);
+		int port;
+		for (port = 0; port < num_ports; port++) {
+			union cvmx_pip_prt_cfgx port_cfg;
+			int ipd_port =
+			    cvmx_helper_get_ipd_port(interface, port);
+			port_cfg.u64 =
+			    cvmx_read_csr(CVMX_PIP_PRT_CFGX(ipd_port));
+			port_cfg.s.maxerr_en = 0;
+			port_cfg.s.minerr_en = 0;
+			cvmx_write_csr(CVMX_PIP_PRT_CFGX(ipd_port),
+				       port_cfg.u64);
+		}
+	}
+
+	/* Enables are controlled by the remote host, so nothing to do here */
+	return 0;
+}
diff --git a/drivers/staging/octeon/cvmx-helper-npi.h b/drivers/staging/octeon/cvmx-helper-npi.h
new file mode 100644
index 0000000..908e7b0
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-npi.h
@@ -0,0 +1,60 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * @file
+ *
+ * Functions for NPI initialization, configuration,
+ * and monitoring.
+ *
+ */
+#ifndef __CVMX_HELPER_NPI_H__
+#define __CVMX_HELPER_NPI_H__
+
+/**
+ * Probe a NPI interface and determine the number of ports
+ * connected to it. The NPI interface should still be down after
+ * this call.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of ports on the interface. Zero to disable.
+ */
+extern int __cvmx_helper_npi_probe(int interface);
+
+/**
+ * Bringup and enable a NPI interface. After this call packet
+ * I/O should be fully functional. This is called with IPD
+ * enabled but PKO disabled.
+ *
+ * @interface: Interface to bring up
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int __cvmx_helper_npi_enable(int interface);
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-helper-rgmii.c b/drivers/staging/octeon/cvmx-helper-rgmii.c
new file mode 100644
index 0000000..aa2d5d7
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-rgmii.c
@@ -0,0 +1,525 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Functions for RGMII/GMII/MII initialization, configuration,
+ * and monitoring.
+ */
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-config.h"
+
+
+#include "cvmx-mdio.h"
+#include "cvmx-pko.h"
+#include "cvmx-helper.h"
+#include "cvmx-helper-board.h"
+
+#include <asm/octeon/cvmx-npi-defs.h>
+#include "cvmx-gmxx-defs.h"
+#include "cvmx-asxx-defs.h"
+#include "cvmx-dbg-defs.h"
+
+void __cvmx_interrupt_gmxx_enable(int interface);
+void __cvmx_interrupt_asxx_enable(int block);
+
+/**
+ * Probe RGMII ports and determine the number present
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of RGMII/GMII/MII ports (0-4).
+ */
+int __cvmx_helper_rgmii_probe(int interface)
+{
+	int num_ports = 0;
+	union cvmx_gmxx_inf_mode mode;
+	mode.u64 = cvmx_read_csr(CVMX_GMXX_INF_MODE(interface));
+
+	if (mode.s.type) {
+		if (OCTEON_IS_MODEL(OCTEON_CN38XX)
+		    || OCTEON_IS_MODEL(OCTEON_CN58XX)) {
+			cvmx_dprintf("ERROR: RGMII initialize called in "
+				     "SPI interface\n");
+		} else if (OCTEON_IS_MODEL(OCTEON_CN31XX)
+			   || OCTEON_IS_MODEL(OCTEON_CN30XX)
+			   || OCTEON_IS_MODEL(OCTEON_CN50XX)) {
+			/*
+			 * On these chips "type" says we're in
+			 * GMII/MII mode. This limits us to 2 ports
+			 */
+			num_ports = 2;
+		} else {
+			cvmx_dprintf("ERROR: Unsupported Octeon model in %s\n",
+				     __func__);
+		}
+	} else {
+		if (OCTEON_IS_MODEL(OCTEON_CN38XX)
+		    || OCTEON_IS_MODEL(OCTEON_CN58XX)) {
+			num_ports = 4;
+		} else if (OCTEON_IS_MODEL(OCTEON_CN31XX)
+			   || OCTEON_IS_MODEL(OCTEON_CN30XX)
+			   || OCTEON_IS_MODEL(OCTEON_CN50XX)) {
+			num_ports = 3;
+		} else {
+			cvmx_dprintf("ERROR: Unsupported Octeon model in %s\n",
+				     __func__);
+		}
+	}
+	return num_ports;
+}
+
+/**
+ * Put an RGMII interface in loopback mode. Internal packets sent
+ * out will be received back again on the same port. Externally
+ * received packets will echo back out.
+ *
+ * @port:   IPD port number to loop.
+ */
+void cvmx_helper_rgmii_internal_loopback(int port)
+{
+	int interface = (port >> 4) & 1;
+	int index = port & 0xf;
+	uint64_t tmp;
+
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	gmx_cfg.u64 = 0;
+	gmx_cfg.s.duplex = 1;
+	gmx_cfg.s.slottime = 1;
+	gmx_cfg.s.speed = 1;
+	cvmx_write_csr(CVMX_GMXX_TXX_CLK(index, interface), 1);
+	cvmx_write_csr(CVMX_GMXX_TXX_SLOT(index, interface), 0x200);
+	cvmx_write_csr(CVMX_GMXX_TXX_BURST(index, interface), 0x2000);
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmx_cfg.u64);
+	tmp = cvmx_read_csr(CVMX_ASXX_PRT_LOOP(interface));
+	cvmx_write_csr(CVMX_ASXX_PRT_LOOP(interface), (1 << index) | tmp);
+	tmp = cvmx_read_csr(CVMX_ASXX_TX_PRT_EN(interface));
+	cvmx_write_csr(CVMX_ASXX_TX_PRT_EN(interface), (1 << index) | tmp);
+	tmp = cvmx_read_csr(CVMX_ASXX_RX_PRT_EN(interface));
+	cvmx_write_csr(CVMX_ASXX_RX_PRT_EN(interface), (1 << index) | tmp);
+	gmx_cfg.s.en = 1;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmx_cfg.u64);
+}
+
+/**
+ * Workaround ASX setup errata with CN38XX pass1
+ *
+ * @interface: Interface to setup
+ * @port:      Port to setup (0..3)
+ * @cpu_clock_hz:
+ *                  Chip frequency in Hertz
+ *
+ * Returns Zero on success, negative on failure
+ */
+static int __cvmx_helper_errata_asx_pass1(int interface, int port,
+					  int cpu_clock_hz)
+{
+	/* Set hi water mark as per errata GMX-4 */
+	if (cpu_clock_hz >= 325000000 && cpu_clock_hz < 375000000)
+		cvmx_write_csr(CVMX_ASXX_TX_HI_WATERX(port, interface), 12);
+	else if (cpu_clock_hz >= 375000000 && cpu_clock_hz < 437000000)
+		cvmx_write_csr(CVMX_ASXX_TX_HI_WATERX(port, interface), 11);
+	else if (cpu_clock_hz >= 437000000 && cpu_clock_hz < 550000000)
+		cvmx_write_csr(CVMX_ASXX_TX_HI_WATERX(port, interface), 10);
+	else if (cpu_clock_hz >= 550000000 && cpu_clock_hz < 687000000)
+		cvmx_write_csr(CVMX_ASXX_TX_HI_WATERX(port, interface), 9);
+	else
+		cvmx_dprintf("Illegal clock frequency (%d). "
+			"CVMX_ASXX_TX_HI_WATERX not set\n", cpu_clock_hz);
+	return 0;
+}
+
+/**
+ * Configure all of the ASX, GMX, and PKO regsiters required
+ * to get RGMII to function on the supplied interface.
+ *
+ * @interface: PKO Interface to configure (0 or 1)
+ *
+ * Returns Zero on success
+ */
+int __cvmx_helper_rgmii_enable(int interface)
+{
+	int num_ports = cvmx_helper_ports_on_interface(interface);
+	int port;
+	struct cvmx_sysinfo *sys_info_ptr = cvmx_sysinfo_get();
+	union cvmx_gmxx_inf_mode mode;
+	union cvmx_asxx_tx_prt_en asx_tx;
+	union cvmx_asxx_rx_prt_en asx_rx;
+
+	mode.u64 = cvmx_read_csr(CVMX_GMXX_INF_MODE(interface));
+
+	if (mode.s.en == 0)
+		return -1;
+	if ((OCTEON_IS_MODEL(OCTEON_CN38XX) ||
+	     OCTEON_IS_MODEL(OCTEON_CN58XX)) && mode.s.type == 1)
+		/* Ignore SPI interfaces */
+		return -1;
+
+	/* Configure the ASX registers needed to use the RGMII ports */
+	asx_tx.u64 = 0;
+	asx_tx.s.prt_en = cvmx_build_mask(num_ports);
+	cvmx_write_csr(CVMX_ASXX_TX_PRT_EN(interface), asx_tx.u64);
+
+	asx_rx.u64 = 0;
+	asx_rx.s.prt_en = cvmx_build_mask(num_ports);
+	cvmx_write_csr(CVMX_ASXX_RX_PRT_EN(interface), asx_rx.u64);
+
+	/* Configure the GMX registers needed to use the RGMII ports */
+	for (port = 0; port < num_ports; port++) {
+		/* Setting of CVMX_GMXX_TXX_THRESH has been moved to
+		   __cvmx_helper_setup_gmx() */
+
+		if (cvmx_octeon_is_pass1())
+			__cvmx_helper_errata_asx_pass1(interface, port,
+						       sys_info_ptr->
+						       cpu_clock_hz);
+		else {
+			/*
+			 * Configure more flexible RGMII preamble
+			 * checking. Pass 1 doesn't support this
+			 * feature.
+			 */
+			union cvmx_gmxx_rxx_frm_ctl frm_ctl;
+			frm_ctl.u64 =
+			    cvmx_read_csr(CVMX_GMXX_RXX_FRM_CTL
+					  (port, interface));
+			/* New field, so must be compile time */
+			frm_ctl.s.pre_free = 1;
+			cvmx_write_csr(CVMX_GMXX_RXX_FRM_CTL(port, interface),
+				       frm_ctl.u64);
+		}
+
+		/*
+		 * Each pause frame transmitted will ask for about 10M
+		 * bit times before resume.  If buffer space comes
+		 * available before that time has expired, an XON
+		 * pause frame (0 time) will be transmitted to restart
+		 * the flow.
+		 */
+		cvmx_write_csr(CVMX_GMXX_TXX_PAUSE_PKT_TIME(port, interface),
+			       20000);
+		cvmx_write_csr(CVMX_GMXX_TXX_PAUSE_PKT_INTERVAL
+			       (port, interface), 19000);
+
+		if (OCTEON_IS_MODEL(OCTEON_CN50XX)) {
+			cvmx_write_csr(CVMX_ASXX_TX_CLK_SETX(port, interface),
+				       16);
+			cvmx_write_csr(CVMX_ASXX_RX_CLK_SETX(port, interface),
+				       16);
+		} else {
+			cvmx_write_csr(CVMX_ASXX_TX_CLK_SETX(port, interface),
+				       24);
+			cvmx_write_csr(CVMX_ASXX_RX_CLK_SETX(port, interface),
+				       24);
+		}
+	}
+
+	__cvmx_helper_setup_gmx(interface, num_ports);
+
+	/* enable the ports now */
+	for (port = 0; port < num_ports; port++) {
+		union cvmx_gmxx_prtx_cfg gmx_cfg;
+		cvmx_helper_link_autoconf(cvmx_helper_get_ipd_port
+					  (interface, port));
+		gmx_cfg.u64 =
+		    cvmx_read_csr(CVMX_GMXX_PRTX_CFG(port, interface));
+		gmx_cfg.s.en = 1;
+		cvmx_write_csr(CVMX_GMXX_PRTX_CFG(port, interface),
+			       gmx_cfg.u64);
+	}
+	__cvmx_interrupt_asxx_enable(interface);
+	__cvmx_interrupt_gmxx_enable(interface);
+
+	return 0;
+}
+
+/**
+ * Return the link state of an IPD/PKO port as returned by
+ * auto negotiation. The result of this function may not match
+ * Octeon's link config if auto negotiation has changed since
+ * the last call to cvmx_helper_link_set().
+ *
+ * @ipd_port: IPD/PKO port to query
+ *
+ * Returns Link state
+ */
+cvmx_helper_link_info_t __cvmx_helper_rgmii_link_get(int ipd_port)
+{
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	int index = cvmx_helper_get_interface_index_num(ipd_port);
+	union cvmx_asxx_prt_loop asxx_prt_loop;
+
+	asxx_prt_loop.u64 = cvmx_read_csr(CVMX_ASXX_PRT_LOOP(interface));
+	if (asxx_prt_loop.s.int_loop & (1 << index)) {
+		/* Force 1Gbps full duplex on internal loopback */
+		cvmx_helper_link_info_t result;
+		result.u64 = 0;
+		result.s.full_duplex = 1;
+		result.s.link_up = 1;
+		result.s.speed = 1000;
+		return result;
+	} else
+		return __cvmx_helper_board_link_get(ipd_port);
+}
+
+/**
+ * Configure an IPD/PKO port for the specified link state. This
+ * function does not influence auto negotiation at the PHY level.
+ * The passed link state must always match the link state returned
+ * by cvmx_helper_link_get(). It is normally best to use
+ * cvmx_helper_link_autoconf() instead.
+ *
+ * @ipd_port:  IPD/PKO port to configure
+ * @link_info: The new link state
+ *
+ * Returns Zero on success, negative on failure
+ */
+int __cvmx_helper_rgmii_link_set(int ipd_port,
+				 cvmx_helper_link_info_t link_info)
+{
+	int result = 0;
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	int index = cvmx_helper_get_interface_index_num(ipd_port);
+	union cvmx_gmxx_prtx_cfg original_gmx_cfg;
+	union cvmx_gmxx_prtx_cfg new_gmx_cfg;
+	union cvmx_pko_mem_queue_qos pko_mem_queue_qos;
+	union cvmx_pko_mem_queue_qos pko_mem_queue_qos_save[16];
+	union cvmx_gmxx_tx_ovr_bp gmx_tx_ovr_bp;
+	union cvmx_gmxx_tx_ovr_bp gmx_tx_ovr_bp_save;
+	int i;
+
+	/* Ignore speed sets in the simulator */
+	if (cvmx_sysinfo_get()->board_type == CVMX_BOARD_TYPE_SIM)
+		return 0;
+
+	/* Read the current settings so we know the current enable state */
+	original_gmx_cfg.u64 =
+	    cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+	new_gmx_cfg = original_gmx_cfg;
+
+	/* Disable the lowest level RX */
+	cvmx_write_csr(CVMX_ASXX_RX_PRT_EN(interface),
+		       cvmx_read_csr(CVMX_ASXX_RX_PRT_EN(interface)) &
+				     ~(1 << index));
+
+	/* Disable all queues so that TX should become idle */
+	for (i = 0; i < cvmx_pko_get_num_queues(ipd_port); i++) {
+		int queue = cvmx_pko_get_base_queue(ipd_port) + i;
+		cvmx_write_csr(CVMX_PKO_REG_READ_IDX, queue);
+		pko_mem_queue_qos.u64 = cvmx_read_csr(CVMX_PKO_MEM_QUEUE_QOS);
+		pko_mem_queue_qos.s.pid = ipd_port;
+		pko_mem_queue_qos.s.qid = queue;
+		pko_mem_queue_qos_save[i] = pko_mem_queue_qos;
+		pko_mem_queue_qos.s.qos_mask = 0;
+		cvmx_write_csr(CVMX_PKO_MEM_QUEUE_QOS, pko_mem_queue_qos.u64);
+	}
+
+	/* Disable backpressure */
+	gmx_tx_ovr_bp.u64 = cvmx_read_csr(CVMX_GMXX_TX_OVR_BP(interface));
+	gmx_tx_ovr_bp_save = gmx_tx_ovr_bp;
+	gmx_tx_ovr_bp.s.bp &= ~(1 << index);
+	gmx_tx_ovr_bp.s.en |= 1 << index;
+	cvmx_write_csr(CVMX_GMXX_TX_OVR_BP(interface), gmx_tx_ovr_bp.u64);
+	cvmx_read_csr(CVMX_GMXX_TX_OVR_BP(interface));
+
+	/*
+	 * Poll the GMX state machine waiting for it to become
+	 * idle. Preferably we should only change speed when it is
+	 * idle. If it doesn't become idle we will still do the speed
+	 * change, but there is a slight chance that GMX will
+	 * lockup.
+	 */
+	cvmx_write_csr(CVMX_NPI_DBG_SELECT,
+		       interface * 0x800 + index * 0x100 + 0x880);
+	CVMX_WAIT_FOR_FIELD64(CVMX_DBG_DATA, union cvmx_dbg_data, data & 7,
+			==, 0, 10000);
+	CVMX_WAIT_FOR_FIELD64(CVMX_DBG_DATA, union cvmx_dbg_data, data & 0xf,
+			==, 0, 10000);
+
+	/* Disable the port before we make any changes */
+	new_gmx_cfg.s.en = 0;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), new_gmx_cfg.u64);
+	cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+
+	/* Set full/half duplex */
+	if (cvmx_octeon_is_pass1())
+		/* Half duplex is broken for 38XX Pass 1 */
+		new_gmx_cfg.s.duplex = 1;
+	else if (!link_info.s.link_up)
+		/* Force full duplex on down links */
+		new_gmx_cfg.s.duplex = 1;
+	else
+		new_gmx_cfg.s.duplex = link_info.s.full_duplex;
+
+	/* Set the link speed. Anything unknown is set to 1Gbps */
+	if (link_info.s.speed == 10) {
+		new_gmx_cfg.s.slottime = 0;
+		new_gmx_cfg.s.speed = 0;
+	} else if (link_info.s.speed == 100) {
+		new_gmx_cfg.s.slottime = 0;
+		new_gmx_cfg.s.speed = 0;
+	} else {
+		new_gmx_cfg.s.slottime = 1;
+		new_gmx_cfg.s.speed = 1;
+	}
+
+	/* Adjust the clocks */
+	if (link_info.s.speed == 10) {
+		cvmx_write_csr(CVMX_GMXX_TXX_CLK(index, interface), 50);
+		cvmx_write_csr(CVMX_GMXX_TXX_SLOT(index, interface), 0x40);
+		cvmx_write_csr(CVMX_GMXX_TXX_BURST(index, interface), 0);
+	} else if (link_info.s.speed == 100) {
+		cvmx_write_csr(CVMX_GMXX_TXX_CLK(index, interface), 5);
+		cvmx_write_csr(CVMX_GMXX_TXX_SLOT(index, interface), 0x40);
+		cvmx_write_csr(CVMX_GMXX_TXX_BURST(index, interface), 0);
+	} else {
+		cvmx_write_csr(CVMX_GMXX_TXX_CLK(index, interface), 1);
+		cvmx_write_csr(CVMX_GMXX_TXX_SLOT(index, interface), 0x200);
+		cvmx_write_csr(CVMX_GMXX_TXX_BURST(index, interface), 0x2000);
+	}
+
+	if (OCTEON_IS_MODEL(OCTEON_CN30XX) || OCTEON_IS_MODEL(OCTEON_CN50XX)) {
+		if ((link_info.s.speed == 10) || (link_info.s.speed == 100)) {
+			union cvmx_gmxx_inf_mode mode;
+			mode.u64 = cvmx_read_csr(CVMX_GMXX_INF_MODE(interface));
+
+	/*
+	 * Port  .en  .type  .p0mii  Configuration
+	 * ----  ---  -----  ------  -----------------------------------------
+	 *  X      0     X      X    All links are disabled.
+	 *  0      1     X      0    Port 0 is RGMII
+	 *  0      1     X      1    Port 0 is MII
+	 *  1      1     0      X    Ports 1 and 2 are configured as RGMII ports.
+	 *  1      1     1      X    Port 1: GMII/MII; Port 2: disabled. GMII or
+	 *                           MII port is selected by GMX_PRT1_CFG[SPEED].
+	 */
+
+			/* In MII mode, CLK_CNT = 1. */
+			if (((index == 0) && (mode.s.p0mii == 1))
+			    || ((index != 0) && (mode.s.type == 1))) {
+				cvmx_write_csr(CVMX_GMXX_TXX_CLK
+					       (index, interface), 1);
+			}
+		}
+	}
+
+	/* Do a read to make sure all setup stuff is complete */
+	cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+
+	/* Save the new GMX setting without enabling the port */
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), new_gmx_cfg.u64);
+
+	/* Enable the lowest level RX */
+	cvmx_write_csr(CVMX_ASXX_RX_PRT_EN(interface),
+		       cvmx_read_csr(CVMX_ASXX_RX_PRT_EN(interface)) | (1 <<
+									index));
+
+	/* Re-enable the TX path */
+	for (i = 0; i < cvmx_pko_get_num_queues(ipd_port); i++) {
+		int queue = cvmx_pko_get_base_queue(ipd_port) + i;
+		cvmx_write_csr(CVMX_PKO_REG_READ_IDX, queue);
+		cvmx_write_csr(CVMX_PKO_MEM_QUEUE_QOS,
+			       pko_mem_queue_qos_save[i].u64);
+	}
+
+	/* Restore backpressure */
+	cvmx_write_csr(CVMX_GMXX_TX_OVR_BP(interface), gmx_tx_ovr_bp_save.u64);
+
+	/* Restore the GMX enable state. Port config is complete */
+	new_gmx_cfg.s.en = original_gmx_cfg.s.en;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), new_gmx_cfg.u64);
+
+	return result;
+}
+
+/**
+ * Configure a port for internal and/or external loopback. Internal loopback
+ * causes packets sent by the port to be received by Octeon. External loopback
+ * causes packets received from the wire to sent out again.
+ *
+ * @ipd_port: IPD/PKO port to loopback.
+ * @enable_internal:
+ *                 Non zero if you want internal loopback
+ * @enable_external:
+ *                 Non zero if you want external loopback
+ *
+ * Returns Zero on success, negative on failure.
+ */
+int __cvmx_helper_rgmii_configure_loopback(int ipd_port, int enable_internal,
+					   int enable_external)
+{
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	int index = cvmx_helper_get_interface_index_num(ipd_port);
+	int original_enable;
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	union cvmx_asxx_prt_loop asxx_prt_loop;
+
+	/* Read the current enable state and save it */
+	gmx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+	original_enable = gmx_cfg.s.en;
+	/* Force port to be disabled */
+	gmx_cfg.s.en = 0;
+	if (enable_internal) {
+		/* Force speed if we're doing internal loopback */
+		gmx_cfg.s.duplex = 1;
+		gmx_cfg.s.slottime = 1;
+		gmx_cfg.s.speed = 1;
+		cvmx_write_csr(CVMX_GMXX_TXX_CLK(index, interface), 1);
+		cvmx_write_csr(CVMX_GMXX_TXX_SLOT(index, interface), 0x200);
+		cvmx_write_csr(CVMX_GMXX_TXX_BURST(index, interface), 0x2000);
+	}
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmx_cfg.u64);
+
+	/* Set the loopback bits */
+	asxx_prt_loop.u64 = cvmx_read_csr(CVMX_ASXX_PRT_LOOP(interface));
+	if (enable_internal)
+		asxx_prt_loop.s.int_loop |= 1 << index;
+	else
+		asxx_prt_loop.s.int_loop &= ~(1 << index);
+	if (enable_external)
+		asxx_prt_loop.s.ext_loop |= 1 << index;
+	else
+		asxx_prt_loop.s.ext_loop &= ~(1 << index);
+	cvmx_write_csr(CVMX_ASXX_PRT_LOOP(interface), asxx_prt_loop.u64);
+
+	/* Force enables in internal loopback */
+	if (enable_internal) {
+		uint64_t tmp;
+		tmp = cvmx_read_csr(CVMX_ASXX_TX_PRT_EN(interface));
+		cvmx_write_csr(CVMX_ASXX_TX_PRT_EN(interface),
+			       (1 << index) | tmp);
+		tmp = cvmx_read_csr(CVMX_ASXX_RX_PRT_EN(interface));
+		cvmx_write_csr(CVMX_ASXX_RX_PRT_EN(interface),
+			       (1 << index) | tmp);
+		original_enable = 1;
+	}
+
+	/* Restore the enable state */
+	gmx_cfg.s.en = original_enable;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmx_cfg.u64);
+	return 0;
+}
diff --git a/drivers/staging/octeon/cvmx-helper-rgmii.h b/drivers/staging/octeon/cvmx-helper-rgmii.h
new file mode 100644
index 0000000..ea26526
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-rgmii.h
@@ -0,0 +1,110 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * @file
+ *
+ * Functions for RGMII/GMII/MII initialization, configuration,
+ * and monitoring.
+ *
+ */
+#ifndef __CVMX_HELPER_RGMII_H__
+#define __CVMX_HELPER_RGMII_H__
+
+/**
+ * Probe RGMII ports and determine the number present
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of RGMII/GMII/MII ports (0-4).
+ */
+extern int __cvmx_helper_rgmii_probe(int interface);
+
+/**
+ * Put an RGMII interface in loopback mode. Internal packets sent
+ * out will be received back again on the same port. Externally
+ * received packets will echo back out.
+ *
+ * @port:   IPD port number to loop.
+ */
+extern void cvmx_helper_rgmii_internal_loopback(int port);
+
+/**
+ * Configure all of the ASX, GMX, and PKO regsiters required
+ * to get RGMII to function on the supplied interface.
+ *
+ * @interface: PKO Interface to configure (0 or 1)
+ *
+ * Returns Zero on success
+ */
+extern int __cvmx_helper_rgmii_enable(int interface);
+
+/**
+ * Return the link state of an IPD/PKO port as returned by
+ * auto negotiation. The result of this function may not match
+ * Octeon's link config if auto negotiation has changed since
+ * the last call to cvmx_helper_link_set().
+ *
+ * @ipd_port: IPD/PKO port to query
+ *
+ * Returns Link state
+ */
+extern cvmx_helper_link_info_t __cvmx_helper_rgmii_link_get(int ipd_port);
+
+/**
+ * Configure an IPD/PKO port for the specified link state. This
+ * function does not influence auto negotiation at the PHY level.
+ * The passed link state must always match the link state returned
+ * by cvmx_helper_link_get(). It is normally best to use
+ * cvmx_helper_link_autoconf() instead.
+ *
+ * @ipd_port:  IPD/PKO port to configure
+ * @link_info: The new link state
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int __cvmx_helper_rgmii_link_set(int ipd_port,
+					cvmx_helper_link_info_t link_info);
+
+/**
+ * Configure a port for internal and/or external loopback. Internal loopback
+ * causes packets sent by the port to be received by Octeon. External loopback
+ * causes packets received from the wire to sent out again.
+ *
+ * @ipd_port: IPD/PKO port to loopback.
+ * @enable_internal:
+ *                 Non zero if you want internal loopback
+ * @enable_external:
+ *                 Non zero if you want external loopback
+ *
+ * Returns Zero on success, negative on failure.
+ */
+extern int __cvmx_helper_rgmii_configure_loopback(int ipd_port,
+						  int enable_internal,
+						  int enable_external);
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-helper-sgmii.c b/drivers/staging/octeon/cvmx-helper-sgmii.c
new file mode 100644
index 0000000..6214e3b
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-sgmii.c
@@ -0,0 +1,550 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Functions for SGMII initialization, configuration,
+ * and monitoring.
+ */
+
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-config.h"
+
+#include "cvmx-mdio.h"
+#include "cvmx-helper.h"
+#include "cvmx-helper-board.h"
+
+#include "cvmx-gmxx-defs.h"
+#include "cvmx-pcsx-defs.h"
+
+void __cvmx_interrupt_gmxx_enable(int interface);
+void __cvmx_interrupt_pcsx_intx_en_reg_enable(int index, int block);
+void __cvmx_interrupt_pcsxx_int_en_reg_enable(int index);
+
+/**
+ * Perform initialization required only once for an SGMII port.
+ *
+ * @interface: Interface to init
+ * @index:     Index of prot on the interface
+ *
+ * Returns Zero on success, negative on failure
+ */
+static int __cvmx_helper_sgmii_hardware_init_one_time(int interface, int index)
+{
+	const uint64_t clock_mhz = cvmx_sysinfo_get()->cpu_clock_hz / 1000000;
+	union cvmx_pcsx_miscx_ctl_reg pcs_misc_ctl_reg;
+	union cvmx_pcsx_linkx_timer_count_reg pcsx_linkx_timer_count_reg;
+	union cvmx_gmxx_prtx_cfg gmxx_prtx_cfg;
+
+	/* Disable GMX */
+	gmxx_prtx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+	gmxx_prtx_cfg.s.en = 0;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmxx_prtx_cfg.u64);
+
+	/*
+	 * Write PCS*_LINK*_TIMER_COUNT_REG[COUNT] with the
+	 * appropriate value. 1000BASE-X specifies a 10ms
+	 * interval. SGMII specifies a 1.6ms interval.
+	 */
+	pcs_misc_ctl_reg.u64 =
+	    cvmx_read_csr(CVMX_PCSX_MISCX_CTL_REG(index, interface));
+	pcsx_linkx_timer_count_reg.u64 =
+	    cvmx_read_csr(CVMX_PCSX_LINKX_TIMER_COUNT_REG(index, interface));
+	if (pcs_misc_ctl_reg.s.mode) {
+		/* 1000BASE-X */
+		pcsx_linkx_timer_count_reg.s.count =
+		    (10000ull * clock_mhz) >> 10;
+	} else {
+		/* SGMII */
+		pcsx_linkx_timer_count_reg.s.count =
+		    (1600ull * clock_mhz) >> 10;
+	}
+	cvmx_write_csr(CVMX_PCSX_LINKX_TIMER_COUNT_REG(index, interface),
+		       pcsx_linkx_timer_count_reg.u64);
+
+	/*
+	 * Write the advertisement register to be used as the
+	 * tx_Config_Reg<D15:D0> of the autonegotiation.  In
+	 * 1000BASE-X mode, tx_Config_Reg<D15:D0> is PCS*_AN*_ADV_REG.
+	 * In SGMII PHY mode, tx_Config_Reg<D15:D0> is
+	 * PCS*_SGM*_AN_ADV_REG.  In SGMII MAC mode,
+	 * tx_Config_Reg<D15:D0> is the fixed value 0x4001, so this
+	 * step can be skipped.
+	 */
+	if (pcs_misc_ctl_reg.s.mode) {
+		/* 1000BASE-X */
+		union cvmx_pcsx_anx_adv_reg pcsx_anx_adv_reg;
+		pcsx_anx_adv_reg.u64 =
+		    cvmx_read_csr(CVMX_PCSX_ANX_ADV_REG(index, interface));
+		pcsx_anx_adv_reg.s.rem_flt = 0;
+		pcsx_anx_adv_reg.s.pause = 3;
+		pcsx_anx_adv_reg.s.hfd = 1;
+		pcsx_anx_adv_reg.s.fd = 1;
+		cvmx_write_csr(CVMX_PCSX_ANX_ADV_REG(index, interface),
+			       pcsx_anx_adv_reg.u64);
+	} else {
+		union cvmx_pcsx_miscx_ctl_reg pcsx_miscx_ctl_reg;
+		pcsx_miscx_ctl_reg.u64 =
+		    cvmx_read_csr(CVMX_PCSX_MISCX_CTL_REG(index, interface));
+		if (pcsx_miscx_ctl_reg.s.mac_phy) {
+			/* PHY Mode */
+			union cvmx_pcsx_sgmx_an_adv_reg pcsx_sgmx_an_adv_reg;
+			pcsx_sgmx_an_adv_reg.u64 =
+			    cvmx_read_csr(CVMX_PCSX_SGMX_AN_ADV_REG
+					  (index, interface));
+			pcsx_sgmx_an_adv_reg.s.link = 1;
+			pcsx_sgmx_an_adv_reg.s.dup = 1;
+			pcsx_sgmx_an_adv_reg.s.speed = 2;
+			cvmx_write_csr(CVMX_PCSX_SGMX_AN_ADV_REG
+				       (index, interface),
+				       pcsx_sgmx_an_adv_reg.u64);
+		} else {
+			/* MAC Mode - Nothing to do */
+		}
+	}
+	return 0;
+}
+
+/**
+ * Initialize the SERTES link for the first time or after a loss
+ * of link.
+ *
+ * @interface: Interface to init
+ * @index:     Index of prot on the interface
+ *
+ * Returns Zero on success, negative on failure
+ */
+static int __cvmx_helper_sgmii_hardware_init_link(int interface, int index)
+{
+	union cvmx_pcsx_mrx_control_reg control_reg;
+
+	/*
+	 * Take PCS through a reset sequence.
+	 * PCS*_MR*_CONTROL_REG[PWR_DN] should be cleared to zero.
+	 * Write PCS*_MR*_CONTROL_REG[RESET]=1 (while not changing the
+	 * value of the other PCS*_MR*_CONTROL_REG bits).  Read
+	 * PCS*_MR*_CONTROL_REG[RESET] until it changes value to
+	 * zero.
+	 */
+	control_reg.u64 =
+	    cvmx_read_csr(CVMX_PCSX_MRX_CONTROL_REG(index, interface));
+	if (cvmx_sysinfo_get()->board_type != CVMX_BOARD_TYPE_SIM) {
+		control_reg.s.reset = 1;
+		cvmx_write_csr(CVMX_PCSX_MRX_CONTROL_REG(index, interface),
+			       control_reg.u64);
+		if (CVMX_WAIT_FOR_FIELD64
+		    (CVMX_PCSX_MRX_CONTROL_REG(index, interface),
+		     union cvmx_pcsx_mrx_control_reg, reset, ==, 0, 10000)) {
+			cvmx_dprintf("SGMII%d: Timeout waiting for port %d "
+				     "to finish reset\n",
+			     interface, index);
+			return -1;
+		}
+	}
+
+	/*
+	 * Write PCS*_MR*_CONTROL_REG[RST_AN]=1 to ensure a fresh
+	 * sgmii negotiation starts.
+	 */
+	control_reg.s.rst_an = 1;
+	control_reg.s.an_en = 1;
+	control_reg.s.pwr_dn = 0;
+	cvmx_write_csr(CVMX_PCSX_MRX_CONTROL_REG(index, interface),
+		       control_reg.u64);
+
+	/*
+	 * Wait for PCS*_MR*_STATUS_REG[AN_CPT] to be set, indicating
+	 * that sgmii autonegotiation is complete. In MAC mode this
+	 * isn't an ethernet link, but a link between Octeon and the
+	 * PHY.
+	 */
+	if ((cvmx_sysinfo_get()->board_type != CVMX_BOARD_TYPE_SIM) &&
+	    CVMX_WAIT_FOR_FIELD64(CVMX_PCSX_MRX_STATUS_REG(index, interface),
+				  union cvmx_pcsx_mrx_status_reg, an_cpt, ==, 1,
+				  10000)) {
+		/* cvmx_dprintf("SGMII%d: Port %d link timeout\n", interface, index); */
+		return -1;
+	}
+	return 0;
+}
+
+/**
+ * Configure an SGMII link to the specified speed after the SERTES
+ * link is up.
+ *
+ * @interface: Interface to init
+ * @index:     Index of prot on the interface
+ * @link_info: Link state to configure
+ *
+ * Returns Zero on success, negative on failure
+ */
+static int __cvmx_helper_sgmii_hardware_init_link_speed(int interface,
+							int index,
+							cvmx_helper_link_info_t
+							link_info)
+{
+	int is_enabled;
+	union cvmx_gmxx_prtx_cfg gmxx_prtx_cfg;
+	union cvmx_pcsx_miscx_ctl_reg pcsx_miscx_ctl_reg;
+
+	/* Disable GMX before we make any changes. Remember the enable state */
+	gmxx_prtx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+	is_enabled = gmxx_prtx_cfg.s.en;
+	gmxx_prtx_cfg.s.en = 0;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmxx_prtx_cfg.u64);
+
+	/* Wait for GMX to be idle */
+	if (CVMX_WAIT_FOR_FIELD64
+	    (CVMX_GMXX_PRTX_CFG(index, interface), union cvmx_gmxx_prtx_cfg,
+	     rx_idle, ==, 1, 10000)
+	    || CVMX_WAIT_FOR_FIELD64(CVMX_GMXX_PRTX_CFG(index, interface),
+				     union cvmx_gmxx_prtx_cfg, tx_idle, ==, 1,
+				     10000)) {
+		cvmx_dprintf
+		    ("SGMII%d: Timeout waiting for port %d to be idle\n",
+		     interface, index);
+		return -1;
+	}
+
+	/* Read GMX CFG again to make sure the disable completed */
+	gmxx_prtx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+
+	/*
+	 * Get the misc control for PCS. We will need to set the
+	 * duplication amount.
+	 */
+	pcsx_miscx_ctl_reg.u64 =
+	    cvmx_read_csr(CVMX_PCSX_MISCX_CTL_REG(index, interface));
+
+	/*
+	 * Use GMXENO to force the link down if the status we get says
+	 * it should be down.
+	 */
+	pcsx_miscx_ctl_reg.s.gmxeno = !link_info.s.link_up;
+
+	/* Only change the duplex setting if the link is up */
+	if (link_info.s.link_up)
+		gmxx_prtx_cfg.s.duplex = link_info.s.full_duplex;
+
+	/* Do speed based setting for GMX */
+	switch (link_info.s.speed) {
+	case 10:
+		gmxx_prtx_cfg.s.speed = 0;
+		gmxx_prtx_cfg.s.speed_msb = 1;
+		gmxx_prtx_cfg.s.slottime = 0;
+		/* Setting from GMX-603 */
+		pcsx_miscx_ctl_reg.s.samp_pt = 25;
+		cvmx_write_csr(CVMX_GMXX_TXX_SLOT(index, interface), 64);
+		cvmx_write_csr(CVMX_GMXX_TXX_BURST(index, interface), 0);
+		break;
+	case 100:
+		gmxx_prtx_cfg.s.speed = 0;
+		gmxx_prtx_cfg.s.speed_msb = 0;
+		gmxx_prtx_cfg.s.slottime = 0;
+		pcsx_miscx_ctl_reg.s.samp_pt = 0x5;
+		cvmx_write_csr(CVMX_GMXX_TXX_SLOT(index, interface), 64);
+		cvmx_write_csr(CVMX_GMXX_TXX_BURST(index, interface), 0);
+		break;
+	case 1000:
+		gmxx_prtx_cfg.s.speed = 1;
+		gmxx_prtx_cfg.s.speed_msb = 0;
+		gmxx_prtx_cfg.s.slottime = 1;
+		pcsx_miscx_ctl_reg.s.samp_pt = 1;
+		cvmx_write_csr(CVMX_GMXX_TXX_SLOT(index, interface), 512);
+		cvmx_write_csr(CVMX_GMXX_TXX_BURST(index, interface), 8192);
+		break;
+	default:
+		break;
+	}
+
+	/* Write the new misc control for PCS */
+	cvmx_write_csr(CVMX_PCSX_MISCX_CTL_REG(index, interface),
+		       pcsx_miscx_ctl_reg.u64);
+
+	/* Write the new GMX settings with the port still disabled */
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmxx_prtx_cfg.u64);
+
+	/* Read GMX CFG again to make sure the config completed */
+	gmxx_prtx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+
+	/* Restore the enabled / disabled state */
+	gmxx_prtx_cfg.s.en = is_enabled;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmxx_prtx_cfg.u64);
+
+	return 0;
+}
+
+/**
+ * Bring up the SGMII interface to be ready for packet I/O but
+ * leave I/O disabled using the GMX override. This function
+ * follows the bringup documented in 10.6.3 of the manual.
+ *
+ * @interface: Interface to bringup
+ * @num_ports: Number of ports on the interface
+ *
+ * Returns Zero on success, negative on failure
+ */
+static int __cvmx_helper_sgmii_hardware_init(int interface, int num_ports)
+{
+	int index;
+
+	__cvmx_helper_setup_gmx(interface, num_ports);
+
+	for (index = 0; index < num_ports; index++) {
+		int ipd_port = cvmx_helper_get_ipd_port(interface, index);
+		__cvmx_helper_sgmii_hardware_init_one_time(interface, index);
+		__cvmx_helper_sgmii_link_set(ipd_port,
+					     __cvmx_helper_sgmii_link_get
+					     (ipd_port));
+
+	}
+
+	return 0;
+}
+
+/**
+ * Probe a SGMII interface and determine the number of ports
+ * connected to it. The SGMII interface should still be down after
+ * this call.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of ports on the interface. Zero to disable.
+ */
+int __cvmx_helper_sgmii_probe(int interface)
+{
+	union cvmx_gmxx_inf_mode mode;
+
+	/*
+	 * Due to errata GMX-700 on CN56XXp1.x and CN52XXp1.x, the
+	 * interface needs to be enabled before IPD otherwise per port
+	 * backpressure may not work properly
+	 */
+	mode.u64 = cvmx_read_csr(CVMX_GMXX_INF_MODE(interface));
+	mode.s.en = 1;
+	cvmx_write_csr(CVMX_GMXX_INF_MODE(interface), mode.u64);
+	return 4;
+}
+
+/**
+ * Bringup and enable a SGMII interface. After this call packet
+ * I/O should be fully functional. This is called with IPD
+ * enabled but PKO disabled.
+ *
+ * @interface: Interface to bring up
+ *
+ * Returns Zero on success, negative on failure
+ */
+int __cvmx_helper_sgmii_enable(int interface)
+{
+	int num_ports = cvmx_helper_ports_on_interface(interface);
+	int index;
+
+	__cvmx_helper_sgmii_hardware_init(interface, num_ports);
+
+	for (index = 0; index < num_ports; index++) {
+		union cvmx_gmxx_prtx_cfg gmxx_prtx_cfg;
+		gmxx_prtx_cfg.u64 =
+		    cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+		gmxx_prtx_cfg.s.en = 1;
+		cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface),
+			       gmxx_prtx_cfg.u64);
+		__cvmx_interrupt_pcsx_intx_en_reg_enable(index, interface);
+	}
+	__cvmx_interrupt_pcsxx_int_en_reg_enable(interface);
+	__cvmx_interrupt_gmxx_enable(interface);
+	return 0;
+}
+
+/**
+ * Return the link state of an IPD/PKO port as returned by
+ * auto negotiation. The result of this function may not match
+ * Octeon's link config if auto negotiation has changed since
+ * the last call to cvmx_helper_link_set().
+ *
+ * @ipd_port: IPD/PKO port to query
+ *
+ * Returns Link state
+ */
+cvmx_helper_link_info_t __cvmx_helper_sgmii_link_get(int ipd_port)
+{
+	cvmx_helper_link_info_t result;
+	union cvmx_pcsx_miscx_ctl_reg pcs_misc_ctl_reg;
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	int index = cvmx_helper_get_interface_index_num(ipd_port);
+	union cvmx_pcsx_mrx_control_reg pcsx_mrx_control_reg;
+
+	result.u64 = 0;
+
+	if (cvmx_sysinfo_get()->board_type == CVMX_BOARD_TYPE_SIM) {
+		/* The simulator gives you a simulated 1Gbps full duplex link */
+		result.s.link_up = 1;
+		result.s.full_duplex = 1;
+		result.s.speed = 1000;
+		return result;
+	}
+
+	pcsx_mrx_control_reg.u64 =
+	    cvmx_read_csr(CVMX_PCSX_MRX_CONTROL_REG(index, interface));
+	if (pcsx_mrx_control_reg.s.loopbck1) {
+		/* Force 1Gbps full duplex link for internal loopback */
+		result.s.link_up = 1;
+		result.s.full_duplex = 1;
+		result.s.speed = 1000;
+		return result;
+	}
+
+	pcs_misc_ctl_reg.u64 =
+	    cvmx_read_csr(CVMX_PCSX_MISCX_CTL_REG(index, interface));
+	if (pcs_misc_ctl_reg.s.mode) {
+		/* 1000BASE-X */
+		/* FIXME */
+	} else {
+		union cvmx_pcsx_miscx_ctl_reg pcsx_miscx_ctl_reg;
+		pcsx_miscx_ctl_reg.u64 =
+		    cvmx_read_csr(CVMX_PCSX_MISCX_CTL_REG(index, interface));
+		if (pcsx_miscx_ctl_reg.s.mac_phy) {
+			/* PHY Mode */
+			union cvmx_pcsx_mrx_status_reg pcsx_mrx_status_reg;
+			union cvmx_pcsx_anx_results_reg pcsx_anx_results_reg;
+
+			/*
+			 * Don't bother continuing if the SERTES low
+			 * level link is down
+			 */
+			pcsx_mrx_status_reg.u64 =
+			    cvmx_read_csr(CVMX_PCSX_MRX_STATUS_REG
+					  (index, interface));
+			if (pcsx_mrx_status_reg.s.lnk_st == 0) {
+				if (__cvmx_helper_sgmii_hardware_init_link
+				    (interface, index) != 0)
+					return result;
+			}
+
+			/* Read the autoneg results */
+			pcsx_anx_results_reg.u64 =
+			    cvmx_read_csr(CVMX_PCSX_ANX_RESULTS_REG
+					  (index, interface));
+			if (pcsx_anx_results_reg.s.an_cpt) {
+				/*
+				 * Auto negotiation is complete. Set
+				 * status accordingly.
+				 */
+				result.s.full_duplex =
+				    pcsx_anx_results_reg.s.dup;
+				result.s.link_up =
+				    pcsx_anx_results_reg.s.link_ok;
+				switch (pcsx_anx_results_reg.s.spd) {
+				case 0:
+					result.s.speed = 10;
+					break;
+				case 1:
+					result.s.speed = 100;
+					break;
+				case 2:
+					result.s.speed = 1000;
+					break;
+				default:
+					result.s.speed = 0;
+					result.s.link_up = 0;
+					break;
+				}
+			} else {
+				/*
+				 * Auto negotiation isn't
+				 * complete. Return link down.
+				 */
+				result.s.speed = 0;
+				result.s.link_up = 0;
+			}
+		} else {	/* MAC Mode */
+
+			result = __cvmx_helper_board_link_get(ipd_port);
+		}
+	}
+	return result;
+}
+
+/**
+ * Configure an IPD/PKO port for the specified link state. This
+ * function does not influence auto negotiation at the PHY level.
+ * The passed link state must always match the link state returned
+ * by cvmx_helper_link_get(). It is normally best to use
+ * cvmx_helper_link_autoconf() instead.
+ *
+ * @ipd_port:  IPD/PKO port to configure
+ * @link_info: The new link state
+ *
+ * Returns Zero on success, negative on failure
+ */
+int __cvmx_helper_sgmii_link_set(int ipd_port,
+				 cvmx_helper_link_info_t link_info)
+{
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	int index = cvmx_helper_get_interface_index_num(ipd_port);
+	__cvmx_helper_sgmii_hardware_init_link(interface, index);
+	return __cvmx_helper_sgmii_hardware_init_link_speed(interface, index,
+							    link_info);
+}
+
+/**
+ * Configure a port for internal and/or external loopback. Internal
+ * loopback causes packets sent by the port to be received by
+ * Octeon. External loopback causes packets received from the wire to
+ * sent out again.
+ *
+ * @ipd_port: IPD/PKO port to loopback.
+ * @enable_internal:
+ *                 Non zero if you want internal loopback
+ * @enable_external:
+ *                 Non zero if you want external loopback
+ *
+ * Returns Zero on success, negative on failure.
+ */
+int __cvmx_helper_sgmii_configure_loopback(int ipd_port, int enable_internal,
+					   int enable_external)
+{
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	int index = cvmx_helper_get_interface_index_num(ipd_port);
+	union cvmx_pcsx_mrx_control_reg pcsx_mrx_control_reg;
+	union cvmx_pcsx_miscx_ctl_reg pcsx_miscx_ctl_reg;
+
+	pcsx_mrx_control_reg.u64 =
+	    cvmx_read_csr(CVMX_PCSX_MRX_CONTROL_REG(index, interface));
+	pcsx_mrx_control_reg.s.loopbck1 = enable_internal;
+	cvmx_write_csr(CVMX_PCSX_MRX_CONTROL_REG(index, interface),
+		       pcsx_mrx_control_reg.u64);
+
+	pcsx_miscx_ctl_reg.u64 =
+	    cvmx_read_csr(CVMX_PCSX_MISCX_CTL_REG(index, interface));
+	pcsx_miscx_ctl_reg.s.loopbck2 = enable_external;
+	cvmx_write_csr(CVMX_PCSX_MISCX_CTL_REG(index, interface),
+		       pcsx_miscx_ctl_reg.u64);
+
+	__cvmx_helper_sgmii_hardware_init_link(interface, index);
+	return 0;
+}
diff --git a/drivers/staging/octeon/cvmx-helper-sgmii.h b/drivers/staging/octeon/cvmx-helper-sgmii.h
new file mode 100644
index 0000000..19b48d6
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-sgmii.h
@@ -0,0 +1,104 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * @file
+ *
+ * Functions for SGMII initialization, configuration,
+ * and monitoring.
+ *
+ */
+#ifndef __CVMX_HELPER_SGMII_H__
+#define __CVMX_HELPER_SGMII_H__
+
+/**
+ * Probe a SGMII interface and determine the number of ports
+ * connected to it. The SGMII interface should still be down after
+ * this call.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of ports on the interface. Zero to disable.
+ */
+extern int __cvmx_helper_sgmii_probe(int interface);
+
+/**
+ * Bringup and enable a SGMII interface. After this call packet
+ * I/O should be fully functional. This is called with IPD
+ * enabled but PKO disabled.
+ *
+ * @interface: Interface to bring up
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int __cvmx_helper_sgmii_enable(int interface);
+
+/**
+ * Return the link state of an IPD/PKO port as returned by
+ * auto negotiation. The result of this function may not match
+ * Octeon's link config if auto negotiation has changed since
+ * the last call to cvmx_helper_link_set().
+ *
+ * @ipd_port: IPD/PKO port to query
+ *
+ * Returns Link state
+ */
+extern cvmx_helper_link_info_t __cvmx_helper_sgmii_link_get(int ipd_port);
+
+/**
+ * Configure an IPD/PKO port for the specified link state. This
+ * function does not influence auto negotiation at the PHY level.
+ * The passed link state must always match the link state returned
+ * by cvmx_helper_link_get(). It is normally best to use
+ * cvmx_helper_link_autoconf() instead.
+ *
+ * @ipd_port:  IPD/PKO port to configure
+ * @link_info: The new link state
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int __cvmx_helper_sgmii_link_set(int ipd_port,
+					cvmx_helper_link_info_t link_info);
+
+/**
+ * Configure a port for internal and/or external loopback. Internal loopback
+ * causes packets sent by the port to be received by Octeon. External loopback
+ * causes packets received from the wire to sent out again.
+ *
+ * @ipd_port: IPD/PKO port to loopback.
+ * @enable_internal:
+ *                 Non zero if you want internal loopback
+ * @enable_external:
+ *                 Non zero if you want external loopback
+ *
+ * Returns Zero on success, negative on failure.
+ */
+extern int __cvmx_helper_sgmii_configure_loopback(int ipd_port,
+						  int enable_internal,
+						  int enable_external);
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-helper-spi.c b/drivers/staging/octeon/cvmx-helper-spi.c
new file mode 100644
index 0000000..8ba6c83
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-spi.c
@@ -0,0 +1,195 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+void __cvmx_interrupt_gmxx_enable(int interface);
+void __cvmx_interrupt_spxx_int_msk_enable(int index);
+void __cvmx_interrupt_stxx_int_msk_enable(int index);
+
+/*
+ * Functions for SPI initialization, configuration,
+ * and monitoring.
+ */
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-config.h"
+#include "cvmx-spi.h"
+#include "cvmx-helper.h"
+
+#include "cvmx-pip-defs.h"
+#include "cvmx-pko-defs.h"
+
+/*
+ * CVMX_HELPER_SPI_TIMEOUT is used to determine how long the SPI
+ * initialization routines wait for SPI training. You can override the
+ * value using executive-config.h if necessary.
+ */
+#ifndef CVMX_HELPER_SPI_TIMEOUT
+#define CVMX_HELPER_SPI_TIMEOUT 10
+#endif
+
+/**
+ * Probe a SPI interface and determine the number of ports
+ * connected to it. The SPI interface should still be down after
+ * this call.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of ports on the interface. Zero to disable.
+ */
+int __cvmx_helper_spi_probe(int interface)
+{
+	int num_ports = 0;
+
+	if ((cvmx_sysinfo_get()->board_type != CVMX_BOARD_TYPE_SIM) &&
+	    cvmx_spi4000_is_present(interface)) {
+		num_ports = 10;
+	} else {
+		union cvmx_pko_reg_crc_enable enable;
+		num_ports = 16;
+		/*
+		 * Unlike the SPI4000, most SPI devices don't
+		 * automatically put on the L2 CRC. For everything
+		 * except for the SPI4000 have PKO append the L2 CRC
+		 * to the packet.
+		 */
+		enable.u64 = cvmx_read_csr(CVMX_PKO_REG_CRC_ENABLE);
+		enable.s.enable |= 0xffff << (interface * 16);
+		cvmx_write_csr(CVMX_PKO_REG_CRC_ENABLE, enable.u64);
+	}
+	__cvmx_helper_setup_gmx(interface, num_ports);
+	return num_ports;
+}
+
+/**
+ * Bringup and enable a SPI interface. After this call packet I/O
+ * should be fully functional. This is called with IPD enabled but
+ * PKO disabled.
+ *
+ * @interface: Interface to bring up
+ *
+ * Returns Zero on success, negative on failure
+ */
+int __cvmx_helper_spi_enable(int interface)
+{
+	/*
+	 * Normally the ethernet L2 CRC is checked and stripped in the
+	 * GMX block.  When you are using SPI, this isn' the case and
+	 * IPD needs to check the L2 CRC.
+	 */
+	int num_ports = cvmx_helper_ports_on_interface(interface);
+	int ipd_port;
+	for (ipd_port = interface * 16; ipd_port < interface * 16 + num_ports;
+	     ipd_port++) {
+		union cvmx_pip_prt_cfgx port_config;
+		port_config.u64 = cvmx_read_csr(CVMX_PIP_PRT_CFGX(ipd_port));
+		port_config.s.crc_en = 1;
+		cvmx_write_csr(CVMX_PIP_PRT_CFGX(ipd_port), port_config.u64);
+	}
+
+	if (cvmx_sysinfo_get()->board_type != CVMX_BOARD_TYPE_SIM) {
+		cvmx_spi_start_interface(interface, CVMX_SPI_MODE_DUPLEX,
+					 CVMX_HELPER_SPI_TIMEOUT, num_ports);
+		if (cvmx_spi4000_is_present(interface))
+			cvmx_spi4000_initialize(interface);
+	}
+	__cvmx_interrupt_spxx_int_msk_enable(interface);
+	__cvmx_interrupt_stxx_int_msk_enable(interface);
+	__cvmx_interrupt_gmxx_enable(interface);
+	return 0;
+}
+
+/**
+ * Return the link state of an IPD/PKO port as returned by
+ * auto negotiation. The result of this function may not match
+ * Octeon's link config if auto negotiation has changed since
+ * the last call to cvmx_helper_link_set().
+ *
+ * @ipd_port: IPD/PKO port to query
+ *
+ * Returns Link state
+ */
+cvmx_helper_link_info_t __cvmx_helper_spi_link_get(int ipd_port)
+{
+	cvmx_helper_link_info_t result;
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	int index = cvmx_helper_get_interface_index_num(ipd_port);
+	result.u64 = 0;
+
+	if (cvmx_sysinfo_get()->board_type == CVMX_BOARD_TYPE_SIM) {
+		/* The simulator gives you a simulated full duplex link */
+		result.s.link_up = 1;
+		result.s.full_duplex = 1;
+		result.s.speed = 10000;
+	} else if (cvmx_spi4000_is_present(interface)) {
+		union cvmx_gmxx_rxx_rx_inbnd inband =
+		    cvmx_spi4000_check_speed(interface, index);
+		result.s.link_up = inband.s.status;
+		result.s.full_duplex = inband.s.duplex;
+		switch (inband.s.speed) {
+		case 0:	/* 10 Mbps */
+			result.s.speed = 10;
+			break;
+		case 1:	/* 100 Mbps */
+			result.s.speed = 100;
+			break;
+		case 2:	/* 1 Gbps */
+			result.s.speed = 1000;
+			break;
+		case 3:	/* Illegal */
+			result.s.speed = 0;
+			result.s.link_up = 0;
+			break;
+		}
+	} else {
+		/* For generic SPI we can't determine the link, just return some
+		   sane results */
+		result.s.link_up = 1;
+		result.s.full_duplex = 1;
+		result.s.speed = 10000;
+	}
+	return result;
+}
+
+/**
+ * Configure an IPD/PKO port for the specified link state. This
+ * function does not influence auto negotiation at the PHY level.
+ * The passed link state must always match the link state returned
+ * by cvmx_helper_link_get(). It is normally best to use
+ * cvmx_helper_link_autoconf() instead.
+ *
+ * @ipd_port:  IPD/PKO port to configure
+ * @link_info: The new link state
+ *
+ * Returns Zero on success, negative on failure
+ */
+int __cvmx_helper_spi_link_set(int ipd_port, cvmx_helper_link_info_t link_info)
+{
+	/* Nothing to do. If we have a SPI4000 then the setup was already performed
+	   by cvmx_spi4000_check_speed(). If not then there isn't any link
+	   info */
+	return 0;
+}
diff --git a/drivers/staging/octeon/cvmx-helper-spi.h b/drivers/staging/octeon/cvmx-helper-spi.h
new file mode 100644
index 0000000..69bac03
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-spi.h
@@ -0,0 +1,84 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Functions for SPI initialization, configuration,
+ * and monitoring.
+ */
+#ifndef __CVMX_HELPER_SPI_H__
+#define __CVMX_HELPER_SPI_H__
+
+/**
+ * Probe a SPI interface and determine the number of ports
+ * connected to it. The SPI interface should still be down after
+ * this call.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of ports on the interface. Zero to disable.
+ */
+extern int __cvmx_helper_spi_probe(int interface);
+
+/**
+ * Bringup and enable a SPI interface. After this call packet I/O
+ * should be fully functional. This is called with IPD enabled but
+ * PKO disabled.
+ *
+ * @interface: Interface to bring up
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int __cvmx_helper_spi_enable(int interface);
+
+/**
+ * Return the link state of an IPD/PKO port as returned by
+ * auto negotiation. The result of this function may not match
+ * Octeon's link config if auto negotiation has changed since
+ * the last call to cvmx_helper_link_set().
+ *
+ * @ipd_port: IPD/PKO port to query
+ *
+ * Returns Link state
+ */
+extern cvmx_helper_link_info_t __cvmx_helper_spi_link_get(int ipd_port);
+
+/**
+ * Configure an IPD/PKO port for the specified link state. This
+ * function does not influence auto negotiation at the PHY level.
+ * The passed link state must always match the link state returned
+ * by cvmx_helper_link_get(). It is normally best to use
+ * cvmx_helper_link_autoconf() instead.
+ *
+ * @ipd_port:  IPD/PKO port to configure
+ * @link_info: The new link state
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int __cvmx_helper_spi_link_set(int ipd_port,
+				      cvmx_helper_link_info_t link_info);
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-helper-util.c b/drivers/staging/octeon/cvmx-helper-util.c
new file mode 100644
index 0000000..41ef8a4
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-util.c
@@ -0,0 +1,433 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Small helper utilities.
+ */
+#include <linux/kernel.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-config.h"
+
+#include "cvmx-fpa.h"
+#include "cvmx-pip.h"
+#include "cvmx-pko.h"
+#include "cvmx-ipd.h"
+#include "cvmx-spi.h"
+
+#include "cvmx-helper.h"
+#include "cvmx-helper-util.h"
+
+#include <asm/octeon/cvmx-ipd-defs.h>
+
+/**
+ * Convert a interface mode into a human readable string
+ *
+ * @mode:   Mode to convert
+ *
+ * Returns String
+ */
+const char *cvmx_helper_interface_mode_to_string(cvmx_helper_interface_mode_t
+						 mode)
+{
+	switch (mode) {
+	case CVMX_HELPER_INTERFACE_MODE_DISABLED:
+		return "DISABLED";
+	case CVMX_HELPER_INTERFACE_MODE_RGMII:
+		return "RGMII";
+	case CVMX_HELPER_INTERFACE_MODE_GMII:
+		return "GMII";
+	case CVMX_HELPER_INTERFACE_MODE_SPI:
+		return "SPI";
+	case CVMX_HELPER_INTERFACE_MODE_PCIE:
+		return "PCIE";
+	case CVMX_HELPER_INTERFACE_MODE_XAUI:
+		return "XAUI";
+	case CVMX_HELPER_INTERFACE_MODE_SGMII:
+		return "SGMII";
+	case CVMX_HELPER_INTERFACE_MODE_PICMG:
+		return "PICMG";
+	case CVMX_HELPER_INTERFACE_MODE_NPI:
+		return "NPI";
+	case CVMX_HELPER_INTERFACE_MODE_LOOP:
+		return "LOOP";
+	}
+	return "UNKNOWN";
+}
+
+/**
+ * Debug routine to dump the packet structure to the console
+ *
+ * @work:   Work queue entry containing the packet to dump
+ * Returns
+ */
+int cvmx_helper_dump_packet(cvmx_wqe_t *work)
+{
+	uint64_t count;
+	uint64_t remaining_bytes;
+	union cvmx_buf_ptr buffer_ptr;
+	uint64_t start_of_buffer;
+	uint8_t *data_address;
+	uint8_t *end_of_data;
+
+	cvmx_dprintf("Packet Length:   %u\n", work->len);
+	cvmx_dprintf("    Input Port:  %u\n", work->ipprt);
+	cvmx_dprintf("    QoS:         %u\n", work->qos);
+	cvmx_dprintf("    Buffers:     %u\n", work->word2.s.bufs);
+
+	if (work->word2.s.bufs == 0) {
+		union cvmx_ipd_wqe_fpa_queue wqe_pool;
+		wqe_pool.u64 = cvmx_read_csr(CVMX_IPD_WQE_FPA_QUEUE);
+		buffer_ptr.u64 = 0;
+		buffer_ptr.s.pool = wqe_pool.s.wqe_pool;
+		buffer_ptr.s.size = 128;
+		buffer_ptr.s.addr = cvmx_ptr_to_phys(work->packet_data);
+		if (likely(!work->word2.s.not_IP)) {
+			union cvmx_pip_ip_offset pip_ip_offset;
+			pip_ip_offset.u64 = cvmx_read_csr(CVMX_PIP_IP_OFFSET);
+			buffer_ptr.s.addr +=
+			    (pip_ip_offset.s.offset << 3) -
+			    work->word2.s.ip_offset;
+			buffer_ptr.s.addr += (work->word2.s.is_v6 ^ 1) << 2;
+		} else {
+			/*
+			 * WARNING: This code assumes that the packet
+			 * is not RAW. If it was, we would use
+			 * PIP_GBL_CFG[RAW_SHF] instead of
+			 * PIP_GBL_CFG[NIP_SHF].
+			 */
+			union cvmx_pip_gbl_cfg pip_gbl_cfg;
+			pip_gbl_cfg.u64 = cvmx_read_csr(CVMX_PIP_GBL_CFG);
+			buffer_ptr.s.addr += pip_gbl_cfg.s.nip_shf;
+		}
+	} else
+		buffer_ptr = work->packet_ptr;
+	remaining_bytes = work->len;
+
+	while (remaining_bytes) {
+		start_of_buffer =
+		    ((buffer_ptr.s.addr >> 7) - buffer_ptr.s.back) << 7;
+		cvmx_dprintf("    Buffer Start:%llx\n",
+			     (unsigned long long)start_of_buffer);
+		cvmx_dprintf("    Buffer I   : %u\n", buffer_ptr.s.i);
+		cvmx_dprintf("    Buffer Back: %u\n", buffer_ptr.s.back);
+		cvmx_dprintf("    Buffer Pool: %u\n", buffer_ptr.s.pool);
+		cvmx_dprintf("    Buffer Data: %llx\n",
+			     (unsigned long long)buffer_ptr.s.addr);
+		cvmx_dprintf("    Buffer Size: %u\n", buffer_ptr.s.size);
+
+		cvmx_dprintf("\t\t");
+		data_address = (uint8_t *) cvmx_phys_to_ptr(buffer_ptr.s.addr);
+		end_of_data = data_address + buffer_ptr.s.size;
+		count = 0;
+		while (data_address < end_of_data) {
+			if (remaining_bytes == 0)
+				break;
+			else
+				remaining_bytes--;
+			cvmx_dprintf("%02x", (unsigned int)*data_address);
+			data_address++;
+			if (remaining_bytes && (count == 7)) {
+				cvmx_dprintf("\n\t\t");
+				count = 0;
+			} else
+				count++;
+		}
+		cvmx_dprintf("\n");
+
+		if (remaining_bytes)
+			buffer_ptr = *(union cvmx_buf_ptr *)
+				cvmx_phys_to_ptr(buffer_ptr.s.addr - 8);
+	}
+	return 0;
+}
+
+/**
+ * Setup Random Early Drop on a specific input queue
+ *
+ * @queue:  Input queue to setup RED on (0-7)
+ * @pass_thresh:
+ *               Packets will begin slowly dropping when there are less than
+ *               this many packet buffers free in FPA 0.
+ * @drop_thresh:
+ *               All incomming packets will be dropped when there are less
+ *               than this many free packet buffers in FPA 0.
+ * Returns Zero on success. Negative on failure
+ */
+int cvmx_helper_setup_red_queue(int queue, int pass_thresh, int drop_thresh)
+{
+	union cvmx_ipd_qosx_red_marks red_marks;
+	union cvmx_ipd_red_quex_param red_param;
+
+	/* Set RED to begin dropping packets when there are pass_thresh buffers
+	   left. It will linearly drop more packets until reaching drop_thresh
+	   buffers */
+	red_marks.u64 = 0;
+	red_marks.s.drop = drop_thresh;
+	red_marks.s.pass = pass_thresh;
+	cvmx_write_csr(CVMX_IPD_QOSX_RED_MARKS(queue), red_marks.u64);
+
+	/* Use the actual queue 0 counter, not the average */
+	red_param.u64 = 0;
+	red_param.s.prb_con =
+	    (255ul << 24) / (red_marks.s.pass - red_marks.s.drop);
+	red_param.s.avg_con = 1;
+	red_param.s.new_con = 255;
+	red_param.s.use_pcnt = 1;
+	cvmx_write_csr(CVMX_IPD_RED_QUEX_PARAM(queue), red_param.u64);
+	return 0;
+}
+
+/**
+ * Setup Random Early Drop to automatically begin dropping packets.
+ *
+ * @pass_thresh:
+ *               Packets will begin slowly dropping when there are less than
+ *               this many packet buffers free in FPA 0.
+ * @drop_thresh:
+ *               All incomming packets will be dropped when there are less
+ *               than this many free packet buffers in FPA 0.
+ * Returns Zero on success. Negative on failure
+ */
+int cvmx_helper_setup_red(int pass_thresh, int drop_thresh)
+{
+	union cvmx_ipd_portx_bp_page_cnt page_cnt;
+	union cvmx_ipd_bp_prt_red_end ipd_bp_prt_red_end;
+	union cvmx_ipd_red_port_enable red_port_enable;
+	int queue;
+	int interface;
+	int port;
+
+	/* Disable backpressure based on queued buffers. It needs SW support */
+	page_cnt.u64 = 0;
+	page_cnt.s.bp_enb = 0;
+	page_cnt.s.page_cnt = 100;
+	for (interface = 0; interface < 2; interface++) {
+		for (port = cvmx_helper_get_first_ipd_port(interface);
+		     port < cvmx_helper_get_last_ipd_port(interface); port++)
+			cvmx_write_csr(CVMX_IPD_PORTX_BP_PAGE_CNT(port),
+				       page_cnt.u64);
+	}
+
+	for (queue = 0; queue < 8; queue++)
+		cvmx_helper_setup_red_queue(queue, pass_thresh, drop_thresh);
+
+	/* Shutoff the dropping based on the per port page count. SW isn't
+	   decrementing it right now */
+	ipd_bp_prt_red_end.u64 = 0;
+	ipd_bp_prt_red_end.s.prt_enb = 0;
+	cvmx_write_csr(CVMX_IPD_BP_PRT_RED_END, ipd_bp_prt_red_end.u64);
+
+	red_port_enable.u64 = 0;
+	red_port_enable.s.prt_enb = 0xfffffffffull;
+	red_port_enable.s.avg_dly = 10000;
+	red_port_enable.s.prb_dly = 10000;
+	cvmx_write_csr(CVMX_IPD_RED_PORT_ENABLE, red_port_enable.u64);
+
+	return 0;
+}
+
+/**
+ * Setup the common GMX settings that determine the number of
+ * ports. These setting apply to almost all configurations of all
+ * chips.
+ *
+ * @interface: Interface to configure
+ * @num_ports: Number of ports on the interface
+ *
+ * Returns Zero on success, negative on failure
+ */
+int __cvmx_helper_setup_gmx(int interface, int num_ports)
+{
+	union cvmx_gmxx_tx_prts gmx_tx_prts;
+	union cvmx_gmxx_rx_prts gmx_rx_prts;
+	union cvmx_pko_reg_gmx_port_mode pko_mode;
+	union cvmx_gmxx_txx_thresh gmx_tx_thresh;
+	int index;
+
+	/* Tell GMX the number of TX ports on this interface */
+	gmx_tx_prts.u64 = cvmx_read_csr(CVMX_GMXX_TX_PRTS(interface));
+	gmx_tx_prts.s.prts = num_ports;
+	cvmx_write_csr(CVMX_GMXX_TX_PRTS(interface), gmx_tx_prts.u64);
+
+	/* Tell GMX the number of RX ports on this interface.  This only
+	 ** applies to *GMII and XAUI ports */
+	if (cvmx_helper_interface_get_mode(interface) ==
+	    CVMX_HELPER_INTERFACE_MODE_RGMII
+	    || cvmx_helper_interface_get_mode(interface) ==
+	    CVMX_HELPER_INTERFACE_MODE_SGMII
+	    || cvmx_helper_interface_get_mode(interface) ==
+	    CVMX_HELPER_INTERFACE_MODE_GMII
+	    || cvmx_helper_interface_get_mode(interface) ==
+	    CVMX_HELPER_INTERFACE_MODE_XAUI) {
+		if (num_ports > 4) {
+			cvmx_dprintf("__cvmx_helper_setup_gmx: Illegal "
+				     "num_ports\n");
+			return -1;
+		}
+
+		gmx_rx_prts.u64 = cvmx_read_csr(CVMX_GMXX_RX_PRTS(interface));
+		gmx_rx_prts.s.prts = num_ports;
+		cvmx_write_csr(CVMX_GMXX_RX_PRTS(interface), gmx_rx_prts.u64);
+	}
+
+	/* Skip setting CVMX_PKO_REG_GMX_PORT_MODE on 30XX, 31XX, and 50XX */
+	if (!OCTEON_IS_MODEL(OCTEON_CN30XX) && !OCTEON_IS_MODEL(OCTEON_CN31XX)
+	    && !OCTEON_IS_MODEL(OCTEON_CN50XX)) {
+		/* Tell PKO the number of ports on this interface */
+		pko_mode.u64 = cvmx_read_csr(CVMX_PKO_REG_GMX_PORT_MODE);
+		if (interface == 0) {
+			if (num_ports == 1)
+				pko_mode.s.mode0 = 4;
+			else if (num_ports == 2)
+				pko_mode.s.mode0 = 3;
+			else if (num_ports <= 4)
+				pko_mode.s.mode0 = 2;
+			else if (num_ports <= 8)
+				pko_mode.s.mode0 = 1;
+			else
+				pko_mode.s.mode0 = 0;
+		} else {
+			if (num_ports == 1)
+				pko_mode.s.mode1 = 4;
+			else if (num_ports == 2)
+				pko_mode.s.mode1 = 3;
+			else if (num_ports <= 4)
+				pko_mode.s.mode1 = 2;
+			else if (num_ports <= 8)
+				pko_mode.s.mode1 = 1;
+			else
+				pko_mode.s.mode1 = 0;
+		}
+		cvmx_write_csr(CVMX_PKO_REG_GMX_PORT_MODE, pko_mode.u64);
+	}
+
+	/*
+	 * Set GMX to buffer as much data as possible before starting
+	 * transmit.  This reduces the chances that we have a TX under
+	 * run due to memory contention. Any packet that fits entirely
+	 * in the GMX FIFO can never have an under run regardless of
+	 * memory load.
+	 */
+	gmx_tx_thresh.u64 = cvmx_read_csr(CVMX_GMXX_TXX_THRESH(0, interface));
+	if (OCTEON_IS_MODEL(OCTEON_CN30XX) || OCTEON_IS_MODEL(OCTEON_CN31XX)
+	    || OCTEON_IS_MODEL(OCTEON_CN50XX)) {
+		/* These chips have a fixed max threshold of 0x40 */
+		gmx_tx_thresh.s.cnt = 0x40;
+	} else {
+		/* Choose the max value for the number of ports */
+		if (num_ports <= 1)
+			gmx_tx_thresh.s.cnt = 0x100 / 1;
+		else if (num_ports == 2)
+			gmx_tx_thresh.s.cnt = 0x100 / 2;
+		else
+			gmx_tx_thresh.s.cnt = 0x100 / 4;
+	}
+	/*
+	 * SPI and XAUI can have lots of ports but the GMX hardware
+	 * only ever has a max of 4.
+	 */
+	if (num_ports > 4)
+		num_ports = 4;
+	for (index = 0; index < num_ports; index++)
+		cvmx_write_csr(CVMX_GMXX_TXX_THRESH(index, interface),
+			       gmx_tx_thresh.u64);
+
+	return 0;
+}
+
+/**
+ * Returns the IPD/PKO port number for a port on teh given
+ * interface.
+ *
+ * @interface: Interface to use
+ * @port:      Port on the interface
+ *
+ * Returns IPD/PKO port number
+ */
+int cvmx_helper_get_ipd_port(int interface, int port)
+{
+	switch (interface) {
+	case 0:
+		return port;
+	case 1:
+		return port + 16;
+	case 2:
+		return port + 32;
+	case 3:
+		return port + 36;
+	}
+	return -1;
+}
+
+/**
+ * Returns the interface number for an IPD/PKO port number.
+ *
+ * @ipd_port: IPD/PKO port number
+ *
+ * Returns Interface number
+ */
+int cvmx_helper_get_interface_num(int ipd_port)
+{
+	if (ipd_port < 16)
+		return 0;
+	else if (ipd_port < 32)
+		return 1;
+	else if (ipd_port < 36)
+		return 2;
+	else if (ipd_port < 40)
+		return 3;
+	else
+		cvmx_dprintf("cvmx_helper_get_interface_num: Illegal IPD "
+			     "port number\n");
+
+	return -1;
+}
+
+/**
+ * Returns the interface index number for an IPD/PKO port
+ * number.
+ *
+ * @ipd_port: IPD/PKO port number
+ *
+ * Returns Interface index number
+ */
+int cvmx_helper_get_interface_index_num(int ipd_port)
+{
+	if (ipd_port < 32)
+		return ipd_port & 15;
+	else if (ipd_port < 36)
+		return ipd_port & 3;
+	else if (ipd_port < 40)
+		return ipd_port & 3;
+	else
+		cvmx_dprintf("cvmx_helper_get_interface_index_num: "
+			     "Illegal IPD port number\n");
+
+	return -1;
+}
diff --git a/drivers/staging/octeon/cvmx-helper-util.h b/drivers/staging/octeon/cvmx-helper-util.h
new file mode 100644
index 0000000..6a6e52f
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-util.h
@@ -0,0 +1,215 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ *
+ * Small helper utilities.
+ *
+ */
+
+#ifndef __CVMX_HELPER_UTIL_H__
+#define __CVMX_HELPER_UTIL_H__
+
+/**
+ * Convert a interface mode into a human readable string
+ *
+ * @mode:   Mode to convert
+ *
+ * Returns String
+ */
+extern const char
+    *cvmx_helper_interface_mode_to_string(cvmx_helper_interface_mode_t mode);
+
+/**
+ * Debug routine to dump the packet structure to the console
+ *
+ * @work:   Work queue entry containing the packet to dump
+ * Returns
+ */
+extern int cvmx_helper_dump_packet(cvmx_wqe_t *work);
+
+/**
+ * Setup Random Early Drop on a specific input queue
+ *
+ * @queue:  Input queue to setup RED on (0-7)
+ * @pass_thresh:
+ *               Packets will begin slowly dropping when there are less than
+ *               this many packet buffers free in FPA 0.
+ * @drop_thresh:
+ *               All incomming packets will be dropped when there are less
+ *               than this many free packet buffers in FPA 0.
+ * Returns Zero on success. Negative on failure
+ */
+extern int cvmx_helper_setup_red_queue(int queue, int pass_thresh,
+				       int drop_thresh);
+
+/**
+ * Setup Random Early Drop to automatically begin dropping packets.
+ *
+ * @pass_thresh:
+ *               Packets will begin slowly dropping when there are less than
+ *               this many packet buffers free in FPA 0.
+ * @drop_thresh:
+ *               All incomming packets will be dropped when there are less
+ *               than this many free packet buffers in FPA 0.
+ * Returns Zero on success. Negative on failure
+ */
+extern int cvmx_helper_setup_red(int pass_thresh, int drop_thresh);
+
+/**
+ * Get the version of the CVMX libraries.
+ *
+ * Returns Version string. Note this buffer is allocated statically
+ *         and will be shared by all callers.
+ */
+extern const char *cvmx_helper_get_version(void);
+
+/**
+ * Setup the common GMX settings that determine the number of
+ * ports. These setting apply to almost all configurations of all
+ * chips.
+ *
+ * @interface: Interface to configure
+ * @num_ports: Number of ports on the interface
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int __cvmx_helper_setup_gmx(int interface, int num_ports);
+
+/**
+ * Returns the IPD/PKO port number for a port on the given
+ * interface.
+ *
+ * @interface: Interface to use
+ * @port:      Port on the interface
+ *
+ * Returns IPD/PKO port number
+ */
+extern int cvmx_helper_get_ipd_port(int interface, int port);
+
+/**
+ * Returns the IPD/PKO port number for the first port on the given
+ * interface.
+ *
+ * @interface: Interface to use
+ *
+ * Returns IPD/PKO port number
+ */
+static inline int cvmx_helper_get_first_ipd_port(int interface)
+{
+	return cvmx_helper_get_ipd_port(interface, 0);
+}
+
+/**
+ * Returns the IPD/PKO port number for the last port on the given
+ * interface.
+ *
+ * @interface: Interface to use
+ *
+ * Returns IPD/PKO port number
+ */
+static inline int cvmx_helper_get_last_ipd_port(int interface)
+{
+	extern int cvmx_helper_ports_on_interface(int interface);
+
+	return cvmx_helper_get_first_ipd_port(interface) +
+	       cvmx_helper_ports_on_interface(interface) - 1;
+}
+
+/**
+ * Free the packet buffers contained in a work queue entry.
+ * The work queue entry is not freed.
+ *
+ * @work:   Work queue entry with packet to free
+ */
+static inline void cvmx_helper_free_packet_data(cvmx_wqe_t *work)
+{
+	uint64_t number_buffers;
+	union cvmx_buf_ptr buffer_ptr;
+	union cvmx_buf_ptr next_buffer_ptr;
+	uint64_t start_of_buffer;
+
+	number_buffers = work->word2.s.bufs;
+	if (number_buffers == 0)
+		return;
+	buffer_ptr = work->packet_ptr;
+
+	/*
+	 * Since the number of buffers is not zero, we know this is
+	 * not a dynamic short packet. We need to check if it is a
+	 * packet received with IPD_CTL_STATUS[NO_WPTR]. If this is
+	 * true, we need to free all buffers except for the first
+	 * one. The caller doesn't expect their WQE pointer to be
+	 * freed
+	 */
+	start_of_buffer = ((buffer_ptr.s.addr >> 7) - buffer_ptr.s.back) << 7;
+	if (cvmx_ptr_to_phys(work) == start_of_buffer) {
+		next_buffer_ptr =
+		    *(union cvmx_buf_ptr *) cvmx_phys_to_ptr(buffer_ptr.s.addr - 8);
+		buffer_ptr = next_buffer_ptr;
+		number_buffers--;
+	}
+
+	while (number_buffers--) {
+		/*
+		 * Remember the back pointer is in cache lines, not
+		 * 64bit words
+		 */
+		start_of_buffer =
+		    ((buffer_ptr.s.addr >> 7) - buffer_ptr.s.back) << 7;
+		/*
+		 * Read pointer to next buffer before we free the
+		 * current buffer.
+		 */
+		next_buffer_ptr =
+		    *(union cvmx_buf_ptr *) cvmx_phys_to_ptr(buffer_ptr.s.addr - 8);
+		cvmx_fpa_free(cvmx_phys_to_ptr(start_of_buffer),
+			      buffer_ptr.s.pool, 0);
+		buffer_ptr = next_buffer_ptr;
+	}
+}
+
+/**
+ * Returns the interface number for an IPD/PKO port number.
+ *
+ * @ipd_port: IPD/PKO port number
+ *
+ * Returns Interface number
+ */
+extern int cvmx_helper_get_interface_num(int ipd_port);
+
+/**
+ * Returns the interface index number for an IPD/PKO port
+ * number.
+ *
+ * @ipd_port: IPD/PKO port number
+ *
+ * Returns Interface index number
+ */
+extern int cvmx_helper_get_interface_index_num(int ipd_port);
+
+#endif /* __CVMX_HELPER_H__ */
diff --git a/drivers/staging/octeon/cvmx-helper-xaui.c b/drivers/staging/octeon/cvmx-helper-xaui.c
new file mode 100644
index 0000000..a11e676
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-xaui.c
@@ -0,0 +1,348 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Functions for XAUI initialization, configuration,
+ * and monitoring.
+ *
+ */
+
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-config.h"
+
+#include "cvmx-helper.h"
+
+#include "cvmx-pko-defs.h"
+#include "cvmx-gmxx-defs.h"
+#include "cvmx-pcsxx-defs.h"
+
+void __cvmx_interrupt_gmxx_enable(int interface);
+void __cvmx_interrupt_pcsx_intx_en_reg_enable(int index, int block);
+void __cvmx_interrupt_pcsxx_int_en_reg_enable(int index);
+/**
+ * Probe a XAUI interface and determine the number of ports
+ * connected to it. The XAUI interface should still be down
+ * after this call.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of ports on the interface. Zero to disable.
+ */
+int __cvmx_helper_xaui_probe(int interface)
+{
+	int i;
+	union cvmx_gmxx_hg2_control gmx_hg2_control;
+	union cvmx_gmxx_inf_mode mode;
+
+	/*
+	 * Due to errata GMX-700 on CN56XXp1.x and CN52XXp1.x, the
+	 * interface needs to be enabled before IPD otherwise per port
+	 * backpressure may not work properly.
+	 */
+	mode.u64 = cvmx_read_csr(CVMX_GMXX_INF_MODE(interface));
+	mode.s.en = 1;
+	cvmx_write_csr(CVMX_GMXX_INF_MODE(interface), mode.u64);
+
+	__cvmx_helper_setup_gmx(interface, 1);
+
+	/*
+	 * Setup PKO to support 16 ports for HiGig2 virtual
+	 * ports. We're pointing all of the PKO packet ports for this
+	 * interface to the XAUI. This allows us to use HiGig2
+	 * backpressure per port.
+	 */
+	for (i = 0; i < 16; i++) {
+		union cvmx_pko_mem_port_ptrs pko_mem_port_ptrs;
+		pko_mem_port_ptrs.u64 = 0;
+		/*
+		 * We set each PKO port to have equal priority in a
+		 * round robin fashion.
+		 */
+		pko_mem_port_ptrs.s.static_p = 0;
+		pko_mem_port_ptrs.s.qos_mask = 0xff;
+		/* All PKO ports map to the same XAUI hardware port */
+		pko_mem_port_ptrs.s.eid = interface * 4;
+		pko_mem_port_ptrs.s.pid = interface * 16 + i;
+		cvmx_write_csr(CVMX_PKO_MEM_PORT_PTRS, pko_mem_port_ptrs.u64);
+	}
+
+	/* If HiGig2 is enabled return 16 ports, otherwise return 1 port */
+	gmx_hg2_control.u64 = cvmx_read_csr(CVMX_GMXX_HG2_CONTROL(interface));
+	if (gmx_hg2_control.s.hg2tx_en)
+		return 16;
+	else
+		return 1;
+}
+
+/**
+ * Bringup and enable a XAUI interface. After this call packet
+ * I/O should be fully functional. This is called with IPD
+ * enabled but PKO disabled.
+ *
+ * @interface: Interface to bring up
+ *
+ * Returns Zero on success, negative on failure
+ */
+int __cvmx_helper_xaui_enable(int interface)
+{
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	union cvmx_pcsxx_control1_reg xauiCtl;
+	union cvmx_pcsxx_misc_ctl_reg xauiMiscCtl;
+	union cvmx_gmxx_tx_xaui_ctl gmxXauiTxCtl;
+	union cvmx_gmxx_rxx_int_en gmx_rx_int_en;
+	union cvmx_gmxx_tx_int_en gmx_tx_int_en;
+	union cvmx_pcsxx_int_en_reg pcsx_int_en_reg;
+
+	/* (1) Interface has already been enabled. */
+
+	/* (2) Disable GMX. */
+	xauiMiscCtl.u64 = cvmx_read_csr(CVMX_PCSXX_MISC_CTL_REG(interface));
+	xauiMiscCtl.s.gmxeno = 1;
+	cvmx_write_csr(CVMX_PCSXX_MISC_CTL_REG(interface), xauiMiscCtl.u64);
+
+	/* (3) Disable GMX and PCSX interrupts. */
+	gmx_rx_int_en.u64 = cvmx_read_csr(CVMX_GMXX_RXX_INT_EN(0, interface));
+	cvmx_write_csr(CVMX_GMXX_RXX_INT_EN(0, interface), 0x0);
+	gmx_tx_int_en.u64 = cvmx_read_csr(CVMX_GMXX_TX_INT_EN(interface));
+	cvmx_write_csr(CVMX_GMXX_TX_INT_EN(interface), 0x0);
+	pcsx_int_en_reg.u64 = cvmx_read_csr(CVMX_PCSXX_INT_EN_REG(interface));
+	cvmx_write_csr(CVMX_PCSXX_INT_EN_REG(interface), 0x0);
+
+	/* (4) Bring up the PCSX and GMX reconciliation layer. */
+	/* (4)a Set polarity and lane swapping. */
+	/* (4)b */
+	gmxXauiTxCtl.u64 = cvmx_read_csr(CVMX_GMXX_TX_XAUI_CTL(interface));
+	/* Enable better IFG packing and improves performance */
+	gmxXauiTxCtl.s.dic_en = 1;
+	gmxXauiTxCtl.s.uni_en = 0;
+	cvmx_write_csr(CVMX_GMXX_TX_XAUI_CTL(interface), gmxXauiTxCtl.u64);
+
+	/* (4)c Aply reset sequence */
+	xauiCtl.u64 = cvmx_read_csr(CVMX_PCSXX_CONTROL1_REG(interface));
+	xauiCtl.s.lo_pwr = 0;
+	xauiCtl.s.reset = 1;
+	cvmx_write_csr(CVMX_PCSXX_CONTROL1_REG(interface), xauiCtl.u64);
+
+	/* Wait for PCS to come out of reset */
+	if (CVMX_WAIT_FOR_FIELD64
+	    (CVMX_PCSXX_CONTROL1_REG(interface), union cvmx_pcsxx_control1_reg,
+	     reset, ==, 0, 10000))
+		return -1;
+	/* Wait for PCS to be aligned */
+	if (CVMX_WAIT_FOR_FIELD64
+	    (CVMX_PCSXX_10GBX_STATUS_REG(interface),
+	     union cvmx_pcsxx_10gbx_status_reg, alignd, ==, 1, 10000))
+		return -1;
+	/* Wait for RX to be ready */
+	if (CVMX_WAIT_FOR_FIELD64
+	    (CVMX_GMXX_RX_XAUI_CTL(interface), union cvmx_gmxx_rx_xaui_ctl,
+		    status, ==, 0, 10000))
+		return -1;
+
+	/* (6) Configure GMX */
+	gmx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(0, interface));
+	gmx_cfg.s.en = 0;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(0, interface), gmx_cfg.u64);
+
+	/* Wait for GMX RX to be idle */
+	if (CVMX_WAIT_FOR_FIELD64
+	    (CVMX_GMXX_PRTX_CFG(0, interface), union cvmx_gmxx_prtx_cfg,
+		    rx_idle, ==, 1, 10000))
+		return -1;
+	/* Wait for GMX TX to be idle */
+	if (CVMX_WAIT_FOR_FIELD64
+	    (CVMX_GMXX_PRTX_CFG(0, interface), union cvmx_gmxx_prtx_cfg,
+		    tx_idle, ==, 1, 10000))
+		return -1;
+
+	/* GMX configure */
+	gmx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(0, interface));
+	gmx_cfg.s.speed = 1;
+	gmx_cfg.s.speed_msb = 0;
+	gmx_cfg.s.slottime = 1;
+	cvmx_write_csr(CVMX_GMXX_TX_PRTS(interface), 1);
+	cvmx_write_csr(CVMX_GMXX_TXX_SLOT(0, interface), 512);
+	cvmx_write_csr(CVMX_GMXX_TXX_BURST(0, interface), 8192);
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(0, interface), gmx_cfg.u64);
+
+	/* (7) Clear out any error state */
+	cvmx_write_csr(CVMX_GMXX_RXX_INT_REG(0, interface),
+		       cvmx_read_csr(CVMX_GMXX_RXX_INT_REG(0, interface)));
+	cvmx_write_csr(CVMX_GMXX_TX_INT_REG(interface),
+		       cvmx_read_csr(CVMX_GMXX_TX_INT_REG(interface)));
+	cvmx_write_csr(CVMX_PCSXX_INT_REG(interface),
+		       cvmx_read_csr(CVMX_PCSXX_INT_REG(interface)));
+
+	/* Wait for receive link */
+	if (CVMX_WAIT_FOR_FIELD64
+	    (CVMX_PCSXX_STATUS1_REG(interface), union cvmx_pcsxx_status1_reg,
+	     rcv_lnk, ==, 1, 10000))
+		return -1;
+	if (CVMX_WAIT_FOR_FIELD64
+	    (CVMX_PCSXX_STATUS2_REG(interface), union cvmx_pcsxx_status2_reg,
+	     xmtflt, ==, 0, 10000))
+		return -1;
+	if (CVMX_WAIT_FOR_FIELD64
+	    (CVMX_PCSXX_STATUS2_REG(interface), union cvmx_pcsxx_status2_reg,
+	     rcvflt, ==, 0, 10000))
+		return -1;
+
+	cvmx_write_csr(CVMX_GMXX_RXX_INT_EN(0, interface), gmx_rx_int_en.u64);
+	cvmx_write_csr(CVMX_GMXX_TX_INT_EN(interface), gmx_tx_int_en.u64);
+	cvmx_write_csr(CVMX_PCSXX_INT_EN_REG(interface), pcsx_int_en_reg.u64);
+
+	cvmx_helper_link_autoconf(cvmx_helper_get_ipd_port(interface, 0));
+
+	/* (8) Enable packet reception */
+	xauiMiscCtl.s.gmxeno = 0;
+	cvmx_write_csr(CVMX_PCSXX_MISC_CTL_REG(interface), xauiMiscCtl.u64);
+
+	gmx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(0, interface));
+	gmx_cfg.s.en = 1;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(0, interface), gmx_cfg.u64);
+
+	__cvmx_interrupt_pcsx_intx_en_reg_enable(0, interface);
+	__cvmx_interrupt_pcsx_intx_en_reg_enable(1, interface);
+	__cvmx_interrupt_pcsx_intx_en_reg_enable(2, interface);
+	__cvmx_interrupt_pcsx_intx_en_reg_enable(3, interface);
+	__cvmx_interrupt_pcsxx_int_en_reg_enable(interface);
+	__cvmx_interrupt_gmxx_enable(interface);
+
+	return 0;
+}
+
+/**
+ * Return the link state of an IPD/PKO port as returned by
+ * auto negotiation. The result of this function may not match
+ * Octeon's link config if auto negotiation has changed since
+ * the last call to cvmx_helper_link_set().
+ *
+ * @ipd_port: IPD/PKO port to query
+ *
+ * Returns Link state
+ */
+cvmx_helper_link_info_t __cvmx_helper_xaui_link_get(int ipd_port)
+{
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	union cvmx_gmxx_tx_xaui_ctl gmxx_tx_xaui_ctl;
+	union cvmx_gmxx_rx_xaui_ctl gmxx_rx_xaui_ctl;
+	union cvmx_pcsxx_status1_reg pcsxx_status1_reg;
+	cvmx_helper_link_info_t result;
+
+	gmxx_tx_xaui_ctl.u64 = cvmx_read_csr(CVMX_GMXX_TX_XAUI_CTL(interface));
+	gmxx_rx_xaui_ctl.u64 = cvmx_read_csr(CVMX_GMXX_RX_XAUI_CTL(interface));
+	pcsxx_status1_reg.u64 =
+	    cvmx_read_csr(CVMX_PCSXX_STATUS1_REG(interface));
+	result.u64 = 0;
+
+	/* Only return a link if both RX and TX are happy */
+	if ((gmxx_tx_xaui_ctl.s.ls == 0) && (gmxx_rx_xaui_ctl.s.status == 0) &&
+	    (pcsxx_status1_reg.s.rcv_lnk == 1)) {
+		result.s.link_up = 1;
+		result.s.full_duplex = 1;
+		result.s.speed = 10000;
+	} else {
+		/* Disable GMX and PCSX interrupts. */
+		cvmx_write_csr(CVMX_GMXX_RXX_INT_EN(0, interface), 0x0);
+		cvmx_write_csr(CVMX_GMXX_TX_INT_EN(interface), 0x0);
+		cvmx_write_csr(CVMX_PCSXX_INT_EN_REG(interface), 0x0);
+	}
+	return result;
+}
+
+/**
+ * Configure an IPD/PKO port for the specified link state. This
+ * function does not influence auto negotiation at the PHY level.
+ * The passed link state must always match the link state returned
+ * by cvmx_helper_link_get(). It is normally best to use
+ * cvmx_helper_link_autoconf() instead.
+ *
+ * @ipd_port:  IPD/PKO port to configure
+ * @link_info: The new link state
+ *
+ * Returns Zero on success, negative on failure
+ */
+int __cvmx_helper_xaui_link_set(int ipd_port, cvmx_helper_link_info_t link_info)
+{
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	union cvmx_gmxx_tx_xaui_ctl gmxx_tx_xaui_ctl;
+	union cvmx_gmxx_rx_xaui_ctl gmxx_rx_xaui_ctl;
+
+	gmxx_tx_xaui_ctl.u64 = cvmx_read_csr(CVMX_GMXX_TX_XAUI_CTL(interface));
+	gmxx_rx_xaui_ctl.u64 = cvmx_read_csr(CVMX_GMXX_RX_XAUI_CTL(interface));
+
+	/* If the link shouldn't be up, then just return */
+	if (!link_info.s.link_up)
+		return 0;
+
+	/* Do nothing if both RX and TX are happy */
+	if ((gmxx_tx_xaui_ctl.s.ls == 0) && (gmxx_rx_xaui_ctl.s.status == 0))
+		return 0;
+
+	/* Bring the link up */
+	return __cvmx_helper_xaui_enable(interface);
+}
+
+/**
+ * Configure a port for internal and/or external loopback. Internal loopback
+ * causes packets sent by the port to be received by Octeon. External loopback
+ * causes packets received from the wire to sent out again.
+ *
+ * @ipd_port: IPD/PKO port to loopback.
+ * @enable_internal:
+ *                 Non zero if you want internal loopback
+ * @enable_external:
+ *                 Non zero if you want external loopback
+ *
+ * Returns Zero on success, negative on failure.
+ */
+extern int __cvmx_helper_xaui_configure_loopback(int ipd_port,
+						 int enable_internal,
+						 int enable_external)
+{
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	union cvmx_pcsxx_control1_reg pcsxx_control1_reg;
+	union cvmx_gmxx_xaui_ext_loopback gmxx_xaui_ext_loopback;
+
+	/* Set the internal loop */
+	pcsxx_control1_reg.u64 =
+	    cvmx_read_csr(CVMX_PCSXX_CONTROL1_REG(interface));
+	pcsxx_control1_reg.s.loopbck1 = enable_internal;
+	cvmx_write_csr(CVMX_PCSXX_CONTROL1_REG(interface),
+		       pcsxx_control1_reg.u64);
+
+	/* Set the external loop */
+	gmxx_xaui_ext_loopback.u64 =
+	    cvmx_read_csr(CVMX_GMXX_XAUI_EXT_LOOPBACK(interface));
+	gmxx_xaui_ext_loopback.s.en = enable_external;
+	cvmx_write_csr(CVMX_GMXX_XAUI_EXT_LOOPBACK(interface),
+		       gmxx_xaui_ext_loopback.u64);
+
+	/* Take the link through a reset */
+	return __cvmx_helper_xaui_enable(interface);
+}
diff --git a/drivers/staging/octeon/cvmx-helper-xaui.h b/drivers/staging/octeon/cvmx-helper-xaui.h
new file mode 100644
index 0000000..4b4db2f
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper-xaui.h
@@ -0,0 +1,103 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * @file
+ *
+ * Functions for XAUI initialization, configuration,
+ * and monitoring.
+ *
+ */
+#ifndef __CVMX_HELPER_XAUI_H__
+#define __CVMX_HELPER_XAUI_H__
+
+/**
+ * Probe a XAUI interface and determine the number of ports
+ * connected to it. The XAUI interface should still be down
+ * after this call.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Number of ports on the interface. Zero to disable.
+ */
+extern int __cvmx_helper_xaui_probe(int interface);
+
+/**
+ * Bringup and enable a XAUI interface. After this call packet
+ * I/O should be fully functional. This is called with IPD
+ * enabled but PKO disabled.
+ *
+ * @interface: Interface to bring up
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int __cvmx_helper_xaui_enable(int interface);
+
+/**
+ * Return the link state of an IPD/PKO port as returned by
+ * auto negotiation. The result of this function may not match
+ * Octeon's link config if auto negotiation has changed since
+ * the last call to cvmx_helper_link_set().
+ *
+ * @ipd_port: IPD/PKO port to query
+ *
+ * Returns Link state
+ */
+extern cvmx_helper_link_info_t __cvmx_helper_xaui_link_get(int ipd_port);
+
+/**
+ * Configure an IPD/PKO port for the specified link state. This
+ * function does not influence auto negotiation at the PHY level.
+ * The passed link state must always match the link state returned
+ * by cvmx_helper_link_get(). It is normally best to use
+ * cvmx_helper_link_autoconf() instead.
+ *
+ * @ipd_port:  IPD/PKO port to configure
+ * @link_info: The new link state
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int __cvmx_helper_xaui_link_set(int ipd_port,
+				       cvmx_helper_link_info_t link_info);
+
+/**
+ * Configure a port for internal and/or external loopback. Internal loopback
+ * causes packets sent by the port to be received by Octeon. External loopback
+ * causes packets received from the wire to sent out again.
+ *
+ * @ipd_port: IPD/PKO port to loopback.
+ * @enable_internal:
+ *                 Non zero if you want internal loopback
+ * @enable_external:
+ *                 Non zero if you want external loopback
+ *
+ * Returns Zero on success, negative on failure.
+ */
+extern int __cvmx_helper_xaui_configure_loopback(int ipd_port,
+						 int enable_internal,
+						 int enable_external);
+#endif
diff --git a/drivers/staging/octeon/cvmx-helper.c b/drivers/staging/octeon/cvmx-helper.c
new file mode 100644
index 0000000..5915066
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper.c
@@ -0,0 +1,1058 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ *
+ * Helper functions for common, but complicated tasks.
+ *
+ */
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-config.h"
+
+#include "cvmx-fpa.h"
+#include "cvmx-pip.h"
+#include "cvmx-pko.h"
+#include "cvmx-ipd.h"
+#include "cvmx-spi.h"
+#include "cvmx-helper.h"
+#include "cvmx-helper-board.h"
+
+#include "cvmx-pip-defs.h"
+#include "cvmx-smix-defs.h"
+#include "cvmx-asxx-defs.h"
+
+/**
+ * cvmx_override_pko_queue_priority(int ipd_port, uint64_t
+ * priorities[16]) is a function pointer. It is meant to allow
+ * customization of the PKO queue priorities based on the port
+ * number. Users should set this pointer to a function before
+ * calling any cvmx-helper operations.
+ */
+void (*cvmx_override_pko_queue_priority) (int pko_port,
+					  uint64_t priorities[16]);
+
+/**
+ * cvmx_override_ipd_port_setup(int ipd_port) is a function
+ * pointer. It is meant to allow customization of the IPD port
+ * setup before packet input/output comes online. It is called
+ * after cvmx-helper does the default IPD configuration, but
+ * before IPD is enabled. Users should set this pointer to a
+ * function before calling any cvmx-helper operations.
+ */
+void (*cvmx_override_ipd_port_setup) (int ipd_port);
+
+/* Port count per interface */
+static int interface_port_count[4] = { 0, 0, 0, 0 };
+
+/* Port last configured link info index by IPD/PKO port */
+static cvmx_helper_link_info_t
+    port_link_info[CVMX_PIP_NUM_INPUT_PORTS];
+
+/**
+ * Return the number of interfaces the chip has. Each interface
+ * may have multiple ports. Most chips support two interfaces,
+ * but the CNX0XX and CNX1XX are exceptions. These only support
+ * one interface.
+ *
+ * Returns Number of interfaces on chip
+ */
+int cvmx_helper_get_number_of_interfaces(void)
+{
+	if (OCTEON_IS_MODEL(OCTEON_CN56XX) || OCTEON_IS_MODEL(OCTEON_CN52XX))
+		return 4;
+	else
+		return 3;
+}
+
+/**
+ * Return the number of ports on an interface. Depending on the
+ * chip and configuration, this can be 1-16. A value of 0
+ * specifies that the interface doesn't exist or isn't usable.
+ *
+ * @interface: Interface to get the port count for
+ *
+ * Returns Number of ports on interface. Can be Zero.
+ */
+int cvmx_helper_ports_on_interface(int interface)
+{
+	return interface_port_count[interface];
+}
+
+/**
+ * Get the operating mode of an interface. Depending on the Octeon
+ * chip and configuration, this function returns an enumeration
+ * of the type of packet I/O supported by an interface.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Mode of the interface. Unknown or unsupported interfaces return
+ *         DISABLED.
+ */
+cvmx_helper_interface_mode_t cvmx_helper_interface_get_mode(int interface)
+{
+	union cvmx_gmxx_inf_mode mode;
+	if (interface == 2)
+		return CVMX_HELPER_INTERFACE_MODE_NPI;
+
+	if (interface == 3) {
+		if (OCTEON_IS_MODEL(OCTEON_CN56XX)
+		    || OCTEON_IS_MODEL(OCTEON_CN52XX))
+			return CVMX_HELPER_INTERFACE_MODE_LOOP;
+		else
+			return CVMX_HELPER_INTERFACE_MODE_DISABLED;
+	}
+
+	if (interface == 0
+	    && cvmx_sysinfo_get()->board_type == CVMX_BOARD_TYPE_CN3005_EVB_HS5
+	    && cvmx_sysinfo_get()->board_rev_major == 1) {
+		/*
+		 * Lie about interface type of CN3005 board.  This
+		 * board has a switch on port 1 like the other
+		 * evaluation boards, but it is connected over RGMII
+		 * instead of GMII.  Report GMII mode so that the
+		 * speed is forced to 1 Gbit full duplex.  Other than
+		 * some initial configuration (which does not use the
+		 * output of this function) there is no difference in
+		 * setup between GMII and RGMII modes.
+		 */
+		return CVMX_HELPER_INTERFACE_MODE_GMII;
+	}
+
+	/* Interface 1 is always disabled on CN31XX and CN30XX */
+	if ((interface == 1)
+	    && (OCTEON_IS_MODEL(OCTEON_CN31XX) || OCTEON_IS_MODEL(OCTEON_CN30XX)
+		|| OCTEON_IS_MODEL(OCTEON_CN50XX)
+		|| OCTEON_IS_MODEL(OCTEON_CN52XX)))
+		return CVMX_HELPER_INTERFACE_MODE_DISABLED;
+
+	mode.u64 = cvmx_read_csr(CVMX_GMXX_INF_MODE(interface));
+
+	if (OCTEON_IS_MODEL(OCTEON_CN56XX) || OCTEON_IS_MODEL(OCTEON_CN52XX)) {
+		switch (mode.cn56xx.mode) {
+		case 0:
+			return CVMX_HELPER_INTERFACE_MODE_DISABLED;
+		case 1:
+			return CVMX_HELPER_INTERFACE_MODE_XAUI;
+		case 2:
+			return CVMX_HELPER_INTERFACE_MODE_SGMII;
+		case 3:
+			return CVMX_HELPER_INTERFACE_MODE_PICMG;
+		default:
+			return CVMX_HELPER_INTERFACE_MODE_DISABLED;
+		}
+	} else {
+		if (!mode.s.en)
+			return CVMX_HELPER_INTERFACE_MODE_DISABLED;
+
+		if (mode.s.type) {
+			if (OCTEON_IS_MODEL(OCTEON_CN38XX)
+			    || OCTEON_IS_MODEL(OCTEON_CN58XX))
+				return CVMX_HELPER_INTERFACE_MODE_SPI;
+			else
+				return CVMX_HELPER_INTERFACE_MODE_GMII;
+		} else
+			return CVMX_HELPER_INTERFACE_MODE_RGMII;
+	}
+}
+
+/**
+ * Configure the IPD/PIP tagging and QoS options for a specific
+ * port. This function determines the POW work queue entry
+ * contents for a port. The setup performed here is controlled by
+ * the defines in executive-config.h.
+ *
+ * @ipd_port: Port to configure. This follows the IPD numbering, not the
+ *                 per interface numbering
+ *
+ * Returns Zero on success, negative on failure
+ */
+static int __cvmx_helper_port_setup_ipd(int ipd_port)
+{
+	union cvmx_pip_prt_cfgx port_config;
+	union cvmx_pip_prt_tagx tag_config;
+
+	port_config.u64 = cvmx_read_csr(CVMX_PIP_PRT_CFGX(ipd_port));
+	tag_config.u64 = cvmx_read_csr(CVMX_PIP_PRT_TAGX(ipd_port));
+
+	/* Have each port go to a different POW queue */
+	port_config.s.qos = ipd_port & 0x7;
+
+	/* Process the headers and place the IP header in the work queue */
+	port_config.s.mode = CVMX_HELPER_INPUT_PORT_SKIP_MODE;
+
+	tag_config.s.ip6_src_flag = CVMX_HELPER_INPUT_TAG_IPV6_SRC_IP;
+	tag_config.s.ip6_dst_flag = CVMX_HELPER_INPUT_TAG_IPV6_DST_IP;
+	tag_config.s.ip6_sprt_flag = CVMX_HELPER_INPUT_TAG_IPV6_SRC_PORT;
+	tag_config.s.ip6_dprt_flag = CVMX_HELPER_INPUT_TAG_IPV6_DST_PORT;
+	tag_config.s.ip6_nxth_flag = CVMX_HELPER_INPUT_TAG_IPV6_NEXT_HEADER;
+	tag_config.s.ip4_src_flag = CVMX_HELPER_INPUT_TAG_IPV4_SRC_IP;
+	tag_config.s.ip4_dst_flag = CVMX_HELPER_INPUT_TAG_IPV4_DST_IP;
+	tag_config.s.ip4_sprt_flag = CVMX_HELPER_INPUT_TAG_IPV4_SRC_PORT;
+	tag_config.s.ip4_dprt_flag = CVMX_HELPER_INPUT_TAG_IPV4_DST_PORT;
+	tag_config.s.ip4_pctl_flag = CVMX_HELPER_INPUT_TAG_IPV4_PROTOCOL;
+	tag_config.s.inc_prt_flag = CVMX_HELPER_INPUT_TAG_INPUT_PORT;
+	tag_config.s.tcp6_tag_type = CVMX_HELPER_INPUT_TAG_TYPE;
+	tag_config.s.tcp4_tag_type = CVMX_HELPER_INPUT_TAG_TYPE;
+	tag_config.s.ip6_tag_type = CVMX_HELPER_INPUT_TAG_TYPE;
+	tag_config.s.ip4_tag_type = CVMX_HELPER_INPUT_TAG_TYPE;
+	tag_config.s.non_tag_type = CVMX_HELPER_INPUT_TAG_TYPE;
+	/* Put all packets in group 0. Other groups can be used by the app */
+	tag_config.s.grp = 0;
+
+	cvmx_pip_config_port(ipd_port, port_config, tag_config);
+
+	/* Give the user a chance to override our setting for each port */
+	if (cvmx_override_ipd_port_setup)
+		cvmx_override_ipd_port_setup(ipd_port);
+
+	return 0;
+}
+
+/**
+ * This function probes an interface to determine the actual
+ * number of hardware ports connected to it. It doesn't setup the
+ * ports or enable them. The main goal here is to set the global
+ * interface_port_count[interface] correctly. Hardware setup of the
+ * ports will be performed later.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Zero on success, negative on failure
+ */
+int cvmx_helper_interface_probe(int interface)
+{
+	/* At this stage in the game we don't want packets to be moving yet.
+	   The following probe calls should perform hardware setup
+	   needed to determine port counts. Receive must still be disabled */
+	switch (cvmx_helper_interface_get_mode(interface)) {
+		/* These types don't support ports to IPD/PKO */
+	case CVMX_HELPER_INTERFACE_MODE_DISABLED:
+	case CVMX_HELPER_INTERFACE_MODE_PCIE:
+		interface_port_count[interface] = 0;
+		break;
+		/* XAUI is a single high speed port */
+	case CVMX_HELPER_INTERFACE_MODE_XAUI:
+		interface_port_count[interface] =
+		    __cvmx_helper_xaui_probe(interface);
+		break;
+		/*
+		 * RGMII/GMII/MII are all treated about the same. Most
+		 * functions refer to these ports as RGMII.
+		 */
+	case CVMX_HELPER_INTERFACE_MODE_RGMII:
+	case CVMX_HELPER_INTERFACE_MODE_GMII:
+		interface_port_count[interface] =
+		    __cvmx_helper_rgmii_probe(interface);
+		break;
+		/*
+		 * SPI4 can have 1-16 ports depending on the device at
+		 * the other end.
+		 */
+	case CVMX_HELPER_INTERFACE_MODE_SPI:
+		interface_port_count[interface] =
+		    __cvmx_helper_spi_probe(interface);
+		break;
+		/*
+		 * SGMII can have 1-4 ports depending on how many are
+		 * hooked up.
+		 */
+	case CVMX_HELPER_INTERFACE_MODE_SGMII:
+	case CVMX_HELPER_INTERFACE_MODE_PICMG:
+		interface_port_count[interface] =
+		    __cvmx_helper_sgmii_probe(interface);
+		break;
+		/* PCI target Network Packet Interface */
+	case CVMX_HELPER_INTERFACE_MODE_NPI:
+		interface_port_count[interface] =
+		    __cvmx_helper_npi_probe(interface);
+		break;
+		/*
+		 * Special loopback only ports. These are not the same
+		 * as other ports in loopback mode.
+		 */
+	case CVMX_HELPER_INTERFACE_MODE_LOOP:
+		interface_port_count[interface] =
+		    __cvmx_helper_loop_probe(interface);
+		break;
+	}
+
+	interface_port_count[interface] =
+	    __cvmx_helper_board_interface_probe(interface,
+						interface_port_count
+						[interface]);
+
+	/* Make sure all global variables propagate to other cores */
+	CVMX_SYNCWS;
+
+	return 0;
+}
+
+/**
+ * Setup the IPD/PIP for the ports on an interface. Packet
+ * classification and tagging are set for every port on the
+ * interface. The number of ports on the interface must already
+ * have been probed.
+ *
+ * @interface: Interface to setup IPD/PIP for
+ *
+ * Returns Zero on success, negative on failure
+ */
+static int __cvmx_helper_interface_setup_ipd(int interface)
+{
+	int ipd_port = cvmx_helper_get_ipd_port(interface, 0);
+	int num_ports = interface_port_count[interface];
+
+	while (num_ports--) {
+		__cvmx_helper_port_setup_ipd(ipd_port);
+		ipd_port++;
+	}
+	return 0;
+}
+
+/**
+ * Setup global setting for IPD/PIP not related to a specific
+ * interface or port. This must be called before IPD is enabled.
+ *
+ * Returns Zero on success, negative on failure.
+ */
+static int __cvmx_helper_global_setup_ipd(void)
+{
+	/* Setup the global packet input options */
+	cvmx_ipd_config(CVMX_FPA_PACKET_POOL_SIZE / 8,
+			CVMX_HELPER_FIRST_MBUFF_SKIP / 8,
+			CVMX_HELPER_NOT_FIRST_MBUFF_SKIP / 8,
+			/* The +8 is to account for the next ptr */
+			(CVMX_HELPER_FIRST_MBUFF_SKIP + 8) / 128,
+			/* The +8 is to account for the next ptr */
+			(CVMX_HELPER_NOT_FIRST_MBUFF_SKIP + 8) / 128,
+			CVMX_FPA_WQE_POOL,
+			CVMX_IPD_OPC_MODE_STT,
+			CVMX_HELPER_ENABLE_BACK_PRESSURE);
+	return 0;
+}
+
+/**
+ * Setup the PKO for the ports on an interface. The number of
+ * queues per port and the priority of each PKO output queue
+ * is set here. PKO must be disabled when this function is called.
+ *
+ * @interface: Interface to setup PKO for
+ *
+ * Returns Zero on success, negative on failure
+ */
+static int __cvmx_helper_interface_setup_pko(int interface)
+{
+	/*
+	 * Each packet output queue has an associated priority. The
+	 * higher the priority, the more often it can send a packet. A
+	 * priority of 8 means it can send in all 8 rounds of
+	 * contention. We're going to make each queue one less than
+	 * the last.  The vector of priorities has been extended to
+	 * support CN5xxx CPUs, where up to 16 queues can be
+	 * associated to a port.  To keep backward compatibility we
+	 * don't change the initial 8 priorities and replicate them in
+	 * the second half.  With per-core PKO queues (PKO lockless
+	 * operation) all queues have the same priority.
+	 */
+	uint64_t priorities[16] =
+	    { 8, 7, 6, 5, 4, 3, 2, 1, 8, 7, 6, 5, 4, 3, 2, 1 };
+
+	/*
+	 * Setup the IPD/PIP and PKO for the ports discovered
+	 * above. Here packet classification, tagging and output
+	 * priorities are set.
+	 */
+	int ipd_port = cvmx_helper_get_ipd_port(interface, 0);
+	int num_ports = interface_port_count[interface];
+	while (num_ports--) {
+		/*
+		 * Give the user a chance to override the per queue
+		 * priorities.
+		 */
+		if (cvmx_override_pko_queue_priority)
+			cvmx_override_pko_queue_priority(ipd_port, priorities);
+
+		cvmx_pko_config_port(ipd_port,
+				     cvmx_pko_get_base_queue_per_core(ipd_port,
+								      0),
+				     cvmx_pko_get_num_queues(ipd_port),
+				     priorities);
+		ipd_port++;
+	}
+	return 0;
+}
+
+/**
+ * Setup global setting for PKO not related to a specific
+ * interface or port. This must be called before PKO is enabled.
+ *
+ * Returns Zero on success, negative on failure.
+ */
+static int __cvmx_helper_global_setup_pko(void)
+{
+	/*
+	 * Disable tagwait FAU timeout. This needs to be done before
+	 * anyone might start packet output using tags.
+	 */
+	union cvmx_iob_fau_timeout fau_to;
+	fau_to.u64 = 0;
+	fau_to.s.tout_val = 0xfff;
+	fau_to.s.tout_enb = 0;
+	cvmx_write_csr(CVMX_IOB_FAU_TIMEOUT, fau_to.u64);
+	return 0;
+}
+
+/**
+ * Setup global backpressure setting.
+ *
+ * Returns Zero on success, negative on failure
+ */
+static int __cvmx_helper_global_setup_backpressure(void)
+{
+#if CVMX_HELPER_DISABLE_RGMII_BACKPRESSURE
+	/* Disable backpressure if configured to do so */
+	/* Disable backpressure (pause frame) generation */
+	int num_interfaces = cvmx_helper_get_number_of_interfaces();
+	int interface;
+	for (interface = 0; interface < num_interfaces; interface++) {
+		switch (cvmx_helper_interface_get_mode(interface)) {
+		case CVMX_HELPER_INTERFACE_MODE_DISABLED:
+		case CVMX_HELPER_INTERFACE_MODE_PCIE:
+		case CVMX_HELPER_INTERFACE_MODE_NPI:
+		case CVMX_HELPER_INTERFACE_MODE_LOOP:
+		case CVMX_HELPER_INTERFACE_MODE_XAUI:
+			break;
+		case CVMX_HELPER_INTERFACE_MODE_RGMII:
+		case CVMX_HELPER_INTERFACE_MODE_GMII:
+		case CVMX_HELPER_INTERFACE_MODE_SPI:
+		case CVMX_HELPER_INTERFACE_MODE_SGMII:
+		case CVMX_HELPER_INTERFACE_MODE_PICMG:
+			cvmx_gmx_set_backpressure_override(interface, 0xf);
+			break;
+		}
+	}
+#endif
+
+	return 0;
+}
+
+/**
+ * Enable packet input/output from the hardware. This function is
+ * called after all internal setup is complete and IPD is enabled.
+ * After this function completes, packets will be accepted from the
+ * hardware ports. PKO should still be disabled to make sure packets
+ * aren't sent out partially setup hardware.
+ *
+ * @interface: Interface to enable
+ *
+ * Returns Zero on success, negative on failure
+ */
+static int __cvmx_helper_packet_hardware_enable(int interface)
+{
+	int result = 0;
+	switch (cvmx_helper_interface_get_mode(interface)) {
+		/* These types don't support ports to IPD/PKO */
+	case CVMX_HELPER_INTERFACE_MODE_DISABLED:
+	case CVMX_HELPER_INTERFACE_MODE_PCIE:
+		/* Nothing to do */
+		break;
+		/* XAUI is a single high speed port */
+	case CVMX_HELPER_INTERFACE_MODE_XAUI:
+		result = __cvmx_helper_xaui_enable(interface);
+		break;
+		/*
+		 * RGMII/GMII/MII are all treated about the same. Most
+		 * functions refer to these ports as RGMII
+		 */
+	case CVMX_HELPER_INTERFACE_MODE_RGMII:
+	case CVMX_HELPER_INTERFACE_MODE_GMII:
+		result = __cvmx_helper_rgmii_enable(interface);
+		break;
+		/*
+		 * SPI4 can have 1-16 ports depending on the device at
+		 * the other end
+		 */
+	case CVMX_HELPER_INTERFACE_MODE_SPI:
+		result = __cvmx_helper_spi_enable(interface);
+		break;
+		/*
+		 * SGMII can have 1-4 ports depending on how many are
+		 * hooked up
+		 */
+	case CVMX_HELPER_INTERFACE_MODE_SGMII:
+	case CVMX_HELPER_INTERFACE_MODE_PICMG:
+		result = __cvmx_helper_sgmii_enable(interface);
+		break;
+		/* PCI target Network Packet Interface */
+	case CVMX_HELPER_INTERFACE_MODE_NPI:
+		result = __cvmx_helper_npi_enable(interface);
+		break;
+		/*
+		 * Special loopback only ports. These are not the same
+		 * as other ports in loopback mode
+		 */
+	case CVMX_HELPER_INTERFACE_MODE_LOOP:
+		result = __cvmx_helper_loop_enable(interface);
+		break;
+	}
+	result |= __cvmx_helper_board_hardware_enable(interface);
+	return result;
+}
+
+/**
+ * Function to adjust internal IPD pointer alignments
+ *
+ * Returns 0 on success
+ *         !0 on failure
+ */
+int __cvmx_helper_errata_fix_ipd_ptr_alignment(void)
+{
+#define FIX_IPD_FIRST_BUFF_PAYLOAD_BYTES \
+     (CVMX_FPA_PACKET_POOL_SIZE-8-CVMX_HELPER_FIRST_MBUFF_SKIP)
+#define FIX_IPD_NON_FIRST_BUFF_PAYLOAD_BYTES \
+	(CVMX_FPA_PACKET_POOL_SIZE-8-CVMX_HELPER_NOT_FIRST_MBUFF_SKIP)
+#define FIX_IPD_OUTPORT 0
+	/* Ports 0-15 are interface 0, 16-31 are interface 1 */
+#define INTERFACE(port) (port >> 4)
+#define INDEX(port) (port & 0xf)
+	uint64_t *p64;
+	cvmx_pko_command_word0_t pko_command;
+	union cvmx_buf_ptr g_buffer, pkt_buffer;
+	cvmx_wqe_t *work;
+	int size, num_segs = 0, wqe_pcnt, pkt_pcnt;
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	int retry_cnt;
+	int retry_loop_cnt;
+	int mtu;
+	int i;
+	cvmx_helper_link_info_t link_info;
+
+	/* Save values for restore at end */
+	uint64_t prtx_cfg =
+	    cvmx_read_csr(CVMX_GMXX_PRTX_CFG
+			  (INDEX(FIX_IPD_OUTPORT), INTERFACE(FIX_IPD_OUTPORT)));
+	uint64_t tx_ptr_en =
+	    cvmx_read_csr(CVMX_ASXX_TX_PRT_EN(INTERFACE(FIX_IPD_OUTPORT)));
+	uint64_t rx_ptr_en =
+	    cvmx_read_csr(CVMX_ASXX_RX_PRT_EN(INTERFACE(FIX_IPD_OUTPORT)));
+	uint64_t rxx_jabber =
+	    cvmx_read_csr(CVMX_GMXX_RXX_JABBER
+			  (INDEX(FIX_IPD_OUTPORT), INTERFACE(FIX_IPD_OUTPORT)));
+	uint64_t frame_max =
+	    cvmx_read_csr(CVMX_GMXX_RXX_FRM_MAX
+			  (INDEX(FIX_IPD_OUTPORT), INTERFACE(FIX_IPD_OUTPORT)));
+
+	/* Configure port to gig FDX as required for loopback mode */
+	cvmx_helper_rgmii_internal_loopback(FIX_IPD_OUTPORT);
+
+	/*
+	 * Disable reception on all ports so if traffic is present it
+	 * will not interfere.
+	 */
+	cvmx_write_csr(CVMX_ASXX_RX_PRT_EN(INTERFACE(FIX_IPD_OUTPORT)), 0);
+
+	cvmx_wait(100000000ull);
+
+	for (retry_loop_cnt = 0; retry_loop_cnt < 10; retry_loop_cnt++) {
+		retry_cnt = 100000;
+		wqe_pcnt = cvmx_read_csr(CVMX_IPD_PTR_COUNT);
+		pkt_pcnt = (wqe_pcnt >> 7) & 0x7f;
+		wqe_pcnt &= 0x7f;
+
+		num_segs = (2 + pkt_pcnt - wqe_pcnt) & 3;
+
+		if (num_segs == 0)
+			goto fix_ipd_exit;
+
+		num_segs += 1;
+
+		size =
+		    FIX_IPD_FIRST_BUFF_PAYLOAD_BYTES +
+		    ((num_segs - 1) * FIX_IPD_NON_FIRST_BUFF_PAYLOAD_BYTES) -
+		    (FIX_IPD_NON_FIRST_BUFF_PAYLOAD_BYTES / 2);
+
+		cvmx_write_csr(CVMX_ASXX_PRT_LOOP(INTERFACE(FIX_IPD_OUTPORT)),
+			       1 << INDEX(FIX_IPD_OUTPORT));
+		CVMX_SYNC;
+
+		g_buffer.u64 = 0;
+		g_buffer.s.addr =
+		    cvmx_ptr_to_phys(cvmx_fpa_alloc(CVMX_FPA_WQE_POOL));
+		if (g_buffer.s.addr == 0) {
+			cvmx_dprintf("WARNING: FIX_IPD_PTR_ALIGNMENT "
+				     "buffer allocation failure.\n");
+			goto fix_ipd_exit;
+		}
+
+		g_buffer.s.pool = CVMX_FPA_WQE_POOL;
+		g_buffer.s.size = num_segs;
+
+		pkt_buffer.u64 = 0;
+		pkt_buffer.s.addr =
+		    cvmx_ptr_to_phys(cvmx_fpa_alloc(CVMX_FPA_PACKET_POOL));
+		if (pkt_buffer.s.addr == 0) {
+			cvmx_dprintf("WARNING: FIX_IPD_PTR_ALIGNMENT "
+				     "buffer allocation failure.\n");
+			goto fix_ipd_exit;
+		}
+		pkt_buffer.s.i = 1;
+		pkt_buffer.s.pool = CVMX_FPA_PACKET_POOL;
+		pkt_buffer.s.size = FIX_IPD_FIRST_BUFF_PAYLOAD_BYTES;
+
+		p64 = (uint64_t *) cvmx_phys_to_ptr(pkt_buffer.s.addr);
+		p64[0] = 0xffffffffffff0000ull;
+		p64[1] = 0x08004510ull;
+		p64[2] = ((uint64_t) (size - 14) << 48) | 0x5ae740004000ull;
+		p64[3] = 0x3a5fc0a81073c0a8ull;
+
+		for (i = 0; i < num_segs; i++) {
+			if (i > 0)
+				pkt_buffer.s.size =
+				    FIX_IPD_NON_FIRST_BUFF_PAYLOAD_BYTES;
+
+			if (i == (num_segs - 1))
+				pkt_buffer.s.i = 0;
+
+			*(uint64_t *) cvmx_phys_to_ptr(g_buffer.s.addr +
+						       8 * i) = pkt_buffer.u64;
+		}
+
+		/* Build the PKO command */
+		pko_command.u64 = 0;
+		pko_command.s.segs = num_segs;
+		pko_command.s.total_bytes = size;
+		pko_command.s.dontfree = 0;
+		pko_command.s.gather = 1;
+
+		gmx_cfg.u64 =
+		    cvmx_read_csr(CVMX_GMXX_PRTX_CFG
+				  (INDEX(FIX_IPD_OUTPORT),
+				   INTERFACE(FIX_IPD_OUTPORT)));
+		gmx_cfg.s.en = 1;
+		cvmx_write_csr(CVMX_GMXX_PRTX_CFG
+			       (INDEX(FIX_IPD_OUTPORT),
+				INTERFACE(FIX_IPD_OUTPORT)), gmx_cfg.u64);
+		cvmx_write_csr(CVMX_ASXX_TX_PRT_EN(INTERFACE(FIX_IPD_OUTPORT)),
+			       1 << INDEX(FIX_IPD_OUTPORT));
+		cvmx_write_csr(CVMX_ASXX_RX_PRT_EN(INTERFACE(FIX_IPD_OUTPORT)),
+			       1 << INDEX(FIX_IPD_OUTPORT));
+
+		mtu =
+		    cvmx_read_csr(CVMX_GMXX_RXX_JABBER
+				  (INDEX(FIX_IPD_OUTPORT),
+				   INTERFACE(FIX_IPD_OUTPORT)));
+		cvmx_write_csr(CVMX_GMXX_RXX_JABBER
+			       (INDEX(FIX_IPD_OUTPORT),
+				INTERFACE(FIX_IPD_OUTPORT)), 65392 - 14 - 4);
+		cvmx_write_csr(CVMX_GMXX_RXX_FRM_MAX
+			       (INDEX(FIX_IPD_OUTPORT),
+				INTERFACE(FIX_IPD_OUTPORT)), 65392 - 14 - 4);
+
+		cvmx_pko_send_packet_prepare(FIX_IPD_OUTPORT,
+					     cvmx_pko_get_base_queue
+					     (FIX_IPD_OUTPORT),
+					     CVMX_PKO_LOCK_CMD_QUEUE);
+		cvmx_pko_send_packet_finish(FIX_IPD_OUTPORT,
+					    cvmx_pko_get_base_queue
+					    (FIX_IPD_OUTPORT), pko_command,
+					    g_buffer, CVMX_PKO_LOCK_CMD_QUEUE);
+
+		CVMX_SYNC;
+
+		do {
+			work = cvmx_pow_work_request_sync(CVMX_POW_WAIT);
+			retry_cnt--;
+		} while ((work == NULL) && (retry_cnt > 0));
+
+		if (!retry_cnt)
+			cvmx_dprintf("WARNING: FIX_IPD_PTR_ALIGNMENT "
+				     "get_work() timeout occured.\n");
+
+		/* Free packet */
+		if (work)
+			cvmx_helper_free_packet_data(work);
+	}
+
+fix_ipd_exit:
+
+	/* Return CSR configs to saved values */
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG
+		       (INDEX(FIX_IPD_OUTPORT), INTERFACE(FIX_IPD_OUTPORT)),
+		       prtx_cfg);
+	cvmx_write_csr(CVMX_ASXX_TX_PRT_EN(INTERFACE(FIX_IPD_OUTPORT)),
+		       tx_ptr_en);
+	cvmx_write_csr(CVMX_ASXX_RX_PRT_EN(INTERFACE(FIX_IPD_OUTPORT)),
+		       rx_ptr_en);
+	cvmx_write_csr(CVMX_GMXX_RXX_JABBER
+		       (INDEX(FIX_IPD_OUTPORT), INTERFACE(FIX_IPD_OUTPORT)),
+		       rxx_jabber);
+	cvmx_write_csr(CVMX_GMXX_RXX_FRM_MAX
+		       (INDEX(FIX_IPD_OUTPORT), INTERFACE(FIX_IPD_OUTPORT)),
+		       frame_max);
+	cvmx_write_csr(CVMX_ASXX_PRT_LOOP(INTERFACE(FIX_IPD_OUTPORT)), 0);
+	/* Set link to down so autonegotiation will set it up again */
+	link_info.u64 = 0;
+	cvmx_helper_link_set(FIX_IPD_OUTPORT, link_info);
+
+	/*
+	 * Bring the link back up as autonegotiation is not done in
+	 * user applications.
+	 */
+	cvmx_helper_link_autoconf(FIX_IPD_OUTPORT);
+
+	CVMX_SYNC;
+	if (num_segs)
+		cvmx_dprintf("WARNING: FIX_IPD_PTR_ALIGNMENT failed.\n");
+
+	return !!num_segs;
+
+}
+
+/**
+ * Called after all internal packet IO paths are setup. This
+ * function enables IPD/PIP and begins packet input and output.
+ *
+ * Returns Zero on success, negative on failure
+ */
+int cvmx_helper_ipd_and_packet_input_enable(void)
+{
+	int num_interfaces;
+	int interface;
+
+	/* Enable IPD */
+	cvmx_ipd_enable();
+
+	/*
+	 * Time to enable hardware ports packet input and output. Note
+	 * that at this point IPD/PIP must be fully functional and PKO
+	 * must be disabled
+	 */
+	num_interfaces = cvmx_helper_get_number_of_interfaces();
+	for (interface = 0; interface < num_interfaces; interface++) {
+		if (cvmx_helper_ports_on_interface(interface) > 0)
+			__cvmx_helper_packet_hardware_enable(interface);
+	}
+
+	/* Finally enable PKO now that the entire path is up and running */
+	cvmx_pko_enable();
+
+	if ((OCTEON_IS_MODEL(OCTEON_CN31XX_PASS1)
+	     || OCTEON_IS_MODEL(OCTEON_CN30XX_PASS1))
+	    && (cvmx_sysinfo_get()->board_type != CVMX_BOARD_TYPE_SIM))
+		__cvmx_helper_errata_fix_ipd_ptr_alignment();
+	return 0;
+}
+
+/**
+ * Initialize the PIP, IPD, and PKO hardware to support
+ * simple priority based queues for the ethernet ports. Each
+ * port is configured with a number of priority queues based
+ * on CVMX_PKO_QUEUES_PER_PORT_* where each queue is lower
+ * priority than the previous.
+ *
+ * Returns Zero on success, non-zero on failure
+ */
+int cvmx_helper_initialize_packet_io_global(void)
+{
+	int result = 0;
+	int interface;
+	union cvmx_l2c_cfg l2c_cfg;
+	union cvmx_smix_en smix_en;
+	const int num_interfaces = cvmx_helper_get_number_of_interfaces();
+
+	/*
+	 * CN52XX pass 1: Due to a bug in 2nd order CDR, it needs to
+	 * be disabled.
+	 */
+	if (OCTEON_IS_MODEL(OCTEON_CN52XX_PASS1_0))
+		__cvmx_helper_errata_qlm_disable_2nd_order_cdr(1);
+
+	/*
+	 * Tell L2 to give the IOB statically higher priority compared
+	 * to the cores. This avoids conditions where IO blocks might
+	 * be starved under very high L2 loads.
+	 */
+	l2c_cfg.u64 = cvmx_read_csr(CVMX_L2C_CFG);
+	l2c_cfg.s.lrf_arb_mode = 0;
+	l2c_cfg.s.rfb_arb_mode = 0;
+	cvmx_write_csr(CVMX_L2C_CFG, l2c_cfg.u64);
+
+	/* Make sure SMI/MDIO is enabled so we can query PHYs */
+	smix_en.u64 = cvmx_read_csr(CVMX_SMIX_EN(0));
+	if (!smix_en.s.en) {
+		smix_en.s.en = 1;
+		cvmx_write_csr(CVMX_SMIX_EN(0), smix_en.u64);
+	}
+
+	/* Newer chips actually have two SMI/MDIO interfaces */
+	if (!OCTEON_IS_MODEL(OCTEON_CN3XXX) &&
+	    !OCTEON_IS_MODEL(OCTEON_CN58XX) &&
+	    !OCTEON_IS_MODEL(OCTEON_CN50XX)) {
+		smix_en.u64 = cvmx_read_csr(CVMX_SMIX_EN(1));
+		if (!smix_en.s.en) {
+			smix_en.s.en = 1;
+			cvmx_write_csr(CVMX_SMIX_EN(1), smix_en.u64);
+		}
+	}
+
+	cvmx_pko_initialize_global();
+	for (interface = 0; interface < num_interfaces; interface++) {
+		result |= cvmx_helper_interface_probe(interface);
+		if (cvmx_helper_ports_on_interface(interface) > 0)
+			cvmx_dprintf("Interface %d has %d ports (%s)\n",
+				     interface,
+				     cvmx_helper_ports_on_interface(interface),
+				     cvmx_helper_interface_mode_to_string
+				     (cvmx_helper_interface_get_mode
+				      (interface)));
+		result |= __cvmx_helper_interface_setup_ipd(interface);
+		result |= __cvmx_helper_interface_setup_pko(interface);
+	}
+
+	result |= __cvmx_helper_global_setup_ipd();
+	result |= __cvmx_helper_global_setup_pko();
+
+	/* Enable any flow control and backpressure */
+	result |= __cvmx_helper_global_setup_backpressure();
+
+#if CVMX_HELPER_ENABLE_IPD
+	result |= cvmx_helper_ipd_and_packet_input_enable();
+#endif
+	return result;
+}
+
+/**
+ * Does core local initialization for packet io
+ *
+ * Returns Zero on success, non-zero on failure
+ */
+int cvmx_helper_initialize_packet_io_local(void)
+{
+	return cvmx_pko_initialize_local();
+}
+
+/**
+ * Auto configure an IPD/PKO port link state and speed. This
+ * function basically does the equivalent of:
+ * cvmx_helper_link_set(ipd_port, cvmx_helper_link_get(ipd_port));
+ *
+ * @ipd_port: IPD/PKO port to auto configure
+ *
+ * Returns Link state after configure
+ */
+cvmx_helper_link_info_t cvmx_helper_link_autoconf(int ipd_port)
+{
+	cvmx_helper_link_info_t link_info;
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	int index = cvmx_helper_get_interface_index_num(ipd_port);
+
+	if (index >= cvmx_helper_ports_on_interface(interface)) {
+		link_info.u64 = 0;
+		return link_info;
+	}
+
+	link_info = cvmx_helper_link_get(ipd_port);
+	if (link_info.u64 == port_link_info[ipd_port].u64)
+		return link_info;
+
+	/* If we fail to set the link speed, port_link_info will not change */
+	cvmx_helper_link_set(ipd_port, link_info);
+
+	/*
+	 * port_link_info should be the current value, which will be
+	 * different than expect if cvmx_helper_link_set() failed.
+	 */
+	return port_link_info[ipd_port];
+}
+
+/**
+ * Return the link state of an IPD/PKO port as returned by
+ * auto negotiation. The result of this function may not match
+ * Octeon's link config if auto negotiation has changed since
+ * the last call to cvmx_helper_link_set().
+ *
+ * @ipd_port: IPD/PKO port to query
+ *
+ * Returns Link state
+ */
+cvmx_helper_link_info_t cvmx_helper_link_get(int ipd_port)
+{
+	cvmx_helper_link_info_t result;
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	int index = cvmx_helper_get_interface_index_num(ipd_port);
+
+	/* The default result will be a down link unless the code below
+	   changes it */
+	result.u64 = 0;
+
+	if (index >= cvmx_helper_ports_on_interface(interface))
+		return result;
+
+	switch (cvmx_helper_interface_get_mode(interface)) {
+	case CVMX_HELPER_INTERFACE_MODE_DISABLED:
+	case CVMX_HELPER_INTERFACE_MODE_PCIE:
+		/* Network links are not supported */
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_XAUI:
+		result = __cvmx_helper_xaui_link_get(ipd_port);
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_GMII:
+		if (index == 0)
+			result = __cvmx_helper_rgmii_link_get(ipd_port);
+		else {
+			result.s.full_duplex = 1;
+			result.s.link_up = 1;
+			result.s.speed = 1000;
+		}
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_RGMII:
+		result = __cvmx_helper_rgmii_link_get(ipd_port);
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_SPI:
+		result = __cvmx_helper_spi_link_get(ipd_port);
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_SGMII:
+	case CVMX_HELPER_INTERFACE_MODE_PICMG:
+		result = __cvmx_helper_sgmii_link_get(ipd_port);
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_NPI:
+	case CVMX_HELPER_INTERFACE_MODE_LOOP:
+		/* Network links are not supported */
+		break;
+	}
+	return result;
+}
+
+/**
+ * Configure an IPD/PKO port for the specified link state. This
+ * function does not influence auto negotiation at the PHY level.
+ * The passed link state must always match the link state returned
+ * by cvmx_helper_link_get(). It is normally best to use
+ * cvmx_helper_link_autoconf() instead.
+ *
+ * @ipd_port:  IPD/PKO port to configure
+ * @link_info: The new link state
+ *
+ * Returns Zero on success, negative on failure
+ */
+int cvmx_helper_link_set(int ipd_port, cvmx_helper_link_info_t link_info)
+{
+	int result = -1;
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	int index = cvmx_helper_get_interface_index_num(ipd_port);
+
+	if (index >= cvmx_helper_ports_on_interface(interface))
+		return -1;
+
+	switch (cvmx_helper_interface_get_mode(interface)) {
+	case CVMX_HELPER_INTERFACE_MODE_DISABLED:
+	case CVMX_HELPER_INTERFACE_MODE_PCIE:
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_XAUI:
+		result = __cvmx_helper_xaui_link_set(ipd_port, link_info);
+		break;
+		/*
+		 * RGMII/GMII/MII are all treated about the same. Most
+		 * functions refer to these ports as RGMII.
+		 */
+	case CVMX_HELPER_INTERFACE_MODE_RGMII:
+	case CVMX_HELPER_INTERFACE_MODE_GMII:
+		result = __cvmx_helper_rgmii_link_set(ipd_port, link_info);
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_SPI:
+		result = __cvmx_helper_spi_link_set(ipd_port, link_info);
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_SGMII:
+	case CVMX_HELPER_INTERFACE_MODE_PICMG:
+		result = __cvmx_helper_sgmii_link_set(ipd_port, link_info);
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_NPI:
+	case CVMX_HELPER_INTERFACE_MODE_LOOP:
+		break;
+	}
+	/* Set the port_link_info here so that the link status is updated
+	   no matter how cvmx_helper_link_set is called. We don't change
+	   the value if link_set failed */
+	if (result == 0)
+		port_link_info[ipd_port].u64 = link_info.u64;
+	return result;
+}
+
+/**
+ * Configure a port for internal and/or external loopback. Internal loopback
+ * causes packets sent by the port to be received by Octeon. External loopback
+ * causes packets received from the wire to sent out again.
+ *
+ * @ipd_port: IPD/PKO port to loopback.
+ * @enable_internal:
+ *                 Non zero if you want internal loopback
+ * @enable_external:
+ *                 Non zero if you want external loopback
+ *
+ * Returns Zero on success, negative on failure.
+ */
+int cvmx_helper_configure_loopback(int ipd_port, int enable_internal,
+				   int enable_external)
+{
+	int result = -1;
+	int interface = cvmx_helper_get_interface_num(ipd_port);
+	int index = cvmx_helper_get_interface_index_num(ipd_port);
+
+	if (index >= cvmx_helper_ports_on_interface(interface))
+		return -1;
+
+	switch (cvmx_helper_interface_get_mode(interface)) {
+	case CVMX_HELPER_INTERFACE_MODE_DISABLED:
+	case CVMX_HELPER_INTERFACE_MODE_PCIE:
+	case CVMX_HELPER_INTERFACE_MODE_SPI:
+	case CVMX_HELPER_INTERFACE_MODE_NPI:
+	case CVMX_HELPER_INTERFACE_MODE_LOOP:
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_XAUI:
+		result =
+		    __cvmx_helper_xaui_configure_loopback(ipd_port,
+							  enable_internal,
+							  enable_external);
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_RGMII:
+	case CVMX_HELPER_INTERFACE_MODE_GMII:
+		result =
+		    __cvmx_helper_rgmii_configure_loopback(ipd_port,
+							   enable_internal,
+							   enable_external);
+		break;
+	case CVMX_HELPER_INTERFACE_MODE_SGMII:
+	case CVMX_HELPER_INTERFACE_MODE_PICMG:
+		result =
+		    __cvmx_helper_sgmii_configure_loopback(ipd_port,
+							   enable_internal,
+							   enable_external);
+		break;
+	}
+	return result;
+}
diff --git a/drivers/staging/octeon/cvmx-helper.h b/drivers/staging/octeon/cvmx-helper.h
new file mode 100644
index 0000000..51916f3
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-helper.h
@@ -0,0 +1,227 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ *
+ * Helper functions for common, but complicated tasks.
+ *
+ */
+
+#ifndef __CVMX_HELPER_H__
+#define __CVMX_HELPER_H__
+
+#include "cvmx-config.h"
+#include "cvmx-fpa.h"
+#include "cvmx-wqe.h"
+
+typedef enum {
+	CVMX_HELPER_INTERFACE_MODE_DISABLED,
+	CVMX_HELPER_INTERFACE_MODE_RGMII,
+	CVMX_HELPER_INTERFACE_MODE_GMII,
+	CVMX_HELPER_INTERFACE_MODE_SPI,
+	CVMX_HELPER_INTERFACE_MODE_PCIE,
+	CVMX_HELPER_INTERFACE_MODE_XAUI,
+	CVMX_HELPER_INTERFACE_MODE_SGMII,
+	CVMX_HELPER_INTERFACE_MODE_PICMG,
+	CVMX_HELPER_INTERFACE_MODE_NPI,
+	CVMX_HELPER_INTERFACE_MODE_LOOP,
+} cvmx_helper_interface_mode_t;
+
+typedef union {
+	uint64_t u64;
+	struct {
+		uint64_t reserved_20_63:44;
+		uint64_t link_up:1;	    /**< Is the physical link up? */
+		uint64_t full_duplex:1;	    /**< 1 if the link is full duplex */
+		uint64_t speed:18;	    /**< Speed of the link in Mbps */
+	} s;
+} cvmx_helper_link_info_t;
+
+#include "cvmx-helper-fpa.h"
+
+#include <asm/octeon/cvmx-helper-errata.h>
+#include "cvmx-helper-loop.h"
+#include "cvmx-helper-npi.h"
+#include "cvmx-helper-rgmii.h"
+#include "cvmx-helper-sgmii.h"
+#include "cvmx-helper-spi.h"
+#include "cvmx-helper-util.h"
+#include "cvmx-helper-xaui.h"
+
+/**
+ * cvmx_override_pko_queue_priority(int ipd_port, uint64_t
+ * priorities[16]) is a function pointer. It is meant to allow
+ * customization of the PKO queue priorities based on the port
+ * number. Users should set this pointer to a function before
+ * calling any cvmx-helper operations.
+ */
+extern void (*cvmx_override_pko_queue_priority) (int pko_port,
+						 uint64_t priorities[16]);
+
+/**
+ * cvmx_override_ipd_port_setup(int ipd_port) is a function
+ * pointer. It is meant to allow customization of the IPD port
+ * setup before packet input/output comes online. It is called
+ * after cvmx-helper does the default IPD configuration, but
+ * before IPD is enabled. Users should set this pointer to a
+ * function before calling any cvmx-helper operations.
+ */
+extern void (*cvmx_override_ipd_port_setup) (int ipd_port);
+
+/**
+ * This function enables the IPD and also enables the packet interfaces.
+ * The packet interfaces (RGMII and SPI) must be enabled after the
+ * IPD.  This should be called by the user program after any additional
+ * IPD configuration changes are made if CVMX_HELPER_ENABLE_IPD
+ * is not set in the executive-config.h file.
+ *
+ * Returns 0 on success
+ *         -1 on failure
+ */
+extern int cvmx_helper_ipd_and_packet_input_enable(void);
+
+/**
+ * Initialize the PIP, IPD, and PKO hardware to support
+ * simple priority based queues for the ethernet ports. Each
+ * port is configured with a number of priority queues based
+ * on CVMX_PKO_QUEUES_PER_PORT_* where each queue is lower
+ * priority than the previous.
+ *
+ * Returns Zero on success, non-zero on failure
+ */
+extern int cvmx_helper_initialize_packet_io_global(void);
+
+/**
+ * Does core local initialization for packet io
+ *
+ * Returns Zero on success, non-zero on failure
+ */
+extern int cvmx_helper_initialize_packet_io_local(void);
+
+/**
+ * Returns the number of ports on the given interface.
+ * The interface must be initialized before the port count
+ * can be returned.
+ *
+ * @interface: Which interface to return port count for.
+ *
+ * Returns Port count for interface
+ *         -1 for uninitialized interface
+ */
+extern int cvmx_helper_ports_on_interface(int interface);
+
+/**
+ * Return the number of interfaces the chip has. Each interface
+ * may have multiple ports. Most chips support two interfaces,
+ * but the CNX0XX and CNX1XX are exceptions. These only support
+ * one interface.
+ *
+ * Returns Number of interfaces on chip
+ */
+extern int cvmx_helper_get_number_of_interfaces(void);
+
+/**
+ * Get the operating mode of an interface. Depending on the Octeon
+ * chip and configuration, this function returns an enumeration
+ * of the type of packet I/O supported by an interface.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Mode of the interface. Unknown or unsupported interfaces return
+ *         DISABLED.
+ */
+extern cvmx_helper_interface_mode_t cvmx_helper_interface_get_mode(int
+								   interface);
+
+/**
+ * Auto configure an IPD/PKO port link state and speed. This
+ * function basically does the equivalent of:
+ * cvmx_helper_link_set(ipd_port, cvmx_helper_link_get(ipd_port));
+ *
+ * @ipd_port: IPD/PKO port to auto configure
+ *
+ * Returns Link state after configure
+ */
+extern cvmx_helper_link_info_t cvmx_helper_link_autoconf(int ipd_port);
+
+/**
+ * Return the link state of an IPD/PKO port as returned by
+ * auto negotiation. The result of this function may not match
+ * Octeon's link config if auto negotiation has changed since
+ * the last call to cvmx_helper_link_set().
+ *
+ * @ipd_port: IPD/PKO port to query
+ *
+ * Returns Link state
+ */
+extern cvmx_helper_link_info_t cvmx_helper_link_get(int ipd_port);
+
+/**
+ * Configure an IPD/PKO port for the specified link state. This
+ * function does not influence auto negotiation at the PHY level.
+ * The passed link state must always match the link state returned
+ * by cvmx_helper_link_get(). It is normally best to use
+ * cvmx_helper_link_autoconf() instead.
+ *
+ * @ipd_port:  IPD/PKO port to configure
+ * @link_info: The new link state
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int cvmx_helper_link_set(int ipd_port,
+				cvmx_helper_link_info_t link_info);
+
+/**
+ * This function probes an interface to determine the actual
+ * number of hardware ports connected to it. It doesn't setup the
+ * ports or enable them. The main goal here is to set the global
+ * interface_port_count[interface] correctly. Hardware setup of the
+ * ports will be performed later.
+ *
+ * @interface: Interface to probe
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int cvmx_helper_interface_probe(int interface);
+
+/**
+ * Configure a port for internal and/or external loopback. Internal loopback
+ * causes packets sent by the port to be received by Octeon. External loopback
+ * causes packets received from the wire to sent out again.
+ *
+ * @ipd_port: IPD/PKO port to loopback.
+ * @enable_internal:
+ *                 Non zero if you want internal loopback
+ * @enable_external:
+ *                 Non zero if you want external loopback
+ *
+ * Returns Zero on success, negative on failure.
+ */
+extern int cvmx_helper_configure_loopback(int ipd_port, int enable_internal,
+					  int enable_external);
+
+#endif /* __CVMX_HELPER_H__ */
diff --git a/drivers/staging/octeon/cvmx-interrupt-decodes.c b/drivers/staging/octeon/cvmx-interrupt-decodes.c
new file mode 100644
index 0000000..a3337e3
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-interrupt-decodes.c
@@ -0,0 +1,371 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2009 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ *
+ * Automatically generated functions useful for enabling
+ * and decoding RSL_INT_BLOCKS interrupts.
+ *
+ */
+
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-gmxx-defs.h"
+#include "cvmx-pcsx-defs.h"
+#include "cvmx-pcsxx-defs.h"
+#include "cvmx-spxx-defs.h"
+#include "cvmx-stxx-defs.h"
+
+#ifndef PRINT_ERROR
+#define PRINT_ERROR(format, ...)
+#endif
+
+
+/**
+ * __cvmx_interrupt_gmxx_rxx_int_en_enable enables all interrupt bits in cvmx_gmxx_rxx_int_en_t
+ */
+void __cvmx_interrupt_gmxx_rxx_int_en_enable(int index, int block)
+{
+	union cvmx_gmxx_rxx_int_en gmx_rx_int_en;
+	cvmx_write_csr(CVMX_GMXX_RXX_INT_REG(index, block),
+		       cvmx_read_csr(CVMX_GMXX_RXX_INT_REG(index, block)));
+	gmx_rx_int_en.u64 = 0;
+	if (OCTEON_IS_MODEL(OCTEON_CN56XX)) {
+		/* Skipping gmx_rx_int_en.s.reserved_29_63 */
+		gmx_rx_int_en.s.hg2cc = 1;
+		gmx_rx_int_en.s.hg2fld = 1;
+		gmx_rx_int_en.s.undat = 1;
+		gmx_rx_int_en.s.uneop = 1;
+		gmx_rx_int_en.s.unsop = 1;
+		gmx_rx_int_en.s.bad_term = 1;
+		gmx_rx_int_en.s.bad_seq = 1;
+		gmx_rx_int_en.s.rem_fault = 1;
+		gmx_rx_int_en.s.loc_fault = 1;
+		gmx_rx_int_en.s.pause_drp = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_16_18 */
+		/*gmx_rx_int_en.s.ifgerr = 1; */
+		/*gmx_rx_int_en.s.coldet = 1; // Collsion detect */
+		/*gmx_rx_int_en.s.falerr = 1; // False carrier error or extend error after slottime */
+		/*gmx_rx_int_en.s.rsverr = 1; // RGMII reserved opcodes */
+		/*gmx_rx_int_en.s.pcterr = 1; // Bad Preamble / Protocol */
+		gmx_rx_int_en.s.ovrerr = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_9_9 */
+		gmx_rx_int_en.s.skperr = 1;
+		gmx_rx_int_en.s.rcverr = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_5_6 */
+		/*gmx_rx_int_en.s.fcserr = 1; // FCS errors are handled when we get work */
+		gmx_rx_int_en.s.jabber = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_2_2 */
+		gmx_rx_int_en.s.carext = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_0_0 */
+	}
+	if (OCTEON_IS_MODEL(OCTEON_CN30XX)) {
+		/* Skipping gmx_rx_int_en.s.reserved_19_63 */
+		/*gmx_rx_int_en.s.phy_dupx = 1; */
+		/*gmx_rx_int_en.s.phy_spd = 1; */
+		/*gmx_rx_int_en.s.phy_link = 1; */
+		/*gmx_rx_int_en.s.ifgerr = 1; */
+		/*gmx_rx_int_en.s.coldet = 1; // Collsion detect */
+		/*gmx_rx_int_en.s.falerr = 1; // False carrier error or extend error after slottime */
+		/*gmx_rx_int_en.s.rsverr = 1; // RGMII reserved opcodes */
+		/*gmx_rx_int_en.s.pcterr = 1; // Bad Preamble / Protocol */
+		gmx_rx_int_en.s.ovrerr = 1;
+		gmx_rx_int_en.s.niberr = 1;
+		gmx_rx_int_en.s.skperr = 1;
+		gmx_rx_int_en.s.rcverr = 1;
+		/*gmx_rx_int_en.s.lenerr = 1; // Length errors are handled when we get work */
+		gmx_rx_int_en.s.alnerr = 1;
+		/*gmx_rx_int_en.s.fcserr = 1; // FCS errors are handled when we get work */
+		gmx_rx_int_en.s.jabber = 1;
+		gmx_rx_int_en.s.maxerr = 1;
+		gmx_rx_int_en.s.carext = 1;
+		gmx_rx_int_en.s.minerr = 1;
+	}
+	if (OCTEON_IS_MODEL(OCTEON_CN50XX)) {
+		/* Skipping gmx_rx_int_en.s.reserved_20_63 */
+		gmx_rx_int_en.s.pause_drp = 1;
+		/*gmx_rx_int_en.s.phy_dupx = 1; */
+		/*gmx_rx_int_en.s.phy_spd = 1; */
+		/*gmx_rx_int_en.s.phy_link = 1; */
+		/*gmx_rx_int_en.s.ifgerr = 1; */
+		/*gmx_rx_int_en.s.coldet = 1; // Collsion detect */
+		/*gmx_rx_int_en.s.falerr = 1; // False carrier error or extend error after slottime */
+		/*gmx_rx_int_en.s.rsverr = 1; // RGMII reserved opcodes */
+		/*gmx_rx_int_en.s.pcterr = 1; // Bad Preamble / Protocol */
+		gmx_rx_int_en.s.ovrerr = 1;
+		gmx_rx_int_en.s.niberr = 1;
+		gmx_rx_int_en.s.skperr = 1;
+		gmx_rx_int_en.s.rcverr = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_6_6 */
+		gmx_rx_int_en.s.alnerr = 1;
+		/*gmx_rx_int_en.s.fcserr = 1; // FCS errors are handled when we get work */
+		gmx_rx_int_en.s.jabber = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_2_2 */
+		gmx_rx_int_en.s.carext = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_0_0 */
+	}
+	if (OCTEON_IS_MODEL(OCTEON_CN38XX)) {
+		/* Skipping gmx_rx_int_en.s.reserved_19_63 */
+		/*gmx_rx_int_en.s.phy_dupx = 1; */
+		/*gmx_rx_int_en.s.phy_spd = 1; */
+		/*gmx_rx_int_en.s.phy_link = 1; */
+		/*gmx_rx_int_en.s.ifgerr = 1; */
+		/*gmx_rx_int_en.s.coldet = 1; // Collsion detect */
+		/*gmx_rx_int_en.s.falerr = 1; // False carrier error or extend error after slottime */
+		/*gmx_rx_int_en.s.rsverr = 1; // RGMII reserved opcodes */
+		/*gmx_rx_int_en.s.pcterr = 1; // Bad Preamble / Protocol */
+		gmx_rx_int_en.s.ovrerr = 1;
+		gmx_rx_int_en.s.niberr = 1;
+		gmx_rx_int_en.s.skperr = 1;
+		gmx_rx_int_en.s.rcverr = 1;
+		/*gmx_rx_int_en.s.lenerr = 1; // Length errors are handled when we get work */
+		gmx_rx_int_en.s.alnerr = 1;
+		/*gmx_rx_int_en.s.fcserr = 1; // FCS errors are handled when we get work */
+		gmx_rx_int_en.s.jabber = 1;
+		gmx_rx_int_en.s.maxerr = 1;
+		gmx_rx_int_en.s.carext = 1;
+		gmx_rx_int_en.s.minerr = 1;
+	}
+	if (OCTEON_IS_MODEL(OCTEON_CN31XX)) {
+		/* Skipping gmx_rx_int_en.s.reserved_19_63 */
+		/*gmx_rx_int_en.s.phy_dupx = 1; */
+		/*gmx_rx_int_en.s.phy_spd = 1; */
+		/*gmx_rx_int_en.s.phy_link = 1; */
+		/*gmx_rx_int_en.s.ifgerr = 1; */
+		/*gmx_rx_int_en.s.coldet = 1; // Collsion detect */
+		/*gmx_rx_int_en.s.falerr = 1; // False carrier error or extend error after slottime */
+		/*gmx_rx_int_en.s.rsverr = 1; // RGMII reserved opcodes */
+		/*gmx_rx_int_en.s.pcterr = 1; // Bad Preamble / Protocol */
+		gmx_rx_int_en.s.ovrerr = 1;
+		gmx_rx_int_en.s.niberr = 1;
+		gmx_rx_int_en.s.skperr = 1;
+		gmx_rx_int_en.s.rcverr = 1;
+		/*gmx_rx_int_en.s.lenerr = 1; // Length errors are handled when we get work */
+		gmx_rx_int_en.s.alnerr = 1;
+		/*gmx_rx_int_en.s.fcserr = 1; // FCS errors are handled when we get work */
+		gmx_rx_int_en.s.jabber = 1;
+		gmx_rx_int_en.s.maxerr = 1;
+		gmx_rx_int_en.s.carext = 1;
+		gmx_rx_int_en.s.minerr = 1;
+	}
+	if (OCTEON_IS_MODEL(OCTEON_CN58XX)) {
+		/* Skipping gmx_rx_int_en.s.reserved_20_63 */
+		gmx_rx_int_en.s.pause_drp = 1;
+		/*gmx_rx_int_en.s.phy_dupx = 1; */
+		/*gmx_rx_int_en.s.phy_spd = 1; */
+		/*gmx_rx_int_en.s.phy_link = 1; */
+		/*gmx_rx_int_en.s.ifgerr = 1; */
+		/*gmx_rx_int_en.s.coldet = 1; // Collsion detect */
+		/*gmx_rx_int_en.s.falerr = 1; // False carrier error or extend error after slottime */
+		/*gmx_rx_int_en.s.rsverr = 1; // RGMII reserved opcodes */
+		/*gmx_rx_int_en.s.pcterr = 1; // Bad Preamble / Protocol */
+		gmx_rx_int_en.s.ovrerr = 1;
+		gmx_rx_int_en.s.niberr = 1;
+		gmx_rx_int_en.s.skperr = 1;
+		gmx_rx_int_en.s.rcverr = 1;
+		/*gmx_rx_int_en.s.lenerr = 1; // Length errors are handled when we get work */
+		gmx_rx_int_en.s.alnerr = 1;
+		/*gmx_rx_int_en.s.fcserr = 1; // FCS errors are handled when we get work */
+		gmx_rx_int_en.s.jabber = 1;
+		gmx_rx_int_en.s.maxerr = 1;
+		gmx_rx_int_en.s.carext = 1;
+		gmx_rx_int_en.s.minerr = 1;
+	}
+	if (OCTEON_IS_MODEL(OCTEON_CN52XX)) {
+		/* Skipping gmx_rx_int_en.s.reserved_29_63 */
+		gmx_rx_int_en.s.hg2cc = 1;
+		gmx_rx_int_en.s.hg2fld = 1;
+		gmx_rx_int_en.s.undat = 1;
+		gmx_rx_int_en.s.uneop = 1;
+		gmx_rx_int_en.s.unsop = 1;
+		gmx_rx_int_en.s.bad_term = 1;
+		gmx_rx_int_en.s.bad_seq = 0;
+		gmx_rx_int_en.s.rem_fault = 1;
+		gmx_rx_int_en.s.loc_fault = 0;
+		gmx_rx_int_en.s.pause_drp = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_16_18 */
+		/*gmx_rx_int_en.s.ifgerr = 1; */
+		/*gmx_rx_int_en.s.coldet = 1; // Collsion detect */
+		/*gmx_rx_int_en.s.falerr = 1; // False carrier error or extend error after slottime */
+		/*gmx_rx_int_en.s.rsverr = 1; // RGMII reserved opcodes */
+		/*gmx_rx_int_en.s.pcterr = 1; // Bad Preamble / Protocol */
+		gmx_rx_int_en.s.ovrerr = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_9_9 */
+		gmx_rx_int_en.s.skperr = 1;
+		gmx_rx_int_en.s.rcverr = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_5_6 */
+		/*gmx_rx_int_en.s.fcserr = 1; // FCS errors are handled when we get work */
+		gmx_rx_int_en.s.jabber = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_2_2 */
+		gmx_rx_int_en.s.carext = 1;
+		/* Skipping gmx_rx_int_en.s.reserved_0_0 */
+	}
+	cvmx_write_csr(CVMX_GMXX_RXX_INT_EN(index, block), gmx_rx_int_en.u64);
+}
+/**
+ * __cvmx_interrupt_pcsx_intx_en_reg_enable enables all interrupt bits in cvmx_pcsx_intx_en_reg_t
+ */
+void __cvmx_interrupt_pcsx_intx_en_reg_enable(int index, int block)
+{
+	union cvmx_pcsx_intx_en_reg pcs_int_en_reg;
+	cvmx_write_csr(CVMX_PCSX_INTX_REG(index, block),
+		       cvmx_read_csr(CVMX_PCSX_INTX_REG(index, block)));
+	pcs_int_en_reg.u64 = 0;
+	if (OCTEON_IS_MODEL(OCTEON_CN56XX)) {
+		/* Skipping pcs_int_en_reg.s.reserved_12_63 */
+		/*pcs_int_en_reg.s.dup = 1; // This happens during normal operation */
+		pcs_int_en_reg.s.sync_bad_en = 1;
+		pcs_int_en_reg.s.an_bad_en = 1;
+		pcs_int_en_reg.s.rxlock_en = 1;
+		pcs_int_en_reg.s.rxbad_en = 1;
+		/*pcs_int_en_reg.s.rxerr_en = 1; // This happens during normal operation */
+		pcs_int_en_reg.s.txbad_en = 1;
+		pcs_int_en_reg.s.txfifo_en = 1;
+		pcs_int_en_reg.s.txfifu_en = 1;
+		pcs_int_en_reg.s.an_err_en = 1;
+		/*pcs_int_en_reg.s.xmit_en = 1; // This happens during normal operation */
+		/*pcs_int_en_reg.s.lnkspd_en = 1; // This happens during normal operation */
+	}
+	if (OCTEON_IS_MODEL(OCTEON_CN52XX)) {
+		/* Skipping pcs_int_en_reg.s.reserved_12_63 */
+		/*pcs_int_en_reg.s.dup = 1; // This happens during normal operation */
+		pcs_int_en_reg.s.sync_bad_en = 1;
+		pcs_int_en_reg.s.an_bad_en = 1;
+		pcs_int_en_reg.s.rxlock_en = 1;
+		pcs_int_en_reg.s.rxbad_en = 1;
+		/*pcs_int_en_reg.s.rxerr_en = 1; // This happens during normal operation */
+		pcs_int_en_reg.s.txbad_en = 1;
+		pcs_int_en_reg.s.txfifo_en = 1;
+		pcs_int_en_reg.s.txfifu_en = 1;
+		pcs_int_en_reg.s.an_err_en = 1;
+		/*pcs_int_en_reg.s.xmit_en = 1; // This happens during normal operation */
+		/*pcs_int_en_reg.s.lnkspd_en = 1; // This happens during normal operation */
+	}
+	cvmx_write_csr(CVMX_PCSX_INTX_EN_REG(index, block), pcs_int_en_reg.u64);
+}
+/**
+ * __cvmx_interrupt_pcsxx_int_en_reg_enable enables all interrupt bits in cvmx_pcsxx_int_en_reg_t
+ */
+void __cvmx_interrupt_pcsxx_int_en_reg_enable(int index)
+{
+	union cvmx_pcsxx_int_en_reg pcsx_int_en_reg;
+	cvmx_write_csr(CVMX_PCSXX_INT_REG(index),
+		       cvmx_read_csr(CVMX_PCSXX_INT_REG(index)));
+	pcsx_int_en_reg.u64 = 0;
+	if (OCTEON_IS_MODEL(OCTEON_CN56XX)) {
+		/* Skipping pcsx_int_en_reg.s.reserved_6_63 */
+		pcsx_int_en_reg.s.algnlos_en = 1;
+		pcsx_int_en_reg.s.synlos_en = 1;
+		pcsx_int_en_reg.s.bitlckls_en = 1;
+		pcsx_int_en_reg.s.rxsynbad_en = 1;
+		pcsx_int_en_reg.s.rxbad_en = 1;
+		pcsx_int_en_reg.s.txflt_en = 1;
+	}
+	if (OCTEON_IS_MODEL(OCTEON_CN52XX)) {
+		/* Skipping pcsx_int_en_reg.s.reserved_6_63 */
+		pcsx_int_en_reg.s.algnlos_en = 1;
+		pcsx_int_en_reg.s.synlos_en = 1;
+		pcsx_int_en_reg.s.bitlckls_en = 0;	/* Happens if XAUI module is not installed */
+		pcsx_int_en_reg.s.rxsynbad_en = 1;
+		pcsx_int_en_reg.s.rxbad_en = 1;
+		pcsx_int_en_reg.s.txflt_en = 1;
+	}
+	cvmx_write_csr(CVMX_PCSXX_INT_EN_REG(index), pcsx_int_en_reg.u64);
+}
+
+/**
+ * __cvmx_interrupt_spxx_int_msk_enable enables all interrupt bits in cvmx_spxx_int_msk_t
+ */
+void __cvmx_interrupt_spxx_int_msk_enable(int index)
+{
+	union cvmx_spxx_int_msk spx_int_msk;
+	cvmx_write_csr(CVMX_SPXX_INT_REG(index),
+		       cvmx_read_csr(CVMX_SPXX_INT_REG(index)));
+	spx_int_msk.u64 = 0;
+	if (OCTEON_IS_MODEL(OCTEON_CN38XX)) {
+		/* Skipping spx_int_msk.s.reserved_12_63 */
+		spx_int_msk.s.calerr = 1;
+		spx_int_msk.s.syncerr = 1;
+		spx_int_msk.s.diperr = 1;
+		spx_int_msk.s.tpaovr = 1;
+		spx_int_msk.s.rsverr = 1;
+		spx_int_msk.s.drwnng = 1;
+		spx_int_msk.s.clserr = 1;
+		spx_int_msk.s.spiovr = 1;
+		/* Skipping spx_int_msk.s.reserved_2_3 */
+		spx_int_msk.s.abnorm = 1;
+		spx_int_msk.s.prtnxa = 1;
+	}
+	if (OCTEON_IS_MODEL(OCTEON_CN58XX)) {
+		/* Skipping spx_int_msk.s.reserved_12_63 */
+		spx_int_msk.s.calerr = 1;
+		spx_int_msk.s.syncerr = 1;
+		spx_int_msk.s.diperr = 1;
+		spx_int_msk.s.tpaovr = 1;
+		spx_int_msk.s.rsverr = 1;
+		spx_int_msk.s.drwnng = 1;
+		spx_int_msk.s.clserr = 1;
+		spx_int_msk.s.spiovr = 1;
+		/* Skipping spx_int_msk.s.reserved_2_3 */
+		spx_int_msk.s.abnorm = 1;
+		spx_int_msk.s.prtnxa = 1;
+	}
+	cvmx_write_csr(CVMX_SPXX_INT_MSK(index), spx_int_msk.u64);
+}
+/**
+ * __cvmx_interrupt_stxx_int_msk_enable enables all interrupt bits in cvmx_stxx_int_msk_t
+ */
+void __cvmx_interrupt_stxx_int_msk_enable(int index)
+{
+	union cvmx_stxx_int_msk stx_int_msk;
+	cvmx_write_csr(CVMX_STXX_INT_REG(index),
+		       cvmx_read_csr(CVMX_STXX_INT_REG(index)));
+	stx_int_msk.u64 = 0;
+	if (OCTEON_IS_MODEL(OCTEON_CN38XX)) {
+		/* Skipping stx_int_msk.s.reserved_8_63 */
+		stx_int_msk.s.frmerr = 1;
+		stx_int_msk.s.unxfrm = 1;
+		stx_int_msk.s.nosync = 1;
+		stx_int_msk.s.diperr = 1;
+		stx_int_msk.s.datovr = 1;
+		stx_int_msk.s.ovrbst = 1;
+		stx_int_msk.s.calpar1 = 1;
+		stx_int_msk.s.calpar0 = 1;
+	}
+	if (OCTEON_IS_MODEL(OCTEON_CN58XX)) {
+		/* Skipping stx_int_msk.s.reserved_8_63 */
+		stx_int_msk.s.frmerr = 1;
+		stx_int_msk.s.unxfrm = 1;
+		stx_int_msk.s.nosync = 1;
+		stx_int_msk.s.diperr = 1;
+		stx_int_msk.s.datovr = 1;
+		stx_int_msk.s.ovrbst = 1;
+		stx_int_msk.s.calpar1 = 1;
+		stx_int_msk.s.calpar0 = 1;
+	}
+	cvmx_write_csr(CVMX_STXX_INT_MSK(index), stx_int_msk.u64);
+}
diff --git a/drivers/staging/octeon/cvmx-interrupt-rsl.c b/drivers/staging/octeon/cvmx-interrupt-rsl.c
new file mode 100644
index 0000000..df50048
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-interrupt-rsl.c
@@ -0,0 +1,140 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Utility functions to decode Octeon's RSL_INT_BLOCKS
+ * interrupts into error messages.
+ */
+
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-asxx-defs.h"
+#include "cvmx-gmxx-defs.h"
+
+#ifndef PRINT_ERROR
+#define PRINT_ERROR(format, ...)
+#endif
+
+void __cvmx_interrupt_gmxx_rxx_int_en_enable(int index, int block);
+
+/**
+ * Enable ASX error interrupts that exist on CN3XXX, CN50XX, and
+ * CN58XX.
+ *
+ * @block:  Interface to enable 0-1
+ */
+void __cvmx_interrupt_asxx_enable(int block)
+{
+	int mask;
+	union cvmx_asxx_int_en csr;
+	/*
+	 * CN38XX and CN58XX have two interfaces with 4 ports per
+	 * interface. All other chips have a max of 3 ports on
+	 * interface 0
+	 */
+	if (OCTEON_IS_MODEL(OCTEON_CN38XX) || OCTEON_IS_MODEL(OCTEON_CN58XX))
+		mask = 0xf;	/* Set enables for 4 ports */
+	else
+		mask = 0x7;	/* Set enables for 3 ports */
+
+	/* Enable interface interrupts */
+	csr.u64 = cvmx_read_csr(CVMX_ASXX_INT_EN(block));
+	csr.s.txpsh = mask;
+	csr.s.txpop = mask;
+	csr.s.ovrflw = mask;
+	cvmx_write_csr(CVMX_ASXX_INT_EN(block), csr.u64);
+}
+/**
+ * Enable GMX error reporting for the supplied interface
+ *
+ * @interface: Interface to enable
+ */
+void __cvmx_interrupt_gmxx_enable(int interface)
+{
+	union cvmx_gmxx_inf_mode mode;
+	union cvmx_gmxx_tx_int_en gmx_tx_int_en;
+	int num_ports;
+	int index;
+
+	mode.u64 = cvmx_read_csr(CVMX_GMXX_INF_MODE(interface));
+
+	if (OCTEON_IS_MODEL(OCTEON_CN56XX) || OCTEON_IS_MODEL(OCTEON_CN52XX)) {
+		if (mode.s.en) {
+			switch (mode.cn56xx.mode) {
+			case 1:	/* XAUI */
+				num_ports = 1;
+				break;
+			case 2:	/* SGMII */
+			case 3:	/* PICMG */
+				num_ports = 4;
+				break;
+			default:	/* Disabled */
+				num_ports = 0;
+				break;
+			}
+		} else
+			num_ports = 0;
+	} else {
+		if (mode.s.en) {
+			if (OCTEON_IS_MODEL(OCTEON_CN38XX)
+			    || OCTEON_IS_MODEL(OCTEON_CN58XX)) {
+				/*
+				 * SPI on CN38XX and CN58XX report all
+				 * errors through port 0.  RGMII needs
+				 * to check all 4 ports
+				 */
+				if (mode.s.type)
+					num_ports = 1;
+				else
+					num_ports = 4;
+			} else {
+				/*
+				 * CN30XX, CN31XX, and CN50XX have two
+				 * or three ports. GMII and MII has 2,
+				 * RGMII has three
+				 */
+				if (mode.s.type)
+					num_ports = 2;
+				else
+					num_ports = 3;
+			}
+		} else
+			num_ports = 0;
+	}
+
+	gmx_tx_int_en.u64 = 0;
+	if (num_ports) {
+		if (OCTEON_IS_MODEL(OCTEON_CN38XX)
+		    || OCTEON_IS_MODEL(OCTEON_CN58XX))
+			gmx_tx_int_en.s.ncb_nxa = 1;
+		gmx_tx_int_en.s.pko_nxa = 1;
+	}
+	gmx_tx_int_en.s.undflw = (1 << num_ports) - 1;
+	cvmx_write_csr(CVMX_GMXX_TX_INT_EN(interface), gmx_tx_int_en.u64);
+	for (index = 0; index < num_ports; index++)
+		__cvmx_interrupt_gmxx_rxx_int_en_enable(index, interface);
+}
diff --git a/drivers/staging/octeon/cvmx-ipd.h b/drivers/staging/octeon/cvmx-ipd.h
new file mode 100644
index 0000000..115a552
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-ipd.h
@@ -0,0 +1,338 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ *
+ * Interface to the hardware Input Packet Data unit.
+ */
+
+#ifndef __CVMX_IPD_H__
+#define __CVMX_IPD_H__
+
+#include <asm/octeon/octeon-feature.h>
+
+#include <asm/octeon/cvmx-ipd-defs.h>
+
+enum cvmx_ipd_mode {
+   CVMX_IPD_OPC_MODE_STT = 0LL,   /* All blocks DRAM, not cached in L2 */
+   CVMX_IPD_OPC_MODE_STF = 1LL,   /* All bloccks into  L2 */
+   CVMX_IPD_OPC_MODE_STF1_STT = 2LL,   /* 1st block L2, rest DRAM */
+   CVMX_IPD_OPC_MODE_STF2_STT = 3LL    /* 1st, 2nd blocks L2, rest DRAM */
+};
+
+#ifndef CVMX_ENABLE_LEN_M8_FIX
+#define CVMX_ENABLE_LEN_M8_FIX 0
+#endif
+
+/* CSR typedefs have been moved to cvmx-csr-*.h */
+typedef union cvmx_ipd_1st_mbuff_skip cvmx_ipd_mbuff_first_skip_t;
+typedef union cvmx_ipd_1st_next_ptr_back cvmx_ipd_first_next_ptr_back_t;
+
+typedef cvmx_ipd_mbuff_first_skip_t cvmx_ipd_mbuff_not_first_skip_t;
+typedef cvmx_ipd_first_next_ptr_back_t cvmx_ipd_second_next_ptr_back_t;
+
+/**
+ * Configure IPD
+ *
+ * @mbuff_size: Packets buffer size in 8 byte words
+ * @first_mbuff_skip:
+ *                   Number of 8 byte words to skip in the first buffer
+ * @not_first_mbuff_skip:
+ *                   Number of 8 byte words to skip in each following buffer
+ * @first_back: Must be same as first_mbuff_skip / 128
+ * @second_back:
+ *                   Must be same as not_first_mbuff_skip / 128
+ * @wqe_fpa_pool:
+ *                   FPA pool to get work entries from
+ * @cache_mode:
+ * @back_pres_enable_flag:
+ *                   Enable or disable port back pressure
+ */
+static inline void cvmx_ipd_config(uint64_t mbuff_size,
+				   uint64_t first_mbuff_skip,
+				   uint64_t not_first_mbuff_skip,
+				   uint64_t first_back,
+				   uint64_t second_back,
+				   uint64_t wqe_fpa_pool,
+				   enum cvmx_ipd_mode cache_mode,
+				   uint64_t back_pres_enable_flag)
+{
+	cvmx_ipd_mbuff_first_skip_t first_skip;
+	cvmx_ipd_mbuff_not_first_skip_t not_first_skip;
+	union cvmx_ipd_packet_mbuff_size size;
+	cvmx_ipd_first_next_ptr_back_t first_back_struct;
+	cvmx_ipd_second_next_ptr_back_t second_back_struct;
+	union cvmx_ipd_wqe_fpa_queue wqe_pool;
+	union cvmx_ipd_ctl_status ipd_ctl_reg;
+
+	first_skip.u64 = 0;
+	first_skip.s.skip_sz = first_mbuff_skip;
+	cvmx_write_csr(CVMX_IPD_1ST_MBUFF_SKIP, first_skip.u64);
+
+	not_first_skip.u64 = 0;
+	not_first_skip.s.skip_sz = not_first_mbuff_skip;
+	cvmx_write_csr(CVMX_IPD_NOT_1ST_MBUFF_SKIP, not_first_skip.u64);
+
+	size.u64 = 0;
+	size.s.mb_size = mbuff_size;
+	cvmx_write_csr(CVMX_IPD_PACKET_MBUFF_SIZE, size.u64);
+
+	first_back_struct.u64 = 0;
+	first_back_struct.s.back = first_back;
+	cvmx_write_csr(CVMX_IPD_1st_NEXT_PTR_BACK, first_back_struct.u64);
+
+	second_back_struct.u64 = 0;
+	second_back_struct.s.back = second_back;
+	cvmx_write_csr(CVMX_IPD_2nd_NEXT_PTR_BACK, second_back_struct.u64);
+
+	wqe_pool.u64 = 0;
+	wqe_pool.s.wqe_pool = wqe_fpa_pool;
+	cvmx_write_csr(CVMX_IPD_WQE_FPA_QUEUE, wqe_pool.u64);
+
+	ipd_ctl_reg.u64 = cvmx_read_csr(CVMX_IPD_CTL_STATUS);
+	ipd_ctl_reg.s.opc_mode = cache_mode;
+	ipd_ctl_reg.s.pbp_en = back_pres_enable_flag;
+	cvmx_write_csr(CVMX_IPD_CTL_STATUS, ipd_ctl_reg.u64);
+
+	/* Note: the example RED code that used to be here has been moved to
+	   cvmx_helper_setup_red */
+}
+
+/**
+ * Enable IPD
+ */
+static inline void cvmx_ipd_enable(void)
+{
+	union cvmx_ipd_ctl_status ipd_reg;
+	ipd_reg.u64 = cvmx_read_csr(CVMX_IPD_CTL_STATUS);
+	if (ipd_reg.s.ipd_en) {
+		cvmx_dprintf
+		    ("Warning: Enabling IPD when IPD already enabled.\n");
+	}
+	ipd_reg.s.ipd_en = 1;
+#if  CVMX_ENABLE_LEN_M8_FIX
+	if (!OCTEON_IS_MODEL(OCTEON_CN38XX_PASS2))
+		ipd_reg.s.len_m8 = TRUE;
+#endif
+	cvmx_write_csr(CVMX_IPD_CTL_STATUS, ipd_reg.u64);
+}
+
+/**
+ * Disable IPD
+ */
+static inline void cvmx_ipd_disable(void)
+{
+	union cvmx_ipd_ctl_status ipd_reg;
+	ipd_reg.u64 = cvmx_read_csr(CVMX_IPD_CTL_STATUS);
+	ipd_reg.s.ipd_en = 0;
+	cvmx_write_csr(CVMX_IPD_CTL_STATUS, ipd_reg.u64);
+}
+
+/**
+ * Supportive function for cvmx_fpa_shutdown_pool.
+ */
+static inline void cvmx_ipd_free_ptr(void)
+{
+	/* Only CN38XXp{1,2} cannot read pointer out of the IPD */
+	if (!OCTEON_IS_MODEL(OCTEON_CN38XX_PASS1)
+	    && !OCTEON_IS_MODEL(OCTEON_CN38XX_PASS2)) {
+		int no_wptr = 0;
+		union cvmx_ipd_ptr_count ipd_ptr_count;
+		ipd_ptr_count.u64 = cvmx_read_csr(CVMX_IPD_PTR_COUNT);
+
+		/* Handle Work Queue Entry in cn56xx and cn52xx */
+		if (octeon_has_feature(OCTEON_FEATURE_NO_WPTR)) {
+			union cvmx_ipd_ctl_status ipd_ctl_status;
+			ipd_ctl_status.u64 = cvmx_read_csr(CVMX_IPD_CTL_STATUS);
+			if (ipd_ctl_status.s.no_wptr)
+				no_wptr = 1;
+		}
+
+		/* Free the prefetched WQE */
+		if (ipd_ptr_count.s.wqev_cnt) {
+			union cvmx_ipd_wqe_ptr_valid ipd_wqe_ptr_valid;
+			ipd_wqe_ptr_valid.u64 =
+			    cvmx_read_csr(CVMX_IPD_WQE_PTR_VALID);
+			if (no_wptr)
+				cvmx_fpa_free(cvmx_phys_to_ptr
+					      ((uint64_t) ipd_wqe_ptr_valid.s.
+					       ptr << 7), CVMX_FPA_PACKET_POOL,
+					      0);
+			else
+				cvmx_fpa_free(cvmx_phys_to_ptr
+					      ((uint64_t) ipd_wqe_ptr_valid.s.
+					       ptr << 7), CVMX_FPA_WQE_POOL, 0);
+		}
+
+		/* Free all WQE in the fifo */
+		if (ipd_ptr_count.s.wqe_pcnt) {
+			int i;
+			union cvmx_ipd_pwp_ptr_fifo_ctl ipd_pwp_ptr_fifo_ctl;
+			ipd_pwp_ptr_fifo_ctl.u64 =
+			    cvmx_read_csr(CVMX_IPD_PWP_PTR_FIFO_CTL);
+			for (i = 0; i < ipd_ptr_count.s.wqe_pcnt; i++) {
+				ipd_pwp_ptr_fifo_ctl.s.cena = 0;
+				ipd_pwp_ptr_fifo_ctl.s.raddr =
+				    ipd_pwp_ptr_fifo_ctl.s.max_cnts +
+				    (ipd_pwp_ptr_fifo_ctl.s.wraddr +
+				     i) % ipd_pwp_ptr_fifo_ctl.s.max_cnts;
+				cvmx_write_csr(CVMX_IPD_PWP_PTR_FIFO_CTL,
+					       ipd_pwp_ptr_fifo_ctl.u64);
+				ipd_pwp_ptr_fifo_ctl.u64 =
+				    cvmx_read_csr(CVMX_IPD_PWP_PTR_FIFO_CTL);
+				if (no_wptr)
+					cvmx_fpa_free(cvmx_phys_to_ptr
+						      ((uint64_t)
+						       ipd_pwp_ptr_fifo_ctl.s.
+						       ptr << 7),
+						      CVMX_FPA_PACKET_POOL, 0);
+				else
+					cvmx_fpa_free(cvmx_phys_to_ptr
+						      ((uint64_t)
+						       ipd_pwp_ptr_fifo_ctl.s.
+						       ptr << 7),
+						      CVMX_FPA_WQE_POOL, 0);
+			}
+			ipd_pwp_ptr_fifo_ctl.s.cena = 1;
+			cvmx_write_csr(CVMX_IPD_PWP_PTR_FIFO_CTL,
+				       ipd_pwp_ptr_fifo_ctl.u64);
+		}
+
+		/* Free the prefetched packet */
+		if (ipd_ptr_count.s.pktv_cnt) {
+			union cvmx_ipd_pkt_ptr_valid ipd_pkt_ptr_valid;
+			ipd_pkt_ptr_valid.u64 =
+			    cvmx_read_csr(CVMX_IPD_PKT_PTR_VALID);
+			cvmx_fpa_free(cvmx_phys_to_ptr
+				      (ipd_pkt_ptr_valid.s.ptr << 7),
+				      CVMX_FPA_PACKET_POOL, 0);
+		}
+
+		/* Free the per port prefetched packets */
+		if (1) {
+			int i;
+			union cvmx_ipd_prc_port_ptr_fifo_ctl
+			    ipd_prc_port_ptr_fifo_ctl;
+			ipd_prc_port_ptr_fifo_ctl.u64 =
+			    cvmx_read_csr(CVMX_IPD_PRC_PORT_PTR_FIFO_CTL);
+
+			for (i = 0; i < ipd_prc_port_ptr_fifo_ctl.s.max_pkt;
+			     i++) {
+				ipd_prc_port_ptr_fifo_ctl.s.cena = 0;
+				ipd_prc_port_ptr_fifo_ctl.s.raddr =
+				    i % ipd_prc_port_ptr_fifo_ctl.s.max_pkt;
+				cvmx_write_csr(CVMX_IPD_PRC_PORT_PTR_FIFO_CTL,
+					       ipd_prc_port_ptr_fifo_ctl.u64);
+				ipd_prc_port_ptr_fifo_ctl.u64 =
+				    cvmx_read_csr
+				    (CVMX_IPD_PRC_PORT_PTR_FIFO_CTL);
+				cvmx_fpa_free(cvmx_phys_to_ptr
+					      ((uint64_t)
+					       ipd_prc_port_ptr_fifo_ctl.s.
+					       ptr << 7), CVMX_FPA_PACKET_POOL,
+					      0);
+			}
+			ipd_prc_port_ptr_fifo_ctl.s.cena = 1;
+			cvmx_write_csr(CVMX_IPD_PRC_PORT_PTR_FIFO_CTL,
+				       ipd_prc_port_ptr_fifo_ctl.u64);
+		}
+
+		/* Free all packets in the holding fifo */
+		if (ipd_ptr_count.s.pfif_cnt) {
+			int i;
+			union cvmx_ipd_prc_hold_ptr_fifo_ctl
+			    ipd_prc_hold_ptr_fifo_ctl;
+
+			ipd_prc_hold_ptr_fifo_ctl.u64 =
+			    cvmx_read_csr(CVMX_IPD_PRC_HOLD_PTR_FIFO_CTL);
+
+			for (i = 0; i < ipd_ptr_count.s.pfif_cnt; i++) {
+				ipd_prc_hold_ptr_fifo_ctl.s.cena = 0;
+				ipd_prc_hold_ptr_fifo_ctl.s.raddr =
+				    (ipd_prc_hold_ptr_fifo_ctl.s.praddr +
+				     i) % ipd_prc_hold_ptr_fifo_ctl.s.max_pkt;
+				cvmx_write_csr(CVMX_IPD_PRC_HOLD_PTR_FIFO_CTL,
+					       ipd_prc_hold_ptr_fifo_ctl.u64);
+				ipd_prc_hold_ptr_fifo_ctl.u64 =
+				    cvmx_read_csr
+				    (CVMX_IPD_PRC_HOLD_PTR_FIFO_CTL);
+				cvmx_fpa_free(cvmx_phys_to_ptr
+					      ((uint64_t)
+					       ipd_prc_hold_ptr_fifo_ctl.s.
+					       ptr << 7), CVMX_FPA_PACKET_POOL,
+					      0);
+			}
+			ipd_prc_hold_ptr_fifo_ctl.s.cena = 1;
+			cvmx_write_csr(CVMX_IPD_PRC_HOLD_PTR_FIFO_CTL,
+				       ipd_prc_hold_ptr_fifo_ctl.u64);
+		}
+
+		/* Free all packets in the fifo */
+		if (ipd_ptr_count.s.pkt_pcnt) {
+			int i;
+			union cvmx_ipd_pwp_ptr_fifo_ctl ipd_pwp_ptr_fifo_ctl;
+			ipd_pwp_ptr_fifo_ctl.u64 =
+			    cvmx_read_csr(CVMX_IPD_PWP_PTR_FIFO_CTL);
+
+			for (i = 0; i < ipd_ptr_count.s.pkt_pcnt; i++) {
+				ipd_pwp_ptr_fifo_ctl.s.cena = 0;
+				ipd_pwp_ptr_fifo_ctl.s.raddr =
+				    (ipd_pwp_ptr_fifo_ctl.s.praddr +
+				     i) % ipd_pwp_ptr_fifo_ctl.s.max_cnts;
+				cvmx_write_csr(CVMX_IPD_PWP_PTR_FIFO_CTL,
+					       ipd_pwp_ptr_fifo_ctl.u64);
+				ipd_pwp_ptr_fifo_ctl.u64 =
+				    cvmx_read_csr(CVMX_IPD_PWP_PTR_FIFO_CTL);
+				cvmx_fpa_free(cvmx_phys_to_ptr
+					      ((uint64_t) ipd_pwp_ptr_fifo_ctl.
+					       s.ptr << 7),
+					      CVMX_FPA_PACKET_POOL, 0);
+			}
+			ipd_pwp_ptr_fifo_ctl.s.cena = 1;
+			cvmx_write_csr(CVMX_IPD_PWP_PTR_FIFO_CTL,
+				       ipd_pwp_ptr_fifo_ctl.u64);
+		}
+
+		/* Reset the IPD to get all buffers out of it */
+		{
+			union cvmx_ipd_ctl_status ipd_ctl_status;
+			ipd_ctl_status.u64 = cvmx_read_csr(CVMX_IPD_CTL_STATUS);
+			ipd_ctl_status.s.reset = 1;
+			cvmx_write_csr(CVMX_IPD_CTL_STATUS, ipd_ctl_status.u64);
+		}
+
+		/* Reset the PIP */
+		{
+			union cvmx_pip_sft_rst pip_sft_rst;
+			pip_sft_rst.u64 = cvmx_read_csr(CVMX_PIP_SFT_RST);
+			pip_sft_rst.s.rst = 1;
+			cvmx_write_csr(CVMX_PIP_SFT_RST, pip_sft_rst.u64);
+		}
+	}
+}
+
+#endif /*  __CVMX_IPD_H__ */
diff --git a/drivers/staging/octeon/cvmx-mdio.h b/drivers/staging/octeon/cvmx-mdio.h
new file mode 100644
index 0000000..c987a75
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-mdio.h
@@ -0,0 +1,506 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ *
+ * Interface to the SMI/MDIO hardware, including support for both IEEE 802.3
+ * clause 22 and clause 45 operations.
+ *
+ */
+
+#ifndef __CVMX_MIO_H__
+#define __CVMX_MIO_H__
+
+#include "cvmx-smix-defs.h"
+
+/**
+ * PHY register 0 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_CONTROL 0
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t reset:1;
+		uint16_t loopback:1;
+		uint16_t speed_lsb:1;
+		uint16_t autoneg_enable:1;
+		uint16_t power_down:1;
+		uint16_t isolate:1;
+		uint16_t restart_autoneg:1;
+		uint16_t duplex:1;
+		uint16_t collision_test:1;
+		uint16_t speed_msb:1;
+		uint16_t unidirectional_enable:1;
+		uint16_t reserved_0_4:5;
+	} s;
+} cvmx_mdio_phy_reg_control_t;
+
+/**
+ * PHY register 1 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_STATUS 1
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t capable_100base_t4:1;
+		uint16_t capable_100base_x_full:1;
+		uint16_t capable_100base_x_half:1;
+		uint16_t capable_10_full:1;
+		uint16_t capable_10_half:1;
+		uint16_t capable_100base_t2_full:1;
+		uint16_t capable_100base_t2_half:1;
+		uint16_t capable_extended_status:1;
+		uint16_t capable_unidirectional:1;
+		uint16_t capable_mf_preamble_suppression:1;
+		uint16_t autoneg_complete:1;
+		uint16_t remote_fault:1;
+		uint16_t capable_autoneg:1;
+		uint16_t link_status:1;
+		uint16_t jabber_detect:1;
+		uint16_t capable_extended_registers:1;
+
+	} s;
+} cvmx_mdio_phy_reg_status_t;
+
+/**
+ * PHY register 2 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_ID1 2
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t oui_bits_3_18;
+	} s;
+} cvmx_mdio_phy_reg_id1_t;
+
+/**
+ * PHY register 3 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_ID2 3
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t oui_bits_19_24:6;
+		uint16_t model:6;
+		uint16_t revision:4;
+	} s;
+} cvmx_mdio_phy_reg_id2_t;
+
+/**
+ * PHY register 4 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_AUTONEG_ADVER 4
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t next_page:1;
+		uint16_t reserved_14:1;
+		uint16_t remote_fault:1;
+		uint16_t reserved_12:1;
+		uint16_t asymmetric_pause:1;
+		uint16_t pause:1;
+		uint16_t advert_100base_t4:1;
+		uint16_t advert_100base_tx_full:1;
+		uint16_t advert_100base_tx_half:1;
+		uint16_t advert_10base_tx_full:1;
+		uint16_t advert_10base_tx_half:1;
+		uint16_t selector:5;
+	} s;
+} cvmx_mdio_phy_reg_autoneg_adver_t;
+
+/**
+ * PHY register 5 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_LINK_PARTNER_ABILITY 5
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t next_page:1;
+		uint16_t ack:1;
+		uint16_t remote_fault:1;
+		uint16_t reserved_12:1;
+		uint16_t asymmetric_pause:1;
+		uint16_t pause:1;
+		uint16_t advert_100base_t4:1;
+		uint16_t advert_100base_tx_full:1;
+		uint16_t advert_100base_tx_half:1;
+		uint16_t advert_10base_tx_full:1;
+		uint16_t advert_10base_tx_half:1;
+		uint16_t selector:5;
+	} s;
+} cvmx_mdio_phy_reg_link_partner_ability_t;
+
+/**
+ * PHY register 6 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_AUTONEG_EXPANSION 6
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t reserved_5_15:11;
+		uint16_t parallel_detection_fault:1;
+		uint16_t link_partner_next_page_capable:1;
+		uint16_t local_next_page_capable:1;
+		uint16_t page_received:1;
+		uint16_t link_partner_autoneg_capable:1;
+
+	} s;
+} cvmx_mdio_phy_reg_autoneg_expansion_t;
+
+/**
+ * PHY register 9 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_CONTROL_1000 9
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t test_mode:3;
+		uint16_t manual_master_slave:1;
+		uint16_t master:1;
+		uint16_t port_type:1;
+		uint16_t advert_1000base_t_full:1;
+		uint16_t advert_1000base_t_half:1;
+		uint16_t reserved_0_7:8;
+	} s;
+} cvmx_mdio_phy_reg_control_1000_t;
+
+/**
+ * PHY register 10 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_STATUS_1000 10
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t master_slave_fault:1;
+		uint16_t is_master:1;
+		uint16_t local_receiver_ok:1;
+		uint16_t remote_receiver_ok:1;
+		uint16_t remote_capable_1000base_t_full:1;
+		uint16_t remote_capable_1000base_t_half:1;
+		uint16_t reserved_8_9:2;
+		uint16_t idle_error_count:8;
+	} s;
+} cvmx_mdio_phy_reg_status_1000_t;
+
+/**
+ * PHY register 15 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_EXTENDED_STATUS 15
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t capable_1000base_x_full:1;
+		uint16_t capable_1000base_x_half:1;
+		uint16_t capable_1000base_t_full:1;
+		uint16_t capable_1000base_t_half:1;
+		uint16_t reserved_0_11:12;
+	} s;
+} cvmx_mdio_phy_reg_extended_status_t;
+
+/**
+ * PHY register 13 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_MMD_CONTROL 13
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t function:2;
+		uint16_t reserved_5_13:9;
+		uint16_t devad:5;
+	} s;
+} cvmx_mdio_phy_reg_mmd_control_t;
+
+/**
+ * PHY register 14 from the 802.3 spec
+ */
+#define CVMX_MDIO_PHY_REG_MMD_ADDRESS_DATA 14
+typedef union {
+	uint16_t u16;
+	struct {
+		uint16_t address_data:16;
+	} s;
+} cvmx_mdio_phy_reg_mmd_address_data_t;
+
+/* Operating request encodings. */
+#define MDIO_CLAUSE_22_WRITE    0
+#define MDIO_CLAUSE_22_READ     1
+
+#define MDIO_CLAUSE_45_ADDRESS  0
+#define MDIO_CLAUSE_45_WRITE    1
+#define MDIO_CLAUSE_45_READ_INC 2
+#define MDIO_CLAUSE_45_READ     3
+
+/* MMD identifiers, mostly for accessing devices withing XENPAK modules. */
+#define CVMX_MMD_DEVICE_PMA_PMD      1
+#define CVMX_MMD_DEVICE_WIS          2
+#define CVMX_MMD_DEVICE_PCS          3
+#define CVMX_MMD_DEVICE_PHY_XS       4
+#define CVMX_MMD_DEVICE_DTS_XS       5
+#define CVMX_MMD_DEVICE_TC           6
+#define CVMX_MMD_DEVICE_CL22_EXT     29
+#define CVMX_MMD_DEVICE_VENDOR_1     30
+#define CVMX_MMD_DEVICE_VENDOR_2     31
+
+/* Helper function to put MDIO interface into clause 45 mode */
+static inline void __cvmx_mdio_set_clause45_mode(int bus_id)
+{
+	union cvmx_smix_clk smi_clk;
+	/* Put bus into clause 45 mode */
+	smi_clk.u64 = cvmx_read_csr(CVMX_SMIX_CLK(bus_id));
+	smi_clk.s.mode = 1;
+	smi_clk.s.preamble = 1;
+	cvmx_write_csr(CVMX_SMIX_CLK(bus_id), smi_clk.u64);
+}
+
+/* Helper function to put MDIO interface into clause 22 mode */
+static inline void __cvmx_mdio_set_clause22_mode(int bus_id)
+{
+	union cvmx_smix_clk smi_clk;
+	/* Put bus into clause 22 mode */
+	smi_clk.u64 = cvmx_read_csr(CVMX_SMIX_CLK(bus_id));
+	smi_clk.s.mode = 0;
+	cvmx_write_csr(CVMX_SMIX_CLK(bus_id), smi_clk.u64);
+}
+
+/**
+ * Perform an MII read. This function is used to read PHY
+ * registers controlling auto negotiation.
+ *
+ * @bus_id:   MDIO bus number. Zero on most chips, but some chips (ex CN56XX)
+ *                 support multiple busses.
+ * @phy_id:   The MII phy id
+ * @location: Register location to read
+ *
+ * Returns Result from the read or -1 on failure
+ */
+static inline int cvmx_mdio_read(int bus_id, int phy_id, int location)
+{
+	union cvmx_smix_cmd smi_cmd;
+	union cvmx_smix_rd_dat smi_rd;
+	int timeout = 1000;
+
+	if (octeon_has_feature(OCTEON_FEATURE_MDIO_CLAUSE_45))
+		__cvmx_mdio_set_clause22_mode(bus_id);
+
+	smi_cmd.u64 = 0;
+	smi_cmd.s.phy_op = MDIO_CLAUSE_22_READ;
+	smi_cmd.s.phy_adr = phy_id;
+	smi_cmd.s.reg_adr = location;
+	cvmx_write_csr(CVMX_SMIX_CMD(bus_id), smi_cmd.u64);
+
+	do {
+		cvmx_wait(1000);
+		smi_rd.u64 = cvmx_read_csr(CVMX_SMIX_RD_DAT(bus_id));
+	} while (smi_rd.s.pending && timeout--);
+
+	if (smi_rd.s.val)
+		return smi_rd.s.dat;
+	else
+		return -1;
+}
+
+/**
+ * Perform an MII write. This function is used to write PHY
+ * registers controlling auto negotiation.
+ *
+ * @bus_id:   MDIO bus number. Zero on most chips, but some chips (ex CN56XX)
+ *                 support multiple busses.
+ * @phy_id:   The MII phy id
+ * @location: Register location to write
+ * @val:      Value to write
+ *
+ * Returns -1 on error
+ *         0 on success
+ */
+static inline int cvmx_mdio_write(int bus_id, int phy_id, int location, int val)
+{
+	union cvmx_smix_cmd smi_cmd;
+	union cvmx_smix_wr_dat smi_wr;
+	int timeout = 1000;
+
+	if (octeon_has_feature(OCTEON_FEATURE_MDIO_CLAUSE_45))
+		__cvmx_mdio_set_clause22_mode(bus_id);
+
+	smi_wr.u64 = 0;
+	smi_wr.s.dat = val;
+	cvmx_write_csr(CVMX_SMIX_WR_DAT(bus_id), smi_wr.u64);
+
+	smi_cmd.u64 = 0;
+	smi_cmd.s.phy_op = MDIO_CLAUSE_22_WRITE;
+	smi_cmd.s.phy_adr = phy_id;
+	smi_cmd.s.reg_adr = location;
+	cvmx_write_csr(CVMX_SMIX_CMD(bus_id), smi_cmd.u64);
+
+	do {
+		cvmx_wait(1000);
+		smi_wr.u64 = cvmx_read_csr(CVMX_SMIX_WR_DAT(bus_id));
+	} while (smi_wr.s.pending && --timeout);
+	if (timeout <= 0)
+		return -1;
+
+	return 0;
+}
+
+/**
+ * Perform an IEEE 802.3 clause 45 MII read. This function is used to
+ * read PHY registers controlling auto negotiation.
+ *
+ * @bus_id:   MDIO bus number. Zero on most chips, but some chips (ex CN56XX)
+ *                 support multiple busses.
+ * @phy_id:   The MII phy id
+ * @device:   MDIO Managable Device (MMD) id
+ * @location: Register location to read
+ *
+ * Returns Result from the read or -1 on failure
+ */
+
+static inline int cvmx_mdio_45_read(int bus_id, int phy_id, int device,
+				    int location)
+{
+	union cvmx_smix_cmd smi_cmd;
+	union cvmx_smix_rd_dat smi_rd;
+	union cvmx_smix_wr_dat smi_wr;
+	int timeout = 1000;
+
+	if (!octeon_has_feature(OCTEON_FEATURE_MDIO_CLAUSE_45))
+		return -1;
+
+	__cvmx_mdio_set_clause45_mode(bus_id);
+
+	smi_wr.u64 = 0;
+	smi_wr.s.dat = location;
+	cvmx_write_csr(CVMX_SMIX_WR_DAT(bus_id), smi_wr.u64);
+
+	smi_cmd.u64 = 0;
+	smi_cmd.s.phy_op = MDIO_CLAUSE_45_ADDRESS;
+	smi_cmd.s.phy_adr = phy_id;
+	smi_cmd.s.reg_adr = device;
+	cvmx_write_csr(CVMX_SMIX_CMD(bus_id), smi_cmd.u64);
+
+	do {
+		cvmx_wait(1000);
+		smi_wr.u64 = cvmx_read_csr(CVMX_SMIX_WR_DAT(bus_id));
+	} while (smi_wr.s.pending && --timeout);
+	if (timeout <= 0) {
+		cvmx_dprintf("cvmx_mdio_45_read: bus_id %d phy_id %2d "
+			     "device %2d register %2d   TIME OUT(address)\n",
+		     bus_id, phy_id, device, location);
+		return -1;
+	}
+
+	smi_cmd.u64 = 0;
+	smi_cmd.s.phy_op = MDIO_CLAUSE_45_READ;
+	smi_cmd.s.phy_adr = phy_id;
+	smi_cmd.s.reg_adr = device;
+	cvmx_write_csr(CVMX_SMIX_CMD(bus_id), smi_cmd.u64);
+
+	do {
+		cvmx_wait(1000);
+		smi_rd.u64 = cvmx_read_csr(CVMX_SMIX_RD_DAT(bus_id));
+	} while (smi_rd.s.pending && timeout--);
+
+	if (timeout <= 0) {
+		cvmx_dprintf("cvmx_mdio_45_read: bus_id %d phy_id %2d "
+			     "device %2d register %2d   TIME OUT(data)\n",
+		     bus_id, phy_id, device, location);
+		return -1;
+	}
+
+	if (smi_rd.s.val)
+		return smi_rd.s.dat;
+	else {
+		cvmx_dprintf("cvmx_mdio_45_read: bus_id %d phy_id %2d "
+			     "device %2d register %2d   INVALID READ\n",
+		     bus_id, phy_id, device, location);
+		return -1;
+	}
+}
+
+/**
+ * Perform an IEEE 802.3 clause 45 MII write. This function is used to
+ * write PHY registers controlling auto negotiation.
+ *
+ * @bus_id:   MDIO bus number. Zero on most chips, but some chips (ex CN56XX)
+ *                 support multiple busses.
+ * @phy_id:   The MII phy id
+ * @device:   MDIO Managable Device (MMD) id
+ * @location: Register location to write
+ * @val:      Value to write
+ *
+ * Returns -1 on error
+ *         0 on success
+ */
+static inline int cvmx_mdio_45_write(int bus_id, int phy_id, int device,
+				     int location, int val)
+{
+	union cvmx_smix_cmd smi_cmd;
+	union cvmx_smix_wr_dat smi_wr;
+	int timeout = 1000;
+
+	if (!octeon_has_feature(OCTEON_FEATURE_MDIO_CLAUSE_45))
+		return -1;
+
+	__cvmx_mdio_set_clause45_mode(bus_id);
+
+	smi_wr.u64 = 0;
+	smi_wr.s.dat = location;
+	cvmx_write_csr(CVMX_SMIX_WR_DAT(bus_id), smi_wr.u64);
+
+	smi_cmd.u64 = 0;
+	smi_cmd.s.phy_op = MDIO_CLAUSE_45_ADDRESS;
+	smi_cmd.s.phy_adr = phy_id;
+	smi_cmd.s.reg_adr = device;
+	cvmx_write_csr(CVMX_SMIX_CMD(bus_id), smi_cmd.u64);
+
+	do {
+		cvmx_wait(1000);
+		smi_wr.u64 = cvmx_read_csr(CVMX_SMIX_WR_DAT(bus_id));
+	} while (smi_wr.s.pending && --timeout);
+	if (timeout <= 0)
+		return -1;
+
+	smi_wr.u64 = 0;
+	smi_wr.s.dat = val;
+	cvmx_write_csr(CVMX_SMIX_WR_DAT(bus_id), smi_wr.u64);
+
+	smi_cmd.u64 = 0;
+	smi_cmd.s.phy_op = MDIO_CLAUSE_45_WRITE;
+	smi_cmd.s.phy_adr = phy_id;
+	smi_cmd.s.reg_adr = device;
+	cvmx_write_csr(CVMX_SMIX_CMD(bus_id), smi_cmd.u64);
+
+	do {
+		cvmx_wait(1000);
+		smi_wr.u64 = cvmx_read_csr(CVMX_SMIX_WR_DAT(bus_id));
+	} while (smi_wr.s.pending && --timeout);
+	if (timeout <= 0)
+		return -1;
+
+	return 0;
+}
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-packet.h b/drivers/staging/octeon/cvmx-packet.h
new file mode 100644
index 0000000..62ffe78a
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-packet.h
@@ -0,0 +1,65 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ *
+ * Packet buffer defines.
+ */
+
+#ifndef __CVMX_PACKET_H__
+#define __CVMX_PACKET_H__
+
+/**
+ * This structure defines a buffer pointer on Octeon
+ */
+union cvmx_buf_ptr {
+	void *ptr;
+	uint64_t u64;
+	struct {
+		/*
+		 * if set, invert the "free" pick of the overall
+		 * packet. HW always sets this bit to 0 on inbound
+		 * packet
+		 */
+		uint64_t i:1;
+		/*
+		 * Indicates the amount to back up to get to the
+		 * buffer start in cache lines. In most cases this is
+		 * less than one complete cache line, so the value is
+		 * zero.
+		 */
+		uint64_t back:4;
+		/* The pool that the buffer came from / goes to */
+		uint64_t pool:3;
+		/* The size of the segment pointed to by addr (in bytes) */
+		uint64_t size:16;
+		/* Pointer to the first byte of the data, NOT buffer */
+		uint64_t addr:40;
+	} s;
+};
+
+#endif /*  __CVMX_PACKET_H__ */
diff --git a/drivers/staging/octeon/cvmx-pcsx-defs.h b/drivers/staging/octeon/cvmx-pcsx-defs.h
new file mode 100644
index 0000000..d45952d
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-pcsx-defs.h
@@ -0,0 +1,370 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_PCSX_DEFS_H__
+#define __CVMX_PCSX_DEFS_H__
+
+#define CVMX_PCSX_ANX_ADV_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001010ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_ANX_EXT_ST_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001028ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_ANX_LP_ABIL_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001018ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_ANX_RESULTS_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001020ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_INTX_EN_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001088ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_INTX_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001080ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_LINKX_TIMER_COUNT_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001040ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_LOG_ANLX_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001090ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_MISCX_CTL_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001078ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_MRX_CONTROL_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001000ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_MRX_STATUS_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001008ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_RXX_STATES_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001058ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_RXX_SYNC_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001050ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_SGMX_AN_ADV_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001068ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_SGMX_LP_ADV_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001070ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_TXX_STATES_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001060ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSX_TX_RXX_POLARITY_REG(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0001048ull + (((offset) & 3) * 1024) + (((block_id) & 1) * 0x8000000ull))
+
+union cvmx_pcsx_anx_adv_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_anx_adv_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t np:1;
+		uint64_t reserved_14_14:1;
+		uint64_t rem_flt:2;
+		uint64_t reserved_9_11:3;
+		uint64_t pause:2;
+		uint64_t hfd:1;
+		uint64_t fd:1;
+		uint64_t reserved_0_4:5;
+	} s;
+	struct cvmx_pcsx_anx_adv_reg_s cn52xx;
+	struct cvmx_pcsx_anx_adv_reg_s cn52xxp1;
+	struct cvmx_pcsx_anx_adv_reg_s cn56xx;
+	struct cvmx_pcsx_anx_adv_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_anx_ext_st_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_anx_ext_st_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t thou_xfd:1;
+		uint64_t thou_xhd:1;
+		uint64_t thou_tfd:1;
+		uint64_t thou_thd:1;
+		uint64_t reserved_0_11:12;
+	} s;
+	struct cvmx_pcsx_anx_ext_st_reg_s cn52xx;
+	struct cvmx_pcsx_anx_ext_st_reg_s cn52xxp1;
+	struct cvmx_pcsx_anx_ext_st_reg_s cn56xx;
+	struct cvmx_pcsx_anx_ext_st_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_anx_lp_abil_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_anx_lp_abil_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t np:1;
+		uint64_t ack:1;
+		uint64_t rem_flt:2;
+		uint64_t reserved_9_11:3;
+		uint64_t pause:2;
+		uint64_t hfd:1;
+		uint64_t fd:1;
+		uint64_t reserved_0_4:5;
+	} s;
+	struct cvmx_pcsx_anx_lp_abil_reg_s cn52xx;
+	struct cvmx_pcsx_anx_lp_abil_reg_s cn52xxp1;
+	struct cvmx_pcsx_anx_lp_abil_reg_s cn56xx;
+	struct cvmx_pcsx_anx_lp_abil_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_anx_results_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_anx_results_reg_s {
+		uint64_t reserved_7_63:57;
+		uint64_t pause:2;
+		uint64_t spd:2;
+		uint64_t an_cpt:1;
+		uint64_t dup:1;
+		uint64_t link_ok:1;
+	} s;
+	struct cvmx_pcsx_anx_results_reg_s cn52xx;
+	struct cvmx_pcsx_anx_results_reg_s cn52xxp1;
+	struct cvmx_pcsx_anx_results_reg_s cn56xx;
+	struct cvmx_pcsx_anx_results_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_intx_en_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_intx_en_reg_s {
+		uint64_t reserved_12_63:52;
+		uint64_t dup:1;
+		uint64_t sync_bad_en:1;
+		uint64_t an_bad_en:1;
+		uint64_t rxlock_en:1;
+		uint64_t rxbad_en:1;
+		uint64_t rxerr_en:1;
+		uint64_t txbad_en:1;
+		uint64_t txfifo_en:1;
+		uint64_t txfifu_en:1;
+		uint64_t an_err_en:1;
+		uint64_t xmit_en:1;
+		uint64_t lnkspd_en:1;
+	} s;
+	struct cvmx_pcsx_intx_en_reg_s cn52xx;
+	struct cvmx_pcsx_intx_en_reg_s cn52xxp1;
+	struct cvmx_pcsx_intx_en_reg_s cn56xx;
+	struct cvmx_pcsx_intx_en_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_intx_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_intx_reg_s {
+		uint64_t reserved_12_63:52;
+		uint64_t dup:1;
+		uint64_t sync_bad:1;
+		uint64_t an_bad:1;
+		uint64_t rxlock:1;
+		uint64_t rxbad:1;
+		uint64_t rxerr:1;
+		uint64_t txbad:1;
+		uint64_t txfifo:1;
+		uint64_t txfifu:1;
+		uint64_t an_err:1;
+		uint64_t xmit:1;
+		uint64_t lnkspd:1;
+	} s;
+	struct cvmx_pcsx_intx_reg_s cn52xx;
+	struct cvmx_pcsx_intx_reg_s cn52xxp1;
+	struct cvmx_pcsx_intx_reg_s cn56xx;
+	struct cvmx_pcsx_intx_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_linkx_timer_count_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_linkx_timer_count_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t count:16;
+	} s;
+	struct cvmx_pcsx_linkx_timer_count_reg_s cn52xx;
+	struct cvmx_pcsx_linkx_timer_count_reg_s cn52xxp1;
+	struct cvmx_pcsx_linkx_timer_count_reg_s cn56xx;
+	struct cvmx_pcsx_linkx_timer_count_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_log_anlx_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_log_anlx_reg_s {
+		uint64_t reserved_4_63:60;
+		uint64_t lafifovfl:1;
+		uint64_t la_en:1;
+		uint64_t pkt_sz:2;
+	} s;
+	struct cvmx_pcsx_log_anlx_reg_s cn52xx;
+	struct cvmx_pcsx_log_anlx_reg_s cn52xxp1;
+	struct cvmx_pcsx_log_anlx_reg_s cn56xx;
+	struct cvmx_pcsx_log_anlx_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_miscx_ctl_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_miscx_ctl_reg_s {
+		uint64_t reserved_13_63:51;
+		uint64_t sgmii:1;
+		uint64_t gmxeno:1;
+		uint64_t loopbck2:1;
+		uint64_t mac_phy:1;
+		uint64_t mode:1;
+		uint64_t an_ovrd:1;
+		uint64_t samp_pt:7;
+	} s;
+	struct cvmx_pcsx_miscx_ctl_reg_s cn52xx;
+	struct cvmx_pcsx_miscx_ctl_reg_s cn52xxp1;
+	struct cvmx_pcsx_miscx_ctl_reg_s cn56xx;
+	struct cvmx_pcsx_miscx_ctl_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_mrx_control_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_mrx_control_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t reset:1;
+		uint64_t loopbck1:1;
+		uint64_t spdlsb:1;
+		uint64_t an_en:1;
+		uint64_t pwr_dn:1;
+		uint64_t reserved_10_10:1;
+		uint64_t rst_an:1;
+		uint64_t dup:1;
+		uint64_t coltst:1;
+		uint64_t spdmsb:1;
+		uint64_t uni:1;
+		uint64_t reserved_0_4:5;
+	} s;
+	struct cvmx_pcsx_mrx_control_reg_s cn52xx;
+	struct cvmx_pcsx_mrx_control_reg_s cn52xxp1;
+	struct cvmx_pcsx_mrx_control_reg_s cn56xx;
+	struct cvmx_pcsx_mrx_control_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_mrx_status_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_mrx_status_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t hun_t4:1;
+		uint64_t hun_xfd:1;
+		uint64_t hun_xhd:1;
+		uint64_t ten_fd:1;
+		uint64_t ten_hd:1;
+		uint64_t hun_t2fd:1;
+		uint64_t hun_t2hd:1;
+		uint64_t ext_st:1;
+		uint64_t reserved_7_7:1;
+		uint64_t prb_sup:1;
+		uint64_t an_cpt:1;
+		uint64_t rm_flt:1;
+		uint64_t an_abil:1;
+		uint64_t lnk_st:1;
+		uint64_t reserved_1_1:1;
+		uint64_t extnd:1;
+	} s;
+	struct cvmx_pcsx_mrx_status_reg_s cn52xx;
+	struct cvmx_pcsx_mrx_status_reg_s cn52xxp1;
+	struct cvmx_pcsx_mrx_status_reg_s cn56xx;
+	struct cvmx_pcsx_mrx_status_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_rxx_states_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_rxx_states_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t rx_bad:1;
+		uint64_t rx_st:5;
+		uint64_t sync_bad:1;
+		uint64_t sync:4;
+		uint64_t an_bad:1;
+		uint64_t an_st:4;
+	} s;
+	struct cvmx_pcsx_rxx_states_reg_s cn52xx;
+	struct cvmx_pcsx_rxx_states_reg_s cn52xxp1;
+	struct cvmx_pcsx_rxx_states_reg_s cn56xx;
+	struct cvmx_pcsx_rxx_states_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_rxx_sync_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_rxx_sync_reg_s {
+		uint64_t reserved_2_63:62;
+		uint64_t sync:1;
+		uint64_t bit_lock:1;
+	} s;
+	struct cvmx_pcsx_rxx_sync_reg_s cn52xx;
+	struct cvmx_pcsx_rxx_sync_reg_s cn52xxp1;
+	struct cvmx_pcsx_rxx_sync_reg_s cn56xx;
+	struct cvmx_pcsx_rxx_sync_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_sgmx_an_adv_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_sgmx_an_adv_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t link:1;
+		uint64_t ack:1;
+		uint64_t reserved_13_13:1;
+		uint64_t dup:1;
+		uint64_t speed:2;
+		uint64_t reserved_1_9:9;
+		uint64_t one:1;
+	} s;
+	struct cvmx_pcsx_sgmx_an_adv_reg_s cn52xx;
+	struct cvmx_pcsx_sgmx_an_adv_reg_s cn52xxp1;
+	struct cvmx_pcsx_sgmx_an_adv_reg_s cn56xx;
+	struct cvmx_pcsx_sgmx_an_adv_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_sgmx_lp_adv_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_sgmx_lp_adv_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t link:1;
+		uint64_t reserved_13_14:2;
+		uint64_t dup:1;
+		uint64_t speed:2;
+		uint64_t reserved_1_9:9;
+		uint64_t one:1;
+	} s;
+	struct cvmx_pcsx_sgmx_lp_adv_reg_s cn52xx;
+	struct cvmx_pcsx_sgmx_lp_adv_reg_s cn52xxp1;
+	struct cvmx_pcsx_sgmx_lp_adv_reg_s cn56xx;
+	struct cvmx_pcsx_sgmx_lp_adv_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_txx_states_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_txx_states_reg_s {
+		uint64_t reserved_7_63:57;
+		uint64_t xmit:2;
+		uint64_t tx_bad:1;
+		uint64_t ord_st:4;
+	} s;
+	struct cvmx_pcsx_txx_states_reg_s cn52xx;
+	struct cvmx_pcsx_txx_states_reg_s cn52xxp1;
+	struct cvmx_pcsx_txx_states_reg_s cn56xx;
+	struct cvmx_pcsx_txx_states_reg_s cn56xxp1;
+};
+
+union cvmx_pcsx_tx_rxx_polarity_reg {
+	uint64_t u64;
+	struct cvmx_pcsx_tx_rxx_polarity_reg_s {
+		uint64_t reserved_4_63:60;
+		uint64_t rxovrd:1;
+		uint64_t autorxpl:1;
+		uint64_t rxplrt:1;
+		uint64_t txplrt:1;
+	} s;
+	struct cvmx_pcsx_tx_rxx_polarity_reg_s cn52xx;
+	struct cvmx_pcsx_tx_rxx_polarity_reg_s cn52xxp1;
+	struct cvmx_pcsx_tx_rxx_polarity_reg_s cn56xx;
+	struct cvmx_pcsx_tx_rxx_polarity_reg_s cn56xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-pcsxx-defs.h b/drivers/staging/octeon/cvmx-pcsxx-defs.h
new file mode 100644
index 0000000..55d120f
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-pcsxx-defs.h
@@ -0,0 +1,316 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_PCSXX_DEFS_H__
+#define __CVMX_PCSXX_DEFS_H__
+
+#define CVMX_PCSXX_10GBX_STATUS_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000828ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_BIST_STATUS_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000870ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_BIT_LOCK_STATUS_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000850ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_CONTROL1_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000800ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_CONTROL2_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000818ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_INT_EN_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000860ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_INT_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000858ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_LOG_ANL_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000868ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_MISC_CTL_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000848ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_RX_SYNC_STATES_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000838ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_SPD_ABIL_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000810ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_STATUS1_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000808ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_STATUS2_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000820ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_TX_RX_POLARITY_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000840ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_PCSXX_TX_RX_STATES_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800B0000830ull + (((block_id) & 1) * 0x8000000ull))
+
+union cvmx_pcsxx_10gbx_status_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_10gbx_status_reg_s {
+		uint64_t reserved_13_63:51;
+		uint64_t alignd:1;
+		uint64_t pattst:1;
+		uint64_t reserved_4_10:7;
+		uint64_t l3sync:1;
+		uint64_t l2sync:1;
+		uint64_t l1sync:1;
+		uint64_t l0sync:1;
+	} s;
+	struct cvmx_pcsxx_10gbx_status_reg_s cn52xx;
+	struct cvmx_pcsxx_10gbx_status_reg_s cn52xxp1;
+	struct cvmx_pcsxx_10gbx_status_reg_s cn56xx;
+	struct cvmx_pcsxx_10gbx_status_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_bist_status_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_bist_status_reg_s {
+		uint64_t reserved_1_63:63;
+		uint64_t bist_status:1;
+	} s;
+	struct cvmx_pcsxx_bist_status_reg_s cn52xx;
+	struct cvmx_pcsxx_bist_status_reg_s cn52xxp1;
+	struct cvmx_pcsxx_bist_status_reg_s cn56xx;
+	struct cvmx_pcsxx_bist_status_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_bit_lock_status_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_bit_lock_status_reg_s {
+		uint64_t reserved_4_63:60;
+		uint64_t bitlck3:1;
+		uint64_t bitlck2:1;
+		uint64_t bitlck1:1;
+		uint64_t bitlck0:1;
+	} s;
+	struct cvmx_pcsxx_bit_lock_status_reg_s cn52xx;
+	struct cvmx_pcsxx_bit_lock_status_reg_s cn52xxp1;
+	struct cvmx_pcsxx_bit_lock_status_reg_s cn56xx;
+	struct cvmx_pcsxx_bit_lock_status_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_control1_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_control1_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t reset:1;
+		uint64_t loopbck1:1;
+		uint64_t spdsel1:1;
+		uint64_t reserved_12_12:1;
+		uint64_t lo_pwr:1;
+		uint64_t reserved_7_10:4;
+		uint64_t spdsel0:1;
+		uint64_t spd:4;
+		uint64_t reserved_0_1:2;
+	} s;
+	struct cvmx_pcsxx_control1_reg_s cn52xx;
+	struct cvmx_pcsxx_control1_reg_s cn52xxp1;
+	struct cvmx_pcsxx_control1_reg_s cn56xx;
+	struct cvmx_pcsxx_control1_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_control2_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_control2_reg_s {
+		uint64_t reserved_2_63:62;
+		uint64_t type:2;
+	} s;
+	struct cvmx_pcsxx_control2_reg_s cn52xx;
+	struct cvmx_pcsxx_control2_reg_s cn52xxp1;
+	struct cvmx_pcsxx_control2_reg_s cn56xx;
+	struct cvmx_pcsxx_control2_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_int_en_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_int_en_reg_s {
+		uint64_t reserved_6_63:58;
+		uint64_t algnlos_en:1;
+		uint64_t synlos_en:1;
+		uint64_t bitlckls_en:1;
+		uint64_t rxsynbad_en:1;
+		uint64_t rxbad_en:1;
+		uint64_t txflt_en:1;
+	} s;
+	struct cvmx_pcsxx_int_en_reg_s cn52xx;
+	struct cvmx_pcsxx_int_en_reg_s cn52xxp1;
+	struct cvmx_pcsxx_int_en_reg_s cn56xx;
+	struct cvmx_pcsxx_int_en_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_int_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_int_reg_s {
+		uint64_t reserved_6_63:58;
+		uint64_t algnlos:1;
+		uint64_t synlos:1;
+		uint64_t bitlckls:1;
+		uint64_t rxsynbad:1;
+		uint64_t rxbad:1;
+		uint64_t txflt:1;
+	} s;
+	struct cvmx_pcsxx_int_reg_s cn52xx;
+	struct cvmx_pcsxx_int_reg_s cn52xxp1;
+	struct cvmx_pcsxx_int_reg_s cn56xx;
+	struct cvmx_pcsxx_int_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_log_anl_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_log_anl_reg_s {
+		uint64_t reserved_7_63:57;
+		uint64_t enc_mode:1;
+		uint64_t drop_ln:2;
+		uint64_t lafifovfl:1;
+		uint64_t la_en:1;
+		uint64_t pkt_sz:2;
+	} s;
+	struct cvmx_pcsxx_log_anl_reg_s cn52xx;
+	struct cvmx_pcsxx_log_anl_reg_s cn52xxp1;
+	struct cvmx_pcsxx_log_anl_reg_s cn56xx;
+	struct cvmx_pcsxx_log_anl_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_misc_ctl_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_misc_ctl_reg_s {
+		uint64_t reserved_4_63:60;
+		uint64_t tx_swap:1;
+		uint64_t rx_swap:1;
+		uint64_t xaui:1;
+		uint64_t gmxeno:1;
+	} s;
+	struct cvmx_pcsxx_misc_ctl_reg_s cn52xx;
+	struct cvmx_pcsxx_misc_ctl_reg_s cn52xxp1;
+	struct cvmx_pcsxx_misc_ctl_reg_s cn56xx;
+	struct cvmx_pcsxx_misc_ctl_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_rx_sync_states_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_rx_sync_states_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t sync3st:4;
+		uint64_t sync2st:4;
+		uint64_t sync1st:4;
+		uint64_t sync0st:4;
+	} s;
+	struct cvmx_pcsxx_rx_sync_states_reg_s cn52xx;
+	struct cvmx_pcsxx_rx_sync_states_reg_s cn52xxp1;
+	struct cvmx_pcsxx_rx_sync_states_reg_s cn56xx;
+	struct cvmx_pcsxx_rx_sync_states_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_spd_abil_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_spd_abil_reg_s {
+		uint64_t reserved_2_63:62;
+		uint64_t tenpasst:1;
+		uint64_t tengb:1;
+	} s;
+	struct cvmx_pcsxx_spd_abil_reg_s cn52xx;
+	struct cvmx_pcsxx_spd_abil_reg_s cn52xxp1;
+	struct cvmx_pcsxx_spd_abil_reg_s cn56xx;
+	struct cvmx_pcsxx_spd_abil_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_status1_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_status1_reg_s {
+		uint64_t reserved_8_63:56;
+		uint64_t flt:1;
+		uint64_t reserved_3_6:4;
+		uint64_t rcv_lnk:1;
+		uint64_t lpable:1;
+		uint64_t reserved_0_0:1;
+	} s;
+	struct cvmx_pcsxx_status1_reg_s cn52xx;
+	struct cvmx_pcsxx_status1_reg_s cn52xxp1;
+	struct cvmx_pcsxx_status1_reg_s cn56xx;
+	struct cvmx_pcsxx_status1_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_status2_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_status2_reg_s {
+		uint64_t reserved_16_63:48;
+		uint64_t dev:2;
+		uint64_t reserved_12_13:2;
+		uint64_t xmtflt:1;
+		uint64_t rcvflt:1;
+		uint64_t reserved_3_9:7;
+		uint64_t tengb_w:1;
+		uint64_t tengb_x:1;
+		uint64_t tengb_r:1;
+	} s;
+	struct cvmx_pcsxx_status2_reg_s cn52xx;
+	struct cvmx_pcsxx_status2_reg_s cn52xxp1;
+	struct cvmx_pcsxx_status2_reg_s cn56xx;
+	struct cvmx_pcsxx_status2_reg_s cn56xxp1;
+};
+
+union cvmx_pcsxx_tx_rx_polarity_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_tx_rx_polarity_reg_s {
+		uint64_t reserved_10_63:54;
+		uint64_t xor_rxplrt:4;
+		uint64_t xor_txplrt:4;
+		uint64_t rxplrt:1;
+		uint64_t txplrt:1;
+	} s;
+	struct cvmx_pcsxx_tx_rx_polarity_reg_s cn52xx;
+	struct cvmx_pcsxx_tx_rx_polarity_reg_cn52xxp1 {
+		uint64_t reserved_2_63:62;
+		uint64_t rxplrt:1;
+		uint64_t txplrt:1;
+	} cn52xxp1;
+	struct cvmx_pcsxx_tx_rx_polarity_reg_s cn56xx;
+	struct cvmx_pcsxx_tx_rx_polarity_reg_cn52xxp1 cn56xxp1;
+};
+
+union cvmx_pcsxx_tx_rx_states_reg {
+	uint64_t u64;
+	struct cvmx_pcsxx_tx_rx_states_reg_s {
+		uint64_t reserved_14_63:50;
+		uint64_t term_err:1;
+		uint64_t syn3bad:1;
+		uint64_t syn2bad:1;
+		uint64_t syn1bad:1;
+		uint64_t syn0bad:1;
+		uint64_t rxbad:1;
+		uint64_t algn_st:3;
+		uint64_t rx_st:2;
+		uint64_t tx_st:3;
+	} s;
+	struct cvmx_pcsxx_tx_rx_states_reg_s cn52xx;
+	struct cvmx_pcsxx_tx_rx_states_reg_cn52xxp1 {
+		uint64_t reserved_13_63:51;
+		uint64_t syn3bad:1;
+		uint64_t syn2bad:1;
+		uint64_t syn1bad:1;
+		uint64_t syn0bad:1;
+		uint64_t rxbad:1;
+		uint64_t algn_st:3;
+		uint64_t rx_st:2;
+		uint64_t tx_st:3;
+	} cn52xxp1;
+	struct cvmx_pcsxx_tx_rx_states_reg_s cn56xx;
+	struct cvmx_pcsxx_tx_rx_states_reg_cn52xxp1 cn56xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-pip-defs.h b/drivers/staging/octeon/cvmx-pip-defs.h
new file mode 100644
index 0000000..5a36910
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-pip-defs.h
@@ -0,0 +1,1267 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_PIP_DEFS_H__
+#define __CVMX_PIP_DEFS_H__
+
+/*
+ * Enumeration representing the amount of packet processing
+ * and validation performed by the input hardware.
+ */
+enum cvmx_pip_port_parse_mode {
+	/*
+	 * Packet input doesn't perform any processing of the input
+	 * packet.
+	 */
+	CVMX_PIP_PORT_CFG_MODE_NONE = 0ull,
+	/*
+	 * Full packet processing is performed with pointer starting
+	 * at the L2 (ethernet MAC) header.
+	 */
+	CVMX_PIP_PORT_CFG_MODE_SKIPL2 = 1ull,
+	/*
+	 * Input packets are assumed to be IP.  Results from non IP
+	 * packets is undefined. Pointers reference the beginning of
+	 * the IP header.
+	 */
+	CVMX_PIP_PORT_CFG_MODE_SKIPIP = 2ull
+};
+
+#define CVMX_PIP_BCK_PRS \
+	 CVMX_ADD_IO_SEG(0x00011800A0000038ull)
+#define CVMX_PIP_BIST_STATUS \
+	 CVMX_ADD_IO_SEG(0x00011800A0000000ull)
+#define CVMX_PIP_CRC_CTLX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000040ull + (((offset) & 1) * 8))
+#define CVMX_PIP_CRC_IVX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000050ull + (((offset) & 1) * 8))
+#define CVMX_PIP_DEC_IPSECX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000080ull + (((offset) & 3) * 8))
+#define CVMX_PIP_DSA_SRC_GRP \
+	 CVMX_ADD_IO_SEG(0x00011800A0000190ull)
+#define CVMX_PIP_DSA_VID_GRP \
+	 CVMX_ADD_IO_SEG(0x00011800A0000198ull)
+#define CVMX_PIP_FRM_LEN_CHKX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000180ull + (((offset) & 1) * 8))
+#define CVMX_PIP_GBL_CFG \
+	 CVMX_ADD_IO_SEG(0x00011800A0000028ull)
+#define CVMX_PIP_GBL_CTL \
+	 CVMX_ADD_IO_SEG(0x00011800A0000020ull)
+#define CVMX_PIP_HG_PRI_QOS \
+	 CVMX_ADD_IO_SEG(0x00011800A00001A0ull)
+#define CVMX_PIP_INT_EN \
+	 CVMX_ADD_IO_SEG(0x00011800A0000010ull)
+#define CVMX_PIP_INT_REG \
+	 CVMX_ADD_IO_SEG(0x00011800A0000008ull)
+#define CVMX_PIP_IP_OFFSET \
+	 CVMX_ADD_IO_SEG(0x00011800A0000060ull)
+#define CVMX_PIP_PRT_CFGX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000200ull + (((offset) & 63) * 8))
+#define CVMX_PIP_PRT_TAGX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000400ull + (((offset) & 63) * 8))
+#define CVMX_PIP_QOS_DIFFX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000600ull + (((offset) & 63) * 8))
+#define CVMX_PIP_QOS_VLANX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A00000C0ull + (((offset) & 7) * 8))
+#define CVMX_PIP_QOS_WATCHX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000100ull + (((offset) & 7) * 8))
+#define CVMX_PIP_RAW_WORD \
+	 CVMX_ADD_IO_SEG(0x00011800A00000B0ull)
+#define CVMX_PIP_SFT_RST \
+	 CVMX_ADD_IO_SEG(0x00011800A0000030ull)
+#define CVMX_PIP_STAT0_PRTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000800ull + (((offset) & 63) * 80))
+#define CVMX_PIP_STAT1_PRTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000808ull + (((offset) & 63) * 80))
+#define CVMX_PIP_STAT2_PRTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000810ull + (((offset) & 63) * 80))
+#define CVMX_PIP_STAT3_PRTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000818ull + (((offset) & 63) * 80))
+#define CVMX_PIP_STAT4_PRTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000820ull + (((offset) & 63) * 80))
+#define CVMX_PIP_STAT5_PRTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000828ull + (((offset) & 63) * 80))
+#define CVMX_PIP_STAT6_PRTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000830ull + (((offset) & 63) * 80))
+#define CVMX_PIP_STAT7_PRTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000838ull + (((offset) & 63) * 80))
+#define CVMX_PIP_STAT8_PRTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000840ull + (((offset) & 63) * 80))
+#define CVMX_PIP_STAT9_PRTX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0000848ull + (((offset) & 63) * 80))
+#define CVMX_PIP_STAT_CTL \
+	 CVMX_ADD_IO_SEG(0x00011800A0000018ull)
+#define CVMX_PIP_STAT_INB_ERRSX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0001A10ull + (((offset) & 63) * 32))
+#define CVMX_PIP_STAT_INB_OCTSX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0001A08ull + (((offset) & 63) * 32))
+#define CVMX_PIP_STAT_INB_PKTSX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0001A00ull + (((offset) & 63) * 32))
+#define CVMX_PIP_TAG_INCX(offset) \
+	 CVMX_ADD_IO_SEG(0x00011800A0001800ull + (((offset) & 63) * 8))
+#define CVMX_PIP_TAG_MASK \
+	 CVMX_ADD_IO_SEG(0x00011800A0000070ull)
+#define CVMX_PIP_TAG_SECRET \
+	 CVMX_ADD_IO_SEG(0x00011800A0000068ull)
+#define CVMX_PIP_TODO_ENTRY \
+	 CVMX_ADD_IO_SEG(0x00011800A0000078ull)
+
+union cvmx_pip_bck_prs {
+	uint64_t u64;
+	struct cvmx_pip_bck_prs_s {
+		uint64_t bckprs:1;
+		uint64_t reserved_13_62:50;
+		uint64_t hiwater:5;
+		uint64_t reserved_5_7:3;
+		uint64_t lowater:5;
+	} s;
+	struct cvmx_pip_bck_prs_s cn38xx;
+	struct cvmx_pip_bck_prs_s cn38xxp2;
+	struct cvmx_pip_bck_prs_s cn56xx;
+	struct cvmx_pip_bck_prs_s cn56xxp1;
+	struct cvmx_pip_bck_prs_s cn58xx;
+	struct cvmx_pip_bck_prs_s cn58xxp1;
+};
+
+union cvmx_pip_bist_status {
+	uint64_t u64;
+	struct cvmx_pip_bist_status_s {
+		uint64_t reserved_18_63:46;
+		uint64_t bist:18;
+	} s;
+	struct cvmx_pip_bist_status_s cn30xx;
+	struct cvmx_pip_bist_status_s cn31xx;
+	struct cvmx_pip_bist_status_s cn38xx;
+	struct cvmx_pip_bist_status_s cn38xxp2;
+	struct cvmx_pip_bist_status_cn50xx {
+		uint64_t reserved_17_63:47;
+		uint64_t bist:17;
+	} cn50xx;
+	struct cvmx_pip_bist_status_s cn52xx;
+	struct cvmx_pip_bist_status_s cn52xxp1;
+	struct cvmx_pip_bist_status_s cn56xx;
+	struct cvmx_pip_bist_status_s cn56xxp1;
+	struct cvmx_pip_bist_status_s cn58xx;
+	struct cvmx_pip_bist_status_s cn58xxp1;
+};
+
+union cvmx_pip_crc_ctlx {
+	uint64_t u64;
+	struct cvmx_pip_crc_ctlx_s {
+		uint64_t reserved_2_63:62;
+		uint64_t invres:1;
+		uint64_t reflect:1;
+	} s;
+	struct cvmx_pip_crc_ctlx_s cn38xx;
+	struct cvmx_pip_crc_ctlx_s cn38xxp2;
+	struct cvmx_pip_crc_ctlx_s cn58xx;
+	struct cvmx_pip_crc_ctlx_s cn58xxp1;
+};
+
+union cvmx_pip_crc_ivx {
+	uint64_t u64;
+	struct cvmx_pip_crc_ivx_s {
+		uint64_t reserved_32_63:32;
+		uint64_t iv:32;
+	} s;
+	struct cvmx_pip_crc_ivx_s cn38xx;
+	struct cvmx_pip_crc_ivx_s cn38xxp2;
+	struct cvmx_pip_crc_ivx_s cn58xx;
+	struct cvmx_pip_crc_ivx_s cn58xxp1;
+};
+
+union cvmx_pip_dec_ipsecx {
+	uint64_t u64;
+	struct cvmx_pip_dec_ipsecx_s {
+		uint64_t reserved_18_63:46;
+		uint64_t tcp:1;
+		uint64_t udp:1;
+		uint64_t dprt:16;
+	} s;
+	struct cvmx_pip_dec_ipsecx_s cn30xx;
+	struct cvmx_pip_dec_ipsecx_s cn31xx;
+	struct cvmx_pip_dec_ipsecx_s cn38xx;
+	struct cvmx_pip_dec_ipsecx_s cn38xxp2;
+	struct cvmx_pip_dec_ipsecx_s cn50xx;
+	struct cvmx_pip_dec_ipsecx_s cn52xx;
+	struct cvmx_pip_dec_ipsecx_s cn52xxp1;
+	struct cvmx_pip_dec_ipsecx_s cn56xx;
+	struct cvmx_pip_dec_ipsecx_s cn56xxp1;
+	struct cvmx_pip_dec_ipsecx_s cn58xx;
+	struct cvmx_pip_dec_ipsecx_s cn58xxp1;
+};
+
+union cvmx_pip_dsa_src_grp {
+	uint64_t u64;
+	struct cvmx_pip_dsa_src_grp_s {
+		uint64_t map15:4;
+		uint64_t map14:4;
+		uint64_t map13:4;
+		uint64_t map12:4;
+		uint64_t map11:4;
+		uint64_t map10:4;
+		uint64_t map9:4;
+		uint64_t map8:4;
+		uint64_t map7:4;
+		uint64_t map6:4;
+		uint64_t map5:4;
+		uint64_t map4:4;
+		uint64_t map3:4;
+		uint64_t map2:4;
+		uint64_t map1:4;
+		uint64_t map0:4;
+	} s;
+	struct cvmx_pip_dsa_src_grp_s cn52xx;
+	struct cvmx_pip_dsa_src_grp_s cn52xxp1;
+	struct cvmx_pip_dsa_src_grp_s cn56xx;
+};
+
+union cvmx_pip_dsa_vid_grp {
+	uint64_t u64;
+	struct cvmx_pip_dsa_vid_grp_s {
+		uint64_t map15:4;
+		uint64_t map14:4;
+		uint64_t map13:4;
+		uint64_t map12:4;
+		uint64_t map11:4;
+		uint64_t map10:4;
+		uint64_t map9:4;
+		uint64_t map8:4;
+		uint64_t map7:4;
+		uint64_t map6:4;
+		uint64_t map5:4;
+		uint64_t map4:4;
+		uint64_t map3:4;
+		uint64_t map2:4;
+		uint64_t map1:4;
+		uint64_t map0:4;
+	} s;
+	struct cvmx_pip_dsa_vid_grp_s cn52xx;
+	struct cvmx_pip_dsa_vid_grp_s cn52xxp1;
+	struct cvmx_pip_dsa_vid_grp_s cn56xx;
+};
+
+union cvmx_pip_frm_len_chkx {
+	uint64_t u64;
+	struct cvmx_pip_frm_len_chkx_s {
+		uint64_t reserved_32_63:32;
+		uint64_t maxlen:16;
+		uint64_t minlen:16;
+	} s;
+	struct cvmx_pip_frm_len_chkx_s cn50xx;
+	struct cvmx_pip_frm_len_chkx_s cn52xx;
+	struct cvmx_pip_frm_len_chkx_s cn52xxp1;
+	struct cvmx_pip_frm_len_chkx_s cn56xx;
+	struct cvmx_pip_frm_len_chkx_s cn56xxp1;
+};
+
+union cvmx_pip_gbl_cfg {
+	uint64_t u64;
+	struct cvmx_pip_gbl_cfg_s {
+		uint64_t reserved_19_63:45;
+		uint64_t tag_syn:1;
+		uint64_t ip6_udp:1;
+		uint64_t max_l2:1;
+		uint64_t reserved_11_15:5;
+		uint64_t raw_shf:3;
+		uint64_t reserved_3_7:5;
+		uint64_t nip_shf:3;
+	} s;
+	struct cvmx_pip_gbl_cfg_s cn30xx;
+	struct cvmx_pip_gbl_cfg_s cn31xx;
+	struct cvmx_pip_gbl_cfg_s cn38xx;
+	struct cvmx_pip_gbl_cfg_s cn38xxp2;
+	struct cvmx_pip_gbl_cfg_s cn50xx;
+	struct cvmx_pip_gbl_cfg_s cn52xx;
+	struct cvmx_pip_gbl_cfg_s cn52xxp1;
+	struct cvmx_pip_gbl_cfg_s cn56xx;
+	struct cvmx_pip_gbl_cfg_s cn56xxp1;
+	struct cvmx_pip_gbl_cfg_s cn58xx;
+	struct cvmx_pip_gbl_cfg_s cn58xxp1;
+};
+
+union cvmx_pip_gbl_ctl {
+	uint64_t u64;
+	struct cvmx_pip_gbl_ctl_s {
+		uint64_t reserved_27_63:37;
+		uint64_t dsa_grp_tvid:1;
+		uint64_t dsa_grp_scmd:1;
+		uint64_t dsa_grp_sid:1;
+		uint64_t reserved_21_23:3;
+		uint64_t ring_en:1;
+		uint64_t reserved_17_19:3;
+		uint64_t ignrs:1;
+		uint64_t vs_wqe:1;
+		uint64_t vs_qos:1;
+		uint64_t l2_mal:1;
+		uint64_t tcp_flag:1;
+		uint64_t l4_len:1;
+		uint64_t l4_chk:1;
+		uint64_t l4_prt:1;
+		uint64_t l4_mal:1;
+		uint64_t reserved_6_7:2;
+		uint64_t ip6_eext:2;
+		uint64_t ip4_opts:1;
+		uint64_t ip_hop:1;
+		uint64_t ip_mal:1;
+		uint64_t ip_chk:1;
+	} s;
+	struct cvmx_pip_gbl_ctl_cn30xx {
+		uint64_t reserved_17_63:47;
+		uint64_t ignrs:1;
+		uint64_t vs_wqe:1;
+		uint64_t vs_qos:1;
+		uint64_t l2_mal:1;
+		uint64_t tcp_flag:1;
+		uint64_t l4_len:1;
+		uint64_t l4_chk:1;
+		uint64_t l4_prt:1;
+		uint64_t l4_mal:1;
+		uint64_t reserved_6_7:2;
+		uint64_t ip6_eext:2;
+		uint64_t ip4_opts:1;
+		uint64_t ip_hop:1;
+		uint64_t ip_mal:1;
+		uint64_t ip_chk:1;
+	} cn30xx;
+	struct cvmx_pip_gbl_ctl_cn30xx cn31xx;
+	struct cvmx_pip_gbl_ctl_cn30xx cn38xx;
+	struct cvmx_pip_gbl_ctl_cn30xx cn38xxp2;
+	struct cvmx_pip_gbl_ctl_cn30xx cn50xx;
+	struct cvmx_pip_gbl_ctl_s cn52xx;
+	struct cvmx_pip_gbl_ctl_s cn52xxp1;
+	struct cvmx_pip_gbl_ctl_s cn56xx;
+	struct cvmx_pip_gbl_ctl_cn56xxp1 {
+		uint64_t reserved_21_63:43;
+		uint64_t ring_en:1;
+		uint64_t reserved_17_19:3;
+		uint64_t ignrs:1;
+		uint64_t vs_wqe:1;
+		uint64_t vs_qos:1;
+		uint64_t l2_mal:1;
+		uint64_t tcp_flag:1;
+		uint64_t l4_len:1;
+		uint64_t l4_chk:1;
+		uint64_t l4_prt:1;
+		uint64_t l4_mal:1;
+		uint64_t reserved_6_7:2;
+		uint64_t ip6_eext:2;
+		uint64_t ip4_opts:1;
+		uint64_t ip_hop:1;
+		uint64_t ip_mal:1;
+		uint64_t ip_chk:1;
+	} cn56xxp1;
+	struct cvmx_pip_gbl_ctl_cn30xx cn58xx;
+	struct cvmx_pip_gbl_ctl_cn30xx cn58xxp1;
+};
+
+union cvmx_pip_hg_pri_qos {
+	uint64_t u64;
+	struct cvmx_pip_hg_pri_qos_s {
+		uint64_t reserved_11_63:53;
+		uint64_t qos:3;
+		uint64_t reserved_6_7:2;
+		uint64_t pri:6;
+	} s;
+	struct cvmx_pip_hg_pri_qos_s cn52xx;
+	struct cvmx_pip_hg_pri_qos_s cn52xxp1;
+	struct cvmx_pip_hg_pri_qos_s cn56xx;
+};
+
+union cvmx_pip_int_en {
+	uint64_t u64;
+	struct cvmx_pip_int_en_s {
+		uint64_t reserved_13_63:51;
+		uint64_t punyerr:1;
+		uint64_t lenerr:1;
+		uint64_t maxerr:1;
+		uint64_t minerr:1;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t crcerr:1;
+		uint64_t pktdrp:1;
+	} s;
+	struct cvmx_pip_int_en_cn30xx {
+		uint64_t reserved_9_63:55;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t crcerr:1;
+		uint64_t pktdrp:1;
+	} cn30xx;
+	struct cvmx_pip_int_en_cn30xx cn31xx;
+	struct cvmx_pip_int_en_cn30xx cn38xx;
+	struct cvmx_pip_int_en_cn30xx cn38xxp2;
+	struct cvmx_pip_int_en_cn50xx {
+		uint64_t reserved_12_63:52;
+		uint64_t lenerr:1;
+		uint64_t maxerr:1;
+		uint64_t minerr:1;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t reserved_1_1:1;
+		uint64_t pktdrp:1;
+	} cn50xx;
+	struct cvmx_pip_int_en_cn52xx {
+		uint64_t reserved_13_63:51;
+		uint64_t punyerr:1;
+		uint64_t lenerr:1;
+		uint64_t maxerr:1;
+		uint64_t minerr:1;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t reserved_1_1:1;
+		uint64_t pktdrp:1;
+	} cn52xx;
+	struct cvmx_pip_int_en_cn52xx cn52xxp1;
+	struct cvmx_pip_int_en_s cn56xx;
+	struct cvmx_pip_int_en_cn56xxp1 {
+		uint64_t reserved_12_63:52;
+		uint64_t lenerr:1;
+		uint64_t maxerr:1;
+		uint64_t minerr:1;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t crcerr:1;
+		uint64_t pktdrp:1;
+	} cn56xxp1;
+	struct cvmx_pip_int_en_cn58xx {
+		uint64_t reserved_13_63:51;
+		uint64_t punyerr:1;
+		uint64_t reserved_9_11:3;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t crcerr:1;
+		uint64_t pktdrp:1;
+	} cn58xx;
+	struct cvmx_pip_int_en_cn30xx cn58xxp1;
+};
+
+union cvmx_pip_int_reg {
+	uint64_t u64;
+	struct cvmx_pip_int_reg_s {
+		uint64_t reserved_13_63:51;
+		uint64_t punyerr:1;
+		uint64_t lenerr:1;
+		uint64_t maxerr:1;
+		uint64_t minerr:1;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t crcerr:1;
+		uint64_t pktdrp:1;
+	} s;
+	struct cvmx_pip_int_reg_cn30xx {
+		uint64_t reserved_9_63:55;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t crcerr:1;
+		uint64_t pktdrp:1;
+	} cn30xx;
+	struct cvmx_pip_int_reg_cn30xx cn31xx;
+	struct cvmx_pip_int_reg_cn30xx cn38xx;
+	struct cvmx_pip_int_reg_cn30xx cn38xxp2;
+	struct cvmx_pip_int_reg_cn50xx {
+		uint64_t reserved_12_63:52;
+		uint64_t lenerr:1;
+		uint64_t maxerr:1;
+		uint64_t minerr:1;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t reserved_1_1:1;
+		uint64_t pktdrp:1;
+	} cn50xx;
+	struct cvmx_pip_int_reg_cn52xx {
+		uint64_t reserved_13_63:51;
+		uint64_t punyerr:1;
+		uint64_t lenerr:1;
+		uint64_t maxerr:1;
+		uint64_t minerr:1;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t reserved_1_1:1;
+		uint64_t pktdrp:1;
+	} cn52xx;
+	struct cvmx_pip_int_reg_cn52xx cn52xxp1;
+	struct cvmx_pip_int_reg_s cn56xx;
+	struct cvmx_pip_int_reg_cn56xxp1 {
+		uint64_t reserved_12_63:52;
+		uint64_t lenerr:1;
+		uint64_t maxerr:1;
+		uint64_t minerr:1;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t crcerr:1;
+		uint64_t pktdrp:1;
+	} cn56xxp1;
+	struct cvmx_pip_int_reg_cn58xx {
+		uint64_t reserved_13_63:51;
+		uint64_t punyerr:1;
+		uint64_t reserved_9_11:3;
+		uint64_t beperr:1;
+		uint64_t feperr:1;
+		uint64_t todoovr:1;
+		uint64_t skprunt:1;
+		uint64_t badtag:1;
+		uint64_t prtnxa:1;
+		uint64_t bckprs:1;
+		uint64_t crcerr:1;
+		uint64_t pktdrp:1;
+	} cn58xx;
+	struct cvmx_pip_int_reg_cn30xx cn58xxp1;
+};
+
+union cvmx_pip_ip_offset {
+	uint64_t u64;
+	struct cvmx_pip_ip_offset_s {
+		uint64_t reserved_3_63:61;
+		uint64_t offset:3;
+	} s;
+	struct cvmx_pip_ip_offset_s cn30xx;
+	struct cvmx_pip_ip_offset_s cn31xx;
+	struct cvmx_pip_ip_offset_s cn38xx;
+	struct cvmx_pip_ip_offset_s cn38xxp2;
+	struct cvmx_pip_ip_offset_s cn50xx;
+	struct cvmx_pip_ip_offset_s cn52xx;
+	struct cvmx_pip_ip_offset_s cn52xxp1;
+	struct cvmx_pip_ip_offset_s cn56xx;
+	struct cvmx_pip_ip_offset_s cn56xxp1;
+	struct cvmx_pip_ip_offset_s cn58xx;
+	struct cvmx_pip_ip_offset_s cn58xxp1;
+};
+
+union cvmx_pip_prt_cfgx {
+	uint64_t u64;
+	struct cvmx_pip_prt_cfgx_s {
+		uint64_t reserved_53_63:11;
+		uint64_t pad_len:1;
+		uint64_t vlan_len:1;
+		uint64_t lenerr_en:1;
+		uint64_t maxerr_en:1;
+		uint64_t minerr_en:1;
+		uint64_t grp_wat_47:4;
+		uint64_t qos_wat_47:4;
+		uint64_t reserved_37_39:3;
+		uint64_t rawdrp:1;
+		uint64_t tag_inc:2;
+		uint64_t dyn_rs:1;
+		uint64_t inst_hdr:1;
+		uint64_t grp_wat:4;
+		uint64_t hg_qos:1;
+		uint64_t qos:3;
+		uint64_t qos_wat:4;
+		uint64_t qos_vsel:1;
+		uint64_t qos_vod:1;
+		uint64_t qos_diff:1;
+		uint64_t qos_vlan:1;
+		uint64_t reserved_13_15:3;
+		uint64_t crc_en:1;
+		uint64_t higig_en:1;
+		uint64_t dsa_en:1;
+		uint64_t mode:2;
+		uint64_t reserved_7_7:1;
+		uint64_t skip:7;
+	} s;
+	struct cvmx_pip_prt_cfgx_cn30xx {
+		uint64_t reserved_37_63:27;
+		uint64_t rawdrp:1;
+		uint64_t tag_inc:2;
+		uint64_t dyn_rs:1;
+		uint64_t inst_hdr:1;
+		uint64_t grp_wat:4;
+		uint64_t reserved_27_27:1;
+		uint64_t qos:3;
+		uint64_t qos_wat:4;
+		uint64_t reserved_18_19:2;
+		uint64_t qos_diff:1;
+		uint64_t qos_vlan:1;
+		uint64_t reserved_10_15:6;
+		uint64_t mode:2;
+		uint64_t reserved_7_7:1;
+		uint64_t skip:7;
+	} cn30xx;
+	struct cvmx_pip_prt_cfgx_cn30xx cn31xx;
+	struct cvmx_pip_prt_cfgx_cn38xx {
+		uint64_t reserved_37_63:27;
+		uint64_t rawdrp:1;
+		uint64_t tag_inc:2;
+		uint64_t dyn_rs:1;
+		uint64_t inst_hdr:1;
+		uint64_t grp_wat:4;
+		uint64_t reserved_27_27:1;
+		uint64_t qos:3;
+		uint64_t qos_wat:4;
+		uint64_t reserved_18_19:2;
+		uint64_t qos_diff:1;
+		uint64_t qos_vlan:1;
+		uint64_t reserved_13_15:3;
+		uint64_t crc_en:1;
+		uint64_t reserved_10_11:2;
+		uint64_t mode:2;
+		uint64_t reserved_7_7:1;
+		uint64_t skip:7;
+	} cn38xx;
+	struct cvmx_pip_prt_cfgx_cn38xx cn38xxp2;
+	struct cvmx_pip_prt_cfgx_cn50xx {
+		uint64_t reserved_53_63:11;
+		uint64_t pad_len:1;
+		uint64_t vlan_len:1;
+		uint64_t lenerr_en:1;
+		uint64_t maxerr_en:1;
+		uint64_t minerr_en:1;
+		uint64_t grp_wat_47:4;
+		uint64_t qos_wat_47:4;
+		uint64_t reserved_37_39:3;
+		uint64_t rawdrp:1;
+		uint64_t tag_inc:2;
+		uint64_t dyn_rs:1;
+		uint64_t inst_hdr:1;
+		uint64_t grp_wat:4;
+		uint64_t reserved_27_27:1;
+		uint64_t qos:3;
+		uint64_t qos_wat:4;
+		uint64_t reserved_19_19:1;
+		uint64_t qos_vod:1;
+		uint64_t qos_diff:1;
+		uint64_t qos_vlan:1;
+		uint64_t reserved_13_15:3;
+		uint64_t crc_en:1;
+		uint64_t reserved_10_11:2;
+		uint64_t mode:2;
+		uint64_t reserved_7_7:1;
+		uint64_t skip:7;
+	} cn50xx;
+	struct cvmx_pip_prt_cfgx_s cn52xx;
+	struct cvmx_pip_prt_cfgx_s cn52xxp1;
+	struct cvmx_pip_prt_cfgx_s cn56xx;
+	struct cvmx_pip_prt_cfgx_cn50xx cn56xxp1;
+	struct cvmx_pip_prt_cfgx_cn58xx {
+		uint64_t reserved_37_63:27;
+		uint64_t rawdrp:1;
+		uint64_t tag_inc:2;
+		uint64_t dyn_rs:1;
+		uint64_t inst_hdr:1;
+		uint64_t grp_wat:4;
+		uint64_t reserved_27_27:1;
+		uint64_t qos:3;
+		uint64_t qos_wat:4;
+		uint64_t reserved_19_19:1;
+		uint64_t qos_vod:1;
+		uint64_t qos_diff:1;
+		uint64_t qos_vlan:1;
+		uint64_t reserved_13_15:3;
+		uint64_t crc_en:1;
+		uint64_t reserved_10_11:2;
+		uint64_t mode:2;
+		uint64_t reserved_7_7:1;
+		uint64_t skip:7;
+	} cn58xx;
+	struct cvmx_pip_prt_cfgx_cn58xx cn58xxp1;
+};
+
+union cvmx_pip_prt_tagx {
+	uint64_t u64;
+	struct cvmx_pip_prt_tagx_s {
+		uint64_t reserved_40_63:24;
+		uint64_t grptagbase:4;
+		uint64_t grptagmask:4;
+		uint64_t grptag:1;
+		uint64_t grptag_mskip:1;
+		uint64_t tag_mode:2;
+		uint64_t inc_vs:2;
+		uint64_t inc_vlan:1;
+		uint64_t inc_prt_flag:1;
+		uint64_t ip6_dprt_flag:1;
+		uint64_t ip4_dprt_flag:1;
+		uint64_t ip6_sprt_flag:1;
+		uint64_t ip4_sprt_flag:1;
+		uint64_t ip6_nxth_flag:1;
+		uint64_t ip4_pctl_flag:1;
+		uint64_t ip6_dst_flag:1;
+		uint64_t ip4_dst_flag:1;
+		uint64_t ip6_src_flag:1;
+		uint64_t ip4_src_flag:1;
+		uint64_t tcp6_tag_type:2;
+		uint64_t tcp4_tag_type:2;
+		uint64_t ip6_tag_type:2;
+		uint64_t ip4_tag_type:2;
+		uint64_t non_tag_type:2;
+		uint64_t grp:4;
+	} s;
+	struct cvmx_pip_prt_tagx_cn30xx {
+		uint64_t reserved_40_63:24;
+		uint64_t grptagbase:4;
+		uint64_t grptagmask:4;
+		uint64_t grptag:1;
+		uint64_t reserved_30_30:1;
+		uint64_t tag_mode:2;
+		uint64_t inc_vs:2;
+		uint64_t inc_vlan:1;
+		uint64_t inc_prt_flag:1;
+		uint64_t ip6_dprt_flag:1;
+		uint64_t ip4_dprt_flag:1;
+		uint64_t ip6_sprt_flag:1;
+		uint64_t ip4_sprt_flag:1;
+		uint64_t ip6_nxth_flag:1;
+		uint64_t ip4_pctl_flag:1;
+		uint64_t ip6_dst_flag:1;
+		uint64_t ip4_dst_flag:1;
+		uint64_t ip6_src_flag:1;
+		uint64_t ip4_src_flag:1;
+		uint64_t tcp6_tag_type:2;
+		uint64_t tcp4_tag_type:2;
+		uint64_t ip6_tag_type:2;
+		uint64_t ip4_tag_type:2;
+		uint64_t non_tag_type:2;
+		uint64_t grp:4;
+	} cn30xx;
+	struct cvmx_pip_prt_tagx_cn30xx cn31xx;
+	struct cvmx_pip_prt_tagx_cn30xx cn38xx;
+	struct cvmx_pip_prt_tagx_cn30xx cn38xxp2;
+	struct cvmx_pip_prt_tagx_s cn50xx;
+	struct cvmx_pip_prt_tagx_s cn52xx;
+	struct cvmx_pip_prt_tagx_s cn52xxp1;
+	struct cvmx_pip_prt_tagx_s cn56xx;
+	struct cvmx_pip_prt_tagx_s cn56xxp1;
+	struct cvmx_pip_prt_tagx_cn30xx cn58xx;
+	struct cvmx_pip_prt_tagx_cn30xx cn58xxp1;
+};
+
+union cvmx_pip_qos_diffx {
+	uint64_t u64;
+	struct cvmx_pip_qos_diffx_s {
+		uint64_t reserved_3_63:61;
+		uint64_t qos:3;
+	} s;
+	struct cvmx_pip_qos_diffx_s cn30xx;
+	struct cvmx_pip_qos_diffx_s cn31xx;
+	struct cvmx_pip_qos_diffx_s cn38xx;
+	struct cvmx_pip_qos_diffx_s cn38xxp2;
+	struct cvmx_pip_qos_diffx_s cn50xx;
+	struct cvmx_pip_qos_diffx_s cn52xx;
+	struct cvmx_pip_qos_diffx_s cn52xxp1;
+	struct cvmx_pip_qos_diffx_s cn56xx;
+	struct cvmx_pip_qos_diffx_s cn56xxp1;
+	struct cvmx_pip_qos_diffx_s cn58xx;
+	struct cvmx_pip_qos_diffx_s cn58xxp1;
+};
+
+union cvmx_pip_qos_vlanx {
+	uint64_t u64;
+	struct cvmx_pip_qos_vlanx_s {
+		uint64_t reserved_7_63:57;
+		uint64_t qos1:3;
+		uint64_t reserved_3_3:1;
+		uint64_t qos:3;
+	} s;
+	struct cvmx_pip_qos_vlanx_cn30xx {
+		uint64_t reserved_3_63:61;
+		uint64_t qos:3;
+	} cn30xx;
+	struct cvmx_pip_qos_vlanx_cn30xx cn31xx;
+	struct cvmx_pip_qos_vlanx_cn30xx cn38xx;
+	struct cvmx_pip_qos_vlanx_cn30xx cn38xxp2;
+	struct cvmx_pip_qos_vlanx_cn30xx cn50xx;
+	struct cvmx_pip_qos_vlanx_s cn52xx;
+	struct cvmx_pip_qos_vlanx_s cn52xxp1;
+	struct cvmx_pip_qos_vlanx_s cn56xx;
+	struct cvmx_pip_qos_vlanx_cn30xx cn56xxp1;
+	struct cvmx_pip_qos_vlanx_cn30xx cn58xx;
+	struct cvmx_pip_qos_vlanx_cn30xx cn58xxp1;
+};
+
+union cvmx_pip_qos_watchx {
+	uint64_t u64;
+	struct cvmx_pip_qos_watchx_s {
+		uint64_t reserved_48_63:16;
+		uint64_t mask:16;
+		uint64_t reserved_28_31:4;
+		uint64_t grp:4;
+		uint64_t reserved_23_23:1;
+		uint64_t qos:3;
+		uint64_t reserved_19_19:1;
+		uint64_t match_type:3;
+		uint64_t match_value:16;
+	} s;
+	struct cvmx_pip_qos_watchx_cn30xx {
+		uint64_t reserved_48_63:16;
+		uint64_t mask:16;
+		uint64_t reserved_28_31:4;
+		uint64_t grp:4;
+		uint64_t reserved_23_23:1;
+		uint64_t qos:3;
+		uint64_t reserved_18_19:2;
+		uint64_t match_type:2;
+		uint64_t match_value:16;
+	} cn30xx;
+	struct cvmx_pip_qos_watchx_cn30xx cn31xx;
+	struct cvmx_pip_qos_watchx_cn30xx cn38xx;
+	struct cvmx_pip_qos_watchx_cn30xx cn38xxp2;
+	struct cvmx_pip_qos_watchx_s cn50xx;
+	struct cvmx_pip_qos_watchx_s cn52xx;
+	struct cvmx_pip_qos_watchx_s cn52xxp1;
+	struct cvmx_pip_qos_watchx_s cn56xx;
+	struct cvmx_pip_qos_watchx_s cn56xxp1;
+	struct cvmx_pip_qos_watchx_cn30xx cn58xx;
+	struct cvmx_pip_qos_watchx_cn30xx cn58xxp1;
+};
+
+union cvmx_pip_raw_word {
+	uint64_t u64;
+	struct cvmx_pip_raw_word_s {
+		uint64_t reserved_56_63:8;
+		uint64_t word:56;
+	} s;
+	struct cvmx_pip_raw_word_s cn30xx;
+	struct cvmx_pip_raw_word_s cn31xx;
+	struct cvmx_pip_raw_word_s cn38xx;
+	struct cvmx_pip_raw_word_s cn38xxp2;
+	struct cvmx_pip_raw_word_s cn50xx;
+	struct cvmx_pip_raw_word_s cn52xx;
+	struct cvmx_pip_raw_word_s cn52xxp1;
+	struct cvmx_pip_raw_word_s cn56xx;
+	struct cvmx_pip_raw_word_s cn56xxp1;
+	struct cvmx_pip_raw_word_s cn58xx;
+	struct cvmx_pip_raw_word_s cn58xxp1;
+};
+
+union cvmx_pip_sft_rst {
+	uint64_t u64;
+	struct cvmx_pip_sft_rst_s {
+		uint64_t reserved_1_63:63;
+		uint64_t rst:1;
+	} s;
+	struct cvmx_pip_sft_rst_s cn30xx;
+	struct cvmx_pip_sft_rst_s cn31xx;
+	struct cvmx_pip_sft_rst_s cn38xx;
+	struct cvmx_pip_sft_rst_s cn50xx;
+	struct cvmx_pip_sft_rst_s cn52xx;
+	struct cvmx_pip_sft_rst_s cn52xxp1;
+	struct cvmx_pip_sft_rst_s cn56xx;
+	struct cvmx_pip_sft_rst_s cn56xxp1;
+	struct cvmx_pip_sft_rst_s cn58xx;
+	struct cvmx_pip_sft_rst_s cn58xxp1;
+};
+
+union cvmx_pip_stat0_prtx {
+	uint64_t u64;
+	struct cvmx_pip_stat0_prtx_s {
+		uint64_t drp_pkts:32;
+		uint64_t drp_octs:32;
+	} s;
+	struct cvmx_pip_stat0_prtx_s cn30xx;
+	struct cvmx_pip_stat0_prtx_s cn31xx;
+	struct cvmx_pip_stat0_prtx_s cn38xx;
+	struct cvmx_pip_stat0_prtx_s cn38xxp2;
+	struct cvmx_pip_stat0_prtx_s cn50xx;
+	struct cvmx_pip_stat0_prtx_s cn52xx;
+	struct cvmx_pip_stat0_prtx_s cn52xxp1;
+	struct cvmx_pip_stat0_prtx_s cn56xx;
+	struct cvmx_pip_stat0_prtx_s cn56xxp1;
+	struct cvmx_pip_stat0_prtx_s cn58xx;
+	struct cvmx_pip_stat0_prtx_s cn58xxp1;
+};
+
+union cvmx_pip_stat1_prtx {
+	uint64_t u64;
+	struct cvmx_pip_stat1_prtx_s {
+		uint64_t reserved_48_63:16;
+		uint64_t octs:48;
+	} s;
+	struct cvmx_pip_stat1_prtx_s cn30xx;
+	struct cvmx_pip_stat1_prtx_s cn31xx;
+	struct cvmx_pip_stat1_prtx_s cn38xx;
+	struct cvmx_pip_stat1_prtx_s cn38xxp2;
+	struct cvmx_pip_stat1_prtx_s cn50xx;
+	struct cvmx_pip_stat1_prtx_s cn52xx;
+	struct cvmx_pip_stat1_prtx_s cn52xxp1;
+	struct cvmx_pip_stat1_prtx_s cn56xx;
+	struct cvmx_pip_stat1_prtx_s cn56xxp1;
+	struct cvmx_pip_stat1_prtx_s cn58xx;
+	struct cvmx_pip_stat1_prtx_s cn58xxp1;
+};
+
+union cvmx_pip_stat2_prtx {
+	uint64_t u64;
+	struct cvmx_pip_stat2_prtx_s {
+		uint64_t pkts:32;
+		uint64_t raw:32;
+	} s;
+	struct cvmx_pip_stat2_prtx_s cn30xx;
+	struct cvmx_pip_stat2_prtx_s cn31xx;
+	struct cvmx_pip_stat2_prtx_s cn38xx;
+	struct cvmx_pip_stat2_prtx_s cn38xxp2;
+	struct cvmx_pip_stat2_prtx_s cn50xx;
+	struct cvmx_pip_stat2_prtx_s cn52xx;
+	struct cvmx_pip_stat2_prtx_s cn52xxp1;
+	struct cvmx_pip_stat2_prtx_s cn56xx;
+	struct cvmx_pip_stat2_prtx_s cn56xxp1;
+	struct cvmx_pip_stat2_prtx_s cn58xx;
+	struct cvmx_pip_stat2_prtx_s cn58xxp1;
+};
+
+union cvmx_pip_stat3_prtx {
+	uint64_t u64;
+	struct cvmx_pip_stat3_prtx_s {
+		uint64_t bcst:32;
+		uint64_t mcst:32;
+	} s;
+	struct cvmx_pip_stat3_prtx_s cn30xx;
+	struct cvmx_pip_stat3_prtx_s cn31xx;
+	struct cvmx_pip_stat3_prtx_s cn38xx;
+	struct cvmx_pip_stat3_prtx_s cn38xxp2;
+	struct cvmx_pip_stat3_prtx_s cn50xx;
+	struct cvmx_pip_stat3_prtx_s cn52xx;
+	struct cvmx_pip_stat3_prtx_s cn52xxp1;
+	struct cvmx_pip_stat3_prtx_s cn56xx;
+	struct cvmx_pip_stat3_prtx_s cn56xxp1;
+	struct cvmx_pip_stat3_prtx_s cn58xx;
+	struct cvmx_pip_stat3_prtx_s cn58xxp1;
+};
+
+union cvmx_pip_stat4_prtx {
+	uint64_t u64;
+	struct cvmx_pip_stat4_prtx_s {
+		uint64_t h65to127:32;
+		uint64_t h64:32;
+	} s;
+	struct cvmx_pip_stat4_prtx_s cn30xx;
+	struct cvmx_pip_stat4_prtx_s cn31xx;
+	struct cvmx_pip_stat4_prtx_s cn38xx;
+	struct cvmx_pip_stat4_prtx_s cn38xxp2;
+	struct cvmx_pip_stat4_prtx_s cn50xx;
+	struct cvmx_pip_stat4_prtx_s cn52xx;
+	struct cvmx_pip_stat4_prtx_s cn52xxp1;
+	struct cvmx_pip_stat4_prtx_s cn56xx;
+	struct cvmx_pip_stat4_prtx_s cn56xxp1;
+	struct cvmx_pip_stat4_prtx_s cn58xx;
+	struct cvmx_pip_stat4_prtx_s cn58xxp1;
+};
+
+union cvmx_pip_stat5_prtx {
+	uint64_t u64;
+	struct cvmx_pip_stat5_prtx_s {
+		uint64_t h256to511:32;
+		uint64_t h128to255:32;
+	} s;
+	struct cvmx_pip_stat5_prtx_s cn30xx;
+	struct cvmx_pip_stat5_prtx_s cn31xx;
+	struct cvmx_pip_stat5_prtx_s cn38xx;
+	struct cvmx_pip_stat5_prtx_s cn38xxp2;
+	struct cvmx_pip_stat5_prtx_s cn50xx;
+	struct cvmx_pip_stat5_prtx_s cn52xx;
+	struct cvmx_pip_stat5_prtx_s cn52xxp1;
+	struct cvmx_pip_stat5_prtx_s cn56xx;
+	struct cvmx_pip_stat5_prtx_s cn56xxp1;
+	struct cvmx_pip_stat5_prtx_s cn58xx;
+	struct cvmx_pip_stat5_prtx_s cn58xxp1;
+};
+
+union cvmx_pip_stat6_prtx {
+	uint64_t u64;
+	struct cvmx_pip_stat6_prtx_s {
+		uint64_t h1024to1518:32;
+		uint64_t h512to1023:32;
+	} s;
+	struct cvmx_pip_stat6_prtx_s cn30xx;
+	struct cvmx_pip_stat6_prtx_s cn31xx;
+	struct cvmx_pip_stat6_prtx_s cn38xx;
+	struct cvmx_pip_stat6_prtx_s cn38xxp2;
+	struct cvmx_pip_stat6_prtx_s cn50xx;
+	struct cvmx_pip_stat6_prtx_s cn52xx;
+	struct cvmx_pip_stat6_prtx_s cn52xxp1;
+	struct cvmx_pip_stat6_prtx_s cn56xx;
+	struct cvmx_pip_stat6_prtx_s cn56xxp1;
+	struct cvmx_pip_stat6_prtx_s cn58xx;
+	struct cvmx_pip_stat6_prtx_s cn58xxp1;
+};
+
+union cvmx_pip_stat7_prtx {
+	uint64_t u64;
+	struct cvmx_pip_stat7_prtx_s {
+		uint64_t fcs:32;
+		uint64_t h1519:32;
+	} s;
+	struct cvmx_pip_stat7_prtx_s cn30xx;
+	struct cvmx_pip_stat7_prtx_s cn31xx;
+	struct cvmx_pip_stat7_prtx_s cn38xx;
+	struct cvmx_pip_stat7_prtx_s cn38xxp2;
+	struct cvmx_pip_stat7_prtx_s cn50xx;
+	struct cvmx_pip_stat7_prtx_s cn52xx;
+	struct cvmx_pip_stat7_prtx_s cn52xxp1;
+	struct cvmx_pip_stat7_prtx_s cn56xx;
+	struct cvmx_pip_stat7_prtx_s cn56xxp1;
+	struct cvmx_pip_stat7_prtx_s cn58xx;
+	struct cvmx_pip_stat7_prtx_s cn58xxp1;
+};
+
+union cvmx_pip_stat8_prtx {
+	uint64_t u64;
+	struct cvmx_pip_stat8_prtx_s {
+		uint64_t frag:32;
+		uint64_t undersz:32;
+	} s;
+	struct cvmx_pip_stat8_prtx_s cn30xx;
+	struct cvmx_pip_stat8_prtx_s cn31xx;
+	struct cvmx_pip_stat8_prtx_s cn38xx;
+	struct cvmx_pip_stat8_prtx_s cn38xxp2;
+	struct cvmx_pip_stat8_prtx_s cn50xx;
+	struct cvmx_pip_stat8_prtx_s cn52xx;
+	struct cvmx_pip_stat8_prtx_s cn52xxp1;
+	struct cvmx_pip_stat8_prtx_s cn56xx;
+	struct cvmx_pip_stat8_prtx_s cn56xxp1;
+	struct cvmx_pip_stat8_prtx_s cn58xx;
+	struct cvmx_pip_stat8_prtx_s cn58xxp1;
+};
+
+union cvmx_pip_stat9_prtx {
+	uint64_t u64;
+	struct cvmx_pip_stat9_prtx_s {
+		uint64_t jabber:32;
+		uint64_t oversz:32;
+	} s;
+	struct cvmx_pip_stat9_prtx_s cn30xx;
+	struct cvmx_pip_stat9_prtx_s cn31xx;
+	struct cvmx_pip_stat9_prtx_s cn38xx;
+	struct cvmx_pip_stat9_prtx_s cn38xxp2;
+	struct cvmx_pip_stat9_prtx_s cn50xx;
+	struct cvmx_pip_stat9_prtx_s cn52xx;
+	struct cvmx_pip_stat9_prtx_s cn52xxp1;
+	struct cvmx_pip_stat9_prtx_s cn56xx;
+	struct cvmx_pip_stat9_prtx_s cn56xxp1;
+	struct cvmx_pip_stat9_prtx_s cn58xx;
+	struct cvmx_pip_stat9_prtx_s cn58xxp1;
+};
+
+union cvmx_pip_stat_ctl {
+	uint64_t u64;
+	struct cvmx_pip_stat_ctl_s {
+		uint64_t reserved_1_63:63;
+		uint64_t rdclr:1;
+	} s;
+	struct cvmx_pip_stat_ctl_s cn30xx;
+	struct cvmx_pip_stat_ctl_s cn31xx;
+	struct cvmx_pip_stat_ctl_s cn38xx;
+	struct cvmx_pip_stat_ctl_s cn38xxp2;
+	struct cvmx_pip_stat_ctl_s cn50xx;
+	struct cvmx_pip_stat_ctl_s cn52xx;
+	struct cvmx_pip_stat_ctl_s cn52xxp1;
+	struct cvmx_pip_stat_ctl_s cn56xx;
+	struct cvmx_pip_stat_ctl_s cn56xxp1;
+	struct cvmx_pip_stat_ctl_s cn58xx;
+	struct cvmx_pip_stat_ctl_s cn58xxp1;
+};
+
+union cvmx_pip_stat_inb_errsx {
+	uint64_t u64;
+	struct cvmx_pip_stat_inb_errsx_s {
+		uint64_t reserved_16_63:48;
+		uint64_t errs:16;
+	} s;
+	struct cvmx_pip_stat_inb_errsx_s cn30xx;
+	struct cvmx_pip_stat_inb_errsx_s cn31xx;
+	struct cvmx_pip_stat_inb_errsx_s cn38xx;
+	struct cvmx_pip_stat_inb_errsx_s cn38xxp2;
+	struct cvmx_pip_stat_inb_errsx_s cn50xx;
+	struct cvmx_pip_stat_inb_errsx_s cn52xx;
+	struct cvmx_pip_stat_inb_errsx_s cn52xxp1;
+	struct cvmx_pip_stat_inb_errsx_s cn56xx;
+	struct cvmx_pip_stat_inb_errsx_s cn56xxp1;
+	struct cvmx_pip_stat_inb_errsx_s cn58xx;
+	struct cvmx_pip_stat_inb_errsx_s cn58xxp1;
+};
+
+union cvmx_pip_stat_inb_octsx {
+	uint64_t u64;
+	struct cvmx_pip_stat_inb_octsx_s {
+		uint64_t reserved_48_63:16;
+		uint64_t octs:48;
+	} s;
+	struct cvmx_pip_stat_inb_octsx_s cn30xx;
+	struct cvmx_pip_stat_inb_octsx_s cn31xx;
+	struct cvmx_pip_stat_inb_octsx_s cn38xx;
+	struct cvmx_pip_stat_inb_octsx_s cn38xxp2;
+	struct cvmx_pip_stat_inb_octsx_s cn50xx;
+	struct cvmx_pip_stat_inb_octsx_s cn52xx;
+	struct cvmx_pip_stat_inb_octsx_s cn52xxp1;
+	struct cvmx_pip_stat_inb_octsx_s cn56xx;
+	struct cvmx_pip_stat_inb_octsx_s cn56xxp1;
+	struct cvmx_pip_stat_inb_octsx_s cn58xx;
+	struct cvmx_pip_stat_inb_octsx_s cn58xxp1;
+};
+
+union cvmx_pip_stat_inb_pktsx {
+	uint64_t u64;
+	struct cvmx_pip_stat_inb_pktsx_s {
+		uint64_t reserved_32_63:32;
+		uint64_t pkts:32;
+	} s;
+	struct cvmx_pip_stat_inb_pktsx_s cn30xx;
+	struct cvmx_pip_stat_inb_pktsx_s cn31xx;
+	struct cvmx_pip_stat_inb_pktsx_s cn38xx;
+	struct cvmx_pip_stat_inb_pktsx_s cn38xxp2;
+	struct cvmx_pip_stat_inb_pktsx_s cn50xx;
+	struct cvmx_pip_stat_inb_pktsx_s cn52xx;
+	struct cvmx_pip_stat_inb_pktsx_s cn52xxp1;
+	struct cvmx_pip_stat_inb_pktsx_s cn56xx;
+	struct cvmx_pip_stat_inb_pktsx_s cn56xxp1;
+	struct cvmx_pip_stat_inb_pktsx_s cn58xx;
+	struct cvmx_pip_stat_inb_pktsx_s cn58xxp1;
+};
+
+union cvmx_pip_tag_incx {
+	uint64_t u64;
+	struct cvmx_pip_tag_incx_s {
+		uint64_t reserved_8_63:56;
+		uint64_t en:8;
+	} s;
+	struct cvmx_pip_tag_incx_s cn30xx;
+	struct cvmx_pip_tag_incx_s cn31xx;
+	struct cvmx_pip_tag_incx_s cn38xx;
+	struct cvmx_pip_tag_incx_s cn38xxp2;
+	struct cvmx_pip_tag_incx_s cn50xx;
+	struct cvmx_pip_tag_incx_s cn52xx;
+	struct cvmx_pip_tag_incx_s cn52xxp1;
+	struct cvmx_pip_tag_incx_s cn56xx;
+	struct cvmx_pip_tag_incx_s cn56xxp1;
+	struct cvmx_pip_tag_incx_s cn58xx;
+	struct cvmx_pip_tag_incx_s cn58xxp1;
+};
+
+union cvmx_pip_tag_mask {
+	uint64_t u64;
+	struct cvmx_pip_tag_mask_s {
+		uint64_t reserved_16_63:48;
+		uint64_t mask:16;
+	} s;
+	struct cvmx_pip_tag_mask_s cn30xx;
+	struct cvmx_pip_tag_mask_s cn31xx;
+	struct cvmx_pip_tag_mask_s cn38xx;
+	struct cvmx_pip_tag_mask_s cn38xxp2;
+	struct cvmx_pip_tag_mask_s cn50xx;
+	struct cvmx_pip_tag_mask_s cn52xx;
+	struct cvmx_pip_tag_mask_s cn52xxp1;
+	struct cvmx_pip_tag_mask_s cn56xx;
+	struct cvmx_pip_tag_mask_s cn56xxp1;
+	struct cvmx_pip_tag_mask_s cn58xx;
+	struct cvmx_pip_tag_mask_s cn58xxp1;
+};
+
+union cvmx_pip_tag_secret {
+	uint64_t u64;
+	struct cvmx_pip_tag_secret_s {
+		uint64_t reserved_32_63:32;
+		uint64_t dst:16;
+		uint64_t src:16;
+	} s;
+	struct cvmx_pip_tag_secret_s cn30xx;
+	struct cvmx_pip_tag_secret_s cn31xx;
+	struct cvmx_pip_tag_secret_s cn38xx;
+	struct cvmx_pip_tag_secret_s cn38xxp2;
+	struct cvmx_pip_tag_secret_s cn50xx;
+	struct cvmx_pip_tag_secret_s cn52xx;
+	struct cvmx_pip_tag_secret_s cn52xxp1;
+	struct cvmx_pip_tag_secret_s cn56xx;
+	struct cvmx_pip_tag_secret_s cn56xxp1;
+	struct cvmx_pip_tag_secret_s cn58xx;
+	struct cvmx_pip_tag_secret_s cn58xxp1;
+};
+
+union cvmx_pip_todo_entry {
+	uint64_t u64;
+	struct cvmx_pip_todo_entry_s {
+		uint64_t val:1;
+		uint64_t reserved_62_62:1;
+		uint64_t entry:62;
+	} s;
+	struct cvmx_pip_todo_entry_s cn30xx;
+	struct cvmx_pip_todo_entry_s cn31xx;
+	struct cvmx_pip_todo_entry_s cn38xx;
+	struct cvmx_pip_todo_entry_s cn38xxp2;
+	struct cvmx_pip_todo_entry_s cn50xx;
+	struct cvmx_pip_todo_entry_s cn52xx;
+	struct cvmx_pip_todo_entry_s cn52xxp1;
+	struct cvmx_pip_todo_entry_s cn56xx;
+	struct cvmx_pip_todo_entry_s cn56xxp1;
+	struct cvmx_pip_todo_entry_s cn58xx;
+	struct cvmx_pip_todo_entry_s cn58xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-pip.h b/drivers/staging/octeon/cvmx-pip.h
new file mode 100644
index 0000000..78dbce8
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-pip.h
@@ -0,0 +1,524 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Interface to the hardware Packet Input Processing unit.
+ *
+ */
+
+#ifndef __CVMX_PIP_H__
+#define __CVMX_PIP_H__
+
+#include "cvmx-wqe.h"
+#include "cvmx-fpa.h"
+#include "cvmx-pip-defs.h"
+
+#define CVMX_PIP_NUM_INPUT_PORTS                40
+#define CVMX_PIP_NUM_WATCHERS                   4
+
+/*
+ * Encodes the different error and exception codes
+ */
+typedef enum {
+	CVMX_PIP_L4_NO_ERR = 0ull,
+	/*
+	 * 1 = TCP (UDP) packet not long enough to cover TCP (UDP)
+	 * header
+	 */
+	CVMX_PIP_L4_MAL_ERR = 1ull,
+	/* 2  = TCP/UDP checksum failure */
+	CVMX_PIP_CHK_ERR = 2ull,
+	/*
+	 * 3 = TCP/UDP length check (TCP/UDP length does not match IP
+	 * length).
+	 */
+	CVMX_PIP_L4_LENGTH_ERR = 3ull,
+	/* 4  = illegal TCP/UDP port (either source or dest port is zero) */
+	CVMX_PIP_BAD_PRT_ERR = 4ull,
+	/* 8  = TCP flags = FIN only */
+	CVMX_PIP_TCP_FLG8_ERR = 8ull,
+	/* 9  = TCP flags = 0 */
+	CVMX_PIP_TCP_FLG9_ERR = 9ull,
+	/* 10 = TCP flags = FIN+RST+* */
+	CVMX_PIP_TCP_FLG10_ERR = 10ull,
+	/* 11 = TCP flags = SYN+URG+* */
+	CVMX_PIP_TCP_FLG11_ERR = 11ull,
+	/* 12 = TCP flags = SYN+RST+* */
+	CVMX_PIP_TCP_FLG12_ERR = 12ull,
+	/* 13 = TCP flags = SYN+FIN+* */
+	CVMX_PIP_TCP_FLG13_ERR = 13ull
+} cvmx_pip_l4_err_t;
+
+typedef enum {
+
+	CVMX_PIP_IP_NO_ERR = 0ull,
+	/* 1 = not IPv4 or IPv6 */
+	CVMX_PIP_NOT_IP = 1ull,
+	/* 2 = IPv4 header checksum violation */
+	CVMX_PIP_IPV4_HDR_CHK = 2ull,
+	/* 3 = malformed (packet not long enough to cover IP hdr) */
+	CVMX_PIP_IP_MAL_HDR = 3ull,
+	/* 4 = malformed (packet not long enough to cover len in IP hdr) */
+	CVMX_PIP_IP_MAL_PKT = 4ull,
+	/* 5 = TTL / hop count equal zero */
+	CVMX_PIP_TTL_HOP = 5ull,
+	/* 6 = IPv4 options / IPv6 early extension headers */
+	CVMX_PIP_OPTS = 6ull
+} cvmx_pip_ip_exc_t;
+
+/**
+ * NOTES
+ *       late collision (data received before collision)
+ *            late collisions cannot be detected by the receiver
+ *            they would appear as JAM bits which would appear as bad FCS
+ *            or carrier extend error which is CVMX_PIP_EXTEND_ERR
+ */
+typedef enum {
+	/* No error */
+	CVMX_PIP_RX_NO_ERR = 0ull,
+	/* RGM+SPI 1 = partially received packet (buffering/bandwidth
+	 * not adequate) */
+	CVMX_PIP_PARTIAL_ERR = 1ull,
+	/* RGM+SPI 2 = receive packet too large and truncated */
+	CVMX_PIP_JABBER_ERR = 2ull,
+	/*
+	 * RGM 3 = max frame error (pkt len > max frame len) (with FCS
+	 * error)
+	 */
+	CVMX_PIP_OVER_FCS_ERR = 3ull,
+	/* RGM+SPI 4 = max frame error (pkt len > max frame len) */
+	CVMX_PIP_OVER_ERR = 4ull,
+	/*
+	 * RGM 5 = nibble error (data not byte multiple - 100M and 10M
+	 * only)
+	 */
+	CVMX_PIP_ALIGN_ERR = 5ull,
+	/*
+	 * RGM 6 = min frame error (pkt len < min frame len) (with FCS
+	 * error)
+	 */
+	CVMX_PIP_UNDER_FCS_ERR = 6ull,
+	/* RGM     7 = FCS error */
+	CVMX_PIP_GMX_FCS_ERR = 7ull,
+	/* RGM+SPI 8 = min frame error (pkt len < min frame len) */
+	CVMX_PIP_UNDER_ERR = 8ull,
+	/* RGM     9 = Frame carrier extend error */
+	CVMX_PIP_EXTEND_ERR = 9ull,
+	/*
+	 * RGM 10 = length mismatch (len did not match len in L2
+	 * length/type)
+	 */
+	CVMX_PIP_LENGTH_ERR = 10ull,
+	/* RGM 11 = Frame error (some or all data bits marked err) */
+	CVMX_PIP_DAT_ERR = 11ull,
+	/*     SPI 11 = DIP4 error */
+	CVMX_PIP_DIP_ERR = 11ull,
+	/*
+	 * RGM 12 = packet was not large enough to pass the skipper -
+	 * no inspection could occur.
+	 */
+	CVMX_PIP_SKIP_ERR = 12ull,
+	/*
+	 * RGM 13 = studder error (data not repeated - 100M and 10M
+	 * only)
+	 */
+	CVMX_PIP_NIBBLE_ERR = 13ull,
+	/* RGM+SPI 16 = FCS error */
+	CVMX_PIP_PIP_FCS = 16L,
+	/*
+	 * RGM+SPI+PCI 17 = packet was not large enough to pass the
+	 * skipper - no inspection could occur.
+	 */
+	CVMX_PIP_PIP_SKIP_ERR = 17L,
+	/*
+	 * RGM+SPI+PCI 18 = malformed l2 (packet not long enough to
+	 * cover L2 hdr).
+	 */
+	CVMX_PIP_PIP_L2_MAL_HDR = 18L
+	/*
+	 * NOTES: xx = late collision (data received before collision)
+	 *       late collisions cannot be detected by the receiver
+	 *       they would appear as JAM bits which would appear as
+	 *       bad FCS or carrier extend error which is
+	 *       CVMX_PIP_EXTEND_ERR
+	 */
+} cvmx_pip_rcv_err_t;
+
+/**
+ * This defines the err_code field errors in the work Q entry
+ */
+typedef union {
+	cvmx_pip_l4_err_t l4_err;
+	cvmx_pip_ip_exc_t ip_exc;
+	cvmx_pip_rcv_err_t rcv_err;
+} cvmx_pip_err_t;
+
+/**
+ * Status statistics for a port
+ */
+typedef struct {
+	/* Inbound octets marked to be dropped by the IPD */
+	uint32_t dropped_octets;
+	/* Inbound packets marked to be dropped by the IPD */
+	uint32_t dropped_packets;
+	/* RAW PCI Packets received by PIP per port */
+	uint32_t pci_raw_packets;
+	/* Number of octets processed by PIP */
+	uint32_t octets;
+	/* Number of packets processed by PIP */
+	uint32_t packets;
+	/*
+	 * Number of indentified L2 multicast packets.  Does not
+	 * include broadcast packets.  Only includes packets whose
+	 * parse mode is SKIP_TO_L2
+	 */
+	uint32_t multicast_packets;
+	/*
+	 * Number of indentified L2 broadcast packets.  Does not
+	 * include multicast packets.  Only includes packets whose
+	 * parse mode is SKIP_TO_L2
+	 */
+	uint32_t broadcast_packets;
+	/* Number of 64B packets */
+	uint32_t len_64_packets;
+	/* Number of 65-127B packets */
+	uint32_t len_65_127_packets;
+	/* Number of 128-255B packets */
+	uint32_t len_128_255_packets;
+	/* Number of 256-511B packets */
+	uint32_t len_256_511_packets;
+	/* Number of 512-1023B packets */
+	uint32_t len_512_1023_packets;
+	/* Number of 1024-1518B packets */
+	uint32_t len_1024_1518_packets;
+	/* Number of 1519-max packets */
+	uint32_t len_1519_max_packets;
+	/* Number of packets with FCS or Align opcode errors */
+	uint32_t fcs_align_err_packets;
+	/* Number of packets with length < min */
+	uint32_t runt_packets;
+	/* Number of packets with length < min and FCS error */
+	uint32_t runt_crc_packets;
+	/* Number of packets with length > max */
+	uint32_t oversize_packets;
+	/* Number of packets with length > max and FCS error */
+	uint32_t oversize_crc_packets;
+	/* Number of packets without GMX/SPX/PCI errors received by PIP */
+	uint32_t inb_packets;
+	/*
+	 * Total number of octets from all packets received by PIP,
+	 * including CRC
+	 */
+	uint64_t inb_octets;
+	/* Number of packets with GMX/SPX/PCI errors received by PIP */
+	uint16_t inb_errors;
+} cvmx_pip_port_status_t;
+
+/**
+ * Definition of the PIP custom header that can be prepended
+ * to a packet by external hardware.
+ */
+typedef union {
+	uint64_t u64;
+	struct {
+		/*
+		 * Documented as R - Set if the Packet is RAWFULL. If
+		 * set, this header must be the full 8 bytes.
+		 */
+		uint64_t rawfull:1;
+		/* Must be zero */
+		uint64_t reserved0:5;
+		/* PIP parse mode for this packet */
+		uint64_t parse_mode:2;
+		/* Must be zero */
+		uint64_t reserved1:1;
+		/*
+		 * Skip amount, including this header, to the
+		 * beginning of the packet
+		 */
+		uint64_t skip_len:7;
+		/* Must be zero */
+		uint64_t reserved2:6;
+		/* POW input queue for this packet */
+		uint64_t qos:3;
+		/* POW input group for this packet */
+		uint64_t grp:4;
+		/*
+		 * Flag to store this packet in the work queue entry,
+		 * if possible
+		 */
+		uint64_t rs:1;
+		/* POW input tag type */
+		uint64_t tag_type:2;
+		/* POW input tag */
+		uint64_t tag:32;
+	} s;
+} cvmx_pip_pkt_inst_hdr_t;
+
+/* CSR typedefs have been moved to cvmx-csr-*.h */
+
+/**
+ * Configure an ethernet input port
+ *
+ * @port_num: Port number to configure
+ * @port_cfg: Port hardware configuration
+ * @port_tag_cfg:
+ *                 Port POW tagging configuration
+ */
+static inline void cvmx_pip_config_port(uint64_t port_num,
+					union cvmx_pip_prt_cfgx port_cfg,
+					union cvmx_pip_prt_tagx port_tag_cfg)
+{
+	cvmx_write_csr(CVMX_PIP_PRT_CFGX(port_num), port_cfg.u64);
+	cvmx_write_csr(CVMX_PIP_PRT_TAGX(port_num), port_tag_cfg.u64);
+}
+#if 0
+/**
+ * @deprecated      This function is a thin wrapper around the Pass1 version
+ *                  of the CVMX_PIP_QOS_WATCHX CSR; Pass2 has added a field for
+ *                  setting the group that is incompatible with this function,
+ *                  the preferred upgrade path is to use the CSR directly.
+ *
+ * Configure the global QoS packet watchers. Each watcher is
+ * capable of matching a field in a packet to determine the
+ * QoS queue for scheduling.
+ *
+ * @watcher:    Watcher number to configure (0 - 3).
+ * @match_type: Watcher match type
+ * @match_value:
+ *                   Value the watcher will match against
+ * @qos:        QoS queue for packets matching this watcher
+ */
+static inline void cvmx_pip_config_watcher(uint64_t watcher,
+					   cvmx_pip_qos_watch_types match_type,
+					   uint64_t match_value, uint64_t qos)
+{
+	cvmx_pip_port_watcher_cfg_t watcher_config;
+
+	watcher_config.u64 = 0;
+	watcher_config.s.match_type = match_type;
+	watcher_config.s.match_value = match_value;
+	watcher_config.s.qos = qos;
+
+	cvmx_write_csr(CVMX_PIP_QOS_WATCHX(watcher), watcher_config.u64);
+}
+#endif
+/**
+ * Configure the VLAN priority to QoS queue mapping.
+ *
+ * @vlan_priority:
+ *               VLAN priority (0-7)
+ * @qos:    QoS queue for packets matching this watcher
+ */
+static inline void cvmx_pip_config_vlan_qos(uint64_t vlan_priority,
+					    uint64_t qos)
+{
+	union cvmx_pip_qos_vlanx pip_qos_vlanx;
+	pip_qos_vlanx.u64 = 0;
+	pip_qos_vlanx.s.qos = qos;
+	cvmx_write_csr(CVMX_PIP_QOS_VLANX(vlan_priority), pip_qos_vlanx.u64);
+}
+
+/**
+ * Configure the Diffserv to QoS queue mapping.
+ *
+ * @diffserv: Diffserv field value (0-63)
+ * @qos:      QoS queue for packets matching this watcher
+ */
+static inline void cvmx_pip_config_diffserv_qos(uint64_t diffserv, uint64_t qos)
+{
+	union cvmx_pip_qos_diffx pip_qos_diffx;
+	pip_qos_diffx.u64 = 0;
+	pip_qos_diffx.s.qos = qos;
+	cvmx_write_csr(CVMX_PIP_QOS_DIFFX(diffserv), pip_qos_diffx.u64);
+}
+
+/**
+ * Get the status counters for a port.
+ *
+ * @port_num: Port number to get statistics for.
+ * @clear:    Set to 1 to clear the counters after they are read
+ * @status:   Where to put the results.
+ */
+static inline void cvmx_pip_get_port_status(uint64_t port_num, uint64_t clear,
+					    cvmx_pip_port_status_t *status)
+{
+	union cvmx_pip_stat_ctl pip_stat_ctl;
+	union cvmx_pip_stat0_prtx stat0;
+	union cvmx_pip_stat1_prtx stat1;
+	union cvmx_pip_stat2_prtx stat2;
+	union cvmx_pip_stat3_prtx stat3;
+	union cvmx_pip_stat4_prtx stat4;
+	union cvmx_pip_stat5_prtx stat5;
+	union cvmx_pip_stat6_prtx stat6;
+	union cvmx_pip_stat7_prtx stat7;
+	union cvmx_pip_stat8_prtx stat8;
+	union cvmx_pip_stat9_prtx stat9;
+	union cvmx_pip_stat_inb_pktsx pip_stat_inb_pktsx;
+	union cvmx_pip_stat_inb_octsx pip_stat_inb_octsx;
+	union cvmx_pip_stat_inb_errsx pip_stat_inb_errsx;
+
+	pip_stat_ctl.u64 = 0;
+	pip_stat_ctl.s.rdclr = clear;
+	cvmx_write_csr(CVMX_PIP_STAT_CTL, pip_stat_ctl.u64);
+
+	stat0.u64 = cvmx_read_csr(CVMX_PIP_STAT0_PRTX(port_num));
+	stat1.u64 = cvmx_read_csr(CVMX_PIP_STAT1_PRTX(port_num));
+	stat2.u64 = cvmx_read_csr(CVMX_PIP_STAT2_PRTX(port_num));
+	stat3.u64 = cvmx_read_csr(CVMX_PIP_STAT3_PRTX(port_num));
+	stat4.u64 = cvmx_read_csr(CVMX_PIP_STAT4_PRTX(port_num));
+	stat5.u64 = cvmx_read_csr(CVMX_PIP_STAT5_PRTX(port_num));
+	stat6.u64 = cvmx_read_csr(CVMX_PIP_STAT6_PRTX(port_num));
+	stat7.u64 = cvmx_read_csr(CVMX_PIP_STAT7_PRTX(port_num));
+	stat8.u64 = cvmx_read_csr(CVMX_PIP_STAT8_PRTX(port_num));
+	stat9.u64 = cvmx_read_csr(CVMX_PIP_STAT9_PRTX(port_num));
+	pip_stat_inb_pktsx.u64 =
+	    cvmx_read_csr(CVMX_PIP_STAT_INB_PKTSX(port_num));
+	pip_stat_inb_octsx.u64 =
+	    cvmx_read_csr(CVMX_PIP_STAT_INB_OCTSX(port_num));
+	pip_stat_inb_errsx.u64 =
+	    cvmx_read_csr(CVMX_PIP_STAT_INB_ERRSX(port_num));
+
+	status->dropped_octets = stat0.s.drp_octs;
+	status->dropped_packets = stat0.s.drp_pkts;
+	status->octets = stat1.s.octs;
+	status->pci_raw_packets = stat2.s.raw;
+	status->packets = stat2.s.pkts;
+	status->multicast_packets = stat3.s.mcst;
+	status->broadcast_packets = stat3.s.bcst;
+	status->len_64_packets = stat4.s.h64;
+	status->len_65_127_packets = stat4.s.h65to127;
+	status->len_128_255_packets = stat5.s.h128to255;
+	status->len_256_511_packets = stat5.s.h256to511;
+	status->len_512_1023_packets = stat6.s.h512to1023;
+	status->len_1024_1518_packets = stat6.s.h1024to1518;
+	status->len_1519_max_packets = stat7.s.h1519;
+	status->fcs_align_err_packets = stat7.s.fcs;
+	status->runt_packets = stat8.s.undersz;
+	status->runt_crc_packets = stat8.s.frag;
+	status->oversize_packets = stat9.s.oversz;
+	status->oversize_crc_packets = stat9.s.jabber;
+	status->inb_packets = pip_stat_inb_pktsx.s.pkts;
+	status->inb_octets = pip_stat_inb_octsx.s.octs;
+	status->inb_errors = pip_stat_inb_errsx.s.errs;
+
+	if (cvmx_octeon_is_pass1()) {
+		/*
+		 * Kludge to fix Octeon Pass 1 errata - Drop counts
+		 * don't work.
+		 */
+		if (status->inb_packets > status->packets)
+			status->dropped_packets =
+			    status->inb_packets - status->packets;
+		else
+			status->dropped_packets = 0;
+		if (status->inb_octets - status->inb_packets * 4 >
+		    status->octets)
+			status->dropped_octets =
+			    status->inb_octets - status->inb_packets * 4 -
+			    status->octets;
+		else
+			status->dropped_octets = 0;
+	}
+}
+
+/**
+ * Configure the hardware CRC engine
+ *
+ * @interface: Interface to configure (0 or 1)
+ * @invert_result:
+ *                 Invert the result of the CRC
+ * @reflect:  Reflect
+ * @initialization_vector:
+ *                 CRC initialization vector
+ */
+static inline void cvmx_pip_config_crc(uint64_t interface,
+				       uint64_t invert_result, uint64_t reflect,
+				       uint32_t initialization_vector)
+{
+	if (OCTEON_IS_MODEL(OCTEON_CN38XX) || OCTEON_IS_MODEL(OCTEON_CN58XX)) {
+		union cvmx_pip_crc_ctlx config;
+		union cvmx_pip_crc_ivx pip_crc_ivx;
+
+		config.u64 = 0;
+		config.s.invres = invert_result;
+		config.s.reflect = reflect;
+		cvmx_write_csr(CVMX_PIP_CRC_CTLX(interface), config.u64);
+
+		pip_crc_ivx.u64 = 0;
+		pip_crc_ivx.s.iv = initialization_vector;
+		cvmx_write_csr(CVMX_PIP_CRC_IVX(interface), pip_crc_ivx.u64);
+	}
+}
+
+/**
+ * Clear all bits in a tag mask. This should be called on
+ * startup before any calls to cvmx_pip_tag_mask_set. Each bit
+ * set in the final mask represent a byte used in the packet for
+ * tag generation.
+ *
+ * @mask_index: Which tag mask to clear (0..3)
+ */
+static inline void cvmx_pip_tag_mask_clear(uint64_t mask_index)
+{
+	uint64_t index;
+	union cvmx_pip_tag_incx pip_tag_incx;
+	pip_tag_incx.u64 = 0;
+	pip_tag_incx.s.en = 0;
+	for (index = mask_index * 16; index < (mask_index + 1) * 16; index++)
+		cvmx_write_csr(CVMX_PIP_TAG_INCX(index), pip_tag_incx.u64);
+}
+
+/**
+ * Sets a range of bits in the tag mask. The tag mask is used
+ * when the cvmx_pip_port_tag_cfg_t tag_mode is non zero.
+ * There are four separate masks that can be configured.
+ *
+ * @mask_index: Which tag mask to modify (0..3)
+ * @offset: Offset into the bitmask to set bits at. Use the GCC macro
+ *          offsetof() to determine the offsets into packet headers.
+ *          For example, offsetof(ethhdr, protocol) returns the offset
+ *          of the ethernet protocol field.  The bitmask selects which
+ *          bytes to include the the tag, with bit offset X selecting
+ *          byte at offset X from the beginning of the packet data.
+ * @len:    Number of bytes to include. Usually this is the sizeof()
+ *          the field.
+ */
+static inline void cvmx_pip_tag_mask_set(uint64_t mask_index, uint64_t offset,
+					 uint64_t len)
+{
+	while (len--) {
+		union cvmx_pip_tag_incx pip_tag_incx;
+		uint64_t index = mask_index * 16 + offset / 8;
+		pip_tag_incx.u64 = cvmx_read_csr(CVMX_PIP_TAG_INCX(index));
+		pip_tag_incx.s.en |= 0x80 >> (offset & 0x7);
+		cvmx_write_csr(CVMX_PIP_TAG_INCX(index), pip_tag_incx.u64);
+		offset++;
+	}
+}
+
+#endif /*  __CVMX_PIP_H__ */
diff --git a/drivers/staging/octeon/cvmx-pko-defs.h b/drivers/staging/octeon/cvmx-pko-defs.h
new file mode 100644
index 0000000..50e779c
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-pko-defs.h
@@ -0,0 +1,1133 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_PKO_DEFS_H__
+#define __CVMX_PKO_DEFS_H__
+
+#define CVMX_PKO_MEM_COUNT0 \
+	 CVMX_ADD_IO_SEG(0x0001180050001080ull)
+#define CVMX_PKO_MEM_COUNT1 \
+	 CVMX_ADD_IO_SEG(0x0001180050001088ull)
+#define CVMX_PKO_MEM_DEBUG0 \
+	 CVMX_ADD_IO_SEG(0x0001180050001100ull)
+#define CVMX_PKO_MEM_DEBUG1 \
+	 CVMX_ADD_IO_SEG(0x0001180050001108ull)
+#define CVMX_PKO_MEM_DEBUG10 \
+	 CVMX_ADD_IO_SEG(0x0001180050001150ull)
+#define CVMX_PKO_MEM_DEBUG11 \
+	 CVMX_ADD_IO_SEG(0x0001180050001158ull)
+#define CVMX_PKO_MEM_DEBUG12 \
+	 CVMX_ADD_IO_SEG(0x0001180050001160ull)
+#define CVMX_PKO_MEM_DEBUG13 \
+	 CVMX_ADD_IO_SEG(0x0001180050001168ull)
+#define CVMX_PKO_MEM_DEBUG14 \
+	 CVMX_ADD_IO_SEG(0x0001180050001170ull)
+#define CVMX_PKO_MEM_DEBUG2 \
+	 CVMX_ADD_IO_SEG(0x0001180050001110ull)
+#define CVMX_PKO_MEM_DEBUG3 \
+	 CVMX_ADD_IO_SEG(0x0001180050001118ull)
+#define CVMX_PKO_MEM_DEBUG4 \
+	 CVMX_ADD_IO_SEG(0x0001180050001120ull)
+#define CVMX_PKO_MEM_DEBUG5 \
+	 CVMX_ADD_IO_SEG(0x0001180050001128ull)
+#define CVMX_PKO_MEM_DEBUG6 \
+	 CVMX_ADD_IO_SEG(0x0001180050001130ull)
+#define CVMX_PKO_MEM_DEBUG7 \
+	 CVMX_ADD_IO_SEG(0x0001180050001138ull)
+#define CVMX_PKO_MEM_DEBUG8 \
+	 CVMX_ADD_IO_SEG(0x0001180050001140ull)
+#define CVMX_PKO_MEM_DEBUG9 \
+	 CVMX_ADD_IO_SEG(0x0001180050001148ull)
+#define CVMX_PKO_MEM_PORT_PTRS \
+	 CVMX_ADD_IO_SEG(0x0001180050001010ull)
+#define CVMX_PKO_MEM_PORT_QOS \
+	 CVMX_ADD_IO_SEG(0x0001180050001018ull)
+#define CVMX_PKO_MEM_PORT_RATE0 \
+	 CVMX_ADD_IO_SEG(0x0001180050001020ull)
+#define CVMX_PKO_MEM_PORT_RATE1 \
+	 CVMX_ADD_IO_SEG(0x0001180050001028ull)
+#define CVMX_PKO_MEM_QUEUE_PTRS \
+	 CVMX_ADD_IO_SEG(0x0001180050001000ull)
+#define CVMX_PKO_MEM_QUEUE_QOS \
+	 CVMX_ADD_IO_SEG(0x0001180050001008ull)
+#define CVMX_PKO_REG_BIST_RESULT \
+	 CVMX_ADD_IO_SEG(0x0001180050000080ull)
+#define CVMX_PKO_REG_CMD_BUF \
+	 CVMX_ADD_IO_SEG(0x0001180050000010ull)
+#define CVMX_PKO_REG_CRC_CTLX(offset) \
+	 CVMX_ADD_IO_SEG(0x0001180050000028ull + (((offset) & 1) * 8))
+#define CVMX_PKO_REG_CRC_ENABLE \
+	 CVMX_ADD_IO_SEG(0x0001180050000020ull)
+#define CVMX_PKO_REG_CRC_IVX(offset) \
+	 CVMX_ADD_IO_SEG(0x0001180050000038ull + (((offset) & 1) * 8))
+#define CVMX_PKO_REG_DEBUG0 \
+	 CVMX_ADD_IO_SEG(0x0001180050000098ull)
+#define CVMX_PKO_REG_DEBUG1 \
+	 CVMX_ADD_IO_SEG(0x00011800500000A0ull)
+#define CVMX_PKO_REG_DEBUG2 \
+	 CVMX_ADD_IO_SEG(0x00011800500000A8ull)
+#define CVMX_PKO_REG_DEBUG3 \
+	 CVMX_ADD_IO_SEG(0x00011800500000B0ull)
+#define CVMX_PKO_REG_ENGINE_INFLIGHT \
+	 CVMX_ADD_IO_SEG(0x0001180050000050ull)
+#define CVMX_PKO_REG_ENGINE_THRESH \
+	 CVMX_ADD_IO_SEG(0x0001180050000058ull)
+#define CVMX_PKO_REG_ERROR \
+	 CVMX_ADD_IO_SEG(0x0001180050000088ull)
+#define CVMX_PKO_REG_FLAGS \
+	 CVMX_ADD_IO_SEG(0x0001180050000000ull)
+#define CVMX_PKO_REG_GMX_PORT_MODE \
+	 CVMX_ADD_IO_SEG(0x0001180050000018ull)
+#define CVMX_PKO_REG_INT_MASK \
+	 CVMX_ADD_IO_SEG(0x0001180050000090ull)
+#define CVMX_PKO_REG_QUEUE_MODE \
+	 CVMX_ADD_IO_SEG(0x0001180050000048ull)
+#define CVMX_PKO_REG_QUEUE_PTRS1 \
+	 CVMX_ADD_IO_SEG(0x0001180050000100ull)
+#define CVMX_PKO_REG_READ_IDX \
+	 CVMX_ADD_IO_SEG(0x0001180050000008ull)
+
+union cvmx_pko_mem_count0 {
+	uint64_t u64;
+	struct cvmx_pko_mem_count0_s {
+		uint64_t reserved_32_63:32;
+		uint64_t count:32;
+	} s;
+	struct cvmx_pko_mem_count0_s cn30xx;
+	struct cvmx_pko_mem_count0_s cn31xx;
+	struct cvmx_pko_mem_count0_s cn38xx;
+	struct cvmx_pko_mem_count0_s cn38xxp2;
+	struct cvmx_pko_mem_count0_s cn50xx;
+	struct cvmx_pko_mem_count0_s cn52xx;
+	struct cvmx_pko_mem_count0_s cn52xxp1;
+	struct cvmx_pko_mem_count0_s cn56xx;
+	struct cvmx_pko_mem_count0_s cn56xxp1;
+	struct cvmx_pko_mem_count0_s cn58xx;
+	struct cvmx_pko_mem_count0_s cn58xxp1;
+};
+
+union cvmx_pko_mem_count1 {
+	uint64_t u64;
+	struct cvmx_pko_mem_count1_s {
+		uint64_t reserved_48_63:16;
+		uint64_t count:48;
+	} s;
+	struct cvmx_pko_mem_count1_s cn30xx;
+	struct cvmx_pko_mem_count1_s cn31xx;
+	struct cvmx_pko_mem_count1_s cn38xx;
+	struct cvmx_pko_mem_count1_s cn38xxp2;
+	struct cvmx_pko_mem_count1_s cn50xx;
+	struct cvmx_pko_mem_count1_s cn52xx;
+	struct cvmx_pko_mem_count1_s cn52xxp1;
+	struct cvmx_pko_mem_count1_s cn56xx;
+	struct cvmx_pko_mem_count1_s cn56xxp1;
+	struct cvmx_pko_mem_count1_s cn58xx;
+	struct cvmx_pko_mem_count1_s cn58xxp1;
+};
+
+union cvmx_pko_mem_debug0 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug0_s {
+		uint64_t fau:28;
+		uint64_t cmd:14;
+		uint64_t segs:6;
+		uint64_t size:16;
+	} s;
+	struct cvmx_pko_mem_debug0_s cn30xx;
+	struct cvmx_pko_mem_debug0_s cn31xx;
+	struct cvmx_pko_mem_debug0_s cn38xx;
+	struct cvmx_pko_mem_debug0_s cn38xxp2;
+	struct cvmx_pko_mem_debug0_s cn50xx;
+	struct cvmx_pko_mem_debug0_s cn52xx;
+	struct cvmx_pko_mem_debug0_s cn52xxp1;
+	struct cvmx_pko_mem_debug0_s cn56xx;
+	struct cvmx_pko_mem_debug0_s cn56xxp1;
+	struct cvmx_pko_mem_debug0_s cn58xx;
+	struct cvmx_pko_mem_debug0_s cn58xxp1;
+};
+
+union cvmx_pko_mem_debug1 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug1_s {
+		uint64_t i:1;
+		uint64_t back:4;
+		uint64_t pool:3;
+		uint64_t size:16;
+		uint64_t ptr:40;
+	} s;
+	struct cvmx_pko_mem_debug1_s cn30xx;
+	struct cvmx_pko_mem_debug1_s cn31xx;
+	struct cvmx_pko_mem_debug1_s cn38xx;
+	struct cvmx_pko_mem_debug1_s cn38xxp2;
+	struct cvmx_pko_mem_debug1_s cn50xx;
+	struct cvmx_pko_mem_debug1_s cn52xx;
+	struct cvmx_pko_mem_debug1_s cn52xxp1;
+	struct cvmx_pko_mem_debug1_s cn56xx;
+	struct cvmx_pko_mem_debug1_s cn56xxp1;
+	struct cvmx_pko_mem_debug1_s cn58xx;
+	struct cvmx_pko_mem_debug1_s cn58xxp1;
+};
+
+union cvmx_pko_mem_debug10 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug10_s {
+		uint64_t reserved_0_63:64;
+	} s;
+	struct cvmx_pko_mem_debug10_cn30xx {
+		uint64_t fau:28;
+		uint64_t cmd:14;
+		uint64_t segs:6;
+		uint64_t size:16;
+	} cn30xx;
+	struct cvmx_pko_mem_debug10_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug10_cn30xx cn38xx;
+	struct cvmx_pko_mem_debug10_cn30xx cn38xxp2;
+	struct cvmx_pko_mem_debug10_cn50xx {
+		uint64_t reserved_49_63:15;
+		uint64_t ptrs1:17;
+		uint64_t reserved_17_31:15;
+		uint64_t ptrs2:17;
+	} cn50xx;
+	struct cvmx_pko_mem_debug10_cn50xx cn52xx;
+	struct cvmx_pko_mem_debug10_cn50xx cn52xxp1;
+	struct cvmx_pko_mem_debug10_cn50xx cn56xx;
+	struct cvmx_pko_mem_debug10_cn50xx cn56xxp1;
+	struct cvmx_pko_mem_debug10_cn50xx cn58xx;
+	struct cvmx_pko_mem_debug10_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_mem_debug11 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug11_s {
+		uint64_t i:1;
+		uint64_t back:4;
+		uint64_t pool:3;
+		uint64_t size:16;
+		uint64_t reserved_0_39:40;
+	} s;
+	struct cvmx_pko_mem_debug11_cn30xx {
+		uint64_t i:1;
+		uint64_t back:4;
+		uint64_t pool:3;
+		uint64_t size:16;
+		uint64_t ptr:40;
+	} cn30xx;
+	struct cvmx_pko_mem_debug11_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug11_cn30xx cn38xx;
+	struct cvmx_pko_mem_debug11_cn30xx cn38xxp2;
+	struct cvmx_pko_mem_debug11_cn50xx {
+		uint64_t reserved_23_63:41;
+		uint64_t maj:1;
+		uint64_t uid:3;
+		uint64_t sop:1;
+		uint64_t len:1;
+		uint64_t chk:1;
+		uint64_t cnt:13;
+		uint64_t mod:3;
+	} cn50xx;
+	struct cvmx_pko_mem_debug11_cn50xx cn52xx;
+	struct cvmx_pko_mem_debug11_cn50xx cn52xxp1;
+	struct cvmx_pko_mem_debug11_cn50xx cn56xx;
+	struct cvmx_pko_mem_debug11_cn50xx cn56xxp1;
+	struct cvmx_pko_mem_debug11_cn50xx cn58xx;
+	struct cvmx_pko_mem_debug11_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_mem_debug12 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug12_s {
+		uint64_t reserved_0_63:64;
+	} s;
+	struct cvmx_pko_mem_debug12_cn30xx {
+		uint64_t data:64;
+	} cn30xx;
+	struct cvmx_pko_mem_debug12_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug12_cn30xx cn38xx;
+	struct cvmx_pko_mem_debug12_cn30xx cn38xxp2;
+	struct cvmx_pko_mem_debug12_cn50xx {
+		uint64_t fau:28;
+		uint64_t cmd:14;
+		uint64_t segs:6;
+		uint64_t size:16;
+	} cn50xx;
+	struct cvmx_pko_mem_debug12_cn50xx cn52xx;
+	struct cvmx_pko_mem_debug12_cn50xx cn52xxp1;
+	struct cvmx_pko_mem_debug12_cn50xx cn56xx;
+	struct cvmx_pko_mem_debug12_cn50xx cn56xxp1;
+	struct cvmx_pko_mem_debug12_cn50xx cn58xx;
+	struct cvmx_pko_mem_debug12_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_mem_debug13 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug13_s {
+		uint64_t i:1;
+		uint64_t back:4;
+		uint64_t pool:3;
+		uint64_t reserved_0_55:56;
+	} s;
+	struct cvmx_pko_mem_debug13_cn30xx {
+		uint64_t reserved_51_63:13;
+		uint64_t widx:17;
+		uint64_t ridx2:17;
+		uint64_t widx2:17;
+	} cn30xx;
+	struct cvmx_pko_mem_debug13_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug13_cn30xx cn38xx;
+	struct cvmx_pko_mem_debug13_cn30xx cn38xxp2;
+	struct cvmx_pko_mem_debug13_cn50xx {
+		uint64_t i:1;
+		uint64_t back:4;
+		uint64_t pool:3;
+		uint64_t size:16;
+		uint64_t ptr:40;
+	} cn50xx;
+	struct cvmx_pko_mem_debug13_cn50xx cn52xx;
+	struct cvmx_pko_mem_debug13_cn50xx cn52xxp1;
+	struct cvmx_pko_mem_debug13_cn50xx cn56xx;
+	struct cvmx_pko_mem_debug13_cn50xx cn56xxp1;
+	struct cvmx_pko_mem_debug13_cn50xx cn58xx;
+	struct cvmx_pko_mem_debug13_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_mem_debug14 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug14_s {
+		uint64_t reserved_0_63:64;
+	} s;
+	struct cvmx_pko_mem_debug14_cn30xx {
+		uint64_t reserved_17_63:47;
+		uint64_t ridx:17;
+	} cn30xx;
+	struct cvmx_pko_mem_debug14_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug14_cn30xx cn38xx;
+	struct cvmx_pko_mem_debug14_cn30xx cn38xxp2;
+	struct cvmx_pko_mem_debug14_cn52xx {
+		uint64_t data:64;
+	} cn52xx;
+	struct cvmx_pko_mem_debug14_cn52xx cn52xxp1;
+	struct cvmx_pko_mem_debug14_cn52xx cn56xx;
+	struct cvmx_pko_mem_debug14_cn52xx cn56xxp1;
+};
+
+union cvmx_pko_mem_debug2 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug2_s {
+		uint64_t i:1;
+		uint64_t back:4;
+		uint64_t pool:3;
+		uint64_t size:16;
+		uint64_t ptr:40;
+	} s;
+	struct cvmx_pko_mem_debug2_s cn30xx;
+	struct cvmx_pko_mem_debug2_s cn31xx;
+	struct cvmx_pko_mem_debug2_s cn38xx;
+	struct cvmx_pko_mem_debug2_s cn38xxp2;
+	struct cvmx_pko_mem_debug2_s cn50xx;
+	struct cvmx_pko_mem_debug2_s cn52xx;
+	struct cvmx_pko_mem_debug2_s cn52xxp1;
+	struct cvmx_pko_mem_debug2_s cn56xx;
+	struct cvmx_pko_mem_debug2_s cn56xxp1;
+	struct cvmx_pko_mem_debug2_s cn58xx;
+	struct cvmx_pko_mem_debug2_s cn58xxp1;
+};
+
+union cvmx_pko_mem_debug3 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug3_s {
+		uint64_t reserved_0_63:64;
+	} s;
+	struct cvmx_pko_mem_debug3_cn30xx {
+		uint64_t i:1;
+		uint64_t back:4;
+		uint64_t pool:3;
+		uint64_t size:16;
+		uint64_t ptr:40;
+	} cn30xx;
+	struct cvmx_pko_mem_debug3_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug3_cn30xx cn38xx;
+	struct cvmx_pko_mem_debug3_cn30xx cn38xxp2;
+	struct cvmx_pko_mem_debug3_cn50xx {
+		uint64_t data:64;
+	} cn50xx;
+	struct cvmx_pko_mem_debug3_cn50xx cn52xx;
+	struct cvmx_pko_mem_debug3_cn50xx cn52xxp1;
+	struct cvmx_pko_mem_debug3_cn50xx cn56xx;
+	struct cvmx_pko_mem_debug3_cn50xx cn56xxp1;
+	struct cvmx_pko_mem_debug3_cn50xx cn58xx;
+	struct cvmx_pko_mem_debug3_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_mem_debug4 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug4_s {
+		uint64_t reserved_0_63:64;
+	} s;
+	struct cvmx_pko_mem_debug4_cn30xx {
+		uint64_t data:64;
+	} cn30xx;
+	struct cvmx_pko_mem_debug4_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug4_cn30xx cn38xx;
+	struct cvmx_pko_mem_debug4_cn30xx cn38xxp2;
+	struct cvmx_pko_mem_debug4_cn50xx {
+		uint64_t cmnd_segs:3;
+		uint64_t cmnd_siz:16;
+		uint64_t cmnd_off:6;
+		uint64_t uid:3;
+		uint64_t dread_sop:1;
+		uint64_t init_dwrite:1;
+		uint64_t chk_once:1;
+		uint64_t chk_mode:1;
+		uint64_t active:1;
+		uint64_t static_p:1;
+		uint64_t qos:3;
+		uint64_t qcb_ridx:5;
+		uint64_t qid_off_max:4;
+		uint64_t qid_off:4;
+		uint64_t qid_base:8;
+		uint64_t wait:1;
+		uint64_t minor:2;
+		uint64_t major:3;
+	} cn50xx;
+	struct cvmx_pko_mem_debug4_cn52xx {
+		uint64_t curr_siz:8;
+		uint64_t curr_off:16;
+		uint64_t cmnd_segs:6;
+		uint64_t cmnd_siz:16;
+		uint64_t cmnd_off:6;
+		uint64_t uid:2;
+		uint64_t dread_sop:1;
+		uint64_t init_dwrite:1;
+		uint64_t chk_once:1;
+		uint64_t chk_mode:1;
+		uint64_t wait:1;
+		uint64_t minor:2;
+		uint64_t major:3;
+	} cn52xx;
+	struct cvmx_pko_mem_debug4_cn52xx cn52xxp1;
+	struct cvmx_pko_mem_debug4_cn52xx cn56xx;
+	struct cvmx_pko_mem_debug4_cn52xx cn56xxp1;
+	struct cvmx_pko_mem_debug4_cn50xx cn58xx;
+	struct cvmx_pko_mem_debug4_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_mem_debug5 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug5_s {
+		uint64_t reserved_0_63:64;
+	} s;
+	struct cvmx_pko_mem_debug5_cn30xx {
+		uint64_t dwri_mod:1;
+		uint64_t dwri_sop:1;
+		uint64_t dwri_len:1;
+		uint64_t dwri_cnt:13;
+		uint64_t cmnd_siz:16;
+		uint64_t uid:1;
+		uint64_t xfer_wor:1;
+		uint64_t xfer_dwr:1;
+		uint64_t cbuf_fre:1;
+		uint64_t reserved_27_27:1;
+		uint64_t chk_mode:1;
+		uint64_t active:1;
+		uint64_t qos:3;
+		uint64_t qcb_ridx:5;
+		uint64_t qid_off:3;
+		uint64_t qid_base:7;
+		uint64_t wait:1;
+		uint64_t minor:2;
+		uint64_t major:4;
+	} cn30xx;
+	struct cvmx_pko_mem_debug5_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug5_cn30xx cn38xx;
+	struct cvmx_pko_mem_debug5_cn30xx cn38xxp2;
+	struct cvmx_pko_mem_debug5_cn50xx {
+		uint64_t curr_ptr:29;
+		uint64_t curr_siz:16;
+		uint64_t curr_off:16;
+		uint64_t cmnd_segs:3;
+	} cn50xx;
+	struct cvmx_pko_mem_debug5_cn52xx {
+		uint64_t reserved_54_63:10;
+		uint64_t nxt_inflt:6;
+		uint64_t curr_ptr:40;
+		uint64_t curr_siz:8;
+	} cn52xx;
+	struct cvmx_pko_mem_debug5_cn52xx cn52xxp1;
+	struct cvmx_pko_mem_debug5_cn52xx cn56xx;
+	struct cvmx_pko_mem_debug5_cn52xx cn56xxp1;
+	struct cvmx_pko_mem_debug5_cn50xx cn58xx;
+	struct cvmx_pko_mem_debug5_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_mem_debug6 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug6_s {
+		uint64_t reserved_37_63:27;
+		uint64_t qid_offres:4;
+		uint64_t qid_offths:4;
+		uint64_t preempter:1;
+		uint64_t preemptee:1;
+		uint64_t preempted:1;
+		uint64_t active:1;
+		uint64_t statc:1;
+		uint64_t qos:3;
+		uint64_t qcb_ridx:5;
+		uint64_t qid_offmax:4;
+		uint64_t reserved_0_11:12;
+	} s;
+	struct cvmx_pko_mem_debug6_cn30xx {
+		uint64_t reserved_11_63:53;
+		uint64_t qid_offm:3;
+		uint64_t static_p:1;
+		uint64_t work_min:3;
+		uint64_t dwri_chk:1;
+		uint64_t dwri_uid:1;
+		uint64_t dwri_mod:2;
+	} cn30xx;
+	struct cvmx_pko_mem_debug6_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug6_cn30xx cn38xx;
+	struct cvmx_pko_mem_debug6_cn30xx cn38xxp2;
+	struct cvmx_pko_mem_debug6_cn50xx {
+		uint64_t reserved_11_63:53;
+		uint64_t curr_ptr:11;
+	} cn50xx;
+	struct cvmx_pko_mem_debug6_cn52xx {
+		uint64_t reserved_37_63:27;
+		uint64_t qid_offres:4;
+		uint64_t qid_offths:4;
+		uint64_t preempter:1;
+		uint64_t preemptee:1;
+		uint64_t preempted:1;
+		uint64_t active:1;
+		uint64_t statc:1;
+		uint64_t qos:3;
+		uint64_t qcb_ridx:5;
+		uint64_t qid_offmax:4;
+		uint64_t qid_off:4;
+		uint64_t qid_base:8;
+	} cn52xx;
+	struct cvmx_pko_mem_debug6_cn52xx cn52xxp1;
+	struct cvmx_pko_mem_debug6_cn52xx cn56xx;
+	struct cvmx_pko_mem_debug6_cn52xx cn56xxp1;
+	struct cvmx_pko_mem_debug6_cn50xx cn58xx;
+	struct cvmx_pko_mem_debug6_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_mem_debug7 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug7_s {
+		uint64_t qos:5;
+		uint64_t tail:1;
+		uint64_t reserved_0_57:58;
+	} s;
+	struct cvmx_pko_mem_debug7_cn30xx {
+		uint64_t reserved_58_63:6;
+		uint64_t dwb:9;
+		uint64_t start:33;
+		uint64_t size:16;
+	} cn30xx;
+	struct cvmx_pko_mem_debug7_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug7_cn30xx cn38xx;
+	struct cvmx_pko_mem_debug7_cn30xx cn38xxp2;
+	struct cvmx_pko_mem_debug7_cn50xx {
+		uint64_t qos:5;
+		uint64_t tail:1;
+		uint64_t buf_siz:13;
+		uint64_t buf_ptr:33;
+		uint64_t qcb_widx:6;
+		uint64_t qcb_ridx:6;
+	} cn50xx;
+	struct cvmx_pko_mem_debug7_cn50xx cn52xx;
+	struct cvmx_pko_mem_debug7_cn50xx cn52xxp1;
+	struct cvmx_pko_mem_debug7_cn50xx cn56xx;
+	struct cvmx_pko_mem_debug7_cn50xx cn56xxp1;
+	struct cvmx_pko_mem_debug7_cn50xx cn58xx;
+	struct cvmx_pko_mem_debug7_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_mem_debug8 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug8_s {
+		uint64_t reserved_59_63:5;
+		uint64_t tail:1;
+		uint64_t buf_siz:13;
+		uint64_t reserved_0_44:45;
+	} s;
+	struct cvmx_pko_mem_debug8_cn30xx {
+		uint64_t qos:5;
+		uint64_t tail:1;
+		uint64_t buf_siz:13;
+		uint64_t buf_ptr:33;
+		uint64_t qcb_widx:6;
+		uint64_t qcb_ridx:6;
+	} cn30xx;
+	struct cvmx_pko_mem_debug8_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug8_cn30xx cn38xx;
+	struct cvmx_pko_mem_debug8_cn30xx cn38xxp2;
+	struct cvmx_pko_mem_debug8_cn50xx {
+		uint64_t reserved_28_63:36;
+		uint64_t doorbell:20;
+		uint64_t reserved_6_7:2;
+		uint64_t static_p:1;
+		uint64_t s_tail:1;
+		uint64_t static_q:1;
+		uint64_t qos:3;
+	} cn50xx;
+	struct cvmx_pko_mem_debug8_cn52xx {
+		uint64_t reserved_29_63:35;
+		uint64_t preempter:1;
+		uint64_t doorbell:20;
+		uint64_t reserved_7_7:1;
+		uint64_t preemptee:1;
+		uint64_t static_p:1;
+		uint64_t s_tail:1;
+		uint64_t static_q:1;
+		uint64_t qos:3;
+	} cn52xx;
+	struct cvmx_pko_mem_debug8_cn52xx cn52xxp1;
+	struct cvmx_pko_mem_debug8_cn52xx cn56xx;
+	struct cvmx_pko_mem_debug8_cn52xx cn56xxp1;
+	struct cvmx_pko_mem_debug8_cn50xx cn58xx;
+	struct cvmx_pko_mem_debug8_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_mem_debug9 {
+	uint64_t u64;
+	struct cvmx_pko_mem_debug9_s {
+		uint64_t reserved_49_63:15;
+		uint64_t ptrs0:17;
+		uint64_t reserved_0_31:32;
+	} s;
+	struct cvmx_pko_mem_debug9_cn30xx {
+		uint64_t reserved_28_63:36;
+		uint64_t doorbell:20;
+		uint64_t reserved_5_7:3;
+		uint64_t s_tail:1;
+		uint64_t static_q:1;
+		uint64_t qos:3;
+	} cn30xx;
+	struct cvmx_pko_mem_debug9_cn30xx cn31xx;
+	struct cvmx_pko_mem_debug9_cn38xx {
+		uint64_t reserved_28_63:36;
+		uint64_t doorbell:20;
+		uint64_t reserved_6_7:2;
+		uint64_t static_p:1;
+		uint64_t s_tail:1;
+		uint64_t static_q:1;
+		uint64_t qos:3;
+	} cn38xx;
+	struct cvmx_pko_mem_debug9_cn38xx cn38xxp2;
+	struct cvmx_pko_mem_debug9_cn50xx {
+		uint64_t reserved_49_63:15;
+		uint64_t ptrs0:17;
+		uint64_t reserved_17_31:15;
+		uint64_t ptrs3:17;
+	} cn50xx;
+	struct cvmx_pko_mem_debug9_cn50xx cn52xx;
+	struct cvmx_pko_mem_debug9_cn50xx cn52xxp1;
+	struct cvmx_pko_mem_debug9_cn50xx cn56xx;
+	struct cvmx_pko_mem_debug9_cn50xx cn56xxp1;
+	struct cvmx_pko_mem_debug9_cn50xx cn58xx;
+	struct cvmx_pko_mem_debug9_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_mem_port_ptrs {
+	uint64_t u64;
+	struct cvmx_pko_mem_port_ptrs_s {
+		uint64_t reserved_62_63:2;
+		uint64_t static_p:1;
+		uint64_t qos_mask:8;
+		uint64_t reserved_16_52:37;
+		uint64_t bp_port:6;
+		uint64_t eid:4;
+		uint64_t pid:6;
+	} s;
+	struct cvmx_pko_mem_port_ptrs_s cn52xx;
+	struct cvmx_pko_mem_port_ptrs_s cn52xxp1;
+	struct cvmx_pko_mem_port_ptrs_s cn56xx;
+	struct cvmx_pko_mem_port_ptrs_s cn56xxp1;
+};
+
+union cvmx_pko_mem_port_qos {
+	uint64_t u64;
+	struct cvmx_pko_mem_port_qos_s {
+		uint64_t reserved_61_63:3;
+		uint64_t qos_mask:8;
+		uint64_t reserved_10_52:43;
+		uint64_t eid:4;
+		uint64_t pid:6;
+	} s;
+	struct cvmx_pko_mem_port_qos_s cn52xx;
+	struct cvmx_pko_mem_port_qos_s cn52xxp1;
+	struct cvmx_pko_mem_port_qos_s cn56xx;
+	struct cvmx_pko_mem_port_qos_s cn56xxp1;
+};
+
+union cvmx_pko_mem_port_rate0 {
+	uint64_t u64;
+	struct cvmx_pko_mem_port_rate0_s {
+		uint64_t reserved_51_63:13;
+		uint64_t rate_word:19;
+		uint64_t rate_pkt:24;
+		uint64_t reserved_6_7:2;
+		uint64_t pid:6;
+	} s;
+	struct cvmx_pko_mem_port_rate0_s cn52xx;
+	struct cvmx_pko_mem_port_rate0_s cn52xxp1;
+	struct cvmx_pko_mem_port_rate0_s cn56xx;
+	struct cvmx_pko_mem_port_rate0_s cn56xxp1;
+};
+
+union cvmx_pko_mem_port_rate1 {
+	uint64_t u64;
+	struct cvmx_pko_mem_port_rate1_s {
+		uint64_t reserved_32_63:32;
+		uint64_t rate_lim:24;
+		uint64_t reserved_6_7:2;
+		uint64_t pid:6;
+	} s;
+	struct cvmx_pko_mem_port_rate1_s cn52xx;
+	struct cvmx_pko_mem_port_rate1_s cn52xxp1;
+	struct cvmx_pko_mem_port_rate1_s cn56xx;
+	struct cvmx_pko_mem_port_rate1_s cn56xxp1;
+};
+
+union cvmx_pko_mem_queue_ptrs {
+	uint64_t u64;
+	struct cvmx_pko_mem_queue_ptrs_s {
+		uint64_t s_tail:1;
+		uint64_t static_p:1;
+		uint64_t static_q:1;
+		uint64_t qos_mask:8;
+		uint64_t buf_ptr:36;
+		uint64_t tail:1;
+		uint64_t index:3;
+		uint64_t port:6;
+		uint64_t queue:7;
+	} s;
+	struct cvmx_pko_mem_queue_ptrs_s cn30xx;
+	struct cvmx_pko_mem_queue_ptrs_s cn31xx;
+	struct cvmx_pko_mem_queue_ptrs_s cn38xx;
+	struct cvmx_pko_mem_queue_ptrs_s cn38xxp2;
+	struct cvmx_pko_mem_queue_ptrs_s cn50xx;
+	struct cvmx_pko_mem_queue_ptrs_s cn52xx;
+	struct cvmx_pko_mem_queue_ptrs_s cn52xxp1;
+	struct cvmx_pko_mem_queue_ptrs_s cn56xx;
+	struct cvmx_pko_mem_queue_ptrs_s cn56xxp1;
+	struct cvmx_pko_mem_queue_ptrs_s cn58xx;
+	struct cvmx_pko_mem_queue_ptrs_s cn58xxp1;
+};
+
+union cvmx_pko_mem_queue_qos {
+	uint64_t u64;
+	struct cvmx_pko_mem_queue_qos_s {
+		uint64_t reserved_61_63:3;
+		uint64_t qos_mask:8;
+		uint64_t reserved_13_52:40;
+		uint64_t pid:6;
+		uint64_t qid:7;
+	} s;
+	struct cvmx_pko_mem_queue_qos_s cn30xx;
+	struct cvmx_pko_mem_queue_qos_s cn31xx;
+	struct cvmx_pko_mem_queue_qos_s cn38xx;
+	struct cvmx_pko_mem_queue_qos_s cn38xxp2;
+	struct cvmx_pko_mem_queue_qos_s cn50xx;
+	struct cvmx_pko_mem_queue_qos_s cn52xx;
+	struct cvmx_pko_mem_queue_qos_s cn52xxp1;
+	struct cvmx_pko_mem_queue_qos_s cn56xx;
+	struct cvmx_pko_mem_queue_qos_s cn56xxp1;
+	struct cvmx_pko_mem_queue_qos_s cn58xx;
+	struct cvmx_pko_mem_queue_qos_s cn58xxp1;
+};
+
+union cvmx_pko_reg_bist_result {
+	uint64_t u64;
+	struct cvmx_pko_reg_bist_result_s {
+		uint64_t reserved_0_63:64;
+	} s;
+	struct cvmx_pko_reg_bist_result_cn30xx {
+		uint64_t reserved_27_63:37;
+		uint64_t psb2:5;
+		uint64_t count:1;
+		uint64_t rif:1;
+		uint64_t wif:1;
+		uint64_t ncb:1;
+		uint64_t out:1;
+		uint64_t crc:1;
+		uint64_t chk:1;
+		uint64_t qsb:2;
+		uint64_t qcb:2;
+		uint64_t pdb:4;
+		uint64_t psb:7;
+	} cn30xx;
+	struct cvmx_pko_reg_bist_result_cn30xx cn31xx;
+	struct cvmx_pko_reg_bist_result_cn30xx cn38xx;
+	struct cvmx_pko_reg_bist_result_cn30xx cn38xxp2;
+	struct cvmx_pko_reg_bist_result_cn50xx {
+		uint64_t reserved_33_63:31;
+		uint64_t csr:1;
+		uint64_t iob:1;
+		uint64_t out_crc:1;
+		uint64_t out_ctl:3;
+		uint64_t out_sta:1;
+		uint64_t out_wif:1;
+		uint64_t prt_chk:3;
+		uint64_t prt_nxt:1;
+		uint64_t prt_psb:6;
+		uint64_t ncb_inb:2;
+		uint64_t prt_qcb:2;
+		uint64_t prt_qsb:3;
+		uint64_t dat_dat:4;
+		uint64_t dat_ptr:4;
+	} cn50xx;
+	struct cvmx_pko_reg_bist_result_cn52xx {
+		uint64_t reserved_35_63:29;
+		uint64_t csr:1;
+		uint64_t iob:1;
+		uint64_t out_dat:1;
+		uint64_t out_ctl:3;
+		uint64_t out_sta:1;
+		uint64_t out_wif:1;
+		uint64_t prt_chk:3;
+		uint64_t prt_nxt:1;
+		uint64_t prt_psb:8;
+		uint64_t ncb_inb:2;
+		uint64_t prt_qcb:2;
+		uint64_t prt_qsb:3;
+		uint64_t prt_ctl:2;
+		uint64_t dat_dat:2;
+		uint64_t dat_ptr:4;
+	} cn52xx;
+	struct cvmx_pko_reg_bist_result_cn52xx cn52xxp1;
+	struct cvmx_pko_reg_bist_result_cn52xx cn56xx;
+	struct cvmx_pko_reg_bist_result_cn52xx cn56xxp1;
+	struct cvmx_pko_reg_bist_result_cn50xx cn58xx;
+	struct cvmx_pko_reg_bist_result_cn50xx cn58xxp1;
+};
+
+union cvmx_pko_reg_cmd_buf {
+	uint64_t u64;
+	struct cvmx_pko_reg_cmd_buf_s {
+		uint64_t reserved_23_63:41;
+		uint64_t pool:3;
+		uint64_t reserved_13_19:7;
+		uint64_t size:13;
+	} s;
+	struct cvmx_pko_reg_cmd_buf_s cn30xx;
+	struct cvmx_pko_reg_cmd_buf_s cn31xx;
+	struct cvmx_pko_reg_cmd_buf_s cn38xx;
+	struct cvmx_pko_reg_cmd_buf_s cn38xxp2;
+	struct cvmx_pko_reg_cmd_buf_s cn50xx;
+	struct cvmx_pko_reg_cmd_buf_s cn52xx;
+	struct cvmx_pko_reg_cmd_buf_s cn52xxp1;
+	struct cvmx_pko_reg_cmd_buf_s cn56xx;
+	struct cvmx_pko_reg_cmd_buf_s cn56xxp1;
+	struct cvmx_pko_reg_cmd_buf_s cn58xx;
+	struct cvmx_pko_reg_cmd_buf_s cn58xxp1;
+};
+
+union cvmx_pko_reg_crc_ctlx {
+	uint64_t u64;
+	struct cvmx_pko_reg_crc_ctlx_s {
+		uint64_t reserved_2_63:62;
+		uint64_t invres:1;
+		uint64_t refin:1;
+	} s;
+	struct cvmx_pko_reg_crc_ctlx_s cn38xx;
+	struct cvmx_pko_reg_crc_ctlx_s cn38xxp2;
+	struct cvmx_pko_reg_crc_ctlx_s cn58xx;
+	struct cvmx_pko_reg_crc_ctlx_s cn58xxp1;
+};
+
+union cvmx_pko_reg_crc_enable {
+	uint64_t u64;
+	struct cvmx_pko_reg_crc_enable_s {
+		uint64_t reserved_32_63:32;
+		uint64_t enable:32;
+	} s;
+	struct cvmx_pko_reg_crc_enable_s cn38xx;
+	struct cvmx_pko_reg_crc_enable_s cn38xxp2;
+	struct cvmx_pko_reg_crc_enable_s cn58xx;
+	struct cvmx_pko_reg_crc_enable_s cn58xxp1;
+};
+
+union cvmx_pko_reg_crc_ivx {
+	uint64_t u64;
+	struct cvmx_pko_reg_crc_ivx_s {
+		uint64_t reserved_32_63:32;
+		uint64_t iv:32;
+	} s;
+	struct cvmx_pko_reg_crc_ivx_s cn38xx;
+	struct cvmx_pko_reg_crc_ivx_s cn38xxp2;
+	struct cvmx_pko_reg_crc_ivx_s cn58xx;
+	struct cvmx_pko_reg_crc_ivx_s cn58xxp1;
+};
+
+union cvmx_pko_reg_debug0 {
+	uint64_t u64;
+	struct cvmx_pko_reg_debug0_s {
+		uint64_t asserts:64;
+	} s;
+	struct cvmx_pko_reg_debug0_cn30xx {
+		uint64_t reserved_17_63:47;
+		uint64_t asserts:17;
+	} cn30xx;
+	struct cvmx_pko_reg_debug0_cn30xx cn31xx;
+	struct cvmx_pko_reg_debug0_cn30xx cn38xx;
+	struct cvmx_pko_reg_debug0_cn30xx cn38xxp2;
+	struct cvmx_pko_reg_debug0_s cn50xx;
+	struct cvmx_pko_reg_debug0_s cn52xx;
+	struct cvmx_pko_reg_debug0_s cn52xxp1;
+	struct cvmx_pko_reg_debug0_s cn56xx;
+	struct cvmx_pko_reg_debug0_s cn56xxp1;
+	struct cvmx_pko_reg_debug0_s cn58xx;
+	struct cvmx_pko_reg_debug0_s cn58xxp1;
+};
+
+union cvmx_pko_reg_debug1 {
+	uint64_t u64;
+	struct cvmx_pko_reg_debug1_s {
+		uint64_t asserts:64;
+	} s;
+	struct cvmx_pko_reg_debug1_s cn50xx;
+	struct cvmx_pko_reg_debug1_s cn52xx;
+	struct cvmx_pko_reg_debug1_s cn52xxp1;
+	struct cvmx_pko_reg_debug1_s cn56xx;
+	struct cvmx_pko_reg_debug1_s cn56xxp1;
+	struct cvmx_pko_reg_debug1_s cn58xx;
+	struct cvmx_pko_reg_debug1_s cn58xxp1;
+};
+
+union cvmx_pko_reg_debug2 {
+	uint64_t u64;
+	struct cvmx_pko_reg_debug2_s {
+		uint64_t asserts:64;
+	} s;
+	struct cvmx_pko_reg_debug2_s cn50xx;
+	struct cvmx_pko_reg_debug2_s cn52xx;
+	struct cvmx_pko_reg_debug2_s cn52xxp1;
+	struct cvmx_pko_reg_debug2_s cn56xx;
+	struct cvmx_pko_reg_debug2_s cn56xxp1;
+	struct cvmx_pko_reg_debug2_s cn58xx;
+	struct cvmx_pko_reg_debug2_s cn58xxp1;
+};
+
+union cvmx_pko_reg_debug3 {
+	uint64_t u64;
+	struct cvmx_pko_reg_debug3_s {
+		uint64_t asserts:64;
+	} s;
+	struct cvmx_pko_reg_debug3_s cn50xx;
+	struct cvmx_pko_reg_debug3_s cn52xx;
+	struct cvmx_pko_reg_debug3_s cn52xxp1;
+	struct cvmx_pko_reg_debug3_s cn56xx;
+	struct cvmx_pko_reg_debug3_s cn56xxp1;
+	struct cvmx_pko_reg_debug3_s cn58xx;
+	struct cvmx_pko_reg_debug3_s cn58xxp1;
+};
+
+union cvmx_pko_reg_engine_inflight {
+	uint64_t u64;
+	struct cvmx_pko_reg_engine_inflight_s {
+		uint64_t reserved_40_63:24;
+		uint64_t engine9:4;
+		uint64_t engine8:4;
+		uint64_t engine7:4;
+		uint64_t engine6:4;
+		uint64_t engine5:4;
+		uint64_t engine4:4;
+		uint64_t engine3:4;
+		uint64_t engine2:4;
+		uint64_t engine1:4;
+		uint64_t engine0:4;
+	} s;
+	struct cvmx_pko_reg_engine_inflight_s cn52xx;
+	struct cvmx_pko_reg_engine_inflight_s cn52xxp1;
+	struct cvmx_pko_reg_engine_inflight_s cn56xx;
+	struct cvmx_pko_reg_engine_inflight_s cn56xxp1;
+};
+
+union cvmx_pko_reg_engine_thresh {
+	uint64_t u64;
+	struct cvmx_pko_reg_engine_thresh_s {
+		uint64_t reserved_10_63:54;
+		uint64_t mask:10;
+	} s;
+	struct cvmx_pko_reg_engine_thresh_s cn52xx;
+	struct cvmx_pko_reg_engine_thresh_s cn52xxp1;
+	struct cvmx_pko_reg_engine_thresh_s cn56xx;
+	struct cvmx_pko_reg_engine_thresh_s cn56xxp1;
+};
+
+union cvmx_pko_reg_error {
+	uint64_t u64;
+	struct cvmx_pko_reg_error_s {
+		uint64_t reserved_3_63:61;
+		uint64_t currzero:1;
+		uint64_t doorbell:1;
+		uint64_t parity:1;
+	} s;
+	struct cvmx_pko_reg_error_cn30xx {
+		uint64_t reserved_2_63:62;
+		uint64_t doorbell:1;
+		uint64_t parity:1;
+	} cn30xx;
+	struct cvmx_pko_reg_error_cn30xx cn31xx;
+	struct cvmx_pko_reg_error_cn30xx cn38xx;
+	struct cvmx_pko_reg_error_cn30xx cn38xxp2;
+	struct cvmx_pko_reg_error_s cn50xx;
+	struct cvmx_pko_reg_error_s cn52xx;
+	struct cvmx_pko_reg_error_s cn52xxp1;
+	struct cvmx_pko_reg_error_s cn56xx;
+	struct cvmx_pko_reg_error_s cn56xxp1;
+	struct cvmx_pko_reg_error_s cn58xx;
+	struct cvmx_pko_reg_error_s cn58xxp1;
+};
+
+union cvmx_pko_reg_flags {
+	uint64_t u64;
+	struct cvmx_pko_reg_flags_s {
+		uint64_t reserved_4_63:60;
+		uint64_t reset:1;
+		uint64_t store_be:1;
+		uint64_t ena_dwb:1;
+		uint64_t ena_pko:1;
+	} s;
+	struct cvmx_pko_reg_flags_s cn30xx;
+	struct cvmx_pko_reg_flags_s cn31xx;
+	struct cvmx_pko_reg_flags_s cn38xx;
+	struct cvmx_pko_reg_flags_s cn38xxp2;
+	struct cvmx_pko_reg_flags_s cn50xx;
+	struct cvmx_pko_reg_flags_s cn52xx;
+	struct cvmx_pko_reg_flags_s cn52xxp1;
+	struct cvmx_pko_reg_flags_s cn56xx;
+	struct cvmx_pko_reg_flags_s cn56xxp1;
+	struct cvmx_pko_reg_flags_s cn58xx;
+	struct cvmx_pko_reg_flags_s cn58xxp1;
+};
+
+union cvmx_pko_reg_gmx_port_mode {
+	uint64_t u64;
+	struct cvmx_pko_reg_gmx_port_mode_s {
+		uint64_t reserved_6_63:58;
+		uint64_t mode1:3;
+		uint64_t mode0:3;
+	} s;
+	struct cvmx_pko_reg_gmx_port_mode_s cn30xx;
+	struct cvmx_pko_reg_gmx_port_mode_s cn31xx;
+	struct cvmx_pko_reg_gmx_port_mode_s cn38xx;
+	struct cvmx_pko_reg_gmx_port_mode_s cn38xxp2;
+	struct cvmx_pko_reg_gmx_port_mode_s cn50xx;
+	struct cvmx_pko_reg_gmx_port_mode_s cn52xx;
+	struct cvmx_pko_reg_gmx_port_mode_s cn52xxp1;
+	struct cvmx_pko_reg_gmx_port_mode_s cn56xx;
+	struct cvmx_pko_reg_gmx_port_mode_s cn56xxp1;
+	struct cvmx_pko_reg_gmx_port_mode_s cn58xx;
+	struct cvmx_pko_reg_gmx_port_mode_s cn58xxp1;
+};
+
+union cvmx_pko_reg_int_mask {
+	uint64_t u64;
+	struct cvmx_pko_reg_int_mask_s {
+		uint64_t reserved_3_63:61;
+		uint64_t currzero:1;
+		uint64_t doorbell:1;
+		uint64_t parity:1;
+	} s;
+	struct cvmx_pko_reg_int_mask_cn30xx {
+		uint64_t reserved_2_63:62;
+		uint64_t doorbell:1;
+		uint64_t parity:1;
+	} cn30xx;
+	struct cvmx_pko_reg_int_mask_cn30xx cn31xx;
+	struct cvmx_pko_reg_int_mask_cn30xx cn38xx;
+	struct cvmx_pko_reg_int_mask_cn30xx cn38xxp2;
+	struct cvmx_pko_reg_int_mask_s cn50xx;
+	struct cvmx_pko_reg_int_mask_s cn52xx;
+	struct cvmx_pko_reg_int_mask_s cn52xxp1;
+	struct cvmx_pko_reg_int_mask_s cn56xx;
+	struct cvmx_pko_reg_int_mask_s cn56xxp1;
+	struct cvmx_pko_reg_int_mask_s cn58xx;
+	struct cvmx_pko_reg_int_mask_s cn58xxp1;
+};
+
+union cvmx_pko_reg_queue_mode {
+	uint64_t u64;
+	struct cvmx_pko_reg_queue_mode_s {
+		uint64_t reserved_2_63:62;
+		uint64_t mode:2;
+	} s;
+	struct cvmx_pko_reg_queue_mode_s cn30xx;
+	struct cvmx_pko_reg_queue_mode_s cn31xx;
+	struct cvmx_pko_reg_queue_mode_s cn38xx;
+	struct cvmx_pko_reg_queue_mode_s cn38xxp2;
+	struct cvmx_pko_reg_queue_mode_s cn50xx;
+	struct cvmx_pko_reg_queue_mode_s cn52xx;
+	struct cvmx_pko_reg_queue_mode_s cn52xxp1;
+	struct cvmx_pko_reg_queue_mode_s cn56xx;
+	struct cvmx_pko_reg_queue_mode_s cn56xxp1;
+	struct cvmx_pko_reg_queue_mode_s cn58xx;
+	struct cvmx_pko_reg_queue_mode_s cn58xxp1;
+};
+
+union cvmx_pko_reg_queue_ptrs1 {
+	uint64_t u64;
+	struct cvmx_pko_reg_queue_ptrs1_s {
+		uint64_t reserved_2_63:62;
+		uint64_t idx3:1;
+		uint64_t qid7:1;
+	} s;
+	struct cvmx_pko_reg_queue_ptrs1_s cn50xx;
+	struct cvmx_pko_reg_queue_ptrs1_s cn52xx;
+	struct cvmx_pko_reg_queue_ptrs1_s cn52xxp1;
+	struct cvmx_pko_reg_queue_ptrs1_s cn56xx;
+	struct cvmx_pko_reg_queue_ptrs1_s cn56xxp1;
+	struct cvmx_pko_reg_queue_ptrs1_s cn58xx;
+	struct cvmx_pko_reg_queue_ptrs1_s cn58xxp1;
+};
+
+union cvmx_pko_reg_read_idx {
+	uint64_t u64;
+	struct cvmx_pko_reg_read_idx_s {
+		uint64_t reserved_16_63:48;
+		uint64_t inc:8;
+		uint64_t index:8;
+	} s;
+	struct cvmx_pko_reg_read_idx_s cn30xx;
+	struct cvmx_pko_reg_read_idx_s cn31xx;
+	struct cvmx_pko_reg_read_idx_s cn38xx;
+	struct cvmx_pko_reg_read_idx_s cn38xxp2;
+	struct cvmx_pko_reg_read_idx_s cn50xx;
+	struct cvmx_pko_reg_read_idx_s cn52xx;
+	struct cvmx_pko_reg_read_idx_s cn52xxp1;
+	struct cvmx_pko_reg_read_idx_s cn56xx;
+	struct cvmx_pko_reg_read_idx_s cn56xxp1;
+	struct cvmx_pko_reg_read_idx_s cn58xx;
+	struct cvmx_pko_reg_read_idx_s cn58xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-pko.c b/drivers/staging/octeon/cvmx-pko.c
new file mode 100644
index 0000000..00db915
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-pko.c
@@ -0,0 +1,506 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ * Support library for the hardware Packet Output unit.
+ */
+
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-config.h"
+#include "cvmx-pko.h"
+#include "cvmx-helper.h"
+
+/**
+ * Internal state of packet output
+ */
+
+/**
+ * Call before any other calls to initialize the packet
+ * output system.  This does chip global config, and should only be
+ * done by one core.
+ */
+
+void cvmx_pko_initialize_global(void)
+{
+	int i;
+	uint64_t priority = 8;
+	union cvmx_pko_reg_cmd_buf config;
+
+	/*
+	 * Set the size of the PKO command buffers to an odd number of
+	 * 64bit words. This allows the normal two word send to stay
+	 * aligned and never span a comamnd word buffer.
+	 */
+	config.u64 = 0;
+	config.s.pool = CVMX_FPA_OUTPUT_BUFFER_POOL;
+	config.s.size = CVMX_FPA_OUTPUT_BUFFER_POOL_SIZE / 8 - 1;
+
+	cvmx_write_csr(CVMX_PKO_REG_CMD_BUF, config.u64);
+
+	for (i = 0; i < CVMX_PKO_MAX_OUTPUT_QUEUES; i++)
+		cvmx_pko_config_port(CVMX_PKO_MEM_QUEUE_PTRS_ILLEGAL_PID, i, 1,
+				     &priority);
+
+	/*
+	 * If we aren't using all of the queues optimize PKO's
+	 * internal memory.
+	 */
+	if (OCTEON_IS_MODEL(OCTEON_CN38XX) || OCTEON_IS_MODEL(OCTEON_CN58XX)
+	    || OCTEON_IS_MODEL(OCTEON_CN56XX)
+	    || OCTEON_IS_MODEL(OCTEON_CN52XX)) {
+		int num_interfaces = cvmx_helper_get_number_of_interfaces();
+		int last_port =
+		    cvmx_helper_get_last_ipd_port(num_interfaces - 1);
+		int max_queues =
+		    cvmx_pko_get_base_queue(last_port) +
+		    cvmx_pko_get_num_queues(last_port);
+		if (OCTEON_IS_MODEL(OCTEON_CN38XX)) {
+			if (max_queues <= 32)
+				cvmx_write_csr(CVMX_PKO_REG_QUEUE_MODE, 2);
+			else if (max_queues <= 64)
+				cvmx_write_csr(CVMX_PKO_REG_QUEUE_MODE, 1);
+		} else {
+			if (max_queues <= 64)
+				cvmx_write_csr(CVMX_PKO_REG_QUEUE_MODE, 2);
+			else if (max_queues <= 128)
+				cvmx_write_csr(CVMX_PKO_REG_QUEUE_MODE, 1);
+		}
+	}
+}
+
+/**
+ * This function does per-core initialization required by the PKO routines.
+ * This must be called on all cores that will do packet output, and must
+ * be called after the FPA has been initialized and filled with pages.
+ *
+ * Returns 0 on success
+ *         !0 on failure
+ */
+int cvmx_pko_initialize_local(void)
+{
+	/* Nothing to do */
+	return 0;
+}
+
+/**
+ * Enables the packet output hardware. It must already be
+ * configured.
+ */
+void cvmx_pko_enable(void)
+{
+	union cvmx_pko_reg_flags flags;
+
+	flags.u64 = cvmx_read_csr(CVMX_PKO_REG_FLAGS);
+	if (flags.s.ena_pko)
+		cvmx_dprintf
+		    ("Warning: Enabling PKO when PKO already enabled.\n");
+
+	flags.s.ena_dwb = 1;
+	flags.s.ena_pko = 1;
+	/*
+	 * always enable big endian for 3-word command. Does nothing
+	 * for 2-word.
+	 */
+	flags.s.store_be = 1;
+	cvmx_write_csr(CVMX_PKO_REG_FLAGS, flags.u64);
+}
+
+/**
+ * Disables the packet output. Does not affect any configuration.
+ */
+void cvmx_pko_disable(void)
+{
+	union cvmx_pko_reg_flags pko_reg_flags;
+	pko_reg_flags.u64 = cvmx_read_csr(CVMX_PKO_REG_FLAGS);
+	pko_reg_flags.s.ena_pko = 0;
+	cvmx_write_csr(CVMX_PKO_REG_FLAGS, pko_reg_flags.u64);
+}
+
+
+/**
+ * Reset the packet output.
+ */
+static void __cvmx_pko_reset(void)
+{
+	union cvmx_pko_reg_flags pko_reg_flags;
+	pko_reg_flags.u64 = cvmx_read_csr(CVMX_PKO_REG_FLAGS);
+	pko_reg_flags.s.reset = 1;
+	cvmx_write_csr(CVMX_PKO_REG_FLAGS, pko_reg_flags.u64);
+}
+
+/**
+ * Shutdown and free resources required by packet output.
+ */
+void cvmx_pko_shutdown(void)
+{
+	union cvmx_pko_mem_queue_ptrs config;
+	int queue;
+
+	cvmx_pko_disable();
+
+	for (queue = 0; queue < CVMX_PKO_MAX_OUTPUT_QUEUES; queue++) {
+		config.u64 = 0;
+		config.s.tail = 1;
+		config.s.index = 0;
+		config.s.port = CVMX_PKO_MEM_QUEUE_PTRS_ILLEGAL_PID;
+		config.s.queue = queue & 0x7f;
+		config.s.qos_mask = 0;
+		config.s.buf_ptr = 0;
+		if (!OCTEON_IS_MODEL(OCTEON_CN3XXX)) {
+			union cvmx_pko_reg_queue_ptrs1 config1;
+			config1.u64 = 0;
+			config1.s.qid7 = queue >> 7;
+			cvmx_write_csr(CVMX_PKO_REG_QUEUE_PTRS1, config1.u64);
+		}
+		cvmx_write_csr(CVMX_PKO_MEM_QUEUE_PTRS, config.u64);
+		cvmx_cmd_queue_shutdown(CVMX_CMD_QUEUE_PKO(queue));
+	}
+	__cvmx_pko_reset();
+}
+
+/**
+ * Configure a output port and the associated queues for use.
+ *
+ * @port:       Port to configure.
+ * @base_queue: First queue number to associate with this port.
+ * @num_queues: Number of queues to associate with this port
+ * @priority:   Array of priority levels for each queue. Values are
+ *                   allowed to be 0-8. A value of 8 get 8 times the traffic
+ *                   of a value of 1.  A value of 0 indicates that no rounds
+ *                   will be participated in. These priorities can be changed
+ *                   on the fly while the pko is enabled. A priority of 9
+ *                   indicates that static priority should be used.  If static
+ *                   priority is used all queues with static priority must be
+ *                   contiguous starting at the base_queue, and lower numbered
+ *                   queues have higher priority than higher numbered queues.
+ *                   There must be num_queues elements in the array.
+ */
+cvmx_pko_status_t cvmx_pko_config_port(uint64_t port, uint64_t base_queue,
+				       uint64_t num_queues,
+				       const uint64_t priority[])
+{
+	cvmx_pko_status_t result_code;
+	uint64_t queue;
+	union cvmx_pko_mem_queue_ptrs config;
+	union cvmx_pko_reg_queue_ptrs1 config1;
+	int static_priority_base = -1;
+	int static_priority_end = -1;
+
+	if ((port >= CVMX_PKO_NUM_OUTPUT_PORTS)
+	    && (port != CVMX_PKO_MEM_QUEUE_PTRS_ILLEGAL_PID)) {
+		cvmx_dprintf("ERROR: cvmx_pko_config_port: Invalid port %llu\n",
+			     (unsigned long long)port);
+		return CVMX_PKO_INVALID_PORT;
+	}
+
+	if (base_queue + num_queues > CVMX_PKO_MAX_OUTPUT_QUEUES) {
+		cvmx_dprintf
+		    ("ERROR: cvmx_pko_config_port: Invalid queue range %llu\n",
+		     (unsigned long long)(base_queue + num_queues));
+		return CVMX_PKO_INVALID_QUEUE;
+	}
+
+	if (port != CVMX_PKO_MEM_QUEUE_PTRS_ILLEGAL_PID) {
+		/*
+		 * Validate the static queue priority setup and set
+		 * static_priority_base and static_priority_end
+		 * accordingly.
+		 */
+		for (queue = 0; queue < num_queues; queue++) {
+			/* Find first queue of static priority */
+			if (static_priority_base == -1
+			    && priority[queue] ==
+			    CVMX_PKO_QUEUE_STATIC_PRIORITY)
+				static_priority_base = queue;
+			/* Find last queue of static priority */
+			if (static_priority_base != -1
+			    && static_priority_end == -1
+			    && priority[queue] != CVMX_PKO_QUEUE_STATIC_PRIORITY
+			    && queue)
+				static_priority_end = queue - 1;
+			else if (static_priority_base != -1
+				 && static_priority_end == -1
+				 && queue == num_queues - 1)
+				/* all queues are static priority */
+				static_priority_end = queue;
+			/*
+			 * Check to make sure all static priority
+			 * queues are contiguous.  Also catches some
+			 * cases of static priorites not starting at
+			 * queue 0.
+			 */
+			if (static_priority_end != -1
+			    && (int)queue > static_priority_end
+			    && priority[queue] ==
+			    CVMX_PKO_QUEUE_STATIC_PRIORITY) {
+				cvmx_dprintf("ERROR: cvmx_pko_config_port: "
+					     "Static priority queues aren't "
+					     "contiguous or don't start at "
+					     "base queue. q: %d, eq: %d\n",
+					(int)queue, static_priority_end);
+				return CVMX_PKO_INVALID_PRIORITY;
+			}
+		}
+		if (static_priority_base > 0) {
+			cvmx_dprintf("ERROR: cvmx_pko_config_port: Static "
+				     "priority queues don't start at base "
+				     "queue. sq: %d\n",
+				static_priority_base);
+			return CVMX_PKO_INVALID_PRIORITY;
+		}
+#if 0
+		cvmx_dprintf("Port %d: Static priority queue base: %d, "
+			     "end: %d\n", port,
+			static_priority_base, static_priority_end);
+#endif
+	}
+	/*
+	 * At this point, static_priority_base and static_priority_end
+	 * are either both -1, or are valid start/end queue
+	 * numbers.
+	 */
+
+	result_code = CVMX_PKO_SUCCESS;
+
+#ifdef PKO_DEBUG
+	cvmx_dprintf("num queues: %d (%lld,%lld)\n", num_queues,
+		     CVMX_PKO_QUEUES_PER_PORT_INTERFACE0,
+		     CVMX_PKO_QUEUES_PER_PORT_INTERFACE1);
+#endif
+
+	for (queue = 0; queue < num_queues; queue++) {
+		uint64_t *buf_ptr = NULL;
+
+		config1.u64 = 0;
+		config1.s.idx3 = queue >> 3;
+		config1.s.qid7 = (base_queue + queue) >> 7;
+
+		config.u64 = 0;
+		config.s.tail = queue == (num_queues - 1);
+		config.s.index = queue;
+		config.s.port = port;
+		config.s.queue = base_queue + queue;
+
+		if (!cvmx_octeon_is_pass1()) {
+			config.s.static_p = static_priority_base >= 0;
+			config.s.static_q = (int)queue <= static_priority_end;
+			config.s.s_tail = (int)queue == static_priority_end;
+		}
+		/*
+		 * Convert the priority into an enable bit field. Try
+		 * to space the bits out evenly so the packet don't
+		 * get grouped up
+		 */
+		switch ((int)priority[queue]) {
+		case 0:
+			config.s.qos_mask = 0x00;
+			break;
+		case 1:
+			config.s.qos_mask = 0x01;
+			break;
+		case 2:
+			config.s.qos_mask = 0x11;
+			break;
+		case 3:
+			config.s.qos_mask = 0x49;
+			break;
+		case 4:
+			config.s.qos_mask = 0x55;
+			break;
+		case 5:
+			config.s.qos_mask = 0x57;
+			break;
+		case 6:
+			config.s.qos_mask = 0x77;
+			break;
+		case 7:
+			config.s.qos_mask = 0x7f;
+			break;
+		case 8:
+			config.s.qos_mask = 0xff;
+			break;
+		case CVMX_PKO_QUEUE_STATIC_PRIORITY:
+			/* Pass 1 will fall through to the error case */
+			if (!cvmx_octeon_is_pass1()) {
+				config.s.qos_mask = 0xff;
+				break;
+			}
+		default:
+			cvmx_dprintf("ERROR: cvmx_pko_config_port: Invalid "
+				     "priority %llu\n",
+				(unsigned long long)priority[queue]);
+			config.s.qos_mask = 0xff;
+			result_code = CVMX_PKO_INVALID_PRIORITY;
+			break;
+		}
+
+		if (port != CVMX_PKO_MEM_QUEUE_PTRS_ILLEGAL_PID) {
+			cvmx_cmd_queue_result_t cmd_res =
+			    cvmx_cmd_queue_initialize(CVMX_CMD_QUEUE_PKO
+						      (base_queue + queue),
+						      CVMX_PKO_MAX_QUEUE_DEPTH,
+						      CVMX_FPA_OUTPUT_BUFFER_POOL,
+						      CVMX_FPA_OUTPUT_BUFFER_POOL_SIZE
+						      -
+						      CVMX_PKO_COMMAND_BUFFER_SIZE_ADJUST
+						      * 8);
+			if (cmd_res != CVMX_CMD_QUEUE_SUCCESS) {
+				switch (cmd_res) {
+				case CVMX_CMD_QUEUE_NO_MEMORY:
+					cvmx_dprintf("ERROR: "
+						     "cvmx_pko_config_port: "
+						     "Unable to allocate "
+						     "output buffer.\n");
+					return CVMX_PKO_NO_MEMORY;
+				case CVMX_CMD_QUEUE_ALREADY_SETUP:
+					cvmx_dprintf
+					    ("ERROR: cvmx_pko_config_port: Port already setup.\n");
+					return CVMX_PKO_PORT_ALREADY_SETUP;
+				case CVMX_CMD_QUEUE_INVALID_PARAM:
+				default:
+					cvmx_dprintf
+					    ("ERROR: cvmx_pko_config_port: Command queue initialization failed.\n");
+					return CVMX_PKO_CMD_QUEUE_INIT_ERROR;
+				}
+			}
+
+			buf_ptr =
+			    (uint64_t *)
+			    cvmx_cmd_queue_buffer(CVMX_CMD_QUEUE_PKO
+						  (base_queue + queue));
+			config.s.buf_ptr = cvmx_ptr_to_phys(buf_ptr);
+		} else
+			config.s.buf_ptr = 0;
+
+		CVMX_SYNCWS;
+
+		if (!OCTEON_IS_MODEL(OCTEON_CN3XXX))
+			cvmx_write_csr(CVMX_PKO_REG_QUEUE_PTRS1, config1.u64);
+		cvmx_write_csr(CVMX_PKO_MEM_QUEUE_PTRS, config.u64);
+	}
+
+	return result_code;
+}
+
+#ifdef PKO_DEBUG
+/**
+ * Show map of ports -> queues for different cores.
+ */
+void cvmx_pko_show_queue_map()
+{
+	int core, port;
+	int pko_output_ports = 36;
+
+	cvmx_dprintf("port");
+	for (port = 0; port < pko_output_ports; port++)
+		cvmx_dprintf("%3d ", port);
+	cvmx_dprintf("\n");
+
+	for (core = 0; core < CVMX_MAX_CORES; core++) {
+		cvmx_dprintf("\n%2d: ", core);
+		for (port = 0; port < pko_output_ports; port++) {
+			cvmx_dprintf("%3d ",
+				     cvmx_pko_get_base_queue_per_core(port,
+								      core));
+		}
+	}
+	cvmx_dprintf("\n");
+}
+#endif
+
+/**
+ * Rate limit a PKO port to a max packets/sec. This function is only
+ * supported on CN51XX and higher, excluding CN58XX.
+ *
+ * @port:      Port to rate limit
+ * @packets_s: Maximum packet/sec
+ * @burst:     Maximum number of packets to burst in a row before rate
+ *                  limiting cuts in.
+ *
+ * Returns Zero on success, negative on failure
+ */
+int cvmx_pko_rate_limit_packets(int port, int packets_s, int burst)
+{
+	union cvmx_pko_mem_port_rate0 pko_mem_port_rate0;
+	union cvmx_pko_mem_port_rate1 pko_mem_port_rate1;
+
+	pko_mem_port_rate0.u64 = 0;
+	pko_mem_port_rate0.s.pid = port;
+	pko_mem_port_rate0.s.rate_pkt =
+	    cvmx_sysinfo_get()->cpu_clock_hz / packets_s / 16;
+	/* No cost per word since we are limited by packets/sec, not bits/sec */
+	pko_mem_port_rate0.s.rate_word = 0;
+
+	pko_mem_port_rate1.u64 = 0;
+	pko_mem_port_rate1.s.pid = port;
+	pko_mem_port_rate1.s.rate_lim =
+	    ((uint64_t) pko_mem_port_rate0.s.rate_pkt * burst) >> 8;
+
+	cvmx_write_csr(CVMX_PKO_MEM_PORT_RATE0, pko_mem_port_rate0.u64);
+	cvmx_write_csr(CVMX_PKO_MEM_PORT_RATE1, pko_mem_port_rate1.u64);
+	return 0;
+}
+
+/**
+ * Rate limit a PKO port to a max bits/sec. This function is only
+ * supported on CN51XX and higher, excluding CN58XX.
+ *
+ * @port:   Port to rate limit
+ * @bits_s: PKO rate limit in bits/sec
+ * @burst:  Maximum number of bits to burst before rate
+ *               limiting cuts in.
+ *
+ * Returns Zero on success, negative on failure
+ */
+int cvmx_pko_rate_limit_bits(int port, uint64_t bits_s, int burst)
+{
+	union cvmx_pko_mem_port_rate0 pko_mem_port_rate0;
+	union cvmx_pko_mem_port_rate1 pko_mem_port_rate1;
+	uint64_t clock_rate = cvmx_sysinfo_get()->cpu_clock_hz;
+	uint64_t tokens_per_bit = clock_rate * 16 / bits_s;
+
+	pko_mem_port_rate0.u64 = 0;
+	pko_mem_port_rate0.s.pid = port;
+	/*
+	 * Each packet has a 12 bytes of interframe gap, an 8 byte
+	 * preamble, and a 4 byte CRC. These are not included in the
+	 * per word count. Multiply by 8 to covert to bits and divide
+	 * by 256 for limit granularity.
+	 */
+	pko_mem_port_rate0.s.rate_pkt = (12 + 8 + 4) * 8 * tokens_per_bit / 256;
+	/* Each 8 byte word has 64bits */
+	pko_mem_port_rate0.s.rate_word = 64 * tokens_per_bit;
+
+	pko_mem_port_rate1.u64 = 0;
+	pko_mem_port_rate1.s.pid = port;
+	pko_mem_port_rate1.s.rate_lim = tokens_per_bit * burst / 256;
+
+	cvmx_write_csr(CVMX_PKO_MEM_PORT_RATE0, pko_mem_port_rate0.u64);
+	cvmx_write_csr(CVMX_PKO_MEM_PORT_RATE1, pko_mem_port_rate1.u64);
+	return 0;
+}
diff --git a/drivers/staging/octeon/cvmx-pko.h b/drivers/staging/octeon/cvmx-pko.h
new file mode 100644
index 0000000..f068c19
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-pko.h
@@ -0,0 +1,610 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ *
+ * Interface to the hardware Packet Output unit.
+ *
+ * Starting with SDK 1.7.0, the PKO output functions now support
+ * two types of locking. CVMX_PKO_LOCK_ATOMIC_TAG continues to
+ * function similarly to previous SDKs by using POW atomic tags
+ * to preserve ordering and exclusivity. As a new option, you
+ * can now pass CVMX_PKO_LOCK_CMD_QUEUE which uses a ll/sc
+ * memory based locking instead. This locking has the advantage
+ * of not affecting the tag state but doesn't preserve packet
+ * ordering. CVMX_PKO_LOCK_CMD_QUEUE is appropriate in most
+ * generic code while CVMX_PKO_LOCK_CMD_QUEUE should be used
+ * with hand tuned fast path code.
+ *
+ * Some of other SDK differences visible to the command command
+ * queuing:
+ * - PKO indexes are no longer stored in the FAU. A large
+ *   percentage of the FAU register block used to be tied up
+ *   maintaining PKO queue pointers. These are now stored in a
+ *   global named block.
+ * - The PKO <b>use_locking</b> parameter can now have a global
+ *   effect. Since all application use the same named block,
+ *   queue locking correctly applies across all operating
+ *   systems when using CVMX_PKO_LOCK_CMD_QUEUE.
+ * - PKO 3 word commands are now supported. Use
+ *   cvmx_pko_send_packet_finish3().
+ *
+ */
+
+#ifndef __CVMX_PKO_H__
+#define __CVMX_PKO_H__
+
+#include "cvmx-fpa.h"
+#include "cvmx-pow.h"
+#include "cvmx-cmd-queue.h"
+#include "cvmx-pko-defs.h"
+
+/* Adjust the command buffer size by 1 word so that in the case of using only
+ * two word PKO commands no command words stradle buffers.  The useful values
+ * for this are 0 and 1. */
+#define CVMX_PKO_COMMAND_BUFFER_SIZE_ADJUST (1)
+
+#define CVMX_PKO_MAX_OUTPUT_QUEUES_STATIC 256
+#define CVMX_PKO_MAX_OUTPUT_QUEUES      ((OCTEON_IS_MODEL(OCTEON_CN31XX) || \
+	OCTEON_IS_MODEL(OCTEON_CN3010) || OCTEON_IS_MODEL(OCTEON_CN3005) || \
+	OCTEON_IS_MODEL(OCTEON_CN50XX)) ? 32 : \
+		(OCTEON_IS_MODEL(OCTEON_CN58XX) || \
+		OCTEON_IS_MODEL(OCTEON_CN56XX)) ? 256 : 128)
+#define CVMX_PKO_NUM_OUTPUT_PORTS       40
+/* use this for queues that are not used */
+#define CVMX_PKO_MEM_QUEUE_PTRS_ILLEGAL_PID 63
+#define CVMX_PKO_QUEUE_STATIC_PRIORITY  9
+#define CVMX_PKO_ILLEGAL_QUEUE  0xFFFF
+#define CVMX_PKO_MAX_QUEUE_DEPTH 0
+
+typedef enum {
+	CVMX_PKO_SUCCESS,
+	CVMX_PKO_INVALID_PORT,
+	CVMX_PKO_INVALID_QUEUE,
+	CVMX_PKO_INVALID_PRIORITY,
+	CVMX_PKO_NO_MEMORY,
+	CVMX_PKO_PORT_ALREADY_SETUP,
+	CVMX_PKO_CMD_QUEUE_INIT_ERROR
+} cvmx_pko_status_t;
+
+/**
+ * This enumeration represents the differnet locking modes supported by PKO.
+ */
+typedef enum {
+	/*
+	 * PKO doesn't do any locking. It is the responsibility of the
+	 * application to make sure that no other core is accessing
+	 * the same queue at the smae time
+	 */
+	CVMX_PKO_LOCK_NONE = 0,
+	/*
+	 * PKO performs an atomic tagswitch to insure exclusive access
+	 * to the output queue. This will maintain packet ordering on
+	 * output.
+	 */
+	CVMX_PKO_LOCK_ATOMIC_TAG = 1,
+	/*
+	 * PKO uses the common command queue locks to insure exclusive
+	 * access to the output queue. This is a memory based
+	 * ll/sc. This is the most portable locking mechanism.
+	 */
+	CVMX_PKO_LOCK_CMD_QUEUE = 2,
+} cvmx_pko_lock_t;
+
+typedef struct {
+	uint32_t packets;
+	uint64_t octets;
+	uint64_t doorbell;
+} cvmx_pko_port_status_t;
+
+/**
+ * This structure defines the address to use on a packet enqueue
+ */
+typedef union {
+	uint64_t u64;
+	struct {
+		/* Must CVMX_IO_SEG */
+		uint64_t mem_space:2;
+		/* Must be zero */
+		uint64_t reserved:13;
+		/* Must be one */
+		uint64_t is_io:1;
+		/* The ID of the device on the non-coherent bus */
+		uint64_t did:8;
+		/* Must be zero */
+		uint64_t reserved2:4;
+		/* Must be zero */
+		uint64_t reserved3:18;
+		/*
+		 * The hardware likes to have the output port in
+		 * addition to the output queue,
+		 */
+		uint64_t port:6;
+		/*
+		 * The output queue to send the packet to (0-127 are
+		 * legal)
+		 */
+		uint64_t queue:9;
+		/* Must be zero */
+		uint64_t reserved4:3;
+	} s;
+} cvmx_pko_doorbell_address_t;
+
+/**
+ * Structure of the first packet output command word.
+ */
+typedef union {
+	uint64_t u64;
+	struct {
+		/*
+		 * The size of the reg1 operation - could be 8, 16,
+		 * 32, or 64 bits.
+		 */
+		uint64_t size1:2;
+		/*
+		 * The size of the reg0 operation - could be 8, 16,
+		 * 32, or 64 bits.
+		 */
+		uint64_t size0:2;
+		/*
+		 * If set, subtract 1, if clear, subtract packet
+		 * size.
+		 */
+		uint64_t subone1:1;
+		/*
+		 * The register, subtract will be done if reg1 is
+		 * non-zero.
+		 */
+		uint64_t reg1:11;
+		/* If set, subtract 1, if clear, subtract packet size */
+		uint64_t subone0:1;
+		/* The register, subtract will be done if reg0 is non-zero */
+		uint64_t reg0:11;
+		/*
+		 * When set, interpret segment pointer and segment
+		 * bytes in little endian order.
+		 */
+		uint64_t le:1;
+		/*
+		 * When set, packet data not allocated in L2 cache by
+		 * PKO.
+		 */
+		uint64_t n2:1;
+		/*
+		 * If set and rsp is set, word3 contains a pointer to
+		 * a work queue entry.
+		 */
+		uint64_t wqp:1;
+		/* If set, the hardware will send a response when done */
+		uint64_t rsp:1;
+		/*
+		 * If set, the supplied pkt_ptr is really a pointer to
+		 * a list of pkt_ptr's.
+		 */
+		uint64_t gather:1;
+		/*
+		 * If ipoffp1 is non zero, (ipoffp1-1) is the number
+		 * of bytes to IP header, and the hardware will
+		 * calculate and insert the UDP/TCP checksum.
+		 */
+		uint64_t ipoffp1:7;
+		/*
+		 * If set, ignore the I bit (force to zero) from all
+		 * pointer structures.
+		 */
+		uint64_t ignore_i:1;
+		/*
+		 * If clear, the hardware will attempt to free the
+		 * buffers containing the packet.
+		 */
+		uint64_t dontfree:1;
+		/*
+		 * The total number of segs in the packet, if gather
+		 * set, also gather list length.
+		 */
+		uint64_t segs:6;
+		/* Including L2, but no trailing CRC */
+		uint64_t total_bytes:16;
+	} s;
+} cvmx_pko_command_word0_t;
+
+/* CSR typedefs have been moved to cvmx-csr-*.h */
+
+/**
+ * Definition of internal state for Packet output processing
+ */
+typedef struct {
+	/* ptr to start of buffer, offset kept in FAU reg */
+	uint64_t *start_ptr;
+} cvmx_pko_state_elem_t;
+
+/**
+ * Call before any other calls to initialize the packet
+ * output system.
+ */
+extern void cvmx_pko_initialize_global(void);
+extern int cvmx_pko_initialize_local(void);
+
+/**
+ * Enables the packet output hardware. It must already be
+ * configured.
+ */
+extern void cvmx_pko_enable(void);
+
+/**
+ * Disables the packet output. Does not affect any configuration.
+ */
+extern void cvmx_pko_disable(void);
+
+/**
+ * Shutdown and free resources required by packet output.
+ */
+
+extern void cvmx_pko_shutdown(void);
+
+/**
+ * Configure a output port and the associated queues for use.
+ *
+ * @port:       Port to configure.
+ * @base_queue: First queue number to associate with this port.
+ * @num_queues: Number of queues t oassociate with this port
+ * @priority:   Array of priority levels for each queue. Values are
+ *                   allowed to be 1-8. A value of 8 get 8 times the traffic
+ *                   of a value of 1. There must be num_queues elements in the
+ *                   array.
+ */
+extern cvmx_pko_status_t cvmx_pko_config_port(uint64_t port,
+					      uint64_t base_queue,
+					      uint64_t num_queues,
+					      const uint64_t priority[]);
+
+/**
+ * Ring the packet output doorbell. This tells the packet
+ * output hardware that "len" command words have been added
+ * to its pending list.  This command includes the required
+ * CVMX_SYNCWS before the doorbell ring.
+ *
+ * @port:   Port the packet is for
+ * @queue:  Queue the packet is for
+ * @len:    Length of the command in 64 bit words
+ */
+static inline void cvmx_pko_doorbell(uint64_t port, uint64_t queue,
+				     uint64_t len)
+{
+	cvmx_pko_doorbell_address_t ptr;
+
+	ptr.u64 = 0;
+	ptr.s.mem_space = CVMX_IO_SEG;
+	ptr.s.did = CVMX_OCT_DID_PKT_SEND;
+	ptr.s.is_io = 1;
+	ptr.s.port = port;
+	ptr.s.queue = queue;
+	/*
+	 * Need to make sure output queue data is in DRAM before
+	 * doorbell write.
+	 */
+	CVMX_SYNCWS;
+	cvmx_write_io(ptr.u64, len);
+}
+
+/**
+ * Prepare to send a packet.  This may initiate a tag switch to
+ * get exclusive access to the output queue structure, and
+ * performs other prep work for the packet send operation.
+ *
+ * cvmx_pko_send_packet_finish() MUST be called after this function is called,
+ * and must be called with the same port/queue/use_locking arguments.
+ *
+ * The use_locking parameter allows the caller to use three
+ * possible locking modes.
+ * - CVMX_PKO_LOCK_NONE
+ *      - PKO doesn't do any locking. It is the responsibility
+ *          of the application to make sure that no other core
+ *          is accessing the same queue at the smae time.
+ * - CVMX_PKO_LOCK_ATOMIC_TAG
+ *      - PKO performs an atomic tagswitch to insure exclusive
+ *          access to the output queue. This will maintain
+ *          packet ordering on output.
+ * - CVMX_PKO_LOCK_CMD_QUEUE
+ *      - PKO uses the common command queue locks to insure
+ *          exclusive access to the output queue. This is a
+ *          memory based ll/sc. This is the most portable
+ *          locking mechanism.
+ *
+ * NOTE: If atomic locking is used, the POW entry CANNOT be
+ * descheduled, as it does not contain a valid WQE pointer.
+ *
+ * @port:   Port to send it on
+ * @queue:  Queue to use
+ * @use_locking: CVMX_PKO_LOCK_NONE, CVMX_PKO_LOCK_ATOMIC_TAG, or
+ *               CVMX_PKO_LOCK_CMD_QUEUE
+ */
+
+static inline void cvmx_pko_send_packet_prepare(uint64_t port, uint64_t queue,
+						cvmx_pko_lock_t use_locking)
+{
+	if (use_locking == CVMX_PKO_LOCK_ATOMIC_TAG) {
+		/*
+		 * Must do a full switch here to handle all cases.  We
+		 * use a fake WQE pointer, as the POW does not access
+		 * this memory.  The WQE pointer and group are only
+		 * used if this work is descheduled, which is not
+		 * supported by the
+		 * cvmx_pko_send_packet_prepare/cvmx_pko_send_packet_finish
+		 * combination.  Note that this is a special case in
+		 * which these fake values can be used - this is not a
+		 * general technique.
+		 */
+		uint32_t tag =
+		    CVMX_TAG_SW_BITS_INTERNAL << CVMX_TAG_SW_SHIFT |
+		    CVMX_TAG_SUBGROUP_PKO << CVMX_TAG_SUBGROUP_SHIFT |
+		    (CVMX_TAG_SUBGROUP_MASK & queue);
+		cvmx_pow_tag_sw_full((cvmx_wqe_t *) cvmx_phys_to_ptr(0x80), tag,
+				     CVMX_POW_TAG_TYPE_ATOMIC, 0);
+	}
+}
+
+/**
+ * Complete packet output. cvmx_pko_send_packet_prepare() must be
+ * called exactly once before this, and the same parameters must be
+ * passed to both cvmx_pko_send_packet_prepare() and
+ * cvmx_pko_send_packet_finish().
+ *
+ * @port:   Port to send it on
+ * @queue:  Queue to use
+ * @pko_command:
+ *               PKO HW command word
+ * @packet: Packet to send
+ * @use_locking: CVMX_PKO_LOCK_NONE, CVMX_PKO_LOCK_ATOMIC_TAG, or
+ *               CVMX_PKO_LOCK_CMD_QUEUE
+ *
+ * Returns returns CVMX_PKO_SUCCESS on success, or error code on
+ * failure of output
+ */
+static inline cvmx_pko_status_t cvmx_pko_send_packet_finish(
+	uint64_t port,
+	uint64_t queue,
+	cvmx_pko_command_word0_t pko_command,
+	union cvmx_buf_ptr packet,
+	cvmx_pko_lock_t use_locking)
+{
+	cvmx_cmd_queue_result_t result;
+	if (use_locking == CVMX_PKO_LOCK_ATOMIC_TAG)
+		cvmx_pow_tag_sw_wait();
+	result = cvmx_cmd_queue_write2(CVMX_CMD_QUEUE_PKO(queue),
+				       (use_locking == CVMX_PKO_LOCK_CMD_QUEUE),
+				       pko_command.u64, packet.u64);
+	if (likely(result == CVMX_CMD_QUEUE_SUCCESS)) {
+		cvmx_pko_doorbell(port, queue, 2);
+		return CVMX_PKO_SUCCESS;
+	} else if ((result == CVMX_CMD_QUEUE_NO_MEMORY)
+		   || (result == CVMX_CMD_QUEUE_FULL)) {
+		return CVMX_PKO_NO_MEMORY;
+	} else {
+		return CVMX_PKO_INVALID_QUEUE;
+	}
+}
+
+/**
+ * Complete packet output. cvmx_pko_send_packet_prepare() must be
+ * called exactly once before this, and the same parameters must be
+ * passed to both cvmx_pko_send_packet_prepare() and
+ * cvmx_pko_send_packet_finish().
+ *
+ * @port:   Port to send it on
+ * @queue:  Queue to use
+ * @pko_command:
+ *               PKO HW command word
+ * @packet: Packet to send
+ * @addr: Plysical address of a work queue entry or physical address
+ *        to zero on complete.
+ * @use_locking: CVMX_PKO_LOCK_NONE, CVMX_PKO_LOCK_ATOMIC_TAG, or
+ *               CVMX_PKO_LOCK_CMD_QUEUE
+ *
+ * Returns returns CVMX_PKO_SUCCESS on success, or error code on
+ * failure of output
+ */
+static inline cvmx_pko_status_t cvmx_pko_send_packet_finish3(
+	uint64_t port,
+	uint64_t queue,
+	cvmx_pko_command_word0_t pko_command,
+	union cvmx_buf_ptr packet,
+	uint64_t addr,
+	cvmx_pko_lock_t use_locking)
+{
+	cvmx_cmd_queue_result_t result;
+	if (use_locking == CVMX_PKO_LOCK_ATOMIC_TAG)
+		cvmx_pow_tag_sw_wait();
+	result = cvmx_cmd_queue_write3(CVMX_CMD_QUEUE_PKO(queue),
+				       (use_locking == CVMX_PKO_LOCK_CMD_QUEUE),
+				       pko_command.u64, packet.u64, addr);
+	if (likely(result == CVMX_CMD_QUEUE_SUCCESS)) {
+		cvmx_pko_doorbell(port, queue, 3);
+		return CVMX_PKO_SUCCESS;
+	} else if ((result == CVMX_CMD_QUEUE_NO_MEMORY)
+		   || (result == CVMX_CMD_QUEUE_FULL)) {
+		return CVMX_PKO_NO_MEMORY;
+	} else {
+		return CVMX_PKO_INVALID_QUEUE;
+	}
+}
+
+/**
+ * Return the pko output queue associated with a port and a specific core.
+ * In normal mode (PKO lockless operation is disabled), the value returned
+ * is the base queue.
+ *
+ * @port:   Port number
+ * @core:   Core to get queue for
+ *
+ * Returns Core-specific output queue
+ */
+static inline int cvmx_pko_get_base_queue_per_core(int port, int core)
+{
+#ifndef CVMX_HELPER_PKO_MAX_PORTS_INTERFACE0
+#define CVMX_HELPER_PKO_MAX_PORTS_INTERFACE0 16
+#endif
+#ifndef CVMX_HELPER_PKO_MAX_PORTS_INTERFACE1
+#define CVMX_HELPER_PKO_MAX_PORTS_INTERFACE1 16
+#endif
+
+	if (port < CVMX_PKO_MAX_PORTS_INTERFACE0)
+		return port * CVMX_PKO_QUEUES_PER_PORT_INTERFACE0 + core;
+	else if (port >= 16 && port < 16 + CVMX_PKO_MAX_PORTS_INTERFACE1)
+		return CVMX_PKO_MAX_PORTS_INTERFACE0 *
+		    CVMX_PKO_QUEUES_PER_PORT_INTERFACE0 + (port -
+							   16) *
+		    CVMX_PKO_QUEUES_PER_PORT_INTERFACE1 + core;
+	else if ((port >= 32) && (port < 36))
+		return CVMX_PKO_MAX_PORTS_INTERFACE0 *
+		    CVMX_PKO_QUEUES_PER_PORT_INTERFACE0 +
+		    CVMX_PKO_MAX_PORTS_INTERFACE1 *
+		    CVMX_PKO_QUEUES_PER_PORT_INTERFACE1 + (port -
+							   32) *
+		    CVMX_PKO_QUEUES_PER_PORT_PCI;
+	else if ((port >= 36) && (port < 40))
+		return CVMX_PKO_MAX_PORTS_INTERFACE0 *
+		    CVMX_PKO_QUEUES_PER_PORT_INTERFACE0 +
+		    CVMX_PKO_MAX_PORTS_INTERFACE1 *
+		    CVMX_PKO_QUEUES_PER_PORT_INTERFACE1 +
+		    4 * CVMX_PKO_QUEUES_PER_PORT_PCI + (port -
+							36) *
+		    CVMX_PKO_QUEUES_PER_PORT_LOOP;
+	else
+		/* Given the limit on the number of ports we can map to
+		 * CVMX_MAX_OUTPUT_QUEUES_STATIC queues (currently 256,
+		 * divided among all cores), the remaining unmapped ports
+		 * are assigned an illegal queue number */
+		return CVMX_PKO_ILLEGAL_QUEUE;
+}
+
+/**
+ * For a given port number, return the base pko output queue
+ * for the port.
+ *
+ * @port:   Port number
+ * Returns Base output queue
+ */
+static inline int cvmx_pko_get_base_queue(int port)
+{
+	return cvmx_pko_get_base_queue_per_core(port, 0);
+}
+
+/**
+ * For a given port number, return the number of pko output queues.
+ *
+ * @port:   Port number
+ * Returns Number of output queues
+ */
+static inline int cvmx_pko_get_num_queues(int port)
+{
+	if (port < 16)
+		return CVMX_PKO_QUEUES_PER_PORT_INTERFACE0;
+	else if (port < 32)
+		return CVMX_PKO_QUEUES_PER_PORT_INTERFACE1;
+	else if (port < 36)
+		return CVMX_PKO_QUEUES_PER_PORT_PCI;
+	else if (port < 40)
+		return CVMX_PKO_QUEUES_PER_PORT_LOOP;
+	else
+		return 0;
+}
+
+/**
+ * Get the status counters for a port.
+ *
+ * @port_num: Port number to get statistics for.
+ * @clear:    Set to 1 to clear the counters after they are read
+ * @status:   Where to put the results.
+ */
+static inline void cvmx_pko_get_port_status(uint64_t port_num, uint64_t clear,
+					    cvmx_pko_port_status_t *status)
+{
+	union cvmx_pko_reg_read_idx pko_reg_read_idx;
+	union cvmx_pko_mem_count0 pko_mem_count0;
+	union cvmx_pko_mem_count1 pko_mem_count1;
+
+	pko_reg_read_idx.u64 = 0;
+	pko_reg_read_idx.s.index = port_num;
+	cvmx_write_csr(CVMX_PKO_REG_READ_IDX, pko_reg_read_idx.u64);
+
+	pko_mem_count0.u64 = cvmx_read_csr(CVMX_PKO_MEM_COUNT0);
+	status->packets = pko_mem_count0.s.count;
+	if (clear) {
+		pko_mem_count0.s.count = port_num;
+		cvmx_write_csr(CVMX_PKO_MEM_COUNT0, pko_mem_count0.u64);
+	}
+
+	pko_mem_count1.u64 = cvmx_read_csr(CVMX_PKO_MEM_COUNT1);
+	status->octets = pko_mem_count1.s.count;
+	if (clear) {
+		pko_mem_count1.s.count = port_num;
+		cvmx_write_csr(CVMX_PKO_MEM_COUNT1, pko_mem_count1.u64);
+	}
+
+	if (OCTEON_IS_MODEL(OCTEON_CN3XXX)) {
+		union cvmx_pko_mem_debug9 debug9;
+		pko_reg_read_idx.s.index = cvmx_pko_get_base_queue(port_num);
+		cvmx_write_csr(CVMX_PKO_REG_READ_IDX, pko_reg_read_idx.u64);
+		debug9.u64 = cvmx_read_csr(CVMX_PKO_MEM_DEBUG9);
+		status->doorbell = debug9.cn38xx.doorbell;
+	} else {
+		union cvmx_pko_mem_debug8 debug8;
+		pko_reg_read_idx.s.index = cvmx_pko_get_base_queue(port_num);
+		cvmx_write_csr(CVMX_PKO_REG_READ_IDX, pko_reg_read_idx.u64);
+		debug8.u64 = cvmx_read_csr(CVMX_PKO_MEM_DEBUG8);
+		status->doorbell = debug8.cn58xx.doorbell;
+	}
+}
+
+/**
+ * Rate limit a PKO port to a max packets/sec. This function is only
+ * supported on CN57XX, CN56XX, CN55XX, and CN54XX.
+ *
+ * @port:      Port to rate limit
+ * @packets_s: Maximum packet/sec
+ * @burst:     Maximum number of packets to burst in a row before rate
+ *                  limiting cuts in.
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int cvmx_pko_rate_limit_packets(int port, int packets_s, int burst);
+
+/**
+ * Rate limit a PKO port to a max bits/sec. This function is only
+ * supported on CN57XX, CN56XX, CN55XX, and CN54XX.
+ *
+ * @port:   Port to rate limit
+ * @bits_s: PKO rate limit in bits/sec
+ * @burst:  Maximum number of bits to burst before rate
+ *               limiting cuts in.
+ *
+ * Returns Zero on success, negative on failure
+ */
+extern int cvmx_pko_rate_limit_bits(int port, uint64_t bits_s, int burst);
+
+#endif /* __CVMX_PKO_H__ */
diff --git a/drivers/staging/octeon/cvmx-pow.h b/drivers/staging/octeon/cvmx-pow.h
new file mode 100644
index 0000000..c5d66f2
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-pow.h
@@ -0,0 +1,1982 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ * Interface to the hardware Packet Order / Work unit.
+ *
+ * New, starting with SDK 1.7.0, cvmx-pow supports a number of
+ * extended consistency checks. The define
+ * CVMX_ENABLE_POW_CHECKS controls the runtime insertion of POW
+ * internal state checks to find common programming errors. If
+ * CVMX_ENABLE_POW_CHECKS is not defined, checks are by default
+ * enabled. For example, cvmx-pow will check for the following
+ * program errors or POW state inconsistency.
+ * - Requesting a POW operation with an active tag switch in
+ *   progress.
+ * - Waiting for a tag switch to complete for an excessively
+ *   long period. This is normally a sign of an error in locking
+ *   causing deadlock.
+ * - Illegal tag switches from NULL_NULL.
+ * - Illegal tag switches from NULL.
+ * - Illegal deschedule request.
+ * - WQE pointer not matching the one attached to the core by
+ *   the POW.
+ *
+ */
+
+#ifndef __CVMX_POW_H__
+#define __CVMX_POW_H__
+
+#include <asm/octeon/cvmx-pow-defs.h>
+
+#include "cvmx-scratch.h"
+#include "cvmx-wqe.h"
+
+/* Default to having all POW constancy checks turned on */
+#ifndef CVMX_ENABLE_POW_CHECKS
+#define CVMX_ENABLE_POW_CHECKS 1
+#endif
+
+enum cvmx_pow_tag_type {
+	/* Tag ordering is maintained */
+	CVMX_POW_TAG_TYPE_ORDERED   = 0L,
+	/* Tag ordering is maintained, and at most one PP has the tag */
+	CVMX_POW_TAG_TYPE_ATOMIC    = 1L,
+	/*
+	 * The work queue entry from the order - NEVER tag switch from
+	 * NULL to NULL
+	 */
+	CVMX_POW_TAG_TYPE_NULL      = 2L,
+	/* A tag switch to NULL, and there is no space reserved in POW
+	 * - NEVER tag switch to NULL_NULL
+	 * - NEVER tag switch from NULL_NULL
+	 * - NULL_NULL is entered at the beginning of time and on a deschedule.
+	 * - NULL_NULL can be exited by a new work request. A NULL_SWITCH
+	 * load can also switch the state to NULL
+	 */
+	CVMX_POW_TAG_TYPE_NULL_NULL = 3L
+};
+
+/**
+ * Wait flag values for pow functions.
+ */
+typedef enum {
+	CVMX_POW_WAIT = 1,
+	CVMX_POW_NO_WAIT = 0,
+} cvmx_pow_wait_t;
+
+/**
+ *  POW tag operations.  These are used in the data stored to the POW.
+ */
+typedef enum {
+	/*
+	 * switch the tag (only) for this PP
+	 * - the previous tag should be non-NULL in this case
+	 * - tag switch response required
+	 * - fields used: op, type, tag
+	 */
+	CVMX_POW_TAG_OP_SWTAG = 0L,
+	/*
+	 * switch the tag for this PP, with full information
+	 * - this should be used when the previous tag is NULL
+	 * - tag switch response required
+	 * - fields used: address, op, grp, type, tag
+	 */
+	CVMX_POW_TAG_OP_SWTAG_FULL = 1L,
+	/*
+	 * switch the tag (and/or group) for this PP and de-schedule
+	 * - OK to keep the tag the same and only change the group
+	 * - fields used: op, no_sched, grp, type, tag
+	 */
+	CVMX_POW_TAG_OP_SWTAG_DESCH = 2L,
+	/*
+	 * just de-schedule
+	 * - fields used: op, no_sched
+	 */
+	CVMX_POW_TAG_OP_DESCH = 3L,
+	/*
+	 * create an entirely new work queue entry
+	 * - fields used: address, op, qos, grp, type, tag
+	 */
+	CVMX_POW_TAG_OP_ADDWQ = 4L,
+	/*
+	 * just update the work queue pointer and grp for this PP
+	 * - fields used: address, op, grp
+	 */
+	CVMX_POW_TAG_OP_UPDATE_WQP_GRP = 5L,
+	/*
+	 * set the no_sched bit on the de-schedule list
+	 *
+	 * - does nothing if the selected entry is not on the
+	 *   de-schedule list
+	 *
+	 * - does nothing if the stored work queue pointer does not
+	 *   match the address field
+	 *
+	 * - fields used: address, index, op
+	 *
+	 *  Before issuing a *_NSCHED operation, SW must guarantee
+	 *  that all prior deschedules and set/clr NSCHED operations
+	 *  are complete and all prior switches are complete. The
+	 *  hardware provides the opsdone bit and swdone bit for SW
+	 *  polling. After issuing a *_NSCHED operation, SW must
+	 *  guarantee that the set/clr NSCHED is complete before any
+	 *  subsequent operations.
+	 */
+	CVMX_POW_TAG_OP_SET_NSCHED = 6L,
+	/*
+	 * clears the no_sched bit on the de-schedule list
+	 *
+	 * - does nothing if the selected entry is not on the
+	 *   de-schedule list
+	 *
+	 * - does nothing if the stored work queue pointer does not
+	 *   match the address field
+	 *
+	 * - fields used: address, index, op
+	 *
+	 * Before issuing a *_NSCHED operation, SW must guarantee that
+	 * all prior deschedules and set/clr NSCHED operations are
+	 * complete and all prior switches are complete. The hardware
+	 * provides the opsdone bit and swdone bit for SW
+	 * polling. After issuing a *_NSCHED operation, SW must
+	 * guarantee that the set/clr NSCHED is complete before any
+	 * subsequent operations.
+	 */
+	CVMX_POW_TAG_OP_CLR_NSCHED = 7L,
+	/* do nothing */
+	CVMX_POW_TAG_OP_NOP = 15L
+} cvmx_pow_tag_op_t;
+
+/**
+ * This structure defines the store data on a store to POW
+ */
+typedef union {
+	uint64_t u64;
+	struct {
+		/*
+		 * Don't reschedule this entry. no_sched is used for
+		 * CVMX_POW_TAG_OP_SWTAG_DESCH and
+		 * CVMX_POW_TAG_OP_DESCH
+		 */
+		uint64_t no_sched:1;
+		uint64_t unused:2;
+		/* Tontains index of entry for a CVMX_POW_TAG_OP_*_NSCHED */
+		uint64_t index:13;
+		/* The operation to perform */
+		cvmx_pow_tag_op_t op:4;
+		uint64_t unused2:2;
+		/*
+		 * The QOS level for the packet. qos is only used for
+		 * CVMX_POW_TAG_OP_ADDWQ
+		 */
+		uint64_t qos:3;
+		/*
+		 * The group that the work queue entry will be
+		 * scheduled to grp is used for CVMX_POW_TAG_OP_ADDWQ,
+		 * CVMX_POW_TAG_OP_SWTAG_FULL,
+		 * CVMX_POW_TAG_OP_SWTAG_DESCH, and
+		 * CVMX_POW_TAG_OP_UPDATE_WQP_GRP
+		 */
+		uint64_t grp:4;
+		/*
+		 * The type of the tag. type is used for everything
+		 * except CVMX_POW_TAG_OP_DESCH,
+		 * CVMX_POW_TAG_OP_UPDATE_WQP_GRP, and
+		 * CVMX_POW_TAG_OP_*_NSCHED
+		 */
+		uint64_t type:3;
+		/*
+		 * The actual tag. tag is used for everything except
+		 * CVMX_POW_TAG_OP_DESCH,
+		 * CVMX_POW_TAG_OP_UPDATE_WQP_GRP, and
+		 * CVMX_POW_TAG_OP_*_NSCHED
+		 */
+		uint64_t tag:32;
+	} s;
+} cvmx_pow_tag_req_t;
+
+/**
+ * This structure describes the address to load stuff from POW
+ */
+typedef union {
+	uint64_t u64;
+
+    /**
+     * Address for new work request loads (did<2:0> == 0)
+     */
+	struct {
+		/* Mips64 address region. Should be CVMX_IO_SEG */
+		uint64_t mem_region:2;
+		/* Must be zero */
+		uint64_t reserved_49_61:13;
+		/* Must be one */
+		uint64_t is_io:1;
+		/* the ID of POW -- did<2:0> == 0 in this case */
+		uint64_t did:8;
+		/* Must be zero */
+		uint64_t reserved_4_39:36;
+		/*
+		 * If set, don't return load response until work is
+		 * available.
+		 */
+		uint64_t wait:1;
+		/* Must be zero */
+		uint64_t reserved_0_2:3;
+	} swork;
+
+    /**
+     * Address for loads to get POW internal status
+     */
+	struct {
+		/* Mips64 address region. Should be CVMX_IO_SEG */
+		uint64_t mem_region:2;
+		/* Must be zero */
+		uint64_t reserved_49_61:13;
+		/* Must be one */
+		uint64_t is_io:1;
+		/* the ID of POW -- did<2:0> == 1 in this case */
+		uint64_t did:8;
+		/* Must be zero */
+		uint64_t reserved_10_39:30;
+		/* The core id to get status for */
+		uint64_t coreid:4;
+		/*
+		 * If set and get_cur is set, return reverse tag-list
+		 * pointer rather than forward tag-list pointer.
+		 */
+		uint64_t get_rev:1;
+		/*
+		 * If set, return current status rather than pending
+		 * status.
+		 */
+		uint64_t get_cur:1;
+		/*
+		 * If set, get the work-queue pointer rather than
+		 * tag/type.
+		 */
+		uint64_t get_wqp:1;
+		/* Must be zero */
+		uint64_t reserved_0_2:3;
+	} sstatus;
+
+    /**
+     * Address for memory loads to get POW internal state
+     */
+	struct {
+		/* Mips64 address region. Should be CVMX_IO_SEG */
+		uint64_t mem_region:2;
+		/* Must be zero */
+		uint64_t reserved_49_61:13;
+		/* Must be one */
+		uint64_t is_io:1;
+		/* the ID of POW -- did<2:0> == 2 in this case */
+		uint64_t did:8;
+		/* Must be zero */
+		uint64_t reserved_16_39:24;
+		/* POW memory index */
+		uint64_t index:11;
+		/*
+		 * If set, return deschedule information rather than
+		 * the standard response for work-queue index (invalid
+		 * if the work-queue entry is not on the deschedule
+		 * list).
+		 */
+		uint64_t get_des:1;
+		/*
+		 * If set, get the work-queue pointer rather than
+		 * tag/type (no effect when get_des set).
+		 */
+		uint64_t get_wqp:1;
+		/* Must be zero */
+		uint64_t reserved_0_2:3;
+	} smemload;
+
+    /**
+     * Address for index/pointer loads
+     */
+	struct {
+		/* Mips64 address region. Should be CVMX_IO_SEG */
+		uint64_t mem_region:2;
+		/* Must be zero */
+		uint64_t reserved_49_61:13;
+		/* Must be one */
+		uint64_t is_io:1;
+		/* the ID of POW -- did<2:0> == 3 in this case */
+		uint64_t did:8;
+		/* Must be zero */
+		uint64_t reserved_9_39:31;
+		/*
+		 * when {get_rmt ==0 AND get_des_get_tail == 0}, this
+		 * field selects one of eight POW internal-input
+		 * queues (0-7), one per QOS level; values 8-15 are
+		 * illegal in this case; when {get_rmt ==0 AND
+		 * get_des_get_tail == 1}, this field selects one of
+		 * 16 deschedule lists (per group); when get_rmt ==1,
+		 * this field selects one of 16 memory-input queue
+		 * lists.  The two memory-input queue lists associated
+		 * with each QOS level are:
+		 *
+		 * - qosgrp = 0, qosgrp = 8:      QOS0
+		 * - qosgrp = 1, qosgrp = 9:      QOS1
+		 * - qosgrp = 2, qosgrp = 10:     QOS2
+		 * - qosgrp = 3, qosgrp = 11:     QOS3
+		 * - qosgrp = 4, qosgrp = 12:     QOS4
+		 * - qosgrp = 5, qosgrp = 13:     QOS5
+		 * - qosgrp = 6, qosgrp = 14:     QOS6
+		 * - qosgrp = 7, qosgrp = 15:     QOS7
+		 */
+		uint64_t qosgrp:4;
+		/*
+		 * If set and get_rmt is clear, return deschedule list
+		 * indexes rather than indexes for the specified qos
+		 * level; if set and get_rmt is set, return the tail
+		 * pointer rather than the head pointer for the
+		 * specified qos level.
+		 */
+		uint64_t get_des_get_tail:1;
+		/*
+		 * If set, return remote pointers rather than the
+		 * local indexes for the specified qos level.
+		 */
+		uint64_t get_rmt:1;
+		/* Must be zero */
+		uint64_t reserved_0_2:3;
+	} sindexload;
+
+    /**
+     * address for NULL_RD request (did<2:0> == 4) when this is read,
+     * HW attempts to change the state to NULL if it is NULL_NULL (the
+     * hardware cannot switch from NULL_NULL to NULL if a POW entry is
+     * not available - software may need to recover by finishing
+     * another piece of work before a POW entry can ever become
+     * available.)
+     */
+	struct {
+		/* Mips64 address region. Should be CVMX_IO_SEG */
+		uint64_t mem_region:2;
+		/* Must be zero */
+		uint64_t reserved_49_61:13;
+		/* Must be one */
+		uint64_t is_io:1;
+		/* the ID of POW -- did<2:0> == 4 in this case */
+		uint64_t did:8;
+		/* Must be zero */
+		uint64_t reserved_0_39:40;
+	} snull_rd;
+} cvmx_pow_load_addr_t;
+
+/**
+ * This structure defines the response to a load/SENDSINGLE to POW
+ * (except CSR reads)
+ */
+typedef union {
+	uint64_t u64;
+
+    /**
+     * Response to new work request loads
+     */
+	struct {
+		/*
+		 * Set when no new work queue entry was returned.  *
+		 * If there was de-scheduled work, the HW will
+		 * definitely return it. When this bit is set, it
+		 * could mean either mean:
+		 *
+		 * - There was no work, or
+		 *
+		 * - There was no work that the HW could find. This
+		 *   case can happen, regardless of the wait bit value
+		 *   in the original request, when there is work in
+		 *   the IQ's that is too deep down the list.
+		 */
+		uint64_t no_work:1;
+		/* Must be zero */
+		uint64_t reserved_40_62:23;
+		/* 36 in O1 -- the work queue pointer */
+		uint64_t addr:40;
+	} s_work;
+
+    /**
+     * Result for a POW Status Load (when get_cur==0 and get_wqp==0)
+     */
+	struct {
+		uint64_t reserved_62_63:2;
+		/* Set when there is a pending non-NULL SWTAG or
+		 * SWTAG_FULL, and the POW entry has not left the list
+		 * for the original tag. */
+		uint64_t pend_switch:1;
+		/* Set when SWTAG_FULL and pend_switch is set. */
+		uint64_t pend_switch_full:1;
+		/*
+		 * Set when there is a pending NULL SWTAG, or an
+		 * implicit switch to NULL.
+		 */
+		uint64_t pend_switch_null:1;
+		/* Set when there is a pending DESCHED or SWTAG_DESCHED. */
+		uint64_t pend_desched:1;
+		/*
+		 * Set when there is a pending SWTAG_DESCHED and
+		 * pend_desched is set.
+		 */
+		uint64_t pend_desched_switch:1;
+		/* Set when nosched is desired and pend_desched is set. */
+		uint64_t pend_nosched:1;
+		/* Set when there is a pending GET_WORK. */
+		uint64_t pend_new_work:1;
+		/*
+		 * When pend_new_work is set, this bit indicates that
+		 * the wait bit was set.
+		 */
+		uint64_t pend_new_work_wait:1;
+		/* Set when there is a pending NULL_RD. */
+		uint64_t pend_null_rd:1;
+		/* Set when there is a pending CLR_NSCHED. */
+		uint64_t pend_nosched_clr:1;
+		uint64_t reserved_51:1;
+		/* This is the index when pend_nosched_clr is set. */
+		uint64_t pend_index:11;
+		/*
+		 * This is the new_grp when (pend_desched AND
+		 * pend_desched_switch) is set.
+		 */
+		uint64_t pend_grp:4;
+		uint64_t reserved_34_35:2;
+		/*
+		 * This is the tag type when pend_switch or
+		 * (pend_desched AND pend_desched_switch) are set.
+		 */
+		uint64_t pend_type:2;
+		/*
+		 * - this is the tag when pend_switch or (pend_desched
+		 *    AND pend_desched_switch) are set.
+		 */
+		uint64_t pend_tag:32;
+	} s_sstatus0;
+
+    /**
+     * Result for a POW Status Load (when get_cur==0 and get_wqp==1)
+     */
+	struct {
+		uint64_t reserved_62_63:2;
+		/*
+		 * Set when there is a pending non-NULL SWTAG or
+		 * SWTAG_FULL, and the POW entry has not left the list
+		 * for the original tag.
+		 */
+		uint64_t pend_switch:1;
+		/* Set when SWTAG_FULL and pend_switch is set. */
+		uint64_t pend_switch_full:1;
+		/*
+		 * Set when there is a pending NULL SWTAG, or an
+		 * implicit switch to NULL.
+		 */
+		uint64_t pend_switch_null:1;
+		/*
+		 * Set when there is a pending DESCHED or
+		 * SWTAG_DESCHED.
+		 */
+		uint64_t pend_desched:1;
+		/*
+		 * Set when there is a pending SWTAG_DESCHED and
+		 * pend_desched is set.
+		 */
+		uint64_t pend_desched_switch:1;
+		/* Set when nosched is desired and pend_desched is set. */
+		uint64_t pend_nosched:1;
+		/* Set when there is a pending GET_WORK. */
+		uint64_t pend_new_work:1;
+		/*
+		 * When pend_new_work is set, this bit indicates that
+		 * the wait bit was set.
+		 */
+		uint64_t pend_new_work_wait:1;
+		/* Set when there is a pending NULL_RD. */
+		uint64_t pend_null_rd:1;
+		/* Set when there is a pending CLR_NSCHED. */
+		uint64_t pend_nosched_clr:1;
+		uint64_t reserved_51:1;
+		/* This is the index when pend_nosched_clr is set. */
+		uint64_t pend_index:11;
+		/*
+		 * This is the new_grp when (pend_desched AND
+		 * pend_desched_switch) is set.
+		 */
+		uint64_t pend_grp:4;
+		/* This is the wqp when pend_nosched_clr is set. */
+		uint64_t pend_wqp:36;
+	} s_sstatus1;
+
+    /**
+     * Result for a POW Status Load (when get_cur==1, get_wqp==0, and
+     * get_rev==0)
+     */
+	struct {
+		uint64_t reserved_62_63:2;
+		/*
+		 * Points to the next POW entry in the tag list when
+		 * tail == 0 (and tag_type is not NULL or NULL_NULL).
+		 */
+		uint64_t link_index:11;
+		/* The POW entry attached to the core. */
+		uint64_t index:11;
+		/*
+		 * The group attached to the core (updated when new
+		 * tag list entered on SWTAG_FULL).
+		 */
+		uint64_t grp:4;
+		/*
+		 * Set when this POW entry is at the head of its tag
+		 * list (also set when in the NULL or NULL_NULL
+		 * state).
+		 */
+		uint64_t head:1;
+		/*
+		 * Set when this POW entry is at the tail of its tag
+		 * list (also set when in the NULL or NULL_NULL
+		 * state).
+		 */
+		uint64_t tail:1;
+		/*
+		 * The tag type attached to the core (updated when new
+		 * tag list entered on SWTAG, SWTAG_FULL, or
+		 * SWTAG_DESCHED).
+		 */
+		uint64_t tag_type:2;
+		/*
+		 * The tag attached to the core (updated when new tag
+		 * list entered on SWTAG, SWTAG_FULL, or
+		 * SWTAG_DESCHED).
+		 */
+		uint64_t tag:32;
+	} s_sstatus2;
+
+    /**
+     * Result for a POW Status Load (when get_cur==1, get_wqp==0, and get_rev==1)
+     */
+	struct {
+		uint64_t reserved_62_63:2;
+		/*
+		 * Points to the prior POW entry in the tag list when
+		 * head == 0 (and tag_type is not NULL or
+		 * NULL_NULL). This field is unpredictable when the
+		 * core's state is NULL or NULL_NULL.
+		 */
+		uint64_t revlink_index:11;
+		/* The POW entry attached to the core. */
+		uint64_t index:11;
+		/*
+		 * The group attached to the core (updated when new
+		 * tag list entered on SWTAG_FULL).
+		 */
+		uint64_t grp:4;
+		/* Set when this POW entry is at the head of its tag
+		 * list (also set when in the NULL or NULL_NULL
+		 * state).
+		 */
+		uint64_t head:1;
+		/*
+		 * Set when this POW entry is at the tail of its tag
+		 * list (also set when in the NULL or NULL_NULL
+		 * state).
+		 */
+		uint64_t tail:1;
+		/*
+		 * The tag type attached to the core (updated when new
+		 * tag list entered on SWTAG, SWTAG_FULL, or
+		 * SWTAG_DESCHED).
+		 */
+		uint64_t tag_type:2;
+		/*
+		 * The tag attached to the core (updated when new tag
+		 * list entered on SWTAG, SWTAG_FULL, or
+		 * SWTAG_DESCHED).
+		 */
+		uint64_t tag:32;
+	} s_sstatus3;
+
+    /**
+     * Result for a POW Status Load (when get_cur==1, get_wqp==1, and
+     * get_rev==0)
+     */
+	struct {
+		uint64_t reserved_62_63:2;
+		/*
+		 * Points to the next POW entry in the tag list when
+		 * tail == 0 (and tag_type is not NULL or NULL_NULL).
+		 */
+		uint64_t link_index:11;
+		/* The POW entry attached to the core. */
+		uint64_t index:11;
+		/*
+		 * The group attached to the core (updated when new
+		 * tag list entered on SWTAG_FULL).
+		 */
+		uint64_t grp:4;
+		/*
+		 * The wqp attached to the core (updated when new tag
+		 * list entered on SWTAG_FULL).
+		 */
+		uint64_t wqp:36;
+	} s_sstatus4;
+
+    /**
+     * Result for a POW Status Load (when get_cur==1, get_wqp==1, and
+     * get_rev==1)
+     */
+	struct {
+		uint64_t reserved_62_63:2;
+		/*
+		 * Points to the prior POW entry in the tag list when
+		 * head == 0 (and tag_type is not NULL or
+		 * NULL_NULL). This field is unpredictable when the
+		 * core's state is NULL or NULL_NULL.
+		 */
+		uint64_t revlink_index:11;
+		/* The POW entry attached to the core. */
+		uint64_t index:11;
+		/*
+		 * The group attached to the core (updated when new
+		 * tag list entered on SWTAG_FULL).
+		 */
+		uint64_t grp:4;
+		/*
+		 * The wqp attached to the core (updated when new tag
+		 * list entered on SWTAG_FULL).
+		 */
+		uint64_t wqp:36;
+	} s_sstatus5;
+
+    /**
+     * Result For POW Memory Load (get_des == 0 and get_wqp == 0)
+     */
+	struct {
+		uint64_t reserved_51_63:13;
+		/*
+		 * The next entry in the input, free, descheduled_head
+		 * list (unpredictable if entry is the tail of the
+		 * list).
+		 */
+		uint64_t next_index:11;
+		/* The group of the POW entry. */
+		uint64_t grp:4;
+		uint64_t reserved_35:1;
+		/*
+		 * Set when this POW entry is at the tail of its tag
+		 * list (also set when in the NULL or NULL_NULL
+		 * state).
+		 */
+		uint64_t tail:1;
+		/* The tag type of the POW entry. */
+		uint64_t tag_type:2;
+		/* The tag of the POW entry. */
+		uint64_t tag:32;
+	} s_smemload0;
+
+    /**
+     * Result For POW Memory Load (get_des == 0 and get_wqp == 1)
+     */
+	struct {
+		uint64_t reserved_51_63:13;
+		/*
+		 * The next entry in the input, free, descheduled_head
+		 * list (unpredictable if entry is the tail of the
+		 * list).
+		 */
+		uint64_t next_index:11;
+		/* The group of the POW entry. */
+		uint64_t grp:4;
+		/* The WQP held in the POW entry. */
+		uint64_t wqp:36;
+	} s_smemload1;
+
+    /**
+     * Result For POW Memory Load (get_des == 1)
+     */
+	struct {
+		uint64_t reserved_51_63:13;
+		/*
+		 * The next entry in the tag list connected to the
+		 * descheduled head.
+		 */
+		uint64_t fwd_index:11;
+		/* The group of the POW entry. */
+		uint64_t grp:4;
+		/* The nosched bit for the POW entry. */
+		uint64_t nosched:1;
+		/* There is a pending tag switch */
+		uint64_t pend_switch:1;
+		/*
+		 * The next tag type for the new tag list when
+		 * pend_switch is set.
+		 */
+		uint64_t pend_type:2;
+		/*
+		 * The next tag for the new tag list when pend_switch
+		 * is set.
+		 */
+		uint64_t pend_tag:32;
+	} s_smemload2;
+
+    /**
+     * Result For POW Index/Pointer Load (get_rmt == 0/get_des_get_tail == 0)
+     */
+	struct {
+		uint64_t reserved_52_63:12;
+		/*
+		 * set when there is one or more POW entries on the
+		 * free list.
+		 */
+		uint64_t free_val:1;
+		/*
+		 * set when there is exactly one POW entry on the free
+		 * list.
+		 */
+		uint64_t free_one:1;
+		uint64_t reserved_49:1;
+		/*
+		 * when free_val is set, indicates the first entry on
+		 * the free list.
+		 */
+		uint64_t free_head:11;
+		uint64_t reserved_37:1;
+		/*
+		 * when free_val is set, indicates the last entry on
+		 * the free list.
+		 */
+		uint64_t free_tail:11;
+		/*
+		 * set when there is one or more POW entries on the
+		 * input Q list selected by qosgrp.
+		 */
+		uint64_t loc_val:1;
+		/*
+		 * set when there is exactly one POW entry on the
+		 * input Q list selected by qosgrp.
+		 */
+		uint64_t loc_one:1;
+		uint64_t reserved_23:1;
+		/*
+		 * when loc_val is set, indicates the first entry on
+		 * the input Q list selected by qosgrp.
+		 */
+		uint64_t loc_head:11;
+		uint64_t reserved_11:1;
+		/*
+		 * when loc_val is set, indicates the last entry on
+		 * the input Q list selected by qosgrp.
+		 */
+		uint64_t loc_tail:11;
+	} sindexload0;
+
+    /**
+     * Result For POW Index/Pointer Load (get_rmt == 0/get_des_get_tail == 1)
+     */
+	struct {
+		uint64_t reserved_52_63:12;
+		/*
+		 * set when there is one or more POW entries on the
+		 * nosched list.
+		 */
+		uint64_t nosched_val:1;
+		/*
+		 * set when there is exactly one POW entry on the
+		 * nosched list.
+		 */
+		uint64_t nosched_one:1;
+		uint64_t reserved_49:1;
+		/*
+		 * when nosched_val is set, indicates the first entry
+		 * on the nosched list.
+		 */
+		uint64_t nosched_head:11;
+		uint64_t reserved_37:1;
+		/*
+		 * when nosched_val is set, indicates the last entry
+		 * on the nosched list.
+		 */
+		uint64_t nosched_tail:11;
+		/*
+		 * set when there is one or more descheduled heads on
+		 * the descheduled list selected by qosgrp.
+		 */
+		uint64_t des_val:1;
+		/*
+		 * set when there is exactly one descheduled head on
+		 * the descheduled list selected by qosgrp.
+		 */
+		uint64_t des_one:1;
+		uint64_t reserved_23:1;
+		/*
+		 * when des_val is set, indicates the first
+		 * descheduled head on the descheduled list selected
+		 * by qosgrp.
+		 */
+		uint64_t des_head:11;
+		uint64_t reserved_11:1;
+		/*
+		 * when des_val is set, indicates the last descheduled
+		 * head on the descheduled list selected by qosgrp.
+		 */
+		uint64_t des_tail:11;
+	} sindexload1;
+
+    /**
+     * Result For POW Index/Pointer Load (get_rmt == 1/get_des_get_tail == 0)
+     */
+	struct {
+		uint64_t reserved_39_63:25;
+		/*
+		 * Set when this DRAM list is the current head
+		 * (i.e. is the next to be reloaded when the POW
+		 * hardware reloads a POW entry from DRAM). The POW
+		 * hardware alternates between the two DRAM lists
+		 * associated with a QOS level when it reloads work
+		 * from DRAM into the POW unit.
+		 */
+		uint64_t rmt_is_head:1;
+		/*
+		 * Set when the DRAM portion of the input Q list
+		 * selected by qosgrp contains one or more pieces of
+		 * work.
+		 */
+		uint64_t rmt_val:1;
+		/*
+		 * Set when the DRAM portion of the input Q list
+		 * selected by qosgrp contains exactly one piece of
+		 * work.
+		 */
+		uint64_t rmt_one:1;
+		/*
+		 * When rmt_val is set, indicates the first piece of
+		 * work on the DRAM input Q list selected by
+		 * qosgrp.
+		 */
+		uint64_t rmt_head:36;
+	} sindexload2;
+
+    /**
+     * Result For POW Index/Pointer Load (get_rmt ==
+     * 1/get_des_get_tail == 1)
+     */
+	struct {
+		uint64_t reserved_39_63:25;
+		/*
+		 * set when this DRAM list is the current head
+		 * (i.e. is the next to be reloaded when the POW
+		 * hardware reloads a POW entry from DRAM). The POW
+		 * hardware alternates between the two DRAM lists
+		 * associated with a QOS level when it reloads work
+		 * from DRAM into the POW unit.
+		 */
+		uint64_t rmt_is_head:1;
+		/*
+		 * set when the DRAM portion of the input Q list
+		 * selected by qosgrp contains one or more pieces of
+		 * work.
+		 */
+		uint64_t rmt_val:1;
+		/*
+		 * set when the DRAM portion of the input Q list
+		 * selected by qosgrp contains exactly one piece of
+		 * work.
+		 */
+		uint64_t rmt_one:1;
+		/*
+		 * when rmt_val is set, indicates the last piece of
+		 * work on the DRAM input Q list selected by
+		 * qosgrp.
+		 */
+		uint64_t rmt_tail:36;
+	} sindexload3;
+
+    /**
+     * Response to NULL_RD request loads
+     */
+	struct {
+		uint64_t unused:62;
+		/* of type cvmx_pow_tag_type_t. state is one of the
+		 * following:
+		 *
+		 * - CVMX_POW_TAG_TYPE_ORDERED
+		 * - CVMX_POW_TAG_TYPE_ATOMIC
+		 * - CVMX_POW_TAG_TYPE_NULL
+		 * - CVMX_POW_TAG_TYPE_NULL_NULL
+		 */
+		uint64_t state:2;
+	} s_null_rd;
+
+} cvmx_pow_tag_load_resp_t;
+
+/**
+ * This structure describes the address used for stores to the POW.
+ *  The store address is meaningful on stores to the POW.  The
+ *  hardware assumes that an aligned 64-bit store was used for all
+ *  these stores.  Note the assumption that the work queue entry is
+ *  aligned on an 8-byte boundary (since the low-order 3 address bits
+ *  must be zero).  Note that not all fields are used by all
+ *  operations.
+ *
+ *  NOTE: The following is the behavior of the pending switch bit at the PP
+ *       for POW stores (i.e. when did<7:3> == 0xc)
+ *     - did<2:0> == 0      => pending switch bit is set
+ *     - did<2:0> == 1      => no affect on the pending switch bit
+ *     - did<2:0> == 3      => pending switch bit is cleared
+ *     - did<2:0> == 7      => no affect on the pending switch bit
+ *     - did<2:0> == others => must not be used
+ *     - No other loads/stores have an affect on the pending switch bit
+ *     - The switch bus from POW can clear the pending switch bit
+ *
+ *  NOTE: did<2:0> == 2 is used by the HW for a special single-cycle
+ *  ADDWQ command that only contains the pointer). SW must never use
+ *  did<2:0> == 2.
+ */
+typedef union {
+    /**
+     * Unsigned 64 bit integer representation of store address
+     */
+	uint64_t u64;
+
+	struct {
+		/* Memory region.  Should be CVMX_IO_SEG in most cases */
+		uint64_t mem_reg:2;
+		uint64_t reserved_49_61:13;	/* Must be zero */
+		uint64_t is_io:1;	/* Must be one */
+		/* Device ID of POW.  Note that different sub-dids are used. */
+		uint64_t did:8;
+		uint64_t reserved_36_39:4;	/* Must be zero */
+		/* Address field. addr<2:0> must be zero */
+		uint64_t addr:36;
+	} stag;
+} cvmx_pow_tag_store_addr_t;
+
+/**
+ * decode of the store data when an IOBDMA SENDSINGLE is sent to POW
+ */
+typedef union {
+	uint64_t u64;
+
+	struct {
+		/*
+		 * the (64-bit word) location in scratchpad to write
+		 * to (if len != 0)
+		 */
+		uint64_t scraddr:8;
+		/* the number of words in the response (0 => no response) */
+		uint64_t len:8;
+		/* the ID of the device on the non-coherent bus */
+		uint64_t did:8;
+		uint64_t unused:36;
+		/* if set, don't return load response until work is available */
+		uint64_t wait:1;
+		uint64_t unused2:3;
+	} s;
+
+} cvmx_pow_iobdma_store_t;
+
+/* CSR typedefs have been moved to cvmx-csr-*.h */
+
+/**
+ * Get the POW tag for this core. This returns the current
+ * tag type, tag, group, and POW entry index associated with
+ * this core. Index is only valid if the tag type isn't NULL_NULL.
+ * If a tag switch is pending this routine returns the tag before
+ * the tag switch, not after.
+ *
+ * Returns Current tag
+ */
+static inline cvmx_pow_tag_req_t cvmx_pow_get_current_tag(void)
+{
+	cvmx_pow_load_addr_t load_addr;
+	cvmx_pow_tag_load_resp_t load_resp;
+	cvmx_pow_tag_req_t result;
+
+	load_addr.u64 = 0;
+	load_addr.sstatus.mem_region = CVMX_IO_SEG;
+	load_addr.sstatus.is_io = 1;
+	load_addr.sstatus.did = CVMX_OCT_DID_TAG_TAG1;
+	load_addr.sstatus.coreid = cvmx_get_core_num();
+	load_addr.sstatus.get_cur = 1;
+	load_resp.u64 = cvmx_read_csr(load_addr.u64);
+	result.u64 = 0;
+	result.s.grp = load_resp.s_sstatus2.grp;
+	result.s.index = load_resp.s_sstatus2.index;
+	result.s.type = load_resp.s_sstatus2.tag_type;
+	result.s.tag = load_resp.s_sstatus2.tag;
+	return result;
+}
+
+/**
+ * Get the POW WQE for this core. This returns the work queue
+ * entry currently associated with this core.
+ *
+ * Returns WQE pointer
+ */
+static inline cvmx_wqe_t *cvmx_pow_get_current_wqp(void)
+{
+	cvmx_pow_load_addr_t load_addr;
+	cvmx_pow_tag_load_resp_t load_resp;
+
+	load_addr.u64 = 0;
+	load_addr.sstatus.mem_region = CVMX_IO_SEG;
+	load_addr.sstatus.is_io = 1;
+	load_addr.sstatus.did = CVMX_OCT_DID_TAG_TAG1;
+	load_addr.sstatus.coreid = cvmx_get_core_num();
+	load_addr.sstatus.get_cur = 1;
+	load_addr.sstatus.get_wqp = 1;
+	load_resp.u64 = cvmx_read_csr(load_addr.u64);
+	return (cvmx_wqe_t *) cvmx_phys_to_ptr(load_resp.s_sstatus4.wqp);
+}
+
+#ifndef CVMX_MF_CHORD
+#define CVMX_MF_CHORD(dest)         CVMX_RDHWR(dest, 30)
+#endif
+
+/**
+ * Print a warning if a tag switch is pending for this core
+ *
+ * @function: Function name checking for a pending tag switch
+ */
+static inline void __cvmx_pow_warn_if_pending_switch(const char *function)
+{
+	uint64_t switch_complete;
+	CVMX_MF_CHORD(switch_complete);
+	if (!switch_complete)
+		pr_warning("%s called with tag switch in progress\n", function);
+}
+
+/**
+ * Waits for a tag switch to complete by polling the completion bit.
+ * Note that switches to NULL complete immediately and do not need
+ * to be waited for.
+ */
+static inline void cvmx_pow_tag_sw_wait(void)
+{
+	const uint64_t MAX_CYCLES = 1ull << 31;
+	uint64_t switch_complete;
+	uint64_t start_cycle = cvmx_get_cycle();
+	while (1) {
+		CVMX_MF_CHORD(switch_complete);
+		if (unlikely(switch_complete))
+			break;
+		if (unlikely(cvmx_get_cycle() > start_cycle + MAX_CYCLES)) {
+			pr_warning("Tag switch is taking a long time, "
+				   "possible deadlock\n");
+			start_cycle = -MAX_CYCLES - 1;
+		}
+	}
+}
+
+/**
+ * Synchronous work request.  Requests work from the POW.
+ * This function does NOT wait for previous tag switches to complete,
+ * so the caller must ensure that there is not a pending tag switch.
+ *
+ * @wait:   When set, call stalls until work becomes avaiable, or times out.
+ *               If not set, returns immediately.
+ *
+ * Returns Returns the WQE pointer from POW. Returns NULL if no work
+ * was available.
+ */
+static inline cvmx_wqe_t *cvmx_pow_work_request_sync_nocheck(cvmx_pow_wait_t
+							     wait)
+{
+	cvmx_pow_load_addr_t ptr;
+	cvmx_pow_tag_load_resp_t result;
+
+	if (CVMX_ENABLE_POW_CHECKS)
+		__cvmx_pow_warn_if_pending_switch(__func__);
+
+	ptr.u64 = 0;
+	ptr.swork.mem_region = CVMX_IO_SEG;
+	ptr.swork.is_io = 1;
+	ptr.swork.did = CVMX_OCT_DID_TAG_SWTAG;
+	ptr.swork.wait = wait;
+
+	result.u64 = cvmx_read_csr(ptr.u64);
+
+	if (result.s_work.no_work)
+		return NULL;
+	else
+		return (cvmx_wqe_t *) cvmx_phys_to_ptr(result.s_work.addr);
+}
+
+/**
+ * Synchronous work request.  Requests work from the POW.
+ * This function waits for any previous tag switch to complete before
+ * requesting the new work.
+ *
+ * @wait:   When set, call stalls until work becomes avaiable, or times out.
+ *               If not set, returns immediately.
+ *
+ * Returns Returns the WQE pointer from POW. Returns NULL if no work
+ * was available.
+ */
+static inline cvmx_wqe_t *cvmx_pow_work_request_sync(cvmx_pow_wait_t wait)
+{
+	if (CVMX_ENABLE_POW_CHECKS)
+		__cvmx_pow_warn_if_pending_switch(__func__);
+
+	/* Must not have a switch pending when requesting work */
+	cvmx_pow_tag_sw_wait();
+	return cvmx_pow_work_request_sync_nocheck(wait);
+
+}
+
+/**
+ * Synchronous null_rd request.  Requests a switch out of NULL_NULL POW state.
+ * This function waits for any previous tag switch to complete before
+ * requesting the null_rd.
+ *
+ * Returns Returns the POW state of type cvmx_pow_tag_type_t.
+ */
+static inline enum cvmx_pow_tag_type cvmx_pow_work_request_null_rd(void)
+{
+	cvmx_pow_load_addr_t ptr;
+	cvmx_pow_tag_load_resp_t result;
+
+	if (CVMX_ENABLE_POW_CHECKS)
+		__cvmx_pow_warn_if_pending_switch(__func__);
+
+	/* Must not have a switch pending when requesting work */
+	cvmx_pow_tag_sw_wait();
+
+	ptr.u64 = 0;
+	ptr.snull_rd.mem_region = CVMX_IO_SEG;
+	ptr.snull_rd.is_io = 1;
+	ptr.snull_rd.did = CVMX_OCT_DID_TAG_NULL_RD;
+
+	result.u64 = cvmx_read_csr(ptr.u64);
+
+	return (enum cvmx_pow_tag_type) result.s_null_rd.state;
+}
+
+/**
+ * Asynchronous work request.  Work is requested from the POW unit,
+ * and should later be checked with function
+ * cvmx_pow_work_response_async.  This function does NOT wait for
+ * previous tag switches to complete, so the caller must ensure that
+ * there is not a pending tag switch.
+ *
+ * @scr_addr: Scratch memory address that response will be returned
+ *            to, which is either a valid WQE, or a response with the
+ *            invalid bit set.  Byte address, must be 8 byte aligned.
+ *
+ * @wait: 1 to cause response to wait for work to become available (or
+ *        timeout), 0 to cause response to return immediately
+ */
+static inline void cvmx_pow_work_request_async_nocheck(int scr_addr,
+						       cvmx_pow_wait_t wait)
+{
+	cvmx_pow_iobdma_store_t data;
+
+	if (CVMX_ENABLE_POW_CHECKS)
+		__cvmx_pow_warn_if_pending_switch(__func__);
+
+	/* scr_addr must be 8 byte aligned */
+	data.s.scraddr = scr_addr >> 3;
+	data.s.len = 1;
+	data.s.did = CVMX_OCT_DID_TAG_SWTAG;
+	data.s.wait = wait;
+	cvmx_send_single(data.u64);
+}
+
+/**
+ * Asynchronous work request.  Work is requested from the POW unit,
+ * and should later be checked with function
+ * cvmx_pow_work_response_async.  This function waits for any previous
+ * tag switch to complete before requesting the new work.
+ *
+ * @scr_addr: Scratch memory address that response will be returned
+ *            to, which is either a valid WQE, or a response with the
+ *            invalid bit set.  Byte address, must be 8 byte aligned.
+ *
+ * @wait: 1 to cause response to wait for work to become available (or
+ *                  timeout), 0 to cause response to return immediately
+ */
+static inline void cvmx_pow_work_request_async(int scr_addr,
+					       cvmx_pow_wait_t wait)
+{
+	if (CVMX_ENABLE_POW_CHECKS)
+		__cvmx_pow_warn_if_pending_switch(__func__);
+
+	/* Must not have a switch pending when requesting work */
+	cvmx_pow_tag_sw_wait();
+	cvmx_pow_work_request_async_nocheck(scr_addr, wait);
+}
+
+/**
+ * Gets result of asynchronous work request.  Performs a IOBDMA sync
+ * to wait for the response.
+ *
+ * @scr_addr: Scratch memory address to get result from Byte address,
+ *            must be 8 byte aligned.
+ *
+ * Returns Returns the WQE from the scratch register, or NULL if no
+ * work was available.
+ */
+static inline cvmx_wqe_t *cvmx_pow_work_response_async(int scr_addr)
+{
+	cvmx_pow_tag_load_resp_t result;
+
+	CVMX_SYNCIOBDMA;
+	result.u64 = cvmx_scratch_read64(scr_addr);
+
+	if (result.s_work.no_work)
+		return NULL;
+	else
+		return (cvmx_wqe_t *) cvmx_phys_to_ptr(result.s_work.addr);
+}
+
+/**
+ * Checks if a work queue entry pointer returned by a work
+ * request is valid.  It may be invalid due to no work
+ * being available or due to a timeout.
+ *
+ * @wqe_ptr: pointer to a work queue entry returned by the POW
+ *
+ * Returns 0 if pointer is valid
+ *         1 if invalid (no work was returned)
+ */
+static inline uint64_t cvmx_pow_work_invalid(cvmx_wqe_t *wqe_ptr)
+{
+	return wqe_ptr == NULL;
+}
+
+/**
+ * Starts a tag switch to the provided tag value and tag type.
+ * Completion for the tag switch must be checked for separately.  This
+ * function does NOT update the work queue entry in dram to match tag
+ * value and type, so the application must keep track of these if they
+ * are important to the application.  This tag switch command must not
+ * be used for switches to NULL, as the tag switch pending bit will be
+ * set by the switch request, but never cleared by the hardware.
+ *
+ * NOTE: This should not be used when switching from a NULL tag.  Use
+ * cvmx_pow_tag_sw_full() instead.
+ *
+ * This function does no checks, so the caller must ensure that any
+ * previous tag switch has completed.
+ *
+ * @tag:      new tag value
+ * @tag_type: new tag type (ordered or atomic)
+ */
+static inline void cvmx_pow_tag_sw_nocheck(uint32_t tag,
+					   enum cvmx_pow_tag_type tag_type)
+{
+	cvmx_addr_t ptr;
+	cvmx_pow_tag_req_t tag_req;
+
+	if (CVMX_ENABLE_POW_CHECKS) {
+		cvmx_pow_tag_req_t current_tag;
+		__cvmx_pow_warn_if_pending_switch(__func__);
+		current_tag = cvmx_pow_get_current_tag();
+		if (current_tag.s.type == CVMX_POW_TAG_TYPE_NULL_NULL)
+			pr_warning("%s called with NULL_NULL tag\n",
+				   __func__);
+		if (current_tag.s.type == CVMX_POW_TAG_TYPE_NULL)
+			pr_warning("%s called with NULL tag\n", __func__);
+		if ((current_tag.s.type == tag_type)
+		   && (current_tag.s.tag == tag))
+			pr_warning("%s called to perform a tag switch to the "
+				   "same tag\n",
+			     __func__);
+		if (tag_type == CVMX_POW_TAG_TYPE_NULL)
+			pr_warning("%s called to perform a tag switch to "
+				   "NULL. Use cvmx_pow_tag_sw_null() instead\n",
+			     __func__);
+	}
+
+	/*
+	 * Note that WQE in DRAM is not updated here, as the POW does
+	 * not read from DRAM once the WQE is in flight.  See hardware
+	 * manual for complete details.  It is the application's
+	 * responsibility to keep track of the current tag value if
+	 * that is important.
+	 */
+
+	tag_req.u64 = 0;
+	tag_req.s.op = CVMX_POW_TAG_OP_SWTAG;
+	tag_req.s.tag = tag;
+	tag_req.s.type = tag_type;
+
+	ptr.u64 = 0;
+	ptr.sio.mem_region = CVMX_IO_SEG;
+	ptr.sio.is_io = 1;
+	ptr.sio.did = CVMX_OCT_DID_TAG_SWTAG;
+
+	/* once this store arrives at POW, it will attempt the switch
+	   software must wait for the switch to complete separately */
+	cvmx_write_io(ptr.u64, tag_req.u64);
+}
+
+/**
+ * Starts a tag switch to the provided tag value and tag type.
+ * Completion for the tag switch must be checked for separately.  This
+ * function does NOT update the work queue entry in dram to match tag
+ * value and type, so the application must keep track of these if they
+ * are important to the application.  This tag switch command must not
+ * be used for switches to NULL, as the tag switch pending bit will be
+ * set by the switch request, but never cleared by the hardware.
+ *
+ * NOTE: This should not be used when switching from a NULL tag.  Use
+ * cvmx_pow_tag_sw_full() instead.
+ *
+ * This function waits for any previous tag switch to complete, and also
+ * displays an error on tag switches to NULL.
+ *
+ * @tag:      new tag value
+ * @tag_type: new tag type (ordered or atomic)
+ */
+static inline void cvmx_pow_tag_sw(uint32_t tag,
+				   enum cvmx_pow_tag_type tag_type)
+{
+	if (CVMX_ENABLE_POW_CHECKS)
+		__cvmx_pow_warn_if_pending_switch(__func__);
+
+	/*
+	 * Note that WQE in DRAM is not updated here, as the POW does
+	 * not read from DRAM once the WQE is in flight.  See hardware
+	 * manual for complete details.  It is the application's
+	 * responsibility to keep track of the current tag value if
+	 * that is important.
+	 */
+
+	/*
+	 * Ensure that there is not a pending tag switch, as a tag
+	 * switch cannot be started if a previous switch is still
+	 * pending.
+	 */
+	cvmx_pow_tag_sw_wait();
+	cvmx_pow_tag_sw_nocheck(tag, tag_type);
+}
+
+/**
+ * Starts a tag switch to the provided tag value and tag type.
+ * Completion for the tag switch must be checked for separately.  This
+ * function does NOT update the work queue entry in dram to match tag
+ * value and type, so the application must keep track of these if they
+ * are important to the application.  This tag switch command must not
+ * be used for switches to NULL, as the tag switch pending bit will be
+ * set by the switch request, but never cleared by the hardware.
+ *
+ * This function must be used for tag switches from NULL.
+ *
+ * This function does no checks, so the caller must ensure that any
+ * previous tag switch has completed.
+ *
+ * @wqp:      pointer to work queue entry to submit.  This entry is
+ *            updated to match the other parameters
+ * @tag:      tag value to be assigned to work queue entry
+ * @tag_type: type of tag
+ * @group:    group value for the work queue entry.
+ */
+static inline void cvmx_pow_tag_sw_full_nocheck(cvmx_wqe_t *wqp, uint32_t tag,
+						enum cvmx_pow_tag_type tag_type,
+						uint64_t group)
+{
+	cvmx_addr_t ptr;
+	cvmx_pow_tag_req_t tag_req;
+
+	if (CVMX_ENABLE_POW_CHECKS) {
+		cvmx_pow_tag_req_t current_tag;
+		__cvmx_pow_warn_if_pending_switch(__func__);
+		current_tag = cvmx_pow_get_current_tag();
+		if (current_tag.s.type == CVMX_POW_TAG_TYPE_NULL_NULL)
+			pr_warning("%s called with NULL_NULL tag\n",
+				   __func__);
+		if ((current_tag.s.type == tag_type)
+		   && (current_tag.s.tag == tag))
+			pr_warning("%s called to perform a tag switch to "
+				   "the same tag\n",
+			     __func__);
+		if (tag_type == CVMX_POW_TAG_TYPE_NULL)
+			pr_warning("%s called to perform a tag switch to "
+				   "NULL. Use cvmx_pow_tag_sw_null() instead\n",
+			     __func__);
+		if (wqp != cvmx_phys_to_ptr(0x80))
+			if (wqp != cvmx_pow_get_current_wqp())
+				pr_warning("%s passed WQE(%p) doesn't match "
+					   "the address in the POW(%p)\n",
+				     __func__, wqp,
+				     cvmx_pow_get_current_wqp());
+	}
+
+	/*
+	 * Note that WQE in DRAM is not updated here, as the POW does
+	 * not read from DRAM once the WQE is in flight.  See hardware
+	 * manual for complete details.  It is the application's
+	 * responsibility to keep track of the current tag value if
+	 * that is important.
+	 */
+
+	tag_req.u64 = 0;
+	tag_req.s.op = CVMX_POW_TAG_OP_SWTAG_FULL;
+	tag_req.s.tag = tag;
+	tag_req.s.type = tag_type;
+	tag_req.s.grp = group;
+
+	ptr.u64 = 0;
+	ptr.sio.mem_region = CVMX_IO_SEG;
+	ptr.sio.is_io = 1;
+	ptr.sio.did = CVMX_OCT_DID_TAG_SWTAG;
+	ptr.sio.offset = CAST64(wqp);
+
+	/*
+	 * once this store arrives at POW, it will attempt the switch
+	 * software must wait for the switch to complete separately.
+	 */
+	cvmx_write_io(ptr.u64, tag_req.u64);
+}
+
+/**
+ * Starts a tag switch to the provided tag value and tag type.
+ * Completion for the tag switch must be checked for separately.  This
+ * function does NOT update the work queue entry in dram to match tag
+ * value and type, so the application must keep track of these if they
+ * are important to the application.  This tag switch command must not
+ * be used for switches to NULL, as the tag switch pending bit will be
+ * set by the switch request, but never cleared by the hardware.
+ *
+ * This function must be used for tag switches from NULL.
+ *
+ * This function waits for any pending tag switches to complete
+ * before requesting the tag switch.
+ *
+ * @wqp:      pointer to work queue entry to submit.  This entry is updated
+ *            to match the other parameters
+ * @tag:      tag value to be assigned to work queue entry
+ * @tag_type: type of tag
+ * @group:      group value for the work queue entry.
+ */
+static inline void cvmx_pow_tag_sw_full(cvmx_wqe_t *wqp, uint32_t tag,
+					enum cvmx_pow_tag_type tag_type,
+					uint64_t group)
+{
+	if (CVMX_ENABLE_POW_CHECKS)
+		__cvmx_pow_warn_if_pending_switch(__func__);
+
+	/*
+	 * Ensure that there is not a pending tag switch, as a tag
+	 * switch cannot be started if a previous switch is still
+	 * pending.
+	 */
+	cvmx_pow_tag_sw_wait();
+	cvmx_pow_tag_sw_full_nocheck(wqp, tag, tag_type, group);
+}
+
+/**
+ * Switch to a NULL tag, which ends any ordering or
+ * synchronization provided by the POW for the current
+ * work queue entry.  This operation completes immediatly,
+ * so completetion should not be waited for.
+ * This function does NOT wait for previous tag switches to complete,
+ * so the caller must ensure that any previous tag switches have completed.
+ */
+static inline void cvmx_pow_tag_sw_null_nocheck(void)
+{
+	cvmx_addr_t ptr;
+	cvmx_pow_tag_req_t tag_req;
+
+	if (CVMX_ENABLE_POW_CHECKS) {
+		cvmx_pow_tag_req_t current_tag;
+		__cvmx_pow_warn_if_pending_switch(__func__);
+		current_tag = cvmx_pow_get_current_tag();
+		if (current_tag.s.type == CVMX_POW_TAG_TYPE_NULL_NULL)
+			pr_warning("%s called with NULL_NULL tag\n",
+				   __func__);
+		if (current_tag.s.type == CVMX_POW_TAG_TYPE_NULL)
+			pr_warning("%s called when we already have a "
+				   "NULL tag\n",
+			     __func__);
+	}
+
+	tag_req.u64 = 0;
+	tag_req.s.op = CVMX_POW_TAG_OP_SWTAG;
+	tag_req.s.type = CVMX_POW_TAG_TYPE_NULL;
+
+	ptr.u64 = 0;
+	ptr.sio.mem_region = CVMX_IO_SEG;
+	ptr.sio.is_io = 1;
+	ptr.sio.did = CVMX_OCT_DID_TAG_TAG1;
+
+	cvmx_write_io(ptr.u64, tag_req.u64);
+
+	/* switch to NULL completes immediately */
+}
+
+/**
+ * Switch to a NULL tag, which ends any ordering or
+ * synchronization provided by the POW for the current
+ * work queue entry.  This operation completes immediatly,
+ * so completetion should not be waited for.
+ * This function waits for any pending tag switches to complete
+ * before requesting the switch to NULL.
+ */
+static inline void cvmx_pow_tag_sw_null(void)
+{
+	if (CVMX_ENABLE_POW_CHECKS)
+		__cvmx_pow_warn_if_pending_switch(__func__);
+
+	/*
+	 * Ensure that there is not a pending tag switch, as a tag
+	 * switch cannot be started if a previous switch is still
+	 * pending.
+	 */
+	cvmx_pow_tag_sw_wait();
+	cvmx_pow_tag_sw_null_nocheck();
+
+	/* switch to NULL completes immediately */
+}
+
+/**
+ * Submits work to an input queue.  This function updates the work
+ * queue entry in DRAM to match the arguments given.  Note that the
+ * tag provided is for the work queue entry submitted, and is
+ * unrelated to the tag that the core currently holds.
+ *
+ * @wqp:      pointer to work queue entry to submit.  This entry is
+ *            updated to match the other parameters
+ * @tag:      tag value to be assigned to work queue entry
+ * @tag_type: type of tag
+ * @qos:      Input queue to add to.
+ * @grp:      group value for the work queue entry.
+ */
+static inline void cvmx_pow_work_submit(cvmx_wqe_t *wqp, uint32_t tag,
+					enum cvmx_pow_tag_type tag_type,
+					uint64_t qos, uint64_t grp)
+{
+	cvmx_addr_t ptr;
+	cvmx_pow_tag_req_t tag_req;
+
+	wqp->qos = qos;
+	wqp->tag = tag;
+	wqp->tag_type = tag_type;
+	wqp->grp = grp;
+
+	tag_req.u64 = 0;
+	tag_req.s.op = CVMX_POW_TAG_OP_ADDWQ;
+	tag_req.s.type = tag_type;
+	tag_req.s.tag = tag;
+	tag_req.s.qos = qos;
+	tag_req.s.grp = grp;
+
+	ptr.u64 = 0;
+	ptr.sio.mem_region = CVMX_IO_SEG;
+	ptr.sio.is_io = 1;
+	ptr.sio.did = CVMX_OCT_DID_TAG_TAG1;
+	ptr.sio.offset = cvmx_ptr_to_phys(wqp);
+
+	/*
+	 * SYNC write to memory before the work submit.  This is
+	 * necessary as POW may read values from DRAM at this time.
+	 */
+	CVMX_SYNCWS;
+	cvmx_write_io(ptr.u64, tag_req.u64);
+}
+
+/**
+ * This function sets the group mask for a core.  The group mask
+ * indicates which groups each core will accept work from. There are
+ * 16 groups.
+ *
+ * @core_num:   core to apply mask to
+ * @mask:   Group mask. There are 16 groups, so only bits 0-15 are valid,
+ *               representing groups 0-15.
+ *               Each 1 bit in the mask enables the core to accept work from
+ *               the corresponding group.
+ */
+static inline void cvmx_pow_set_group_mask(uint64_t core_num, uint64_t mask)
+{
+	union cvmx_pow_pp_grp_mskx grp_msk;
+
+	grp_msk.u64 = cvmx_read_csr(CVMX_POW_PP_GRP_MSKX(core_num));
+	grp_msk.s.grp_msk = mask;
+	cvmx_write_csr(CVMX_POW_PP_GRP_MSKX(core_num), grp_msk.u64);
+}
+
+/**
+ * This function sets POW static priorities for a core. Each input queue has
+ * an associated priority value.
+ *
+ * @core_num:   core to apply priorities to
+ * @priority:   Vector of 8 priorities, one per POW Input Queue (0-7).
+ *                   Highest priority is 0 and lowest is 7. A priority value
+ *                   of 0xF instructs POW to skip the Input Queue when
+ *                   scheduling to this specific core.
+ *                   NOTE: priorities should not have gaps in values, meaning
+ *                         {0,1,1,1,1,1,1,1} is a valid configuration while
+ *                         {0,2,2,2,2,2,2,2} is not.
+ */
+static inline void cvmx_pow_set_priority(uint64_t core_num,
+					 const uint8_t priority[])
+{
+	/* POW priorities are supported on CN5xxx and later */
+	if (!OCTEON_IS_MODEL(OCTEON_CN3XXX)) {
+		union cvmx_pow_pp_grp_mskx grp_msk;
+
+		grp_msk.u64 = cvmx_read_csr(CVMX_POW_PP_GRP_MSKX(core_num));
+		grp_msk.s.qos0_pri = priority[0];
+		grp_msk.s.qos1_pri = priority[1];
+		grp_msk.s.qos2_pri = priority[2];
+		grp_msk.s.qos3_pri = priority[3];
+		grp_msk.s.qos4_pri = priority[4];
+		grp_msk.s.qos5_pri = priority[5];
+		grp_msk.s.qos6_pri = priority[6];
+		grp_msk.s.qos7_pri = priority[7];
+
+		/* Detect gaps between priorities and flag error */
+		{
+			int i;
+			uint32_t prio_mask = 0;
+
+			for (i = 0; i < 8; i++)
+				if (priority[i] != 0xF)
+					prio_mask |= 1 << priority[i];
+
+			if (prio_mask ^ ((1 << cvmx_pop(prio_mask)) - 1)) {
+				pr_err("POW static priorities should be "
+				       "contiguous (0x%llx)\n",
+				     (unsigned long long)prio_mask);
+				return;
+			}
+		}
+
+		cvmx_write_csr(CVMX_POW_PP_GRP_MSKX(core_num), grp_msk.u64);
+	}
+}
+
+/**
+ * Performs a tag switch and then an immediate deschedule. This completes
+ * immediatly, so completion must not be waited for.  This function does NOT
+ * update the wqe in DRAM to match arguments.
+ *
+ * This function does NOT wait for any prior tag switches to complete, so the
+ * calling code must do this.
+ *
+ * Note the following CAVEAT of the Octeon HW behavior when
+ * re-scheduling DE-SCHEDULEd items whose (next) state is
+ * ORDERED:
+ *   - If there are no switches pending at the time that the
+ *     HW executes the de-schedule, the HW will only re-schedule
+ *     the head of the FIFO associated with the given tag. This
+ *     means that in many respects, the HW treats this ORDERED
+ *     tag as an ATOMIC tag. Note that in the SWTAG_DESCH
+ *     case (to an ORDERED tag), the HW will do the switch
+ *     before the deschedule whenever it is possible to do
+ *     the switch immediately, so it may often look like
+ *     this case.
+ *   - If there is a pending switch to ORDERED at the time
+ *     the HW executes the de-schedule, the HW will perform
+ *     the switch at the time it re-schedules, and will be
+ *     able to reschedule any/all of the entries with the
+ *     same tag.
+ * Due to this behavior, the RECOMMENDATION to software is
+ * that they have a (next) state of ATOMIC when they
+ * DE-SCHEDULE. If an ORDERED tag is what was really desired,
+ * SW can choose to immediately switch to an ORDERED tag
+ * after the work (that has an ATOMIC tag) is re-scheduled.
+ * Note that since there are never any tag switches pending
+ * when the HW re-schedules, this switch can be IMMEDIATE upon
+ * the reception of the pointer during the re-schedule.
+ *
+ * @tag:      New tag value
+ * @tag_type: New tag type
+ * @group:    New group value
+ * @no_sched: Control whether this work queue entry will be rescheduled.
+ *                 - 1 : don't schedule this work
+ *                 - 0 : allow this work to be scheduled.
+ */
+static inline void cvmx_pow_tag_sw_desched_nocheck(
+	uint32_t tag,
+	enum cvmx_pow_tag_type tag_type,
+	uint64_t group,
+	uint64_t no_sched)
+{
+	cvmx_addr_t ptr;
+	cvmx_pow_tag_req_t tag_req;
+
+	if (CVMX_ENABLE_POW_CHECKS) {
+		cvmx_pow_tag_req_t current_tag;
+		__cvmx_pow_warn_if_pending_switch(__func__);
+		current_tag = cvmx_pow_get_current_tag();
+		if (current_tag.s.type == CVMX_POW_TAG_TYPE_NULL_NULL)
+			pr_warning("%s called with NULL_NULL tag\n",
+				   __func__);
+		if (current_tag.s.type == CVMX_POW_TAG_TYPE_NULL)
+			pr_warning("%s called with NULL tag. Deschedule not "
+				   "allowed from NULL state\n",
+			     __func__);
+		if ((current_tag.s.type != CVMX_POW_TAG_TYPE_ATOMIC)
+			&& (tag_type != CVMX_POW_TAG_TYPE_ATOMIC))
+			pr_warning("%s called where neither the before or "
+				   "after tag is ATOMIC\n",
+			     __func__);
+	}
+
+	tag_req.u64 = 0;
+	tag_req.s.op = CVMX_POW_TAG_OP_SWTAG_DESCH;
+	tag_req.s.tag = tag;
+	tag_req.s.type = tag_type;
+	tag_req.s.grp = group;
+	tag_req.s.no_sched = no_sched;
+
+	ptr.u64 = 0;
+	ptr.sio.mem_region = CVMX_IO_SEG;
+	ptr.sio.is_io = 1;
+	ptr.sio.did = CVMX_OCT_DID_TAG_TAG3;
+	/*
+	 * since TAG3 is used, this store will clear the local pending
+	 * switch bit.
+	 */
+	cvmx_write_io(ptr.u64, tag_req.u64);
+}
+
+/**
+ * Performs a tag switch and then an immediate deschedule. This completes
+ * immediatly, so completion must not be waited for.  This function does NOT
+ * update the wqe in DRAM to match arguments.
+ *
+ * This function waits for any prior tag switches to complete, so the
+ * calling code may call this function with a pending tag switch.
+ *
+ * Note the following CAVEAT of the Octeon HW behavior when
+ * re-scheduling DE-SCHEDULEd items whose (next) state is
+ * ORDERED:
+ *   - If there are no switches pending at the time that the
+ *     HW executes the de-schedule, the HW will only re-schedule
+ *     the head of the FIFO associated with the given tag. This
+ *     means that in many respects, the HW treats this ORDERED
+ *     tag as an ATOMIC tag. Note that in the SWTAG_DESCH
+ *     case (to an ORDERED tag), the HW will do the switch
+ *     before the deschedule whenever it is possible to do
+ *     the switch immediately, so it may often look like
+ *     this case.
+ *   - If there is a pending switch to ORDERED at the time
+ *     the HW executes the de-schedule, the HW will perform
+ *     the switch at the time it re-schedules, and will be
+ *     able to reschedule any/all of the entries with the
+ *     same tag.
+ * Due to this behavior, the RECOMMENDATION to software is
+ * that they have a (next) state of ATOMIC when they
+ * DE-SCHEDULE. If an ORDERED tag is what was really desired,
+ * SW can choose to immediately switch to an ORDERED tag
+ * after the work (that has an ATOMIC tag) is re-scheduled.
+ * Note that since there are never any tag switches pending
+ * when the HW re-schedules, this switch can be IMMEDIATE upon
+ * the reception of the pointer during the re-schedule.
+ *
+ * @tag:      New tag value
+ * @tag_type: New tag type
+ * @group:    New group value
+ * @no_sched: Control whether this work queue entry will be rescheduled.
+ *                 - 1 : don't schedule this work
+ *                 - 0 : allow this work to be scheduled.
+ */
+static inline void cvmx_pow_tag_sw_desched(uint32_t tag,
+					   enum cvmx_pow_tag_type tag_type,
+					   uint64_t group, uint64_t no_sched)
+{
+	if (CVMX_ENABLE_POW_CHECKS)
+		__cvmx_pow_warn_if_pending_switch(__func__);
+
+	/* Need to make sure any writes to the work queue entry are complete */
+	CVMX_SYNCWS;
+	/*
+	 * Ensure that there is not a pending tag switch, as a tag
+	 * switch cannot be started if a previous switch is still
+	 * pending.
+	 */
+	cvmx_pow_tag_sw_wait();
+	cvmx_pow_tag_sw_desched_nocheck(tag, tag_type, group, no_sched);
+}
+
+/**
+ * Descchedules the current work queue entry.
+ *
+ * @no_sched: no schedule flag value to be set on the work queue
+ *            entry.  If this is set the entry will not be
+ *            rescheduled.
+ */
+static inline void cvmx_pow_desched(uint64_t no_sched)
+{
+	cvmx_addr_t ptr;
+	cvmx_pow_tag_req_t tag_req;
+
+	if (CVMX_ENABLE_POW_CHECKS) {
+		cvmx_pow_tag_req_t current_tag;
+		__cvmx_pow_warn_if_pending_switch(__func__);
+		current_tag = cvmx_pow_get_current_tag();
+		if (current_tag.s.type == CVMX_POW_TAG_TYPE_NULL_NULL)
+			pr_warning("%s called with NULL_NULL tag\n",
+				   __func__);
+		if (current_tag.s.type == CVMX_POW_TAG_TYPE_NULL)
+			pr_warning("%s called with NULL tag. Deschedule not "
+				   "expected from NULL state\n",
+			     __func__);
+	}
+
+	/* Need to make sure any writes to the work queue entry are complete */
+	CVMX_SYNCWS;
+
+	tag_req.u64 = 0;
+	tag_req.s.op = CVMX_POW_TAG_OP_DESCH;
+	tag_req.s.no_sched = no_sched;
+
+	ptr.u64 = 0;
+	ptr.sio.mem_region = CVMX_IO_SEG;
+	ptr.sio.is_io = 1;
+	ptr.sio.did = CVMX_OCT_DID_TAG_TAG3;
+	/*
+	 * since TAG3 is used, this store will clear the local pending
+	 * switch bit.
+	 */
+	cvmx_write_io(ptr.u64, tag_req.u64);
+}
+
+/****************************************************
+* Define usage of bits within the 32 bit tag values.
+*****************************************************/
+
+/*
+ * Number of bits of the tag used by software.  The SW bits are always
+ * a contiguous block of the high starting at bit 31.  The hardware
+ * bits are always the low bits.  By default, the top 8 bits of the
+ * tag are reserved for software, and the low 24 are set by the IPD
+ * unit.
+ */
+#define CVMX_TAG_SW_BITS    (8)
+#define CVMX_TAG_SW_SHIFT   (32 - CVMX_TAG_SW_BITS)
+
+/* Below is the list of values for the top 8 bits of the tag. */
+/*
+ * Tag values with top byte of this value are reserved for internal
+ * executive uses.
+ */
+#define CVMX_TAG_SW_BITS_INTERNAL  0x1
+/* The executive divides the remaining 24 bits as follows:
+ *  - the upper 8 bits (bits 23 - 16 of the tag) define a subgroup
+ *
+ *  - the lower 16 bits (bits 15 - 0 of the tag) define are the value
+ *    with the subgroup
+ *
+ * Note that this section describes the format of tags generated by
+ * software - refer to the hardware documentation for a description of
+ * the tags values generated by the packet input hardware.  Subgroups
+ * are defined here.
+ */
+/* Mask for the value portion of the tag */
+#define CVMX_TAG_SUBGROUP_MASK  0xFFFF
+#define CVMX_TAG_SUBGROUP_SHIFT 16
+#define CVMX_TAG_SUBGROUP_PKO  0x1
+
+/* End of executive tag subgroup definitions */
+
+/*
+ * The remaining values software bit values 0x2 - 0xff are available
+ * for application use.
+ */
+
+/**
+ * This function creates a 32 bit tag value from the two values provided.
+ *
+ * @sw_bits: The upper bits (number depends on configuration) are set
+ *           to this value.  The remainder of bits are set by the
+ *           hw_bits parameter.
+ *
+ * @hw_bits: The lower bits (number depends on configuration) are set
+ *           to this value.  The remainder of bits are set by the
+ *           sw_bits parameter.
+ *
+ * Returns 32 bit value of the combined hw and sw bits.
+ */
+static inline uint32_t cvmx_pow_tag_compose(uint64_t sw_bits, uint64_t hw_bits)
+{
+	return ((sw_bits & cvmx_build_mask(CVMX_TAG_SW_BITS)) <<
+			CVMX_TAG_SW_SHIFT) |
+		(hw_bits & cvmx_build_mask(32 - CVMX_TAG_SW_BITS));
+}
+
+/**
+ * Extracts the bits allocated for software use from the tag
+ *
+ * @tag:    32 bit tag value
+ *
+ * Returns N bit software tag value, where N is configurable with the
+ * CVMX_TAG_SW_BITS define
+ */
+static inline uint32_t cvmx_pow_tag_get_sw_bits(uint64_t tag)
+{
+	return (tag >> (32 - CVMX_TAG_SW_BITS)) &
+		cvmx_build_mask(CVMX_TAG_SW_BITS);
+}
+
+/**
+ *
+ * Extracts the bits allocated for hardware use from the tag
+ *
+ * @tag:    32 bit tag value
+ *
+ * Returns (32 - N) bit software tag value, where N is configurable
+ * with the CVMX_TAG_SW_BITS define
+ */
+static inline uint32_t cvmx_pow_tag_get_hw_bits(uint64_t tag)
+{
+	return tag & cvmx_build_mask(32 - CVMX_TAG_SW_BITS);
+}
+
+/**
+ * Store the current POW internal state into the supplied
+ * buffer. It is recommended that you pass a buffer of at least
+ * 128KB. The format of the capture may change based on SDK
+ * version and Octeon chip.
+ *
+ * @buffer: Buffer to store capture into
+ * @buffer_size:
+ *               The size of the supplied buffer
+ *
+ * Returns Zero on sucess, negative on failure
+ */
+extern int cvmx_pow_capture(void *buffer, int buffer_size);
+
+/**
+ * Dump a POW capture to the console in a human readable format.
+ *
+ * @buffer: POW capture from cvmx_pow_capture()
+ * @buffer_size:
+ *               Size of the buffer
+ */
+extern void cvmx_pow_display(void *buffer, int buffer_size);
+
+/**
+ * Return the number of POW entries supported by this chip
+ *
+ * Returns Number of POW entries
+ */
+extern int cvmx_pow_get_num_entries(void);
+
+#endif /* __CVMX_POW_H__ */
diff --git a/drivers/staging/octeon/cvmx-scratch.h b/drivers/staging/octeon/cvmx-scratch.h
new file mode 100644
index 0000000..96b70cf
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-scratch.h
@@ -0,0 +1,139 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ *
+ * This file provides support for the processor local scratch memory.
+ * Scratch memory is byte addressable - all addresses are byte addresses.
+ *
+ */
+
+#ifndef __CVMX_SCRATCH_H__
+#define __CVMX_SCRATCH_H__
+
+/*
+ * Note: This define must be a long, not a long long in order to
+ * compile without warnings for both 32bit and 64bit.
+ */
+#define CVMX_SCRATCH_BASE       (-32768l)	/* 0xffffffffffff8000 */
+
+/**
+ * Reads an 8 bit value from the processor local scratchpad memory.
+ *
+ * @address: byte address to read from
+ *
+ * Returns value read
+ */
+static inline uint8_t cvmx_scratch_read8(uint64_t address)
+{
+	return *CASTPTR(volatile uint8_t, CVMX_SCRATCH_BASE + address);
+}
+
+/**
+ * Reads a 16 bit value from the processor local scratchpad memory.
+ *
+ * @address: byte address to read from
+ *
+ * Returns value read
+ */
+static inline uint16_t cvmx_scratch_read16(uint64_t address)
+{
+	return *CASTPTR(volatile uint16_t, CVMX_SCRATCH_BASE + address);
+}
+
+/**
+ * Reads a 32 bit value from the processor local scratchpad memory.
+ *
+ * @address: byte address to read from
+ *
+ * Returns value read
+ */
+static inline uint32_t cvmx_scratch_read32(uint64_t address)
+{
+	return *CASTPTR(volatile uint32_t, CVMX_SCRATCH_BASE + address);
+}
+
+/**
+ * Reads a 64 bit value from the processor local scratchpad memory.
+ *
+ * @address: byte address to read from
+ *
+ * Returns value read
+ */
+static inline uint64_t cvmx_scratch_read64(uint64_t address)
+{
+	return *CASTPTR(volatile uint64_t, CVMX_SCRATCH_BASE + address);
+}
+
+/**
+ * Writes an 8 bit value to the processor local scratchpad memory.
+ *
+ * @address: byte address to write to
+ * @value:   value to write
+ */
+static inline void cvmx_scratch_write8(uint64_t address, uint64_t value)
+{
+	*CASTPTR(volatile uint8_t, CVMX_SCRATCH_BASE + address) =
+	    (uint8_t) value;
+}
+
+/**
+ * Writes a 32 bit value to the processor local scratchpad memory.
+ *
+ * @address: byte address to write to
+ * @value:   value to write
+ */
+static inline void cvmx_scratch_write16(uint64_t address, uint64_t value)
+{
+	*CASTPTR(volatile uint16_t, CVMX_SCRATCH_BASE + address) =
+	    (uint16_t) value;
+}
+
+/**
+ * Writes a 16 bit value to the processor local scratchpad memory.
+ *
+ * @address: byte address to write to
+ * @value:   value to write
+ */
+static inline void cvmx_scratch_write32(uint64_t address, uint64_t value)
+{
+	*CASTPTR(volatile uint32_t, CVMX_SCRATCH_BASE + address) =
+	    (uint32_t) value;
+}
+
+/**
+ * Writes a 64 bit value to the processor local scratchpad memory.
+ *
+ * @address: byte address to write to
+ * @value:   value to write
+ */
+static inline void cvmx_scratch_write64(uint64_t address, uint64_t value)
+{
+	*CASTPTR(volatile uint64_t, CVMX_SCRATCH_BASE + address) = value;
+}
+
+#endif /* __CVMX_SCRATCH_H__ */
diff --git a/drivers/staging/octeon/cvmx-smix-defs.h b/drivers/staging/octeon/cvmx-smix-defs.h
new file mode 100644
index 0000000..9ae45fc
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-smix-defs.h
@@ -0,0 +1,178 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_SMIX_DEFS_H__
+#define __CVMX_SMIX_DEFS_H__
+
+#define CVMX_SMIX_CLK(offset) \
+	 CVMX_ADD_IO_SEG(0x0001180000001818ull + (((offset) & 1) * 256))
+#define CVMX_SMIX_CMD(offset) \
+	 CVMX_ADD_IO_SEG(0x0001180000001800ull + (((offset) & 1) * 256))
+#define CVMX_SMIX_EN(offset) \
+	 CVMX_ADD_IO_SEG(0x0001180000001820ull + (((offset) & 1) * 256))
+#define CVMX_SMIX_RD_DAT(offset) \
+	 CVMX_ADD_IO_SEG(0x0001180000001810ull + (((offset) & 1) * 256))
+#define CVMX_SMIX_WR_DAT(offset) \
+	 CVMX_ADD_IO_SEG(0x0001180000001808ull + (((offset) & 1) * 256))
+
+union cvmx_smix_clk {
+	uint64_t u64;
+	struct cvmx_smix_clk_s {
+		uint64_t reserved_25_63:39;
+		uint64_t mode:1;
+		uint64_t reserved_21_23:3;
+		uint64_t sample_hi:5;
+		uint64_t sample_mode:1;
+		uint64_t reserved_14_14:1;
+		uint64_t clk_idle:1;
+		uint64_t preamble:1;
+		uint64_t sample:4;
+		uint64_t phase:8;
+	} s;
+	struct cvmx_smix_clk_cn30xx {
+		uint64_t reserved_21_63:43;
+		uint64_t sample_hi:5;
+		uint64_t reserved_14_15:2;
+		uint64_t clk_idle:1;
+		uint64_t preamble:1;
+		uint64_t sample:4;
+		uint64_t phase:8;
+	} cn30xx;
+	struct cvmx_smix_clk_cn30xx cn31xx;
+	struct cvmx_smix_clk_cn30xx cn38xx;
+	struct cvmx_smix_clk_cn30xx cn38xxp2;
+	struct cvmx_smix_clk_cn50xx {
+		uint64_t reserved_25_63:39;
+		uint64_t mode:1;
+		uint64_t reserved_21_23:3;
+		uint64_t sample_hi:5;
+		uint64_t reserved_14_15:2;
+		uint64_t clk_idle:1;
+		uint64_t preamble:1;
+		uint64_t sample:4;
+		uint64_t phase:8;
+	} cn50xx;
+	struct cvmx_smix_clk_s cn52xx;
+	struct cvmx_smix_clk_cn50xx cn52xxp1;
+	struct cvmx_smix_clk_s cn56xx;
+	struct cvmx_smix_clk_cn50xx cn56xxp1;
+	struct cvmx_smix_clk_cn30xx cn58xx;
+	struct cvmx_smix_clk_cn30xx cn58xxp1;
+};
+
+union cvmx_smix_cmd {
+	uint64_t u64;
+	struct cvmx_smix_cmd_s {
+		uint64_t reserved_18_63:46;
+		uint64_t phy_op:2;
+		uint64_t reserved_13_15:3;
+		uint64_t phy_adr:5;
+		uint64_t reserved_5_7:3;
+		uint64_t reg_adr:5;
+	} s;
+	struct cvmx_smix_cmd_cn30xx {
+		uint64_t reserved_17_63:47;
+		uint64_t phy_op:1;
+		uint64_t reserved_13_15:3;
+		uint64_t phy_adr:5;
+		uint64_t reserved_5_7:3;
+		uint64_t reg_adr:5;
+	} cn30xx;
+	struct cvmx_smix_cmd_cn30xx cn31xx;
+	struct cvmx_smix_cmd_cn30xx cn38xx;
+	struct cvmx_smix_cmd_cn30xx cn38xxp2;
+	struct cvmx_smix_cmd_s cn50xx;
+	struct cvmx_smix_cmd_s cn52xx;
+	struct cvmx_smix_cmd_s cn52xxp1;
+	struct cvmx_smix_cmd_s cn56xx;
+	struct cvmx_smix_cmd_s cn56xxp1;
+	struct cvmx_smix_cmd_cn30xx cn58xx;
+	struct cvmx_smix_cmd_cn30xx cn58xxp1;
+};
+
+union cvmx_smix_en {
+	uint64_t u64;
+	struct cvmx_smix_en_s {
+		uint64_t reserved_1_63:63;
+		uint64_t en:1;
+	} s;
+	struct cvmx_smix_en_s cn30xx;
+	struct cvmx_smix_en_s cn31xx;
+	struct cvmx_smix_en_s cn38xx;
+	struct cvmx_smix_en_s cn38xxp2;
+	struct cvmx_smix_en_s cn50xx;
+	struct cvmx_smix_en_s cn52xx;
+	struct cvmx_smix_en_s cn52xxp1;
+	struct cvmx_smix_en_s cn56xx;
+	struct cvmx_smix_en_s cn56xxp1;
+	struct cvmx_smix_en_s cn58xx;
+	struct cvmx_smix_en_s cn58xxp1;
+};
+
+union cvmx_smix_rd_dat {
+	uint64_t u64;
+	struct cvmx_smix_rd_dat_s {
+		uint64_t reserved_18_63:46;
+		uint64_t pending:1;
+		uint64_t val:1;
+		uint64_t dat:16;
+	} s;
+	struct cvmx_smix_rd_dat_s cn30xx;
+	struct cvmx_smix_rd_dat_s cn31xx;
+	struct cvmx_smix_rd_dat_s cn38xx;
+	struct cvmx_smix_rd_dat_s cn38xxp2;
+	struct cvmx_smix_rd_dat_s cn50xx;
+	struct cvmx_smix_rd_dat_s cn52xx;
+	struct cvmx_smix_rd_dat_s cn52xxp1;
+	struct cvmx_smix_rd_dat_s cn56xx;
+	struct cvmx_smix_rd_dat_s cn56xxp1;
+	struct cvmx_smix_rd_dat_s cn58xx;
+	struct cvmx_smix_rd_dat_s cn58xxp1;
+};
+
+union cvmx_smix_wr_dat {
+	uint64_t u64;
+	struct cvmx_smix_wr_dat_s {
+		uint64_t reserved_18_63:46;
+		uint64_t pending:1;
+		uint64_t val:1;
+		uint64_t dat:16;
+	} s;
+	struct cvmx_smix_wr_dat_s cn30xx;
+	struct cvmx_smix_wr_dat_s cn31xx;
+	struct cvmx_smix_wr_dat_s cn38xx;
+	struct cvmx_smix_wr_dat_s cn38xxp2;
+	struct cvmx_smix_wr_dat_s cn50xx;
+	struct cvmx_smix_wr_dat_s cn52xx;
+	struct cvmx_smix_wr_dat_s cn52xxp1;
+	struct cvmx_smix_wr_dat_s cn56xx;
+	struct cvmx_smix_wr_dat_s cn56xxp1;
+	struct cvmx_smix_wr_dat_s cn58xx;
+	struct cvmx_smix_wr_dat_s cn58xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-spi.c b/drivers/staging/octeon/cvmx-spi.c
new file mode 100644
index 0000000..82794d9
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-spi.c
@@ -0,0 +1,667 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ *
+ * Support library for the SPI
+ */
+#include <asm/octeon/octeon.h>
+
+#include "cvmx-config.h"
+
+#include "cvmx-pko.h"
+#include "cvmx-spi.h"
+
+#include "cvmx-spxx-defs.h"
+#include "cvmx-stxx-defs.h"
+#include "cvmx-srxx-defs.h"
+
+#define INVOKE_CB(function_p, args...)		\
+	do {					\
+		if (function_p) {		\
+			res = function_p(args); \
+			if (res)		\
+				return res;	\
+		}				\
+	} while (0)
+
+#if CVMX_ENABLE_DEBUG_PRINTS
+static const char *modes[] =
+    { "UNKNOWN", "TX Halfplex", "Rx Halfplex", "Duplex" };
+#endif
+
+/* Default callbacks, can be overridden
+ *  using cvmx_spi_get_callbacks/cvmx_spi_set_callbacks
+ */
+static cvmx_spi_callbacks_t cvmx_spi_callbacks = {
+	.reset_cb = cvmx_spi_reset_cb,
+	.calendar_setup_cb = cvmx_spi_calendar_setup_cb,
+	.clock_detect_cb = cvmx_spi_clock_detect_cb,
+	.training_cb = cvmx_spi_training_cb,
+	.calendar_sync_cb = cvmx_spi_calendar_sync_cb,
+	.interface_up_cb = cvmx_spi_interface_up_cb
+};
+
+/**
+ * Get current SPI4 initialization callbacks
+ *
+ * @callbacks:  Pointer to the callbacks structure.to fill
+ *
+ * Returns Pointer to cvmx_spi_callbacks_t structure.
+ */
+void cvmx_spi_get_callbacks(cvmx_spi_callbacks_t *callbacks)
+{
+	memcpy(callbacks, &cvmx_spi_callbacks, sizeof(cvmx_spi_callbacks));
+}
+
+/**
+ * Set new SPI4 initialization callbacks
+ *
+ * @new_callbacks:  Pointer to an updated callbacks structure.
+ */
+void cvmx_spi_set_callbacks(cvmx_spi_callbacks_t *new_callbacks)
+{
+	memcpy(&cvmx_spi_callbacks, new_callbacks, sizeof(cvmx_spi_callbacks));
+}
+
+/**
+ * Initialize and start the SPI interface.
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @timeout:   Timeout to wait for clock synchronization in seconds
+ * @num_ports: Number of SPI ports to configure
+ *
+ * Returns Zero on success, negative of failure.
+ */
+int cvmx_spi_start_interface(int interface, cvmx_spi_mode_t mode, int timeout,
+			     int num_ports)
+{
+	int res = -1;
+
+	if (!(OCTEON_IS_MODEL(OCTEON_CN38XX) || OCTEON_IS_MODEL(OCTEON_CN58XX)))
+		return res;
+
+	/* Callback to perform SPI4 reset */
+	INVOKE_CB(cvmx_spi_callbacks.reset_cb, interface, mode);
+
+	/* Callback to perform calendar setup */
+	INVOKE_CB(cvmx_spi_callbacks.calendar_setup_cb, interface, mode,
+		  num_ports);
+
+	/* Callback to perform clock detection */
+	INVOKE_CB(cvmx_spi_callbacks.clock_detect_cb, interface, mode, timeout);
+
+	/* Callback to perform SPI4 link training */
+	INVOKE_CB(cvmx_spi_callbacks.training_cb, interface, mode, timeout);
+
+	/* Callback to perform calendar sync */
+	INVOKE_CB(cvmx_spi_callbacks.calendar_sync_cb, interface, mode,
+		  timeout);
+
+	/* Callback to handle interface coming up */
+	INVOKE_CB(cvmx_spi_callbacks.interface_up_cb, interface, mode);
+
+	return res;
+}
+
+/**
+ * This routine restarts the SPI interface after it has lost synchronization
+ * with its correspondent system.
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @timeout:   Timeout to wait for clock synchronization in seconds
+ *
+ * Returns Zero on success, negative of failure.
+ */
+int cvmx_spi_restart_interface(int interface, cvmx_spi_mode_t mode, int timeout)
+{
+	int res = -1;
+
+	if (!(OCTEON_IS_MODEL(OCTEON_CN38XX) || OCTEON_IS_MODEL(OCTEON_CN58XX)))
+		return res;
+
+	cvmx_dprintf("SPI%d: Restart %s\n", interface, modes[mode]);
+
+	/* Callback to perform SPI4 reset */
+	INVOKE_CB(cvmx_spi_callbacks.reset_cb, interface, mode);
+
+	/* NOTE: Calendar setup is not performed during restart */
+	/*       Refer to cvmx_spi_start_interface() for the full sequence */
+
+	/* Callback to perform clock detection */
+	INVOKE_CB(cvmx_spi_callbacks.clock_detect_cb, interface, mode, timeout);
+
+	/* Callback to perform SPI4 link training */
+	INVOKE_CB(cvmx_spi_callbacks.training_cb, interface, mode, timeout);
+
+	/* Callback to perform calendar sync */
+	INVOKE_CB(cvmx_spi_callbacks.calendar_sync_cb, interface, mode,
+		  timeout);
+
+	/* Callback to handle interface coming up */
+	INVOKE_CB(cvmx_spi_callbacks.interface_up_cb, interface, mode);
+
+	return res;
+}
+
+/**
+ * Callback to perform SPI4 reset
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+int cvmx_spi_reset_cb(int interface, cvmx_spi_mode_t mode)
+{
+	union cvmx_spxx_dbg_deskew_ctl spxx_dbg_deskew_ctl;
+	union cvmx_spxx_clk_ctl spxx_clk_ctl;
+	union cvmx_spxx_bist_stat spxx_bist_stat;
+	union cvmx_spxx_int_msk spxx_int_msk;
+	union cvmx_stxx_int_msk stxx_int_msk;
+	union cvmx_spxx_trn4_ctl spxx_trn4_ctl;
+	int index;
+	uint64_t MS = cvmx_sysinfo_get()->cpu_clock_hz / 1000;
+
+	/* Disable SPI error events while we run BIST */
+	spxx_int_msk.u64 = cvmx_read_csr(CVMX_SPXX_INT_MSK(interface));
+	cvmx_write_csr(CVMX_SPXX_INT_MSK(interface), 0);
+	stxx_int_msk.u64 = cvmx_read_csr(CVMX_STXX_INT_MSK(interface));
+	cvmx_write_csr(CVMX_STXX_INT_MSK(interface), 0);
+
+	/* Run BIST in the SPI interface */
+	cvmx_write_csr(CVMX_SRXX_COM_CTL(interface), 0);
+	cvmx_write_csr(CVMX_STXX_COM_CTL(interface), 0);
+	spxx_clk_ctl.u64 = 0;
+	spxx_clk_ctl.s.runbist = 1;
+	cvmx_write_csr(CVMX_SPXX_CLK_CTL(interface), spxx_clk_ctl.u64);
+	cvmx_wait(10 * MS);
+	spxx_bist_stat.u64 = cvmx_read_csr(CVMX_SPXX_BIST_STAT(interface));
+	if (spxx_bist_stat.s.stat0)
+		cvmx_dprintf
+		    ("ERROR SPI%d: BIST failed on receive datapath FIFO\n",
+		     interface);
+	if (spxx_bist_stat.s.stat1)
+		cvmx_dprintf("ERROR SPI%d: BIST failed on RX calendar table\n",
+			     interface);
+	if (spxx_bist_stat.s.stat2)
+		cvmx_dprintf("ERROR SPI%d: BIST failed on TX calendar table\n",
+			     interface);
+
+	/* Clear the calendar table after BIST to fix parity errors */
+	for (index = 0; index < 32; index++) {
+		union cvmx_srxx_spi4_calx srxx_spi4_calx;
+		union cvmx_stxx_spi4_calx stxx_spi4_calx;
+
+		srxx_spi4_calx.u64 = 0;
+		srxx_spi4_calx.s.oddpar = 1;
+		cvmx_write_csr(CVMX_SRXX_SPI4_CALX(index, interface),
+			       srxx_spi4_calx.u64);
+
+		stxx_spi4_calx.u64 = 0;
+		stxx_spi4_calx.s.oddpar = 1;
+		cvmx_write_csr(CVMX_STXX_SPI4_CALX(index, interface),
+			       stxx_spi4_calx.u64);
+	}
+
+	/* Re enable reporting of error interrupts */
+	cvmx_write_csr(CVMX_SPXX_INT_REG(interface),
+		       cvmx_read_csr(CVMX_SPXX_INT_REG(interface)));
+	cvmx_write_csr(CVMX_SPXX_INT_MSK(interface), spxx_int_msk.u64);
+	cvmx_write_csr(CVMX_STXX_INT_REG(interface),
+		       cvmx_read_csr(CVMX_STXX_INT_REG(interface)));
+	cvmx_write_csr(CVMX_STXX_INT_MSK(interface), stxx_int_msk.u64);
+
+	/* Setup the CLKDLY right in the middle */
+	spxx_clk_ctl.u64 = 0;
+	spxx_clk_ctl.s.seetrn = 0;
+	spxx_clk_ctl.s.clkdly = 0x10;
+	spxx_clk_ctl.s.runbist = 0;
+	spxx_clk_ctl.s.statdrv = 0;
+	/* This should always be on the opposite edge as statdrv */
+	spxx_clk_ctl.s.statrcv = 1;
+	spxx_clk_ctl.s.sndtrn = 0;
+	spxx_clk_ctl.s.drptrn = 0;
+	spxx_clk_ctl.s.rcvtrn = 0;
+	spxx_clk_ctl.s.srxdlck = 0;
+	cvmx_write_csr(CVMX_SPXX_CLK_CTL(interface), spxx_clk_ctl.u64);
+	cvmx_wait(100 * MS);
+
+	/* Reset SRX0 DLL */
+	spxx_clk_ctl.s.srxdlck = 1;
+	cvmx_write_csr(CVMX_SPXX_CLK_CTL(interface), spxx_clk_ctl.u64);
+
+	/* Waiting for Inf0 Spi4 RX DLL to lock */
+	cvmx_wait(100 * MS);
+
+	/* Enable dynamic alignment */
+	spxx_trn4_ctl.s.trntest = 0;
+	spxx_trn4_ctl.s.jitter = 1;
+	spxx_trn4_ctl.s.clr_boot = 1;
+	spxx_trn4_ctl.s.set_boot = 0;
+	if (OCTEON_IS_MODEL(OCTEON_CN58XX))
+		spxx_trn4_ctl.s.maxdist = 3;
+	else
+		spxx_trn4_ctl.s.maxdist = 8;
+	spxx_trn4_ctl.s.macro_en = 1;
+	spxx_trn4_ctl.s.mux_en = 1;
+	cvmx_write_csr(CVMX_SPXX_TRN4_CTL(interface), spxx_trn4_ctl.u64);
+
+	spxx_dbg_deskew_ctl.u64 = 0;
+	cvmx_write_csr(CVMX_SPXX_DBG_DESKEW_CTL(interface),
+		       spxx_dbg_deskew_ctl.u64);
+
+	return 0;
+}
+
+/**
+ * Callback to setup calendar and miscellaneous settings before clock detection
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @num_ports: Number of ports to configure on SPI
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+int cvmx_spi_calendar_setup_cb(int interface, cvmx_spi_mode_t mode,
+			       int num_ports)
+{
+	int port;
+	int index;
+	if (mode & CVMX_SPI_MODE_RX_HALFPLEX) {
+		union cvmx_srxx_com_ctl srxx_com_ctl;
+		union cvmx_srxx_spi4_stat srxx_spi4_stat;
+
+		/* SRX0 number of Ports */
+		srxx_com_ctl.u64 = 0;
+		srxx_com_ctl.s.prts = num_ports - 1;
+		srxx_com_ctl.s.st_en = 0;
+		srxx_com_ctl.s.inf_en = 0;
+		cvmx_write_csr(CVMX_SRXX_COM_CTL(interface), srxx_com_ctl.u64);
+
+		/* SRX0 Calendar Table. This round robbins through all ports */
+		port = 0;
+		index = 0;
+		while (port < num_ports) {
+			union cvmx_srxx_spi4_calx srxx_spi4_calx;
+			srxx_spi4_calx.u64 = 0;
+			srxx_spi4_calx.s.prt0 = port++;
+			srxx_spi4_calx.s.prt1 = port++;
+			srxx_spi4_calx.s.prt2 = port++;
+			srxx_spi4_calx.s.prt3 = port++;
+			srxx_spi4_calx.s.oddpar =
+			    ~(cvmx_dpop(srxx_spi4_calx.u64) & 1);
+			cvmx_write_csr(CVMX_SRXX_SPI4_CALX(index, interface),
+				       srxx_spi4_calx.u64);
+			index++;
+		}
+		srxx_spi4_stat.u64 = 0;
+		srxx_spi4_stat.s.len = num_ports;
+		srxx_spi4_stat.s.m = 1;
+		cvmx_write_csr(CVMX_SRXX_SPI4_STAT(interface),
+			       srxx_spi4_stat.u64);
+	}
+
+	if (mode & CVMX_SPI_MODE_TX_HALFPLEX) {
+		union cvmx_stxx_arb_ctl stxx_arb_ctl;
+		union cvmx_gmxx_tx_spi_max gmxx_tx_spi_max;
+		union cvmx_gmxx_tx_spi_thresh gmxx_tx_spi_thresh;
+		union cvmx_gmxx_tx_spi_ctl gmxx_tx_spi_ctl;
+		union cvmx_stxx_spi4_stat stxx_spi4_stat;
+		union cvmx_stxx_spi4_dat stxx_spi4_dat;
+
+		/* STX0 Config */
+		stxx_arb_ctl.u64 = 0;
+		stxx_arb_ctl.s.igntpa = 0;
+		stxx_arb_ctl.s.mintrn = 0;
+		cvmx_write_csr(CVMX_STXX_ARB_CTL(interface), stxx_arb_ctl.u64);
+
+		gmxx_tx_spi_max.u64 = 0;
+		gmxx_tx_spi_max.s.max1 = 8;
+		gmxx_tx_spi_max.s.max2 = 4;
+		gmxx_tx_spi_max.s.slice = 0;
+		cvmx_write_csr(CVMX_GMXX_TX_SPI_MAX(interface),
+			       gmxx_tx_spi_max.u64);
+
+		gmxx_tx_spi_thresh.u64 = 0;
+		gmxx_tx_spi_thresh.s.thresh = 4;
+		cvmx_write_csr(CVMX_GMXX_TX_SPI_THRESH(interface),
+			       gmxx_tx_spi_thresh.u64);
+
+		gmxx_tx_spi_ctl.u64 = 0;
+		gmxx_tx_spi_ctl.s.tpa_clr = 0;
+		gmxx_tx_spi_ctl.s.cont_pkt = 0;
+		cvmx_write_csr(CVMX_GMXX_TX_SPI_CTL(interface),
+			       gmxx_tx_spi_ctl.u64);
+
+		/* STX0 Training Control */
+		stxx_spi4_dat.u64 = 0;
+		/*Minimum needed by dynamic alignment */
+		stxx_spi4_dat.s.alpha = 32;
+		stxx_spi4_dat.s.max_t = 0xFFFF;	/*Minimum interval is 0x20 */
+		cvmx_write_csr(CVMX_STXX_SPI4_DAT(interface),
+			       stxx_spi4_dat.u64);
+
+		/* STX0 Calendar Table. This round robbins through all ports */
+		port = 0;
+		index = 0;
+		while (port < num_ports) {
+			union cvmx_stxx_spi4_calx stxx_spi4_calx;
+			stxx_spi4_calx.u64 = 0;
+			stxx_spi4_calx.s.prt0 = port++;
+			stxx_spi4_calx.s.prt1 = port++;
+			stxx_spi4_calx.s.prt2 = port++;
+			stxx_spi4_calx.s.prt3 = port++;
+			stxx_spi4_calx.s.oddpar =
+			    ~(cvmx_dpop(stxx_spi4_calx.u64) & 1);
+			cvmx_write_csr(CVMX_STXX_SPI4_CALX(index, interface),
+				       stxx_spi4_calx.u64);
+			index++;
+		}
+		stxx_spi4_stat.u64 = 0;
+		stxx_spi4_stat.s.len = num_ports;
+		stxx_spi4_stat.s.m = 1;
+		cvmx_write_csr(CVMX_STXX_SPI4_STAT(interface),
+			       stxx_spi4_stat.u64);
+	}
+
+	return 0;
+}
+
+/**
+ * Callback to perform clock detection
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @timeout:   Timeout to wait for clock synchronization in seconds
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+int cvmx_spi_clock_detect_cb(int interface, cvmx_spi_mode_t mode, int timeout)
+{
+	int clock_transitions;
+	union cvmx_spxx_clk_stat stat;
+	uint64_t timeout_time;
+	uint64_t MS = cvmx_sysinfo_get()->cpu_clock_hz / 1000;
+
+	/*
+	 * Regardless of operating mode, both Tx and Rx clocks must be
+	 * present for the SPI interface to operate.
+	 */
+	cvmx_dprintf("SPI%d: Waiting to see TsClk...\n", interface);
+	timeout_time = cvmx_get_cycle() + 1000ull * MS * timeout;
+	/*
+	 * Require 100 clock transitions in order to avoid any noise
+	 * in the beginning.
+	 */
+	clock_transitions = 100;
+	do {
+		stat.u64 = cvmx_read_csr(CVMX_SPXX_CLK_STAT(interface));
+		if (stat.s.s4clk0 && stat.s.s4clk1 && clock_transitions) {
+			/*
+			 * We've seen a clock transition, so decrement
+			 * the number we still need.
+			 */
+			clock_transitions--;
+			cvmx_write_csr(CVMX_SPXX_CLK_STAT(interface), stat.u64);
+			stat.s.s4clk0 = 0;
+			stat.s.s4clk1 = 0;
+		}
+		if (cvmx_get_cycle() > timeout_time) {
+			cvmx_dprintf("SPI%d: Timeout\n", interface);
+			return -1;
+		}
+	} while (stat.s.s4clk0 == 0 || stat.s.s4clk1 == 0);
+
+	cvmx_dprintf("SPI%d: Waiting to see RsClk...\n", interface);
+	timeout_time = cvmx_get_cycle() + 1000ull * MS * timeout;
+	/*
+	 * Require 100 clock transitions in order to avoid any noise in the
+	 * beginning.
+	 */
+	clock_transitions = 100;
+	do {
+		stat.u64 = cvmx_read_csr(CVMX_SPXX_CLK_STAT(interface));
+		if (stat.s.d4clk0 && stat.s.d4clk1 && clock_transitions) {
+			/*
+			 * We've seen a clock transition, so decrement
+			 * the number we still need
+			 */
+			clock_transitions--;
+			cvmx_write_csr(CVMX_SPXX_CLK_STAT(interface), stat.u64);
+			stat.s.d4clk0 = 0;
+			stat.s.d4clk1 = 0;
+		}
+		if (cvmx_get_cycle() > timeout_time) {
+			cvmx_dprintf("SPI%d: Timeout\n", interface);
+			return -1;
+		}
+	} while (stat.s.d4clk0 == 0 || stat.s.d4clk1 == 0);
+
+	return 0;
+}
+
+/**
+ * Callback to perform link training
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @timeout:   Timeout to wait for link to be trained (in seconds)
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+int cvmx_spi_training_cb(int interface, cvmx_spi_mode_t mode, int timeout)
+{
+	union cvmx_spxx_trn4_ctl spxx_trn4_ctl;
+	union cvmx_spxx_clk_stat stat;
+	uint64_t MS = cvmx_sysinfo_get()->cpu_clock_hz / 1000;
+	uint64_t timeout_time = cvmx_get_cycle() + 1000ull * MS * timeout;
+	int rx_training_needed;
+
+	/* SRX0 & STX0 Inf0 Links are configured - begin training */
+	union cvmx_spxx_clk_ctl spxx_clk_ctl;
+	spxx_clk_ctl.u64 = 0;
+	spxx_clk_ctl.s.seetrn = 0;
+	spxx_clk_ctl.s.clkdly = 0x10;
+	spxx_clk_ctl.s.runbist = 0;
+	spxx_clk_ctl.s.statdrv = 0;
+	/* This should always be on the opposite edge as statdrv */
+	spxx_clk_ctl.s.statrcv = 1;
+	spxx_clk_ctl.s.sndtrn = 1;
+	spxx_clk_ctl.s.drptrn = 1;
+	spxx_clk_ctl.s.rcvtrn = 1;
+	spxx_clk_ctl.s.srxdlck = 1;
+	cvmx_write_csr(CVMX_SPXX_CLK_CTL(interface), spxx_clk_ctl.u64);
+	cvmx_wait(1000 * MS);
+
+	/* SRX0 clear the boot bit */
+	spxx_trn4_ctl.u64 = cvmx_read_csr(CVMX_SPXX_TRN4_CTL(interface));
+	spxx_trn4_ctl.s.clr_boot = 1;
+	cvmx_write_csr(CVMX_SPXX_TRN4_CTL(interface), spxx_trn4_ctl.u64);
+
+	/* Wait for the training sequence to complete */
+	cvmx_dprintf("SPI%d: Waiting for training\n", interface);
+	cvmx_wait(1000 * MS);
+	/* Wait a really long time here */
+	timeout_time = cvmx_get_cycle() + 1000ull * MS * 600;
+	/*
+	 * The HRM says we must wait for 34 + 16 * MAXDIST training sequences.
+	 * We'll be pessimistic and wait for a lot more.
+	 */
+	rx_training_needed = 500;
+	do {
+		stat.u64 = cvmx_read_csr(CVMX_SPXX_CLK_STAT(interface));
+		if (stat.s.srxtrn && rx_training_needed) {
+			rx_training_needed--;
+			cvmx_write_csr(CVMX_SPXX_CLK_STAT(interface), stat.u64);
+			stat.s.srxtrn = 0;
+		}
+		if (cvmx_get_cycle() > timeout_time) {
+			cvmx_dprintf("SPI%d: Timeout\n", interface);
+			return -1;
+		}
+	} while (stat.s.srxtrn == 0);
+
+	return 0;
+}
+
+/**
+ * Callback to perform calendar data synchronization
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @timeout:   Timeout to wait for calendar data in seconds
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+int cvmx_spi_calendar_sync_cb(int interface, cvmx_spi_mode_t mode, int timeout)
+{
+	uint64_t MS = cvmx_sysinfo_get()->cpu_clock_hz / 1000;
+	if (mode & CVMX_SPI_MODE_RX_HALFPLEX) {
+		/* SRX0 interface should be good, send calendar data */
+		union cvmx_srxx_com_ctl srxx_com_ctl;
+		cvmx_dprintf
+		    ("SPI%d: Rx is synchronized, start sending calendar data\n",
+		     interface);
+		srxx_com_ctl.u64 = cvmx_read_csr(CVMX_SRXX_COM_CTL(interface));
+		srxx_com_ctl.s.inf_en = 1;
+		srxx_com_ctl.s.st_en = 1;
+		cvmx_write_csr(CVMX_SRXX_COM_CTL(interface), srxx_com_ctl.u64);
+	}
+
+	if (mode & CVMX_SPI_MODE_TX_HALFPLEX) {
+		/* STX0 has achieved sync */
+		/* The corespondant board should be sending calendar data */
+		/* Enable the STX0 STAT receiver. */
+		union cvmx_spxx_clk_stat stat;
+		uint64_t timeout_time;
+		union cvmx_stxx_com_ctl stxx_com_ctl;
+		stxx_com_ctl.u64 = 0;
+		stxx_com_ctl.s.st_en = 1;
+		cvmx_write_csr(CVMX_STXX_COM_CTL(interface), stxx_com_ctl.u64);
+
+		/* Waiting for calendar sync on STX0 STAT */
+		cvmx_dprintf("SPI%d: Waiting to sync on STX[%d] STAT\n",
+			     interface, interface);
+		timeout_time = cvmx_get_cycle() + 1000ull * MS * timeout;
+		/* SPX0_CLK_STAT - SPX0_CLK_STAT[STXCAL] should be 1 (bit10) */
+		do {
+			stat.u64 = cvmx_read_csr(CVMX_SPXX_CLK_STAT(interface));
+			if (cvmx_get_cycle() > timeout_time) {
+				cvmx_dprintf("SPI%d: Timeout\n", interface);
+				return -1;
+			}
+		} while (stat.s.stxcal == 0);
+	}
+
+	return 0;
+}
+
+/**
+ * Callback to handle interface up
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+int cvmx_spi_interface_up_cb(int interface, cvmx_spi_mode_t mode)
+{
+	union cvmx_gmxx_rxx_frm_min gmxx_rxx_frm_min;
+	union cvmx_gmxx_rxx_frm_max gmxx_rxx_frm_max;
+	union cvmx_gmxx_rxx_jabber gmxx_rxx_jabber;
+
+	if (mode & CVMX_SPI_MODE_RX_HALFPLEX) {
+		union cvmx_srxx_com_ctl srxx_com_ctl;
+		srxx_com_ctl.u64 = cvmx_read_csr(CVMX_SRXX_COM_CTL(interface));
+		srxx_com_ctl.s.inf_en = 1;
+		cvmx_write_csr(CVMX_SRXX_COM_CTL(interface), srxx_com_ctl.u64);
+		cvmx_dprintf("SPI%d: Rx is now up\n", interface);
+	}
+
+	if (mode & CVMX_SPI_MODE_TX_HALFPLEX) {
+		union cvmx_stxx_com_ctl stxx_com_ctl;
+		stxx_com_ctl.u64 = cvmx_read_csr(CVMX_STXX_COM_CTL(interface));
+		stxx_com_ctl.s.inf_en = 1;
+		cvmx_write_csr(CVMX_STXX_COM_CTL(interface), stxx_com_ctl.u64);
+		cvmx_dprintf("SPI%d: Tx is now up\n", interface);
+	}
+
+	gmxx_rxx_frm_min.u64 = 0;
+	gmxx_rxx_frm_min.s.len = 64;
+	cvmx_write_csr(CVMX_GMXX_RXX_FRM_MIN(0, interface),
+		       gmxx_rxx_frm_min.u64);
+	gmxx_rxx_frm_max.u64 = 0;
+	gmxx_rxx_frm_max.s.len = 64 * 1024 - 4;
+	cvmx_write_csr(CVMX_GMXX_RXX_FRM_MAX(0, interface),
+		       gmxx_rxx_frm_max.u64);
+	gmxx_rxx_jabber.u64 = 0;
+	gmxx_rxx_jabber.s.cnt = 64 * 1024 - 4;
+	cvmx_write_csr(CVMX_GMXX_RXX_JABBER(0, interface), gmxx_rxx_jabber.u64);
+
+	return 0;
+}
diff --git a/drivers/staging/octeon/cvmx-spi.h b/drivers/staging/octeon/cvmx-spi.h
new file mode 100644
index 0000000..e814648
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-spi.h
@@ -0,0 +1,269 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/*
+ *
+ * This file contains defines for the SPI interface
+ */
+#ifndef __CVMX_SPI_H__
+#define __CVMX_SPI_H__
+
+#include "cvmx-gmxx-defs.h"
+
+/* CSR typedefs have been moved to cvmx-csr-*.h */
+
+typedef enum {
+	CVMX_SPI_MODE_UNKNOWN = 0,
+	CVMX_SPI_MODE_TX_HALFPLEX = 1,
+	CVMX_SPI_MODE_RX_HALFPLEX = 2,
+	CVMX_SPI_MODE_DUPLEX = 3
+} cvmx_spi_mode_t;
+
+/** Callbacks structure to customize SPI4 initialization sequence */
+typedef struct {
+    /** Called to reset SPI4 DLL */
+	int (*reset_cb) (int interface, cvmx_spi_mode_t mode);
+
+    /** Called to setup calendar */
+	int (*calendar_setup_cb) (int interface, cvmx_spi_mode_t mode,
+				  int num_ports);
+
+    /** Called for Tx and Rx clock detection */
+	int (*clock_detect_cb) (int interface, cvmx_spi_mode_t mode,
+				int timeout);
+
+    /** Called to perform link training */
+	int (*training_cb) (int interface, cvmx_spi_mode_t mode, int timeout);
+
+    /** Called for calendar data synchronization */
+	int (*calendar_sync_cb) (int interface, cvmx_spi_mode_t mode,
+				 int timeout);
+
+    /** Called when interface is up */
+	int (*interface_up_cb) (int interface, cvmx_spi_mode_t mode);
+
+} cvmx_spi_callbacks_t;
+
+/**
+ * Return true if the supplied interface is configured for SPI
+ *
+ * @interface: Interface to check
+ * Returns True if interface is SPI
+ */
+static inline int cvmx_spi_is_spi_interface(int interface)
+{
+	uint64_t gmxState = cvmx_read_csr(CVMX_GMXX_INF_MODE(interface));
+	return (gmxState & 0x2) && (gmxState & 0x1);
+}
+
+/**
+ * Initialize and start the SPI interface.
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @timeout:   Timeout to wait for clock synchronization in seconds
+ * @num_ports: Number of SPI ports to configure
+ *
+ * Returns Zero on success, negative of failure.
+ */
+extern int cvmx_spi_start_interface(int interface, cvmx_spi_mode_t mode,
+				    int timeout, int num_ports);
+
+/**
+ * This routine restarts the SPI interface after it has lost synchronization
+ * with its corespondant system.
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @timeout:   Timeout to wait for clock synchronization in seconds
+ * Returns Zero on success, negative of failure.
+ */
+extern int cvmx_spi_restart_interface(int interface, cvmx_spi_mode_t mode,
+				      int timeout);
+
+/**
+ * Return non-zero if the SPI interface has a SPI4000 attached
+ *
+ * @interface: SPI interface the SPI4000 is connected to
+ *
+ * Returns
+ */
+static inline int cvmx_spi4000_is_present(int interface)
+{
+	return 0;
+}
+
+/**
+ * Initialize the SPI4000 for use
+ *
+ * @interface: SPI interface the SPI4000 is connected to
+ */
+static inline int cvmx_spi4000_initialize(int interface)
+{
+	return 0;
+}
+
+/**
+ * Poll all the SPI4000 port and check its speed
+ *
+ * @interface: Interface the SPI4000 is on
+ * @port:      Port to poll (0-9)
+ * Returns Status of the port. 0=down. All other values the port is up.
+ */
+static inline union cvmx_gmxx_rxx_rx_inbnd cvmx_spi4000_check_speed(
+	int interface,
+	int port)
+{
+	union cvmx_gmxx_rxx_rx_inbnd r;
+	r.u64 = 0;
+	return r;
+}
+
+/**
+ * Get current SPI4 initialization callbacks
+ *
+ * @callbacks:  Pointer to the callbacks structure.to fill
+ *
+ * Returns Pointer to cvmx_spi_callbacks_t structure.
+ */
+extern void cvmx_spi_get_callbacks(cvmx_spi_callbacks_t *callbacks);
+
+/**
+ * Set new SPI4 initialization callbacks
+ *
+ * @new_callbacks:  Pointer to an updated callbacks structure.
+ */
+extern void cvmx_spi_set_callbacks(cvmx_spi_callbacks_t *new_callbacks);
+
+/**
+ * Callback to perform SPI4 reset
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+extern int cvmx_spi_reset_cb(int interface, cvmx_spi_mode_t mode);
+
+/**
+ * Callback to setup calendar and miscellaneous settings before clock
+ * detection
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @num_ports: Number of ports to configure on SPI
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+extern int cvmx_spi_calendar_setup_cb(int interface, cvmx_spi_mode_t mode,
+				      int num_ports);
+
+/**
+ * Callback to perform clock detection
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @timeout:   Timeout to wait for clock synchronization in seconds
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+extern int cvmx_spi_clock_detect_cb(int interface, cvmx_spi_mode_t mode,
+				    int timeout);
+
+/**
+ * Callback to perform link training
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @timeout:   Timeout to wait for link to be trained (in seconds)
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+extern int cvmx_spi_training_cb(int interface, cvmx_spi_mode_t mode,
+				int timeout);
+
+/**
+ * Callback to perform calendar data synchronization
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ * @timeout:   Timeout to wait for calendar data in seconds
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+extern int cvmx_spi_calendar_sync_cb(int interface, cvmx_spi_mode_t mode,
+				     int timeout);
+
+/**
+ * Callback to handle interface up
+ *
+ * @interface: The identifier of the packet interface to configure and
+ *                  use as a SPI interface.
+ * @mode:      The operating mode for the SPI interface. The interface
+ *                  can operate as a full duplex (both Tx and Rx data paths
+ *                  active) or as a halfplex (either the Tx data path is
+ *                  active or the Rx data path is active, but not both).
+ *
+ * Returns Zero on success, non-zero error code on failure (will cause
+ * SPI initialization to abort)
+ */
+extern int cvmx_spi_interface_up_cb(int interface, cvmx_spi_mode_t mode);
+
+#endif /* __CVMX_SPI_H__ */
diff --git a/drivers/staging/octeon/cvmx-spxx-defs.h b/drivers/staging/octeon/cvmx-spxx-defs.h
new file mode 100644
index 0000000..b16940e
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-spxx-defs.h
@@ -0,0 +1,347 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_SPXX_DEFS_H__
+#define __CVMX_SPXX_DEFS_H__
+
+#define CVMX_SPXX_BCKPRS_CNT(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000340ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_BIST_STAT(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800900007F8ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_CLK_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000348ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_CLK_STAT(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000350ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_DBG_DESKEW_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000368ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_DBG_DESKEW_STATE(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000370ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_DRV_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000358ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_ERR_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000320ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_INT_DAT(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000318ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_INT_MSK(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000308ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_INT_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000300ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_INT_SYNC(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000310ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_TPA_ACC(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000338ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_TPA_MAX(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000330ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_TPA_SEL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000328ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SPXX_TRN4_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000360ull + (((block_id) & 1) * 0x8000000ull))
+
+union cvmx_spxx_bckprs_cnt {
+	uint64_t u64;
+	struct cvmx_spxx_bckprs_cnt_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_spxx_bckprs_cnt_s cn38xx;
+	struct cvmx_spxx_bckprs_cnt_s cn38xxp2;
+	struct cvmx_spxx_bckprs_cnt_s cn58xx;
+	struct cvmx_spxx_bckprs_cnt_s cn58xxp1;
+};
+
+union cvmx_spxx_bist_stat {
+	uint64_t u64;
+	struct cvmx_spxx_bist_stat_s {
+		uint64_t reserved_3_63:61;
+		uint64_t stat2:1;
+		uint64_t stat1:1;
+		uint64_t stat0:1;
+	} s;
+	struct cvmx_spxx_bist_stat_s cn38xx;
+	struct cvmx_spxx_bist_stat_s cn38xxp2;
+	struct cvmx_spxx_bist_stat_s cn58xx;
+	struct cvmx_spxx_bist_stat_s cn58xxp1;
+};
+
+union cvmx_spxx_clk_ctl {
+	uint64_t u64;
+	struct cvmx_spxx_clk_ctl_s {
+		uint64_t reserved_17_63:47;
+		uint64_t seetrn:1;
+		uint64_t reserved_12_15:4;
+		uint64_t clkdly:5;
+		uint64_t runbist:1;
+		uint64_t statdrv:1;
+		uint64_t statrcv:1;
+		uint64_t sndtrn:1;
+		uint64_t drptrn:1;
+		uint64_t rcvtrn:1;
+		uint64_t srxdlck:1;
+	} s;
+	struct cvmx_spxx_clk_ctl_s cn38xx;
+	struct cvmx_spxx_clk_ctl_s cn38xxp2;
+	struct cvmx_spxx_clk_ctl_s cn58xx;
+	struct cvmx_spxx_clk_ctl_s cn58xxp1;
+};
+
+union cvmx_spxx_clk_stat {
+	uint64_t u64;
+	struct cvmx_spxx_clk_stat_s {
+		uint64_t reserved_11_63:53;
+		uint64_t stxcal:1;
+		uint64_t reserved_9_9:1;
+		uint64_t srxtrn:1;
+		uint64_t s4clk1:1;
+		uint64_t s4clk0:1;
+		uint64_t d4clk1:1;
+		uint64_t d4clk0:1;
+		uint64_t reserved_0_3:4;
+	} s;
+	struct cvmx_spxx_clk_stat_s cn38xx;
+	struct cvmx_spxx_clk_stat_s cn38xxp2;
+	struct cvmx_spxx_clk_stat_s cn58xx;
+	struct cvmx_spxx_clk_stat_s cn58xxp1;
+};
+
+union cvmx_spxx_dbg_deskew_ctl {
+	uint64_t u64;
+	struct cvmx_spxx_dbg_deskew_ctl_s {
+		uint64_t reserved_30_63:34;
+		uint64_t fallnop:1;
+		uint64_t fall8:1;
+		uint64_t reserved_26_27:2;
+		uint64_t sstep_go:1;
+		uint64_t sstep:1;
+		uint64_t reserved_22_23:2;
+		uint64_t clrdly:1;
+		uint64_t dec:1;
+		uint64_t inc:1;
+		uint64_t mux:1;
+		uint64_t offset:5;
+		uint64_t bitsel:5;
+		uint64_t offdly:6;
+		uint64_t dllfrc:1;
+		uint64_t dlldis:1;
+	} s;
+	struct cvmx_spxx_dbg_deskew_ctl_s cn38xx;
+	struct cvmx_spxx_dbg_deskew_ctl_s cn38xxp2;
+	struct cvmx_spxx_dbg_deskew_ctl_s cn58xx;
+	struct cvmx_spxx_dbg_deskew_ctl_s cn58xxp1;
+};
+
+union cvmx_spxx_dbg_deskew_state {
+	uint64_t u64;
+	struct cvmx_spxx_dbg_deskew_state_s {
+		uint64_t reserved_9_63:55;
+		uint64_t testres:1;
+		uint64_t unxterm:1;
+		uint64_t muxsel:2;
+		uint64_t offset:5;
+	} s;
+	struct cvmx_spxx_dbg_deskew_state_s cn38xx;
+	struct cvmx_spxx_dbg_deskew_state_s cn38xxp2;
+	struct cvmx_spxx_dbg_deskew_state_s cn58xx;
+	struct cvmx_spxx_dbg_deskew_state_s cn58xxp1;
+};
+
+union cvmx_spxx_drv_ctl {
+	uint64_t u64;
+	struct cvmx_spxx_drv_ctl_s {
+		uint64_t reserved_0_63:64;
+	} s;
+	struct cvmx_spxx_drv_ctl_cn38xx {
+		uint64_t reserved_16_63:48;
+		uint64_t stx4ncmp:4;
+		uint64_t stx4pcmp:4;
+		uint64_t srx4cmp:8;
+	} cn38xx;
+	struct cvmx_spxx_drv_ctl_cn38xx cn38xxp2;
+	struct cvmx_spxx_drv_ctl_cn58xx {
+		uint64_t reserved_24_63:40;
+		uint64_t stx4ncmp:4;
+		uint64_t stx4pcmp:4;
+		uint64_t reserved_10_15:6;
+		uint64_t srx4cmp:10;
+	} cn58xx;
+	struct cvmx_spxx_drv_ctl_cn58xx cn58xxp1;
+};
+
+union cvmx_spxx_err_ctl {
+	uint64_t u64;
+	struct cvmx_spxx_err_ctl_s {
+		uint64_t reserved_9_63:55;
+		uint64_t prtnxa:1;
+		uint64_t dipcls:1;
+		uint64_t dippay:1;
+		uint64_t reserved_4_5:2;
+		uint64_t errcnt:4;
+	} s;
+	struct cvmx_spxx_err_ctl_s cn38xx;
+	struct cvmx_spxx_err_ctl_s cn38xxp2;
+	struct cvmx_spxx_err_ctl_s cn58xx;
+	struct cvmx_spxx_err_ctl_s cn58xxp1;
+};
+
+union cvmx_spxx_int_dat {
+	uint64_t u64;
+	struct cvmx_spxx_int_dat_s {
+		uint64_t reserved_32_63:32;
+		uint64_t mul:1;
+		uint64_t reserved_14_30:17;
+		uint64_t calbnk:2;
+		uint64_t rsvop:4;
+		uint64_t prt:8;
+	} s;
+	struct cvmx_spxx_int_dat_s cn38xx;
+	struct cvmx_spxx_int_dat_s cn38xxp2;
+	struct cvmx_spxx_int_dat_s cn58xx;
+	struct cvmx_spxx_int_dat_s cn58xxp1;
+};
+
+union cvmx_spxx_int_msk {
+	uint64_t u64;
+	struct cvmx_spxx_int_msk_s {
+		uint64_t reserved_12_63:52;
+		uint64_t calerr:1;
+		uint64_t syncerr:1;
+		uint64_t diperr:1;
+		uint64_t tpaovr:1;
+		uint64_t rsverr:1;
+		uint64_t drwnng:1;
+		uint64_t clserr:1;
+		uint64_t spiovr:1;
+		uint64_t reserved_2_3:2;
+		uint64_t abnorm:1;
+		uint64_t prtnxa:1;
+	} s;
+	struct cvmx_spxx_int_msk_s cn38xx;
+	struct cvmx_spxx_int_msk_s cn38xxp2;
+	struct cvmx_spxx_int_msk_s cn58xx;
+	struct cvmx_spxx_int_msk_s cn58xxp1;
+};
+
+union cvmx_spxx_int_reg {
+	uint64_t u64;
+	struct cvmx_spxx_int_reg_s {
+		uint64_t reserved_32_63:32;
+		uint64_t spf:1;
+		uint64_t reserved_12_30:19;
+		uint64_t calerr:1;
+		uint64_t syncerr:1;
+		uint64_t diperr:1;
+		uint64_t tpaovr:1;
+		uint64_t rsverr:1;
+		uint64_t drwnng:1;
+		uint64_t clserr:1;
+		uint64_t spiovr:1;
+		uint64_t reserved_2_3:2;
+		uint64_t abnorm:1;
+		uint64_t prtnxa:1;
+	} s;
+	struct cvmx_spxx_int_reg_s cn38xx;
+	struct cvmx_spxx_int_reg_s cn38xxp2;
+	struct cvmx_spxx_int_reg_s cn58xx;
+	struct cvmx_spxx_int_reg_s cn58xxp1;
+};
+
+union cvmx_spxx_int_sync {
+	uint64_t u64;
+	struct cvmx_spxx_int_sync_s {
+		uint64_t reserved_12_63:52;
+		uint64_t calerr:1;
+		uint64_t syncerr:1;
+		uint64_t diperr:1;
+		uint64_t tpaovr:1;
+		uint64_t rsverr:1;
+		uint64_t drwnng:1;
+		uint64_t clserr:1;
+		uint64_t spiovr:1;
+		uint64_t reserved_2_3:2;
+		uint64_t abnorm:1;
+		uint64_t prtnxa:1;
+	} s;
+	struct cvmx_spxx_int_sync_s cn38xx;
+	struct cvmx_spxx_int_sync_s cn38xxp2;
+	struct cvmx_spxx_int_sync_s cn58xx;
+	struct cvmx_spxx_int_sync_s cn58xxp1;
+};
+
+union cvmx_spxx_tpa_acc {
+	uint64_t u64;
+	struct cvmx_spxx_tpa_acc_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_spxx_tpa_acc_s cn38xx;
+	struct cvmx_spxx_tpa_acc_s cn38xxp2;
+	struct cvmx_spxx_tpa_acc_s cn58xx;
+	struct cvmx_spxx_tpa_acc_s cn58xxp1;
+};
+
+union cvmx_spxx_tpa_max {
+	uint64_t u64;
+	struct cvmx_spxx_tpa_max_s {
+		uint64_t reserved_32_63:32;
+		uint64_t max:32;
+	} s;
+	struct cvmx_spxx_tpa_max_s cn38xx;
+	struct cvmx_spxx_tpa_max_s cn38xxp2;
+	struct cvmx_spxx_tpa_max_s cn58xx;
+	struct cvmx_spxx_tpa_max_s cn58xxp1;
+};
+
+union cvmx_spxx_tpa_sel {
+	uint64_t u64;
+	struct cvmx_spxx_tpa_sel_s {
+		uint64_t reserved_4_63:60;
+		uint64_t prtsel:4;
+	} s;
+	struct cvmx_spxx_tpa_sel_s cn38xx;
+	struct cvmx_spxx_tpa_sel_s cn38xxp2;
+	struct cvmx_spxx_tpa_sel_s cn58xx;
+	struct cvmx_spxx_tpa_sel_s cn58xxp1;
+};
+
+union cvmx_spxx_trn4_ctl {
+	uint64_t u64;
+	struct cvmx_spxx_trn4_ctl_s {
+		uint64_t reserved_13_63:51;
+		uint64_t trntest:1;
+		uint64_t jitter:3;
+		uint64_t clr_boot:1;
+		uint64_t set_boot:1;
+		uint64_t maxdist:5;
+		uint64_t macro_en:1;
+		uint64_t mux_en:1;
+	} s;
+	struct cvmx_spxx_trn4_ctl_s cn38xx;
+	struct cvmx_spxx_trn4_ctl_s cn38xxp2;
+	struct cvmx_spxx_trn4_ctl_s cn58xx;
+	struct cvmx_spxx_trn4_ctl_s cn58xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-srxx-defs.h b/drivers/staging/octeon/cvmx-srxx-defs.h
new file mode 100644
index 0000000..d82b366
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-srxx-defs.h
@@ -0,0 +1,126 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_SRXX_DEFS_H__
+#define __CVMX_SRXX_DEFS_H__
+
+#define CVMX_SRXX_COM_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000200ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SRXX_IGN_RX_FULL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000218ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SRXX_SPI4_CALX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000000ull + (((offset) & 31) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SRXX_SPI4_STAT(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000208ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SRXX_SW_TICK_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000220ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_SRXX_SW_TICK_DAT(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000228ull + (((block_id) & 1) * 0x8000000ull))
+
+union cvmx_srxx_com_ctl {
+	uint64_t u64;
+	struct cvmx_srxx_com_ctl_s {
+		uint64_t reserved_8_63:56;
+		uint64_t prts:4;
+		uint64_t st_en:1;
+		uint64_t reserved_1_2:2;
+		uint64_t inf_en:1;
+	} s;
+	struct cvmx_srxx_com_ctl_s cn38xx;
+	struct cvmx_srxx_com_ctl_s cn38xxp2;
+	struct cvmx_srxx_com_ctl_s cn58xx;
+	struct cvmx_srxx_com_ctl_s cn58xxp1;
+};
+
+union cvmx_srxx_ign_rx_full {
+	uint64_t u64;
+	struct cvmx_srxx_ign_rx_full_s {
+		uint64_t reserved_16_63:48;
+		uint64_t ignore:16;
+	} s;
+	struct cvmx_srxx_ign_rx_full_s cn38xx;
+	struct cvmx_srxx_ign_rx_full_s cn38xxp2;
+	struct cvmx_srxx_ign_rx_full_s cn58xx;
+	struct cvmx_srxx_ign_rx_full_s cn58xxp1;
+};
+
+union cvmx_srxx_spi4_calx {
+	uint64_t u64;
+	struct cvmx_srxx_spi4_calx_s {
+		uint64_t reserved_17_63:47;
+		uint64_t oddpar:1;
+		uint64_t prt3:4;
+		uint64_t prt2:4;
+		uint64_t prt1:4;
+		uint64_t prt0:4;
+	} s;
+	struct cvmx_srxx_spi4_calx_s cn38xx;
+	struct cvmx_srxx_spi4_calx_s cn38xxp2;
+	struct cvmx_srxx_spi4_calx_s cn58xx;
+	struct cvmx_srxx_spi4_calx_s cn58xxp1;
+};
+
+union cvmx_srxx_spi4_stat {
+	uint64_t u64;
+	struct cvmx_srxx_spi4_stat_s {
+		uint64_t reserved_16_63:48;
+		uint64_t m:8;
+		uint64_t reserved_7_7:1;
+		uint64_t len:7;
+	} s;
+	struct cvmx_srxx_spi4_stat_s cn38xx;
+	struct cvmx_srxx_spi4_stat_s cn38xxp2;
+	struct cvmx_srxx_spi4_stat_s cn58xx;
+	struct cvmx_srxx_spi4_stat_s cn58xxp1;
+};
+
+union cvmx_srxx_sw_tick_ctl {
+	uint64_t u64;
+	struct cvmx_srxx_sw_tick_ctl_s {
+		uint64_t reserved_14_63:50;
+		uint64_t eop:1;
+		uint64_t sop:1;
+		uint64_t mod:4;
+		uint64_t opc:4;
+		uint64_t adr:4;
+	} s;
+	struct cvmx_srxx_sw_tick_ctl_s cn38xx;
+	struct cvmx_srxx_sw_tick_ctl_s cn58xx;
+	struct cvmx_srxx_sw_tick_ctl_s cn58xxp1;
+};
+
+union cvmx_srxx_sw_tick_dat {
+	uint64_t u64;
+	struct cvmx_srxx_sw_tick_dat_s {
+		uint64_t dat:64;
+	} s;
+	struct cvmx_srxx_sw_tick_dat_s cn38xx;
+	struct cvmx_srxx_sw_tick_dat_s cn58xx;
+	struct cvmx_srxx_sw_tick_dat_s cn58xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-stxx-defs.h b/drivers/staging/octeon/cvmx-stxx-defs.h
new file mode 100644
index 0000000..4f209b6
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-stxx-defs.h
@@ -0,0 +1,292 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+#ifndef __CVMX_STXX_DEFS_H__
+#define __CVMX_STXX_DEFS_H__
+
+#define CVMX_STXX_ARB_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000608ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_BCKPRS_CNT(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000688ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_COM_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000600ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_DIP_CNT(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000690ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_IGN_CAL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000610ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_INT_MSK(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800900006A0ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_INT_REG(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000698ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_INT_SYNC(block_id) \
+	 CVMX_ADD_IO_SEG(0x00011800900006A8ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_MIN_BST(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000618ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_SPI4_CALX(offset, block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000400ull + (((offset) & 31) * 8) + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_SPI4_DAT(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000628ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_SPI4_STAT(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000630ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_STAT_BYTES_HI(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000648ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_STAT_BYTES_LO(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000680ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_STAT_CTL(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000638ull + (((block_id) & 1) * 0x8000000ull))
+#define CVMX_STXX_STAT_PKT_XMT(block_id) \
+	 CVMX_ADD_IO_SEG(0x0001180090000640ull + (((block_id) & 1) * 0x8000000ull))
+
+union cvmx_stxx_arb_ctl {
+	uint64_t u64;
+	struct cvmx_stxx_arb_ctl_s {
+		uint64_t reserved_6_63:58;
+		uint64_t mintrn:1;
+		uint64_t reserved_4_4:1;
+		uint64_t igntpa:1;
+		uint64_t reserved_0_2:3;
+	} s;
+	struct cvmx_stxx_arb_ctl_s cn38xx;
+	struct cvmx_stxx_arb_ctl_s cn38xxp2;
+	struct cvmx_stxx_arb_ctl_s cn58xx;
+	struct cvmx_stxx_arb_ctl_s cn58xxp1;
+};
+
+union cvmx_stxx_bckprs_cnt {
+	uint64_t u64;
+	struct cvmx_stxx_bckprs_cnt_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_stxx_bckprs_cnt_s cn38xx;
+	struct cvmx_stxx_bckprs_cnt_s cn38xxp2;
+	struct cvmx_stxx_bckprs_cnt_s cn58xx;
+	struct cvmx_stxx_bckprs_cnt_s cn58xxp1;
+};
+
+union cvmx_stxx_com_ctl {
+	uint64_t u64;
+	struct cvmx_stxx_com_ctl_s {
+		uint64_t reserved_4_63:60;
+		uint64_t st_en:1;
+		uint64_t reserved_1_2:2;
+		uint64_t inf_en:1;
+	} s;
+	struct cvmx_stxx_com_ctl_s cn38xx;
+	struct cvmx_stxx_com_ctl_s cn38xxp2;
+	struct cvmx_stxx_com_ctl_s cn58xx;
+	struct cvmx_stxx_com_ctl_s cn58xxp1;
+};
+
+union cvmx_stxx_dip_cnt {
+	uint64_t u64;
+	struct cvmx_stxx_dip_cnt_s {
+		uint64_t reserved_8_63:56;
+		uint64_t frmmax:4;
+		uint64_t dipmax:4;
+	} s;
+	struct cvmx_stxx_dip_cnt_s cn38xx;
+	struct cvmx_stxx_dip_cnt_s cn38xxp2;
+	struct cvmx_stxx_dip_cnt_s cn58xx;
+	struct cvmx_stxx_dip_cnt_s cn58xxp1;
+};
+
+union cvmx_stxx_ign_cal {
+	uint64_t u64;
+	struct cvmx_stxx_ign_cal_s {
+		uint64_t reserved_16_63:48;
+		uint64_t igntpa:16;
+	} s;
+	struct cvmx_stxx_ign_cal_s cn38xx;
+	struct cvmx_stxx_ign_cal_s cn38xxp2;
+	struct cvmx_stxx_ign_cal_s cn58xx;
+	struct cvmx_stxx_ign_cal_s cn58xxp1;
+};
+
+union cvmx_stxx_int_msk {
+	uint64_t u64;
+	struct cvmx_stxx_int_msk_s {
+		uint64_t reserved_8_63:56;
+		uint64_t frmerr:1;
+		uint64_t unxfrm:1;
+		uint64_t nosync:1;
+		uint64_t diperr:1;
+		uint64_t datovr:1;
+		uint64_t ovrbst:1;
+		uint64_t calpar1:1;
+		uint64_t calpar0:1;
+	} s;
+	struct cvmx_stxx_int_msk_s cn38xx;
+	struct cvmx_stxx_int_msk_s cn38xxp2;
+	struct cvmx_stxx_int_msk_s cn58xx;
+	struct cvmx_stxx_int_msk_s cn58xxp1;
+};
+
+union cvmx_stxx_int_reg {
+	uint64_t u64;
+	struct cvmx_stxx_int_reg_s {
+		uint64_t reserved_9_63:55;
+		uint64_t syncerr:1;
+		uint64_t frmerr:1;
+		uint64_t unxfrm:1;
+		uint64_t nosync:1;
+		uint64_t diperr:1;
+		uint64_t datovr:1;
+		uint64_t ovrbst:1;
+		uint64_t calpar1:1;
+		uint64_t calpar0:1;
+	} s;
+	struct cvmx_stxx_int_reg_s cn38xx;
+	struct cvmx_stxx_int_reg_s cn38xxp2;
+	struct cvmx_stxx_int_reg_s cn58xx;
+	struct cvmx_stxx_int_reg_s cn58xxp1;
+};
+
+union cvmx_stxx_int_sync {
+	uint64_t u64;
+	struct cvmx_stxx_int_sync_s {
+		uint64_t reserved_8_63:56;
+		uint64_t frmerr:1;
+		uint64_t unxfrm:1;
+		uint64_t nosync:1;
+		uint64_t diperr:1;
+		uint64_t datovr:1;
+		uint64_t ovrbst:1;
+		uint64_t calpar1:1;
+		uint64_t calpar0:1;
+	} s;
+	struct cvmx_stxx_int_sync_s cn38xx;
+	struct cvmx_stxx_int_sync_s cn38xxp2;
+	struct cvmx_stxx_int_sync_s cn58xx;
+	struct cvmx_stxx_int_sync_s cn58xxp1;
+};
+
+union cvmx_stxx_min_bst {
+	uint64_t u64;
+	struct cvmx_stxx_min_bst_s {
+		uint64_t reserved_9_63:55;
+		uint64_t minb:9;
+	} s;
+	struct cvmx_stxx_min_bst_s cn38xx;
+	struct cvmx_stxx_min_bst_s cn38xxp2;
+	struct cvmx_stxx_min_bst_s cn58xx;
+	struct cvmx_stxx_min_bst_s cn58xxp1;
+};
+
+union cvmx_stxx_spi4_calx {
+	uint64_t u64;
+	struct cvmx_stxx_spi4_calx_s {
+		uint64_t reserved_17_63:47;
+		uint64_t oddpar:1;
+		uint64_t prt3:4;
+		uint64_t prt2:4;
+		uint64_t prt1:4;
+		uint64_t prt0:4;
+	} s;
+	struct cvmx_stxx_spi4_calx_s cn38xx;
+	struct cvmx_stxx_spi4_calx_s cn38xxp2;
+	struct cvmx_stxx_spi4_calx_s cn58xx;
+	struct cvmx_stxx_spi4_calx_s cn58xxp1;
+};
+
+union cvmx_stxx_spi4_dat {
+	uint64_t u64;
+	struct cvmx_stxx_spi4_dat_s {
+		uint64_t reserved_32_63:32;
+		uint64_t alpha:16;
+		uint64_t max_t:16;
+	} s;
+	struct cvmx_stxx_spi4_dat_s cn38xx;
+	struct cvmx_stxx_spi4_dat_s cn38xxp2;
+	struct cvmx_stxx_spi4_dat_s cn58xx;
+	struct cvmx_stxx_spi4_dat_s cn58xxp1;
+};
+
+union cvmx_stxx_spi4_stat {
+	uint64_t u64;
+	struct cvmx_stxx_spi4_stat_s {
+		uint64_t reserved_16_63:48;
+		uint64_t m:8;
+		uint64_t reserved_7_7:1;
+		uint64_t len:7;
+	} s;
+	struct cvmx_stxx_spi4_stat_s cn38xx;
+	struct cvmx_stxx_spi4_stat_s cn38xxp2;
+	struct cvmx_stxx_spi4_stat_s cn58xx;
+	struct cvmx_stxx_spi4_stat_s cn58xxp1;
+};
+
+union cvmx_stxx_stat_bytes_hi {
+	uint64_t u64;
+	struct cvmx_stxx_stat_bytes_hi_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_stxx_stat_bytes_hi_s cn38xx;
+	struct cvmx_stxx_stat_bytes_hi_s cn38xxp2;
+	struct cvmx_stxx_stat_bytes_hi_s cn58xx;
+	struct cvmx_stxx_stat_bytes_hi_s cn58xxp1;
+};
+
+union cvmx_stxx_stat_bytes_lo {
+	uint64_t u64;
+	struct cvmx_stxx_stat_bytes_lo_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_stxx_stat_bytes_lo_s cn38xx;
+	struct cvmx_stxx_stat_bytes_lo_s cn38xxp2;
+	struct cvmx_stxx_stat_bytes_lo_s cn58xx;
+	struct cvmx_stxx_stat_bytes_lo_s cn58xxp1;
+};
+
+union cvmx_stxx_stat_ctl {
+	uint64_t u64;
+	struct cvmx_stxx_stat_ctl_s {
+		uint64_t reserved_5_63:59;
+		uint64_t clr:1;
+		uint64_t bckprs:4;
+	} s;
+	struct cvmx_stxx_stat_ctl_s cn38xx;
+	struct cvmx_stxx_stat_ctl_s cn38xxp2;
+	struct cvmx_stxx_stat_ctl_s cn58xx;
+	struct cvmx_stxx_stat_ctl_s cn58xxp1;
+};
+
+union cvmx_stxx_stat_pkt_xmt {
+	uint64_t u64;
+	struct cvmx_stxx_stat_pkt_xmt_s {
+		uint64_t reserved_32_63:32;
+		uint64_t cnt:32;
+	} s;
+	struct cvmx_stxx_stat_pkt_xmt_s cn38xx;
+	struct cvmx_stxx_stat_pkt_xmt_s cn38xxp2;
+	struct cvmx_stxx_stat_pkt_xmt_s cn58xx;
+	struct cvmx_stxx_stat_pkt_xmt_s cn58xxp1;
+};
+
+#endif
diff --git a/drivers/staging/octeon/cvmx-wqe.h b/drivers/staging/octeon/cvmx-wqe.h
new file mode 100644
index 0000000..6536109
--- /dev/null
+++ b/drivers/staging/octeon/cvmx-wqe.h
@@ -0,0 +1,397 @@
+/***********************license start***************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2008 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+ ***********************license end**************************************/
+
+/**
+ *
+ * This header file defines the work queue entry (wqe) data structure.
+ * Since this is a commonly used structure that depends on structures
+ * from several hardware blocks, those definitions have been placed
+ * in this file to create a single point of definition of the wqe
+ * format.
+ * Data structures are still named according to the block that they
+ * relate to.
+ *
+ */
+
+#ifndef __CVMX_WQE_H__
+#define __CVMX_WQE_H__
+
+#include "cvmx-packet.h"
+
+
+#define OCT_TAG_TYPE_STRING(x)						\
+	(((x) == CVMX_POW_TAG_TYPE_ORDERED) ?  "ORDERED" :		\
+		(((x) == CVMX_POW_TAG_TYPE_ATOMIC) ?  "ATOMIC" :	\
+			(((x) == CVMX_POW_TAG_TYPE_NULL) ?  "NULL" :	\
+				"NULL_NULL")))
+
+/**
+ * HW decode / err_code in work queue entry
+ */
+typedef union {
+	uint64_t u64;
+
+	/* Use this struct if the hardware determines that the packet is IP */
+	struct {
+		/* HW sets this to the number of buffers used by this packet */
+		uint64_t bufs:8;
+		/* HW sets to the number of L2 bytes prior to the IP */
+		uint64_t ip_offset:8;
+		/* set to 1 if we found DSA/VLAN in the L2 */
+		uint64_t vlan_valid:1;
+		/* Set to 1 if the DSA/VLAN tag is stacked */
+		uint64_t vlan_stacked:1;
+		uint64_t unassigned:1;
+		/* HW sets to the DSA/VLAN CFI flag (valid when vlan_valid) */
+		uint64_t vlan_cfi:1;
+		/* HW sets to the DSA/VLAN_ID field (valid when vlan_valid) */
+		uint64_t vlan_id:12;
+		/* Ring Identifier (if PCIe). Requires PIP_GBL_CTL[RING_EN]=1 */
+		uint64_t pr:4;
+		uint64_t unassigned2:8;
+		/* the packet needs to be decompressed */
+		uint64_t dec_ipcomp:1;
+		/* the packet is either TCP or UDP */
+		uint64_t tcp_or_udp:1;
+		/* the packet needs to be decrypted (ESP or AH) */
+		uint64_t dec_ipsec:1;
+		/* the packet is IPv6 */
+		uint64_t is_v6:1;
+
+		/*
+		 * (rcv_error, not_IP, IP_exc, is_frag, L4_error,
+		 * software, etc.).
+		 */
+
+		/*
+		 * reserved for software use, hardware will clear on
+		 * packet creation.
+		 */
+		uint64_t software:1;
+		/* exceptional conditions below */
+		/* the receive interface hardware detected an L4 error
+		 * (only applies if !is_frag) (only applies if
+		 * !rcv_error && !not_IP && !IP_exc && !is_frag)
+		 * failure indicated in err_code below, decode:
+		 *
+		 * - 1 = Malformed L4
+		 * - 2 = L4 Checksum Error: the L4 checksum value is
+		 * - 3 = UDP Length Error: The UDP length field would
+		 *       make the UDP data longer than what remains in
+		 *       the IP packet (as defined by the IP header
+		 *       length field).
+		 * - 4 = Bad L4 Port: either the source or destination
+		 *       TCP/UDP port is 0.
+		 * - 8 = TCP FIN Only: the packet is TCP and only the
+		 *       FIN flag set.
+		 * - 9 = TCP No Flags: the packet is TCP and no flags
+		 *       are set.
+		 * - 10 = TCP FIN RST: the packet is TCP and both FIN
+		 *        and RST are set.
+		 * - 11 = TCP SYN URG: the packet is TCP and both SYN
+		 *        and URG are set.
+		 * - 12 = TCP SYN RST: the packet is TCP and both SYN
+		 *        and RST are set.
+		 * - 13 = TCP SYN FIN: the packet is TCP and both SYN
+		 *        and FIN are set.
+		 */
+		uint64_t L4_error:1;
+		/* set if the packet is a fragment */
+		uint64_t is_frag:1;
+		/* the receive interface hardware detected an IP error
+		 * / exception (only applies if !rcv_error && !not_IP)
+		 * failure indicated in err_code below, decode:
+		 *
+		 * - 1 = Not IP: the IP version field is neither 4 nor
+		 *       6.
+		 * - 2 = IPv4 Header Checksum Error: the IPv4 header
+		 *       has a checksum violation.
+		 * - 3 = IP Malformed Header: the packet is not long
+		 *       enough to contain the IP header.
+		 * - 4 = IP Malformed: the packet is not long enough
+		 *	 to contain the bytes indicated by the IP
+		 *	 header. Pad is allowed.
+		 * - 5 = IP TTL Hop: the IPv4 TTL field or the IPv6
+		 *       Hop Count field are zero.
+		 * - 6 = IP Options
+		 */
+		uint64_t IP_exc:1;
+		/*
+		 * Set if the hardware determined that the packet is a
+		 * broadcast.
+		 */
+		uint64_t is_bcast:1;
+		/*
+		 * St if the hardware determined that the packet is a
+		 * multi-cast.
+		 */
+		uint64_t is_mcast:1;
+		/*
+		 * Set if the packet may not be IP (must be zero in
+		 * this case).
+		 */
+		uint64_t not_IP:1;
+		/*
+		 * The receive interface hardware detected a receive
+		 * error (must be zero in this case).
+		 */
+		uint64_t rcv_error:1;
+		/* lower err_code = first-level descriptor of the
+		 * work */
+		/* zero for packet submitted by hardware that isn't on
+		 * the slow path */
+		/* type is cvmx_pip_err_t */
+		uint64_t err_code:8;
+	} s;
+
+	/* use this to get at the 16 vlan bits */
+	struct {
+		uint64_t unused1:16;
+		uint64_t vlan:16;
+		uint64_t unused2:32;
+	} svlan;
+
+	/*
+	 * use this struct if the hardware could not determine that
+	 * the packet is ip.
+	 */
+	struct {
+		/*
+		 * HW sets this to the number of buffers used by this
+		 * packet.
+		 */
+		uint64_t bufs:8;
+		uint64_t unused:8;
+		/* set to 1 if we found DSA/VLAN in the L2 */
+		uint64_t vlan_valid:1;
+		/* Set to 1 if the DSA/VLAN tag is stacked */
+		uint64_t vlan_stacked:1;
+		uint64_t unassigned:1;
+		/*
+		 * HW sets to the DSA/VLAN CFI flag (valid when
+		 * vlan_valid)
+		 */
+		uint64_t vlan_cfi:1;
+		/*
+		 * HW sets to the DSA/VLAN_ID field (valid when
+		 * vlan_valid).
+		 */
+		uint64_t vlan_id:12;
+		/*
+		 * Ring Identifier (if PCIe). Requires
+		 * PIP_GBL_CTL[RING_EN]=1
+		 */
+		uint64_t pr:4;
+		uint64_t unassigned2:12;
+		/*
+		 * reserved for software use, hardware will clear on
+		 * packet creation.
+		 */
+		uint64_t software:1;
+		uint64_t unassigned3:1;
+		/*
+		 * set if the hardware determined that the packet is
+		 * rarp.
+		 */
+		uint64_t is_rarp:1;
+		/*
+		 * set if the hardware determined that the packet is
+		 * arp
+		 */
+		uint64_t is_arp:1;
+		/*
+		 * set if the hardware determined that the packet is a
+		 * broadcast.
+		 */
+		uint64_t is_bcast:1;
+		/*
+		 * set if the hardware determined that the packet is a
+		 * multi-cast
+		 */
+		uint64_t is_mcast:1;
+		/*
+		 * set if the packet may not be IP (must be one in
+		 * this case)
+		 */
+		uint64_t not_IP:1;
+		/* The receive interface hardware detected a receive
+		 * error.  Failure indicated in err_code below,
+		 * decode:
+		 *
+		 * - 1 = partial error: a packet was partially
+		 *       received, but internal buffering / bandwidth
+		 *       was not adequate to receive the entire
+		 *       packet.
+		 * - 2 = jabber error: the RGMII packet was too large
+		 *       and is truncated.
+		 * - 3 = overrun error: the RGMII packet is longer
+		 *       than allowed and had an FCS error.
+		 * - 4 = oversize error: the RGMII packet is longer
+		 *       than allowed.
+		 * - 5 = alignment error: the RGMII packet is not an
+		 *       integer number of bytes
+		 *       and had an FCS error (100M and 10M only).
+		 * - 6 = fragment error: the RGMII packet is shorter
+		 *       than allowed and had an FCS error.
+		 * - 7 = GMX FCS error: the RGMII packet had an FCS
+		 *       error.
+		 * - 8 = undersize error: the RGMII packet is shorter
+		 *       than allowed.
+		 * - 9 = extend error: the RGMII packet had an extend
+		 *       error.
+		 * - 10 = length mismatch error: the RGMII packet had
+		 *        a length that did not match the length field
+		 *        in the L2 HDR.
+		 * - 11 = RGMII RX error/SPI4 DIP4 Error: the RGMII
+		 * 	  packet had one or more data reception errors
+		 * 	  (RXERR) or the SPI4 packet had one or more
+		 * 	  DIP4 errors.
+		 * - 12 = RGMII skip error/SPI4 Abort Error: the RGMII
+		 *        packet was not large enough to cover the
+		 *        skipped bytes or the SPI4 packet was
+		 *        terminated with an About EOPS.
+		 * - 13 = RGMII nibble error/SPI4 Port NXA Error: the
+		 *        RGMII packet had a studder error (data not
+		 *        repeated - 10/100M only) or the SPI4 packet
+		 *        was sent to an NXA.
+		 * - 16 = FCS error: a SPI4.2 packet had an FCS error.
+		 * - 17 = Skip error: a packet was not large enough to
+		 *        cover the skipped bytes.
+		 * - 18 = L2 header malformed: the packet is not long
+		 *        enough to contain the L2.
+		 */
+
+		uint64_t rcv_error:1;
+		/*
+		 * lower err_code = first-level descriptor of the
+		 * work
+		 */
+		/*
+		 * zero for packet submitted by hardware that isn't on
+		 * the slow path
+		 */
+		/* type is cvmx_pip_err_t (union, so can't use directly */
+		uint64_t err_code:8;
+	} snoip;
+
+} cvmx_pip_wqe_word2;
+
+/**
+ * Work queue entry format
+ *
+ * must be 8-byte aligned
+ */
+typedef struct {
+
+    /*****************************************************************
+     * WORD 0
+     *  HW WRITE: the following 64 bits are filled by HW when a packet arrives
+     */
+
+    /**
+     * raw chksum result generated by the HW
+     */
+	uint16_t hw_chksum;
+    /**
+     * Field unused by hardware - available for software
+     */
+	uint8_t unused;
+    /**
+     * Next pointer used by hardware for list maintenance.
+     * May be written/read by HW before the work queue
+     *           entry is scheduled to a PP
+     * (Only 36 bits used in Octeon 1)
+     */
+	uint64_t next_ptr:40;
+
+    /*****************************************************************
+     * WORD 1
+     *  HW WRITE: the following 64 bits are filled by HW when a packet arrives
+     */
+
+    /**
+     * HW sets to the total number of bytes in the packet
+     */
+	uint64_t len:16;
+    /**
+     * HW sets this to input physical port
+     */
+	uint64_t ipprt:6;
+
+    /**
+     * HW sets this to what it thought the priority of the input packet was
+     */
+	uint64_t qos:3;
+
+    /**
+     * the group that the work queue entry will be scheduled to
+     */
+	uint64_t grp:4;
+    /**
+     * the type of the tag (ORDERED, ATOMIC, NULL)
+     */
+	uint64_t tag_type:3;
+    /**
+     * the synchronization/ordering tag
+     */
+	uint64_t tag:32;
+
+    /**
+     * WORD 2 HW WRITE: the following 64-bits are filled in by
+     *   hardware when a packet arrives This indicates a variety of
+     *   status and error conditions.
+     */
+	cvmx_pip_wqe_word2 word2;
+
+    /**
+     * Pointer to the first segment of the packet.
+     */
+	union cvmx_buf_ptr packet_ptr;
+
+    /**
+     *   HW WRITE: octeon will fill in a programmable amount from the
+     *             packet, up to (at most, but perhaps less) the amount
+     *             needed to fill the work queue entry to 128 bytes
+     *
+     *   If the packet is recognized to be IP, the hardware starts
+     *   (except that the IPv4 header is padded for appropriate
+     *   alignment) writing here where the IP header starts.  If the
+     *   packet is not recognized to be IP, the hardware starts
+     *   writing the beginning of the packet here.
+     */
+	uint8_t packet_data[96];
+
+    /**
+     * If desired, SW can make the work Q entry any length. For the
+     * purposes of discussion here, Assume 128B always, as this is all that
+     * the hardware deals with.
+     *
+     */
+
+} CVMX_CACHE_LINE_ALIGNED cvmx_wqe_t;
+
+#endif /* __CVMX_WQE_H__ */
diff --git a/drivers/staging/octeon/ethernet-common.c b/drivers/staging/octeon/ethernet-common.c
new file mode 100644
index 0000000..3e6f5b8
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-common.c
@@ -0,0 +1,328 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+#include <linux/kernel.h>
+#include <linux/mii.h>
+#include <net/dst.h>
+
+#include <asm/atomic.h>
+#include <asm/octeon/octeon.h>
+
+#include "ethernet-defines.h"
+#include "ethernet-tx.h"
+#include "ethernet-mdio.h"
+#include "ethernet-util.h"
+#include "octeon-ethernet.h"
+#include "ethernet-common.h"
+
+#include "cvmx-pip.h"
+#include "cvmx-pko.h"
+#include "cvmx-fau.h"
+#include "cvmx-helper.h"
+
+#include "cvmx-gmxx-defs.h"
+
+/**
+ * Get the low level ethernet statistics
+ *
+ * @dev:    Device to get the statistics from
+ * Returns Pointer to the statistics
+ */
+static struct net_device_stats *cvm_oct_common_get_stats(struct net_device *dev)
+{
+	cvmx_pip_port_status_t rx_status;
+	cvmx_pko_port_status_t tx_status;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+
+	if (priv->port < CVMX_PIP_NUM_INPUT_PORTS) {
+		if (octeon_is_simulation()) {
+			/* The simulator doesn't support statistics */
+			memset(&rx_status, 0, sizeof(rx_status));
+			memset(&tx_status, 0, sizeof(tx_status));
+		} else {
+			cvmx_pip_get_port_status(priv->port, 1, &rx_status);
+			cvmx_pko_get_port_status(priv->port, 1, &tx_status);
+		}
+
+		priv->stats.rx_packets += rx_status.inb_packets;
+		priv->stats.tx_packets += tx_status.packets;
+		priv->stats.rx_bytes += rx_status.inb_octets;
+		priv->stats.tx_bytes += tx_status.octets;
+		priv->stats.multicast += rx_status.multicast_packets;
+		priv->stats.rx_crc_errors += rx_status.inb_errors;
+		priv->stats.rx_frame_errors += rx_status.fcs_align_err_packets;
+
+		/*
+		 * The drop counter must be incremented atomically
+		 * since the RX tasklet also increments it.
+		 */
+#ifdef CONFIG_64BIT
+		atomic64_add(rx_status.dropped_packets,
+			     (atomic64_t *)&priv->stats.rx_dropped);
+#else
+		atomic_add(rx_status.dropped_packets,
+			     (atomic_t *)&priv->stats.rx_dropped);
+#endif
+	}
+
+	return &priv->stats;
+}
+
+/**
+ * Set the multicast list. Currently unimplemented.
+ *
+ * @dev:    Device to work on
+ */
+static void cvm_oct_common_set_multicast_list(struct net_device *dev)
+{
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int interface = INTERFACE(priv->port);
+	int index = INDEX(priv->port);
+
+	if ((interface < 2)
+	    && (cvmx_helper_interface_get_mode(interface) !=
+		CVMX_HELPER_INTERFACE_MODE_SPI)) {
+		union cvmx_gmxx_rxx_adr_ctl control;
+		control.u64 = 0;
+		control.s.bcst = 1;	/* Allow broadcast MAC addresses */
+
+		if (dev->mc_list || (dev->flags & IFF_ALLMULTI) ||
+		    (dev->flags & IFF_PROMISC))
+			/* Force accept multicast packets */
+			control.s.mcst = 2;
+		else
+			/* Force reject multicat packets */
+			control.s.mcst = 1;
+
+		if (dev->flags & IFF_PROMISC)
+			/*
+			 * Reject matches if promisc. Since CAM is
+			 * shut off, should accept everything.
+			 */
+			control.s.cam_mode = 0;
+		else
+			/* Filter packets based on the CAM */
+			control.s.cam_mode = 1;
+
+		gmx_cfg.u64 =
+		    cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+		cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface),
+			       gmx_cfg.u64 & ~1ull);
+
+		cvmx_write_csr(CVMX_GMXX_RXX_ADR_CTL(index, interface),
+			       control.u64);
+		if (dev->flags & IFF_PROMISC)
+			cvmx_write_csr(CVMX_GMXX_RXX_ADR_CAM_EN
+				       (index, interface), 0);
+		else
+			cvmx_write_csr(CVMX_GMXX_RXX_ADR_CAM_EN
+				       (index, interface), 1);
+
+		cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface),
+			       gmx_cfg.u64);
+	}
+}
+
+/**
+ * Set the hardware MAC address for a device
+ *
+ * @dev:    Device to change the MAC address for
+ * @addr:   Address structure to change it too. MAC address is addr + 2.
+ * Returns Zero on success
+ */
+static int cvm_oct_common_set_mac_address(struct net_device *dev, void *addr)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	int interface = INTERFACE(priv->port);
+	int index = INDEX(priv->port);
+
+	memcpy(dev->dev_addr, addr + 2, 6);
+
+	if ((interface < 2)
+	    && (cvmx_helper_interface_get_mode(interface) !=
+		CVMX_HELPER_INTERFACE_MODE_SPI)) {
+		int i;
+		uint8_t *ptr = addr;
+		uint64_t mac = 0;
+		for (i = 0; i < 6; i++)
+			mac = (mac << 8) | (uint64_t) (ptr[i + 2]);
+
+		gmx_cfg.u64 =
+		    cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+		cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface),
+			       gmx_cfg.u64 & ~1ull);
+
+		cvmx_write_csr(CVMX_GMXX_SMACX(index, interface), mac);
+		cvmx_write_csr(CVMX_GMXX_RXX_ADR_CAM0(index, interface),
+			       ptr[2]);
+		cvmx_write_csr(CVMX_GMXX_RXX_ADR_CAM1(index, interface),
+			       ptr[3]);
+		cvmx_write_csr(CVMX_GMXX_RXX_ADR_CAM2(index, interface),
+			       ptr[4]);
+		cvmx_write_csr(CVMX_GMXX_RXX_ADR_CAM3(index, interface),
+			       ptr[5]);
+		cvmx_write_csr(CVMX_GMXX_RXX_ADR_CAM4(index, interface),
+			       ptr[6]);
+		cvmx_write_csr(CVMX_GMXX_RXX_ADR_CAM5(index, interface),
+			       ptr[7]);
+		cvm_oct_common_set_multicast_list(dev);
+		cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface),
+			       gmx_cfg.u64);
+	}
+	return 0;
+}
+
+/**
+ * Change the link MTU. Unimplemented
+ *
+ * @dev:     Device to change
+ * @new_mtu: The new MTU
+ *
+ * Returns Zero on success
+ */
+static int cvm_oct_common_change_mtu(struct net_device *dev, int new_mtu)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int interface = INTERFACE(priv->port);
+	int index = INDEX(priv->port);
+#if defined(CONFIG_VLAN_8021Q) || defined(CONFIG_VLAN_8021Q_MODULE)
+	int vlan_bytes = 4;
+#else
+	int vlan_bytes = 0;
+#endif
+
+	/*
+	 * Limit the MTU to make sure the ethernet packets are between
+	 * 64 bytes and 65535 bytes.
+	 */
+	if ((new_mtu + 14 + 4 + vlan_bytes < 64)
+	    || (new_mtu + 14 + 4 + vlan_bytes > 65392)) {
+		pr_err("MTU must be between %d and %d.\n",
+		       64 - 14 - 4 - vlan_bytes, 65392 - 14 - 4 - vlan_bytes);
+		return -EINVAL;
+	}
+	dev->mtu = new_mtu;
+
+	if ((interface < 2)
+	    && (cvmx_helper_interface_get_mode(interface) !=
+		CVMX_HELPER_INTERFACE_MODE_SPI)) {
+		/* Add ethernet header and FCS, and VLAN if configured. */
+		int max_packet = new_mtu + 14 + 4 + vlan_bytes;
+
+		if (OCTEON_IS_MODEL(OCTEON_CN3XXX)
+		    || OCTEON_IS_MODEL(OCTEON_CN58XX)) {
+			/* Signal errors on packets larger than the MTU */
+			cvmx_write_csr(CVMX_GMXX_RXX_FRM_MAX(index, interface),
+				       max_packet);
+		} else {
+			/*
+			 * Set the hardware to truncate packets larger
+			 * than the MTU and smaller the 64 bytes.
+			 */
+			union cvmx_pip_frm_len_chkx frm_len_chk;
+			frm_len_chk.u64 = 0;
+			frm_len_chk.s.minlen = 64;
+			frm_len_chk.s.maxlen = max_packet;
+			cvmx_write_csr(CVMX_PIP_FRM_LEN_CHKX(interface),
+				       frm_len_chk.u64);
+		}
+		/*
+		 * Set the hardware to truncate packets larger than
+		 * the MTU. The jabber register must be set to a
+		 * multiple of 8 bytes, so round up.
+		 */
+		cvmx_write_csr(CVMX_GMXX_RXX_JABBER(index, interface),
+			       (max_packet + 7) & ~7u);
+	}
+	return 0;
+}
+
+/**
+ * Per network device initialization
+ *
+ * @dev:    Device to initialize
+ * Returns Zero on success
+ */
+int cvm_oct_common_init(struct net_device *dev)
+{
+	static int count;
+	char mac[8] = { 0x00, 0x00,
+		octeon_bootinfo->mac_addr_base[0],
+		octeon_bootinfo->mac_addr_base[1],
+		octeon_bootinfo->mac_addr_base[2],
+		octeon_bootinfo->mac_addr_base[3],
+		octeon_bootinfo->mac_addr_base[4],
+		octeon_bootinfo->mac_addr_base[5] + count
+	};
+	struct octeon_ethernet *priv = netdev_priv(dev);
+
+	/*
+	 * Force the interface to use the POW send if always_use_pow
+	 * was specified or it is in the pow send list.
+	 */
+	if ((pow_send_group != -1)
+	    && (always_use_pow || strstr(pow_send_list, dev->name)))
+		priv->queue = -1;
+
+	if (priv->queue != -1) {
+		dev->hard_start_xmit = cvm_oct_xmit;
+		if (USE_HW_TCPUDP_CHECKSUM)
+			dev->features |= NETIF_F_IP_CSUM;
+	} else
+		dev->hard_start_xmit = cvm_oct_xmit_pow;
+	count++;
+
+	dev->get_stats = cvm_oct_common_get_stats;
+	dev->set_mac_address = cvm_oct_common_set_mac_address;
+	dev->set_multicast_list = cvm_oct_common_set_multicast_list;
+	dev->change_mtu = cvm_oct_common_change_mtu;
+	dev->do_ioctl = cvm_oct_ioctl;
+	/* We do our own locking, Linux doesn't need to */
+	dev->features |= NETIF_F_LLTX;
+	SET_ETHTOOL_OPS(dev, &cvm_oct_ethtool_ops);
+#ifdef CONFIG_NET_POLL_CONTROLLER
+	dev->poll_controller = cvm_oct_poll_controller;
+#endif
+
+	cvm_oct_mdio_setup_device(dev);
+	dev->set_mac_address(dev, mac);
+	dev->change_mtu(dev, dev->mtu);
+
+	/*
+	 * Zero out stats for port so we won't mistakenly show
+	 * counters from the bootloader.
+	 */
+	memset(dev->get_stats(dev), 0, sizeof(struct net_device_stats));
+
+	return 0;
+}
+
+void cvm_oct_common_uninit(struct net_device *dev)
+{
+	/* Currently nothing to do */
+}
diff --git a/drivers/staging/octeon/ethernet-common.h b/drivers/staging/octeon/ethernet-common.h
new file mode 100644
index 0000000..2bd9cd7
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-common.h
@@ -0,0 +1,29 @@
+/*********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+*********************************************************************/
+
+int cvm_oct_common_init(struct net_device *dev);
+void cvm_oct_common_uninit(struct net_device *dev);
diff --git a/drivers/staging/octeon/ethernet-defines.h b/drivers/staging/octeon/ethernet-defines.h
new file mode 100644
index 0000000..8f7374e
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-defines.h
@@ -0,0 +1,134 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+
+/*
+ * A few defines are used to control the operation of this driver:
+ *  CONFIG_CAVIUM_RESERVE32
+ *      This kernel config options controls the amount of memory configured
+ *      in a wired TLB entry for all processes to share. If this is set, the
+ *      driver will use this memory instead of kernel memory for pools. This
+ *      allows 32bit userspace application to access the buffers, but also
+ *      requires all received packets to be copied.
+ *  CONFIG_CAVIUM_OCTEON_NUM_PACKET_BUFFERS
+ *      This kernel config option allows the user to control the number of
+ *      packet and work queue buffers allocated by the driver. If this is zero,
+ *      the driver uses the default from below.
+ *  USE_SKBUFFS_IN_HW
+ *      Tells the driver to populate the packet buffers with kernel skbuffs.
+ *      This allows the driver to receive packets without copying them. It also
+ *      means that 32bit userspace can't access the packet buffers.
+ *  USE_32BIT_SHARED
+ *      This define tells the driver to allocate memory for buffers from the
+ *      32bit sahred region instead of the kernel memory space.
+ *  USE_HW_TCPUDP_CHECKSUM
+ *      Controls if the Octeon TCP/UDP checksum engine is used for packet
+ *      output. If this is zero, the kernel will perform the checksum in
+ *      software.
+ *  USE_MULTICORE_RECEIVE
+ *      Process receive interrupts on multiple cores. This spreads the network
+ *      load across the first 8 processors. If ths is zero, only one core
+ *      processes incomming packets.
+ *  USE_ASYNC_IOBDMA
+ *      Use asynchronous IO access to hardware. This uses Octeon's asynchronous
+ *      IOBDMAs to issue IO accesses without stalling. Set this to zero
+ *      to disable this. Note that IOBDMAs require CVMSEG.
+ *  REUSE_SKBUFFS_WITHOUT_FREE
+ *      Allows the TX path to free an skbuff into the FPA hardware pool. This
+ *      can significantly improve performance for forwarding and bridging, but
+ *      may be somewhat dangerous. Checks are made, but if any buffer is reused
+ *      without the proper Linux cleanup, the networking stack may have very
+ *      bizarre bugs.
+ */
+#ifndef __ETHERNET_DEFINES_H__
+#define __ETHERNET_DEFINES_H__
+
+#include "cvmx-config.h"
+
+
+#define OCTEON_ETHERNET_VERSION "1.9"
+
+#ifndef CONFIG_CAVIUM_RESERVE32
+#define CONFIG_CAVIUM_RESERVE32 0
+#endif
+
+#if CONFIG_CAVIUM_RESERVE32
+#define USE_32BIT_SHARED            1
+#define USE_SKBUFFS_IN_HW           0
+#define REUSE_SKBUFFS_WITHOUT_FREE  0
+#else
+#define USE_32BIT_SHARED            0
+#define USE_SKBUFFS_IN_HW           1
+#ifdef CONFIG_NETFILTER
+#define REUSE_SKBUFFS_WITHOUT_FREE  0
+#else
+#define REUSE_SKBUFFS_WITHOUT_FREE  1
+#endif
+#endif
+
+/* Max interrupts per second per core */
+#define INTERRUPT_LIMIT             10000
+
+/* Don't limit the number of interrupts */
+/*#define INTERRUPT_LIMIT             0     */
+#define USE_HW_TCPUDP_CHECKSUM      1
+
+#define USE_MULTICORE_RECEIVE       1
+
+/* Enable Random Early Dropping under load */
+#define USE_RED                     1
+#define USE_ASYNC_IOBDMA            (CONFIG_CAVIUM_OCTEON_CVMSEG_SIZE > 0)
+
+/*
+ * Allow SW based preamble removal at 10Mbps to workaround PHYs giving
+ * us bad preambles.
+ */
+#define USE_10MBPS_PREAMBLE_WORKAROUND 1
+/*
+ * Use this to have all FPA frees also tell the L2 not to write data
+ * to memory.
+ */
+#define DONT_WRITEBACK(x)           (x)
+/* Use this to not have FPA frees control L2 */
+/*#define DONT_WRITEBACK(x)         0   */
+
+/* Maximum number of packets to process per interrupt. */
+#define MAX_RX_PACKETS 120
+#define MAX_OUT_QUEUE_DEPTH 1000
+
+#ifndef CONFIG_SMP
+#undef USE_MULTICORE_RECEIVE
+#define USE_MULTICORE_RECEIVE 0
+#endif
+
+#define IP_PROTOCOL_TCP             6
+#define IP_PROTOCOL_UDP             0x11
+
+#define FAU_NUM_PACKET_BUFFERS_TO_FREE (CVMX_FAU_REG_END - sizeof(uint32_t))
+#define TOTAL_NUMBER_OF_PORTS       (CVMX_PIP_NUM_INPUT_PORTS+1)
+
+
+#endif /* __ETHERNET_DEFINES_H__ */
diff --git a/drivers/staging/octeon/ethernet-mdio.c b/drivers/staging/octeon/ethernet-mdio.c
new file mode 100644
index 0000000..93cab0a
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-mdio.c
@@ -0,0 +1,231 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+#include <linux/kernel.h>
+#include <linux/ethtool.h>
+#include <linux/mii.h>
+#include <net/dst.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "ethernet-defines.h"
+#include "octeon-ethernet.h"
+#include "ethernet-mdio.h"
+
+#include "cvmx-helper-board.h"
+
+#include "cvmx-smix-defs.h"
+
+DECLARE_MUTEX(mdio_sem);
+
+/**
+ * Perform an MII read. Called by the generic MII routines
+ *
+ * @dev:      Device to perform read for
+ * @phy_id:   The MII phy id
+ * @location: Register location to read
+ * Returns Result from the read or zero on failure
+ */
+static int cvm_oct_mdio_read(struct net_device *dev, int phy_id, int location)
+{
+	union cvmx_smix_cmd smi_cmd;
+	union cvmx_smix_rd_dat smi_rd;
+
+	smi_cmd.u64 = 0;
+	smi_cmd.s.phy_op = 1;
+	smi_cmd.s.phy_adr = phy_id;
+	smi_cmd.s.reg_adr = location;
+	cvmx_write_csr(CVMX_SMIX_CMD(0), smi_cmd.u64);
+
+	do {
+		if (!in_interrupt())
+			yield();
+		smi_rd.u64 = cvmx_read_csr(CVMX_SMIX_RD_DAT(0));
+	} while (smi_rd.s.pending);
+
+	if (smi_rd.s.val)
+		return smi_rd.s.dat;
+	else
+		return 0;
+}
+
+static int cvm_oct_mdio_dummy_read(struct net_device *dev, int phy_id,
+				   int location)
+{
+	return 0xffff;
+}
+
+/**
+ * Perform an MII write. Called by the generic MII routines
+ *
+ * @dev:      Device to perform write for
+ * @phy_id:   The MII phy id
+ * @location: Register location to write
+ * @val:      Value to write
+ */
+static void cvm_oct_mdio_write(struct net_device *dev, int phy_id, int location,
+			       int val)
+{
+	union cvmx_smix_cmd smi_cmd;
+	union cvmx_smix_wr_dat smi_wr;
+
+	smi_wr.u64 = 0;
+	smi_wr.s.dat = val;
+	cvmx_write_csr(CVMX_SMIX_WR_DAT(0), smi_wr.u64);
+
+	smi_cmd.u64 = 0;
+	smi_cmd.s.phy_op = 0;
+	smi_cmd.s.phy_adr = phy_id;
+	smi_cmd.s.reg_adr = location;
+	cvmx_write_csr(CVMX_SMIX_CMD(0), smi_cmd.u64);
+
+	do {
+		if (!in_interrupt())
+			yield();
+		smi_wr.u64 = cvmx_read_csr(CVMX_SMIX_WR_DAT(0));
+	} while (smi_wr.s.pending);
+}
+
+static void cvm_oct_mdio_dummy_write(struct net_device *dev, int phy_id,
+				     int location, int val)
+{
+}
+
+static void cvm_oct_get_drvinfo(struct net_device *dev,
+				struct ethtool_drvinfo *info)
+{
+	strcpy(info->driver, "cavium-ethernet");
+	strcpy(info->version, OCTEON_ETHERNET_VERSION);
+	strcpy(info->bus_info, "Builtin");
+}
+
+static int cvm_oct_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int ret;
+
+	down(&mdio_sem);
+	ret = mii_ethtool_gset(&priv->mii_info, cmd);
+	up(&mdio_sem);
+
+	return ret;
+}
+
+static int cvm_oct_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int ret;
+
+	down(&mdio_sem);
+	ret = mii_ethtool_sset(&priv->mii_info, cmd);
+	up(&mdio_sem);
+
+	return ret;
+}
+
+static int cvm_oct_nway_reset(struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int ret;
+
+	down(&mdio_sem);
+	ret = mii_nway_restart(&priv->mii_info);
+	up(&mdio_sem);
+
+	return ret;
+}
+
+static u32 cvm_oct_get_link(struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	u32 ret;
+
+	down(&mdio_sem);
+	ret = mii_link_ok(&priv->mii_info);
+	up(&mdio_sem);
+
+	return ret;
+}
+
+struct ethtool_ops cvm_oct_ethtool_ops = {
+	.get_drvinfo = cvm_oct_get_drvinfo,
+	.get_settings = cvm_oct_get_settings,
+	.set_settings = cvm_oct_set_settings,
+	.nway_reset = cvm_oct_nway_reset,
+	.get_link = cvm_oct_get_link,
+	.get_sg = ethtool_op_get_sg,
+	.get_tx_csum = ethtool_op_get_tx_csum,
+};
+
+/**
+ * IOCTL support for PHY control
+ *
+ * @dev:    Device to change
+ * @rq:     the request
+ * @cmd:    the command
+ * Returns Zero on success
+ */
+int cvm_oct_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	struct mii_ioctl_data *data = if_mii(rq);
+	unsigned int duplex_chg;
+	int ret;
+
+	down(&mdio_sem);
+	ret = generic_mii_ioctl(&priv->mii_info, data, cmd, &duplex_chg);
+	up(&mdio_sem);
+
+	return ret;
+}
+
+/**
+ * Setup the MDIO device structures
+ *
+ * @dev:    Device to setup
+ *
+ * Returns Zero on success, negative on failure
+ */
+int cvm_oct_mdio_setup_device(struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int phy_id = cvmx_helper_board_get_mii_address(priv->port);
+	if (phy_id != -1) {
+		priv->mii_info.dev = dev;
+		priv->mii_info.phy_id = phy_id;
+		priv->mii_info.phy_id_mask = 0xff;
+		priv->mii_info.supports_gmii = 1;
+		priv->mii_info.reg_num_mask = 0x1f;
+		priv->mii_info.mdio_read = cvm_oct_mdio_read;
+		priv->mii_info.mdio_write = cvm_oct_mdio_write;
+	} else {
+		/* Supply dummy MDIO routines so the kernel won't crash
+		   if the user tries to read them */
+		priv->mii_info.mdio_read = cvm_oct_mdio_dummy_read;
+		priv->mii_info.mdio_write = cvm_oct_mdio_dummy_write;
+	}
+	return 0;
+}
diff --git a/drivers/staging/octeon/ethernet-mdio.h b/drivers/staging/octeon/ethernet-mdio.h
new file mode 100644
index 0000000..6314141
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-mdio.h
@@ -0,0 +1,46 @@
+/*********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+*********************************************************************/
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/netdevice.h>
+#include <linux/init.h>
+#include <linux/etherdevice.h>
+#include <linux/ip.h>
+#include <linux/string.h>
+#include <linux/ethtool.h>
+#include <linux/mii.h>
+#include <linux/seq_file.h>
+#include <linux/proc_fs.h>
+#include <net/dst.h>
+#ifdef CONFIG_XFRM
+#include <linux/xfrm.h>
+#include <net/xfrm.h>
+#endif /* CONFIG_XFRM */
+
+extern struct ethtool_ops cvm_oct_ethtool_ops;
+int cvm_oct_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
+int cvm_oct_mdio_setup_device(struct net_device *dev);
diff --git a/drivers/staging/octeon/ethernet-mem.c b/drivers/staging/octeon/ethernet-mem.c
new file mode 100644
index 0000000..b595903
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-mem.c
@@ -0,0 +1,198 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+#include <linux/kernel.h>
+#include <linux/netdevice.h>
+#include <linux/mii.h>
+#include <net/dst.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "ethernet-defines.h"
+
+#include "cvmx-fpa.h"
+
+/**
+ * Fill the supplied hardware pool with skbuffs
+ *
+ * @pool:     Pool to allocate an skbuff for
+ * @size:     Size of the buffer needed for the pool
+ * @elements: Number of buffers to allocate
+ */
+static int cvm_oct_fill_hw_skbuff(int pool, int size, int elements)
+{
+	int freed = elements;
+	while (freed) {
+
+		struct sk_buff *skb = dev_alloc_skb(size + 128);
+		if (unlikely(skb == NULL)) {
+			pr_warning
+			    ("Failed to allocate skb for hardware pool %d\n",
+			     pool);
+			break;
+		}
+
+		skb_reserve(skb, 128 - (((unsigned long)skb->data) & 0x7f));
+		*(struct sk_buff **)(skb->data - sizeof(void *)) = skb;
+		cvmx_fpa_free(skb->data, pool, DONT_WRITEBACK(size / 128));
+		freed--;
+	}
+	return elements - freed;
+}
+
+/**
+ * Free the supplied hardware pool of skbuffs
+ *
+ * @pool:     Pool to allocate an skbuff for
+ * @size:     Size of the buffer needed for the pool
+ * @elements: Number of buffers to allocate
+ */
+static void cvm_oct_free_hw_skbuff(int pool, int size, int elements)
+{
+	char *memory;
+
+	do {
+		memory = cvmx_fpa_alloc(pool);
+		if (memory) {
+			struct sk_buff *skb =
+			    *(struct sk_buff **)(memory - sizeof(void *));
+			elements--;
+			dev_kfree_skb(skb);
+		}
+	} while (memory);
+
+	if (elements < 0)
+		pr_warning("Freeing of pool %u had too many skbuffs (%d)\n",
+		     pool, elements);
+	else if (elements > 0)
+		pr_warning("Freeing of pool %u is missing %d skbuffs\n",
+		       pool, elements);
+}
+
+/**
+ * This function fills a hardware pool with memory. Depending
+ * on the config defines, this memory might come from the
+ * kernel or global 32bit memory allocated with
+ * cvmx_bootmem_alloc.
+ *
+ * @pool:     Pool to populate
+ * @size:     Size of each buffer in the pool
+ * @elements: Number of buffers to allocate
+ */
+static int cvm_oct_fill_hw_memory(int pool, int size, int elements)
+{
+	char *memory;
+	int freed = elements;
+
+	if (USE_32BIT_SHARED) {
+		extern uint64_t octeon_reserve32_memory;
+
+		memory =
+		    cvmx_bootmem_alloc_range(elements * size, 128,
+					     octeon_reserve32_memory,
+					     octeon_reserve32_memory +
+					     (CONFIG_CAVIUM_RESERVE32 << 20) -
+					     1);
+		if (memory == NULL)
+			panic("Unable to allocate %u bytes for FPA pool %d\n",
+			      elements * size, pool);
+
+		pr_notice("Memory range %p - %p reserved for "
+			  "hardware\n", memory,
+			  memory + elements * size - 1);
+
+		while (freed) {
+			cvmx_fpa_free(memory, pool, 0);
+			memory += size;
+			freed--;
+		}
+	} else {
+		while (freed) {
+			/* We need to force alignment to 128 bytes here */
+			memory = kmalloc(size + 127, GFP_ATOMIC);
+			if (unlikely(memory == NULL)) {
+				pr_warning("Unable to allocate %u bytes for "
+					   "FPA pool %d\n",
+				     elements * size, pool);
+				break;
+			}
+			memory = (char *)(((unsigned long)memory + 127) & -128);
+			cvmx_fpa_free(memory, pool, 0);
+			freed--;
+		}
+	}
+	return elements - freed;
+}
+
+/**
+ * Free memory previously allocated with cvm_oct_fill_hw_memory
+ *
+ * @pool:     FPA pool to free
+ * @size:     Size of each buffer in the pool
+ * @elements: Number of buffers that should be in the pool
+ */
+static void cvm_oct_free_hw_memory(int pool, int size, int elements)
+{
+	if (USE_32BIT_SHARED) {
+		pr_warning("Warning: 32 shared memory is not freeable\n");
+	} else {
+		char *memory;
+		do {
+			memory = cvmx_fpa_alloc(pool);
+			if (memory) {
+				elements--;
+				kfree(phys_to_virt(cvmx_ptr_to_phys(memory)));
+			}
+		} while (memory);
+
+		if (elements < 0)
+			pr_warning("Freeing of pool %u had too many "
+				   "buffers (%d)\n",
+			       pool, elements);
+		else if (elements > 0)
+			pr_warning("Warning: Freeing of pool %u is "
+				"missing %d buffers\n",
+			     pool, elements);
+	}
+}
+
+int cvm_oct_mem_fill_fpa(int pool, int size, int elements)
+{
+	int freed;
+	if (USE_SKBUFFS_IN_HW)
+		freed = cvm_oct_fill_hw_skbuff(pool, size, elements);
+	else
+		freed = cvm_oct_fill_hw_memory(pool, size, elements);
+	return freed;
+}
+
+void cvm_oct_mem_empty_fpa(int pool, int size, int elements)
+{
+	if (USE_SKBUFFS_IN_HW)
+		cvm_oct_free_hw_skbuff(pool, size, elements);
+	else
+		cvm_oct_free_hw_memory(pool, size, elements);
+}
diff --git a/drivers/staging/octeon/ethernet-mem.h b/drivers/staging/octeon/ethernet-mem.h
new file mode 100644
index 0000000..713f2ed
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-mem.h
@@ -0,0 +1,29 @@
+/*********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+********************************************************************/
+
+int cvm_oct_mem_fill_fpa(int pool, int size, int elements);
+void cvm_oct_mem_empty_fpa(int pool, int size, int elements);
diff --git a/drivers/staging/octeon/ethernet-proc.c b/drivers/staging/octeon/ethernet-proc.c
new file mode 100644
index 0000000..8fa88fc
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-proc.c
@@ -0,0 +1,256 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+#include <linux/kernel.h>
+#include <linux/mii.h>
+#include <linux/seq_file.h>
+#include <linux/proc_fs.h>
+#include <net/dst.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "octeon-ethernet.h"
+#include "ethernet-defines.h"
+
+#include "cvmx-helper.h"
+#include "cvmx-pip.h"
+
+static unsigned long long cvm_oct_stats_read_switch(struct net_device *dev,
+						    int phy_id, int offset)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+
+	priv->mii_info.mdio_write(dev, phy_id, 0x1d, 0xcc00 | offset);
+	return ((uint64_t) priv->mii_info.
+		mdio_read(dev, phy_id,
+			  0x1e) << 16) | (uint64_t) priv->mii_info.
+	    mdio_read(dev, phy_id, 0x1f);
+}
+
+static int cvm_oct_stats_switch_show(struct seq_file *m, void *v)
+{
+	static const int ports[] = { 0, 1, 2, 3, 9, -1 };
+	struct net_device *dev = cvm_oct_device[0];
+	int index = 0;
+
+	while (ports[index] != -1) {
+
+		/* Latch port */
+		struct octeon_ethernet *priv = netdev_priv(dev);
+
+		priv->mii_info.mdio_write(dev, 0x1b, 0x1d,
+					  0xdc00 | ports[index]);
+		seq_printf(m, "\nSwitch Port %d\n", ports[index]);
+		seq_printf(m, "InGoodOctets:   %12llu\t"
+			   "OutOctets:      %12llu\t"
+			   "64 Octets:      %12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b,
+						     0x00) |
+			   (cvm_oct_stats_read_switch(dev, 0x1b, 0x01) << 32),
+			   cvm_oct_stats_read_switch(dev, 0x1b,
+						     0x0E) |
+			   (cvm_oct_stats_read_switch(dev, 0x1b, 0x0F) << 32),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x08));
+
+		seq_printf(m, "InBadOctets:    %12llu\t"
+			   "OutUnicast:     %12llu\t"
+			   "65-127 Octets:  %12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x02),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x10),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x09));
+
+		seq_printf(m, "InUnicast:      %12llu\t"
+			   "OutBroadcasts:  %12llu\t"
+			   "128-255 Octets: %12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x04),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x13),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x0A));
+
+		seq_printf(m, "InBroadcasts:   %12llu\t"
+			   "OutMulticasts:  %12llu\t"
+			   "256-511 Octets: %12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x06),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x12),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x0B));
+
+		seq_printf(m, "InMulticasts:   %12llu\t"
+			   "OutPause:       %12llu\t"
+			   "512-1023 Octets:%12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x07),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x15),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x0C));
+
+		seq_printf(m, "InPause:        %12llu\t"
+			   "Excessive:      %12llu\t"
+			   "1024-Max Octets:%12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x16),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x11),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x0D));
+
+		seq_printf(m, "InUndersize:    %12llu\t"
+			   "Collisions:     %12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x18),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x1E));
+
+		seq_printf(m, "InFragments:    %12llu\t"
+			   "Deferred:       %12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x19),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x05));
+
+		seq_printf(m, "InOversize:     %12llu\t"
+			   "Single:         %12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x1A),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x14));
+
+		seq_printf(m, "InJabber:       %12llu\t"
+			   "Multiple:       %12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x1B),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x17));
+
+		seq_printf(m, "In RxErr:       %12llu\t"
+			   "OutFCSErr:      %12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x1C),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x03));
+
+		seq_printf(m, "InFCSErr:       %12llu\t"
+			   "Late:           %12llu\n",
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x1D),
+			   cvm_oct_stats_read_switch(dev, 0x1b, 0x1F));
+		index++;
+	}
+	return 0;
+}
+
+/**
+ * User is reading /proc/octeon_ethernet_stats
+ *
+ * @m:
+ * @v:
+ * Returns
+ */
+static int cvm_oct_stats_show(struct seq_file *m, void *v)
+{
+	struct octeon_ethernet *priv;
+	int port;
+
+	for (port = 0; port < TOTAL_NUMBER_OF_PORTS; port++) {
+
+		if (cvm_oct_device[port]) {
+			priv = netdev_priv(cvm_oct_device[port]);
+
+			seq_printf(m, "\nOcteon Port %d (%s)\n", port,
+				   cvm_oct_device[port]->name);
+			seq_printf(m,
+				   "rx_packets:             %12lu\t"
+				   "tx_packets:             %12lu\n",
+				   priv->stats.rx_packets,
+				   priv->stats.tx_packets);
+			seq_printf(m,
+				   "rx_bytes:               %12lu\t"
+				   "tx_bytes:               %12lu\n",
+				   priv->stats.rx_bytes, priv->stats.tx_bytes);
+			seq_printf(m,
+				   "rx_errors:              %12lu\t"
+				   "tx_errors:              %12lu\n",
+				   priv->stats.rx_errors,
+				   priv->stats.tx_errors);
+			seq_printf(m,
+				   "rx_dropped:             %12lu\t"
+				   "tx_dropped:             %12lu\n",
+				   priv->stats.rx_dropped,
+				   priv->stats.tx_dropped);
+			seq_printf(m,
+				   "rx_length_errors:       %12lu\t"
+				   "tx_aborted_errors:      %12lu\n",
+				   priv->stats.rx_length_errors,
+				   priv->stats.tx_aborted_errors);
+			seq_printf(m,
+				   "rx_over_errors:         %12lu\t"
+				   "tx_carrier_errors:      %12lu\n",
+				   priv->stats.rx_over_errors,
+				   priv->stats.tx_carrier_errors);
+			seq_printf(m,
+				   "rx_crc_errors:          %12lu\t"
+				   "tx_fifo_errors:         %12lu\n",
+				   priv->stats.rx_crc_errors,
+				   priv->stats.tx_fifo_errors);
+			seq_printf(m,
+				   "rx_frame_errors:        %12lu\t"
+				   "tx_heartbeat_errors:    %12lu\n",
+				   priv->stats.rx_frame_errors,
+				   priv->stats.tx_heartbeat_errors);
+			seq_printf(m,
+				   "rx_fifo_errors:         %12lu\t"
+				   "tx_window_errors:       %12lu\n",
+				   priv->stats.rx_fifo_errors,
+				   priv->stats.tx_window_errors);
+			seq_printf(m,
+				   "rx_missed_errors:       %12lu\t"
+				   "multicast:              %12lu\n",
+				   priv->stats.rx_missed_errors,
+				   priv->stats.multicast);
+		}
+	}
+
+	if (cvm_oct_device[0]) {
+		priv = netdev_priv(cvm_oct_device[0]);
+		if (priv->imode == CVMX_HELPER_INTERFACE_MODE_GMII)
+			cvm_oct_stats_switch_show(m, v);
+	}
+	return 0;
+}
+
+/**
+ * /proc/octeon_ethernet_stats was openned. Use the single_open iterator
+ *
+ * @inode:
+ * @file:
+ * Returns
+ */
+static int cvm_oct_stats_open(struct inode *inode, struct file *file)
+{
+	return single_open(file, cvm_oct_stats_show, NULL);
+}
+
+static const struct file_operations cvm_oct_stats_operations = {
+	.open = cvm_oct_stats_open,
+	.read = seq_read,
+	.llseek = seq_lseek,
+	.release = single_release,
+};
+
+void cvm_oct_proc_initialize(void)
+{
+	struct proc_dir_entry *entry =
+	    create_proc_entry("octeon_ethernet_stats", 0, NULL);
+	if (entry)
+		entry->proc_fops = &cvm_oct_stats_operations;
+}
+
+void cvm_oct_proc_shutdown(void)
+{
+	remove_proc_entry("octeon_ethernet_stats", NULL);
+}
diff --git a/drivers/staging/octeon/ethernet-proc.h b/drivers/staging/octeon/ethernet-proc.h
new file mode 100644
index 0000000..82c7d9f
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-proc.h
@@ -0,0 +1,29 @@
+/*********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+*********************************************************************/
+
+void cvm_oct_proc_initialize(void);
+void cvm_oct_proc_shutdown(void);
diff --git a/drivers/staging/octeon/ethernet-rgmii.c b/drivers/staging/octeon/ethernet-rgmii.c
new file mode 100644
index 0000000..8579f16
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-rgmii.c
@@ -0,0 +1,397 @@
+/*********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+#include <linux/kernel.h>
+#include <linux/netdevice.h>
+#include <linux/mii.h>
+#include <net/dst.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "ethernet-defines.h"
+#include "octeon-ethernet.h"
+#include "ethernet-common.h"
+#include "ethernet-util.h"
+
+#include "cvmx-helper.h"
+
+#include <asm/octeon/cvmx-ipd-defs.h>
+#include <asm/octeon/cvmx-npi-defs.h>
+#include "cvmx-gmxx-defs.h"
+
+DEFINE_SPINLOCK(global_register_lock);
+
+static int number_rgmii_ports;
+
+static void cvm_oct_rgmii_poll(struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	unsigned long flags;
+	cvmx_helper_link_info_t link_info;
+
+	/*
+	 * Take the global register lock since we are going to touch
+	 * registers that affect more than one port.
+	 */
+	spin_lock_irqsave(&global_register_lock, flags);
+
+	link_info = cvmx_helper_link_get(priv->port);
+	if (link_info.u64 == priv->link_info) {
+
+		/*
+		 * If the 10Mbps preamble workaround is supported and we're
+		 * at 10Mbps we may need to do some special checking.
+		 */
+		if (USE_10MBPS_PREAMBLE_WORKAROUND && (link_info.s.speed == 10)) {
+
+			/*
+			 * Read the GMXX_RXX_INT_REG[PCTERR] bit and
+			 * see if we are getting preamble errors.
+			 */
+			int interface = INTERFACE(priv->port);
+			int index = INDEX(priv->port);
+			union cvmx_gmxx_rxx_int_reg gmxx_rxx_int_reg;
+			gmxx_rxx_int_reg.u64 =
+			    cvmx_read_csr(CVMX_GMXX_RXX_INT_REG
+					  (index, interface));
+			if (gmxx_rxx_int_reg.s.pcterr) {
+
+				/*
+				 * We are getting preamble errors at
+				 * 10Mbps.  Most likely the PHY is
+				 * giving us packets with mis aligned
+				 * preambles. In order to get these
+				 * packets we need to disable preamble
+				 * checking and do it in software.
+				 */
+				union cvmx_gmxx_rxx_frm_ctl gmxx_rxx_frm_ctl;
+				union cvmx_ipd_sub_port_fcs ipd_sub_port_fcs;
+
+				/* Disable preamble checking */
+				gmxx_rxx_frm_ctl.u64 =
+				    cvmx_read_csr(CVMX_GMXX_RXX_FRM_CTL
+						  (index, interface));
+				gmxx_rxx_frm_ctl.s.pre_chk = 0;
+				cvmx_write_csr(CVMX_GMXX_RXX_FRM_CTL
+					       (index, interface),
+					       gmxx_rxx_frm_ctl.u64);
+
+				/* Disable FCS stripping */
+				ipd_sub_port_fcs.u64 =
+				    cvmx_read_csr(CVMX_IPD_SUB_PORT_FCS);
+				ipd_sub_port_fcs.s.port_bit &=
+				    0xffffffffull ^ (1ull << priv->port);
+				cvmx_write_csr(CVMX_IPD_SUB_PORT_FCS,
+					       ipd_sub_port_fcs.u64);
+
+				/* Clear any error bits */
+				cvmx_write_csr(CVMX_GMXX_RXX_INT_REG
+					       (index, interface),
+					       gmxx_rxx_int_reg.u64);
+				DEBUGPRINT("%s: Using 10Mbps with software "
+					   "preamble removal\n",
+				     dev->name);
+			}
+		}
+		spin_unlock_irqrestore(&global_register_lock, flags);
+		return;
+	}
+
+	/* If the 10Mbps preamble workaround is allowed we need to on
+	   preamble checking, FCS stripping, and clear error bits on
+	   every speed change. If errors occur during 10Mbps operation
+	   the above code will change this stuff */
+	if (USE_10MBPS_PREAMBLE_WORKAROUND) {
+
+		union cvmx_gmxx_rxx_frm_ctl gmxx_rxx_frm_ctl;
+		union cvmx_ipd_sub_port_fcs ipd_sub_port_fcs;
+		union cvmx_gmxx_rxx_int_reg gmxx_rxx_int_reg;
+		int interface = INTERFACE(priv->port);
+		int index = INDEX(priv->port);
+
+		/* Enable preamble checking */
+		gmxx_rxx_frm_ctl.u64 =
+		    cvmx_read_csr(CVMX_GMXX_RXX_FRM_CTL(index, interface));
+		gmxx_rxx_frm_ctl.s.pre_chk = 1;
+		cvmx_write_csr(CVMX_GMXX_RXX_FRM_CTL(index, interface),
+			       gmxx_rxx_frm_ctl.u64);
+		/* Enable FCS stripping */
+		ipd_sub_port_fcs.u64 = cvmx_read_csr(CVMX_IPD_SUB_PORT_FCS);
+		ipd_sub_port_fcs.s.port_bit |= 1ull << priv->port;
+		cvmx_write_csr(CVMX_IPD_SUB_PORT_FCS, ipd_sub_port_fcs.u64);
+		/* Clear any error bits */
+		gmxx_rxx_int_reg.u64 =
+		    cvmx_read_csr(CVMX_GMXX_RXX_INT_REG(index, interface));
+		cvmx_write_csr(CVMX_GMXX_RXX_INT_REG(index, interface),
+			       gmxx_rxx_int_reg.u64);
+	}
+
+	link_info = cvmx_helper_link_autoconf(priv->port);
+	priv->link_info = link_info.u64;
+	spin_unlock_irqrestore(&global_register_lock, flags);
+
+	/* Tell Linux */
+	if (link_info.s.link_up) {
+
+		if (!netif_carrier_ok(dev))
+			netif_carrier_on(dev);
+		if (priv->queue != -1)
+			DEBUGPRINT
+			    ("%s: %u Mbps %s duplex, port %2d, queue %2d\n",
+			     dev->name, link_info.s.speed,
+			     (link_info.s.full_duplex) ? "Full" : "Half",
+			     priv->port, priv->queue);
+		else
+			DEBUGPRINT("%s: %u Mbps %s duplex, port %2d, POW\n",
+				   dev->name, link_info.s.speed,
+				   (link_info.s.full_duplex) ? "Full" : "Half",
+				   priv->port);
+	} else {
+
+		if (netif_carrier_ok(dev))
+			netif_carrier_off(dev);
+		DEBUGPRINT("%s: Link down\n", dev->name);
+	}
+}
+
+static irqreturn_t cvm_oct_rgmii_rml_interrupt(int cpl, void *dev_id)
+{
+	union cvmx_npi_rsl_int_blocks rsl_int_blocks;
+	int index;
+	irqreturn_t return_status = IRQ_NONE;
+
+	rsl_int_blocks.u64 = cvmx_read_csr(CVMX_NPI_RSL_INT_BLOCKS);
+
+	/* Check and see if this interrupt was caused by the GMX0 block */
+	if (rsl_int_blocks.s.gmx0) {
+
+		int interface = 0;
+		/* Loop through every port of this interface */
+		for (index = 0;
+		     index < cvmx_helper_ports_on_interface(interface);
+		     index++) {
+
+			/* Read the GMX interrupt status bits */
+			union cvmx_gmxx_rxx_int_reg gmx_rx_int_reg;
+			gmx_rx_int_reg.u64 =
+			    cvmx_read_csr(CVMX_GMXX_RXX_INT_REG
+					  (index, interface));
+			gmx_rx_int_reg.u64 &=
+			    cvmx_read_csr(CVMX_GMXX_RXX_INT_EN
+					  (index, interface));
+			/* Poll the port if inband status changed */
+			if (gmx_rx_int_reg.s.phy_dupx
+			    || gmx_rx_int_reg.s.phy_link
+			    || gmx_rx_int_reg.s.phy_spd) {
+
+				struct net_device *dev =
+				    cvm_oct_device[cvmx_helper_get_ipd_port
+						   (interface, index)];
+				if (dev)
+					cvm_oct_rgmii_poll(dev);
+				gmx_rx_int_reg.u64 = 0;
+				gmx_rx_int_reg.s.phy_dupx = 1;
+				gmx_rx_int_reg.s.phy_link = 1;
+				gmx_rx_int_reg.s.phy_spd = 1;
+				cvmx_write_csr(CVMX_GMXX_RXX_INT_REG
+					       (index, interface),
+					       gmx_rx_int_reg.u64);
+				return_status = IRQ_HANDLED;
+			}
+		}
+	}
+
+	/* Check and see if this interrupt was caused by the GMX1 block */
+	if (rsl_int_blocks.s.gmx1) {
+
+		int interface = 1;
+		/* Loop through every port of this interface */
+		for (index = 0;
+		     index < cvmx_helper_ports_on_interface(interface);
+		     index++) {
+
+			/* Read the GMX interrupt status bits */
+			union cvmx_gmxx_rxx_int_reg gmx_rx_int_reg;
+			gmx_rx_int_reg.u64 =
+			    cvmx_read_csr(CVMX_GMXX_RXX_INT_REG
+					  (index, interface));
+			gmx_rx_int_reg.u64 &=
+			    cvmx_read_csr(CVMX_GMXX_RXX_INT_EN
+					  (index, interface));
+			/* Poll the port if inband status changed */
+			if (gmx_rx_int_reg.s.phy_dupx
+			    || gmx_rx_int_reg.s.phy_link
+			    || gmx_rx_int_reg.s.phy_spd) {
+
+				struct net_device *dev =
+				    cvm_oct_device[cvmx_helper_get_ipd_port
+						   (interface, index)];
+				if (dev)
+					cvm_oct_rgmii_poll(dev);
+				gmx_rx_int_reg.u64 = 0;
+				gmx_rx_int_reg.s.phy_dupx = 1;
+				gmx_rx_int_reg.s.phy_link = 1;
+				gmx_rx_int_reg.s.phy_spd = 1;
+				cvmx_write_csr(CVMX_GMXX_RXX_INT_REG
+					       (index, interface),
+					       gmx_rx_int_reg.u64);
+				return_status = IRQ_HANDLED;
+			}
+		}
+	}
+	return return_status;
+}
+
+static int cvm_oct_rgmii_open(struct net_device *dev)
+{
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int interface = INTERFACE(priv->port);
+	int index = INDEX(priv->port);
+	cvmx_helper_link_info_t link_info;
+
+	gmx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+	gmx_cfg.s.en = 1;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmx_cfg.u64);
+
+	if (!octeon_is_simulation()) {
+		link_info = cvmx_helper_link_get(priv->port);
+		if (!link_info.s.link_up)
+			netif_carrier_off(dev);
+	}
+
+	return 0;
+}
+
+static int cvm_oct_rgmii_stop(struct net_device *dev)
+{
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int interface = INTERFACE(priv->port);
+	int index = INDEX(priv->port);
+
+	gmx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+	gmx_cfg.s.en = 0;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmx_cfg.u64);
+	return 0;
+}
+
+int cvm_oct_rgmii_init(struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int r;
+
+	cvm_oct_common_init(dev);
+	dev->open = cvm_oct_rgmii_open;
+	dev->stop = cvm_oct_rgmii_stop;
+	dev->stop(dev);
+
+	/*
+	 * Due to GMX errata in CN3XXX series chips, it is necessary
+	 * to take the link down immediately whne the PHY changes
+	 * state. In order to do this we call the poll function every
+	 * time the RGMII inband status changes.  This may cause
+	 * problems if the PHY doesn't implement inband status
+	 * properly.
+	 */
+	if (number_rgmii_ports == 0) {
+		r = request_irq(OCTEON_IRQ_RML, cvm_oct_rgmii_rml_interrupt,
+				IRQF_SHARED, "RGMII", &number_rgmii_ports);
+	}
+	number_rgmii_ports++;
+
+	/*
+	 * Only true RGMII ports need to be polled. In GMII mode, port
+	 * 0 is really a RGMII port.
+	 */
+	if (((priv->imode == CVMX_HELPER_INTERFACE_MODE_GMII)
+	     && (priv->port == 0))
+	    || (priv->imode == CVMX_HELPER_INTERFACE_MODE_RGMII)) {
+
+		if (!octeon_is_simulation()) {
+
+			union cvmx_gmxx_rxx_int_en gmx_rx_int_en;
+			int interface = INTERFACE(priv->port);
+			int index = INDEX(priv->port);
+
+			/*
+			 * Enable interrupts on inband status changes
+			 * for this port.
+			 */
+			gmx_rx_int_en.u64 =
+			    cvmx_read_csr(CVMX_GMXX_RXX_INT_EN
+					  (index, interface));
+			gmx_rx_int_en.s.phy_dupx = 1;
+			gmx_rx_int_en.s.phy_link = 1;
+			gmx_rx_int_en.s.phy_spd = 1;
+			cvmx_write_csr(CVMX_GMXX_RXX_INT_EN(index, interface),
+				       gmx_rx_int_en.u64);
+			priv->poll = cvm_oct_rgmii_poll;
+		}
+	}
+
+	return 0;
+}
+
+void cvm_oct_rgmii_uninit(struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	cvm_oct_common_uninit(dev);
+
+	/*
+	 * Only true RGMII ports need to be polled. In GMII mode, port
+	 * 0 is really a RGMII port.
+	 */
+	if (((priv->imode == CVMX_HELPER_INTERFACE_MODE_GMII)
+	     && (priv->port == 0))
+	    || (priv->imode == CVMX_HELPER_INTERFACE_MODE_RGMII)) {
+
+		if (!octeon_is_simulation()) {
+
+			union cvmx_gmxx_rxx_int_en gmx_rx_int_en;
+			int interface = INTERFACE(priv->port);
+			int index = INDEX(priv->port);
+
+			/*
+			 * Disable interrupts on inband status changes
+			 * for this port.
+			 */
+			gmx_rx_int_en.u64 =
+			    cvmx_read_csr(CVMX_GMXX_RXX_INT_EN
+					  (index, interface));
+			gmx_rx_int_en.s.phy_dupx = 0;
+			gmx_rx_int_en.s.phy_link = 0;
+			gmx_rx_int_en.s.phy_spd = 0;
+			cvmx_write_csr(CVMX_GMXX_RXX_INT_EN(index, interface),
+				       gmx_rx_int_en.u64);
+		}
+	}
+
+	/* Remove the interrupt handler when the last port is removed. */
+	number_rgmii_ports--;
+	if (number_rgmii_ports == 0)
+		free_irq(OCTEON_IRQ_RML, &number_rgmii_ports);
+}
diff --git a/drivers/staging/octeon/ethernet-rx.c b/drivers/staging/octeon/ethernet-rx.c
new file mode 100644
index 0000000..1b237b7
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-rx.c
@@ -0,0 +1,505 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/cache.h>
+#include <linux/netdevice.h>
+#include <linux/init.h>
+#include <linux/etherdevice.h>
+#include <linux/ip.h>
+#include <linux/string.h>
+#include <linux/prefetch.h>
+#include <linux/ethtool.h>
+#include <linux/mii.h>
+#include <linux/seq_file.h>
+#include <linux/proc_fs.h>
+#include <net/dst.h>
+#ifdef CONFIG_XFRM
+#include <linux/xfrm.h>
+#include <net/xfrm.h>
+#endif /* CONFIG_XFRM */
+
+#include <asm/atomic.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "ethernet-defines.h"
+#include "octeon-ethernet.h"
+#include "ethernet-mem.h"
+#include "ethernet-util.h"
+
+#include "cvmx-helper.h"
+#include "cvmx-wqe.h"
+#include "cvmx-fau.h"
+#include "cvmx-pow.h"
+#include "cvmx-pip.h"
+#include "cvmx-scratch.h"
+
+#include "cvmx-gmxx-defs.h"
+
+struct cvm_tasklet_wrapper {
+	struct tasklet_struct t;
+};
+
+/*
+ * Aligning the tasklet_struct on cachline boundries seems to decrease
+ * throughput even though in theory it would reduce contantion on the
+ * cache lines containing the locks.
+ */
+
+static struct cvm_tasklet_wrapper cvm_oct_tasklet[NR_CPUS];
+
+/**
+ * Interrupt handler. The interrupt occurs whenever the POW
+ * transitions from 0->1 packets in our group.
+ *
+ * @cpl:
+ * @dev_id:
+ * @regs:
+ * Returns
+ */
+irqreturn_t cvm_oct_do_interrupt(int cpl, void *dev_id)
+{
+	/* Acknowledge the interrupt */
+	if (INTERRUPT_LIMIT)
+		cvmx_write_csr(CVMX_POW_WQ_INT, 1 << pow_receive_group);
+	else
+		cvmx_write_csr(CVMX_POW_WQ_INT, 0x10001 << pow_receive_group);
+	preempt_disable();
+	tasklet_schedule(&cvm_oct_tasklet[smp_processor_id()].t);
+	preempt_enable();
+	return IRQ_HANDLED;
+}
+
+#ifdef CONFIG_NET_POLL_CONTROLLER
+/**
+ * This is called when the kernel needs to manually poll the
+ * device. For Octeon, this is simply calling the interrupt
+ * handler. We actually poll all the devices, not just the
+ * one supplied.
+ *
+ * @dev:    Device to poll. Unused
+ */
+void cvm_oct_poll_controller(struct net_device *dev)
+{
+	preempt_disable();
+	tasklet_schedule(&cvm_oct_tasklet[smp_processor_id()].t);
+	preempt_enable();
+}
+#endif
+
+/**
+ * This is called on receive errors, and determines if the packet
+ * can be dropped early-on in cvm_oct_tasklet_rx().
+ *
+ * @work: Work queue entry pointing to the packet.
+ * Returns Non-zero if the packet can be dropped, zero otherwise.
+ */
+static inline int cvm_oct_check_rcv_error(cvmx_wqe_t *work)
+{
+	if ((work->word2.snoip.err_code == 10) && (work->len <= 64)) {
+		/*
+		 * Ignore length errors on min size packets. Some
+		 * equipment incorrectly pads packets to 64+4FCS
+		 * instead of 60+4FCS.  Note these packets still get
+		 * counted as frame errors.
+		 */
+	} else
+	    if (USE_10MBPS_PREAMBLE_WORKAROUND
+		&& ((work->word2.snoip.err_code == 5)
+		    || (work->word2.snoip.err_code == 7))) {
+
+		/*
+		 * We received a packet with either an alignment error
+		 * or a FCS error. This may be signalling that we are
+		 * running 10Mbps with GMXX_RXX_FRM_CTL[PRE_CHK}
+		 * off. If this is the case we need to parse the
+		 * packet to determine if we can remove a non spec
+		 * preamble and generate a correct packet.
+		 */
+		int interface = cvmx_helper_get_interface_num(work->ipprt);
+		int index = cvmx_helper_get_interface_index_num(work->ipprt);
+		union cvmx_gmxx_rxx_frm_ctl gmxx_rxx_frm_ctl;
+		gmxx_rxx_frm_ctl.u64 =
+		    cvmx_read_csr(CVMX_GMXX_RXX_FRM_CTL(index, interface));
+		if (gmxx_rxx_frm_ctl.s.pre_chk == 0) {
+
+			uint8_t *ptr =
+			    cvmx_phys_to_ptr(work->packet_ptr.s.addr);
+			int i = 0;
+
+			while (i < work->len - 1) {
+				if (*ptr != 0x55)
+					break;
+				ptr++;
+				i++;
+			}
+
+			if (*ptr == 0xd5) {
+				/*
+				   DEBUGPRINT("Port %d received 0xd5 preamble\n", work->ipprt);
+				 */
+				work->packet_ptr.s.addr += i + 1;
+				work->len -= i + 5;
+			} else if ((*ptr & 0xf) == 0xd) {
+				/*
+				   DEBUGPRINT("Port %d received 0x?d preamble\n", work->ipprt);
+				 */
+				work->packet_ptr.s.addr += i;
+				work->len -= i + 4;
+				for (i = 0; i < work->len; i++) {
+					*ptr =
+					    ((*ptr & 0xf0) >> 4) |
+					    ((*(ptr + 1) & 0xf) << 4);
+					ptr++;
+				}
+			} else {
+				DEBUGPRINT("Port %d unknown preamble, packet "
+					   "dropped\n",
+				     work->ipprt);
+				/*
+				   cvmx_helper_dump_packet(work);
+				 */
+				cvm_oct_free_work(work);
+				return 1;
+			}
+		}
+	} else {
+		DEBUGPRINT("Port %d receive error code %d, packet dropped\n",
+			   work->ipprt, work->word2.snoip.err_code);
+		cvm_oct_free_work(work);
+		return 1;
+	}
+
+	return 0;
+}
+
+/**
+ * Tasklet function that is scheduled on a core when an interrupt occurs.
+ *
+ * @unused:
+ */
+void cvm_oct_tasklet_rx(unsigned long unused)
+{
+	const int coreid = cvmx_get_core_num();
+	uint64_t old_group_mask;
+	uint64_t old_scratch;
+	int rx_count = 0;
+	int number_to_free;
+	int num_freed;
+	int packet_not_copied;
+
+	/* Prefetch cvm_oct_device since we know we need it soon */
+	prefetch(cvm_oct_device);
+
+	if (USE_ASYNC_IOBDMA) {
+		/* Save scratch in case userspace is using it */
+		CVMX_SYNCIOBDMA;
+		old_scratch = cvmx_scratch_read64(CVMX_SCR_SCRATCH);
+	}
+
+	/* Only allow work for our group (and preserve priorities) */
+	old_group_mask = cvmx_read_csr(CVMX_POW_PP_GRP_MSKX(coreid));
+	cvmx_write_csr(CVMX_POW_PP_GRP_MSKX(coreid),
+		       (old_group_mask & ~0xFFFFull) | 1 << pow_receive_group);
+
+	if (USE_ASYNC_IOBDMA)
+		cvmx_pow_work_request_async(CVMX_SCR_SCRATCH, CVMX_POW_NO_WAIT);
+
+	while (1) {
+		struct sk_buff *skb = NULL;
+		int skb_in_hw;
+		cvmx_wqe_t *work;
+
+		if (USE_ASYNC_IOBDMA) {
+			work = cvmx_pow_work_response_async(CVMX_SCR_SCRATCH);
+		} else {
+			if ((INTERRUPT_LIMIT == 0)
+			    || likely(rx_count < MAX_RX_PACKETS))
+				work =
+				    cvmx_pow_work_request_sync
+				    (CVMX_POW_NO_WAIT);
+			else
+				work = NULL;
+		}
+		prefetch(work);
+		if (work == NULL)
+			break;
+
+		/*
+		 * Limit each core to processing MAX_RX_PACKETS
+		 * packets without a break.  This way the RX can't
+		 * starve the TX task.
+		 */
+		if (USE_ASYNC_IOBDMA) {
+
+			if ((INTERRUPT_LIMIT == 0)
+			    || likely(rx_count < MAX_RX_PACKETS))
+				cvmx_pow_work_request_async_nocheck
+				    (CVMX_SCR_SCRATCH, CVMX_POW_NO_WAIT);
+			else {
+				cvmx_scratch_write64(CVMX_SCR_SCRATCH,
+						     0x8000000000000000ull);
+				cvmx_pow_tag_sw_null_nocheck();
+			}
+		}
+
+		skb_in_hw = USE_SKBUFFS_IN_HW && work->word2.s.bufs == 1;
+		if (likely(skb_in_hw)) {
+			skb =
+			    *(struct sk_buff
+			      **)(cvm_oct_get_buffer_ptr(work->packet_ptr) -
+				  sizeof(void *));
+			prefetch(&skb->head);
+			prefetch(&skb->len);
+		}
+		prefetch(cvm_oct_device[work->ipprt]);
+
+		rx_count++;
+		/* Immediately throw away all packets with receive errors */
+		if (unlikely(work->word2.snoip.rcv_error)) {
+			if (cvm_oct_check_rcv_error(work))
+				continue;
+		}
+
+		/*
+		 * We can only use the zero copy path if skbuffs are
+		 * in the FPA pool and the packet fits in a single
+		 * buffer.
+		 */
+		if (likely(skb_in_hw)) {
+			/*
+			 * This calculation was changed in case the
+			 * skb header is using a different address
+			 * aliasing type than the buffer. It doesn't
+			 * make any differnece now, but the new one is
+			 * more correct.
+			 */
+			skb->data =
+			    skb->head + work->packet_ptr.s.addr -
+			    cvmx_ptr_to_phys(skb->head);
+			prefetch(skb->data);
+			skb->len = work->len;
+			skb_set_tail_pointer(skb, skb->len);
+			packet_not_copied = 1;
+		} else {
+
+			/*
+			 * We have to copy the packet. First allocate
+			 * an skbuff for it.
+			 */
+			skb = dev_alloc_skb(work->len);
+			if (!skb) {
+				DEBUGPRINT("Port %d failed to allocate "
+					   "skbuff, packet dropped\n",
+				     work->ipprt);
+				cvm_oct_free_work(work);
+				continue;
+			}
+
+			/*
+			 * Check if we've received a packet that was
+			 * entirely stored in the work entry. This is
+			 * untested.
+			 */
+			if (unlikely(work->word2.s.bufs == 0)) {
+				uint8_t *ptr = work->packet_data;
+
+				if (likely(!work->word2.s.not_IP)) {
+					/*
+					 * The beginning of the packet
+					 * moves for IP packets.
+					 */
+					if (work->word2.s.is_v6)
+						ptr += 2;
+					else
+						ptr += 6;
+				}
+				memcpy(skb_put(skb, work->len), ptr, work->len);
+				/* No packet buffers to free */
+			} else {
+				int segments = work->word2.s.bufs;
+				union cvmx_buf_ptr segment_ptr =
+					work->packet_ptr;
+				int len = work->len;
+
+				while (segments--) {
+					union cvmx_buf_ptr next_ptr =
+					    *(union cvmx_buf_ptr *)
+					    cvmx_phys_to_ptr(segment_ptr.s.
+							     addr - 8);
+			/*
+			 * Octeon Errata PKI-100: The segment size is
+			 * wrong. Until it is fixed, calculate the
+			 * segment size based on the packet pool
+			 * buffer size. When it is fixed, the
+			 * following line should be replaced with this
+			 * one: int segment_size =
+			 * segment_ptr.s.size;
+			 */
+					int segment_size =
+					    CVMX_FPA_PACKET_POOL_SIZE -
+					    (segment_ptr.s.addr -
+					     (((segment_ptr.s.addr >> 7) -
+					       segment_ptr.s.back) << 7));
+					/* Don't copy more than what is left
+					   in the packet */
+					if (segment_size > len)
+						segment_size = len;
+					/* Copy the data into the packet */
+					memcpy(skb_put(skb, segment_size),
+					       cvmx_phys_to_ptr(segment_ptr.s.
+								addr),
+					       segment_size);
+					/* Reduce the amount of bytes left
+					   to copy */
+					len -= segment_size;
+					segment_ptr = next_ptr;
+				}
+			}
+			packet_not_copied = 0;
+		}
+
+		if (likely((work->ipprt < TOTAL_NUMBER_OF_PORTS) &&
+			   cvm_oct_device[work->ipprt])) {
+			struct net_device *dev = cvm_oct_device[work->ipprt];
+			struct octeon_ethernet *priv = netdev_priv(dev);
+
+			/* Only accept packets for devices
+			   that are currently up */
+			if (likely(dev->flags & IFF_UP)) {
+				skb->protocol = eth_type_trans(skb, dev);
+				skb->dev = dev;
+
+				if (unlikely
+				    (work->word2.s.not_IP
+				     || work->word2.s.IP_exc
+				     || work->word2.s.L4_error))
+					skb->ip_summed = CHECKSUM_NONE;
+				else
+					skb->ip_summed = CHECKSUM_UNNECESSARY;
+
+				/* Increment RX stats for virtual ports */
+				if (work->ipprt >= CVMX_PIP_NUM_INPUT_PORTS) {
+#ifdef CONFIG_64BIT
+					atomic64_add(1, (atomic64_t *)&priv->stats.rx_packets);
+					atomic64_add(skb->len, (atomic64_t *)&priv->stats.rx_bytes);
+#else
+					atomic_add(1, (atomic_t *)&priv->stats.rx_packets);
+					atomic_add(skb->len, (atomic_t *)&priv->stats.rx_bytes);
+#endif
+				}
+				netif_receive_skb(skb);
+			} else {
+				/*
+				 * Drop any packet received for a
+				 * device that isn't up.
+				 */
+				/*
+				   DEBUGPRINT("%s: Device not up, packet dropped\n",
+				   dev->name);
+				 */
+#ifdef CONFIG_64BIT
+				atomic64_add(1, (atomic64_t *)&priv->stats.rx_dropped);
+#else
+				atomic_add(1, (atomic_t *)&priv->stats.rx_dropped);
+#endif
+				dev_kfree_skb_irq(skb);
+			}
+		} else {
+			/*
+			 * Drop any packet received for a device that
+			 * doesn't exist.
+			 */
+			DEBUGPRINT("Port %d not controlled by Linux, packet "
+				   "dropped\n",
+			     work->ipprt);
+			dev_kfree_skb_irq(skb);
+		}
+		/*
+		 * Check to see if the skbuff and work share the same
+		 * packet buffer.
+		 */
+		if (USE_SKBUFFS_IN_HW && likely(packet_not_copied)) {
+			/*
+			 * This buffer needs to be replaced, increment
+			 * the number of buffers we need to free by
+			 * one.
+			 */
+			cvmx_fau_atomic_add32(FAU_NUM_PACKET_BUFFERS_TO_FREE,
+					      1);
+
+			cvmx_fpa_free(work, CVMX_FPA_WQE_POOL,
+				      DONT_WRITEBACK(1));
+		} else {
+			cvm_oct_free_work(work);
+		}
+	}
+
+	/* Restore the original POW group mask */
+	cvmx_write_csr(CVMX_POW_PP_GRP_MSKX(coreid), old_group_mask);
+	if (USE_ASYNC_IOBDMA) {
+		/* Restore the scratch area */
+		cvmx_scratch_write64(CVMX_SCR_SCRATCH, old_scratch);
+	}
+
+	if (USE_SKBUFFS_IN_HW) {
+		/* Refill the packet buffer pool */
+		number_to_free =
+		    cvmx_fau_fetch_and_add32(FAU_NUM_PACKET_BUFFERS_TO_FREE, 0);
+
+		if (number_to_free > 0) {
+			cvmx_fau_atomic_add32(FAU_NUM_PACKET_BUFFERS_TO_FREE,
+					      -number_to_free);
+			num_freed =
+			    cvm_oct_mem_fill_fpa(CVMX_FPA_PACKET_POOL,
+						 CVMX_FPA_PACKET_POOL_SIZE,
+						 number_to_free);
+			if (num_freed != number_to_free) {
+				cvmx_fau_atomic_add32
+				    (FAU_NUM_PACKET_BUFFERS_TO_FREE,
+				     number_to_free - num_freed);
+			}
+		}
+	}
+}
+
+void cvm_oct_rx_initialize(void)
+{
+	int i;
+	/* Initialize all of the tasklets */
+	for (i = 0; i < NR_CPUS; i++)
+		tasklet_init(&cvm_oct_tasklet[i].t, cvm_oct_tasklet_rx, 0);
+}
+
+void cvm_oct_rx_shutdown(void)
+{
+	int i;
+	/* Shutdown all of the tasklets */
+	for (i = 0; i < NR_CPUS; i++)
+		tasklet_kill(&cvm_oct_tasklet[i].t);
+}
diff --git a/drivers/staging/octeon/ethernet-rx.h b/drivers/staging/octeon/ethernet-rx.h
new file mode 100644
index 0000000..a9b72b8
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-rx.h
@@ -0,0 +1,33 @@
+/*********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+*********************************************************************/
+
+irqreturn_t cvm_oct_do_interrupt(int cpl, void *dev_id);
+void cvm_oct_poll_controller(struct net_device *dev);
+void cvm_oct_tasklet_rx(unsigned long unused);
+
+void cvm_oct_rx_initialize(void);
+void cvm_oct_rx_shutdown(void);
diff --git a/drivers/staging/octeon/ethernet-sgmii.c b/drivers/staging/octeon/ethernet-sgmii.c
new file mode 100644
index 0000000..58fa39c
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-sgmii.c
@@ -0,0 +1,129 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+#include <linux/kernel.h>
+#include <linux/netdevice.h>
+#include <linux/mii.h>
+#include <net/dst.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "ethernet-defines.h"
+#include "octeon-ethernet.h"
+#include "ethernet-util.h"
+#include "ethernet-common.h"
+
+#include "cvmx-helper.h"
+
+#include "cvmx-gmxx-defs.h"
+
+static int cvm_oct_sgmii_open(struct net_device *dev)
+{
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int interface = INTERFACE(priv->port);
+	int index = INDEX(priv->port);
+	cvmx_helper_link_info_t link_info;
+
+	gmx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+	gmx_cfg.s.en = 1;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmx_cfg.u64);
+
+	if (!octeon_is_simulation()) {
+		link_info = cvmx_helper_link_get(priv->port);
+		if (!link_info.s.link_up)
+			netif_carrier_off(dev);
+	}
+
+	return 0;
+}
+
+static int cvm_oct_sgmii_stop(struct net_device *dev)
+{
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int interface = INTERFACE(priv->port);
+	int index = INDEX(priv->port);
+
+	gmx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+	gmx_cfg.s.en = 0;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmx_cfg.u64);
+	return 0;
+}
+
+static void cvm_oct_sgmii_poll(struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	cvmx_helper_link_info_t link_info;
+
+	link_info = cvmx_helper_link_get(priv->port);
+	if (link_info.u64 == priv->link_info)
+		return;
+
+	link_info = cvmx_helper_link_autoconf(priv->port);
+	priv->link_info = link_info.u64;
+
+	/* Tell Linux */
+	if (link_info.s.link_up) {
+
+		if (!netif_carrier_ok(dev))
+			netif_carrier_on(dev);
+		if (priv->queue != -1)
+			DEBUGPRINT
+			    ("%s: %u Mbps %s duplex, port %2d, queue %2d\n",
+			     dev->name, link_info.s.speed,
+			     (link_info.s.full_duplex) ? "Full" : "Half",
+			     priv->port, priv->queue);
+		else
+			DEBUGPRINT("%s: %u Mbps %s duplex, port %2d, POW\n",
+				   dev->name, link_info.s.speed,
+				   (link_info.s.full_duplex) ? "Full" : "Half",
+				   priv->port);
+	} else {
+		if (netif_carrier_ok(dev))
+			netif_carrier_off(dev);
+		DEBUGPRINT("%s: Link down\n", dev->name);
+	}
+}
+
+int cvm_oct_sgmii_init(struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	cvm_oct_common_init(dev);
+	dev->open = cvm_oct_sgmii_open;
+	dev->stop = cvm_oct_sgmii_stop;
+	dev->stop(dev);
+	if (!octeon_is_simulation())
+		priv->poll = cvm_oct_sgmii_poll;
+
+	/* FIXME: Need autoneg logic */
+	return 0;
+}
+
+void cvm_oct_sgmii_uninit(struct net_device *dev)
+{
+	cvm_oct_common_uninit(dev);
+}
diff --git a/drivers/staging/octeon/ethernet-spi.c b/drivers/staging/octeon/ethernet-spi.c
new file mode 100644
index 0000000..e0971bb
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-spi.c
@@ -0,0 +1,323 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+#include <linux/kernel.h>
+#include <linux/netdevice.h>
+#include <linux/mii.h>
+#include <net/dst.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "ethernet-defines.h"
+#include "octeon-ethernet.h"
+#include "ethernet-common.h"
+#include "ethernet-util.h"
+
+#include "cvmx-spi.h"
+
+#include <asm/octeon/cvmx-npi-defs.h>
+#include "cvmx-spxx-defs.h"
+#include "cvmx-stxx-defs.h"
+
+static int number_spi_ports;
+static int need_retrain[2] = { 0, 0 };
+
+static irqreturn_t cvm_oct_spi_rml_interrupt(int cpl, void *dev_id)
+{
+	irqreturn_t return_status = IRQ_NONE;
+	union cvmx_npi_rsl_int_blocks rsl_int_blocks;
+
+	/* Check and see if this interrupt was caused by the GMX block */
+	rsl_int_blocks.u64 = cvmx_read_csr(CVMX_NPI_RSL_INT_BLOCKS);
+	if (rsl_int_blocks.s.spx1) {	/* 19 - SPX1_INT_REG & STX1_INT_REG */
+
+		union cvmx_spxx_int_reg spx_int_reg;
+		union cvmx_stxx_int_reg stx_int_reg;
+
+		spx_int_reg.u64 = cvmx_read_csr(CVMX_SPXX_INT_REG(1));
+		cvmx_write_csr(CVMX_SPXX_INT_REG(1), spx_int_reg.u64);
+		if (!need_retrain[1]) {
+
+			spx_int_reg.u64 &= cvmx_read_csr(CVMX_SPXX_INT_MSK(1));
+			if (spx_int_reg.s.spf)
+				pr_err("SPI1: SRX Spi4 interface down\n");
+			if (spx_int_reg.s.calerr)
+				pr_err("SPI1: SRX Spi4 Calendar table "
+				       "parity error\n");
+			if (spx_int_reg.s.syncerr)
+				pr_err("SPI1: SRX Consecutive Spi4 DIP4 "
+				       "errors have exceeded "
+				       "SPX_ERR_CTL[ERRCNT]\n");
+			if (spx_int_reg.s.diperr)
+				pr_err("SPI1: SRX Spi4 DIP4 error\n");
+			if (spx_int_reg.s.tpaovr)
+				pr_err("SPI1: SRX Selected port has hit "
+				       "TPA overflow\n");
+			if (spx_int_reg.s.rsverr)
+				pr_err("SPI1: SRX Spi4 reserved control "
+				       "word detected\n");
+			if (spx_int_reg.s.drwnng)
+				pr_err("SPI1: SRX Spi4 receive FIFO "
+				       "drowning/overflow\n");
+			if (spx_int_reg.s.clserr)
+				pr_err("SPI1: SRX Spi4 packet closed on "
+				       "non-16B alignment without EOP\n");
+			if (spx_int_reg.s.spiovr)
+				pr_err("SPI1: SRX Spi4 async FIFO overflow\n");
+			if (spx_int_reg.s.abnorm)
+				pr_err("SPI1: SRX Abnormal packet "
+				       "termination (ERR bit)\n");
+			if (spx_int_reg.s.prtnxa)
+				pr_err("SPI1: SRX Port out of range\n");
+		}
+
+		stx_int_reg.u64 = cvmx_read_csr(CVMX_STXX_INT_REG(1));
+		cvmx_write_csr(CVMX_STXX_INT_REG(1), stx_int_reg.u64);
+		if (!need_retrain[1]) {
+
+			stx_int_reg.u64 &= cvmx_read_csr(CVMX_STXX_INT_MSK(1));
+			if (stx_int_reg.s.syncerr)
+				pr_err("SPI1: STX Interface encountered a "
+				       "fatal error\n");
+			if (stx_int_reg.s.frmerr)
+				pr_err("SPI1: STX FRMCNT has exceeded "
+				       "STX_DIP_CNT[MAXFRM]\n");
+			if (stx_int_reg.s.unxfrm)
+				pr_err("SPI1: STX Unexpected framing "
+				       "sequence\n");
+			if (stx_int_reg.s.nosync)
+				pr_err("SPI1: STX ERRCNT has exceeded "
+				       "STX_DIP_CNT[MAXDIP]\n");
+			if (stx_int_reg.s.diperr)
+				pr_err("SPI1: STX DIP2 error on the Spi4 "
+				       "Status channel\n");
+			if (stx_int_reg.s.datovr)
+				pr_err("SPI1: STX Spi4 FIFO overflow error\n");
+			if (stx_int_reg.s.ovrbst)
+				pr_err("SPI1: STX Transmit packet burst "
+				       "too big\n");
+			if (stx_int_reg.s.calpar1)
+				pr_err("SPI1: STX Calendar Table Parity "
+				       "Error Bank1\n");
+			if (stx_int_reg.s.calpar0)
+				pr_err("SPI1: STX Calendar Table Parity "
+				       "Error Bank0\n");
+		}
+
+		cvmx_write_csr(CVMX_SPXX_INT_MSK(1), 0);
+		cvmx_write_csr(CVMX_STXX_INT_MSK(1), 0);
+		need_retrain[1] = 1;
+		return_status = IRQ_HANDLED;
+	}
+
+	if (rsl_int_blocks.s.spx0) {	/* 18 - SPX0_INT_REG & STX0_INT_REG */
+		union cvmx_spxx_int_reg spx_int_reg;
+		union cvmx_stxx_int_reg stx_int_reg;
+
+		spx_int_reg.u64 = cvmx_read_csr(CVMX_SPXX_INT_REG(0));
+		cvmx_write_csr(CVMX_SPXX_INT_REG(0), spx_int_reg.u64);
+		if (!need_retrain[0]) {
+
+			spx_int_reg.u64 &= cvmx_read_csr(CVMX_SPXX_INT_MSK(0));
+			if (spx_int_reg.s.spf)
+				pr_err("SPI0: SRX Spi4 interface down\n");
+			if (spx_int_reg.s.calerr)
+				pr_err("SPI0: SRX Spi4 Calendar table "
+				       "parity error\n");
+			if (spx_int_reg.s.syncerr)
+				pr_err("SPI0: SRX Consecutive Spi4 DIP4 "
+				       "errors have exceeded "
+				       "SPX_ERR_CTL[ERRCNT]\n");
+			if (spx_int_reg.s.diperr)
+				pr_err("SPI0: SRX Spi4 DIP4 error\n");
+			if (spx_int_reg.s.tpaovr)
+				pr_err("SPI0: SRX Selected port has hit "
+				       "TPA overflow\n");
+			if (spx_int_reg.s.rsverr)
+				pr_err("SPI0: SRX Spi4 reserved control "
+				       "word detected\n");
+			if (spx_int_reg.s.drwnng)
+				pr_err("SPI0: SRX Spi4 receive FIFO "
+				       "drowning/overflow\n");
+			if (spx_int_reg.s.clserr)
+				pr_err("SPI0: SRX Spi4 packet closed on "
+				       "non-16B alignment without EOP\n");
+			if (spx_int_reg.s.spiovr)
+				pr_err("SPI0: SRX Spi4 async FIFO overflow\n");
+			if (spx_int_reg.s.abnorm)
+				pr_err("SPI0: SRX Abnormal packet "
+				       "termination (ERR bit)\n");
+			if (spx_int_reg.s.prtnxa)
+				pr_err("SPI0: SRX Port out of range\n");
+		}
+
+		stx_int_reg.u64 = cvmx_read_csr(CVMX_STXX_INT_REG(0));
+		cvmx_write_csr(CVMX_STXX_INT_REG(0), stx_int_reg.u64);
+		if (!need_retrain[0]) {
+
+			stx_int_reg.u64 &= cvmx_read_csr(CVMX_STXX_INT_MSK(0));
+			if (stx_int_reg.s.syncerr)
+				pr_err("SPI0: STX Interface encountered a "
+				       "fatal error\n");
+			if (stx_int_reg.s.frmerr)
+				pr_err("SPI0: STX FRMCNT has exceeded "
+				       "STX_DIP_CNT[MAXFRM]\n");
+			if (stx_int_reg.s.unxfrm)
+				pr_err("SPI0: STX Unexpected framing "
+				       "sequence\n");
+			if (stx_int_reg.s.nosync)
+				pr_err("SPI0: STX ERRCNT has exceeded "
+				       "STX_DIP_CNT[MAXDIP]\n");
+			if (stx_int_reg.s.diperr)
+				pr_err("SPI0: STX DIP2 error on the Spi4 "
+				       "Status channel\n");
+			if (stx_int_reg.s.datovr)
+				pr_err("SPI0: STX Spi4 FIFO overflow error\n");
+			if (stx_int_reg.s.ovrbst)
+				pr_err("SPI0: STX Transmit packet burst "
+				       "too big\n");
+			if (stx_int_reg.s.calpar1)
+				pr_err("SPI0: STX Calendar Table Parity "
+				       "Error Bank1\n");
+			if (stx_int_reg.s.calpar0)
+				pr_err("SPI0: STX Calendar Table Parity "
+				       "Error Bank0\n");
+		}
+
+		cvmx_write_csr(CVMX_SPXX_INT_MSK(0), 0);
+		cvmx_write_csr(CVMX_STXX_INT_MSK(0), 0);
+		need_retrain[0] = 1;
+		return_status = IRQ_HANDLED;
+	}
+
+	return return_status;
+}
+
+static void cvm_oct_spi_enable_error_reporting(int interface)
+{
+	union cvmx_spxx_int_msk spxx_int_msk;
+	union cvmx_stxx_int_msk stxx_int_msk;
+
+	spxx_int_msk.u64 = cvmx_read_csr(CVMX_SPXX_INT_MSK(interface));
+	spxx_int_msk.s.calerr = 1;
+	spxx_int_msk.s.syncerr = 1;
+	spxx_int_msk.s.diperr = 1;
+	spxx_int_msk.s.tpaovr = 1;
+	spxx_int_msk.s.rsverr = 1;
+	spxx_int_msk.s.drwnng = 1;
+	spxx_int_msk.s.clserr = 1;
+	spxx_int_msk.s.spiovr = 1;
+	spxx_int_msk.s.abnorm = 1;
+	spxx_int_msk.s.prtnxa = 1;
+	cvmx_write_csr(CVMX_SPXX_INT_MSK(interface), spxx_int_msk.u64);
+
+	stxx_int_msk.u64 = cvmx_read_csr(CVMX_STXX_INT_MSK(interface));
+	stxx_int_msk.s.frmerr = 1;
+	stxx_int_msk.s.unxfrm = 1;
+	stxx_int_msk.s.nosync = 1;
+	stxx_int_msk.s.diperr = 1;
+	stxx_int_msk.s.datovr = 1;
+	stxx_int_msk.s.ovrbst = 1;
+	stxx_int_msk.s.calpar1 = 1;
+	stxx_int_msk.s.calpar0 = 1;
+	cvmx_write_csr(CVMX_STXX_INT_MSK(interface), stxx_int_msk.u64);
+}
+
+static void cvm_oct_spi_poll(struct net_device *dev)
+{
+	static int spi4000_port;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int interface;
+
+	for (interface = 0; interface < 2; interface++) {
+
+		if ((priv->port == interface * 16) && need_retrain[interface]) {
+
+			if (cvmx_spi_restart_interface
+			    (interface, CVMX_SPI_MODE_DUPLEX, 10) == 0) {
+				need_retrain[interface] = 0;
+				cvm_oct_spi_enable_error_reporting(interface);
+			}
+		}
+
+		/*
+		 * The SPI4000 TWSI interface is very slow. In order
+		 * not to bring the system to a crawl, we only poll a
+		 * single port every second. This means negotiation
+		 * speed changes take up to 10 seconds, but at least
+		 * we don't waste absurd amounts of time waiting for
+		 * TWSI.
+		 */
+		if (priv->port == spi4000_port) {
+			/*
+			 * This function does nothing if it is called on an
+			 * interface without a SPI4000.
+			 */
+			cvmx_spi4000_check_speed(interface, priv->port);
+			/*
+			 * Normal ordering increments. By decrementing
+			 * we only match once per iteration.
+			 */
+			spi4000_port--;
+			if (spi4000_port < 0)
+				spi4000_port = 10;
+		}
+	}
+}
+
+int cvm_oct_spi_init(struct net_device *dev)
+{
+	int r;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+
+	if (number_spi_ports == 0) {
+		r = request_irq(OCTEON_IRQ_RML, cvm_oct_spi_rml_interrupt,
+				IRQF_SHARED, "SPI", &number_spi_ports);
+	}
+	number_spi_ports++;
+
+	if ((priv->port == 0) || (priv->port == 16)) {
+		cvm_oct_spi_enable_error_reporting(INTERFACE(priv->port));
+		priv->poll = cvm_oct_spi_poll;
+	}
+	cvm_oct_common_init(dev);
+	return 0;
+}
+
+void cvm_oct_spi_uninit(struct net_device *dev)
+{
+	int interface;
+
+	cvm_oct_common_uninit(dev);
+	number_spi_ports--;
+	if (number_spi_ports == 0) {
+		for (interface = 0; interface < 2; interface++) {
+			cvmx_write_csr(CVMX_SPXX_INT_MSK(interface), 0);
+			cvmx_write_csr(CVMX_STXX_INT_MSK(interface), 0);
+		}
+		free_irq(8 + 46, &number_spi_ports);
+	}
+}
diff --git a/drivers/staging/octeon/ethernet-tx.c b/drivers/staging/octeon/ethernet-tx.c
new file mode 100644
index 0000000..77b7122
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-tx.c
@@ -0,0 +1,634 @@
+/*********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+*********************************************************************/
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/netdevice.h>
+#include <linux/init.h>
+#include <linux/etherdevice.h>
+#include <linux/ip.h>
+#include <linux/string.h>
+#include <linux/ethtool.h>
+#include <linux/mii.h>
+#include <linux/seq_file.h>
+#include <linux/proc_fs.h>
+#include <net/dst.h>
+#ifdef CONFIG_XFRM
+#include <linux/xfrm.h>
+#include <net/xfrm.h>
+#endif /* CONFIG_XFRM */
+
+#include <asm/atomic.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "ethernet-defines.h"
+#include "octeon-ethernet.h"
+#include "ethernet-util.h"
+
+#include "cvmx-wqe.h"
+#include "cvmx-fau.h"
+#include "cvmx-pko.h"
+#include "cvmx-helper.h"
+
+#include "cvmx-gmxx-defs.h"
+
+/*
+ * You can define GET_SKBUFF_QOS() to override how the skbuff output
+ * function determines which output queue is used. The default
+ * implementation always uses the base queue for the port. If, for
+ * example, you wanted to use the skb->priority fieid, define
+ * GET_SKBUFF_QOS as: #define GET_SKBUFF_QOS(skb) ((skb)->priority)
+ */
+#ifndef GET_SKBUFF_QOS
+#define GET_SKBUFF_QOS(skb) 0
+#endif
+
+/**
+ * Packet transmit
+ *
+ * @skb:    Packet to send
+ * @dev:    Device info structure
+ * Returns Always returns zero
+ */
+int cvm_oct_xmit(struct sk_buff *skb, struct net_device *dev)
+{
+	cvmx_pko_command_word0_t pko_command;
+	union cvmx_buf_ptr hw_buffer;
+	uint64_t old_scratch;
+	uint64_t old_scratch2;
+	int dropped;
+	int qos;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int32_t in_use;
+	int32_t buffers_to_free;
+#if REUSE_SKBUFFS_WITHOUT_FREE
+	unsigned char *fpa_head;
+#endif
+
+	/*
+	 * Prefetch the private data structure.  It is larger that one
+	 * cache line.
+	 */
+	prefetch(priv);
+
+	/* Start off assuming no drop */
+	dropped = 0;
+
+	/*
+	 * The check on CVMX_PKO_QUEUES_PER_PORT_* is designed to
+	 * completely remove "qos" in the event neither interface
+	 * supports multiple queues per port.
+	 */
+	if ((CVMX_PKO_QUEUES_PER_PORT_INTERFACE0 > 1) ||
+	    (CVMX_PKO_QUEUES_PER_PORT_INTERFACE1 > 1)) {
+		qos = GET_SKBUFF_QOS(skb);
+		if (qos <= 0)
+			qos = 0;
+		else if (qos >= cvmx_pko_get_num_queues(priv->port))
+			qos = 0;
+	} else
+		qos = 0;
+
+	if (USE_ASYNC_IOBDMA) {
+		/* Save scratch in case userspace is using it */
+		CVMX_SYNCIOBDMA;
+		old_scratch = cvmx_scratch_read64(CVMX_SCR_SCRATCH);
+		old_scratch2 = cvmx_scratch_read64(CVMX_SCR_SCRATCH + 8);
+
+		/*
+		 * Assume we're going to be able t osend this
+		 * packet. Fetch and increment the number of pending
+		 * packets for output.
+		 */
+		cvmx_fau_async_fetch_and_add32(CVMX_SCR_SCRATCH + 8,
+					       FAU_NUM_PACKET_BUFFERS_TO_FREE,
+					       0);
+		cvmx_fau_async_fetch_and_add32(CVMX_SCR_SCRATCH,
+					       priv->fau + qos * 4, 1);
+	}
+
+	/*
+	 * The CN3XXX series of parts has an errata (GMX-401) which
+	 * causes the GMX block to hang if a collision occurs towards
+	 * the end of a <68 byte packet. As a workaround for this, we
+	 * pad packets to be 68 bytes whenever we are in half duplex
+	 * mode. We don't handle the case of having a small packet but
+	 * no room to add the padding.  The kernel should always give
+	 * us at least a cache line
+	 */
+	if ((skb->len < 64) && OCTEON_IS_MODEL(OCTEON_CN3XXX)) {
+		union cvmx_gmxx_prtx_cfg gmx_prt_cfg;
+		int interface = INTERFACE(priv->port);
+		int index = INDEX(priv->port);
+
+		if (interface < 2) {
+			/* We only need to pad packet in half duplex mode */
+			gmx_prt_cfg.u64 =
+			    cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+			if (gmx_prt_cfg.s.duplex == 0) {
+				int add_bytes = 64 - skb->len;
+				if ((skb_tail_pointer(skb) + add_bytes) <=
+				    skb_end_pointer(skb))
+					memset(__skb_put(skb, add_bytes), 0,
+					       add_bytes);
+			}
+		}
+	}
+
+	/* Build the PKO buffer pointer */
+	hw_buffer.u64 = 0;
+	hw_buffer.s.addr = cvmx_ptr_to_phys(skb->data);
+	hw_buffer.s.pool = 0;
+	hw_buffer.s.size =
+	    (unsigned long)skb_end_pointer(skb) - (unsigned long)skb->head;
+
+	/* Build the PKO command */
+	pko_command.u64 = 0;
+	pko_command.s.n2 = 1;	/* Don't pollute L2 with the outgoing packet */
+	pko_command.s.segs = 1;
+	pko_command.s.total_bytes = skb->len;
+	pko_command.s.size0 = CVMX_FAU_OP_SIZE_32;
+	pko_command.s.subone0 = 1;
+
+	pko_command.s.dontfree = 1;
+	pko_command.s.reg0 = priv->fau + qos * 4;
+	/*
+	 * See if we can put this skb in the FPA pool. Any strange
+	 * behavior from the Linux networking stack will most likely
+	 * be caused by a bug in the following code. If some field is
+	 * in use by the network stack and get carried over when a
+	 * buffer is reused, bad thing may happen.  If in doubt and
+	 * you dont need the absolute best performance, disable the
+	 * define REUSE_SKBUFFS_WITHOUT_FREE. The reuse of buffers has
+	 * shown a 25% increase in performance under some loads.
+	 */
+#if REUSE_SKBUFFS_WITHOUT_FREE
+	fpa_head = skb->head + 128 - ((unsigned long)skb->head & 0x7f);
+	if (unlikely(skb->data < fpa_head)) {
+		/*
+		 * printk("TX buffer beginning can't meet FPA
+		 * alignment constraints\n");
+		 */
+		goto dont_put_skbuff_in_hw;
+	}
+	if (unlikely
+	    ((skb_end_pointer(skb) - fpa_head) < CVMX_FPA_PACKET_POOL_SIZE)) {
+		/*
+		   printk("TX buffer isn't large enough for the FPA\n");
+		 */
+		goto dont_put_skbuff_in_hw;
+	}
+	if (unlikely(skb_shared(skb))) {
+		/*
+		   printk("TX buffer sharing data with someone else\n");
+		 */
+		goto dont_put_skbuff_in_hw;
+	}
+	if (unlikely(skb_cloned(skb))) {
+		/*
+		   printk("TX buffer has been cloned\n");
+		 */
+		goto dont_put_skbuff_in_hw;
+	}
+	if (unlikely(skb_header_cloned(skb))) {
+		/*
+		   printk("TX buffer header has been cloned\n");
+		 */
+		goto dont_put_skbuff_in_hw;
+	}
+	if (unlikely(skb->destructor)) {
+		/*
+		   printk("TX buffer has a destructor\n");
+		 */
+		goto dont_put_skbuff_in_hw;
+	}
+	if (unlikely(skb_shinfo(skb)->nr_frags)) {
+		/*
+		   printk("TX buffer has fragments\n");
+		 */
+		goto dont_put_skbuff_in_hw;
+	}
+	if (unlikely
+	    (skb->truesize !=
+	     sizeof(*skb) + skb_end_pointer(skb) - skb->head)) {
+		/*
+		   printk("TX buffer truesize has been changed\n");
+		 */
+		goto dont_put_skbuff_in_hw;
+	}
+
+	/*
+	 * We can use this buffer in the FPA.  We don't need the FAU
+	 * update anymore
+	 */
+	pko_command.s.reg0 = 0;
+	pko_command.s.dontfree = 0;
+
+	hw_buffer.s.back = (skb->data - fpa_head) >> 7;
+	*(struct sk_buff **)(fpa_head - sizeof(void *)) = skb;
+
+	/*
+	 * The skbuff will be reused without ever being freed. We must
+	 * cleanup a bunch of Linux stuff.
+	 */
+	dst_release(skb->dst);
+	skb->dst = NULL;
+#ifdef CONFIG_XFRM
+	secpath_put(skb->sp);
+	skb->sp = NULL;
+#endif
+	nf_reset(skb);
+
+#ifdef CONFIG_NET_SCHED
+	skb->tc_index = 0;
+#ifdef CONFIG_NET_CLS_ACT
+	skb->tc_verd = 0;
+#endif /* CONFIG_NET_CLS_ACT */
+#endif /* CONFIG_NET_SCHED */
+
+dont_put_skbuff_in_hw:
+#endif /* REUSE_SKBUFFS_WITHOUT_FREE */
+
+	/* Check if we can use the hardware checksumming */
+	if (USE_HW_TCPUDP_CHECKSUM && (skb->protocol == htons(ETH_P_IP)) &&
+	    (ip_hdr(skb)->version == 4) && (ip_hdr(skb)->ihl == 5) &&
+	    ((ip_hdr(skb)->frag_off == 0) || (ip_hdr(skb)->frag_off == 1 << 14))
+	    && ((ip_hdr(skb)->protocol == IP_PROTOCOL_TCP)
+		|| (ip_hdr(skb)->protocol == IP_PROTOCOL_UDP))) {
+		/* Use hardware checksum calc */
+		pko_command.s.ipoffp1 = sizeof(struct ethhdr) + 1;
+	}
+
+	if (USE_ASYNC_IOBDMA) {
+		/* Get the number of skbuffs in use by the hardware */
+		CVMX_SYNCIOBDMA;
+		in_use = cvmx_scratch_read64(CVMX_SCR_SCRATCH);
+		buffers_to_free = cvmx_scratch_read64(CVMX_SCR_SCRATCH + 8);
+	} else {
+		/* Get the number of skbuffs in use by the hardware */
+		in_use = cvmx_fau_fetch_and_add32(priv->fau + qos * 4, 1);
+		buffers_to_free =
+		    cvmx_fau_fetch_and_add32(FAU_NUM_PACKET_BUFFERS_TO_FREE, 0);
+	}
+
+	/*
+	 * If we're sending faster than the receive can free them then
+	 * don't do the HW free.
+	 */
+	if ((buffers_to_free < -100) && !pko_command.s.dontfree) {
+		pko_command.s.dontfree = 1;
+		pko_command.s.reg0 = priv->fau + qos * 4;
+	}
+
+	cvmx_pko_send_packet_prepare(priv->port, priv->queue + qos,
+				     CVMX_PKO_LOCK_CMD_QUEUE);
+
+	/* Drop this packet if we have too many already queued to the HW */
+	if (unlikely
+	    (skb_queue_len(&priv->tx_free_list[qos]) >= MAX_OUT_QUEUE_DEPTH)) {
+		/*
+		   DEBUGPRINT("%s: Tx dropped. Too many queued\n", dev->name);
+		 */
+		dropped = 1;
+	}
+	/* Send the packet to the output queue */
+	else if (unlikely
+		 (cvmx_pko_send_packet_finish
+		  (priv->port, priv->queue + qos, pko_command, hw_buffer,
+		   CVMX_PKO_LOCK_CMD_QUEUE))) {
+		DEBUGPRINT("%s: Failed to send the packet\n", dev->name);
+		dropped = 1;
+	}
+
+	if (USE_ASYNC_IOBDMA) {
+		/* Restore the scratch area */
+		cvmx_scratch_write64(CVMX_SCR_SCRATCH, old_scratch);
+		cvmx_scratch_write64(CVMX_SCR_SCRATCH + 8, old_scratch2);
+	}
+
+	if (unlikely(dropped)) {
+		dev_kfree_skb_any(skb);
+		cvmx_fau_atomic_add32(priv->fau + qos * 4, -1);
+		priv->stats.tx_dropped++;
+	} else {
+		if (USE_SKBUFFS_IN_HW) {
+			/* Put this packet on the queue to be freed later */
+			if (pko_command.s.dontfree)
+				skb_queue_tail(&priv->tx_free_list[qos], skb);
+			else {
+				cvmx_fau_atomic_add32
+				    (FAU_NUM_PACKET_BUFFERS_TO_FREE, -1);
+				cvmx_fau_atomic_add32(priv->fau + qos * 4, -1);
+			}
+		} else {
+			/* Put this packet on the queue to be freed later */
+			skb_queue_tail(&priv->tx_free_list[qos], skb);
+		}
+	}
+
+	/* Free skbuffs not in use by the hardware, possibly two at a time */
+	if (skb_queue_len(&priv->tx_free_list[qos]) > in_use) {
+		spin_lock(&priv->tx_free_list[qos].lock);
+		/*
+		 * Check again now that we have the lock. It might
+		 * have changed.
+		 */
+		if (skb_queue_len(&priv->tx_free_list[qos]) > in_use)
+			dev_kfree_skb(__skb_dequeue(&priv->tx_free_list[qos]));
+		if (skb_queue_len(&priv->tx_free_list[qos]) > in_use)
+			dev_kfree_skb(__skb_dequeue(&priv->tx_free_list[qos]));
+		spin_unlock(&priv->tx_free_list[qos].lock);
+	}
+
+	return 0;
+}
+
+/**
+ * Packet transmit to the POW
+ *
+ * @skb:    Packet to send
+ * @dev:    Device info structure
+ * Returns Always returns zero
+ */
+int cvm_oct_xmit_pow(struct sk_buff *skb, struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	void *packet_buffer;
+	void *copy_location;
+
+	/* Get a work queue entry */
+	cvmx_wqe_t *work = cvmx_fpa_alloc(CVMX_FPA_WQE_POOL);
+	if (unlikely(work == NULL)) {
+		DEBUGPRINT("%s: Failed to allocate a work queue entry\n",
+			   dev->name);
+		priv->stats.tx_dropped++;
+		dev_kfree_skb(skb);
+		return 0;
+	}
+
+	/* Get a packet buffer */
+	packet_buffer = cvmx_fpa_alloc(CVMX_FPA_PACKET_POOL);
+	if (unlikely(packet_buffer == NULL)) {
+		DEBUGPRINT("%s: Failed to allocate a packet buffer\n",
+			   dev->name);
+		cvmx_fpa_free(work, CVMX_FPA_WQE_POOL, DONT_WRITEBACK(1));
+		priv->stats.tx_dropped++;
+		dev_kfree_skb(skb);
+		return 0;
+	}
+
+	/*
+	 * Calculate where we need to copy the data to. We need to
+	 * leave 8 bytes for a next pointer (unused). We also need to
+	 * include any configure skip. Then we need to align the IP
+	 * packet src and dest into the same 64bit word. The below
+	 * calculation may add a little extra, but that doesn't
+	 * hurt.
+	 */
+	copy_location = packet_buffer + sizeof(uint64_t);
+	copy_location += ((CVMX_HELPER_FIRST_MBUFF_SKIP + 7) & 0xfff8) + 6;
+
+	/*
+	 * We have to copy the packet since whoever processes this
+	 * packet will free it to a hardware pool. We can't use the
+	 * trick of counting outstanding packets like in
+	 * cvm_oct_xmit.
+	 */
+	memcpy(copy_location, skb->data, skb->len);
+
+	/*
+	 * Fill in some of the work queue fields. We may need to add
+	 * more if the software at the other end needs them.
+	 */
+	work->hw_chksum = skb->csum;
+	work->len = skb->len;
+	work->ipprt = priv->port;
+	work->qos = priv->port & 0x7;
+	work->grp = pow_send_group;
+	work->tag_type = CVMX_HELPER_INPUT_TAG_TYPE;
+	work->tag = pow_send_group;	/* FIXME */
+	/* Default to zero. Sets of zero later are commented out */
+	work->word2.u64 = 0;
+	work->word2.s.bufs = 1;
+	work->packet_ptr.u64 = 0;
+	work->packet_ptr.s.addr = cvmx_ptr_to_phys(copy_location);
+	work->packet_ptr.s.pool = CVMX_FPA_PACKET_POOL;
+	work->packet_ptr.s.size = CVMX_FPA_PACKET_POOL_SIZE;
+	work->packet_ptr.s.back = (copy_location - packet_buffer) >> 7;
+
+	if (skb->protocol == htons(ETH_P_IP)) {
+		work->word2.s.ip_offset = 14;
+#if 0
+		work->word2.s.vlan_valid = 0;	/* FIXME */
+		work->word2.s.vlan_cfi = 0;	/* FIXME */
+		work->word2.s.vlan_id = 0;	/* FIXME */
+		work->word2.s.dec_ipcomp = 0;	/* FIXME */
+#endif
+		work->word2.s.tcp_or_udp =
+		    (ip_hdr(skb)->protocol == IP_PROTOCOL_TCP)
+		    || (ip_hdr(skb)->protocol == IP_PROTOCOL_UDP);
+#if 0
+		/* FIXME */
+		work->word2.s.dec_ipsec = 0;
+		/* We only support IPv4 right now */
+		work->word2.s.is_v6 = 0;
+		/* Hardware would set to zero */
+		work->word2.s.software = 0;
+		/* No error, packet is internal */
+		work->word2.s.L4_error = 0;
+#endif
+		work->word2.s.is_frag = !((ip_hdr(skb)->frag_off == 0)
+					  || (ip_hdr(skb)->frag_off ==
+					      1 << 14));
+#if 0
+		/* Assume Linux is sending a good packet */
+		work->word2.s.IP_exc = 0;
+#endif
+		work->word2.s.is_bcast = (skb->pkt_type == PACKET_BROADCAST);
+		work->word2.s.is_mcast = (skb->pkt_type == PACKET_MULTICAST);
+#if 0
+		/* This is an IP packet */
+		work->word2.s.not_IP = 0;
+		/* No error, packet is internal */
+		work->word2.s.rcv_error = 0;
+		/* No error, packet is internal */
+		work->word2.s.err_code = 0;
+#endif
+
+		/*
+		 * When copying the data, include 4 bytes of the
+		 * ethernet header to align the same way hardware
+		 * does.
+		 */
+		memcpy(work->packet_data, skb->data + 10,
+		       sizeof(work->packet_data));
+	} else {
+#if 0
+		work->word2.snoip.vlan_valid = 0;	/* FIXME */
+		work->word2.snoip.vlan_cfi = 0;	/* FIXME */
+		work->word2.snoip.vlan_id = 0;	/* FIXME */
+		work->word2.snoip.software = 0;	/* Hardware would set to zero */
+#endif
+		work->word2.snoip.is_rarp = skb->protocol == htons(ETH_P_RARP);
+		work->word2.snoip.is_arp = skb->protocol == htons(ETH_P_ARP);
+		work->word2.snoip.is_bcast =
+		    (skb->pkt_type == PACKET_BROADCAST);
+		work->word2.snoip.is_mcast =
+		    (skb->pkt_type == PACKET_MULTICAST);
+		work->word2.snoip.not_IP = 1;	/* IP was done up above */
+#if 0
+		/* No error, packet is internal */
+		work->word2.snoip.rcv_error = 0;
+		/* No error, packet is internal */
+		work->word2.snoip.err_code = 0;
+#endif
+		memcpy(work->packet_data, skb->data, sizeof(work->packet_data));
+	}
+
+	/* Submit the packet to the POW */
+	cvmx_pow_work_submit(work, work->tag, work->tag_type, work->qos,
+			     work->grp);
+	priv->stats.tx_packets++;
+	priv->stats.tx_bytes += skb->len;
+	dev_kfree_skb(skb);
+	return 0;
+}
+
+/**
+ * Transmit a work queue entry out of the ethernet port. Both
+ * the work queue entry and the packet data can optionally be
+ * freed. The work will be freed on error as well.
+ *
+ * @dev:     Device to transmit out.
+ * @work_queue_entry:
+ *                Work queue entry to send
+ * @do_free: True if the work queue entry and packet data should be
+ *                freed. If false, neither will be freed.
+ * @qos:     Index into the queues for this port to transmit on. This
+ *                is used to implement QoS if their are multiple queues per
+ *                port. This parameter must be between 0 and the number of
+ *                queues per port minus 1. Values outside of this range will
+ *                be change to zero.
+ *
+ * Returns Zero on success, negative on failure.
+ */
+int cvm_oct_transmit_qos(struct net_device *dev, void *work_queue_entry,
+			 int do_free, int qos)
+{
+	unsigned long flags;
+	union cvmx_buf_ptr hw_buffer;
+	cvmx_pko_command_word0_t pko_command;
+	int dropped;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	cvmx_wqe_t *work = work_queue_entry;
+
+	if (!(dev->flags & IFF_UP)) {
+		DEBUGPRINT("%s: Device not up\n", dev->name);
+		if (do_free)
+			cvm_oct_free_work(work);
+		return -1;
+	}
+
+	/* The check on CVMX_PKO_QUEUES_PER_PORT_* is designed to completely
+	   remove "qos" in the event neither interface supports
+	   multiple queues per port */
+	if ((CVMX_PKO_QUEUES_PER_PORT_INTERFACE0 > 1) ||
+	    (CVMX_PKO_QUEUES_PER_PORT_INTERFACE1 > 1)) {
+		if (qos <= 0)
+			qos = 0;
+		else if (qos >= cvmx_pko_get_num_queues(priv->port))
+			qos = 0;
+	} else
+		qos = 0;
+
+	/* Start off assuming no drop */
+	dropped = 0;
+
+	local_irq_save(flags);
+	cvmx_pko_send_packet_prepare(priv->port, priv->queue + qos,
+				     CVMX_PKO_LOCK_CMD_QUEUE);
+
+	/* Build the PKO buffer pointer */
+	hw_buffer.u64 = 0;
+	hw_buffer.s.addr = work->packet_ptr.s.addr;
+	hw_buffer.s.pool = CVMX_FPA_PACKET_POOL;
+	hw_buffer.s.size = CVMX_FPA_PACKET_POOL_SIZE;
+	hw_buffer.s.back = work->packet_ptr.s.back;
+
+	/* Build the PKO command */
+	pko_command.u64 = 0;
+	pko_command.s.n2 = 1;	/* Don't pollute L2 with the outgoing packet */
+	pko_command.s.dontfree = !do_free;
+	pko_command.s.segs = work->word2.s.bufs;
+	pko_command.s.total_bytes = work->len;
+
+	/* Check if we can use the hardware checksumming */
+	if (unlikely(work->word2.s.not_IP || work->word2.s.IP_exc))
+		pko_command.s.ipoffp1 = 0;
+	else
+		pko_command.s.ipoffp1 = sizeof(struct ethhdr) + 1;
+
+	/* Send the packet to the output queue */
+	if (unlikely
+	    (cvmx_pko_send_packet_finish
+	     (priv->port, priv->queue + qos, pko_command, hw_buffer,
+	      CVMX_PKO_LOCK_CMD_QUEUE))) {
+		DEBUGPRINT("%s: Failed to send the packet\n", dev->name);
+		dropped = -1;
+	}
+	local_irq_restore(flags);
+
+	if (unlikely(dropped)) {
+		if (do_free)
+			cvm_oct_free_work(work);
+		priv->stats.tx_dropped++;
+	} else if (do_free)
+		cvmx_fpa_free(work, CVMX_FPA_WQE_POOL, DONT_WRITEBACK(1));
+
+	return dropped;
+}
+EXPORT_SYMBOL(cvm_oct_transmit_qos);
+
+/**
+ * This function frees all skb that are currenty queued for TX.
+ *
+ * @dev:    Device being shutdown
+ */
+void cvm_oct_tx_shutdown(struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	unsigned long flags;
+	int qos;
+
+	for (qos = 0; qos < 16; qos++) {
+		spin_lock_irqsave(&priv->tx_free_list[qos].lock, flags);
+		while (skb_queue_len(&priv->tx_free_list[qos]))
+			dev_kfree_skb_any(__skb_dequeue
+					  (&priv->tx_free_list[qos]));
+		spin_unlock_irqrestore(&priv->tx_free_list[qos].lock, flags);
+	}
+}
diff --git a/drivers/staging/octeon/ethernet-tx.h b/drivers/staging/octeon/ethernet-tx.h
new file mode 100644
index 0000000..5106236
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-tx.h
@@ -0,0 +1,32 @@
+/*********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+*********************************************************************/
+
+int cvm_oct_xmit(struct sk_buff *skb, struct net_device *dev);
+int cvm_oct_xmit_pow(struct sk_buff *skb, struct net_device *dev);
+int cvm_oct_transmit_qos(struct net_device *dev, void *work_queue_entry,
+			 int do_free, int qos);
+void cvm_oct_tx_shutdown(struct net_device *dev);
diff --git a/drivers/staging/octeon/ethernet-util.h b/drivers/staging/octeon/ethernet-util.h
new file mode 100644
index 0000000..37b6659
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-util.h
@@ -0,0 +1,81 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+*********************************************************************/
+
+#define DEBUGPRINT(format, ...) do { if (printk_ratelimit()) 		\
+					printk(format, ##__VA_ARGS__);	\
+				} while (0)
+
+/**
+ * Given a packet data address, return a pointer to the
+ * beginning of the packet buffer.
+ *
+ * @packet_ptr: Packet data hardware address
+ * Returns Packet buffer pointer
+ */
+static inline void *cvm_oct_get_buffer_ptr(union cvmx_buf_ptr packet_ptr)
+{
+	return cvmx_phys_to_ptr(((packet_ptr.s.addr >> 7) - packet_ptr.s.back)
+				<< 7);
+}
+
+/**
+ * Given an IPD/PKO port number, return the logical interface it is
+ * on.
+ *
+ * @ipd_port: Port to check
+ *
+ * Returns Logical interface
+ */
+static inline int INTERFACE(int ipd_port)
+{
+	if (ipd_port < 32)	/* Interface 0 or 1 for RGMII,GMII,SPI, etc */
+		return ipd_port >> 4;
+	else if (ipd_port < 36)	/* Interface 2 for NPI */
+		return 2;
+	else if (ipd_port < 40)	/* Interface 3 for loopback */
+		return 3;
+	else if (ipd_port == 40)	/* Non existant interface for POW0 */
+		return 4;
+	else
+		panic("Illegal ipd_port %d passed to INTERFACE\n", ipd_port);
+}
+
+/**
+ * Given an IPD/PKO port number, return the port's index on a
+ * logical interface.
+ *
+ * @ipd_port: Port to check
+ *
+ * Returns Index into interface port list
+ */
+static inline int INDEX(int ipd_port)
+{
+	if (ipd_port < 32)
+		return ipd_port & 15;
+	else
+		return ipd_port & 3;
+}
diff --git a/drivers/staging/octeon/ethernet-xaui.c b/drivers/staging/octeon/ethernet-xaui.c
new file mode 100644
index 0000000..f08eb32
--- /dev/null
+++ b/drivers/staging/octeon/ethernet-xaui.c
@@ -0,0 +1,127 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+#include <linux/kernel.h>
+#include <linux/netdevice.h>
+#include <linux/mii.h>
+#include <net/dst.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "ethernet-defines.h"
+#include "octeon-ethernet.h"
+#include "ethernet-common.h"
+#include "ethernet-util.h"
+
+#include "cvmx-helper.h"
+
+#include "cvmx-gmxx-defs.h"
+
+static int cvm_oct_xaui_open(struct net_device *dev)
+{
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int interface = INTERFACE(priv->port);
+	int index = INDEX(priv->port);
+	cvmx_helper_link_info_t link_info;
+
+	gmx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+	gmx_cfg.s.en = 1;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmx_cfg.u64);
+
+	if (!octeon_is_simulation()) {
+		link_info = cvmx_helper_link_get(priv->port);
+		if (!link_info.s.link_up)
+			netif_carrier_off(dev);
+	}
+	return 0;
+}
+
+static int cvm_oct_xaui_stop(struct net_device *dev)
+{
+	union cvmx_gmxx_prtx_cfg gmx_cfg;
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	int interface = INTERFACE(priv->port);
+	int index = INDEX(priv->port);
+
+	gmx_cfg.u64 = cvmx_read_csr(CVMX_GMXX_PRTX_CFG(index, interface));
+	gmx_cfg.s.en = 0;
+	cvmx_write_csr(CVMX_GMXX_PRTX_CFG(index, interface), gmx_cfg.u64);
+	return 0;
+}
+
+static void cvm_oct_xaui_poll(struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	cvmx_helper_link_info_t link_info;
+
+	link_info = cvmx_helper_link_get(priv->port);
+	if (link_info.u64 == priv->link_info)
+		return;
+
+	link_info = cvmx_helper_link_autoconf(priv->port);
+	priv->link_info = link_info.u64;
+
+	/* Tell Linux */
+	if (link_info.s.link_up) {
+
+		if (!netif_carrier_ok(dev))
+			netif_carrier_on(dev);
+		if (priv->queue != -1)
+			DEBUGPRINT
+			    ("%s: %u Mbps %s duplex, port %2d, queue %2d\n",
+			     dev->name, link_info.s.speed,
+			     (link_info.s.full_duplex) ? "Full" : "Half",
+			     priv->port, priv->queue);
+		else
+			DEBUGPRINT("%s: %u Mbps %s duplex, port %2d, POW\n",
+				   dev->name, link_info.s.speed,
+				   (link_info.s.full_duplex) ? "Full" : "Half",
+				   priv->port);
+	} else {
+		if (netif_carrier_ok(dev))
+			netif_carrier_off(dev);
+		DEBUGPRINT("%s: Link down\n", dev->name);
+	}
+}
+
+int cvm_oct_xaui_init(struct net_device *dev)
+{
+	struct octeon_ethernet *priv = netdev_priv(dev);
+	cvm_oct_common_init(dev);
+	dev->open = cvm_oct_xaui_open;
+	dev->stop = cvm_oct_xaui_stop;
+	dev->stop(dev);
+	if (!octeon_is_simulation())
+		priv->poll = cvm_oct_xaui_poll;
+
+	return 0;
+}
+
+void cvm_oct_xaui_uninit(struct net_device *dev)
+{
+	cvm_oct_common_uninit(dev);
+}
diff --git a/drivers/staging/octeon/ethernet.c b/drivers/staging/octeon/ethernet.c
new file mode 100644
index 0000000..e8ef9e0
--- /dev/null
+++ b/drivers/staging/octeon/ethernet.c
@@ -0,0 +1,507 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/module.h>
+#include <linux/netdevice.h>
+#include <linux/etherdevice.h>
+#include <linux/delay.h>
+#include <linux/mii.h>
+
+#include <net/dst.h>
+
+#include <asm/octeon/octeon.h>
+
+#include "ethernet-defines.h"
+#include "ethernet-mem.h"
+#include "ethernet-rx.h"
+#include "ethernet-tx.h"
+#include "ethernet-util.h"
+#include "ethernet-proc.h"
+#include "ethernet-common.h"
+#include "octeon-ethernet.h"
+
+#include "cvmx-pip.h"
+#include "cvmx-pko.h"
+#include "cvmx-fau.h"
+#include "cvmx-ipd.h"
+#include "cvmx-helper.h"
+
+#include "cvmx-smix-defs.h"
+
+#if defined(CONFIG_CAVIUM_OCTEON_NUM_PACKET_BUFFERS) \
+	&& CONFIG_CAVIUM_OCTEON_NUM_PACKET_BUFFERS
+int num_packet_buffers = CONFIG_CAVIUM_OCTEON_NUM_PACKET_BUFFERS;
+#else
+int num_packet_buffers = 1024;
+#endif
+module_param(num_packet_buffers, int, 0444);
+MODULE_PARM_DESC(num_packet_buffers, "\n"
+	"\tNumber of packet buffers to allocate and store in the\n"
+	"\tFPA. By default, 1024 packet buffers are used unless\n"
+	"\tCONFIG_CAVIUM_OCTEON_NUM_PACKET_BUFFERS is defined.");
+
+int pow_receive_group = 15;
+module_param(pow_receive_group, int, 0444);
+MODULE_PARM_DESC(pow_receive_group, "\n"
+	"\tPOW group to receive packets from. All ethernet hardware\n"
+	"\twill be configured to send incomming packets to this POW\n"
+	"\tgroup. Also any other software can submit packets to this\n"
+	"\tgroup for the kernel to process.");
+
+int pow_send_group = -1;
+module_param(pow_send_group, int, 0644);
+MODULE_PARM_DESC(pow_send_group, "\n"
+	"\tPOW group to send packets to other software on. This\n"
+	"\tcontrols the creation of the virtual device pow0.\n"
+	"\talways_use_pow also depends on this value.");
+
+int always_use_pow;
+module_param(always_use_pow, int, 0444);
+MODULE_PARM_DESC(always_use_pow, "\n"
+	"\tWhen set, always send to the pow group. This will cause\n"
+	"\tpackets sent to real ethernet devices to be sent to the\n"
+	"\tPOW group instead of the hardware. Unless some other\n"
+	"\tapplication changes the config, packets will still be\n"
+	"\treceived from the low level hardware. Use this option\n"
+	"\tto allow a CVMX app to intercept all packets from the\n"
+	"\tlinux kernel. You must specify pow_send_group along with\n"
+	"\tthis option.");
+
+char pow_send_list[128] = "";
+module_param_string(pow_send_list, pow_send_list, sizeof(pow_send_list), 0444);
+MODULE_PARM_DESC(pow_send_list, "\n"
+	"\tComma separated list of ethernet devices that should use the\n"
+	"\tPOW for transmit instead of the actual ethernet hardware. This\n"
+	"\tis a per port version of always_use_pow. always_use_pow takes\n"
+	"\tprecedence over this list. For example, setting this to\n"
+	"\t\"eth2,spi3,spi7\" would cause these three devices to transmit\n"
+	"\tusing the pow_send_group.");
+
+static int disable_core_queueing = 1;
+module_param(disable_core_queueing, int, 0444);
+MODULE_PARM_DESC(disable_core_queueing, "\n"
+	"\tWhen set the networking core's tx_queue_len is set to zero.  This\n"
+	"\tallows packets to be sent without lock contention in the packet\n"
+	"\tscheduler resulting in some cases in improved throughput.\n");
+
+/**
+ * Periodic timer to check auto negotiation
+ */
+static struct timer_list cvm_oct_poll_timer;
+
+/**
+ * Array of every ethernet device owned by this driver indexed by
+ * the ipd input port number.
+ */
+struct net_device *cvm_oct_device[TOTAL_NUMBER_OF_PORTS];
+
+extern struct semaphore mdio_sem;
+
+/**
+ * Periodic timer tick for slow management operations
+ *
+ * @arg:    Device to check
+ */
+static void cvm_do_timer(unsigned long arg)
+{
+	static int port;
+	if (port < CVMX_PIP_NUM_INPUT_PORTS) {
+		if (cvm_oct_device[port]) {
+			int queues_per_port;
+			int qos;
+			struct octeon_ethernet *priv =
+				netdev_priv(cvm_oct_device[port]);
+			if (priv->poll) {
+				/* skip polling if we don't get the lock */
+				if (!down_trylock(&mdio_sem)) {
+					priv->poll(cvm_oct_device[port]);
+					up(&mdio_sem);
+				}
+			}
+
+			queues_per_port = cvmx_pko_get_num_queues(port);
+			/* Drain any pending packets in the free list */
+			for (qos = 0; qos < queues_per_port; qos++) {
+				if (skb_queue_len(&priv->tx_free_list[qos])) {
+					spin_lock(&priv->tx_free_list[qos].
+						  lock);
+					while (skb_queue_len
+					       (&priv->tx_free_list[qos]) >
+					       cvmx_fau_fetch_and_add32(priv->
+									fau +
+									qos * 4,
+									0))
+						dev_kfree_skb(__skb_dequeue
+							      (&priv->
+							       tx_free_list
+							       [qos]));
+					spin_unlock(&priv->tx_free_list[qos].
+						    lock);
+				}
+			}
+			cvm_oct_device[port]->get_stats(cvm_oct_device[port]);
+		}
+		port++;
+		/* Poll the next port in a 50th of a second.
+		   This spreads the polling of ports out a little bit */
+		mod_timer(&cvm_oct_poll_timer, jiffies + HZ / 50);
+	} else {
+		port = 0;
+		/* All ports have been polled. Start the next iteration through
+		   the ports in one second */
+		mod_timer(&cvm_oct_poll_timer, jiffies + HZ);
+	}
+}
+
+/**
+ * Configure common hardware for all interfaces
+ */
+static __init void cvm_oct_configure_common_hw(void)
+{
+	int r;
+	/* Setup the FPA */
+	cvmx_fpa_enable();
+	cvm_oct_mem_fill_fpa(CVMX_FPA_PACKET_POOL, CVMX_FPA_PACKET_POOL_SIZE,
+			     num_packet_buffers);
+	cvm_oct_mem_fill_fpa(CVMX_FPA_WQE_POOL, CVMX_FPA_WQE_POOL_SIZE,
+			     num_packet_buffers);
+	if (CVMX_FPA_OUTPUT_BUFFER_POOL != CVMX_FPA_PACKET_POOL)
+		cvm_oct_mem_fill_fpa(CVMX_FPA_OUTPUT_BUFFER_POOL,
+				     CVMX_FPA_OUTPUT_BUFFER_POOL_SIZE, 128);
+
+	if (USE_RED)
+		cvmx_helper_setup_red(num_packet_buffers / 4,
+				      num_packet_buffers / 8);
+
+	/* Enable the MII interface */
+	if (!octeon_is_simulation())
+		cvmx_write_csr(CVMX_SMIX_EN(0), 1);
+
+	/* Register an IRQ hander for to receive POW interrupts */
+	r = request_irq(OCTEON_IRQ_WORKQ0 + pow_receive_group,
+			cvm_oct_do_interrupt, IRQF_SHARED, "Ethernet",
+			cvm_oct_device);
+
+#if defined(CONFIG_SMP) && 0
+	if (USE_MULTICORE_RECEIVE) {
+		irq_set_affinity(OCTEON_IRQ_WORKQ0 + pow_receive_group,
+				 cpu_online_mask);
+	}
+#endif
+}
+
+/**
+ * Free a work queue entry received in a intercept callback.
+ *
+ * @work_queue_entry:
+ *               Work queue entry to free
+ * Returns Zero on success, Negative on failure.
+ */
+int cvm_oct_free_work(void *work_queue_entry)
+{
+	cvmx_wqe_t *work = work_queue_entry;
+
+	int segments = work->word2.s.bufs;
+	union cvmx_buf_ptr segment_ptr = work->packet_ptr;
+
+	while (segments--) {
+		union cvmx_buf_ptr next_ptr = *(union cvmx_buf_ptr *)
+			cvmx_phys_to_ptr(segment_ptr.s.addr - 8);
+		if (unlikely(!segment_ptr.s.i))
+			cvmx_fpa_free(cvm_oct_get_buffer_ptr(segment_ptr),
+				      segment_ptr.s.pool,
+				      DONT_WRITEBACK(CVMX_FPA_PACKET_POOL_SIZE /
+						     128));
+		segment_ptr = next_ptr;
+	}
+	cvmx_fpa_free(work, CVMX_FPA_WQE_POOL, DONT_WRITEBACK(1));
+
+	return 0;
+}
+EXPORT_SYMBOL(cvm_oct_free_work);
+
+/**
+ * Module/ driver initialization. Creates the linux network
+ * devices.
+ *
+ * Returns Zero on success
+ */
+static int __init cvm_oct_init_module(void)
+{
+	int num_interfaces;
+	int interface;
+	int fau = FAU_NUM_PACKET_BUFFERS_TO_FREE;
+	int qos;
+
+	pr_notice("cavium-ethernet %s\n", OCTEON_ETHERNET_VERSION);
+
+	cvm_oct_proc_initialize();
+	cvm_oct_rx_initialize();
+	cvm_oct_configure_common_hw();
+
+	cvmx_helper_initialize_packet_io_global();
+
+	/* Change the input group for all ports before input is enabled */
+	num_interfaces = cvmx_helper_get_number_of_interfaces();
+	for (interface = 0; interface < num_interfaces; interface++) {
+		int num_ports = cvmx_helper_ports_on_interface(interface);
+		int port;
+
+		for (port = cvmx_helper_get_ipd_port(interface, 0);
+		     port < cvmx_helper_get_ipd_port(interface, num_ports);
+		     port++) {
+			union cvmx_pip_prt_tagx pip_prt_tagx;
+			pip_prt_tagx.u64 =
+			    cvmx_read_csr(CVMX_PIP_PRT_TAGX(port));
+			pip_prt_tagx.s.grp = pow_receive_group;
+			cvmx_write_csr(CVMX_PIP_PRT_TAGX(port),
+				       pip_prt_tagx.u64);
+		}
+	}
+
+	cvmx_helper_ipd_and_packet_input_enable();
+
+	memset(cvm_oct_device, 0, sizeof(cvm_oct_device));
+
+	/*
+	 * Initialize the FAU used for counting packet buffers that
+	 * need to be freed.
+	 */
+	cvmx_fau_atomic_write32(FAU_NUM_PACKET_BUFFERS_TO_FREE, 0);
+
+	if ((pow_send_group != -1)) {
+		struct net_device *dev;
+		pr_info("\tConfiguring device for POW only access\n");
+		dev = alloc_etherdev(sizeof(struct octeon_ethernet));
+		if (dev) {
+			/* Initialize the device private structure. */
+			struct octeon_ethernet *priv = netdev_priv(dev);
+			memset(priv, 0, sizeof(struct octeon_ethernet));
+
+			dev->init = cvm_oct_common_init;
+			priv->imode = CVMX_HELPER_INTERFACE_MODE_DISABLED;
+			priv->port = CVMX_PIP_NUM_INPUT_PORTS;
+			priv->queue = -1;
+			strcpy(dev->name, "pow%d");
+			for (qos = 0; qos < 16; qos++)
+				skb_queue_head_init(&priv->tx_free_list[qos]);
+
+			if (register_netdev(dev) < 0) {
+				pr_err("Failed to register ethernet "
+					 "device for POW\n");
+				kfree(dev);
+			} else {
+				cvm_oct_device[CVMX_PIP_NUM_INPUT_PORTS] = dev;
+				pr_info("%s: POW send group %d, receive "
+					"group %d\n",
+				     dev->name, pow_send_group,
+				     pow_receive_group);
+			}
+		} else {
+			pr_err("Failed to allocate ethernet device "
+				 "for POW\n");
+		}
+	}
+
+	num_interfaces = cvmx_helper_get_number_of_interfaces();
+	for (interface = 0; interface < num_interfaces; interface++) {
+		cvmx_helper_interface_mode_t imode =
+		    cvmx_helper_interface_get_mode(interface);
+		int num_ports = cvmx_helper_ports_on_interface(interface);
+		int port;
+
+		for (port = cvmx_helper_get_ipd_port(interface, 0);
+		     port < cvmx_helper_get_ipd_port(interface, num_ports);
+		     port++) {
+			struct octeon_ethernet *priv;
+			struct net_device *dev =
+			    alloc_etherdev(sizeof(struct octeon_ethernet));
+			if (!dev) {
+				pr_err("Failed to allocate ethernet device "
+					 "for port %d\n", port);
+				continue;
+			}
+			if (disable_core_queueing)
+				dev->tx_queue_len = 0;
+
+			/* Initialize the device private structure. */
+			priv = netdev_priv(dev);
+			memset(priv, 0, sizeof(struct octeon_ethernet));
+
+			priv->imode = imode;
+			priv->port = port;
+			priv->queue = cvmx_pko_get_base_queue(priv->port);
+			priv->fau = fau - cvmx_pko_get_num_queues(port) * 4;
+			for (qos = 0; qos < 16; qos++)
+				skb_queue_head_init(&priv->tx_free_list[qos]);
+			for (qos = 0; qos < cvmx_pko_get_num_queues(port);
+			     qos++)
+				cvmx_fau_atomic_write32(priv->fau + qos * 4, 0);
+
+			switch (priv->imode) {
+
+			/* These types don't support ports to IPD/PKO */
+			case CVMX_HELPER_INTERFACE_MODE_DISABLED:
+			case CVMX_HELPER_INTERFACE_MODE_PCIE:
+			case CVMX_HELPER_INTERFACE_MODE_PICMG:
+				break;
+
+			case CVMX_HELPER_INTERFACE_MODE_NPI:
+				dev->init = cvm_oct_common_init;
+				dev->uninit = cvm_oct_common_uninit;
+				strcpy(dev->name, "npi%d");
+				break;
+
+			case CVMX_HELPER_INTERFACE_MODE_XAUI:
+				dev->init = cvm_oct_xaui_init;
+				dev->uninit = cvm_oct_xaui_uninit;
+				strcpy(dev->name, "xaui%d");
+				break;
+
+			case CVMX_HELPER_INTERFACE_MODE_LOOP:
+				dev->init = cvm_oct_common_init;
+				dev->uninit = cvm_oct_common_uninit;
+				strcpy(dev->name, "loop%d");
+				break;
+
+			case CVMX_HELPER_INTERFACE_MODE_SGMII:
+				dev->init = cvm_oct_sgmii_init;
+				dev->uninit = cvm_oct_sgmii_uninit;
+				strcpy(dev->name, "eth%d");
+				break;
+
+			case CVMX_HELPER_INTERFACE_MODE_SPI:
+				dev->init = cvm_oct_spi_init;
+				dev->uninit = cvm_oct_spi_uninit;
+				strcpy(dev->name, "spi%d");
+				break;
+
+			case CVMX_HELPER_INTERFACE_MODE_RGMII:
+			case CVMX_HELPER_INTERFACE_MODE_GMII:
+				dev->init = cvm_oct_rgmii_init;
+				dev->uninit = cvm_oct_rgmii_uninit;
+				strcpy(dev->name, "eth%d");
+				break;
+			}
+
+			if (!dev->init) {
+				kfree(dev);
+			} else if (register_netdev(dev) < 0) {
+				pr_err("Failed to register ethernet device "
+					 "for interface %d, port %d\n",
+					 interface, priv->port);
+				kfree(dev);
+			} else {
+				cvm_oct_device[priv->port] = dev;
+				fau -=
+				    cvmx_pko_get_num_queues(priv->port) *
+				    sizeof(uint32_t);
+			}
+		}
+	}
+
+	if (INTERRUPT_LIMIT) {
+		/*
+		 * Set the POW timer rate to give an interrupt at most
+		 * INTERRUPT_LIMIT times per second.
+		 */
+		cvmx_write_csr(CVMX_POW_WQ_INT_PC,
+			       octeon_bootinfo->eclock_hz / (INTERRUPT_LIMIT *
+							     16 * 256) << 8);
+
+		/*
+		 * Enable POW timer interrupt. It will count when
+		 * there are packets available.
+		 */
+		cvmx_write_csr(CVMX_POW_WQ_INT_THRX(pow_receive_group),
+			       0x1ful << 24);
+	} else {
+		/* Enable POW interrupt when our port has at least one packet */
+		cvmx_write_csr(CVMX_POW_WQ_INT_THRX(pow_receive_group), 0x1001);
+	}
+
+	/* Enable the poll timer for checking RGMII status */
+	init_timer(&cvm_oct_poll_timer);
+	cvm_oct_poll_timer.data = 0;
+	cvm_oct_poll_timer.function = cvm_do_timer;
+	mod_timer(&cvm_oct_poll_timer, jiffies + HZ);
+
+	return 0;
+}
+
+/**
+ * Module / driver shutdown
+ *
+ * Returns Zero on success
+ */
+static void __exit cvm_oct_cleanup_module(void)
+{
+	int port;
+
+	/* Disable POW interrupt */
+	cvmx_write_csr(CVMX_POW_WQ_INT_THRX(pow_receive_group), 0);
+
+	cvmx_ipd_disable();
+
+	/* Free the interrupt handler */
+	free_irq(OCTEON_IRQ_WORKQ0 + pow_receive_group, cvm_oct_device);
+
+	del_timer(&cvm_oct_poll_timer);
+	cvm_oct_rx_shutdown();
+	cvmx_pko_disable();
+
+	/* Free the ethernet devices */
+	for (port = 0; port < TOTAL_NUMBER_OF_PORTS; port++) {
+		if (cvm_oct_device[port]) {
+			cvm_oct_tx_shutdown(cvm_oct_device[port]);
+			unregister_netdev(cvm_oct_device[port]);
+			kfree(cvm_oct_device[port]);
+			cvm_oct_device[port] = NULL;
+		}
+	}
+
+	cvmx_pko_shutdown();
+	cvm_oct_proc_shutdown();
+
+	cvmx_ipd_free_ptr();
+
+	/* Free the HW pools */
+	cvm_oct_mem_empty_fpa(CVMX_FPA_PACKET_POOL, CVMX_FPA_PACKET_POOL_SIZE,
+			      num_packet_buffers);
+	cvm_oct_mem_empty_fpa(CVMX_FPA_WQE_POOL, CVMX_FPA_WQE_POOL_SIZE,
+			      num_packet_buffers);
+	if (CVMX_FPA_OUTPUT_BUFFER_POOL != CVMX_FPA_PACKET_POOL)
+		cvm_oct_mem_empty_fpa(CVMX_FPA_OUTPUT_BUFFER_POOL,
+				      CVMX_FPA_OUTPUT_BUFFER_POOL_SIZE, 128);
+}
+
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Cavium Networks <support@caviumnetworks.com>");
+MODULE_DESCRIPTION("Cavium Networks Octeon ethernet driver.");
+module_init(cvm_oct_init_module);
+module_exit(cvm_oct_cleanup_module);
diff --git a/drivers/staging/octeon/octeon-ethernet.h b/drivers/staging/octeon/octeon-ethernet.h
new file mode 100644
index 0000000..b319907
--- /dev/null
+++ b/drivers/staging/octeon/octeon-ethernet.h
@@ -0,0 +1,127 @@
+/**********************************************************************
+ * Author: Cavium Networks
+ *
+ * Contact: support@caviumnetworks.com
+ * This file is part of the OCTEON SDK
+ *
+ * Copyright (c) 2003-2007 Cavium Networks
+ *
+ * This file is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, Version 2, as
+ * published by the Free Software Foundation.
+ *
+ * This file is distributed in the hope that it will be useful, but
+ * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
+ * NONINFRINGEMENT.  See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this file; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ * or visit http://www.gnu.org/licenses/.
+ *
+ * This file may also be available under a different license from Cavium.
+ * Contact Cavium Networks for more information
+**********************************************************************/
+
+/*
+ * External interface for the Cavium Octeon ethernet driver.
+ */
+#ifndef OCTEON_ETHERNET_H
+#define OCTEON_ETHERNET_H
+
+/**
+ * This is the definition of the Ethernet driver's private
+ * driver state stored in netdev_priv(dev).
+ */
+struct octeon_ethernet {
+	/* PKO hardware output port */
+	int port;
+	/* PKO hardware queue for the port */
+	int queue;
+	/* Hardware fetch and add to count outstanding tx buffers */
+	int fau;
+	/*
+	 * Type of port. This is one of the enums in
+	 * cvmx_helper_interface_mode_t
+	 */
+	int imode;
+	/* List of outstanding tx buffers per queue */
+	struct sk_buff_head tx_free_list[16];
+	/* Device statistics */
+	struct net_device_stats stats
+;	/* Generic MII info structure */
+	struct mii_if_info mii_info;
+	/* Last negotiated link state */
+	uint64_t link_info;
+	/* Called periodically to check link status */
+	void (*poll) (struct net_device *dev);
+};
+
+/**
+ * Free a work queue entry received in a intercept callback.
+ *
+ * @work_queue_entry:
+ *               Work queue entry to free
+ * Returns Zero on success, Negative on failure.
+ */
+int cvm_oct_free_work(void *work_queue_entry);
+
+/**
+ * Transmit a work queue entry out of the ethernet port. Both
+ * the work queue entry and the packet data can optionally be
+ * freed. The work will be freed on error as well.
+ *
+ * @dev:     Device to transmit out.
+ * @work_queue_entry:
+ *                Work queue entry to send
+ * @do_free: True if the work queue entry and packet data should be
+ *                freed. If false, neither will be freed.
+ * @qos:     Index into the queues for this port to transmit on. This
+ *                is used to implement QoS if their are multiple queues per
+ *                port. This parameter must be between 0 and the number of
+ *                queues per port minus 1. Values outside of this range will
+ *                be change to zero.
+ *
+ * Returns Zero on success, negative on failure.
+ */
+int cvm_oct_transmit_qos(struct net_device *dev, void *work_queue_entry,
+			 int do_free, int qos);
+
+/**
+ * Transmit a work queue entry out of the ethernet port. Both
+ * the work queue entry and the packet data can optionally be
+ * freed. The work will be freed on error as well. This simply
+ * wraps cvmx_oct_transmit_qos() for backwards compatability.
+ *
+ * @dev:     Device to transmit out.
+ * @work_queue_entry:
+ *                Work queue entry to send
+ * @do_free: True if the work queue entry and packet data should be
+ *                freed. If false, neither will be freed.
+ *
+ * Returns Zero on success, negative on failure.
+ */
+static inline int cvm_oct_transmit(struct net_device *dev,
+				   void *work_queue_entry, int do_free)
+{
+	return cvm_oct_transmit_qos(dev, work_queue_entry, do_free, 0);
+}
+
+extern int cvm_oct_rgmii_init(struct net_device *dev);
+extern void cvm_oct_rgmii_uninit(struct net_device *dev);
+extern int cvm_oct_sgmii_init(struct net_device *dev);
+extern void cvm_oct_sgmii_uninit(struct net_device *dev);
+extern int cvm_oct_spi_init(struct net_device *dev);
+extern void cvm_oct_spi_uninit(struct net_device *dev);
+extern int cvm_oct_xaui_init(struct net_device *dev);
+extern void cvm_oct_xaui_uninit(struct net_device *dev);
+
+extern int always_use_pow;
+extern int pow_send_group;
+extern int pow_receive_group;
+extern char pow_send_list[];
+extern struct net_device *cvm_oct_device[];
+
+#endif
diff --git a/drivers/staging/otus/80211core/ccmd.c b/drivers/staging/otus/80211core/ccmd.c
index 4799779..83dd8ba 100644
--- a/drivers/staging/otus/80211core/ccmd.c
+++ b/drivers/staging/otus/80211core/ccmd.c
@@ -27,1019 +27,941 @@
 #include "../hal/hpreg.h"
 
 
-u16_t zfWlanReset(zdev_t* dev);
-u32_t zfUpdateRxRate(zdev_t* dev);
+u16_t zfWlanReset(zdev_t *dev);
+u32_t zfUpdateRxRate(zdev_t *dev);
 
 
 extern void zfiUsbRecv(zdev_t *dev, zbuf_t *buf);
-extern void zfiUsbRegIn(zdev_t* dev, u32_t* rsp, u16_t rspLen);
-extern void zfiUsbOutComplete(zdev_t* dev, zbuf_t *buf, u8_t status, u8_t *hdr);
-extern void zfiUsbRegOutComplete(zdev_t* dev);
-extern u16_t zfHpReinit(zdev_t* dev, u32_t frequency);
+extern void zfiUsbRegIn(zdev_t *dev, u32_t *rsp, u16_t rspLen);
+extern void zfiUsbOutComplete(zdev_t *dev, zbuf_t *buf, u8_t status, u8_t *hdr);
+extern void zfiUsbRegOutComplete(zdev_t *dev);
+extern u16_t zfHpReinit(zdev_t *dev, u32_t frequency);
 
 /* Get size (byte) of driver core global data structure.    */
 /* This size will be used by driver wrapper to allocate     */
 /* a memory space for driver core to store global variables */
-u16_t zfiGlobalDataSize(zdev_t* dev)
+u16_t zfiGlobalDataSize(zdev_t *dev)
 {
-    u32_t ret;
-    ret = (sizeof(struct zsWlanDev));
-    zm_assert((ret>>16) == 0);
-    return (u16_t)ret;
+	u32_t ret;
+	ret = (sizeof(struct zsWlanDev));
+	zm_assert((ret>>16) == 0);
+	return (u16_t)ret;
 }
 
 
 /* Initialize WLAN hardware and software, resource will be allocated */
 /* for WLAN operation, must be called first before other function.   */
-extern u16_t zfiWlanOpen(zdev_t* dev, struct zsCbFuncTbl* cbFuncTbl)
+extern u16_t zfiWlanOpen(zdev_t *dev, struct zsCbFuncTbl *cbFuncTbl)
 {
-    //u16_t ret;
-    //u32_t i;
-    //u8_t* ch;
-    //u8_t  bPassive;
-    u32_t devSize;
-    struct zfCbUsbFuncTbl cbUsbFuncTbl;
-    zmw_get_wlan_dev(dev);
+	/* u16_t ret;
+	   u32_t i;
+	   u8_t* ch;
+	   u8_t  bPassive;
+	*/
+	u32_t devSize;
+	struct zfCbUsbFuncTbl cbUsbFuncTbl;
+	zmw_get_wlan_dev(dev);
 
-    zm_debug_msg0("start");
+	zm_debug_msg0("start");
 
-    devSize = sizeof(struct zsWlanDev);
-    /* Zeroize zsWlanDev struct */
-    zfZeroMemory((u8_t*)wd, (u16_t)devSize);
+	devSize = sizeof(struct zsWlanDev);
+	/* Zeroize zsWlanDev struct */
+	zfZeroMemory((u8_t *)wd, (u16_t)devSize);
 
 #ifdef ZM_ENABLE_AGGREGATION
-    zfAggInit(dev);
+	zfAggInit(dev);
 #endif
 
-    zfCwmInit(dev);
+	zfCwmInit(dev);
 
-    wd->commTally.RateCtrlTxMPDU = 0;
-    wd->commTally.RateCtrlBAFail = 0;
-    wd->preambleTypeInUsed = ZM_PREAMBLE_TYPE_SHORT;
+	wd->commTally.RateCtrlTxMPDU = 0;
+	wd->commTally.RateCtrlBAFail = 0;
+	wd->preambleTypeInUsed = ZM_PREAMBLE_TYPE_SHORT;
 
-    if (cbFuncTbl == NULL)
-    {
-        /* zfcbRecvEth() is mandatory */
-        zm_assert(0);
-    }
-    else
-    {
-        if (cbFuncTbl->zfcbRecvEth == NULL)
-        {
-            /* zfcbRecvEth() is mandatory */
-            zm_assert(0);
-        }
-        wd->zfcbAuthNotify = cbFuncTbl->zfcbAuthNotify;
-        wd->zfcbAuthNotify = cbFuncTbl->zfcbAuthNotify;
-        wd->zfcbAsocNotify = cbFuncTbl->zfcbAsocNotify;
-        wd->zfcbDisAsocNotify = cbFuncTbl->zfcbDisAsocNotify;
-        wd->zfcbApConnectNotify = cbFuncTbl->zfcbApConnectNotify;
-        wd->zfcbConnectNotify = cbFuncTbl->zfcbConnectNotify;
-        wd->zfcbScanNotify = cbFuncTbl->zfcbScanNotify;
-        wd->zfcbMicFailureNotify = cbFuncTbl->zfcbMicFailureNotify;
-        wd->zfcbApMicFailureNotify = cbFuncTbl->zfcbApMicFailureNotify;
-        wd->zfcbIbssPartnerNotify = cbFuncTbl->zfcbIbssPartnerNotify;
-        wd->zfcbMacAddressNotify = cbFuncTbl->zfcbMacAddressNotify;
-        wd->zfcbSendCompleteIndication = cbFuncTbl->zfcbSendCompleteIndication;
-        wd->zfcbRecvEth = cbFuncTbl->zfcbRecvEth;
-        wd->zfcbRestoreBufData = cbFuncTbl->zfcbRestoreBufData;
-        wd->zfcbRecv80211 = cbFuncTbl->zfcbRecv80211;
+	if (cbFuncTbl == NULL) {
+		/* zfcbRecvEth() is mandatory */
+		zm_assert(0);
+	} else {
+		if (cbFuncTbl->zfcbRecvEth == NULL) {
+			/* zfcbRecvEth() is mandatory */
+			zm_assert(0);
+		}
+		wd->zfcbAuthNotify = cbFuncTbl->zfcbAuthNotify;
+		wd->zfcbAuthNotify = cbFuncTbl->zfcbAuthNotify;
+		wd->zfcbAsocNotify = cbFuncTbl->zfcbAsocNotify;
+		wd->zfcbDisAsocNotify = cbFuncTbl->zfcbDisAsocNotify;
+		wd->zfcbApConnectNotify = cbFuncTbl->zfcbApConnectNotify;
+		wd->zfcbConnectNotify = cbFuncTbl->zfcbConnectNotify;
+		wd->zfcbScanNotify = cbFuncTbl->zfcbScanNotify;
+		wd->zfcbMicFailureNotify = cbFuncTbl->zfcbMicFailureNotify;
+		wd->zfcbApMicFailureNotify = cbFuncTbl->zfcbApMicFailureNotify;
+		wd->zfcbIbssPartnerNotify = cbFuncTbl->zfcbIbssPartnerNotify;
+		wd->zfcbMacAddressNotify = cbFuncTbl->zfcbMacAddressNotify;
+		wd->zfcbSendCompleteIndication =
+					cbFuncTbl->zfcbSendCompleteIndication;
+		wd->zfcbRecvEth = cbFuncTbl->zfcbRecvEth;
+		wd->zfcbRestoreBufData = cbFuncTbl->zfcbRestoreBufData;
+		wd->zfcbRecv80211 = cbFuncTbl->zfcbRecv80211;
 #ifdef ZM_ENABLE_CENC
-        wd->zfcbCencAsocNotify = cbFuncTbl->zfcbCencAsocNotify;
-#endif //ZM_ENABLE_CENC
-        wd->zfcbClassifyTxPacket = cbFuncTbl->zfcbClassifyTxPacket;
-        wd->zfcbHwWatchDogNotify = cbFuncTbl->zfcbHwWatchDogNotify;
-    }
+		wd->zfcbCencAsocNotify = cbFuncTbl->zfcbCencAsocNotify;
+#endif /* ZM_ENABLE_CENC */
+		wd->zfcbClassifyTxPacket = cbFuncTbl->zfcbClassifyTxPacket;
+		wd->zfcbHwWatchDogNotify = cbFuncTbl->zfcbHwWatchDogNotify;
+	}
 
-    //add by honda 0330
-    cbUsbFuncTbl.zfcbUsbRecv = zfiUsbRecv;
-    cbUsbFuncTbl.zfcbUsbRegIn = zfiUsbRegIn;
-    cbUsbFuncTbl.zfcbUsbOutComplete = zfiUsbOutComplete;
-    cbUsbFuncTbl.zfcbUsbRegOutComplete = zfiUsbRegOutComplete;
-    zfwUsbRegisterCallBack(dev, &cbUsbFuncTbl);
-    /* Init OWN MAC address */
-    wd->macAddr[0] = 0x8000;
-    wd->macAddr[1] = 0x0000;
-    wd->macAddr[2] = 0x0000;
+	/* add by honda 0330 */
+	cbUsbFuncTbl.zfcbUsbRecv = zfiUsbRecv;
+	cbUsbFuncTbl.zfcbUsbRegIn = zfiUsbRegIn;
+	cbUsbFuncTbl.zfcbUsbOutComplete = zfiUsbOutComplete;
+	cbUsbFuncTbl.zfcbUsbRegOutComplete = zfiUsbRegOutComplete;
+	zfwUsbRegisterCallBack(dev, &cbUsbFuncTbl);
+	/* Init OWN MAC address */
+	wd->macAddr[0] = 0x8000;
+	wd->macAddr[1] = 0x0000;
+	wd->macAddr[2] = 0x0000;
 
-    wd->regulationTable.regionCode = 0xffff;
+	wd->regulationTable.regionCode = 0xffff;
 
-    zfHpInit(dev, wd->frequency);
+	zfHpInit(dev, wd->frequency);
 
-    /* init region code */
-    //wd->regulationTable.regionCode = NULL1_WORLD; //Only 2.4g RegCode
-    //zfHpGetRegulationTablefromRegionCode(dev, NULL1_WORLD);
-    //zfiWlanSetDot11DMode(dev , 1); // Enable 802.11d
-    /* Get the first channel */
-    //wd->frequency = zfChGetFirstChannel(dev, &bPassive);
+	/* init region code */
+	/* wd->regulationTable.regionCode = NULL1_WORLD; //Only 2.4g RegCode */
+	/* zfHpGetRegulationTablefromRegionCode(dev, NULL1_WORLD); */
+	/* zfiWlanSetDot11DMode(dev , 1); //Enable 802.11d */
+	/* Get the first channel */
+	/* wd->frequency = zfChGetFirstChannel(dev, &bPassive); */
 #ifdef ZM_AP_DEBUG
-    //wd->frequency = 2437;
+	/* wd->frequency = 2437; */
 #endif
 
-    //STA mode
-    wd->sta.mTxRate = 0x0;
-    wd->sta.uTxRate = 0x3;
-    wd->sta.mmTxRate = 0x0;
-    wd->sta.adapterState = ZM_STA_STATE_DISCONNECT;
-    wd->sta.capability[0] = 0x01;
-    wd->sta.capability[1] = 0x00;
+	/* STA mode */
+	wd->sta.mTxRate = 0x0;
+	wd->sta.uTxRate = 0x3;
+	wd->sta.mmTxRate = 0x0;
+	wd->sta.adapterState = ZM_STA_STATE_DISCONNECT;
+	wd->sta.capability[0] = 0x01;
+	wd->sta.capability[1] = 0x00;
 
-    wd->sta.preambleTypeHT = 0;
-    wd->sta.htCtrlBandwidth = 0;
-    wd->sta.htCtrlSTBC = 0;
-    wd->sta.htCtrlSG = 0;
-    wd->sta.defaultTA = 0;
-    //wd->sta.activescanTickPerChannel = ZM_TIME_ACTIVE_SCAN/ZM_MS_PER_TICK;
+	wd->sta.preambleTypeHT = 0;
+	wd->sta.htCtrlBandwidth = 0;
+	wd->sta.htCtrlSTBC = 0;
+	wd->sta.htCtrlSG = 0;
+	wd->sta.defaultTA = 0;
+	/*wd->sta.activescanTickPerChannel =
+	*ZM_TIME_ACTIVE_SCAN/ZM_MS_PER_TICK;
+	*/
 	{
 		u8_t Dur = ZM_TIME_ACTIVE_SCAN;
 		zfwGetActiveScanDur(dev, &Dur);
-		wd->sta.activescanTickPerChannel = Dur/ZM_MS_PER_TICK;
+		wd->sta.activescanTickPerChannel = Dur / ZM_MS_PER_TICK;
 
 	}
-    wd->sta.passiveScanTickPerChannel = ZM_TIME_PASSIVE_SCAN/ZM_MS_PER_TICK;
-    wd->sta.bAutoReconnect = TRUE;
-    wd->sta.dropUnencryptedPkts = FALSE;
+	wd->sta.passiveScanTickPerChannel = ZM_TIME_PASSIVE_SCAN/ZM_MS_PER_TICK;
+	wd->sta.bAutoReconnect = TRUE;
+	wd->sta.dropUnencryptedPkts = FALSE;
 
-    /* set default to bypass all multicast packet for linux, window XP would set 0 by wrapper initialization */
+	/* set default to bypass all multicast packet for linux,
+	*  window XP would set 0 by wrapper initialization
+	*/
 	wd->sta.bAllMulticast = 1;
 
-    /* Initial the RIFS Status / RIFS-like frame count / RIFS count */
-    wd->sta.rifsState = ZM_RIFS_STATE_DETECTING;
-    wd->sta.rifsLikeFrameCnt = 0;
-    wd->sta.rifsCount = 0;
+	/* Initial the RIFS Status / RIFS-like frame count / RIFS count */
+	wd->sta.rifsState = ZM_RIFS_STATE_DETECTING;
+	wd->sta.rifsLikeFrameCnt = 0;
+	wd->sta.rifsCount = 0;
 
-    wd->sta.osRxFilter = 0;
-    wd->sta.bSafeMode = 0;
+	wd->sta.osRxFilter = 0;
+	wd->sta.bSafeMode = 0;
 
-    //Common
-    zfResetSupportRate(dev, ZM_DEFAULT_SUPPORT_RATE_DISCONNECT);
-    wd->beaconInterval = 100;
-    wd->rtsThreshold = 2346;
-    wd->fragThreshold = 32767;
-    wd->wlanMode = ZM_MODE_INFRASTRUCTURE;
-    wd->txMCS = 0xff;    //AUTO
-    wd->dtim = 1;
-    //wd->txMT = 1;       //OFDM
-    wd->tick = 1;
-    wd->maxTxPower2 = 0xff;
-    wd->maxTxPower5 = 0xff;
-    wd->supportMode = 0xffffffff;
-    wd->ws.adhocMode = ZM_ADHOCBAND_G;
-    wd->ws.autoSetFrequency = 0xff;
+	/* Common */
+	zfResetSupportRate(dev, ZM_DEFAULT_SUPPORT_RATE_DISCONNECT);
+	wd->beaconInterval = 100;
+	wd->rtsThreshold = 2346;
+	wd->fragThreshold = 32767;
+	wd->wlanMode = ZM_MODE_INFRASTRUCTURE;
+	wd->txMCS = 0xff;    /* AUTO */
+	wd->dtim = 1;
+	/* wd->txMT = 1;       *//*OFDM */
+	wd->tick = 1;
+	wd->maxTxPower2 = 0xff;
+	wd->maxTxPower5 = 0xff;
+	wd->supportMode = 0xffffffff;
+	wd->ws.adhocMode = ZM_ADHOCBAND_G;
+	wd->ws.autoSetFrequency = 0xff;
 
-    //AP mode
-    //wd->bgMode = wd->ws.bgMode;
-    wd->ap.ssidLen[0] = 6;
-    wd->ap.ssid[0][0] = 'Z';
-    wd->ap.ssid[0][1] = 'D';
-    wd->ap.ssid[0][2] = '1';
-    wd->ap.ssid[0][3] = '2';
-    wd->ap.ssid[0][4] = '2';
-    wd->ap.ssid[0][5] = '1';
+	/* AP mode */
+	/* wd->bgMode = wd->ws.bgMode; */
+	wd->ap.ssidLen[0] = 6;
+	wd->ap.ssid[0][0] = 'Z';
+	wd->ap.ssid[0][1] = 'D';
+	wd->ap.ssid[0][2] = '1';
+	wd->ap.ssid[0][3] = '2';
+	wd->ap.ssid[0][4] = '2';
+	wd->ap.ssid[0][5] = '1';
 
-    // Init the country iso name as NA
-    wd->ws.countryIsoName[0] = 0;
-    wd->ws.countryIsoName[1] = 0;
-    wd->ws.countryIsoName[2] = '\0';
+	/* Init the country iso name as NA */
+	wd->ws.countryIsoName[0] = 0;
+	wd->ws.countryIsoName[1] = 0;
+	wd->ws.countryIsoName[2] = '\0';
 
 	/* init fragmentation is disabled */
-	//zfiWlanSetFragThreshold(dev, 0);
+	/* zfiWlanSetFragThreshold(dev, 0); */
 
 	/* airopeek : swSniffer 1=>on  0=>off */
 	wd->swSniffer = 0;
-    wd->XLinkMode = 0;
+	wd->XLinkMode = 0;
 
-// jhlee HT 0
+	/* jhlee HT 0 */
 #if 1
-    /* AP Mode*/
-    /* Init HT Capability Info */
-    wd->ap.HTCap.Data.ElementID = ZM_WLAN_EID_HT_CAPABILITY;
-    wd->ap.HTCap.Data.Length = 26;
-    //wd->ap.HTCap.Data.SupChannelWidthSet = 0;
-    //wd->ap.HTCap.Data.MIMOPowerSave = 3;
-    //wd->ap.HTCap.Data.ShortGIfor40MHz = 0;
-    //wd->ap.HTCap.Data.ShortGIfor20MHz = 0;
-    //wd->ap.HTCap.Data.DSSSandCCKin40MHz = 0;
-    wd->ap.HTCap.Data.AMPDUParam |= HTCAP_MaxRxAMPDU3;
-    wd->ap.HTCap.Data.MCSSet[0] = 0xFF; // MCS 0 ~  7
-    wd->ap.HTCap.Data.MCSSet[1] = 0xFF; // MCS 8 ~ 15
+	/* AP Mode*/
+	/* Init HT Capability Info */
+	wd->ap.HTCap.Data.ElementID = ZM_WLAN_EID_HT_CAPABILITY;
+	wd->ap.HTCap.Data.Length = 26;
+	/*wd->ap.HTCap.Data.SupChannelWidthSet = 0;
+	wd->ap.HTCap.Data.MIMOPowerSave = 3;
+	wd->ap.HTCap.Data.ShortGIfor40MHz = 0;
+	wd->ap.HTCap.Data.ShortGIfor20MHz = 0;
+	wd->ap.HTCap.Data.DSSSandCCKin40MHz = 0;
+	*/
+	wd->ap.HTCap.Data.AMPDUParam |= HTCAP_MaxRxAMPDU3;
+	wd->ap.HTCap.Data.MCSSet[0] = 0xFF; /* MCS 0 ~  7 */
+	wd->ap.HTCap.Data.MCSSet[1] = 0xFF; /* MCS 8 ~ 15 */
 
-    /* Init Extended HT Capability Info */
-    wd->ap.ExtHTCap.Data.ElementID = ZM_WLAN_EID_EXTENDED_HT_CAPABILITY;
-    wd->ap.ExtHTCap.Data.Length = 22;
-    wd->ap.ExtHTCap.Data.ControlChannel = 6;
-    //wd->ap.ExtHTCap.Data.ExtChannelOffset = 3;
-    wd->ap.ExtHTCap.Data.ChannelInfo |= ExtHtCap_RecomTxWidthSet;
-    //wd->ap.ExtHTCap.Data.RIFSMode = 1;
-    wd->ap.ExtHTCap.Data.OperatingInfo |= 1;
+	/* Init Extended HT Capability Info */
+	wd->ap.ExtHTCap.Data.ElementID = ZM_WLAN_EID_EXTENDED_HT_CAPABILITY;
+	wd->ap.ExtHTCap.Data.Length = 22;
+	wd->ap.ExtHTCap.Data.ControlChannel = 6;
+	/* wd->ap.ExtHTCap.Data.ExtChannelOffset = 3; */
+	wd->ap.ExtHTCap.Data.ChannelInfo |= ExtHtCap_RecomTxWidthSet;
+	/* wd->ap.ExtHTCap.Data.RIFSMode = 1; */
+	wd->ap.ExtHTCap.Data.OperatingInfo |= 1;
 
-    /* STA Mode*/
-    /* Init HT Capability Info */
-    wd->sta.HTCap.Data.ElementID = ZM_WLAN_EID_HT_CAPABILITY;
-    wd->sta.HTCap.Data.Length = 26;
+	/* STA Mode*/
+	/* Init HT Capability Info */
+	wd->sta.HTCap.Data.ElementID = ZM_WLAN_EID_HT_CAPABILITY;
+	wd->sta.HTCap.Data.Length = 26;
 
-    /* Test with 5G-AP : 7603 */
-    //wd->sta.HTCap.Data.SupChannelWidthSet = 1;
-    wd->sta.HTCap.Data.HtCapInfo |= HTCAP_SMEnabled;
-    wd->sta.HTCap.Data.HtCapInfo |= HTCAP_SupChannelWidthSet;
-    wd->sta.HTCap.Data.HtCapInfo |= HTCAP_ShortGIfor40MHz;
-    wd->sta.HTCap.Data.HtCapInfo |= HTCAP_DSSSandCCKin40MHz;
+	/* Test with 5G-AP : 7603 */
+	/* wd->sta.HTCap.Data.SupChannelWidthSet = 1; */
+	wd->sta.HTCap.Data.HtCapInfo |= HTCAP_SMEnabled;
+	wd->sta.HTCap.Data.HtCapInfo |= HTCAP_SupChannelWidthSet;
+	wd->sta.HTCap.Data.HtCapInfo |= HTCAP_ShortGIfor40MHz;
+	wd->sta.HTCap.Data.HtCapInfo |= HTCAP_DSSSandCCKin40MHz;
 #ifndef ZM_DISABLE_AMSDU8K_SUPPORT
-    wd->sta.HTCap.Data.HtCapInfo |= HTCAP_MaxAMSDULength;
+	wd->sta.HTCap.Data.HtCapInfo |= HTCAP_MaxAMSDULength;
 #endif
-    //wd->sta.HTCap.Data.MIMOPowerSave = 0;
-    //wd->sta.HTCap.Data.ShortGIfor40MHz = 0;
-    //wd->sta.HTCap.Data.ShortGIfor20MHz = 0;
-    //wd->sta.HTCap.Data.DSSSandCCKin40MHz = 0;
-    wd->sta.HTCap.Data.AMPDUParam |= HTCAP_MaxRxAMPDU3;
-    wd->sta.HTCap.Data.MCSSet[0] = 0xFF; // MCS 0 ~  7
-    wd->sta.HTCap.Data.MCSSet[1] = 0xFF; // MCS 8 ~ 15
-    wd->sta.HTCap.Data.PCO |= HTCAP_TransmissionTime3;
-    //wd->sta.HTCap.Data.TransmissionTime = 0;
-    /* Init Extended HT Capability Info */
-    wd->sta.ExtHTCap.Data.ElementID = ZM_WLAN_EID_EXTENDED_HT_CAPABILITY;
-    wd->sta.ExtHTCap.Data.Length = 22;
-    wd->sta.ExtHTCap.Data.ControlChannel = 6;
+	/*wd->sta.HTCap.Data.MIMOPowerSave = 0;
+	wd->sta.HTCap.Data.ShortGIfor40MHz = 0;
+	wd->sta.HTCap.Data.ShortGIfor20MHz = 0;
+	wd->sta.HTCap.Data.DSSSandCCKin40MHz = 0;
+	*/
+	wd->sta.HTCap.Data.AMPDUParam |= HTCAP_MaxRxAMPDU3;
+	wd->sta.HTCap.Data.MCSSet[0] = 0xFF; /* MCS 0 ~  7 */
+	wd->sta.HTCap.Data.MCSSet[1] = 0xFF; /* MCS 8 ~ 15 */
+	wd->sta.HTCap.Data.PCO |= HTCAP_TransmissionTime3;
+	/* wd->sta.HTCap.Data.TransmissionTime = 0; */
+	/* Init Extended HT Capability Info */
+	wd->sta.ExtHTCap.Data.ElementID = ZM_WLAN_EID_EXTENDED_HT_CAPABILITY;
+	wd->sta.ExtHTCap.Data.Length = 22;
+	wd->sta.ExtHTCap.Data.ControlChannel = 6;
 
-    //wd->sta.ExtHTCap.Data.ExtChannelOffset |= 3;
-    wd->sta.ExtHTCap.Data.ChannelInfo |= ExtHtCap_ExtChannelOffsetBelow;
+	/* wd->sta.ExtHTCap.Data.ExtChannelOffset |= 3; */
+	wd->sta.ExtHTCap.Data.ChannelInfo |= ExtHtCap_ExtChannelOffsetBelow;
 
-    //wd->sta.ExtHTCap.Data.RecomTxWidthSet = 1;
-    //wd->sta.ExtHTCap.Data.RIFSMode = 1;
-    wd->sta.ExtHTCap.Data.OperatingInfo |= 1;
+	/* wd->sta.ExtHTCap.Data.RecomTxWidthSet = 1; */
+	/* wd->sta.ExtHTCap.Data.RIFSMode = 1; */
+	wd->sta.ExtHTCap.Data.OperatingInfo |= 1;
 #endif
 
 #if 0
-    /* WME test code */
-    wd->ap.qosMode[0] = 1;
+	/* WME test code */
+	wd->ap.qosMode[0] = 1;
 #endif
 
-    wd->ledStruct.ledMode[0] = 0x2221;
-    wd->ledStruct.ledMode[1] = 0x2221;
+	wd->ledStruct.ledMode[0] = 0x2221;
+	wd->ledStruct.ledMode[1] = 0x2221;
 
-    zfTimerInit(dev);
+	zfTimerInit(dev);
 
-    ZM_PERFORMANCE_INIT(dev);
+	ZM_PERFORMANCE_INIT(dev);
 
-    zfBssInfoCreate(dev);
-    zfScanMgrInit(dev);
-    zfPowerSavingMgrInit(dev);
+	zfBssInfoCreate(dev);
+	zfScanMgrInit(dev);
+	zfPowerSavingMgrInit(dev);
 
 #if 0
-    /* Test code */
-    {
-        u32_t key[4] = {0xffffffff, 0xff, 0, 0};
-        u16_t addr[3] = {0x8000, 0x01ab, 0x0000};
-        //zfSetKey(dev, 0, 0, ZM_WEP64, addr, key);
-        //zfSetKey(dev, 0, 0, ZM_AES, addr, key);
-        //zfSetKey(dev, 64, 0, 1, wd->macAddr, key);
-    }
+	/* Test code */
+	{
+		u32_t key[4] = {0xffffffff, 0xff, 0, 0};
+		u16_t addr[3] = {0x8000, 0x01ab, 0x0000};
+		/*zfSetKey(dev, 0, 0, ZM_WEP64, addr, key);
+		zfSetKey(dev, 0, 0, ZM_AES, addr, key);
+		zfSetKey(dev, 64, 0, 1, wd->macAddr, key);
+		*/
+	}
 #endif
 
-    // WME settings
-    wd->ws.staWmeEnabled = 1;           // Enable WME by default
-    #define ZM_UAPSD_Q_SIZE 32 //2^N
-    wd->ap.uapsdQ = zfQueueCreate(dev, ZM_UAPSD_Q_SIZE);
-    zm_assert(wd->ap.uapsdQ != NULL);
-    wd->sta.uapsdQ = zfQueueCreate(dev, ZM_UAPSD_Q_SIZE);
-    zm_assert(wd->sta.uapsdQ != NULL);
+	/* WME settings */
+	wd->ws.staWmeEnabled = 1;           /* Enable WME by default */
+#define ZM_UAPSD_Q_SIZE 32 /* 2^N */
+	wd->ap.uapsdQ = zfQueueCreate(dev, ZM_UAPSD_Q_SIZE);
+	zm_assert(wd->ap.uapsdQ != NULL);
+	wd->sta.uapsdQ = zfQueueCreate(dev, ZM_UAPSD_Q_SIZE);
+	zm_assert(wd->sta.uapsdQ != NULL);
 
-    //zfHpInit(dev, wd->frequency);
+	/* zfHpInit(dev, wd->frequency); */
 
-    /* MAC address */
-    //zfHpSetMacAddress(dev, wd->macAddr, 0);
-    zfHpGetMacAddress(dev);
+	/* MAC address */
+	/* zfHpSetMacAddress(dev, wd->macAddr, 0); */
+	zfHpGetMacAddress(dev);
 
-    zfCoreSetFrequency(dev, wd->frequency);
+	zfCoreSetFrequency(dev, wd->frequency);
 
 #if ZM_PCI_LOOP_BACK == 1
-    zfwWriteReg(dev, ZM_REG_PCI_CONTROL, 6);
+	zfwWriteReg(dev, ZM_REG_PCI_CONTROL, 6);
 #endif /* #if ZM_PCI_LOOP_BACK == 1 */
 
-    //zfiWlanSetDot11DMode(dev , 1); // Enable 802.11d
-    //zfiWlanSetDot11HDFSMode(dev , 1); // Enable 802.11h DFS
-    wd->sta.DFSEnable = 1;
-    wd->sta.capability[1] |= ZM_BIT_0;
+	/* zfiWlanSetDot11DMode(dev , 1); // Enable 802.11d */
+	/* zfiWlanSetDot11HDFSMode(dev , 1); // Enable 802.11h DFS */
+	wd->sta.DFSEnable = 1;
+	wd->sta.capability[1] |= ZM_BIT_0;
 
-    //zfiWlanSetFrequency(dev, 5260000, TRUE);
-    //zfiWlanSetAniMode(dev , 1); // Enable ANI
+	/* zfiWlanSetFrequency(dev, 5260000, TRUE); */
+	/* zfiWlanSetAniMode(dev , 1); // Enable ANI */
 
-    /* Trgger Rx DMA */
-    zfHpStartRecv(dev);
+	/* Trgger Rx DMA */
+	zfHpStartRecv(dev);
 
-    zm_debug_msg0("end");
+	zm_debug_msg0("end");
 
-    return 0;
+	return 0;
 }
 
 /* WLAN hardware will be shutdown and all resource will be release */
-u16_t zfiWlanClose(zdev_t* dev)
+u16_t zfiWlanClose(zdev_t *dev)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    zm_msg0_init(ZM_LV_0, "enter");
+	zm_msg0_init(ZM_LV_0, "enter");
 
-    wd->state = ZM_WLAN_STATE_CLOSEDED;
+	wd->state = ZM_WLAN_STATE_CLOSEDED;
 
-    //zfiWlanDisable(dev, 1);
-    zfWlanReset(dev);
+	/* zfiWlanDisable(dev, 1); */
+	zfWlanReset(dev);
 
-    zfHpStopRecv(dev);
+	zfHpStopRecv(dev);
 
-    /* Disable MAC */
-    /* Disable PHY */
-    /* Disable RF */
+	/* Disable MAC */
+	/* Disable PHY */
+	/* Disable RF */
 
-    zfHpRelease(dev);
+	zfHpRelease(dev);
 
-    zfQueueDestroy(dev, wd->ap.uapsdQ);
-    zfQueueDestroy(dev, wd->sta.uapsdQ);
+	zfQueueDestroy(dev, wd->ap.uapsdQ);
+	zfQueueDestroy(dev, wd->sta.uapsdQ);
 
-    zfBssInfoDestroy(dev);
+	zfBssInfoDestroy(dev);
 
 #ifdef ZM_ENABLE_AGGREGATION
-    /* add by honda */
-    zfAggRxFreeBuf(dev, 1);  //1 for release structure memory
-    /* end of add by honda */
+	/* add by honda */
+	zfAggRxFreeBuf(dev, 1);  /* 1 for release structure memory */
+	/* end of add by honda */
 #endif
 
-    zm_msg0_init(ZM_LV_0, "exit");
+	zm_msg0_init(ZM_LV_0, "exit");
 
-    return 0;
+	return 0;
 }
 
-void zfGetWrapperSetting(zdev_t* dev)
+void zfGetWrapperSetting(zdev_t *dev)
 {
-    u8_t   bPassive;
-    u16_t vapId = 0;
+	u8_t bPassive;
+	u16_t vapId = 0;
 
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    zmw_declare_for_critical_section();
+	zmw_declare_for_critical_section();
 #if 0
-    if ( (wd->ws.countryIsoName[0] != 0)
-         || (wd->ws.countryIsoName[1] != 0)
-         || (wd->ws.countryIsoName[2] != '\0') )
-    {
-        zfHpGetRegulationTablefromRegionCode(
-            dev,
-            zfHpGetRegionCodeFromIsoName(dev, wd->ws.countryIsoName) );
-    }
+	if ((wd->ws.countryIsoName[0] != 0)
+		|| (wd->ws.countryIsoName[1] != 0)
+		|| (wd->ws.countryIsoName[2] != '\0')) {
+		zfHpGetRegulationTablefromRegionCode(dev,
+		zfHpGetRegionCodeFromIsoName(dev, wd->ws.countryIsoName));
+	}
 #endif
-    zmw_enter_critical_section(dev);
+	zmw_enter_critical_section(dev);
 
-    wd->wlanMode = wd->ws.wlanMode;
+	wd->wlanMode = wd->ws.wlanMode;
 
-    /* set channel */
-    if ( wd->ws.frequency )
-    {
-        wd->frequency = wd->ws.frequency;
-        wd->ws.frequency = 0;
-    }
-    else
-    {
-        wd->frequency = zfChGetFirstChannel(dev, &bPassive);
+	/* set channel */
+	if (wd->ws.frequency) {
+		wd->frequency = wd->ws.frequency;
+		wd->ws.frequency = 0;
+	} else {
+		wd->frequency = zfChGetFirstChannel(dev, &bPassive);
 
-        if ( wd->wlanMode == ZM_MODE_IBSS )
-        {
-            if (wd->ws.adhocMode == ZM_ADHOCBAND_A)
-            {
-                wd->frequency = ZM_CH_A_36;
-            }
-            else
-            {
-            wd->frequency = ZM_CH_G_6;
-            }
-        }
-    }
+		if (wd->wlanMode == ZM_MODE_IBSS) {
+			if (wd->ws.adhocMode == ZM_ADHOCBAND_A)
+				wd->frequency = ZM_CH_A_36;
+			else
+				wd->frequency = ZM_CH_G_6;
+		}
+	}
 #ifdef ZM_AP_DEBUG
-    /* honda add for debug, 2437 channel 6, 2452 channel 9 */
-    wd->frequency = 2437;
-    /* end of add by honda */
+	/* honda add for debug, 2437 channel 6, 2452 channel 9 */
+	wd->frequency = 2437;
+	/* end of add by honda */
 #endif
 
-    /* set preamble type */
-    switch (wd->ws.preambleType)
-    {
-    case ZM_PREAMBLE_TYPE_AUTO:
-    case ZM_PREAMBLE_TYPE_SHORT:
-    case ZM_PREAMBLE_TYPE_LONG:
-        wd->preambleType = wd->ws.preambleType;
-        break;
-    default:
-        wd->preambleType = ZM_PREAMBLE_TYPE_SHORT;
-        break;
-    }
-    wd->ws.preambleType = 0;
+	/* set preamble type */
+	switch (wd->ws.preambleType) {
+	case ZM_PREAMBLE_TYPE_AUTO:
+	case ZM_PREAMBLE_TYPE_SHORT:
+	case ZM_PREAMBLE_TYPE_LONG:
+		wd->preambleType = wd->ws.preambleType;
+		break;
+	default:
+		wd->preambleType = ZM_PREAMBLE_TYPE_SHORT;
+		break;
+	}
+	wd->ws.preambleType = 0;
 
-    if ( wd->wlanMode == ZM_MODE_AP )
-    {
-        vapId = zfwGetVapId(dev);
+	if (wd->wlanMode == ZM_MODE_AP) {
+		vapId = zfwGetVapId(dev);
 
-        if (vapId == 0xffff)
-        {
-            wd->ap.authAlgo[0] = wd->ws.authMode;
-            wd->ap.encryMode[0] = wd->ws.encryMode;
-        }
-        else
-        {
-            wd->ap.authAlgo[vapId + 1] = wd->ws.authMode;
-            wd->ap.encryMode[vapId + 1] = wd->ws.encryMode;
-        }
-        wd->ws.authMode = 0;
-        wd->ws.encryMode = ZM_NO_WEP;
+		if (vapId == 0xffff) {
+			wd->ap.authAlgo[0] = wd->ws.authMode;
+			wd->ap.encryMode[0] = wd->ws.encryMode;
+		} else {
+			wd->ap.authAlgo[vapId + 1] = wd->ws.authMode;
+			wd->ap.encryMode[vapId + 1] = wd->ws.encryMode;
+		}
+		wd->ws.authMode = 0;
+		wd->ws.encryMode = ZM_NO_WEP;
 
-        /* Get beaconInterval from WrapperSetting */
-        if ((wd->ws.beaconInterval >= 20) && (wd->ws.beaconInterval <= 1000))
-        {
-            wd->beaconInterval = wd->ws.beaconInterval;
-        }
-        else
-        {
-            wd->beaconInterval = 100; //100ms
-        }
+		/* Get beaconInterval from WrapperSetting */
+		if ((wd->ws.beaconInterval >= 20) &&
+					(wd->ws.beaconInterval <= 1000))
+			wd->beaconInterval = wd->ws.beaconInterval;
+		else
+			wd->beaconInterval = 100; /* 100ms */
 
-        if (wd->ws.dtim > 0)
-        {
-            wd->dtim = wd->ws.dtim;
-        }
-        else
-        {
-            wd->dtim = 1;
-        }
+		if (wd->ws.dtim > 0)
+			wd->dtim = wd->ws.dtim;
+		else
+			wd->dtim = 1;
 
-        wd->ap.qosMode = wd->ws.apWmeEnabled & 0x1;
-        wd->ap.uapsdEnabled = (wd->ws.apWmeEnabled & 0x2) >> 1;
-    }
-    else
-    {
-        wd->sta.authMode = wd->ws.authMode;
-        wd->sta.currentAuthMode = wd->ws.authMode;
-        wd->sta.wepStatus = wd->ws.wepStatus;
 
-        if ( wd->ws.beaconInterval )
-        {
-            wd->beaconInterval = wd->ws.beaconInterval;
-        }
-        else
-        {
-            wd->beaconInterval = 0x64;
-        }
+		wd->ap.qosMode = wd->ws.apWmeEnabled & 0x1;
+		wd->ap.uapsdEnabled = (wd->ws.apWmeEnabled & 0x2) >> 1;
+	} else {
+		wd->sta.authMode = wd->ws.authMode;
+		wd->sta.currentAuthMode = wd->ws.authMode;
+		wd->sta.wepStatus = wd->ws.wepStatus;
 
-        if ( wd->wlanMode == ZM_MODE_IBSS )
-        {
-            /* 1. Set default channel 6 (2437MHz) */
-//            wd->frequency = 2437;
+		if (wd->ws.beaconInterval)
+			wd->beaconInterval = wd->ws.beaconInterval;
+		else
+			wd->beaconInterval = 0x64;
 
-            /* 2. Otus support 802.11g Mode */
-            if ((wd->ws.adhocMode == ZM_ADHOCBAND_G) ||
-                (wd->ws.adhocMode == ZM_ADHOCBAND_BG) ||
-                (wd->ws.adhocMode == ZM_ADHOCBAND_ABG) ) {
-                wd->wfc.bIbssGMode = 1;
-            } else {
-                wd->wfc.bIbssGMode = 0;
-            }
+		if (wd->wlanMode == ZM_MODE_IBSS) {
+			/* 1. Set default channel 6 (2437MHz) */
+			/* wd->frequency = 2437; */
 
-            /* 3. set short preamble  */
-            //wd->sta.preambleType = ZM_PREAMBLE_TYPE_SHORT ;
-        }
+			/* 2. Otus support 802.11g Mode */
+			if ((wd->ws.adhocMode == ZM_ADHOCBAND_G) ||
+				(wd->ws.adhocMode == ZM_ADHOCBAND_BG) ||
+				(wd->ws.adhocMode == ZM_ADHOCBAND_ABG))
+				wd->wfc.bIbssGMode = 1;
+			else
+				wd->wfc.bIbssGMode = 0;
 
-        /* set ATIM window */
-        if ( wd->ws.atimWindow )
-        {
-            wd->sta.atimWindow = wd->ws.atimWindow;
-        }
-        else
-        {
-            //wd->sta.atimWindow = 0x0a;
-            wd->sta.atimWindow = 0;
-        }
+			/* 3. set short preamble  */
+			/* wd->sta.preambleType = ZM_PREAMBLE_TYPE_SHORT; */
+		}
 
-        //wd->sta.connectingHiddenAP = 1;//wd->ws.connectingHiddenAP;
-        wd->sta.dropUnencryptedPkts = wd->ws.dropUnencryptedPkts;
-        wd->sta.ibssJoinOnly = wd->ws.ibssJoinOnly;
+		/* set ATIM window */
+		if (wd->ws.atimWindow)
+			wd->sta.atimWindow = wd->ws.atimWindow;
+		else {
+			/* wd->sta.atimWindow = 0x0a; */
+			wd->sta.atimWindow = 0;
+		}
 
-        if ( wd->ws.bDesiredBssid )
-        {
-            zfMemoryCopy(wd->sta.desiredBssid, wd->ws.desiredBssid, 6);
-            wd->sta.bDesiredBssid = TRUE;
-            wd->ws.bDesiredBssid = FALSE;
-        }
-        else
-        {
-            wd->sta.bDesiredBssid = FALSE;
-        }
+		/* wd->sta.connectingHiddenAP = 1;
+		   wd->ws.connectingHiddenAP;
+		*/
+		wd->sta.dropUnencryptedPkts = wd->ws.dropUnencryptedPkts;
+		wd->sta.ibssJoinOnly = wd->ws.ibssJoinOnly;
 
-        /* check ssid */
-        if ( wd->ws.ssidLen != 0 )
-        {
-            if ( (!zfMemoryIsEqual(wd->ws.ssid, wd->sta.ssid,
-                                   wd->sta.ssidLen))||
-                 (wd->ws.ssidLen != wd->sta.ssidLen)||
-                 (wd->sta.authMode == ZM_AUTH_MODE_WPA)||
-                 (wd->sta.authMode == ZM_AUTH_MODE_WPAPSK) ||
-                 (wd->ws.staWmeQosInfo!= 0) )
-            {
-                /*if u-APSD test(set QosInfo), clear connectByReasso to do association (not reassociation)*/
-                wd->sta.connectByReasso = FALSE;
-                wd->sta.failCntOfReasso = 0;
-                wd->sta.pmkidInfo.bssidCount = 0;
+		if (wd->ws.bDesiredBssid) {
+			zfMemoryCopy(wd->sta.desiredBssid,
+						wd->ws.desiredBssid, 6);
+			wd->sta.bDesiredBssid = TRUE;
+			wd->ws.bDesiredBssid = FALSE;
+		} else
+			wd->sta.bDesiredBssid = FALSE;
 
-                wd->sta.ssidLen = wd->ws.ssidLen;
-                zfMemoryCopy(wd->sta.ssid, wd->ws.ssid, wd->sta.ssidLen);
+		/* check ssid */
+		if (wd->ws.ssidLen != 0) {
+			if ((!zfMemoryIsEqual(wd->ws.ssid, wd->sta.ssid,
+				wd->sta.ssidLen)) ||
+				(wd->ws.ssidLen != wd->sta.ssidLen) ||
+				(wd->sta.authMode == ZM_AUTH_MODE_WPA) ||
+				(wd->sta.authMode == ZM_AUTH_MODE_WPAPSK) ||
+				(wd->ws.staWmeQosInfo != 0)) {
+				/* if u-APSD test(set QosInfo), clear
+				   connectByReasso to do association
+				   (not reassociation)
+				*/
+				wd->sta.connectByReasso = FALSE;
+				wd->sta.failCntOfReasso = 0;
+				wd->sta.pmkidInfo.bssidCount = 0;
 
-                if ( wd->sta.ssidLen < 32 )
-                {
-                    wd->sta.ssid[wd->sta.ssidLen] = 0;
-                }
-            }
-        }
-        else
-        {   /* ANY BSS */
-            wd->sta.ssid[0] = 0;
-            wd->sta.ssidLen = 0;
-        }
+				wd->sta.ssidLen = wd->ws.ssidLen;
+				zfMemoryCopy(wd->sta.ssid, wd->ws.ssid,
+							wd->sta.ssidLen);
 
-        wd->sta.wmeEnabled = wd->ws.staWmeEnabled;
-        wd->sta.wmeQosInfo = wd->ws.staWmeQosInfo;
+				if (wd->sta.ssidLen < 32)
+					wd->sta.ssid[wd->sta.ssidLen] = 0;
+			}
+		} else {
+			/* ANY BSS */
+			wd->sta.ssid[0] = 0;
+			wd->sta.ssidLen = 0;
+		}
 
-    }
+		wd->sta.wmeEnabled = wd->ws.staWmeEnabled;
+		wd->sta.wmeQosInfo = wd->ws.staWmeQosInfo;
 
-    zmw_leave_critical_section(dev);
+	}
+
+	zmw_leave_critical_section(dev);
 }
 
-u16_t zfWlanEnable(zdev_t* dev)
+u16_t zfWlanEnable(zdev_t *dev)
 {
-    u8_t     bssid[6] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
-    u16_t i;
+	u8_t bssid[6] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
+	u16_t i;
 
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    zmw_declare_for_critical_section();
+	zmw_declare_for_critical_section();
 
-    if ( wd->wlanMode == ZM_MODE_UNKNOWN )
-    {
-        zm_debug_msg0("Unknown Mode...Skip...");
-        return 0;
-    }
+	if (wd->wlanMode == ZM_MODE_UNKNOWN) {
+		zm_debug_msg0("Unknown Mode...Skip...");
+		return 0;
+	}
 
-    if (wd->wlanMode == ZM_MODE_AP)
-    {
-        u16_t vapId;
+	if (wd->wlanMode == ZM_MODE_AP) {
+		u16_t vapId;
 
-        vapId = zfwGetVapId(dev);
+		vapId = zfwGetVapId(dev);
 
-        if (vapId == 0xffff)
-        {
-            /* AP mode */
-            zfApInitStaTbl(dev);
+		if (vapId == 0xffff) {
+			/* AP mode */
+			zfApInitStaTbl(dev);
 
-            /* AP default parameters */
-            wd->bRate = 0xf;
-            wd->gRate = 0xff;
-            wd->bRateBasic = 0xf;
-            wd->gRateBasic = 0x0;
-            //wd->beaconInterval = 100;
-            wd->ap.apBitmap = 1;
-            wd->ap.beaconCounter = 0;
-            //wd->ap.vapNumber = 1;    //mark by ygwei for Vap
+			/* AP default parameters */
+			wd->bRate = 0xf;
+			wd->gRate = 0xff;
+			wd->bRateBasic = 0xf;
+			wd->gRateBasic = 0x0;
+			/* wd->beaconInterval = 100; */
+			wd->ap.apBitmap = 1;
+			wd->ap.beaconCounter = 0;
+			/* wd->ap.vapNumber = 1; //mark by ygwei for Vap */
 
-            wd->ap.hideSsid[0] = 0;
-            wd->ap.staAgingTimeSec = 10*60;
-            wd->ap.staProbingTimeSec = 60;
+			wd->ap.hideSsid[0] = 0;
+			wd->ap.staAgingTimeSec = 10*60;
+			wd->ap.staProbingTimeSec = 60;
 
-            for (i=0; i<ZM_MAX_AP_SUPPORT; i++)
-            {
-                wd->ap.bcmcHead[i] = wd->ap.bcmcTail[i] = 0;
-            }
+			for (i = 0; i < ZM_MAX_AP_SUPPORT; i++)
+				wd->ap.bcmcHead[i] = wd->ap.bcmcTail[i] = 0;
 
-            //wd->ap.uniHead = wd->ap.uniTail = 0;
+			/* wd->ap.uniHead = wd->ap.uniTail = 0; */
 
-            /* load AP parameters */
-            wd->bRateBasic = wd->ws.bRateBasic;
-            wd->gRateBasic = wd->ws.gRateBasic;
-            wd->bgMode = wd->ws.bgMode;
-            if ((wd->ws.ssidLen <= 32) && (wd->ws.ssidLen != 0))
-            {
-                wd->ap.ssidLen[0] = wd->ws.ssidLen;
-                for(i=0; i<wd->ws.ssidLen; i++)
-                {
-                    wd->ap.ssid[0][i] = wd->ws.ssid[i];
-                }
-                wd->ws.ssidLen = 0; // Reset Wrapper Variable
-            }
+			/* load AP parameters */
+			wd->bRateBasic = wd->ws.bRateBasic;
+			wd->gRateBasic = wd->ws.gRateBasic;
+			wd->bgMode = wd->ws.bgMode;
+			if ((wd->ws.ssidLen <= 32) && (wd->ws.ssidLen != 0)) {
+				wd->ap.ssidLen[0] = wd->ws.ssidLen;
+				for (i = 0; i < wd->ws.ssidLen; i++)
+					wd->ap.ssid[0][i] = wd->ws.ssid[i];
+				wd->ws.ssidLen = 0; /* Reset Wrapper Variable */
+			}
 
-            if (wd->ap.encryMode[0] == 0)
-            {
-                wd->ap.capab[0] = 0x001;
-            }
-            else
-            {
-                wd->ap.capab[0] = 0x011;
-            }
-            /* set Short Slot Time bit if not 11b */
-            if (wd->ap.wlanType[0] != ZM_WLAN_TYPE_PURE_B)
-            {
-              wd->ap.capab[0] |= 0x400;
-            }
+			if (wd->ap.encryMode[0] == 0)
+				wd->ap.capab[0] = 0x001;
+			else
+				wd->ap.capab[0] = 0x011;
+			/* set Short Slot Time bit if not 11b */
+			if (wd->ap.wlanType[0] != ZM_WLAN_TYPE_PURE_B)
+				wd->ap.capab[0] |= 0x400;
 
-            // wd->ap.vapNumber = 1;    // mark by ygwei for Vap Test
-        }
-        else
-        {
+			/* wd->ap.vapNumber = 1; //mark by ygwei for Vap Test */
+		} else {
 #if 0
-            /* VAP Test Code */
-            wd->ap.apBitmap = 0x3;
-            wd->ap.capab[1] = 0x401;
-            wd->ap.ssidLen[1] = 4;
-            wd->ap.ssid[1][0] = 'v';
-            wd->ap.ssid[1][1] = 'a';
-            wd->ap.ssid[1][2] = 'p';
-            wd->ap.ssid[1][3] = '1';
-            wd->ap.authAlgo[1] = wd->ws.authMode;
-            wd->ap.encryMode[1] = wd->ws.encryMode;
-            wd->ap.vapNumber = 2;
+			/* VAP Test Code */
+			wd->ap.apBitmap = 0x3;
+			wd->ap.capab[1] = 0x401;
+			wd->ap.ssidLen[1] = 4;
+			wd->ap.ssid[1][0] = 'v';
+			wd->ap.ssid[1][1] = 'a';
+			wd->ap.ssid[1][2] = 'p';
+			wd->ap.ssid[1][3] = '1';
+			wd->ap.authAlgo[1] = wd->ws.authMode;
+			wd->ap.encryMode[1] = wd->ws.encryMode;
+			wd->ap.vapNumber = 2;
 #else
-            /* VAP Test Code */
-            wd->ap.apBitmap = 0x1 | (0x01 << (vapId+1));
+			/* VAP Test Code */
+			wd->ap.apBitmap = 0x1 | (0x01 << (vapId+1));
 
-            if ((wd->ws.ssidLen <= 32) && (wd->ws.ssidLen != 0))
-            {
-                wd->ap.ssidLen[vapId+1] = wd->ws.ssidLen;
-                for(i=0; i<wd->ws.ssidLen; i++)
-                {
-                    wd->ap.ssid[vapId+1][i] = wd->ws.ssid[i];
-                }
-                wd->ws.ssidLen = 0; // Reset Wrapper Variable
-            }
+			if ((wd->ws.ssidLen <= 32) && (wd->ws.ssidLen != 0)) {
+				wd->ap.ssidLen[vapId+1] = wd->ws.ssidLen;
+				for (i = 0; i < wd->ws.ssidLen; i++)
+					wd->ap.ssid[vapId+1][i] =
+								wd->ws.ssid[i];
+				wd->ws.ssidLen = 0; /* Reset Wrapper Variable */
+			}
 
-            if (wd->ap.encryMode[vapId+1] == 0)
-            {
-                wd->ap.capab[vapId+1] = 0x401;
-            }
-            else
-            {
-                wd->ap.capab[vapId+1] = 0x411;
-            }
+			if (wd->ap.encryMode[vapId+1] == 0)
+				wd->ap.capab[vapId+1] = 0x401;
+			else
+				wd->ap.capab[vapId+1] = 0x411;
 
-            wd->ap.authAlgo[vapId+1] = wd->ws.authMode;
-            wd->ap.encryMode[vapId+1] = wd->ws.encryMode;
+			wd->ap.authAlgo[vapId+1] = wd->ws.authMode;
+			wd->ap.encryMode[vapId+1] = wd->ws.encryMode;
 
-            /* Need to be modified when VAP is used */
-            //wd->ap.vapNumber = 2;
+			/* Need to be modified when VAP is used */
+			/* wd->ap.vapNumber = 2; */
 #endif
-        }
+		}
 
-        wd->ap.vapNumber++;
+		wd->ap.vapNumber++;
 
-        zfCoreSetFrequency(dev, wd->frequency);
+		zfCoreSetFrequency(dev, wd->frequency);
 
-        zfInitMacApMode(dev);
+		zfInitMacApMode(dev);
 
-        /* Disable protection mode */
-        zfApSetProtectionMode(dev, 0);
+		/* Disable protection mode */
+		zfApSetProtectionMode(dev, 0);
 
-        zfApSendBeacon(dev);
-    } /*if (wd->wlanMode == ZM_MODE_AP) */
-    else
-    {
-        zfScanMgrScanStop(dev, ZM_SCAN_MGR_SCAN_INTERNAL);
-        zfScanMgrScanStop(dev, ZM_SCAN_MGR_SCAN_EXTERNAL);
+		zfApSendBeacon(dev);
+	} else { /*if (wd->wlanMode == ZM_MODE_AP) */
 
-        zmw_enter_critical_section(dev);
-        wd->sta.oppositeCount = 0;    /* reset opposite count */
-        //wd->sta.bAutoReconnect = wd->sta.bAutoReconnectEnabled;
-        //wd->sta.scanWithSSID = 0;
-        zfStaInitOppositeInfo(dev);
-        zmw_leave_critical_section(dev);
+		zfScanMgrScanStop(dev, ZM_SCAN_MGR_SCAN_INTERNAL);
+		zfScanMgrScanStop(dev, ZM_SCAN_MGR_SCAN_EXTERNAL);
 
-        zfStaResetStatus(dev, 0);
+		zmw_enter_critical_section(dev);
+		wd->sta.oppositeCount = 0;    /* reset opposite count */
+		/* wd->sta.bAutoReconnect = wd->sta.bAutoReconnectEnabled; */
+		/* wd->sta.scanWithSSID = 0; */
+		zfStaInitOppositeInfo(dev);
+		zmw_leave_critical_section(dev);
 
-        if ( (wd->sta.cmDisallowSsidLength != 0)&&
-             (wd->sta.ssidLen == wd->sta.cmDisallowSsidLength)&&
-             (zfMemoryIsEqual(wd->sta.ssid, wd->sta.cmDisallowSsid,
-                              wd->sta.ssidLen)) &&
-             (wd->sta.wepStatus == ZM_ENCRYPTION_TKIP))
-        {   /* countermeasures */
-            zm_debug_msg0("countermeasures disallow association");
+		zfStaResetStatus(dev, 0);
 
-        }
-        else
-        {
-            switch( wd->wlanMode )
-            {
-                case ZM_MODE_IBSS:
-                    /* some registers may be set here */
-                    if ( wd->sta.authMode == ZM_AUTH_MODE_WPA2PSK )
-                    {
-                        zfHpSetApStaMode(dev, ZM_HAL_80211_MODE_IBSS_WPA2PSK);
-                    }
-                    else
-                    {
-                        zfHpSetApStaMode(dev, ZM_HAL_80211_MODE_IBSS_GENERAL);
-                    }
+		if ((wd->sta.cmDisallowSsidLength != 0) &&
+		(wd->sta.ssidLen == wd->sta.cmDisallowSsidLength) &&
+		(zfMemoryIsEqual(wd->sta.ssid, wd->sta.cmDisallowSsid,
+		wd->sta.ssidLen)) &&
+		(wd->sta.wepStatus == ZM_ENCRYPTION_TKIP)) {/*countermeasures*/
+			zm_debug_msg0("countermeasures disallow association");
+		} else {
+			switch (wd->wlanMode) {
+			case ZM_MODE_IBSS:
+				/* some registers may be set here */
+				if (wd->sta.authMode == ZM_AUTH_MODE_WPA2PSK)
+					zfHpSetApStaMode(dev,
+					ZM_HAL_80211_MODE_IBSS_WPA2PSK);
+				else
+					zfHpSetApStaMode(dev,
+					ZM_HAL_80211_MODE_IBSS_GENERAL);
 
-                    zm_msg0_mm(ZM_LV_0, "ZM_MODE_IBSS");
-                    zfIbssConnectNetwork(dev);
-                    break;
+				zm_msg0_mm(ZM_LV_0, "ZM_MODE_IBSS");
+				zfIbssConnectNetwork(dev);
+				break;
 
-                case ZM_MODE_INFRASTRUCTURE:
-                    /* some registers may be set here */
-                    zfHpSetApStaMode(dev, ZM_HAL_80211_MODE_STA);
+			case ZM_MODE_INFRASTRUCTURE:
+				/* some registers may be set here */
+				zfHpSetApStaMode(dev, ZM_HAL_80211_MODE_STA);
 
-                    zfInfraConnectNetwork(dev);
-                    break;
+				zfInfraConnectNetwork(dev);
+				break;
 
-                case ZM_MODE_PSEUDO:
-                    /* some registers may be set here */
-                    zfHpSetApStaMode(dev, ZM_HAL_80211_MODE_STA);
+			case ZM_MODE_PSEUDO:
+				/* some registers may be set here */
+				zfHpSetApStaMode(dev, ZM_HAL_80211_MODE_STA);
 
-                    zfUpdateBssid(dev, bssid);
-                    zfCoreSetFrequency(dev, wd->frequency);
-                    break;
+				zfUpdateBssid(dev, bssid);
+				zfCoreSetFrequency(dev, wd->frequency);
+				break;
 
-                default:
-                    break;
-            }
-        }
+			default:
+				break;
+			}
+		}
 
-    }
+	}
 
 
-    //if ( (wd->wlanMode != ZM_MODE_INFRASTRUCTURE)&&
-    //     (wd->wlanMode != ZM_MODE_AP) )
-    if ( wd->wlanMode == ZM_MODE_PSEUDO )
-    {
-        /* Reset Wlan status */
-        zfWlanReset(dev);
+	/* if ((wd->wlanMode != ZM_MODE_INFRASTRUCTURE) &&
+		(wd->wlanMode != ZM_MODE_AP))
+	*/
+	if (wd->wlanMode == ZM_MODE_PSEUDO) {
+		/* Reset Wlan status */
+		zfWlanReset(dev);
 
-        if (wd->zfcbConnectNotify != NULL)
-        {
-            wd->zfcbConnectNotify(dev, ZM_STATUS_MEDIA_CONNECT, wd->sta.bssid);
-        }
-        zfChangeAdapterState(dev, ZM_STA_STATE_CONNECTED);
-    }
+		if (wd->zfcbConnectNotify != NULL)
+			wd->zfcbConnectNotify(dev, ZM_STATUS_MEDIA_CONNECT,
+								wd->sta.bssid);
+		zfChangeAdapterState(dev, ZM_STA_STATE_CONNECTED);
+	}
 
 
-    if(wd->wlanMode == ZM_MODE_AP)
-    {
-        if (wd->zfcbConnectNotify != NULL)
-        {
-            wd->zfcbConnectNotify(dev, ZM_STATUS_MEDIA_CONNECT, wd->sta.bssid);
-        }
-        //zfChangeAdapterState(dev, ZM_STA_STATE_CONNECTED);
-    }
+	if (wd->wlanMode == ZM_MODE_AP) {
+		if (wd->zfcbConnectNotify != NULL)
+			wd->zfcbConnectNotify(dev, ZM_STATUS_MEDIA_CONNECT,
+								wd->sta.bssid);
+		/* zfChangeAdapterState(dev, ZM_STA_STATE_CONNECTED); */
+	}
 
-    // Assign default Tx Rate
-    if ( wd->sta.EnableHT )
-    {
+	/* Assign default Tx Rate */
+	if (wd->sta.EnableHT) {
 		u32_t oneTxStreamCap;
-		oneTxStreamCap = (zfHpCapability(dev) & ZM_HP_CAP_11N_ONE_TX_STREAM);
-		if(oneTxStreamCap)
+		oneTxStreamCap = (zfHpCapability(dev) &
+						ZM_HP_CAP_11N_ONE_TX_STREAM);
+		if (oneTxStreamCap)
 			wd->CurrentTxRateKbps = 135000;
 		else
 			wd->CurrentTxRateKbps = 270000;
-        wd->CurrentRxRateKbps = 270000;
-    }
-    else
-    {
-        wd->CurrentTxRateKbps = 54000;
-        wd->CurrentRxRateKbps = 54000;
-    }
+		wd->CurrentRxRateKbps = 270000;
+	} else {
+		wd->CurrentTxRateKbps = 54000;
+		wd->CurrentRxRateKbps = 54000;
+	}
 
-    wd->state = ZM_WLAN_STATE_ENABLED;
+	wd->state = ZM_WLAN_STATE_ENABLED;
 
-    return 0;
+	return 0;
 }
 
 /* Enable/disable Wlan operation */
-u16_t zfiWlanEnable(zdev_t* dev)
+u16_t zfiWlanEnable(zdev_t *dev)
 {
-    u16_t ret;
+	u16_t ret;
 
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    zm_msg0_mm(ZM_LV_1, "Enable Wlan");
+	zm_msg0_mm(ZM_LV_1, "Enable Wlan");
 
-    zfGetWrapperSetting(dev);
+	zfGetWrapperSetting(dev);
 
-    zfZeroMemory((u8_t*) &wd->trafTally, sizeof(struct zsTrafTally));
+	zfZeroMemory((u8_t *) &wd->trafTally, sizeof(struct zsTrafTally));
 
-    // Reset cmMicFailureCount to 0 for new association request
-    if ( wd->sta.cmMicFailureCount == 1 )
-    {
-        zfTimerCancel(dev, ZM_EVENT_CM_TIMER);
-        wd->sta.cmMicFailureCount = 0;
-    }
+	/* Reset cmMicFailureCount to 0 for new association request */
+	if (wd->sta.cmMicFailureCount == 1) {
+		zfTimerCancel(dev, ZM_EVENT_CM_TIMER);
+		wd->sta.cmMicFailureCount = 0;
+	}
 
-    zfFlushVtxq(dev);
-    if ((wd->queueFlushed & 0x10) != 0)
-    {
-        zfHpUsbReset(dev);
-    }
-    ret = zfWlanEnable(dev);
+	zfFlushVtxq(dev);
+	if ((wd->queueFlushed & 0x10) != 0)
+		zfHpUsbReset(dev);
 
-    return ret;
+	ret = zfWlanEnable(dev);
+
+	return ret;
 }
 /* Add a flag named ResetKeyCache to show if KeyCache should be cleared.
    for hostapd in AP mode, if driver receives iwconfig ioctl
-   after setting group key, it shouldn't clear KeyCache.                 */
-u16_t zfiWlanDisable(zdev_t* dev, u8_t ResetKeyCache)
+   after setting group key, it shouldn't clear KeyCache.
+*/
+u16_t zfiWlanDisable(zdev_t *dev, u8_t ResetKeyCache)
 {
-    u16_t  i;
-    u8_t isConnected;
+	u16_t  i;
+	u8_t isConnected;
 
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
 #ifdef ZM_ENABLE_IBSS_WPA2PSK
-    zmw_declare_for_critical_section();
+	zmw_declare_for_critical_section();
 #endif
-    wd->state = ZM_WLAN_STATE_DISABLED;
+	wd->state = ZM_WLAN_STATE_DISABLED;
 
-    zm_msg0_mm(ZM_LV_1, "Disable Wlan");
+	zm_msg0_mm(ZM_LV_1, "Disable Wlan");
 
-    if ( wd->wlanMode != ZM_MODE_AP )
-    {
-        isConnected = zfStaIsConnected(dev);
+	if (wd->wlanMode != ZM_MODE_AP) {
+		isConnected = zfStaIsConnected(dev);
 
-        if ( (wd->wlanMode == ZM_MODE_INFRASTRUCTURE)&&
-             (wd->sta.currentAuthMode != ZM_AUTH_MODE_WPA2) )
-        {
-            /* send deauthentication frame */
-            if (isConnected)
-            {
-                //zfiWlanDeauth(dev, NULL, 0);
-                zfSendMmFrame(dev, ZM_WLAN_FRAME_TYPE_DEAUTH, wd->sta.bssid, 3, 0, 0);
-                //zmw_debug_msg0("send a Deauth frame!");
-            }
-        }
+		if ((wd->wlanMode == ZM_MODE_INFRASTRUCTURE) &&
+			(wd->sta.currentAuthMode != ZM_AUTH_MODE_WPA2)) {
+			/* send deauthentication frame */
+			if (isConnected) {
+				/* zfiWlanDeauth(dev, NULL, 0); */
+				zfSendMmFrame(dev, ZM_WLAN_FRAME_TYPE_DEAUTH,
+						wd->sta.bssid, 3, 0, 0);
+				/* zmw_debug_msg0("send a Deauth frame!"); */
+			}
+		}
 
-        // Remove all the connected peer stations
-        if ( wd->wlanMode == ZM_MODE_IBSS )
-        {
-            wd->sta.ibssBssIsCreator = 0;
-            zfTimerCancel(dev, ZM_EVENT_IBSS_MONITOR);
-            zfStaIbssMonitoring(dev, 1);
-        }
+		/* Remove all the connected peer stations */
+		if (wd->wlanMode == ZM_MODE_IBSS) {
+			wd->sta.ibssBssIsCreator = 0;
+			zfTimerCancel(dev, ZM_EVENT_IBSS_MONITOR);
+			zfStaIbssMonitoring(dev, 1);
+		}
 
 #ifdef ZM_ENABLE_IBSS_WPA2PSK
-        zmw_enter_critical_section(dev);
-        wd->sta.ibssWpa2Psk = 0;
-        zmw_leave_critical_section(dev);
+		zmw_enter_critical_section(dev);
+		wd->sta.ibssWpa2Psk = 0;
+		zmw_leave_critical_section(dev);
 #endif
 
-        wd->sta.wpaState = ZM_STA_WPA_STATE_INIT;
+		wd->sta.wpaState = ZM_STA_WPA_STATE_INIT;
 
-        /* reset connect timeout counter */
-        wd->sta.connectTimeoutCount = 0;
+		/* reset connect timeout counter */
+		wd->sta.connectTimeoutCount = 0;
 
-        /* reset connectState to None */
-        wd->sta.connectState = ZM_STA_CONN_STATE_NONE;
+		/* reset connectState to None */
+		wd->sta.connectState = ZM_STA_CONN_STATE_NONE;
 
-        /* reset leap enable variable */
-        wd->sta.leapEnabled = 0;
+		/* reset leap enable variable */
+		wd->sta.leapEnabled = 0;
 
-        /* Disable the RIFS Status / RIFS-like frame count / RIFS count */
-        if( wd->sta.rifsState == ZM_RIFS_STATE_DETECTED )
-            zfHpDisableRifs(dev);
-        wd->sta.rifsState = ZM_RIFS_STATE_DETECTING;
-        wd->sta.rifsLikeFrameCnt = 0;
-        wd->sta.rifsCount = 0;
+		/* Disable the RIFS Status/RIFS-like frame count/RIFS count */
+		if (wd->sta.rifsState == ZM_RIFS_STATE_DETECTED)
+			zfHpDisableRifs(dev);
+		wd->sta.rifsState = ZM_RIFS_STATE_DETECTING;
+		wd->sta.rifsLikeFrameCnt = 0;
+		wd->sta.rifsCount = 0;
 
-        wd->sta.osRxFilter = 0;
-        wd->sta.bSafeMode = 0;
+		wd->sta.osRxFilter = 0;
+		wd->sta.bSafeMode = 0;
 
-        zfChangeAdapterState(dev, ZM_STA_STATE_DISCONNECT);
-        if (ResetKeyCache)
-            zfHpResetKeyCache(dev);
+		zfChangeAdapterState(dev, ZM_STA_STATE_DISCONNECT);
+		if (ResetKeyCache)
+			zfHpResetKeyCache(dev);
 
-        if (isConnected)
-        {
-            if (wd->zfcbConnectNotify != NULL)
-            {
-                wd->zfcbConnectNotify(dev, ZM_STATUS_MEDIA_CONNECTION_DISABLED, wd->sta.bssid);
-            }
-        }
-        else
-        {
-            if (wd->zfcbConnectNotify != NULL)
-            {
-                wd->zfcbConnectNotify(dev, ZM_STATUS_MEDIA_DISABLED, wd->sta.bssid);
-            }
-        }
-    }
-    else //if (wd->wlanMode == ZM_MODE_AP)
-    {
-        for (i=0; i<ZM_MAX_STA_SUPPORT; i++)
-        {
-            /* send deauthentication frame */
-            if (wd->ap.staTable[i].valid == 1)
-            {
-                /* Reason : Sending station is leaving */
-                zfSendMmFrame(dev, ZM_WLAN_FRAME_TYPE_DEAUTH,
-                        wd->ap.staTable[i].addr, 3, 0, 0);
-            }
-        }
+		if (isConnected) {
+			if (wd->zfcbConnectNotify != NULL)
+				wd->zfcbConnectNotify(dev,
+				ZM_STATUS_MEDIA_CONNECTION_DISABLED,
+				wd->sta.bssid);
+		} else {
+			if (wd->zfcbConnectNotify != NULL)
+				wd->zfcbConnectNotify(dev,
+				ZM_STATUS_MEDIA_DISABLED, wd->sta.bssid);
+		}
+	} else { /* if (wd->wlanMode == ZM_MODE_AP) */
+		for (i = 0; i < ZM_MAX_STA_SUPPORT; i++) {
+			/* send deauthentication frame */
+			if (wd->ap.staTable[i].valid == 1) {
+				/* Reason : Sending station is leaving */
+				zfSendMmFrame(dev, ZM_WLAN_FRAME_TYPE_DEAUTH,
+				wd->ap.staTable[i].addr, 3, 0, 0);
+			}
+		}
 
-        if (ResetKeyCache)
-            zfHpResetKeyCache(dev);
+		if (ResetKeyCache)
+			zfHpResetKeyCache(dev);
 
-        wd->ap.vapNumber--;
-    }
+		wd->ap.vapNumber--;
+	}
 
-    /* stop beacon */
-    zfHpDisableBeacon(dev);
+	/* stop beacon */
+	zfHpDisableBeacon(dev);
 
-    /* Flush VTxQ and MmQ */
-    zfFlushVtxq(dev);
-    /* Flush AP PS queues */
-    zfApFlushBufferedPsFrame(dev);
-    /* Free buffer in defragment list*/
-    zfAgingDefragList(dev, 1);
+	/* Flush VTxQ and MmQ */
+	zfFlushVtxq(dev);
+	/* Flush AP PS queues */
+	zfApFlushBufferedPsFrame(dev);
+	/* Free buffer in defragment list*/
+	zfAgingDefragList(dev, 1);
 
-    #ifdef ZM_ENABLE_AGGREGATION
-    /* add by honda */
-    zfAggRxFreeBuf(dev, 0);  //1 for release structure memory
-    /* end of add by honda */
-    #endif
+#ifdef ZM_ENABLE_AGGREGATION
+	/* add by honda */
+	zfAggRxFreeBuf(dev, 0);  /* 1 for release structure memory */
+	/* end of add by honda */
+#endif
 
-    // Clear the information for the peer stations of IBSS or AP of Station mode
-    zfZeroMemory((u8_t*)wd->sta.oppositeInfo, sizeof(struct zsOppositeInfo) * ZM_MAX_OPPOSITE_COUNT);
+	/* Clear the information for the peer stations
+	of IBSS or AP of Station mode
+	*/
+	zfZeroMemory((u8_t *)wd->sta.oppositeInfo,
+			sizeof(struct zsOppositeInfo) * ZM_MAX_OPPOSITE_COUNT);
 
-    /* Turn off Software WEP/TKIP */
-    if (wd->sta.SWEncryptEnable != 0)
-    {
-        zm_debug_msg0("Disable software encryption");
-        zfStaDisableSWEncryption(dev);
-    }
+	/* Turn off Software WEP/TKIP */
+	if (wd->sta.SWEncryptEnable != 0) {
+		zm_debug_msg0("Disable software encryption");
+		zfStaDisableSWEncryption(dev);
+	}
 
-    /* Improve WEP/TKIP performace with HT AP, detail information please look bug#32495 */
-    //zfHpSetTTSIFSTime(dev, 0x8);
+	/* Improve WEP/TKIP performace with HT AP,
+	detail information please look bug#32495 */
+	/* zfHpSetTTSIFSTime(dev, 0x8); */
 
-    return 0;
+	return 0;
 }
 
-u16_t zfiWlanSuspend(zdev_t* dev)
+u16_t zfiWlanSuspend(zdev_t *dev)
 {
-    zmw_get_wlan_dev(dev);
-    zmw_declare_for_critical_section();
+	zmw_get_wlan_dev(dev);
+	zmw_declare_for_critical_section();
 
-    // Change the HAL state to init so that any packet can't be transmitted between
-    // resume & HAL reinit. This would cause the chip hang issue in OTUS.
-    zmw_enter_critical_section(dev);
-    wd->halState = ZM_HAL_STATE_INIT;
-    zmw_leave_critical_section(dev);
+	/* Change the HAL state to init so that any packet
+	can't be transmitted between resume & HAL reinit.
+	This would cause the chip hang issue in OTUS.
+	*/
+	zmw_enter_critical_section(dev);
+	wd->halState = ZM_HAL_STATE_INIT;
+	zmw_leave_critical_section(dev);
 
-    return 0;
+	return 0;
 }
 
-u16_t zfiWlanResume(zdev_t* dev, u8_t doReconn)
+u16_t zfiWlanResume(zdev_t *dev, u8_t doReconn)
 {
-    u16_t ret;
-    zmw_get_wlan_dev(dev);
-    zmw_declare_for_critical_section();
+	u16_t ret;
+	zmw_get_wlan_dev(dev);
+	zmw_declare_for_critical_section();
 
-    /* Redownload firmware, Reinit MAC,PHY,RF */
-    zfHpReinit(dev, wd->frequency);
+	/* Redownload firmware, Reinit MAC,PHY,RF */
+	zfHpReinit(dev, wd->frequency);
 
-    //Set channel according to AP's configuration
-    zfCoreSetFrequencyExV2(dev, wd->frequency, wd->BandWidth40,
-            wd->ExtOffset, NULL, 1);
+	/* Set channel according to AP's configuration */
+	zfCoreSetFrequencyExV2(dev, wd->frequency, wd->BandWidth40,
+		wd->ExtOffset, NULL, 1);
 
-    zfHpSetMacAddress(dev, wd->macAddr, 0);
+	zfHpSetMacAddress(dev, wd->macAddr, 0);
 
-    /* Start Rx */
-    zfHpStartRecv(dev);
+	/* Start Rx */
+	zfHpStartRecv(dev);
 
-    zfFlushVtxq(dev);
+	zfFlushVtxq(dev);
 
-    if ( wd->wlanMode != ZM_MODE_INFRASTRUCTURE &&
-         wd->wlanMode != ZM_MODE_IBSS )
-    {
-        return 1;
-    }
+	if (wd->wlanMode != ZM_MODE_INFRASTRUCTURE &&
+			wd->wlanMode != ZM_MODE_IBSS)
+		return 1;
 
-    zm_msg0_mm(ZM_LV_1, "Resume Wlan");
-    if ( (zfStaIsConnected(dev)) || (zfStaIsConnecting(dev)) )
-    {
-        if (doReconn == 1)
-        {
-            zm_msg0_mm(ZM_LV_1, "Re-connect...");
-            zmw_enter_critical_section(dev);
-            wd->sta.connectByReasso = FALSE;
-            zmw_leave_critical_section(dev);
+	zm_msg0_mm(ZM_LV_1, "Resume Wlan");
+	if ((zfStaIsConnected(dev)) || (zfStaIsConnecting(dev))) {
+		if (doReconn == 1) {
+			zm_msg0_mm(ZM_LV_1, "Re-connect...");
+			zmw_enter_critical_section(dev);
+			wd->sta.connectByReasso = FALSE;
+			zmw_leave_critical_section(dev);
 
-            zfWlanEnable(dev);
-        }
-        else if (doReconn == 0)
-        {
-            zfHpSetRollCallTable(dev);
-        }
-    }
+			zfWlanEnable(dev);
+		} else if (doReconn == 0)
+			zfHpSetRollCallTable(dev);
+	}
 
-    ret = 0;
+	ret = 0;
 
-    return ret;
+	return ret;
 }
 
 /************************************************************************/
@@ -1057,235 +979,227 @@
 /*      Stephen Chen        Atheros Communications, INC.    2007.1      */
 /*                                                                      */
 /************************************************************************/
-void zfiWlanFlushAllQueuedBuffers(zdev_t* dev)
+void zfiWlanFlushAllQueuedBuffers(zdev_t *dev)
 {
-    /* Flush VTxQ and MmQ */
-    zfFlushVtxq(dev);
-    /* Flush AP PS queues */
-    zfApFlushBufferedPsFrame(dev);
-    /* Free buffer in defragment list*/
-    zfAgingDefragList(dev, 1);
+	/* Flush VTxQ and MmQ */
+	zfFlushVtxq(dev);
+	/* Flush AP PS queues */
+	zfApFlushBufferedPsFrame(dev);
+	/* Free buffer in defragment list*/
+	zfAgingDefragList(dev, 1);
 }
 
 /* Do WLAN site survey */
-u16_t zfiWlanScan(zdev_t* dev)
+u16_t zfiWlanScan(zdev_t *dev)
 {
-    u16_t ret = 1;
-    zmw_get_wlan_dev(dev);
+	u16_t ret = 1;
+	zmw_get_wlan_dev(dev);
 
-    zm_debug_msg0("");
+	zm_debug_msg0("");
 
-    zmw_declare_for_critical_section();
+	zmw_declare_for_critical_section();
 
-    zmw_enter_critical_section(dev);
+	zmw_enter_critical_section(dev);
 
-    if (wd->wlanMode == ZM_MODE_AP)
-    {
-        wd->heartBeatNotification |= ZM_BSSID_LIST_SCAN;
-        wd->sta.scanFrequency = 0;
-        //wd->sta.pUpdateBssList->bssCount = 0;
-        ret = 0;
-    }
-    else
-    {
-        #if 0
-        if ( !zfStaBlockWlanScan(dev) )
-        {
-            zm_debug_msg0("scan request");
-            //zfTimerSchedule(dev, ZM_EVENT_SCAN, ZM_TICK_ZERO);
-            ret = 0;
-            goto start_scan;
-        }
-        #else
-            goto start_scan;
-        #endif
-    }
+	if (wd->wlanMode == ZM_MODE_AP) {
+		wd->heartBeatNotification |= ZM_BSSID_LIST_SCAN;
+		wd->sta.scanFrequency = 0;
+		/* wd->sta.pUpdateBssList->bssCount = 0; */
+		ret = 0;
+	} else {
+#if 0
+		if (!zfStaBlockWlanScan(dev)) {
+			zm_debug_msg0("scan request");
+			/*zfTimerSchedule(dev, ZM_EVENT_SCAN, ZM_TICK_ZERO);*/
+			ret = 0;
+			goto start_scan;
+		}
+#else
+		goto start_scan;
+#endif
+	}
 
-    zmw_leave_critical_section(dev);
+	zmw_leave_critical_section(dev);
 
-    return ret;
+	return ret;
 
 start_scan:
-    zmw_leave_critical_section(dev);
+	zmw_leave_critical_section(dev);
 
-    if(wd->ledStruct.LEDCtrlFlagFromReg & ZM_LED_CTRL_FLAG_ALPHA)   // flag for Alpha
-        wd->ledStruct.LEDCtrlFlag |= ZM_LED_CTRL_FLAG_ALPHA;
+	if (wd->ledStruct.LEDCtrlFlagFromReg & ZM_LED_CTRL_FLAG_ALPHA) {
+		/* flag for Alpha */
+		wd->ledStruct.LEDCtrlFlag |= ZM_LED_CTRL_FLAG_ALPHA;
+	}
 
-    ret = zfScanMgrScanStart(dev, ZM_SCAN_MGR_SCAN_EXTERNAL);
+	ret = zfScanMgrScanStart(dev, ZM_SCAN_MGR_SCAN_EXTERNAL);
 
-    zm_debug_msg1("ret = ", ret);
+	zm_debug_msg1("ret = ", ret);
 
-    return ret;
+	return ret;
 }
 
 
-/* rate         */
-/*    0 : AUTO  */
-/*    1 : CCK 1M */
-/*    2 : CCK 2M */
-/*    3 : CCK 5.5M */
-/*    4 : CCK 11M */
-/*    5 : OFDM 6M */
-/*    6 : OFDM 9M */
-/*    7 : OFDM 12M */
-/*    8 : OFDM 18M */
-/*    9 : OFDM 24M */
-/*    10 : OFDM 36M */
-/*    11 : OFDM 48M */
-/*    12 : OFDM 54M */
-/*    13 : MCS 0 */
-/*    28 : MCS 15 */
+/* rate         	*/
+/*    0 : AUTO  	*/
+/*    1 : CCK 1M 	*/
+/*    2 : CCK 2M 	*/
+/*    3 : CCK 5.5M 	*/
+/*    4 : CCK 11M 	*/
+/*    5 : OFDM 6M 	*/
+/*    6 : OFDM 9M 	*/
+/*    7 : OFDM 12M 	*/
+/*    8 : OFDM 18M 	*/
+/*    9 : OFDM 24M 	*/
+/*    10 : OFDM 36M 	*/
+/*    11 : OFDM 48M 	*/
+/*    12 : OFDM 54M 	*/
+/*    13 : MCS 0 	*/
+/*    28 : MCS 15 	*/
 u16_t zcRateToMCS[] =
     {0xff, 0, 1, 2, 3, 0xb, 0xf, 0xa, 0xe, 0x9, 0xd, 0x8, 0xc};
 u16_t zcRateToMT[] = {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1};
 
-u16_t zfiWlanSetTxRate(zdev_t* dev, u16_t rate)
-{   // jhlee HT 0
-    zmw_get_wlan_dev(dev);
+u16_t zfiWlanSetTxRate(zdev_t *dev, u16_t rate)
+{
+	/* jhlee HT 0 */
+	zmw_get_wlan_dev(dev);
 
-    if (rate <=12)
-    {
-        wd->txMCS = zcRateToMCS[rate];
-        wd->txMT = zcRateToMT[rate];
-        return ZM_SUCCESS;
-    }
-    else if ((rate<=28)||(rate==13+32))
-    {
-        wd->txMCS = rate - 12 - 1;
-        wd->txMT = 2;
-        return ZM_SUCCESS;
-    }
+	if (rate <= 12) {
+		wd->txMCS = zcRateToMCS[rate];
+		wd->txMT = zcRateToMT[rate];
+		return ZM_SUCCESS;
+	} else if ((rate <= 28) || (rate == 13 + 32)) {
+		wd->txMCS = rate - 12 - 1;
+		wd->txMT = 2;
+		return ZM_SUCCESS;
+	}
 
-    return ZM_ERR_INVALID_TX_RATE;
+	return ZM_ERR_INVALID_TX_RATE;
 }
 
 const u32_t zcRateIdToKbps40M[] =
-    {
-        1000, 2000, 5500, 11000,                  /* 1M, 2M, 5M, 11M          ,  0  1  2  3*/
-        6000, 9000, 12000, 18000,                 /* 6M  9M  12M  18M         ,  4  5  6  7*/
-        24000, 36000, 48000, 54000,               /* 24M  36M  48M  54M       ,  8  9 10 11*/
-        13500, 27000, 40500, 54000,               /* MCS0 MCS1 MCS2 MCS3      , 12 13 14 15*/
-        81000, 108000, 121500, 135000,            /* MCS4 MCS5 MCS6 MCS7      , 16 17 18 19*/
-        27000, 54000, 81000, 108000,              /* MCS8 MCS9 MCS10 MCS11    , 20 21 22 23*/
-        162000, 216000, 243000, 270000,           /* MCS12 MCS13 MCS14 MCS15  , 24 25 26 27*/
-        270000, 300000, 150000                    /* MCS14SG, MCS15SG, MCS7SG , 28 29 30*/
-    };
+{
+	1000, 2000, 5500, 11000, /* 1M, 2M, 5M, 11M ,  0  1  2  3             */
+	6000, 9000, 12000, 18000, /* 6M  9M  12M  18M ,  4  5  6  7           */
+	24000, 36000, 48000, 54000, /* 24M  36M  48M  54M ,  8  9 10 11       */
+	13500, 27000, 40500, 54000, /* MCS0 MCS1 MCS2 MCS3 , 12 13 14 15      */
+	81000, 108000, 121500, 135000, /* MCS4 MCS5 MCS6 MCS7 , 16 17 18 19   */
+	27000, 54000, 81000, 108000, /* MCS8 MCS9 MCS10 MCS11 , 20 21 22 23   */
+	162000, 216000, 243000, 270000, /*MCS12 MCS13 MCS14 MCS15, 24 25 26 27*/
+	270000, 300000, 150000  /* MCS14SG, MCS15SG, MCS7SG , 28 29 30        */
+};
 
 const u32_t zcRateIdToKbps20M[] =
-    {
-        1000, 2000, 5500, 11000,                  /* 1M, 2M, 5M, 11M          ,  0  1  2  3*/
-        6000, 9000, 12000, 18000,                 /* 6M  9M  12M  18M         ,  4  5  6  7*/
-        24000, 36000, 48000, 54000,               /* 24M  36M  48M  54M       ,  8  9 10 11*/
-        6500, 13000, 19500, 26000,                /* MCS0 MCS1 MCS2 MCS3      , 12 13 14 15*/
-        39000, 52000, 58500, 65000,               /* MCS4 MCS5 MCS6 MCS7      , 16 17 18 19*/
-        13000, 26000, 39000, 52000,               /* MCS8 MCS9 MCS10 MCS11    , 20 21 22 23*/
-        78000, 104000, 117000, 130000,            /* MCS12 MCS13 MCS14 MCS15  , 24 25 26 27*/
-        130000, 144400, 72200                     /* MCS14SG, MCS15SG, MSG7SG , 28 29 30*/
-    };
-
-u32_t zfiWlanQueryTxRate(zdev_t* dev)
 {
-    u8_t rateId = 0xff;
-    zmw_get_wlan_dev(dev);
-    zmw_declare_for_critical_section();
+	1000, 2000, 5500, 11000, /* 1M, 2M, 5M, 11M ,  0  1  2  3             */
+	6000, 9000, 12000, 18000, /* 6M  9M  12M  18M  ,  4  5  6  7          */
+	24000, 36000, 48000, 54000, /* 24M  36M  48M  54M ,  8  9 10 11       */
+	6500, 13000, 19500, 26000, /* MCS0 MCS1 MCS2 MCS3 , 12 13 14 15       */
+	39000, 52000, 58500, 65000, /* MCS4 MCS5 MCS6 MCS7 , 16 17 18 19      */
+	13000, 26000, 39000, 52000, /* MCS8 MCS9 MCS10 MCS11 , 20 21 22 23    */
+	78000, 104000, 117000, 130000, /* MCS12 MCS13 MCS14 MCS15, 24 25 26 27*/
+	130000, 144400, 72200  /* MCS14SG, MCS15SG, MSG7SG , 28 29 30         */
+};
 
-    /* If Tx rate had not been trained, return maximum Tx rate instead */
-    if ((wd->wlanMode == ZM_MODE_INFRASTRUCTURE) && (zfStaIsConnected(dev)))
-    {
-        zmw_enter_critical_section(dev);
-        //Not in fixed rate mode
-        if (wd->txMCS == 0xff)
-        {
-            if ((wd->sta.oppositeInfo[0].rcCell.flag & ZM_RC_TRAINED_BIT) == 0)
-            {
-                rateId = wd->sta.oppositeInfo[0].rcCell.operationRateSet[wd->sta.oppositeInfo[0].rcCell.operationRateCount-1];
-            }
-            else
-            {
-                rateId = wd->sta.oppositeInfo[0].rcCell.operationRateSet[wd->sta.oppositeInfo[0].rcCell.currentRateIndex];
-            }
-        }
-        zmw_leave_critical_section(dev);
-    }
-    if (rateId != 0xff)
-    {
-        if (wd->sta.htCtrlBandwidth)
-        {
-            return zcRateIdToKbps40M[rateId];
-        }
-        else
-        {
-            return zcRateIdToKbps20M[rateId];
-        }
-    }
-    else
-    {
-        return wd->CurrentTxRateKbps;
-    }
+u32_t zfiWlanQueryTxRate(zdev_t *dev)
+{
+	u8_t rateId = 0xff;
+	zmw_get_wlan_dev(dev);
+	zmw_declare_for_critical_section();
+
+	/* If Tx rate had not been trained, return maximum Tx rate instead */
+	if ((wd->wlanMode == ZM_MODE_INFRASTRUCTURE) &&
+						(zfStaIsConnected(dev))) {
+		zmw_enter_critical_section(dev);
+		/* Not in fixed rate mode */
+		if (wd->txMCS == 0xff) {
+			if ((wd->sta.oppositeInfo[0].rcCell.flag &
+							ZM_RC_TRAINED_BIT) == 0)
+				rateId = wd->sta.oppositeInfo[0].rcCell. \
+				operationRateSet[wd->sta.oppositeInfo[0]. \
+				rcCell.operationRateCount-1];
+			else
+				rateId = wd->sta.oppositeInfo[0].rcCell. \
+				operationRateSet[wd->sta.oppositeInfo[0]. \
+				rcCell.currentRateIndex];
+		}
+		zmw_leave_critical_section(dev);
+	}
+
+	if (rateId != 0xff) {
+		if (wd->sta.htCtrlBandwidth)
+			return zcRateIdToKbps40M[rateId];
+		else
+			return zcRateIdToKbps20M[rateId];
+	} else
+		return wd->CurrentTxRateKbps;
 }
 
-void zfWlanUpdateRxRate(zdev_t* dev, struct zsAdditionInfo* addInfo)
+void zfWlanUpdateRxRate(zdev_t *dev, struct zsAdditionInfo *addInfo)
 {
-    u32_t rxRateKbps;
-    zmw_get_wlan_dev(dev);
-    //zm_msg1_mm(ZM_LV_0, "addInfo->Tail.Data.RxMacStatus =", addInfo->Tail.Data.RxMacStatus & 0x03);
+	u32_t rxRateKbps;
+	zmw_get_wlan_dev(dev);
+	/* zm_msg1_mm(ZM_LV_0, "addInfo->Tail.Data.RxMacStatus =",
+	*  addInfo->Tail.Data.RxMacStatus & 0x03);
+	*/
 
-    /* b5~b4: MPDU indication.                */
-    /*        00: Single MPDU.                */
-    /*        10: First MPDU of A-MPDU.       */
-    /*        11: Middle MPDU of A-MPDU.      */
-    /*        01: Last MPDU of A-MPDU.        */
-    /* Only First MPDU and Single MPDU have PLCP header */
-    /* First MPDU  : (mpduInd & 0x30) == 0x00 */
-    /* Single MPDU : (mpduInd & 0x30) == 0x20 */
-    if ((addInfo->Tail.Data.RxMacStatus & 0x10) == 0)
-    {
-        /* Modulation type */
-        wd->modulationType = addInfo->Tail.Data.RxMacStatus & 0x03;
-        switch(wd->modulationType)
-        {
-    		case 0x0: wd->rateField = addInfo->PlcpHeader[0] & 0xff; //CCK mode
-                      wd->rxInfo = 0;
-                      break;
-    		case 0x1: wd->rateField = addInfo->PlcpHeader[0] & 0x0f; //Legacy-OFDM mode
-                      wd->rxInfo = 0;
-                      break;
-    		case 0x2: wd->rateField = addInfo->PlcpHeader[3]; //HT-OFDM mode
-    		          wd->rxInfo = addInfo->PlcpHeader[6];
-                      break;
-            default: break;
-         }
+	/* b5~b4: MPDU indication.                */
+	/*        00: Single MPDU.                */
+	/*        10: First MPDU of A-MPDU.       */
+	/*        11: Middle MPDU of A-MPDU.      */
+	/*        01: Last MPDU of A-MPDU.        */
+	/* Only First MPDU and Single MPDU have PLCP header */
+	/* First MPDU  : (mpduInd & 0x30) == 0x00 */
+	/* Single MPDU : (mpduInd & 0x30) == 0x20 */
+	if ((addInfo->Tail.Data.RxMacStatus & 0x10) == 0) {
+		/* Modulation type */
+		wd->modulationType = addInfo->Tail.Data.RxMacStatus & 0x03;
+		switch (wd->modulationType) {
+		/* CCK mode */
+		case 0x0:
+			wd->rateField = addInfo->PlcpHeader[0] & 0xff;
+			wd->rxInfo = 0;
+			break;
+		/* Legacy-OFDM mode */
+		case 0x1:
+			wd->rateField = addInfo->PlcpHeader[0] & 0x0f;
+			wd->rxInfo = 0;
+			break;
+		/* HT-OFDM mode */
+		case 0x2:
+			wd->rateField = addInfo->PlcpHeader[3];
+			wd->rxInfo = addInfo->PlcpHeader[6];
+			break;
+		default:
+			break;
+		}
 
-        rxRateKbps = zfUpdateRxRate(dev);
-        if (wd->CurrentRxRateUpdated == 1)
-        {
-            if (rxRateKbps > wd->CurrentRxRateKbps)
-            {
-                wd->CurrentRxRateKbps = rxRateKbps;
-            }
-        }
-        else
-        {
-            wd->CurrentRxRateKbps = rxRateKbps;
-            wd->CurrentRxRateUpdated = 1;
-        }
-    }
+		rxRateKbps = zfUpdateRxRate(dev);
+		if (wd->CurrentRxRateUpdated == 1) {
+			if (rxRateKbps > wd->CurrentRxRateKbps)
+				wd->CurrentRxRateKbps = rxRateKbps;
+		} else {
+			wd->CurrentRxRateKbps = rxRateKbps;
+			wd->CurrentRxRateUpdated = 1;
+		}
+	}
 }
+
 #if 0
 u16_t zcIndextoRateBG[16] = {1000, 2000, 5500, 11000, 0, 0, 0, 0, 48000,
-                               24000, 12000, 6000, 54000, 36000, 18000, 9000};
+			24000, 12000, 6000, 54000, 36000, 18000, 9000};
 u32_t zcIndextoRateN20L[16] = {6500, 13000, 19500, 26000, 39000, 52000, 58500,
-                              65000, 13000, 26000, 39000, 52000, 78000, 104000,
-                              117000, 130000};
+			65000, 13000, 26000, 39000, 52000, 78000, 104000,
+			117000, 130000};
 u32_t zcIndextoRateN20S[16] = {7200, 14400, 21700, 28900, 43300, 57800, 65000,
-                              72200, 14400, 28900, 43300, 57800, 86700, 115600,
-                              130000, 144400};
-u32_t zcIndextoRateN40L[16] = {13500, 27000, 40500, 54000, 81000, 108000, 121500,
-                              135000, 27000, 54000, 81000, 108000, 162000, 216000,
-                              243000, 270000};
-u32_t zcIndextoRateN40S[16] = {15000, 30000, 45000, 60000, 90000, 120000, 135000,
-                              150000, 30000, 60000, 90000, 120000, 180000, 240000,
-                              270000, 300000};
+			72200, 14400, 28900, 43300, 57800, 86700, 115600,
+			130000, 144400};
+u32_t zcIndextoRateN40L[16] = {13500, 27000, 40500, 54000, 81000, 108000,
+			121500, 135000, 27000, 54000, 81000, 108000,
+			162000, 216000, 243000, 270000};
+u32_t zcIndextoRateN40S[16] = {15000, 30000, 45000, 60000, 90000, 120000,
+			135000, 150000, 30000, 60000, 90000, 120000,
+			180000, 240000, 270000, 300000};
 #endif
 
 extern u16_t zcIndextoRateBG[16];
@@ -1294,568 +1208,558 @@
 extern u32_t zcIndextoRateN40L[16];
 extern u32_t zcIndextoRateN40S[16];
 
-u32_t zfiWlanQueryRxRate(zdev_t* dev)
+u32_t zfiWlanQueryRxRate(zdev_t *dev)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    wd->CurrentRxRateUpdated = 0;
-    return wd->CurrentRxRateKbps;
+	wd->CurrentRxRateUpdated = 0;
+	return wd->CurrentRxRateKbps;
 }
 
-u32_t zfUpdateRxRate(zdev_t* dev)
+u32_t zfUpdateRxRate(zdev_t *dev)
 {
-    u8_t mcs, bandwidth;
-    u32_t rxRateKbps = 130000;
-    zmw_get_wlan_dev(dev);
+	u8_t mcs, bandwidth;
+	u32_t rxRateKbps = 130000;
+	zmw_get_wlan_dev(dev);
 
-    switch (wd->modulationType)
-    {
-		case 0x0: //CCK mode
-                  switch (wd->rateField)
-                  {
-                      case 0x0a: rxRateKbps = 1000;
-                            break;
-                      case 0x14: rxRateKbps = 2000;
+	switch (wd->modulationType) {
+	/* CCK mode */
+	case 0x0:
+		switch (wd->rateField) {
+		case 0x0a:
+			rxRateKbps = 1000;
+			break;
+		case 0x14:
+			rxRateKbps = 2000;
 
-                      case 0x37: rxRateKbps = 5500;
-                            break;
-                      case 0x6e: rxRateKbps = 11000;
-                            break;
-                      default:
-                            break;
-                  }
-                  break;
-		case 0x1: //Legacy-OFDM mode
-                  if (wd->rateField <= 15)
-                  {
-                      rxRateKbps = zcIndextoRateBG[wd->rateField];
-                  }
-                  break;
-		case 0x2: //HT-OFDM mode
-		          mcs = wd->rateField & 0x7F;
-		          bandwidth = wd->rateField & 0x80;
-                  if (mcs <= 15)
-                  {
-                      if (bandwidth != 0)
-                      {
-                          if((wd->rxInfo & 0x80) != 0)
-                          {
-                              /* Short GI 40 MHz MIMO Rate */
-                              rxRateKbps = zcIndextoRateN40S[mcs];
-                          }
-                          else
-                          {
-                              /* Long GI 40 MHz MIMO Rate */
-                              rxRateKbps = zcIndextoRateN40L[mcs];
-                          }
-                      }
-                      else
-                      {
-                          if((wd->rxInfo & 0x80) != 0)
-                          {
-                              /* Short GI 20 MHz MIMO Rate */
-                              rxRateKbps = zcIndextoRateN20S[mcs];
-                          }
-                          else
-                          {
-                              /* Long GI 20 MHz MIMO Rate */
-                              rxRateKbps = zcIndextoRateN20L[mcs];
-                          }
-                      }
-                  }
-                  break;
-        default:
-                  break;
-    }
-    //zm_msg1_mm(ZM_LV_0, "wd->CurrentRxRateKbps=", wd->CurrentRxRateKbps);
+		case 0x37:
+			rxRateKbps = 5500;
+			break;
+		case 0x6e:
+			rxRateKbps = 11000;
+			break;
+		default:
+			break;
+		}
+		break;
+	/* Legacy-OFDM mode */
+	case 0x1:
+		if (wd->rateField <= 15)
+			rxRateKbps = zcIndextoRateBG[wd->rateField];
+		break;
+	/* HT-OFDM mode */
+	case 0x2:
+		mcs = wd->rateField & 0x7F;
+		bandwidth = wd->rateField & 0x80;
+		if (mcs <= 15) {
+			if (bandwidth != 0) {
+				if ((wd->rxInfo & 0x80) != 0) {
+					/* Short GI 40 MHz MIMO Rate */
+					rxRateKbps = zcIndextoRateN40S[mcs];
+				} else {
+					/* Long GI 40 MHz MIMO Rate */
+					rxRateKbps = zcIndextoRateN40L[mcs];
+				}
+			} else {
+				if ((wd->rxInfo & 0x80) != 0) {
+					/* Short GI 20 MHz MIMO Rate */
+					rxRateKbps = zcIndextoRateN20S[mcs];
+				} else {
+					/* Long GI 20 MHz MIMO Rate */
+					rxRateKbps = zcIndextoRateN20L[mcs];
+				}
+			}
+		}
+		break;
+	default:
+		break;
+	}
+	/*	zm_msg1_mm(ZM_LV_0, "wd->CurrentRxRateKbps=",
+		wd->CurrentRxRateKbps);
+	*/
 
-     // ToDo: use bandwith field to define 40MB
-    return rxRateKbps;
+	/* ToDo: use bandwith field to define 40MB */
+	return rxRateKbps;
 }
 
 /* Get WLAN stastics */
-u16_t zfiWlanGetStatistics(zdev_t* dev)
+u16_t zfiWlanGetStatistics(zdev_t *dev)
 {
-    /* Return link statistics */
-    return 0;
+	/* Return link statistics */
+	return 0;
 }
 
-u16_t zfiWlanReset(zdev_t* dev)
+u16_t zfiWlanReset(zdev_t *dev)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    wd->state = ZM_WLAN_STATE_DISABLED;
+	wd->state = ZM_WLAN_STATE_DISABLED;
 
-    return zfWlanReset(dev);
+	return zfWlanReset(dev);
 }
 
 /* Reset WLAN */
-u16_t zfWlanReset(zdev_t* dev)
+u16_t zfWlanReset(zdev_t *dev)
 {
-    u8_t isConnected;
-    zmw_get_wlan_dev(dev);
+	u8_t isConnected;
+	zmw_get_wlan_dev(dev);
 
-    zmw_declare_for_critical_section();
+	zmw_declare_for_critical_section();
 
-    zm_debug_msg0("zfWlanReset");
+	zm_debug_msg0("zfWlanReset");
 
-    isConnected = zfStaIsConnected(dev);
+	isConnected = zfStaIsConnected(dev);
 
-    //if ( wd->wlanMode != ZM_MODE_AP )
-    {
-        if ( (wd->wlanMode == ZM_MODE_INFRASTRUCTURE)&&
-             (wd->sta.currentAuthMode != ZM_AUTH_MODE_WPA2) )
-        {
-            /* send deauthentication frame */
-            if (isConnected)
-            {
-                //zfiWlanDeauth(dev, NULL, 0);
-                zfSendMmFrame(dev, ZM_WLAN_FRAME_TYPE_DEAUTH, wd->sta.bssid, 3, 0, 0);
-                //zmw_debug_msg0("send a Deauth frame!");
-            }
-        }
-    }
+	/* if ( wd->wlanMode != ZM_MODE_AP ) */
+	{
+		if ((wd->wlanMode == ZM_MODE_INFRASTRUCTURE) &&
+		(wd->sta.currentAuthMode != ZM_AUTH_MODE_WPA2)) {
+			/* send deauthentication frame */
+			if (isConnected) {
+				/* zfiWlanDeauth(dev, NULL, 0); */
+				zfSendMmFrame(dev, ZM_WLAN_FRAME_TYPE_DEAUTH,
+						wd->sta.bssid, 3, 0, 0);
+				/* zmw_debug_msg0("send a Deauth frame!"); */
+			}
+		}
+	}
 
-    zfChangeAdapterState(dev, ZM_STA_STATE_DISCONNECT);
-    zfHpResetKeyCache(dev);
+	zfChangeAdapterState(dev, ZM_STA_STATE_DISCONNECT);
+	zfHpResetKeyCache(dev);
 
-    if (isConnected)
-    {
-        //zfiWlanDisable(dev);
-        if (wd->zfcbConnectNotify != NULL)
-        {
-            wd->zfcbConnectNotify(dev, ZM_STATUS_MEDIA_CONNECTION_RESET, wd->sta.bssid);
-        }
-    }
-    else
-    {
-        if (wd->zfcbConnectNotify != NULL)
-        {
-            wd->zfcbConnectNotify(dev, ZM_STATUS_MEDIA_RESET, wd->sta.bssid);
-        }
-    }
+	if (isConnected) {
+		/* zfiWlanDisable(dev); */
+		if (wd->zfcbConnectNotify != NULL)
+			wd->zfcbConnectNotify(dev,
+			ZM_STATUS_MEDIA_CONNECTION_RESET, wd->sta.bssid);
+	} else {
+		if (wd->zfcbConnectNotify != NULL)
+			wd->zfcbConnectNotify(dev, ZM_STATUS_MEDIA_RESET,
+								wd->sta.bssid);
+	}
 
-    /* stop beacon */
-    zfHpDisableBeacon(dev);
+	/* stop beacon */
+	zfHpDisableBeacon(dev);
 
-    /* Free buffer in defragment list*/
-    zfAgingDefragList(dev, 1);
+	/* Free buffer in defragment list*/
+	zfAgingDefragList(dev, 1);
 
-    /* Flush VTxQ and MmQ */
-    zfFlushVtxq(dev);
+	/* Flush VTxQ and MmQ */
+	zfFlushVtxq(dev);
 
-    #ifdef ZM_ENABLE_AGGREGATION
-    /* add by honda */
-    zfAggRxFreeBuf(dev, 0);  //1 for release structure memory
-    /* end of add by honda */
-    #endif
-
-    zfStaRefreshBlockList(dev, 1);
-
-    zmw_enter_critical_section(dev);
-
-    zfTimerCancel(dev, ZM_EVENT_IBSS_MONITOR);
-    zfTimerCancel(dev, ZM_EVENT_CM_BLOCK_TIMER);
-    zfTimerCancel(dev, ZM_EVENT_CM_DISCONNECT);
-
-    wd->sta.connectState = ZM_STA_CONN_STATE_NONE;
-    wd->sta.connectByReasso = FALSE;
-    wd->sta.cmDisallowSsidLength = 0;
-    wd->sta.bAutoReconnect = 0;
-    wd->sta.InternalScanReq = 0;
-    wd->sta.encryMode = ZM_NO_WEP;
-    wd->sta.wepStatus = ZM_ENCRYPTION_WEP_DISABLED;
-    wd->sta.wpaState = ZM_STA_WPA_STATE_INIT;
-    wd->sta.cmMicFailureCount = 0;
-    wd->sta.ibssBssIsCreator = 0;
-#ifdef ZM_ENABLE_IBSS_WPA2PSK
-    wd->sta.ibssWpa2Psk = 0;
+#ifdef ZM_ENABLE_AGGREGATION
+	/* add by honda */
+	zfAggRxFreeBuf(dev, 0);  /* 1 for release structure memory */
+	/* end of add by honda */
 #endif
-    /* reset connect timeout counter */
-    wd->sta.connectTimeoutCount = 0;
 
-    /* reset leap enable variable */
-    wd->sta.leapEnabled = 0;
+	zfStaRefreshBlockList(dev, 1);
 
-    /* Reset the RIFS Status / RIFS-like frame count / RIFS count */
-    if( wd->sta.rifsState == ZM_RIFS_STATE_DETECTED )
-        zfHpDisableRifs(dev);
-    wd->sta.rifsState = ZM_RIFS_STATE_DETECTING;
-    wd->sta.rifsLikeFrameCnt = 0;
-    wd->sta.rifsCount = 0;
+	zmw_enter_critical_section(dev);
 
-    wd->sta.osRxFilter = 0;
-    wd->sta.bSafeMode = 0;
+	zfTimerCancel(dev, ZM_EVENT_IBSS_MONITOR);
+	zfTimerCancel(dev, ZM_EVENT_CM_BLOCK_TIMER);
+	zfTimerCancel(dev, ZM_EVENT_CM_DISCONNECT);
 
-    // Clear the information for the peer stations of IBSS or AP of Station mode
-    zfZeroMemory((u8_t*)wd->sta.oppositeInfo, sizeof(struct zsOppositeInfo) * ZM_MAX_OPPOSITE_COUNT);
+	wd->sta.connectState = ZM_STA_CONN_STATE_NONE;
+	wd->sta.connectByReasso = FALSE;
+	wd->sta.cmDisallowSsidLength = 0;
+	wd->sta.bAutoReconnect = 0;
+	wd->sta.InternalScanReq = 0;
+	wd->sta.encryMode = ZM_NO_WEP;
+	wd->sta.wepStatus = ZM_ENCRYPTION_WEP_DISABLED;
+	wd->sta.wpaState = ZM_STA_WPA_STATE_INIT;
+	wd->sta.cmMicFailureCount = 0;
+	wd->sta.ibssBssIsCreator = 0;
+#ifdef ZM_ENABLE_IBSS_WPA2PSK
+	wd->sta.ibssWpa2Psk = 0;
+#endif
+	/* reset connect timeout counter */
+	wd->sta.connectTimeoutCount = 0;
 
-    zmw_leave_critical_section(dev);
+	/* reset leap enable variable */
+	wd->sta.leapEnabled = 0;
 
-    zfScanMgrScanStop(dev, ZM_SCAN_MGR_SCAN_INTERNAL);
-    zfScanMgrScanStop(dev, ZM_SCAN_MGR_SCAN_EXTERNAL);
+	/* Reset the RIFS Status / RIFS-like frame count / RIFS count */
+	if (wd->sta.rifsState == ZM_RIFS_STATE_DETECTED)
+		zfHpDisableRifs(dev);
+	wd->sta.rifsState = ZM_RIFS_STATE_DETECTING;
+	wd->sta.rifsLikeFrameCnt = 0;
+	wd->sta.rifsCount = 0;
 
-    /* Turn off Software WEP/TKIP */
-    if (wd->sta.SWEncryptEnable != 0)
-    {
-        zm_debug_msg0("Disable software encryption");
-        zfStaDisableSWEncryption(dev);
-    }
+	wd->sta.osRxFilter = 0;
+	wd->sta.bSafeMode = 0;
 
-    /* Improve WEP/TKIP performace with HT AP, detail information please look bug#32495 */
-    //zfHpSetTTSIFSTime(dev, 0x8);
+	/* 	Clear the information for the peer
+		stations of IBSS or AP of Station mode
+	*/
+	zfZeroMemory((u8_t *)wd->sta.oppositeInfo,
+			sizeof(struct zsOppositeInfo) * ZM_MAX_OPPOSITE_COUNT);
 
-    /* Keep Pseudo mode */
-    if ( wd->wlanMode != ZM_MODE_PSEUDO )
-    {
-        wd->wlanMode = ZM_MODE_INFRASTRUCTURE;
-    }
-    return 0;
+	zmw_leave_critical_section(dev);
+
+	zfScanMgrScanStop(dev, ZM_SCAN_MGR_SCAN_INTERNAL);
+	zfScanMgrScanStop(dev, ZM_SCAN_MGR_SCAN_EXTERNAL);
+
+	/* Turn off Software WEP/TKIP */
+	if (wd->sta.SWEncryptEnable != 0) {
+		zm_debug_msg0("Disable software encryption");
+		zfStaDisableSWEncryption(dev);
+	}
+
+	/* 	Improve WEP/TKIP performace with HT AP,
+		detail information please look bug#32495
+	*/
+	/* zfHpSetTTSIFSTime(dev, 0x8); */
+
+	/* Keep Pseudo mode */
+	if (wd->wlanMode != ZM_MODE_PSEUDO)
+		wd->wlanMode = ZM_MODE_INFRASTRUCTURE;
+
+	return 0;
 }
 
 /* Deauthenticate a STA */
-u16_t zfiWlanDeauth(zdev_t* dev, u16_t* macAddr, u16_t reason)
+u16_t zfiWlanDeauth(zdev_t *dev, u16_t *macAddr, u16_t reason)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    if ( wd->wlanMode == ZM_MODE_AP )
-    {
-        //u16_t id;
+	if (wd->wlanMode == ZM_MODE_AP) {
+		/* u16_t id; */
 
-        /*
-         * we will reset all key in zfHpResetKeyCache() when call
-         * zfiWlanDisable(), if we want to reset PairwiseKey for each sta,
-         * need to use a nullAddr to let keyindex not match.
-         * otherwise hardware will still find PairwiseKey when AP change
-         * encryption mode from WPA to WEP
-         */
+		/*
+		* we will reset all key in zfHpResetKeyCache() when call
+		* zfiWlanDisable(), if we want to reset PairwiseKey for each
+		* sta, need to use a nullAddr to let keyindex not match.
+		* otherwise hardware will still find PairwiseKey when AP change
+		* encryption mode from WPA to WEP
+		*/
 
-        /*
-        if ((id = zfApFindSta(dev, macAddr)) != 0xffff)
-        {
-            u32_t key[8];
-            u16_t nullAddr[3] = { 0x0, 0x0, 0x0 };
+		/*
+		if ((id = zfApFindSta(dev, macAddr)) != 0xffff)
+		{
+			u32_t key[8];
+			u16_t nullAddr[3] = { 0x0, 0x0, 0x0 };
 
-            if (wd->ap.staTable[i].encryMode != ZM_NO_WEP)
-            {
-                zfHpSetApPairwiseKey(dev, nullAddr,
-                        ZM_NO_WEP, &key[0], &key[4], i+1);
-            }
-            //zfHpSetApPairwiseKey(dev, (u16_t *)macAddr,
-            //        ZM_NO_WEP, &key[0], &key[4], id+1);
-            wd->ap.staTable[id].encryMode = ZM_NO_WEP;
-            wd->ap.staTable[id].keyIdx = 0xff;
-        }
-        */
+			if (wd->ap.staTable[i].encryMode != ZM_NO_WEP)
+			{
+				zfHpSetApPairwiseKey(dev, nullAddr,
+				ZM_NO_WEP, &key[0], &key[4], i+1);
+			}
+			//zfHpSetApPairwiseKey(dev, (u16_t *)macAddr,
+			//        ZM_NO_WEP, &key[0], &key[4], id+1);
+		wd->ap.staTable[id].encryMode = ZM_NO_WEP;
+		wd->ap.staTable[id].keyIdx = 0xff;
+		}
+		*/
 
-        zfSendMmFrame(dev, ZM_WLAN_FRAME_TYPE_DEAUTH, macAddr, reason, 0, 0);
-    }
-    else
-    {
-        zfSendMmFrame(dev, ZM_WLAN_FRAME_TYPE_DEAUTH, wd->sta.bssid, 3, 0, 0);
-    }
+		zfSendMmFrame(dev, ZM_WLAN_FRAME_TYPE_DEAUTH, macAddr,
+								reason, 0, 0);
+	} else
+		zfSendMmFrame(dev, ZM_WLAN_FRAME_TYPE_DEAUTH,
+						wd->sta.bssid, 3, 0, 0);
 
-    /* Issue DEAUTH command to FW */
-    return 0;
+	/* Issue DEAUTH command to FW */
+	return 0;
 }
 
 
 /* XP packet filter feature : */
-/* 1=>enable: All multicast address packets, not just the ones enumerated in the multicast address list. */
+/* 1=>enable: All multicast address packets, not just the ones */
+/* enumerated in the multicast address list. */
 /* 0=>disable */
-void zfiWlanSetAllMulticast(zdev_t* dev, u32_t setting)
+void zfiWlanSetAllMulticast(zdev_t *dev, u32_t setting)
 {
-    zmw_get_wlan_dev(dev);
-    zm_msg1_mm(ZM_LV_0, "sta.bAllMulticast = ", setting);
-    wd->sta.bAllMulticast = (u8_t)setting;
+	zmw_get_wlan_dev(dev);
+	zm_msg1_mm(ZM_LV_0, "sta.bAllMulticast = ", setting);
+	wd->sta.bAllMulticast = (u8_t)setting;
 }
 
 
 /* HT configure API */
-void zfiWlanSetHTCtrl(zdev_t* dev, u32_t *setting, u32_t forceTxTPC)
+void zfiWlanSetHTCtrl(zdev_t *dev, u32_t *setting, u32_t forceTxTPC)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    wd->preambleType        = (u8_t)setting[0];
-    wd->sta.preambleTypeHT  = (u8_t)setting[1];
-    wd->sta.htCtrlBandwidth = (u8_t)setting[2];
-    wd->sta.htCtrlSTBC      = (u8_t)setting[3];
-    wd->sta.htCtrlSG        = (u8_t)setting[4];
-    wd->sta.defaultTA       = (u8_t)setting[5];
-    wd->enableAggregation   = (u8_t)setting[6];
-    wd->enableWDS           = (u8_t)setting[7];
+	wd->preambleType        = (u8_t)setting[0];
+	wd->sta.preambleTypeHT  = (u8_t)setting[1];
+	wd->sta.htCtrlBandwidth = (u8_t)setting[2];
+	wd->sta.htCtrlSTBC      = (u8_t)setting[3];
+	wd->sta.htCtrlSG        = (u8_t)setting[4];
+	wd->sta.defaultTA       = (u8_t)setting[5];
+	wd->enableAggregation   = (u8_t)setting[6];
+	wd->enableWDS           = (u8_t)setting[7];
 
-    wd->forceTxTPC          = forceTxTPC;
+	wd->forceTxTPC          = forceTxTPC;
 }
 
 /* FB50 in OS XP, RD private test code */
-void zfiWlanQueryHTCtrl(zdev_t* dev, u32_t *setting, u32_t *forceTxTPC)
+void zfiWlanQueryHTCtrl(zdev_t *dev, u32_t *setting, u32_t *forceTxTPC)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    setting[0] = wd->preambleType;
-    setting[1] = wd->sta.preambleTypeHT;
-    setting[2] = wd->sta.htCtrlBandwidth;
-    setting[3] = wd->sta.htCtrlSTBC;
-    setting[4] = wd->sta.htCtrlSG;
-    setting[5] = wd->sta.defaultTA;
-    setting[6] = wd->enableAggregation;
-    setting[7] = wd->enableWDS;
+	setting[0] = wd->preambleType;
+	setting[1] = wd->sta.preambleTypeHT;
+	setting[2] = wd->sta.htCtrlBandwidth;
+	setting[3] = wd->sta.htCtrlSTBC;
+	setting[4] = wd->sta.htCtrlSG;
+	setting[5] = wd->sta.defaultTA;
+	setting[6] = wd->enableAggregation;
+	setting[7] = wd->enableWDS;
 
-    *forceTxTPC = wd->forceTxTPC;
+	*forceTxTPC = wd->forceTxTPC;
 }
 
-void zfiWlanDbg(zdev_t* dev, u8_t setting)
+void zfiWlanDbg(zdev_t *dev, u8_t setting)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    wd->enableHALDbgInfo = setting;
+	wd->enableHALDbgInfo = setting;
 }
 
 /* FB50 in OS XP, RD private test code */
-void zfiWlanSetRxPacketDump(zdev_t* dev, u32_t setting)
+void zfiWlanSetRxPacketDump(zdev_t *dev, u32_t setting)
 {
-    zmw_get_wlan_dev(dev);
-    if (setting)
-    {
-        wd->rxPacketDump = 1;   /* enable */
-    }
-    else
-    {
-        wd->rxPacketDump = 0;   /* disable */
-    }
+	zmw_get_wlan_dev(dev);
+	if (setting)
+		wd->rxPacketDump = 1;   /* enable */
+	else
+		wd->rxPacketDump = 0;   /* disable */
 }
 
 
 /* FB50 in OS XP, RD private test code */
 /* Tally */
-void zfiWlanResetTally(zdev_t* dev)
+void zfiWlanResetTally(zdev_t *dev)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    zmw_declare_for_critical_section();
+	zmw_declare_for_critical_section();
 
-    zmw_enter_critical_section(dev);
+	zmw_enter_critical_section(dev);
 
-	   wd->commTally.txUnicastFrm = 0;		//txUnicastFrames
-	   wd->commTally.txMulticastFrm = 0;		//txMulticastFrames
-	   wd->commTally.txUnicastOctets = 0;	//txUniOctets  byte size
-	   wd->commTally.txMulticastOctets = 0;	//txMultiOctets  byte size
-	   wd->commTally.txFrmUpperNDIS = 0;
-	   wd->commTally.txFrmDrvMgt = 0;
-	   wd->commTally.RetryFailCnt = 0;
-	   wd->commTally.Hw_TotalTxFrm = 0;		//Hardware total Tx Frame
-	   wd->commTally.Hw_RetryCnt = 0;		//txMultipleRetriesFrames
-	   wd->commTally.Hw_UnderrunCnt = 0;//
-	   wd->commTally.DriverRxFrmCnt = 0;//
-	   wd->commTally.rxUnicastFrm = 0;		//rxUnicastFrames
-	   wd->commTally.rxMulticastFrm = 0;	//rxMulticastFrames
-	   wd->commTally.NotifyNDISRxFrmCnt = 0;//
-	   wd->commTally.rxUnicastOctets = 0;	//rxUniOctets  byte size
-	   wd->commTally.rxMulticastOctets = 0;	//rxMultiOctets  byte size
-	   wd->commTally.DriverDiscardedFrm = 0;// Discard by ValidateFrame
-	   wd->commTally.LessThanDataMinLen = 0;//
-	   wd->commTally.GreaterThanMaxLen = 0;//
-	   wd->commTally.DriverDiscardedFrmCauseByMulticastList = 0;
-	   wd->commTally.DriverDiscardedFrmCauseByFrmCtrl = 0;
-	   wd->commTally.rxNeedFrgFrm = 0;		// need more frg frm
-	   wd->commTally.DriverRxMgtFrmCnt = 0;
-	   wd->commTally.rxBroadcastFrm = 0;	//Receive broadcast frame count
-	   wd->commTally.rxBroadcastOctets = 0;	//Receive broadcast frame byte size
-	   wd->commTally.Hw_TotalRxFrm = 0;//
-	   wd->commTally.Hw_CRC16Cnt = 0;		//rxPLCPCRCErrCnt
-	   wd->commTally.Hw_CRC32Cnt = 0;		//rxCRC32ErrCnt
-	   wd->commTally.Hw_DecrypErr_UNI = 0;//
-	   wd->commTally.Hw_DecrypErr_Mul = 0;//
-	   wd->commTally.Hw_RxFIFOOverrun = 0;//
-	   wd->commTally.Hw_RxTimeOut = 0;
-	   wd->commTally.LossAP = 0;//
+	wd->commTally.txUnicastFrm = 0;		/* txUnicastFrames */
+	wd->commTally.txMulticastFrm = 0;	/* txMulticastFrames */
+	wd->commTally.txUnicastOctets = 0;	/* txUniOctets  byte size */
+	wd->commTally.txMulticastOctets = 0;	/* txMultiOctets  byte size */
+	wd->commTally.txFrmUpperNDIS = 0;
+	wd->commTally.txFrmDrvMgt = 0;
+	wd->commTally.RetryFailCnt = 0;
+	wd->commTally.Hw_TotalTxFrm = 0;	/* Hardware total Tx Frame */
+	wd->commTally.Hw_RetryCnt = 0;		/* txMultipleRetriesFrames */
+	wd->commTally.Hw_UnderrunCnt = 0;
+	wd->commTally.DriverRxFrmCnt = 0;
+	wd->commTally.rxUnicastFrm = 0;		/* rxUnicastFrames */
+	wd->commTally.rxMulticastFrm = 0;	/* rxMulticastFrames */
+	wd->commTally.NotifyNDISRxFrmCnt = 0;
+	wd->commTally.rxUnicastOctets = 0;	/* rxUniOctets  byte size */
+	wd->commTally.rxMulticastOctets = 0;	/* rxMultiOctets  byte size */
+	wd->commTally.DriverDiscardedFrm = 0;	/* Discard by ValidateFrame */
+	wd->commTally.LessThanDataMinLen = 0;
+	wd->commTally.GreaterThanMaxLen = 0;
+	wd->commTally.DriverDiscardedFrmCauseByMulticastList = 0;
+	wd->commTally.DriverDiscardedFrmCauseByFrmCtrl = 0;
+	wd->commTally.rxNeedFrgFrm = 0;		/* need more frg frm */
+	wd->commTally.DriverRxMgtFrmCnt = 0;
+	wd->commTally.rxBroadcastFrm = 0;/* Receive broadcast frame count */
+	wd->commTally.rxBroadcastOctets = 0;/*Receive broadcast framebyte size*/
+	wd->commTally.Hw_TotalRxFrm = 0;
+	wd->commTally.Hw_CRC16Cnt = 0;		/* rxPLCPCRCErrCnt */
+	wd->commTally.Hw_CRC32Cnt = 0;		/* rxCRC32ErrCnt */
+	wd->commTally.Hw_DecrypErr_UNI = 0;
+	wd->commTally.Hw_DecrypErr_Mul = 0;
+	wd->commTally.Hw_RxFIFOOverrun = 0;
+	wd->commTally.Hw_RxTimeOut = 0;
+	wd->commTally.LossAP = 0;
 
-	   wd->commTally.Tx_MPDU = 0;
-	   wd->commTally.BA_Fail = 0;
-	   wd->commTally.Hw_Tx_AMPDU = 0;
-	   wd->commTally.Hw_Tx_MPDU = 0;
+	wd->commTally.Tx_MPDU = 0;
+	wd->commTally.BA_Fail = 0;
+	wd->commTally.Hw_Tx_AMPDU = 0;
+	wd->commTally.Hw_Tx_MPDU = 0;
 
-    wd->commTally.txQosDropCount[0] = 0;
-    wd->commTally.txQosDropCount[1] = 0;
-    wd->commTally.txQosDropCount[2] = 0;
-    wd->commTally.txQosDropCount[3] = 0;
-    wd->commTally.txQosDropCount[4] = 0;
+	wd->commTally.txQosDropCount[0] = 0;
+	wd->commTally.txQosDropCount[1] = 0;
+	wd->commTally.txQosDropCount[2] = 0;
+	wd->commTally.txQosDropCount[3] = 0;
+	wd->commTally.txQosDropCount[4] = 0;
 
-    wd->commTally.Hw_RxMPDU = 0;
-    wd->commTally.Hw_RxDropMPDU = 0;
-    wd->commTally.Hw_RxDelMPDU = 0;
+	wd->commTally.Hw_RxMPDU = 0;
+	wd->commTally.Hw_RxDropMPDU = 0;
+	wd->commTally.Hw_RxDelMPDU = 0;
 
-    wd->commTally.Hw_RxPhyMiscError = 0;
-    wd->commTally.Hw_RxPhyXRError = 0;
-    wd->commTally.Hw_RxPhyOFDMError = 0;
-    wd->commTally.Hw_RxPhyCCKError = 0;
-    wd->commTally.Hw_RxPhyHTError = 0;
-    wd->commTally.Hw_RxPhyTotalCount = 0;
+	wd->commTally.Hw_RxPhyMiscError = 0;
+	wd->commTally.Hw_RxPhyXRError = 0;
+	wd->commTally.Hw_RxPhyOFDMError = 0;
+	wd->commTally.Hw_RxPhyCCKError = 0;
+	wd->commTally.Hw_RxPhyHTError = 0;
+	wd->commTally.Hw_RxPhyTotalCount = 0;
 
-#if	(defined(GCCK) && defined(OFDM))
-	   wd->commTally.rx11bDataFrame = 0;
-	   wd->commTally.rxOFDMDataFrame = 0;
+#if (defined(GCCK) && defined(OFDM))
+	wd->commTally.rx11bDataFrame = 0;
+	wd->commTally.rxOFDMDataFrame = 0;
 #endif
 
-    zmw_leave_critical_section(dev);
+	zmw_leave_critical_section(dev);
 }
 
 /* FB50 in OS XP, RD private test code */
-void zfiWlanQueryTally(zdev_t* dev, struct zsCommTally *tally)
+void zfiWlanQueryTally(zdev_t *dev, struct zsCommTally *tally)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    zmw_declare_for_critical_section();
+	zmw_declare_for_critical_section();
 
-    zmw_enter_critical_section(dev);
-    zfMemoryCopy((u8_t*)tally, (u8_t*)&wd->commTally, sizeof(struct zsCommTally));
-    zmw_leave_critical_section(dev);
-}
-void zfiWlanQueryTrafTally(zdev_t* dev, struct zsTrafTally *tally)
-{
-    zmw_get_wlan_dev(dev);
-
-    zmw_declare_for_critical_section();
-
-    zmw_enter_critical_section(dev);
-    zfMemoryCopy((u8_t*)tally, (u8_t*)&wd->trafTally, sizeof(struct zsTrafTally));
-    zmw_leave_critical_section(dev);
+	zmw_enter_critical_section(dev);
+	zfMemoryCopy((u8_t *)tally, (u8_t *)&wd->commTally,
+						sizeof(struct zsCommTally));
+	zmw_leave_critical_section(dev);
 }
 
-void zfiWlanQueryMonHalRxInfo(zdev_t* dev, struct zsMonHalRxInfo *monHalRxInfo)
+void zfiWlanQueryTrafTally(zdev_t *dev, struct zsTrafTally *tally)
 {
-    zfHpQueryMonHalRxInfo(dev, (u8_t *)monHalRxInfo);
+	zmw_get_wlan_dev(dev);
+
+	zmw_declare_for_critical_section();
+
+	zmw_enter_critical_section(dev);
+	zfMemoryCopy((u8_t *)tally, (u8_t *)&wd->trafTally,
+						sizeof(struct zsTrafTally));
+	zmw_leave_critical_section(dev);
+}
+
+void zfiWlanQueryMonHalRxInfo(zdev_t *dev, struct zsMonHalRxInfo *monHalRxInfo)
+{
+	zfHpQueryMonHalRxInfo(dev, (u8_t *)monHalRxInfo);
 }
 
 /* parse the modeMDKEnable to DrvCore */
-void zfiDKEnable(zdev_t* dev, u32_t enable)
+void zfiDKEnable(zdev_t *dev, u32_t enable)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    wd->modeMDKEnable = enable;
-    zm_debug_msg1("modeMDKEnable = ", wd->modeMDKEnable);
+	wd->modeMDKEnable = enable;
+	zm_debug_msg1("modeMDKEnable = ", wd->modeMDKEnable);
 }
 
 /* airoPeek */
-u32_t zfiWlanQueryPacketTypePromiscuous(zdev_t* dev)
+u32_t zfiWlanQueryPacketTypePromiscuous(zdev_t *dev)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    return wd->swSniffer;
+	return wd->swSniffer;
 }
 
 /* airoPeek */
-void zfiWlanSetPacketTypePromiscuous(zdev_t* dev, u32_t setValue)
+void zfiWlanSetPacketTypePromiscuous(zdev_t *dev, u32_t setValue)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-	   wd->swSniffer = setValue;
-	   zm_msg1_mm(ZM_LV_0, "wd->swSniffer ", wd->swSniffer);
-	   if (setValue)
-	   {
-	       	/* write register for sniffer mode */
-            zfHpSetSnifferMode(dev, 1);
-            zm_msg0_mm(ZM_LV_1, "enalbe sniffer mode");
-	   }
-	   else
-	   {
-            zfHpSetSnifferMode(dev, 0);
-            zm_msg0_mm(ZM_LV_0, "disalbe sniffer mode");
-	   }
+	wd->swSniffer = setValue;
+	zm_msg1_mm(ZM_LV_0, "wd->swSniffer ", wd->swSniffer);
+	if (setValue) {
+		/* write register for sniffer mode */
+		zfHpSetSnifferMode(dev, 1);
+		zm_msg0_mm(ZM_LV_1, "enalbe sniffer mode");
+	} else {
+		zfHpSetSnifferMode(dev, 0);
+		zm_msg0_mm(ZM_LV_0, "disalbe sniffer mode");
+	}
 }
 
-void zfiWlanSetXLinkMode(zdev_t* dev, u32_t setValue)
+void zfiWlanSetXLinkMode(zdev_t *dev, u32_t setValue)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    wd->XLinkMode = setValue;
-    if (setValue)
-    {
-        /* write register for sniffer mode */
-        zfHpSetSnifferMode(dev, 1);
-    }
-    else
-    {
-        zfHpSetSnifferMode(dev, 0);
-    }
+	wd->XLinkMode = setValue;
+	if (setValue) {
+		/* write register for sniffer mode */
+		zfHpSetSnifferMode(dev, 1);
+	} else
+		zfHpSetSnifferMode(dev, 0);
 }
 
-extern void zfStaChannelManagement(zdev_t* dev, u8_t scan);
-void zfiSetChannelManagement(zdev_t* dev, u32_t setting)
+extern void zfStaChannelManagement(zdev_t *dev, u8_t scan);
+
+void zfiSetChannelManagement(zdev_t *dev, u32_t setting)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    switch (setting)
-    {
-        case 1:
-            wd->sta.EnableHT = 1;
-            wd->BandWidth40 = 1;
-            wd->ExtOffset   = 1;
-            break;
-        case 3:
-            wd->sta.EnableHT = 1;
-            wd->BandWidth40 = 1;
-            wd->ExtOffset   = 3;
-            break;
-        case 0:
-            wd->sta.EnableHT = 1;
-            wd->BandWidth40 = 0;
-            wd->ExtOffset   = 0;
-            break;
-        default:
-            wd->BandWidth40 = 0;
-            wd->ExtOffset   = 0;
-            break;
+	switch (setting) {
+	case 1:
+		wd->sta.EnableHT = 1;
+		wd->BandWidth40 = 1;
+		wd->ExtOffset   = 1;
+		break;
+	case 3:
+		wd->sta.EnableHT = 1;
+		wd->BandWidth40 = 1;
+		wd->ExtOffset   = 3;
+		break;
+	case 0:
+		wd->sta.EnableHT = 1;
+		wd->BandWidth40 = 0;
+		wd->ExtOffset   = 0;
+		break;
+	default:
+		wd->BandWidth40 = 0;
+		wd->ExtOffset   = 0;
+		break;
+	}
 
-    }
-    zfCoreSetFrequencyEx(dev, wd->frequency, wd->BandWidth40,
-                    wd->ExtOffset, NULL);
+	zfCoreSetFrequencyEx(dev, wd->frequency, wd->BandWidth40,
+							wd->ExtOffset, NULL);
 }
 
-void zfiSetRifs(zdev_t* dev, u16_t setting)
+void zfiSetRifs(zdev_t *dev, u16_t setting)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    wd->sta.ie.HtInfo.ChannelInfo |= ExtHtCap_RIFSMode;
-    wd->sta.EnableHT = 1;
-    switch (setting)
-    {
-        case 0:
-            wd->sta.HT2040 = 0;
-//            zfHpSetRifs(dev, 1, 0, (wd->sta.currentFrequency < 3000)? 1:0);
-            break;
-        case 1:
-            wd->sta.HT2040 = 1;
-//            zfHpSetRifs(dev, 1, 1, (wd->sta.currentFrequency < 3000)? 1:0);
-            break;
-        default:
-            wd->sta.HT2040 = 0;
-//            zfHpSetRifs(dev, 1, 0, (wd->sta.currentFrequency < 3000)? 1:0);
-            break;
-    }
+	wd->sta.ie.HtInfo.ChannelInfo |= ExtHtCap_RIFSMode;
+	wd->sta.EnableHT = 1;
+
+	switch (setting) {
+	case 0:
+		wd->sta.HT2040 = 0;
+		/* zfHpSetRifs(dev, 1, 0,
+		*  (wd->sta.currentFrequency < 3000)? 1:0);
+		*/
+		break;
+	case 1:
+		wd->sta.HT2040 = 1;
+		/* zfHpSetRifs(dev, 1, 1,
+		*  (wd->sta.currentFrequency < 3000)? 1:0);
+		*/
+		break;
+	default:
+		wd->sta.HT2040 = 0;
+		/* zfHpSetRifs(dev, 1, 0,
+		*  (wd->sta.currentFrequency < 3000)? 1:0);
+		*/
+		break;
+	}
 }
 
-void zfiCheckRifs(zdev_t* dev)
+void zfiCheckRifs(zdev_t *dev)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    if(wd->sta.ie.HtInfo.ChannelInfo & ExtHtCap_RIFSMode)
-    {
-//        zfHpSetRifs(dev, wd->sta.EnableHT, wd->sta.HT2040, (wd->sta.currentFrequency < 3000)? 1:0);
-    }
+	if (wd->sta.ie.HtInfo.ChannelInfo & ExtHtCap_RIFSMode)
+		;
+		/* zfHpSetRifs(dev, wd->sta.EnableHT, wd->sta.HT2040,
+		*  (wd->sta.currentFrequency < 3000)? 1:0);
+		*/
 }
 
-void zfiSetReorder(zdev_t* dev, u16_t value)
+void zfiSetReorder(zdev_t *dev, u16_t value)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    wd->reorder = value;
+	wd->reorder = value;
 }
 
-void zfiSetSeqDebug(zdev_t* dev, u16_t value)
+void zfiSetSeqDebug(zdev_t *dev, u16_t value)
 {
-    zmw_get_wlan_dev(dev);
+	zmw_get_wlan_dev(dev);
 
-    wd->seq_debug = value;
+	wd->seq_debug = value;
 }
diff --git a/drivers/staging/otus/80211core/coid.c b/drivers/staging/otus/80211core/coid.c
index 88f8d349..0524e1f 100644
--- a/drivers/staging/otus/80211core/coid.c
+++ b/drivers/staging/otus/80211core/coid.c
@@ -2013,7 +2013,7 @@
 
     zmw_get_wlan_dev(dev);
 
-    if (wdsPortId > ZM_MAX_WDS_SUPPORT)
+    if (wdsPortId >= ZM_MAX_WDS_SUPPORT)
     {
         return ZM_ERR_WDS_PORT_ID;
     }
diff --git a/drivers/staging/p9auth/p9auth.c b/drivers/staging/p9auth/p9auth.c
index 3cac89b..9111dcb 100644
--- a/drivers/staging/p9auth/p9auth.c
+++ b/drivers/staging/p9auth/p9auth.c
@@ -180,8 +180,12 @@
 	if (down_interruptible(&dev->sem))
 		return -ERESTARTSYS;
 
+	user_buf_running = NULL;
+	hash_str = NULL;
 	node_ptr = kmalloc(sizeof(struct cap_node), GFP_KERNEL);
 	user_buf = kzalloc(count, GFP_KERNEL);
+	if (!node_ptr || !user_buf)
+		goto out;
 
 	if (copy_from_user(user_buf, buf, count)) {
 		retval = -EFAULT;
@@ -193,11 +197,21 @@
 	 * hashed capability supplied by the user to the list of hashes
 	 */
 	if (0 == iminor(filp->f_dentry->d_inode)) {
+		if (count > CAP_NODE_SIZE) {
+			retval = -EINVAL;
+			goto out;
+		}
 		printk(KERN_INFO "Capability being written to /dev/caphash : \n");
 		hexdump(user_buf, count);
 		memcpy(node_ptr->data, user_buf, count);
 		list_add(&(node_ptr->list), &(dev->head->list));
+		node_ptr = NULL;
 	} else {
+		if (!cap_devices[0].head ||
+				list_empty(&(cap_devices[0].head->list))) {
+			retval = -EINVAL;
+			goto out;
+		}
 		/*
 		 * break the supplied string into tokens with @ as the
 		 * delimiter If the string is "user1@user2@randomstring" we
@@ -208,6 +222,10 @@
 		source_user = strsep(&user_buf_running, "@");
 		target_user = strsep(&user_buf_running, "@");
 		rand_str = strsep(&user_buf_running, "@");
+		if (!source_user || !target_user || !rand_str) {
+			retval = -EINVAL;
+			goto out;
+		}
 
 		/* hash the string user1@user2 with rand_str as the key */
 		len = strlen(source_user) + strlen(target_user) + 1;
@@ -224,7 +242,7 @@
 			retval = -EFAULT;
 			goto out;
 		}
-		memcpy(node_ptr->data, result, CAP_NODE_SIZE);
+		memcpy(node_ptr->data, result, CAP_NODE_SIZE);  /* why? */
 		/* Change the process's uid if the hash is present in the
 		 * list of hashes
 		 */
@@ -299,6 +317,10 @@
 		dev->size = *f_pos;
 
 out:
+	kfree(node_ptr);
+	kfree(user_buf);
+	kfree(user_buf_running);
+	kfree(hash_str);
 	up(&dev->sem);
 	return retval;
 }
diff --git a/drivers/staging/pata_rdc/Kconfig b/drivers/staging/pata_rdc/Kconfig
new file mode 100644
index 0000000..7a406b0
--- /dev/null
+++ b/drivers/staging/pata_rdc/Kconfig
@@ -0,0 +1,6 @@
+config RDC_17F3101X
+	tristate "RDC_17F3101X IDE support"
+	depends on PCI && ATA && ATA_SFF
+	---help---
+	  This is an experimental driver for RDC_17F31011 and
+	  RDC_17F31012 IDE driver.
diff --git a/drivers/staging/pata_rdc/Makefile b/drivers/staging/pata_rdc/Makefile
new file mode 100644
index 0000000..f952c16
--- /dev/null
+++ b/drivers/staging/pata_rdc/Makefile
@@ -0,0 +1,2 @@
+obj-$(CONFIG_RDC_17F3101X)	+= pata_rdc.o
+
diff --git a/drivers/staging/pata_rdc/pata_rdc.c b/drivers/staging/pata_rdc/pata_rdc.c
new file mode 100644
index 0000000..6252745
--- /dev/null
+++ b/drivers/staging/pata_rdc/pata_rdc.c
@@ -0,0 +1,955 @@
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/module.h>
+
+#include <linux/pci.h>
+#include <linux/device.h>
+
+#include <scsi/scsi_host.h>
+#include <linux/libata.h>
+
+#include "pata_rdc.h"
+
+static const struct pci_device_id rdc_pata_id_table[] = {
+	{ PCI_DEVICE(0x17F3, 0x1011), RDC_17F31011},
+	{ PCI_DEVICE(0x17F3, 0x1012), RDC_17F31012},
+	{ }	/* terminate list */
+};
+MODULE_DEVICE_TABLE(pci, rdc_pata_id_table);
+
+/* see ATA Host Adapters Standards. */
+static struct pci_bits ATA_Decode_Enable_Bits[] = {
+	{ 0x41U, 1U, 0x80UL, 0x80UL },	/* port (Channel) 0 */
+	{ 0x43U, 1U, 0x80UL, 0x80UL },	/* port (Channel) 1 */
+};
+
+static uint PCIDeviceIO_ReadPCIConfiguration(struct pci_dev *pdev, uint Offset, uint Length, void *pBuffer)
+{
+	uint funcresult;
+	unchar *pchar;
+	uint i;
+
+	funcresult = TRUE;
+
+	pchar = pBuffer;
+
+	for (i = 0; i < Length; i++) {
+		pci_read_config_byte(pdev, Offset, pchar);
+		Offset++;
+		pchar++;
+	}
+
+	funcresult = TRUE;
+
+	goto funcexit;
+funcexit:
+
+	return funcresult;
+}
+
+static uint PCIDeviceIO_WritePCIConfiguration(struct pci_dev *pdev, uint Offset, uint Length, void *pBuffer)
+{
+	uint funcresult;
+	unchar *pchar;
+	uint i;
+
+	funcresult = TRUE;
+
+	pchar = pBuffer;
+
+	for (i = 0; i < Length; i++) {
+		pci_write_config_byte(pdev, Offset, *pchar);
+		Offset++;
+		pchar++;
+	}
+
+	funcresult = TRUE;
+
+	goto funcexit;
+funcexit:
+
+	return funcresult;
+}
+
+static uint ATAHostAdapter_SetPrimaryPIO(struct pci_dev *pdev, uint DeviceID,
+					 uint PIOTimingMode, uint DMAEnable,
+					 uint PrefetchPostingEnable)
+{
+	uint funcresult;
+	uint result;
+	uint ATATimingRegister;
+	uint Device1TimingRegister;
+
+	funcresult = TRUE;
+
+	ATATimingRegister = 0;
+	Device1TimingRegister = 0;
+
+	result = PCIDeviceIO_ReadPCIConfiguration(pdev,
+						 ATAConfiguration_ID_PrimaryTiming + ATAConfiguration_PCIOffset,
+						 ATAConfiguration_ID_PrimaryTiming_Size,
+						 &ATATimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_ReadPCIConfiguration(pdev,
+						  ATAConfiguration_ID_Device1Timing + ATAConfiguration_PCIOffset,
+						  ATAConfiguration_ID_Device1Timing_Size,
+						  &Device1TimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device1TimingRegisterEnable;
+
+	switch (DeviceID) {
+	case 0:
+		/* mask clear */
+		ATATimingRegister &= ~(ATAConfiguration_PrimaryTiming_Device0FastTimingEnable |
+				      ATAConfiguration_PrimaryTiming_Device0IORDYSampleModeEnable |
+				      ATAConfiguration_PrimaryTiming_Device0PrefetchandPostingEnable |
+				      ATAConfiguration_PrimaryTiming_Device0DMATimingEnable |
+				      ATAConfiguration_PrimaryTiming_Device0RecoveryMode |
+				      ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode);
+
+		if (PIOTimingMode > PIO0)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0FastTimingEnable;
+
+		if (PIOTimingMode >= PIO3)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0IORDYSampleModeEnable;
+
+		if (PIOTimingMode >= PIO2 && PrefetchPostingEnable == TRUE)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0PrefetchandPostingEnable;
+
+		if (DMAEnable == TRUE && PIOTimingMode >= PIO2)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0DMATimingEnable;
+
+		if (PIOTimingMode <= PIO2)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0RecoveryMode_0;
+		else if (PIOTimingMode == PIO3)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0RecoveryMode_1;
+		else if (PIOTimingMode == PIO4)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0RecoveryMode_3;
+
+		if (PIOTimingMode <= PIO1)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode_0;
+		else if (PIOTimingMode == PIO2)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode_1;
+		else if (PIOTimingMode <= PIO4)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode_2;
+		break;
+	case 1:
+		ATATimingRegister &= ~(ATAConfiguration_PrimaryTiming_Device1FastTimingEnable |
+				       ATAConfiguration_PrimaryTiming_Device1IORDYSampleModeEnable |
+				       ATAConfiguration_PrimaryTiming_Device1PrefetchandPostingEnable |
+				       ATAConfiguration_PrimaryTiming_Device1DMATimingEnable);
+
+		if (PIOTimingMode > PIO0)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device1FastTimingEnable;
+
+		if (PIOTimingMode >= PIO3)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device1IORDYSampleModeEnable;
+
+		if (PIOTimingMode >= PIO2 && PrefetchPostingEnable == TRUE)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device1PrefetchandPostingEnable;
+
+		if (DMAEnable == TRUE && PIOTimingMode >= PIO2)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device1DMATimingEnable;
+
+		Device1TimingRegister &= ~(ATAConfiguration_Device1Timing_PrimaryRecoveryMode |
+					   ATAConfiguration_Device1Timing_PrimaryIORDYSampleMode);
+
+		if (PIOTimingMode <= PIO2)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_PrimaryRecoveryMode_0;
+		else if (PIOTimingMode == PIO3)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_PrimaryRecoveryMode_1;
+		else if (PIOTimingMode == PIO4)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_PrimaryRecoveryMode_3;
+
+		if (PIOTimingMode <= PIO1)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_PrimaryIORDYSampleMode_0;
+		else if (PIOTimingMode == PIO2)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_PrimaryIORDYSampleMode_1;
+		else if (PIOTimingMode <= PIO4)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_PrimaryIORDYSampleMode_2;
+		break;
+	default:
+		funcresult = FALSE;
+		goto funcexit;
+		break;
+	}
+
+	result = PCIDeviceIO_WritePCIConfiguration(pdev,
+						   ATAConfiguration_ID_PrimaryTiming + ATAConfiguration_PCIOffset,
+						   ATAConfiguration_ID_PrimaryTiming_Size,
+						   &ATATimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_WritePCIConfiguration(pdev,
+						   ATAConfiguration_ID_Device1Timing + ATAConfiguration_PCIOffset,
+						   ATAConfiguration_ID_Device1Timing_Size,
+						   &Device1TimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	goto funcexit;
+funcexit:
+
+	return funcresult;
+}
+
+static uint ATAHostAdapter_SetSecondaryPIO(struct pci_dev *pdev, uint DeviceID,
+					   uint PIOTimingMode, uint DMAEnable,
+					   uint PrefetchPostingEnable)
+{
+	uint funcresult;
+	uint result;
+	uint ATATimingRegister;
+	uint Device1TimingRegister;
+
+	funcresult = TRUE;
+
+	ATATimingRegister = 0;
+	Device1TimingRegister = 0;
+
+	result = PCIDeviceIO_ReadPCIConfiguration(pdev,
+						  ATAConfiguration_ID_SecondaryTiming + ATAConfiguration_PCIOffset,
+						  ATAConfiguration_ID_SecondaryTiming_Size,
+						  &ATATimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_ReadPCIConfiguration(pdev,
+						  ATAConfiguration_ID_Device1Timing + ATAConfiguration_PCIOffset,
+						  ATAConfiguration_ID_Device1Timing_Size,
+						  &Device1TimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device1TimingRegisterEnable;
+
+	switch (DeviceID) {
+	case 0:
+		/* mask clear */
+		ATATimingRegister &= ~(ATAConfiguration_PrimaryTiming_Device0FastTimingEnable |
+				       ATAConfiguration_PrimaryTiming_Device0IORDYSampleModeEnable |
+				       ATAConfiguration_PrimaryTiming_Device0PrefetchandPostingEnable |
+				       ATAConfiguration_PrimaryTiming_Device0DMATimingEnable |
+				       ATAConfiguration_PrimaryTiming_Device0RecoveryMode |
+				       ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode);
+
+		if (PIOTimingMode > PIO0)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0FastTimingEnable;
+
+		if (PIOTimingMode >= PIO3)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0IORDYSampleModeEnable;
+
+		if (PIOTimingMode >= PIO2 && PrefetchPostingEnable == TRUE)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0PrefetchandPostingEnable;
+
+		if (DMAEnable == TRUE && PIOTimingMode >= PIO2)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0DMATimingEnable;
+
+		if (PIOTimingMode <= PIO2)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0RecoveryMode_0;
+		else if (PIOTimingMode == PIO3)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0RecoveryMode_1;
+		else if (PIOTimingMode == PIO4)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0RecoveryMode_3;
+
+		if (PIOTimingMode <= PIO1)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode_0;
+		else if (PIOTimingMode == PIO2)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode_1;
+		else if (PIOTimingMode <= PIO4)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode_2;
+		break;
+	case 1:
+		ATATimingRegister &= ~(ATAConfiguration_PrimaryTiming_Device1FastTimingEnable |
+				       ATAConfiguration_PrimaryTiming_Device1IORDYSampleModeEnable |
+				       ATAConfiguration_PrimaryTiming_Device1PrefetchandPostingEnable |
+				       ATAConfiguration_PrimaryTiming_Device1DMATimingEnable);
+
+		if (PIOTimingMode > PIO0)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device1FastTimingEnable;
+
+		if (PIOTimingMode >= PIO3)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device1IORDYSampleModeEnable;
+
+		if (PIOTimingMode >= PIO2 && PrefetchPostingEnable == TRUE)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device1PrefetchandPostingEnable;
+
+		if (DMAEnable == TRUE && PIOTimingMode >= PIO2)
+			ATATimingRegister |= ATAConfiguration_PrimaryTiming_Device1DMATimingEnable;
+
+		Device1TimingRegister &= ~(ATAConfiguration_Device1Timing_SecondaryRecoveryMode |
+					   ATAConfiguration_Device1Timing_SecondaryIORDYSampleMode);
+
+		if (PIOTimingMode <= PIO2)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_SecondaryRecoveryMode_0;
+		else if (PIOTimingMode == PIO3)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_SecondaryRecoveryMode_1;
+		else if (PIOTimingMode == PIO4)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_SecondaryRecoveryMode_3;
+
+		if (PIOTimingMode <= PIO1)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_SecondaryIORDYSampleMode_0;
+		else if (PIOTimingMode == PIO2)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_SecondaryIORDYSampleMode_1;
+		else if (PIOTimingMode <= PIO4)
+			Device1TimingRegister |= ATAConfiguration_Device1Timing_SecondaryIORDYSampleMode_2;
+		break;
+	default:
+		funcresult = FALSE;
+		goto funcexit;
+		break;
+	}
+
+	result = PCIDeviceIO_WritePCIConfiguration(pdev,
+						   ATAConfiguration_ID_SecondaryTiming + ATAConfiguration_PCIOffset,
+						   ATAConfiguration_ID_SecondaryTiming_Size,
+						   &ATATimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_WritePCIConfiguration(pdev,
+						   ATAConfiguration_ID_Device1Timing + ATAConfiguration_PCIOffset,
+						   ATAConfiguration_ID_Device1Timing_Size,
+						   &Device1TimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	goto funcexit;
+funcexit:
+	return funcresult;
+}
+
+static uint ATAHostAdapter_SetPrimaryUDMA(struct pci_dev *pdev, uint DeviceID,
+					  uint UDMAEnable, uint UDMATimingMode)
+{
+	uint funcresult;
+	uint result;
+	uint UDMAControlRegister;
+	uint UDMATimingRegister;
+	ulong IDEIOConfigurationRegister;
+
+	funcresult = TRUE;
+	UDMAControlRegister = 0;
+	UDMATimingRegister = 0;
+	IDEIOConfigurationRegister = 0;
+
+	result = PCIDeviceIO_ReadPCIConfiguration(pdev,
+						  ATAConfiguration_ID_UDMAControl + ATAConfiguration_PCIOffset,
+						  ATAConfiguration_ID_UDMAControl_Size,
+						  &UDMAControlRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_ReadPCIConfiguration(pdev,
+						  ATAConfiguration_ID_UDMATiming + ATAConfiguration_PCIOffset,
+						  ATAConfiguration_ID_UDMATiming_Size,
+						  &UDMATimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_ReadPCIConfiguration(pdev,
+						  ATAConfiguration_ID_IDEIOConfiguration + ATAConfiguration_PCIOffset,
+						  ATAConfiguration_ID_IDEIOConfiguration_Size,
+						  &IDEIOConfigurationRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	/*Rom Code will determine the device cable type and ATA 100.*/
+	/*IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_DeviceCable80Report;*/
+	/*IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_ATA100IsSupported;*/
+
+	switch (DeviceID) {
+	case 0:
+		UDMAControlRegister &= ~(ATAConfiguration_UDMAControl_PrimaryDevice0UDMAModeEnable);
+		if (UDMAEnable == TRUE)
+			UDMAControlRegister |= ATAConfiguration_UDMAControl_PrimaryDevice0UDMAModeEnable;
+
+		IDEIOConfigurationRegister &= ~(ATAConfiguration_IDEIOConfiguration_PrimaryDevice066MhzEnable |
+						ATAConfiguration_IDEIOConfiguration_PrimaryDevice0100MhzEnable);
+
+		if (UDMATimingMode >= UDMA5)
+			IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_PrimaryDevice0100MhzEnable;
+		else if (UDMATimingMode >= UDMA3)
+			IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_PrimaryDevice066MhzEnable;
+
+		/* if 80 cable report */
+		UDMATimingRegister &= ~(ATAConfiguration_UDMATiming_PrimaryDevice0CycleTime);
+
+		if (UDMATimingMode == UDMA0) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_PrimaryDevice0CycleTime_0;
+		} else if (UDMATimingMode == UDMA1 ||
+			   UDMATimingMode == UDMA3 ||
+			   UDMATimingMode == UDMA5) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_PrimaryDevice0CycleTime_1;
+		} else if (UDMATimingMode == UDMA2 ||
+			   UDMATimingMode == UDMA4) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_PrimaryDevice0CycleTime_2;
+		}
+		break;
+	case 1:
+		UDMAControlRegister &= ~(ATAConfiguration_UDMAControl_PrimaryDevice1UDMAModeEnable);
+		if (UDMAEnable == TRUE)
+			UDMAControlRegister |= ATAConfiguration_UDMAControl_PrimaryDevice1UDMAModeEnable;
+
+		IDEIOConfigurationRegister &= ~(ATAConfiguration_IDEIOConfiguration_PrimaryDevice166MhzEnable |
+						ATAConfiguration_IDEIOConfiguration_PrimaryDevice1100MhzEnable);
+
+		if (UDMATimingMode >= UDMA5)
+			IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_PrimaryDevice1100MhzEnable;
+		else if (UDMATimingMode >= UDMA3)
+			IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_PrimaryDevice166MhzEnable;
+
+		/* if 80 cable report */
+		UDMATimingRegister &= ~(ATAConfiguration_UDMATiming_PrimaryDevice1CycleTime);
+
+		if (UDMATimingMode == UDMA0) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_PrimaryDevice1CycleTime_0;
+		} else if (UDMATimingMode == UDMA1 ||
+			   UDMATimingMode == UDMA3 ||
+			   UDMATimingMode == UDMA5) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_PrimaryDevice1CycleTime_1;
+		} else if (UDMATimingMode == UDMA2 ||
+			   UDMATimingMode == UDMA4) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_PrimaryDevice1CycleTime_2;
+		}
+		break;
+	default:
+		funcresult = FALSE;
+		goto funcexit;
+		break;
+	}
+
+	result = PCIDeviceIO_WritePCIConfiguration(pdev,
+						   ATAConfiguration_ID_UDMAControl + ATAConfiguration_PCIOffset,
+						   ATAConfiguration_ID_UDMAControl_Size,
+						   &UDMAControlRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_WritePCIConfiguration(pdev,
+						   ATAConfiguration_ID_UDMATiming + ATAConfiguration_PCIOffset,
+						   ATAConfiguration_ID_UDMATiming_Size,
+						   &UDMATimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_WritePCIConfiguration(pdev,
+						   ATAConfiguration_ID_IDEIOConfiguration + ATAConfiguration_PCIOffset,
+						   ATAConfiguration_ID_IDEIOConfiguration_Size,
+						   &IDEIOConfigurationRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	goto funcexit;
+funcexit:
+	return funcresult;
+}
+
+static uint ATAHostAdapter_SetSecondaryUDMA(struct pci_dev *pdev, uint DeviceID,
+					    uint UDMAEnable, uint UDMATimingMode)
+{
+	uint funcresult;
+	uint result;
+	uint UDMAControlRegister;
+	uint UDMATimingRegister;
+	ulong IDEIOConfigurationRegister;
+
+	funcresult = TRUE;
+
+	UDMAControlRegister = 0;
+	UDMATimingRegister = 0;
+	IDEIOConfigurationRegister = 0;
+
+	result = PCIDeviceIO_ReadPCIConfiguration(pdev,
+						  ATAConfiguration_ID_UDMAControl + ATAConfiguration_PCIOffset,
+						  ATAConfiguration_ID_UDMAControl_Size,
+						  &UDMAControlRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_ReadPCIConfiguration(pdev,
+						  ATAConfiguration_ID_UDMATiming + ATAConfiguration_PCIOffset,
+						  ATAConfiguration_ID_UDMATiming_Size,
+						  &UDMATimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_ReadPCIConfiguration(pdev,
+						  ATAConfiguration_ID_IDEIOConfiguration + ATAConfiguration_PCIOffset,
+						  ATAConfiguration_ID_IDEIOConfiguration_Size,
+						  &IDEIOConfigurationRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	/* Rom Code will determine the device cable type and ATA 100. */
+	/* IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_DeviceCable80Report; */
+	/* IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_ATA100IsSupported; */
+
+	switch (DeviceID) {
+	case 0:
+		UDMAControlRegister &= ~(ATAConfiguration_UDMAControl_SecondaryDevice0UDMAModeEnable);
+		if (UDMAEnable == TRUE)
+			UDMAControlRegister |= ATAConfiguration_UDMAControl_SecondaryDevice0UDMAModeEnable;
+
+		IDEIOConfigurationRegister &= ~(ATAConfiguration_IDEIOConfiguration_SecondaryDevice066MhzEnable |
+						ATAConfiguration_IDEIOConfiguration_SecondaryDevice0100MhzEnable);
+
+		if (UDMATimingMode >= UDMA5)
+			IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_SecondaryDevice0100MhzEnable;
+		else if (UDMATimingMode >= UDMA3)
+			IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_SecondaryDevice066MhzEnable;
+
+		/* if 80 cable report */
+		UDMATimingRegister &= ~(ATAConfiguration_UDMATiming_SecondaryDevice0CycleTime);
+
+		if (UDMATimingMode == UDMA0) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_SecondaryDevice0CycleTime_0;
+		} else if (UDMATimingMode == UDMA1 ||
+			   UDMATimingMode == UDMA3 ||
+			   UDMATimingMode == UDMA5) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_SecondaryDevice0CycleTime_1;
+		} else if (UDMATimingMode == UDMA2 ||
+			   UDMATimingMode == UDMA4) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_SecondaryDevice0CycleTime_2;
+		}
+		break;
+	case 1:
+		UDMAControlRegister &= ~(ATAConfiguration_UDMAControl_SecondaryDevice1UDMAModeEnable);
+		if (UDMAEnable == TRUE)
+			UDMAControlRegister |= ATAConfiguration_UDMAControl_SecondaryDevice1UDMAModeEnable;
+
+		IDEIOConfigurationRegister &= ~(ATAConfiguration_IDEIOConfiguration_SecondaryDevice166MhzEnable |
+						ATAConfiguration_IDEIOConfiguration_SecondaryDevice1100MhzEnable);
+
+		if (UDMATimingMode >= UDMA5)
+			IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_SecondaryDevice1100MhzEnable;
+		else if (UDMATimingMode >= UDMA3)
+			IDEIOConfigurationRegister |= ATAConfiguration_IDEIOConfiguration_SecondaryDevice166MhzEnable;
+
+		/* if 80 cable report */
+		UDMATimingRegister &= ~(ATAConfiguration_UDMATiming_SecondaryDevice1CycleTime);
+
+		if (UDMATimingMode == UDMA0) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_SecondaryDevice1CycleTime_0;
+		} else if (UDMATimingMode == UDMA1 ||
+			   UDMATimingMode == UDMA3 ||
+			   UDMATimingMode == UDMA5) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_SecondaryDevice1CycleTime_1;
+		} else if (UDMATimingMode == UDMA2 ||
+			   UDMATimingMode == UDMA4) {
+			UDMATimingRegister |= ATAConfiguration_UDMATiming_SecondaryDevice1CycleTime_2;
+		}
+		break;
+	default:
+		funcresult = FALSE;
+		goto funcexit;
+		break;
+	}
+
+	result = PCIDeviceIO_WritePCIConfiguration(pdev,
+						   ATAConfiguration_ID_UDMAControl + ATAConfiguration_PCIOffset,
+						   ATAConfiguration_ID_UDMAControl_Size,
+						   &UDMAControlRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_WritePCIConfiguration(pdev,
+						   ATAConfiguration_ID_UDMATiming + ATAConfiguration_PCIOffset,
+						   ATAConfiguration_ID_UDMATiming_Size,
+						   &UDMATimingRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	result = PCIDeviceIO_WritePCIConfiguration(pdev,
+						   ATAConfiguration_ID_IDEIOConfiguration + ATAConfiguration_PCIOffset,
+						   ATAConfiguration_ID_IDEIOConfiguration_Size,
+						   &IDEIOConfigurationRegister);
+	if (result == FALSE) {
+		funcresult = FALSE;
+		goto funcexit;
+	}
+
+	goto funcexit;
+funcexit:
+	return funcresult;
+}
+
+static int rdc_pata_port_start(struct ata_port *ap)
+{
+	uint    Channel;
+
+	Channel = ap->port_no;
+	dev_dbg(ap->dev, "%s: Channel: %u\n", __func__, Channel);
+	if (ap->ioaddr.bmdma_addr) {
+		return ata_port_start(ap);
+	} else {
+		dev_dbg(ap->dev, "%s: return 0!!!\n", __func__);
+		return 0;
+	}
+}
+
+static void rdc_pata_port_stop(struct ata_port *ap)
+{
+	uint    Channel;
+
+	Channel = ap->port_no;
+
+	dev_dbg(ap->dev, "%s Channel: %u\n", __func__, Channel);
+}
+
+static int rdc_pata_prereset(struct ata_link *link, unsigned long deadline)
+{
+	struct pci_dev *pdev;
+	struct ata_port *ap;
+	uint Channel;
+
+	dev_dbg(link->ap->dev, "%s\n", __func__);
+
+	ap = link->ap;
+	pdev = to_pci_dev(ap->host->dev);
+
+	Channel = ap->port_no;
+
+	/* test ATA Decode Enable Bits, should be enable. */
+	if (!pci_test_config_bits(pdev, &ATA_Decode_Enable_Bits[Channel])) {
+		dev_dbg(link->ap->dev, "%s: Channel: %u, Decode Disable\n",
+			__func__, Channel);
+		return -ENOENT;
+	} else {
+		dev_dbg(link->ap->dev, "%s: Channel: %u, Decode Enable\n",
+			__func__, Channel);
+		return ata_std_prereset(link, deadline);
+	}
+}
+
+static int rdc_pata_cable_detect(struct ata_port *ap)
+{
+	struct pci_dev *pdev;
+	uint Channel;
+	uint Mask;
+	u32 u32Value;
+
+	dev_dbg(ap->dev, "%s\n", __func__);
+
+	pdev = to_pci_dev(ap->host->dev);
+
+	Channel = ap->port_no;
+
+	if (Channel == 0)
+		Mask = ATAConfiguration_IDEIOConfiguration_PrimaryDeviceCable80Report;
+	else
+		Mask = ATAConfiguration_IDEIOConfiguration_SecondaryDeviceCable80Report;
+
+	/* check BIOS cable detect results */
+	pci_read_config_dword(pdev, ATAConfiguration_ID_IDEIOConfiguration + ATAConfiguration_PCIOffset, &u32Value);
+
+	if ((u32Value & Mask) == 0) {
+		dev_dbg(ap->dev, "%s: Channel: %u, PATA40 \n",
+			__func__, Channel);
+		return ATA_CBL_PATA40;
+	} else {
+		dev_dbg(ap->dev, "%s: Channel: %u, PATA80 \n",
+			__func__, Channel);
+		return ATA_CBL_PATA80;
+	}
+}
+
+static void rdc_pata_set_piomode(struct ata_port *ap, struct ata_device *adev)
+{
+	struct pci_dev *pdev;
+	uint    Channel;
+	uint    DeviceID;
+	uint    PIOTimingMode;
+	uint    PrefetchPostingEnable;
+
+	dev_dbg(ap->dev, "%s\n", __func__);
+
+	pdev = to_pci_dev(ap->host->dev);
+
+	Channel = ap->port_no;
+	DeviceID = adev->devno;
+	/*
+	 * piomode = 0, 1, 2, 3... ; adev->pio_mode = XFER_PIO_0, XFER_PIO_1,
+	 * XFER_PIO_2, XFER_PIO_3...
+	 */
+	PIOTimingMode = adev->pio_mode - XFER_PIO_0;
+
+	if (adev->class == ATA_DEV_ATA) {
+		PrefetchPostingEnable = TRUE;
+	} else {
+		/* ATAPI, CD DVD Rom */
+		PrefetchPostingEnable = FALSE;
+	}
+
+	/* PIO configuration clears DTE unconditionally.  It will be
+	 * programmed in set_dmamode which is guaranteed to be called
+	 * after set_piomode if any DMA mode is available.
+	 */
+
+	/* Ensure the UDMA bit is off - it will be turned back on if UDMA is
+	 * selected */
+
+	if (Channel == 0) {
+		ATAHostAdapter_SetPrimaryPIO(
+		    pdev,
+		    DeviceID,
+		    PIOTimingMode,
+		    TRUE,
+		    PrefetchPostingEnable
+		    );
+
+		ATAHostAdapter_SetPrimaryUDMA(
+		    pdev,
+		    DeviceID,
+		    FALSE,
+		    UDMA0
+		    );
+	} else {
+		ATAHostAdapter_SetSecondaryPIO(
+		    pdev,
+		    DeviceID,
+		    PIOTimingMode,
+		    TRUE,
+		    PrefetchPostingEnable
+		    );
+
+		ATAHostAdapter_SetSecondaryUDMA(
+		    pdev,
+		    DeviceID,
+		    FALSE,
+		    UDMA0
+		    );
+	}
+	dev_dbg(ap->dev, "%s: Channel: %u, DeviceID: %u, PIO: %d\n",
+		__func__, Channel, DeviceID, PIOTimingMode);
+}
+
+static void rdc_pata_set_dmamode(struct ata_port *ap, struct ata_device *adev)
+{
+	struct pci_dev *pdev;
+	uint    Channel;
+	uint    DeviceID;
+	uint    PIOTimingMode;
+	uint    PrefetchPostingEnable;
+	uint    DMATimingMode;
+	uint    UDMAEnable;
+
+	dev_dbg(ap->dev, "%s\n", __func__);
+
+	pdev = to_pci_dev(ap->host->dev);
+
+	Channel = ap->port_no;
+	DeviceID = adev->devno;
+	PIOTimingMode = adev->pio_mode - XFER_PIO_0;  /* piomode = 0, 1, 2, 3... ; adev->pio_mode = XFER_PIO_0, XFER_PIO_1, XFER_PIO_2, XFER_PIO_3... */
+	DMATimingMode = adev->dma_mode; /* UDMA or MDMA */
+
+	if (adev->class == ATA_DEV_ATA) {
+		PrefetchPostingEnable = TRUE;
+	} else {
+		/* ATAPI, CD DVD Rom */
+		PrefetchPostingEnable = FALSE;
+	}
+
+	if (ap->udma_mask == 0) {
+		/* ata_port dont support udma. depend on hardware spec. */
+		UDMAEnable = FALSE;
+	} else {
+		UDMAEnable = TRUE;
+	}
+
+	if (Channel == 0) {
+		if (DMATimingMode >= XFER_UDMA_0) {
+			/* UDMA */
+			ATAHostAdapter_SetPrimaryPIO(pdev,
+				DeviceID,
+				PIOTimingMode,
+				TRUE,
+				PrefetchPostingEnable);
+
+			ATAHostAdapter_SetPrimaryUDMA(pdev,
+				DeviceID,
+				UDMAEnable,
+				DMATimingMode - XFER_UDMA_0);
+			dev_dbg(ap->dev,
+				"%s: Channel: %u, DeviceID: %u, UDMA: %u\n",
+				__func__, Channel, DeviceID,
+				(uint)(DMATimingMode - XFER_UDMA_0));
+		} else {
+			/* MDMA */
+			ATAHostAdapter_SetPrimaryPIO(pdev,
+				DeviceID,
+				(DMATimingMode - XFER_MW_DMA_0) + PIO2, /* MDMA0 = PIO2 */
+				TRUE,
+				PrefetchPostingEnable);
+
+			ATAHostAdapter_SetPrimaryUDMA(pdev,
+				DeviceID,
+				FALSE,
+				UDMA0);
+			dev_dbg(ap->dev,
+				"%s: Channel: %u, DeviceID: %u, MDMA: %u\n",
+				__func__, Channel, DeviceID,
+				(uint)(DMATimingMode - XFER_MW_DMA_0));
+		}
+	} else {
+		if (DMATimingMode >= XFER_UDMA_0) {
+			/* UDMA */
+			ATAHostAdapter_SetSecondaryPIO(pdev,
+				DeviceID,
+				PIOTimingMode,
+				TRUE,
+				PrefetchPostingEnable);
+
+			ATAHostAdapter_SetSecondaryUDMA(pdev,
+				DeviceID,
+				UDMAEnable,
+				DMATimingMode - XFER_UDMA_0);
+			dev_dbg(ap->dev,
+				"%s: Channel: %u, DeviceID: %u, UDMA: %u\n",
+				__func__, Channel, DeviceID,
+				(uint)(DMATimingMode - XFER_UDMA_0));
+		} else {
+			/* MDMA */
+			ATAHostAdapter_SetSecondaryPIO(pdev,
+				DeviceID,
+				(DMATimingMode - XFER_MW_DMA_0) + PIO2, /* MDMA0 = PIO2 */
+				TRUE,
+				PrefetchPostingEnable);
+
+			ATAHostAdapter_SetSecondaryUDMA(pdev,
+				DeviceID,
+				FALSE,
+				UDMA0);
+			dev_dbg(ap->dev,
+				"%s: Channel: %u, DeviceID: %u, MDMA: %u \n",
+				__func__, Channel, DeviceID,
+				(uint)(DMATimingMode - XFER_MW_DMA_0));
+		}
+	}
+}
+
+static struct scsi_host_template rdc_pata_sht = {
+	ATA_BMDMA_SHT(KBUILD_MODNAME),
+};
+
+static struct ata_port_operations rdc_pata_ops = {
+	.inherits	= &ata_bmdma_port_ops,
+
+	.port_start	= rdc_pata_port_start,
+	.port_stop	= rdc_pata_port_stop,
+	.prereset	= rdc_pata_prereset,
+	.cable_detect	= rdc_pata_cable_detect,
+	.set_piomode	= rdc_pata_set_piomode,
+	.set_dmamode	= rdc_pata_set_dmamode,
+};
+
+static struct ata_port_info rdc_pata_port_info[] = {
+	[RDC_17F31011] = {
+	.flags		= ATA_FLAG_SLAVE_POSS,
+	.pio_mask	= 0x1f,		/* pio0-4 */
+	.mwdma_mask	= 0x07,		/* mwdma0-2 */
+	.udma_mask	= ATA_UDMA5,	/* udma0-5 */
+	.port_ops	= &rdc_pata_ops,
+	},
+
+	[RDC_17F31012] = {
+	.flags		= ATA_FLAG_SLAVE_POSS,
+	.pio_mask	= 0x1f,		/* pio0-4 */
+	.mwdma_mask	= 0x07,		/* mwdma0-2 */
+	.udma_mask	= ATA_UDMA5,	/* udma0-5 */
+	.port_ops	= &rdc_pata_ops,
+	},
+};
+
+static int __devinit rdc_init_one(struct pci_dev *pdev,
+				  const struct pci_device_id *ent)
+{
+	struct ata_port_info port_info[2];
+	const struct ata_port_info *ppinfo[] = { &port_info[0], &port_info[1] };
+
+	int rc;
+
+	dev_dbg(&pdev->dev, "%s\n", __func__);
+
+	port_info[0] = rdc_pata_port_info[ent->driver_data];
+	port_info[1] = rdc_pata_port_info[ent->driver_data];
+
+	rc = pci_enable_device(pdev);
+	if (rc) {
+		dev_dbg(&pdev->dev, "%s pci_enable_device failed\n", __func__);
+		return rc;
+	}
+	pci_intx(pdev, 1);
+
+	return ata_pci_sff_init_one(pdev, ppinfo, &rdc_pata_sht, NULL);
+}
+
+static struct pci_driver rdc_pata_driver = {
+	.name		= KBUILD_MODNAME,
+	.id_table	= rdc_pata_id_table,
+	.probe		= rdc_init_one,
+	.remove		= ata_pci_remove_one,
+#ifdef CONFIG_PM
+	.suspend	= ata_pci_device_suspend,
+	.resume		= ata_pci_device_resume,
+#endif
+};
+
+static int __init pata_rdc_init(void)
+{
+	return pci_register_driver(&rdc_pata_driver);
+}
+
+static void __exit pata_rdc_exit(void)
+{
+	pci_unregister_driver(&rdc_pata_driver);
+}
+
+module_init(pata_rdc_init);
+module_exit(pata_rdc_exit);
+
+MODULE_LICENSE("GPL");
+MODULE_DESCRIPTION("RDC PCI IDE Driver");
diff --git a/drivers/staging/pata_rdc/pata_rdc.h b/drivers/staging/pata_rdc/pata_rdc.h
new file mode 100644
index 0000000..a833339
--- /dev/null
+++ b/drivers/staging/pata_rdc/pata_rdc.h
@@ -0,0 +1,144 @@
+#ifndef pata_rdc_H
+#define pata_rdc_H
+
+#ifndef TRUE
+#define TRUE	1
+#endif
+
+#ifndef FALSE
+#define FALSE	0
+#endif
+
+/* ATA Configuration Register ID offset address size */
+#define ATAConfiguration_PCIOffset			0x40
+#define ATAConfiguration_ID_PrimaryTiming		0x00
+#define ATAConfiguration_ID_SecondaryTiming		0x02
+#define ATAConfiguration_ID_Device1Timing		0x04
+#define ATAConfiguration_ID_UDMAControl			0x08
+#define ATAConfiguration_ID_UDMATiming			0x0A
+#define ATAConfiguration_ID_IDEIOConfiguration		0x14
+
+#define ATAConfiguration_ID_PrimaryTiming_Size		2
+#define ATAConfiguration_ID_SecondaryTiming_Size	2
+#define ATAConfiguration_ID_Device1Timing_Size		1
+#define ATAConfiguration_ID_UDMAControl_Size		1
+#define ATAConfiguration_ID_UDMATiming_Size		2
+#define ATAConfiguration_ID_IDEIOConfiguration_Size	4
+
+/* ATA Configuration Register bit define */
+#define ATAConfiguration_PrimaryTiming_Device0FastTimingEnable		0x0001
+#define ATAConfiguration_PrimaryTiming_Device0IORDYSampleModeEnable	0x0002	/* PIO 3 or greater */
+#define ATAConfiguration_PrimaryTiming_Device0PrefetchandPostingEnable	0x0004	/* PIO 2 or greater */
+#define ATAConfiguration_PrimaryTiming_Device0DMATimingEnable		0x0008
+#define ATAConfiguration_PrimaryTiming_Device1FastTimingEnable		0x0010
+#define ATAConfiguration_PrimaryTiming_Device1IORDYSampleModeEnable	0x0020	/* PIO 3 or greater */
+#define ATAConfiguration_PrimaryTiming_Device1PrefetchandPostingEnable	0x0040	/* PIO 2 or greater */
+#define ATAConfiguration_PrimaryTiming_Device1DMATimingEnable		0x0080
+#define ATAConfiguration_PrimaryTiming_Device0RecoveryMode		0x0300
+#define ATAConfiguration_PrimaryTiming_Device0RecoveryMode_0		0x0000	/* PIO 0, PIO 2, MDMA 0 */
+#define ATAConfiguration_PrimaryTiming_Device0RecoveryMode_1		0x0100	/* PIO 3, MDMA 1 */
+#define ATAConfiguration_PrimaryTiming_Device0RecoveryMode_2		0x0200	/* X */
+#define ATAConfiguration_PrimaryTiming_Device0RecoveryMode_3		0x0300	/* PIO 4, MDMA 2 */
+#define ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode		0x3000
+#define ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode_0		0x0000	/* PIO 0 */
+#define ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode_1		0x1000	/* PIO 2, MDMA 0 */
+#define ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode_2		0x2000	/* PIO 3, PIO 4, MDMA 1, MDMA 2 */
+#define ATAConfiguration_PrimaryTiming_Device0IORDYSampleMode_3		0x3000	/* X */
+#define ATAConfiguration_PrimaryTiming_Device1TimingRegisterEnable	0x4000
+#define ATAConfiguration_PrimaryTiming_IDEDecodeEnable			0x8000
+
+#define ATAConfiguration_Device1Timing_PrimaryRecoveryMode		0x0003
+#define ATAConfiguration_Device1Timing_PrimaryRecoveryMode_0		0x0000
+#define ATAConfiguration_Device1Timing_PrimaryRecoveryMode_1		0x0001
+#define ATAConfiguration_Device1Timing_PrimaryRecoveryMode_2		0x0002
+#define ATAConfiguration_Device1Timing_PrimaryRecoveryMode_3		0x0003
+#define ATAConfiguration_Device1Timing_PrimaryIORDYSampleMode		0x000C
+#define ATAConfiguration_Device1Timing_PrimaryIORDYSampleMode_0		0x0000
+#define ATAConfiguration_Device1Timing_PrimaryIORDYSampleMode_1		0x0004
+#define ATAConfiguration_Device1Timing_PrimaryIORDYSampleMode_2		0x0008
+#define ATAConfiguration_Device1Timing_PrimaryIORDYSampleMode_3		0x000C
+#define ATAConfiguration_Device1Timing_SecondaryRecoveryMode		0x0030
+#define ATAConfiguration_Device1Timing_SecondaryRecoveryMode_0		0x0000
+#define ATAConfiguration_Device1Timing_SecondaryRecoveryMode_1		0x0010
+#define ATAConfiguration_Device1Timing_SecondaryRecoveryMode_2		0x0020
+#define ATAConfiguration_Device1Timing_SecondaryRecoveryMode_3		0x0030
+#define ATAConfiguration_Device1Timing_SecondaryIORDYSampleMode		0x00C0
+#define ATAConfiguration_Device1Timing_SecondaryIORDYSampleMode_0	0x0000
+#define ATAConfiguration_Device1Timing_SecondaryIORDYSampleMode_1	0x0040
+#define ATAConfiguration_Device1Timing_SecondaryIORDYSampleMode_2	0x0080
+#define ATAConfiguration_Device1Timing_SecondaryIORDYSampleMode_3	0x00C0
+
+#define ATAConfiguration_UDMAControl_PrimaryDevice0UDMAModeEnable	0x0001
+#define ATAConfiguration_UDMAControl_PrimaryDevice1UDMAModeEnable	0x0002
+#define ATAConfiguration_UDMAControl_SecondaryDevice0UDMAModeEnable	0x0004
+#define ATAConfiguration_UDMAControl_SecondaryDevice1UDMAModeEnable	0x0008
+
+#define ATAConfiguration_UDMATiming_PrimaryDevice0CycleTime		0x0003
+#define ATAConfiguration_UDMATiming_PrimaryDevice0CycleTime_0		0x0000	/* UDMA 0 */
+#define ATAConfiguration_UDMATiming_PrimaryDevice0CycleTime_1		0x0001	/* UDMA 1, UDMA 3, UDMA 5 */
+#define ATAConfiguration_UDMATiming_PrimaryDevice0CycleTime_2		0x0002	/* UDMA 2, UDMA 4 */
+#define ATAConfiguration_UDMATiming_PrimaryDevice0CycleTime_3		0x0003	/* X */
+#define ATAConfiguration_UDMATiming_PrimaryDevice1CycleTime		0x0030
+#define ATAConfiguration_UDMATiming_PrimaryDevice1CycleTime_0		0x0000	/* UDMA 0 */
+#define ATAConfiguration_UDMATiming_PrimaryDevice1CycleTime_1		0x0010	/* UDMA 1, UDMA 3, UDMA 5 */
+#define ATAConfiguration_UDMATiming_PrimaryDevice1CycleTime_2		0x0020	/* UDMA 2, UDMA 4 */
+#define ATAConfiguration_UDMATiming_PrimaryDevice1CycleTime_3		0x0030	/* X */
+#define ATAConfiguration_UDMATiming_SecondaryDevice0CycleTime		0x0300
+#define ATAConfiguration_UDMATiming_SecondaryDevice0CycleTime_0		0x0000	/* UDMA 0 */
+#define ATAConfiguration_UDMATiming_SecondaryDevice0CycleTime_1		0x0100	/* UDMA 1, UDMA 3, UDMA 5 */
+#define ATAConfiguration_UDMATiming_SecondaryDevice0CycleTime_2		0x0200	/* UDMA 2, UDMA 4 */
+#define ATAConfiguration_UDMATiming_SecondaryDevice0CycleTime_3		0x0300	/* X */
+#define ATAConfiguration_UDMATiming_SecondaryDevice1CycleTime		0x3000
+#define ATAConfiguration_UDMATiming_SecondaryDevice1CycleTime_0		0x0000	/* UDMA 0 */
+#define ATAConfiguration_UDMATiming_SecondaryDevice1CycleTime_1		0x1000	/* UDMA 1, UDMA 3, UDMA 5 */
+#define ATAConfiguration_UDMATiming_SecondaryDevice1CycleTime_2		0x2000	/* UDMA 2, UDMA 4 */
+#define ATAConfiguration_UDMATiming_SecondaryDevice1CycleTime_3		0x3000	/* X */
+
+#define ATAConfiguration_IDEIOConfiguration_PrimaryDevice066MhzEnable		0x00000001	/* UDMA 3, UDMA 4 */
+#define ATAConfiguration_IDEIOConfiguration_PrimaryDevice166MhzEnable		0x00000002
+#define ATAConfiguration_IDEIOConfiguration_SecondaryDevice066MhzEnable		0x00000004
+#define ATAConfiguration_IDEIOConfiguration_SecondaryDevice166MhzEnable		0x00000008
+#define ATAConfiguration_IDEIOConfiguration_DeviceCable80Report			0x000000F0
+#define ATAConfiguration_IDEIOConfiguration_PrimaryDeviceCable80Report		0x00000030
+#define ATAConfiguration_IDEIOConfiguration_PrimaryDevice0Cable80Report		0x00000010	/* UDMA 3, UDMA 4, UDMA 5 */
+#define ATAConfiguration_IDEIOConfiguration_PrimaryDevice1Cable80Report		0x00000020
+#define ATAConfiguration_IDEIOConfiguration_SecondaryDeviceCable80Report	0x000000C0
+#define ATAConfiguration_IDEIOConfiguration_SecondaryDevice0Cable80Report	0x00000040
+#define ATAConfiguration_IDEIOConfiguration_SecondaryDevice1Cable80Report	0x00000080
+#define ATAConfiguration_IDEIOConfiguration_PrimaryDevice0100MhzEnable		0x00001000	/* UDMA 5 */
+#define ATAConfiguration_IDEIOConfiguration_PrimaryDevice1100MhzEnable		0x00002000
+#define ATAConfiguration_IDEIOConfiguration_SecondaryDevice0100MhzEnable	0x00004000
+#define ATAConfiguration_IDEIOConfiguration_SecondaryDevice1100MhzEnable	0x00008000
+#define ATAConfiguration_IDEIOConfiguration_ATA100IsSupported			0x00F00000
+
+enum _PIOTimingMode {
+	PIO0 = 0,
+	PIO1,
+	PIO2,	/* MDMA 0 */
+	PIO3,	/* MDMA 1 */
+	PIO4	/* MDMA 2 */
+};
+
+enum _DMATimingMode {
+	MDMA0 = 0,
+	MDMA1,
+	MDMA2
+};
+
+enum _UDMATimingMode {
+	UDMA0 = 0,
+	UDMA1,
+	UDMA2,
+	UDMA3,
+	UDMA4,
+	UDMA5
+};
+
+
+enum rdc_controller_ids {
+	/* controller IDs */
+	RDC_17F31011,
+	RDC_17F31012
+};
+
+#endif
diff --git a/drivers/staging/pohmelfs/crypto.c b/drivers/staging/pohmelfs/crypto.c
index 31d765d..19781ad 100644
--- a/drivers/staging/pohmelfs/crypto.c
+++ b/drivers/staging/pohmelfs/crypto.c
@@ -832,8 +832,7 @@
 	return pohmelfs_crypto_thread_get(psb, pohmelfs_trans_crypt_action, trans);
 }
 
-struct pohmelfs_crypto_input_action_data
-{
+struct pohmelfs_crypto_input_action_data {
 	struct page			*page;
 	struct pohmelfs_crypto_engine	*e;
 	u64				iv;
diff --git a/drivers/staging/pohmelfs/dir.c b/drivers/staging/pohmelfs/dir.c
index b579984..4c58e22 100644
--- a/drivers/staging/pohmelfs/dir.c
+++ b/drivers/staging/pohmelfs/dir.c
@@ -562,7 +562,7 @@
 		if (!inode) {
 			dprintk("%s: No inode for ino: %lu, name: '%s', hash: %x.\n",
 				__func__, ino, str.name, str.hash);
-			//return NULL;
+			/* return NULL; */
 			return ERR_PTR(-EACCES);
 		}
 	} else {
@@ -692,9 +692,9 @@
 	n = pohmelfs_search_hash(parent, str.hash);
 	if (n) {
 		pohmelfs_fix_offset(parent, n);
-		if (test_bit(NETFS_INODE_REMOTE_SYNCED, &pi->state)) {
+		if (test_bit(NETFS_INODE_REMOTE_SYNCED, &pi->state))
 			pohmelfs_remove_child(pi, n);
-		}
+
 		pohmelfs_name_free(parent, n);
 		err = 0;
 	}
@@ -1006,9 +1006,8 @@
 	pi = POHMELFS_I(inode);
 	old_parent = POHMELFS_I(old_dir);
 
-	if (new_dir) {
+	if (new_dir)
 		new_dir->i_sb->s_op->write_inode(new_dir, 0);
-	}
 
 	old_hash = jhash(old_dentry->d_name.name, old_dentry->d_name.len, 0);
 	str.hash = jhash(new_dentry->d_name.name, new_dentry->d_name.len, 0);
diff --git a/drivers/staging/pohmelfs/inode.c b/drivers/staging/pohmelfs/inode.c
index b2eaf90..7b60579 100644
--- a/drivers/staging/pohmelfs/inode.c
+++ b/drivers/staging/pohmelfs/inode.c
@@ -386,7 +386,7 @@
 		if (inode && (inode->i_state & I_DIRTY)) {
 			struct pohmelfs_inode *pi = POHMELFS_I(inode);
 			pohmelfs_write_create_inode(pi);
-			//pohmelfs_meta_command(pi, NETFS_INODE_INFO, 0, NULL, NULL, 0);
+			/* pohmelfs_meta_command(pi, NETFS_INODE_INFO, 0, NULL, NULL, 0); */
 			iput(inode);
 		}
 	}
@@ -845,7 +845,7 @@
 	struct pohmelfs_sb *psb = POHMELFS_SB(sb);
 	struct pohmelfs_inode *pi = POHMELFS_I(inode);
 
-	//pohmelfs_data_unlock(pi, 0, inode->i_size, POHMELFS_READ_LOCK);
+	/* pohmelfs_data_unlock(pi, 0, inode->i_size, POHMELFS_READ_LOCK); */
 
 	pohmelfs_inode_del_inode(psb, pi);
 
@@ -943,7 +943,7 @@
 	return ret;
 }
 
-const static struct file_operations pohmelfs_file_ops = {
+static const struct file_operations pohmelfs_file_ops = {
 	.open		= generic_file_open,
 	.fsync		= pohmelfs_fsync,
 
@@ -1529,9 +1529,9 @@
 	struct pohmelfs_inode *pi;
 	unsigned int count = 0;
 
-	while ((pi = pohmelfs_get_inode_from_list(psb, &psb->drop_list, &count))) {
+	while ((pi = pohmelfs_get_inode_from_list(psb, &psb->drop_list, &count)))
 		pohmelfs_put_inode_count(pi, count);
-	}
+
 	pohmelfs_check_states(psb);
 
 	if (psb->drop_scan_timeout)
@@ -1568,9 +1568,8 @@
 		rb_node = rb_next(rb_node);
 
 		err = -ETIMEDOUT;
-		if (timeout && (++dst->retries < psb->trans_retries)) {
+		if (timeout && (++dst->retries < psb->trans_retries))
 			err = netfs_trans_resend(t, psb);
-		}
 
 		if (err || (t->flags & NETFS_TRANS_SINGLE_DST)) {
 			if (netfs_trans_remove_nolock(dst, st))
@@ -1777,7 +1776,7 @@
 		seq_printf(m, "%u ", ctl->idx);
 		if (ctl->addr.sa_family == AF_INET) {
 			struct sockaddr_in *sin = (struct sockaddr_in *)&st->ctl.addr;
-			//seq_printf(m, "%pi4:%u", &sin->sin_addr.s_addr, ntohs(sin->sin_port));
+			/* seq_printf(m, "%pi4:%u", &sin->sin_addr.s_addr, ntohs(sin->sin_port)); */
 			seq_printf(m, "%u.%u.%u.%u:%u", NIPQUAD(sin->sin_addr.s_addr), ntohs(sin->sin_port));
 		} else if (ctl->addr.sa_family == AF_INET6) {
 			struct sockaddr_in6 *sin = (struct sockaddr_in6 *)&st->ctl.addr;
diff --git a/drivers/staging/pohmelfs/net.c b/drivers/staging/pohmelfs/net.c
index 11ecac0..5f312c9 100644
--- a/drivers/staging/pohmelfs/net.c
+++ b/drivers/staging/pohmelfs/net.c
@@ -168,8 +168,7 @@
  * Polling machinery.
  */
 
-struct netfs_poll_helper
-{
+struct netfs_poll_helper {
 	poll_table 		pt;
 	struct netfs_state	*st;
 };
@@ -915,9 +914,9 @@
 				unsigned char *hash = e->data;
 
 				dprintk("%s: received hash: ", __func__);
-				for (i=0; i<cmd->csize; ++i) {
+				for (i=0; i<cmd->csize; ++i)
 					printk("%02x ", hash[i]);
-				}
+
 				printk("\n");
 			}
 #endif
diff --git a/drivers/staging/pohmelfs/netfs.h b/drivers/staging/pohmelfs/netfs.h
index c78cfcb..3b60c61 100644
--- a/drivers/staging/pohmelfs/netfs.h
+++ b/drivers/staging/pohmelfs/netfs.h
@@ -30,8 +30,7 @@
  * Network command structure.
  * Will be extended.
  */
-struct netfs_cmd
-{
+struct netfs_cmd {
 	__u16			cmd;	/* Command number */
 	__u16			csize;	/* Attached crypto information size */
 	__u16			cpad;	/* Attached padding size */
@@ -96,8 +95,7 @@
  */
 #define _K_SS_MAXSIZE	128
 
-struct saddr
-{
+struct saddr {
 	unsigned short		sa_family;
 	char			addr[_K_SS_MAXSIZE];
 };
@@ -107,8 +105,7 @@
 	POHMELFS_CRYPTO_CIPHER,
 };
 
-struct pohmelfs_crypto
-{
+struct pohmelfs_crypto {
 	unsigned int		idx;		/* Config index */
 	unsigned short		strlen;		/* Size of the attached crypto string including 0-byte
 						 * "cbc(aes)" for example */
@@ -123,8 +120,7 @@
 /*
  * Configuration command used to create table of different remote servers.
  */
-struct pohmelfs_ctl
-{
+struct pohmelfs_ctl {
 	__u32			idx;		/* Config index */
 	__u32			type;		/* Socket type */
 	__u32			proto;		/* Socket protocol */
@@ -137,8 +133,7 @@
 /*
  * Ack for userspace about requested command.
  */
-struct pohmelfs_cn_ack
-{
+struct pohmelfs_cn_ack {
 	struct cn_msg		msg;
 	int			error;
 	int			msg_num;
@@ -150,8 +145,7 @@
  * Inode info structure used to sync with server.
  * Check what stat() returns.
  */
-struct netfs_inode_info
-{
+struct netfs_inode_info {
 	unsigned int		mode;
 	unsigned int		nlink;
 	unsigned int		uid;
@@ -205,8 +199,7 @@
 /* Extended attributes support on/off */
 #define POHMELFS_FLAGS_XATTR		(1<<1)
 
-struct netfs_root_capabilities
-{
+struct netfs_root_capabilities {
 	__u64			nr_files;
 	__u64			used, avail;
 	__u64			flags;
@@ -220,8 +213,7 @@
 	cap->flags = __cpu_to_be64(cap->flags);
 }
 
-struct netfs_crypto_capabilities
-{
+struct netfs_crypto_capabilities {
 	unsigned short		hash_strlen;	/* Hash string length, like "hmac(sha1) including 0 byte "*/
 	unsigned short		cipher_strlen;	/* Cipher string length with the same format */
 	unsigned int		cipher_keysize;	/* Cipher key size */
@@ -241,8 +233,7 @@
 	POHMELFS_WRITE_LOCK,
 };
 
-struct netfs_lock
-{
+struct netfs_lock {
 	__u64			start;
 	__u64			ino;
 	__u32			size;
@@ -268,8 +259,7 @@
 /*
  * Private POHMELFS cache of objects in directory.
  */
-struct pohmelfs_name
-{
+struct pohmelfs_name {
 	struct rb_node		hash_node;
 
 	struct list_head	sync_create_entry;
@@ -286,8 +276,7 @@
 /*
  * POHMELFS inode. Main object.
  */
-struct pohmelfs_inode
-{
+struct pohmelfs_inode {
 	struct list_head	inode_entry;		/* Entry in superblock list.
 							 * Objects which are not bound to dentry require to be dropped
 							 * in ->put_super()
@@ -318,8 +307,7 @@
 struct netfs_state;
 struct pohmelfs_sb;
 
-struct netfs_trans
-{
+struct netfs_trans {
 	/*
 	 * Transaction header and attached contiguous data live here.
 	 */
@@ -426,8 +414,7 @@
 	t->complete = NULL;
 }
 
-struct netfs_trans_dst
-{
+struct netfs_trans_dst {
 	struct list_head		trans_entry;
 	struct rb_node			state_entry;
 
@@ -456,8 +443,7 @@
 int netfs_trans_init(void);
 void netfs_trans_exit(void);
 
-struct pohmelfs_crypto_engine
-{
+struct pohmelfs_crypto_engine {
 	u64				iv;		/* Crypto IV for current operation */
 	unsigned long			timeout;	/* Crypto waiting timeout */
 	unsigned int			size;		/* Size of crypto scratchpad */
@@ -474,8 +460,7 @@
 	unsigned int			page_num;
 };
 
-struct pohmelfs_crypto_thread
-{
+struct pohmelfs_crypto_thread {
 	struct list_head		thread_entry;
 
 	struct task_struct		*thread;
@@ -497,8 +482,7 @@
 /*
  * Network state, attached to one server.
  */
-struct netfs_state
-{
+struct netfs_state {
 	struct mutex		__state_lock;		/* Can not allow to use the same socket simultaneously */
 	struct mutex		__state_send_lock;
 	struct netfs_cmd 	cmd;			/* Cached command */
@@ -580,8 +564,7 @@
 
 struct pohmelfs_config;
 
-struct pohmelfs_sb
-{
+struct pohmelfs_sb {
 	struct rb_root		mcache_root;
 	struct mutex		mcache_lock;
 	atomic_long_t		mcache_gen;
@@ -718,15 +701,13 @@
 	spin_unlock(&psb->ino_lock);
 }
 
-struct pohmelfs_config
-{
+struct pohmelfs_config {
 	struct list_head	config_entry;
 
 	struct netfs_state	state;
 };
 
-struct pohmelfs_config_group
-{
+struct pohmelfs_config_group {
 	/*
 	 * Entry in the global config group list.
 	 */
@@ -814,8 +795,7 @@
 int pohmelfs_construct_path_string(struct pohmelfs_inode *pi, void *data, int len);
 int pohmelfs_path_length(struct pohmelfs_inode *pi);
 
-struct pohmelfs_crypto_completion
-{
+struct pohmelfs_crypto_completion {
 	struct completion	complete;
 	int			error;
 };
@@ -864,7 +844,7 @@
 int __init pohmelfs_mcache_init(void);
 void pohmelfs_mcache_exit(void);
 
-//#define CONFIG_POHMELFS_DEBUG
+/* #define CONFIG_POHMELFS_DEBUG */
 
 #ifdef CONFIG_POHMELFS_DEBUG
 #define dprintka(f, a...) printk(f, ##a)
@@ -891,8 +871,7 @@
 	}
 }
 
-struct pohmelfs_mcache
-{
+struct pohmelfs_mcache {
 	struct rb_node			mcache_entry;
 	struct completion		complete;
 
diff --git a/drivers/staging/pohmelfs/trans.c b/drivers/staging/pohmelfs/trans.c
index fef5f9b..4587f6d 100644
--- a/drivers/staging/pohmelfs/trans.c
+++ b/drivers/staging/pohmelfs/trans.c
@@ -101,7 +101,8 @@
 			goto err_out;
 		}
 
-		msg.msg_flags = MSG_WAITALL|(attached_pages == 1)?0:MSG_MORE;
+		msg.msg_flags = MSG_WAITALL | (attached_pages == 1 ? 0 :
+				MSG_MORE);
 
 		err = kernel_sendpage(st->socket, page, 0, size, msg.msg_flags);
 		if (err <= 0) {
@@ -177,9 +178,9 @@
 
 err_out_unlock_return:
 
-	if (st->need_reset) {
+	if (st->need_reset)
 		netfs_state_exit(st);
-	}
+
 	netfs_state_unlock_send(st);
 
 	dprintk("%s: t: %p, gen: %u, err: %d.\n",
diff --git a/drivers/staging/rspiusb/rspiusb.c b/drivers/staging/rspiusb/rspiusb.c
index ecaffb5..1cdfe69 100644
--- a/drivers/staging/rspiusb/rspiusb.c
+++ b/drivers/staging/rspiusb/rspiusb.c
@@ -39,7 +39,11 @@
 #endif
 /* Use our own dbg macro */
 #undef dbg
-#define dbg(format, arg...) do { if (debug) printk(KERN_DEBUG __FILE__ ": " format "\n" , ## arg); } while (0)
+#define dbg(format, arg...) \
+	do { \
+		if (debug) \
+			printk(KERN_DEBUG __FILE__ ": " format "\n" , ##arg); \
+	} while (0)
 
 /* Version Information */
 #define DRIVER_VERSION "V1.0.1"
@@ -63,52 +67,58 @@
 
 /* Structure to hold all of our device specific stuff */
 struct device_extension {
-	struct usb_device *udev;	/* save off the usb device pointer */
-	struct usb_interface *interface;	/* the interface for this device */
-	unsigned char minor;	/* the starting minor number for this device */
+	struct usb_device *udev;	 /* save off the usb device pointer */
+	struct usb_interface *interface; /* the interface for this device */
+	unsigned char minor;		 /* the starting minor number
+					  * for this device
+					  */
 	size_t bulk_in_size_returned;
 	int bulk_in_byte_trk;
 	struct urb ***PixelUrb;
 	int frameIdx;
 	int urbIdx;
 	unsigned int *maplist_numPagesMapped;
-	int open;		/* if the port is open or not */
-	int present;		/* if the device is not disconnected */
-	int userBufMapped;	/* has the user buffer been mapped? */
-	struct scatterlist **sgl;	/* scatter-gather list for user buffer */
+	int open;		  /* if the port is open or not */
+	int present;		  /* if the device is not disconnected */
+	int userBufMapped;	  /* has the user buffer been mapped ? */
+	struct scatterlist **sgl; /* scatter-gather list for user buffer */
 	unsigned int *sgEntries;
 	struct kref kref;
 	int gotPixelData;
 	int pendingWrite;
 	char **pendedPixelUrbs;
-	int iama;		/*PIXIS or ST133 */
-	int num_frames;		/* the number of frames that will fit in the user buffer */
+	int iama;		 /* PIXIS or ST133 */
+	int num_frames;		 /* the number of frames that will fit
+				  * in the user buffer
+				  */
 	int active_frame;
 	unsigned long frameSize;
 	struct semaphore sem;
-	//FX2 specific endpoints
-	unsigned int hEP[8];
+	unsigned int hEP[8];	 /* FX2 specific endpoints */
 };
-#define to_pi_dev(d) container_of( d, struct device_extension, kref )
 
+#define to_pi_dev(d) container_of(d, struct device_extension, kref)
+
+/* Prototypes */
 static int MapUserBuffer(struct ioctl_struct *, struct device_extension *);
 static int UnMapUserBuffer(struct device_extension *);
 static int piusb_ioctl(struct inode *inode, struct file *file, unsigned int cmd,
 		       unsigned long arg);
-static int piusb_output(struct ioctl_struct *, unsigned char *, int, struct device_extension *);
+static int piusb_output(struct ioctl_struct *, unsigned char *, int,
+		struct device_extension *);
 static struct usb_driver piusb_driver;
 
 /* table of devices that work with this driver */
 static struct usb_device_id pi_device_table[] = {
 	{USB_DEVICE(VENDOR_ID, ST133_PID)},
 	{USB_DEVICE(VENDOR_ID, PIXIS_PID)},
-	{0, }			/* Terminating entry */
+	{0, } /* Terminating entry */
 };
 
 MODULE_DEVICE_TABLE(usb, pi_device_table);
 
-static int lastErr = 0;
-static int errCnt = 0;
+static int lastErr;
+static int errCnt;
 
 static void piusb_delete(struct kref *kref)
 {
@@ -143,25 +153,29 @@
 	}
 	dbg("Alternate Setting = %d", interface->num_altsetting);
 
-	pdx->frameIdx = pdx->urbIdx = 0;
+	pdx->bulk_in_size_returned = 0;
+	pdx->bulk_in_byte_trk = 0;
+	pdx->PixelUrb = NULL;
+	pdx->frameIdx = 0;
+	pdx->urbIdx = 0;
+	pdx->maplist_numPagesMapped = NULL;
+	pdx->userBufMapped = 0;
+	pdx->sgl = NULL;
+	pdx->sgEntries = NULL;
 	pdx->gotPixelData = 0;
 	pdx->pendingWrite = 0;
-	pdx->frameSize = 0;
+	pdx->pendedPixelUrbs = NULL;
 	pdx->num_frames = 0;
 	pdx->active_frame = 0;
-	pdx->bulk_in_byte_trk = 0;
-	pdx->userBufMapped = 0;
-	pdx->pendedPixelUrbs = NULL;
-	pdx->sgEntries = NULL;
-	pdx->sgl = NULL;
-	pdx->maplist_numPagesMapped = NULL;
-	pdx->PixelUrb = NULL;
-	pdx->bulk_in_size_returned = 0;
+	pdx->frameSize = 0;
+
 	/* increment our usage count for the device */
 	kref_get(&pdx->kref);
+
 	/* save our object in the file's private structure */
 	file->private_data = pdx;
-      exit_no_device:
+
+exit_no_device:
 	return retval;
 }
 
@@ -174,13 +188,91 @@
 	pdx = (struct device_extension *)file->private_data;
 	if (pdx == NULL) {
 		dbg("%s - object is NULL", __func__);
-		return -ENODEV;
+		retval = -ENODEV;
+		goto object_null;
 	}
 	/* decrement the count on our device */
 	kref_put(&pdx->kref, piusb_delete);
+
+object_null:
 	return retval;
 }
 
+static int pixis_io(struct ioctl_struct *ctrl, struct device_extension *pdx,
+		struct ioctl_struct *arg)
+{
+	unsigned int numToRead = 0;
+	unsigned int totalRead = 0;
+	unsigned char *uBuf;
+	int numbytes;
+	int i;
+
+	uBuf = kmalloc(ctrl->numbytes, GFP_KERNEL);
+	if (!uBuf) {
+		dbg("Alloc for uBuf failed");
+		return 0;
+	}
+	numbytes = (int) ctrl->numbytes;
+	numToRead = (unsigned int) ctrl->numbytes;
+	dbg("numbytes to read = %d", numbytes);
+	dbg("endpoint # %d", ctrl->endpoint);
+
+	if (copy_from_user(uBuf, ctrl->pData, numbytes)) {
+		dbg("copying ctrl->pData to dummyBuf failed");
+		return -EFAULT;
+	}
+
+	do {
+		i = usb_bulk_msg(pdx->udev, pdx->hEP[ctrl->endpoint],
+				(uBuf + totalRead),
+				/* EP0 can only handle 64 bytes at a time */
+				(numToRead > 64) ? 64 : numToRead,
+				&numbytes, HZ * 10);
+		if (i) {
+			dbg("CMD = %s, Address = 0x%02X",
+					((uBuf[3] == 0x02) ? "WRITE" : "READ"),
+					uBuf[1]);
+			dbg("Number of bytes Attempted to read = %d",
+					(int)ctrl->numbytes);
+			dbg("Blocking ReadI/O Failed with status %d", i);
+			kfree(uBuf);
+			return -1;
+		}
+		dbg("Pixis EP0 Read %d bytes", numbytes);
+		totalRead += numbytes;
+		numToRead -= numbytes;
+	} while (numToRead);
+
+	memcpy(ctrl->pData, uBuf, totalRead);
+	dbg("Total Bytes Read from PIXIS EP0 = %d", totalRead);
+	ctrl->numbytes = totalRead;
+
+	if (copy_to_user(arg, ctrl, sizeof(struct ioctl_struct)))
+		dbg("copy_to_user failed in IORB");
+
+	kfree(uBuf);
+	return ctrl->numbytes;
+}
+
+static int pixel_data(struct ioctl_struct *ctrl, struct device_extension *pdx)
+{
+	int i;
+
+	if (!pdx->gotPixelData)
+		return 0;
+
+	pdx->gotPixelData = 0;
+	ctrl->numbytes = pdx->bulk_in_size_returned;
+	pdx->bulk_in_size_returned -= pdx->frameSize;
+
+	for (i = 0; i < pdx->maplist_numPagesMapped[pdx->active_frame]; i++)
+		SetPageDirty(sg_page(&pdx->sgl[pdx->active_frame][i]));
+
+	pdx->active_frame = ((pdx->active_frame + 1) % pdx->num_frames);
+
+	return ctrl->numbytes;
+}
+
 /**
  *	piusb_ioctl
  */
@@ -190,12 +282,9 @@
 	struct device_extension *pdx;
 	char dummyCtlBuf[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
 	unsigned long devRB = 0;
-	int i = 0;
 	int err = 0;
 	int retval = 0;
 	struct ioctl_struct ctrl;
-	unsigned char *uBuf;
-	int numbytes = 0;
 	unsigned short controlData = 0;
 
 	pdx = (struct device_extension *)file->private_data;
@@ -206,18 +295,22 @@
 	}
 	/* fill in your device specific stuff here */
 	if (_IOC_DIR(cmd) & _IOC_READ)
-		err = !access_ok(VERIFY_WRITE, (void __user *)arg, _IOC_SIZE(cmd));
+		err = !access_ok(VERIFY_WRITE, (void __user *)arg,
+				_IOC_SIZE(cmd));
 	else if (_IOC_DIR(cmd) & _IOC_WRITE)
-		err = !access_ok(VERIFY_READ, (void __user *)arg, _IOC_SIZE(cmd));
+		err = !access_ok(VERIFY_READ, (void __user *)arg,
+			       _IOC_SIZE(cmd));
 	if (err) {
 		dev_err(&pdx->udev->dev, "return with error = %d\n", err);
 		return -EFAULT;
 	}
 	switch (cmd) {
 	case PIUSB_GETVNDCMD:
-		if (copy_from_user
-		    (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
-			info("copy_from_user failed\n");
+		if (__copy_from_user
+		    (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct))) {
+			dev_err(&pdx->udev->dev, "copy_from_user failed\n");
+			return -EFAULT;
+		}
 		dbg("%s %x\n", "Get Vendor Command = ", ctrl.cmd);
 		retval =
 		    usb_control_msg(pdx->udev, usb_rcvctrlpipe(pdx->udev, 0),
@@ -227,167 +320,85 @@
 			dbg("FW Version returned from HW = %ld.%ld",
 			    (devRB >> 8), (devRB & 0xFF));
 		}
-		return devRB;
+		if (retval >= 0)
+			retval = (int)devRB;
+		return retval;
+
 	case PIUSB_SETVNDCMD:
-		if (copy_from_user
-		    (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
-			info("copy_from_user failed\n");
-//            dbg( "%s %x", "Set Vendor Command = ",ctrl.cmd );
+		if (__copy_from_user
+		    (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct))) {
+			dev_err(&pdx->udev->dev, "copy_from_user failed\n");
+			return -EFAULT;
+		}
+		/* dbg( "%s %x", "Set Vendor Command = ",ctrl.cmd ); */
 		controlData = ctrl.pData[0];
 		controlData |= (ctrl.pData[1] << 8);
-//            dbg( "%s %d", "Vendor Data =",controlData );
-		retval = usb_control_msg(pdx->udev, usb_sndctrlpipe(pdx->udev, 0), ctrl.cmd, (USB_DIR_OUT | USB_TYPE_VENDOR),	/* | USB_RECIP_ENDPOINT), */
-					 controlData,
-					 0,
-					 &dummyCtlBuf, ctrl.numbytes, HZ * 10);
+		/* dbg( "%s %d", "Vendor Data =",controlData ); */
+		retval = usb_control_msg(pdx->udev,
+				usb_sndctrlpipe(pdx->udev, 0),
+				ctrl.cmd,
+				(USB_DIR_OUT | USB_TYPE_VENDOR
+				 /* | USB_RECIP_ENDPOINT */),
+				controlData, 0,
+				&dummyCtlBuf, ctrl.numbytes, HZ * 10);
 		return retval;
-		break;
+
 	case PIUSB_ISHIGHSPEED:
 		return ((pdx->udev->speed == USB_SPEED_HIGH) ? 1 : 0);
-		break;
+
 	case PIUSB_WRITEPIPE:
-		if (copy_from_user(&ctrl, (void __user *)arg, _IOC_SIZE(cmd)))
-			info("copy_from_user WRITE_DUMMY failed\n");
+		if (__copy_from_user(&ctrl, (void __user *)arg, _IOC_SIZE(cmd))) {
+			dev_err(&pdx->udev->dev,
+					"copy_from_user WRITE_DUMMY failed\n");
+			return -EFAULT;
+		}
 		if (!access_ok(VERIFY_READ, ctrl.pData, ctrl.numbytes)) {
 			dbg("can't access pData");
 			return 0;
 		}
-		piusb_output(&ctrl, ctrl.pData /*uBuf */ , ctrl.numbytes, pdx);
+		piusb_output(&ctrl, ctrl.pData /* uBuf */, ctrl.numbytes, pdx);
 		return ctrl.numbytes;
-		break;
-	case PIUSB_USERBUFFER:
-		if (copy_from_user
-		    (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
-			info("copy_from_user failed\n");
-		return MapUserBuffer((struct ioctl_struct *) & ctrl, pdx);
-		break;
-	case PIUSB_UNMAP_USERBUFFER:
-		UnMapUserBuffer(pdx);
-		return 0;
-		break;
-	case PIUSB_READPIPE:
-		if (copy_from_user
-		    (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
-			info("copy_from_user failed\n");
-		switch (ctrl.endpoint) {
-		case 0:	//ST133 Pixel Data or PIXIS IO
-			if (pdx->iama == PIXIS_PID) {
-				unsigned int numToRead = 0;
-				unsigned int totalRead = 0;
-				uBuf = kmalloc(ctrl.numbytes, GFP_KERNEL);
-				if (!uBuf) {
-					dbg("Alloc for uBuf failed");
-					return 0;
-				}
-				numbytes = ctrl.numbytes;
-				numToRead = numbytes;
-				dbg("numbytes to read = %d", numbytes);
-				dbg("endpoint # %d", ctrl.endpoint);
-				if (copy_from_user(uBuf, ctrl.pData, numbytes))
-					dbg("copying ctrl.pData to dummyBuf failed");
-				do {
-					i = usb_bulk_msg(pdx->udev, pdx->hEP[ctrl.endpoint], (uBuf + totalRead), (numToRead > 64) ? 64 : numToRead, &numbytes, HZ * 10);	//EP0 can only handle 64 bytes at a time
-					if (i) {
-						dbg("CMD = %s, Address = 0x%02X", ((uBuf[3] == 0x02) ? "WRITE" : "READ"), uBuf[1]);
-						dbg("Number of bytes Attempted to read = %d", (int)ctrl.numbytes);
-						dbg("Blocking ReadI/O Failed with status %d", i);
-						kfree(uBuf);
-						return -1;
-					} else {
-						dbg("Pixis EP0 Read %d bytes",
-						    numbytes);
-						totalRead += numbytes;
-						numToRead -= numbytes;
-					}
-				}
-				while (numToRead);
-				memcpy(ctrl.pData, uBuf, totalRead);
-				dbg("Total Bytes Read from PIXIS EP0 = %d",
-				    totalRead);
-				ctrl.numbytes = totalRead;
-				if (copy_to_user
-				    ((struct ioctl_struct *) arg, &ctrl,
-				     sizeof(struct ioctl_struct)))
-					dbg("copy_to_user failed in IORB");
-				kfree(uBuf);
-				return ctrl.numbytes;
-			} else	//ST133 Pixel Data
-			{
-				if (!pdx->gotPixelData)
-					return 0;
-				else {
-					pdx->gotPixelData = 0;
-					ctrl.numbytes =
-					    pdx->bulk_in_size_returned;
-					pdx->bulk_in_size_returned -=
-					    pdx->frameSize;
-					for (i = 0; i < pdx->maplist_numPagesMapped[pdx->active_frame]; i++)
-						SetPageDirty(pdx->sgl[pdx->active_frame][i].page_link);
-					pdx->active_frame =
-					    ((pdx->active_frame +
-					      1) % pdx->num_frames);
-					return ctrl.numbytes;
-				}
-			}
-			break;
-		case 1:	//ST133IO
-		case 4:	//PIXIS IO
-			uBuf = kmalloc(ctrl.numbytes, GFP_KERNEL);
-			if (!uBuf) {
-				dbg("Alloc for uBuf failed");
-				return 0;
-			}
-			numbytes = ctrl.numbytes;
-//                                      dbg( "numbytes to read = %d", numbytes );
-			if (copy_from_user(uBuf, ctrl.pData, numbytes))
-				dbg("copying ctrl.pData to dummyBuf failed");
-			i = usb_bulk_msg(pdx->udev, pdx->hEP[ctrl.endpoint],
-					 uBuf, numbytes, &numbytes, HZ * 10);
-			if (i) {
-				dbg("Blocking ReadI/O Failed with status %d",
-				    i);
-				kfree(uBuf);
-				return -1;
-			} else {
-				ctrl.numbytes = numbytes;
-				memcpy(ctrl.pData, uBuf, numbytes);
-				if (copy_to_user
-				    ((struct ioctl_struct *) arg, &ctrl,
-				     sizeof(struct ioctl_struct)))
-					dbg("copy_to_user failed in IORB");
-				kfree(uBuf);
-				return ctrl.numbytes;
-			}
-			break;
 
-		case 2:	//PIXIS Ping
-		case 3:	//PIXIS Pong
-			if (!pdx->gotPixelData)
-				return 0;
-			else {
-				pdx->gotPixelData = 0;
-				ctrl.numbytes = pdx->bulk_in_size_returned;
-				pdx->bulk_in_size_returned -= pdx->frameSize;
-				for (i = 0;
-				     i <
-				     pdx->maplist_numPagesMapped[pdx->
-								 active_frame];
-				     i++)
-					SetPageDirty(pdx->sgl[pdx->active_frame][i].page_link);
-				pdx->active_frame =
-				    ((pdx->active_frame + 1) % pdx->num_frames);
-				return ctrl.numbytes;
-			}
-			break;
+	case PIUSB_USERBUFFER:
+		if (__copy_from_user
+		    (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct))) {
+			dev_err(&pdx->udev->dev, "copy_from_user failed\n");
+			return -EFAULT;
 		}
+		return MapUserBuffer((struct ioctl_struct *) &ctrl, pdx);
+
+	case PIUSB_UNMAP_USERBUFFER:
+		retval = UnMapUserBuffer(pdx);
+		return retval;
+
+	case PIUSB_READPIPE:
+		if (__copy_from_user(&ctrl, (void __user *)arg,
+					sizeof(struct ioctl_struct))) {
+			dev_err(&pdx->udev->dev, "copy_from_user failed\n");
+			return -EFAULT;
+		}
+		if (((0 == ctrl.endpoint) && (PIXIS_PID == pdx->iama)) ||
+				(1 == ctrl.endpoint) ||	/* ST133IO */
+				(4 == ctrl.endpoint))	/* PIXIS IO */
+			return pixis_io(&ctrl, pdx,
+					(struct ioctl_struct *)arg);
+		else if ((0 == ctrl.endpoint) || /* ST133 Pixel Data */
+				(2 == ctrl.endpoint) || /* PIXIS Ping */
+				(3 == ctrl.endpoint))	/* PIXIS Pong */
+			return pixel_data(&ctrl, pdx);
+
 		break;
+
 	case PIUSB_WHATCAMERA:
 		return pdx->iama;
+
 	case PIUSB_SETFRAMESIZE:
 		dbg("PIUSB_SETFRAMESIZE");
-		if (copy_from_user
-		    (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct)))
-			info("copy_from_user failed\n");
+		if (__copy_from_user
+		    (&ctrl, (void __user *)arg, sizeof(struct ioctl_struct))) {
+			dev_err(&pdx->udev->dev, "copy_from_user failed\n");
+			return -EFAULT;
+		}
 		pdx->frameSize = ctrl.numbytes;
 		pdx->num_frames = ctrl.numFrames;
 		if (!pdx->sgl)
@@ -410,6 +421,7 @@
 			    kmalloc(sizeof(char *) * pdx->num_frames,
 				    GFP_KERNEL);
 		return 0;
+
 	default:
 		dbg("%s\n", "No IOCTL found");
 		break;
@@ -436,7 +448,7 @@
 			urb->transfer_buffer, urb->transfer_dma);
 }
 
-int piusb_output(struct ioctl_struct * io, unsigned char *uBuf, int len,
+int piusb_output(struct ioctl_struct *io, unsigned char *uBuf, int len,
 		 struct device_extension *pdx)
 {
 	struct urb *urb = NULL;
@@ -449,10 +461,13 @@
 		    usb_buffer_alloc(pdx->udev, len, GFP_KERNEL,
 				     &urb->transfer_dma);
 		if (!kbuf) {
-			info("buffer_alloc failed\n");
+			dev_err(&pdx->udev->dev, "buffer_alloc failed\n");
 			return -ENOMEM;
 		}
-		memcpy(kbuf, uBuf, len);
+		if(__copy_from_user(kbuf, uBuf, len)) {
+			dev_err(&pdx->udev->dev, "__copy_from_user failed\n");
+			return -EFAULT;
+		}
 		usb_fill_bulk_urb(urb, pdx->udev, pdx->hEP[io->endpoint], kbuf,
 				  len, piusb_write_bulk_callback, pdx);
 		urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
@@ -472,6 +487,7 @@
 	int i = 0;
 	int k = 0;
 	unsigned int epAddr;
+
 	for (k = 0; k < pdx->num_frames; k++) {
 		dbg("Killing Urbs for Frame %d", k);
 		for (i = 0; i < pdx->sgEntries[k]; i++) {
@@ -485,23 +501,19 @@
 	}
 
 	for (k = 0; k < pdx->num_frames; k++) {
-		if (pdx->iama == PIXIS_PID)	//if so, which EP should we map this frame to
-		{
-			if (k % 2)	//check to see if this should use EP4(PONG)
-			{
-				epAddr = pdx->hEP[3];	//PONG, odd frames
-			} else {
-				epAddr = pdx->hEP[2];	//PING, even frames and zero
-			}
-		} else		//ST133 only has 1 endpoint for Pixel data transfer
-		{
+		if (pdx->iama == PIXIS_PID)
+			/* which EP should we map this frame to ? */
+			/* PONG, odd frames: hEP[3] */
+			/* PING, even frames and zero hEP[2] */
+			epAddr = (k % 2) ? pdx->hEP[3] : pdx->hEP[2];
+		else
+			/* ST133 only has 1 endpoint for Pixel data transfer */
 			epAddr = pdx->hEP[0];
-		}
+
 		usb_buffer_unmap_sg(pdx->udev, epAddr, pdx->sgl[k],
 				    pdx->maplist_numPagesMapped[k]);
-		for (i = 0; i < pdx->maplist_numPagesMapped[k]; i++) {
-			page_cache_release(pdx->sgl[k][i].page_link);
-		}
+		for (i = 0; i < pdx->maplist_numPagesMapped[k]; i++)
+			page_cache_release(sg_page(&pdx->sgl[k][i]));
 		kfree(pdx->sgl[k]);
 		kfree(pdx->PixelUrb[k]);
 		kfree(pdx->pendedPixelUrbs[k]);
@@ -509,6 +521,7 @@
 		pdx->PixelUrb[k] = NULL;
 		pdx->pendedPixelUrbs[k] = NULL;
 	}
+
 	kfree(pdx->sgEntries);
 	vfree(pdx->maplist_numPagesMapped);
 	pdx->sgEntries = NULL;
@@ -519,6 +532,7 @@
 	pdx->sgl = NULL;
 	pdx->pendedPixelUrbs = NULL;
 	pdx->PixelUrb = NULL;
+
 	return 0;
 }
 
@@ -539,26 +553,25 @@
 		pdx->pendedPixelUrbs[pdx->frameIdx][pdx->urbIdx] = 0;
 	} else {
 		pdx->bulk_in_byte_trk += urb->actual_length;
-		{
-			i = usb_submit_urb(urb, GFP_ATOMIC);	//resubmit the URB
-			if (i) {
-				errCnt++;
-				if (i != lastErr) {
-					dbg("submit urb in callback failed with error code %d", i);
-					lastErr = i;
-				}
-			} else {
-				pdx->urbIdx++;	//point to next URB when we callback
-				if (pdx->bulk_in_byte_trk >= pdx->frameSize) {
-					pdx->bulk_in_size_returned =
-					    pdx->bulk_in_byte_trk;
-					pdx->bulk_in_byte_trk = 0;
-					pdx->gotPixelData = 1;
-					pdx->frameIdx =
-					    ((pdx->frameIdx +
-					      1) % pdx->num_frames);
-					pdx->urbIdx = 0;
-				}
+		i = usb_submit_urb(urb, GFP_ATOMIC);	/* resubmit the URB */
+		if (i) {
+			errCnt++;
+			if (i != lastErr) {
+				dbg("submit urb in callback failed "
+						"with error code %d", i);
+				lastErr = i;
+			}
+		} else {
+			pdx->urbIdx++; /* point to next URB when we callback */
+			if (pdx->bulk_in_byte_trk >= pdx->frameSize) {
+				pdx->bulk_in_size_returned =
+					pdx->bulk_in_byte_trk;
+				pdx->bulk_in_byte_trk = 0;
+				pdx->gotPixelData = 1;
+				pdx->frameIdx =
+					((pdx->frameIdx +
+					  1) % pdx->num_frames);
+				pdx->urbIdx = 0;
 			}
 		}
 	}
@@ -566,24 +579,37 @@
 
 /* MapUserBuffer(
 	inputs:
-	struct ioctl_struct *io - structure containing user address, frame #, and size
+	struct ioctl_struct *io - structure containing user address,
+				frame #, and size
 	struct device_extension *pdx - the PIUSB device extension
+
 	returns:
 	int - status of the task
+
 	Notes:
-	MapUserBuffer maps a buffer passed down through an ioctl.  The user buffer is Page Aligned by the app
-	and then passed down.  The function get_free_pages(...) does the actual mapping of the buffer from user space to
-	kernel space.  From there a scatterlist is created from all the pages.  The next function called is to usb_buffer_map_sg
-	which allocated DMA addresses for each page, even coalescing them if possible.  The DMA address is placed in the scatterlist
-	structure.  The function returns the number of DMA addresses.  This may or may not be equal to the number of pages that
-	the user buffer uses.  We then build an URB for each DMA address and then submit them.
+	MapUserBuffer maps a buffer passed down through an ioctl.
+	The user buffer is Page Aligned by the app and then passed down.
+	The function get_free_pages(...) does the actual mapping of the buffer
+	from user space to kernel space.
+	From there a scatterlist is created from all the pages.
+	The next function called is to usb_buffer_map_sg which allocated
+	DMA addresses for each page, even coalescing them if possible.
+	The DMA address is placed in the scatterlist structure.
+	The function returns the number of DMA addresses.
+	This may or may not be equal to the number of pages that
+	the user buffer uses.
+	We then build an URB for each DMA address and then submit them.
 */
-//int MapUserBuffer( unsigned long uaddr, unsigned long numbytes, unsigned long frameInfo, struct device_extension *pdx )
+
+/*
+int MapUserBuffer(unsigned long uaddr, unsigned long numbytes,
+		unsigned long frameInfo, struct device_extension *pdx)
+*/
 static int MapUserBuffer(struct ioctl_struct *io, struct device_extension *pdx)
 {
 	unsigned long uaddr;
 	unsigned long numbytes;
-	int frameInfo;		//which frame we're mapping
+	int frameInfo;	/* which frame we're mapping */
 	unsigned int epAddr = 0;
 	unsigned long count = 0;
 	int i = 0;
@@ -591,45 +617,45 @@
 	int err = 0;
 	struct page **maplist_p;
 	int numPagesRequired;
+
 	frameInfo = io->numFrames;
 	uaddr = (unsigned long)io->pData;
 	numbytes = io->numbytes;
 
-	if (pdx->iama == PIXIS_PID)	//if so, which EP should we map this frame to
-	{
-		if (frameInfo % 2)	//check to see if this should use EP4(PONG)
-		{
-			epAddr = pdx->hEP[3];	//PONG, odd frames
-		} else {
-			epAddr = pdx->hEP[2];	//PING, even frames and zero
-		}
+	if (pdx->iama == PIXIS_PID) {
+		/* which EP should we map this frame to ? */
+		/* PONG, odd frames: hEP[3] */
+		/* PING, even frames and zero hEP[2] */
+		epAddr = (frameInfo % 2) ? pdx->hEP[3] : pdx->hEP[2];
 		dbg("Pixis Frame #%d: EP=%d", frameInfo,
 		    (epAddr == pdx->hEP[2]) ? 2 : 4);
-	} else			//ST133 only has 1 endpoint for Pixel data transfer
-	{
+	} else { /* ST133 only has 1 endpoint for Pixel data transfer */
 		epAddr = pdx->hEP[0];
 		dbg("ST133 Frame #%d: EP=2", frameInfo);
 	}
 	count = numbytes;
 	dbg("UserAddress = 0x%08lX", uaddr);
 	dbg("numbytes = %d", (int)numbytes);
-	//number of pages to map the entire user space DMA buffer
+
+	/* number of pages to map the entire user space DMA buffer */
 	numPagesRequired =
 	    ((uaddr & ~PAGE_MASK) + count + ~PAGE_MASK) >> PAGE_SHIFT;
 	dbg("Number of pages needed = %d", numPagesRequired);
-	maplist_p = vmalloc(numPagesRequired * sizeof(struct page));	//, GFP_ATOMIC);
+	maplist_p = vmalloc(numPagesRequired * sizeof(struct page));
 	if (!maplist_p) {
 		dbg("Can't Allocate Memory for maplist_p");
 		return -ENOMEM;
 	}
-	//map the user buffer to kernel memory
+
+	/* map the user buffer to kernel memory */
 	down_write(&current->mm->mmap_sem);
-	pdx->maplist_numPagesMapped[frameInfo] = get_user_pages(current, current->mm, (uaddr & PAGE_MASK), numPagesRequired, WRITE, 0,	//Don't Force
-								maplist_p,
-								NULL);
+	pdx->maplist_numPagesMapped[frameInfo] = get_user_pages(current,
+			current->mm, (uaddr & PAGE_MASK), numPagesRequired,
+			WRITE, 0 /* Don't Force*/, maplist_p, NULL);
 	up_write(&current->mm->mmap_sem);
 	dbg("Number of pages mapped = %d",
 	    pdx->maplist_numPagesMapped[frameInfo]);
+
 	for (i = 0; i < pdx->maplist_numPagesMapped[frameInfo]; i++)
 		flush_dcache_page(maplist_p[i]);
 	if (!pdx->maplist_numPagesMapped[frameInfo]) {
@@ -637,7 +663,10 @@
 		vfree(maplist_p);
 		return -ENOMEM;
 	}
-	//need to create a scatterlist that spans each frame that can fit into the mapped buffer
+
+	/* need to create a scatterlist that spans each frame
+	 * that can fit into the mapped buffer
+	 */
 	pdx->sgl[frameInfo] =
 	    kmalloc((pdx->maplist_numPagesMapped[frameInfo] *
 		     sizeof(struct scatterlist)), GFP_ATOMIC);
@@ -646,7 +675,7 @@
 		dbg("can't allocate mem for sgl");
 		return -ENOMEM;
 	}
-	pdx->sgl[frameInfo][0].page_link = maplist_p[0];
+	sg_assign_page(&pdx->sgl[frameInfo][0], maplist_p[0]);
 	pdx->sgl[frameInfo][0].offset = uaddr & ~PAGE_MASK;
 	if (pdx->maplist_numPagesMapped[frameInfo] > 1) {
 		pdx->sgl[frameInfo][0].length =
@@ -654,10 +683,10 @@
 		count -= pdx->sgl[frameInfo][0].length;
 		for (k = 1; k < pdx->maplist_numPagesMapped[frameInfo]; k++) {
 			pdx->sgl[frameInfo][k].offset = 0;
-			pdx->sgl[frameInfo][k].page_link = maplist_p[k];
+			sg_assign_page(&pdx->sgl[frameInfo][k], maplist_p[k]);
 			pdx->sgl[frameInfo][k].length =
 			    (count < PAGE_SIZE) ? count : PAGE_SIZE;
-			count -= PAGE_SIZE;	//example had PAGE_SIZE here;
+			count -= PAGE_SIZE; /* example had PAGE_SIZE here */
 		}
 	} else {
 		pdx->sgl[frameInfo][0].length = count;
@@ -668,7 +697,8 @@
 	dbg("number of sgEntries = %d", pdx->sgEntries[frameInfo]);
 	pdx->userBufMapped = 1;
 	vfree(maplist_p);
-	//Create and Send the URB's for each s/g entry
+
+	/* Create and Send the URB's for each s/g entry */
 	pdx->PixelUrb[frameInfo] =
 	    kmalloc(pdx->sgEntries[frameInfo] * sizeof(struct urb *),
 		    GFP_KERNEL);
@@ -677,7 +707,8 @@
 		return -ENOMEM;
 	}
 	for (i = 0; i < pdx->sgEntries[frameInfo]; i++) {
-		pdx->PixelUrb[frameInfo][i] = usb_alloc_urb(0, GFP_KERNEL);	//0 because we're using BULK transfers
+		/* 0 iso packets because we're using BULK transfers */
+		pdx->PixelUrb[frameInfo][i] = usb_alloc_urb(0, GFP_KERNEL);
 		usb_fill_bulk_urb(pdx->PixelUrb[frameInfo][i],
 				  pdx->udev,
 				  epAddr,
@@ -691,7 +722,8 @@
 		pdx->PixelUrb[frameInfo][i]->transfer_flags =
 		    URB_NO_TRANSFER_DMA_MAP | URB_NO_INTERRUPT;
 	}
-	pdx->PixelUrb[frameInfo][--i]->transfer_flags &= ~URB_NO_INTERRUPT;	//only interrupt when last URB completes
+	/* only interrupt when last URB completes */
+	pdx->PixelUrb[frameInfo][--i]->transfer_flags &= ~URB_NO_INTERRUPT;
 	pdx->pendedPixelUrbs[frameInfo] =
 	    kmalloc((pdx->sgEntries[frameInfo] * sizeof(char)), GFP_KERNEL);
 	if (!pdx->pendedPixelUrbs[frameInfo])
@@ -702,13 +734,13 @@
 			dbg("%s %d\n", "submit urb error =", err);
 			pdx->pendedPixelUrbs[frameInfo][i] = 0;
 			return err;
-		} else
-			pdx->pendedPixelUrbs[frameInfo][i] = 1;;
+		}
+		pdx->pendedPixelUrbs[frameInfo][i] = 1;
 	}
 	return 0;
 }
 
-static struct file_operations piusb_fops = {
+static const struct file_operations piusb_fops = {
 	.owner = THIS_MODULE,
 	.ioctl = piusb_ioctl,
 	.open = piusb_open,
@@ -751,9 +783,9 @@
 	/* See if the device offered us matches what we can accept */
 	if ((pdx->udev->descriptor.idVendor != VENDOR_ID)
 	    || ((pdx->udev->descriptor.idProduct != PIXIS_PID)
-		&& (pdx->udev->descriptor.idProduct != ST133_PID))) {
+		&& (pdx->udev->descriptor.idProduct != ST133_PID)))
 		return -ENODEV;
-	}
+
 	pdx->iama = pdx->udev->descriptor.idProduct;
 
 	if (debug) {
@@ -807,7 +839,7 @@
 	dbg("PI USB2.0 device now attached to piusb-%d", pdx->minor);
 	return 0;
 
-      error:
+error:
 	if (pdx)
 		kref_put(&pdx->kref, piusb_delete);
 	return retval;
@@ -828,12 +860,17 @@
 {
 	struct device_extension *pdx;
 	int minor = interface->minor;
+
 	lock_kernel();
+
 	pdx = usb_get_intfdata(interface);
 	usb_set_intfdata(interface, NULL);
+
 	/* give back our minor */
 	usb_deregister_dev(interface, &piusb_class);
+
 	unlock_kernel();
+
 	/* prevent device read, write and ioctl */
 	pdx->present = 0;
 	kref_put(&pdx->kref, piusb_delete);
@@ -853,16 +890,20 @@
 static int __init piusb_init(void)
 {
 	int result;
+
+	lastErr = 0;
+	errCnt = 0;
+
 	/* register this driver with the USB subsystem */
 	result = usb_register(&piusb_driver);
-	if (result) {
+	if (result)
 		printk(KERN_ERR KBUILD_MODNAME
-		       ": usb_register failed. Error number %d\n", result);
-		return result;
-	}
-	printk(KERN_INFO KBUILD_MODNAME ":%s: %s\n", DRIVER_DESC,
-	       DRIVER_VERSION);
-	return 0;
+				": usb_register failed. Error number %d\n",
+				result);
+	else
+		printk(KERN_INFO KBUILD_MODNAME ":%s: %s\n", DRIVER_DESC,
+				DRIVER_VERSION);
+	return result;
 }
 
 /**
diff --git a/drivers/staging/rspiusb/rspiusb.h b/drivers/staging/rspiusb/rspiusb.h
index 965cd2d8..3fc1db7 100644
--- a/drivers/staging/rspiusb/rspiusb.h
+++ b/drivers/staging/rspiusb/rspiusb.h
@@ -3,20 +3,28 @@
 
 #define PIUSB_MAGIC		'm'
 #define PIUSB_IOCTL_BASE	192
-#define PIUSB_GETVNDCMD		_IOR(PIUSB_MAGIC, PIUSB_IOCTL_BASE + 1, struct ioctl_struct)
-#define PIUSB_SETVNDCMD		_IOW(PIUSB_MAGIC, PIUSB_IOCTL_BASE + 2, struct ioctl_struct)
-#define PIUSB_WRITEPIPE		_IOW(PIUSB_MAGIC, PIUSB_IOCTL_BASE + 3, struct ioctl_struct)
-#define PIUSB_READPIPE		_IOR(PIUSB_MAGIC, PIUSB_IOCTL_BASE + 4, struct ioctl_struct)
-#define PIUSB_SETFRAMESIZE	_IOW(PIUSB_MAGIC, PIUSB_IOCTL_BASE + 5, struct ioctl_struct)
-#define PIUSB_WHATCAMERA	_IO(PIUSB_MAGIC,  PIUSB_IOCTL_BASE + 6)
-#define PIUSB_USERBUFFER	_IOW(PIUSB_MAGIC, PIUSB_IOCTL_BASE + 7, struct ioctl_struct)
-#define PIUSB_ISHIGHSPEED	_IO(PIUSB_MAGIC,  PIUSB_IOCTL_BASE + 8)
-#define PIUSB_UNMAP_USERBUFFER	_IOW(PIUSB_MAGIC, PIUSB_IOCTL_BASE + 9, struct ioctl_struct)
+
+#define PIUSB_IOR(offset) \
+	_IOR(PIUSB_MAGIC, PIUSB_IOCTL_BASE + offset, struct ioctl_struct)
+#define PIUSB_IOW(offset) \
+	_IOW(PIUSB_MAGIC, PIUSB_IOCTL_BASE + offset, struct ioctl_struct)
+#define PIUSB_IO(offset) \
+	_IO(PIUSB_MAGIC, PIUSB_IOCTL_BASE + offset)
+
+#define PIUSB_GETVNDCMD		PIUSB_IOR(1)
+#define PIUSB_SETVNDCMD		PIUSB_IOW(2)
+#define PIUSB_WRITEPIPE		PIUSB_IOW(3)
+#define PIUSB_READPIPE		PIUSB_IOR(4)
+#define PIUSB_SETFRAMESIZE	PIUSB_IOW(5)
+#define PIUSB_WHATCAMERA	PIUSB_IO(6)
+#define PIUSB_USERBUFFER	PIUSB_IOW(7)
+#define PIUSB_ISHIGHSPEED	PIUSB_IO(8)
+#define PIUSB_UNMAP_USERBUFFER	PIUSB_IOW(9)
 
 struct ioctl_struct {
 	unsigned char cmd;
 	unsigned long numbytes;
-	unsigned char dir;	//1=out;0=in
+	unsigned char dir;	/* 1=out; 0=in */
 	int endpoint;
 	int numFrames;
 	unsigned char *pData;
diff --git a/drivers/staging/rt2860/2860_main_dev.c b/drivers/staging/rt2860/2860_main_dev.c
index ff7f833..c7038e0 100644
--- a/drivers/staging/rt2860/2860_main_dev.c
+++ b/drivers/staging/rt2860/2860_main_dev.c
@@ -37,13 +37,6 @@
 
 #include "rt_config.h"
 
-
-#ifdef MULTIPLE_CARD_SUPPORT
-// record whether the card in the card list is used in the card file
-extern UINT8  MC_CardUsed[];
-#endif // MULTIPLE_CARD_SUPPORT //
-
-
 extern INT __devinit rt28xx_probe(IN void *_dev_p, IN void *_dev_id_p,
 									IN UINT argc, OUT PRTMP_ADAPTER *ppAd);
 
@@ -110,13 +103,10 @@
 };
 
 MODULE_DEVICE_TABLE(pci, rt2860_pci_tbl);
-#ifdef CONFIG_STA_SUPPORT
 MODULE_LICENSE("GPL");
 #ifdef MODULE_VERSION
 MODULE_VERSION(STA_DRIVER_VERSION);
 #endif
-#endif // CONFIG_STA_SUPPORT //
-
 
 //
 // Our PCI driver structure
@@ -328,14 +318,6 @@
 
 	if (pAd != NULL)
 	{
-#ifdef MULTIPLE_CARD_SUPPORT
-		if ((pAd->MC_RowID >= 0) && (pAd->MC_RowID <= MAX_NUM_OF_MULTIPLE_CARD))
-			MC_CardUsed[pAd->MC_RowID] = 0; // not clear MAC address
-#endif // MULTIPLE_CARD_SUPPORT //
-
-
-
-
 		// Unregister network device
 		unregister_netdev(net_dev);
 
@@ -494,10 +476,8 @@
     pObj = (POS_COOKIE) pAd->OS_Cookie;
 
 	pAd->int_pending &= ~(INT_RX);
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		bReschedule = STARxDoneInterruptHandle(pAd, 0);
-#endif // CONFIG_STA_SUPPORT //
+
+	bReschedule = STARxDoneInterruptHandle(pAd, 0);
 
 	RTMP_INT_LOCK(&pAd->irq_lock, flags);
 	/*
@@ -933,15 +913,8 @@
 		RTMPHandleTBTTInterrupt(pAd);
 	}
 
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (IntSource.word & AutoWakeupInt)
-			RTMPHandleTwakeupInterrupt(pAd);
-	}
-#endif // CONFIG_STA_SUPPORT //
+	if (IntSource.word & AutoWakeupInt)
+		RTMPHandleTwakeupInterrupt(pAd);
 
     return  IRQ_HANDLED;
 }
@@ -1182,9 +1155,7 @@
 	else
 	{
 		ptr = (PUCHAR)&pAd->BeaconTxWI;
-#ifdef RT_BIG_ENDIAN
-		RTMPWIEndianChange(ptr, TYPE_TXWI);
-#endif
+
 		for (i=0; i<TXWI_SIZE; i+=4)  // 16-byte TXWI field
 		{
 			UINT32 longptr =  *ptr + (*(ptr+1)<<8) + (*(ptr+2)<<16) + (*(ptr+3)<<24);
@@ -1212,7 +1183,6 @@
 
 }
 
-#ifdef CONFIG_STA_SUPPORT
 VOID RTMPInitPCIeLinkCtrlValue(
 	IN	PRTMP_ADAPTER	pAd)
 {
@@ -1256,7 +1226,6 @@
 	IN 	USHORT		Max)
 {
 }
-#endif // CONFIG_STA_SUPPORT //
 
 VOID rt2860_stop(struct net_device *net_dev)
 {
diff --git a/drivers/staging/rt2860/Makefile b/drivers/staging/rt2860/Makefile
index b956364..c9fe925 100644
--- a/drivers/staging/rt2860/Makefile
+++ b/drivers/staging/rt2860/Makefile
@@ -2,11 +2,8 @@
 
 # TODO: all of these should be removed
 EXTRA_CFLAGS += -DLINUX -DAGGREGATION_SUPPORT -DPIGGYBACK_SUPPORT -DWMM_SUPPORT
-EXTRA_CFLAGS += -DCONFIG_STA_SUPPORT
+EXTRA_CFLAGS += -DRT2860
 EXTRA_CFLAGS += -DDBG
-EXTRA_CFLAGS += -DDOT11_N_SUPPORT
-EXTRA_CFLAGS += -DWPA_SUPPLICANT_SUPPORT
-EXTRA_CFLAGS += -DNATIVE_WPA_SUPPLICANT_SUPPORT
 
 rt2860sta-objs :=	\
 	common/md5.o		\
diff --git a/drivers/staging/rt2860/ap.h b/drivers/staging/rt2860/ap.h
index df6db28..a814d55 100644
--- a/drivers/staging/rt2860/ap.h
+++ b/drivers/staging/rt2860/ap.h
@@ -159,9 +159,6 @@
     IN UCHAR  *pRSNLen,
     IN BOOLEAN bWmmCapable,
     IN ULONG  RalinkIe,
-#ifdef DOT11N_DRAFT3
-    IN EXT_CAP_INFO_ELEMENT ExtCapInfo,
-#endif // DOT11N_DRAFT3 //
 	IN HT_CAPABILITY_IE		*pHtCapability,
 	IN UCHAR		 HtCapabilityLen,
     OUT USHORT *pAid);
@@ -282,11 +279,6 @@
 BOOLEAN ApScanRunning(
 	IN PRTMP_ADAPTER pAd);
 
-#ifdef DOT11N_DRAFT3
-VOID APOverlappingBSSScan(
-	IN RTMP_ADAPTER *pAd);
-#endif // DOT11N_DRAFT3 //
-
 // ap_wpa.c
 
 VOID APWpaStateMachineInit(
@@ -332,6 +324,13 @@
     IN PVOID SystemSpecific2,
     IN PVOID SystemSpecific3);
 
+#ifdef RT2870
+VOID BeaconUpdateExec(
+    IN PVOID SystemSpecific1,
+    IN PVOID FunctionContext,
+    IN PVOID SystemSpecific2,
+    IN PVOID SystemSpecific3);
+#endif // RT2870 //
 
 VOID RTMPSetPiggyBack(
 	IN PRTMP_ADAPTER	pAd,
@@ -408,10 +407,8 @@
     IN PUCHAR           pAddr,
     IN USHORT           Event);
 
-#ifdef DOT11_N_SUPPORT
 VOID APUpdateOperationMode(
     IN PRTMP_ADAPTER pAd);
-#endif // DOT11_N_SUPPORT //
 
 VOID APUpdateCapabilityAndErpIe(
 	IN PRTMP_ADAPTER pAd);
@@ -472,9 +469,6 @@
     OUT UCHAR *pRSNLen,
     OUT BOOLEAN *pbWmmCapable,
     OUT ULONG  *pRalinkIe,
-#ifdef DOT11N_DRAFT3
-    OUT EXT_CAP_INFO_ELEMENT	*pExtCapInfo,
-#endif // DOT11N_DRAFT3 //
     OUT UCHAR		 *pHtCapabilityLen,
     OUT HT_CAPABILITY_IE *pHtCapability);
 
@@ -529,26 +523,6 @@
     OUT BOOLEAN *ExtendedRateIeExist,
     OUT UCHAR *Erp);
 
-// ap_info.c
-
-#ifdef WIN_NDIS
-NDIS_STATUS APQueryInformation(
-    IN  NDIS_HANDLE MiniportAdapterContext,
-    IN  NDIS_OID    Oid,
-    IN  PVOID       pInformationBuffer,
-    IN  ULONG       InformationBufferLength,
-    OUT PULONG      pBytesWritten,
-    OUT PULONG      pBytesNeeded);
-
-NDIS_STATUS APSetInformation(
-    IN  NDIS_HANDLE MiniportAdapterContext,
-    IN  NDIS_OID    Oid,
-    IN  PVOID       pInformationBuffer,
-    IN  ULONG       InformationBufferLength,
-    OUT PULONG      pBytesRead,
-    OUT PULONG      pBytesNeeded);
-#endif
-
 
 // ================== end of AP RTMP.h ========================
 
diff --git a/drivers/staging/rt2860/chlist.h b/drivers/staging/rt2860/chlist.h
index 9e15b9d..1ad26b5 100644
--- a/drivers/staging/rt2860/chlist.h
+++ b/drivers/staging/rt2860/chlist.h
@@ -524,7 +524,12 @@
 			JAP,
 			{
 				{ 1,   14,  20, BOTH, FALSE},	// 2.4 G, ch 1~14
+#ifndef RT30xx
 				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
+#endif
+#ifdef RT30xx
+				{ 34, 	4,  23, IDOR, FALSE},	// 5G, ch 34~46
+#endif
 				{ 0},							// end
 			}
 		},
@@ -957,16 +962,12 @@
 	switch(PhyMode)
 	{
 		case PHY_11A:
-#ifdef DOT11_N_SUPPORT
 		case PHY_11AN_MIXED:
-#endif // DOT11_N_SUPPORT //
 			*pChType = BAND_5G;
 			break;
 		case PHY_11ABG_MIXED:
-#ifdef DOT11_N_SUPPORT
 		case PHY_11AGN_MIXED:
 		case PHY_11ABGN_MIXED:
-#endif // DOT11_N_SUPPORT //
 			*pChType = BAND_BOTH;
 			break;
 
@@ -1114,8 +1115,6 @@
 	}
 }
 
-
-#ifdef DOT11_N_SUPPORT
 static inline BOOLEAN IsValidChannel(
 	IN PRTMP_ADAPTER pAd,
 	IN UCHAR channel)
@@ -1201,49 +1200,6 @@
 				pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
 				//pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_NONE;	// We didn't set the ExtCh as NONE due to it'll set in RTMPSetHT()
 			}
-#if 0
-			switch (pAd->CommonCfg.CountryRegion  & 0x7f)
-			{
-				case REGION_0_BG_BAND:	// 1 -11
-				case REGION_1_BG_BAND:	// 1 - 13
-				case REGION_5_BG_BAND:	// 1 - 14
-					if (Channel <= 4)
-					{
-						pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-					}
-					else if (Channel >= 8)
-					{
-						if ((ChannelNum - Channel) < 4)
-							pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_BELOW;
-					}
-					break;
-
-				case REGION_2_BG_BAND:	// 10 - 11
-				case REGION_3_BG_BAND:	// 10 - 13
-				case REGION_4_BG_BAND:	// 14
-					pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-					break;
-
-				case REGION_6_BG_BAND:	// 3 - 9
-					if (Channel <= 5)
-						pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-					else if (Channel == 6)
-						pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-					else if (Channel >= 7)
-						pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_BELOW;
-					break;
-
-				case REGION_7_BG_BAND:  // 5 - 13
-					if (Channel <= 8)
-						pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-					else if (Channel >= 10)
-						pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_BELOW;
-					break;
-
-				default:	// Error. should never happen
-					break;
-			}
-#endif
 		}
 	}
 
@@ -1273,8 +1229,6 @@
 		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
 	}
 }
-#endif // DOT11_N_SUPPORT //
-
 
 static inline UINT8 GetCuntryMaxTxPwr(
 	IN PRTMP_ADAPTER pAd,
diff --git a/drivers/staging/rt2860/common/2860_rtmp_init.c b/drivers/staging/rt2860/common/2860_rtmp_init.c
index 546f304..0bc0fb99 100644
--- a/drivers/staging/rt2860/common/2860_rtmp_init.c
+++ b/drivers/staging/rt2860/common/2860_rtmp_init.c
@@ -173,9 +173,6 @@
 				pTxD->SDPtr0 = BufBasePaLow;
 				// advance to next ring descriptor address
 				pTxD->DMADONE = 1;
-#ifdef RT_BIG_ENDIAN
-				RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#endif
 				RingBasePaLow += TXD_SIZE;
 				RingBaseVa = (PUCHAR) RingBaseVa + TXD_SIZE;
 
@@ -236,9 +233,6 @@
 			pTxD = (PTXD_STRUC) pAd->MgmtRing.Cell[index].AllocVa;
 			pTxD->DMADONE = 1;
 
-#ifdef RT_BIG_ENDIAN
-			RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#endif
 			// no pre-allocated buffer required in MgmtRing for scatter-gather case
 		}
 		DBGPRINT(RT_DEBUG_TRACE, ("MGMT Ring: total %d entry allocated\n", index));
@@ -318,10 +312,6 @@
 			pRxD = (PRXD_STRUC) pAd->RxRing.Cell[index].AllocVa;
 			pRxD->SDP0 = RTMP_GetPhysicalAddressLow(pDmaBuf->AllocPa);
 			pRxD->DDONE = 0;
-
-#ifdef RT_BIG_ENDIAN
-			RTMPDescriptorEndianChange((PUCHAR)pRxD, TYPE_RXD);
-#endif
 		}
 
 		DBGPRINT(RT_DEBUG_TRACE, ("Rx Ring: total %d entry allocated\n", index));
@@ -821,10 +811,6 @@
 	IN OUT	UINT32			*pRxPending)
 {
 	PRXD_STRUC				pRxD;
-#ifdef RT_BIG_ENDIAN
-	PRXD_STRUC				pDestRxD;
-	RXD_STRUC				RxD;
-#endif
 	PNDIS_PACKET			pRxPacket = NULL;
 	PNDIS_PACKET			pNewPacket;
 	PVOID					AllocVa;
@@ -853,15 +839,8 @@
 
 	}
 
-#ifdef RT_BIG_ENDIAN
-	pDestRxD = (PRXD_STRUC) pAd->RxRing.Cell[pAd->RxRing.RxSwReadIdx].AllocVa;
-	RxD = *pDestRxD;
-	pRxD = &RxD;
-	RTMPDescriptorEndianChange((PUCHAR)pRxD, TYPE_RXD);
-#else
 	// Point to Rx indexed rx ring descriptor
 	pRxD = (PRXD_STRUC) pAd->RxRing.Cell[pAd->RxRing.RxSwReadIdx].AllocVa;
-#endif
 
 	if (pRxD->DDONE == 0)
 	{
@@ -904,10 +883,6 @@
 	*pRxPending = *pRxPending - 1;
 
 	// update rx descriptor and kick rx
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pRxD, TYPE_RXD);
-	WriteBackToDescriptor((PUCHAR)pDestRxD, (PUCHAR)pRxD, FALSE, TYPE_RXD);
-#endif
 	INC_RING_INDEX(pAd->RxRing.RxSwReadIdx, RX_RING_SIZE);
 
 	pAd->RxRing.RxCpuIdx = (pAd->RxRing.RxSwReadIdx == 0) ? (RX_RING_SIZE-1) : (pAd->RxRing.RxSwReadIdx-1);
diff --git a/drivers/staging/rt2860/common/action.c b/drivers/staging/rt2860/common/action.c
index d6f530f..a4d9fdc 100644
--- a/drivers/staging/rt2860/common/action.c
+++ b/drivers/staging/rt2860/common/action.c
@@ -72,17 +72,12 @@
 	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_QOS_CATE, (STATE_MACHINE_FUNC)PeerQOSAction);
 
 	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_DLS_CATE, (STATE_MACHINE_FUNC)ReservedAction);
-#ifdef QOS_DLS_SUPPORT
-		StateMachineSetAction(S, ACT_IDLE, MT2_PEER_DLS_CATE, (STATE_MACHINE_FUNC)PeerDLSAction);
-#endif // QOS_DLS_SUPPORT //
 
-#ifdef DOT11_N_SUPPORT
 	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_BA_CATE, (STATE_MACHINE_FUNC)PeerBAAction);
 	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_HT_CATE, (STATE_MACHINE_FUNC)PeerHTAction);
 	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_ADD_BA_CATE, (STATE_MACHINE_FUNC)MlmeADDBAAction);
 	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_ORI_DELBA_CATE, (STATE_MACHINE_FUNC)MlmeDELBAAction);
 	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_REC_DELBA_CATE, (STATE_MACHINE_FUNC)MlmeDELBAAction);
-#endif // DOT11_N_SUPPORT //
 
 	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_PUBLIC_CATE, (STATE_MACHINE_FUNC)PeerPublicAction);
 	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_RM_CATE, (STATE_MACHINE_FUNC)PeerRMAction);
@@ -92,7 +87,6 @@
 	StateMachineSetAction(S, ACT_IDLE, MT2_ACT_INVALID, (STATE_MACHINE_FUNC)MlmeInvalidAction);
 }
 
-#ifdef DOT11_N_SUPPORT
 VOID MlmeADDBAAction(
     IN PRTMP_ADAPTER pAd,
     IN MLME_QUEUE_ELEM *Elem)
@@ -131,21 +125,12 @@
 			pBAEntry =&pAd->BATable.BAOriEntry[Idx];
 		}
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			if (ADHOC_ON(pAd))
 				ActHeaderInit(pAd, &Frame.Hdr, pInfo->pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
 			else
-#ifdef QOS_DLS_SUPPORT
-			if (pAd->MacTab.Content[pInfo->Wcid].ValidAsDls)
-				ActHeaderInit(pAd, &Frame.Hdr, pInfo->pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-			else
-#endif // QOS_DLS_SUPPORT //
 				ActHeaderInit(pAd, &Frame.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pInfo->pAddr);
-
 		}
-#endif // CONFIG_STA_SUPPORT //
 
 		Frame.Category = CATEGORY_BA;
 		Frame.Action = ADDBA_REQ;
@@ -220,10 +205,8 @@
 
 		// SEND BAR (Send BAR to refresh peer reordering buffer.)
 		Idx = pAd->MacTab.Content[pInfo->Wcid].BAOriWcidArray[pInfo->TID];
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			BarHeaderInit(pAd, &FrameBar, pAd->MacTab.Content[pInfo->Wcid].Addr, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
+
+		BarHeaderInit(pAd, &FrameBar, pAd->MacTab.Content[pInfo->Wcid].Addr, pAd->CurrentAddress);
 
 		FrameBar.StartingSeq.field.FragNum = 0; // make sure sequence not clear in DEL funciton.
 		FrameBar.StartingSeq.field.StartSeq = pAd->MacTab.Content[pInfo->Wcid].TxSeq[pInfo->TID]; // make sure sequence not clear in DEL funciton.
@@ -241,20 +224,14 @@
 
 		// SEND DELBA FRAME
 		FrameLen = 0;
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+
 		{
 			if (ADHOC_ON(pAd))
 				ActHeaderInit(pAd, &Frame.Hdr, pAd->MacTab.Content[pInfo->Wcid].Addr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
 			else
-#ifdef QOS_DLS_SUPPORT
-			if (pAd->MacTab.Content[pInfo->Wcid].ValidAsDls)
-				ActHeaderInit(pAd, &Frame.Hdr, pAd->MacTab.Content[pInfo->Wcid].Addr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-			else
-#endif // QOS_DLS_SUPPORT //
 				ActHeaderInit(pAd, &Frame.Hdr,  pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->MacTab.Content[pInfo->Wcid].Addr);
 		}
-#endif // CONFIG_STA_SUPPORT //
+
 		Frame.Category = CATEGORY_BA;
 		Frame.Action = DELBA;
 		Frame.DelbaParm.Initiator = pInfo->Initiator;
@@ -271,7 +248,6 @@
 		DBGPRINT(RT_DEBUG_TRACE, ("BA - MlmeDELBAAction() . 3 DELBA sent. Initiator(%d)\n", pInfo->Initiator));
     	}
 }
-#endif // DOT11_N_SUPPORT //
 
 VOID MlmeQOSAction(
     IN PRTMP_ADAPTER pAd,
@@ -299,40 +275,6 @@
 {
 }
 
-#ifdef QOS_DLS_SUPPORT
-VOID PeerDLSAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-
-	switch(Action)
-	{
-		case ACTION_DLS_REQUEST:
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			PeerDlsReqAction(pAd, Elem);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-
-		case ACTION_DLS_RESPONSE:
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			PeerDlsRspAction(pAd, Elem);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-
-		case ACTION_DLS_TEARDOWN:
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			PeerDlsTearDownAction(pAd, Elem);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-	}
-}
-#endif // QOS_DLS_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
 VOID PeerBAAction(
 	IN PRTMP_ADAPTER pAd,
 	IN MLME_QUEUE_ELEM *Elem)
@@ -353,320 +295,12 @@
 	}
 }
 
-
-#ifdef DOT11N_DRAFT3
-
-#ifdef CONFIG_STA_SUPPORT
-VOID StaPublicAction(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR Bss2040Coexist)
-{
-	BSS_2040_COEXIST_IE		BssCoexist;
-	MLME_SCAN_REQ_STRUCT			ScanReq;
-
-	BssCoexist.word = Bss2040Coexist;
-	// AP asks Station to return a 20/40 BSS Coexistence mgmt frame.  So we first starts a scan, then send back 20/40 BSS Coexistence mgmt frame
-	if ((BssCoexist.field.InfoReq == 1) && (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SCAN_2040)))
-	{
-		// Clear record first.  After scan , will update those bit and send back to transmiter.
-		pAd->CommonCfg.BSSCoexist2040.field.InfoReq = 1;
-		pAd->CommonCfg.BSSCoexist2040.field.Intolerant40 = 0;
-		pAd->CommonCfg.BSSCoexist2040.field.BSS20WidthReq = 0;
-		// Fill out stuff for scan request
-		ScanParmFill(pAd, &ScanReq, ZeroSsid, 0, BSS_ANY, SCAN_2040_BSS_COEXIST);
-		MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-	}
-}
-
-
-/*
-Description : Build Intolerant Channel Rerpot from Trigger event table.
-return : how many bytes copied.
-*/
-ULONG BuildIntolerantChannelRep(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    PUCHAR  pDest)
-{
-	ULONG			FrameLen = 0;
-	ULONG			ReadOffset = 0;
-	UCHAR			i;
-	UCHAR			LastRegClass = 0xff;
-	PUCHAR			pLen;
-
-	for ( i = 0;i < MAX_TRIGGER_EVENT;i++)
-	{
-		if (pAd->CommonCfg.TriggerEventTab.EventA[i].bValid == TRUE)
-		{
-			if (pAd->CommonCfg.TriggerEventTab.EventA[i].RegClass == LastRegClass)
-			{
-				*(pDest + ReadOffset) = (UCHAR)pAd->CommonCfg.TriggerEventTab.EventA[i].Channel;
-				*pLen++;
-				ReadOffset++;
-				FrameLen++;
-			}
-			else
-			{
-				*(pDest + ReadOffset) = IE_2040_BSS_INTOLERANT_REPORT;  // IE
-				*(pDest + ReadOffset + 1) = 2;	// Len = RegClass byte + channel byte.
-				pLen = pDest + ReadOffset + 1;
-				LastRegClass = pAd->CommonCfg.TriggerEventTab.EventA[i].RegClass;
-				*(pDest + ReadOffset + 2) = LastRegClass;	// Len = RegClass byte + channel byte.
-				*(pDest + ReadOffset + 3) = (UCHAR)pAd->CommonCfg.TriggerEventTab.EventA[i].Channel;
-				FrameLen += 4;
-				ReadOffset += 4;
-			}
-
-		}
-	}
-	return FrameLen;
-}
-
-
-/*
-Description : Send 20/40 BSS Coexistence Action frame If one trigger event is triggered.
-*/
-VOID Send2040CoexistAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS 	NStatus;
-	FRAME_ACTION_HDR	Frame;
-	ULONG			FrameLen;
-	ULONG			IntolerantChaRepLen;
-
-	IntolerantChaRepLen = 0;
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("ACT - Send2040CoexistAction() allocate memory failed \n"));
-		return;
-	}
-	ActHeaderInit(pAd, &Frame.Hdr, pAd->MacTab.Content[Wcid].Addr, pAd->CommonCfg.Bssid);
-	Frame.Category = CATEGORY_PUBLIC;
-	Frame.Action = ACTION_BSS_2040_COEXIST;
-
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-				  sizeof(FRAME_ACTION_HDR),	  &Frame,
-				  END_OF_ARGS);
-
-	*(pOutBuffer + FrameLen) = pAd->CommonCfg.BSSCoexist2040.word;
-	FrameLen++;
-
-	if (bAddIntolerantCha == TRUE)
-		IntolerantChaRepLen = BuildIntolerantChannelRep(pAd, pOutBuffer + FrameLen);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen + IntolerantChaRepLen);
-	DBGPRINT(RT_DEBUG_ERROR,("ACT - Send2040CoexistAction( BSSCoexist2040 = 0x%x )  \n", pAd->CommonCfg.BSSCoexist2040.word));
-
-}
-
-
-/*
-	==========================================================================
-	Description:
-	After scan, Update 20/40 BSS Coexistence IE and send out.
-	According to 802.11n D3.03 11.14.10
-
-	Parameters:
-	==========================================================================
- */
-VOID Update2040CoexistFrameAndNotify(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha)
-{
-	BSS_2040_COEXIST_IE	OldValue;
-
-	OldValue.word = pAd->CommonCfg.BSSCoexist2040.word;
-	if ((pAd->CommonCfg.TriggerEventTab.EventANo > 0) || (pAd->CommonCfg.TriggerEventTab.EventBCountDown > 0))
-		pAd->CommonCfg.BSSCoexist2040.field.BSS20WidthReq = 1;
-
-	// Need to check !!!!
-	// How STA will set Intolerant40 if implementation dependent. Now we don't set this bit first.!!!!!
-	// So Only check BSS20WidthReq change.
-	if (OldValue.field.BSS20WidthReq != pAd->CommonCfg.BSSCoexist2040.field.BSS20WidthReq)
-	{
-		Send2040CoexistAction(pAd, Wcid, bAddIntolerantCha);
-	}
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-BOOLEAN ChannelSwitchSanityCheck(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  NewChannel,
-	IN    UCHAR  Secondary)
-{
-	UCHAR		i;
-
-	if (Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return FALSE;
-
-	if ((NewChannel > 7) && (Secondary == 1))
-		return FALSE;
-
-	if ((NewChannel < 5) && (Secondary == 3))
-		return FALSE;
-
-	// 0. Check if new channel is in the channellist.
-	for (i = 0;i < pAd->ChannelListNum;i++)
-	{
-		if (pAd->ChannelList[i].Channel == NewChannel)
-		{
-			break;
-		}
-	}
-
-	if (i == pAd->ChannelListNum)
-		return FALSE;
-
-	return TRUE;
-}
-
-
-VOID ChannelSwitchAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  NewChannel,
-	IN    UCHAR  Secondary)
-{
-	UCHAR		BBPValue = 0;
-	ULONG		MACValue;
-
-	DBGPRINT(RT_DEBUG_TRACE,("SPECTRUM - ChannelSwitchAction(NewChannel = %d , Secondary = %d)  \n", NewChannel, Secondary));
-
-	if (ChannelSwitchSanityCheck(pAd, Wcid, NewChannel, Secondary) == FALSE)
-		return;
-
-	// 1.  Switches to BW = 20.
-	if (Secondary == 0)
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-		BBPValue&= (~0x18);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-		if (pAd->MACVersion == 0x28600100)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x16);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x08);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x11);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
-		}
-		pAd->CommonCfg.BBPCurrentBW = BW_20;
-		pAd->CommonCfg.Channel = NewChannel;
-		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.Channel,FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-		pAd->MacTab.Content[Wcid].HTPhyMode.field.BW = 0;
-		DBGPRINT(RT_DEBUG_TRACE, ("!!!20MHz   !!! \n" ));
-	}
-	// 1.  Switches to BW = 40 And Station supports BW = 40.
-	else if (((Secondary == 1) || (Secondary == 3)) && (pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth == 1))
-	{
-		pAd->CommonCfg.Channel = NewChannel;
-
-		if (Secondary == 1)
-		{
-			// Secondary above.
-			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel + 2;
-			RTMP_IO_READ32(pAd, TX_BAND_CFG, &MACValue);
-			MACValue &= 0xfe;
-			RTMP_IO_WRITE32(pAd, TX_BAND_CFG, MACValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue&= (~0x18);
-			BBPValue|= (0x10);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPValue);
-			BBPValue&= (~0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPValue);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!!40MHz Lower LINK UP !!! Control Channel at Below. Central = %d \n", pAd->CommonCfg.CentralChannel ));
-		}
-		else
-		{
-			// Secondary below.
-			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel - 2;
-			RTMP_IO_READ32(pAd, TX_BAND_CFG, &MACValue);
-			MACValue &= 0xfe;
-			MACValue |= 0x1;
-			RTMP_IO_WRITE32(pAd, TX_BAND_CFG, MACValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue&= (~0x18);
-			BBPValue|= (0x10);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPValue);
-			BBPValue&= (~0x20);
-			BBPValue|= (0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPValue);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!!40MHz Upper LINK UP !!! Control Channel at UpperCentral = %d \n", pAd->CommonCfg.CentralChannel ));
-		}
-		pAd->CommonCfg.BBPCurrentBW = BW_40;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-		pAd->MacTab.Content[Wcid].HTPhyMode.field.BW = 1;
-	}
-}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
 VOID PeerPublicAction(
 	IN PRTMP_ADAPTER pAd,
 	IN MLME_QUEUE_ELEM *Elem)
 {
-#ifdef DOT11N_DRAFT3
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-#endif // DOT11N_DRAFT3 //
-
 	if (Elem->Wcid >= MAX_LEN_OF_MAC_TABLE)
 		return;
-
-#ifdef DOT11N_DRAFT3
-	switch(Action)
-	{
-		case ACTION_BSS_2040_COEXIST:	// Format defined in IEEE 7.4.7a.1 in 11n Draf3.03
-			{
-				//UCHAR	BssCoexist;
-				BSS_2040_COEXIST_ELEMENT		*pCoexistInfo;
-				BSS_2040_COEXIST_IE 			*pBssCoexistIe;
-				BSS_2040_INTOLERANT_CH_REPORT	*pIntolerantReport = NULL;
-
-				if (Elem->MsgLen <= (LENGTH_802_11 + sizeof(BSS_2040_COEXIST_ELEMENT)) )
-				{
-					DBGPRINT(RT_DEBUG_ERROR, ("ACTION - 20/40 BSS Coexistence Management Frame length too short! len = %ld!\n", Elem->MsgLen));
-					break;
-				}
-				DBGPRINT(RT_DEBUG_TRACE, ("ACTION - 20/40 BSS Coexistence Management action----> \n"));
-				hex_dump("CoexistenceMgmtFrame", Elem->Msg, Elem->MsgLen);
-
-
-				pCoexistInfo = (BSS_2040_COEXIST_ELEMENT *) &Elem->Msg[LENGTH_802_11+2];
-				//hex_dump("CoexistInfo", (PUCHAR)pCoexistInfo, sizeof(BSS_2040_COEXIST_ELEMENT));
-				if (Elem->MsgLen >= (LENGTH_802_11 + sizeof(BSS_2040_COEXIST_ELEMENT) + sizeof(BSS_2040_INTOLERANT_CH_REPORT)))
-				{
-					pIntolerantReport = (BSS_2040_INTOLERANT_CH_REPORT *)((PUCHAR)pCoexistInfo + sizeof(BSS_2040_COEXIST_ELEMENT));
-				}
-				//hex_dump("IntolerantReport ", (PUCHAR)pIntolerantReport, sizeof(BSS_2040_INTOLERANT_CH_REPORT));
-
-				pBssCoexistIe = (BSS_2040_COEXIST_IE *)(&pCoexistInfo->BssCoexistIe);
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-					if (INFRA_ON(pAd))
-					{
-						StaPublicAction(pAd, pCoexistInfo);
-					}
-				}
-#endif // CONFIG_STA_SUPPORT //
-
-			}
-			break;
-	}
-
-#endif // DOT11N_DRAFT3 //
-
 }
 
 
@@ -694,7 +328,6 @@
 	return;
 }
 
-#ifdef DOT11_N_SUPPORT
 static VOID respond_ht_information_exchange_action(
 	IN PRTMP_ADAPTER pAd,
 	IN MLME_QUEUE_ELEM *Elem)
@@ -721,15 +354,12 @@
 
 	NdisZeroMemory(&HTINFOframe, sizeof(FRAME_HT_INFO));
 	// 2-1. Prepare ADDBA Response frame.
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		if (ADHOC_ON(pAd))
 			ActHeaderInit(pAd, &HTINFOframe.Hdr, pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
 		else
 			ActHeaderInit(pAd, &HTINFOframe.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAddr);
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	HTINFOframe.Category = CATEGORY_HT;
 	HTINFOframe.Action = HT_INFO_EXCHANGE;
@@ -745,51 +375,6 @@
 	MlmeFreeMemory(pAd, pOutBuffer);
 }
 
-
-#ifdef DOT11N_DRAFT3
-VOID SendNotifyBWActionFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR  Wcid,
-	IN UCHAR apidx)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS 	NStatus;
-	FRAME_ACTION_HDR	Frame;
-	ULONG			FrameLen;
-	PUCHAR			pAddr1;
-
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("ACT - SendNotifyBWAction() allocate memory failed \n"));
-		return;
-	}
-
-	if (Wcid == MCAST_WCID)
-		pAddr1 = &BROADCAST_ADDR[0];
-	else
-		pAddr1 = pAd->MacTab.Content[Wcid].Addr;
-	ActHeaderInit(pAd, &Frame.Hdr, pAddr1, pAd->ApCfg.MBSSID[apidx].Bssid, pAd->ApCfg.MBSSID[apidx].Bssid);
-
-	Frame.Category = CATEGORY_HT;
-	Frame.Action = NOTIFY_BW_ACTION;
-
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-				  sizeof(FRAME_ACTION_HDR),	  &Frame,
-				  END_OF_ARGS);
-
-	*(pOutBuffer + FrameLen) = pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth;
-	FrameLen++;
-
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	DBGPRINT(RT_DEBUG_TRACE,("ACT - SendNotifyBWAction(NotifyBW= %d)!\n", pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth));
-
-}
-#endif // DOT11N_DRAFT3 //
-
-
 VOID PeerHTAction(
 	IN PRTMP_ADAPTER pAd,
 	IN MLME_QUEUE_ELEM *Elem)
@@ -803,7 +388,7 @@
 	{
 		case NOTIFY_BW_ACTION:
 			DBGPRINT(RT_DEBUG_TRACE,("ACTION - HT Notify Channel bandwidth action----> \n"));
-#ifdef CONFIG_STA_SUPPORT
+
 			if(pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE)
 			{
 				// Note, this is to patch DIR-1353 AP. When the AP set to Wep, it will use legacy mode. But AP still keeps
@@ -813,7 +398,6 @@
 								Elem->Msg[LENGTH_802_11+2] ));
 				break;
 			}
-#endif // CONFIG_STA_SUPPORT //
 
 			if (Elem->Msg[LENGTH_802_11+2] == 0)	// 7.4.8.2. if value is 1, keep the same as supported channel bandwidth.
 				pAd->MacTab.Content[Elem->Wcid].HTPhyMode.field.BW = 0;
@@ -881,11 +465,6 @@
 	INT			i, total;
 	UCHAR			TID;
 
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
 	total = pAd->MacTab.Size * NUM_OF_TID;
 
 	for (i = 1; ((i <MAX_LEN_OF_BA_ORI_TABLE) && (total > 0)) ; i++)
@@ -938,10 +517,8 @@
 			}
 
 			Sequence = pEntry->TxSeq[TID];
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				BarHeaderInit(pAd, &FrameBar, pEntry->Addr, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
+
+			BarHeaderInit(pAd, &FrameBar, pEntry->Addr, pAd->CurrentAddress);
 
 			FrameBar.StartingSeq.field.FragNum = 0; // make sure sequence not clear in DEL function.
 			FrameBar.StartingSeq.field.StartSeq = Sequence; // make sure sequence not clear in DEL funciton.
@@ -950,15 +527,20 @@
 			MakeOutgoingFrame(pOutBuffer,				&FrameLen,
 							  sizeof(FRAME_BAR),	  &FrameBar,
 							  END_OF_ARGS);
+
 			if (1)	// Now we always send BAR.
 			{
+#ifndef RT30xx
 				MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
+#endif
+#ifdef RT30xx
+				MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
+#endif
 			}
 			MlmeFreeMemory(pAd, pOutBuffer);
 		}
 	}
 }
-#endif // DOT11_N_SUPPORT //
 
 VOID ActHeaderInit(
     IN	PRTMP_ADAPTER	pAd,
diff --git a/drivers/staging/rt2860/common/action.h b/drivers/staging/rt2860/common/action.h
index ce3877d..cfc2a5f 100644
--- a/drivers/staging/rt2860/common/action.h
+++ b/drivers/staging/rt2860/common/action.h
@@ -41,17 +41,10 @@
 
 typedef struct PACKED __HT_INFO_OCTET
 {
-#ifdef RT_BIG_ENDIAN
-	UCHAR	Reserved:5;
-	UCHAR 	STA_Channel_Width:1;
-	UCHAR	Forty_MHz_Intolerant:1;
-	UCHAR	Request:1;
-#else
 	UCHAR	Request:1;
 	UCHAR	Forty_MHz_Intolerant:1;
 	UCHAR 	STA_Channel_Width:1;
 	UCHAR	Reserved:5;
-#endif
 } HT_INFORMATION_OCTET;
 
 
diff --git a/drivers/staging/rt2860/common/ba_action.c b/drivers/staging/rt2860/common/ba_action.c
index 591d1e2..b95a341 100644
--- a/drivers/staging/rt2860/common/ba_action.c
+++ b/drivers/staging/rt2860/common/ba_action.c
@@ -25,8 +25,6 @@
  *************************************************************************
  */
 
-#ifdef DOT11_N_SUPPORT
-
 #include "../rt_config.h"
 
 
@@ -132,10 +130,7 @@
 		// pass this 802.3 packet to upper layer or forward this packet to WM directly
 		//
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pPacket, RTMP_GET_PACKET_IF(pPacket));
-#endif // CONFIG_STA_SUPPORT //
+		ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pPacket, RTMP_GET_PACKET_IF(pPacket));
 	}
 }
 
@@ -449,9 +444,6 @@
 		&& (pBAEntry->list.qlen > 0)
 	   )
 		{
-//		printk("timeout[%d] (%lx-%lx = %d > %d): %x, ", pBAEntry->list.qlen, Now32, (pBAEntry->LastIndSeqAtTimer),
-//			   (int)((long) Now32 - (long)(pBAEntry->LastIndSeqAtTimer)), REORDERING_PACKET_TIMEOUT,
-//			   pBAEntry->LastIndSeq);
     		//
 		// force LastIndSeq to shift to LastIndSeq+1
     		//
@@ -468,22 +460,7 @@
     			pBAEntry->LastIndSeq = Sequence;
     		}
 
-		//printk("%x, flush one!\n", pBAEntry->LastIndSeq);
-
 	}
-#if 0
-	else if (
-			 (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(MAX_REORDERING_PACKET_TIMEOUT))) &&
-			  (pBAEntry->list.qlen > 1))
-			)
-		{
-		DBGPRINT(RT_DEBUG_TRACE,("timeout[%d] (%lx-%lx = %d > %d): %x\n ", pBAEntry->list.qlen, Now32, (pBAEntry->LastIndSeqAtTimer),
-			   (int)((long) Now32 - (long)(pBAEntry->LastIndSeqAtTimer)), MAX_REORDERING_PACKET_TIMEOUT,
-			   pBAEntry->LastIndSeq));
-		ba_refresh_reordering_mpdus(pAd, pBAEntry);
-			pBAEntry->LastIndSeqAtTimer = Now32;
-				}
-#endif
 }
 
 
@@ -554,6 +531,13 @@
 	pBAEntry->TimeOutValue = TimeOut;
 	pBAEntry->pAdapter = pAd;
 
+#ifdef RT30xx
+	DBGPRINT(RT_DEBUG_TRACE,("Send AddBA to %02x:%02x:%02x:%02x:%02x:%02x Tid:%d isForced:%d Wcid:%d\n"
+		,pEntry->Addr[0],pEntry->Addr[1],pEntry->Addr[2]
+		,pEntry->Addr[3],pEntry->Addr[4],pEntry->Addr[5]
+		,TID,isForced,pEntry->Aid));
+#endif
+
 	if (!(pEntry->TXBAbitmap & (1<<TID)))
 	{
 		RTMPInitTimer(pAd, &pBAEntry->ORIBATimer, GET_TIMER_FUNCTION(BAOriSessionSetupTimeout), pBAEntry, FALSE);
@@ -610,11 +594,7 @@
 			return;
 		}
 
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			BarHeaderInit(pAd, &FrameBar, pAd->MacTab.Content[pBAEntry->Wcid].Addr, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
+		BarHeaderInit(pAd, &FrameBar, pAd->MacTab.Content[pBAEntry->Wcid].Addr, pAd->CurrentAddress);
 
 		FrameBar.StartingSeq.field.FragNum = 0;	// make sure sequence not clear in DEL function.
 		FrameBar.StartingSeq.field.StartSeq = pBAEntry->Sequence; // make sure sequence not clear in DEL funciton.
@@ -701,10 +681,6 @@
 			RTMPInitTimer(pAd, &pBAEntry->RECBATimer, GET_TIMER_FUNCTION(BARecSessionIdleTimeout), pBAEntry, TRUE);
 		}
 
-#if 0	// for debugging
-		RTMPSetTimer(&pBAEntry->RECBATimer, REC_BA_SESSION_IDLE_TIMEOUT);
-#endif
-
 		// Set Bitmap flag.
 		pEntry->RXBAbitmap |= (1<<TID);
 		pEntry->BARecWcidArray[TID] = Idx;
@@ -1083,20 +1059,9 @@
 
 	pAd = pBAEntry->pAdapter;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Do nothing if monitor mode is on
-		if (MONITOR_ON(pAd))
-			return;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef RALINK_ATE
-	// Nothing to do in ATE mode.
-	if (ATE_ON(pAd))
+	// Do nothing if monitor mode is on
+	if (MONITOR_ON(pAd))
 		return;
-#endif // RALINK_ATE //
 
 	pEntry = &pAd->MacTab.Content[pBAEntry->Wcid];
 
@@ -1113,8 +1078,16 @@
 		AddbaReq.Token = pBAEntry->Token;
 		MlmeEnqueue(pAd, ACTION_STATE_MACHINE, MT2_MLME_ADD_BA_CATE, sizeof(MLME_ADDBA_REQ_STRUCT), (PVOID)&AddbaReq);
 		RT28XX_MLME_HANDLER(pAd);
+#ifndef RT30xx
 		DBGPRINT(RT_DEBUG_TRACE,("BA Ori Session Timeout(%d) : Send ADD BA again\n", pBAEntry->Token));
-
+#endif
+#ifdef RT30xx
+		DBGPRINT(RT_DEBUG_TRACE,("BA Ori Session Timeout(%d) to %02x:%02x:%02x:%02x:%02x:%02x Tid:%d Wcid:%d\n"
+		,pBAEntry->Token
+		,pEntry->Addr[0],pEntry->Addr[1],pEntry->Addr[2]
+		,pEntry->Addr[3],pEntry->Addr[4],pEntry->Addr[5]
+		,pBAEntry->TID,pEntry->Aid));
+#endif
 		pBAEntry->Token++;
 		RTMPSetTimer(&pBAEntry->ORIBATimer, ORI_BA_SESSION_TIMEOUT);
 	}
@@ -1229,21 +1202,15 @@
 	}
 
 	NdisZeroMemory(&ADDframe, sizeof(FRAME_ADDBA_RSP));
+
 	// 2-1. Prepare ADDBA Response frame.
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		if (ADHOC_ON(pAd))
 			ActHeaderInit(pAd, &ADDframe.Hdr, pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
 		else
-#ifdef QOS_DLS_SUPPORT
-		if (pAd->MacTab.Content[Elem->Wcid].ValidAsDls)
-			ActHeaderInit(pAd, &ADDframe.Hdr, pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-		else
-#endif // QOS_DLS_SUPPORT //
 			ActHeaderInit(pAd, &ADDframe.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAddr);
 	}
-#endif // CONFIG_STA_SUPPORT //
+
 	ADDframe.Category = CATEGORY_BA;
 	ADDframe.Action = ADDBA_RESP;
 	ADDframe.Token = pAddreqFrame->Token;
@@ -1310,9 +1277,7 @@
 		}
 		// Rcv Decline StatusCode
 		if ((pFrame->StatusCode == 37)
-#ifdef CONFIG_STA_SUPPORT
             || ((pAd->OpMode == OPMODE_STA) && STA_TGN_WIFI_ON(pAd) && (pFrame->StatusCode != 0))
-#endif // CONFIG_STA_SUPPORT //
             )
 		{
 			pAd->MacTab.Content[Elem->Wcid].BADeclineBitmap |= 1<<pFrame->BaParm.TID;
@@ -1426,6 +1391,10 @@
 	//ULONG           Idx;
 	FRAME_PSMP_ACTION   Frame;
 	ULONG           FrameLen;
+#ifdef RT30xx
+	UCHAR			bbpdata=0;
+	UINT32			macdata;
+#endif // RT30xx //
 
 	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);	 //Get an unused nonpaged memory
 	if (NStatus != NDIS_STATUS_SUCCESS)
@@ -1433,22 +1402,62 @@
 		DBGPRINT(RT_DEBUG_ERROR,("BA - MlmeADDBAAction() allocate memory failed \n"));
 		return;
 	}
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		ActHeaderInit(pAd, &Frame.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->MacTab.Content[Wcid].Addr);
-#endif // CONFIG_STA_SUPPORT //
+
+	ActHeaderInit(pAd, &Frame.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->MacTab.Content[Wcid].Addr);
 
 	Frame.Category = CATEGORY_HT;
 	Frame.Action = SMPS_ACTION;
 	switch (Psmp)
 	{
 		case MMPS_ENABLE:
+#ifdef RT30xx
+			if (IS_RT3090(pAd))
+			{
+				// disable MMPS BBP control register
+				RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &bbpdata);
+				bbpdata &= ~(0x04);	//bit 2
+				RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, bbpdata);
+
+				// disable MMPS MAC control register
+				RTMP_IO_READ32(pAd, 0x1210, &macdata);
+				macdata &= ~(0x09);	//bit 0, 3
+				RTMP_IO_WRITE32(pAd, 0x1210, macdata);
+			}
+#endif // RT30xx //
 			Frame.Psmp = 0;
 			break;
 		case MMPS_DYNAMIC:
+#ifdef RT30xx
+			if (IS_RT3090(pAd))
+			{
+				// enable MMPS BBP control register
+				RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &bbpdata);
+				bbpdata |= 0x04;	//bit 2
+				RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, bbpdata);
+
+				// enable MMPS MAC control register
+				RTMP_IO_READ32(pAd, 0x1210, &macdata);
+				macdata |= 0x09;	//bit 0, 3
+				RTMP_IO_WRITE32(pAd, 0x1210, macdata);
+			}
+#endif // RT30xx //
 			Frame.Psmp = 3;
 			break;
 		case MMPS_STATIC:
+#ifdef RT30xx
+			if (IS_RT3090(pAd))
+			{
+				// enable MMPS BBP control register
+				RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &bbpdata);
+				bbpdata |= 0x04;	//bit 2
+				RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, bbpdata);
+
+				// enable MMPS MAC control register
+				RTMP_IO_READ32(pAd, 0x1210, &macdata);
+				macdata |= 0x09;	//bit 0, 3
+				RTMP_IO_WRITE32(pAd, 0x1210, macdata);
+			}
+#endif // RT30xx //
 			Frame.Psmp = 1;
 			break;
 	}
@@ -1501,10 +1510,7 @@
 	// 		a. pointer pRxBlk->pData to payload
 	//      b. modify pRxBlk->DataSize
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
-#endif // CONFIG_STA_SUPPORT //
+	RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
 
 	ASSERT(pRxBlk->pRxPacket);
 	pRxPkt = RTPKT_TO_OSPKT(pRxBlk->pRxPacket);
@@ -1519,18 +1525,9 @@
 	//
 	if (!RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU))
 	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
 #ifdef LINUX
-			NdisMoveMemory(skb_push(pRxPkt, LENGTH_802_3), Header802_3, LENGTH_802_3);
+		NdisMoveMemory(skb_push(pRxPkt, LENGTH_802_3), Header802_3, LENGTH_802_3);
 #endif
-#ifdef UCOS
-			NdisMoveMemory(net_pkt_push(pRxPkt, LENGTH_802_3), Header802_3, LENGTH_802_3);
-#endif
-		}
-#endif // CONFIG_STA_SUPPORT //
 	}
 }
 
@@ -1598,13 +1595,9 @@
 	}
 	else
 	{
-#if 0
-		DBGPRINT(RT_DEBUG_ERROR,  ("!!! (%d:%d) Can't allocate reordering mpdu blk\n",
-								   blk_count, pBAEntry->list.qlen));
-#else
 		DBGPRINT(RT_DEBUG_ERROR,  ("!!! (%d) Can't allocate reordering mpdu blk\n",
 								   pBAEntry->list.qlen));
-#endif
+
 		/*
 		 * flush all pending reordering mpdus
 		 * and receving mpdu to upper layer
@@ -1652,29 +1645,11 @@
 
 	if (!RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU) &&  (pRxBlk->DataSize > MAX_RX_PKT_LEN))
 	{
-#if 0 // sample take off, no use
-		static int err_size;
-
-		err_size++;
-		if (err_size > 20) {
-			 printk("AMPDU DataSize = %d\n", pRxBlk->DataSize);
-			 hex_dump("802.11 Header", (UCHAR *)pRxBlk->pHeader, 24);
-			 hex_dump("Payload", pRxBlk->pData, 64);
-			 err_size = 0;
-		}
-#endif
 		// release packet
 		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
 		return;
 	}
 
-
-#if 0 // test
-	/* Rec BA Session had been torn down */
-	INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
-	return;
-#endif
-
 	if (Wcid < MAX_LEN_OF_MAC_TABLE)
 	{
 		Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID];
@@ -1769,10 +1744,6 @@
 	//
 	else
 	{
-#if 0
-		ba_refresh_reordering_mpdus(pAd, pBAEntry);
-		INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
-#else
 		LONG WinStartSeq, TmpSeq;
 
 
@@ -1794,9 +1765,5 @@
 		{
 			pBAEntry->LastIndSeq = TmpSeq;
 		}
-#endif
 	}
 }
-
-#endif // DOT11_N_SUPPORT //
-
diff --git a/drivers/staging/rt2860/common/cmm_data.c b/drivers/staging/rt2860/common/cmm_data.c
index b3f88f5..66eca20 100644
--- a/drivers/staging/rt2860/common/cmm_data.c
+++ b/drivers/staging/rt2860/common/cmm_data.c
@@ -105,7 +105,9 @@
 	PNDIS_PACKET	pPacket;
 	NDIS_STATUS  	Status = NDIS_STATUS_SUCCESS;
 	ULONG	 		FreeNum;
+#ifdef RT2860
 	unsigned long	IrqFlags = 0;
+#endif
 	UCHAR			IrqState;
 	UCHAR			rtmpHwHdr[TXINFO_SIZE + TXWI_SIZE]; //RTMP_HW_HDR_LEN];
 
@@ -117,9 +119,10 @@
 
 	IrqState = pAd->irq_disabled;
 
+#ifdef RT2860
 	if ((pAd->MACVersion == 0x28600100) && (!IrqState))
 		RTMP_IRQ_LOCK(&pAd->irq_lock, IrqFlags);
-
+#endif
 	do
 	{
 		// Reset is in progress, stop immediately
@@ -172,14 +175,15 @@
 
 	} while (FALSE);
 
+#ifdef RT2860
 	// 2860C use Tx Ring
 	if ((pAd->MACVersion == 0x28600100) && (!IrqState))
 		RTMP_IRQ_UNLOCK(&pAd->irq_lock, IrqFlags);
-
+#endif
 	return Status;
 }
 
-
+#ifdef RT2860
 NDIS_STATUS MiniportMMRequestUnlock(
 	IN	PRTMP_ADAPTER	pAd,
 	IN	UCHAR			QueIdx,
@@ -247,7 +251,115 @@
 
 	return Status;
 }
+#endif
+#ifdef RT30xx
+NDIS_STATUS MlmeDataHardTransmit(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR	QueIdx,
+	IN	PNDIS_PACKET	pPacket);
 
+#define MAX_DATAMM_RETRY	3
+/*
+	========================================================================
+
+	Routine Description:
+		API for MLME to transmit management frame to AP (BSS Mode)
+	or station (IBSS Mode)
+
+	Arguments:
+		pAd Pointer to our adapter
+		pData		Pointer to the outgoing 802.11 frame
+		Length		Size of outgoing management frame
+
+	Return Value:
+		NDIS_STATUS_FAILURE
+		NDIS_STATUS_PENDING
+		NDIS_STATUS_SUCCESS
+
+	IRQL = PASSIVE_LEVEL
+	IRQL = DISPATCH_LEVEL
+
+	Note:
+
+	========================================================================
+*/
+NDIS_STATUS MiniportDataMMRequest(
+							 IN  PRTMP_ADAPTER   pAd,
+							 IN  UCHAR           QueIdx,
+							 IN  PUCHAR          pData,
+							 IN  UINT            Length)
+{
+	PNDIS_PACKET    pPacket;
+	NDIS_STATUS  Status = NDIS_STATUS_SUCCESS;
+	ULONG    FreeNum;
+	int 	retry = 0;
+	UCHAR           IrqState;
+	UCHAR			rtmpHwHdr[TXINFO_SIZE + TXWI_SIZE]; //RTMP_HW_HDR_LEN];
+
+	ASSERT(Length <= MGMT_DMA_BUFFER_SIZE);
+
+	// 2860C use Tx Ring
+	IrqState = pAd->irq_disabled;
+
+	do
+	{
+		// Reset is in progress, stop immediately
+		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS) ||
+			 RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST)||
+			!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP))
+		{
+			Status = NDIS_STATUS_FAILURE;
+			break;
+		}
+
+		// Check Free priority queue
+		// Since we use PBF Queue2 for management frame.  Its corresponding DMA ring should be using TxRing.
+
+		// 2860C use Tx Ring
+
+		// free Tx(QueIdx) resources
+		FreeNum = GET_TXRING_FREENO(pAd, QueIdx);
+
+		if ((FreeNum > 0))
+		{
+			// We need to reserve space for rtmp hardware header. i.e., TxWI for RT2860 and TxInfo+TxWI for RT2870
+			NdisZeroMemory(&rtmpHwHdr, (TXINFO_SIZE + TXWI_SIZE));
+			Status = RTMPAllocateNdisPacket(pAd, &pPacket, (PUCHAR)&rtmpHwHdr, (TXINFO_SIZE + TXWI_SIZE), pData, Length);
+			if (Status != NDIS_STATUS_SUCCESS)
+			{
+				DBGPRINT(RT_DEBUG_WARN, ("MiniportMMRequest (error:: can't allocate NDIS PACKET)\n"));
+				break;
+			}
+
+			//pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_CCK;
+			//pAd->CommonCfg.MlmeRate = RATE_2;
+
+
+			Status = MlmeDataHardTransmit(pAd, QueIdx, pPacket);
+			if (Status != NDIS_STATUS_SUCCESS)
+				RTMPFreeNdisPacket(pAd, pPacket);
+			retry = MAX_DATAMM_RETRY;
+		}
+		else
+		{
+			retry ++;
+
+			printk("retry %d\n", retry);
+			pAd->RalinkCounters.MgmtRingFullCount++;
+
+			if (retry >= MAX_DATAMM_RETRY)
+			{
+				DBGPRINT(RT_DEBUG_ERROR, ("Qidx(%d), not enough space in DataRing, MgmtRingFullCount=%ld!\n",
+											QueIdx, pAd->RalinkCounters.MgmtRingFullCount));
+			}
+		}
+
+	} while (retry < MAX_DATAMM_RETRY);
+
+
+	return Status;
+}
+#endif /* RT30xx */
 
 /*
 	========================================================================
@@ -283,14 +395,16 @@
 		return NDIS_STATUS_FAILURE;
 	}
 
+#ifdef RT2860
 	if ( pAd->MACVersion == 0x28600100 )
 		return MlmeHardTransmitTxRing(pAd,QueIdx,pPacket);
 	else
+#endif
 		return MlmeHardTransmitMgmtRing(pAd,QueIdx,pPacket);
 
 }
 
-
+#ifdef RT2860
 NDIS_STATUS MlmeHardTransmitTxRing(
 	IN	PRTMP_ADAPTER	pAd,
 	IN	UCHAR	QueIdx,
@@ -300,10 +414,6 @@
 	PUCHAR			pSrcBufVA;
 	UINT			SrcBufLen;
 	PTXD_STRUC		pTxD;
-#ifdef RT_BIG_ENDIAN
-    PTXD_STRUC      pDestTxD;
-    TXD_STRUC       TxD;
-#endif
 	PHEADER_802_11	pHeader_802_11;
 	BOOLEAN 		bAckRequired, bInsertTimestamp;
 	ULONG			SrcBufPA;
@@ -335,14 +445,7 @@
 
 	SwIdx = pAd->TxRing[QueIdx].TxCpuIdx;
 
-#ifndef RT_BIG_ENDIAN
 	pTxD  = (PTXD_STRUC) pAd->TxRing[QueIdx].Cell[SwIdx].AllocVa;
-#else
-    pDestTxD  = (PTXD_STRUC)pAd->TxRing[QueIdx].Cell[SwIdx].AllocVa;
-    TxD = *pDestTxD;
-    pTxD = &TxD;
-    RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#endif
 
 	if (pAd->TxRing[QueIdx].Cell[SwIdx].pNdisPacket)
 	{
@@ -350,15 +453,10 @@
 		return NDIS_STATUS_FAILURE;
 	}
 
+	// outgoing frame always wakeup PHY to prevent frame lost
+	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
+		AsicForceWakeup(pAd, FROM_TX);
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// outgoing frame always wakeup PHY to prevent frame lost
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-			AsicForceWakeup(pAd, FROM_TX);
-	}
-#endif // CONFIG_STA_SUPPORT //
 	pFirstTxWI	=(PTXWI_STRUC)pSrcBufVA;
 
 	pHeader_802_11 = (PHEADER_802_11) (pSrcBufVA + TXWI_SIZE);
@@ -388,7 +486,7 @@
 	//
 	//
 	// In WMM-UAPSD, mlme frame should be set psm as power saving but probe request frame
-#ifdef CONFIG_STA_SUPPORT
+
     // Data-Null packets alse pass through MMRequest in RT2860, however, we hope control the psm bit to pass APSD
 	if (pHeader_802_11->FC.Type != BTYPE_DATA)
     {
@@ -401,7 +499,6 @@
     		pHeader_802_11->FC.PwrMgmt = pAd->CommonCfg.bAPSDForcePowerSave;
     	}
     }
-#endif // CONFIG_STA_SUPPORT //
 
 	bInsertTimestamp = FALSE;
 	if (pHeader_802_11->FC.Type == BTYPE_CNTL) // must be PS-POLL
@@ -438,9 +535,6 @@
 		return (NDIS_STATUS_FAILURE);
 	}
 
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pHeader_802_11, DIR_WRITE, FALSE);
-#endif
 	//
 	// fill scatter-and-gather buffer list into TXD. Internally created NDIS PACKET
 	// should always has only one ohysical buffer, and the whole frame size equals
@@ -470,9 +564,7 @@
 
 	pAd->TxRing[QueIdx].Cell[SwIdx].pNdisPacket = pPacket;
 	pAd->TxRing[QueIdx].Cell[SwIdx].pNextNdisPacket = NULL;
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange((PUCHAR)pFirstTxWI, TYPE_TXWI);
-#endif
+
 	SrcBufPA = PCI_MAP_SINGLE(pAd, pSrcBufVA, SrcBufLen, 0, PCI_DMA_TODEVICE);
 
 
@@ -484,11 +576,6 @@
 	pTxD->SDPtr0 = SrcBufPA;
 	pTxD->DMADONE = 0;
 
-#ifdef RT_BIG_ENDIAN
-    RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-    WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif
-
 	pAd->RalinkCounters.KickTxCount++;
 	pAd->RalinkCounters.OneSecTxDoneCount++;
 
@@ -499,7 +586,25 @@
 
 	return NDIS_STATUS_SUCCESS;
 }
+#endif /* RT2860 */
 
+#ifdef RT30xx
+NDIS_STATUS MlmeDataHardTransmit(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR	QueIdx,
+	IN	PNDIS_PACKET	pPacket)
+{
+	if ((pAd->CommonCfg.RadarDetect.RDMode != RD_NORMAL_MODE)
+		)
+	{
+		return NDIS_STATUS_FAILURE;
+	}
+
+#ifdef RT2870
+	return MlmeHardTransmitMgmtRing(pAd,QueIdx,pPacket);
+#endif // RT2870 //
+}
+#endif /* RT30xx */
 
 NDIS_STATUS MlmeHardTransmitMgmtRing(
 	IN	PRTMP_ADAPTER	pAd,
@@ -525,14 +630,14 @@
 		return NDIS_STATUS_FAILURE;
 	}
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// outgoing frame always wakeup PHY to prevent frame lost
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-			AsicForceWakeup(pAd, FROM_TX);
-	}
-#endif // CONFIG_STA_SUPPORT //
+	// outgoing frame always wakeup PHY to prevent frame lost
+	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
+#ifdef RT2860
+		AsicForceWakeup(pAd, FROM_TX);
+#endif
+#ifdef RT2870
+		AsicForceWakeup(pAd, TRUE);
+#endif
 
 	pFirstTxWI = (PTXWI_STRUC)(pSrcBufVA +  TXINFO_SIZE);
 	pHeader_802_11 = (PHEADER_802_11) (pSrcBufVA + TXINFO_SIZE + TXWI_SIZE); //TXWI_SIZE);
@@ -556,14 +661,10 @@
 		pMacEntry = MacTableLookup(pAd, pHeader_802_11->Addr1);
 	}
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		// Fixed W52 with Activity scan issue in ABG_MIXED and ABGN_MIXED mode.
 		if (pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED
-#ifdef DOT11_N_SUPPORT
 			|| pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED
-#endif // DOT11_N_SUPPORT //
 		)
 		{
 			if (pAd->LatchRfRegs.Channel > 14)
@@ -572,7 +673,6 @@
 				pAd->CommonCfg.MlmeTransmit.field.MODE = 0;
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	//
 	// Should not be hard code to set PwrMgmt to 0 (PWR_ACTIVE)
@@ -582,7 +682,7 @@
 	// pHeader_802_11->FC.PwrMgmt = 0; // (pAd->StaCfg.Psm == PWR_SAVE);
 	//
 	// In WMM-UAPSD, mlme frame should be set psm as power saving but probe request frame
-#ifdef CONFIG_STA_SUPPORT
+
     // Data-Null packets alse pass through MMRequest in RT2860, however, we hope control the psm bit to pass APSD
 	if ((pHeader_802_11->FC.Type != BTYPE_DATA) && (pHeader_802_11->FC.Type != BTYPE_CNTL))
 	{
@@ -592,18 +692,15 @@
 		else
 			pHeader_802_11->FC.PwrMgmt = PWR_ACTIVE;
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	bInsertTimestamp = FALSE;
 	if (pHeader_802_11->FC.Type == BTYPE_CNTL) // must be PS-POLL
 	{
-#ifdef CONFIG_STA_SUPPORT
 		//Set PM bit in ps-poll, to fix WLK 1.2  PowerSaveMode_ext failure issue.
 		if ((pAd->OpMode == OPMODE_STA) && (pHeader_802_11->FC.SubType == SUBTYPE_PS_POLL))
 		{
 			pHeader_802_11->FC.PwrMgmt = PWR_SAVE;
 		}
-#endif // CONFIG_STA_SUPPORT //
 		bAckRequired = FALSE;
 	}
 	else // BTYPE_MGMT or BTYPE_DATA(must be NULL frame)
@@ -639,10 +736,6 @@
 		return (NDIS_STATUS_FAILURE);
 	}
 
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pHeader_802_11, DIR_WRITE, FALSE);
-#endif
-
 	//
 	// fill scatter-and-gather buffer list into TXD. Internally created NDIS PACKET
 	// should always has only one ohysical buffer, and the whole frame size equals
@@ -669,10 +762,6 @@
 					IFS_BACKOFF, FALSE, &pMacEntry->MaxHTPhyMode);
 	}
 
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange((PUCHAR)pFirstTxWI, TYPE_TXWI);
-#endif
-
 	// Now do hardware-depened kick out.
 	HAL_KickOutMgmtTx(pAd, QueIdx, pPacket, pSrcBufVA, SrcBufLen);
 
@@ -752,9 +841,7 @@
 	UCHAR			TxFrameType = TX_UNKOWN_FRAME;
 	UCHAR			Wcid;
 	MAC_TABLE_ENTRY	*pMacEntry = NULL;
-#ifdef DOT11_N_SUPPORT
 	BOOLEAN			bHTRate = FALSE;
-#endif // DOT11_N_SUPPORT //
 
 	Wcid = RTMP_GET_PACKET_WCID(pPacket);
 	if (Wcid == MCAST_WCID)
@@ -768,7 +855,6 @@
 	{	// It's a specific packet need to force low rate, i.e., bDHCPFrame, bEAPOLFrame, bWAIFrame
 		TxFrameType = TX_LEGACY_FRAME;
 	}
-#ifdef DOT11_N_SUPPORT
 	else if (IS_HT_RATE(pMacEntry))
 	{	// it's a 11n capable packet
 
@@ -788,7 +874,6 @@
 		else
 			TxFrameType = TX_LEGACY_FRAME;
 	}
-#endif // DOT11_N_SUPPORT //
 	else
 	{	// it's a legacy b/g packet.
 		if ((CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_AGGREGATION_CAPABLE) && pAd->CommonCfg.bAggregationCapable) &&
@@ -874,16 +959,15 @@
 			TX_BLK_SET_FLAG(pTxBlk, fTX_bAckRequired);
 
 		{
-
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			{
-
-				// If support WMM, enable it.
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED))
-					TX_BLK_SET_FLAG(pTxBlk, fTX_bWMM);
-			}
-#endif // CONFIG_STA_SUPPORT //
+			// If support WMM, enable it.
+#ifdef RT2860
+			if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED))
+#endif
+#ifdef RT2870
+			if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) &&
+				CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_WMM_CAPABLE))
+#endif
+				TX_BLK_SET_FLAG(pTxBlk, fTX_bWMM);
 		}
 
 		if (pTxBlk->TxFrameType == TX_LEGACY_FRAME)
@@ -892,7 +976,7 @@
                 ((pAd->OpMode == OPMODE_AP) && (pMacEntry->MaxHTPhyMode.field.MODE == MODE_CCK) && (pMacEntry->MaxHTPhyMode.field.MCS == RATE_1)))
 			{	// Specific packet, i.e., bDHCPFrame, bEAPOLFrame, bWAIFrame, need force low rate.
 				pTxBlk->pTransmit = &pAd->MacTab.Content[MCAST_WCID].HTPhyMode;
-#ifdef DOT11_N_SUPPORT
+
 				// Modify the WMM bit for ICV issue. If we have a packet with EOSP field need to set as 1, how to handle it???
 				if (IS_HT_STA(pTxBlk->pMacEntry) &&
 					(CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_RALINK_CHIPSET)) &&
@@ -901,16 +985,13 @@
 					TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bWMM);
 					TX_BLK_SET_FLAG(pTxBlk, fTX_bForceNonQoS);
 				}
-#endif // DOT11_N_SUPPORT //
 			}
 
-#ifdef DOT11_N_SUPPORT
 			if ( (IS_HT_RATE(pMacEntry) == FALSE) &&
 				(CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_PIGGYBACK_CAPABLE)))
 			{	// Currently piggy-back only support when peer is operate in b/g mode.
 				TX_BLK_SET_FLAG(pTxBlk, fTX_bPiggyBack);
 			}
-#endif // DOT11_N_SUPPORT //
 
 			if (RTMP_GET_PACKET_MOREDATA(pPacket))
 			{
@@ -932,6 +1013,11 @@
 	}
 
 	return TRUE;
+
+#ifdef RT30xx
+FillTxBlkErr:
+	return FALSE;
+#endif
 }
 
 
@@ -963,13 +1049,10 @@
 		return FALSE;
 	}
 
-#ifdef CONFIG_STA_SUPPORT
 	if ((INFRA_ON(pAd)) && (pAd->OpMode == OPMODE_STA)) // must be unicast to AP
 		return TRUE;
 	else
-#endif // CONFIG_STA_SUPPORT //
 		return FALSE;
-
 }
 
 
@@ -1022,6 +1105,7 @@
 	if (QIdx == NUM_OF_TX_RING)
 	{
 		sQIdx = 0;
+//PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
 		eQIdx = 3;	// 4 ACs, start from 0.
 	}
 	else
@@ -1064,7 +1148,7 @@
 				DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
 				break;
 			}
-
+#ifdef RT2860
 			FreeNumber[QueIdx] = GET_TXRING_FREENO(pAd, QueIdx);
 
 #ifdef DBG_DIAGNOSE
@@ -1089,7 +1173,7 @@
 				RTMPFreeTXDUponTxDmaDone(pAd, QueIdx);
 				FreeNumber[QueIdx] = GET_TXRING_FREENO(pAd, QueIdx);
 			}
-
+#endif /* RT2860 */
 			// probe the Queue Head
 			pQueue = &pAd->TxSwQueue[QueIdx];
 			if ((pEntry = pQueue->Head) == NULL)
@@ -1158,32 +1242,29 @@
 					pTxBlk->TxFrameType = TX_LEGACY_FRAME;
 			}
 
+#ifdef RT2870
+			DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
+#endif // RT2870 //
 
 			Count += pTxBlk->TxPacketList.Number;
 
-				// Do HardTransmit now.
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				Status = STAHardTransmit(pAd, pTxBlk, QueIdx);
-#endif // CONFIG_STA_SUPPORT //
+			// Do HardTransmit now.
+			Status = STAHardTransmit(pAd, pTxBlk, QueIdx);
 
+#ifdef RT2860
 			DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
 			// static rate also need NICUpdateFifoStaCounters() function.
 			//if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED))
 				NICUpdateFifoStaCounters(pAd);
+#endif
 		}
 
 		RT28XX_STOP_DEQUEUE(pAd, QueIdx, IrqFlags);
 
-
-#ifdef BLOCK_NET_IF
-		if ((pAd->blockQueueTab[QueIdx].SwTxQueueBlockFlag == TRUE)
-			&& (pAd->TxSwQueue[QueIdx].Number < 1))
-		{
-			releaseNetIf(&pAd->blockQueueTab[QueIdx]);
-		}
-#endif // BLOCK_NET_IF //
-
+#ifdef RT2870
+		if (!hasTxDesc)
+			RTUSBKickBulkOut(pAd);
+#endif // RT2870 //
 	}
 
 }
@@ -1318,7 +1399,6 @@
 
 	pTxWI->NSEQ = NSeq;
 	// John tune the performace with Intel Client in 20 MHz performance
-#ifdef DOT11_N_SUPPORT
 	BASize = pAd->CommonCfg.TxBASize;
 
 	if( BASize >7 )
@@ -1326,7 +1406,6 @@
 	pTxWI->BAWinSize = BASize;
 	pTxWI->ShortGI = pTransmit->field.ShortGI;
 	pTxWI->STBC = pTransmit->field.STBC;
-#endif // DOT11_N_SUPPORT //
 
 	pTxWI->WirelessCliID = WCID;
 	pTxWI->MPDUtotalByteCount = Length;
@@ -1334,16 +1413,11 @@
 
 	// If CCK or OFDM, BW must be 20
 	pTxWI->BW = (pTransmit->field.MODE <= MODE_OFDM) ? (BW_20) : (pTransmit->field.BW);
-#ifdef DOT11N_DRAFT3
-	if (pTxWI->BW)
-		pTxWI->BW = (pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth == 0) ? (BW_20) : (pTransmit->field.BW);
-#endif // DOT11N_DRAFT3 //
 
 	pTxWI->MCS = pTransmit->field.MCS;
 	pTxWI->PHYMODE = pTransmit->field.MODE;
 	pTxWI->CFACK = CfAck;
 
-#ifdef DOT11_N_SUPPORT
 	if (pMac)
 	{
 		if (pAd->CommonCfg.bMIMOPSEnable)
@@ -1373,7 +1447,6 @@
 			pTxWI->MpduDensity = pMac->MpduDensity;
 		}
 	}
-#endif // DOT11_N_SUPPORT //
 
 	pTxWI->PacketId = pTxWI->MCS;
 	NdisMoveMemory(pOutTxWI, &TxWI, sizeof(TXWI_STRUC));
@@ -1387,10 +1460,7 @@
 {
 	HTTRANSMIT_SETTING	*pTransmit;
 	PMAC_TABLE_ENTRY	pMacEntry;
-#ifdef DOT11_N_SUPPORT
 	UCHAR				BASize;
-#endif // DOT11_N_SUPPORT //
-
 
 	ASSERT(pTxWI);
 
@@ -1409,15 +1479,6 @@
 	pTxWI->ACK		= TX_BLK_TEST_FLAG(pTxBlk, fTX_bAckRequired);
 	pTxWI->txop		= pTxBlk->FrameGap;
 
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-	if (pMacEntry &&
-		(pAd->StaCfg.BssType == BSS_INFRA) &&
-		(pMacEntry->ValidAsDls == TRUE))
-		pTxWI->WirelessCliID = BSSID_WCID;
-	else
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
 		pTxWI->WirelessCliID		= pTxBlk->Wcid;
 
 	pTxWI->MPDUtotalByteCount	= pTxBlk->MpduHeaderLen + pTxBlk->SrcBufLen;
@@ -1425,11 +1486,6 @@
 
 	// If CCK or OFDM, BW must be 20
 	pTxWI->BW = (pTransmit->field.MODE <= MODE_OFDM) ? (BW_20) : (pTransmit->field.BW);
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	if (pTxWI->BW)
-		pTxWI->BW = (pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth == 0) ? (BW_20) : (pTransmit->field.BW);
-#endif // DOT11N_DRAFT3 //
 	pTxWI->AMPDU	= ((pTxBlk->TxFrameType == TX_AMPDU_FRAME) ? TRUE : FALSE);
 
 	// John tune the performace with Intel Client in 20 MHz performance
@@ -1446,12 +1502,10 @@
 	pTxWI->BAWinSize = BASize;
 	pTxWI->ShortGI = pTransmit->field.ShortGI;
 	pTxWI->STBC = pTransmit->field.STBC;
-#endif // DOT11_N_SUPPORT //
 
 	pTxWI->MCS = pTransmit->field.MCS;
 	pTxWI->PHYMODE = pTransmit->field.MODE;
 
-#ifdef DOT11_N_SUPPORT
 	if (pMacEntry)
 	{
 		if ((pMacEntry->MmpsMode == MMPS_DYNAMIC) && (pTransmit->field.MCS > 7))
@@ -1478,7 +1532,6 @@
 			pTxWI->MpduDensity = pMacEntry->MpduDensity;
 		}
 	}
-#endif // DOT11_N_SUPPORT //
 
 #ifdef DBG_DIAGNOSE
 		if (pTxBlk->QueIdx== 0)
@@ -1523,15 +1576,9 @@
 		pTxWI->PacketId = pTransmit->field.MCS;
 	}
 
-#ifdef DOT11_N_SUPPORT
 	pTxWI->AMPDU = ((pMacEntry->NoBADataCountDown == 0) ? TRUE: FALSE);
 	pTxWI->MIMOps = 0;
 
-#ifdef DOT11N_DRAFT3
-	if (pTxWI->BW)
-		pTxWI->BW = (pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth == 0) ? (BW_20) : (pTransmit->field.BW);
-#endif // DOT11N_DRAFT3 //
-
 	if (pAd->CommonCfg.bMIMOPSEnable)
 	{
 		// MIMO Power Save Mode
@@ -1550,7 +1597,6 @@
 			}
 		}
 	}
-#endif // DOT11_N_SUPPORT //
 
 #ifdef DBG_DIAGNOSE
 	if (pTxBlk->QueIdx== 0)
@@ -1665,12 +1711,10 @@
 
 	if (pMacEntry != NULL && CLIENT_STATUS_TEST_FLAG(pMacEntry, AFlags))
 	{
-#ifdef DOT11_N_SUPPORT
 		if (pMacEntry->HTPhyMode.field.MODE >= MODE_HTMIX)
 		{
 			return TRUE;
 		}
-#endif // DOT11_N_SUPPORT //
 
 #ifdef AGGREGATION_SUPPORT
 		if (TxRate >= RATE_6 && pAd->CommonCfg.bAggregationCapable && (!(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) && CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_WMM_CAPABLE))))
@@ -1748,16 +1792,13 @@
 	return (NULL);
 }
 
-
+#ifdef RT2860
 BOOLEAN  RTMPFreeTXDUponTxDmaDone(
 	IN PRTMP_ADAPTER	pAd,
 	IN UCHAR			QueIdx)
 {
 	PRTMP_TX_RING pTxRing;
 	PTXD_STRUC	  pTxD;
-#ifdef	RT_BIG_ENDIAN
-    PTXD_STRUC      pDestTxD;
-#endif
 	PNDIS_PACKET  pPacket;
 	UCHAR	FREE = 0;
 	TXD_STRUC	TxD, *pOriTxD;
@@ -1771,111 +1812,19 @@
 	RTMP_IO_READ32(pAd, TX_DTX_IDX0 + QueIdx * RINGREG_DIFF, &pTxRing->TxDmaIdx);
 	while (pTxRing->TxSwFreeIdx != pTxRing->TxDmaIdx)
 	{
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-		PHEADER_802_11	pHeader80211;
-
-		if ((ATE_ON(pAd)) && (pAd->ate.bQATxStart == TRUE))
-		{
-			if (pAd->ate.QID == QueIdx)
-			{
-				pAd->ate.TxDoneCount++;
-				//pAd->ate.Repeat++;
-				pAd->RalinkCounters.KickTxCount++;
-
-				/* always use QID_AC_BE and FIFO_EDCA */
-				ASSERT(pAd->ate.QID == 0);
-				pAd->ate.TxAc0++;
-
-				FREE++;
-#ifndef RT_BIG_ENDIAN
-				pTxD = (PTXD_STRUC) (pTxRing->Cell[pTxRing->TxSwFreeIdx].AllocVa);
-				pOriTxD = pTxD;
-		        NdisMoveMemory(&TxD, pTxD, sizeof(TXD_STRUC));
-				pTxD = &TxD;
-#else
-		        pDestTxD = (PTXD_STRUC) (pTxRing->Cell[pTxRing->TxSwFreeIdx].AllocVa);
-		        pOriTxD = pDestTxD ;
-		        TxD = *pDestTxD;
-		        pTxD = &TxD;
-		        RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#endif
-				pTxD->DMADONE = 0;
-
-				pHeader80211 = pTxRing->Cell[pTxRing->TxSwFreeIdx].DmaBuf.AllocVa + sizeof(TXWI_STRUC);
-#ifdef RT_BIG_ENDIAN
-				RTMPFrameEndianChange(pAd, (PUCHAR)pHeader80211, DIR_READ, FALSE);
-#endif
-				pHeader80211->Sequence = ++pAd->ate.seq;
-#ifdef RT_BIG_ENDIAN
-				RTMPFrameEndianChange(pAd, (PUCHAR)pHeader80211, DIR_WRITE, FALSE);
-#endif
-
-				if  ((pAd->ate.bQATxStart == TRUE) && (pAd->ate.Mode & ATE_TXFRAME) && (pAd->ate.TxDoneCount < pAd->ate.TxCount))
-				{
-					pAd->RalinkCounters.TransmittedByteCount +=  (pTxD->SDLen1 + pTxD->SDLen0);
-					pAd->RalinkCounters.OneSecDmaDoneCount[QueIdx] ++;
-					INC_RING_INDEX(pTxRing->TxSwFreeIdx, TX_RING_SIZE);
-					/* get tx_tdx_idx again */
-					RTMP_IO_READ32(pAd, TX_DTX_IDX0 + QueIdx * RINGREG_DIFF ,  &pTxRing->TxDmaIdx);
-					goto kick_out;
-				}
-				else if ((pAd->ate.TxStatus == 1)/* or (pAd->ate.bQATxStart == TRUE) ??? */ && (pAd->ate.TxDoneCount == pAd->ate.TxCount))//<========================PETER
-				{
-					DBGPRINT(RT_DEBUG_TRACE,("all Tx is done\n"));
-					// Tx status enters idle mode.
-					pAd->ate.TxStatus = 0;
-				}
-				else if (!(pAd->ate.Mode & ATE_TXFRAME))
-				{
-					/* not complete sending yet, but someone press the Stop TX botton. */
-					DBGPRINT(RT_DEBUG_ERROR,("not complete sending yet, but someone pressed the Stop TX bottom\n"));
-					DBGPRINT(RT_DEBUG_ERROR,("pAd->ate.Mode = 0x%02x\n", pAd->ate.Mode));
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_OFF,("pTxRing->TxSwFreeIdx = %d\n", pTxRing->TxSwFreeIdx));
-  				}
-#ifndef RT_BIG_ENDIAN
-	        	NdisMoveMemory(pOriTxD, pTxD, sizeof(TXD_STRUC));
-#else
-        		RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-        		*pDestTxD = TxD;
-#endif // RT_BIG_ENDIAN //
-
-				INC_RING_INDEX(pTxRing->TxSwFreeIdx, TX_RING_SIZE);
-				continue;
-			}
-		}
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
 		// static rate also need NICUpdateFifoStaCounters() function.
 		//if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED))
 			NICUpdateFifoStaCounters(pAd);
 
 		/* Note : If (pAd->ate.bQATxStart == TRUE), we will never reach here. */
 		FREE++;
-#ifndef RT_BIG_ENDIAN
                 pTxD = (PTXD_STRUC) (pTxRing->Cell[pTxRing->TxSwFreeIdx].AllocVa);
 		pOriTxD = pTxD;
                 NdisMoveMemory(&TxD, pTxD, sizeof(TXD_STRUC));
 		pTxD = &TxD;
-#else
-        pDestTxD = (PTXD_STRUC) (pTxRing->Cell[pTxRing->TxSwFreeIdx].AllocVa);
-        pOriTxD = pDestTxD ;
-        TxD = *pDestTxD;
-        pTxD = &TxD;
-        RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#endif
 
 		pTxD->DMADONE = 0;
 
-
-#ifdef RALINK_ATE
-		/* Execution of this block is not allowed when ATE is running. */
-		if (!(ATE_ON(pAd)))
-#endif // RALINK_ATE //
 /*====================================================================*/
 		{
 			pPacket = pTxRing->Cell[pTxRing->TxSwFreeIdx].pNdisPacket;
@@ -1915,59 +1864,8 @@
 		INC_RING_INDEX(pTxRing->TxSwFreeIdx, TX_RING_SIZE);
 		/* get tx_tdx_idx again */
 		RTMP_IO_READ32(pAd, TX_DTX_IDX0 + QueIdx * RINGREG_DIFF ,  &pTxRing->TxDmaIdx);
-#ifdef RT_BIG_ENDIAN
-        RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-        *pDestTxD = TxD;
-#else
+
         NdisMoveMemory(pOriTxD, pTxD, sizeof(TXD_STRUC));
-#endif
-
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-kick_out:
-#endif // RALINK_28xx_QA //
-
-		//
-		// ATE_TXCONT mode also need to send some normal frames, so let it in.
-		// ATE_STOP must be changed not to be 0xff
-		// to prevent it from running into this block.
-		//
-		if ((pAd->ate.Mode & ATE_TXFRAME) && (pAd->ate.QID == QueIdx))
-		{
-			// TxDoneCount++ has been done if QA is used.
-			if (pAd->ate.bQATxStart == FALSE)
-			{
-				pAd->ate.TxDoneCount++;
-			}
-			if (((pAd->ate.TxCount - pAd->ate.TxDoneCount + 1) >= TX_RING_SIZE))
-			{
-				/* Note : We increase TxCpuIdx here, not TxSwFreeIdx ! */
-				INC_RING_INDEX(pAd->TxRing[QueIdx].TxCpuIdx, TX_RING_SIZE);
-#ifndef RT_BIG_ENDIAN//<==========================PETER
-				pTxD = (PTXD_STRUC) (pTxRing->Cell[pAd->TxRing[QueIdx].TxCpuIdx].AllocVa);
-				pOriTxD = pTxD;
-		        NdisMoveMemory(&TxD, pTxD, sizeof(TXD_STRUC));
-				pTxD = &TxD;
-#else
-		        pDestTxD = (PTXD_STRUC) (pTxRing->Cell[pAd->TxRing[QueIdx].TxCpuIdx].AllocVa);
-		        pOriTxD = pDestTxD ;
-		        TxD = *pDestTxD;
-		        pTxD = &TxD;
-		        RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#endif
-				pTxD->DMADONE = 0;
-#ifndef RT_BIG_ENDIAN//<==========================PETER
-        		NdisMoveMemory(pOriTxD, pTxD, sizeof(TXD_STRUC));
-#else
-        		RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-        		*pDestTxD = TxD;
-#endif
-				// kick Tx-Ring.
-				RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QueIdx * RINGREG_DIFF, pAd->TxRing[QueIdx].TxCpuIdx);
-				pAd->RalinkCounters.KickTxCount++;
-			}
-		}
-#endif // RALINK_ATE //
 	}
 
 
@@ -2050,10 +1948,6 @@
 	IN	PRTMP_ADAPTER	pAd)
 {
 	PTXD_STRUC	 pTxD;
-#ifdef RT_BIG_ENDIAN
-    PTXD_STRUC      pDestTxD;
-    TXD_STRUC       TxD;
-#endif
 	PNDIS_PACKET pPacket;
 	UCHAR	FREE = 0;
 	PRTMP_MGMT_RING pMgmtRing = &pAd->MgmtRing;
@@ -2064,14 +1958,7 @@
 	while (pMgmtRing->TxSwFreeIdx!= pMgmtRing->TxDmaIdx)
 	{
 		FREE++;
-#ifdef RT_BIG_ENDIAN
-        pDestTxD = (PTXD_STRUC) (pMgmtRing->Cell[pAd->MgmtRing.TxSwFreeIdx].AllocVa);
-        TxD = *pDestTxD;
-        pTxD = &TxD;
-		RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#else
 		pTxD = (PTXD_STRUC) (pMgmtRing->Cell[pAd->MgmtRing.TxSwFreeIdx].AllocVa);
-#endif
 		pTxD->DMADONE = 0;
 		pPacket = pMgmtRing->Cell[pMgmtRing->TxSwFreeIdx].pNdisPacket;
 
@@ -2091,11 +1978,6 @@
 		}
 		pMgmtRing->Cell[pMgmtRing->TxSwFreeIdx].pNextNdisPacket = NULL;
 		INC_RING_INDEX(pMgmtRing->TxSwFreeIdx, MGMT_RING_SIZE);
-
-#ifdef RT_BIG_ENDIAN
-        RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-        WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, TRUE, TYPE_TXD);
-#endif
 	}
 	NdisReleaseSpinLock(&pAd->MgmtRingLock);
 
@@ -2293,6 +2175,7 @@
 	DBGPRINT_RAW(RT_DEBUG_TRACE,(" 	RxSwReadIdx [%d]=", AC0freeIdx));
 	DBGPRINT_RAW(RT_DEBUG_TRACE,("	pending-NDIS=%ld\n", pAd->RalinkCounters.PendingNdisPacketCount));
 }
+#endif /* RT2860 */
 
 /*
 	========================================================================
@@ -2352,7 +2235,15 @@
 {
 	DBGPRINT(RT_DEBUG_TRACE,("SCAN done, resume MSDU transmission ...\n"));
 
-
+#ifdef RT30xx
+	// After finish BSS_SCAN_IN_PROGRESS, we need to restore Current R66 value
+	// R66 should not be 0
+	if (pAd->BbpTuning.R66CurrentValue == 0)
+	{
+		pAd->BbpTuning.R66CurrentValue = 0x38;
+		DBGPRINT_ERR(("RTMPResumeMsduTransmission, R66CurrentValue=0...\n"));
+	}
+#endif
 	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, pAd->BbpTuning.R66CurrentValue);
 
 	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
@@ -2401,7 +2292,6 @@
 		// convert to 802.3 header
         CONVERT_TO_802_3(Header802_3, pDA, pSA, pPayload, PayloadSize, pRemovedLLCSNAP);
 
-#ifdef CONFIG_STA_SUPPORT
 		if ((Header802_3[12] == 0x88) && (Header802_3[13] == 0x8E) )
 		{
 		    // avoid local heap overflow, use dyanamic allocation
@@ -2411,10 +2301,7 @@
 		   WpaEAPOLKeyAction(pAd, Elem);
 		   kfree(Elem);
 		}
-#endif // CONFIG_STA_SUPPORT //
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 	        	if (pRemovedLLCSNAP)
 	        	{
@@ -2423,15 +2310,11 @@
 	    			NdisMoveMemory(pPayload, &Header802_3[0], LENGTH_802_3);
 	        	}
 		}
-#endif // CONFIG_STA_SUPPORT //
 
 		pClonePacket = ClonePacket(pAd, pPacket, pPayload, PayloadSize);
 		if (pClonePacket)
 		{
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pClonePacket, RTMP_GET_PACKET_IF(pPacket));
-#endif // CONFIG_STA_SUPPORT //
+			ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pClonePacket, RTMP_GET_PACKET_IF(pPacket));
 		}
 
 
@@ -2527,11 +2410,9 @@
 		return NULL;
 
 	FirstWcid = 1;
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+
 	if (pAd->StaCfg.BssType == BSS_INFRA)
 		FirstWcid = 2;
-#endif // CONFIG_STA_SUPPORT //
 
 	// allocate one MAC entry
 	NdisAcquireSpinLock(&pAd->MacTabLock);
@@ -2542,11 +2423,6 @@
 			(pAd->MacTab.Content[i].ValidAsWDS == FALSE) &&
 			(pAd->MacTab.Content[i].ValidAsApCli== FALSE) &&
 			(pAd->MacTab.Content[i].ValidAsMesh == FALSE)
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-			&& (pAd->MacTab.Content[i].ValidAsDls == FALSE)
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
 			)
 		{
 			pEntry = &pAd->MacTab.Content[i];
@@ -2558,24 +2434,7 @@
 				pEntry->PairwiseKey.KeyLen = 0;
 				pEntry->PairwiseKey.CipherAlg = CIPHER_NONE;
 			}
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-			if (apidx >= MIN_NET_DEVICE_FOR_DLS)
 			{
-				pEntry->ValidAsCLI = FALSE;
-				pEntry->ValidAsWDS = FALSE;
-				pEntry->ValidAsApCli = FALSE;
-				pEntry->ValidAsMesh = FALSE;
-				pEntry->ValidAsDls = TRUE;
-				pEntry->isCached = FALSE;
-			}
-			else
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-			{
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 				{
 					pEntry->ValidAsCLI = TRUE;
 					pEntry->ValidAsWDS = FALSE;
@@ -2583,7 +2442,6 @@
 					pEntry->ValidAsMesh = FALSE;
 					pEntry->ValidAsDls = FALSE;
 				}
-#endif // CONFIG_STA_SUPPORT //
 			}
 
 			pEntry->bIAmBadAtheros = FALSE;
@@ -2600,43 +2458,32 @@
 				pEntry->apidx = (apidx - MIN_NET_DEVICE_FOR_APCLI);
 			else if (pEntry->ValidAsWDS)
 				pEntry->apidx = (apidx - MIN_NET_DEVICE_FOR_WDS);
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-			else if (pEntry->ValidAsDls)
-				pEntry->apidx = (apidx - MIN_NET_DEVICE_FOR_DLS);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
 			else
 				pEntry->apidx = apidx;
 
 			{
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 				{
 					pEntry->AuthMode = pAd->StaCfg.AuthMode;
 					pEntry->WepStatus = pAd->StaCfg.WepStatus;
 					pEntry->PrivacyFilter = Ndis802_11PrivFilterAcceptAll;
+#ifdef RT2860
 					AsicRemovePairwiseKeyEntry(pAd, pEntry->apidx, (UCHAR)i);
+#endif
 				}
-#endif // CONFIG_STA_SUPPORT //
 			}
 
 			pEntry->GTKState = REKEY_NEGOTIATING;
 			pEntry->PairwiseKey.KeyLen = 0;
 			pEntry->PairwiseKey.CipherAlg = CIPHER_NONE;
-#ifdef CONFIG_STA_SUPPORT
+
+#ifdef RT2860
 			if ((pAd->OpMode == OPMODE_STA) &&
 				(pAd->StaCfg.BssType == BSS_ADHOC))
 				pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
 			else
-#ifdef QOS_DLS_SUPPORT
-			if (pEntry->ValidAsDls == TRUE)
-				pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
-			else
-#endif //QOS_DLS_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
+#endif
 			pEntry->PortSecured = WPA_802_1X_PORT_NOT_SECURED;
+
 			pEntry->PMKID_CacheIdx = ENTRY_NOT_FOUND;
 			COPY_MAC_ADDR(pEntry->Addr, pAddr);
 			pEntry->Sst = SST_NOT_AUTH;
@@ -2706,11 +2553,6 @@
 	pEntry = &pAd->MacTab.Content[wcid];
 
 	if (pEntry && (pEntry->ValidAsCLI || pEntry->ValidAsApCli || pEntry->ValidAsWDS || pEntry->ValidAsMesh
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
- 		|| pEntry->ValidAsDls
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
 		))
 	{
 		if (MAC_ADDR_EQUAL(pEntry->Addr, pAddr))
@@ -2719,11 +2561,8 @@
 			// Delete this entry from ASIC on-chip WCID Table
 			RT28XX_STA_ENTRY_MAC_RESET(pAd, wcid);
 
-#ifdef DOT11_N_SUPPORT
 			// free resources of BA
 			BASessionTearDownALL(pAd, pEntry->Aid);
-#endif // DOT11_N_SUPPORT //
-
 
 			pPrevEntry = NULL;
 			pProbeEntry = pAd->MacTab.Hash[HashIdx];
@@ -2777,10 +2616,13 @@
 	//Reset operating mode when no Sta.
 	if (pAd->MacTab.Size == 0)
 	{
-#ifdef DOT11_N_SUPPORT
 		pAd->CommonCfg.AddHTInfo.AddHtInfo2.OperaionMode = 0;
-#endif // DOT11_N_SUPPORT //
+#ifndef RT30xx
 		AsicUpdateProtect(pAd, 0 /*pAd->CommonCfg.AddHTInfo.AddHtInfo2.OperaionMode*/, (ALLN_SETPROTECT), TRUE, 0 /*pAd->MacTab.fAnyStationNonGF*/);
+#endif
+#ifdef RT30xx
+		RT28XX_UPDATE_PROTECT(pAd);  // edit by johnli, fix "in_interrupt" error when call "MacTableDeleteEntry" in Rx tasklet
+#endif
 	}
 
 	return TRUE;
@@ -2804,19 +2646,22 @@
 
 	for (i=1; i<MAX_LEN_OF_MAC_TABLE; i++)
 	{
+#ifdef RT2860
 		RT28XX_STA_ENTRY_MAC_RESET(pAd, i);
+#endif
 		if (pAd->MacTab.Content[i].ValidAsCLI == TRUE)
 	   {
-
-#ifdef DOT11_N_SUPPORT
 			// free resources of BA
 			BASessionTearDownALL(pAd, i);
-#endif // DOT11_N_SUPPORT //
 
 			pAd->MacTab.Content[i].ValidAsCLI = FALSE;
 
 
 
+#ifdef RT2870
+			NdisZeroMemory(pAd->MacTab.Content[i].Addr, 6);
+			RT28XX_STA_ENTRY_MAC_RESET(pAd, i);
+#endif // RT2870 //
 
 			//AsicDelWcidTab(pAd, i);
 		}
@@ -3116,10 +2961,7 @@
 	// 2. remove LLC
 	// 		a. pointer pRxBlk->pData to payload
 	//      b. modify pRxBlk->DataSize
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
-#endif // CONFIG_STA_SUPPORT //
+	RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
 
 	if (pRxBlk->DataSize > MAX_RX_PKT_LEN)
 	{
@@ -3132,17 +2974,44 @@
 
 	STATS_INC_RX_PACKETS(pAd, FromWhichBSSID);
 
+#ifdef RT2870
+	if (pAd->CommonCfg.bDisableReordering == 0)
+	{
+		PBA_REC_ENTRY		pBAEntry;
+		ULONG				Now32;
+		UCHAR				Wcid = pRxBlk->pRxWI->WirelessCliID;
+		UCHAR				TID = pRxBlk->pRxWI->TID;
+		USHORT				Idx;
+
+#define REORDERING_PACKET_TIMEOUT		((100 * HZ)/1000)	// system ticks -- 100 ms
+
+		if (Wcid < MAX_LEN_OF_MAC_TABLE)
+		{
+			Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID];
+			if (Idx != 0)
+			{
+				pBAEntry = &pAd->BATable.BARecEntry[Idx];
+				// update last rx time
+				NdisGetSystemUpTime(&Now32);
+				if ((pBAEntry->list.qlen > 0) &&
+					 RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(REORDERING_PACKET_TIMEOUT)))
+	   				)
+				{
+					printk("Indicate_Legacy_Packet():flush reordering_timeout_mpdus! RxWI->Flags=%d, pRxWI.TID=%d, RxD->AMPDU=%d!\n", pRxBlk->Flags, pRxBlk->pRxWI->TID, pRxBlk->RxD.AMPDU);
+					hex_dump("Dump the legacy Packet:", GET_OS_PKT_DATAPTR(pRxBlk->pRxPacket), 64);
+					ba_flush_reordering_timeout_mpdus(pAd, pBAEntry, Now32);
+				}
+			}
+		}
+	}
+#endif // RT2870 //
 
 	wlan_802_11_to_802_3_packet(pAd, pRxBlk, Header802_3, FromWhichBSSID);
 
 	//
 	// pass this 802.3 packet to upper layer or forward this packet to WM directly
 	//
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pRxPacket, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
-
+	ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pRxPacket, FromWhichBSSID);
 }
 
 
@@ -3152,22 +3021,18 @@
 	IN	RX_BLK			*pRxBlk,
 	IN	UCHAR			FromWhichBSSID)
 {
-#ifdef DOT11_N_SUPPORT
 	if (RX_BLK_TEST_FLAG(pRxBlk, fRX_AMPDU) && (pAd->CommonCfg.bDisableReordering == 0))
 	{
 		Indicate_AMPDU_Packet(pAd, pRxBlk, FromWhichBSSID);
 	}
 	else
-#endif // DOT11_N_SUPPORT //
 	{
-#ifdef DOT11_N_SUPPORT
 		if (RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU))
 		{
 			// handle A-MSDU
 			Indicate_AMSDU_Packet(pAd, pRxBlk, FromWhichBSSID);
 		}
 		else
-#endif // DOT11_N_SUPPORT //
 		{
 			Indicate_Legacy_Packet(pAd, pRxBlk, FromWhichBSSID);
 		}
@@ -3205,11 +3070,7 @@
 	}
 
 	// get 802.3 Header and  remove LLC
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
-#endif // CONFIG_STA_SUPPORT //
-
+	RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
 
 	ASSERT(pRxBlk->pRxPacket);
 
@@ -3219,10 +3080,8 @@
 	Payload2Size = Msdu2Size - LENGTH_802_3;
 
 	pData2 = pRxBlk->pData + Payload1Size + LENGTH_802_3;
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		pPacket2 = duplicate_pkt(pAd, (pData2-LENGTH_802_3), LENGTH_802_3, pData2, Payload2Size, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
+
+	pPacket2 = duplicate_pkt(pAd, (pData2-LENGTH_802_3), LENGTH_802_3, pData2, Payload2Size, FromWhichBSSID);
 
 	if (!pPacket2)
 	{
@@ -3235,17 +3094,11 @@
 	pRxBlk->DataSize = Payload1Size;
 	wlan_802_11_to_802_3_packet(pAd, pRxBlk, Header802_3, FromWhichBSSID);
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pRxBlk->pRxPacket, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
+	ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pRxBlk->pRxPacket, FromWhichBSSID);
 
 	if (pPacket2)
 	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pPacket2, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
+		ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pPacket2, FromWhichBSSID);
 	}
 }
 
@@ -3388,15 +3241,11 @@
 {
 	MAC_TABLE_ENTRY *pEntry = NULL;
 
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		pEntry = &pAd->MacTab.Content[BSSID_WCID];
 		STARxEAPOLFrameIndicate(pAd, pEntry, pRxBlk, FromWhichBSSID);
 		return;
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	if (pEntry == NULL)
 	{
diff --git a/drivers/staging/rt2860/common/cmm_data_2860.c b/drivers/staging/rt2860/common/cmm_data_2860.c
index fae741e..fb17355 100644
--- a/drivers/staging/rt2860/common/cmm_data_2860.c
+++ b/drivers/staging/rt2860/common/cmm_data_2860.c
@@ -110,10 +110,6 @@
 	UCHAR			*pDMAHeaderBufVA;
 	USHORT			TxIdx, RetTxIdx;
 	PTXD_STRUC		pTxD;
-#ifdef RT_BIG_ENDIAN
-    PTXD_STRUC      pDestTxD;
-    TXD_STRUC       TxD;
-#endif
 	UINT32			BufBasePaLow;
 	PRTMP_TX_RING	pTxRing;
 	USHORT			hwHeaderLen;
@@ -137,13 +133,8 @@
 	//
 	// build Tx Descriptor
 	//
-#ifndef RT_BIG_ENDIAN
 	pTxD = (PTXD_STRUC) pTxRing->Cell[TxIdx].AllocVa;
-#else
-	pDestTxD = (PTXD_STRUC) pTxRing->Cell[TxIdx].AllocVa;
-	TxD = *pDestTxD;
-	pTxD = &TxD;
-#endif
+
 	NdisZeroMemory(pTxD, TXD_SIZE);
 
 	pTxD->SDPtr0 = BufBasePaLow;
@@ -154,12 +145,6 @@
 	pTxD->LastSec1 = (bIsLast) ? 1 : 0;
 
 	RTMPWriteTxDescriptor(pAd, pTxD, FALSE, FIFO_EDCA);
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange((PUCHAR)(pDMAHeaderBufVA + TXINFO_SIZE), TYPE_TXWI);
-	RTMPFrameEndianChange(pAd, (PUCHAR)(pDMAHeaderBufVA + TXINFO_SIZE + TXWI_SIZE), DIR_WRITE, FALSE);
-	RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-    WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif // RT_BIG_ENDIAN //
 
 	RetTxIdx = TxIdx;
 	//
@@ -184,10 +169,6 @@
 	UCHAR			*pDMAHeaderBufVA;
 	USHORT			TxIdx, RetTxIdx;
 	PTXD_STRUC		pTxD;
-#ifdef RT_BIG_ENDIAN
-    PTXD_STRUC      pDestTxD;
-    TXD_STRUC       TxD;
-#endif
 	UINT32			BufBasePaLow;
 	PRTMP_TX_RING	pTxRing;
 	USHORT			hwHdrLen;
@@ -231,13 +212,8 @@
 	//
 	// build Tx Descriptor
 	//
-#ifndef RT_BIG_ENDIAN
 	pTxD = (PTXD_STRUC) pTxRing->Cell[TxIdx].AllocVa;
-#else
-	pDestTxD = (PTXD_STRUC) pTxRing->Cell[TxIdx].AllocVa;
-	TxD = *pDestTxD;
-	pTxD = &TxD;
-#endif
+
 	NdisZeroMemory(pTxD, TXD_SIZE);
 
 	pTxD->SDPtr0 = BufBasePaLow;
@@ -249,17 +225,6 @@
 
 	RTMPWriteTxDescriptor(pAd, pTxD, FALSE, FIFO_EDCA);
 
-#ifdef RT_BIG_ENDIAN
-	if (frameNum == 0)
-		RTMPFrameEndianChange(pAd, (PUCHAR)(pDMAHeaderBufVA+ TXINFO_SIZE + TXWI_SIZE), DIR_WRITE, FALSE);
-
-	if (frameNum != 0)
-		RTMPWIEndianChange((PUCHAR)(pDMAHeaderBufVA + TXINFO_SIZE), TYPE_TXWI);
-
-	RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-	WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif // RT_BIG_ENDIAN //
-
 	RetTxIdx = TxIdx;
 	//
 	// Update Tx index
@@ -290,10 +255,6 @@
 	pTxRing = &pAd->TxRing[pTxBlk->QueIdx];
 	pTxWI = (PTXWI_STRUC) pTxRing->Cell[FirstTxIdx].DmaBuf.AllocVa;
 	pTxWI->MPDUtotalByteCount = totalMPDUSize;
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-#endif // RT_BIG_ENDIAN //
-
 }
 
 
@@ -303,10 +264,6 @@
 	IN	USHORT			LastTxIdx)
 {
 	PTXD_STRUC		pTxD;
-#ifdef RT_BIG_ENDIAN
-    PTXD_STRUC      pDestTxD;
-    TXD_STRUC       TxD;
-#endif
 	PRTMP_TX_RING	pTxRing;
 
 	//
@@ -317,21 +274,9 @@
 	//
 	// build Tx Descriptor
 	//
-#ifndef RT_BIG_ENDIAN
 	pTxD = (PTXD_STRUC) pTxRing->Cell[LastTxIdx].AllocVa;
-#else
-	pDestTxD = (PTXD_STRUC) pTxRing->Cell[LastTxIdx].AllocVa;
-	TxD = *pDestTxD;
-	pTxD = &TxD;
-#endif
 
 	pTxD->LastSec1 = 1;
-
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-    WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif // RT_BIG_ENDIAN //
-
 }
 
 
@@ -344,10 +289,6 @@
 	UCHAR			*pDMAHeaderBufVA;
 	USHORT			TxIdx, RetTxIdx;
 	PTXD_STRUC		pTxD;
-#ifdef RT_BIG_ENDIAN
-    PTXD_STRUC      pDestTxD;
-    TXD_STRUC       TxD;
-#endif
 	UINT32			BufBasePaLow;
 	PRTMP_TX_RING	pTxRing;
 	USHORT			hwHeaderLen;
@@ -373,13 +314,8 @@
 	//
 	// Build Tx Descriptor
 	//
-#ifndef RT_BIG_ENDIAN
 	pTxD = (PTXD_STRUC) pTxRing->Cell[TxIdx].AllocVa;
-#else
-	pDestTxD = (PTXD_STRUC) pTxRing->Cell[TxIdx].AllocVa;
-	TxD = *pDestTxD;
-	pTxD = &TxD;
-#endif
+
 	NdisZeroMemory(pTxD, TXD_SIZE);
 
 	if (fragNum == pTxBlk->TotalFragNum)
@@ -397,13 +333,6 @@
 
 	RTMPWriteTxDescriptor(pAd, pTxD, FALSE, FIFO_EDCA);
 
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange((PUCHAR)(pDMAHeaderBufVA + TXINFO_SIZE), TYPE_TXWI);
-	RTMPFrameEndianChange(pAd, (PUCHAR)(pDMAHeaderBufVA + TXINFO_SIZE + TXWI_SIZE), DIR_WRITE, FALSE);
-	RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-    WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif // RT_BIG_ENDIAN //
-
 	RetTxIdx = TxIdx;
 	pTxBlk->Priv += pTxBlk->SrcBufLen;
 
@@ -431,20 +360,9 @@
 	IN UINT 			SrcBufLen)
 {
 	PTXD_STRUC		pTxD;
-#ifdef RT_BIG_ENDIAN
-    PTXD_STRUC      pDestTxD;
-    TXD_STRUC       TxD;
-#endif
 	ULONG			SwIdx = pAd->MgmtRing.TxCpuIdx;
 
-#ifdef RT_BIG_ENDIAN
-    pDestTxD  = (PTXD_STRUC)pAd->MgmtRing.Cell[SwIdx].AllocVa;
-    TxD = *pDestTxD;
-    pTxD = &TxD;
-    RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#else
 	pTxD  = (PTXD_STRUC) pAd->MgmtRing.Cell[SwIdx].AllocVa;
-#endif
 
 	pAd->MgmtRing.Cell[SwIdx].pNdisPacket = pPacket;
 	pAd->MgmtRing.Cell[SwIdx].pNextNdisPacket = NULL;
@@ -457,11 +375,6 @@
 	pTxD->SDPtr0 = PCI_MAP_SINGLE(pAd, pSrcBufVA, SrcBufLen, 0, PCI_DMA_TODEVICE);;
 	pTxD->SDLen0 = SrcBufLen;
 
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-    WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif
-
 	pAd->RalinkCounters.KickTxCount++;
 	pAd->RalinkCounters.OneSecTxDoneCount++;
 
@@ -473,8 +386,6 @@
 	return 0;
 }
 
-
-#ifdef CONFIG_STA_SUPPORT
 /*
 	========================================================================
 
@@ -570,12 +481,11 @@
 		if (pRxD->CipherErr == 2)
 		{
 			pWpaKey = &pAd->SharedKey[BSS0][pRxWI->KeyIndex];
-#ifdef WPA_SUPPLICANT_SUPPORT
+
             if (pAd->StaCfg.WpaSupplicantUP)
                 WpaSendMicFailureToWpaSupplicant(pAd,
                                    (pWpaKey->Type == PAIRWISEKEY) ? TRUE:FALSE);
             else
-#endif // WPA_SUPPLICANT_SUPPORT //
 			    RTMPReportMicError(pAd, pWpaKey);
 
             if (((pRxD->CipherErr & 2) == 2) && pAd->CommonCfg.bWirelessEvent && INFRA_ON(pAd))
@@ -1128,8 +1038,6 @@
 	}
 }
 
-#endif // CONFIG_STA_SUPPORT //
-
 VOID RT28xxPciMlmeRadioOn(
 	IN PRTMP_ADAPTER pAd)
 {
@@ -1163,7 +1071,6 @@
 	    RTMPSetLED(pAd, LED_RADIO_ON);
     }
 
-#ifdef CONFIG_STA_SUPPORT
     if ((pAd->OpMode == OPMODE_STA) &&
         (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE)))
     {
@@ -1176,7 +1083,6 @@
     	RTMPCancelTimer(&pAd->Mlme.RadioOnOffTimer,	&Cancelled);
     	RTMPSetTimer(&pAd->Mlme.RadioOnOffTimer, 10);
     }
-#endif // CONFIG_STA_SUPPORT //
 }
 
 VOID RT28xxPciMlmeRadioOFF(
@@ -1199,8 +1105,6 @@
 	// Set LED
 	RTMPSetLED(pAd, LED_RADIO_OFF);
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
     {
     	BOOLEAN		Cancelled;
 
@@ -1249,7 +1153,6 @@
 			return;
 		}
     }
-#endif // CONFIG_STA_SUPPORT //
 
 	// Set Radio off flag
 	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
diff --git a/drivers/staging/rt2860/common/cmm_info.c b/drivers/staging/rt2860/common/cmm_info.c
index c3e1319..306c3a2 100644
--- a/drivers/staging/rt2860/common/cmm_info.c
+++ b/drivers/staging/rt2860/common/cmm_info.c
@@ -63,7 +63,6 @@
 	IN	PRTMP_ADAPTER	pAd,
 	OUT	PUCHAR			pBuf);
 
-#ifdef DOT11_N_SUPPORT
 INT	Show_HtBw_Proc(
 	IN	PRTMP_ADAPTER	pAd,
 	OUT	PUCHAR			pBuf);
@@ -103,7 +102,6 @@
 INT	Show_HtAutoBa_Proc(
 	IN	PRTMP_ADAPTER	pAd,
 	OUT	PUCHAR			pBuf);
-#endif // DOT11_N_SUPPORT //
 
 INT	Show_CountryRegion_Proc(
 	IN	PRTMP_ADAPTER	pAd,
@@ -133,11 +131,9 @@
 	IN	PRTMP_ADAPTER	pAd,
 	OUT	PUCHAR			pBuf);
 
-#ifdef CONFIG_STA_SUPPORT
 INT	Show_NetworkType_Proc(
 	IN	PRTMP_ADAPTER	pAd,
 	OUT	PUCHAR			pBuf);
-#endif // CONFIG_STA_SUPPORT //
 
 INT	Show_AuthMode_Proc(
 	IN	PRTMP_ADAPTER	pAd,
@@ -184,7 +180,6 @@
 	{"BGProtection",			Show_BGProtection_Proc},
 	{"RTSThreshold",			Show_RTSThreshold_Proc},
 	{"FragThreshold",			Show_FragThreshold_Proc},
-#ifdef DOT11_N_SUPPORT
 	{"HtBw",					Show_HtBw_Proc},
 	{"HtMcs",					Show_HtMcs_Proc},
 	{"HtGi",					Show_HtGi_Proc},
@@ -195,7 +190,6 @@
 	{"HtRdg",		        	Show_HtRdg_Proc},
 	{"HtAmsdu",		        	Show_HtAmsdu_Proc},
 	{"HtAutoBa",		        Show_HtAutoBa_Proc},
-#endif // DOT11_N_SUPPORT //
 	{"CountryRegion",			Show_CountryRegion_Proc},
 	{"CountryRegionABand",		Show_CountryRegionABand_Proc},
 	{"CountryCode",				Show_CountryCode_Proc},
@@ -207,9 +201,7 @@
 	{"WmmCapable",				Show_WmmCapable_Proc},
 #endif
 	{"IEEE80211H",				Show_IEEE80211H_Proc},
-#ifdef CONFIG_STA_SUPPORT
     {"NetworkType",				Show_NetworkType_Proc},
-#endif // CONFIG_STA_SUPPORT //
 	{"AuthMode",				Show_AuthMode_Proc},
 	{"EncrypType",				Show_EncrypType_Proc},
 	{"DefaultKeyID",			Show_DefaultKeyID_Proc},
@@ -233,11 +225,7 @@
 	IN	PRTMP_ADAPTER	pAd,
 	IN	PUCHAR			arg)
 {
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		DBGPRINT(RT_DEBUG_TRACE, ("Driver version-%s\n", STA_DRIVER_VERSION));
-#endif // CONFIG_STA_SUPPORT //
+	DBGPRINT(RT_DEBUG_TRACE, ("Driver version-%s\n", STA_DRIVER_VERSION));
 
     return TRUE;
 }
@@ -259,10 +247,6 @@
 
 	region = simple_strtol(arg, 0, 10);
 
-#ifdef EXT_BUILD_CHANNEL_LIST
-	return -EOPNOTSUPP;
-#endif // EXT_BUILD_CHANNEL_LIST //
-
 	// Country can be set only when EEPROM not programmed
 	if (pAd->CommonCfg.CountryRegion & 0x80)
 	{
@@ -309,10 +293,6 @@
 
 	region = simple_strtol(arg, 0, 10);
 
-#ifdef EXT_BUILD_CHANNEL_LIST
-	return -EOPNOTSUPP;
-#endif // EXT_BUILD_CHANNEL_LIST //
-
 	// Country can be set only when EEPROM not programmed
 	if (pAd->CommonCfg.CountryRegionForABand & 0x80)
 	{
@@ -355,20 +335,15 @@
 
 	WirelessMode = simple_strtol(arg, 0, 10);
 
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		INT MaxPhyMode = PHY_11G;
 
-#ifdef DOT11_N_SUPPORT
 		MaxPhyMode = PHY_11N_5G;
-#endif // DOT11_N_SUPPORT //
 
 		if (WirelessMode <= MaxPhyMode)
 		{
 			RTMPSetPhyMode(pAd, WirelessMode);
-#ifdef DOT11_N_SUPPORT
+
 			if (WirelessMode >= PHY_11ABGN_MIXED)
 			{
 				pAd->CommonCfg.BACapability.field.AutoBA = TRUE;
@@ -379,7 +354,7 @@
 				pAd->CommonCfg.BACapability.field.AutoBA = FALSE;
 				pAd->CommonCfg.REGBACapability.field.AutoBA = FALSE;
 			}
-#endif // DOT11_N_SUPPORT //
+
 			// Set AdhocMode rates
 			if (pAd->StaCfg.BssType == BSS_ADHOC)
 			{
@@ -393,14 +368,11 @@
 			success = FALSE;
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	// it is needed to set SSID to take effect
 	if (success == TRUE)
 	{
-#ifdef DOT11_N_SUPPORT
 		SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
 		DBGPRINT(RT_DEBUG_TRACE, ("Set_WirelessMode_Proc::(=%ld)\n", WirelessMode));
 	}
 	else
@@ -431,14 +403,11 @@
 	// check if this channel is valid
 	if (ChannelSanity(pAd, Channel) == TRUE)
 	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			pAd->CommonCfg.Channel = Channel;
 
 			if (MONITOR_ON(pAd))
 			{
-#ifdef DOT11_N_SUPPORT
 				N_ChannelCheck(pAd);
 				if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
 					pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40)
@@ -450,7 +419,6 @@
 								pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel));
 				}
 				else
-#endif // DOT11_N_SUPPORT //
 				{
 					AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
 					AsicLockChannel(pAd, pAd->CommonCfg.Channel);
@@ -458,16 +426,11 @@
 				}
 			}
 		}
-#endif // CONFIG_STA_SUPPORT //
 		success = TRUE;
 	}
 	else
 	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			success = FALSE;
-#endif // CONFIG_STA_SUPPORT //
+		success = FALSE;
 	}
 
 
@@ -523,14 +486,10 @@
 	TxPower = (ULONG) simple_strtol(arg, 0, 10);
 	if (TxPower <= 100)
 	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			pAd->CommonCfg.TxPowerDefault = TxPower;
 			pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault;
 		}
-#endif // CONFIG_STA_SUPPORT //
 		success = TRUE;
 	}
 	else
@@ -595,22 +554,16 @@
 	{
 		case Rt802_11PreambleShort:
 			pAd->CommonCfg.TxPreamble = Preamble;
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				MlmeSetTxPreamble(pAd, Rt802_11PreambleShort);
-#endif // CONFIG_STA_SUPPORT //
+
+			MlmeSetTxPreamble(pAd, Rt802_11PreambleShort);
 			break;
 		case Rt802_11PreambleLong:
-#ifdef CONFIG_STA_SUPPORT
 		case Rt802_11PreambleAuto:
 			// if user wants AUTO, initialize to LONG here, then change according to AP's
 			// capability upon association.
-#endif // CONFIG_STA_SUPPORT //
 			pAd->CommonCfg.TxPreamble = Preamble;
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				MlmeSetTxPreamble(pAd, Rt802_11PreambleLong);
-#endif // CONFIG_STA_SUPPORT //
+
+			MlmeSetTxPreamble(pAd, Rt802_11PreambleLong);
 			break;
 		default: //Invalid argument
 			return FALSE;
@@ -639,10 +592,8 @@
 
 	if((RtsThresh > 0) && (RtsThresh <= MAX_RTS_THRESHOLD))
 		pAd->CommonCfg.RtsThreshold  = (USHORT)RtsThresh;
-#ifdef CONFIG_STA_SUPPORT
 	else if (RtsThresh == 0)
 		pAd->CommonCfg.RtsThreshold = MAX_RTS_THRESHOLD;
-#endif // CONFIG_STA_SUPPORT //
 	else
 		return FALSE; //Invalid argument
 
@@ -683,15 +634,12 @@
 		pAd->CommonCfg.FragmentThreshold = (USHORT)FragThresh;
 	}
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		if (pAd->CommonCfg.FragmentThreshold == MAX_FRAG_THRESHOLD)
 			pAd->CommonCfg.bUseZeroToDisableFragment = TRUE;
 		else
 			pAd->CommonCfg.bUseZeroToDisableFragment = FALSE;
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	DBGPRINT(RT_DEBUG_TRACE, ("Set_FragThreshold_Proc::(FragThreshold=%d)\n", pAd->CommonCfg.FragmentThreshold));
 
@@ -814,6 +762,7 @@
 	IN	PRTMP_ADAPTER	pAd,
 	IN	PUCHAR			arg)
 {
+#ifdef RT2860
 	INT i, QueIdx=0;
 	PRT28XX_RXD_STRUC pRxD;
     PTXD_STRUC pTxD;
@@ -844,7 +793,7 @@
 	    hex_dump("Rx Descriptor", (char *)pRxD, 16);
 		printk("pRxD->DDONE = %x\n", pRxD->DDONE);
 	}
-
+#endif /* RT2860 */
 	return TRUE;
 }
 
@@ -912,7 +861,6 @@
 
 	========================================================================
 */
-#ifdef CONFIG_STA_SUPPORT
 VOID    RTMPSetDesiredRates(
     IN  PRTMP_ADAPTER   pAdapter,
     IN  LONG            Rates)
@@ -1125,10 +1073,7 @@
 
 	return (Status);
 }
-#endif // CONFIG_STA_SUPPORT //
 
-
-#ifdef CONFIG_STA_SUPPORT
 /*
 	========================================================================
 
@@ -1178,7 +1123,6 @@
 	}
 
 }
-#endif // CONFIG_STA_SUPPORT //
 
 /*
 	========================================================================
@@ -1202,19 +1146,11 @@
 	INT i;
 	// the selected phymode must be supported by the RF IC encoded in E2PROM
 
-	// if no change, do nothing
-	/* bug fix
-	if (pAd->CommonCfg.PhyMode == phymode)
-		return;
-    */
 	pAd->CommonCfg.PhyMode = (UCHAR)phymode;
 
 	DBGPRINT(RT_DEBUG_TRACE,("RTMPSetPhyMode : PhyMode=%d, channel=%d \n", pAd->CommonCfg.PhyMode, pAd->CommonCfg.Channel));
-#ifdef EXT_BUILD_CHANNEL_LIST
-	BuildChannelListEx(pAd);
-#else
+
 	BuildChannelList(pAd);
-#endif // EXT_BUILD_CHANNEL_LIST //
 
 	// sanity check user setting
 	for (i = 0; i < pAd->ChannelListNum; i++)
@@ -1225,10 +1161,7 @@
 
 	if (i == pAd->ChannelListNum)
 	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			pAd->CommonCfg.Channel = FirstChannel(pAd);
-#endif // CONFIG_STA_SUPPORT //
+		pAd->CommonCfg.Channel = FirstChannel(pAd);
 		DBGPRINT(RT_DEBUG_ERROR, ("RTMPSetPhyMode: channel is out of range, use first channel=%d \n", pAd->CommonCfg.Channel));
 	}
 
@@ -1253,12 +1186,10 @@
 		case PHY_11G:
 		case PHY_11BG_MIXED:
 		case PHY_11ABG_MIXED:
-#ifdef DOT11_N_SUPPORT
 		case PHY_11N_2_4G:
 		case PHY_11ABGN_MIXED:
 		case PHY_11BGN_MIXED:
 		case PHY_11GN_MIXED:
-#endif // DOT11_N_SUPPORT //
 			pAd->CommonCfg.SupRate[0]  = 0x82;	  // 1 mbps, in units of 0.5 Mbps, basic rate
 			pAd->CommonCfg.SupRate[1]  = 0x84;	  // 2 mbps, in units of 0.5 Mbps, basic rate
 			pAd->CommonCfg.SupRate[2]  = 0x8B;	  // 5.5 mbps, in units of 0.5 Mbps, basic rate
@@ -1288,11 +1219,9 @@
 			break;
 
 		case PHY_11A:
-#ifdef DOT11_N_SUPPORT
 		case PHY_11AN_MIXED:
 		case PHY_11AGN_MIXED:
 		case PHY_11N_5G:
-#endif // DOT11_N_SUPPORT //
 			pAd->CommonCfg.SupRate[0]  = 0x8C;	  // 6 mbps, in units of 0.5 Mbps, basic rate
 			pAd->CommonCfg.SupRate[1]  = 0x12;	  // 9 mbps, in units of 0.5 Mbps
 			pAd->CommonCfg.SupRate[2]  = 0x98;	  // 12 mbps, in units of 0.5 Mbps, basic rate
@@ -1322,8 +1251,6 @@
 	pAd->CommonCfg.BandState = UNKNOWN_BAND;
 }
 
-
-#ifdef DOT11_N_SUPPORT
 /*
 	========================================================================
 	Routine Description:
@@ -1492,6 +1419,16 @@
 		pAd->CommonCfg.DesiredHtPhy.RxSTBC = 0;
 	}
 
+#ifndef RT30xx
+#ifdef RT2870
+	/* Frank recommend ,If not, Tx maybe block in high power. Rx has no problem*/
+	if(IS_RT3070(pAd) && ((pAd->RfIcType == RFIC_3020) || (pAd->RfIcType == RFIC_2020)))
+	{
+		pAd->CommonCfg.HtCapability.HtCapInfo.TxSTBC = 0;
+		pAd->CommonCfg.DesiredHtPhy.TxSTBC = 0;
+	}
+#endif // RT2870 //
+#endif
 
 	if(pHTPhyMode->SHORTGI == GI_400)
 	{
@@ -1539,14 +1476,7 @@
 	}
 	AsicSetEdcaParm(pAd, &pAd->CommonCfg.APEdcaParm);
 
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		RTMPSetIndividualHT(pAd, 0);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
+	RTMPSetIndividualHT(pAd, 0);
 }
 
 /*
@@ -1571,16 +1501,12 @@
 
 	do
 	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			pDesired_ht_phy = &pAd->StaCfg.DesiredHtPhyInfo;
 			DesiredMcs = pAd->StaCfg.DesiredTransmitSetting.field.MCS;
 			//pAd->StaCfg.bAutoTxRateSwitch = (DesiredMcs == MCS_AUTO) ? TRUE : FALSE;
 				break;
 		}
-#endif // CONFIG_STA_SUPPORT //
 	} while (FALSE);
 
 	if (pDesired_ht_phy == NULL)
@@ -1710,7 +1636,6 @@
 
         DBGPRINT(RT_DEBUG_TRACE,("RTMPUpdateHTIE <== \n"));
 }
-#endif // DOT11_N_SUPPORT //
 
 /*
 	========================================================================
@@ -1732,8 +1657,6 @@
 	USHORT		Wcid = 0;
 
 	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			if (BssIdx > BSS0)
 			{
@@ -1748,39 +1671,22 @@
 				Wcid = pEntry->Aid;
 			else if (pEntry && INFRA_ON(pAd))
 			{
-#ifdef QOS_DLS_SUPPORT
-				if (pEntry->ValidAsDls == TRUE)
-					Wcid = pEntry->Aid;
-				else
-#endif // QOS_DLS_SUPPORT //
 				Wcid = BSSID_WCID;
 			}
 			else
 				Wcid = MCAST_WCID;
 		}
-#endif // CONFIG_STA_SUPPORT //
 	}
 
 	// Update WCID attribute table
 	offset = MAC_WCID_ATTRIBUTE_BASE + (Wcid * HW_WCID_ATTRI_SIZE);
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		if (pEntry && pEntry->ValidAsMesh)
 			WCIDAttri = (CipherAlg<<1) | PAIRWISEKEYTABLE;
-#ifdef QOS_DLS_SUPPORT
-		else if ((pEntry) && (pEntry->ValidAsDls) &&
-					((CipherAlg == CIPHER_TKIP) ||
-				 	(CipherAlg == CIPHER_TKIP_NO_MIC) ||
-					(CipherAlg == CIPHER_AES) ||
-				 	(CipherAlg == CIPHER_NONE)))
-			WCIDAttri = (CipherAlg<<1) | PAIRWISEKEYTABLE;
-#endif // QOS_DLS_SUPPORT //
 		else
 			WCIDAttri = (CipherAlg<<1) | SHAREDKEYTABLE;
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	RTMP_IO_WRITE32(pAd, offset, WCIDAttri);
 
@@ -1801,7 +1707,12 @@
 	}
 
 	// For key index and ext IV bit, so only need to update the position(offset+3).
+#ifdef RT2860
 	RTMP_IO_WRITE8(pAd, offset+3, IVEIV);
+#endif
+#ifdef RT2870
+	RTUSBMultiWrite_OneByte(pAd, offset+3, &IVEIV);
+#endif // RT2870 //
 
 	DBGPRINT(RT_DEBUG_TRACE,("RTMPAddWcidAttributeEntry: WCID #%d, KeyIndex #%d, Alg=%s\n",Wcid, KeyIdx, CipherName[CipherAlg]));
 	DBGPRINT(RT_DEBUG_TRACE,("	WCIDAttri = 0x%x \n",  WCIDAttri));
@@ -1864,7 +1775,6 @@
     	return "UNKNOW";
 }
 
-#if 1 //#ifndef UCOS
 /*
     ==========================================================================
     Description:
@@ -1912,11 +1822,10 @@
 	    "Ch", "SSID", "BSSID", "Enc", "Auth", "Siganl(%)", "W-Mode", " NT");
 
 	WaitCnt = 0;
-#ifdef CONFIG_STA_SUPPORT
 	pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
+
 	while ((ScanRunning(pAdapter) == TRUE) && (WaitCnt++ < 200))
 		OS_WAIT(500);
-#endif // CONFIG_STA_SUPPORT //
 
 	for(i=0; i<pAdapter->ScanTab.BssNr ;i++)
 	{
@@ -1982,9 +1891,7 @@
         sprintf(msg+strlen(msg),"\n");
 	}
 
-#ifdef CONFIG_STA_SUPPORT
 	pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-#endif // CONFIG_STA_SUPPORT //
 	wrq->u.data.length = strlen(msg);
 	Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
 
@@ -2010,9 +1917,7 @@
 			COPY_MAC_ADDR(MacTab.Entry[MacTab.Num].Addr, &pAd->MacTab.Content[i].Addr);
 			MacTab.Entry[MacTab.Num].Aid = (UCHAR)pAd->MacTab.Content[i].Aid;
 			MacTab.Entry[MacTab.Num].Psm = pAd->MacTab.Content[i].PsMode;
-#ifdef DOT11_N_SUPPORT
 			MacTab.Entry[MacTab.Num].MimoPs = pAd->MacTab.Content[i].MmpsMode;
-#endif // DOT11_N_SUPPORT //
 
 			// Fill in RSSI per entry
 			MacTab.Entry[MacTab.Num].AvgRssi0 = pAd->MacTab.Content[i].RssiSample.AvgRssi0;
@@ -2072,9 +1977,7 @@
 
 	kfree(msg);
 }
-#endif // UCOS //
 
-#ifdef DOT11_N_SUPPORT
 INT	Set_BASetup_Proc(
 	IN	PRTMP_ADAPTER	pAd,
 	IN	PUCHAR			arg)
@@ -2089,7 +1992,6 @@
 		=>The six 2 digit hex-decimal number previous are the Mac address,
 		=>The seventh decimal number is the tid value.
 */
-	//printk("\n%s\n", arg);
 
 	if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and tid value in decimal format.
 		return FALSE;
@@ -2283,9 +2185,7 @@
 	IN	PUCHAR			arg)
 {
 	ULONG HtMcs, Mcs_tmp;
-#ifdef CONFIG_STA_SUPPORT
     BOOLEAN bAutoRate = FALSE;
-#endif // CONFIG_STA_SUPPORT //
 
 	Mcs_tmp = simple_strtol(arg, 0, 10);
 
@@ -2294,8 +2194,6 @@
 	else
 		HtMcs = MCS_AUTO;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		pAd->StaCfg.DesiredTransmitSetting.field.MCS = HtMcs;
 		pAd->StaCfg.bAutoTxRateSwitch = (HtMcs == MCS_AUTO) ? TRUE:FALSE;
@@ -2330,7 +2228,6 @@
         if (ADHOC_ON(pAd))
             return TRUE;
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	SetCommonHT(pAd);
 
@@ -2592,13 +2489,26 @@
 
 	Value = simple_strtol(arg, 0, 10);
 	if (Value == 0)
+	{
 		pAd->CommonCfg.BACapability.field.AutoBA = FALSE;
+#ifdef RT30xx
+		pAd->CommonCfg.BACapability.field.Policy = BA_NOTUSE;
+#endif
+	}
     else if (Value == 1)
+	{
 		pAd->CommonCfg.BACapability.field.AutoBA = TRUE;
+#ifdef RT30xx
+		pAd->CommonCfg.BACapability.field.Policy = IMMED_BA;
+#endif
+	}
 	else
 		return FALSE; //Invalid argument
 
     pAd->CommonCfg.REGBACapability.field.AutoBA = pAd->CommonCfg.BACapability.field.AutoBA;
+#ifdef RT30xx
+    pAd->CommonCfg.REGBACapability.field.Policy = pAd->CommonCfg.BACapability.field.Policy;
+#endif
 	SetCommonHT(pAd);
 
 	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtAutoBa_Proc::(HtAutoBa=%d)\n",pAd->CommonCfg.BACapability.field.AutoBA));
@@ -2762,10 +2672,7 @@
 
 	return TRUE;
 }
-#endif // DOT11_N_SUPPORT //
 
-
-#ifdef DOT11_N_SUPPORT
 INT	SetCommonHT(
 	IN	PRTMP_ADAPTER	pAd)
 {
@@ -2787,7 +2694,6 @@
 
 	return TRUE;
 }
-#endif // DOT11_N_SUPPORT //
 
 INT	Set_FixedTxMode_Proc(
 	IN	PRTMP_ADAPTER	pAd,
@@ -2804,45 +2710,13 @@
         fix_tx_mode = FIXED_TXMODE_CCK;
 	}
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode = fix_tx_mode;
-#endif // CONFIG_STA_SUPPORT //
+	pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode = fix_tx_mode;
 
 	DBGPRINT(RT_DEBUG_TRACE, ("Set_FixedTxMode_Proc::(FixedTxMode=%d)\n", fix_tx_mode));
 
 	return TRUE;
 }
 
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-INT	Set_OpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Can not switch operate mode on interface up !! \n"));
-		return FALSE;
-	}
-
-	if (Value == 0)
-		pAd->OpMode = OPMODE_STA;
-	else if (Value == 1)
-		pAd->OpMode = OPMODE_AP;
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_OpMode_Proc::(OpMode=%s)\n", pAd->OpMode == 1 ? "AP Mode" : "STA Mode"));
-
-	return TRUE;
-}
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-
 /////////////////////////////////////////////////////////////////////////
 PCHAR   RTMPGetRalinkAuthModeStr(
     IN  NDIS_802_11_AUTHENTICATION_MODE authMode)
@@ -2851,7 +2725,9 @@
 	{
 		case Ndis802_11AuthModeOpen:
 			return "OPEN";
+#if defined(RT2860) || defined(RT30xx)
         default:
+#endif
 		case Ndis802_11AuthModeWPAPSK:
 			return "WPAPSK";
 		case Ndis802_11AuthModeShared:
@@ -2866,8 +2742,14 @@
 			return "WPAPSKWPA2PSK";
         case Ndis802_11AuthModeWPA1WPA2:
 			return "WPA1WPA2";
+#ifndef RT30xx
 		case Ndis802_11AuthModeWPANone:
 			return "WPANONE";
+#ifdef RT2870
+		default:
+			return "UNKNOW";
+#endif
+#endif
 	}
 }
 
@@ -2876,7 +2758,9 @@
 {
 	switch(encryMode)
 	{
+#if defined(RT2860) || defined(RT30xx)
 	    default:
+#endif
 		case Ndis802_11WEPDisabled:
 			return "NONE";
 		case Ndis802_11WEPEnabled:
@@ -2887,6 +2771,10 @@
 			return "AES";
         case Ndis802_11Encryption4Enabled:
 			return "TKIPAES";
+#if !defined(RT2860) && !defined(RT30xx)
+		default:
+			return "UNKNOW";
+#endif
 	}
 }
 
@@ -2911,7 +2799,7 @@
 	{
 		sprintf(pBuf, "\n");
 		for (PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC = RTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC; PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name; PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC++)
-			sprintf(pBuf, "%s%s\n", pBuf, PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name);
+			sprintf(pBuf + strlen(pBuf), "%s\n", PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name);
 	}
 
 	return Status;
@@ -2921,11 +2809,7 @@
 	IN	PRTMP_ADAPTER	pAd,
 	OUT	PUCHAR			pBuf)
 {
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		sprintf(pBuf, "\t%s", pAd->CommonCfg.Ssid);
-#endif // CONFIG_STA_SUPPORT //
+	sprintf(pBuf, "\t%s", pAd->CommonCfg.Ssid);
 	return 0;
 }
 
@@ -2950,7 +2834,6 @@
 		case PHY_11G:
 			sprintf(pBuf, "\t11G");
 			break;
-#ifdef DOT11_N_SUPPORT
 		case PHY_11ABGN_MIXED:
 			sprintf(pBuf, "\t11A/B/G/N");
 			break;
@@ -2972,7 +2855,6 @@
 		case PHY_11N_5G:
 			sprintf(pBuf, "\t11N only with 5G");
 			break;
-#endif // DOT11_N_SUPPORT //
 		default:
 			sprintf(pBuf, "\tUnknow Value(%d)", pAd->CommonCfg.PhyMode);
 			break;
@@ -3066,7 +2948,6 @@
 	return 0;
 }
 
-#ifdef DOT11_N_SUPPORT
 INT	Show_HtBw_Proc(
 	IN	PRTMP_ADAPTER	pAd,
 	OUT	PUCHAR			pBuf)
@@ -3086,11 +2967,7 @@
 	IN	PRTMP_ADAPTER	pAd,
 	OUT	PUCHAR			pBuf)
 {
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		sprintf(pBuf, "\t%u", pAd->StaCfg.DesiredTransmitSetting.field.MCS);
-#endif // CONFIG_STA_SUPPORT //
+	sprintf(pBuf, "\t%u", pAd->StaCfg.DesiredTransmitSetting.field.MCS);
 	return 0;
 }
 
@@ -3191,7 +3068,6 @@
 	sprintf(pBuf, "\t%s", pAd->CommonCfg.BACapability.field.AutoBA ? "TRUE":"FALSE");
 	return 0;
 }
-#endif // DOT11_N_SUPPORT //
 
 INT	Show_CountryRegion_Proc(
 	IN	PRTMP_ADAPTER	pAd,
@@ -3232,11 +3108,7 @@
 	IN	PRTMP_ADAPTER	pAd,
 	OUT	PUCHAR			pBuf)
 {
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		sprintf(pBuf, "\t%s", pAd->CommonCfg.bWmmCapable ? "TRUE":"FALSE");
-#endif // CONFIG_STA_SUPPORT //
+	sprintf(pBuf, "\t%s", pAd->CommonCfg.bWmmCapable ? "TRUE":"FALSE");
 
 	return 0;
 }
@@ -3250,7 +3122,6 @@
 	return 0;
 }
 
-#ifdef CONFIG_STA_SUPPORT
 INT	Show_NetworkType_Proc(
 	IN	PRTMP_ADAPTER	pAd,
 	OUT	PUCHAR			pBuf)
@@ -3275,7 +3146,6 @@
 	}
 	return 0;
 }
-#endif // CONFIG_STA_SUPPORT //
 
 INT	Show_AuthMode_Proc(
 	IN	PRTMP_ADAPTER	pAd,
@@ -3283,10 +3153,7 @@
 {
 	NDIS_802_11_AUTHENTICATION_MODE	AuthMode = Ndis802_11AuthModeOpen;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		AuthMode = pAd->StaCfg.AuthMode;
-#endif // CONFIG_STA_SUPPORT //
+	AuthMode = pAd->StaCfg.AuthMode;
 
 	if ((AuthMode >= Ndis802_11AuthModeOpen) &&
 		(AuthMode <= Ndis802_11AuthModeWPA1PSKWPA2PSK))
@@ -3303,10 +3170,7 @@
 {
 	NDIS_802_11_WEP_STATUS	WepStatus = Ndis802_11WEPDisabled;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		WepStatus = pAd->StaCfg.WepStatus;
-#endif // CONFIG_STA_SUPPORT //
+	WepStatus = pAd->StaCfg.WepStatus;
 
 	if ((WepStatus >= Ndis802_11WEPEnabled) &&
 		(WepStatus <= Ndis802_11Encryption4KeyAbsent))
@@ -3323,10 +3187,7 @@
 {
 	UCHAR DefaultKeyId = 0;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		DefaultKeyId = pAd->StaCfg.DefaultKeyId;
-#endif // CONFIG_STA_SUPPORT //
+	DefaultKeyId = pAd->StaCfg.DefaultKeyId;
 
 	sprintf(pBuf, "\t%d", DefaultKeyId);
 
@@ -3396,11 +3257,7 @@
 	INT 	idx;
 	UCHAR	PMK[32] = {0};
 
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		NdisMoveMemory(PMK, pAd->StaCfg.PMK, 32);
-#endif // CONFIG_STA_SUPPORT //
+	NdisMoveMemory(PMK, pAd->StaCfg.PMK, 32);
 
     sprintf(pBuf, "\tPMK = ");
     for (idx = 0; idx < 32; idx++)
diff --git a/drivers/staging/rt2860/common/cmm_sanity.c b/drivers/staging/rt2860/common/cmm_sanity.c
index b0f070d..843e44e 100644
--- a/drivers/staging/rt2860/common/cmm_sanity.c
+++ b/drivers/staging/rt2860/common/cmm_sanity.c
@@ -275,9 +275,7 @@
     OUT PQOS_CAPABILITY_PARM pQosCapability,
     OUT ULONG *pRalinkIe,
     OUT UCHAR		 *pHtCapabilityLen,
-#ifdef CONFIG_STA_SUPPORT
     OUT UCHAR		 *pPreNHtCapabilityLen,
-#endif // CONFIG_STA_SUPPORT //
     OUT HT_CAPABILITY_IE *pHtCapability,
 	OUT UCHAR		 *AddHtInfoLen,
 	OUT ADD_HT_INFO_IE *AddHtInfo,
@@ -286,9 +284,7 @@
     OUT	PNDIS_802_11_VARIABLE_IEs pVIE)
 {
     CHAR				*Ptr;
-#ifdef CONFIG_STA_SUPPORT
 	CHAR 				TimLen;
-#endif // CONFIG_STA_SUPPORT //
     PFRAME_802_11		pFrame;
     PEID_STRUCT         pEid;
     UCHAR				SubType;
@@ -316,10 +312,8 @@
     *pAironetCellPowerLimit = 0xFF;  // Default of AironetCellPowerLimit is 0xFF
     *LengthVIE = 0;					// Set the length of VIE to init value 0
     *pHtCapabilityLen = 0;					// Set the length of VIE to init value 0
-#ifdef CONFIG_STA_SUPPORT
 	if (pAd->OpMode == OPMODE_STA)
 		*pPreNHtCapabilityLen = 0;					// Set the length of VIE to init value 0
-#endif // CONFIG_STA_SUPPORT //
     *AddHtInfoLen = 0;					// Set the length of VIE to init value 0
     *pRalinkIe = 0;
     *pNewChannel = 0;
@@ -428,8 +422,6 @@
 				*(USHORT *)(&pHtCapability->HtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->HtCapInfo));
 				*(USHORT *)(&pHtCapability->ExtHtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->ExtHtCapInfo));
 
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 				{
 					*pPreNHtCapabilityLen = 0;	// Nnow we only support 26 bytes.
 
@@ -437,7 +429,6 @@
 					NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
 					*LengthVIE += (pEid->Len + 2);
 				}
-#endif // CONFIG_STA_SUPPORT //
 			}
 			else
 			{
@@ -458,14 +449,11 @@
 				*(USHORT *)(&AddHtInfo->AddHtInfo2) = cpu2le16(*(USHORT *)(&AddHtInfo->AddHtInfo2));
 				*(USHORT *)(&AddHtInfo->AddHtInfo3) = cpu2le16(*(USHORT *)(&AddHtInfo->AddHtInfo3));
 
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 				{
 			                Ptr = (PUCHAR) pVIE;
 			                NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
 			                *LengthVIE += (pEid->Len + 2);
 				}
-#endif // CONFIG_STA_SUPPORT //
 			}
 			else
 			{
@@ -492,8 +480,7 @@
                 if(pEid->Len == 1)
                 {
                     *pChannel = *pEid->Octet;
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+
 					{
 						if (ChannelSanity(pAd, *pChannel) == 0)
 						{
@@ -501,7 +488,7 @@
 							return FALSE;
 						}
 					}
-#endif // CONFIG_STA_SUPPORT //
+
                     Sanity |= 0x4;
                 }
                 else
@@ -539,14 +526,13 @@
                 }
                 break;
 
-#ifdef CONFIG_STA_SUPPORT
             case IE_TIM:
                 if(INFRA_ON(pAd) && SubType == SUBTYPE_BEACON)
                 {
                     GetTimBit((PUCHAR)pEid, pAd->StaActive.Aid, &TimLen, pBcastFlag, pDtimCount, pDtimPeriod, pMessageToMe);
                 }
                 break;
-#endif // CONFIG_STA_SUPPORT //
+
             case IE_CHANNEL_SWITCH_ANNOUNCEMENT:
                 if(pEid->Len == 3)
                 {
@@ -568,8 +554,6 @@
         			else
         				*pRalinkIe = 0xf0000000; // Set to non-zero value (can't set bit0-2) to represent this is Ralink Chip. So at linkup, we will set ralinkchip flag.
                 }
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
 		// This HT IE is before IEEE draft set HT IE value.2006-09-28 by Jan.
 
                 // Other vendors had production before IE_HT_CAP value is assigned. To backward support those old-firmware AP,
@@ -588,8 +572,6 @@
                         *AddHtInfoLen = SIZE_ADD_HT_INFO_IE;
                     }
                 }
-#endif // DOT11_N_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
                 else if (NdisEqualMemory(pEid->Octet, WPA_OUI, 4))
                 {
                     // Copy to pVIE which will report to microsoft bssid list.
@@ -712,15 +694,6 @@
                     *LengthVIE += (pEid->Len + 2);
                 }
                 break;
-#ifdef CONFIG_STA_SUPPORT
-#ifdef EXT_BUILD_CHANNEL_LIST
-			case IE_COUNTRY:
-				Ptr = (PUCHAR) pVIE;
-                NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
-                *LengthVIE += (pEid->Len + 2);
-				break;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
 
             default:
                 break;
@@ -731,8 +704,6 @@
     }
 
     // For some 11a AP. it did not have the channel EID, patch here
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		UCHAR LatchRfChannel = MsgChannel;
 		if ((pAd->LatchRfRegs.Channel > 14) && ((Sanity & 0x4) == 0))
@@ -744,7 +715,6 @@
 			Sanity |= 0x4;
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	if (Sanity != 0x7)
 	{
@@ -758,76 +728,6 @@
 
 }
 
-#ifdef DOT11N_DRAFT3
-/*
-	==========================================================================
-	Description:
-		MLME message sanity check for some IE addressed  in 802.11n d3.03.
-	Return:
-		TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-BOOLEAN PeerBeaconAndProbeRspSanity2(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *Msg,
-	IN ULONG MsgLen,
-	OUT UCHAR 	*RegClass)
-{
-	CHAR				*Ptr;
-	PFRAME_802_11		pFrame;
-	PEID_STRUCT			pEid;
-	ULONG				Length = 0;
-
-	pFrame = (PFRAME_802_11)Msg;
-
-	*RegClass = 0;
-	Ptr = pFrame->Octet;
-	Length += LENGTH_802_11;
-
-	// get timestamp from payload and advance the pointer
-	Ptr += TIMESTAMP_LEN;
-	Length += TIMESTAMP_LEN;
-
-	// get beacon interval from payload and advance the pointer
-	Ptr += 2;
-	Length += 2;
-
-	// get capability info from payload and advance the pointer
-	Ptr += 2;
-	Length += 2;
-
-	pEid = (PEID_STRUCT) Ptr;
-
-	// get variable fields from payload and advance the pointer
-	while ((Length + 2 + pEid->Len) <= MsgLen)
-	{
-		switch(pEid->Eid)
-		{
-			case IE_SUPP_REG_CLASS:
-				if(pEid->Len > 0)
-				{
-					*RegClass = *pEid->Octet;
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_SSID (len=%d)\n",pEid->Len));
-					return FALSE;
-				}
-				break;
-		}
-
-		Length = Length + 2 + pEid->Len;  // Eid[1] + Len[1]+ content[Len]
-		pEid = (PEID_STRUCT)((UCHAR*)pEid + 2 + pEid->Len);
-	}
-
-	return TRUE;
-
-}
-#endif // DOT11N_DRAFT3 //
-
 /*
     ==========================================================================
     Description:
@@ -855,10 +755,8 @@
 
 	if ((*pBssType == BSS_INFRA || *pBssType == BSS_ADHOC || *pBssType == BSS_ANY)
 		&& (*pScanType == SCAN_ACTIVE || *pScanType == SCAN_PASSIVE
-#ifdef CONFIG_STA_SUPPORT
 		|| *pScanType == SCAN_CISCO_PASSIVE || *pScanType == SCAN_CISCO_ACTIVE
 		|| *pScanType == SCAN_CISCO_CHANNEL_LOAD || *pScanType == SCAN_CISCO_NOISE
-#endif // CONFIG_STA_SUPPORT //
 		))
 	{
 		return TRUE;
@@ -940,9 +838,6 @@
     NdisMoveMemory(pStatus, &pFrame->Octet[4], 2);
 
     if ((*pAlg == Ndis802_11AuthModeOpen)
-#ifdef LEAP_SUPPORT
-      || (*pAlg == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
       )
     {
         if (*pSeq == 1 || *pSeq == 2)
@@ -1003,9 +898,6 @@
     *pAlg = pInfo->Alg;
 
     if (((*pAlg == Ndis802_11AuthModeShared) ||(*pAlg == Ndis802_11AuthModeOpen)
-#ifdef LEAP_SUPPORT
-     || (*pAlg == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
      	) &&
         ((*pAddr & 0x01) == 0))
     {
@@ -1344,290 +1236,3 @@
 	return TRUE;
 
 }
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-BOOLEAN MlmeDlsReqSanity(
-	IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PRT_802_11_DLS *pDLS,
-    OUT PUSHORT pReason)
-{
-	MLME_DLS_REQ_STRUCT *pInfo;
-
-    pInfo = (MLME_DLS_REQ_STRUCT *)Msg;
-
-	*pDLS = pInfo->pDLS;
-	*pReason = pInfo->Reason;
-
-	return TRUE;
-}
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef QOS_DLS_SUPPORT
-BOOLEAN PeerDlsReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pDlsTimeout,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-	OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability)
-{
-	CHAR            *Ptr;
-    PFRAME_802_11	Fr = (PFRAME_802_11)Msg;
-	PEID_STRUCT  eid_ptr;
-
-    // to prevent caller from using garbage output value
-    *pCapabilityInfo	= 0;
-    *pDlsTimeout	= 0;
-	*pHtCapabilityLen = 0;
-
-    Ptr = Fr->Octet;
-
-	// offset to destination MAC address (Category and Action field)
-    Ptr += 2;
-
-    // get DA from payload and advance the pointer
-    NdisMoveMemory(pDA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get SA from payload and advance the pointer
-    NdisMoveMemory(pSA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get capability info from payload and advance the pointer
-    NdisMoveMemory(pCapabilityInfo, Ptr, 2);
-    Ptr += 2;
-
-    // get capability info from payload and advance the pointer
-    NdisMoveMemory(pDlsTimeout, Ptr, 2);
-    Ptr += 2;
-
-	// Category and Action field + DA + SA + capability + Timeout
-	eid_ptr = (PEID_STRUCT) &Fr->Octet[18];
-
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((UCHAR*)Fr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_SUPP_RATES:
-                if ((eid_ptr->Len <= MAX_LEN_OF_SUPPORTED_RATES) && (eid_ptr->Len > 0))
-                {
-                    NdisMoveMemory(Rates, eid_ptr->Octet, eid_ptr->Len);
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - IE_SUPP_RATES., Len=%d. Rates[0]=%x\n",eid_ptr->Len, Rates[0]));
-                    DBGPRINT(RT_DEBUG_TRACE, ("Rates[1]=%x %x %x %x %x %x %x\n", Rates[1], Rates[2], Rates[3], Rates[4], Rates[5], Rates[6], Rates[7]));
-                    *pRatesLen = eid_ptr->Len;
-                }
-                else
-                {
-                    *pRatesLen = 8;
-					Rates[0] = 0x82;
-					Rates[1] = 0x84;
-					Rates[2] = 0x8b;
-					Rates[3] = 0x96;
-					Rates[4] = 0x12;
-					Rates[5] = 0x24;
-					Rates[6] = 0x48;
-					Rates[7] = 0x6c;
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - wrong IE_SUPP_RATES., Len=%d\n",eid_ptr->Len));
-                }
-				break;
-
-			case IE_EXT_SUPP_RATES:
-                if (eid_ptr->Len + *pRatesLen <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, eid_ptr->Len);
-                    *pRatesLen = (*pRatesLen) + eid_ptr->Len;
-                }
-                else
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, MAX_LEN_OF_SUPPORTED_RATES - (*pRatesLen));
-                    *pRatesLen = MAX_LEN_OF_SUPPORTED_RATES;
-                }
-				break;
-
-			case IE_HT_CAP:
-				if (eid_ptr->Len >= sizeof(HT_CAPABILITY_IE))
-				{
-					NdisMoveMemory(pHtCapability, eid_ptr->Octet, sizeof(HT_CAPABILITY_IE));
-
-					*(USHORT *)(&pHtCapability->HtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->HtCapInfo));
-					*(USHORT *)(&pHtCapability->ExtHtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->ExtHtCapInfo));
-					*pHtCapabilityLen = sizeof(HT_CAPABILITY_IE);
-
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - IE_HT_CAP\n"));
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - wrong IE_HT_CAP.eid_ptr->Len = %d\n", eid_ptr->Len));
-				}
-				break;
-
-			default:
-				break;
-		}
-
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-    return TRUE;
-}
-
-BOOLEAN PeerDlsRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pStatus,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-    OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability)
-{
-    CHAR            *Ptr;
-    PFRAME_802_11	Fr = (PFRAME_802_11)Msg;
-	PEID_STRUCT  eid_ptr;
-
-    // to prevent caller from using garbage output value
-    *pStatus		= 0;
-    *pCapabilityInfo	= 0;
-	*pHtCapabilityLen = 0;
-
-    Ptr = Fr->Octet;
-
-	// offset to destination MAC address (Category and Action field)
-    Ptr += 2;
-
-	// get status code from payload and advance the pointer
-    NdisMoveMemory(pStatus, Ptr, 2);
-    Ptr += 2;
-
-    // get DA from payload and advance the pointer
-    NdisMoveMemory(pDA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get SA from payload and advance the pointer
-    NdisMoveMemory(pSA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-	if (pStatus == 0)
-	{
-	    // get capability info from payload and advance the pointer
-	    NdisMoveMemory(pCapabilityInfo, Ptr, 2);
-	    Ptr += 2;
-	}
-
-	// Category and Action field + status code + DA + SA + capability
-	eid_ptr = (PEID_STRUCT) &Fr->Octet[18];
-
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((UCHAR*)Fr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_SUPP_RATES:
-                if ((eid_ptr->Len <= MAX_LEN_OF_SUPPORTED_RATES) && (eid_ptr->Len > 0))
-                {
-                    NdisMoveMemory(Rates, eid_ptr->Octet, eid_ptr->Len);
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - IE_SUPP_RATES., Len=%d. Rates[0]=%x\n",eid_ptr->Len, Rates[0]));
-                    DBGPRINT(RT_DEBUG_TRACE, ("Rates[1]=%x %x %x %x %x %x %x\n", Rates[1], Rates[2], Rates[3], Rates[4], Rates[5], Rates[6], Rates[7]));
-                    *pRatesLen = eid_ptr->Len;
-                }
-                else
-                {
-                    *pRatesLen = 8;
-					Rates[0] = 0x82;
-					Rates[1] = 0x84;
-					Rates[2] = 0x8b;
-					Rates[3] = 0x96;
-					Rates[4] = 0x12;
-					Rates[5] = 0x24;
-					Rates[6] = 0x48;
-					Rates[7] = 0x6c;
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - wrong IE_SUPP_RATES., Len=%d\n",eid_ptr->Len));
-                }
-				break;
-
-			case IE_EXT_SUPP_RATES:
-                if (eid_ptr->Len + *pRatesLen <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, eid_ptr->Len);
-                    *pRatesLen = (*pRatesLen) + eid_ptr->Len;
-                }
-                else
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, MAX_LEN_OF_SUPPORTED_RATES - (*pRatesLen));
-                    *pRatesLen = MAX_LEN_OF_SUPPORTED_RATES;
-                }
-				break;
-
-			case IE_HT_CAP:
-				if (eid_ptr->Len >= sizeof(HT_CAPABILITY_IE))
-				{
-					NdisMoveMemory(pHtCapability, eid_ptr->Octet, sizeof(HT_CAPABILITY_IE));
-
-					*(USHORT *)(&pHtCapability->HtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->HtCapInfo));
-					*(USHORT *)(&pHtCapability->ExtHtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->ExtHtCapInfo));
-					*pHtCapabilityLen = sizeof(HT_CAPABILITY_IE);
-
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - IE_HT_CAP\n"));
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - wrong IE_HT_CAP.eid_ptr->Len = %d\n", eid_ptr->Len));
-				}
-				break;
-
-			default:
-				break;
-		}
-
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-    return TRUE;
-}
-
-BOOLEAN PeerDlsTearDownSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pReason)
-{
-    CHAR            *Ptr;
-    PFRAME_802_11	Fr = (PFRAME_802_11)Msg;
-
-    // to prevent caller from using garbage output value
-    *pReason	= 0;
-
-    Ptr = Fr->Octet;
-
-	// offset to destination MAC address (Category and Action field)
-    Ptr += 2;
-
-    // get DA from payload and advance the pointer
-    NdisMoveMemory(pDA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get SA from payload and advance the pointer
-    NdisMoveMemory(pSA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-	// get reason code from payload and advance the pointer
-    NdisMoveMemory(pReason, Ptr, 2);
-    Ptr += 2;
-
-    return TRUE;
-}
-#endif // QOS_DLS_SUPPORT //
-
diff --git a/drivers/staging/rt2860/common/cmm_sync.c b/drivers/staging/rt2860/common/cmm_sync.c
index d29e0b6..a6e1b6d 100644
--- a/drivers/staging/rt2860/common/cmm_sync.c
+++ b/drivers/staging/rt2860/common/cmm_sync.c
@@ -95,9 +95,7 @@
 
 	// if not 11a-only mode, channel list starts from 2.4Ghz band
 	if ((pAd->CommonCfg.PhyMode != PHY_11A)
-#ifdef DOT11_N_SUPPORT
 		&& (pAd->CommonCfg.PhyMode != PHY_11AN_MIXED) && (pAd->CommonCfg.PhyMode != PHY_11N_5G)
-#endif // DOT11_N_SUPPORT //
 	)
 	{
 		switch (pAd->CommonCfg.CountryRegion  & 0x7f)
@@ -146,10 +144,8 @@
 	}
 
 	if ((pAd->CommonCfg.PhyMode == PHY_11A) || (pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED)
-#ifdef DOT11_N_SUPPORT
 		|| (pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED) || (pAd->CommonCfg.PhyMode == PHY_11AN_MIXED)
 		|| (pAd->CommonCfg.PhyMode == PHY_11AGN_MIXED) || (pAd->CommonCfg.PhyMode == PHY_11N_5G)
-#endif // DOT11_N_SUPPORT //
 	)
 	{
 		switch (pAd->CommonCfg.CountryRegionForABand & 0x7f)
@@ -383,33 +379,18 @@
 	NDIS_STATUS     NStatus;
 	ULONG           FrameLen = 0;
 	UCHAR           SsidLen = 0, ScanType = pAd->MlmeAux.ScanType, BBPValue = 0;
-#ifdef CONFIG_STA_SUPPORT
 	USHORT          Status;
 	PHEADER_802_11  pHdr80211;
-#endif // CONFIG_STA_SUPPORT //
 	UINT			ScanTimeIn5gChannel = SHORT_CHANNEL_TIME;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (MONITOR_ON(pAd))
-			return;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef RALINK_ATE
-	// Nothing to do in ATE mode.
-	if (ATE_ON(pAd))
+	if (MONITOR_ON(pAd))
 		return;
-#endif // RALINK_ATE //
 
 	if (pAd->MlmeAux.Channel == 0)
 	{
 		if ((pAd->CommonCfg.BBPCurrentBW == BW_40)
-#ifdef CONFIG_STA_SUPPORT
 			&& (INFRA_ON(pAd)
 				|| (pAd->OpMode == OPMODE_AP))
-#endif // CONFIG_STA_SUPPORT //
 			)
 		{
 			AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
@@ -427,8 +408,6 @@
 			DBGPRINT(RT_DEBUG_TRACE, ("SYNC - End of SCAN, restore to channel %d, Total BSS[%02d]\n",pAd->CommonCfg.Channel, pAd->ScanTab.BssNr));
 		}
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			//
 			// To prevent data lost.
@@ -458,31 +437,35 @@
 			Status = MLME_SUCCESS;
 			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status);
 		}
-#endif // CONFIG_STA_SUPPORT //
-
 
 		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
 	}
+#ifdef RT2870
+	else if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST) && (pAd->OpMode == OPMODE_STA))
+	{
+		pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
+		MlmeCntlConfirm(pAd, MT2_SCAN_CONF, MLME_FAIL_NO_RESOURCE);
+	}
+#endif // RT2870 //
 	else
 	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 		// BBP and RF are not accessible in PS mode, we has to wake them up first
 		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
+#ifdef RT2860
 				AsicForceWakeup(pAd, FROM_TX);
-
+#endif
+#ifdef RT2870
+			AsicForceWakeup(pAd, TRUE);
+#endif
 			// leave PSM during scanning. otherwise we may lost ProbeRsp & BEACON
 			if (pAd->StaCfg.Psm == PWR_SAVE)
 				MlmeSetPsmBit(pAd, PWR_ACTIVE);
 		}
-#endif // CONFIG_STA_SUPPORT //
 
 		AsicSwitchChannel(pAd, pAd->MlmeAux.Channel, TRUE);
 		AsicLockChannel(pAd, pAd->MlmeAux.Channel);
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			if (pAd->MlmeAux.Channel > 14)
 			{
@@ -492,19 +475,8 @@
 					ScanTimeIn5gChannel = MIN_CHANNEL_TIME;
 				}
 			}
-
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-			// carrier detection
-			if (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-			{
-				ScanType = SCAN_PASSIVE;
-				ScanTimeIn5gChannel = MIN_CHANNEL_TIME;
-			}
-#endif // CARRIER_DETECTION_SUPPORT //
 		}
 
-#endif // CONFIG_STA_SUPPORT //
-
 		//Global country domain(ch1-11:active scan, ch12-14 passive scan)
 		if ((pAd->MlmeAux.Channel <= 14) && (pAd->MlmeAux.Channel >= 12) && ((pAd->CommonCfg.CountryRegion & 0x7f) == REGION_31_BG_BAND))
 		{
@@ -515,7 +487,6 @@
 		// Chnage the channel scan time for CISCO stuff based on its IAPP announcement
 		if (ScanType == FAST_SCAN_ACTIVE)
 			RTMPSetTimer(&pAd->MlmeAux.ScanTimer, FAST_ACTIVE_SCAN_TIME);
-#ifdef CONFIG_STA_SUPPORT
 		else if (((ScanType == SCAN_CISCO_ACTIVE) ||
 				(ScanType == SCAN_CISCO_PASSIVE) ||
 				(ScanType == SCAN_CISCO_CHANNEL_LOAD) ||
@@ -526,13 +497,10 @@
 			else
 				RTMPSetTimer(&pAd->MlmeAux.ScanTimer, pAd->StaCfg.CCXScanTime);
 		}
-#endif // CONFIG_STA_SUPPORT //
 		else // must be SCAN_PASSIVE or SCAN_ACTIVE
 		{
 			if ((pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED)
-#ifdef DOT11_N_SUPPORT
 				|| (pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED) || (pAd->CommonCfg.PhyMode == PHY_11AGN_MIXED)
-#endif // DOT11_N_SUPPORT //
 			)
 			{
 				if (pAd->MlmeAux.Channel > 14)
@@ -551,14 +519,12 @@
 			if (NStatus != NDIS_STATUS_SUCCESS)
 			{
 				DBGPRINT(RT_DEBUG_TRACE, ("SYNC - ScanNextChannel() allocate memory fail\n"));
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+
 				{
 					pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
 					Status = MLME_FAIL_NO_RESOURCE;
 					MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status);
 				}
-#endif // CONFIG_STA_SUPPORT //
 
 				return;
 			}
@@ -592,78 +558,35 @@
 				FrameLen += Tmp;
 			}
 
-#ifdef DOT11_N_SUPPORT
 			if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
 			{
 				ULONG	Tmp;
 				UCHAR	HtLen;
 				UCHAR	BROADCOM[4] = {0x0, 0x90, 0x4c, 0x33};
-#ifdef RT_BIG_ENDIAN
-				HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
+
 				if (pAd->bBroadComHT == TRUE)
 				{
 					HtLen = pAd->MlmeAux.HtCapabilityLen + 4;
-#ifdef RT_BIG_ENDIAN
-					NdisMoveMemory(&HtCapabilityTmp, &pAd->MlmeAux.HtCapability, SIZE_HT_CAP_IE);
-					*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-					*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
 
 					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
 									1,                                &WpaIe,
 									1,                                &HtLen,
 									4,                                &BROADCOM[0],
-									pAd->MlmeAux.HtCapabilityLen,     &HtCapabilityTmp,
-									END_OF_ARGS);
-#else
-					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
-									1,                                &WpaIe,
-									1,                                &HtLen,
-									4,                                &BROADCOM[0],
 									pAd->MlmeAux.HtCapabilityLen,     &pAd->MlmeAux.HtCapability,
 									END_OF_ARGS);
-#endif // RT_BIG_ENDIAN //
 				}
 				else
 				{
 					HtLen = pAd->MlmeAux.HtCapabilityLen;
-#ifdef RT_BIG_ENDIAN
-					NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, SIZE_HT_CAP_IE);
-					*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-					*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
 
 					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
 									1,                                &HtCapIe,
 									1,                                &HtLen,
-									HtLen,                            &HtCapabilityTmp,
-									END_OF_ARGS);
-#else
-					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
-									1,                                &HtCapIe,
-									1,                                &HtLen,
 									HtLen,                            &pAd->CommonCfg.HtCapability,
 									END_OF_ARGS);
-#endif // RT_BIG_ENDIAN //
 				}
 				FrameLen += Tmp;
-
-#ifdef DOT11N_DRAFT3
-				if (pAd->CommonCfg.BACapability.field.b2040CoexistScanSup == 1)
-				{
-					ULONG		Tmp;
-					HtLen = 1;
-					MakeOutgoingFrame(pOutBuffer + FrameLen,            &Tmp,
-									  1,					&ExtHtCapIe,
-									  1,					&HtLen,
-									  1,          			&pAd->CommonCfg.BSSCoexist2040.word,
-									  END_OF_ARGS);
-
-					FrameLen += Tmp;
-				}
-#endif // DOT11N_DRAFT3 //
 			}
-#endif // DOT11_N_SUPPORT //
-
 
 			MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
 			MlmeFreeMemory(pAd, pOutBuffer);
@@ -671,11 +594,7 @@
 
 		// For SCAN_CISCO_PASSIVE, do nothing and silently wait for beacon or other probe reponse
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			pAd->Mlme.SyncMachine.CurrState = SCAN_LISTEN;
-#endif // CONFIG_STA_SUPPORT //
-
+		pAd->Mlme.SyncMachine.CurrState = SCAN_LISTEN;
 	}
 }
 
diff --git a/drivers/staging/rt2860/common/cmm_wpa.c b/drivers/staging/rt2860/common/cmm_wpa.c
index 69baf52..bda69e7 100644
--- a/drivers/staging/rt2860/common/cmm_wpa.c
+++ b/drivers/staging/rt2860/common/cmm_wpa.c
@@ -39,10 +39,14 @@
 // WPA OUI
 UCHAR		OUI_WPA_NONE_AKM[4]		= {0x00, 0x50, 0xF2, 0x00};
 UCHAR       OUI_WPA_VERSION[4]      = {0x00, 0x50, 0xF2, 0x01};
+#ifndef RT30xx
 UCHAR       OUI_WPA_WEP40[4]      = {0x00, 0x50, 0xF2, 0x01};
+#endif
 UCHAR       OUI_WPA_TKIP[4]     = {0x00, 0x50, 0xF2, 0x02};
 UCHAR       OUI_WPA_CCMP[4]     = {0x00, 0x50, 0xF2, 0x04};
+#ifndef RT30xx
 UCHAR       OUI_WPA_WEP104[4]      = {0x00, 0x50, 0xF2, 0x05};
+#endif
 UCHAR       OUI_WPA_8021X_AKM[4]	= {0x00, 0x50, 0xF2, 0x01};
 UCHAR       OUI_WPA_PSK_AKM[4]      = {0x00, 0x50, 0xF2, 0x02};
 // WPA2 OUI
@@ -51,7 +55,9 @@
 UCHAR       OUI_WPA2_CCMP[4]        = {0x00, 0x0F, 0xAC, 0x04};
 UCHAR       OUI_WPA2_8021X_AKM[4]   = {0x00, 0x0F, 0xAC, 0x01};
 UCHAR       OUI_WPA2_PSK_AKM[4]   	= {0x00, 0x0F, 0xAC, 0x02};
+#ifndef RT30xx
 UCHAR       OUI_WPA2_WEP104[4]   = {0x00, 0x0F, 0xAC, 0x05};
+#endif
 // MSA OUI
 UCHAR   	OUI_MSA_8021X_AKM[4]    = {0x00, 0x0F, 0xAC, 0x05};		// Not yet final - IEEE 802.11s-D1.06
 UCHAR   	OUI_MSA_PSK_AKM[4]   	= {0x00, 0x0F, 0xAC, 0x06};		// Not yet final - IEEE 802.11s-D1.06
@@ -370,7 +376,7 @@
                 break;
         }
 
-#ifdef CONFIG_STA_SUPPORT
+#ifndef RT30xx
 		if ((pAd->OpMode == OPMODE_STA) &&
 			(pAd->StaCfg.GroupCipher != Ndis802_11Encryption2Enabled) &&
 			(pAd->StaCfg.GroupCipher != Ndis802_11Encryption3Enabled))
@@ -386,8 +392,7 @@
 					break;
 			}
 		}
-#endif // CONFIG_STA_SUPPORT //
-
+#endif
 		// swap for big-endian platform
 		pRsnie_cipher->version = cpu2le16(pRsnie_cipher->version);
 	    pRsnie_cipher->ucount = cpu2le16(pRsnie_cipher->ucount);
@@ -448,7 +453,7 @@
                 break;
         }
 
-#ifdef CONFIG_STA_SUPPORT
+#ifndef RT30xx
 		if ((pAd->OpMode == OPMODE_STA) &&
 			(pAd->StaCfg.GroupCipher != Ndis802_11Encryption2Enabled) &&
 			(pAd->StaCfg.GroupCipher != Ndis802_11Encryption3Enabled))
@@ -464,8 +469,7 @@
 					break;
 			}
 		}
-#endif // CONFIG_STA_SUPPORT //
-
+#endif
 		// swap for big-endian platform
 		pRsnie_cipher->version = cpu2le16(pRsnie_cipher->version);
 	    pRsnie_cipher->ucount = cpu2le16(pRsnie_cipher->ucount);
@@ -621,23 +625,19 @@
 	UCHAR		PrimaryRsnie;
 	BOOLEAN		bMixCipher = FALSE;	// indicate the pairwise and group cipher are different
 	UCHAR		p_offset;
-	WPA_MIX_PAIR_CIPHER		FlexibleCipher = MIX_CIPHER_NOTUSE;	// it provide the more flexible cipher combination in WPA-WPA2 and TKIPAES mode
+	WPA_MIX_PAIR_CIPHER		FlexibleCipher = WPA_TKIPAES_WPA2_TKIPAES;	// it provide the more flexible cipher combination in WPA-WPA2 and TKIPAES mode
 
 	rsnielen_cur_p = NULL;
 	rsnielen_ex_cur_p = NULL;
 
 	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
-#ifdef WPA_SUPPLICANT_SUPPORT
 			if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
 			{
 				if (AuthMode < Ndis802_11AuthModeWPA)
 					return;
 			}
 			else
-#endif // WPA_SUPPLICANT_SUPPORT //
 			{
 				// Support WPAPSK or WPA2PSK in STA-Infra mode
 				// Support WPANone in STA-Adhoc mode
@@ -660,7 +660,6 @@
 
 			bMixCipher = pAd->StaCfg.bMixCipher;
 		}
-#endif // CONFIG_STA_SUPPORT //
 	}
 
 	// indicate primary RSNIE as WPA or WPA2
@@ -1131,11 +1130,6 @@
         return FALSE;
     }
 
-
-#ifdef CONFIG_STA_SUPPORT
-	// Todo
-#endif // CONFIG_STA_SUPPORT //
-
 	return TRUE;
 
 }
diff --git a/drivers/staging/rt2860/common/dfs.c b/drivers/staging/rt2860/common/dfs.c
index b09bba5..23330f2 100644
--- a/drivers/staging/rt2860/common/dfs.c
+++ b/drivers/staging/rt2860/common/dfs.c
@@ -80,18 +80,6 @@
 	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 124, 0x28);
 	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 125, 0xff);
 
-#if 0
-	// toggle Rx enable bit for radar detection.
-	// it's Andy's recommand.
-	{
-		UINT32 Value;
-	RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-	Value |= (0x1 << 3);
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-	Value &= ~(0x1 << 3);
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-	}
-#endif
 	RadarPeriod = ((UINT)RdIdleTimeTable[pAd->CommonCfg.RadarDetect.RDDurRegion][0] + (UINT)pAd->CommonCfg.RadarDetect.DfsSessionTime) < 250 ?
 			(RdIdleTimeTable[pAd->CommonCfg.RadarDetect.RDDurRegion][0] + pAd->CommonCfg.RadarDetect.DfsSessionTime) : 250;
 
@@ -314,15 +302,6 @@
 {
 	ULONG result = 0;
 
-#ifdef DFS_SUPPORT
-	UINT8 duration1 = 0, duration2 = 0, duration3 = 0;
-
-	BBP_IO_READ8_BY_REG_ID(pAd, BBP_R116, &duration1);
-	BBP_IO_READ8_BY_REG_ID(pAd, BBP_R117, &duration2);
-	BBP_IO_READ8_BY_REG_ID(pAd, BBP_R118, &duration3);
-	result = (duration1 << 16) + (duration2 << 8) + duration3;
-#endif // DFS_SUPPORT //
-
 	return result;
 
 }
diff --git a/drivers/staging/rt2860/common/eeprom.c b/drivers/staging/rt2860/common/eeprom.c
index bed2d66..9729323 100644
--- a/drivers/staging/rt2860/common/eeprom.c
+++ b/drivers/staging/rt2860/common/eeprom.c
@@ -73,12 +73,16 @@
         RaiseClock(pAd, &x);
 
         RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-
+#ifdef RT30xx
+		LowerClock(pAd, &x); //prevent read failed
+#endif
         x &= ~(EEDI);
         if(x & EEDO)
             data |= 1;
 
+#ifndef RT30xx
         LowerClock(pAd, &x);
+#endif
     }
 
     return data;
@@ -181,6 +185,15 @@
     UINT32		x;
     USHORT		data;
 
+#ifdef RT30xx
+	if (pAd->NicConfig2.field.AntDiversity)
+    {
+    	pAd->EepromAccess = TRUE;
+    }
+//2008/09/11:KH add to support efuse<--
+//2008/09/11:KH add to support efuse-->
+{
+#endif
     Offset /= 2;
     // reset bits and set EECS
     RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
@@ -188,9 +201,17 @@
     x |= EECS;
     RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
 
+#ifdef RT30xx
+	// patch can not access e-Fuse issue
+    if (!IS_RT3090(pAd))
+    {
+#endif
 	// kick a pulse
 	RaiseClock(pAd, &x);
 	LowerClock(pAd, &x);
+#ifdef RT30xx
+    }
+#endif
 
     // output the read_opcode and register number in that order
     ShiftOutBits(pAd, EEPROM_READ_OPCODE, 3);
@@ -201,6 +222,17 @@
 
     EEpromCleanup(pAd);
 
+#ifdef RT30xx
+	// Antenna and EEPROM access are both using EESK pin,
+    // Therefor we should avoid accessing EESK at the same time
+    // Then restore antenna after EEPROM access
+	if ((pAd->NicConfig2.field.AntDiversity) || (pAd->RfIcType == RFIC_3020))
+    {
+	    pAd->EepromAccess = FALSE;
+	    AsicSetRxAnt(pAd, pAd->RxAnt.Pair1PrimaryRxAnt);
+    }
+}
+#endif
     return data;
 }	//ReadEEprom
 
@@ -211,6 +243,15 @@
 {
     UINT32 x;
 
+#ifdef RT30xx
+	if (pAd->NicConfig2.field.AntDiversity)
+    {
+    	pAd->EepromAccess = TRUE;
+    }
+	//2008/09/11:KH add to support efuse<--
+//2008/09/11:KH add to support efuse-->
+	{
+#endif
 	Offset /= 2;
 
 	EWEN(pAd);
@@ -221,9 +262,17 @@
     x |= EECS;
     RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
 
+#ifdef RT30xx
+	// patch can not access e-Fuse issue
+    if (!IS_RT3090(pAd))
+    {
+#endif
 	// kick a pulse
 	RaiseClock(pAd, &x);
 	LowerClock(pAd, &x);
+#ifdef RT30xx
+    }
+#endif
 
     // output the read_opcode ,register number and data in that order
     ShiftOutBits(pAd, EEPROM_WRITE_OPCODE, 3);
@@ -240,5 +289,1222 @@
 	EWDS(pAd);
 
     EEpromCleanup(pAd);
+
+#ifdef RT30xx
+	// Antenna and EEPROM access are both using EESK pin,
+    // Therefor we should avoid accessing EESK at the same time
+    // Then restore antenna after EEPROM access
+	if ((pAd->NicConfig2.field.AntDiversity) || (pAd->RfIcType == RFIC_3020))
+    {
+	    pAd->EepromAccess = FALSE;
+	    AsicSetRxAnt(pAd, pAd->RxAnt.Pair1PrimaryRxAnt);
+    }
+}
+#endif
 }
 
+//2008/09/11:KH add to support efuse<--
+#ifdef RT30xx
+/*
+	========================================================================
+
+	Routine Description:
+
+	Arguments:
+
+	Return Value:
+
+	IRQL =
+
+	Note:
+
+	========================================================================
+*/
+UCHAR eFuseReadRegisters(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT Offset,
+	IN	USHORT Length,
+	OUT	USHORT* pData)
+{
+	EFUSE_CTRL_STRUC		eFuseCtrlStruc;
+	int	i;
+	USHORT	efuseDataOffset;
+	UINT32	data;
+
+	RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
+
+	//Step0. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
+	//Use the eeprom logical address and covert to address to block number
+	eFuseCtrlStruc.field.EFSROM_AIN = Offset & 0xfff0;
+
+	//Step1. Write EFSROM_MODE (0x580, bit7:bit6) to 0.
+	eFuseCtrlStruc.field.EFSROM_MODE = 0;
+
+	//Step2. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical read procedure.
+	eFuseCtrlStruc.field.EFSROM_KICK = 1;
+
+	NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
+	RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
+
+	//Step3. Polling EFSROM_KICK(0x580, bit30) until it become 0 again.
+	i = 0;
+	while(i < 100)
+	{
+		//rtmp.HwMemoryReadDword(EFUSE_CTRL, (DWORD *) &eFuseCtrlStruc, 4);
+		RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
+		if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
+		{
+			break;
+		}
+		RTMPusecDelay(2);
+		i++;
+	}
+
+	//if EFSROM_AOUT is not found in physical address, write 0xffff
+	if (eFuseCtrlStruc.field.EFSROM_AOUT == 0x3f)
+	{
+		for(i=0; i<Length/2; i++)
+			*(pData+2*i) = 0xffff;
+	}
+	else
+	{
+		//Step4. Read 16-byte of data from EFUSE_DATA0-3 (0x590-0x59C)
+		efuseDataOffset =  EFUSE_DATA3 - (Offset & 0xC)  ;
+		//data hold 4 bytes data.
+		//In RTMP_IO_READ32 will automatically execute 32-bytes swapping
+		RTMP_IO_READ32(pAd, efuseDataOffset, &data);
+		//Decide the upper 2 bytes or the bottom 2 bytes.
+		// Little-endian		S	|	S	Big-endian
+		// addr	3	2	1	0	|	0	1	2	3
+		// Ori-V	D	C	B	A	|	A	B	C	D
+		//After swapping
+		//		D	C	B	A	|	D	C	B	A
+		//Return 2-bytes
+		//The return byte statrs from S. Therefore, the little-endian will return BA, the Big-endian will return DC.
+		//For returning the bottom 2 bytes, the Big-endian should shift right 2-bytes.
+		data = data >> (8*(Offset & 0x3));
+
+		NdisMoveMemory(pData, &data, Length);
+	}
+
+	return (UCHAR) eFuseCtrlStruc.field.EFSROM_AOUT;
+
+}
+
+/*
+	========================================================================
+
+	Routine Description:
+
+	Arguments:
+
+	Return Value:
+
+	IRQL =
+
+	Note:
+
+	========================================================================
+*/
+VOID eFusePhysicalReadRegisters(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT Offset,
+	IN	USHORT Length,
+	OUT	USHORT* pData)
+{
+	EFUSE_CTRL_STRUC		eFuseCtrlStruc;
+	int	i;
+	USHORT	efuseDataOffset;
+	UINT32	data;
+
+	RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
+
+	//Step0. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
+	eFuseCtrlStruc.field.EFSROM_AIN = Offset & 0xfff0;
+
+	//Step1. Write EFSROM_MODE (0x580, bit7:bit6) to 1.
+	//Read in physical view
+	eFuseCtrlStruc.field.EFSROM_MODE = 1;
+
+	//Step2. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical read procedure.
+	eFuseCtrlStruc.field.EFSROM_KICK = 1;
+
+	NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
+	RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
+
+	//Step3. Polling EFSROM_KICK(0x580, bit30) until it become 0 again.
+	i = 0;
+	while(i < 100)
+	{
+		RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
+		if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
+			break;
+		RTMPusecDelay(2);
+		i++;
+	}
+
+	//Step4. Read 16-byte of data from EFUSE_DATA0-3 (0x59C-0x590)
+	//Because the size of each EFUSE_DATA is 4 Bytes, the size of address of each is 2 bits.
+	//The previous 2 bits is the EFUSE_DATA number, the last 2 bits is used to decide which bytes
+	//Decide which EFUSE_DATA to read
+	//590:F E D C
+	//594:B A 9 8
+	//598:7 6 5 4
+	//59C:3 2 1 0
+	efuseDataOffset =  EFUSE_DATA3 - (Offset & 0xC)  ;
+
+	RTMP_IO_READ32(pAd, efuseDataOffset, &data);
+
+	data = data >> (8*(Offset & 0x3));
+
+	NdisMoveMemory(pData, &data, Length);
+
+}
+
+/*
+	========================================================================
+
+	Routine Description:
+
+	Arguments:
+
+	Return Value:
+
+	IRQL =
+
+	Note:
+
+	========================================================================
+*/
+VOID eFuseReadPhysical(
+	IN	PRTMP_ADAPTER	pAd,
+  	IN	PUSHORT lpInBuffer,
+  	IN	ULONG nInBufferSize,
+  	OUT	PUSHORT lpOutBuffer,
+  	IN	ULONG nOutBufferSize
+)
+{
+	USHORT* pInBuf = (USHORT*)lpInBuffer;
+	USHORT* pOutBuf = (USHORT*)lpOutBuffer;
+
+	USHORT Offset = pInBuf[0];					//addr
+	USHORT Length = pInBuf[1];					//length
+	int 		i;
+
+	for(i=0; i<Length; i+=2)
+	{
+		eFusePhysicalReadRegisters(pAd,Offset+i, 2, &pOutBuf[i/2]);
+	}
+}
+
+/*
+	========================================================================
+
+	Routine Description:
+
+	Arguments:
+
+	Return Value:
+
+	IRQL =
+
+	Note:
+
+	========================================================================
+*/
+NTSTATUS eFuseRead(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT			Offset,
+	OUT	PUCHAR			pData,
+	IN	USHORT			Length)
+{
+	USHORT* pOutBuf = (USHORT*)pData;
+	NTSTATUS	Status = STATUS_SUCCESS;
+	UCHAR	EFSROM_AOUT;
+	int	i;
+
+	for(i=0; i<Length; i+=2)
+	{
+		EFSROM_AOUT = eFuseReadRegisters(pAd, Offset+i, 2, &pOutBuf[i/2]);
+	}
+	return Status;
+}
+
+/*
+	========================================================================
+
+	Routine Description:
+
+	Arguments:
+
+	Return Value:
+
+	IRQL =
+
+	Note:
+
+	========================================================================
+*/
+VOID eFusePhysicalWriteRegisters(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT Offset,
+	IN	USHORT Length,
+	OUT	USHORT* pData)
+{
+	EFUSE_CTRL_STRUC		eFuseCtrlStruc;
+	int	i;
+	USHORT	efuseDataOffset;
+	UINT32	data, eFuseDataBuffer[4];
+
+	//Step0. Write 16-byte of data to EFUSE_DATA0-3 (0x590-0x59C), where EFUSE_DATA0 is the LSB DW, EFUSE_DATA3 is the MSB DW.
+
+	/////////////////////////////////////////////////////////////////
+	//read current values of 16-byte block
+	RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
+
+	//Step0. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
+	eFuseCtrlStruc.field.EFSROM_AIN = Offset & 0xfff0;
+
+	//Step1. Write EFSROM_MODE (0x580, bit7:bit6) to 1.
+	eFuseCtrlStruc.field.EFSROM_MODE = 1;
+
+	//Step2. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical read procedure.
+	eFuseCtrlStruc.field.EFSROM_KICK = 1;
+
+	NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
+	RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
+
+	//Step3. Polling EFSROM_KICK(0x580, bit30) until it become 0 again.
+	i = 0;
+	while(i < 100)
+	{
+		RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
+
+		if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
+			break;
+		RTMPusecDelay(2);
+		i++;
+	}
+
+	//Step4. Read 16-byte of data from EFUSE_DATA0-3 (0x59C-0x590)
+	efuseDataOffset =  EFUSE_DATA3;
+	for(i=0; i< 4; i++)
+	{
+		RTMP_IO_READ32(pAd, efuseDataOffset, (PUINT32) &eFuseDataBuffer[i]);
+		efuseDataOffset -=  4;
+	}
+
+	//Update the value, the offset is multiple of 2, length is 2
+	efuseDataOffset = (Offset & 0xc) >> 2;
+	data = pData[0] & 0xffff;
+	//The offset should be 0x***10 or 0x***00
+	if((Offset % 4) != 0)
+	{
+		eFuseDataBuffer[efuseDataOffset] = (eFuseDataBuffer[efuseDataOffset] & 0xffff) | (data << 16);
+	}
+	else
+	{
+		eFuseDataBuffer[efuseDataOffset] = (eFuseDataBuffer[efuseDataOffset] & 0xffff0000) | data;
+	}
+
+	efuseDataOffset =  EFUSE_DATA3;
+	for(i=0; i< 4; i++)
+	{
+		RTMP_IO_WRITE32(pAd, efuseDataOffset, eFuseDataBuffer[i]);
+		efuseDataOffset -= 4;
+	}
+	/////////////////////////////////////////////////////////////////
+
+	//Step1. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
+	eFuseCtrlStruc.field.EFSROM_AIN = Offset & 0xfff0;
+
+	//Step2. Write EFSROM_MODE (0x580, bit7:bit6) to 3.
+	eFuseCtrlStruc.field.EFSROM_MODE = 3;
+
+	//Step3. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical write procedure.
+	eFuseCtrlStruc.field.EFSROM_KICK = 1;
+
+	NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
+	RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
+
+	//Step4. Polling EFSROM_KICK(0x580, bit30) until it become 0 again. It��s done.
+	i = 0;
+	while(i < 100)
+	{
+		RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
+
+		if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
+			break;
+
+		RTMPusecDelay(2);
+		i++;
+	}
+}
+
+/*
+	========================================================================
+
+	Routine Description:
+
+	Arguments:
+
+	Return Value:
+
+	IRQL =
+
+	Note:
+
+	========================================================================
+*/
+NTSTATUS eFuseWriteRegisters(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT Offset,
+	IN	USHORT Length,
+	IN	USHORT* pData)
+{
+	USHORT	i;
+	USHORT	eFuseData;
+	USHORT	LogicalAddress, BlkNum = 0xffff;
+	UCHAR	EFSROM_AOUT;
+
+	USHORT addr,tmpaddr, InBuf[3], tmpOffset;
+	USHORT buffer[8];
+	BOOLEAN		bWriteSuccess = TRUE;
+
+	DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters Offset=%x, pData=%x\n", Offset, *pData));
+
+	//Step 0. find the entry in the mapping table
+	//The address of EEPROM is 2-bytes alignment.
+	//The last bit is used for alignment, so it must be 0.
+	tmpOffset = Offset & 0xfffe;
+	EFSROM_AOUT = eFuseReadRegisters(pAd, tmpOffset, 2, &eFuseData);
+
+	if( EFSROM_AOUT == 0x3f)
+	{	//find available logical address pointer
+		//the logical address does not exist, find an empty one
+		//from the first address of block 45=16*45=0x2d0 to the last address of block 47
+		//==>48*16-3(reserved)=2FC
+		for (i=EFUSE_USAGE_MAP_START; i<=EFUSE_USAGE_MAP_END; i+=2)
+		{
+			//Retrive the logical block nubmer form each logical address pointer
+			//It will access two logical address pointer each time.
+			eFusePhysicalReadRegisters(pAd, i, 2, &LogicalAddress);
+			if( (LogicalAddress & 0xff) == 0)
+			{//Not used logical address pointer
+				BlkNum = i-EFUSE_USAGE_MAP_START;
+				break;
+			}
+			else if(( (LogicalAddress >> 8) & 0xff) == 0)
+			{//Not used logical address pointer
+				if (i != EFUSE_USAGE_MAP_END)
+				{
+					BlkNum = i-EFUSE_USAGE_MAP_START+1;
+				}
+				break;
+			}
+		}
+	}
+	else
+	{
+		BlkNum = EFSROM_AOUT;
+	}
+
+	DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters BlkNum = %d \n", BlkNum));
+
+	if(BlkNum == 0xffff)
+	{
+		DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters: out of free E-fuse space!!!\n"));
+		return FALSE;
+	}
+
+	//Step 1. Save data of this block	which is pointed by the avaible logical address pointer
+	// read and save the original block data
+	for(i =0; i<8; i++)
+	{
+		addr = BlkNum * 0x10 ;
+
+		InBuf[0] = addr+2*i;
+		InBuf[1] = 2;
+		InBuf[2] = 0x0;
+
+		eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
+
+		buffer[i] = InBuf[2];
+	}
+
+	//Step 2. Update the data in buffer, and write the data to Efuse
+	buffer[ (Offset >> 1) % 8] = pData[0];
+
+	do
+	{
+		//Step 3. Write the data to Efuse
+		if(!bWriteSuccess)
+		{
+			for(i =0; i<8; i++)
+			{
+				addr = BlkNum * 0x10 ;
+
+				InBuf[0] = addr+2*i;
+				InBuf[1] = 2;
+				InBuf[2] = buffer[i];
+
+				eFuseWritePhysical(pAd, &InBuf[0], 6, NULL, 2);
+			}
+		}
+		else
+		{
+				addr = BlkNum * 0x10 ;
+
+				InBuf[0] = addr+(Offset % 16);
+				InBuf[1] = 2;
+				InBuf[2] = pData[0];
+
+				eFuseWritePhysical(pAd, &InBuf[0], 6, NULL, 2);
+		}
+
+		//Step 4. Write mapping table
+		addr = EFUSE_USAGE_MAP_START+BlkNum;
+
+		tmpaddr = addr;
+
+		if(addr % 2 != 0)
+			addr = addr -1;
+		InBuf[0] = addr;
+		InBuf[1] = 2;
+
+		//convert the address from 10 to 8 bit ( bit7, 6 = parity and bit5 ~ 0 = bit9~4), and write to logical map entry
+		tmpOffset = Offset;
+		tmpOffset >>= 4;
+		tmpOffset |= ((~((tmpOffset & 0x01) ^ ( tmpOffset >> 1 & 0x01) ^  (tmpOffset >> 2 & 0x01) ^  (tmpOffset >> 3 & 0x01))) << 6) & 0x40;
+		tmpOffset |= ((~( (tmpOffset >> 2 & 0x01) ^ (tmpOffset >> 3 & 0x01) ^ (tmpOffset >> 4 & 0x01) ^ ( tmpOffset >> 5 & 0x01))) << 7) & 0x80;
+
+		// write the logical address
+		if(tmpaddr%2 != 0)
+			InBuf[2] = tmpOffset<<8;
+		else
+			InBuf[2] = tmpOffset;
+
+		eFuseWritePhysical(pAd,&InBuf[0], 6, NULL, 0);
+
+		//Step 5. Compare data if not the same, invalidate the mapping entry, then re-write the data until E-fuse is exhausted
+		bWriteSuccess = TRUE;
+		for(i =0; i<8; i++)
+		{
+			addr = BlkNum * 0x10 ;
+
+			InBuf[0] = addr+2*i;
+			InBuf[1] = 2;
+			InBuf[2] = 0x0;
+
+			eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
+
+			if(buffer[i] != InBuf[2])
+			{
+				bWriteSuccess = FALSE;
+				break;
+			}
+		}
+
+		//Step 6. invlidate mapping entry and find a free mapping entry if not succeed
+		if (!bWriteSuccess)
+		{
+			DBGPRINT(RT_DEBUG_TRACE, ("Not bWriteSuccess BlkNum = %d\n", BlkNum));
+
+			// the offset of current mapping entry
+			addr = EFUSE_USAGE_MAP_START+BlkNum;
+
+			//find a new mapping entry
+			BlkNum = 0xffff;
+			for (i=EFUSE_USAGE_MAP_START; i<=EFUSE_USAGE_MAP_END; i+=2)
+			{
+				eFusePhysicalReadRegisters(pAd, i, 2, &LogicalAddress);
+				if( (LogicalAddress & 0xff) == 0)
+				{
+					BlkNum = i-EFUSE_USAGE_MAP_START;
+					break;
+				}
+				else if(( (LogicalAddress >> 8) & 0xff) == 0)
+				{
+					if (i != EFUSE_USAGE_MAP_END)
+					{
+						BlkNum = i+1-EFUSE_USAGE_MAP_START;
+					}
+					break;
+				}
+			}
+			DBGPRINT(RT_DEBUG_TRACE, ("Not bWriteSuccess new BlkNum = %d\n", BlkNum));
+			if(BlkNum == 0xffff)
+			{
+				DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters: out of free E-fuse space!!!\n"));
+				return FALSE;
+			}
+
+			//invalidate the original mapping entry if new entry is not found
+			tmpaddr = addr;
+
+			if(addr % 2 != 0)
+				addr = addr -1;
+			InBuf[0] = addr;
+			InBuf[1] = 2;
+
+			eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
+
+			// write the logical address
+			if(tmpaddr%2 != 0)
+			{
+				// Invalidate the high byte
+				for (i=8; i<15; i++)
+				{
+					if( ( (InBuf[2] >> i) & 0x01) == 0)
+					{
+						InBuf[2] |= (0x1 <<i);
+						break;
+					}
+				}
+			}
+			else
+			{
+				// invalidate the low byte
+				for (i=0; i<8; i++)
+				{
+					if( ( (InBuf[2] >> i) & 0x01) == 0)
+					{
+						InBuf[2] |= (0x1 <<i);
+						break;
+					}
+				}
+			}
+			eFuseWritePhysical(pAd, &InBuf[0], 6, NULL, 0);
+		}
+	}
+	while(!bWriteSuccess);
+
+	return TRUE;
+}
+
+/*
+	========================================================================
+
+	Routine Description:
+
+	Arguments:
+
+	Return Value:
+
+	IRQL =
+
+	Note:
+
+	========================================================================
+*/
+VOID eFuseWritePhysical(
+	IN	PRTMP_ADAPTER	pAd,
+  	PUSHORT lpInBuffer,
+	ULONG nInBufferSize,
+  	PUCHAR lpOutBuffer,
+  	ULONG nOutBufferSize
+)
+{
+	USHORT* pInBuf = (USHORT*)lpInBuffer;
+	int 		i;
+	//USHORT* pOutBuf = (USHORT*)ioBuffer;
+
+	USHORT Offset = pInBuf[0];					//addr
+	USHORT Length = pInBuf[1];					//length
+	USHORT* pValueX = &pInBuf[2];				//value ...
+		// Little-endian		S	|	S	Big-endian
+		// addr	3	2	1	0	|	0	1	2	3
+		// Ori-V	D	C	B	A	|	A	B	C	D
+		//After swapping
+		//		D	C	B	A	|	D	C	B	A
+		//Both the little and big-endian use the same sequence to write  data.
+		//Therefore, we only need swap data when read the data.
+	for(i=0; i<Length; i+=2)
+	{
+		eFusePhysicalWriteRegisters(pAd, Offset+i, 2, &pValueX[i/2]);
+	}
+}
+
+
+/*
+	========================================================================
+
+	Routine Description:
+
+	Arguments:
+
+	Return Value:
+
+	IRQL =
+
+	Note:
+
+	========================================================================
+*/
+NTSTATUS eFuseWrite(
+   	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT			Offset,
+	IN	PUCHAR			pData,
+	IN	USHORT			length)
+{
+	int i;
+
+	USHORT* pValueX = (PUSHORT) pData;				//value ...
+		//The input value=3070 will be stored as following
+ 		// Little-endian		S	|	S	Big-endian
+		// addr			1	0	|	0	1
+		// Ori-V			30	70	|	30	70
+		//After swapping
+		//				30	70	|	70	30
+		//Casting
+		//				3070	|	7030 (x)
+		//The swapping should be removed for big-endian
+	for(i=0; i<length; i+=2)
+	{
+		eFuseWriteRegisters(pAd, Offset+i, 2, &pValueX[i/2]);
+	}
+
+	return TRUE;
+}
+
+/*
+	========================================================================
+
+	Routine Description:
+
+	Arguments:
+
+	Return Value:
+
+	IRQL =
+
+	Note:
+
+	========================================================================
+*/
+INT set_eFuseGetFreeBlockCount_Proc(
+   	IN	PRTMP_ADAPTER	pAd,
+	IN	PUCHAR			arg)
+{
+	USHORT i;
+	USHORT	LogicalAddress;
+	USHORT efusefreenum=0;
+	if(!pAd->bUseEfuse)
+		return FALSE;
+	for (i = EFUSE_USAGE_MAP_START; i <= EFUSE_USAGE_MAP_END; i+=2)
+	{
+		eFusePhysicalReadRegisters(pAd, i, 2, &LogicalAddress);
+		if( (LogicalAddress & 0xff) == 0)
+		{
+			efusefreenum= (UCHAR) (EFUSE_USAGE_MAP_END-i+1);
+			break;
+		}
+		else if(( (LogicalAddress >> 8) & 0xff) == 0)
+		{
+			efusefreenum = (UCHAR) (EFUSE_USAGE_MAP_END-i);
+			break;
+		}
+
+		if(i == EFUSE_USAGE_MAP_END)
+			efusefreenum = 0;
+	}
+	printk("efuseFreeNumber is %d\n",efusefreenum);
+	return TRUE;
+}
+INT set_eFusedump_Proc(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PUCHAR			arg)
+{
+USHORT InBuf[3];
+	INT i=0;
+	if(!pAd->bUseEfuse)
+		return FALSE;
+	for(i =0; i<EFUSE_USAGE_MAP_END/2; i++)
+	{
+		InBuf[0] = 2*i;
+		InBuf[1] = 2;
+		InBuf[2] = 0x0;
+
+		eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
+		if(i%4==0)
+		printk("\nBlock %x:",i/8);
+		printk("%04x ",InBuf[2]);
+	}
+	return TRUE;
+}
+INT	set_eFuseLoadFromBin_Proc(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PUCHAR			arg)
+{
+	CHAR					*src;
+	struct file				*srcf;
+	INT 					retval, orgfsuid, orgfsgid;
+   	mm_segment_t			orgfs;
+	UCHAR					*buffer;
+	UCHAR					BinFileSize=0;
+	INT						i = 0,j=0,k=1;
+	USHORT					*PDATA;
+	USHORT					DATA;
+	BinFileSize=strlen("RT30xxEEPROM.bin");
+	src = kmalloc(128, MEM_ALLOC_FLAG);
+	NdisZeroMemory(src, 128);
+
+ 	if(strlen(arg)>0)
+	{
+
+		NdisMoveMemory(src, arg, strlen(arg));
+ 	}
+
+	else
+	{
+
+		NdisMoveMemory(src, "RT30xxEEPROM.bin", BinFileSize);
+	}
+
+	DBGPRINT(RT_DEBUG_TRACE, ("FileName=%s\n",src));
+	buffer = kmalloc(MAX_EEPROM_BIN_FILE_SIZE, MEM_ALLOC_FLAG);
+
+	if(buffer == NULL)
+	{
+		kfree(src);
+		 return FALSE;
+}
+	PDATA=kmalloc(sizeof(USHORT)*8,MEM_ALLOC_FLAG);
+
+	if(PDATA==NULL)
+	{
+		kfree(src);
+
+		kfree(buffer);
+		return FALSE;
+	}
+	/* Don't change to uid 0, let the file be opened as the "normal" user */
+#if 0
+	orgfsuid = current->fsuid;
+	orgfsgid = current->fsgid;
+	current->fsuid=current->fsgid = 0;
+#endif
+    	orgfs = get_fs();
+   	 set_fs(KERNEL_DS);
+
+	if (src && *src)
+	{
+		srcf = filp_open(src, O_RDONLY, 0);
+		if (IS_ERR(srcf))
+		{
+			DBGPRINT(RT_DEBUG_ERROR, ("--> Error %ld opening %s\n", -PTR_ERR(srcf),src));
+			return FALSE;
+		}
+		else
+		{
+			// The object must have a read method
+			if (srcf->f_op && srcf->f_op->read)
+			{
+				memset(buffer, 0x00, MAX_EEPROM_BIN_FILE_SIZE);
+				while(srcf->f_op->read(srcf, &buffer[i], 1, &srcf->f_pos)==1)
+				{
+					DBGPRINT(RT_DEBUG_TRACE, ("%02X ",buffer[i]));
+					if((i+1)%8==0)
+						DBGPRINT(RT_DEBUG_TRACE, ("\n"));
+              			i++;
+						if(i>=MAX_EEPROM_BIN_FILE_SIZE)
+							{
+								DBGPRINT(RT_DEBUG_ERROR, ("--> Error %ld reading %s, The file is too large[1024]\n", -PTR_ERR(srcf),src));
+								kfree(PDATA);
+								kfree(buffer);
+								kfree(src);
+								return FALSE;
+							}
+			       }
+			}
+			else
+			{
+						DBGPRINT(RT_DEBUG_ERROR, ("--> Error!! System doest not support read function\n"));
+						kfree(PDATA);
+						kfree(buffer);
+						kfree(src);
+						return FALSE;
+			}
+      		}
+
+
+	}
+	else
+		{
+					DBGPRINT(RT_DEBUG_ERROR, ("--> Error src  or srcf is null\n"));
+					kfree(PDATA);
+					kfree(buffer);
+					return FALSE;
+
+		}
+
+
+	retval=filp_close(srcf,NULL);
+
+	if (retval)
+	{
+		DBGPRINT(RT_DEBUG_TRACE, ("--> Error %d closing %s\n", -retval, src));
+	}
+	set_fs(orgfs);
+#if 0
+	current->fsuid = orgfsuid;
+	current->fsgid = orgfsgid;
+#endif
+	for(j=0;j<i;j++)
+	{
+		DBGPRINT(RT_DEBUG_TRACE, ("%02X ",buffer[j]));
+		if((j+1)%2==0)
+			PDATA[j/2%8]=((buffer[j]<<8)&0xff00)|(buffer[j-1]&0xff);
+		if(j%16==0)
+		{
+			k=buffer[j];
+		}
+		else
+		{
+			k&=buffer[j];
+			if((j+1)%16==0)
+			{
+
+				DBGPRINT(RT_DEBUG_TRACE, (" result=%02X,blk=%02x\n",k,j/16));
+
+				if(k!=0xff)
+					eFuseWriteRegistersFromBin(pAd,(USHORT)j-15, 16, PDATA);
+				else
+					{
+						if(eFuseReadRegisters(pAd,j, 2,(PUSHORT)&DATA)!=0x3f)
+							eFuseWriteRegistersFromBin(pAd,(USHORT)j-15, 16, PDATA);
+					}
+				/*
+				for(l=0;l<8;l++)
+					printk("%04x ",PDATA[l]);
+				printk("\n");
+				*/
+				NdisZeroMemory(PDATA,16);
+
+
+			}
+		}
+
+
+	}
+
+
+	kfree(PDATA);
+	kfree(buffer);
+	kfree(src);
+	return TRUE;
+}
+NTSTATUS eFuseWriteRegistersFromBin(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT Offset,
+	IN	USHORT Length,
+	IN	USHORT* pData)
+{
+	USHORT	i;
+	USHORT	eFuseData;
+	USHORT	LogicalAddress, BlkNum = 0xffff;
+	UCHAR	EFSROM_AOUT,Loop=0;
+	EFUSE_CTRL_STRUC		eFuseCtrlStruc;
+	USHORT	efuseDataOffset;
+	UINT32	data,tempbuffer;
+	USHORT addr,tmpaddr, InBuf[3], tmpOffset;
+	UINT32 buffer[4];
+	BOOLEAN		bWriteSuccess = TRUE;
+	BOOLEAN		bNotWrite=TRUE;
+	BOOLEAN		bAllocateNewBlk=TRUE;
+
+	DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegistersFromBin Offset=%x, pData=%04x:%04x:%04x:%04x\n", Offset, *pData,*(pData+1),*(pData+2),*(pData+3)));
+
+	do
+	{
+	//Step 0. find the entry in the mapping table
+	//The address of EEPROM is 2-bytes alignment.
+	//The last bit is used for alignment, so it must be 0.
+	Loop++;
+	tmpOffset = Offset & 0xfffe;
+	EFSROM_AOUT = eFuseReadRegisters(pAd, tmpOffset, 2, &eFuseData);
+
+	if( EFSROM_AOUT == 0x3f)
+	{	//find available logical address pointer
+		//the logical address does not exist, find an empty one
+		//from the first address of block 45=16*45=0x2d0 to the last address of block 47
+		//==>48*16-3(reserved)=2FC
+		bAllocateNewBlk=TRUE;
+		for (i=EFUSE_USAGE_MAP_START; i<=EFUSE_USAGE_MAP_END; i+=2)
+		{
+			//Retrive the logical block nubmer form each logical address pointer
+			//It will access two logical address pointer each time.
+			eFusePhysicalReadRegisters(pAd, i, 2, &LogicalAddress);
+			if( (LogicalAddress & 0xff) == 0)
+			{//Not used logical address pointer
+				BlkNum = i-EFUSE_USAGE_MAP_START;
+				break;
+			}
+			else if(( (LogicalAddress >> 8) & 0xff) == 0)
+			{//Not used logical address pointer
+				if (i != EFUSE_USAGE_MAP_END)
+				{
+					BlkNum = i-EFUSE_USAGE_MAP_START+1;
+				}
+				break;
+			}
+		}
+	}
+	else
+	{
+		bAllocateNewBlk=FALSE;
+		BlkNum = EFSROM_AOUT;
+	}
+
+	DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters BlkNum = %d \n", BlkNum));
+
+	if(BlkNum == 0xffff)
+	{
+		DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters: out of free E-fuse space!!!\n"));
+		return FALSE;
+	}
+	//Step 1.1.0
+	//If the block is not existing in mapping table, create one
+	//and write down the 16-bytes data to the new block
+	if(bAllocateNewBlk)
+	{
+		DBGPRINT(RT_DEBUG_TRACE, ("Allocate New Blk\n"));
+		efuseDataOffset =  EFUSE_DATA3;
+		for(i=0; i< 4; i++)
+		{
+			DBGPRINT(RT_DEBUG_TRACE, ("Allocate New Blk, Data%d=%04x%04x\n",3-i,pData[2*i+1],pData[2*i]));
+			tempbuffer=((pData[2*i+1]<<16)&0xffff0000)|pData[2*i];
+
+
+			RTMP_IO_WRITE32(pAd, efuseDataOffset,tempbuffer);
+			efuseDataOffset -= 4;
+
+		}
+		/////////////////////////////////////////////////////////////////
+
+		//Step1.1.1. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
+		eFuseCtrlStruc.field.EFSROM_AIN = BlkNum* 0x10 ;
+
+		//Step1.1.2. Write EFSROM_MODE (0x580, bit7:bit6) to 3.
+		eFuseCtrlStruc.field.EFSROM_MODE = 3;
+
+		//Step1.1.3. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical write procedure.
+		eFuseCtrlStruc.field.EFSROM_KICK = 1;
+
+		NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
+
+		RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
+
+		//Step1.1.4. Polling EFSROM_KICK(0x580, bit30) until it become 0 again. It��s done.
+		i = 0;
+		while(i < 100)
+		{
+			RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
+
+			if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
+				break;
+
+			RTMPusecDelay(2);
+			i++;
+		}
+
+	}
+	else
+	{	//Step1.2.
+		//If the same logical number is existing, check if the writting data and the data
+		//saving in this block are the same.
+		/////////////////////////////////////////////////////////////////
+		//read current values of 16-byte block
+		RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
+
+		//Step1.2.0. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
+		eFuseCtrlStruc.field.EFSROM_AIN = Offset & 0xfff0;
+
+		//Step1.2.1. Write EFSROM_MODE (0x580, bit7:bit6) to 1.
+		eFuseCtrlStruc.field.EFSROM_MODE = 0;
+
+		//Step1.2.2. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical read procedure.
+		eFuseCtrlStruc.field.EFSROM_KICK = 1;
+
+		NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
+		RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
+
+		//Step1.2.3. Polling EFSROM_KICK(0x580, bit30) until it become 0 again.
+		i = 0;
+		while(i < 100)
+		{
+			RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
+
+			if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
+				break;
+			RTMPusecDelay(2);
+			i++;
+		}
+
+		//Step1.2.4. Read 16-byte of data from EFUSE_DATA0-3 (0x59C-0x590)
+		efuseDataOffset =  EFUSE_DATA3;
+		for(i=0; i< 4; i++)
+		{
+			RTMP_IO_READ32(pAd, efuseDataOffset, (PUINT32) &buffer[i]);
+			efuseDataOffset -=  4;
+		}
+		//Step1.2.5. Check if the data of efuse and the writing data are the same.
+		for(i =0; i<4; i++)
+		{
+			tempbuffer=((pData[2*i+1]<<16)&0xffff0000)|pData[2*i];
+			DBGPRINT(RT_DEBUG_TRACE, ("buffer[%d]=%x,pData[%d]=%x,pData[%d]=%x,tempbuffer=%x\n",i,buffer[i],2*i,pData[2*i],2*i+1,pData[2*i+1],tempbuffer));
+
+			if(((buffer[i]&0xffff0000)==(pData[2*i+1]<<16))&&((buffer[i]&0xffff)==pData[2*i]))
+				bNotWrite&=TRUE;
+			else
+			{
+				bNotWrite&=FALSE;
+				break;
+			}
+		}
+		if(!bNotWrite)
+		{
+		printk("The data is not the same\n");
+
+			for(i =0; i<8; i++)
+			{
+				addr = BlkNum * 0x10 ;
+
+				InBuf[0] = addr+2*i;
+				InBuf[1] = 2;
+				InBuf[2] = pData[i];
+
+				eFuseWritePhysical(pAd, &InBuf[0], 6, NULL, 2);
+			}
+
+		}
+		else
+			return TRUE;
+	     }
+
+
+
+		//Step 2. Write mapping table
+		addr = EFUSE_USAGE_MAP_START+BlkNum;
+
+		tmpaddr = addr;
+
+		if(addr % 2 != 0)
+			addr = addr -1;
+		InBuf[0] = addr;
+		InBuf[1] = 2;
+
+		//convert the address from 10 to 8 bit ( bit7, 6 = parity and bit5 ~ 0 = bit9~4), and write to logical map entry
+		tmpOffset = Offset;
+		tmpOffset >>= 4;
+		tmpOffset |= ((~((tmpOffset & 0x01) ^ ( tmpOffset >> 1 & 0x01) ^  (tmpOffset >> 2 & 0x01) ^  (tmpOffset >> 3 & 0x01))) << 6) & 0x40;
+		tmpOffset |= ((~( (tmpOffset >> 2 & 0x01) ^ (tmpOffset >> 3 & 0x01) ^ (tmpOffset >> 4 & 0x01) ^ ( tmpOffset >> 5 & 0x01))) << 7) & 0x80;
+
+		// write the logical address
+		if(tmpaddr%2 != 0)
+			InBuf[2] = tmpOffset<<8;
+		else
+			InBuf[2] = tmpOffset;
+
+		eFuseWritePhysical(pAd,&InBuf[0], 6, NULL, 0);
+
+		//Step 3. Compare data if not the same, invalidate the mapping entry, then re-write the data until E-fuse is exhausted
+		bWriteSuccess = TRUE;
+		for(i =0; i<8; i++)
+		{
+			addr = BlkNum * 0x10 ;
+
+			InBuf[0] = addr+2*i;
+			InBuf[1] = 2;
+			InBuf[2] = 0x0;
+
+			eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
+			DBGPRINT(RT_DEBUG_TRACE, ("addr=%x, buffer[i]=%x,InBuf[2]=%x\n",InBuf[0],pData[i],InBuf[2]));
+			if(pData[i] != InBuf[2])
+			{
+				bWriteSuccess = FALSE;
+				break;
+			}
+		}
+
+		//Step 4. invlidate mapping entry and find a free mapping entry if not succeed
+
+		if (!bWriteSuccess&&Loop<2)
+		{
+			DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegistersFromBin::Not bWriteSuccess BlkNum = %d\n", BlkNum));
+
+			// the offset of current mapping entry
+			addr = EFUSE_USAGE_MAP_START+BlkNum;
+
+			//find a new mapping entry
+			BlkNum = 0xffff;
+			for (i=EFUSE_USAGE_MAP_START; i<=EFUSE_USAGE_MAP_END; i+=2)
+			{
+				eFusePhysicalReadRegisters(pAd, i, 2, &LogicalAddress);
+				if( (LogicalAddress & 0xff) == 0)
+				{
+					BlkNum = i-EFUSE_USAGE_MAP_START;
+					break;
+				}
+				else if(( (LogicalAddress >> 8) & 0xff) == 0)
+				{
+					if (i != EFUSE_USAGE_MAP_END)
+					{
+						BlkNum = i+1-EFUSE_USAGE_MAP_START;
+					}
+					break;
+				}
+			}
+			DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegistersFromBin::Not bWriteSuccess new BlkNum = %d\n", BlkNum));
+			if(BlkNum == 0xffff)
+			{
+				DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegistersFromBin: out of free E-fuse space!!!\n"));
+				return FALSE;
+			}
+
+			//invalidate the original mapping entry if new entry is not found
+			tmpaddr = addr;
+
+			if(addr % 2 != 0)
+				addr = addr -1;
+			InBuf[0] = addr;
+			InBuf[1] = 2;
+
+			eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
+
+			// write the logical address
+			if(tmpaddr%2 != 0)
+			{
+				// Invalidate the high byte
+				for (i=8; i<15; i++)
+				{
+					if( ( (InBuf[2] >> i) & 0x01) == 0)
+					{
+						InBuf[2] |= (0x1 <<i);
+						break;
+					}
+				}
+			}
+			else
+			{
+				// invalidate the low byte
+				for (i=0; i<8; i++)
+				{
+					if( ( (InBuf[2] >> i) & 0x01) == 0)
+					{
+						InBuf[2] |= (0x1 <<i);
+						break;
+					}
+				}
+			}
+			eFuseWritePhysical(pAd, &InBuf[0], 6, NULL, 0);
+		}
+
+	}
+	while(!bWriteSuccess&&Loop<2);
+
+	return TRUE;
+}
+
+#endif // RT30xx //
+//2008/09/11:KH add to support efuse-->
diff --git a/drivers/staging/rt2860/common/md5.c b/drivers/staging/rt2860/common/md5.c
index 774776b..ad883ca 100644
--- a/drivers/staging/rt2860/common/md5.c
+++ b/drivers/staging/rt2860/common/md5.c
@@ -131,19 +131,7 @@
 	MD5Final(mac, &context);			 /*	finish up 2nd pass */
 }
 
-#ifndef RT_BIG_ENDIAN
 #define byteReverse(buf, len)   /* Nothing */
-#else
-void byteReverse(unsigned char *buf, unsigned longs);
-void byteReverse(unsigned char *buf, unsigned longs)
-{
-    do {
-        *(UINT32 *)buf = SWAP32(*(UINT32 *)buf);
-        buf += 4;
-    } while (--longs);
-}
-#endif
-
 
 /* ==========================  MD5 implementation =========================== */
 // four base functions for MD5
diff --git a/drivers/staging/rt2860/common/mlme.c b/drivers/staging/rt2860/common/mlme.c
index 2edf299..bb6fccb 100644
--- a/drivers/staging/rt2860/common/mlme.c
+++ b/drivers/staging/rt2860/common/mlme.c
@@ -50,11 +50,7 @@
 UCHAR   RALINK_OUI[]  = {0x00, 0x0c, 0x43};
 UCHAR   BROADCOM_OUI[]  = {0x00, 0x90, 0x4c};
 UCHAR   WPS_OUI[] = {0x00, 0x50, 0xf2, 0x04};
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
 UCHAR	PRE_N_HT_OUI[]	= {0x00, 0x90, 0x4c};
-#endif // DOT11_N_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
 
 UCHAR RateSwitchTable[] = {
 // Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
@@ -130,7 +126,6 @@
     0x07, 0x10,  7, 10, 13,
 };
 
-#ifdef DOT11_N_SUPPORT
 UCHAR RateSwitchTable11N1S[] = {
 // Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
     0x09, 0x00,  0,  0,  0,						// Initial used item after association
@@ -287,7 +282,6 @@
     0x0a, 0x20, 23,  8, 25,
     0x0b, 0x22, 23,  8, 25,
 };
-#endif // DOT11_N_SUPPORT //
 
 PUCHAR ReasonString[] = {
 	/* 0  */	 "Reserved",
@@ -334,14 +328,9 @@
 UCHAR  SsidIe	 = IE_SSID;
 UCHAR  SupRateIe = IE_SUPP_RATES;
 UCHAR  ExtRateIe = IE_EXT_SUPP_RATES;
-#ifdef DOT11_N_SUPPORT
 UCHAR  HtCapIe = IE_HT_CAP;
 UCHAR  AddHtInfoIe = IE_ADD_HT;
 UCHAR  NewExtChanIe = IE_SECONDARY_CH_OFFSET;
-#ifdef DOT11N_DRAFT3
-UCHAR  ExtHtCapIe = IE_EXT_CAPABILITY;
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
 UCHAR  ErpIe	 = IE_ERP;
 UCHAR  DsIe 	 = IE_DS_PARM;
 UCHAR  TimIe	 = IE_TIM;
@@ -349,6 +338,9 @@
 UCHAR  Wpa2Ie	 = IE_WPA2;
 UCHAR  IbssIe	 = IE_IBSS_PARM;
 UCHAR  Ccx2Ie	 = IE_CCX_V2;
+#ifdef RT2870
+UCHAR  WapiIe	 = IE_WAPI;
+#endif
 
 extern UCHAR	WPA_OUI[];
 
@@ -457,7 +449,13 @@
 	{13,   247,	 2,  2},
 	{14,   248,	 2,  4},
 };
+#ifndef RT30xx
 #define	NUM_OF_3020_CHNL	(sizeof(FreqItems3020) / sizeof(FREQUENCY_ITEM))
+#endif
+#ifdef RT30xx
+//2008/07/10:KH Modified to share this variable
+UCHAR	NUM_OF_3020_CHNL=(sizeof(FreqItems3020) / sizeof(FREQUENCY_ITEM));
+#endif
 
 /*
 	==========================================================================
@@ -488,8 +486,6 @@
 		pAd->Mlme.bRunning = FALSE;
 		NdisAllocateSpinLock(&pAd->Mlme.TaskLock);
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			BssTableInit(&pAd->ScanTab);
 
@@ -501,18 +497,10 @@
 			WpaPskStateMachineInit(pAd, &pAd->Mlme.WpaPskMachine, pAd->Mlme.WpaPskFunc);
 			AironetStateMachineInit(pAd, &pAd->Mlme.AironetMachine, pAd->Mlme.AironetFunc);
 
-#ifdef QOS_DLS_SUPPORT
-			DlsStateMachineInit(pAd, &pAd->Mlme.DlsMachine, pAd->Mlme.DlsFunc);
-#endif // QOS_DLS_SUPPORT //
-
-
 			// Since we are using switch/case to implement it, the init is different from the above
 			// state machine init
 			MlmeCntlInit(pAd, &pAd->Mlme.CntlMachine, NULL);
 		}
-#endif // CONFIG_STA_SUPPORT //
-
-
 
 		ActionStateMachineInit(pAd, &pAd->Mlme.ActMachine, pAd->Mlme.ActFunc);
 
@@ -525,9 +513,7 @@
 		// software-based RX Antenna diversity
 		RTMPInitTimer(pAd, &pAd->Mlme.RxAntEvalTimer, GET_TIMER_FUNCTION(AsicRxAntEvalTimeout), pAd, FALSE);
 
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+#ifdef RT2860
 		{
 	        if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE))
 	        {
@@ -536,8 +522,7 @@
 	    		RTMPInitTimer(pAd, &pAd->Mlme.RadioOnOffTimer, GET_TIMER_FUNCTION(RadioOnExec), pAd, FALSE);
 	        }
 		}
-#endif // CONFIG_STA_SUPPORT //
-
+#endif
 	} while (FALSE);
 
 	DBGPRINT(RT_DEBUG_TRACE, ("<-- MLME Initialize\n"));
@@ -563,9 +548,6 @@
 	IN PRTMP_ADAPTER pAd)
 {
 	MLME_QUEUE_ELEM 	   *Elem = NULL;
-#ifdef APCLI_SUPPORT
-	SHORT apcliIfIndex;
-#endif
 
 	// Only accept MLME and Frame from peer side, no other (control/data) frame should
 	// get into this state machine
@@ -592,23 +574,24 @@
 			break;
 		}
 
-#ifdef RALINK_ATE
-		if(ATE_ON(pAd))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now in MlmeHandler\n"));
-			break;
-		}
-#endif // RALINK_ATE //
-
 		//From message type, determine which state machine I should drive
 		if (MlmeDequeue(&pAd->Mlme.Queue, &Elem))
 		{
+#ifdef RT2870
+			if (Elem->MsgType == MT2_RESET_CONF)
+			{
+				DBGPRINT_RAW(RT_DEBUG_TRACE, ("!!! reset MLME state machine !!!\n"));
+				MlmeRestartStateMachine(pAd);
+				Elem->Occupied = FALSE;
+				Elem->MsgLen = 0;
+				continue;
+			}
+#endif // RT2870 //
 
 			// if dequeue success
 			switch (Elem->Machine)
 			{
 				// STA state machines
-#ifdef	CONFIG_STA_SUPPORT
 				case ASSOC_STATE_MACHINE:
 					StateMachinePerformAction(pAd, &pAd->Mlme.AssocMachine, Elem);
 					break;
@@ -627,22 +610,9 @@
 				case WPA_PSK_STATE_MACHINE:
 					StateMachinePerformAction(pAd, &pAd->Mlme.WpaPskMachine, Elem);
 					break;
-#ifdef LEAP_SUPPORT
-				case LEAP_STATE_MACHINE:
-					LeapMachinePerformAction(pAd, &pAd->Mlme.LeapMachine, Elem);
-					break;
-#endif
 				case AIRONET_STATE_MACHINE:
 					StateMachinePerformAction(pAd, &pAd->Mlme.AironetMachine, Elem);
 					break;
-
-#ifdef QOS_DLS_SUPPORT
-				case DLS_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.DlsMachine, Elem);
-					break;
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
 				case ACTION_STATE_MACHINE:
 					StateMachinePerformAction(pAd, &pAd->Mlme.ActMachine, Elem);
 					break;
@@ -687,6 +657,9 @@
 	IN PRTMP_ADAPTER pAd)
 {
 	BOOLEAN 	  Cancelled;
+#ifdef RT3070
+	UINT32		TxPinCfg = 0x00050F0F;
+#endif // RT3070 //
 
 	DBGPRINT(RT_DEBUG_TRACE, ("==> MlmeHalt\n"));
 
@@ -696,12 +669,7 @@
 		AsicDisableSync(pAd);
 	}
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
-#ifdef QOS_DLS_SUPPORT
-		UCHAR		i;
-#endif // QOS_DLS_SUPPORT //
 		// Cancel pending timers
 		RTMPCancelTimer(&pAd->MlmeAux.AssocTimer,		&Cancelled);
 		RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer,		&Cancelled);
@@ -709,20 +677,14 @@
 		RTMPCancelTimer(&pAd->MlmeAux.AuthTimer,		&Cancelled);
 		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer,		&Cancelled);
 		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer,		&Cancelled);
+#ifdef RT2860
 	    if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE))
 	    {
 	   	    RTMPCancelTimer(&pAd->Mlme.PsPollTimer,		&Cancelled);
 		    RTMPCancelTimer(&pAd->Mlme.RadioOnOffTimer,		&Cancelled);
 		}
-
-#ifdef QOS_DLS_SUPPORT
-		for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &Cancelled);
-		}
-#endif // QOS_DLS_SUPPORT //
+#endif
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	RTMPCancelTimer(&pAd->Mlme.PeriodicTimer,		&Cancelled);
 	RTMPCancelTimer(&pAd->Mlme.RxAntEvalTimer,		&Cancelled);
@@ -734,6 +696,27 @@
 		// Set LED
 		RTMPSetLED(pAd, LED_HALT);
         RTMPSetSignalLED(pAd, -100);	// Force signal strength Led to be turned off, firmware is not done it.
+#ifdef RT2870
+        {
+            LED_CFG_STRUC LedCfg;
+            RTMP_IO_READ32(pAd, LED_CFG, &LedCfg.word);
+            LedCfg.field.LedPolar = 0;
+            LedCfg.field.RLedMode = 0;
+            LedCfg.field.GLedMode = 0;
+            LedCfg.field.YLedMode = 0;
+            RTMP_IO_WRITE32(pAd, LED_CFG, LedCfg.word);
+        }
+#endif // RT2870 //
+#ifdef RT3070
+		//
+		// Turn off LNA_PE
+		//
+		if (IS_RT3070(pAd) || IS_RT3071(pAd))
+		{
+			TxPinCfg &= 0xFFFFF0F0;
+			RTUSBWriteMACRegister(pAd, TX_PIN_CFG, TxPinCfg);
+		}
+#endif // RT3070 //
 	}
 
 	RTMPusecDelay(5000);    //  5 msec to gurantee Ant Diversity timer canceled
@@ -804,6 +787,7 @@
 	ULONG			TxTotalCnt;
 	PRTMP_ADAPTER	pAd = (RTMP_ADAPTER *)FunctionContext;
 
+#ifdef RT2860
 	//Baron 2008/07/10
 	//printk("Baron_Test:\t%s", RTMPGetRalinkEncryModeStr(pAd->StaCfg.WepStatus));
 	//If the STA security setting is OPEN or WEP, pAd->StaCfg.WpaSupplicantUP = 0.
@@ -817,8 +801,6 @@
 		pAd->StaCfg.WpaSupplicantUP = 1;
 	}
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 	    // If Hardware controlled Radio enabled, we have to check GPIO pin2 every 2 second.
 		// Move code to here, because following code will return when radio is off
@@ -858,7 +840,7 @@
 			}
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
+#endif /* RT2860 */
 
 	// Do nothing if the driver is starting halt state.
 	// This might happen when timer already been fired before cancel timer with mlmehalt
@@ -868,7 +850,7 @@
 								fRTMP_ADAPTER_RESET_IN_PROGRESS))))
 		return;
 
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+#ifdef RT2860
 	{
 		if ((pAd->RalinkCounters.LastReceivedByteCount == pAd->RalinkCounters.ReceivedByteCount) && (pAd->StaCfg.bRadio == TRUE))
 		{
@@ -906,23 +888,9 @@
 			AsicResetFromDMABusy(pAd);
 		}
 	}
-
+#endif /* RT2860 */
 	RT28XX_MLME_PRE_SANITY_CHECK(pAd);
 
-#ifdef RALINK_ATE
-	/* Do not show RSSI until "Normal 1 second Mlme PeriodicExec". */
-	if (ATE_ON(pAd))
-	{
-		if (pAd->Mlme.PeriodicRound % MLME_TASK_EXEC_MULTIPLE != (MLME_TASK_EXEC_MULTIPLE - 1))
-	{
-			pAd->Mlme.PeriodicRound ++;
-			return;
-		}
-	}
-#endif // RALINK_ATE //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		// Do nothing if monitor mode is on
 		if (MONITOR_ON(pAd))
@@ -947,26 +915,26 @@
 				}
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	pAd->bUpdateBcnCntDone = FALSE;
 
 //	RECBATimerTimeout(SystemSpecific1,FunctionContext,SystemSpecific2,SystemSpecific3);
 	pAd->Mlme.PeriodicRound ++;
 
+#ifdef RT3070
+	// execute every 100ms, update the Tx FIFO Cnt for update Tx Rate.
+	NICUpdateFifoStaCounters(pAd);
+#endif // RT3070 //
 	// execute every 500ms
 	if ((pAd->Mlme.PeriodicRound % 5 == 0) && RTMPAutoRateSwitchCheck(pAd)/*(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED))*/)
 	{
-#ifdef CONFIG_STA_SUPPORT
 		// perform dynamic tx rate switching based on past TX history
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			if ((OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)
 					)
 				&& (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE)))
 				MlmeDynamicTxRateSwitching(pAd);
 		}
-#endif // CONFIG_STA_SUPPORT //
 	}
 
 	// Normal 1 second Mlme PeriodicExec.
@@ -974,30 +942,6 @@
 	{
                 pAd->Mlme.OneSecPeriodicRound ++;
 
-#ifdef RALINK_ATE
-    	if (ATE_ON(pAd))
-    	{
-			/* request from Baron : move this routine from later to here */
-			/* for showing Rx error count in ATE RXFRAME */
-            NICUpdateRawCounters(pAd);
-			if (pAd->ate.bRxFer == 1)
-			{
-				pAd->ate.RxTotalCnt += pAd->ate.RxCntPerSec;
-			    ate_print(KERN_EMERG "MlmePeriodicExec: Rx packet cnt = %d/%d\n", pAd->ate.RxCntPerSec, pAd->ate.RxTotalCnt);
-				pAd->ate.RxCntPerSec = 0;
-
-				if (pAd->ate.RxAntennaSel == 0)
-					ate_print(KERN_EMERG "MlmePeriodicExec: Rx AvgRssi0=%d, AvgRssi1=%d, AvgRssi2=%d\n\n",
-						pAd->ate.AvgRssi0, pAd->ate.AvgRssi1, pAd->ate.AvgRssi2);
-				else
-					ate_print(KERN_EMERG "MlmePeriodicExec: Rx AvgRssi=%d\n\n", pAd->ate.AvgRssi0);
-			}
-			MlmeResetRalinkCounters(pAd);
-			return;
-    	}
-#endif // RALINK_ATE //
-
-
 		if (rx_Total)
 		{
 
@@ -1029,12 +973,12 @@
 		// the dynamic tuning mechanism below are based on most up-to-date information
 		NICUpdateRawCounters(pAd);
 
+#ifdef RT2870
+		RT2870_WatchDog(pAd);
+#endif // RT2870 //
 
-#ifdef DOT11_N_SUPPORT
    		// Need statistics after read counter. So put after NICUpdateRawCounters
 		ORIBATimerTimeout(pAd);
-#endif // DOT11_N_SUPPORT //
-
 
 		// The time period for checking antenna is according to traffic
 		if (pAd->Mlme.bEnableAutoAntennaCheck)
@@ -1043,6 +987,7 @@
 							 pAd->RalinkCounters.OneSecTxRetryOkCount +
 							 pAd->RalinkCounters.OneSecTxFailCount;
 
+			// dynamic adjust antenna evaluation period according to the traffic
 			if (TxTotalCnt > 50)
 			{
 				if (pAd->Mlme.OneSecPeriodicRound % 10 == 0)
@@ -1059,17 +1004,14 @@
 			}
 		}
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			STAMlmePeriodicExec(pAd);
-#endif // CONFIG_STA_SUPPORT //
+		STAMlmePeriodicExec(pAd);
 
 		MlmeResetRalinkCounters(pAd);
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
+#ifdef RT2860
 			if (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST) && (pAd->bPCIclkOff == FALSE))
+#endif
 			{
 				// When Adhoc beacon is enabled and RTS/CTS is enabled, there is a chance that hardware MAC FSM will run into a deadlock
 				// and sending CTS-to-self over and over.
@@ -1091,41 +1033,32 @@
 				}
 			}
 		}
-#endif // CONFIG_STA_SUPPORT //
 
 		RT28XX_MLME_HANDLER(pAd);
 	}
 
-
 	pAd->bUpdateBcnCntDone = FALSE;
 }
 
-#ifdef CONFIG_STA_SUPPORT
 VOID STAMlmePeriodicExec(
 	PRTMP_ADAPTER pAd)
 {
+#ifdef RT2860
 	ULONG			    TxTotalCnt;
+#endif
+#ifdef RT2870
+	ULONG	TxTotalCnt;
+	int 	i;
+#endif
 
-//
-// We return here in ATE mode, because the statistics
-// that ATE needs are not collected via this routine.
-//
-#ifdef RALINK_ATE
-	// It is supposed that we will never reach here in ATE mode.
-	ASSERT(!(ATE_ON(pAd)));
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
     if (pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_DISABLE)
-#endif // WPA_SUPPLICANT_SUPPORT //
     {
     	// WPA MIC error should block association attempt for 60 seconds
     	if (pAd->StaCfg.bBlockAssoc && (pAd->StaCfg.LastMicErrorTime + (60 * OS_HZ) < pAd->Mlme.Now32))
     		pAd->StaCfg.bBlockAssoc = FALSE;
     }
 
+#ifdef RT2860
 	//Baron 2008/07/10
 	//printk("Baron_Test:\t%s", RTMPGetRalinkEncryModeStr(pAd->StaCfg.WepStatus));
 	//If the STA security setting is OPEN or WEP, pAd->StaCfg.WpaSupplicantUP = 0.
@@ -1138,6 +1071,7 @@
 	{
 		pAd->StaCfg.WpaSupplicantUP = 1;
 	}
+#endif
 
     if ((pAd->PreMediaState != pAd->IndicateMediaState) && (pAd->CommonCfg.bWirelessEvent))
 	{
@@ -1148,6 +1082,7 @@
 		pAd->PreMediaState = pAd->IndicateMediaState;
 	}
 
+#ifdef RT2860
 	if ((pAd->OpMode == OPMODE_STA) && (IDLE_ON(pAd)) &&
         (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE)) &&
 		(pAd->Mlme.SyncMachine.CurrState == SYNC_IDLE) &&
@@ -1157,6 +1092,7 @@
 	{
 		RT28xxPciAsicRadioOff(pAd, GUI_IDLE_POWER_SAVE, 0);
 	}
+#endif
 
 
 
@@ -1179,11 +1115,6 @@
 
 	if (INFRA_ON(pAd))
 	{
-#ifdef QOS_DLS_SUPPORT
-		// Check DLS time out, then tear down those session
-		RTMPCheckDLSTimeOut(pAd);
-#endif // QOS_DLS_SUPPORT //
-
 		// Is PSM bit consistent with user power management policy?
 		// This is the only place that will set PSM bit ON.
 		if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
@@ -1228,26 +1159,11 @@
 			// Lost AP, send disconnect & link down event
 			LinkDown(pAd, FALSE);
 
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.WpaSupplicantUP)
-			{
-                union iwreq_data    wrqu;
-                //send disassociate event to wpa_supplicant
-                memset(&wrqu, 0, sizeof(wrqu));
-                wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-                wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
             {
                 union iwreq_data    wrqu;
                 memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
                 wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
             }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
 
 			MlmeAutoReconnectLastSSID(pAd);
 		}
@@ -1273,6 +1189,7 @@
 	}
 	else if (ADHOC_ON(pAd))
 	{
+#ifdef RT2860
 		// 2003-04-17 john. this is a patch that driver forces a BEACON out if ASIC fails
 		// the "TX BEACON competition" for the entire past 1 sec.
 		// So that even when ASIC's BEACONgen engine been blocked
@@ -1297,7 +1214,6 @@
 			pAd->StaCfg.AdhocBOnlyJoined = FALSE;
 		}
 
-#ifdef DOT11_N_SUPPORT
 		if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
 		{
 			if ((pAd->StaCfg.AdhocBGJoined) &&
@@ -1314,7 +1230,7 @@
 				pAd->StaCfg.Adhoc20NJoined = FALSE;
 			}
 		}
-#endif // DOT11_N_SUPPORT //
+#endif /* RT2860 */
 
 		//radar detect
 		if ((pAd->CommonCfg.Channel > 14)
@@ -1339,6 +1255,19 @@
 			MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_START_REQ, sizeof(MLME_START_REQ_STRUCT), &StartReq);
 			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_START;
 		}
+
+#ifdef RT2870
+		for (i = 1; i < MAX_LEN_OF_MAC_TABLE; i++)
+		{
+			MAC_TABLE_ENTRY *pEntry = &pAd->MacTab.Content[i];
+
+			if (pEntry->ValidAsCLI == FALSE)
+				continue;
+
+			if (pEntry->LastBeaconRxTime + ADHOC_BEACON_LOST_TIME < pAd->Mlme.Now32)
+				MacTableDeleteEntry(pAd, pEntry->Aid, pEntry->Addr);
+		}
+#endif
 	}
 	else // no INFRA nor ADHOC connection
 	{
@@ -1378,14 +1307,6 @@
 				}
 				else
 				{
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-					if (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-					{
-						if ((pAd->Mlme.OneSecPeriodicRound % 5) == 1)
-							MlmeAutoReconnectLastSSID(pAd);
-					}
-					else
-#endif // CARRIER_DETECTION_SUPPORT //
 						MlmeAutoReconnectLastSSID(pAd);
 				}
 			}
@@ -1394,7 +1315,6 @@
 
 SKIP_AUTO_SCAN_CONN:
 
-#ifdef DOT11_N_SUPPORT
     if ((pAd->MacTab.Content[BSSID_WCID].TXBAbitmap !=0) && (pAd->MacTab.fAnyBASession == FALSE))
 	{
 		pAd->MacTab.fAnyBASession = TRUE;
@@ -1405,15 +1325,6 @@
 		pAd->MacTab.fAnyBASession = FALSE;
 		AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode,  ALLN_SETPROTECT, FALSE, FALSE);
 	}
-#endif // DOT11_N_SUPPORT //
-
-
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SCAN_2040))
-		TriEventCounterMaintenance(pAd);
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
 
 	return;
 }
@@ -1473,7 +1384,6 @@
 		RT28XX_MLME_HANDLER(pAd);
 	}
 }
-#endif // CONFIG_STA_SUPPORT //
 
 /*
 	==========================================================================
@@ -1522,15 +1432,19 @@
 			break;
 		}
 
-#ifdef CONFIG_STA_SUPPORT
 		if ((pAd->OpMode == OPMODE_STA) && ADHOC_ON(pAd))
 		{
-#ifdef DOT11_N_SUPPORT
 			if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED) &&
+#ifdef RT2860
 				!pAd->StaCfg.AdhocBOnlyJoined &&
 				!pAd->StaCfg.AdhocBGJoined &&
 				(pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0xff) &&
 				((pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0x00) || (pAd->Antenna.field.TxPath == 1)))
+#endif
+#ifdef RT2870
+				(pEntry->HTCapability.MCSSet[0] == 0xff) &&
+				((pEntry->HTCapability.MCSSet[1] == 0x00) || (pAd->Antenna.field.TxPath == 1)))
+#endif
 			{// 11N 1S Adhoc
 				*ppTable = RateSwitchTable11N1S;
 				*pTableSize = RateSwitchTable11N1S[0];
@@ -1538,10 +1452,16 @@
 
 			}
 			else if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED) &&
+#ifdef RT2860
 					!pAd->StaCfg.AdhocBOnlyJoined &&
 					!pAd->StaCfg.AdhocBGJoined &&
 					(pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0xff) &&
 					(pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0xff) &&
+#endif
+#ifdef RT2870
+					(pEntry->HTCapability.MCSSet[0] == 0xff) &&
+					(pEntry->HTCapability.MCSSet[1] == 0xff) &&
+#endif
 					(pAd->Antenna.field.TxPath == 2))
 			{// 11N 2S Adhoc
 				if (pAd->LatchRfRegs.Channel <= 14)
@@ -1559,7 +1479,7 @@
 
 			}
 			else
-#endif // DOT11_N_SUPPORT //
+#ifdef RT2860
 				if (pAd->CommonCfg.PhyMode == PHY_11B)
 			{
 				*ppTable = RateSwitchTable11B;
@@ -1568,6 +1488,12 @@
 
 			}
 	        else if((pAd->LatchRfRegs.Channel <= 14) && (pAd->StaCfg.AdhocBOnlyJoined == TRUE))
+#endif
+#ifdef RT2870
+				if ((pEntry->RateLen == 4)
+					&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
+					)
+#endif
 			{
 				// USe B Table when Only b-only Station in my IBSS .
 				*ppTable = RateSwitchTable11B;
@@ -1591,9 +1517,7 @@
 			}
 			break;
 		}
-#endif // CONFIG_STA_SUPPORT //
 
-#ifdef DOT11_N_SUPPORT
 		if ((pEntry->RateLen == 12) && (pEntry->HTCapability.MCSSet[0] == 0xff) &&
 			((pEntry->HTCapability.MCSSet[1] == 0x00) || (pAd->CommonCfg.TxStream == 1)))
 		{// 11BGN 1S AP
@@ -1650,12 +1574,13 @@
 
 			break;
 		}
-#endif // DOT11_N_SUPPORT //
+
 		//else if ((pAd->StaActive.SupRateLen == 4) && (pAd->StaActive.ExtRateLen == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
 		if ((pEntry->RateLen == 4)
-#ifdef DOT11_N_SUPPORT
+#ifndef RT30xx
+//Iverson mark for Adhoc b mode,sta will use rate 54  Mbps when connect with sta b/g/n mode
 			&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
-#endif // DOT11_N_SUPPORT //
+#endif
 			)
 		{// B only AP
 			*ppTable = RateSwitchTable11B;
@@ -1667,9 +1592,7 @@
 
 		//else if ((pAd->StaActive.SupRateLen + pAd->StaActive.ExtRateLen > 8) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
 		if ((pEntry->RateLen > 8)
-#ifdef DOT11_N_SUPPORT
 			&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
-#endif // DOT11_N_SUPPORT //
 			)
 		{// B/G  mixed AP
 			*ppTable = RateSwitchTable11BG;
@@ -1681,9 +1604,7 @@
 
 		//else if ((pAd->StaActive.SupRateLen + pAd->StaActive.ExtRateLen == 8) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
 		if ((pEntry->RateLen == 8)
-#ifdef DOT11_N_SUPPORT
 			&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
-#endif // DOT11_N_SUPPORT //
 			)
 		{// G only AP
 			*ppTable = RateSwitchTable11G;
@@ -1692,16 +1613,10 @@
 
 			break;
 		}
-#ifdef DOT11_N_SUPPORT
-#endif // DOT11_N_SUPPORT //
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
-#ifdef DOT11_N_SUPPORT
 			//else if ((pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
 			if ((pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0))
-#endif // DOT11_N_SUPPORT //
 			{	// Legacy mode
 				if (pAd->CommonCfg.MaxTxRate <= RATE_11)
 				{
@@ -1724,7 +1639,7 @@
 				}
 				break;
 			}
-#ifdef DOT11_N_SUPPORT
+
 			if (pAd->LatchRfRegs.Channel <= 14)
 			{
 				if (pAd->CommonCfg.TxStream == 1)
@@ -1759,15 +1674,13 @@
 					DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode,default use 11N 2S AP \n"));
 				}
 			}
-#endif // DOT11_N_SUPPORT //
+
 			DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode (SupRateLen=%d, ExtRateLen=%d, MCSSet[0]=0x%x, MCSSet[1]=0x%x)\n",
 				pAd->StaActive.SupRateLen, pAd->StaActive.ExtRateLen, pAd->StaActive.SupportedPhyInfo.MCSSet[0], pAd->StaActive.SupportedPhyInfo.MCSSet[1]));
 		}
-#endif // CONFIG_STA_SUPPORT //
 	} while(FALSE);
 }
 
-#ifdef CONFIG_STA_SUPPORT
 /*
 	==========================================================================
 	Description:
@@ -1921,14 +1834,6 @@
 	CHAR  MaxRssi;
 	ULONG BeaconLostTime = BEACON_LOST_TIME;
 
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-	// longer beacon lost time when carrier detection enabled
-	if (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-	{
-		BeaconLostTime = BEACON_LOST_TIME + BEACON_LOST_TIME/2;
-	}
-#endif // CARRIER_DETECTION_SUPPORT //
-
 	MaxRssi = RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2);
 
 	//
@@ -1993,13 +1898,11 @@
 {
 	UCHAR	MaxMode = MODE_OFDM;
 
-#ifdef DOT11_N_SUPPORT
 	MaxMode = MODE_HTGREENFIELD;
 
 	if (pTxRate->STBC && (pAd->StaCfg.MaxHTPhyMode.field.STBC) && (pAd->Antenna.field.TxPath == 2))
 		pAd->StaCfg.HTPhyMode.field.STBC = STBC_USE;
 	else
-#endif // DOT11_N_SUPPORT //
 		pAd->StaCfg.HTPhyMode.field.STBC = STBC_NONE;
 
 	if (pTxRate->CurrMCS < MCS_AUTO)
@@ -2029,14 +1932,11 @@
 		if (pTxRate->Mode <= MaxMode)
 			pAd->StaCfg.HTPhyMode.field.MODE = pTxRate->Mode;
 
-#ifdef DOT11_N_SUPPORT
 		if (pTxRate->ShortGI && (pAd->StaCfg.MaxHTPhyMode.field.ShortGI))
 			pAd->StaCfg.HTPhyMode.field.ShortGI = GI_400;
 		else
-#endif // DOT11_N_SUPPORT //
 			pAd->StaCfg.HTPhyMode.field.ShortGI = GI_800;
 
-#ifdef DOT11_N_SUPPORT
 		// Reexam each bandwidth's SGI support.
 		if (pAd->StaCfg.HTPhyMode.field.ShortGI == GI_400)
 		{
@@ -2080,17 +1980,15 @@
 		{
 			AsicUpdateProtect(pAd, HT_RTSCTS_6M, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
 		}
-#endif // DOT11_N_SUPPORT //
 
 		pEntry->HTPhyMode.field.STBC	= pAd->StaCfg.HTPhyMode.field.STBC;
 		pEntry->HTPhyMode.field.ShortGI	= pAd->StaCfg.HTPhyMode.field.ShortGI;
 		pEntry->HTPhyMode.field.MCS		= pAd->StaCfg.HTPhyMode.field.MCS;
 		pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-#ifdef DOT11_N_SUPPORT
+
 		if ((pAd->StaCfg.MaxHTPhyMode.field.MODE == MODE_HTGREENFIELD) &&
 		    pAd->WIFItestbed.bGreenField)
 		    pEntry->HTPhyMode.field.MODE = MODE_HTGREENFIELD;
-#endif // DOT11_N_SUPPORT //
 	}
 
 	pAd->LastTxRate = (USHORT)(pEntry->HTPhyMode.word);
@@ -2130,18 +2028,6 @@
 	ULONG					TxRetransmit = 0, TxSuccess = 0, TxFailCount = 0;
 	MAC_TABLE_ENTRY			*pEntry;
 
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-		return;
-	}
-#endif // RALINK_ATE //
-
-	/*if (pAd->Antenna.field.RxPath > 1)
-		Rssi = (pAd->StaCfg.RssiSample.AvgRssi0 + pAd->StaCfg.RssiSample.AvgRssi1) >> 1;
-	else
-		Rssi = pAd->StaCfg.RssiSample.AvgRssi0;*/
-
 	//
 	// walk through MAC table, see if need to change AP's TX rate toward each entry
 	//
@@ -2155,7 +2041,15 @@
 
 		if ((pAd->MacTab.Size == 1) || (pEntry->ValidAsDls))
 		{
+#ifdef RT2860
 			Rssi = RTMPMaxRssi(pAd, (CHAR)pAd->StaCfg.RssiSample.AvgRssi0, (CHAR)pAd->StaCfg.RssiSample.AvgRssi1, (CHAR)pAd->StaCfg.RssiSample.AvgRssi2);
+#endif
+#ifdef RT2870
+			Rssi = RTMPMaxRssi(pAd,
+							   pAd->StaCfg.RssiSample.AvgRssi0,
+							   pAd->StaCfg.RssiSample.AvgRssi1,
+							   pAd->StaCfg.RssiSample.AvgRssi2);
+#endif
 
 			// Update statistic counter
 			RTMP_IO_READ32(pAd, TX_STA_CNT0, &TxStaCnt0.word);
@@ -2185,7 +2079,21 @@
 		}
 		else
 		{
+#ifdef RT2860
 			Rssi = RTMPMaxRssi(pAd, (CHAR)pEntry->RssiSample.AvgRssi0, (CHAR)pEntry->RssiSample.AvgRssi1, (CHAR)pEntry->RssiSample.AvgRssi2);
+#endif
+#ifdef RT2870
+			if (INFRA_ON(pAd) && (i == 1))
+				Rssi = RTMPMaxRssi(pAd,
+								   pAd->StaCfg.RssiSample.AvgRssi0,
+								   pAd->StaCfg.RssiSample.AvgRssi1,
+								   pAd->StaCfg.RssiSample.AvgRssi2);
+			else
+				Rssi = RTMPMaxRssi(pAd,
+								   pEntry->RssiSample.AvgRssi0,
+								   pEntry->RssiSample.AvgRssi1,
+								   pEntry->RssiSample.AvgRssi2);
+#endif
 
 			TxTotalCnt = pEntry->OneSecTxNoRetryOkCount +
 				 pEntry->OneSecTxRetryOkCount +
@@ -2242,14 +2150,12 @@
 
 		pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(CurrRateIdx+1)*5];
 
-#ifdef DOT11_N_SUPPORT
 		if ((Rssi > -65) && (pCurrTxRate->Mode >= MODE_HTMIX))
 		{
 			TrainUp		= (pCurrTxRate->TrainUp + (pCurrTxRate->TrainUp >> 1));
 			TrainDown	= (pCurrTxRate->TrainDown + (pCurrTxRate->TrainDown >> 1));
 		}
 		else
-#endif // DOT11_N_SUPPORT //
 		{
 			TrainUp		= pCurrTxRate->TrainUp;
 			TrainDown	= pCurrTxRate->TrainDown;
@@ -2327,7 +2233,6 @@
 				{
 					MCS14 = idx;
 				}
-				//else if ((pCurrTxRate->CurrMCS == MCS_15)/* && (pCurrTxRate->ShortGI == GI_800)*/)	//we hope to use ShortGI as initial rate
 				else if ((pCurrTxRate->CurrMCS == MCS_15) && (pCurrTxRate->ShortGI == GI_800))	//we hope to use ShortGI as initial rate, however Atheros's chip has bugs when short GI
 				{
 					MCS15 = idx;
@@ -2373,7 +2278,7 @@
 					RssiOffset = 8;
 				}
 			}
-#ifdef DOT11_N_SUPPORT
+
 			/*if (MCS15)*/
 			if ((pTable == RateSwitchTable11BGN3S) ||
 				(pTable == RateSwitchTable11N3S) ||
@@ -2439,7 +2344,6 @@
 					TxRateIdx = MCS0;
 			}
 			else
-#endif // DOT11_N_SUPPORT //
 			{// Legacy mode
 				if (MCS7 && (Rssi > -70))
 					TxRateIdx = MCS7;
@@ -2613,7 +2517,12 @@
 	UCHAR					UpRateIdx = 0, DownRateIdx = 0, CurrRateIdx = 0;
 	ULONG					TxTotalCnt;
 	ULONG					TxErrorRatio = 0;
+#ifdef RT2860
 	BOOLEAN					bTxRateChanged = TRUE; //, bUpgradeQuality = FALSE;
+#endif
+#ifdef RT2870
+	BOOLEAN					bTxRateChanged; //, bUpgradeQuality = FALSE;
+#endif
 	PRTMP_TX_RATE_SWITCH	pCurrTxRate, pNextTxRate = NULL;
 	PUCHAR					pTable;
 	UCHAR					TableSize = 0;
@@ -2638,11 +2547,25 @@
 		if (RTMPCheckEntryEnableAutoRateSwitch(pAd, pEntry) == FALSE)
 			continue;
 
+#ifdef RT2860
 		//Rssi = RTMPMaxRssi(pAd, (CHAR)pAd->StaCfg.AvgRssi0, (CHAR)pAd->StaCfg.AvgRssi1, (CHAR)pAd->StaCfg.AvgRssi2);
 	    if (pAd->Antenna.field.TxPath > 1)
 			Rssi = (pAd->StaCfg.RssiSample.AvgRssi0 + pAd->StaCfg.RssiSample.AvgRssi1) >> 1;
 		else
 			Rssi = pAd->StaCfg.RssiSample.AvgRssi0;
+#endif
+#ifdef RT2870
+		if (INFRA_ON(pAd) && (i == 1))
+			Rssi = RTMPMaxRssi(pAd,
+							   pAd->StaCfg.RssiSample.AvgRssi0,
+							   pAd->StaCfg.RssiSample.AvgRssi1,
+							   pAd->StaCfg.RssiSample.AvgRssi2);
+		else
+			Rssi = RTMPMaxRssi(pAd,
+							   pEntry->RssiSample.AvgRssi0,
+							   pEntry->RssiSample.AvgRssi1,
+							   pEntry->RssiSample.AvgRssi2);
+#endif
 
 		CurrRateIdx = pAd->CommonCfg.TxRateIndex;
 
@@ -2667,14 +2590,12 @@
 
 		pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(CurrRateIdx+1)*5];
 
-#ifdef DOT11_N_SUPPORT
 		if ((Rssi > -65) && (pCurrTxRate->Mode >= MODE_HTMIX))
 		{
 			TrainUp		= (pCurrTxRate->TrainUp + (pCurrTxRate->TrainUp >> 1));
 			TrainDown	= (pCurrTxRate->TrainDown + (pCurrTxRate->TrainDown >> 1));
 		}
 		else
-#endif // DOT11_N_SUPPORT //
 		{
 			TrainUp		= pCurrTxRate->TrainUp;
 			TrainDown	= pCurrTxRate->TrainDown;
@@ -2784,6 +2705,9 @@
 			pAd->DrsCounters.TxRateUpPenalty = 0;
 			NdisZeroMemory(pAd->DrsCounters.TxQuality, sizeof(USHORT) * MAX_STEP_OF_TX_RATE_SWITCH);
 			NdisZeroMemory(pAd->DrsCounters.PER, sizeof(UCHAR) * MAX_STEP_OF_TX_RATE_SWITCH);
+#ifdef RT2870
+			bTxRateChanged = TRUE;
+#endif
 		}
 		// if rate-down happen, only clear DownRate's bad history
 		else if (pAd->CommonCfg.TxRateIndex < CurrRateIdx)
@@ -2793,6 +2717,9 @@
 			pAd->DrsCounters.TxRateUpPenalty = 0;           // no penalty
 			pAd->DrsCounters.TxQuality[pAd->CommonCfg.TxRateIndex] = 0;
 			pAd->DrsCounters.PER[pAd->CommonCfg.TxRateIndex] = 0;
+#ifdef RT2870
+			bTxRateChanged = TRUE;
+#endif
 		}
 		else
 		{
@@ -2848,7 +2775,13 @@
 	if (INFRA_ON(pAd) &&
 		(PowerMode != Ndis802_11PowerModeCAM) &&
 		(pAd->StaCfg.Psm == PWR_ACTIVE) &&
+#ifdef RT2860
 		RTMP_TEST_PSFLAG(pAd, fRTMP_PS_CAN_GO_SLEEP))
+#endif
+#if !defined(RT2860) && !defined(RT30xx)
+		(pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE))
+#endif
+#ifndef RT30xx
 	{
 		NdisGetSystemUpTime(&pAd->Mlme.LastSendNULLpsmTime);
 		pAd->RalinkCounters.RxCountSinceLastNULL = 0;
@@ -2862,6 +2795,42 @@
 			RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, TRUE);
 		}
 	}
+#endif
+#ifdef RT30xx
+//		(! RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
+		(pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE) /*&&
+		(pAd->RalinkCounters.OneSecTxNoRetryOkCount == 0) &&
+		(pAd->RalinkCounters.OneSecTxRetryOkCount == 0)*/)
+	{
+		// add by johnli, use Rx OK data count per second to calculate throughput
+		// If Ttraffic is too high ( > 400 Rx per second), don't go to sleep mode. If tx rate is low, use low criteria
+		// Mode=CCK/MCS=3 => 11 Mbps, Mode=OFDM/MCS=3 => 18 Mbps
+		if (((pAd->StaCfg.HTPhyMode.field.MCS <= 3) &&
+/* Iverson mark
+				(pAd->StaCfg.HTPhyMode.field.MODE <= MODE_OFDM) &&
+*/
+				(pAd->RalinkCounters.OneSecRxOkDataCnt < (ULONG)100)) ||
+			((pAd->StaCfg.HTPhyMode.field.MCS > 3) &&
+/* Iverson mark
+			(pAd->StaCfg.HTPhyMode.field.MODE > MODE_OFDM) &&
+*/
+			(pAd->RalinkCounters.OneSecRxOkDataCnt < (ULONG)400)))
+		{
+				// Get this time
+			NdisGetSystemUpTime(&pAd->Mlme.LastSendNULLpsmTime);
+			pAd->RalinkCounters.RxCountSinceLastNULL = 0;
+			MlmeSetPsmBit(pAd, PWR_SAVE);
+			if (!(pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable))
+			{
+				RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, FALSE);
+			}
+			else
+			{
+				RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, TRUE);
+			}
+		}
+	}
+#endif
 }
 
 // IRQL = PASSIVE_LEVEL
@@ -2876,10 +2845,10 @@
 	RTMP_IO_READ32(pAd, AUTO_RSP_CFG, &csr4.word);
 	csr4.field.AckCtsPsmBit = (psm == PWR_SAVE)? 1:0;
 	RTMP_IO_WRITE32(pAd, AUTO_RSP_CFG, csr4.word);
+#ifndef RT30xx
 	DBGPRINT(RT_DEBUG_TRACE, ("MlmeSetPsmBit = %d\n", psm));
+#endif
 }
-#endif // CONFIG_STA_SUPPORT //
-
 
 // IRQL = DISPATCH_LEVEL
 VOID MlmeSetTxPreamble(
@@ -3018,9 +2987,6 @@
 
 //===========================================================================
 //===========================================================================
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		pHtPhy 		= &pAd->StaCfg.HTPhyMode;
 		pMaxHtPhy	= &pAd->StaCfg.MaxHTPhyMode;
@@ -3036,7 +3002,6 @@
 			MaxDesire = RATE_11;
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	pAd->CommonCfg.MaxDesiredRate = MaxDesire;
 	pMinHtPhy->word = 0;
@@ -3065,7 +3030,6 @@
 	}
 #endif
 
-#ifdef CONFIG_STA_SUPPORT
 	if ((ADHOC_ON(pAd) || INFRA_ON(pAd)) && (pAd->OpMode == OPMODE_STA))
 	{
 		pSupRate = &pAd->StaActive.SupRate[0];
@@ -3074,7 +3038,6 @@
 		ExtRateLen = pAd->StaActive.ExtRateLen;
 	}
 	else
-#endif // CONFIG_STA_SUPPORT //
 	{
 		pSupRate = &pAd->CommonCfg.SupRate[0];
 		pExtRate = &pAd->CommonCfg.ExtRate[0];
@@ -3151,10 +3114,9 @@
 	if (*auto_rate_cur_p)
 	{
 		short dbm = 0;
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			dbm = pAd->StaCfg.RssiSample.AvgRssi0 - pAd->BbpRssiToDbmDelta;
-#endif // CONFIG_STA_SUPPORT //
+
+		dbm = pAd->StaCfg.RssiSample.AvgRssi0 - pAd->BbpRssiToDbmDelta;
+
 		if (bLinkUp == TRUE)
 			pAd->CommonCfg.TxRate = RATE_24;
 		else
@@ -3212,9 +3174,7 @@
 		{
 			case PHY_11BG_MIXED:
 			case PHY_11B:
-#ifdef DOT11_N_SUPPORT
 			case PHY_11BGN_MIXED:
-#endif // DOT11_N_SUPPORT //
 				pAd->CommonCfg.MlmeRate = RATE_1;
 				pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_CCK;
 				pAd->CommonCfg.MlmeTransmit.field.MCS = RATE_1;
@@ -3222,22 +3182,18 @@
 				break;
 			case PHY_11G:
 			case PHY_11A:
-#ifdef DOT11_N_SUPPORT
 			case PHY_11AGN_MIXED:
 			case PHY_11GN_MIXED:
 			case PHY_11N_2_4G:
 			case PHY_11AN_MIXED:
 			case PHY_11N_5G:
-#endif // DOT11_N_SUPPORT //
 				pAd->CommonCfg.MlmeRate = RATE_6;
 				pAd->CommonCfg.RtsRate = RATE_6;
 				pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
 				pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
 				break;
 			case PHY_11ABG_MIXED:
-#ifdef DOT11_N_SUPPORT
 			case PHY_11ABGN_MIXED:
-#endif // DOT11_N_SUPPORT //
 				if (pAd->CommonCfg.Channel <= 14)
 				{
 					pAd->CommonCfg.MlmeRate = RATE_1;
@@ -3280,7 +3236,6 @@
 			 pAd->CommonCfg.MlmeTransmit.word, pAd->MacTab.Content[BSSID_WCID].MinHTPhyMode.word ,pAd->MacTab.Content[BSSID_WCID].MaxHTPhyMode.word ,pAd->MacTab.Content[BSSID_WCID].HTPhyMode.word ));
 }
 
-#ifdef DOT11_N_SUPPORT
 /*
 	==========================================================================
 	Description:
@@ -3313,8 +3268,6 @@
 
 	auto_rate_cur_p = NULL;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		pDesireHtPhy	= &pAd->StaCfg.DesiredHtPhyInfo;
 		pActiveHtPhy	= &pAd->StaCfg.DesiredHtPhyInfo;
@@ -3324,9 +3277,7 @@
 
 		auto_rate_cur_p = &pAd->StaCfg.bAutoTxRateSwitch;
 	}
-#endif // CONFIG_STA_SUPPORT //
 
-#ifdef CONFIG_STA_SUPPORT
 	if ((ADHOC_ON(pAd) || INFRA_ON(pAd)) && (pAd->OpMode == OPMODE_STA))
 	{
 		if (pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE)
@@ -3342,7 +3293,6 @@
 			pMaxHtPhy->field.STBC = STBC_NONE;
 	}
 	else
-#endif // CONFIG_STA_SUPPORT //
 	{
 		if (pDesireHtPhy->bHtEnable == FALSE)
 			return;
@@ -3393,7 +3343,6 @@
 	pMinHtPhy->field.STBC = 0;
 	pMinHtPhy->field.ShortGI = 0;
 	//If STA assigns fixed rate. update to fixed here.
-#ifdef CONFIG_STA_SUPPORT
 	if ( (pAd->OpMode == OPMODE_STA) && (pDesireHtPhy->MCSSet[0] != 0xff))
 	{
 		if (pDesireHtPhy->MCSSet[4] != 0)
@@ -3417,8 +3366,6 @@
 				break;
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
-
 
 	// Decide ht rate
 	pHtPhy->field.STBC = pMaxHtPhy->field.STBC;
@@ -3438,7 +3385,6 @@
 		pHtPhy->field.BW, pHtPhy->field.ShortGI, pHtPhy->field.MODE));
 	DBGPRINT(RT_DEBUG_TRACE,("MlmeUpdateHtTxRates<=== \n"));
 }
-#endif // DOT11_N_SUPPORT //
 
 // IRQL = DISPATCH_LEVEL
 VOID MlmeRadioOff(
@@ -3483,7 +3429,6 @@
 	}
 }
 
-#ifdef DOT11_N_SUPPORT
 VOID BATableInit(
 	IN PRTMP_ADAPTER pAd,
     IN BA_TABLE *Tab)
@@ -3503,7 +3448,6 @@
 		Tab->BAOriEntry[i].ORI_BA_Status = Originator_NONE;
 	}
 }
-#endif // DOT11_N_SUPPORT //
 
 /*! \brief search the BSS table by SSID
  *	\param p_tab pointer to the bss table
@@ -3613,7 +3557,6 @@
 	}
 }
 
-#ifdef DOT11_N_SUPPORT
 /*
 	========================================================================
 	Routine Description:
@@ -3645,7 +3588,6 @@
 		NdisReleaseSpinLock(&pAd->BATabLock);
 	}
 }
-#endif // DOT11_N_SUPPORT //
 
 /*! \brief
  *	\param
@@ -3762,7 +3704,7 @@
 
 	pBss->AddHtInfoLen = 0;
 	pBss->HtCapabilityLen = 0;
-#ifdef DOT11_N_SUPPORT
+
 	if (HtCapabilityLen> 0)
 	{
 		pBss->HtCapabilityLen = HtCapabilityLen;
@@ -3782,7 +3724,6 @@
 				}
 		}
 	}
-#endif // DOT11_N_SUPPORT //
 
 	BssCipherParse(pBss);
 
@@ -3800,8 +3741,6 @@
 	else
 		pBss->QbssLoad.bValid = FALSE;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		PEID_STRUCT     pEid;
 		USHORT          Length = 0;
@@ -3809,11 +3748,9 @@
 
 		NdisZeroMemory(&pBss->WpaIE.IE[0], MAX_CUSTOM_LEN);
 		NdisZeroMemory(&pBss->RsnIE.IE[0], MAX_CUSTOM_LEN);
-#ifdef EXT_BUILD_CHANNEL_LIST
-		NdisZeroMemory(&pBss->CountryString[0], 3);
-		pBss->bHasCountryIE = FALSE;
-#endif // EXT_BUILD_CHANNEL_LIST //
+
 		pEid = (PEID_STRUCT) pVIE;
+
 		while ((Length + 2 + (USHORT)pEid->Len) <= LengthVIE)
 		{
 			switch(pEid->Eid)
@@ -3842,18 +3779,11 @@
 						NdisMoveMemory(pBss->RsnIE.IE, pEid, pBss->RsnIE.IELen);
 			}
 				break;
-#ifdef EXT_BUILD_CHANNEL_LIST
-				case IE_COUNTRY:
-					NdisMoveMemory(&pBss->CountryString[0], pEid->Octet, 3);
-					pBss->bHasCountryIE = TRUE;
-					break;
-#endif // EXT_BUILD_CHANNEL_LIST //
             }
 			Length = Length + 2 + (USHORT)pEid->Len;  // Eid[1] + Len[1]+ content[Len]
 			pEid = (PEID_STRUCT)((UCHAR*)pEid + 2 + pEid->Len);
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 }
 
 /*!
@@ -3947,120 +3877,23 @@
 	}
 	else
 	{
+#ifdef RT30xx
+		/* avoid  Hidden SSID form beacon to overwirite correct SSID from probe response */
+		if ((SSID_EQUAL(Ssid, SsidLen, Tab->BssEntry[Idx].Ssid, Tab->BssEntry[Idx].SsidLen)) ||
+			(NdisEqualMemory(Tab->BssEntry[Idx].Ssid, ZeroSsid, Tab->BssEntry[Idx].SsidLen)))
+		{
+#endif
 		BssEntrySet(pAd, &Tab->BssEntry[Idx], pBssid, Ssid, SsidLen, BssType, BeaconPeriod,CfParm, AtimWin,
 					CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,pHtCapability, pAddHtInfo,HtCapabilityLen, AddHtInfoLen,
 					NewExtChanOffset, ChannelNo, Rssi, TimeStamp, CkipFlag, pEdcaParm, pQosCapability, pQbssLoad, LengthVIE, pVIE);
+#ifdef RT30xx
+		}
+#endif
 	}
 
 	return Idx;
 }
 
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-VOID  TriEventInit(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UCHAR		i;
-
-	for (i = 0;i < MAX_TRIGGER_EVENT;i++)
-		pAd->CommonCfg.TriggerEventTab.EventA[i].bValid = FALSE;
-
-	pAd->CommonCfg.TriggerEventTab.EventANo = 0;
-	pAd->CommonCfg.TriggerEventTab.EventBCountDown = 0;
-}
-
-ULONG TriEventTableSetEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT TRIGGER_EVENT_TAB *Tab,
-	IN PUCHAR pBssid,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			RegClass,
-	IN UCHAR ChannelNo)
-{
-	// Event A
-	if (HtCapabilityLen == 0)
-	{
-		if (Tab->EventANo < MAX_TRIGGER_EVENT)
-		{
-			RTMPMoveMemory(Tab->EventA[Tab->EventANo].BSSID, pBssid, 6);
-			Tab->EventA[Tab->EventANo].bValid = TRUE;
-			Tab->EventA[Tab->EventANo].Channel = ChannelNo;
-			Tab->EventA[Tab->EventANo].CDCounter = pAd->CommonCfg.Dot11BssWidthChanTranDelay;
-			if (RegClass != 0)
-			{
-				// Beacon has Regulatory class IE. So use beacon's
-				Tab->EventA[Tab->EventANo].RegClass = RegClass;
-			}
-			else
-			{
-				// Use Station's Regulatory class instead.
-				if (pAd->StaActive.SupportedHtPhy.bHtEnable == TRUE)
-				{
-					if (pAd->CommonCfg.CentralChannel > pAd->CommonCfg.Channel)
-					{
-						Tab->EventA[Tab->EventANo].RegClass = 32;
-					}
-					else if (pAd->CommonCfg.CentralChannel < pAd->CommonCfg.Channel)
-						Tab->EventA[Tab->EventANo].RegClass = 33;
-				}
-				else
-					Tab->EventA[Tab->EventANo].RegClass = ??;
-
-			}
-
-			Tab->EventANo ++;
-		}
-	}
-	else if (pHtCapability->HtCapInfo.Intolerant40)
-	{
-		Tab->EventBCountDown = pAd->CommonCfg.Dot11BssWidthChanTranDelay;
-	}
-
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Trigger Event table Maintainence called once every second.
-
-	Arguments:
-	// IRQL = DISPATCH_LEVEL
-	========================================================================
-*/
-VOID TriEventCounterMaintenance(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UCHAR		i;
-	BOOLEAN			bNotify = FALSE;
-	for (i = 0;i < MAX_TRIGGER_EVENT;i++)
-	{
-		if (pAd->CommonCfg.TriggerEventTab.EventA[i].bValid && (pAd->CommonCfg.TriggerEventTab.EventA[i].CDCounter > 0))
-		{
-			pAd->CommonCfg.TriggerEventTab.EventA[i].CDCounter--;
-			if (pAd->CommonCfg.TriggerEventTab.EventA[i].CDCounter == 0)
-			{
-				pAd->CommonCfg.TriggerEventTab.EventA[i].bValid = FALSE;
-				pAd->CommonCfg.TriggerEventTab.EventANo --;
-				// Need to send 20/40 Coexistence Notify frame if has status change.
-				bNotify = TRUE;
-			}
-		}
-	}
-	if (pAd->CommonCfg.TriggerEventTab.EventBCountDown > 0)
-	{
-		pAd->CommonCfg.TriggerEventTab.EventBCountDown--;
-		if (pAd->CommonCfg.TriggerEventTab.EventBCountDown == 0)
-			bNotify = TRUE;
-	}
-
-	if (bNotify == TRUE)
-		Update2040CoexistFrameAndNotify(pAd, BSSID_WCID, TRUE);
-}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
 // IRQL = DISPATCH_LEVEL
 VOID BssTableSsidSort(
 	IN	PRTMP_ADAPTER	pAd,
@@ -4079,9 +3912,6 @@
 		if (((pAd->CommonCfg.bIEEE80211H == 1) &&
             (pAd->MlmeAux.Channel > 14) &&
              RadarChannelCheck(pAd, pInBss->Channel))
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-             || (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-#endif // CARRIER_DETECTION_SUPPORT //
             )
 		{
 			if (pInBss->Hidden)
@@ -4093,18 +3923,6 @@
 		{
 			BSS_ENTRY *pOutBss = &OutTab->BssEntry[OutTab->BssNr];
 
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-			// If no Country IE exists no Connection will be established when IEEE80211dClientMode is strict.
-			if ((pAd->StaCfg.IEEE80211dClientMode == Rt802_11_D_Strict) &&
-				(pInBss->bHasCountryIE == FALSE))
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("StaCfg.IEEE80211dClientMode == Rt802_11_D_Strict, but this AP doesn't have country IE.\n"));
-				continue;
-			}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef DOT11_N_SUPPORT
 			// 2.4G/5G N only mode
 			if ((pInBss->HtCapabilityLen == 0) &&
 				((pAd->CommonCfg.PhyMode == PHY_11N_2_4G) || (pAd->CommonCfg.PhyMode == PHY_11N_5G)))
@@ -4112,7 +3930,6 @@
 				DBGPRINT(RT_DEBUG_TRACE,("STA is in N-only Mode, this AP don't have Ht capability in Beacon.\n"));
 				continue;
 			}
-#endif // DOT11_N_SUPPORT //
 
 			// New for WPA2
 			// Check the Authmode first
@@ -4132,9 +3949,14 @@
 							continue;
 
 					// check group cipher
+#ifndef RT30xx
 					if ((pAd->StaCfg.WepStatus < pInBss->WPA.GroupCipher) &&
 						(pInBss->WPA.GroupCipher != Ndis802_11GroupWEP40Enabled) &&
 						(pInBss->WPA.GroupCipher != Ndis802_11GroupWEP104Enabled))
+#endif
+#ifdef RT30xx
+					if (pAd->StaCfg.WepStatus < pInBss->WPA.GroupCipher)
+#endif
 						continue;
 
 					// check pairwise cipher, skip if none matched
@@ -4153,9 +3975,14 @@
 							continue;
 
 					// check group cipher
+#ifndef RT30xx
 					if ((pAd->StaCfg.WepStatus < pInBss->WPA.GroupCipher) &&
 						(pInBss->WPA2.GroupCipher != Ndis802_11GroupWEP40Enabled) &&
 						(pInBss->WPA2.GroupCipher != Ndis802_11GroupWEP104Enabled))
+#endif
+#ifdef RT30xx
+					if (pAd->StaCfg.WepStatus < pInBss->WPA2.GroupCipher)
+#endif
 						continue;
 
 					// check pairwise cipher, skip if none matched
@@ -4185,7 +4012,6 @@
 			if (SsidLen == 0)
 				continue;
 
-#ifdef DOT11_N_SUPPORT
 			// If both station and AP use 40MHz, still need to check if the 40MHZ band's legality in my country region
 			// If this 40MHz wideband is not allowed in my country list, use bandwidth 20MHZ instead,
 			if ((pInBss->CentralChannel != pInBss->Channel) &&
@@ -4205,7 +4031,6 @@
 					}
 				}
 			}
-#endif // DOT11_N_SUPPORT //
 
 			// copy matching BSS from InTab to OutTab
 			NdisMoveMemory(pOutBss, pInBss, sizeof(BSS_ENTRY));
@@ -4216,8 +4041,6 @@
 		{
 			BSS_ENTRY *pOutBss = &OutTab->BssEntry[OutTab->BssNr];
 
-
-#ifdef DOT11_N_SUPPORT
 			// 2.4G/5G N only mode
 			if ((pInBss->HtCapabilityLen == 0) &&
 				((pAd->CommonCfg.PhyMode == PHY_11N_2_4G) || (pAd->CommonCfg.PhyMode == PHY_11N_5G)))
@@ -4225,7 +4048,6 @@
 				DBGPRINT(RT_DEBUG_TRACE,("STA is in N-only Mode, this AP don't have Ht capability in Beacon.\n"));
 				continue;
 			}
-#endif // DOT11_N_SUPPORT //
 
 			// New for WPA2
 			// Check the Authmode first
@@ -4281,7 +4103,6 @@
 			else if (pAd->StaCfg.WepStatus != pInBss->WepStatus)
 					continue;
 
-#ifdef DOT11_N_SUPPORT
 			// If both station and AP use 40MHz, still need to check if the 40MHZ band's legality in my country region
 			// If this 40MHz wideband is not allowed in my country list, use bandwidth 20MHZ instead,
 			if ((pInBss->CentralChannel != pInBss->Channel) &&
@@ -4294,7 +4115,6 @@
 					pAd->CommonCfg.RegTransmitSetting.field.BW = BW_40;
 				}
 			}
-#endif // DOT11_N_SUPPORT //
 
 			// copy matching BSS from InTab to OutTab
 			NdisMoveMemory(pOutBss, pInBss, sizeof(BSS_ENTRY));
@@ -4330,8 +4150,6 @@
 		}
 	}
 }
-#endif // CONFIG_STA_SUPPORT //
-
 
 VOID BssCipherParse(
 	IN OUT	PBSS_ENTRY	pBss)
@@ -4442,10 +4260,16 @@
 				switch (*pTmp)
 				{
 					case 1:
+#ifndef RT30xx
 						pBss->WPA.GroupCipher = Ndis802_11GroupWEP40Enabled;
 						break;
 					case 5:
 						pBss->WPA.GroupCipher = Ndis802_11GroupWEP104Enabled;
+#endif
+#ifdef RT30xx
+					case 5:	// Although WEP is not allowed in WPA related auth mode, we parse it anyway
+						pBss->WPA.GroupCipher = Ndis802_11Encryption1Enabled;
+#endif
 						break;
 					case 2:
 						pBss->WPA.GroupCipher = Ndis802_11Encryption2Enabled;
@@ -4532,7 +4356,6 @@
 					pBss->AuthMode	  = Ndis802_11AuthModeWPANone;
 					pBss->AuthModeAux = Ndis802_11AuthModeWPANone;
 					pBss->WepStatus   = pBss->WPA.GroupCipher;
-					// Patched bugs for old driver
 					if (pBss->WPA.PairCipherAux == Ndis802_11WEPDisabled)
 						pBss->WPA.PairCipherAux = pBss->WPA.GroupCipher;
 				}
@@ -4562,10 +4385,16 @@
 				switch (pCipher->Type)
 				{
 					case 1:
+#ifndef RT30xx
 						pBss->WPA2.GroupCipher = Ndis802_11GroupWEP40Enabled;
 						break;
 					case 5:
 						pBss->WPA2.GroupCipher = Ndis802_11GroupWEP104Enabled;
+#endif
+#ifdef RT30xx
+					case 5:	// Although WEP is not allowed in WPA related auth mode, we parse it anyway
+						pBss->WPA2.GroupCipher = Ndis802_11Encryption1Enabled;
+#endif
 						break;
 					case 2:
 						pBss->WPA2.GroupCipher = Ndis802_11Encryption2Enabled;
@@ -4659,7 +4488,6 @@
 					pBss->WPA.PairCipherAux = pBss->WPA2.PairCipherAux;
 					pBss->WPA.GroupCipher	= pBss->WPA2.GroupCipher;
 					pBss->WepStatus 		= pBss->WPA.GroupCipher;
-					// Patched bugs for old driver
 					if (pBss->WPA.PairCipherAux == Ndis802_11WEPDisabled)
 						pBss->WPA.PairCipherAux = pBss->WPA.GroupCipher;
 				}
@@ -4735,10 +4563,9 @@
 	pHdr80211->FC.SubType = SubType;
 	pHdr80211->FC.ToDs = ToDs;
 	COPY_MAC_ADDR(pHdr80211->Addr1, pDA);
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		COPY_MAC_ADDR(pHdr80211->Addr2, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
+
+	COPY_MAC_ADDR(pHdr80211->Addr2, pAd->CurrentAddress);
+
 	COPY_MAC_ADDR(pHdr80211->Addr3, pBssid);
 }
 
@@ -4925,12 +4752,6 @@
 	INT		 MsgType;
 	MLME_QUEUE	*Queue = (MLME_QUEUE *)&pAd->Mlme.Queue;
 
-#ifdef RALINK_ATE
-	/* Nothing to do in ATE mode */
-	if(ATE_ON(pAd))
-		return FALSE;
-#endif // RALINK_ATE //
-
 	// Do nothing if the driver is starting halt state.
 	// This might happen when timer already been fired before cancel timer with mlmehalt
 	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
@@ -4951,8 +4772,6 @@
 		return FALSE;
 	}
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		if (!MsgTypeSubst(pAd, pFrame, &Machine, &MsgType))
 		{
@@ -4960,7 +4779,6 @@
 			return FALSE;
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	// OK, we got all the informations, it is time to put things into queue
 	NdisAcquireSpinLock(&(Queue->Lock));
@@ -5028,13 +4846,14 @@
 VOID	MlmeRestartStateMachine(
 	IN	PRTMP_ADAPTER	pAd)
 {
+#ifdef RT2860
 	MLME_QUEUE_ELEM		*Elem = NULL;
-#ifdef CONFIG_STA_SUPPORT
+#endif
 	BOOLEAN				Cancelled;
-#endif // CONFIG_STA_SUPPORT //
 
 	DBGPRINT(RT_DEBUG_TRACE, ("MlmeRestartStateMachine \n"));
 
+#ifdef RT2860
 	NdisAcquireSpinLock(&pAd->Mlme.TaskLock);
 	if(pAd->Mlme.bRunning)
 	{
@@ -5062,13 +4881,9 @@
 			DBGPRINT_ERR(("MlmeRestartStateMachine: MlmeQueue empty\n"));
 		}
 	}
+#endif /* RT2860 */
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
-#ifdef QOS_DLS_SUPPORT
-		UCHAR i;
-#endif // QOS_DLS_SUPPORT //
 		// Cancel all timer events
 		// Be careful to cancel new added timer
 		RTMPCancelTimer(&pAd->MlmeAux.AssocTimer,	  &Cancelled);
@@ -5077,15 +4892,7 @@
 		RTMPCancelTimer(&pAd->MlmeAux.AuthTimer,	   &Cancelled);
 		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer,	   &Cancelled);
 		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer,	   &Cancelled);
-
-#ifdef QOS_DLS_SUPPORT
-		for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &Cancelled);
-		}
-#endif // QOS_DLS_SUPPORT //
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	// Change back to original channel in case of doing scan
 	AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
@@ -5094,8 +4901,6 @@
 	// Resume MSDU which is turned off durning scan
 	RTMPResumeMsduTransmission(pAd);
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		// Set all state machines back IDLE
 		pAd->Mlme.CntlMachine.CurrState    = CNTL_IDLE;
@@ -5104,16 +4909,14 @@
 		pAd->Mlme.AuthRspMachine.CurrState = AUTH_RSP_IDLE;
 		pAd->Mlme.SyncMachine.CurrState    = SYNC_IDLE;
 		pAd->Mlme.ActMachine.CurrState    = ACT_IDLE;
-#ifdef QOS_DLS_SUPPORT
-		pAd->Mlme.DlsMachine.CurrState    = DLS_IDLE;
-#endif // QOS_DLS_SUPPORT //
 	}
-#endif // CONFIG_STA_SUPPORT //
 
+#ifdef RT2860
 	// Remove running state
 	NdisAcquireSpinLock(&pAd->Mlme.TaskLock);
 	pAd->Mlme.bRunning = FALSE;
 	NdisReleaseSpinLock(&pAd->Mlme.TaskLock);
+#endif
 }
 
 /*! \brief	test if the MLME Queue is empty
@@ -5191,7 +4994,6 @@
  IRQL = DISPATCH_LEVEL
 
  */
-#ifdef CONFIG_STA_SUPPORT
 BOOLEAN MsgTypeSubst(
 	IN PRTMP_ADAPTER  pAd,
 	IN PFRAME_802_11 pFrame,
@@ -5215,16 +5017,6 @@
 			*MsgType = MT2_AIRONET_MSG;
 			return (TRUE);
 		}
-#ifdef LEAP_SUPPORT
-		if ( pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP ) //LEAP
-		{
-			// LEAP frames
-			*Machine = LEAP_STATE_MACHINE;
-			EAPType = *((UCHAR*)pFrame + LENGTH_802_11 + LENGTH_802_1_H + 1);
-			return (LeapMsgTypeSubst(EAPType, MsgType));
-		}
-		else
-#endif // LEAP_SUPPORT //
 		{
 			*Machine = WPA_PSK_STATE_MACHINE;
 			EAPType = *((UCHAR*)pFrame + LENGTH_802_11 + LENGTH_802_1_H + 1);
@@ -5311,7 +5103,6 @@
 
 	return TRUE;
 }
-#endif // CONFIG_STA_SUPPORT //
 
 // ===========================================================================================
 // state_machine.c
@@ -5533,7 +5324,6 @@
 					}
 				}
 				break;
-#ifdef DOT11_N_SUPPORT
 			case 2:		//HT-MIX
 			case 3:		//HT-GF
 				{
@@ -5595,7 +5385,6 @@
 					}
 				}
 				break;
-#endif // DOT11_N_SUPPORT //
 		}
 
 		pNextTxRate = pCurrTxRate;
@@ -5637,12 +5426,6 @@
 	UCHAR			i;
 	UINT32 MacReg = 0;
 
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-#ifdef DOT11_N_SUPPORT
 	if (!(pAd->CommonCfg.bHTProtect) && (OperationMode != 8))
 	{
 		return;
@@ -5656,19 +5439,14 @@
 		SetMask = ALLN_SETPROTECT;
 		OperationMode = 8;
 	}
-#endif // DOT11_N_SUPPORT //
 
 	// Config ASIC RTS threshold register
 	RTMP_IO_READ32(pAd, TX_RTS_CFG, &MacReg);
 	MacReg &= 0xFF0000FF;
-#if 0
-	MacReg |= (pAd->CommonCfg.RtsThreshold << 8);
-#else
+
 	// If the user want disable RtsThreshold and enable Amsdu/Ralink-Aggregation, set the RtsThreshold as 4096
         if ((
-#ifdef DOT11_N_SUPPORT
 			(pAd->CommonCfg.BACapability.field.AmsduEnable) ||
-#endif // DOT11_N_SUPPORT //
 			(pAd->CommonCfg.bAggregationCapable == TRUE))
             && pAd->CommonCfg.RtsThreshold == MAX_RTS_THRESHOLD)
         {
@@ -5678,7 +5456,6 @@
         {
 			MacReg |= (pAd->CommonCfg.RtsThreshold << 8);
         }
-#endif
 
 	RTMP_IO_WRITE32(pAd, TX_RTS_CFG, MacReg);
 
@@ -5717,7 +5494,6 @@
 		Protect[1] = ProtCfg.word;
 	}
 
-#ifdef DOT11_N_SUPPORT
 	// Decide HT frame protection.
 	if ((SetMask & ALLN_SETPROTECT) != 0)
 	{
@@ -5848,7 +5624,6 @@
 				break;
 		}
 	}
-#endif // DOT11_N_SUPPORT //
 
 	offset = CCK_PROT_CFG;
 	for (i = 0;i < 6;i++)
@@ -5860,6 +5635,276 @@
 	}
 }
 
+#ifdef RT30xx
+/*
+	========================================================================
+
+	Routine Description: Write RT30xx RF register through MAC
+
+	Arguments:
+
+	Return Value:
+
+	IRQL =
+
+	Note:
+
+	========================================================================
+*/
+NTSTATUS RT30xxWriteRFRegister(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			RegID,
+	IN	UCHAR			Value)
+{
+	RF_CSR_CFG_STRUC	rfcsr;
+	UINT				i = 0;
+
+	do
+	{
+		RTMP_IO_READ32(pAd, RF_CSR_CFG, &rfcsr.word);
+
+		if (!rfcsr.field.RF_CSR_KICK)
+			break;
+		i++;
+	}
+	while ((i < RETRY_LIMIT) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));
+
+	if ((i == RETRY_LIMIT) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
+	{
+		DBGPRINT_RAW(RT_DEBUG_ERROR, ("Retry count exhausted or device removed!!!\n"));
+		return STATUS_UNSUCCESSFUL;
+	}
+
+	rfcsr.field.RF_CSR_WR = 1;
+	rfcsr.field.RF_CSR_KICK = 1;
+	rfcsr.field.TESTCSR_RFACC_REGNUM = RegID;
+	rfcsr.field.RF_CSR_DATA = Value;
+
+	RTMP_IO_WRITE32(pAd, RF_CSR_CFG, rfcsr.word);
+
+	return STATUS_SUCCESS;
+}
+
+
+/*
+	========================================================================
+
+	Routine Description: Read RT30xx RF register through MAC
+
+	Arguments:
+
+	Return Value:
+
+	IRQL =
+
+	Note:
+
+	========================================================================
+*/
+NTSTATUS RT30xxReadRFRegister(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			RegID,
+	IN	PUCHAR			pValue)
+{
+	RF_CSR_CFG_STRUC	rfcsr;
+	UINT				i=0, k=0;
+
+	for (i=0; i<MAX_BUSY_COUNT; i++)
+	{
+		RTMP_IO_READ32(pAd, RF_CSR_CFG, &rfcsr.word);
+
+		if (rfcsr.field.RF_CSR_KICK == BUSY)
+		{
+			continue;
+		}
+		rfcsr.word = 0;
+		rfcsr.field.RF_CSR_WR = 0;
+		rfcsr.field.RF_CSR_KICK = 1;
+		rfcsr.field.TESTCSR_RFACC_REGNUM = RegID;
+		RTMP_IO_WRITE32(pAd, RF_CSR_CFG, rfcsr.word);
+		for (k=0; k<MAX_BUSY_COUNT; k++)
+		{
+			RTMP_IO_READ32(pAd, RF_CSR_CFG, &rfcsr.word);
+
+			if (rfcsr.field.RF_CSR_KICK == IDLE)
+				break;
+		}
+		if ((rfcsr.field.RF_CSR_KICK == IDLE) &&
+			(rfcsr.field.TESTCSR_RFACC_REGNUM == RegID))
+		{
+			*pValue = (UCHAR)rfcsr.field.RF_CSR_DATA;
+			break;
+		}
+	}
+	if (rfcsr.field.RF_CSR_KICK == BUSY)
+	{
+		DBGPRINT_ERR(("RF read R%d=0x%x fail, i[%d], k[%d]\n", RegID, rfcsr.word,i,k));
+		return STATUS_UNSUCCESSFUL;
+	}
+
+	return STATUS_SUCCESS;
+}
+#endif // RT30xx //
+
+#ifdef RT30xx
+// add by johnli, RF power sequence setup
+/*
+	==========================================================================
+	Description:
+
+	Load RF normal operation-mode setup
+
+	==========================================================================
+ */
+VOID RT30xxLoadRFNormalModeSetup(
+	IN PRTMP_ADAPTER 	pAd)
+{
+	UCHAR RFValue;
+
+	// RX0_PD & TX0_PD, RF R1 register Bit 2 & Bit 3 to 0 and RF_BLOCK_en,RX1_PD & TX1_PD, Bit0, Bit 4 & Bit5 to 1
+	RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
+	RFValue = (RFValue & (~0x0C)) | 0x31;
+	RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
+
+	// TX_LO2_en, RF R15 register Bit 3 to 0
+	RT30xxReadRFRegister(pAd, RF_R15, &RFValue);
+	RFValue &= (~0x08);
+	RT30xxWriteRFRegister(pAd, RF_R15, RFValue);
+
+	// TX_LO1_en, RF R17 register Bit 3 to 0
+	RT30xxReadRFRegister(pAd, RF_R17, &RFValue);
+	RFValue &= (~0x08);
+	// to fix rx long range issue
+	if (((pAd->MACVersion & 0xffff) >= 0x0211) && (pAd->NicConfig2.field.ExternalLNAForG == 0))
+	{
+		RFValue |= 0x20;
+	}
+	RT30xxWriteRFRegister(pAd, RF_R17, RFValue);
+
+	// RX_LO1_en, RF R20 register Bit 3 to 0
+	RT30xxReadRFRegister(pAd, RF_R20, &RFValue);
+	RFValue &= (~0x08);
+	RT30xxWriteRFRegister(pAd, RF_R20, RFValue);
+
+	// RX_LO2_en, RF R21 register Bit 3 to 0
+	RT30xxReadRFRegister(pAd, RF_R21, &RFValue);
+	RFValue &= (~0x08);
+	RT30xxWriteRFRegister(pAd, RF_R21, RFValue);
+
+	// LDORF_VC, RF R27 register Bit 2 to 0
+	RT30xxReadRFRegister(pAd, RF_R27, &RFValue);
+	if ((pAd->MACVersion & 0xffff) < 0x0211)
+		RFValue = (RFValue & (~0x77)) | 0x3;
+	else
+		RFValue = (RFValue & (~0x77));
+	RT30xxWriteRFRegister(pAd, RF_R27, RFValue);
+	/* end johnli */
+}
+
+/*
+	==========================================================================
+	Description:
+
+	Load RF sleep-mode setup
+
+	==========================================================================
+ */
+VOID RT30xxLoadRFSleepModeSetup(
+	IN PRTMP_ADAPTER 	pAd)
+{
+	UCHAR RFValue;
+	UINT32 MACValue;
+
+	// RF_BLOCK_en. RF R1 register Bit 0 to 0
+	RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
+	RFValue &= (~0x01);
+	RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
+
+	// VCO_IC, RF R7 register Bit 4 & Bit 5 to 0
+	RT30xxReadRFRegister(pAd, RF_R07, &RFValue);
+	RFValue &= (~0x30);
+	RT30xxWriteRFRegister(pAd, RF_R07, RFValue);
+
+	// Idoh, RF R9 register Bit 1, Bit 2 & Bit 3 to 0
+	RT30xxReadRFRegister(pAd, RF_R09, &RFValue);
+	RFValue &= (~0x0E);
+	RT30xxWriteRFRegister(pAd, RF_R09, RFValue);
+
+	// RX_CTB_en, RF R21 register Bit 7 to 0
+	RT30xxReadRFRegister(pAd, RF_R21, &RFValue);
+	RFValue &= (~0x80);
+	RT30xxWriteRFRegister(pAd, RF_R21, RFValue);
+
+	// LDORF_VC, RF R27 register Bit 0, Bit 1 & Bit 2 to 1
+	RT30xxReadRFRegister(pAd, RF_R27, &RFValue);
+	RFValue |= 0x77;
+	RT30xxWriteRFRegister(pAd, RF_R27, RFValue);
+
+	RTMP_IO_READ32(pAd, LDO_CFG0, &MACValue);
+	MACValue |= 0x1D000000;
+	RTMP_IO_WRITE32(pAd, LDO_CFG0, MACValue);
+}
+
+/*
+	==========================================================================
+	Description:
+
+	Reverse RF sleep-mode setup
+
+	==========================================================================
+ */
+VOID RT30xxReverseRFSleepModeSetup(
+	IN PRTMP_ADAPTER 	pAd)
+{
+	UCHAR RFValue;
+	UINT32 MACValue;
+
+	// RF_BLOCK_en, RF R1 register Bit 0 to 1
+	RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
+	RFValue |= 0x01;
+	RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
+
+	// VCO_IC, RF R7 register Bit 4 & Bit 5 to 1
+	RT30xxReadRFRegister(pAd, RF_R07, &RFValue);
+	RFValue |= 0x30;
+	RT30xxWriteRFRegister(pAd, RF_R07, RFValue);
+
+	// Idoh, RF R9 register Bit 1, Bit 2 & Bit 3 to 1
+	RT30xxReadRFRegister(pAd, RF_R09, &RFValue);
+	RFValue |= 0x0E;
+	RT30xxWriteRFRegister(pAd, RF_R09, RFValue);
+
+	// RX_CTB_en, RF R21 register Bit 7 to 1
+	RT30xxReadRFRegister(pAd, RF_R21, &RFValue);
+	RFValue |= 0x80;
+	RT30xxWriteRFRegister(pAd, RF_R21, RFValue);
+
+	// LDORF_VC, RF R27 register Bit 2 to 0
+	RT30xxReadRFRegister(pAd, RF_R27, &RFValue);
+	if ((pAd->MACVersion & 0xffff) < 0x0211)
+		RFValue = (RFValue & (~0x77)) | 0x3;
+	else
+		RFValue = (RFValue & (~0x77));
+	RT30xxWriteRFRegister(pAd, RF_R27, RFValue);
+
+	// RT3071 version E has fixed this issue
+	if ((pAd->NicConfig2.field.DACTestBit == 1) && ((pAd->MACVersion & 0xffff) < 0x0211))
+	{
+		// patch tx EVM issue temporarily
+		RTMP_IO_READ32(pAd, LDO_CFG0, &MACValue);
+		MACValue = ((MACValue & 0xE0FFFFFF) | 0x0D000000);
+		RTMP_IO_WRITE32(pAd, LDO_CFG0, MACValue);
+	}
+	else
+	{
+		RTMP_IO_READ32(pAd, LDO_CFG0, &MACValue);
+		MACValue = ((MACValue & 0xE0FFFFFF) | 0x01000000);
+		RTMP_IO_WRITE32(pAd, LDO_CFG0, MACValue);
+	}
+}
+// end johnli
+#endif // RT30xx //
+
 /*
 	==========================================================================
 	Description:
@@ -5881,6 +5926,21 @@
 	RTMP_RF_REGS *RFRegTable;
 
 	// Search Tx power value
+#ifdef RT30xx
+	// We can't use ChannelList to search channel, since some central channl's txpowr doesn't list
+	// in ChannelList, so use TxPower array instead.
+	//
+	for (index = 0; index < MAX_NUM_OF_CHANNELS; index++)
+	{
+		if (Channel == pAd->TxPower[index].Channel)
+	{
+			TxPwer = pAd->TxPower[index].Power;
+			TxPwer2 = pAd->TxPower[index].Power2;
+			break;
+		}
+	}
+#endif
+#ifndef RT30xx
 	for (index = 0; index < pAd->ChannelListNum; index++)
 	{
 		if (Channel == pAd->ChannelList[index].Channel)
@@ -5890,12 +5950,152 @@
 			break;
 		}
 	}
+#endif
 
 	if (index == MAX_NUM_OF_CHANNELS)
 	{
+#ifndef RT30xx
 		DBGPRINT(RT_DEBUG_ERROR, ("AsicSwitchChannel: Cant find the Channel#%d \n", Channel));
+#endif
+#ifdef RT30xx
+		DBGPRINT(RT_DEBUG_ERROR, ("AsicSwitchChannel: Can't find the Channel#%d \n", Channel));
+#endif
 	}
 
+#ifdef RT2870
+	// The RF programming sequence is difference between 3xxx and 2xxx
+#ifdef RT30xx
+	if ((IS_RT3070(pAd) || IS_RT3090(pAd)) && ((pAd->RfIcType == RFIC_3020) || (pAd->RfIcType == RFIC_2020) ||
+		(pAd->RfIcType == RFIC_3021) || (pAd->RfIcType == RFIC_3022)))
+#endif
+#ifndef RT30xx
+	if (IS_RT3070(pAd) && ((pAd->RfIcType == RFIC_3020) || (pAd->RfIcType == RFIC_2020)))
+#endif
+	{
+		/* modify by WY for Read RF Reg. error */
+		UCHAR RFValue;
+
+		for (index = 0; index < NUM_OF_3020_CHNL; index++)
+		{
+			if (Channel == FreqItems3020[index].Channel)
+			{
+				// Programming channel parameters
+				RT30xxWriteRFRegister(pAd, RF_R02, FreqItems3020[index].N);
+				RT30xxWriteRFRegister(pAd, RF_R03, FreqItems3020[index].K);
+
+#ifndef RT30xx
+				RT30xxReadRFRegister(pAd, RF_R06, (PUCHAR)&RFValue);
+				RFValue = (RFValue & 0xFC) | FreqItems3020[index].R;
+				RT30xxWriteRFRegister(pAd, RF_R06, (UCHAR)RFValue);
+
+				// Set Tx Power
+				RT30xxReadRFRegister(pAd, RF_R12, (PUCHAR)&RFValue);
+				RFValue = (RFValue & 0xE0) | TxPwer;
+				RT30xxWriteRFRegister(pAd, RF_R12, (UCHAR)RFValue);
+
+				// Set RF offset
+				RT30xxReadRFRegister(pAd, RF_R23, (PUCHAR)&RFValue);
+				RFValue = (RFValue & 0x80) | pAd->RfFreqOffset;
+				RT30xxWriteRFRegister(pAd, RF_R23, (UCHAR)RFValue);
+#endif
+#ifdef RT30xx
+				RT30xxReadRFRegister(pAd, RF_R06, &RFValue);
+				RFValue = (RFValue & 0xFC) | FreqItems3020[index].R;
+				RT30xxWriteRFRegister(pAd, RF_R06, RFValue);
+
+				// Set Tx0 Power
+				RT30xxReadRFRegister(pAd, RF_R12, &RFValue);
+				RFValue = (RFValue & 0xE0) | TxPwer;
+				RT30xxWriteRFRegister(pAd, RF_R12, RFValue);
+
+				// Set Tx1 Power
+				RT30xxReadRFRegister(pAd, RF_R13, &RFValue);
+				RFValue = (RFValue & 0xE0) | TxPwer2;
+				RT30xxWriteRFRegister(pAd, RF_R13, RFValue);
+
+				// Tx/Rx Stream setting
+				RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
+				//if (IS_RT3090(pAd))
+				//	RFValue |= 0x01; // Enable RF block.
+				RFValue &= 0x03;	//clear bit[7~2]
+				if (pAd->Antenna.field.TxPath == 1)
+					RFValue |= 0xA0;
+				else if (pAd->Antenna.field.TxPath == 2)
+					RFValue |= 0x80;
+				if (pAd->Antenna.field.RxPath == 1)
+					RFValue |= 0x50;
+				else if (pAd->Antenna.field.RxPath == 2)
+					RFValue |= 0x40;
+				RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
+
+				// Set RF offset
+				RT30xxReadRFRegister(pAd, RF_R23, &RFValue);
+				RFValue = (RFValue & 0x80) | pAd->RfFreqOffset;
+				RT30xxWriteRFRegister(pAd, RF_R23, RFValue);
+#endif
+
+				// Set BW
+				if (!bScan && (pAd->CommonCfg.BBPCurrentBW == BW_40))
+				{
+					RFValue = pAd->Mlme.CaliBW40RfR24;
+					//DISABLE_11N_CHECK(pAd);
+				}
+				else
+				{
+					RFValue = pAd->Mlme.CaliBW20RfR24;
+				}
+#ifndef RT30xx
+				RT30xxWriteRFRegister(pAd, RF_R24, (UCHAR)RFValue);
+
+				// Enable RF tuning
+				RT30xxReadRFRegister(pAd, RF_R07, (PUCHAR)&RFValue);
+				RFValue = RFValue | 0x1;
+				RT30xxWriteRFRegister(pAd, RF_R07, (UCHAR)RFValue);
+
+				// latch channel for future usage.
+				pAd->LatchRfRegs.Channel = Channel;
+#endif
+#ifdef RT30xx
+				RT30xxWriteRFRegister(pAd, RF_R24, RFValue);
+				RT30xxWriteRFRegister(pAd, RF_R31, RFValue);
+
+				// Enable RF tuning
+				RT30xxReadRFRegister(pAd, RF_R07, &RFValue);
+				RFValue = RFValue | 0x1;
+				RT30xxWriteRFRegister(pAd, RF_R07, RFValue);
+
+				// latch channel for future usage.
+				pAd->LatchRfRegs.Channel = Channel;
+
+				DBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%d, Pwr1=%d, %dT), N=0x%02X, K=0x%02X, R=0x%02X\n",
+					Channel,
+					pAd->RfIcType,
+					TxPwer,
+					TxPwer2,
+					pAd->Antenna.field.TxPath,
+					FreqItems3020[index].N,
+					FreqItems3020[index].K,
+					FreqItems3020[index].R));
+#endif
+
+				break;
+			}
+		}
+
+#ifndef RT30xx
+		DBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%d, Pwr1=%d, %dT), N=0x%02X, K=0x%02X, R=0x%02X\n",
+			Channel,
+			pAd->RfIcType,
+			TxPwer,
+			TxPwer2,
+			pAd->Antenna.field.TxPath,
+			FreqItems3020[index].N,
+			FreqItems3020[index].K,
+			FreqItems3020[index].R));
+#endif
+	}
+	else
+#endif // RT2870 //
 	{
 		RFRegTable = RF2850RegTable;
 
@@ -6149,6 +6349,53 @@
 	IN	PRTMP_ADAPTER	pAd,
 	IN	UCHAR			Channel)
 {
+#ifdef RT30xx
+			if (pAd->Mlme.OneSecPeriodicRound % 2 == 1)
+			{
+				// patch for AsicSetRxAnt failed
+				pAd->RxAnt.EvaluatePeriod = 0;
+
+				// check every 2 second. If rcv-beacon less than 5 in the past 2 second, then AvgRSSI is no longer a
+				// valid indication of the distance between this AP and its clients.
+				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
+				{
+					SHORT	realavgrssi1;
+
+					// if no traffic then reset average rssi to trigger evaluation
+					if (pAd->StaCfg.NumOfAvgRssiSample < 5)
+					{
+						pAd->RxAnt.Pair1LastAvgRssi = (-99);
+						pAd->RxAnt.Pair2LastAvgRssi = (-99);
+						DBGPRINT(RT_DEBUG_TRACE, ("MlmePeriodicExec: no traffic/beacon, reset RSSI\n"));
+					}
+
+					pAd->StaCfg.NumOfAvgRssiSample = 0;
+					realavgrssi1 = (pAd->RxAnt.Pair1AvgRssi[pAd->RxAnt.Pair1PrimaryRxAnt] >> 3);
+
+					DBGPRINT(RT_DEBUG_TRACE,("Ant-realrssi0(%d), Lastrssi0(%d), EvaluateStableCnt=%d\n", realavgrssi1, pAd->RxAnt.Pair1LastAvgRssi, pAd->RxAnt.EvaluateStableCnt));
+
+					// if the difference between two rssi is larger or less than 5, then evaluate the other antenna
+					if ((pAd->RxAnt.EvaluateStableCnt < 2) || (realavgrssi1 > (pAd->RxAnt.Pair1LastAvgRssi + 5)) || (realavgrssi1 < (pAd->RxAnt.Pair1LastAvgRssi - 5)))
+					{
+						pAd->RxAnt.Pair1LastAvgRssi = realavgrssi1;
+						AsicEvaluateRxAnt(pAd);
+					}
+				}
+				else
+				{
+					// if not connected, always switch antenna to try to connect
+					UCHAR	temp;
+
+					temp = pAd->RxAnt.Pair1PrimaryRxAnt;
+					pAd->RxAnt.Pair1PrimaryRxAnt = pAd->RxAnt.Pair1SecondaryRxAnt;
+					pAd->RxAnt.Pair1SecondaryRxAnt = temp;
+
+					DBGPRINT(RT_DEBUG_TRACE, ("MlmePeriodicExec: no connect, switch to another one to try connection\n"));
+
+					AsicSetRxAnt(pAd, pAd->RxAnt.Pair1PrimaryRxAnt);
+				}
+			}
+#endif /* RT30xx */
 }
 
 /*
@@ -6218,11 +6465,13 @@
 	ULONG		TxPwr[5];
 	CHAR		Value;
 
+#ifdef RT2860
 	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE)
 		|| (pAd->bPCIclkOff == TRUE)
 		|| RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF)
 		|| RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
 		return;
+#endif
 
 	if (pAd->CommonCfg.BBPCurrentBW == BW_40)
 	{
@@ -6364,95 +6613,6 @@
 	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpR1);
 	BbpR1 &= 0xFC;
 
-#ifdef SINGLE_SKU
-	// Handle regulatory max tx power constrain
-	do
-	{
-		UCHAR    TxPwrInEEPROM = 0xFF, CountryTxPwr = 0xFF, criterion;
-		UCHAR    AdjustMaxTxPwr[40];
-
-		if (pAd->CommonCfg.Channel > 14) // 5G band
-			TxPwrInEEPROM = ((pAd->CommonCfg.DefineMaxTxPwr & 0xFF00) >> 8);
-		else // 2.4G band
-			TxPwrInEEPROM = (pAd->CommonCfg.DefineMaxTxPwr & 0x00FF);
-		CountryTxPwr = GetCuntryMaxTxPwr(pAd, pAd->CommonCfg.Channel);
-
-		// error handling, range check
-		if ((TxPwrInEEPROM > 0x50) || (CountryTxPwr > 0x50))
-		{
-			DBGPRINT(RT_DEBUG_ERROR,("AsicAdjustTxPower - Invalid max tx power (=0x%02x), CountryTxPwr=%d\n", TxPwrInEEPROM, CountryTxPwr));
-			break;
-		}
-
-		criterion = *((PUCHAR)TxPwr + 2) & 0xF;        // FAE use OFDM 6M as criterion
-
-		DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (criterion=%d, TxPwrInEEPROM=%d, CountryTxPwr=%d)\n", criterion, TxPwrInEEPROM, CountryTxPwr));
-
-		// Adjust max tx power according to the relationship of tx power in E2PROM
-		for (i=0; i<5; i++)
-		{
-			// CCK will have 4dBm larger than OFDM
-			// Therefore, we should separate to parse the tx power field
-			if (i == 0)
-			{
-				for (j=0; j<8; j++)
-				{
-					Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F);
-
-					if (j < 4)
-					{
-						// CCK will have 4dBm larger than OFDM
-						AdjustMaxTxPwr[i*8+j] = TxPwrInEEPROM + (Value - criterion) + 4;
-					}
-					else
-					{
-						AdjustMaxTxPwr[i*8+j] = TxPwrInEEPROM + (Value - criterion);
-					}
-					DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-				}
-			}
-			else
-			{
-				for (j=0; j<8; j++)
-				{
-					Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F);
-
-					AdjustMaxTxPwr[i*8+j] = TxPwrInEEPROM + (Value - criterion);
-					DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-				}
-			}
-		}
-
-		// Adjust tx power according to the relationship
-		for (i=0; i<5; i++)
-		{
-			if (TxPwr[i] != 0xffffffff)
-			{
-				for (j=0; j<8; j++)
-				{
-					Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F);
-
-					// The system tx power is larger than the regulatory, the power should be restrain
-					if (AdjustMaxTxPwr[i*8+j] > CountryTxPwr)
-					{
-						// decrease to zero and don't need to take care BBPR1
-						if ((Value - (AdjustMaxTxPwr[i*8+j] - CountryTxPwr)) > 0)
-							Value -= (AdjustMaxTxPwr[i*8+j] - CountryTxPwr);
-						else
-							Value = 0;
-
-						DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-					}
-					else
-						DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d, no change)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-
-						TxPwr[i] = (TxPwr[i] & ~(0x0000000F << j*4)) | (Value << j*4);
-				}
-			}
-		}
-	} while (FALSE);
-#endif // SINGLE_SKU //
-
 	/* calculate delta power based on the percentage specified from UI */
 	// E2PROM setting is calibrated for maximum TX power (i.e. 100%)
 	// We lower TX power here according to the percentage specified from UI
@@ -6522,7 +6682,6 @@
 
 }
 
-#ifdef CONFIG_STA_SUPPORT
 /*
 	==========================================================================
 	Description:
@@ -6568,12 +6727,22 @@
  */
 VOID AsicForceWakeup(
 	IN PRTMP_ADAPTER pAd,
+#ifdef RT2860
 	IN UCHAR    	 Level)
+#endif
+#ifdef RT2870
+	IN BOOLEAN    bFromTx)
+#endif
 {
     DBGPRINT(RT_DEBUG_TRACE, ("--> AsicForceWakeup \n"));
+#ifdef RT2860
     RT28XX_STA_FORCE_WAKEUP(pAd, Level);
+#endif
+#ifdef RT2870
+    RT28XX_STA_FORCE_WAKEUP(pAd, bFromTx);
+#endif
 }
-#endif // CONFIG_STA_SUPPORT //
+
 /*
 	==========================================================================
 	Description:
@@ -6688,9 +6857,7 @@
 
 	Data  &= 0xFFFFFF00;
 	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_DYNAMIC_BE_TXOP_ACTIVE)
-#ifdef DOT11_N_SUPPORT
 		&& (pAd->MacTab.fAnyStationMIMOPSDynamic == FALSE)
-#endif // DOT11_N_SUPPORT //
 	)
 	{
 		// For CWC test, change txop from 0x30 to 0x20 in TxBurst mode
@@ -6745,8 +6912,7 @@
 	DBGPRINT(RT_DEBUG_TRACE, ("--->AsicEnableBssSync(INFRA mode)\n"));
 
 	RTMP_IO_READ32(pAd, BCN_TIME_CFG, &csr.word);
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+
 	{
 		csr.field.BeaconInterval = pAd->CommonCfg.BeaconPeriod << 4; // ASIC register in units of 1/16 TU
 		csr.field.bTsfTicking = 1;
@@ -6754,7 +6920,7 @@
 		csr.field.bBeaconGen  = 0; // do NOT generate BEACON
 		csr.field.bTBTTEnable = 1;
 	}
-#endif // CONFIG_STA_SUPPORT //
+
 	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr.word);
 }
 
@@ -6785,6 +6951,7 @@
 	csr9.field.bTsfTicking = 0;
 	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr9.word);
 
+#ifdef RT2860
 	// move BEACON TXD and frame content to on-chip memory
 	ptr = (PUCHAR)&pAd->BeaconTxWI;
 	for (i=0; i<TXWI_SIZE; i+=4)  // 16-byte TXWI field
@@ -6802,6 +6969,24 @@
 		RTMP_IO_WRITE32(pAd, HW_BEACON_BASE0 + TXWI_SIZE + i, longptr);
 		ptr +=4;
 	}
+#endif
+#ifdef RT2870
+	// move BEACON TXD and frame content to on-chip memory
+	ptr = (PUCHAR)&pAd->BeaconTxWI;
+	for (i=0; i<TXWI_SIZE; i+=2)  // 16-byte TXWI field
+	{
+		RTUSBMultiWrite(pAd, HW_BEACON_BASE0 + i, ptr, 2);
+		ptr += 2;
+	}
+
+	// start right after the 16-byte TXWI field
+	ptr = pAd->BeaconBuf;
+	for (i=0; i< pAd->BeaconTxWI.MPDUtotalByteCount; i+=2)
+	{
+		RTUSBMultiWrite(pAd, HW_BEACON_BASE0 + TXWI_SIZE + i, ptr, 2);
+		ptr +=2;
+	}
+#endif // RT2870 //
 
 	// start sending BEACON
 	csr9.field.BeaconInterval = pAd->CommonCfg.BeaconPeriod << 4; // ASIC register in units of 1/16 TU
@@ -6949,8 +7134,7 @@
 		Ac2Cfg.field.Cwmin = pEdcaParm->Cwmin[QID_AC_VI];
 		Ac2Cfg.field.Cwmax = pEdcaParm->Cwmax[QID_AC_VI];
 		Ac2Cfg.field.Aifsn = pEdcaParm->Aifsn[QID_AC_VI];
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+
 		{
 			// Tuning for Wi-Fi WMM S06
 			if (pAd->CommonCfg.bWiFiTest &&
@@ -6958,15 +7142,22 @@
 				Ac2Cfg.field.Aifsn -= 1;
 
 			// Tuning for TGn Wi-Fi 5.2.32
-			// STA TestBed changes in this item: conexant legacy sta ==> broadcom 11n sta
+			// STA TestBed changes in this item: connexant legacy sta ==> broadcom 11n sta
 			if (STA_TGN_WIFI_ON(pAd) &&
 				pEdcaParm->Aifsn[QID_AC_VI] == 10)
 			{
 				Ac0Cfg.field.Aifsn = 3;
 				Ac2Cfg.field.AcTxop = 5;
 			}
+
+#ifdef RT30xx
+			if (pAd->RfIcType == RFIC_3020 || pAd->RfIcType == RFIC_2020)
+			{
+				// Tuning for WiFi WMM S3-T07: connexant legacy sta ==> broadcom 11n sta.
+				Ac2Cfg.field.Aifsn = 5;
+			}
+#endif // RT30xx //
 		}
-#endif // CONFIG_STA_SUPPORT //
 
 		Ac3Cfg.field.AcTxop = pEdcaParm->Txop[QID_AC_VO];
 		Ac3Cfg.field.Cwmin = pEdcaParm->Cwmin[QID_AC_VO];
@@ -7008,10 +7199,9 @@
 		CwminCsr.field.Cwmin0 = pEdcaParm->Cwmin[QID_AC_BE];
 		CwminCsr.field.Cwmin1 = pEdcaParm->Cwmin[QID_AC_BK];
 		CwminCsr.field.Cwmin2 = pEdcaParm->Cwmin[QID_AC_VI];
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			CwminCsr.field.Cwmin3 = pEdcaParm->Cwmin[QID_AC_VO] - 1; //for TGn wifi test
-#endif // CONFIG_STA_SUPPORT //
+
+		CwminCsr.field.Cwmin3 = pEdcaParm->Cwmin[QID_AC_VO] - 1; //for TGn wifi test
+
 		RTMP_IO_WRITE32(pAd, WMM_CWMIN_CFG, CwminCsr.word);
 
 		CwmaxCsr.word = 0;
@@ -7025,8 +7215,7 @@
 		AifsnCsr.field.Aifsn0 = Ac0Cfg.field.Aifsn; //pEdcaParm->Aifsn[QID_AC_BE];
 		AifsnCsr.field.Aifsn1 = Ac1Cfg.field.Aifsn; //pEdcaParm->Aifsn[QID_AC_BK];
 		AifsnCsr.field.Aifsn2 = Ac2Cfg.field.Aifsn; //pEdcaParm->Aifsn[QID_AC_VI];
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+
 		{
 			// Tuning for Wi-Fi WMM S06
 			if (pAd->CommonCfg.bWiFiTest &&
@@ -7034,20 +7223,25 @@
 				AifsnCsr.field.Aifsn2 = Ac2Cfg.field.Aifsn - 4;
 
 			// Tuning for TGn Wi-Fi 5.2.32
-			// STA TestBed changes in this item: conexant legacy sta ==> broadcom 11n sta
+			// STA TestBed changes in this item: connexant legacy sta ==> broadcom 11n sta
 			if (STA_TGN_WIFI_ON(pAd) &&
 				pEdcaParm->Aifsn[QID_AC_VI] == 10)
 			{
 				AifsnCsr.field.Aifsn0 = 3;
 				AifsnCsr.field.Aifsn2 = 7;
 			}
+#ifdef RT2870
+			if (INFRA_ON(pAd))
+				CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_WMM_CAPABLE);
+#endif
 		}
-#endif // CONFIG_STA_SUPPORT //
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			AifsnCsr.field.Aifsn3 = Ac3Cfg.field.Aifsn - 1; //pEdcaParm->Aifsn[QID_AC_VO]; //for TGn wifi test
-#endif // CONFIG_STA_SUPPORT //
+		AifsnCsr.field.Aifsn3 = Ac3Cfg.field.Aifsn - 1; //pEdcaParm->Aifsn[QID_AC_VO]; //for TGn wifi test
+#ifdef RT30xx
+		if (pAd->RfIcType == RFIC_3020 || pAd->RfIcType == RFIC_2020)
+			AifsnCsr.field.Aifsn2 = 0x2; //pEdcaParm->Aifsn[QID_AC_VI]; //for WiFi WMM S4-T04.
+#endif // RT30xx //
+
 		RTMP_IO_WRITE32(pAd, WMM_AIFSN_CFG, AifsnCsr.word);
 
 		NdisMoveMemory(&pAd->CommonCfg.APEdcaParm, pEdcaParm, sizeof(EDCA_PARM));
@@ -7098,10 +7292,8 @@
 	ULONG	SlotTime;
 	UINT32	RegValue = 0;
 
-#ifdef CONFIG_STA_SUPPORT
 	if (pAd->CommonCfg.Channel > 14)
 		bUseShortSlotTime = TRUE;
-#endif // CONFIG_STA_SUPPORT //
 
 	if (bUseShortSlotTime)
 		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_SHORT_SLOT_INUSED);
@@ -7110,36 +7302,31 @@
 
 	SlotTime = (bUseShortSlotTime)? 9 : 20;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
+#ifndef RT30xx
 		// force using short SLOT time for FAE to demo performance when TxBurst is ON
 		if (((pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE) && (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED)))
-#ifdef DOT11_N_SUPPORT
 			|| ((pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE) && (pAd->CommonCfg.BACapability.field.Policy == BA_NOTUSE))
-#endif // DOT11_N_SUPPORT //
 			)
 		{
 			// In this case, we will think it is doing Wi-Fi test
 			// And we will not set to short slot when bEnableTxBurst is TRUE.
 		}
 		else if (pAd->CommonCfg.bEnableTxBurst)
+#endif
+#ifdef RT30xx
+		if (pAd->CommonCfg.bEnableTxBurst)
+#endif
 			SlotTime = 9;
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	//
 	// For some reasons, always set it to short slot time.
 	//
 	// ToDo: Should consider capability with 11B
 	//
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pAd->StaCfg.BssType == BSS_ADHOC)
-			SlotTime = 20;
-	}
-#endif // CONFIG_STA_SUPPORT //
+	if (pAd->StaCfg.BssType == BSS_ADHOC)
+		SlotTime = 20;
 
 	RTMP_IO_READ32(pAd, BKOFF_SLOT_CFG, &RegValue);
 	RegValue = RegValue & 0xFFFFFF00;
@@ -7170,7 +7357,9 @@
 {
 	ULONG offset; //, csr0;
 	SHAREDKEY_MODE_STRUC csr1;
+#ifdef RT2860
 	INT   i;
+#endif
 
 	DBGPRINT(RT_DEBUG_TRACE, ("AsicAddSharedKeyEntry BssIndex=%d, KeyIdx=%d\n", BssIndex,KeyIdx));
 //============================================================================================
@@ -7192,28 +7381,43 @@
 	//
 	// fill key material - key + TX MIC + RX MIC
 	//
+
 	offset = SHARED_KEY_TABLE_BASE + (4*BssIndex + KeyIdx)*HW_KEY_ENTRY_SIZE;
+#ifdef RT2860
 	for (i=0; i<MAX_LEN_OF_SHARE_KEY; i++)
 	{
 		RTMP_IO_WRITE8(pAd, offset + i, pKey[i]);
 	}
-
+#endif
+#ifdef RT2870
+	RTUSBMultiWrite(pAd, offset, pKey, MAX_LEN_OF_SHARE_KEY);
+#endif
 	offset += MAX_LEN_OF_SHARE_KEY;
 	if (pTxMic)
 	{
+#ifdef RT2860
 		for (i=0; i<8; i++)
 		{
 			RTMP_IO_WRITE8(pAd, offset + i, pTxMic[i]);
 		}
+#endif
+#ifdef RT2870
+		RTUSBMultiWrite(pAd, offset, pTxMic, 8);
+#endif
 	}
 
 	offset += 8;
 	if (pRxMic)
 	{
+#ifdef RT2860
 		for (i=0; i<8; i++)
 		{
 			RTMP_IO_WRITE8(pAd, offset + i, pRxMic[i]);
 		}
+#endif
+#ifdef RT2870
+		RTUSBMultiWrite(pAd, offset, pRxMic, 8);
+#endif
 	}
 
 
@@ -7389,7 +7593,9 @@
 	PUCHAR		pTxtsc = pCipherKey->TxTsc;
 	UCHAR		CipherAlg = pCipherKey->CipherAlg;
 	SHAREDKEY_MODE_STRUC csr1;
+#ifdef RT2860
 	UCHAR		i;
+#endif
 
 	DBGPRINT(RT_DEBUG_TRACE, ("==> AsicAddKeyEntry\n"));
 	//
@@ -7404,10 +7610,15 @@
 	// 2.) Set Key to Asic
 	//
 	//for (i = 0; i < KeyLen; i++)
+#ifdef RT2860
 	for (i = 0; i < MAX_LEN_OF_PEER_KEY; i++)
 	{
 		RTMP_IO_WRITE8(pAd, offset + i, pKey[i]);
 	}
+#endif
+#ifdef RT2870
+	RTUSBMultiWrite(pAd, offset, pKey, MAX_LEN_OF_PEER_KEY);
+#endif
 	offset += MAX_LEN_OF_PEER_KEY;
 
 	//
@@ -7415,19 +7626,29 @@
 	//
 	if (pTxMic)
 	{
+#ifdef RT2860
 		for (i = 0; i < 8; i++)
 		{
 			RTMP_IO_WRITE8(pAd, offset + i, pTxMic[i]);
 		}
+#endif
+#ifdef RT2870
+		RTUSBMultiWrite(pAd, offset, pTxMic, 8);
+#endif
 	}
 	offset += LEN_TKIP_TXMICK;
 
 	if (pRxMic)
 	{
+#ifdef RT2860
 		for (i = 0; i < 8; i++)
 		{
 			RTMP_IO_WRITE8(pAd, offset + i, pRxMic[i]);
 		}
+#endif
+#ifdef RT2870
+		RTUSBMultiWrite(pAd, offset, pRxMic, 8);
+#endif
 	}
 
 
@@ -7437,6 +7658,7 @@
 	//
 	if (bTxKey)
 	{
+#ifdef RT2860
 		offset = MAC_IVEIV_TABLE_BASE + (WCID * HW_IVEIV_ENTRY_SIZE);
 		//
 		// Write IV
@@ -7460,6 +7682,26 @@
 			RTMP_IO_WRITE8(pAd, offset + i, pTxtsc[i + 2]);
 		}
 
+#endif
+#ifdef RT2870
+		UINT32 tmpVal;
+
+		//
+		// Write IV
+		//
+		IV4 = (KeyIdx << 6);
+		if ((CipherAlg == CIPHER_TKIP) || (CipherAlg == CIPHER_TKIP_NO_MIC) ||(CipherAlg == CIPHER_AES))
+			IV4 |= 0x20;  // turn on extension bit means EIV existence
+
+		tmpVal = pTxtsc[1] + (((pTxtsc[1] | 0x20) & 0x7f) << 8) + (pTxtsc[0] << 16) + (IV4 << 24);
+		RTMP_IO_WRITE32(pAd, offset, tmpVal);
+
+		//
+		// Write EIV
+		//
+		offset += 4;
+		RTMP_IO_WRITE32(pAd, offset, *(PUINT32)&pCipherKey->TxTsc[2]);
+#endif // RT2870 //
 		AsicUpdateWCIDAttribute(pAd, WCID, BssIndex, CipherAlg, bUsePairewiseKeyTable);
 	}
 
@@ -7524,10 +7766,15 @@
 
 	// EKEY
 	offset = PAIRWISE_KEY_TABLE_BASE + (WCID * HW_KEY_ENTRY_SIZE);
+#ifdef RT2860
 	for (i=0; i<MAX_LEN_OF_PEER_KEY; i++)
 	{
 		RTMP_IO_WRITE8(pAd, offset + i, pKey[i]);
 	}
+#endif
+#ifdef RT2870
+	RTUSBMultiWrite(pAd, offset, &pCipherKey->Key[0], MAX_LEN_OF_PEER_KEY);
+#endif // RT2870 //
 	for (i=0; i<MAX_LEN_OF_PEER_KEY; i+=4)
 	{
 		UINT32 Value;
@@ -7539,18 +7786,28 @@
 	//  MIC KEY
 	if (pTxMic)
 	{
+#ifdef RT2860
 		for (i=0; i<8; i++)
 		{
 			RTMP_IO_WRITE8(pAd, offset+i, pTxMic[i]);
 		}
+#endif
+#ifdef RT2870
+		RTUSBMultiWrite(pAd, offset, &pCipherKey->TxMic[0], 8);
+#endif // RT2870 //
 	}
 	offset += 8;
 	if (pRxMic)
 	{
+#ifdef RT2860
 		for (i=0; i<8; i++)
 		{
 			RTMP_IO_WRITE8(pAd, offset+i, pRxMic[i]);
 		}
+#endif
+#ifdef RT2870
+		RTUSBMultiWrite(pAd, offset, &pCipherKey->RxMic[0], 8);
+#endif // RT2870 //
 	}
 
 	DBGPRINT(RT_DEBUG_TRACE,("AsicAddPairwiseKeyEntry: WCID #%d Alg=%s\n",WCID, CipherName[CipherAlg]));
@@ -7599,9 +7856,7 @@
 	HOST_CMD_CSR_STRUC	H2MCmd;
 	H2M_MAILBOX_STRUC	H2MMailbox;
 	ULONG				i = 0;
-#ifdef RALINK_ATE
-	static UINT32 j = 0;
-#endif // RALINK_ATE //
+
 	do
 	{
 		RTMP_IO_READ32(pAd, H2M_MAILBOX_CSR, &H2MMailbox.word);
@@ -7611,33 +7866,10 @@
 		RTMPusecDelay(2);
 	} while(i++ < 100);
 
-	if (i >= 100)
+	if (i > 100)
 	{
-#ifdef RALINK_ATE
-		if (pAd->ate.bFWLoading == TRUE)
 		{
-			/* reloading firmware when received iwpriv cmd "ATE=ATESTOP" */
-			if (j > 0)
-			{
-				if (j % 64 != 0)
-				{
-					DBGPRINT(RT_DEBUG_ERROR, ("#"));
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_ERROR, ("\n"));
-				}
-				++j;
-			}
-			else if (j == 0)
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("Loading firmware. Please wait for a moment...\n"));
-				++j;
-			}
-		}
-		else
-#endif // RALINK_ATE //
-		{
+#ifdef RT2860
 			UINT32 Data;
 
 			// Reset DMA
@@ -7659,21 +7891,15 @@
 			RTMP_IO_READ32(pAd, PBF_SYS_CTRL, &Data);
 			Data &= 0xfffffffd;
 			RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, Data);
+#endif /* RT2860 */
 		DBGPRINT_ERR(("H2M_MAILBOX still hold by MCU. command fail\n"));
 		}
 		//return FALSE;
+#ifdef RT2870
+		return FALSE;
+#endif
 	}
 
-#ifdef RALINK_ATE
-	else if (pAd->ate.bFWLoading == TRUE)
-	{
-		/* reloading of firmware is completed */
-		pAd->ate.bFWLoading = FALSE;
-		DBGPRINT(RT_DEBUG_ERROR, ("\n"));
-		j = 0;
-	}
-#endif // RALINK_ATE //
-
 	H2MMailbox.field.Owner	  = 1;	   // pass ownership to MCU
 	H2MMailbox.field.CmdToken = Token;
 	H2MMailbox.field.HighByte = Arg1;
@@ -7691,6 +7917,7 @@
 	return TRUE;
 }
 
+#ifdef RT2860
 BOOLEAN AsicCheckCommanOk(
 	IN PRTMP_ADAPTER pAd,
 	IN UCHAR		 Command)
@@ -7755,6 +7982,7 @@
 
 	return FALSE;
 }
+#endif /* RT8260 */
 
 /*
 	========================================================================
@@ -7797,8 +8025,6 @@
 	NdisMoveMemory(SupRate, NewRate, NewRateLen);
 }
 
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
 BOOLEAN RTMPCheckChannel(
 	IN PRTMP_ADAPTER pAd,
 	IN UCHAR		CentralChannel,
@@ -7944,8 +8170,6 @@
 	COPY_AP_HTSETTINGS_FROM_BEACON(pAd, pHtCapability);
 	return TRUE;
 }
-#endif // DOT11_N_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
 
 /*
 	========================================================================
@@ -7978,10 +8202,8 @@
 			MinimumRate = RATE_1;
 			break;
 		case PHY_11BG_MIXED:
-#ifdef DOT11_N_SUPPORT
 		case PHY_11ABGN_MIXED:
 		case PHY_11BGN_MIXED:
-#endif // DOT11_N_SUPPORT //
 			if ((pAd->MlmeAux.SupRateLen == 4) &&
 				(pAd->MlmeAux.ExtRateLen == 0))
 				// B only AP
@@ -7995,13 +8217,11 @@
 				MinimumRate = RATE_6;
 			break;
 		case PHY_11A:
-#ifdef DOT11_N_SUPPORT
 		case PHY_11N_2_4G:	// rt2860 need to check mlmerate for 802.11n
 		case PHY_11GN_MIXED:
 		case PHY_11AGN_MIXED:
 		case PHY_11AN_MIXED:
 		case PHY_11N_5G:
-#endif // DOT11_N_SUPPORT //
 			ProperMlmeRate = RATE_24;
 			MinimumRate = RATE_6;
 			break;
@@ -8111,6 +8331,58 @@
 	return larger;
 }
 
+#ifdef RT30xx
+// Antenna divesity use GPIO3 and EESK pin for control
+// Antenna and EEPROM access are both using EESK pin,
+// Therefor we should avoid accessing EESK at the same time
+// Then restore antenna after EEPROM access
+VOID AsicSetRxAnt(
+	IN PRTMP_ADAPTER	pAd,
+	IN UCHAR			Ant)
+{
+#ifdef RT30xx
+	UINT32	Value;
+	UINT32	x;
+
+	if ((pAd->EepromAccess)										||
+		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS))	||
+		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS))	||
+		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))			||
+		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
+	{
+		return;
+	}
+
+	// the antenna selection is through firmware and MAC register(GPIO3)
+	if (Ant == 0)
+	{
+		// Main antenna
+		RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
+		x |= (EESK);
+		RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
+
+		RTMP_IO_READ32(pAd, GPIO_CTRL_CFG, &Value);
+		Value &= ~(0x0808);
+		RTMP_IO_WRITE32(pAd, GPIO_CTRL_CFG, Value);
+		DBGPRINT_RAW(RT_DEBUG_TRACE, ("AsicSetRxAnt, switch to main antenna\n"));
+	}
+	else
+	{
+		// Aux antenna
+		RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
+		x &= ~(EESK);
+		RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
+
+		RTMP_IO_READ32(pAd, GPIO_CTRL_CFG, &Value);
+		Value &= ~(0x0808);
+		Value |= 0x08;
+		RTMP_IO_WRITE32(pAd, GPIO_CTRL_CFG, Value);
+		DBGPRINT_RAW(RT_DEBUG_TRACE, ("AsicSetRxAnt, switch to aux antenna\n"));
+	}
+#endif // RT30xx //
+}
+#endif /* RT30xx */
+
 /*
     ========================================================================
     Routine Description:
@@ -8129,14 +8401,7 @@
 {
 	UCHAR	BBPR3 = 0;
 
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+#ifndef RT30xx
 	{
 		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS	|
 								fRTMP_ADAPTER_HALT_IN_PROGRESS	|
@@ -8148,7 +8413,6 @@
 		if (pAd->StaCfg.Psm == PWR_SAVE)
 			return;
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPR3);
 	BBPR3 &= (~0x18);
@@ -8165,10 +8429,11 @@
 		BBPR3 |= (0x0);
 	}
 	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPR3);
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+
+#ifdef RT2860
     	pAd->StaCfg.BBPR3 = BBPR3;
-#endif // CONFIG_STA_SUPPORT //
+#endif
+#ifdef RT2870
 	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)
 		)
 	{
@@ -8187,6 +8452,90 @@
 			pAd->Mlme.bLowThroughput = TRUE;
 		}
 	}
+#endif
+#endif /* RT30xx */
+#ifdef RT30xx
+	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS	|
+							fRTMP_ADAPTER_HALT_IN_PROGRESS	|
+							fRTMP_ADAPTER_RADIO_OFF			|
+							fRTMP_ADAPTER_NIC_NOT_EXIST		|
+							fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS) ||
+							OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE)
+#ifdef RT30xx
+							|| (pAd->EepromAccess)
+#endif // RT30xx //
+							)
+		return;
+
+
+	{
+		//if (pAd->StaCfg.Psm == PWR_SAVE)
+		//	return;
+	}
+
+	// two antenna selection mechanism- one is antenna diversity, the other is failed antenna remove
+	// one is antenna diversity:there is only one antenna can rx and tx
+	// the other is failed antenna remove:two physical antenna can rx and tx
+	if (pAd->NicConfig2.field.AntDiversity)
+	{
+		DBGPRINT(RT_DEBUG_TRACE,("AntDiv - before evaluate Pair1-Ant (%d,%d)\n",
+			pAd->RxAnt.Pair1PrimaryRxAnt, pAd->RxAnt.Pair1SecondaryRxAnt));
+
+		AsicSetRxAnt(pAd, pAd->RxAnt.Pair1SecondaryRxAnt);
+
+		pAd->RxAnt.EvaluatePeriod = 1; // 1:Means switch to SecondaryRxAnt, 0:Means switch to Pair1PrimaryRxAnt
+		pAd->RxAnt.FirstPktArrivedWhenEvaluate = FALSE;
+		pAd->RxAnt.RcvPktNumWhenEvaluate = 0;
+
+		// a one-shot timer to end the evalution
+		// dynamic adjust antenna evaluation period according to the traffic
+		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
+			RTMPSetTimer(&pAd->Mlme.RxAntEvalTimer, 100);
+		else
+			RTMPSetTimer(&pAd->Mlme.RxAntEvalTimer, 300);
+	}
+	else
+	{
+		if (pAd->StaCfg.Psm == PWR_SAVE)
+			return;
+
+		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPR3);
+		BBPR3 &= (~0x18);
+		if(pAd->Antenna.field.RxPath == 3)
+		{
+			BBPR3 |= (0x10);
+		}
+		else if(pAd->Antenna.field.RxPath == 2)
+		{
+			BBPR3 |= (0x8);
+		}
+		else if(pAd->Antenna.field.RxPath == 1)
+		{
+			BBPR3 |= (0x0);
+		}
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPR3);
+	}
+#endif /* RT30xx */
+
+	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)
+		)
+	{
+		ULONG	TxTotalCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount +
+								pAd->RalinkCounters.OneSecTxRetryOkCount +
+								pAd->RalinkCounters.OneSecTxFailCount;
+
+			// dynamic adjust antenna evaluation period according to the traffic
+		if (TxTotalCnt > 50)
+		{
+			RTMPSetTimer(&pAd->Mlme.RxAntEvalTimer, 20);
+			pAd->Mlme.bLowThroughput = FALSE;
+		}
+		else
+		{
+			RTMPSetTimer(&pAd->Mlme.RxAntEvalTimer, 300);
+			pAd->Mlme.bLowThroughput = TRUE;
+		}
+	}
 }
 
 /*
@@ -8209,19 +8558,10 @@
 	IN PVOID SystemSpecific3)
 {
 	RTMP_ADAPTER	*pAd = (RTMP_ADAPTER *)FunctionContext;
-#ifdef CONFIG_STA_SUPPORT
 	UCHAR			BBPR3 = 0;
 	CHAR			larger = -127, rssi0, rssi1, rssi2;
-#endif // CONFIG_STA_SUPPORT //
 
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+#ifndef RT30xx
 	{
 		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)	||
 			RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)		||
@@ -8279,11 +8619,111 @@
 			BBPR3 |= (0x0);
 		}
 		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPR3);
+#ifdef RT2860
 		pAd->StaCfg.BBPR3 = BBPR3;
+#endif
 	}
+#endif /* RT30xx */
+#ifdef RT30xx
+	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS	|
+							fRTMP_ADAPTER_HALT_IN_PROGRESS	|
+							fRTMP_ADAPTER_RADIO_OFF			|
+							fRTMP_ADAPTER_NIC_NOT_EXIST) ||
+							OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE)
+#ifdef RT30xx
+							|| (pAd->EepromAccess)
+#endif // RT30xx //
+							)
+		return;
 
-#endif // CONFIG_STA_SUPPORT //
+	{
+		//if (pAd->StaCfg.Psm == PWR_SAVE)
+		//	return;
 
+		if (pAd->NicConfig2.field.AntDiversity)
+		{
+			if ((pAd->RxAnt.RcvPktNumWhenEvaluate != 0) && (pAd->RxAnt.Pair1AvgRssi[pAd->RxAnt.Pair1SecondaryRxAnt] >= pAd->RxAnt.Pair1AvgRssi[pAd->RxAnt.Pair1PrimaryRxAnt]))
+			{
+				UCHAR			temp;
+
+				//
+				// select PrimaryRxAntPair
+				//    Role change, Used Pair1SecondaryRxAnt as PrimaryRxAntPair.
+				//    Since Pair1SecondaryRxAnt Quality good than Pair1PrimaryRxAnt
+				//
+				temp = pAd->RxAnt.Pair1PrimaryRxAnt;
+				pAd->RxAnt.Pair1PrimaryRxAnt = pAd->RxAnt.Pair1SecondaryRxAnt;
+				pAd->RxAnt.Pair1SecondaryRxAnt = temp;
+
+				pAd->RxAnt.Pair1LastAvgRssi = (pAd->RxAnt.Pair1AvgRssi[pAd->RxAnt.Pair1SecondaryRxAnt] >> 3);
+				pAd->RxAnt.EvaluateStableCnt = 0;
+			}
+			else
+			{
+				// if the evaluated antenna is not better than original, switch back to original antenna
+				AsicSetRxAnt(pAd, pAd->RxAnt.Pair1PrimaryRxAnt);
+				pAd->RxAnt.EvaluateStableCnt ++;
+			}
+
+			pAd->RxAnt.EvaluatePeriod = 0; // 1:Means switch to SecondaryRxAnt, 0:Means switch to Pair1PrimaryRxAnt
+
+			DBGPRINT(RT_DEBUG_TRACE,("AsicRxAntEvalAction::After Eval(fix in #%d), <%d, %d>, RcvPktNumWhenEvaluate=%ld\n",
+					pAd->RxAnt.Pair1PrimaryRxAnt, (pAd->RxAnt.Pair1AvgRssi[0] >> 3), (pAd->RxAnt.Pair1AvgRssi[1] >> 3), pAd->RxAnt.RcvPktNumWhenEvaluate));
+		}
+		else
+		{
+			if (pAd->StaCfg.Psm == PWR_SAVE)
+				return;
+
+			// if the traffic is low, use average rssi as the criteria
+			if (pAd->Mlme.bLowThroughput == TRUE)
+			{
+				rssi0 = pAd->StaCfg.RssiSample.LastRssi0;
+				rssi1 = pAd->StaCfg.RssiSample.LastRssi1;
+				rssi2 = pAd->StaCfg.RssiSample.LastRssi2;
+			}
+			else
+			{
+				rssi0 = pAd->StaCfg.RssiSample.AvgRssi0;
+				rssi1 = pAd->StaCfg.RssiSample.AvgRssi1;
+				rssi2 = pAd->StaCfg.RssiSample.AvgRssi2;
+			}
+
+			if(pAd->Antenna.field.RxPath == 3)
+			{
+				larger = max(rssi0, rssi1);
+
+				if (larger > (rssi2 + 20))
+					pAd->Mlme.RealRxPath = 2;
+				else
+					pAd->Mlme.RealRxPath = 3;
+			}
+			else if(pAd->Antenna.field.RxPath == 2)
+			{
+				if (rssi0 > (rssi1 + 20))
+					pAd->Mlme.RealRxPath = 1;
+				else
+					pAd->Mlme.RealRxPath = 2;
+			}
+
+			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPR3);
+			BBPR3 &= (~0x18);
+			if(pAd->Mlme.RealRxPath == 3)
+			{
+				BBPR3 |= (0x10);
+			}
+			else if(pAd->Mlme.RealRxPath == 2)
+			{
+				BBPR3 |= (0x8);
+			}
+			else if(pAd->Mlme.RealRxPath == 1)
+			{
+				BBPR3 |= (0x0);
+			}
+			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPR3);
+		}
+	}
+#endif /* RT30xx */
 }
 
 
@@ -8350,9 +8790,6 @@
 {
 	BOOLEAN		result = TRUE;
 
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		// only associated STA counts
 		if (pEntry && (pEntry->ValidAsCLI) && (pEntry->Sst == SST_ASSOC))
@@ -8361,15 +8798,7 @@
 		}
 		else
 			result = FALSE;
-
-#ifdef QOS_DLS_SUPPORT
-		if (pEntry && (pEntry->ValidAsDls))
-			result = pAd->StaCfg.bAutoTxRateSwitch;
-#endif // QOS_DLS_SUPPORT //
 	}
-#endif // CONFIG_STA_SUPPORT //
-
-
 
 	return result;
 }
@@ -8378,14 +8807,9 @@
 BOOLEAN RTMPAutoRateSwitchCheck(
 	IN PRTMP_ADAPTER    pAd)
 {
+	if (pAd->StaCfg.bAutoTxRateSwitch)
+		return TRUE;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pAd->StaCfg.bAutoTxRateSwitch)
-			return TRUE;
-	}
-#endif // CONFIG_STA_SUPPORT //
 	return FALSE;
 }
 
@@ -8411,13 +8835,7 @@
 {
 	UCHAR	tx_mode = FIXED_TXMODE_HT;
 
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		tx_mode = (UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode;
-	}
-#endif // CONFIG_STA_SUPPORT //
+	tx_mode = (UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode;
 
 	return tx_mode;
 }
@@ -8474,7 +8892,6 @@
 	}
 }
 
-#ifdef CONFIG_STA_SUPPORT
 /*
 	==========================================================================
 	Description:
@@ -8505,7 +8922,12 @@
 		&& (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)
 			)
 		&& !(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
+#ifdef RT2860
 		&& (pAd->bPCIclkOff == FALSE))
+#endif
+#ifdef RT2870
+		)
+#endif
 	{
 		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &OrigR66Value);
 		R66 = OrigR66Value;
@@ -8517,6 +8939,45 @@
 
 		if (pAd->LatchRfRegs.Channel <= 14)
 		{	//BG band
+#ifdef RT2870
+			// RT3070 is a no LNA solution, it should have different control regarding to AGC gain control
+			// Otherwise, it will have some throughput side effect when low RSSI
+#ifndef RT30xx
+			if (IS_RT3070(pAd))
+#endif
+#ifdef RT30xx
+			if (IS_RT30xx(pAd))
+#endif
+			{
+				if (Rssi > RSSI_FOR_MID_LOW_SENSIBILITY)
+				{
+					R66 = 0x1C + 2*GET_LNA_GAIN(pAd) + 0x20;
+					if (OrigR66Value != R66)
+					{
+#ifndef RT30xx
+						RTUSBWriteBBPRegister(pAd, BBP_R66, R66);
+#endif
+#ifdef RT30xx
+						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
+#endif
+					}
+				}
+				else
+				{
+					R66 = 0x1C + 2*GET_LNA_GAIN(pAd);
+					if (OrigR66Value != R66)
+					{
+#ifndef RT30xx
+						RTUSBWriteBBPRegister(pAd, BBP_R66, R66);
+#endif
+#ifdef RT30xx
+						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
+#endif
+					}
+				}
+			}
+			else
+#endif // RT2870 //
 			{
 				if (Rssi > RSSI_FOR_MID_LOW_SENSIBILITY)
 				{
@@ -8582,6 +9043,7 @@
 	}
 }
 
+#ifdef RT2860
 VOID AsicResetFromDMABusy(
 	IN PRTMP_ADAPTER pAd)
 {
@@ -8681,7 +9143,7 @@
 		DBGPRINT(RT_DEBUG_TRACE, ("<---  Asic HardReset PBF !!!! \n"));
 	}
 }
-#endif // CONFIG_STA_SUPPORT //
+#endif /* RT2860 */
 
 VOID RTMPSetAGCInitValue(
 	IN PRTMP_ADAPTER	pAd,
@@ -8701,13 +9163,11 @@
 			R66 = (UCHAR)(0x32 + (GET_LNA_GAIN(pAd)*5)/3);
 			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
 		}
-#ifdef DOT11_N_SUPPORT
 		else
 		{
 			R66 = (UCHAR)(0x3A + (GET_LNA_GAIN(pAd)*5)/3);
 			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
 		}
-#endif // DOT11_N_SUPPORT //
 	}
 
 }
@@ -8722,6 +9182,15 @@
 	UCHAR			index;
 	RTMP_RF_REGS	*RFRegTable;
 
+#ifdef RT30xx
+	// The RF programming sequence is difference between 3xxx and 2xxx
+	if (IS_RT3090(pAd))
+	{
+		RT30xxLoadRFSleepModeSetup(pAd);  // add by johnli,  RF power sequence setup, load RF sleep-mode setup
+	}
+	else
+	{
+#endif // RT30xx //
 	RFRegTable = RF2850RegTable;
 
 	switch (pAd->RfIcType)
@@ -8763,6 +9232,10 @@
 		default:
 			break;
 	}
+#ifdef RT30xx
+	}
+#endif // RT30xx //
+
 }
 
 
@@ -8776,6 +9249,14 @@
 	UCHAR			index;
 	RTMP_RF_REGS	*RFRegTable;
 
+#ifdef RT30xx
+	// The RF programming sequence is difference between 3xxx and 2xxx
+	if (IS_RT3090(pAd))
+	{
+	}
+	else
+	{
+#endif // RT30xx //
 	RFRegTable = RF2850RegTable;
 
 	switch (pAd->RfIcType)
@@ -8822,9 +9303,14 @@
 			break;
 	}
 
+#ifndef RT30xx
 	DBGPRINT(RT_DEBUG_TRACE, ("AsicTurnOnRFClk#%d(RF=%d, ) , R2=0x%08x\n",
 		Channel,
 		pAd->RfIcType,
 		R2));
+#endif
+#ifdef RT30xx
+	}
+#endif // RT30xx //
 }
 
diff --git a/drivers/staging/rt2860/common/netif_block.c b/drivers/staging/rt2860/common/netif_block.c
deleted file mode 100644
index d3f7d08..0000000
--- a/drivers/staging/rt2860/common/netif_block.c
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#include "../rt_config.h"
-#include "netif_block.h"
-
-static NETIF_ENTRY freeNetIfEntryPool[FREE_NETIF_POOL_SIZE];
-static LIST_HEADER freeNetIfEntryList;
-
-void initblockQueueTab(
-	IN PRTMP_ADAPTER pAd)
-{
-	int i;
-
-	initList(&freeNetIfEntryList);
-	for (i = 0; i < FREE_NETIF_POOL_SIZE; i++)
-		insertTailList(&freeNetIfEntryList, (PLIST_ENTRY)&freeNetIfEntryPool[i]);
-
-	for (i=0; i < NUM_OF_TX_RING; i++)
-		initList(&pAd->blockQueueTab[i].NetIfList);
-
-	return;
-}
-
-BOOLEAN blockNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry,
-	IN PNET_DEV pNetDev)
-{
-	PNETIF_ENTRY pNetIfEntry = NULL;
-
-	if ((pNetIfEntry = (PNETIF_ENTRY)removeHeadList(&freeNetIfEntryList)) != NULL)
-	{
-		netif_stop_queue(pNetDev);
-		pNetIfEntry->pNetDev = pNetDev;
-		insertTailList(&pBlockQueueEntry->NetIfList, (PLIST_ENTRY)pNetIfEntry);
-
-		pBlockQueueEntry->SwTxQueueBlockFlag = TRUE;
-		DBGPRINT(RT_DEBUG_TRACE, ("netif_stop_queue(%s)\n", pNetDev->name));
-	}
-	else
-		return FALSE;
-
-	return TRUE;
-}
-
-VOID releaseNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry)
-{
-	PNETIF_ENTRY pNetIfEntry = NULL;
-	PLIST_HEADER pNetIfList = &pBlockQueueEntry->NetIfList;
-
-	while((pNetIfEntry = (PNETIF_ENTRY)removeHeadList(pNetIfList)) !=  NULL)
-	{
-		PNET_DEV pNetDev = pNetIfEntry->pNetDev;
-		netif_wake_queue(pNetDev);
-		insertTailList(&freeNetIfEntryList, (PLIST_ENTRY)pNetIfEntry);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("netif_wake_queue(%s)\n", pNetDev->name));
-	}
-	pBlockQueueEntry->SwTxQueueBlockFlag = FALSE;
-	return;
-}
-
-
-VOID StopNetIfQueue(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR QueIdx,
-	IN PNDIS_PACKET pPacket)
-{
-	PNET_DEV NetDev = NULL;
-	UCHAR IfIdx = 0;
-	BOOLEAN valid = FALSE;
-
-#ifdef APCLI_SUPPORT
-	if (RTMP_GET_PACKET_NET_DEVICE(pPacket) >= MIN_NET_DEVICE_FOR_APCLI)
-	{
-		IfIdx = (RTMP_GET_PACKET_NET_DEVICE(pPacket) - MIN_NET_DEVICE_FOR_APCLI) % MAX_APCLI_NUM;
-		NetDev = pAd->ApCfg.ApCliTab[IfIdx].dev;
-	}
-	else
-#endif // APCLI_SUPPORT //
-#ifdef WDS_SUPPORT
-	if (RTMP_GET_PACKET_NET_DEVICE(pPacket) >= MIN_NET_DEVICE_FOR_WDS)
-	{
-		IfIdx = (RTMP_GET_PACKET_NET_DEVICE(pPacket) - MIN_NET_DEVICE_FOR_WDS) % MAX_WDS_ENTRY;
-		NetDev = pAd->WdsTab.WdsEntry[IfIdx].dev;
-	}
-	else
-#endif // WDS_SUPPORT //
-	{
-#ifdef MBSS_SUPPORT
-		if (pAd->OpMode == OPMODE_AP)
-		{
-			IfIdx = (RTMP_GET_PACKET_NET_DEVICE(pPacket) - MIN_NET_DEVICE_FOR_MBSSID) % MAX_MBSSID_NUM;
-			NetDev = pAd->ApCfg.MBSSID[IfIdx].MSSIDDev;
-		}
-		else
-		{
-			IfIdx = MAIN_MBSSID;
-			NetDev = pAd->net_dev;
-		}
-#else
-		IfIdx = MAIN_MBSSID;
-		NetDev = pAd->net_dev;
-#endif
-	}
-
-	// WMM support 4 software queues.
-	// One software queue full doesn't mean device have no capbility to transmit packet.
-	// So disable block Net-If queue function while WMM enable.
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		valid = (pAd->CommonCfg.bWmmCapable == TRUE) ? FALSE : TRUE;
-#endif // CONFIG_STA_SUPPORT //
-
-	if (valid)
-		blockNetIf(&pAd->blockQueueTab[QueIdx], NetDev);
-	return;
-}
-
diff --git a/drivers/staging/rt2860/common/netif_block.h b/drivers/staging/rt2860/common/netif_block.h
deleted file mode 100644
index 6e5151c..0000000
--- a/drivers/staging/rt2860/common/netif_block.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#ifndef __NET_IF_BLOCK_H__
-#define __NET_IF_BLOCK_H__
-
-//#include <linux/device.h>
-#include "link_list.h"
-#include "rtmp.h"
-
-#define FREE_NETIF_POOL_SIZE 32
-
-typedef struct _NETIF_ENTRY
-{
-	struct _NETIF_ENTRY *pNext;
-	PNET_DEV pNetDev;
-} NETIF_ENTRY, *PNETIF_ENTRY;
-
-void initblockQueueTab(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN blockNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry,
-	IN PNET_DEV pNetDev);
-
-VOID releaseNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry);
-
-VOID StopNetIfQueue(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR QueIdx,
-	IN PNDIS_PACKET pPacket);
-#endif // __NET_IF_BLOCK_H__
-
diff --git a/drivers/staging/rt2860/common/rtmp_init.c b/drivers/staging/rt2860/common/rtmp_init.c
index 8a00cee3..004f530 100644
--- a/drivers/staging/rt2860/common/rtmp_init.c
+++ b/drivers/staging/rt2860/common/rtmp_init.c
@@ -38,8 +38,18 @@
     Jan Lee  2006-09-15    RT2860. Change for 802.11n , EEPROM, Led, BA, HT.
 */
 #include "../rt_config.h"
-#include 	"firmware.h"
+#ifndef RT30xx
+#ifdef RT2860
+#include "firmware.h"
 #include <linux/bitrev.h>
+#endif
+#ifdef RT2870
+#include "../../rt2870/common/firmware.h"
+#endif
+#endif
+#ifdef RT30xx
+#include "../../rt3070/firmware.h"
+#endif
 
 UCHAR    BIT8[] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
 ULONG    BIT32[] = {0x00000001, 0x00000002, 0x00000004, 0x00000008,
@@ -90,6 +100,22 @@
 #define ByteCRC16(v, crc) \
 	(unsigned short)((crc << 8) ^  ccitt_16Table[((crc >> 8) ^ (v)) & 255])
 
+#ifdef RT2870
+unsigned char BitReverse(unsigned char x)
+{
+	int i;
+	unsigned char Temp=0;
+	for(i=0; ; i++)
+	{
+		if(x & 0x80)	Temp |= 0x80;
+		if(i==7)		break;
+		x	<<= 1;
+		Temp >>= 1;
+	}
+	return Temp;
+}
+#endif
+
 //
 // BBP register initialization set
 //
@@ -114,6 +140,38 @@
 //
 // RF register initialization set
 //
+#ifdef RT2870
+REG_PAIR   RT30xx_RFRegTable[] = {
+        {RF_R04,          0x40},
+        {RF_R05,          0x03},
+        {RF_R06,          0x02},
+        {RF_R07,          0x70},
+        {RF_R09,          0x0F},
+#ifndef RT30xx
+        {RF_R10,          0x71},
+#endif
+#ifdef RT30xx
+        {RF_R10,          0x41},
+#endif
+        {RF_R11,          0x21},
+        {RF_R12,          0x7B},
+        {RF_R14,          0x90},
+        {RF_R15,          0x58},
+        {RF_R16,          0xB3},
+        {RF_R17,          0x92},
+        {RF_R18,          0x2C},
+        {RF_R19,          0x02},
+        {RF_R20,          0xBA},
+        {RF_R21,          0xDB},
+        {RF_R24,          0x16},
+        {RF_R25,          0x01},
+#ifndef RT30xx
+        {RF_R27,          0x03},
+#endif
+        {RF_R29,          0x1F},
+};
+#define	NUM_RF_REG_PARMS	(sizeof(RT30xx_RFRegTable) / sizeof(REG_PAIR))
+#endif // RT2870 //
 
 //
 // ASIC register initialization sets
@@ -146,10 +204,18 @@
 	{AUTO_RSP_CFG,			0x00000013},	// Initial Auto_Responder, because QA will turn off Auto-Responder
 	{CCK_PROT_CFG,			0x05740003 /*0x01740003*/},	// Initial Auto_Responder, because QA will turn off Auto-Responder. And RTS threshold is enabled.
 	{OFDM_PROT_CFG,			0x05740003 /*0x01740003*/},	// Initial Auto_Responder, because QA will turn off Auto-Responder. And RTS threshold is enabled.
+//PS packets use Tx1Q (for HCCA) when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
+#ifdef RT2870
+	{PBF_CFG, 				0xf40006}, 		// Only enable Queue 2
+	{MM40_PROT_CFG,			0x3F44084},		// Initial Auto_Responder, because QA will turn off Auto-Responder
+	{WPDMA_GLO_CFG,			0x00000030},
+#endif // RT2870 //
 	{GF20_PROT_CFG,			0x01744004},    // set 19:18 --> Short NAV for MIMO PS
 	{GF40_PROT_CFG,			0x03F44084},
 	{MM20_PROT_CFG,			0x01744004},
+#ifdef RT2860
 	{MM40_PROT_CFG,			0x03F54084},
+#endif
 	{TXOP_CTRL_CFG,			0x0000583f, /*0x0000243f*/ /*0x000024bf*/},	//Extension channel backoff.
 	{TX_RTS_CFG,			0x00092b20},
 	{EXP_ACK_TIME,			0x002400ca},	// default value
@@ -163,20 +229,22 @@
 	{PWR_PIN_CFG,			0x00000003},	// patch for 2880-E
 };
 
-
-#ifdef CONFIG_STA_SUPPORT
 RTMP_REG_PAIR	STAMACRegTable[] =	{
 	{WMM_AIFSN_CFG,		0x00002273},
 	{WMM_CWMIN_CFG,	0x00002344},
 	{WMM_CWMAX_CFG,	0x000034aa},
 };
-#endif // CONFIG_STA_SUPPORT //
 
 #define	NUM_MAC_REG_PARMS		(sizeof(MACRegTable) / sizeof(RTMP_REG_PAIR))
-#ifdef CONFIG_STA_SUPPORT
 #define	NUM_STA_MAC_REG_PARMS	(sizeof(STAMACRegTable) / sizeof(RTMP_REG_PAIR))
-#endif // CONFIG_STA_SUPPORT //
 
+#ifdef RT2870
+//
+// RT2870 Firmware Spec only used 1 oct for version expression
+//
+#define FIRMWARE_MINOR_VERSION	7
+
+#endif // RT2870 //
 
 // New 8k byte firmware size for RT3071/RT3072
 #define FIRMWAREIMAGE_MAX_LENGTH	0x2000
@@ -186,7 +254,9 @@
 #define FIRMWAREIMAGEV1_LENGTH	0x1000
 #define FIRMWAREIMAGEV2_LENGTH	0x1000
 
+#ifdef RT2860
 #define FIRMWARE_MINOR_VERSION	2
+#endif
 
 
 /*
@@ -244,7 +314,9 @@
 
 		// Init spin locks
 		NdisAllocateSpinLock(&pAd->MgmtRingLock);
+#ifdef RT2860
 		NdisAllocateSpinLock(&pAd->RxRingLock);
+#endif
 
 		for (index =0 ; index < NUM_OF_TX_RING; index++)
 		{
@@ -974,67 +1046,6 @@
 
 	// 4. Print and Debug
 	choffset = 14 + 12 + 16 + 7;
-
-
-#if 0
-	// Init the 802.11j channel number for TX channel power
-	// 0. 20MHz
-	for (i = 0; i < 3; i++)
-	{
-		pAd->TxPower11J[i].Channel = 8 + i * 4;
-		pAd->TxPower11J[i].BW = BW_20;
-	}
-
-	for (i = 0; i < 4; i++)
-	{
-		pAd->TxPower11J[i + 3].Channel = 34 + i * 4;
-		pAd->TxPower11J[i + 3].BW = BW_20;
-	}
-
-	for (i = 0; i < 4; i++)
-	{
-		pAd->TxPower11J[i + 7].Channel = 184 + i * 4;
-		pAd->TxPower11J[i + 7].BW = BW_20;
-	}
-
-	// 0. 10MHz
-	for (i = 0; i < 2; i++)
-	{
-		pAd->TxPower11J[i + 11].Channel = 7 + i;
-		pAd->TxPower11J[i + 11].BW = BW_10;
-	}
-	pAd->TxPower11J[13].Channel = 11;
-	pAd->TxPower11J[13].BW = BW_10;
-
-	for (i = 0; i < 3; i++)
-	{
-		pAd->TxPower11J[i + 14].Channel = 183 + i;
-		pAd->TxPower11J[i + 14].BW= BW_10;
-	}
-
-	for (i = 0; i < 3; i++)
-	{
-		pAd->TxPower11J[i + 17].Channel = 187 + i;
-		pAd->TxPower11J[i + 17].BW = BW_10;
-	}
-	for (i = 0; i < 10; i++)
-	{
-		Power.word = RTMP_EEPROM_READ16(pAd, EEPROM_Japan_TX_PWR_OFFSET + i * 2);
-		Power2.word = RTMP_EEPROM_READ16(pAd, EEPROM_Japan_TX2_PWR_OFFSET + i * 2);
-
-		if ((Power.field.Byte0 < 36) && (Power.field.Byte0 > -6))
-			pAd->TxPower11J[i * 2].Power = Power.field.Byte0;
-
-		if ((Power.field.Byte1 < 36) && (Power.field.Byte1 > -6))
-			pAd->TxPower11J[i * 2 + 1].Power = Power.field.Byte1;
-
-		if ((Power2.field.Byte0 < 36) && (Power2.field.Byte0 > -6))
-			pAd->TxPower11J[i * 2].Power2 = Power2.field.Byte0;
-
-		if ((Power2.field.Byte1 < 36) && (Power2.field.Byte1 > -6))
-			pAd->TxPower11J[i * 2 + 1].Power2 = Power2.field.Byte1;
-	}
-#endif
 }
 
 /*
@@ -1071,6 +1082,425 @@
 }
 
 
+#ifdef RT2870
+/*
+	========================================================================
+
+	Routine Description:
+		For RF filter calibration purpose
+
+	Arguments:
+		pAd                          Pointer to our adapter
+
+	Return Value:
+		None
+
+	IRQL = PASSIVE_LEVEL
+
+	========================================================================
+*/
+#ifndef RT30xx
+VOID RTUSBFilterCalibration(
+	IN PRTMP_ADAPTER pAd)
+{
+	UCHAR	R55x = 0, value, FilterTarget = 0x1E, BBPValue;
+	UINT	loop = 0, count = 0, loopcnt = 0, ReTry = 0;
+	UCHAR	RF_R24_Value = 0;
+
+	// Give bbp filter initial value
+	pAd->Mlme.CaliBW20RfR24 = 0x16;
+	pAd->Mlme.CaliBW40RfR24 = 0x36;  //Bit[5] must be 1 for BW 40
+
+	do
+	{
+		if (loop == 1)	//BandWidth = 40 MHz
+		{
+			// Write 0x27 to RF_R24 to program filter
+			RF_R24_Value = 0x27;
+			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
+			FilterTarget = 0x19;
+
+			// when calibrate BW40, BBP mask must set to BW40.
+			RTUSBReadBBPRegister(pAd, BBP_R4, &BBPValue);
+			BBPValue&= (~0x18);
+			BBPValue|= (0x10);
+			RTUSBWriteBBPRegister(pAd, BBP_R4, BBPValue);
+		}
+		else			//BandWidth = 20 MHz
+		{
+			// Write 0x07 to RF_R24 to program filter
+			RF_R24_Value = 0x07;
+			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
+			FilterTarget = 0x16;
+		}
+
+		// Write 0x01 to RF_R22 to enable baseband loopback mode
+		RT30xxReadRFRegister(pAd, RF_R22, &value);
+		value |= 0x01;
+		RT30xxWriteRFRegister(pAd, RF_R22, value);
+
+		// Write 0x00 to BBP_R24 to set power & frequency of passband test tone
+		RTUSBWriteBBPRegister(pAd, BBP_R24, 0);
+
+		do
+		{
+			// Write 0x90 to BBP_R25 to transmit test tone
+			RTUSBWriteBBPRegister(pAd, BBP_R25, 0x90);
+
+			RTMPusecDelay(1000);
+			// Read BBP_R55[6:0] for received power, set R55x = BBP_R55[6:0]
+			RTUSBReadBBPRegister(pAd, BBP_R55, &value);
+			R55x = value & 0xFF;
+
+		} while ((ReTry++ < 100) && (R55x == 0));
+
+		// Write 0x06 to BBP_R24 to set power & frequency of stopband test tone
+		RTUSBWriteBBPRegister(pAd, BBP_R24, 0x06);
+
+		while(TRUE)
+		{
+			// Write 0x90 to BBP_R25 to transmit test tone
+			RTUSBWriteBBPRegister(pAd, BBP_R25, 0x90);
+
+			//We need to wait for calibration
+			RTMPusecDelay(1000);
+			RTUSBReadBBPRegister(pAd, BBP_R55, &value);
+			value &= 0xFF;
+			if ((R55x - value) < FilterTarget)
+			{
+				RF_R24_Value ++;
+			}
+			else if ((R55x - value) == FilterTarget)
+			{
+				RF_R24_Value ++;
+				count ++;
+			}
+			else
+			{
+				break;
+			}
+
+			// prevent infinite loop cause driver hang.
+			if (loopcnt++ > 100)
+			{
+				DBGPRINT(RT_DEBUG_ERROR, ("RTUSBFilterCalibration - can't find a valid value, loopcnt=%d stop calibrating", loopcnt));
+				break;
+			}
+
+			// Write RF_R24 to program filter
+			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
+		}
+
+		if (count > 0)
+		{
+			RF_R24_Value = RF_R24_Value - ((count) ? (1) : (0));
+		}
+
+		// Store for future usage
+		if (loopcnt < 100)
+		{
+			if (loop++ == 0)
+			{
+				//BandWidth = 20 MHz
+				pAd->Mlme.CaliBW20RfR24 = (UCHAR)RF_R24_Value;
+			}
+			else
+			{
+				//BandWidth = 40 MHz
+				pAd->Mlme.CaliBW40RfR24 = (UCHAR)RF_R24_Value;
+				break;
+			}
+		}
+		else
+			break;
+
+		RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
+
+		// reset count
+		count = 0;
+	} while(TRUE);
+
+	//
+	// Set back to initial state
+	//
+	RTUSBWriteBBPRegister(pAd, BBP_R24, 0);
+
+	RT30xxReadRFRegister(pAd, RF_R22, &value);
+	value &= ~(0x01);
+	RT30xxWriteRFRegister(pAd, RF_R22, value);
+
+	// set BBP back to BW20
+	RTUSBReadBBPRegister(pAd, BBP_R4, &BBPValue);
+	BBPValue&= (~0x18);
+	RTUSBWriteBBPRegister(pAd, BBP_R4, BBPValue);
+
+	DBGPRINT(RT_DEBUG_TRACE, ("RTUSBFilterCalibration - CaliBW20RfR24=0x%x, CaliBW40RfR24=0x%x\n", pAd->Mlme.CaliBW20RfR24, pAd->Mlme.CaliBW40RfR24));
+}
+#endif /* RT30xx */
+#ifdef RT30xx
+VOID RTMPFilterCalibration(
+	IN PRTMP_ADAPTER pAd)
+{
+	UCHAR	R55x = 0, value, FilterTarget = 0x1E, BBPValue=0;
+	UINT	loop = 0, count = 0, loopcnt = 0, ReTry = 0;
+	UCHAR	RF_R24_Value = 0;
+
+	// Give bbp filter initial value
+	pAd->Mlme.CaliBW20RfR24 = 0x1F;
+	pAd->Mlme.CaliBW40RfR24 = 0x2F; //Bit[5] must be 1 for BW 40
+
+	do
+	{
+		if (loop == 1)	//BandWidth = 40 MHz
+		{
+			// Write 0x27 to RF_R24 to program filter
+			RF_R24_Value = 0x27;
+			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
+			if (IS_RT3090(pAd))
+				FilterTarget = 0x15;
+			else
+				FilterTarget = 0x19;
+
+			// when calibrate BW40, BBP mask must set to BW40.
+			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
+			BBPValue&= (~0x18);
+			BBPValue|= (0x10);
+			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
+
+			// set to BW40
+			RT30xxReadRFRegister(pAd, RF_R31, &value);
+			value |= 0x20;
+			RT30xxWriteRFRegister(pAd, RF_R31, value);
+		}
+		else			//BandWidth = 20 MHz
+		{
+			// Write 0x07 to RF_R24 to program filter
+			RF_R24_Value = 0x07;
+			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
+			if (IS_RT3090(pAd))
+				FilterTarget = 0x13;
+			else
+				FilterTarget = 0x16;
+
+			// set to BW20
+			RT30xxReadRFRegister(pAd, RF_R31, &value);
+			value &= (~0x20);
+			RT30xxWriteRFRegister(pAd, RF_R31, value);
+		}
+
+		// Write 0x01 to RF_R22 to enable baseband loopback mode
+		RT30xxReadRFRegister(pAd, RF_R22, &value);
+		value |= 0x01;
+		RT30xxWriteRFRegister(pAd, RF_R22, value);
+
+		// Write 0x00 to BBP_R24 to set power & frequency of passband test tone
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, 0);
+
+		do
+		{
+			// Write 0x90 to BBP_R25 to transmit test tone
+			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R25, 0x90);
+
+			RTMPusecDelay(1000);
+			// Read BBP_R55[6:0] for received power, set R55x = BBP_R55[6:0]
+			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R55, &value);
+			R55x = value & 0xFF;
+
+		} while ((ReTry++ < 100) && (R55x == 0));
+
+		// Write 0x06 to BBP_R24 to set power & frequency of stopband test tone
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, 0x06);
+
+		while(TRUE)
+		{
+			// Write 0x90 to BBP_R25 to transmit test tone
+			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R25, 0x90);
+
+			//We need to wait for calibration
+			RTMPusecDelay(1000);
+			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R55, &value);
+			value &= 0xFF;
+			if ((R55x - value) < FilterTarget)
+			{
+				RF_R24_Value ++;
+			}
+			else if ((R55x - value) == FilterTarget)
+			{
+				RF_R24_Value ++;
+				count ++;
+			}
+			else
+			{
+				break;
+			}
+
+			// prevent infinite loop cause driver hang.
+			if (loopcnt++ > 100)
+			{
+				DBGPRINT(RT_DEBUG_ERROR, ("RTMPFilterCalibration - can't find a valid value, loopcnt=%d stop calibrating", loopcnt));
+				break;
+			}
+
+			// Write RF_R24 to program filter
+			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
+		}
+
+		if (count > 0)
+		{
+			RF_R24_Value = RF_R24_Value - ((count) ? (1) : (0));
+		}
+
+		// Store for future usage
+		if (loopcnt < 100)
+		{
+			if (loop++ == 0)
+			{
+				//BandWidth = 20 MHz
+				pAd->Mlme.CaliBW20RfR24 = (UCHAR)RF_R24_Value;
+			}
+			else
+			{
+				//BandWidth = 40 MHz
+				pAd->Mlme.CaliBW40RfR24 = (UCHAR)RF_R24_Value;
+				break;
+			}
+		}
+		else
+			break;
+
+		RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
+
+		// reset count
+		count = 0;
+	} while(TRUE);
+
+	//
+	// Set back to initial state
+	//
+	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, 0);
+
+	RT30xxReadRFRegister(pAd, RF_R22, &value);
+	value &= ~(0x01);
+	RT30xxWriteRFRegister(pAd, RF_R22, value);
+
+	// set BBP back to BW20
+	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
+	BBPValue&= (~0x18);
+	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
+
+	DBGPRINT(RT_DEBUG_TRACE, ("RTMPFilterCalibration - CaliBW20RfR24=0x%x, CaliBW40RfR24=0x%x\n", pAd->Mlme.CaliBW20RfR24, pAd->Mlme.CaliBW40RfR24));
+}
+#endif /* RT30xx */
+
+VOID NICInitRT30xxRFRegisters(IN PRTMP_ADAPTER pAd)
+{
+	INT i;
+	// Driver must read EEPROM to get RfIcType before initial RF registers
+	// Initialize RF register to default value
+#ifndef RT30xx
+        if (IS_RT3070(pAd) && ((pAd->RfIcType == RFIC_3020) ||(pAd->RfIcType == RFIC_2020)))
+        {
+                // Init RF calibration
+                // Driver should toggle RF R30 bit7 before init RF registers
+                ULONG RfReg = 0;
+                RT30xxReadRFRegister(pAd, RF_R30, (PUCHAR)&RfReg);
+                RfReg |= 0x80;
+                RT30xxWriteRFRegister(pAd, RF_R30, (UCHAR)RfReg);
+                RTMPusecDelay(1000);
+                RfReg &= 0x7F;
+                RT30xxWriteRFRegister(pAd, RF_R30, (UCHAR)RfReg);
+
+                // Initialize RF register to default value
+                for (i = 0; i < NUM_RF_REG_PARMS; i++)
+                {
+                        RT30xxWriteRFRegister(pAd, RT30xx_RFRegTable[i].Register, RT30xx_RFRegTable[i].Value);
+                }
+
+                //For RF filter Calibration
+                RTUSBFilterCalibration(pAd);
+        }
+#endif
+#ifdef RT30xx
+	if (IS_RT3070(pAd) || IS_RT3071(pAd))
+	{
+		// Init RF calibration
+		// Driver should toggle RF R30 bit7 before init RF registers
+		UINT32 RfReg = 0;
+		UINT32 data;
+
+		RT30xxReadRFRegister(pAd, RF_R30, (PUCHAR)&RfReg);
+		RfReg |= 0x80;
+		RT30xxWriteRFRegister(pAd, RF_R30, (UCHAR)RfReg);
+		RTMPusecDelay(1000);
+		RfReg &= 0x7F;
+		RT30xxWriteRFRegister(pAd, RF_R30, (UCHAR)RfReg);
+
+		// Initialize RF register to default value
+		for (i = 0; i < NUM_RF_REG_PARMS; i++)
+		{
+			RT30xxWriteRFRegister(pAd, RT30xx_RFRegTable[i].Register, RT30xx_RFRegTable[i].Value);
+		}
+
+		// add by johnli
+		if (IS_RT3070(pAd))
+		{
+			//  Update MAC 0x05D4 from 01xxxxxx to 0Dxxxxxx (voltage 1.2V to 1.35V) for RT3070 to improve yield rate
+			RTUSBReadMACRegister(pAd, LDO_CFG0, &data);
+			data = ((data & 0xF0FFFFFF) | 0x0D000000);
+			RTUSBWriteMACRegister(pAd, LDO_CFG0, data);
+		}
+		else if (IS_RT3071(pAd))
+		{
+			// Driver should set RF R6 bit6 on before init RF registers
+			RT30xxReadRFRegister(pAd, RF_R06, (PUCHAR)&RfReg);
+			RfReg |= 0x40;
+			RT30xxWriteRFRegister(pAd, RF_R06, (UCHAR)RfReg);
+
+			// init R31
+			RT30xxWriteRFRegister(pAd, RF_R31, 0x14);
+
+			// RT3071 version E has fixed this issue
+			if ((pAd->NicConfig2.field.DACTestBit == 1) && ((pAd->MACVersion & 0xffff) < 0x0211))
+			{
+				// patch tx EVM issue temporarily
+				RTUSBReadMACRegister(pAd, LDO_CFG0, &data);
+				data = ((data & 0xE0FFFFFF) | 0x0D000000);
+				RTUSBWriteMACRegister(pAd, LDO_CFG0, data);
+			}
+			else
+			{
+				RTMP_IO_READ32(pAd, LDO_CFG0, &data);
+				data = ((data & 0xE0FFFFFF) | 0x01000000);
+				RTMP_IO_WRITE32(pAd, LDO_CFG0, data);
+			}
+
+			// patch LNA_PE_G1 failed issue
+			RTUSBReadMACRegister(pAd, GPIO_SWITCH, &data);
+			data &= ~(0x20);
+			RTUSBWriteMACRegister(pAd, GPIO_SWITCH, data);
+		}
+
+		//For RF filter Calibration
+		RTMPFilterCalibration(pAd);
+
+		// Initialize RF R27 register, set RF R27 must be behind RTMPFilterCalibration()
+		if ((pAd->MACVersion & 0xffff) < 0x0211)
+			RT30xxWriteRFRegister(pAd, RF_R27, 0x3);
+
+		// set led open drain enable
+		RTUSBReadMACRegister(pAd, OPT_14, &data);
+		data |= 0x01;
+		RTUSBWriteMACRegister(pAd, OPT_14, data);
+
+		if (IS_RT3071(pAd))
+		{
+			// add by johnli, RF power sequence setup, load RF normal operation-mode setup
+			RT30xxLoadRFNormalModeSetup(pAd);
+		}
+	}
+#endif
+}
+#endif // RT2870 //
 
 
 /*
@@ -1245,11 +1675,25 @@
 	Antenna.word = pAd->EEPROMDefaultValue[0];
 	if (Antenna.word == 0xFFFF)
 	{
+#ifdef RT30xx
+		if(IS_RT3090(pAd))
+		{
+			Antenna.word = 0;
+			Antenna.field.RfIcType = RFIC_3020;
+			Antenna.field.TxPath = 1;
+			Antenna.field.RxPath = 1;
+		}
+		else
+		{
+#endif // RT30xx //
 		Antenna.word = 0;
 		Antenna.field.RfIcType = RFIC_2820;
 		Antenna.field.TxPath = 1;
 		Antenna.field.RxPath = 2;
 		DBGPRINT(RT_DEBUG_WARN, ("E2PROM error, hard code as 0x%04x\n", Antenna.word));
+#ifdef RT30xx
+		}
+#endif // RT30xx //
 	}
 
 	// Choose the desired Tx&Rx stream.
@@ -1277,12 +1721,10 @@
 
 	NicConfig2.word = pAd->EEPROMDefaultValue[1];
 
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
+#ifndef RT30xx
 		NicConfig2.word = 0;
+#endif
 		if ((NicConfig2.word & 0x00ff) == 0xff)
 		{
 			NicConfig2.word &= 0xff00;
@@ -1293,7 +1735,6 @@
 			NicConfig2.word &= 0x00ff;
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	if (NicConfig2.field.DynamicTxAgcControl == 1)
 		pAd->bAutoTxAgcA = pAd->bAutoTxAgcG = TRUE;
@@ -1314,13 +1755,11 @@
 		if ((pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED) ||
 			(pAd->CommonCfg.PhyMode == PHY_11A))
 			pAd->CommonCfg.PhyMode = PHY_11BG_MIXED;
-#ifdef DOT11_N_SUPPORT
 		else if ((pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED)	||
 				 (pAd->CommonCfg.PhyMode == PHY_11AN_MIXED) 	||
 				 (pAd->CommonCfg.PhyMode == PHY_11AGN_MIXED) 	||
 				 (pAd->CommonCfg.PhyMode == PHY_11N_5G))
 			pAd->CommonCfg.PhyMode = PHY_11BGN_MIXED;
-#endif // DOT11_N_SUPPORT //
 	}
 
 	// Read TSSI reference and TSSI boundary for temperature compensation. This is ugly
@@ -1411,9 +1850,7 @@
 		TmpPhy = pAd->CommonCfg.PhyMode;
 		pAd->CommonCfg.PhyMode = 0xff;
 		RTMPSetPhyMode(pAd, TmpPhy);
-#ifdef DOT11_N_SUPPORT
 		SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
 	}
 
 	//
@@ -1480,10 +1917,13 @@
 
 	RTMPReadTxPwrPerRate(pAd);
 
-#ifdef SINGLE_SKU
-	//pAd->CommonCfg.DefineMaxTxPwr = RTMP_EEPROM_READ16(pAd, EEPROM_DEFINE_MAX_TXPWR);
-	RT28xx_EEPROM_READ16(pAd, EEPROM_DEFINE_MAX_TXPWR, pAd->CommonCfg.DefineMaxTxPwr);
-#endif // SINGLE_SKU //
+#ifdef RT30xx
+	if (IS_RT30xx(pAd))
+	{
+		eFusePhysicalReadRegisters(pAd, EFUSE_TAG, 2, &value);
+		pAd->EFuseTag = (value & 0xff);
+	}
+#endif // RT30xx //
 
 	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICReadEEPROMParameters\n"));
 }
@@ -1509,10 +1949,8 @@
 VOID	NICInitAsicFromEEPROM(
 	IN	PRTMP_ADAPTER	pAd)
 {
-#ifdef CONFIG_STA_SUPPORT
 	UINT32					data = 0;
 	UCHAR	BBPR1 = 0;
-#endif // CONFIG_STA_SUPPORT //
 	USHORT					i;
 	EEPROM_ANTENNA_STRUC	Antenna;
 	EEPROM_NIC_CONFIG2_STRUC    NicConfig2;
@@ -1531,16 +1969,49 @@
 		}
 	}
 
+#ifndef RT30xx
 	Antenna.word = pAd->Antenna.word;
+#endif
+#ifdef RT30xx
+	Antenna.word = pAd->EEPROMDefaultValue[0];
+	if (Antenna.word == 0xFFFF)
+	{
+		DBGPRINT(RT_DEBUG_ERROR, ("E2PROM error, hard code as 0x%04x\n", Antenna.word));
+		BUG_ON(Antenna.word == 0xFFFF);
+	}
+#endif
 	pAd->Mlme.RealRxPath = (UCHAR) Antenna.field.RxPath;
 	pAd->RfIcType = (UCHAR) Antenna.field.RfIcType;
 
+#ifdef RT30xx
+	DBGPRINT(RT_DEBUG_WARN, ("pAd->RfIcType = %d, RealRxPath=%d, TxPath = %d\n", pAd->RfIcType, pAd->Mlme.RealRxPath,Antenna.field.TxPath));
+
+	// Save the antenna for future use
+	pAd->Antenna.word = Antenna.word;
+#endif
 	NicConfig2.word = pAd->EEPROMDefaultValue[1];
 
+#ifdef RT30xx
+	{
+		if ((NicConfig2.word & 0x00ff) == 0xff)
+		{
+			NicConfig2.word &= 0xff00;
+		}
 
+		if ((NicConfig2.word >> 8) == 0xff)
+		{
+			NicConfig2.word &= 0x00ff;
+		}
+	}
+#endif
 	// Save the antenna for future use
 	pAd->NicConfig2.word = NicConfig2.word;
 
+#ifdef RT30xx
+	// set default antenna as main
+	if (pAd->RfIcType == RFIC_3020)
+		AsicSetRxAnt(pAd, pAd->RxAnt.Pair1PrimaryRxAnt);
+#endif
 	//
 	// Send LED Setting to MCU.
 	//
@@ -1549,7 +2020,13 @@
 		pAd->LedCntl.word = 0x01;
 		pAd->Led1 = 0x5555;
 		pAd->Led2 = 0x2221;
+#ifdef RT2860
 		pAd->Led3 = 0xA9F8;
+#endif
+
+#ifdef RT2870
+		pAd->Led3 = 0x5627;
+#endif // RT2870 //
 	}
 
 	AsicSendCommandToMcu(pAd, 0x52, 0xff, (UCHAR)pAd->Led1, (UCHAR)(pAd->Led1 >> 8));
@@ -1558,8 +2035,6 @@
     pAd->LedIndicatorStregth = 0xFF;
     RTMPSetSignalLED(pAd, -100);	// Force signal strength Led to be turned off, before link up
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		// Read Hardware controlled Radio state enable bit
 		if (NicConfig2.field.HardwareRadioControl == 1)
@@ -1585,13 +2060,14 @@
 		else
 		{
 			RTMPSetLED(pAd, LED_RADIO_ON);
+#ifdef RT2860
 			AsicSendCommandToMcu(pAd, 0x30, 0xff, 0xff, 0x02);
 			AsicSendCommandToMcu(pAd, 0x31, PowerWakeCID, 0x00, 0x00);
 			// 2-1. wait command ok.
 			AsicCheckCommanOk(pAd, PowerWakeCID);
+#endif
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	// Turn off patching for cardbus controller
 	if (NicConfig2.field.CardbusAcceleration == 1)
@@ -1624,8 +2100,6 @@
 	}
 	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPR3);
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		// Handle the difference when 1T
 		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BBPR1);
@@ -1637,7 +2111,7 @@
 
 		DBGPRINT(RT_DEBUG_TRACE, ("Use Hw Radio Control Pin=%d; if used Pin=%d;\n", pAd->CommonCfg.bHardwareRadio, pAd->CommonCfg.bHardwareRadio));
 	}
-#endif // CONFIG_STA_SUPPORT //
+
 	DBGPRINT(RT_DEBUG_TRACE, ("TxPath = %d, RxPath = %d, RFIC=%d, Polar+LED mode=%x\n", pAd->Antenna.field.TxPath, pAd->Antenna.field.RxPath, pAd->RfIcType, pAd->LedCntl.word));
 	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICInitAsicFromEEPROM\n"));
 }
@@ -1666,8 +2140,10 @@
 {
 	NDIS_STATUS     Status = NDIS_STATUS_SUCCESS;
 	WPDMA_GLO_CFG_STRUC	GloCfg;
+#ifdef RT2860
 	UINT32			Value;
 	DELAY_INT_CFG_STRUC	IntCfg;
+#endif
 	ULONG	i =0, j=0;
 	AC_TXOP_CSR0_STRUC	csr0;
 
@@ -1706,9 +2182,11 @@
 
 	// asic simulation sequence put this ahead before loading firmware.
 	// pbf hardware reset
+#ifdef RT2860
 	RTMP_IO_WRITE32(pAd, WPDMA_RST_IDX, 0x1003f);	// 0x10000 for reset rx, 0x3f resets all 6 tx rings.
 	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, 0xe1f);
 	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, 0xe00);
+#endif
 
 	// Initialze ASIC for TX & Rx operation
 	if (NICInitializeAsic(pAd , bHardReset) != NDIS_STATUS_SUCCESS)
@@ -1722,6 +2200,7 @@
 	}
 
 
+#ifdef RT2860
 	// Write AC_BK base address register
 	Value = RTMP_GetPhysicalAddressLow(pAd->TxRing[QID_AC_BK].Cell[0].AllocPa);
 	RTMP_IO_WRITE32(pAd, TX_BASE_PTR1, Value);
@@ -1794,6 +2273,7 @@
 	// Write RX_RING_CSR register
 	Value = RX_RING_SIZE;
 	RTMP_IO_WRITE32(pAd, RX_MAX_CNT, Value);
+#endif /* RT2860 */
 
 
 	// WMM parameter
@@ -1812,6 +2292,7 @@
 	RTMP_IO_WRITE32(pAd, WMM_TXOP1_CFG, csr0.word);
 
 
+#ifdef RT2860
 	// 3. Set DMA global configuration except TX_DMA_EN and RX_DMA_EN bits:
 	i = 0;
 	do
@@ -1830,6 +2311,7 @@
 
 	IntCfg.word = 0;
 	RTMP_IO_WRITE32(pAd, DELAY_INT_CFG, IntCfg.word);
+#endif
 
 
 	// reset action
@@ -1865,36 +2347,133 @@
 	ULONG			Index = 0;
 	UCHAR			R0 = 0xff;
 	UINT32			MacCsr12 = 0, Counter = 0;
+#ifdef RT2870
+	UINT32			MacCsr0 = 0;
+	NTSTATUS		Status;
+	UCHAR			Value = 0xff;
+#endif // RT2870 //
+#ifdef RT30xx
+	UINT32			eFuseCtrl;
+#endif // RT30xx //
 	USHORT			KeyIdx;
 	INT				i,apidx;
 
 	DBGPRINT(RT_DEBUG_TRACE, ("--> NICInitializeAsic\n"));
 
+#ifdef RT2860
 	if (bHardReset == TRUE)
 	{
 		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x3);
 	}
 	else
 		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x1);
+#endif
+#ifdef RT2870
+	//
+	// Make sure MAC gets ready after NICLoadFirmware().
+	//
+	Index = 0;
+
+	//To avoid hang-on issue when interface up in kernel 2.4,
+	//we use a local variable "MacCsr0" instead of using "pAd->MACVersion" directly.
+	do
+	{
+		RTMP_IO_READ32(pAd, MAC_CSR0, &MacCsr0);
+
+		if ((MacCsr0 != 0x00) && (MacCsr0 != 0xFFFFFFFF))
+			break;
+
+		RTMPusecDelay(10);
+	} while (Index++ < 100);
+
+	pAd->MACVersion = MacCsr0;
+	DBGPRINT(RT_DEBUG_TRACE, ("MAC_CSR0  [ Ver:Rev=0x%08x]\n", pAd->MACVersion));
+	// turn on bit13 (set to zero) after rt2860D. This is to solve high-current issue.
+	RTMP_IO_READ32(pAd, PBF_SYS_CTRL, &MacCsr12);
+	MacCsr12 &= (~0x2000);
+	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, MacCsr12);
+
+	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x3);
+	RTMP_IO_WRITE32(pAd, USB_DMA_CFG, 0x0);
+	Status = RTUSBVenderReset(pAd);
+#endif
 
 	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x0);
+
 	// Initialize MAC register to default value
+#ifdef RT2860
 	for (Index = 0; Index < NUM_MAC_REG_PARMS; Index++)
 	{
 		RTMP_IO_WRITE32(pAd, MACRegTable[Index].Register, MACRegTable[Index].Value);
 	}
+#endif
+#ifdef RT2870
+	for(Index=0; Index<NUM_MAC_REG_PARMS; Index++)
+	{
+#ifdef RT3070
+		if ((MACRegTable[Index].Register == TX_SW_CFG0) && (IS_RT3070(pAd) || IS_RT3071(pAd)))
+		{
+			MACRegTable[Index].Value = 0x00000400;
+		}
+#endif // RT3070 //
+		RTMP_IO_WRITE32(pAd, (USHORT)MACRegTable[Index].Register, MACRegTable[Index].Value);
+	}
+
+#ifndef RT30xx
+	if(IS_RT3070(pAd))
+	{
+		// According to Frank Hsu (from Gary Tsao)
+		RTMP_IO_WRITE32(pAd, (USHORT)TX_SW_CFG0, 0x00000400);
+
+		// Initialize RT3070 serial MAC registers which is different from RT2870 serial
+		RTUSBWriteMACRegister(pAd, TX_SW_CFG1, 0);
+		RTUSBWriteMACRegister(pAd, TX_SW_CFG2, 0);
+	}
+#endif
+#endif // RT2870 //
 
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		for (Index = 0; Index < NUM_STA_MAC_REG_PARMS; Index++)
 		{
+#ifdef RT2860
 			RTMP_IO_WRITE32(pAd, STAMACRegTable[Index].Register, STAMACRegTable[Index].Value);
+#endif
+#ifdef RT2870
+			RTMP_IO_WRITE32(pAd, (USHORT)STAMACRegTable[Index].Register, STAMACRegTable[Index].Value);
+#endif
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
+#ifdef RT30xx
+	// Initialize RT3070 serial MAc registers which is different from RT2870 serial
+	if (IS_RT3090(pAd))
+	{
+		RTMP_IO_WRITE32(pAd, TX_SW_CFG1, 0);
+
+		// RT3071 version E has fixed this issue
+		if ((pAd->MACVersion & 0xffff) < 0x0211)
+		{
+			if (pAd->NicConfig2.field.DACTestBit == 1)
+			{
+				RTMP_IO_WRITE32(pAd, TX_SW_CFG2, 0x1F);	// To fix throughput drop drastically
+			}
+			else
+			{
+				RTMP_IO_WRITE32(pAd, TX_SW_CFG2, 0x0F);	// To fix throughput drop drastically
+			}
+		}
+		else
+		{
+			RTMP_IO_WRITE32(pAd, TX_SW_CFG2, 0x0);
+		}
+	}
+	else if (IS_RT3070(pAd))
+	{
+		RTMP_IO_WRITE32(pAd, TX_SW_CFG1, 0);
+		RTMP_IO_WRITE32(pAd, TX_SW_CFG2, 0x1F);	// To fix throughput drop drastically
+	}
+#endif // RT30xx //
 
 	//
 	// Before program BBP, we need to wait BBP/RF get wake up.
@@ -1935,11 +2514,69 @@
 		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBPRegTable[Index].Register, BBPRegTable[Index].Value);
 	}
 
+#ifndef RT30xx
 	// for rt2860E and after, init BBP_R84 with 0x19. This is for extension channel overlapping IOT.
 	if ((pAd->MACVersion&0xffff) != 0x0101)
 		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R84, 0x19);
 
+#ifdef RT2870
+	//write RT3070 BBP wchich different with 2870 after write RT2870 BBP
+	if (IS_RT3070(pAd))
+	{
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0a);
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R84, 0x99);
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R105, 0x05);
+	}
+#endif // RT2870 //
+#endif
+#ifdef RT30xx
+	// for rt2860E and after, init BBP_R84 with 0x19. This is for extension channel overlapping IOT.
+	// RT3090 should not program BBP R84 to 0x19, otherwise TX will block.
+	if (((pAd->MACVersion&0xffff) != 0x0101) && (!IS_RT30xx(pAd)))
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R84, 0x19);
 
+// add by johnli, RF power sequence setup
+	if (IS_RT30xx(pAd))
+	{	//update for RT3070/71/72/90/91/92.
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R79, 0x13);
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R80, 0x05);
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R81, 0x33);
+	}
+
+	if (IS_RT3090(pAd))
+	{
+		UCHAR		bbpreg=0;
+
+		// enable DC filter
+		if ((pAd->MACVersion & 0xffff) >= 0x0211)
+		{
+			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R103, 0xc0);
+		}
+
+		// improve power consumption
+		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R138, &bbpreg);
+		if (pAd->Antenna.field.TxPath == 1)
+		{
+			// turn off tx DAC_1
+			bbpreg = (bbpreg | 0x20);
+		}
+
+		if (pAd->Antenna.field.RxPath == 1)
+		{
+			// turn off tx ADC_1
+			bbpreg &= (~0x2);
+		}
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R138, bbpreg);
+
+		// improve power consumption in RT3071 Ver.E
+		if ((pAd->MACVersion & 0xffff) >= 0x0211)
+		{
+			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R31, &bbpreg);
+			bbpreg &= (~0x3);
+			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R31, bbpreg);
+		}
+	}
+#endif
 	if (pAd->MACVersion == 0x28600100)
 	{
 		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x16);
@@ -1956,10 +2593,20 @@
 		RTMP_IO_WRITE32(pAd, MAX_LEN_CFG, csr);
 	}
 
+#ifdef RT2870
+{
+	UCHAR	MAC_Value[]={0xff,0xff,0xff,0xff,0xff,0xff,0xff,0,0};
+
+	//Initialize WCID table
+	Value = 0xff;
+	for(Index =0 ;Index < 254;Index++)
+	{
+		RTUSBMultiWrite(pAd, (USHORT)(MAC_WCID_BASE + Index * 8), MAC_Value, 8);
+	}
+}
+#endif // RT2870 //
 
 	// Add radio off control
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		if (pAd->StaCfg.bRadio == FALSE)
 		{
@@ -1968,7 +2615,6 @@
 			DBGPRINT(RT_DEBUG_TRACE, ("Set Radio Off\n"));
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	// Clear raw counters
 	RTMP_IO_READ32(pAd, RX_STA_CNT0, &Counter);
@@ -2006,21 +2652,48 @@
 				RTMP_IO_WRITE32(pAd, pAd->BeaconOffset[apidx] + i, 0x00);
 		}
 	}
+#ifdef RT2870
+	AsicDisableSync(pAd);
+	// Clear raw counters
+	RTMP_IO_READ32(pAd, RX_STA_CNT0, &Counter);
+	RTMP_IO_READ32(pAd, RX_STA_CNT1, &Counter);
+	RTMP_IO_READ32(pAd, RX_STA_CNT2, &Counter);
+	RTMP_IO_READ32(pAd, TX_STA_CNT0, &Counter);
+	RTMP_IO_READ32(pAd, TX_STA_CNT1, &Counter);
+	RTMP_IO_READ32(pAd, TX_STA_CNT2, &Counter);
+	// Default PCI clock cycle per ms is different as default setting, which is based on PCI.
+	RTMP_IO_READ32(pAd, USB_CYC_CFG, &Counter);
+	Counter&=0xffffff00;
+	Counter|=0x000001e;
+	RTMP_IO_WRITE32(pAd, USB_CYC_CFG, Counter);
+#endif // RT2870 //
+#ifdef RT30xx
+	pAd->bUseEfuse=FALSE;
+	RTMP_IO_READ32(pAd, EFUSE_CTRL, &eFuseCtrl);
+	pAd->bUseEfuse = ( (eFuseCtrl & 0x80000000) == 0x80000000) ? 1 : 0;
+	if(pAd->bUseEfuse)
+	{
+			DBGPRINT(RT_DEBUG_TRACE, ("NVM is Efuse\n"));
+	}
+	else
+	{
+			DBGPRINT(RT_DEBUG_TRACE, ("NVM is EEPROM\n"));
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+	}
+#endif // RT30xx //
+
 	{
 		// for rt2860E and after, init TXOP_CTRL_CFG with 0x583f. This is for extension channel overlapping IOT.
 		if ((pAd->MACVersion&0xffff) != 0x0101)
 			RTMP_IO_WRITE32(pAd, TXOP_CTRL_CFG, 0x583f);
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICInitializeAsic\n"));
 	return NDIS_STATUS_SUCCESS;
 }
 
 
+#ifdef RT2860
 VOID NICRestoreBBPValue(
 	IN PRTMP_ADAPTER pAd)
 {
@@ -2144,6 +2817,7 @@
 
 	DBGPRINT(RT_DEBUG_TRACE, ("<---  NICRestoreBBPValue !!!!!!!!!!!!!!!!!!!!!!!  \n"));
 }
+#endif /* RT2860 */
 
 /*
 	========================================================================
@@ -2214,12 +2888,6 @@
 	CHAR				reTry;
 	UCHAR				succMCS;
 
-#ifdef RALINK_ATE
-	/* Nothing to do in ATE mode */
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
 		do
 		{
 			RTMP_IO_READ32(pAd, TX_STA_FIFO, &StaFifo.word);
@@ -2244,10 +2912,8 @@
 
 			pEntry->DebugFIFOCount++;
 
-#ifdef DOT11_N_SUPPORT
 			if (StaFifo.field.TxBF) // 3*3
 				pEntry->TxBFCount++;
-#endif // DOT11_N_SUPPORT //
 
 #ifdef UAPSD_AP_SUPPORT
 			UAPSD_SP_AUE_Handle(pAd, pEntry, StaFifo.field.TxSuccess);
@@ -2261,23 +2927,15 @@
 				if (pEntry->FIFOCount >= 1)
 				{
 					DBGPRINT(RT_DEBUG_TRACE, ("#"));
-#if 0
-					SendRefreshBAR(pAd, pEntry);
 					pEntry->NoBADataCountDown = 64;
-#else
-#ifdef DOT11_N_SUPPORT
-					pEntry->NoBADataCountDown = 64;
-#endif // DOT11_N_SUPPORT //
 
 					if(pEntry->PsMode == PWR_ACTIVE)
 					{
-#ifdef DOT11_N_SUPPORT
 						int tid;
 						for (tid=0; tid<NUM_OF_TID; tid++)
 						{
 							BAOriSessionTearDown(pAd, pEntry->Aid,  tid, FALSE, FALSE);
 						}
-#endif // DOT11_N_SUPPORT //
 
 						// Update the continuous transmission counter except PS mode
 						pEntry->ContinueTxFailCnt++;
@@ -2289,14 +2947,10 @@
 						pEntry->FIFOCount = 0;
 						pEntry->ContinueTxFailCnt = 0;
 					}
-#endif
-					//pEntry->FIFOCount = 0;
 				}
-				//pEntry->bSendBAR = TRUE;
 			}
 			else
 			{
-#ifdef DOT11_N_SUPPORT
 				if ((pEntry->PsMode != PWR_SAVE) && (pEntry->NoBADataCountDown > 0))
 				{
 					pEntry->NoBADataCountDown--;
@@ -2305,7 +2959,7 @@
 						DBGPRINT(RT_DEBUG_TRACE, ("@\n"));
 					}
 				}
-#endif // DOT11_N_SUPPORT //
+
 				pEntry->FIFOCount = 0;
 				pEntry->OneSecTxNoRetryOkCount++;
 				// update NoDataIdleCount when sucessful send packet to STA.
@@ -2416,6 +3070,22 @@
 	// Update RX Overflow counter
 	pAd->Counters8023.RxNoBuffer += (RxStaCnt2.field.RxFifoOverflowCount);
 
+#ifdef RT2870
+	if (pAd->RalinkCounters.RxCount != pAd->watchDogRxCnt)
+	{
+		pAd->watchDogRxCnt = pAd->RalinkCounters.RxCount;
+		pAd->watchDogRxOverFlowCnt = 0;
+	}
+	else
+	{
+		if (RxStaCnt2.field.RxFifoOverflowCount)
+			pAd->watchDogRxOverFlowCnt++;
+		else
+			pAd->watchDogRxOverFlowCnt = 0;
+	}
+#endif // RT2870 //
+
+
 	if (!pAd->bUpdateBcnCntDone)
 	{
 	// Update BEACON sent count
@@ -2643,217 +3313,46 @@
 NDIS_STATUS NICLoadFirmware(
 	IN PRTMP_ADAPTER pAd)
 {
-#ifdef BIN_IN_FILE
-#define NICLF_DEFAULT_USE()	\
-	flg_default_firm_use = TRUE; \
-	printk("%s - Use default firmware!\n", __func__);
-
-	NDIS_STATUS		Status = NDIS_STATUS_SUCCESS;
-	PUCHAR			src;
-	struct file		*srcf;
-	INT 			retval, orgfsuid, orgfsgid, i;
-   	mm_segment_t	orgfs;
-	PUCHAR			pFirmwareImage;
-	UINT			FileLength = 0;
-	UINT32			MacReg;
-	ULONG			Index;
-	ULONG			firm;
-	BOOLEAN			flg_default_firm_use = FALSE;
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("===> %s\n", __func__));
-
-	/* init */
-	pFirmwareImage = NULL;
-	src = RTMP_FIRMWARE_FILE_NAME;
-
-	/* save uid and gid used for filesystem access.
-	   set user and group to 0 (root) */
-	orgfsuid = current->fsuid;
-	orgfsgid = current->fsgid;
-	current->fsuid = current->fsgid = 0;
-    orgfs = get_fs();
-    set_fs(KERNEL_DS);
-
-	pAd->FirmwareVersion = (FIRMWARE_MAJOR_VERSION << 8) + \
-						   FIRMWARE_MINOR_VERSION;
-
-
-	/* allocate firmware buffer */
-    pFirmwareImage = kmalloc(MAX_FIRMWARE_IMAGE_SIZE, MEM_ALLOC_FLAG);
-    if (pFirmwareImage == NULL)
-	{
-		/* allocate fail, use default firmware array in firmware.h */
-		printk("%s - Allocate memory fail!\n", __func__);
-		NICLF_DEFAULT_USE();
-    }
-	else
-	{
-		/* allocate ok! zero the firmware buffer */
-		memset(pFirmwareImage, 0x00, MAX_FIRMWARE_IMAGE_SIZE);
-	} /* End of if */
-
-
-	/* if ok, read firmware file from *.bin file */
-	if (flg_default_firm_use == FALSE)
-	{
-		do
-		{
-			/* open the bin file */
-			srcf = filp_open(src, O_RDONLY, 0);
-
-			if (IS_ERR(srcf))
-			{
-				printk("%s - Error %ld opening %s\n",
-					   __func__, -PTR_ERR(srcf), src);
-				NICLF_DEFAULT_USE();
-				break;
-			} /* End of if */
-
-			/* the object must have a read method */
-			if ((srcf->f_op == NULL) || (srcf->f_op->read == NULL))
-			{
-				printk("%s - %s does not have a write method\n", __func__, src);
-				NICLF_DEFAULT_USE();
-				break;
-			} /* End of if */
-
-			/* read the firmware from the file *.bin */
-			FileLength = srcf->f_op->read(srcf,
-										  pFirmwareImage,
-										  MAX_FIRMWARE_IMAGE_SIZE,
-										  &srcf->f_pos);
-
-			if (FileLength != MAX_FIRMWARE_IMAGE_SIZE)
-			{
-				printk("%s: error file length (=%d) in RT2860AP.BIN\n",
-					   __func__, FileLength);
-				NICLF_DEFAULT_USE();
-				break;
-			}
-			else
-			{
-				PUCHAR ptr = pFirmwareImage;
-				USHORT crc = 0xffff;
-
-
-				/* calculate firmware CRC */
-				for(i=0; i<(MAX_FIRMWARE_IMAGE_SIZE-2); i++, ptr++)
-					crc = ByteCRC16(bitrev8(*ptr), crc);
-				/* End of for */
-
-				if ((pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-2] != \
-								(UCHAR)bitrev8((UCHAR)(crc>>8))) ||
-					(pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-1] != \
-								(UCHAR)bitrev8((UCHAR)crc)))
-				{
-					/* CRC fail */
-					printk("%s: CRC = 0x%02x 0x%02x "
-						   "error, should be 0x%02x 0x%02x\n",
-						   __func__,
-						   pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-2],
-						   pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-1],
-						   (UCHAR)(crc>>8), (UCHAR)(crc));
-					NICLF_DEFAULT_USE();
-					break;
-				}
-				else
-				{
-					/* firmware is ok */
-					pAd->FirmwareVersion = \
-						(pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-4] << 8) +
-						pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-3];
-
-					/* check if firmware version of the file is too old */
-					if ((pAd->FirmwareVersion) < \
-											((FIRMWARE_MAJOR_VERSION << 8) +
-									  	 	 FIRMWARE_MINOR_VERSION))
-					{
-						printk("%s: firmware version too old!\n", __func__);
-						NICLF_DEFAULT_USE();
-						break;
-					} /* End of if */
-				} /* End of if */
-
-				DBGPRINT(RT_DEBUG_TRACE,
-						 ("NICLoadFirmware: CRC ok, ver=%d.%d\n",
-						  pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-4],
-						  pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-3]));
-			} /* End of if (FileLength == MAX_FIRMWARE_IMAGE_SIZE) */
-			break;
-		} while(TRUE);
-
-		/* close firmware file */
-		if (IS_ERR(srcf))
-			;
-		else
-		{
-			retval = filp_close(srcf, NULL);
-			if (retval)
-			{
-				DBGPRINT(RT_DEBUG_ERROR,
-						 ("--> Error %d closing %s\n", -retval, src));
-			} /* End of if */
-		} /* End of if */
-	} /* End of if */
-
-
-	/* write firmware to ASIC */
-	if (flg_default_firm_use == TRUE)
-	{
-		/* use default fimeware, free allocated buffer */
-		if (pFirmwareImage != NULL)
-			kfree(pFirmwareImage);
-		/* End of if */
-
-		/* use default *.bin array */
-		pFirmwareImage = FirmwareImage;
-		FileLength = sizeof(FirmwareImage);
-	} /* End of if */
-
-	/* enable Host program ram write selection */
-	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, 0x10000);
-
-	for(i=0; i<FileLength; i+=4)
-	{
-		firm = pFirmwareImage[i] +
-			   (pFirmwareImage[i+3] << 24) +
-			   (pFirmwareImage[i+2] << 16) +
-			   (pFirmwareImage[i+1] << 8);
-
-		RTMP_IO_WRITE32(pAd, FIRMWARE_IMAGE_BASE + i, firm);
-	} /* End of for */
-
-	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, 0x00000);
-	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, 0x00001);
-
-	/* initialize BBP R/W access agent */
-	RTMP_IO_WRITE32(pAd, H2M_BBP_AGENT, 0);
-	RTMP_IO_WRITE32(pAd, H2M_MAILBOX_CSR, 0);
-
-	if (flg_default_firm_use == FALSE)
-	{
-		/* use file firmware, free allocated buffer */
-		if (pFirmwareImage != NULL)
-			kfree(pFirmwareImage);
-		/* End of if */
-	} /* End of if */
-
-	set_fs(orgfs);
-	current->fsuid = orgfsuid;
-	current->fsgid = orgfsgid;
-#else
-
 	NDIS_STATUS		Status = NDIS_STATUS_SUCCESS;
 	PUCHAR			pFirmwareImage;
 	ULONG			FileLength, Index;
 	//ULONG			firm;
 	UINT32			MacReg = 0;
+#ifdef RT2870
+	UINT32			Version = (pAd->MACVersion >> 16);
+#endif // RT2870 //
 
 	pFirmwareImage = FirmwareImage;
 	FileLength = sizeof(FirmwareImage);
+#ifdef RT2870
+	// New 8k byte firmware size for RT3071/RT3072
+	//printk("Usb Chip\n");
+	if (FIRMWAREIMAGE_LENGTH == FIRMWAREIMAGE_MAX_LENGTH)
+	//The firmware image consists of two parts. One is the origianl and the other is the new.
+	//Use Second Part
+	{
+		if ((Version != 0x2860) && (Version != 0x2872) && (Version != 0x3070))
+		{	// Use Firmware V2.
+			//printk("KH:Use New Version,part2\n");
+			pFirmwareImage = (PUCHAR)&FirmwareImage[FIRMWAREIMAGEV1_LENGTH];
+			FileLength = FIRMWAREIMAGEV2_LENGTH;
+		}
+		else
+		{
+			//printk("KH:Use New Version,part1\n");
+			pFirmwareImage = FirmwareImage;
+			FileLength = FIRMWAREIMAGEV1_LENGTH;
+		}
+	}
+	else
+	{
+		DBGPRINT(RT_DEBUG_ERROR, ("KH: bin file should be 8KB.\n"));
+		Status = NDIS_STATUS_FAILURE;
+	}
+
+#endif // RT2870 //
+
 	RT28XX_WRITE_FIRMWARE(pAd, pFirmwareImage, FileLength);
-#endif
 
 	/* check if MCU is ready */
 	Index = 0;
@@ -2867,7 +3366,7 @@
 		RTMPusecDelay(1000);
 	} while (Index++ < 1000);
 
-    if (Index >= 1000)
+    if (Index > 1000)
 	{
 		Status = NDIS_STATUS_FAILURE;
 		DBGPRINT(RT_DEBUG_ERROR, ("NICLoadFirmware: MCU is not ready\n\n\n"));
@@ -3118,6 +3617,31 @@
 	//
 	//  part I. intialize common configuration
 	//
+#ifdef RT2870
+	pAd->BulkOutReq = 0;
+
+	pAd->BulkOutComplete = 0;
+	pAd->BulkOutCompleteOther = 0;
+	pAd->BulkOutCompleteCancel = 0;
+	pAd->BulkInReq = 0;
+	pAd->BulkInComplete = 0;
+	pAd->BulkInCompleteFail = 0;
+
+	//pAd->QuickTimerP = 100;
+	//pAd->TurnAggrBulkInCount = 0;
+	pAd->bUsbTxBulkAggre = 0;
+
+	// init as unsed value to ensure driver will set to MCU once.
+	pAd->LedIndicatorStregth = 0xFF;
+
+	pAd->CommonCfg.MaxPktOneTxBulk = 2;
+	pAd->CommonCfg.TxBulkFactor = 1;
+	pAd->CommonCfg.RxBulkFactor =1;
+
+	pAd->CommonCfg.TxPower = 100; //mW
+
+	NdisZeroMemory(&pAd->CommonCfg.IOTestParm, sizeof(pAd->CommonCfg.IOTestParm));
+#endif // RT2870 //
 
 	for(key_index=0; key_index<SHARE_KEY_NUM; key_index++)
 	{
@@ -3128,14 +3652,19 @@
 		}
 	}
 
+#ifdef RT30xx
+	pAd->EepromAccess = FALSE;
+#endif
 	pAd->Antenna.word = 0;
 	pAd->CommonCfg.BBPCurrentBW = BW_20;
 
 	pAd->LedCntl.word = 0;
+#ifdef RT2860
 	pAd->LedIndicatorStregth = 0;
 	pAd->RLnkCtrlOffset = 0;
 	pAd->HostLnkCtrlOffset = 0;
 	pAd->CheckDmaBusyCount = 0;
+#endif
 
 	pAd->bAutoTxAgcA = FALSE;			// Default is OFF
 	pAd->bAutoTxAgcG = FALSE;			// Default is OFF
@@ -3176,23 +3705,11 @@
 
 	NdisZeroMemory(&pAd->BeaconTxWI, sizeof(pAd->BeaconTxWI));
 
-#ifdef DOT11_N_SUPPORT
 	NdisZeroMemory(&pAd->CommonCfg.HtCapability, sizeof(pAd->CommonCfg.HtCapability));
 	pAd->HTCEnable = FALSE;
 	pAd->bBroadComHT = FALSE;
 	pAd->CommonCfg.bRdg = FALSE;
 
-#ifdef DOT11N_DRAFT3
-	pAd->CommonCfg.Dot11OBssScanPassiveDwell = dot11OBSSScanPassiveDwell;	// Unit : TU. 5~1000
-	pAd->CommonCfg.Dot11OBssScanActiveDwell = dot11OBSSScanActiveDwell;	// Unit : TU. 10~1000
-	pAd->CommonCfg.Dot11BssWidthTriggerScanInt = dot11BSSWidthTriggerScanInterval;	// Unit : Second
-	pAd->CommonCfg.Dot11OBssScanPassiveTotalPerChannel = dot11OBSSScanPassiveTotalPerChannel;	// Unit : TU. 200~10000
-	pAd->CommonCfg.Dot11OBssScanActiveTotalPerChannel = dot11OBSSScanActiveTotalPerChannel;	// Unit : TU. 20~10000
-	pAd->CommonCfg.Dot11BssWidthChanTranDelayFactor = dot11BSSWidthChannelTransactionDelayFactor;
-	pAd->CommonCfg.Dot11OBssScanActivityThre = dot11BSSScanActivityThreshold;	// Unit : percentage
-	pAd->CommonCfg.Dot11BssWidthChanTranDelay = (pAd->CommonCfg.Dot11BssWidthTriggerScanInt * pAd->CommonCfg.Dot11BssWidthChanTranDelayFactor);
-#endif  // DOT11N_DRAFT3 //
-
 	NdisZeroMemory(&pAd->CommonCfg.AddHTInfo, sizeof(pAd->CommonCfg.AddHTInfo));
 	pAd->CommonCfg.BACapability.field.MMPSmode = MMPS_ENABLE;
 	pAd->CommonCfg.BACapability.field.MpduDensity = 0;
@@ -3213,7 +3730,6 @@
 	pAd->CommonCfg.TxBASize = 7;
 
 	pAd->CommonCfg.REGBACapability.word = pAd->CommonCfg.BACapability.word;
-#endif // DOT11_N_SUPPORT //
 
 	//pAd->CommonCfg.HTPhyMode.field.BW = BW_20;
 	//pAd->CommonCfg.HTPhyMode.field.MCS = MCS_AUTO;
@@ -3230,8 +3746,6 @@
 	//
 	// part II. intialize STA specific configuration
 	//
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		RX_FILTER_SET_FLAG(pAd, fRX_FILTER_ACCEPT_DIRECT);
 		RX_FILTER_CLEAR_FLAG(pAd, fRX_FILTER_ACCEPT_MULTICAST);
@@ -3270,11 +3784,6 @@
 		pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
 	}
 
-#ifdef EXT_BUILD_CHANNEL_LIST
-	pAd->StaCfg.IEEE80211dClientMode = Rt802_11_D_None;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
-
 	// global variables mXXXX used in MAC protocol state machines
 	OPSTATUS_SET_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM);
 	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_ADHOC_ON);
@@ -3284,21 +3793,12 @@
 	pAd->CommonCfg.PhyMode = PHY_11BG_MIXED;		// default PHY mode
 	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);  // CCK use LONG preamble
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		// user desired power mode
 		pAd->StaCfg.WindowsPowerMode = Ndis802_11PowerModeCAM;
 		pAd->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeCAM;
 		pAd->StaCfg.bWindowsACCAMEnable = FALSE;
 
-#ifdef LEAP_SUPPORT
-		// CCX v1.0 releated init value
-		RTMPInitTimer(pAd, &pAd->StaCfg.LeapAuthTimer, GET_TIMER_FUNCTION(LeapAuthTimeout), pAd, FALSE);
-		pAd->StaCfg.LeapAuthMode = CISCO_AuthModeLEAPNone;
-		pAd->StaCfg.bCkipOn = FALSE;
-#endif // LEAP_SUPPORT //
-
 		RTMPInitTimer(pAd, &pAd->StaCfg.StaQuickResponeForRateUpTimer, GET_TIMER_FUNCTION(StaQuickResponeForRateUpExec), pAd, FALSE);
 		pAd->StaCfg.StaQuickResponeForRateUpTimerRunning = FALSE;
 
@@ -3326,17 +3826,11 @@
 		NdisZeroMemory(pAd->nickname, IW_ESSID_MAX_SIZE+1);
 		sprintf(pAd->nickname, "%s", STA_NIC_DEVICE_NAME);
 		RTMPInitTimer(pAd, &pAd->StaCfg.WpaDisassocAndBlockAssocTimer, GET_TIMER_FUNCTION(WpaDisassocApAndBlockAssoc), pAd, FALSE);
-#ifdef WPA_SUPPLICANT_SUPPORT
 		pAd->StaCfg.IEEE8021X = FALSE;
 		pAd->StaCfg.IEEE8021x_required_keys = FALSE;
 		pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_DISABLE;
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
 		pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_ENABLE;
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	// Default for extra information is not valid
 	pAd->ExtraInfo = EXTRA_INFO_CLEAR;
@@ -3373,41 +3867,12 @@
 	InitializeQueueHeader(&pAd->MacTab.McastPsQueue);
 	NdisAllocateSpinLock(&pAd->MacTabLock);
 
-#ifdef RALINK_ATE
-	NdisZeroMemory(&pAd->ate, sizeof(ATE_INFO));
-	pAd->ate.Mode = ATE_STOP;
-	pAd->ate.TxCount = 200;/* to exceed TX_RING_SIZE ... */
-	pAd->ate.TxLength = 1024;
-	pAd->ate.TxWI.ShortGI = 0;// LONG GI : 800 ns
-	pAd->ate.TxWI.PHYMODE = MODE_CCK;
-	pAd->ate.TxWI.MCS = 3;
-	pAd->ate.TxWI.BW = BW_20;
-	pAd->ate.Channel = 1;
-	pAd->ate.QID = QID_AC_BE;
-	pAd->ate.Addr1[0] = 0x00;
-	pAd->ate.Addr1[1] = 0x11;
-	pAd->ate.Addr1[2] = 0x22;
-	pAd->ate.Addr1[3] = 0xAA;
-	pAd->ate.Addr1[4] = 0xBB;
-	pAd->ate.Addr1[5] = 0xCC;
-	NdisMoveMemory(pAd->ate.Addr2, pAd->ate.Addr1, ETH_LENGTH_OF_ADDRESS);
-	NdisMoveMemory(pAd->ate.Addr3, pAd->ate.Addr1, ETH_LENGTH_OF_ADDRESS);
-	pAd->ate.bRxFer = 0;
-	pAd->ate.bQATxStart = FALSE;
-	pAd->ate.bQARxStart = FALSE;
-	pAd->ate.bFWLoading = FALSE;
-#ifdef RALINK_28xx_QA
-	//pAd->ate.Repeat = 0;
-	pAd->ate.TxStatus = 0;
-	pAd->ate.AtePid = THREAD_PID_INIT_VALUE;
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-
 	pAd->CommonCfg.bWiFiTest = FALSE;
+#ifdef RT2860
 	pAd->bPCIclkOff = FALSE;
 
 	RTMP_SET_PSFLAG(pAd, fRTMP_PS_CAN_GO_SLEEP);
+#endif
 	DBGPRINT(RT_DEBUG_TRACE, ("<-- UserCfgInit\n"));
 }
 
@@ -3509,6 +3974,9 @@
 	pTimer->State      = FALSE;
 	pTimer->cookie = (ULONG) pData;
 
+#ifdef RT2870
+	pTimer->pAd = pAd;
+#endif // RT2870 //
 
 	RTMP_OS_Init_Timer(pAd,	&pTimer->TimerObj,	pTimerFunc, (PVOID) pTimer);
 }
@@ -3635,6 +4103,12 @@
 		if (*pCancelled == TRUE)
 			pTimer->State = TRUE;
 
+#ifdef RT2870
+		// We need to go-through the TimerQ to findout this timer handler and remove it if
+		//		it's still waiting for execution.
+
+		RT2870_TimerQ_Remove(pTimer->pAd, pTimer);
+#endif // RT2870 //
 	}
 	else
 	{
@@ -3674,13 +4148,6 @@
 	UCHAR			HighByte = 0;
 	UCHAR			LowByte;
 
-// In ATE mode of RT2860 AP/STA, we have erased 8051 firmware.
-// So LED mode is not supported when ATE is running.
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
 	LowByte = pAd->LedCntl.field.LedMode&0x7f;
 	switch (Status)
 	{
diff --git a/drivers/staging/rt2860/common/rtmp_tkip.c b/drivers/staging/rt2860/common/rtmp_tkip.c
index a87ea3a..4a7fda6 100644
--- a/drivers/staging/rt2860/common/rtmp_tkip.c
+++ b/drivers/staging/rt2860/common/rtmp_tkip.c
@@ -199,15 +199,9 @@
 			{
 				struct PACKED
 				{
-#ifdef RT_BIG_ENDIAN
-					UCHAR	KeyID:2;
-					UCHAR	ExtIV:1;
-					UCHAR	Rsvd:5;
-#else
 					UCHAR	Rsvd:5;
 					UCHAR	ExtIV:1;
 					UCHAR	KeyID:2;
-#endif
 				}	field;
 				UCHAR		Byte;
 			}	CONTROL;
@@ -1114,10 +1108,6 @@
 	UCHAR			MIC[8];
 	UCHAR			TrailMIC[8];
 
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
-
 	fc0 = *pData;
 	fc1 = *(pData + 1);
 
@@ -1224,9 +1214,6 @@
 		return (FALSE);
 	}
 
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
 	return TRUE;
 }
 
@@ -1266,10 +1253,6 @@
 	UCHAR			MIC[8];
 	UCHAR			TrailMIC[8];
 
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
-
 	fc0 = *pData;
 	fc1 = *(pData + 1);
 
@@ -1437,10 +1420,6 @@
 		return FALSE;
 	}
 
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
-
 	return TRUE;
 }
 
diff --git a/drivers/staging/rt2860/common/rtmp_wep.c b/drivers/staging/rt2860/common/rtmp_wep.c
index ffe26c2..8e833e7 100644
--- a/drivers/staging/rt2860/common/rtmp_wep.c
+++ b/drivers/staging/rt2860/common/rtmp_wep.c
@@ -144,14 +144,12 @@
 
 	pAd->PrivateInfo.FCSCRC32 = PPPINITFCS32;   //Init crc32.
 
-#ifdef CONFIG_STA_SUPPORT
     if (pAd->StaCfg.bCkipOn && (pAd->StaCfg.CkipFlag & 0x10) && (pAd->OpMode == OPMODE_STA))
     {
         ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, pKey, KeyLen);  //INIT SBOX, KEYLEN+3(IV)
         NdisMoveMemory(pDest, pKey, 3);  //Append Init Vector
     }
     else
-#endif // CONFIG_STA_SUPPORT //
     {
 		NdisMoveMemory(WEPKEY + 3, pKey, KeyLen);
 
diff --git a/drivers/staging/rt2860/common/spectrum.c b/drivers/staging/rt2860/common/spectrum.c
index b3650ec..101c292 100644
--- a/drivers/staging/rt2860/common/spectrum.c
+++ b/drivers/staging/rt2860/common/spectrum.c
@@ -1060,27 +1060,6 @@
 	IN UINT8 ChSwMode,
 	IN UINT8 Channel)
 {
-#ifdef WDS_SUPPORT
-	if (!((pRA[0] & 0xff) == 0xff)) // is pRA a broadcase address.
-	{
-		INT i;
-		// info neighbor APs that Radar signal found throgh WDS link.
-		for (i = 0; i < MAX_WDS_ENTRY; i++)
-		{
-			if (ValidWdsEntry(pAd, i))
-			{
-				PUCHAR pDA = pAd->WdsTab.WdsEntry[i].PeerWdsAddr;
-
-				// DA equal to SA. have no necessary orignal AP which found Radar signal.
-				if (MAC_ADDR_EQUAL(pTA, pDA))
-					continue;
-
-				// send Channel Switch Action frame to info Neighbro APs.
-				EnqueueChSwAnn(pAd, pDA, ChSwMode, Channel);
-			}
-		}
-	}
-#endif // WDS_SUPPORT //
 }
 
 static VOID StartDFSProcedure(
@@ -1090,9 +1069,9 @@
 {
 	// start DFS procedure
 	pAd->CommonCfg.Channel = Channel;
-#ifdef DOT11_N_SUPPORT
+
 	N_ChannelCheck(pAd);
-#endif // DOT11_N_SUPPORT //
+
 	pAd->CommonCfg.RadarDetect.RDMode = RD_SWITCHING_MODE;
 	pAd->CommonCfg.RadarDetect.CSCount = 0;
 }
@@ -1475,10 +1454,8 @@
 {
 	CH_SW_ANN_INFO ChSwAnnInfo;
 	PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
-#ifdef CONFIG_STA_SUPPORT
 	UCHAR index = 0, Channel = 0, NewChannel = 0;
 	ULONG Bssidx = 0;
-#endif // CONFIG_STA_SUPPORT //
 
 	NdisZeroMemory(&ChSwAnnInfo, sizeof(CH_SW_ANN_INFO));
 	if (! PeerChSwAnnSanity(pAd, Elem->Msg, Elem->MsgLen, &ChSwAnnInfo))
@@ -1487,8 +1464,6 @@
 		return;
 	}
 
-
-#ifdef CONFIG_STA_SUPPORT
 	if (pAd->OpMode == OPMODE_STA)
 	{
 		Bssidx = BssTableSearch(&pAd->ScanTab, pFr->Hdr.Addr3, pAd->CommonCfg.Channel);
@@ -1535,7 +1510,6 @@
 			}
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	return;
 }
@@ -1596,7 +1570,12 @@
 
 	if ((pMeasureReportInfo = kmalloc(sizeof(MEASURE_RPI_REPORT), GFP_ATOMIC)) == NULL)
 	{
+#ifndef RT30xx
 		DBGPRINT(RT_DEBUG_ERROR, ("%s unable to alloc memory for measure report buffer (size=%zu).\n", __func__, sizeof(MEASURE_RPI_REPORT)));
+#endif
+#ifdef RT30xx
+		DBGPRINT(RT_DEBUG_ERROR, ("%s unable to alloc memory for measure report buffer (size=%d).\n", __func__, sizeof(MEASURE_RPI_REPORT)));
+#endif
 		return;
 	}
 
@@ -1756,28 +1735,6 @@
 
 		case SPEC_CHANNEL_SWITCH:
 {
-#ifdef DOT11N_DRAFT3
-				SEC_CHA_OFFSET_IE	Secondary;
-				CHA_SWITCH_ANNOUNCE_IE	ChannelSwitch;
-
-				// 802.11h only has Channel Switch Announcement IE.
-				RTMPMoveMemory(&ChannelSwitch, &Elem->Msg[LENGTH_802_11+4], sizeof (CHA_SWITCH_ANNOUNCE_IE));
-
-				// 802.11n D3.03 adds secondary channel offset element in the end.
-				if (Elem->MsgLen ==  (LENGTH_802_11 + 2 + sizeof (CHA_SWITCH_ANNOUNCE_IE) + sizeof (SEC_CHA_OFFSET_IE)))
-				{
-					RTMPMoveMemory(&Secondary, &Elem->Msg[LENGTH_802_11+9], sizeof (SEC_CHA_OFFSET_IE));
-				}
-				else
-				{
-					Secondary.SecondaryChannelOffset = 0;
-				}
-
-				if ((Elem->Msg[LENGTH_802_11+2] == IE_CHANNEL_SWITCH_ANNOUNCEMENT) && (Elem->Msg[LENGTH_802_11+3] == 3))
-				{
-					ChannelSwitchAction(pAd, Elem->Wcid, ChannelSwitch.NewChannel, Secondary.SecondaryChannelOffset);
-				}
-#endif // DOT11N_DRAFT3 //
 }
 			PeerChSwAnnAction(pAd, Elem);
 			break;
diff --git a/drivers/staging/rt2860/leap.h b/drivers/staging/rt2860/leap.h
deleted file mode 100644
index 6818c1f..0000000
--- a/drivers/staging/rt2860/leap.h
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	leap.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-*/
-#ifndef __LEAP_H__
-#define __LEAP_H__
-
-// Messages for Associate state machine
-#define LEAP_MACHINE_BASE                   30
-
-#define LEAP_MSG_REQUEST_IDENTITY           31
-#define LEAP_MSG_REQUEST_LEAP               32
-#define LEAP_MSG_SUCCESS                    33
-#define LEAP_MSG_FAILED                     34
-#define LEAP_MSG_RESPONSE_LEAP              35
-#define LEAP_MSG_EAPOLKEY                   36
-#define LEAP_MSG_UNKNOWN                    37
-#define LEAP_MSG                            38
-//! assoc state-machine states
-#define LEAP_IDLE                           0
-#define LEAP_WAIT_IDENTITY_REQUEST          1
-#define LEAP_WAIT_CHANLLENGE_REQUEST        2
-#define LEAP_WAIT_SUCCESS                   3
-#define LEAP_WAIT_CHANLLENGE_RESPONSE       4
-#define LEAP_WAIT_EAPOLKEY                  5
-
-#define LEAP_REASON_INVALID_AUTH                    0x01
-#define LEAP_REASON_AUTH_TIMEOUT                    0x02
-#define LEAP_REASON_CHALLENGE_FROM_AP_FAILED        0x03
-#define LEAP_REASON_CHALLENGE_TO_AP_FAILED          0x04
-
-#define CISCO_AuthModeLEAP                          0x80
-#define CISCO_AuthModeLEAPNone                      0x00
-#define LEAP_AUTH_TIMEOUT                           30000
-#define LEAP_CHALLENGE_RESPONSE_LENGTH              24
-#define LEAP_CHALLENGE_REQUEST_LENGTH               8
-
-typedef struct _LEAP_EAPOL_HEADER_ {
-    UCHAR       Version;
-    UCHAR       Type;
-    UCHAR       Length[2];
-} LEAP_EAPOL_HEADER, *PLEAP_EAPOL_HEADER;
-
-typedef struct _LEAP_EAPOL_PACKET_ {
-    UCHAR       Code;
-    UCHAR       Identifier;
-    UCHAR       Length[2];
-    UCHAR       Type;
-} LEAP_EAPOL_PACKET, *PLEAP_EAPOL_PACKET;
-
-typedef struct _LEAP_EAP_CONTENTS_ {
-    UCHAR       Version;
-    UCHAR       Reserved;
-    UCHAR       Length;
-} LEAP_EAP_CONTENTS, *PLEAP_EAP_CONTENTS;
-
-/*** EAPOL key ***/
-typedef struct _EAPOL_KEY_HEADER_ {
-    UCHAR       Type;
-    UCHAR       Length[2];
-    UCHAR       Counter[8];
-    UCHAR       IV[16];
-    UCHAR       Index;
-    UCHAR       Signature[16];
-} EAPOL_KEY_HEADER, *PEAPOL_KEY_HEADER;
-
-BOOLEAN LeapMsgTypeSubst(
-    IN  UCHAR   EAPType,
-    OUT ULONG   *MsgType);
-
-VOID LeapMachinePerformAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN STATE_MACHINE    *S,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapMacHeaderInit(
-    IN  PRTMP_ADAPTER       pAd,
-    IN  OUT PHEADER_802_11  pHdr80211,
-    IN  UCHAR               wep,
-    IN  PUCHAR              pAddr3);
-
-VOID LeapStartAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapIdentityAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapPeerChallengeAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID HashPwd(
-    IN  PUCHAR  pwd,
-    IN  INT     pwdlen,
-    OUT PUCHAR  hash);
-
-VOID PeerChallengeResponse(
-    IN  PUCHAR  szChallenge,
-    IN  PUCHAR  smbPasswd,
-    OUT PUCHAR  szResponse);
-
-VOID ParityKey(
-    OUT PUCHAR  szOut,
-    IN  PUCHAR  szIn);
-
-VOID DesKey(
-    OUT ULONG   k[16][2],
-    IN  PUCHAR  key,
-    IN  INT     decrypt);
-
-VOID Des(
-    IN  ULONG   ks[16][2],
-    OUT UCHAR   block[8]);
-
-VOID DesEncrypt(
-    IN  PUCHAR  szClear,
-    IN  PUCHAR  szKey,
-    OUT PUCHAR  szOut);
-
-VOID LeapNetworkChallengeAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapNetworkChallengeResponse(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID HashpwdHash(
-    IN  PUCHAR  hash,
-    IN  PUCHAR  hashhash);
-
-VOID ProcessSessionKey(
-    OUT PUCHAR  SessionKey,
-    IN  PUCHAR  hash2,
-    IN  PUCHAR  ChallengeToRadius,
-    IN  PUCHAR  ChallengeResponseFromRadius,
-    IN  PUCHAR  ChallengeFromRadius,
-    IN  PUCHAR  ChallengeResponseToRadius);
-
-VOID LeapEapolKeyAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID RogueApTableInit(
-    IN ROGUEAP_TABLE    *Tab);
-
-ULONG RogueApTableSearch(
-    IN ROGUEAP_TABLE    *Tab,
-    IN PUCHAR           pAddr);
-
-VOID RogueApEntrySet(
-    IN  PRTMP_ADAPTER   pAd,
-    OUT ROGUEAP_ENTRY   *pRogueAp,
-    IN PUCHAR           pAddr,
-    IN UCHAR            FaileCode);
-
-ULONG RogueApTableSetEntry(
-    IN  PRTMP_ADAPTER   pAd,
-    OUT ROGUEAP_TABLE  *Tab,
-    IN PUCHAR           pAddr,
-    IN UCHAR            FaileCode);
-
-VOID RogueApTableDeleteEntry(
-    IN OUT ROGUEAP_TABLE *Tab,
-    IN PUCHAR          pAddr);
-
-VOID LeapAuthTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-VOID LeapSendRogueAPReport(
-    IN  PRTMP_ADAPTER   pAd);
-
-BOOLEAN CCKMAssocRspSanity(
-    IN PRTMP_ADAPTER    pAd,
-    IN VOID             *Msg,
-    IN ULONG            MsgLen);
-
-#endif  // __LEAP_H__
diff --git a/drivers/staging/rt2860/mlme.h b/drivers/staging/rt2860/mlme.h
index 5cb6165..3d1a828 100644
--- a/drivers/staging/rt2860/mlme.h
+++ b/drivers/staging/rt2860/mlme.h
@@ -73,17 +73,7 @@
 #define MAX_CHANNEL_TIME            140       // unit: msec, for single band scan
 #define	FAST_ACTIVE_SCAN_TIME	    30 		  // Active scan waiting for probe response time
 #define CW_MIN_IN_BITS              4         // actual CwMin = 2^CW_MIN_IN_BITS - 1
-
-
-#ifdef CONFIG_STA_SUPPORT
-#ifndef CONFIG_AP_SUPPORT
 #define CW_MAX_IN_BITS              10        // actual CwMax = 2^CW_MAX_IN_BITS - 1
-#endif
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-extern UINT32 CW_MAX_IN_BITS;
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
 
 // Note: RSSI_TO_DBM_OFFSET has been changed to variable for new RF (2004-0720).
 // SHould not refer to this constant anymore
@@ -115,10 +105,7 @@
 
 #define BSS_NOT_FOUND                    0xFFFFFFFF
 
-
-#ifdef CONFIG_STA_SUPPORT
 #define MAX_LEN_OF_MLME_QUEUE            40 //10
-#endif // CONFIG_STA_SUPPORT //
 
 #define SCAN_PASSIVE                     18		// scan with no probe request, only wait beacon and probe response
 #define SCAN_ACTIVE                      19		// scan with probe request, and wait beacon and probe response
@@ -128,10 +115,6 @@
 #define	SCAN_CISCO_CHANNEL_LOAD			 23		// Single channel passive scan for channel load collection
 #define FAST_SCAN_ACTIVE                 24		// scan with probe request, and wait beacon and probe response
 
-#ifdef DOT11N_DRAFT3
-#define SCAN_2040_BSS_COEXIST                  26
-#endif // DOT11N_DRAFT3 //
-
 #define MAC_ADDR_IS_GROUP(Addr)       (((Addr[0]) & 0x01))
 #define MAC_ADDR_HASH(Addr)            (Addr[0] ^ Addr[1] ^ Addr[2] ^ Addr[3] ^ Addr[4] ^ Addr[5])
 #define MAC_ADDR_HASH_INDEX(Addr)      (MAC_ADDR_HASH(Addr) % HASH_TABLE_SIZE)
@@ -204,22 +187,6 @@
 //
 //  HT Capability INFO field in HT Cap IE .
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	USHORT	LSIGTxopProSup:1;
-	USHORT	Forty_Mhz_Intolerant:1;
-	USHORT	PSMP:1;
-	USHORT	CCKmodein40:1;
-	USHORT	AMsduSize:1;
-	USHORT	DelayedBA:1;	//rt2860c not support
-	USHORT	RxSTBC:2;
-	USHORT	TxSTBC:1;
-	USHORT	ShortGIfor40:1;	//for40MHz
-	USHORT	ShortGIfor20:1;
-	USHORT	GF:1;	//green field
-	USHORT	MimoPs:2;//momi power safe
-	USHORT	ChannelWidth:1;
-	USHORT	AdvCoding:1;
-#else
 	USHORT	AdvCoding:1;
 	USHORT	ChannelWidth:1;
 	USHORT	MimoPs:2;//momi power safe
@@ -234,53 +201,29 @@
 	USHORT	PSMP:1;
 	USHORT	Forty_Mhz_Intolerant:1;
 	USHORT	LSIGTxopProSup:1;
-#endif	/* !RT_BIG_ENDIAN */
 } HT_CAP_INFO, *PHT_CAP_INFO;
 
 //  HT Capability INFO field in HT Cap IE .
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:3;//momi power safe
-	UCHAR	MpduDensity:3;
-	UCHAR	MaxRAmpduFactor:2;
-#else
 	UCHAR	MaxRAmpduFactor:2;
 	UCHAR	MpduDensity:3;
 	UCHAR	rsv:3;//momi power safe
-#endif /* !RT_BIG_ENDIAN */
 } HT_CAP_PARM, *PHT_CAP_PARM;
 
 //  HT Capability INFO field in HT Cap IE .
 typedef struct PACKED {
 	UCHAR	MCSSet[10];
 	UCHAR	SupRate[2];  // unit : 1Mbps
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:3;
-	UCHAR	MpduDensity:1;
-	UCHAR	TxStream:2;
-	UCHAR	TxRxNotEqual:1;
-	UCHAR	TxMCSSetDefined:1;
-#else
 	UCHAR	TxMCSSetDefined:1;
 	UCHAR	TxRxNotEqual:1;
 	UCHAR	TxStream:2;
 	UCHAR	MpduDensity:1;
 	UCHAR	rsv:3;
-#endif // RT_BIG_ENDIAN //
 	UCHAR	rsv3[3];
 } HT_MCS_SET, *PHT_MCS_SET;
 
 //  HT Capability INFO field in HT Cap IE .
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv2:4;
-	USHORT	RDGSupport:1;	//reverse Direction Grant  support
-	USHORT	PlusHTC:1;	//+HTC control field support
-	USHORT	MCSFeedback:2;	//0:no MCS feedback, 2:unsolicited MCS feedback, 3:Full MCS feedback,  1:rsv.
-	USHORT	rsv:5;//momi power safe
-	USHORT	TranTime:2;
-	USHORT	Pco:1;
-#else
 	USHORT	Pco:1;
 	USHORT	TranTime:2;
 	USHORT	rsv:5;//momi power safe
@@ -288,33 +231,10 @@
 	USHORT	PlusHTC:1;	//+HTC control field support
 	USHORT	RDGSupport:1;	//reverse Direction Grant  support
 	USHORT	rsv2:4;
-#endif /* RT_BIG_ENDIAN */
 } EXT_HT_CAP_INFO, *PEXT_HT_CAP_INFO;
 
 //  HT Beamforming field in HT Cap IE .
 typedef struct PACKED _HT_BF_CAP{
-#ifdef RT_BIG_ENDIAN
-	ULONG	rsv:3;
-	ULONG	ChanEstimation:2;
-	ULONG	CSIRowBFSup:2;
-	ULONG	ComSteerBFAntSup:2;
-	ULONG	NoComSteerBFAntSup:2;
-	ULONG	CSIBFAntSup:2;
-	ULONG	MinGrouping:2;
-	ULONG	ExpComBF:2;
-	ULONG	ExpNoComBF:2;
-	ULONG	ExpCSIFbk:2;
-	ULONG	ExpComSteerCapable:1;
-	ULONG	ExpNoComSteerCapable:1;
-	ULONG	ExpCSICapable:1;
-	ULONG	Calibration:2;
-	ULONG	ImpTxBFCapable:1;
-	ULONG	TxNDPCapable:1;
-	ULONG	RxNDPCapable:1;
-	ULONG	TxSoundCapable:1;
-	ULONG	RxSoundCapable:1;
-	ULONG	TxBFRecCapable:1;
-#else
 	ULONG	TxBFRecCapable:1;
 	ULONG	RxSoundCapable:1;
 	ULONG	TxSoundCapable:1;
@@ -335,21 +255,10 @@
 	ULONG	CSIRowBFSup:2;
 	ULONG	ChanEstimation:2;
 	ULONG	rsv:3;
-#endif // RT_BIG_ENDIAN //
 } HT_BF_CAP, *PHT_BF_CAP;
 
 //  HT antenna selection field in HT Cap IE .
 typedef struct PACKED _HT_AS_CAP{
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:1;
-	UCHAR	TxSoundPPDU:1;
-	UCHAR	RxASel:1;
-	UCHAR	AntIndFbk:1;
-	UCHAR	ExpCSIFbk:1;
-	UCHAR	AntIndFbkTxASEL:1;
-	UCHAR	ExpCSIFbkTxASEL:1;
-	UCHAR	AntSelect:1;
-#else
 	UCHAR	AntSelect:1;
 	UCHAR	ExpCSIFbkTxASEL:1;
 	UCHAR	AntIndFbkTxASEL:1;
@@ -358,7 +267,6 @@
 	UCHAR	RxASel:1;
 	UCHAR	TxSoundPPDU:1;
 	UCHAR	rsv:1;
-#endif // RT_BIG_ENDIAN //
 } HT_AS_CAP, *PHT_AS_CAP;
 
 // Draft 1.0 set IE length 26, but is extensible..
@@ -402,17 +310,10 @@
 //  7.3.2.56. 20/40 Coexistence element used in  Element ID = 72 = IE_2040_BSS_COEXIST
 typedef union PACKED _BSS_2040_COEXIST_IE{
  struct PACKED {
- #ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:5;
-	UCHAR	BSS20WidthReq:1;
-	UCHAR	Intolerant40:1;
-	UCHAR	InfoReq:1;
- #else
 	UCHAR	InfoReq:1;
 	UCHAR	Intolerant40:1;			// Inter-BSS. set 1 when prohibits a receiving BSS from operating as a 20/40 Mhz BSS.
 	UCHAR	BSS20WidthReq:1;		// Intra-BSS set 1 when prohibits a receiving AP from operating its BSS as a 20/40MHz BSS.
 	UCHAR	rsv:5;
-#endif // RT_BIG_ENDIAN //
     } field;
  UCHAR   word;
 } BSS_2040_COEXIST_IE, *PBSS_2040_COEXIST_IE;
@@ -438,17 +339,10 @@
 // 7.3.27 20/40 Bss Coexistence Mgmt capability used in extended capabilities information IE( ID = 127 = IE_EXT_CAPABILITY).
 //	This is the first octet and was defined in 802.11n D3.03 and 802.11yD9.0
 typedef struct PACKED _EXT_CAP_INFO_ELEMENT{
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv2:5;
-	UCHAR	ExtendChannelSwitch:1;
-	UCHAR	rsv:1;
-	UCHAR	BssCoexistMgmtSupport:1;
-#else
 	UCHAR	BssCoexistMgmtSupport:1;
 	UCHAR	rsv:1;
 	UCHAR	ExtendChannelSwitch:1;
 	UCHAR	rsv2:5;
-#endif // RT_BIG_ENDIAN //
 }EXT_CAP_INFO_ELEMENT, *PEXT_CAP_INFO_ELEMENT;
 
 
@@ -494,18 +388,6 @@
 //This structure substracts ralink supports from all 802.11n-related features.
 //Features not listed here but contained in 802.11n spec are not supported in rt2860.
 typedef struct {
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv:5;
-	USHORT	AmsduSize:1;	// Max receiving A-MSDU size
-	USHORT	AmsduEnable:1;	// Enable to transmit A-MSDU. Suggest disable. We should use A-MPDU to gain best benifit of 802.11n
-	USHORT	RxSTBC:2;	// 2 bits
-	USHORT	TxSTBC:1;
-	USHORT	ShortGIfor40:1;	//for40MHz
-	USHORT	ShortGIfor20:1;
-	USHORT	GF:1;	//green field
-	USHORT	MimoPs:2;//mimo power safe MMPS_
-	USHORT	ChannelWidth:1;
-#else
 	USHORT	ChannelWidth:1;
 	USHORT	MimoPs:2;//mimo power safe MMPS_
 	USHORT	GF:1;	//green field
@@ -516,34 +398,18 @@
 	USHORT	AmsduEnable:1;	// Enable to transmit A-MSDU. Suggest disable. We should use A-MPDU to gain best benifit of 802.11n
 	USHORT	AmsduSize:1;	// Max receiving A-MSDU size
 	USHORT	rsv:5;
-#endif
 
 	//Substract from Addiont HT INFO IE
-#ifdef RT_BIG_ENDIAN
-	UCHAR	RecomWidth:1;
-	UCHAR	ExtChanOffset:2;	// Please not the difference with following 	UCHAR	NewExtChannelOffset; from 802.11n
-	UCHAR	MpduDensity:3;
-	UCHAR	MaxRAmpduFactor:2;
-#else
 	UCHAR	MaxRAmpduFactor:2;
 	UCHAR	MpduDensity:3;
 	UCHAR	ExtChanOffset:2;	// Please not the difference with following 	UCHAR	NewExtChannelOffset; from 802.11n
 	UCHAR	RecomWidth:1;
-#endif
 
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv2:11;
-	USHORT	OBSS_NonHTExist:1;
-	USHORT	rsv3:1;
-	USHORT	NonGfPresent:1;
-	USHORT	OperaionMode:2;
-#else
 	USHORT	OperaionMode:2;
 	USHORT	NonGfPresent:1;
 	USHORT	rsv3:1;
 	USHORT	OBSS_NonHTExist:1;
 	USHORT	rsv2:11;
-#endif
 
 	// New Extension Channel Offset IE
 	UCHAR	NewExtChannelOffset;
@@ -553,50 +419,24 @@
 
 //   field in Addtional HT Information IE .
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR	SerInterGranu:3;
-	UCHAR	S_PSMPSup:1;
-	UCHAR	RifsMode:1;
-	UCHAR	RecomWidth:1;
-	UCHAR	ExtChanOffset:2;
-#else
 	UCHAR	ExtChanOffset:2;
 	UCHAR	RecomWidth:1;
 	UCHAR	RifsMode:1;
 	UCHAR	S_PSMPSup:1;	 //Indicate support for scheduled PSMP
 	UCHAR	SerInterGranu:3;	 //service interval granularity
-#endif
 } ADD_HTINFO, *PADD_HTINFO;
 
 typedef struct PACKED{
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv2:11;
-	USHORT	OBSS_NonHTExist:1;
-	USHORT	rsv:1;
-	USHORT	NonGfPresent:1;
-	USHORT	OperaionMode:2;
-#else
 	USHORT	OperaionMode:2;
 	USHORT	NonGfPresent:1;
 	USHORT	rsv:1;
 	USHORT	OBSS_NonHTExist:1;
 	USHORT	rsv2:11;
-#endif
 } ADD_HTINFO2, *PADD_HTINFO2;
 
 
 // TODO: Need sync with spec about the definition of StbcMcs. In Draft 3.03, it's reserved.
 typedef struct PACKED{
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv:4;
-	USHORT	PcoPhase:1;
-	USHORT	PcoActive:1;
-	USHORT	LsigTxopProt:1;
-	USHORT	STBCBeacon:1;
-	USHORT	DualCTSProtect:1;
-	USHORT	DualBeacon:1;
-	USHORT	StbcMcs:6;
-#else
 	USHORT	StbcMcs:6;
 	USHORT	DualBeacon:1;
 	USHORT	DualCTSProtect:1;
@@ -605,7 +445,6 @@
 	USHORT	PcoActive:1;
 	USHORT	PcoPhase:1;
 	USHORT	rsv:4;
-#endif // RT_BIG_ENDIAN //
 } ADD_HTINFO3, *PADD_HTINFO3;
 
 #define SIZE_ADD_HT_INFO_IE		22
@@ -624,22 +463,6 @@
 
 // 4-byte HTC field.  maybe included in any frame except non-QOS data frame.  The Order bit must set 1.
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    UINT32		RDG:1;	//RDG / More PPDU
-    UINT32		ACConstraint:1;	//feedback request
-    UINT32		rsv:5;  //calibration sequence
-    UINT32		ZLFAnnouce:1;	// ZLF announcement
-    UINT32		CSISTEERING:2;	//CSI/ STEERING
-    UINT32		FBKReq:2;	//feedback request
-    UINT32		CalSeq:2;  //calibration sequence
-    UINT32		CalPos:2;	// calibration position
-    UINT32		MFBorASC:7;	//Link adaptation feedback containing recommended MCS. 0x7f for no feedback or not available
-    UINT32		MFS:3;	//SET to the received value of MRS. 0x111 for unsolicited MFB.
-    UINT32		MRSorASI:3;	// MRQ Sequence identifier. unchanged during entire procedure. 0x000-0x110.
-    UINT32		MRQ:1;	//MCS feedback. Request for a MCS feedback
-    UINT32		TRQ:1;	//sounding request
-    UINT32		MA:1;	//management action payload exist in (QoS Null+HTC)
-#else
     UINT32		MA:1;	//management action payload exist in (QoS Null+HTC)
     UINT32		TRQ:1;	//sounding request
     UINT32		MRQ:1;	//MCS feedback. Request for a MCS feedback
@@ -654,41 +477,19 @@
     UINT32		rsv:5;  //calibration sequence
     UINT32		ACConstraint:1;	//feedback request
     UINT32		RDG:1;	//RDG / More PPDU
-#endif /* !RT_BIG_ENDIAN */
 } HT_CONTROL, *PHT_CONTROL;
 
 // 2-byte QOS CONTROL field
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      Txop_QueueSize:8;
-    USHORT      AMsduPresent:1;
-    USHORT      AckPolicy:2;  //0: normal ACK 1:No ACK 2:scheduled under MTBA/PSMP  3: BA
-    USHORT      EOSP:1;
-    USHORT      TID:4;
-#else
     USHORT      TID:4;
     USHORT      EOSP:1;
     USHORT      AckPolicy:2;  //0: normal ACK 1:No ACK 2:scheduled under MTBA/PSMP  3: BA
     USHORT      AMsduPresent:1;
     USHORT      Txop_QueueSize:8;
-#endif /* !RT_BIG_ENDIAN */
 } QOS_CONTROL, *PQOS_CONTROL;
 
 // 2-byte Frame control field
 typedef	struct	PACKED {
-#ifdef RT_BIG_ENDIAN
-	USHORT		Order:1;			// Strict order expected
-	USHORT		Wep:1;				// Wep data
-	USHORT		MoreData:1;			// More data bit
-	USHORT		PwrMgmt:1;			// Power management bit
-	USHORT		Retry:1;			// Retry status bit
-	USHORT		MoreFrag:1;			// More fragment bit
-	USHORT		FrDs:1;				// From DS indication
-	USHORT		ToDs:1;				// To DS indication
-	USHORT		SubType:4;			// MSDU subtype
-	USHORT		Type:2;				// MSDU type
-	USHORT		Ver:2;				// Protocol version
-#else
 	USHORT		Ver:2;				// Protocol version
 	USHORT		Type:2;				// MSDU type
 	USHORT		SubType:4;			// MSDU subtype
@@ -700,7 +501,6 @@
 	USHORT		MoreData:1;			// More data bit
 	USHORT		Wep:1;				// Wep data
 	USHORT		Order:1;			// Strict order expected
-#endif /* !RT_BIG_ENDIAN */
 } FRAME_CONTROL, *PFRAME_CONTROL;
 
 typedef	struct	PACKED _HEADER_802_11	{
@@ -709,13 +509,8 @@
     UCHAR           Addr1[MAC_ADDR_LEN];
     UCHAR           Addr2[MAC_ADDR_LEN];
 	UCHAR			Addr3[MAC_ADDR_LEN];
-#ifdef RT_BIG_ENDIAN
-	USHORT			Sequence:12;
-	USHORT			Frag:4;
-#else
 	USHORT			Frag:4;
 	USHORT			Sequence:12;
-#endif /* !RT_BIG_ENDIAN */
 	UCHAR			Octet[0];
 }	HEADER_802_11, *PHEADER_802_11;
 
@@ -739,42 +534,24 @@
 ////Block ACK related format
 // 2-byte BA Parameter  field  in 	DELBA frames to terminate an already set up bA
 typedef struct PACKED{
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;	// value of TC os TS
-    USHORT      Initiator:1;	// 1: originator    0:recipient
-    USHORT      Rsv:11;	// always set to 0
-#else
     USHORT      Rsv:11;	// always set to 0
     USHORT      Initiator:1;	// 1: originator    0:recipient
     USHORT      TID:4;	// value of TC os TS
-#endif /* !RT_BIG_ENDIAN */
 } DELBA_PARM, *PDELBA_PARM;
 
 // 2-byte BA Parameter Set field  in ADDBA frames to signal parm for setting up a BA
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      BufSize:10;	// number of buffe of size 2304 octetsr
-    USHORT      TID:4;	// value of TC os TS
-    USHORT      BAPolicy:1;	// 1: immediately BA    0:delayed BA
-    USHORT      AMSDUSupported:1;	// 0: not permitted		1: permitted
-#else
     USHORT      AMSDUSupported:1;	// 0: not permitted		1: permitted
     USHORT      BAPolicy:1;	// 1: immediately BA    0:delayed BA
     USHORT      TID:4;	// value of TC os TS
     USHORT      BufSize:10;	// number of buffe of size 2304 octetsr
-#endif /* !RT_BIG_ENDIAN */
 } BA_PARM, *PBA_PARM;
 
 // 2-byte BA Starting Seq CONTROL field
 typedef union PACKED {
     struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      StartSeq:12;   // sequence number of the 1st MSDU for which this BAR is sent
-	USHORT      FragNum:4;	// always set to 0
-#else
     USHORT      FragNum:4;	// always set to 0
 	USHORT      StartSeq:12;   // sequence number of the 1st MSDU for which this BAR is sent
-#endif /* RT_BIG_ENDIAN */
     }   field;
     USHORT           word;
 } BASEQ_CONTROL, *PBASEQ_CONTROL;
@@ -782,63 +559,34 @@
 //BAControl and BARControl are the same
 // 2-byte BA CONTROL field in BA frame
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;
-    USHORT      Rsv:9;
-    USHORT      Compressed:1;
-    USHORT      MTID:1;		//EWC V1.24
-    USHORT      ACKPolicy:1; // only related to N-Delayed BA. But not support in RT2860b. 0:NormalACK  1:No ACK
-#else
     USHORT      ACKPolicy:1; // only related to N-Delayed BA. But not support in RT2860b. 0:NormalACK  1:No ACK
     USHORT      MTID:1;		//EWC V1.24
     USHORT      Compressed:1;
     USHORT      Rsv:9;
     USHORT      TID:4;
-#endif /* !RT_BIG_ENDIAN */
 } BA_CONTROL, *PBA_CONTROL;
 
 // 2-byte BAR CONTROL field in BAR frame
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;
-    USHORT      Rsv1:9;
-    USHORT      Compressed:1;
-    USHORT      MTID:1;		//if this bit1, use  FRAME_MTBA_REQ,  if 0, use FRAME_BA_REQ
-    USHORT      ACKPolicy:1;
-#else
     USHORT      ACKPolicy:1; // 0:normal ack,  1:no ack.
     USHORT      MTID:1;		//if this bit1, use  FRAME_MTBA_REQ,  if 0, use FRAME_BA_REQ
     USHORT      Compressed:1;
     USHORT      Rsv1:9;
     USHORT      TID:4;
-#endif /* !RT_BIG_ENDIAN */
 } BAR_CONTROL, *PBAR_CONTROL;
 
 // BARControl in MTBAR frame
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      NumTID:4;
-    USHORT      Rsv1:9;
-    USHORT      Compressed:1;
-    USHORT      MTID:1;
-    USHORT      ACKPolicy:1;
-#else
     USHORT      ACKPolicy:1;
     USHORT      MTID:1;
     USHORT      Compressed:1;
     USHORT      Rsv1:9;
     USHORT      NumTID:4;
-#endif /* !RT_BIG_ENDIAN */
 } MTBAR_CONTROL, *PMTBAR_CONTROL;
 
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;
-    USHORT      Rsv1:12;
-#else
     USHORT      Rsv1:12;
     USHORT      TID:4;
-#endif /* !RT_BIG_ENDIAN */
 } PER_TID_INFO, *PPER_TID_INFO;
 
 typedef struct {
@@ -1058,15 +806,6 @@
 
 // QBSS Info field in QSTA's assoc req
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR		Rsv2:1;
-	UCHAR		MaxSPLength:2;
-	UCHAR		Rsv1:1;
-	UCHAR		UAPSD_AC_BE:1;
-	UCHAR		UAPSD_AC_BK:1;
-	UCHAR		UAPSD_AC_VI:1;
-	UCHAR		UAPSD_AC_VO:1;
-#else
     UCHAR		UAPSD_AC_VO:1;
 	UCHAR		UAPSD_AC_VI:1;
 	UCHAR		UAPSD_AC_BK:1;
@@ -1074,20 +813,13 @@
 	UCHAR		Rsv1:1;
 	UCHAR		MaxSPLength:2;
 	UCHAR		Rsv2:1;
-#endif /* !RT_BIG_ENDIAN */
 } QBSS_STA_INFO_PARM, *PQBSS_STA_INFO_PARM;
 
 // QBSS Info field in QAP's Beacon/ProbeRsp
 typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR		UAPSD:1;
-	UCHAR		Rsv:3;
-    UCHAR		ParamSetCount:4;
-#else
     UCHAR		ParamSetCount:4;
 	UCHAR		Rsv:3;
 	UCHAR		UAPSD:1;
-#endif /* !RT_BIG_ENDIAN */
 } QBSS_AP_INFO_PARM, *PQBSS_AP_INFO_PARM;
 
 // QOS Capability reported in QAP's BEACON/ProbeRsp
@@ -1101,13 +833,10 @@
     UCHAR       EdcaUpdateCount;
 } QOS_CAPABILITY_PARM, *PQOS_CAPABILITY_PARM;
 
-#ifdef CONFIG_STA_SUPPORT
 typedef struct {
     UCHAR       IELen;
     UCHAR       IE[MAX_CUSTOM_LEN];
 } WPA_IE_;
-#endif // CONFIG_STA_SUPPORT //
-
 
 typedef struct {
     UCHAR   Bssid[MAC_ADDR_LEN];
@@ -1167,14 +896,8 @@
 	EDCA_PARM           EdcaParm;
 	QOS_CAPABILITY_PARM QosCapability;
 	QBSS_LOAD_PARM      QbssLoad;
-#ifdef CONFIG_STA_SUPPORT
     WPA_IE_     WpaIE;
     WPA_IE_     RsnIE;
-#ifdef EXT_BUILD_CHANNEL_LIST
-	UCHAR		CountryString[3];
-	BOOLEAN		bHasCountryIE;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
 } BSS_ENTRY, *PBSS_ENTRY;
 
 typedef struct {
@@ -1333,29 +1056,6 @@
     UCHAR       SsidLen;
 } MLME_START_REQ_STRUCT, *PMLME_START_REQ_STRUCT;
 
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-// structure for DLS
-typedef struct _RT_802_11_DLS {
-	USHORT						TimeOut;		// Use to time out while slience, unit: second , set by UI
-	USHORT						CountDownTimer;	// Use to time out while slience,unit: second , used by driver only
-	NDIS_802_11_MAC_ADDRESS		MacAddr;		// set by UI
-	UCHAR						Status;			// 0: none , 1: wait STAkey, 2: finish DLS setup , set by driver only
-	BOOLEAN						Valid;			// 1: valid , 0: invalid , set by UI, use to setup or tear down DLS link
-	RALINK_TIMER_STRUCT			Timer;			// Use to time out while handshake
-	USHORT						Sequence;
-	USHORT						MacTabMatchWCID;	// ASIC
-	BOOLEAN						bHTCap;
-	PVOID						pAd;
-} RT_802_11_DLS, *PRT_802_11_DLS;
-
-typedef struct _MLME_DLS_REQ_STRUCT {
-    PRT_802_11_DLS	pDLS;
-    USHORT			Reason;
-} MLME_DLS_REQ_STRUCT, *PMLME_DLS_REQ_STRUCT;
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
 typedef struct PACKED {
     UCHAR   Eid;
     UCHAR   Len;
@@ -1365,21 +1065,12 @@
 typedef struct PACKED _RTMP_TX_RATE_SWITCH
 {
 	UCHAR   ItemNo;
-#ifdef RT_BIG_ENDIAN
-	UCHAR	Rsv2:2;
-	UCHAR	Mode:2;
-	UCHAR	Rsv1:1;
-	UCHAR	BW:1;
-	UCHAR	ShortGI:1;
-	UCHAR	STBC:1;
-#else
 	UCHAR	STBC:1;
 	UCHAR	ShortGI:1;
 	UCHAR	BW:1;
 	UCHAR	Rsv1:1;
 	UCHAR	Mode:2;
 	UCHAR	Rsv2:2;
-#endif
 	UCHAR   CurrMCS;
 	UCHAR   TrainUp;
 	UCHAR   TrainDown;
diff --git a/drivers/staging/rt2860/oid.h b/drivers/staging/rt2860/oid.h
index 5e6ed9f..8519afc 100644
--- a/drivers/staging/rt2860/oid.h
+++ b/drivers/staging/rt2860/oid.h
@@ -80,13 +80,8 @@
 #define MAX_LENGTH_OF_SUPPORT_RATES		12    // 1, 2, 5.5, 11, 6, 9, 12, 18, 24, 36, 48, 54
 #define MAX_NUMBER_OF_DLS_ENTRY			4
 
-#ifndef UNDER_CE
-
 #define OID_GEN_MACHINE_NAME               0x0001021A
 
-#ifdef RALINK_ATE
-#define RT_QUERY_ATE_TXDONE_COUNT			0x0401
-#endif // RALINK_ATE //
 #define RT_QUERY_SIGNAL_CONTEXT				0x0402
 #define RT_SET_IAPP_PID                 	0x0404
 #define RT_SET_APD_PID						0x0405
@@ -163,7 +158,7 @@
 #define	RT_OID_802_11_QUERY_LAST_RX_RATE			0x0613
 #define	RT_OID_802_11_TX_POWER_LEVEL_1				0x0614
 #define	RT_OID_802_11_QUERY_PIDVID					0x0615
-//for WPA_SUPPLICANT_SUPPORT
+
 #define OID_SET_COUNTERMEASURES                     0x0616
 #define OID_802_11_SET_IEEE8021X                    0x0617
 #define OID_802_11_SET_IEEE8021X_REQUIRE_KEY        0x0618
@@ -388,9 +383,6 @@
 	RADIUS_KEY_INFO	RadiusInfo[8/*MAX_MBSSID_NUM*/];
 } RADIUS_CONF, *PRADIUS_CONF;
 
-
-
-#ifdef CONFIG_STA_SUPPORT
 // Key mapping keys require a BSSID
 typedef struct _NDIS_802_11_KEY
 {
@@ -401,7 +393,6 @@
     NDIS_802_11_KEY_RSC KeyRSC;
     UCHAR           KeyMaterial[1];     // variable length depending on above field
 } NDIS_802_11_KEY, *PNDIS_802_11_KEY;
-#endif // CONFIG_STA_SUPPORT //
 
 typedef struct _NDIS_802_11_REMOVE_KEY
 {
@@ -544,8 +535,10 @@
     Ndis802_11Encryption3KeyAbsent,
     Ndis802_11Encryption4Enabled,	// TKIP or AES mix
     Ndis802_11Encryption4KeyAbsent,
+#ifndef RT30xx
     Ndis802_11GroupWEP40Enabled,
 	Ndis802_11GroupWEP104Enabled,
+#endif
 } NDIS_802_11_WEP_STATUS, *PNDIS_802_11_WEP_STATUS,
   NDIS_802_11_ENCRYPTION_STATUS, *PNDIS_802_11_ENCRYPTION_STATUS;
 
@@ -605,7 +598,6 @@
 // PMKID Structures
 typedef UCHAR   NDIS_802_11_PMKID_VALUE[16];
 
-#ifdef CONFIG_STA_SUPPORT
 typedef struct _BSSID_INFO
 {
     NDIS_802_11_MAC_ADDRESS BSSID;
@@ -618,8 +610,6 @@
     UINT    BSSIDInfoCount;
     BSSID_INFO BSSIDInfo[1];
 } NDIS_802_11_PMKID, *PNDIS_802_11_PMKID;
-#endif // CONFIG_STA_SUPPORT //
-
 
 typedef struct _NDIS_802_11_AUTHENTICATION_ENCRYPTION
 {
@@ -636,9 +626,6 @@
      NDIS_802_11_AUTHENTICATION_ENCRYPTION AuthenticationEncryptionSupported[1];
 } NDIS_802_11_CAPABILITY, *PNDIS_802_11_CAPABILITY;
 
-//#endif //of WIN 2k
-#endif //UNDER_CE
-
 #if WIRELESS_EXT <= 11
 #ifndef SIOCDEVPRIVATE
 #define SIOCDEVPRIVATE                              0x8BE0
@@ -646,21 +633,20 @@
 #define SIOCIWFIRSTPRIV								SIOCDEVPRIVATE
 #endif
 
-#ifdef CONFIG_STA_SUPPORT
+#ifdef RT30xx
+#define RT_PRIV_IOCTL_EXT							(SIOCIWFIRSTPRIV + 0x01) // Sync. with AP for wsc upnp daemon
+#endif
 #define RTPRIV_IOCTL_SET							(SIOCIWFIRSTPRIV + 0x02)
 
 #ifdef DBG
 #define RTPRIV_IOCTL_BBP                            (SIOCIWFIRSTPRIV + 0x03)
 #define RTPRIV_IOCTL_MAC                            (SIOCIWFIRSTPRIV + 0x05)
+#ifdef RT30xx
+#define RTPRIV_IOCTL_RF                             (SIOCIWFIRSTPRIV + 0x13)
+#endif
 #define RTPRIV_IOCTL_E2P                            (SIOCIWFIRSTPRIV + 0x07)
 #endif
 
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-#define RTPRIV_IOCTL_ATE							(SIOCIWFIRSTPRIV + 0x08)
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
 #define RTPRIV_IOCTL_STATISTICS                     (SIOCIWFIRSTPRIV + 0x09)
 #define RTPRIV_IOCTL_ADD_PMKID_CACHE                (SIOCIWFIRSTPRIV + 0x0A)
 #define RTPRIV_IOCTL_RADIUS_DATA                    (SIOCIWFIRSTPRIV + 0x0C)
@@ -674,67 +660,61 @@
     SHOW_DRVIER_VERION = 5,
     SHOW_BA_INFO = 6,
 	SHOW_DESC_INFO = 7,
+#ifdef RT2870
+	SHOW_RXBULK_INFO = 8,
+	SHOW_TXBULK_INFO = 9,
+#endif // RT2870 //
     RAIO_OFF = 10,
     RAIO_ON = 11,
-#ifdef QOS_DLS_SUPPORT
-	SHOW_DLS_ENTRY_INFO = 19,
-#endif // QOS_DLS_SUPPORT //
 	SHOW_CFG_VALUE = 20,
+#if !defined(RT2860) && !defined(RT30xx)
+	SHOW_ADHOC_ENTRY_INFO = 21,
+#endif
 };
 
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef SNMP_SUPPORT
-//SNMP ieee 802dot11, kathy , 2008_0220
-// dot11res(3)
-#define RT_OID_802_11_MANUFACTUREROUI			0x0700
-#define RT_OID_802_11_MANUFACTURERNAME			0x0701
-#define RT_OID_802_11_RESOURCETYPEIDNAME		0x0702
-
-// dot11smt(1)
-#define RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED	0x0703
-#define RT_OID_802_11_POWERMANAGEMENTMODE		0x0704
-#define OID_802_11_WEPDEFAULTKEYVALUE			0x0705 // read , write
-#define OID_802_11_WEPDEFAULTKEYID				0x0706
-#define RT_OID_802_11_WEPKEYMAPPINGLENGTH		0x0707
-#define OID_802_11_SHORTRETRYLIMIT				0x0708
-#define OID_802_11_LONGRETRYLIMIT				0x0709
-#define RT_OID_802_11_PRODUCTID					0x0710
-#define RT_OID_802_11_MANUFACTUREID				0x0711
-
-// //dot11Phy(4)
-#define OID_802_11_CURRENTCHANNEL				0x0712
-
-//dot11mac
-#define RT_OID_802_11_MAC_ADDRESS				0x0713
-#endif // SNMP_SUPPORT //
-
 #define OID_802_11_BUILD_CHANNEL_EX				0x0714
 #define OID_802_11_GET_CH_LIST					0x0715
 #define OID_802_11_GET_COUNTRY_CODE				0x0716
 #define OID_802_11_GET_CHANNEL_GEOGRAPHY		0x0717
 
+#ifdef RT30xx
+#define RT_OID_WSC_SET_PASSPHRASE                   0x0740 // passphrase for wpa(2)-psk
+#define RT_OID_WSC_DRIVER_AUTO_CONNECT              0x0741
+#define RT_OID_WSC_QUERY_DEFAULT_PROFILE            0x0742
+#define RT_OID_WSC_SET_CONN_BY_PROFILE_INDEX        0x0743
+#define RT_OID_WSC_SET_ACTION                       0x0744
+#define RT_OID_WSC_SET_SSID                         0x0745
+#define RT_OID_WSC_SET_PIN_CODE                     0x0746
+#define RT_OID_WSC_SET_MODE                         0x0747 // PIN or PBC
+#define RT_OID_WSC_SET_CONF_MODE                    0x0748 // Enrollee or Registrar
+#define RT_OID_WSC_SET_PROFILE                      0x0749
+
+#define RT_OID_802_11_WSC_QUERY_PROFILE				0x0750
+// for consistency with RT61
+#define RT_OID_WSC_QUERY_STATUS						0x0751
+#define RT_OID_WSC_PIN_CODE							0x0752
+#define RT_OID_WSC_UUID								0x0753
+#define RT_OID_WSC_SET_SELECTED_REGISTRAR			0x0754
+#define RT_OID_WSC_EAPMSG							0x0755
+#define RT_OID_WSC_MANUFACTURER						0x0756
+#define RT_OID_WSC_MODEL_NAME						0x0757
+#define RT_OID_WSC_MODEL_NO							0x0758
+#define RT_OID_WSC_SERIAL_NO						0x0759
+#define RT_OID_WSC_MAC_ADDRESS						0x0760
+#endif
+
 #ifdef LLTD_SUPPORT
 // for consistency with RT61
 #define RT_OID_GET_PHY_MODE                         0x761
 #endif // LLTD_SUPPORT //
 
+#if defined(RT2860) || defined(RT30xx)
 // New for MeetingHouse Api support
 #define OID_MH_802_1X_SUPPORTED               0xFFEDC100
+#endif
 
 // MIMO Tx parameter, ShortGI, MCS, STBC, etc.  these are fields in TXWI. Don't change this definition!!!
 typedef union  _HTTRANSMIT_SETTING {
-#ifdef RT_BIG_ENDIAN
-	struct	{
-	USHORT		MODE:2;	// Use definition MODE_xxx.
-	USHORT		TxBF:1;
-	USHORT		rsv:2;
-	USHORT		STBC:2;	//SPACE
-	USHORT		ShortGI:1;
-	USHORT		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	USHORT   	MCS:7;                 // MCS
-	}	field;
-#else
 	struct	{
 	USHORT   	MCS:7;                 // MCS
 	USHORT		BW:1;	//channel bandwidth 20MHz or 40 MHz
@@ -744,7 +724,6 @@
 	USHORT		TxBF:1;
 	USHORT		MODE:2;	// Use definition MODE_xxx.
 	}	field;
-#endif
 	USHORT		word;
  } HTTRANSMIT_SETTING, *PHTTRANSMIT_SETTING;
 
@@ -755,14 +734,12 @@
 } RT_802_11_PREAMBLE, *PRT_802_11_PREAMBLE;
 
 // Only for STA, need to sync with AP
-// 2005-03-08 match current RaConfig.
 typedef enum _RT_802_11_PHY_MODE {
 	PHY_11BG_MIXED = 0,
 	PHY_11B,
 	PHY_11A,
 	PHY_11ABG_MIXED,
 	PHY_11G,
-#ifdef DOT11_N_SUPPORT
 	PHY_11ABGN_MIXED,	// both band   5
 	PHY_11N_2_4G,		// 11n-only with 2.4G band   	6
 	PHY_11GN_MIXED,	// 2.4G band      7
@@ -770,7 +747,6 @@
 	PHY_11BGN_MIXED,	// if check 802.11b.      9
 	PHY_11AGN_MIXED,	// if check 802.11b.      10
 	PHY_11N_5G,			// 11n-only with 5G band		11
-#endif // DOT11_N_SUPPORT //
 } RT_802_11_PHY_MODE;
 
 // put all proprietery for-query objects here to reduce # of Query_OID
@@ -937,54 +913,14 @@
 } RT_LLTD_ASSOICATION_TABLE, *PRT_LLTD_ASSOICATION_TABLE;
 #endif // LLTD_SUPPORT //
 
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-//rt2860, kathy 2007-0118
-// structure for DLS
-typedef struct _RT_802_11_DLS_UI {
-	USHORT						TimeOut;		// unit: second , set by UI
-	USHORT						CountDownTimer;	// unit: second , used by driver only
-	NDIS_802_11_MAC_ADDRESS		MacAddr;		// set by UI
-	UCHAR						Status;			// 0: none , 1: wait STAkey, 2: finish DLS setup , set by driver only
-	BOOLEAN						Valid;			// 1: valid , 0: invalid , set by UI, use to setup or tear down DLS link
-} RT_802_11_DLS_UI, *PRT_802_11_DLS_UI;
-
-typedef struct _RT_802_11_DLS_INFO {
-	RT_802_11_DLS_UI	Entry[MAX_NUMBER_OF_DLS_ENTRY];
-	UCHAR				num;
-} RT_802_11_DLS_INFO, *PRT_802_11_DLS_INFO;
-
-typedef enum _RT_802_11_DLS_MODE {
-    DLS_NONE,
-    DLS_WAIT_KEY,
-    DLS_FINISH
-} RT_802_11_DLS_MODE;
-#endif // QOS_DLS_SUPPORT //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-#define	RT_ASSOC_EVENT_FLAG                         0x0101
-#define	RT_DISASSOC_EVENT_FLAG                      0x0102
-#define	RT_REQIE_EVENT_FLAG                         0x0103
-#define	RT_RESPIE_EVENT_FLAG                        0x0104
-#define	RT_ASSOCINFO_EVENT_FLAG                     0x0105
-#define RT_PMKIDCAND_FLAG                           0x0106
-#define RT_INTERFACE_DOWN                           0x0107
-#define RT_INTERFACE_UP                             0x0108
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
 #define MAX_CUSTOM_LEN 128
 
-#ifdef CONFIG_STA_SUPPORT
 typedef enum _RT_802_11_D_CLIENT_MODE
 {
    Rt802_11_D_None,
    Rt802_11_D_Flexible,
    Rt802_11_D_Strict,
 } RT_802_11_D_CLIENT_MODE, *PRT_802_11_D_CLIENT_MODE;
-#endif // CONFIG_STA_SUPPORT //
 
 typedef struct _RT_CHANNEL_LIST_INFO
 {
@@ -992,6 +928,27 @@
 	UCHAR ChannelListNum; // number of channel in ChannelList[]
 } RT_CHANNEL_LIST_INFO, *PRT_CHANNEL_LIST_INFO;
 
+#ifdef RT2870
+// WSC configured credential
+typedef	struct	_WSC_CREDENTIAL
+{
+	NDIS_802_11_SSID	SSID;				// mandatory
+	USHORT				AuthType;			// mandatory, 1: open, 2: wpa-psk, 4: shared, 8:wpa, 0x10: wpa2, 0x20: wpa2-psk
+	USHORT				EncrType;			// mandatory, 1: none, 2: wep, 4: tkip, 8: aes
+	UCHAR				Key[64];			// mandatory, Maximum 64 byte
+	USHORT				KeyLength;
+	UCHAR				MacAddr[6];			// mandatory, AP MAC address
+	UCHAR				KeyIndex;			// optional, default is 1
+	UCHAR				Rsvd[3];			// Make alignment
+}	WSC_CREDENTIAL, *PWSC_CREDENTIAL;
+
+// WSC configured profiles
+typedef	struct	_WSC_PROFILE
+{
+	UINT			ProfileCnt;
+	WSC_CREDENTIAL	Profile[8];				// Support up to 8 profiles
+}	WSC_PROFILE, *PWSC_PROFILE;
+#endif
 
 #endif // _OID_H_
 
diff --git a/drivers/staging/rt2860/rt28xx.h b/drivers/staging/rt2860/rt28xx.h
index e5e6f0a..6e71acb 100644
--- a/drivers/staging/rt2860/rt28xx.h
+++ b/drivers/staging/rt2860/rt28xx.h
@@ -47,6 +47,15 @@
 #define PCI_EECTRL			0x0004
 #define PCI_MCUCTRL			0x0008
 
+#ifdef RT30xx
+#define	OPT_14			0x114
+
+typedef int				NTSTATUS;
+#define	RETRY_LIMIT             10
+#define STATUS_SUCCESS				0x00
+#define STATUS_UNSUCCESSFUL 		0x01
+#endif
+
 //
 // SCH/DMA registers - base address 0x0200
 //
@@ -54,32 +63,6 @@
 //
 #define DMA_CSR0      0x200
 #define INT_SOURCE_CSR      0x200
-#ifdef RT_BIG_ENDIAN
-typedef	union	_INT_SOURCE_CSR_STRUC	{
-	struct	{
-		UINT32       	:14;
-		UINT32       	TxCoherent:1;
-		UINT32       	RxCoherent:1;
-		UINT32       	GPTimer:1;
-		UINT32       	AutoWakeup:1;//bit14
-		UINT32       	TXFifoStatusInt:1;//FIFO Statistics is full, sw should read 0x171c
-		UINT32       	PreTBTT:1;
-		UINT32       	TBTTInt:1;
-		UINT32       	RxTxCoherent:1;
-		UINT32       	MCUCommandINT:1;
-		UINT32       	MgmtDmaDone:1;
-		UINT32       	HccaDmaDone:1;
-		UINT32       	Ac3DmaDone:1;
-		UINT32       	Ac2DmaDone:1;
-		UINT32       	Ac1DmaDone:1;
-		UINT32		Ac0DmaDone:1;
-		UINT32		RxDone:1;
-		UINT32		TxDelayINT:1;	//delayed interrupt, not interrupt until several int or time limit hit
-		UINT32		RxDelayINT:1; //dealyed interrupt
-	}	field;
-	UINT32			word;
-}	INT_SOURCE_CSR_STRUC, *PINT_SOURCE_CSR_STRUC;
-#else
 typedef	union	_INT_SOURCE_CSR_STRUC	{
 	struct	{
 		UINT32		RxDelayINT:1;
@@ -104,32 +87,11 @@
 	}	field;
 	UINT32			word;
 } INT_SOURCE_CSR_STRUC, *PINT_SOURCE_CSR_STRUC;
-#endif
 
 //
 // INT_MASK_CSR:   Interrupt MASK register.   1: the interrupt is mask OFF
 //
 #define INT_MASK_CSR        0x204
-#ifdef RT_BIG_ENDIAN
-typedef	union	_INT_MASK_CSR_STRUC	{
-	struct	{
-		UINT32       	TxCoherent:1;
-		UINT32       	RxCoherent:1;
-		UINT32       	:20;
-		UINT32       	MCUCommandINT:1;
-		UINT32       	MgmtDmaDone:1;
-		UINT32       	HccaDmaDone:1;
-		UINT32       	Ac3DmaDone:1;
-		UINT32       	Ac2DmaDone:1;
-		UINT32       	Ac1DmaDone:1;
-		UINT32		Ac0DmaDone:1;
-		UINT32		RxDone:1;
-		UINT32		TxDelay:1;
-		UINT32		RXDelay_INT_MSK:1;
-	}	field;
-	UINT32			word;
-}INT_MASK_CSR_STRUC, *PINT_MASK_CSR_STRUC;
-#else
 typedef	union	_INT_MASK_CSR_STRUC	{
 	struct	{
 		UINT32		RXDelay_INT_MSK:1;
@@ -148,24 +110,8 @@
 	}	field;
 	UINT32			word;
 } INT_MASK_CSR_STRUC, *PINT_MASK_CSR_STRUC;
-#endif
+
 #define WPDMA_GLO_CFG 	0x208
-#ifdef RT_BIG_ENDIAN
-typedef	union	_WPDMA_GLO_CFG_STRUC	{
-	struct	{
-		UINT32       	HDR_SEG_LEN:16;
-		UINT32       	RXHdrScater:8;
-		UINT32       	BigEndian:1;
-		UINT32       	EnTXWriteBackDDONE:1;
-		UINT32       	WPDMABurstSIZE:2;
-		UINT32		RxDMABusy:1;
-		UINT32		EnableRxDMA:1;
-		UINT32		TxDMABusy:1;
-		UINT32		EnableTxDMA:1;
-	}	field;
-	UINT32			word;
-}WPDMA_GLO_CFG_STRUC, *PWPDMA_GLO_CFG_STRUC;
-#else
 typedef	union	_WPDMA_GLO_CFG_STRUC	{
 	struct	{
 		UINT32		EnableTxDMA:1;
@@ -180,24 +126,8 @@
 	}	field;
 	UINT32			word;
 } WPDMA_GLO_CFG_STRUC, *PWPDMA_GLO_CFG_STRUC;
-#endif
+
 #define WPDMA_RST_IDX 	0x20c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_WPDMA_RST_IDX_STRUC	{
-	struct	{
-		UINT32       	:15;
-		UINT32       	RST_DRX_IDX0:1;
-		UINT32       	rsv:10;
-		UINT32       	RST_DTX_IDX5:1;
-		UINT32       	RST_DTX_IDX4:1;
-		UINT32		RST_DTX_IDX3:1;
-		UINT32		RST_DTX_IDX2:1;
-		UINT32		RST_DTX_IDX1:1;
-		UINT32		RST_DTX_IDX0:1;
-	}	field;
-	UINT32			word;
-}WPDMA_RST_IDX_STRUC, *PWPDMA_RST_IDX_STRUC;
-#else
 typedef	union	_WPDMA_RST_IDX_STRUC	{
 	struct	{
 		UINT32		RST_DTX_IDX0:1;
@@ -212,21 +142,8 @@
 	}	field;
 	UINT32			word;
 } WPDMA_RST_IDX_STRUC, *PWPDMA_RST_IDX_STRUC;
-#endif
+
 #define DELAY_INT_CFG  0x0210
-#ifdef RT_BIG_ENDIAN
-typedef	union	_DELAY_INT_CFG_STRUC	{
-	struct	{
-		UINT32       	TXDLY_INT_EN:1;
-		UINT32       	TXMAX_PINT:7;
-		UINT32       	TXMAX_PTIME:8;
-		UINT32       	RXDLY_INT_EN:1;
-		UINT32       	RXMAX_PINT:7;
-		UINT32		RXMAX_PTIME:8;
-	}	field;
-	UINT32			word;
-}DELAY_INT_CFG_STRUC, *PDELAY_INT_CFG_STRUC;
-#else
 typedef	union	_DELAY_INT_CFG_STRUC	{
 	struct	{
 		UINT32		RXMAX_PTIME:8;
@@ -238,20 +155,8 @@
 	}	field;
 	UINT32			word;
 } DELAY_INT_CFG_STRUC, *PDELAY_INT_CFG_STRUC;
-#endif
+
 #define WMM_AIFSN_CFG   0x0214
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AIFSN_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:16;
-	    UINT32   Aifsn3:4;       // for AC_VO
-	    UINT32   Aifsn2:4;       // for AC_VI
-	    UINT32   Aifsn1:4;       // for AC_BK
-	    UINT32   Aifsn0:4;       // for AC_BE
-	}	field;
-	UINT32			word;
-}	AIFSN_CSR_STRUC, *PAIFSN_CSR_STRUC;
-#else
 typedef	union	_AIFSN_CSR_STRUC	{
 	struct	{
 	    UINT32   Aifsn0:4;       // for AC_BE
@@ -262,23 +167,11 @@
 	}	field;
 	UINT32			word;
 }	AIFSN_CSR_STRUC, *PAIFSN_CSR_STRUC;
-#endif
+
 //
 // CWMIN_CSR: CWmin for each EDCA AC
 //
 #define WMM_CWMIN_CFG   0x0218
-#ifdef RT_BIG_ENDIAN
-typedef	union	_CWMIN_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:16;
-	    UINT32   Cwmin3:4;       // for AC_VO
-	    UINT32   Cwmin2:4;       // for AC_VI
-	    UINT32   Cwmin1:4;       // for AC_BK
-	    UINT32   Cwmin0:4;       // for AC_BE
-	}	field;
-	UINT32			word;
-}	CWMIN_CSR_STRUC, *PCWMIN_CSR_STRUC;
-#else
 typedef	union	_CWMIN_CSR_STRUC	{
 	struct	{
 	    UINT32   Cwmin0:4;       // for AC_BE
@@ -289,24 +182,11 @@
 	}	field;
 	UINT32			word;
 }	CWMIN_CSR_STRUC, *PCWMIN_CSR_STRUC;
-#endif
 
 //
 // CWMAX_CSR: CWmin for each EDCA AC
 //
 #define WMM_CWMAX_CFG   0x021c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_CWMAX_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:16;
-	    UINT32   Cwmax3:4;       // for AC_VO
-	    UINT32   Cwmax2:4;       // for AC_VI
-	    UINT32   Cwmax1:4;       // for AC_BK
-	    UINT32   Cwmax0:4;       // for AC_BE
-	}	field;
-	UINT32			word;
-}	CWMAX_CSR_STRUC, *PCWMAX_CSR_STRUC;
-#else
 typedef	union	_CWMAX_CSR_STRUC	{
 	struct	{
 	    UINT32   Cwmax0:4;       // for AC_BE
@@ -317,22 +197,11 @@
 	}	field;
 	UINT32			word;
 }	CWMAX_CSR_STRUC, *PCWMAX_CSR_STRUC;
-#endif
-
 
 //
 // AC_TXOP_CSR0: AC_BK/AC_BE TXOP register
 //
 #define WMM_TXOP0_CFG    0x0220
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AC_TXOP_CSR0_STRUC	{
-	struct	{
-	    USHORT  Ac1Txop;        // for AC_BE, in unit of 32us
-	    USHORT  Ac0Txop;        // for AC_BK, in unit of 32us
-	}	field;
-	UINT32			word;
-}	AC_TXOP_CSR0_STRUC, *PAC_TXOP_CSR0_STRUC;
-#else
 typedef	union	_AC_TXOP_CSR0_STRUC	{
 	struct	{
 	    USHORT  Ac0Txop;        // for AC_BK, in unit of 32us
@@ -340,21 +209,11 @@
 	}	field;
 	UINT32			word;
 }	AC_TXOP_CSR0_STRUC, *PAC_TXOP_CSR0_STRUC;
-#endif
 
 //
 // AC_TXOP_CSR1: AC_VO/AC_VI TXOP register
 //
 #define WMM_TXOP1_CFG    0x0224
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AC_TXOP_CSR1_STRUC	{
-	struct	{
-	    USHORT  Ac3Txop;        // for AC_VO, in unit of 32us
-	    USHORT  Ac2Txop;        // for AC_VI, in unit of 32us
-	}	field;
-	UINT32			word;
-}	AC_TXOP_CSR1_STRUC, *PAC_TXOP_CSR1_STRUC;
-#else
 typedef	union	_AC_TXOP_CSR1_STRUC	{
 	struct	{
 	    USHORT  Ac2Txop;        // for AC_VI, in unit of 32us
@@ -362,7 +221,7 @@
 	}	field;
 	UINT32			word;
 }	AC_TXOP_CSR1_STRUC, *PAC_TXOP_CSR1_STRUC;
-#endif
+
 #define RINGREG_DIFF			0x10
 #define GPIO_CTRL_CFG    0x0228	//MAC_CSR13
 #define MCU_CMD_CFG    0x022c
@@ -398,25 +257,7 @@
 #define RX_CRX_IDX       0x0298
 #define RX_DRX_IDX      0x029c
 #define USB_DMA_CFG      0x02a0
-#ifdef RT_BIG_ENDIAN
-typedef	union	_USB_DMA_CFG_STRUC	{
-	struct	{
-	    UINT32  TxBusy:1;   	//USB DMA TX FSM busy . debug only
-	    UINT32  RxBusy:1;        //USB DMA RX FSM busy . debug only
-	    UINT32  EpoutValid:6;        //OUT endpoint data valid. debug only
-	    UINT32  TxBulkEn:1;        //Enable USB DMA Tx
-	    UINT32  RxBulkEn:1;        //Enable USB DMA Rx
-	    UINT32  RxBulkAggEn:1;        //Enable Rx Bulk Aggregation
-	    UINT32  TxopHalt:1;        //Halt TXOP count down when TX buffer is full.
-	    UINT32  TxClear:1;        //Clear USB DMA TX path
-	    UINT32  rsv:2;
-	    UINT32  phyclear:1;        		//phy watch dog enable. write 1
-	    UINT32  RxBulkAggLmt:8;        //Rx Bulk Aggregation Limit  in unit of 1024 bytes
-	    UINT32  RxBulkAggTOut:8;        //Rx Bulk Aggregation TimeOut  in unit of 33ns
-	}	field;
-	UINT32			word;
-}	USB_DMA_CFG_STRUC, *PUSB_DMA_CFG_STRUC;
-#else
+
 typedef	union	_USB_DMA_CFG_STRUC	{
 	struct	{
 	    UINT32  RxBulkAggTOut:8;        //Rx Bulk Aggregation TimeOut  in unit of 33ns
@@ -434,7 +275,6 @@
 	}	field;
 	UINT32			word;
 }	USB_DMA_CFG_STRUC, *PUSB_DMA_CFG_STRUC;
-#endif
 
 //
 //  3  PBF  registers
@@ -451,6 +291,36 @@
 #define 	PBF_DBG 	 	 0x043c
 #define     PBF_CAP_CTRL     0x0440
 
+#ifdef RT30xx
+// eFuse registers
+#define EFUSE_CTRL              0x0580
+#define EFUSE_DATA0             0x0590
+#define EFUSE_DATA1             0x0594
+#define EFUSE_DATA2             0x0598
+#define EFUSE_DATA3             0x059c
+#define EFUSE_USAGE_MAP_START   0x2d0
+#define EFUSE_USAGE_MAP_END     0x2fc
+#define EFUSE_TAG               0x2fe
+#define EFUSE_USAGE_MAP_SIZE    45
+
+typedef	union	_EFUSE_CTRL_STRUC {
+	struct	{
+		UINT32            EFSROM_AOUT:6;
+		UINT32            EFSROM_MODE:2;
+		UINT32            EFSROM_LDO_OFF_TIME:6;
+		UINT32            EFSROM_LDO_ON_TIME:2;
+		UINT32            EFSROM_AIN:10;
+		UINT32            RESERVED:4;
+		UINT32            EFSROM_KICK:1;
+		UINT32            SEL_EFUSE:1;
+	}	field;
+	UINT32			word;
+}	EFUSE_CTRL_STRUC, *PEFUSE_CTRL_STRUC;
+
+#define LDO_CFG0 				0x05d4
+#define GPIO_SWITCH				0x05dc
+#endif /* RT30xx */
+
 //
 //  4  MAC  registers
 //
@@ -458,15 +328,6 @@
 //  4.1 MAC SYSTEM  configuration registers (offset:0x1000)
 //
 #define MAC_CSR0            0x1000
-#ifdef RT_BIG_ENDIAN
-typedef	union	_ASIC_VER_ID_STRUC	{
-	struct	{
-	    USHORT  ASICVer;        // version : 2860
-	    USHORT  ASICRev;        // reversion  : 0
-	}	field;
-	UINT32			word;
-}	ASIC_VER_ID_STRUC, *PASIC_VER_ID_STRUC;
-#else
 typedef	union	_ASIC_VER_ID_STRUC	{
 	struct	{
 	    USHORT  ASICRev;        // reversion  : 0
@@ -474,24 +335,13 @@
 	}	field;
 	UINT32			word;
 }	ASIC_VER_ID_STRUC, *PASIC_VER_ID_STRUC;
-#endif
+
 #define MAC_SYS_CTRL            0x1004		//MAC_CSR1
 #define MAC_ADDR_DW0            		0x1008		// MAC ADDR DW0
 #define MAC_ADDR_DW1           		 0x100c		// MAC ADDR DW1
 //
 // MAC_CSR2: STA MAC register 0
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MAC_DW0_STRUC	{
-	struct	{
-		UCHAR		Byte3;		// MAC address byte 3
-		UCHAR		Byte2;		// MAC address byte 2
-		UCHAR		Byte1;		// MAC address byte 1
-		UCHAR		Byte0;		// MAC address byte 0
-	}	field;
-	UINT32			word;
-}	MAC_DW0_STRUC, *PMAC_DW0_STRUC;
-#else
 typedef	union	_MAC_DW0_STRUC	{
 	struct	{
 		UCHAR		Byte0;		// MAC address byte 0
@@ -501,22 +351,10 @@
 	}	field;
 	UINT32			word;
 }	MAC_DW0_STRUC, *PMAC_DW0_STRUC;
-#endif
 
 //
 // MAC_CSR3: STA MAC register 1
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MAC_DW1_STRUC	{
-	struct	{
-		UCHAR		Rsvd1;
-		UCHAR		U2MeMask;
-		UCHAR		Byte5;		// MAC address byte 5
-		UCHAR		Byte4;		// MAC address byte 4
-	}	field;
-	UINT32			word;
-}	MAC_DW1_STRUC, *PMAC_DW1_STRUC;
-#else
 typedef	union	_MAC_DW1_STRUC	{
 	struct	{
 		UCHAR		Byte4;		// MAC address byte 4
@@ -526,7 +364,6 @@
 	}	field;
 	UINT32			word;
 }	MAC_DW1_STRUC, *PMAC_DW1_STRUC;
-#endif
 
 #define MAC_BSSID_DW0            		0x1010		// MAC BSSID DW0
 #define MAC_BSSID_DW1            		0x1014		// MAC BSSID DW1
@@ -534,18 +371,6 @@
 //
 // MAC_CSR5: BSSID register 1
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MAC_CSR5_STRUC	{
-	struct	{
-		USHORT		Rsvd:11;
-		USHORT		MBssBcnNum:3;
-		USHORT		BssIdMode:2; // 0: one BSSID, 10: 4 BSSID,  01: 2 BSSID , 11: 8BSSID
-		UCHAR		Byte5;		 // BSSID byte 5
-		UCHAR		Byte4;		 // BSSID byte 4
-	}	field;
-	UINT32			word;
-}	MAC_CSR5_STRUC, *PMAC_CSR5_STRUC;
-#else
 typedef	union	_MAC_CSR5_STRUC	{
 	struct	{
 		UCHAR		Byte4;		 // BSSID byte 4
@@ -556,27 +381,12 @@
 	}	field;
 	UINT32			word;
 }	MAC_CSR5_STRUC, *PMAC_CSR5_STRUC;
-#endif
 
 #define MAX_LEN_CFG              0x1018		// rt2860b max 16k bytes. bit12:13 Maximum PSDU length (power factor) 0:2^13, 1:2^14, 2:2^15, 3:2^16
 #define BBP_CSR_CFG            		0x101c		//
 //
 // BBP_CSR_CFG: BBP serial control register
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_BBP_CSR_CFG_STRUC	{
-	struct	{
-		UINT32		:12;
-		UINT32		BBP_RW_MODE:1;		// 0: use serial mode  1:parallel
-		UINT32		BBP_PAR_DUR:1;		    // 0: 4 MAC clock cycles  1: 8 MAC clock cycles
-		UINT32		Busy:1;				// 1: ASIC is busy execute BBP programming.
-		UINT32		fRead:1;		    // 0: Write	BBP, 1:	Read BBP
-		UINT32		RegNum:8;			// Selected	BBP	register
-		UINT32		Value:8;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	BBP_CSR_CFG_STRUC, *PBBP_CSR_CFG_STRUC;
-#else
 typedef	union	_BBP_CSR_CFG_STRUC	{
 	struct	{
 		UINT32		Value:8;			// Register	value to program into BBP
@@ -589,23 +399,11 @@
 	}	field;
 	UINT32			word;
 }	BBP_CSR_CFG_STRUC, *PBBP_CSR_CFG_STRUC;
-#endif
+
 #define RF_CSR_CFG0            		0x1020
 //
 // RF_CSR_CFG: RF control register
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG0_STRUC	{
-	struct	{
-		UINT32		Busy:1;		    // 0: idle 1: 8busy
-		UINT32		Sel:1;				// 0:RF_LE0 activate  1:RF_LE1 activate
-		UINT32		StandbyMode:1;		    // 0: high when stand by 1:	low when standby
-		UINT32		bitwidth:5;			// Selected	BBP	register
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG0_STRUC, *PRF_CSR_CFG0_STRUC;
-#else
 typedef	union	_RF_CSR_CFG0_STRUC	{
 	struct	{
 		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
@@ -616,18 +414,8 @@
 	}	field;
 	UINT32			word;
 }	RF_CSR_CFG0_STRUC, *PRF_CSR_CFG0_STRUC;
-#endif
+
 #define RF_CSR_CFG1           		0x1024
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG1_STRUC	{
-	struct	{
-		UINT32		rsv:7;		    // 0: idle 1: 8busy
-		UINT32		RFGap:5;			// Gap between BB_CONTROL_RF and RF_LE. 0: 3 system clock cycle (37.5usec) 1: 5 system clock cycle (62.5usec)
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG1_STRUC, *PRF_CSR_CFG1_STRUC;
-#else
 typedef	union	_RF_CSR_CFG1_STRUC	{
 	struct	{
 		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
@@ -636,17 +424,8 @@
 	}	field;
 	UINT32			word;
 }	RF_CSR_CFG1_STRUC, *PRF_CSR_CFG1_STRUC;
-#endif
+
 #define RF_CSR_CFG2           		0x1028		//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG2_STRUC	{
-	struct	{
-		UINT32		rsv:8;		    // 0: idle 1: 8busy
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG2_STRUC, *PRF_CSR_CFG2_STRUC;
-#else
 typedef	union	_RF_CSR_CFG2_STRUC	{
 	struct	{
 		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
@@ -654,24 +433,8 @@
 	}	field;
 	UINT32			word;
 }	RF_CSR_CFG2_STRUC, *PRF_CSR_CFG2_STRUC;
-#endif
+
 #define LED_CFG           		0x102c		//  MAC_CSR14
-#ifdef RT_BIG_ENDIAN
-typedef	union	_LED_CFG_STRUC	{
-	struct	{
-		UINT32		:1;
-		UINT32		LedPolar:1;			// Led Polarity.  0: active low1: active high
-		UINT32		YLedMode:2;			// yellow Led Mode
-		UINT32		GLedMode:2;			// green Led Mode
-		UINT32		RLedMode:2;			// red Led Mode    0: off1: blinking upon TX2: periodic slow blinking3: always on
-		UINT32		rsv:2;
-		UINT32		SlowBlinkPeriod:6;			// slow blinking period. unit:1ms
-		UINT32		OffPeriod:8;			// blinking off period unit 1ms
-		UINT32		OnPeriod:8;			// blinking on period unit 1ms
-	}	field;
-	UINT32			word;
-}	LED_CFG_STRUC, *PLED_CFG_STRUC;
-#else
 typedef	union	_LED_CFG_STRUC	{
 	struct	{
 		UINT32		OnPeriod:8;			// blinking on period unit 1ms
@@ -686,24 +449,11 @@
 	}	field;
 	UINT32			word;
 }	LED_CFG_STRUC, *PLED_CFG_STRUC;
-#endif
+
 //
 //  4.2 MAC TIMING  configuration registers (offset:0x1100)
 //
 #define XIFS_TIME_CFG             0x1100		 // MAC_CSR8  MAC_CSR9
-#ifdef RT_BIG_ENDIAN
-typedef	union	_IFS_SLOT_CFG_STRUC	{
-	struct	{
-	    UINT32  rsv:2;
-	    UINT32  BBRxendEnable:1;        //  reference RXEND signal to begin XIFS defer
-	    UINT32  EIFS:9;        //  unit 1us
-	    UINT32  OfdmXifsTime:4;        //OFDM SIFS. unit 1us. Applied after OFDM RX when MAC doesn't reference BBP signal BBRXEND
-	    UINT32  OfdmSifsTime:8;        //  unit 1us. Applied after OFDM RX/TX
-	    UINT32  CckmSifsTime:8;        //  unit 1us. Applied after CCK RX/TX
-	}	field;
-	UINT32			word;
-}	IFS_SLOT_CFG_STRUC, *PIFS_SLOT_CFG_STRUC;
-#else
 typedef	union	_IFS_SLOT_CFG_STRUC	{
 	struct	{
 	    UINT32  CckmSifsTime:8;        //  unit 1us. Applied after CCK RX/TX
@@ -715,7 +465,6 @@
 	}	field;
 	UINT32			word;
 }	IFS_SLOT_CFG_STRUC, *PIFS_SLOT_CFG_STRUC;
-#endif
 
 #define BKOFF_SLOT_CFG             0x1104		 //  mac_csr9 last 8 bits
 #define NAV_TIME_CFG             0x1108		 // NAV  (MAC_CSR15)
@@ -729,20 +478,6 @@
 //
 // BCN_TIME_CFG : Synchronization control register
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_BCN_TIME_CFG_STRUC	{
-	struct	{
-		UINT32		TxTimestampCompensate:8;
-        UINT32       :3;
-		UINT32		bBeaconGen:1;		// Enable beacon generator
-        UINT32       bTBTTEnable:1;
-		UINT32		TsfSyncMode:2;		// Enable TSF sync, 00: disable, 01: infra mode, 10: ad-hoc mode
-		UINT32		bTsfTicking:1;		// Enable TSF auto counting
-		UINT32       BeaconInterval:16;  // in unit of 1/16 TU
-	}	field;
-	UINT32			word;
-}	BCN_TIME_CFG_STRUC, *PBCN_TIME_CFG_STRUC;
-#else
 typedef	union	_BCN_TIME_CFG_STRUC	{
 	struct	{
 		UINT32       BeaconInterval:16;  // in unit of 1/16 TU
@@ -755,7 +490,7 @@
 	}	field;
 	UINT32			word;
 }	BCN_TIME_CFG_STRUC, *PBCN_TIME_CFG_STRUC;
-#endif
+
 #define TBTT_SYNC_CFG            0x1118  		// txrx_csr10
 #define TSF_TIMER_DW0             0x111C  		// Local TSF timer lsb 32 bits. Read-only
 #define TSF_TIMER_DW1             0x1120  		// msb 32 bits. Read-only.
@@ -773,17 +508,6 @@
 //
 // AUTO_WAKEUP_CFG: Manual power control / status register
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AUTO_WAKEUP_STRUC	{
-	struct	{
-		UINT32		:16;
-		UINT32		EnableAutoWakeup:1;	// 0:sleep, 1:awake
-		UINT32       NumofSleepingTbtt:7;          // ForceWake has high privilege than PutToSleep when both set
-		UINT32       AutoLeadTime:8;
-	}	field;
-	UINT32			word;
-}	AUTO_WAKEUP_STRUC, *PAUTO_WAKEUP_STRUC;
-#else
 typedef	union	_AUTO_WAKEUP_STRUC	{
 	struct	{
 		UINT32       AutoLeadTime:8;
@@ -793,7 +517,7 @@
 	}	field;
 	UINT32			word;
 }	AUTO_WAKEUP_STRUC, *PAUTO_WAKEUP_STRUC;
-#endif
+
 //
 //  4.3 MAC TX  configuration registers (offset:0x1300)
 //
@@ -802,18 +526,6 @@
 #define EDCA_AC1_CFG	0x1304
 #define EDCA_AC2_CFG	0x1308
 #define EDCA_AC3_CFG	0x130c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EDCA_AC_CFG_STRUC	{
-	struct	{
-	    UINT32  :12;        //
-	    UINT32  Cwmax:4;        //unit power of 2
-	    UINT32  Cwmin:4;        //
-	    UINT32  Aifsn:4;        // # of slot time
-	    UINT32  AcTxop:8;        //  in unit of 32us
-	}	field;
-	UINT32			word;
-}	EDCA_AC_CFG_STRUC, *PEDCA_AC_CFG_STRUC;
-#else
 typedef	union	_EDCA_AC_CFG_STRUC	{
 	struct	{
 	    UINT32  AcTxop:8;        //  in unit of 32us
@@ -824,7 +536,6 @@
 	}	field;
 	UINT32			word;
 }	EDCA_AC_CFG_STRUC, *PEDCA_AC_CFG_STRUC;
-#endif
 
 #define EDCA_TID_AC_MAP	0x1310
 #define TX_PWR_CFG_0	0x1314
@@ -841,17 +552,6 @@
 #define TXOP_CTRL_CFG		0x1340
 #define TX_RTS_CFG		0x1344
 
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_RTS_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv:7;
-	    UINT32       RtsFbkEn:1;    // enable rts rate fallback
-	    UINT32       RtsThres:16;    // unit:byte
-	    UINT32       AutoRtsRetryLimit:8;
-	}	field;
-	UINT32			word;
-}	TX_RTS_CFG_STRUC, *PTX_RTS_CFG_STRUC;
-#else
 typedef	union	_TX_RTS_CFG_STRUC	{
 	struct	{
 	    UINT32       AutoRtsRetryLimit:8;
@@ -861,20 +561,8 @@
 	}	field;
 	UINT32			word;
 }	TX_RTS_CFG_STRUC, *PTX_RTS_CFG_STRUC;
-#endif
+
 #define TX_TIMEOUT_CFG	0x1348
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_TIMEOUT_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv2:8;
-	    UINT32       TxopTimeout:8;	//TXOP timeout value for TXOP truncation.  It is recommended that (SLOT_TIME) > (TX_OP_TIMEOUT) > (RX_ACK_TIMEOUT)
-	    UINT32       RxAckTimeout:8;	// unit:slot. Used for TX precedure
-	    UINT32       MpduLifeTime:4;    //  expiration time = 2^(9+MPDU LIFE TIME)  us
-	    UINT32       rsv:4;
-	}	field;
-	UINT32			word;
-}	TX_TIMEOUT_CFG_STRUC, *PTX_TIMEOUT_CFG_STRUC;
-#else
 typedef	union	_TX_TIMEOUT_CFG_STRUC	{
 	struct	{
 	    UINT32       rsv:4;
@@ -885,23 +573,8 @@
 	}	field;
 	UINT32			word;
 }	TX_TIMEOUT_CFG_STRUC, *PTX_TIMEOUT_CFG_STRUC;
-#endif
-#define TX_RTY_CFG	0x134c
-#ifdef RT_BIG_ENDIAN
-typedef	union PACKED _TX_RTY_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv:1;
-	    UINT32       TxautoFBEnable:1;    // Tx retry PHY rate auto fallback enable
-	    UINT32       AggRtyMode:1;	// Aggregate MPDU retry mode.  0:expired by retry limit, 1: expired by mpdu life timer
-	    UINT32       NonAggRtyMode:1;	// Non-Aggregate MPDU retry mode.  0:expired by retry limit, 1: expired by mpdu life timer
-	    UINT32       LongRtyThre:12;	// Long retry threshoold
-	    UINT32       LongRtyLimit:8;	//long retry limit
-	    UINT32       ShortRtyLimit:8;	//  short retry limit
 
-	}	field;
-	UINT32			word;
-}	TX_RTY_CFG_STRUC, *PTX_RTY_CFG_STRUC;
-#else
+#define TX_RTY_CFG	0x134c
 typedef	union PACKED _TX_RTY_CFG_STRUC	{
 	struct	{
 	    UINT32       ShortRtyLimit:8;	//  short retry limit
@@ -914,24 +587,8 @@
 	}	field;
 	UINT32			word;
 }	TX_RTY_CFG_STRUC, *PTX_RTY_CFG_STRUC;
-#endif
+
 #define TX_LINK_CFG	0x1350
-#ifdef RT_BIG_ENDIAN
-typedef	union	PACKED _TX_LINK_CFG_STRUC	{
-	struct PACKED {
-	    UINT32       RemotMFS:8;	//remote MCS feedback sequence number
-	    UINT32       RemotMFB:8;    //  remote MCS feedback
-	    UINT32       rsv:3;	//
-	    UINT32       TxCFAckEn:1;	//   Piggyback CF-ACK enable
-	    UINT32       TxRDGEn:1;	// RDG TX enable
-	    UINT32       TxMRQEn:1;	//  MCS request TX enable
-	    UINT32       RemoteUMFSEnable:1;	//  remote unsolicit  MFB enable.  0: not apply remote remote unsolicit (MFS=7)
-	    UINT32       MFBEnable:1;	//  TX apply remote MFB 1:enable
-	    UINT32       RemoteMFBLifeTime:8;	//remote MFB life time. unit : 32us
-	}	field;
-	UINT32			word;
-}	TX_LINK_CFG_STRUC, *PTX_LINK_CFG_STRUC;
-#else
 typedef	union	PACKED _TX_LINK_CFG_STRUC	{
 	struct PACKED {
 	    UINT32       RemoteMFBLifeTime:8;	//remote MFB life time. unit : 32us
@@ -946,23 +603,8 @@
 	}	field;
 	UINT32			word;
 }	TX_LINK_CFG_STRUC, *PTX_LINK_CFG_STRUC;
-#endif
+
 #define HT_FBK_CFG0	0x1354
-#ifdef RT_BIG_ENDIAN
-typedef	union PACKED _HT_FBK_CFG0_STRUC	{
-	struct	{
-	    UINT32       HTMCS7FBK:4;
-	    UINT32       HTMCS6FBK:4;
-	    UINT32       HTMCS5FBK:4;
-	    UINT32       HTMCS4FBK:4;
-	    UINT32       HTMCS3FBK:4;
-	    UINT32       HTMCS2FBK:4;
-	    UINT32       HTMCS1FBK:4;
-	    UINT32       HTMCS0FBK:4;
-	}	field;
-	UINT32			word;
-}	HT_FBK_CFG0_STRUC, *PHT_FBK_CFG0_STRUC;
-#else
 typedef	union PACKED _HT_FBK_CFG0_STRUC	{
 	struct	{
 	    UINT32       HTMCS0FBK:4;
@@ -976,23 +618,8 @@
 	}	field;
 	UINT32			word;
 }	HT_FBK_CFG0_STRUC, *PHT_FBK_CFG0_STRUC;
-#endif
+
 #define HT_FBK_CFG1	0x1358
-#ifdef RT_BIG_ENDIAN
-typedef	union	_HT_FBK_CFG1_STRUC	{
-	struct	{
-	    UINT32       HTMCS15FBK:4;
-	    UINT32       HTMCS14FBK:4;
-	    UINT32       HTMCS13FBK:4;
-	    UINT32       HTMCS12FBK:4;
-	    UINT32       HTMCS11FBK:4;
-	    UINT32       HTMCS10FBK:4;
-	    UINT32       HTMCS9FBK:4;
-	    UINT32       HTMCS8FBK:4;
-	}	field;
-	UINT32			word;
-}	HT_FBK_CFG1_STRUC, *PHT_FBK_CFG1_STRUC;
-#else
 typedef	union	_HT_FBK_CFG1_STRUC	{
 	struct	{
 	    UINT32       HTMCS8FBK:4;
@@ -1006,23 +633,8 @@
 	}	field;
 	UINT32			word;
 }	HT_FBK_CFG1_STRUC, *PHT_FBK_CFG1_STRUC;
-#endif
+
 #define LG_FBK_CFG0	0x135c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_LG_FBK_CFG0_STRUC	{
-	struct	{
-	    UINT32       OFDMMCS7FBK:4;	//initial value is 6
-	    UINT32       OFDMMCS6FBK:4;	//initial value is 5
-	    UINT32       OFDMMCS5FBK:4;	//initial value is 4
-	    UINT32       OFDMMCS4FBK:4;	//initial value is 3
-	    UINT32       OFDMMCS3FBK:4;	//initial value is 2
-	    UINT32       OFDMMCS2FBK:4;	//initial value is 1
-	    UINT32       OFDMMCS1FBK:4;	//initial value is 0
-	    UINT32       OFDMMCS0FBK:4;	//initial value is 0
-	}	field;
-	UINT32			word;
-}	LG_FBK_CFG0_STRUC, *PLG_FBK_CFG0_STRUC;
-#else
 typedef	union	_LG_FBK_CFG0_STRUC	{
 	struct	{
 	    UINT32       OFDMMCS0FBK:4;	//initial value is 0
@@ -1036,20 +648,8 @@
 	}	field;
 	UINT32			word;
 }	LG_FBK_CFG0_STRUC, *PLG_FBK_CFG0_STRUC;
-#endif
+
 #define LG_FBK_CFG1		0x1360
-#ifdef RT_BIG_ENDIAN
-typedef	union	_LG_FBK_CFG1_STRUC	{
-	struct	{
-	    UINT32       rsv:16;
-	    UINT32       CCKMCS3FBK:4;	//initial value is 2
-	    UINT32       CCKMCS2FBK:4;	//initial value is 1
-	    UINT32       CCKMCS1FBK:4;	//initial value is 0
-	    UINT32       CCKMCS0FBK:4;	//initial value is 0
-	}	field;
-	UINT32			word;
-}	LG_FBK_CFG1_STRUC, *PLG_FBK_CFG1_STRUC;
-#else
 typedef	union	_LG_FBK_CFG1_STRUC	{
 	struct	{
 	    UINT32       CCKMCS0FBK:4;	//initial value is 0
@@ -1060,7 +660,6 @@
 	}	field;
 	UINT32			word;
 }	LG_FBK_CFG1_STRUC, *PLG_FBK_CFG1_STRUC;
-#endif
 
 //=======================================================
 //================ Protection Paramater================================
@@ -1070,24 +669,6 @@
 #define ASIC_LONGNAV		2
 #define ASIC_RTS		1
 #define ASIC_CTS		2
-#ifdef RT_BIG_ENDIAN
-typedef	union	_PROT_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv:5;
-	    UINT32       RTSThEn:1;	//RTS threshold enable on CCK TX
-	    UINT32       TxopAllowGF40:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowGF20:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowMM40:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowMM20:1;	//CCK TXOP allowance. 0:disallow.
-	    UINT32       TxopAllowOfdm:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowCck:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       ProtectNav:2;	//TXOP protection type for CCK TX. 0:None, 1:ShortNAVprotect,  2:LongNAVProtect, 3:rsv
-	    UINT32       ProtectCtrl:2;	//Protection control frame type for CCK TX. 1:RTS/CTS, 2:CTS-to-self, 0:None, 3:rsv
-	    UINT32       ProtectRate:16;	//Protection control frame rate for CCK TX(RTS/CTS/CFEnd).
-	}	field;
-	UINT32			word;
-}	PROT_CFG_STRUC, *PPROT_CFG_STRUC;
-#else
 typedef	union	_PROT_CFG_STRUC	{
 	struct	{
 	    UINT32       ProtectRate:16;	//Protection control frame rate for CCK TX(RTS/CTS/CFEnd).
@@ -1104,7 +685,6 @@
 	}	field;
 	UINT32			word;
 }	PROT_CFG_STRUC, *PPROT_CFG_STRUC;
-#endif
 
 #define OFDM_PROT_CFG	0x1368		//OFDM Protection
 #define MM20_PROT_CFG	0x136C		//MM20 Protection
@@ -1122,22 +702,6 @@
 //
 // TXRX_CSR4: Auto-Responder/
 //
-#ifdef RT_BIG_ENDIAN
-typedef union _AUTO_RSP_CFG_STRUC {
- struct {
-     UINT32        :24;
-     UINT32       AckCtsPsmBit:1;   // Power bit value in conrtrol frame
-     UINT32       DualCTSEn:1;   // Power bit value in conrtrol frame
-     UINT32       rsv:1;   // Power bit value in conrtrol frame
-     UINT32       AutoResponderPreamble:1;    // 0:long, 1:short preamble
-     UINT32       CTS40MRef:1;  // Response CTS 40MHz duplicate mode
-     UINT32       CTS40MMode:1;  // Response CTS 40MHz duplicate mode
-     UINT32       BACAckPolicyEnable:1;    // 0:long, 1:short preamble
-     UINT32       AutoResponderEnable:1;
- } field;
- UINT32   word;
-} AUTO_RSP_CFG_STRUC, *PAUTO_RSP_CFG_STRUC;
-#else
 typedef union _AUTO_RSP_CFG_STRUC {
  struct {
      UINT32       AutoResponderEnable:1;
@@ -1152,7 +716,6 @@
  } field;
  UINT32   word;
 } AUTO_RSP_CFG_STRUC, *PAUTO_RSP_CFG_STRUC;
-#endif
 
 #define LEGACY_BASIC_RATE	0x1408	//  TXRX_CSR5           0x3054
 #define HT_BASIC_RATE		0x140c
@@ -1185,15 +748,6 @@
 //
 // RX_STA_CNT0_STRUC: RX PLCP error count & RX CRC error count
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RX_STA_CNT0_STRUC	{
-	struct	{
-	    USHORT  PhyErr;
-	    USHORT  CrcErr;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT0_STRUC, *PRX_STA_CNT0_STRUC;
-#else
 typedef	union	_RX_STA_CNT0_STRUC	{
 	struct	{
 	    USHORT  CrcErr;
@@ -1201,20 +755,10 @@
 	}	field;
 	UINT32			word;
 }	RX_STA_CNT0_STRUC, *PRX_STA_CNT0_STRUC;
-#endif
 
 //
 // RX_STA_CNT1_STRUC: RX False CCA count & RX LONG frame count
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RX_STA_CNT1_STRUC	{
-	struct	{
-	    USHORT  PlcpErr;
-	    USHORT  FalseCca;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT1_STRUC, *PRX_STA_CNT1_STRUC;
-#else
 typedef	union	_RX_STA_CNT1_STRUC	{
 	struct	{
 	    USHORT  FalseCca;
@@ -1222,20 +766,10 @@
 	}	field;
 	UINT32			word;
 }	RX_STA_CNT1_STRUC, *PRX_STA_CNT1_STRUC;
-#endif
 
 //
 // RX_STA_CNT2_STRUC:
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RX_STA_CNT2_STRUC	{
-	struct	{
-	    USHORT  RxFifoOverflowCount;
-	    USHORT  RxDupliCount;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT2_STRUC, *PRX_STA_CNT2_STRUC;
-#else
 typedef	union	_RX_STA_CNT2_STRUC	{
 	struct	{
 	    USHORT  RxDupliCount;
@@ -1243,20 +777,11 @@
 	}	field;
 	UINT32			word;
 }	RX_STA_CNT2_STRUC, *PRX_STA_CNT2_STRUC;
-#endif
+
 #define TX_STA_CNT0		0x170C		//
 //
 // STA_CSR3: TX Beacon count
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_STA_CNT0_STRUC	{
-	struct	{
-	    USHORT  TxBeaconCount;
-	    USHORT  TxFailCount;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT0_STRUC, *PTX_STA_CNT0_STRUC;
-#else
 typedef	union	_TX_STA_CNT0_STRUC	{
 	struct	{
 	    USHORT  TxFailCount;
@@ -1264,20 +789,11 @@
 	}	field;
 	UINT32			word;
 }	TX_STA_CNT0_STRUC, *PTX_STA_CNT0_STRUC;
-#endif
+
 #define TX_STA_CNT1		0x1710		//
 //
 // TX_STA_CNT1: TX tx count
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_STA_CNT1_STRUC	{
-	struct	{
-	    USHORT  TxRetransmit;
-	    USHORT  TxSuccess;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT1_STRUC, *PTX_STA_CNT1_STRUC;
-#else
 typedef	union	_TX_STA_CNT1_STRUC	{
 	struct	{
 	    USHORT  TxSuccess;
@@ -1285,20 +801,11 @@
 	}	field;
 	UINT32			word;
 }	TX_STA_CNT1_STRUC, *PTX_STA_CNT1_STRUC;
-#endif
+
 #define TX_STA_CNT2		0x1714		//
 //
 // TX_STA_CNT2: TX tx count
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_STA_CNT2_STRUC	{
-	struct	{
-	    USHORT  TxUnderFlowCount;
-	    USHORT  TxZeroLenCount;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT2_STRUC, *PTX_STA_CNT2_STRUC;
-#else
 typedef	union	_TX_STA_CNT2_STRUC	{
 	struct	{
 	    USHORT  TxZeroLenCount;
@@ -1306,28 +813,11 @@
 	}	field;
 	UINT32			word;
 }	TX_STA_CNT2_STRUC, *PTX_STA_CNT2_STRUC;
-#endif
+
 #define TX_STA_FIFO		0x1718		//
 //
 // TX_STA_FIFO_STRUC: TX Result for specific PID status fifo register
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union PACKED _TX_STA_FIFO_STRUC	{
-	struct	{
-		UINT32		Reserve:2;
-		UINT32		TxBF:1; // 3*3
-		UINT32		SuccessRate:13;	//include MCS, mode ,shortGI, BW settingSame format as TXWI Word 0 Bit 31-16.
-//		UINT32		SuccessRate:16;	//include MCS, mode ,shortGI, BW settingSame format as TXWI Word 0 Bit 31-16.
-		UINT32		wcid:8;		//wireless client index
-		UINT32       	TxAckRequired:1;    // ack required
-		UINT32       	TxAggre:1;    // Tx is aggregated
-		UINT32       	TxSuccess:1;   // Tx success. whether success or not
-		UINT32       	PidType:4;
-		UINT32       	bValid:1;   // 1:This register contains a valid TX result
-	}	field;
-	UINT32			word;
-}	TX_STA_FIFO_STRUC, *PTX_STA_FIFO_STRUC;
-#else
 typedef	union PACKED _TX_STA_FIFO_STRUC	{
 	struct	{
 		UINT32       	bValid:1;   // 1:This register contains a valid TX result
@@ -1343,18 +833,9 @@
 	}	field;
 	UINT32			word;
 }	TX_STA_FIFO_STRUC, *PTX_STA_FIFO_STRUC;
-#endif
+
 // Debug counter
 #define TX_AGG_CNT	0x171c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT_STRUC	{
-	struct	{
-	    USHORT  AggTxCount;
-	    USHORT  NonAggTxCount;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT_STRUC, *PTX_AGG_CNT_STRUC;
-#else
 typedef	union	_TX_AGG_CNT_STRUC	{
 	struct	{
 	    USHORT  NonAggTxCount;
@@ -1362,18 +843,9 @@
 	}	field;
 	UINT32			word;
 }	TX_AGG_CNT_STRUC, *PTX_AGG_CNT_STRUC;
-#endif
+
 // Debug counter
 #define TX_AGG_CNT0	0x1720
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT0_STRUC	{
-	struct	{
-	    USHORT  AggSize2Count;
-	    USHORT  AggSize1Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT0_STRUC, *PTX_AGG_CNT0_STRUC;
-#else
 typedef	union	_TX_AGG_CNT0_STRUC	{
 	struct	{
 	    USHORT  AggSize1Count;
@@ -1381,18 +853,9 @@
 	}	field;
 	UINT32			word;
 }	TX_AGG_CNT0_STRUC, *PTX_AGG_CNT0_STRUC;
-#endif
+
 // Debug counter
 #define TX_AGG_CNT1	0x1724
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT1_STRUC	{
-	struct	{
-	    USHORT  AggSize4Count;
-	    USHORT  AggSize3Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT1_STRUC, *PTX_AGG_CNT1_STRUC;
-#else
 typedef	union	_TX_AGG_CNT1_STRUC	{
 	struct	{
 	    USHORT  AggSize3Count;
@@ -1400,17 +863,8 @@
 	}	field;
 	UINT32			word;
 }	TX_AGG_CNT1_STRUC, *PTX_AGG_CNT1_STRUC;
-#endif
+
 #define TX_AGG_CNT2	0x1728
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT2_STRUC	{
-	struct	{
-	    USHORT  AggSize6Count;
-	    USHORT  AggSize5Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT2_STRUC, *PTX_AGG_CNT2_STRUC;
-#else
 typedef	union	_TX_AGG_CNT2_STRUC	{
 	struct	{
 	    USHORT  AggSize5Count;
@@ -1418,18 +872,9 @@
 	}	field;
 	UINT32			word;
 }	TX_AGG_CNT2_STRUC, *PTX_AGG_CNT2_STRUC;
-#endif
+
 // Debug counter
 #define TX_AGG_CNT3	0x172c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT3_STRUC	{
-	struct	{
-	    USHORT  AggSize8Count;
-	    USHORT  AggSize7Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT3_STRUC, *PTX_AGG_CNT3_STRUC;
-#else
 typedef	union	_TX_AGG_CNT3_STRUC	{
 	struct	{
 	    USHORT  AggSize7Count;
@@ -1437,18 +882,9 @@
 	}	field;
 	UINT32			word;
 }	TX_AGG_CNT3_STRUC, *PTX_AGG_CNT3_STRUC;
-#endif
+
 // Debug counter
 #define TX_AGG_CNT4	0x1730
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT4_STRUC	{
-	struct	{
-	    USHORT  AggSize10Count;
-	    USHORT  AggSize9Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT4_STRUC, *PTX_AGG_CNT4_STRUC;
-#else
 typedef	union	_TX_AGG_CNT4_STRUC	{
 	struct	{
 	    USHORT  AggSize9Count;
@@ -1456,17 +892,8 @@
 	}	field;
 	UINT32			word;
 }	TX_AGG_CNT4_STRUC, *PTX_AGG_CNT4_STRUC;
-#endif
+
 #define TX_AGG_CNT5	0x1734
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT5_STRUC	{
-	struct	{
-	    USHORT  AggSize12Count;
-	    USHORT  AggSize11Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT5_STRUC, *PTX_AGG_CNT5_STRUC;
-#else
 typedef	union	_TX_AGG_CNT5_STRUC	{
 	struct	{
 	    USHORT  AggSize11Count;
@@ -1474,17 +901,8 @@
 	}	field;
 	UINT32			word;
 }	TX_AGG_CNT5_STRUC, *PTX_AGG_CNT5_STRUC;
-#endif
+
 #define TX_AGG_CNT6		0x1738
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT6_STRUC	{
-	struct	{
-	    USHORT  AggSize14Count;
-	    USHORT  AggSize13Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT6_STRUC, *PTX_AGG_CNT6_STRUC;
-#else
 typedef	union	_TX_AGG_CNT6_STRUC	{
 	struct	{
 	    USHORT  AggSize13Count;
@@ -1492,17 +910,8 @@
 	}	field;
 	UINT32			word;
 }	TX_AGG_CNT6_STRUC, *PTX_AGG_CNT6_STRUC;
-#endif
+
 #define TX_AGG_CNT7		0x173c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT7_STRUC	{
-	struct	{
-	    USHORT  AggSize16Count;
-	    USHORT  AggSize15Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT7_STRUC, *PTX_AGG_CNT7_STRUC;
-#else
 typedef	union	_TX_AGG_CNT7_STRUC	{
 	struct	{
 	    USHORT  AggSize15Count;
@@ -1510,17 +919,8 @@
 	}	field;
 	UINT32			word;
 }	TX_AGG_CNT7_STRUC, *PTX_AGG_CNT7_STRUC;
-#endif
+
 #define MPDU_DENSITY_CNT		0x1740
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MPDU_DEN_CNT_STRUC	{
-	struct	{
-	    USHORT  RXZeroDelCount;	//RX zero length delimiter count
-	    USHORT  TXZeroDelCount;	//TX zero length delimiter count
-	}	field;
-	UINT32			word;
-}	MPDU_DEN_CNT_STRUC, *PMPDU_DEN_CNT_STRUC;
-#else
 typedef	union	_MPDU_DEN_CNT_STRUC	{
 	struct	{
 	    USHORT  TXZeroDelCount;	//TX zero length delimiter count
@@ -1528,7 +928,7 @@
 	}	field;
 	UINT32			word;
 }	MPDU_DEN_CNT_STRUC, *PMPDU_DEN_CNT_STRUC;
-#endif
+
 //
 // TXRX control registers - base address 0x3000
 //
@@ -1554,52 +954,28 @@
 #define SHAREDKEYTABLE			0
 #define PAIRWISEKEYTABLE			1
 
+typedef	union	_SHAREDKEY_MODE_STRUC	{
+	struct	{
+		UINT32       Bss0Key0CipherAlg:3;
+		UINT32       :1;
+		UINT32       Bss0Key1CipherAlg:3;
+		UINT32       :1;
+		UINT32       Bss0Key2CipherAlg:3;
+		UINT32       :1;
+		UINT32       Bss0Key3CipherAlg:3;
+		UINT32       :1;
+		UINT32       Bss1Key0CipherAlg:3;
+		UINT32       :1;
+		UINT32       Bss1Key1CipherAlg:3;
+		UINT32       :1;
+		UINT32       Bss1Key2CipherAlg:3;
+		UINT32       :1;
+		UINT32       Bss1Key3CipherAlg:3;
+		UINT32       :1;
+	}	field;
+	UINT32			word;
+}	SHAREDKEY_MODE_STRUC, *PSHAREDKEY_MODE_STRUC;
 
-#ifdef RT_BIG_ENDIAN
-typedef	union	_SHAREDKEY_MODE_STRUC	{
-	struct	{
-		UINT32       :1;
-		UINT32       Bss1Key3CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key0CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key3CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key0CipherAlg:3;
-	}	field;
-	UINT32			word;
-}	SHAREDKEY_MODE_STRUC, *PSHAREDKEY_MODE_STRUC;
-#else
-typedef	union	_SHAREDKEY_MODE_STRUC	{
-	struct	{
-		UINT32       Bss0Key0CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key3CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key0CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key3CipherAlg:3;
-		UINT32       :1;
-	}	field;
-	UINT32			word;
-}	SHAREDKEY_MODE_STRUC, *PSHAREDKEY_MODE_STRUC;
-#endif
 // 64-entry for pairwise key table
 typedef struct _HW_WCID_ENTRY {  // 8-byte per entry
     UCHAR   Address[6];
@@ -1670,10 +1046,16 @@
 #define E2PROM_CSR          0x0004
 #define IO_CNTL_CSR         0x77d0
 
+#ifdef RT2860
 // 8051 firmware image for RT2860 - base address = 0x4000
 #define FIRMWARE_IMAGE_BASE     0x2000
 #define MAX_FIRMWARE_IMAGE_SIZE 0x2000    // 8kbyte
-
+#endif
+#ifdef RT2870
+// 8051 firmware image for usb - use last-half base address = 0x3000
+#define FIRMWARE_IMAGE_BASE     0x3000
+#define MAX_FIRMWARE_IMAGE_SIZE 0x1000    // 4kbyte
+#endif // RT2870 //
 
 // ================================================================
 // Tx /	Rx / Mgmt ring descriptor definition
@@ -1754,6 +1136,9 @@
 #define BBP_R22                     22
 #define BBP_R24                     24
 #define BBP_R25                     25
+#ifdef RT30xx
+#define BBP_R31                     31
+#endif
 #define BBP_R49                     49 //TSSI
 #define BBP_R50                     50
 #define BBP_R51                     51
@@ -1771,6 +1156,10 @@
 #define BBP_R73                     73
 #define BBP_R75						75
 #define BBP_R77                     77
+#ifdef RT30xx
+#define BBP_R79                     79
+#define BBP_R80                     80
+#endif
 #define BBP_R81                     81
 #define BBP_R82                     82
 #define BBP_R83                     83
@@ -1792,6 +1181,9 @@
 #define BBP_R121                    121
 #define BBP_R122                    122
 #define BBP_R123                    123
+#ifdef RT30xx
+#define BBP_R138                    138 // add by johnli, RF power sequence setup, ADC dynamic on/off control
+#endif // RT30xx //
 
 
 #define BBPR94_DEFAULT              0x06 // Add 1 value will gain 1db
@@ -1872,15 +1264,6 @@
 //8.1.2	IV/EIV  format  : 2DW
 
 //8.1.3	RX attribute entry format  : 1DW
-#ifdef RT_BIG_ENDIAN
-typedef	struct	_MAC_ATTRIBUTE_STRUC {
-	UINT32		rsv:22;
-	UINT32		RXWIUDF:3;
-	UINT32		BSSIDIdx:3; //multipleBSS index for the WCID
-	UINT32		PairKeyMode:3;
-	UINT32		KeyTab:1;	// 0 for shared key table.  1 for pairwise key table
-}	MAC_ATTRIBUTE_STRUC, *PMAC_ATTRIBUTE_STRUC;
-#else
 typedef	struct	_MAC_ATTRIBUTE_STRUC {
 	UINT32		KeyTab:1;	// 0 for shared key table.  1 for pairwise key table
 	UINT32		PairKeyMode:3;
@@ -1888,8 +1271,6 @@
 	UINT32		RXWIUDF:3;
 	UINT32		rsv:22;
 }	MAC_ATTRIBUTE_STRUC, *PMAC_ATTRIBUTE_STRUC;
-#endif
-
 
 // =================================================================================
 // TX / RX ring descriptor format
@@ -1904,29 +1285,6 @@
 //
 // TX descriptor format, Tx	ring, Mgmt Ring
 //
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _TXD_STRUC {
-	// Word 0
-	UINT32		SDPtr0;
-	// Word 1
-	UINT32		DMADONE:1;
-	UINT32		LastSec0:1;
-	UINT32		SDLen0:14;
-	UINT32		Burst:1;
-	UINT32		LastSec1:1;
-	UINT32		SDLen1:14;
-	// Word 2
-	UINT32		SDPtr1;
-	// Word 3
-	UINT32		ICO:1;
-	UINT32		UCO:1;
-	UINT32		TCO:1;
-	UINT32		rsv:2;
-	UINT32		QSEL:2;	// select on-chip FIFO ID for 2nd-stage output scheduler.0:MGMT, 1:HCCA 2:EDCA
-	UINT32		WIV:1;	// Wireless Info Valid. 1 if Driver already fill WI,  o if DMA needs to copy WI to correctposition
-	UINT32		rsv2:24;
-}	TXD_STRUC, *PTXD_STRUC;
-#else
 typedef	struct	PACKED _TXD_STRUC {
 	// Word	0
 	UINT32		SDPtr0;
@@ -1948,8 +1306,6 @@
 	UINT32		UCO:1;	//
 	UINT32		ICO:1;	//
 }	TXD_STRUC, *PTXD_STRUC;
-#endif
-
 
 //
 // TXD Wireless Information format for Tx ring and Mgmt Ring
@@ -1957,40 +1313,6 @@
 //txop : for txop mode
 // 0:txop for the MPDU frame will be handles by ASIC by register
 // 1/2/3:the MPDU frame is send after PIFS/backoff/SIFS
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _TXWI_STRUC {
-	// Word 0
-	UINT32		PHYMODE:2;
-	UINT32		TxBF:1;	// 3*3
-	UINT32		rsv2:1;
-	UINT32		Ifs:1;	//
-	UINT32		STBC:2;	//channel bandwidth 20MHz or 40 MHz
-	UINT32		ShortGI:1;
-	UINT32		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	UINT32		MCS:7;
-
-	UINT32		rsv:6;
-	UINT32		txop:2;	//tx back off mode 0:HT TXOP rule , 1:PIFS TX ,2:Backoff, 3:sifs only when previous frame exchange is successful.
-	UINT32		MpduDensity:3;
-	UINT32		AMPDU:1;
-
-	UINT32		TS:1;
-	UINT32		CFACK:1;
-	UINT32		MIMOps:1;	// the remote peer is in dynamic MIMO-PS mode
-	UINT32		FRAG:1;		// 1 to inform TKIP engine this is a fragment.
-	// Word 1
-	UINT32		PacketId:4;
-	UINT32		MPDUtotalByteCount:12;
-	UINT32		WirelessCliID:8;
-	UINT32		BAWinSize:6;
-	UINT32		NSEQ:1;
-	UINT32		ACK:1;
-	// Word 2
-	UINT32		IV;
-	// Word 3
-	UINT32		EIV;
-}	TXWI_STRUC, *PTXWI_STRUC;
-#else
 typedef	struct	PACKED _TXWI_STRUC {
 	// Word	0
 	UINT32		FRAG:1;		// 1 to inform TKIP engine this is a fragment.
@@ -2023,45 +1345,11 @@
 	//Word3
 	UINT32		EIV;
 }	TXWI_STRUC, *PTXWI_STRUC;
-#endif
+
 //
 // Rx descriptor format, Rx	Ring
 //
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _RXD_STRUC	{
-	// Word 0
-	UINT32		SDP0;
-	// Word 1
-	UINT32		DDONE:1;
-	UINT32		LS0:1;
-	UINT32		SDL0:14;
-	UINT32		Rsv:2;
-	UINT32		SDL1:14;
-	// Word 2
-	UINT32		SDP1;
-	// Word 3
-	UINT32		Rsv1:13;
-	UINT32		PlcpRssil:1;// To be moved
-	UINT32		PlcpSignal:1;		// To be moved
-	UINT32		Decrypted:1;	// this frame is being decrypted.
-	UINT32		AMPDU:1;
-	UINT32		L2PAD:1;
-	UINT32		RSSI:1;
-	UINT32		HTC:1;
-	UINT32		AMSDU:1;		// rx with 802.3 header, not 802.11 header. obsolete.
-	UINT32		CipherErr:2;        // 0: decryption okay, 1:ICV error, 2:MIC error, 3:KEY not valid
-	UINT32		Crc:1;              // 1: CRC error
-	UINT32		MyBss:1;  	// 1: this frame belongs to the same BSSID
-	UINT32		Bcast:1;            // 1: this is a broadcast frame
-	UINT32		Mcast:1;            // 1: this is a multicast frame
-	UINT32		U2M:1;              // 1: this RX frame is unicast to me
-	UINT32		FRAG:1;
-	UINT32		NULLDATA:1;
-	UINT32		DATA:1;
-	UINT32		BA:1;
-
-}	RXD_STRUC, *PRXD_STRUC, RT28XX_RXD_STRUC, *PRT28XX_RXD_STRUC;
-#else
+#ifdef RT2860
 typedef	struct	PACKED _RXD_STRUC	{
 	// Word	0
 	UINT32		SDP0;
@@ -2094,39 +1382,11 @@
 	UINT32		PlcpRssil:1;// To be moved
 	UINT32		Rsv1:13;
 }	RXD_STRUC, *PRXD_STRUC, RT28XX_RXD_STRUC, *PRT28XX_RXD_STRUC;
-#endif
+#endif /* RT2860 */
+
 //
 // RXWI wireless information format, in PBF. invisible in driver.
 //
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _RXWI_STRUC {
-	// Word 0
-	UINT32		TID:4;
-	UINT32		MPDUtotalByteCount:12;
-	UINT32		UDF:3;
-	UINT32		BSSID:3;
-	UINT32		KeyIndex:2;
-	UINT32		WirelessCliID:8;
-	// Word 1
-	UINT32		PHYMODE:2;              // 1: this RX frame is unicast to me
-	UINT32		rsv:3;
-	UINT32		STBC:2;
-	UINT32		ShortGI:1;
-	UINT32		BW:1;
-	UINT32		MCS:7;
-	UINT32		SEQUENCE:12;
-	UINT32		FRAG:4;
-	// Word 2
-	UINT32		rsv1:8;
-	UINT32		RSSI2:8;
-	UINT32		RSSI1:8;
-	UINT32		RSSI0:8;
-	// Word 3
-	UINT32		rsv2:16;
-	UINT32		SNR1:8;
-	UINT32		SNR0:8;
-}	RXWI_STRUC, *PRXWI_STRUC;
-#else
 typedef	struct	PACKED _RXWI_STRUC {
 	// Word	0
 	UINT32		WirelessCliID:8;
@@ -2154,8 +1414,6 @@
 	UINT32		SNR1:8;
 	UINT32		rsv2:16;
 }	RXWI_STRUC, *PRXWI_STRUC;
-#endif
-
 
 // =================================================================================
 // HOST-MCU communication data structure
@@ -2164,17 +1422,6 @@
 //
 // H2M_MAILBOX_CSR: Host-to-MCU Mailbox
 //
-#ifdef RT_BIG_ENDIAN
-typedef union  _H2M_MAILBOX_STRUC {
-    struct {
-        UINT32       Owner:8;
-        UINT32       CmdToken:8;    // 0xff tells MCU not to report CmdDoneInt after excuting the command
-        UINT32       HighByte:8;
-        UINT32       LowByte:8;
-    }   field;
-    UINT32           word;
-} H2M_MAILBOX_STRUC, *PH2M_MAILBOX_STRUC;
-#else
 typedef union  _H2M_MAILBOX_STRUC {
     struct {
         UINT32       LowByte:8;
@@ -2184,22 +1431,10 @@
     }   field;
     UINT32           word;
 } H2M_MAILBOX_STRUC, *PH2M_MAILBOX_STRUC;
-#endif
 
 //
 // M2H_CMD_DONE_CSR: MCU-to-Host command complete indication
 //
-#ifdef RT_BIG_ENDIAN
-typedef union _M2H_CMD_DONE_STRUC {
-    struct  {
-        UINT32       CmdToken3;
-        UINT32       CmdToken2;
-        UINT32       CmdToken1;
-        UINT32       CmdToken0;
-    } field;
-    UINT32           word;
-} M2H_CMD_DONE_STRUC, *PM2H_CMD_DONE_STRUC;
-#else
 typedef union _M2H_CMD_DONE_STRUC {
     struct  {
         UINT32       CmdToken0;
@@ -2209,22 +1444,10 @@
     } field;
     UINT32           word;
 } M2H_CMD_DONE_STRUC, *PM2H_CMD_DONE_STRUC;
-#endif
-
-
 
 //
 // MCU_LEDCS: MCU LED Control Setting.
 //
-#ifdef RT_BIG_ENDIAN
-typedef union  _MCU_LEDCS_STRUC {
-	struct	{
-		UCHAR		Polarity:1;
-		UCHAR		LedMode:7;
-	} field;
-	UCHAR				word;
-} MCU_LEDCS_STRUC, *PMCU_LEDCS_STRUC;
-#else
 typedef union  _MCU_LEDCS_STRUC {
 	struct	{
 		UCHAR		LedMode:7;
@@ -2232,7 +1455,7 @@
 	} field;
 	UCHAR			word;
 } MCU_LEDCS_STRUC, *PMCU_LEDCS_STRUC;
-#endif
+
 // =================================================================================
 // Register format
 // =================================================================================
@@ -2240,18 +1463,6 @@
 
 
 //NAV_TIME_CFG :NAV
-#ifdef RT_BIG_ENDIAN
-typedef	union	_NAV_TIME_CFG_STRUC	{
-	struct	{
-		USHORT		rsv:6;
-		USHORT		ZeroSifs:1;               // Applied zero SIFS timer after OFDM RX 0: disable
-		USHORT		Eifs:9;               // in unit of 1-us
-		UCHAR       SlotTime;    // in unit of 1-us
-		UCHAR		Sifs;               // in unit of 1-us
-	}	field;
-	UINT32			word;
-}	NAV_TIME_CFG_STRUC, *PNAV_TIME_CFG_STRUC;
-#else
 typedef	union	_NAV_TIME_CFG_STRUC	{
 	struct	{
 		UCHAR		Sifs;               // in unit of 1-us
@@ -2262,44 +1473,10 @@
 	}	field;
 	UINT32			word;
 }	NAV_TIME_CFG_STRUC, *PNAV_TIME_CFG_STRUC;
-#endif
-
-
-
-
 
 //
 // RX_FILTR_CFG:  /RX configuration register
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	RX_FILTR_CFG_STRUC	{
-	struct	{
-		UINT32		:15;
-		UINT32       DropRsvCntlType:1;
-
-        	UINT32       	DropBAR:1;       //
-		UINT32		DropBA:1;		//
-		UINT32		DropPsPoll:1;		// Drop Ps-Poll
-		UINT32		DropRts:1;		// Drop Ps-Poll
-
-		UINT32		DropCts:1;		// Drop Ps-Poll
-		UINT32		DropAck:1;		// Drop Ps-Poll
-		UINT32		DropCFEnd:1;		// Drop Ps-Poll
-		UINT32		DropCFEndAck:1;		// Drop Ps-Poll
-
-		UINT32		DropDuplicate:1;		// Drop duplicate frame
-		UINT32		DropBcast:1;		// Drop broadcast frames
-		UINT32		DropMcast:1;		// Drop multicast frames
-		UINT32		DropVerErr:1;	    // Drop version error frame
-
-		UINT32		DropNotMyBSSID:1;			// Drop fram ToDs bit is true
-		UINT32		DropNotToMe:1;		// Drop not to me unicast frame
-		UINT32		DropPhyErr:1;		// Drop physical error
-		UINT32		DropCRCErr:1;		// Drop CRC error
-	}	field;
-	UINT32			word;
-}	RX_FILTR_CFG_STRUC, *PRX_FILTR_CFG_STRUC;
-#else
 typedef	union	_RX_FILTR_CFG_STRUC	{
 	struct	{
 		UINT32		DropCRCErr:1;		// Drop CRC error
@@ -2327,26 +1504,10 @@
 	}	field;
 	UINT32			word;
 }	RX_FILTR_CFG_STRUC, *PRX_FILTR_CFG_STRUC;
-#endif
-
-
-
 
 //
 // PHY_CSR4: RF serial control register
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_PHY_CSR4_STRUC	{
-	struct	{
-		UINT32		Busy:1;				// 1: ASIC is busy execute RF programming.
-		UINT32		PLL_LD:1;			// RF PLL_LD status
-		UINT32		IFSelect:1;			// 1: select IF	to program,	0: select RF to	program
-		UINT32		NumberOfBits:5;		// Number of bits used in RFRegValue (I:20,	RFMD:22)
-		UINT32		RFRegValue:24;		// Register	value (include register	id)	serial out to RF/IF	chip.
-	}	field;
-	UINT32			word;
-}	PHY_CSR4_STRUC, *PPHY_CSR4_STRUC;
-#else
 typedef	union	_PHY_CSR4_STRUC	{
 	struct	{
 		UINT32		RFRegValue:24;		// Register	value (include register	id)	serial out to RF/IF	chip.
@@ -2357,35 +1518,10 @@
 	}	field;
 	UINT32			word;
 }	PHY_CSR4_STRUC, *PPHY_CSR4_STRUC;
-#endif
-
 
 //
 // SEC_CSR5: shared key table security mode register
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_SEC_CSR5_STRUC	{
-	struct	{
-        UINT32       :1;
-        UINT32       Bss3Key3CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key2CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key1CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key0CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key3CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key2CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key1CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key0CipherAlg:3;
-	}	field;
-	UINT32			word;
-}	SEC_CSR5_STRUC, *PSEC_CSR5_STRUC;
-#else
 typedef	union	_SEC_CSR5_STRUC	{
 	struct	{
         UINT32       Bss2Key0CipherAlg:3;
@@ -2407,21 +1543,10 @@
 	}	field;
 	UINT32			word;
 }	SEC_CSR5_STRUC, *PSEC_CSR5_STRUC;
-#endif
-
 
 //
 // HOST_CMD_CSR: For HOST to interrupt embedded processor
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_HOST_CMD_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:24;
-	    UINT32   HostCommand:8;
-	}	field;
-	UINT32			word;
-}	HOST_CMD_CSR_STRUC, *PHOST_CMD_CSR_STRUC;
-#else
 typedef	union	_HOST_CMD_CSR_STRUC	{
 	struct	{
 	    UINT32   HostCommand:8;
@@ -2429,8 +1554,6 @@
 	}	field;
 	UINT32			word;
 }	HOST_CMD_CSR_STRUC, *PHOST_CMD_CSR_STRUC;
-#endif
-
 
 //
 // AIFSN_CSR: AIFSN for each EDCA AC
@@ -2441,21 +1564,6 @@
 //
 // E2PROM_CSR: EEPROM control register
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_E2PROM_CSR_STRUC	{
-	struct	{
-		UINT32		Rsvd:25;
-		UINT32       LoadStatus:1;   // 1:loading, 0:done
-		UINT32		Type:1;			// 1: 93C46, 0:93C66
-		UINT32		EepromDO:1;
-		UINT32		EepromDI:1;
-		UINT32		EepromCS:1;
-		UINT32		EepromSK:1;
-		UINT32		Reload:1;		// Reload EEPROM content, write one to reload, self-cleared.
-	}	field;
-	UINT32			word;
-}	E2PROM_CSR_STRUC, *PE2PROM_CSR_STRUC;
-#else
 typedef	union	_E2PROM_CSR_STRUC	{
 	struct	{
 		UINT32		Reload:1;		// Reload EEPROM content, write one to reload, self-cleared.
@@ -2469,8 +1577,6 @@
 	}	field;
 	UINT32			word;
 }	E2PROM_CSR_STRUC, *PE2PROM_CSR_STRUC;
-#endif
-
 
 // -------------------------------------------------------------------
 //  E2PROM data layout
@@ -2479,17 +1585,6 @@
 //
 // EEPROM antenna select format
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_ANTENNA_STRUC	{
-	struct	{
-		USHORT      Rsv:4;
-		USHORT      RfIcType:4;             // see E2PROM document
-		USHORT		TxPath:4;	// 1: 1T, 2: 2T
-		USHORT		RxPath:4;	// 1: 1R, 2: 2R, 3: 3R
-	}	field;
-	USHORT			word;
-}	EEPROM_ANTENNA_STRUC, *PEEPROM_ANTENNA_STRUC;
-#else
 typedef	union	_EEPROM_ANTENNA_STRUC	{
 	struct	{
 		USHORT		RxPath:4;	// 1: 1R, 2: 2R, 3: 3R
@@ -2499,26 +1594,7 @@
 	}	field;
 	USHORT			word;
 }	EEPROM_ANTENNA_STRUC, *PEEPROM_ANTENNA_STRUC;
-#endif
 
-#ifdef RT_BIG_ENDIAN
-typedef	union _EEPROM_NIC_CINFIG2_STRUC	{
-	struct	{
-        USHORT		Rsv2:6;					// must be 0
-		USHORT		BW40MAvailForA:1;			// 0:enable, 1:disable
-		USHORT		BW40MAvailForG:1;			// 0:enable, 1:disable
-		USHORT		EnableWPSPBC:1;                 // WPS PBC Control bit
-		USHORT		BW40MSidebandForA:1;
-		USHORT		BW40MSidebandForG:1;
-		USHORT		CardbusAcceleration:1;	// !!! NOTE: 0 - enable, 1 - disable
-		USHORT		ExternalLNAForA:1;			// external LNA enable for 5G
-		USHORT		ExternalLNAForG:1;			// external LNA enable for 2.4G
-		USHORT		DynamicTxAgcControl:1;			//
-		USHORT		HardwareRadioControl:1;	// Whether RF is controlled by driver or HW. 1:enable hw control, 0:disable
-	}	field;
-	USHORT			word;
-}	EEPROM_NIC_CONFIG2_STRUC, *PEEPROM_NIC_CONFIG2_STRUC;
-#else
 typedef	union _EEPROM_NIC_CINFIG2_STRUC	{
 	struct {
 		USHORT		HardwareRadioControl:1;	// 1:enable, 0:disable
@@ -2531,24 +1607,22 @@
 		USHORT		EnableWPSPBC:1;                 // WPS PBC Control bit
 		USHORT		BW40MAvailForG:1;			// 0:enable, 1:disable
 		USHORT		BW40MAvailForA:1;			// 0:enable, 1:disable
+#ifndef RT30xx
 		USHORT		Rsv2:6;                 // must be 0
+#endif
+#ifdef RT30xx
+		USHORT		Rsv1:1;					// must be 0
+		USHORT		AntDiversity:1;			// Antenna diversity
+		USHORT		Rsv2:3;					// must be 0
+		USHORT		DACTestBit:1;			// control if driver should patch the DAC issue
+#endif
 	}	field;
 	USHORT			word;
 }	EEPROM_NIC_CONFIG2_STRUC, *PEEPROM_NIC_CONFIG2_STRUC;
-#endif
 
 //
 // TX_PWR Value valid range 0xFA(-6) ~ 0x24(36)
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_TX_PWR_STRUC	{
-	struct	{
-		CHAR	Byte1;				// High Byte
-		CHAR	Byte0;				// Low Byte
-	}	field;
-	USHORT	word;
-}	EEPROM_TX_PWR_STRUC, *PEEPROM_TX_PWR_STRUC;
-#else
 typedef	union	_EEPROM_TX_PWR_STRUC	{
 	struct	{
 		CHAR	Byte0;				// Low Byte
@@ -2556,17 +1630,7 @@
 	}	field;
 	USHORT	word;
 }	EEPROM_TX_PWR_STRUC, *PEEPROM_TX_PWR_STRUC;
-#endif
 
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_VERSION_STRUC	{
-	struct	{
-		UCHAR	Version;			// High Byte
-		UCHAR	FaeReleaseNumber;	// Low Byte
-	}	field;
-	USHORT	word;
-}	EEPROM_VERSION_STRUC, *PEEPROM_VERSION_STRUC;
-#else
 typedef	union	_EEPROM_VERSION_STRUC	{
 	struct	{
 		UCHAR	FaeReleaseNumber;	// Low Byte
@@ -2574,25 +1638,7 @@
 	}	field;
 	USHORT	word;
 }	EEPROM_VERSION_STRUC, *PEEPROM_VERSION_STRUC;
-#endif
 
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_LED_STRUC	{
-	struct	{
-		USHORT	Rsvd:3;				// Reserved
-		USHORT	LedMode:5;			// Led mode.
-		USHORT	PolarityGPIO_4:1;	// Polarity GPIO#4 setting.
-		USHORT	PolarityGPIO_3:1;	// Polarity GPIO#3 setting.
-		USHORT	PolarityGPIO_2:1;	// Polarity GPIO#2 setting.
-		USHORT	PolarityGPIO_1:1;	// Polarity GPIO#1 setting.
-		USHORT	PolarityGPIO_0:1;	// Polarity GPIO#0 setting.
-		USHORT	PolarityACT:1;		// Polarity ACT setting.
-		USHORT	PolarityRDY_A:1;		// Polarity RDY_A setting.
-		USHORT	PolarityRDY_G:1;		// Polarity RDY_G setting.
-	}	field;
-	USHORT	word;
-}	EEPROM_LED_STRUC, *PEEPROM_LED_STRUC;
-#else
 typedef	union	_EEPROM_LED_STRUC	{
 	struct	{
 		USHORT	PolarityRDY_G:1;		// Polarity RDY_G setting.
@@ -2608,18 +1654,7 @@
 	}	field;
 	USHORT	word;
 }	EEPROM_LED_STRUC, *PEEPROM_LED_STRUC;
-#endif
 
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_TXPOWER_DELTA_STRUC	{
-	struct	{
-		UCHAR	TxPowerEnable:1;// Enable
-		UCHAR	Type:1;			// 1: plus the delta value, 0: minus the delta value
-		UCHAR	DeltaValue:6;	// Tx Power dalta value (MAX=4)
-	}	field;
-	UCHAR	value;
-}	EEPROM_TXPOWER_DELTA_STRUC, *PEEPROM_TXPOWER_DELTA_STRUC;
-#else
 typedef	union	_EEPROM_TXPOWER_DELTA_STRUC	{
 	struct	{
 		UCHAR	DeltaValue:6;	// Tx Power dalta value (MAX=4)
@@ -2628,22 +1663,10 @@
 	}	field;
 	UCHAR	value;
 }	EEPROM_TXPOWER_DELTA_STRUC, *PEEPROM_TXPOWER_DELTA_STRUC;
-#endif
 
 //
 // QOS_CSR0: TXOP holder address0 register
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_QOS_CSR0_STRUC	{
-	struct	{
-		UCHAR		Byte3;		// MAC address byte 3
-		UCHAR		Byte2;		// MAC address byte 2
-		UCHAR		Byte1;		// MAC address byte 1
-		UCHAR		Byte0;		// MAC address byte 0
-	}	field;
-	UINT32			word;
-}	QOS_CSR0_STRUC, *PQOS_CSR0_STRUC;
-#else
 typedef	union	_QOS_CSR0_STRUC	{
 	struct	{
 		UCHAR		Byte0;		// MAC address byte 0
@@ -2653,22 +1676,10 @@
 	}	field;
 	UINT32			word;
 }	QOS_CSR0_STRUC, *PQOS_CSR0_STRUC;
-#endif
 
 //
 // QOS_CSR1: TXOP holder address1 register
 //
-#ifdef RT_BIG_ENDIAN
-typedef	union	_QOS_CSR1_STRUC	{
-	struct	{
-		UCHAR		Rsvd1;
-		UCHAR		Rsvd0;
-		UCHAR		Byte5;		// MAC address byte 5
-		UCHAR		Byte4;		// MAC address byte 4
-	}	field;
-	UINT32			word;
-}	QOS_CSR1_STRUC, *PQOS_CSR1_STRUC;
-#else
 typedef	union	_QOS_CSR1_STRUC	{
 	struct	{
 		UCHAR		Byte4;		// MAC address byte 4
@@ -2678,22 +1689,8 @@
 	}	field;
 	UINT32			word;
 }	QOS_CSR1_STRUC, *PQOS_CSR1_STRUC;
-#endif
 
 #define	RF_CSR_CFG	0x500
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG_STRUC	{
-	struct	{
-		UINT	Rsvd1:14;				// Reserved
-		UINT	RF_CSR_KICK:1;			// kick RF register read/write
-		UINT	RF_CSR_WR:1;			// 0: read  1: write
-		UINT	Rsvd2:3;				// Reserved
-		UINT	TESTCSR_RFACC_REGNUM:5;	// RF register ID
-		UINT	RF_CSR_DATA:8;			// DATA
-	}	field;
-	UINT	word;
-}	RF_CSR_CFG_STRUC, *PRF_CSR_CFG_STRUC;
-#else
 typedef	union	_RF_CSR_CFG_STRUC	{
 	struct	{
 		UINT	RF_CSR_DATA:8;			// DATA
@@ -2705,6 +1702,5 @@
 	}	field;
 	UINT	word;
 }	RF_CSR_CFG_STRUC, *PRF_CSR_CFG_STRUC;
-#endif
 
 #endif	// __RT28XX_H__
diff --git a/drivers/staging/rt2860/rt_ate.c b/drivers/staging/rt2860/rt_ate.c
deleted file mode 100644
index 1ed73c9..0000000
--- a/drivers/staging/rt2860/rt_ate.c
+++ /dev/null
@@ -1,6009 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#include "rt_config.h"
-
-#ifdef RALINK_ATE
-UCHAR TemplateFrame[24] = {0x08/* Data type */,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0xAA,0xBB,0x12,0x34,0x56,0x00,0x11,0x22,0xAA,0xBB,0xCC,0x00,0x00};	// 802.11 MAC Header, Type:Data, Length:24bytes
-extern RTMP_RF_REGS RF2850RegTable[];
-extern UCHAR NUM_OF_2850_CHNL;
-
-static CHAR CCKRateTable[] = {0, 1, 2, 3, 8, 9, 10, 11, -1}; /* CCK Mode. */
-static CHAR OFDMRateTable[] = {0, 1, 2, 3, 4, 5, 6, 7, -1}; /* OFDM Mode. */
-static CHAR HTMIXRateTable[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1}; /* HT Mix Mode. */
-
-static INT TxDmaBusy(
-	IN PRTMP_ADAPTER pAd);
-
-static INT RxDmaBusy(
-	IN PRTMP_ADAPTER pAd);
-
-static VOID RtmpDmaEnable(
-	IN PRTMP_ADAPTER pAd,
-	IN INT Enable);
-
-static VOID BbpSoftReset(
-	IN PRTMP_ADAPTER pAd);
-
-static VOID RtmpRfIoWrite(
-	IN PRTMP_ADAPTER pAd);
-
-static INT ATESetUpFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT32 TxIdx);
-
-static INT ATETxPwrHandler(
-	IN PRTMP_ADAPTER pAd,
-	IN char index);
-
-static INT ATECmdHandler(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-static int CheckMCSValid(
-	IN UCHAR Mode,
-	IN UCHAR Mcs);
-
-static VOID ATEWriteTxWI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXWI_STRUC 	pOutTxWI,
-	IN	BOOLEAN			FRAG,
-	IN	BOOLEAN			CFACK,
-	IN	BOOLEAN			InsTimestamp,
-	IN	BOOLEAN 		AMPDU,
-	IN	BOOLEAN 		Ack,
-	IN	BOOLEAN 		NSeq,		// HW new a sequence.
-	IN	UCHAR			BASize,
-	IN	UCHAR			WCID,
-	IN	ULONG			Length,
-	IN	UCHAR 			PID,
-	IN	UCHAR			TID,
-	IN	UCHAR			TxRate,
-	IN	UCHAR			Txopmode,
-	IN	BOOLEAN			CfAck,
-	IN	HTTRANSMIT_SETTING	*pTransmit);
-
-
-static VOID SetJapanFilter(
-	IN	PRTMP_ADAPTER	pAd);
-
-/*=========================end of prototype=========================*/
-
-static INT TxDmaBusy(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT result;
-	WPDMA_GLO_CFG_STRUC GloCfg;
-
-	RTMP_IO_READ32(pAd, WPDMA_GLO_CFG, &GloCfg.word);	// disable DMA
-	if (GloCfg.field.TxDMABusy)
-		result = 1;
-	else
-		result = 0;
-
-	return result;
-}
-
-static INT RxDmaBusy(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT result;
-	WPDMA_GLO_CFG_STRUC GloCfg;
-
-	RTMP_IO_READ32(pAd, WPDMA_GLO_CFG, &GloCfg.word);	// disable DMA
-	if (GloCfg.field.RxDMABusy)
-		result = 1;
-	else
-		result = 0;
-
-	return result;
-}
-
-static VOID RtmpDmaEnable(
-	IN PRTMP_ADAPTER pAd,
-	IN INT Enable)
-{
-	BOOLEAN value;
-	ULONG WaitCnt;
-	WPDMA_GLO_CFG_STRUC GloCfg;
-
-	value = Enable > 0 ? 1 : 0;
-
-	// check DMA is in busy mode.
-	WaitCnt = 0;
-	while (TxDmaBusy(pAd) || RxDmaBusy(pAd))
-	{
-		RTMPusecDelay(10);
-		if (WaitCnt++ > 100)
-			break;
-	}
-
-	RTMP_IO_READ32(pAd, WPDMA_GLO_CFG, &GloCfg.word);	// disable DMA
-	GloCfg.field.EnableTxDMA = value;
-	GloCfg.field.EnableRxDMA = value;
-	RTMP_IO_WRITE32(pAd, WPDMA_GLO_CFG, GloCfg.word);	// abort all TX rings
-	RTMPusecDelay(5000);
-
-	return;
-}
-
-
-static VOID BbpSoftReset(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR BbpData = 0;
-
-	// Soft reset, set BBP R21 bit0=1->0
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R21, &BbpData);
-	BbpData |= 0x00000001; //set bit0=1
-	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R21, BbpData);
-
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R21, &BbpData);
-	BbpData &= ~(0x00000001); //set bit0=0
-	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R21, BbpData);
-
-	return;
-}
-
-static VOID RtmpRfIoWrite(
-	IN PRTMP_ADAPTER pAd)
-{
-	// Set RF value 1's set R3[bit2] = [0]
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-	RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-	RTMPusecDelay(200);
-
-	// Set RF value 2's set R3[bit2] = [1]
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-	RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 | 0x04));
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-	RTMPusecDelay(200);
-
-	// Set RF value 3's set R3[bit2] = [0]
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-	RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-	return;
-}
-
-static int CheckMCSValid(
-	UCHAR Mode,
-	UCHAR Mcs)
-{
-	int i;
-	PCHAR pRateTab;
-
-	switch(Mode)
-	{
-		case 0:
-			pRateTab = CCKRateTable;
-			break;
-		case 1:
-			pRateTab = OFDMRateTable;
-			break;
-		case 2:
-		case 3:
-			pRateTab = HTMIXRateTable;
-			break;
-		default:
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("unrecognizable Tx Mode %d\n", Mode));
-			return -1;
-			break;
-	}
-
-	i = 0;
-	while(pRateTab[i] != -1)
-	{
-		if (pRateTab[i] == Mcs)
-			return 0;
-		i++;
-	}
-
-	return -1;
-}
-
-#if 1
-static INT ATETxPwrHandler(
-	IN PRTMP_ADAPTER pAd,
-	IN char index)
-{
-	ULONG R;
-	CHAR TxPower;
-	UCHAR Bbp94 = 0;
-	BOOLEAN bPowerReduce = FALSE;
-
-#ifdef RALINK_28xx_QA
-	if ((pAd->ate.bQATxStart == TRUE) || (pAd->ate.bQARxStart == TRUE))
-	{
-		/* When QA is used for Tx, pAd->ate.TxPower0/1 and real tx power
-		** are not synchronized.
-		*/
-/*
-		pAd->ate.TxPower0 = pAd->LatchRfRegs.xxx;
-		pAd->ate.TxPower1 = pAd->LatchRfRegs.xxx;
-*/
-		return 0;
-	}
-	else
-#endif // RALINK_28xx_QA //
-	{
-		TxPower = index == 0 ? pAd->ate.TxPower0 : pAd->ate.TxPower1;
-
-		if (pAd->ate.Channel <= 14)
-		{
-			if (TxPower > 31)
-			{
-				//
-				// R3, R4 can't large than 31 (0x24), 31 ~ 36 used by BBP 94
-				//
-				R = 31;
-				if (TxPower <= 36)
-					Bbp94 = BBPR94_DEFAULT + (UCHAR)(TxPower - 31);
-			}
-			else if (TxPower < 0)
-			{
-				//
-				// R3, R4 can't less than 0, -1 ~ -6 used by BBP 94
-				//
-				R = 0;
-				if (TxPower >= -6)
-					Bbp94 = BBPR94_DEFAULT + TxPower;
-			}
-			else
-			{
-				// 0 ~ 31
-				R = (ULONG) TxPower;
-				Bbp94 = BBPR94_DEFAULT;
-			}
-
-			ATEDBGPRINT(RT_DEBUG_TRACE, ("%s (TxPower=%d, R=%ld, BBP_R94=%d)\n", __func__, TxPower, R, Bbp94));
-		}
-		else// 5.5 GHz
-		{
-			if (TxPower > 15)
-			{
-				//
-				// R3, R4 can't large than 15 (0x0F)
-				//
-				R = 15;
-			}
-			else if (TxPower < 0)
-			{
-				//
-				// R3, R4 can't less than 0
-				//
-				// -1 ~ -7
-				ASSERT((TxPower >= -7));
-				R = (ULONG)(TxPower + 7);
-				bPowerReduce = TRUE;
-			}
-			else
-			{
-				// 0 ~ 15
-				R = (ULONG) TxPower;
-			}
-
-			ATEDBGPRINT(RT_DEBUG_TRACE, ("%s (TxPower=%d, R=%lu)\n", __func__, TxPower, R));
-		}
-
-		if (pAd->ate.Channel <= 14)
-		{
-			if (index == 0)
-			{
-				R = R << 9;		// shift TX power control to correct RF(R3) register bit position
-				R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-				pAd->LatchRfRegs.R3 = R;
-			}
-			else
-			{
-				R = R << 6;		// shift TX power control to correct RF(R4) register bit position
-				R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-				pAd->LatchRfRegs.R4 = R;
-			}
-		}
-		else// 5.5GHz
-		{
-			if (bPowerReduce == FALSE)
-			{
-				if (index == 0)
-				{
-					R = (R << 10) | (1 << 9);		// shift TX power control to correct RF(R3) register bit position
-					R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-					pAd->LatchRfRegs.R3 = R;
-				}
-				else
-				{
-					R = (R << 7) | (1 << 6);		// shift TX power control to correct RF(R4) register bit position
-					R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-					pAd->LatchRfRegs.R4 = R;
-				}
-			}
-			else
-			{
-				if (index == 0)
-				{
-					R = (R << 10);		// shift TX power control to correct RF(R3) register bit position
-					R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-
-					/* Clear bit 9 of R3 to reduce 7dB. */
-					pAd->LatchRfRegs.R3 = (R & (~(1 << 9)));
-				}
-				else
-				{
-					R = (R << 7);		// shift TX power control to correct RF(R4) register bit position
-					R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-
-					/* Clear bit 6 of R4 to reduce 7dB. */
-					pAd->LatchRfRegs.R4 = (R & (~(1 << 6)));
-				}
-			}
-		}
-
-		RtmpRfIoWrite(pAd);
-
-		return 0;
-	}
-}
-#else// 1 //
-static INT ATETxPwrHandler(
-	IN PRTMP_ADAPTER pAd,
-	IN char index)
-{
-	ULONG R;
-	CHAR TxPower;
-	UCHAR Bbp94 = 0;
-
-#ifdef RALINK_28xx_QA
-	if ((pAd->ate.bQATxStart == TRUE) || (pAd->ate.bQARxStart == TRUE))
-	{
-		// TODO: how to get current TxPower0/1 from pAd->LatchRfRegs ?
-		/* When QA is used for Tx, pAd->ate.TxPower0/1 and real tx power
-		** are not synchronized.
-		*/
-/*
-		pAd->ate.TxPower0 = pAd->LatchRfRegs.xxx;
-		pAd->ate.TxPower1 = pAd->LatchRfRegs.xxx;
-*/
-		return 0;
-	}
-	else
-#endif // RALINK_28xx_QA //
-	{
-		TxPower = index == 0 ? pAd->ate.TxPower0 : pAd->ate.TxPower1;
-
-	if (TxPower > 31)
-	{
-		//
-		// R3, R4 can't large than 36 (0x24), 31 ~ 36 used by BBP 94
-		//
-		R = 31;
-		if (TxPower <= 36)
-			Bbp94 = BBPR94_DEFAULT + (UCHAR)(TxPower - 31);
-	}
-	else if (TxPower < 0)
-	{
-		//
-		// R3, R4 can't less than 0, -1 ~ -6 used by BBP 94
-		//
-		R = 0;
-		if (TxPower >= -6)
-			Bbp94 = BBPR94_DEFAULT + TxPower;
-	}
-	else
-	{
-		// 0 ~ 31
-		R = (ULONG) TxPower;
-		Bbp94 = BBPR94_DEFAULT;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("%s (TxPower=%d, R3=%ld, BBP_R94=%d)\n", __func__, TxPower, R, Bbp94));
-
-		if (pAd->ate.Channel <= 14)
-		{
-	if (index == 0)
-	{
-		R = R << 9;		// shift TX power control to correct RF(R3) register bit position
-		R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-		pAd->LatchRfRegs.R3 = R;
-	}
-	else
-	{
-		R = R << 6;		// shift TX power control to correct RF(R4) register bit position
-		R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-		pAd->LatchRfRegs.R4 = R;
-	}
-		}
-		else
-		{
-			if (index == 0)
-			{
-				R = (R << 10) | (1 << 9);		// shift TX power control to correct RF(R3) register bit position
-				R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-				pAd->LatchRfRegs.R3 = R;
-			}
-			else
-			{
-				R = (R << 7) | (1 << 6);		// shift TX power control to correct RF(R4) register bit position
-				R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-				pAd->LatchRfRegs.R4 = R;
-			}
-		}
-
-	RtmpRfIoWrite(pAd);
-
-	return 0;
-	}
-}
-#endif // 1 //
-/*
-    ==========================================================================
-    Description:
-        Set ATE operation mode to
-        0. ATESTART  = Start ATE Mode
-        1. ATESTOP   = Stop ATE Mode
-        2. TXCONT    = Continuous Transmit
-        3. TXCARR    = Transmit Carrier
-        4. TXFRAME   = Transmit Frames
-        5. RXFRAME   = Receive Frames
-#ifdef RALINK_28xx_QA
-        6. TXSTOP    = Stop Any Type of Transmition
-        7. RXSTOP    = Stop Receiving Frames
-#endif // RALINK_28xx_QA //
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-static INT	ATECmdHandler(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT32			Value = 0;
-	UCHAR			BbpData;
-	UINT32			MacData = 0;
-	PTXD_STRUC		pTxD;
-	INT				index;
-	UINT			i=0, atemode;
-	PRXD_STRUC		pRxD;
-	PRTMP_TX_RING 	pTxRing = &pAd->TxRing[QID_AC_BE];
-#ifndef UCOS
-	NDIS_STATUS		Status = NDIS_STATUS_SUCCESS;
-#endif // UCOS //
-#ifdef	RT_BIG_ENDIAN
-    PTXD_STRUC      pDestTxD;
-    TXD_STRUC       TxD;
-#endif
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("===> ATECmdHandler()\n"));
-
-	ATEAsicSwitchChannel(pAd);
-	AsicLockChannel(pAd, pAd->ate.Channel);
-
-	RTMPusecDelay(5000);
-
-	// read MAC_SYS_CTRL and backup MAC_SYS_CTRL value.
-	RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-
-	// Default value in BBP R22 is 0x0.
-	BbpData = 0;
-
-	// clean bit4 to stop continuous Tx production test.
-	MacData &= 0xFFFFFFEF;
-
-	if (!strcmp(arg, "ATESTART")) 		//Enter ATE mode and set Tx/Rx Idle
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: ATESTART\n"));
-
-#ifndef UCOS
-		// check if we have removed the firmware
-		if (!(ATE_ON(pAd)))
-		{
-			NICEraseFirmware(pAd);
-		}
-#endif // !UCOS //
-		atemode = pAd->ate.Mode;
-		pAd->ate.Mode = ATE_START;
-//		pAd->ate.TxDoneCount = pAd->ate.TxCount;
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-		if (atemode & ATE_TXCARR)
-		{
-			// No Carrier Test set BBP R22 bit7=0, bit6=0, bit[5~0]=0x0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF00; //clear bit7, bit6, bit[5~0]
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		}
-		else if (atemode & ATE_TXCARRSUPP)
-		{
-			// No Cont. TX set BBP R22 bit7=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= ~(1 << 7); //set bit7=0
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-			// No Carrier Suppression set BBP R24 bit0=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R24, &BbpData);
-			BbpData &= 0xFFFFFFFE; //clear bit0
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, BbpData);
-		}
-		// We should free some resource which was allocated when ATE_TXFRAME , ATE_STOP, and ATE_TXCONT.
-		else if ((atemode & ATE_TXFRAME) || (atemode == ATE_STOP))
-		{
-			PRTMP_TX_RING pTxRing = &pAd->TxRing[QID_AC_BE];
-
-			if (atemode & ATE_TXCONT)
-			{
-				// No Cont. TX set BBP R22 bit7=0
-				ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-				BbpData &= ~(1 << 7); //set bit7=0
-				ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-			}
-			// Abort Tx, Rx DMA.
-			RtmpDmaEnable(pAd, 0);
-			for (i=0; i<TX_RING_SIZE; i++)
-			{
-				PNDIS_PACKET  pPacket;
-
-#ifndef RT_BIG_ENDIAN
-			    pTxD = (PTXD_STRUC)pAd->TxRing[QID_AC_BE].Cell[i].AllocVa;
-#else
-        		pDestTxD = (PTXD_STRUC)pAd->TxRing[QID_AC_BE].Cell[i].AllocVa;
-        		TxD = *pDestTxD;
-        		pTxD = &TxD;
-        		RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#endif
-				pTxD->DMADONE = 0;
-				pPacket = pTxRing->Cell[i].pNdisPacket;
-				if (pPacket)
-				{
-					PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr0, pTxD->SDLen0, PCI_DMA_TODEVICE);
-					RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-				}
-				//Always assign pNdisPacket as NULL after clear
-				pTxRing->Cell[i].pNdisPacket = NULL;
-
-				pPacket = pTxRing->Cell[i].pNextNdisPacket;
-				if (pPacket)
-				{
-					PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr1, pTxD->SDLen1, PCI_DMA_TODEVICE);
-					RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-				}
-				//Always assign pNextNdisPacket as NULL after clear
-				pTxRing->Cell[i].pNextNdisPacket = NULL;
-#ifdef RT_BIG_ENDIAN
-				RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-				WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif
-			}
-			// Start Tx, RX DMA
-			RtmpDmaEnable(pAd, 1);
-		}
-		// reset Rx statistics.
-		pAd->ate.LastSNR0 = 0;
-		pAd->ate.LastSNR1 = 0;
-		pAd->ate.LastRssi0 = 0;
-		pAd->ate.LastRssi1 = 0;
-		pAd->ate.LastRssi2 = 0;
-		pAd->ate.AvgRssi0 = 0;
-		pAd->ate.AvgRssi1 = 0;
-		pAd->ate.AvgRssi2 = 0;
-		pAd->ate.AvgRssi0X8 = 0;
-		pAd->ate.AvgRssi1X8 = 0;
-		pAd->ate.AvgRssi2X8 = 0;
-		pAd->ate.NumOfAvgRssiSample = 0;
-
-#ifdef RALINK_28xx_QA
-		// Tx frame
-		pAd->ate.bQATxStart = FALSE;
-		pAd->ate.bQARxStart = FALSE;
-		pAd->ate.seq = 0;
-
-		// counters
-		pAd->ate.U2M = 0;
-		pAd->ate.OtherData = 0;
-		pAd->ate.Beacon = 0;
-		pAd->ate.OtherCount = 0;
-		pAd->ate.TxAc0 = 0;
-		pAd->ate.TxAc1 = 0;
-		pAd->ate.TxAc2 = 0;
-		pAd->ate.TxAc3 = 0;
-		pAd->ate.TxHCCA = 0;
-		pAd->ate.TxMgmt = 0;
-		pAd->ate.RSSI0 = 0;
-		pAd->ate.RSSI1 = 0;
-		pAd->ate.RSSI2 = 0;
-		pAd->ate.SNR0 = 0;
-		pAd->ate.SNR1 = 0;
-
-		// control
-		pAd->ate.TxDoneCount = 0;
-		pAd->ate.TxStatus = 0; // task Tx status // 0 --> task is idle, 1 --> task is running
-#endif // RALINK_28xx_QA //
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-
-#ifdef CONFIG_STA_SUPPORT
-		//
-		// LinkDown() has "AsicDisableSync();" and "RTMP_BBP_IO_R/W8_BY_REG_ID();" inside.
-		//
-//      LinkDown(pAd, FALSE);
-//		AsicEnableBssSync(pAd);
-#ifndef UCOS
-		netif_stop_queue(pAd->net_dev);
-#endif // !UCOS //
-		//
-		// If we skip "LinkDown()", we should disable protection
-		// to prevent from sending out RTS or CTS-to-self.
-		//
-		ATEDisableAsicProtect(pAd);
-		RTMPStationStop(pAd);
-#endif // CONFIG_STA_SUPPORT //
-
-		/* Disable Tx */
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		/* Disable Rx */
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-	}
-	else if (!strcmp(arg, "ATESTOP"))
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: ATESTOP\n"));
-
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData); // recover the MAC_SYS_CTRL register back.
-
-		// Disable Tx, Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= (0xfffffff3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-#ifndef UCOS
-		pAd->ate.bFWLoading = TRUE;
-		Status = NICLoadFirmware(pAd);
-		if (Status != NDIS_STATUS_SUCCESS)
-		{
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("NICLoadFirmware failed, Status[=0x%08x]\n", Status));
-			return FALSE;
-		}
-#endif // !UCOS //
-		pAd->ate.Mode = ATE_STOP;
-
-
-#ifdef CONFIG_STA_SUPPORT
-		//
-		// Even the firmware has been loaded,
-		// we still could use ATE_BBP_IO_READ8_BY_REG_ID().
-		// But this is not suggested.
-		//
-		BbpSoftReset(pAd);
-#endif // CONFIG_STA_SUPPORT //
-
-		NICDisableInterrupt(pAd);
-
-		NICInitializeAdapter(pAd, TRUE);
-
-
-		// Reinitialize Rx Ring before Rx DMA is enabled.
-		// The nightmare of >>>RxCoherent<<< was gone !
-		for (index = 0; index < RX_RING_SIZE; index++)
-		{
-			pRxD = (PRXD_STRUC) pAd->RxRing.Cell[index].AllocVa;
-			pRxD->DDONE = 0;
-		}
-
-		// We should read EEPROM for all cases.
-		NICReadEEPROMParameters(pAd, NULL);
-		NICInitAsicFromEEPROM(pAd);
-
-		AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-
-		//
-		// Enable Interrupt
-		//
-
-		//
-		// These steps are only for APAutoSelectChannel().
-		//
-#if 0
-		//pAd->bStaFifoTest = TRUE;
-		pAd->int_enable_reg = ((DELAYINTMASK)  | (RxINT|TxDataInt|TxMgmtInt)) & ~(0x03);
-		pAd->int_disable_mask = 0;
-		pAd->int_pending = 0;
-#endif
-		RTMP_IO_WRITE32(pAd, INT_SOURCE_CSR, 0xffffffff);  // clear garbage interrupts
-		NICEnableInterrupt(pAd);
-
-
-/*=========================================================================*/
-		/* restore RX_FILTR_CFG */
-#ifdef CONFIG_STA_SUPPORT
-		/* restore RX_FILTR_CFG due to that QA maybe set it to 0x3 */
-		RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, STANORMAL);
-#endif // CONFIG_STA_SUPPORT //
-/*=========================================================================*/
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Enable Tx, Rx DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		// Enable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-
-#ifdef CONFIG_STA_SUPPORT
-		RTMPStationStart(pAd);
-#endif // CONFIG_STA_SUPPORT //
-#ifndef UCOS
-		netif_start_queue(pAd->net_dev);
-#endif // !UCOS //
-	}
-	else if (!strcmp(arg, "TXCARR"))	// Tx Carrier
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXCARR\n"));
-		pAd->ate.Mode |= ATE_TXCARR;
-
-		// QA has done the following steps if it is used.
-		if (pAd->ate.bQATxStart == FALSE)
-		{
-			// Soft reset BBP.
-			BbpSoftReset(pAd);
-
-			// Carrier Test set BBP R22 bit7=1, bit6=1, bit[5~0]=0x01
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF00; //clear bit7, bit6, bit[5~0]
-			BbpData |= 0x000000C1; //set bit7=1, bit6=1, bit[5~0]=0x01
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-			// set MAC_SYS_CTRL(0x1004) Continuous Tx Production Test (bit4) = 1
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-			Value = Value | 0x00000010;
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-		}
-	}
-	else if (!strcmp(arg, "TXCONT"))	// Tx Continue
-	{
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			/* set MAC_SYS_CTRL(0x1004) bit4(Continuous Tx Production Test)
-			   and bit2(MAC TX enable) back to zero. */
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-			MacData &= 0xFFFFFFEB;
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-			// set BBP R22 bit7=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF7F; //set bit7=0
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		}
-
-		/* for TxCont mode.
-		** Step 1: Send 50 packets first then wait for a moment.
-		** Step 2: Send more 50 packet then start continue mode.
-		*/
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXCONT\n"));
-		// Step 1: send 50 packets first.
-		pAd->ate.Mode |= ATE_TXCONT;
-		pAd->ate.TxCount = 50;
-                /* Do it after Tx/Rx DMA is aborted. */
-//		pAd->ate.TxDoneCount = 0;
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-		// Fix can't smooth kick
-		{
-			RTMP_IO_READ32(pAd, TX_DTX_IDX0 + QID_AC_BE * 0x10,  &pTxRing->TxDmaIdx);
-			pTxRing->TxSwFreeIdx = pTxRing->TxDmaIdx;
-			pTxRing->TxCpuIdx = pTxRing->TxDmaIdx;
-			RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * 0x10, pTxRing->TxCpuIdx);
-		}
-
-		pAd->ate.TxDoneCount = 0;
-
-		/* Only needed if we have to send some normal frames. */
-		SetJapanFilter(pAd);
-
-		for (i = 0; (i < TX_RING_SIZE-1) && (i < pAd->ate.TxCount); i++)
-		{
-			PNDIS_PACKET pPacket;
-			UINT32 TxIdx = pTxRing->TxCpuIdx;
-
-#ifndef RT_BIG_ENDIAN
-			pTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
-#else
-			pDestTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
-			TxD = *pDestTxD;
-			pTxD = &TxD;
-			RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#endif
-			// Clean current cell.
-			pPacket = pTxRing->Cell[TxIdx].pNdisPacket;
-			if (pPacket)
-			{
-				PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr0, pTxD->SDLen0, PCI_DMA_TODEVICE);
-				RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-			}
-			//Always assign pNdisPacket as NULL after clear
-			pTxRing->Cell[TxIdx].pNdisPacket = NULL;
-
-			pPacket = pTxRing->Cell[TxIdx].pNextNdisPacket;
-			if (pPacket)
-			{
-				PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr1, pTxD->SDLen1, PCI_DMA_TODEVICE);
-				RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-			}
-			//Always assign pNextNdisPacket as NULL after clear
-			pTxRing->Cell[TxIdx].pNextNdisPacket = NULL;
-
-#ifdef RT_BIG_ENDIAN
-			RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-			WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif
-
-			if (ATESetUpFrame(pAd, TxIdx) != 0)
-				break;
-
-			INC_RING_INDEX(pTxRing->TxCpuIdx, TX_RING_SIZE);
-		}
-
-                // Setup frame format.
-		ATESetUpFrame(pAd, pTxRing->TxCpuIdx);
-
-		// Start Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-#ifdef RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			pAd->ate.TxStatus = 1;
-			//pAd->ate.Repeat = 0;
-		}
-#endif // RALINK_28xx_QA //
-
-		// kick Tx-Ring.
-		RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * RINGREG_DIFF, pAd->TxRing[QID_AC_BE].TxCpuIdx);
-
-		RTMPusecDelay(5000);
-
-
-		// Step 2: send more 50 packets then start continue mode.
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-		// Cont. TX set BBP R22 bit7=1
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-		BbpData |= 0x00000080; //set bit7=1
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-		pAd->ate.TxCount = 50;
-
-		// Fix can't smooth kick
-		{
-			RTMP_IO_READ32(pAd, TX_DTX_IDX0 + QID_AC_BE * 0x10,  &pTxRing->TxDmaIdx);
-			pTxRing->TxSwFreeIdx = pTxRing->TxDmaIdx;
-			pTxRing->TxCpuIdx = pTxRing->TxDmaIdx;
-			RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * 0x10, pTxRing->TxCpuIdx);
-		}
-
-		pAd->ate.TxDoneCount = 0;
-
-		SetJapanFilter(pAd);
-
-		for (i = 0; (i < TX_RING_SIZE-1) && (i < pAd->ate.TxCount); i++)
-		{
-			PNDIS_PACKET pPacket;
-			UINT32 TxIdx = pTxRing->TxCpuIdx;
-
-#ifndef RT_BIG_ENDIAN
-			pTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
-#else
-			pDestTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
-			TxD = *pDestTxD;
-			pTxD = &TxD;
-			RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#endif
-			// clean current cell.
-			pPacket = pTxRing->Cell[TxIdx].pNdisPacket;
-			if (pPacket)
-			{
-				PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr0, pTxD->SDLen0, PCI_DMA_TODEVICE);
-				RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-			}
-			//Always assign pNdisPacket as NULL after clear
-			pTxRing->Cell[TxIdx].pNdisPacket = NULL;
-
-			pPacket = pTxRing->Cell[TxIdx].pNextNdisPacket;
-			if (pPacket)
-			{
-				PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr1, pTxD->SDLen1, PCI_DMA_TODEVICE);
-				RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-			}
-			//Always assign pNextNdisPacket as NULL after clear
-			pTxRing->Cell[TxIdx].pNextNdisPacket = NULL;
-
-#ifdef RT_BIG_ENDIAN
-			RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-			WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif
-
-			if (ATESetUpFrame(pAd, TxIdx) != 0)
-				break;
-
-			INC_RING_INDEX(pTxRing->TxCpuIdx, TX_RING_SIZE);
-		}
-
-		ATESetUpFrame(pAd, pTxRing->TxCpuIdx);
-
-		// Start Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-#ifdef RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			pAd->ate.TxStatus = 1;
-			//pAd->ate.Repeat = 0;
-		}
-#endif // RALINK_28xx_QA //
-
-		// kick Tx-Ring.
-		RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * RINGREG_DIFF, pAd->TxRing[QID_AC_BE].TxCpuIdx);
-
-		RTMPusecDelay(500);
-
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-		MacData |= 0x00000010;
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-	}
-	else if (!strcmp(arg, "TXFRAME")) // Tx Frames
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXFRAME(Count=%d)\n", pAd->ate.TxCount));
-		pAd->ate.Mode |= ATE_TXFRAME;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-		// Fix can't smooth kick
-		{
-			RTMP_IO_READ32(pAd, TX_DTX_IDX0 + QID_AC_BE * 0x10,  &pTxRing->TxDmaIdx);
-			pTxRing->TxSwFreeIdx = pTxRing->TxDmaIdx;
-			pTxRing->TxCpuIdx = pTxRing->TxDmaIdx;
-			RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * 0x10, pTxRing->TxCpuIdx);
-		}
-
-		pAd->ate.TxDoneCount = 0;
-
-		SetJapanFilter(pAd);
-
-		for (i = 0; (i < TX_RING_SIZE-1) && (i < pAd->ate.TxCount); i++)
-		{
-			PNDIS_PACKET pPacket;
-			UINT32 TxIdx = pTxRing->TxCpuIdx;
-
-#ifndef RT_BIG_ENDIAN
-			pTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
-#else
-			pDestTxD = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
-			TxD = *pDestTxD;
-			pTxD = &TxD;
-			RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#endif
-			// Clean current cell.
-			pPacket = pTxRing->Cell[TxIdx].pNdisPacket;
-			if (pPacket)
-			{
-				PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr0, pTxD->SDLen0, PCI_DMA_TODEVICE);
-				RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-			}
-			//Always assign pNdisPacket as NULL after clear
-			pTxRing->Cell[TxIdx].pNdisPacket = NULL;
-
-			pPacket = pTxRing->Cell[TxIdx].pNextNdisPacket;
-			if (pPacket)
-			{
-				PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr1, pTxD->SDLen1, PCI_DMA_TODEVICE);
-				RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-			}
-			//Always assign pNextNdisPacket as NULL after clear
-			pTxRing->Cell[TxIdx].pNextNdisPacket = NULL;
-
-#ifdef RT_BIG_ENDIAN
-			RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-			WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif
-
-			if (ATESetUpFrame(pAd, TxIdx) != 0)
-				break;
-
-			INC_RING_INDEX(pTxRing->TxCpuIdx, TX_RING_SIZE);
-
-		}
-
-		ATESetUpFrame(pAd, pTxRing->TxCpuIdx);
-
-		// Start Tx, Rx DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-#ifdef RALINK_28xx_QA
-		// add this for LoopBack mode
-		if (pAd->ate.bQARxStart == FALSE)
-		{
-			// Disable Rx
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-			Value &= ~(1 << 3);
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-		}
-
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			pAd->ate.TxStatus = 1;
-			//pAd->ate.Repeat = 0;
-		}
-#else
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-#endif // RALINK_28xx_QA //
-
-		RTMP_IO_READ32(pAd, TX_DTX_IDX0 + QID_AC_BE * RINGREG_DIFF, &pAd->TxRing[QID_AC_BE].TxDmaIdx);
-		// kick Tx-Ring.
-		RTMP_IO_WRITE32(pAd, TX_CTX_IDX0 + QID_AC_BE * RINGREG_DIFF, pAd->TxRing[QID_AC_BE].TxCpuIdx);
-
-		pAd->RalinkCounters.KickTxCount++;
-	}
-#ifdef RALINK_28xx_QA
-	else if (!strcmp(arg, "TXSTOP"))
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXSTOP\n"));
-		atemode = pAd->ate.Mode;
-		pAd->ate.Mode &= ATE_TXSTOP;
-		pAd->ate.bQATxStart = FALSE;
-//		pAd->ate.TxDoneCount = pAd->ate.TxCount;
-
-		if (atemode & ATE_TXCARR)
-		{
-			// No Carrier Test set BBP R22 bit7=0, bit6=0, bit[5~0]=0x0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF00; //clear bit7, bit6, bit[5~0]
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		}
-		else if (atemode & ATE_TXCARRSUPP)
-		{
-			// No Cont. TX set BBP R22 bit7=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= ~(1 << 7); //set bit7=0
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-			// No Carrier Suppression set BBP R24 bit0=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R24, &BbpData);
-			BbpData &= 0xFFFFFFFE; //clear bit0
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, BbpData);
-		}
-		// We should free some resource which allocate when ATE_TXFRAME , ATE_STOP, and ATE_TXCONT.
-		else if ((atemode & ATE_TXFRAME) || (atemode == ATE_STOP))
-		{
-
-			PRTMP_TX_RING pTxRing = &pAd->TxRing[QID_AC_BE];
-
-			if (atemode & ATE_TXCONT)
-			{
-				// No Cont. TX set BBP R22 bit7=0
-				ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-				BbpData &= ~(1 << 7); //set bit7=0
-				ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-			}
-
-			// Abort Tx, Rx DMA.
-			RtmpDmaEnable(pAd, 0);
-			for (i=0; i<TX_RING_SIZE; i++)
-			{
-				PNDIS_PACKET  pPacket;
-
-#ifndef RT_BIG_ENDIAN
-			    pTxD = (PTXD_STRUC)pAd->TxRing[QID_AC_BE].Cell[i].AllocVa;
-#else
-        		pDestTxD = (PTXD_STRUC)pAd->TxRing[QID_AC_BE].Cell[i].AllocVa;
-        		TxD = *pDestTxD;
-        		pTxD = &TxD;
-        		RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-#endif
-				pTxD->DMADONE = 0;
-				pPacket = pTxRing->Cell[i].pNdisPacket;
-				if (pPacket)
-				{
-					PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr0, pTxD->SDLen0, PCI_DMA_TODEVICE);
-					RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-				}
-				//Always assign pNdisPacket as NULL after clear
-				pTxRing->Cell[i].pNdisPacket = NULL;
-
-				pPacket = pTxRing->Cell[i].pNextNdisPacket;
-				if (pPacket)
-				{
-					PCI_UNMAP_SINGLE(pAd, pTxD->SDPtr1, pTxD->SDLen1, PCI_DMA_TODEVICE);
-					RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-				}
-				//Always assign pNextNdisPacket as NULL after clear
-				pTxRing->Cell[i].pNextNdisPacket = NULL;
-#ifdef RT_BIG_ENDIAN
-				RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-				WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif
-			}
-			// Enable Tx, Rx DMA
-			RtmpDmaEnable(pAd, 1);
-
-		}
-
-		// control
-//		pAd->ate.TxDoneCount = 0;
-		pAd->ate.TxStatus = 0; // task Tx status // 0 --> task is idle, 1 --> task is running
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-		// Disable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-	}
-	else if (!strcmp(arg, "RXSTOP"))
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: RXSTOP\n"));
-		atemode = pAd->ate.Mode;
-		pAd->ate.Mode &= ATE_RXSTOP;
-		pAd->ate.bQARxStart = FALSE;
-//		pAd->ate.TxDoneCount = pAd->ate.TxCount;
-
-		if (atemode & ATE_TXCARR)
-		{
-			;
-		}
-		else if (atemode & ATE_TXCARRSUPP)
-		{
-			;
-		}
-
-		// We should free some resource which was allocated when ATE_TXFRAME , ATE_STOP, and ATE_TXCONT.
-		else if ((atemode & ATE_TXFRAME) || (atemode == ATE_STOP))
-		{
-			if (atemode & ATE_TXCONT)
-			{
-				;
-			}
-		}
-
-		// control
-//		pAd->ate.TxDoneCount = 0;
-//		pAd->ate.TxStatus = 0; // task Tx status // 0 --> task is idle, 1 --> task is running
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-	}
-#endif // RALINK_28xx_QA //
-	else if (!strcmp(arg, "RXFRAME")) // Rx Frames
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: RXFRAME\n"));
-
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-		pAd->ate.Mode |= ATE_RXFRAME;
-
-		// Disable Tx of MAC block.
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Enable Rx of MAC block.
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: Invalid arg!\n"));
-		return FALSE;
-	}
-	RTMPusecDelay(5000);
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("<=== ATECmdHandler()\n"));
-
-	return TRUE;
-}
-/*                                                           */
-/*                                                           */
-/*=======================End of RT2860=======================*/
-
-
-/*======================Start of RT2870======================*/
-/*                                                           */
-/*                                                           */
-
-
-INT	Set_ATE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	if (ATECmdHandler(pAd, arg))
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_Proc Success\n"));
-
-
-		return TRUE;
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_Proc Failed\n"));
-		return FALSE;
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE ADDR1=DA for TxFrame(AP  : To DS = 0 ; From DS = 1)
-        or
-        Set ATE ADDR3=DA for TxFrame(STA : To DS = 1 ; From DS = 0)
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_DA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR				*value;
-	INT					i;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-    for (i=0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-		AtoH(value, &pAd->ate.Addr3[i++], 1);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	if(i != 6)
-		return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_DA_Proc (DA = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAd->ate.Addr3[0],
-		pAd->ate.Addr3[1], pAd->ate.Addr3[2], pAd->ate.Addr3[3], pAd->ate.Addr3[4], pAd->ate.Addr3[5]));
-#endif // CONFIG_STA_SUPPORT //
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_DA_Proc Success\n"));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE ADDR3=SA for TxFrame(AP  : To DS = 0 ; From DS = 1)
-        or
-        Set ATE ADDR2=SA for TxFrame(STA : To DS = 1 ; From DS = 0)
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_SA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR				*value;
-	INT					i;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-    for (i=0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-		AtoH(value, &pAd->ate.Addr2[i++], 1);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	if(i != 6)
-		return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_SA_Proc (SA = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAd->ate.Addr2[0],
-		pAd->ate.Addr2[1], pAd->ate.Addr2[2], pAd->ate.Addr2[3], pAd->ate.Addr2[4], pAd->ate.Addr2[5]));
-#endif // CONFIG_STA_SUPPORT //
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_SA_Proc Success\n"));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE ADDR2=BSSID for TxFrame(AP  : To DS = 0 ; From DS = 1)
-        or
-        Set ATE ADDR1=BSSID for TxFrame(STA : To DS = 1 ; From DS = 0)
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_BSSID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR				*value;
-	INT					i;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-    for (i=0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-		AtoH(value, &pAd->ate.Addr1[i++], 1);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	if(i != 6)
-		return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_BSSID_Proc (BSSID = %2X:%2X:%2X:%2X:%2X:%2X)\n",	pAd->ate.Addr1[0],
-		pAd->ate.Addr1[1], pAd->ate.Addr1[2], pAd->ate.Addr1[3], pAd->ate.Addr1[4], pAd->ate.Addr1[5]));
-#endif // CONFIG_STA_SUPPORT //
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_BSSID_Proc Success\n"));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Channel
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_CHANNEL_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR channel;
-
-	channel = simple_strtol(arg, 0, 10);
-
-	if ((channel < 1) || (channel > 216))// to allow A band channel : ((channel < 1) || (channel > 14))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_CHANNEL_Proc::Out of range, it should be in range of 1~14.\n"));
-		return FALSE;
-	}
-	pAd->ate.Channel = channel;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_CHANNEL_Proc (ATE Channel = %d)\n", pAd->ate.Channel));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_CHANNEL_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Power0
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_POWER0_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR TxPower;
-
-	TxPower = simple_strtol(arg, 0, 10);
-
-	if (pAd->ate.Channel <= 14)
-	{
-		if ((TxPower > 31) || (TxPower < 0))
-		{
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER0_Proc::Out of range (Value=%d)\n", TxPower));
-			return FALSE;
-		}
-	}
-	else// 5.5GHz
-	{
-		if ((TxPower > 15) || (TxPower < -7))
-		{
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER0_Proc::Out of range (Value=%d)\n", TxPower));
-			return FALSE;
-		}
-	}
-
-	pAd->ate.TxPower0 = TxPower;
-	ATETxPwrHandler(pAd, 0);
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_POWER0_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Power1
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_POWER1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR TxPower;
-
-	TxPower = simple_strtol(arg, 0, 10);
-
-	if (pAd->ate.Channel <= 14)
-	{
-	if ((TxPower > 31) || (TxPower < 0))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER1_Proc::Out of range (Value=%d)\n", TxPower));
-		return FALSE;
-	}
-	}
-	else
-	{
-		if ((TxPower > 15) || (TxPower < -7))
-		{
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER1_Proc::Out of range (Value=%d)\n", TxPower));
-			return FALSE;
-		}
-	}
-
-	pAd->ate.TxPower1 = TxPower;
-	ATETxPwrHandler(pAd, 1);
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_POWER1_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Antenna
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR value;
-
-	value = simple_strtol(arg, 0, 10);
-
-	if ((value > 2) || (value < 0))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_Antenna_Proc::Out of range (Value=%d)\n", value));
-		return FALSE;
-	}
-
-	pAd->ate.TxAntennaSel = value;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_Antenna_Proc (Antenna = %d)\n", pAd->ate.TxAntennaSel));
-	ATEDBGPRINT(RT_DEBUG_TRACE,("Ralink: Set_ATE_TX_Antenna_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Rx Antenna
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_RX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR value;
-
-	value = simple_strtol(arg, 0, 10);
-
-	if ((value > 3) || (value < 0))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_RX_Antenna_Proc::Out of range (Value=%d)\n", value));
-		return FALSE;
-	}
-
-	pAd->ate.RxAntennaSel = value;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_RX_Antenna_Proc (Antenna = %d)\n", pAd->ate.RxAntennaSel));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_RX_Antenna_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE RF frequence offset
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_FREQOFFSET_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR RFFreqOffset;
-	ULONG R4;
-
-	RFFreqOffset = simple_strtol(arg, 0, 10);
-
-	if(RFFreqOffset >= 64)
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_FREQOFFSET_Proc::Out of range, it should be in range of 0~63.\n"));
-		return FALSE;
-	}
-
-	pAd->ate.RFFreqOffset = RFFreqOffset;
-	R4 = pAd->ate.RFFreqOffset << 15;		// shift TX power control to correct RF register bit position
-	R4 |= (pAd->LatchRfRegs.R4 & ((~0x001f8000)));
-	pAd->LatchRfRegs.R4 = R4;
-
-	RtmpRfIoWrite(pAd);
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_FREQOFFSET_Proc (RFFreqOffset = %d)\n", pAd->ate.RFFreqOffset));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_FREQOFFSET_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE RF BW
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_BW_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	int i;
-	UCHAR value = 0;
-	UCHAR BBPCurrentBW;
-
-	BBPCurrentBW = simple_strtol(arg, 0, 10);
-
-	if(BBPCurrentBW == 0)
-		pAd->ate.TxWI.BW = BW_20;
-	else
-		pAd->ate.TxWI.BW = BW_40;
-
-	if(pAd->ate.TxWI.BW == BW_20)
-	{
-		if(pAd->ate.Channel <= 14)
-		{
- 		for (i=0; i<5; i++)
- 		{
-				if (pAd->Tx20MPwrCfgGBand[i] != 0xffffffff)
-				{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx20MPwrCfgGBand[i]);
-					RTMPusecDelay(5000);
-				}
-			}
-		}
-		else
-		{
-			for (i=0; i<5; i++)
-			{
-				if (pAd->Tx20MPwrCfgABand[i] != 0xffffffff)
- 			{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx20MPwrCfgABand[i]);
- 				RTMPusecDelay(5000);
- 			}
- 		}
-		}
-
-		//Set BBP R4 bit[4:3]=0:0
- 		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
- 		value &= (~0x18);
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
-
-  		//Set BBP R66=0x3C
- 		value = 0x3C;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, value);
-		//Set BBP R68=0x0B
-		//to improve Rx sensitivity.
-		value = 0x0B;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R68, value);
-		//Set BBP R69=0x16
-		value = 0x16;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, value);
-		//Set BBP R70=0x08
-		value = 0x08;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, value);
-		//Set BBP R73=0x11
-		value = 0x11;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, value);
-
-	    // If Channel=14, Bandwidth=20M and Mode=CCK, Set BBP R4 bit5=1
-	    // (Japan filter coefficients)
-	    // This segment of code will only works when ATETXMODE and ATECHANNEL
-	    // were set to MODE_CCK and 14 respectively before ATETXBW is set to 0.
-	    //=====================================================================
-		if (pAd->ate.Channel == 14)
-		{
-			int TxMode = pAd->ate.TxWI.PHYMODE;
-			if (TxMode == MODE_CCK)
-			{
-				// when Channel==14 && Mode==CCK && BandWidth==20M, BBP R4 bit5=1
- 				ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
-				value |= 0x20; //set bit5=1
- 				ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
-			}
-		}
-
-	    //=====================================================================
-		// If bandwidth != 40M, RF Reg4 bit 21 = 0.
-		pAd->LatchRfRegs.R4 &= ~0x00200000;
-		RtmpRfIoWrite(pAd);
-	}
-	else if(pAd->ate.TxWI.BW == BW_40)
-	{
-		if(pAd->ate.Channel <= 14)
-		{
-			for (i=0; i<5; i++)
-			{
-				if (pAd->Tx40MPwrCfgGBand[i] != 0xffffffff)
-				{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx40MPwrCfgGBand[i]);
-					RTMPusecDelay(5000);
-				}
-			}
-		}
-		else
-		{
-			for (i=0; i<5; i++)
-			{
-				if (pAd->Tx40MPwrCfgABand[i] != 0xffffffff)
-				{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx40MPwrCfgABand[i]);
-					RTMPusecDelay(5000);
-				}
-			}
-#ifdef DOT11_N_SUPPORT
-			if ((pAd->ate.TxWI.PHYMODE >= MODE_HTMIX) && (pAd->ate.TxWI.MCS == 7))
-			{
-    			value = 0x28;
-    			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R67, value);
-			}
-#endif // DOT11_N_SUPPORT //
-		}
-
-		//Set BBP R4 bit[4:3]=1:0
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
-		value &= (~0x18);
-		value |= 0x10;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
-
-		//Set BBP R66=0x3C
-		value = 0x3C;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, value);
-		//Set BBP R68=0x0C
-		//to improve Rx sensitivity.
-		value = 0x0C;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R68, value);
-		//Set BBP R69=0x1A
-		value = 0x1A;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, value);
-		//Set BBP R70=0x0A
-		value = 0x0A;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, value);
-		//Set BBP R73=0x16
-		value = 0x16;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, value);
-
-		// If bandwidth = 40M, set RF Reg4 bit 21 = 1.
-		pAd->LatchRfRegs.R4 |= 0x00200000;
-		RtmpRfIoWrite(pAd);
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_BW_Proc (BBPCurrentBW = %d)\n", pAd->ate.TxWI.BW));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_BW_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame length
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_LENGTH_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxLength = simple_strtol(arg, 0, 10);
-
-	if((pAd->ate.TxLength < 24) || (pAd->ate.TxLength > (MAX_FRAME_SIZE - 34/* == 2312 */)))
-	{
-		pAd->ate.TxLength = (MAX_FRAME_SIZE - 34/* == 2312 */);
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_LENGTH_Proc::Out of range, it should be in range of 24~%d.\n", (MAX_FRAME_SIZE - 34/* == 2312 */)));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_LENGTH_Proc (TxLength = %d)\n", pAd->ate.TxLength));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_LENGTH_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame count
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_COUNT_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxCount = simple_strtol(arg, 0, 10);
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_COUNT_Proc (TxCount = %d)\n", pAd->ate.TxCount));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_COUNT_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame MCS
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_MCS_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR MCS;
-	int result;
-
-	MCS = simple_strtol(arg, 0, 10);
-	result = CheckMCSValid(pAd->ate.TxWI.PHYMODE, MCS);
-
-	if (result != -1)
-	{
-		pAd->ate.TxWI.MCS = (UCHAR)MCS;
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_MCS_Proc::Out of range, refer to rate table.\n"));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_MCS_Proc (MCS = %d)\n", pAd->ate.TxWI.MCS));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_MCS_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame Mode
-        0: MODE_CCK
-        1: MODE_OFDM
-        2: MODE_HTMIX
-        3: MODE_HTGREENFIELD
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_MODE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxWI.PHYMODE = simple_strtol(arg, 0, 10);
-
-	if(pAd->ate.TxWI.PHYMODE > 3)
-	{
-		pAd->ate.TxWI.PHYMODE = 0;
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_MODE_Proc::Out of range. it should be in range of 0~3\n"));
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("0: CCK, 1: OFDM, 2: HT_MIX, 3: HT_GREEN_FIELD.\n"));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_MODE_Proc (TxMode = %d)\n", pAd->ate.TxWI.PHYMODE));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_MODE_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame GI
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_GI_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxWI.ShortGI = simple_strtol(arg, 0, 10);
-
-	if(pAd->ate.TxWI.ShortGI > 1)
-	{
-		pAd->ate.TxWI.ShortGI = 0;
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_GI_Proc::Out of range\n"));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_GI_Proc (GI = %d)\n", pAd->ate.TxWI.ShortGI));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_GI_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-    ==========================================================================
- */
-INT	Set_ATE_RX_FER_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.bRxFer = simple_strtol(arg, 0, 10);
-
-	if (pAd->ate.bRxFer == 1)
-	{
-		pAd->ate.RxCntPerSec = 0;
-		pAd->ate.RxTotalCnt = 0;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_RX_FER_Proc (bRxFer = %d)\n", pAd->ate.bRxFer));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_RX_FER_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-INT Set_ATE_Read_RF_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ate_print(KERN_EMERG "R1 = %lx\n", pAd->LatchRfRegs.R1);
-	ate_print(KERN_EMERG "R2 = %lx\n", pAd->LatchRfRegs.R2);
-	ate_print(KERN_EMERG "R3 = %lx\n", pAd->LatchRfRegs.R3);
-	ate_print(KERN_EMERG "R4 = %lx\n", pAd->LatchRfRegs.R4);
-
-	return TRUE;
-}
-
-INT Set_ATE_Write_RF1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT32 value = simple_strtol(arg, 0, 16);
-
-	pAd->LatchRfRegs.R1 = value;
-	RtmpRfIoWrite(pAd);
-
-	return TRUE;
-}
-
-INT Set_ATE_Write_RF2_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT32 value = simple_strtol(arg, 0, 16);
-
-	pAd->LatchRfRegs.R2 = value;
-	RtmpRfIoWrite(pAd);
-
-	return TRUE;
-}
-
-INT Set_ATE_Write_RF3_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT32 value = simple_strtol(arg, 0, 16);
-
-	pAd->LatchRfRegs.R3 = value;
-	RtmpRfIoWrite(pAd);
-
-	return TRUE;
-}
-
-INT Set_ATE_Write_RF4_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT32 value = simple_strtol(arg, 0, 16);
-
-	pAd->LatchRfRegs.R4 = value;
-	RtmpRfIoWrite(pAd);
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Load and Write EEPROM from a binary file prepared in advance.
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-#ifndef UCOS
-INT Set_ATE_Load_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	BOOLEAN		    ret = FALSE;
-	PUCHAR			src = EEPROM_BIN_FILE_NAME;
-	struct file		*srcf;
-	INT32 			retval, orgfsuid, orgfsgid;
-   	mm_segment_t	orgfs;
-	USHORT 			WriteEEPROM[(EEPROM_SIZE/2)];
-	UINT32			FileLength = 0;
-	UINT32 			value = simple_strtol(arg, 0, 10);
-
-	ATEDBGPRINT(RT_DEBUG_ERROR, ("===> %s (value=%d)\n\n", __func__, value));
-
-	if (value > 0)
-	{
-		/* zero the e2p buffer */
-		NdisZeroMemory((PUCHAR)WriteEEPROM, EEPROM_SIZE);
-
-		/* save uid and gid used for filesystem access.
-	    ** set user and group to 0 (root)
-	    */
-		orgfsuid = current->fsuid;
-		orgfsgid = current->fsgid;
-		/* as root */
-		current->fsuid = current->fsgid = 0;
-    	orgfs = get_fs();
-    	set_fs(KERNEL_DS);
-
-		do
-		{
-			/* open the bin file */
-			srcf = filp_open(src, O_RDONLY, 0);
-
-			if (IS_ERR(srcf))
-			{
-				ate_print("%s - Error %ld opening %s\n", __func__, -PTR_ERR(srcf), src);
-				break;
-			}
-
-			/* the object must have a read method */
-			if ((srcf->f_op == NULL) || (srcf->f_op->read == NULL))
-			{
-				ate_print("%s - %s does not have a read method\n", __func__, src);
-				break;
-			}
-
-			/* read the firmware from the file *.bin */
-			FileLength = srcf->f_op->read(srcf,
-										  (PUCHAR)WriteEEPROM,
-										  EEPROM_SIZE,
-										  &srcf->f_pos);
-
-			if (FileLength != EEPROM_SIZE)
-			{
-				ate_print("%s: error file length (=%d) in e2p.bin\n",
-					   __func__, FileLength);
-				break;
-			}
-			else
-			{
-				/* write the content of .bin file to EEPROM */
-				rt_ee_write_all(pAd, WriteEEPROM);
-				ret = TRUE;
-			}
-			break;
-		} while(TRUE);
-
-		/* close firmware file */
-		if (IS_ERR(srcf))
-		{
-				;
-		}
-		else
-		{
-			retval = filp_close(srcf, NULL);
-			if (retval)
-			{
-				ATEDBGPRINT(RT_DEBUG_ERROR, ("--> Error %d closing %s\n", -retval, src));
-
-			}
-		}
-
-		/* restore */
-		set_fs(orgfs);
-		current->fsuid = orgfsuid;
-		current->fsgid = orgfsgid;
-	}
-    ATEDBGPRINT(RT_DEBUG_ERROR, ("<=== %s (ret=%d)\n", __func__, ret));
-
-    return ret;
-
-}
-#else
-INT Set_ATE_Load_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	USHORT 			WriteEEPROM[(EEPROM_SIZE/2)];
-	struct iwreq	*wrq = (struct iwreq *)arg;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("===> %s (wrq->u.data.length = %d)\n\n", __func__, wrq->u.data.length));
-
-	if (wrq->u.data.length != EEPROM_SIZE)
-	{
-		ate_print("%s: error length (=%d) from host\n",
-			   __func__, wrq->u.data.length);
-		return FALSE;
-	}
-	else/* (wrq->u.data.length == EEPROM_SIZE) */
-	{
-		/* zero the e2p buffer */
-		NdisZeroMemory((PUCHAR)WriteEEPROM, EEPROM_SIZE);
-
-		/* fill the local buffer */
-		NdisMoveMemory((PUCHAR)WriteEEPROM, wrq->u.data.pointer, wrq->u.data.length);
-
-		do
-		{
-				/* write the content of .bin file to EEPROM */
-				rt_ee_write_all(pAd, WriteEEPROM);
-
-		} while(FALSE);
-		}
-
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("<=== %s\n", __func__));
-
-    return TRUE;
-
-}
-#endif // !UCOS //
-
-INT Set_ATE_Read_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	USHORT buffer[EEPROM_SIZE/2];
-	USHORT *p;
-	int i;
-
-	rt_ee_read_all(pAd, (USHORT *)buffer);
-	p = buffer;
-	for (i = 0; i < (EEPROM_SIZE/2); i++)
-	{
-		ate_print("%4.4x ", *p);
-		if (((i+1) % 16) == 0)
-			ate_print("\n");
-		p++;
-	}
-	return TRUE;
-}
-
-INT	Set_ATE_Show_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ate_print("Mode=%d\n", pAd->ate.Mode);
-	ate_print("TxPower0=%d\n", pAd->ate.TxPower0);
-	ate_print("TxPower1=%d\n", pAd->ate.TxPower1);
-	ate_print("TxAntennaSel=%d\n", pAd->ate.TxAntennaSel);
-	ate_print("RxAntennaSel=%d\n", pAd->ate.RxAntennaSel);
-	ate_print("BBPCurrentBW=%d\n", pAd->ate.TxWI.BW);
-	ate_print("GI=%d\n", pAd->ate.TxWI.ShortGI);
-	ate_print("MCS=%d\n", pAd->ate.TxWI.MCS);
-	ate_print("TxMode=%d\n", pAd->ate.TxWI.PHYMODE);
-	ate_print("Addr1=%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pAd->ate.Addr1[0], pAd->ate.Addr1[1], pAd->ate.Addr1[2], pAd->ate.Addr1[3], pAd->ate.Addr1[4], pAd->ate.Addr1[5]);
-	ate_print("Addr2=%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pAd->ate.Addr2[0], pAd->ate.Addr2[1], pAd->ate.Addr2[2], pAd->ate.Addr2[3], pAd->ate.Addr2[4], pAd->ate.Addr2[5]);
-	ate_print("Addr3=%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pAd->ate.Addr3[0], pAd->ate.Addr3[1], pAd->ate.Addr3[2], pAd->ate.Addr3[3], pAd->ate.Addr3[4], pAd->ate.Addr3[5]);
-	ate_print("Channel=%d\n", pAd->ate.Channel);
-	ate_print("TxLength=%d\n", pAd->ate.TxLength);
-	ate_print("TxCount=%u\n", pAd->ate.TxCount);
-	ate_print("RFFreqOffset=%d\n", pAd->ate.RFFreqOffset);
-	ate_print(KERN_EMERG "Set_ATE_Show_Proc Success\n");
-	return TRUE;
-}
-
-INT	Set_ATE_Help_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ate_print("ATE=ATESTART, ATESTOP, TXCONT, TXCARR, TXFRAME, RXFRAME\n");
-	ate_print("ATEDA\n");
-	ate_print("ATESA\n");
-	ate_print("ATEBSSID\n");
-	ate_print("ATECHANNEL, range:0~14(unless A band !)\n");
-	ate_print("ATETXPOW0, set power level of antenna 1.\n");
-	ate_print("ATETXPOW1, set power level of antenna 2.\n");
-	ate_print("ATETXANT, set TX antenna. 0:all, 1:antenna one, 2:antenna two.\n");
-	ate_print("ATERXANT, set RX antenna.0:all, 1:antenna one, 2:antenna two, 3:antenna three.\n");
-	ate_print("ATETXFREQOFFSET, set frequency offset, range 0~63\n");
-	ate_print("ATETXBW, set BandWidth, 0:20MHz, 1:40MHz.\n");
-	ate_print("ATETXLEN, set Frame length, range 24~%d\n", (MAX_FRAME_SIZE - 34/* == 2312 */));
-	ate_print("ATETXCNT, set how many frame going to transmit.\n");
-	ate_print("ATETXMCS, set MCS, reference to rate table.\n");
-	ate_print("ATETXMODE, set Mode 0:CCK, 1:OFDM, 2:HT-Mix, 3:GreenField, reference to rate table.\n");
-	ate_print("ATETXGI, set GI interval, 0:Long, 1:Short\n");
-	ate_print("ATERXFER, 0:disable Rx Frame error rate. 1:enable Rx Frame error rate.\n");
-	ate_print("ATERRF, show all RF registers.\n");
-	ate_print("ATEWRF1, set RF1 register.\n");
-	ate_print("ATEWRF2, set RF2 register.\n");
-	ate_print("ATEWRF3, set RF3 register.\n");
-	ate_print("ATEWRF4, set RF4 register.\n");
-	ate_print("ATELDE2P, load EEPROM from .bin file.\n");
-	ate_print("ATERE2P, display all EEPROM content.\n");
-	ate_print("ATESHOW, display all parameters of ATE.\n");
-	ate_print("ATEHELP, online help.\n");
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	AsicSwitchChannel() dedicated for ATE.
-
-    ==========================================================================
-*/
-VOID ATEAsicSwitchChannel(
-    IN PRTMP_ADAPTER pAd)
-{
-	UINT32 R2 = 0, R3 = DEFAULT_RF_TX_POWER, R4 = 0, Value = 0;
-	CHAR TxPwer = 0, TxPwer2 = 0;
-	UCHAR index, BbpValue = 0, R66 = 0x30;
-	RTMP_RF_REGS *RFRegTable;
-	UCHAR Channel;
-
-#ifdef RALINK_28xx_QA
-	if ((pAd->ate.bQATxStart == TRUE) || (pAd->ate.bQARxStart == TRUE))
-	{
-		if (pAd->ate.Channel != pAd->LatchRfRegs.Channel)
-		{
-			pAd->ate.Channel = pAd->LatchRfRegs.Channel;
-		}
-		return;
-	}
-	else
-#endif // RALINK_28xx_QA //
-	Channel = pAd->ate.Channel;
-
-	// Select antenna
-	AsicAntennaSelect(pAd, Channel);
-
-	// fill Tx power value
-	TxPwer = pAd->ate.TxPower0;
-	TxPwer2 = pAd->ate.TxPower1;
-
-	RFRegTable = RF2850RegTable;
-
-	switch (pAd->RfIcType)
-	{
-		/* But only 2850 and 2750 support 5.5GHz band... */
-		case RFIC_2820:
-		case RFIC_2850:
-		case RFIC_2720:
-		case RFIC_2750:
-
-			for (index = 0; index < NUM_OF_2850_CHNL; index++)
-			{
-				if (Channel == RFRegTable[index].Channel)
-				{
-					R2 = RFRegTable[index].R2;
-					if (pAd->Antenna.field.TxPath == 1)
-					{
-						R2 |= 0x4000;	// If TXpath is 1, bit 14 = 1;
-					}
-
-					if (pAd->Antenna.field.RxPath == 2)
-					{
-						switch (pAd->ate.RxAntennaSel)
-						{
-							case 1:
-								R2 |= 0x20040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x00;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							case 2:
-								R2 |= 0x10040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x01;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							default:
-								R2 |= 0x40;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								/* Only enable two Antenna to receive. */
-								BbpValue |= 0x08;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-						}
-					}
-					else if (pAd->Antenna.field.RxPath == 1)
-					{
-						R2 |= 0x20040;	// write 1 to off RxPath
-					}
-
-					if (pAd->Antenna.field.TxPath == 2)
-					{
-						if (pAd->ate.TxAntennaSel == 1)
-						{
-							R2 |= 0x4000;	// If TX Antenna select is 1 , bit 14 = 1; Disable Ant 2
-							ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
-							BbpValue &= 0xE7;		//11100111B
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
-						}
-						else if (pAd->ate.TxAntennaSel == 2)
-						{
-							R2 |= 0x8000;	// If TX Antenna select is 2 , bit 15 = 1; Disable Ant 1
-							ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
-							BbpValue &= 0xE7;
-							BbpValue |= 0x08;
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
-						}
-						else
-						{
-							ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
-							BbpValue &= 0xE7;
-							BbpValue |= 0x10;
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
-						}
-					}
-					if (pAd->Antenna.field.RxPath == 3)
-					{
-						switch (pAd->ate.RxAntennaSel)
-						{
-							case 1:
-								R2 |= 0x20040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x00;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							case 2:
-								R2 |= 0x10040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x01;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							case 3:
-								R2 |= 0x30000;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x02;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							default:
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x10;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-						}
-					}
-
-					if (Channel > 14)
-					{
-						// initialize R3, R4
-						R3 = (RFRegTable[index].R3 & 0xffffc1ff);
-						R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->ate.RFFreqOffset << 15);
-
-                        // According the Rory's suggestion to solve the middle range issue.
-						// 5.5G band power range: 0xF9~0X0F, TX0 Reg3 bit9/TX1 Reg4 bit6="0" means the TX power reduce 7dB
-						// R3
-						if ((TxPwer >= -7) && (TxPwer < 0))
-						{
-							TxPwer = (7+TxPwer);
-							TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
-							R3 |= (TxPwer << 10);
-							ATEDBGPRINT(RT_DEBUG_TRACE, ("ATEAsicSwitchChannel: TxPwer=%d \n", TxPwer));
-						}
-						else
-						{
-							TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
-							R3 |= (TxPwer << 10) | (1 << 9);
-						}
-
-						// R4
-						if ((TxPwer2 >= -7) && (TxPwer2 < 0))
-						{
-							TxPwer2 = (7+TxPwer2);
-							TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
-							R4 |= (TxPwer2 << 7);
-							ATEDBGPRINT(RT_DEBUG_TRACE, ("ATEAsicSwitchChannel: TxPwer2=%d \n", TxPwer2));
-						}
-						else
-						{
-							TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
-							R4 |= (TxPwer2 << 7) | (1 << 6);
-						}
-					}
-					else
-					{
-						R3 = (RFRegTable[index].R3 & 0xffffc1ff) | (TxPwer << 9); // set TX power0
-						R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->ate.RFFreqOffset << 15) | (TxPwer2 <<6);// Set freq offset & TxPwr1
-					}
-
-					// Based on BBP current mode before changing RF channel.
-					if (pAd->ate.TxWI.BW == BW_40)
-					{
-						R4 |=0x200000;
-					}
-
-					// Update variables
-					pAd->LatchRfRegs.Channel = Channel;
-					pAd->LatchRfRegs.R1 = RFRegTable[index].R1;
-					pAd->LatchRfRegs.R2 = R2;
-					pAd->LatchRfRegs.R3 = R3;
-					pAd->LatchRfRegs.R4 = R4;
-
-					RtmpRfIoWrite(pAd);
-
-					break;
-				}
-			}
-			break;
-
-		default:
-			break;
-	}
-
-	// Change BBP setting during switch from a->g, g->a
-	if (Channel <= 14)
-	{
-	    ULONG	TxPinCfg = 0x00050F0A;// 2007.10.09 by Brian : 0x0005050A ==> 0x00050F0A
-
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
-
-		/* For 1T/2R chip only... */
-	    if (pAd->NicConfig2.field.ExternalLNAForG)
-	    {
-	        ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x62);
-	    }
-	    else
-	    {
-	        ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x84);
-	    }
-
-        // According the Rory's suggestion to solve the middle range issue.
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R86, &BbpValue);
-		ASSERT((BbpValue == 0x00));
-		if ((BbpValue != 0x00))
-		{
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0x00);
-		}
-
-		// 5.5GHz band selection PIN, bit1 and bit2 are complement
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		Value &= (~0x6);
-		Value |= (0x04);
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-
-        // Turn off unused PA or LNA when only 1T or 1R.
-		if (pAd->Antenna.field.TxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFFFF3;
-		}
-		if (pAd->Antenna.field.RxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFF3FF;
-		}
-
-		RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
-	}
-	else
-	{
-	    ULONG	TxPinCfg = 0x00050F05;//2007.10.09 by Brian : 0x00050505 ==> 0x00050F05
-
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0xF2);
-
-        // According the Rory's suggestion to solve the middle range issue.
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R86, &BbpValue);
-		ASSERT((BbpValue == 0x00));
-		if ((BbpValue != 0x00))
-		{
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0x00);
-		}
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R91, &BbpValue);
-		ASSERT((BbpValue == 0x04));
-
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R92, &BbpValue);
-		ASSERT((BbpValue == 0x00));
-
-		// 5.5GHz band selection PIN, bit1 and bit2 are complement
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		Value &= (~0x6);
-		Value |= (0x02);
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-
-        // Turn off unused PA or LNA when only 1T or 1R.
-		if (pAd->Antenna.field.TxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFFFF3;
-	    }
-		if (pAd->Antenna.field.RxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFF3FF;
-		}
-
-		RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
-	}
-
-    // R66 should be set according to Channel and use 20MHz when scanning
-	if (Channel <= 14)
-	{
-		// BG band
-		R66 = 0x2E + GET_LNA_GAIN(pAd);
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-	}
-	else
-	{
-		// 5.5 GHz band
-		if (pAd->ate.TxWI.BW == BW_20)
-		{
-			R66 = (UCHAR)(0x32 + (GET_LNA_GAIN(pAd)*5)/3);
-    		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-		}
-		else
-		{
-			R66 = (UCHAR)(0x3A + (GET_LNA_GAIN(pAd)*5)/3);
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-		}
-	}
-
-	//
-	// On 11A, We should delay and wait RF/BBP to be stable
-	// and the appropriate time should be 1000 micro seconds
-	// 2005/06/05 - On 11G, We also need this delay time. Otherwise it's difficult to pass the WHQL.
-	//
-	RTMPusecDelay(1000);
-
-	if (Channel > 14)
-	{
-		// When 5.5GHz band the LSB of TxPwr will be used to reduced 7dB or not.
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, %dT) to , R1=0x%08lx, R2=0x%08lx, R3=0x%08lx, R4=0x%08lx\n",
-								  Channel,
-								  pAd->RfIcType,
-								  pAd->Antenna.field.TxPath,
-								  pAd->LatchRfRegs.R1,
-								  pAd->LatchRfRegs.R2,
-								  pAd->LatchRfRegs.R3,
-								  pAd->LatchRfRegs.R4));
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%u, Pwr1=%u, %dT) to , R1=0x%08lx, R2=0x%08lx, R3=0x%08lx, R4=0x%08lx\n",
-								  Channel,
-								  pAd->RfIcType,
-								  (R3 & 0x00003e00) >> 9,
-								  (R4 & 0x000007c0) >> 6,
-								  pAd->Antenna.field.TxPath,
-								  pAd->LatchRfRegs.R1,
-								  pAd->LatchRfRegs.R2,
-								  pAd->LatchRfRegs.R3,
-								  pAd->LatchRfRegs.R4));
-    }
-}
-
-//
-// In fact, no one will call this routine so far !
-//
-/*
-	==========================================================================
-	Description:
-		Gives CCK TX rate 2 more dB TX power.
-		This routine works only in ATE mode.
-
-		calculate desired Tx power in RF R3.Tx0~5,	should consider -
-		0. if current radio is a noisy environment (pAd->DrsCounters.fNoisyEnvironment)
-		1. TxPowerPercentage
-		2. auto calibration based on TSSI feedback
-		3. extra 2 db for CCK
-		4. -10 db upon very-short distance (AvgRSSI >= -40db) to AP
-
-	NOTE: Since this routine requires the value of (pAd->DrsCounters.fNoisyEnvironment),
-		it should be called AFTER MlmeDynamicTxRateSwitching()
-	==========================================================================
- */
-VOID ATEAsicAdjustTxPower(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT			i, j;
-	CHAR		DeltaPwr = 0;
-	BOOLEAN		bAutoTxAgc = FALSE;
-	UCHAR		TssiRef, *pTssiMinusBoundary, *pTssiPlusBoundary, TxAgcStep;
-	UCHAR		BbpR49 = 0, idx;
-	PCHAR		pTxAgcCompensate;
-	ULONG		TxPwr[5];
-	CHAR		Value;
-
-	/* no one calls this procedure so far */
-	if (pAd->ate.TxWI.BW == BW_40)
-	{
-		if (pAd->ate.Channel > 14)
-		{
-			TxPwr[0] = pAd->Tx40MPwrCfgABand[0];
-			TxPwr[1] = pAd->Tx40MPwrCfgABand[1];
-			TxPwr[2] = pAd->Tx40MPwrCfgABand[2];
-			TxPwr[3] = pAd->Tx40MPwrCfgABand[3];
-			TxPwr[4] = pAd->Tx40MPwrCfgABand[4];
-		}
-		else
-		{
-			TxPwr[0] = pAd->Tx40MPwrCfgGBand[0];
-			TxPwr[1] = pAd->Tx40MPwrCfgGBand[1];
-			TxPwr[2] = pAd->Tx40MPwrCfgGBand[2];
-			TxPwr[3] = pAd->Tx40MPwrCfgGBand[3];
-			TxPwr[4] = pAd->Tx40MPwrCfgGBand[4];
-		}
-	}
-	else
-	{
-		if (pAd->ate.Channel > 14)
-		{
-			TxPwr[0] = pAd->Tx20MPwrCfgABand[0];
-			TxPwr[1] = pAd->Tx20MPwrCfgABand[1];
-			TxPwr[2] = pAd->Tx20MPwrCfgABand[2];
-			TxPwr[3] = pAd->Tx20MPwrCfgABand[3];
-			TxPwr[4] = pAd->Tx20MPwrCfgABand[4];
-		}
-		else
-		{
-			TxPwr[0] = pAd->Tx20MPwrCfgGBand[0];
-			TxPwr[1] = pAd->Tx20MPwrCfgGBand[1];
-			TxPwr[2] = pAd->Tx20MPwrCfgGBand[2];
-			TxPwr[3] = pAd->Tx20MPwrCfgGBand[3];
-			TxPwr[4] = pAd->Tx20MPwrCfgGBand[4];
-		}
-	}
-
-	// TX power compensation for temperature variation based on TSSI.
-	// Do it per 4 seconds.
-	if (pAd->Mlme.OneSecPeriodicRound % 4 == 0)
-	{
-		if (pAd->ate.Channel <= 14)
-		{
-			/* bg channel */
-			bAutoTxAgc         = pAd->bAutoTxAgcG;
-			TssiRef            = pAd->TssiRefG;
-			pTssiMinusBoundary = &pAd->TssiMinusBoundaryG[0];
-			pTssiPlusBoundary  = &pAd->TssiPlusBoundaryG[0];
-			TxAgcStep          = pAd->TxAgcStepG;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateG;
-		}
-		else
-		{
-			/* a channel */
-			bAutoTxAgc         = pAd->bAutoTxAgcA;
-			TssiRef            = pAd->TssiRefA;
-			pTssiMinusBoundary = &pAd->TssiMinusBoundaryA[0];
-			pTssiPlusBoundary  = &pAd->TssiPlusBoundaryA[0];
-			TxAgcStep          = pAd->TxAgcStepA;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateA;
-		}
-
-		if (bAutoTxAgc)
-		{
-			/* BbpR49 is unsigned char */
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R49, &BbpR49);
-
-			/* (p) TssiPlusBoundaryG[0] = 0 = (m) TssiMinusBoundaryG[0] */
-			/* compensate: +4     +3   +2   +1    0   -1   -2   -3   -4 * steps */
-			/* step value is defined in pAd->TxAgcStepG for tx power value */
-
-			/* [4]+1+[4]   p4     p3   p2   p1   o1   m1   m2   m3   m4 */
-			/* ex:         0x00 0x15 0x25 0x45 0x88 0xA0 0xB5 0xD0 0xF0
-			   above value are examined in mass factory production */
-			/*             [4]    [3]  [2]  [1]  [0]  [1]  [2]  [3]  [4] */
-
-			/* plus is 0x10 ~ 0x40, minus is 0x60 ~ 0x90 */
-			/* if value is between p1 ~ o1 or o1 ~ s1, no need to adjust tx power */
-			/* if value is 0x65, tx power will be -= TxAgcStep*(2-1) */
-
-			if (BbpR49 > pTssiMinusBoundary[1])
-			{
-				// Reading is larger than the reference value.
-				// Check for how large we need to decrease the Tx power.
-				for (idx = 1; idx < 5; idx++)
-				{
-					if (BbpR49 <= pTssiMinusBoundary[idx])  // Found the range
-						break;
-				}
-				// The index is the step we should decrease, idx = 0 means there is nothing to compensate
-//				if (R3 > (ULONG) (TxAgcStep * (idx-1)))
-					*pTxAgcCompensate = -(TxAgcStep * (idx-1));
-//				else
-//					*pTxAgcCompensate = -((UCHAR)R3);
-
-				DeltaPwr += (*pTxAgcCompensate);
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("-- Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = -%d\n",
-					BbpR49, TssiRef, TxAgcStep, idx-1));
-			}
-			else if (BbpR49 < pTssiPlusBoundary[1])
-			{
-				// Reading is smaller than the reference value
-				// check for how large we need to increase the Tx power
-				for (idx = 1; idx < 5; idx++)
-				{
-					if (BbpR49 >= pTssiPlusBoundary[idx])   // Found the range
-						break;
-				}
-				// The index is the step we should increase, idx = 0 means there is nothing to compensate
-				*pTxAgcCompensate = TxAgcStep * (idx-1);
-				DeltaPwr += (*pTxAgcCompensate);
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("++ Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
-					BbpR49, TssiRef, TxAgcStep, idx-1));
-			}
-			else
-			{
-				*pTxAgcCompensate = 0;
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("   Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
-					BbpR49, TssiRef, TxAgcStep, 0));
-			}
-		}
-	}
-	else
-	{
-		if (pAd->ate.Channel <= 14)
-		{
-			bAutoTxAgc         = pAd->bAutoTxAgcG;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateG;
-		}
-		else
-		{
-			bAutoTxAgc         = pAd->bAutoTxAgcA;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateA;
-		}
-
-		if (bAutoTxAgc)
-			DeltaPwr += (*pTxAgcCompensate);
-	}
-
-	/* calculate delta power based on the percentage specified from UI */
-	// E2PROM setting is calibrated for maximum TX power (i.e. 100%)
-	// We lower TX power here according to the percentage specified from UI
-	if (pAd->CommonCfg.TxPowerPercentage == 0xffffffff)       // AUTO TX POWER control
-		;
-	else if (pAd->CommonCfg.TxPowerPercentage > 90)  // 91 ~ 100% & AUTO, treat as 100% in terms of mW
-		;
-	else if (pAd->CommonCfg.TxPowerPercentage > 60)  // 61 ~ 90%, treat as 75% in terms of mW
-	{
-		DeltaPwr -= 1;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 30)  // 31 ~ 60%, treat as 50% in terms of mW
-	{
-		DeltaPwr -= 3;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 15)  // 16 ~ 30%, treat as 25% in terms of mW
-	{
-		DeltaPwr -= 6;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 9)   // 10 ~ 15%, treat as 12.5% in terms of mW
-	{
-		DeltaPwr -= 9;
-	}
-	else                                           // 0 ~ 9 %, treat as MIN(~3%) in terms of mW
-	{
-		DeltaPwr -= 12;
-	}
-
-	/* reset different new tx power for different TX rate */
-	for(i=0; i<5; i++)
-	{
-		if (TxPwr[i] != 0xffffffff)
-		{
-			for (j=0; j<8; j++)
-			{
-				Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F); /* 0 ~ 15 */
-
-				if ((Value + DeltaPwr) < 0)
-				{
-					Value = 0; /* min */
-				}
-				else if ((Value + DeltaPwr) > 0xF)
-				{
-					Value = 0xF; /* max */
-				}
-				else
-				{
-					Value += DeltaPwr; /* temperature compensation */
-				}
-
-				/* fill new value to CSR offset */
-				TxPwr[i] = (TxPwr[i] & ~(0x0000000F << j*4)) | (Value << j*4);
-			}
-
-			/* write tx power value to CSR */
-			/* TX_PWR_CFG_0 (8 tx rate) for	TX power for OFDM 12M/18M
-											TX power for OFDM 6M/9M
-											TX power for CCK5.5M/11M
-											TX power for CCK1M/2M */
-			/* TX_PWR_CFG_1 ~ TX_PWR_CFG_4 */
-			RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, TxPwr[i]);
-
-
-		}
-	}
-
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Write TxWI for ATE mode.
-
-	Return Value:
-		None
-	========================================================================
-*/
-static VOID ATEWriteTxWI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXWI_STRUC 	pOutTxWI,
-	IN	BOOLEAN			FRAG,
-	IN	BOOLEAN			CFACK,
-	IN	BOOLEAN			InsTimestamp,
-	IN	BOOLEAN 		AMPDU,
-	IN	BOOLEAN 		Ack,
-	IN	BOOLEAN 		NSeq,		// HW new a sequence.
-	IN	UCHAR			BASize,
-	IN	UCHAR			WCID,
-	IN	ULONG			Length,
-	IN	UCHAR 			PID,
-	IN	UCHAR			TID,
-	IN	UCHAR			TxRate,
-	IN	UCHAR			Txopmode,
-	IN	BOOLEAN			CfAck,
-	IN	HTTRANSMIT_SETTING	*pTransmit)
-{
-	TXWI_STRUC 		TxWI;
-	PTXWI_STRUC 	pTxWI;
-
-	//
-	// Always use Long preamble before verifiation short preamble functionality works well.
-	// Todo: remove the following line if short preamble functionality works
-	//
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-	NdisZeroMemory(&TxWI, TXWI_SIZE);
-	pTxWI = &TxWI;
-
-	pTxWI->FRAG= FRAG;
-
-	pTxWI->CFACK = CFACK;
-	pTxWI->TS= InsTimestamp;
-	pTxWI->AMPDU = AMPDU;
-	pTxWI->ACK = Ack;
-	pTxWI->txop= Txopmode;
-
-	pTxWI->NSEQ = NSeq;
-	// John tune the performace with Intel Client in 20 MHz performance
-	if( BASize >7 )
-		BASize =7;
-
-	pTxWI->BAWinSize = BASize;
-	pTxWI->WirelessCliID = WCID;
-	pTxWI->MPDUtotalByteCount = Length;
-	pTxWI->PacketId = PID;
-
-	// If CCK or OFDM, BW must be 20
-	pTxWI->BW = (pTransmit->field.MODE <= MODE_OFDM) ? (BW_20) : (pTransmit->field.BW);
-	pTxWI->ShortGI = pTransmit->field.ShortGI;
-	pTxWI->STBC = pTransmit->field.STBC;
-
-	pTxWI->MCS = pTransmit->field.MCS;
-	pTxWI->PHYMODE = pTransmit->field.MODE;
-	pTxWI->CFACK = CfAck;
-	pTxWI->MIMOps = 0;
-	pTxWI->MpduDensity = 0;
-
-	pTxWI->PacketId = pTxWI->MCS;
-	NdisMoveMemory(pOutTxWI, &TxWI, sizeof(TXWI_STRUC));
-
-        return;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Disable protection for ATE.
-	========================================================================
-*/
-VOID ATEDisableAsicProtect(
-	IN		PRTMP_ADAPTER	pAd)
-{
-	PROT_CFG_STRUC	ProtCfg, ProtCfg4;
-	UINT32 Protect[6];
-	USHORT			offset;
-	UCHAR			i;
-	UINT32 MacReg = 0;
-
-	// Config ASIC RTS threshold register
-	RTMP_IO_READ32(pAd, TX_RTS_CFG, &MacReg);
-	MacReg &= 0xFF0000FF;
-	MacReg |= (pAd->CommonCfg.RtsThreshold << 8);
-	RTMP_IO_WRITE32(pAd, TX_RTS_CFG, MacReg);
-
-	// Initial common protection settings
-	RTMPZeroMemory(Protect, sizeof(Protect));
-	ProtCfg4.word = 0;
-	ProtCfg.word = 0;
-	ProtCfg.field.TxopAllowGF40 = 1;
-	ProtCfg.field.TxopAllowGF20 = 1;
-	ProtCfg.field.TxopAllowMM40 = 1;
-	ProtCfg.field.TxopAllowMM20 = 1;
-	ProtCfg.field.TxopAllowOfdm = 1;
-	ProtCfg.field.TxopAllowCck = 1;
-	ProtCfg.field.RTSThEn = 1;
-	ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
-
-	// Handle legacy(B/G) protection
-	ProtCfg.field.ProtectRate = pAd->CommonCfg.RtsRate;
-	ProtCfg.field.ProtectCtrl = 0;
-	Protect[0] = ProtCfg.word;
-	Protect[1] = ProtCfg.word;
-
-	// NO PROTECT
-	// 1.All STAs in the BSS are 20/40 MHz HT
-	// 2. in ai 20/40MHz BSS
-	// 3. all STAs are 20MHz in a 20MHz BSS
-	// Pure HT. no protection.
-
-	// MM20_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 010111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4004 (OFDM 24M)
-	Protect[2] = 0x01744004;
-
-	// MM40_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 111111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4084 (duplicate OFDM 24M)
-	Protect[3] = 0x03f44084;
-
-	// CF20_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 010111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4004 (OFDM 24M)
-	Protect[4] = 0x01744004;
-
-	// CF40_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 111111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4084 (duplicate OFDM 24M)
-	Protect[5] = 0x03f44084;
-
-	pAd->CommonCfg.IOTestParm.bRTSLongProtOn = FALSE;
-
-	offset = CCK_PROT_CFG;
-	for (i = 0;i < 6;i++)
-		RTMP_IO_WRITE32(pAd, offset + i*4, Protect[i]);
-
-}
-
-
-/* There are two ways to convert Rssi */
-#if 1
-//
-// The way used with GET_LNA_GAIN().
-//
-CHAR ATEConvertToRssi(
-	IN PRTMP_ADAPTER pAd,
-	IN	CHAR	Rssi,
-	IN  UCHAR   RssiNumber)
-{
-	UCHAR	RssiOffset, LNAGain;
-
-	// Rssi equals to zero should be an invalid value
-	if (Rssi == 0)
-		return -99;
-
-	LNAGain = GET_LNA_GAIN(pAd);
-	if (pAd->LatchRfRegs.Channel > 14)
-	{
-		if (RssiNumber == 0)
-			RssiOffset = pAd->ARssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->ARssiOffset1;
-		else
-			RssiOffset = pAd->ARssiOffset2;
-	}
-	else
-	{
-		if (RssiNumber == 0)
-			RssiOffset = pAd->BGRssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->BGRssiOffset1;
-		else
-			RssiOffset = pAd->BGRssiOffset2;
-	}
-
-	return (-12 - RssiOffset - LNAGain - Rssi);
-}
-#else
-//
-// The way originally used in ATE of rt2860ap.
-//
-CHAR ATEConvertToRssi(
-	IN PRTMP_ADAPTER pAd,
-	IN	CHAR			Rssi,
-	IN  UCHAR   RssiNumber)
-{
-	UCHAR	RssiOffset, LNAGain;
-
-	// Rssi equals to zero should be an invalid value
-	if (Rssi == 0)
-		return -99;
-
-    if (pAd->LatchRfRegs.Channel > 14)
-    {
-        LNAGain = pAd->ALNAGain;
-        if (RssiNumber == 0)
-			RssiOffset = pAd->ARssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->ARssiOffset1;
-		else
-			RssiOffset = pAd->ARssiOffset2;
-    }
-    else
-    {
-        LNAGain = pAd->BLNAGain;
-        if (RssiNumber == 0)
-			RssiOffset = pAd->BGRssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->BGRssiOffset1;
-		else
-			RssiOffset = pAd->BGRssiOffset2;
-    }
-
-    return (-32 - RssiOffset + LNAGain - Rssi);
-}
-#endif /* end of #if 1 */
-
-/*
-	========================================================================
-
-	Routine Description:
-		Set Japan filter coefficients if needed.
-	Note:
-		This routine should only be called when
-		entering TXFRAME mode or TXCONT mode.
-
-	========================================================================
-*/
-static VOID SetJapanFilter(
-	IN		PRTMP_ADAPTER	pAd)
-{
-	UCHAR			BbpData = 0;
-
-	//
-	// If Channel=14 and Bandwidth=20M and Mode=CCK, set BBP R4 bit5=1
-	// (Japan Tx filter coefficients)when (TXFRAME or TXCONT).
-	//
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BbpData);
-
-    if ((pAd->ate.TxWI.PHYMODE == MODE_CCK) && (pAd->ate.Channel == 14) && (pAd->ate.TxWI.BW == BW_20))
-    {
-        BbpData |= 0x20;    // turn on
-        ATEDBGPRINT(RT_DEBUG_TRACE, ("SetJapanFilter!!!\n"));
-    }
-    else
-    {
-		BbpData &= 0xdf;    // turn off
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ClearJapanFilter!!!\n"));
-    }
-
-	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BbpData);
-}
-
-VOID ATESampleRssi(
-	IN PRTMP_ADAPTER	pAd,
-	IN PRXWI_STRUC		pRxWI)
-{
-	/* There are two ways to collect RSSI. */
-#if 1
-	//pAd->LastRxRate = (USHORT)((pRxWI->MCS) + (pRxWI->BW <<7) + (pRxWI->ShortGI <<8)+ (pRxWI->PHYMODE <<14)) ;
-	if (pRxWI->RSSI0 != 0)
-	{
-		pAd->ate.LastRssi0	= ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI0, RSSI_0);
-		pAd->ate.AvgRssi0X8	= (pAd->ate.AvgRssi0X8 - pAd->ate.AvgRssi0) + pAd->ate.LastRssi0;
-		pAd->ate.AvgRssi0  	= pAd->ate.AvgRssi0X8 >> 3;
-	}
-	if (pRxWI->RSSI1 != 0)
-	{
-		pAd->ate.LastRssi1	= ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI1, RSSI_1);
-		pAd->ate.AvgRssi1X8	= (pAd->ate.AvgRssi1X8 - pAd->ate.AvgRssi1) + pAd->ate.LastRssi1;
-		pAd->ate.AvgRssi1	= pAd->ate.AvgRssi1X8 >> 3;
-	}
-	if (pRxWI->RSSI2 != 0)
-	{
-		pAd->ate.LastRssi2	= ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI2, RSSI_2);
-		pAd->ate.AvgRssi2X8	= (pAd->ate.AvgRssi2X8 - pAd->ate.AvgRssi2) + pAd->ate.LastRssi2;
-		pAd->ate.AvgRssi2	= pAd->ate.AvgRssi2X8 >> 3;
-	}
-
-	pAd->ate.LastSNR0 = (CHAR)(pRxWI->SNR0);// CHAR ==> UCHAR ?
-	pAd->ate.LastSNR1 = (CHAR)(pRxWI->SNR1);// CHAR ==> UCHAR ?
-
-	pAd->ate.NumOfAvgRssiSample ++;
-#else
-	pAd->ate.LastSNR0 = (CHAR)(pRxWI->SNR0);
-	pAd->ate.LastSNR1 = (CHAR)(pRxWI->SNR1);
-	pAd->ate.RxCntPerSec++;
-	pAd->ate.LastRssi0 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI0, RSSI_0);
-	pAd->ate.LastRssi1 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI1, RSSI_1);
-	pAd->ate.LastRssi2 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI2, RSSI_2);
-	pAd->ate.AvgRssi0X8 = (pAd->ate.AvgRssi0X8 - pAd->ate.AvgRssi0) + pAd->ate.LastRssi0;
-	pAd->ate.AvgRssi0 = pAd->ate.AvgRssi0X8 >> 3;
-	pAd->ate.AvgRssi1X8 = (pAd->ate.AvgRssi1X8 - pAd->ate.AvgRssi1) + pAd->ate.LastRssi1;
-	pAd->ate.AvgRssi1 = pAd->ate.AvgRssi1X8 >> 3;
-	pAd->ate.AvgRssi2X8 = (pAd->ate.AvgRssi2X8 - pAd->ate.AvgRssi2) + pAd->ate.LastRssi2;
-	pAd->ate.AvgRssi2 = pAd->ate.AvgRssi2X8 >> 3;
-	pAd->ate.NumOfAvgRssiSample ++;
-#endif
-}
-
-#ifdef CONFIG_STA_SUPPORT
-VOID RTMPStationStop(
-    IN  PRTMP_ADAPTER   pAd)
-{
-//	BOOLEAN       Cancelled;
-
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("==> RTMPStationStop\n"));
-
-#if 0
-	RTMPCancelTimer(&pAd->MlmeAux.AssocTimer,      &Cancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer,    &Cancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer,   &Cancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.AuthTimer,       &Cancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer,     &Cancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.ScanTimer,       &Cancelled);
-#endif
-	// For rx statistics, we need to keep this timer running.
-//	RTMPCancelTimer(&pAd->Mlme.PeriodicTimer,      &Cancelled);
-
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("<== RTMPStationStop\n"));
-}
-
-VOID RTMPStationStart(
-    IN  PRTMP_ADAPTER   pAd)
-{
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("==> RTMPStationStart\n"));
-epAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-	//
-	// We did not cancel this timer when entering ATE mode.
-	//
-//	RTMPSetTimer(&pAd->Mlme.PeriodicTimer, MLME_TASK_EXEC_INTV);
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("<== RTMPStationStart\n"));
-}
-#endif // CONFIG_STA_SUPPORT //
-
-/*
-	==========================================================================
-	Description:
-		Setup Frame format.
-	NOTE:
-		This routine should only be used in ATE mode.
-	==========================================================================
- */
-static INT ATESetUpFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT32 TxIdx)
-{
-	UINT j;
-	PTXD_STRUC pTxD;
-#ifdef RT_BIG_ENDIAN
-    PTXD_STRUC      pDestTxD;
-    TXD_STRUC       TxD;
-#endif
-	PNDIS_PACKET pPacket;
-	PUCHAR pDest;
-	PVOID AllocVa;
-	NDIS_PHYSICAL_ADDRESS AllocPa;
-	HTTRANSMIT_SETTING	TxHTPhyMode;
-
-	PRTMP_TX_RING pTxRing = &pAd->TxRing[QID_AC_BE];
-	PTXWI_STRUC pTxWI = (PTXWI_STRUC) pTxRing->Cell[TxIdx].DmaBuf.AllocVa;
-	PUCHAR pDMAHeaderBufVA = (PUCHAR) pTxRing->Cell[TxIdx].DmaBuf.AllocVa;
-
-#ifdef RALINK_28xx_QA
-	PHEADER_802_11	pHeader80211;
-#endif // RALINK_28xx_QA //
-
-	if (pAd->ate.bQATxStart == TRUE)
-	{
-		// always use QID_AC_BE and FIFO_EDCA
-
-		// fill TxWI
-		TxHTPhyMode.field.BW = pAd->ate.TxWI.BW;
-		TxHTPhyMode.field.ShortGI = pAd->ate.TxWI.ShortGI;
-		TxHTPhyMode.field.STBC = 0;
-		TxHTPhyMode.field.MCS = pAd->ate.TxWI.MCS;
-		TxHTPhyMode.field.MODE = pAd->ate.TxWI.PHYMODE;
-		ATEWriteTxWI(pAd, pTxWI, pAd->ate.TxWI.FRAG, pAd->ate.TxWI.CFACK, pAd->ate.TxWI.TS,  pAd->ate.TxWI.AMPDU, pAd->ate.TxWI.ACK, pAd->ate.TxWI.NSEQ,
-			pAd->ate.TxWI.BAWinSize, 0, pAd->ate.TxWI.MPDUtotalByteCount, pAd->ate.TxWI.PacketId, 0, 0, pAd->ate.TxWI.txop/*IFS_HTTXOP*/, pAd->ate.TxWI.CFACK/*FALSE*/, &TxHTPhyMode);
-	}
-	else
-	{
-		TxHTPhyMode.field.BW = pAd->ate.TxWI.BW;
-		TxHTPhyMode.field.ShortGI = pAd->ate.TxWI.ShortGI;
-		TxHTPhyMode.field.STBC = 0;
-		TxHTPhyMode.field.MCS = pAd->ate.TxWI.MCS;
-		TxHTPhyMode.field.MODE = pAd->ate.TxWI.PHYMODE;
-		ATEWriteTxWI(pAd, pTxWI, FALSE, FALSE, FALSE,  FALSE, FALSE, FALSE,
-			4, 0, pAd->ate.TxLength, 0, 0, 0, IFS_HTTXOP, FALSE, &TxHTPhyMode);
-	}
-
-	// fill 802.11 header.
-#ifdef RALINK_28xx_QA
-	if (pAd->ate.bQATxStart == TRUE)
-	{
-		NdisMoveMemory(pDMAHeaderBufVA+TXWI_SIZE, pAd->ate.Header, pAd->ate.HLen);
-	}
-	else
-#endif // RALINK_28xx_QA //
-	{
-		NdisMoveMemory(pDMAHeaderBufVA+TXWI_SIZE, TemplateFrame, LENGTH_802_11);
-		NdisMoveMemory(pDMAHeaderBufVA+TXWI_SIZE+4, pAd->ate.Addr1, ETH_LENGTH_OF_ADDRESS);
-		NdisMoveMemory(pDMAHeaderBufVA+TXWI_SIZE+10, pAd->ate.Addr2, ETH_LENGTH_OF_ADDRESS);
-		NdisMoveMemory(pDMAHeaderBufVA+TXWI_SIZE+16, pAd->ate.Addr3, ETH_LENGTH_OF_ADDRESS);
-	}
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (((PUCHAR)pDMAHeaderBufVA)+TXWI_SIZE), DIR_READ, FALSE);
-#endif // RT_BIG_ENDIAN //
-
-	/* alloc buffer for payload */
-#ifdef RALINK_28xx_QA
-	if (pAd->ate.bQATxStart == TRUE)
-	{
-		/* Why not use RTMP_AllocateTxPacketBuffer() instead of RTMP_AllocateRxPacketBuffer()? */
-		pPacket = RTMP_AllocateRxPacketBuffer(pAd, pAd->ate.DLen + 0x100, FALSE, &AllocVa, &AllocPa);
-	}
-	else
-#endif // RALINK_28xx_QA //
-	{
-		/* Why not use RTMP_AllocateTxPacketBuffer() instead of RTMP_AllocateRxPacketBuffer()? */
-		pPacket = RTMP_AllocateRxPacketBuffer(pAd, pAd->ate.TxLength, FALSE, &AllocVa, &AllocPa);
-	}
-
-	if (pPacket == NULL)
-	{
-		pAd->ate.TxCount = 0;
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("%s fail to alloc packet space.\n", __func__));
-		return -1;
-	}
-	pTxRing->Cell[TxIdx].pNextNdisPacket = pPacket;
-
-	pDest = (PUCHAR) AllocVa;
-
-#ifdef RALINK_28xx_QA
-	if (pAd->ate.bQATxStart == TRUE)
-	{
-		RTPKT_TO_OSPKT(pPacket)->len = pAd->ate.DLen;
-	}
-	else
-#endif // RALINK_28xx_QA //
-	{
-		RTPKT_TO_OSPKT(pPacket)->len = pAd->ate.TxLength - LENGTH_802_11;
-	}
-
-	// Prepare frame payload
-#ifdef RALINK_28xx_QA
-	if (pAd->ate.bQATxStart == TRUE)
-	{
-		// copy pattern
-		if ((pAd->ate.PLen != 0))
-		{
-			int j;
-
-			for (j = 0; j < pAd->ate.DLen; j+=pAd->ate.PLen)
-			{
-				memcpy(RTPKT_TO_OSPKT(pPacket)->data + j, pAd->ate.Pattern, pAd->ate.PLen);
-			}
-		}
-	}
-	else
-#endif // RALINK_28xx_QA //
-	{
-		for(j = 0; j < RTPKT_TO_OSPKT(pPacket)->len; j++)
-			pDest[j] = 0xA5;
-	}
-
-	//
-	// build Tx Descriptor
-	//
-#ifndef RT_BIG_ENDIAN
-	pTxD = (PTXD_STRUC) pTxRing->Cell[TxIdx].AllocVa;
-#else
-    pDestTxD  = (PTXD_STRUC)pTxRing->Cell[TxIdx].AllocVa;
-    TxD = *pDestTxD;
-    pTxD = &TxD;
-#endif // !RT_BIG_ENDIAN //
-
-#ifdef RALINK_28xx_QA
-	if (pAd->ate.bQATxStart == TRUE)
-	{
-		// prepare TxD
-		NdisZeroMemory(pTxD, TXD_SIZE);
-		RTMPWriteTxDescriptor(pAd, pTxD, FALSE, FIFO_EDCA);
-		// build TX DESC
-		pTxD->SDPtr0 = RTMP_GetPhysicalAddressLow(pTxRing->Cell[TxIdx].DmaBuf.AllocPa);
-		pTxD->SDLen0 = TXWI_SIZE + pAd->ate.HLen;
-		pTxD->LastSec0 = 0;
-		pTxD->SDPtr1 = AllocPa;
-		pTxD->SDLen1 = RTPKT_TO_OSPKT(pPacket)->len;
-		pTxD->LastSec1 = 1;
-
-		pDest = (PUCHAR)pTxWI;
-		pDest += TXWI_SIZE;
-		pHeader80211 = (PHEADER_802_11)pDest;
-
-		// modify sequence number....
-		if (pAd->ate.TxDoneCount == 0)
-		{
-			pAd->ate.seq = pHeader80211->Sequence;
-		}
-		else
-			pHeader80211->Sequence = ++pAd->ate.seq;
-	}
-	else
-#endif // RALINK_28xx_QA //
-	{
-		NdisZeroMemory(pTxD, TXD_SIZE);
-		RTMPWriteTxDescriptor(pAd, pTxD, FALSE, FIFO_EDCA);
-		// build TX DESC
-		pTxD->SDPtr0 = RTMP_GetPhysicalAddressLow (pTxRing->Cell[TxIdx].DmaBuf.AllocPa);
-		pTxD->SDLen0 = TXWI_SIZE + LENGTH_802_11;
-		pTxD->LastSec0 = 0;
-		pTxD->SDPtr1 = AllocPa;
-		pTxD->SDLen1 = RTPKT_TO_OSPKT(pPacket)->len;
-		pTxD->LastSec1 = 1;
-	}
-
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-	RTMPFrameEndianChange(pAd, (((PUCHAR)pDMAHeaderBufVA)+TXWI_SIZE), DIR_WRITE, FALSE);
-    RTMPDescriptorEndianChange((PUCHAR)pTxD, TYPE_TXD);
-    WriteBackToDescriptor((PUCHAR)pDestTxD, (PUCHAR)pTxD, FALSE, TYPE_TXD);
-#endif // RT_BIG_ENDIAN //
-	return 0;
-}
-/*                                                           */
-/*                                                           */
-/*=======================End of RT2860=======================*/
-
-
-VOID rt_ee_read_all(PRTMP_ADAPTER pAd, USHORT *Data)
-{
-	USHORT i;
-	USHORT value;
-
-	for (i = 0 ; i < EEPROM_SIZE/2 ; )
-	{
-		/* "value" is expecially for some compilers... */
-		RT28xx_EEPROM_READ16(pAd, i*2, value);
-		Data[i] = value;
-		i++;
-	}
-}
-
-VOID rt_ee_write_all(PRTMP_ADAPTER pAd, USHORT *Data)
-{
-	USHORT i;
-	USHORT value;
-
-	for (i = 0 ; i < EEPROM_SIZE/2 ; )
-	{
-		/* "value" is expecially for some compilers... */
-		value = Data[i];
-		RT28xx_EEPROM_WRITE16(pAd, i*2, value);
-		i ++;
-	}
-}
-#ifdef RALINK_28xx_QA
-VOID ATE_QA_Statistics(
-	IN PRTMP_ADAPTER			pAd,
-	IN PRXWI_STRUC				pRxWI,
-	IN PRT28XX_RXD_STRUC		pRxD,
-	IN PHEADER_802_11			pHeader)
-{
-	// update counter first
-	if (pHeader != NULL)
-	{
-		if (pHeader->FC.Type == BTYPE_DATA)
-		{
-			if (pRxD->U2M)
-				pAd->ate.U2M++;
-			else
-				pAd->ate.OtherData++;
-		}
-		else if (pHeader->FC.Type == BTYPE_MGMT)
-		{
-			if (pHeader->FC.SubType == SUBTYPE_BEACON)
-				pAd->ate.Beacon++;
-			else
-				pAd->ate.OtherCount++;
-		}
-		else if (pHeader->FC.Type == BTYPE_CNTL)
-		{
-			pAd->ate.OtherCount++;
-		}
-	}
-	pAd->ate.RSSI0 = pRxWI->RSSI0;
-	pAd->ate.RSSI1 = pRxWI->RSSI1;
-	pAd->ate.RSSI2 = pRxWI->RSSI2;
-	pAd->ate.SNR0 = pRxWI->SNR0;
-	pAd->ate.SNR1 = pRxWI->SNR1;
-}
-
-/* command id with Cmd Type == 0x0008(for 28xx)/0x0005(for iNIC) */
-#define RACFG_CMD_RF_WRITE_ALL		0x0000
-#define RACFG_CMD_E2PROM_READ16		0x0001
-#define RACFG_CMD_E2PROM_WRITE16	0x0002
-#define RACFG_CMD_E2PROM_READ_ALL	0x0003
-#define RACFG_CMD_E2PROM_WRITE_ALL	0x0004
-#define RACFG_CMD_IO_READ			0x0005
-#define RACFG_CMD_IO_WRITE			0x0006
-#define RACFG_CMD_IO_READ_BULK		0x0007
-#define RACFG_CMD_BBP_READ8			0x0008
-#define RACFG_CMD_BBP_WRITE8		0x0009
-#define RACFG_CMD_BBP_READ_ALL		0x000a
-#define RACFG_CMD_GET_COUNTER		0x000b
-#define RACFG_CMD_CLEAR_COUNTER		0x000c
-
-#define RACFG_CMD_RSV1				0x000d
-#define RACFG_CMD_RSV2				0x000e
-#define RACFG_CMD_RSV3				0x000f
-
-#define RACFG_CMD_TX_START			0x0010
-#define RACFG_CMD_GET_TX_STATUS		0x0011
-#define RACFG_CMD_TX_STOP			0x0012
-#define RACFG_CMD_RX_START			0x0013
-#define RACFG_CMD_RX_STOP			0x0014
-#define RACFG_CMD_GET_NOISE_LEVEL	0x0015
-
-#define RACFG_CMD_ATE_START			0x0080
-#define RACFG_CMD_ATE_STOP			0x0081
-
-#define RACFG_CMD_ATE_START_TX_CARRIER		0x0100
-#define RACFG_CMD_ATE_START_TX_CONT			0x0101
-#define RACFG_CMD_ATE_START_TX_FRAME		0x0102
-#define RACFG_CMD_ATE_SET_BW	            0x0103
-#define RACFG_CMD_ATE_SET_TX_POWER0	        0x0104
-#define RACFG_CMD_ATE_SET_TX_POWER1			0x0105
-#define RACFG_CMD_ATE_SET_FREQ_OFFSET		0x0106
-#define RACFG_CMD_ATE_GET_STATISTICS		0x0107
-#define RACFG_CMD_ATE_RESET_COUNTER			0x0108
-#define RACFG_CMD_ATE_SEL_TX_ANTENNA		0x0109
-#define RACFG_CMD_ATE_SEL_RX_ANTENNA		0x010a
-#define RACFG_CMD_ATE_SET_PREAMBLE			0x010b
-#define RACFG_CMD_ATE_SET_CHANNEL			0x010c
-#define RACFG_CMD_ATE_SET_ADDR1				0x010d
-#define RACFG_CMD_ATE_SET_ADDR2				0x010e
-#define RACFG_CMD_ATE_SET_ADDR3				0x010f
-#define RACFG_CMD_ATE_SET_RATE				0x0110
-#define RACFG_CMD_ATE_SET_TX_FRAME_LEN		0x0111
-#define RACFG_CMD_ATE_SET_TX_FRAME_COUNT	0x0112
-#define RACFG_CMD_ATE_START_RX_FRAME		0x0113
-#define RACFG_CMD_ATE_E2PROM_READ_BULK	0x0114
-#define RACFG_CMD_ATE_E2PROM_WRITE_BULK	0x0115
-#define RACFG_CMD_ATE_IO_WRITE_BULK		0x0116
-#define RACFG_CMD_ATE_BBP_READ_BULK		0x0117
-#define RACFG_CMD_ATE_BBP_WRITE_BULK	0x0118
-#define RACFG_CMD_ATE_RF_READ_BULK		0x0119
-#define RACFG_CMD_ATE_RF_WRITE_BULK		0x011a
-
-
-
-#define A2Hex(_X, _p) 				\
-{									\
-	UCHAR *p;						\
-	_X = 0;							\
-	p = _p;							\
-	while (((*p >= 'a') && (*p <= 'f')) || ((*p >= 'A') && (*p <= 'F')) || ((*p >= '0') && (*p <= '9')))		\
-	{												\
-		if ((*p >= 'a') && (*p <= 'f'))				\
-			_X = _X * 16 + *p - 87;					\
-		else if ((*p >= 'A') && (*p <= 'F'))		\
-			_X = _X * 16 + *p - 55;					\
-		else if ((*p >= '0') && (*p <= '9'))		\
-			_X = _X * 16 + *p - 48;					\
-		p++;										\
-	}												\
-}
-
-
-static VOID memcpy_exl(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len);
-static VOID memcpy_exs(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len);
-static VOID RTMP_IO_READ_BULK(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, UINT32 len);
-
-#ifdef UCOS
-int ate_copy_to_user(
-	IN PUCHAR payload,
-	IN PUCHAR msg,
-	IN INT    len)
-{
-	memmove(payload, msg, len);
-	return 0;
-}
-
-#undef	copy_to_user
-#define copy_to_user(x,y,z) ate_copy_to_user((PUCHAR)x, (PUCHAR)y, z)
-#endif // UCOS //
-
-#define	LEN_OF_ARG 16
-
-VOID RtmpDoAte(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	unsigned short Command_Id;
-	struct ate_racfghdr *pRaCfg;
-	INT	Status = NDIS_STATUS_SUCCESS;
-
-
-
-	if((pRaCfg = kmalloc(sizeof(struct ate_racfghdr), GFP_KERNEL)) == NULL)
-	{
-		Status = -EINVAL;
-		return;
-	}
-
-	NdisZeroMemory(pRaCfg, sizeof(struct ate_racfghdr));
-
-    if (copy_from_user((PUCHAR)pRaCfg, wrq->u.data.pointer, wrq->u.data.length))
-	{
-		Status = -EFAULT;
-		kfree(pRaCfg);
-		return;
-	}
-
-
-	Command_Id = ntohs(pRaCfg->command_id);
-
-	ATEDBGPRINT(RT_DEBUG_TRACE,("\n%s: Command_Id = 0x%04x !\n", __func__, Command_Id));
-
-	switch (Command_Id)
-	{
- 		// We will get this command when QA starts.
-		case RACFG_CMD_ATE_START:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START\n"));
-
-				// prepare feedback as soon as we can to avoid QA timeout.
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_TRACE, ("copy_to_user() fail in case RACFG_CMD_ATE_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START is done !\n"));
-				}
-				Set_ATE_Proc(pAdapter, "ATESTART");
-			}
-			break;
-
- 		// We will get this command either QA is closed or ated is killed by user.
-		case RACFG_CMD_ATE_STOP:
-			{
-#ifndef UCOS
-				INT32 ret;
-#endif // !UCOS //
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_STOP\n"));
-
-				// Distinguish this command came from QA(via ated)
-				// or ate daemon according to the existence of pid in payload.
-				// No need to prepare feedback if this cmd came directly from ate daemon.
-				pRaCfg->length = ntohs(pRaCfg->length);
-
-				if (pRaCfg->length == sizeof(pAdapter->ate.AtePid))
-				{
-					// This command came from QA.
-					// Get the pid of ATE daemon.
-					memcpy((UCHAR *)&pAdapter->ate.AtePid,
-						(&pRaCfg->data[0]) - 2/* == &(pRaCfg->status) */,
-						sizeof(pAdapter->ate.AtePid));
-
-					// prepare feedback as soon as we can to avoid QA timeout.
-					pRaCfg->length = htons(2);
-					pRaCfg->status = htons(0);
-
-					wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-										+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-										+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-	            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-	            	{
-	            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_STOP\n"));
-	                    Status = -EFAULT;
-	            	}
-
-					//
-					// kill ATE daemon when leaving ATE mode.
-					// We must kill ATE daemon first before setting ATESTOP,
-					// or Microsoft will report sth. wrong.
-#ifndef UCOS
-					ret = KILL_THREAD_PID(pAdapter->ate.AtePid, SIGTERM, 1);
-					if (ret)
-					{
-						ATEDBGPRINT(RT_DEBUG_ERROR, ("%s: unable to signal thread\n", pAdapter->net_dev->name));
-					}
-#endif // !UCOS //
-				}
-
-				// AP might have in ATE_STOP mode due to cmd from QA.
-				if (ATE_ON(pAdapter))
-				{
-					// Someone has killed ate daemon while QA GUI is still open.
-					Set_ATE_Proc(pAdapter, "ATESTOP");
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_AP_START is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_RF_WRITE_ALL:
-			{
-				UINT32 R1, R2, R3, R4;
-				USHORT channel;
-
-				memcpy(&R1, pRaCfg->data-2, 4);
-				memcpy(&R2, pRaCfg->data+2, 4);
-				memcpy(&R3, pRaCfg->data+6, 4);
-				memcpy(&R4, pRaCfg->data+10, 4);
-				memcpy(&channel, pRaCfg->data+14, 2);
-
-				pAdapter->LatchRfRegs.R1 = ntohl(R1);
-				pAdapter->LatchRfRegs.R2 = ntohl(R2);
-				pAdapter->LatchRfRegs.R3 = ntohl(R3);
-				pAdapter->LatchRfRegs.R4 = ntohl(R4);
-				pAdapter->LatchRfRegs.Channel = ntohs(channel);
-
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R1);
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R2);
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R3);
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R4);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RF_WRITE_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RF_WRITE_ALL is done !\n"));
-				}
-			}
-            break;
-
-		case RACFG_CMD_E2PROM_READ16:
-			{
-				USHORT	offset, value, tmp;
-
-				offset = ntohs(pRaCfg->status);
-				/* "tmp" is expecially for some compilers... */
-				RT28xx_EEPROM_READ16(pAdapter, offset, tmp);
-				value = tmp;
-				value = htons(value);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("EEPROM Read offset = 0x%04x, value = 0x%04x\n", offset, value));
-
-				// prepare feedback
-				pRaCfg->length = htons(4);
-				pRaCfg->status = htons(0);
-				memcpy(pRaCfg->data, &value, 2);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("sizeof(struct ate_racfghdr) = %d\n", sizeof(struct ate_racfghdr)));
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_READ16\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_E2PROM_READ16 is done !\n"));
-				}
-           	}
-			break;
-
-		case RACFG_CMD_E2PROM_WRITE16:
-			{
-				USHORT	offset, value;
-
-				offset = ntohs(pRaCfg->status);
-				memcpy(&value, pRaCfg->data, 2);
-				value = ntohs(value);
-				RT28xx_EEPROM_WRITE16(pAdapter, offset, value);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_WRITE16\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_E2PROM_WRITE16 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_E2PROM_READ_ALL:
-			{
-				USHORT buffer[EEPROM_SIZE/2];
-
-				rt_ee_read_all(pAdapter,(USHORT *)buffer);
-				memcpy_exs(pAdapter, pRaCfg->data, (UCHAR *)buffer, EEPROM_SIZE);
-
-				// prepare feedback
-				pRaCfg->length = htons(2+EEPROM_SIZE);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_READ_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_E2PROM_READ_ALL is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_E2PROM_WRITE_ALL:
-			{
-				USHORT buffer[EEPROM_SIZE/2];
-
-				NdisZeroMemory((UCHAR *)buffer, EEPROM_SIZE);
-				memcpy_exs(pAdapter, (UCHAR *)buffer, (UCHAR *)&pRaCfg->status, EEPROM_SIZE);
-				rt_ee_write_all(pAdapter,(USHORT *)buffer);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_WRITE_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_ERROR, ("RACFG_CMD_E2PROM_WRITE_ALL is done !\n"));
-				}
-
-			}
-			break;
-
-		case RACFG_CMD_IO_READ:
-			{
-				UINT32	offset;
-				UINT32	value;
-
-				memcpy(&offset, &pRaCfg->status, 4);
-				offset = ntohl(offset);
-
-				// We do not need the base address.
-				// So just extract the offset out.
-				offset &= 0x0000FFFF;
-				RTMP_IO_READ32(pAdapter, offset, &value);
-				value = htonl(value);
-
-				// prepare feedback
-				pRaCfg->length = htons(6);
-				pRaCfg->status = htons(0);
-				memcpy(pRaCfg->data, &value, 4);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_IO_READ\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_IO_READ is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_IO_WRITE:
-			{
-				UINT32	offset, value;
-
-				memcpy(&offset, pRaCfg->data-2, 4);
-				memcpy(&value, pRaCfg->data+2, 4);
-
-				offset = ntohl(offset);
-
-				// We do not need the base address.
-				// So just extract out the offset.
-				offset &= 0x0000FFFF;
-				value = ntohl(value);
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_IO_WRITE: offset = %x, value = %x\n", offset, value));
-				RTMP_IO_WRITE32(pAdapter, offset, value);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_IO_WRITE\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_IO_WRITE is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_IO_READ_BULK:
-			{
-				UINT32	offset;
-				USHORT	len;
-
-				memcpy(&offset, &pRaCfg->status, 4);
-				offset = ntohl(offset);
-
-				// We do not need the base address.
-				// So just extract the offset.
-				offset &= 0x0000FFFF;
-				memcpy(&len, pRaCfg->data+2, 2);
-				len = ntohs(len);
-
-				if (len > 371)
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE,("len is too large, make it smaller\n"));
-					pRaCfg->length = htons(2);
-					pRaCfg->status = htons(1);
-					break;
-				}
-
-				RTMP_IO_READ_BULK(pAdapter, pRaCfg->data, (UCHAR *)offset, len*4);// unit in four bytes
-
-				// prepare feedback
-				pRaCfg->length = htons(2+len*4);// unit in four bytes
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_IO_READ_BULK\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_IO_READ_BULK is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_BBP_READ8:
-			{
-				USHORT	offset;
-				UCHAR	value;
-
-				value = 0;
-				offset = ntohs(pRaCfg->status);
-
-				if (ATE_ON(pAdapter))
-				{
-					ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, offset,  &value);
-				}
-				else
-				{
-					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, offset,  &value);
-				}
-				// prepare feedback
-				pRaCfg->length = htons(3);
-				pRaCfg->status = htons(0);
-				pRaCfg->data[0] = value;
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("BBP value = %x\n", value));
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_BBP_READ8\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_BBP_READ8 is done !\n"));
-				}
-			}
-			break;
-		case RACFG_CMD_BBP_WRITE8:
-			{
-				USHORT	offset;
-				UCHAR	value;
-
-				offset = ntohs(pRaCfg->status);
-				memcpy(&value, pRaCfg->data, 1);
-
-				if (ATE_ON(pAdapter))
-				{
-					ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, offset,  value);
-				}
-				else
-				{
-					RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, offset,  value);
-				}
-
-				if ((offset == BBP_R1) || (offset == BBP_R3))
-				{
-					SyncTxRxConfig(pAdapter, offset, value);
-				}
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_BBP_WRITE8\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_BBP_WRITE8 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_BBP_READ_ALL:
-			{
-				USHORT j;
-
-				for (j = 0; j < 137; j++)
-				{
-					pRaCfg->data[j] = 0;
-
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j]);
-					}
-					else
-					{
-						RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j]);
-					}
-				}
-
-				// prepare feedback
-				pRaCfg->length = htons(2+137);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_BBP_READ_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_BBP_READ_ALL is done !\n"));
-				}
-			}
-
-			break;
-
-		case RACFG_CMD_ATE_E2PROM_READ_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT buffer[EEPROM_SIZE/2];
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			rt_ee_read_all(pAdapter,(USHORT *)buffer);
-			if (offset + len <= EEPROM_SIZE)
-				memcpy_exs(pAdapter, pRaCfg->data, (UCHAR *)buffer+offset, len);
-			else
-				ATEDBGPRINT(RT_DEBUG_ERROR, ("exceed EEPROM size\n"));
-
-			// prepare feedback
-			pRaCfg->length = htons(2+len);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_E2PROM_READ_BULK\n"));
-                Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_E2PROM_READ_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_E2PROM_WRITE_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT buffer[EEPROM_SIZE/2];
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			rt_ee_read_all(pAdapter,(USHORT *)buffer);
-			memcpy_exs(pAdapter, (UCHAR *)buffer + offset, (UCHAR *)pRaCfg->data + 2, len);
-			rt_ee_write_all(pAdapter,(USHORT *)buffer);
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_E2PROM_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_ERROR, ("RACFG_CMD_ATE_E2PROM_WRITE_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_IO_WRITE_BULK:
-		{
-			UINT32 offset, i, value;
-			USHORT len;
-
-			memcpy(&offset, &pRaCfg->status, 4);
-			offset = ntohl(offset);
-			memcpy(&len, pRaCfg->data+2, 2);
-			len = ntohs(len);
-
-			for (i = 0; i < len; i += 4)
-			{
-				memcpy_exl(pAdapter, (UCHAR *)&value, pRaCfg->data+4+i, 4);
-				printk("Write %x %x\n", offset + i, value);
-				RTMP_IO_WRITE32(pAdapter, (offset +i) & 0xffff, value);
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_IO_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_ERROR, ("RACFG_CMD_ATE_IO_WRITE_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_BBP_READ_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				pRaCfg->data[j - offset] = 0;
-
-				if (pAdapter->ate.Mode == ATE_STOP)
-				{
-					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j - offset]);
-				}
-				else
-				{
-					ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j - offset]);
-				}
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2+len);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_BBP_READ_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_BBP_READ_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_BBP_WRITE_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-			UCHAR *value;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				value = pRaCfg->data + 2 + (j - offset);
-				if (pAdapter->ate.Mode == ATE_STOP)
-				{
-					RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, j,  *value);
-				}
-				else
-				{
-					ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, j,  *value);
-				}
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_BBP_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_BBP_WRITE_BULK is done !\n"));
-			}
-		}
-			break;
-
-#ifdef CONFIG_RALINK_RT3052
-		case RACFG_CMD_ATE_RF_READ_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				pRaCfg->data[j - offset] = 0;
-				RT30xxReadRFRegister(pAdapter, j,  &pRaCfg->data[j - offset]);
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2+len);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_RF_READ_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_RF_READ_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_RF_WRITE_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-			UCHAR *value;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				value = pRaCfg->data + 2 + (j - offset);
-				RT30xxWriteRFRegister(pAdapter, j,  *value);
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_RF_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_RF_WRITE_BULK is done !\n"));
-			}
-
-		}
-			break;
-#endif
-
-
-		case RACFG_CMD_GET_NOISE_LEVEL:
-			{
-				UCHAR	channel;
-				INT32   buffer[3][10];/* 3 : RxPath ; 10 : no. of per rssi samples */
-
-				channel = (ntohs(pRaCfg->status) & 0x00FF);
-				CalNoiseLevel(pAdapter, channel, buffer);
-				memcpy_exl(pAdapter, (UCHAR *)pRaCfg->data, (UCHAR *)&(buffer[0][0]), (sizeof(INT32)*3*10));
-
-				// prepare feedback
-				pRaCfg->length = htons(2 + (sizeof(INT32)*3*10));
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_GET_NOISE_LEVEL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_GET_NOISE_LEVEL is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_GET_COUNTER:
-			{
-				memcpy_exl(pAdapter, &pRaCfg->data[0], (UCHAR *)&pAdapter->ate.U2M, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[4], (UCHAR *)&pAdapter->ate.OtherData, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[8], (UCHAR *)&pAdapter->ate.Beacon, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[12], (UCHAR *)&pAdapter->ate.OtherCount, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[16], (UCHAR *)&pAdapter->ate.TxAc0, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[20], (UCHAR *)&pAdapter->ate.TxAc1, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[24], (UCHAR *)&pAdapter->ate.TxAc2, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[28], (UCHAR *)&pAdapter->ate.TxAc3, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[32], (UCHAR *)&pAdapter->ate.TxHCCA, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[36], (UCHAR *)&pAdapter->ate.TxMgmt, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&pAdapter->ate.RSSI0, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[44], (UCHAR *)&pAdapter->ate.RSSI1, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[48], (UCHAR *)&pAdapter->ate.RSSI2, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[52], (UCHAR *)&pAdapter->ate.SNR0, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[56], (UCHAR *)&pAdapter->ate.SNR1, 4);
-
-				pRaCfg->length = htons(2+60);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_GET_COUNTER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_GET_COUNTER is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_CLEAR_COUNTER:
-			{
-				pAdapter->ate.U2M = 0;
-				pAdapter->ate.OtherData = 0;
-				pAdapter->ate.Beacon = 0;
-				pAdapter->ate.OtherCount = 0;
-				pAdapter->ate.TxAc0 = 0;
-				pAdapter->ate.TxAc1 = 0;
-				pAdapter->ate.TxAc2 = 0;
-				pAdapter->ate.TxAc3 = 0;
-				pAdapter->ate.TxHCCA = 0;
-				pAdapter->ate.TxMgmt = 0;
-				pAdapter->ate.TxDoneCount = 0;
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_CLEAR_COUNTER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_CLEAR_COUNTER is done !\n"));
-				}
-			}
-
-			break;
-
-		case RACFG_CMD_TX_START:
-			{
-				USHORT *p;
-				USHORT	err = 1;
-				UCHAR   Bbp22Value = 0, Bbp24Value = 0;
-
-				if ((pAdapter->ate.TxStatus != 0) && (pAdapter->ate.Mode & ATE_TXFRAME))
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE,("Ate Tx is already running, to run next Tx, you must stop it first\n"));
-					err = 2;
-					goto TX_START_ERROR;
-				}
-				else if ((pAdapter->ate.TxStatus != 0) && !(pAdapter->ate.Mode & ATE_TXFRAME))
-				{
-					int i = 0;
-
-					while ((i++ < 10) && (pAdapter->ate.TxStatus != 0))
-					{
-						RTMPusecDelay(5000);
-					}
-
-					// force it to stop
-					pAdapter->ate.TxStatus = 0;
-					pAdapter->ate.TxDoneCount = 0;
-					//pAdapter->ate.Repeat = 0;
-					pAdapter->ate.bQATxStart = FALSE;
-				}
-
-				// If pRaCfg->length == 0, this "RACFG_CMD_TX_START" is for Carrier test or Carrier Suppression.
-				if (ntohs(pRaCfg->length) != 0)
-				{
-					// Get frame info
-
-					NdisMoveMemory(&pAdapter->ate.TxWI, pRaCfg->data + 2, 16);
-#ifdef RT_BIG_ENDIAN
-					RTMPWIEndianChange((PUCHAR)&pAdapter->ate.TxWI, TYPE_TXWI);
-#endif // RT_BIG_ENDIAN //
-
-					NdisMoveMemory(&pAdapter->ate.TxCount, pRaCfg->data + 18, 4);
-					pAdapter->ate.TxCount = ntohl(pAdapter->ate.TxCount);
-
-					p = (USHORT *)(&pRaCfg->data[22]);
-					//p = pRaCfg->data + 22;
-					// always use QID_AC_BE
-					pAdapter->ate.QID = 0;
-					p = (USHORT *)(&pRaCfg->data[24]);
-					//p = pRaCfg->data + 24;
-					pAdapter->ate.HLen = ntohs(*p);
-
-					if (pAdapter->ate.HLen > 32)
-					{
-						ATEDBGPRINT(RT_DEBUG_ERROR,("pAdapter->ate.HLen > 32\n"));
-						err = 3;
-						goto TX_START_ERROR;
-					}
-
-					NdisMoveMemory(&pAdapter->ate.Header, pRaCfg->data + 26, pAdapter->ate.HLen);
-
-
-					pAdapter->ate.PLen = ntohs(pRaCfg->length) - (pAdapter->ate.HLen + 28);
-
-					if (pAdapter->ate.PLen > 32)
-					{
-						ATEDBGPRINT(RT_DEBUG_ERROR,("pAdapter->ate.PLen > 32\n"));
-						err = 4;
-						goto TX_START_ERROR;
-					}
-
-					NdisMoveMemory(&pAdapter->ate.Pattern, pRaCfg->data + 26 + pAdapter->ate.HLen, pAdapter->ate.PLen);
-					pAdapter->ate.DLen = pAdapter->ate.TxWI.MPDUtotalByteCount - pAdapter->ate.HLen;
-				}
-
-				ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R22, &Bbp22Value);
-
-				switch (Bbp22Value)
-				{
-					case BBP22_TXFRAME:
-						{
-							if (pAdapter->ate.TxCount == 0)
-							{
-								pAdapter->ate.TxCount = 0xFFFFFFFF;
-							}
-							ATEDBGPRINT(RT_DEBUG_TRACE,("START TXFRAME\n"));
-							pAdapter->ate.bQATxStart = TRUE;
-							Set_ATE_Proc(pAdapter, "TXFRAME");
-						}
-						break;
-
-					case BBP22_TXCONT_OR_CARRSUPP:
-						{
-							ATEDBGPRINT(RT_DEBUG_TRACE,("BBP22_TXCONT_OR_CARRSUPP\n"));
-							ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, 24, &Bbp24Value);
-
-							switch (Bbp24Value)
-							{
-								case BBP24_TXCONT:
-									{
-										ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCONT\n"));
-										pAdapter->ate.bQATxStart = TRUE;
-										Set_ATE_Proc(pAdapter, "TXCONT");
-									}
-									break;
-
-								case BBP24_CARRSUPP:
-									{
-										ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCARRSUPP\n"));
-										pAdapter->ate.bQATxStart = TRUE;
-										pAdapter->ate.Mode |= ATE_TXCARRSUPP;
-									}
-									break;
-
-								default:
-									{
-										ATEDBGPRINT(RT_DEBUG_ERROR,("Unknown Start TX subtype !"));
-									}
-									break;
-							}
-						}
-						break;
-
-					case BBP22_TXCARR:
-						{
-							ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCARR\n"));
-							pAdapter->ate.bQATxStart = TRUE;
-							Set_ATE_Proc(pAdapter, "TXCARR");
-						}
-						break;
-
-					default:
-						{
-							ATEDBGPRINT(RT_DEBUG_ERROR,("Unknown Start TX subtype !"));
-						}
-						break;
-				}
-
-				if (pAdapter->ate.bQATxStart == TRUE)
-				{
-					// prepare feedback
-					pRaCfg->length = htons(2);
-					pRaCfg->status = htons(0);
-
-					wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-										+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-										+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-	            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-	            	{
-	            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() was failed in case RACFG_CMD_TX_START\n"));
-	                    Status = -EFAULT;
-	            	}
-					else
-					{
-	                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_TX_START is done !\n"));
-					}
-					break;
-				}
-
-TX_START_ERROR:
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(err);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_TX_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("feedback of TX_START_ERROR is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_GET_TX_STATUS:
-			{
-				UINT32 count;
-
-				// prepare feedback
-				pRaCfg->length = htons(6);
-				pRaCfg->status = htons(0);
-				count = htonl(pAdapter->ate.TxDoneCount);
-				NdisMoveMemory(pRaCfg->data, &count, 4);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_GET_TX_STATUS\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_GET_TX_STATUS is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_TX_STOP:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_TX_STOP\n"));
-
-				Set_ATE_Proc(pAdapter, "TXSTOP");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_TRACE, ("copy_to_user() fail in case RACFG_CMD_TX_STOP\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_TX_STOP is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_RX_START:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_START\n"));
-
-				pAdapter->ate.bQARxStart = TRUE;
-				Set_ATE_Proc(pAdapter, "RXFRAME");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RX_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RX_START is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_RX_STOP:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_STOP\n"));
-
-				Set_ATE_Proc(pAdapter, "RXSTOP");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RX_STOP\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RX_STOP is done !\n"));
-				}
-			}
-			break;
-
-		/* The following cases are for new ATE GUI(not QA). */
-		/*==================================================*/
-		case RACFG_CMD_ATE_START_TX_CARRIER:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_CARRIER\n"));
-
-				Set_ATE_Proc(pAdapter, "TXCARR");
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_START_TX_CARRIER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START_TX_CARRIER is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_START_TX_CONT:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_CONT\n"));
-
-				Set_ATE_Proc(pAdapter, "TXCONT");
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_START_TX_CONT\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START_TX_CONT is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_START_TX_FRAME:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_FRAME\n"));
-
-				Set_ATE_Proc(pAdapter, "TXFRAME");
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_START_TX_FRAME\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START_TX_FRAME is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_BW:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_BW\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-
-				Set_ATE_TX_BW_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_BW\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_BW is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_POWER0:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_POWER0\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_POWER0_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_POWER0\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_POWER0 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_POWER1:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_POWER1\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_POWER1_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_POWER1\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_POWER1 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_FREQ_OFFSET:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_FREQ_OFFSET\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_FREQOFFSET_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_FREQ_OFFSET\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_FREQ_OFFSET is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_GET_STATISTICS:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_GET_STATISTICS\n"));
-
-				memcpy_exl(pAdapter, &pRaCfg->data[0], (UCHAR *)&pAdapter->ate.TxDoneCount, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[4], (UCHAR *)&pAdapter->WlanCounters.RetryCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[8], (UCHAR *)&pAdapter->WlanCounters.FailedCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[12], (UCHAR *)&pAdapter->WlanCounters.RTSSuccessCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[16], (UCHAR *)&pAdapter->WlanCounters.RTSFailureCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[20], (UCHAR *)&pAdapter->WlanCounters.ReceivedFragmentCount.QuadPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[24], (UCHAR *)&pAdapter->WlanCounters.FCSErrorCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[28], (UCHAR *)&pAdapter->Counters8023.RxNoBuffer, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[32], (UCHAR *)&pAdapter->WlanCounters.FrameDuplicateCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[36], (UCHAR *)&pAdapter->RalinkCounters.OneSecFalseCCACnt, 4);
-
-				if (pAdapter->ate.RxAntennaSel == 0)
-				{
-					INT32 RSSI0 = 0;
-					INT32 RSSI1 = 0;
-					INT32 RSSI2 = 0;
-
-					RSSI0 = (INT32)(pAdapter->ate.LastRssi0 - pAdapter->BbpRssiToDbmDelta);
-					RSSI1 = (INT32)(pAdapter->ate.LastRssi1 - pAdapter->BbpRssiToDbmDelta);
-					RSSI2 = (INT32)(pAdapter->ate.LastRssi2 - pAdapter->BbpRssiToDbmDelta);
-					memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&RSSI0, 4);
-					memcpy_exl(pAdapter, &pRaCfg->data[44], (UCHAR *)&RSSI1, 4);
-					memcpy_exl(pAdapter, &pRaCfg->data[48], (UCHAR *)&RSSI2, 4);
-					pRaCfg->length = htons(2+52);
-				}
-				else
-				{
-					INT32 RSSI0 = 0;
-
-					RSSI0 = (INT32)(pAdapter->ate.LastRssi0 - pAdapter->BbpRssiToDbmDelta);
-					memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&RSSI0, 4);
-					pRaCfg->length = htons(2+44);
-				}
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_GET_STATISTICS\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_GET_STATISTICS is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_RESET_COUNTER:
-			{
-				SHORT    value = 1;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_RESET_COUNTER\n"));
-
-				sprintf((PCHAR)str, "%d", value);
-				Set_ResetStatCounter_Proc(pAdapter, str);
-
-				pAdapter->ate.TxDoneCount = 0;
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_RESET_COUNTER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_RESET_COUNTER is done !\n"));
-				}
-			}
-
-			break;
-
-		case RACFG_CMD_ATE_SEL_TX_ANTENNA:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SEL_TX_ANTENNA\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_Antenna_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SEL_TX_ANTENNA\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SEL_TX_ANTENNA is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SEL_RX_ANTENNA:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SEL_RX_ANTENNA\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_RX_Antenna_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SEL_RX_ANTENNA\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SEL_RX_ANTENNA is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_PREAMBLE:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_PREAMBLE\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_MODE_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_PREAMBLE\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_PREAMBLE is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_CHANNEL:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_CHANNEL\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_CHANNEL_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_CHANNEL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_CHANNEL is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_ADDR1:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR1\n"));
-
-				// Addr is an array of UCHAR,
-				// so no need to perform endian swap.
-				memcpy(pAdapter->ate.Addr1, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_ADDR1\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_ADDR1 is done !\n (ADDR1 = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAdapter->ate.Addr1[0],
-						pAdapter->ate.Addr1[1], pAdapter->ate.Addr1[2], pAdapter->ate.Addr1[3], pAdapter->ate.Addr1[4], pAdapter->ate.Addr1[5]));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_ADDR2:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR2\n"));
-
-				// Addr is an array of UCHAR,
-				// so no need to perform endian swap.
-				memcpy(pAdapter->ate.Addr2, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_ADDR2\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_ADDR2 is done !\n (ADDR2 = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAdapter->ate.Addr2[0],
-						pAdapter->ate.Addr2[1], pAdapter->ate.Addr2[2], pAdapter->ate.Addr2[3], pAdapter->ate.Addr2[4], pAdapter->ate.Addr2[5]));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_ADDR3:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR3\n"));
-
-				// Addr is an array of UCHAR,
-				// so no need to perform endian swap.
-				memcpy(pAdapter->ate.Addr3, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_ADDR3\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_ADDR3 is done !\n (ADDR3 = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAdapter->ate.Addr3[0],
-						pAdapter->ate.Addr3[1], pAdapter->ate.Addr3[2], pAdapter->ate.Addr3[3], pAdapter->ate.Addr3[4], pAdapter->ate.Addr3[5]));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_RATE:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_RATE\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_MCS_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_RATE\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_RATE is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_FRAME_LEN:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_FRAME_LEN\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_LENGTH_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_FRAME_LEN\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_FRAME_LEN is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_FRAME_COUNT:
-			{
-				USHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_FRAME_COUNT\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				/* TX_FRAME_COUNT == 0 means tx infinitely */
-				if (value == 0)
-				{
-					/* Use TxCount = 0xFFFFFFFF to approximate the infinity. */
-					pAdapter->ate.TxCount = 0xFFFFFFFF;
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_COUNT_Proc (TxCount = %d)\n", pAdapter->ate.TxCount));
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_COUNT_Proc Success\n"));
-
-
-				}
-				else
-				{
-					sprintf((PCHAR)str, "%d", value);
-					Set_ATE_TX_COUNT_Proc(pAdapter, str);
-				}
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_FRAME_COUNT\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_FRAME_COUNT is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_START_RX_FRAME:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_START\n"));
-
-				Set_ATE_Proc(pAdapter, "RXFRAME");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RX_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RX_START is done !\n"));
-				}
-			}
-			break;
-		default:
-			break;
-	}
-    ASSERT(pRaCfg != NULL);
-    if (pRaCfg != NULL)
-    {
-    kfree(pRaCfg);
-    }
-	return;
-}
-
-VOID BubbleSort(INT32 n, INT32 a[])
-{
-	INT32 k, j, temp;
-
-	for (k = n-1;  k>0;  k--)
-	{
-		for (j = 0; j<k; j++)
-		{
-			if(a[j] > a[j+1])
-			{
-				temp = a[j];
-				a[j]=a[j+1];
-				a[j+1]=temp;
-			}
-		}
-	}
-}
-
-VOID CalNoiseLevel(PRTMP_ADAPTER pAd, UCHAR channel, INT32 RSSI[3][10])
-{
-	INT32		RSSI0, RSSI1, RSSI2;
- 	CHAR		Rssi0Offset, Rssi1Offset, Rssi2Offset;
-	UCHAR		BbpR50Rssi0 = 0, BbpR51Rssi1 = 0, BbpR52Rssi2 = 0;
-	UCHAR		Org_BBP66value = 0, Org_BBP69value = 0, Org_BBP70value = 0, data = 0;
-	USHORT		LNA_Gain = 0;
-	INT32       j = 0;
-	UCHAR		Org_Channel = pAd->ate.Channel;
-	USHORT	    GainValue = 0, OffsetValue = 0;
-
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &Org_BBP66value);
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R69, &Org_BBP69value);
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R70, &Org_BBP70value);
-
-	//**********************************************************************
-	// Read the value of LNA gain and Rssi offset
-	//**********************************************************************
-	RT28xx_EEPROM_READ16(pAd, EEPROM_LNA_OFFSET, GainValue);
-
-	// for Noise Level
-	if (channel <= 14)
-	{
-		LNA_Gain = GainValue & 0x00FF;
-
-		RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_BG_OFFSET, OffsetValue);
-		Rssi0Offset = OffsetValue & 0x00FF;
-		Rssi1Offset = (OffsetValue & 0xFF00) >> 8;
-		RT28xx_EEPROM_READ16(pAd, (EEPROM_RSSI_BG_OFFSET + 2)/* 0x48 */, OffsetValue);
-		Rssi2Offset = OffsetValue & 0x00FF;
-	}
-	else
-	{
-		LNA_Gain = (GainValue & 0xFF00) >> 8;
-
-		RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_A_OFFSET, OffsetValue);
-		Rssi0Offset = OffsetValue & 0x00FF;
-		Rssi1Offset = (OffsetValue & 0xFF00) >> 8;
-		RT28xx_EEPROM_READ16(pAd, (EEPROM_RSSI_A_OFFSET + 2)/* 0x4C */, OffsetValue);
-		Rssi2Offset = OffsetValue & 0x00FF;
-	}
-	//**********************************************************************
-	{
-		pAd->ate.Channel = channel;
-		ATEAsicSwitchChannel(pAd);
-		mdelay(5);
-
-		data = 0x10;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, data);
-		data = 0x40;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, data);
-		data = 0x40;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, data);
-		mdelay(5);
-
-		// Start Rx
-		pAd->ate.bQARxStart = TRUE;
-		Set_ATE_Proc(pAd, "RXFRAME");
-
-		mdelay(5);
-
-		for (j = 0; j < 10; j++)
-		{
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R50, &BbpR50Rssi0);
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R51, &BbpR51Rssi1);
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R52, &BbpR52Rssi2);
-
-			mdelay(10);
-
-			// Calculate RSSI 0
-			if (BbpR50Rssi0 == 0)
-			{
-				RSSI0 = -100;
-			}
-			else
-			{
-				RSSI0 = (INT32)(-12 - BbpR50Rssi0 - LNA_Gain - Rssi0Offset);
-			}
-			RSSI[0][j] = RSSI0;
-
-			if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
-			{
-				// Calculate RSSI 1
-				if (BbpR51Rssi1 == 0)
-				{
-					RSSI1 = -100;
-				}
-				else
-				{
-					RSSI1 = (INT32)(-12 - BbpR51Rssi1 - LNA_Gain - Rssi1Offset);
-				}
-				RSSI[1][j] = RSSI1;
-			}
-
-			if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
-			{
-				// Calculate RSSI 2
-				if (BbpR52Rssi2 == 0)
-					RSSI2 = -100;
-				else
-					RSSI2 = (INT32)(-12 - BbpR52Rssi2 - LNA_Gain - Rssi2Offset);
-
-				RSSI[2][j] = RSSI2;
-			}
-		}
-
-		// Stop Rx
-		Set_ATE_Proc(pAd, "RXSTOP");
-
-		mdelay(5);
-
-#if 0// Debug Message................
-		ate_print("\n**********************************************************\n");
-		ate_print("Noise Level: Channel %d\n", channel);
-		ate_print("RSSI0 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-			RSSI[0][0], RSSI[0][1], RSSI[0][2],
-			RSSI[0][3], RSSI[0][4], RSSI[0][5],
-			RSSI[0][6], RSSI[0][7], RSSI[0][8],
-			RSSI[0][9]);
-		if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
-		{
-			ate_print("RSSI1 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-				RSSI[1][0], RSSI[1][1], RSSI[1][2],
-				RSSI[1][3], RSSI[1][4], RSSI[1][5],
-				RSSI[1][6], RSSI[1][7], RSSI[1][8],
-				RSSI[1][9]);
-		}
-		if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
-		{
-			ate_print("RSSI2 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-				RSSI[2][0], RSSI[2][1], RSSI[2][2],
-				RSSI[2][3], RSSI[2][4], RSSI[2][5],
-				RSSI[2][6], RSSI[2][7], RSSI[2][8],
-				RSSI[2][9]);
-		}
-#endif // 0 //
-		BubbleSort(10, RSSI[0]);	// 1R
-
-		if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
-		{
-			BubbleSort(10, RSSI[1]);
-		}
-
-		if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
-		{
-			BubbleSort(10, RSSI[2]);
-		}
-
-#if 0// Debug Message................
-		ate_print("\nAfter Sorting....Channel %d\n", channel);
-		ate_print("RSSI0 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-			RSSI[0][0], RSSI[0][1], RSSI[0][2],
-			RSSI[0][3], RSSI[0][4], RSSI[0][5],
-			RSSI[0][6], RSSI[0][7], RSSI[0][8],
-			RSSI[0][9]);
-		if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
-		{
-			ate_print("RSSI1 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-				RSSI[1][0], RSSI[1][1], RSSI[1][2],
-				RSSI[1][3], RSSI[1][4], RSSI[1][5],
-				RSSI[1][6], RSSI[1][7], RSSI[1][8],
-				RSSI[1][9]);
-		}
-		if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
-		{
-			ate_print("RSSI2 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-				RSSI[2][0], RSSI[2][1], RSSI[2][2],
-				RSSI[2][3], RSSI[2][4], RSSI[2][5],
-				RSSI[2][6], RSSI[2][7], RSSI[2][8],
-				RSSI[2][9]);
-		}
-		ate_print("**********************************************************\n");
-#endif // 0 //
-	}
-
-	pAd->ate.Channel = Org_Channel;
-	ATEAsicSwitchChannel(pAd);
-
-	// Restore original value
-    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, Org_BBP66value);
-    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, Org_BBP69value);
-    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, Org_BBP70value);
-
-	return;
-}
-
-BOOLEAN SyncTxRxConfig(PRTMP_ADAPTER pAd, USHORT offset, UCHAR value)
-{
-	UCHAR tmp = 0, bbp_data = 0;
-
-	if (ATE_ON(pAd))
-	{
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, offset, &bbp_data);
-	}
-	else
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, offset, &bbp_data);
-	}
-
-	/* confirm again */
-	ASSERT(bbp_data == value);
-
-	switch(offset)
-	{
-		case BBP_R1:
-			/* Need to sync. tx configuration with legacy ATE. */
-			tmp = (bbp_data & ((1 << 4) | (1 << 3))/* 0x18 */) >> 3;
-		    switch(tmp)
-		    {
-				/* The BBP R1 bit[4:3] = 2 :: Both DACs will be used by QA. */
-		        case 2:
-					/* All */
-					pAd->ate.TxAntennaSel = 0;
-		            break;
-				/* The BBP R1 bit[4:3] = 0 :: DAC 0 will be used by QA. */
-		        case 0:
-					/* Antenna one */
-					pAd->ate.TxAntennaSel = 1;
-		            break;
-				/* The BBP R1 bit[4:3] = 1 :: DAC 1 will be used by QA. */
-		        case 1:
-					/* Antenna two */
-					pAd->ate.TxAntennaSel = 2;
-		            break;
-		        default:
-		            DBGPRINT(RT_DEBUG_TRACE, ("%s -- Sth. wrong!  : return FALSE; \n", __func__));
-		            return FALSE;
-		    }
-			break;/* case BBP_R1 */
-
-		case BBP_R3:
-			/* Need to sync. rx configuration with legacy ATE. */
-			tmp = (bbp_data & ((1 << 1) | (1 << 0))/* 0x03 */);
-		    switch(tmp)
-		    {
-				/* The BBP R3 bit[1:0] = 3 :: All ADCs will be used by QA. */
-		        case 3:
-					/* All */
-					pAd->ate.RxAntennaSel = 0;
-		            break;
-				/* The BBP R3 bit[1:0] = 0 :: ADC 0 will be used by QA, */
-				/* unless the BBP R3 bit[4:3] = 2 */
-		        case 0:
-					/* Antenna one */
-					pAd->ate.RxAntennaSel = 1;
-					tmp = ((bbp_data & ((1 << 4) | (1 << 3))/* 0x03 */) >> 3);
-					if (tmp == 2)// 3R
-					{
-						/* Default : All ADCs will be used by QA */
-						pAd->ate.RxAntennaSel = 0;
-					}
-		            break;
-				/* The BBP R3 bit[1:0] = 1 :: ADC 1 will be used by QA. */
-		        case 1:
-					/* Antenna two */
-					pAd->ate.RxAntennaSel = 2;
-		            break;
-				/* The BBP R3 bit[1:0] = 2 :: ADC 2 will be used by QA. */
-		        case 2:
-					/* Antenna three */
-					pAd->ate.RxAntennaSel = 3;
-		            break;
-		        default:
-		            DBGPRINT(RT_DEBUG_ERROR, ("%s -- Impossible!  : return FALSE; \n", __func__));
-		            return FALSE;
-		    }
-			break;/* case BBP_R3 */
-
-        default:
-            DBGPRINT(RT_DEBUG_ERROR, ("%s -- Sth. wrong!  : return FALSE; \n", __func__));
-            return FALSE;
-
-	}
-	return TRUE;
-}
-
-static VOID memcpy_exl(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len)
-{
-	ULONG i, Value = 0;
-	ULONG *pDst, *pSrc;
-	UCHAR *p8;
-
-	p8 = src;
-	pDst = (ULONG *) dst;
-	pSrc = (ULONG *) src;
-
-	for (i = 0 ; i < (len/4); i++)
-	{
-		/* For alignment issue, we need a variable "Value". */
-		memmove(&Value, pSrc, 4);
-		Value = htonl(Value);
-		memmove(pDst, &Value, 4);
-		pDst++;
-		pSrc++;
-	}
-	if ((len % 4) != 0)
-	{
-		/* wish that it will never reach here */
-		memmove(&Value, pSrc, (len % 4));
-		Value = htonl(Value);
-		memmove(pDst, &Value, (len % 4));
-	}
-}
-
-static VOID memcpy_exs(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len)
-{
-	ULONG i;
-	UCHAR *pDst, *pSrc;
-
-	pDst = dst;
-	pSrc = src;
-
-	for (i = 0; i < (len/2); i++)
-	{
-		memmove(pDst, pSrc, 2);
-		*((USHORT *)pDst) = htons(*((USHORT *)pDst));
-		pDst+=2;
-		pSrc+=2;
-	}
-
-	if ((len % 2) != 0)
-	{
-		memmove(pDst, pSrc, 1);
-	}
-}
-
-static VOID RTMP_IO_READ_BULK(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, UINT32 len)
-{
-	UINT32 i, Value;
-	UINT32 *pDst, *pSrc;
-
-	pDst = (UINT32 *) dst;
-	pSrc = (UINT32 *) src;
-
-	for (i = 0 ; i < (len/4); i++)
-	{
-		RTMP_IO_READ32(pAd, (ULONG)pSrc, &Value);
-		Value = htonl(Value);
-		memmove(pDst, &Value, 4);
-		pDst++;
-		pSrc++;
-	}
-	return;
-}
-
-// TODO:
-#if 0
-/* These work only when RALINK_ATE is defined */
-INT Set_TxStart_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG value = simple_strtol(arg, 0, 10);
-	UCHAR buffer[26] = {0x88, 0x02, 0x2c, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x00, 0x55, 0x44, 0x33, 0x22, 0x11, 0xc0, 0x22, 0x00, 0x00};
-	POS_COOKIE pObj;
-
-	if (pAd->ate.TxStatus != 0)
-		return FALSE;
-
-	pAd->ate.TxInfo = 0x04000000;
-	bzero(&pAd->ate.TxWI, sizeof(TXWI_STRUC));
-	pAd->ate.TxWI.PHYMODE = 0;// MODE_CCK
-	pAd->ate.TxWI.MPDUtotalByteCount = 1226;
-	pAd->ate.TxWI.MCS = 3;
-	//pAd->ate.Mode = ATE_START;
-	pAd->ate.Mode |= ATE_TXFRAME;
-	pAd->ate.TxCount = value;
-	pAd->ate.QID = 0;
-	pAd->ate.HLen = 26;
-	pAd->ate.PLen = 0;
-	pAd->ate.DLen = 1200;
-	memcpy(pAd->ate.Header, buffer, 26);
-	pAd->ate.bQATxStart = TRUE;
-	//pObj = (POS_COOKIE) pAd->OS_Cookie;
-	//tasklet_hi_schedule(&pObj->AteTxTask);
-	return TRUE;
-}
-#endif  /* end of #if 0 */
-
-INT Set_TxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ATEDBGPRINT(RT_DEBUG_TRACE,("Set_TxStop_Proc\n"));
-
-	if (Set_ATE_Proc(pAd, "TXSTOP"))
-	{
-	return TRUE;
-}
-	else
-	{
-		return FALSE;
-	}
-}
-
-INT Set_RxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ATEDBGPRINT(RT_DEBUG_TRACE,("Set_RxStop_Proc\n"));
-
-	if (Set_ATE_Proc(pAd, "RXSTOP"))
-	{
-	return TRUE;
-}
-	else
-	{
-		return FALSE;
-	}
-}
-
-#if 0
-INT Set_EEWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	USHORT offset = 0, value;
-	PUCHAR p2 = arg;
-
-	while((*p2 != ':') && (*p2 != '\0'))
-	{
-		p2++;
-	}
-
-	if (*p2 == ':')
-	{
-		A2Hex(offset, arg);
-		A2Hex(value, p2+ 1);
-	}
-	else
-	{
-		A2Hex(value, arg);
-	}
-
-	if (offset >= EEPROM_SIZE)
-	{
-		ate_print("Offset can not exceed EEPROM_SIZE( == 0x%04x)\n", EEPROM_SIZE);
-		return FALSE;
-	}
-
-	RTMP_EEPROM_WRITE16(pAd, offset, value);
-
-	return TRUE;
-}
-
-INT Set_BBPRead_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR value = 0, offset;
-
-	A2Hex(offset, arg);
-
-	if (ATE_ON(pAd))
-	{
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, offset,  &value);
-	}
-	else
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, offset,  &value);
-	}
-
-	ate_print("%x\n", value);
-
-	return TRUE;
-}
-
-
-INT Set_BBPWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	USHORT offset = 0;
-	PUCHAR p2 = arg;
-	UCHAR value;
-
-	while((*p2 != ':') && (*p2 != '\0'))
-	{
-		p2++;
-	}
-
-	if (*p2 == ':')
-	{
-		A2Hex(offset, arg);
-		A2Hex(value, p2+ 1);
-	}
-	else
-	{
-		A2Hex(value, arg);
-	}
-
-	if (ATE_ON(pAd))
-	{
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, offset,  value);
-	}
-	else
-	{
-		RTNP_BBP_IO_WRITE8_BY_REG_ID(pAd, offset,  value);
-	}
-
-	return TRUE;
-}
-
-INT Set_RFWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	PUCHAR p2, p3, p4;
-	ULONG R1, R2, R3, R4;
-
-	p2 = arg;
-
-	while((*p2 != ':') && (*p2 != '\0'))
-	{
-		p2++;
-	}
-
-	if (*p2 != ':')
-		return FALSE;
-
-	p3 = p2 + 1;
-
-	while((*p3 != ':') && (*p3 != '\0'))
-	{
-		p3++;
-	}
-
-	if (*p3 != ':')
-		return FALSE;
-
-	p4 = p3 + 1;
-
-	while((*p4 != ':') && (*p4 != '\0'))
-	{
-		p4++;
-	}
-
-	if (*p4 != ':')
-		return FALSE;
-
-
-	A2Hex(R1, arg);
-	A2Hex(R2, p2 + 1);
-	A2Hex(R3, p3 + 1);
-	A2Hex(R4, p4 + 1);
-
-	RTMP_RF_IO_WRITE32(pAd, R1);
-	RTMP_RF_IO_WRITE32(pAd, R2);
-	RTMP_RF_IO_WRITE32(pAd, R3);
-	RTMP_RF_IO_WRITE32(pAd, R4);
-
-	return TRUE;
-}
-#endif  // end of #if 0 //
-#endif	// RALINK_28xx_QA //
-
-#endif	// RALINK_ATE //
-
diff --git a/drivers/staging/rt2860/rt_ate.h b/drivers/staging/rt2860/rt_ate.h
deleted file mode 100644
index 38f5c4a..0000000
--- a/drivers/staging/rt2860/rt_ate.h
+++ /dev/null
@@ -1,347 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#ifndef __ATE_H__
-#define __ATE_H__
-
-#ifndef UCOS
-#define ate_print printk
-#define ATEDBGPRINT DBGPRINT
-#define EEPROM_SIZE								0x200
-#ifdef CONFIG_STA_SUPPORT
-#define EEPROM_BIN_FILE_NAME  "/etc/Wireless/RT2860STA/e2p.bin"
-#endif // CONFIG_STA_SUPPORT //
-
-#else // !UCOS //
-#define fATE_LOAD_EEPROM						0x0C43
-#ifdef CONFIG_PRINTK
-extern INT ConsoleResponse(IN PUCHAR buff);
-extern int (*remote_display)(char *);
-extern void puts (const char *s);
-
-/* specificly defined to redirect and show ate-related messages to host. */
-/* Try to define ate_print as a macro. */
-#define ate_print(fmt, args...)                 \
-do{   int (*org_remote_display)(char *) = NULL;   \
-	org_remote_display = remote_display;\
-	/* Save original "remote_display" */\
-	remote_display = (int (*)(char *))ConsoleResponse;           \
-	printk(fmt, ## args);                       \
-	/* Restore the remote_display function pointer */        \
-	remote_display = org_remote_display; }while(0)
-
-#define ATEDBGPRINT(Level, Fmt)    	\
-{                                   \
-    if ((Level) <= RTDebugLevel)      \
-    {                               \
-        ate_print Fmt;					\
-    }                               \
-}
-#endif // CONFIG_PRINTK //
-#endif // !UCOS //
-
-#define ATE_ON(_p)              (((_p)->ate.Mode) != ATE_STOP)
-
-/* RT2880_iNIC will define "RT2860". */
-#define ATE_BBP_IO_READ8_BY_REG_ID(_A, _I, _pV)        \
-{                                                       \
-    BBP_CSR_CFG_STRUC  BbpCsr;                             \
-    int             i, k;                               \
-    for (i=0; i<MAX_BUSY_COUNT; i++)                    \
-    {                                                   \
-        RTMP_IO_READ32(_A, BBP_CSR_CFG, &BbpCsr.word);     \
-        if (BbpCsr.field.Busy == BUSY)                  \
-        {                                               \
-            continue;                                   \
-        }                                               \
-        BbpCsr.word = 0;                                \
-        BbpCsr.field.fRead = 1;                         \
-        BbpCsr.field.BBP_RW_MODE = 1;                         \
-        BbpCsr.field.Busy = 1;                          \
-        BbpCsr.field.RegNum = _I;                       \
-        RTMP_IO_WRITE32(_A, BBP_CSR_CFG, BbpCsr.word);     \
-        for (k=0; k<MAX_BUSY_COUNT; k++)                \
-        {                                               \
-            RTMP_IO_READ32(_A, BBP_CSR_CFG, &BbpCsr.word); \
-            if (BbpCsr.field.Busy == IDLE)              \
-                break;                                  \
-        }                                               \
-        if ((BbpCsr.field.Busy == IDLE) &&              \
-            (BbpCsr.field.RegNum == _I))                \
-        {                                               \
-            *(_pV) = (UCHAR)BbpCsr.field.Value;         \
-            break;                                      \
-        }                                               \
-    }                                                   \
-    if (BbpCsr.field.Busy == BUSY)                      \
-    {                                                   \
-        ATEDBGPRINT(RT_DEBUG_ERROR, ("BBP read R%d fail\n", _I));      \
-        *(_pV) = (_A)->BbpWriteLatch[_I];               \
-    }                                                   \
-}
-
-#define ATE_BBP_IO_WRITE8_BY_REG_ID(_A, _I, _V)        \
-{                                                       \
-    BBP_CSR_CFG_STRUC  BbpCsr;                             \
-    int             BusyCnt;                            \
-    for (BusyCnt=0; BusyCnt<MAX_BUSY_COUNT; BusyCnt++)  \
-    {                                                   \
-        RTMP_IO_READ32(_A, BBP_CSR_CFG, &BbpCsr.word);     \
-        if (BbpCsr.field.Busy == BUSY)                  \
-            continue;                                   \
-        BbpCsr.word = 0;                                \
-        BbpCsr.field.fRead = 0;                         \
-        BbpCsr.field.BBP_RW_MODE = 1;                         \
-        BbpCsr.field.Busy = 1;                          \
-        BbpCsr.field.Value = _V;                        \
-        BbpCsr.field.RegNum = _I;                       \
-        RTMP_IO_WRITE32(_A, BBP_CSR_CFG, BbpCsr.word);     \
-        (_A)->BbpWriteLatch[_I] = _V;                   \
-        break;                                          \
-    }                                                   \
-    if (BusyCnt == MAX_BUSY_COUNT)                      \
-    {                                                   \
-        ATEDBGPRINT(RT_DEBUG_ERROR, ("BBP write R%d fail\n", _I));     \
-    }                                                   \
-}
-
-/* RT2880_iNIC will define RT2860. */
-#define EEPROM_SIZE								0x200
-/* iNIC has its own EEPROM_BIN_FILE_NAME */
-#ifndef UCOS
-#ifdef CONFIG_STA_SUPPORT
-#define EEPROM_BIN_FILE_NAME  "/etc/Wireless/RT2860STA/e2p.bin"
-#endif // CONFIG_STA_SUPPORT //
-#endif // !UCOS //
-
-
-
-VOID rt_ee_read_all(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT USHORT *Data);
-
-
-VOID rt_ee_write_all(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  USHORT *Data);
-
-INT Set_ATE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_DA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_SA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_BSSID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_CHANNEL_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_POWER0_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_POWER1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_RX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_FREQOFFSET_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_BW_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_LENGTH_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_COUNT_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_MCS_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_MODE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_GI_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-
-INT	Set_ATE_RX_FER_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Read_RF_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF2_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF3_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF4_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Load_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Read_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_Show_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_Help_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-VOID ATE_QA_Statistics(
-	IN PRTMP_ADAPTER		pAd,
-	IN PRXWI_STRUC			pRxWI,
-	IN PRT28XX_RXD_STRUC    p28xxRxD,
-	IN PHEADER_802_11		pHeader);
-
-VOID RtmpDoAte(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID BubbleSort(
-	IN  INT32 n,
-	IN  INT32 a[]);
-
-VOID CalNoiseLevel(
-	IN  PRTMP_ADAPTER   pAdapter,
-	IN  UCHAR           channel,
-	OUT INT32           buffer[3][10]);
-
-BOOLEAN SyncTxRxConfig(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	USHORT			offset,
-	IN	UCHAR			value);
-
-#if 0
-INT Set_TxStart_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif  // 0 //
-
-INT Set_TxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_RxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#if 0
-INT Set_EERead_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_EEWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_BBPRead_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_BBPWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_RFWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // end of #if 0 //
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-VOID ATEAsicSwitchChannel(
-	IN PRTMP_ADAPTER pAd);
-
-VOID ATEAsicAdjustTxPower(
-	IN PRTMP_ADAPTER pAd);
-
-VOID ATEDisableAsicProtect(
-	IN		PRTMP_ADAPTER	pAd);
-
-CHAR ATEConvertToRssi(
-	IN PRTMP_ADAPTER  pAd,
-	IN CHAR				Rssi,
-	IN UCHAR    RssiNumber);
-
-VOID ATESampleRssi(
-	IN PRTMP_ADAPTER	pAd,
-	IN PRXWI_STRUC		pRxWI);
-
-
-#ifdef CONFIG_STA_SUPPORT
-VOID RTMPStationStop(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPStationStart(
-    IN  PRTMP_ADAPTER   pAd);
-#endif // CONFIG_STA_SUPPORT //
-#endif // __ATE_H__ //
diff --git a/drivers/staging/rt2860/rt_config.h b/drivers/staging/rt2860/rt_config.h
index a67024f..a19cbe1 100644
--- a/drivers/staging/rt2860/rt_config.h
+++ b/drivers/staging/rt2860/rt_config.h
@@ -41,20 +41,18 @@
 #define	__RT_CONFIG_H__
 
 #include    "rtmp_type.h"
-#ifdef UCOS
-#include "includes.h"
-#include <stdio.h>
-#include 	"rt_ucos.h"
-#endif
-
 #ifdef LINUX
 #include	"rt_linux.h"
 #endif
 #include    "rtmp_def.h"
 #include    "rt28xx.h"
 
+#ifdef RT2860
 #include	"rt2860.h"
-
+#endif
+#ifdef RT2870
+#include	"../rt2870/rt2870.h"
+#endif // RT2870 //
 
 #include    "oid.h"
 #include    "mlme.h"
@@ -66,31 +64,10 @@
 #include	"chlist.h"
 #include	"spectrum.h"
 
-#ifdef LEAP_SUPPORT
-#include    "leap.h"
-#endif // LEAP_SUPPORT //
-
-#ifdef BLOCK_NET_IF
-#include "netif_block.h"
-#endif // BLOCK_NET_IF //
-
 #ifdef IGMP_SNOOP_SUPPORT
 #include "igmp_snoop.h"
 #endif // IGMP_SNOOP_SUPPORT //
 
-#ifdef RALINK_ATE
-#include "rt_ate.h"
-#endif // RALINK_ATE //
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-#ifndef WPA_SUPPLICANT_SUPPORT
-#error "Build for being controlled by NetworkManager or wext, please set HAS_WPA_SUPPLICANT=y and HAS_NATIVE_WPA_SUPPLICANT_SUPPORT=y"
-#endif // WPA_SUPPLICANT_SUPPORT //
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-#endif // CONFIG_STA_SUPPORT //
-
 #ifdef IKANOS_VX_1X0
 #include	"vr_ikans.h"
 #endif // IKANOS_VX_1X0 //
diff --git a/drivers/staging/rt2860/rt_linux.c b/drivers/staging/rt2860/rt_linux.c
index f3c128c..80176b2 100644
--- a/drivers/staging/rt2860/rt_linux.c
+++ b/drivers/staging/rt2860/rt_linux.c
@@ -33,9 +33,10 @@
 BUILD_TIMER_FUNCTION(AsicRxAntEvalTimeout);
 BUILD_TIMER_FUNCTION(APSDPeriodicExec);
 BUILD_TIMER_FUNCTION(AsicRfTuningExec);
+#ifdef RT2870
+BUILD_TIMER_FUNCTION(BeaconUpdateExec);
+#endif // RT2870 //
 
-
-#ifdef CONFIG_STA_SUPPORT
 BUILD_TIMER_FUNCTION(BeaconTimeout);
 BUILD_TIMER_FUNCTION(ScanTimeout);
 BUILD_TIMER_FUNCTION(AuthTimeout);
@@ -43,17 +44,12 @@
 BUILD_TIMER_FUNCTION(ReassocTimeout);
 BUILD_TIMER_FUNCTION(DisassocTimeout);
 BUILD_TIMER_FUNCTION(LinkDownExec);
-#ifdef LEAP_SUPPORT
-BUILD_TIMER_FUNCTION(LeapAuthTimeout);
-#endif
 BUILD_TIMER_FUNCTION(StaQuickResponeForRateUpExec);
 BUILD_TIMER_FUNCTION(WpaDisassocApAndBlockAssoc);
+#ifdef RT2860
 BUILD_TIMER_FUNCTION(PsPollWakeExec);
 BUILD_TIMER_FUNCTION(RadioOnExec);
-#ifdef QOS_DLS_SUPPORT
-BUILD_TIMER_FUNCTION(DlsTimeoutAction);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
+#endif
 
 // for wireless system event message
 char const *pWirelessSysEventText[IW_SYS_EVENT_TYPE_NUM] = {
@@ -290,9 +286,9 @@
 
 
 	NdisFreeSpinLock(&pAd->MgmtRingLock);
-
+#ifdef RT2860
 	NdisFreeSpinLock(&pAd->RxRingLock);
-
+#endif
 	for (index =0 ; index < NUM_OF_TX_RING; index++)
 	{
     	NdisFreeSpinLock(&pAd->TxSwQueueLock[index]);
@@ -495,12 +491,7 @@
 {
     PNET_DEV dev_p = NULL;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		dev_p = pAd->net_dev;
-	}
-#endif // CONFIG_STA_SUPPORT //
+	dev_p = pAd->net_dev;
 
 	ASSERT(dev_p);
 	return dev_p; /* return one of MBSS */
@@ -656,13 +647,8 @@
 	//
 	//
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		NdisMoveMemory(skb_push(pOSPkt, LENGTH_802_3), pHeader802_3, LENGTH_802_3);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-
+	NdisMoveMemory(skb_push(pOSPkt, LENGTH_802_3), pHeader802_3, LENGTH_802_3);
+}
 
 void announce_802_3_packet(
 	IN	PRTMP_ADAPTER	pAd,
@@ -824,8 +810,6 @@
 #endif  /* WIRELESS_EXT >= 15 */
 }
 
-
-#ifdef CONFIG_STA_SUPPORT
 void send_monitor_packets(
 	IN	PRTMP_ADAPTER	pAd,
 	IN	RX_BLK			*pRxBlk)
@@ -850,7 +834,12 @@
 
     if (pRxBlk->DataSize + sizeof(wlan_ng_prism2_header) > RX_BUFFER_AGGRESIZE)
     {
+#ifndef RT30xx
         DBGPRINT(RT_DEBUG_ERROR, ("%s : Size is too large! (%zu)\n", __func__, pRxBlk->DataSize + sizeof(wlan_ng_prism2_header)));
+#endif
+#ifdef RT30xx
+        DBGPRINT(RT_DEBUG_ERROR, ("%s : Size is too large! (%d)\n", __func__, pRxBlk->DataSize + sizeof(wlan_ng_prism2_header)));
+#endif
 		goto err_free_sk_buff;
     }
 
@@ -957,13 +946,11 @@
 	ph->noise.len = 4;
 	ph->noise.data = 0;
 
-#ifdef DOT11_N_SUPPORT
     if (pRxBlk->pRxWI->PHYMODE >= MODE_HTMIX)
     {
     	rate_index = 16 + ((UCHAR)pRxBlk->pRxWI->BW *16) + ((UCHAR)pRxBlk->pRxWI->ShortGI *32) + ((UCHAR)pRxBlk->pRxWI->MCS);
     }
     else
-#endif // DOT11_N_SUPPORT //
 	if (pRxBlk->pRxWI->PHYMODE == MODE_OFDM)
     	rate_index = (UCHAR)(pRxBlk->pRxWI->MCS) + 4;
     else
@@ -996,8 +983,6 @@
 	return;
 
 }
-#endif // CONFIG_STA_SUPPORT //
-
 
 void rtmp_os_thread_init(PUCHAR pThreadName, PVOID pNotify)
 {
diff --git a/drivers/staging/rt2860/rt_linux.h b/drivers/staging/rt2860/rt_linux.h
index 708923c..85175c1 100644
--- a/drivers/staging/rt2860/rt_linux.h
+++ b/drivers/staging/rt2860/rt_linux.h
@@ -42,8 +42,10 @@
 
 #include "rtmp_type.h"
 #include <linux/module.h>
-#include <linux/version.h>
 #include <linux/kernel.h>
+#if !defined(RT2860) && !defined(RT30xx)
+#include <linux/kthread.h>
+#endif
 
 #include <linux/spinlock.h>
 #include <linux/init.h>
@@ -65,6 +67,9 @@
 #include <linux/vmalloc.h>
 
 
+#ifdef RT30xx
+#include <linux/wireless.h>
+#endif
 #include <net/iw_handler.h>
 
 // load firmware
@@ -88,23 +93,31 @@
 
 // add by kathy
 
-#ifdef CONFIG_STA_SUPPORT
+#ifdef RT2860
 #define STA_PROFILE_PATH			"/etc/Wireless/RT2860STA/RT2860STA.dat"
 #define STA_RTMP_FIRMWARE_FILE_NAME "/etc/Wireless/RT2860STA/RT2860STA.bin"
 #define STA_NIC_DEVICE_NAME			"RT2860STA"
 #define STA_DRIVER_VERSION			"1.8.1.1"
-#ifdef MULTIPLE_CARD_SUPPORT
-#define CARD_INFO_PATH			"/etc/Wireless/RT2860STA/RT2860STACard.dat"
-#endif // MULTIPLE_CARD_SUPPORT //
+#endif
+#ifdef RT2870
+#define STA_PROFILE_PATH			"/etc/Wireless/RT2870STA/RT2870STA.dat"
+#define STA_RT2870_IMAGE_FILE_NAME  "/etc/Wireless/RT2870STA/rt2870.bin"
+#define STA_NIC_DEVICE_NAME			"RT2870STA"
+#ifndef RT30xx
+#define STA_DRIVER_VERSION			"1.4.0.0"
+#endif
+#ifdef RT30xx
+#define STA_DRIVER_VERSION			"2.0.1.0"
+#endif
+#endif
 
-
-#endif // CONFIG_STA_SUPPORT //
-
+#ifdef RT2860
 #ifndef PCI_DEVICE
 #define PCI_DEVICE(vend,dev) \
 	.vendor = (vend), .device = (dev), \
 	.subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID
 #endif // PCI_DEVICE //
+#endif
 
 #define RTMP_TIME_AFTER(a,b)		\
 	(typecheck(unsigned long, (unsigned long)a) && \
@@ -144,24 +157,23 @@
 #define MIN_NET_DEVICE_FOR_WDS			0x10		//0x40,0x50,0x60,0x70
 #define MIN_NET_DEVICE_FOR_APCLI		0x20
 #define MIN_NET_DEVICE_FOR_MESH			0x30
-#ifdef CONFIG_STA_SUPPORT
 #define MIN_NET_DEVICE_FOR_DLS			0x40
-#endif // CONFIG_STA_SUPPORT //
 
-
-#ifdef CONFIG_STA_SUPPORT
 #define NDIS_PACKET_TYPE_DIRECTED		0
 #define NDIS_PACKET_TYPE_MULTICAST		1
 #define NDIS_PACKET_TYPE_BROADCAST		2
 #define NDIS_PACKET_TYPE_ALL_MULTICAST	3
-#endif // CONFIG_STA_SUPPORT //
 
+#ifndef RT30xx
 typedef	struct pid *	THREAD_PID;
+#ifdef RT2860
 #define	THREAD_PID_INIT_VALUE	NULL
+#endif
 #define	GET_PID(_v)	find_get_pid(_v)
 #define	GET_PID_NUMBER(_v)	pid_nr(_v)
 #define CHECK_PID_LEGALITY(_pid)	if (pid_nr(_pid) >= 0)
 #define KILL_THREAD_PID(_A, _B, _C)	kill_pid(_A, _B, _C)
+#endif
 
 struct os_lock  {
 	spinlock_t		lock;
@@ -170,10 +182,25 @@
 
 
 struct os_cookie {
+#ifdef RT2860
 	struct pci_dev 			*pci_dev;
 	struct pci_dev 			*parent_pci_dev;
 	dma_addr_t		  		pAd_pa;
+#endif
+#ifdef RT2870
+	struct usb_device	*pUsb_Dev;
 
+#ifndef RT30xx
+	struct task_struct	*MLMEThr_task;
+	struct task_struct	*RTUSBCmdThr_task;
+	struct task_struct	*TimerQThr_task;
+#endif
+#ifdef RT30xx
+	struct pid	*MLMEThr_pid;
+	struct pid	*RTUSBCmdThr_pid;
+	struct pid	*TimerQThr_pid;
+#endif
+#endif // RT2870 //
 
 	struct tasklet_struct 	rx_done_task;
 	struct tasklet_struct 	mgmt_dma_done_task;
@@ -183,8 +210,14 @@
 	struct tasklet_struct 	ac3_dma_done_task;
 	struct tasklet_struct 	hcca_dma_done_task;
 	struct tasklet_struct	tbtt_task;
+#ifdef RT2860
 	struct tasklet_struct	fifo_statistic_full_task;
-
+#endif
+#ifdef RT2870
+	struct tasklet_struct	null_frame_complete_task;
+	struct tasklet_struct	rts_frame_complete_task;
+	struct tasklet_struct	pspoll_frame_complete_task;
+#endif // RT2870 //
 
 	unsigned long			apd_pid; //802.1x daemon pid
 	INT						ioctl_if_type;
@@ -198,13 +231,7 @@
 } VIRTUAL_ADAPTER, PVIRTUAL_ADAPTER;
 
 #undef  ASSERT
-#define ASSERT(x)                                                               \
-{                                                                               \
-    if (!(x))                                                                   \
-    {                                                                           \
-        printk(KERN_WARNING __FILE__ ":%d assert " #x "failed\n", __LINE__);    \
-    }                                                                           \
-}
+#define ASSERT(x)
 
 typedef struct os_cookie	* POS_COOKIE;
 typedef struct pci_dev 		* PPCI_DEV;
@@ -238,6 +265,7 @@
 
 #define RT2860_PCI_DEVICE_ID		0x0601
 
+#ifdef RT2860
 #define PCI_MAP_SINGLE(_handle, _ptr, _size, _sd_idx, _dir) \
 	linux_pci_map_single(_handle, _ptr, _size, _sd_idx, _dir)
 
@@ -252,7 +280,12 @@
 
 #define DEV_ALLOC_SKB(_length) \
 	dev_alloc_skb(_length)
+#endif
+#ifdef RT2870
+#define PCI_MAP_SINGLE(_handle, _ptr, _size, _dir) (ULONG)0
 
+#define PCI_UNMAP_SINGLE(_handle, _ptr, _size, _dir)
+#endif // RT2870 //
 
 
 #define BEACON_FRAME_DMA_CACHE_WBACK(_ptr, _size)	\
@@ -266,9 +299,20 @@
 
 #define NdisMIndicateStatus(_w, _x, _y, _z)
 
-
 typedef struct timer_list	RTMP_OS_TIMER;
 
+#ifdef RT2870
+/* ----------------- Timer Related MARCO ---------------*/
+// In RT2870, we have a lot of timer functions and will read/write register, it's
+//	not allowed in Linux USB sub-system to do it ( because of sleep issue when submit
+//  to ctrl pipe). So we need a wrapper function to take care it.
+
+typedef VOID (*RT2870_TIMER_HANDLE)(
+	IN  PVOID   SystemSpecific1,
+	IN  PVOID   FunctionContext,
+	IN  PVOID   SystemSpecific2,
+	IN  PVOID   SystemSpecific3);
+#endif // RT2870 //
 
 
 typedef struct  _RALINK_TIMER_STRUCT    {
@@ -279,9 +323,42 @@
     BOOLEAN             Repeat;         // True if periodic timer
     ULONG               TimerValue;     // Timer value in milliseconds
 	ULONG				cookie;			// os specific object
+#ifdef RT2870
+	RT2870_TIMER_HANDLE	handle;
+	void				*pAd;
+#endif // RT2870 //
 }   RALINK_TIMER_STRUCT, *PRALINK_TIMER_STRUCT;
 
 
+#ifdef RT2870
+
+typedef enum _RT2870_KERNEL_THREAD_STATUS_
+{
+	RT2870_THREAD_UNKNOWN = 0,
+	RT2870_THREAD_INITED = 1,
+	RT2870_THREAD_RUNNING = 2,
+	RT2870_THREAD_STOPED = 4,
+}RT2870_KERNEL_THREAD_STATUS;
+
+#define RT2870_THREAD_CAN_DO_INSERT		(RT2870_THREAD_INITED |RT2870_THREAD_RUNNING)
+
+typedef struct _RT2870_TIMER_ENTRY_
+{
+	RALINK_TIMER_STRUCT 			*pRaTimer;
+	struct _RT2870_TIMER_ENTRY_ 	*pNext;
+}RT2870_TIMER_ENTRY;
+
+
+#define TIMER_QUEUE_SIZE_MAX	128
+typedef struct _RT2870_TIMER_QUEUE_
+{
+	unsigned int		status;
+	UCHAR				*pTimerQPoll;
+	RT2870_TIMER_ENTRY	*pQPollFreeList;
+	RT2870_TIMER_ENTRY 	*pQHead;
+	RT2870_TIMER_ENTRY 	*pQTail;
+}RT2870_TIMER_QUEUE;
+#endif // RT2870 //
 
 
 //#define DBG	1
@@ -371,6 +448,7 @@
 	spin_unlock_irqrestore((spinlock_t *)(__lock), ((unsigned long)__irqflag));	\
 }
 
+#ifdef RT2860
 #if defined(INF_TWINPASS) || defined(INF_DANUBE) || defined(IKANOS_VX_1X0)
 //Patch for ASIC turst read/write bug, needs to remove after metel fix
 #define RTMP_IO_READ32(_A, _R, _pV)									\
@@ -472,7 +550,32 @@
 	writew((_V), (PUSHORT)((_A)->CSRBaseAddress + (_R)));	\
 }
 #endif
+#endif /* RT2860 */
+#ifdef RT2870
+//Patch for ASIC turst read/write bug, needs to remove after metel fix
+#define RTMP_IO_READ32(_A, _R, _pV)								\
+	RTUSBReadMACRegister(_A, _R, _pV)
 
+#define RTMP_IO_READ8(_A, _R, _pV)								\
+{																\
+}
+
+#define RTMP_IO_WRITE32(_A, _R, _V)								\
+	RTUSBWriteMACRegister(_A, _R, _V)
+
+
+#define RTMP_IO_WRITE8(_A, _R, _V)								\
+{																\
+	USHORT	_Val = _V;											\
+	RTUSBSingleWrite(_A, _R, _Val);								\
+}
+
+
+#define RTMP_IO_WRITE16(_A, _R, _V)								\
+{																\
+	RTUSBSingleWrite(_A, _R, _V);								\
+}
+#endif // RT2870 //
 
 #ifndef wait_event_interruptible_timeout
 #define __wait_event_interruptible_timeout(wq, condition, ret) \
@@ -515,7 +618,6 @@
 		wait_event_interruptible_timeout(_wait, 0, ONE_TICK); }
 
 
-/* Modified by Wu Xi-Kun 4/21/2006 */
 typedef void (*TIMER_FUNCTION)(unsigned long);
 
 #define COPY_MAC_ADDR(Addr1, Addr2)             memcpy((Addr1), (Addr2), MAC_ADDR_LEN)
@@ -523,6 +625,7 @@
 #define MlmeAllocateMemory(_pAd, _ppVA) os_alloc_mem(_pAd, _ppVA, MGMT_DMA_BUFFER_SIZE)
 #define MlmeFreeMemory(_pAd, _pVA)     os_free_mem(_pAd, _pVA)
 
+#ifdef RT2860
 #define BUILD_TIMER_FUNCTION(_func)												\
 void linux_##_func(unsigned long data)											\
 {																				\
@@ -532,7 +635,22 @@
 	if (pTimer->Repeat)															\
 		RTMP_OS_Add_Timer(&pTimer->TimerObj, pTimer->TimerValue);				\
 }
-
+#endif
+#ifdef RT2870
+#define BUILD_TIMER_FUNCTION(_func)													\
+void linux_##_func(unsigned long data)												\
+{																					\
+	PRALINK_TIMER_STRUCT	_pTimer = (PRALINK_TIMER_STRUCT)data;					\
+	RT2870_TIMER_ENTRY		*_pQNode;												\
+	RTMP_ADAPTER			*_pAd;													\
+																				\
+	_pTimer->handle = _func;															\
+	_pAd = (RTMP_ADAPTER *)_pTimer->pAd;												\
+	_pQNode = RT2870_TimerQ_Insert(_pAd, _pTimer); 									\
+	if ((_pQNode == NULL) && (_pAd->TimerQ.status & RT2870_THREAD_CAN_DO_INSERT))	\
+		RTMP_OS_Add_Timer(&_pTimer->TimerObj, HZ);               					\
+}
+#endif // RT2870 //
 
 
 #define DECLARE_TIMER_FUNCTION(_func)			\
@@ -546,9 +664,10 @@
 DECLARE_TIMER_FUNCTION(AsicRxAntEvalTimeout);
 DECLARE_TIMER_FUNCTION(APSDPeriodicExec);
 DECLARE_TIMER_FUNCTION(AsicRfTuningExec);
+#ifdef RT2870
+DECLARE_TIMER_FUNCTION(BeaconUpdateExec);
+#endif // RT2870 //
 
-
-#ifdef CONFIG_STA_SUPPORT
 DECLARE_TIMER_FUNCTION(BeaconTimeout);
 DECLARE_TIMER_FUNCTION(ScanTimeout);
 DECLARE_TIMER_FUNCTION(AuthTimeout);
@@ -556,19 +675,11 @@
 DECLARE_TIMER_FUNCTION(ReassocTimeout);
 DECLARE_TIMER_FUNCTION(DisassocTimeout);
 DECLARE_TIMER_FUNCTION(LinkDownExec);
-#ifdef LEAP_SUPPORT
-DECLARE_TIMER_FUNCTION(LeapAuthTimeout);
-#endif
 DECLARE_TIMER_FUNCTION(StaQuickResponeForRateUpExec);
 DECLARE_TIMER_FUNCTION(WpaDisassocApAndBlockAssoc);
 DECLARE_TIMER_FUNCTION(PsPollWakeExec);
 DECLARE_TIMER_FUNCTION(RadioOnExec);
 
-#ifdef QOS_DLS_SUPPORT
-DECLARE_TIMER_FUNCTION(DlsTimeoutAction);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
 void RTMP_GetCurrentSystemTime(LARGE_INTEGER *time);
 
 
@@ -676,10 +787,6 @@
 #define RTMP_GET_PACKET_MOREDATA(_p)				(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+7])
 
 
-#if 0
-//#define RTMP_SET_PACKET_DHCP(_p, _flg)   	(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] = _flg)
-//#define RTMP_GET_PACKET_DHCP(_p)         	(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11])
-#else
 //
 //	Sepcific Pakcet Type definition
 //
@@ -759,8 +866,6 @@
 
 #define RTMP_GET_PACKET_IPV4(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_IPV4)
 
-#endif
-
 
 // If this flag is set, it indicates that this EAPoL frame MUST be clear.
 #define RTMP_SET_PACKET_CLEAR_EAP_FRAME(_p, _flg)   (RTPKT_TO_OSPKT(_p)->cb[CB_OFF+12] = _flg)
@@ -884,6 +989,7 @@
 
 void rtmp_os_thread_init(PUCHAR pThreadName, PVOID pNotify);
 
+#ifdef RT2860
 #if !defined(PCI_CAP_ID_EXP)
 #define PCI_CAP_ID_EXP			    0x10
 #endif
@@ -897,5 +1003,5 @@
 #endif
 
 #define PCIBUS_INTEL_VENDOR         0x8086
-
+#endif
 
diff --git a/drivers/staging/rt2860/rt_main_dev.c b/drivers/staging/rt2860/rt_main_dev.c
index 6c4396f..f298b9b 100644
--- a/drivers/staging/rt2860/rt_main_dev.c
+++ b/drivers/staging/rt2860/rt_main_dev.c
@@ -40,17 +40,6 @@
 
 #define FORTY_MHZ_INTOLERANT_INTERVAL	(60*1000) // 1 min
 
-#ifdef MULTIPLE_CARD_SUPPORT
-// record whether the card in the card list is used in the card file
-UINT8  MC_CardUsed[MAX_NUM_OF_MULTIPLE_CARD];
-// record used card mac address in the card list
-static UINT8  MC_CardMac[MAX_NUM_OF_MULTIPLE_CARD][6];
-#endif // MULTIPLE_CARD_SUPPORT //
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-UINT32 CW_MAX_IN_BITS;
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
 /*---------------------------------------------------------------------*/
 /* Private Variables Used                                              */
 /*---------------------------------------------------------------------*/
@@ -65,13 +54,13 @@
 /*---------------------------------------------------------------------*/
 /* Prototypes of Functions Used                                        */
 /*---------------------------------------------------------------------*/
-#ifdef DOT11_N_SUPPORT
 extern BOOLEAN ba_reordering_resource_init(PRTMP_ADAPTER pAd, int num);
 extern void ba_reordering_resource_release(PRTMP_ADAPTER pAd);
-#endif // DOT11_N_SUPPORT //
 extern NDIS_STATUS NICLoadRateSwitchingParams(IN PRTMP_ADAPTER pAd);
 
+#ifdef RT2860
 extern void init_thread_task(PRTMP_ADAPTER pAd);
+#endif
 
 // public function prototype
 INT __devinit rt28xx_probe(IN void *_dev_p, IN void *_dev_id_p,
@@ -83,13 +72,7 @@
 
 static void CfgInitHook(PRTMP_ADAPTER pAd);
 
-#ifdef CONFIG_STA_SUPPORT
 extern	const struct iw_handler_def rt28xx_iw_handler_def;
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-extern	const struct iw_handler_def rt28xx_ap_iw_handler_def;
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
 
 #if WIRELESS_EXT >= 12
 // This function will be called when query /proc
@@ -206,6 +189,12 @@
     RTMP_ADAPTER	*pAd = net_dev->ml_priv;
 	BOOLEAN 		Cancelled = FALSE;
 	UINT32			i = 0;
+#ifdef RT2870
+	DECLARE_WAIT_QUEUE_HEAD(unlink_wakeup);
+	DECLARE_WAITQUEUE(wait, current);
+
+	//RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_REMOVE_IN_PROGRESS);
+#endif // RT2870 //
 
 
     DBGPRINT(RT_DEBUG_TRACE, ("===> rt28xx_close\n"));
@@ -214,54 +203,26 @@
 	if (pAd == NULL)
 		return 0; // close ok
 
-
-#ifdef WDS_SUPPORT
-	WdsDown(pAd);
-#endif // WDS_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		// If dirver doesn't wake up firmware here,
 		// NICLoadFirmware will hang forever when interface is up again.
+#ifdef RT2860
 		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE) ||
 			RTMP_SET_PSFLAG(pAd, fRTMP_PS_SET_PCI_CLK_OFF_COMMAND) ||
 			RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF))
+#endif
+#ifdef RT2870
+		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
+#endif
         {
+#ifdef RT2860
 		    AsicForceWakeup(pAd, RTMP_HALT);
+#endif
+#ifdef RT2870
+		    AsicForceWakeup(pAd, TRUE);
+#endif
         }
 
-#ifdef QOS_DLS_SUPPORT
-		// send DLS-TEAR_DOWN message,
-		if (pAd->CommonCfg.bDLSCapable)
-		{
-			UCHAR i;
-
-			// tear down local dls table entry
-			for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-				{
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-					pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				}
-			}
-
-			// tear down peer dls table entry
-			for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-				{
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				}
-			}
-			RT28XX_MLME_HANDLER(pAd);
-		}
-#endif // QOS_DLS_SUPPORT //
-
 		if (INFRA_ON(pAd) &&
 			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
 		{
@@ -287,6 +248,9 @@
 			RTMPusecDelay(1000);
 		}
 
+#ifdef RT2870
+	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_REMOVE_IN_PROGRESS);
+#endif // RT2870 //
 
 #ifdef CCX_SUPPORT
 		RTMPCancelTimer(&pAd->StaCfg.LeapAuthTimer, &Cancelled);
@@ -295,22 +259,11 @@
 		RTMPCancelTimer(&pAd->StaCfg.StaQuickResponeForRateUpTimer, &Cancelled);
 		RTMPCancelTimer(&pAd->StaCfg.WpaDisassocAndBlockAssocTimer, &Cancelled);
 
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-		{
-			union iwreq_data    wrqu;
-			// send wireless event to wpa_supplicant for infroming interface down.
-			memset(&wrqu, 0, sizeof(wrqu));
-			wrqu.data.flags = RT_INTERFACE_DOWN;
-			wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-		}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
 		MlmeRadioOff(pAd);
+#ifdef RT2860
 		pAd->bPCIclkOff = FALSE;
+#endif
 	}
-#endif // CONFIG_STA_SUPPORT //
 
 	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS);
 
@@ -323,25 +276,52 @@
 		}
 	}
 
+#ifdef RT2870
+	// ensure there are no more active urbs.
+	add_wait_queue (&unlink_wakeup, &wait);
+	pAd->wait = &unlink_wakeup;
+
+	// maybe wait for deletions to finish.
+	i = 0;
+	//while((i < 25) && atomic_read(&pAd->PendingRx) > 0)
+	while(i < 25)
+	{
+		unsigned long IrqFlags;
+
+		RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
+		if (pAd->PendingRx == 0)
+		{
+			RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
+			break;
+		}
+		RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
+
+		msleep(UNLINK_TIMEOUT_MS);	//Time in millisecond
+		i++;
+	}
+	pAd->wait = NULL;
+	remove_wait_queue (&unlink_wakeup, &wait);
+#endif // RT2870 //
+
+#ifdef RT2870
+	// We need clear timerQ related structure before exits of the timer thread.
+	RT2870_TimerQ_Exit(pAd);
+	// Close kernel threads or tasklets
+	RT28xxThreadTerminate(pAd);
+#endif // RT2870 //
+
 	// Stop Mlme state machine
 	MlmeHalt(pAd);
 
 	// Close kernel threads or tasklets
 	kill_thread_task(pAd);
 
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		MacTableReset(pAd);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
+	MacTableReset(pAd);
 
 	MeasureReqTabExit(pAd);
 	TpcReqTabExit(pAd);
 
-
+#ifdef RT2860
 	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_ACTIVE))
 	{
 		NICDisableInterrupt(pAd);
@@ -357,18 +337,15 @@
 		RT28XX_IRQ_RELEASE(net_dev)
 		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE);
 	}
-
+#endif
 
 	// Free Ring or USB buffers
 	RTMPFreeTxRxRingMemory(pAd);
 
 	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS);
 
-#ifdef DOT11_N_SUPPORT
 	// Free BA reorder resource
 	ba_reordering_resource_release(pAd);
-#endif // DOT11_N_SUPPORT //
-
 
 	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_START_UP);
 
@@ -377,17 +354,19 @@
 
 static int rt28xx_init(IN struct net_device *net_dev)
 {
+#ifdef RT2860
 	PRTMP_ADAPTER 			pAd = (PRTMP_ADAPTER)net_dev->ml_priv;
+#endif
+#ifdef RT2870
+	PRTMP_ADAPTER 			pAd = net_dev->ml_priv;
+#endif
 	UINT					index;
 	UCHAR					TmpPhy;
 	NDIS_STATUS				Status;
 	UINT32 		MacCsr0 = 0;
 
-
-#ifdef DOT11_N_SUPPORT
 	// Allocate BA Reordering memory
 	ba_reordering_resource_init(pAd, MAX_REORDERING_MPDU_NUM);
-#endif // DOT11_N_SUPPORT //
 
 	// Make sure MAC gets ready.
 	index = 0;
@@ -403,11 +382,11 @@
 	} while (index++ < 100);
 
 	DBGPRINT(RT_DEBUG_TRACE, ("MAC_CSR0  [ Ver:Rev=0x%08x]\n", pAd->MACVersion));
+/*Iverson patch PCIE L1 issue */
 
 	// Disable DMA
 	RT28XXDMADisable(pAd);
 
-
 	// Load 8051 firmware
 	Status = NICLoadFirmware(pAd);
 	if (Status != NDIS_STATUS_SUCCESS)
@@ -420,10 +399,12 @@
 
 	// Disable interrupts here which is as soon as possible
 	// This statement should never be true. We might consider to remove it later
+#ifdef RT2860
 	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_ACTIVE))
 	{
 		NICDisableInterrupt(pAd);
 	}
+#endif
 
 	Status = RTMPAllocTxRxRingMemory(pAd);
 	if (Status != NDIS_STATUS_SUCCESS)
@@ -448,6 +429,10 @@
 	//
 	UserCfgInit(pAd);
 
+#ifdef RT2870
+	// We need init timerQ related structure before create the timer thread.
+	RT2870_TimerQ_Init(pAd);
+#endif // RT2870 //
 
 	RT28XX_TASK_THREAD_INIT(pAd, Status);
 	if (Status != NDIS_STATUS_SUCCESS)
@@ -455,15 +440,7 @@
 
 	CfgInitHook(pAd);
 
-
-#ifdef BLOCK_NET_IF
-	initblockQueueTab(pAd);
-#endif // BLOCK_NET_IF //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		NdisAllocateSpinLock(&pAd->MacTabLock);
-#endif // CONFIG_STA_SUPPORT //
+	NdisAllocateSpinLock(&pAd->MacTabLock);
 
 	MeasureReqTabInit(pAd);
 	TpcReqTabInit(pAd);
@@ -489,10 +466,17 @@
 		goto err4;
 	}
 
+#ifdef RT2870
+	pAd->CommonCfg.bMultipleIRP = FALSE;
+
+	if (pAd->CommonCfg.bMultipleIRP)
+		pAd->CommonCfg.NumOfBulkInIRP = RX_RING_SIZE;
+	else
+		pAd->CommonCfg.NumOfBulkInIRP = 1;
+#endif // RT2870 //
 
 
    	//Init Ba Capability parameters.
-#ifdef DOT11_N_SUPPORT
 	pAd->CommonCfg.DesiredHtPhy.MpduDensity = (UCHAR)pAd->CommonCfg.BACapability.field.MpduDensity;
 	pAd->CommonCfg.DesiredHtPhy.AmsduEnable = (USHORT)pAd->CommonCfg.BACapability.field.AmsduEnable;
 	pAd->CommonCfg.DesiredHtPhy.AmsduSize = (USHORT)pAd->CommonCfg.BACapability.field.AmsduSize;
@@ -501,7 +485,6 @@
 	pAd->CommonCfg.HtCapability.HtCapInfo.MimoPs = (USHORT)pAd->CommonCfg.BACapability.field.MMPSmode;
 	pAd->CommonCfg.HtCapability.HtCapInfo.AMsduSize = (USHORT)pAd->CommonCfg.BACapability.field.AmsduSize;
 	pAd->CommonCfg.HtCapability.HtCapParm.MpduDensity = (UCHAR)pAd->CommonCfg.BACapability.field.MpduDensity;
-#endif // DOT11_N_SUPPORT //
 
 	printk("2. Phy Mode = %d\n", pAd->CommonCfg.PhyMode);
 
@@ -516,9 +499,7 @@
 	TmpPhy = pAd->CommonCfg.PhyMode;
 	pAd->CommonCfg.PhyMode = 0xff;
 	RTMPSetPhyMode(pAd, TmpPhy);
-#ifdef DOT11_N_SUPPORT
 	SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
 
 	// No valid channels.
 	if (pAd->ChannelListNum == 0)
@@ -527,11 +508,14 @@
 		goto err4;
 	}
 
-#ifdef DOT11_N_SUPPORT
 	printk("MCS Set = %02x %02x %02x %02x %02x\n", pAd->CommonCfg.HtCapability.MCSSet[0],
            pAd->CommonCfg.HtCapability.MCSSet[1], pAd->CommonCfg.HtCapability.MCSSet[2],
            pAd->CommonCfg.HtCapability.MCSSet[3], pAd->CommonCfg.HtCapability.MCSSet[4]);
-#endif // DOT11_N_SUPPORT //
+
+#ifdef RT2870
+    //Init RT30xx RFRegisters after read RFIC type from EEPROM
+	NICInitRT30xxRFRegisters(pAd);
+#endif // RT2870 //
 
 #ifdef IKANOS_VX_1X0
 	VR_IKANOS_FP_Init(pAd->ApCfg.BssidNum, pAd->PermanentAddress);
@@ -543,8 +527,10 @@
 	AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
 	AsicLockChannel(pAd, pAd->CommonCfg.Channel);
 
+#ifndef RT30xx
 	// 8051 firmware require the signal during booting time.
 	AsicSendCommandToMcu(pAd, 0x72, 0xFF, 0x00, 0x00);
+#endif
 
 	if (pAd && (Status != NDIS_STATUS_SUCCESS))
 	{
@@ -561,9 +547,24 @@
 		// Microsoft HCT require driver send a disconnect event after driver initialization.
 		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
 		RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_MEDIA_STATE_CHANGE);
+
 		DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event B!\n"));
 
 
+#ifdef RT2870
+		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS);
+		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_REMOVE_IN_PROGRESS);
+
+		//
+		// Support multiple BulkIn IRP,
+		// the value on pAd->CommonCfg.NumOfBulkInIRP may be large than 1.
+		//
+		for(index=0; index<pAd->CommonCfg.NumOfBulkInIRP; index++)
+		{
+			RTUSBBulkReceive(pAd);
+			DBGPRINT(RT_DEBUG_TRACE, ("RTUSBBulkReceive!\n" ));
+		}
+#endif // RT2870 //
 	}// end of else
 
 
@@ -578,17 +579,12 @@
 err2:
 	RTMPFreeTxRxRingMemory(pAd);
 err1:
-
-#ifdef DOT11_N_SUPPORT
 	os_free_mem(pAd, pAd->mpdu_blk_pool.mem); // free BA pool
-#endif // DOT11_N_SUPPORT //
 	RT28XX_IRQ_RELEASE(net_dev);
 
 	// shall not set ml_priv to NULL here because the ml_priv didn't been free yet.
 	//net_dev->ml_priv = 0;
-#ifdef INF_AMAZON_SE
-err0:
-#endif // INF_AMAZON_SE //
+
 	printk("!!! %s Initialized fail !!!\n", RT28xx_CHIP_NAME);
 	return FALSE;
 } /* End of rt28xx_init */
@@ -625,27 +621,6 @@
 		return -1;
 	}
 
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	if (pAd->OpMode == OPMODE_AP)
-	{
-		CW_MAX_IN_BITS = 6;
-	}
-	else if (pAd->OpMode == OPMODE_STA)
-	{
-		CW_MAX_IN_BITS = 10;
-	}
-
-#if WIRELESS_EXT >= 12
-	if (net_dev->priv_flags == INT_MAIN)
-	{
-		if (pAd->OpMode == OPMODE_AP)
-			net_dev->wireless_handlers = (struct iw_handler_def *) &rt28xx_ap_iw_handler_def;
-		else if (pAd->OpMode == OPMODE_STA)
-			net_dev->wireless_handlers = (struct iw_handler_def *) &rt28xx_iw_handler_def;
-	}
-#endif // WIRELESS_EXT >= 12 //
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
 	// Init
  	pObj = (POS_COOKIE)pAd->OS_Cookie;
 
@@ -664,13 +639,8 @@
 	if (rt28xx_init(net_dev) == FALSE)
 		goto err;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		NdisZeroMemory(pAd->StaCfg.dev_name, 16);
-		NdisMoveMemory(pAd->StaCfg.dev_name, net_dev->name, strlen(net_dev->name));
-	}
-#endif // CONFIG_STA_SUPPORT //
+	NdisZeroMemory(pAd->StaCfg.dev_name, 16);
+	NdisMoveMemory(pAd->StaCfg.dev_name, net_dev->name, strlen(net_dev->name));
 
 	// Set up the Mac address
 	NdisMoveMemory(net_dev->dev_addr, (void *) pAd->CurrentAddress, 6);
@@ -680,24 +650,6 @@
 
 	// Various AP function init
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-		{
-			union iwreq_data    wrqu;
-			// send wireless event to wpa_supplicant for infroming interface down.
-			memset(&wrqu, 0, sizeof(wrqu));
-			wrqu.data.flags = RT_INTERFACE_UP;
-			wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-		}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-	}
-#endif // CONFIG_STA_SUPPORT //
-
 	// Enable Interrupt
 	RT28XX_IRQ_ENABLE(pAd);
 
@@ -711,11 +663,9 @@
 	printk("0x1300 = %08x\n", reg);
 	}
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
+#ifdef RT2860
         RTMPInitPCIeLinkCtrlValue(pAd);
-#endif // CONFIG_STA_SUPPORT //
-
+#endif
 	return (retval);
 
 err:
@@ -745,26 +695,12 @@
 	CHAR    slot_name[IFNAMSIZ];
 	struct net_device   *device;
 
-
-	//ether_setup(dev);
-
-#ifdef CONFIG_STA_SUPPORT
 #if WIRELESS_EXT >= 12
 	if (pAd->OpMode == OPMODE_STA)
 	{
 		dev->wireless_handlers = &rt28xx_iw_handler_def;
 	}
 #endif //WIRELESS_EXT >= 12
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-#if WIRELESS_EXT >= 12
-	if (pAd->OpMode == OPMODE_AP)
-	{
-		dev->wireless_handlers = &rt28xx_ap_iw_handler_def;
-	}
-#endif //WIRELESS_EXT >= 12
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
 
 #if WIRELESS_EXT < 21
 		dev->get_wireless_stats = rt28xx_get_wireless_stats;
@@ -774,11 +710,6 @@
 	// find available device name
 	for (i = 0; i < 8; i++)
 	{
-#ifdef MULTIPLE_CARD_SUPPORT
-		if (pAd->MC_RowID >= 0)
-			sprintf(slot_name, "ra%02d_%d", pAd->MC_RowID, i);
-		else
-#endif // MULTIPLE_CARD_SUPPORT //
 		sprintf(slot_name, "ra%d", i);
 
 		device = dev_get_by_name(dev_net(dev), slot_name);
@@ -796,11 +727,6 @@
 	}
 	else
 	{
-#ifdef MULTIPLE_CARD_SUPPORT
-		if (pAd->MC_RowID >= 0)
-	        sprintf(dev->name, "ra%02d_%d", pAd->MC_RowID, i);
-		else
-#endif // MULTIPLE_CARD_SUPPORT //
 		sprintf(dev->name, "ra%d", i);
 		Status = NDIS_STATUS_SUCCESS;
 	}
@@ -809,369 +735,6 @@
 
 }
 
-
-#ifdef MULTIPLE_CARD_SUPPORT
-/*
-========================================================================
-Routine Description:
-    Get card profile path.
-
-Arguments:
-    pAd
-
-Return Value:
-    TRUE		- Find a card profile
-	FALSE		- use default profile
-
-Note:
-========================================================================
-*/
-extern INT RTMPGetKeyParameter(
-    IN  PCHAR   key,
-    OUT PCHAR   dest,
-    IN  INT     destsize,
-    IN  PCHAR   buffer);
-
-BOOLEAN RTMP_CardInfoRead(
-	IN	PRTMP_ADAPTER pAd)
-{
-#define MC_SELECT_CARDID		0	/* use CARD ID (0 ~ 31) to identify different cards */
-#define MC_SELECT_MAC			1	/* use CARD MAC to identify different cards */
-#define MC_SELECT_CARDTYPE		2	/* use CARD type (abgn or bgn) to identify different cards */
-
-#define LETTER_CASE_TRANSLATE(txt_p, card_id)			\
-	{	UINT32 _len; char _char;						\
-		for(_len=0; _len<strlen(card_id); _len++) {		\
-			_char = *(txt_p + _len);					\
-			if (('A' <= _char) && (_char <= 'Z'))		\
-				*(txt_p+_len) = 'a'+(_char-'A');		\
-		} }
-
-	struct file *srcf;
-	INT retval, orgfsuid, orgfsgid;
-   	mm_segment_t orgfs;
-	CHAR *buffer, *tmpbuf, card_id_buf[30], RFIC_word[30];
-	BOOLEAN flg_match_ok = FALSE;
-	INT32 card_select_method;
-	INT32 card_free_id, card_nouse_id, card_same_mac_id, card_match_id;
-	EEPROM_ANTENNA_STRUC antenna;
-	USHORT addr01, addr23, addr45;
-	UINT8 mac[6];
-	UINT32 data, card_index;
-	UCHAR *start_ptr;
-
-
-	// init
-	buffer = kmalloc(MAX_INI_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	if (buffer == NULL)
-        return FALSE;
-
-	tmpbuf = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	if(tmpbuf == NULL)
-	{
-		kfree(buffer);
-        return NDIS_STATUS_FAILURE;
-	}
-
-	orgfsuid = current->fsuid;
-	orgfsgid = current->fsgid;
-	current->fsuid = current->fsgid = 0;
-    orgfs = get_fs();
-    set_fs(KERNEL_DS);
-
-	// get RF IC type
-	RTMP_IO_READ32(pAd, E2PROM_CSR, &data);
-
-	if ((data & 0x30) == 0)
-		pAd->EEPROMAddressNum = 6;	// 93C46
-	else if ((data & 0x30) == 0x10)
-		pAd->EEPROMAddressNum = 8;	// 93C66
-	else
-		pAd->EEPROMAddressNum = 8;	// 93C86
-
-	RT28xx_EEPROM_READ16(pAd, EEPROM_NIC1_OFFSET, antenna.word);
-
-	if ((antenna.field.RfIcType == RFIC_2850) ||
-		(antenna.field.RfIcType == RFIC_2750))
-	{
-		/* ABGN card */
-		strcpy(RFIC_word, "abgn");
-	}
-	else
-	{
-		/* BGN card */
-		strcpy(RFIC_word, "bgn");
-	}
-
-	// get MAC address
-	RT28xx_EEPROM_READ16(pAd, 0x04, addr01);
-	RT28xx_EEPROM_READ16(pAd, 0x06, addr23);
-	RT28xx_EEPROM_READ16(pAd, 0x08, addr45);
-
-	mac[0] = (UCHAR)(addr01 & 0xff);
-	mac[1] = (UCHAR)(addr01 >> 8);
-	mac[2] = (UCHAR)(addr23 & 0xff);
-	mac[3] = (UCHAR)(addr23 >> 8);
-	mac[4] = (UCHAR)(addr45 & 0xff);
-	mac[5] = (UCHAR)(addr45 >> 8);
-
-	// open card information file
-	srcf = filp_open(CARD_INFO_PATH, O_RDONLY, 0);
-	if (IS_ERR(srcf))
-	{
-		/* card information file does not exist */
-			DBGPRINT(RT_DEBUG_TRACE,
-				("--> Error %ld opening %s\n", -PTR_ERR(srcf), CARD_INFO_PATH));
-		return FALSE;
-	}
-
-	if (srcf->f_op && srcf->f_op->read)
-	{
-		/* card information file exists so reading the card information */
-		memset(buffer, 0x00, MAX_INI_BUFFER_SIZE);
-		retval = srcf->f_op->read(srcf, buffer, MAX_INI_BUFFER_SIZE, &srcf->f_pos);
-		if (retval < 0)
-		{
-			/* read fail */
-				DBGPRINT(RT_DEBUG_TRACE,
-					("--> Read %s error %d\n", CARD_INFO_PATH, -retval));
-		}
-		else
-		{
-			/* get card selection method */
-			memset(tmpbuf, 0x00, MAX_PARAM_BUFFER_SIZE);
-			card_select_method = MC_SELECT_CARDTYPE; // default
-
-			if (RTMPGetKeyParameter("SELECT", tmpbuf, 256, buffer))
-			{
-				if (strcmp(tmpbuf, "CARDID") == 0)
-					card_select_method = MC_SELECT_CARDID;
-				else if (strcmp(tmpbuf, "MAC") == 0)
-					card_select_method = MC_SELECT_MAC;
-				else if (strcmp(tmpbuf, "CARDTYPE") == 0)
-					card_select_method = MC_SELECT_CARDTYPE;
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE,
-					("MC> Card Selection = %d\n", card_select_method));
-
-			// init
-			card_free_id = -1;
-			card_nouse_id = -1;
-			card_same_mac_id = -1;
-			card_match_id = -1;
-
-			// search current card information records
-			for(card_index=0;
-				card_index<MAX_NUM_OF_MULTIPLE_CARD;
-				card_index++)
-			{
-				if ((*(UINT32 *)&MC_CardMac[card_index][0] == 0) &&
-					(*(UINT16 *)&MC_CardMac[card_index][4] == 0))
-				{
-					// MAC is all-0 so the entry is available
-					MC_CardUsed[card_index] = 0;
-
-					if (card_free_id < 0)
-						card_free_id = card_index; // 1st free entry
-				}
-				else
-				{
-					if (memcmp(MC_CardMac[card_index], mac, 6) == 0)
-					{
-						// we find the entry with same MAC
-						if (card_same_mac_id < 0)
-							card_same_mac_id = card_index; // 1st same entry
-					}
-					else
-					{
-						// MAC is not all-0 but used flag == 0
-						if ((MC_CardUsed[card_index] == 0) &&
-							(card_nouse_id < 0))
-						{
-							card_nouse_id = card_index; // 1st available entry
-						}
-					}
-				}
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE,
-					("MC> Free = %d, Same = %d, NOUSE = %d\n",
-					card_free_id, card_same_mac_id, card_nouse_id));
-
-			if ((card_same_mac_id >= 0) &&
-				((card_select_method == MC_SELECT_CARDID) ||
-				(card_select_method == MC_SELECT_CARDTYPE)))
-			{
-				// same MAC entry is found
-				card_match_id = card_same_mac_id;
-
-				if (card_select_method == MC_SELECT_CARDTYPE)
-				{
-					// for CARDTYPE
-					sprintf(card_id_buf, "%02dCARDTYPE%s",
-							card_match_id, RFIC_word);
-
-					if ((start_ptr=rtstrstruncasecmp(buffer, card_id_buf)) != NULL)
-					{
-						// we found the card ID
-						LETTER_CASE_TRANSLATE(start_ptr, card_id_buf);
-					}
-				}
-			}
-			else
-			{
-				// the card is 1st plug-in, try to find the match card profile
-				switch(card_select_method)
-				{
-					case MC_SELECT_CARDID: // CARDID
-					default:
-						if (card_free_id >= 0)
-							card_match_id = card_free_id;
-						else
-							card_match_id = card_nouse_id;
-						break;
-
-					case MC_SELECT_MAC: // MAC
-						sprintf(card_id_buf, "MAC%02x:%02x:%02x:%02x:%02x:%02x",
-								mac[0], mac[1], mac[2],
-								mac[3], mac[4], mac[5]);
-
-						/* try to find the key word in the card file */
-						if ((start_ptr=rtstrstruncasecmp(buffer, card_id_buf)) != NULL)
-						{
-							LETTER_CASE_TRANSLATE(start_ptr, card_id_buf);
-
-							/* get the row ID (2 ASCII characters) */
-							start_ptr -= 2;
-							card_id_buf[0] = *(start_ptr);
-							card_id_buf[1] = *(start_ptr+1);
-							card_id_buf[2] = 0x00;
-
-							card_match_id = simple_strtol(card_id_buf, 0, 10);
-						}
-						break;
-
-					case MC_SELECT_CARDTYPE: // CARDTYPE
-						card_nouse_id = -1;
-
-						for(card_index=0;
-							card_index<MAX_NUM_OF_MULTIPLE_CARD;
-							card_index++)
-						{
-							sprintf(card_id_buf, "%02dCARDTYPE%s",
-									card_index, RFIC_word);
-
-							if ((start_ptr=rtstrstruncasecmp(buffer,
-														card_id_buf)) != NULL)
-							{
-								LETTER_CASE_TRANSLATE(start_ptr, card_id_buf);
-
-								if (MC_CardUsed[card_index] == 0)
-								{
-									/* current the card profile is not used */
-									if ((*(UINT32 *)&MC_CardMac[card_index][0] == 0) &&
-										(*(UINT16 *)&MC_CardMac[card_index][4] == 0))
-									{
-										// find it and no previous card use it
-										card_match_id = card_index;
-										break;
-									}
-									else
-									{
-										// ever a card use it
-										if (card_nouse_id < 0)
-											card_nouse_id = card_index;
-									}
-								}
-							}
-						}
-
-						// if not find a free one, use the available one
-						if (card_match_id < 0)
-							card_match_id = card_nouse_id;
-						break;
-				}
-			}
-
-			if (card_match_id >= 0)
-			{
-				// make up search keyword
-				switch(card_select_method)
-				{
-					case MC_SELECT_CARDID: // CARDID
-						sprintf(card_id_buf, "%02dCARDID", card_match_id);
-						break;
-
-					case MC_SELECT_MAC: // MAC
-						sprintf(card_id_buf,
-								"%02dmac%02x:%02x:%02x:%02x:%02x:%02x",
-								card_match_id,
-								mac[0], mac[1], mac[2],
-								mac[3], mac[4], mac[5]);
-						break;
-
-					case MC_SELECT_CARDTYPE: // CARDTYPE
-					default:
-						sprintf(card_id_buf, "%02dcardtype%s",
-								card_match_id, RFIC_word);
-						break;
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Search Keyword = %s\n", card_id_buf));
-
-				// read card file path
-				if (RTMPGetKeyParameter(card_id_buf, tmpbuf, 256, buffer))
-				{
-					if (strlen(tmpbuf) < sizeof(pAd->MC_FileName))
-					{
-						// backup card information
-						pAd->MC_RowID = card_match_id; /* base 0 */
-						MC_CardUsed[card_match_id] = 1;
-						memcpy(MC_CardMac[card_match_id], mac, sizeof(mac));
-
-						// backup card file path
-						NdisMoveMemory(pAd->MC_FileName, tmpbuf , strlen(tmpbuf));
-						pAd->MC_FileName[strlen(tmpbuf)] = '\0';
-						flg_match_ok = TRUE;
-
-						DBGPRINT(RT_DEBUG_TRACE,
-								("Card Profile Name = %s\n", pAd->MC_FileName));
-					}
-					else
-					{
-						DBGPRINT(RT_DEBUG_ERROR,
-								("Card Profile Name length too large!\n"));
-					}
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_ERROR,
-							("Can not find search key word in card.dat!\n"));
-				}
-
-				if ((flg_match_ok != TRUE) &&
-					(card_match_id < MAX_NUM_OF_MULTIPLE_CARD))
-				{
-					MC_CardUsed[card_match_id] = 0;
-					memset(MC_CardMac[card_match_id], 0, sizeof(mac));
-				}
-			} // if (card_match_id >= 0)
-		}
-	}
-
-	// close file
-	retval = filp_close(srcf, NULL);
-	set_fs(orgfs);
-	current->fsuid = orgfsuid;
-	current->fsgid = orgfsgid;
-	kfree(buffer);
-	kfree(tmpbuf);
-	return flg_match_ok;
-}
-#endif // MULTIPLE_CARD_SUPPORT //
-
-
 /*
 ========================================================================
 Routine Description:
@@ -1198,12 +761,17 @@
     PRTMP_ADAPTER       pAd = (PRTMP_ADAPTER) NULL;
     INT                 status;
 	PVOID				handle;
+#ifdef RT2860
 	struct pci_dev *dev_p = (struct pci_dev *)_dev_p;
+#endif
+#ifdef RT2870
+	struct usb_interface *intf = (struct usb_interface *)_dev_p;
+	struct usb_device *dev_p = interface_to_usbdev(intf);
 
+	dev_p = usb_get_dev(dev_p);
+#endif // RT2870 //
 
-#ifdef CONFIG_STA_SUPPORT
     DBGPRINT(RT_DEBUG_TRACE, ("STA Driver version-%s\n", STA_DRIVER_VERSION));
-#endif // CONFIG_STA_SUPPORT //
 
     net_dev = alloc_etherdev(sizeof(PRTMP_ADAPTER));
     if (net_dev == NULL)
@@ -1214,13 +782,12 @@
     }
 
 	netif_stop_queue(net_dev);
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
+
 /* for supporting Network Manager */
 /* Set the sysfs physical device reference for the network logical device
  * if set prior to registration will cause a symlink during initialization.
  */
     SET_NETDEV_DEV(net_dev, &(dev_p->dev));
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
 
 	// Allocate RTMP_ADAPTER miniport adapter structure
 	handle = kmalloc(sizeof(struct os_cookie), GFP_KERNEL);
@@ -1235,32 +802,13 @@
 
 	RT28XXNetDevInit(_dev_p, net_dev, pAd);
 
-#ifdef CONFIG_STA_SUPPORT
     pAd->StaCfg.OriDevType = net_dev->type;
-#endif // CONFIG_STA_SUPPORT //
 
 	// Post config
 	if (RT28XXProbePostConfig(_dev_p, pAd, 0) == FALSE)
 		goto err_out_unmap;
 
-#ifdef CONFIG_STA_SUPPORT
 	pAd->OpMode = OPMODE_STA;
-#endif // CONFIG_STA_SUPPORT //
-
-
-#ifdef MULTIPLE_CARD_SUPPORT
-	// find its profile path
-	pAd->MC_RowID = -1; // use default profile path
-	RTMP_CardInfoRead(pAd);
-
-	if (pAd->MC_RowID == -1)
-#ifdef CONFIG_STA_SUPPORT
-		strcpy(pAd->MC_FileName, STA_PROFILE_PATH);
-#endif // CONFIG_STA_SUPPORT //
-
-	DBGPRINT(RT_DEBUG_TRACE,
-			("MC> ROW = %d, PATH = %s\n", pAd->MC_RowID, pAd->MC_FileName));
-#endif // MULTIPLE_CARD_SUPPORT //
 
 	// sample move
 	if (rt_ieee80211_if_setup(net_dev, pAd) != NDIS_STATUS_SUCCESS)
@@ -1317,17 +865,6 @@
 	int status = 0;
 	PNDIS_PACKET pPacket = (PNDIS_PACKET) skb;
 
-	/* RT2870STA does this in RTMPSendPackets() */
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_RESOURCES);
-		return 0;
-	}
-#endif // RALINK_ATE //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		// Drop send request since we are in monitor mode
 		if (MONITOR_ON(pAd))
@@ -1336,7 +873,6 @@
 			goto done;
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 
         // EapolStart size is 18
 	if (skb->len < 14)
@@ -1354,16 +890,7 @@
     }
 #endif
 
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-
-		STASendPackets((NDIS_HANDLE)pAd, (PPNDIS_PACKET) &pPacket, 1);
-	}
-
-#endif // CONFIG_STA_SUPPORT //
+	STASendPackets((NDIS_HANDLE)pAd, (PPNDIS_PACKET) &pPacket, 1);
 
 	status = 0;
 done:
@@ -1432,10 +959,8 @@
 	if(pAd->iw_stats.qual.qual > 100)
 		pAd->iw_stats.qual.qual = 100;
 
-#ifdef CONFIG_STA_SUPPORT
 	if (pAd->OpMode == OPMODE_STA)
 		pAd->iw_stats.qual.level = RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2);
-#endif // CONFIG_STA_SUPPORT //
 
 	pAd->iw_stats.qual.noise = pAd->BbpWriteLatch[66]; // noise level (dBm)
 
@@ -1487,13 +1012,7 @@
 		return -ENETDOWN;
 	}
 
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		ret = rt28xx_sta_ioctl(net_dev, rq, cmd);
-	}
-#endif // CONFIG_STA_SUPPORT //
+	ret = rt28xx_sta_ioctl(net_dev, rq, cmd);
 
 	return ret;
 }
diff --git a/drivers/staging/rt2860/rt_profile.c b/drivers/staging/rt2860/rt_profile.c
index 62141f3..d92b143 100644
--- a/drivers/staging/rt2860/rt_profile.c
+++ b/drivers/staging/rt2860/rt_profile.c
@@ -27,12 +27,10 @@
 
 #include "rt_config.h"
 
-#ifdef DOT11_N_SUPPORT
 static void HTParametersHook(
 	IN	PRTMP_ADAPTER pAd,
 	IN	CHAR		  *pValueStr,
 	IN	CHAR		  *pInput);
-#endif // DOT11_N_SUPPORT //
 
 #define ETH_MAC_ADDR_STR_LEN 17  // in format of xx:xx:xx:xx:xx:xx
 
@@ -756,9 +754,6 @@
 	//DefaultKeyID
 	if(RTMPGetKeyParameter("DefaultKeyID", tmpbuf, 25, buffer))
 	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			KeyIdx = simple_strtol(tmpbuf, 0, 10);
 			if((KeyIdx >= 1 ) && (KeyIdx <= 4))
@@ -768,7 +763,6 @@
 
 			DBGPRINT(RT_DEBUG_TRACE, ("DefaultKeyID(0~3)=%d\n", pAd->StaCfg.DefaultKeyId));
 		}
-#endif // CONFIG_STA_SUPPORT //
 	}
 
 
@@ -783,8 +777,6 @@
 			    KeyType[i] = simple_strtol(macptr, 0, 10);
 		    }
 
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 			{
 				sprintf(tok_str, "Key%dStr", idx + 1);
 				if (RTMPGetCriticalParameter(tok_str, tmpbuf, 128, buffer))
@@ -792,13 +784,10 @@
 					rtmp_parse_key_buffer_from_file(pAd, tmpbuf, KeyType[BSS0], BSS0, idx);
 				}
 			}
-#endif // CONFIG_STA_SUPPORT //
 		}
 	}
 }
 
-
-#ifdef CONFIG_STA_SUPPORT
 static void rtmp_read_sta_wmm_parms_from_file(IN  PRTMP_ADAPTER pAd, char *tmpbuf, char *buffer)
 {
 	PUCHAR					macptr;
@@ -821,23 +810,6 @@
 		DBGPRINT(RT_DEBUG_TRACE, ("WmmCapable=%d\n", pAd->CommonCfg.bWmmCapable));
 	}
 
-#ifdef QOS_DLS_SUPPORT
-	//DLSCapable
-	if(RTMPGetKeyParameter("DLSCapable", tmpbuf, 32, buffer))
-	{
-		if(simple_strtol(tmpbuf, 0, 10) != 0)  //Enable
-		{
-			pAd->CommonCfg.bDLSCapable = TRUE;
-		}
-		else //Disable
-		{
-			pAd->CommonCfg.bDLSCapable = FALSE;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("bDLSCapable=%d\n", pAd->CommonCfg.bDLSCapable));
-	}
-#endif // QOS_DLS_SUPPORT //
-
 	//AckPolicy for AC_BK, AC_BE, AC_VI, AC_VO
 	if(RTMPGetKeyParameter("AckPolicy", tmpbuf, 32, buffer))
 	{
@@ -882,8 +854,6 @@
 	}
 
 }
-#endif // CONFIG_STA_SUPPORT //
-
 
 NDIS_STATUS	RTMPReadParametersHook(
 	IN	PRTMP_ADAPTER pAd)
@@ -896,10 +866,7 @@
 	CHAR					*tmpbuf;
 	ULONG					RtsThresh;
 	ULONG					FragThresh;
-#ifdef CONFIG_STA_SUPPORT
 	UCHAR	                keyMaterial[40];
-#endif // CONFIG_STA_SUPPORT //
-
 
 	PUCHAR					macptr;
 	INT						i = 0;
@@ -915,21 +882,17 @@
         return NDIS_STATUS_FAILURE;
 	}
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		src = STA_PROFILE_PATH;
-#endif // CONFIG_STA_SUPPORT //
-#ifdef MULTIPLE_CARD_SUPPORT
-	src = pAd->MC_FileName;
-#endif // MULTIPLE_CARD_SUPPORT //
+	src = STA_PROFILE_PATH;
 
 	// Save uid and gid used for filesystem access.
 	// Set user and group to 0 (root)
+#ifndef RT30xx
 	orgfsuid = current_fsuid();
 	orgfsgid = current_fsgid();
 	/* Hm, can't really do this nicely anymore, so rely on these files
 	 * being set to the proper permission to read them... */
 	/* current->cred->fsuid = current->cred->fsgid = 0; */
+#endif
     orgfs = get_fs();
     set_fs(KERNEL_DS);
 
@@ -970,12 +933,7 @@
 					if(RTMPGetKeyParameter("CountryCode", tmpbuf, 25, buffer))
 					{
 						NdisMoveMemory(pAd->CommonCfg.CountryCode, tmpbuf , 2);
-#ifdef CONFIG_STA_SUPPORT
-#ifdef EXT_BUILD_CHANNEL_LIST
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-							NdisMoveMemory(pAd->StaCfg.StaOriCountryCode, tmpbuf , 2);
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
+
 						if (strlen(pAd->CommonCfg.CountryCode) != 0)
 						{
 							pAd->CommonCfg.bCountryFlag = TRUE;
@@ -991,12 +949,6 @@
 							pAd->CommonCfg.Geography = Geography;
 							pAd->CommonCfg.CountryCode[2] =
 								(pAd->CommonCfg.Geography == BOTH) ? ' ' : ((pAd->CommonCfg.Geography == IDOR) ? 'I' : 'O');
-#ifdef CONFIG_STA_SUPPORT
-#ifdef EXT_BUILD_CHANNEL_LIST
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-							pAd->StaCfg.StaOriGeography = pAd->CommonCfg.Geography;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
 							DBGPRINT(RT_DEBUG_TRACE, ("ChannelGeography=%d\n", pAd->CommonCfg.Geography));
 						}
 					}
@@ -1006,9 +958,6 @@
 						pAd->CommonCfg.CountryCode[2] = ' ';
 					}
 
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 					{
 						//SSID
 						if (RTMPGetCriticalParameter("SSID", tmpbuf, 256, buffer))
@@ -1028,10 +977,7 @@
 							}
 						}
 					}
-#endif // CONFIG_STA_SUPPORT //
 
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 					{
 						//NetworkType
 						if (RTMPGetKeyParameter("NetworkType", tmpbuf, 25, buffer))
@@ -1046,7 +992,7 @@
 							DBGPRINT(RT_DEBUG_TRACE, ("%s::(NetworkType=%d)\n", __func__, pAd->StaCfg.BssType));
 						}
 					}
-#endif // CONFIG_STA_SUPPORT //
+
 					//Channel
 					if(RTMPGetKeyParameter("Channel", tmpbuf, 10, buffer))
 					{
@@ -1058,9 +1004,7 @@
 					{
 						int value  = 0, maxPhyMode = PHY_11G;
 
-#ifdef DOT11_N_SUPPORT
 						maxPhyMode = PHY_11N_5G;
-#endif // DOT11_N_SUPPORT //
 
 						value = simple_strtol(tmpbuf, 0, 10);
 
@@ -1086,10 +1030,9 @@
 					if(RTMPGetKeyParameter("TxPower", tmpbuf, 10, buffer))
 					{
 						pAd->CommonCfg.TxPowerPercentage = (ULONG) simple_strtol(tmpbuf, 0, 10);
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-							pAd->CommonCfg.TxPowerDefault = pAd->CommonCfg.TxPowerPercentage;
-#endif // CONFIG_STA_SUPPORT //
+
+						pAd->CommonCfg.TxPowerDefault = pAd->CommonCfg.TxPowerPercentage;
+
 						DBGPRINT(RT_DEBUG_TRACE, ("TxPower=%ld\n", pAd->CommonCfg.TxPowerPercentage));
 					}
 					//BGProtection
@@ -1206,11 +1149,7 @@
 #endif // AGGREGATION_SUPPORT //
 
 					// WmmCapable
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-						rtmp_read_sta_wmm_parms_from_file(pAd, tmpbuf, buffer);
-#endif // CONFIG_STA_SUPPORT //
+					rtmp_read_sta_wmm_parms_from_file(pAd, tmpbuf, buffer);
 
 					//ShortSlot
 					if(RTMPGetKeyParameter("ShortSlot", tmpbuf, 10, buffer))
@@ -1313,8 +1252,6 @@
 					//AuthMode
 					if(RTMPGetKeyParameter("AuthMode", tmpbuf, 128, buffer))
 					{
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 						{
 							if ((strcmp(tmpbuf, "WEPAUTO") == 0) || (strcmp(tmpbuf, "wepauto") == 0))
 							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeAutoSwitch;
@@ -1326,12 +1263,10 @@
 							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
 							else if ((strcmp(tmpbuf, "WPA2PSK") == 0) || (strcmp(tmpbuf, "wpa2psk") == 0))
 							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-#ifdef WPA_SUPPLICANT_SUPPORT
 							else if ((strcmp(tmpbuf, "WPA") == 0) || (strcmp(tmpbuf, "wpa") == 0))
 							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
 							else if ((strcmp(tmpbuf, "WPA2") == 0) || (strcmp(tmpbuf, "wpa2") == 0))
 							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#endif // WPA_SUPPLICANT_SUPPORT //
 				                        else
 				                            pAd->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
 
@@ -1339,14 +1274,10 @@
 
 							DBGPRINT(RT_DEBUG_TRACE, ("%s::(EncrypType=%d)\n", __func__, pAd->StaCfg.WepStatus));
 						}
-#endif // CONFIG_STA_SUPPORT //
 					}
 					//EncrypType
 					if(RTMPGetKeyParameter("EncrypType", tmpbuf, 128, buffer))
 					{
-
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 						{
 							if ((strcmp(tmpbuf, "WEP") == 0) || (strcmp(tmpbuf, "wep") == 0))
 								pAd->StaCfg.WepStatus	= Ndis802_11WEPEnabled;
@@ -1365,13 +1296,8 @@
 
 							DBGPRINT(RT_DEBUG_TRACE, ("%s::(EncrypType=%d)\n", __func__, pAd->StaCfg.WepStatus));
 						}
-#endif // CONFIG_STA_SUPPORT //
 					}
 
-
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 					{
 						if(RTMPGetCriticalParameter("WPAPSK", tmpbuf, 512, buffer))
 						{
@@ -1420,38 +1346,20 @@
 							}
 						}
 					}
-#endif // CONFIG_STA_SUPPORT //
 
 					//DefaultKeyID, KeyType, KeyStr
 					rtmp_read_key_parms_from_file(pAd, tmpbuf, buffer);
 
-#ifdef DOT11_N_SUPPORT
 					HTParametersHook(pAd, tmpbuf, buffer);
-#endif // DOT11_N_SUPPORT //
 
-
-#ifdef CARRIER_DETECTION_SUPPORT
-						//CarrierDetect
-						if(RTMPGetKeyParameter("CarrierDetect", tmpbuf, 128, buffer))
-						{
-							if ((strncmp(tmpbuf, "0", 1) == 0))
-								pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-							else if ((strncmp(tmpbuf, "1", 1) == 0))
-								pAd->CommonCfg.CarrierDetect.Enable = TRUE;
-							else
-								pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-
-							DBGPRINT(RT_DEBUG_TRACE, ("CarrierDetect.Enable=%d\n", pAd->CommonCfg.CarrierDetect.Enable));
-						}
-						else
-							pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-#endif // CARRIER_DETECTION_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 					{
 						//PSMode
+#ifdef RT2860
 						if (RTMPGetKeyParameter("PSMode", tmpbuf, 32, buffer))
+#endif
+#ifdef RT2870
+						if (RTMPGetKeyParameter("PSMode", tmpbuf, 10, buffer))
+#endif
 						{
 							if (pAd->StaCfg.BssType == BSS_INFRA)
 							{
@@ -1534,8 +1442,23 @@
 								DBGPRINT(RT_DEBUG_TRACE, ("TGnWifiTest=%d\n", pAd->StaCfg.bTGnWifiTest));
 						}
 					}
-#endif // CONFIG_STA_SUPPORT //
 
+#ifdef RT30xx
+						{
+							if(RTMPGetKeyParameter("AntDiversity", tmpbuf, 10, buffer))
+							{
+								for (i = 0, macptr = rstrtok(tmpbuf,";"); macptr; macptr = rstrtok(NULL,";"), i++)
+								{
+									if(simple_strtol(macptr, 0, 10) != 0)  //Enable
+										pAd->CommonCfg.bRxAntDiversity = TRUE;
+									else //Disable
+										pAd->CommonCfg.bRxAntDiversity = FALSE;
+
+									DBGPRINT(RT_DEBUG_ERROR, ("AntDiversity=%d\n", pAd->CommonCfg.bRxAntDiversity));
+								}
+							}
+						}
+#endif // RT30xx //
 				}
 			}
 			else
@@ -1554,18 +1477,12 @@
 
 	set_fs(orgfs);
 
-#if 0
-	current->cred->fsuid = orgfsuid;
-	current->cred->fsgid = orgfsgid;
-#endif
-
 	kfree(buffer);
 	kfree(tmpbuf);
 
 	return (NDIS_STATUS_SUCCESS);
 }
 
-#ifdef DOT11_N_SUPPORT
 static void	HTParametersHook(
 	IN	PRTMP_ADAPTER pAd,
 	IN	CHAR		  *pValueStr,
@@ -1654,12 +1571,21 @@
         if (Value == 0)
         {
             pAd->CommonCfg.BACapability.field.AutoBA = FALSE;
+#ifdef RT30xx
+	    pAd->CommonCfg.BACapability.field.Policy = BA_NOTUSE;
+#endif
         }
         else
         {
             pAd->CommonCfg.BACapability.field.AutoBA = TRUE;
+#ifdef RT30xx
+	    pAd->CommonCfg.BACapability.field.Policy = IMMED_BA;
+#endif
         }
         pAd->CommonCfg.REGBACapability.field.AutoBA = pAd->CommonCfg.BACapability.field.AutoBA;
+#ifdef RT30xx
+	pAd->CommonCfg.REGBACapability.field.Policy = pAd->CommonCfg.BACapability.field.Policy;
+#endif
         DBGPRINT(RT_DEBUG_TRACE, ("HT: Auto BA  = %s\n", (Value==0) ? "Disable" : "Enable"));
     }
 
@@ -1804,8 +1730,6 @@
 	{
 		UCHAR	fix_tx_mode;
 
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			fix_tx_mode = FIXED_TXMODE_HT;
 
@@ -1837,7 +1761,6 @@
 			DBGPRINT(RT_DEBUG_TRACE, ("Fixed Tx Mode = %d\n", fix_tx_mode));
 
 		}
-#endif // CONFIG_STA_SUPPORT //
 	}
 
 
@@ -1882,9 +1805,6 @@
 	// MSC
 	if (RTMPGetKeyParameter("HT_MCS", pValueStr, 50, pInput))
 	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 		{
 			Value = simple_strtol(pValueStr, 0, 10);
 
@@ -1901,7 +1821,6 @@
 				DBGPRINT(RT_DEBUG_TRACE, ("HT: MCS = AUTO\n"));
 		}
 	}
-#endif // CONFIG_STA_SUPPORT //
 	}
 
 	// STBC
@@ -1977,5 +1896,3 @@
 	}
 
 }
-#endif // DOT11_N_SUPPORT //
-
diff --git a/drivers/staging/rt2860/rtmp.h b/drivers/staging/rt2860/rtmp.h
index b904b78..25c3199 100644
--- a/drivers/staging/rt2860/rtmp.h
+++ b/drivers/staging/rt2860/rtmp.h
@@ -43,25 +43,112 @@
 #include "link_list.h"
 #include "spectrum_def.h"
 
-
-#ifdef CONFIG_STA_SUPPORT
 #include "aironet.h"
-#endif // CONFIG_STA_SUPPORT //
 
 //#define DBG_DIAGNOSE		1
 
-#if defined(CONFIG_AP_SUPPORT) && defined(CONFIG_STA_SUPPORT)
-#define IF_DEV_CONFIG_OPMODE_ON_AP(_pAd)	if(_pAd->OpMode == OPMODE_AP)
-#define IF_DEV_CONFIG_OPMODE_ON_STA(_pAd)	if(_pAd->OpMode == OPMODE_STA)
-#else
-#define IF_DEV_CONFIG_OPMODE_ON_AP(_pAd)
-#define IF_DEV_CONFIG_OPMODE_ON_STA(_pAd)
-#endif
-
 #define VIRTUAL_IF_INC(__pAd) ((__pAd)->VirtualIfCnt++)
 #define VIRTUAL_IF_DEC(__pAd) ((__pAd)->VirtualIfCnt--)
 #define VIRTUAL_IF_NUM(__pAd) ((__pAd)->VirtualIfCnt)
 
+#ifdef RT2870
+////////////////////////////////////////////////////////////////////////////
+// The TX_BUFFER structure forms the transmitted USB packet to the device
+////////////////////////////////////////////////////////////////////////////
+typedef struct __TX_BUFFER{
+	union	{
+		UCHAR			WirelessPacket[TX_BUFFER_NORMSIZE];
+		HEADER_802_11	NullFrame;
+		PSPOLL_FRAME	PsPollPacket;
+		RTS_FRAME		RTSFrame;
+	}field;
+	UCHAR			Aggregation[4];  //Buffer for save Aggregation size.
+} TX_BUFFER, *PTX_BUFFER;
+
+typedef struct __HTTX_BUFFER{
+	union	{
+		UCHAR			WirelessPacket[MAX_TXBULK_SIZE];
+		HEADER_802_11	NullFrame;
+		PSPOLL_FRAME	PsPollPacket;
+		RTS_FRAME		RTSFrame;
+	}field;
+	UCHAR			Aggregation[4];  //Buffer for save Aggregation size.
+} HTTX_BUFFER, *PHTTX_BUFFER;
+
+
+// used to track driver-generated write irps
+typedef struct _TX_CONTEXT
+{
+	PVOID			pAd;		//Initialized in MiniportInitialize
+	PURB			pUrb;			//Initialized in MiniportInitialize
+	PIRP			pIrp;			//used to cancel pending bulk out.
+									//Initialized in MiniportInitialize
+	PTX_BUFFER		TransferBuffer;	//Initialized in MiniportInitialize
+	ULONG			BulkOutSize;
+	UCHAR			BulkOutPipeId;
+	UCHAR			SelfIdx;
+	BOOLEAN			InUse;
+	BOOLEAN			bWaitingBulkOut; // at least one packet is in this TxContext, ready for making IRP anytime.
+	BOOLEAN			bFullForBulkOut; // all tx buffer are full , so waiting for tx bulkout.
+	BOOLEAN			IRPPending;
+	BOOLEAN			LastOne;
+	BOOLEAN			bAggregatible;
+	UCHAR			Header_802_3[LENGTH_802_3];
+	UCHAR			Rsv[2];
+	ULONG			DataOffset;
+	UINT			TxRate;
+	dma_addr_t		data_dma;		// urb dma on linux
+
+}	TX_CONTEXT, *PTX_CONTEXT, **PPTX_CONTEXT;
+
+
+// used to track driver-generated write irps
+typedef struct _HT_TX_CONTEXT
+{
+	PVOID			pAd;		//Initialized in MiniportInitialize
+	PURB			pUrb;			//Initialized in MiniportInitialize
+	PIRP			pIrp;			//used to cancel pending bulk out.
+									//Initialized in MiniportInitialize
+	PHTTX_BUFFER	TransferBuffer;	//Initialized in MiniportInitialize
+	ULONG			BulkOutSize;	// Indicate the total bulk-out size in bytes in one bulk-transmission
+	UCHAR			BulkOutPipeId;
+	BOOLEAN			IRPPending;
+	BOOLEAN			LastOne;
+	BOOLEAN			bCurWriting;
+	BOOLEAN			bRingEmpty;
+	BOOLEAN			bCopySavePad;
+	UCHAR			SavedPad[8];
+	UCHAR			Header_802_3[LENGTH_802_3];
+	ULONG			CurWritePosition;		// Indicate the buffer offset which packet will be inserted start from.
+	ULONG			CurWriteRealPos;		// Indicate the buffer offset which packet now are writing to.
+	ULONG			NextBulkOutPosition;	// Indicate the buffer start offset of a bulk-transmission
+	ULONG			ENextBulkOutPosition;	// Indicate the buffer end offset of a bulk-transmission
+	UINT			TxRate;
+	dma_addr_t		data_dma;		// urb dma on linux
+}	HT_TX_CONTEXT, *PHT_TX_CONTEXT, **PPHT_TX_CONTEXT;
+
+
+//
+// Structure to keep track of receive packets and buffers to indicate
+// receive data to the protocol.
+//
+typedef struct _RX_CONTEXT
+{
+	PUCHAR				TransferBuffer;
+	PVOID				pAd;
+	PIRP				pIrp;//used to cancel pending bulk in.
+	PURB				pUrb;
+	//These 2 Boolean shouldn't both be 1 at the same time.
+	ULONG				BulkInOffset;	// number of packets waiting for reordering .
+	BOOLEAN				bRxHandling;	// Notify this packet is being process now.
+	BOOLEAN				InUse;			// USB Hardware Occupied. Wait for USB HW to put packet.
+	BOOLEAN				Readable;		// Receive Complete back. OK for driver to indicate receiving packet.
+	BOOLEAN				IRPPending;		// TODO: To be removed
+	atomic_t			IrpLock;
+	NDIS_SPIN_LOCK		RxContextLock;
+	dma_addr_t			data_dma;		// urb dma on linux
+}	RX_CONTEXT, *PRX_CONTEXT;
+#endif // RT2870 //
 
 
 //
@@ -136,14 +223,9 @@
 extern UCHAR  SupRateIe;
 extern UCHAR  ExtRateIe;
 
-#ifdef DOT11_N_SUPPORT
 extern UCHAR  HtCapIe;
 extern UCHAR  AddHtInfoIe;
 extern UCHAR  NewExtChanIe;
-#ifdef DOT11N_DRAFT3
-extern UCHAR  ExtHtCapIe;
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
 
 extern UCHAR  ErpIe;
 extern UCHAR  DsIe;
@@ -152,9 +234,15 @@
 extern UCHAR  Wpa2Ie;
 extern UCHAR  IbssIe;
 extern UCHAR  Ccx2Ie;
+#ifdef RT30xx
+extern UCHAR  WapiIe;
+#endif
 
 extern UCHAR  WPA_OUI[];
 extern UCHAR  RSN_OUI[];
+#ifdef RT30xx
+extern UCHAR  WAPI_OUI[];
+#endif
 extern UCHAR  WME_INFO_ELEM[];
 extern UCHAR  WME_PARM_ELEM[];
 extern UCHAR  Ccx2QosInfo[];
@@ -168,7 +256,6 @@
 extern UCHAR  RateSwitchTable11G[];
 extern UCHAR  RateSwitchTable11BG[];
 
-#ifdef DOT11_N_SUPPORT
 extern UCHAR  RateSwitchTable11BGN1S[];
 extern UCHAR  RateSwitchTable11BGN2S[];
 extern UCHAR  RateSwitchTable11BGN2SForABand[];
@@ -176,97 +263,10 @@
 extern UCHAR  RateSwitchTable11N2S[];
 extern UCHAR  RateSwitchTable11N2SForABand[];
 
-#ifdef CONFIG_STA_SUPPORT
 extern UCHAR  PRE_N_HT_OUI[];
-#endif // CONFIG_STA_SUPPORT //
-#endif // DOT11_N_SUPPORT //
 
 #define	MAXSEQ		(0xFFF)
 
-#ifdef RALINK_ATE
-typedef	struct _ATE_INFO {
-	UCHAR	Mode;
-	CHAR	TxPower0;
-	CHAR	TxPower1;
-	CHAR    TxAntennaSel;
-	CHAR    RxAntennaSel;
-	TXWI_STRUC  TxWI; 	  // TXWI
-	USHORT	QID;
-	UCHAR	Addr1[MAC_ADDR_LEN];
-	UCHAR	Addr2[MAC_ADDR_LEN];
-	UCHAR	Addr3[MAC_ADDR_LEN];
-	UCHAR	Channel;
-	UINT32	TxLength;
-	UINT32	TxCount;
-	UINT32	TxDoneCount; // Tx DMA Done
-	UINT32	RFFreqOffset;
-	BOOLEAN	bRxFer;
-	BOOLEAN	bQATxStart; // Have compiled QA in and use it to ATE tx.
-	BOOLEAN	bQARxStart;	// Have compiled QA in and use it to ATE rx.
-	BOOLEAN	bFWLoading;	// Reload firmware when ATE is done.
-	UINT32	RxTotalCnt;
-	UINT32	RxCntPerSec;
-
-	CHAR	LastSNR0;             // last received SNR
-	CHAR    LastSNR1;             // last received SNR for 2nd  antenna
-	CHAR    LastRssi0;            // last received RSSI
-	CHAR    LastRssi1;            // last received RSSI for 2nd  antenna
-	CHAR    LastRssi2;            // last received RSSI for 3rd  antenna
-	CHAR    AvgRssi0;             // last 8 frames' average RSSI
-	CHAR    AvgRssi1;             // last 8 frames' average RSSI
-	CHAR    AvgRssi2;             // last 8 frames' average RSSI
-	SHORT   AvgRssi0X8;           // sum of last 8 frames' RSSI
-	SHORT   AvgRssi1X8;           // sum of last 8 frames' RSSI
-	SHORT   AvgRssi2X8;           // sum of last 8 frames' RSSI
-
-	UINT32	NumOfAvgRssiSample;
-
-#ifdef RALINK_28xx_QA
-	// Tx frame
-	USHORT		HLen; // Header Length
-	USHORT		PLen; // Pattern Length
-	UCHAR 		Header[32]; // Header buffer
-	UCHAR		Pattern[32]; // Pattern buffer
-	USHORT		DLen; // Data Length
-	USHORT		seq;
-	UINT32		CID;
-	THREAD_PID 		AtePid;
-	// counters
-	UINT32		U2M;
-	UINT32		OtherData;
-	UINT32		Beacon;
-	UINT32		OtherCount;
-	UINT32		TxAc0;
-	UINT32		TxAc1;
-	UINT32		TxAc2;
-	UINT32		TxAc3;
-	UINT32		TxHCCA;
-	UINT32		TxMgmt;
-	UINT32		RSSI0;
-	UINT32		RSSI1;
-	UINT32		RSSI2;
-	UINT32		SNR0;
-	UINT32		SNR1;
-	// control
-	//UINT32		Repeat; // Tx Cpu count
-	UCHAR		TxStatus; // task Tx status // 0 --> task is idle, 1 --> task is running
-#endif // RALINK_28xx_QA //
-}	ATE_INFO, *PATE_INFO;
-
-#ifdef RALINK_28xx_QA
-struct ate_racfghdr {
- 	UINT32		magic_no;
-	USHORT		command_type;
-	USHORT		command_id;
-	USHORT		length;
-	USHORT		sequence;
-	USHORT		status;
-	UCHAR		data[2046];
-}  __attribute__((packed));
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-#ifdef DOT11_N_SUPPORT
 struct reordering_mpdu
 {
 	struct reordering_mpdu	*next;
@@ -287,7 +287,6 @@
 	NDIS_SPIN_LOCK			lock;
 	struct reordering_list 	freelist;
 };
-#endif // DOT11_N_SUPPORT //
 
 typedef struct 	_RSSI_SAMPLE {
 	CHAR			LastRssi0;             // last received RSSI
@@ -364,12 +363,14 @@
 #define RTMP_TEST_FLAG(_M, _F)      (((_M)->Flags & (_F)) != 0)
 #define RTMP_TEST_FLAGS(_M, _F)     (((_M)->Flags & (_F)) == (_F))
 
+#ifdef RT2860
 // Macro for power save flag.
 #define RTMP_SET_PSFLAG(_M, _F)       ((_M)->PSFlags |= (_F))
 #define RTMP_CLEAR_PSFLAG(_M, _F)     ((_M)->PSFlags &= ~(_F))
 #define RTMP_CLEAR_PSFLAGS(_M)        ((_M)->PSFlags = 0)
 #define RTMP_TEST_PSFLAG(_M, _F)      (((_M)->PSFlags & (_F)) != 0)
 #define RTMP_TEST_PSFLAGS(_M, _F)     (((_M)->PSFlags & (_F)) == (_F))
+#endif
 
 #define OPSTATUS_SET_FLAG(_pAd, _F)     ((_pAd)->CommonCfg.OpStatusFlags |= (_F))
 #define OPSTATUS_CLEAR_FLAG(_pAd, _F)   ((_pAd)->CommonCfg.OpStatusFlags &= ~(_F))
@@ -383,14 +384,12 @@
 #define RX_FILTER_CLEAR_FLAG(_pAd, _F)  ((_pAd)->CommonCfg.PacketFilter &= ~(_F))
 #define RX_FILTER_TEST_FLAG(_pAd, _F)   (((_pAd)->CommonCfg.PacketFilter & (_F)) != 0)
 
-#ifdef CONFIG_STA_SUPPORT
 #define STA_NO_SECURITY_ON(_p)          (_p->StaCfg.WepStatus == Ndis802_11EncryptionDisabled)
 #define STA_WEP_ON(_p)                  (_p->StaCfg.WepStatus == Ndis802_11Encryption1Enabled)
 #define STA_TKIP_ON(_p)                 (_p->StaCfg.WepStatus == Ndis802_11Encryption2Enabled)
 #define STA_AES_ON(_p)                  (_p->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
 
 #define STA_TGN_WIFI_ON(_p)             (_p->StaCfg.bTGnWifiTest == TRUE)
-#endif // CONFIG_STA_SUPPORT //
 
 #define CKIP_KP_ON(_p)				((((_p)->StaCfg.CkipFlag) & 0x10) && ((_p)->StaCfg.bCkipCmicOn == TRUE))
 #define CKIP_CMIC_ON(_p)			((((_p)->StaCfg.CkipFlag) & 0x08) && ((_p)->StaCfg.bCkipCmicOn == TRUE))
@@ -401,7 +400,17 @@
     (_idx) = (_idx+1) % (_RingSize);       \
 }
 
+#ifdef RT30xx
+// We will have a cost down version which mac version is 0x3090xxxx
+#define IS_RT3090(_pAd)				((((_pAd)->MACVersion & 0xffff0000) == 0x30710000) || (((_pAd)->MACVersion & 0xffff0000) == 0x30900000))
+#endif
 #define IS_RT3070(_pAd)				(((_pAd)->MACVersion & 0xffff0000) == 0x30700000)
+#ifdef RT30xx
+#define IS_RT3071(_pAd)				(((_pAd)->MACVersion & 0xffff0000) == 0x30710000)
+#define IS_RT2070(_pAd)				(((_pAd)->RfIcType == RFIC_2020) || ((_pAd)->EFuseTag == 0x27))
+
+#define IS_RT30xx(_pAd)				(((_pAd)->MACVersion & 0xfff00000) == 0x30700000)
+#endif
 
 #define RING_PACKET_INIT(_TxRing, _idx)    \
 {                                          \
@@ -437,7 +446,6 @@
     }                                                   \
 }
 
-#ifdef DOT11_N_SUPPORT
 // StaActive.SupportedHtPhy.MCSSet is copied from AP beacon.  Don't need to update here.
 #define COPY_HTSETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(_pAd)                                 \
 {                                                                                       \
@@ -461,7 +469,6 @@
 	_pAd->MacTab.Content[BSSID_WCID].MmpsMode= (UCHAR)(_pHtCapability->HtCapInfo.MimoPs);	\
 	_pAd->MacTab.Content[BSSID_WCID].MaxRAmpduFactor = (UCHAR)(_pHtCapability->HtCapParm.MaxRAmpduFactor);	\
 }
-#endif // DOT11_N_SUPPORT //
 
 //
 // MACRO for 32-bit PCI register read / write
@@ -483,6 +490,7 @@
 //
 #define MAX_BUSY_COUNT  100         // Number of retry before failing access BBP & RF indirect register
 //
+#ifdef RT2860
 #define RTMP_RF_IO_WRITE32(_A, _V)                  \
 {                                                   \
     PHY_CSR4_STRUC  Value;                          \
@@ -646,7 +654,20 @@
     }                                                   \
     }                                                   \
 }
+#endif /* RT2860 */
+#ifdef RT2870
+#define RTMP_RF_IO_WRITE32(_A, _V)                 RTUSBWriteRFRegister(_A, _V)
+#define RTMP_BBP_IO_READ8_BY_REG_ID(_A, _I, _pV)   RTUSBReadBBPRegister(_A, _I, _pV)
+#define RTMP_BBP_IO_WRITE8_BY_REG_ID(_A, _I, _V)   RTUSBWriteBBPRegister(_A, _I, _V)
 
+#define BBP_IO_WRITE8_BY_REG_ID(_A, _I, _V)			RTUSBWriteBBPRegister(_A, _I, _V)
+#define BBP_IO_READ8_BY_REG_ID(_A, _I, _pV)   		RTUSBReadBBPRegister(_A, _I, _pV)
+#endif // RT2870 //
+
+#ifdef RT30xx
+#define RTMP_RF_IO_READ8_BY_REG_ID(_A, _I, _pV)    RT30xxReadRFRegister(_A, _I, _pV)
+#define RTMP_RF_IO_WRITE8_BY_REG_ID(_A, _I, _V)    RT30xxWriteRFRegister(_A, _I, _V)
+#endif // RT30xx //
 
 #define     MAP_CHANNEL_ID_TO_KHZ(ch, khz)  {               \
                 switch (ch)                                 \
@@ -897,6 +918,7 @@
 // Enqueue this frame to MLME engine
 // We need to enqueue the whole frame because MLME need to pass data type
 // information from 802.11 header
+#ifdef RT2860
 #define REPORT_MGMT_FRAME_TO_MLME(_pAd, Wcid, _pFrame, _FrameSize, _Rssi0, _Rssi1, _Rssi2, _PlcpSignal)        \
 {                                                                                       \
     UINT32 High32TSF, Low32TSF;                                                          \
@@ -904,6 +926,49 @@
     RTMP_IO_READ32(_pAd, TSF_TIMER_DW0, &Low32TSF);                                        \
     MlmeEnqueueForRecv(_pAd, Wcid, High32TSF, Low32TSF, (UCHAR)_Rssi0, (UCHAR)_Rssi1,(UCHAR)_Rssi2,_FrameSize, _pFrame, (UCHAR)_PlcpSignal);   \
 }
+#endif
+#ifdef RT2870
+#define REPORT_MGMT_FRAME_TO_MLME(_pAd, Wcid, _pFrame, _FrameSize, _Rssi0, _Rssi1, _Rssi2, _PlcpSignal)        \
+{                                                                                       \
+    UINT32 High32TSF=0, Low32TSF=0;                                                          \
+    MlmeEnqueueForRecv(_pAd, Wcid, High32TSF, Low32TSF, (UCHAR)_Rssi0, (UCHAR)_Rssi1,(UCHAR)_Rssi2,_FrameSize, _pFrame, (UCHAR)_PlcpSignal);   \
+}
+#endif // RT2870 //
+
+#ifdef RT30xx
+//Need to collect each ant's rssi concurrently
+//rssi1 is report to pair2 Ant and rss2 is reprot to pair1 Ant when 4 Ant
+#define COLLECT_RX_ANTENNA_AVERAGE_RSSI(_pAd, _rssi1, _rssi2)					\
+{																				\
+	SHORT	AvgRssi;															\
+	UCHAR	UsedAnt;															\
+	if (_pAd->RxAnt.EvaluatePeriod == 0)									\
+	{																		\
+		UsedAnt = _pAd->RxAnt.Pair1PrimaryRxAnt;							\
+		AvgRssi = _pAd->RxAnt.Pair1AvgRssi[UsedAnt];						\
+		if (AvgRssi < 0)													\
+			AvgRssi = AvgRssi - (AvgRssi >> 3) + _rssi1;					\
+		else																\
+			AvgRssi = _rssi1 << 3;											\
+		_pAd->RxAnt.Pair1AvgRssi[UsedAnt] = AvgRssi;						\
+	}																		\
+	else																	\
+	{																		\
+		UsedAnt = _pAd->RxAnt.Pair1SecondaryRxAnt;							\
+		AvgRssi = _pAd->RxAnt.Pair1AvgRssi[UsedAnt];						\
+		if ((AvgRssi < 0) && (_pAd->RxAnt.FirstPktArrivedWhenEvaluate))		\
+			AvgRssi = AvgRssi - (AvgRssi >> 3) + _rssi1;					\
+		else																\
+		{																	\
+			_pAd->RxAnt.FirstPktArrivedWhenEvaluate = TRUE;					\
+			AvgRssi = _rssi1 << 3;											\
+		}																	\
+		_pAd->RxAnt.Pair1AvgRssi[UsedAnt] = AvgRssi;						\
+		_pAd->RxAnt.RcvPktNumWhenEvaluate++;								\
+	}																		\
+}
+#endif // RT30xx //
+
 
 #define NDIS_QUERY_BUFFER(_NdisBuf, _ppVA, _pBufLen)                    \
     NdisQueryBuffer(_NdisBuf, _ppVA, _pBufLen)
@@ -916,7 +981,7 @@
 //
 #define JapanChannelCheck(channel)  ((channel == 52) || (channel == 56) || (channel == 60) || (channel == 64))
 
-#ifdef CONFIG_STA_SUPPORT
+#ifdef RT2860
 #define STA_PORT_SECURED(_pAd) \
 { \
 	_pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED; \
@@ -925,8 +990,16 @@
 	_pAd->MacTab.Content[BSSID_WCID].PortSecured = _pAd->StaCfg.PortSecured; \
 	NdisReleaseSpinLock(&(_pAd)->MacTabLock); \
 }
-#endif // CONFIG_STA_SUPPORT //
-
+#endif
+#ifdef RT2870
+#define STA_PORT_SECURED(_pAd) \
+{ \
+	_pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED; \
+	NdisAcquireSpinLock(&_pAd->MacTabLock); \
+	_pAd->MacTab.Content[BSSID_WCID].PortSecured = _pAd->StaCfg.PortSecured; \
+	NdisReleaseSpinLock(&_pAd->MacTabLock); \
+}
+#endif
 
 //
 // Register set pair for initialzation register set definition
@@ -975,17 +1048,10 @@
 
 
 typedef	union	_HEADER_802_11_SEQ{
-#ifdef RT_BIG_ENDIAN
-    struct {
-   	USHORT			Sequence:12;
-	USHORT			Frag:4;
-    }   field;
-#else
     struct {
 	USHORT			Frag:4;
 	USHORT			Sequence:12;
     }   field;
-#endif
     USHORT           value;
 }	HEADER_802_11_SEQ, *PHEADER_802_11_SEQ;
 
@@ -1002,7 +1068,12 @@
 	UCHAR 		DataOffset;
 	USHORT 		Datasize;
 	ULONG                   AllocSize;
+#ifdef RT2860
 	NDIS_PHYSICAL_ADDRESS   AllocPa;            // TxBuf physical address
+#endif
+#ifdef RT2870
+	PUCHAR					AllocPa;
+#endif // RT2870 //
 }   RTMP_REORDERBUF, *PRTMP_REORDERBUF;
 
 //
@@ -1101,7 +1172,9 @@
 
 typedef struct _COUNTER_RALINK {
 	ULONG           TransmittedByteCount;   // both successful and failure, used to calculate TX throughput
+#ifdef RT2860
 	ULONG           LastReceivedByteCount;
+#endif
 	ULONG           ReceivedByteCount;      // both CRC okay and CRC error, used to calculate RX throughput
 	ULONG           BeenDisassociatedCount;
 	ULONG           BadCQIAutoRecoveryCount;
@@ -1124,6 +1197,9 @@
 
 	UINT32   		OneSecFrameDuplicateCount;
 
+#ifdef RT2870
+	ULONG           OneSecTransmittedByteCount;   // both successful and failure, used to calculate TX throughput
+#endif // RT2870 //
 
 	UINT32          OneSecTxNoRetryOkCount;
 	UINT32          OneSecTxRetryOkCount;
@@ -1197,15 +1273,6 @@
 
 // MIMO Tx parameter, ShortGI, MCS, STBC, etc.  these are fields in TXWI too. just copy to TXWI.
 typedef struct  _RECEIVE_SETTING {
-#ifdef RT_BIG_ENDIAN
-	USHORT		MIMO:1;
-	USHORT		OFDM:1;
-	USHORT		rsv:3;
-	USHORT		STBC:2;	//SPACE
-	USHORT		ShortGI:1;
-	USHORT		Mode:2;	//channel bandwidth 20MHz or 40 MHz
-	USHORT   	NumOfRX:2;                 // MIMO. WE HAVE 3R
-#else
 	USHORT   	NumOfRX:2;                 // MIMO. WE HAVE 3R
 	USHORT		Mode:2;	//channel bandwidth 20MHz or 40 MHz
 	USHORT		ShortGI:1;
@@ -1213,7 +1280,6 @@
 	USHORT		rsv:3;
 	USHORT		OFDM:1;
 	USHORT		MIMO:1;
-#endif
  } RECEIVE_SETTING, *PRECEIVE_SETTING;
 
 // Shared key data structure
@@ -1230,9 +1296,7 @@
 	UCHAR   RxTsc[6];           // 48bit TSC value
 	UCHAR   CipherAlg;          // 0-none, 1:WEP64, 2:WEP128, 3:TKIP, 4:AES, 5:CKIP64, 6:CKIP128
 	UCHAR   KeyLen;
-#ifdef CONFIG_STA_SUPPORT
 	UCHAR   BssId[6];
-#endif // CONFIG_STA_SUPPORT //
             // Key length for each key, 0: entry is invalid
 	UCHAR   Type;               // Indicate Pairwise/Group when reporting MIC error
 } CIPHER_KEY, *PCIPHER_KEY;
@@ -1248,6 +1312,9 @@
 
 typedef struct _SOFT_RX_ANT_DIVERSITY_STRUCT {
 	UCHAR     EvaluatePeriod;		 // 0:not evalute status, 1: evaluate status, 2: switching status
+#ifdef RT30xx
+	UCHAR     EvaluateStableCnt;
+#endif
 	UCHAR     Pair1PrimaryRxAnt;     // 0:Ant-E1, 1:Ant-E2
 	UCHAR     Pair1SecondaryRxAnt;   // 0:Ant-E1, 1:Ant-E2
 	UCHAR     Pair2PrimaryRxAnt;     // 0:Ant-E3, 1:Ant-E4
@@ -1368,9 +1435,6 @@
 typedef struct _CHANNEL_TX_POWER {
 	USHORT     RemainingTimeForUse;		//unit: sec
 	UCHAR      Channel;
-#ifdef DOT11N_DRAFT3
-	BOOLEAN       bEffectedChannel;	// For BW 40 operating in 2.4GHz , the "effected channel" is the channel that is covered in 40Mhz.
-#endif // DOT11N_DRAFT3 //
 	CHAR       Power;
 	CHAR       Power2;
 	UCHAR      MaxTxPwr;
@@ -1393,7 +1457,6 @@
 } ABGBAND_STATE;
 
 typedef struct _MLME_STRUCT {
-#ifdef CONFIG_STA_SUPPORT
 	// STA state machines
 	STATE_MACHINE           CntlMachine;
 	STATE_MACHINE           AssocMachine;
@@ -1409,20 +1472,10 @@
 	STATE_MACHINE_FUNC      SyncFunc[SYNC_FUNC_SIZE];
 	STATE_MACHINE_FUNC      WpaPskFunc[WPA_PSK_FUNC_SIZE];
 	STATE_MACHINE_FUNC      AironetFunc[AIRONET_FUNC_SIZE];
-#endif // CONFIG_STA_SUPPORT //
 	STATE_MACHINE_FUNC      ActFunc[ACT_FUNC_SIZE];
 	// Action
 	STATE_MACHINE           ActMachine;
 
-
-#ifdef QOS_DLS_SUPPORT
-	STATE_MACHINE			DlsMachine;
-	STATE_MACHINE_FUNC      DlsFunc[DLS_FUNC_SIZE];
-#endif // QOS_DLS_SUPPORT //
-
-
-
-
 	ULONG                   ChannelQuality;  // 0..100, Channel Quality Indication for Roaming
 	ULONG                   Now32;           // latch the value of NdisGetSystemUpTime()
 	ULONG                   LastSendNULLpsmTime;
@@ -1437,9 +1490,11 @@
 	RALINK_TIMER_STRUCT     APSDPeriodicTimer;
 	RALINK_TIMER_STRUCT     LinkDownTimer;
 	RALINK_TIMER_STRUCT     LinkUpTimer;
+#ifdef RT2860
     UCHAR                   bPsPollTimerRunning;
     RALINK_TIMER_STRUCT     PsPollTimer;
 	RALINK_TIMER_STRUCT     RadioOnOffTimer;
+#endif
 	ULONG                   PeriodicRound;
 	ULONG                   OneSecPeriodicRound;
 
@@ -1448,7 +1503,10 @@
 	BOOLEAN					bEnableAutoAntennaCheck;
 	RALINK_TIMER_STRUCT		RxAntEvalTimer;
 
-
+#ifdef RT2870
+	UCHAR CaliBW40RfR24;
+	UCHAR CaliBW20RfR24;
+#endif // RT2870 //
 } MLME_STRUCT, *PMLME_STRUCT;
 
 // structure for radar detection and channel switch
@@ -1471,23 +1529,6 @@
 	UINT8		LongPulseRadarTh;
 } RADAR_DETECT_STRUCT, *PRADAR_DETECT_STRUCT;
 
-#ifdef CARRIER_DETECTION_SUPPORT
-typedef enum CD_STATE_n
-{
-	CD_NORMAL,
-	CD_SILENCE,
-	CD_MAX_STATE
-} CD_STATE;
-
-typedef struct CARRIER_DETECTION_s
-{
-	BOOLEAN					Enable;
-	UINT8					CDSessionTime;
-	UINT8					CDPeriod;
-	CD_STATE				CD_State;
-} CARRIER_DETECTION, *PCARRIER_DETECTION;
-#endif // CARRIER_DETECTION_SUPPORT //
-
 typedef enum _REC_BLOCKACK_STATUS
 {
     Recipient_NONE=0,
@@ -1504,7 +1545,6 @@
     Originator_Done
 } ORI_BLOCKACK_STATUS, *PORI_BLOCKACK_STATUS;
 
-#ifdef DOT11_N_SUPPORT
 typedef struct _BA_ORI_ENTRY{
 	UCHAR   Wcid;
 	UCHAR   TID;
@@ -1568,21 +1608,6 @@
 } QUERYBA_TABLE, *PQUERYBA_TABLE;
 
 typedef	union	_BACAP_STRUC	{
-#ifdef RT_BIG_ENDIAN
-	struct	{
-		UINT32     :4;
-		UINT32     b2040CoexistScanSup:1;		//As Sta, support do 2040 coexistence scan for AP. As Ap, support monitor trigger event to check if can use BW 40MHz.
-		UINT32     bHtAdhoc:1;			// adhoc can use ht rate.
-		UINT32     MMPSmode:2;	// MIMO power save more, 0:static, 1:dynamic, 2:rsv, 3:mimo enable
-		UINT32     AmsduSize:1;	// 0:3839, 1:7935 bytes. UINT  MSDUSizeToBytes[]	= { 3839, 7935};
-		UINT32     AmsduEnable:1;	//Enable AMSDU transmisstion
-		UINT32		MpduDensity:3;
-		UINT32		Policy:2;	// 0: DELAY_BA 1:IMMED_BA  (//BA Policy subfiled value in ADDBA frame)   2:BA-not use
-		UINT32		AutoBA:1;	// automatically BA
-		UINT32		TxBAWinLimit:8;
-		UINT32		RxBAWinLimit:8;
-	}	field;
-#else
 	struct	{
 		UINT32		RxBAWinLimit:8;
 		UINT32		TxBAWinLimit:8;
@@ -1596,10 +1621,8 @@
 		UINT32       	b2040CoexistScanSup:1;		//As Sta, support do 2040 coexistence scan for AP. As Ap, support monitor trigger event to check if can use BW 40MHz.
 		UINT32       	:4;
 	}	field;
-#endif
 	UINT32			word;
 } BACAP_STRUC, *PBACAP_STRUC;
-#endif // DOT11_N_SUPPORT //
 
 //This structure is for all 802.11n card InterOptibilityTest action. Reset all Num every n second.  (Details see MLMEPeriodic)
 typedef	struct	_IOT_STRUC	{
@@ -1614,30 +1637,15 @@
 	UCHAR			RTSShortProt;
 	UCHAR			RTSLongProt;
 	BOOLEAN			bRTSLongProtOn;
-#ifdef CONFIG_STA_SUPPORT
 	BOOLEAN			bLastAtheros;
     BOOLEAN			bCurrentAtheros;
     BOOLEAN         bNowAtherosBurstOn;
 	BOOLEAN			bNextDisableRxBA;
     BOOLEAN			bToggle;
-#endif // CONFIG_STA_SUPPORT //
 } IOT_STRUC, *PIOT_STRUC;
 
 // This is the registry setting for 802.11n transmit setting.  Used in advanced page.
 typedef union _REG_TRANSMIT_SETTING {
-#ifdef RT_BIG_ENDIAN
- struct {
-         UINT32  rsv:13;
-		 UINT32  EXTCHA:2;
-		 UINT32  HTMODE:1;
-		 UINT32  TRANSNO:2;
-		 UINT32  STBC:1; //SPACE
-		 UINT32  ShortGI:1;
-		 UINT32  BW:1; //channel bandwidth 20MHz or 40 MHz
-		 UINT32  TxBF:1; // 3*3
-		 UINT32  rsv0:10;
-    } field;
-#else
  struct {
 		 UINT32  rsv0:10;
 		 UINT32  TxBF:1;
@@ -1649,26 +1657,16 @@
          UINT32  EXTCHA:2;
          UINT32  rsv:13;
     } field;
-#endif
  UINT32   word;
 } REG_TRANSMIT_SETTING, *PREG_TRANSMIT_SETTING;
 
 typedef union  _DESIRED_TRANSMIT_SETTING {
-#ifdef RT_BIG_ENDIAN
-	struct	{
-			USHORT		rsv:3;
-			USHORT		FixedTxMode:2;			// If MCS isn't AUTO, fix rate in CCK, OFDM or HT mode.
-			USHORT		PhyMode:4;
-			USHORT   	MCS:7;                 // MCS
-	}	field;
-#else
 	struct	{
 			USHORT   	MCS:7;                 	// MCS
 			USHORT		PhyMode:4;
 			USHORT	 	FixedTxMode:2;			// If MCS isn't AUTO, fix rate in CCK, OFDM or HT mode.
 			USHORT		rsv:3;
 	}	field;
-#endif
 	USHORT		word;
  } DESIRED_TRANSMIT_SETTING, *PDESIRED_TRANSMIT_SETTING;
 
@@ -1707,6 +1705,19 @@
 		UCHAR bit_offset = wcid & 0x7; \
 		ad_p->ApCfg.MBSSID[apidx].TimBitmaps[tim_offset] |= BIT8[bit_offset]; }
 
+#ifdef RT2870
+#define BEACON_BITMAP_MASK		0xff
+typedef struct _BEACON_SYNC_STRUCT_
+{
+	UCHAR        			BeaconBuf[HW_BEACON_MAX_COUNT][HW_BEACON_OFFSET];
+	UCHAR					BeaconTxWI[HW_BEACON_MAX_COUNT][TXWI_SIZE];
+	ULONG 					TimIELocationInBeacon[HW_BEACON_MAX_COUNT];
+	ULONG					CapabilityInfoLocationInBeacon[HW_BEACON_MAX_COUNT];
+	BOOLEAN					EnableBeacon;		// trigger to enable beacon transmission.
+	UCHAR					BeaconBitMap;		// NOTE: If the MAX_MBSSID_NUM is larger than 8, this parameter need to change.
+	UCHAR					DtimBitOn;			// NOTE: If the MAX_MBSSID_NUM is larger than 8, this parameter need to change.
+}BEACON_SYNC_STRUCT;
+#endif // RT2870 //
 
 typedef struct _MULTISSID_STRUCT {
 	UCHAR								Bssid[MAC_ADDR_LEN];
@@ -1813,17 +1824,6 @@
 	UCHAR					BcnBufIdx;
 } MULTISSID_STRUCT, *PMULTISSID_STRUCT;
 
-
-
-#ifdef DOT11N_DRAFT3
-typedef enum _BSS2040COEXIST_FLAG{
-	BSS_2040_COEXIST_DISABLE = 0,
-	BSS_2040_COEXIST_TIMER_FIRED  = 1,
-	BSS_2040_COEXIST_INFO_SYNC = 2,
-	BSS_2040_COEXIST_INFO_NOTIFY = 4,
-}BSS2040COEXIST_FLAG;
-#endif // DOT11N_DRAFT3 //
-
 // configuration common to OPMODE_AP as well as OPMODE_STA
 typedef struct _COMMON_CONFIG {
 
@@ -1886,10 +1886,9 @@
 	ULONG       TxPowerPercentage;      // 0~100 %
 	ULONG       TxPowerDefault;         // keep for TxPowerPercentage
 
-#ifdef DOT11_N_SUPPORT
 	BACAP_STRUC        BACapability; //   NO USE = 0XFF  ;  IMMED_BA =1  ;  DELAY_BA=0
 	BACAP_STRUC        REGBACapability; //   NO USE = 0XFF  ;  IMMED_BA =1  ;  DELAY_BA=0
-#endif // DOT11_N_SUPPORT //
+
 	IOT_STRUC		IOTestParm;	// 802.11n InterOpbility Test Parameter;
 	ULONG       TxPreamble;             // Rt802_11PreambleLong, Rt802_11PreambleShort, Rt802_11PreambleAuto
 	BOOLEAN     bUseZeroToDisableFragment;     // Microsoft use 0 as disable
@@ -1901,17 +1900,14 @@
 	BOOLEAN     bIEEE80211H;			// 1: enable IEEE802.11h spec.
 	ULONG		DisableOLBCDetect;		// 0: enable OLBC detect; 1 disable OLBC detect
 
-#ifdef DOT11_N_SUPPORT
 	BOOLEAN				bRdg;
-#endif // DOT11_N_SUPPORT //
+
 	BOOLEAN             bWmmCapable;        // 0:disable WMM, 1:enable WMM
 	QOS_CAPABILITY_PARM APQosCapability;    // QOS capability of the current associated AP
 	EDCA_PARM           APEdcaParm;         // EDCA parameters of the current associated AP
 	QBSS_LOAD_PARM      APQbssLoad;         // QBSS load of the current associated AP
 	UCHAR               AckPolicy[4];       // ACK policy of the specified AC. see ACK_xxx
-#ifdef CONFIG_STA_SUPPORT
 	BOOLEAN				bDLSCapable;		// 0:disable DLS, 1:enable DLS
-#endif // CONFIG_STA_SUPPORT //
 	// a bitmap of BOOLEAN flags. each bit represent an operation status of a particular
 	// BOOLEAN control, either ON or OFF. These flags should always be accessed via
 	// OPSTATUS_TEST_FLAG(), OPSTATUS_SET_FLAG(), OP_STATUS_CLEAR_FLAG() macros.
@@ -1920,15 +1916,13 @@
 
 	BOOLEAN				NdisRadioStateOff; //For HCT 12.0, set this flag to TRUE instead of called MlmeRadioOff.
 	ABGBAND_STATE		BandState;		// For setting BBP used on B/G or A mode.
+#ifdef RT30xx
+	BOOLEAN				bRxAntDiversity; // 0:disable, 1:enable Software Rx Antenna Diversity.
+#endif
 
 	// IEEE802.11H--DFS.
 	RADAR_DETECT_STRUCT	RadarDetect;
 
-#ifdef CARRIER_DETECTION_SUPPORT
-	CARRIER_DETECTION		CarrierDetect;
-#endif // CARRIER_DETECTION_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
 	// HT
 	UCHAR			BASize;		// USer desired BAWindowSize. Should not exceed our max capability
 	//RT_HT_CAPABILITY	SupportedHtPhy;
@@ -1939,33 +1933,6 @@
 	//This IE is included in channel switch ammouncement frames 7.4.1.5, beacons, probe Rsp.
 	NEW_EXT_CHAN_IE	NewExtChanOffset;	//7.3.2.20A, 1 if extension channel is above the control channel, 3 if below, 0 if not present
 
-#ifdef DOT11N_DRAFT3
-	UCHAR					Bss2040CoexistFlag;		// bit 0: bBssCoexistTimerRunning, bit 1: NeedSyncAddHtInfo.
-	RALINK_TIMER_STRUCT	Bss2040CoexistTimer;
-
-	//This IE is used for 20/40 BSS Coexistence.
-	BSS_2040_COEXIST_IE		BSS2040CoexistInfo;
-	// ====== 11n D3.0 =======================>
-	USHORT					Dot11OBssScanPassiveDwell;				// Unit : TU. 5~1000
-	USHORT					Dot11OBssScanActiveDwell;				// Unit : TU. 10~1000
-	USHORT					Dot11BssWidthTriggerScanInt;			// Unit : Second
-	USHORT					Dot11OBssScanPassiveTotalPerChannel;	// Unit : TU. 200~10000
-	USHORT					Dot11OBssScanActiveTotalPerChannel;	// Unit : TU. 20~10000
-	USHORT					Dot11BssWidthChanTranDelayFactor;
-	USHORT					Dot11OBssScanActivityThre;				// Unit : percentage
-
-	ULONG					Dot11BssWidthChanTranDelay;			// multiple of (Dot11BssWidthTriggerScanInt * Dot11BssWidthChanTranDelayFactor)
-	ULONG					CountDownCtr;	// CountDown Counter from (Dot11BssWidthTriggerScanInt * Dot11BssWidthChanTranDelayFactor)
-
-	NDIS_SPIN_LOCK          TriggerEventTabLock;
-	BSS_2040_COEXIST_IE		LastBSSCoexist2040;
-	BSS_2040_COEXIST_IE		BSSCoexist2040;
-	TRIGGER_EVENT_TAB		TriggerEventTab;
-	UCHAR					ChannelListIdx;
-	// <====== 11n D3.0 =======================
-	BOOLEAN					bOverlapScanning;
-#endif // DOT11N_DRAFT3 //
-
     BOOLEAN                 bHTProtect;
     BOOLEAN                 bMIMOPSEnable;
     BOOLEAN					bBADecline;
@@ -1976,7 +1943,6 @@
 	ULONG					LastRcvBSSWidthTriggerEventsTime;
 
 	UCHAR					TxBASize;
-#endif // DOT11_N_SUPPORT //
 
 	// Enable wireless event
 	BOOLEAN				bWirelessEvent;
@@ -1994,6 +1960,20 @@
 
 	BOOLEAN     		bHardwareRadio;     // Hardware controlled Radio enabled
 
+#ifdef RT2870
+	BOOLEAN     		bMultipleIRP;       // Multiple Bulk IN flag
+	UCHAR       		NumOfBulkInIRP;     // if bMultipleIRP == TRUE, NumOfBulkInIRP will be 4 otherwise be 1
+ 	RT_HT_CAPABILITY	SupportedHtPhy;
+	ULONG				MaxPktOneTxBulk;
+	UCHAR				TxBulkFactor;
+	UCHAR				RxBulkFactor;
+
+	BEACON_SYNC_STRUCT	*pBeaconSync;
+	RALINK_TIMER_STRUCT	BeaconUpdateTimer;
+	UINT32				BeaconAdjust;
+	UINT32				BeaconFactor;
+	UINT32				BeaconRemain;
+#endif // RT2870 //
 
 
  	NDIS_SPIN_LOCK			MeasureReqTabLock;
@@ -2006,16 +1986,8 @@
 #ifdef MCAST_RATE_SPECIFIC
 	HTTRANSMIT_SETTING		MCastPhyMode;
 #endif // MCAST_RATE_SPECIFIC //
-
-#ifdef SINGLE_SKU
-	UINT16					DefineMaxTxPwr;
-#endif // SINGLE_SKU //
-
-
 } COMMON_CONFIG, *PCOMMON_CONFIG;
 
-
-#ifdef CONFIG_STA_SUPPORT
 /* Modified by Wu Xi-Kun 4/21/2006 */
 // STA configuration and status
 typedef struct _STA_ADMIN_CONFIG {
@@ -2103,11 +2075,11 @@
 	BOOLEAN     bRadio;             // Radio state, And of Sw & Hw radio state
 	BOOLEAN     bHardwareRadio;     // Hardware controlled Radio enabled
 	BOOLEAN     bShowHiddenSSID;    // Show all known SSID in SSID list get operation
-
+#ifdef RT2860
     BOOLEAN		AdhocBOnlyJoined;	// Indicate Adhoc B Join.
     BOOLEAN		AdhocBGJoined;		// Indicate Adhoc B/G Join.
     BOOLEAN		Adhoc20NJoined;		// Indicate Adhoc 20MHz N Join.
-
+#endif
 	// New for WPA, windows want us to to keep association information and
 	// Fixed IEs from last association response
 	NDIS_802_11_ASSOCIATION_INFORMATION     AssocInfo;
@@ -2189,10 +2161,6 @@
 	UCHAR           	DtimCount;      // 0.. DtimPeriod-1
 	UCHAR           	DtimPeriod;     // default = 3
 
-#ifdef QOS_DLS_SUPPORT
-	RT_802_11_DLS		DLSEntry[MAX_NUM_OF_DLS_ENTRY];
-	UCHAR				DlsReplayCounter[8];
-#endif // QOS_DLS_SUPPORT //
 	////////////////////////////////////////////////////////////////////////////////////////
 	// This is only for WHQL test.
 	BOOLEAN				WhqlTest;
@@ -2203,7 +2171,6 @@
 	BOOLEAN		        bFastRoaming;       // 0:disable fast roaming, 1:enable fast roaming
 	CHAR		        dBmToRoam;          // the condition to roam when receiving Rssi less than this value. It's negative value.
 
-#ifdef WPA_SUPPLICANT_SUPPORT
     BOOLEAN             IEEE8021X;
     BOOLEAN             IEEE8021x_required_keys;
     CIPHER_KEY	        DesireSharedKey[4];	// Record user desired WEP keys
@@ -2214,7 +2181,6 @@
     // 2: driver takes care of scanning, AP selection, and IEEE 802.11 association parameters
     UCHAR               WpaSupplicantUP;
 	UCHAR				WpaSupplicantScanCount;
-#endif // WPA_SUPPLICANT_SUPPORT //
 
     CHAR                dev_name[16];
     USHORT              OriDevType;
@@ -2227,13 +2193,9 @@
 	RT_HT_PHY_INFO					DesiredHtPhyInfo;
 	BOOLEAN							bAutoTxRateSwitch;
 
+#ifdef RT2860
     UCHAR       BBPR3;
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-	UCHAR				IEEE80211dClientMode;
-	UCHAR				StaOriCountryCode[3];
-	UCHAR				StaOriGeography;
-#endif // EXT_BUILD_CHANNEL_LIST //
+#endif
 } STA_ADMIN_CONFIG, *PSTA_ADMIN_CONFIG;
 
 // This data structure keep the current active BSS/IBSS's configuration that this STA
@@ -2259,7 +2221,15 @@
 	RT_HT_PHY_INFO		SupportedPhyInfo;
 	RT_HT_CAPABILITY	SupportedHtPhy;
 } STA_ACTIVE_CONFIG, *PSTA_ACTIVE_CONFIG;
-#endif // CONFIG_STA_SUPPORT //
+
+#ifdef RT2870
+// for USB interface, avoid in interrupt when write key
+typedef struct   RT_ADD_PAIRWISE_KEY_ENTRY {
+        NDIS_802_11_MAC_ADDRESS         MacAddr;
+        USHORT                          MacTabMatchWCID;        // ASIC
+        CIPHER_KEY                      CipherKey;
+} RT_ADD_PAIRWISE_KEY_ENTRY,*PRT_ADD_PAIRWISE_KEY_ENTRY;
+#endif // RT2870 //
 
 // ----------- start of AP --------------------------
 // AUTH-RSP State Machine Aux data structure
@@ -2325,14 +2295,11 @@
 
 	UINT32			StaConnectTime;		// the live time of this station since associated with AP
 
-
-#ifdef DOT11_N_SUPPORT
 	BOOLEAN			bSendBAR;
 	USHORT			NoBADataCountDown;
 
 	UINT32   		CachedBuf[16];		// UINT (4 bytes) for alignment
 	UINT			TxBFCount; // 3*3
-#endif // DOT11_N_SUPPORT //
 	UINT			FIFOCount;
 	UINT			DebugFIFOCount;
 	UINT			DebugTxCount;
@@ -2356,14 +2323,6 @@
 	UCHAR           TxRateUpPenalty;      // extra # of second penalty due to last unstable condition
 //====================================================
 
-
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-	UINT			MatchDlsEntryIdx; // indicate the index in pAd->StaCfg.DLSEntry
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
 	BOOLEAN         fNoisyEnvironment;
 	BOOLEAN			fLastSecAccordingRSSI;
 	UCHAR           LastSecTxRateChangeAction; // 0: no change, 1:rate UP, 2:rate down
@@ -2377,10 +2336,8 @@
 	// see fOP_STATUS_xxx in RTMP_DEF.C for detail bit definition. fCLIENT_STATUS_AMSDU_INUSED
 	ULONG           ClientStatusFlags;
 
-	// TODO: Shall we move that to DOT11_N_SUPPORT???
 	HTTRANSMIT_SETTING	HTPhyMode, MaxHTPhyMode, MinHTPhyMode;// For transmit phy setting in TXWI.
 
-#ifdef DOT11_N_SUPPORT
 	// HT EWC MIMO-N used parameters
 	USHORT		RXBAbitmap;	// fill to on-chip  RXWI_BA_BITMASK in 8.1.3RX attribute entry format
 	USHORT		TXBAbitmap;	// This bitmap as originator, only keep in software used to mark AMPDU bit in TXWI
@@ -2398,11 +2355,6 @@
 
 	HT_CAPABILITY_IE		HTCapability;
 
-#ifdef DOT11N_DRAFT3
-	UCHAR		BSS2040CoexistenceMgmtSupport;
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
 	BOOLEAN		bAutoTxRateSwitch;
 
 	UCHAR       RateLen;
@@ -2416,6 +2368,9 @@
 	UINT32			TXMCSSuccessful[16];
 	UINT32			TXMCSFailed[16];
 	UINT32			TXMCSAutoFallBack[16][16];
+#ifdef RT2870
+	ULONG   		LastBeaconRxTime;
+#endif
 } MAC_TABLE_ENTRY, *PMAC_TABLE_ENTRY;
 
 typedef struct _MAC_TABLE {
@@ -2427,16 +2382,16 @@
 	BOOLEAN         fAnyStationInPsm;
 	BOOLEAN         fAnyStationBadAtheros;	// Check if any Station is atheros 802.11n Chip.  We need to use RTS/CTS with Atheros 802,.11n chip.
 	BOOLEAN			fAnyTxOPForceDisable;	// Check if it is necessary to disable BE TxOP
-#ifdef DOT11_N_SUPPORT
+#ifdef RT2870
+	BOOLEAN			fAllStationAsRalink; 	// Check if all stations are ralink-chipset
+#endif
 	BOOLEAN         fAnyStationIsLegacy;	// Check if I use legacy rate to transmit to my BSS Station/
 	BOOLEAN         fAnyStationNonGF;		// Check if any Station can't support GF.
 	BOOLEAN         fAnyStation20Only;		// Check if any Station can't support GF.
 	BOOLEAN			fAnyStationMIMOPSDynamic; // Check if any Station is MIMO Dynamic
 	BOOLEAN         fAnyBASession;   // Check if there is BA session.  Force turn on RTS/CTS
-#endif // DOT11_N_SUPPORT //
 } MAC_TABLE, *PMAC_TABLE;
 
-#ifdef DOT11_N_SUPPORT
 #define IS_HT_STA(_pMacEntry)	\
 	(_pMacEntry->MaxHTPhyMode.field.MODE >= MODE_HTMIX)
 
@@ -2445,7 +2400,6 @@
 
 #define PEER_IS_HT_RATE(_pMacEntry)	\
 	(_pMacEntry->HTPhyMode.field.MODE >= MODE_HTMIX)
-#endif // DOT11_N_SUPPORT //
 
 typedef struct _WDS_ENTRY {
 	BOOLEAN         Valid;
@@ -2549,10 +2503,6 @@
 	UCHAR       	SNonce[32];         // SNonce for WPA-PSK
 	UCHAR			GNonce[32];			// GNonce for WPA-PSK from authenticator
 
-#ifdef WSC_AP_SUPPORT
-	WSC_CTRL	           WscControl;
-#endif // WSC_AP_SUPPORT //
-
 	HTTRANSMIT_SETTING				HTPhyMode, MaxHTPhyMode, MinHTPhyMode;
 	RT_HT_PHY_INFO					DesiredHtPhyInfo;
 	BOOLEAN							bAutoTxRateSwitch;
@@ -2561,14 +2511,6 @@
 
 // ----------- end of AP ----------------------------
 
-#ifdef BLOCK_NET_IF
-typedef struct _BLOCK_QUEUE_ENTRY
-{
-	BOOLEAN SwTxQueueBlockFlag;
-	LIST_HEADER NetIfList;
-} BLOCK_QUEUE_ENTRY, *PBLOCK_QUEUE_ENTRY;
-#endif // BLOCK_NET_IF //
-
 struct wificonf
 {
 	BOOLEAN	bShortGI;
@@ -2600,28 +2542,6 @@
 	};
 #endif // IKANOS_VX_1X0 //
 
-#ifdef NINTENDO_AP
-typedef struct _NINDO_CTRL_BLOCK {
-
-	RT_NINTENDO_TABLE	DS_TABLE;
-
-#ifdef CHIP25XX
-	spinlock_t			NINTENDO_TABLE_Lock;
-#else
-	NDIS_SPIN_LOCK		NINTENDO_TABLE_Lock;
-#endif // CHIP25XX //
-
-	UCHAR				NINTENDO_UP_BUFFER[512];
-	UCHAR				Local_KeyIdx;
-	CIPHER_KEY			Local_SharedKey;
-	UCHAR				Local_bHideSsid;
-	UCHAR				Local_AuthMode;
-	UCHAR				Local_WepStatus;
-	USHORT				Local_CapabilityInfo;
-} NINDO_CTRL_BLOCK;
-#endif // NINTENDO_AP //
-
-
 #ifdef DBG_DIAGNOSE
 #define DIAGNOSE_TIME	10   // 10 sec
 typedef struct _RtmpDiagStrcut_
@@ -2660,6 +2580,7 @@
 	PNET_DEV				net_dev;
 	ULONG					VirtualIfCnt;
 
+#ifdef RT2860
     USHORT		            LnkCtrlBitMask;
     USHORT		            RLnkCtrlConfiguration;
     USHORT                  RLnkCtrlOffset;
@@ -2686,11 +2607,51 @@
 	RTMP_DMABUF             RxDescRing;                 // Shared memory for RX descriptors
 	RTMP_DMABUF             TxDescRing[NUM_OF_TX_RING]; 	// Shared memory for Tx descriptors
 	RTMP_TX_RING            TxRing[NUM_OF_TX_RING];     	// AC0~4 + HCCA
-
+#endif
 
 	NDIS_SPIN_LOCK          irq_lock;
 	UCHAR                   irq_disabled;
 
+#ifdef RT2870
+/*****************************************************************************************/
+/*      USB related parameters                                                           */
+/*****************************************************************************************/
+	struct usb_config_descriptor		*config;
+	UINT								BulkInEpAddr;		// bulk-in endpoint address
+	UINT								BulkOutEpAddr[6];	// bulk-out endpoint address
+
+	UINT								NumberOfPipes;
+	USHORT								BulkOutMaxPacketSize;
+	USHORT								BulkInMaxPacketSize;
+
+	//======Control Flags
+	LONG                    	PendingIoCount;
+	ULONG						BulkFlags;
+	BOOLEAN                     bUsbTxBulkAggre;	// Flags for bulk out data priority
+
+
+	//======Timer Thread
+	RT2870_TIMER_QUEUE		TimerQ;
+	NDIS_SPIN_LOCK			TimerQLock;
+
+
+	//======Cmd Thread
+	CmdQ					CmdQ;
+	NDIS_SPIN_LOCK			CmdQLock;				// CmdQLock spinlock
+
+	BOOLEAN					TimerFunc_kill;
+	BOOLEAN					mlme_kill;
+
+
+	//======Semaphores (event)
+	struct semaphore			mlme_semaphore;			/* to sleep thread on	*/
+	struct semaphore			RTUSBCmd_semaphore;		/* to sleep thread on	*/
+	struct semaphore			RTUSBTimer_semaphore;
+	struct completion			TimerQComplete;
+	struct completion			mlmeComplete;
+	struct completion			CmdQComplete;
+	wait_queue_head_t			*wait;
+#endif // RT2870 //
 
 
 /*****************************************************************************************/
@@ -2704,6 +2665,22 @@
 	BOOLEAN                 DeQueueRunning[NUM_OF_TX_RING];  // for ensuring RTUSBDeQueuePacket get call once
 	NDIS_SPIN_LOCK          DeQueueLock[NUM_OF_TX_RING];
 
+#ifdef RT2870
+	// Data related context and AC specified, 4 AC supported
+	NDIS_SPIN_LOCK			BulkOutLock[6];			// BulkOut spinlock for 4 ACs
+	NDIS_SPIN_LOCK			MLMEBulkOutLock;	// MLME BulkOut lock
+
+	HT_TX_CONTEXT			TxContext[NUM_OF_TX_RING];
+	NDIS_SPIN_LOCK			TxContextQueueLock[NUM_OF_TX_RING];		// TxContextQueue spinlock
+
+	// 4 sets of Bulk Out index and pending flag
+	UCHAR					NextBulkOutIndex[4];	// only used for 4 EDCA bulkout pipe
+
+	BOOLEAN					BulkOutPending[6];	// used for total 6 bulkout pipe
+	UCHAR					bulkResetPipeid;
+	BOOLEAN					MgmtBulkPending;
+	ULONG					bulkResetReq[6];
+#endif // RT2870 //
 
 	// resource for software backlog queues
 	QUEUE_HEADER            TxSwQueue[NUM_OF_TX_RING];  // 4 AC + 1 HCCA
@@ -2717,10 +2694,20 @@
 /*****************************************************************************************/
 /*      Rx related parameters                                                           */
 /*****************************************************************************************/
-
+#ifdef RT2860
 	RTMP_RX_RING            RxRing;
 	NDIS_SPIN_LOCK          RxRingLock;                 // Rx Ring spinlock
-
+#endif
+#ifdef RT2870
+	RX_CONTEXT				RxContext[RX_RING_SIZE];  // 1 for redundant multiple IRP bulk in.
+	NDIS_SPIN_LOCK			BulkInLock;				// BulkIn spinlock for 4 ACs
+	UCHAR					PendingRx;				// The Maxima pending Rx value should be 	RX_RING_SIZE.
+	UCHAR					NextRxBulkInIndex;		// Indicate the current RxContext Index which hold by Host controller.
+	UCHAR					NextRxBulkInReadIndex;	// Indicate the current RxContext Index which driver can read & process it.
+	ULONG					NextRxBulkInPosition;   // Want to contatenate 2 URB buffer while 1st is bulkin failed URB. This Position is 1st URB TransferLength.
+	ULONG					TransferBufferLength;	// current length of the packet buffer
+	ULONG					ReadPosition;			// current read position in a packet buffer
+#endif // RT2870 //
 
 
 /*****************************************************************************************/
@@ -2734,6 +2721,10 @@
 	ULONG                   EepromVersion;          // byte 0: version, byte 1: revision, byte 2~3: unused
 	UCHAR                   EEPROMAddressNum;       // 93c46=6  93c66=8
 	USHORT                  EEPROMDefaultValue[NUM_EEPROM_BBP_PARMS];
+#ifdef RT30xx
+	BOOLEAN                 EepromAccess;
+	UCHAR                   EFuseTag;
+#endif
 	ULONG                   FirmwareVersion;        // byte 0: Minor version, byte 1: Major version, otherwise unused.
 
 	// ---------------------------
@@ -2826,11 +2817,19 @@
 	PSPOLL_FRAME            	PsPollFrame;
 	HEADER_802_11           	NullFrame;
 
+#ifdef RT2870
+	TX_CONTEXT				BeaconContext[BEACON_RING_SIZE];
+	TX_CONTEXT				NullContext;
+	TX_CONTEXT				PsPollContext;
+	TX_CONTEXT				RTSContext;
+#endif // RT2870 //
+
+
+
 //=========AP===========
 
 
 //=======STA===========
-#ifdef CONFIG_STA_SUPPORT
 /* Modified by Wu Xi-Kun 4/21/2006 */
 	// -----------------------------------------------
 	// STA specific configuration & operation status
@@ -2840,7 +2839,6 @@
 	STA_ACTIVE_CONFIG       StaActive;         // valid only when ADHOC_ON(pAd) || INFRA_ON(pAd)
 	CHAR                    nickname[IW_ESSID_MAX_SIZE+1]; // nickname, only used in the iwconfig i/f
 	NDIS_MEDIA_STATE        PreMediaState;
-#endif // CONFIG_STA_SUPPORT //
 
 //=======Common===========
 	// OP mode: either AP or STA
@@ -2848,7 +2846,6 @@
 
 	NDIS_MEDIA_STATE        IndicateMediaState;			// Base on Indication state, default is NdisMediaStateDisConnected
 
-	// MAT related parameters
 
 	// configuration: read from Registry & E2PROM
 	BOOLEAN                 bLocalAdminMAC;             // Use user changed MAC
@@ -2869,9 +2866,8 @@
 	MAC_TABLE                 MacTab;     // ASIC on-chip WCID entry table.  At TX, ASIC always use key according to this on-chip table.
 	NDIS_SPIN_LOCK          MacTabLock;
 
-#ifdef DOT11_N_SUPPORT
 	BA_TABLE			BATable;
-#endif // DOT11_N_SUPPORT //
+
 	NDIS_SPIN_LOCK          BATabLock;
 	RALINK_TIMER_STRUCT RECBATimer;
 
@@ -2890,16 +2886,13 @@
 
 	// flags, see fRTMP_ADAPTER_xxx flags
 	ULONG                   Flags;                      // Represent current device status
+#ifdef RT2860
 	ULONG                   PSFlags;                    // Power Save operation flag.
+#endif
 
 	// current TX sequence #
 	USHORT                  Sequence;
 
-#ifdef UNDER_CE
-	NDIS_HANDLE             hGiISR;
-#endif
-
-
 	// Control disconnect / connect event generation
 	//+++Didn't used anymore
 	ULONG                   LinkDownTime;
@@ -2928,6 +2921,14 @@
 	/*****************************************************************************************/
 	/*      Statistic related parameters                                                     */
 	/*****************************************************************************************/
+#ifdef RT2870
+	ULONG						BulkOutDataOneSecCount;
+	ULONG						BulkInDataOneSecCount;
+	ULONG						BulkLastOneSecCount; // BulkOutDataOneSecCount + BulkInDataOneSecCount
+	ULONG						watchDogRxCnt;
+	ULONG						watchDogRxOverFlowCnt;
+	ULONG						watchDogTxPendingCnt[NUM_OF_TX_RING];
+#endif // RT2870 //
 
 	BOOLEAN						bUpdateBcnCntDone;
 	ULONG						watchDogMacDeadlock;	// prevent MAC/BBP into deadlock condition
@@ -2967,13 +2968,7 @@
 
     struct wificonf			WIFItestbed;
 
-#ifdef RALINK_ATE
-	ATE_INFO				ate;
-#endif // RALINK_ATE //
-
-#ifdef DOT11_N_SUPPORT
 	struct reordering_mpdu_pool mpdu_blk_pool;
-#endif // DOT11_N_SUPPORT //
 
 	ULONG					OneSecondnonBEpackets;		// record non BE packets per second
 
@@ -2983,17 +2978,6 @@
 
 	struct net_device_stats	stats;
 
-#ifdef BLOCK_NET_IF
-	BLOCK_QUEUE_ENTRY		blockQueueTab[NUM_OF_TX_RING];
-#endif // BLOCK_NET_IF //
-
-
-
-#ifdef MULTIPLE_CARD_SUPPORT
-	INT32					MC_RowID;
-	UCHAR					MC_FileName[256];
-#endif // MULTIPLE_CARD_SUPPORT //
-
 	ULONG					TbttTickCount;
 #ifdef PCI_MSI_SUPPORT
 	BOOLEAN					HaveMsi;
@@ -3007,11 +2991,6 @@
 	UCHAR					flg_be_adjust;
 	ULONG					be_adjust_last_time;
 
-#ifdef NINTENDO_AP
-	NINDO_CTRL_BLOCK		nindo_ctrl_block;
-#endif // NINTENDO_AP //
-
-
 #ifdef IKANOS_VX_1X0
 	struct IKANOS_TX_INFO	IkanosTxInfo;
 	struct IKANOS_TX_INFO	IkanosRxInfo[MAX_MBSSID_NUM + MAX_WDS_ENTRY + MAX_APCLI_NUM + MAX_MESH_NUM];
@@ -3024,6 +3003,13 @@
 
 
 	UINT8					PM_FlgSuspend;
+
+#ifdef RT30xx
+//======efuse
+	BOOLEAN		bUseEfuse;
+	BOOLEAN		bEEPROMFile;
+#endif // RT30xx //
+
 } RTMP_ADAPTER, *PRTMP_ADAPTER;
 
 //
@@ -3176,7 +3162,7 @@
 
 //------------------------------------------------------------------------------------------
 
-
+#ifdef RT2860
 //
 // Enable & Disable NIC interrupt via writing interrupt mask register
 // Since it use ADAPTER structure, it have to be put after structure definition.
@@ -3210,243 +3196,6 @@
 	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_ACTIVE);
 }
 
-#ifdef RT_BIG_ENDIAN
-static inline VOID	WriteBackToDescriptor(
-	IN  PUCHAR			Dest,
- 	IN	PUCHAR			Src,
-    IN  BOOLEAN			DoEncrypt,
-	IN  ULONG           DescriptorType)
-{
-	UINT32 *p1, *p2;
-
-	p1 = ((UINT32 *)Dest);
-	p2 = ((UINT32 *)Src);
-
-	*p1 = *p2;
-	*(p1+2) = *(p2+2);
-	*(p1+3) = *(p2+3);
-	*(p1+1) = *(p2+1); // Word 1; this must be written back last
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Endian conversion of Tx/Rx descriptor .
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pData			Pointer to Tx/Rx descriptor
-		DescriptorType	Direction of the frame
-
-	Return Value:
-		None
-
-	Note:
-		Call this function when read or update descriptor
-	========================================================================
-*/
-static inline VOID	RTMPWIEndianChange(
-	IN	PUCHAR			pData,
-	IN	ULONG			DescriptorType)
-{
-	int size;
-	int i;
-
-	size = ((DescriptorType == TYPE_TXWI) ? TXWI_SIZE : RXWI_SIZE);
-
-	if(DescriptorType == TYPE_TXWI)
-	{
-		*((UINT32 *)(pData)) = SWAP32(*((UINT32 *)(pData)));		// Byte 0~3
-		*((UINT32 *)(pData + 4)) = SWAP32(*((UINT32 *)(pData+4)));	// Byte 4~7
-	}
-	else
-	{
-		for(i=0; i < size/4 ; i++)
-			*(((UINT32 *)pData) +i) = SWAP32(*(((UINT32 *)pData)+i));
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Endian conversion of Tx/Rx descriptor .
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pData			Pointer to Tx/Rx descriptor
-		DescriptorType	Direction of the frame
-
-	Return Value:
-		None
-
-	Note:
-		Call this function when read or update descriptor
-	========================================================================
-*/
-static inline VOID	RTMPDescriptorEndianChange(
-	IN	PUCHAR			pData,
-	IN	ULONG			DescriptorType)
-{
-	*((UINT32 *)(pData)) = SWAP32(*((UINT32 *)(pData)));		// Byte 0~3
-	*((UINT32 *)(pData + 8)) = SWAP32(*((UINT32 *)(pData+8)));	// Byte 8~11
-	*((UINT32 *)(pData +12)) = SWAP32(*((UINT32 *)(pData + 12)));	// Byte 12~15
-	*((UINT32 *)(pData + 4)) = SWAP32(*((UINT32 *)(pData + 4)));				// Byte 4~7, this must be swapped last
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Endian conversion of all kinds of 802.11 frames .
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pData			Pointer to the 802.11 frame structure
-		Dir 			Direction of the frame
-		FromRxDoneInt	Caller is from RxDone interrupt
-
-	Return Value:
-		None
-
-	Note:
-		Call this function when read or update buffer data
-	========================================================================
-*/
-static inline VOID	RTMPFrameEndianChange(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pData,
-	IN	ULONG			Dir,
-	IN	BOOLEAN 		FromRxDoneInt)
-{
-	PHEADER_802_11 pFrame;
-	PUCHAR	pMacHdr;
-
-	// swab 16 bit fields - Frame Control field
-	if(Dir == DIR_READ)
-	{
-		*(USHORT *)pData = SWAP16(*(USHORT *)pData);
-	}
-
-	pFrame = (PHEADER_802_11) pData;
-	pMacHdr = (PUCHAR) pFrame;
-
-	// swab 16 bit fields - Duration/ID field
-	*(USHORT *)(pMacHdr + 2) = SWAP16(*(USHORT *)(pMacHdr + 2));
-
-	// swab 16 bit fields - Sequence Control field
-	*(USHORT *)(pMacHdr + 22) = SWAP16(*(USHORT *)(pMacHdr + 22));
-
-	if(pFrame->FC.Type == BTYPE_MGMT)
-	{
-		switch(pFrame->FC.SubType)
-		{
-			case SUBTYPE_ASSOC_REQ:
-			case SUBTYPE_REASSOC_REQ:
-				// swab 16 bit fields - CapabilityInfo field
-				pMacHdr += sizeof(HEADER_802_11);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - Listen Interval field
-				pMacHdr += 2;
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-
-			case SUBTYPE_ASSOC_RSP:
-			case SUBTYPE_REASSOC_RSP:
-				// swab 16 bit fields - CapabilityInfo field
-				pMacHdr += sizeof(HEADER_802_11);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - Status Code field
-				pMacHdr += 2;
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - AID field
-				pMacHdr += 2;
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-
-			case SUBTYPE_AUTH:
-				// If from APHandleRxDoneInterrupt routine, it is still a encrypt format.
-				// The convertion is delayed to RTMPHandleDecryptionDoneInterrupt.
-				if(!FromRxDoneInt && pFrame->FC.Wep == 1)
-					break;
-				else
-				{
-					// swab 16 bit fields - Auth Alg No. field
-					pMacHdr += sizeof(HEADER_802_11);
-					*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-					// swab 16 bit fields - Auth Seq No. field
-					pMacHdr += 2;
-					*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-					// swab 16 bit fields - Status Code field
-					pMacHdr += 2;
-					*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				}
-				break;
-
-			case SUBTYPE_BEACON:
-			case SUBTYPE_PROBE_RSP:
-				// swab 16 bit fields - BeaconInterval field
-				pMacHdr += (sizeof(HEADER_802_11) + TIMESTAMP_LEN);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - CapabilityInfo field
-				pMacHdr += sizeof(USHORT);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-
-			case SUBTYPE_DEAUTH:
-			case SUBTYPE_DISASSOC:
-				// swab 16 bit fields - Reason code field
-				pMacHdr += sizeof(HEADER_802_11);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-		}
-	}
-	else if( pFrame->FC.Type == BTYPE_DATA )
-	{
-	}
-	else if(pFrame->FC.Type == BTYPE_CNTL)
-	{
-		switch(pFrame->FC.SubType)
-		{
-			case SUBTYPE_BLOCK_ACK_REQ:
-				{
-					PFRAME_BA_REQ pBAReq = (PFRAME_BA_REQ)pFrame;
-					*(USHORT *)(&pBAReq->BARControl) = SWAP16(*(USHORT *)(&pBAReq->BARControl));
-					pBAReq->BAStartingSeq.word = SWAP16(pBAReq->BAStartingSeq.word);
-				}
-				break;
-			case SUBTYPE_BLOCK_ACK:
-				// For Block Ack packet, the HT_CONTROL field is in the same offset with Addr3
-				*(UINT32 *)(&pFrame->Addr3[0]) = SWAP32(*(UINT32 *)(&pFrame->Addr3[0]));
-				break;
-
-			case SUBTYPE_ACK:
-				//For ACK packet, the HT_CONTROL field is in the same offset with Addr2
-				*(UINT32 *)(&pFrame->Addr2[0])=	SWAP32(*(UINT32 *)(&pFrame->Addr2[0]));
-				break;
-		}
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("Invalid Frame Type!!!\n"));
-	}
-
-	// swab 16 bit fields - Frame Control
-	if(Dir == DIR_WRITE)
-	{
-		*(USHORT *)pData = SWAP16(*(USHORT *)pData);
-	}
-}
-#endif // RT_BIG_ENDIAN //
-
-
 static inline VOID ConvertMulticastIP2MAC(
 	IN PUCHAR pIpAddr,
 	IN PUCHAR *ppMacAddr,
@@ -3484,6 +3233,7 @@
 
 	return;
 }
+#endif /* RT2860 */
 
 BOOLEAN RTMPCheckForHang(
 	IN  NDIS_HANDLE MiniportAdapterContext
@@ -3523,6 +3273,10 @@
 	IN  NDIS_HANDLE         WrapperConfigurationContext
 	);
 
+#ifdef RT2870
+VOID NICInitRT30xxRFRegisters(
+	IN PRTMP_ADAPTER pAd);
+#endif // RT2870 //
 
 VOID NICReadEEPROMParameters(
 	IN  PRTMP_ADAPTER       pAd,
@@ -3541,10 +3295,10 @@
 NDIS_STATUS NICInitializeAsic(
 	IN  PRTMP_ADAPTER   pAd,
 	IN  BOOLEAN		bHardReset);
-
+#ifdef RT2860
 VOID NICRestoreBBPValue(
 	IN PRTMP_ADAPTER pAd);
-
+#endif
 VOID NICIssueReset(
 	IN  PRTMP_ADAPTER   pAd);
 
@@ -3691,7 +3445,6 @@
     IN PRTMP_ADAPTER pAd,
     IN MLME_QUEUE_ELEM *Elem);
 
-#ifdef DOT11_N_SUPPORT
 VOID PeerAddBAReqAction(
 	IN PRTMP_ADAPTER pAd,
 	IN MLME_QUEUE_ELEM *Elem);
@@ -3707,53 +3460,12 @@
 VOID PeerBAAction(
     IN PRTMP_ADAPTER pAd,
     IN MLME_QUEUE_ELEM *Elem);
-#endif // DOT11_N_SUPPORT //
 
 VOID SendPSMPAction(
 	IN PRTMP_ADAPTER	pAd,
 	IN UCHAR			Wcid,
 	IN UCHAR			Psmp);
 
-
-#ifdef DOT11N_DRAFT3
-VOID SendBSS2040CoexistMgmtAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR	Wcid,
-	IN	UCHAR	apidx,
-	IN	UCHAR	InfoReq);
-
-VOID SendNotifyBWActionFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR  Wcid,
-	IN UCHAR apidx);
-
-BOOLEAN ChannelSwitchSanityCheck(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  NewChannel,
-	IN    UCHAR  Secondary);
-
-VOID ChannelSwitchAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  Channel,
-	IN    UCHAR  Secondary);
-
-ULONG BuildIntolerantChannelRep(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    PUCHAR  pDest);
-
-VOID Update2040CoexistFrameAndNotify(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha);
-
-VOID Send2040CoexistAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha);
-#endif // DOT11N_DRAFT3 //
-
 VOID PeerRMAction(
 	IN PRTMP_ADAPTER pAd,
 	IN MLME_QUEUE_ELEM *Elem);
@@ -3762,44 +3474,22 @@
 	IN PRTMP_ADAPTER pAd,
 	IN MLME_QUEUE_ELEM *Elem);
 
-#ifdef CONFIG_STA_SUPPORT
 VOID StaPublicAction(
 	IN PRTMP_ADAPTER pAd,
 	IN UCHAR Bss2040Coexist);
-#endif // CONFIG_STA_SUPPORT //
-
 
 VOID PeerBSSTranAction(
 	IN PRTMP_ADAPTER pAd,
 	IN MLME_QUEUE_ELEM *Elem);
 
-#ifdef DOT11_N_SUPPORT
 VOID PeerHTAction(
 	IN PRTMP_ADAPTER pAd,
 	IN MLME_QUEUE_ELEM *Elem);
-#endif // DOT11_N_SUPPORT //
 
 VOID PeerQOSAction(
     IN PRTMP_ADAPTER pAd,
     IN MLME_QUEUE_ELEM *Elem);
 
-#ifdef QOS_DLS_SUPPORT
-VOID PeerDLSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-#endif // QOS_DLS_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-VOID DlsParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_DLS_REQ_STRUCT *pDlsReq,
-	IN PRT_802_11_DLS pDls,
-	IN USHORT reason);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
 VOID RECBATimerTimeout(
     IN PVOID SystemSpecific1,
     IN PVOID FunctionContext,
@@ -3812,7 +3502,6 @@
 VOID SendRefreshBAR(
 	IN	PRTMP_ADAPTER	pAd,
 	IN	MAC_TABLE_ENTRY	*pEntry);
-#endif // DOT11_N_SUPPORT //
 
 VOID ActHeaderInit(
     IN	PRTMP_ADAPTER	pAd,
@@ -3845,7 +3534,6 @@
 	IN USHORT Datasize,
 	IN UINT   CurRxIndex);
 
-#ifdef DOT11_N_SUPPORT
 BOOLEAN CntlEnqueueForRecv(
     IN	PRTMP_ADAPTER	pAd,
 	IN ULONG Wcid,
@@ -3854,7 +3542,6 @@
 
 VOID BaAutoManSwitch(
 	IN	PRTMP_ADAPTER	pAd);
-#endif // DOT11_N_SUPPORT //
 
 VOID HTIOTCheck(
 	IN	PRTMP_ADAPTER	pAd,
@@ -4010,7 +3697,13 @@
 	IN	UCHAR			QueIdx,
 	IN	PUCHAR			pData,
 	IN  UINT            Length);
-
+#ifdef RT2870
+NDIS_STATUS MiniportDataMMRequest(
+	 IN  PRTMP_ADAPTER   pAd,
+	 IN  UCHAR           QueIdx,
+	 IN  PUCHAR          pData,
+	 IN  UINT            Length);
+#endif
 VOID RTMPSendNullFrame(
 	IN  PRTMP_ADAPTER   pAd,
 	IN  UCHAR           TxRate,
@@ -4039,7 +3732,6 @@
 	IN  PRTMP_ADAPTER   pAd,
 	OUT UCHAR           *QueIdx);
 
-#ifdef CONFIG_STA_SUPPORT
 VOID RTMPReportMicError(
 	IN  PRTMP_ADAPTER   pAd,
 	IN  PCIPHER_KEY     pWpaKey);
@@ -4053,7 +3745,6 @@
     IN  PVOID FunctionContext,
     IN  PVOID SystemSpecific2,
     IN  PVOID SystemSpecific3);
-#endif // CONFIG_STA_SUPPORT //
 
 NDIS_STATUS RTMPCloneNdisPacket(
 	IN  PRTMP_ADAPTER   pAd,
@@ -4193,7 +3884,6 @@
 	IN PVOID SystemSpecific2,
 	IN PVOID SystemSpecific3);
 
-#ifdef CONFIG_STA_SUPPORT
 VOID AsicSleepThenAutoWakeup(
 	IN  PRTMP_ADAPTER   pAd,
 	IN  USHORT TbttNumToNextWakeUp);
@@ -4203,8 +3893,12 @@
 
 VOID AsicForceWakeup(
 	IN PRTMP_ADAPTER pAd,
+#ifdef RT2860
 	IN UCHAR    	 Level);
-#endif // CONFIG_STA_SUPPORT //
+#endif
+#ifdef RT2870
+	IN BOOLEAN    bFromTx);
+#endif
 
 VOID AsicSetBssid(
 	IN  PRTMP_ADAPTER   pAd,
@@ -4298,11 +3992,11 @@
 	IN UCHAR         Token,
 	IN UCHAR         Arg0,
 	IN UCHAR         Arg1);
-
+#ifdef RT2860
 BOOLEAN AsicCheckCommanOk(
 	IN PRTMP_ADAPTER pAd,
 	IN UCHAR		 Command);
-
+#endif
 VOID MacAddrRandomBssid(
 	IN  PRTMP_ADAPTER   pAd,
 	OUT PUCHAR pAddr);
@@ -4325,11 +4019,9 @@
 VOID BssTableInit(
 	IN BSS_TABLE *Tab);
 
-#ifdef DOT11_N_SUPPORT
 VOID BATableInit(
 	IN PRTMP_ADAPTER pAd,
     IN BA_TABLE *Tab);
-#endif // DOT11_N_SUPPORT //
 
 ULONG BssTableSearch(
 	IN BSS_TABLE *Tab,
@@ -4355,7 +4047,6 @@
 	IN      PUCHAR pBssid,
 	IN      UCHAR Channel);
 
-#ifdef DOT11_N_SUPPORT
 VOID BATableDeleteORIEntry(
 	IN OUT	PRTMP_ADAPTER pAd,
 	IN		BA_ORI_ENTRY	*pBAORIEntry);
@@ -4376,7 +4067,6 @@
 	IN		UCHAR TID,
 	IN		UCHAR WCID,
 	IN		BOOLEAN ALL);
-#endif // DOT11_N_SUPPORT //
 
 VOID  BssEntrySet(
 	IN  PRTMP_ADAPTER   pAd,
@@ -4438,7 +4128,6 @@
 	IN USHORT LengthVIE,
 	IN PNDIS_802_11_VARIABLE_IEs pVIE);
 
-#ifdef DOT11_N_SUPPORT
 VOID BATableInsertEntry(
     IN	PRTMP_ADAPTER	pAd,
 	IN USHORT Aid,
@@ -4449,31 +4138,6 @@
 	IN UCHAR OriginatorStatus,
     IN BOOLEAN IsRecipient);
 
-#ifdef DOT11N_DRAFT3
-VOID Bss2040CoexistTimeOut(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-
-VOID  TriEventInit(
-	IN	PRTMP_ADAPTER	pAd);
-
-ULONG TriEventTableSetEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT TRIGGER_EVENT_TAB *Tab,
-	IN PUCHAR pBssid,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			RegClass,
-	IN UCHAR ChannelNo);
-
-VOID TriEventCounterMaintenance(
-	IN	PRTMP_ADAPTER	pAd);
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
 VOID BssTableSsidSort(
 	IN  PRTMP_ADAPTER   pAd,
 	OUT BSS_TABLE *OutTab,
@@ -4638,6 +4302,12 @@
 	IN  PRTMP_ADAPTER pAd,
 	IN  MLME_QUEUE_ELEM *Elem);
 
+#ifdef RT2870
+VOID MlmeCntlConfirm(
+	IN PRTMP_ADAPTER pAd,
+	IN ULONG MsgType,
+	IN USHORT Msg);
+#endif // RT2870 //
 
 VOID  ComposePsPoll(
 	IN  PRTMP_ADAPTER   pAd);
@@ -4721,142 +4391,6 @@
 // Private routines in dls.c
 //
 
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-void DlsStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID MlmeDlsReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerDlsReqAction(
-    IN PRTMP_ADAPTER	pAd,
-    IN MLME_QUEUE_ELEM	*Elem);
-
-VOID PeerDlsRspAction(
-    IN PRTMP_ADAPTER	pAd,
-    IN MLME_QUEUE_ELEM	*Elem);
-
-VOID MlmeDlsTearDownAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerDlsTearDownAction(
-    IN PRTMP_ADAPTER	pAd,
-    IN MLME_QUEUE_ELEM	*Elem);
-
-VOID RTMPCheckDLSTimeOut(
-	IN PRTMP_ADAPTER	pAd);
-
-BOOLEAN RTMPRcvFrameDLSCheck(
-	IN PRTMP_ADAPTER	pAd,
-	IN PHEADER_802_11	pHeader,
-	IN ULONG			Len,
-	IN PRT28XX_RXD_STRUC	pRxD);
-
-INT	RTMPCheckDLSFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA);
-
-VOID RTMPSendDLSTearDownFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA);
-
-NDIS_STATUS RTMPSendSTAKeyRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA);
-
-NDIS_STATUS RTMPSendSTAKeyHandShake(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA);
-
-VOID DlsTimeoutAction(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-BOOLEAN MlmeDlsReqSanity(
-	IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PRT_802_11_DLS *pDLS,
-    OUT PUSHORT pReason);
-
-INT Set_DlsEntryInfo_Display_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg);
-
-MAC_TABLE_ENTRY *MacTableInsertDlsEntry(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR	pAddr,
-	IN  UINT	DlsEntryIdx);
-
-BOOLEAN MacTableDeleteDlsEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT wcid,
-	IN PUCHAR pAddr);
-
-MAC_TABLE_ENTRY *DlsEntryTableLookup(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount);
-
-MAC_TABLE_ENTRY *DlsEntryTableLookupByWcid(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR	wcid,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount);
-
-INT	Set_DlsAddEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_DlsTearDownEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef QOS_DLS_SUPPORT
-BOOLEAN PeerDlsReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pDlsTimeout,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-    OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability);
-
-BOOLEAN PeerDlsRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pStatus,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-    OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability);
-
-BOOLEAN PeerDlsTearDownSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pReason);
-#endif // QOS_DLS_SUPPORT //
-
 //========================================
 
 VOID SyncStateMachineInit(
@@ -4961,12 +4495,6 @@
 	IN  PRTMP_ADAPTER   pAd,
 	IN  MLME_QUEUE_ELEM *Elem);
 
-#ifdef QOS_DLS_SUPPORT
-VOID CntlOidDLSSetupProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-#endif // QOS_DLS_SUPPORT //
-
 VOID LinkUp(
 	IN  PRTMP_ADAPTER   pAd,
 	IN  UCHAR BssType);
@@ -5113,9 +4641,7 @@
 	OUT PQOS_CAPABILITY_PARM pQosCapability,
 	OUT ULONG *pRalinkIe,
 	OUT UCHAR		 *pHtCapabilityLen,
-#ifdef CONFIG_STA_SUPPORT
 	OUT UCHAR		 *pPreNHtCapabilityLen,
-#endif // CONFIG_STA_SUPPORT //
 	OUT HT_CAPABILITY_IE *pHtCapability,
 	OUT UCHAR		 *AddHtInfoLen,
 	OUT ADD_HT_INFO_IE *AddHtInfo,
@@ -5343,23 +4869,19 @@
 	IN 	BOOLEAN		 	bLinkUp,
 	IN	UCHAR			apidx);
 
-#ifdef DOT11_N_SUPPORT
 VOID MlmeUpdateHtTxRates(
 	IN PRTMP_ADAPTER 		pAd,
 	IN	UCHAR				apidx);
-#endif // DOT11_N_SUPPORT //
 
 VOID    RTMPCheckRates(
 	IN      PRTMP_ADAPTER   pAd,
 	IN OUT  UCHAR           SupRate[],
 	IN OUT  UCHAR           *SupRateLen);
 
-#ifdef CONFIG_STA_SUPPORT
 BOOLEAN RTMPCheckChannel(
 	IN PRTMP_ADAPTER pAd,
 	IN UCHAR		CentralChannel,
 	IN UCHAR		Channel);
-#endif // CONFIG_STA_SUPPORT //
 
 BOOLEAN 	RTMPCheckHt(
 	IN		PRTMP_ADAPTER	pAd,
@@ -5388,6 +4910,12 @@
 	IN CHAR				Rssi1,
 	IN CHAR				Rssi2);
 
+#ifdef RT30xx
+VOID AsicSetRxAnt(
+	IN PRTMP_ADAPTER	pAd,
+	IN UCHAR			Ant);
+#endif
+
 VOID AsicEvaluateRxAnt(
 	IN PRTMP_ADAPTER	pAd);
 
@@ -5600,15 +5128,12 @@
 VOID	RTMPOPModeSwitching(
 	IN	PRTMP_ADAPTER	pAd);
 
-#ifdef CONFIG_STA_SUPPORT
 VOID    RTMPAddBSSIDCipher(
     IN  PRTMP_ADAPTER   pAd,
 	IN	UCHAR	Aid,
     IN  PNDIS_802_11_KEY    pKey,
     IN  UCHAR   CipherAlg);
-#endif // CONFIG_STA_SUPPORT //
 
-#ifdef DOT11_N_SUPPORT
 VOID	RTMPSetHT(
 	IN	PRTMP_ADAPTER	pAd,
 	IN	OID_SET_HT_PHYMODE *pHTPhyMode);
@@ -5616,7 +5141,6 @@
 VOID	RTMPSetIndividualHT(
 	IN	PRTMP_ADAPTER		pAd,
 	IN	UCHAR				apidx);
-#endif // DOT11_N_SUPPORT //
 
 VOID RTMPSendWirelessEvent(
 	IN	PRTMP_ADAPTER	pAd,
@@ -5793,13 +5317,6 @@
 	IN CHAR				Rssi,
 	IN UCHAR    RssiNumber);
 
-
-#ifdef DOT11N_DRAFT3
-VOID BuildEffectedChannelList(
-	IN PRTMP_ADAPTER pAd);
-#endif // DOT11N_DRAFT3 //
-
-
 VOID APAsicEvaluateRxAnt(
 	IN PRTMP_ADAPTER	pAd);
 
@@ -6072,6 +5589,10 @@
 	IN  UCHAR           TxRate,
 	IN	BOOLEAN			bQosNull);
 
+#ifdef RT30xx
+VOID RTMPFilterCalibration(
+	IN PRTMP_ADAPTER pAd);
+#endif // RT30xx //
 
 /* timeout -- ms */
 VOID RTMP_SetPeriodicTimer(
@@ -6263,7 +5784,6 @@
 	OUT PUCHAR			pData,
 	IN	UCHAR			FromWhichBSSID);
 
-#ifdef DOT11_N_SUPPORT
 void ba_flush_reordering_timeout_mpdus(
 	IN PRTMP_ADAPTER	pAd,
 	IN PBA_REC_ENTRY	pBAEntry,
@@ -6281,7 +5801,6 @@
 VOID BASessionTearDownALL(
 	IN OUT	PRTMP_ADAPTER pAd,
 	IN		UCHAR Wcid);
-#endif // DOT11_N_SUPPORT //
 
 BOOLEAN OS_Need_Clone_Packet(void);
 
@@ -6429,7 +5948,6 @@
 	IN	PRTMP_ADAPTER	pAd,
 	IN	PUCHAR			arg);
 
-#ifdef DOT11_N_SUPPORT
 INT	Set_BASetup_Proc(
 	IN	PRTMP_ADAPTER	pAd,
 	IN	PUCHAR			arg);
@@ -6530,24 +6048,17 @@
 INT	Set_HtTxBASize_Proc(
 	IN	PRTMP_ADAPTER	pAd,
 	IN	PUCHAR			arg);
-#endif // DOT11_N_SUPPORT //
 
-
-
-#ifdef CONFIG_STA_SUPPORT
 //Dls ,	kathy
 VOID RTMPSendDLSTearDownFrame(
 	IN	PRTMP_ADAPTER	pAd,
 	IN	PUCHAR			pDA);
 
-#ifdef DOT11_N_SUPPORT
 //Block ACK
 VOID QueryBATABLE(
 	IN  PRTMP_ADAPTER pAd,
 	OUT PQUERYBA_TABLE pBAT);
-#endif // DOT11_N_SUPPORT //
 
-#ifdef WPA_SUPPLICANT_SUPPORT
 INT	    WpaCheckEapCode(
 	IN  PRTMP_ADAPTER   	pAd,
 	IN  PUCHAR				pFrame,
@@ -6560,26 +6071,16 @@
 
 VOID    SendAssocIEsToWpaSupplicant(
     IN  PRTMP_ADAPTER       pAd);
-#endif // WPA_SUPPLICANT_SUPPORT //
 
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
 int wext_notify_event_assoc(
 	IN  RTMP_ADAPTER *pAd);
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
 
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-#ifdef DOT11_N_SUPPORT
 VOID Handle_BSS_Width_Trigger_Events(
 	IN PRTMP_ADAPTER pAd);
 
 void build_ext_channel_switch_ie(
 	IN PRTMP_ADAPTER pAd,
 	IN HT_EXT_CHANNEL_SWITCH_ANNOUNCEMENT_IE *pIE);
-#endif // DOT11_N_SUPPORT //
-
 
 BOOLEAN APRxDoneInterruptHandle(
 	IN	PRTMP_ADAPTER	pAd);
@@ -6588,7 +6089,6 @@
 	IN	PRTMP_ADAPTER	pAd,
 	IN	BOOLEAN			argc);
 
-#ifdef DOT11_N_SUPPORT
 // AMPDU packet indication
 VOID Indicate_AMPDU_Packet(
 	IN	PRTMP_ADAPTER	pAd,
@@ -6600,7 +6100,6 @@
 	IN	PRTMP_ADAPTER	pAd,
 	IN	RX_BLK			*pRxBlk,
 	IN	UCHAR			FromWhichBSSID);
-#endif // DOT11_N_SUPPORT //
 
 // Normal legacy Rx packet indication
 VOID Indicate_Legacy_Packet(
@@ -6630,8 +6129,6 @@
 	IN	PUCHAR			pData,
 	IN	ULONG			DataSize);
 
-
-#ifdef CONFIG_STA_SUPPORT
 // remove LLC and get 802_3 Header
 #define  RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(_pRxBlk, _pHeader802_3)	\
 {																				\
@@ -6662,8 +6159,6 @@
 	CONVERT_TO_802_3(_pHeader802_3, _pDA, _pSA, _pRxBlk->pData, 				\
 		_pRxBlk->DataSize, _pRemovedLLCSNAP);                                   \
 }
-#endif // CONFIG_STA_SUPPORT //
-
 
 BOOLEAN APFowardWirelessStaToWirelessSta(
 	IN	PRTMP_ADAPTER	pAd,
@@ -6680,13 +6175,9 @@
 	IN	PNDIS_PACKET	pPacket,
 	IN	UCHAR			FromWhichBSSID);
 
-
-#ifdef CONFIG_STA_SUPPORT
 #define ANNOUNCE_OR_FORWARD_802_3_PACKET(_pAd, _pPacket, _FromWhichBSS)\
 			Sta_Announce_or_Forward_802_3_Packet(_pAd, _pPacket, _FromWhichBSS);
 			//announce_802_3_packet(_pAd, _pPacket);
-#endif // CONFIG_STA_SUPPORT //
-
 
 PNDIS_PACKET DuplicatePacket(
 	IN	PRTMP_ADAPTER	pAd,
@@ -6729,22 +6220,6 @@
 	IN	RX_BLK			*pRxBlk);
 
 ////////////////////////////////////////
-
-
-
-
-
-#ifdef SNMP_SUPPORT
-//for snmp , kathy
-typedef struct _DefaultKeyIdxValue
-{
-	UCHAR	KeyIdx;
-	UCHAR	Value[16];
-} DefaultKeyIdxValue, *PDefaultKeyIdxValue;
-#endif
-
-
-#ifdef CONFIG_STA_SUPPORT
 enum {
 	DIDmsg_lnxind_wlansniffrm		= 0x00000044,
 	DIDmsg_lnxind_wlansniffrm_hosttime	= 0x00010044,
@@ -6857,18 +6332,11 @@
 VOID    RTMPSetDesiredRates(
     IN  PRTMP_ADAPTER   pAdapter,
     IN  LONG            Rates);
-#endif // CONFIG_STA_SUPPORT //
 
 INT	Set_FixedTxMode_Proc(
 	IN	PRTMP_ADAPTER	pAd,
 	IN	PUCHAR			arg);
 
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-INT	Set_OpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
 static inline char* GetPhyMode(
 	int Mode)
 {
@@ -6879,13 +6347,11 @@
 
 		case MODE_OFDM:
 			return "OFDM";
-#ifdef DOT11_N_SUPPORT
 		case MODE_HTMIX:
 			return "HTMIX";
 
 		case MODE_HTGREENFIELD:
 			return "GREEN";
-#endif // DOT11_N_SUPPORT //
 		default:
 			return "N/A";
 	}
@@ -6902,10 +6368,8 @@
 
 		case BW_20:
 			return "20M";
-#ifdef DOT11_N_SUPPORT
 		case BW_40:
 			return "40M";
-#endif // DOT11_N_SUPPORT //
 		default:
 			return "N/A";
 	}
@@ -6945,13 +6409,10 @@
 	IN	OUT	struct ifreq	*rq,
 	IN	INT			cmd);
 
-
-#ifdef CONFIG_STA_SUPPORT
 INT rt28xx_sta_ioctl(
 	IN	struct net_device	*net_dev,
 	IN	OUT	struct ifreq	*rq,
 	IN	INT			cmd);
-#endif // CONFIG_STA_SUPPORT //
 
 BOOLEAN RT28XXSecurityKeyAdd(
 	IN		PRTMP_ADAPTER		pAd,
@@ -6971,6 +6432,7 @@
 
 void tbtt_tasklet(unsigned long data);
 
+#ifdef RT2860
 //
 // Function Prototype in cmm_data_2860.c
 //
@@ -7035,7 +6497,6 @@
 	IN	PRXWI_STRUC	pRxWI,
 	IN  PRT28XX_RXD_STRUC      pRxD);
 
-#ifdef CONFIG_STA_SUPPORT
 VOID RTMPInitPCIeLinkCtrlValue(
 	IN	PRTMP_ADAPTER	pAd);
 
@@ -7078,13 +6539,13 @@
 	IN PVOID FunctionContext,
 	IN PVOID SystemSpecific2,
 	IN PVOID SystemSpecific3);
-#endif // CONFIG_STA_SUPPORT //
 
 VOID RT28xxPciMlmeRadioOn(
 	IN PRTMP_ADAPTER pAd);
 
 VOID RT28xxPciMlmeRadioOFF(
 	IN PRTMP_ADAPTER pAd);
+#endif /* RT2860 */
 
 VOID AsicTurnOffRFClk(
 	IN PRTMP_ADAPTER    pAd,
@@ -7094,6 +6555,493 @@
 	IN PRTMP_ADAPTER 	pAd,
 	IN	UCHAR			Channel);
 
+#ifdef RT30xx
+NTSTATUS RT30xxWriteRFRegister(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			RegID,
+	IN	UCHAR			Value);
+
+NTSTATUS RT30xxReadRFRegister(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			RegID,
+	IN	PUCHAR			pValue);
+
+//2008/09/11:KH add to support efuse<--
+UCHAR eFuseReadRegisters(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT Offset,
+	IN	USHORT Length,
+	OUT	USHORT* pData);
+
+VOID eFuseReadPhysical(
+	IN	PRTMP_ADAPTER	pAd,
+  	IN	PUSHORT lpInBuffer,
+  	IN	ULONG nInBufferSize,
+  	OUT	PUSHORT lpOutBuffer,
+  	IN	ULONG nOutBufferSize
+);
+
+NTSTATUS eFuseRead(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT			Offset,
+	OUT	PUCHAR			pData,
+	IN	USHORT			Length);
+
+VOID eFusePhysicalWriteRegisters(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT Offset,
+	IN	USHORT Length,
+	OUT	USHORT* pData);
+
+NTSTATUS eFuseWriteRegisters(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT Offset,
+	IN	USHORT Length,
+	IN	USHORT* pData);
+
+VOID eFuseWritePhysical(
+	IN	PRTMP_ADAPTER	pAd,
+  	PUSHORT lpInBuffer,
+	ULONG nInBufferSize,
+  	PUCHAR lpOutBuffer,
+  	ULONG nOutBufferSize
+);
+
+NTSTATUS eFuseWrite(
+   	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT			Offset,
+	IN	PUCHAR			pData,
+	IN	USHORT			length);
+
+INT set_eFuseGetFreeBlockCount_Proc(
+   	IN	PRTMP_ADAPTER	pAd,
+	IN	PUCHAR			arg);
+
+INT set_eFusedump_Proc(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PUCHAR			arg);
+
+INT set_eFuseLoadFromBin_Proc(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PUCHAR			arg);
+
+NTSTATUS eFuseWriteRegistersFromBin(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT Offset,
+	IN	USHORT Length,
+	IN	USHORT* pData);
+
+VOID eFusePhysicalReadRegisters(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT Offset,
+	IN	USHORT Length,
+	OUT	USHORT* pData);
+
+NDIS_STATUS NICLoadEEPROM(
+	IN PRTMP_ADAPTER pAd);
+
+BOOLEAN bNeedLoadEEPROM(
+	IN	PRTMP_ADAPTER	pAd);
+//2008/09/11:KH add to support efuse-->
+#endif // RT30xx //
+
+#ifdef RT30xx
+// add by johnli, RF power sequence setup
+VOID RT30xxLoadRFNormalModeSetup(
+	IN PRTMP_ADAPTER 	pAd);
+
+VOID RT30xxLoadRFSleepModeSetup(
+	IN PRTMP_ADAPTER 	pAd);
+
+VOID RT30xxReverseRFSleepModeSetup(
+	IN PRTMP_ADAPTER 	pAd);
+// end johnli
+#endif // RT30xx //
+
+#ifdef RT2870
+//
+// Function Prototype in rtusb_bulk.c
+//
+VOID	RTUSBInitTxDesc(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PTX_CONTEXT		pTxContext,
+	IN	UCHAR			BulkOutPipeId,
+	IN	usb_complete_t	Func);
+
+VOID	RTUSBInitHTTxDesc(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PHT_TX_CONTEXT	pTxContext,
+	IN	UCHAR			BulkOutPipeId,
+	IN	ULONG			BulkOutSize,
+	IN	usb_complete_t	Func);
+
+VOID	RTUSBInitRxDesc(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PRX_CONTEXT		pRxContext);
+
+VOID RTUSBCleanUpDataBulkOutQueue(
+	IN	PRTMP_ADAPTER	pAd);
+
+VOID RTUSBCancelPendingBulkOutIRP(
+	IN	PRTMP_ADAPTER	pAd);
+
+VOID RTUSBBulkOutDataPacket(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			BulkOutPipeId,
+	IN	UCHAR			Index);
+
+VOID RTUSBBulkOutNullFrame(
+	IN	PRTMP_ADAPTER	pAd);
+
+VOID RTUSBBulkOutRTSFrame(
+	IN	PRTMP_ADAPTER	pAd);
+
+VOID RTUSBCancelPendingBulkInIRP(
+	IN	PRTMP_ADAPTER	pAd);
+
+VOID RTUSBCancelPendingIRPs(
+	IN	PRTMP_ADAPTER	pAd);
+
+VOID RTUSBBulkOutMLMEPacket(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			Index);
+
+VOID RTUSBBulkOutPsPoll(
+	IN	PRTMP_ADAPTER	pAd);
+
+VOID RTUSBCleanUpMLMEBulkOutQueue(
+	IN	PRTMP_ADAPTER	pAd);
+
+VOID RTUSBKickBulkOut(
+	IN	PRTMP_ADAPTER pAd);
+
+VOID	RTUSBBulkReceive(
+	IN	PRTMP_ADAPTER	pAd);
+
+VOID DoBulkIn(
+	IN RTMP_ADAPTER *pAd);
+
+VOID RTUSBInitRxDesc(
+	IN	PRTMP_ADAPTER	pAd,
+	IN  PRX_CONTEXT		pRxContext);
+
+VOID RTUSBBulkRxHandle(
+	IN unsigned long data);
+
+//
+// Function Prototype in rtusb_io.c
+//
+NTSTATUS RTUSBMultiRead(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT			Offset,
+	OUT	PUCHAR			pData,
+	IN	USHORT			length);
+
+NTSTATUS RTUSBMultiWrite(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT			Offset,
+	IN	PUCHAR			pData,
+	IN	USHORT			length);
+
+NTSTATUS RTUSBMultiWrite_OneByte(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT			Offset,
+	IN	PUCHAR			pData);
+
+NTSTATUS RTUSBReadBBPRegister(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			Id,
+	IN	PUCHAR			pValue);
+
+NTSTATUS RTUSBWriteBBPRegister(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			Id,
+	IN	UCHAR			Value);
+
+NTSTATUS RTUSBWriteRFRegister(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UINT32			Value);
+
+#ifndef RT30xx
+NTSTATUS	RT30xxWriteRFRegister(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			RegID,
+	IN	UCHAR			Value);
+
+NTSTATUS	RT30xxReadRFRegister(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			RegID,
+	IN	PUCHAR			pValue);
+#endif
+
+NTSTATUS RTUSB_VendorRequest(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UINT32			TransferFlags,
+	IN	UCHAR			ReservedBits,
+	IN	UCHAR			Request,
+	IN	USHORT			Value,
+	IN	USHORT			Index,
+	IN	PVOID			TransferBuffer,
+	IN	UINT32			TransferBufferLength);
+
+NTSTATUS RTUSBReadEEPROM(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT			Offset,
+	OUT	PUCHAR			pData,
+	IN	USHORT			length);
+
+NTSTATUS RTUSBWriteEEPROM(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT			Offset,
+	IN	PUCHAR			pData,
+	IN	USHORT			length);
+
+VOID RTUSBPutToSleep(
+	IN	PRTMP_ADAPTER	pAd);
+
+NTSTATUS RTUSBWakeUp(
+	IN	PRTMP_ADAPTER	pAd);
+
+VOID RTUSBInitializeCmdQ(
+	IN	PCmdQ	cmdq);
+
+NDIS_STATUS	RTUSBEnqueueCmdFromNdis(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	NDIS_OID		Oid,
+	IN	BOOLEAN			SetInformation,
+	IN	PVOID			pInformationBuffer,
+	IN	UINT32			InformationBufferLength);
+
+NDIS_STATUS RTUSBEnqueueInternalCmd(
+	IN	PRTMP_ADAPTER	pAd,
+	IN NDIS_OID			Oid,
+	IN PVOID			pInformationBuffer,
+	IN UINT32			InformationBufferLength);
+
+VOID RTUSBDequeueCmd(
+	IN	PCmdQ		cmdq,
+	OUT	PCmdQElmt	*pcmdqelmt);
+
+INT RTUSBCmdThread(
+	IN OUT PVOID Context);
+
+INT TimerQThread(
+	IN OUT PVOID Context);
+
+RT2870_TIMER_ENTRY *RT2870_TimerQ_Insert(
+	IN RTMP_ADAPTER *pAd,
+	IN RALINK_TIMER_STRUCT *pTimer);
+
+BOOLEAN RT2870_TimerQ_Remove(
+	IN RTMP_ADAPTER *pAd,
+	IN RALINK_TIMER_STRUCT *pTimer);
+
+void RT2870_TimerQ_Exit(
+	IN RTMP_ADAPTER *pAd);
+
+void RT2870_TimerQ_Init(
+	IN RTMP_ADAPTER *pAd);
+
+VOID RT2870_BssBeaconExit(
+	IN RTMP_ADAPTER *pAd);
+
+VOID RT2870_BssBeaconStop(
+	IN RTMP_ADAPTER *pAd);
+
+VOID RT2870_BssBeaconStart(
+	IN RTMP_ADAPTER * pAd);
+
+VOID RT2870_BssBeaconInit(
+	IN RTMP_ADAPTER *pAd);
+
+VOID RT2870_WatchDog(
+	IN RTMP_ADAPTER *pAd);
+
+NTSTATUS RTUSBWriteMACRegister(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT			Offset,
+	IN	UINT32			Value);
+
+NTSTATUS RTUSBReadMACRegister(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	USHORT			Offset,
+	OUT	PUINT32			pValue);
+
+NTSTATUS RTUSBSingleWrite(
+	IN 	RTMP_ADAPTER 	*pAd,
+	IN	USHORT			Offset,
+	IN	USHORT			Value);
+
+NTSTATUS RTUSBFirmwareRun(
+	IN	PRTMP_ADAPTER	pAd);
+
+NTSTATUS RTUSBFirmwareWrite(
+	IN PRTMP_ADAPTER pAd,
+	IN PUCHAR		pFwImage,
+	IN ULONG		FwLen);
+
+NTSTATUS	RTUSBFirmwareOpmode(
+	IN	PRTMP_ADAPTER	pAd,
+	OUT	PUINT32			pValue);
+
+NTSTATUS	RTUSBVenderReset(
+	IN	PRTMP_ADAPTER	pAd);
+
+NDIS_STATUS RTUSBSetHardWareRegister(
+	IN	PRTMP_ADAPTER	pAdapter,
+	IN	PVOID			pBuf);
+
+NDIS_STATUS RTUSBQueryHardWareRegister(
+	IN	PRTMP_ADAPTER	pAdapter,
+	IN	PVOID			pBuf);
+
+VOID CMDHandler(
+    IN PRTMP_ADAPTER pAd);
+
+
+NDIS_STATUS	 CreateThreads(
+	IN	struct net_device *net_dev );
+
+
+VOID MacTableInitialize(
+	IN  PRTMP_ADAPTER   pAd);
+
+VOID MlmeSetPsm(
+	IN PRTMP_ADAPTER pAd,
+	IN USHORT psm);
+
+NDIS_STATUS RTMPWPAAddKeyProc(
+	IN  PRTMP_ADAPTER   pAd,
+	IN  PVOID           pBuf);
+
+VOID AsicRxAntEvalAction(
+	IN PRTMP_ADAPTER pAd);
+
+void append_pkt(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PUCHAR			pHeader802_3,
+    IN  UINT            HdrLen,
+	IN	PUCHAR			pData,
+	IN	ULONG			DataSize,
+	OUT  PNDIS_PACKET	*ppPacket);
+
+UINT deaggregate_AMSDU_announce(
+	IN	PRTMP_ADAPTER	pAd,
+	PNDIS_PACKET		pPacket,
+	IN	PUCHAR			pData,
+	IN	ULONG			DataSize);
+
+NDIS_STATUS	RTMPCheckRxError(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PHEADER_802_11	pHeader,
+	IN	PRXWI_STRUC	pRxWI,
+	IN	PRT28XX_RXD_STRUC	pRxINFO);
+
+
+VOID RTUSBMlmeHardTransmit(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PMGMT_STRUC		pMgmt);
+
+INT MlmeThread(
+	IN PVOID Context);
+
+//
+// Function Prototype in rtusb_data.c
+//
+NDIS_STATUS	RTUSBFreeDescriptorRequest(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			BulkOutPipeId,
+	IN	UINT32			NumberRequired);
+
+
+BOOLEAN	RTUSBNeedQueueBackForAgg(
+	IN RTMP_ADAPTER *pAd,
+	IN UCHAR		BulkOutPipeId);
+
+
+VOID RTMPWriteTxInfo(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PTXINFO_STRUC 	pTxInfo,
+	IN	  USHORT		USBDMApktLen,
+	IN	  BOOLEAN		bWiv,
+	IN	  UCHAR			QueueSel,
+	IN	  UCHAR			NextValid,
+	IN	  UCHAR			TxBurst);
+
+//
+// Function Prototype in cmm_data_2870.c
+//
+USHORT RtmpUSB_WriteSubTxResource(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	TX_BLK			*pTxBlk,
+	IN	BOOLEAN			bIsLast,
+	OUT	USHORT			*FreeNumber);
+
+USHORT RtmpUSB_WriteSingleTxResource(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	TX_BLK			*pTxBlk,
+	IN	BOOLEAN			bIsLast,
+	OUT	USHORT			*FreeNumber);
+
+USHORT	RtmpUSB_WriteFragTxResource(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	TX_BLK			*pTxBlk,
+	IN	UCHAR			fragNum,
+	OUT	USHORT			*FreeNumber);
+
+USHORT RtmpUSB_WriteMultiTxResource(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	TX_BLK			*pTxBlk,
+	IN	UCHAR			frameNum,
+	OUT	USHORT			*FreeNumber);
+
+VOID RtmpUSB_FinalWriteTxResource(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	TX_BLK			*pTxBlk,
+	IN	USHORT			totalMPDUSize,
+#ifdef RT2860
+	IN	USHORT			FirstTxIdx);
+#endif
+	IN	USHORT			TxIdx);
+
+VOID RtmpUSBDataLastTxIdx(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	UCHAR			QueIdx,
+	IN	USHORT			TxIdx);
+
+VOID RtmpUSBDataKickOut(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	TX_BLK			*pTxBlk,
+	IN	UCHAR			QueIdx);
+
+
+int RtmpUSBMgmtKickOut(
+	IN RTMP_ADAPTER 	*pAd,
+	IN UCHAR 			QueIdx,
+	IN PNDIS_PACKET		pPacket,
+	IN PUCHAR			pSrcBufVA,
+	IN UINT 			SrcBufLen);
+
+VOID RtmpUSBNullFrameKickOut(
+	IN RTMP_ADAPTER *pAd,
+	IN UCHAR		QueIdx,
+	IN UCHAR		*pNullFrame,
+	IN UINT32		frameLen);
+
+VOID RT28xxUsbStaAsicForceWakeup(
+	IN PRTMP_ADAPTER pAd,
+	IN BOOLEAN       bFromTx);
+
+VOID RT28xxUsbStaAsicSleepThenAutoWakeup(
+	IN PRTMP_ADAPTER pAd,
+	IN USHORT TbttNumToNextWakeUp);
+
+VOID RT28xxUsbMlmeRadioOn(
+	IN PRTMP_ADAPTER pAd);
+
+VOID RT28xxUsbMlmeRadioOFF(
+	IN PRTMP_ADAPTER pAd);
+#endif // RT2870 //
 
 ////////////////////////////////////////
 
@@ -7120,10 +7068,10 @@
     IN  USHORT encryMode);
 //////////////////////////////////////
 
-#ifdef CONFIG_STA_SUPPORT
 VOID AsicStaBbpTuning(
 	IN PRTMP_ADAPTER pAd);
 
+#ifdef RT2860
 VOID AsicResetFromDMABusy(
 	IN PRTMP_ADAPTER pAd);
 
@@ -7135,7 +7083,16 @@
 
 VOID AsicResetPBF(
 	IN PRTMP_ADAPTER pAd);
-#endif // CONFIG_STA_SUPPORT //
+#endif
+#ifdef RT2870
+BOOLEAN StaAddMacTableEntry(
+	IN  PRTMP_ADAPTER		pAd,
+	IN  PMAC_TABLE_ENTRY	pEntry,
+	IN  UCHAR				MaxSupportedRateIn500Kbps,
+	IN  HT_CAPABILITY_IE	*pHtCapability,
+	IN  UCHAR				HtCapabilityLen,
+	IN  USHORT        		CapabilityInfo);
+#endif
 
 void RTMP_IndicateMediaState(
 	IN	PRTMP_ADAPTER	pAd);
diff --git a/drivers/staging/rt2860/rtmp_def.h b/drivers/staging/rt2860/rtmp_def.h
index 25a53d8..5dde860 100644
--- a/drivers/staging/rt2860/rtmp_def.h
+++ b/drivers/staging/rt2860/rtmp_def.h
@@ -54,15 +54,6 @@
 #define NIC_TAG             ((ULONG)'0682')
 #define NIC_DBG_STRING      ("**RT28xx**")
 
-#ifdef SNMP_SUPPORT
-// for snmp
-// to get manufacturer OUI, kathy, 2008_0220
-#define ManufacturerOUI_LEN			3
-#define ManufacturerNAME			("Ralink Technology Company.")
-#define	ResourceTypeIdName			("Ralink_ID")
-#endif
-
-
 #define RALINK_2883_VERSION		((UINT32)0x28830300)
 #define RALINK_2880E_VERSION	((UINT32)0x28720200)
 #define RALINK_3070_VERSION		((UINT32)0x30700200)
@@ -111,6 +102,7 @@
 // Entry number for each DMA descriptor ring
 //
 
+#ifdef RT2860
 #define TX_RING_SIZE            64 //64
 #define MGMT_RING_SIZE          128
 #define RX_RING_SIZE            128 //64
@@ -118,12 +110,15 @@
 #define MAX_DMA_DONE_PROCESS    TX_RING_SIZE
 #define MAX_TX_DONE_PROCESS     TX_RING_SIZE //8
 #define LOCAL_TXBUF_SIZE        2
-
-
-#ifdef MULTIPLE_CARD_SUPPORT
-// MC: Multple Cards
-#define MAX_NUM_OF_MULTIPLE_CARD		32
-#endif // MULTIPLE_CARD_SUPPORT //
+#endif
+#ifdef RT2870
+#define TX_RING_SIZE            8 // 1
+#define PRIO_RING_SIZE          8
+#define MGMT_RING_SIZE       32 // PRIO_RING_SIZE
+#define RX_RING_SIZE            8
+#define MAX_TX_PROCESS          4
+#define LOCAL_TXBUF_SIZE        2048
+#endif // RT2870 //
 
 #define MAX_RX_PROCESS          128 //64 //32
 #define NUM_OF_LOCAL_TXBUF      2
@@ -153,7 +148,11 @@
 #define MAX_PACKETS_IN_PS_QUEUE				128	//32
 #define WMM_NUM_OF_AC                       4  /* AC0, AC1, AC2, and AC3 */
 
-
+#ifdef RT30xx
+//2008/09/11:KH add to support efuse<--
+#define MAX_EEPROM_BIN_FILE_SIZE					1024
+//2008/09/11:KH add to support efuse-->
+#endif
 
 // RxFilter
 #define STANORMAL	 0x17f97
@@ -210,6 +209,7 @@
 #define fOP_STATUS_WAKEUP_NOW               0x00008000
 #define fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE       0x00020000
 
+#ifdef RT2860
 //
 //  RTMP_ADAPTER PSFlags : related to advanced power save.
 //
@@ -222,10 +222,7 @@
 // Indicate driver should IMMEDIATELY fo to sleep after receiving AP's beacon in which  doesn't indicate unicate nor multicast packets for me
 //. This flag is used ONLY in RTMPHandleRxDoneInterrupt routine.
 #define fRTMP_PS_GO_TO_SLEEP_NOW         0x00000008
-
-#ifdef DOT11N_DRAFT3
-#define fOP_STATUS_SCAN_2040               	    0x00040000
-#endif // DOT11N_DRAFT3 //
+#endif
 
 #define CCKSETPROTECT		0x1
 #define OFDMSETPROTECT		0x2
@@ -251,10 +248,6 @@
 #define fCLIENT_STATUS_MCSFEEDBACK_CAPABLE  0x00000400
 #define fCLIENT_STATUS_APSD_CAPABLE         0x00000800  /* UAPSD STATION */
 
-#ifdef DOT11N_DRAFT3
-#define fCLIENT_STATUS_BSSCOEXIST_CAPABLE	0x00001000
-#endif // DOT11N_DRAFT3 //
-
 #define fCLIENT_STATUS_RALINK_CHIPSET		0x00100000
 //
 //  STA configuration flags
@@ -330,16 +323,14 @@
 #define MAX_MESH_NUM				0
 
 #define MAX_APCLI_NUM				0
-#ifdef APCLI_SUPPORT
-#undef	MAX_APCLI_NUM
-#define MAX_APCLI_NUM				1
-#endif // APCLI_SUPPORT //
 
 #define MAX_MBSSID_NUM				1
+#if defined(RT2860) || defined(RT30xx)
 #ifdef MBSS_SUPPORT
 #undef	MAX_MBSSID_NUM
 #define MAX_MBSSID_NUM				(8 - MAX_MESH_NUM - MAX_APCLI_NUM)
 #endif // MBSS_SUPPORT //
+#endif
 
 /* sanity check for apidx */
 #define MBSS_MR_APIDX_SANITY_CHECK(apidx) \
@@ -582,6 +573,9 @@
 // For 802.11n D3.03
 //#define IE_NEW_EXT_CHA_OFFSET             62    // 802.11n d1. New extension channel offset elemet
 #define IE_SECONDARY_CH_OFFSET		62	// 802.11n D3.03	Secondary Channel Offset element
+#ifdef RT2870
+#define IE_WAPI							68		// WAPI information element
+#endif
 #define IE_2040_BSS_COEXIST               72    // 802.11n D3.0.3
 #define IE_2040_BSS_INTOLERANT_REPORT     73    // 802.11n D3.03
 #define IE_OVERLAPBSS_SCAN_PARM           74    // 802.11n D3.03
@@ -630,9 +624,10 @@
 #define AP_CNTL_STATE_MACHINE           15
 #define AP_WPA_STATE_MACHINE            16
 
-#ifdef QOS_DLS_SUPPORT
-#define DLS_STATE_MACHINE               26
-#endif // QOS_DLS_SUPPORT //
+#ifdef RT30xx
+#define WSC_STATE_MACHINE            17
+#define WSC_UPNP_STATE_MACHINE		    18
+#endif
 
 //
 // STA's CONTROL/CONNECT state machine: states, events, total function #
@@ -647,6 +642,9 @@
 #define CNTL_WAIT_AUTH2                 7
 #define CNTL_WAIT_OID_LIST_SCAN         8
 #define CNTL_WAIT_OID_DISASSOC          9
+#ifdef RT2870
+#define CNTL_WAIT_SCAN_FOR_CONNECT      10
+#endif // RT2870 //
 
 #define MT2_ASSOC_CONF                  34
 #define MT2_AUTH_CONF                   35
@@ -948,79 +946,6 @@
 
 #define AP_WPA_FUNC_SIZE                (AP_MAX_WPA_PTK_STATE * AP_MAX_WPA_MSG)
 
-#ifdef APCLI_SUPPORT
-//ApCli authentication state machine
-#define APCLI_AUTH_REQ_IDLE                0
-#define APCLI_AUTH_WAIT_SEQ2               1
-#define APCLI_AUTH_WAIT_SEQ4               2
-#define APCLI_MAX_AUTH_STATE               3
-
-#define APCLI_AUTH_MACHINE_BASE            0
-#define APCLI_MT2_MLME_AUTH_REQ            0
-#define APCLI_MT2_MLME_DEAUTH_REQ          1
-#define APCLI_MT2_PEER_AUTH_EVEN           2
-#define APCLI_MT2_PEER_DEAUTH              3
-#define APCLI_MT2_AUTH_TIMEOUT             4
-#define APCLI_MAX_AUTH_MSG                 5
-
-#define APCLI_AUTH_FUNC_SIZE               (APCLI_MAX_AUTH_STATE * APCLI_MAX_AUTH_MSG)
-
-//ApCli association state machine
-#define APCLI_ASSOC_IDLE                   0
-#define APCLI_ASSOC_WAIT_RSP               1
-#define APCLI_MAX_ASSOC_STATE              2
-
-#define APCLI_ASSOC_MACHINE_BASE           0
-#define APCLI_MT2_MLME_ASSOC_REQ           0
-#define APCLI_MT2_MLME_DISASSOC_REQ        1
-#define APCLI_MT2_PEER_DISASSOC_REQ        2
-#define APCLI_MT2_PEER_ASSOC_RSP           3
-#define APCLI_MT2_ASSOC_TIMEOUT            4
-#define APCLI_MAX_ASSOC_MSG                5
-
-#define APCLI_ASSOC_FUNC_SIZE              (APCLI_MAX_ASSOC_STATE * APCLI_MAX_ASSOC_MSG)
-
-//ApCli sync state machine
-#define APCLI_SYNC_IDLE                   0  // merge NO_BSS,IBSS_IDLE,IBSS_ACTIVE and BSS in to 1 state
-#define APCLI_JOIN_WAIT_PROBE_RSP         1
-#define APCLI_MAX_SYNC_STATE              2
-
-#define APCLI_SYNC_MACHINE_BASE           0
-#define APCLI_MT2_MLME_PROBE_REQ          0
-#define APCLI_MT2_PEER_PROBE_RSP          1
-#define APCLI_MT2_PROBE_TIMEOUT           2
-#define APCLI_MAX_SYNC_MSG                3
-
-#define APCLI_SYNC_FUNC_SIZE              (APCLI_MAX_SYNC_STATE * APCLI_MAX_SYNC_MSG)
-
-//ApCli ctrl state machine
-#define APCLI_CTRL_DISCONNECTED           0  // merge NO_BSS,IBSS_IDLE,IBSS_ACTIVE and BSS in to 1 state
-#define APCLI_CTRL_PROBE                  1
-#define APCLI_CTRL_AUTH                   2
-#define APCLI_CTRL_AUTH_2                 3
-#define APCLI_CTRL_ASSOC                  4
-#define APCLI_CTRL_DEASSOC                5
-#define APCLI_CTRL_CONNECTED              6
-#define APCLI_MAX_CTRL_STATE              7
-
-#define APCLI_CTRL_MACHINE_BASE           0
-#define APCLI_CTRL_JOIN_REQ               0
-#define APCLI_CTRL_PROBE_RSP              1
-#define APCLI_CTRL_AUTH_RSP               2
-#define APCLI_CTRL_DISCONNECT_REQ         3
-#define APCLI_CTRL_PEER_DISCONNECT_REQ    4
-#define APCLI_CTRL_ASSOC_RSP              5
-#define APCLI_CTRL_DEASSOC_RSP            6
-#define APCLI_CTRL_JOIN_REQ_TIMEOUT       7
-#define APCLI_CTRL_AUTH_REQ_TIMEOUT       8
-#define APCLI_CTRL_ASSOC_REQ_TIMEOUT      9
-#define APCLI_MAX_CTRL_MSG                10
-
-#define APCLI_CTRL_FUNC_SIZE              (APCLI_MAX_CTRL_STATE * APCLI_MAX_CTRL_MSG)
-
-#endif	// APCLI_SUPPORT //
-
-
 // =============================================================================
 
 // value domain of 802.11 header FC.Tyte, which is b3..b2 of the 1st-byte of MAC header
@@ -1107,10 +1032,9 @@
 // Preamble MODE in TxD
 #define MODE_CCK	0
 #define MODE_OFDM   1
-#ifdef DOT11_N_SUPPORT
 #define MODE_HTMIX	2
 #define MODE_HTGREENFIELD	3
-#endif // DOT11_N_SUPPORT //
+
 // MCS for CCK.  BW.SGI.STBC are reserved
 #define MCS_LONGP_RATE_1                      0	 // long preamble CCK 1Mbps
 #define MCS_LONGP_RATE_2                      1	// long preamble CCK 1Mbps
@@ -1157,12 +1081,10 @@
 #define MCS_32		32
 #define MCS_AUTO		33
 
-#ifdef DOT11_N_SUPPORT
 // OID_HTPHYMODE
 // MODE
 #define HTMODE_MM	0
 #define HTMODE_GF	1
-#endif // DOT11_N_SUPPORT //
 
 // Fixed Tx MODE - HT, CCK or OFDM
 #define FIXED_TXMODE_HT		0
@@ -1174,15 +1096,12 @@
 #define BW_BOTH		BAND_WIDTH_BOTH
 #define BW_10		BAND_WIDTH_10	// 802.11j has 10MHz. This definition is for internal usage. doesn't fill in the IE or other field.
 
-#ifdef DOT11_N_SUPPORT
 // SHORTGI
 #define GI_400		GAP_INTERVAL_400	// only support in HT mode
 #define GI_BOTH		GAP_INTERVAL_BOTH
-#endif // DOT11_N_SUPPORT //
 #define GI_800		GAP_INTERVAL_800
 // STBC
 #define STBC_NONE	0
-#ifdef DOT11_N_SUPPORT
 #define STBC_USE	1	// limited use in rt2860b phy
 #define RXSTBC_ONE	1	// rx support of one spatial stream
 #define RXSTBC_TWO	2	// rx support of 1 and 2 spatial stream
@@ -1204,8 +1123,6 @@
 #define	AMSDU_0	0
 #define	AMSDU_1		1
 
-#endif // DOT11_N_SUPPORT //
-
 // MCS use 7 bits
 #define TXRATEMIMO		0x80
 #define TXRATEMCS		0x7F
@@ -1298,6 +1215,10 @@
 #define RFIC_2750                   4       // 2.4G/5G 1T2R
 #define RFIC_3020                   5       // 2.4G 1T1R
 #define RFIC_2020                   6       // 2.4G B/G
+#ifdef RT30xx
+#define RFIC_3021                   7       // 2.4G 1T2R
+#define RFIC_3022                   8       // 2.4G 2T2R
+#endif
 
 // LED Status.
 #define LED_LINK_DOWN               0
@@ -1353,17 +1274,6 @@
 #define OPMODE_AP                   1
 //#define OPMODE_L3_BRG               2       // as AP and STA at the same time
 
-#ifdef RT_BIG_ENDIAN
-#define DIR_READ                    0
-#define DIR_WRITE                   1
-#define TYPE_TXD                    0
-#define TYPE_RXD                    1
-#define TYPE_TXINFO					0
-#define TYPE_RXINFO					1
-#define TYPE_TXWI					0
-#define TYPE_RXWI					1
-#endif
-
 // ========================= AP rtmp_def.h ===========================
 // value domain for pAd->EventTab.Log[].Event
 #define EVENT_RESET_ACCESS_POINT    0 // Log = "hh:mm:ss   Restart Access Point"
@@ -1410,24 +1320,6 @@
 #define INT_MESH                   	0x0500
 
 // Use bitmap to allow coexist of ATE_TXFRAME and ATE_RXFRAME(i.e.,to support LoopBack mode)
-#ifdef RALINK_ATE
-#define	ATE_START                   0x00   // Start ATE
-#define	ATE_STOP                    0x80   // Stop ATE
-#define	ATE_TXCONT                  0x05   // Continuous Transmit
-#define	ATE_TXCARR                  0x09   // Transmit Carrier
-#define	ATE_TXCARRSUPP              0x11   // Transmit Carrier Suppression
-#define	ATE_TXFRAME                 0x01   // Transmit Frames
-#define	ATE_RXFRAME                 0x02   // Receive Frames
-#ifdef RALINK_28xx_QA
-#define ATE_TXSTOP                  0xe2   // Stop Transmition(i.e., TXCONT, TXCARR, TXCARRSUPP, and TXFRAME)
-#define ATE_RXSTOP					0xfd   // Stop receiving Frames
-#define	BBP22_TXFRAME     			0x00   // Transmit Frames
-#define	BBP22_TXCONT_OR_CARRSUPP    0x80   // Continuous Transmit or Carrier Suppression
-#define	BBP22_TXCARR                0xc1   // Transmit Carrier
-#define	BBP24_TXCONT                0x00   // Continuous Transmit
-#define	BBP24_CARRSUPP              0x01   // Carrier Suppression
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
 
 // WEP Key TYPE
 #define WEP_HEXADECIMAL_TYPE    0
@@ -1498,7 +1390,6 @@
 
 // End - WIRELESS EVENTS definition
 
-#ifdef CONFIG_STA_SUPPORT
 // definition for DLS, kathy
 #define	MAX_NUM_OF_INIT_DLS_ENTRY   1
 #define	MAX_NUM_OF_DLS_ENTRY        MAX_NUMBER_OF_DLS_ENTRY
@@ -1508,15 +1399,12 @@
 #define MAX_RX_REORDERBUF		64
 #define DEFAULT_TX_TIMEOUT		30
 #define DEFAULT_RX_TIMEOUT		30
-#ifndef CONFIG_AP_SUPPORT
 #define MAX_BARECI_SESSION		8
-#endif
 
 #ifndef IW_ESSID_MAX_SIZE
 /* Maximum size of the ESSID and pAd->nickname strings */
 #define IW_ESSID_MAX_SIZE   		32
 #endif
-#endif // CONFIG_STA_SUPPORT //
 
 #ifdef MCAST_RATE_SPECIFIC
 #define MCAST_DISABLE	0
@@ -1525,6 +1413,7 @@
 #define MCAST_HTMIX		3
 #endif // MCAST_RATE_SPECIFIC //
 
+#ifdef RT2860
 // For AsicRadioOff/AsicRadioOn/AsicForceWakeup function
 // This is to indicate from where to call this function.
 #define DOT11POWERSAVE		0	// TO do .11 power save sleep
@@ -1532,8 +1421,14 @@
 #define RTMP_HALT			2	// Called from Halt handler.
 #define GUI_IDLE_POWER_SAVE	3	// Call to sleep before link up with AP
 #define FROM_TX				4	// Force wake up from Tx packet.
-
-
+#endif
+#ifdef RT2870
+// For AsicRadioOff/AsicRadioOn function
+#define DOT11POWERSAVE		0
+#define GUIRADIO_OFF		1
+#define RTMP_HALT		    2
+#define GUI_IDLE_POWER_SAVE		3
+#endif
 
 // definition for WpaSupport flag
 #define WPA_SUPPLICANT_DISABLE				0
@@ -1564,23 +1459,6 @@
     (UINT64)(((UINT64)(x) & (UINT64) 0x00ff000000000000ULL) >> 40) | \
     (UINT64)(((UINT64)(x) & (UINT64) 0xff00000000000000ULL) >> 56) ))
 
-#ifdef RT_BIG_ENDIAN
-
-#define cpu2le64(x) SWAP64((x))
-#define le2cpu64(x) SWAP64((x))
-#define cpu2le32(x) SWAP32((x))
-#define le2cpu32(x) SWAP32((x))
-#define cpu2le16(x) SWAP16((x))
-#define le2cpu16(x) SWAP16((x))
-#define cpu2be64(x) ((UINT64)(x))
-#define be2cpu64(x) ((UINT64)(x))
-#define cpu2be32(x) ((UINT32)(x))
-#define be2cpu32(x) ((UINT32)(x))
-#define cpu2be16(x) ((UINT16)(x))
-#define be2cpu16(x) ((UINT16)(x))
-
-#else   // Little_Endian
-
 #define cpu2le64(x) ((UINT64)(x))
 #define le2cpu64(x) ((UINT64)(x))
 #define cpu2le32(x) ((UINT32)(x))
@@ -1594,8 +1472,6 @@
 #define cpu2be16(x) SWAP16((x))
 #define be2cpu16(x) SWAP16((x))
 
-#endif  // RT_BIG_ENDIAN
-
 #endif  // __RTMP_DEF_H__
 
 
diff --git a/drivers/staging/rt2860/spectrum.h b/drivers/staging/rt2860/spectrum.h
index 60f25db..0a878ba 100644
--- a/drivers/staging/rt2860/spectrum.h
+++ b/drivers/staging/rt2860/spectrum.h
@@ -46,16 +46,6 @@
 
 typedef union PACKED _MEASURE_REQ_MODE
 {
-#ifdef RT_BIG_ENDIAN
-	struct PACKED
-	{
-		UINT8 Rev1:4;
-		UINT8 Report:1;
-		UINT8 Request:1;
-		UINT8 Enable:1;
-		UINT8 Rev0:1;
-	} field;
-#else
 	struct PACKED
 	{
 		UINT8 Rev0:1;
@@ -64,7 +54,6 @@
 		UINT8 Report:1;
 		UINT8 Rev1:4;
 	} field;
-#endif // RT_BIG_ENDIAN //
 	UINT8 word;
 } MEASURE_REQ_MODE, *PMEASURE_REQ_MODE;
 
@@ -85,17 +74,6 @@
 
 typedef union PACKED _MEASURE_BASIC_REPORT_MAP
 {
-#ifdef RT_BIG_ENDIAN
-	struct PACKED
-	{
-		UINT8 Rev:3;
-		UINT8 Unmeasure:1;
-		UINT8 Radar:1;
-		UINT8 UnidentifiedSignal:1;
-		UINT8 OfdmPreamble:1;
-		UINT8 BSS:1;
-	} field;
-#else
 	struct PACKED
 	{
 		UINT8 BSS:1;
@@ -105,7 +83,6 @@
 		UINT8 Unmeasure:1;
 		UINT8 Rev:3;
 	} field;
-#endif // RT_BIG_ENDIAN //
 	UINT8 word;
 } MEASURE_BASIC_REPORT_MAP, *PMEASURE_BASIC_REPORT_MAP;
 
@@ -137,17 +114,10 @@
 {
 	struct PACKED
 	{
-#ifdef RT_BIG_ENDIAN
-		UINT8 Rev:5;
-		UINT8 Refused:1;
-		UINT8 Incapable:1;
-		UINT8 Late:1;
-#else
 		UINT8 Late:1;
 		UINT8 Incapable:1;
 		UINT8 Refused:1;
 		UINT8 Rev:5;
-#endif // RT_BIG_ENDIAN //
 	} field;
 	UINT8 word;
 } MEASURE_REPORT_MODE, *PMEASURE_REPORT_MODE;
diff --git a/drivers/staging/rt2860/sta/assoc.c b/drivers/staging/rt2860/sta/assoc.c
index 34f1c14..a0734c6 100644
--- a/drivers/staging/rt2860/sta/assoc.c
+++ b/drivers/staging/rt2860/sta/assoc.c
@@ -341,7 +341,6 @@
 			FrameLen += tmp;
 		}
 
-#ifdef DOT11_N_SUPPORT
 		// HT
 		if ((pAd->MlmeAux.HtCapabilityLen > 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
 		{
@@ -360,32 +359,14 @@
 			}
 			else
 			{
-#ifdef RT_BIG_ENDIAN
-		        HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
-
-#ifndef RT_BIG_ENDIAN
 				MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
 							  1,                                &HtCapIe,
 							  1,                                &pAd->MlmeAux.HtCapabilityLen,
 							 pAd->MlmeAux.HtCapabilityLen,          &pAd->MlmeAux.HtCapability,
 							  END_OF_ARGS);
-#else
-                NdisZeroMemory(&HtCapabilityTmp, sizeof(HT_CAPABILITY_IE));
-                NdisMoveMemory(&HtCapabilityTmp, &pAd->MlmeAux.HtCapability, pAd->MlmeAux.HtCapabilityLen);
-        		*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-        		*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-        		MakeOutgoingFrame(pOutBuffer + FrameLen,         &TmpLen,
-        							1,                           &HtCapIe,
-        							1,                           &pAd->MlmeAux.HtCapabilityLen,
-        							pAd->MlmeAux.HtCapabilityLen,&HtCapabilityTmp,
-        							END_OF_ARGS);
-#endif
 			}
 			FrameLen += TmpLen;
 		}
-#endif // DOT11_N_SUPPORT //
 
 		// add Ralink proprietary IE to inform AP this STA is going to use AGGREGATION or PIGGY-BACK+AGGREGATION
 		// Case I: (Aggregation + Piggy-Back)
@@ -473,6 +454,11 @@
 				RSNIe = IE_WPA2;
 			}
 
+#ifdef RT30xx
+#ifdef SIOCSIWGENIE
+			if (pAd->StaCfg.WpaSupplicantUP != 1)
+#endif // SIOCSIWGENIE //
+#endif
             RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, BSS0);
 
             // Check for WPA PMK cache list
@@ -499,6 +485,17 @@
 				}
 			}
 
+#ifdef RT30xx
+#ifdef SIOCSIWGENIE
+			if (pAd->StaCfg.WpaSupplicantUP == 1)
+			{
+				MakeOutgoingFrame(pOutBuffer + FrameLen,    		&tmp,
+		                        	pAd->StaCfg.RSNIE_Len,			pAd->StaCfg.RSN_IE,
+		                        	END_OF_ARGS);
+			}
+			else
+#endif
+#endif
 			{
 				MakeOutgoingFrame(pOutBuffer + FrameLen,    		&tmp,
 				              		1,                              &RSNIe,
@@ -509,6 +506,11 @@
 
 			FrameLen += tmp;
 
+#ifdef RT30xx
+#ifdef SIOCSIWGENIE
+			if (pAd->StaCfg.WpaSupplicantUP != 1)
+#endif
+#endif
 			{
 	            // Append Variable IE
 	            NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &RSNIe, 1);
@@ -560,34 +562,6 @@
 						END_OF_ARGS);
 			FrameLen += tmp;
 
-			//
-			// Add CipherSuite CCKM or LeapTkip if setting.
-			//
-#ifdef LEAP_SUPPORT
-			if (LEAP_CCKM_ON(pAd))
-			{
-				MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-						CipherSuiteCiscoCCKMLen,		CipherSuiteCiscoCCKM,
-						END_OF_ARGS);
-				FrameLen += tmp;
-
-				// Third add RSN
-				NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, CipherSuiteCiscoCCKM, CipherSuiteCiscoCCKMLen); //Save CipherSuite
-				VarIesOffset += CipherSuiteCiscoCCKMLen;
-			}
-			else if ((pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP) && (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled))
-			{
-				MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-						CipherSuiteCCXTkipLen,	    CipherSuiteCCXTkip,
-						END_OF_ARGS);
-				FrameLen += tmp;
-
-				// Third add RSN
-				NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, CipherSuiteCCXTkip, CipherSuiteCCXTkipLen);
-				VarIesOffset += CipherSuiteCCXTkipLen;
-			}
-#endif // LEAP_SUPPORT //
-
 			// Add by James 03/06/27
 			// Set Variable IEs Length
 			pAd->StaCfg.ReqVarIELen = VarIesOffset;
@@ -647,23 +621,6 @@
 	NDIS_STATUS		NStatus;
 	ULONG			tmp;
 	PUCHAR			pOutBuffer = NULL;
-//CCX 2.X
-#ifdef LEAP_SUPPORT
-	UCHAR			CkipFlag;
-	UCHAR			CkipNegotiationBuffer[CKIP_NEGOTIATION_LENGTH];
-	UCHAR			AironetCkipIe = IE_AIRONET_CKIP;
-	UCHAR			AironetCkipLen = CKIP_NEGOTIATION_LENGTH;
-	UCHAR			AironetIPAddressIE = IE_AIRONET_IPADDRESS;
-	UCHAR			AironetIPAddressLen = AIRONET_IPADDRESS_LENGTH;
-	UCHAR			AironetIPAddressBuffer[AIRONET_IPADDRESS_LENGTH] = {0x00, 0x40, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00};
-	UCHAR			AironetCCKMReassocIE = IE_AIRONET_CCKMREASSOC;
-	UCHAR			AironetCCKMReassocLen = AIRONET_CCKMREASSOC_LENGTH;
-	UCHAR			AironetCCKMReassocBuffer[AIRONET_CCKMREASSOC_LENGTH];
-	UCHAR			AironetOUI[] = {0x00, 0x40, 0x96, 0x00};
-	UCHAR			MICMN[16];
-	UCHAR			CalcMicBuffer[80];
-	ULONG			CalcMicBufferLen = 0;
-#endif // LEAP_SUPPORT //
 	USHORT			Status;
 
 	// Block all authentication request durning WPA block period
@@ -738,7 +695,6 @@
 			FrameLen += tmp;
 		}
 
-#ifdef DOT11_N_SUPPORT
 		// HT
 		if ((pAd->MlmeAux.HtCapabilityLen > 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
 		{
@@ -765,7 +721,6 @@
 			}
 			FrameLen += TmpLen;
 		}
-#endif // DOT11_N_SUPPORT //
 
 		// add Ralink proprietary IE to inform AP this STA is going to use AGGREGATION or PIGGY-BACK+AGGREGATION
 		// Case I: (Aggregation + Piggy-Back)
@@ -805,73 +760,6 @@
 							  END_OF_ARGS);
 			FrameLen += TmpLen;
 		}
-#ifdef LEAP_SUPPORT
-		if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-		{
-			CkipFlag = pAd->StaCfg.CkipFlag;	// We have update that at PeerBeaconAtJoinRequest()
-			if (CkipFlag != 0)
-			{
-				NdisZeroMemory(CkipNegotiationBuffer, CKIP_NEGOTIATION_LENGTH);
-				CkipNegotiationBuffer[2] = 0x66;
-				// Make it try KP & MIC, since we have to follow the result from AssocRsp
-				CkipNegotiationBuffer[8] = 0x18;
-				CkipNegotiationBuffer[CKIP_NEGOTIATION_LENGTH - 1] = 0x22;
-
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &tmp,
-									1,                              &AironetCkipIe,
-									1,                              &AironetCkipLen,
-									AironetCkipLen,                 CkipNegotiationBuffer,
-									END_OF_ARGS);
-				FrameLen += tmp;
-			}
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-							1,                              &AironetIPAddressIE,
-							1,                              &AironetIPAddressLen,
-							AironetIPAddressLen,            AironetIPAddressBuffer,
-							END_OF_ARGS);
-			FrameLen += tmp;
-
-			//
-			// The RN is incremented before each reassociation request.
-			//
-			pAd->StaCfg.CCKMRN++;
-			//
-			// Calculate MIC = hmac-md5(krk, STA-ID|BSSID|RSNIE|TSF|RN);
-			//
-			COPY_MAC_ADDR(CalcMicBuffer, pAd->CurrentAddress);
-			CalcMicBufferLen = MAC_ADDR_LEN;
-			COPY_MAC_ADDR(CalcMicBuffer + CalcMicBufferLen, pAd->MlmeAux.Bssid);
-			CalcMicBufferLen += MAC_ADDR_LEN;
-			NdisMoveMemory(CalcMicBuffer + CalcMicBufferLen, CipherSuiteCiscoCCKM, CipherSuiteCiscoCCKMLen);
-			CalcMicBufferLen += CipherSuiteCiscoCCKMLen;
-			NdisMoveMemory(CalcMicBuffer + CalcMicBufferLen, (PUCHAR) &pAd->StaCfg.CCKMBeaconAtJoinTimeStamp, sizeof(pAd->StaCfg.CCKMBeaconAtJoinTimeStamp));
-			CalcMicBufferLen += sizeof(pAd->StaCfg.CCKMBeaconAtJoinTimeStamp);
-			NdisMoveMemory(CalcMicBuffer + CalcMicBufferLen, (PUCHAR)&pAd->StaCfg.CCKMRN, sizeof(pAd->StaCfg.CCKMRN));
-			CalcMicBufferLen += sizeof(pAd->StaCfg.CCKMRN);
-			hmac_md5(pAd->StaCfg.KRK, LEN_EAP_MICK, CalcMicBuffer, CalcMicBufferLen, MICMN);
-
-			//
-			// fill up CCKM reassociation request element
-			//
-			NdisMoveMemory(AironetCCKMReassocBuffer, AironetOUI, 4);
-			NdisMoveMemory(AironetCCKMReassocBuffer + 4, (PUCHAR)&pAd->StaCfg.CCKMBeaconAtJoinTimeStamp, 8);
-			NdisMoveMemory(AironetCCKMReassocBuffer + 12, (PUCHAR) &pAd->StaCfg.CCKMRN, 4);
-			NdisMoveMemory(AironetCCKMReassocBuffer +16, MICMN, 8);
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-							1,                      &AironetCCKMReassocIE,
-							1,                      &AironetCCKMReassocLen,
-							AironetCCKMReassocLen,  AironetCCKMReassocBuffer,
-							END_OF_ARGS);
-			FrameLen += tmp;
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-							CipherSuiteCiscoCCKMLen,CipherSuiteCiscoCCKM,
-							END_OF_ARGS);
-			FrameLen += tmp;
-		}
-#endif // LEAP_SUPPORT //
 
 		// Add CCX v2 request if CCX2 admin state is on
 		if (pAd->StaCfg.CCXControl.field.Enable == 1)
@@ -927,36 +815,6 @@
 	ULONG                 Timeout = 0;
 	USHORT                Status;
 
-#ifdef QOS_DLS_SUPPORT
-	// send DLS-TEAR_DOWN message,
-	if (pAd->CommonCfg.bDLSCapable)
-	{
-		UCHAR i;
-
-		// tear down local dls table entry
-		for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-			{
-				RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			}
-		}
-
-		// tear down peer dls table entry
-		for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-			{
-				RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			}
-		}
-	}
-#endif // QOS_DLS_SUPPORT //
-
 	// skip sanity check
 	pDisassocReq = (PMLME_DISASSOC_REQ_STRUCT)(Elem->Msg);
 
@@ -999,27 +857,11 @@
 	RTMPSetTimer(&pAd->MlmeAux.DisassocTimer, Timeout); /* in mSec */
 	pAd->Mlme.AssocMachine.CurrState = DISASSOC_WAIT_RSP;
 
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-    if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-	{
-        union iwreq_data    wrqu;
-        //send disassociate event to wpa_supplicant
-        memset(&wrqu, 0, sizeof(wrqu));
-        wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-    }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
     {
         union iwreq_data    wrqu;
         memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
         wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
     }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
 }
 
 /*
@@ -1057,31 +899,15 @@
 		if(MAC_ADDR_EQUAL(Addr2, pAd->MlmeAux.Bssid))
 		{
 			DBGPRINT(RT_DEBUG_TRACE, ("PeerAssocRspAction():ASSOC - receive ASSOC_RSP to me (status=%d)\n", Status));
-#ifdef DOT11_N_SUPPORT
 			DBGPRINT(RT_DEBUG_TRACE, ("PeerAssocRspAction():MacTable [%d].AMsduSize = %d. ClientStatusFlags = 0x%lx \n",Elem->Wcid, pAd->MacTab.Content[BSSID_WCID].AMsduSize, pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
-#endif // DOT11_N_SUPPORT //
 			RTMPCancelTimer(&pAd->MlmeAux.AssocTimer, &TimerCancelled);
 			if(Status == MLME_SUCCESS)
 			{
+#ifdef RT2860
 				// go to procedure listed on page 376
 				AssocPostProc(pAd, Addr2, CapabilityInfo, Aid, SupRate, SupRateLen, ExtRate, ExtRateLen,
 					&EdcaParm, &HtCapability, HtCapabilityLen, &AddHtInfo);
 
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-                if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-                {
-                    union iwreq_data    wrqu;
-
-                    SendAssocIEsToWpaSupplicant(pAd);
-                    memset(&wrqu, 0, sizeof(wrqu));
-                    wrqu.data.flags = RT_ASSOC_EVENT_FLAG;
-                    wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-                }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
                 {
                     union iwreq_data    wrqu;
                     wext_notify_event_assoc(pAd);
@@ -1091,9 +917,29 @@
                     wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
 
                 }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
+#endif
+#ifdef RT2870
+				UCHAR			MaxSupportedRateIn500Kbps = 0;
+				UCHAR			idx;
 
+				// supported rates array may not be sorted. sort it and find the maximum rate
+			    for (idx=0; idx<SupRateLen; idx++)
+                {
+			        if (MaxSupportedRateIn500Kbps < (SupRate[idx] & 0x7f))
+			            MaxSupportedRateIn500Kbps = SupRate[idx] & 0x7f;
+			    }
 
+				for (idx=0; idx<ExtRateLen; idx++)
+			    {
+			        if (MaxSupportedRateIn500Kbps < (ExtRate[idx] & 0x7f))
+			            MaxSupportedRateIn500Kbps = ExtRate[idx] & 0x7f;
+                }
+				// go to procedure listed on page 376
+				AssocPostProc(pAd, Addr2, CapabilityInfo, Aid, SupRate, SupRateLen, ExtRate, ExtRateLen,
+					&EdcaParm, &HtCapability, HtCapabilityLen, &AddHtInfo);
+
+				StaAddMacTableEntry(pAd, &pAd->MacTab.Content[BSSID_WCID], MaxSupportedRateIn500Kbps, &HtCapability, HtCapabilityLen, CapabilityInfo);
+#endif
 				pAd->StaCfg.CkipFlag = CkipFlag;
 				if (CkipFlag & 0x18)
 				{
@@ -1109,14 +955,6 @@
 			}
 			else
 			{
-				// Faile on Association, we need to check the status code
-				// Is that a Rogue AP?
-#ifdef LEAP_SUPPORT
-				if ((pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP) && (Status == MLME_ALG_NOT_SUPPORT))
-				{ //Possibly Rogue AP
-					RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, pAd->MlmeAux.Bssid, LEAP_REASON_INVALID_AUTH);
-				}
-#endif // LEAP_SUPPORT //
 			}
 			pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
 			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
@@ -1172,21 +1010,6 @@
 				AssocPostProc(pAd, Addr2, CapabilityInfo, Aid, SupRate, SupRateLen, ExtRate, ExtRateLen,
 					 &EdcaParm, &HtCapability, HtCapabilityLen, &AddHtInfo);
 
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-                if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-                {
-                    union iwreq_data    wrqu;
-
-                    SendAssocIEsToWpaSupplicant(pAd);
-                    memset(&wrqu, 0, sizeof(wrqu));
-                    wrqu.data.flags = RT_ASSOC_EVENT_FLAG;
-                    wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-                }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
                 {
                     union iwreq_data    wrqu;
                     wext_notify_event_assoc(pAd);
@@ -1196,41 +1019,9 @@
                     wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
 
                 }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
 
 			}
 
-			//
-			// Cisco Leap CCKM supported Re-association.
-			//
-#ifdef LEAP_SUPPORT
-			if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-			{
-				if (CCKMAssocRspSanity(pAd, Elem->Msg, Elem->MsgLen) == TRUE)
-				{
-					pAd->StaCfg.CkipFlag = CkipFlag;
-					if (CkipFlag & 0x18)
-					{
-						NdisZeroMemory(pAd->StaCfg.TxSEQ, 4);
-						NdisZeroMemory(pAd->StaCfg.RxSEQ, 4);
-						NdisZeroMemory(pAd->StaCfg.CKIPMIC, 4);
-						pAd->StaCfg.GIV[0] = RandomByte(pAd);
-						pAd->StaCfg.GIV[1] = RandomByte(pAd);
-						pAd->StaCfg.GIV[2] = RandomByte(pAd);
-						pAd->StaCfg.bCkipOn = TRUE;
-						DBGPRINT(RT_DEBUG_TRACE, ("<CCX> pAd->StaCfg.CkipFlag = 0x%02x\n", pAd->StaCfg.CkipFlag));
-					}
-
-					pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-					MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - CCKMAssocRspSanity() sanity check fail\n"));
-				}
-			}
-			else
-#endif // LEAP_SUPPORT //
 			{
 				// CkipFlag is no use for reassociate
 				pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
@@ -1275,7 +1066,7 @@
 	COPY_MAC_ADDR(pAd->MlmeAux.Bssid, pAddr2);
 	pAd->MlmeAux.Aid = Aid;
 	pAd->MlmeAux.CapabilityInfo = CapabilityInfo & SUPPORTED_CAPABILITY_INFO;
-#ifdef DOT11_N_SUPPORT
+
 	// Some HT AP might lost WMM IE. We add WMM ourselves. beacuase HT requires QoS on.
 	if ((HtCapabilityLen > 0) && (pEdcaParm->bValid == FALSE))
 	{
@@ -1301,7 +1092,6 @@
 		pEdcaParm->Txop[3]  = 48;
 
 	}
-#endif // DOT11_N_SUPPORT //
 
 	NdisMoveMemory(&pAd->MlmeAux.APEdcaParm, pEdcaParm, sizeof(EDCA_PARM));
 
@@ -1315,7 +1105,6 @@
 	NdisMoveMemory(pAd->MlmeAux.ExtRate, ExtRate, ExtRateLen);
 	RTMPCheckRates(pAd, pAd->MlmeAux.ExtRate, &pAd->MlmeAux.ExtRateLen);
 
-#ifdef DOT11_N_SUPPORT
 	if (HtCapabilityLen > 0)
 	{
 		RTMPCheckHt(pAd, BSSID_WCID, pHtCapability, pAddHtInfo);
@@ -1324,7 +1113,6 @@
 
 	DBGPRINT(RT_DEBUG_TRACE, ("AssocPostProc===>    (Mmps=%d, AmsduSize=%d, )\n",
 		pAd->MacTab.Content[BSSID_WCID].MmpsMode, pAd->MacTab.Content[BSSID_WCID].AMsduSize));
-#endif // DOT11_N_SUPPORT //
 
 	// Set New WPA information
 	Idx = BssTableSearch(&pAd->ScanTab, pAddr2, pAd->MlmeAux.Channel);
@@ -1414,21 +1202,6 @@
 				RTMPSendWirelessEvent(pAd, IW_DISASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
 			}
 
-
-#ifdef LEAP_SUPPORT
-			if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-			{
-				// Cisco_LEAP has start a timer
-				// We should cancel it if using LEAP
-				RTMPCancelTimer(&pAd->StaCfg.LeapAuthTimer, &TimerCancelled);
-				//Check is it mach the LEAP Authentication failed as possible a Rogue AP
-				//on it's PortSecured not equal to WPA_802_1X_PORT_SECURED while process the Association.
-				if ((pAd->Mlme.LeapMachine.CurrState != LEAP_IDLE) && (pAd->StaCfg.PortSecured != WPA_802_1X_PORT_SECURED))
-				{
-					RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, Addr2, LEAP_REASON_AUTH_TIMEOUT);
-				}
-			}
-#endif	// LEAP_SUPPORT //
 			//
 			// Get Current System time and Turn on AdjacentAPReport
 			//
@@ -1437,26 +1210,11 @@
 			LinkDown(pAd, TRUE);
 			pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
 
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-			{
-                union iwreq_data    wrqu;
-                //send disassociate event to wpa_supplicant
-                memset(&wrqu, 0, sizeof(wrqu));
-                wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-                wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
             {
                 union iwreq_data    wrqu;
                 memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
                 wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
             }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
 		}
 	}
 	else
@@ -1739,36 +1497,6 @@
 	}
 }
 
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-VOID    SendAssocIEsToWpaSupplicant(
-    IN  PRTMP_ADAPTER pAd)
-{
-    union iwreq_data    wrqu;
-    unsigned char custom[IW_CUSTOM_MAX] = {0};
-
-    if ((pAd->StaCfg.ReqVarIELen + 17) <= IW_CUSTOM_MAX)
-    {
-        sprintf(custom, "ASSOCINFO_ReqIEs=");
-	    NdisMoveMemory(custom+17, pAd->StaCfg.ReqVarIEs, pAd->StaCfg.ReqVarIELen);
-	    memset(&wrqu, 0, sizeof(wrqu));
-        wrqu.data.length = pAd->StaCfg.ReqVarIELen + 17;
-        wrqu.data.flags = RT_REQIE_EVENT_FLAG;
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, custom);
-
-        memset(&wrqu, 0, sizeof(wrqu));
-        wrqu.data.flags = RT_ASSOCINFO_EVENT_FLAG;
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-    }
-    else
-        DBGPRINT(RT_DEBUG_TRACE, ("pAd->StaCfg.ReqVarIELen + 17 > MAX_CUSTOM_LEN\n"));
-
-    return;
-}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
 int wext_notify_event_assoc(
 	IN  RTMP_ADAPTER *pAd)
 {
@@ -1791,7 +1519,7 @@
         wrqu.data.length = (pAd->StaCfg.ReqVarIELen*2) + 17;
         sprintf(custom, "ASSOCINFO(ReqIEs=");
         for (idx=0; idx<pAd->StaCfg.ReqVarIELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAd->StaCfg.ReqVarIEs[idx]);
+                sprintf(custom + strlen(custom), "%02x", pAd->StaCfg.ReqVarIEs[idx]);
         wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, custom);
     }
     else
@@ -1801,5 +1529,227 @@
 	return 0;
 
 }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
 
+#ifdef RT2870
+BOOLEAN StaAddMacTableEntry(
+	IN  PRTMP_ADAPTER		pAd,
+	IN  PMAC_TABLE_ENTRY	pEntry,
+	IN  UCHAR				MaxSupportedRateIn500Kbps,
+	IN  HT_CAPABILITY_IE	*pHtCapability,
+	IN  UCHAR				HtCapabilityLen,
+	IN  USHORT        		CapabilityInfo)
+{
+	UCHAR            MaxSupportedRate = RATE_11;
+
+	if (ADHOC_ON(pAd))
+		CLIENT_STATUS_CLEAR_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
+
+	switch (MaxSupportedRateIn500Kbps)
+    {
+        case 108: MaxSupportedRate = RATE_54;   break;
+        case 96:  MaxSupportedRate = RATE_48;   break;
+        case 72:  MaxSupportedRate = RATE_36;   break;
+        case 48:  MaxSupportedRate = RATE_24;   break;
+        case 36:  MaxSupportedRate = RATE_18;   break;
+        case 24:  MaxSupportedRate = RATE_12;   break;
+        case 18:  MaxSupportedRate = RATE_9;    break;
+        case 12:  MaxSupportedRate = RATE_6;    break;
+        case 22:  MaxSupportedRate = RATE_11;   break;
+        case 11:  MaxSupportedRate = RATE_5_5;  break;
+        case 4:   MaxSupportedRate = RATE_2;    break;
+        case 2:   MaxSupportedRate = RATE_1;    break;
+        default:  MaxSupportedRate = RATE_11;   break;
+    }
+
+    if ((pAd->CommonCfg.PhyMode == PHY_11G) && (MaxSupportedRate < RATE_FIRST_OFDM_RATE))
+        return FALSE;
+
+	// 11n only
+	if (((pAd->CommonCfg.PhyMode == PHY_11N_2_4G) || (pAd->CommonCfg.PhyMode == PHY_11N_5G))&& (HtCapabilityLen == 0))
+		return FALSE;
+
+	if (!pEntry)
+        return FALSE;
+
+	NdisAcquireSpinLock(&pAd->MacTabLock);
+	if (pEntry)
+	{
+		pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
+		if ((MaxSupportedRate < RATE_FIRST_OFDM_RATE) ||
+			(pAd->CommonCfg.PhyMode == PHY_11B))
+		{
+			pEntry->RateLen = 4;
+			if (MaxSupportedRate >= RATE_FIRST_OFDM_RATE)
+				MaxSupportedRate = RATE_11;
+		}
+		else
+			pEntry->RateLen = 12;
+
+		pEntry->MaxHTPhyMode.word = 0;
+		pEntry->MinHTPhyMode.word = 0;
+		pEntry->HTPhyMode.word = 0;
+		pEntry->MaxSupportedRate = MaxSupportedRate;
+		if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
+		{
+			pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
+			pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
+			pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
+			pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
+			pEntry->HTPhyMode.field.MODE = MODE_CCK;
+			pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
+		}
+		else
+		{
+			pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
+			pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
+			pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
+			pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
+			pEntry->HTPhyMode.field.MODE = MODE_OFDM;
+			pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
+		}
+		pEntry->CapabilityInfo = CapabilityInfo;
+		CLIENT_STATUS_CLEAR_FLAG(pEntry, fCLIENT_STATUS_AGGREGATION_CAPABLE);
+		CLIENT_STATUS_CLEAR_FLAG(pEntry, fCLIENT_STATUS_PIGGYBACK_CAPABLE);
+	}
+
+	// If this Entry supports 802.11n, upgrade to HT rate.
+	if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
+	{
+		UCHAR	j, bitmask; //k,bitmask;
+		CHAR    i;
+
+		if (ADHOC_ON(pAd))
+			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
+		if ((pHtCapability->HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
+		{
+			pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
+		}
+		else
+		{
+			pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
+			pAd->MacTab.fAnyStationNonGF = TRUE;
+			pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
+		}
+
+		if ((pHtCapability->HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
+		{
+			pEntry->MaxHTPhyMode.field.BW= BW_40;
+			pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(pHtCapability->HtCapInfo.ShortGIfor40));
+		}
+		else
+		{
+			pEntry->MaxHTPhyMode.field.BW = BW_20;
+			pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(pHtCapability->HtCapInfo.ShortGIfor20));
+			pAd->MacTab.fAnyStation20Only = TRUE;
+		}
+
+		// 3*3
+		if (pAd->MACVersion >= RALINK_2883_VERSION && pAd->MACVersion < RALINK_3070_VERSION)
+			pEntry->MaxHTPhyMode.field.TxBF = pAd->CommonCfg.RegTransmitSetting.field.TxBF;
+
+		// find max fixed rate
+		for (i=23; i>=0; i--) // 3*3
+		{
+			j = i/8;
+			bitmask = (1<<(i-(j*8)));
+			if ((pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j] & bitmask) && (pHtCapability->MCSSet[j] & bitmask))
+			{
+				pEntry->MaxHTPhyMode.field.MCS = i;
+				break;
+			}
+			if (i==0)
+				break;
+		}
+
+
+		if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
+		{
+			if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
+			{
+				// Fix MCS as HT Duplicated Mode
+				pEntry->MaxHTPhyMode.field.BW = 1;
+				pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
+				pEntry->MaxHTPhyMode.field.STBC = 0;
+				pEntry->MaxHTPhyMode.field.ShortGI = 0;
+				pEntry->MaxHTPhyMode.field.MCS = 32;
+			}
+			else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
+			{
+				// STA supports fixed MCS
+				pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
+			}
+		}
+
+		pEntry->MaxHTPhyMode.field.STBC = (pHtCapability->HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
+		pEntry->MpduDensity = pHtCapability->HtCapParm.MpduDensity;
+		pEntry->MaxRAmpduFactor = pHtCapability->HtCapParm.MaxRAmpduFactor;
+		pEntry->MmpsMode = (UCHAR)pHtCapability->HtCapInfo.MimoPs;
+		pEntry->AMsduSize = (UCHAR)pHtCapability->HtCapInfo.AMsduSize;
+		pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
+
+		if (pAd->CommonCfg.DesiredHtPhy.AmsduEnable && (pAd->CommonCfg.REGBACapability.field.AutoBA == FALSE))
+			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_AMSDU_INUSED);
+		if (pHtCapability->HtCapInfo.ShortGIfor20)
+			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
+		if (pHtCapability->HtCapInfo.ShortGIfor40)
+			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
+		if (pHtCapability->HtCapInfo.TxSTBC)
+			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
+		if (pHtCapability->HtCapInfo.RxSTBC)
+			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
+		if (pHtCapability->ExtHtCapInfo.PlusHTC)
+			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
+		if (pAd->CommonCfg.bRdg && pHtCapability->ExtHtCapInfo.RDGSupport)
+			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
+		if (pHtCapability->ExtHtCapInfo.MCSFeedback == 0x03)
+			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
+	}
+	else
+	{
+		pAd->MacTab.fAnyStationIsLegacy = TRUE;
+	}
+
+	NdisMoveMemory(&pEntry->HTCapability, pHtCapability, sizeof(HT_CAPABILITY_IE));
+
+	pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
+	pEntry->CurrTxRate = pEntry->MaxSupportedRate;
+
+	// Set asic auto fall back
+	if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
+	{
+		PUCHAR					pTable;
+		UCHAR					TableSize = 0;
+
+		MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
+		pEntry->bAutoTxRateSwitch = TRUE;
+	}
+	else
+	{
+		pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
+		pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
+		pEntry->bAutoTxRateSwitch = FALSE;
+
+		// If the legacy mode is set, overwrite the transmit setting of this entry.
+		RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
+	}
+
+	pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
+	pEntry->Sst = SST_ASSOC;
+	pEntry->AuthState = AS_AUTH_OPEN;
+	pEntry->AuthMode = pAd->StaCfg.AuthMode;
+	pEntry->WepStatus = pAd->StaCfg.WepStatus;
+
+	NdisReleaseSpinLock(&pAd->MacTabLock);
+
+    {
+        union iwreq_data    wrqu;
+        wext_notify_event_assoc(pAd);
+
+        memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
+        memcpy(wrqu.ap_addr.sa_data, pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
+        wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
+
+    }
+	return TRUE;
+}
+#endif /* RT2870 */
diff --git a/drivers/staging/rt2860/sta/auth.c b/drivers/staging/rt2860/sta/auth.c
index 73fb8d6e..d8414ea 100644
--- a/drivers/staging/rt2860/sta/auth.c
+++ b/drivers/staging/rt2860/sta/auth.c
@@ -218,15 +218,9 @@
             {
                 // Authentication Mode "LEAP" has allow for CCX 1.X
                 if ((pAd->MlmeAux.Alg == Ndis802_11AuthModeOpen)
-#ifdef LEAP_SUPPORT
-					|| (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
 				)
                 {
                     pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-#ifdef LEAP_SUPPORT
-                    pAd->Mlme.LeapMachine.CurrState = LEAP_IDLE;
-#endif // LEAP_SUPPORT //
                     MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
                 }
                 else
@@ -282,14 +276,6 @@
             }
             else
             {
-#ifdef LEAP_SUPPORT
-                if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-                {
-                    //Invalid Authentication possible rogue AP
-                    //Add this Ap to Rogue AP.
-                    RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, Addr2, LEAP_REASON_INVALID_AUTH);
-				}
-#endif // LEAP_SUPPORT //
                 pAd->StaCfg.AuthFailReason = Status;
                 COPY_MAC_ADDR(pAd->StaCfg.AuthFailSta, Addr2);
                 pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
diff --git a/drivers/staging/rt2860/sta/auth_rsp.c b/drivers/staging/rt2860/sta/auth_rsp.c
index f7aa4b9..cc639b1 100644
--- a/drivers/staging/rt2860/sta/auth_rsp.c
+++ b/drivers/staging/rt2860/sta/auth_rsp.c
@@ -127,36 +127,17 @@
         {
             DBGPRINT(RT_DEBUG_TRACE,("AUTH_RSP - receive DE-AUTH from our AP (Reason=%d)\n", Reason));
 
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
             {
                 union iwreq_data    wrqu;
                 memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
                 wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
             }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
 
 			// send wireless event - for deauthentication
 			if (pAd->CommonCfg.bWirelessEvent)
 				RTMPSendWirelessEvent(pAd, IW_DEAUTH_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
 
             LinkDown(pAd, TRUE);
-
-            // Authentication Mode Cisco_LEAP has start a timer
-            // We should cancel it if using LEAP
-#ifdef LEAP_SUPPORT
-            if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-            {
-                RTMPCancelTimer(&pAd->StaCfg.LeapAuthTimer, &TimerCancelled);
-                //Check is it mach the LEAP Authentication failed as possible a Rogue AP
-                //on it's PortSecured not equal to WPA_802_1X_PORT_SECURED while process the Authenticaton.
-                if ((pAd->StaCfg.PortSecured != WPA_802_1X_PORT_SECURED) && (pAd->Mlme.LeapMachine.CurrState != LEAP_IDLE))
-                {
-                    RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, Addr2, LEAP_REASON_AUTH_TIMEOUT);
-                }
-            }
-#endif // LEAP_SUPPORT //
         }
     }
     else
diff --git a/drivers/staging/rt2860/sta/connect.c b/drivers/staging/rt2860/sta/connect.c
index d8bcc766..ac71351 100644
--- a/drivers/staging/rt2860/sta/connect.c
+++ b/drivers/staging/rt2860/sta/connect.c
@@ -178,13 +178,6 @@
 					pAd->bLedOnScanning = FALSE;
 					RTMPSetLED(pAd, pAd->LedStatus);
 				}
-#ifdef DOT11N_DRAFT3
-				// AP sent a 2040Coexistence mgmt frame, then station perform a scan, and then send back the respone.
-				if (pAd->CommonCfg.BSSCoexist2040.field.InfoReq == 1)
-				{
-					Update2040CoexistFrameAndNotify(pAd, BSSID_WCID, TRUE);
-				}
-#endif // DOT11N_DRAFT3 //
 			}
 			break;
 
@@ -195,6 +188,38 @@
 				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
 			}
 			break;
+#ifdef RT2870
+		//
+		// This state is for that we want to connect to an AP but
+		// it didn't find on BSS List table. So we need to scan the air first,
+		// after that we can try to connect to the desired AP if available.
+		//
+		case CNTL_WAIT_SCAN_FOR_CONNECT:
+			if(Elem->MsgType == MT2_SCAN_CONF)
+			{
+				// Resume TxRing after SCANING complete. We hope the out-of-service time
+				// won't be too long to let upper layer time-out the waiting frames
+				RTMPResumeMsduTransmission(pAd);
+#ifdef CCX_SUPPORT
+				if (pAd->StaCfg.CCXReqType != MSRN_TYPE_UNUSED)
+				{
+					// Cisco scan request is finished, prepare beacon report
+					MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_DONE, 0, NULL);
+				}
+#endif // CCX_SUPPORT //
+				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
+
+				//
+				// Check if we can connect to.
+				//
+				BssTableSsidSort(pAd, &pAd->MlmeAux.SsidBssTab, pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen);
+				if (pAd->MlmeAux.SsidBssTab.BssNr > 0)
+				{
+					MlmeAutoReconnectLastSSID(pAd);
+				}
+			}
+			break;
+#endif // RT2870 //
 		default:
 			DBGPRINT_ERR(("!ERROR! CNTL - Illegal message type(=%ld)", Elem->MsgType));
 			break;
@@ -234,19 +259,11 @@
 			break;
 
 		case OID_802_11_DISASSOCIATE:
-#ifdef RALINK_ATE
-			if(ATE_ON(pAd))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
 			DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
 			MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ, sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
 			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_DISASSOC;
-#ifdef WPA_SUPPLICANT_SUPPORT
+
             if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_ENABLE_WITH_WEB_UI)
-#endif // WPA_SUPPLICANT_SUPPORT //
             {
     			// Set the AutoReconnectSsid to prevent it reconnect to old SSID
     			// Since calling this indicate user don't want to connect to that SSID anymore.
@@ -263,12 +280,6 @@
             WpaMicFailureReportFrame(pAd, Elem);
             break;
 
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_SET_DLS_PARAM:
-			CntlOidDLSSetupProc(pAd, Elem);
-			break;
-#endif // QOS_DLS_SUPPORT //
-
 		default:
 			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Illegal message in CntlIdleProc(MsgType=%ld)\n",Elem->MsgType));
 			break;
@@ -283,13 +294,6 @@
 	ULONG                      BssIdx = BSS_NOT_FOUND;
 	BSS_ENTRY                  CurrBss;
 
-#ifdef RALINK_ATE
-/* Disable scanning when ATE is running. */
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-
 	// record current BSS if network is connected.
 	// 2003-2-13 do not include current IBSS if this is the only STA in this IBSS.
 	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
@@ -337,9 +341,11 @@
 	MLME_DISASSOC_REQ_STRUCT   DisassocReq;
 	ULONG					   Now;
 
+#ifdef RT2860
 	// BBP and RF are not accessible in PS mode, we has to wake them up first
 	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
 		AsicForceWakeup(pAd, RTMP_HALT);
+#endif
 
 	// Step 1. record the desired user settings to MlmeAux
 	NdisZeroMemory(pAd->MlmeAux.Ssid, MAX_LEN_OF_SSID);
@@ -377,9 +383,6 @@
 			 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
 			 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
 			 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-#ifdef LEAP_SUPPORT
-			 || (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
 			 ) &&
 			(pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
 		{
@@ -420,7 +423,7 @@
 			}
 
 			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
+
             {
                 union iwreq_data    wrqu;
 
@@ -429,7 +432,6 @@
                 wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
 
             }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
 		}
 	}
 	else if (INFRA_ON(pAd))
@@ -513,12 +515,6 @@
 	MLME_DISASSOC_REQ_STRUCT    DisassocReq;
 	MLME_JOIN_REQ_STRUCT        JoinReq;
 
-#ifdef RALINK_ATE
-/* No need to perform this routine when ATE is running. */
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
 	// record user desired settings
 	COPY_MAC_ADDR(pAd->MlmeAux.Bssid, pOidBssid);
 	pAd->MlmeAux.BssType = pAd->StaCfg.BssType;
@@ -558,7 +554,7 @@
 		// already connected to the same BSSID, go back to idle state directly
 		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - already in this BSSID. ignore this SET_BSSID request\n"));
 		pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
+
             {
                 union iwreq_data    wrqu;
 
@@ -567,7 +563,6 @@
                 wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
 
             }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
 	}
 	else
 	{
@@ -672,113 +667,6 @@
 	IterateOnBssTab(pAd);
 }
 
-#ifdef QOS_DLS_SUPPORT
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlOidDLSSetupProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PRT_802_11_DLS		pDLS = (PRT_802_11_DLS)Elem->Msg;
-	MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-	INT					i;
-	USHORT				reason = REASON_UNSPECIFY;
-
-	DBGPRINT(RT_DEBUG_TRACE,("CNTL - (OID set %02x:%02x:%02x:%02x:%02x:%02x with Valid=%d, Status=%d, TimeOut=%d, CountDownTimer=%d)\n",
-		pDLS->MacAddr[0], pDLS->MacAddr[1], pDLS->MacAddr[2], pDLS->MacAddr[3], pDLS->MacAddr[4], pDLS->MacAddr[5],
-		pDLS->Valid, pDLS->Status, pDLS->TimeOut, pDLS->CountDownTimer));
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return;
-
-	// DLS will not be supported when Adhoc mode
-	if (INFRA_ON(pAd))
-	{
-		for (i = 0; i < MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				(pDLS->TimeOut == pAd->StaCfg.DLSEntry[i].TimeOut) && MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 1. Same setting, just drop it
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - setting unchanged\n"));
-				break;
-			}
-			else if (!pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 2. Disable DLS link case, just tear down DLS link
-				reason = REASON_QOS_UNWANTED_MECHANISM;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - start tear down procedure\n"));
-				break;
-			}
-			else if ((i < MAX_NUM_OF_DLS_ENTRY) && pDLS->Valid && !pAd->StaCfg.DLSEntry[i].Valid)
-			{
-				// 3. Enable case, start DLS setup procedure
-				NdisMoveMemory(&pAd->StaCfg.DLSEntry[i], pDLS, sizeof(RT_802_11_DLS_UI));
-
-				//Update countdown timer
-				pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS setup case\n"));
-				break;
-			}
-			else if ((i < MAX_NUM_OF_DLS_ENTRY) && pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
-				(pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) && !MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 4. update mac case, tear down old DLS and setup new DLS
-				reason = REASON_QOS_UNWANTED_MECHANISM;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				NdisMoveMemory(&pAd->StaCfg.DLSEntry[i], pDLS, sizeof(RT_802_11_DLS_UI));
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS tear down and restart case\n"));
-				break;
-			}
-			else if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
-				MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr) && (pAd->StaCfg.DLSEntry[i].TimeOut != pDLS->TimeOut))
-			{
-				// 5. update timeout case, start DLS setup procedure (no tear down)
-				pAd->StaCfg.DLSEntry[i].TimeOut	= pDLS->TimeOut;
-				//Update countdown timer
-				pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS update timeout case\n"));
-				break;
-			}
-			else if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
-				(pAd->StaCfg.DLSEntry[i].Status != DLS_FINISH) && MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 6. re-setup case, start DLS setup procedure (no tear down)
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS retry setup procedure\n"));
-				break;
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN,("CNTL - DLS not changed in entry - %d - Valid=%d, Status=%d, TimeOut=%d\n",
-					i, pAd->StaCfg.DLSEntry[i].Valid, pAd->StaCfg.DLSEntry[i].Status, pAd->StaCfg.DLSEntry[i].TimeOut));
-			}
-		}
-	}
-}
-#endif // QOS_DLS_SUPPORT //
-
 /*
 	==========================================================================
 	Description:
@@ -870,14 +758,6 @@
 			// 2. joined a new INFRA network, start from authentication
 			else
 			{
-#ifdef LEAP_SUPPORT
-				// Add AuthMode "LEAP" for CCX 1.X
-				if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-				{
-					AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, CISCO_AuthModeLEAP);
-				}
-				else
-#endif // LEAP_SUPPORT //
 				{
 					// either Ndis802_11AuthModeShared or Ndis802_11AuthModeAutoSwitch, try shared key first
 					if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeShared) ||
@@ -937,7 +817,7 @@
 				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Channel=%d, Start adhoc on W53(52,56,60,64) Channels are not accepted\n", pAd->CommonCfg.Channel));
 				return;
 			}
-#ifdef DOT11_N_SUPPORT
+
 			if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
 			{
 				N_ChannelCheck(pAd);
@@ -961,7 +841,6 @@
 				}
 			}
 			else
-#endif // DOT11_N_SUPPORT //
 			{
 				pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
 			}
@@ -974,9 +853,6 @@
 			{
 				pAd->CommonCfg.RadarDetect.RDMode = RD_SILENCE_MODE;
 				pAd->CommonCfg.RadarDetect.RDCount = 0;
-#ifdef DFS_SUPPORT
-				BbpRadarDetectionStart(pAd);
-#endif // DFS_SUPPORT //
 			}
 
 			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - start a new IBSS = %02x:%02x:%02x:%02x:%02x:%02x ...\n",
@@ -1016,21 +892,6 @@
 			AssocParmFill(pAd, &AssocReq, pAd->MlmeAux.Bssid, pAd->MlmeAux.CapabilityInfo,
 						  ASSOC_TIMEOUT, pAd->StaCfg.DefaultListenCount);
 
-#ifdef LEAP_SUPPORT
-			//
-			// Cisco Leap CCKM supported Re-association.
-			//
-			if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-			{
-				//if CCKM is turn on , that's mean Fast Reauthentication
-				//Use CCKM Reassociation instead of normal association for Fast Roaming.
-				MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_REASSOC_REQ,
-							sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
-
-				pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_REASSOC;
-			}
-			else
-#endif // LEAP_SUPPORT //
 			{
 				MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_ASSOC_REQ,
 							sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
@@ -1044,14 +905,7 @@
 			// ageing-out. The previous authentication attempt must have let it remove us.
 			// so try Authentication again may help. For D-Link DWL-900AP+ compatibility.
 			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH FAIL, try again...\n"));
-#ifdef LEAP_SUPPORT
-			//Add AuthMode "LEAP" for CCX 1.X
-			if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-			{
-				AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, CISCO_AuthModeLEAP);
-			}
-			else
-#endif // LEAP_SUPPORT //
+
 			{
 				if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeShared) ||
 					(pAd->StaCfg.AuthMode == Ndis802_11AuthModeAutoSwitch))
@@ -1103,20 +957,6 @@
 		}
 		else
 		{
-#ifdef LEAP_SUPPORT
-			// Process LEAP first, since it use different control variable
-			// We don't want to affect other poven operation
-			if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-			{
-				// LEAP Auth not success, try next BSS
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - *LEAP* AUTH FAIL, give up; try next BSS\n"));
-				DBGPRINT(RT_DEBUG_TRACE, ("Total match BSSID [=%d]\n", pAd->MlmeAux.SsidBssTab.BssNr));
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-				pAd->MlmeAux.BssIdx++;
-				IterateOnBssTab(pAd);
-			}
-			else
-#endif // LEAP_SUPPORT //
 			if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeAutoSwitch) &&
 				 (pAd->MlmeAux.Alg == Ndis802_11AuthModeShared))
 			{
@@ -1205,14 +1045,6 @@
 			if (pAd->CommonCfg.bWirelessEvent)
 				RTMPSendWirelessEvent(pAd, IW_ASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
 
-
-#ifdef LEAP_SUPPORT
-			if (LEAP_CCKM_ON(pAd))
-			{
-				STA_PORT_SECURED(pAd);
-				pAd->StaCfg.WpaState = SS_FINISH;
-			}
-#endif // LEAP_SUPPORT //
 			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
 			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Re-assocition successful on BSS #%ld\n", pAd->MlmeAux.RoamIdx));
 		}
@@ -1226,6 +1058,44 @@
 	}
 }
 
+
+#ifdef RT2870
+VOID	AdhocTurnOnQos(
+	IN  PRTMP_ADAPTER pAd)
+{
+#define AC0_DEF_TXOP		0
+#define AC1_DEF_TXOP		0
+#define AC2_DEF_TXOP		94
+#define AC3_DEF_TXOP		47
+
+	// Turn on QOs if use HT rate.
+	if (pAd->CommonCfg.APEdcaParm.bValid == FALSE)
+	{
+		pAd->CommonCfg.APEdcaParm.bValid = TRUE;
+		pAd->CommonCfg.APEdcaParm.Aifsn[0] = 3;
+		pAd->CommonCfg.APEdcaParm.Aifsn[1] = 7;
+		pAd->CommonCfg.APEdcaParm.Aifsn[2] = 1;
+		pAd->CommonCfg.APEdcaParm.Aifsn[3] = 1;
+
+		pAd->CommonCfg.APEdcaParm.Cwmin[0] = 4;
+		pAd->CommonCfg.APEdcaParm.Cwmin[1] = 4;
+		pAd->CommonCfg.APEdcaParm.Cwmin[2] = 3;
+		pAd->CommonCfg.APEdcaParm.Cwmin[3] = 2;
+
+		pAd->CommonCfg.APEdcaParm.Cwmax[0] = 10;
+		pAd->CommonCfg.APEdcaParm.Cwmax[1] = 6;
+		pAd->CommonCfg.APEdcaParm.Cwmax[2] = 4;
+		pAd->CommonCfg.APEdcaParm.Cwmax[3] = 3;
+
+		pAd->CommonCfg.APEdcaParm.Txop[0]  = 0;
+		pAd->CommonCfg.APEdcaParm.Txop[1]  = 0;
+		pAd->CommonCfg.APEdcaParm.Txop[2]  = AC2_DEF_TXOP;
+		pAd->CommonCfg.APEdcaParm.Txop[3]  = AC3_DEF_TXOP;
+	}
+	AsicSetEdcaParm(pAd, &pAd->CommonCfg.APEdcaParm);
+}
+#endif /* RT2870 */
+
 /*
 	==========================================================================
 	Description:
@@ -1244,12 +1114,14 @@
 	UCHAR	Value = 0, idx;
 	MAC_TABLE_ENTRY *pEntry = NULL, *pCurrEntry;
 
+#ifdef RT2860
 	if (RTMP_TEST_PSFLAG(pAd, fRTMP_PS_SET_PCI_CLK_OFF_COMMAND))
 	{
 		RTMPPCIeLinkCtrlValueRestore(pAd, RESTORE_HALT);
 		RTMPusecDelay(6000);
 		pAd->bPCIclkOff = FALSE;
 	}
+#endif
 
 	pEntry = &pAd->MacTab.Content[BSSID_WCID];
 
@@ -1266,15 +1138,15 @@
 
 	COPY_SETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(pAd);
 
-#ifdef DOT11_N_SUPPORT
 	COPY_HTSETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(pAd);
-#endif // DOT11_N_SUPPORT //
+
 	// It's quite difficult to tell if a newly added KEY is WEP or CKIP until a new BSS
 	// is formed (either ASSOC/RE-ASSOC done or IBSS started. LinkUP should be a safe place
 	// to examine if cipher algorithm switching is required.
 	//rt2860b. Don't know why need this
 	SwitchBetweenWepAndCkip(pAd);
 
+#ifdef RT2860
 	// Before power save before link up function, We will force use 1R.
 	// So after link up, check Rx antenna # again.
 	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
@@ -1292,17 +1164,30 @@
 	}
 	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
 	pAd->StaCfg.BBPR3 = Value;
+#endif /* RT2860 */
 
 	if (BssType == BSS_ADHOC)
 	{
 		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_ADHOC_ON);
 		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_INFRA_ON);
 
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-		// No carrier detection when adhoc
-		// CarrierDetectionStop(pAd);
-		pAd->CommonCfg.CarrierDetect.CD_State = CD_NORMAL;
-#endif // CARRIER_DETECTION_SUPPORT //
+#ifdef RT30xx
+		if ((pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth  == BW_40) &&
+			(pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_ABOVE))
+		{
+			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel + 2;
+		}
+		else if ((pAd->CommonCfg.Channel > 2) &&
+				 (pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth  == BW_40) &&
+				 (pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_BELOW))
+		{
+			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel - 2;
+		}
+#endif
+#ifdef RT2870
+		if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
+			AdhocTurnOnQos(pAd);
+#endif
 
 		DBGPRINT(RT_DEBUG_TRACE, ("!!!Adhoc LINK UP !!! \n" ));
 	}
@@ -1321,7 +1206,6 @@
 	Value |= pAd->CommonCfg.RegTransmitSetting.field.TxBF;
 	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
 
-#ifdef DOT11_N_SUPPORT
 	// Change to AP channel
     if ((pAd->CommonCfg.CentralChannel > pAd->CommonCfg.Channel) && (pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth == BW_40))
 	{
@@ -1339,7 +1223,9 @@
 		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
 		Value &= (~0x20);
 		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
+#ifdef RT2860
         pAd->StaCfg.BBPR3 = Value;
+#endif
 
 		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Data);
 		Data &= 0xfffffffe;
@@ -1374,7 +1260,9 @@
 		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
 	    Value |= (0x20);
 		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
+#ifdef RT2860
         pAd->StaCfg.BBPR3 = Value;
+#endif
 
 		if (pAd->MACVersion == 0x28600100)
 		{
@@ -1387,7 +1275,6 @@
 	    DBGPRINT(RT_DEBUG_TRACE, ("!!! 40MHz Upper LINK UP !!! Control Channel at UpperCentral = %d \n", pAd->CommonCfg.CentralChannel ));
     }
     else
-#endif // DOT11_N_SUPPORT //
     {
 	    pAd->CommonCfg.BBPCurrentBW = BW_20;
 		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
@@ -1405,7 +1292,9 @@
 		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
 		Value &= (~0x20);
 		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
+#ifdef RT2860
         pAd->StaCfg.BBPR3 = Value;
+#endif
 
 		if (pAd->MACVersion == 0x28600100)
 		{
@@ -1427,9 +1316,7 @@
 	DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !!! (BssType=%d, AID=%d, ssid=%s, Channel=%d, CentralChannel = %d)\n",
 		BssType, pAd->StaActive.Aid, pAd->CommonCfg.Ssid, pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel));
 
-#ifdef DOT11_N_SUPPORT
 	DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !!! (Density =%d, )\n", pAd->MacTab.Content[BSSID_WCID].MpduDensity));
-#endif // DOT11_N_SUPPORT //
 
 		AsicSetBssid(pAd, pAd->CommonCfg.Bssid);
 
@@ -1439,7 +1326,6 @@
 	// Call this for RTS protectionfor legacy rate, we will always enable RTS threshold, but normally it will not hit
 	AsicUpdateProtect(pAd, 0, (OFDMSETPROTECT | CCKSETPROTECT), TRUE, FALSE);
 
-#ifdef DOT11_N_SUPPORT
 	if ((pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE))
 	{
 		// Update HT protectionfor based on AP's operating mode.
@@ -1450,7 +1336,6 @@
     	else
    			AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode,  ALLN_SETPROTECT, FALSE, FALSE);
 	}
-#endif // DOT11_N_SUPPORT //
 
 	NdisZeroMemory(&pAd->DrsCounters, sizeof(COUNTER_DRS));
 
@@ -1467,9 +1352,6 @@
 
 	if (pAd->CommonCfg.RadarDetect.RDMode == RD_SILENCE_MODE)
 	{
-#ifdef DFS_SUPPORT
-		RadarDetectionStop(pAd);
-#endif // DFS_SUPPORT //
 	}
 	pAd->CommonCfg.RadarDetect.RDMode = RD_NORMAL_MODE;
 
@@ -1602,7 +1484,9 @@
 			IV |= (pAd->StaCfg.DefaultKeyId << 30);
 			AsicUpdateWCIDIVEIV(pAd, BSSID_WCID, IV, 0);
 
+#ifdef RT2860
 			RTMP_CLEAR_PSFLAG(pAd, fRTMP_PS_CAN_GO_SLEEP);
+#endif
 		}
 		// NOTE:
 		// the decision of using "short slot time" or not may change dynamically due to
@@ -1643,15 +1527,11 @@
 
 
 		// If WEP is enabled, add paiewise and shared key
-#ifdef WPA_SUPPLICANT_SUPPORT
         if (((pAd->StaCfg.WpaSupplicantUP)&&
              (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)&&
              (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED)) ||
             ((pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_DISABLE)&&
               (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)))
-#else
-		if (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)
-#endif // WPA_SUPPLICANT_SUPPORT //
 		{
 			PUCHAR	Key;
 			UCHAR 	CipherAlg;
@@ -1687,9 +1567,14 @@
 		{
 			pAd->IndicateMediaState = NdisMediaStateConnected;
 			pAd->ExtraInfo = GENERAL_LINK_UP;
+#ifdef RT2870
+			RTMP_IndicateMediaState(pAd);
+#endif
 		}
         // --
+#ifdef RT2860
 		RTMP_IndicateMediaState(pAd);
+#endif
 
 		// Add BSSID in my MAC Table.
         NdisAcquireSpinLock(&pAd->MacTabLock);
@@ -1700,6 +1585,9 @@
 		pAd->MacTab.Size = 1;	// infra mode always set MACtab size =1.
 		pAd->MacTab.Content[BSSID_WCID].Sst = SST_ASSOC;
 		pAd->MacTab.Content[BSSID_WCID].AuthState = SST_ASSOC;
+#ifdef RT30xx
+		pAd->MacTab.Content[BSSID_WCID].AuthMode = pAd->StaCfg.AuthMode;
+#endif
 		pAd->MacTab.Content[BSSID_WCID].WepStatus = pAd->StaCfg.WepStatus;
         NdisReleaseSpinLock(&pAd->MacTabLock);
 
@@ -1707,17 +1595,8 @@
 			pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
 
 		MlmeUpdateTxRates(pAd, TRUE, BSS0);
-#ifdef DOT11_N_SUPPORT
 		MlmeUpdateHtTxRates(pAd, BSS0);
 		DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !! (StaActive.bHtEnable =%d, )\n", pAd->StaActive.SupportedPhyInfo.bHtEnable));
-#endif // DOT11_N_SUPPORT //
-
-		//
-		// Report Adjacent AP report.
-		//
-#ifdef LEAP_SUPPORT
-		CCXAdjacentAPReport(pAd);
-#endif // LEAP_SUPPORT //
 
 		if (pAd->CommonCfg.bAggregationCapable)
 		{
@@ -1737,12 +1616,11 @@
 
 		if (pAd->MlmeAux.APRalinkIe != 0x0)
 		{
-#ifdef DOT11_N_SUPPORT
 			if (CLIENT_STATUS_TEST_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_RDG_CAPABLE))
 			{
 				AsicEnableRDG(pAd);
 			}
-#endif // DOT11_N_SUPPORT //
+
 			OPSTATUS_SET_FLAG(pAd, fCLIENT_STATUS_RALINK_CHIPSET);
 			CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_RALINK_CHIPSET);
 		}
@@ -1753,9 +1631,7 @@
 		}
 	}
 
-#ifdef DOT11_N_SUPPORT
 	DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_CONNECT Event B!.BACapability = %x. ClientStatusFlags = %lx\n", pAd->CommonCfg.BACapability.word, pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
-#endif // DOT11_N_SUPPORT //
 
 	// Set LED
 	RTMPSetLED(pAd, LED_LINK_UP);
@@ -1780,13 +1656,13 @@
 	if (pAd->StaCfg.bAutoTxRateSwitch == FALSE)
 	{
 		pEntry->bAutoTxRateSwitch = FALSE;
-#ifdef DOT11_N_SUPPORT
+
 		if (pEntry->HTPhyMode.field.MCS == 32)
 			pEntry->HTPhyMode.field.ShortGI = GI_800;
 
 		if ((pEntry->HTPhyMode.field.MCS > MCS_7) || (pEntry->HTPhyMode.field.MCS == 32))
 			pEntry->HTPhyMode.field.STBC = STBC_NONE;
-#endif // DOT11_N_SUPPORT //
+
 		// If the legacy mode is set, overwrite the transmit setting of this entry.
 		if (pEntry->HTPhyMode.field.MODE <= MODE_OFDM)
 			RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
@@ -1815,7 +1691,6 @@
 		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, Value);
 	}
 
-#ifdef DOT11_N_SUPPORT
 	if (pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE)
 	{
 	}
@@ -1825,7 +1700,6 @@
 	    // Because our Init value is 1 at MACRegTable.
 		RTMP_IO_WRITE32(pAd, MAX_LEN_CFG, 0x0fff);
 	}
-#endif // DOT11_N_SUPPORT //
 
 	// Patch for Marvel AP to gain high throughput
 	// Need to set as following,
@@ -1837,9 +1711,15 @@
 	// Txop can only be modified when RDG is off, WMM is disable and TxBurst is enable
 	//
 	// if 1. Legacy AP WMM on,  or 2. 11n AP, AMPDU disable.  Force turn off burst no matter what bEnableTxBurst is.
-#ifdef DOT11_N_SUPPORT
+#ifdef RT30xx
+	if (!((pAd->CommonCfg.RxStream == 1)&&(pAd->CommonCfg.TxStream == 1)) &&
+		(((pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED))
+		|| ((pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE) && (pAd->CommonCfg.BACapability.field.Policy == BA_NOTUSE))))
+#endif
+#ifndef RT30xx
 	if (((pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE) && (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED)))
 		|| ((pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE) && (pAd->CommonCfg.BACapability.field.Policy == BA_NOTUSE)))
+#endif
 	{
 		RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
 		Data  &= 0xFFFFFF00;
@@ -1849,7 +1729,6 @@
 		DBGPRINT(RT_DEBUG_TRACE, ("Txburst 1\n"));
 	}
 	else
-#endif // DOT11_N_SUPPORT //
 	if (pAd->CommonCfg.bEnableTxBurst)
 	{
 		RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
@@ -1871,7 +1750,6 @@
 		DBGPRINT(RT_DEBUG_TRACE, ("Txburst 3\n"));
 	}
 
-#ifdef DOT11_N_SUPPORT
 	// Re-check to turn on TX burst or not.
 	if ((pAd->CommonCfg.IOTestParm.bLastAtheros == TRUE) && ((STA_WEP_ON(pAd))||(STA_TKIP_ON(pAd))))
 	{
@@ -1891,7 +1769,6 @@
 	{
 		pAd->CommonCfg.IOTestParm.bNextDisableRxBA = FALSE;
 	}
-#endif // DOT11_N_SUPPORT //
 
 	pAd->CommonCfg.IOTestParm.bLastAtheros = FALSE;
 	COPY_MAC_ADDR(pAd->CommonCfg.LastBssid, pAd->CommonCfg.Bssid);
@@ -1924,17 +1801,9 @@
 	}
 
 	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
+#ifdef RT2860
 	RTMP_CLEAR_PSFLAG(pAd, fRTMP_PS_GO_TO_SLEEP_NOW);
-
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	if ((pAd->CommonCfg.BACapability.field.b2040CoexistScanSup) && (pAd->CommonCfg.Channel <= 11))
-	{
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_SCAN_2040);
-		BuildEffectedChannelList(pAd);
-	}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
+#endif
 }
 
 /*
@@ -1967,23 +1836,21 @@
 	IN  BOOLEAN      IsReqFromAP)
 {
 	UCHAR			    i, ByteValue = 0;
+#ifdef RT2860
 	BOOLEAN		Cancelled;
+#endif
 
 	// Do nothing if monitor mode is on
 	if (MONITOR_ON(pAd))
 		return;
 
-#ifdef RALINK_ATE
-	// Nothing to do in ATE mode.
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
+#ifdef RT2860
 	RTMP_CLEAR_PSFLAG(pAd, fRTMP_PS_GO_TO_SLEEP_NOW);
 	RTMPCancelTimer(&pAd->Mlme.PsPollTimer,		&Cancelled);
 
 	// Not allow go to sleep within linkdown function.
 	RTMP_CLEAR_PSFLAG(pAd, fRTMP_PS_CAN_GO_SLEEP);
+#endif
 
     if (pAd->CommonCfg.bWirelessEvent)
 	{
@@ -1993,6 +1860,7 @@
 	DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN !!!\n"));
 	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
 
+#ifdef RT2860
     if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE))
     {
 	    BOOLEAN Cancelled;
@@ -2009,6 +1877,7 @@
     }
 
     pAd->bPCIclkOff = FALSE;
+#endif
 	if (ADHOC_ON(pAd))		// Adhoc mode link down
 	{
 		DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN 1!!!\n"));
@@ -2025,33 +1894,6 @@
 	{
 		DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN 2!!!\n"));
 
-#ifdef QOS_DLS_SUPPORT
-		// DLS tear down frame must be sent before link down
-		// send DLS-TEAR_DOWN message
-		if (pAd->CommonCfg.bDLSCapable)
-		{
-			// tear down local dls table entry
-			for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-				{
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				}
-			}
-
-			// tear down peer dls table entry
-			for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status ==  DLS_FINISH))
-				{
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				}
-			}
-		}
-#endif // QOS_DLS_SUPPORT //
-
 		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_INFRA_ON);
 		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
 
@@ -2095,17 +1937,6 @@
 			NdisMoveMemory(pAd->StaCfg.CCXAdjacentAPSsid, pAd->CommonCfg.Ssid, pAd->StaCfg.CCXAdjacentAPSsidLen);
 			COPY_MAC_ADDR(pAd->StaCfg.CCXAdjacentAPBssid, pAd->CommonCfg.Bssid);
 		}
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-		// Country IE of the AP will be evaluated and will be used.
-		if (pAd->StaCfg.IEEE80211dClientMode != Rt802_11_D_None)
-		{
-			NdisMoveMemory(&pAd->CommonCfg.CountryCode[0], &pAd->StaCfg.StaOriCountryCode[0], 2);
-			pAd->CommonCfg.Geography = pAd->StaCfg.StaOriGeography;
-			BuildChannelListEx(pAd);
-		}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
 	}
 
 	for (i=1; i<MAX_LEN_OF_MAC_TABLE; i++)
@@ -2137,12 +1968,11 @@
 		NdisZeroMemory(pAd->CommonCfg.Ssid, MAX_LEN_OF_SSID);
 		pAd->CommonCfg.SsidLen = 0;
 	}
-#ifdef DOT11_N_SUPPORT
+
 	NdisZeroMemory(&pAd->MlmeAux.HtCapability, sizeof(HT_CAPABILITY_IE));
 	NdisZeroMemory(&pAd->MlmeAux.AddHtInfo, sizeof(ADD_HT_INFO_IE));
 	pAd->MlmeAux.HtCapabilityLen = 0;
 	pAd->MlmeAux.NewExtChannelOffset = 0xff;
-#endif // DOT11_N_SUPPORT //
 
 	// Reset WPA-PSK state. Only reset when supplicant enabled
 	if (pAd->StaCfg.WpaState != SS_NOTUSE)
@@ -2150,11 +1980,6 @@
 		pAd->StaCfg.WpaState = SS_START;
 		// Clear Replay counter
 		NdisZeroMemory(pAd->StaCfg.ReplayCounter, 8);
-
-#ifdef QOS_DLS_SUPPORT
-		if (pAd->CommonCfg.bDLSCapable)
-			NdisZeroMemory(pAd->StaCfg.DlsReplayCounter, 8);
-#endif // QOS_DLS_SUPPORT //
 	}
 
 
@@ -2169,7 +1994,7 @@
 	}
 
 	// 802.1x port control
-#ifdef WPA_SUPPLICANT_SUPPORT
+
 	// Prevent clear PortSecured here with static WEP
 	// NetworkManger set security policy first then set SSID to connect AP.
 	if (pAd->StaCfg.WpaSupplicantUP &&
@@ -2179,7 +2004,6 @@
 		pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
 	}
 	else
-#endif // WPA_SUPPLICANT_SUPPORT //
 	{
 		pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
 		pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilter8021xWEP;
@@ -2199,13 +2023,18 @@
 	// Update extra information to link is up
 	pAd->ExtraInfo = GENERAL_LINK_DOWN;
 
+#ifdef RT2860
     pAd->StaCfg.AdhocBOnlyJoined = FALSE;
 	pAd->StaCfg.AdhocBGJoined = FALSE;
 	pAd->StaCfg.Adhoc20NJoined = FALSE;
+#endif
     pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
 
 	// Reset the Current AP's IP address
 	NdisZeroMemory(pAd->StaCfg.AironetIPAddress, 4);
+#ifdef RT2870
+	pAd->bUsbTxBulkAggre = FALSE;
+#endif // RT2870 //
 
 	// Clean association information
 	NdisZeroMemory(&pAd->StaCfg.AssocInfo, sizeof(NDIS_802_11_ASSOCIATION_INFORMATION));
@@ -2227,7 +2056,6 @@
 	pAd->CommonCfg.MlmeRate = pAd->CommonCfg.BasicMlmeRate;
 	pAd->CommonCfg.RtsRate = pAd->CommonCfg.BasicMlmeRate;
 
-#ifdef DOT11_N_SUPPORT
 	//
 	// After Link down, reset piggy-back setting in ASIC. Disable RDG.
 	//
@@ -2238,7 +2066,7 @@
 		ByteValue &= (~0x18);
 		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, ByteValue);
 	}
-#endif // DOT11_N_SUPPORT //
+
 	// Reset DAC
 	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &ByteValue);
 	ByteValue &= (~0x18);
@@ -2251,9 +2079,7 @@
 	RTMPSetPiggyBack(pAd,FALSE);
 	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_PIGGYBACK_INUSED);
 
-#ifdef DOT11_N_SUPPORT
 	pAd->CommonCfg.BACapability.word = pAd->CommonCfg.REGBACapability.word;
-#endif // DOT11_N_SUPPORT //
 
 	// Restore all settings in the following.
 	AsicUpdateProtect(pAd, 0, (ALLN_SETPROTECT|CCKSETPROTECT|OFDMSETPROTECT), TRUE, FALSE);
@@ -2261,43 +2087,35 @@
 	pAd->CommonCfg.IOTestParm.bCurrentAtheros = FALSE;
 	pAd->CommonCfg.IOTestParm.bNowAtherosBurstOn = FALSE;
 
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SCAN_2040);
-	pAd->CommonCfg.BSSCoexist2040.word = 0;
-	TriEventInit(pAd);
-	for (i = 0; i < (pAd->ChannelListNum - 1); i++)
-	{
-		pAd->ChannelList[i].bEffectedChannel = FALSE;
-	}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
 	RTMP_IO_WRITE32(pAd, MAX_LEN_CFG, 0x1fff);
 	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
 
+#ifdef RT2860
 	// Allow go to sleep after linkdown steps.
 	RTMP_SET_PSFLAG(pAd, fRTMP_PS_CAN_GO_SLEEP);
+#endif
 
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-	if (pAd->StaCfg.WpaSupplicantUP) {
-		union iwreq_data    wrqu;
-		//send disassociate event to wpa_supplicant
-		memset(&wrqu, 0, sizeof(wrqu));
-		wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-		wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-	}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
 	{
 		union iwreq_data    wrqu;
 		memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
 		wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
 	}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
+
+#ifdef RT30xx
+	if (IS_RT3090(pAd))
+	{
+		UINT32				macdata;
+		// disable MMPS BBP control register
+		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &ByteValue);
+		ByteValue &= ~(0x04);	//bit 2
+		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, ByteValue);
+
+		// disable MMPS MAC control register
+		RTMP_IO_READ32(pAd, 0x1210, &macdata);
+		macdata &= ~(0x09);	//bit 0, 3
+		RTMP_IO_WRITE32(pAd, 0x1210, macdata);
+	}
+#endif // RT30xx //
 }
 
 /*
@@ -2457,26 +2275,6 @@
 	ScanReq->ScanType = ScanType;
 }
 
-#ifdef QOS_DLS_SUPPORT
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID DlsParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_DLS_REQ_STRUCT *pDlsReq,
-	IN PRT_802_11_DLS pDls,
-	IN USHORT reason)
-{
-	pDlsReq->pDLS = pDls;
-	pDlsReq->Reason = reason;
-}
-#endif // QOS_DLS_SUPPORT //
-
 /*
 	==========================================================================
 	Description:
@@ -2523,21 +2321,61 @@
 
 	==========================================================================
  */
+
+
+#ifdef RT2870
+
+VOID MlmeCntlConfirm(
+	IN PRTMP_ADAPTER pAd,
+	IN ULONG MsgType,
+	IN USHORT Msg)
+{
+	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MsgType, sizeof(USHORT), &Msg);
+}
+#endif
+
 VOID ComposePsPoll(
 	IN PRTMP_ADAPTER pAd)
 {
+#ifdef RT2870
+	PTXINFO_STRUC		pTxInfo;
+	PTXWI_STRUC		pTxWI;
+
+	DBGPRINT(RT_DEBUG_TRACE, ("ComposePsPoll\n"));
+#endif
 	NdisZeroMemory(&pAd->PsPollFrame, sizeof(PSPOLL_FRAME));
+
+#ifdef RT2870
+	pAd->PsPollFrame.FC.PwrMgmt = 0;
+#endif
 	pAd->PsPollFrame.FC.Type = BTYPE_CNTL;
 	pAd->PsPollFrame.FC.SubType = SUBTYPE_PS_POLL;
 	pAd->PsPollFrame.Aid = pAd->StaActive.Aid | 0xC000;
 	COPY_MAC_ADDR(pAd->PsPollFrame.Bssid, pAd->CommonCfg.Bssid);
 	COPY_MAC_ADDR(pAd->PsPollFrame.Ta, pAd->CurrentAddress);
+
+#ifdef RT2870
+	RTMPZeroMemory(&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[0], 100);
+	pTxInfo = (PTXINFO_STRUC)&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[0];
+	RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(sizeof(PSPOLL_FRAME)+TXWI_SIZE), TRUE, EpToQueue[MGMTPIPEIDX], FALSE,  FALSE);
+	pTxWI = (PTXWI_STRUC)&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE];
+	RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, 0, BSSID_WCID, (sizeof(PSPOLL_FRAME)),
+		0,  0, (UCHAR)pAd->CommonCfg.MlmeTransmit.field.MCS, IFS_BACKOFF, FALSE, &pAd->CommonCfg.MlmeTransmit);
+	RTMPMoveMemory(&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[TXWI_SIZE+TXINFO_SIZE], &pAd->PsPollFrame, sizeof(PSPOLL_FRAME));
+	// Append 4 extra zero bytes.
+	pAd->PsPollContext.BulkOutSize =  TXINFO_SIZE + TXWI_SIZE + sizeof(PSPOLL_FRAME) + 4;
+#endif
 }
 
 // IRQL = DISPATCH_LEVEL
 VOID ComposeNullFrame(
 	IN PRTMP_ADAPTER pAd)
 {
+#ifdef RT2870
+	PTXINFO_STRUC		pTxInfo;
+	PTXWI_STRUC		pTxWI;
+#endif
+
 	NdisZeroMemory(&pAd->NullFrame, sizeof(HEADER_802_11));
 	pAd->NullFrame.FC.Type = BTYPE_DATA;
 	pAd->NullFrame.FC.SubType = SUBTYPE_NULL_FUNC;
@@ -2545,6 +2383,16 @@
 	COPY_MAC_ADDR(pAd->NullFrame.Addr1, pAd->CommonCfg.Bssid);
 	COPY_MAC_ADDR(pAd->NullFrame.Addr2, pAd->CurrentAddress);
 	COPY_MAC_ADDR(pAd->NullFrame.Addr3, pAd->CommonCfg.Bssid);
+#ifdef RT2870
+	RTMPZeroMemory(&pAd->NullContext.TransferBuffer->field.WirelessPacket[0], 100);
+	pTxInfo = (PTXINFO_STRUC)&pAd->NullContext.TransferBuffer->field.WirelessPacket[0];
+	RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(sizeof(HEADER_802_11)+TXWI_SIZE), TRUE, EpToQueue[MGMTPIPEIDX], FALSE,  FALSE);
+	pTxWI = (PTXWI_STRUC)&pAd->NullContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE];
+	RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, 0, BSSID_WCID, (sizeof(HEADER_802_11)),
+		0, 0, (UCHAR)pAd->CommonCfg.MlmeTransmit.field.MCS, IFS_BACKOFF, FALSE, &pAd->CommonCfg.MlmeTransmit);
+	RTMPMoveMemory(&pAd->NullContext.TransferBuffer->field.WirelessPacket[TXWI_SIZE+TXINFO_SIZE], &pAd->NullFrame, sizeof(HEADER_802_11));
+	pAd->NullContext.BulkOutSize =  TXINFO_SIZE + TXWI_SIZE + sizeof(pAd->NullFrame) + 4;
+#endif
 }
 
 
@@ -2688,22 +2536,15 @@
 		FrameLen += tmp;
 	}
 
-#ifdef DOT11_N_SUPPORT
 	if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
 	{
 		ULONG TmpLen;
 		UCHAR HtLen, HtLen1;
 
-#ifdef RT_BIG_ENDIAN
-		HT_CAPABILITY_IE HtCapabilityTmp;
-		ADD_HT_INFO_IE	addHTInfoTmp;
-		USHORT	b2lTmp, b2lTmp2;
-#endif
-
 		// add HT Capability IE
 		HtLen = sizeof(pAd->CommonCfg.HtCapability);
 		HtLen1 = sizeof(pAd->CommonCfg.AddHTInfo);
-#ifndef RT_BIG_ENDIAN
+
 		MakeOutgoingFrame(pBeaconFrame+FrameLen,	&TmpLen,
 						  1,						&HtCapIe,
 						  1,						&HtLen,
@@ -2712,27 +2553,9 @@
 						  1,						&HtLen1,
 						  HtLen1,					&pAd->CommonCfg.AddHTInfo,
 						  END_OF_ARGS);
-#else
-		NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, HtLen);
-		*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-		*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
 
-		NdisMoveMemory(&addHTInfoTmp, &pAd->CommonCfg.AddHTInfo, HtLen1);
-		*(USHORT *)(&addHTInfoTmp.AddHtInfo2) = SWAP16(*(USHORT *)(&addHTInfoTmp.AddHtInfo2));
-		*(USHORT *)(&addHTInfoTmp.AddHtInfo3) = SWAP16(*(USHORT *)(&addHTInfoTmp.AddHtInfo3));
-
-		MakeOutgoingFrame(pBeaconFrame+FrameLen,	&TmpLen,
-						  1,						&HtCapIe,
-						  1,						&HtLen,
-						  HtLen,					&HtCapabilityTmp,
-						  1,						&AddHtInfoIe,
-						  1,						&HtLen1,
-						  HtLen1,					&addHTInfoTmp,
-						  END_OF_ARGS);
-#endif
 		FrameLen += TmpLen;
 	}
-#endif // DOT11_N_SUPPORT //
 
 	//beacon use reserved WCID 0xff
     if (pAd->CommonCfg.Channel > 14)
@@ -2749,11 +2572,6 @@
     		PID_MGMT, PID_BEACON, RATE_1, IFS_HTTXOP, FALSE, &Transmit);
     }
 
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, pBeaconFrame, DIR_WRITE, FALSE);
-	RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-#endif
-
     DBGPRINT(RT_DEBUG_TRACE, ("MakeIbssBeacon (len=%ld), SupRateLen=%d, ExtRateLen=%d, Channel=%d, PhyMode=%d\n",
 					FrameLen, SupRateLen, ExtRateLen, pAd->CommonCfg.Channel, pAd->CommonCfg.PhyMode));
 	return FrameLen;
diff --git a/drivers/staging/rt2860/sta/dls.c b/drivers/staging/rt2860/sta/dls.c
deleted file mode 100644
index 873cf7f..0000000
--- a/drivers/staging/rt2860/sta/dls.c
+++ /dev/null
@@ -1,2197 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    dls.c
-
-    Abstract:
-    Handle WMM-DLS state machine
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Rory Chen   02-14-2006
-	Arvin Tai	06-03-2008	  Modified for RT28xx
- */
-
-#include "../rt_config.h"
-
-/*
-    ==========================================================================
-    Description:
-        dls state machine init, including state transition and timer init
-    Parameters:
-        Sm - pointer to the dls state machine
-    Note:
-        The state machine looks like this
-
-                            DLS_IDLE
-    MT2_MLME_DLS_REQUEST   MlmeDlsReqAction
-    MT2_PEER_DLS_REQUEST   PeerDlsReqAction
-    MT2_PEER_DLS_RESPONSE  PeerDlsRspAction
-    MT2_MLME_DLS_TEARDOWN  MlmeTearDownAction
-    MT2_PEER_DLS_TEARDOWN  PeerTearDownAction
-
-	IRQL = PASSIVE_LEVEL
-
-    ==========================================================================
- */
-void DlsStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[])
-{
-	UCHAR	i;
-
-    StateMachineInit(Sm, (STATE_MACHINE_FUNC*)Trans, MAX_DLS_STATE, MAX_DLS_MSG, (STATE_MACHINE_FUNC)Drop, DLS_IDLE, DLS_MACHINE_BASE);
-
-    // the first column
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_MLME_DLS_REQ, (STATE_MACHINE_FUNC)MlmeDlsReqAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_PEER_DLS_REQ, (STATE_MACHINE_FUNC)PeerDlsReqAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_PEER_DLS_RSP, (STATE_MACHINE_FUNC)PeerDlsRspAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_MLME_DLS_TEAR_DOWN, (STATE_MACHINE_FUNC)MlmeDlsTearDownAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_PEER_DLS_TEAR_DOWN, (STATE_MACHINE_FUNC)PeerDlsTearDownAction);
-
-	for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		pAd->StaCfg.DLSEntry[i].pAd = pAd;
-		RTMPInitTimer(pAd, &pAd->StaCfg.DLSEntry[i].Timer, GET_TIMER_FUNCTION(DlsTimeoutAction), pAd, FALSE);
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeDlsReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen = 0;
-	HEADER_802_11	DlsReqHdr;
-	PRT_802_11_DLS	pDLS = NULL;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_REQUEST;
-	ULONG			tmp;
-	USHORT			reason;
-	ULONG			Timeout;
-	BOOLEAN			TimerCancelled;
-
-	if(!MlmeDlsReqSanity(pAd, Elem->Msg, Elem->MsgLen, &pDLS, &reason))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - MlmeDlsReqAction() \n"));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("DLS - MlmeDlsReqAction() allocate memory failed \n"));
-		return;
-	}
-
-	ActHeaderInit(pAd, &DlsReqHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-
-	// Build basic frame first
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-					sizeof(HEADER_802_11),		&DlsReqHdr,
-					1,							&Category,
-					1,							&Action,
-					6,							&pDLS->MacAddr,
-					6,							pAd->CurrentAddress,
-					2,							&pAd->StaActive.CapabilityInfo,
-					2,							&pDLS->TimeOut,
-					1,							&SupRateIe,
-					1,							&pAd->MlmeAux.SupRateLen,
-					pAd->MlmeAux.SupRateLen,	pAd->MlmeAux.SupRate,
-					END_OF_ARGS);
-
-	if (pAd->MlmeAux.ExtRateLen != 0)
-	{
-		MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-						  1,						&ExtRateIe,
-						  1,						&pAd->MlmeAux.ExtRateLen,
-						  pAd->MlmeAux.ExtRateLen,	pAd->MlmeAux.ExtRate,
-						  END_OF_ARGS);
-		FrameLen += tmp;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-	{
-		UCHAR HtLen;
-
-#ifdef RT_BIG_ENDIAN
-		HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
-
-		// add HT Capability IE
-		HtLen = sizeof(HT_CAPABILITY_IE);
-#ifndef RT_BIG_ENDIAN
-		MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-							1,						&HtCapIe,
-							1,						&HtLen,
-							HtLen,					&pAd->CommonCfg.HtCapability,
-							END_OF_ARGS);
-#else
-		NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, HtLen);
-							*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-							*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-		MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-							1,						&HtCapIe,
-							1,						&HtLen,
-							HtLen,					&HtCapabilityTmp,
-							END_OF_ARGS);
-#endif
-		FrameLen = FrameLen + tmp;
-	}
-#endif // DOT11_N_SUPPORT //
-
-	RTMPCancelTimer(&pDLS->Timer, &TimerCancelled);
-	Timeout = DLS_TIMEOUT;
-	RTMPSetTimer(&pDLS->Timer, Timeout);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerDlsReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen = 0;
-	USHORT			StatusCode = MLME_SUCCESS;
-	HEADER_802_11	DlsRspHdr;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_RESPONSE;
-	ULONG			tmp;
-	USHORT			CapabilityInfo;
-	UCHAR			DA[MAC_ADDR_LEN], SA[MAC_ADDR_LEN];
-	USHORT			DLSTimeOut;
-	SHORT			i;
-	ULONG			Timeout;
-	BOOLEAN			TimerCancelled;
-	PRT_802_11_DLS	pDLS = NULL;
-	UCHAR			MaxSupportedRateIn500Kbps = 0;
-    UCHAR			SupportedRatesLen;
-    UCHAR			SupportedRates[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR			HtCapabilityLen;
-	HT_CAPABILITY_IE	HtCapability;
-
-	if (!PeerDlsReqSanity(pAd, Elem->Msg, Elem->MsgLen, DA, SA, &CapabilityInfo, &DLSTimeOut,
-							&SupportedRatesLen, &SupportedRates[0], &HtCapabilityLen, &HtCapability))
-		return;
-
-    // supported rates array may not be sorted. sort it and find the maximum rate
-    for (i = 0; i < SupportedRatesLen; i++)
-    {
-        if (MaxSupportedRateIn500Kbps < (SupportedRates[i] & 0x7f))
-            MaxSupportedRateIn500Kbps = SupportedRates[i] & 0x7f;
-    }
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsReqAction() from %02x:%02x:%02x:%02x:%02x:%02x\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsReqAction() allocate memory failed \n"));
-		return;
-	}
-
-	if (!INFRA_ON(pAd))
-	{
-		StatusCode = MLME_REQUEST_DECLINED;
-	}
-	else if (!pAd->CommonCfg.bWmmCapable)
-	{
-		StatusCode = MLME_DEST_STA_IS_NOT_A_QSTA;
-	}
-	else if (!pAd->CommonCfg.bDLSCapable)
-	{
-		StatusCode = MLME_REQUEST_DECLINED;
-	}
-	else
-	{
-		// find table to update parameters
-		for (i = (MAX_NUM_OF_DLS_ENTRY-1); i >= 0; i--)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-					pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-				else
-				{
-					RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-					pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-				}
-
-				pAd->StaCfg.DLSEntry[i].Sequence = 0;
-				pAd->StaCfg.DLSEntry[i].TimeOut = DLSTimeOut;
-				pAd->StaCfg.DLSEntry[i].CountDownTimer = DLSTimeOut;
-				if (HtCapabilityLen != 0)
-					pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-				else
-					pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-				pDLS = &pAd->StaCfg.DLSEntry[i];
-				break;
-			}
-		}
-
-		// can not find in table, create a new one
-		if (i < 0)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsReqAction() can not find same entry \n"));
-			for (i=(MAX_NUM_OF_DLS_ENTRY - 1); i >= MAX_NUM_OF_INIT_DLS_ENTRY; i--)
-			{
-				if (!pAd->StaCfg.DLSEntry[i].Valid)
-				{
-					MAC_TABLE_ENTRY *pEntry;
-					UCHAR MaxSupportedRate = RATE_11;
-
-					if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-					{
-						pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-					}
-					else
-					{
-						RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-						pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-					}
-
-					pAd->StaCfg.DLSEntry[i].Sequence = 0;
-					pAd->StaCfg.DLSEntry[i].Valid = TRUE;
-					pAd->StaCfg.DLSEntry[i].TimeOut = DLSTimeOut;
-					pAd->StaCfg.DLSEntry[i].CountDownTimer = DLSTimeOut;
-					NdisMoveMemory(pAd->StaCfg.DLSEntry[i].MacAddr, SA, MAC_ADDR_LEN);
-					if (HtCapabilityLen != 0)
-						pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-					else
-						pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-					pDLS = &pAd->StaCfg.DLSEntry[i];
-					pEntry = MacTableInsertDlsEntry(pAd, SA, i);
-
-					switch (MaxSupportedRateIn500Kbps)
-					{
-						case 108: MaxSupportedRate = RATE_54;   break;
-						case 96:  MaxSupportedRate = RATE_48;   break;
-						case 72:  MaxSupportedRate = RATE_36;   break;
-						case 48:  MaxSupportedRate = RATE_24;   break;
-						case 36:  MaxSupportedRate = RATE_18;   break;
-						case 24:  MaxSupportedRate = RATE_12;   break;
-						case 18:  MaxSupportedRate = RATE_9;    break;
-						case 12:  MaxSupportedRate = RATE_6;    break;
-						case 22:  MaxSupportedRate = RATE_11;   break;
-						case 11:  MaxSupportedRate = RATE_5_5;  break;
-						case 4:   MaxSupportedRate = RATE_2;    break;
-						case 2:   MaxSupportedRate = RATE_1;    break;
-						default:  MaxSupportedRate = RATE_11;   break;
-					}
-
-					pEntry->MaxSupportedRate = min(pAd->CommonCfg.MaxTxRate, MaxSupportedRate);
-
-					if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->HTPhyMode.field.MODE = MODE_CCK;
-						pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->HTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					}
-
-					pEntry->MaxHTPhyMode.field.BW = BW_20;
-					pEntry->MinHTPhyMode.field.BW = BW_20;
-
-#ifdef DOT11_N_SUPPORT
-					pEntry->HTCapability.MCSSet[0] = 0;
-					pEntry->HTCapability.MCSSet[1] = 0;
-
-					// If this Entry supports 802.11n, upgrade to HT rate.
-					if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-					{
-						UCHAR	j, bitmask; //k,bitmask;
-						CHAR    ii;
-
-						DBGPRINT(RT_DEBUG_OFF, ("DLS - PeerDlsReqAction() Receive Peer HT Capable STA from %02x:%02x:%02x:%02x:%02x:%02x\n",
-									SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-
-						if ((HtCapability.HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-							pAd->MacTab.fAnyStationNonGF = TRUE;
-							pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
-						}
-
-						if ((HtCapability.HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
-						{
-							pEntry->MaxHTPhyMode.field.BW= BW_40;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(HtCapability.HtCapInfo.ShortGIfor40));
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.BW = BW_20;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(HtCapability.HtCapInfo.ShortGIfor20));
-							pAd->MacTab.fAnyStation20Only = TRUE;
-						}
-
-						// find max fixed rate
-						for (ii=15; ii>=0; ii--)
-						{
-							j = ii/8;
-							bitmask = (1<<(ii-(j*8)));
-							if ( (pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j]&bitmask) && (HtCapability.MCSSet[j]&bitmask))
-							{
-								pEntry->MaxHTPhyMode.field.MCS = ii;
-								break;
-							}
-							if (ii==0)
-								break;
-						}
-
-
-						if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
-						{
-
-							printk("@@@ pAd->CommonCfg.RegTransmitSetting.field.MCS = %d\n",
-								pAd->StaCfg.DesiredTransmitSetting.field.MCS);
-							if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
-							{
-								// Fix MCS as HT Duplicated Mode
-								pEntry->MaxHTPhyMode.field.BW = 1;
-								pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-								pEntry->MaxHTPhyMode.field.STBC = 0;
-								pEntry->MaxHTPhyMode.field.ShortGI = 0;
-								pEntry->MaxHTPhyMode.field.MCS = 32;
-							}
-							else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
-							{
-								// STA supports fixed MCS
-								pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
-							}
-						}
-
-						pEntry->MaxHTPhyMode.field.STBC = (HtCapability.HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
-						pEntry->MpduDensity = HtCapability.HtCapParm.MpduDensity;
-						pEntry->MaxRAmpduFactor = HtCapability.HtCapParm.MaxRAmpduFactor;
-						pEntry->MmpsMode = (UCHAR)HtCapability.HtCapInfo.MimoPs;
-						pEntry->AMsduSize = (UCHAR)HtCapability.HtCapInfo.AMsduSize;
-						pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-
-						if (HtCapability.HtCapInfo.ShortGIfor20)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
-						if (HtCapability.HtCapInfo.ShortGIfor40)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
-						if (HtCapability.HtCapInfo.TxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
-						if (HtCapability.HtCapInfo.RxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.PlusHTC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
-						if (pAd->CommonCfg.bRdg && HtCapability.ExtHtCapInfo.RDGSupport)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.MCSFeedback == 0x03)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
-
-						NdisMoveMemory(&pEntry->HTCapability, &HtCapability, sizeof(HT_CAPABILITY_IE));
-					}
-#endif // DOT11_N_SUPPORT //
-
-					pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-					pEntry->CurrTxRate = pEntry->MaxSupportedRate;
-					CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-
-					if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-					{
-						PUCHAR pTable;
-						UCHAR TableSize = 0;
-
-						MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
-						pEntry->bAutoTxRateSwitch = TRUE;
-					}
-					else
-					{
-						pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-						pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
-						pEntry->bAutoTxRateSwitch = FALSE;
-
-						RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-					}
-					pEntry->RateLen = SupportedRatesLen;
-
-					break;
-				}
-			}
-		}
-		StatusCode = MLME_SUCCESS;
-
-		// can not find in table, create a new one
-		if (i < 0)
-		{
-			StatusCode = MLME_QOS_UNSPECIFY;
-			DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsReqAction() DLSEntry table full(only can support %d DLS session) \n", MAX_NUM_OF_DLS_ENTRY - MAX_NUM_OF_INIT_DLS_ENTRY));
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsReqAction() use entry(%d) %02x:%02x:%02x:%02x:%02x:%02x\n",
-				i, SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-		}
-	}
-
-	ActHeaderInit(pAd, &DlsRspHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-
-	// Build basic frame first
-	if (StatusCode == MLME_SUCCESS)
-	{
-		MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-						sizeof(HEADER_802_11),		&DlsRspHdr,
-						1,							&Category,
-						1,							&Action,
-						2,							&StatusCode,
-						6,							SA,
-						6,							pAd->CurrentAddress,
-						2,							&pAd->StaActive.CapabilityInfo,
-						1,							&SupRateIe,
-						1,							&pAd->MlmeAux.SupRateLen,
-						pAd->MlmeAux.SupRateLen,	pAd->MlmeAux.SupRate,
-						END_OF_ARGS);
-
-		if (pAd->MlmeAux.ExtRateLen != 0)
-		{
-			MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-							  1,						&ExtRateIe,
-							  1,						&pAd->MlmeAux.ExtRateLen,
-							  pAd->MlmeAux.ExtRateLen, 	pAd->MlmeAux.ExtRate,
-							  END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-#ifdef DOT11_N_SUPPORT
-		if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-		{
-			UCHAR HtLen;
-
-#ifdef RT_BIG_ENDIAN
-			HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
-
-			// add HT Capability IE
-			HtLen = sizeof(HT_CAPABILITY_IE);
-#ifndef RT_BIG_ENDIAN
-			MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-								1,						&HtCapIe,
-								1,						&HtLen,
-								HtLen,					&pAd->CommonCfg.HtCapability,
-								END_OF_ARGS);
-#else
-			NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, HtLen);
-								*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-								*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-								1,						&HtCapIe,
-								1,						&HtLen,
-								HtLen,					&HtCapabilityTmp,
-								END_OF_ARGS);
-#endif
-			FrameLen = FrameLen + tmp;
-		}
-#endif // DOT11_N_SUPPORT //
-
-		if (pDLS && (pDLS->Status != DLS_FINISH))
-		{
-			RTMPCancelTimer(&pDLS->Timer, &TimerCancelled);
-			Timeout = DLS_TIMEOUT;
-			RTMPSetTimer(&pDLS->Timer, Timeout);
-		}
-	}
-	else
-	{
-		MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-						sizeof(HEADER_802_11),		&DlsRspHdr,
-						1,							&Category,
-						1,							&Action,
-						2,							&StatusCode,
-						6,							SA,
-						6,							pAd->CurrentAddress,
-						END_OF_ARGS);
-	}
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerDlsRspAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT		CapabilityInfo;
-	UCHAR		DA[MAC_ADDR_LEN], SA[MAC_ADDR_LEN];
-	USHORT		StatusCode;
-	SHORT		i;
-	BOOLEAN		TimerCancelled;
-	UCHAR		MaxSupportedRateIn500Kbps = 0;
-    UCHAR		SupportedRatesLen;
-    UCHAR		SupportedRates[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		HtCapabilityLen;
-	HT_CAPABILITY_IE	HtCapability;
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return;
-
-	if (!INFRA_ON(pAd))
-		return;
-
-	if (!PeerDlsRspSanity(pAd, Elem->Msg, Elem->MsgLen, DA, SA, &CapabilityInfo, &StatusCode,
-							&SupportedRatesLen, &SupportedRates[0], &HtCapabilityLen, &HtCapability))
-		return;
-
-    // supported rates array may not be sorted. sort it and find the maximum rate
-    for (i=0; i<SupportedRatesLen; i++)
-    {
-        if (MaxSupportedRateIn500Kbps < (SupportedRates[i] & 0x7f))
-            MaxSupportedRateIn500Kbps = SupportedRates[i] & 0x7f;
-    }
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() from %02x:%02x:%02x:%02x:%02x:%02x with StatusCode=%d, CapabilityInfo=0x%x\n",
-		SA[0], SA[1], SA[2], SA[3], SA[4], SA[5], StatusCode, CapabilityInfo));
-
-	for (i = 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			if (StatusCode == MLME_SUCCESS)
-			{
-				MAC_TABLE_ENTRY *pEntry;
-				UCHAR MaxSupportedRate = RATE_11;
-
-				pEntry = MacTableInsertDlsEntry(pAd, SA, i);
-
-				switch (MaxSupportedRateIn500Kbps)
-				{
-					case 108: MaxSupportedRate = RATE_54;   break;
-					case 96:  MaxSupportedRate = RATE_48;   break;
-					case 72:  MaxSupportedRate = RATE_36;   break;
-					case 48:  MaxSupportedRate = RATE_24;   break;
-					case 36:  MaxSupportedRate = RATE_18;   break;
-					case 24:  MaxSupportedRate = RATE_12;   break;
-					case 18:  MaxSupportedRate = RATE_9;    break;
-					case 12:  MaxSupportedRate = RATE_6;    break;
-					case 22:  MaxSupportedRate = RATE_11;   break;
-					case 11:  MaxSupportedRate = RATE_5_5;  break;
-					case 4:   MaxSupportedRate = RATE_2;    break;
-					case 2:   MaxSupportedRate = RATE_1;    break;
-					default:  MaxSupportedRate = RATE_11;   break;
-				}
-
-				pEntry->MaxSupportedRate = min(pAd->CommonCfg.MaxTxRate, MaxSupportedRate);
-
-				if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
-				{
-					pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
-					pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
-					pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					pEntry->HTPhyMode.field.MODE = MODE_CCK;
-					pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-				}
-				else
-				{
-					pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
-					pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
-					pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					pEntry->HTPhyMode.field.MODE = MODE_OFDM;
-					pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-				}
-
-				pEntry->MaxHTPhyMode.field.BW = BW_20;
-				pEntry->MinHTPhyMode.field.BW = BW_20;
-
-#ifdef DOT11_N_SUPPORT
-				pEntry->HTCapability.MCSSet[0] = 0;
-				pEntry->HTCapability.MCSSet[1] = 0;
-
-				// If this Entry supports 802.11n, upgrade to HT rate.
-				if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-				{
-					UCHAR	j, bitmask; //k,bitmask;
-					CHAR    ii;
-
-					DBGPRINT(RT_DEBUG_OFF, ("DLS - PeerDlsRspAction Receive Peer HT Capable STA from %02x:%02x:%02x:%02x:%02x:%02x\n",
-								SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-
-					if ((HtCapability.HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-						pAd->MacTab.fAnyStationNonGF = TRUE;
-						pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
-					}
-
-					if ((HtCapability.HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
-					{
-						pEntry->MaxHTPhyMode.field.BW= BW_40;
-						pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(HtCapability.HtCapInfo.ShortGIfor40));
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.BW = BW_20;
-						pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(HtCapability.HtCapInfo.ShortGIfor20));
-						pAd->MacTab.fAnyStation20Only = TRUE;
-					}
-
-					// find max fixed rate
-					for (ii=15; ii>=0; ii--)
-					{
-						j = ii/8;
-						bitmask = (1<<(ii-(j*8)));
-						if ( (pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j]&bitmask) && (HtCapability.MCSSet[j]&bitmask))
-						{
-							pEntry->MaxHTPhyMode.field.MCS = ii;
-							break;
-						}
-						if (ii==0)
-							break;
-					}
-
-					if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
-					{
-						if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
-						{
-							// Fix MCS as HT Duplicated Mode
-							pEntry->MaxHTPhyMode.field.BW = 1;
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-							pEntry->MaxHTPhyMode.field.STBC = 0;
-							pEntry->MaxHTPhyMode.field.ShortGI = 0;
-							pEntry->MaxHTPhyMode.field.MCS = 32;
-						}
-						else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
-						{
-							// STA supports fixed MCS
-							pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
-						}
-					}
-
-					pEntry->MaxHTPhyMode.field.STBC = (HtCapability.HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
-					pEntry->MpduDensity = HtCapability.HtCapParm.MpduDensity;
-					pEntry->MaxRAmpduFactor = HtCapability.HtCapParm.MaxRAmpduFactor;
-					pEntry->MmpsMode = (UCHAR)HtCapability.HtCapInfo.MimoPs;
-					pEntry->AMsduSize = (UCHAR)HtCapability.HtCapInfo.AMsduSize;
-					pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-
-					if (HtCapability.HtCapInfo.ShortGIfor20)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
-					if (HtCapability.HtCapInfo.ShortGIfor40)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
-					if (HtCapability.HtCapInfo.TxSTBC)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
-					if (HtCapability.HtCapInfo.RxSTBC)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
-					if (HtCapability.ExtHtCapInfo.PlusHTC)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
-					if (pAd->CommonCfg.bRdg && HtCapability.ExtHtCapInfo.RDGSupport)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
-					if (HtCapability.ExtHtCapInfo.MCSFeedback == 0x03)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
-
-					NdisMoveMemory(&pEntry->HTCapability, &HtCapability, sizeof(HT_CAPABILITY_IE));
-				}
-#endif // DOT11_N_SUPPORT //
-				pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-				pEntry->CurrTxRate = pEntry->MaxSupportedRate;
-				CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-
-				if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-				{
-					PUCHAR pTable;
-					UCHAR TableSize = 0;
-
-					MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
-					pEntry->bAutoTxRateSwitch = TRUE;
-				}
-				else
-				{
-					pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-					pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
-					pEntry->bAutoTxRateSwitch = FALSE;
-
-					RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-				}
-				pEntry->RateLen = SupportedRatesLen;
-
-				if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-				{
-					// If support WPA or WPA2, start STAKey hand shake,
-					// If failed hand shake, just tear down peer DLS
-					if (RTMPSendSTAKeyRequest(pAd, pAd->StaCfg.DLSEntry[i].MacAddr) != NDIS_STATUS_SUCCESS)
-					{
-						MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-						USHORT				reason = REASON_QOS_CIPHER_NOT_SUPPORT;
-
-						DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-						MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-						pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-						pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-						DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed when call RTMPSendSTAKeyRequest \n"));
-					}
-					else
-					{
-						pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-						DBGPRINT(RT_DEBUG_TRACE,("DLS - waiting for STAKey handshake procedure\n"));
-					}
-				}
-				else
-				{
-					RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-					pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-					DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() from %02x:%02x:%02x:%02x:%02x:%02x Succeed with WEP or no security\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-				}
-
-				//initialize seq no for DLS frames.
-				pAd->StaCfg.DLSEntry[i].Sequence = 0;
-				if (HtCapabilityLen != 0)
-					pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-				else
-					pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-			}
-			else
-			{
-				// DLS setup procedure failed.
-				pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-				DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed with StatusCode=%d \n", StatusCode));
-			}
-		}
-	}
-
-	if (i >= MAX_NUM_OF_INIT_DLS_ENTRY)
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() update timeout value \n"));
-		for (i=(MAX_NUM_OF_DLS_ENTRY-1); i>=MAX_NUM_OF_INIT_DLS_ENTRY; i--)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				if (StatusCode == MLME_SUCCESS)
-				{
-					MAC_TABLE_ENTRY *pEntry;
-					UCHAR MaxSupportedRate = RATE_11;
-
-					pEntry = MacTableInsertDlsEntry(pAd, SA, i);
-
-					switch (MaxSupportedRateIn500Kbps)
-					{
-						case 108: MaxSupportedRate = RATE_54;   break;
-						case 96:  MaxSupportedRate = RATE_48;   break;
-						case 72:  MaxSupportedRate = RATE_36;   break;
-						case 48:  MaxSupportedRate = RATE_24;   break;
-						case 36:  MaxSupportedRate = RATE_18;   break;
-						case 24:  MaxSupportedRate = RATE_12;   break;
-						case 18:  MaxSupportedRate = RATE_9;    break;
-						case 12:  MaxSupportedRate = RATE_6;    break;
-						case 22:  MaxSupportedRate = RATE_11;   break;
-						case 11:  MaxSupportedRate = RATE_5_5;  break;
-						case 4:   MaxSupportedRate = RATE_2;    break;
-						case 2:   MaxSupportedRate = RATE_1;    break;
-						default:  MaxSupportedRate = RATE_11;   break;
-					}
-
-					pEntry->MaxSupportedRate = min(pAd->CommonCfg.MaxTxRate, MaxSupportedRate);
-
-					if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->HTPhyMode.field.MODE = MODE_CCK;
-						pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->HTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					}
-
-					pEntry->MaxHTPhyMode.field.BW = BW_20;
-					pEntry->MinHTPhyMode.field.BW = BW_20;
-
-#ifdef DOT11_N_SUPPORT
-					pEntry->HTCapability.MCSSet[0] = 0;
-					pEntry->HTCapability.MCSSet[1] = 0;
-
-					// If this Entry supports 802.11n, upgrade to HT rate.
-					if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-					{
-						UCHAR	j, bitmask; //k,bitmask;
-						CHAR    ii;
-
-						DBGPRINT(RT_DEBUG_OFF, ("DLS - PeerDlsRspAction Receive Peer HT Capable STA from %02x:%02x:%02x:%02x:%02x:%02x\n",
-									SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-
-						if ((HtCapability.HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-							pAd->MacTab.fAnyStationNonGF = TRUE;
-							pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
-						}
-
-						if ((HtCapability.HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
-						{
-							pEntry->MaxHTPhyMode.field.BW= BW_40;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(HtCapability.HtCapInfo.ShortGIfor40));
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.BW = BW_20;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(HtCapability.HtCapInfo.ShortGIfor20));
-							pAd->MacTab.fAnyStation20Only = TRUE;
-						}
-
-						// find max fixed rate
-						for (ii=15; ii>=0; ii--)
-						{
-							j = ii/8;
-							bitmask = (1<<(ii-(j*8)));
-							if ( (pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j]&bitmask) && (HtCapability.MCSSet[j]&bitmask))
-							{
-								pEntry->MaxHTPhyMode.field.MCS = ii;
-								break;
-							}
-							if (ii==0)
-								break;
-						}
-
-						if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
-						{
-							printk("@@@ pAd->CommonCfg.RegTransmitSetting.field.MCS = %d\n",
-								pAd->StaCfg.DesiredTransmitSetting.field.MCS);
-							if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
-							{
-								// Fix MCS as HT Duplicated Mode
-								pEntry->MaxHTPhyMode.field.BW = 1;
-								pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-								pEntry->MaxHTPhyMode.field.STBC = 0;
-								pEntry->MaxHTPhyMode.field.ShortGI = 0;
-								pEntry->MaxHTPhyMode.field.MCS = 32;
-							}
-							else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
-							{
-								// STA supports fixed MCS
-								pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
-							}
-						}
-
-						pEntry->MaxHTPhyMode.field.STBC = (HtCapability.HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
-						pEntry->MpduDensity = HtCapability.HtCapParm.MpduDensity;
-						pEntry->MaxRAmpduFactor = HtCapability.HtCapParm.MaxRAmpduFactor;
-						pEntry->MmpsMode = (UCHAR)HtCapability.HtCapInfo.MimoPs;
-						pEntry->AMsduSize = (UCHAR)HtCapability.HtCapInfo.AMsduSize;
-						pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-
-						if (HtCapability.HtCapInfo.ShortGIfor20)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
-						if (HtCapability.HtCapInfo.ShortGIfor40)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
-						if (HtCapability.HtCapInfo.TxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
-						if (HtCapability.HtCapInfo.RxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.PlusHTC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
-						if (pAd->CommonCfg.bRdg && HtCapability.ExtHtCapInfo.RDGSupport)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.MCSFeedback == 0x03)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
-
-						NdisMoveMemory(&pEntry->HTCapability, &HtCapability, sizeof(HT_CAPABILITY_IE));
-					}
-#endif // DOT11_N_SUPPORT //
-
-					pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-					pEntry->CurrTxRate = pEntry->MaxSupportedRate;
-					CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-
-					if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-					{
-						PUCHAR pTable;
-						UCHAR TableSize = 0;
-
-						MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
-						pEntry->bAutoTxRateSwitch = TRUE;
-					}
-					else
-					{
-						pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-						pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
-						pEntry->bAutoTxRateSwitch = FALSE;
-
-						RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-					}
-					pEntry->RateLen = SupportedRatesLen;
-
-					if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-					{
-						// If support WPA or WPA2, start STAKey hand shake,
-						// If failed hand shake, just tear down peer DLS
-						if (RTMPSendSTAKeyRequest(pAd, pAd->StaCfg.DLSEntry[i].MacAddr) != NDIS_STATUS_SUCCESS)
-						{
-							MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-							USHORT				reason = REASON_QOS_CIPHER_NOT_SUPPORT;
-
-							DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-							MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-							pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-							pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-							DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed when call RTMPSendSTAKeyRequest \n"));
-						}
-						else
-						{
-							pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-							DBGPRINT(RT_DEBUG_TRACE,("DLS - waiting for STAKey handshake procedure\n"));
-						}
-					}
-					else
-					{
-						RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-						pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-						DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() from %02x:%02x:%02x:%02x:%02x:%02x Succeed with WEP or no security\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-					}
-					pAd->StaCfg.DLSEntry[i].Sequence = 0;
-					if (HtCapabilityLen != 0)
-						pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-					else
-						pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-				}
-				else
-				{
-					// DLS setup procedure failed.
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-					RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-					DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed with StatusCode=%d \n", StatusCode));
-				}
-			}
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeDlsTearDownAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen = 0;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_TEARDOWN;
-	USHORT			ReasonCode = REASON_QOS_UNSPECIFY;
-	HEADER_802_11	DlsTearDownHdr;
-	PRT_802_11_DLS	pDLS;
-	BOOLEAN			TimerCancelled;
-	UCHAR			i;
-
-	if(!MlmeDlsReqSanity(pAd, Elem->Msg, Elem->MsgLen, &pDLS, &ReasonCode))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - MlmeDlsTearDownAction() with ReasonCode=%d \n", ReasonCode));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("DLS - MlmeDlsTearDownAction() allocate memory failed \n"));
-		return;
-	}
-
-	ActHeaderInit(pAd, &DlsTearDownHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-
-	// Build basic frame first
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-					sizeof(HEADER_802_11),		&DlsTearDownHdr,
-					1,							&Category,
-					1,							&Action,
-					6,							&pDLS->MacAddr,
-					6,							pAd->CurrentAddress,
-					2,							&ReasonCode,
-					END_OF_ARGS);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-	RTMPCancelTimer(&pDLS->Timer, &TimerCancelled);
-
-	// Remove key in local dls table entry
-	for (i = 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	// clear peer dls table entry
-	for (i = MAX_NUM_OF_INIT_DLS_ENTRY; i < MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-			pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerDlsTearDownAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR			DA[MAC_ADDR_LEN], SA[MAC_ADDR_LEN];
-	USHORT			ReasonCode;
-	UINT			i;
-	BOOLEAN			TimerCancelled;
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return;
-
-	if (!INFRA_ON(pAd))
-		return;
-
-	if (!PeerDlsTearDownSanity(pAd, Elem->Msg, Elem->MsgLen, DA, SA, &ReasonCode))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsTearDownAction() from %02x:%02x:%02x:%02x:%02x:%02x with ReasonCode=%d\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5], ReasonCode));
-
-	// clear local dls table entry
-	for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-			pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-			//AsicDelWcidTab(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			//AsicRemovePairwiseKeyEntry(pAd, BSS0, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	// clear peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-			pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-			//AsicDelWcidTab(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			//AsicRemovePairwiseKeyEntry(pAd, BSS0, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID RTMPCheckDLSTimeOut(
-	IN PRTMP_ADAPTER	pAd)
-{
-	ULONG				i;
-	MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-	USHORT				reason = REASON_QOS_UNSPECIFY;
-
-	if (! pAd->CommonCfg.bDLSCapable)
-		return;
-
-	if (! INFRA_ON(pAd))
-		return;
-
-	// If timeout value is equaled to zero, it means always not be timeout.
-
-	// update local dls table entry
-	for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if ((pAd->StaCfg.DLSEntry[i].Valid) && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& (pAd->StaCfg.DLSEntry[i].TimeOut != 0))
-		{
-			pAd->StaCfg.DLSEntry[i].CountDownTimer --;
-
-			if (pAd->StaCfg.DLSEntry[i].CountDownTimer == 0)
-			{
-				reason = REASON_QOS_REQUEST_TIMEOUT;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-			}
-		}
-	}
-
-	// update peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if ((pAd->StaCfg.DLSEntry[i].Valid) && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& (pAd->StaCfg.DLSEntry[i].TimeOut != 0))
-		{
-			pAd->StaCfg.DLSEntry[i].CountDownTimer --;
-
-			if (pAd->StaCfg.DLSEntry[i].CountDownTimer == 0)
-			{
-				reason = REASON_QOS_REQUEST_TIMEOUT;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-			}
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN RTMPRcvFrameDLSCheck(
-	IN PRTMP_ADAPTER	pAd,
-	IN PHEADER_802_11	pHeader,
-	IN ULONG			Len,
-	IN PRT28XX_RXD_STRUC	pRxD)
-{
-	ULONG			i;
-	BOOLEAN			bFindEntry = FALSE;
-	BOOLEAN			bSTAKeyFrame = FALSE;
-	PEAPOL_PACKET	pEap;
-	PUCHAR			pProto, pAddr = NULL;
-	PUCHAR			pSTAKey = NULL;
-	UCHAR			ZeroReplay[LEN_KEY_DESC_REPLAY];
-	UCHAR			Mic[16], OldMic[16];
-	UCHAR			digest[80];
-	UCHAR			DlsPTK[80];
-	UCHAR			temp[64];
-	BOOLEAN			TimerCancelled;
-	CIPHER_KEY		PairwiseKey;
-
-
-	if (! pAd->CommonCfg.bDLSCapable)
-		return bSTAKeyFrame;
-
-	if (! INFRA_ON(pAd))
-		return bSTAKeyFrame;
-
-	if (! (pHeader->FC.SubType & 0x08))
-		return bSTAKeyFrame;
-
-	if (Len < LENGTH_802_11 + 6 + 2 + 2)
-		return bSTAKeyFrame;
-
-	pProto	= (PUCHAR)pHeader + LENGTH_802_11 + 2 + 6;	// QOS Control field , 0xAA 0xAA 0xAA 0x00 0x00 0x00
-	pAddr	= pHeader->Addr2;
-
-	// L2PAD bit on will pad 2 bytes at LLC
-	if (pRxD->L2PAD)
-	{
-		pProto += 2;
-	}
-
-	if (RTMPEqualMemory(EAPOL, pProto, 2) && (pAd->StaCfg.AuthMode >=  Ndis802_11AuthModeWPA))
-	{
-		pEap = (PEAPOL_PACKET) (pProto + 2);
-
-		DBGPRINT(RT_DEBUG_TRACE,("DLS - Sniff Len=%ld, DataLen=%d, KeyMic=%d, Install=%d, KeyAck=%d, Secure=%d, EKD_DL=%d, Error=%d, Request=%d\n", Len,
-			                                                             (LENGTH_802_11 + 6 + 2 + 2 + sizeof(EAPOL_PACKET) - MAX_LEN_OF_RSNIE + 16),
-			                                                             pEap->KeyDesc.KeyInfo.KeyMic,
-			                                                             pEap->KeyDesc.KeyInfo.Install,
-			                                                             pEap->KeyDesc.KeyInfo.KeyAck,
-			                                                             pEap->KeyDesc.KeyInfo.Secure,
-			                                                             pEap->KeyDesc.KeyInfo.EKD_DL,
-			                                                             pEap->KeyDesc.KeyInfo.Error,
-			                                                             pEap->KeyDesc.KeyInfo.Request));
-
-		if ((Len >= (LENGTH_802_11 + 6 + 2 + 2 + sizeof(EAPOL_PACKET) - MAX_LEN_OF_RSNIE + 16)) && pEap->KeyDesc.KeyInfo.KeyMic
-			&& pEap->KeyDesc.KeyInfo.Install && pEap->KeyDesc.KeyInfo.KeyAck && pEap->KeyDesc.KeyInfo.Secure
-			&& pEap->KeyDesc.KeyInfo.EKD_DL && !pEap->KeyDesc.KeyInfo.Error && !pEap->KeyDesc.KeyInfo.Request)
-		{
-			// First validate replay counter, only accept message with larger replay counter
-			// Let equal pass, some AP start with all zero replay counter
-			NdisZeroMemory(ZeroReplay, LEN_KEY_DESC_REPLAY);
-			if ((RTMPCompareMemory(pEap->KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1) &&
-				(RTMPCompareMemory(pEap->KeyDesc.ReplayCounter, ZeroReplay, LEN_KEY_DESC_REPLAY) != 0))
-				return bSTAKeyFrame;
-
-			//RTMPMoveMemory(pAd->StaCfg.ReplayCounter, pEap->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-			RTMPMoveMemory(pAd->StaCfg.DlsReplayCounter, pEap->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - Sniff replay counter (%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x) Len=%ld, KeyDataLen=%d\n",
-				pAd->StaCfg.ReplayCounter[0], pAd->StaCfg.ReplayCounter[1], pAd->StaCfg.ReplayCounter[2],
-				pAd->StaCfg.ReplayCounter[3], pAd->StaCfg.ReplayCounter[4],	pAd->StaCfg.ReplayCounter[5],
-				pAd->StaCfg.ReplayCounter[6], pAd->StaCfg.ReplayCounter[7], Len, pEap->KeyDesc.KeyData[1]));
-
-			// put these code segment to get the replay counter
-			if (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED)
-				return bSTAKeyFrame;
-
-			// Check MIC value
-			// Save the MIC and replace with zero
-			// use proprietary PTK
-			NdisZeroMemory(temp, 64);
-			NdisMoveMemory(temp, "IEEE802.11 WIRELESS ACCESS POINT", 32);
-			WpaCountPTK(pAd, temp, temp, pAd->CommonCfg.Bssid, temp, pAd->CurrentAddress, DlsPTK, LEN_PTK);
-
-			NdisMoveMemory(OldMic, pEap->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-			NdisZeroMemory(pEap->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-			if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-			{
-				// AES
-				HMAC_SHA1((PUCHAR) pEap, pEap->Body_Len[1] + 4, DlsPTK, LEN_EAP_MICK, digest);
-				NdisMoveMemory(Mic,	digest,	LEN_KEY_DESC_MIC);
-			}
-			else
-			{
-				hmac_md5(DlsPTK, LEN_EAP_MICK, (PUCHAR) pEap, pEap->Body_Len[1] + 4, Mic);
-			}
-
-			if (!NdisEqualMemory(OldMic, Mic, LEN_KEY_DESC_MIC))
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("MIC Different in Msg1 of STAKey handshake! \n"));
-				return bSTAKeyFrame;
-			}
-			else
-				DBGPRINT(RT_DEBUG_TRACE, ("MIC VALID in Msg1 of STAKey handshake! \n"));
-#if 1
-			if ((pEap->KeyDesc.KeyData[0] == 0xDD) && (pEap->KeyDesc.KeyData[2] == 0x00) && (pEap->KeyDesc.KeyData[3] == 0x0C)
-				&& (pEap->KeyDesc.KeyData[4] == 0x43) && (pEap->KeyDesc.KeyData[5] == 0x02))
-			{
-				pAddr			= pEap->KeyDesc.KeyData + 8;		// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2)
-				pSTAKey			= pEap->KeyDesc.KeyData + 14;	// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2), STAKey_Mac_Addr(6)
-
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 from %02x:%02x:%02x:%02x:%02x:%02x Len=%ld, KeyDataLen=%d\n",
-					pAddr[0], pAddr[1], pAddr[2], pAddr[3], pAddr[4], pAddr[5], Len, pEap->KeyDesc.KeyData[1]));
-
-				bSTAKeyFrame = TRUE;
-			}
-#else
-			if ((pEap->KeyDesc.KeyData[0] == 0xDD) && (pEap->KeyDesc.KeyData[2] == 0x00) && (pEap->KeyDesc.KeyData[3] == 0x0F)
-				&& (pEap->KeyDesc.KeyData[4] == 0xAC) && (pEap->KeyDesc.KeyData[5] == 0x02))
-			{
-				pAddr			= pEap->KeyDesc.KeyData + 8;		// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2)
-				pSTAKey			= pEap->KeyDesc.KeyData + 14;	// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2), STAKey_Mac_Addr(6)
-
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 from %02x:%02x:%02x:%02x:%02x:%02x Len=%d, KeyDataLen=%d\n",
-					pAddr[0], pAddr[1], pAddr[2], pAddr[3], pAddr[4], pAddr[5], Len, pEap->KeyDesc.KeyData[1]));
-
-				bSTAKeyFrame = TRUE;
-			}
-#endif
-
-		}
-		else if (Len >= (LENGTH_802_11 + 6 + 2 + 2 + sizeof(EAPOL_PACKET) - MAX_LEN_OF_RSNIE))
-		{
-#if 0
-			RTMPMoveMemory(pAd->StaCfg.ReplayCounter, pEap->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-#endif
-			RTMPMoveMemory(pAd->StaCfg.DlsReplayCounter, pEap->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - Sniff replay counter 2(%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x) Len=%ld, KeyDataLen=%d\n",
-				pAd->StaCfg.ReplayCounter[0], pAd->StaCfg.ReplayCounter[1], pAd->StaCfg.ReplayCounter[2],
-				pAd->StaCfg.ReplayCounter[3], pAd->StaCfg.ReplayCounter[4],	pAd->StaCfg.ReplayCounter[5],
-				pAd->StaCfg.ReplayCounter[6], pAd->StaCfg.ReplayCounter[7], Len, pEap->KeyDesc.KeyData[1]));
-
-		}
-	}
-
-	// If timeout value is equaled to zero, it means always not be timeout.
-	// update local dls table entry
-	for (i= 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(pAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			if (bSTAKeyFrame)
-			{
-				PMAC_TABLE_ENTRY pEntry;
-
-				// STAKey frame, add pairwise key table
-				pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-				RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-
-				PairwiseKey.KeyLen = LEN_TKIP_EK;
-				NdisMoveMemory(PairwiseKey.Key, &pSTAKey[0], LEN_TKIP_EK);
-				NdisMoveMemory(PairwiseKey.TxMic, &pSTAKey[16], LEN_TKIP_RXMICK);
-				NdisMoveMemory(PairwiseKey.RxMic, &pSTAKey[24], LEN_TKIP_TXMICK);
-
-				PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg;
-
-				pEntry = DlsEntryTableLookup(pAd, pAd->StaCfg.DLSEntry[i].MacAddr, TRUE);
-				//AsicAddKeyEntry(pAd, (USHORT)(i + 2), BSS0, 0, &PairwiseKey, TRUE, TRUE);	// reserve 0 for multicast, 1 for unicast
-				//AsicUpdateRxWCIDTable(pAd, (USHORT)(i + 2), pAddr);
-				// Add Pair-wise key to Asic
-            	AsicAddPairwiseKeyEntry(pAd,
-										pAd->StaCfg.DLSEntry[i].MacAddr,
-										(UCHAR)pAd->StaCfg.DLSEntry[i].MacTabMatchWCID,
-										&PairwiseKey);
-
-				RTMPAddWcidAttributeEntry(pAd,
-										  BSS0,
-										  0,
-										  PairwiseKey.CipherAlg,
-										  pEntry);
-
-				NdisMoveMemory(&pEntry->PairwiseKey, &PairwiseKey, sizeof(CIPHER_KEY));
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 (Peer STA MAC Address STAKey) \n"));
-
-				RTMPSendSTAKeyHandShake(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Finish STAKey handshake procedure (Initiator side)\n"));
-			}
-			else
-			{
-				// Data frame, update timeout value
-				if (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-				{
-					pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-					//AsicUpdateRxWCIDTable(pAd, (USHORT)(i + 2), pAddr);
-				}
-			}
-
-			bFindEntry = TRUE;
-		}
-	}
-
-	// update peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(pAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			if (bSTAKeyFrame)
-			{
-				PMAC_TABLE_ENTRY pEntry = NULL;
-
-				// STAKey frame, add pairwise key table, and send STAkey Msg-2
-				pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-				RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-
-				PairwiseKey.KeyLen = LEN_TKIP_EK;
-				NdisMoveMemory(PairwiseKey.Key, &pSTAKey[0], LEN_TKIP_EK);
-				NdisMoveMemory(PairwiseKey.TxMic, &pSTAKey[16], LEN_TKIP_RXMICK);
-				NdisMoveMemory(PairwiseKey.RxMic, &pSTAKey[24], LEN_TKIP_TXMICK);
-
-				PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg;
-
-				pEntry = DlsEntryTableLookup(pAd, pAd->StaCfg.DLSEntry[i].MacAddr, TRUE);
-				//AsicAddKeyEntry(pAd, (USHORT)(i + 2), BSS0, 0, &PairwiseKey, TRUE, TRUE);	// reserve 0 for multicast, 1 for unicast
-				//AsicUpdateRxWCIDTable(pAd, (USHORT)(i + 2), pAddr);
-				// Add Pair-wise key to Asic
-            	AsicAddPairwiseKeyEntry(pAd,
-										pAd->StaCfg.DLSEntry[i].MacAddr,
-										(UCHAR)pAd->StaCfg.DLSEntry[i].MacTabMatchWCID,
-										&PairwiseKey);
-
-				RTMPAddWcidAttributeEntry(pAd,
-										  BSS0,
-										  0,
-										  PairwiseKey.CipherAlg,
-										  pEntry);
-				NdisMoveMemory(&pEntry->PairwiseKey, &PairwiseKey, sizeof(CIPHER_KEY));
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 (Initiator STA MAC Address STAKey)\n"));
-
-				// If support WPA or WPA2, start STAKey hand shake,
-				// If failed hand shake, just tear down peer DLS
-				if (RTMPSendSTAKeyHandShake(pAd, pAddr) != NDIS_STATUS_SUCCESS)
-				{
-					MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-					USHORT				reason = REASON_QOS_CIPHER_NOT_SUPPORT;
-
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-					pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-					DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-					MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE,("DLS - Finish STAKey handshake procedure (Peer side)\n"));
-				}
-			}
-			else
-			{
-				// Data frame, update timeout value
-				if (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-				{
-					pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-				}
-			}
-
-			bFindEntry = TRUE;
-		}
-	}
-
-
-	return bSTAKeyFrame;
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Check if the frame can be sent through DLS direct link interface
-
-	Arguments:
-		pAd		Pointer	to adapter
-
-	Return Value:
-		DLS entry index
-
-	Note:
-
-	========================================================================
-*/
-INT	RTMPCheckDLSFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA)
-{
-	INT rval = -1;
-	INT	i;
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return rval;
-
-	if (!INFRA_ON(pAd))
-		return rval;
-
-	do{
-		// check local dls table entry
-		for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				rval = i;
-				break;
-			}
-		}
-
-		// check peer dls table entry
-		for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				rval = i;
-				break;
-			}
-		}
-	} while (FALSE);
-
-	return rval;
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID RTMPSendDLSTearDownFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	HEADER_802_11	DlsTearDownHdr;
-	ULONG			FrameLen = 0;
-	USHORT			Reason = REASON_QOS_QSTA_LEAVING_QBSS;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_TEARDOWN;
-	UCHAR			i = 0;
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS) ||
-		RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Send DLS TearDown Frame \n"));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("ASSOC - RTMPSendDLSTearDownFrame() allocate memory failed \n"));
-		return;
-	}
-
-	ActHeaderInit(pAd, &DlsTearDownHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-					sizeof(HEADER_802_11),		&DlsTearDownHdr,
-					1,							&Category,
-					1,							&Action,
-					6,							pDA,
-					6,							pAd->CurrentAddress,
-					2,							&Reason,
-					END_OF_ARGS);
-
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	// Remove key in local dls table entry
-	for (i = 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	// Remove key in peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Send DLS TearDown Frame and remove key in (i=%d) \n", i));
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-NDIS_STATUS RTMPSendSTAKeyRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA)
-{
-	UCHAR				Header802_3[14];
-	NDIS_STATUS			NStatus;
-	ULONG				FrameLen = 0;
-	EAPOL_PACKET		Packet;
-	UCHAR				Mic[16];
-	UCHAR				digest[80];
-	PUCHAR				pOutBuffer = NULL;
-	PNDIS_PACKET		pNdisPacket;
-	UCHAR				temp[64];
-	UCHAR				DlsPTK[80];
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - RTMPSendSTAKeyRequest() to %02x:%02x:%02x:%02x:%02x:%02x\n", pDA[0], pDA[1], pDA[2], pDA[3], pDA[4], pDA[5]));
-
-	pAd->Sequence ++;
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero message body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer = EAPOL_VER;
-	Packet.ProType    = EAPOLKey;
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE + 6 + MAC_ADDR_LEN;		// data field contain KDE andPeer MAC address
-
-	// STAKey Message is as EAPOL-Key(1,1,0,0,G/0,0,0, MIC, 0,Peer MAC KDE)
-	if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-    {
-        Packet.KeyDesc.Type = WPA1_KEY_DESC;
-    }
-    else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-    {
-        Packet.KeyDesc.Type = WPA2_KEY_DESC;
-    }
-
-	// Key descriptor version
-	Packet.KeyDesc.KeyInfo.KeyDescVer =
-		(((pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled) || (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)) ? (DESC_TYPE_AES) : (DESC_TYPE_TKIP));
-
-	Packet.KeyDesc.KeyInfo.KeyMic	= 1;
-	Packet.KeyDesc.KeyInfo.Secure	= 1;
-	Packet.KeyDesc.KeyInfo.Request	= 1;
-
-	Packet.KeyDesc.KeyDataLen[1]	= 12;
-
-	// use our own OUI to distinguish proprietary with standard.
-	Packet.KeyDesc.KeyData[0]		= 0xDD;
-	Packet.KeyDesc.KeyData[1]		= 0x0A;
-	Packet.KeyDesc.KeyData[2]		= 0x00;
-	Packet.KeyDesc.KeyData[3]		= 0x0C;
-	Packet.KeyDesc.KeyData[4]		= 0x43;
-	Packet.KeyDesc.KeyData[5]		= 0x03;
-	NdisMoveMemory(&Packet.KeyDesc.KeyData[6], pDA, MAC_ADDR_LEN);
-
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.DlsReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Allocate buffer for transmitting message
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-	if (NStatus	!= NDIS_STATUS_SUCCESS)
-		return NStatus;
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		              Packet.Body_Len[1] + 4,    &Packet,
-		              END_OF_ARGS);
-
-	// use proprietary PTK
-	NdisZeroMemory(temp, 64);
-	NdisMoveMemory(temp, "IEEE802.11 WIRELESS ACCESS POINT", 32);
-	WpaCountPTK(pAd, temp, temp, pAd->CommonCfg.Bssid, temp, pAd->CurrentAddress, DlsPTK, LEN_PTK);
-
-	// calculate MIC
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		NdisZeroMemory(digest,	sizeof(digest));
-		HMAC_SHA1(pOutBuffer, FrameLen, DlsPTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		NdisZeroMemory(Mic,	sizeof(Mic));
-		hmac_md5(DlsPTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-	}
-
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-	                  sizeof(Header802_3),	Header802_3,
-		              Packet.Body_Len[1] + 4,	&Packet,
-		              END_OF_ARGS);
-
-	NStatus = RTMPAllocateNdisPacket(pAd, &pNdisPacket, NULL, 0, pOutBuffer, FrameLen);
-	if (NStatus == NDIS_STATUS_SUCCESS)
-	{
-		RTMP_SET_PACKET_WCID(pNdisPacket, BSSID_WCID);
-		STASendPacket(pAd, pNdisPacket);
-		RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSendSTAKeyRequest- Send STAKey request (NStatus=%x, FrameLen=%ld)\n", NStatus, FrameLen));
-
-	return NStatus;
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-NDIS_STATUS RTMPSendSTAKeyHandShake(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA)
-{
-	UCHAR				Header802_3[14];
-	NDIS_STATUS			NStatus;
-	ULONG				FrameLen = 0;
-	EAPOL_PACKET		Packet;
-	UCHAR				Mic[16];
-	UCHAR				digest[80];
-	PUCHAR				pOutBuffer = NULL;
-	PNDIS_PACKET		pNdisPacket;
-	UCHAR				temp[64];
-	UCHAR				DlsPTK[80];			// Due to dirver can not get PTK, use proprietary PTK
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - RTMPSendSTAKeyHandShake() to %02x:%02x:%02x:%02x:%02x:%02x\n", pDA[0], pDA[1], pDA[2], pDA[3], pDA[4], pDA[5]));
-
-	pAd->Sequence ++;
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero message body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer = EAPOL_VER;
-	Packet.ProType    = EAPOLKey;
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE + 6 + MAC_ADDR_LEN;		// data field contain KDE and Peer MAC address
-
-	// STAKey Message is as EAPOL-Key(1,1,0,0,G/0,0,0, MIC, 0,Peer MAC KDE)
-	if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-    {
-        Packet.KeyDesc.Type = WPA1_KEY_DESC;
-    }
-    else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-    {
-        Packet.KeyDesc.Type = WPA2_KEY_DESC;
-    }
-
-	// Key descriptor version
-	Packet.KeyDesc.KeyInfo.KeyDescVer =
-		(((pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled) || (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)) ? (DESC_TYPE_AES) : (DESC_TYPE_TKIP));
-
-	Packet.KeyDesc.KeyInfo.KeyMic	= 1;
-	Packet.KeyDesc.KeyInfo.Secure	= 1;
-
-	Packet.KeyDesc.KeyDataLen[1]	= 12;
-
-	// use our own OUI to distinguish proprietary with standard.
-	Packet.KeyDesc.KeyData[0]		= 0xDD;
-	Packet.KeyDesc.KeyData[1]		= 0x0A;
-	Packet.KeyDesc.KeyData[2]		= 0x00;
-	Packet.KeyDesc.KeyData[3]		= 0x0C;
-	Packet.KeyDesc.KeyData[4]		= 0x43;
-	Packet.KeyDesc.KeyData[5]		= 0x03;
-	NdisMoveMemory(&Packet.KeyDesc.KeyData[6], pDA, MAC_ADDR_LEN);
-
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.DlsReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Allocate buffer for transmitting message
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-	if (NStatus	!= NDIS_STATUS_SUCCESS)
-		return NStatus;
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		              Packet.Body_Len[1] + 4,    &Packet,
-		              END_OF_ARGS);
-
-	// use proprietary PTK
-	NdisZeroMemory(temp, 64);
-	NdisMoveMemory(temp, "IEEE802.11 WIRELESS ACCESS POINT", 32);
-	WpaCountPTK(pAd, temp, temp, pAd->CommonCfg.Bssid, temp, pAd->CurrentAddress, DlsPTK, LEN_PTK);
-
-	// calculate MIC
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		NdisZeroMemory(digest,	sizeof(digest));
-		HMAC_SHA1(pOutBuffer, FrameLen, DlsPTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		NdisZeroMemory(Mic,	sizeof(Mic));
-		hmac_md5(DlsPTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-	}
-
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-	                  sizeof(Header802_3),	Header802_3,
-		              Packet.Body_Len[1] + 4,	&Packet,
-		              END_OF_ARGS);
-
-	NStatus = RTMPAllocateNdisPacket(pAd, &pNdisPacket, NULL, 0, pOutBuffer, FrameLen);
-	if (NStatus == NDIS_STATUS_SUCCESS)
-	{
-		RTMP_SET_PACKET_WCID(pNdisPacket, BSSID_WCID);
-		STASendPacket(pAd, pNdisPacket);
-		RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSendSTAKeyHandShake- Send STAKey Message-2 (NStatus=%x, FrameLen=%ld)\n", NStatus, FrameLen));
-
-	return NStatus;
-}
-
-VOID DlsTimeoutAction(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	MLME_DLS_REQ_STRUCT		MlmeDlsReq;
-	USHORT					reason;
-	PRT_802_11_DLS			pDLS = (PRT_802_11_DLS)FunctionContext;
-	PRTMP_ADAPTER			pAd = pDLS->pAd;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("DlsTimeout - Tear down DLS links (%02x:%02x:%02x:%02x:%02x:%02x)\n",
-		pDLS->MacAddr[0], pDLS->MacAddr[1], pDLS->MacAddr[2], pDLS->MacAddr[3], pDLS->MacAddr[4], pDLS->MacAddr[5]));
-
-	if ((pDLS) && (pDLS->Valid))
-	{
-		reason			= REASON_QOS_REQUEST_TIMEOUT;
-		pDLS->Valid		= FALSE;
-		pDLS->Status	= DLS_NONE;
-		DlsParmFill(pAd, &MlmeDlsReq, pDLS, reason);
-		MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-		RT28XX_MLME_HANDLER(pAd);
-	}
-}
-
-/*
-================================================================
-Description : because DLS and CLI share the same WCID table in ASIC.
-Mesh entry also insert to pAd->MacTab.content[].  Such is marked as ValidAsDls = TRUE.
-Also fills the pairwise key.
-Because front MAX_AID_BA entries have direct mapping to BAEntry, which is only used as CLI. So we insert Dls
-from index MAX_AID_BA.
-================================================================
-*/
-MAC_TABLE_ENTRY *MacTableInsertDlsEntry(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR	pAddr,
-	IN  UINT	DlsEntryIdx)
-{
-	PMAC_TABLE_ENTRY pEntry = NULL;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("====> MacTableInsertDlsEntry\n"));
-	// if FULL, return
-	if (pAd->MacTab.Size >= MAX_LEN_OF_MAC_TABLE)
-		return NULL;
-
-	do
-	{
-		if((pEntry = DlsEntryTableLookup(pAd, pAddr, TRUE)) != NULL)
-			break;
-
-		// allocate one MAC entry
-		pEntry = MacTableInsertEntry(pAd, pAddr, DlsEntryIdx + MIN_NET_DEVICE_FOR_DLS, TRUE);
-		if (pEntry)
-		{
-			pAd->StaCfg.DLSEntry[DlsEntryIdx].MacTabMatchWCID = pEntry->Aid;
-			pEntry->MatchDlsEntryIdx = DlsEntryIdx;
-			pEntry->AuthMode = pAd->StaCfg.AuthMode;
-			pEntry->WepStatus = pAd->StaCfg.WepStatus;
-			pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("MacTableInsertDlsEntry - allocate entry #%d, Total= %d\n",pEntry->Aid, pAd->MacTab.Size));
-
-			// If legacy WEP is used, set pair-wise cipherAlg into WCID attribute table for this entry
-			if ((pEntry->ValidAsDls) && (pEntry->WepStatus == Ndis802_11WEPEnabled))
-			{
-				UCHAR KeyIdx = 0;
-				UCHAR CipherAlg = 0;
-
-				KeyIdx	= pAd->StaCfg.DefaultKeyId;
-
-				CipherAlg 	= pAd->SharedKey[BSS0][KeyIdx].CipherAlg;
-
-				RTMPAddWcidAttributeEntry(pAd,
-											BSS0,
-											pAd->StaCfg.DefaultKeyId,
-											pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-											pEntry);
-			}
-
-			break;
-		}
-	} while(FALSE);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==== MacTableInsertDlsEntry\n"));
-
-	return pEntry;
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Delete all Mesh Entry in pAd->MacTab
-	==========================================================================
- */
-BOOLEAN MacTableDeleteDlsEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT wcid,
-	IN PUCHAR pAddr)
-{
-	DBGPRINT(RT_DEBUG_TRACE, ("====> MacTableDeleteDlsEntry\n"));
-
-	if (!VALID_WCID(wcid))
-		return FALSE;
-
-	MacTableDeleteEntry(pAd, wcid, pAddr);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==== MacTableDeleteDlsEntry\n"));
-
-	return TRUE;
-}
-
-MAC_TABLE_ENTRY *DlsEntryTableLookup(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount)
-{
-	ULONG HashIdx;
-	MAC_TABLE_ENTRY *pEntry = NULL;
-
-	RTMP_SEM_LOCK(&pAd->MacTabLock);
-	HashIdx = MAC_ADDR_HASH_INDEX(pAddr);
-	pEntry = pAd->MacTab.Hash[HashIdx];
-
-	while (pEntry)
-	{
-		if ((pEntry->ValidAsDls == TRUE)
-			&& MAC_ADDR_EQUAL(pEntry->Addr, pAddr))
-		{
-			if(bResetIdelCount)
-				pEntry->NoDataIdleCount = 0;
-			break;
-		}
-		else
-			pEntry = pEntry->pNext;
-	}
-
-	RTMP_SEM_UNLOCK(&pAd->MacTabLock);
-	return pEntry;
-}
-
-MAC_TABLE_ENTRY *DlsEntryTableLookupByWcid(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR	wcid,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount)
-{
-	ULONG DLsIndex;
-	PMAC_TABLE_ENTRY pCurEntry = NULL;
-	PMAC_TABLE_ENTRY pEntry = NULL;
-
-	if (!VALID_WCID(wcid))
-		return NULL;
-
-	RTMP_SEM_LOCK(&pAd->MacTabLock);
-
-	do
-	{
-		pCurEntry = &pAd->MacTab.Content[wcid];
-
-		DLsIndex = 0xff;
-		if ((pCurEntry) && (pCurEntry->ValidAsDls== TRUE))
-		{
-			DLsIndex = pCurEntry->MatchDlsEntryIdx;
-		}
-
-		if (DLsIndex == 0xff)
-			break;
-
-		if (MAC_ADDR_EQUAL(pCurEntry->Addr, pAddr))
-		{
-			if(bResetIdelCount)
-				pCurEntry->NoDataIdleCount = 0;
-			pEntry = pCurEntry;
-			break;
-		}
-	} while(FALSE);
-
-	RTMP_SEM_UNLOCK(&pAd->MacTabLock);
-
-	return pEntry;
-}
-
-INT Set_DlsEntryInfo_Display_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg)
-{
-	INT i;
-
-	printk("\n%-19s%-8s\n", "MAC", "TIMEOUT\n");
-	for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if ((pAd->StaCfg.DLSEntry[i].Valid) && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-		{
-			PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[pAd->StaCfg.DLSEntry[i].MacTabMatchWCID];
-
-			printk("%02x:%02x:%02x:%02x:%02x:%02x  ",
-				pAd->StaCfg.DLSEntry[i].MacAddr[0], pAd->StaCfg.DLSEntry[i].MacAddr[1], pAd->StaCfg.DLSEntry[i].MacAddr[2],
-				pAd->StaCfg.DLSEntry[i].MacAddr[3], pAd->StaCfg.DLSEntry[i].MacAddr[4], pAd->StaCfg.DLSEntry[i].MacAddr[5]);
-			printk("%-8d\n", pAd->StaCfg.DLSEntry[i].TimeOut);
-
-			printk("\n");
-			printk("\n%-19s%-4s%-4s%-4s%-4s%-8s%-7s%-7s%-7s%-10s%-6s%-6s%-6s%-6s\n",
-				   "MAC", "AID", "BSS", "PSM", "WMM", "MIMOPS", "RSSI0", "RSSI1", "RSSI2", "PhMd", "BW", "MCS", "SGI", "STBC");
-			printk("%02X:%02X:%02X:%02X:%02X:%02X  ",
-				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
-				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5]);
-			printk("%-4d", (int)pEntry->Aid);
-			printk("%-4d", (int)pEntry->apidx);
-			printk("%-4d", (int)pEntry->PsMode);
-			printk("%-4d", (int)CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE));
-			printk("%-8d", (int)pEntry->MmpsMode);
-			printk("%-7d", pEntry->RssiSample.AvgRssi0);
-			printk("%-7d", pEntry->RssiSample.AvgRssi1);
-			printk("%-7d", pEntry->RssiSample.AvgRssi2);
-			printk("%-10s", GetPhyMode(pEntry->HTPhyMode.field.MODE));
-			printk("%-6s", GetBW(pEntry->HTPhyMode.field.BW));
-			printk("%-6d", pEntry->HTPhyMode.field.MCS);
-			printk("%-6d", pEntry->HTPhyMode.field.ShortGI);
-			printk("%-6d", pEntry->HTPhyMode.field.STBC);
-			printk("%-10d, %d, %d%%\n", pEntry->DebugFIFOCount, pEntry->DebugTxCount,
-						(pEntry->DebugTxCount) ? ((pEntry->DebugTxCount-pEntry->DebugFIFOCount)*100/pEntry->DebugTxCount) : 0);
-			printk("\n");
-
-		}
-	}
-
-	return TRUE;
-}
-
-INT	Set_DlsAddEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    UCHAR	mac[MAC_ADDR_LEN];
-	USHORT	Timeout;
-	char *token, sepValue[] = ":", DASH = '-';
-	INT i;
-    RT_802_11_DLS	Dls;
-
-    if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and timeout value in decimal format.
-		return FALSE;
-
-	token = strchr(arg, DASH);
-	if ((token != NULL) && (strlen(token)>1))
-	{
-		Timeout = simple_strtol((token+1), 0, 10);
-
-		*token = '\0';
-		for (i = 0, token = rstrtok(arg, &sepValue[0]); token; token = rstrtok(NULL, &sepValue[0]), i++)
-		{
-			if((strlen(token) != 2) || (!isxdigit(*token)) || (!isxdigit(*(token+1))))
-				return FALSE;
-			AtoH(token, (PUCHAR)(&mac[i]), 1);
-		}
-		if(i != 6)
-			return FALSE;
-
-	    printk("\n%02x:%02x:%02x:%02x:%02x:%02x-%d", mac[0], mac[1],
-	           mac[2], mac[3], mac[4], mac[5], (int)Timeout);
-
-		NdisZeroMemory(&Dls, sizeof(RT_802_11_DLS));
-		Dls.TimeOut = Timeout;
-		COPY_MAC_ADDR(Dls.MacAddr, mac);
-		Dls.Valid = 1;
-
-		MlmeEnqueue(pAd,
-					MLME_CNTL_STATE_MACHINE,
-					RT_OID_802_11_SET_DLS_PARAM,
-					sizeof(RT_802_11_DLS),
-					&Dls);
-
-		return TRUE;
-	}
-
-	return FALSE;
-
-}
-
-INT	Set_DlsTearDownEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR			macAddr[MAC_ADDR_LEN];
-	CHAR			*value;
-	INT				i;
-	RT_802_11_DLS	Dls;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-	for (i=0, value = rstrtok(arg,":"); value; value = rstrtok(NULL,":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-		AtoH(value, &macAddr[i++], 2);
-	}
-
-	printk("\n%02x:%02x:%02x:%02x:%02x:%02x", macAddr[0], macAddr[1],
-	           macAddr[2], macAddr[3], macAddr[4], macAddr[5]);
-
-	NdisZeroMemory(&Dls, sizeof(RT_802_11_DLS));
-	COPY_MAC_ADDR(Dls.MacAddr, macAddr);
-	Dls.Valid = 0;
-
-	MlmeEnqueue(pAd,
-				MLME_CNTL_STATE_MACHINE,
-				RT_OID_802_11_SET_DLS_PARAM,
-				sizeof(RT_802_11_DLS),
-				&Dls);
-
-	return TRUE;
-}
-
diff --git a/drivers/staging/rt2860/sta/rtmp_data.c b/drivers/staging/rt2860/sta/rtmp_data.c
index c5e76a2..b41ce23 100644
--- a/drivers/staging/rt2860/sta/rtmp_data.c
+++ b/drivers/staging/rt2860/sta/rtmp_data.c
@@ -50,7 +50,6 @@
 	PRXWI_STRUC		pRxWI = pRxBlk->pRxWI;
 	UCHAR			*pTmpBuf;
 
-#ifdef WPA_SUPPLICANT_SUPPORT
 	if (pAd->StaCfg.WpaSupplicantUP)
 	{
 		// All EAPoL frames have to pass to upper layer (ex. WPA_SUPPLICANT daemon)
@@ -75,6 +74,7 @@
 
                     if (pAd->StaCfg.DesireSharedKey[idx].KeyLen > 0)
     				{
+#ifdef RT2860
 						MAC_TABLE_ENTRY *pEntry = &pAd->MacTab.Content[BSSID_WCID];
 
 						// Set key material and cipherAlg to Asic
@@ -88,6 +88,32 @@
 
                         pAd->IndicateMediaState = NdisMediaStateConnected;
                         pAd->ExtraInfo = GENERAL_LINK_UP;
+#endif
+#ifdef RT2870
+						union
+						{
+							char buf[sizeof(NDIS_802_11_WEP)+MAX_LEN_OF_KEY- 1];
+							NDIS_802_11_WEP keyinfo;
+						}  WepKey;
+						int len;
+
+
+						NdisZeroMemory(&WepKey, sizeof(WepKey));
+						len =pAd->StaCfg.DesireSharedKey[idx].KeyLen;
+
+						NdisMoveMemory(WepKey.keyinfo.KeyMaterial,
+							pAd->StaCfg.DesireSharedKey[idx].Key,
+							pAd->StaCfg.DesireSharedKey[idx].KeyLen);
+
+						WepKey.keyinfo.KeyIndex = 0x80000000 + idx;
+						WepKey.keyinfo.KeyLength = len;
+						pAd->SharedKey[BSS0][idx].KeyLen =(UCHAR) (len <= 5 ? 5 : 13);
+
+						pAd->IndicateMediaState = NdisMediaStateConnected;
+						pAd->ExtraInfo = GENERAL_LINK_UP;
+						// need to enqueue cmd to thread
+						RTUSBEnqueueCmdFromNdis(pAd, OID_802_11_ADD_WEP, TRUE, &WepKey, sizeof(WepKey.keyinfo) + len - 1);
+#endif // RT2870 //
 						// For Preventing ShardKey Table is cleared by remove key procedure.
     					pAd->SharedKey[BSS0][idx].CipherAlg = CipherAlg;
 						pAd->SharedKey[BSS0][idx].KeyLen = pAd->StaCfg.DesireSharedKey[idx].KeyLen;
@@ -103,7 +129,6 @@
 		}
 	}
 	else
-#endif // WPA_SUPPLICANT_SUPPORT //
 	{
 		// Special DATA frame that has to pass to MLME
 		//	 1. Cisco Aironet frames for CCX2. We need pass it to MLME for special process
@@ -168,20 +193,16 @@
 			// ARALINK
 			CmmRxRalinkFrameIndicate(pAd, pEntry, pRxBlk, FromWhichBSSID);
 		}
-#ifdef QOS_DLS_SUPPORT
-		RX_BLK_CLEAR_FLAG(pRxBlk, fRX_DLS);
-#endif // QOS_DLS_SUPPORT //
 	}
 	else
 	{
 		RX_BLK_SET_FLAG(pRxBlk, fRX_EAP);
-#ifdef DOT11_N_SUPPORT
+
 		if (RX_BLK_TEST_FLAG(pRxBlk, fRX_AMPDU) && (pAd->CommonCfg.bDisableReordering == 0))
 		{
 			Indicate_AMPDU_Packet(pAd, pRxBlk, FromWhichBSSID);
 		}
 		else
-#endif // DOT11_N_SUPPORT //
 		{
 			// Determin the destination of the EAP frame
 			//  to WPA state machine or upper layer
@@ -226,13 +247,11 @@
 	{
 		DBGPRINT_RAW(RT_DEBUG_ERROR,("Rx MIC Value error 2\n"));
 
-#ifdef WPA_SUPPLICANT_SUPPORT
 		if (pAd->StaCfg.WpaSupplicantUP)
 		{
 			WpaSendMicFailureToWpaSupplicant(pAd, (pWpaKey->Type == PAIRWISEKEY) ? TRUE : FALSE);
 		}
 		else
-#endif // WPA_SUPPLICANT_SUPPORT //
 		{
 			RTMPReportMicError(pAd, pWpaKey);
 		}
@@ -276,14 +295,6 @@
 			return;
 		}
 
-#ifdef QOS_DLS_SUPPORT
-		//if ((pHeader->FC.FrDs == 0) && (pHeader->FC.ToDs == 0))
-		if (RTMPRcvFrameDLSCheck(pAd, pHeader, pRxWI->MPDUtotalByteCount, pRxD))
-		{
-			return;
-		}
-#endif // QOS_DLS_SUPPORT //
-
 		// Drop not my BSS frames
 		if (pRxD->MyBss == 0)
 		{
@@ -342,10 +353,7 @@
 		}
 
 	    // Drop not my BSS frame (we can not only check the MyBss bit in RxD)
-#ifdef QOS_DLS_SUPPORT
-	    if (!pAd->CommonCfg.bDLSCapable)
-	    {
-#endif // QOS_DLS_SUPPORT //
+
 		if (INFRA_ON(pAd))
 		{
 			// Infrastructure mode, check address 2 for BSSID
@@ -368,9 +376,6 @@
 				return;
 			}
 		}
-#ifdef QOS_DLS_SUPPORT
-	    }
-#endif // QOS_DLS_SUPPORT //
 
 		//
 		// find pEntry
@@ -391,11 +396,6 @@
 		if (INFRA_ON(pAd))
 		{
 			RX_BLK_SET_FLAG(pRxBlk, fRX_INFRA);
-#ifdef QOS_DLS_SUPPORT
-			if ((pHeader->FC.FrDs == 0) && (pHeader->FC.ToDs == 0))
-				RX_BLK_SET_FLAG(pRxBlk, fRX_DLS);
-			else
-#endif // QOS_DLS_SUPPORT //
 			ASSERT(pRxWI->WirelessCliID == BSSID_WCID);
 		}
 
@@ -453,12 +453,10 @@
 		else
 #endif
 		{
-#ifdef DOT11_N_SUPPORT
 			RX_BLK_SET_FLAG(pRxBlk, fRX_HTC);
 			// skip HTC contorl field
 			pRxBlk->pData += 4;
 			pRxBlk->DataSize -= 4;
-#endif // DOT11_N_SUPPORT //
 		}
 	}
 
@@ -471,13 +469,10 @@
 		pRxBlk->pData += 2;
 	}
 
-#ifdef DOT11_N_SUPPORT
 	if (pRxD->BA)
 	{
 		RX_BLK_SET_FLAG(pRxBlk, fRX_AMPDU);
 	}
-#endif // DOT11_N_SUPPORT //
-
 
 	//
 	// Case I  Process Broadcast & Multicast data frame
@@ -509,18 +504,6 @@
 	{
 		pAd->LastRxRate = (USHORT)((pRxWI->MCS) + (pRxWI->BW <<7) + (pRxWI->ShortGI <<8)+ (pRxWI->PHYMODE <<14)) ;
 
-
-#ifdef QOS_DLS_SUPPORT
-        if (RX_BLK_TEST_FLAG(pRxBlk, fRX_DLS))
-		{
-			MAC_TABLE_ENTRY *pDlsEntry = NULL;
-
-			pDlsEntry = DlsEntryTableLookupByWcid(pAd, pRxWI->WirelessCliID, pHeader->Addr2, TRUE);
-										                        if(pDlsEntry)
-			Update_Rssi_Sample(pAd, &pDlsEntry->RssiSample, pRxWI);
-		}
-		else
-#endif // QOS_DLS_SUPPORT //
 		if (ADHOC_ON(pAd))
 		{
 			pEntry = MacTableLookup(pAd, pHeader->Addr2);
@@ -592,7 +575,13 @@
 	{
 
 		// We should collect RSSI not only U2M data but also my beacon
+#ifdef RT30xx
+		if ((pHeader->FC.SubType == SUBTYPE_BEACON) && (MAC_ADDR_EQUAL(&pAd->CommonCfg.Bssid, &pHeader->Addr2))
+			&& (pAd->RxAnt.EvaluatePeriod == 0))
+#endif
+#ifndef RT30xx
 		if ((pHeader->FC.SubType == SUBTYPE_BEACON) && (MAC_ADDR_EQUAL(&pAd->CommonCfg.Bssid, &pHeader->Addr2)))
+#endif
 		{
 			Update_Rssi_Sample(pAd, &pAd->StaCfg.RssiSample, pRxWI);
 
@@ -600,6 +589,18 @@
 			pAd->StaCfg.LastSNR1 = (UCHAR)(pRxWI->SNR1);
 		}
 
+#ifdef RT30xx
+		// collect rssi information for antenna diversity
+		if (pAd->NicConfig2.field.AntDiversity)
+		{
+			if ((pRxD->U2M) || ((pHeader->FC.SubType == SUBTYPE_BEACON) && (MAC_ADDR_EQUAL(&pAd->CommonCfg.Bssid, &pHeader->Addr2))))
+			{
+					COLLECT_RX_ANTENNA_AVERAGE_RSSI(pAd, ConvertToRssi(pAd, (UCHAR)pRxWI->RSSI0, RSSI_0), 0); //Note: RSSI2 not used on RT73
+					pAd->StaCfg.NumOfAvgRssiSample ++;
+			}
+		}
+#endif // RT30xx //
+
 		// First check the size, it MUST not exceed the mlme queue size
 		if (pRxWI->MPDUtotalByteCount > MGMT_DMA_BUFFER_SIZE)
 		{
@@ -618,21 +619,17 @@
 	IN	PRTMP_ADAPTER	pAd,
 	IN	RX_BLK			*pRxBlk)
 {
-#ifdef DOT11_N_SUPPORT
 	PRXWI_STRUC		pRxWI = pRxBlk->pRxWI;
-#endif // DOT11_N_SUPPORT //
 	PHEADER_802_11	pHeader = pRxBlk->pHeader;
 	PNDIS_PACKET	pRxPacket = pRxBlk->pRxPacket;
 
 	switch (pHeader->FC.SubType)
 	{
 		case SUBTYPE_BLOCK_ACK_REQ:
-#ifdef DOT11_N_SUPPORT
 			{
 				CntlEnqueueForRecv(pAd, pRxWI->WirelessCliID, (pRxWI->MPDUtotalByteCount), (PFRAME_BA_REQ)pHeader);
 			}
 			break;
-#endif // DOT11_N_SUPPORT //
 		case SUBTYPE_BLOCK_ACK:
 		case SUBTYPE_ACK:
 		default:
@@ -691,12 +688,14 @@
 			break;
 		}
 
+#ifdef RT2860
 		if (RxProcessed++ > MAX_RX_PROCESS_CNT)
 		{
 			// need to reschedule rx handle
 			bReschedule = TRUE;
 			break;
 		}
+#endif
 
 		RxProcessed ++; // test
 
@@ -721,11 +720,6 @@
 		pRxWI	= (PRXWI_STRUC) pData;
 		pHeader = (PHEADER_802_11) (pData+RXWI_SIZE) ;
 
-#ifdef RT_BIG_ENDIAN
-	    RTMPFrameEndianChange(pAd, (PUCHAR)pHeader, DIR_READ, TRUE);
-		RTMPWIEndianChange((PUCHAR)pRxWI, TYPE_RXWI);
-#endif
-
 		// build RxCell
 		RxCell.pRxWI = pRxWI;
 		RxCell.pHeader = pHeader;
@@ -749,22 +743,6 @@
 			break;
 		}
 		/* RT2870 invokes STARxDoneInterruptHandle() in rtusb_bulk.c */
-#ifdef RALINK_ATE
-		if (ATE_ON(pAd))
-		{
-			pAd->ate.RxCntPerSec++;
-			ATESampleRssi(pAd, pRxWI);
-#ifdef RALINK_28xx_QA
-			if (pAd->ate.bQARxStart == TRUE)
-			{
-				/* (*pRxD) has been swapped in GetPacketFromRxRing() */
-				ATE_QA_Statistics(pAd, pRxWI, pRxD,	pHeader);
-			}
-#endif // RALINK_28xx_QA //
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_SUCCESS);
-			continue;
-		}
-#endif // RALINK_ATE //
 
 		// Check for all RxD errors
 		Status = RTMPCheckRxError(pAd, pHeader, pRxWI, pRxD);
@@ -807,6 +785,7 @@
 		}
 	}
 
+#ifdef RT2860
 	// fRTMP_PS_GO_TO_SLEEP_NOW is set if receiving beacon.
 	if (RTMP_TEST_PSFLAG(pAd, fRTMP_PS_GO_TO_SLEEP_NOW) && (INFRA_ON(pAd)))
 	{
@@ -814,6 +793,7 @@
 		AsicSleepThenAutoWakeup(pAd, pAd->ThisTbttNumToNextWakeUp);
 		bReschedule = FALSE;
 	}
+#endif
 	return bReschedule;
 }
 
@@ -831,7 +811,12 @@
 VOID	RTMPHandleTwakeupInterrupt(
 	IN PRTMP_ADAPTER pAd)
 {
+#ifdef RT2860
 	AsicForceWakeup(pAd, DOT11POWERSAVE);
+#endif
+#ifdef RT2870
+	AsicForceWakeup(pAd, FALSE);
+#endif
 }
 
 /*
@@ -885,17 +870,6 @@
 			{
 				// Record that orignal packet source is from NDIS layer,so that
 				// later on driver knows how to release this NDIS PACKET
-#ifdef QOS_DLS_SUPPORT
-				MAC_TABLE_ENTRY *pEntry;
-				PUCHAR pSrcBufVA = GET_OS_PKT_DATAPTR(pPacket);
-
-				pEntry = MacTableLookup(pAd, pSrcBufVA);
-				if (pEntry && (pEntry->ValidAsDls == TRUE))
-				{
-					RTMP_SET_PACKET_WCID(pPacket, pEntry->Aid);
-				}
-				else
-#endif // QOS_DLS_SUPPORT //
 				RTMP_SET_PACKET_WCID(pPacket, 0); // this field is useless when in STA mode
 				RTMP_SET_PACKET_SOURCE(pPacket, PKTSRC_NDIS);
 				NDIS_SET_PACKET_STATUS(pPacket, NDIS_STATUS_PENDING);
@@ -977,18 +951,6 @@
 	{
 		if(INFRA_ON(pAd))
 		{
-#ifdef QOS_DLS_SUPPORT
-			USHORT	tmpWcid;
-
-			tmpWcid = RTMP_GET_PACKET_WCID(pPacket);
-			if (VALID_WCID(tmpWcid) &&
-				(pAd->MacTab.Content[tmpWcid].ValidAsDls== TRUE))
-			{
-				pEntry = &pAd->MacTab.Content[tmpWcid];
-				Rate = pAd->MacTab.Content[tmpWcid].CurrTxRate;
-			}
-			else
-#endif // QOS_DLS_SUPPORT //
 			{
 			pEntry = &pAd->MacTab.Content[BSSID_WCID];
 			RTMP_SET_PACKET_WCID(pPacket, BSSID_WCID);
@@ -1039,12 +1001,7 @@
 		 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
 		 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
 		 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-#ifdef WPA_SUPPLICANT_SUPPORT
 		  || (pAd->StaCfg.IEEE8021X == TRUE)
-#endif // WPA_SUPPLICANT_SUPPORT //
-#ifdef LEAP_SUPPORT
-		  || (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
 		  )
 		  && ((pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED) || (pAd->StaCfg.MicErrCnt >= 2))
 		  && (RTMP_GET_PACKET_EAPOL(pPacket)== FALSE)
@@ -1070,10 +1027,8 @@
 		NumberOfFrag = 1;	// Aggregation overwhelms fragmentation
 	else if (CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_AMSDU_INUSED))
 		NumberOfFrag = 1;	// Aggregation overwhelms fragmentation
-#ifdef DOT11_N_SUPPORT
 	else if ((pAd->StaCfg.HTPhyMode.field.MODE == MODE_HTMIX) || (pAd->StaCfg.HTPhyMode.field.MODE == MODE_HTGREENFIELD))
 		NumberOfFrag = 1;	// MIMO RATE overwhelms fragmentation
-#endif // DOT11_N_SUPPORT //
 	else
 	{
 		// The calculated "NumberOfFrag" is a rough estimation because of various
@@ -1110,7 +1065,13 @@
 	//
 	UserPriority = 0;
 	QueIdx		 = QID_AC_BE;
+#ifdef RT2860
 	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED))
+#endif
+#ifdef RT2870
+	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) &&
+		CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE))
+#endif
 	{
 		USHORT Protocol;
 		UCHAR  LlcSnapLen = 0, Byte0, Byte1;
@@ -1163,9 +1124,6 @@
 	if (pAd->TxSwQueue[QueIdx].Number >= MAX_PACKETS_IN_QUEUE)
 	{
 		RTMP_IRQ_UNLOCK(&pAd->irq_lock, IrqFlags);
-#ifdef BLOCK_NET_IF
-		StopNetIfQueue(pAd, QueIdx, pPacket);
-#endif // BLOCK_NET_IF //
 		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
 
 		return NDIS_STATUS_FAILURE;
@@ -1176,9 +1134,13 @@
 	}
 	RTMP_IRQ_UNLOCK(&pAd->irq_lock, IrqFlags);
 
-#ifdef DOT11_N_SUPPORT
     if ((pAd->CommonCfg.BACapability.field.AutoBA == TRUE)&&
+#ifdef RT2860
         (pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE))
+#endif
+#ifdef RT2870
+        IS_HT_STA(pEntry))
+#endif
 	{
 		if (((pEntry->TXBAbitmap & (1<<UserPriority)) == 0) &&
             ((pEntry->BADeclineBitmap & (1<<UserPriority)) == 0) &&
@@ -1194,7 +1156,6 @@
 			BAOriSessionSetUp(pAd, pEntry, 0, 0, 10, FALSE);
 		}
 	}
-#endif // DOT11_N_SUPPORT //
 
 	pAd->RalinkCounters.OneSecOsTxCount[QueIdx]++; // TODO: for debug only. to be removed
 	return NDIS_STATUS_SUCCESS;
@@ -1223,14 +1184,27 @@
 
 	========================================================================
 */
+
+#ifdef RT2870
+/*
+	Actually, this function used to check if the TxHardware Queue still has frame need to send.
+	If no frame need to send, go to sleep, else, still wake up.
+*/
+#endif
 NDIS_STATUS RTMPFreeTXDRequest(
 	IN		PRTMP_ADAPTER	pAd,
 	IN		UCHAR			QueIdx,
 	IN		UCHAR			NumberRequired,
 	IN		PUCHAR			FreeNumberIs)
 {
+#ifdef RT2860
 	ULONG		FreeNumber = 0;
+#endif
 	NDIS_STATUS 	Status = NDIS_STATUS_FAILURE;
+#ifdef RT2870
+	unsigned long   IrqFlags;
+	HT_TX_CONTEXT	*pHTTXContext;
+#endif
 
 	switch (QueIdx)
 	{
@@ -1239,6 +1213,7 @@
 		case QID_AC_VI:
 		case QID_AC_VO:
 		case QID_HCCA:
+#ifdef RT2860
 			if (pAd->TxRing[QueIdx].TxSwFreeIdx > pAd->TxRing[QueIdx].TxCpuIdx)
 				FreeNumber = pAd->TxRing[QueIdx].TxSwFreeIdx - pAd->TxRing[QueIdx].TxCpuIdx - 1;
 			else
@@ -1246,9 +1221,27 @@
 
 			if (FreeNumber >= NumberRequired)
 				Status = NDIS_STATUS_SUCCESS;
+#endif
+#ifdef RT2870
+			{
+				pHTTXContext = &pAd->TxContext[QueIdx];
+				RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
+				if ((pHTTXContext->CurWritePosition != pHTTXContext->ENextBulkOutPosition) ||
+					(pHTTXContext->IRPPending == TRUE))
+				{
+					Status = NDIS_STATUS_FAILURE;
+				}
+				else
+				{
+					Status = NDIS_STATUS_SUCCESS;
+				}
+				RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
+			}
+#endif
 			break;
 
 		case QID_MGMT:
+#ifdef RT2860
 			if (pAd->MgmtRing.TxSwFreeIdx > pAd->MgmtRing.TxCpuIdx)
 				FreeNumber = pAd->MgmtRing.TxSwFreeIdx - pAd->MgmtRing.TxCpuIdx - 1;
 			else
@@ -1256,13 +1249,22 @@
 
 			if (FreeNumber >= NumberRequired)
 				Status = NDIS_STATUS_SUCCESS;
+#endif
+#ifdef RT2870
+			if (pAd->MgmtRing.TxSwFreeIdx != MGMT_RING_SIZE)
+				Status = NDIS_STATUS_FAILURE;
+			else
+				Status = NDIS_STATUS_SUCCESS;
+#endif
 			break;
 
 		default:
 			DBGPRINT(RT_DEBUG_ERROR,("RTMPFreeTXDRequest::Invalid QueIdx(=%d)\n", QueIdx));
 			break;
 	}
+#ifdef RT2860
 	*FreeNumberIs = (UCHAR)FreeNumber;
+#endif
 
 	return (Status);
 }
@@ -1283,22 +1285,12 @@
 	ULONG	Length;
 	PHEADER_802_11	pHeader_802_11;
 
-
-#ifdef RALINK_ATE
-	if(ATE_ON(pAd))
-	{
-		return;
-	}
-#endif // RALINK_ATE //
-
     // WPA 802.1x secured port control
     if (((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
          (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
          (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
          (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-#ifdef WPA_SUPPLICANT_SUPPORT
 			  || (pAd->StaCfg.IEEE8021X == TRUE)
-#endif
         ) &&
        (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
 	{
@@ -1402,30 +1394,6 @@
 		}
 		else if (Cipher == Ndis802_11Encryption1Enabled)
 		{
-#ifdef LEAP_SUPPORT
-			if (pAd->StaCfg.CkipFlag & 0x10) // Cisco CKIP KP is on
-			{
-				if (LEAP_CCKM_ON(pAd))
-				{
-					if (((*pSrcBufVA & 0x01) && (ADHOC_ON(pAd))))
-						KeyIdx = 1;
-					else
-						KeyIdx = 0;
-				}
-				else
-					KeyIdx = pAd->StaCfg.DefaultKeyId;
-			}
-			else if (pAd->StaCfg.CkipFlag & 0x08) // only CKIP CMIC
-				KeyIdx = pAd->StaCfg.DefaultKeyId;
-			else if (LEAP_CCKM_ON(pAd))
-			{
-				if ((*pSrcBufVA & 0x01) && (ADHOC_ON(pAd)))
-					KeyIdx = 1;
-				else
-					KeyIdx = 0;
-			}
-			else	// standard WEP64 or WEP128
-#endif // LEAP_SUPPORT //
 				KeyIdx = pAd->StaCfg.DefaultKeyId;
 		}
 		else if ((Cipher == Ndis802_11Encryption2Enabled) ||
@@ -1443,13 +1411,11 @@
 			CipherAlg = CIPHER_NONE;
 		else if ((Cipher == Ndis802_11EncryptionDisabled) || (pAd->SharedKey[BSS0][KeyIdx].KeyLen == 0))
 			CipherAlg = CIPHER_NONE;
-#ifdef WPA_SUPPLICANT_SUPPORT
 	    else if ( pAd->StaCfg.WpaSupplicantUP &&
 	             (Cipher == Ndis802_11Encryption1Enabled) &&
 	             (pAd->StaCfg.IEEE8021X == TRUE) &&
 	             (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
 	        CipherAlg = CIPHER_NONE;
-#endif // WPA_SUPPLICANT_SUPPORT //
 		else
 		{
 			//Header_802_11.FC.Wep = 1;
@@ -1467,12 +1433,7 @@
 	IN  PRTMP_ADAPTER   pAd,
 	IN  TX_BLK          *pTxBlk)
 {
-
 	HEADER_802_11	*pHeader_802_11;
-#ifdef QOS_DLS_SUPPORT
-	BOOLEAN	bDLSFrame = FALSE;
-	INT	DlsEntryIndex = 0;
-#endif // QOS_DLS_SUPPORT //
 
 	//
 	// MAKE A COMMON 802.11 HEADER
@@ -1489,19 +1450,6 @@
 	pHeader_802_11->FC.Type = BTYPE_DATA;
 	pHeader_802_11->FC.SubType = ((TX_BLK_TEST_FLAG(pTxBlk, fTX_bWMM)) ? SUBTYPE_QDATA : SUBTYPE_DATA);
 
-#ifdef QOS_DLS_SUPPORT
-	if (INFRA_ON(pAd))
-	{
-		// Check if the frame can be sent through DLS direct link interface
-		// If packet can be sent through DLS, then force aggregation disable. (Hard to determine peer STA's capability)
-		DlsEntryIndex = RTMPCheckDLSFrame(pAd, pTxBlk->pSrcBufHeader);
-		if (DlsEntryIndex >= 0)
-			bDLSFrame = TRUE;
-		else
-			bDLSFrame = FALSE;
-	}
-#endif // QOS_DLS_SUPPORT //
-
     if (pTxBlk->pMacEntry)
 	{
 		if (TX_BLK_TEST_FLAG(pTxBlk, fTX_bForceNonQoS))
@@ -1511,14 +1459,6 @@
 		}
 		else
 		{
-#ifdef QOS_DLS_SUPPORT
-			if (bDLSFrame)
-			{
-				pHeader_802_11->Sequence = pAd->StaCfg.DLSEntry[DlsEntryIndex].Sequence;
-				pAd->StaCfg.DLSEntry[DlsEntryIndex].Sequence = (pAd->StaCfg.DLSEntry[DlsEntryIndex].Sequence+1) & MAXSEQ;
-			}
-			else
-#endif // QOS_DLS_SUPPORT //
 			{
     	    pHeader_802_11->Sequence = pTxBlk->pMacEntry->TxSeq[pTxBlk->UserPriority];
     	    pTxBlk->pMacEntry->TxSeq[pTxBlk->UserPriority] = (pTxBlk->pMacEntry->TxSeq[pTxBlk->UserPriority]+1) & MAXSEQ;
@@ -1538,16 +1478,6 @@
 	{
 		if (INFRA_ON(pAd))
 		{
-#ifdef QOS_DLS_SUPPORT
-			if (bDLSFrame)
-			{
-				COPY_MAC_ADDR(pHeader_802_11->Addr1, pTxBlk->pSrcBufHeader);
-				COPY_MAC_ADDR(pHeader_802_11->Addr2, pAd->CurrentAddress);
-				COPY_MAC_ADDR(pHeader_802_11->Addr3, pAd->CommonCfg.Bssid);
-				pHeader_802_11->FC.ToDs = 0;
-			}
-			else
-#endif // QOS_DLS_SUPPORT //
 			{
 			COPY_MAC_ADDR(pHeader_802_11->Addr1, pAd->CommonCfg.Bssid);
 			COPY_MAC_ADDR(pHeader_802_11->Addr2, pAd->CurrentAddress);
@@ -1576,7 +1506,6 @@
     	pHeader_802_11->FC.PwrMgmt = (pAd->StaCfg.Psm == PWR_SAVE);
 }
 
-#ifdef DOT11_N_SUPPORT
 VOID STABuildCache802_11Header(
 	IN RTMP_ADAPTER		*pAd,
 	IN TX_BLK			*pTxBlk,
@@ -1603,29 +1532,7 @@
     pMacEntry->TxSeq[pTxBlk->UserPriority] = (pMacEntry->TxSeq[pTxBlk->UserPriority]+1) & MAXSEQ;
 
 	{
-		// Check if the frame can be sent through DLS direct link interface
-		// If packet can be sent through DLS, then force aggregation disable. (Hard to determine peer STA's capability)
-#ifdef QOS_DLS_SUPPORT
-		BOOLEAN	bDLSFrame = FALSE;
-		INT	DlsEntryIndex = 0;
-
-		DlsEntryIndex = RTMPCheckDLSFrame(pAd, pTxBlk->pSrcBufHeader);
-		if (DlsEntryIndex >= 0)
-			bDLSFrame = TRUE;
-		else
-			bDLSFrame = FALSE;
-#endif // QOS_DLS_SUPPORT //
-
 		// The addr3 of normal packet send from DS is Dest Mac address.
-#ifdef QOS_DLS_SUPPORT
-		if (bDLSFrame)
-		{
-			COPY_MAC_ADDR(pHeader80211->Addr1, pTxBlk->pSrcBufHeader);
-			COPY_MAC_ADDR(pHeader80211->Addr3, pAd->CommonCfg.Bssid);
-			pHeader80211->FC.ToDs = 0;
-		}
-		else
-#endif // QOS_DLS_SUPPORT //
 		if (ADHOC_ON(pAd))
 			COPY_MAC_ADDR(pHeader80211->Addr3, pAd->CommonCfg.Bssid);
 		else
@@ -1640,7 +1547,6 @@
 	else
     	pHeader80211->FC.PwrMgmt = (pAd->StaCfg.Psm == PWR_SAVE);
 }
-#endif // DOT11_N_SUPPORT //
 
 static inline PUCHAR STA_Build_ARalink_Frame_Header(
 	IN RTMP_ADAPTER *pAd,
@@ -1700,7 +1606,6 @@
 
 }
 
-#ifdef DOT11_N_SUPPORT
 static inline PUCHAR STA_Build_AMSDU_Frame_Header(
 	IN RTMP_ADAPTER *pAd,
 	IN TX_BLK		*pTxBlk)
@@ -1890,7 +1795,9 @@
 		//
 		// Kick out Tx
 		//
+#ifdef RT2860
 		if (!RTMP_TEST_PSFLAG(pAd, fRTMP_PS_DISABLE_TX))
+#endif
 			HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
 
 		pAd->RalinkCounters.KickTxCount++;
@@ -2021,10 +1928,11 @@
 	//
 	// Kick out Tx
 	//
+#ifdef RT2860
 	if (!RTMP_TEST_PSFLAG(pAd, fRTMP_PS_DISABLE_TX))
+#endif
 		HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
 }
-#endif // DOT11_N_SUPPORT //
 
 VOID STA_Legacy_Frame_Tx(
 	IN	PRTMP_ADAPTER	pAd,
@@ -2142,7 +2050,9 @@
 	//
 	// Kick out Tx
 	//
+#ifdef RT2860
 	if (!RTMP_TEST_PSFLAG(pAd, fRTMP_PS_DISABLE_TX))
+#endif
 		HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
 }
 
@@ -2253,7 +2163,9 @@
 	//
 	// Kick out Tx
 	//
+#ifdef RT2860
 	if (!RTMP_TEST_PSFLAG(pAd, fRTMP_PS_DISABLE_TX))
+#endif
 		HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
 
 }
@@ -2513,15 +2425,6 @@
 
 	pPacket = QUEUE_ENTRY_TO_PACKET(pTxBlk->TxPacketList.Head);
 
-#if 0 //def CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-		if ((pAd->CommonCfg.CarrierDetect.Enable == TRUE) && (isCarrierDetectExist(pAd) == TRUE))
-	{
-		DBGPRINT(RT_DEBUG_INFO,("STAHardTransmit --> radar detect not in normal mode !!!\n"));
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-		return (NDIS_STATUS_FAILURE);
-	}
-#endif // CARRIER_DETECTION_SUPPORT //
-
 	// ------------------------------------------------------------------
 	// STEP 1. WAKE UP PHY
 	//		outgoing frame always wakeup PHY to prevent frame lost and
@@ -2531,7 +2434,12 @@
 	if ((pAd->StaCfg.Psm == PWR_SAVE) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
 	{
 	    DBGPRINT_RAW(RT_DEBUG_TRACE, ("AsicForceWakeup At HardTx\n"));
+#ifdef RT2860
 		AsicForceWakeup(pAd, FROM_TX);
+#endif
+#ifdef RT2870
+		AsicForceWakeup(pAd, TRUE);
+#endif
 	}
 
 	// It should not change PSM bit, when APSD turn on.
@@ -2546,14 +2454,12 @@
 
 	switch (pTxBlk->TxFrameType)
 	{
-#ifdef DOT11_N_SUPPORT
 		case TX_AMPDU_FRAME:
 				STA_AMPDU_Frame_Tx(pAd, pTxBlk);
 			break;
 		case TX_AMSDU_FRAME:
 				STA_AMSDU_Frame_Tx(pAd, pTxBlk);
 			break;
-#endif // DOT11_N_SUPPORT //
 		case TX_LEGACY_FRAME:
 				STA_Legacy_Frame_Tx(pAd, pTxBlk);
 			break;
diff --git a/drivers/staging/rt2860/sta/sanity.c b/drivers/staging/rt2860/sta/sanity.c
index 2398724..7d530f6 100644
--- a/drivers/staging/rt2860/sta/sanity.c
+++ b/drivers/staging/rt2860/sta/sanity.c
@@ -184,7 +184,6 @@
 			}
 
 		break;
-#ifdef DOT11_N_SUPPORT
             case IE_ADD_HT:
             case IE_ADD_HT2:
 			if (pEid->Len >= sizeof(ADD_HT_INFO_IE))
@@ -213,7 +212,6 @@
 			{
 				DBGPRINT(RT_DEBUG_WARN, ("PeerAssocRspSanity - wrong IE_SECONDARY_CH_OFFSET. \n"));
 			}
-#endif // DOT11_N_SUPPORT //
 		break;
             case IE_AIRONET_CKIP:
                 // 0. Check Aironet IE length, it must be larger or equal to 28
diff --git a/drivers/staging/rt2860/sta/sync.c b/drivers/staging/rt2860/sta/sync.c
index 148037a..87b5e49 100644
--- a/drivers/staging/rt2860/sta/sync.c
+++ b/drivers/staging/rt2860/sta/sync.c
@@ -37,6 +37,7 @@
 */
 #include "../rt_config.h"
 
+#ifdef RT2860
 #define AC0_DEF_TXOP		0
 #define AC1_DEF_TXOP		0
 #define AC2_DEF_TXOP		94
@@ -71,6 +72,10 @@
 	}
 	AsicSetEdcaParm(pAd, &pAd->CommonCfg.APEdcaParm);
 }
+#endif /* RT2860 */
+#ifdef RT2870
+#define ADHOC_ENTRY_BEACON_LOST_TIME	(2*OS_HZ)	// 2 sec
+#endif
 
 /*
 	==========================================================================
@@ -141,7 +146,6 @@
 	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS))
 		return;
 
-#ifdef DOT11_N_SUPPORT
 	if ((pAd->CommonCfg.BBPCurrentBW == BW_40)
 		)
 	{
@@ -154,7 +158,6 @@
 		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
 		DBGPRINT(RT_DEBUG_TRACE, ("SYNC - End of SCAN, restore to 40MHz channel %d, Total BSS[%02d]\n",pAd->CommonCfg.CentralChannel, pAd->ScanTab.BssNr));
 	}
-#endif // DOT11_N_SUPPORT //
 
 	MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_BEACON_TIMEOUT, 0, NULL);
 	RT28XX_MLME_HANDLER(pAd);
@@ -228,6 +231,7 @@
 	// Increase the scan retry counters.
 	pAd->StaCfg.ScanCnt++;
 
+#ifdef RT2860
     if ((OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE)) &&
         (IDLE_ON(pAd)) &&
 		(pAd->StaCfg.bRadio == TRUE) &&
@@ -235,6 +239,7 @@
 	{
 		RT28xxPciAsicRadioOn(pAd, GUI_IDLE_POWER_SAVE);
 	}
+#endif
 
 	// first check the parameter sanity
 	if (MlmeScanReqSanity(pAd,
@@ -347,6 +352,7 @@
 
 	DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeJoinReqAction(BSS #%ld)\n", pInfo->BssIdx));
 
+#ifdef RT2860
     if ((OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE)) &&
         (IDLE_ON(pAd)) &&
 		(pAd->StaCfg.bRadio == TRUE) &&
@@ -354,6 +360,7 @@
 	{
 		RT28xxPciAsicRadioOn(pAd, GUI_IDLE_POWER_SAVE);
 	}
+#endif
 
 	// reset all the timers
 	RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled);
@@ -375,22 +382,6 @@
 	pAd->MlmeAux.Channel = pBss->Channel;
 	pAd->MlmeAux.CentralChannel = pBss->CentralChannel;
 
-#ifdef EXT_BUILD_CHANNEL_LIST
-	// Country IE of the AP will be evaluated and will be used.
-	if ((pAd->StaCfg.IEEE80211dClientMode != Rt802_11_D_None) &&
-		(pBss->bHasCountryIE == TRUE))
-	{
-		NdisMoveMemory(&pAd->CommonCfg.CountryCode[0], &pBss->CountryString[0], 2);
-		if (pBss->CountryString[2] == 'I')
-			pAd->CommonCfg.Geography = IDOR;
-		else if (pBss->CountryString[2] == 'O')
-			pAd->CommonCfg.Geography = ODOR;
-		else
-			pAd->CommonCfg.Geography = BOTH;
-		BuildChannelListEx(pAd);
-	}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
 	// Let BBP register at 20MHz to do scan
 	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
 	BBPValue &= (~0x18);
@@ -407,9 +398,6 @@
 		if (((pAd->CommonCfg.bIEEE80211H == 1) &&
             (pAd->MlmeAux.Channel > 14) &&
              RadarChannelCheck(pAd, pAd->MlmeAux.Channel))
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-             || (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-#endif // CARRIER_DETECTION_SUPPORT //
             )
 		{
 			//
@@ -541,7 +529,7 @@
 		pAd->MlmeAux.ExtRateLen = pAd->CommonCfg.ExtRateLen;
 		NdisMoveMemory(pAd->MlmeAux.ExtRate, pAd->CommonCfg.ExtRate, MAX_LEN_OF_SUPPORTED_RATES);
 		RTMPCheckRates(pAd, pAd->MlmeAux.ExtRate, &pAd->MlmeAux.ExtRateLen);
-#ifdef DOT11_N_SUPPORT
+
 		if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
 		{
 			RTMPUpdateHTIE(&pAd->CommonCfg.DesiredHtPhy, &pAd->StaCfg.DesiredHtPhyInfo.MCSSet[0], &pAd->MlmeAux.HtCapability, &pAd->MlmeAux.AddHtInfo);
@@ -550,7 +538,6 @@
 			DBGPRINT(RT_DEBUG_TRACE, ("SYNC -pAd->StaActive.SupportedHtPhy.bHtEnable = TRUE\n"));
 		}
 		else
-#endif // DOT11_N_SUPPORT //
 		{
 			pAd->MlmeAux.HtCapabilityLen = 0;
 			pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
@@ -618,10 +605,9 @@
 	// Init Variable IE structure
 	pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
 	pVIE->Length = 0;
-#ifdef DOT11_N_SUPPORT
+
     RTMPZeroMemory(&HtCapability, sizeof(HtCapability));
 	RTMPZeroMemory(&AddHtInfo, sizeof(ADD_HT_INFO_IE));
-#endif // DOT11_N_SUPPORT //
 
 	if (PeerBeaconAndProbeRspSanity(pAd,
 								Elem->Msg,
@@ -672,11 +658,9 @@
 
 		Rssi = RTMPMaxRssi(pAd, ConvertToRssi(pAd, Elem->Rssi0, RSSI_0), ConvertToRssi(pAd, Elem->Rssi1, RSSI_1), ConvertToRssi(pAd, Elem->Rssi2, RSSI_2));
 
-
-#ifdef DOT11_N_SUPPORT
 		if ((HtCapabilityLen > 0) || (PreNHtCapabilityLen > 0))
 			HtCapabilityLen = SIZE_HT_CAP_IE;
-#endif // DOT11_N_SUPPORT //
+
 		if ((pAd->StaCfg.CCXReqType != MSRN_TYPE_UNUSED) && (Channel == pAd->StaCfg.CCXScanChannel))
 		{
 			Idx = BssTableSetEntry(pAd, &pAd->StaCfg.CCXBssTab, Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
@@ -698,16 +682,7 @@
 						  &CfParm, AtimWin, CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,  &HtCapability,
 						 &AddHtInfo, HtCapabilityLen, AddHtInfoLen, NewExtChannelOffset, Channel, Rssi, TimeStamp, CkipFlag,
 						 &EdcaParm, &QosCapability, &QbssLoad, LenVIE, pVIE);
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-			if (pAd->ChannelList[pAd->CommonCfg.ChannelListIdx].bEffectedChannel == TRUE)
-			{
-				UCHAR		RegClass;
-				PeerBeaconAndProbeRspSanity2(pAd, Elem->Msg, Elem->MsgLen, &RegClass);
-				TriEventTableSetEntry(pAd, &pAd->CommonCfg.TriggerEventTab, Bssid, &HtCapability, HtCapabilityLen, RegClass, Channel);
-			}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
+
 			if (Idx != BSS_NOT_FOUND)
 			{
 				NdisMoveMemory(pAd->ScanTab.BssEntry[Idx].PTSF, &Elem->Msg[24], 4);
@@ -755,9 +730,7 @@
 	UCHAR				HtCapabilityLen = 0, PreNHtCapabilityLen = 0;
 	UCHAR			AddHtInfoLen;
 	UCHAR			NewExtChannelOffset = 0xff;
-#ifdef DOT11_N_SUPPORT
 	UCHAR			CentralChannel;
-#endif // DOT11_N_SUPPORT //
 
 	// Init Variable IE structure
 	pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
@@ -873,7 +846,7 @@
 			RTMPCheckRates(pAd, pAd->MlmeAux.ExtRate, &pAd->MlmeAux.ExtRateLen);
 
             NdisZeroMemory(pAd->StaActive.SupportedPhyInfo.MCSSet, 16);
-#ifdef DOT11_N_SUPPORT
+
 			pAd->MlmeAux.NewExtChannelOffset = NewExtChannelOffset;
 			pAd->MlmeAux.HtCapabilityLen = HtCapabilityLen;
 
@@ -918,7 +891,6 @@
 
 			}
 			else
-#endif // DOT11_N_SUPPORT //
 			{
    				// To prevent error, let legacy AP must have same CentralChannel and Channel.
 				if ((HtCapabilityLen == 0) && (PreNHtCapabilityLen == 0))
@@ -933,9 +905,7 @@
 
 			// copy QOS related information
 			if ((pAd->CommonCfg.bWmmCapable)
-#ifdef DOT11_N_SUPPORT
 				 || (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-#endif // DOT11_N_SUPPORT //
 				)
 			{
 				NdisMoveMemory(&pAd->MlmeAux.APEdcaParm, &EdcaParm, sizeof(EDCA_PARM));
@@ -952,15 +922,6 @@
 			DBGPRINT(RT_DEBUG_TRACE, ("SYNC - after JOIN, SupRateLen=%d, ExtRateLen=%d\n",
 										pAd->MlmeAux.SupRateLen, pAd->MlmeAux.ExtRateLen));
 
-#ifdef LEAP_SUPPORT
-			// Update CkipFlag
-			pAd->StaCfg.CkipFlag = CkipFlag;
-
-			// Keep TimeStamp for Re-Association used.
-			if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-				pAd->StaCfg.CCKMBeaconAtJoinTimeStamp = TimeStamp;
-#endif // LEAP_SUPPORT //
-
 			if (AironetCellPowerLimit != 0xFF)
 			{
 				//We need to change our TxPower for CCX 2.0 AP Control of Client Transmit Power
@@ -1018,14 +979,6 @@
 	UCHAR			AddHtInfoLen;
 	UCHAR			NewExtChannelOffset = 0xff;
 
-
-#ifdef RALINK_ATE
-    if (ATE_ON(pAd))
-    {
-		return;
-    }
-#endif // RALINK_ATE //
-
 	if (!(INFRA_ON(pAd) || ADHOC_ON(pAd)
 		))
 		return;
@@ -1093,14 +1046,12 @@
 		if (pAd->Mlme.CntlMachine.CurrState == CNTL_WAIT_DISASSOC)
 			return;
 
-#ifdef DOT11_N_SUPPORT
 		// Copy Control channel for this BSSID.
 		if (AddHtInfoLen != 0)
 			Channel = AddHtInfo.ControlChan;
 
 		if ((HtCapabilityLen > 0) || (PreNHtCapabilityLen > 0))
 			HtCapabilityLen = SIZE_HT_CAP_IE;
-#endif // DOT11_N_SUPPORT //
 
 		//
 		// Housekeeping "SsidBssTab" table for later-on ROAMing usage.
@@ -1165,6 +1116,10 @@
 			// Add the safeguard against the mismatch of adhoc wep status
 			if (pAd->StaCfg.WepStatus != pAd->ScanTab.BssEntry[Bssidx].WepStatus)
 			{
+#ifdef RT30xx
+				DBGPRINT(RT_DEBUG_TRACE, ("SYNC - Not matched wep status %d %d\n", pAd->StaCfg.WepStatus, pAd->ScanTab.BssEntry[Bssidx].WepStatus));
+				DBGPRINT(RT_DEBUG_TRACE, ("bssid=%s\n", pAd->ScanTab.BssEntry[Bssidx].Bssid));
+#endif
 				return;
 			}
 
@@ -1228,11 +1183,14 @@
 				pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault;
 			}
 
+#ifdef RT2860
 			// at least one 11b peer joined. downgrade the MaxTxRate to 11Mbps
 			// after last 11b peer left for several seconds, we'll auto switch back to 11G rate
 			// in MlmePeriodicExec()
+#endif
 			if (ADHOC_ON(pAd) && (CAP_IS_IBSS_ON(CapabilityInfo)))
 			{
+#ifdef RT2860
 				BOOLEAN	bRestart;
                 BOOLEAN	bnRestart;
 
@@ -1260,7 +1218,7 @@
 						pAd->StaCfg.Last11bBeaconRxTime = Now;
 						break;
 					}
-#ifdef DOT11_N_SUPPORT
+
 					// Update Ht Phy.
 					if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
 					{
@@ -1316,7 +1274,6 @@
 
 					}
 					else
-#endif // DOT11_N_SUPPORT //
 					{
 						RTMPZeroMemory(&pAd->MlmeAux.HtCapability, SIZE_HT_CAP_IE);
 						RTMPZeroMemory(&pAd->MlmeAux.AddHtInfo, SIZE_ADD_HT_INFO_IE);
@@ -1330,7 +1287,6 @@
 					MakeIbssBeacon(pAd);        // re-build BEACON frame
 					AsicEnableIbssSync(pAd);    // copy to on-chip memory
 				}
-#ifdef DOT11_N_SUPPORT
 				else if ((bRestart == TRUE) && (bnRestart == TRUE))
 				{
 					MlmeUpdateTxRates(pAd, FALSE, BSS0);
@@ -1338,7 +1294,6 @@
 					MakeIbssBeacon(pAd);        // re-build BEACON frame
 					AsicEnableIbssSync(pAd);    // copy to on-chip memory
 				}
-#endif // DOT11_N_SUPPORT //
 
 				// At least another peer in this IBSS, declare MediaState as CONNECTED
 				if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
@@ -1402,29 +1357,12 @@
 	        					}
 								MlmeUpdateTxRates(pAd, FALSE, 0);
 	                        }
-#ifdef DOT11_N_SUPPORT
 							else
 							{
 								MlmeUpdateTxRates(pAd, FALSE, 0);
 								MlmeUpdateHtTxRates(pAd, BSS0);
 							}
-#endif // DOT11_N_SUPPORT //
 
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-	                        if (pAd->StaCfg.WpaSupplicantUP)
-	                        {
-	                            union iwreq_data    wrqu;
-
-	                            SendAssocIEsToWpaSupplicant(pAd);
-	                            memset(&wrqu, 0, sizeof(wrqu));
-	                            wrqu.data.flags = RT_ASSOC_EVENT_FLAG;
-	                            wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-	                        }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
 	                        {
 	                            union iwreq_data    wrqu;
 	                            wext_notify_event_assoc(pAd);
@@ -1434,10 +1372,82 @@
 	                            wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
 
 	                        }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
 						}
 					}
 				}
+#endif /* RT2860 */
+#ifdef RT2870
+				UCHAR			MaxSupportedRateIn500Kbps = 0;
+				UCHAR			idx;
+				MAC_TABLE_ENTRY *pEntry;
+
+				// supported rates array may not be sorted. sort it and find the maximum rate
+			    for (idx=0; idx<SupRateLen; idx++)
+			    {
+			        if (MaxSupportedRateIn500Kbps < (SupRate[idx] & 0x7f))
+			            MaxSupportedRateIn500Kbps = SupRate[idx] & 0x7f;
+			    }
+
+				for (idx=0; idx<ExtRateLen; idx++)
+			    {
+			        if (MaxSupportedRateIn500Kbps < (ExtRate[idx] & 0x7f))
+			            MaxSupportedRateIn500Kbps = ExtRate[idx] & 0x7f;
+			    }
+
+				// look up the existing table
+				pEntry = MacTableLookup(pAd, Addr2);
+
+				// Ad-hoc mode is using MAC address as BA session. So we need to continuously find newly joined adhoc station by receiving beacon.
+				// To prevent always check this, we use wcid == RESERVED_WCID to recognize it as newly joined adhoc station.
+				if ((ADHOC_ON(pAd) && (Elem->Wcid == RESERVED_WCID)) ||
+					(pEntry && ((pEntry->LastBeaconRxTime + ADHOC_ENTRY_BEACON_LOST_TIME) < Now)))
+				{
+					if (pEntry == NULL)
+						// Another adhoc joining, add to our MAC table.
+						pEntry = MacTableInsertEntry(pAd, Addr2, BSS0, FALSE);
+
+					if (StaAddMacTableEntry(pAd, pEntry, MaxSupportedRateIn500Kbps, &HtCapability, HtCapabilityLen, CapabilityInfo) == FALSE)
+					{
+						DBGPRINT(RT_DEBUG_TRACE, ("ADHOC - Add Entry failed.\n"));
+						return;
+					}
+
+					if (pEntry &&
+						(Elem->Wcid == RESERVED_WCID))
+					{
+						idx = pAd->StaCfg.DefaultKeyId;
+						RT28XX_STA_SECURITY_INFO_ADD(pAd, BSS0, idx, pEntry);
+					}
+				}
+
+				if (pEntry && pEntry->ValidAsCLI)
+					pEntry->LastBeaconRxTime = Now;
+
+				// At least another peer in this IBSS, declare MediaState as CONNECTED
+				if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
+				{
+					OPSTATUS_SET_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
+
+					pAd->IndicateMediaState = NdisMediaStateConnected;
+					RTMP_IndicateMediaState(pAd);
+	                pAd->ExtraInfo = GENERAL_LINK_UP;
+					AsicSetBssid(pAd, pAd->CommonCfg.Bssid);
+
+					// 2003/03/12 - john
+					// Make sure this entry in "ScanTab" table, thus complies to Microsoft's policy that
+					// "site survey" result should always include the current connected network.
+					//
+					Bssidx = BssTableSearch(&pAd->ScanTab, Bssid, Channel);
+					if (Bssidx == BSS_NOT_FOUND)
+					{
+						Bssidx = BssTableSetEntry(pAd, &pAd->ScanTab, Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
+									&CfParm, AtimWin, CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen, &HtCapability,
+									&AddHtInfo, HtCapabilityLen, AddHtInfoLen, NewExtChannelOffset, Channel, RealRssi, TimeStamp, 0,
+									&EdcaParm, &QosCapability, &QbssLoad, LenVIE, pVIE);
+					}
+					DBGPRINT(RT_DEBUG_TRACE, ("ADHOC  fOP_STATUS_MEDIA_STATE_CONNECTED.\n"));
+				}
+#endif /* RT2870 */
 			}
 
 			if (INFRA_ON(pAd))
@@ -1476,7 +1486,6 @@
 					DBGPRINT(RT_DEBUG_WARN, ("SYNC - AP changed B/G protection to %d\n", bUseBGProtection));
 				}
 
-#ifdef DOT11_N_SUPPORT
 				// check Ht protection mode. and adhere to the Non-GF device indication by AP.
 				if ((AddHtInfoLen != 0) &&
 					((AddHtInfo.AddHtInfo2.OperaionMode != pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode) ||
@@ -1493,7 +1502,6 @@
 
 					DBGPRINT(RT_DEBUG_TRACE, ("SYNC - AP changed N OperaionMode to %d\n", pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode));
 				}
-#endif // DOT11_N_SUPPORT //
 
 				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED) &&
 					ERP_IS_USE_BARKER_PREAMBLE(Erp))
@@ -1528,10 +1536,12 @@
 				//  5. otherwise, put PHY back to sleep to save battery.
 				if (MessageToMe)
 				{
+#ifdef RT2860
 					if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE))
 					{
 						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, pAd->StaCfg.BBPR3);
 					}
+#endif
 					if (pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable &&
 						pAd->CommonCfg.bAPSDAC_BE && pAd->CommonCfg.bAPSDAC_BK && pAd->CommonCfg.bAPSDAC_VI && pAd->CommonCfg.bAPSDAC_VO)
 					{
@@ -1542,10 +1552,12 @@
 				}
 				else if (BcastFlag && (DtimCount == 0) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM))
 				{
+#ifdef RT2860
 					if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE))
 					{
 						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, pAd->StaCfg.BBPR3);
 					}
+#endif
 				}
 				else if ((pAd->TxSwQueue[QID_AC_BK].Number != 0)													||
 						(pAd->TxSwQueue[QID_AC_BE].Number != 0)														||
@@ -1559,10 +1571,12 @@
 				{
 					// TODO: consider scheduled HCCA. might not be proper to use traditional DTIM-based power-saving scheme
 					// can we cheat here (i.e. just check MGMT & AC_BE) for better performance?
+#ifdef RT2860
 					if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE))
 					{
 						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, pAd->StaCfg.BBPR3);
 					}
+#endif
 				}
 				else
 				{
@@ -1577,10 +1591,14 @@
 
 					if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
 					{
+#ifdef RT2860
 						// Set a flag to go to sleep . Then after parse this RxDoneInterrupt, will go to sleep mode.
 						RTMP_SET_PSFLAG(pAd, fRTMP_PS_GO_TO_SLEEP_NOW);
 						pAd->ThisTbttNumToNextWakeUp = TbttNumToNextWakeUp;
-						//AsicSleepThenAutoWakeup(pAd, TbttNumToNextWakeUp);
+#endif
+#ifdef RT2870
+						AsicSleepThenAutoWakeup(pAd, TbttNumToNextWakeUp);
+#endif
 					}
 				}
 			}
@@ -1603,9 +1621,7 @@
 	UCHAR         Addr2[MAC_ADDR_LEN];
 	CHAR          Ssid[MAX_LEN_OF_SSID];
 	UCHAR         SsidLen;
-#ifdef DOT11_N_SUPPORT
 	UCHAR		  HtLen, AddHtLen, NewExtLen;
-#endif // DOT11_N_SUPPORT //
 	HEADER_802_11 ProbeRspHdr;
 	NDIS_STATUS   NStatus;
 	PUCHAR        pOutBuffer = NULL;
@@ -1678,7 +1694,7 @@
 						  			END_OF_ARGS);
 				FrameLen += tmp;
 			}
-#ifdef DOT11_N_SUPPORT
+
 			if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
 			{
 				ULONG TmpLen;
@@ -1711,7 +1727,7 @@
 				}
 				FrameLen += TmpLen;
 			}
-#endif // DOT11_N_SUPPORT //
+
 			MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
 			MlmeFreeMemory(pAd, pOutBuffer);
 		}
@@ -1811,14 +1827,6 @@
 VOID EnqueuePsPoll(
 	IN PRTMP_ADAPTER pAd)
 {
-#ifdef RALINK_ATE
-    if (ATE_ON(pAd))
-    {
-		return;
-    }
-#endif // RALINK_ATE //
-
-
 	if (pAd->StaCfg.WindowsPowerMode == Ndis802_11PowerModeLegacy_PSP)
     	pAd->PsPollFrame.FC.PwrMgmt = PWR_SAVE;
 	MiniportMMRequest(pAd, 0, (PUCHAR)&pAd->PsPollFrame, sizeof(PSPOLL_FRAME));
@@ -1861,88 +1869,6 @@
 
 }
 
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-VOID BuildEffectedChannelList(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR		EChannel[11];
-	UCHAR		i, j, k;
-	UCHAR		UpperChannel = 0, LowerChannel = 0;
-
-	RTMPZeroMemory(EChannel, 11);
-	i = 0;
-	// Find upper channel and lower channel.
-	if (pAd->CommonCfg.CentralChannel < pAd->CommonCfg.Channel)
-	{
-		UpperChannel = pAd->CommonCfg.Channel;
-		LowerChannel = pAd->CommonCfg.CentralChannel;
-	}
-	else if (pAd->CommonCfg.CentralChannel > pAd->CommonCfg.Channel)
-	{
-		UpperChannel = pAd->CommonCfg.CentralChannel;
-		LowerChannel = pAd->CommonCfg.Channel;
-	}
-	else
-	{
-		return;
-	}
-
-	// Record channels that is below lower channel..
-	if (LowerChannel > 1)
-	{
-		EChannel[0] = LowerChannel - 1;
-		i = 1;
-		if (LowerChannel > 2)
-		{
-			EChannel[1] = LowerChannel - 2;
-			i = 2;
-			if (LowerChannel > 3)
-			{
-				EChannel[2] = LowerChannel - 3;
-				i = 3;
-			}
-		}
-	}
-	// Record channels that is between  lower channel and upper channel.
-	for (k = LowerChannel;k < UpperChannel;k++)
-	{
-		EChannel[i] = k;
-		i++;
-	}
-	// Record channels that is above upper channel..
-	if (LowerChannel < 11)
-	{
-		EChannel[i] = UpperChannel + 1;
-		i++;
-		if (LowerChannel < 10)
-		{
-			EChannel[i] = LowerChannel + 2;
-			i++;
-			if (LowerChannel < 9)
-			{
-				EChannel[i] = LowerChannel + 3;
-				i++;
-			}
-		}
-	}
-	//
-	for (j = 0;j < i;j++)
-	{
-		for (k = 0;k < pAd->ChannelListNum;k++)
-		{
-			if (pAd->ChannelList[k].Channel == EChannel[j])
-			{
-				pAd->ChannelList[k].bEffectedChannel = TRUE;
-				DBGPRINT(RT_DEBUG_TRACE,(" EffectedChannel( =%d)\n", EChannel[j]));
-				break;
-			}
-		}
-	}
-}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
 BOOLEAN ScanRunning(
 		IN PRTMP_ADAPTER pAd)
 {
diff --git a/drivers/staging/rt2860/sta/wpa.c b/drivers/staging/rt2860/sta/wpa.c
index 2609d84..5827436 100644
--- a/drivers/staging/rt2860/sta/wpa.c
+++ b/drivers/staging/rt2860/sta/wpa.c
@@ -1384,10 +1384,12 @@
 			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_TKIP;
 		else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
 			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_AES;
+#ifndef RT30xx
 		else if (pAd->StaCfg.GroupCipher == Ndis802_11GroupWEP40Enabled)
 			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_WEP64;
 		else if (pAd->StaCfg.GroupCipher == Ndis802_11GroupWEP104Enabled)
 			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_WEP128;
+#endif
 
     	//hex_dump("Group Key :", pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, LEN_TKIP_EK);
 	}
@@ -1764,7 +1766,12 @@
 	// Get GTK length - refer to IEEE 802.11i-2004 p.82
 	GTKLEN = pKDE->Len -6;
 
+#ifdef RT30xx
+	if (GTKLEN < LEN_AES_KEY)
+#endif
+#ifndef RT30xx
 	if (GTKLEN < MIN_LEN_OF_GTK)
+#endif
 	{
 		DBGPRINT(RT_DEBUG_ERROR, ("ERROR: GTK Key length is too short (%d) \n", GTKLEN));
         return FALSE;
@@ -1790,10 +1797,12 @@
 		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_TKIP;
 	else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
 		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_AES;
+#ifndef RT30xx
 	else if (pAd->StaCfg.GroupCipher == Ndis802_11GroupWEP40Enabled)
 		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_WEP64;
 	else if (pAd->StaCfg.GroupCipher == Ndis802_11GroupWEP104Enabled)
 		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_WEP128;
+#endif
 
 	return TRUE;
 
@@ -1915,8 +1924,6 @@
     }
 }
 
-
-#ifdef WPA_SUPPLICANT_SUPPORT
 #define	LENGTH_EAP_H    4
 // If the received frame is EAP-Packet ,find out its EAP-Code (Request(0x01), Response(0x02), Success(0x03), Failure(0x04)).
 INT	    WpaCheckEapCode(
@@ -1957,7 +1964,6 @@
 
     return;
 }
-#endif // WPA_SUPPLICANT_SUPPORT //
 
 VOID	WpaMicFailureReportFrame(
 	IN  PRTMP_ADAPTER   pAd,
diff --git a/drivers/staging/rt2860/sta_ioctl.c b/drivers/staging/rt2860/sta_ioctl.c
index c5452f1..eb0109a 100644
--- a/drivers/staging/rt2860/sta_ioctl.c
+++ b/drivers/staging/rt2860/sta_ioctl.c
@@ -49,10 +49,6 @@
 
 #define GROUP_KEY_NO                4
 
-#define IWE_STREAM_ADD_EVENT(_A, _B, _C, _D, _E)		iwe_stream_add_event(_A, _B, _C, _D, _E)
-#define IWE_STREAM_ADD_POINT(_A, _B, _C, _D, _E)		iwe_stream_add_point(_A, _B, _C, _D, _E)
-#define IWE_STREAM_ADD_VALUE(_A, _B, _C, _D, _E, _F)	iwe_stream_add_value(_A, _B, _C, _D, _E, _F)
-
 extern UCHAR    CipherWpa2Template[];
 extern UCHAR    CipherWpaPskTkip[];
 extern UCHAR    CipherWpaPskTkipLen;
@@ -89,12 +85,12 @@
 	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "radio_off" },
 	{ RAIO_ON,
 	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "radio_on" },
-#ifdef QOS_DLS_SUPPORT
-	{ SHOW_DLS_ENTRY_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "dlsentryinfo" },
-#endif // QOS_DLS_SUPPORT //
 	{ SHOW_CFG_VALUE,
 	  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "show" },
+#if !defined(RT2860) && !defined(RT30xx)
+	{ SHOW_ADHOC_ENTRY_INFO,
+	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "adhocEntry" },
+#endif
 /* --- sub-ioctls relations --- */
 
 #ifdef DBG
@@ -104,6 +100,11 @@
 { RTPRIV_IOCTL_MAC,
   IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | 1024,
   "mac"},
+#ifdef RT30xx
+{ RTPRIV_IOCTL_RF,
+  IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
+  "rf"},
+#endif // RT30xx //
 { RTPRIV_IOCTL_E2P,
   IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | 1024,
   "e2p"},
@@ -168,16 +169,16 @@
     IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
-#ifdef WPA_SUPPLICANT_SUPPORT
 INT Set_Wpa_Support(
     IN	PRTMP_ADAPTER	pAd,
 	IN	PUCHAR			arg);
-#endif // WPA_SUPPLICANT_SUPPORT //
 
 #ifdef DBG
+#if !defined(RT2860) && !defined(RT30xx)
 VOID RTMPIoctlBBP(
 	IN	PRTMP_ADAPTER	pAdapter,
 	IN	struct iwreq	*wrq);
+#endif
 
 VOID RTMPIoctlMAC(
 	IN	PRTMP_ADAPTER	pAdapter,
@@ -186,6 +187,12 @@
 VOID RTMPIoctlE2PROM(
     IN  PRTMP_ADAPTER   pAdapter,
     IN  struct iwreq    *wrq);
+
+#ifdef RT30xx
+VOID RTMPIoctlRF(
+    IN  PRTMP_ADAPTER   pAdapter,
+    IN  struct iwreq    *wrq);
+#endif // RT30xx //
 #endif // DBG //
 
 
@@ -197,11 +204,9 @@
     IN  PRTMP_ADAPTER   pAdapter,
     IN  PUCHAR          arg);
 
-#ifdef DOT11_N_SUPPORT
 INT Set_TGnWifiTest_Proc(
     IN  PRTMP_ADAPTER   pAd,
     IN  PUCHAR          arg);
-#endif // DOT11_N_SUPPORT //
 
 INT Set_LongRetryLimit_Proc(
 	IN	PRTMP_ADAPTER	pAdapter,
@@ -211,17 +216,11 @@
 	IN	PRTMP_ADAPTER	pAdapter,
 	IN	PUCHAR			arg);
 
-#ifdef EXT_BUILD_CHANNEL_LIST
-INT Set_Ieee80211dClientMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef CARRIER_DETECTION_SUPPORT
-INT Set_CarrierDetect_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg);
-#endif // CARRIER_DETECTION_SUPPORT //
+#if !defined(RT2860) && !defined(RT30xx)
+INT	Show_Adhoc_MacTable_Proc(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PCHAR			extra);
+#endif
 
 static struct {
 	CHAR *name;
@@ -239,7 +238,6 @@
 	{"BGProtection",				Set_BGProtection_Proc},
 	{"RTSThreshold",				Set_RTSThreshold_Proc},
 	{"FragThreshold",				Set_FragThreshold_Proc},
-#ifdef DOT11_N_SUPPORT
 	{"HtBw",		                Set_HtBw_Proc},
 	{"HtMcs",		                Set_HtMcs_Proc},
 	{"HtGi",		                Set_HtGi_Proc},
@@ -253,8 +251,6 @@
 	{"HtBaDecline",					Set_BADecline_Proc},
 	{"HtProtect",		        	Set_HtProtect_Proc},
 	{"HtMimoPs",		        	Set_HtMimoPs_Proc},
-#endif // DOT11_N_SUPPORT //
-
 #ifdef AGGREGATION_SUPPORT
 	{"PktAggregate",				Set_PktAggregate_Proc},
 #endif
@@ -277,68 +273,19 @@
 #ifdef DBG
 	{"Debug",						Set_Debug_Proc},
 #endif
-
-#ifdef RALINK_ATE
-	{"ATE",							Set_ATE_Proc},
-	{"ATEDA",						Set_ATE_DA_Proc},
-	{"ATESA",						Set_ATE_SA_Proc},
-	{"ATEBSSID",					Set_ATE_BSSID_Proc},
-	{"ATECHANNEL",					Set_ATE_CHANNEL_Proc},
-	{"ATETXPOW0",					Set_ATE_TX_POWER0_Proc},
-	{"ATETXPOW1",					Set_ATE_TX_POWER1_Proc},
-	{"ATETXANT",					Set_ATE_TX_Antenna_Proc},
-	{"ATERXANT",					Set_ATE_RX_Antenna_Proc},
-	{"ATETXFREQOFFSET",				Set_ATE_TX_FREQOFFSET_Proc},
-	{"ATETXBW",						Set_ATE_TX_BW_Proc},
-	{"ATETXLEN",					Set_ATE_TX_LENGTH_Proc},
-	{"ATETXCNT",					Set_ATE_TX_COUNT_Proc},
-	{"ATETXMCS",					Set_ATE_TX_MCS_Proc},
-	{"ATETXMODE",					Set_ATE_TX_MODE_Proc},
-	{"ATETXGI",						Set_ATE_TX_GI_Proc},
-	{"ATERXFER",					Set_ATE_RX_FER_Proc},
-	{"ATERRF",						Set_ATE_Read_RF_Proc},
-	{"ATEWRF1",						Set_ATE_Write_RF1_Proc},
-	{"ATEWRF2",						Set_ATE_Write_RF2_Proc},
-	{"ATEWRF3",						Set_ATE_Write_RF3_Proc},
-	{"ATEWRF4",						Set_ATE_Write_RF4_Proc},
-	{"ATELDE2P",				    Set_ATE_Load_E2P_Proc},
-	{"ATERE2P",						Set_ATE_Read_E2P_Proc},
-	{"ATESHOW",						Set_ATE_Show_Proc},
-	{"ATEHELP",						Set_ATE_Help_Proc},
-
-#ifdef RALINK_28xx_QA
-	{"TxStop",						Set_TxStop_Proc},
-	{"RxStop",						Set_RxStop_Proc},
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
     {"WpaSupport",                  Set_Wpa_Support},
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-
 	{"FixedTxMode",                 Set_FixedTxMode_Proc},
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	{"OpMode",						Set_OpMode_Proc},
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-#ifdef DOT11_N_SUPPORT
     {"TGnWifiTest",                 Set_TGnWifiTest_Proc},
     {"ForceGF",		        		Set_ForceGF_Proc},
-#endif // DOT11_N_SUPPORT //
-#ifdef QOS_DLS_SUPPORT
-	{"DlsAddEntry",					Set_DlsAddEntry_Proc},
-	{"DlsTearDownEntry",			Set_DlsTearDownEntry_Proc},
-#endif // QOS_DLS_SUPPORT //
 	{"LongRetry",	        		Set_LongRetryLimit_Proc},
 	{"ShortRetry",	        		Set_ShortRetryLimit_Proc},
-#ifdef EXT_BUILD_CHANNEL_LIST
-	{"11dClientMode",				Set_Ieee80211dClientMode_Proc},
-#endif // EXT_BUILD_CHANNEL_LIST //
-#ifdef CARRIER_DETECTION_SUPPORT
-	{"CarrierDetect",				Set_CarrierDetect_Proc},
-#endif // CARRIER_DETECTION_SUPPORT //
-
+//2008/09/11:KH add to support efuse<--
+#ifdef RT30xx
+	{"efuseFreeNumber",				set_eFuseGetFreeBlockCount_Proc},
+	{"efuseDump",					set_eFusedump_Proc},
+	{"efuseLoadFromBin",				set_eFuseLoadFromBin_Proc},
+#endif // RT30xx //
+//2008/09/11:KH add to support efuse-->
 	{NULL,}
 };
 
@@ -352,6 +299,7 @@
 
     DBGPRINT(RT_DEBUG_TRACE, ("RTMPAddKey ------>\n"));
 
+#ifdef RT2860
 	RTMP_CLEAR_PSFLAG(pAd, fRTMP_PS_CAN_GO_SLEEP);
 	if (RTMP_TEST_PSFLAG(pAd, fRTMP_PS_SET_PCI_CLK_OFF_COMMAND))
 	{
@@ -365,6 +313,7 @@
 		RTMPusecDelay(6000);
 		pAd->bPCIclkOff = FALSE;
 	}
+#endif
 
 	if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
 	{
@@ -380,14 +329,13 @@
 		    NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
             pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
             NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, pKey->KeyMaterial, LEN_TKIP_EK);
-#ifdef WPA_SUPPLICANT_SUPPORT
+
             if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
             {
                 NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
                 NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
             }
             else
-#endif // WPA_SUPPLICANT_SUPPORT //
             {
             	NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
                 NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
@@ -440,14 +388,13 @@
             NdisZeroMemory(&pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId], sizeof(CIPHER_KEY));
             pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].KeyLen = LEN_TKIP_EK;
             NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, pKey->KeyMaterial, LEN_TKIP_EK);
-#ifdef WPA_SUPPLICANT_SUPPORT
+
             if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
             {
                 NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
                 NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
             }
             else
-#endif // WPA_SUPPLICANT_SUPPORT //
             {
             	NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
                 NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
@@ -559,8 +506,10 @@
 		}
 	}
 end:
+#ifdef RT2860
 	RTMP_SET_PSFLAG(pAd, fRTMP_PS_CAN_GO_SLEEP);
     DBGPRINT(RT_DEBUG_INFO, ("<------ RTMPAddKey\n"));
+#endif
 	return;
 }
 
@@ -582,8 +531,12 @@
 		   char *name, char *extra)
 {
 //	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
+#ifdef RT2860
     strncpy(name, "RT2860 Wireless", IFNAMSIZ);
+#endif
+#ifdef RT2870
+	strncpy(name, "RT2870 Wireless", IFNAMSIZ);
+#endif // RT2870 //
 	return 0;
 }
 
@@ -625,7 +578,12 @@
 		   struct iw_freq *freq, char *extra)
 {
     VIRTUAL_ADAPTER *pVirtualAd = NULL;
+#ifndef RT30xx
 	PRTMP_ADAPTER pAdapter = NULL;
+#endif
+#ifdef RT30xx
+	PRTMP_ADAPTER pAdapter;
+#endif
 	UCHAR ch;
 	ULONG	m;
 
@@ -636,7 +594,9 @@
 	else
 	{
 		pVirtualAd = dev->ml_priv;
+#ifndef RT30xx
 		if (pVirtualAd && pVirtualAd->RtmpDev)
+#endif
 			pAdapter = pVirtualAd->RtmpDev->ml_priv;
 	}
 
@@ -696,6 +656,7 @@
 		   struct iw_request_info *info,
 		   __u32 *mode, char *extra)
 {
+#ifndef RT30xx
 	PRTMP_ADAPTER 	pAdapter = NULL;
 	VIRTUAL_ADAPTER *pVirtualAd = NULL;
 
@@ -716,6 +677,10 @@
 		   So the net_dev->ml_priv will be NULL in 2rd open */
 		return -ENETDOWN;
 	}
+#endif
+#ifdef RT30xx
+	PRTMP_ADAPTER pAdapter = dev->ml_priv;
+#endif
 
 	if (ADHOC_ON(pAdapter))
 		*mode = IW_MODE_ADHOC;
@@ -759,12 +724,18 @@
 		   struct iw_request_info *info,
 		   struct iw_point *data, char *extra)
 {
+#ifndef RT30xx
 	PRTMP_ADAPTER 	pAdapter = NULL;
 	VIRTUAL_ADAPTER *pVirtualAd = NULL;
+#endif
+#ifdef RT30xx
+	PRTMP_ADAPTER pAdapter = dev->ml_priv;
+#endif
 	struct iw_range *range = (struct iw_range *) extra;
 	u16 val;
 	int i;
 
+#ifndef RT30xx
 	if (dev->priv_flags == INT_MAIN)
 	{
 		pAdapter = dev->ml_priv;
@@ -782,6 +753,7 @@
 		   So the net_dev->ml_priv will be NULL in 2rd open */
 		return -ENETDOWN;
 	}
+#endif
 
 	DBGPRINT(RT_DEBUG_TRACE ,("===>rt_ioctl_giwrange\n"));
 	data->length = sizeof(struct iw_range);
@@ -901,6 +873,7 @@
 		      struct iw_request_info *info,
 		      struct sockaddr *ap_addr, char *extra)
 {
+#ifndef RT30xx
 	PRTMP_ADAPTER 	pAdapter = NULL;
 	VIRTUAL_ADAPTER *pVirtualAd = NULL;
 
@@ -921,20 +894,22 @@
 		   So the net_dev->ml_priv will be NULL in 2rd open */
 		return -ENETDOWN;
 	}
+#endif
+#ifdef RT30xx
+	PRTMP_ADAPTER pAdapter = dev->ml_priv;
+#endif
 
 	if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
 	{
 		ap_addr->sa_family = ARPHRD_ETHER;
 		memcpy(ap_addr->sa_data, &pAdapter->CommonCfg.Bssid, ETH_ALEN);
 	}
-#ifdef WPA_SUPPLICANT_SUPPORT
     // Add for RT2870
     else if (pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
     {
         ap_addr->sa_family = ARPHRD_ETHER;
         memcpy(ap_addr->sa_data, &pAdapter->MlmeAux.Bssid, ETH_ALEN);
     }
-#endif // WPA_SUPPLICANT_SUPPORT //
 	else
 	{
 		DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCGIWAP(=EMPTY)\n"));
@@ -1041,7 +1016,7 @@
         DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is in Monitor Mode now !!!\n"));
         return -EINVAL;
     }
-
+#ifdef RT2860
 	if ((pAdapter->OpMode == OPMODE_STA) && (IDLE_ON(pAdapter))
 		&& (pAdapter->StaCfg.bRadio == TRUE)
 		&& (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_IDLE_RADIO_OFF)))
@@ -1051,13 +1026,11 @@
 	// Check if still radio off.
 	else if (pAdapter->bPCIclkOff == TRUE)
 		return 0;
-
-#ifdef WPA_SUPPLICANT_SUPPORT
+#endif
 	if (pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
 	{
 		pAdapter->StaCfg.WpaSupplicantScanCount++;
 	}
-#endif // WPA_SUPPLICANT_SUPPORT //
 
     pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
 	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
@@ -1065,7 +1038,6 @@
 	do{
 		Now = jiffies;
 
-#ifdef WPA_SUPPLICANT_SUPPORT
 		if ((pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE) &&
 			(pAdapter->StaCfg.WpaSupplicantScanCount > 3))
 		{
@@ -1073,7 +1045,6 @@
 			Status = NDIS_STATUS_SUCCESS;
 			break;
 		}
-#endif // WPA_SUPPLICANT_SUPPORT //
 
 		if ((OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED)) &&
 			((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
@@ -1133,13 +1104,10 @@
 		return -EAGAIN;
 	}
 
-
-#ifdef WPA_SUPPLICANT_SUPPORT
 	if (pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
 	{
 		pAdapter->StaCfg.WpaSupplicantScanCount = 0;
 	}
-#endif // WPA_SUPPLICANT_SUPPORT //
 
 	if (pAdapter->ScanTab.BssNr == 0)
 	{
@@ -1175,7 +1143,88 @@
 		memcpy(iwe.u.ap_addr.sa_data, &pAdapter->ScanTab.BssEntry[i].Bssid, ETH_ALEN);
 
         previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev,end_buf, &iwe, IW_EV_ADDR_LEN);
+		current_ev = iwe_stream_add_event(info, current_ev,end_buf, &iwe, IW_EV_ADDR_LEN);
+#ifdef RT30xx
+        if (current_ev == previous_ev)
+#if WIRELESS_EXT >= 17
+            return -E2BIG;
+#else
+			break;
+#endif
+
+		/*
+		Protocol:
+			it will show scanned AP's WirelessMode .
+			it might be
+					802.11a
+					802.11a/n
+					802.11g/n
+					802.11b/g/n
+					802.11g
+					802.11b/g
+		*/
+		memset(&iwe, 0, sizeof(iwe));
+		iwe.cmd = SIOCGIWNAME;
+
+
+	{
+		PBSS_ENTRY pBssEntry=&pAdapter->ScanTab.BssEntry[i];
+		BOOLEAN isGonly=FALSE;
+		int rateCnt=0;
+
+		if (pBssEntry->Channel>14)
+		{
+			if (pBssEntry->HtCapabilityLen!=0)
+				strcpy(iwe.u.name,"802.11a/n");
+			else
+				strcpy(iwe.u.name,"802.11a");
+		}
+		else
+		{
+			/*
+				if one of non B mode rate is set supported rate . it mean G only.
+			*/
+			for (rateCnt=0;rateCnt<pBssEntry->SupRateLen;rateCnt++)
+			{
+				/*
+					6Mbps(140) 9Mbps(146) and >=12Mbps(152) are supported rate , it mean G only.
+				*/
+				if (pBssEntry->SupRate[rateCnt]==140 || pBssEntry->SupRate[rateCnt]==146 || pBssEntry->SupRate[rateCnt]>=152)
+					isGonly=TRUE;
+			}
+
+			for (rateCnt=0;rateCnt<pBssEntry->ExtRateLen;rateCnt++)
+			{
+				if (pBssEntry->ExtRate[rateCnt]==140 || pBssEntry->ExtRate[rateCnt]==146 || pBssEntry->ExtRate[rateCnt]>=152)
+					isGonly=TRUE;
+			}
+
+
+			if (pBssEntry->HtCapabilityLen!=0)
+			{
+				if (isGonly==TRUE)
+					strcpy(iwe.u.name,"802.11g/n");
+				else
+					strcpy(iwe.u.name,"802.11b/g/n");
+			}
+			else
+			{
+				if (isGonly==TRUE)
+					strcpy(iwe.u.name,"802.11g");
+				else
+				{
+					if (pBssEntry->SupRateLen==4 && pBssEntry->ExtRateLen==0)
+						strcpy(iwe.u.name,"802.11b");
+					else
+						strcpy(iwe.u.name,"802.11b/g");
+				}
+			}
+		}
+	}
+
+		previous_ev = current_ev;
+		current_ev	 = iwe_stream_add_event(info, current_ev, end_buf, &iwe, IW_EV_ADDR_LEN);
+#endif /* RT30xx */
         if (current_ev == previous_ev)
 #if WIRELESS_EXT >= 17
             return -E2BIG;
@@ -1191,7 +1240,7 @@
 		iwe.u.data.flags = 1;
 
         previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_POINT(info, current_ev,end_buf, &iwe, pAdapter->ScanTab.BssEntry[i].Ssid);
+		current_ev = iwe_stream_add_point(info, current_ev,end_buf, &iwe, pAdapter->ScanTab.BssEntry[i].Ssid);
         if (current_ev == previous_ev)
 #if WIRELESS_EXT >= 17
             return -E2BIG;
@@ -1218,7 +1267,7 @@
 		iwe.len = IW_EV_UINT_LEN;
 
         previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev, end_buf, &iwe,  IW_EV_UINT_LEN);
+		current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe,  IW_EV_UINT_LEN);
         if (current_ev == previous_ev)
 #if WIRELESS_EXT >= 17
             return -E2BIG;
@@ -1238,7 +1287,7 @@
 		iwe.u.freq.i = 0;
 
 		previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev,end_buf, &iwe, IW_EV_FREQ_LEN);
+		current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe, IW_EV_FREQ_LEN);
         if (current_ev == previous_ev)
 #if WIRELESS_EXT >= 17
             return -E2BIG;
@@ -1253,7 +1302,7 @@
     	iwe.u.qual.level = 0;
     	iwe.u.qual.noise = 0;
         set_quality(pAdapter, &iwe.u.qual, pAdapter->ScanTab.BssEntry[i].Rssi);
-    	current_ev = IWE_STREAM_ADD_EVENT(info, current_ev, end_buf, &iwe, IW_EV_QUAL_LEN);
+    	current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe, IW_EV_QUAL_LEN);
         if (current_ev == previous_ev)
 #if WIRELESS_EXT >= 17
             return -E2BIG;
@@ -1271,7 +1320,7 @@
 			iwe.u.data.flags = IW_ENCODE_DISABLED;
 
         previous_ev = current_ev;
-        current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf,&iwe, (char *)pAdapter->SharedKey[BSS0][(iwe.u.data.flags & IW_ENCODE_INDEX)-1].Key);
+        current_ev = iwe_stream_add_point(info, current_ev, end_buf,&iwe, (char *)pAdapter->SharedKey[BSS0][(iwe.u.data.flags & IW_ENCODE_INDEX)-1].Key);
         if (current_ev == previous_ev)
 #if WIRELESS_EXT >= 17
             return -E2BIG;
@@ -1299,7 +1348,7 @@
     		    iwe.u.bitrate.value =  (tmpRate/2) * 1000000;
 
 			iwe.u.bitrate.disabled = 0;
-			current_val = IWE_STREAM_ADD_VALUE(info, current_ev,
+			current_val = iwe_stream_add_value(info, current_ev,
 				current_val, end_buf, &iwe,
     			IW_EV_PARAM_LEN);
 
@@ -1323,7 +1372,7 @@
 						   pAdapter->ScanTab.BssEntry[i].WpaIE.IELen);
 			iwe.cmd = IWEVGENIE;
 			iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].WpaIE.IELen;
-			current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe, custom);
+			current_ev = iwe_stream_add_point(info, current_ev, end_buf, &iwe, custom);
 			if (current_ev == previous_ev)
 #if WIRELESS_EXT >= 17
                 return -E2BIG;
@@ -1341,7 +1390,7 @@
 						   pAdapter->ScanTab.BssEntry[i].RsnIE.IELen);
 			iwe.cmd = IWEVGENIE;
 			iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].RsnIE.IELen;
-			current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe, custom);
+			current_ev = iwe_stream_add_point(info, current_ev, end_buf, &iwe, custom);
 			if (current_ev == previous_ev)
 #if WIRELESS_EXT >= 17
                 return -E2BIG;
@@ -1360,9 +1409,9 @@
             iwe.u.data.length = (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen * 2) + 7;
             NdisMoveMemory(custom, "wpa_ie=", 7);
             for (idx = 0; idx < pAdapter->ScanTab.BssEntry[i].WpaIE.IELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAdapter->ScanTab.BssEntry[i].WpaIE.IE[idx]);
+                sprintf(custom + strlen(custom), "%02x", pAdapter->ScanTab.BssEntry[i].WpaIE.IE[idx]);
             previous_ev = current_ev;
-    		current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe,  custom);
+    		current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe,  custom);
             if (current_ev == previous_ev)
 #if WIRELESS_EXT >= 17
                 return -E2BIG;
@@ -1380,9 +1429,9 @@
             iwe.u.data.length = (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen * 2) + 7;
             NdisMoveMemory(custom, "rsn_ie=", 7);
 			for (idx = 0; idx < pAdapter->ScanTab.BssEntry[i].RsnIE.IELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAdapter->ScanTab.BssEntry[i].RsnIE.IE[idx]);
+                sprintf(custom + strlen(custom), "%02x", pAdapter->ScanTab.BssEntry[i].RsnIE.IE[idx]);
             previous_ev = current_ev;
-    		current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe,  custom);
+    		current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe,  custom);
             if (current_ev == previous_ev)
 #if WIRELESS_EXT >= 17
                 return -E2BIG;
@@ -1445,6 +1494,7 @@
 			 struct iw_request_info *info,
 			 struct iw_point *data, char *essid)
 {
+#ifndef RT30xx
 	PRTMP_ADAPTER 	pAdapter = NULL;
 	VIRTUAL_ADAPTER *pVirtualAd = NULL;
 
@@ -1465,6 +1515,10 @@
 		   So the net_dev->ml_priv will be NULL in 2rd open */
 		return -ENETDOWN;
 	}
+#endif
+#ifdef RT30xx
+	PRTMP_ADAPTER pAdapter = dev->ml_priv;
+#endif
 
 	data->flags = 1;
     if (MONITOR_ON(pAdapter))
@@ -1479,6 +1533,14 @@
 		data->length = pAdapter->CommonCfg.SsidLen;
 		memcpy(essid, pAdapter->CommonCfg.Ssid, pAdapter->CommonCfg.SsidLen);
 	}
+#ifdef RT2870
+    // Add for RT2870
+    else if (pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
+    {
+        data->length = pAdapter->CommonCfg.SsidLen;
+		memcpy(essid, pAdapter->CommonCfg.Ssid, pAdapter->CommonCfg.SsidLen);
+	}
+#endif // RT2870 //
 	else
 	{//the ANY ssid was specified
 		data->length  = 0;
@@ -1516,6 +1578,7 @@
 			 struct iw_request_info *info,
 			 struct iw_point *data, char *nickname)
 {
+#ifndef RT30xx
 	PRTMP_ADAPTER 	pAdapter = NULL;
 	VIRTUAL_ADAPTER *pVirtualAd = NULL;
 
@@ -1536,6 +1599,10 @@
 		   So the net_dev->ml_priv will be NULL in 2rd open */
 		return -ENETDOWN;
 	}
+#endif
+#ifdef RT30xx
+	PRTMP_ADAPTER pAdapter = dev->ml_priv;
+#endif
 
 	if (data->length > strlen(pAdapter->nickname) + 1)
 		data->length = strlen(pAdapter->nickname) + 1;
@@ -1579,6 +1646,7 @@
 		       struct iw_request_info *info,
 		       struct iw_param *rts, char *extra)
 {
+#ifndef RT30xx
 	PRTMP_ADAPTER 	pAdapter = NULL;
 	VIRTUAL_ADAPTER *pVirtualAd = NULL;
 
@@ -1599,6 +1667,10 @@
 		   So the net_dev->ml_priv will be NULL in 2rd open */
 		return -ENETDOWN;
 	}
+#endif
+#ifdef RT30xx
+	PRTMP_ADAPTER pAdapter = dev->ml_priv;
+#endif
 
 	//check if the interface is down
     	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
@@ -1645,6 +1717,7 @@
 			struct iw_request_info *info,
 			struct iw_param *frag, char *extra)
 {
+#ifndef RT30xx
 	PRTMP_ADAPTER 	pAdapter = NULL;
 	VIRTUAL_ADAPTER *pVirtualAd = NULL;
 
@@ -1665,6 +1738,10 @@
 		   So the net_dev->ml_priv will be NULL in 2rd open */
 		return -ENETDOWN;
 	}
+#endif
+#ifdef RT30xx
+	PRTMP_ADAPTER pAdapter = dev->ml_priv;
+#endif
 
 	//check if the interface is down
     	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
@@ -1705,8 +1782,13 @@
         pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
         goto done;
 	}
+#ifndef RT30xx
 	else if ((erq->length == 0) &&
              (erq->flags & IW_ENCODE_RESTRICTED || erq->flags & IW_ENCODE_OPEN))
+#endif
+#ifdef RT30xx
+	else if (erq->flags & IW_ENCODE_RESTRICTED || erq->flags & IW_ENCODE_OPEN)
+#endif
 	{
 		STA_PORT_SECURED(pAdapter);
 		pAdapter->StaCfg.PairCipher = Ndis802_11WEPEnabled;
@@ -1717,7 +1799,9 @@
 			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
     	else
 			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
+#ifndef RT30xx
         goto done;
+#endif
 	}
 
     if (erq->length > 0)
@@ -1736,6 +1820,12 @@
             //Using default key
 			keyIdx = pAdapter->StaCfg.DefaultKeyId;
         }
+#ifdef RT30xx
+		else
+		{
+			pAdapter->StaCfg.DefaultKeyId=keyIdx;
+		}
+#endif
 
         NdisZeroMemory(pAdapter->SharedKey[BSS0][keyIdx].Key,  16);
 
@@ -1787,7 +1877,11 @@
 			  struct iw_request_info *info,
 			  struct iw_point *erq, char *key)
 {
+#ifdef RT30xx
+	PRTMP_ADAPTER pAdapter = dev->ml_priv;
+#endif
 	int kid;
+#ifndef RT30xx
 	PRTMP_ADAPTER 	pAdapter = NULL;
 	VIRTUAL_ADAPTER *pVirtualAd = NULL;
 
@@ -1808,6 +1902,7 @@
 		   So the net_dev->ml_priv will be NULL in 2rd open */
 		return -ENETDOWN;
 	}
+#endif
 
 	//check if the interface is down
 	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
@@ -1952,14 +2047,6 @@
     memset(extra, 0x00, IW_PRIV_SIZE_MASK);
     sprintf(extra, "\n\n");
 
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-	    sprintf(extra+strlen(extra), "Tx success                      = %ld\n", (ULONG)pAd->ate.TxDoneCount);
-	    //sprintf(extra+strlen(extra), "Tx success without retry        = %ld\n", (ULONG)pAd->ate.TxDoneCount);
-	}
-	else
-#endif // RALINK_ATE //
 	{
     sprintf(extra+strlen(extra), "Tx success                      = %ld\n", (ULONG)pAd->WlanCounters.TransmittedFragmentCount.QuadPart);
     sprintf(extra+strlen(extra), "Tx success without retry        = %ld\n", (ULONG)pAd->WlanCounters.TransmittedFragmentCount.QuadPart - (ULONG)pAd->WlanCounters.RetryCount.QuadPart);
@@ -1975,31 +2062,12 @@
     sprintf(extra+strlen(extra), "Rx duplicate frame              = %ld\n", (ULONG)pAd->WlanCounters.FrameDuplicateCount.QuadPart);
 
     sprintf(extra+strlen(extra), "False CCA (one second)          = %ld\n", (ULONG)pAd->RalinkCounters.OneSecFalseCCACnt);
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-		if (pAd->ate.RxAntennaSel == 0)
-		{
-    		sprintf(extra+strlen(extra), "RSSI-A                          = %ld\n", (LONG)(pAd->ate.LastRssi0 - pAd->BbpRssiToDbmDelta));
-			sprintf(extra+strlen(extra), "RSSI-B (if available)           = %ld\n", (LONG)(pAd->ate.LastRssi1 - pAd->BbpRssiToDbmDelta));
-			sprintf(extra+strlen(extra), "RSSI-C (if available)           = %ld\n\n", (LONG)(pAd->ate.LastRssi2 - pAd->BbpRssiToDbmDelta));
-		}
-		else
-		{
-    		sprintf(extra+strlen(extra), "RSSI                            = %ld\n", (LONG)(pAd->ate.LastRssi0 - pAd->BbpRssiToDbmDelta));
-		}
-	}
-	else
-#endif // RALINK_ATE //
 	{
     	sprintf(extra+strlen(extra), "RSSI-A                          = %ld\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi0 - pAd->BbpRssiToDbmDelta));
         sprintf(extra+strlen(extra), "RSSI-B (if available)           = %ld\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi1 - pAd->BbpRssiToDbmDelta));
         sprintf(extra+strlen(extra), "RSSI-C (if available)           = %ld\n\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi2 - pAd->BbpRssiToDbmDelta));
 	}
-#ifdef WPA_SUPPLICANT_SUPPORT
     sprintf(extra+strlen(extra), "WpaSupplicantUP                 = %d\n\n", pAd->StaCfg.WpaSupplicantUP);
-#endif // WPA_SUPPLICANT_SUPPORT //
-
 
     wrq->length = strlen(extra) + 1; // 1: size of '\0'
     DBGPRINT(RT_DEBUG_TRACE, ("<== rt_private_get_statistics, wrq->length = %d\n", wrq->length));
@@ -2007,7 +2075,6 @@
     return Status;
 }
 
-#ifdef DOT11_N_SUPPORT
 void	getBaInfo(
 	IN	PRTMP_ADAPTER	pAd,
 	IN	PUCHAR			pOutBuf)
@@ -2022,8 +2089,7 @@
 		if (((pEntry->ValidAsCLI || pEntry->ValidAsApCli) && (pEntry->Sst == SST_ASSOC))
 			|| (pEntry->ValidAsWDS) || (pEntry->ValidAsMesh))
 		{
-			sprintf(pOutBuf, "%s\n%02X:%02X:%02X:%02X:%02X:%02X (Aid = %d) (AP) -\n",
-                pOutBuf,
+			sprintf(pOutBuf + strlen(pOutBuf), "\n%02X:%02X:%02X:%02X:%02X:%02X (Aid = %d) (AP) -\n",
 				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
 				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5], pEntry->Aid);
 
@@ -2033,7 +2099,7 @@
 				if (pEntry->BARecWcidArray[j] != 0)
 				{
 					pRecBAEntry =&pAd->BATable.BARecEntry[pEntry->BARecWcidArray[j]];
-					sprintf(pOutBuf, "%sTID=%d, BAWinSize=%d, LastIndSeq=%d, ReorderingPkts=%d\n", pOutBuf, j, pRecBAEntry->BAWinSize, pRecBAEntry->LastIndSeq, pRecBAEntry->list.qlen);
+					sprintf(pOutBuf + strlen(pOutBuf), "TID=%d, BAWinSize=%d, LastIndSeq=%d, ReorderingPkts=%d\n", j, pRecBAEntry->BAWinSize, pRecBAEntry->LastIndSeq, pRecBAEntry->list.qlen);
 				}
 			}
 			sprintf(pOutBuf, "%s\n", pOutBuf);
@@ -2044,7 +2110,7 @@
 				if (pEntry->BAOriWcidArray[j] != 0)
 				{
 					pOriBAEntry =&pAd->BATable.BAOriEntry[pEntry->BAOriWcidArray[j]];
-					sprintf(pOutBuf, "%sTID=%d, BAWinSize=%d, StartSeq=%d, CurTxSeq=%d\n", pOutBuf, j, pOriBAEntry->BAWinSize, pOriBAEntry->Sequence, pEntry->TxSeq[j]);
+					sprintf(pOutBuf + strlen(pOutBuf), "TID=%d, BAWinSize=%d, StartSeq=%d, CurTxSeq=%d\n", j, pOriBAEntry->BAWinSize, pOriBAEntry->Sequence, pEntry->TxSeq[j]);
 				}
 			}
 			sprintf(pOutBuf, "%s\n\n", pOutBuf);
@@ -2055,7 +2121,6 @@
 
 	return;
 }
-#endif // DOT11_N_SUPPORT //
 
 static int
 rt_private_show(struct net_device *dev, struct iw_request_info *info,
@@ -2101,12 +2166,10 @@
         case SHOW_CONN_STATUS:
             if (MONITOR_ON(pAd))
             {
-#ifdef DOT11_N_SUPPORT
                 if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
                     pAd->CommonCfg.RegTransmitSetting.field.BW)
                     sprintf(extra, "Monitor Mode(CentralChannel %d)\n", pAd->CommonCfg.CentralChannel);
                 else
-#endif // DOT11_N_SUPPORT //
                     sprintf(extra, "Monitor Mode(Channel %d)\n", pAd->CommonCfg.Channel);
             }
             else
@@ -2140,12 +2203,10 @@
             sprintf(extra, "Driver version-%s, %s %s\n", STA_DRIVER_VERSION, __DATE__, __TIME__ );
             wrq->length = strlen(extra) + 1; // 1: size of '\0'
             break;
-#ifdef DOT11_N_SUPPORT
         case SHOW_BA_INFO:
             getBaInfo(pAd, extra);
             wrq->length = strlen(extra) + 1; // 1: size of '\0'
             break;
-#endif // DOT11_N_SUPPORT //
 		case SHOW_DESC_INFO:
 			{
 				Show_DescInfo_Proc(pAd, NULL);
@@ -2174,6 +2235,14 @@
             wrq->length = strlen(extra) + 1; // 1: size of '\0'
             break;
         case RAIO_ON:
+#ifdef RT2870
+            if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
+            {
+                sprintf(extra, "Scanning\n");
+                wrq->length = strlen(extra) + 1; // 1: size of '\0'
+                break;
+            }
+#endif
             pAd->StaCfg.bSwRadio = TRUE;
             //if (pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
             {
@@ -2189,16 +2258,6 @@
             wrq->length = strlen(extra) + 1; // 1: size of '\0'
             break;
 
-
-#ifdef QOS_DLS_SUPPORT
-		case SHOW_DLS_ENTRY_INFO:
-			{
-				Set_DlsEntryInfo_Display_Proc(pAd, NULL);
-				wrq->length = 0; // 1: size of '\0'
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-
 		case SHOW_CFG_VALUE:
 			{
 				Status = RTMPShowCfgValue(pAd, wrq->pointer, extra);
@@ -2206,6 +2265,12 @@
 					wrq->length = strlen(extra) + 1; // 1: size of '\0'
 			}
 			break;
+#if !defined(RT2860) && !defined(RT30xx)
+		case SHOW_ADHOC_ENTRY_INFO:
+			Show_Adhoc_MacTable_Proc(pAd, extra);
+			wrq->length = strlen(extra) + 1; // 1: size of '\0'
+			break;
+#endif
         default:
             DBGPRINT(RT_DEBUG_TRACE, ("%s - unknow subcmd = %d\n", __func__, subcmd));
             break;
@@ -2312,9 +2377,7 @@
                 pAdapter->StaCfg.WepStatus = Ndis802_11WEPEnabled;
                 pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
                 pAdapter->StaCfg.PairCipher = Ndis802_11WEPEnabled;
-#ifdef WPA_SUPPLICANT_SUPPORT
                 pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
             }
             else if (param->value == IW_AUTH_CIPHER_TKIP)
             {
@@ -2356,22 +2419,16 @@
                 if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)
                 {
                     pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
-#ifdef WPA_SUPPLICANT_SUPPORT
                     pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
                 }
                 else if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
                 {
                     pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#ifdef WPA_SUPPLICANT_SUPPORT
                     pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
                 }
-#ifdef WPA_SUPPLICANT_SUPPORT
                 else
                     // WEP 1x
                     pAdapter->StaCfg.IEEE8021X = TRUE;
-#endif // WPA_SUPPLICANT_SUPPORT //
             }
             else if (param->value == 0)
             {
@@ -2457,6 +2514,7 @@
     IN  BOOLEAN         bGTK,
     IN  struct iw_encode_ext *ext)
 {
+#ifdef RT2860
 	RTMP_CLEAR_PSFLAG(pAdapter, fRTMP_PS_CAN_GO_SLEEP);
 	if (RTMP_TEST_PSFLAG(pAdapter, fRTMP_PS_SET_PCI_CLK_OFF_COMMAND))
 	{
@@ -2470,7 +2528,7 @@
 		RTMPusecDelay(6000);
 		pAdapter->bPCIclkOff = FALSE;
 	}
-
+#endif
     NdisZeroMemory(&pAdapter->SharedKey[BSS0][keyIdx], sizeof(CIPHER_KEY));
     pAdapter->SharedKey[BSS0][keyIdx].KeyLen = LEN_TKIP_EK;
     NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, ext->key, LEN_TKIP_EK);
@@ -2501,8 +2559,9 @@
     							  keyIdx,
     							  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
     							  &pAdapter->MacTab.Content[BSSID_WCID]);
-
+#ifdef RT2860
 	RTMP_SET_PSFLAG(pAdapter, fRTMP_PS_CAN_GO_SLEEP);
+#endif
 }
 
 int rt_ioctl_siwencodeext(struct net_device *dev,
@@ -2567,7 +2626,7 @@
 
                 NdisZeroMemory(pAdapter->SharedKey[BSS0][keyIdx].Key,  16);
 			    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, ext->key, ext->key_len);
-
+#ifndef RT30xx
 				if (pAdapter->StaCfg.GroupCipher == Ndis802_11GroupWEP40Enabled ||
 					pAdapter->StaCfg.GroupCipher == Ndis802_11GroupWEP104Enabled)
 				{
@@ -2582,6 +2641,7 @@
     				// Indicate Connected for GUI
     				pAdapter->IndicateMediaState = NdisMediaStateConnected;
 				}
+#endif
     			break;
             case IW_ENCODE_ALG_TKIP:
                 DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_TKIP - keyIdx = %d, ext->key_len = %d\n", __func__, keyIdx, ext->key_len));
@@ -2752,7 +2812,6 @@
 		return 0;
 	}
 
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
 #ifdef SIOCSIWGENIE
 	if (pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
 	{
@@ -2764,7 +2823,6 @@
 	}
 	else
 #endif // SIOCSIWGENIE //
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
 	{
 		UCHAR RSNIe = IE_WPA;
 
@@ -2895,15 +2953,13 @@
 			DBGPRINT(RT_DEBUG_TRACE, ("this_char=%s, value=%s\n", this_char, value));
 			if (sscanf(this_char, "%d", &(bbpId)) == 1)
 			{
+#ifndef RT30xx
 				if (bbpId <= 136)
+#endif // RT30xx //
+#ifdef RT30xx
+				if (bbpId <= 138)  // edit by johnli, RF power sequence setup, add BBP R138 for ADC dynamic on/off control
+#endif // RT30xx //
 				{
-#ifdef RALINK_ATE
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					else
-#endif // RALINK_ATE //
 					{
 					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
 					}
@@ -2927,17 +2983,13 @@
 		{ //Write
 			if ((sscanf(this_char, "%d", &(bbpId)) == 1) && (sscanf(value, "%x", &(bbpValue)) == 1))
 			{
+#ifndef RT30xx
 				if (bbpId <= 136)
+#endif // RT30xx //
+#ifdef RT30xx
+				if (bbpId <= 138)  // edit by johnli, RF power sequence setup, add BBP R138 for ADC dynamic on/off control
+#endif // RT30xx //
 				{
-#ifdef RALINK_ATE
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, bbpId, bbpValue);
-						//Read it back for showing
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					else
-#endif // RALINK_ATE //
 					{
 					    RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, bbpId, bbpValue);
     					//Read it back for showing
@@ -2968,21 +3020,24 @@
 	{
 		memset(extra, 0x00, IW_PRIV_SIZE_MASK);
 		sprintf(extra, "\n");
+#ifndef RT30xx
 		for (bbpId = 0; bbpId <= 136; bbpId++)
+#endif // RT30xx //
+#ifdef RT30xx
+		for (bbpId = 0; bbpId <= 138; bbpId++)  // edit by johnli, RF power sequence setup, add BBP R138 for ADC dynamic on/off control
+#endif // RT30xx //
 		{
 		    if (strlen(extra) >= (IW_PRIV_SIZE_MASK - 10))
                 break;
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			}
-			else
-#endif // RALINK_ATE //
 			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
+#ifndef RT30xx
 			sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X    ", bbpId, bbpId*2, regBBP);
 			if (bbpId%5 == 4)
 				sprintf(extra+strlen(extra), "\n");
+#endif
+#ifdef RT30xx
+			sprintf(extra+strlen(extra), "%03d = %02X\n", bbpId, regBBP);  // edit by johnli, change display format
+#endif
 		}
 
         wrq->length = strlen(extra) + 1; // 1: size of '\0'
@@ -3022,9 +3077,7 @@
 		    (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM))
 			RTMPSetDesiredRates(pAd, -1);
 
-#ifdef DOT11_N_SUPPORT
 		SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
     }
     else
     {
@@ -3037,9 +3090,7 @@
             else
             {
                 pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-#ifdef DOT11_N_SUPPORT
                 SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
             }
             DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::(HtMcs=%d)\n",pAd->StaCfg.DesiredTransmitSetting.field.MCS));
         }
@@ -3087,13 +3138,11 @@
     else
         ht_setting.word = pAd->MacTab.Content[BSSID_WCID].HTPhyMode.word;
 
-#ifdef DOT11_N_SUPPORT
     if (ht_setting.field.MODE >= MODE_HTMIX)
     {
     	rate_index = 12 + ((UCHAR)ht_setting.field.BW *24) + ((UCHAR)ht_setting.field.ShortGI *48) + ((UCHAR)ht_setting.field.MCS);
     }
     else
-#endif // DOT11_N_SUPPORT //
     if (ht_setting.field.MODE == MODE_OFDM)
     	rate_index = (UCHAR)(ht_setting.field.MCS) + 4;
     else if (ht_setting.field.MODE == MODE_CCK)
@@ -3184,11 +3233,7 @@
 static const iw_handler rt_priv_handlers[] = {
 	(iw_handler) NULL, /* + 0x00 */
 	(iw_handler) NULL, /* + 0x01 */
-#ifndef CONFIG_AP_SUPPORT
 	(iw_handler) rt_ioctl_setparam, /* + 0x02 */
-#else
-	(iw_handler) NULL, /* + 0x02 */
-#endif // CONFIG_AP_SUPPORT //
 #ifdef DBG
 	(iw_handler) rt_private_ioctl_bbp, /* + 0x03 */
 #else
@@ -3258,27 +3303,13 @@
     ULONG                               PowerTemp;
     BOOLEAN                             RadioState;
     BOOLEAN                             StateMachineTouched = FALSE;
-#ifdef DOT11_N_SUPPORT
 	OID_SET_HT_PHYMODE					HT_PhyMode;	//11n ,kathy
-#endif // DOT11_N_SUPPORT //
-#ifdef WPA_SUPPLICANT_SUPPORT
     PNDIS_802_11_PMKID                  pPmkId = NULL;
     BOOLEAN				                IEEE8021xState = FALSE;
     BOOLEAN				                IEEE8021x_required_keys = FALSE;
     UCHAR                               wpa_supplicant_enable = 0;
-#endif // WPA_SUPPLICANT_SUPPORT //
 
-#ifdef SNMP_SUPPORT
-	TX_RTY_CFG_STRUC			tx_rty_cfg;
-	ULONG						ShortRetryLimit, LongRetryLimit;
-	UCHAR						ctmp;
-#endif // SNMP_SUPPORT //
-
-
-#ifdef DOT11_N_SUPPORT
 	MaxPhyMode = PHY_11N_5G;
-#endif // DOT11_N_SUPPORT //
-
 
 	DBGPRINT(RT_DEBUG_TRACE, ("-->RTMPSetInformation(),	0x%08x\n", cmd&0x7FFF));
     switch(cmd & 0x7FFF) {
@@ -3298,21 +3329,12 @@
 				pAdapter->CommonCfg.PhyMode = 0xff;
 				// Build all corresponding channel information
 				RTMPSetPhyMode(pAdapter, TmpPhy);
-#ifdef DOT11_N_SUPPORT
 				SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
 				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_COUNTRY_REGION (A:%d  B/G:%d)\n", pAdapter->CommonCfg.CountryRegionForABand,
 				    pAdapter->CommonCfg.CountryRegion));
             }
             break;
         case OID_802_11_BSSID_LIST_SCAN:
- #ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
             Now = jiffies;
 			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_BSSID_LIST_SCAN, TxCnt = %d \n", pAdapter->RalinkCounters.LastOneSecTotalTxCount));
 
@@ -3414,13 +3436,6 @@
             }
             break;
         case OID_802_11_BSSID:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
             if (wrq->u.data.length != sizeof(NDIS_802_11_MAC_ADDRESS))
                 Status  = -EINVAL;
             else
@@ -3492,9 +3507,7 @@
 				if (PhyMode <= MaxPhyMode)
 				{
                 	RTMPSetPhyMode(pAdapter, PhyMode);
-#ifdef DOT11_N_SUPPORT
 					SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
 				}
                 DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_PHY_MODE (=%d)\n", PhyMode));
             }
@@ -3513,9 +3526,14 @@
                 {
                     // allow dynamic change of "USE OFDM rate or not" in ADHOC mode
                     // if setting changed, need to reset current TX rate as well as BEACON frame format
+#ifdef RT30xx
+                    pAdapter->CommonCfg.PhyMode = StaConfig.AdhocMode;
+#endif
                     if (pAdapter->StaCfg.BssType == BSS_ADHOC)
                     {
+#ifndef RT30xx
 						pAdapter->CommonCfg.PhyMode = StaConfig.AdhocMode;
+#endif
                     	RTMPSetPhyMode(pAdapter, PhyMode);
                         MlmeUpdateTxRates(pAdapter, FALSE, 0);
                         MakeIbssBeacon(pAdapter);           // re-build BEACON frame
@@ -3679,6 +3697,15 @@
             pAdapter->Counters8023.RxNoBuffer   = 0;
 			pAdapter->Counters8023.GoodReceives = 0;
 			pAdapter->Counters8023.RxNoBuffer   = 0;
+#ifdef RT2870
+			pAdapter->BulkOutComplete	= 0;
+			pAdapter->BulkOutCompleteOther= 0;
+			pAdapter->BulkOutCompleteCancel = 0;
+			pAdapter->BulkOutReq = 0;
+			pAdapter->BulkInReq= 0;
+			pAdapter->BulkInComplete = 0;
+			pAdapter->BulkInCompleteFail = 0;
+#endif // RT2870 //
             DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_RESET_COUNTERS \n"));
             break;
         case OID_802_11_RTS_THRESHOLD:
@@ -3763,10 +3790,10 @@
 					RTMPSetPhyMode(pAdapter, PHY_11A);
 				else
 					Status = -EINVAL;
-#ifdef DOT11_N_SUPPORT
+
 				if (Status == NDIS_STATUS_SUCCESS)
 					SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
+
                 DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_NETWORK_TYPE_IN_USE (=%d)\n",NetType));
 		    }
 			break;
@@ -3910,7 +3937,6 @@
                 pAdapter->bConfigChanged = TRUE;
             }
             break;
-#ifdef DOT11_N_SUPPORT
 		case RT_OID_802_11_SET_HT_PHYMODE:
 			if (wrq->u.data.length	!= sizeof(OID_SET_HT_PHYMODE))
 				Status = -EINVAL;
@@ -3929,7 +3955,6 @@
 				pAdapter->StaCfg.HTPhyMode.field.MCS, pAdapter->StaCfg.HTPhyMode.field.BW, pAdapter->StaCfg.HTPhyMode.field.ShortGI,
 				pAdapter->StaCfg.HTPhyMode.field.STBC));
 			break;
-#endif // DOT11_N_SUPPORT //
 		case RT_OID_802_11_SET_APSD_SETTING:
 			if (wrq->u.data.length != sizeof(ULONG))
 				Status = -EINVAL;
@@ -3970,62 +3995,7 @@
 				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_APSD_PSM (bAPSDForcePowerSave:%d)\n",	pAdapter->CommonCfg.bAPSDForcePowerSave));
 			}
 			break;
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_SET_DLS:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				BOOLEAN	oldvalue = pAdapter->CommonCfg.bDLSCapable;
-				Status = copy_from_user(&pAdapter->CommonCfg.bDLSCapable, wrq->u.data.pointer, wrq->u.data.length);
-				if (oldvalue &&	!pAdapter->CommonCfg.bDLSCapable)
-				{
-					int	i;
-					// tear	down local dls table entry
-					for	(i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-					{
-						if (pAdapter->StaCfg.DLSEntry[i].Valid && (pAdapter->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-						{
-							pAdapter->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-							pAdapter->StaCfg.DLSEntry[i].Valid	= FALSE;
-							RTMPSendDLSTearDownFrame(pAdapter, pAdapter->StaCfg.DLSEntry[i].MacAddr);
-						}
-					}
 
-					// tear	down peer dls table	entry
-					for	(i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-					{
-						if (pAdapter->StaCfg.DLSEntry[i].Valid && (pAdapter->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-						{
-							pAdapter->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-							pAdapter->StaCfg.DLSEntry[i].Valid	= FALSE;
-							RTMPSendDLSTearDownFrame(pAdapter, pAdapter->StaCfg.DLSEntry[i].MacAddr);
-						}
-					}
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE,("Set::RT_OID_802_11_SET_DLS (=%d)\n", pAdapter->CommonCfg.bDLSCapable));
-			}
-			break;
-
-		case RT_OID_802_11_SET_DLS_PARAM:
-			if (wrq->u.data.length	!= sizeof(RT_802_11_DLS_UI))
-				Status = -EINVAL;
-			else
-			{
-				RT_802_11_DLS	Dls;
-
-				NdisZeroMemory(&Dls, sizeof(RT_802_11_DLS));
-				RTMPMoveMemory(&Dls, wrq->u.data.pointer, sizeof(RT_802_11_DLS_UI));
-				MlmeEnqueue(pAdapter,
-							MLME_CNTL_STATE_MACHINE,
-							RT_OID_802_11_SET_DLS_PARAM,
-							sizeof(RT_802_11_DLS),
-							&Dls);
-				DBGPRINT(RT_DEBUG_TRACE,("Set::RT_OID_802_11_SET_DLS_PARAM \n"));
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
 		case RT_OID_802_11_SET_WMM:
 			if (wrq->u.data.length	!= sizeof(BOOLEAN))
 				Status = -EINVAL;
@@ -4037,13 +4007,6 @@
 			break;
 
 		case OID_802_11_DISASSOCIATE:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
 			//
 			// Set NdisRadioStateOff to	TRUE, instead of called	MlmeRadioOff.
 			// Later on, NDIS_802_11_BSSID_LIST_EX->NumberOfItems should be	0
@@ -4074,8 +4037,6 @@
 				StateMachineTouched	= TRUE;
 			}
 			break;
-
-#ifdef DOT11_N_SUPPORT
 		case RT_OID_802_11_SET_IMME_BA_CAP:
 				if (wrq->u.data.length != sizeof(OID_BACAP_STRUC))
 					Status = -EINVAL;
@@ -4230,8 +4191,6 @@
 				}
             }
             break;
-#endif // DOT11_N_SUPPORT //
-
         // For WPA_SUPPLICANT to set static wep key
     	case OID_802_11_ADD_WEP:
     	    pWepKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
@@ -4285,19 +4244,21 @@
                     // Default key for tx (shared key)
                     if (pWepKey->KeyIndex & 0x80000000)
                     {
-#ifdef WPA_SUPPLICANT_SUPPORT
                         // set key material and key length
                         NdisZeroMemory(pAdapter->StaCfg.DesireSharedKey[KeyIdx].Key, 16);
                         pAdapter->StaCfg.DesireSharedKey[KeyIdx].KeyLen = (UCHAR) pWepKey->KeyLength;
                         NdisMoveMemory(pAdapter->StaCfg.DesireSharedKey[KeyIdx].Key, &pWepKey->KeyMaterial, pWepKey->KeyLength);
                         pAdapter->StaCfg.DesireSharedKeyId = KeyIdx;
                         pAdapter->StaCfg.DesireSharedKey[KeyIdx].CipherAlg = CipherAlg;
-#endif // WPA_SUPPLICANT_SUPPORT //
                         pAdapter->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
                     }
-
-#ifdef WPA_SUPPLICANT_SUPPORT
+#ifndef RT30xx
+#ifdef RT2860
 					if ((pAdapter->StaCfg.WpaSupplicantUP != 0) &&
+#endif
+#ifdef RT2870
+					if ((pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE) &&
+#endif
 						(pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA))
 					{
 						Key = pWepKey->KeyMaterial;
@@ -4314,7 +4275,10 @@
         				pAdapter->IndicateMediaState = NdisMediaStateConnected;
 					}
                     else if (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED)
-#endif // WPA_SUPPLICANT_SUPPORT
+#endif
+#ifdef RT30xx
+                    if (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED)
+#endif
                     {
                         Key = pAdapter->SharedKey[BSS0][KeyIdx].Key;
 
@@ -4335,7 +4299,6 @@
             }
             kfree(pWepKey);
             break;
-#ifdef WPA_SUPPLICANT_SUPPORT
 	    case OID_SET_COUNTERMEASURES:
             if (wrq->u.data.length != sizeof(int))
                 Status  = -EINVAL;
@@ -4469,95 +4432,6 @@
 			if(pPmkId)
 				kfree(pPmkId);
 	        break;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-
-#ifdef SNMP_SUPPORT
-		case OID_802_11_SHORTRETRYLIMIT:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&ShortRetryLimit, wrq->u.data.pointer, wrq->u.data.length);
-				RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-				tx_rty_cfg.field.ShortRtyLimit = ShortRetryLimit;
-				RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SHORTRETRYLIMIT (tx_rty_cfg.field.ShortRetryLimit=%d, ShortRetryLimit=%ld)\n", tx_rty_cfg.field.ShortRtyLimit, ShortRetryLimit));
-			}
-			break;
-
-		case OID_802_11_LONGRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_LONGRETRYLIMIT \n"));
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&LongRetryLimit, wrq->u.data.pointer, wrq->u.data.length);
-				RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-				tx_rty_cfg.field.LongRtyLimit = LongRetryLimit;
-				RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_LONGRETRYLIMIT (tx_rty_cfg.field.LongRetryLimit= %d,LongRetryLimit=%ld)\n", tx_rty_cfg.field.LongRtyLimit, LongRetryLimit));
-			}
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYVALUE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYVALUE\n"));
-			pKey = kmalloc(wrq->u.data.length, GFP_KERNEL);
-			Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-			//pKey = &WepKey;
-
-			if ( pKey->Length != wrq->u.data.length)
-			{
-				Status = -EINVAL;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYVALUE, Failed!!\n"));
-			}
-			KeyIdx = pKey->KeyIndex & 0x0fffffff;
-			DBGPRINT(RT_DEBUG_TRACE,("pKey->KeyIndex =%d, pKey->KeyLength=%d\n", pKey->KeyIndex, pKey->KeyLength));
-
-			// it is a shared key
-			if (KeyIdx > 4)
-				Status = -EINVAL;
-			else
-			{
-				pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen = (UCHAR) pKey->KeyLength;
-				NdisMoveMemory(&pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key, &pKey->KeyMaterial, pKey->KeyLength);
-				if (pKey->KeyIndex & 0x80000000)
-				{
-					// Default key for tx (shared key)
-					pAdapter->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-				}
-				//RestartAPIsRequired = TRUE;
-			}
-			break;
-
-
-		case OID_802_11_WEPDEFAULTKEYID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYID \n"));
-
-			if (wrq->u.data.length != sizeof(UCHAR))
-				Status = -EINVAL;
-			else
-				Status = copy_from_user(&pAdapter->StaCfg.DefaultKeyId, wrq->u.data.pointer, wrq->u.data.length);
-
-			break;
-
-
-		case OID_802_11_CURRENTCHANNEL:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_CURRENTCHANNEL \n"));
-			if (wrq->u.data.length != sizeof(UCHAR))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&ctmp, wrq->u.data.pointer, wrq->u.data.length);
-				sprintf(&ctmp,"%d", ctmp);
-				Set_Channel_Proc(pAdapter, &ctmp);
-			}
-			break;
-#endif
-
-
-
         default:
             DBGPRINT(RT_DEBUG_TRACE, ("Set::unknown IOCTL's subcmd = 0x%08x\n", cmd));
             Status = -EOPNOTSUPP;
@@ -4599,16 +4473,6 @@
 	UCHAR	driverVersion[8];
     OID_SET_HT_PHYMODE			        *pHTPhyMode = NULL;
 
-
-#ifdef SNMP_SUPPORT
-	//for snmp, kathy
-	DefaultKeyIdxValue			*pKeyIdxValue;
-	INT							valueLen;
-	TX_RTY_CFG_STRUC			tx_rty_cfg;
-	ULONG						ShortRetryLimit, LongRetryLimit;
-	UCHAR						tmp[64];
-#endif //SNMP
-
     switch(cmd)
     {
         case RT_OID_DEVICE_NAME:
@@ -4625,16 +4489,6 @@
 				Status = -EFAULT;
             }
             break;
-#ifdef RALINK_ATE
-		case RT_QUERY_ATE_TXDONE_COUNT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_QUERY_ATE_TXDONE_COUNT \n"));
-			wrq->u.data.length = sizeof(UINT32);
-			if (copy_to_user(wrq->u.data.pointer, &pAdapter->ate.TxDoneCount, wrq->u.data.length))
-			{
-				Status = -EFAULT;
-			}
-			break;
-#endif // RALINK_ATE //
         case OID_802_11_BSSID_LIST:
             if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
             {
@@ -4776,14 +4630,6 @@
             Status = copy_to_user(wrq->u.data.pointer, &MediaState, wrq->u.data.length);
             break;
         case OID_802_11_BSSID:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				Status = NDIS_STATUS_RESOURCES;
-				break;
-			}
-#endif // RALINK_ATE //
             if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
             {
                 Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Bssid, sizeof(NDIS_802_11_MAC_ADDRESS));
@@ -5121,7 +4967,6 @@
 			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bWmmCapable, wrq->u.data.length);
 			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_WMM (=%d)\n",	pAdapter->CommonCfg.bWmmCapable));
 			break;
-#ifdef WPA_SUPPLICANT_SUPPORT
         case RT_OID_NEW_DRIVER:
             {
                 UCHAR enabled = 1;
@@ -5135,8 +4980,6 @@
 	        Status = copy_to_user(wrq->u.data.pointer, &pAdapter->StaCfg.WpaSupplicantUP, wrq->u.data.length);
             DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_WPA_SUPPLICANT_SUPPORT (=%d)\n", pAdapter->StaCfg.WpaSupplicantUP));
 	        break;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
         case RT_OID_DRIVER_DEVICE_NAME:
             DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_DRIVER_DEVICE_NAME \n"));
 			wrq->u.data.length = 16;
@@ -5211,154 +5054,20 @@
         case RT_OID_QUERY_MULTIPLE_CARD_SUPPORT:
 			wrq->u.data.length = sizeof(UCHAR);
             i = 0;
-#ifdef MULTIPLE_CARD_SUPPORT
-            i = 1;
-#endif // MULTIPLE_CARD_SUPPORT //
 			if (copy_to_user(wrq->u.data.pointer, &i, wrq->u.data.length))
             {
 				Status = -EFAULT;
             }
             DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_QUERY_MULTIPLE_CARD_SUPPORT(=%d) \n", i));
             break;
-#ifdef SNMP_SUPPORT
-		case RT_OID_802_11_MAC_ADDRESS:
-            wrq->u.data.length = MAC_ADDR_LEN;
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTUREROUI:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTUREROUI \n"));
-			wrq->u.data.length = ManufacturerOUI_LEN;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTURERNAME:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTURERNAME \n"));
-			wrq->u.data.length = strlen(ManufacturerNAME);
-			Status = copy_to_user(wrq->u.data.pointer, ManufacturerNAME, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_RESOURCETYPEIDNAME:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_RESOURCETYPEIDNAME \n"));
-			wrq->u.data.length = strlen(ResourceTypeIdName);
-			Status = copy_to_user(wrq->u.data.pointer, ResourceTypeIdName, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED \n"));
-			ulInfo = 1; // 1 is support wep else 2 is not support.
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_POWERMANAGEMENTMODE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_POWERMANAGEMENTMODE \n"));
-			if (pAdapter->StaCfg.Psm == PSMP_ACTION)
-				ulInfo = 1; // 1 is power active else 2 is power save.
-			else
-				ulInfo = 2;
-
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYVALUE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_WEPDEFAULTKEYVALUE \n"));
-			//KeyIdxValue.KeyIdx = pAd->PortCfg.MBSSID[pAd->IoctlIF].DefaultKeyId;
-			pKeyIdxValue = wrq->u.data.pointer;
-			DBGPRINT(RT_DEBUG_TRACE,("KeyIdxValue.KeyIdx = %d, \n",pKeyIdxValue->KeyIdx));
-			valueLen = pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen;
-			NdisMoveMemory(pKeyIdxValue->Value,
-						   &pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key,
-						   valueLen);
-			pKeyIdxValue->Value[valueLen]='\0';
-
-			wrq->u.data.length = sizeof(DefaultKeyIdxValue);
-
-			Status = copy_to_user(wrq->u.data.pointer, pKeyIdxValue, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE,("DefaultKeyId = %d, total len = %d, str len=%d, KeyValue= %02x %02x %02x %02x \n", pAdapter->StaCfg.DefaultKeyId, wrq->u.data.length, pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen,
-			pAdapter->SharedKey[BSS0][0].Key[0],
-			pAdapter->SharedKey[BSS0][1].Key[0],
-			pAdapter->SharedKey[BSS0][2].Key[0],
-			pAdapter->SharedKey[BSS0][3].Key[0]));
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_WEPDEFAULTKEYID \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->StaCfg.DefaultKeyId, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("DefaultKeyId =%d \n", pAdapter->StaCfg.DefaultKeyId));
-			break;
-
-		case RT_OID_802_11_WEPKEYMAPPINGLENGTH:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_WEPKEYMAPPINGLENGTH \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer,
-									&pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen,
-									wrq->u.data.length);
-			break;
-
-		case OID_802_11_SHORTRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_SHORTRETRYLIMIT \n"));
-			wrq->u.data.length = sizeof(ULONG);
-			RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-			ShortRetryLimit = tx_rty_cfg.field.ShortRtyLimit;
-			DBGPRINT(RT_DEBUG_TRACE, ("ShortRetryLimit =%ld,  tx_rty_cfg.field.ShortRetryLimit=%d\n", ShortRetryLimit, tx_rty_cfg.field.ShortRtyLimit));
-			Status = copy_to_user(wrq->u.data.pointer, &ShortRetryLimit, wrq->u.data.length);
-			break;
-
-		case OID_802_11_LONGRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_LONGRETRYLIMIT \n"));
-			wrq->u.data.length = sizeof(ULONG);
-			RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-			LongRetryLimit = tx_rty_cfg.field.LongRtyLimit;
-			DBGPRINT(RT_DEBUG_TRACE, ("LongRetryLimit =%ld,  tx_rty_cfg.field.LongRtyLimit=%d\n", LongRetryLimit, tx_rty_cfg.field.LongRtyLimit));
-			Status = copy_to_user(wrq->u.data.pointer, &LongRetryLimit, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_PRODUCTID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PRODUCTID \n"));
-
-			{
-
-				USHORT  device_id;
-				if (((POS_COOKIE)pAdapter->OS_Cookie)->pci_dev != NULL)
-			    	pci_read_config_word(((POS_COOKIE)pAdapter->OS_Cookie)->pci_dev, PCI_DEVICE_ID, &device_id);
-				else
-					DBGPRINT(RT_DEBUG_TRACE, (" pci_dev = NULL\n"));
-				sprintf(tmp, "%04x %04x\n", NIC_PCI_VENDOR_ID, device_id);
-			}
-			wrq->u.data.length = strlen(tmp);
-			Status = copy_to_user(wrq->u.data.pointer, tmp, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTUREID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTUREID \n"));
-			wrq->u.data.length = strlen(ManufacturerNAME);
-			Status = copy_to_user(wrq->u.data.pointer, ManufacturerNAME, wrq->u.data.length);
-			break;
-
-		case OID_802_11_CURRENTCHANNEL:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CURRENTCHANNEL \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			DBGPRINT(RT_DEBUG_TRACE, ("sizeof UCHAR=%d, channel=%d \n", sizeof(UCHAR), pAdapter->CommonCfg.Channel));
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Channel, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-#endif //SNMP_SUPPORT
 
 		case OID_802_11_BUILD_CHANNEL_EX:
 			{
 				UCHAR value;
 				DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BUILD_CHANNEL_EX \n"));
 				wrq->u.data.length = sizeof(UCHAR);
-#ifdef EXT_BUILD_CHANNEL_LIST
-				DBGPRINT(RT_DEBUG_TRACE, ("Support EXT_BUILD_CHANNEL_LIST.\n"));
-				value = 1;
-#else
 				DBGPRINT(RT_DEBUG_TRACE, ("Doesn't support EXT_BUILD_CHANNEL_LIST.\n"));
 				value = 0;
-#endif // EXT_BUILD_CHANNEL_LIST //
 				Status = copy_to_user(wrq->u.data.pointer, &value, 1);
 				DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
 			}
@@ -5409,35 +5118,6 @@
 			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
 			break;
 
-
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_QUERY_DLS:
-			wrq->u.data.length = sizeof(BOOLEAN);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bDLSCapable, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_DLS(=%d)\n", pAdapter->CommonCfg.bDLSCapable));
-			break;
-
-		case RT_OID_802_11_QUERY_DLS_PARAM:
-			{
-				PRT_802_11_DLS_INFO	pDlsInfo = kmalloc(sizeof(RT_802_11_DLS_INFO), GFP_ATOMIC);
-				if (pDlsInfo == NULL)
-					break;
-
-				for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-				{
-					RTMPMoveMemory(&pDlsInfo->Entry[i], &pAdapter->StaCfg.DLSEntry[i], sizeof(RT_802_11_DLS_UI));
-				}
-
-				pDlsInfo->num = MAX_NUM_OF_DLS_ENTRY;
-				wrq->u.data.length = sizeof(RT_802_11_DLS_INFO);
-				Status = copy_to_user(wrq->u.data.pointer, pDlsInfo, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_DLS_PARAM\n"));
-
-				if (pDlsInfo)
-					kfree(pDlsInfo);
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
         default:
             DBGPRINT(RT_DEBUG_TRACE, ("Query::unknown IOCTL's subcmd = 0x%08x\n", cmd));
             Status = -EOPNOTSUPP;
@@ -5480,14 +5160,6 @@
     //check if the interface is down
     if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
     {
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	    if (wrq->u.data.pointer == NULL)
-	    {
-		    return Status;
-	    }
-
-	    if (strstr(wrq->u.data.pointer, "OpMode") == NULL)
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
         {
             DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
 		    return -ENETDOWN;
@@ -5501,15 +5173,6 @@
 
 	switch(cmd)
 	{
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-		case RTPRIV_IOCTL_ATE:
-			{
-				RtmpDoAte(pAd, wrq);
-			}
-			break;
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
         case SIOCGIFHWADDR:
 			DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCGIFHWADDR\n"));
 			memcpy(wrq->u.name, pAd->CurrentAddress, ETH_ALEN);
@@ -5640,6 +5303,9 @@
 			Status = -EOPNOTSUPP;
 			break;
 		case RT_PRIV_IOCTL:
+#ifdef RT30xx
+        case RT_PRIV_IOCTL_EXT:
+#endif
 			subcmd = wrq->u.data.flags;
 			if( subcmd & OID_GET_SET_TOGGLE)
 				Status = RTMPSetInformation(pAd, rq, subcmd);
@@ -5671,6 +5337,11 @@
 		case RTPRIV_IOCTL_E2P:
 			RTMPIoctlE2PROM(pAd, wrq);
 			break;
+#ifdef RT30xx
+		case RTPRIV_IOCTL_RF:
+			RTMPIoctlRF(pAd, wrq);
+			break;
+#endif // RT30xx //
 #endif // DBG //
         case SIOCETHTOOL:
                 break;
@@ -5766,6 +5437,9 @@
 	bWmmCapable = simple_strtol(arg, 0, 10);
 
 	if ((bWmmCapable == 1)
+#ifdef RT2870
+		&& (pAd->NumberOfPipes >= 5)
+#endif // RT2870 //
 		)
 		pAd->CommonCfg.bWmmCapable = TRUE;
 	else if (bWmmCapable == 0)
@@ -5873,19 +5547,14 @@
 		DBGPRINT(RT_DEBUG_TRACE, ("fOP_STATUS_MEDIA_STATE_CONNECTED \n"));
         if (pAdapter->CommonCfg.CentralChannel == 0)
         {
-#ifdef DOT11_N_SUPPORT
             if (pAdapter->CommonCfg.PhyMode == PHY_11AN_MIXED)
                 pAdapter->CommonCfg.CentralChannel = 36;
             else
-#endif // DOT11_N_SUPPORT //
                 pAdapter->CommonCfg.CentralChannel = 6;
         }
-#ifdef DOT11_N_SUPPORT
         else
             N_ChannelCheck(pAdapter);
-#endif // DOT11_N_SUPPORT //
 
-#ifdef DOT11_N_SUPPORT
 	if (pAdapter->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
             pAdapter->CommonCfg.RegTransmitSetting.field.BW == BW_40 &&
             pAdapter->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_ABOVE)
@@ -5936,7 +5605,6 @@
                                        pAdapter->CommonCfg.CentralChannel));
 		}
 		else
-#endif // DOT11_N_SUPPORT //
 		{
 			// 20MHz
 			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
@@ -5997,12 +5665,10 @@
         pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
     else if ((strcmp(arg, "WPA2PSK") == 0) || (strcmp(arg, "wpa2psk") == 0))
         pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-#ifdef WPA_SUPPLICANT_SUPPORT
     else if ((strcmp(arg, "WPA") == 0) || (strcmp(arg, "wpa") == 0))
         pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
     else if ((strcmp(arg, "WPA2") == 0) || (strcmp(arg, "wpa2") == 0))
         pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#endif // WPA_SUPPLICANT_SUPPORT //
     else
         return FALSE;
 
@@ -6544,7 +6210,6 @@
     return TRUE;
 }
 
-#ifdef WPA_SUPPLICANT_SUPPORT
 /*
     ==========================================================================
     Description:
@@ -6575,7 +6240,6 @@
 
     return TRUE;
 }
-#endif // WPA_SUPPLICANT_SUPPORT //
 
 #ifdef DBG
 /*
@@ -6608,7 +6272,9 @@
 	UCHAR				temp[16], temp2[16];
 	UINT32				macValue = 0;
 	INT					Status;
-
+#ifdef RT30xx
+	BOOLEAN				bIsPrintAllMAC = FALSE;
+#endif
 
 	memset(msg, 0x00, 1024);
 	if (wrq->u.data.length > 1) //No parameters.
@@ -6659,7 +6325,13 @@
 					sprintf(msg+strlen(msg), "[0x%08lX]:%08X  ", macAddr , macValue);
 				}
 				else
+#ifndef RT30xx
 				{//Invalid parametes, so default printk all bbp
+#endif
+#ifdef RT30xx
+				{//Invalid parametes, so default printk all mac
+					bIsPrintAllMAC = TRUE;
+#endif
 					goto next;
 				}
 			}
@@ -6730,13 +6402,6 @@
                         UCHAR R66;
                         pAdapter->BbpTuning.bEnable = FALSE;
                         R66 = 0x26 + GET_LNA_GAIN(pAdapter);
-#ifdef RALINK_ATE
-						if (ATE_ON(pAdapter))
-						{
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R66, (0x26 + GET_LNA_GAIN(pAdapter)));
-						}
-						else
-#endif // RALINK_ATE //
 						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R66, (0x26 + GET_LNA_GAIN(pAdapter)));
                         DBGPRINT(RT_DEBUG_TRACE,("turn off R17 tuning, restore to 0x%02x\n", R66));
                     }
@@ -6750,7 +6415,52 @@
 			}
 		}
 	}
+#ifdef RT30xx
+	else
+		bIsPrintAllMAC = TRUE;
+#endif
 next:
+#ifdef RT30xx
+	if (bIsPrintAllMAC)
+	{
+		struct file		*file_w;
+		PCHAR			fileName = "MacDump.txt";
+		mm_segment_t	orig_fs;
+
+		orig_fs = get_fs();
+		set_fs(KERNEL_DS);
+
+		// open file
+		file_w = filp_open(fileName, O_WRONLY|O_CREAT, 0);
+		if (IS_ERR(file_w))
+		{
+			DBGPRINT(RT_DEBUG_TRACE, ("-->2) %s: Error %ld opening %s\n", __func__, -PTR_ERR(file_w), fileName));
+		}
+		else
+		{
+			if (file_w->f_op && file_w->f_op->write)
+			{
+				file_w->f_pos = 0;
+				macAddr = 0x1000;
+
+				while (macAddr <= 0x1800)
+				{
+					RTMP_IO_READ32(pAdapter, macAddr, &macValue);
+					sprintf(msg, "%08lx = %08X\n", macAddr, macValue);
+
+					// write data to file
+					file_w->f_op->write(file_w, msg, strlen(msg), &file_w->f_pos);
+
+					printk("%s", msg);
+					macAddr += 4;
+				}
+				sprintf(msg, "\nDump all MAC values to %s\n", fileName);
+			}
+			filp_close(file_w, NULL);
+		}
+		set_fs(orig_fs);
+	}
+#endif /* RT30xx */
 	if(strlen(msg) == 1)
 		sprintf(msg+strlen(msg), "===>Error command format!");
 
@@ -6791,7 +6501,9 @@
 	UCHAR				temp[16], temp2[16];
 	USHORT				eepValue;
 	int					Status;
-
+#ifdef RT30xx
+	BOOLEAN				bIsPrintAllE2P = FALSE;
+#endif
 
 	memset(msg, 0x00, 1024);
 	if (wrq->u.data.length > 1) //No parameters.
@@ -6845,6 +6557,9 @@
 				}
 				else
 				{//Invalid parametes, so default printk all bbp
+#ifdef RT30xx
+					bIsPrintAllE2P = TRUE;
+#endif
 					goto next;
 				}
 			}
@@ -6903,7 +6618,52 @@
 			sprintf(msg+strlen(msg), "[0x%02X]:%02X  ", eepAddr, eepValue);
 		}
 	}
+#ifdef RT30xx
+	else
+		bIsPrintAllE2P = TRUE;
+#endif
 next:
+#ifdef RT30xx
+	if (bIsPrintAllE2P)
+	{
+		struct file		*file_w;
+		PCHAR			fileName = "EEPROMDump.txt";
+		mm_segment_t	orig_fs;
+
+		orig_fs = get_fs();
+		set_fs(KERNEL_DS);
+
+		// open file
+		file_w = filp_open(fileName, O_WRONLY|O_CREAT, 0);
+		if (IS_ERR(file_w))
+		{
+			DBGPRINT(RT_DEBUG_TRACE, ("-->2) %s: Error %ld opening %s\n", __func__, -PTR_ERR(file_w), fileName));
+		}
+		else
+		{
+			if (file_w->f_op && file_w->f_op->write)
+			{
+				file_w->f_pos = 0;
+				eepAddr = 0x00;
+
+				while (eepAddr <= 0xFE)
+				{
+					RT28xx_EEPROM_READ16(pAdapter, eepAddr, eepValue);
+					sprintf(msg, "%08x = %04x\n", eepAddr , eepValue);
+
+					// write data to file
+					file_w->f_op->write(file_w, msg, strlen(msg), &file_w->f_pos);
+
+					printk("%s", msg);
+					eepAddr += 2;
+				}
+				sprintf(msg, "\nDump all EEPROM values to %s\n", fileName);
+			}
+			filp_close(file_w, NULL);
+		}
+		set_fs(orig_fs);
+	}
+#endif /* RT30xx */
 	if(strlen(msg) == 1)
 		sprintf(msg+strlen(msg), "===>Error command format!");
 
@@ -6914,6 +6674,154 @@
 
 	DBGPRINT(RT_DEBUG_TRACE, ("<==RTMPIoctlE2PROM\n"));
 }
+#ifdef RT30xx
+/*
+    ==========================================================================
+    Description:
+        Read / Write RF register
+Arguments:
+    pAdapter                    Pointer to our adapter
+    wrq                         Pointer to the ioctl argument
+
+    Return Value:
+        None
+
+    Note:
+        Usage:
+               1.) iwpriv ra0 rf                ==> read all RF registers
+               2.) iwpriv ra0 rf 1              ==> read RF where RegID=1
+               3.) iwpriv ra0 rf 1=10		    ==> write RF R1=0x10
+    ==========================================================================
+*/
+VOID RTMPIoctlRF(
+	IN	PRTMP_ADAPTER	pAdapter,
+	IN	struct iwreq	*wrq)
+{
+	CHAR				*this_char;
+	CHAR				*value;
+	UCHAR				regRF = 0;
+	CHAR				msg[2048];
+	CHAR				arg[255];
+	INT					rfId;
+	LONG				rfValue;
+	int					Status;
+	BOOLEAN				bIsPrintAllRF = FALSE;
+
+
+	memset(msg, 0x00, 2048);
+	if (wrq->u.data.length > 1) //No parameters.
+	{
+	    Status = copy_from_user(arg, wrq->u.data.pointer, (wrq->u.data.length > 255) ? 255 : wrq->u.data.length);
+		sprintf(msg, "\n");
+
+	    //Parsing Read or Write
+		this_char = arg;
+		if (!*this_char)
+			goto next;
+
+		if ((value = strchr(this_char, '=')) != NULL)
+			*value++ = 0;
+
+		if (!value || !*value)
+		{ //Read
+			if (sscanf(this_char, "%d", &(rfId)) == 1)
+			{
+				if (rfId <= 31)
+				{
+					// In RT2860 ATE mode, we do not load 8051 firmware.
+                                            //We must access RF directly.
+                    // For RT2870 ATE mode, ATE_RF_IO_WRITE8(/READ8)_BY_REG_ID are redefined.
+					// according to Andy, Gary, David require.
+					// the command rf shall read rf register directly for dubug.
+					// BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
+					RT30xxReadRFRegister(pAdapter, rfId, &regRF);
+
+					sprintf(msg+strlen(msg), "R%02d[0x%02x]:%02X  ", rfId, rfId*2, regRF);
+				}
+				else
+				{//Invalid parametes, so default printk all RF
+					bIsPrintAllRF = TRUE;
+					goto next;
+				}
+			}
+			else
+			{ //Invalid parametes, so default printk all RF
+				bIsPrintAllRF = TRUE;
+				goto next;
+			}
+		}
+		else
+		{ //Write
+			if ((sscanf(this_char, "%d", &(rfId)) == 1) && (sscanf(value, "%lx", &(rfValue)) == 1))
+			{
+				if (rfId <= 31)
+				{
+					// In RT2860 ATE mode, we do not load 8051 firmware.
+					// We should access RF registers directly.
+                    // For RT2870 ATE mode, ATE_RF_IO_WRITE8/READ8_BY_REG_ID are redefined.
+						{
+							// according to Andy, Gary, David require.
+							// the command RF shall read/write RF register directly for dubug.
+							//BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
+					                //BBP_IO_WRITE8_BY_REG_ID(pAdapter, (UCHAR)bbpId,(UCHAR) bbpValue);
+							RT30xxReadRFRegister(pAdapter, rfId, &regRF);
+							RT30xxWriteRFRegister(pAdapter, (UCHAR)rfId,(UCHAR) rfValue);
+					                //Read it back for showing
+							//BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
+							RT30xxReadRFRegister(pAdapter, rfId, &regRF);
+					                sprintf(msg+strlen(msg), "R%02d[0x%02X]:%02X\n", rfId, rfId*2, regRF);
+				                }
+				}
+				else
+				{//Invalid parametes, so default printk all RF
+					bIsPrintAllRF = TRUE;
+				}
+			}
+			else
+			{ //Invalid parametes, so default printk all RF
+				bIsPrintAllRF = TRUE;
+			}
+		}
+	}
+	else
+		bIsPrintAllRF = TRUE;
+next:
+	if (bIsPrintAllRF)
+	{
+		memset(msg, 0x00, 2048);
+		sprintf(msg, "\n");
+		for (rfId = 0; rfId <= 31; rfId++)
+		{
+			// according to Andy, Gary, David require.
+			// the command RF shall read/write RF register directly for dubug.
+			RT30xxReadRFRegister(pAdapter, rfId, &regRF);
+			sprintf(msg+strlen(msg), "%03d = %02X\n", rfId, regRF);
+		}
+		// Copy the information into the user buffer
+		DBGPRINT(RT_DEBUG_TRACE, ("strlen(msg)=%d\n", (UINT32)strlen(msg)));
+		wrq->u.data.length = strlen(msg);
+		if (copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length))
+		{
+			DBGPRINT(RT_DEBUG_TRACE, ("%s: copy_to_user() fail\n", __func__));
+		}
+	}
+	else
+	{
+		if(strlen(msg) == 1)
+			sprintf(msg+strlen(msg), "===>Error command format!");
+
+		DBGPRINT(RT_DEBUG_TRACE, ("copy to user [msg=%s]\n", msg));
+		// Copy the information into the user buffer
+		DBGPRINT(RT_DEBUG_TRACE, ("strlen(msg) =%d\n", (UINT32)strlen(msg)));
+
+		// Copy the information into the user buffer
+		wrq->u.data.length = strlen(msg);
+		Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
+	}
+
+	DBGPRINT(RT_DEBUG_TRACE, ("<==RTMPIoctlRF\n\n"));
+}
+#endif // RT30xx //
 #endif // DBG //
 
 
@@ -6960,37 +6868,47 @@
 	return TRUE;
 }
 
-#ifdef EXT_BUILD_CHANNEL_LIST
-INT Set_Ieee80211dClientMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
+#if !defined(RT2860) && !defined(RT30xx)
+INT	Show_Adhoc_MacTable_Proc(
+	IN	PRTMP_ADAPTER	pAd,
+	IN	PCHAR			extra)
 {
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_None;
-    else if (simple_strtol(arg, 0, 10) == 1)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_Flexible;
-    else if (simple_strtol(arg, 0, 10) == 2)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_Strict;
-    else
-        return FALSE;
+	INT i;
 
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_Ieee802dMode_Proc::(IEEEE0211dMode=%d)\n", pAdapter->StaCfg.IEEE80211dClientMode));
-    return TRUE;
-}
-#endif // EXT_BUILD_CHANNEL_LIST //
+	sprintf(extra, "\n");
 
-#ifdef CARRIER_DETECTION_SUPPORT
-INT Set_CarrierDetect_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-    else
-        pAd->CommonCfg.CarrierDetect.Enable = TRUE;
+	sprintf(extra + strlen(extra), "HT Operating Mode : %d\n", pAd->CommonCfg.AddHTInfo.AddHtInfo2.OperaionMode);
 
-    DBGPRINT(RT_DEBUG_TRACE, ("IF Set_CarrierDetect_Proc::(CarrierDetect.Enable=%d)\n", pAd->CommonCfg.CarrierDetect.Enable));
+	sprintf(extra + strlen(extra), "\n%-19s%-4s%-4s%-7s%-7s%-7s%-10s%-6s%-6s%-6s%-6s\n",
+			"MAC", "AID", "BSS", "RSSI0", "RSSI1", "RSSI2", "PhMd", "BW", "MCS", "SGI", "STBC");
+
+	for (i=1; i<MAX_LEN_OF_MAC_TABLE; i++)
+	{
+		PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[i];
+
+		if (strlen(extra) > (IW_PRIV_SIZE_MASK - 30))
+		    break;
+		if ((pEntry->ValidAsCLI || pEntry->ValidAsApCli) && (pEntry->Sst == SST_ASSOC))
+		{
+			sprintf(extra + strlen(extra), "%02X:%02X:%02X:%02X:%02X:%02X  ",
+				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
+				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5]);
+			sprintf(extra + strlen(extra), "%-4d", (int)pEntry->Aid);
+			sprintf(extra + strlen(extra), "%-4d", (int)pEntry->apidx);
+			sprintf(extra + strlen(extra), "%-7d", pEntry->RssiSample.AvgRssi0);
+			sprintf(extra + strlen(extra), "%-7d", pEntry->RssiSample.AvgRssi1);
+			sprintf(extra + strlen(extra), "%-7d", pEntry->RssiSample.AvgRssi2);
+			sprintf(extra + strlen(extra), "%-10s", GetPhyMode(pEntry->HTPhyMode.field.MODE));
+			sprintf(extra + strlen(extra), "%-6s", GetBW(pEntry->HTPhyMode.field.BW));
+			sprintf(extra + strlen(extra), "%-6d", pEntry->HTPhyMode.field.MCS);
+			sprintf(extra + strlen(extra), "%-6d", pEntry->HTPhyMode.field.ShortGI);
+			sprintf(extra + strlen(extra), "%-6d", pEntry->HTPhyMode.field.STBC);
+			sprintf(extra + strlen(extra), "%-10d, %d, %d%%\n", pEntry->DebugFIFOCount, pEntry->DebugTxCount,
+						(pEntry->DebugTxCount) ? ((pEntry->DebugTxCount-pEntry->DebugFIFOCount)*100/pEntry->DebugTxCount) : 0);
+			sprintf(extra, "%s\n", extra);
+		}
+	}
+
 	return TRUE;
 }
-#endif // CARRIER_DETECTION_SUPPORT //
-
+#endif /* RT2870 */
diff --git a/drivers/staging/rt2860/wpa.h b/drivers/staging/rt2860/wpa.h
index 0134ae6..e671674 100644
--- a/drivers/staging/rt2860/wpa.h
+++ b/drivers/staging/rt2860/wpa.h
@@ -90,7 +90,9 @@
 #define TKIP_AP_RXMICK_OFFSET		(TKIP_AP_TXMICK_OFFSET+LEN_TKIP_TXMICK)
 #define TKIP_GTK_LENGTH				((LEN_TKIP_EK)+(LEN_TKIP_RXMICK)+(LEN_TKIP_TXMICK))
 #define LEN_PTK						((LEN_EAP_KEY)+(LEN_TKIP_KEY))
+#ifndef RT30xx
 #define MIN_LEN_OF_GTK				5
+#endif
 
 // RSN IE Length definition
 #define MAX_LEN_OF_RSNIE         	90
@@ -150,19 +152,6 @@
 // EAPOL Key Information definition within Key descriptor format
 typedef	struct PACKED _KEY_INFO
 {
-#ifdef RT_BIG_ENDIAN
-	UCHAR	KeyAck:1;
-    UCHAR	Install:1;
-    UCHAR	KeyIndex:2;
-    UCHAR	KeyType:1;
-    UCHAR	KeyDescVer:3;
-    UCHAR	Rsvd:3;
-    UCHAR	EKD_DL:1;		// EKD for AP; DL for STA
-    UCHAR	Request:1;
-    UCHAR	Error:1;
-    UCHAR	Secure:1;
-    UCHAR	KeyMic:1;
-#else
 	UCHAR	KeyMic:1;
 	UCHAR	Secure:1;
 	UCHAR	Error:1;
@@ -174,7 +163,6 @@
 	UCHAR	KeyIndex:2;
 	UCHAR	Install:1;
 	UCHAR	KeyAck:1;
-#endif
 }	KEY_INFO, *PKEY_INFO;
 
 // EAPOL Key descriptor format
@@ -204,17 +192,10 @@
 //802.11i D10 page 83
 typedef struct PACKED _GTK_ENCAP
 {
-#ifndef RT_BIG_ENDIAN
     UCHAR               Kid:2;
     UCHAR               tx:1;
     UCHAR               rsv:5;
     UCHAR               rsv1;
-#else
-    UCHAR               rsv:5;
-    UCHAR               tx:1;
-    UCHAR               Kid:2;
-    UCHAR               rsv1;
-#endif
     UCHAR               GTK[TKIP_GTK_LENGTH];
 }   GTK_ENCAP, *PGTK_ENCAP;
 
@@ -258,19 +239,11 @@
 
 typedef	union PACKED _RSN_CAPABILITIES	{
 	struct	PACKED {
-#ifdef RT_BIG_ENDIAN
-        USHORT		Rsvd:10;
-        USHORT		GTKSA_R_Counter:2;
-        USHORT		PTKSA_R_Counter:2;
-        USHORT		No_Pairwise:1;
-		USHORT		PreAuth:1;
-#else
         USHORT		PreAuth:1;
 		USHORT		No_Pairwise:1;
 		USHORT		PTKSA_R_Counter:2;
 		USHORT		GTKSA_R_Counter:2;
 		USHORT		Rsvd:10;
-#endif
 	}	field;
 	USHORT			word;
 }	RSN_CAPABILITIES, *PRSN_CAPABILITIES;
diff --git a/drivers/staging/rt2870/2870_main_dev.c b/drivers/staging/rt2870/2870_main_dev.c
index 9d59e31..dd01c64 100644
--- a/drivers/staging/rt2870/2870_main_dev.c
+++ b/drivers/staging/rt2870/2870_main_dev.c
@@ -46,17 +46,10 @@
 // Otherwise post to forum in ralinktech's web site(www.ralinktech.com) and let all users help you. ***
 MODULE_AUTHOR("Paul Lin <paul_lin@ralinktech.com>");
 MODULE_DESCRIPTION("RT2870 Wireless Lan Linux Driver");
-#ifdef CONFIG_STA_SUPPORT
 MODULE_LICENSE("GPL");
 #ifdef MODULE_VERSION
 MODULE_VERSION(STA_DRIVER_VERSION);
 #endif
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef MULTIPLE_CARD_SUPPORT
-// record whether the card in the card list is used in the card file
-extern UINT8  MC_CardUsed[];
-#endif // MULTIPLE_CARD_SUPPORT //
 
 /* Kernel thread and vars, which handles packets that are completed. Only
  * packets that have a "complete" function are sent here. This way, the
@@ -77,26 +70,6 @@
 #endif
 
 
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-
-/**************************************************************************/
-/**************************************************************************/
-//tested for kernel 2.4 series
-/**************************************************************************/
-/**************************************************************************/
-static void *rtusb_probe(struct usb_device *dev, UINT interface,
-						const struct usb_device_id *id_table);
-static void rtusb_disconnect(struct usb_device *dev, void *ptr);
-
-struct usb_driver rtusb_driver = {
-		name:"rt2870",
-		probe:rtusb_probe,
-		disconnect:rtusb_disconnect,
-		id_table:rtusb_usb_id,
-	};
-
-#else
-
 #ifdef CONFIG_PM
 static int rt2870_suspend(struct usb_interface *intf, pm_message_t state);
 static int rt2870_resume(struct usb_interface *intf);
@@ -112,9 +85,6 @@
 static void rtusb_disconnect(struct usb_interface *intf);
 
 struct usb_driver rtusb_driver = {
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,15)
-	.owner = THIS_MODULE,
-#endif
 	.name="rt2870",
 	.probe=rtusb_probe,
 	.disconnect=rtusb_disconnect,
@@ -176,7 +146,6 @@
 	return 0;
 }
 #endif // CONFIG_PM //
-#endif // LINUX_VERSION_CODE //
 
 
 // Init driver module
@@ -265,7 +234,12 @@
 	 */
 	DBGPRINT(RT_DEBUG_TRACE,( "<---%s\n",__func__));
 
+#ifndef RT30xx
 	pObj->MLMEThr_task = NULL;
+#endif
+#ifdef RT30xx
+	pObj->MLMEThr_pid = NULL;
+#endif
 
 	complete_and_exit (&pAd->mlmeComplete, 0);
 	return 0;
@@ -373,7 +347,12 @@
 	 */
 	DBGPRINT(RT_DEBUG_TRACE,( "<---RTUSBCmdThread\n"));
 
+#ifndef RT30xx
 	pObj->RTUSBCmdThr_task = NULL;
+#endif
+#ifdef RT30xx
+	pObj->RTUSBCmdThr_pid = NULL;
+#endif
 
 	complete_and_exit (&pAd->CmdQComplete, 0);
 	return 0;
@@ -467,8 +446,12 @@
 	 */
 	DBGPRINT(RT_DEBUG_TRACE,( "<---%s\n",__func__));
 
+#ifndef RT30xx
 	pObj->TimerQThr_task = NULL;
-
+#endif
+#ifdef RT30xx
+	pObj->TimerQThr_pid = NULL;
+#endif
 	complete_and_exit(&pAd->TimerQComplete, 0);
 	return 0;
 
@@ -636,6 +619,7 @@
 		RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf40006);
 	}
 
+//PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
 	idx = 0;
 	if ((MACValue & 0xff00) !=0 )
 	{
@@ -649,7 +633,6 @@
 		RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf40006);
 	}
 
-
 	if (pAd->watchDogRxOverFlowCnt >= 2)
 	{
 		DBGPRINT(RT_DEBUG_TRACE, ("Maybe the Rx Bulk-In hanged! Cancel the pending Rx bulks request!\n"));
@@ -740,7 +723,6 @@
 		}
 	}
 
-#ifdef DOT11_N_SUPPORT
 	// For Sigma debug, dump the ba_reordering sequence.
 	if((needDumpSeq == TRUE) && (pAd->CommonCfg.bDisableReordering == 0))
 	{
@@ -768,7 +750,6 @@
 			NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
 		}
 	}
-#endif // DOT11_N_SUPPORT //
 }
 
 /*
@@ -795,19 +776,7 @@
 				dev->bus->bus_name, dev->devpath));
 	if (!pAd)
 	{
-#ifdef MULTIPLE_CARD_SUPPORT
-		if ((pAd->MC_RowID >= 0) && (pAd->MC_RowID <= MAX_NUM_OF_MULTIPLE_CARD))
-			MC_CardUsed[pAd->MC_RowID] = 0; // not clear MAC address
-#endif // MULTIPLE_CARD_SUPPORT //
-
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-		while(MOD_IN_USE > 0)
-		{
-			MOD_DEC_USE_COUNT;
-		}
-#else
 		usb_put_dev(dev);
-#endif // LINUX_VERSION_CODE //
 
 		printk("rtusb_disconnect: pAd == NULL!\n");
 		return;
@@ -829,31 +798,17 @@
 		unregister_netdev (pAd->net_dev);
 	}
 	udelay(1);
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-#else
 	flush_scheduled_work();
-#endif // LINUX_VERSION_CODE //
 	udelay(1);
 
 	// free net_device memory
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	kfree(net_dev);
-#else
 	free_netdev(net_dev);
-#endif // LINUX_VERSION_CODE //
 
 	// free adapter memory
 	RTMPFreeAdapter(pAd);
 
 	// release a use of the usb device structure
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	while(MOD_IN_USE > 0)
-	{
-		MOD_DEC_USE_COUNT;
-	}
-#else
 	usb_put_dev(dev);
-#endif // LINUX_VERSION_CODE //
 	udelay(1);
 
 	DBGPRINT(RT_DEBUG_ERROR, (" RTUSB disconnect successfully\n"));
@@ -876,22 +831,6 @@
 Note:
 ========================================================================
 */
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-static void *rtusb_probe(struct usb_device *dev, UINT interface,
-						const struct usb_device_id *id)
-{
-	PRTMP_ADAPTER pAd;
-	rt28xx_probe((void *)dev, (void *)id, interface, &pAd);
-	return (void *)pAd;
-}
-
-//Disconnect function is called within exit routine
-static void rtusb_disconnect(struct usb_device *dev, void *ptr)
-{
-	_rtusb_disconnect(dev, ((PRTMP_ADAPTER)ptr));
-}
-
-#else	/* kernel 2.6 series */
 static int rtusb_probe (struct usb_interface *intf,
 						const struct usb_device_id *id)
 {
@@ -911,7 +850,6 @@
 
 	_rtusb_disconnect(dev, pAd);
 }
-#endif // LINUX_VERSION_CODE //
 
 
 /*
@@ -944,6 +882,7 @@
 	RTUSBCancelPendingIRPs(pAd);
 
 	// Terminate Threads
+#ifndef RT30xx
 	BUG_ON(pObj->TimerQThr_task == NULL);
 	CHECK_PID_LEGALITY(task_pid(pObj->TimerQThr_task))
 	{
@@ -985,7 +924,72 @@
 		kthread_stop(pObj->RTUSBCmdThr_task);
 		pObj->RTUSBCmdThr_task = NULL;
 	}
+#endif
+#ifdef RT30xx
+	if (pObj->MLMEThr_pid)
+	{
+		printk("Terminate the MLMEThr_pid=%d!\n", pid_nr(pObj->MLMEThr_pid));
+		mb();
+		pAd->mlme_kill = 1;
+		//RT28XX_MLME_HANDLER(pAd);
+		mb();
+		ret = kill_pid(pObj->MLMEThr_pid, SIGTERM, 1);
+		if (ret)
+		{
+			printk (KERN_WARNING "%s: unable to Mlme thread, pid=%d, ret=%d!\n",
+					pAd->net_dev->name, pid_nr(pObj->MLMEThr_pid), ret);
+		}
+		else
+		{
+			//wait_for_completion (&pAd->notify);
+			wait_for_completion (&pAd->mlmeComplete);
+			pObj->MLMEThr_pid = NULL;
+		}
+	}
 
+	if (pObj->RTUSBCmdThr_pid >= 0)
+	{
+		printk("Terminate the RTUSBCmdThr_pid=%d!\n", pid_nr(pObj->RTUSBCmdThr_pid));
+		mb();
+		NdisAcquireSpinLock(&pAd->CmdQLock);
+		pAd->CmdQ.CmdQState = RT2870_THREAD_STOPED;
+		NdisReleaseSpinLock(&pAd->CmdQLock);
+		mb();
+		//RTUSBCMDUp(pAd);
+		ret = kill_pid(pObj->RTUSBCmdThr_pid, SIGTERM, 1);
+		if (ret)
+		{
+			printk(KERN_WARNING "%s: unable to RTUSBCmd thread, pid=%d, ret=%d!\n",
+					pAd->net_dev->name, pid_nr(pObj->RTUSBCmdThr_pid), ret);
+	}
+		else
+		{
+			//wait_for_completion (&pAd->notify);
+			wait_for_completion (&pAd->CmdQComplete);
+			pObj->RTUSBCmdThr_pid = NULL;
+		}
+	}
+	if (pObj->TimerQThr_pid >= 0)
+	{
+		POS_COOKIE pObj = (POS_COOKIE)pAd->OS_Cookie;
+		printk("Terminate the TimerQThr_pid=%d!\n", pid_nr(pObj->TimerQThr_pid));
+		mb();
+		pAd->TimerFunc_kill = 1;
+		mb();
+		ret = kill_pid(pObj->TimerQThr_pid, SIGTERM, 1);
+		if (ret)
+		{
+			printk(KERN_WARNING "%s: unable to stop TimerQThread, pid=%d, ret=%d!\n",
+					pAd->net_dev->name, pid_nr(pObj->TimerQThr_pid), ret);
+		}
+		else
+		{
+			printk("wait_for_completion TimerQThr\n");
+			wait_for_completion(&pAd->TimerQComplete);
+			pObj->TimerQThr_pid = NULL;
+		}
+	}
+#endif
 
 	// Kill tasklets
 	pAd->mlme_kill = 0;
@@ -1030,12 +1034,8 @@
 BOOLEAN RT28XXChipsetCheck(
 	IN void *_dev_p)
 {
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	struct usb_device *dev_p = (struct usb_device *)_dev_p;
-#else
 	struct usb_interface *intf = (struct usb_interface *)_dev_p;
 	struct usb_device *dev_p = interface_to_usbdev(intf);
-#endif // LINUX_VERSION_CODE //
 	UINT32 i;
 
 
@@ -1044,7 +1044,12 @@
 		if (dev_p->descriptor.idVendor == rtusb_usb_id[i].idVendor &&
 			dev_p->descriptor.idProduct == rtusb_usb_id[i].idProduct)
 		{
+#ifndef RT30xx
 			printk(KERN_DEBUG "rt2870: idVendor = 0x%x, idProduct = 0x%x\n",
+#endif
+#ifdef RT30xx
+			printk("rt2870: idVendor = 0x%x, idProduct = 0x%x\n",
+#endif
 					dev_p->descriptor.idVendor, dev_p->descriptor.idProduct);
 			break;
 		}
@@ -1082,19 +1087,11 @@
 	IN struct  net_device	*net_dev,
 	IN RTMP_ADAPTER 		*pAd)
 {
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	struct usb_device *dev_p = (struct usb_device *)_dev_p;
-#else
 	struct usb_interface *intf = (struct usb_interface *)_dev_p;
 	struct usb_device *dev_p = interface_to_usbdev(intf);
-#endif // LINUX_VERSION_CODE //
 
 
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	pAd->config = dev_p->config;
-#else
 	pAd->config = &dev_p->config->desc;
-#endif // LINUX_VERSION_CODE //
 	return TRUE;
 }
 
@@ -1115,70 +1112,6 @@
 Note:
 ========================================================================
 */
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-BOOLEAN RT28XXProbePostConfig(
-	IN void 				*_dev_p,
-	IN RTMP_ADAPTER 		*pAd,
-	IN INT32				interface)
-{
-	struct usb_device *dev_p = (struct usb_device *)_dev_p;
-	struct usb_interface *intf;
-	struct usb_interface_descriptor *iface_desc;
-	struct usb_endpoint_descriptor *endpoint;
-	ULONG BulkOutIdx;
-	UINT32 i;
-
-
-	/* get the active interface descriptor */
-	intf = &dev_p->actconfig->interface[interface];
-	iface_desc = &intf->altsetting[0];
-
-	/* get # of enpoints */
-	pAd->NumberOfPipes = iface_desc->bNumEndpoints;
-	DBGPRINT(RT_DEBUG_TRACE, ("NumEndpoints=%d\n", iface_desc->bNumEndpoints));
-
-	/* Configure Pipes */
-	endpoint = &iface_desc->endpoint[0];
-	BulkOutIdx = 0;
-
-	for(i=0; i<pAd->NumberOfPipes; i++)
-	{
-		if ((endpoint[i].bmAttributes == USB_ENDPOINT_XFER_BULK) &&
-			((endpoint[i].bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN))
-		{
-			pAd->BulkInEpAddr = endpoint[i].bEndpointAddress;
-			pAd->BulkInMaxPacketSize = endpoint[i].wMaxPacketSize;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("BULK IN MaximumPacketSize = %d\n", pAd->BulkInMaxPacketSize));
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("EP address = 0x%2x  \n", endpoint[i].bEndpointAddress));
-		}
-		else if ((endpoint[i].bmAttributes == USB_ENDPOINT_XFER_BULK) &&
-				((endpoint[i].bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT))
-		{
-			// There are 6 bulk out EP. EP6 highest priority.
-			// EP1-4 is EDCA.  EP5 is HCCA.
-			pAd->BulkOutEpAddr[BulkOutIdx++] = endpoint[i].bEndpointAddress;
-			pAd->BulkOutMaxPacketSize = endpoint[i].wMaxPacketSize;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("BULK OUT MaximumPacketSize = %d\n", pAd->BulkOutMaxPacketSize));
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("EP address = 0x%2x  \n", endpoint[i].bEndpointAddress));
-		}
-	}
-
-	if (!(pAd->BulkInEpAddr && pAd->BulkOutEpAddr[0]))
-	{
-		printk("Could not find both bulk-in and bulk-out endpoints\n");
-		return FALSE;
-	}
-
-	return TRUE;
-}
-
-#else
 BOOLEAN RT28XXProbePostConfig(
 	IN void 				*_dev_p,
 	IN RTMP_ADAPTER 		*pAd,
@@ -1241,7 +1174,6 @@
 
 	return TRUE;
 }
-#endif // LINUX_VERSION_CODE //
 
 
 /*
@@ -1380,9 +1312,7 @@
 	else
 	{
 		ptr = (PUCHAR)&pAd->BeaconTxWI;
-#ifdef RT_BIG_ENDIAN
-		RTMPWIEndianChange(ptr, TYPE_TXWI);
-#endif
+
 		if (NdisEqualMemory(pBeaconSync->BeaconTxWI[bcn_idx], &pAd->BeaconTxWI, TXWI_SIZE) == FALSE)
 		{	// If BeaconTxWI changed, we need to rewrite the TxWI for the Beacon frames.
 			pBeaconSync->BeaconBitMap &= (~(BEACON_BITMAP_MASK & (1 << bcn_idx)));
@@ -1417,6 +1347,8 @@
 		}
 
 		pBeaconSync->BeaconBitMap |= (1 << bcn_idx);
+
+		// For AP interface, set the DtimBitOn so that we can send Bcast/Mcast frame out after this beacon frame.
 	}
 
 }
@@ -1434,13 +1366,7 @@
 	{
 		INT NumOfBcn;
 
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			NumOfBcn = MAX_MESH_NUM;
-		}
-#endif // CONFIG_STA_SUPPORT //
+		NumOfBcn = MAX_MESH_NUM;
 
 		RTMPCancelTimer(&pAd->CommonCfg.BeaconUpdateTimer, &Cancelled);
 
@@ -1473,13 +1399,7 @@
 	{
 		INT NumOfBcn;
 
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			NumOfBcn = MAX_MESH_NUM;
-		}
-#endif // CONFIG_STA_SUPPORT //
+		NumOfBcn = MAX_MESH_NUM;
 
 		for(apidx=0; apidx<NumOfBcn; apidx++)
 		{
diff --git a/drivers/staging/rt2870/Makefile b/drivers/staging/rt2870/Makefile
index 1a015f4..3c17921 100644
--- a/drivers/staging/rt2870/Makefile
+++ b/drivers/staging/rt2870/Makefile
@@ -3,11 +3,7 @@
 # TODO: all of these should be removed
 EXTRA_CFLAGS += -DLINUX -DAGGREGATION_SUPPORT -DPIGGYBACK_SUPPORT -DWMM_SUPPORT
 EXTRA_CFLAGS += -DRT2870
-EXTRA_CFLAGS += -DCONFIG_STA_SUPPORT
 EXTRA_CFLAGS += -DDBG
-EXTRA_CFLAGS += -DDOT11_N_SUPPORT
-EXTRA_CFLAGS += -DWPA_SUPPLICANT_SUPPORT
-EXTRA_CFLAGS += -DNATIVE_WPA_SUPPLICANT_SUPPORT
 
 rt2870sta-objs :=		\
 	common/md5.o		\
diff --git a/drivers/staging/rt2870/aironet.h b/drivers/staging/rt2870/aironet.h
index 1e07b19..ae62597 100644
--- a/drivers/staging/rt2870/aironet.h
+++ b/drivers/staging/rt2870/aironet.h
@@ -1,210 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	aironet.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-	Paul Lin	04-06-15		Initial
-*/
-
-#ifndef	__AIRONET_H__
-#define	__AIRONET_H__
-
-// Measurement Type definition
-#define	MSRN_TYPE_UNUSED				0
-#define	MSRN_TYPE_CHANNEL_LOAD_REQ		1
-#define	MSRN_TYPE_NOISE_HIST_REQ		2
-#define	MSRN_TYPE_BEACON_REQ			3
-#define	MSRN_TYPE_FRAME_REQ				4
-
-// Scan Mode in Beacon Request
-#define	MSRN_SCAN_MODE_PASSIVE			0
-#define	MSRN_SCAN_MODE_ACTIVE			1
-#define	MSRN_SCAN_MODE_BEACON_TABLE		2
-
-// PHY type definition for Aironet beacon report, CCX 2 table 36-9
-#define	PHY_FH							1
-#define	PHY_DSS							2
-#define	PHY_UNUSED						3
-#define	PHY_OFDM						4
-#define	PHY_HR_DSS						5
-#define	PHY_ERP							6
-
-// RPI table in dBm
-#define	RPI_0			0			//	Power <= -87
-#define	RPI_1			1			//	-87 < Power <= -82
-#define	RPI_2			2			//	-82 < Power <= -77
-#define	RPI_3			3			//	-77 < Power <= -72
-#define	RPI_4			4			//	-72 < Power <= -67
-#define	RPI_5			5			//	-67 < Power <= -62
-#define	RPI_6			6			//	-62 < Power <= -57
-#define	RPI_7			7			//	-57 < Power
-
-// Cisco Aironet IAPP definetions
-#define	AIRONET_IAPP_TYPE					0x32
-#define	AIRONET_IAPP_SUBTYPE_REQUEST		0x01
-#define	AIRONET_IAPP_SUBTYPE_REPORT			0x81
-
-// Measurement Request detail format
-typedef	struct	_MEASUREMENT_REQUEST	{
-	UCHAR	Channel;
-	UCHAR	ScanMode;			// Use only in beacon request, other requests did not use this field
-	USHORT	Duration;
-}	MEASUREMENT_REQUEST, *PMEASUREMENT_REQUEST;
-
-// Beacon Measurement Report
-// All these field might change to UCHAR, because we didn't do anything to these report.
-// We copy all these beacons and report to CCX 2 AP.
-typedef	struct	_BEACON_REPORT	{
-	UCHAR	Channel;
-	UCHAR	Spare;
-	USHORT	Duration;
-	UCHAR	PhyType;			// Definiation is listed above table 36-9
-	UCHAR	RxPower;
-	UCHAR	BSSID[6];
-	UCHAR	ParentTSF[4];
-	UCHAR	TargetTSF[8];
-	USHORT	BeaconInterval;
-	USHORT	CapabilityInfo;
-}	BEACON_REPORT, *PBEACON_REPORT;
-
-// Frame Measurement Report (Optional)
-typedef	struct	_FRAME_REPORT	{
-	UCHAR	Channel;
-	UCHAR	Spare;
-	USHORT	Duration;
-	UCHAR	TA;
-	UCHAR	BSSID[6];
-	UCHAR	RSSI;
-	UCHAR	Count;
-}	FRAME_REPORT, *PFRAME_REPORT;
-
-#pragma pack(1)
-// Channel Load Report
-typedef	struct	_CHANNEL_LOAD_REPORT	{
-	UCHAR	Channel;
-	UCHAR	Spare;
-	USHORT	Duration;
-	UCHAR	CCABusy;
-}	CHANNEL_LOAD_REPORT, *PCHANNEL_LOAD_REPORT;
-#pragma pack()
-
-// Nosie Histogram Report
-typedef	struct	_NOISE_HIST_REPORT	{
-	UCHAR	Channel;
-	UCHAR	Spare;
-	USHORT	Duration;
-	UCHAR	Density[8];
-}	NOISE_HIST_REPORT, *PNOISE_HIST_REPORT;
-
-// Radio Management Capability element
-typedef	struct	_RADIO_MANAGEMENT_CAPABILITY	{
-	UCHAR	Eid;				// TODO: Why the Eid is 1 byte, not normal 2 bytes???
-	UCHAR	Length;
-	UCHAR	AironetOui[3];		// AIronet OUI (00 40 96)
-	UCHAR	Type;				// Type / Version
-	USHORT	Status;				// swap16 required
-}	RADIO_MANAGEMENT_CAPABILITY, *PRADIO_MANAGEMENT_CAPABILITY;
-
-// Measurement Mode Bit definition
-typedef	struct	_MEASUREMENT_MODE	{
-	UCHAR	Rsvd:4;
-	UCHAR	Report:1;
-	UCHAR	NotUsed:1;
-	UCHAR	Enable:1;
-	UCHAR	Parallel:1;
-}	MEASUREMENT_MODE, *PMEASUREMENT_MODE;
-
-// Measurement Request element, This is little endian mode
-typedef	struct	_MEASUREMENT_REQUEST_ELEMENT	{
-	USHORT				Eid;
-	USHORT				Length;				// swap16 required
-	USHORT				Token;				// non-zero unique token
-	UCHAR				Mode;				// Measurement Mode
-	UCHAR				Type;				// Measurement type
-}	MEASUREMENT_REQUEST_ELEMENT, *PMEASUREMENT_REQUEST_ELEMENT;
-
-// Measurement Report element, This is little endian mode
-typedef	struct	_MEASUREMENT_REPORT_ELEMENT	{
-	USHORT				Eid;
-	USHORT				Length;				// swap16 required
-	USHORT				Token;				// non-zero unique token
-	UCHAR				Mode;				// Measurement Mode
-	UCHAR				Type;				// Measurement type
-}	MEASUREMENT_REPORT_ELEMENT, *PMEASUREMENT_REPORT_ELEMENT;
-
-// Cisco Aironet IAPP Frame Header, Network byte order used
-typedef	struct	_AIRONET_IAPP_HEADER {
-	UCHAR	CiscoSnapHeader[8];	// 8 bytes Cisco snap header
-	USHORT	Length;				// IAPP ID & length, remember to swap16 in LE system
-	UCHAR	Type;				// IAPP type
-	UCHAR	SubType;			// IAPP subtype
-	UCHAR	DA[6];				// Destination MAC address
-	UCHAR	SA[6];				// Source MAC address
-	USHORT	Token;				// Dialog token, no need to swap16 since it is for yoken usage only
-}	AIRONET_IAPP_HEADER, *PAIRONET_IAPP_HEADER;
-
-// Radio Measurement Request frame
-typedef	struct	_AIRONET_RM_REQUEST_FRAME	{
-    AIRONET_IAPP_HEADER	IAPP;			// Common header
-	UCHAR				Delay;			// Activation Delay
-	UCHAR				Offset;			// Measurement offset
-}	AIRONET_RM_REQUEST_FRAME, *PAIRONET_RM_REQUEST_FRAME;
-
-// Radio Measurement Report frame
-typedef	struct	_AIRONET_RM_REPORT_FRAME	{
-    AIRONET_IAPP_HEADER	IAPP;			// Common header
-}	AIRONET_RM_REPORT_FRAME, *PAIRONET_RM_REPORT_FRAME;
-
-// Saved element request actions which will saved in StaCfg.
-typedef	struct	_RM_REQUEST_ACTION	{
-	MEASUREMENT_REQUEST_ELEMENT	ReqElem;		// Saved request element
-	MEASUREMENT_REQUEST			Measurement;	// Saved measurement within the request element
-}	RM_REQUEST_ACTION, *PRM_REQUEST_ACTION;
-
-// CCX administration control
-typedef	union	_CCX_CONTROL	{
-	struct	{
-		UINT32		Enable:1;			// Enable CCX2
-		UINT32		LeapEnable:1;		// Enable LEAP at CCX2
-		UINT32		RMEnable:1;			// Radio Measurement Enable
-		UINT32		DCRMEnable:1;		// Non serving channel Radio Measurement enable
-		UINT32		QOSEnable:1;		// Enable QOS for CCX 2.0 support
-		UINT32		FastRoamEnable:1;	// Enable fast roaming
-		UINT32		Rsvd:2;				// Not used
-		UINT32		dBmToRoam:8;		// the condition to roam when receiving Rssi less than this value. It's negative value.
-		UINT32		TuLimit:16;			// Limit for different channel scan
-	}	field;
-	UINT32			word;
-}	CCX_CONTROL, *PCCX_CONTROL;
-
-#endif	// __AIRONET_H__
+#include "../rt2860/aironet.h"
diff --git a/drivers/staging/rt2870/ap.h b/drivers/staging/rt2870/ap.h
index 0dc5575..fe04b5f 100644
--- a/drivers/staging/rt2870/ap.h
+++ b/drivers/staging/rt2870/ap.h
@@ -1,562 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    ap.h
-
-    Abstract:
-    Miniport generic portion header file
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Paul Lin    08-01-2002    created
-    James Tan   09-06-2002    modified (Revise NTCRegTable)
-    John Chang  12-22-2004    modified for RT2561/2661. merge with STA driver
-*/
-#ifndef __AP_H__
-#define __AP_H__
-
-
-
-// ========================= AP RTMP.h ================================
-
-
-
-// =============================================================
-//      Function Prototypes
-// =============================================================
-
-// ap_data.c
-
-BOOLEAN APBridgeToWirelessSta(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pHeader,
-    IN  UINT            HdrLen,
-    IN  PUCHAR          pData,
-    IN  UINT            DataLen,
-    IN  ULONG           fromwdsidx);
-
-BOOLEAN APHandleRxDoneInterrupt(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID	APSendPackets(
-	IN	NDIS_HANDLE		MiniportAdapterContext,
-	IN	PPNDIS_PACKET	ppPacketArray,
-	IN	UINT			NumberOfPackets);
-
-NDIS_STATUS APSendPacket(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PNDIS_PACKET    pPacket);
-
-
-NDIS_STATUS APHardTransmit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	UCHAR			QueIdx);
-
-VOID APRxEAPOLFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-NDIS_STATUS APCheckRxError(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PRT28XX_RXD_STRUC		pRxD,
-	IN	UCHAR			Wcid);
-
-BOOLEAN APCheckClass2Class3Error(
-    IN  PRTMP_ADAPTER   pAd,
-	IN ULONG Wcid,
-	IN  PHEADER_802_11  pHeader);
-
-VOID APHandleRxPsPoll(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pAddr,
-	IN	USHORT			Aid,
-    IN	BOOLEAN			isActive);
-
-VOID    RTMPDescriptorEndianChange(
-    IN  PUCHAR          pData,
-    IN  ULONG           DescriptorType);
-
-VOID    RTMPFrameEndianChange(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pData,
-    IN  ULONG           Dir,
-    IN  BOOLEAN         FromRxDoneInt);
-
-// ap_assoc.c
-
-VOID APAssocStateMachineInit(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  STATE_MACHINE *S,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID  APPeerAssocReqAction(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID  APPeerReassocReqAction(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID  APPeerDisassocReqAction(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MbssKickOutStas(
-	IN PRTMP_ADAPTER pAd,
-	IN INT apidx,
-	IN USHORT Reason);
-
-VOID APMlmeKickOutSta(
-    IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pStaAddr,
-	IN UCHAR Wcid,
-	IN USHORT Reason);
-
-VOID APMlmeDisassocReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID  APCls3errAction(
-    IN  PRTMP_ADAPTER   pAd,
-	IN 	ULONG Wcid,
-    IN	PHEADER_802_11	pHeader);
-
-
-USHORT APBuildAssociation(
-    IN PRTMP_ADAPTER pAd,
-    IN MAC_TABLE_ENTRY *pEntry,
-    IN USHORT CapabilityInfo,
-    IN UCHAR  MaxSupportedRateIn500Kbps,
-    IN UCHAR  *RSN,
-    IN UCHAR  *pRSNLen,
-    IN BOOLEAN bWmmCapable,
-    IN ULONG  RalinkIe,
-#ifdef DOT11N_DRAFT3
-    IN EXT_CAP_INFO_ELEMENT ExtCapInfo,
-#endif // DOT11N_DRAFT3 //
-	IN HT_CAPABILITY_IE		*pHtCapability,
-	IN UCHAR		 HtCapabilityLen,
-    OUT USHORT *pAid);
-
-/*
-VOID	RTMPAddClientSec(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR	BssIdx,
-	IN UCHAR		 KeyIdx,
-	IN UCHAR		 CipherAlg,
-	IN PUCHAR		 pKey,
-	IN PUCHAR		 pTxMic,
-	IN PUCHAR		 pRxMic,
-	IN MAC_TABLE_ENTRY *pEntry);
-*/
-
-// ap_auth.c
-
-void APAuthStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID APMlmeDeauthReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID APCls2errAction(
-    IN PRTMP_ADAPTER pAd,
-	IN 	ULONG Wcid,
-    IN	PHEADER_802_11	pHeader);
-
-// ap_authrsp.c
-
-VOID APAuthRspStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN PSTATE_MACHINE Sm,
-    IN STATE_MACHINE_FUNC Trans[]);
-
-VOID APPeerAuthAtAuthRspIdleAction(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID APPeerDeauthReqAction(
-    IN PRTMP_ADAPTER	pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID APPeerAuthSimpleRspGenAndSend(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PHEADER_802_11 pHdr80211,
-    IN  USHORT Alg,
-    IN  USHORT Seq,
-    IN  USHORT StatusCode);
-
-// ap_connect.c
-
-BOOLEAN BeaconTransmitRequired(
-	IN PRTMP_ADAPTER	pAd,
-	IN INT				apidx);
-
-VOID APMakeBssBeacon(
-    IN  PRTMP_ADAPTER   pAd,
-	IN	INT				apidx);
-
-VOID  APUpdateBeaconFrame(
-    IN  PRTMP_ADAPTER   pAd,
-	IN	INT				apidx);
-
-VOID APMakeAllBssBeacon(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID  APUpdateAllBeaconFrame(
-    IN  PRTMP_ADAPTER   pAd);
-
-
-// ap_sync.c
-
-VOID APSyncStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID APScanTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID APInvalidStateWhenScan(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APScanTimeoutAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APPeerProbeReqAction(
-    IN  PRTMP_ADAPTER pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID APPeerBeaconAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID APMlmeScanReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APPeerBeaconAtScanAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APScanCnclAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID ApSiteSurvey(
-	IN PRTMP_ADAPTER pAd);
-
-VOID SupportRate(
-	IN PUCHAR SupRate,
-	IN UCHAR SupRateLen,
-	IN PUCHAR ExtRate,
-	IN UCHAR ExtRateLen,
-	OUT PUCHAR *Rates,
-	OUT PUCHAR RatesLen,
-	OUT PUCHAR pMaxSupportRate);
-
-
-BOOLEAN ApScanRunning(
-	IN PRTMP_ADAPTER pAd);
-
-#ifdef DOT11N_DRAFT3
-VOID APOverlappingBSSScan(
-	IN RTMP_ADAPTER *pAd);
-#endif // DOT11N_DRAFT3 //
-
-// ap_wpa.c
-
-VOID APWpaStateMachineInit(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-// ap_mlme.c
-
-VOID APMlmePeriodicExec(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID APMlmeSelectTxRateTable(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PUCHAR				*ppTable,
-	IN PUCHAR				pTableSize,
-	IN PUCHAR				pInitTxRateIdx);
-
-VOID APMlmeSetTxRate(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PRTMP_TX_RATE_SWITCH	pTxRate);
-
-VOID APMlmeDynamicTxRateSwitching(
-    IN PRTMP_ADAPTER pAd);
-
-VOID APQuickResponeForRateUpExec(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-BOOLEAN APMsgTypeSubst(
-    IN PRTMP_ADAPTER pAd,
-    IN PFRAME_802_11 pFrame,
-    OUT INT *Machine,
-    OUT INT *MsgType);
-
-VOID APQuickResponeForRateUpExec(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-#ifdef RT2870
-VOID BeaconUpdateExec(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-#endif // RT2870 //
-
-VOID RTMPSetPiggyBack(
-	IN PRTMP_ADAPTER	pAd,
-	IN BOOLEAN			bPiggyBack);
-
-VOID APAsicEvaluateRxAnt(
-	IN PRTMP_ADAPTER	pAd);
-
-VOID APAsicRxAntEvalTimeout(
-	IN PRTMP_ADAPTER	pAd);
-
-// ap.c
-
-VOID APSwitchChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN INT Channel);
-
-NDIS_STATUS APInitialize(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID APShutdown(
-    IN PRTMP_ADAPTER    pAd);
-
-VOID APStartUp(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID APStop(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID APCleanupPsQueue(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PQUEUE_HEADER   pQueue);
-
-VOID MacTableReset(
-    IN  PRTMP_ADAPTER   pAd);
-
-MAC_TABLE_ENTRY *MacTableInsertEntry(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pAddr,
-	IN	UCHAR			apidx,
-	IN BOOLEAN	CleanAll);
-
-BOOLEAN MacTableDeleteEntry(
-    IN  PRTMP_ADAPTER   pAd,
-	IN USHORT wcid,
-    IN  PUCHAR          pAddr);
-
-MAC_TABLE_ENTRY *MacTableLookup(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pAddr);
-
-VOID MacTableMaintenance(
-    IN PRTMP_ADAPTER pAd);
-
-UINT32 MacTableAssocStaNumGet(
-	IN PRTMP_ADAPTER pAd);
-
-MAC_TABLE_ENTRY *APSsPsInquiry(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pAddr,
-    OUT SST             *Sst,
-    OUT USHORT          *Aid,
-    OUT UCHAR           *PsMode,
-    OUT UCHAR           *Rate);
-
-BOOLEAN APPsIndicate(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pAddr,
-	IN ULONG Wcid,
-    IN  UCHAR           Psm);
-
-VOID ApLogEvent(
-    IN PRTMP_ADAPTER    pAd,
-    IN PUCHAR           pAddr,
-    IN USHORT           Event);
-
-#ifdef DOT11_N_SUPPORT
-VOID APUpdateOperationMode(
-    IN PRTMP_ADAPTER pAd);
-#endif // DOT11_N_SUPPORT //
-
-VOID APUpdateCapabilityAndErpIe(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN ApCheckAccessControlList(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR        pAddr,
-	IN UCHAR         Apidx);
-
-VOID ApUpdateAccessControlList(
-    IN PRTMP_ADAPTER pAd,
-    IN UCHAR         Apidx);
-
-VOID ApEnqueueNullFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR        pAddr,
-	IN UCHAR         TxRate,
-	IN UCHAR         PID,
-	IN UCHAR         apidx,
-    IN BOOLEAN       bQosNull,
-    IN BOOLEAN       bEOSP,
-    IN UCHAR         OldUP);
-
-VOID ApSendFrame(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PVOID           pBuffer,
-    IN  ULONG           Length,
-    IN  UCHAR           TxRate,
-    IN  UCHAR           PID);
-
-VOID ApEnqueueAckFrame(
-    IN PRTMP_ADAPTER pAd,
-    IN PUCHAR        pAddr,
-    IN UCHAR         TxRate,
-	IN UCHAR         apidx);
-
-UCHAR APAutoSelectChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN Optimal);
-
-// ap_sanity.c
-
-
-BOOLEAN PeerAssocReqCmmSanity(
-    IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN isRessoc,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pListenInterval,
-    OUT PUCHAR pApAddr,
-    OUT UCHAR *pSsidLen,
-    OUT char *Ssid,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-    OUT UCHAR *RSN,
-    OUT UCHAR *pRSNLen,
-    OUT BOOLEAN *pbWmmCapable,
-#ifdef WSC_AP_SUPPORT
-    OUT BOOLEAN *pWscCapable,
-#endif // WSC_AP_SUPPORT //
-    OUT ULONG  *pRalinkIe,
-#ifdef DOT11N_DRAFT3
-    OUT EXT_CAP_INFO_ELEMENT	*pExtCapInfo,
-#endif // DOT11N_DRAFT3 //
-    OUT UCHAR		 *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability);
-
-BOOLEAN PeerDisassocReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *Reason);
-
-BOOLEAN PeerDeauthReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *Reason);
-
-BOOLEAN APPeerAuthSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-	OUT PUCHAR pAddr1,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *Alg,
-    OUT USHORT *Seq,
-    OUT USHORT *Status,
-    CHAR *ChlgText);
-
-BOOLEAN APPeerProbeReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT CHAR Ssid[],
-    OUT UCHAR *SsidLen);
-
-BOOLEAN APPeerBeaconAndProbeRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT PUCHAR pBssid,
-    OUT CHAR Ssid[],
-    OUT UCHAR *SsidLen,
-    OUT UCHAR *BssType,
-    OUT USHORT *BeaconPeriod,
-    OUT UCHAR *Channel,
-    OUT LARGE_INTEGER *Timestamp,
-    OUT USHORT *CapabilityInfo,
-    OUT UCHAR Rate[],
-    OUT UCHAR *RateLen,
-    OUT BOOLEAN *ExtendedRateIeExist,
-    OUT UCHAR *Erp);
-
-// ap_info.c
-
-
-
-// ================== end of AP RTMP.h ========================
-
-
-#endif  // __AP_H__
-
+#include "../rt2860/ap.h"
diff --git a/drivers/staging/rt2870/chlist.h b/drivers/staging/rt2870/chlist.h
index 9e15b9d..3199958 100644
--- a/drivers/staging/rt2870/chlist.h
+++ b/drivers/staging/rt2870/chlist.h
@@ -1,1296 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	chlist.c
-
-	Abstract:
-
-	Revision History:
-	Who         When          What
-	--------    ----------    ----------------------------------------------
-	Fonchi Wu   2007-12-19    created
-*/
-
-#ifndef __CHLIST_H__
-#define __CHLIST_H__
-
-#include "rtmp_type.h"
-#include "rtmp_def.h"
-
-
-#define ODOR			0
-#define IDOR			1
-#define BOTH			2
-
-#define BAND_5G         0
-#define BAND_24G        1
-#define BAND_BOTH       2
-
-typedef struct _CH_DESP {
-	UCHAR FirstChannel;
-	UCHAR NumOfCh;
-	CHAR MaxTxPwr;			// dBm
-	UCHAR Geography;			// 0:out door, 1:in door, 2:both
-	BOOLEAN DfsReq;			// Dfs require, 0: No, 1: yes.
-} CH_DESP, *PCH_DESP;
-
-typedef struct _CH_REGION {
-	UCHAR CountReg[3];
-	UCHAR DfsType;			// 0: CE, 1: FCC, 2: JAP, 3:JAP_W53, JAP_W56
-	CH_DESP ChDesp[10];
-} CH_REGION, *PCH_REGION;
-
-static CH_REGION ChRegion[] =
-{
-		{	// Antigua and Berbuda
-			"AG",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Argentina
-			"AR",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Aruba
-			"AW",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Australia
-			"AU",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Austria
-			"AT",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, IDOR, TRUE},		// 5G, ch 36~48
-				{ 52,  4,  23, IDOR, TRUE},		// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, TRUE},		// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Bahamas
-			"BS",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Barbados
-			"BB",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Bermuda
-			"BM",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Brazil
-			"BR",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 24, BOTH, FALSE},	// 5G, ch 100~140
-				{ 149, 5,  30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Belgium
-			"BE",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  18, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  18, IDOR, FALSE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Bulgaria
-			"BG",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11, 30, ODOR, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Canada
-			"CA",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Cayman IsLands
-			"KY",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Chile
-			"CL",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  20, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  20, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 5,  20, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// China
-			"CN",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149, 4,  27, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Colombia
-			"CO",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  17, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 149, 5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Costa Rica
-			"CR",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  17, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Cyprus
-			"CY",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, IDOR, TRUE},		// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, TRUE},		// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Czech_Republic
-			"CZ",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, IDOR, TRUE},		// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Denmark
-			"DK",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, IDOR, TRUE},		// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, TRUE},		// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Dominican Republic
-			"DO",
-			CE,
-			{
-				{ 1,   0,  20, BOTH, FALSE},	// 2.4 G, ch 0
-				{ 149, 4,  20, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Equador
-			"EC",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 100, 11,  27, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// El Salvador
-			"SV",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   30, BOTH, TRUE},	// 5G, ch 52~64
-				{ 149, 4,   36, BOTH, TRUE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Finland
-			"FI",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// France
-			"FR",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Germany
-			"DE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Greece
-			"GR",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, ODOR, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Guam
-			"GU",
-			CE,
-			{
-				{ 1,   11,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 36,  4,   17, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 149,  5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Guatemala
-			"GT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   17, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Haiti
-			"HT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   17, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Honduras
-			"HN",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149,  4,  27, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Hong Kong
-			"HK",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Hungary
-			"HU",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Iceland
-			"IS",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// India
-			"IN",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149, 	4,  24, IDOR, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Indonesia
-			"ID",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149, 	4,  27, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Ireland
-			"IE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, ODOR, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Israel
-			"IL",
-			CE,
-			{
-				{ 1,    3,  20, IDOR, FALSE},	// 2.4 G, ch 1~3
-				{ 4, 	6,  20, BOTH, FALSE},	// 2.4 G, ch 4~9
-				{ 10, 	4,  20, IDOR, FALSE},	// 2.4 G, ch 10~13
-				{ 0},							// end
-			}
-		},
-
-		{	// Italy
-			"IT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, ODOR, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Japan
-			"JP",
-			JAP,
-			{
-				{ 1,   14,  20, BOTH, FALSE},	// 2.4 G, ch 1~14
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 0},							// end
-			}
-		},
-
-		{	// Jordan
-			"JO",
-			CE,
-			{
-				{ 1,   13,  20, IDOR, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 149, 	4,  23, IDOR, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Latvia
-			"LV",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Liechtenstein
-			"LI",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Lithuania
-			"LT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Luxemburg
-			"LU",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Malaysia
-			"MY",
-			CE,
-			{
-				{ 36, 	4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  5,  20, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Malta
-			"MT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Marocco
-			"MA",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  24, IDOR, FALSE},	// 5G, ch 36~48
-				{ 0},							// end
-			}
-		},
-
-		{	// Mexico
-			"MX",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  5,  30, IDOR, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Netherlands
-			"NL",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  24, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// New Zealand
-			"NZ",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  24, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Norway
-			"NO",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  24, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  24, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Peru
-			"PE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149,  4,  27, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Portugal
-			"PT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Poland
-			"PL",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Romania
-			"RO",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Russia
-			"RU",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149,  4,  20, IDOR, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Saudi Arabia
-			"SA",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  23, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Serbia_and_Montenegro
-			"CS",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 0},							// end
-			}
-		},
-
-		{	// Singapore
-			"SG",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  20, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Slovakia
-			"SK",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Slovenia
-			"SI",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// South Africa
-			"ZA",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, FALSE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 149,  4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// South Korea
-			"KR",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  20, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  20, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100,  8,  20, BOTH, FALSE},	// 5G, ch 100~128
-				{ 149,  4,  20, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Spain
-			"ES",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  17, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Sweden
-			"SE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Switzerland
-			"CH",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, TRUE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Taiwan
-			"TW",
-			CE,
-			{
-				{ 1,   11,  30, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 52,   4,  23, IDOR, FALSE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Turkey
-			"TR",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 36,   4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// UK
-			"GB",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 52~64
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Ukraine
-			"UA",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 0},							// end
-			}
-		},
-
-		{	// United_Arab_Emirates
-			"AE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 0},							// end
-			}
-		},
-
-		{	// United_States
-			"US",
-			CE,
-			{
-				{ 1,   11,  30, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 36,   4,  17, IDOR, FALSE},	// 5G, ch 52~64
-				{ 52,   4,  24, BOTH, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 149,  5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Venezuela
-			"VE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 149,  4,  27, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Default
-			"",
-			CE,
-			{
-				{ 1,   11,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 36,   4,  20, BOTH, FALSE},	// 5G, ch 52~64
-				{ 52,   4,  20, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11,  20, BOTH, FALSE},	// 5G, ch 100~140
-				{ 149,  5,  20, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-};
-
-static inline PCH_REGION GetChRegion(
-	IN PUCHAR CntryCode)
-{
-	INT loop = 0;
-	PCH_REGION pChRegion = NULL;
-
-	while (strcmp(ChRegion[loop].CountReg, "") != 0)
-	{
-		if (strncmp(ChRegion[loop].CountReg, CntryCode, 2) == 0)
-		{
-			pChRegion = &ChRegion[loop];
-			break;
-		}
-		loop++;
-	}
-
-	if (pChRegion == NULL)
-		pChRegion = &ChRegion[loop];
-	return pChRegion;
-}
-
-static inline VOID ChBandCheck(
-	IN UCHAR PhyMode,
-	OUT PUCHAR pChType)
-{
-	switch(PhyMode)
-	{
-		case PHY_11A:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11AN_MIXED:
-#endif // DOT11_N_SUPPORT //
-			*pChType = BAND_5G;
-			break;
-		case PHY_11ABG_MIXED:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11AGN_MIXED:
-		case PHY_11ABGN_MIXED:
-#endif // DOT11_N_SUPPORT //
-			*pChType = BAND_BOTH;
-			break;
-
-		default:
-			*pChType = BAND_24G;
-			break;
-	}
-}
-
-static inline UCHAR FillChList(
-	IN PRTMP_ADAPTER pAd,
-	IN PCH_DESP pChDesp,
-	IN UCHAR Offset,
-	IN UCHAR increment)
-{
-	INT i, j, l;
-	UCHAR channel;
-
-	j = Offset;
-	for (i = 0; i < pChDesp->NumOfCh; i++)
-	{
-		channel = pChDesp->FirstChannel + i * increment;
-		for (l=0; l<MAX_NUM_OF_CHANNELS; l++)
-		{
-			if (channel == pAd->TxPower[l].Channel)
-			{
-				pAd->ChannelList[j].Power = pAd->TxPower[l].Power;
-				pAd->ChannelList[j].Power2 = pAd->TxPower[l].Power2;
-				break;
-			}
-		}
-		if (l == MAX_NUM_OF_CHANNELS)
-			continue;
-
-		pAd->ChannelList[j].Channel = pChDesp->FirstChannel + i * increment;
-		pAd->ChannelList[j].MaxTxPwr = pChDesp->MaxTxPwr;
-		pAd->ChannelList[j].DfsReq = pChDesp->DfsReq;
-		j++;
-	}
-	pAd->ChannelListNum = j;
-
-	return j;
-}
-
-static inline VOID CreateChList(
-	IN PRTMP_ADAPTER pAd,
-	IN PCH_REGION pChRegion,
-	IN UCHAR Geography)
-{
-	INT i;
-	UCHAR offset = 0;
-	PCH_DESP pChDesp;
-	UCHAR ChType;
-	UCHAR increment;
-
-	if (pChRegion == NULL)
-		return;
-
-	ChBandCheck(pAd->CommonCfg.PhyMode, &ChType);
-
-	for (i=0; i<10; i++)
-	{
-		pChDesp = &pChRegion->ChDesp[i];
-		if (pChDesp->FirstChannel == 0)
-			break;
-
-		if (ChType == BAND_5G)
-		{
-			if (pChDesp->FirstChannel <= 14)
-				continue;
-		}
-		else if (ChType == BAND_24G)
-		{
-			if (pChDesp->FirstChannel > 14)
-				continue;
-		}
-
-		if ((pChDesp->Geography == BOTH)
-			|| (pChDesp->Geography == Geography))
-        {
-			if (pChDesp->FirstChannel > 14)
-                increment = 4;
-            else
-                increment = 1;
-			offset = FillChList(pAd, pChDesp, offset, increment);
-        }
-	}
-}
-
-static inline VOID BuildChannelListEx(
-	IN PRTMP_ADAPTER pAd)
-{
-	PCH_REGION pChReg;
-
-	pChReg = GetChRegion(pAd->CommonCfg.CountryCode);
-	CreateChList(pAd, pChReg, pAd->CommonCfg.Geography);
-}
-
-static inline VOID BuildBeaconChList(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pBuf,
-	OUT	PULONG pBufLen)
-{
-	INT i;
-	ULONG TmpLen;
-	PCH_REGION pChRegion;
-	PCH_DESP pChDesp;
-	UCHAR ChType;
-
-	pChRegion = GetChRegion(pAd->CommonCfg.CountryCode);
-
-	if (pChRegion == NULL)
-		return;
-
-	ChBandCheck(pAd->CommonCfg.PhyMode, &ChType);
-	*pBufLen = 0;
-
-	for (i=0; i<10; i++)
-	{
-		pChDesp = &pChRegion->ChDesp[i];
-		if (pChDesp->FirstChannel == 0)
-			break;
-
-		if (ChType == BAND_5G)
-		{
-			if (pChDesp->FirstChannel <= 14)
-				continue;
-		}
-		else if (ChType == BAND_24G)
-		{
-			if (pChDesp->FirstChannel > 14)
-				continue;
-		}
-
-		if ((pChDesp->Geography == BOTH)
-			|| (pChDesp->Geography == pAd->CommonCfg.Geography))
-		{
-			MakeOutgoingFrame(pBuf + *pBufLen,		&TmpLen,
-								1,                 	&pChDesp->FirstChannel,
-								1,                 	&pChDesp->NumOfCh,
-								1,                 	&pChDesp->MaxTxPwr,
-								END_OF_ARGS);
-			*pBufLen += TmpLen;
-		}
-	}
-}
-
-
-#ifdef DOT11_N_SUPPORT
-static inline BOOLEAN IsValidChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR channel)
-
-{
-	INT i;
-
-	for (i = 0; i < pAd->ChannelListNum; i++)
-	{
-		if (pAd->ChannelList[i].Channel == channel)
-			break;
-	}
-
-	if (i == pAd->ChannelListNum)
-		return FALSE;
-	else
-		return TRUE;
-}
-
-
-static inline UCHAR GetExtCh(
-	IN UCHAR Channel,
-	IN UCHAR Direction)
-{
-	CHAR ExtCh;
-
-	if (Direction == EXTCHA_ABOVE)
-		ExtCh = Channel + 4;
-	else
-		ExtCh = (Channel - 4) > 0 ? (Channel - 4) : 0;
-
-	return ExtCh;
-}
-
-
-static inline VOID N_ChannelCheck(
-	IN PRTMP_ADAPTER pAd)
-{
-	//UCHAR ChannelNum = pAd->ChannelListNum;
-	UCHAR Channel = pAd->CommonCfg.Channel;
-
-	if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED) && (pAd->CommonCfg.RegTransmitSetting.field.BW  == BW_40))
-	{
-		if (Channel > 14)
-		{
-			if ((Channel == 36) || (Channel == 44) || (Channel == 52) || (Channel == 60) || (Channel == 100) || (Channel == 108) ||
-			    (Channel == 116) || (Channel == 124) || (Channel == 132) || (Channel == 149) || (Channel == 157))
-			{
-				pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-			}
-			else if ((Channel == 40) || (Channel == 48) || (Channel == 56) || (Channel == 64) || (Channel == 104) || (Channel == 112) ||
-					(Channel == 120) || (Channel == 128) || (Channel == 136) || (Channel == 153) || (Channel == 161))
-			{
-				pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_BELOW;
-			}
-			else
-			{
-				pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-			}
-		}
-		else
-		{
-			do
-			{
-				UCHAR ExtCh;
-				UCHAR Dir = pAd->CommonCfg.RegTransmitSetting.field.EXTCHA;
-				ExtCh = GetExtCh(Channel, Dir);
-				if (IsValidChannel(pAd, ExtCh))
-					break;
-
-				Dir = (Dir == EXTCHA_ABOVE) ? EXTCHA_BELOW : EXTCHA_ABOVE;
-				ExtCh = GetExtCh(Channel, Dir);
-				if (IsValidChannel(pAd, ExtCh))
-				{
-					pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = Dir;
-					break;
-				}
-				pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-			} while(FALSE);
-
-			if (Channel == 14)
-			{
-				pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-				//pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_NONE;	// We didn't set the ExtCh as NONE due to it'll set in RTMPSetHT()
-			}
-#if 0
-			switch (pAd->CommonCfg.CountryRegion  & 0x7f)
-			{
-				case REGION_0_BG_BAND:	// 1 -11
-				case REGION_1_BG_BAND:	// 1 - 13
-				case REGION_5_BG_BAND:	// 1 - 14
-					if (Channel <= 4)
-					{
-						pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-					}
-					else if (Channel >= 8)
-					{
-						if ((ChannelNum - Channel) < 4)
-							pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_BELOW;
-					}
-					break;
-
-				case REGION_2_BG_BAND:	// 10 - 11
-				case REGION_3_BG_BAND:	// 10 - 13
-				case REGION_4_BG_BAND:	// 14
-					pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-					break;
-
-				case REGION_6_BG_BAND:	// 3 - 9
-					if (Channel <= 5)
-						pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-					else if (Channel == 6)
-						pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-					else if (Channel >= 7)
-						pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_BELOW;
-					break;
-
-				case REGION_7_BG_BAND:  // 5 - 13
-					if (Channel <= 8)
-						pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-					else if (Channel >= 10)
-						pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_BELOW;
-					break;
-
-				default:	// Error. should never happen
-					break;
-			}
-#endif
-		}
-	}
-
-
-}
-
-
-static inline VOID N_SetCenCh(
-	IN PRTMP_ADAPTER pAd)
-{
-	if (pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40)
-	{
-		if (pAd->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_ABOVE)
-		{
-			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel + 2;
-		}
-		else
-		{
-			if (pAd->CommonCfg.Channel == 14)
-				pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel - 1;
-			else
-				pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel - 2;
-		}
-	}
-	else
-	{
-		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
-	}
-}
-#endif // DOT11_N_SUPPORT //
-
-
-static inline UINT8 GetCuntryMaxTxPwr(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT8 channel)
-{
-	int i;
-	for (i = 0; i < pAd->ChannelListNum; i++)
-	{
-		if (pAd->ChannelList[i].Channel == channel)
-			break;
-	}
-
-	if (i == pAd->ChannelListNum)
-		return 0xff;
-	else
-		return pAd->ChannelList[i].MaxTxPwr;
-}
-#endif // __CHLIST_H__
-
+#include "../rt2860/chlist.h"
diff --git a/drivers/staging/rt2870/common/2870_rtmp_init.c b/drivers/staging/rt2870/common/2870_rtmp_init.c
index cb16d2f..0f4c8af 100644
--- a/drivers/staging/rt2870/common/2870_rtmp_init.c
+++ b/drivers/staging/rt2870/common/2870_rtmp_init.c
@@ -266,27 +266,6 @@
 		//
 		// MGMT_RING_SIZE
 		//
-#if 0
-		for(i=0; i<MGMT_RING_SIZE; i++) // 8
-		{
-			PTX_CONTEXT	pMLMEContext = &(pAd->MLMEContext[i]);
-
-
-			NdisZeroMemory(pMLMEContext, sizeof(TX_CONTEXT));
-
-			//Allocate URB
-			LM_USB_ALLOC(pObj, pMLMEContext, PTX_BUFFER, sizeof(TX_BUFFER), Status,
-							("<-- ERROR in Alloc TX MLMEContext[%d] urb!! \n", i),
-							out2,
-							("<-- ERROR in Alloc TX MLMEContext[%d] TX_BUFFER !! \n", i),
-							out2);
-
-			pMLMEContext->pAd = pAd;
-			pMLMEContext->pIrp = NULL;
-			pMLMEContext->InUse = FALSE;
-			pMLMEContext->IRPPending = FALSE;
-		}
-#else
 		// Allocate MGMT ring descriptor's memory
 		pAd->MgmtDescRing.AllocSize = MGMT_RING_SIZE * sizeof(TX_CONTEXT);
 		RTMPAllocateMemory(&pAd->MgmtDescRing.AllocVa, pAd->MgmtDescRing.AllocSize);
@@ -336,7 +315,6 @@
 		pAd->MgmtRing.TxSwFreeIdx = MGMT_RING_SIZE;
 		pAd->MgmtRing.TxCpuIdx = 0;
 		pAd->MgmtRing.TxDmaIdx = 0;
-#endif
 
 		//
 		// BEACON_RING_SIZE
@@ -518,10 +496,6 @@
 			NdisAllocateSpinLock(&pAd->TxContextQueueLock[num]);
 		}
 
-#ifdef RALINK_ATE
-		NdisAllocateSpinLock(&pAd->GenericLock);
-#endif // RALINK_ATE //
-
 //		NdisAllocateSpinLock(&pAd->MemLock);	// Not used in RT28XX
 
 //		NdisAllocateSpinLock(&pAd->MacTabLock); // init it in UserCfgInit()
@@ -665,7 +639,7 @@
 
 
 	// Free Tx frame resource
-	for (acidx = 0; acidx < 4; acidx++)
+		for(acidx=0; acidx<4; acidx++)
 		{
 		PHT_TX_CONTEXT pHTTXContext = &(pAd->TxContext[acidx]);
 			if (pHTTXContext)
@@ -684,9 +658,7 @@
 	NdisFreeSpinLock(&pAd->MLMEBulkOutLock);
 
 	NdisFreeSpinLock(&pAd->CmdQLock);
-#ifdef RALINK_ATE
-	NdisFreeSpinLock(&pAd->GenericLock);
-#endif // RALINK_ATE //
+
 	// Clear all pending bulk-out request flags.
 	RTUSB_CLEAR_BULK_FLAG(pAd, 0xffffffff);
 
@@ -727,9 +699,14 @@
 
 	usb_dev = pObj->pUsb_Dev;
 
+#ifndef RT30xx
 	pObj->MLMEThr_task		= NULL;
 	pObj->RTUSBCmdThr_task	= NULL;
-
+#endif
+#ifdef RT30xx
+	pObj->MLMEThr_pid	= NULL;
+	pObj->RTUSBCmdThr_pid	= NULL;
+#endif
 	*ppAd = (PVOID)vmalloc(sizeof(RTMP_ADAPTER));
 
 	if (*ppAd)
@@ -765,7 +742,12 @@
 {
 	PRTMP_ADAPTER pAd = net_dev->ml_priv;
 	POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;
+#ifndef RT30xx
 	struct task_struct *tsk;
+#endif
+#ifdef RT30xx
+	pid_t pid_number;
+#endif
 
 	//init_MUTEX(&(pAd->usbdev_semaphore));
 
@@ -779,39 +761,76 @@
 	init_completion (&pAd->TimerQComplete);
 
 	// Creat MLME Thread
+#ifndef RT30xx
 	pObj->MLMEThr_task = NULL;
-	tsk = kthread_run(MlmeThread, pAd, pAd->net_dev->name);
+	tsk = kthread_run(MlmeThread, pAd, "%s", pAd->net_dev->name);
 
 	if (IS_ERR(tsk)) {
+#endif
+#ifdef RT30xx
+	pObj->MLMEThr_pid = NULL;
+	pid_number = kernel_thread(MlmeThread, pAd, CLONE_VM);
+	if (pid_number < 0)
+	{
+#endif
 		printk (KERN_WARNING "%s: unable to start Mlme thread\n",pAd->net_dev->name);
 		return NDIS_STATUS_FAILURE;
 	}
 
+#ifndef RT30xx
 	pObj->MLMEThr_task = tsk;
+#endif
+#ifdef RT30xx
+	pObj->MLMEThr_pid = find_get_pid(pid_number);
+#endif
 	// Wait for the thread to start
 	wait_for_completion(&(pAd->mlmeComplete));
 
 	// Creat Command Thread
+#ifndef RT30xx
 	pObj->RTUSBCmdThr_task = NULL;
-	tsk = kthread_run(RTUSBCmdThread, pAd, pAd->net_dev->name);
+	tsk = kthread_run(RTUSBCmdThread, pAd, "%s", pAd->net_dev->name);
 
 	if (IS_ERR(tsk) < 0)
+#endif
+#ifdef RT30xx
+	pObj->RTUSBCmdThr_pid = NULL;
+	pid_number = kernel_thread(RTUSBCmdThread, pAd, CLONE_VM);
+	if (pid_number < 0)
+#endif
 	{
 		printk (KERN_WARNING "%s: unable to start RTUSBCmd thread\n",pAd->net_dev->name);
 		return NDIS_STATUS_FAILURE;
 	}
 
+#ifndef RT30xx
 	pObj->RTUSBCmdThr_task = tsk;
+#endif
+#ifdef RT30xx
+	pObj->RTUSBCmdThr_pid = find_get_pid(pid_number);
+#endif
 	wait_for_completion(&(pAd->CmdQComplete));
 
+#ifndef RT30xx
 	pObj->TimerQThr_task = NULL;
-	tsk = kthread_run(TimerQThread, pAd, pAd->net_dev->name);
+	tsk = kthread_run(TimerQThread, pAd, "%s", pAd->net_dev->name);
 	if (IS_ERR(tsk) < 0)
+#endif
+#ifdef RT30xx
+	pObj->TimerQThr_pid = NULL;
+	pid_number = kernel_thread(TimerQThread, pAd, CLONE_VM);
+	if (pid_number < 0)
+#endif
 	{
 		printk (KERN_WARNING "%s: unable to start TimerQThread\n",pAd->net_dev->name);
 		return NDIS_STATUS_FAILURE;
 	}
+#ifndef RT30xx
 	pObj->TimerQThr_task = tsk;
+#endif
+#ifdef RT30xx
+	pObj->TimerQThr_pid = find_get_pid(pid_number);
+#endif
 	// Wait for the thread to start
 	wait_for_completion(&(pAd->TimerQComplete));
 
@@ -831,8 +850,6 @@
 	return NDIS_STATUS_SUCCESS;
 }
 
-
-#ifdef CONFIG_STA_SUPPORT
 /*
 ========================================================================
 Routine Description:
@@ -1013,7 +1030,6 @@
 		DBGPRINT_RAW(RT_DEBUG_TRACE,(" %x:", pKey->KeyMaterial[i]));
 	DBGPRINT(RT_DEBUG_TRACE,("	 \n"));
 }
-#endif // CONFIG_STA_SUPPORT //
 
 /*
 ========================================================================
@@ -1084,18 +1100,13 @@
 	// skip USB frame length field
 	pData += RT2870_RXDMALEN_FIELD_SIZE;
 	pRxWI = (PRXWI_STRUC)pData;
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange(pData, TYPE_RXWI);
-#endif // RT_BIG_ENDIAN //
+
 	if (pRxWI->MPDUtotalByteCount > ThisFrameLen)
 	{
 		DBGPRINT(RT_DEBUG_ERROR, ("%s():pRxWIMPDUtotalByteCount(%d) large than RxDMALen(%ld)\n",
 									__func__, pRxWI->MPDUtotalByteCount, ThisFrameLen));
 		goto label_null;
 	}
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange(pData, TYPE_RXWI);
-#endif // RT_BIG_ENDIAN //
 
 	// allocate a rx packet
 	pSkb = dev_alloc_skb(ThisFrameLen);
@@ -1112,9 +1123,6 @@
 
 	// copy RxD
 	*pSaveRxD = *(PRXINFO_STRUC)(pData + ThisFrameLen);
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pSaveRxD, TYPE_RXINFO);
-#endif // RT_BIG_ENDIAN //
 
 	// update next packet read position.
 	pAd->ReadPosition += (ThisFrameLen + RT2870_RXDMALEN_FIELD_SIZE + RXINFO_SIZE);	// 8 for (RT2870_RXDMALEN_FIELD_SIZE + sizeof(RXINFO_STRUC))
@@ -1197,17 +1205,6 @@
 
 	ASSERT((pRxContext->InUse == pRxContext->IRPPending));
 
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-    {
-		// If the driver is in ATE mode and Rx frame is set into here.
-		if (pAd->ContinBulkIn == TRUE)
-		{
-			RTUSBBulkReceive(pAd);
-		}
-	}
-	else
-#endif // RALINK_ATE //
 	RTUSBBulkReceive(pAd);
 
 	return;
@@ -1310,9 +1307,9 @@
 	UCHAR				BulkOutPipeId = 4;
 	purbb_t				pUrb;
 
-
+#ifndef RT30xx
 	DBGPRINT_RAW(RT_DEBUG_ERROR, ("--->hcca_dma_done_tasklet\n"));
-
+#endif
 
 	pUrb			= (purbb_t)data;
 	pHTTXContext	= (PHT_TX_CONTEXT)pUrb->context;
@@ -1342,13 +1339,19 @@
 				RTMPDeQueuePacket(pAd, FALSE, BulkOutPipeId, MAX_TX_PROCESS);
 			}
 
+#ifndef RT30xx
 			RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL);
+#endif
+#ifdef RT30xx
+			RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL<<4);
+#endif
 			RTUSBKickBulkOut(pAd);
 		}
 	}
 
+#ifndef RT30xx
 	DBGPRINT_RAW(RT_DEBUG_ERROR, ("<---hcca_dma_done_tasklet\n"));
-
+#endif
 		return;
 }
 
diff --git a/drivers/staging/rt2870/common/action.c b/drivers/staging/rt2870/common/action.c
index 3a48a7f..fd806c3 100644
--- a/drivers/staging/rt2870/common/action.c
+++ b/drivers/staging/rt2870/common/action.c
@@ -1,1046 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-	action.c
-
-    Abstract:
-    Handle association related requests either from WSTA or from local MLME
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-	Jan Lee		2006	  	created for rt2860
- */
-
-#include "../rt_config.h"
-#include "action.h"
-
-
-static VOID ReservedAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-/*
-    ==========================================================================
-    Description:
-        association state machine init, including state transition and timer init
-    Parameters:
-        S - pointer to the association state machine
-    Note:
-        The state machine looks like the following
-
-                                    ASSOC_IDLE
-        MT2_MLME_DISASSOC_REQ    mlme_disassoc_req_action
-        MT2_PEER_DISASSOC_REQ    peer_disassoc_action
-        MT2_PEER_ASSOC_REQ       drop
-        MT2_PEER_REASSOC_REQ     drop
-        MT2_CLS3ERR              cls3err_action
-    ==========================================================================
- */
-VOID ActionStateMachineInit(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  STATE_MACHINE *S,
-    OUT STATE_MACHINE_FUNC Trans[])
-{
-	StateMachineInit(S, (STATE_MACHINE_FUNC *)Trans, MAX_ACT_STATE, MAX_ACT_MSG, (STATE_MACHINE_FUNC)Drop, ACT_IDLE, ACT_MACHINE_BASE);
-
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_SPECTRUM_CATE, (STATE_MACHINE_FUNC)PeerSpectrumAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_QOS_CATE, (STATE_MACHINE_FUNC)PeerQOSAction);
-
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_DLS_CATE, (STATE_MACHINE_FUNC)ReservedAction);
-#ifdef QOS_DLS_SUPPORT
-		StateMachineSetAction(S, ACT_IDLE, MT2_PEER_DLS_CATE, (STATE_MACHINE_FUNC)PeerDLSAction);
-#endif // QOS_DLS_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_BA_CATE, (STATE_MACHINE_FUNC)PeerBAAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_HT_CATE, (STATE_MACHINE_FUNC)PeerHTAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_ADD_BA_CATE, (STATE_MACHINE_FUNC)MlmeADDBAAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_ORI_DELBA_CATE, (STATE_MACHINE_FUNC)MlmeDELBAAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_REC_DELBA_CATE, (STATE_MACHINE_FUNC)MlmeDELBAAction);
-#endif // DOT11_N_SUPPORT //
-
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_PUBLIC_CATE, (STATE_MACHINE_FUNC)PeerPublicAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_RM_CATE, (STATE_MACHINE_FUNC)PeerRMAction);
-
-	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_QOS_CATE, (STATE_MACHINE_FUNC)MlmeQOSAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_DLS_CATE, (STATE_MACHINE_FUNC)MlmeDLSAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_ACT_INVALID, (STATE_MACHINE_FUNC)MlmeInvalidAction);
-}
-
-#ifdef DOT11_N_SUPPORT
-VOID MlmeADDBAAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-
-{
-	MLME_ADDBA_REQ_STRUCT *pInfo;
-	UCHAR           Addr[6];
-	PUCHAR         pOutBuffer = NULL;
-	NDIS_STATUS     NStatus;
-	ULONG		Idx;
-	FRAME_ADDBA_REQ  Frame;
-	ULONG		FrameLen;
-	BA_ORI_ENTRY			*pBAEntry = NULL;
-
-	pInfo = (MLME_ADDBA_REQ_STRUCT *)Elem->Msg;
-	NdisZeroMemory(&Frame, sizeof(FRAME_ADDBA_REQ));
-
-	if(MlmeAddBAReqSanity(pAd, Elem->Msg, Elem->MsgLen, Addr))
-	{
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-		if(NStatus != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("BA - MlmeADDBAAction() allocate memory failed \n"));
-			return;
-		}
-		// 1. find entry
-		Idx = pAd->MacTab.Content[pInfo->Wcid].BAOriWcidArray[pInfo->TID];
-		if (Idx == 0)
-		{
-			MlmeFreeMemory(pAd, pOutBuffer);
-			DBGPRINT(RT_DEBUG_ERROR,("BA - MlmeADDBAAction() can't find BAOriEntry \n"));
-			return;
-		}
-		else
-		{
-			pBAEntry =&pAd->BATable.BAOriEntry[Idx];
-		}
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			if (ADHOC_ON(pAd))
-				ActHeaderInit(pAd, &Frame.Hdr, pInfo->pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-			else
-#ifdef QOS_DLS_SUPPORT
-			if (pAd->MacTab.Content[pInfo->Wcid].ValidAsDls)
-				ActHeaderInit(pAd, &Frame.Hdr, pInfo->pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-			else
-#endif // QOS_DLS_SUPPORT //
-				ActHeaderInit(pAd, &Frame.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pInfo->pAddr);
-
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		Frame.Category = CATEGORY_BA;
-		Frame.Action = ADDBA_REQ;
-		Frame.BaParm.AMSDUSupported = 0;
-		Frame.BaParm.BAPolicy = IMMED_BA;
-		Frame.BaParm.TID = pInfo->TID;
-		Frame.BaParm.BufSize = pInfo->BaBufSize;
-		Frame.Token = pInfo->Token;
-		Frame.TimeOutValue = pInfo->TimeOutValue;
-		Frame.BaStartSeq.field.FragNum = 0;
-		Frame.BaStartSeq.field.StartSeq = pAd->MacTab.Content[pInfo->Wcid].TxSeq[pInfo->TID];
-
-		*(USHORT *)(&Frame.BaParm) = cpu2le16(*(USHORT *)(&Frame.BaParm));
-		Frame.TimeOutValue = cpu2le16(Frame.TimeOutValue);
-		Frame.BaStartSeq.word = cpu2le16(Frame.BaStartSeq.word);
-
-		MakeOutgoingFrame(pOutBuffer,		   &FrameLen,
-		              sizeof(FRAME_ADDBA_REQ), &Frame,
-		              END_OF_ARGS);
-		MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("BA - Send ADDBA request. StartSeq = %x,  FrameLen = %ld. BufSize = %d\n", Frame.BaStartSeq.field.StartSeq, FrameLen, Frame.BaParm.BufSize));
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-        send DELBA and delete BaEntry if any
-    Parametrs:
-        Elem - MLME message MLME_DELBA_REQ_STRUCT
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeDELBAAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	MLME_DELBA_REQ_STRUCT *pInfo;
-	PUCHAR         pOutBuffer = NULL;
-	PUCHAR		   pOutBuffer2 = NULL;
-	NDIS_STATUS     NStatus;
-	ULONG		Idx;
-	FRAME_DELBA_REQ  Frame;
-	ULONG		FrameLen;
-	FRAME_BAR	FrameBar;
-
-	pInfo = (MLME_DELBA_REQ_STRUCT *)Elem->Msg;
-	// must send back DELBA
-	NdisZeroMemory(&Frame, sizeof(FRAME_DELBA_REQ));
-	DBGPRINT(RT_DEBUG_TRACE, ("==> MlmeDELBAAction(), Initiator(%d) \n", pInfo->Initiator));
-
-	if(MlmeDelBAReqSanity(pAd, Elem->Msg, Elem->MsgLen))
-	{
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-		if(NStatus != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_ERROR,("BA - MlmeDELBAAction() allocate memory failed 1. \n"));
-			return;
-		}
-
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer2);  //Get an unused nonpaged memory
-		if(NStatus != NDIS_STATUS_SUCCESS)
-		{
-			MlmeFreeMemory(pAd, pOutBuffer);
-			DBGPRINT(RT_DEBUG_ERROR, ("BA - MlmeDELBAAction() allocate memory failed 2. \n"));
-			return;
-		}
-
-		// SEND BAR (Send BAR to refresh peer reordering buffer.)
-		Idx = pAd->MacTab.Content[pInfo->Wcid].BAOriWcidArray[pInfo->TID];
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			BarHeaderInit(pAd, &FrameBar, pAd->MacTab.Content[pInfo->Wcid].Addr, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
-
-		FrameBar.StartingSeq.field.FragNum = 0; // make sure sequence not clear in DEL funciton.
-		FrameBar.StartingSeq.field.StartSeq = pAd->MacTab.Content[pInfo->Wcid].TxSeq[pInfo->TID]; // make sure sequence not clear in DEL funciton.
-		FrameBar.BarControl.TID = pInfo->TID; // make sure sequence not clear in DEL funciton.
-		FrameBar.BarControl.ACKPolicy = IMMED_BA; // make sure sequence not clear in DEL funciton.
-		FrameBar.BarControl.Compressed = 1; // make sure sequence not clear in DEL funciton.
-		FrameBar.BarControl.MTID = 0; // make sure sequence not clear in DEL funciton.
-
-		MakeOutgoingFrame(pOutBuffer2,				&FrameLen,
-					  sizeof(FRAME_BAR),	  &FrameBar,
-					  END_OF_ARGS);
-		MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer2, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer2);
-		DBGPRINT(RT_DEBUG_TRACE,("BA - MlmeDELBAAction() . Send BAR to refresh peer reordering buffer \n"));
-
-		// SEND DELBA FRAME
-		FrameLen = 0;
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			if (ADHOC_ON(pAd))
-				ActHeaderInit(pAd, &Frame.Hdr, pAd->MacTab.Content[pInfo->Wcid].Addr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-			else
-#ifdef QOS_DLS_SUPPORT
-			if (pAd->MacTab.Content[pInfo->Wcid].ValidAsDls)
-				ActHeaderInit(pAd, &Frame.Hdr, pAd->MacTab.Content[pInfo->Wcid].Addr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-			else
-#endif // QOS_DLS_SUPPORT //
-				ActHeaderInit(pAd, &Frame.Hdr,  pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->MacTab.Content[pInfo->Wcid].Addr);
-		}
-#endif // CONFIG_STA_SUPPORT //
-		Frame.Category = CATEGORY_BA;
-		Frame.Action = DELBA;
-		Frame.DelbaParm.Initiator = pInfo->Initiator;
-		Frame.DelbaParm.TID = pInfo->TID;
-		Frame.ReasonCode = 39; // Time Out
-		*(USHORT *)(&Frame.DelbaParm) = cpu2le16(*(USHORT *)(&Frame.DelbaParm));
-		Frame.ReasonCode = cpu2le16(Frame.ReasonCode);
-
-		MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-		              sizeof(FRAME_DELBA_REQ),    &Frame,
-		              END_OF_ARGS);
-		MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer);
-		DBGPRINT(RT_DEBUG_TRACE, ("BA - MlmeDELBAAction() . 3 DELBA sent. Initiator(%d)\n", pInfo->Initiator));
-    	}
-}
-#endif // DOT11_N_SUPPORT //
-
-VOID MlmeQOSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-}
-
-VOID MlmeDLSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-}
-
-VOID MlmeInvalidAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	//PUCHAR		   pOutBuffer = NULL;
-	//Return the receiving frame except the MSB of category filed set to 1.  7.3.1.11
-}
-
-VOID PeerQOSAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-}
-
-#ifdef QOS_DLS_SUPPORT
-VOID PeerDLSAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-
-	switch(Action)
-	{
-		case ACTION_DLS_REQUEST:
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			PeerDlsReqAction(pAd, Elem);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-
-		case ACTION_DLS_RESPONSE:
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			PeerDlsRspAction(pAd, Elem);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-
-		case ACTION_DLS_TEARDOWN:
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			PeerDlsTearDownAction(pAd, Elem);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-	}
-}
-#endif // QOS_DLS_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-VOID PeerBAAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-
-	switch(Action)
-	{
-		case ADDBA_REQ:
-			PeerAddBAReqAction(pAd,Elem);
-			break;
-		case ADDBA_RESP:
-			PeerAddBARspAction(pAd,Elem);
-			break;
-		case DELBA:
-			PeerDelBAAction(pAd,Elem);
-			break;
-	}
-}
-
-
-#ifdef DOT11N_DRAFT3
-
-#ifdef CONFIG_STA_SUPPORT
-VOID StaPublicAction(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR Bss2040Coexist)
-{
-	BSS_2040_COEXIST_IE		BssCoexist;
-	MLME_SCAN_REQ_STRUCT			ScanReq;
-
-	BssCoexist.word = Bss2040Coexist;
-	// AP asks Station to return a 20/40 BSS Coexistence mgmt frame.  So we first starts a scan, then send back 20/40 BSS Coexistence mgmt frame
-	if ((BssCoexist.field.InfoReq == 1) && (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SCAN_2040)))
-	{
-		// Clear record first.  After scan , will update those bit and send back to transmiter.
-		pAd->CommonCfg.BSSCoexist2040.field.InfoReq = 1;
-		pAd->CommonCfg.BSSCoexist2040.field.Intolerant40 = 0;
-		pAd->CommonCfg.BSSCoexist2040.field.BSS20WidthReq = 0;
-		// Fill out stuff for scan request
-		ScanParmFill(pAd, &ScanReq, ZeroSsid, 0, BSS_ANY, SCAN_2040_BSS_COEXIST);
-		MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-	}
-}
-
-
-/*
-Description : Build Intolerant Channel Rerpot from Trigger event table.
-return : how many bytes copied.
-*/
-ULONG BuildIntolerantChannelRep(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    PUCHAR  pDest)
-{
-	ULONG			FrameLen = 0;
-	ULONG			ReadOffset = 0;
-	UCHAR			i;
-	UCHAR			LastRegClass = 0xff;
-	PUCHAR			pLen;
-
-	for ( i = 0;i < MAX_TRIGGER_EVENT;i++)
-	{
-		if (pAd->CommonCfg.TriggerEventTab.EventA[i].bValid == TRUE)
-		{
-			if (pAd->CommonCfg.TriggerEventTab.EventA[i].RegClass == LastRegClass)
-			{
-				*(pDest + ReadOffset) = (UCHAR)pAd->CommonCfg.TriggerEventTab.EventA[i].Channel;
-				*pLen++;
-				ReadOffset++;
-				FrameLen++;
-			}
-			else
-			{
-				*(pDest + ReadOffset) = IE_2040_BSS_INTOLERANT_REPORT;  // IE
-				*(pDest + ReadOffset + 1) = 2;	// Len = RegClass byte + channel byte.
-				pLen = pDest + ReadOffset + 1;
-				LastRegClass = pAd->CommonCfg.TriggerEventTab.EventA[i].RegClass;
-				*(pDest + ReadOffset + 2) = LastRegClass;	// Len = RegClass byte + channel byte.
-				*(pDest + ReadOffset + 3) = (UCHAR)pAd->CommonCfg.TriggerEventTab.EventA[i].Channel;
-				FrameLen += 4;
-				ReadOffset += 4;
-			}
-
-		}
-	}
-	return FrameLen;
-}
-
-
-/*
-Description : Send 20/40 BSS Coexistence Action frame If one trigger event is triggered.
-*/
-VOID Send2040CoexistAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS 	NStatus;
-	FRAME_ACTION_HDR	Frame;
-	ULONG			FrameLen;
-	ULONG			IntolerantChaRepLen;
-
-	IntolerantChaRepLen = 0;
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("ACT - Send2040CoexistAction() allocate memory failed \n"));
-		return;
-	}
-	ActHeaderInit(pAd, &Frame.Hdr, pAd->MacTab.Content[Wcid].Addr, pAd->CommonCfg.Bssid);
-	Frame.Category = CATEGORY_PUBLIC;
-	Frame.Action = ACTION_BSS_2040_COEXIST;
-
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-				  sizeof(FRAME_ACTION_HDR),	  &Frame,
-				  END_OF_ARGS);
-
-	*(pOutBuffer + FrameLen) = pAd->CommonCfg.BSSCoexist2040.word;
-	FrameLen++;
-
-	if (bAddIntolerantCha == TRUE)
-		IntolerantChaRepLen = BuildIntolerantChannelRep(pAd, pOutBuffer + FrameLen);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen + IntolerantChaRepLen);
-	DBGPRINT(RT_DEBUG_ERROR,("ACT - Send2040CoexistAction( BSSCoexist2040 = 0x%x )  \n", pAd->CommonCfg.BSSCoexist2040.word));
-
-}
-
-
-/*
-	==========================================================================
-	Description:
-	After scan, Update 20/40 BSS Coexistence IE and send out.
-	According to 802.11n D3.03 11.14.10
-
-	Parameters:
-	==========================================================================
- */
-VOID Update2040CoexistFrameAndNotify(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha)
-{
-	BSS_2040_COEXIST_IE	OldValue;
-
-	OldValue.word = pAd->CommonCfg.BSSCoexist2040.word;
-	if ((pAd->CommonCfg.TriggerEventTab.EventANo > 0) || (pAd->CommonCfg.TriggerEventTab.EventBCountDown > 0))
-		pAd->CommonCfg.BSSCoexist2040.field.BSS20WidthReq = 1;
-
-	// Need to check !!!!
-	// How STA will set Intolerant40 if implementation dependent. Now we don't set this bit first.!!!!!
-	// So Only check BSS20WidthReq change.
-	if (OldValue.field.BSS20WidthReq != pAd->CommonCfg.BSSCoexist2040.field.BSS20WidthReq)
-	{
-		Send2040CoexistAction(pAd, Wcid, bAddIntolerantCha);
-	}
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-BOOLEAN ChannelSwitchSanityCheck(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  NewChannel,
-	IN    UCHAR  Secondary)
-{
-	UCHAR		i;
-
-	if (Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return FALSE;
-
-	if ((NewChannel > 7) && (Secondary == 1))
-		return FALSE;
-
-	if ((NewChannel < 5) && (Secondary == 3))
-		return FALSE;
-
-	// 0. Check if new channel is in the channellist.
-	for (i = 0;i < pAd->ChannelListNum;i++)
-	{
-		if (pAd->ChannelList[i].Channel == NewChannel)
-		{
-			break;
-		}
-	}
-
-	if (i == pAd->ChannelListNum)
-		return FALSE;
-
-	return TRUE;
-}
-
-
-VOID ChannelSwitchAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  NewChannel,
-	IN    UCHAR  Secondary)
-{
-	UCHAR		BBPValue = 0;
-	ULONG		MACValue;
-
-	DBGPRINT(RT_DEBUG_TRACE,("SPECTRUM - ChannelSwitchAction(NewChannel = %d , Secondary = %d)  \n", NewChannel, Secondary));
-
-	if (ChannelSwitchSanityCheck(pAd, Wcid, NewChannel, Secondary) == FALSE)
-		return;
-
-	// 1.  Switches to BW = 20.
-	if (Secondary == 0)
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-		BBPValue&= (~0x18);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-		if (pAd->MACVersion == 0x28600100)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x16);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x08);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x11);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
-		}
-		pAd->CommonCfg.BBPCurrentBW = BW_20;
-		pAd->CommonCfg.Channel = NewChannel;
-		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.Channel,FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-		pAd->MacTab.Content[Wcid].HTPhyMode.field.BW = 0;
-		DBGPRINT(RT_DEBUG_TRACE, ("!!!20MHz   !!! \n" ));
-	}
-	// 1.  Switches to BW = 40 And Station supports BW = 40.
-	else if (((Secondary == 1) || (Secondary == 3)) && (pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth == 1))
-	{
-		pAd->CommonCfg.Channel = NewChannel;
-
-		if (Secondary == 1)
-		{
-			// Secondary above.
-			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel + 2;
-			RTMP_IO_READ32(pAd, TX_BAND_CFG, &MACValue);
-			MACValue &= 0xfe;
-			RTMP_IO_WRITE32(pAd, TX_BAND_CFG, MACValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue&= (~0x18);
-			BBPValue|= (0x10);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPValue);
-			BBPValue&= (~0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPValue);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!!40MHz Lower LINK UP !!! Control Channel at Below. Central = %d \n", pAd->CommonCfg.CentralChannel ));
-		}
-		else
-		{
-			// Secondary below.
-			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel - 2;
-			RTMP_IO_READ32(pAd, TX_BAND_CFG, &MACValue);
-			MACValue &= 0xfe;
-			MACValue |= 0x1;
-			RTMP_IO_WRITE32(pAd, TX_BAND_CFG, MACValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue&= (~0x18);
-			BBPValue|= (0x10);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPValue);
-			BBPValue&= (~0x20);
-			BBPValue|= (0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPValue);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!!40MHz Upper LINK UP !!! Control Channel at UpperCentral = %d \n", pAd->CommonCfg.CentralChannel ));
-		}
-		pAd->CommonCfg.BBPCurrentBW = BW_40;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-		pAd->MacTab.Content[Wcid].HTPhyMode.field.BW = 1;
-	}
-}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-VOID PeerPublicAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-#ifdef DOT11N_DRAFT3
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-#endif // DOT11N_DRAFT3 //
-
-	if (Elem->Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return;
-
-#ifdef DOT11N_DRAFT3
-	switch(Action)
-	{
-		case ACTION_BSS_2040_COEXIST:	// Format defined in IEEE 7.4.7a.1 in 11n Draf3.03
-			{
-				//UCHAR	BssCoexist;
-				BSS_2040_COEXIST_ELEMENT		*pCoexistInfo;
-				BSS_2040_COEXIST_IE 			*pBssCoexistIe;
-				BSS_2040_INTOLERANT_CH_REPORT	*pIntolerantReport = NULL;
-
-				if (Elem->MsgLen <= (LENGTH_802_11 + sizeof(BSS_2040_COEXIST_ELEMENT)) )
-				{
-					DBGPRINT(RT_DEBUG_ERROR, ("ACTION - 20/40 BSS Coexistence Management Frame length too short! len = %ld!\n", Elem->MsgLen));
-					break;
-				}
-				DBGPRINT(RT_DEBUG_TRACE, ("ACTION - 20/40 BSS Coexistence Management action----> \n"));
-				hex_dump("CoexistenceMgmtFrame", Elem->Msg, Elem->MsgLen);
-
-
-				pCoexistInfo = (BSS_2040_COEXIST_ELEMENT *) &Elem->Msg[LENGTH_802_11+2];
-				//hex_dump("CoexistInfo", (PUCHAR)pCoexistInfo, sizeof(BSS_2040_COEXIST_ELEMENT));
-				if (Elem->MsgLen >= (LENGTH_802_11 + sizeof(BSS_2040_COEXIST_ELEMENT) + sizeof(BSS_2040_INTOLERANT_CH_REPORT)))
-				{
-					pIntolerantReport = (BSS_2040_INTOLERANT_CH_REPORT *)((PUCHAR)pCoexistInfo + sizeof(BSS_2040_COEXIST_ELEMENT));
-				}
-				//hex_dump("IntolerantReport ", (PUCHAR)pIntolerantReport, sizeof(BSS_2040_INTOLERANT_CH_REPORT));
-
-				pBssCoexistIe = (BSS_2040_COEXIST_IE *)(&pCoexistInfo->BssCoexistIe);
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-					if (INFRA_ON(pAd))
-					{
-						StaPublicAction(pAd, pCoexistInfo);
-					}
-				}
-#endif // CONFIG_STA_SUPPORT //
-
-			}
-			break;
-	}
-
-#endif // DOT11N_DRAFT3 //
-
-}
-
-
-static VOID ReservedAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR Category;
-
-	if (Elem->MsgLen <= LENGTH_802_11)
-	{
-		return;
-	}
-
-	Category = Elem->Msg[LENGTH_802_11];
-	DBGPRINT(RT_DEBUG_TRACE,("Rcv reserved category(%d) Action Frame\n", Category));
-	hex_dump("Reserved Action Frame", &Elem->Msg[0], Elem->MsgLen);
-}
-
-VOID PeerRMAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-
-{
-	return;
-}
-
-#ifdef DOT11_N_SUPPORT
-static VOID respond_ht_information_exchange_action(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen;
-	FRAME_HT_INFO	HTINFOframe, *pFrame;
-	UCHAR   		*pAddr;
-
-
-	// 2. Always send back ADDBA Response
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);	 //Get an unused nonpaged memory
-
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("ACTION - respond_ht_information_exchange_action() allocate memory failed \n"));
-		return;
-	}
-
-	// get RA
-	pFrame = (FRAME_HT_INFO *) &Elem->Msg[0];
-	pAddr = pFrame->Hdr.Addr2;
-
-	NdisZeroMemory(&HTINFOframe, sizeof(FRAME_HT_INFO));
-	// 2-1. Prepare ADDBA Response frame.
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (ADHOC_ON(pAd))
-			ActHeaderInit(pAd, &HTINFOframe.Hdr, pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-		else
-			ActHeaderInit(pAd, &HTINFOframe.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAddr);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	HTINFOframe.Category = CATEGORY_HT;
-	HTINFOframe.Action = HT_INFO_EXCHANGE;
-	HTINFOframe.HT_Info.Request = 0;
-	HTINFOframe.HT_Info.Forty_MHz_Intolerant = pAd->CommonCfg.HtCapability.HtCapInfo.Forty_Mhz_Intolerant;
-	HTINFOframe.HT_Info.STA_Channel_Width	 = pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth;
-
-	MakeOutgoingFrame(pOutBuffer,					&FrameLen,
-					  sizeof(FRAME_HT_INFO),	&HTINFOframe,
-					  END_OF_ARGS);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-}
-
-
-#ifdef DOT11N_DRAFT3
-VOID SendNotifyBWActionFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR  Wcid,
-	IN UCHAR apidx)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS 	NStatus;
-	FRAME_ACTION_HDR	Frame;
-	ULONG			FrameLen;
-	PUCHAR			pAddr1;
-
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("ACT - SendNotifyBWAction() allocate memory failed \n"));
-		return;
-	}
-
-	if (Wcid == MCAST_WCID)
-		pAddr1 = &BROADCAST_ADDR[0];
-	else
-		pAddr1 = pAd->MacTab.Content[Wcid].Addr;
-	ActHeaderInit(pAd, &Frame.Hdr, pAddr1, pAd->ApCfg.MBSSID[apidx].Bssid, pAd->ApCfg.MBSSID[apidx].Bssid);
-
-	Frame.Category = CATEGORY_HT;
-	Frame.Action = NOTIFY_BW_ACTION;
-
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-				  sizeof(FRAME_ACTION_HDR),	  &Frame,
-				  END_OF_ARGS);
-
-	*(pOutBuffer + FrameLen) = pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth;
-	FrameLen++;
-
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	DBGPRINT(RT_DEBUG_TRACE,("ACT - SendNotifyBWAction(NotifyBW= %d)!\n", pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth));
-
-}
-#endif // DOT11N_DRAFT3 //
-
-
-VOID PeerHTAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-
-	if (Elem->Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return;
-
-	switch(Action)
-	{
-		case NOTIFY_BW_ACTION:
-			DBGPRINT(RT_DEBUG_TRACE,("ACTION - HT Notify Channel bandwidth action----> \n"));
-#ifdef CONFIG_STA_SUPPORT
-			if(pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE)
-			{
-				// Note, this is to patch DIR-1353 AP. When the AP set to Wep, it will use legacy mode. But AP still keeps
-				// sending BW_Notify Action frame, and cause us to linkup and linkdown.
-				// In legacy mode, don't need to parse HT action frame.
-				DBGPRINT(RT_DEBUG_TRACE,("ACTION -Ignore HT Notify Channel BW when link as legacy mode. BW = %d---> \n",
-								Elem->Msg[LENGTH_802_11+2] ));
-				break;
-			}
-#endif // CONFIG_STA_SUPPORT //
-
-			if (Elem->Msg[LENGTH_802_11+2] == 0)	// 7.4.8.2. if value is 1, keep the same as supported channel bandwidth.
-				pAd->MacTab.Content[Elem->Wcid].HTPhyMode.field.BW = 0;
-
-			break;
-
-		case SMPS_ACTION:
-			// 7.3.1.25
- 			DBGPRINT(RT_DEBUG_TRACE,("ACTION - SMPS action----> \n"));
-			if (((Elem->Msg[LENGTH_802_11+2]&0x1) == 0))
-			{
-				pAd->MacTab.Content[Elem->Wcid].MmpsMode = MMPS_ENABLE;
-			}
-			else if (((Elem->Msg[LENGTH_802_11+2]&0x2) == 0))
-			{
-				pAd->MacTab.Content[Elem->Wcid].MmpsMode = MMPS_STATIC;
-			}
-			else
-			{
-				pAd->MacTab.Content[Elem->Wcid].MmpsMode = MMPS_DYNAMIC;
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE,("Aid(%d) MIMO PS = %d\n", Elem->Wcid, pAd->MacTab.Content[Elem->Wcid].MmpsMode));
-			// rt2860c : add something for smps change.
-			break;
-
-		case SETPCO_ACTION:
-			break;
-
-		case MIMO_CHA_MEASURE_ACTION:
-			break;
-
-		case HT_INFO_EXCHANGE:
-			{
-				HT_INFORMATION_OCTET	*pHT_info;
-
-				pHT_info = (HT_INFORMATION_OCTET *) &Elem->Msg[LENGTH_802_11+2];
-    				// 7.4.8.10
-    				DBGPRINT(RT_DEBUG_TRACE,("ACTION - HT Information Exchange action----> \n"));
-    				if (pHT_info->Request)
-    				{
-    					respond_ht_information_exchange_action(pAd, Elem);
-    				}
-			}
-    			break;
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Retry sending ADDBA Reqest.
-
-	IRQL = DISPATCH_LEVEL
-
-	Parametrs:
-	p8023Header: if this is already 802.3 format, p8023Header is NULL
-
-	Return	: TRUE if put into rx reordering buffer, shouldn't indicaterxhere.
-				FALSE , then continue indicaterx at this moment.
-	==========================================================================
- */
-VOID ORIBATimerTimeout(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	MAC_TABLE_ENTRY	*pEntry;
-	INT			i, total;
-//	FRAME_BAR			FrameBar;
-//	ULONG			FrameLen;
-//	NDIS_STATUS 	NStatus;
-//	PUCHAR			pOutBuffer = NULL;
-//	USHORT			Sequence;
-	UCHAR			TID;
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	total = pAd->MacTab.Size * NUM_OF_TID;
-
-	for (i = 1; ((i <MAX_LEN_OF_BA_ORI_TABLE) && (total > 0)) ; i++)
-	{
-		if  (pAd->BATable.BAOriEntry[i].ORI_BA_Status == Originator_Done)
-		{
-			pEntry = &pAd->MacTab.Content[pAd->BATable.BAOriEntry[i].Wcid];
-			TID = pAd->BATable.BAOriEntry[i].TID;
-
-			ASSERT(pAd->BATable.BAOriEntry[i].Wcid < MAX_LEN_OF_MAC_TABLE);
-		}
-		total --;
-	}
-}
-
-
-VOID SendRefreshBAR(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry)
-{
-	FRAME_BAR		FrameBar;
-	ULONG			FrameLen;
-	NDIS_STATUS 	NStatus;
-	PUCHAR			pOutBuffer = NULL;
-	USHORT			Sequence;
-	UCHAR			i, TID;
-	USHORT			idx;
-	BA_ORI_ENTRY	*pBAEntry;
-
-	for (i = 0; i <NUM_OF_TID; i++)
-	{
-		idx = pEntry->BAOriWcidArray[i];
-		if (idx == 0)
-		{
-			continue;
-		}
-		pBAEntry = &pAd->BATable.BAOriEntry[idx];
-
-		if  (pBAEntry->ORI_BA_Status == Originator_Done)
-		{
-			TID = pBAEntry->TID;
-
-			ASSERT(pBAEntry->Wcid < MAX_LEN_OF_MAC_TABLE);
-
-			NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-			if(NStatus != NDIS_STATUS_SUCCESS)
-			{
-				DBGPRINT(RT_DEBUG_ERROR,("BA - MlmeADDBAAction() allocate memory failed \n"));
-				return;
-			}
-
-			Sequence = pEntry->TxSeq[TID];
-
-
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				BarHeaderInit(pAd, &FrameBar, pEntry->Addr, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
-
-			FrameBar.StartingSeq.field.FragNum = 0; // make sure sequence not clear in DEL function.
-			FrameBar.StartingSeq.field.StartSeq = Sequence; // make sure sequence not clear in DEL funciton.
-			FrameBar.BarControl.TID = TID; // make sure sequence not clear in DEL funciton.
-
-			MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-							  sizeof(FRAME_BAR),	  &FrameBar,
-							  END_OF_ARGS);
-			//if (!(CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_RALINK_CHIPSET)))
-			if (1)	// Now we always send BAR.
-			{
-				//MiniportMMRequestUnlock(pAd, 0, pOutBuffer, FrameLen);
-				MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-			}
-			MlmeFreeMemory(pAd, pOutBuffer);
-		}
-	}
-}
-#endif // DOT11_N_SUPPORT //
-
-VOID ActHeaderInit(
-    IN	PRTMP_ADAPTER	pAd,
-    IN OUT PHEADER_802_11 pHdr80211,
-    IN PUCHAR Addr1,
-    IN PUCHAR Addr2,
-    IN PUCHAR Addr3)
-{
-    NdisZeroMemory(pHdr80211, sizeof(HEADER_802_11));
-    pHdr80211->FC.Type = BTYPE_MGMT;
-    pHdr80211->FC.SubType = SUBTYPE_ACTION;
-
-    COPY_MAC_ADDR(pHdr80211->Addr1, Addr1);
-	COPY_MAC_ADDR(pHdr80211->Addr2, Addr2);
-    COPY_MAC_ADDR(pHdr80211->Addr3, Addr3);
-}
-
-VOID BarHeaderInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN OUT PFRAME_BAR pCntlBar,
-	IN PUCHAR pDA,
-	IN PUCHAR pSA)
-{
-//	USHORT	Duration;
-
-	NdisZeroMemory(pCntlBar, sizeof(FRAME_BAR));
-	pCntlBar->FC.Type = BTYPE_CNTL;
-	pCntlBar->FC.SubType = SUBTYPE_BLOCK_ACK_REQ;
-   	pCntlBar->BarControl.MTID = 0;
-	pCntlBar->BarControl.Compressed = 1;
-	pCntlBar->BarControl.ACKPolicy = 0;
-
-
-	pCntlBar->Duration = 16 + RTMPCalcDuration(pAd, RATE_1, sizeof(FRAME_BA));
-
-	COPY_MAC_ADDR(pCntlBar->Addr1, pDA);
-	COPY_MAC_ADDR(pCntlBar->Addr2, pSA);
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Insert Category and action code into the action frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. category code of the frame.
-		4. action code of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID InsertActField(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN UINT8 Category,
-	IN UINT8 ActCode)
-{
-	ULONG TempLen;
-
-	MakeOutgoingFrame(	pFrameBuf,		&TempLen,
-						1,				&Category,
-						1,				&ActCode,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-	return;
-}
+#include "../../rt2860/common/action.c"
diff --git a/drivers/staging/rt2870/common/action.h b/drivers/staging/rt2870/common/action.h
index ce3877d..9a18955 100644
--- a/drivers/staging/rt2870/common/action.h
+++ b/drivers/staging/rt2870/common/action.h
@@ -1,68 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	aironet.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-	Paul Lin	04-06-15		Initial
-*/
-
-#ifndef	__ACTION_H__
-#define	__ACTION_H__
-
-typedef struct PACKED __HT_INFO_OCTET
-{
-#ifdef RT_BIG_ENDIAN
-	UCHAR	Reserved:5;
-	UCHAR 	STA_Channel_Width:1;
-	UCHAR	Forty_MHz_Intolerant:1;
-	UCHAR	Request:1;
-#else
-	UCHAR	Request:1;
-	UCHAR	Forty_MHz_Intolerant:1;
-	UCHAR 	STA_Channel_Width:1;
-	UCHAR	Reserved:5;
-#endif
-} HT_INFORMATION_OCTET;
-
-
-typedef struct PACKED __FRAME_HT_INFO
-{
-	HEADER_802_11   		Hdr;
-	UCHAR					Category;
-	UCHAR					Action;
-	HT_INFORMATION_OCTET	HT_Info;
-}   FRAME_HT_INFO, *PFRAME_HT_INFO;
-
-#endif /* __ACTION_H__ */
-
-
+#include "../../rt2860/common/action.h"
diff --git a/drivers/staging/rt2870/common/ba_action.c b/drivers/staging/rt2870/common/ba_action.c
index d9f7381..a9e6a09 100644
--- a/drivers/staging/rt2870/common/ba_action.c
+++ b/drivers/staging/rt2870/common/ba_action.c
@@ -1,1798 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-
-#ifdef DOT11_N_SUPPORT
-
-#include "../rt_config.h"
-
-
-
-#define BA_ORI_INIT_SEQ		(pEntry->TxSeq[TID]) //1			// inital sequence number of BA session
-
-#define ORI_SESSION_MAX_RETRY	8
-#define ORI_BA_SESSION_TIMEOUT	(2000)	// ms
-#define REC_BA_SESSION_IDLE_TIMEOUT	(1000)	// ms
-
-#define REORDERING_PACKET_TIMEOUT		((100 * HZ)/1000)	// system ticks -- 100 ms
-#define MAX_REORDERING_PACKET_TIMEOUT	((3000 * HZ)/1000)	// system ticks -- 100 ms
-
-#define RESET_RCV_SEQ		(0xFFFF)
-
-static void ba_mpdu_blk_free(PRTMP_ADAPTER pAd, struct reordering_mpdu *mpdu_blk);
-
-
-BA_ORI_ENTRY *BATableAllocOriEntry(
-								  IN  PRTMP_ADAPTER   pAd,
-								  OUT USHORT          *Idx);
-
-BA_REC_ENTRY *BATableAllocRecEntry(
-								  IN  PRTMP_ADAPTER   pAd,
-								  OUT USHORT          *Idx);
-
-VOID BAOriSessionSetupTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-VOID BARecSessionIdleTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-
-BUILD_TIMER_FUNCTION(BAOriSessionSetupTimeout);
-BUILD_TIMER_FUNCTION(BARecSessionIdleTimeout);
-
-#define ANNOUNCE_REORDERING_PACKET(_pAd, _mpdu_blk)	\
-			Announce_Reordering_Packet(_pAd, _mpdu_blk);
-
-VOID BA_MaxWinSizeReasign(
-	IN PRTMP_ADAPTER	pAd,
-	IN MAC_TABLE_ENTRY  *pEntryPeer,
-	OUT UCHAR			*pWinSize)
-{
-	UCHAR MaxSize;
-
-
-	if (pAd->MACVersion >= RALINK_2883_VERSION) // 3*3
-	{
-		if (pAd->MACVersion >= RALINK_3070_VERSION)
-		{
-			if (pEntryPeer->WepStatus != Ndis802_11EncryptionDisabled)
-				MaxSize = 7; // for non-open mode
-			else
-				MaxSize = 13;
-		}
-		else
-			MaxSize = 31;
-	}
-	else if (pAd->MACVersion >= RALINK_2880E_VERSION) // 2880 e
-	{
-		if (pEntryPeer->WepStatus != Ndis802_11EncryptionDisabled)
-			MaxSize = 7; // for non-open mode
-		else
-			MaxSize = 13;
-	}
-	else
-		MaxSize = 7;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ba> Win Size = %d, Max Size = %d\n",
-			*pWinSize, MaxSize));
-
-	if ((*pWinSize) > MaxSize)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ba> reassign max win size from %d to %d\n",
-				*pWinSize, MaxSize));
-
-		*pWinSize = MaxSize;
-	}
-}
-
-void Announce_Reordering_Packet(IN PRTMP_ADAPTER			pAd,
-								IN struct reordering_mpdu	*mpdu)
-{
-	PNDIS_PACKET    pPacket;
-
-	pPacket = mpdu->pPacket;
-
-	if (mpdu->bAMSDU)
-	{
-		ASSERT(0);
-		BA_Reorder_AMSDU_Annnounce(pAd, pPacket);
-	}
-	else
-	{
-		//
-		// pass this 802.3 packet to upper layer or forward this packet to WM directly
-		//
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pPacket, RTMP_GET_PACKET_IF(pPacket));
-#endif // CONFIG_STA_SUPPORT //
-	}
-}
-
-/*
- * Insert a reordering mpdu into sorted linked list by sequence no.
- */
-BOOLEAN ba_reordering_mpdu_insertsorted(struct reordering_list *list, struct reordering_mpdu *mpdu)
-{
-
-	struct reordering_mpdu **ppScan = &list->next;
-
-	while (*ppScan != NULL)
-	{
-		if (SEQ_SMALLER((*ppScan)->Sequence, mpdu->Sequence, MAXSEQ))
-		{
-			ppScan = &(*ppScan)->next;
-		}
-		else if ((*ppScan)->Sequence == mpdu->Sequence)
-		{
-			/* give up this duplicated frame */
-			return(FALSE);
-		}
-		else
-		{
-			/* find position */
-			break;
-		}
-	}
-
-	mpdu->next = *ppScan;
-	*ppScan = mpdu;
-	list->qlen++;
-	return TRUE;
-}
-
-
-/*
- * caller lock critical section if necessary
- */
-static inline void ba_enqueue(struct reordering_list *list, struct reordering_mpdu *mpdu_blk)
-{
-	list->qlen++;
-	mpdu_blk->next = list->next;
-	list->next = mpdu_blk;
-}
-
-/*
- * caller lock critical section if necessary
- */
-static inline struct reordering_mpdu * ba_dequeue(struct reordering_list *list)
-{
-	struct reordering_mpdu *mpdu_blk = NULL;
-
-	ASSERT(list);
-
-		if (list->qlen)
-		{
-			list->qlen--;
-			mpdu_blk = list->next;
-			if (mpdu_blk)
-			{
-				list->next = mpdu_blk->next;
-				mpdu_blk->next = NULL;
-			}
-		}
-	return mpdu_blk;
-}
-
-
-static inline struct reordering_mpdu  *ba_reordering_mpdu_dequeue(struct reordering_list *list)
-{
-	return(ba_dequeue(list));
-}
-
-
-static inline struct reordering_mpdu  *ba_reordering_mpdu_probe(struct reordering_list *list)
-	{
-	ASSERT(list);
-
-		return(list->next);
-	}
-
-
-/*
- * free all resource for reordering mechanism
- */
-void ba_reordering_resource_release(PRTMP_ADAPTER pAd)
-{
-	BA_TABLE        *Tab;
-	PBA_REC_ENTRY   pBAEntry;
-	struct reordering_mpdu *mpdu_blk;
-	int i;
-
-	Tab = &pAd->BATable;
-
-	/* I.  release all pending reordering packet */
-	NdisAcquireSpinLock(&pAd->BATabLock);
-	for (i = 0; i < MAX_LEN_OF_BA_REC_TABLE; i++)
-	{
-		pBAEntry = &Tab->BARecEntry[i];
-		if (pBAEntry->REC_BA_Status != Recipient_NONE)
-		{
-			while ((mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list)))
-			{
-				ASSERT(mpdu_blk->pPacket);
-				RELEASE_NDIS_PACKET(pAd, mpdu_blk->pPacket, NDIS_STATUS_FAILURE);
-				ba_mpdu_blk_free(pAd, mpdu_blk);
-			}
-		}
-	}
-	NdisReleaseSpinLock(&pAd->BATabLock);
-
-	ASSERT(pBAEntry->list.qlen == 0);
-	/* II. free memory of reordering mpdu table */
-	NdisAcquireSpinLock(&pAd->mpdu_blk_pool.lock);
-	os_free_mem(pAd, pAd->mpdu_blk_pool.mem);
-	NdisReleaseSpinLock(&pAd->mpdu_blk_pool.lock);
-}
-
-
-
-/*
- * Allocate all resource for reordering mechanism
- */
-BOOLEAN ba_reordering_resource_init(PRTMP_ADAPTER pAd, int num)
-{
-	int     i;
-	PUCHAR  mem;
-	struct reordering_mpdu *mpdu_blk;
-	struct reordering_list *freelist;
-
-	/* allocate spinlock */
-	NdisAllocateSpinLock(&pAd->mpdu_blk_pool.lock);
-
-	/* initialize freelist */
-	freelist = &pAd->mpdu_blk_pool.freelist;
-	freelist->next = NULL;
-	freelist->qlen = 0;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Allocate %d memory for BA reordering\n", (UINT32)(num*sizeof(struct reordering_mpdu))));
-
-	/* allocate number of mpdu_blk memory */
-	os_alloc_mem(pAd, (PUCHAR *)&mem, (num*sizeof(struct reordering_mpdu)));
-
-	pAd->mpdu_blk_pool.mem = mem;
-
-	if (mem == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Can't Allocate Memory for BA Reordering\n"));
-		return(FALSE);
-	}
-
-	/* build mpdu_blk free list */
-	for (i=0; i<num; i++)
-	{
-		/* get mpdu_blk */
-		mpdu_blk = (struct reordering_mpdu *) mem;
-		/* initial mpdu_blk */
-		NdisZeroMemory(mpdu_blk, sizeof(struct reordering_mpdu));
-		/* next mpdu_blk */
-		mem += sizeof(struct reordering_mpdu);
-		/* insert mpdu_blk into freelist */
-		ba_enqueue(freelist, mpdu_blk);
-	}
-
-	return(TRUE);
-}
-
-//static int blk_count=0; // sample take off, no use
-
-static struct reordering_mpdu *ba_mpdu_blk_alloc(PRTMP_ADAPTER pAd)
-{
-	struct reordering_mpdu *mpdu_blk;
-
-	NdisAcquireSpinLock(&pAd->mpdu_blk_pool.lock);
-	mpdu_blk = ba_dequeue(&pAd->mpdu_blk_pool.freelist);
-	if (mpdu_blk)
-	{
-//		blk_count++;
-		/* reset mpdu_blk */
-		NdisZeroMemory(mpdu_blk, sizeof(struct reordering_mpdu));
-	}
-	NdisReleaseSpinLock(&pAd->mpdu_blk_pool.lock);
-	return mpdu_blk;
-}
-
-static void ba_mpdu_blk_free(PRTMP_ADAPTER pAd, struct reordering_mpdu *mpdu_blk)
-{
-	ASSERT(mpdu_blk);
-
-	NdisAcquireSpinLock(&pAd->mpdu_blk_pool.lock);
-//	blk_count--;
-	ba_enqueue(&pAd->mpdu_blk_pool.freelist, mpdu_blk);
-	NdisReleaseSpinLock(&pAd->mpdu_blk_pool.lock);
-}
-
-
-static USHORT ba_indicate_reordering_mpdus_in_order(
-												   IN PRTMP_ADAPTER    pAd,
-												   IN PBA_REC_ENTRY    pBAEntry,
-												   IN USHORT           StartSeq)
-{
-	struct reordering_mpdu *mpdu_blk;
-	USHORT  LastIndSeq = RESET_RCV_SEQ;
-
-	NdisAcquireSpinLock(&pBAEntry->RxReRingLock);
-
-	while ((mpdu_blk = ba_reordering_mpdu_probe(&pBAEntry->list)))
-		{
-			/* find in-order frame */
-		if (!SEQ_STEPONE(mpdu_blk->Sequence, StartSeq, MAXSEQ))
-			{
-				break;
-			}
-			/* dequeue in-order frame from reodering list */
-			mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list);
-			/* pass this frame up */
-		ANNOUNCE_REORDERING_PACKET(pAd, mpdu_blk);
-		/* move to next sequence */
-			StartSeq = mpdu_blk->Sequence;
-		LastIndSeq = StartSeq;
-		/* free mpdu_blk */
-			ba_mpdu_blk_free(pAd, mpdu_blk);
-	}
-
-	NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
-
-	/* update last indicated sequence */
-	return LastIndSeq;
-}
-
-static void ba_indicate_reordering_mpdus_le_seq(
-											   IN PRTMP_ADAPTER    pAd,
-											   IN PBA_REC_ENTRY    pBAEntry,
-											   IN USHORT           Sequence)
-{
-	struct reordering_mpdu *mpdu_blk;
-
-	NdisAcquireSpinLock(&pBAEntry->RxReRingLock);
-	while ((mpdu_blk = ba_reordering_mpdu_probe(&pBAEntry->list)))
-		{
-			/* find in-order frame */
-		if ((mpdu_blk->Sequence == Sequence) || SEQ_SMALLER(mpdu_blk->Sequence, Sequence, MAXSEQ))
-		{
-			/* dequeue in-order frame from reodering list */
-			mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list);
-			/* pass this frame up */
-			ANNOUNCE_REORDERING_PACKET(pAd, mpdu_blk);
-			/* free mpdu_blk */
-			ba_mpdu_blk_free(pAd, mpdu_blk);
-		}
-		else
-			{
-				break;
-			}
-	}
-	NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
-}
-
-
-static void ba_refresh_reordering_mpdus(
-									   IN PRTMP_ADAPTER    pAd,
-									   PBA_REC_ENTRY       pBAEntry)
-{
-	struct reordering_mpdu *mpdu_blk;
-
-	NdisAcquireSpinLock(&pBAEntry->RxReRingLock);
-
-			/* dequeue in-order frame from reodering list */
-	while ((mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list)))
-	{
-			/* pass this frame up */
-		ANNOUNCE_REORDERING_PACKET(pAd, mpdu_blk);
-
-		pBAEntry->LastIndSeq = mpdu_blk->Sequence;
-			ba_mpdu_blk_free(pAd, mpdu_blk);
-
-		/* update last indicated sequence */
-	}
-	ASSERT(pBAEntry->list.qlen == 0);
-	pBAEntry->LastIndSeq = RESET_RCV_SEQ;
-	NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
-}
-
-
-//static
-void ba_flush_reordering_timeout_mpdus(
-									IN PRTMP_ADAPTER    pAd,
-									IN PBA_REC_ENTRY    pBAEntry,
-									IN ULONG            Now32)
-
-{
-	USHORT Sequence;
-
-//	if ((RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+REORDERING_PACKET_TIMEOUT)) &&
-//		 (pBAEntry->list.qlen > ((pBAEntry->BAWinSize*7)/8))) //||
-//		(RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(10*REORDERING_PACKET_TIMEOUT))) &&
-//		 (pBAEntry->list.qlen > (pBAEntry->BAWinSize/8)))
-	if (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(MAX_REORDERING_PACKET_TIMEOUT/6)))
-		 &&(pBAEntry->list.qlen > 1)
-		)
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("timeout[%d] (%08lx-%08lx = %d > %d): %x, flush all!\n ", pBAEntry->list.qlen, Now32, (pBAEntry->LastIndSeqAtTimer),
-			   (int)((long) Now32 - (long)(pBAEntry->LastIndSeqAtTimer)), MAX_REORDERING_PACKET_TIMEOUT,
-			   pBAEntry->LastIndSeq));
-		ba_refresh_reordering_mpdus(pAd, pBAEntry);
-		pBAEntry->LastIndSeqAtTimer = Now32;
-	}
-	else
-	if (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(REORDERING_PACKET_TIMEOUT)))
-		&& (pBAEntry->list.qlen > 0)
-	   )
-		{
-    		//
-		// force LastIndSeq to shift to LastIndSeq+1
-    		//
-    		Sequence = (pBAEntry->LastIndSeq+1) & MAXSEQ;
-    		ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, Sequence);
-    		pBAEntry->LastIndSeqAtTimer = Now32;
-			pBAEntry->LastIndSeq = Sequence;
-    		//
-    		// indicate in-order mpdus
-    		//
-    		Sequence = ba_indicate_reordering_mpdus_in_order(pAd, pBAEntry, Sequence);
-    		if (Sequence != RESET_RCV_SEQ)
-    		{
-    			pBAEntry->LastIndSeq = Sequence;
-    		}
-
-	}
-#if 0
-	else if (
-			 (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(MAX_REORDERING_PACKET_TIMEOUT))) &&
-			  (pBAEntry->list.qlen > 1))
-			)
-		{
-		DBGPRINT(RT_DEBUG_TRACE,("timeout[%d] (%lx-%lx = %d > %d): %x\n ", pBAEntry->list.qlen, Now32, (pBAEntry->LastIndSeqAtTimer),
-			   (int)((long) Now32 - (long)(pBAEntry->LastIndSeqAtTimer)), MAX_REORDERING_PACKET_TIMEOUT,
-			   pBAEntry->LastIndSeq));
-		ba_refresh_reordering_mpdus(pAd, pBAEntry);
-			pBAEntry->LastIndSeqAtTimer = Now32;
-				}
-#endif
-}
-
-
-/*
- * generate ADDBA request to
- * set up BA agreement
- */
-VOID BAOriSessionSetUp(
-					  IN PRTMP_ADAPTER    pAd,
-					  IN MAC_TABLE_ENTRY  *pEntry,
-					  IN UCHAR            TID,
-					  IN USHORT           TimeOut,
-					  IN ULONG            DelayTime,
-					  IN BOOLEAN          isForced)
-
-{
-	//MLME_ADDBA_REQ_STRUCT	AddbaReq;
-	BA_ORI_ENTRY            *pBAEntry = NULL;
-	USHORT                  Idx;
-	BOOLEAN                 Cancelled;
-
-	if ((pAd->CommonCfg.BACapability.field.AutoBA != TRUE)  &&  (isForced == FALSE))
-		return;
-
-	// if this entry is limited to use legacy tx mode, it doesn't generate BA.
-	if (RTMPStaFixedTxMode(pAd, pEntry) != FIXED_TXMODE_HT)
-		return;
-
-	if ((pEntry->BADeclineBitmap & (1<<TID)) && (isForced == FALSE))
-	{
-		// try again after 3 secs
-		DelayTime = 3000;
-//		printk("DeCline BA from Peer\n");
-//		return;
-	}
-
-
-	Idx = pEntry->BAOriWcidArray[TID];
-	if (Idx == 0)
-	{
-		// allocate a BA session
-		pBAEntry = BATableAllocOriEntry(pAd, &Idx);
-		if (pBAEntry == NULL)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("ADDBA - MlmeADDBAAction() allocate BA session failed \n"));
-			return;
-		}
-	}
-	else
-	{
-		pBAEntry =&pAd->BATable.BAOriEntry[Idx];
-	}
-
-	if (pBAEntry->ORI_BA_Status >= Originator_WaitRes)
-	{
-		return;
-	}
-
-	pEntry->BAOriWcidArray[TID] = Idx;
-
-	// Initialize BA session
-	pBAEntry->ORI_BA_Status = Originator_WaitRes;
-	pBAEntry->Wcid = pEntry->Aid;
-	pBAEntry->BAWinSize = pAd->CommonCfg.BACapability.field.RxBAWinLimit;
-	pBAEntry->Sequence = BA_ORI_INIT_SEQ;
-	pBAEntry->Token = 1;	// (2008-01-21) Jan Lee recommends it - this token can't be 0
-	pBAEntry->TID = TID;
-	pBAEntry->TimeOutValue = TimeOut;
-	pBAEntry->pAdapter = pAd;
-
-	if (!(pEntry->TXBAbitmap & (1<<TID)))
-	{
-		RTMPInitTimer(pAd, &pBAEntry->ORIBATimer, GET_TIMER_FUNCTION(BAOriSessionSetupTimeout), pBAEntry, FALSE);
-	}
-	else
-		RTMPCancelTimer(&pBAEntry->ORIBATimer, &Cancelled);
-
-	// set timer to send ADDBA request
-	RTMPSetTimer(&pBAEntry->ORIBATimer, DelayTime);
-}
-
-VOID BAOriSessionAdd(
-			IN PRTMP_ADAPTER    pAd,
-					IN MAC_TABLE_ENTRY  *pEntry,
-			IN PFRAME_ADDBA_RSP pFrame)
-{
-	BA_ORI_ENTRY  *pBAEntry = NULL;
-	BOOLEAN       Cancelled;
-	UCHAR         TID;
-	USHORT        Idx;
-	PUCHAR          pOutBuffer2 = NULL;
-	NDIS_STATUS     NStatus;
-	ULONG           FrameLen;
-	FRAME_BAR       FrameBar;
-
-	TID = pFrame->BaParm.TID;
-	Idx = pEntry->BAOriWcidArray[TID];
-	pBAEntry =&pAd->BATable.BAOriEntry[Idx];
-
-	// Start fill in parameters.
-	if ((Idx !=0) && (pBAEntry->TID == TID) && (pBAEntry->ORI_BA_Status == Originator_WaitRes))
-	{
-		pBAEntry->BAWinSize = min(pBAEntry->BAWinSize, ((UCHAR)pFrame->BaParm.BufSize));
-		BA_MaxWinSizeReasign(pAd, pEntry, &pBAEntry->BAWinSize);
-
-		pBAEntry->TimeOutValue = pFrame->TimeOutValue;
-		pBAEntry->ORI_BA_Status = Originator_Done;
-		// reset sequence number
-		pBAEntry->Sequence = BA_ORI_INIT_SEQ;
-		// Set Bitmap flag.
-		pEntry->TXBAbitmap |= (1<<TID);
-				RTMPCancelTimer(&pBAEntry->ORIBATimer, &Cancelled);
-
-		pBAEntry->ORIBATimer.TimerValue = 0;	//pFrame->TimeOutValue;
-
-		DBGPRINT(RT_DEBUG_TRACE,("%s : TXBAbitmap = %x, BAWinSize = %d, TimeOut = %ld\n", __func__, pEntry->TXBAbitmap,
-								 pBAEntry->BAWinSize, pBAEntry->ORIBATimer.TimerValue));
-
-		// SEND BAR ;
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer2);  //Get an unused nonpaged memory
-		if (NStatus != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("BA - BAOriSessionAdd() allocate memory failed \n"));
-			return;
-		}
-
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			BarHeaderInit(pAd, &FrameBar, pAd->MacTab.Content[pBAEntry->Wcid].Addr, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
-
-		FrameBar.StartingSeq.field.FragNum = 0;	// make sure sequence not clear in DEL function.
-		FrameBar.StartingSeq.field.StartSeq = pBAEntry->Sequence; // make sure sequence not clear in DEL funciton.
-		FrameBar.BarControl.TID = pBAEntry->TID; // make sure sequence not clear in DEL funciton.
-		MakeOutgoingFrame(pOutBuffer2,              &FrameLen,
-						  sizeof(FRAME_BAR),      &FrameBar,
-					  END_OF_ARGS);
-		MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer2, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer2);
-
-
-		if (pBAEntry->ORIBATimer.TimerValue)
-			RTMPSetTimer(&pBAEntry->ORIBATimer, pBAEntry->ORIBATimer.TimerValue); // in mSec
-	}
-}
-
-BOOLEAN BARecSessionAdd(
-					   IN PRTMP_ADAPTER    pAd,
-					   IN MAC_TABLE_ENTRY  *pEntry,
-					   IN PFRAME_ADDBA_REQ pFrame)
-{
-	BA_REC_ENTRY            *pBAEntry = NULL;
-	BOOLEAN                 Status = TRUE;
-	BOOLEAN                 Cancelled;
-	USHORT                  Idx;
-	UCHAR                   TID;
-	UCHAR                   BAWinSize;
-	//UINT32                  Value;
-	//UINT                    offset;
-
-
-	ASSERT(pEntry);
-
-	// find TID
-	TID = pFrame->BaParm.TID;
-
-	BAWinSize = min(((UCHAR)pFrame->BaParm.BufSize), (UCHAR)pAd->CommonCfg.BACapability.field.RxBAWinLimit);
-
-	// Intel patch
-	if (BAWinSize == 0)
-	{
-		BAWinSize = 64;
-	}
-
-	Idx = pEntry->BARecWcidArray[TID];
-
-
-	if (Idx == 0)
-	{
-		pBAEntry = BATableAllocRecEntry(pAd, &Idx);
-	}
-	else
-	{
-		pBAEntry = &pAd->BATable.BARecEntry[Idx];
-		// flush all pending reordering mpdus
-		ba_refresh_reordering_mpdus(pAd, pBAEntry);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("%s(%ld): Idx = %d, BAWinSize(req %d) = %d\n", __func__, pAd->BATable.numAsRecipient, Idx,
-							 pFrame->BaParm.BufSize, BAWinSize));
-
-	// Start fill in parameters.
-	if (pBAEntry != NULL)
-	{
-		ASSERT(pBAEntry->list.qlen == 0);
-
-		pBAEntry->REC_BA_Status = Recipient_HandleRes;
-		pBAEntry->BAWinSize = BAWinSize;
-		pBAEntry->Wcid = pEntry->Aid;
-		pBAEntry->TID = TID;
-		pBAEntry->TimeOutValue = pFrame->TimeOutValue;
-		pBAEntry->REC_BA_Status = Recipient_Accept;
-		// initial sequence number
-		pBAEntry->LastIndSeq = RESET_RCV_SEQ; //pFrame->BaStartSeq.field.StartSeq;
-
-		printk("Start Seq = %08x\n",  pFrame->BaStartSeq.field.StartSeq);
-
-		if (pEntry->RXBAbitmap & (1<<TID))
-		{
-			RTMPCancelTimer(&pBAEntry->RECBATimer, &Cancelled);
-		}
-		else
-		{
-			RTMPInitTimer(pAd, &pBAEntry->RECBATimer, GET_TIMER_FUNCTION(BARecSessionIdleTimeout), pBAEntry, TRUE);
-		}
-
-#if 0	// for debugging
-		RTMPSetTimer(&pBAEntry->RECBATimer, REC_BA_SESSION_IDLE_TIMEOUT);
-#endif
-
-		// Set Bitmap flag.
-		pEntry->RXBAbitmap |= (1<<TID);
-		pEntry->BARecWcidArray[TID] = Idx;
-
-		pEntry->BADeclineBitmap &= ~(1<<TID);
-
-		// Set BA session mask in WCID table.
-		RT28XX_ADD_BA_SESSION_TO_ASIC(pAd, pEntry->Aid, TID);
-
-		DBGPRINT(RT_DEBUG_TRACE,("MACEntry[%d]RXBAbitmap = 0x%x. BARecWcidArray=%d\n",
-				pEntry->Aid, pEntry->RXBAbitmap, pEntry->BARecWcidArray[TID]));
-	}
-	else
-	{
-		Status = FALSE;
-		DBGPRINT(RT_DEBUG_TRACE,("Can't Accept ADDBA for %02x:%02x:%02x:%02x:%02x:%02x TID = %d\n",
-				PRINT_MAC(pEntry->Addr), TID));
-	}
-	return(Status);
-}
-
-
-BA_REC_ENTRY *BATableAllocRecEntry(
-								  IN  PRTMP_ADAPTER   pAd,
-								  OUT USHORT          *Idx)
-{
-	int             i;
-	BA_REC_ENTRY    *pBAEntry = NULL;
-
-
-	NdisAcquireSpinLock(&pAd->BATabLock);
-
-	if (pAd->BATable.numAsRecipient >= MAX_BARECI_SESSION)
-	{
-		printk("BA Recipeint Session (%ld) > %d\n", pAd->BATable.numAsRecipient,
-			MAX_BARECI_SESSION);
-		goto done;
-	}
-
-	// reserve idx 0 to identify BAWcidArray[TID] as empty
-	for (i=1; i < MAX_LEN_OF_BA_REC_TABLE; i++)
-	{
-		pBAEntry =&pAd->BATable.BARecEntry[i];
-		if ((pBAEntry->REC_BA_Status == Recipient_NONE))
-		{
-			// get one
-			pAd->BATable.numAsRecipient++;
-			pBAEntry->REC_BA_Status = Recipient_USED;
-			*Idx = i;
-			break;
-		}
-	}
-
-done:
-	NdisReleaseSpinLock(&pAd->BATabLock);
-	return pBAEntry;
-}
-
-BA_ORI_ENTRY *BATableAllocOriEntry(
-								  IN  PRTMP_ADAPTER   pAd,
-								  OUT USHORT          *Idx)
-{
-	int             i;
-	BA_ORI_ENTRY    *pBAEntry = NULL;
-
-	NdisAcquireSpinLock(&pAd->BATabLock);
-
-	if (pAd->BATable.numAsOriginator >= (MAX_LEN_OF_BA_ORI_TABLE))
-	{
-		goto done;
-	}
-
-	// reserve idx 0 to identify BAWcidArray[TID] as empty
-	for (i=1; i<MAX_LEN_OF_BA_ORI_TABLE; i++)
-	{
-		pBAEntry =&pAd->BATable.BAOriEntry[i];
-		if ((pBAEntry->ORI_BA_Status == Originator_NONE))
-		{
-			// get one
-			pAd->BATable.numAsOriginator++;
-			pBAEntry->ORI_BA_Status = Originator_USED;
-			pBAEntry->pAdapter = pAd;
-			*Idx = i;
-			break;
-		}
-	}
-
-done:
-	NdisReleaseSpinLock(&pAd->BATabLock);
-	return pBAEntry;
-}
-
-
-VOID BATableFreeOriEntry(
-						IN  PRTMP_ADAPTER   pAd,
-						IN  ULONG           Idx)
-{
-	BA_ORI_ENTRY    *pBAEntry = NULL;
-	MAC_TABLE_ENTRY *pEntry;
-
-
-	if ((Idx == 0) || (Idx >= MAX_LEN_OF_BA_ORI_TABLE))
-		return;
-
-	pBAEntry =&pAd->BATable.BAOriEntry[Idx];
-
-	if (pBAEntry->ORI_BA_Status != Originator_NONE)
-	{
-		pEntry = &pAd->MacTab.Content[pBAEntry->Wcid];
-		pEntry->BAOriWcidArray[pBAEntry->TID] = 0;
-
-
-		NdisAcquireSpinLock(&pAd->BATabLock);
-		if (pBAEntry->ORI_BA_Status == Originator_Done)
-		{
-		 	pEntry->TXBAbitmap &= (~(1<<(pBAEntry->TID) ));
-			DBGPRINT(RT_DEBUG_TRACE, ("BATableFreeOriEntry numAsOriginator= %ld\n", pAd->BATable.numAsRecipient));
-			// Erase Bitmap flag.
-		}
-
-		ASSERT(pAd->BATable.numAsOriginator != 0);
-
-		pAd->BATable.numAsOriginator -= 1;
-
-		pBAEntry->ORI_BA_Status = Originator_NONE;
-		pBAEntry->Token = 0;
-		NdisReleaseSpinLock(&pAd->BATabLock);
-	}
-}
-
-
-VOID BATableFreeRecEntry(
-						IN  PRTMP_ADAPTER   pAd,
-						IN  ULONG           Idx)
-{
-	BA_REC_ENTRY    *pBAEntry = NULL;
-	MAC_TABLE_ENTRY *pEntry;
-
-
-	if ((Idx == 0) || (Idx >= MAX_LEN_OF_BA_REC_TABLE))
-		return;
-
-	pBAEntry =&pAd->BATable.BARecEntry[Idx];
-
-	if (pBAEntry->REC_BA_Status != Recipient_NONE)
-	{
-		pEntry = &pAd->MacTab.Content[pBAEntry->Wcid];
-		pEntry->BARecWcidArray[pBAEntry->TID] = 0;
-
-		NdisAcquireSpinLock(&pAd->BATabLock);
-
-		ASSERT(pAd->BATable.numAsRecipient != 0);
-
-		pAd->BATable.numAsRecipient -= 1;
-
-		pBAEntry->REC_BA_Status = Recipient_NONE;
-		NdisReleaseSpinLock(&pAd->BATabLock);
-	}
-}
-
-
-VOID BAOriSessionTearDown(
-						 IN OUT  PRTMP_ADAPTER   pAd,
-						 IN      UCHAR           Wcid,
-						 IN      UCHAR           TID,
-						 IN      BOOLEAN         bPassive,
-						 IN      BOOLEAN         bForceSend)
-{
-	ULONG           Idx = 0;
-	BA_ORI_ENTRY    *pBAEntry;
-	BOOLEAN         Cancelled;
-
-	if (Wcid >= MAX_LEN_OF_MAC_TABLE)
-	{
-		return;
-	}
-
-	//
-	// Locate corresponding BA Originator Entry in BA Table with the (pAddr,TID).
-	//
-	Idx = pAd->MacTab.Content[Wcid].BAOriWcidArray[TID];
-	if ((Idx == 0) || (Idx >= MAX_LEN_OF_BA_ORI_TABLE))
-	{
-		if (bForceSend == TRUE)
-		{
-			// force send specified TID DelBA
-			MLME_DELBA_REQ_STRUCT   DelbaReq;
-			MLME_QUEUE_ELEM *Elem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-
-			NdisZeroMemory(&DelbaReq, sizeof(DelbaReq));
-			NdisZeroMemory(Elem, sizeof(MLME_QUEUE_ELEM));
-
-			COPY_MAC_ADDR(DelbaReq.Addr, pAd->MacTab.Content[Wcid].Addr);
-			DelbaReq.Wcid = Wcid;
-			DelbaReq.TID = TID;
-			DelbaReq.Initiator = ORIGINATOR;
-#if 1
-			Elem->MsgLen  = sizeof(DelbaReq);
-			NdisMoveMemory(Elem->Msg, &DelbaReq, sizeof(DelbaReq));
-			MlmeDELBAAction(pAd, Elem);
-			kfree(Elem);
-#else
-			MlmeEnqueue(pAd, ACTION_STATE_MACHINE, MT2_MLME_ORI_DELBA_CATE, sizeof(MLME_DELBA_REQ_STRUCT), (PVOID)&DelbaReq);
-			RT28XX_MLME_HANDLER(pAd);
-#endif
-		}
-
-		return;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("%s===>Wcid=%d.TID=%d \n", __func__, Wcid, TID));
-
-	pBAEntry = &pAd->BATable.BAOriEntry[Idx];
-	DBGPRINT(RT_DEBUG_TRACE,("\t===>Idx = %ld, Wcid=%d.TID=%d, ORI_BA_Status = %d \n", Idx, Wcid, TID, pBAEntry->ORI_BA_Status));
-	//
-	// Prepare DelBA action frame and send to the peer.
-	//
-	if ((bPassive == FALSE) && (TID == pBAEntry->TID) && (pBAEntry->ORI_BA_Status == Originator_Done))
-	{
-		MLME_DELBA_REQ_STRUCT   DelbaReq;
-		MLME_QUEUE_ELEM *Elem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-
-		NdisZeroMemory(&DelbaReq, sizeof(DelbaReq));
-		NdisZeroMemory(Elem, sizeof(MLME_QUEUE_ELEM));
-
-		COPY_MAC_ADDR(DelbaReq.Addr, pAd->MacTab.Content[Wcid].Addr);
-		DelbaReq.Wcid = Wcid;
-		DelbaReq.TID = pBAEntry->TID;
-		DelbaReq.Initiator = ORIGINATOR;
-#if 1
-		Elem->MsgLen  = sizeof(DelbaReq);
-		NdisMoveMemory(Elem->Msg, &DelbaReq, sizeof(DelbaReq));
-		MlmeDELBAAction(pAd, Elem);
-		kfree(Elem);
-#else
-		MlmeEnqueue(pAd, ACTION_STATE_MACHINE, MT2_MLME_ORI_DELBA_CATE, sizeof(MLME_DELBA_REQ_STRUCT), (PVOID)&DelbaReq);
-		RT28XX_MLME_HANDLER(pAd);
-#endif
-	}
-	RTMPCancelTimer(&pBAEntry->ORIBATimer, &Cancelled);
-	BATableFreeOriEntry(pAd, Idx);
-
-	if (bPassive)
-	{
-		//BAOriSessionSetUp(pAd, &pAd->MacTab.Content[Wcid], TID, 0, 10000, TRUE);
-	}
-}
-
-VOID BARecSessionTearDown(
-						 IN OUT  PRTMP_ADAPTER   pAd,
-						 IN      UCHAR           Wcid,
-						 IN      UCHAR           TID,
-						 IN      BOOLEAN         bPassive)
-{
-	ULONG           Idx = 0;
-	BA_REC_ENTRY    *pBAEntry;
-
-	if (Wcid >= MAX_LEN_OF_MAC_TABLE)
-	{
-		return;
-	}
-
-	//
-	//  Locate corresponding BA Originator Entry in BA Table with the (pAddr,TID).
-	//
-	Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID];
-	if (Idx == 0)
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE,("%s===>Wcid=%d.TID=%d \n", __func__, Wcid, TID));
-
-
-	pBAEntry = &pAd->BATable.BARecEntry[Idx];
-	DBGPRINT(RT_DEBUG_TRACE,("\t===>Idx = %ld, Wcid=%d.TID=%d, REC_BA_Status = %d \n", Idx, Wcid, TID, pBAEntry->REC_BA_Status));
-	//
-	// Prepare DelBA action frame and send to the peer.
-	//
-	if ((TID == pBAEntry->TID) && (pBAEntry->REC_BA_Status == Recipient_Accept))
-	{
-		MLME_DELBA_REQ_STRUCT   DelbaReq;
-		BOOLEAN 				Cancelled;
-		MLME_QUEUE_ELEM *Elem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-		//ULONG   offset;
-		//UINT32  VALUE;
-
-		RTMPCancelTimer(&pBAEntry->RECBATimer, &Cancelled);
-
-		//
-		// 1. Send DELBA Action Frame
-		//
-		if (bPassive == FALSE)
-		{
-			NdisZeroMemory(&DelbaReq, sizeof(DelbaReq));
-			NdisZeroMemory(Elem, sizeof(MLME_QUEUE_ELEM));
-
-			COPY_MAC_ADDR(DelbaReq.Addr, pAd->MacTab.Content[Wcid].Addr);
-			DelbaReq.Wcid = Wcid;
-			DelbaReq.TID = TID;
-			DelbaReq.Initiator = RECIPIENT;
-#if 1
-			Elem->MsgLen  = sizeof(DelbaReq);
-			NdisMoveMemory(Elem->Msg, &DelbaReq, sizeof(DelbaReq));
-			MlmeDELBAAction(pAd, Elem);
-			kfree(Elem);
-#else
-			MlmeEnqueue(pAd, ACTION_STATE_MACHINE, MT2_MLME_ORI_DELBA_CATE, sizeof(MLME_DELBA_REQ_STRUCT), (PVOID)&DelbaReq);
-			RT28XX_MLME_HANDLER(pAd);
-#endif
-		}
-
-
-		//
-		// 2. Free resource of BA session
-		//
-		// flush all pending reordering mpdus
-		ba_refresh_reordering_mpdus(pAd, pBAEntry);
-
-		NdisAcquireSpinLock(&pAd->BATabLock);
-
-		// Erase Bitmap flag.
-		pBAEntry->LastIndSeq = RESET_RCV_SEQ;
-		pBAEntry->BAWinSize = 0;
-		// Erase Bitmap flag at software mactable
-		pAd->MacTab.Content[Wcid].RXBAbitmap &= (~(1<<(pBAEntry->TID)));
-		pAd->MacTab.Content[Wcid].BARecWcidArray[TID] = 0;
-
-		RT28XX_DEL_BA_SESSION_FROM_ASIC(pAd, Wcid, TID);
-
-		NdisReleaseSpinLock(&pAd->BATabLock);
-
-	}
-
-	BATableFreeRecEntry(pAd, Idx);
-}
-
-VOID BASessionTearDownALL(
-						 IN OUT  PRTMP_ADAPTER pAd,
-						 IN      UCHAR Wcid)
-{
-	int i;
-
-	for (i=0; i<NUM_OF_TID; i++)
-	{
-		BAOriSessionTearDown(pAd, Wcid, i, FALSE, FALSE);
-		BARecSessionTearDown(pAd, Wcid, i, FALSE);
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Retry sending ADDBA Reqest.
-
-	IRQL = DISPATCH_LEVEL
-
-	Parametrs:
-	p8023Header: if this is already 802.3 format, p8023Header is NULL
-
-	Return	: TRUE if put into rx reordering buffer, shouldn't indicaterxhere.
-				FALSE , then continue indicaterx at this moment.
-	==========================================================================
- */
-VOID BAOriSessionSetupTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3)
-{
-	BA_ORI_ENTRY    *pBAEntry = (BA_ORI_ENTRY *)FunctionContext;
-	MAC_TABLE_ENTRY *pEntry;
-	PRTMP_ADAPTER   pAd;
-
-	if (pBAEntry == NULL)
-		return;
-
-	pAd = pBAEntry->pAdapter;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Do nothing if monitor mode is on
-		if (MONITOR_ON(pAd))
-			return;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef RALINK_ATE
-	// Nothing to do in ATE mode.
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	pEntry = &pAd->MacTab.Content[pBAEntry->Wcid];
-
-	if ((pBAEntry->ORI_BA_Status == Originator_WaitRes) && (pBAEntry->Token < ORI_SESSION_MAX_RETRY))
-	{
-		MLME_ADDBA_REQ_STRUCT    AddbaReq;
-
-		NdisZeroMemory(&AddbaReq, sizeof(AddbaReq));
-		COPY_MAC_ADDR(AddbaReq.pAddr, pEntry->Addr);
-		AddbaReq.Wcid = (UCHAR)(pEntry->Aid);
-		AddbaReq.TID = pBAEntry->TID;
-		AddbaReq.BaBufSize = pAd->CommonCfg.BACapability.field.RxBAWinLimit;
-		AddbaReq.TimeOutValue = 0;
-		AddbaReq.Token = pBAEntry->Token;
-		MlmeEnqueue(pAd, ACTION_STATE_MACHINE, MT2_MLME_ADD_BA_CATE, sizeof(MLME_ADDBA_REQ_STRUCT), (PVOID)&AddbaReq);
-		RT28XX_MLME_HANDLER(pAd);
-		DBGPRINT(RT_DEBUG_TRACE,("BA Ori Session Timeout(%d) : Send ADD BA again\n", pBAEntry->Token));
-
-		pBAEntry->Token++;
-		RTMPSetTimer(&pBAEntry->ORIBATimer, ORI_BA_SESSION_TIMEOUT);
-	}
-	else
-	{
-		BATableFreeOriEntry(pAd, pEntry->BAOriWcidArray[pBAEntry->TID]);
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		Retry sending ADDBA Reqest.
-
-	IRQL = DISPATCH_LEVEL
-
-	Parametrs:
-	p8023Header: if this is already 802.3 format, p8023Header is NULL
-
-	Return	: TRUE if put into rx reordering buffer, shouldn't indicaterxhere.
-				FALSE , then continue indicaterx at this moment.
-	==========================================================================
- */
-VOID BARecSessionIdleTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3)
-{
-
-	BA_REC_ENTRY    *pBAEntry = (BA_REC_ENTRY *)FunctionContext;
-	PRTMP_ADAPTER   pAd;
-	ULONG           Now32;
-
-	if (pBAEntry == NULL)
-		return;
-
-	if ((pBAEntry->REC_BA_Status == Recipient_Accept))
-	{
-		NdisGetSystemUpTime(&Now32);
-
-		if (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer + REC_BA_SESSION_IDLE_TIMEOUT)))
-		{
-			pAd = pBAEntry->pAdapter;
-			// flush all pending reordering mpdus
-			ba_refresh_reordering_mpdus(pAd, pBAEntry);
-			printk("%ld: REC BA session Timeout\n", Now32);
-		}
-	}
-}
-
-
-VOID PeerAddBAReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-
-{
-	//	7.4.4.1
-	//ULONG	Idx;
-	UCHAR   Status = 1;
-	UCHAR   pAddr[6];
-	FRAME_ADDBA_RSP ADDframe;
-	PUCHAR         pOutBuffer = NULL;
-	NDIS_STATUS     NStatus;
-	PFRAME_ADDBA_REQ  pAddreqFrame = NULL;
-	//UCHAR		BufSize;
-	ULONG       FrameLen;
-	PULONG      ptemp;
-	PMAC_TABLE_ENTRY	pMacEntry;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s ==> (Wcid = %d)\n", __func__, Elem->Wcid));
-
-	//hex_dump("AddBAReq", Elem->Msg, Elem->MsgLen);
-
-	//ADDBA Request from unknown peer, ignore this.
-	if (Elem->Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return;
-
-	pMacEntry = &pAd->MacTab.Content[Elem->Wcid];
-	DBGPRINT(RT_DEBUG_TRACE,("BA - PeerAddBAReqAction----> \n"));
-	ptemp = (PULONG)Elem->Msg;
-	//DBGPRINT_RAW(RT_DEBUG_EMU, ("%08x:: %08x:: %08x:: %08x:: %08x:: %08x:: %08x:: %08x:: %08x\n", *(ptemp), *(ptemp+1), *(ptemp+2), *(ptemp+3), *(ptemp+4), *(ptemp+5), *(ptemp+6), *(ptemp+7), *(ptemp+8)));
-
-	if (PeerAddBAReqActionSanity(pAd, Elem->Msg, Elem->MsgLen, pAddr))
-	{
-
-		if ((pAd->CommonCfg.bBADecline == FALSE) && IS_HT_STA(pMacEntry))
-		{
-			pAddreqFrame = (PFRAME_ADDBA_REQ)(&Elem->Msg[0]);
-			printk("Rcv Wcid(%d) AddBAReq\n", Elem->Wcid);
-			if (BARecSessionAdd(pAd, &pAd->MacTab.Content[Elem->Wcid], pAddreqFrame))
-				Status = 0;
-			else
-				Status = 38; // more parameters have invalid values
-		}
-		else
-		{
-			Status = 37; // the request has been declined.
-		}
-	}
-
-	if (pAd->MacTab.Content[Elem->Wcid].ValidAsCLI)
-		ASSERT(pAd->MacTab.Content[Elem->Wcid].Sst == SST_ASSOC);
-
-	pAddreqFrame = (PFRAME_ADDBA_REQ)(&Elem->Msg[0]);
-	// 2. Always send back ADDBA Response
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);	 //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("ACTION - PeerBAAction() allocate memory failed \n"));
-		return;
-	}
-
-	NdisZeroMemory(&ADDframe, sizeof(FRAME_ADDBA_RSP));
-	// 2-1. Prepare ADDBA Response frame.
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (ADHOC_ON(pAd))
-			ActHeaderInit(pAd, &ADDframe.Hdr, pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-		else
-#ifdef QOS_DLS_SUPPORT
-		if (pAd->MacTab.Content[Elem->Wcid].ValidAsDls)
-			ActHeaderInit(pAd, &ADDframe.Hdr, pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-		else
-#endif // QOS_DLS_SUPPORT //
-			ActHeaderInit(pAd, &ADDframe.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAddr);
-	}
-#endif // CONFIG_STA_SUPPORT //
-	ADDframe.Category = CATEGORY_BA;
-	ADDframe.Action = ADDBA_RESP;
-	ADDframe.Token = pAddreqFrame->Token;
-	// What is the Status code??  need to check.
-	ADDframe.StatusCode = Status;
-	ADDframe.BaParm.BAPolicy = IMMED_BA;
-	ADDframe.BaParm.AMSDUSupported = 0;
-	ADDframe.BaParm.TID = pAddreqFrame->BaParm.TID;
-	ADDframe.BaParm.BufSize = min(((UCHAR)pAddreqFrame->BaParm.BufSize), (UCHAR)pAd->CommonCfg.BACapability.field.RxBAWinLimit);
-	if (ADDframe.BaParm.BufSize == 0)
-	{
-		ADDframe.BaParm.BufSize = 64;
-	}
-	ADDframe.TimeOutValue = 0; //pAddreqFrame->TimeOutValue;
-
-	*(USHORT *)(&ADDframe.BaParm) = cpu2le16(*(USHORT *)(&ADDframe.BaParm));
-	ADDframe.StatusCode = cpu2le16(ADDframe.StatusCode);
-	ADDframe.TimeOutValue = cpu2le16(ADDframe.TimeOutValue);
-
-	MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-					  sizeof(FRAME_ADDBA_RSP),  &ADDframe,
-			  END_OF_ARGS);
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s(%d): TID(%d), BufSize(%d) <== \n", __func__, Elem->Wcid, ADDframe.BaParm.TID,
-							  ADDframe.BaParm.BufSize));
-}
-
-
-VOID PeerAddBARspAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-
-{
-	//UCHAR		Idx, i;
-	//PUCHAR		   pOutBuffer = NULL;
-	PFRAME_ADDBA_RSP    pFrame = NULL;
-	//PBA_ORI_ENTRY		pBAEntry;
-
-	//ADDBA Response from unknown peer, ignore this.
-	if (Elem->Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s ==> Wcid(%d)\n", __func__, Elem->Wcid));
-
-	//hex_dump("PeerAddBARspAction()", Elem->Msg, Elem->MsgLen);
-
-	if (PeerAddBARspActionSanity(pAd, Elem->Msg, Elem->MsgLen))
-	{
-		pFrame = (PFRAME_ADDBA_RSP)(&Elem->Msg[0]);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("\t\t StatusCode = %d\n", pFrame->StatusCode));
-		switch (pFrame->StatusCode)
-		{
-			case 0:
-				// I want a BAsession with this peer as an originator.
-				BAOriSessionAdd(pAd, &pAd->MacTab.Content[Elem->Wcid], pFrame);
-				break;
-			default:
-				// check status == USED ???
-				BAOriSessionTearDown(pAd, Elem->Wcid, pFrame->BaParm.TID, TRUE, FALSE);
-				break;
-		}
-		// Rcv Decline StatusCode
-		if ((pFrame->StatusCode == 37)
-#ifdef CONFIG_STA_SUPPORT
-            || ((pAd->OpMode == OPMODE_STA) && STA_TGN_WIFI_ON(pAd) && (pFrame->StatusCode != 0))
-#endif // CONFIG_STA_SUPPORT //
-            )
-		{
-			pAd->MacTab.Content[Elem->Wcid].BADeclineBitmap |= 1<<pFrame->BaParm.TID;
-		}
-	}
-}
-
-VOID PeerDelBAAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-
-{
-	//UCHAR				Idx;
-	//PUCHAR				pOutBuffer = NULL;
-	PFRAME_DELBA_REQ    pDelFrame = NULL;
-
-	DBGPRINT(RT_DEBUG_TRACE,("%s ==>\n", __func__));
-	//DELBA Request from unknown peer, ignore this.
-	if (PeerDelBAActionSanity(pAd, Elem->Wcid, Elem->Msg, Elem->MsgLen))
-	{
-		pDelFrame = (PFRAME_DELBA_REQ)(&Elem->Msg[0]);
-		if (pDelFrame->DelbaParm.Initiator == ORIGINATOR)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("BA - PeerDelBAAction----> ORIGINATOR\n"));
-			BARecSessionTearDown(pAd, Elem->Wcid, pDelFrame->DelbaParm.TID, TRUE);
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("BA - PeerDelBAAction----> RECIPIENT, Reason = %d\n",  pDelFrame->ReasonCode));
-			//hex_dump("DelBA Frame", pDelFrame, Elem->MsgLen);
-			BAOriSessionTearDown(pAd, Elem->Wcid, pDelFrame->DelbaParm.TID, TRUE, FALSE);
-		}
-	}
-}
-
-
-BOOLEAN CntlEnqueueForRecv(
-						  IN PRTMP_ADAPTER		pAd,
-						  IN ULONG				Wcid,
-						  IN ULONG				MsgLen,
-						  IN PFRAME_BA_REQ		pMsg)
-{
-	PFRAME_BA_REQ   pFrame = pMsg;
-	//PRTMP_REORDERBUF	pBuffer;
-	//PRTMP_REORDERBUF	pDmaBuf;
-	PBA_REC_ENTRY pBAEntry;
-	//BOOLEAN 	Result;
-	ULONG   Idx;
-	//UCHAR	NumRxPkt;
-	UCHAR	TID;//, i;
-
-	TID = (UCHAR)pFrame->BARControl.TID;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s(): BAR-Wcid(%ld), Tid (%d)\n", __func__, Wcid, TID));
-	//hex_dump("BAR", (PCHAR) pFrame, MsgLen);
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return FALSE;
-
-	// First check the size, it MUST not exceed the mlme queue size
-	if (MsgLen > MGMT_DMA_BUFFER_SIZE)
-	{
-		DBGPRINT_ERR(("CntlEnqueueForRecv: frame too large, size = %ld \n", MsgLen));
-		return FALSE;
-	}
-	else if (MsgLen != sizeof(FRAME_BA_REQ))
-	{
-		DBGPRINT_ERR(("CntlEnqueueForRecv: BlockAck Request frame length size = %ld incorrect\n", MsgLen));
-		return FALSE;
-	}
-	else if (MsgLen != sizeof(FRAME_BA_REQ))
-	{
-		DBGPRINT_ERR(("CntlEnqueueForRecv: BlockAck Request frame length size = %ld incorrect\n", MsgLen));
-		return FALSE;
-	}
-
-	if ((Wcid < MAX_LEN_OF_MAC_TABLE) && (TID < 8))
-		{
-		// if this receiving packet is from SA that is in our OriEntry. Since WCID <9 has direct mapping. no need search.
-		Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID];
-		pBAEntry = &pAd->BATable.BARecEntry[Idx];
-		}
-		else
-		{
-		return FALSE;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("BAR(%ld) : Tid (%d) - %04x:%04x\n", Wcid, TID, pFrame->BAStartingSeq.field.StartSeq, pBAEntry->LastIndSeq ));
-
-	if (SEQ_SMALLER(pBAEntry->LastIndSeq, pFrame->BAStartingSeq.field.StartSeq, MAXSEQ))
-	{
-		//printk("BAR Seq = %x, LastIndSeq = %x\n", pFrame->BAStartingSeq.field.StartSeq, pBAEntry->LastIndSeq);
-		ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, pFrame->BAStartingSeq.field.StartSeq);
-		pBAEntry->LastIndSeq = (pFrame->BAStartingSeq.field.StartSeq == 0) ? MAXSEQ :(pFrame->BAStartingSeq.field.StartSeq -1);
-	}
-	//ba_refresh_reordering_mpdus(pAd, pBAEntry);
-	return TRUE;
-}
-
-/*
-Description : Send PSMP Action frame If PSMP mode switches.
-*/
-VOID SendPSMPAction(
-				   IN PRTMP_ADAPTER		pAd,
-				   IN UCHAR				Wcid,
-				   IN UCHAR				Psmp)
-{
-	PUCHAR          pOutBuffer = NULL;
-	NDIS_STATUS     NStatus;
-	//ULONG           Idx;
-	FRAME_PSMP_ACTION   Frame;
-	ULONG           FrameLen;
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);	 //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("BA - MlmeADDBAAction() allocate memory failed \n"));
-		return;
-	}
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		ActHeaderInit(pAd, &Frame.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->MacTab.Content[Wcid].Addr);
-#endif // CONFIG_STA_SUPPORT //
-
-	Frame.Category = CATEGORY_HT;
-	Frame.Action = SMPS_ACTION;
-	switch (Psmp)
-	{
-		case MMPS_ENABLE:
-			Frame.Psmp = 0;
-			break;
-		case MMPS_DYNAMIC:
-			Frame.Psmp = 3;
-			break;
-		case MMPS_STATIC:
-			Frame.Psmp = 1;
-			break;
-	}
-	MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-					  sizeof(FRAME_PSMP_ACTION),      &Frame,
-					  END_OF_ARGS);
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-	DBGPRINT(RT_DEBUG_ERROR,("HT - SendPSMPAction( %d )  \n", Frame.Psmp));
-}
-
-
-#define RADIO_MEASUREMENT_REQUEST_ACTION	0
-
-typedef struct PACKED
-{
-	UCHAR	RegulatoryClass;
-	UCHAR	ChannelNumber;
-	USHORT	RandomInterval;
-	USHORT	MeasurementDuration;
-	UCHAR	MeasurementMode;
-	UCHAR   BSSID[MAC_ADDR_LEN];
-	UCHAR	ReportingCondition;
-	UCHAR	Threshold;
-	UCHAR   SSIDIE[2];			// 2 byte
-} BEACON_REQUEST;
-
-typedef struct PACKED
-{
-	UCHAR	ID;
-	UCHAR	Length;
-	UCHAR	Token;
-	UCHAR	RequestMode;
-	UCHAR	Type;
-} MEASUREMENT_REQ;
-
-
-
-
-void convert_reordering_packet_to_preAMSDU_or_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN  UCHAR			FromWhichBSSID)
-{
-	PNDIS_PACKET	pRxPkt;
-	UCHAR			Header802_3[LENGTH_802_3];
-
-	// 1. get 802.3 Header
-	// 2. remove LLC
-	// 		a. pointer pRxBlk->pData to payload
-	//      b. modify pRxBlk->DataSize
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
-#endif // CONFIG_STA_SUPPORT //
-
-	ASSERT(pRxBlk->pRxPacket);
-	pRxPkt = RTPKT_TO_OSPKT(pRxBlk->pRxPacket);
-
-	RTPKT_TO_OSPKT(pRxPkt)->dev = get_netdev_from_bssid(pAd, FromWhichBSSID);
-	RTPKT_TO_OSPKT(pRxPkt)->data = pRxBlk->pData;
-	RTPKT_TO_OSPKT(pRxPkt)->len = pRxBlk->DataSize;
-	RTPKT_TO_OSPKT(pRxPkt)->tail = RTPKT_TO_OSPKT(pRxPkt)->data + RTPKT_TO_OSPKT(pRxPkt)->len;
-
-	//
-	// copy 802.3 header, if necessary
-	//
-	if (!RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU))
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-#ifdef LINUX
-			NdisMoveMemory(skb_push(pRxPkt, LENGTH_802_3), Header802_3, LENGTH_802_3);
-#endif
-#ifdef UCOS
-			NdisMoveMemory(net_pkt_push(pRxPkt, LENGTH_802_3), Header802_3, LENGTH_802_3);
-#endif
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-}
-
-
-#define INDICATE_LEGACY_OR_AMSDU(_pAd, _pRxBlk, _fromWhichBSSID)		\
-	do																	\
-	{																	\
-    	if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_AMSDU))						\
-    	{																\
-    		Indicate_AMSDU_Packet(_pAd, _pRxBlk, _fromWhichBSSID);		\
-    	}																\
-		else if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_EAP))					\
-		{																\
-			Indicate_EAPOL_Packet(_pAd, _pRxBlk, _fromWhichBSSID);		\
-		}																\
-    	else															\
-    	{																\
-    		Indicate_Legacy_Packet(_pAd, _pRxBlk, _fromWhichBSSID);		\
-    	}																\
-	} while (0);
-
-
-
-static VOID ba_enqueue_reordering_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PBA_REC_ENTRY	pBAEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	struct reordering_mpdu *mpdu_blk;
-	UINT16	Sequence = (UINT16) pRxBlk->pHeader->Sequence;
-
-	mpdu_blk = ba_mpdu_blk_alloc(pAd);
-	if (mpdu_blk != NULL)
-	{
-		// Write RxD buffer address & allocated buffer length
-		NdisAcquireSpinLock(&pBAEntry->RxReRingLock);
-
-		mpdu_blk->Sequence = Sequence;
-
-		mpdu_blk->bAMSDU = RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU);
-
-		convert_reordering_packet_to_preAMSDU_or_802_3_packet(pAd, pRxBlk, FromWhichBSSID);
-
-		STATS_INC_RX_PACKETS(pAd, FromWhichBSSID);
-
-        //
-		// it is necessary for reordering packet to record
-		// which BSS it come from
-		//
-		RTMP_SET_PACKET_IF(pRxBlk->pRxPacket, FromWhichBSSID);
-
-		mpdu_blk->pPacket = pRxBlk->pRxPacket;
-
-		if (ba_reordering_mpdu_insertsorted(&pBAEntry->list, mpdu_blk) == FALSE)
-		{
-			// had been already within reordering list
-			// don't indicate
-			RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_SUCCESS);
-			ba_mpdu_blk_free(pAd, mpdu_blk);
-		}
-
-		ASSERT((0<= pBAEntry->list.qlen)  && (pBAEntry->list.qlen <= pBAEntry->BAWinSize));
-		NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
-	}
-	else
-	{
-#if 0
-		DBGPRINT(RT_DEBUG_ERROR,  ("!!! (%d:%d) Can't allocate reordering mpdu blk\n",
-								   blk_count, pBAEntry->list.qlen));
-#else
-		DBGPRINT(RT_DEBUG_ERROR,  ("!!! (%d) Can't allocate reordering mpdu blk\n",
-								   pBAEntry->list.qlen));
-#endif
-		/*
-		 * flush all pending reordering mpdus
-		 * and receving mpdu to upper layer
-		 * make tcp/ip to take care reordering mechanism
-		 */
-		//ba_refresh_reordering_mpdus(pAd, pBAEntry);
-		ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, Sequence);
-
-		pBAEntry->LastIndSeq = Sequence;
-		INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Indicate this packet to upper layer or put it into reordering buffer
-
-	Parametrs:
-		pRxBlk         : carry necessary packet info 802.11 format
-		FromWhichBSSID : the packet received from which BSS
-
-	Return	:
-			  none
-
-	Note    :
-	          the packet queued into reordering buffer need to cover to 802.3 format
-			  or pre_AMSDU format
-	==========================================================================
- */
-
-VOID Indicate_AMPDU_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	USHORT				Idx;
-	PBA_REC_ENTRY		pBAEntry = NULL;
-	UINT16				Sequence = pRxBlk->pHeader->Sequence;
-	ULONG				Now32;
-	UCHAR				Wcid = pRxBlk->pRxWI->WirelessCliID;
-	UCHAR				TID = pRxBlk->pRxWI->TID;
-
-
-	if (!RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU) &&  (pRxBlk->DataSize > MAX_RX_PKT_LEN))
-	{
-#if 0 // sample take off, no use
-		static int err_size;
-
-		err_size++;
-		if (err_size > 20) {
-			 printk("AMPDU DataSize = %d\n", pRxBlk->DataSize);
-			 hex_dump("802.11 Header", (UCHAR *)pRxBlk->pHeader, 24);
-			 hex_dump("Payload", pRxBlk->pData, 64);
-			 err_size = 0;
-		}
-#endif
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-
-#if 0 // test
-	/* Rec BA Session had been torn down */
-	INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
-	return;
-#endif
-
-	if (Wcid < MAX_LEN_OF_MAC_TABLE)
-	{
-		Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID];
-		if (Idx == 0)
-		{
-			/* Rec BA Session had been torn down */
-			INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
-			return;
-		}
-		pBAEntry = &pAd->BATable.BARecEntry[Idx];
-	}
-	else
-	{
-		// impossible !!!
-		ASSERT(0);
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-	ASSERT(pBAEntry);
-
-	// update last rx time
-	NdisGetSystemUpTime(&Now32);
-
-	pBAEntry->rcvSeq = Sequence;
-
-
-	ba_flush_reordering_timeout_mpdus(pAd, pBAEntry, Now32);
-	pBAEntry->LastIndSeqAtTimer = Now32;
-
-	//
-	// Reset Last Indicate Sequence
-	//
-	if (pBAEntry->LastIndSeq == RESET_RCV_SEQ)
-	{
-		ASSERT((pBAEntry->list.qlen == 0) && (pBAEntry->list.next == NULL));
-
-		// reset rcv sequence of BA session
-		pBAEntry->LastIndSeq = Sequence;
-		pBAEntry->LastIndSeqAtTimer = Now32;
-		INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
-		return;
-	}
-
-
-	//
-	// I. Check if in order.
-	//
-	if (SEQ_STEPONE(Sequence, pBAEntry->LastIndSeq, MAXSEQ))
-	{
-		USHORT  LastIndSeq;
-
-		pBAEntry->LastIndSeq = Sequence;
-		INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
- 		LastIndSeq = ba_indicate_reordering_mpdus_in_order(pAd, pBAEntry, pBAEntry->LastIndSeq);
-		if (LastIndSeq != RESET_RCV_SEQ)
-		{
-			pBAEntry->LastIndSeq = LastIndSeq;
-		}
-		pBAEntry->LastIndSeqAtTimer = Now32;
-	}
-	//
-	// II. Drop Duplicated Packet
-	//
-	else if (Sequence == pBAEntry->LastIndSeq)
-	{
-
-		// drop and release packet
-		pBAEntry->nDropPacket++;
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-	}
-	//
-	// III. Drop Old Received Packet
-	//
-	else if (SEQ_SMALLER(Sequence, pBAEntry->LastIndSeq, MAXSEQ))
-	{
-
-		// drop and release packet
-		pBAEntry->nDropPacket++;
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-	}
-	//
-	// IV. Receive Sequence within Window Size
-	//
-	else if (SEQ_SMALLER(Sequence, (((pBAEntry->LastIndSeq+pBAEntry->BAWinSize+1)) & MAXSEQ), MAXSEQ))
-	{
-		ba_enqueue_reordering_packet(pAd, pBAEntry, pRxBlk, FromWhichBSSID);
-	}
-	//
-	// V. Receive seq surpasses Win(lastseq + nMSDU). So refresh all reorder buffer
-	//
-	else
-	{
-#if 0
-		ba_refresh_reordering_mpdus(pAd, pBAEntry);
-		INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
-#else
-		LONG WinStartSeq, TmpSeq;
-
-
-		TmpSeq = Sequence - (pBAEntry->BAWinSize) -1;
-		if (TmpSeq < 0)
-		{
-			TmpSeq = (MAXSEQ+1) + TmpSeq;
-		}
-		WinStartSeq = (TmpSeq+1) & MAXSEQ;
-		ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, WinStartSeq);
-		pBAEntry->LastIndSeq = WinStartSeq; //TmpSeq;
-
-		pBAEntry->LastIndSeqAtTimer = Now32;
-
-		ba_enqueue_reordering_packet(pAd, pBAEntry, pRxBlk, FromWhichBSSID);
-
-		TmpSeq = ba_indicate_reordering_mpdus_in_order(pAd, pBAEntry, pBAEntry->LastIndSeq);
-		if (TmpSeq != RESET_RCV_SEQ)
-		{
-			pBAEntry->LastIndSeq = TmpSeq;
-		}
-#endif
-	}
-}
-
-#endif // DOT11_N_SUPPORT //
-
+#include "../../rt2860/common/ba_action.c"
diff --git a/drivers/staging/rt2870/common/cmm_data.c b/drivers/staging/rt2870/common/cmm_data.c
index f8e0ebd..df775c3 100644
--- a/drivers/staging/rt2870/common/cmm_data.c
+++ b/drivers/staging/rt2870/common/cmm_data.c
@@ -1,2731 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-*/
-
-#include "../rt_config.h"
-
-#define MAX_TX_IN_TBTT		(16)
-
-
-UCHAR	SNAP_802_1H[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00};
-UCHAR	SNAP_BRIDGE_TUNNEL[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0xf8};
-// Add Cisco Aironet SNAP heade for CCX2 support
-UCHAR	SNAP_AIRONET[] = {0xaa, 0xaa, 0x03, 0x00, 0x40, 0x96, 0x00, 0x00};
-UCHAR	CKIP_LLC_SNAP[] = {0xaa, 0xaa, 0x03, 0x00, 0x40, 0x96, 0x00, 0x02};
-UCHAR	EAPOL_LLC_SNAP[]= {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00, 0x88, 0x8e};
-UCHAR	EAPOL[] = {0x88, 0x8e};
-UCHAR   TPID[] = {0x81, 0x00}; /* VLAN related */
-
-UCHAR	IPX[] = {0x81, 0x37};
-UCHAR	APPLE_TALK[] = {0x80, 0xf3};
-UCHAR	RateIdToPlcpSignal[12] = {
-	 0, /* RATE_1 */	1, /* RATE_2 */ 	2, /* RATE_5_5 */	3, /* RATE_11 */	// see BBP spec
-	11, /* RATE_6 */   15, /* RATE_9 */    10, /* RATE_12 */   14, /* RATE_18 */	// see IEEE802.11a-1999 p.14
-	 9, /* RATE_24 */  13, /* RATE_36 */	8, /* RATE_48 */   12  /* RATE_54 */ }; // see IEEE802.11a-1999 p.14
-
-UCHAR	 OfdmSignalToRateId[16] = {
-	RATE_54,  RATE_54,	RATE_54,  RATE_54,	// OFDM PLCP Signal = 0,  1,  2,  3 respectively
-	RATE_54,  RATE_54,	RATE_54,  RATE_54,	// OFDM PLCP Signal = 4,  5,  6,  7 respectively
-	RATE_48,  RATE_24,	RATE_12,  RATE_6,	// OFDM PLCP Signal = 8,  9,  10, 11 respectively
-	RATE_54,  RATE_36,	RATE_18,  RATE_9,	// OFDM PLCP Signal = 12, 13, 14, 15 respectively
-};
-
-UCHAR	 OfdmRateToRxwiMCS[12] = {
-	0,  0,	0,  0,
-	0,  1,	2,  3,	// OFDM rate 6,9,12,18 = rxwi mcs 0,1,2,3
-	4,  5,	6,  7,	// OFDM rate 24,36,48,54 = rxwi mcs 4,5,6,7
-};
-UCHAR	 RxwiMCSToOfdmRate[12] = {
-	RATE_6,  RATE_9,	RATE_12,  RATE_18,
-	RATE_24,  RATE_36,	RATE_48,  RATE_54,	// OFDM rate 6,9,12,18 = rxwi mcs 0,1,2,3
-	4,  5,	6,  7,	// OFDM rate 24,36,48,54 = rxwi mcs 4,5,6,7
-};
-
-char*   MCSToMbps[] = {"1Mbps","2Mbps","5.5Mbps","11Mbps","06Mbps","09Mbps","12Mbps","18Mbps","24Mbps","36Mbps","48Mbps","54Mbps","MM-0","MM-1","MM-2","MM-3","MM-4","MM-5","MM-6","MM-7","MM-8","MM-9","MM-10","MM-11","MM-12","MM-13","MM-14","MM-15","MM-32","ee1","ee2","ee3"};
-
-UCHAR default_cwmin[]={CW_MIN_IN_BITS, CW_MIN_IN_BITS, CW_MIN_IN_BITS-1, CW_MIN_IN_BITS-2};
-//UCHAR default_cwmax[]={CW_MAX_IN_BITS, CW_MAX_IN_BITS, CW_MIN_IN_BITS, CW_MIN_IN_BITS-1};
-UCHAR default_sta_aifsn[]={3,7,2,2};
-
-UCHAR MapUserPriorityToAccessCategory[8] = {QID_AC_BE, QID_AC_BK, QID_AC_BK, QID_AC_BE, QID_AC_VI, QID_AC_VI, QID_AC_VO, QID_AC_VO};
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		API for MLME to transmit management frame to AP (BSS Mode)
-	or station (IBSS Mode)
-
-	Arguments:
-		pAd Pointer to our adapter
-		pData		Pointer to the outgoing 802.11 frame
-		Length		Size of outgoing management frame
-
-	Return Value:
-		NDIS_STATUS_FAILURE
-		NDIS_STATUS_PENDING
-		NDIS_STATUS_SUCCESS
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS MiniportMMRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			QueIdx,
-	IN	PUCHAR			pData,
-	IN	UINT			Length)
-{
-	PNDIS_PACKET	pPacket;
-	NDIS_STATUS  	Status = NDIS_STATUS_SUCCESS;
-	ULONG	 		FreeNum;
-	UCHAR			IrqState;
-	UCHAR			rtmpHwHdr[TXINFO_SIZE + TXWI_SIZE]; //RTMP_HW_HDR_LEN];
-
-	ASSERT(Length <= MGMT_DMA_BUFFER_SIZE);
-
-	QueIdx=3;
-
-	// 2860C use Tx Ring
-
-	IrqState = pAd->irq_disabled;
-
-	do
-	{
-		// Reset is in progress, stop immediately
-		if ( RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS) ||
-			 RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST)||
-			 !RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP))
-		{
-			Status = NDIS_STATUS_FAILURE;
-			break;
-		}
-
-		// Check Free priority queue
-		// Since we use PBF Queue2 for management frame.  Its corresponding DMA ring should be using TxRing.
-
-		// 2860C use Tx Ring
-		if (pAd->MACVersion == 0x28600100)
-		{
-			FreeNum = GET_TXRING_FREENO(pAd, QueIdx);
-		}
-		else
-		{
-			FreeNum = GET_MGMTRING_FREENO(pAd);
-		}
-
-		if ((FreeNum > 0))
-		{
-			// We need to reserve space for rtmp hardware header. i.e., TxWI for RT2860 and TxInfo+TxWI for RT2870
-			NdisZeroMemory(&rtmpHwHdr, (TXINFO_SIZE + TXWI_SIZE));
-			Status = RTMPAllocateNdisPacket(pAd, &pPacket, (PUCHAR)&rtmpHwHdr, (TXINFO_SIZE + TXWI_SIZE), pData, Length);
-			if (Status != NDIS_STATUS_SUCCESS)
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("MiniportMMRequest (error:: can't allocate NDIS PACKET)\n"));
-				break;
-			}
-
-			//pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_CCK;
-			//pAd->CommonCfg.MlmeRate = RATE_2;
-
-
-			Status = MlmeHardTransmit(pAd, QueIdx, pPacket);
-			if (Status != NDIS_STATUS_SUCCESS)
-				RTMPFreeNdisPacket(pAd, pPacket);
-		}
-		else
-		{
-			pAd->RalinkCounters.MgmtRingFullCount++;
-			DBGPRINT(RT_DEBUG_ERROR, ("Qidx(%d), not enough space in MgmtRing, MgmtRingFullCount=%ld!\n",
-										QueIdx, pAd->RalinkCounters.MgmtRingFullCount));
-		}
-
-	} while (FALSE);
-
-
-	return Status;
-}
-
-
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Copy frame from waiting queue into relative ring buffer and set
-	appropriate ASIC register to kick hardware transmit function
-
-	Arguments:
-		pAd Pointer to our adapter
-		pBuffer 	Pointer to	memory of outgoing frame
-		Length		Size of outgoing management frame
-
-	Return Value:
-		NDIS_STATUS_FAILURE
-		NDIS_STATUS_PENDING
-		NDIS_STATUS_SUCCESS
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS MlmeHardTransmit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			QueIdx,
-	IN	PNDIS_PACKET	pPacket)
-{
-	if ((pAd->CommonCfg.RadarDetect.RDMode != RD_NORMAL_MODE)
-#ifdef CARRIER_DETECTION_SUPPORT
-#endif // CARRIER_DETECTION_SUPPORT //
-		)
-	{
-		return NDIS_STATUS_FAILURE;
-	}
-
-		return MlmeHardTransmitMgmtRing(pAd,QueIdx,pPacket);
-
-}
-
-
-
-NDIS_STATUS MlmeHardTransmitMgmtRing(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR	QueIdx,
-	IN	PNDIS_PACKET	pPacket)
-{
-	PACKET_INFO 	PacketInfo;
-	PUCHAR			pSrcBufVA;
-	UINT			SrcBufLen;
-	PHEADER_802_11	pHeader_802_11;
-	BOOLEAN 		bAckRequired, bInsertTimestamp;
-	UCHAR			MlmeRate;
-	PTXWI_STRUC 	pFirstTxWI;
-	MAC_TABLE_ENTRY	*pMacEntry = NULL;
-
-	RTMP_QueryPacketInfo(pPacket, &PacketInfo, &pSrcBufVA, &SrcBufLen);
-
-	// Make sure MGMT ring resource won't be used by other threads
-// sample, for IRQ LOCK -> SEM LOCK
-//	IrqState = pAd->irq_disabled;
-//	if (!IrqState)
-		RTMP_SEM_LOCK(&pAd->MgmtRingLock);
-
-
-	if (pSrcBufVA == NULL)
-	{
-		// The buffer shouldn't be NULL
-//		if (!IrqState)
-			RTMP_SEM_UNLOCK(&pAd->MgmtRingLock);
-		return NDIS_STATUS_FAILURE;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// outgoing frame always wakeup PHY to prevent frame lost
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-			AsicForceWakeup(pAd, TRUE);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	pFirstTxWI = (PTXWI_STRUC)(pSrcBufVA +  TXINFO_SIZE);
-	pHeader_802_11 = (PHEADER_802_11) (pSrcBufVA + TXINFO_SIZE + TXWI_SIZE); //TXWI_SIZE);
-
-	if (pHeader_802_11->Addr1[0] & 0x01)
-	{
-		MlmeRate = pAd->CommonCfg.BasicMlmeRate;
-	}
-	else
-	{
-		MlmeRate = pAd->CommonCfg.MlmeRate;
-	}
-
-	// Verify Mlme rate for a / g bands.
-	if ((pAd->LatchRfRegs.Channel > 14) && (MlmeRate < RATE_6)) // 11A band
-		MlmeRate = RATE_6;
-
-	if ((pHeader_802_11->FC.Type == BTYPE_DATA) &&
-		(pHeader_802_11->FC.SubType == SUBTYPE_QOS_NULL))
-	{
-		pMacEntry = MacTableLookup(pAd, pHeader_802_11->Addr1);
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Fixed W52 with Activity scan issue in ABG_MIXED and ABGN_MIXED mode.
-		if (pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED
-#ifdef DOT11_N_SUPPORT
-			|| pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED
-#endif // DOT11_N_SUPPORT //
-		)
-		{
-			if (pAd->LatchRfRegs.Channel > 14)
-				pAd->CommonCfg.MlmeTransmit.field.MODE = 1;
-			else
-				pAd->CommonCfg.MlmeTransmit.field.MODE = 0;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	//
-	// Should not be hard code to set PwrMgmt to 0 (PWR_ACTIVE)
-	// Snice it's been set to 0 while on MgtMacHeaderInit
-	// By the way this will cause frame to be send on PWR_SAVE failed.
-	//
-	// pHeader_802_11->FC.PwrMgmt = 0; // (pAd->StaCfg.Psm == PWR_SAVE);
-	//
-	// In WMM-UAPSD, mlme frame should be set psm as power saving but probe request frame
-#ifdef CONFIG_STA_SUPPORT
-    // Data-Null packets alse pass through MMRequest in RT2860, however, we hope control the psm bit to pass APSD
-	if ((pHeader_802_11->FC.Type != BTYPE_DATA) && (pHeader_802_11->FC.Type != BTYPE_CNTL))
-	{
-		if ((pAd->StaCfg.Psm == PWR_SAVE) &&
-			(pHeader_802_11->FC.SubType == SUBTYPE_ACTION))
-			pHeader_802_11->FC.PwrMgmt = PWR_SAVE;
-		else
-			pHeader_802_11->FC.PwrMgmt = PWR_ACTIVE;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	bInsertTimestamp = FALSE;
-	if (pHeader_802_11->FC.Type == BTYPE_CNTL) // must be PS-POLL
-	{
-#ifdef CONFIG_STA_SUPPORT
-		//Set PM bit in ps-poll, to fix WLK 1.2  PowerSaveMode_ext failure issue.
-		if ((pAd->OpMode == OPMODE_STA) && (pHeader_802_11->FC.SubType == SUBTYPE_PS_POLL))
-		{
-			pHeader_802_11->FC.PwrMgmt = PWR_SAVE;
-		}
-#endif // CONFIG_STA_SUPPORT //
-		bAckRequired = FALSE;
-	}
-	else // BTYPE_MGMT or BTYPE_DATA(must be NULL frame)
-	{
-		//pAd->Sequence++;
-		//pHeader_802_11->Sequence = pAd->Sequence;
-
-		if (pHeader_802_11->Addr1[0] & 0x01) // MULTICAST, BROADCAST
-		{
-			bAckRequired = FALSE;
-			pHeader_802_11->Duration = 0;
-		}
-		else
-		{
-			bAckRequired = TRUE;
-			pHeader_802_11->Duration = RTMPCalcDuration(pAd, MlmeRate, 14);
-			if (pHeader_802_11->FC.SubType == SUBTYPE_PROBE_RSP)
-			{
-				bInsertTimestamp = TRUE;
-			}
-		}
-	}
-
-	pHeader_802_11->Sequence = pAd->Sequence++;
-	if (pAd->Sequence >0xfff)
-		pAd->Sequence = 0;
-
-	// Before radar detection done, mgmt frame can not be sent but probe req
-	// Because we need to use probe req to trigger driver to send probe req in passive scan
-	if ((pHeader_802_11->FC.SubType != SUBTYPE_PROBE_REQ)
-		&& (pAd->CommonCfg.bIEEE80211H == 1)
-		&& (pAd->CommonCfg.RadarDetect.RDMode != RD_NORMAL_MODE))
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("MlmeHardTransmit --> radar detect not in normal mode !!!\n"));
-//		if (!IrqState)
-			RTMP_SEM_UNLOCK(&pAd->MgmtRingLock);
-		return (NDIS_STATUS_FAILURE);
-	}
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pHeader_802_11, DIR_WRITE, FALSE);
-#endif
-
-	//
-	// fill scatter-and-gather buffer list into TXD. Internally created NDIS PACKET
-	// should always has only one ohysical buffer, and the whole frame size equals
-	// to the first scatter buffer size
-	//
-
-	// Initialize TX Descriptor
-	// For inter-frame gap, the number is for this frame and next frame
-	// For MLME rate, we will fix as 2Mb to match other vendor's implement
-//	pAd->CommonCfg.MlmeTransmit.field.MODE = 1;
-
-// management frame doesn't need encryption. so use RESERVED_WCID no matter u are sending to specific wcid or not.
-	if (pMacEntry == NULL)
-	{
-		RTMPWriteTxWI(pAd, pFirstTxWI, FALSE, FALSE, bInsertTimestamp, FALSE, bAckRequired, FALSE,
-		0, RESERVED_WCID, (SrcBufLen - TXINFO_SIZE - TXWI_SIZE), PID_MGMT, 0,  (UCHAR)pAd->CommonCfg.MlmeTransmit.field.MCS, IFS_BACKOFF, FALSE, &pAd->CommonCfg.MlmeTransmit);
-	}
-	else
-	{
-		RTMPWriteTxWI(pAd, pFirstTxWI, FALSE, FALSE,
-					bInsertTimestamp, FALSE, bAckRequired, FALSE,
-					0, pMacEntry->Aid, (SrcBufLen - TXINFO_SIZE - TXWI_SIZE),
-					pMacEntry->MaxHTPhyMode.field.MCS, 0,
-					(UCHAR)pMacEntry->MaxHTPhyMode.field.MCS,
-					IFS_BACKOFF, FALSE, &pMacEntry->MaxHTPhyMode);
-	}
-
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange((PUCHAR)pFirstTxWI, TYPE_TXWI);
-#endif
-
-	// Now do hardware-depened kick out.
-	HAL_KickOutMgmtTx(pAd, QueIdx, pPacket, pSrcBufVA, SrcBufLen);
-
-	// Make sure to release MGMT ring resource
-//	if (!IrqState)
-		RTMP_SEM_UNLOCK(&pAd->MgmtRingLock);
-	return NDIS_STATUS_SUCCESS;
-}
-
-
-/********************************************************************************
-
-	New DeQueue Procedures.
-
- ********************************************************************************/
-
-#define DEQUEUE_LOCK(lock, bIntContext, IrqFlags) 				\
-			do{													\
-				if (bIntContext == FALSE)						\
-				RTMP_IRQ_LOCK((lock), IrqFlags);		\
-			}while(0)
-
-#define DEQUEUE_UNLOCK(lock, bIntContext, IrqFlags)				\
-			do{													\
-				if (bIntContext == FALSE)						\
-					RTMP_IRQ_UNLOCK((lock), IrqFlags);	\
-			}while(0)
-
-
-#if 0
-static VOID dumpTxBlk(TX_BLK *pTxBlk)
-{
-	NDIS_PACKET *pPacket;
-	int i, frameNum;
-	PQUEUE_ENTRY	pQEntry;
-
-	printk("Dump TX_BLK Structure:\n");
-	printk("\tTxFrameType=%d!\n", pTxBlk->TxFrameType);
-	printk("\tTotalFrameLen=%d\n", pTxBlk->TotalFrameLen);
-	printk("\tTotalFrameNum=%ld!\n", pTxBlk->TxPacketList.Number);
-	printk("\tTotalFragNum=%d!\n", pTxBlk->TotalFragNum);
-	printk("\tpPacketList=\n");
-
-	frameNum = pTxBlk->TxPacketList.Number;
-
-	for(i=0; i < frameNum; i++)
-	{	int j;
-		UCHAR	*pBuf;
-
-		pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-		pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-		if (pPacket)
-		{
-			pBuf = GET_OS_PKT_DATAPTR(pPacket);
-			printk("\t\t[%d]:ptr=0x%x, Len=%d!\n", i, (UINT32)(GET_OS_PKT_DATAPTR(pPacket)), GET_OS_PKT_LEN(pPacket));
-			printk("\t\t");
-			for (j =0 ; j < GET_OS_PKT_LEN(pPacket); j++)
-			{
-				printk("%02x ", (pBuf[j] & 0xff));
-				if (j == 16)
-					break;
-			}
-			InsertTailQueue(&pTxBlk->TxPacketList, PACKET_TO_QUEUE_ENTRY(pPacket));
-		}
-	}
-	printk("\tWcid=%d!\n", pTxBlk->Wcid);
-	printk("\tapidx=%d!\n", pTxBlk->apidx);
-	printk("----EndOfDump\n");
-
-}
-#endif
-
-
-/*
-	========================================================================
-	Tx Path design algorithm:
-		Basically, we divide the packets into four types, Broadcast/Multicast, 11N Rate(AMPDU, AMSDU, Normal), B/G Rate(ARALINK, Normal),
-		Specific Packet Type. Following show the classification rule and policy for each kinds of packets.
-				Classification Rule=>
-					Multicast: (*addr1 & 0x01) == 0x01
-					Specific : bDHCPFrame, bARPFrame, bEAPOLFrame, etc.
-					11N Rate : If peer support HT
-								(1).AMPDU  -- If TXBA is negotiated.
-								(2).AMSDU  -- If AMSDU is capable for both peer and ourself.
-											*). AMSDU can embedded in a AMPDU, but now we didn't support it.
-								(3).Normal -- Other packets which send as 11n rate.
-
-					B/G Rate : If peer is b/g only.
-								(1).ARALINK-- If both of peer/us supprot Ralink proprietary Aggregation and the TxRate is large than RATE_6
-								(2).Normal -- Other packets which send as b/g rate.
-					Fragment:
-								The packet must be unicast, NOT A-RALINK, NOT A-MSDU, NOT 11n, then can consider about fragment.
-
-				Classified Packet Handle Rule=>
-					Multicast:
-								No ACK, 		//pTxBlk->bAckRequired = FALSE;
-								No WMM, 		//pTxBlk->bWMM = FALSE;
-								No piggyback,   //pTxBlk->bPiggyBack = FALSE;
-								Force LowRate,  //pTxBlk->bForceLowRate = TRUE;
-					Specific :	Basically, for specific packet, we should handle it specifically, but now all specific packets are use
-									the same policy to handle it.
-								Force LowRate,  //pTxBlk->bForceLowRate = TRUE;
-
-					11N Rate :
-								No piggyback,	//pTxBlk->bPiggyBack = FALSE;
-
-								(1).AMSDU
-									pTxBlk->bWMM = TRUE;
-								(2).AMPDU
-									pTxBlk->bWMM = TRUE;
-								(3).Normal
-
-					B/G Rate :
-								(1).ARALINK
-
-								(2).Normal
-	========================================================================
-*/
-static UCHAR TxPktClassification(
-	IN RTMP_ADAPTER *pAd,
-	IN PNDIS_PACKET  pPacket)
-{
-	UCHAR			TxFrameType = TX_UNKOWN_FRAME;
-	UCHAR			Wcid;
-	MAC_TABLE_ENTRY	*pMacEntry = NULL;
-#ifdef DOT11_N_SUPPORT
-	BOOLEAN			bHTRate = FALSE;
-#endif // DOT11_N_SUPPORT //
-
-	Wcid = RTMP_GET_PACKET_WCID(pPacket);
-	if (Wcid == MCAST_WCID)
-	{	// Handle for RA is Broadcast/Multicast Address.
-		return TX_MCAST_FRAME;
-	}
-
-	// Handle for unicast packets
-	pMacEntry = &pAd->MacTab.Content[Wcid];
-	if (RTMP_GET_PACKET_LOWRATE(pPacket))
-	{	// It's a specific packet need to force low rate, i.e., bDHCPFrame, bEAPOLFrame, bWAIFrame
-		TxFrameType = TX_LEGACY_FRAME;
-	}
-#ifdef DOT11_N_SUPPORT
-	else if (IS_HT_RATE(pMacEntry))
-	{	// it's a 11n capable packet
-
-		// Depends on HTPhyMode to check if the peer support the HTRate transmission.
-		// 	Currently didn't support A-MSDU embedded in A-MPDU
-		bHTRate = TRUE;
-		if (RTMP_GET_PACKET_MOREDATA(pPacket) || (pMacEntry->PsMode == PWR_SAVE))
-			TxFrameType = TX_LEGACY_FRAME;
-#ifdef UAPSD_AP_SUPPORT
-		else if (RTMP_GET_PACKET_EOSP(pPacket))
-			TxFrameType = TX_LEGACY_FRAME;
-#endif // UAPSD_AP_SUPPORT //
-		else if((pMacEntry->TXBAbitmap & (1<<(RTMP_GET_PACKET_UP(pPacket)))) != 0)
-			return TX_AMPDU_FRAME;
-		else if(CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_AMSDU_INUSED))
-			return TX_AMSDU_FRAME;
-		else
-			TxFrameType = TX_LEGACY_FRAME;
-	}
-#endif // DOT11_N_SUPPORT //
-	else
-	{	// it's a legacy b/g packet.
-		if ((CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_AGGREGATION_CAPABLE) && pAd->CommonCfg.bAggregationCapable) &&
-			(RTMP_GET_PACKET_TXRATE(pPacket) >= RATE_6) &&
-			(!(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) && CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_WMM_CAPABLE))))
-		{	// if peer support Ralink Aggregation, we use it.
-			TxFrameType = TX_RALINK_FRAME;
-		}
-		else
-		{
-			TxFrameType = TX_LEGACY_FRAME;
-		}
-	}
-
-	// Currently, our fragment only support when a unicast packet send as NOT-ARALINK, NOT-AMSDU and NOT-AMPDU.
-	if ((RTMP_GET_PACKET_FRAGMENTS(pPacket) > 1) && (TxFrameType == TX_LEGACY_FRAME))
-		TxFrameType = TX_FRAG_FRAME;
-
-	return TxFrameType;
-}
-
-
-BOOLEAN RTMP_FillTxBlkInfo(
-	IN RTMP_ADAPTER *pAd,
-	IN TX_BLK *pTxBlk)
-{
-	PACKET_INFO			PacketInfo;
-	PNDIS_PACKET		pPacket;
-	PMAC_TABLE_ENTRY	pMacEntry = NULL;
-
-	pPacket = pTxBlk->pPacket;
-	RTMP_QueryPacketInfo(pPacket, &PacketInfo, &pTxBlk->pSrcBufHeader, &pTxBlk->SrcBufLen);
-
-	pTxBlk->Wcid	 	 		= RTMP_GET_PACKET_WCID(pPacket);
-	pTxBlk->apidx		 		= RTMP_GET_PACKET_IF(pPacket);
-	pTxBlk->UserPriority 		= RTMP_GET_PACKET_UP(pPacket);
-	pTxBlk->FrameGap = IFS_HTTXOP;		// ASIC determine Frame Gap
-
-	if (RTMP_GET_PACKET_CLEAR_EAP_FRAME(pTxBlk->pPacket))
-		TX_BLK_SET_FLAG(pTxBlk, fTX_bClearEAPFrame);
-	else
-		TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bClearEAPFrame);
-
-	// Default to clear this flag
-	TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bForceNonQoS);
-
-
-	if (pTxBlk->Wcid == MCAST_WCID)
-	{
-		pTxBlk->pMacEntry = NULL;
-		{
-#ifdef MCAST_RATE_SPECIFIC
-			PUCHAR pDA = GET_OS_PKT_DATAPTR(pPacket);
-			if (((*pDA & 0x01) == 0x01) && (*pDA != 0xff))
-				pTxBlk->pTransmit = &pAd->CommonCfg.MCastPhyMode;
-			else
-#endif // MCAST_RATE_SPECIFIC //
-				pTxBlk->pTransmit = &pAd->MacTab.Content[MCAST_WCID].HTPhyMode;
-		}
-
-		TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bAckRequired);	// AckRequired = FALSE, when broadcast packet in Adhoc mode.
-		//TX_BLK_SET_FLAG(pTxBlk, fTX_bForceLowRate);
-		TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bAllowFrag);
-		TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bWMM);
-		if (RTMP_GET_PACKET_MOREDATA(pPacket))
-		{
-			TX_BLK_SET_FLAG(pTxBlk, fTX_bMoreData);
-		}
-
-	}
-	else
-	{
-		pTxBlk->pMacEntry = &pAd->MacTab.Content[pTxBlk->Wcid];
-		pTxBlk->pTransmit = &pTxBlk->pMacEntry->HTPhyMode;
-
-		pMacEntry = pTxBlk->pMacEntry;
-
-
-		// For all unicast packets, need Ack unless the Ack Policy is not set as NORMAL_ACK.
-		if (pAd->CommonCfg.AckPolicy[pTxBlk->QueIdx] != NORMAL_ACK)
-			TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bAckRequired);
-		else
-			TX_BLK_SET_FLAG(pTxBlk, fTX_bAckRequired);
-
-		{
-
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			{
-
-				// If support WMM, enable it.
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) &&
-					CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_WMM_CAPABLE))
-					TX_BLK_SET_FLAG(pTxBlk, fTX_bWMM);
-			}
-#endif // CONFIG_STA_SUPPORT //
-		}
-
-		if (pTxBlk->TxFrameType == TX_LEGACY_FRAME)
-		{
-			if ( (RTMP_GET_PACKET_LOWRATE(pPacket)) ||
-                ((pAd->OpMode == OPMODE_AP) && (pMacEntry->MaxHTPhyMode.field.MODE == MODE_CCK) && (pMacEntry->MaxHTPhyMode.field.MCS == RATE_1)))
-			{	// Specific packet, i.e., bDHCPFrame, bEAPOLFrame, bWAIFrame, need force low rate.
-				pTxBlk->pTransmit = &pAd->MacTab.Content[MCAST_WCID].HTPhyMode;
-#ifdef DOT11_N_SUPPORT
-				// Modify the WMM bit for ICV issue. If we have a packet with EOSP field need to set as 1, how to handle it???
-				if (IS_HT_STA(pTxBlk->pMacEntry) &&
-					(CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_RALINK_CHIPSET)) &&
-					((pAd->CommonCfg.bRdg == TRUE) && CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_RDG_CAPABLE)))
-				{
-					TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bWMM);
-					TX_BLK_SET_FLAG(pTxBlk, fTX_bForceNonQoS);
-				}
-#endif // DOT11_N_SUPPORT //
-			}
-
-#ifdef DOT11_N_SUPPORT
-			if ( (IS_HT_RATE(pMacEntry) == FALSE) &&
-				(CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_PIGGYBACK_CAPABLE)))
-			{	// Currently piggy-back only support when peer is operate in b/g mode.
-				TX_BLK_SET_FLAG(pTxBlk, fTX_bPiggyBack);
-			}
-#endif // DOT11_N_SUPPORT //
-
-			if (RTMP_GET_PACKET_MOREDATA(pPacket))
-			{
-				TX_BLK_SET_FLAG(pTxBlk, fTX_bMoreData);
-			}
-#ifdef UAPSD_AP_SUPPORT
-			if (RTMP_GET_PACKET_EOSP(pPacket))
-			{
-				TX_BLK_SET_FLAG(pTxBlk, fTX_bWMM_UAPSD_EOSP);
-			}
-#endif // UAPSD_AP_SUPPORT //
-		}
-		else if (pTxBlk->TxFrameType == TX_FRAG_FRAME)
-		{
-			TX_BLK_SET_FLAG(pTxBlk, fTX_bAllowFrag);
-		}
-
-		pMacEntry->DebugTxCount++;
-	}
-
-	return TRUE;
-}
-
-
-BOOLEAN CanDoAggregateTransmit(
-	IN RTMP_ADAPTER *pAd,
-	IN NDIS_PACKET *pPacket,
-	IN TX_BLK		*pTxBlk)
-{
-
-	//printk("Check if can do aggregation! TxFrameType=%d!\n", pTxBlk->TxFrameType);
-
-	if (RTMP_GET_PACKET_WCID(pPacket) == MCAST_WCID)
-		return FALSE;
-
-	if (RTMP_GET_PACKET_DHCP(pPacket) ||
-		RTMP_GET_PACKET_EAPOL(pPacket) ||
-		RTMP_GET_PACKET_WAI(pPacket))
-		return FALSE;
-
-	if ((pTxBlk->TxFrameType == TX_AMSDU_FRAME) &&
-		((pTxBlk->TotalFrameLen + GET_OS_PKT_LEN(pPacket))> (RX_BUFFER_AGGRESIZE - 100)))
-	{	// For AMSDU, allow the packets with total length < max-amsdu size
-		return FALSE;
-	}
-
-	if ((pTxBlk->TxFrameType == TX_RALINK_FRAME) &&
-		(pTxBlk->TxPacketList.Number == 2))
-	{	// For RALINK-Aggregation, allow two frames in one batch.
-		return FALSE;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	if ((INFRA_ON(pAd)) && (pAd->OpMode == OPMODE_STA)) // must be unicast to AP
-		return TRUE;
-	else
-#endif // CONFIG_STA_SUPPORT //
-		return FALSE;
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		To do the enqueue operation and extract the first item of waiting
-		list. If a number of available shared memory segments could meet
-		the request of extracted item, the extracted item will be fragmented
-		into shared memory segments.
-
-	Arguments:
-		pAd Pointer to our adapter
-		pQueue		Pointer to Waiting Queue
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID RTMPDeQueuePacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  BOOLEAN         bIntContext,
-	IN  UCHAR			QIdx, /* BulkOutPipeId */
-	IN  UCHAR           Max_Tx_Packets)
-{
-	PQUEUE_ENTRY    pEntry = NULL;
-	PNDIS_PACKET 	pPacket;
-	NDIS_STATUS     Status = NDIS_STATUS_SUCCESS;
-	UCHAR           Count=0;
-	PQUEUE_HEADER   pQueue;
-	ULONG           FreeNumber[NUM_OF_TX_RING];
-	UCHAR			QueIdx, sQIdx, eQIdx;
-	unsigned long	IrqFlags = 0;
-	BOOLEAN			hasTxDesc = FALSE;
-	TX_BLK			TxBlk;
-	TX_BLK			*pTxBlk;
-
-#ifdef DBG_DIAGNOSE
-	BOOLEAN			firstRound;
-	RtmpDiagStruct	*pDiagStruct = &pAd->DiagStruct;
-#endif
-
-
-	if (QIdx == NUM_OF_TX_RING)
-	{
-		sQIdx = 0;
-		eQIdx = 3;	// 4 ACs, start from 0.
-	}
-	else
-	{
-		sQIdx = eQIdx = QIdx;
-	}
-
-	for (QueIdx=sQIdx; QueIdx <= eQIdx; QueIdx++)
-	{
-		Count=0;
-
-		RT28XX_START_DEQUEUE(pAd, QueIdx, IrqFlags);
-
-#ifdef DBG_DIAGNOSE
-		firstRound = ((QueIdx == 0) ? TRUE : FALSE);
-#endif // DBG_DIAGNOSE //
-
-		while (1)
-		{
-			if ((RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS |
-										fRTMP_ADAPTER_RADIO_OFF |
-										fRTMP_ADAPTER_RESET_IN_PROGRESS |
-										fRTMP_ADAPTER_HALT_IN_PROGRESS |
-										fRTMP_ADAPTER_NIC_NOT_EXIST))))
-			{
-				RT28XX_STOP_DEQUEUE(pAd, QueIdx, IrqFlags);
-				return;
-			}
-
-			if (Count >= Max_Tx_Packets)
-				break;
-
-			DEQUEUE_LOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-			if (&pAd->TxSwQueue[QueIdx] == NULL)
-			{
-#ifdef DBG_DIAGNOSE
-				if (firstRound == TRUE)
-					pDiagStruct->TxSWQueCnt[pDiagStruct->ArrayCurIdx][0]++;
-#endif // DBG_DIAGNOSE //
-				DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-				break;
-			}
-
-
-			// probe the Queue Head
-			pQueue = &pAd->TxSwQueue[QueIdx];
-			if ((pEntry = pQueue->Head) == NULL)
-			{
-				DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-				break;
-			}
-
-			pTxBlk = &TxBlk;
-			NdisZeroMemory((PUCHAR)pTxBlk, sizeof(TX_BLK));
-			//InitializeQueueHeader(&pTxBlk->TxPacketList);		// Didn't need it because we already memzero it.
-			pTxBlk->QueIdx = QueIdx;
-
-			pPacket = QUEUE_ENTRY_TO_PKT(pEntry);
-
-			// Early check to make sure we have enoguh Tx Resource.
-			hasTxDesc = RT28XX_HAS_ENOUGH_FREE_DESC(pAd, pTxBlk, FreeNumber[QueIdx], pPacket);
-			if (!hasTxDesc)
-			{
-				pAd->PrivateInfo.TxRingFullCnt++;
-
-				DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-
-				break;
-			}
-
-			pTxBlk->TxFrameType = TxPktClassification(pAd, pPacket);
-			pEntry = RemoveHeadQueue(pQueue);
-			pTxBlk->TotalFrameNum++;
-			pTxBlk->TotalFragNum += RTMP_GET_PACKET_FRAGMENTS(pPacket);	// The real fragment number maybe vary
-			pTxBlk->TotalFrameLen += GET_OS_PKT_LEN(pPacket);
-			pTxBlk->pPacket = pPacket;
-			InsertTailQueue(&pTxBlk->TxPacketList, PACKET_TO_QUEUE_ENTRY(pPacket));
-
-			if (pTxBlk->TxFrameType == TX_RALINK_FRAME || pTxBlk->TxFrameType == TX_AMSDU_FRAME)
-			{
-				// Enhance SW Aggregation Mechanism
-				if (NEED_QUEUE_BACK_FOR_AGG(pAd, QueIdx, FreeNumber[QueIdx], pTxBlk->TxFrameType))
-				{
-					InsertHeadQueue(pQueue, PACKET_TO_QUEUE_ENTRY(pPacket));
-					DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-					break;
-				}
-
-				do{
-					if((pEntry = pQueue->Head) == NULL)
-						break;
-
-					// For TX_AMSDU_FRAME/TX_RALINK_FRAME, Need to check if next pakcet can do aggregation.
-					pPacket = QUEUE_ENTRY_TO_PKT(pEntry);
-					FreeNumber[QueIdx] = GET_TXRING_FREENO(pAd, QueIdx);
-					hasTxDesc = RT28XX_HAS_ENOUGH_FREE_DESC(pAd, pTxBlk, FreeNumber[QueIdx], pPacket);
-					if ((hasTxDesc == FALSE) || (CanDoAggregateTransmit(pAd, pPacket, pTxBlk) == FALSE))
-						break;
-
-					//Remove the packet from the TxSwQueue and insert into pTxBlk
-					pEntry = RemoveHeadQueue(pQueue);
-					ASSERT(pEntry);
-					pPacket = QUEUE_ENTRY_TO_PKT(pEntry);
-					pTxBlk->TotalFrameNum++;
-					pTxBlk->TotalFragNum += RTMP_GET_PACKET_FRAGMENTS(pPacket);	// The real fragment number maybe vary
-					pTxBlk->TotalFrameLen += GET_OS_PKT_LEN(pPacket);
-					InsertTailQueue(&pTxBlk->TxPacketList, PACKET_TO_QUEUE_ENTRY(pPacket));
-				}while(1);
-
-				if (pTxBlk->TxPacketList.Number == 1)
-					pTxBlk->TxFrameType = TX_LEGACY_FRAME;
-			}
-
-#ifdef RT2870
-			DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-#endif // RT2870 //
-
-			Count += pTxBlk->TxPacketList.Number;
-
-				// Do HardTransmit now.
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				Status = STAHardTransmit(pAd, pTxBlk, QueIdx);
-#endif // CONFIG_STA_SUPPORT //
-
-
-#if 0	// We should not break if HardTransmit failed. Well, at least now we should not!
-			if (Status != NDIS_STATUS_SUCCESS)
-			{
-				DBGPRINT(RT_DEBUG_TRACE /*RT_DEBUG_INFO*/,("RTMPHardTransmit return failed!!!\n"));
-				break;
-			}
-#endif
-		}
-
-		RT28XX_STOP_DEQUEUE(pAd, QueIdx, IrqFlags);
-
-#ifdef RT2870
-		if (!hasTxDesc)
-			RTUSBKickBulkOut(pAd);
-#endif // RT2870 //
-
-#ifdef BLOCK_NET_IF
-		if ((pAd->blockQueueTab[QueIdx].SwTxQueueBlockFlag == TRUE)
-			&& (pAd->TxSwQueue[QueIdx].Number < 1))
-		{
-			releaseNetIf(&pAd->blockQueueTab[QueIdx]);
-		}
-#endif // BLOCK_NET_IF //
-
-	}
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Calculates the duration which is required to transmit out frames
-	with given size and specified rate.
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		Rate			Transmit rate
-		Size			Frame size in units of byte
-
-	Return Value:
-		Duration number in units of usec
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-USHORT	RTMPCalcDuration(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Rate,
-	IN	ULONG			Size)
-{
-	ULONG	Duration = 0;
-
-	if (Rate < RATE_FIRST_OFDM_RATE) // CCK
-	{
-		if ((Rate > RATE_1) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED))
-			Duration = 96;	// 72+24 preamble+plcp
-		else
-			Duration = 192; // 144+48 preamble+plcp
-
-		Duration += (USHORT)((Size << 4) / RateIdTo500Kbps[Rate]);
-		if ((Size << 4) % RateIdTo500Kbps[Rate])
-			Duration ++;
-	}
-	else if (Rate <= RATE_LAST_OFDM_RATE)// OFDM rates
-	{
-		Duration = 20 + 6;		// 16+4 preamble+plcp + Signal Extension
-		Duration += 4 * (USHORT)((11 + Size * 4) / RateIdTo500Kbps[Rate]);
-		if ((11 + Size * 4) % RateIdTo500Kbps[Rate])
-			Duration += 4;
-	}
-	else	//mimo rate
-	{
-		Duration = 20 + 6;		// 16+4 preamble+plcp + Signal Extension
-	}
-
-	return (USHORT)Duration;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Calculates the duration which is required to transmit out frames
-	with given size and specified rate.
-
-	Arguments:
-		pTxWI		Pointer to head of each MPDU to HW.
-		Ack 		Setting for Ack requirement bit
-		Fragment	Setting for Fragment bit
-		RetryMode	Setting for retry mode
-		Ifs 		Setting for IFS gap
-		Rate		Setting for transmit rate
-		Service 	Setting for service
-		Length		Frame length
-		TxPreamble	Short or Long preamble when using CCK rates
-		QueIdx - 0-3, according to 802.11e/d4.4 June/2003
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-    See also : BASmartHardTransmit()    !!!
-
-	========================================================================
-*/
-VOID RTMPWriteTxWI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXWI_STRUC 	pOutTxWI,
-	IN	BOOLEAN			FRAG,
-	IN	BOOLEAN			CFACK,
-	IN	BOOLEAN			InsTimestamp,
-	IN	BOOLEAN 		AMPDU,
-	IN	BOOLEAN 		Ack,
-	IN	BOOLEAN 		NSeq,		// HW new a sequence.
-	IN	UCHAR			BASize,
-	IN	UCHAR			WCID,
-	IN	ULONG			Length,
-	IN	UCHAR 			PID,
-	IN	UCHAR			TID,
-	IN	UCHAR			TxRate,
-	IN	UCHAR			Txopmode,
-	IN	BOOLEAN			CfAck,
-	IN	HTTRANSMIT_SETTING	*pTransmit)
-{
-	PMAC_TABLE_ENTRY	pMac = NULL;
-	TXWI_STRUC 		TxWI;
-	PTXWI_STRUC 	pTxWI;
-
-	if (WCID < MAX_LEN_OF_MAC_TABLE)
-		pMac = &pAd->MacTab.Content[WCID];
-
-	//
-	// Always use Long preamble before verifiation short preamble functionality works well.
-	// Todo: remove the following line if short preamble functionality works
-	//
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-	NdisZeroMemory(&TxWI, TXWI_SIZE);
-	pTxWI = &TxWI;
-
-	pTxWI->FRAG= FRAG;
-
-	pTxWI->CFACK = CFACK;
-	pTxWI->TS= InsTimestamp;
-	pTxWI->AMPDU = AMPDU;
-	pTxWI->ACK = Ack;
-	pTxWI->txop= Txopmode;
-
-	pTxWI->NSEQ = NSeq;
-	// John tune the performace with Intel Client in 20 MHz performance
-#ifdef DOT11_N_SUPPORT
-	BASize = pAd->CommonCfg.TxBASize;
-
-	if( BASize >7 )
-		BASize =7;
-	pTxWI->BAWinSize = BASize;
-	pTxWI->ShortGI = pTransmit->field.ShortGI;
-	pTxWI->STBC = pTransmit->field.STBC;
-#endif // DOT11_N_SUPPORT //
-
-	pTxWI->WirelessCliID = WCID;
-	pTxWI->MPDUtotalByteCount = Length;
-	pTxWI->PacketId = PID;
-
-	// If CCK or OFDM, BW must be 20
-	pTxWI->BW = (pTransmit->field.MODE <= MODE_OFDM) ? (BW_20) : (pTransmit->field.BW);
-#ifdef DOT11N_DRAFT3
-	if (pTxWI->BW)
-		pTxWI->BW = (pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth == 0) ? (BW_20) : (pTransmit->field.BW);
-#endif // DOT11N_DRAFT3 //
-
-	pTxWI->MCS = pTransmit->field.MCS;
-	pTxWI->PHYMODE = pTransmit->field.MODE;
-	pTxWI->CFACK = CfAck;
-
-#ifdef DOT11_N_SUPPORT
-	if (pMac)
-	{
-		if (pAd->CommonCfg.bMIMOPSEnable)
-		{
-			if ((pMac->MmpsMode == MMPS_DYNAMIC) && (pTransmit->field.MCS > 7))
-			{
-				// Dynamic MIMO Power Save Mode
-				pTxWI->MIMOps = 1;
-			}
-			else if (pMac->MmpsMode == MMPS_STATIC)
-			{
-				// Static MIMO Power Save Mode
-				if (pTransmit->field.MODE >= MODE_HTMIX && pTransmit->field.MCS > 7)
-				{
-					pTxWI->MCS = 7;
-					pTxWI->MIMOps = 0;
-				}
-			}
-		}
-		//pTxWI->MIMOps = (pMac->PsMode == PWR_MMPS)? 1:0;
-		if (pMac->bIAmBadAtheros && (pMac->WepStatus != Ndis802_11WEPDisabled))
-		{
-			pTxWI->MpduDensity = 7;
-		}
-		else
-		{
-			pTxWI->MpduDensity = pMac->MpduDensity;
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-	pTxWI->PacketId = pTxWI->MCS;
-	NdisMoveMemory(pOutTxWI, &TxWI, sizeof(TXWI_STRUC));
-}
-
-
-VOID RTMPWriteTxWI_Data(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	OUT PTXWI_STRUC		pTxWI,
-	IN	TX_BLK				*pTxBlk)
-{
-	HTTRANSMIT_SETTING	*pTransmit;
-	PMAC_TABLE_ENTRY	pMacEntry;
-#ifdef DOT11_N_SUPPORT
-	UCHAR				BASize;
-#endif // DOT11_N_SUPPORT //
-
-
-	ASSERT(pTxWI);
-
-	pTransmit = pTxBlk->pTransmit;
-	pMacEntry = pTxBlk->pMacEntry;
-
-
-	//
-	// Always use Long preamble before verifiation short preamble functionality works well.
-	// Todo: remove the following line if short preamble functionality works
-	//
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-	NdisZeroMemory(pTxWI, TXWI_SIZE);
-
-	pTxWI->FRAG		= TX_BLK_TEST_FLAG(pTxBlk, fTX_bAllowFrag);
-	pTxWI->ACK		= TX_BLK_TEST_FLAG(pTxBlk, fTX_bAckRequired);
-	pTxWI->txop		= pTxBlk->FrameGap;
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-	if (pMacEntry &&
-		(pAd->StaCfg.BssType == BSS_INFRA) &&
-		(pMacEntry->ValidAsDls == TRUE))
-		pTxWI->WirelessCliID = BSSID_WCID;
-	else
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-		pTxWI->WirelessCliID		= pTxBlk->Wcid;
-
-	pTxWI->MPDUtotalByteCount	= pTxBlk->MpduHeaderLen + pTxBlk->SrcBufLen;
-	pTxWI->CFACK				= TX_BLK_TEST_FLAG(pTxBlk, fTX_bPiggyBack);
-
-	// If CCK or OFDM, BW must be 20
-	pTxWI->BW = (pTransmit->field.MODE <= MODE_OFDM) ? (BW_20) : (pTransmit->field.BW);
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	if (pTxWI->BW)
-		pTxWI->BW = (pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth == 0) ? (BW_20) : (pTransmit->field.BW);
-#endif // DOT11N_DRAFT3 //
-	pTxWI->AMPDU	= ((pTxBlk->TxFrameType == TX_AMPDU_FRAME) ? TRUE : FALSE);
-
-	// John tune the performace with Intel Client in 20 MHz performance
-	BASize = pAd->CommonCfg.TxBASize;
-	if((pTxBlk->TxFrameType == TX_AMPDU_FRAME) && (pMacEntry))
-	{
-		UCHAR		RABAOriIdx = 0;	//The RA's BA Originator table index.
-
-		RABAOriIdx = pTxBlk->pMacEntry->BAOriWcidArray[pTxBlk->UserPriority];
-		BASize = pAd->BATable.BAOriEntry[RABAOriIdx].BAWinSize;
-	}
-
-#if 0 // 3*3
-	if (BASize > 7)
-		BASize = 7;
-#endif
-
-	pTxWI->TxBF = pTransmit->field.TxBF;
-	pTxWI->BAWinSize = BASize;
-	pTxWI->ShortGI = pTransmit->field.ShortGI;
-	pTxWI->STBC = pTransmit->field.STBC;
-#endif // DOT11_N_SUPPORT //
-
-	pTxWI->MCS = pTransmit->field.MCS;
-	pTxWI->PHYMODE = pTransmit->field.MODE;
-
-#ifdef DOT11_N_SUPPORT
-	if (pMacEntry)
-	{
-		if ((pMacEntry->MmpsMode == MMPS_DYNAMIC) && (pTransmit->field.MCS > 7))
-		{
-			// Dynamic MIMO Power Save Mode
-			pTxWI->MIMOps = 1;
-		}
-		else if (pMacEntry->MmpsMode == MMPS_STATIC)
-		{
-			// Static MIMO Power Save Mode
-			if (pTransmit->field.MODE >= MODE_HTMIX && pTransmit->field.MCS > 7)
-			{
-				pTxWI->MCS = 7;
-				pTxWI->MIMOps = 0;
-			}
-		}
-
-		if (pMacEntry->bIAmBadAtheros && (pMacEntry->WepStatus != Ndis802_11WEPDisabled))
-		{
-			pTxWI->MpduDensity = 7;
-		}
-		else
-		{
-			pTxWI->MpduDensity = pMacEntry->MpduDensity;
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-#ifdef DBG_DIAGNOSE
-		if (pTxBlk->QueIdx== 0)
-		{
-			pAd->DiagStruct.TxDataCnt[pAd->DiagStruct.ArrayCurIdx]++;
-			pAd->DiagStruct.TxMcsCnt[pAd->DiagStruct.ArrayCurIdx][pTxWI->MCS]++;
-		}
-#endif // DBG_DIAGNOSE //
-
-	// for rate adapation
-	pTxWI->PacketId = pTxWI->MCS;
-}
-
-
-VOID RTMPWriteTxWI_Cache(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	OUT PTXWI_STRUC		pTxWI,
-	IN	TX_BLK				*pTxBlk)
-{
-	PHTTRANSMIT_SETTING	/*pTxHTPhyMode,*/ pTransmit;
-	PMAC_TABLE_ENTRY	pMacEntry;
-
-	//
-	// update TXWI
-	//
-	pMacEntry = pTxBlk->pMacEntry;
-	pTransmit = pTxBlk->pTransmit;
-
-	if (pMacEntry->bAutoTxRateSwitch)
-	{
-		pTxWI->txop = IFS_HTTXOP;
-
-		// If CCK or OFDM, BW must be 20
-		pTxWI->BW = (pTransmit->field.MODE <= MODE_OFDM) ? (BW_20) : (pTransmit->field.BW);
-		pTxWI->ShortGI = pTransmit->field.ShortGI;
-		pTxWI->STBC = pTransmit->field.STBC;
-
-		pTxWI->MCS = pTransmit->field.MCS;
-		pTxWI->PHYMODE = pTransmit->field.MODE;
-
-		// set PID for TxRateSwitching
-		pTxWI->PacketId = pTransmit->field.MCS;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	pTxWI->AMPDU = ((pMacEntry->NoBADataCountDown == 0) ? TRUE: FALSE);
-	pTxWI->MIMOps = 0;
-
-#ifdef DOT11N_DRAFT3
-	if (pTxWI->BW)
-		pTxWI->BW = (pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth == 0) ? (BW_20) : (pTransmit->field.BW);
-#endif // DOT11N_DRAFT3 //
-
-	if (pAd->CommonCfg.bMIMOPSEnable)
-	{
-		// MIMO Power Save Mode
-		if ((pMacEntry->MmpsMode == MMPS_DYNAMIC) && (pTransmit->field.MCS > 7))
-		{
-			// Dynamic MIMO Power Save Mode
-			pTxWI->MIMOps = 1;
-		}
-		else if (pMacEntry->MmpsMode == MMPS_STATIC)
-		{
-			// Static MIMO Power Save Mode
-			if ((pTransmit->field.MODE >= MODE_HTMIX) && (pTransmit->field.MCS > 7))
-			{
-				pTxWI->MCS = 7;
-				pTxWI->MIMOps = 0;
-			}
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-#ifdef DBG_DIAGNOSE
-	if (pTxBlk->QueIdx== 0)
-	{
-		pAd->DiagStruct.TxDataCnt[pAd->DiagStruct.ArrayCurIdx]++;
-		pAd->DiagStruct.TxMcsCnt[pAd->DiagStruct.ArrayCurIdx][pTxWI->MCS]++;
-	}
-#endif // DBG_DIAGNOSE //
-
-	pTxWI->MPDUtotalByteCount = pTxBlk->MpduHeaderLen + pTxBlk->SrcBufLen;
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Calculates the duration which is required to transmit out frames
-	with given size and specified rate.
-
-	Arguments:
-		pTxD		Pointer to transmit descriptor
-		Ack 		Setting for Ack requirement bit
-		Fragment	Setting for Fragment bit
-		RetryMode	Setting for retry mode
-		Ifs 		Setting for IFS gap
-		Rate		Setting for transmit rate
-		Service 	Setting for service
-		Length		Frame length
-		TxPreamble	Short or Long preamble when using CCK rates
-		QueIdx - 0-3, according to 802.11e/d4.4 June/2003
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-VOID RTMPWriteTxDescriptor(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXD_STRUC		pTxD,
-	IN	BOOLEAN 		bWIV,
-	IN	UCHAR			QueueSEL)
-{
-	//
-	// Always use Long preamble before verifiation short preamble functionality works well.
-	// Todo: remove the following line if short preamble functionality works
-	//
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-
-	pTxD->WIV	= (bWIV) ? 1: 0;
-	pTxD->QSEL= (QueueSEL);
-	//RT2860c??  fixed using EDCA queue for test...  We doubt Queue1 has problem.  2006-09-26 Jan
-	//pTxD->QSEL= FIFO_EDCA;
-	if (pAd->bGenOneHCCA == TRUE)
-		pTxD->QSEL= FIFO_HCCA;
-	pTxD->DMADONE = 0;
-}
-
-
-// should be called only when -
-// 1. MEADIA_CONNECTED
-// 2. AGGREGATION_IN_USED
-// 3. Fragmentation not in used
-// 4. either no previous frame (pPrevAddr1=NULL) .OR. previoud frame is aggregatible
-BOOLEAN TxFrameIsAggregatible(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pPrevAddr1,
-	IN	PUCHAR			p8023hdr)
-{
-
-	// can't aggregate EAPOL (802.1x) frame
-	if ((p8023hdr[12] == 0x88) && (p8023hdr[13] == 0x8e))
-		return FALSE;
-
-	// can't aggregate multicast/broadcast frame
-	if (p8023hdr[0] & 0x01)
-		return FALSE;
-
-	if (INFRA_ON(pAd)) // must be unicast to AP
-		return TRUE;
-	else if ((pPrevAddr1 == NULL) || MAC_ADDR_EQUAL(pPrevAddr1, p8023hdr)) // unicast to same STA
-		return TRUE;
-	else
-		return FALSE;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-	   Check the MSDU Aggregation policy
-	1.HT aggregation is A-MSDU
-	2.legaacy rate aggregation is software aggregation by Ralink.
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-BOOLEAN PeerIsAggreOn(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	ULONG		   TxRate,
-	IN	PMAC_TABLE_ENTRY pMacEntry)
-{
-	ULONG	AFlags = (fCLIENT_STATUS_AMSDU_INUSED | fCLIENT_STATUS_AGGREGATION_CAPABLE);
-
-	if (pMacEntry != NULL && CLIENT_STATUS_TEST_FLAG(pMacEntry, AFlags))
-	{
-#ifdef DOT11_N_SUPPORT
-		if (pMacEntry->HTPhyMode.field.MODE >= MODE_HTMIX)
-		{
-			return TRUE;
-		}
-#endif // DOT11_N_SUPPORT //
-
-#ifdef AGGREGATION_SUPPORT
-		if (TxRate >= RATE_6 && pAd->CommonCfg.bAggregationCapable && (!(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) && CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_WMM_CAPABLE))))
-		{	// legacy  Ralink Aggregation support
-			return TRUE;
-		}
-#endif // AGGREGATION_SUPPORT //
-	}
-
-	return FALSE;
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Check and fine the packet waiting in SW queue with highest priority
-
-	Arguments:
-		pAd Pointer to our adapter
-
-	Return Value:
-		pQueue		Pointer to Waiting Queue
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-PQUEUE_HEADER	RTMPCheckTxSwQueue(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT PUCHAR			pQueIdx)
-{
-
-	ULONG	Number;
-	// 2004-11-15 to be removed. test aggregation only
-//	if ((OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED)) && (*pNumber < 2))
-//		 return NULL;
-
-	Number = pAd->TxSwQueue[QID_AC_BK].Number
-			 + pAd->TxSwQueue[QID_AC_BE].Number
-			 + pAd->TxSwQueue[QID_AC_VI].Number
-			 + pAd->TxSwQueue[QID_AC_VO].Number
-			 + pAd->TxSwQueue[QID_HCCA].Number;
-
-	if (pAd->TxSwQueue[QID_AC_VO].Head != NULL)
-	{
-		*pQueIdx = QID_AC_VO;
-		return (&pAd->TxSwQueue[QID_AC_VO]);
-	}
-	else if (pAd->TxSwQueue[QID_AC_VI].Head != NULL)
-	{
-		*pQueIdx = QID_AC_VI;
-		return (&pAd->TxSwQueue[QID_AC_VI]);
-	}
-	else if (pAd->TxSwQueue[QID_AC_BE].Head != NULL)
-	{
-		*pQueIdx = QID_AC_BE;
-		return (&pAd->TxSwQueue[QID_AC_BE]);
-	}
-	else if (pAd->TxSwQueue[QID_AC_BK].Head != NULL)
-	{
-		*pQueIdx = QID_AC_BK;
-		return (&pAd->TxSwQueue[QID_AC_BK]);
-	}
-	else if (pAd->TxSwQueue[QID_HCCA].Head != NULL)
-	{
-		*pQueIdx = QID_HCCA;
-		return (&pAd->TxSwQueue[QID_HCCA]);
-	}
-
-	// No packet pending in Tx Sw queue
-	*pQueIdx = QID_AC_BK;
-
-	return (NULL);
-}
-
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Suspend MSDU transmission
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPSuspendMsduTransmission(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	DBGPRINT(RT_DEBUG_TRACE,("SCANNING, suspend MSDU transmission ...\n"));
-
-
-	//
-	// Before BSS_SCAN_IN_PROGRESS, we need to keep Current R66 value and
-	// use Lowbound as R66 value on ScanNextChannel(...)
-	//
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &pAd->BbpTuning.R66CurrentValue);
-
-	// set BBP_R66 to 0x30/0x40 when scanning (AsicSwitchChannel will set R66 according to channel when scanning)
-	//RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, (0x26 + GET_LNA_GAIN(pAd)));
-	RTMPSetAGCInitValue(pAd, BW_20);
-
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-	//RTMP_IO_WRITE32(pAd, TX_CNTL_CSR, 0x000f0000);		// abort all TX rings
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Resume MSDU transmission
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID RTMPResumeMsduTransmission(
-	IN	PRTMP_ADAPTER	pAd)
-{
-//    UCHAR			IrqState;
-
-	DBGPRINT(RT_DEBUG_TRACE,("SCAN done, resume MSDU transmission ...\n"));
-
-
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, pAd->BbpTuning.R66CurrentValue);
-
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-// sample, for IRQ LOCK to SEM LOCK
-//    IrqState = pAd->irq_disabled;
-//	if (IrqState)
-//		RTMPDeQueuePacket(pAd, TRUE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-//    else
-	RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-}
-
-
-UINT deaggregate_AMSDU_announce(
-	IN	PRTMP_ADAPTER	pAd,
-	PNDIS_PACKET		pPacket,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize)
-{
-	USHORT 			PayloadSize;
-	USHORT 			SubFrameSize;
-	PHEADER_802_3 	pAMSDUsubheader;
-	UINT			nMSDU;
-    UCHAR			Header802_3[14];
-
-	PUCHAR			pPayload, pDA, pSA, pRemovedLLCSNAP;
-	PNDIS_PACKET	pClonePacket;
-
-
-
-	nMSDU = 0;
-
-	while (DataSize > LENGTH_802_3)
-	{
-
-		nMSDU++;
-
-		//hex_dump("subheader", pData, 64);
-		pAMSDUsubheader = (PHEADER_802_3)pData;
-		//pData += LENGTH_802_3;
-		PayloadSize = pAMSDUsubheader->Octet[1] + (pAMSDUsubheader->Octet[0]<<8);
-		SubFrameSize = PayloadSize + LENGTH_802_3;
-
-
-		if ((DataSize < SubFrameSize) || (PayloadSize > 1518 ))
-		{
-			break;
-		}
-
-		//printk("%d subframe: Size = %d\n",  nMSDU, PayloadSize);
-
-		pPayload = pData + LENGTH_802_3;
-		pDA = pData;
-		pSA = pData + MAC_ADDR_LEN;
-
-		// convert to 802.3 header
-        CONVERT_TO_802_3(Header802_3, pDA, pSA, pPayload, PayloadSize, pRemovedLLCSNAP);
-
-#ifdef CONFIG_STA_SUPPORT
-		if ((Header802_3[12] == 0x88) && (Header802_3[13] == 0x8E) )
-		{
-		    // avoid local heap overflow, use dyanamic allocation
-		   MLME_QUEUE_ELEM *Elem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-		   memmove(Elem->Msg+(LENGTH_802_11 + LENGTH_802_1_H), pPayload, PayloadSize);
-		   Elem->MsgLen = LENGTH_802_11 + LENGTH_802_1_H + PayloadSize;
-		   WpaEAPOLKeyAction(pAd, Elem);
-		   kfree(Elem);
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-	        	if (pRemovedLLCSNAP)
-	        	{
-	    			pPayload -= LENGTH_802_3;
-	    			PayloadSize += LENGTH_802_3;
-	    			NdisMoveMemory(pPayload, &Header802_3[0], LENGTH_802_3);
-	        	}
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		pClonePacket = ClonePacket(pAd, pPacket, pPayload, PayloadSize);
-		if (pClonePacket)
-		{
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pClonePacket, RTMP_GET_PACKET_IF(pPacket));
-#endif // CONFIG_STA_SUPPORT //
-		}
-
-
-		// A-MSDU has padding to multiple of 4 including subframe header.
-		// align SubFrameSize up to multiple of 4
-		SubFrameSize = (SubFrameSize+3)&(~0x3);
-
-
-		if (SubFrameSize > 1528 || SubFrameSize < 32)
-		{
-			break;
-		}
-
-		if (DataSize > SubFrameSize)
-		{
-			pData += SubFrameSize;
-			DataSize -= SubFrameSize;
-		}
-		else
-		{
-			// end of A-MSDU
-			DataSize = 0;
-		}
-	}
-
-	// finally release original rx packet
-	RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-
-	return nMSDU;
-}
-
-
-UINT BA_Reorder_AMSDU_Annnounce(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-	PUCHAR			pData;
-	USHORT			DataSize;
-	UINT			nMSDU = 0;
-
-	pData = (PUCHAR) GET_OS_PKT_DATAPTR(pPacket);
-	DataSize = (USHORT) GET_OS_PKT_LEN(pPacket);
-
-	nMSDU = deaggregate_AMSDU_announce(pAd, pPacket, pData, DataSize);
-
-	return nMSDU;
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Look up the MAC address in the MAC table. Return NULL if not found.
-	Return:
-		pEntry - pointer to the MAC entry; NULL is not found
-	==========================================================================
-*/
-MAC_TABLE_ENTRY *MacTableLookup(
-	IN PRTMP_ADAPTER pAd,
-	PUCHAR pAddr)
-{
-	ULONG HashIdx;
-	MAC_TABLE_ENTRY *pEntry = NULL;
-
-	HashIdx = MAC_ADDR_HASH_INDEX(pAddr);
-	pEntry = pAd->MacTab.Hash[HashIdx];
-
-	while (pEntry && (pEntry->ValidAsCLI || pEntry->ValidAsWDS || pEntry->ValidAsApCli || pEntry->ValidAsMesh))
-	{
-		if (MAC_ADDR_EQUAL(pEntry->Addr, pAddr))
-		{
-			break;
-		}
-		else
-			pEntry = pEntry->pNext;
-	}
-
-	return pEntry;
-}
-
-MAC_TABLE_ENTRY *MacTableInsertEntry(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR			pAddr,
-	IN	UCHAR			apidx,
-	IN BOOLEAN	CleanAll)
-{
-	UCHAR HashIdx;
-	int i, FirstWcid;
-	MAC_TABLE_ENTRY *pEntry = NULL, *pCurrEntry;
-
-	// if FULL, return
-	if (pAd->MacTab.Size >= MAX_LEN_OF_MAC_TABLE)
-		return NULL;
-
-	FirstWcid = 1;
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	if (pAd->StaCfg.BssType == BSS_INFRA)
-		FirstWcid = 2;
-#endif // CONFIG_STA_SUPPORT //
-
-	// allocate one MAC entry
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-	for (i = FirstWcid; i< MAX_LEN_OF_MAC_TABLE; i++)   // skip entry#0 so that "entry index == AID" for fast lookup
-	{
-		// pick up the first available vacancy
-		if ((pAd->MacTab.Content[i].ValidAsCLI == FALSE) &&
-			(pAd->MacTab.Content[i].ValidAsWDS == FALSE) &&
-			(pAd->MacTab.Content[i].ValidAsApCli== FALSE) &&
-			(pAd->MacTab.Content[i].ValidAsMesh == FALSE)
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-			&& (pAd->MacTab.Content[i].ValidAsDls == FALSE)
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-			)
-		{
-			pEntry = &pAd->MacTab.Content[i];
-			if (CleanAll == TRUE)
-			{
-				pEntry->MaxSupportedRate = RATE_11;
-				pEntry->CurrTxRate = RATE_11;
-				NdisZeroMemory(pEntry, sizeof(MAC_TABLE_ENTRY));
-				pEntry->PairwiseKey.KeyLen = 0;
-				pEntry->PairwiseKey.CipherAlg = CIPHER_NONE;
-			}
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-			if (apidx >= MIN_NET_DEVICE_FOR_DLS)
-			{
-				pEntry->ValidAsCLI = FALSE;
-				pEntry->ValidAsWDS = FALSE;
-				pEntry->ValidAsApCli = FALSE;
-				pEntry->ValidAsMesh = FALSE;
-				pEntry->ValidAsDls = TRUE;
-				pEntry->isCached = FALSE;
-			}
-			else
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-			{
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-					pEntry->ValidAsCLI = TRUE;
-					pEntry->ValidAsWDS = FALSE;
-					pEntry->ValidAsApCli = FALSE;
-					pEntry->ValidAsMesh = FALSE;
-					pEntry->ValidAsDls = FALSE;
-				}
-#endif // CONFIG_STA_SUPPORT //
-			}
-
-			pEntry->bIAmBadAtheros = FALSE;
-			pEntry->pAd = pAd;
-			pEntry->CMTimerRunning = FALSE;
-			pEntry->EnqueueEapolStartTimerRunning = EAPOL_START_DISABLE;
-			pEntry->RSNIE_Len = 0;
-			NdisZeroMemory(pEntry->R_Counter, sizeof(pEntry->R_Counter));
-			pEntry->ReTryCounter = PEER_MSG1_RETRY_TIMER_CTR;
-
-			if (pEntry->ValidAsMesh)
-				pEntry->apidx = (apidx - MIN_NET_DEVICE_FOR_MESH);
-			else if (pEntry->ValidAsApCli)
-				pEntry->apidx = (apidx - MIN_NET_DEVICE_FOR_APCLI);
-			else if (pEntry->ValidAsWDS)
-				pEntry->apidx = (apidx - MIN_NET_DEVICE_FOR_WDS);
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-			else if (pEntry->ValidAsDls)
-				pEntry->apidx = (apidx - MIN_NET_DEVICE_FOR_DLS);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-			else
-				pEntry->apidx = apidx;
-
-			{
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-					pEntry->AuthMode = pAd->StaCfg.AuthMode;
-					pEntry->WepStatus = pAd->StaCfg.WepStatus;
-					pEntry->PrivacyFilter = Ndis802_11PrivFilterAcceptAll;
-				}
-#endif // CONFIG_STA_SUPPORT //
-			}
-
-			pEntry->GTKState = REKEY_NEGOTIATING;
-			pEntry->PairwiseKey.KeyLen = 0;
-			pEntry->PairwiseKey.CipherAlg = CIPHER_NONE;
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-			if (pEntry->ValidAsDls == TRUE)
-				pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
-#endif //QOS_DLS_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-			pEntry->PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			pEntry->PMKID_CacheIdx = ENTRY_NOT_FOUND;
-			COPY_MAC_ADDR(pEntry->Addr, pAddr);
-			pEntry->Sst = SST_NOT_AUTH;
-			pEntry->AuthState = AS_NOT_AUTH;
-			pEntry->Aid = (USHORT)i;  //0;
-			pEntry->CapabilityInfo = 0;
-			pEntry->PsMode = PWR_ACTIVE;
-			pEntry->PsQIdleCount = 0;
-			pEntry->NoDataIdleCount = 0;
-			pEntry->ContinueTxFailCnt = 0;
-			InitializeQueueHeader(&pEntry->PsQueue);
-
-
-			pAd->MacTab.Size ++;
-			// Add this entry into ASIC RX WCID search table
-			RT28XX_STA_ENTRY_ADD(pAd, pEntry);
-
-			DBGPRINT(RT_DEBUG_TRACE, ("MacTableInsertEntry - allocate entry #%d, Total= %d\n",i, pAd->MacTab.Size));
-			break;
-		}
-	}
-
-	// add this MAC entry into HASH table
-	if (pEntry)
-	{
-		HashIdx = MAC_ADDR_HASH_INDEX(pAddr);
-		if (pAd->MacTab.Hash[HashIdx] == NULL)
-		{
-			pAd->MacTab.Hash[HashIdx] = pEntry;
-		}
-		else
-		{
-			pCurrEntry = pAd->MacTab.Hash[HashIdx];
-			while (pCurrEntry->pNext != NULL)
-				pCurrEntry = pCurrEntry->pNext;
-			pCurrEntry->pNext = pEntry;
-		}
-	}
-
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-	return pEntry;
-}
-
-/*
-	==========================================================================
-	Description:
-		Delete a specified client from MAC table
-	==========================================================================
- */
-BOOLEAN MacTableDeleteEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT wcid,
-	IN PUCHAR pAddr)
-{
-	USHORT HashIdx;
-	MAC_TABLE_ENTRY *pEntry, *pPrevEntry, *pProbeEntry;
-	BOOLEAN Cancelled;
-	//USHORT	offset;	// unused variable
-	//UCHAR	j;			// unused variable
-
-	if (wcid >= MAX_LEN_OF_MAC_TABLE)
-		return FALSE;
-
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-
-	HashIdx = MAC_ADDR_HASH_INDEX(pAddr);
-	//pEntry = pAd->MacTab.Hash[HashIdx];
-	pEntry = &pAd->MacTab.Content[wcid];
-
-	if (pEntry && (pEntry->ValidAsCLI || pEntry->ValidAsApCli || pEntry->ValidAsWDS || pEntry->ValidAsMesh
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
- 		|| pEntry->ValidAsDls
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-		))
-	{
-		if (MAC_ADDR_EQUAL(pEntry->Addr, pAddr))
-		{
-
-			// Delete this entry from ASIC on-chip WCID Table
-			RT28XX_STA_ENTRY_MAC_RESET(pAd, wcid);
-
-#ifdef DOT11_N_SUPPORT
-			// free resources of BA
-			BASessionTearDownALL(pAd, pEntry->Aid);
-#endif // DOT11_N_SUPPORT //
-
-
-			pPrevEntry = NULL;
-			pProbeEntry = pAd->MacTab.Hash[HashIdx];
-			ASSERT(pProbeEntry);
-
-			// update Hash list
-			do
-			{
-				if (pProbeEntry == pEntry)
-				{
-					if (pPrevEntry == NULL)
-					{
-						pAd->MacTab.Hash[HashIdx] = pEntry->pNext;
-					}
-					else
-					{
-						pPrevEntry->pNext = pEntry->pNext;
-					}
-					break;
-				}
-
-				pPrevEntry = pProbeEntry;
-				pProbeEntry = pProbeEntry->pNext;
-			} while (pProbeEntry);
-
-			// not found !!!
-			ASSERT(pProbeEntry != NULL);
-
-			RT28XX_STA_ENTRY_KEY_DEL(pAd, BSS0, wcid);
-
-
-		if (pEntry->EnqueueEapolStartTimerRunning != EAPOL_START_DISABLE)
-		{
-			RTMPCancelTimer(&pEntry->EnqueueStartForPSKTimer, &Cancelled);
-			pEntry->EnqueueEapolStartTimerRunning = EAPOL_START_DISABLE;
-		}
-
-
-   			NdisZeroMemory(pEntry, sizeof(MAC_TABLE_ENTRY));
-			pAd->MacTab.Size --;
-			DBGPRINT(RT_DEBUG_TRACE, ("MacTableDeleteEntry1 - Total= %d\n", pAd->MacTab.Size));
-		}
-		else
-		{
-			printk("\n%s: Impossible Wcid = %d !!!!!\n", __func__, wcid);
-		}
-	}
-
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-
-	//Reset operating mode when no Sta.
-	if (pAd->MacTab.Size == 0)
-	{
-#ifdef DOT11_N_SUPPORT
-		pAd->CommonCfg.AddHTInfo.AddHtInfo2.OperaionMode = 0;
-#endif // DOT11_N_SUPPORT //
-		AsicUpdateProtect(pAd, 0 /*pAd->CommonCfg.AddHTInfo.AddHtInfo2.OperaionMode*/, (ALLN_SETPROTECT), TRUE, 0 /*pAd->MacTab.fAnyStationNonGF*/);
-	}
-
-	return TRUE;
-}
-
-
-/*
-	==========================================================================
-	Description:
-		This routine reset the entire MAC table. All packets pending in
-		the power-saving queues are freed here.
-	==========================================================================
- */
-VOID MacTableReset(
-	IN  PRTMP_ADAPTER  pAd)
-{
-	int         i;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("MacTableReset\n"));
-	//NdisAcquireSpinLock(&pAd->MacTabLock);
-
-	for (i=1; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		if (pAd->MacTab.Content[i].ValidAsCLI == TRUE)
-	   {
-
-#ifdef DOT11_N_SUPPORT
-			// free resources of BA
-			BASessionTearDownALL(pAd, i);
-#endif // DOT11_N_SUPPORT //
-
-			pAd->MacTab.Content[i].ValidAsCLI = FALSE;
-
-
-
-#ifdef RT2870
-			NdisZeroMemory(pAd->MacTab.Content[i].Addr, 6);
-			RT28XX_STA_ENTRY_MAC_RESET(pAd, i);
-#endif // RT2870 //
-
-			//AsicDelWcidTab(pAd, i);
-		}
-	}
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID AssocParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_ASSOC_REQ_STRUCT *AssocReq,
-	IN PUCHAR                     pAddr,
-	IN USHORT                     CapabilityInfo,
-	IN ULONG                      Timeout,
-	IN USHORT                     ListenIntv)
-{
-	COPY_MAC_ADDR(AssocReq->Addr, pAddr);
-	// Add mask to support 802.11b mode only
-	AssocReq->CapabilityInfo = CapabilityInfo & SUPPORTED_CAPABILITY_INFO; // not cf-pollable, not cf-poll-request
-	AssocReq->Timeout = Timeout;
-	AssocReq->ListenIntv = ListenIntv;
-}
-
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID DisassocParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_DISASSOC_REQ_STRUCT *DisassocReq,
-	IN PUCHAR pAddr,
-	IN USHORT Reason)
-{
-	COPY_MAC_ADDR(DisassocReq->Addr, pAddr);
-	DisassocReq->Reason = Reason;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Check the out going frame, if this is an DHCP or ARP datagram
-	will be duplicate another frame at low data rate transmit.
-
-	Arguments:
-		pAd 		Pointer to our adapter
-		pPacket 	Pointer to outgoing Ndis frame
-
-	Return Value:
-		TRUE		To be duplicate at Low data rate transmit. (1mb)
-		FALSE		Do nothing.
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-		MAC header + IP Header + UDP Header
-		  14 Bytes	  20 Bytes
-
-		UDP Header
-		00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|
-						Source Port
-		16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|
-					Destination Port
-
-		port 0x43 means Bootstrap Protocol, server.
-		Port 0x44 means Bootstrap Protocol, client.
-
-	========================================================================
-*/
-
-BOOLEAN RTMPCheckDHCPFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-	PACKET_INFO 	PacketInfo;
-	ULONG			NumberOfBytesRead = 0;
-	ULONG			CurrentOffset = 0;
-	PVOID			pVirtualAddress = NULL;
-	UINT			NdisBufferLength;
-	PUCHAR			pSrc;
-	USHORT			Protocol;
-	UCHAR			ByteOffset36 = 0;
-	UCHAR			ByteOffset38 = 0;
-	BOOLEAN 		ReadFirstParm = TRUE;
-
-	RTMP_QueryPacketInfo(pPacket, &PacketInfo, (PUCHAR *)&pVirtualAddress, &NdisBufferLength);
-
-	NumberOfBytesRead += NdisBufferLength;
-	pSrc = (PUCHAR) pVirtualAddress;
-	Protocol = *(pSrc + 12) * 256 + *(pSrc + 13);
-
-	//
-	// Check DHCP & BOOTP protocol
-	//
-	while (NumberOfBytesRead <= PacketInfo.TotalPacketLength)
-	{
-		if ((NumberOfBytesRead >= 35) && (ReadFirstParm == TRUE))
-		{
-			CurrentOffset = 35 - (NumberOfBytesRead - NdisBufferLength);
-			ByteOffset36 = *(pSrc + CurrentOffset);
-			ReadFirstParm = FALSE;
-		}
-
-		if (NumberOfBytesRead >= 37)
-		{
-			CurrentOffset = 37 - (NumberOfBytesRead - NdisBufferLength);
-			ByteOffset38 = *(pSrc + CurrentOffset);
-			//End of Read
-			break;
-		}
-		return FALSE;
-	}
-
-	// Check for DHCP & BOOTP protocol
-	if ((ByteOffset36 != 0x44) || (ByteOffset38 != 0x43))
-		{
-		//
-		// 2054 (hex 0806) for ARP datagrams
-		// if this packet is not ARP datagrams, then do nothing
-		// ARP datagrams will also be duplicate at 1mb broadcast frames
-		//
-		if (Protocol != 0x0806 )
-			return FALSE;
-		}
-
-	return TRUE;
-}
-
-
-BOOLEAN RTMPCheckEtherType(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-	USHORT	TypeLen;
-	UCHAR	Byte0, Byte1;
-	PUCHAR	pSrcBuf;
-	UINT32	pktLen;
-	UINT16 	srcPort, dstPort;
-	BOOLEAN	status = TRUE;
-
-
-	pSrcBuf = GET_OS_PKT_DATAPTR(pPacket);
-	pktLen = GET_OS_PKT_LEN(pPacket);
-
-	ASSERT(pSrcBuf);
-
-	RTMP_SET_PACKET_SPECIFIC(pPacket, 0);
-
-	// get Ethernet protocol field
-	TypeLen = (pSrcBuf[12] << 8) + pSrcBuf[13];
-
-	pSrcBuf += LENGTH_802_3;	// Skip the Ethernet Header.
-
-	if (TypeLen <= 1500)
-	{	// 802.3, 802.3 LLC
-		/*
-			DestMAC(6) + SrcMAC(6) + Lenght(2) +
-			DSAP(1) + SSAP(1) + Control(1) +
-			if the DSAP = 0xAA, SSAP=0xAA, Contorl = 0x03, it has a 5-bytes SNAP header.
-				=> + SNAP (5, OriginationID(3) + etherType(2))
-		*/
-		if (pSrcBuf[0] == 0xAA && pSrcBuf[1] == 0xAA && pSrcBuf[2] == 0x03)
-		{
-			Sniff2BytesFromNdisBuffer(pSrcBuf, 6, &Byte0, &Byte1);
-			RTMP_SET_PACKET_LLCSNAP(pPacket, 1);
-			TypeLen = (USHORT)((Byte0 << 8) + Byte1);
-			pSrcBuf += 8; // Skip this LLC/SNAP header
-		}
-		else
-		{
-			//It just has 3-byte LLC header, maybe a legacy ether type frame. we didn't handle it.
-		}
-	}
-
-	// If it's a VLAN packet, get the real Type/Length field.
-	if (TypeLen == 0x8100)
-	{
-		/* 0x8100 means VLAN packets */
-
-		/* Dest. MAC Address (6-bytes) +
-		   Source MAC Address (6-bytes) +
-		   Length/Type = 802.1Q Tag Type (2-byte) +
-		   Tag Control Information (2-bytes) +
-		   Length / Type (2-bytes) +
-		   data payload (0-n bytes) +
-		   Pad (0-p bytes) +
-		   Frame Check Sequence (4-bytes) */
-
-		RTMP_SET_PACKET_VLAN(pPacket, 1);
-		Sniff2BytesFromNdisBuffer(pSrcBuf, 2, &Byte0, &Byte1);
-		TypeLen = (USHORT)((Byte0 << 8) + Byte1);
-
-		pSrcBuf += 4; // Skip the VLAN Header.
-	}
-
-	switch (TypeLen)
-	{
-		case 0x0800:
-			{
-				ASSERT((pktLen > 34));
-				if (*(pSrcBuf + 9) == 0x11)
-				{	// udp packet
-					ASSERT((pktLen > 34));	// 14 for ethernet header, 20 for IP header
-
-					pSrcBuf += 20;	// Skip the IP header
-					srcPort = OS_NTOHS(*((UINT16 *)pSrcBuf));
-					dstPort = OS_NTOHS(*((UINT16 *)(pSrcBuf +2)));
-
-					if ((srcPort==0x44 && dstPort==0x43) || (srcPort==0x43 && dstPort==0x44))
-					{	//It's a BOOTP/DHCP packet
-						RTMP_SET_PACKET_DHCP(pPacket, 1);
-					}
-				}
-			}
-			break;
-		case 0x0806:
-			{
-				//ARP Packet.
-				RTMP_SET_PACKET_DHCP(pPacket, 1);
-			}
-			break;
-		case 0x888e:
-			{
-				// EAPOL Packet.
-				RTMP_SET_PACKET_EAPOL(pPacket, 1);
-			}
-			break;
-		default:
-			status = FALSE;
-			break;
-	}
-
-	return status;
-
-}
-
-
-
-VOID Update_Rssi_Sample(
-	IN PRTMP_ADAPTER	pAd,
-	IN RSSI_SAMPLE		*pRssi,
-	IN PRXWI_STRUC		pRxWI)
-		{
-	CHAR	rssi0 = pRxWI->RSSI0;
-	CHAR	rssi1 = pRxWI->RSSI1;
-	CHAR	rssi2 = pRxWI->RSSI2;
-
-	if (rssi0 != 0)
-	{
-		pRssi->LastRssi0	= ConvertToRssi(pAd, (CHAR)rssi0, RSSI_0);
-		pRssi->AvgRssi0X8	= (pRssi->AvgRssi0X8 - pRssi->AvgRssi0) + pRssi->LastRssi0;
-		pRssi->AvgRssi0	= pRssi->AvgRssi0X8 >> 3;
-	}
-
-	if (rssi1 != 0)
-	{
-		pRssi->LastRssi1	= ConvertToRssi(pAd, (CHAR)rssi1, RSSI_1);
-		pRssi->AvgRssi1X8	= (pRssi->AvgRssi1X8 - pRssi->AvgRssi1) + pRssi->LastRssi1;
-		pRssi->AvgRssi1	= pRssi->AvgRssi1X8 >> 3;
-	}
-
-	if (rssi2 != 0)
-	{
-		pRssi->LastRssi2	= ConvertToRssi(pAd, (CHAR)rssi2, RSSI_2);
-		pRssi->AvgRssi2X8  = (pRssi->AvgRssi2X8 - pRssi->AvgRssi2) + pRssi->LastRssi2;
-		pRssi->AvgRssi2 = pRssi->AvgRssi2X8 >> 3;
-	}
-}
-
-
-
-// Normal legacy Rx packet indication
-VOID Indicate_Legacy_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	PNDIS_PACKET	pRxPacket = pRxBlk->pRxPacket;
-	UCHAR			Header802_3[LENGTH_802_3];
-
-	// 1. get 802.3 Header
-	// 2. remove LLC
-	// 		a. pointer pRxBlk->pData to payload
-	//      b. modify pRxBlk->DataSize
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
-#endif // CONFIG_STA_SUPPORT //
-
-	if (pRxBlk->DataSize > MAX_RX_PKT_LEN)
-	{
-#if 0 // sample take off, for multiple card design
-		static int err_size;
-
-		err_size++;
-		if (err_size > 20)
-		{
-			 printk("Legacy DataSize = %d\n", pRxBlk->DataSize);
-			 hex_dump("802.3 Header", Header802_3, LENGTH_802_3);
-			 hex_dump("Payload", pRxBlk->pData, 64);
-			 err_size = 0;
-		}
-#endif
-
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-
-	STATS_INC_RX_PACKETS(pAd, FromWhichBSSID);
-
-#ifdef RT2870
-#ifdef DOT11_N_SUPPORT
-	if (pAd->CommonCfg.bDisableReordering == 0)
-	{
-		PBA_REC_ENTRY		pBAEntry;
-		ULONG				Now32;
-		UCHAR				Wcid = pRxBlk->pRxWI->WirelessCliID;
-		UCHAR				TID = pRxBlk->pRxWI->TID;
-		USHORT				Idx;
-
-#define REORDERING_PACKET_TIMEOUT		((100 * HZ)/1000)	// system ticks -- 100 ms
-
-		if (Wcid < MAX_LEN_OF_MAC_TABLE)
-		{
-			Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID];
-			if (Idx != 0)
-			{
-				pBAEntry = &pAd->BATable.BARecEntry[Idx];
-				// update last rx time
-				NdisGetSystemUpTime(&Now32);
-				if ((pBAEntry->list.qlen > 0) &&
-					 RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(REORDERING_PACKET_TIMEOUT)))
-	   				)
-				{
-					printk("Indicate_Legacy_Packet():flush reordering_timeout_mpdus! RxWI->Flags=%d, pRxWI.TID=%d, RxD->AMPDU=%d!\n", pRxBlk->Flags, pRxBlk->pRxWI->TID, pRxBlk->RxD.AMPDU);
-					hex_dump("Dump the legacy Packet:", GET_OS_PKT_DATAPTR(pRxBlk->pRxPacket), 64);
-					ba_flush_reordering_timeout_mpdus(pAd, pBAEntry, Now32);
-				}
-			}
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-#endif // RT2870 //
-
-	wlan_802_11_to_802_3_packet(pAd, pRxBlk, Header802_3, FromWhichBSSID);
-
-	//
-	// pass this 802.3 packet to upper layer or forward this packet to WM directly
-	//
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pRxPacket, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
-
-}
-
-
-// Normal, AMPDU or AMSDU
-VOID CmmRxnonRalinkFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-#ifdef DOT11_N_SUPPORT
-	if (RX_BLK_TEST_FLAG(pRxBlk, fRX_AMPDU) && (pAd->CommonCfg.bDisableReordering == 0))
-	{
-		Indicate_AMPDU_Packet(pAd, pRxBlk, FromWhichBSSID);
-	}
-	else
-#endif // DOT11_N_SUPPORT //
-	{
-#ifdef DOT11_N_SUPPORT
-		if (RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU))
-		{
-			// handle A-MSDU
-			Indicate_AMSDU_Packet(pAd, pRxBlk, FromWhichBSSID);
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			Indicate_Legacy_Packet(pAd, pRxBlk, FromWhichBSSID);
-		}
-	}
-}
-
-
-VOID CmmRxRalinkFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	UCHAR			Header802_3[LENGTH_802_3];
-	UINT16			Msdu2Size;
-	UINT16 			Payload1Size, Payload2Size;
-	PUCHAR 			pData2;
-	PNDIS_PACKET	pPacket2 = NULL;
-
-
-
-	Msdu2Size = *(pRxBlk->pData) + (*(pRxBlk->pData+1) << 8);
-
-	if ((Msdu2Size <= 1536) && (Msdu2Size < pRxBlk->DataSize))
-	{
-		/* skip two byte MSDU2 len */
-		pRxBlk->pData += 2;
-		pRxBlk->DataSize -= 2;
-	}
-	else
-	{
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-	// get 802.3 Header and  remove LLC
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
-#endif // CONFIG_STA_SUPPORT //
-
-
-	ASSERT(pRxBlk->pRxPacket);
-
-	// Ralink Aggregation frame
-	pAd->RalinkCounters.OneSecRxAggregationCount ++;
-	Payload1Size = pRxBlk->DataSize - Msdu2Size;
-	Payload2Size = Msdu2Size - LENGTH_802_3;
-
-	pData2 = pRxBlk->pData + Payload1Size + LENGTH_802_3;
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		pPacket2 = duplicate_pkt(pAd, (pData2-LENGTH_802_3), LENGTH_802_3, pData2, Payload2Size, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
-
-	if (!pPacket2)
-	{
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-	// update payload size of 1st packet
-	pRxBlk->DataSize = Payload1Size;
-	wlan_802_11_to_802_3_packet(pAd, pRxBlk, Header802_3, FromWhichBSSID);
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pRxBlk->pRxPacket, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
-
-	if (pPacket2)
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pPacket2, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
-	}
-}
-
-
-#define RESET_FRAGFRAME(_fragFrame) \
-	{								\
-		_fragFrame.RxSize = 0;		\
-		_fragFrame.Sequence = 0;	\
-		_fragFrame.LastFrag = 0;	\
-		_fragFrame.Flags = 0;		\
-	}
-
-
-PNDIS_PACKET RTMPDeFragmentDataFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk)
-{
-	PHEADER_802_11	pHeader = pRxBlk->pHeader;
-	PNDIS_PACKET	pRxPacket = pRxBlk->pRxPacket;
-	UCHAR			*pData = pRxBlk->pData;
-	USHORT			DataSize = pRxBlk->DataSize;
-	PNDIS_PACKET	pRetPacket = NULL;
-	UCHAR			*pFragBuffer = NULL;
-	BOOLEAN 		bReassDone = FALSE;
-	UCHAR			HeaderRoom = 0;
-
-
-	ASSERT(pHeader);
-
-	HeaderRoom = pData - (UCHAR *)pHeader;
-
-	// Re-assemble the fragmented packets
-	if (pHeader->Frag == 0)		// Frag. Number is 0 : First frag or only one pkt
-	{
-		// the first pkt of fragment, record it.
-		if (pHeader->FC.MoreFrag)
-		{
-			ASSERT(pAd->FragFrame.pFragPacket);
-			pFragBuffer = GET_OS_PKT_DATAPTR(pAd->FragFrame.pFragPacket);
-			pAd->FragFrame.RxSize   = DataSize + HeaderRoom;
-			NdisMoveMemory(pFragBuffer,	 pHeader, pAd->FragFrame.RxSize);
-			pAd->FragFrame.Sequence = pHeader->Sequence;
-			pAd->FragFrame.LastFrag = pHeader->Frag;	   // Should be 0
-			ASSERT(pAd->FragFrame.LastFrag == 0);
-			goto done;	// end of processing this frame
-		}
-	}
-	else	//Middle & End of fragment
-	{
-		if ((pHeader->Sequence != pAd->FragFrame.Sequence) ||
-			(pHeader->Frag != (pAd->FragFrame.LastFrag + 1)))
-		{
-			// Fragment is not the same sequence or out of fragment number order
-			// Reset Fragment control blk
-			RESET_FRAGFRAME(pAd->FragFrame);
-			DBGPRINT(RT_DEBUG_ERROR, ("Fragment is not the same sequence or out of fragment number order.\n"));
-			goto done; // give up this frame
-		}
-		else if ((pAd->FragFrame.RxSize + DataSize) > MAX_FRAME_SIZE)
-		{
-			// Fragment frame is too large, it exeeds the maximum frame size.
-			// Reset Fragment control blk
-			RESET_FRAGFRAME(pAd->FragFrame);
-			DBGPRINT(RT_DEBUG_ERROR, ("Fragment frame is too large, it exeeds the maximum frame size.\n"));
-			goto done; // give up this frame
-		}
-
-        //
-		// Broadcom AP(BCM94704AGR) will send out LLC in fragment's packet, LLC only can accpet at first fragment.
-		// In this case, we will dropt it.
-		//
-		if (NdisEqualMemory(pData, SNAP_802_1H, sizeof(SNAP_802_1H)))
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("Find another LLC at Middle or End fragment(SN=%d, Frag=%d)\n", pHeader->Sequence, pHeader->Frag));
-			goto done; // give up this frame
-		}
-
-		pFragBuffer = GET_OS_PKT_DATAPTR(pAd->FragFrame.pFragPacket);
-
-		// concatenate this fragment into the re-assembly buffer
-		NdisMoveMemory((pFragBuffer + pAd->FragFrame.RxSize), pData, DataSize);
-		pAd->FragFrame.RxSize  += DataSize;
-		pAd->FragFrame.LastFrag = pHeader->Frag;	   // Update fragment number
-
-		// Last fragment
-		if (pHeader->FC.MoreFrag == FALSE)
-		{
-			bReassDone = TRUE;
-		}
-	}
-
-done:
-	// always release rx fragmented packet
-	RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-
-	// return defragmented packet if packet is reassembled completely
-	// otherwise return NULL
-	if (bReassDone)
-	{
-		PNDIS_PACKET pNewFragPacket;
-
-		// allocate a new packet buffer for fragment
-		pNewFragPacket = RTMP_AllocateFragPacketBuffer(pAd, RX_BUFFER_NORMSIZE);
-		if (pNewFragPacket)
-		{
-			// update RxBlk
-			pRetPacket = pAd->FragFrame.pFragPacket;
-			pAd->FragFrame.pFragPacket = pNewFragPacket;
-			pRxBlk->pHeader = (PHEADER_802_11) GET_OS_PKT_DATAPTR(pRetPacket);
-			pRxBlk->pData = (UCHAR *)pRxBlk->pHeader + HeaderRoom;
-			pRxBlk->DataSize = pAd->FragFrame.RxSize - HeaderRoom;
-			pRxBlk->pRxPacket = pRetPacket;
-		}
-		else
-		{
-			RESET_FRAGFRAME(pAd->FragFrame);
-		}
-	}
-
-	return pRetPacket;
-}
-
-
-VOID Indicate_AMSDU_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	UINT			nMSDU;
-
-	update_os_packet_info(pAd, pRxBlk, FromWhichBSSID);
-	RTMP_SET_PACKET_IF(pRxBlk->pRxPacket, FromWhichBSSID);
-	nMSDU = deaggregate_AMSDU_announce(pAd, pRxBlk->pRxPacket, pRxBlk->pData, pRxBlk->DataSize);
-}
-
-VOID Indicate_EAPOL_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	MAC_TABLE_ENTRY *pEntry = NULL;
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		pEntry = &pAd->MacTab.Content[BSSID_WCID];
-		STARxEAPOLFrameIndicate(pAd, pEntry, pRxBlk, FromWhichBSSID);
-		return;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	if (pEntry == NULL)
-	{
-		DBGPRINT(RT_DEBUG_WARN, ("Indicate_EAPOL_Packet: drop and release the invalid packet.\n"));
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-}
-
-#define BCN_TBTT_OFFSET		64	//defer 64 us
-VOID ReSyncBeaconTime(
-	IN  PRTMP_ADAPTER   pAd)
-{
-
-	UINT32  Offset;
-
-
-	Offset = (pAd->TbttTickCount) % (BCN_TBTT_OFFSET);
-
-	pAd->TbttTickCount++;
-
-	//
-	// The updated BeaconInterval Value will affect Beacon Interval after two TBTT
-	// beacasue the original BeaconInterval had been loaded into next TBTT_TIMER
-	//
-	if (Offset == (BCN_TBTT_OFFSET-2))
-	{
-		BCN_TIME_CFG_STRUC csr;
-		RTMP_IO_READ32(pAd, BCN_TIME_CFG, &csr.word);
-		csr.field.BeaconInterval = (pAd->CommonCfg.BeaconPeriod << 4) - 1 ;	// ASIC register in units of 1/16 TU = 64us
-		RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr.word);
-	}
-	else
-	{
-		if (Offset == (BCN_TBTT_OFFSET-1))
-		{
-			BCN_TIME_CFG_STRUC csr;
-
-			RTMP_IO_READ32(pAd, BCN_TIME_CFG, &csr.word);
-			csr.field.BeaconInterval = (pAd->CommonCfg.BeaconPeriod) << 4; // ASIC register in units of 1/16 TU
-			RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr.word);
-		}
-	}
-}
-
+#include "../../rt2860/common/cmm_data.c"
diff --git a/drivers/staging/rt2870/common/cmm_data_2870.c b/drivers/staging/rt2870/common/cmm_data_2870.c
index f77000f..d6fc056 100644
--- a/drivers/staging/rt2870/common/cmm_data_2870.c
+++ b/drivers/staging/rt2870/common/cmm_data_2870.c
@@ -189,9 +189,6 @@
 	}
 
 	NdisMoveMemory(pWirelessPacket, pTxBlk->HeaderBuf, TXINFO_SIZE + TXWI_SIZE + hwHdrLen);
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)(pWirelessPacket + TXINFO_SIZE + TXWI_SIZE), DIR_WRITE, FALSE);
-#endif // RT_BIG_ENDIAN //
 	pWirelessPacket += (TXINFO_SIZE + TXWI_SIZE + hwHdrLen);
 	pHTTXContext->CurWriteRealPos += (TXINFO_SIZE + TXWI_SIZE + hwHdrLen);
 
@@ -295,6 +292,7 @@
 		pTxBlk->Priv = (TXINFO_SIZE + USBDMApktLen);
 
 		// For TxInfo, the length of USBDMApktLen = TXWI_SIZE + 802.11 header + payload
+		//PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
 		RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(USBDMApktLen), FALSE, FIFO_EDCA, FALSE /*NextValid*/,  FALSE);
 
 		if ((pHTTXContext->CurWritePosition + 3906 + pTxBlk->Priv) > MAX_TXBULK_LIMIT)
@@ -303,9 +301,6 @@
 			bTxQLastRound = TRUE;
 		}
 		NdisMoveMemory(pWirelessPacket, pTxBlk->HeaderBuf, TXINFO_SIZE + TXWI_SIZE + hwHdrLen);
-#ifdef RT_BIG_ENDIAN
-		RTMPFrameEndianChange(pAd, (PUCHAR)(pWirelessPacket + TXINFO_SIZE + TXWI_SIZE), DIR_WRITE, FALSE);
-#endif // RT_BIG_ENDIAN //
 		pWirelessPacket += (TXINFO_SIZE + TXWI_SIZE + hwHdrLen);
 
 		// We unlock it here to prevent the first 8 bytes maybe over-writed issue.
@@ -417,9 +412,6 @@
 
 			// Copy it.
 			NdisMoveMemory(pWirelessPacket, pTxBlk->HeaderBuf, pTxBlk->Priv);
-#ifdef RT_BIG_ENDIAN
-			RTMPFrameEndianChange(pAd, (PUCHAR)(pWirelessPacket+ TXINFO_SIZE + TXWI_SIZE), DIR_WRITE, FALSE);
-#endif // RT_BIG_ENDIAN //
 			pHTTXContext->CurWriteRealPos += pTxBlk->Priv;
 			pWirelessPacket += pTxBlk->Priv;
 		}
@@ -687,14 +679,7 @@
 		pTxWI = (PTXWI_STRUC)&pWirelessPkt[TXINFO_SIZE];
 		RTMPWriteTxWI(pAd, pTxWI,  FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, 0, BSSID_WCID, (sizeof(HEADER_802_11)),
 			0, 0, (UCHAR)pAd->CommonCfg.MlmeTransmit.field.MCS, IFS_HTTXOP, FALSE, &pAd->CommonCfg.MlmeTransmit);
-#ifdef RT_BIG_ENDIAN
-		RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-#endif // RT_BIG_ENDIAN //
-
 		RTMPMoveMemory(&pWirelessPkt[TXWI_SIZE+TXINFO_SIZE], &pAd->NullFrame, sizeof(HEADER_802_11));
-#ifdef RT_BIG_ENDIAN
-		RTMPFrameEndianChange(pAd, (PUCHAR)&pWirelessPkt[TXINFO_SIZE + TXWI_SIZE], DIR_WRITE, FALSE);
-#endif // RT_BIG_ENDIAN //
 		pAd->NullContext.BulkOutSize =  TXINFO_SIZE + TXWI_SIZE + sizeof(pAd->NullFrame) + 4;
 
 		// Fill out frame length information for global Bulk out arbitor
@@ -708,7 +693,6 @@
 
 }
 
-#ifdef CONFIG_STA_SUPPORT
 /*
 	========================================================================
 
@@ -826,7 +810,12 @@
 	AutoWakeupCfg.word = 0;
 	RTMP_IO_WRITE32(pAd, AUTO_WAKEUP_CFG, AutoWakeupCfg.word);
 
+#ifndef RT30xx
 	AsicSendCommandToMcu(pAd, 0x31, 0xff, 0x00, 0x00);
+#endif
+#ifdef RT30xx
+	AsicSendCommandToMcu(pAd, 0x31, 0xff, 0x00, 0x02);
+#endif
 
 	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_DOZE);
 }
@@ -854,7 +843,6 @@
 	OPSTATUS_SET_FLAG(pAd, fOP_STATUS_DOZE);
 
 }
-#endif // CONFIG_STA_SUPPORT //
 
 VOID RT28xxUsbMlmeRadioOn(
 	IN PRTMP_ADAPTER pAd)
@@ -864,25 +852,30 @@
 	if (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))
 		return;
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
+#ifndef RT30xx
     	AsicSendCommandToMcu(pAd, 0x31, 0xff, 0x00, 0x00);
+#endif
+#ifdef RT30xx
+    	AsicSendCommandToMcu(pAd, 0x31, 0xff, 0x00, 0x02);
+#endif
 		RTMPusecDelay(10000);
-	}
-#endif // CONFIG_STA_SUPPORT //
+
 	NICResetFromError(pAd);
 
 	// Enable Tx/Rx
 	RTMPEnableRxTx(pAd);
 
+#ifdef RT3070
+	if (IS_RT3071(pAd))
+	{
+		RT30xxReverseRFSleepModeSetup(pAd);
+	}
+#endif // RT3070 //
+
 	// Clear Radio off flag
 	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTUSBBulkReceive(pAd);
-#endif // CONFIG_STA_SUPPORT //
+	RTUSBBulkReceive(pAd);
 
 	// Set LED
 	RTMPSetLED(pAd, LED_RADIO_ON);
@@ -904,8 +897,6 @@
 	// Set Radio off flag
 	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 	{
 		// Link down first if any association exists
 		if (INFRA_ON(pAd) || ADHOC_ON(pAd))
@@ -916,9 +907,8 @@
 		// Clean up old bss table
 		BssTableInit(&pAd->ScanTab);
 	}
-#endif // CONFIG_STA_SUPPORT //
 
-
+#ifndef RT30xx
 	// Disable MAC Tx/Rx
 	RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
 	Value &= (0xfffffff3);
@@ -932,6 +922,7 @@
 
 	// TX_PIN_CFG => value = 0x0 => 20mA
 	RTMP_IO_WRITE32(pAd, TX_PIN_CFG, 0);
+#endif
 
 	if (pAd->CommonCfg.BBPCurrentBW == BW_40)
 	{
@@ -944,6 +935,14 @@
 		AsicTurnOffRFClk(pAd, pAd->CommonCfg.Channel);
 	}
 
+#ifdef RT30xx
+	// Disable Tx/Rx DMA
+	RTUSBReadMACRegister(pAd, WPDMA_GLO_CFG, &GloCfg.word);	   // disable DMA
+	GloCfg.field.EnableTxDMA = 0;
+	GloCfg.field.EnableRxDMA = 0;
+	RTUSBWriteMACRegister(pAd, WPDMA_GLO_CFG, GloCfg.word);	   // abort all TX rings
+#endif
+
 	// Waiting for DMA idle
 	i = 0;
 	do
@@ -955,9 +954,13 @@
 		RTMPusecDelay(1000);
 	}while (i++ < 100);
 
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		AsicSendCommandToMcu(pAd, 0x30, 0xff, 0xff, 0x02);
-#endif // CONFIG_STA_SUPPORT //
+#ifdef RT30xx
+	// Disable MAC Tx/Rx
+	RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
+	Value &= (0xfffffff3);
+	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
+#endif
+
+	AsicSendCommandToMcu(pAd, 0x30, 0xff, 0xff, 0x02);
 }
 
diff --git a/drivers/staging/rt2870/common/cmm_info.c b/drivers/staging/rt2870/common/cmm_info.c
index 47a1b1a..226187e 100644
--- a/drivers/staging/rt2870/common/cmm_info.c
+++ b/drivers/staging/rt2870/common/cmm_info.c
@@ -1,3712 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-*/
-
-#include "../rt_config.h"
-
-INT	Show_SSID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_WirelessMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_TxBurst_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_TxPreamble_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_TxPower_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_Channel_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_BGProtection_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_RTSThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_FragThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-#ifdef DOT11_N_SUPPORT
-INT	Show_HtBw_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtMcs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtGi_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtOpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtExtcha_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtMpduDensity_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtBaWinSize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtRdg_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtAmsdu_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtAutoBa_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-#endif // DOT11_N_SUPPORT //
-
-INT	Show_CountryRegion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_CountryRegionABand_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_CountryCode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-#ifdef AGGREGATION_SUPPORT
-INT	Show_PktAggregate_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-#endif // AGGREGATION_SUPPORT //
-
-#ifdef WMM_SUPPORT
-INT	Show_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-#endif // WMM_SUPPORT //
-
-INT	Show_IEEE80211H_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-#ifdef CONFIG_STA_SUPPORT
-INT	Show_NetworkType_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-#endif // CONFIG_STA_SUPPORT //
-
-INT	Show_AuthMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_EncrypType_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_DefaultKeyID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_Key1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_Key2_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_Key3_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_Key4_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_WPAPSK_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-static struct {
-	CHAR *name;
-	INT (*show_proc)(PRTMP_ADAPTER pAdapter, PUCHAR arg);
-} *PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC, RTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC[] = {
-	{"SSID",					Show_SSID_Proc},
-	{"WirelessMode",			Show_WirelessMode_Proc},
-	{"TxBurst",					Show_TxBurst_Proc},
-	{"TxPreamble",				Show_TxPreamble_Proc},
-	{"TxPower",					Show_TxPower_Proc},
-	{"Channel",					Show_Channel_Proc},
-	{"BGProtection",			Show_BGProtection_Proc},
-	{"RTSThreshold",			Show_RTSThreshold_Proc},
-	{"FragThreshold",			Show_FragThreshold_Proc},
-#ifdef DOT11_N_SUPPORT
-	{"HtBw",					Show_HtBw_Proc},
-	{"HtMcs",					Show_HtMcs_Proc},
-	{"HtGi",					Show_HtGi_Proc},
-	{"HtOpMode",				Show_HtOpMode_Proc},
-	{"HtExtcha",				Show_HtExtcha_Proc},
-	{"HtMpduDensity",			Show_HtMpduDensity_Proc},
-	{"HtBaWinSize",		        Show_HtBaWinSize_Proc},
-	{"HtRdg",		        	Show_HtRdg_Proc},
-	{"HtAmsdu",		        	Show_HtAmsdu_Proc},
-	{"HtAutoBa",		        Show_HtAutoBa_Proc},
-#endif // DOT11_N_SUPPORT //
-	{"CountryRegion",			Show_CountryRegion_Proc},
-	{"CountryRegionABand",		Show_CountryRegionABand_Proc},
-	{"CountryCode",				Show_CountryCode_Proc},
-#ifdef AGGREGATION_SUPPORT
-	{"PktAggregate",			Show_PktAggregate_Proc},
-#endif
-
-#ifdef WMM_SUPPORT
-	{"WmmCapable",				Show_WmmCapable_Proc},
-#endif
-	{"IEEE80211H",				Show_IEEE80211H_Proc},
-#ifdef CONFIG_STA_SUPPORT
-    {"NetworkType",				Show_NetworkType_Proc},
-#endif // CONFIG_STA_SUPPORT //
-	{"AuthMode",				Show_AuthMode_Proc},
-	{"EncrypType",				Show_EncrypType_Proc},
-	{"DefaultKeyID",			Show_DefaultKeyID_Proc},
-	{"Key1",					Show_Key1_Proc},
-	{"Key2",					Show_Key2_Proc},
-	{"Key3",					Show_Key3_Proc},
-	{"Key4",					Show_Key4_Proc},
-	{"WPAPSK",					Show_WPAPSK_Proc},
-	{NULL, NULL}
-};
-
-/*
-    ==========================================================================
-    Description:
-        Get Driver version.
-
-    Return:
-    ==========================================================================
-*/
-INT Set_DriverVersion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		DBGPRINT(RT_DEBUG_TRACE, ("Driver version-%s\n", STA_DRIVER_VERSION));
-#endif // CONFIG_STA_SUPPORT //
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Country Region.
-        This command will not work, if the field of CountryRegion in eeprom is programmed.
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_CountryRegion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG region;
-
-	region = simple_strtol(arg, 0, 10);
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-	return -EOPNOTSUPP;
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-	// Country can be set only when EEPROM not programmed
-	if (pAd->CommonCfg.CountryRegion & 0x80)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Set_CountryRegion_Proc::parameter of CountryRegion in eeprom is programmed \n"));
-		return FALSE;
-	}
-
-	if((region >= 0) && (region <= REGION_MAXIMUM_BG_BAND))
-	{
-		pAd->CommonCfg.CountryRegion = (UCHAR) region;
-	}
-	else if (region == REGION_31_BG_BAND)
-	{
-		pAd->CommonCfg.CountryRegion = (UCHAR) region;
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Set_CountryRegion_Proc::parameters out of range\n"));
-		return FALSE;
-	}
-
-	// if set country region, driver needs to be reset
-	BuildChannelList(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_CountryRegion_Proc::(CountryRegion=%d)\n", pAd->CommonCfg.CountryRegion));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Country Region for A band.
-        This command will not work, if the field of CountryRegion in eeprom is programmed.
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_CountryRegionABand_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG region;
-
-	region = simple_strtol(arg, 0, 10);
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-	return -EOPNOTSUPP;
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-	// Country can be set only when EEPROM not programmed
-	if (pAd->CommonCfg.CountryRegionForABand & 0x80)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Set_CountryRegionABand_Proc::parameter of CountryRegion in eeprom is programmed \n"));
-		return FALSE;
-	}
-
-	if((region >= 0) && (region <= REGION_MAXIMUM_A_BAND))
-	{
-		pAd->CommonCfg.CountryRegionForABand = (UCHAR) region;
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Set_CountryRegionABand_Proc::parameters out of range\n"));
-		return FALSE;
-	}
-
-	// if set country region, driver needs to be reset
-	BuildChannelList(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_CountryRegionABand_Proc::(CountryRegion=%d)\n", pAd->CommonCfg.CountryRegionForABand));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Wireless Mode
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_WirelessMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG	WirelessMode;
-	INT		success = TRUE;
-
-	WirelessMode = simple_strtol(arg, 0, 10);
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		INT MaxPhyMode = PHY_11G;
-
-#ifdef DOT11_N_SUPPORT
-		MaxPhyMode = PHY_11N_5G;
-#endif // DOT11_N_SUPPORT //
-
-		if (WirelessMode <= MaxPhyMode)
-		{
-			RTMPSetPhyMode(pAd, WirelessMode);
-#ifdef DOT11_N_SUPPORT
-			if (WirelessMode >= PHY_11ABGN_MIXED)
-			{
-				pAd->CommonCfg.BACapability.field.AutoBA = TRUE;
-				pAd->CommonCfg.REGBACapability.field.AutoBA = TRUE;
-			}
-			else
-			{
-				pAd->CommonCfg.BACapability.field.AutoBA = FALSE;
-				pAd->CommonCfg.REGBACapability.field.AutoBA = FALSE;
-			}
-#endif // DOT11_N_SUPPORT //
-			// Set AdhocMode rates
-			if (pAd->StaCfg.BssType == BSS_ADHOC)
-			{
-				MlmeUpdateTxRates(pAd, FALSE, 0);
-				MakeIbssBeacon(pAd);           // re-build BEACON frame
-				AsicEnableIbssSync(pAd);       // copy to on-chip memory
-			}
-		}
-		else
-		{
-			success = FALSE;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// it is needed to set SSID to take effect
-	if (success == TRUE)
-	{
-#ifdef DOT11_N_SUPPORT
-		SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-		DBGPRINT(RT_DEBUG_TRACE, ("Set_WirelessMode_Proc::(=%ld)\n", WirelessMode));
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Set_WirelessMode_Proc::parameters out of range\n"));
-	}
-
-	return success;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Channel
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_Channel_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
- 	INT		success = TRUE;
-	UCHAR	Channel;
-
-	Channel = (UCHAR) simple_strtol(arg, 0, 10);
-
-	// check if this channel is valid
-	if (ChannelSanity(pAd, Channel) == TRUE)
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			pAd->CommonCfg.Channel = Channel;
-
-			if (MONITOR_ON(pAd))
-			{
-#ifdef DOT11_N_SUPPORT
-				N_ChannelCheck(pAd);
-				if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-					pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40)
-				{
-					N_SetCenCh(pAd);
-					AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-					AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-					DBGPRINT(RT_DEBUG_TRACE, ("BW_40, control_channel(%d), CentralChannel(%d) \n",
-								pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel));
-				}
-				else
-#endif // DOT11_N_SUPPORT //
-				{
-					AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-					AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-					DBGPRINT(RT_DEBUG_TRACE, ("BW_20, Channel(%d)\n", pAd->CommonCfg.Channel));
-				}
-			}
-		}
-#endif // CONFIG_STA_SUPPORT //
-		success = TRUE;
-	}
-	else
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			success = FALSE;
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-
-	if (success == TRUE)
-		DBGPRINT(RT_DEBUG_TRACE, ("Set_Channel_Proc::(Channel=%d)\n", pAd->CommonCfg.Channel));
-
-	return success;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Short Slot Time Enable or Disable
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ShortSlot_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG ShortSlot;
-
-	ShortSlot = simple_strtol(arg, 0, 10);
-
-	if (ShortSlot == 1)
-		pAd->CommonCfg.bUseShortSlotTime = TRUE;
-	else if (ShortSlot == 0)
-		pAd->CommonCfg.bUseShortSlotTime = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_ShortSlot_Proc::(ShortSlot=%d)\n", pAd->CommonCfg.bUseShortSlotTime));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Tx power
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_TxPower_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG TxPower;
-	INT   success = FALSE;
-
-	TxPower = (ULONG) simple_strtol(arg, 0, 10);
-	if (TxPower <= 100)
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			pAd->CommonCfg.TxPowerDefault = TxPower;
-			pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault;
-		}
-#endif // CONFIG_STA_SUPPORT //
-		success = TRUE;
-	}
-	else
-		success = FALSE;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_TxPower_Proc::(TxPowerPercentage=%ld)\n", pAd->CommonCfg.TxPowerPercentage));
-
-	return success;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set 11B/11G Protection
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_BGProtection_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	switch (simple_strtol(arg, 0, 10))
-	{
-		case 0: //AUTO
-			pAd->CommonCfg.UseBGProtection = 0;
-			break;
-		case 1: //Always On
-			pAd->CommonCfg.UseBGProtection = 1;
-			break;
-		case 2: //Always OFF
-			pAd->CommonCfg.UseBGProtection = 2;
-			break;
-		default:  //Invalid argument
-			return FALSE;
-	}
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_BGProtection_Proc::(BGProtection=%ld)\n", pAd->CommonCfg.UseBGProtection));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set TxPreamble
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_TxPreamble_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	RT_802_11_PREAMBLE	Preamble;
-
-	Preamble = simple_strtol(arg, 0, 10);
-
-
-	switch (Preamble)
-	{
-		case Rt802_11PreambleShort:
-			pAd->CommonCfg.TxPreamble = Preamble;
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				MlmeSetTxPreamble(pAd, Rt802_11PreambleShort);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-		case Rt802_11PreambleLong:
-#ifdef CONFIG_STA_SUPPORT
-		case Rt802_11PreambleAuto:
-			// if user wants AUTO, initialize to LONG here, then change according to AP's
-			// capability upon association.
-#endif // CONFIG_STA_SUPPORT //
-			pAd->CommonCfg.TxPreamble = Preamble;
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				MlmeSetTxPreamble(pAd, Rt802_11PreambleLong);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-		default: //Invalid argument
-			return FALSE;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_TxPreamble_Proc::(TxPreamble=%ld)\n", pAd->CommonCfg.TxPreamble));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set RTS Threshold
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_RTSThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	 NDIS_802_11_RTS_THRESHOLD           RtsThresh;
-
-	RtsThresh = simple_strtol(arg, 0, 10);
-
-	if((RtsThresh > 0) && (RtsThresh <= MAX_RTS_THRESHOLD))
-		pAd->CommonCfg.RtsThreshold  = (USHORT)RtsThresh;
-#ifdef CONFIG_STA_SUPPORT
-	else if (RtsThresh == 0)
-		pAd->CommonCfg.RtsThreshold = MAX_RTS_THRESHOLD;
-#endif // CONFIG_STA_SUPPORT //
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_RTSThreshold_Proc::(RTSThreshold=%d)\n", pAd->CommonCfg.RtsThreshold));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Fragment Threshold
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_FragThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	 NDIS_802_11_FRAGMENTATION_THRESHOLD     FragThresh;
-
-	FragThresh = simple_strtol(arg, 0, 10);
-
-	if (FragThresh > MAX_FRAG_THRESHOLD || FragThresh < MIN_FRAG_THRESHOLD)
-	{
-		//Illegal FragThresh so we set it to default
-		pAd->CommonCfg.FragmentThreshold = MAX_FRAG_THRESHOLD;
-	}
-	else if (FragThresh % 2 == 1)
-	{
-		// The length of each fragment shall always be an even number of octets, except for the last fragment
-		// of an MSDU or MMPDU, which may be either an even or an odd number of octets.
-		pAd->CommonCfg.FragmentThreshold = (USHORT)(FragThresh - 1);
-	}
-	else
-	{
-		pAd->CommonCfg.FragmentThreshold = (USHORT)FragThresh;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pAd->CommonCfg.FragmentThreshold == MAX_FRAG_THRESHOLD)
-			pAd->CommonCfg.bUseZeroToDisableFragment = TRUE;
-		else
-			pAd->CommonCfg.bUseZeroToDisableFragment = FALSE;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_FragThreshold_Proc::(FragThreshold=%d)\n", pAd->CommonCfg.FragmentThreshold));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set TxBurst
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_TxBurst_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG TxBurst;
-
-	TxBurst = simple_strtol(arg, 0, 10);
-	if (TxBurst == 1)
-		pAd->CommonCfg.bEnableTxBurst = TRUE;
-	else if (TxBurst == 0)
-		pAd->CommonCfg.bEnableTxBurst = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_TxBurst_Proc::(TxBurst=%d)\n", pAd->CommonCfg.bEnableTxBurst));
-
-	return TRUE;
-}
-
-#ifdef AGGREGATION_SUPPORT
-/*
-    ==========================================================================
-    Description:
-        Set TxBurst
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_PktAggregate_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG aggre;
-
-	aggre = simple_strtol(arg, 0, 10);
-
-	if (aggre == 1)
-		pAd->CommonCfg.bAggregationCapable = TRUE;
-	else if (aggre == 0)
-		pAd->CommonCfg.bAggregationCapable = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_PktAggregate_Proc::(AGGRE=%d)\n", pAd->CommonCfg.bAggregationCapable));
-
-	return TRUE;
-}
-#endif
-
-/*
-    ==========================================================================
-    Description:
-        Set IEEE80211H.
-        This parameter is 1 when needs radar detection, otherwise 0
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_IEEE80211H_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    ULONG ieee80211h;
-
-	ieee80211h = simple_strtol(arg, 0, 10);
-
-	if (ieee80211h == 1)
-		pAd->CommonCfg.bIEEE80211H = TRUE;
-	else if (ieee80211h == 0)
-		pAd->CommonCfg.bIEEE80211H = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_IEEE80211H_Proc::(IEEE80211H=%d)\n", pAd->CommonCfg.bIEEE80211H));
-
-	return TRUE;
-}
-
-
-#ifdef DBG
-/*
-    ==========================================================================
-    Description:
-        For Debug information
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_Debug_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	DBGPRINT(RT_DEBUG_TRACE, ("==> Set_Debug_Proc *******************\n"));
-
-    if(simple_strtol(arg, 0, 10) <= RT_DEBUG_LOUD)
-        RTDebugLevel = simple_strtol(arg, 0, 10);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<== Set_Debug_Proc(RTDebugLevel = %ld)\n", RTDebugLevel));
-
-	return TRUE;
-}
-#endif
-
-INT	Show_DescInfo_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Reset statistics counter
-
-    Arguments:
-        pAdapter            Pointer to our adapter
-        arg
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ResetStatCounter_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	//UCHAR           i;
-	//MAC_TABLE_ENTRY *pEntry;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==>Set_ResetStatCounter_Proc\n"));
-
-	// add the most up-to-date h/w raw counters into software counters
-	NICUpdateRawCounters(pAd);
-
-	NdisZeroMemory(&pAd->WlanCounters, sizeof(COUNTER_802_11));
-	NdisZeroMemory(&pAd->Counters8023, sizeof(COUNTER_802_3));
-	NdisZeroMemory(&pAd->RalinkCounters, sizeof(COUNTER_RALINK));
-
-	// Reset HotSpot counter
-#if 0 // ToDo.
-	for (i = 0; i < MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		pEntry = &pAd->MacTab.Content[i];
-
-		if ((pEntry->Valid == FALSE) || (pEntry->Sst != SST_ASSOC))
-			continue;
-
-		pEntry->HSCounter.LastDataPacketTime = 0;
-		pEntry->HSCounter.TotalRxByteCount= 0;
-		pEntry->HSCounter.TotalTxByteCount= 0;
-	}
-#endif
-
-
-	return TRUE;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Add WPA key process.
-		In Adhoc WPANONE, bPairwise = 0;  KeyIdx = 0;
-
-	Arguments:
-		pAd 					Pointer to our adapter
-		pBuf							Pointer to the where the key stored
-
-	Return Value:
-		NDIS_SUCCESS					Add key successfully
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-#if 0 // remove by AlbertY
-NDIS_STATUS RTMPWPAAddKeyProc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PVOID			pBuf)
-{
-	PNDIS_802_11_KEY	pKey;
-	ULONG				KeyIdx;
-//	NDIS_STATUS 		Status;
-//	ULONG 	offset;	// unused variable, snowpin 2006.07.13
-
-	PUCHAR		pTxMic, pRxMic;
-	BOOLEAN 	bTxKey; 		// Set the key as transmit key
-	BOOLEAN 	bPairwise;		// Indicate the key is pairwise key
-	BOOLEAN 	bKeyRSC;		// indicate the receive  SC set by KeyRSC value.
-								// Otherwise, it will set by the NIC.
-	BOOLEAN 	bAuthenticator; // indicate key is set by authenticator.
-	UCHAR		apidx = BSS0;
-
-	pKey = (PNDIS_802_11_KEY) pBuf;
-	KeyIdx = pKey->KeyIndex & 0xff;
-	// Bit 31 of Add-key, Tx Key
-	bTxKey		   = (pKey->KeyIndex & 0x80000000) ? TRUE : FALSE;
-	// Bit 30 of Add-key PairwiseKey
-	bPairwise	   = (pKey->KeyIndex & 0x40000000) ? TRUE : FALSE;
-	// Bit 29 of Add-key KeyRSC
-	bKeyRSC 	   = (pKey->KeyIndex & 0x20000000) ? TRUE : FALSE;
-	// Bit 28 of Add-key Authenticator
-	bAuthenticator = (pKey->KeyIndex & 0x10000000) ? TRUE : FALSE;
-
-	DBGPRINT(RT_DEBUG_TRACE,("RTMPWPAAddKeyProc==>pKey->KeyIndex = %x. bPairwise= %d\n", pKey->KeyIndex, bPairwise));
-	// 1. Check Group / Pairwise Key
-	if (bPairwise)	// Pairwise Key
-	{
-		// 1. KeyIdx must be 0, otherwise, return NDIS_STATUS_INVALID_DATA
-		if (KeyIdx != 0)
-			return(NDIS_STATUS_INVALID_DATA);
-
-		// 2. Check bTx, it must be true, otherwise, return NDIS_STATUS_INVALID_DATA
-		if (bTxKey == FALSE)
-			return(NDIS_STATUS_INVALID_DATA);
-
-		// 3. If BSSID is all 0xff, return NDIS_STATUS_INVALID_DATA
-		if (MAC_ADDR_EQUAL(pKey->BSSID, BROADCAST_ADDR))
-			return(NDIS_STATUS_INVALID_DATA);
-
-		// 3.1 Check Pairwise key length for TKIP key. For AES, it's always 128 bits
-		//if ((pAdapter->PortCfg.WepStatus == Ndis802_11Encryption2Enabled) && (pKey->KeyLength != LEN_TKIP_KEY))
-		if ((pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled) && (pKey->KeyLength != LEN_TKIP_KEY))
-			return(NDIS_STATUS_INVALID_DATA);
-
-		pAd->SharedKey[apidx][KeyIdx].Type = PAIRWISE_KEY;
-
-		if (pAd->ApCfg.MBSSID[apidx].AuthMode == Ndis802_11AuthModeWPA2)
-		{
-			// Send media specific event to start PMKID caching
-			RTMPIndicateWPA2Status(pAd);
-		}
-	}
-	else
-	{
-		// 1. Check BSSID, if not current BSSID or Bcast, return NDIS_STATUS_INVALID_DATA
-		if ((! MAC_ADDR_EQUAL(pKey->BSSID, BROADCAST_ADDR)) &&
-			(! MAC_ADDR_EQUAL(pKey->BSSID, pAd->ApCfg.MBSSID[apidx].Bssid)))
-			return(NDIS_STATUS_INVALID_DATA);
-
-		// 2. Check Key index for supported Group Key
-		if (KeyIdx >= GROUP_KEY_NUM)
-			return(NDIS_STATUS_INVALID_DATA);
-
-		// 3. Set as default Tx Key if bTxKey is TRUE
-		if (bTxKey == TRUE)
-			pAd->ApCfg.MBSSID[apidx].DefaultKeyId = (UCHAR) KeyIdx;
-
-		pAd->SharedKey[apidx][KeyIdx].Type = GROUP_KEY;
-	}
-
-	// 4. Select RxMic / TxMic based on Supp / Authenticator
-	if (pAd->ApCfg.MBSSID[apidx].AuthMode == Ndis802_11AuthModeWPANone)
-	{
-		// for WPA-None Tx, Rx MIC is the same
-		pTxMic = (PUCHAR) (&pKey->KeyMaterial) + 16;
-		pRxMic = pTxMic;
-	}
-	else if (bAuthenticator == TRUE)
-	{
-		pTxMic = (PUCHAR) (&pKey->KeyMaterial) + 16;
-		pRxMic = (PUCHAR) (&pKey->KeyMaterial) + 24;
-	}
-	else
-	{
-		pRxMic = (PUCHAR) (&pKey->KeyMaterial) + 16;
-		pTxMic = (PUCHAR) (&pKey->KeyMaterial) + 24;
-	}
-
-	// 6. Check RxTsc
-	if (bKeyRSC == TRUE)
-	{
-		NdisMoveMemory(pAd->SharedKey[apidx][KeyIdx].RxTsc, &pKey->KeyRSC, 6);
-		NdisMoveMemory(pAd->MacTab.Content[BSSID_WCID].PairwiseKey.RxTsc, &pKey->KeyRSC, 6);
-	}
-	else
-	{
-		NdisZeroMemory(pAd->SharedKey[apidx][KeyIdx].RxTsc, 6);
-	}
-
-	// 7. Copy information into Pairwise Key structure.
-	// pKey->KeyLength will include TxMic and RxMic, therefore, we use 16 bytes hardcoded.
-	pAd->SharedKey[apidx][KeyIdx].KeyLen = (UCHAR) pKey->KeyLength;
-	pAd->MacTab.Content[BSSID_WCID].PairwiseKey.KeyLen = (UCHAR)pKey->KeyLength;
-	NdisMoveMemory(pAd->SharedKey[BSS0][KeyIdx].Key, &pKey->KeyMaterial, 16);
-	NdisMoveMemory(pAd->MacTab.Content[BSSID_WCID].PairwiseKey.Key, &pKey->KeyMaterial, 16);
-	if (pKey->KeyLength == LEN_TKIP_KEY)
-	{
-		// Only Key lenth equal to TKIP key have these
-		NdisMoveMemory(pAd->SharedKey[apidx][KeyIdx].RxMic, pRxMic, 8);
-		NdisMoveMemory(pAd->SharedKey[apidx][KeyIdx].TxMic, pTxMic, 8);
-		NdisMoveMemory(pAd->MacTab.Content[BSSID_WCID].PairwiseKey.RxMic, pRxMic, 8);
-		NdisMoveMemory(pAd->MacTab.Content[BSSID_WCID].PairwiseKey.TxMic, pTxMic, 8);
-	}
-
-	COPY_MAC_ADDR(pAd->SharedKey[BSS0][KeyIdx].BssId, pKey->BSSID);
-
-	// Init TxTsc to one based on WiFi WPA specs
-	pAd->SharedKey[apidx][KeyIdx].TxTsc[0] = 1;
-	pAd->SharedKey[apidx][KeyIdx].TxTsc[1] = 0;
-	pAd->SharedKey[apidx][KeyIdx].TxTsc[2] = 0;
-	pAd->SharedKey[apidx][KeyIdx].TxTsc[3] = 0;
-	pAd->SharedKey[apidx][KeyIdx].TxTsc[4] = 0;
-	pAd->SharedKey[apidx][KeyIdx].TxTsc[5] = 0;
-	// 4. Init TxTsc to one based on WiFi WPA specs
-	pAd->MacTab.Content[BSSID_WCID].PairwiseKey.TxTsc[0] = 1;
-	pAd->MacTab.Content[BSSID_WCID].PairwiseKey.TxTsc[1] = 0;
-	pAd->MacTab.Content[BSSID_WCID].PairwiseKey.TxTsc[2] = 0;
-	pAd->MacTab.Content[BSSID_WCID].PairwiseKey.TxTsc[3] = 0;
-	pAd->MacTab.Content[BSSID_WCID].PairwiseKey.TxTsc[4] = 0;
-	pAd->MacTab.Content[BSSID_WCID].PairwiseKey.TxTsc[5] = 0;
-
-	if (pAd->ApCfg.MBSSID[apidx].WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		pAd->SharedKey[apidx][KeyIdx].CipherAlg = CIPHER_AES;
-		pAd->MacTab.Content[BSSID_WCID].PairwiseKey.CipherAlg = CIPHER_AES;
-	}
-	else if (pAd->ApCfg.MBSSID[apidx].WepStatus == Ndis802_11Encryption2Enabled)
-	{
-		pAd->SharedKey[apidx][KeyIdx].CipherAlg = CIPHER_TKIP;
-		pAd->MacTab.Content[BSSID_WCID].PairwiseKey.CipherAlg = CIPHER_TKIP;
-	}
-	else if (pAd->ApCfg.MBSSID[apidx].WepStatus == Ndis802_11Encryption1Enabled)
-	{
-		if (pAd->SharedKey[apidx][KeyIdx].KeyLen == 5)
-		{
-			pAd->SharedKey[apidx][KeyIdx].CipherAlg = CIPHER_WEP64;
-			pAd->MacTab.Content[BSSID_WCID].PairwiseKey.CipherAlg = CIPHER_WEP64;
-		}
-		else if (pAd->SharedKey[apidx][KeyIdx].KeyLen == 13)
-		{
-			pAd->SharedKey[apidx][KeyIdx].CipherAlg = CIPHER_WEP128;
-			pAd->MacTab.Content[BSSID_WCID].PairwiseKey.CipherAlg = CIPHER_WEP128;
-		}
-		else
-		{
-			pAd->SharedKey[apidx][KeyIdx].CipherAlg = CIPHER_NONE;
-			pAd->MacTab.Content[BSSID_WCID].PairwiseKey.CipherAlg = CIPHER_NONE;
-		}
-	}
-	else
-	{
-		pAd->SharedKey[apidx][KeyIdx].CipherAlg = CIPHER_NONE;
-		pAd->MacTab.Content[BSSID_WCID].PairwiseKey.CipherAlg = CIPHER_NONE;
-	}
-
-	if ((pAd->OpMode == OPMODE_STA))  // Pairwise Key. Add BSSID to WCTable
-	{
-		pAd->MacTab.Content[BSSID_WCID].PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][KeyIdx].CipherAlg;
-		pAd->MacTab.Content[BSSID_WCID].PairwiseKey.KeyLen = pAd->SharedKey[BSS0][KeyIdx].KeyLen;
-	}
-
-	if ((pAd->ApCfg.MBSSID[apidx].AuthMode == Ndis802_11AuthModeWPA2) ||
-		(pAd->ApCfg.MBSSID[apidx].AuthMode == Ndis802_11AuthModeWPA2PSK))
-	{
-		//
-		// On WPA2, Update Group Key Cipher.
-		//
-		if (!bPairwise)
-		{
-			if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
-				pAd->SharedKey[apidx][KeyIdx].CipherAlg = CIPHER_AES;
-			else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-				pAd->SharedKey[apidx][KeyIdx].CipherAlg = CIPHER_TKIP;
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("pAd->SharedKey[%d][%d].CipherAlg = %d\n", apidx, KeyIdx, pAd->SharedKey[apidx][KeyIdx].CipherAlg));
-
-#if 0
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("%s Key #%d", CipherName[pAd->SharedKey[apidx][KeyIdx].CipherAlg],KeyIdx));
-	for (i = 0; i < 16; i++)
-	{
-		DBGPRINT_RAW(RT_DEBUG_TRACE, ("%02x:", pAd->SharedKey[apidx][KeyIdx].Key[i]));
-	}
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("\n	  Rx MIC Key = "));
-	for (i = 0; i < 8; i++)
-	{
-		DBGPRINT_RAW(RT_DEBUG_TRACE, ("%02x:", pAd->SharedKey[apidx][KeyIdx].RxMic[i]));
-	}
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("\n	  Tx MIC Key = "));
-	for (i = 0; i < 8; i++)
-	{
-		DBGPRINT_RAW(RT_DEBUG_TRACE, ("%02x:", pAd->SharedKey[apidx][KeyIdx].TxMic[i]));
-	}
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("\n	  RxTSC = "));
-	for (i = 0; i < 6; i++)
-	{
-		DBGPRINT_RAW(RT_DEBUG_TRACE, ("%02x:", pAd->SharedKey[apidx][KeyIdx].RxTsc[i]));
-	}
-#endif
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("\n pKey-> BSSID:%02x:%02x:%02x:%02x:%02x:%02x \n",
-		pKey->BSSID[0],pKey->BSSID[1],pKey->BSSID[2],pKey->BSSID[3],pKey->BSSID[4],pKey->BSSID[5]));
-
-	if ((bTxKey) && (pAd->OpMode == OPMODE_STA))  // Pairwise Key. Add BSSID to WCTable
-		RTMPAddBSSIDCipher(pAd, BSSID_WCID, pKey, pAd->SharedKey[BSS0][KeyIdx].CipherAlg);
-
-
-	// No matter pairwise key or what leyidx is, always has a copy at on-chip SharedKeytable.
-	AsicAddSharedKeyEntry(pAd,
-						  apidx,
-						  (UCHAR)KeyIdx,
-						  pAd->SharedKey[apidx][KeyIdx].CipherAlg,
-						  pAd->SharedKey[apidx][KeyIdx].Key,
-						  pAd->SharedKey[apidx][KeyIdx].TxMic,
-						  pAd->SharedKey[apidx][KeyIdx].RxMic);
-
-	// The WCID key specified in used at Tx. For STA, always use pairwise key.
-
-	// ad-hoc mode need to specify WAP Group key with WCID index=BSS0Mcast_WCID. Let's always set this key here.
-/*	if (bPairwise == FALSE)
-	{
-		offset = MAC_IVEIV_TABLE_BASE + (BSS0Mcast_WCID * HW_IVEIV_ENTRY_SIZE);
-		NdisZeroMemory(IVEIV, 8);
-		// 1. IV/EIV
-		// Specify key index to find shared key.
-		if ((pAd->SharedKey[BSS0][KeyIdx].CipherAlg==CIPHER_TKIP) ||
-			(pAd->SharedKey[BSS0][KeyIdx].CipherAlg==CIPHER_AES))
-		IVEIV[3] = 0x20;		// Eiv bit on. keyid always 0 for pairwise key
-		IVEIV[3] |= (KeyIdx<< 6);	// groupkey index is not 0
-		for (i=0; i<8; i++)
-		{
-			RTMP_IO_WRITE8(pAd, offset+i, IVEIV[i]);
-		}
-
-		// 2. WCID Attribute UDF:3, BSSIdx:3, Alg:3, Keytable:use share key, BSSIdx is 0
-		WCIDAttri = (pAd->SharedKey[BSS0][KeyIdx].CipherAlg<<1)|PAIRWISEKEYTABLE;
-		offset = MAC_WCID_ATTRIBUTE_BASE + (BSS0Mcast_WCID* HW_WCID_ATTRI_SIZE);
-		RTMP_IO_WRITE32(pAd, offset, WCIDAttri);
-
-	}
-
-*/
-
-   if (pAd->SharedKey[apidx][KeyIdx].Type == GROUP_KEY)
-	{
-		// 802.1x port control
-		pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-		DBGPRINT(RT_DEBUG_TRACE,("!!WPA_802_1X_PORT_SECURED!!\n"));
-
-	}
-
-	return (NDIS_STATUS_SUCCESS);
-}
-#endif
-
-BOOLEAN RTMPCheckStrPrintAble(
-    IN  CHAR *pInPutStr,
-    IN  UCHAR strLen)
-{
-    UCHAR i=0;
-
-    for (i=0; i<strLen; i++)
-    {
-        if ((pInPutStr[i] < 0x21) ||
-            (pInPutStr[i] > 0x7E))
-            return FALSE;
-    }
-
-    return TRUE;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Remove WPA Key process
-
-	Arguments:
-		pAd 					Pointer to our adapter
-		pBuf							Pointer to the where the key stored
-
-	Return Value:
-		NDIS_SUCCESS					Add key successfully
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-#ifdef CONFIG_STA_SUPPORT
-VOID    RTMPSetDesiredRates(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  LONG            Rates)
-{
-    NDIS_802_11_RATES aryRates;
-
-    memset(&aryRates, 0x00, sizeof(NDIS_802_11_RATES));
-    switch (pAdapter->CommonCfg.PhyMode)
-    {
-        case PHY_11A: // A only
-            switch (Rates)
-            {
-                case 6000000: //6M
-                    aryRates[0] = 0x0c; // 6M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_0;
-                    break;
-                case 9000000: //9M
-                    aryRates[0] = 0x12; // 9M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_1;
-                    break;
-                case 12000000: //12M
-                    aryRates[0] = 0x18; // 12M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_2;
-                    break;
-                case 18000000: //18M
-                    aryRates[0] = 0x24; // 18M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_3;
-                    break;
-                case 24000000: //24M
-                    aryRates[0] = 0x30; // 24M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_4;
-                    break;
-                case 36000000: //36M
-                    aryRates[0] = 0x48; // 36M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_5;
-                    break;
-                case 48000000: //48M
-                    aryRates[0] = 0x60; // 48M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_6;
-                    break;
-                case 54000000: //54M
-                    aryRates[0] = 0x6c; // 54M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_7;
-                    break;
-                case -1: //Auto
-                default:
-                    aryRates[0] = 0x6c; // 54Mbps
-                    aryRates[1] = 0x60; // 48Mbps
-                    aryRates[2] = 0x48; // 36Mbps
-                    aryRates[3] = 0x30; // 24Mbps
-                    aryRates[4] = 0x24; // 18M
-                    aryRates[5] = 0x18; // 12M
-                    aryRates[6] = 0x12; // 9M
-                    aryRates[7] = 0x0c; // 6M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-                    break;
-            }
-            break;
-        case PHY_11BG_MIXED: // B/G Mixed
-        case PHY_11B: // B only
-        case PHY_11ABG_MIXED: // A/B/G Mixed
-        default:
-            switch (Rates)
-            {
-                case 1000000: //1M
-                    aryRates[0] = 0x02;
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_0;
-                    break;
-                case 2000000: //2M
-                    aryRates[0] = 0x04;
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_1;
-                    break;
-                case 5000000: //5.5M
-                    aryRates[0] = 0x0b; // 5.5M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_2;
-                    break;
-                case 11000000: //11M
-                    aryRates[0] = 0x16; // 11M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_3;
-                    break;
-                case 6000000: //6M
-                    aryRates[0] = 0x0c; // 6M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_0;
-                    break;
-                case 9000000: //9M
-                    aryRates[0] = 0x12; // 9M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_1;
-                    break;
-                case 12000000: //12M
-                    aryRates[0] = 0x18; // 12M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_2;
-                    break;
-                case 18000000: //18M
-                    aryRates[0] = 0x24; // 18M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_3;
-                    break;
-                case 24000000: //24M
-                    aryRates[0] = 0x30; // 24M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_4;
-                    break;
-                case 36000000: //36M
-                    aryRates[0] = 0x48; // 36M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_5;
-                    break;
-                case 48000000: //48M
-                    aryRates[0] = 0x60; // 48M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_6;
-                    break;
-                case 54000000: //54M
-                    aryRates[0] = 0x6c; // 54M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_7;
-                    break;
-                case -1: //Auto
-                default:
-                    if (pAdapter->CommonCfg.PhyMode == PHY_11B)
-                    { //B Only
-                        aryRates[0] = 0x16; // 11Mbps
-                        aryRates[1] = 0x0b; // 5.5Mbps
-                        aryRates[2] = 0x04; // 2Mbps
-                        aryRates[3] = 0x02; // 1Mbps
-                    }
-                    else
-                    { //(B/G) Mixed or (A/B/G) Mixed
-                        aryRates[0] = 0x6c; // 54Mbps
-                        aryRates[1] = 0x60; // 48Mbps
-                        aryRates[2] = 0x48; // 36Mbps
-                        aryRates[3] = 0x30; // 24Mbps
-                        aryRates[4] = 0x16; // 11Mbps
-                        aryRates[5] = 0x0b; // 5.5Mbps
-                        aryRates[6] = 0x04; // 2Mbps
-                        aryRates[7] = 0x02; // 1Mbps
-                    }
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-                    break;
-            }
-            break;
-    }
-
-    NdisZeroMemory(pAdapter->CommonCfg.DesireRate, MAX_LEN_OF_SUPPORTED_RATES);
-    NdisMoveMemory(pAdapter->CommonCfg.DesireRate, &aryRates, sizeof(NDIS_802_11_RATES));
-    DBGPRINT(RT_DEBUG_TRACE, (" RTMPSetDesiredRates (%02x,%02x,%02x,%02x,%02x,%02x,%02x,%02x)\n",
-        pAdapter->CommonCfg.DesireRate[0],pAdapter->CommonCfg.DesireRate[1],
-        pAdapter->CommonCfg.DesireRate[2],pAdapter->CommonCfg.DesireRate[3],
-        pAdapter->CommonCfg.DesireRate[4],pAdapter->CommonCfg.DesireRate[5],
-        pAdapter->CommonCfg.DesireRate[6],pAdapter->CommonCfg.DesireRate[7] ));
-    // Changing DesiredRate may affect the MAX TX rate we used to TX frames out
-    MlmeUpdateTxRates(pAdapter, FALSE, 0);
-}
-
-NDIS_STATUS RTMPWPARemoveKeyProc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PVOID			pBuf)
-{
-	PNDIS_802_11_REMOVE_KEY pKey;
-	ULONG					KeyIdx;
-	NDIS_STATUS 			Status = NDIS_STATUS_FAILURE;
-	BOOLEAN 	bTxKey; 		// Set the key as transmit key
-	BOOLEAN 	bPairwise;		// Indicate the key is pairwise key
-	BOOLEAN 	bKeyRSC;		// indicate the receive  SC set by KeyRSC value.
-								// Otherwise, it will set by the NIC.
-	BOOLEAN 	bAuthenticator; // indicate key is set by authenticator.
-	INT 		i;
-
-	DBGPRINT(RT_DEBUG_TRACE,("---> RTMPWPARemoveKeyProc\n"));
-
-	pKey = (PNDIS_802_11_REMOVE_KEY) pBuf;
-	KeyIdx = pKey->KeyIndex & 0xff;
-	// Bit 31 of Add-key, Tx Key
-	bTxKey		   = (pKey->KeyIndex & 0x80000000) ? TRUE : FALSE;
-	// Bit 30 of Add-key PairwiseKey
-	bPairwise	   = (pKey->KeyIndex & 0x40000000) ? TRUE : FALSE;
-	// Bit 29 of Add-key KeyRSC
-	bKeyRSC 	   = (pKey->KeyIndex & 0x20000000) ? TRUE : FALSE;
-	// Bit 28 of Add-key Authenticator
-	bAuthenticator = (pKey->KeyIndex & 0x10000000) ? TRUE : FALSE;
-
-	// 1. If bTx is TRUE, return failure information
-	if (bTxKey == TRUE)
-		return(NDIS_STATUS_INVALID_DATA);
-
-	// 2. Check Pairwise Key
-	if (bPairwise)
-	{
-		// a. If BSSID is broadcast, remove all pairwise keys.
-		// b. If not broadcast, remove the pairwise specified by BSSID
-		for (i = 0; i < SHARE_KEY_NUM; i++)
-		{
-			if (MAC_ADDR_EQUAL(pAd->SharedKey[BSS0][i].BssId, pKey->BSSID))
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("RTMPWPARemoveKeyProc(KeyIdx=%d)\n", i));
-				pAd->SharedKey[BSS0][i].KeyLen = 0;
-				pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_NONE;
-				AsicRemoveSharedKeyEntry(pAd, BSS0, (UCHAR)i);
-				Status = NDIS_STATUS_SUCCESS;
-				break;
-			}
-		}
-	}
-	// 3. Group Key
-	else
-	{
-		// a. If BSSID is broadcast, remove all group keys indexed
-		// b. If BSSID matched, delete the group key indexed.
-		DBGPRINT(RT_DEBUG_TRACE,("RTMPWPARemoveKeyProc(KeyIdx=%ld)\n", KeyIdx));
-		pAd->SharedKey[BSS0][KeyIdx].KeyLen = 0;
-		pAd->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_NONE;
-		AsicRemoveSharedKeyEntry(pAd, BSS0, (UCHAR)KeyIdx);
-		Status = NDIS_STATUS_SUCCESS;
-	}
-
-	return (Status);
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-#ifdef CONFIG_STA_SUPPORT
-/*
-	========================================================================
-
-	Routine Description:
-		Remove All WPA Keys
-
-	Arguments:
-		pAd 					Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPWPARemoveAllKeys(
-	IN	PRTMP_ADAPTER	pAd)
-{
-
-	UCHAR 	i;
-
-	DBGPRINT(RT_DEBUG_TRACE,("RTMPWPARemoveAllKeys(AuthMode=%d, WepStatus=%d)\n", pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus));
-
-	// For WEP/CKIP, there is no need to remove it, since WinXP won't set it again after
-	// Link up. And it will be replaced if user changed it.
-	if (pAd->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-		return;
-
-	// For WPA-None, there is no need to remove it, since WinXP won't set it again after
-	// Link up. And it will be replaced if user changed it.
-	if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-		return;
-
-	// set BSSID wcid entry of the Pair-wise Key table as no-security mode
-	AsicRemovePairwiseKeyEntry(pAd, BSS0, BSSID_WCID);
-
-	// set all shared key mode as no-security.
-	for (i = 0; i < SHARE_KEY_NUM; i++)
-    {
-		DBGPRINT(RT_DEBUG_TRACE,("remove %s key #%d\n", CipherName[pAd->SharedKey[BSS0][i].CipherAlg], i));
-		NdisZeroMemory(&pAd->SharedKey[BSS0][i], sizeof(CIPHER_KEY));
-
-		AsicRemoveSharedKeyEntry(pAd, BSS0, i);
-	}
-
-}
-#endif // CONFIG_STA_SUPPORT //
-
-/*
-	========================================================================
-	Routine Description:
-		Change NIC PHY mode. Re-association may be necessary. possible settings
-		include - PHY_11B, PHY_11BG_MIXED, PHY_11A, and PHY_11ABG_MIXED
-
-	Arguments:
-		pAd - Pointer to our adapter
-		phymode  -
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-VOID	RTMPSetPhyMode(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	ULONG phymode)
-{
-	INT i;
-	// the selected phymode must be supported by the RF IC encoded in E2PROM
-
-	// if no change, do nothing
-	/* bug fix
-	if (pAd->CommonCfg.PhyMode == phymode)
-		return;
-    */
-	pAd->CommonCfg.PhyMode = (UCHAR)phymode;
-
-	DBGPRINT(RT_DEBUG_TRACE,("RTMPSetPhyMode : PhyMode=%d, channel=%d \n", pAd->CommonCfg.PhyMode, pAd->CommonCfg.Channel));
-#ifdef EXT_BUILD_CHANNEL_LIST
-	BuildChannelListEx(pAd);
-#else
-	BuildChannelList(pAd);
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-	// sanity check user setting
-	for (i = 0; i < pAd->ChannelListNum; i++)
-	{
-		if (pAd->CommonCfg.Channel == pAd->ChannelList[i].Channel)
-			break;
-	}
-
-	if (i == pAd->ChannelListNum)
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			pAd->CommonCfg.Channel = FirstChannel(pAd);
-#endif // CONFIG_STA_SUPPORT //
-		DBGPRINT(RT_DEBUG_ERROR, ("RTMPSetPhyMode: channel is out of range, use first channel=%d \n", pAd->CommonCfg.Channel));
-	}
-
-	NdisZeroMemory(pAd->CommonCfg.SupRate, MAX_LEN_OF_SUPPORTED_RATES);
-	NdisZeroMemory(pAd->CommonCfg.ExtRate, MAX_LEN_OF_SUPPORTED_RATES);
-	NdisZeroMemory(pAd->CommonCfg.DesireRate, MAX_LEN_OF_SUPPORTED_RATES);
-	switch (phymode) {
-		case PHY_11B:
-			pAd->CommonCfg.SupRate[0]  = 0x82;	  // 1 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[1]  = 0x84;	  // 2 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[2]  = 0x8B;	  // 5.5 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[3]  = 0x96;	  // 11 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRateLen  = 4;
-			pAd->CommonCfg.ExtRateLen  = 0;
-			pAd->CommonCfg.DesireRate[0]  = 2;	   // 1 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[1]  = 4;	   // 2 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[2]  = 11;    // 5.5 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[3]  = 22;    // 11 mbps, in units of 0.5 Mbps
-			//pAd->CommonCfg.HTPhyMode.field.MODE = MODE_CCK; // This MODE is only FYI. not use
-			break;
-
-		case PHY_11G:
-		case PHY_11BG_MIXED:
-		case PHY_11ABG_MIXED:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11N_2_4G:
-		case PHY_11ABGN_MIXED:
-		case PHY_11BGN_MIXED:
-		case PHY_11GN_MIXED:
-#endif // DOT11_N_SUPPORT //
-			pAd->CommonCfg.SupRate[0]  = 0x82;	  // 1 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[1]  = 0x84;	  // 2 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[2]  = 0x8B;	  // 5.5 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[3]  = 0x96;	  // 11 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[4]  = 0x12;	  // 9 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[5]  = 0x24;	  // 18 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[6]  = 0x48;	  // 36 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[7]  = 0x6c;	  // 54 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRateLen  = 8;
-			pAd->CommonCfg.ExtRate[0]  = 0x0C;	  // 6 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.ExtRate[1]  = 0x18;	  // 12 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.ExtRate[2]  = 0x30;	  // 24 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.ExtRate[3]  = 0x60;	  // 48 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.ExtRateLen  = 4;
-			pAd->CommonCfg.DesireRate[0]  = 2;	   // 1 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[1]  = 4;	   // 2 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[2]  = 11;    // 5.5 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[3]  = 22;    // 11 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[4]  = 12;    // 6 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[5]  = 18;    // 9 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[6]  = 24;    // 12 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[7]  = 36;    // 18 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[8]  = 48;    // 24 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[9]  = 72;    // 36 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[10] = 96;    // 48 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[11] = 108;   // 54 mbps, in units of 0.5 Mbps
-			break;
-
-		case PHY_11A:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11AN_MIXED:
-		case PHY_11AGN_MIXED:
-		case PHY_11N_5G:
-#endif // DOT11_N_SUPPORT //
-			pAd->CommonCfg.SupRate[0]  = 0x8C;	  // 6 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[1]  = 0x12;	  // 9 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[2]  = 0x98;	  // 12 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[3]  = 0x24;	  // 18 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[4]  = 0xb0;	  // 24 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[5]  = 0x48;	  // 36 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[6]  = 0x60;	  // 48 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[7]  = 0x6c;	  // 54 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRateLen  = 8;
-			pAd->CommonCfg.ExtRateLen  = 0;
-			pAd->CommonCfg.DesireRate[0]  = 12;    // 6 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[1]  = 18;    // 9 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[2]  = 24;    // 12 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[3]  = 36;    // 18 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[4]  = 48;    // 24 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[5]  = 72;    // 36 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[6]  = 96;    // 48 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[7]  = 108;   // 54 mbps, in units of 0.5 Mbps
-			//pAd->CommonCfg.HTPhyMode.field.MODE = MODE_OFDM; // This MODE is only FYI. not use
-			break;
-
-		default:
-			break;
-	}
-
-
-	pAd->CommonCfg.BandState = UNKNOWN_BAND;
-}
-
-
-#ifdef DOT11_N_SUPPORT
-/*
-	========================================================================
-	Routine Description:
-		Caller ensures we has 802.11n support.
-		Calls at setting HT from AP/STASetinformation
-
-	Arguments:
-		pAd - Pointer to our adapter
-		phymode  -
-
-	========================================================================
-*/
-VOID	RTMPSetHT(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	OID_SET_HT_PHYMODE *pHTPhyMode)
-{
-	//ULONG	*pmcs;
-	UINT32	Value = 0;
-	UCHAR	BBPValue = 0;
-	UCHAR	BBP3Value = 0;
-	UCHAR	RxStream = pAd->CommonCfg.RxStream;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSetHT : HT_mode(%d), ExtOffset(%d), MCS(%d), BW(%d), STBC(%d), SHORTGI(%d)\n",
-										pHTPhyMode->HtMode, pHTPhyMode->ExtOffset,
-										pHTPhyMode->MCS, pHTPhyMode->BW,
-										pHTPhyMode->STBC, pHTPhyMode->SHORTGI));
-
-	// Don't zero supportedHyPhy structure.
-	RTMPZeroMemory(&pAd->CommonCfg.HtCapability, sizeof(pAd->CommonCfg.HtCapability));
-	RTMPZeroMemory(&pAd->CommonCfg.AddHTInfo, sizeof(pAd->CommonCfg.AddHTInfo));
-	RTMPZeroMemory(&pAd->CommonCfg.NewExtChanOffset, sizeof(pAd->CommonCfg.NewExtChanOffset));
-	RTMPZeroMemory(&pAd->CommonCfg.DesiredHtPhy, sizeof(pAd->CommonCfg.DesiredHtPhy));
-
-   	if (pAd->CommonCfg.bRdg)
-	{
-		pAd->CommonCfg.HtCapability.ExtHtCapInfo.PlusHTC = 1;
-		pAd->CommonCfg.HtCapability.ExtHtCapInfo.RDGSupport = 1;
-	}
-	else
-	{
-		pAd->CommonCfg.HtCapability.ExtHtCapInfo.PlusHTC = 0;
-		pAd->CommonCfg.HtCapability.ExtHtCapInfo.RDGSupport = 0;
-	}
-
-	pAd->CommonCfg.HtCapability.HtCapParm.MaxRAmpduFactor = 3;
-	pAd->CommonCfg.DesiredHtPhy.MaxRAmpduFactor = 3;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSetHT : RxBAWinLimit = %d\n", pAd->CommonCfg.BACapability.field.RxBAWinLimit));
-
-	// Mimo power save, A-MSDU size,
-	pAd->CommonCfg.DesiredHtPhy.AmsduEnable = (USHORT)pAd->CommonCfg.BACapability.field.AmsduEnable;
-	pAd->CommonCfg.DesiredHtPhy.AmsduSize = (UCHAR)pAd->CommonCfg.BACapability.field.AmsduSize;
-	pAd->CommonCfg.DesiredHtPhy.MimoPs = (UCHAR)pAd->CommonCfg.BACapability.field.MMPSmode;
-	pAd->CommonCfg.DesiredHtPhy.MpduDensity = (UCHAR)pAd->CommonCfg.BACapability.field.MpduDensity;
-
-	pAd->CommonCfg.HtCapability.HtCapInfo.AMsduSize = (USHORT)pAd->CommonCfg.BACapability.field.AmsduSize;
-	pAd->CommonCfg.HtCapability.HtCapInfo.MimoPs = (USHORT)pAd->CommonCfg.BACapability.field.MMPSmode;
-	pAd->CommonCfg.HtCapability.HtCapParm.MpduDensity = (UCHAR)pAd->CommonCfg.BACapability.field.MpduDensity;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSetHT : AMsduSize = %d, MimoPs = %d, MpduDensity = %d, MaxRAmpduFactor = %d\n",
-													pAd->CommonCfg.DesiredHtPhy.AmsduSize,
-													pAd->CommonCfg.DesiredHtPhy.MimoPs,
-													pAd->CommonCfg.DesiredHtPhy.MpduDensity,
-													pAd->CommonCfg.DesiredHtPhy.MaxRAmpduFactor));
-
-	if(pHTPhyMode->HtMode == HTMODE_GF)
-	{
-		pAd->CommonCfg.HtCapability.HtCapInfo.GF = 1;
-		pAd->CommonCfg.DesiredHtPhy.GF = 1;
-	}
-	else
-		pAd->CommonCfg.DesiredHtPhy.GF = 0;
-
-	// Decide Rx MCSSet
-	switch (RxStream)
-	{
-		case 1:
-			pAd->CommonCfg.HtCapability.MCSSet[0] =  0xff;
-			pAd->CommonCfg.HtCapability.MCSSet[1] =  0x00;
-			break;
-
-		case 2:
-			pAd->CommonCfg.HtCapability.MCSSet[0] =  0xff;
-			pAd->CommonCfg.HtCapability.MCSSet[1] =  0xff;
-			break;
-
-		case 3: // 3*3
-			pAd->CommonCfg.HtCapability.MCSSet[0] =  0xff;
-			pAd->CommonCfg.HtCapability.MCSSet[1] =  0xff;
-			pAd->CommonCfg.HtCapability.MCSSet[2] =  0xff;
-			break;
-	}
-
-	if (pAd->CommonCfg.bForty_Mhz_Intolerant && (pAd->CommonCfg.Channel <= 14) && (pHTPhyMode->BW == BW_40) )
-	{
-		pHTPhyMode->BW = BW_20;
-		pAd->CommonCfg.HtCapability.HtCapInfo.Forty_Mhz_Intolerant = 1;
-	}
-
-	if(pHTPhyMode->BW == BW_40)
-	{
-		pAd->CommonCfg.HtCapability.MCSSet[4] = 0x1; // MCS 32
-		pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth = 1;
-		if (pAd->CommonCfg.Channel <= 14)
-			pAd->CommonCfg.HtCapability.HtCapInfo.CCKmodein40 = 1;
-
-		pAd->CommonCfg.DesiredHtPhy.ChannelWidth = 1;
-		pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth = 1;
-		pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset = (pHTPhyMode->ExtOffset == EXTCHA_BELOW)? (EXTCHA_BELOW): EXTCHA_ABOVE;
-		// Set Regsiter for extension channel position.
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBP3Value);
-		if ((pHTPhyMode->ExtOffset == EXTCHA_BELOW))
-		{
-			Value |= 0x1;
-			BBP3Value |= (0x20);
-			RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-		}
-		else if ((pHTPhyMode->ExtOffset == EXTCHA_ABOVE))
-		{
-			Value &= 0xfe;
-			BBP3Value &= (~0x20);
-			RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-		}
-
-		// Turn on BBP 40MHz mode now only as AP .
-		// Sta can turn on BBP 40MHz after connection with 40MHz AP. Sta only broadcast 40MHz capability before connection.
-		if ((pAd->OpMode == OPMODE_AP) || INFRA_ON(pAd) || ADHOC_ON(pAd)
-			)
-		{
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue &= (~0x18);
-			BBPValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBP3Value);
-			pAd->CommonCfg.BBPCurrentBW = BW_40;
-		}
-	}
-	else
-	{
-		pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth = 0;
-		pAd->CommonCfg.DesiredHtPhy.ChannelWidth = 0;
-		pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth = 0;
-		pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset = EXTCHA_NONE;
-		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
-		// Turn on BBP 20MHz mode by request here.
-		{
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue &= (~0x18);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-			pAd->CommonCfg.BBPCurrentBW = BW_20;
-		}
-	}
-
-	if(pHTPhyMode->STBC == STBC_USE)
-	{
-		pAd->CommonCfg.HtCapability.HtCapInfo.TxSTBC = 1;
-		pAd->CommonCfg.DesiredHtPhy.TxSTBC = 1;
-		pAd->CommonCfg.HtCapability.HtCapInfo.RxSTBC = 1;
-		pAd->CommonCfg.DesiredHtPhy.RxSTBC = 1;
-	}
-	else
-	{
-		pAd->CommonCfg.DesiredHtPhy.TxSTBC = 0;
-		pAd->CommonCfg.DesiredHtPhy.RxSTBC = 0;
-	}
-
-#ifdef RT2870
-	/* Frank recommend ,If not, Tx maybe block in high power. Rx has no problem*/
-	if(IS_RT3070(pAd) && ((pAd->RfIcType == RFIC_3020) || (pAd->RfIcType == RFIC_2020)))
-	{
-		pAd->CommonCfg.HtCapability.HtCapInfo.TxSTBC = 0;
-		pAd->CommonCfg.DesiredHtPhy.TxSTBC = 0;
-	}
-#endif // RT2870 //
-
-	if(pHTPhyMode->SHORTGI == GI_400)
-	{
-		pAd->CommonCfg.HtCapability.HtCapInfo.ShortGIfor20 = 1;
-		pAd->CommonCfg.HtCapability.HtCapInfo.ShortGIfor40 = 1;
-		pAd->CommonCfg.DesiredHtPhy.ShortGIfor20 = 1;
-		pAd->CommonCfg.DesiredHtPhy.ShortGIfor40 = 1;
-	}
-	else
-	{
-		pAd->CommonCfg.HtCapability.HtCapInfo.ShortGIfor20 = 0;
-		pAd->CommonCfg.HtCapability.HtCapInfo.ShortGIfor40 = 0;
-		pAd->CommonCfg.DesiredHtPhy.ShortGIfor20 = 0;
-		pAd->CommonCfg.DesiredHtPhy.ShortGIfor40 = 0;
-	}
-
-	// We support link adaptation for unsolicit MCS feedback, set to 2.
-	pAd->CommonCfg.HtCapability.ExtHtCapInfo.MCSFeedback = MCSFBK_NONE; //MCSFBK_UNSOLICIT;
-	pAd->CommonCfg.AddHTInfo.ControlChan = pAd->CommonCfg.Channel;
-	// 1, the extension channel above the control channel.
-
-	// EDCA parameters used for AP's own transmission
-	if (pAd->CommonCfg.APEdcaParm.bValid == FALSE)
-	{
-		pAd->CommonCfg.APEdcaParm.bValid = TRUE;
-		pAd->CommonCfg.APEdcaParm.Aifsn[0] = 3;
-		pAd->CommonCfg.APEdcaParm.Aifsn[1] = 7;
-		pAd->CommonCfg.APEdcaParm.Aifsn[2] = 1;
-		pAd->CommonCfg.APEdcaParm.Aifsn[3] = 1;
-
-		pAd->CommonCfg.APEdcaParm.Cwmin[0] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmin[1] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmin[2] = 3;
-		pAd->CommonCfg.APEdcaParm.Cwmin[3] = 2;
-
-		pAd->CommonCfg.APEdcaParm.Cwmax[0] = 6;
-		pAd->CommonCfg.APEdcaParm.Cwmax[1] = 10;
-		pAd->CommonCfg.APEdcaParm.Cwmax[2] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmax[3] = 3;
-
-		pAd->CommonCfg.APEdcaParm.Txop[0]  = 0;
-		pAd->CommonCfg.APEdcaParm.Txop[1]  = 0;
-		pAd->CommonCfg.APEdcaParm.Txop[2]  = 94;
-		pAd->CommonCfg.APEdcaParm.Txop[3]  = 47;
-	}
-	AsicSetEdcaParm(pAd, &pAd->CommonCfg.APEdcaParm);
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		RTMPSetIndividualHT(pAd, 0);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Caller ensures we has 802.11n support.
-		Calls at setting HT from AP/STASetinformation
-
-	Arguments:
-		pAd - Pointer to our adapter
-		phymode  -
-
-	========================================================================
-*/
-VOID	RTMPSetIndividualHT(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	UCHAR				apidx)
-{
-	PRT_HT_PHY_INFO		pDesired_ht_phy = NULL;
-	UCHAR	TxStream = pAd->CommonCfg.TxStream;
-	UCHAR	DesiredMcs	= MCS_AUTO;
-
-	do
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			pDesired_ht_phy = &pAd->StaCfg.DesiredHtPhyInfo;
-			DesiredMcs = pAd->StaCfg.DesiredTransmitSetting.field.MCS;
-			//pAd->StaCfg.bAutoTxRateSwitch = (DesiredMcs == MCS_AUTO) ? TRUE : FALSE;
-				break;
-		}
-#endif // CONFIG_STA_SUPPORT //
-	} while (FALSE);
-
-	if (pDesired_ht_phy == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RTMPSetIndividualHT: invalid apidx(%d)\n", apidx));
-		return;
-	}
-	RTMPZeroMemory(pDesired_ht_phy, sizeof(RT_HT_PHY_INFO));
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSetIndividualHT : Desired MCS = %d\n", DesiredMcs));
-	// Check the validity of MCS
-	if ((TxStream == 1) && ((DesiredMcs >= MCS_8) && (DesiredMcs <= MCS_15)))
-	{
-		DBGPRINT(RT_DEBUG_WARN, ("RTMPSetIndividualHT: MCS(%d) is invalid in 1S, reset it as MCS_7\n", DesiredMcs));
-		DesiredMcs = MCS_7;
-	}
-
-	if ((pAd->CommonCfg.DesiredHtPhy.ChannelWidth == BW_20) && (DesiredMcs == MCS_32))
-	{
-		DBGPRINT(RT_DEBUG_WARN, ("RTMPSetIndividualHT: MCS_32 is only supported in 40-MHz, reset it as MCS_0\n"));
-		DesiredMcs = MCS_0;
-	}
-
-	pDesired_ht_phy->bHtEnable = TRUE;
-
-	// Decide desired Tx MCS
-	switch (TxStream)
-	{
-		case 1:
-			if (DesiredMcs == MCS_AUTO)
-			{
-				pDesired_ht_phy->MCSSet[0]= 0xff;
-				pDesired_ht_phy->MCSSet[1]= 0x00;
-			}
-			else if (DesiredMcs <= MCS_7)
-			{
-				pDesired_ht_phy->MCSSet[0]= 1<<DesiredMcs;
-				pDesired_ht_phy->MCSSet[1]= 0x00;
-			}
-			break;
-
-		case 2:
-			if (DesiredMcs == MCS_AUTO)
-			{
-				pDesired_ht_phy->MCSSet[0]= 0xff;
-				pDesired_ht_phy->MCSSet[1]= 0xff;
-			}
-			else if (DesiredMcs <= MCS_15)
-			{
-				ULONG mode;
-
-				mode = DesiredMcs / 8;
-				if (mode < 2)
-					pDesired_ht_phy->MCSSet[mode] = (1 << (DesiredMcs - mode * 8));
-			}
-			break;
-
-		case 3: // 3*3
-			if (DesiredMcs == MCS_AUTO)
-			{
-				/* MCS0 ~ MCS23, 3 bytes */
-				pDesired_ht_phy->MCSSet[0]= 0xff;
-				pDesired_ht_phy->MCSSet[1]= 0xff;
-				pDesired_ht_phy->MCSSet[2]= 0xff;
-			}
-			else if (DesiredMcs <= MCS_23)
-			{
-				ULONG mode;
-
-				mode = DesiredMcs / 8;
-				if (mode < 3)
-					pDesired_ht_phy->MCSSet[mode] = (1 << (DesiredMcs - mode * 8));
-			}
-			break;
-	}
-
-	if(pAd->CommonCfg.DesiredHtPhy.ChannelWidth == BW_40)
-	{
-		if (DesiredMcs == MCS_AUTO || DesiredMcs == MCS_32)
-			pDesired_ht_phy->MCSSet[4] = 0x1;
-	}
-
-	// update HT Rate setting
-    if (pAd->OpMode == OPMODE_STA)
-        MlmeUpdateHtTxRates(pAd, BSS0);
-    else
-	    MlmeUpdateHtTxRates(pAd, apidx);
-}
-
-
-/*
-	========================================================================
-	Routine Description:
-		Update HT IE from our capability.
-
-	Arguments:
-		Send all HT IE in beacon/probe rsp/assoc rsp/action frame.
-
-
-	========================================================================
-*/
-VOID	RTMPUpdateHTIE(
-	IN	RT_HT_CAPABILITY	*pRtHt,
-	IN		UCHAR				*pMcsSet,
-	OUT		HT_CAPABILITY_IE *pHtCapability,
-	OUT		ADD_HT_INFO_IE		*pAddHtInfo)
-{
-	RTMPZeroMemory(pHtCapability, sizeof(HT_CAPABILITY_IE));
-	RTMPZeroMemory(pAddHtInfo, sizeof(ADD_HT_INFO_IE));
-
-		pHtCapability->HtCapInfo.ChannelWidth = pRtHt->ChannelWidth;
-		pHtCapability->HtCapInfo.MimoPs = pRtHt->MimoPs;
-		pHtCapability->HtCapInfo.GF = pRtHt->GF;
-		pHtCapability->HtCapInfo.ShortGIfor20 = pRtHt->ShortGIfor20;
-		pHtCapability->HtCapInfo.ShortGIfor40 = pRtHt->ShortGIfor40;
-		pHtCapability->HtCapInfo.TxSTBC = pRtHt->TxSTBC;
-		pHtCapability->HtCapInfo.RxSTBC = pRtHt->RxSTBC;
-		pHtCapability->HtCapInfo.AMsduSize = pRtHt->AmsduSize;
-		pHtCapability->HtCapParm.MaxRAmpduFactor = pRtHt->MaxRAmpduFactor;
-		pHtCapability->HtCapParm.MpduDensity = pRtHt->MpduDensity;
-
-		pAddHtInfo->AddHtInfo.ExtChanOffset = pRtHt->ExtChanOffset ;
-		pAddHtInfo->AddHtInfo.RecomWidth = pRtHt->RecomWidth;
-		pAddHtInfo->AddHtInfo2.OperaionMode = pRtHt->OperaionMode;
-		pAddHtInfo->AddHtInfo2.NonGfPresent = pRtHt->NonGfPresent;
-		RTMPMoveMemory(pAddHtInfo->MCSSet, /*pRtHt->MCSSet*/pMcsSet, 4); // rt2860 only support MCS max=32, no need to copy all 16 uchar.
-
-        DBGPRINT(RT_DEBUG_TRACE,("RTMPUpdateHTIE <== \n"));
-}
-#endif // DOT11_N_SUPPORT //
-
-/*
-	========================================================================
-	Description:
-		Add Client security information into ASIC WCID table and IVEIV table.
-    Return:
-	========================================================================
-*/
-VOID	RTMPAddWcidAttributeEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BssIdx,
-	IN 	UCHAR		 	KeyIdx,
-	IN 	UCHAR		 	CipherAlg,
-	IN 	MAC_TABLE_ENTRY *pEntry)
-{
-	UINT32		WCIDAttri = 0;
-	USHORT		offset;
-	UCHAR		IVEIV = 0;
-	USHORT		Wcid = 0;
-
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			if (BssIdx > BSS0)
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("RTMPAddWcidAttributeEntry: The BSS-index(%d) is out of range for Infra link. \n", BssIdx));
-				return;
-			}
-
-			// 1.	In ADHOC mode, the AID is wcid number. And NO mesh link exists.
-			// 2.	In Infra mode, the AID:1 MUST be wcid of infra STA.
-			//					   the AID:2~ assign to mesh link entry.
-			if (pEntry && ADHOC_ON(pAd))
-				Wcid = pEntry->Aid;
-			else if (pEntry && INFRA_ON(pAd))
-			{
-#ifdef QOS_DLS_SUPPORT
-				if (pEntry->ValidAsDls == TRUE)
-					Wcid = pEntry->Aid;
-				else
-#endif // QOS_DLS_SUPPORT //
-				Wcid = BSSID_WCID;
-			}
-			else
-				Wcid = MCAST_WCID;
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	// Update WCID attribute table
-	offset = MAC_WCID_ATTRIBUTE_BASE + (Wcid * HW_WCID_ATTRI_SIZE);
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pEntry && pEntry->ValidAsMesh)
-			WCIDAttri = (CipherAlg<<1) | PAIRWISEKEYTABLE;
-#ifdef QOS_DLS_SUPPORT
-		else if ((pEntry) && (pEntry->ValidAsDls) &&
-					((CipherAlg == CIPHER_TKIP) ||
-				 	(CipherAlg == CIPHER_TKIP_NO_MIC) ||
-					(CipherAlg == CIPHER_AES) ||
-				 	(CipherAlg == CIPHER_NONE)))
-			WCIDAttri = (CipherAlg<<1) | PAIRWISEKEYTABLE;
-#endif // QOS_DLS_SUPPORT //
-		else
-			WCIDAttri = (CipherAlg<<1) | SHAREDKEYTABLE;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	RTMP_IO_WRITE32(pAd, offset, WCIDAttri);
-
-
-	// Update IV/EIV table
-	offset = MAC_IVEIV_TABLE_BASE + (Wcid * HW_IVEIV_ENTRY_SIZE);
-
-	// WPA mode
-	if ((CipherAlg == CIPHER_TKIP) || (CipherAlg == CIPHER_TKIP_NO_MIC) || (CipherAlg == CIPHER_AES))
-	{
-		// Eiv bit on. keyid always is 0 for pairwise key
-		IVEIV = (KeyIdx <<6) | 0x20;
-	}
-	else
-	{
-		// WEP KeyIdx is default tx key.
-		IVEIV = (KeyIdx << 6);
-	}
-
-	// For key index and ext IV bit, so only need to update the position(offset+3).
-#ifdef RT2870
-	RTUSBMultiWrite_OneByte(pAd, offset+3, &IVEIV);
-#endif // RT2870 //
-
-	DBGPRINT(RT_DEBUG_TRACE,("RTMPAddWcidAttributeEntry: WCID #%d, KeyIndex #%d, Alg=%s\n",Wcid, KeyIdx, CipherName[CipherAlg]));
-	DBGPRINT(RT_DEBUG_TRACE,("	WCIDAttri = 0x%x \n",  WCIDAttri));
-
-}
-
-/*
-    ==========================================================================
-    Description:
-        Parse encryption type
-Arguments:
-    pAdapter                    Pointer to our adapter
-    wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-    ==========================================================================
-*/
-CHAR *GetEncryptType(CHAR enc)
-{
-    if(enc == Ndis802_11WEPDisabled)
-        return "NONE";
-    if(enc == Ndis802_11WEPEnabled)
-    	return "WEP";
-    if(enc == Ndis802_11Encryption2Enabled)
-    	return "TKIP";
-    if(enc == Ndis802_11Encryption3Enabled)
-    	return "AES";
-	if(enc == Ndis802_11Encryption4Enabled)
-    	return "TKIPAES";
-    else
-    	return "UNKNOW";
-}
-
-CHAR *GetAuthMode(CHAR auth)
-{
-    if(auth == Ndis802_11AuthModeOpen)
-    	return "OPEN";
-    if(auth == Ndis802_11AuthModeShared)
-    	return "SHARED";
-	if(auth == Ndis802_11AuthModeAutoSwitch)
-    	return "AUTOWEP";
-    if(auth == Ndis802_11AuthModeWPA)
-    	return "WPA";
-    if(auth == Ndis802_11AuthModeWPAPSK)
-    	return "WPAPSK";
-    if(auth == Ndis802_11AuthModeWPANone)
-    	return "WPANONE";
-    if(auth == Ndis802_11AuthModeWPA2)
-    	return "WPA2";
-    if(auth == Ndis802_11AuthModeWPA2PSK)
-    	return "WPA2PSK";
-	if(auth == Ndis802_11AuthModeWPA1WPA2)
-    	return "WPA1WPA2";
-	if(auth == Ndis802_11AuthModeWPA1PSKWPA2PSK)
-    	return "WPA1PSKWPA2PSK";
-
-    	return "UNKNOW";
-}
-
-#if 1 //#ifndef UCOS
-/*
-    ==========================================================================
-    Description:
-        Get site survey results
-	Arguments:
-	    pAdapter                    Pointer to our adapter
-	    wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-        		1.) UI needs to wait 4 seconds after issue a site survey command
-        		2.) iwpriv ra0 get_site_survey
-        		3.) UI needs to prepare at least 4096bytes to get the results
-    ==========================================================================
-*/
-#define	LINE_LEN	(4+33+20+8+10+9+7+3)	// Channel+SSID+Bssid+WepStatus+AuthMode+Signal+WiressMode+NetworkType
-VOID RTMPIoctlGetSiteSurvey(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	CHAR		*msg;
-	INT 		i=0;
-	INT			WaitCnt;
-	INT 		Status=0;
-	CHAR		Ssid[MAX_LEN_OF_SSID +1];
-    INT         Rssi = 0, max_len = LINE_LEN;
-	UINT        Rssi_Quality = 0;
-	NDIS_802_11_NETWORK_TYPE    wireless_mode;
-
-	os_alloc_mem(NULL, (PUCHAR *)&msg, sizeof(CHAR)*((MAX_LEN_OF_BSS_TABLE)*max_len));
-
-	if (msg == NULL)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("RTMPIoctlGetSiteSurvey - msg memory alloc fail.\n"));
-		return;
-	}
-
-	memset(msg, 0 ,(MAX_LEN_OF_BSS_TABLE)*max_len );
-	memset(Ssid, 0 ,(MAX_LEN_OF_SSID +1));
-	sprintf(msg,"%s","\n");
-	sprintf(msg+strlen(msg),"%-4s%-33s%-20s%-8s%-10s%-9s%-7s%-3s\n",
-	    "Ch", "SSID", "BSSID", "Enc", "Auth", "Siganl(%)", "W-Mode", " NT");
-
-
-	WaitCnt = 0;
-#ifdef CONFIG_STA_SUPPORT
-	pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-	while ((ScanRunning(pAdapter) == TRUE) && (WaitCnt++ < 200))
-		OS_WAIT(500);
-#endif // CONFIG_STA_SUPPORT //
-
-	for(i=0; i<pAdapter->ScanTab.BssNr ;i++)
-	{
-		if( pAdapter->ScanTab.BssEntry[i].Channel==0)
-			break;
-
-		if((strlen(msg)+max_len ) >= IW_SCAN_MAX_DATA)
-			break;
-
-		//Channel
-		sprintf(msg+strlen(msg),"%-4d", pAdapter->ScanTab.BssEntry[i].Channel);
-		//SSID
-		memcpy(Ssid, pAdapter->ScanTab.BssEntry[i].Ssid, pAdapter->ScanTab.BssEntry[i].SsidLen);
-		Ssid[pAdapter->ScanTab.BssEntry[i].SsidLen] = '\0';
-		sprintf(msg+strlen(msg),"%-33s", Ssid);
-		//BSSID
-		sprintf(msg+strlen(msg),"%02x:%02x:%02x:%02x:%02x:%02x   ",
-			pAdapter->ScanTab.BssEntry[i].Bssid[0],
-			pAdapter->ScanTab.BssEntry[i].Bssid[1],
-			pAdapter->ScanTab.BssEntry[i].Bssid[2],
-			pAdapter->ScanTab.BssEntry[i].Bssid[3],
-			pAdapter->ScanTab.BssEntry[i].Bssid[4],
-			pAdapter->ScanTab.BssEntry[i].Bssid[5]);
-		//Encryption Type
-		sprintf(msg+strlen(msg),"%-8s",GetEncryptType(pAdapter->ScanTab.BssEntry[i].WepStatus));
-		//Authentication Mode
-		if (pAdapter->ScanTab.BssEntry[i].WepStatus == Ndis802_11WEPEnabled)
-			sprintf(msg+strlen(msg),"%-10s", "UNKNOW");
-		else
-			sprintf(msg+strlen(msg),"%-10s",GetAuthMode(pAdapter->ScanTab.BssEntry[i].AuthMode));
-		// Rssi
-		Rssi = (INT)pAdapter->ScanTab.BssEntry[i].Rssi;
-		if (Rssi >= -50)
-			Rssi_Quality = 100;
-		else if (Rssi >= -80)    // between -50 ~ -80dbm
-			Rssi_Quality = (UINT)(24 + ((Rssi + 80) * 26)/10);
-		else if (Rssi >= -90)   // between -80 ~ -90dbm
-			Rssi_Quality = (UINT)(((Rssi + 90) * 26)/10);
-		else    // < -84 dbm
-			Rssi_Quality = 0;
-		sprintf(msg+strlen(msg),"%-9d", Rssi_Quality);
-		// Wireless Mode
-		wireless_mode = NetworkTypeInUseSanity(&pAdapter->ScanTab.BssEntry[i]);
-		if (wireless_mode == Ndis802_11FH ||
-			wireless_mode == Ndis802_11DS)
-			sprintf(msg+strlen(msg),"%-7s", "11b");
-		else if (wireless_mode == Ndis802_11OFDM5)
-			sprintf(msg+strlen(msg),"%-7s", "11a");
-		else if (wireless_mode == Ndis802_11OFDM5_N)
-			sprintf(msg+strlen(msg),"%-7s", "11a/n");
-		else if (wireless_mode == Ndis802_11OFDM24)
-			sprintf(msg+strlen(msg),"%-7s", "11b/g");
-		else if (wireless_mode == Ndis802_11OFDM24_N)
-			sprintf(msg+strlen(msg),"%-7s", "11b/g/n");
-		else
-			sprintf(msg+strlen(msg),"%-7s", "unknow");
-		//Network Type
-		if (pAdapter->ScanTab.BssEntry[i].BssType == BSS_ADHOC)
-			sprintf(msg+strlen(msg),"%-3s", " Ad");
-		else
-			sprintf(msg+strlen(msg),"%-3s", " In");
-
-        sprintf(msg+strlen(msg),"\n");
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-#endif // CONFIG_STA_SUPPORT //
-	wrq->u.data.length = strlen(msg);
-	Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPIoctlGetSiteSurvey - wrq->u.data.length = %d\n", wrq->u.data.length));
-	os_free_mem(NULL, (PUCHAR)msg);
-}
-
-
-#define	MAC_LINE_LEN	(14+4+4+10+10+10+6+6)	// Addr+aid+psm+datatime+rxbyte+txbyte+current tx rate+last tx rate
-VOID RTMPIoctlGetMacTable(
-	IN PRTMP_ADAPTER pAd,
-	IN struct iwreq *wrq)
-{
-	INT i;
-	RT_802_11_MAC_TABLE MacTab;
-	char *msg;
-
-	MacTab.Num = 0;
-	for (i=0; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		if (pAd->MacTab.Content[i].ValidAsCLI && (pAd->MacTab.Content[i].Sst == SST_ASSOC))
-		{
-			COPY_MAC_ADDR(MacTab.Entry[MacTab.Num].Addr, &pAd->MacTab.Content[i].Addr);
-			MacTab.Entry[MacTab.Num].Aid = (UCHAR)pAd->MacTab.Content[i].Aid;
-			MacTab.Entry[MacTab.Num].Psm = pAd->MacTab.Content[i].PsMode;
-#ifdef DOT11_N_SUPPORT
-			MacTab.Entry[MacTab.Num].MimoPs = pAd->MacTab.Content[i].MmpsMode;
-#endif // DOT11_N_SUPPORT //
-
-			// Fill in RSSI per entry
-			MacTab.Entry[MacTab.Num].AvgRssi0 = pAd->MacTab.Content[i].RssiSample.AvgRssi0;
-			MacTab.Entry[MacTab.Num].AvgRssi1 = pAd->MacTab.Content[i].RssiSample.AvgRssi1;
-			MacTab.Entry[MacTab.Num].AvgRssi2 = pAd->MacTab.Content[i].RssiSample.AvgRssi2;
-
-			// the connected time per entry
-			MacTab.Entry[MacTab.Num].ConnectedTime = pAd->MacTab.Content[i].StaConnectTime;
-#if 0 // ToDo
-			MacTab.Entry[MacTab.Num].HSCounter.LastDataPacketTime = pAd->MacTab.Content[i].HSCounter.LastDataPacketTime;
-			MacTab.Entry[MacTab.Num].HSCounter.TotalRxByteCount = pAd->MacTab.Content[i].HSCounter.TotalRxByteCount;
-			MacTab.Entry[MacTab.Num].HSCounter.TotalTxByteCount = pAd->MacTab.Content[i].HSCounter.TotalTxByteCount;
-#endif
-			MacTab.Entry[MacTab.Num].TxRate.field.MCS = pAd->MacTab.Content[i].HTPhyMode.field.MCS;
-			MacTab.Entry[MacTab.Num].TxRate.field.BW = pAd->MacTab.Content[i].HTPhyMode.field.BW;
-			MacTab.Entry[MacTab.Num].TxRate.field.ShortGI = pAd->MacTab.Content[i].HTPhyMode.field.ShortGI;
-			MacTab.Entry[MacTab.Num].TxRate.field.STBC = pAd->MacTab.Content[i].HTPhyMode.field.STBC;
-			MacTab.Entry[MacTab.Num].TxRate.field.rsv = pAd->MacTab.Content[i].HTPhyMode.field.rsv;
-			MacTab.Entry[MacTab.Num].TxRate.field.MODE = pAd->MacTab.Content[i].HTPhyMode.field.MODE;
-			MacTab.Entry[MacTab.Num].TxRate.word = pAd->MacTab.Content[i].HTPhyMode.word;
-
-			MacTab.Num += 1;
-		}
-	}
-	wrq->u.data.length = sizeof(RT_802_11_MAC_TABLE);
-	if (copy_to_user(wrq->u.data.pointer, &MacTab, wrq->u.data.length))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s: copy_to_user() fail\n", __func__));
-	}
-
-	msg = (CHAR *) kmalloc(sizeof(CHAR)*(MAX_LEN_OF_MAC_TABLE*MAC_LINE_LEN), MEM_ALLOC_FLAG);
-	memset(msg, 0 ,MAX_LEN_OF_MAC_TABLE*MAC_LINE_LEN );
-	sprintf(msg,"%s","\n");
-	sprintf(msg+strlen(msg),"%-14s%-4s%-4s%-10s%-10s%-10s%-6s%-6s\n",
-		"MAC", "AID", "PSM", "LDT", "RxB", "TxB","CTxR", "LTxR");
-
-	for (i=0; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[i];
-		if (pEntry->ValidAsCLI && (pEntry->Sst == SST_ASSOC))
-		{
-			if((strlen(msg)+MAC_LINE_LEN ) >= (MAX_LEN_OF_MAC_TABLE*MAC_LINE_LEN) )
-				break;
-			sprintf(msg+strlen(msg),"%02x%02x%02x%02x%02x%02x  ",
-				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
-				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5]);
-			sprintf(msg+strlen(msg),"%-4d", (int)pEntry->Aid);
-			sprintf(msg+strlen(msg),"%-4d", (int)pEntry->PsMode);
-			sprintf(msg+strlen(msg),"%-10d",0/*pAd->MacTab.Content[i].HSCounter.LastDataPacketTime*/); // ToDo
-			sprintf(msg+strlen(msg),"%-10d",0/*pAd->MacTab.Content[i].HSCounter.TotalRxByteCount*/); // ToDo
-			sprintf(msg+strlen(msg),"%-10d",0/*pAd->MacTab.Content[i].HSCounter.TotalTxByteCount*/); // ToDo
-			sprintf(msg+strlen(msg),"%-6d",RateIdToMbps[pAd->MacTab.Content[i].CurrTxRate]);
-			sprintf(msg+strlen(msg),"%-6d\n",0/*RateIdToMbps[pAd->MacTab.Content[i].LastTxRate]*/); // ToDo
-		}
-	}
-	// for compatible with old API just do the printk to console
-	//wrq->u.data.length = strlen(msg);
-	//if (copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s", msg));
-	}
-
-	kfree(msg);
-}
-#endif // UCOS //
-
-#ifdef DOT11_N_SUPPORT
-INT	Set_BASetup_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    UCHAR mac[6], tid;
-	char *token, sepValue[] = ":", DASH = '-';
-	INT i;
-    MAC_TABLE_ENTRY *pEntry;
-
-/*
-	The BASetup inupt string format should be xx:xx:xx:xx:xx:xx-d,
-		=>The six 2 digit hex-decimal number previous are the Mac address,
-		=>The seventh decimal number is the tid value.
-*/
-	//printk("\n%s\n", arg);
-
-	if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and tid value in decimal format.
-		return FALSE;
-
-	token = strchr(arg, DASH);
-	if ((token != NULL) && (strlen(token)>1))
-	{
-		tid = simple_strtol((token+1), 0, 10);
-		if (tid > 15)
-			return FALSE;
-
-		*token = '\0';
-		for (i = 0, token = rstrtok(arg, &sepValue[0]); token; token = rstrtok(NULL, &sepValue[0]), i++)
-		{
-			if((strlen(token) != 2) || (!isxdigit(*token)) || (!isxdigit(*(token+1))))
-				return FALSE;
-			AtoH(token, (PUCHAR)(&mac[i]), 1);
-		}
-		if(i != 6)
-			return FALSE;
-
-		printk("\n%02x:%02x:%02x:%02x:%02x:%02x-%02x\n", mac[0], mac[1],
-				mac[2], mac[3], mac[4], mac[5], tid);
-
-	    pEntry = MacTableLookup(pAd, mac);
-
-    	if (pEntry) {
-        	printk("\nSetup BA Session: Tid = %d\n", tid);
-	        BAOriSessionSetUp(pAd, pEntry, tid, 0, 100, TRUE);
-    	}
-
-		return TRUE;
-	}
-
-	return FALSE;
-
-}
-
-INT	Set_BADecline_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG bBADecline;
-
-	bBADecline = simple_strtol(arg, 0, 10);
-
-	if (bBADecline == 0)
-	{
-		pAd->CommonCfg.bBADecline = FALSE;
-	}
-	else if (bBADecline == 1)
-	{
-		pAd->CommonCfg.bBADecline = TRUE;
-	}
-	else
-	{
-		return FALSE; //Invalid argument
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_BADecline_Proc::(BADecline=%d)\n", pAd->CommonCfg.bBADecline));
-
-	return TRUE;
-}
-
-INT	Set_BAOriTearDown_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    UCHAR mac[6], tid;
-	char *token, sepValue[] = ":", DASH = '-';
-	INT i;
-    MAC_TABLE_ENTRY *pEntry;
-
-    //printk("\n%s\n", arg);
-/*
-	The BAOriTearDown inupt string format should be xx:xx:xx:xx:xx:xx-d,
-		=>The six 2 digit hex-decimal number previous are the Mac address,
-		=>The seventh decimal number is the tid value.
-*/
-    if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and tid value in decimal format.
-		return FALSE;
-
-	token = strchr(arg, DASH);
-	if ((token != NULL) && (strlen(token)>1))
-	{
-		tid = simple_strtol((token+1), 0, 10);
-		if (tid > NUM_OF_TID)
-			return FALSE;
-
-		*token = '\0';
-		for (i = 0, token = rstrtok(arg, &sepValue[0]); token; token = rstrtok(NULL, &sepValue[0]), i++)
-		{
-			if((strlen(token) != 2) || (!isxdigit(*token)) || (!isxdigit(*(token+1))))
-				return FALSE;
-			AtoH(token, (PUCHAR)(&mac[i]), 1);
-		}
-		if(i != 6)
-			return FALSE;
-
-	    printk("\n%02x:%02x:%02x:%02x:%02x:%02x-%02x", mac[0], mac[1],
-	           mac[2], mac[3], mac[4], mac[5], tid);
-
-	    pEntry = MacTableLookup(pAd, mac);
-
-	    if (pEntry) {
-	        printk("\nTear down Ori BA Session: Tid = %d\n", tid);
-        BAOriSessionTearDown(pAd, pEntry->Aid, tid, FALSE, TRUE);
-	    }
-
-		return TRUE;
-	}
-
-	return FALSE;
-
-}
-
-INT	Set_BARecTearDown_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    UCHAR mac[6], tid;
-	char *token, sepValue[] = ":", DASH = '-';
-	INT i;
-    MAC_TABLE_ENTRY *pEntry;
-
-    //printk("\n%s\n", arg);
-/*
-	The BARecTearDown inupt string format should be xx:xx:xx:xx:xx:xx-d,
-		=>The six 2 digit hex-decimal number previous are the Mac address,
-		=>The seventh decimal number is the tid value.
-*/
-    if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and tid value in decimal format.
-		return FALSE;
-
-	token = strchr(arg, DASH);
-	if ((token != NULL) && (strlen(token)>1))
-	{
-		tid = simple_strtol((token+1), 0, 10);
-		if (tid > NUM_OF_TID)
-			return FALSE;
-
-		*token = '\0';
-		for (i = 0, token = rstrtok(arg, &sepValue[0]); token; token = rstrtok(NULL, &sepValue[0]), i++)
-		{
-			if((strlen(token) != 2) || (!isxdigit(*token)) || (!isxdigit(*(token+1))))
-				return FALSE;
-			AtoH(token, (PUCHAR)(&mac[i]), 1);
-		}
-		if(i != 6)
-			return FALSE;
-
-		printk("\n%02x:%02x:%02x:%02x:%02x:%02x-%02x", mac[0], mac[1],
-		       mac[2], mac[3], mac[4], mac[5], tid);
-
-		pEntry = MacTableLookup(pAd, mac);
-
-		if (pEntry) {
-		    printk("\nTear down Rec BA Session: Tid = %d\n", tid);
-		    BARecSessionTearDown(pAd, pEntry->Aid, tid, FALSE);
-		}
-
-		return TRUE;
-	}
-
-	return FALSE;
-
-}
-
-INT	Set_HtBw_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG HtBw;
-
-	HtBw = simple_strtol(arg, 0, 10);
-	if (HtBw == BW_40)
-		pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_40;
-	else if (HtBw == BW_20)
-		pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-	else
-		return FALSE;  //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtBw_Proc::(HtBw=%d)\n", pAd->CommonCfg.RegTransmitSetting.field.BW));
-
-	return TRUE;
-}
-
-INT	Set_HtMcs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG HtMcs, Mcs_tmp;
-#ifdef CONFIG_STA_SUPPORT
-    BOOLEAN bAutoRate = FALSE;
-#endif // CONFIG_STA_SUPPORT //
-
-	Mcs_tmp = simple_strtol(arg, 0, 10);
-
-	if (Mcs_tmp <= 15 || Mcs_tmp == 32)
-		HtMcs = Mcs_tmp;
-	else
-		HtMcs = MCS_AUTO;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		pAd->StaCfg.DesiredTransmitSetting.field.MCS = HtMcs;
-		pAd->StaCfg.bAutoTxRateSwitch = (HtMcs == MCS_AUTO) ? TRUE:FALSE;
-		DBGPRINT(RT_DEBUG_TRACE, ("Set_HtMcs_Proc::(HtMcs=%d, bAutoTxRateSwitch = %d)\n",
-						pAd->StaCfg.DesiredTransmitSetting.field.MCS, pAd->StaCfg.bAutoTxRateSwitch));
-
-		if ((pAd->CommonCfg.PhyMode < PHY_11ABGN_MIXED) ||
-			(pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE < MODE_HTMIX))
-		{
-	        if ((pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO) &&
-				(HtMcs >= 0 && HtMcs <= 3) &&
-	            (pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode == FIXED_TXMODE_CCK))
-			{
-				RTMPSetDesiredRates(pAd, (LONG) (RateIdToMbps[HtMcs] * 1000000));
-			}
-	        else if ((pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO) &&
-					(HtMcs >= 0 && HtMcs <= 7) &&
-	            	(pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode == FIXED_TXMODE_OFDM))
-			{
-				RTMPSetDesiredRates(pAd, (LONG) (RateIdToMbps[HtMcs+4] * 1000000));
-			}
-			else
-				bAutoRate = TRUE;
-
-			if (bAutoRate)
-			{
-	            pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-				RTMPSetDesiredRates(pAd, -1);
-			}
-	        DBGPRINT(RT_DEBUG_TRACE, ("Set_HtMcs_Proc::(FixedTxMode=%d)\n",pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode));
-		}
-        if (ADHOC_ON(pAd))
-            return TRUE;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	SetCommonHT(pAd);
-
-	return TRUE;
-}
-
-INT	Set_HtGi_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG HtGi;
-
-	HtGi = simple_strtol(arg, 0, 10);
-
-	if ( HtGi == GI_400)
-		pAd->CommonCfg.RegTransmitSetting.field.ShortGI = GI_400;
-	else if ( HtGi == GI_800 )
-		pAd->CommonCfg.RegTransmitSetting.field.ShortGI = GI_800;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtGi_Proc::(ShortGI=%d)\n",pAd->CommonCfg.RegTransmitSetting.field.ShortGI));
-
-	return TRUE;
-}
-
-
-INT	Set_HtTxBASize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR Size;
-
-	Size = simple_strtol(arg, 0, 10);
-
-	if (Size <=0 || Size >=64)
-	{
-		Size = 8;
-	}
-	pAd->CommonCfg.TxBASize = Size-1;
-	DBGPRINT(RT_DEBUG_ERROR, ("Set_HtTxBASize ::(TxBASize= %d)\n", Size));
-
-	return TRUE;
-}
-
-
-INT	Set_HtOpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value == HTMODE_GF)
-		pAd->CommonCfg.RegTransmitSetting.field.HTMODE  = HTMODE_GF;
-	else if ( Value == HTMODE_MM )
-		pAd->CommonCfg.RegTransmitSetting.field.HTMODE  = HTMODE_MM;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtOpMode_Proc::(HtOpMode=%d)\n",pAd->CommonCfg.RegTransmitSetting.field.HTMODE));
-
-	return TRUE;
-
-}
-
-INT	Set_HtStbc_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value == STBC_USE)
-		pAd->CommonCfg.RegTransmitSetting.field.STBC = STBC_USE;
-	else if ( Value == STBC_NONE )
-		pAd->CommonCfg.RegTransmitSetting.field.STBC = STBC_NONE;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_Stbc_Proc::(HtStbc=%d)\n",pAd->CommonCfg.RegTransmitSetting.field.STBC));
-
-	return TRUE;
-}
-
-INT	Set_HtHtc_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->HTCEnable = FALSE;
-	else if ( Value ==1 )
-        	pAd->HTCEnable = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtHtc_Proc::(HtHtc=%d)\n",pAd->HTCEnable));
-
-	return TRUE;
-}
-
-INT	Set_HtExtcha_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value == 0)
-		pAd->CommonCfg.RegTransmitSetting.field.EXTCHA  = EXTCHA_BELOW;
-	else if ( Value ==1 )
-        pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtExtcha_Proc::(HtExtcha=%d)\n",pAd->CommonCfg.RegTransmitSetting.field.EXTCHA));
-
-	return TRUE;
-}
-
-INT	Set_HtMpduDensity_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value <=7 && Value >= 0)
-		pAd->CommonCfg.BACapability.field.MpduDensity = Value;
-	else
-		pAd->CommonCfg.BACapability.field.MpduDensity = 4;
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtMpduDensity_Proc::(HtMpduDensity=%d)\n",pAd->CommonCfg.BACapability.field.MpduDensity));
-
-	return TRUE;
-}
-
-INT	Set_HtBaWinSize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-
-	if (Value >=1 && Value <= 64)
-	{
-		pAd->CommonCfg.REGBACapability.field.RxBAWinLimit = Value;
-		pAd->CommonCfg.BACapability.field.RxBAWinLimit = Value;
-	}
-	else
-	{
-        pAd->CommonCfg.REGBACapability.field.RxBAWinLimit = 64;
-		pAd->CommonCfg.BACapability.field.RxBAWinLimit = 64;
-	}
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtBaWinSize_Proc::(HtBaWinSize=%d)\n",pAd->CommonCfg.BACapability.field.RxBAWinLimit));
-
-	return TRUE;
-}
-
-INT	Set_HtRdg_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value == 0)
-		pAd->CommonCfg.bRdg = FALSE;
-	else if ( Value ==1 )
-	{
-		pAd->HTCEnable = TRUE;
-        	pAd->CommonCfg.bRdg = TRUE;
-	}
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtRdg_Proc::(HtRdg=%d)\n",pAd->CommonCfg.bRdg));
-
-	return TRUE;
-}
-
-INT	Set_HtLinkAdapt_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->bLinkAdapt = FALSE;
-	else if ( Value ==1 )
-	{
-			pAd->HTCEnable = TRUE;
-			pAd->bLinkAdapt = TRUE;
-	}
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtLinkAdapt_Proc::(HtLinkAdapt=%d)\n",pAd->bLinkAdapt));
-
-	return TRUE;
-}
-
-INT	Set_HtAmsdu_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->CommonCfg.BACapability.field.AmsduEnable = FALSE;
-	else if ( Value == 1 )
-        pAd->CommonCfg.BACapability.field.AmsduEnable = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtAmsdu_Proc::(HtAmsdu=%d)\n",pAd->CommonCfg.BACapability.field.AmsduEnable));
-
-	return TRUE;
-}
-
-INT	Set_HtAutoBa_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->CommonCfg.BACapability.field.AutoBA = FALSE;
-    else if (Value == 1)
-		pAd->CommonCfg.BACapability.field.AutoBA = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-    pAd->CommonCfg.REGBACapability.field.AutoBA = pAd->CommonCfg.BACapability.field.AutoBA;
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtAutoBa_Proc::(HtAutoBa=%d)\n",pAd->CommonCfg.BACapability.field.AutoBA));
-
-	return TRUE;
-
-}
-
-INT	Set_HtProtect_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->CommonCfg.bHTProtect = FALSE;
-    else if (Value == 1)
-		pAd->CommonCfg.bHTProtect = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtProtect_Proc::(HtProtect=%d)\n",pAd->CommonCfg.bHTProtect));
-
-	return TRUE;
-}
-
-INT	Set_SendPSMPAction_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    UCHAR mac[6], mode;
-	char *token, sepValue[] = ":", DASH = '-';
-	INT i;
-    MAC_TABLE_ENTRY *pEntry;
-
-    //printk("\n%s\n", arg);
-/*
-	The BARecTearDown inupt string format should be xx:xx:xx:xx:xx:xx-d,
-		=>The six 2 digit hex-decimal number previous are the Mac address,
-		=>The seventh decimal number is the mode value.
-*/
-    if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and mode value in decimal format.
-		return FALSE;
-
-   	token = strchr(arg, DASH);
-	if ((token != NULL) && (strlen(token)>1))
-	{
-		mode = simple_strtol((token+1), 0, 10);
-		if (mode > MMPS_ENABLE)
-			return FALSE;
-
-		*token = '\0';
-		for (i = 0, token = rstrtok(arg, &sepValue[0]); token; token = rstrtok(NULL, &sepValue[0]), i++)
-		{
-			if((strlen(token) != 2) || (!isxdigit(*token)) || (!isxdigit(*(token+1))))
-				return FALSE;
-			AtoH(token, (PUCHAR)(&mac[i]), 1);
-		}
-		if(i != 6)
-			return FALSE;
-
-		printk("\n%02x:%02x:%02x:%02x:%02x:%02x-%02x", mac[0], mac[1],
-		       mac[2], mac[3], mac[4], mac[5], mode);
-
-		pEntry = MacTableLookup(pAd, mac);
-
-		if (pEntry) {
-		    printk("\nSendPSMPAction MIPS mode = %d\n", mode);
-		    SendPSMPAction(pAd, pEntry->Aid, mode);
-		}
-
-		return TRUE;
-	}
-
-	return FALSE;
-
-
-}
-
-INT	Set_HtMIMOPSmode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value <=3 && Value >= 0)
-		pAd->CommonCfg.BACapability.field.MMPSmode = Value;
-	else
-		pAd->CommonCfg.BACapability.field.MMPSmode = 3;
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtMIMOPSmode_Proc::(MIMOPS mode=%d)\n",pAd->CommonCfg.BACapability.field.MMPSmode));
-
-	return TRUE;
-}
-
-
-INT	Set_ForceShortGI_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->WIFItestbed.bShortGI = FALSE;
-	else if (Value == 1)
-		pAd->WIFItestbed.bShortGI = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_ForceShortGI_Proc::(ForceShortGI=%d)\n", pAd->WIFItestbed.bShortGI));
-
-	return TRUE;
-}
-
-
-
-INT	Set_ForceGF_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->WIFItestbed.bGreenField = FALSE;
-	else if (Value == 1)
-		pAd->WIFItestbed.bGreenField = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_ForceGF_Proc::(ForceGF=%d)\n", pAd->WIFItestbed.bGreenField));
-
-	return TRUE;
-}
-
-INT	Set_HtMimoPs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->CommonCfg.bMIMOPSEnable = FALSE;
-	else if (Value == 1)
-		pAd->CommonCfg.bMIMOPSEnable = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtMimoPs_Proc::(HtMimoPs=%d)\n",pAd->CommonCfg.bMIMOPSEnable));
-
-	return TRUE;
-}
-#endif // DOT11_N_SUPPORT //
-
-
-#ifdef DOT11_N_SUPPORT
-INT	SetCommonHT(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	OID_SET_HT_PHYMODE		SetHT;
-
-	if (pAd->CommonCfg.PhyMode < PHY_11ABGN_MIXED)
-		return FALSE;
-
-	SetHT.PhyMode = pAd->CommonCfg.PhyMode;
-	SetHT.TransmitNo = ((UCHAR)pAd->Antenna.field.TxPath);
-	SetHT.HtMode = (UCHAR)pAd->CommonCfg.RegTransmitSetting.field.HTMODE;
-	SetHT.ExtOffset = (UCHAR)pAd->CommonCfg.RegTransmitSetting.field.EXTCHA;
-	SetHT.MCS = MCS_AUTO;
-	SetHT.BW = (UCHAR)pAd->CommonCfg.RegTransmitSetting.field.BW;
-	SetHT.STBC = (UCHAR)pAd->CommonCfg.RegTransmitSetting.field.STBC;
-	SetHT.SHORTGI = (UCHAR)pAd->CommonCfg.RegTransmitSetting.field.ShortGI;
-
-	RTMPSetHT(pAd, &SetHT);
-
-	return TRUE;
-}
-#endif // DOT11_N_SUPPORT //
-
-INT	Set_FixedTxMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR	fix_tx_mode = FIXED_TXMODE_HT;
-
-	if (strcmp(arg, "OFDM") == 0 || strcmp(arg, "ofdm") == 0)
-	{
-		fix_tx_mode = FIXED_TXMODE_OFDM;
-	}
-	else if (strcmp(arg, "CCK") == 0 || strcmp(arg, "cck") == 0)
-	{
-        fix_tx_mode = FIXED_TXMODE_CCK;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode = fix_tx_mode;
-#endif // CONFIG_STA_SUPPORT //
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_FixedTxMode_Proc::(FixedTxMode=%d)\n", fix_tx_mode));
-
-	return TRUE;
-}
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-INT	Set_OpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-#ifdef RT2870
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP))
-#endif // RT2870 //
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Can not switch operate mode on interface up !! \n"));
-		return FALSE;
-	}
-
-	if (Value == 0)
-		pAd->OpMode = OPMODE_STA;
-	else if (Value == 1)
-		pAd->OpMode = OPMODE_AP;
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_OpMode_Proc::(OpMode=%s)\n", pAd->OpMode == 1 ? "AP Mode" : "STA Mode"));
-
-	return TRUE;
-}
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-
-/////////////////////////////////////////////////////////////////////////
-PCHAR   RTMPGetRalinkAuthModeStr(
-    IN  NDIS_802_11_AUTHENTICATION_MODE authMode)
-{
-	switch(authMode)
-	{
-		case Ndis802_11AuthModeOpen:
-			return "OPEN";
-		case Ndis802_11AuthModeWPAPSK:
-			return "WPAPSK";
-		case Ndis802_11AuthModeShared:
-			return "SHARED";
-		case Ndis802_11AuthModeWPA:
-			return "WPA";
-		case Ndis802_11AuthModeWPA2:
-			return "WPA2";
-		case Ndis802_11AuthModeWPA2PSK:
-			return "WPA2PSK";
-        case Ndis802_11AuthModeWPA1PSKWPA2PSK:
-			return "WPAPSKWPA2PSK";
-        case Ndis802_11AuthModeWPA1WPA2:
-			return "WPA1WPA2";
-		case Ndis802_11AuthModeWPANone:
-			return "WPANONE";
-		default:
-			return "UNKNOW";
-	}
-}
-
-PCHAR   RTMPGetRalinkEncryModeStr(
-    IN  USHORT encryMode)
-{
-	switch(encryMode)
-	{
-		case Ndis802_11WEPDisabled:
-			return "NONE";
-		case Ndis802_11WEPEnabled:
-			return "WEP";
-		case Ndis802_11Encryption2Enabled:
-			return "TKIP";
-		case Ndis802_11Encryption3Enabled:
-			return "AES";
-        case Ndis802_11Encryption4Enabled:
-			return "TKIPAES";
-		default:
-			return "UNKNOW";
-	}
-}
-
-INT RTMPShowCfgValue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pName,
-	IN	PUCHAR			pBuf)
-{
-	INT	Status = 0;
-
-	for (PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC = RTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC; PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name; PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC++)
-	{
-		if (!strcmp(pName, PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name))
-		{
-			if(PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->show_proc(pAd, pBuf))
-				Status = -EINVAL;
-			break;  //Exit for loop.
-		}
-	}
-
-	if(PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name == NULL)
-	{
-		sprintf(pBuf, "\n");
-		for (PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC = RTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC; PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name; PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC++)
-			sprintf(pBuf, "%s%s\n", pBuf, PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name);
-	}
-
-	return Status;
-}
-
-INT	Show_SSID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		sprintf(pBuf, "\t%s", pAd->CommonCfg.Ssid);
-#endif // CONFIG_STA_SUPPORT //
-	return 0;
-}
-
-INT	Show_WirelessMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.PhyMode)
-	{
-		case PHY_11BG_MIXED:
-			sprintf(pBuf, "\t11B/G");
-			break;
-		case PHY_11B:
-			sprintf(pBuf, "\t11B");
-			break;
-		case PHY_11A:
-			sprintf(pBuf, "\t11A");
-			break;
-		case PHY_11ABG_MIXED:
-			sprintf(pBuf, "\t11A/B/G");
-			break;
-		case PHY_11G:
-			sprintf(pBuf, "\t11G");
-			break;
-#ifdef DOT11_N_SUPPORT
-		case PHY_11ABGN_MIXED:
-			sprintf(pBuf, "\t11A/B/G/N");
-			break;
-		case PHY_11N_2_4G:
-			sprintf(pBuf, "\t11N only with 2.4G");
-			break;
-		case PHY_11GN_MIXED:
-			sprintf(pBuf, "\t11G/N");
-			break;
-		case PHY_11AN_MIXED:
-			sprintf(pBuf, "\t11A/N");
-			break;
-		case PHY_11BGN_MIXED:
-			sprintf(pBuf, "\t11B/G/N");
-			break;
-		case PHY_11AGN_MIXED:
-			sprintf(pBuf, "\t11A/G/N");
-			break;
-		case PHY_11N_5G:
-			sprintf(pBuf, "\t11N only with 5G");
-			break;
-#endif // DOT11_N_SUPPORT //
-		default:
-			sprintf(pBuf, "\tUnknow Value(%d)", pAd->CommonCfg.PhyMode);
-			break;
-	}
-	return 0;
-}
-
-
-INT	Show_TxBurst_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.bEnableTxBurst ? "TRUE":"FALSE");
-	return 0;
-}
-
-INT	Show_TxPreamble_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.TxPreamble)
-	{
-		case Rt802_11PreambleShort:
-			sprintf(pBuf, "\tShort");
-			break;
-		case Rt802_11PreambleLong:
-			sprintf(pBuf, "\tLong");
-			break;
-		case Rt802_11PreambleAuto:
-			sprintf(pBuf, "\tAuto");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%lu)", pAd->CommonCfg.TxPreamble);
-			break;
-	}
-
-	return 0;
-}
-
-INT	Show_TxPower_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%lu", pAd->CommonCfg.TxPowerPercentage);
-	return 0;
-}
-
-INT	Show_Channel_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%d", pAd->CommonCfg.Channel);
-	return 0;
-}
-
-INT	Show_BGProtection_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.UseBGProtection)
-	{
-		case 1: //Always On
-			sprintf(pBuf, "\tON");
-			break;
-		case 2: //Always OFF
-			sprintf(pBuf, "\tOFF");
-			break;
-		case 0: //AUTO
-			sprintf(pBuf, "\tAuto");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%lu)", pAd->CommonCfg.UseBGProtection);
-			break;
-	}
-	return 0;
-}
-
-INT	Show_RTSThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%u", pAd->CommonCfg.RtsThreshold);
-	return 0;
-}
-
-INT	Show_FragThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%u", pAd->CommonCfg.FragmentThreshold);
-	return 0;
-}
-
-#ifdef DOT11_N_SUPPORT
-INT	Show_HtBw_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	if (pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40)
-	{
-		sprintf(pBuf, "\t40 MHz");
-	}
-	else
-	{
-        sprintf(pBuf, "\t20 MHz");
-	}
-	return 0;
-}
-
-INT	Show_HtMcs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		sprintf(pBuf, "\t%u", pAd->StaCfg.DesiredTransmitSetting.field.MCS);
-#endif // CONFIG_STA_SUPPORT //
-	return 0;
-}
-
-INT	Show_HtGi_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.RegTransmitSetting.field.ShortGI)
-	{
-		case GI_400:
-			sprintf(pBuf, "\tGI_400");
-			break;
-		case GI_800:
-			sprintf(pBuf, "\tGI_800");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%u)", pAd->CommonCfg.RegTransmitSetting.field.ShortGI);
-			break;
-	}
-	return 0;
-}
-
-INT	Show_HtOpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.RegTransmitSetting.field.HTMODE)
-	{
-		case HTMODE_GF:
-			sprintf(pBuf, "\tGF");
-			break;
-		case HTMODE_MM:
-			sprintf(pBuf, "\tMM");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%u)", pAd->CommonCfg.RegTransmitSetting.field.HTMODE);
-			break;
-	}
-	return 0;
-}
-
-INT	Show_HtExtcha_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.RegTransmitSetting.field.EXTCHA)
-	{
-		case EXTCHA_BELOW:
-			sprintf(pBuf, "\tBelow");
-			break;
-		case EXTCHA_ABOVE:
-			sprintf(pBuf, "\tAbove");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%u)", pAd->CommonCfg.RegTransmitSetting.field.EXTCHA);
-			break;
-	}
-	return 0;
-}
-
-
-INT	Show_HtMpduDensity_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%u", pAd->CommonCfg.BACapability.field.MpduDensity);
-	return 0;
-}
-
-INT	Show_HtBaWinSize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%u", pAd->CommonCfg.BACapability.field.RxBAWinLimit);
-	return 0;
-}
-
-INT	Show_HtRdg_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.bRdg ? "TRUE":"FALSE");
-	return 0;
-}
-
-INT	Show_HtAmsdu_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.BACapability.field.AmsduEnable ? "TRUE":"FALSE");
-	return 0;
-}
-
-INT	Show_HtAutoBa_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.BACapability.field.AutoBA ? "TRUE":"FALSE");
-	return 0;
-}
-#endif // DOT11_N_SUPPORT //
-
-INT	Show_CountryRegion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%d", pAd->CommonCfg.CountryRegion);
-	return 0;
-}
-
-INT	Show_CountryRegionABand_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%d", pAd->CommonCfg.CountryRegionForABand);
-	return 0;
-}
-
-INT	Show_CountryCode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.CountryCode);
-	return 0;
-}
-
-#ifdef AGGREGATION_SUPPORT
-INT	Show_PktAggregate_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.bAggregationCapable ? "TRUE":"FALSE");
-	return 0;
-}
-#endif // AGGREGATION_SUPPORT //
-
-#ifdef WMM_SUPPORT
-INT	Show_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		sprintf(pBuf, "\t%s", pAd->CommonCfg.bWmmCapable ? "TRUE":"FALSE");
-#endif // CONFIG_STA_SUPPORT //
-
-	return 0;
-}
-#endif // WMM_SUPPORT //
-
-INT	Show_IEEE80211H_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.bIEEE80211H ? "TRUE":"FALSE");
-	return 0;
-}
-
-#ifdef CONFIG_STA_SUPPORT
-INT	Show_NetworkType_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->StaCfg.BssType)
-	{
-		case BSS_ADHOC:
-			sprintf(pBuf, "\tAdhoc");
-			break;
-		case BSS_INFRA:
-			sprintf(pBuf, "\tInfra");
-			break;
-		case BSS_ANY:
-			sprintf(pBuf, "\tAny");
-			break;
-		case BSS_MONITOR:
-			sprintf(pBuf, "\tMonitor");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%d)", pAd->StaCfg.BssType);
-			break;
-	}
-	return 0;
-}
-#endif // CONFIG_STA_SUPPORT //
-
-INT	Show_AuthMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	NDIS_802_11_AUTHENTICATION_MODE	AuthMode = Ndis802_11AuthModeOpen;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		AuthMode = pAd->StaCfg.AuthMode;
-#endif // CONFIG_STA_SUPPORT //
-
-	if ((AuthMode >= Ndis802_11AuthModeOpen) &&
-		(AuthMode <= Ndis802_11AuthModeWPA1PSKWPA2PSK))
-		sprintf(pBuf, "\t%s", RTMPGetRalinkAuthModeStr(AuthMode));
-	else
-		sprintf(pBuf, "\tUnknow Value(%d)", AuthMode);
-
-	return 0;
-}
-
-INT	Show_EncrypType_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	NDIS_802_11_WEP_STATUS	WepStatus = Ndis802_11WEPDisabled;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		WepStatus = pAd->StaCfg.WepStatus;
-#endif // CONFIG_STA_SUPPORT //
-
-	if ((WepStatus >= Ndis802_11WEPEnabled) &&
-		(WepStatus <= Ndis802_11Encryption4KeyAbsent))
-		sprintf(pBuf, "\t%s", RTMPGetRalinkEncryModeStr(WepStatus));
-	else
-		sprintf(pBuf, "\tUnknow Value(%d)", WepStatus);
-
-	return 0;
-}
-
-INT	Show_DefaultKeyID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	UCHAR DefaultKeyId = 0;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		DefaultKeyId = pAd->StaCfg.DefaultKeyId;
-#endif // CONFIG_STA_SUPPORT //
-
-	sprintf(pBuf, "\t%d", DefaultKeyId);
-
-	return 0;
-}
-
-INT	Show_WepKey_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  INT				KeyIdx,
-	OUT	PUCHAR			pBuf)
-{
-	UCHAR   Key[16] = {0}, KeyLength = 0;
-	INT		index = BSS0;
-
-	KeyLength = pAd->SharedKey[index][KeyIdx].KeyLen;
-	NdisMoveMemory(Key, pAd->SharedKey[index][KeyIdx].Key, KeyLength);
-
-	//check key string is ASCII or not
-    if (RTMPCheckStrPrintAble(Key, KeyLength))
-        sprintf(pBuf, "\t%s", Key);
-    else
-    {
-        int idx;
-        sprintf(pBuf, "\t");
-        for (idx = 0; idx < KeyLength; idx++)
-            sprintf(pBuf+strlen(pBuf), "%02X", Key[idx]);
-    }
-	return 0;
-}
-
-INT	Show_Key1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	Show_WepKey_Proc(pAd, 0, pBuf);
-	return 0;
-}
-
-INT	Show_Key2_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	Show_WepKey_Proc(pAd, 1, pBuf);
-	return 0;
-}
-
-INT	Show_Key3_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	Show_WepKey_Proc(pAd, 2, pBuf);
-	return 0;
-}
-
-INT	Show_Key4_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	Show_WepKey_Proc(pAd, 3, pBuf);
-	return 0;
-}
-
-INT	Show_WPAPSK_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	INT 	idx;
-	UCHAR	PMK[32] = {0};
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		NdisMoveMemory(PMK, pAd->StaCfg.PMK, 32);
-#endif // CONFIG_STA_SUPPORT //
-
-    sprintf(pBuf, "\tPMK = ");
-    for (idx = 0; idx < 32; idx++)
-        sprintf(pBuf+strlen(pBuf), "%02X", PMK[idx]);
-
-	return 0;
-}
-
+#include "../../rt2860/common/cmm_info.c"
diff --git a/drivers/staging/rt2870/common/cmm_sanity.c b/drivers/staging/rt2870/common/cmm_sanity.c
index 1e24320..cb33521 100644
--- a/drivers/staging/rt2870/common/cmm_sanity.c
+++ b/drivers/staging/rt2870/common/cmm_sanity.c
@@ -1,1663 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	sanity.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang  2004-09-01      add WMM support
-*/
-#include "../rt_config.h"
-
-
-extern UCHAR	CISCO_OUI[];
-
-extern UCHAR	WPA_OUI[];
-extern UCHAR	RSN_OUI[];
-extern UCHAR	WME_INFO_ELEM[];
-extern UCHAR	WME_PARM_ELEM[];
-extern UCHAR	Ccx2QosInfo[];
-extern UCHAR	RALINK_OUI[];
-extern UCHAR	BROADCOM_OUI[];
-extern UCHAR    WPS_OUI[];
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN MlmeAddBAReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2)
-{
-    PMLME_ADDBA_REQ_STRUCT   pInfo;
-
-    pInfo = (MLME_ADDBA_REQ_STRUCT *)Msg;
-
-    if ((MsgLen != sizeof(MLME_ADDBA_REQ_STRUCT)))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeAddBAReqSanity fail - message lenght not correct.\n"));
-        return FALSE;
-    }
-
-    if ((pInfo->Wcid >= MAX_LEN_OF_MAC_TABLE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeAddBAReqSanity fail - The peer Mac is not associated yet.\n"));
-        return FALSE;
-    }
-
-	/*
-    if ((pInfo->BaBufSize > MAX_RX_REORDERBUF) || (pInfo->BaBufSize < 2))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeAddBAReqSanity fail - Rx Reordering buffer too big or too small\n"));
-        return FALSE;
-    }
-	*/
-
-    if ((pInfo->pAddr[0]&0x01) == 0x01)
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeAddBAReqSanity fail - broadcast address not support BA\n"));
-        return FALSE;
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN MlmeDelBAReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen)
-{
-	MLME_DELBA_REQ_STRUCT *pInfo;
-	pInfo = (MLME_DELBA_REQ_STRUCT *)Msg;
-
-    if ((MsgLen != sizeof(MLME_DELBA_REQ_STRUCT)))
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("MlmeDelBAReqSanity fail - message lenght not correct.\n"));
-        return FALSE;
-    }
-
-    if ((pInfo->Wcid >= MAX_LEN_OF_MAC_TABLE))
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("MlmeDelBAReqSanity fail - The peer Mac is not associated yet.\n"));
-        return FALSE;
-    }
-
-    if ((pInfo->TID & 0xf0))
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("MlmeDelBAReqSanity fail - The peer TID is incorrect.\n"));
-        return FALSE;
-    }
-
-	if (NdisEqualMemory(pAd->MacTab.Content[pInfo->Wcid].Addr, pInfo->Addr, MAC_ADDR_LEN) == 0)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("MlmeDelBAReqSanity fail - the peer addr dosen't exist.\n"));
-        return FALSE;
-    }
-
-    return TRUE;
-}
-
-BOOLEAN PeerAddBAReqActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *pMsg,
-    IN ULONG MsgLen,
-	OUT PUCHAR pAddr2)
-{
-	PFRAME_802_11 pFrame = (PFRAME_802_11)pMsg;
-	PFRAME_ADDBA_REQ pAddFrame;
-	pAddFrame = (PFRAME_ADDBA_REQ)(pMsg);
-	if (MsgLen < (sizeof(FRAME_ADDBA_REQ)))
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBAReqActionSanity: ADDBA Request frame length size = %ld incorrect\n", MsgLen));
-		return FALSE;
-	}
-	// we support immediate BA.
-	*(USHORT *)(&pAddFrame->BaParm) = cpu2le16(*(USHORT *)(&pAddFrame->BaParm));
-	pAddFrame->TimeOutValue = cpu2le16(pAddFrame->TimeOutValue);
-	pAddFrame->BaStartSeq.word = cpu2le16(pAddFrame->BaStartSeq.word);
-
-	if (pAddFrame->BaParm.BAPolicy != IMMED_BA)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBAReqActionSanity: ADDBA Request Ba Policy[%d] not support\n", pAddFrame->BaParm.BAPolicy));
-		DBGPRINT(RT_DEBUG_ERROR,("ADDBA Request. tid=%x, Bufsize=%x, AMSDUSupported=%x \n", pAddFrame->BaParm.TID, pAddFrame->BaParm.BufSize, pAddFrame->BaParm.AMSDUSupported));
-		return FALSE;
-	}
-
-	// we support immediate BA.
-	if (pAddFrame->BaParm.TID &0xfff0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBAReqActionSanity: ADDBA Request incorrect TID = %d\n", pAddFrame->BaParm.TID));
-		return FALSE;
-	}
-	COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-	return TRUE;
-}
-
-BOOLEAN PeerAddBARspActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *pMsg,
-    IN ULONG MsgLen)
-{
-	//PFRAME_802_11 pFrame = (PFRAME_802_11)pMsg;
-	PFRAME_ADDBA_RSP pAddFrame;
-
-	pAddFrame = (PFRAME_ADDBA_RSP)(pMsg);
-	if (MsgLen < (sizeof(FRAME_ADDBA_RSP)))
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBARspActionSanity: ADDBA Response frame length size = %ld incorrect\n", MsgLen));
-		return FALSE;
-	}
-	// we support immediate BA.
-	*(USHORT *)(&pAddFrame->BaParm) = cpu2le16(*(USHORT *)(&pAddFrame->BaParm));
-	pAddFrame->StatusCode = cpu2le16(pAddFrame->StatusCode);
-	pAddFrame->TimeOutValue = cpu2le16(pAddFrame->TimeOutValue);
-
-	if (pAddFrame->BaParm.BAPolicy != IMMED_BA)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBAReqActionSanity: ADDBA Response Ba Policy[%d] not support\n", pAddFrame->BaParm.BAPolicy));
-		return FALSE;
-	}
-
-	// we support immediate BA.
-	if (pAddFrame->BaParm.TID &0xfff0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBARspActionSanity: ADDBA Response incorrect TID = %d\n", pAddFrame->BaParm.TID));
-		return FALSE;
-	}
-	return TRUE;
-
-}
-
-BOOLEAN PeerDelBAActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN UCHAR Wcid,
-    IN VOID *pMsg,
-    IN ULONG MsgLen )
-{
-	//PFRAME_802_11 pFrame = (PFRAME_802_11)pMsg;
-	PFRAME_DELBA_REQ  pDelFrame;
-	if (MsgLen != (sizeof(FRAME_DELBA_REQ)))
-		return FALSE;
-
-	if (Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return FALSE;
-
-	pDelFrame = (PFRAME_DELBA_REQ)(pMsg);
-
-	*(USHORT *)(&pDelFrame->DelbaParm) = cpu2le16(*(USHORT *)(&pDelFrame->DelbaParm));
-	pDelFrame->ReasonCode = cpu2le16(pDelFrame->ReasonCode);
-
-	if (pDelFrame->DelbaParm.TID &0xfff0)
-		return FALSE;
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerBeaconAndProbeRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    IN UCHAR  MsgChannel,
-    OUT PUCHAR pAddr2,
-    OUT PUCHAR pBssid,
-    OUT CHAR Ssid[],
-    OUT UCHAR *pSsidLen,
-    OUT UCHAR *pBssType,
-    OUT USHORT *pBeaconPeriod,
-    OUT UCHAR *pChannel,
-    OUT UCHAR *pNewChannel,
-    OUT LARGE_INTEGER *pTimestamp,
-    OUT CF_PARM *pCfParm,
-    OUT USHORT *pAtimWin,
-    OUT USHORT *pCapabilityInfo,
-    OUT UCHAR *pErp,
-    OUT UCHAR *pDtimCount,
-    OUT UCHAR *pDtimPeriod,
-    OUT UCHAR *pBcastFlag,
-    OUT UCHAR *pMessageToMe,
-    OUT UCHAR SupRate[],
-    OUT UCHAR *pSupRateLen,
-    OUT UCHAR ExtRate[],
-    OUT UCHAR *pExtRateLen,
-    OUT	UCHAR *pCkipFlag,
-    OUT	UCHAR *pAironetCellPowerLimit,
-    OUT PEDCA_PARM       pEdcaParm,
-    OUT PQBSS_LOAD_PARM  pQbssLoad,
-    OUT PQOS_CAPABILITY_PARM pQosCapability,
-    OUT ULONG *pRalinkIe,
-    OUT UCHAR		 *pHtCapabilityLen,
-#ifdef CONFIG_STA_SUPPORT
-    OUT UCHAR		 *pPreNHtCapabilityLen,
-#endif // CONFIG_STA_SUPPORT //
-    OUT HT_CAPABILITY_IE *pHtCapability,
-	OUT UCHAR		 *AddHtInfoLen,
-	OUT ADD_HT_INFO_IE *AddHtInfo,
-	OUT UCHAR *NewExtChannelOffset,		// Ht extension channel offset(above or below)
-    OUT USHORT *LengthVIE,
-    OUT	PNDIS_802_11_VARIABLE_IEs pVIE)
-{
-    CHAR				*Ptr;
-#ifdef CONFIG_STA_SUPPORT
-	CHAR 				TimLen;
-#endif // CONFIG_STA_SUPPORT //
-    PFRAME_802_11		pFrame;
-    PEID_STRUCT         pEid;
-    UCHAR				SubType;
-    UCHAR				Sanity;
-    //UCHAR				ECWMin, ECWMax;
-    //MAC_CSR9_STRUC		Csr9;
-    ULONG				Length = 0;
-
-	// For some 11a AP which didn't have DS_IE, we use two conditions to decide the channel
-	//	1. If the AP is 11n enabled, then check the control channel.
-	//	2. If the AP didn't have any info about channel, use the channel we received this frame as the channel. (May inaccuracy!!)
-	UCHAR			CtrlChannel = 0;
-
-    // Add for 3 necessary EID field check
-    Sanity = 0;
-
-    *pAtimWin = 0;
-    *pErp = 0;
-    *pDtimCount = 0;
-    *pDtimPeriod = 0;
-    *pBcastFlag = 0;
-    *pMessageToMe = 0;
-    *pExtRateLen = 0;
-    *pCkipFlag = 0;			        // Default of CkipFlag is 0
-    *pAironetCellPowerLimit = 0xFF;  // Default of AironetCellPowerLimit is 0xFF
-    *LengthVIE = 0;					// Set the length of VIE to init value 0
-    *pHtCapabilityLen = 0;					// Set the length of VIE to init value 0
-#ifdef CONFIG_STA_SUPPORT
-	if (pAd->OpMode == OPMODE_STA)
-		*pPreNHtCapabilityLen = 0;					// Set the length of VIE to init value 0
-#endif // CONFIG_STA_SUPPORT //
-    *AddHtInfoLen = 0;					// Set the length of VIE to init value 0
-    *pRalinkIe = 0;
-    *pNewChannel = 0;
-    *NewExtChannelOffset = 0xff;	//Default 0xff means no such IE
-    pCfParm->bValid = FALSE;        // default: no IE_CF found
-    pQbssLoad->bValid = FALSE;      // default: no IE_QBSS_LOAD found
-    pEdcaParm->bValid = FALSE;      // default: no IE_EDCA_PARAMETER found
-    pQosCapability->bValid = FALSE; // default: no IE_QOS_CAPABILITY found
-
-    pFrame = (PFRAME_802_11)Msg;
-
-    // get subtype from header
-    SubType = (UCHAR)pFrame->Hdr.FC.SubType;
-
-    // get Addr2 and BSSID from header
-    COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-    COPY_MAC_ADDR(pBssid, pFrame->Hdr.Addr3);
-
-//	hex_dump("Beacon", Msg, MsgLen);
-
-    Ptr = pFrame->Octet;
-    Length += LENGTH_802_11;
-
-    // get timestamp from payload and advance the pointer
-    NdisMoveMemory(pTimestamp, Ptr, TIMESTAMP_LEN);
-
-	pTimestamp->u.LowPart = cpu2le32(pTimestamp->u.LowPart);
-	pTimestamp->u.HighPart = cpu2le32(pTimestamp->u.HighPart);
-
-    Ptr += TIMESTAMP_LEN;
-    Length += TIMESTAMP_LEN;
-
-    // get beacon interval from payload and advance the pointer
-    NdisMoveMemory(pBeaconPeriod, Ptr, 2);
-    Ptr += 2;
-    Length += 2;
-
-    // get capability info from payload and advance the pointer
-    NdisMoveMemory(pCapabilityInfo, Ptr, 2);
-    Ptr += 2;
-    Length += 2;
-
-    if (CAP_IS_ESS_ON(*pCapabilityInfo))
-        *pBssType = BSS_INFRA;
-    else
-        *pBssType = BSS_ADHOC;
-
-    pEid = (PEID_STRUCT) Ptr;
-
-    // get variable fields from payload and advance the pointer
-    while ((Length + 2 + pEid->Len) <= MsgLen)
-    {
-        //
-        // Secure copy VIE to VarIE[MAX_VIE_LEN] didn't overflow.
-        //
-        if ((*LengthVIE + pEid->Len + 2) >= MAX_VIE_LEN)
-        {
-            DBGPRINT(RT_DEBUG_WARN, ("PeerBeaconAndProbeRspSanity - Variable IEs out of resource [len(=%d) > MAX_VIE_LEN(=%d)]\n",
-                    (*LengthVIE + pEid->Len + 2), MAX_VIE_LEN));
-            break;
-        }
-
-        switch(pEid->Eid)
-        {
-            case IE_SSID:
-                // Already has one SSID EID in this beacon, ignore the second one
-                if (Sanity & 0x1)
-                    break;
-                if(pEid->Len <= MAX_LEN_OF_SSID)
-                {
-                    NdisMoveMemory(Ssid, pEid->Octet, pEid->Len);
-                    *pSsidLen = pEid->Len;
-                    Sanity |= 0x1;
-                }
-                else
-                {
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_SSID (len=%d)\n",pEid->Len));
-                    return FALSE;
-                }
-                break;
-
-            case IE_SUPP_RATES:
-                if(pEid->Len <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    Sanity |= 0x2;
-                    NdisMoveMemory(SupRate, pEid->Octet, pEid->Len);
-                    *pSupRateLen = pEid->Len;
-
-                    // TODO: 2004-09-14 not a good design here, cause it exclude extra rates
-                    // from ScanTab. We should report as is. And filter out unsupported
-                    // rates in MlmeAux.
-                    // Check against the supported rates
-                    // RTMPCheckRates(pAd, SupRate, pSupRateLen);
-                }
-                else
-                {
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_SUPP_RATES (len=%d)\n",pEid->Len));
-                    return FALSE;
-                }
-                break;
-
-            case IE_HT_CAP:
-			if (pEid->Len >= SIZE_HT_CAP_IE)  //Note: allow extension.!!
-			{
-				NdisMoveMemory(pHtCapability, pEid->Octet, sizeof(HT_CAPABILITY_IE));
-				*pHtCapabilityLen = SIZE_HT_CAP_IE;	// Nnow we only support 26 bytes.
-
-				*(USHORT *)(&pHtCapability->HtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->HtCapInfo));
-				*(USHORT *)(&pHtCapability->ExtHtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->ExtHtCapInfo));
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-					*pPreNHtCapabilityLen = 0;	// Nnow we only support 26 bytes.
-
-					Ptr = (PUCHAR) pVIE;
-					NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
-					*LengthVIE += (pEid->Len + 2);
-				}
-#endif // CONFIG_STA_SUPPORT //
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerBeaconAndProbeRspSanity - wrong IE_HT_CAP. pEid->Len = %d\n", pEid->Len));
-			}
-
-		break;
-            case IE_ADD_HT:
-			if (pEid->Len >= sizeof(ADD_HT_INFO_IE))
-			{
-				// This IE allows extension, but we can ignore extra bytes beyond our knowledge , so only
-				// copy first sizeof(ADD_HT_INFO_IE)
-				NdisMoveMemory(AddHtInfo, pEid->Octet, sizeof(ADD_HT_INFO_IE));
-				*AddHtInfoLen = SIZE_ADD_HT_INFO_IE;
-
-				CtrlChannel = AddHtInfo->ControlChan;
-
-				*(USHORT *)(&AddHtInfo->AddHtInfo2) = cpu2le16(*(USHORT *)(&AddHtInfo->AddHtInfo2));
-				*(USHORT *)(&AddHtInfo->AddHtInfo3) = cpu2le16(*(USHORT *)(&AddHtInfo->AddHtInfo3));
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-			                Ptr = (PUCHAR) pVIE;
-			                NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
-			                *LengthVIE += (pEid->Len + 2);
-				}
-#endif // CONFIG_STA_SUPPORT //
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerBeaconAndProbeRspSanity - wrong IE_ADD_HT. \n"));
-			}
-
-		break;
-            case IE_SECONDARY_CH_OFFSET:
-			if (pEid->Len == 1)
-			{
-				*NewExtChannelOffset = pEid->Octet[0];
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerBeaconAndProbeRspSanity - wrong IE_SECONDARY_CH_OFFSET. \n"));
-			}
-
-		break;
-            case IE_FH_PARM:
-                DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity(IE_FH_PARM) \n"));
-                break;
-
-            case IE_DS_PARM:
-                if(pEid->Len == 1)
-                {
-                    *pChannel = *pEid->Octet;
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-					{
-						if (ChannelSanity(pAd, *pChannel) == 0)
-						{
-
-							return FALSE;
-						}
-					}
-#endif // CONFIG_STA_SUPPORT //
-                    Sanity |= 0x4;
-                }
-                else
-                {
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_DS_PARM (len=%d)\n",pEid->Len));
-                    return FALSE;
-                }
-                break;
-
-            case IE_CF_PARM:
-                if(pEid->Len == 6)
-                {
-                    pCfParm->bValid = TRUE;
-                    pCfParm->CfpCount = pEid->Octet[0];
-                    pCfParm->CfpPeriod = pEid->Octet[1];
-                    pCfParm->CfpMaxDuration = pEid->Octet[2] + 256 * pEid->Octet[3];
-                    pCfParm->CfpDurRemaining = pEid->Octet[4] + 256 * pEid->Octet[5];
-                }
-                else
-                {
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_CF_PARM\n"));
-                    return FALSE;
-                }
-                break;
-
-            case IE_IBSS_PARM:
-                if(pEid->Len == 2)
-                {
-                    NdisMoveMemory(pAtimWin, pEid->Octet, pEid->Len);
-                }
-                else
-                {
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_IBSS_PARM\n"));
-                    return FALSE;
-                }
-                break;
-
-#ifdef CONFIG_STA_SUPPORT
-            case IE_TIM:
-                if(INFRA_ON(pAd) && SubType == SUBTYPE_BEACON)
-                {
-                    GetTimBit((PUCHAR)pEid, pAd->StaActive.Aid, &TimLen, pBcastFlag, pDtimCount, pDtimPeriod, pMessageToMe);
-                }
-                break;
-#endif // CONFIG_STA_SUPPORT //
-            case IE_CHANNEL_SWITCH_ANNOUNCEMENT:
-                if(pEid->Len == 3)
-                {
-                	*pNewChannel = pEid->Octet[1];	//extract new channel number
-                }
-                break;
-
-            // New for WPA
-            // CCX v2 has the same IE, we need to parse that too
-            // Wifi WMM use the same IE vale, need to parse that too
-            // case IE_WPA:
-            case IE_VENDOR_SPECIFIC:
-                // Check Broadcom/Atheros 802.11n OUI version, for HT Capability IE.
-                // This HT IE is before IEEE draft set HT IE value.2006-09-28 by Jan.
-                /*if (NdisEqualMemory(pEid->Octet, BROADCOM_OUI, 3) && (pEid->Len >= 4))
-                {
-                	if ((pEid->Octet[3] == OUI_BROADCOM_HT) && (pEid->Len >= 30))
-            		{
-				{
-					NdisMoveMemory(pHtCapability, &pEid->Octet[4], sizeof(HT_CAPABILITY_IE));
-					*pHtCapabilityLen = SIZE_HT_CAP_IE;	// Nnow we only support 26 bytes.
-				}
-         		}
-                	if ((pEid->Octet[3] == OUI_BROADCOM_HT) && (pEid->Len >= 26))
-            		{
-				{
-					NdisMoveMemory(AddHtInfo, &pEid->Octet[4], sizeof(ADD_HT_INFO_IE));
-					*AddHtInfoLen = SIZE_ADD_HT_INFO_IE;	// Nnow we only support 26 bytes.
-				}
-         		}
-                }
-				*/
-                // Check the OUI version, filter out non-standard usage
-                if (NdisEqualMemory(pEid->Octet, RALINK_OUI, 3) && (pEid->Len == 7))
-                {
-                    //*pRalinkIe = pEid->Octet[3];
-                    if (pEid->Octet[3] != 0)
-        				*pRalinkIe = pEid->Octet[3];
-        			else
-        				*pRalinkIe = 0xf0000000; // Set to non-zero value (can't set bit0-2) to represent this is Ralink Chip. So at linkup, we will set ralinkchip flag.
-                }
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
-		// This HT IE is before IEEE draft set HT IE value.2006-09-28 by Jan.
-
-                // Other vendors had production before IE_HT_CAP value is assigned. To backward support those old-firmware AP,
-                // Check broadcom-defiend pre-802.11nD1.0 OUI for HT related IE, including HT Capatilities IE and HT Information IE
-                else if ((*pHtCapabilityLen == 0) && NdisEqualMemory(pEid->Octet, PRE_N_HT_OUI, 3) && (pEid->Len >= 4) && (pAd->OpMode == OPMODE_STA))
-                {
-                    if ((pEid->Octet[3] == OUI_PREN_HT_CAP) && (pEid->Len >= 30) && (*pHtCapabilityLen == 0))
-                    {
-                        NdisMoveMemory(pHtCapability, &pEid->Octet[4], sizeof(HT_CAPABILITY_IE));
-                        *pPreNHtCapabilityLen = SIZE_HT_CAP_IE;
-                    }
-
-                    if ((pEid->Octet[3] == OUI_PREN_ADD_HT) && (pEid->Len >= 26))
-                    {
-                        NdisMoveMemory(AddHtInfo, &pEid->Octet[4], sizeof(ADD_HT_INFO_IE));
-                        *AddHtInfoLen = SIZE_ADD_HT_INFO_IE;
-                    }
-                }
-#endif // DOT11_N_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-                else if (NdisEqualMemory(pEid->Octet, WPA_OUI, 4))
-                {
-                    // Copy to pVIE which will report to microsoft bssid list.
-                    Ptr = (PUCHAR) pVIE;
-                    NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
-                    *LengthVIE += (pEid->Len + 2);
-                }
-                else if (NdisEqualMemory(pEid->Octet, WME_PARM_ELEM, 6) && (pEid->Len == 24))
-                {
-                    PUCHAR ptr;
-                    int i;
-
-                    // parsing EDCA parameters
-                    pEdcaParm->bValid          = TRUE;
-                    pEdcaParm->bQAck           = FALSE; // pEid->Octet[0] & 0x10;
-                    pEdcaParm->bQueueRequest   = FALSE; // pEid->Octet[0] & 0x20;
-                    pEdcaParm->bTxopRequest    = FALSE; // pEid->Octet[0] & 0x40;
-                    pEdcaParm->EdcaUpdateCount = pEid->Octet[6] & 0x0f;
-                    pEdcaParm->bAPSDCapable    = (pEid->Octet[6] & 0x80) ? 1 : 0;
-                    ptr = &pEid->Octet[8];
-                    for (i=0; i<4; i++)
-                    {
-                        UCHAR aci = (*ptr & 0x60) >> 5; // b5~6 is AC INDEX
-                        pEdcaParm->bACM[aci]  = (((*ptr) & 0x10) == 0x10);   // b5 is ACM
-                        pEdcaParm->Aifsn[aci] = (*ptr) & 0x0f;               // b0~3 is AIFSN
-                        pEdcaParm->Cwmin[aci] = *(ptr+1) & 0x0f;             // b0~4 is Cwmin
-                        pEdcaParm->Cwmax[aci] = *(ptr+1) >> 4;               // b5~8 is Cwmax
-                        pEdcaParm->Txop[aci]  = *(ptr+2) + 256 * (*(ptr+3)); // in unit of 32-us
-                        ptr += 4; // point to next AC
-                    }
-                }
-                else if (NdisEqualMemory(pEid->Octet, WME_INFO_ELEM, 6) && (pEid->Len == 7))
-                {
-                    // parsing EDCA parameters
-                    pEdcaParm->bValid          = TRUE;
-                    pEdcaParm->bQAck           = FALSE; // pEid->Octet[0] & 0x10;
-                    pEdcaParm->bQueueRequest   = FALSE; // pEid->Octet[0] & 0x20;
-                    pEdcaParm->bTxopRequest    = FALSE; // pEid->Octet[0] & 0x40;
-                    pEdcaParm->EdcaUpdateCount = pEid->Octet[6] & 0x0f;
-                    pEdcaParm->bAPSDCapable    = (pEid->Octet[6] & 0x80) ? 1 : 0;
-
-                    // use default EDCA parameter
-                    pEdcaParm->bACM[QID_AC_BE]  = 0;
-                    pEdcaParm->Aifsn[QID_AC_BE] = 3;
-                    pEdcaParm->Cwmin[QID_AC_BE] = CW_MIN_IN_BITS;
-                    pEdcaParm->Cwmax[QID_AC_BE] = CW_MAX_IN_BITS;
-                    pEdcaParm->Txop[QID_AC_BE]  = 0;
-
-                    pEdcaParm->bACM[QID_AC_BK]  = 0;
-                    pEdcaParm->Aifsn[QID_AC_BK] = 7;
-                    pEdcaParm->Cwmin[QID_AC_BK] = CW_MIN_IN_BITS;
-                    pEdcaParm->Cwmax[QID_AC_BK] = CW_MAX_IN_BITS;
-                    pEdcaParm->Txop[QID_AC_BK]  = 0;
-
-                    pEdcaParm->bACM[QID_AC_VI]  = 0;
-                    pEdcaParm->Aifsn[QID_AC_VI] = 2;
-                    pEdcaParm->Cwmin[QID_AC_VI] = CW_MIN_IN_BITS-1;
-                    pEdcaParm->Cwmax[QID_AC_VI] = CW_MAX_IN_BITS;
-                    pEdcaParm->Txop[QID_AC_VI]  = 96;   // AC_VI: 96*32us ~= 3ms
-
-                    pEdcaParm->bACM[QID_AC_VO]  = 0;
-                    pEdcaParm->Aifsn[QID_AC_VO] = 2;
-                    pEdcaParm->Cwmin[QID_AC_VO] = CW_MIN_IN_BITS-2;
-                    pEdcaParm->Cwmax[QID_AC_VO] = CW_MAX_IN_BITS-1;
-                    pEdcaParm->Txop[QID_AC_VO]  = 48;   // AC_VO: 48*32us ~= 1.5ms
-                }
-                break;
-
-            case IE_EXT_SUPP_RATES:
-                if (pEid->Len <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    NdisMoveMemory(ExtRate, pEid->Octet, pEid->Len);
-                    *pExtRateLen = pEid->Len;
-
-                    // TODO: 2004-09-14 not a good design here, cause it exclude extra rates
-                    // from ScanTab. We should report as is. And filter out unsupported
-                    // rates in MlmeAux.
-                    // Check against the supported rates
-                    // RTMPCheckRates(pAd, ExtRate, pExtRateLen);
-                }
-                break;
-
-            case IE_ERP:
-                if (pEid->Len == 1)
-                {
-                    *pErp = (UCHAR)pEid->Octet[0];
-                }
-                break;
-
-            case IE_AIRONET_CKIP:
-                // 0. Check Aironet IE length, it must be larger or equal to 28
-                // Cisco AP350 used length as 28
-                // Cisco AP12XX used length as 30
-                if (pEid->Len < (CKIP_NEGOTIATION_LENGTH - 2))
-                    break;
-
-                // 1. Copy CKIP flag byte to buffer for process
-                *pCkipFlag = *(pEid->Octet + 8);
-                break;
-
-            case IE_AP_TX_POWER:
-                // AP Control of Client Transmit Power
-                //0. Check Aironet IE length, it must be 6
-                if (pEid->Len != 0x06)
-                    break;
-
-                // Get cell power limit in dBm
-                if (NdisEqualMemory(pEid->Octet, CISCO_OUI, 3) == 1)
-                    *pAironetCellPowerLimit = *(pEid->Octet + 4);
-                break;
-
-            // WPA2 & 802.11i RSN
-            case IE_RSN:
-                // There is no OUI for version anymore, check the group cipher OUI before copying
-                if (RTMPEqualMemory(pEid->Octet + 2, RSN_OUI, 3))
-                {
-                    // Copy to pVIE which will report to microsoft bssid list.
-                    Ptr = (PUCHAR) pVIE;
-                    NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
-                    *LengthVIE += (pEid->Len + 2);
-                }
-                break;
-#ifdef CONFIG_STA_SUPPORT
-#ifdef EXT_BUILD_CHANNEL_LIST
-			case IE_COUNTRY:
-				Ptr = (PUCHAR) pVIE;
-                NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
-                *LengthVIE += (pEid->Len + 2);
-				break;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
-            default:
-                break;
-        }
-
-        Length = Length + 2 + pEid->Len;  // Eid[1] + Len[1]+ content[Len]
-        pEid = (PEID_STRUCT)((UCHAR*)pEid + 2 + pEid->Len);
-    }
-
-    // For some 11a AP. it did not have the channel EID, patch here
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		UCHAR LatchRfChannel = MsgChannel;
-		if ((pAd->LatchRfRegs.Channel > 14) && ((Sanity & 0x4) == 0))
-		{
-			if (CtrlChannel != 0)
-				*pChannel = CtrlChannel;
-			else
-				*pChannel = LatchRfChannel;
-			Sanity |= 0x4;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	if (Sanity != 0x7)
-	{
-		DBGPRINT(RT_DEBUG_WARN, ("PeerBeaconAndProbeRspSanity - missing field, Sanity=0x%02x\n", Sanity));
-		return FALSE;
-	}
-	else
-	{
-		return TRUE;
-	}
-
-}
-
-#ifdef DOT11N_DRAFT3
-/*
-	==========================================================================
-	Description:
-		MLME message sanity check for some IE addressed  in 802.11n d3.03.
-	Return:
-		TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-BOOLEAN PeerBeaconAndProbeRspSanity2(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *Msg,
-	IN ULONG MsgLen,
-	OUT UCHAR 	*RegClass)
-{
-	CHAR				*Ptr;
-	PFRAME_802_11		pFrame;
-	PEID_STRUCT			pEid;
-	ULONG				Length = 0;
-
-	pFrame = (PFRAME_802_11)Msg;
-
-	*RegClass = 0;
-	Ptr = pFrame->Octet;
-	Length += LENGTH_802_11;
-
-	// get timestamp from payload and advance the pointer
-	Ptr += TIMESTAMP_LEN;
-	Length += TIMESTAMP_LEN;
-
-	// get beacon interval from payload and advance the pointer
-	Ptr += 2;
-	Length += 2;
-
-	// get capability info from payload and advance the pointer
-	Ptr += 2;
-	Length += 2;
-
-	pEid = (PEID_STRUCT) Ptr;
-
-	// get variable fields from payload and advance the pointer
-	while ((Length + 2 + pEid->Len) <= MsgLen)
-	{
-		switch(pEid->Eid)
-		{
-			case IE_SUPP_REG_CLASS:
-				if(pEid->Len > 0)
-				{
-					*RegClass = *pEid->Octet;
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_SSID (len=%d)\n",pEid->Len));
-					return FALSE;
-				}
-				break;
-		}
-
-		Length = Length + 2 + pEid->Len;  // Eid[1] + Len[1]+ content[Len]
-		pEid = (PEID_STRUCT)((UCHAR*)pEid + 2 + pEid->Len);
-	}
-
-	return TRUE;
-
-}
-#endif // DOT11N_DRAFT3 //
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
- */
-BOOLEAN MlmeScanReqSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *Msg,
-	IN ULONG MsgLen,
-	OUT UCHAR *pBssType,
-	OUT CHAR Ssid[],
-	OUT UCHAR *pSsidLen,
-	OUT UCHAR *pScanType)
-{
-	MLME_SCAN_REQ_STRUCT *Info;
-
-	Info = (MLME_SCAN_REQ_STRUCT *)(Msg);
-	*pBssType = Info->BssType;
-	*pSsidLen = Info->SsidLen;
-	NdisMoveMemory(Ssid, Info->Ssid, *pSsidLen);
-	*pScanType = Info->ScanType;
-
-	if ((*pBssType == BSS_INFRA || *pBssType == BSS_ADHOC || *pBssType == BSS_ANY)
-		&& (*pScanType == SCAN_ACTIVE || *pScanType == SCAN_PASSIVE
-#ifdef CONFIG_STA_SUPPORT
-		|| *pScanType == SCAN_CISCO_PASSIVE || *pScanType == SCAN_CISCO_ACTIVE
-		|| *pScanType == SCAN_CISCO_CHANNEL_LOAD || *pScanType == SCAN_CISCO_NOISE
-#endif // CONFIG_STA_SUPPORT //
-		))
-	{
-		return TRUE;
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("MlmeScanReqSanity fail - wrong BssType or ScanType\n"));
-		return FALSE;
-	}
-}
-
-// IRQL = DISPATCH_LEVEL
-UCHAR ChannelSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN UCHAR channel)
-{
-    int i;
-
-    for (i = 0; i < pAd->ChannelListNum; i ++)
-    {
-        if (channel == pAd->ChannelList[i].Channel)
-            return 1;
-    }
-    return 0;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerDeauthSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *pReason)
-{
-    PFRAME_802_11 pFrame = (PFRAME_802_11)Msg;
-
-    COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-    NdisMoveMemory(pReason, &pFrame->Octet[0], 2);
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerAuthSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr,
-    OUT USHORT *pAlg,
-    OUT USHORT *pSeq,
-    OUT USHORT *pStatus,
-    CHAR *pChlgText)
-{
-    PFRAME_802_11 pFrame = (PFRAME_802_11)Msg;
-
-    COPY_MAC_ADDR(pAddr,   pFrame->Hdr.Addr2);
-    NdisMoveMemory(pAlg,    &pFrame->Octet[0], 2);
-    NdisMoveMemory(pSeq,    &pFrame->Octet[2], 2);
-    NdisMoveMemory(pStatus, &pFrame->Octet[4], 2);
-
-    if ((*pAlg == Ndis802_11AuthModeOpen)
-#ifdef LEAP_SUPPORT
-      || (*pAlg == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
-      )
-    {
-        if (*pSeq == 1 || *pSeq == 2)
-        {
-            return TRUE;
-        }
-        else
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("PeerAuthSanity fail - wrong Seg#\n"));
-            return FALSE;
-        }
-    }
-    else if (*pAlg == Ndis802_11AuthModeShared)
-    {
-        if (*pSeq == 1 || *pSeq == 4)
-        {
-            return TRUE;
-        }
-        else if (*pSeq == 2 || *pSeq == 3)
-        {
-            NdisMoveMemory(pChlgText, &pFrame->Octet[8], CIPHER_TEXT_LEN);
-            return TRUE;
-        }
-        else
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("PeerAuthSanity fail - wrong Seg#\n"));
-            return FALSE;
-        }
-    }
-    else
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("PeerAuthSanity fail - wrong algorithm\n"));
-        return FALSE;
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
- */
-BOOLEAN MlmeAuthReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr,
-    OUT ULONG *pTimeout,
-    OUT USHORT *pAlg)
-{
-    MLME_AUTH_REQ_STRUCT *pInfo;
-
-    pInfo  = (MLME_AUTH_REQ_STRUCT *)Msg;
-    COPY_MAC_ADDR(pAddr, pInfo->Addr);
-    *pTimeout = pInfo->Timeout;
-    *pAlg = pInfo->Alg;
-
-    if (((*pAlg == Ndis802_11AuthModeShared) ||(*pAlg == Ndis802_11AuthModeOpen)
-#ifdef LEAP_SUPPORT
-     || (*pAlg == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
-     	) &&
-        ((*pAddr & 0x01) == 0))
-    {
-        return TRUE;
-    }
-    else
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeAuthReqSanity fail - wrong algorithm\n"));
-        return FALSE;
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN MlmeAssocReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pApAddr,
-    OUT USHORT *pCapabilityInfo,
-    OUT ULONG *pTimeout,
-    OUT USHORT *pListenIntv)
-{
-    MLME_ASSOC_REQ_STRUCT *pInfo;
-
-    pInfo = (MLME_ASSOC_REQ_STRUCT *)Msg;
-    *pTimeout = pInfo->Timeout;                             // timeout
-    COPY_MAC_ADDR(pApAddr, pInfo->Addr);                   // AP address
-    *pCapabilityInfo = pInfo->CapabilityInfo;               // capability info
-    *pListenIntv = pInfo->ListenIntv;
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerDisassocSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *pReason)
-{
-    PFRAME_802_11 pFrame = (PFRAME_802_11)Msg;
-
-    COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-    NdisMoveMemory(pReason, &pFrame->Octet[0], 2);
-
-    return TRUE;
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Sanity check NetworkType (11b, 11g or 11a)
-
-	Arguments:
-		pBss - Pointer to BSS table.
-
-	Return Value:
-        Ndis802_11DS .......(11b)
-        Ndis802_11OFDM24....(11g)
-        Ndis802_11OFDM5.....(11a)
-
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-NDIS_802_11_NETWORK_TYPE NetworkTypeInUseSanity(
-    IN PBSS_ENTRY pBss)
-{
-	NDIS_802_11_NETWORK_TYPE	NetWorkType;
-	UCHAR						rate, i;
-
-	NetWorkType = Ndis802_11DS;
-
-	if (pBss->Channel <= 14)
-	{
-		//
-		// First check support Rate.
-		//
-		for (i = 0; i < pBss->SupRateLen; i++)
-		{
-			rate = pBss->SupRate[i] & 0x7f; // Mask out basic rate set bit
-			if ((rate == 2) || (rate == 4) || (rate == 11) || (rate == 22))
-			{
-				continue;
-			}
-			else
-			{
-				//
-				// Otherwise (even rate > 108) means Ndis802_11OFDM24
-				//
-				NetWorkType = Ndis802_11OFDM24;
-				break;
-			}
-		}
-
-		//
-		// Second check Extend Rate.
-		//
-		if (NetWorkType != Ndis802_11OFDM24)
-		{
-			for (i = 0; i < pBss->ExtRateLen; i++)
-			{
-				rate = pBss->SupRate[i] & 0x7f; // Mask out basic rate set bit
-				if ((rate == 2) || (rate == 4) || (rate == 11) || (rate == 22))
-				{
-					continue;
-				}
-				else
-				{
-					//
-					// Otherwise (even rate > 108) means Ndis802_11OFDM24
-					//
-					NetWorkType = Ndis802_11OFDM24;
-					break;
-				}
-			}
-		}
-	}
-	else
-	{
-		NetWorkType = Ndis802_11OFDM5;
-	}
-
-    if (pBss->HtCapabilityLen != 0)
-    {
-        if (NetWorkType == Ndis802_11OFDM5)
-            NetWorkType = Ndis802_11OFDM5_N;
-        else
-            NetWorkType = Ndis802_11OFDM24_N;
-    }
-
-	return NetWorkType;
-}
-
-/*
-    ==========================================================================
-    Description:
-        WPA message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
- */
-BOOLEAN PeerWpaMessageSanity(
-    IN 	PRTMP_ADAPTER 		pAd,
-    IN 	PEAPOL_PACKET 		pMsg,
-    IN 	ULONG 				MsgLen,
-    IN 	UCHAR				MsgType,
-    IN 	MAC_TABLE_ENTRY  	*pEntry)
-{
-	UCHAR			mic[LEN_KEY_DESC_MIC], digest[80], KEYDATA[MAX_LEN_OF_RSNIE];
-	BOOLEAN			bReplayDiff = FALSE;
-	BOOLEAN			bWPA2 = FALSE;
-	KEY_INFO		EapolKeyInfo;
-	UCHAR			GroupKeyIndex = 0;
-
-
-	NdisZeroMemory(mic, sizeof(mic));
-	NdisZeroMemory(digest, sizeof(digest));
-	NdisZeroMemory(KEYDATA, sizeof(KEYDATA));
-	NdisZeroMemory((PUCHAR)&EapolKeyInfo, sizeof(EapolKeyInfo));
-
-	NdisMoveMemory((PUCHAR)&EapolKeyInfo, (PUCHAR)&pMsg->KeyDesc.KeyInfo, sizeof(KEY_INFO));
-
-	*((USHORT *)&EapolKeyInfo) = cpu2le16(*((USHORT *)&EapolKeyInfo));
-
-	// Choose WPA2 or not
-	if ((pEntry->AuthMode == Ndis802_11AuthModeWPA2) || (pEntry->AuthMode == Ndis802_11AuthModeWPA2PSK))
-		bWPA2 = TRUE;
-
-	// 0. Check MsgType
-	if ((MsgType > EAPOL_GROUP_MSG_2) || (MsgType < EAPOL_PAIR_MSG_1))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("The message type is invalid(%d)! \n", MsgType));
-		return FALSE;
-	}
-
-	// 1. Replay counter check
- 	if (MsgType == EAPOL_PAIR_MSG_1 || MsgType == EAPOL_PAIR_MSG_3 || MsgType == EAPOL_GROUP_MSG_1)	// For supplicant
-    {
-    	// First validate replay counter, only accept message with larger replay counter.
-		// Let equal pass, some AP start with all zero replay counter
-		UCHAR	ZeroReplay[LEN_KEY_DESC_REPLAY];
-
-        NdisZeroMemory(ZeroReplay, LEN_KEY_DESC_REPLAY);
-		if ((RTMPCompareMemory(pMsg->KeyDesc.ReplayCounter, pEntry->R_Counter, LEN_KEY_DESC_REPLAY) != 1) &&
-			(RTMPCompareMemory(pMsg->KeyDesc.ReplayCounter, ZeroReplay, LEN_KEY_DESC_REPLAY) != 0))
-    	{
-			bReplayDiff = TRUE;
-    	}
- 	}
-	else if (MsgType == EAPOL_PAIR_MSG_2 || MsgType == EAPOL_PAIR_MSG_4 || MsgType == EAPOL_GROUP_MSG_2)	// For authenticator
-	{
-		// check Replay Counter coresponds to MSG from authenticator, otherwise discard
-    	if (!NdisEqualMemory(pMsg->KeyDesc.ReplayCounter, pEntry->R_Counter, LEN_KEY_DESC_REPLAY))
-    	{
-			bReplayDiff = TRUE;
-    	}
-	}
-
-	// Replay Counter different condition
-	if (bReplayDiff)
-	{
-		// send wireless event - for replay counter different
-		if (pAd->CommonCfg.bWirelessEvent)
-			RTMPSendWirelessEvent(pAd, IW_REPLAY_COUNTER_DIFF_EVENT_FLAG, pEntry->Addr, pEntry->apidx, 0);
-
-		if (MsgType < EAPOL_GROUP_MSG_1)
-		{
-           	DBGPRINT(RT_DEBUG_ERROR, ("Replay Counter Different in pairwise msg %d of 4-way handshake!\n", MsgType));
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("Replay Counter Different in group msg %d of 2-way handshake!\n", (MsgType - EAPOL_PAIR_MSG_4)));
-		}
-
-		hex_dump("Receive replay counter ", pMsg->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-		hex_dump("Current replay counter ", pEntry->R_Counter, LEN_KEY_DESC_REPLAY);
-        return FALSE;
-	}
-
-	// 2. Verify MIC except Pairwise Msg1
-	if (MsgType != EAPOL_PAIR_MSG_1)
-	{
-		UCHAR			rcvd_mic[LEN_KEY_DESC_MIC];
-
-		// Record the received MIC for check later
-		NdisMoveMemory(rcvd_mic, pMsg->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-		NdisZeroMemory(pMsg->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-
-        if (pEntry->WepStatus == Ndis802_11Encryption2Enabled)	// TKIP
-        {
-            hmac_md5(pEntry->PTK, LEN_EAP_MICK, (PUCHAR)pMsg, MsgLen, mic);
-        }
-        else if (pEntry->WepStatus == Ndis802_11Encryption3Enabled)	// AES
-        {
-            HMAC_SHA1((PUCHAR)pMsg, MsgLen, pEntry->PTK, LEN_EAP_MICK, digest);
-            NdisMoveMemory(mic, digest, LEN_KEY_DESC_MIC);
-        }
-
-        if (!NdisEqualMemory(rcvd_mic, mic, LEN_KEY_DESC_MIC))
-        {
-			// send wireless event - for MIC different
-			if (pAd->CommonCfg.bWirelessEvent)
-				RTMPSendWirelessEvent(pAd, IW_MIC_DIFF_EVENT_FLAG, pEntry->Addr, pEntry->apidx, 0);
-
-			if (MsgType < EAPOL_GROUP_MSG_1)
-			{
-            	DBGPRINT(RT_DEBUG_ERROR, ("MIC Different in pairwise msg %d of 4-way handshake!\n", MsgType));
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("MIC Different in group msg %d of 2-way handshake!\n", (MsgType - EAPOL_PAIR_MSG_4)));
-			}
-
-			hex_dump("Received MIC", rcvd_mic, LEN_KEY_DESC_MIC);
-			hex_dump("Desired  MIC", mic, LEN_KEY_DESC_MIC);
-
-			return FALSE;
-        }
-	}
-
-	// Extract the context of the Key Data field if it exist
-	// The field in pairwise_msg_2_WPA1(WPA2) & pairwise_msg_3_WPA1 is un-encrypted.
-	// The field in group_msg_1_WPA1(WPA2) & pairwise_msg_3_WPA2 is encrypted.
-	if (pMsg->KeyDesc.KeyDataLen[1] > 0)
-	{
-		// Decrypt this field
-		if ((MsgType == EAPOL_PAIR_MSG_3 && bWPA2) || (MsgType == EAPOL_GROUP_MSG_1))
-		{
-			if(pEntry->WepStatus == Ndis802_11Encryption3Enabled)
-			{
-				// AES
-				AES_GTK_KEY_UNWRAP(&pEntry->PTK[16], KEYDATA, pMsg->KeyDesc.KeyDataLen[1],pMsg->KeyDesc.KeyData);
-			}
-			else
-			{
-				INT 	i;
-				UCHAR   Key[32];
-				// Decrypt TKIP GTK
-				// Construct 32 bytes RC4 Key
-				NdisMoveMemory(Key, pMsg->KeyDesc.KeyIv, 16);
-				NdisMoveMemory(&Key[16], &pEntry->PTK[16], 16);
-				ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, Key, 32);
-				//discard first 256 bytes
-				for(i = 0; i < 256; i++)
-					ARCFOUR_BYTE(&pAd->PrivateInfo.WEPCONTEXT);
-				// Decrypt GTK. Becareful, there is no ICV to check the result is correct or not
-				ARCFOUR_DECRYPT(&pAd->PrivateInfo.WEPCONTEXT, KEYDATA, pMsg->KeyDesc.KeyData, pMsg->KeyDesc.KeyDataLen[1]);
-			}
-
-			if (!bWPA2 && (MsgType == EAPOL_GROUP_MSG_1))
-				GroupKeyIndex = EapolKeyInfo.KeyIndex;
-
-		}
-		else if ((MsgType == EAPOL_PAIR_MSG_2) || (MsgType == EAPOL_PAIR_MSG_3 && !bWPA2))
-		{
-			NdisMoveMemory(KEYDATA, pMsg->KeyDesc.KeyData, pMsg->KeyDesc.KeyDataLen[1]);
-		}
-		else
-		{
-
-			return TRUE;
-		}
-
-		// Parse Key Data field to
-		// 1. verify RSN IE for pairwise_msg_2_WPA1(WPA2) ,pairwise_msg_3_WPA1(WPA2)
-		// 2. verify KDE format for pairwise_msg_3_WPA2, group_msg_1_WPA2
-		// 3. update shared key for pairwise_msg_3_WPA2, group_msg_1_WPA1(WPA2)
-		if (!RTMPParseEapolKeyData(pAd, KEYDATA, pMsg->KeyDesc.KeyDataLen[1], GroupKeyIndex, MsgType, bWPA2, pEntry))
-		{
-			return FALSE;
-		}
-	}
-
-	return TRUE;
-
-}
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-BOOLEAN MlmeDlsReqSanity(
-	IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PRT_802_11_DLS *pDLS,
-    OUT PUSHORT pReason)
-{
-	MLME_DLS_REQ_STRUCT *pInfo;
-
-    pInfo = (MLME_DLS_REQ_STRUCT *)Msg;
-
-	*pDLS = pInfo->pDLS;
-	*pReason = pInfo->Reason;
-
-	return TRUE;
-}
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef QOS_DLS_SUPPORT
-BOOLEAN PeerDlsReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pDlsTimeout,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-	OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability)
-{
-	CHAR            *Ptr;
-    PFRAME_802_11	Fr = (PFRAME_802_11)Msg;
-	PEID_STRUCT  eid_ptr;
-
-    // to prevent caller from using garbage output value
-    *pCapabilityInfo	= 0;
-    *pDlsTimeout	= 0;
-	*pHtCapabilityLen = 0;
-
-    Ptr = Fr->Octet;
-
-	// offset to destination MAC address (Category and Action field)
-    Ptr += 2;
-
-    // get DA from payload and advance the pointer
-    NdisMoveMemory(pDA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get SA from payload and advance the pointer
-    NdisMoveMemory(pSA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get capability info from payload and advance the pointer
-    NdisMoveMemory(pCapabilityInfo, Ptr, 2);
-    Ptr += 2;
-
-    // get capability info from payload and advance the pointer
-    NdisMoveMemory(pDlsTimeout, Ptr, 2);
-    Ptr += 2;
-
-	// Category and Action field + DA + SA + capability + Timeout
-	eid_ptr = (PEID_STRUCT) &Fr->Octet[18];
-
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((UCHAR*)Fr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_SUPP_RATES:
-                if ((eid_ptr->Len <= MAX_LEN_OF_SUPPORTED_RATES) && (eid_ptr->Len > 0))
-                {
-                    NdisMoveMemory(Rates, eid_ptr->Octet, eid_ptr->Len);
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - IE_SUPP_RATES., Len=%d. Rates[0]=%x\n",eid_ptr->Len, Rates[0]));
-                    DBGPRINT(RT_DEBUG_TRACE, ("Rates[1]=%x %x %x %x %x %x %x\n", Rates[1], Rates[2], Rates[3], Rates[4], Rates[5], Rates[6], Rates[7]));
-                    *pRatesLen = eid_ptr->Len;
-                }
-                else
-                {
-                    *pRatesLen = 8;
-					Rates[0] = 0x82;
-					Rates[1] = 0x84;
-					Rates[2] = 0x8b;
-					Rates[3] = 0x96;
-					Rates[4] = 0x12;
-					Rates[5] = 0x24;
-					Rates[6] = 0x48;
-					Rates[7] = 0x6c;
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - wrong IE_SUPP_RATES., Len=%d\n",eid_ptr->Len));
-                }
-				break;
-
-			case IE_EXT_SUPP_RATES:
-                if (eid_ptr->Len + *pRatesLen <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, eid_ptr->Len);
-                    *pRatesLen = (*pRatesLen) + eid_ptr->Len;
-                }
-                else
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, MAX_LEN_OF_SUPPORTED_RATES - (*pRatesLen));
-                    *pRatesLen = MAX_LEN_OF_SUPPORTED_RATES;
-                }
-				break;
-
-			case IE_HT_CAP:
-				if (eid_ptr->Len >= sizeof(HT_CAPABILITY_IE))
-				{
-					NdisMoveMemory(pHtCapability, eid_ptr->Octet, sizeof(HT_CAPABILITY_IE));
-
-					*(USHORT *)(&pHtCapability->HtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->HtCapInfo));
-					*(USHORT *)(&pHtCapability->ExtHtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->ExtHtCapInfo));
-					*pHtCapabilityLen = sizeof(HT_CAPABILITY_IE);
-
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - IE_HT_CAP\n"));
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - wrong IE_HT_CAP.eid_ptr->Len = %d\n", eid_ptr->Len));
-				}
-				break;
-
-			default:
-				break;
-		}
-
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-    return TRUE;
-}
-
-BOOLEAN PeerDlsRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pStatus,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-    OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability)
-{
-    CHAR            *Ptr;
-    PFRAME_802_11	Fr = (PFRAME_802_11)Msg;
-	PEID_STRUCT  eid_ptr;
-
-    // to prevent caller from using garbage output value
-    *pStatus		= 0;
-    *pCapabilityInfo	= 0;
-	*pHtCapabilityLen = 0;
-
-    Ptr = Fr->Octet;
-
-	// offset to destination MAC address (Category and Action field)
-    Ptr += 2;
-
-	// get status code from payload and advance the pointer
-    NdisMoveMemory(pStatus, Ptr, 2);
-    Ptr += 2;
-
-    // get DA from payload and advance the pointer
-    NdisMoveMemory(pDA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get SA from payload and advance the pointer
-    NdisMoveMemory(pSA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-	if (pStatus == 0)
-	{
-	    // get capability info from payload and advance the pointer
-	    NdisMoveMemory(pCapabilityInfo, Ptr, 2);
-	    Ptr += 2;
-	}
-
-	// Category and Action field + status code + DA + SA + capability
-	eid_ptr = (PEID_STRUCT) &Fr->Octet[18];
-
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((UCHAR*)Fr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_SUPP_RATES:
-                if ((eid_ptr->Len <= MAX_LEN_OF_SUPPORTED_RATES) && (eid_ptr->Len > 0))
-                {
-                    NdisMoveMemory(Rates, eid_ptr->Octet, eid_ptr->Len);
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - IE_SUPP_RATES., Len=%d. Rates[0]=%x\n",eid_ptr->Len, Rates[0]));
-                    DBGPRINT(RT_DEBUG_TRACE, ("Rates[1]=%x %x %x %x %x %x %x\n", Rates[1], Rates[2], Rates[3], Rates[4], Rates[5], Rates[6], Rates[7]));
-                    *pRatesLen = eid_ptr->Len;
-                }
-                else
-                {
-                    *pRatesLen = 8;
-					Rates[0] = 0x82;
-					Rates[1] = 0x84;
-					Rates[2] = 0x8b;
-					Rates[3] = 0x96;
-					Rates[4] = 0x12;
-					Rates[5] = 0x24;
-					Rates[6] = 0x48;
-					Rates[7] = 0x6c;
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - wrong IE_SUPP_RATES., Len=%d\n",eid_ptr->Len));
-                }
-				break;
-
-			case IE_EXT_SUPP_RATES:
-                if (eid_ptr->Len + *pRatesLen <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, eid_ptr->Len);
-                    *pRatesLen = (*pRatesLen) + eid_ptr->Len;
-                }
-                else
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, MAX_LEN_OF_SUPPORTED_RATES - (*pRatesLen));
-                    *pRatesLen = MAX_LEN_OF_SUPPORTED_RATES;
-                }
-				break;
-
-			case IE_HT_CAP:
-				if (eid_ptr->Len >= sizeof(HT_CAPABILITY_IE))
-				{
-					NdisMoveMemory(pHtCapability, eid_ptr->Octet, sizeof(HT_CAPABILITY_IE));
-
-					*(USHORT *)(&pHtCapability->HtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->HtCapInfo));
-					*(USHORT *)(&pHtCapability->ExtHtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->ExtHtCapInfo));
-					*pHtCapabilityLen = sizeof(HT_CAPABILITY_IE);
-
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - IE_HT_CAP\n"));
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - wrong IE_HT_CAP.eid_ptr->Len = %d\n", eid_ptr->Len));
-				}
-				break;
-
-			default:
-				break;
-		}
-
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-    return TRUE;
-}
-
-BOOLEAN PeerDlsTearDownSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pReason)
-{
-    CHAR            *Ptr;
-    PFRAME_802_11	Fr = (PFRAME_802_11)Msg;
-
-    // to prevent caller from using garbage output value
-    *pReason	= 0;
-
-    Ptr = Fr->Octet;
-
-	// offset to destination MAC address (Category and Action field)
-    Ptr += 2;
-
-    // get DA from payload and advance the pointer
-    NdisMoveMemory(pDA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get SA from payload and advance the pointer
-    NdisMoveMemory(pSA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-	// get reason code from payload and advance the pointer
-    NdisMoveMemory(pReason, Ptr, 2);
-    Ptr += 2;
-
-    return TRUE;
-}
-#endif // QOS_DLS_SUPPORT //
-
+#include "../../rt2860/common/cmm_sanity.c"
diff --git a/drivers/staging/rt2870/common/cmm_sync.c b/drivers/staging/rt2870/common/cmm_sync.c
index 2be7c77..5e7221d 100644
--- a/drivers/staging/rt2870/common/cmm_sync.c
+++ b/drivers/staging/rt2870/common/cmm_sync.c
@@ -1,711 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	sync.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang	2004-09-01      modified for rt2561/2661
-*/
-#include "../rt_config.h"
-
-// 2.4 Ghz channel plan index in the TxPower arrays.
-#define	BG_BAND_REGION_0_START	0			// 1,2,3,4,5,6,7,8,9,10,11
-#define	BG_BAND_REGION_0_SIZE	11
-#define	BG_BAND_REGION_1_START	0			// 1,2,3,4,5,6,7,8,9,10,11,12,13
-#define	BG_BAND_REGION_1_SIZE	13
-#define	BG_BAND_REGION_2_START	9			// 10,11
-#define	BG_BAND_REGION_2_SIZE	2
-#define	BG_BAND_REGION_3_START	9			// 10,11,12,13
-#define	BG_BAND_REGION_3_SIZE	4
-#define	BG_BAND_REGION_4_START	13			// 14
-#define	BG_BAND_REGION_4_SIZE	1
-#define	BG_BAND_REGION_5_START	0			// 1,2,3,4,5,6,7,8,9,10,11,12,13,14
-#define	BG_BAND_REGION_5_SIZE	14
-#define	BG_BAND_REGION_6_START	2			// 3,4,5,6,7,8,9
-#define	BG_BAND_REGION_6_SIZE	7
-#define	BG_BAND_REGION_7_START	4			// 5,6,7,8,9,10,11,12,13
-#define	BG_BAND_REGION_7_SIZE	9
-#define	BG_BAND_REGION_31_START	0			// 1,2,3,4,5,6,7,8,9,10,11,12,13,14
-#define	BG_BAND_REGION_31_SIZE	14
-
-// 5 Ghz channel plan index in the TxPower arrays.
-UCHAR A_BAND_REGION_0_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64, 149, 153, 157, 161, 165};
-UCHAR A_BAND_REGION_1_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140};
-UCHAR A_BAND_REGION_2_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64};
-UCHAR A_BAND_REGION_3_CHANNEL_LIST[]={52, 56, 60, 64, 149, 153, 157, 161};
-UCHAR A_BAND_REGION_4_CHANNEL_LIST[]={149, 153, 157, 161, 165};
-UCHAR A_BAND_REGION_5_CHANNEL_LIST[]={149, 153, 157, 161};
-UCHAR A_BAND_REGION_6_CHANNEL_LIST[]={36, 40, 44, 48};
-UCHAR A_BAND_REGION_7_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 149, 153, 157, 161, 165};
-UCHAR A_BAND_REGION_8_CHANNEL_LIST[]={52, 56, 60, 64};
-UCHAR A_BAND_REGION_9_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 132, 136, 140, 149, 153, 157, 161, 165};
-UCHAR A_BAND_REGION_10_CHANNEL_LIST[]={36, 40, 44, 48, 149, 153, 157, 161, 165};
-UCHAR A_BAND_REGION_11_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 149, 153, 157, 161};
-
-//BaSizeArray follows the 802.11n definition as MaxRxFactor.  2^(13+factor) bytes. When factor =0, it's about Ba buffer size =8.
-UCHAR BaSizeArray[4] = {8,16,32,64};
-
-/*
-	==========================================================================
-	Description:
-		Update StaCfg->ChannelList[] according to 1) Country Region 2) RF IC type,
-		and 3) PHY-mode user selected.
-		The outcome is used by driver when doing site survey.
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID BuildChannelList(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR i, j, index=0, num=0;
-	PUCHAR	pChannelList = NULL;
-
-	NdisZeroMemory(pAd->ChannelList, MAX_NUM_OF_CHANNELS * sizeof(CHANNEL_TX_POWER));
-
-	// if not 11a-only mode, channel list starts from 2.4Ghz band
-	if ((pAd->CommonCfg.PhyMode != PHY_11A)
-#ifdef DOT11_N_SUPPORT
-		&& (pAd->CommonCfg.PhyMode != PHY_11AN_MIXED) && (pAd->CommonCfg.PhyMode != PHY_11N_5G)
-#endif // DOT11_N_SUPPORT //
-	)
-	{
-		switch (pAd->CommonCfg.CountryRegion  & 0x7f)
-		{
-			case REGION_0_BG_BAND:	// 1 -11
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_0_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_0_SIZE);
-				index += BG_BAND_REGION_0_SIZE;
-				break;
-			case REGION_1_BG_BAND:	// 1 - 13
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_1_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_1_SIZE);
-				index += BG_BAND_REGION_1_SIZE;
-				break;
-			case REGION_2_BG_BAND:	// 10 - 11
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_2_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_2_SIZE);
-				index += BG_BAND_REGION_2_SIZE;
-				break;
-			case REGION_3_BG_BAND:	// 10 - 13
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_3_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_3_SIZE);
-				index += BG_BAND_REGION_3_SIZE;
-				break;
-			case REGION_4_BG_BAND:	// 14
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_4_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_4_SIZE);
-				index += BG_BAND_REGION_4_SIZE;
-				break;
-			case REGION_5_BG_BAND:	// 1 - 14
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_5_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_5_SIZE);
-				index += BG_BAND_REGION_5_SIZE;
-				break;
-			case REGION_6_BG_BAND:	// 3 - 9
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_6_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_6_SIZE);
-				index += BG_BAND_REGION_6_SIZE;
-				break;
-			case REGION_7_BG_BAND:  // 5 - 13
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_7_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_7_SIZE);
-				index += BG_BAND_REGION_7_SIZE;
-				break;
-			case REGION_31_BG_BAND:	// 1 - 14
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_31_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_31_SIZE);
-				index += BG_BAND_REGION_31_SIZE;
-				break;
-			default:            // Error. should never happen
-				break;
-		}
-		for (i=0; i<index; i++)
-			pAd->ChannelList[i].MaxTxPwr = 20;
-	}
-
-	if ((pAd->CommonCfg.PhyMode == PHY_11A) || (pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED)
-#ifdef DOT11_N_SUPPORT
-		|| (pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED) || (pAd->CommonCfg.PhyMode == PHY_11AN_MIXED)
-		|| (pAd->CommonCfg.PhyMode == PHY_11AGN_MIXED) || (pAd->CommonCfg.PhyMode == PHY_11N_5G)
-#endif // DOT11_N_SUPPORT //
-	)
-	{
-		switch (pAd->CommonCfg.CountryRegionForABand & 0x7f)
-		{
-			case REGION_0_A_BAND:
-				num = sizeof(A_BAND_REGION_0_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_0_CHANNEL_LIST;
-				break;
-			case REGION_1_A_BAND:
-				num = sizeof(A_BAND_REGION_1_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_1_CHANNEL_LIST;
-				break;
-			case REGION_2_A_BAND:
-				num = sizeof(A_BAND_REGION_2_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_2_CHANNEL_LIST;
-				break;
-			case REGION_3_A_BAND:
-				num = sizeof(A_BAND_REGION_3_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_3_CHANNEL_LIST;
-				break;
-			case REGION_4_A_BAND:
-				num = sizeof(A_BAND_REGION_4_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_4_CHANNEL_LIST;
-				break;
-			case REGION_5_A_BAND:
-				num = sizeof(A_BAND_REGION_5_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_5_CHANNEL_LIST;
-				break;
-			case REGION_6_A_BAND:
-				num = sizeof(A_BAND_REGION_6_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_6_CHANNEL_LIST;
-				break;
-			case REGION_7_A_BAND:
-				num = sizeof(A_BAND_REGION_7_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_7_CHANNEL_LIST;
-				break;
-			case REGION_8_A_BAND:
-				num = sizeof(A_BAND_REGION_8_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_8_CHANNEL_LIST;
-				break;
-			case REGION_9_A_BAND:
-				num = sizeof(A_BAND_REGION_9_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_9_CHANNEL_LIST;
-				break;
-
-			case REGION_10_A_BAND:
-				num = sizeof(A_BAND_REGION_10_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_10_CHANNEL_LIST;
-				break;
-
-			case REGION_11_A_BAND:
-				num = sizeof(A_BAND_REGION_11_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_11_CHANNEL_LIST;
-				break;
-
-			default:            // Error. should never happen
-				DBGPRINT(RT_DEBUG_WARN,("countryregion=%d not support", pAd->CommonCfg.CountryRegionForABand));
-				break;
-		}
-
-		if (num != 0)
-		{
-			UCHAR RadarCh[15]={52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140};
-			for (i=0; i<num; i++)
-			{
-				for (j=0; j<MAX_NUM_OF_CHANNELS; j++)
-				{
-					if (pChannelList[i] == pAd->TxPower[j].Channel)
-						NdisMoveMemory(&pAd->ChannelList[index+i], &pAd->TxPower[j], sizeof(CHANNEL_TX_POWER));
-					}
-				for (j=0; j<15; j++)
-				{
-					if (pChannelList[i] == RadarCh[j])
-						pAd->ChannelList[index+i].DfsReq = TRUE;
-				}
-				pAd->ChannelList[index+i].MaxTxPwr = 20;
-			}
-			index += num;
-		}
-	}
-
-	pAd->ChannelListNum = index;
-	DBGPRINT(RT_DEBUG_TRACE,("country code=%d/%d, RFIC=%d, PHY mode=%d, support %d channels\n",
-		pAd->CommonCfg.CountryRegion, pAd->CommonCfg.CountryRegionForABand, pAd->RfIcType, pAd->CommonCfg.PhyMode, pAd->ChannelListNum));
-#ifdef DBG
-	for (i=0;i<pAd->ChannelListNum;i++)
-	{
-		DBGPRINT_RAW(RT_DEBUG_TRACE,("BuildChannel # %d :: Pwr0 = %d, Pwr1 =%d, \n ", pAd->ChannelList[i].Channel, pAd->ChannelList[i].Power, pAd->ChannelList[i].Power2));
-	}
-#endif
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine return the first channel number according to the country
-		code selection and RF IC selection (signal band or dual band). It is called
-		whenever driver need to start a site survey of all supported channels.
-	Return:
-		ch - the first channel number of current country code setting
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
- */
-UCHAR FirstChannel(
-	IN PRTMP_ADAPTER pAd)
-{
-	return pAd->ChannelList[0].Channel;
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine returns the next channel number. This routine is called
-		during driver need to start a site survey of all supported channels.
-	Return:
-		next_channel - the next channel number valid in current country code setting.
-	Note:
-		return 0 if no more next channel
-	==========================================================================
- */
-UCHAR NextChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR channel)
-{
-	int i;
-	UCHAR next_channel = 0;
-
-	for (i = 0; i < (pAd->ChannelListNum - 1); i++)
-		if (channel == pAd->ChannelList[i].Channel)
-		{
-			next_channel = pAd->ChannelList[i+1].Channel;
-			break;
-	}
-	return next_channel;
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine is for Cisco Compatible Extensions 2.X
-		Spec31. AP Control of Client Transmit Power
-	Return:
-		None
-	Note:
-	   Required by Aironet dBm(mW)
-		   0dBm(1mW),   1dBm(5mW), 13dBm(20mW), 15dBm(30mW),
-		  17dBm(50mw), 20dBm(100mW)
-
-	   We supported
-		   3dBm(Lowest), 6dBm(10%), 9dBm(25%), 12dBm(50%),
-		  14dBm(75%),   15dBm(100%)
-
-		The client station's actual transmit power shall be within +/- 5dB of
-		the minimum value or next lower value.
-	==========================================================================
- */
-VOID ChangeToCellPowerLimit(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR         AironetCellPowerLimit)
-{
-	//valud 0xFF means that hasn't found power limit information
-	//from the AP's Beacon/Probe response.
-	if (AironetCellPowerLimit == 0xFF)
-		return;
-
-	if (AironetCellPowerLimit < 6) //Used Lowest Power Percentage.
-		pAd->CommonCfg.TxPowerPercentage = 6;
-	else if (AironetCellPowerLimit < 9)
-		pAd->CommonCfg.TxPowerPercentage = 10;
-	else if (AironetCellPowerLimit < 12)
-		pAd->CommonCfg.TxPowerPercentage = 25;
-	else if (AironetCellPowerLimit < 14)
-		pAd->CommonCfg.TxPowerPercentage = 50;
-	else if (AironetCellPowerLimit < 15)
-		pAd->CommonCfg.TxPowerPercentage = 75;
-	else
-		pAd->CommonCfg.TxPowerPercentage = 100; //else used maximum
-
-	if (pAd->CommonCfg.TxPowerPercentage > pAd->CommonCfg.TxPowerDefault)
-		pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault;
-
-}
-
-CHAR	ConvertToRssi(
-	IN PRTMP_ADAPTER pAd,
-	IN	CHAR			Rssi,
-	IN  UCHAR   RssiNumber)
-{
-	UCHAR	RssiOffset, LNAGain;
-
-	// Rssi equals to zero should be an invalid value
-	if (Rssi == 0)
-		return -99;
-
-	LNAGain = GET_LNA_GAIN(pAd);
-    if (pAd->LatchRfRegs.Channel > 14)
-    {
-        if (RssiNumber == 0)
-			RssiOffset = pAd->ARssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->ARssiOffset1;
-		else
-			RssiOffset = pAd->ARssiOffset2;
-    }
-    else
-    {
-        if (RssiNumber == 0)
-			RssiOffset = pAd->BGRssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->BGRssiOffset1;
-		else
-			RssiOffset = pAd->BGRssiOffset2;
-    }
-
-    return (-12 - RssiOffset - LNAGain - Rssi);
-}
-
-/*
-	==========================================================================
-	Description:
-		Scan next channel
-	==========================================================================
- */
-VOID ScanNextChannel(
-	IN PRTMP_ADAPTER pAd)
-{
-	HEADER_802_11   Hdr80211;
-	PUCHAR          pOutBuffer = NULL;
-	NDIS_STATUS     NStatus;
-	ULONG           FrameLen = 0;
-	UCHAR           SsidLen = 0, ScanType = pAd->MlmeAux.ScanType, BBPValue = 0;
-#ifdef CONFIG_STA_SUPPORT
-	USHORT          Status;
-	PHEADER_802_11  pHdr80211;
-#endif // CONFIG_STA_SUPPORT //
-	UINT			ScanTimeIn5gChannel = SHORT_CHANNEL_TIME;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (MONITOR_ON(pAd))
-			return;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef RALINK_ATE
-	// Nothing to do in ATE mode.
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	if (pAd->MlmeAux.Channel == 0)
-	{
-		if ((pAd->CommonCfg.BBPCurrentBW == BW_40)
-#ifdef CONFIG_STA_SUPPORT
-			&& (INFRA_ON(pAd)
-				|| (pAd->OpMode == OPMODE_AP))
-#endif // CONFIG_STA_SUPPORT //
-			)
-		{
-			AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-			AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue &= (~0x18);
-			BBPValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-			DBGPRINT(RT_DEBUG_TRACE, ("SYNC - End of SCAN, restore to 40MHz channel %d, Total BSS[%02d]\n",pAd->CommonCfg.CentralChannel, pAd->ScanTab.BssNr));
-		}
-		else
-		{
-			AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-			AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-			DBGPRINT(RT_DEBUG_TRACE, ("SYNC - End of SCAN, restore to channel %d, Total BSS[%02d]\n",pAd->CommonCfg.Channel, pAd->ScanTab.BssNr));
-		}
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			//
-			// To prevent data lost.
-			// Send an NULL data with turned PSM bit on to current associated AP before SCAN progress.
-			// Now, we need to send an NULL data with turned PSM bit off to AP, when scan progress done
-			//
-			if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) && (INFRA_ON(pAd)))
-			{
-				NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);
-				if (NStatus	== NDIS_STATUS_SUCCESS)
-				{
-					pHdr80211 = (PHEADER_802_11) pOutBuffer;
-					MgtMacHeaderInit(pAd, pHdr80211, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-					pHdr80211->Duration = 0;
-					pHdr80211->FC.Type = BTYPE_DATA;
-					pHdr80211->FC.PwrMgmt = (pAd->StaCfg.Psm == PWR_SAVE);
-
-					// Send using priority queue
-					MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-					DBGPRINT(RT_DEBUG_TRACE, ("MlmeScanReqAction -- Send PSM Data frame\n"));
-					MlmeFreeMemory(pAd, pOutBuffer);
-					RTMPusecDelay(5000);
-				}
-			}
-
-			pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-			Status = MLME_SUCCESS;
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status);
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-
-		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-	}
-#ifdef RT2870
-#ifdef CONFIG_STA_SUPPORT
-	else if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST) && (pAd->OpMode == OPMODE_STA))
-	{
-		pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-		MlmeCntlConfirm(pAd, MT2_SCAN_CONF, MLME_FAIL_NO_RESOURCE);
-	}
-#endif // CONFIG_STA_SUPPORT //
-#endif // RT2870 //
-	else
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-		// BBP and RF are not accessible in PS mode, we has to wake them up first
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-			AsicForceWakeup(pAd, TRUE);
-
-			// leave PSM during scanning. otherwise we may lost ProbeRsp & BEACON
-			if (pAd->StaCfg.Psm == PWR_SAVE)
-				MlmeSetPsmBit(pAd, PWR_ACTIVE);
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		AsicSwitchChannel(pAd, pAd->MlmeAux.Channel, TRUE);
-		AsicLockChannel(pAd, pAd->MlmeAux.Channel);
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			if (pAd->MlmeAux.Channel > 14)
-			{
-				if ((pAd->CommonCfg.bIEEE80211H == 1) && RadarChannelCheck(pAd, pAd->MlmeAux.Channel))
-				{
-					ScanType = SCAN_PASSIVE;
-					ScanTimeIn5gChannel = MIN_CHANNEL_TIME;
-				}
-			}
-
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-			// carrier detection
-			if (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-			{
-				ScanType = SCAN_PASSIVE;
-				ScanTimeIn5gChannel = MIN_CHANNEL_TIME;
-			}
-#endif // CARRIER_DETECTION_SUPPORT //
-		}
-
-#endif // CONFIG_STA_SUPPORT //
-
-		//Global country domain(ch1-11:active scan, ch12-14 passive scan)
-		if ((pAd->MlmeAux.Channel <= 14) && (pAd->MlmeAux.Channel >= 12) && ((pAd->CommonCfg.CountryRegion & 0x7f) == REGION_31_BG_BAND))
-		{
-			ScanType = SCAN_PASSIVE;
-		}
-
-		// We need to shorten active scan time in order for WZC connect issue
-		// Chnage the channel scan time for CISCO stuff based on its IAPP announcement
-		if (ScanType == FAST_SCAN_ACTIVE)
-			RTMPSetTimer(&pAd->MlmeAux.ScanTimer, FAST_ACTIVE_SCAN_TIME);
-#ifdef CONFIG_STA_SUPPORT
-		else if (((ScanType == SCAN_CISCO_ACTIVE) ||
-				(ScanType == SCAN_CISCO_PASSIVE) ||
-				(ScanType == SCAN_CISCO_CHANNEL_LOAD) ||
-				(ScanType == SCAN_CISCO_NOISE)) && (pAd->OpMode == OPMODE_STA))
-		{
-			if (pAd->StaCfg.CCXScanTime < 25)
-				RTMPSetTimer(&pAd->MlmeAux.ScanTimer, pAd->StaCfg.CCXScanTime * 2);
-			else
-				RTMPSetTimer(&pAd->MlmeAux.ScanTimer, pAd->StaCfg.CCXScanTime);
-		}
-#endif // CONFIG_STA_SUPPORT //
-		else // must be SCAN_PASSIVE or SCAN_ACTIVE
-		{
-			if ((pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED)
-#ifdef DOT11_N_SUPPORT
-				|| (pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED) || (pAd->CommonCfg.PhyMode == PHY_11AGN_MIXED)
-#endif // DOT11_N_SUPPORT //
-			)
-			{
-				if (pAd->MlmeAux.Channel > 14)
-					RTMPSetTimer(&pAd->MlmeAux.ScanTimer, ScanTimeIn5gChannel);
-				else
-				RTMPSetTimer(&pAd->MlmeAux.ScanTimer, MIN_CHANNEL_TIME);
-			}
-			else
-				RTMPSetTimer(&pAd->MlmeAux.ScanTimer, MAX_CHANNEL_TIME);
-		}
-
-		if ((ScanType == SCAN_ACTIVE) || (ScanType == FAST_SCAN_ACTIVE) ||
-			(ScanType == SCAN_CISCO_ACTIVE))
-		{
-			NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-			if (NStatus != NDIS_STATUS_SUCCESS)
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("SYNC - ScanNextChannel() allocate memory fail\n"));
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-					pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-					Status = MLME_FAIL_NO_RESOURCE;
-					MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status);
-				}
-#endif // CONFIG_STA_SUPPORT //
-
-				return;
-			}
-
-			// There is no need to send broadcast probe request if active scan is in effect.
-			if ((ScanType == SCAN_ACTIVE) || (ScanType == FAST_SCAN_ACTIVE)
-				)
-				SsidLen = pAd->MlmeAux.SsidLen;
-			else
-				SsidLen = 0;
-
-			MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, BROADCAST_ADDR, BROADCAST_ADDR);
-			MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-							  sizeof(HEADER_802_11),    &Hdr80211,
-							  1,                        &SsidIe,
-							  1,                        &SsidLen,
-							  SsidLen,			        pAd->MlmeAux.Ssid,
-							  1,                        &SupRateIe,
-							  1,                        &pAd->CommonCfg.SupRateLen,
-							  pAd->CommonCfg.SupRateLen,  pAd->CommonCfg.SupRate,
-							  END_OF_ARGS);
-
-			if (pAd->CommonCfg.ExtRateLen)
-			{
-				ULONG Tmp;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &Tmp,
-								  1,                                &ExtRateIe,
-								  1,                                &pAd->CommonCfg.ExtRateLen,
-								  pAd->CommonCfg.ExtRateLen,          pAd->CommonCfg.ExtRate,
-								  END_OF_ARGS);
-				FrameLen += Tmp;
-			}
-
-#ifdef DOT11_N_SUPPORT
-			if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-			{
-				ULONG	Tmp;
-				UCHAR	HtLen;
-				UCHAR	BROADCOM[4] = {0x0, 0x90, 0x4c, 0x33};
-#ifdef RT_BIG_ENDIAN
-				HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
-				if (pAd->bBroadComHT == TRUE)
-				{
-					HtLen = pAd->MlmeAux.HtCapabilityLen + 4;
-#ifdef RT_BIG_ENDIAN
-					NdisMoveMemory(&HtCapabilityTmp, &pAd->MlmeAux.HtCapability, SIZE_HT_CAP_IE);
-					*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-					*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
-									1,                                &WpaIe,
-									1,                                &HtLen,
-									4,                                &BROADCOM[0],
-									pAd->MlmeAux.HtCapabilityLen,     &HtCapabilityTmp,
-									END_OF_ARGS);
-#else
-					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
-									1,                                &WpaIe,
-									1,                                &HtLen,
-									4,                                &BROADCOM[0],
-									pAd->MlmeAux.HtCapabilityLen,     &pAd->MlmeAux.HtCapability,
-									END_OF_ARGS);
-#endif // RT_BIG_ENDIAN //
-				}
-				else
-				{
-					HtLen = pAd->MlmeAux.HtCapabilityLen;
-#ifdef RT_BIG_ENDIAN
-					NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, SIZE_HT_CAP_IE);
-					*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-					*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
-									1,                                &HtCapIe,
-									1,                                &HtLen,
-									HtLen,                            &HtCapabilityTmp,
-									END_OF_ARGS);
-#else
-					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
-									1,                                &HtCapIe,
-									1,                                &HtLen,
-									HtLen,                            &pAd->CommonCfg.HtCapability,
-									END_OF_ARGS);
-#endif // RT_BIG_ENDIAN //
-				}
-				FrameLen += Tmp;
-
-#ifdef DOT11N_DRAFT3
-				if (pAd->CommonCfg.BACapability.field.b2040CoexistScanSup == 1)
-				{
-					ULONG		Tmp;
-					HtLen = 1;
-					MakeOutgoingFrame(pOutBuffer + FrameLen,            &Tmp,
-									  1,					&ExtHtCapIe,
-									  1,					&HtLen,
-									  1,          			&pAd->CommonCfg.BSSCoexist2040.word,
-									  END_OF_ARGS);
-
-					FrameLen += Tmp;
-				}
-#endif // DOT11N_DRAFT3 //
-			}
-#endif // DOT11_N_SUPPORT //
-
-
-			MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-			MlmeFreeMemory(pAd, pOutBuffer);
-		}
-
-		// For SCAN_CISCO_PASSIVE, do nothing and silently wait for beacon or other probe reponse
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			pAd->Mlme.SyncMachine.CurrState = SCAN_LISTEN;
-#endif // CONFIG_STA_SUPPORT //
-
-	}
-}
-
-VOID MgtProbReqMacHeaderInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN OUT PHEADER_802_11 pHdr80211,
-	IN UCHAR SubType,
-	IN UCHAR ToDs,
-	IN PUCHAR pDA,
-	IN PUCHAR pBssid)
-{
-	NdisZeroMemory(pHdr80211, sizeof(HEADER_802_11));
-
-	pHdr80211->FC.Type = BTYPE_MGMT;
-	pHdr80211->FC.SubType = SubType;
-	if (SubType == SUBTYPE_ACK)
-		pHdr80211->FC.Type = BTYPE_CNTL;
-	pHdr80211->FC.ToDs = ToDs;
-	COPY_MAC_ADDR(pHdr80211->Addr1, pDA);
-	COPY_MAC_ADDR(pHdr80211->Addr2, pAd->CurrentAddress);
-	COPY_MAC_ADDR(pHdr80211->Addr3, pBssid);
-}
-
-
+#include "../../rt2860/common/cmm_sync.c"
diff --git a/drivers/staging/rt2870/common/cmm_wpa.c b/drivers/staging/rt2870/common/cmm_wpa.c
index d2c24bd..04a54bb 100644
--- a/drivers/staging/rt2870/common/cmm_wpa.c
+++ b/drivers/staging/rt2870/common/cmm_wpa.c
@@ -1,1654 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	wpa.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Jan	Lee		03-07-22		Initial
-	Paul Lin	03-11-28		Modify for supplicant
-*/
-#include "../rt_config.h"
-// WPA OUI
-UCHAR		OUI_WPA_NONE_AKM[4]		= {0x00, 0x50, 0xF2, 0x00};
-UCHAR       OUI_WPA_VERSION[4]      = {0x00, 0x50, 0xF2, 0x01};
-UCHAR       OUI_WPA_WEP40[4]      = {0x00, 0x50, 0xF2, 0x01};
-UCHAR       OUI_WPA_TKIP[4]     = {0x00, 0x50, 0xF2, 0x02};
-UCHAR       OUI_WPA_CCMP[4]     = {0x00, 0x50, 0xF2, 0x04};
-UCHAR       OUI_WPA_WEP104[4]      = {0x00, 0x50, 0xF2, 0x05};
-UCHAR       OUI_WPA_8021X_AKM[4]	= {0x00, 0x50, 0xF2, 0x01};
-UCHAR       OUI_WPA_PSK_AKM[4]      = {0x00, 0x50, 0xF2, 0x02};
-// WPA2 OUI
-UCHAR       OUI_WPA2_WEP40[4]   = {0x00, 0x0F, 0xAC, 0x01};
-UCHAR       OUI_WPA2_TKIP[4]        = {0x00, 0x0F, 0xAC, 0x02};
-UCHAR       OUI_WPA2_CCMP[4]        = {0x00, 0x0F, 0xAC, 0x04};
-UCHAR       OUI_WPA2_8021X_AKM[4]   = {0x00, 0x0F, 0xAC, 0x01};
-UCHAR       OUI_WPA2_PSK_AKM[4]   	= {0x00, 0x0F, 0xAC, 0x02};
-UCHAR       OUI_WPA2_WEP104[4]   = {0x00, 0x0F, 0xAC, 0x05};
-// MSA OUI
-UCHAR   	OUI_MSA_8021X_AKM[4]    = {0x00, 0x0F, 0xAC, 0x05};		// Not yet final - IEEE 802.11s-D1.06
-UCHAR   	OUI_MSA_PSK_AKM[4]   	= {0x00, 0x0F, 0xAC, 0x06};		// Not yet final - IEEE 802.11s-D1.06
-
-/*
-	========================================================================
-
-	Routine Description:
-		The pseudo-random function(PRF) that hashes various inputs to
-		derive a pseudo-random value. To add liveness to the pseudo-random
-		value, a nonce should be one of the inputs.
-
-		It is used to generate PTK, GTK or some specific random value.
-
-	Arguments:
-		UCHAR	*key,		-	the key material for HMAC_SHA1 use
-		INT		key_len		-	the length of key
-		UCHAR	*prefix		-	a prefix label
-		INT		prefix_len	-	the length of the label
-		UCHAR	*data		-	a specific data with variable length
-		INT		data_len	-	the length of a specific data
-		INT		len			-	the output lenght
-
-	Return Value:
-		UCHAR	*output		-	the calculated result
-
-	Note:
-		802.11i-2004	Annex H.3
-
-	========================================================================
-*/
-VOID	PRF(
-	IN	UCHAR	*key,
-	IN	INT		key_len,
-	IN	UCHAR	*prefix,
-	IN	INT		prefix_len,
-	IN	UCHAR	*data,
-	IN	INT		data_len,
-	OUT	UCHAR	*output,
-	IN	INT		len)
-{
-	INT		i;
-    UCHAR   *input;
-	INT		currentindex = 0;
-	INT		total_len;
-
-	// Allocate memory for input
-	os_alloc_mem(NULL, (PUCHAR *)&input, 1024);
-
-    if (input == NULL)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("!!!PRF: no memory!!!\n"));
-        return;
-    }
-
-	// Generate concatenation input
-	NdisMoveMemory(input, prefix, prefix_len);
-
-	// Concatenate a single octet containing 0
-	input[prefix_len] =	0;
-
-	// Concatenate specific data
-	NdisMoveMemory(&input[prefix_len + 1], data, data_len);
-	total_len =	prefix_len + 1 + data_len;
-
-	// Concatenate a single octet containing 0
-	// This octet shall be update later
-	input[total_len] = 0;
-	total_len++;
-
-	// Iterate to calculate the result by hmac-sha-1
-	// Then concatenate to last result
-	for	(i = 0;	i <	(len + 19) / 20; i++)
-	{
-		HMAC_SHA1(input, total_len,	key, key_len, &output[currentindex]);
-		currentindex +=	20;
-
-		// update the last octet
-		input[total_len - 1]++;
-	}
-    os_free_mem(NULL, input);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		It utilizes PRF-384 or PRF-512 to derive session-specific keys from a PMK.
-		It shall be called by 4-way handshake processing.
-
-	Arguments:
-		pAd 	-	pointer to our pAdapter context
-		PMK		-	pointer to PMK
-		ANonce	-	pointer to ANonce
-		AA		-	pointer to Authenticator Address
-		SNonce	-	pointer to SNonce
-		SA		-	pointer to Supplicant Address
-		len		-	indicate the length of PTK (octet)
-
-	Return Value:
-		Output		pointer to the PTK
-
-	Note:
-		Refer to IEEE 802.11i-2004 8.5.1.2
-
-	========================================================================
-*/
-VOID WpaCountPTK(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR	*PMK,
-	IN	UCHAR	*ANonce,
-	IN	UCHAR	*AA,
-	IN	UCHAR	*SNonce,
-	IN	UCHAR	*SA,
-	OUT	UCHAR	*output,
-	IN	UINT	len)
-{
-	UCHAR	concatenation[76];
-	UINT	CurrPos = 0;
-	UCHAR	temp[32];
-	UCHAR	Prefix[] = {'P', 'a', 'i', 'r', 'w', 'i', 's', 'e', ' ', 'k', 'e', 'y', ' ',
-						'e', 'x', 'p', 'a', 'n', 's', 'i', 'o', 'n'};
-
-	// initiate the concatenation input
-	NdisZeroMemory(temp, sizeof(temp));
-	NdisZeroMemory(concatenation, 76);
-
-	// Get smaller address
-	if (RTMPCompareMemory(SA, AA, 6) == 1)
-		NdisMoveMemory(concatenation, AA, 6);
-	else
-		NdisMoveMemory(concatenation, SA, 6);
-	CurrPos += 6;
-
-	// Get larger address
-	if (RTMPCompareMemory(SA, AA, 6) == 1)
-		NdisMoveMemory(&concatenation[CurrPos], SA, 6);
-	else
-		NdisMoveMemory(&concatenation[CurrPos], AA, 6);
-
-	// store the larger mac address for backward compatible of
-	// ralink proprietary STA-key issue
-	NdisMoveMemory(temp, &concatenation[CurrPos], MAC_ADDR_LEN);
-	CurrPos += 6;
-
-	// Get smaller Nonce
-	if (RTMPCompareMemory(ANonce, SNonce, 32) == 0)
-		NdisMoveMemory(&concatenation[CurrPos], temp, 32);	// patch for ralink proprietary STA-key issue
-	else if (RTMPCompareMemory(ANonce, SNonce, 32) == 1)
-		NdisMoveMemory(&concatenation[CurrPos], SNonce, 32);
-	else
-		NdisMoveMemory(&concatenation[CurrPos], ANonce, 32);
-	CurrPos += 32;
-
-	// Get larger Nonce
-	if (RTMPCompareMemory(ANonce, SNonce, 32) == 0)
-		NdisMoveMemory(&concatenation[CurrPos], temp, 32);	// patch for ralink proprietary STA-key issue
-	else if (RTMPCompareMemory(ANonce, SNonce, 32) == 1)
-		NdisMoveMemory(&concatenation[CurrPos], ANonce, 32);
-	else
-		NdisMoveMemory(&concatenation[CurrPos], SNonce, 32);
-	CurrPos += 32;
-
-	hex_dump("concatenation=", concatenation, 76);
-
-	// Use PRF to generate PTK
-	PRF(PMK, LEN_MASTER_KEY, Prefix, 22, concatenation, 76, output, len);
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Generate random number by software.
-
-	Arguments:
-		pAd		-	pointer to our pAdapter context
-		macAddr	-	pointer to local MAC address
-
-	Return Value:
-
-	Note:
-		802.1ii-2004  Annex H.5
-
-	========================================================================
-*/
-VOID	GenRandom(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			*macAddr,
-	OUT	UCHAR			*random)
-{
-	INT		i, curr;
-	UCHAR	local[80], KeyCounter[32];
-	UCHAR	result[80];
-	ULONG	CurrentTime;
-	UCHAR	prefix[] = {'I', 'n', 'i', 't', ' ', 'C', 'o', 'u', 'n', 't', 'e', 'r'};
-
-	// Zero the related information
-	NdisZeroMemory(result, 80);
-	NdisZeroMemory(local, 80);
-	NdisZeroMemory(KeyCounter, 32);
-
-	for	(i = 0;	i <	32;	i++)
-	{
-		// copy the local MAC address
-		COPY_MAC_ADDR(local, macAddr);
-		curr =	MAC_ADDR_LEN;
-
-		// concatenate the current time
-		NdisGetSystemUpTime(&CurrentTime);
-		NdisMoveMemory(&local[curr],  &CurrentTime,	sizeof(CurrentTime));
-		curr +=	sizeof(CurrentTime);
-
-		// concatenate the last result
-		NdisMoveMemory(&local[curr],  result, 32);
-		curr +=	32;
-
-		// concatenate a variable
-		NdisMoveMemory(&local[curr],  &i,  2);
-		curr +=	2;
-
-		// calculate the result
-		PRF(KeyCounter, 32, prefix,12, local, curr, result, 32);
-	}
-
-	NdisMoveMemory(random, result,	32);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Build cipher suite in RSN-IE.
-		It only shall be called by RTMPMakeRSNIE.
-
-	Arguments:
-		pAd			-	pointer to our pAdapter context
-    	ElementID	-	indicate the WPA1 or WPA2
-    	WepStatus	-	indicate the encryption type
-		bMixCipher	-	a boolean to indicate the pairwise cipher and group
-						cipher are the same or not
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-static VOID RTMPInsertRsnIeCipher(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			ElementID,
-	IN	UINT			WepStatus,
-	IN	BOOLEAN			bMixCipher,
-	IN	UCHAR			FlexibleCipher,
-	OUT	PUCHAR			pRsnIe,
-	OUT	UCHAR			*rsn_len)
-{
-	UCHAR	PairwiseCnt;
-
-	*rsn_len = 0;
-
-	// decide WPA2 or WPA1
-	if (ElementID == Wpa2Ie)
-	{
-		RSNIE2	*pRsnie_cipher = (RSNIE2*)pRsnIe;
-
-		// Assign the verson as 1
-		pRsnie_cipher->version = 1;
-
-        switch (WepStatus)
-        {
-        	// TKIP mode
-            case Ndis802_11Encryption2Enabled:
-                NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_TKIP, 4);
-                pRsnie_cipher->ucount = 1;
-                NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_TKIP, 4);
-                *rsn_len = sizeof(RSNIE2);
-                break;
-
-			// AES mode
-            case Ndis802_11Encryption3Enabled:
-				if (bMixCipher)
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_TKIP, 4);
-				else
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_CCMP, 4);
-                pRsnie_cipher->ucount = 1;
-                NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_CCMP, 4);
-                *rsn_len = sizeof(RSNIE2);
-                break;
-
-			// TKIP-AES mix mode
-            case Ndis802_11Encryption4Enabled:
-                NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_TKIP, 4);
-
-				PairwiseCnt = 1;
-				// Insert WPA2 TKIP as the first pairwise cipher
-				if (MIX_CIPHER_WPA2_TKIP_ON(FlexibleCipher))
-				{
-                	NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_TKIP, 4);
-					// Insert WPA2 AES as the secondary pairwise cipher
-					if (MIX_CIPHER_WPA2_AES_ON(FlexibleCipher))
-					{
-                		NdisMoveMemory(pRsnie_cipher->ucast[0].oui + 4, OUI_WPA2_CCMP, 4);
-						PairwiseCnt = 2;
-					}
-				}
-				else
-				{
-					// Insert WPA2 AES as the first pairwise cipher
-					NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_CCMP, 4);
-				}
-
-                pRsnie_cipher->ucount = PairwiseCnt;
-                *rsn_len = sizeof(RSNIE2) + (4 * (PairwiseCnt - 1));
-                break;
-        }
-
-#ifdef CONFIG_STA_SUPPORT
-		if ((pAd->OpMode == OPMODE_STA) &&
-			(pAd->StaCfg.GroupCipher != Ndis802_11Encryption2Enabled) &&
-			(pAd->StaCfg.GroupCipher != Ndis802_11Encryption3Enabled))
-		{
-			UINT GroupCipher = pAd->StaCfg.GroupCipher;
-			switch(GroupCipher)
-			{
-				case Ndis802_11GroupWEP40Enabled:
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_WEP40, 4);
-					break;
-				case Ndis802_11GroupWEP104Enabled:
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_WEP104, 4);
-					break;
-			}
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		// swap for big-endian platform
-		pRsnie_cipher->version = cpu2le16(pRsnie_cipher->version);
-	    pRsnie_cipher->ucount = cpu2le16(pRsnie_cipher->ucount);
-	}
-	else
-	{
-		RSNIE	*pRsnie_cipher = (RSNIE*)pRsnIe;
-
-		// Assign OUI and version
-		NdisMoveMemory(pRsnie_cipher->oui, OUI_WPA_VERSION, 4);
-        pRsnie_cipher->version = 1;
-
-		switch (WepStatus)
-		{
-			// TKIP mode
-            case Ndis802_11Encryption2Enabled:
-                NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_TKIP, 4);
-                pRsnie_cipher->ucount = 1;
-                NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_TKIP, 4);
-                *rsn_len = sizeof(RSNIE);
-                break;
-
-			// AES mode
-            case Ndis802_11Encryption3Enabled:
-				if (bMixCipher)
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_TKIP, 4);
-				else
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_CCMP, 4);
-                pRsnie_cipher->ucount = 1;
-                NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_CCMP, 4);
-                *rsn_len = sizeof(RSNIE);
-                break;
-
-			// TKIP-AES mix mode
-            case Ndis802_11Encryption4Enabled:
-                NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_TKIP, 4);
-
-				PairwiseCnt = 1;
-				// Insert WPA TKIP as the first pairwise cipher
-				if (MIX_CIPHER_WPA_TKIP_ON(FlexibleCipher))
-				{
-                	NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_TKIP, 4);
-					// Insert WPA AES as the secondary pairwise cipher
-					if (MIX_CIPHER_WPA_AES_ON(FlexibleCipher))
-					{
-                		NdisMoveMemory(pRsnie_cipher->ucast[0].oui + 4, OUI_WPA_CCMP, 4);
-						PairwiseCnt = 2;
-					}
-				}
-				else
-				{
-					// Insert WPA AES as the first pairwise cipher
-					NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_CCMP, 4);
-				}
-
-                pRsnie_cipher->ucount = PairwiseCnt;
-                *rsn_len = sizeof(RSNIE) + (4 * (PairwiseCnt - 1));
-                break;
-        }
-
-#ifdef CONFIG_STA_SUPPORT
-		if ((pAd->OpMode == OPMODE_STA) &&
-			(pAd->StaCfg.GroupCipher != Ndis802_11Encryption2Enabled) &&
-			(pAd->StaCfg.GroupCipher != Ndis802_11Encryption3Enabled))
-		{
-			UINT GroupCipher = pAd->StaCfg.GroupCipher;
-			switch(GroupCipher)
-			{
-				case Ndis802_11GroupWEP40Enabled:
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_WEP40, 4);
-					break;
-				case Ndis802_11GroupWEP104Enabled:
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_WEP104, 4);
-					break;
-			}
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		// swap for big-endian platform
-		pRsnie_cipher->version = cpu2le16(pRsnie_cipher->version);
-	    pRsnie_cipher->ucount = cpu2le16(pRsnie_cipher->ucount);
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Build AKM suite in RSN-IE.
-		It only shall be called by RTMPMakeRSNIE.
-
-	Arguments:
-		pAd			-	pointer to our pAdapter context
-    	ElementID	-	indicate the WPA1 or WPA2
-    	AuthMode	-	indicate the authentication mode
-		apidx		-	indicate the interface index
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-static VOID RTMPInsertRsnIeAKM(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			ElementID,
-	IN	UINT			AuthMode,
-	IN	UCHAR			apidx,
-	OUT	PUCHAR			pRsnIe,
-	OUT	UCHAR			*rsn_len)
-{
-	RSNIE_AUTH		*pRsnie_auth;
-
-	pRsnie_auth = (RSNIE_AUTH*)(pRsnIe + (*rsn_len));
-
-	// decide WPA2 or WPA1
-	if (ElementID == Wpa2Ie)
-	{
-		switch (AuthMode)
-        {
-            case Ndis802_11AuthModeWPA2:
-            case Ndis802_11AuthModeWPA1WPA2:
-                pRsnie_auth->acount = 1;
-                	NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA2_8021X_AKM, 4);
-                break;
-
-            case Ndis802_11AuthModeWPA2PSK:
-            case Ndis802_11AuthModeWPA1PSKWPA2PSK:
-                pRsnie_auth->acount = 1;
-                	NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA2_PSK_AKM, 4);
-                break;
-        }
-	}
-	else
-	{
-		switch (AuthMode)
-        {
-            case Ndis802_11AuthModeWPA:
-            case Ndis802_11AuthModeWPA1WPA2:
-                pRsnie_auth->acount = 1;
-                NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA_8021X_AKM, 4);
-                break;
-
-            case Ndis802_11AuthModeWPAPSK:
-            case Ndis802_11AuthModeWPA1PSKWPA2PSK:
-                pRsnie_auth->acount = 1;
-                NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA_PSK_AKM, 4);
-                break;
-
-			case Ndis802_11AuthModeWPANone:
-                pRsnie_auth->acount = 1;
-                NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA_NONE_AKM, 4);
-                break;
-        }
-	}
-
-	pRsnie_auth->acount = cpu2le16(pRsnie_auth->acount);
-
-	(*rsn_len) += sizeof(RSNIE_AUTH);	// update current RSNIE length
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Build capability in RSN-IE.
-		It only shall be called by RTMPMakeRSNIE.
-
-	Arguments:
-		pAd			-	pointer to our pAdapter context
-    	ElementID	-	indicate the WPA1 or WPA2
-		apidx		-	indicate the interface index
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-static VOID RTMPInsertRsnIeCap(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			ElementID,
-	IN	UCHAR			apidx,
-	OUT	PUCHAR			pRsnIe,
-	OUT	UCHAR			*rsn_len)
-{
-	RSN_CAPABILITIES    *pRSN_Cap;
-
-	// it could be ignored in WPA1 mode
-	if (ElementID == WpaIe)
-		return;
-
-	pRSN_Cap = (RSN_CAPABILITIES*)(pRsnIe + (*rsn_len));
-
-
-	pRSN_Cap->word = cpu2le16(pRSN_Cap->word);
-
-	(*rsn_len) += sizeof(RSN_CAPABILITIES);	// update current RSNIE length
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Build RSN IE context. It is not included element-ID and length.
-
-	Arguments:
-		pAd			-	pointer to our pAdapter context
-    	AuthMode	-	indicate the authentication mode
-    	WepStatus	-	indicate the encryption type
-		apidx		-	indicate the interface index
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID RTMPMakeRSNIE(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  UINT            AuthMode,
-    IN  UINT            WepStatus,
-	IN	UCHAR			apidx)
-{
-	PUCHAR		pRsnIe = NULL;			// primary RSNIE
-	UCHAR 		*rsnielen_cur_p = 0;	// the length of the primary RSNIE
-	UCHAR		*rsnielen_ex_cur_p = 0;	// the length of the secondary RSNIE
-	UCHAR		PrimaryRsnie;
-	BOOLEAN		bMixCipher = FALSE;	// indicate the pairwise and group cipher are different
-	UCHAR		p_offset;
-	WPA_MIX_PAIR_CIPHER		FlexibleCipher = MIX_CIPHER_NOTUSE;	// it provide the more flexible cipher combination in WPA-WPA2 and TKIPAES mode
-
-	rsnielen_cur_p = NULL;
-	rsnielen_ex_cur_p = NULL;
-
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-#ifdef WPA_SUPPLICANT_SUPPORT
-			if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-			{
-				if (AuthMode < Ndis802_11AuthModeWPA)
-					return;
-			}
-			else
-#endif // WPA_SUPPLICANT_SUPPORT //
-			{
-				// Support WPAPSK or WPA2PSK in STA-Infra mode
-				// Support WPANone in STA-Adhoc mode
-				if ((AuthMode != Ndis802_11AuthModeWPAPSK) &&
-					(AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-					(AuthMode != Ndis802_11AuthModeWPANone)
-					)
-					return;
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE,("==> RTMPMakeRSNIE(STA)\n"));
-
-			// Zero RSNIE context
-			pAd->StaCfg.RSNIE_Len = 0;
-			NdisZeroMemory(pAd->StaCfg.RSN_IE, MAX_LEN_OF_RSNIE);
-
-			// Pointer to RSNIE
-			rsnielen_cur_p = &pAd->StaCfg.RSNIE_Len;
-			pRsnIe = pAd->StaCfg.RSN_IE;
-
-			bMixCipher = pAd->StaCfg.bMixCipher;
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	// indicate primary RSNIE as WPA or WPA2
-	if ((AuthMode == Ndis802_11AuthModeWPA) ||
-		(AuthMode == Ndis802_11AuthModeWPAPSK) ||
-		(AuthMode == Ndis802_11AuthModeWPANone) ||
-		(AuthMode == Ndis802_11AuthModeWPA1WPA2) ||
-		(AuthMode == Ndis802_11AuthModeWPA1PSKWPA2PSK))
-		PrimaryRsnie = WpaIe;
-	else
-		PrimaryRsnie = Wpa2Ie;
-
-	{
-		// Build the primary RSNIE
-		// 1. insert cipher suite
-		RTMPInsertRsnIeCipher(pAd, PrimaryRsnie, WepStatus, bMixCipher, FlexibleCipher, pRsnIe, &p_offset);
-
-		// 2. insert AKM
-		RTMPInsertRsnIeAKM(pAd, PrimaryRsnie, AuthMode, apidx, pRsnIe, &p_offset);
-
-		// 3. insert capability
-		RTMPInsertRsnIeCap(pAd, PrimaryRsnie, apidx, pRsnIe, &p_offset);
-	}
-
-	// 4. update the RSNIE length
-	*rsnielen_cur_p = p_offset;
-
-	hex_dump("The primary RSNIE", pRsnIe, (*rsnielen_cur_p));
-
-
-}
-
-/*
-    ==========================================================================
-    Description:
-		Check whether the received frame is EAP frame.
-
-	Arguments:
-		pAd				-	pointer to our pAdapter context
-		pEntry			-	pointer to active entry
-		pData			-	the received frame
-		DataByteCount 	-	the received frame's length
-		FromWhichBSSID	-	indicate the interface index
-
-    Return:
-         TRUE 			-	This frame is EAP frame
-         FALSE 			-	otherwise
-    ==========================================================================
-*/
-BOOLEAN RTMPCheckWPAframe(
-    IN PRTMP_ADAPTER    pAd,
-    IN PMAC_TABLE_ENTRY	pEntry,
-    IN PUCHAR           pData,
-    IN ULONG            DataByteCount,
-	IN UCHAR			FromWhichBSSID)
-{
-	ULONG	Body_len;
-	BOOLEAN Cancelled;
-
-
-    if(DataByteCount < (LENGTH_802_1_H + LENGTH_EAPOL_H))
-        return FALSE;
-
-
-	// Skip LLC header
-    if (NdisEqualMemory(SNAP_802_1H, pData, 6) ||
-        // Cisco 1200 AP may send packet with SNAP_BRIDGE_TUNNEL
-        NdisEqualMemory(SNAP_BRIDGE_TUNNEL, pData, 6))
-    {
-        pData += 6;
-    }
-	// Skip 2-bytes EAPoL type
-    if (NdisEqualMemory(EAPOL, pData, 2))
-    {
-        pData += 2;
-    }
-    else
-        return FALSE;
-
-    switch (*(pData+1))
-    {
-        case EAPPacket:
-			Body_len = (*(pData+2)<<8) | (*(pData+3));
-            DBGPRINT(RT_DEBUG_TRACE, ("Receive EAP-Packet frame, TYPE = 0, Length = %ld\n", Body_len));
-            break;
-        case EAPOLStart:
-            DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL-Start frame, TYPE = 1 \n"));
-			if (pEntry->EnqueueEapolStartTimerRunning != EAPOL_START_DISABLE)
-            {
-            	DBGPRINT(RT_DEBUG_TRACE, ("Cancel the EnqueueEapolStartTimerRunning \n"));
-                RTMPCancelTimer(&pEntry->EnqueueStartForPSKTimer, &Cancelled);
-                pEntry->EnqueueEapolStartTimerRunning = EAPOL_START_DISABLE;
-            }
-            break;
-        case EAPOLLogoff:
-            DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOLLogoff frame, TYPE = 2 \n"));
-            break;
-        case EAPOLKey:
-			Body_len = (*(pData+2)<<8) | (*(pData+3));
-            DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL-Key frame, TYPE = 3, Length = %ld\n", Body_len));
-            break;
-        case EAPOLASFAlert:
-            DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOLASFAlert frame, TYPE = 4 \n"));
-            break;
-        default:
-            return FALSE;
-
-    }
-    return TRUE;
-}
-
-
-/*
-    ==========================================================================
-    Description:
-        ENCRYPT AES GTK before sending in EAPOL frame.
-        AES GTK length = 128 bit,  so fix blocks for aes-key-wrap as 2 in this function.
-        This function references to RFC 3394 for aes key wrap algorithm.
-    Return:
-    ==========================================================================
-*/
-VOID AES_GTK_KEY_WRAP(
-    IN UCHAR    *key,
-    IN UCHAR    *plaintext,
-    IN UCHAR    p_len,
-    OUT UCHAR   *ciphertext)
-{
-    UCHAR       A[8], BIN[16], BOUT[16];
-    UCHAR       R[512];
-    INT         num_blocks = p_len/8;   // unit:64bits
-    INT         i, j;
-    aes_context aesctx;
-    UCHAR       xor;
-
-    rtmp_aes_set_key(&aesctx, key, 128);
-
-    // Init IA
-    for (i = 0; i < 8; i++)
-        A[i] = 0xa6;
-
-    //Input plaintext
-    for (i = 0; i < num_blocks; i++)
-    {
-        for (j = 0 ; j < 8; j++)
-            R[8 * (i + 1) + j] = plaintext[8 * i + j];
-    }
-
-    // Key Mix
-    for (j = 0; j < 6; j++)
-    {
-        for(i = 1; i <= num_blocks; i++)
-        {
-            //phase 1
-            NdisMoveMemory(BIN, A, 8);
-            NdisMoveMemory(&BIN[8], &R[8 * i], 8);
-            rtmp_aes_encrypt(&aesctx, BIN, BOUT);
-
-            NdisMoveMemory(A, &BOUT[0], 8);
-            xor = num_blocks * j + i;
-            A[7] = BOUT[7] ^ xor;
-            NdisMoveMemory(&R[8 * i], &BOUT[8], 8);
-        }
-    }
-
-    // Output ciphertext
-    NdisMoveMemory(ciphertext, A, 8);
-
-    for (i = 1; i <= num_blocks; i++)
-    {
-        for (j = 0 ; j < 8; j++)
-            ciphertext[8 * i + j] = R[8 * i + j];
-    }
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Misc function to decrypt AES body
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-		This function references to	RFC	3394 for aes key unwrap algorithm.
-
-	========================================================================
-*/
-VOID	AES_GTK_KEY_UNWRAP(
-	IN	UCHAR	*key,
-	OUT	UCHAR	*plaintext,
-	IN	UCHAR    c_len,
-	IN	UCHAR	*ciphertext)
-
-{
-	UCHAR       A[8], BIN[16], BOUT[16];
-	UCHAR       xor;
-	INT         i, j;
-	aes_context aesctx;
-	UCHAR       *R;
-	INT         num_blocks = c_len/8;	// unit:64bits
-
-
-	os_alloc_mem(NULL, (PUCHAR *)&R, 512);
-
-	if (R == NULL)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("!!!AES_GTK_KEY_UNWRAP: no memory!!!\n"));
-        return;
-    } /* End of if */
-
-	// Initialize
-	NdisMoveMemory(A, ciphertext, 8);
-	//Input plaintext
-	for(i = 0; i < (c_len-8); i++)
-	{
-		R[ i] = ciphertext[i + 8];
-	}
-
-	rtmp_aes_set_key(&aesctx, key, 128);
-
-	for(j = 5; j >= 0; j--)
-	{
-		for(i = (num_blocks-1); i > 0; i--)
-		{
-			xor = (num_blocks -1 )* j + i;
-			NdisMoveMemory(BIN, A, 8);
-			BIN[7] = A[7] ^ xor;
-			NdisMoveMemory(&BIN[8], &R[(i-1)*8], 8);
-			rtmp_aes_decrypt(&aesctx, BIN, BOUT);
-			NdisMoveMemory(A, &BOUT[0], 8);
-			NdisMoveMemory(&R[(i-1)*8], &BOUT[8], 8);
-		}
-	}
-
-	// OUTPUT
-	for(i = 0; i < c_len; i++)
-	{
-		plaintext[i] = R[i];
-	}
-
-
-	os_free_mem(NULL, R);
-}
-
-/*
-    ==========================================================================
-    Description:
-		Report the EAP message type
-
-	Arguments:
-		msg		-	EAPOL_PAIR_MSG_1
-					EAPOL_PAIR_MSG_2
-					EAPOL_PAIR_MSG_3
-					EAPOL_PAIR_MSG_4
-					EAPOL_GROUP_MSG_1
-					EAPOL_GROUP_MSG_2
-
-    Return:
-         message type string
-
-    ==========================================================================
-*/
-CHAR *GetEapolMsgType(CHAR msg)
-{
-    if(msg == EAPOL_PAIR_MSG_1)
-        return "Pairwise Message 1";
-    else if(msg == EAPOL_PAIR_MSG_2)
-        return "Pairwise Message 2";
-	else if(msg == EAPOL_PAIR_MSG_3)
-        return "Pairwise Message 3";
-	else if(msg == EAPOL_PAIR_MSG_4)
-        return "Pairwise Message 4";
-	else if(msg == EAPOL_GROUP_MSG_1)
-        return "Group Message 1";
-	else if(msg == EAPOL_GROUP_MSG_2)
-        return "Group Message 2";
-    else
-    	return "Invalid Message";
-}
-
-
-/*
-    ========================================================================
-
-    Routine Description:
-    Check Sanity RSN IE of EAPoL message
-
-    Arguments:
-
-    Return Value:
-
-
-    ========================================================================
-*/
-BOOLEAN RTMPCheckRSNIE(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pData,
-	IN  UCHAR           DataLen,
-	IN  MAC_TABLE_ENTRY *pEntry,
-	OUT	UCHAR			*Offset)
-{
-	PUCHAR              pVIE;
-	UCHAR               len;
-	PEID_STRUCT         pEid;
-	BOOLEAN				result = FALSE;
-
-	pVIE = pData;
-	len	 = DataLen;
-	*Offset = 0;
-
-	while (len > sizeof(RSNIE2))
-	{
-		pEid = (PEID_STRUCT) pVIE;
-		// WPA RSN IE
-		if ((pEid->Eid == IE_WPA) && (NdisEqualMemory(pEid->Octet, WPA_OUI, 4)))
-		{
-			if ((pEntry->AuthMode == Ndis802_11AuthModeWPA || pEntry->AuthMode == Ndis802_11AuthModeWPAPSK) &&
-				(NdisEqualMemory(pVIE, pEntry->RSN_IE, pEntry->RSNIE_Len)) &&
-				(pEntry->RSNIE_Len == (pEid->Len + 2)))
-			{
-					result = TRUE;
-			}
-
-			*Offset += (pEid->Len + 2);
-		}
-		// WPA2 RSN IE
-		else if ((pEid->Eid == IE_RSN) && (NdisEqualMemory(pEid->Octet + 2, RSN_OUI, 3)))
-		{
-			if ((pEntry->AuthMode == Ndis802_11AuthModeWPA2 || pEntry->AuthMode == Ndis802_11AuthModeWPA2PSK) &&
-				(NdisEqualMemory(pVIE, pEntry->RSN_IE, pEntry->RSNIE_Len)) &&
-				(pEntry->RSNIE_Len == (pEid->Len + 2))/* ToDo-AlbertY for mesh*/)
-			{
-					result = TRUE;
-			}
-
-			*Offset += (pEid->Len + 2);
-		}
-		else
-		{
-			break;
-		}
-
-		pVIE += (pEid->Len + 2);
-		len  -= (pEid->Len + 2);
-	}
-
-
-	return result;
-
-}
-
-
-/*
-    ========================================================================
-
-    Routine Description:
-    Parse KEYDATA field.  KEYDATA[] May contain 2 RSN IE and optionally GTK.
-    GTK  is encaptulated in KDE format at  p.83 802.11i D10
-
-    Arguments:
-
-    Return Value:
-
-    Note:
-        802.11i D10
-
-    ========================================================================
-*/
-BOOLEAN RTMPParseEapolKeyData(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pKeyData,
-	IN  UCHAR           KeyDataLen,
-	IN	UCHAR			GroupKeyIndex,
-	IN	UCHAR			MsgType,
-	IN	BOOLEAN			bWPA2,
-	IN  MAC_TABLE_ENTRY *pEntry)
-{
-    PKDE_ENCAP          pKDE = NULL;
-    PUCHAR              pMyKeyData = pKeyData;
-    UCHAR               KeyDataLength = KeyDataLen;
-    UCHAR               GTKLEN = 0;
-	UCHAR				DefaultIdx = 0;
-	UCHAR				skip_offset;
-
-	// Verify The RSN IE contained in pairewise_msg_2 && pairewise_msg_3 and skip it
-	if (MsgType == EAPOL_PAIR_MSG_2 || MsgType == EAPOL_PAIR_MSG_3)
-    {
-		// Check RSN IE whether it is WPA2/WPA2PSK
-		if (!RTMPCheckRSNIE(pAd, pKeyData, KeyDataLen, pEntry, &skip_offset))
-		{
-			// send wireless event - for RSN IE different
-			if (pAd->CommonCfg.bWirelessEvent)
-				RTMPSendWirelessEvent(pAd, IW_RSNIE_DIFF_EVENT_FLAG, pEntry->Addr, pEntry->apidx, 0);
-
-        	DBGPRINT(RT_DEBUG_ERROR, ("RSN_IE Different in msg %d of 4-way handshake!\n", MsgType));
-			hex_dump("Receive RSN_IE ", pKeyData, KeyDataLen);
-			hex_dump("Desired RSN_IE ", pEntry->RSN_IE, pEntry->RSNIE_Len);
-
-			return FALSE;
-    	}
-    	else
-		{
-			if (bWPA2 && MsgType == EAPOL_PAIR_MSG_3)
-			{
-				// skip RSN IE
-				pMyKeyData += skip_offset;
-				KeyDataLength -= skip_offset;
-				DBGPRINT(RT_DEBUG_TRACE, ("RTMPParseEapolKeyData ==> WPA2/WPA2PSK RSN IE matched in Msg 3, Length(%d) \n", skip_offset));
-			}
-			else
-				return TRUE;
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("RTMPParseEapolKeyData ==> KeyDataLength %d without RSN_IE \n", KeyDataLength));
-
-	// Parse EKD format in pairwise_msg_3_WPA2 && group_msg_1_WPA2
-	if (bWPA2 && (MsgType == EAPOL_PAIR_MSG_3 || MsgType == EAPOL_GROUP_MSG_1))
-	{
-		if (KeyDataLength >= 8)	// KDE format exclude GTK length
-    	{
-        	pKDE = (PKDE_ENCAP) pMyKeyData;
-
-
-			DefaultIdx = pKDE->GTKEncap.Kid;
-
-			// Sanity check - KED length
-			if (KeyDataLength < (pKDE->Len + 2))
-    		{
-        		DBGPRINT(RT_DEBUG_ERROR, ("ERROR: The len from KDE is too short \n"));
-        		return FALSE;
-    		}
-
-			// Get GTK length - refer to IEEE 802.11i-2004 p.82
-			GTKLEN = pKDE->Len -6;
-			if (GTKLEN < LEN_AES_KEY)
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("ERROR: GTK Key length is too short (%d) \n", GTKLEN));
-        		return FALSE;
-			}
-
-    	}
-		else
-    	{
-			DBGPRINT(RT_DEBUG_ERROR, ("ERROR: KDE format length is too short \n"));
-	        return FALSE;
-    	}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("GTK in KDE format ,DefaultKeyID=%d, KeyLen=%d \n", DefaultIdx, GTKLEN));
-		// skip it
-		pMyKeyData += 8;
-		KeyDataLength -= 8;
-
-	}
-	else if (!bWPA2 && MsgType == EAPOL_GROUP_MSG_1)
-	{
-		DefaultIdx = GroupKeyIndex;
-		DBGPRINT(RT_DEBUG_TRACE, ("GTK DefaultKeyID=%d \n", DefaultIdx));
-	}
-
-	// Sanity check - shared key index must be 1 ~ 3
-	if (DefaultIdx < 1 || DefaultIdx > 3)
-    {
-     	DBGPRINT(RT_DEBUG_ERROR, ("ERROR: GTK Key index(%d) is invalid in %s %s \n", DefaultIdx, ((bWPA2) ? "WPA2" : "WPA"), GetEapolMsgType(MsgType)));
-        return FALSE;
-    }
-
-
-#ifdef CONFIG_STA_SUPPORT
-	// Todo
-#endif // CONFIG_STA_SUPPORT //
-
-	return TRUE;
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Construct EAPoL message for WPA handshaking
-		Its format is below,
-
-		+--------------------+
-		| Protocol Version	 |  1 octet
-		+--------------------+
-		| Protocol Type		 |	1 octet
-		+--------------------+
-		| Body Length		 |  2 octets
-		+--------------------+
-		| Descriptor Type	 |	1 octet
-		+--------------------+
-		| Key Information    |	2 octets
-		+--------------------+
-		| Key Length	     |  1 octet
-		+--------------------+
-		| Key Repaly Counter |	8 octets
-		+--------------------+
-		| Key Nonce		     |  32 octets
-		+--------------------+
-		| Key IV			 |  16 octets
-		+--------------------+
-		| Key RSC			 |  8 octets
-		+--------------------+
-		| Key ID or Reserved |	8 octets
-		+--------------------+
-		| Key MIC			 |	16 octets
-		+--------------------+
-		| Key Data Length	 |	2 octets
-		+--------------------+
-		| Key Data			 |	n octets
-		+--------------------+
-
-
-	Arguments:
-		pAd			Pointer	to our adapter
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	ConstructEapolMsg(
-	IN 	PRTMP_ADAPTER    	pAd,
-    IN 	UCHAR				AuthMode,
-    IN 	UCHAR				WepStatus,
-    IN 	UCHAR				GroupKeyWepStatus,
-    IN 	UCHAR				MsgType,
-    IN	UCHAR				DefaultKeyIdx,
-    IN 	UCHAR				*ReplayCounter,
-	IN 	UCHAR				*KeyNonce,
-	IN	UCHAR				*TxRSC,
-	IN	UCHAR				*PTK,
-	IN	UCHAR				*GTK,
-	IN	UCHAR				*RSNIE,
-	IN	UCHAR				RSNIE_Len,
-    OUT PEAPOL_PACKET       pMsg)
-{
-	BOOLEAN	bWPA2 = FALSE;
-
-	// Choose WPA2 or not
-	if ((AuthMode == Ndis802_11AuthModeWPA2) || (AuthMode == Ndis802_11AuthModeWPA2PSK))
-		bWPA2 = TRUE;
-
-    // Init Packet and Fill header
-    pMsg->ProVer = EAPOL_VER;
-    pMsg->ProType = EAPOLKey;
-
-	// Default 95 bytes, the EAPoL-Key descriptor exclude Key-data field
-	pMsg->Body_Len[1] = LEN_EAPOL_KEY_MSG;
-
-	// Fill in EAPoL descriptor
-	if (bWPA2)
-		pMsg->KeyDesc.Type = WPA2_KEY_DESC;
-	else
-		pMsg->KeyDesc.Type = WPA1_KEY_DESC;
-
-	// Fill in Key information, refer to IEEE Std 802.11i-2004 page 78
-	// When either the pairwise or the group cipher is AES, the DESC_TYPE_AES(2) shall be used.
-	pMsg->KeyDesc.KeyInfo.KeyDescVer =
-        	(((WepStatus == Ndis802_11Encryption3Enabled) || (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)) ? (DESC_TYPE_AES) : (DESC_TYPE_TKIP));
-
-	// Specify Key Type as Group(0) or Pairwise(1)
-	if (MsgType >= EAPOL_GROUP_MSG_1)
-		pMsg->KeyDesc.KeyInfo.KeyType = GROUPKEY;
-	else
-		pMsg->KeyDesc.KeyInfo.KeyType = PAIRWISEKEY;
-
-	// Specify Key Index, only group_msg1_WPA1
-	if (!bWPA2 && (MsgType >= EAPOL_GROUP_MSG_1))
-		pMsg->KeyDesc.KeyInfo.KeyIndex = DefaultKeyIdx;
-
-	if (MsgType == EAPOL_PAIR_MSG_3)
-		pMsg->KeyDesc.KeyInfo.Install = 1;
-
-	if ((MsgType == EAPOL_PAIR_MSG_1) || (MsgType == EAPOL_PAIR_MSG_3) || (MsgType == EAPOL_GROUP_MSG_1))
-		pMsg->KeyDesc.KeyInfo.KeyAck = 1;
-
-	if (MsgType != EAPOL_PAIR_MSG_1)
-		pMsg->KeyDesc.KeyInfo.KeyMic = 1;
-
-	if ((bWPA2 && (MsgType >= EAPOL_PAIR_MSG_3)) || (!bWPA2 && (MsgType >= EAPOL_GROUP_MSG_1)))
-    {
-       	pMsg->KeyDesc.KeyInfo.Secure = 1;
-    }
-
-	if (bWPA2 && ((MsgType == EAPOL_PAIR_MSG_3) || (MsgType == EAPOL_GROUP_MSG_1)))
-    {
-        pMsg->KeyDesc.KeyInfo.EKD_DL = 1;
-    }
-
-	// key Information element has done.
-	*(USHORT *)(&pMsg->KeyDesc.KeyInfo) = cpu2le16(*(USHORT *)(&pMsg->KeyDesc.KeyInfo));
-
-	// Fill in Key Length
-#if 0
-	if (bWPA2)
-	{
-		// In WPA2 mode, the field indicates the length of pairwise key cipher,
-		// so only pairwise_msg_1 and pairwise_msg_3 need to fill.
-		if ((MsgType == EAPOL_PAIR_MSG_1) || (MsgType == EAPOL_PAIR_MSG_3))
-			pMsg->KeyDesc.KeyLength[1] = ((WepStatus == Ndis802_11Encryption2Enabled) ? LEN_TKIP_KEY : LEN_AES_KEY);
-	}
-	else if (!bWPA2)
-#endif
-	{
-		if (MsgType >= EAPOL_GROUP_MSG_1)
-		{
-			// the length of group key cipher
-			pMsg->KeyDesc.KeyLength[1] = ((GroupKeyWepStatus == Ndis802_11Encryption2Enabled) ? TKIP_GTK_LENGTH : LEN_AES_KEY);
-		}
-		else
-		{
-			// the length of pairwise key cipher
-			pMsg->KeyDesc.KeyLength[1] = ((WepStatus == Ndis802_11Encryption2Enabled) ? LEN_TKIP_KEY : LEN_AES_KEY);
-		}
-	}
-
- 	// Fill in replay counter
-    NdisMoveMemory(pMsg->KeyDesc.ReplayCounter, ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Fill Key Nonce field
-	// ANonce : pairwise_msg1 & pairwise_msg3
-	// SNonce : pairwise_msg2
-	// GNonce : group_msg1_wpa1
-	if ((MsgType <= EAPOL_PAIR_MSG_3) || ((!bWPA2 && (MsgType == EAPOL_GROUP_MSG_1))))
-    	NdisMoveMemory(pMsg->KeyDesc.KeyNonce, KeyNonce, LEN_KEY_DESC_NONCE);
-
-	// Fill key IV - WPA2 as 0, WPA1 as random
-	if (!bWPA2 && (MsgType == EAPOL_GROUP_MSG_1))
-	{
-		// Suggest IV be random number plus some number,
-		NdisMoveMemory(pMsg->KeyDesc.KeyIv, &KeyNonce[16], LEN_KEY_DESC_IV);
-        pMsg->KeyDesc.KeyIv[15] += 2;
-	}
-
-    // Fill Key RSC field
-    // It contains the RSC for the GTK being installed.
-	if ((MsgType == EAPOL_PAIR_MSG_3 && bWPA2) || (MsgType == EAPOL_GROUP_MSG_1))
-	{
-        NdisMoveMemory(pMsg->KeyDesc.KeyRsc, TxRSC, 6);
-	}
-
-	// Clear Key MIC field for MIC calculation later
-    NdisZeroMemory(pMsg->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-
-	ConstructEapolKeyData(pAd,
-						  AuthMode,
-						  WepStatus,
-						  GroupKeyWepStatus,
-						  MsgType,
-						  DefaultKeyIdx,
-						  bWPA2,
-						  PTK,
-						  GTK,
-						  RSNIE,
-						  RSNIE_Len,
-						  pMsg);
-
-	// Calculate MIC and fill in KeyMic Field except Pairwise Msg 1.
-	if (MsgType != EAPOL_PAIR_MSG_1)
-	{
-		CalculateMIC(pAd, WepStatus, PTK, pMsg);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("===> ConstructEapolMsg for %s %s\n", ((bWPA2) ? "WPA2" : "WPA"), GetEapolMsgType(MsgType)));
-	DBGPRINT(RT_DEBUG_TRACE, ("	     Body length = %d \n", pMsg->Body_Len[1]));
-	DBGPRINT(RT_DEBUG_TRACE, ("	     Key length  = %d \n", pMsg->KeyDesc.KeyLength[1]));
-
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Construct the Key Data field of EAPoL message
-
-	Arguments:
-		pAd			Pointer	to our adapter
-		Elem		Message body
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	ConstructEapolKeyData(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			AuthMode,
-	IN	UCHAR			WepStatus,
-	IN	UCHAR			GroupKeyWepStatus,
-	IN 	UCHAR			MsgType,
-	IN	UCHAR			DefaultKeyIdx,
-	IN	BOOLEAN			bWPA2Capable,
-	IN	UCHAR			*PTK,
-	IN	UCHAR			*GTK,
-	IN	UCHAR			*RSNIE,
-	IN	UCHAR			RSNIE_LEN,
-	OUT PEAPOL_PACKET   pMsg)
-{
-	UCHAR		*mpool, *Key_Data, *Rc4GTK;
-	UCHAR       ekey[(LEN_KEY_DESC_IV+LEN_EAP_EK)];
-	UCHAR		data_offset;
-
-
-	if (MsgType == EAPOL_PAIR_MSG_1 || MsgType == EAPOL_PAIR_MSG_4 || MsgType == EAPOL_GROUP_MSG_2)
-		return;
-
-	// allocate memory pool
-	os_alloc_mem(pAd, (PUCHAR *)&mpool, 1500);
-
-    if (mpool == NULL)
-		return;
-
-	/* Rc4GTK Len = 512 */
-	Rc4GTK = (UCHAR *) ROUND_UP(mpool, 4);
-	/* Key_Data Len = 512 */
-	Key_Data = (UCHAR *) ROUND_UP(Rc4GTK + 512, 4);
-
-	NdisZeroMemory(Key_Data, 512);
-	pMsg->KeyDesc.KeyDataLen[1] = 0;
-	data_offset = 0;
-
-	// Encapsulate RSNIE in pairwise_msg2 & pairwise_msg3
-	if (RSNIE_LEN && ((MsgType == EAPOL_PAIR_MSG_2) || (MsgType == EAPOL_PAIR_MSG_3)))
-	{
-		if (bWPA2Capable)
-			Key_Data[data_offset + 0] = IE_WPA2;
-		else
-			Key_Data[data_offset + 0] = IE_WPA;
-
-        Key_Data[data_offset + 1] = RSNIE_LEN;
-		NdisMoveMemory(&Key_Data[data_offset + 2], RSNIE, RSNIE_LEN);
-		data_offset += (2 + RSNIE_LEN);
-	}
-
-	// Encapsulate KDE format in pairwise_msg3_WPA2 & group_msg1_WPA2
-	if (bWPA2Capable && ((MsgType == EAPOL_PAIR_MSG_3) || (MsgType == EAPOL_GROUP_MSG_1)))
-	{
-		// Key Data Encapsulation (KDE) format - 802.11i-2004  Figure-43w and Table-20h
-        Key_Data[data_offset + 0] = 0xDD;
-
-		if (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)
-		{
-			Key_Data[data_offset + 1] = 0x16;// 4+2+16(OUI+DataType+DataField)
-		}
-		else
-		{
-			Key_Data[data_offset + 1] = 0x26;// 4+2+32(OUI+DataType+DataField)
-		}
-
-        Key_Data[data_offset + 2] = 0x00;
-        Key_Data[data_offset + 3] = 0x0F;
-        Key_Data[data_offset + 4] = 0xAC;
-        Key_Data[data_offset + 5] = 0x01;
-
-		// GTK KDE format - 802.11i-2004  Figure-43x
-        Key_Data[data_offset + 6] = (DefaultKeyIdx & 0x03);
-        Key_Data[data_offset + 7] = 0x00;	// Reserved Byte
-
-		data_offset += 8;
-	}
-
-
-	// Encapsulate GTK and encrypt the key-data field with KEK.
-	// Only for pairwise_msg3_WPA2 and group_msg1
-	if ((MsgType == EAPOL_PAIR_MSG_3 && bWPA2Capable) || (MsgType == EAPOL_GROUP_MSG_1))
-	{
-		// Fill in GTK
-		if (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)
-		{
-			NdisMoveMemory(&Key_Data[data_offset], GTK, LEN_AES_KEY);
-			data_offset += LEN_AES_KEY;
-		}
-		else
-		{
-			NdisMoveMemory(&Key_Data[data_offset], GTK, TKIP_GTK_LENGTH);
-			data_offset += TKIP_GTK_LENGTH;
-		}
-
-		// Still dont know why, but if not append will occur "GTK not include in MSG3"
-		// Patch for compatibility between zero config and funk
-		if (MsgType == EAPOL_PAIR_MSG_3 && bWPA2Capable)
-		{
-			if (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)
-			{
-				Key_Data[data_offset + 0] = 0xDD;
-				Key_Data[data_offset + 1] = 0;
-				data_offset += 2;
-			}
-			else
-			{
-				Key_Data[data_offset + 0] = 0xDD;
-				Key_Data[data_offset + 1] = 0;
-				Key_Data[data_offset + 2] = 0;
-				Key_Data[data_offset + 3] = 0;
-				Key_Data[data_offset + 4] = 0;
-				Key_Data[data_offset + 5] = 0;
-				data_offset += 6;
-			}
-		}
-
-		// Encrypt the data material in key data field
-		if (WepStatus == Ndis802_11Encryption3Enabled)
-		{
-			AES_GTK_KEY_WRAP(&PTK[16], Key_Data, data_offset, Rc4GTK);
-            // AES wrap function will grow 8 bytes in length
-            data_offset += 8;
-		}
-		else
-		{
-			// PREPARE Encrypted  "Key DATA" field.  (Encrypt GTK with RC4, usinf PTK[16]->[31] as Key, IV-field as IV)
-			// put TxTsc in Key RSC field
-			pAd->PrivateInfo.FCSCRC32 = PPPINITFCS32;   //Init crc32.
-
-			// ekey is the contanetion of IV-field, and PTK[16]->PTK[31]
-			NdisMoveMemory(ekey, pMsg->KeyDesc.KeyIv, LEN_KEY_DESC_IV);
-			NdisMoveMemory(&ekey[LEN_KEY_DESC_IV], &PTK[16], LEN_EAP_EK);
-			ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, ekey, sizeof(ekey));  //INIT SBOX, KEYLEN+3(IV)
-			pAd->PrivateInfo.FCSCRC32 = RTMP_CALC_FCS32(pAd->PrivateInfo.FCSCRC32, Key_Data, data_offset);
-			WPAARCFOUR_ENCRYPT(&pAd->PrivateInfo.WEPCONTEXT, Rc4GTK, Key_Data, data_offset);
-		}
-
-		NdisMoveMemory(pMsg->KeyDesc.KeyData, Rc4GTK, data_offset);
-	}
-	else
-	{
-		NdisMoveMemory(pMsg->KeyDesc.KeyData, Key_Data, data_offset);
-	}
-
-	// set key data length field and total length
-	pMsg->KeyDesc.KeyDataLen[1] = data_offset;
-    pMsg->Body_Len[1] += data_offset;
-
-	os_free_mem(pAd, mpool);
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Calcaulate MIC. It is used during 4-ways handsharking.
-
-	Arguments:
-		pAd				-	pointer to our pAdapter context
-    	PeerWepStatus	-	indicate the encryption type
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	CalculateMIC(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			PeerWepStatus,
-	IN	UCHAR			*PTK,
-	OUT PEAPOL_PACKET   pMsg)
-{
-    UCHAR   *OutBuffer;
-	ULONG	FrameLen = 0;
-	UCHAR	mic[LEN_KEY_DESC_MIC];
-	UCHAR	digest[80];
-
-	// allocate memory for MIC calculation
-	os_alloc_mem(pAd, (PUCHAR *)&OutBuffer, 512);
-
-    if (OutBuffer == NULL)
-    {
-		DBGPRINT(RT_DEBUG_ERROR, ("!!!CalculateMIC: no memory!!!\n"));
-		return;
-    }
-
-	// make a frame for calculating MIC.
-    MakeOutgoingFrame(OutBuffer,            	&FrameLen,
-                      pMsg->Body_Len[1] + 4,  	pMsg,
-                      END_OF_ARGS);
-
-	NdisZeroMemory(mic, sizeof(mic));
-
-	// Calculate MIC
-    if (PeerWepStatus == Ndis802_11Encryption3Enabled)
- 	{
-		HMAC_SHA1(OutBuffer,  FrameLen, PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(PTK,  LEN_EAP_MICK, OutBuffer, FrameLen, mic);
-	}
-
-	// store the calculated MIC
-	NdisMoveMemory(pMsg->KeyDesc.KeyMic, mic, LEN_KEY_DESC_MIC);
-
-	os_free_mem(pAd, OutBuffer);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Some received frames can't decrypt by Asic, so decrypt them by software.
-
-	Arguments:
-		pAd				-	pointer to our pAdapter context
-    	PeerWepStatus	-	indicate the encryption type
-
-	Return Value:
-		NDIS_STATUS_SUCCESS		-	decryption successful
-		NDIS_STATUS_FAILURE		-	decryption failure
-
-	========================================================================
-*/
-NDIS_STATUS	RTMPSoftDecryptBroadCastData(
-	IN	PRTMP_ADAPTER					pAd,
-	IN	RX_BLK							*pRxBlk,
-	IN  NDIS_802_11_ENCRYPTION_STATUS 	GroupCipher,
-	IN  PCIPHER_KEY						pShard_key)
-{
-	PRXWI_STRUC			pRxWI = pRxBlk->pRxWI;
-
-
-
-	// handle WEP decryption
-	if (GroupCipher == Ndis802_11Encryption1Enabled)
-    {
-		if (RTMPSoftDecryptWEP(pAd, pRxBlk->pData, pRxWI->MPDUtotalByteCount, pShard_key))
-		{
-
-			//Minus IV[4] & ICV[4]
-			pRxWI->MPDUtotalByteCount -= 8;
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("ERROR : Software decrypt WEP data fails.\n"));
-			// give up this frame
-			return NDIS_STATUS_FAILURE;
-		}
-	}
-	// handle TKIP decryption
-	else if (GroupCipher == Ndis802_11Encryption2Enabled)
-	{
-		if (RTMPSoftDecryptTKIP(pAd, pRxBlk->pData, pRxWI->MPDUtotalByteCount, 0, pShard_key))
-		{
-
-			//Minus 8 bytes MIC, 8 bytes IV/EIV, 4 bytes ICV
-			pRxWI->MPDUtotalByteCount -= 20;
-		}
-        else
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("ERROR : RTMPSoftDecryptTKIP Failed\n"));
-			// give up this frame
-			return NDIS_STATUS_FAILURE;
-        }
-	}
-	// handle AES decryption
-	else if (GroupCipher == Ndis802_11Encryption3Enabled)
-	{
-		if (RTMPSoftDecryptAES(pAd, pRxBlk->pData, pRxWI->MPDUtotalByteCount , pShard_key))
-		{
-
-			//8 bytes MIC, 8 bytes IV/EIV (CCMP Header)
-			pRxWI->MPDUtotalByteCount -= 16;
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("ERROR : RTMPSoftDecryptAES Failed\n"));
-			// give up this frame
-			return NDIS_STATUS_FAILURE;
-		}
-	}
-	else
-	{
-		// give up this frame
-		return NDIS_STATUS_FAILURE;
-	}
-
-	return NDIS_STATUS_SUCCESS;
-
-}
-
+#include "../../rt2860/common/cmm_wpa.c"
diff --git a/drivers/staging/rt2870/common/dfs.c b/drivers/staging/rt2870/common/dfs.c
index b09bba5..ac2da4c 100644
--- a/drivers/staging/rt2870/common/dfs.c
+++ b/drivers/staging/rt2870/common/dfs.c
@@ -1,453 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    ap_dfs.c
-
-    Abstract:
-    Support DFS function.
-
-    Revision History:
-    Who       When            What
-    --------  ----------      ----------------------------------------------
-    Fonchi    03-12-2007      created
-*/
-
-#include "../rt_config.h"
-
-typedef struct _RADAR_DURATION_TABLE
-{
-	ULONG RDDurRegion;
-	ULONG RadarSignalDuration;
-	ULONG Tolerance;
-} RADAR_DURATION_TABLE, *PRADAR_DURATION_TABLE;
-
-
-static UCHAR RdIdleTimeTable[MAX_RD_REGION][4] =
-{
-	{9, 250, 250, 250},		// CE
-	{4, 250, 250, 250},		// FCC
-	{4, 250, 250, 250},		// JAP
-	{15, 250, 250, 250},	// JAP_W53
-	{4, 250, 250, 250}		// JAP_W56
-};
-
-/*
-	========================================================================
-
-	Routine Description:
-		Bbp Radar detection routine
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-
-	========================================================================
-*/
-VOID BbpRadarDetectionStart(
-	IN PRTMP_ADAPTER pAd)
-{
-	UINT8 RadarPeriod;
-
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 114, 0x02);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 121, 0x20);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 122, 0x00);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 123, 0x08/*0x80*/);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 124, 0x28);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 125, 0xff);
-
-#if 0
-	// toggle Rx enable bit for radar detection.
-	// it's Andy's recommand.
-	{
-		UINT32 Value;
-	RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-	Value |= (0x1 << 3);
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-	Value &= ~(0x1 << 3);
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-	}
-#endif
-	RadarPeriod = ((UINT)RdIdleTimeTable[pAd->CommonCfg.RadarDetect.RDDurRegion][0] + (UINT)pAd->CommonCfg.RadarDetect.DfsSessionTime) < 250 ?
-			(RdIdleTimeTable[pAd->CommonCfg.RadarDetect.RDDurRegion][0] + pAd->CommonCfg.RadarDetect.DfsSessionTime) : 250;
-
-	RTMP_IO_WRITE8(pAd, 0x7020, 0x1d);
-	RTMP_IO_WRITE8(pAd, 0x7021, 0x40);
-
-	RadarDetectionStart(pAd, 0, RadarPeriod);
-	return;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Bbp Radar detection routine
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-
-	========================================================================
-*/
-VOID BbpRadarDetectionStop(
-	IN PRTMP_ADAPTER pAd)
-{
-	RTMP_IO_WRITE8(pAd, 0x7020, 0x1d);
-	RTMP_IO_WRITE8(pAd, 0x7021, 0x60);
-
-	RadarDetectionStop(pAd);
-	return;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Radar detection routine
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-
-	========================================================================
-*/
-VOID RadarDetectionStart(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN CTSProtect,
-	IN UINT8 CTSPeriod)
-{
-	UINT8 DfsActiveTime = (pAd->CommonCfg.RadarDetect.DfsSessionTime & 0x1f);
-	UINT8 CtsProtect = (CTSProtect == 1) ? 0x02 : 0x01; // CTS protect.
-
-	if (CTSProtect != 0)
-	{
-		switch(pAd->CommonCfg.RadarDetect.RDDurRegion)
-		{
-		case FCC:
-		case JAP_W56:
-			CtsProtect = 0x03;
-			break;
-
-		case CE:
-		case JAP_W53:
-		default:
-			CtsProtect = 0x02;
-			break;
-		}
-	}
-	else
-		CtsProtect = 0x01;
-
-
-	// send start-RD with CTS protection command to MCU
-	// highbyte [7]		reserve
-	// highbyte [6:5]	0x: stop Carrier/Radar detection
-	// highbyte [10]:	Start Carrier/Radar detection without CTS protection, 11: Start Carrier/Radar detection with CTS protection
-	// highbyte [4:0]	Radar/carrier detection duration. In 1ms.
-
-	// lowbyte [7:0]	Radar/carrier detection period, in 1ms.
-	AsicSendCommandToMcu(pAd, 0x60, 0xff, CTSPeriod, DfsActiveTime | (CtsProtect << 5));
-	//AsicSendCommandToMcu(pAd, 0x63, 0xff, 10, 0);
-
-	return;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Radar detection routine
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-		TRUE	Found radar signal
-		FALSE	Not found radar signal
-
-	========================================================================
-*/
-VOID RadarDetectionStop(
-	IN PRTMP_ADAPTER	pAd)
-{
-	DBGPRINT(RT_DEBUG_TRACE,("RadarDetectionStop.\n"));
-	AsicSendCommandToMcu(pAd, 0x60, 0xff, 0x00, 0x00);	// send start-RD with CTS protection command to MCU
-
-	return;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Radar channel check routine
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-		TRUE	need to do radar detect
-		FALSE	need not to do radar detect
-
-	========================================================================
-*/
-BOOLEAN RadarChannelCheck(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			Ch)
-{
-#if 1
-	INT		i;
-	BOOLEAN result = FALSE;
-
-	for (i=0; i<pAd->ChannelListNum; i++)
-	{
-		if (Ch == pAd->ChannelList[i].Channel)
-		{
-			result = pAd->ChannelList[i].DfsReq;
-			break;
-		}
-	}
-
-	return result;
-#else
-	INT		i;
-	UCHAR	Channel[15]={52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140};
-
-	for (i=0; i<15; i++)
-	{
-		if (Ch == Channel[i])
-		{
-			break;
-		}
-	}
-
-	if (i != 15)
-		return TRUE;
-	else
-		return FALSE;
-#endif
-}
-
-ULONG JapRadarType(
-	IN PRTMP_ADAPTER pAd)
-{
-	ULONG		i;
-	const UCHAR	Channel[15]={52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140};
-
-	if (pAd->CommonCfg.RadarDetect.RDDurRegion != JAP)
-	{
-		return pAd->CommonCfg.RadarDetect.RDDurRegion;
-	}
-
-	for (i=0; i<15; i++)
-	{
-		if (pAd->CommonCfg.Channel == Channel[i])
-		{
-			break;
-		}
-	}
-
-	if (i < 4)
-		return JAP_W53;
-	else if (i < 15)
-		return JAP_W56;
-	else
-		return JAP; // W52
-
-}
-
-ULONG RTMPBbpReadRadarDuration(
-	IN PRTMP_ADAPTER	pAd)
-{
-	UINT8 byteValue = 0;
-	ULONG result;
-
-	BBP_IO_READ8_BY_REG_ID(pAd, BBP_R115, &byteValue);
-
-	result = 0;
-	switch (byteValue)
-	{
-	case 1: // radar signal detected by pulse mode.
-	case 2: // radar signal detected by width mode.
-		result = RTMPReadRadarDuration(pAd);
-		break;
-
-	case 0: // No radar signal.
-	default:
-
-		result = 0;
-		break;
-	}
-
-	return result;
-}
-
-ULONG RTMPReadRadarDuration(
-	IN PRTMP_ADAPTER	pAd)
-{
-	ULONG result = 0;
-
-#ifdef DFS_SUPPORT
-	UINT8 duration1 = 0, duration2 = 0, duration3 = 0;
-
-	BBP_IO_READ8_BY_REG_ID(pAd, BBP_R116, &duration1);
-	BBP_IO_READ8_BY_REG_ID(pAd, BBP_R117, &duration2);
-	BBP_IO_READ8_BY_REG_ID(pAd, BBP_R118, &duration3);
-	result = (duration1 << 16) + (duration2 << 8) + duration3;
-#endif // DFS_SUPPORT //
-
-	return result;
-
-}
-
-VOID RTMPCleanRadarDuration(
-	IN PRTMP_ADAPTER	pAd)
-{
-	return;
-}
-
-/*
-    ========================================================================
-    Routine Description:
-        Radar wave detection. The API should be invoke each second.
-
-    Arguments:
-        pAd         - Adapter pointer
-
-    Return Value:
-        None
-
-    ========================================================================
-*/
-VOID ApRadarDetectPeriodic(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT	i;
-
-	pAd->CommonCfg.RadarDetect.InServiceMonitorCount++;
-
-	for (i=0; i<pAd->ChannelListNum; i++)
-	{
-		if (pAd->ChannelList[i].RemainingTimeForUse > 0)
-		{
-			pAd->ChannelList[i].RemainingTimeForUse --;
-			if ((pAd->Mlme.PeriodicRound%5) == 0)
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("RadarDetectPeriodic - ch=%d, RemainingTimeForUse=%d\n", pAd->ChannelList[i].Channel, pAd->ChannelList[i].RemainingTimeForUse));
-			}
-		}
-	}
-
-	//radar detect
-	if ((pAd->CommonCfg.Channel > 14)
-		&& (pAd->CommonCfg.bIEEE80211H == 1)
-		&& RadarChannelCheck(pAd, pAd->CommonCfg.Channel))
-	{
-		RadarDetectPeriodic(pAd);
-	}
-
-	return;
-}
-
-// Periodic Radar detection, switch channel will occur in RTMPHandleTBTTInterrupt()
-// Before switch channel, driver needs doing channel switch announcement.
-VOID RadarDetectPeriodic(
-	IN PRTMP_ADAPTER	pAd)
-{
-	// need to check channel availability, after switch channel
-	if (pAd->CommonCfg.RadarDetect.RDMode != RD_SILENCE_MODE)
-			return;
-
-	// channel availability check time is 60sec, use 65 for assurance
-	if (pAd->CommonCfg.RadarDetect.RDCount++ > pAd->CommonCfg.RadarDetect.ChMovingTime)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("Not found radar signal, start send beacon and radar detection in service monitor\n\n"));
-			BbpRadarDetectionStop(pAd);
-		AsicEnableBssSync(pAd);
-		pAd->CommonCfg.RadarDetect.RDMode = RD_NORMAL_MODE;
-
-
-		return;
-	}
-
-	return;
-}
-
-
-/*
-    ==========================================================================
-    Description:
-		change channel moving time for DFS testing.
-
-	Arguments:
-	    pAdapter                    Pointer to our adapter
-	    wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-               1.) iwpriv ra0 set ChMovTime=[value]
-    ==========================================================================
-*/
-INT Set_ChMovingTime_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg)
-{
-	UINT8 Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	pAd->CommonCfg.RadarDetect.ChMovingTime = Value;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s:: %d\n", __func__,
-		pAd->CommonCfg.RadarDetect.ChMovingTime));
-
-	return TRUE;
-}
-
-INT Set_LongPulseRadarTh_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg)
-{
-	UINT8 Value;
-
-	Value = simple_strtol(arg, 0, 10) > 10 ? 10 : simple_strtol(arg, 0, 10);
-
-	pAd->CommonCfg.RadarDetect.LongPulseRadarTh = Value;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s:: %d\n", __func__,
-		pAd->CommonCfg.RadarDetect.LongPulseRadarTh));
-
-	return TRUE;
-}
-
-
+#include "../../rt2860/common/dfs.c"
diff --git a/drivers/staging/rt2870/common/eeprom.c b/drivers/staging/rt2870/common/eeprom.c
index 33f16ed..def0965 100644
--- a/drivers/staging/rt2870/common/eeprom.c
+++ b/drivers/staging/rt2870/common/eeprom.c
@@ -1,254 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	eeprom.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-*/
-#include "../rt_config.h"
-
-#if 0
-#define EEPROM_SIZE								0x200
-#define NVRAM_OFFSET			0x30000
-#define RF_OFFSET				0x40000
-
-static UCHAR init_flag = 0;
-static PUCHAR nv_ee_start = 0;
-
-static UCHAR EeBuffer[EEPROM_SIZE];
-#endif
-// IRQL = PASSIVE_LEVEL
-VOID RaiseClock(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  UINT32 *x)
-{
-    *x = *x | EESK;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, *x);
-    RTMPusecDelay(1);				// Max frequency = 1MHz in Spec. definition
-}
-
-// IRQL = PASSIVE_LEVEL
-VOID LowerClock(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  UINT32 *x)
-{
-    *x = *x & ~EESK;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, *x);
-    RTMPusecDelay(1);
-}
-
-// IRQL = PASSIVE_LEVEL
-USHORT ShiftInBits(
-    IN	PRTMP_ADAPTER	pAd)
-{
-    UINT32		x,i;
-	USHORT      data=0;
-
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-
-    x &= ~( EEDO | EEDI);
-
-    for(i=0; i<16; i++)
-    {
-        data = data << 1;
-        RaiseClock(pAd, &x);
-
-        RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-
-        x &= ~(EEDI);
-        if(x & EEDO)
-            data |= 1;
-
-        LowerClock(pAd, &x);
-    }
-
-    return data;
-}
-
-// IRQL = PASSIVE_LEVEL
-VOID ShiftOutBits(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  USHORT data,
-    IN  USHORT count)
-{
-    UINT32       x,mask;
-
-    mask = 0x01 << (count - 1);
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-
-    x &= ~(EEDO | EEDI);
-
-    do
-    {
-        x &= ~EEDI;
-        if(data & mask)		x |= EEDI;
-
-        RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-        RaiseClock(pAd, &x);
-        LowerClock(pAd, &x);
-
-        mask = mask >> 1;
-    } while(mask);
-
-    x &= ~EEDI;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-}
-
-// IRQL = PASSIVE_LEVEL
-VOID EEpromCleanup(
-    IN	PRTMP_ADAPTER	pAd)
-{
-    UINT32 x;
-
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-
-    x &= ~(EECS | EEDI);
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-    RaiseClock(pAd, &x);
-    LowerClock(pAd, &x);
-}
-
-VOID EWEN(
-	IN	PRTMP_ADAPTER	pAd)
-{
-    UINT32	x;
-
-    // reset bits and set EECS
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-    x &= ~(EEDI | EEDO | EESK);
-    x |= EECS;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-	// kick a pulse
-	RaiseClock(pAd, &x);
-	LowerClock(pAd, &x);
-
-    // output the read_opcode and six pulse in that order
-    ShiftOutBits(pAd, EEPROM_EWEN_OPCODE, 5);
-    ShiftOutBits(pAd, 0, 6);
-
-    EEpromCleanup(pAd);
-}
-
-VOID EWDS(
-	IN	PRTMP_ADAPTER	pAd)
-{
-    UINT32	x;
-
-    // reset bits and set EECS
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-    x &= ~(EEDI | EEDO | EESK);
-    x |= EECS;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-	// kick a pulse
-	RaiseClock(pAd, &x);
-	LowerClock(pAd, &x);
-
-    // output the read_opcode and six pulse in that order
-    ShiftOutBits(pAd, EEPROM_EWDS_OPCODE, 5);
-    ShiftOutBits(pAd, 0, 6);
-
-    EEpromCleanup(pAd);
-}
-
-// IRQL = PASSIVE_LEVEL
-USHORT RTMP_EEPROM_READ16(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  USHORT Offset)
-{
-    UINT32		x;
-    USHORT		data;
-
-    Offset /= 2;
-    // reset bits and set EECS
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-    x &= ~(EEDI | EEDO | EESK);
-    x |= EECS;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-	// kick a pulse
-	RaiseClock(pAd, &x);
-	LowerClock(pAd, &x);
-
-    // output the read_opcode and register number in that order
-    ShiftOutBits(pAd, EEPROM_READ_OPCODE, 3);
-    ShiftOutBits(pAd, Offset, pAd->EEPROMAddressNum);
-
-    // Now read the data (16 bits) in from the selected EEPROM word
-    data = ShiftInBits(pAd);
-
-    EEpromCleanup(pAd);
-
-    return data;
-}	//ReadEEprom
-
-VOID RTMP_EEPROM_WRITE16(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  USHORT Offset,
-    IN  USHORT Data)
-{
-    UINT32 x;
-
-	Offset /= 2;
-
-	EWEN(pAd);
-
-    // reset bits and set EECS
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-    x &= ~(EEDI | EEDO | EESK);
-    x |= EECS;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-	// kick a pulse
-	RaiseClock(pAd, &x);
-	LowerClock(pAd, &x);
-
-    // output the read_opcode ,register number and data in that order
-    ShiftOutBits(pAd, EEPROM_WRITE_OPCODE, 3);
-    ShiftOutBits(pAd, Offset, pAd->EEPROMAddressNum);
-	ShiftOutBits(pAd, Data, 16);		// 16-bit access
-
-    // read DO status
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-
-	EEpromCleanup(pAd);
-
-	RTMPusecDelay(10000);	//delay for twp(MAX)=10ms
-
-	EWDS(pAd);
-
-    EEpromCleanup(pAd);
-}
-
+#include "../../rt2860/common/eeprom.c"
diff --git a/drivers/staging/rt2870/common/md5.c b/drivers/staging/rt2870/common/md5.c
index 774776b..195645c 100644
--- a/drivers/staging/rt2870/common/md5.c
+++ b/drivers/staging/rt2870/common/md5.c
@@ -1,1427 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    md5.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-	jan			10-28-03		Initial
-	Rita    	11-23-04		Modify MD5 and SHA-1
-	Rita		10-14-05		Modify SHA-1 in big-endian platform
- */
-#include "../rt_config.h"
-
-/**
- * md5_mac:
- * @key: pointer to	the	key	used for MAC generation
- * @key_len: length	of the key in bytes
- * @data: pointer to the data area for which the MAC is	generated
- * @data_len: length of	the	data in	bytes
- * @mac: pointer to	the	buffer holding space for the MAC; the buffer should
- * have	space for 128-bit (16 bytes) MD5 hash value
- *
- * md5_mac() determines	the	message	authentication code	by using secure	hash
- * MD5(key | data |	key).
- */
-void md5_mac(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac)
-{
-	MD5_CTX	context;
-
-	MD5Init(&context);
-	MD5Update(&context,	key, key_len);
-	MD5Update(&context,	data, data_len);
-	MD5Update(&context,	key, key_len);
-	MD5Final(mac, &context);
-}
-
-/**
- * hmac_md5:
- * @key: pointer to	the	key	used for MAC generation
- * @key_len: length	of the key in bytes
- * @data: pointer to the data area for which the MAC is	generated
- * @data_len: length of	the	data in	bytes
- * @mac: pointer to	the	buffer holding space for the MAC; the buffer should
- * have	space for 128-bit (16 bytes) MD5 hash value
- *
- * hmac_md5() determines the message authentication	code using HMAC-MD5.
- * This	implementation is based	on the sample code presented in	RFC	2104.
- */
-void hmac_md5(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac)
-{
-	MD5_CTX	context;
-    u8 k_ipad[65]; /* inner padding - key XORd with ipad */
-    u8 k_opad[65]; /* outer padding - key XORd with opad */
-    u8 tk[16];
-	int	i;
-
-	//assert(key != NULL && data != NULL && mac != NULL);
-
-	/* if key is longer	than 64	bytes reset	it to key =	MD5(key) */
-	if (key_len	> 64) {
-		MD5_CTX	ttcontext;
-
-		MD5Init(&ttcontext);
-		MD5Update(&ttcontext, key, key_len);
-		MD5Final(tk, &ttcontext);
-		//key=(PUCHAR)ttcontext.buf;
-		key	= tk;
-		key_len	= 16;
-	}
-
-	/* the HMAC_MD5	transform looks	like:
-	 *
-	 * MD5(K XOR opad, MD5(K XOR ipad, text))
-	 *
-	 * where K is an n byte	key
-	 * ipad	is the byte	0x36 repeated 64 times
-	 * opad	is the byte	0x5c repeated 64 times
-	 * and text	is the data	being protected	*/
-
-	/* start out by	storing	key	in pads	*/
-	NdisZeroMemory(k_ipad, sizeof(k_ipad));
-	NdisZeroMemory(k_opad,	sizeof(k_opad));
-	//assert(key_len < sizeof(k_ipad));
-	NdisMoveMemory(k_ipad, key,	key_len);
-	NdisMoveMemory(k_opad, key,	key_len);
-
-	/* XOR key with	ipad and opad values */
-	for	(i = 0;	i <	64;	i++) {
-		k_ipad[i] ^= 0x36;
-		k_opad[i] ^= 0x5c;
-	}
-
-	/* perform inner MD5 */
-	MD5Init(&context);					 /*	init context for 1st pass */
-	MD5Update(&context,	k_ipad,	64);	 /*	start with inner pad */
-	MD5Update(&context,	data, data_len); /*	then text of datagram */
-	MD5Final(mac, &context);			 /*	finish up 1st pass */
-
-	/* perform outer MD5 */
-	MD5Init(&context);					 /*	init context for 2nd pass */
-	MD5Update(&context,	k_opad,	64);	 /*	start with outer pad */
-	MD5Update(&context,	mac, 16);		 /*	then results of	1st	hash */
-	MD5Final(mac, &context);			 /*	finish up 2nd pass */
-}
-
-#ifndef RT_BIG_ENDIAN
-#define byteReverse(buf, len)   /* Nothing */
-#else
-void byteReverse(unsigned char *buf, unsigned longs);
-void byteReverse(unsigned char *buf, unsigned longs)
-{
-    do {
-        *(UINT32 *)buf = SWAP32(*(UINT32 *)buf);
-        buf += 4;
-    } while (--longs);
-}
-#endif
-
-
-/* ==========================  MD5 implementation =========================== */
-// four base functions for MD5
-#define MD5_F1(x, y, z) (((x) & (y)) | ((~x) & (z)))
-#define MD5_F2(x, y, z) (((x) & (z)) | ((y) & (~z)))
-#define MD5_F3(x, y, z) ((x) ^ (y) ^ (z))
-#define MD5_F4(x, y, z) ((y) ^ ((x) | (~z)))
-#define CYCLIC_LEFT_SHIFT(w, s) (((w) << (s)) | ((w) >> (32-(s))))
-
-#define	MD5Step(f, w, x, y,	z, data, t, s)	\
-	( w	+= f(x,	y, z) +	data + t,  w = (CYCLIC_LEFT_SHIFT(w, s)) & 0xffffffff, w +=	x )
-
-
-/*
- *  Function Description:
- *      Initiate MD5 Context satisfied in RFC 1321
- *
- *  Arguments:
- *      pCtx        Pointer	to MD5 context
- *
- *  Return Value:
- *      None
- */
-VOID MD5Init(MD5_CTX *pCtx)
-{
-    pCtx->Buf[0]=0x67452301;
-    pCtx->Buf[1]=0xefcdab89;
-    pCtx->Buf[2]=0x98badcfe;
-    pCtx->Buf[3]=0x10325476;
-
-    pCtx->LenInBitCount[0]=0;
-    pCtx->LenInBitCount[1]=0;
-}
-
-
-/*
- *  Function Description:
- *      Update MD5 Context, allow of an arrary of octets as the next portion
- *      of the message
- *
- *  Arguments:
- *      pCtx		Pointer	to MD5 context
- * 	    pData       Pointer to input data
- *      LenInBytes  The length of input data (unit: byte)
- *
- *  Return Value:
- *      None
- *
- *  Note:
- *      Called after MD5Init or MD5Update(itself)
- */
-VOID MD5Update(MD5_CTX *pCtx, UCHAR *pData, UINT32 LenInBytes)
-{
-
-    UINT32 TfTimes;
-    UINT32 temp;
-	unsigned int i;
-
-    temp = pCtx->LenInBitCount[0];
-
-    pCtx->LenInBitCount[0] = (UINT32) (pCtx->LenInBitCount[0] + (LenInBytes << 3));
-
-    if (pCtx->LenInBitCount[0] < temp)
-        pCtx->LenInBitCount[1]++;   //carry in
-
-    pCtx->LenInBitCount[1] += LenInBytes >> 29;
-
-    // mod 64 bytes
-    temp = (temp >> 3) & 0x3f;
-
-    // process lacks of 64-byte data
-    if (temp)
-    {
-        UCHAR *pAds = (UCHAR *) pCtx->Input + temp;
-
-        if ((temp+LenInBytes) < 64)
-        {
-            NdisMoveMemory(pAds, (UCHAR *)pData, LenInBytes);
-            return;
-        }
-
-        NdisMoveMemory(pAds, (UCHAR *)pData, 64-temp);
-        byteReverse(pCtx->Input, 16);
-        MD5Transform(pCtx->Buf, (UINT32 *)pCtx->Input);
-
-        pData += 64-temp;
-        LenInBytes -= 64-temp;
-    } // end of if (temp)
-
-
-    TfTimes = (LenInBytes >> 6);
-
-    for (i=TfTimes; i>0; i--)
-    {
-        NdisMoveMemory(pCtx->Input, (UCHAR *)pData, 64);
-        byteReverse(pCtx->Input, 16);
-        MD5Transform(pCtx->Buf, (UINT32 *)pCtx->Input);
-        pData += 64;
-        LenInBytes -= 64;
-    } // end of for
-
-    // buffering lacks of 64-byte data
-    if(LenInBytes)
-        NdisMoveMemory(pCtx->Input, (UCHAR *)pData, LenInBytes);
-
-}
-
-
-/*
- *  Function Description:
- *      Append padding bits and length of original message in the tail
- *      The message digest has to be completed in the end
- *
- *  Arguments:
- *      Digest		Output of Digest-Message for MD5
- *  	pCtx        Pointer	to MD5 context
- *
- *  Return Value:
- *      None
- *
- *  Note:
- *      Called after MD5Update
- */
-VOID MD5Final(UCHAR Digest[16], MD5_CTX *pCtx)
-{
-    UCHAR Remainder;
-    UCHAR PadLenInBytes;
-    UCHAR *pAppend=0;
-    unsigned int i;
-
-    Remainder = (UCHAR)((pCtx->LenInBitCount[0] >> 3) & 0x3f);
-
-    PadLenInBytes = (Remainder < 56) ? (56-Remainder) : (120-Remainder);
-
-    pAppend = (UCHAR *)pCtx->Input + Remainder;
-
-    // padding bits without crossing block(64-byte based) boundary
-    if (Remainder < 56)
-    {
-        *pAppend = 0x80;
-        PadLenInBytes --;
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, PadLenInBytes);
-
-		// add data-length field, from low to high
-       	for (i=0; i<4; i++)
-        {
-        	pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[0] >> (i << 3)) & 0xff);
-        	pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[1] >> (i << 3)) & 0xff);
-      	}
-
-        byteReverse(pCtx->Input, 16);
-        MD5Transform(pCtx->Buf, (UINT32 *)pCtx->Input);
-    } // end of if
-
-    // padding bits with crossing block(64-byte based) boundary
-    else
-    {
-        // the first block ===
-        *pAppend = 0x80;
-        PadLenInBytes --;
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, (64-Remainder-1));
-        PadLenInBytes -= (64 - Remainder - 1);
-
-        byteReverse(pCtx->Input, 16);
-        MD5Transform(pCtx->Buf, (UINT32 *)pCtx->Input);
-
-
-        // the second block ===
-        NdisZeroMemory((UCHAR *)pCtx->Input, PadLenInBytes);
-
-        // add data-length field
-        for (i=0; i<4; i++)
-        {
-        	pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[0] >> (i << 3)) & 0xff);
-        	pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[1] >> (i << 3)) & 0xff);
-      	}
-
-        byteReverse(pCtx->Input, 16);
-        MD5Transform(pCtx->Buf, (UINT32 *)pCtx->Input);
-    } // end of else
-
-
-    NdisMoveMemory((UCHAR *)Digest, (UINT32 *)pCtx->Buf, 16); // output
-    byteReverse((UCHAR *)Digest, 4);
-    NdisZeroMemory(pCtx, sizeof(pCtx)); // memory free
-}
-
-
-/*
- *  Function Description:
- *      The central algorithm of MD5, consists of four rounds and sixteen
- *  	steps per round
- *
- *  Arguments:
- *      Buf     Buffers of four states (output: 16 bytes)
- * 	    Mes     Input data (input: 64 bytes)
- *
- *  Return Value:
- *      None
- *
- *  Note:
- *      Called by MD5Update or MD5Final
- */
-VOID MD5Transform(UINT32 Buf[4], UINT32 Mes[16])
-{
-    UINT32 Reg[4], Temp;
-	unsigned int i;
-
-    static UCHAR LShiftVal[16] =
-    {
-        7, 12, 17, 22,
-		5, 9 , 14, 20,
-		4, 11, 16, 23,
- 		6, 10, 15, 21,
- 	};
-
-
-	// [equal to 4294967296*abs(sin(index))]
-    static UINT32 MD5Table[64] =
-	{
-		0xd76aa478,	0xe8c7b756,	0x242070db,	0xc1bdceee,
-		0xf57c0faf,	0x4787c62a,	0xa8304613, 0xfd469501,
-		0x698098d8,	0x8b44f7af,	0xffff5bb1,	0x895cd7be,
-    	0x6b901122,	0xfd987193,	0xa679438e,	0x49b40821,
-
-    	0xf61e2562,	0xc040b340,	0x265e5a51,	0xe9b6c7aa,
-    	0xd62f105d,	0x02441453,	0xd8a1e681,	0xe7d3fbc8,
-    	0x21e1cde6,	0xc33707d6,	0xf4d50d87,	0x455a14ed,
-    	0xa9e3e905,	0xfcefa3f8,	0x676f02d9,	0x8d2a4c8a,
-
-    	0xfffa3942,	0x8771f681,	0x6d9d6122,	0xfde5380c,
-    	0xa4beea44,	0x4bdecfa9,	0xf6bb4b60,	0xbebfbc70,
-    	0x289b7ec6,	0xeaa127fa,	0xd4ef3085,	0x04881d05,
-    	0xd9d4d039,	0xe6db99e5,	0x1fa27cf8,	0xc4ac5665,
-
-    	0xf4292244,	0x432aff97,	0xab9423a7,	0xfc93a039,
-   		0x655b59c3,	0x8f0ccc92,	0xffeff47d,	0x85845dd1,
-    	0x6fa87e4f,	0xfe2ce6e0,	0xa3014314,	0x4e0811a1,
-    	0xf7537e82,	0xbd3af235,	0x2ad7d2bb,	0xeb86d391
-	};
-
-
-    for (i=0; i<4; i++)
-        Reg[i]=Buf[i];
-
-
-    // 64 steps in MD5 algorithm
-    for (i=0; i<16; i++)
-    {
-        MD5Step(MD5_F1, Reg[0], Reg[1], Reg[2], Reg[3], Mes[i],
-                MD5Table[i], LShiftVal[i & 0x3]);
-
-        // one-word right shift
-        Temp   = Reg[3];
-        Reg[3] = Reg[2];
-        Reg[2] = Reg[1];
-        Reg[1] = Reg[0];
-        Reg[0] = Temp;
-    }
-    for (i=16; i<32; i++)
-    {
-        MD5Step(MD5_F2, Reg[0], Reg[1], Reg[2], Reg[3], Mes[(5*(i & 0xf)+1) & 0xf],
-                MD5Table[i], LShiftVal[(0x1 << 2)+(i & 0x3)]);
-
-        // one-word right shift
-        Temp   = Reg[3];
-        Reg[3] = Reg[2];
-        Reg[2] = Reg[1];
-        Reg[1] = Reg[0];
-        Reg[0] = Temp;
-    }
-    for (i=32; i<48; i++)
-    {
-        MD5Step(MD5_F3, Reg[0], Reg[1], Reg[2], Reg[3], Mes[(3*(i & 0xf)+5) & 0xf],
-                MD5Table[i], LShiftVal[(0x1 << 3)+(i & 0x3)]);
-
-        // one-word right shift
-        Temp   = Reg[3];
-        Reg[3] = Reg[2];
-        Reg[2] = Reg[1];
-        Reg[1] = Reg[0];
-        Reg[0] = Temp;
-    }
-    for (i=48; i<64; i++)
-    {
-        MD5Step(MD5_F4, Reg[0], Reg[1], Reg[2], Reg[3], Mes[(7*(i & 0xf)) & 0xf],
-                MD5Table[i], LShiftVal[(0x3 << 2)+(i & 0x3)]);
-
-        // one-word right shift
-        Temp   = Reg[3];
-        Reg[3] = Reg[2];
-        Reg[2] = Reg[1];
-        Reg[1] = Reg[0];
-        Reg[0] = Temp;
-    }
-
-
-    // (temporary)output
-    for (i=0; i<4; i++)
-        Buf[i] += Reg[i];
-
-}
-
-
-
-/* =========================  SHA-1 implementation ========================== */
-// four base functions for SHA-1
-#define SHA1_F1(b, c, d)    (((b) & (c)) | ((~b) & (d)))
-#define SHA1_F2(b, c, d)    ((b) ^ (c) ^ (d))
-#define SHA1_F3(b, c, d)    (((b) & (c)) | ((b) & (d)) | ((c) & (d)))
-
-
-#define SHA1Step(f, a, b, c, d, e, w, k)    \
-    ( e	+= ( f(b, c, d) + w + k + CYCLIC_LEFT_SHIFT(a, 5)) & 0xffffffff, \
-      b = CYCLIC_LEFT_SHIFT(b, 30) )
-
-//Initiate SHA-1 Context satisfied in RFC 3174
-VOID SHAInit(SHA_CTX *pCtx)
-{
-    pCtx->Buf[0]=0x67452301;
-    pCtx->Buf[1]=0xefcdab89;
-    pCtx->Buf[2]=0x98badcfe;
-    pCtx->Buf[3]=0x10325476;
-    pCtx->Buf[4]=0xc3d2e1f0;
-
-    pCtx->LenInBitCount[0]=0;
-    pCtx->LenInBitCount[1]=0;
-}
-
-/*
- *  Function Description:
- *      Update SHA-1 Context, allow of an arrary of octets as the next
- *      portion of the message
- *
- *  Arguments:
- *      pCtx		Pointer	to SHA-1 context
- * 	    pData       Pointer to input data
- *      LenInBytes  The length of input data (unit: byte)
- *
- *  Return Value:
- *      error       indicate more than pow(2,64) bits of data
- *
- *  Note:
- *      Called after SHAInit or SHAUpdate(itself)
- */
-UCHAR SHAUpdate(SHA_CTX *pCtx, UCHAR *pData, UINT32 LenInBytes)
-{
-    UINT32 TfTimes;
-    UINT32 temp1,temp2;
-	unsigned int i;
-	UCHAR err=1;
-
-    temp1 = pCtx->LenInBitCount[0];
-    temp2 = pCtx->LenInBitCount[1];
-
-    pCtx->LenInBitCount[0] = (UINT32) (pCtx->LenInBitCount[0] + (LenInBytes << 3));
-    if (pCtx->LenInBitCount[0] < temp1)
-        pCtx->LenInBitCount[1]++;   //carry in
-
-
-    pCtx->LenInBitCount[1] = (UINT32) (pCtx->LenInBitCount[1] +(LenInBytes >> 29));
-    if (pCtx->LenInBitCount[1] < temp2)
-        return (err);   //check total length of original data
-
-
-    // mod 64 bytes
-    temp1 = (temp1 >> 3) & 0x3f;
-
-    // process lacks of 64-byte data
-    if (temp1)
-    {
-        UCHAR *pAds = (UCHAR *) pCtx->Input + temp1;
-
-        if ((temp1+LenInBytes) < 64)
-        {
-            NdisMoveMemory(pAds, (UCHAR *)pData, LenInBytes);
-            return (0);
-        }
-
-        NdisMoveMemory(pAds, (UCHAR *)pData, 64-temp1);
-        byteReverse((UCHAR *)pCtx->Input, 16);
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
-        SHATransform(pCtx->Buf, (UINT32 *)pCtx->Input);
-
-        pData += 64-temp1;
-        LenInBytes -= 64-temp1;
-    } // end of if (temp1)
-
-
-    TfTimes = (LenInBytes >> 6);
-
-    for (i=TfTimes; i>0; i--)
-    {
-        NdisMoveMemory(pCtx->Input, (UCHAR *)pData, 64);
-        byteReverse((UCHAR *)pCtx->Input, 16);
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
-        SHATransform(pCtx->Buf, (UINT32 *)pCtx->Input);
-        pData += 64;
-        LenInBytes -= 64;
-    } // end of for
-
-    // buffering lacks of 64-byte data
-    if(LenInBytes)
-        NdisMoveMemory(pCtx->Input, (UCHAR *)pData, LenInBytes);
-
-	return (0);
-
-}
-
-// Append padding bits and length of original message in the tail
-// The message digest has to be completed in the end
-VOID SHAFinal(SHA_CTX *pCtx, UCHAR Digest[20])
-{
-    UCHAR Remainder;
-    UCHAR PadLenInBytes;
-    UCHAR *pAppend=0;
-    unsigned int i;
-
-    Remainder = (UCHAR)((pCtx->LenInBitCount[0] >> 3) & 0x3f);
-
-    pAppend = (UCHAR *)pCtx->Input + Remainder;
-
-    PadLenInBytes = (Remainder < 56) ? (56-Remainder) : (120-Remainder);
-
-    // padding bits without crossing block(64-byte based) boundary
-    if (Remainder < 56)
-    {
-        *pAppend = 0x80;
-        PadLenInBytes --;
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, PadLenInBytes);
-
-		// add data-length field, from high to low
-        for (i=0; i<4; i++)
-        {
-        	pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[1] >> ((3-i) << 3)) & 0xff);
-        	pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[0] >> ((3-i) << 3)) & 0xff);
-      	}
-
-        byteReverse((UCHAR *)pCtx->Input, 16);
-        NdisZeroMemory((UCHAR *)pCtx->Input + 64, 14);
-        SHATransform(pCtx->Buf, (UINT32 *)pCtx->Input);
-    } // end of if
-
-    // padding bits with crossing block(64-byte based) boundary
-    else
-    {
-        // the first block ===
-        *pAppend = 0x80;
-        PadLenInBytes --;
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, (64-Remainder-1));
-        PadLenInBytes -= (64 - Remainder - 1);
-
-        byteReverse((UCHAR *)pCtx->Input, 16);
-        NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
-        SHATransform(pCtx->Buf, (UINT32 *)pCtx->Input);
-
-
-        // the second block ===
-        NdisZeroMemory((UCHAR *)pCtx->Input, PadLenInBytes);
-
-		// add data-length field
-		for (i=0; i<4; i++)
-        {
-        	pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[1] >> ((3-i) << 3)) & 0xff);
-        	pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[0] >> ((3-i) << 3)) & 0xff);
-      	}
-
-        byteReverse((UCHAR *)pCtx->Input, 16);
-        NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
-        SHATransform(pCtx->Buf, (UINT32 *)pCtx->Input);
-    } // end of else
-
-
-    //Output, bytereverse
-    for (i=0; i<20; i++)
-    {
-        Digest [i] = (UCHAR)(pCtx->Buf[i>>2] >> 8*(3-(i & 0x3)));
-    }
-
-    NdisZeroMemory(pCtx, sizeof(pCtx)); // memory free
-}
-
-
-// The central algorithm of SHA-1, consists of four rounds and
-// twenty steps per round
-VOID SHATransform(UINT32 Buf[5], UINT32 Mes[20])
-{
-    UINT32 Reg[5],Temp;
-	unsigned int i;
-    UINT32 W[80];
-
-    static UINT32 SHA1Table[4] = { 0x5a827999, 0x6ed9eba1,
-                                  0x8f1bbcdc, 0xca62c1d6 };
-
-    Reg[0]=Buf[0];
-	Reg[1]=Buf[1];
-	Reg[2]=Buf[2];
-	Reg[3]=Buf[3];
-	Reg[4]=Buf[4];
-
-    //the first octet of a word is stored in the 0th element, bytereverse
-	for(i = 0; i < 16; i++)
-    {
-    	W[i]  = (Mes[i] >> 24) & 0xff;
-        W[i] |= (Mes[i] >> 8 ) & 0xff00;
-        W[i] |= (Mes[i] << 8 ) & 0xff0000;
-        W[i] |= (Mes[i] << 24) & 0xff000000;
-    }
-
-
-    for	(i = 0; i < 64; i++)
-	    W[16+i] = CYCLIC_LEFT_SHIFT(W[i] ^ W[2+i] ^ W[8+i] ^ W[13+i], 1);
-
-
-    // 80 steps in SHA-1 algorithm
-    for (i=0; i<80; i++)
-    {
-        if (i<20)
-            SHA1Step(SHA1_F1, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
-                     W[i], SHA1Table[0]);
-
-        else if (i>=20 && i<40)
-            SHA1Step(SHA1_F2, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
-                     W[i], SHA1Table[1]);
-
-		else if (i>=40 && i<60)
-            SHA1Step(SHA1_F3, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
-                      W[i], SHA1Table[2]);
-
-        else
-            SHA1Step(SHA1_F2, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
-                     W[i], SHA1Table[3]);
-
-
-       // one-word right shift
-		Temp   = Reg[4];
-        Reg[4] = Reg[3];
-        Reg[3] = Reg[2];
-        Reg[2] = Reg[1];
-        Reg[1] = Reg[0];
-        Reg[0] = Temp;
-
-    } // end of for-loop
-
-
-    // (temporary)output
-    for (i=0; i<5; i++)
-        Buf[i] += Reg[i];
-
-}
-
-
-/* =========================  AES En/Decryption ========================== */
-
-/* forward S-box */
-static uint32 FSb[256] =
-{
-	0x63, 0x7C,	0x77, 0x7B,	0xF2, 0x6B,	0x6F, 0xC5,
-	0x30, 0x01,	0x67, 0x2B,	0xFE, 0xD7,	0xAB, 0x76,
-	0xCA, 0x82,	0xC9, 0x7D,	0xFA, 0x59,	0x47, 0xF0,
-	0xAD, 0xD4,	0xA2, 0xAF,	0x9C, 0xA4,	0x72, 0xC0,
-	0xB7, 0xFD,	0x93, 0x26,	0x36, 0x3F,	0xF7, 0xCC,
-	0x34, 0xA5,	0xE5, 0xF1,	0x71, 0xD8,	0x31, 0x15,
-	0x04, 0xC7,	0x23, 0xC3,	0x18, 0x96,	0x05, 0x9A,
-	0x07, 0x12,	0x80, 0xE2,	0xEB, 0x27,	0xB2, 0x75,
-	0x09, 0x83,	0x2C, 0x1A,	0x1B, 0x6E,	0x5A, 0xA0,
-	0x52, 0x3B,	0xD6, 0xB3,	0x29, 0xE3,	0x2F, 0x84,
-	0x53, 0xD1,	0x00, 0xED,	0x20, 0xFC,	0xB1, 0x5B,
-	0x6A, 0xCB,	0xBE, 0x39,	0x4A, 0x4C,	0x58, 0xCF,
-	0xD0, 0xEF,	0xAA, 0xFB,	0x43, 0x4D,	0x33, 0x85,
-	0x45, 0xF9,	0x02, 0x7F,	0x50, 0x3C,	0x9F, 0xA8,
-	0x51, 0xA3,	0x40, 0x8F,	0x92, 0x9D,	0x38, 0xF5,
-	0xBC, 0xB6,	0xDA, 0x21,	0x10, 0xFF,	0xF3, 0xD2,
-	0xCD, 0x0C,	0x13, 0xEC,	0x5F, 0x97,	0x44, 0x17,
-	0xC4, 0xA7,	0x7E, 0x3D,	0x64, 0x5D,	0x19, 0x73,
-	0x60, 0x81,	0x4F, 0xDC,	0x22, 0x2A,	0x90, 0x88,
-	0x46, 0xEE,	0xB8, 0x14,	0xDE, 0x5E,	0x0B, 0xDB,
-	0xE0, 0x32,	0x3A, 0x0A,	0x49, 0x06,	0x24, 0x5C,
-	0xC2, 0xD3,	0xAC, 0x62,	0x91, 0x95,	0xE4, 0x79,
-	0xE7, 0xC8,	0x37, 0x6D,	0x8D, 0xD5,	0x4E, 0xA9,
-	0x6C, 0x56,	0xF4, 0xEA,	0x65, 0x7A,	0xAE, 0x08,
-	0xBA, 0x78,	0x25, 0x2E,	0x1C, 0xA6,	0xB4, 0xC6,
-	0xE8, 0xDD,	0x74, 0x1F,	0x4B, 0xBD,	0x8B, 0x8A,
-	0x70, 0x3E,	0xB5, 0x66,	0x48, 0x03,	0xF6, 0x0E,
-	0x61, 0x35,	0x57, 0xB9,	0x86, 0xC1,	0x1D, 0x9E,
-	0xE1, 0xF8,	0x98, 0x11,	0x69, 0xD9,	0x8E, 0x94,
-	0x9B, 0x1E,	0x87, 0xE9,	0xCE, 0x55,	0x28, 0xDF,
-	0x8C, 0xA1,	0x89, 0x0D,	0xBF, 0xE6,	0x42, 0x68,
-	0x41, 0x99,	0x2D, 0x0F,	0xB0, 0x54,	0xBB, 0x16
-};
-
-/* forward table */
-#define	FT \
-\
-	V(C6,63,63,A5),	V(F8,7C,7C,84),	V(EE,77,77,99),	V(F6,7B,7B,8D),	\
-	V(FF,F2,F2,0D),	V(D6,6B,6B,BD),	V(DE,6F,6F,B1),	V(91,C5,C5,54),	\
-	V(60,30,30,50),	V(02,01,01,03),	V(CE,67,67,A9),	V(56,2B,2B,7D),	\
-	V(E7,FE,FE,19),	V(B5,D7,D7,62),	V(4D,AB,AB,E6),	V(EC,76,76,9A),	\
-	V(8F,CA,CA,45),	V(1F,82,82,9D),	V(89,C9,C9,40),	V(FA,7D,7D,87),	\
-	V(EF,FA,FA,15),	V(B2,59,59,EB),	V(8E,47,47,C9),	V(FB,F0,F0,0B),	\
-	V(41,AD,AD,EC),	V(B3,D4,D4,67),	V(5F,A2,A2,FD),	V(45,AF,AF,EA),	\
-	V(23,9C,9C,BF),	V(53,A4,A4,F7),	V(E4,72,72,96),	V(9B,C0,C0,5B),	\
-	V(75,B7,B7,C2),	V(E1,FD,FD,1C),	V(3D,93,93,AE),	V(4C,26,26,6A),	\
-	V(6C,36,36,5A),	V(7E,3F,3F,41),	V(F5,F7,F7,02),	V(83,CC,CC,4F),	\
-	V(68,34,34,5C),	V(51,A5,A5,F4),	V(D1,E5,E5,34),	V(F9,F1,F1,08),	\
-	V(E2,71,71,93),	V(AB,D8,D8,73),	V(62,31,31,53),	V(2A,15,15,3F),	\
-	V(08,04,04,0C),	V(95,C7,C7,52),	V(46,23,23,65),	V(9D,C3,C3,5E),	\
-	V(30,18,18,28),	V(37,96,96,A1),	V(0A,05,05,0F),	V(2F,9A,9A,B5),	\
-	V(0E,07,07,09),	V(24,12,12,36),	V(1B,80,80,9B),	V(DF,E2,E2,3D),	\
-	V(CD,EB,EB,26),	V(4E,27,27,69),	V(7F,B2,B2,CD),	V(EA,75,75,9F),	\
-	V(12,09,09,1B),	V(1D,83,83,9E),	V(58,2C,2C,74),	V(34,1A,1A,2E),	\
-	V(36,1B,1B,2D),	V(DC,6E,6E,B2),	V(B4,5A,5A,EE),	V(5B,A0,A0,FB),	\
-	V(A4,52,52,F6),	V(76,3B,3B,4D),	V(B7,D6,D6,61),	V(7D,B3,B3,CE),	\
-	V(52,29,29,7B),	V(DD,E3,E3,3E),	V(5E,2F,2F,71),	V(13,84,84,97),	\
-	V(A6,53,53,F5),	V(B9,D1,D1,68),	V(00,00,00,00),	V(C1,ED,ED,2C),	\
-	V(40,20,20,60),	V(E3,FC,FC,1F),	V(79,B1,B1,C8),	V(B6,5B,5B,ED),	\
-	V(D4,6A,6A,BE),	V(8D,CB,CB,46),	V(67,BE,BE,D9),	V(72,39,39,4B),	\
-	V(94,4A,4A,DE),	V(98,4C,4C,D4),	V(B0,58,58,E8),	V(85,CF,CF,4A),	\
-	V(BB,D0,D0,6B),	V(C5,EF,EF,2A),	V(4F,AA,AA,E5),	V(ED,FB,FB,16),	\
-	V(86,43,43,C5),	V(9A,4D,4D,D7),	V(66,33,33,55),	V(11,85,85,94),	\
-	V(8A,45,45,CF),	V(E9,F9,F9,10),	V(04,02,02,06),	V(FE,7F,7F,81),	\
-	V(A0,50,50,F0),	V(78,3C,3C,44),	V(25,9F,9F,BA),	V(4B,A8,A8,E3),	\
-	V(A2,51,51,F3),	V(5D,A3,A3,FE),	V(80,40,40,C0),	V(05,8F,8F,8A),	\
-	V(3F,92,92,AD),	V(21,9D,9D,BC),	V(70,38,38,48),	V(F1,F5,F5,04),	\
-	V(63,BC,BC,DF),	V(77,B6,B6,C1),	V(AF,DA,DA,75),	V(42,21,21,63),	\
-	V(20,10,10,30),	V(E5,FF,FF,1A),	V(FD,F3,F3,0E),	V(BF,D2,D2,6D),	\
-	V(81,CD,CD,4C),	V(18,0C,0C,14),	V(26,13,13,35),	V(C3,EC,EC,2F),	\
-	V(BE,5F,5F,E1),	V(35,97,97,A2),	V(88,44,44,CC),	V(2E,17,17,39),	\
-	V(93,C4,C4,57),	V(55,A7,A7,F2),	V(FC,7E,7E,82),	V(7A,3D,3D,47),	\
-	V(C8,64,64,AC),	V(BA,5D,5D,E7),	V(32,19,19,2B),	V(E6,73,73,95),	\
-	V(C0,60,60,A0),	V(19,81,81,98),	V(9E,4F,4F,D1),	V(A3,DC,DC,7F),	\
-	V(44,22,22,66),	V(54,2A,2A,7E),	V(3B,90,90,AB),	V(0B,88,88,83),	\
-	V(8C,46,46,CA),	V(C7,EE,EE,29),	V(6B,B8,B8,D3),	V(28,14,14,3C),	\
-	V(A7,DE,DE,79),	V(BC,5E,5E,E2),	V(16,0B,0B,1D),	V(AD,DB,DB,76),	\
-	V(DB,E0,E0,3B),	V(64,32,32,56),	V(74,3A,3A,4E),	V(14,0A,0A,1E),	\
-	V(92,49,49,DB),	V(0C,06,06,0A),	V(48,24,24,6C),	V(B8,5C,5C,E4),	\
-	V(9F,C2,C2,5D),	V(BD,D3,D3,6E),	V(43,AC,AC,EF),	V(C4,62,62,A6),	\
-	V(39,91,91,A8),	V(31,95,95,A4),	V(D3,E4,E4,37),	V(F2,79,79,8B),	\
-	V(D5,E7,E7,32),	V(8B,C8,C8,43),	V(6E,37,37,59),	V(DA,6D,6D,B7),	\
-	V(01,8D,8D,8C),	V(B1,D5,D5,64),	V(9C,4E,4E,D2),	V(49,A9,A9,E0),	\
-	V(D8,6C,6C,B4),	V(AC,56,56,FA),	V(F3,F4,F4,07),	V(CF,EA,EA,25),	\
-	V(CA,65,65,AF),	V(F4,7A,7A,8E),	V(47,AE,AE,E9),	V(10,08,08,18),	\
-	V(6F,BA,BA,D5),	V(F0,78,78,88),	V(4A,25,25,6F),	V(5C,2E,2E,72),	\
-	V(38,1C,1C,24),	V(57,A6,A6,F1),	V(73,B4,B4,C7),	V(97,C6,C6,51),	\
-	V(CB,E8,E8,23),	V(A1,DD,DD,7C),	V(E8,74,74,9C),	V(3E,1F,1F,21),	\
-	V(96,4B,4B,DD),	V(61,BD,BD,DC),	V(0D,8B,8B,86),	V(0F,8A,8A,85),	\
-	V(E0,70,70,90),	V(7C,3E,3E,42),	V(71,B5,B5,C4),	V(CC,66,66,AA),	\
-	V(90,48,48,D8),	V(06,03,03,05),	V(F7,F6,F6,01),	V(1C,0E,0E,12),	\
-	V(C2,61,61,A3),	V(6A,35,35,5F),	V(AE,57,57,F9),	V(69,B9,B9,D0),	\
-	V(17,86,86,91),	V(99,C1,C1,58),	V(3A,1D,1D,27),	V(27,9E,9E,B9),	\
-	V(D9,E1,E1,38),	V(EB,F8,F8,13),	V(2B,98,98,B3),	V(22,11,11,33),	\
-	V(D2,69,69,BB),	V(A9,D9,D9,70),	V(07,8E,8E,89),	V(33,94,94,A7),	\
-	V(2D,9B,9B,B6),	V(3C,1E,1E,22),	V(15,87,87,92),	V(C9,E9,E9,20),	\
-	V(87,CE,CE,49),	V(AA,55,55,FF),	V(50,28,28,78),	V(A5,DF,DF,7A),	\
-	V(03,8C,8C,8F),	V(59,A1,A1,F8),	V(09,89,89,80),	V(1A,0D,0D,17),	\
-	V(65,BF,BF,DA),	V(D7,E6,E6,31),	V(84,42,42,C6),	V(D0,68,68,B8),	\
-	V(82,41,41,C3),	V(29,99,99,B0),	V(5A,2D,2D,77),	V(1E,0F,0F,11),	\
-	V(7B,B0,B0,CB),	V(A8,54,54,FC),	V(6D,BB,BB,D6),	V(2C,16,16,3A)
-
-#define	V(a,b,c,d) 0x##a##b##c##d
-static uint32 FT0[256] = { FT };
-#undef V
-
-#define	V(a,b,c,d) 0x##d##a##b##c
-static uint32 FT1[256] = { FT };
-#undef V
-
-#define	V(a,b,c,d) 0x##c##d##a##b
-static uint32 FT2[256] = { FT };
-#undef V
-
-#define	V(a,b,c,d) 0x##b##c##d##a
-static uint32 FT3[256] = { FT };
-#undef V
-
-#undef FT
-
-/* reverse S-box */
-
-static uint32 RSb[256] =
-{
-	0x52, 0x09,	0x6A, 0xD5,	0x30, 0x36,	0xA5, 0x38,
-	0xBF, 0x40,	0xA3, 0x9E,	0x81, 0xF3,	0xD7, 0xFB,
-	0x7C, 0xE3,	0x39, 0x82,	0x9B, 0x2F,	0xFF, 0x87,
-	0x34, 0x8E,	0x43, 0x44,	0xC4, 0xDE,	0xE9, 0xCB,
-	0x54, 0x7B,	0x94, 0x32,	0xA6, 0xC2,	0x23, 0x3D,
-	0xEE, 0x4C,	0x95, 0x0B,	0x42, 0xFA,	0xC3, 0x4E,
-	0x08, 0x2E,	0xA1, 0x66,	0x28, 0xD9,	0x24, 0xB2,
-	0x76, 0x5B,	0xA2, 0x49,	0x6D, 0x8B,	0xD1, 0x25,
-	0x72, 0xF8,	0xF6, 0x64,	0x86, 0x68,	0x98, 0x16,
-	0xD4, 0xA4,	0x5C, 0xCC,	0x5D, 0x65,	0xB6, 0x92,
-	0x6C, 0x70,	0x48, 0x50,	0xFD, 0xED,	0xB9, 0xDA,
-	0x5E, 0x15,	0x46, 0x57,	0xA7, 0x8D,	0x9D, 0x84,
-	0x90, 0xD8,	0xAB, 0x00,	0x8C, 0xBC,	0xD3, 0x0A,
-	0xF7, 0xE4,	0x58, 0x05,	0xB8, 0xB3,	0x45, 0x06,
-	0xD0, 0x2C,	0x1E, 0x8F,	0xCA, 0x3F,	0x0F, 0x02,
-	0xC1, 0xAF,	0xBD, 0x03,	0x01, 0x13,	0x8A, 0x6B,
-	0x3A, 0x91,	0x11, 0x41,	0x4F, 0x67,	0xDC, 0xEA,
-	0x97, 0xF2,	0xCF, 0xCE,	0xF0, 0xB4,	0xE6, 0x73,
-	0x96, 0xAC,	0x74, 0x22,	0xE7, 0xAD,	0x35, 0x85,
-	0xE2, 0xF9,	0x37, 0xE8,	0x1C, 0x75,	0xDF, 0x6E,
-	0x47, 0xF1,	0x1A, 0x71,	0x1D, 0x29,	0xC5, 0x89,
-	0x6F, 0xB7,	0x62, 0x0E,	0xAA, 0x18,	0xBE, 0x1B,
-	0xFC, 0x56,	0x3E, 0x4B,	0xC6, 0xD2,	0x79, 0x20,
-	0x9A, 0xDB,	0xC0, 0xFE,	0x78, 0xCD,	0x5A, 0xF4,
-	0x1F, 0xDD,	0xA8, 0x33,	0x88, 0x07,	0xC7, 0x31,
-	0xB1, 0x12,	0x10, 0x59,	0x27, 0x80,	0xEC, 0x5F,
-	0x60, 0x51,	0x7F, 0xA9,	0x19, 0xB5,	0x4A, 0x0D,
-	0x2D, 0xE5,	0x7A, 0x9F,	0x93, 0xC9,	0x9C, 0xEF,
-	0xA0, 0xE0,	0x3B, 0x4D,	0xAE, 0x2A,	0xF5, 0xB0,
-	0xC8, 0xEB,	0xBB, 0x3C,	0x83, 0x53,	0x99, 0x61,
-	0x17, 0x2B,	0x04, 0x7E,	0xBA, 0x77,	0xD6, 0x26,
-	0xE1, 0x69,	0x14, 0x63,	0x55, 0x21,	0x0C, 0x7D
-};
-
-/* reverse table */
-
-#define	RT \
-\
-	V(51,F4,A7,50),	V(7E,41,65,53),	V(1A,17,A4,C3),	V(3A,27,5E,96),	\
-	V(3B,AB,6B,CB),	V(1F,9D,45,F1),	V(AC,FA,58,AB),	V(4B,E3,03,93),	\
-	V(20,30,FA,55),	V(AD,76,6D,F6),	V(88,CC,76,91),	V(F5,02,4C,25),	\
-	V(4F,E5,D7,FC),	V(C5,2A,CB,D7),	V(26,35,44,80),	V(B5,62,A3,8F),	\
-	V(DE,B1,5A,49),	V(25,BA,1B,67),	V(45,EA,0E,98),	V(5D,FE,C0,E1),	\
-	V(C3,2F,75,02),	V(81,4C,F0,12),	V(8D,46,97,A3),	V(6B,D3,F9,C6),	\
-	V(03,8F,5F,E7),	V(15,92,9C,95),	V(BF,6D,7A,EB),	V(95,52,59,DA),	\
-	V(D4,BE,83,2D),	V(58,74,21,D3),	V(49,E0,69,29),	V(8E,C9,C8,44),	\
-	V(75,C2,89,6A),	V(F4,8E,79,78),	V(99,58,3E,6B),	V(27,B9,71,DD),	\
-	V(BE,E1,4F,B6),	V(F0,88,AD,17),	V(C9,20,AC,66),	V(7D,CE,3A,B4),	\
-	V(63,DF,4A,18),	V(E5,1A,31,82),	V(97,51,33,60),	V(62,53,7F,45),	\
-	V(B1,64,77,E0),	V(BB,6B,AE,84),	V(FE,81,A0,1C),	V(F9,08,2B,94),	\
-	V(70,48,68,58),	V(8F,45,FD,19),	V(94,DE,6C,87),	V(52,7B,F8,B7),	\
-	V(AB,73,D3,23),	V(72,4B,02,E2),	V(E3,1F,8F,57),	V(66,55,AB,2A),	\
-	V(B2,EB,28,07),	V(2F,B5,C2,03),	V(86,C5,7B,9A),	V(D3,37,08,A5),	\
-	V(30,28,87,F2),	V(23,BF,A5,B2),	V(02,03,6A,BA),	V(ED,16,82,5C),	\
-	V(8A,CF,1C,2B),	V(A7,79,B4,92),	V(F3,07,F2,F0),	V(4E,69,E2,A1),	\
-	V(65,DA,F4,CD),	V(06,05,BE,D5),	V(D1,34,62,1F),	V(C4,A6,FE,8A),	\
-	V(34,2E,53,9D),	V(A2,F3,55,A0),	V(05,8A,E1,32),	V(A4,F6,EB,75),	\
-	V(0B,83,EC,39),	V(40,60,EF,AA),	V(5E,71,9F,06),	V(BD,6E,10,51),	\
-	V(3E,21,8A,F9),	V(96,DD,06,3D),	V(DD,3E,05,AE),	V(4D,E6,BD,46),	\
-	V(91,54,8D,B5),	V(71,C4,5D,05),	V(04,06,D4,6F),	V(60,50,15,FF),	\
-	V(19,98,FB,24),	V(D6,BD,E9,97),	V(89,40,43,CC),	V(67,D9,9E,77),	\
-	V(B0,E8,42,BD),	V(07,89,8B,88),	V(E7,19,5B,38),	V(79,C8,EE,DB),	\
-	V(A1,7C,0A,47),	V(7C,42,0F,E9),	V(F8,84,1E,C9),	V(00,00,00,00),	\
-	V(09,80,86,83),	V(32,2B,ED,48),	V(1E,11,70,AC),	V(6C,5A,72,4E),	\
-	V(FD,0E,FF,FB),	V(0F,85,38,56),	V(3D,AE,D5,1E),	V(36,2D,39,27),	\
-	V(0A,0F,D9,64),	V(68,5C,A6,21),	V(9B,5B,54,D1),	V(24,36,2E,3A),	\
-	V(0C,0A,67,B1),	V(93,57,E7,0F),	V(B4,EE,96,D2),	V(1B,9B,91,9E),	\
-	V(80,C0,C5,4F),	V(61,DC,20,A2),	V(5A,77,4B,69),	V(1C,12,1A,16),	\
-	V(E2,93,BA,0A),	V(C0,A0,2A,E5),	V(3C,22,E0,43),	V(12,1B,17,1D),	\
-	V(0E,09,0D,0B),	V(F2,8B,C7,AD),	V(2D,B6,A8,B9),	V(14,1E,A9,C8),	\
-	V(57,F1,19,85),	V(AF,75,07,4C),	V(EE,99,DD,BB),	V(A3,7F,60,FD),	\
-	V(F7,01,26,9F),	V(5C,72,F5,BC),	V(44,66,3B,C5),	V(5B,FB,7E,34),	\
-	V(8B,43,29,76),	V(CB,23,C6,DC),	V(B6,ED,FC,68),	V(B8,E4,F1,63),	\
-	V(D7,31,DC,CA),	V(42,63,85,10),	V(13,97,22,40),	V(84,C6,11,20),	\
-	V(85,4A,24,7D),	V(D2,BB,3D,F8),	V(AE,F9,32,11),	V(C7,29,A1,6D),	\
-	V(1D,9E,2F,4B),	V(DC,B2,30,F3),	V(0D,86,52,EC),	V(77,C1,E3,D0),	\
-	V(2B,B3,16,6C),	V(A9,70,B9,99),	V(11,94,48,FA),	V(47,E9,64,22),	\
-	V(A8,FC,8C,C4),	V(A0,F0,3F,1A),	V(56,7D,2C,D8),	V(22,33,90,EF),	\
-	V(87,49,4E,C7),	V(D9,38,D1,C1),	V(8C,CA,A2,FE),	V(98,D4,0B,36),	\
-	V(A6,F5,81,CF),	V(A5,7A,DE,28),	V(DA,B7,8E,26),	V(3F,AD,BF,A4),	\
-	V(2C,3A,9D,E4),	V(50,78,92,0D),	V(6A,5F,CC,9B),	V(54,7E,46,62),	\
-	V(F6,8D,13,C2),	V(90,D8,B8,E8),	V(2E,39,F7,5E),	V(82,C3,AF,F5),	\
-	V(9F,5D,80,BE),	V(69,D0,93,7C),	V(6F,D5,2D,A9),	V(CF,25,12,B3),	\
-	V(C8,AC,99,3B),	V(10,18,7D,A7),	V(E8,9C,63,6E),	V(DB,3B,BB,7B),	\
-	V(CD,26,78,09),	V(6E,59,18,F4),	V(EC,9A,B7,01),	V(83,4F,9A,A8),	\
-	V(E6,95,6E,65),	V(AA,FF,E6,7E),	V(21,BC,CF,08),	V(EF,15,E8,E6),	\
-	V(BA,E7,9B,D9),	V(4A,6F,36,CE),	V(EA,9F,09,D4),	V(29,B0,7C,D6),	\
-	V(31,A4,B2,AF),	V(2A,3F,23,31),	V(C6,A5,94,30),	V(35,A2,66,C0),	\
-	V(74,4E,BC,37),	V(FC,82,CA,A6),	V(E0,90,D0,B0),	V(33,A7,D8,15),	\
-	V(F1,04,98,4A),	V(41,EC,DA,F7),	V(7F,CD,50,0E),	V(17,91,F6,2F),	\
-	V(76,4D,D6,8D),	V(43,EF,B0,4D),	V(CC,AA,4D,54),	V(E4,96,04,DF),	\
-	V(9E,D1,B5,E3),	V(4C,6A,88,1B),	V(C1,2C,1F,B8),	V(46,65,51,7F),	\
-	V(9D,5E,EA,04),	V(01,8C,35,5D),	V(FA,87,74,73),	V(FB,0B,41,2E),	\
-	V(B3,67,1D,5A),	V(92,DB,D2,52),	V(E9,10,56,33),	V(6D,D6,47,13),	\
-	V(9A,D7,61,8C),	V(37,A1,0C,7A),	V(59,F8,14,8E),	V(EB,13,3C,89),	\
-	V(CE,A9,27,EE),	V(B7,61,C9,35),	V(E1,1C,E5,ED),	V(7A,47,B1,3C),	\
-	V(9C,D2,DF,59),	V(55,F2,73,3F),	V(18,14,CE,79),	V(73,C7,37,BF),	\
-	V(53,F7,CD,EA),	V(5F,FD,AA,5B),	V(DF,3D,6F,14),	V(78,44,DB,86),	\
-	V(CA,AF,F3,81),	V(B9,68,C4,3E),	V(38,24,34,2C),	V(C2,A3,40,5F),	\
-	V(16,1D,C3,72),	V(BC,E2,25,0C),	V(28,3C,49,8B),	V(FF,0D,95,41),	\
-	V(39,A8,01,71),	V(08,0C,B3,DE),	V(D8,B4,E4,9C),	V(64,56,C1,90),	\
-	V(7B,CB,84,61),	V(D5,32,B6,70),	V(48,6C,5C,74),	V(D0,B8,57,42)
-
-#define	V(a,b,c,d) 0x##a##b##c##d
-static uint32 RT0[256] = { RT };
-#undef V
-
-#define	V(a,b,c,d) 0x##d##a##b##c
-static uint32 RT1[256] = { RT };
-#undef V
-
-#define	V(a,b,c,d) 0x##c##d##a##b
-static uint32 RT2[256] = { RT };
-#undef V
-
-#define	V(a,b,c,d) 0x##b##c##d##a
-static uint32 RT3[256] = { RT };
-#undef V
-
-#undef RT
-
-/* round constants */
-
-static uint32 RCON[10] =
-{
-	0x01000000,	0x02000000,	0x04000000,	0x08000000,
-	0x10000000,	0x20000000,	0x40000000,	0x80000000,
-	0x1B000000,	0x36000000
-};
-
-/* key schedule	tables */
-
-static int KT_init = 1;
-
-static uint32 KT0[256];
-static uint32 KT1[256];
-static uint32 KT2[256];
-static uint32 KT3[256];
-
-/* platform-independant	32-bit integer manipulation	macros */
-
-#define	GET_UINT32(n,b,i)						\
-{												\
-	(n)	= (	(uint32) (b)[(i)	] << 24	)		\
-		| (	(uint32) (b)[(i) + 1] << 16	)		\
-		| (	(uint32) (b)[(i) + 2] <<  8	)		\
-		| (	(uint32) (b)[(i) + 3]		);		\
-}
-
-#define	PUT_UINT32(n,b,i)						\
-{												\
-	(b)[(i)	   ] = (uint8) ( (n) >>	24 );		\
-	(b)[(i)	+ 1] = (uint8) ( (n) >>	16 );		\
-	(b)[(i)	+ 2] = (uint8) ( (n) >>	 8 );		\
-	(b)[(i)	+ 3] = (uint8) ( (n)	   );		\
-}
-
-/* AES key scheduling routine */
-
-int	rtmp_aes_set_key( aes_context *ctx, uint8 *key, int nbits )
-{
-	int	i;
-	uint32 *RK,	*SK;
-
-	switch(	nbits )
-	{
-		case 128: ctx->nr =	10;	break;
-		case 192: ctx->nr =	12;	break;
-		case 256: ctx->nr =	14;	break;
-		default	: return( 1	);
-	}
-
-	RK = ctx->erk;
-
-	for( i = 0;	i <	(nbits >> 5); i++ )
-	{
-		GET_UINT32(	RK[i], key,	i *	4 );
-	}
-
-	/* setup encryption	round keys */
-
-	switch(	nbits )
-	{
-	case 128:
-
-		for( i = 0;	i <	10;	i++, RK	+= 4 )
-		{
-			RK[4]  = RK[0] ^ RCON[i] ^
-						( FSb[ (uint8) ( RK[3] >> 16 ) ] <<	24 ) ^
-						( FSb[ (uint8) ( RK[3] >>  8 ) ] <<	16 ) ^
-						( FSb[ (uint8) ( RK[3]		 ) ] <<	 8 ) ^
-						( FSb[ (uint8) ( RK[3] >> 24 ) ]	   );
-
-			RK[5]  = RK[1] ^ RK[4];
-			RK[6]  = RK[2] ^ RK[5];
-			RK[7]  = RK[3] ^ RK[6];
-		}
-		break;
-
-	case 192:
-
-		for( i = 0;	i <	8; i++,	RK += 6	)
-		{
-			RK[6]  = RK[0] ^ RCON[i] ^
-						( FSb[ (uint8) ( RK[5] >> 16 ) ] <<	24 ) ^
-						( FSb[ (uint8) ( RK[5] >>  8 ) ] <<	16 ) ^
-						( FSb[ (uint8) ( RK[5]		 ) ] <<	 8 ) ^
-						( FSb[ (uint8) ( RK[5] >> 24 ) ]	   );
-
-			RK[7]  = RK[1] ^ RK[6];
-			RK[8]  = RK[2] ^ RK[7];
-			RK[9]  = RK[3] ^ RK[8];
-			RK[10] = RK[4] ^ RK[9];
-			RK[11] = RK[5] ^ RK[10];
-		}
-		break;
-
-	case 256:
-
-		for( i = 0;	i <	7; i++,	RK += 8	)
-		{
-			RK[8]  = RK[0] ^ RCON[i] ^
-						( FSb[ (uint8) ( RK[7] >> 16 ) ] <<	24 ) ^
-						( FSb[ (uint8) ( RK[7] >>  8 ) ] <<	16 ) ^
-						( FSb[ (uint8) ( RK[7]		 ) ] <<	 8 ) ^
-						( FSb[ (uint8) ( RK[7] >> 24 ) ]	   );
-
-			RK[9]  = RK[1] ^ RK[8];
-			RK[10] = RK[2] ^ RK[9];
-			RK[11] = RK[3] ^ RK[10];
-
-			RK[12] = RK[4] ^
-						( FSb[ (uint8) ( RK[11]	>> 24 )	] << 24	) ^
-						( FSb[ (uint8) ( RK[11]	>> 16 )	] << 16	) ^
-						( FSb[ (uint8) ( RK[11]	>>	8 )	] <<  8	) ^
-						( FSb[ (uint8) ( RK[11]		  )	]		);
-
-			RK[13] = RK[5] ^ RK[12];
-			RK[14] = RK[6] ^ RK[13];
-			RK[15] = RK[7] ^ RK[14];
-		}
-		break;
-	}
-
-	/* setup decryption	round keys */
-
-	if(	KT_init	)
-	{
-		for( i = 0;	i <	256; i++ )
-		{
-			KT0[i] = RT0[ FSb[i] ];
-			KT1[i] = RT1[ FSb[i] ];
-			KT2[i] = RT2[ FSb[i] ];
-			KT3[i] = RT3[ FSb[i] ];
-		}
-
-		KT_init	= 0;
-	}
-
-	SK = ctx->drk;
-
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-
-	for( i = 1;	i <	ctx->nr; i++ )
-	{
-		RK -= 8;
-
-		*SK++ =	KT0[ (uint8) ( *RK >> 24 ) ] ^
-				KT1[ (uint8) ( *RK >> 16 ) ] ^
-				KT2[ (uint8) ( *RK >>  8 ) ] ^
-				KT3[ (uint8) ( *RK		 ) ]; RK++;
-
-		*SK++ =	KT0[ (uint8) ( *RK >> 24 ) ] ^
-				KT1[ (uint8) ( *RK >> 16 ) ] ^
-				KT2[ (uint8) ( *RK >>  8 ) ] ^
-				KT3[ (uint8) ( *RK		 ) ]; RK++;
-
-		*SK++ =	KT0[ (uint8) ( *RK >> 24 ) ] ^
-				KT1[ (uint8) ( *RK >> 16 ) ] ^
-				KT2[ (uint8) ( *RK >>  8 ) ] ^
-				KT3[ (uint8) ( *RK		 ) ]; RK++;
-
-		*SK++ =	KT0[ (uint8) ( *RK >> 24 ) ] ^
-				KT1[ (uint8) ( *RK >> 16 ) ] ^
-				KT2[ (uint8) ( *RK >>  8 ) ] ^
-				KT3[ (uint8) ( *RK		 ) ]; RK++;
-	}
-
-	RK -= 8;
-
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-
-	return(	0 );
-}
-
-/* AES 128-bit block encryption	routine	*/
-
-void rtmp_aes_encrypt(aes_context *ctx, uint8 input[16],	uint8 output[16] )
-{
-	uint32 *RK,	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3;
-
-	RK = ctx->erk;
-	GET_UINT32(	X0,	input,	0 ); X0	^= RK[0];
-	GET_UINT32(	X1,	input,	4 ); X1	^= RK[1];
-	GET_UINT32(	X2,	input,	8 ); X2	^= RK[2];
-	GET_UINT32(	X3,	input, 12 ); X3	^= RK[3];
-
-#define	AES_FROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3)		\
-{												\
-	RK += 4;									\
-												\
-	X0 = RK[0] ^ FT0[ (uint8) (	Y0 >> 24 ) ] ^	\
-				 FT1[ (uint8) (	Y1 >> 16 ) ] ^	\
-				 FT2[ (uint8) (	Y2 >>  8 ) ] ^	\
-				 FT3[ (uint8) (	Y3		 ) ];	\
-												\
-	X1 = RK[1] ^ FT0[ (uint8) (	Y1 >> 24 ) ] ^	\
-				 FT1[ (uint8) (	Y2 >> 16 ) ] ^	\
-				 FT2[ (uint8) (	Y3 >>  8 ) ] ^	\
-				 FT3[ (uint8) (	Y0		 ) ];	\
-												\
-	X2 = RK[2] ^ FT0[ (uint8) (	Y2 >> 24 ) ] ^	\
-				 FT1[ (uint8) (	Y3 >> 16 ) ] ^	\
-				 FT2[ (uint8) (	Y0 >>  8 ) ] ^	\
-				 FT3[ (uint8) (	Y1		 ) ];	\
-												\
-	X3 = RK[3] ^ FT0[ (uint8) (	Y3 >> 24 ) ] ^	\
-				 FT1[ (uint8) (	Y0 >> 16 ) ] ^	\
-				 FT2[ (uint8) (	Y1 >>  8 ) ] ^	\
-				 FT3[ (uint8) (	Y2		 ) ];	\
-}
-
-	AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 1 */
-	AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 2 */
-	AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 3 */
-	AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 4 */
-	AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 5 */
-	AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 6 */
-	AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 7 */
-	AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 8 */
-	AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 9 */
-
-	if(	ctx->nr	> 10 )
-	{
-		AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );	/* round 10	*/
-		AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );	/* round 11	*/
-	}
-
-	if(	ctx->nr	> 12 )
-	{
-		AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );	/* round 12	*/
-		AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );	/* round 13	*/
-	}
-
-	/* last	round */
-
-	RK += 4;
-
-	X0 = RK[0] ^ ( FSb[	(uint8)	( Y0 >>	24 ) ] << 24 ) ^
-				 ( FSb[	(uint8)	( Y1 >>	16 ) ] << 16 ) ^
-				 ( FSb[	(uint8)	( Y2 >>	 8 ) ] <<  8 ) ^
-				 ( FSb[	(uint8)	( Y3	   ) ]		 );
-
-	X1 = RK[1] ^ ( FSb[	(uint8)	( Y1 >>	24 ) ] << 24 ) ^
-				 ( FSb[	(uint8)	( Y2 >>	16 ) ] << 16 ) ^
-				 ( FSb[	(uint8)	( Y3 >>	 8 ) ] <<  8 ) ^
-				 ( FSb[	(uint8)	( Y0	   ) ]		 );
-
-	X2 = RK[2] ^ ( FSb[	(uint8)	( Y2 >>	24 ) ] << 24 ) ^
-				 ( FSb[	(uint8)	( Y3 >>	16 ) ] << 16 ) ^
-				 ( FSb[	(uint8)	( Y0 >>	 8 ) ] <<  8 ) ^
-				 ( FSb[	(uint8)	( Y1	   ) ]		 );
-
-	X3 = RK[3] ^ ( FSb[	(uint8)	( Y3 >>	24 ) ] << 24 ) ^
-				 ( FSb[	(uint8)	( Y0 >>	16 ) ] << 16 ) ^
-				 ( FSb[	(uint8)	( Y1 >>	 8 ) ] <<  8 ) ^
-				 ( FSb[	(uint8)	( Y2	   ) ]		 );
-
-	PUT_UINT32(	X0,	output,	 0 );
-	PUT_UINT32(	X1,	output,	 4 );
-	PUT_UINT32(	X2,	output,	 8 );
-	PUT_UINT32(	X3,	output,	12 );
-}
-
-/* AES 128-bit block decryption	routine	*/
-
-void rtmp_aes_decrypt( aes_context *ctx,	uint8 input[16], uint8 output[16] )
-{
-	uint32 *RK,	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3;
-
-	RK = ctx->drk;
-
-	GET_UINT32(	X0,	input,	0 ); X0	^= RK[0];
-	GET_UINT32(	X1,	input,	4 ); X1	^= RK[1];
-	GET_UINT32(	X2,	input,	8 ); X2	^= RK[2];
-	GET_UINT32(	X3,	input, 12 ); X3	^= RK[3];
-
-#define	AES_RROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3)		\
-{												\
-	RK += 4;									\
-												\
-	X0 = RK[0] ^ RT0[ (uint8) (	Y0 >> 24 ) ] ^	\
-				 RT1[ (uint8) (	Y3 >> 16 ) ] ^	\
-				 RT2[ (uint8) (	Y2 >>  8 ) ] ^	\
-				 RT3[ (uint8) (	Y1		 ) ];	\
-												\
-	X1 = RK[1] ^ RT0[ (uint8) (	Y1 >> 24 ) ] ^	\
-				 RT1[ (uint8) (	Y0 >> 16 ) ] ^	\
-				 RT2[ (uint8) (	Y3 >>  8 ) ] ^	\
-				 RT3[ (uint8) (	Y2		 ) ];	\
-												\
-	X2 = RK[2] ^ RT0[ (uint8) (	Y2 >> 24 ) ] ^	\
-				 RT1[ (uint8) (	Y1 >> 16 ) ] ^	\
-				 RT2[ (uint8) (	Y0 >>  8 ) ] ^	\
-				 RT3[ (uint8) (	Y3		 ) ];	\
-												\
-	X3 = RK[3] ^ RT0[ (uint8) (	Y3 >> 24 ) ] ^	\
-				 RT1[ (uint8) (	Y2 >> 16 ) ] ^	\
-				 RT2[ (uint8) (	Y1 >>  8 ) ] ^	\
-				 RT3[ (uint8) (	Y0		 ) ];	\
-}
-
-	AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 1 */
-	AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 2 */
-	AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 3 */
-	AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 4 */
-	AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 5 */
-	AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 6 */
-	AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 7 */
-	AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 8 */
-	AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 9 */
-
-	if(	ctx->nr	> 10 )
-	{
-		AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );	/* round 10	*/
-		AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );	/* round 11	*/
-	}
-
-	if(	ctx->nr	> 12 )
-	{
-		AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );	/* round 12	*/
-		AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );	/* round 13	*/
-	}
-
-	/* last	round */
-
-	RK += 4;
-
-	X0 = RK[0] ^ ( RSb[	(uint8)	( Y0 >>	24 ) ] << 24 ) ^
-				 ( RSb[	(uint8)	( Y3 >>	16 ) ] << 16 ) ^
-				 ( RSb[	(uint8)	( Y2 >>	 8 ) ] <<  8 ) ^
-				 ( RSb[	(uint8)	( Y1	   ) ]		 );
-
-	X1 = RK[1] ^ ( RSb[	(uint8)	( Y1 >>	24 ) ] << 24 ) ^
-				 ( RSb[	(uint8)	( Y0 >>	16 ) ] << 16 ) ^
-				 ( RSb[	(uint8)	( Y3 >>	 8 ) ] <<  8 ) ^
-				 ( RSb[	(uint8)	( Y2	   ) ]		 );
-
-	X2 = RK[2] ^ ( RSb[	(uint8)	( Y2 >>	24 ) ] << 24 ) ^
-				 ( RSb[	(uint8)	( Y1 >>	16 ) ] << 16 ) ^
-				 ( RSb[	(uint8)	( Y0 >>	 8 ) ] <<  8 ) ^
-				 ( RSb[	(uint8)	( Y3	   ) ]		 );
-
-	X3 = RK[3] ^ ( RSb[	(uint8)	( Y3 >>	24 ) ] << 24 ) ^
-				 ( RSb[	(uint8)	( Y2 >>	16 ) ] << 16 ) ^
-				 ( RSb[	(uint8)	( Y1 >>	 8 ) ] <<  8 ) ^
-				 ( RSb[	(uint8)	( Y0	   ) ]		 );
-
-	PUT_UINT32(	X0,	output,	 0 );
-	PUT_UINT32(	X1,	output,	 4 );
-	PUT_UINT32(	X2,	output,	 8 );
-	PUT_UINT32(	X3,	output,	12 );
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		SHA1 function
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	HMAC_SHA1(
-	IN	UCHAR	*text,
-	IN	UINT	text_len,
-	IN	UCHAR	*key,
-	IN	UINT	key_len,
-	IN	UCHAR	*digest)
-{
-	SHA_CTX	context;
-	UCHAR	k_ipad[65]; /* inner padding - key XORd with ipad	*/
-	UCHAR	k_opad[65]; /* outer padding - key XORd with opad	*/
-	INT		i;
-
-	// if key is longer	than 64	bytes reset	it to key=SHA1(key)
-	if (key_len	> 64)
-	{
-		SHA_CTX		 tctx;
-		SHAInit(&tctx);
-		SHAUpdate(&tctx, key, key_len);
-		SHAFinal(&tctx,	key);
-		key_len	= 20;
-	}
-	NdisZeroMemory(k_ipad, sizeof(k_ipad));
-	NdisZeroMemory(k_opad, sizeof(k_opad));
-	NdisMoveMemory(k_ipad, key,	key_len);
-	NdisMoveMemory(k_opad, key,	key_len);
-
-	// XOR key with	ipad and opad values
-	for	(i = 0;	i <	64;	i++)
-	{
-		k_ipad[i] ^= 0x36;
-		k_opad[i] ^= 0x5c;
-	}
-
-	// perform inner SHA1
-	SHAInit(&context); 						/* init context for 1st pass */
-	SHAUpdate(&context,	k_ipad,	64);		/*	start with inner pad */
-	SHAUpdate(&context,	text, text_len);	/*	then text of datagram */
-	SHAFinal(&context, digest);				/* finish up 1st pass */
-
-	//perform outer	SHA1
-	SHAInit(&context);					/* init context for 2nd pass */
-	SHAUpdate(&context,	k_opad,	64);	/*	start with outer pad */
-	SHAUpdate(&context,	digest,	20);	/*	then results of	1st	hash */
-	SHAFinal(&context, digest);			/* finish up 2nd pass */
-
-}
-
-/*
-* F(P, S, c, i) = U1 xor U2 xor ... Uc
-* U1 = PRF(P, S || Int(i))
-* U2 = PRF(P, U1)
-* Uc = PRF(P, Uc-1)
-*/
-
-void F(char *password, unsigned char *ssid, int ssidlength, int iterations, int count, unsigned char *output)
-{
-    unsigned char digest[36], digest1[SHA_DIGEST_LEN];
-    int i, j;
-
-    /* U1 = PRF(P, S || int(i)) */
-    memcpy(digest, ssid, ssidlength);
-    digest[ssidlength] = (unsigned char)((count>>24) & 0xff);
-    digest[ssidlength+1] = (unsigned char)((count>>16) & 0xff);
-    digest[ssidlength+2] = (unsigned char)((count>>8) & 0xff);
-    digest[ssidlength+3] = (unsigned char)(count & 0xff);
-    HMAC_SHA1(digest, ssidlength+4, (unsigned char*) password, (int) strlen(password), digest1); // for WPA update
-
-    /* output = U1 */
-    memcpy(output, digest1, SHA_DIGEST_LEN);
-
-    for (i = 1; i < iterations; i++)
-    {
-        /* Un = PRF(P, Un-1) */
-        HMAC_SHA1(digest1, SHA_DIGEST_LEN, (unsigned char*) password, (int) strlen(password), digest); // for WPA update
-        memcpy(digest1, digest, SHA_DIGEST_LEN);
-
-        /* output = output xor Un */
-        for (j = 0; j < SHA_DIGEST_LEN; j++)
-        {
-            output[j] ^= digest[j];
-        }
-    }
-}
-/*
-* password - ascii string up to 63 characters in length
-* ssid - octet string up to 32 octets
-* ssidlength - length of ssid in octets
-* output must be 40 octets in length and outputs 256 bits of key
-*/
-int PasswordHash(char *password, unsigned char *ssid, int ssidlength, unsigned char *output)
-{
-    if ((strlen(password) > 63) || (ssidlength > 32))
-        return 0;
-
-    F(password, ssid, ssidlength, 4096, 1, output);
-    F(password, ssid, ssidlength, 4096, 2, &output[SHA_DIGEST_LEN]);
-    return 1;
-}
-
-
+#include "../../rt2860/common/md5.c"
diff --git a/drivers/staging/rt2870/common/mlme.c b/drivers/staging/rt2870/common/mlme.c
index a26bc03..f88040a 100644
--- a/drivers/staging/rt2870/common/mlme.c
+++ b/drivers/staging/rt2870/common/mlme.c
@@ -1,8609 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	mlme.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang	2004-08-25		Modify from RT2500 code base
-	John Chang	2004-09-06		modified for RT2600
-*/
-
-#include "../rt_config.h"
-#include <stdarg.h>
-
-UCHAR	CISCO_OUI[] = {0x00, 0x40, 0x96};
-
-UCHAR	WPA_OUI[] = {0x00, 0x50, 0xf2, 0x01};
-UCHAR	RSN_OUI[] = {0x00, 0x0f, 0xac};
-UCHAR	WAPI_OUI[] = {0x00, 0x14, 0x72};
-UCHAR   WME_INFO_ELEM[]  = {0x00, 0x50, 0xf2, 0x02, 0x00, 0x01};
-UCHAR   WME_PARM_ELEM[] = {0x00, 0x50, 0xf2, 0x02, 0x01, 0x01};
-UCHAR	Ccx2QosInfo[] = {0x00, 0x40, 0x96, 0x04};
-UCHAR   RALINK_OUI[]  = {0x00, 0x0c, 0x43};
-UCHAR   BROADCOM_OUI[]  = {0x00, 0x90, 0x4c};
-UCHAR   WPS_OUI[] = {0x00, 0x50, 0xf2, 0x04};
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
-UCHAR	PRE_N_HT_OUI[]	= {0x00, 0x90, 0x4c};
-#endif // DOT11_N_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-UCHAR RateSwitchTable[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x11, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x00,  0, 40, 101,
-    0x01, 0x00,  1, 40, 50,
-    0x02, 0x00,  2, 35, 45,
-    0x03, 0x00,  3, 20, 45,
-    0x04, 0x21,  0, 30, 50,
-    0x05, 0x21,  1, 20, 50,
-    0x06, 0x21,  2, 20, 50,
-    0x07, 0x21,  3, 15, 50,
-    0x08, 0x21,  4, 15, 30,
-    0x09, 0x21,  5, 10, 25,
-    0x0a, 0x21,  6,  8, 25,
-    0x0b, 0x21,  7,  8, 25,
-    0x0c, 0x20, 12,  15, 30,
-    0x0d, 0x20, 13,  8, 20,
-    0x0e, 0x20, 14,  8, 20,
-    0x0f, 0x20, 15,  8, 25,
-    0x10, 0x22, 15,  8, 25,
-    0x11, 0x00,  0,  0,  0,
-    0x12, 0x00,  0,  0,  0,
-    0x13, 0x00,  0,  0,  0,
-    0x14, 0x00,  0,  0,  0,
-    0x15, 0x00,  0,  0,  0,
-    0x16, 0x00,  0,  0,  0,
-    0x17, 0x00,  0,  0,  0,
-    0x18, 0x00,  0,  0,  0,
-    0x19, 0x00,  0,  0,  0,
-    0x1a, 0x00,  0,  0,  0,
-    0x1b, 0x00,  0,  0,  0,
-    0x1c, 0x00,  0,  0,  0,
-    0x1d, 0x00,  0,  0,  0,
-    0x1e, 0x00,  0,  0,  0,
-    0x1f, 0x00,  0,  0,  0,
-};
-
-UCHAR RateSwitchTable11B[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x04, 0x03,  0,  0,  0,						// Initial used item after association
-    0x00, 0x00,  0, 40, 101,
-    0x01, 0x00,  1, 40, 50,
-    0x02, 0x00,  2, 35, 45,
-    0x03, 0x00,  3, 20, 45,
-};
-
-UCHAR RateSwitchTable11BG[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0a, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x00,  0, 40, 101,
-    0x01, 0x00,  1, 40, 50,
-    0x02, 0x00,  2, 35, 45,
-    0x03, 0x00,  3, 20, 45,
-    0x04, 0x10,  2, 20, 35,
-    0x05, 0x10,  3, 16, 35,
-    0x06, 0x10,  4, 10, 25,
-    0x07, 0x10,  5, 16, 25,
-    0x08, 0x10,  6, 10, 25,
-    0x09, 0x10,  7, 10, 13,
-};
-
-UCHAR RateSwitchTable11G[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x08, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x10,  0, 20, 101,
-    0x01, 0x10,  1, 20, 35,
-    0x02, 0x10,  2, 20, 35,
-    0x03, 0x10,  3, 16, 35,
-    0x04, 0x10,  4, 10, 25,
-    0x05, 0x10,  5, 16, 25,
-    0x06, 0x10,  6, 10, 25,
-    0x07, 0x10,  7, 10, 13,
-};
-
-#ifdef DOT11_N_SUPPORT
-UCHAR RateSwitchTable11N1S[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x09, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30, 101,
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x21,  5, 10, 25,
-    0x06, 0x21,  6,  8, 14,
-    0x07, 0x21,  7,  8, 14,
-    0x08, 0x23,  7,  8, 14,
-};
-
-UCHAR RateSwitchTable11N2S[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0a, 0x00,  0,  0,  0,      // Initial used item after association
-    0x00, 0x21,  0, 30, 101,
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x20, 12,  15, 30,
-    0x06, 0x20, 13,  8, 20,
-    0x07, 0x20, 14,  8, 20,
-    0x08, 0x20, 15,  8, 25,
-    0x09, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11N3S[] = {
-// Item No.	Mode	Curr-MCS	TrainUp	TrainDown	// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0a, 0x00,  0,  0,  0,      // Initial used item after association
-    0x00, 0x21,  0, 30, 101,
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x20, 12,  15, 30,
-    0x06, 0x20, 13,  8, 20,
-    0x07, 0x20, 14,  8, 20,
-    0x08, 0x20, 15,  8, 25,
-    0x09, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11N2SForABand[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0b, 0x09,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30, 101,
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x21,  5, 15, 30,
-    0x06, 0x20, 12,  15, 30,
-    0x07, 0x20, 13,  8, 20,
-    0x08, 0x20, 14,  8, 20,
-    0x09, 0x20, 15,  8, 25,
-    0x0a, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11N3SForABand[] = { // 3*3
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0b, 0x09,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30, 101,
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x21,  5, 15, 30,
-    0x06, 0x20, 12,  15, 30,
-    0x07, 0x20, 13,  8, 20,
-    0x08, 0x20, 14,  8, 20,
-    0x09, 0x20, 15,  8, 25,
-    0x0a, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11BGN1S[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0d, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x00,  0, 40, 101,
-    0x01, 0x00,  1, 40, 50,
-    0x02, 0x00,  2, 35, 45,
-    0x03, 0x00,  3, 20, 45,
-    0x04, 0x21,  0, 30,101,	//50
-    0x05, 0x21,  1, 20, 50,
-    0x06, 0x21,  2, 20, 50,
-    0x07, 0x21,  3, 15, 50,
-    0x08, 0x21,  4, 15, 30,
-    0x09, 0x21,  5, 10, 25,
-    0x0a, 0x21,  6,  8, 14,
-    0x0b, 0x21,  7,  8, 14,
-	0x0c, 0x23,  7,  8, 14,
-};
-
-UCHAR RateSwitchTable11BGN2S[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0a, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30,101,	//50
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x20, 12, 15, 30,
-    0x06, 0x20, 13,  8, 20,
-    0x07, 0x20, 14,  8, 20,
-    0x08, 0x20, 15,  8, 25,
-    0x09, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11BGN3S[] = { // 3*3
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0a, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30,101,	//50
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 20, 50,
-    0x04, 0x21,  4, 15, 50,
-#if 1
-    0x05, 0x20, 20, 15, 30,
-    0x06, 0x20, 21,  8, 20,
-    0x07, 0x20, 22,  8, 20,
-    0x08, 0x20, 23,  8, 25,
-    0x09, 0x22, 23,  8, 25,
-#else // for RT2860 2*3 test
-    0x05, 0x20, 12, 15, 30,
-    0x06, 0x20, 13,  8, 20,
-    0x07, 0x20, 14,  8, 20,
-    0x08, 0x20, 15,  8, 25,
-    0x09, 0x22, 15,  8, 25,
-#endif
-};
-
-UCHAR RateSwitchTable11BGN2SForABand[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0b, 0x09,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30,101,	//50
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x21,  5, 15, 30,
-    0x06, 0x20, 12, 15, 30,
-    0x07, 0x20, 13,  8, 20,
-    0x08, 0x20, 14,  8, 20,
-    0x09, 0x20, 15,  8, 25,
-    0x0a, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11BGN3SForABand[] = { // 3*3
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0c, 0x09,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30,101,	//50
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x21,  5, 15, 30,
-    0x06, 0x21, 12, 15, 30,
-    0x07, 0x20, 20, 15, 30,
-    0x08, 0x20, 21,  8, 20,
-    0x09, 0x20, 22,  8, 20,
-    0x0a, 0x20, 23,  8, 25,
-    0x0b, 0x22, 23,  8, 25,
-};
-#endif // DOT11_N_SUPPORT //
-
-PUCHAR ReasonString[] = {
-	/* 0  */	 "Reserved",
-	/* 1  */	 "Unspecified Reason",
-	/* 2  */	 "Previous Auth no longer valid",
-	/* 3  */	 "STA is leaving / has left",
-	/* 4  */	 "DIS-ASSOC due to inactivity",
-	/* 5  */	 "AP unable to hanle all associations",
-	/* 6  */	 "class 2 error",
-	/* 7  */	 "class 3 error",
-	/* 8  */	 "STA is leaving / has left",
-	/* 9  */	 "require auth before assoc/re-assoc",
-	/* 10 */	 "Reserved",
-	/* 11 */	 "Reserved",
-	/* 12 */	 "Reserved",
-	/* 13 */	 "invalid IE",
-	/* 14 */	 "MIC error",
-	/* 15 */	 "4-way handshake timeout",
-	/* 16 */	 "2-way (group key) handshake timeout",
-	/* 17 */	 "4-way handshake IE diff among AssosReq/Rsp/Beacon",
-	/* 18 */
-};
-
-extern UCHAR	 OfdmRateToRxwiMCS[];
-// since RT61 has better RX sensibility, we have to limit TX ACK rate not to exceed our normal data TX rate.
-// otherwise the WLAN peer may not be able to receive the ACK thus downgrade its data TX rate
-ULONG BasicRateMask[12]				= {0xfffff001 /* 1-Mbps */, 0xfffff003 /* 2 Mbps */, 0xfffff007 /* 5.5 */, 0xfffff00f /* 11 */,
-									  0xfffff01f /* 6 */	 , 0xfffff03f /* 9 */	  , 0xfffff07f /* 12 */ , 0xfffff0ff /* 18 */,
-									  0xfffff1ff /* 24 */	 , 0xfffff3ff /* 36 */	  , 0xfffff7ff /* 48 */ , 0xffffffff /* 54 */};
-
-UCHAR MULTICAST_ADDR[MAC_ADDR_LEN] = {0x1,  0x00, 0x00, 0x00, 0x00, 0x00};
-UCHAR BROADCAST_ADDR[MAC_ADDR_LEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
-UCHAR ZERO_MAC_ADDR[MAC_ADDR_LEN]  = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-
-// e.g. RssiSafeLevelForTxRate[RATE_36]" means if the current RSSI is greater than
-//		this value, then it's quaranteed capable of operating in 36 mbps TX rate in
-//		clean environment.
-//								  TxRate: 1   2   5.5	11	 6	  9    12	18	 24   36   48	54	 72  100
-CHAR RssiSafeLevelForTxRate[] ={  -92, -91, -90, -87, -88, -86, -85, -83, -81, -78, -72, -71, -40, -40 };
-
-UCHAR  RateIdToMbps[]	 = { 1, 2, 5, 11, 6, 9, 12, 18, 24, 36, 48, 54, 72, 100};
-USHORT RateIdTo500Kbps[] = { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108, 144, 200};
-
-UCHAR  SsidIe	 = IE_SSID;
-UCHAR  SupRateIe = IE_SUPP_RATES;
-UCHAR  ExtRateIe = IE_EXT_SUPP_RATES;
-#ifdef DOT11_N_SUPPORT
-UCHAR  HtCapIe = IE_HT_CAP;
-UCHAR  AddHtInfoIe = IE_ADD_HT;
-UCHAR  NewExtChanIe = IE_SECONDARY_CH_OFFSET;
-#ifdef DOT11N_DRAFT3
-UCHAR  ExtHtCapIe = IE_EXT_CAPABILITY;
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-UCHAR  ErpIe	 = IE_ERP;
-UCHAR  DsIe 	 = IE_DS_PARM;
-UCHAR  TimIe	 = IE_TIM;
-UCHAR  WpaIe	 = IE_WPA;
-UCHAR  Wpa2Ie	 = IE_WPA2;
-UCHAR  IbssIe	 = IE_IBSS_PARM;
-UCHAR  Ccx2Ie	 = IE_CCX_V2;
-UCHAR  WapiIe	 = IE_WAPI;
-
-extern UCHAR	WPA_OUI[];
-
-UCHAR	SES_OUI[] = {0x00, 0x90, 0x4c};
-
-UCHAR	ZeroSsid[32] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
-
-// Reset the RFIC setting to new series
-RTMP_RF_REGS RF2850RegTable[] = {
-//		ch	 R1 		 R2 		 R3(TX0~4=0) R4
-		{1,  0x98402ecc, 0x984c0786, 0x9816b455, 0x9800510b},
-		{2,  0x98402ecc, 0x984c0786, 0x98168a55, 0x9800519f},
-		{3,  0x98402ecc, 0x984c078a, 0x98168a55, 0x9800518b},
-		{4,  0x98402ecc, 0x984c078a, 0x98168a55, 0x9800519f},
-		{5,  0x98402ecc, 0x984c078e, 0x98168a55, 0x9800518b},
-		{6,  0x98402ecc, 0x984c078e, 0x98168a55, 0x9800519f},
-		{7,  0x98402ecc, 0x984c0792, 0x98168a55, 0x9800518b},
-		{8,  0x98402ecc, 0x984c0792, 0x98168a55, 0x9800519f},
-		{9,  0x98402ecc, 0x984c0796, 0x98168a55, 0x9800518b},
-		{10, 0x98402ecc, 0x984c0796, 0x98168a55, 0x9800519f},
-		{11, 0x98402ecc, 0x984c079a, 0x98168a55, 0x9800518b},
-		{12, 0x98402ecc, 0x984c079a, 0x98168a55, 0x9800519f},
-		{13, 0x98402ecc, 0x984c079e, 0x98168a55, 0x9800518b},
-		{14, 0x98402ecc, 0x984c07a2, 0x98168a55, 0x98005193},
-
-		// 802.11 UNI / HyperLan 2
-		{36, 0x98402ecc, 0x984c099a, 0x98158a55, 0x980ed1a3},
-		{38, 0x98402ecc, 0x984c099e, 0x98158a55, 0x980ed193},
-		{40, 0x98402ec8, 0x984c0682, 0x98158a55, 0x980ed183},
-		{44, 0x98402ec8, 0x984c0682, 0x98158a55, 0x980ed1a3},
-		{46, 0x98402ec8, 0x984c0686, 0x98158a55, 0x980ed18b},
-		{48, 0x98402ec8, 0x984c0686, 0x98158a55, 0x980ed19b},
-		{52, 0x98402ec8, 0x984c068a, 0x98158a55, 0x980ed193},
-		{54, 0x98402ec8, 0x984c068a, 0x98158a55, 0x980ed1a3},
-		{56, 0x98402ec8, 0x984c068e, 0x98158a55, 0x980ed18b},
-		{60, 0x98402ec8, 0x984c0692, 0x98158a55, 0x980ed183},
-		{62, 0x98402ec8, 0x984c0692, 0x98158a55, 0x980ed193},
-		{64, 0x98402ec8, 0x984c0692, 0x98158a55, 0x980ed1a3}, // Plugfest#4, Day4, change RFR3 left4th 9->5.
-
-		// 802.11 HyperLan 2
-		{100, 0x98402ec8, 0x984c06b2, 0x98178a55, 0x980ed783},
-
-		// 2008.04.30 modified
-		// The system team has AN to improve the EVM value
-		// for channel 102 to 108 for the RT2850/RT2750 dual band solution.
-		{102, 0x98402ec8, 0x985c06b2, 0x98578a55, 0x980ed793},
-		{104, 0x98402ec8, 0x985c06b2, 0x98578a55, 0x980ed1a3},
-		{108, 0x98402ecc, 0x985c0a32, 0x98578a55, 0x980ed193},
-
-		{110, 0x98402ecc, 0x984c0a36, 0x98178a55, 0x980ed183},
-		{112, 0x98402ecc, 0x984c0a36, 0x98178a55, 0x980ed19b},
-		{116, 0x98402ecc, 0x984c0a3a, 0x98178a55, 0x980ed1a3},
-		{118, 0x98402ecc, 0x984c0a3e, 0x98178a55, 0x980ed193},
-		{120, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed183},
-		{124, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed193},
-		{126, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed15b}, // 0x980ed1bb->0x980ed15b required by Rory 20070927
-		{128, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed1a3},
-		{132, 0x98402ec4, 0x984c0386, 0x98178a55, 0x980ed18b},
-		{134, 0x98402ec4, 0x984c0386, 0x98178a55, 0x980ed193},
-		{136, 0x98402ec4, 0x984c0386, 0x98178a55, 0x980ed19b},
-		{140, 0x98402ec4, 0x984c038a, 0x98178a55, 0x980ed183},
-
-		// 802.11 UNII
-		{149, 0x98402ec4, 0x984c038a, 0x98178a55, 0x980ed1a7},
-		{151, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed187},
-		{153, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed18f},
-		{157, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed19f},
-		{159, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed1a7},
-		{161, 0x98402ec4, 0x984c0392, 0x98178a55, 0x980ed187},
-		{165, 0x98402ec4, 0x984c0392, 0x98178a55, 0x980ed197},
-
-		// Japan
-		{184, 0x95002ccc, 0x9500491e, 0x9509be55, 0x950c0a0b},
-		{188, 0x95002ccc, 0x95004922, 0x9509be55, 0x950c0a13},
-		{192, 0x95002ccc, 0x95004926, 0x9509be55, 0x950c0a1b},
-		{196, 0x95002ccc, 0x9500492a, 0x9509be55, 0x950c0a23},
-		{208, 0x95002ccc, 0x9500493a, 0x9509be55, 0x950c0a13},
-		{212, 0x95002ccc, 0x9500493e, 0x9509be55, 0x950c0a1b},
-		{216, 0x95002ccc, 0x95004982, 0x9509be55, 0x950c0a23},
-
-		// still lack of MMAC(Japan) ch 34,38,42,46
-};
-UCHAR	NUM_OF_2850_CHNL = (sizeof(RF2850RegTable) / sizeof(RTMP_RF_REGS));
-
-FREQUENCY_ITEM FreqItems3020[] =
-{
-	/**************************************************/
-	// ISM : 2.4 to 2.483 GHz                         //
-	/**************************************************/
-	// 11g
-	/**************************************************/
-	//-CH---N-------R---K-----------
-	{1,    241,  2,  2},
-	{2,    241,	 2,  7},
-	{3,    242,	 2,  2},
-	{4,    242,	 2,  7},
-	{5,    243,	 2,  2},
-	{6,    243,	 2,  7},
-	{7,    244,	 2,  2},
-	{8,    244,	 2,  7},
-	{9,    245,	 2,  2},
-	{10,   245,	 2,  7},
-	{11,   246,	 2,  2},
-	{12,   246,	 2,  7},
-	{13,   247,	 2,  2},
-	{14,   248,	 2,  4},
-};
-#define	NUM_OF_3020_CHNL	(sizeof(FreqItems3020) / sizeof(FREQUENCY_ITEM))
-
-/*
-	==========================================================================
-	Description:
-		initialize the MLME task and its data structure (queue, spinlock,
-		timer, state machines).
-
-	IRQL = PASSIVE_LEVEL
-
-	Return:
-		always return NDIS_STATUS_SUCCESS
-
-	==========================================================================
-*/
-NDIS_STATUS MlmeInit(
-	IN PRTMP_ADAPTER pAd)
-{
-	NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> MLME Initialize\n"));
-
-	do
-	{
-		Status = MlmeQueueInit(&pAd->Mlme.Queue);
-		if(Status != NDIS_STATUS_SUCCESS)
-			break;
-
-		pAd->Mlme.bRunning = FALSE;
-		NdisAllocateSpinLock(&pAd->Mlme.TaskLock);
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			BssTableInit(&pAd->ScanTab);
-
-			// init STA state machines
-			AssocStateMachineInit(pAd, &pAd->Mlme.AssocMachine, pAd->Mlme.AssocFunc);
-			AuthStateMachineInit(pAd, &pAd->Mlme.AuthMachine, pAd->Mlme.AuthFunc);
-			AuthRspStateMachineInit(pAd, &pAd->Mlme.AuthRspMachine, pAd->Mlme.AuthRspFunc);
-			SyncStateMachineInit(pAd, &pAd->Mlme.SyncMachine, pAd->Mlme.SyncFunc);
-			WpaPskStateMachineInit(pAd, &pAd->Mlme.WpaPskMachine, pAd->Mlme.WpaPskFunc);
-			AironetStateMachineInit(pAd, &pAd->Mlme.AironetMachine, pAd->Mlme.AironetFunc);
-
-#ifdef QOS_DLS_SUPPORT
-			DlsStateMachineInit(pAd, &pAd->Mlme.DlsMachine, pAd->Mlme.DlsFunc);
-#endif // QOS_DLS_SUPPORT //
-
-
-			// Since we are using switch/case to implement it, the init is different from the above
-			// state machine init
-			MlmeCntlInit(pAd, &pAd->Mlme.CntlMachine, NULL);
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-		ActionStateMachineInit(pAd, &pAd->Mlme.ActMachine, pAd->Mlme.ActFunc);
-
-		// Init mlme periodic timer
-		RTMPInitTimer(pAd, &pAd->Mlme.PeriodicTimer, GET_TIMER_FUNCTION(MlmePeriodicExec), pAd, TRUE);
-
-		// Set mlme periodic timer
-		RTMPSetTimer(&pAd->Mlme.PeriodicTimer, MLME_TASK_EXEC_INTV);
-
-		// software-based RX Antenna diversity
-		RTMPInitTimer(pAd, &pAd->Mlme.RxAntEvalTimer, GET_TIMER_FUNCTION(AsicRxAntEvalTimeout), pAd, FALSE);
-
-	} while (FALSE);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- MLME Initialize\n"));
-
-	return Status;
-}
-
-/*
-	==========================================================================
-	Description:
-		main loop of the MLME
-	Pre:
-		Mlme has to be initialized, and there are something inside the queue
-	Note:
-		This function is invoked from MPSetInformation and MPReceive;
-		This task guarantee only one MlmeHandler will run.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID MlmeHandler(
-	IN PRTMP_ADAPTER pAd)
-{
-	MLME_QUEUE_ELEM 	   *Elem = NULL;
-#ifdef APCLI_SUPPORT
-	SHORT apcliIfIndex;
-#endif
-
-	// Only accept MLME and Frame from peer side, no other (control/data) frame should
-	// get into this state machine
-
-	NdisAcquireSpinLock(&pAd->Mlme.TaskLock);
-	if(pAd->Mlme.bRunning)
-	{
-		NdisReleaseSpinLock(&pAd->Mlme.TaskLock);
-		return;
-	}
-	else
-	{
-		pAd->Mlme.bRunning = TRUE;
-	}
-	NdisReleaseSpinLock(&pAd->Mlme.TaskLock);
-
-	while (!MlmeQueueEmpty(&pAd->Mlme.Queue))
-	{
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_MLME_RESET_IN_PROGRESS) ||
-			RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS) ||
-			RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("Device Halted or Removed or MlmeRest, exit MlmeHandler! (queue num = %ld)\n", pAd->Mlme.Queue.Num));
-			break;
-		}
-
-#ifdef RALINK_ATE
-		if(ATE_ON(pAd))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now in MlmeHandler\n"));
-			break;
-		}
-#endif // RALINK_ATE //
-
-		//From message type, determine which state machine I should drive
-		if (MlmeDequeue(&pAd->Mlme.Queue, &Elem))
-		{
-#ifdef RT2870
-			if (Elem->MsgType == MT2_RESET_CONF)
-			{
-				DBGPRINT_RAW(RT_DEBUG_TRACE, ("!!! reset MLME state machine !!!\n"));
-				MlmeRestartStateMachine(pAd);
-				Elem->Occupied = FALSE;
-				Elem->MsgLen = 0;
-				continue;
-			}
-#endif // RT2870 //
-
-			// if dequeue success
-			switch (Elem->Machine)
-			{
-				// STA state machines
-#ifdef	CONFIG_STA_SUPPORT
-				case ASSOC_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.AssocMachine, Elem);
-					break;
-				case AUTH_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.AuthMachine, Elem);
-					break;
-				case AUTH_RSP_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.AuthRspMachine, Elem);
-					break;
-				case SYNC_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.SyncMachine, Elem);
-					break;
-				case MLME_CNTL_STATE_MACHINE:
-					MlmeCntlMachinePerformAction(pAd, &pAd->Mlme.CntlMachine, Elem);
-					break;
-				case WPA_PSK_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.WpaPskMachine, Elem);
-					break;
-#ifdef LEAP_SUPPORT
-				case LEAP_STATE_MACHINE:
-					LeapMachinePerformAction(pAd, &pAd->Mlme.LeapMachine, Elem);
-					break;
-#endif
-				case AIRONET_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.AironetMachine, Elem);
-					break;
-
-#ifdef QOS_DLS_SUPPORT
-				case DLS_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.DlsMachine, Elem);
-					break;
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-				case ACTION_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.ActMachine, Elem);
-					break;
-
-
-
-
-				default:
-					DBGPRINT(RT_DEBUG_TRACE, ("ERROR: Illegal machine %ld in MlmeHandler()\n", Elem->Machine));
-					break;
-			} // end of switch
-
-			// free MLME element
-			Elem->Occupied = FALSE;
-			Elem->MsgLen = 0;
-
-		}
-		else {
-			DBGPRINT_ERR(("MlmeHandler: MlmeQueue empty\n"));
-		}
-	}
-
-	NdisAcquireSpinLock(&pAd->Mlme.TaskLock);
-	pAd->Mlme.bRunning = FALSE;
-	NdisReleaseSpinLock(&pAd->Mlme.TaskLock);
-}
-
-/*
-	==========================================================================
-	Description:
-		Destructor of MLME (Destroy queue, state machine, spin lock and timer)
-	Parameters:
-		Adapter - NIC Adapter pointer
-	Post:
-		The MLME task will no longer work properly
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
- */
-VOID MlmeHalt(
-	IN PRTMP_ADAPTER pAd)
-{
-	BOOLEAN 	  Cancelled;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==> MlmeHalt\n"));
-
-	if (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
-	{
-		// disable BEACON generation and other BEACON related hardware timers
-		AsicDisableSync(pAd);
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-#ifdef QOS_DLS_SUPPORT
-		UCHAR		i;
-#endif // QOS_DLS_SUPPORT //
-		// Cancel pending timers
-		RTMPCancelTimer(&pAd->MlmeAux.AssocTimer,		&Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer,		&Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer,	&Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.AuthTimer,		&Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer,		&Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer,		&Cancelled);
-
-#ifdef QOS_DLS_SUPPORT
-		for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &Cancelled);
-		}
-#endif // QOS_DLS_SUPPORT //
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	RTMPCancelTimer(&pAd->Mlme.PeriodicTimer,		&Cancelled);
-	RTMPCancelTimer(&pAd->Mlme.RxAntEvalTimer,		&Cancelled);
-
-
-
-	if (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
-	{
-		// Set LED
-		RTMPSetLED(pAd, LED_HALT);
-        RTMPSetSignalLED(pAd, -100);	// Force signal strength Led to be turned off, firmware is not done it.
-#ifdef RT2870
-        {
-            LED_CFG_STRUC LedCfg;
-            RTMP_IO_READ32(pAd, LED_CFG, &LedCfg.word);
-            LedCfg.field.LedPolar = 0;
-            LedCfg.field.RLedMode = 0;
-            LedCfg.field.GLedMode = 0;
-            LedCfg.field.YLedMode = 0;
-            RTMP_IO_WRITE32(pAd, LED_CFG, LedCfg.word);
-        }
-#endif // RT2870 //
-	}
-
-	RTMPusecDelay(5000);    //  5 msec to gurantee Ant Diversity timer canceled
-
-	MlmeQueueDestroy(&pAd->Mlme.Queue);
-	NdisFreeSpinLock(&pAd->Mlme.TaskLock);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<== MlmeHalt\n"));
-}
-
-VOID MlmeResetRalinkCounters(
-	IN  PRTMP_ADAPTER   pAd)
-{
-	pAd->RalinkCounters.LastOneSecRxOkDataCnt = pAd->RalinkCounters.OneSecRxOkDataCnt;
-	// clear all OneSecxxx counters.
-	pAd->RalinkCounters.OneSecBeaconSentCnt = 0;
-	pAd->RalinkCounters.OneSecFalseCCACnt = 0;
-	pAd->RalinkCounters.OneSecRxFcsErrCnt = 0;
-	pAd->RalinkCounters.OneSecRxOkCnt = 0;
-	pAd->RalinkCounters.OneSecTxFailCount = 0;
-	pAd->RalinkCounters.OneSecTxNoRetryOkCount = 0;
-	pAd->RalinkCounters.OneSecTxRetryOkCount = 0;
-	pAd->RalinkCounters.OneSecRxOkDataCnt = 0;
-
-	// TODO: for debug only. to be removed
-	pAd->RalinkCounters.OneSecOsTxCount[QID_AC_BE] = 0;
-	pAd->RalinkCounters.OneSecOsTxCount[QID_AC_BK] = 0;
-	pAd->RalinkCounters.OneSecOsTxCount[QID_AC_VI] = 0;
-	pAd->RalinkCounters.OneSecOsTxCount[QID_AC_VO] = 0;
-	pAd->RalinkCounters.OneSecDmaDoneCount[QID_AC_BE] = 0;
-	pAd->RalinkCounters.OneSecDmaDoneCount[QID_AC_BK] = 0;
-	pAd->RalinkCounters.OneSecDmaDoneCount[QID_AC_VI] = 0;
-	pAd->RalinkCounters.OneSecDmaDoneCount[QID_AC_VO] = 0;
-	pAd->RalinkCounters.OneSecTxDoneCount = 0;
-	pAd->RalinkCounters.OneSecRxCount = 0;
-	pAd->RalinkCounters.OneSecTxAggregationCount = 0;
-	pAd->RalinkCounters.OneSecRxAggregationCount = 0;
-
-	return;
-}
-
-unsigned long rx_AMSDU;
-unsigned long rx_Total;
-
-/*
-	==========================================================================
-	Description:
-		This routine is executed periodically to -
-		1. Decide if it's a right time to turn on PwrMgmt bit of all
-		   outgoiing frames
-		2. Calculate ChannelQuality based on statistics of the last
-		   period, so that TX rate won't toggling very frequently between a
-		   successful TX and a failed TX.
-		3. If the calculated ChannelQuality indicated current connection not
-		   healthy, then a ROAMing attempt is tried here.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-#define ADHOC_BEACON_LOST_TIME		(8*OS_HZ)  // 8 sec
-VOID MlmePeriodicExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	ULONG			TxTotalCnt;
-	PRTMP_ADAPTER	pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if ((RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_HALT_IN_PROGRESS |
-								fRTMP_ADAPTER_RADIO_OFF |
-								fRTMP_ADAPTER_RADIO_MEASUREMENT |
-								fRTMP_ADAPTER_RESET_IN_PROGRESS))))
-		return;
-
-	RT28XX_MLME_PRE_SANITY_CHECK(pAd);
-
-#ifdef RALINK_ATE
-	/* Do not show RSSI until "Normal 1 second Mlme PeriodicExec". */
-	if (ATE_ON(pAd))
-	{
-		if (pAd->Mlme.PeriodicRound % MLME_TASK_EXEC_MULTIPLE != (MLME_TASK_EXEC_MULTIPLE - 1))
-	{
-			pAd->Mlme.PeriodicRound ++;
-			return;
-		}
-	}
-#endif // RALINK_ATE //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Do nothing if monitor mode is on
-		if (MONITOR_ON(pAd))
-			return;
-
-		if (pAd->Mlme.PeriodicRound & 0x1)
-		{
-			// This is the fix for wifi 11n extension channel overlapping test case.  for 2860D
-			if (((pAd->MACVersion & 0xffff) == 0x0101) &&
-				(STA_TGN_WIFI_ON(pAd)) &&
-				(pAd->CommonCfg.IOTestParm.bToggle == FALSE))
-
-				{
-					RTMP_IO_WRITE32(pAd, TXOP_CTRL_CFG, 0x24Bf);
-					pAd->CommonCfg.IOTestParm.bToggle = TRUE;
-				}
-				else if ((STA_TGN_WIFI_ON(pAd)) &&
-						((pAd->MACVersion & 0xffff) == 0x0101))
-				{
-					RTMP_IO_WRITE32(pAd, TXOP_CTRL_CFG, 0x243f);
-					pAd->CommonCfg.IOTestParm.bToggle = FALSE;
-				}
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	pAd->bUpdateBcnCntDone = FALSE;
-
-//	RECBATimerTimeout(SystemSpecific1,FunctionContext,SystemSpecific2,SystemSpecific3);
-	pAd->Mlme.PeriodicRound ++;
-
-	// execute every 500ms
-	if ((pAd->Mlme.PeriodicRound % 5 == 0) && RTMPAutoRateSwitchCheck(pAd)/*(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED))*/)
-	{
-#ifdef CONFIG_STA_SUPPORT
-		// perform dynamic tx rate switching based on past TX history
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			if ((OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)
-					)
-				&& (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE)))
-				MlmeDynamicTxRateSwitching(pAd);
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	// Normal 1 second Mlme PeriodicExec.
-	if (pAd->Mlme.PeriodicRound %MLME_TASK_EXEC_MULTIPLE == 0)
-	{
-                pAd->Mlme.OneSecPeriodicRound ++;
-
-#ifdef RALINK_ATE
-    	if (ATE_ON(pAd))
-    	{
-			/* request from Baron : move this routine from later to here */
-			/* for showing Rx error count in ATE RXFRAME */
-            NICUpdateRawCounters(pAd);
-			if (pAd->ate.bRxFer == 1)
-			{
-				pAd->ate.RxTotalCnt += pAd->ate.RxCntPerSec;
-			    ate_print(KERN_EMERG "MlmePeriodicExec: Rx packet cnt = %d/%d\n", pAd->ate.RxCntPerSec, pAd->ate.RxTotalCnt);
-				pAd->ate.RxCntPerSec = 0;
-
-				if (pAd->ate.RxAntennaSel == 0)
-					ate_print(KERN_EMERG "MlmePeriodicExec: Rx AvgRssi0=%d, AvgRssi1=%d, AvgRssi2=%d\n\n",
-						pAd->ate.AvgRssi0, pAd->ate.AvgRssi1, pAd->ate.AvgRssi2);
-				else
-					ate_print(KERN_EMERG "MlmePeriodicExec: Rx AvgRssi=%d\n\n", pAd->ate.AvgRssi0);
-			}
-			MlmeResetRalinkCounters(pAd);
-			return;
-    	}
-#endif // RALINK_ATE //
-
-
-		if (rx_Total)
-		{
-
-			// reset counters
-			rx_AMSDU = 0;
-			rx_Total = 0;
-		}
-
-		//ORIBATimerTimeout(pAd);
-
-		// Media status changed, report to NDIS
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_MEDIA_STATE_CHANGE))
-		{
-			RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_MEDIA_STATE_CHANGE);
-			if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-			{
-				pAd->IndicateMediaState = NdisMediaStateConnected;
-				RTMP_IndicateMediaState(pAd);
-
-			}
-			else
-			{
-				pAd->IndicateMediaState = NdisMediaStateDisconnected;
-				RTMP_IndicateMediaState(pAd);
-			}
-		}
-
-		NdisGetSystemUpTime(&pAd->Mlme.Now32);
-
-		// add the most up-to-date h/w raw counters into software variable, so that
-		// the dynamic tuning mechanism below are based on most up-to-date information
-		NICUpdateRawCounters(pAd);
-
-#ifdef RT2870
-		RT2870_WatchDog(pAd);
-#endif // RT2870 //
-
-#ifdef DOT11_N_SUPPORT
-   		// Need statistics after read counter. So put after NICUpdateRawCounters
-		ORIBATimerTimeout(pAd);
-#endif // DOT11_N_SUPPORT //
-
-		// if MGMT RING is full more than twice within 1 second, we consider there's
-		// a hardware problem stucking the TX path. In this case, try a hardware reset
-		// to recover the system
-	//	if (pAd->RalinkCounters.MgmtRingFullCount >= 2)
-	//		RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_HARDWARE_ERROR);
-	//	else
-	//		pAd->RalinkCounters.MgmtRingFullCount = 0;
-
-		// The time period for checking antenna is according to traffic
-		if (pAd->Mlme.bEnableAutoAntennaCheck)
-		{
-			TxTotalCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount +
-							 pAd->RalinkCounters.OneSecTxRetryOkCount +
-							 pAd->RalinkCounters.OneSecTxFailCount;
-
-			if (TxTotalCnt > 50)
-			{
-				if (pAd->Mlme.OneSecPeriodicRound % 10 == 0)
-				{
-					AsicEvaluateRxAnt(pAd);
-				}
-			}
-			else
-			{
-				if (pAd->Mlme.OneSecPeriodicRound % 3 == 0)
-				{
-					AsicEvaluateRxAnt(pAd);
-				}
-			}
-		}
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			STAMlmePeriodicExec(pAd);
-#endif // CONFIG_STA_SUPPORT //
-
-		MlmeResetRalinkCounters(pAd);
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			{
-				// When Adhoc beacon is enabled and RTS/CTS is enabled, there is a chance that hardware MAC FSM will run into a deadlock
-				// and sending CTS-to-self over and over.
-				// Software Patch Solution:
-				// 1. Polling debug state register 0x10F4 every one second.
-				// 2. If in 0x10F4 the ((bit29==1) && (bit7==1)) OR ((bit29==1) && (bit5==1)), it means the deadlock has occurred.
-				// 3. If the deadlock occurred, reset MAC/BBP by setting 0x1004 to 0x0001 for a while then setting it back to 0x000C again.
-
-				UINT32	MacReg = 0;
-
-				RTMP_IO_READ32(pAd, 0x10F4, &MacReg);
-				if (((MacReg & 0x20000000) && (MacReg & 0x80)) || ((MacReg & 0x20000000) && (MacReg & 0x20)))
-				{
-					RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x1);
-					RTMPusecDelay(1);
-					RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0xC);
-
-					DBGPRINT(RT_DEBUG_WARN,("Warning, MAC specific condition occurs \n"));
-				}
-			}
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		RT28XX_MLME_HANDLER(pAd);
-	}
-
-
-	pAd->bUpdateBcnCntDone = FALSE;
-}
-
-#ifdef CONFIG_STA_SUPPORT
-VOID STAMlmePeriodicExec(
-	PRTMP_ADAPTER pAd)
-{
-	ULONG	TxTotalCnt;
-	int 	i;
-
-//
-// We return here in ATE mode, because the statistics
-// that ATE needs are not collected via this routine.
-//
-#ifdef RALINK_ATE
-	// It is supposed that we will never reach here in ATE mode.
-	ASSERT(!(ATE_ON(pAd)));
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-    if (pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_DISABLE)
-#endif // WPA_SUPPLICANT_SUPPORT //
-    {
-    	// WPA MIC error should block association attempt for 60 seconds
-    	if (pAd->StaCfg.bBlockAssoc && (pAd->StaCfg.LastMicErrorTime + (60 * OS_HZ) < pAd->Mlme.Now32))
-    		pAd->StaCfg.bBlockAssoc = FALSE;
-    }
-
-    if ((pAd->PreMediaState != pAd->IndicateMediaState) && (pAd->CommonCfg.bWirelessEvent))
-	{
-		if (pAd->IndicateMediaState == NdisMediaStateConnected)
-		{
-			RTMPSendWirelessEvent(pAd, IW_STA_LINKUP_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-		}
-		pAd->PreMediaState = pAd->IndicateMediaState;
-	}
-
-
-
-
-   	AsicStaBbpTuning(pAd);
-
-	TxTotalCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount +
-					 pAd->RalinkCounters.OneSecTxRetryOkCount +
-					 pAd->RalinkCounters.OneSecTxFailCount;
-
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-	{
-		// update channel quality for Roaming and UI LinkQuality display
-		MlmeCalculateChannelQuality(pAd, pAd->Mlme.Now32);
-	}
-
-	// must be AFTER MlmeDynamicTxRateSwitching() because it needs to know if
-	// Radio is currently in noisy environment
-	if (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-		AsicAdjustTxPower(pAd);
-
-	if (INFRA_ON(pAd))
-	{
-#ifdef QOS_DLS_SUPPORT
-		// Check DLS time out, then tear down those session
-		RTMPCheckDLSTimeOut(pAd);
-#endif // QOS_DLS_SUPPORT //
-
-		// Is PSM bit consistent with user power management policy?
-		// This is the only place that will set PSM bit ON.
-		if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-		MlmeCheckPsmChange(pAd, pAd->Mlme.Now32);
-
-		pAd->RalinkCounters.LastOneSecTotalTxCount = TxTotalCnt;
-
-		if ((pAd->StaCfg.LastBeaconRxTime + 1*OS_HZ < pAd->Mlme.Now32) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) &&
-			((TxTotalCnt + pAd->RalinkCounters.OneSecRxOkCnt < 600)))
-		{
-			RTMPSetAGCInitValue(pAd, BW_20);
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - No BEACON. restore R66 to the low bound(%d) \n", (0x2E + GET_LNA_GAIN(pAd))));
-		}
-
-        //if ((pAd->RalinkCounters.OneSecTxNoRetryOkCount == 0) &&
-        //    (pAd->RalinkCounters.OneSecTxRetryOkCount == 0))
-        {
-    		if (pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable)
-    		{
-    		    // When APSD is enabled, the period changes as 20 sec
-    			if ((pAd->Mlme.OneSecPeriodicRound % 20) == 8)
-    				RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, TRUE);
-    		}
-    		else
-    		{
-    		    // Send out a NULL frame every 10 sec to inform AP that STA is still alive (Avoid being age out)
-    			if ((pAd->Mlme.OneSecPeriodicRound % 10) == 8)
-                {
-                    if (pAd->CommonCfg.bWmmCapable)
-    					RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, TRUE);
-                    else
-						RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, FALSE);
-                }
-    		}
-        }
-
-		if (CQI_IS_DEAD(pAd->Mlme.ChannelQuality))
-			{
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - No BEACON. Dead CQI. Auto Recovery attempt #%ld\n", pAd->RalinkCounters.BadCQIAutoRecoveryCount));
-			pAd->StaCfg.CCXAdjacentAPReportFlag = TRUE;
-			pAd->StaCfg.CCXAdjacentAPLinkDownTime = pAd->StaCfg.LastBeaconRxTime;
-
-			// Lost AP, send disconnect & link down event
-			LinkDown(pAd, FALSE);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.WpaSupplicantUP)
-			{
-                union iwreq_data    wrqu;
-                //send disassociate event to wpa_supplicant
-                memset(&wrqu, 0, sizeof(wrqu));
-                wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-                wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-            {
-                union iwreq_data    wrqu;
-                memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-			// RTMPPatchMacBbpBug(pAd);
-			MlmeAutoReconnectLastSSID(pAd);
-		}
-		else if (CQI_IS_BAD(pAd->Mlme.ChannelQuality))
-		{
-			pAd->RalinkCounters.BadCQIAutoRecoveryCount ++;
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - Bad CQI. Auto Recovery attempt #%ld\n", pAd->RalinkCounters.BadCQIAutoRecoveryCount));
-			MlmeAutoReconnectLastSSID(pAd);
-		}
-
-		// Add auto seamless roaming
-		if (pAd->StaCfg.bFastRoaming)
-		{
-			SHORT	dBmToRoam = (SHORT)pAd->StaCfg.dBmToRoam;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("Rssi=%d, dBmToRoam=%d\n", RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2), (CHAR)dBmToRoam));
-
-			if (RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2) <= (CHAR)dBmToRoam)
-			{
-				MlmeCheckForFastRoaming(pAd, pAd->Mlme.Now32);
-			}
-		}
-	}
-	else if (ADHOC_ON(pAd))
-	{
-		//radar detect
-		if ((pAd->CommonCfg.Channel > 14)
-			&& (pAd->CommonCfg.bIEEE80211H == 1)
-			&& RadarChannelCheck(pAd, pAd->CommonCfg.Channel))
-		{
-			RadarDetectPeriodic(pAd);
-		}
-
-		// If all peers leave, and this STA becomes the last one in this IBSS, then change MediaState
-		// to DISCONNECTED. But still holding this IBSS (i.e. sending BEACON) so that other STAs can
-		// join later.
-		if ((pAd->StaCfg.LastBeaconRxTime + ADHOC_BEACON_LOST_TIME < pAd->Mlme.Now32) &&
-			OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-		{
-			MLME_START_REQ_STRUCT     StartReq;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - excessive BEACON lost, last STA in this IBSS, MediaState=Disconnected\n"));
-			LinkDown(pAd, FALSE);
-
-			StartParmFill(pAd, &StartReq, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-			MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_START_REQ, sizeof(MLME_START_REQ_STRUCT), &StartReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_START;
-		}
-
-		for (i = 1; i < MAX_LEN_OF_MAC_TABLE; i++)
-		{
-			MAC_TABLE_ENTRY *pEntry = &pAd->MacTab.Content[i];
-
-			if (pEntry->ValidAsCLI == FALSE)
-				continue;
-
-			if (pEntry->LastBeaconRxTime + ADHOC_BEACON_LOST_TIME < pAd->Mlme.Now32)
-				MacTableDeleteEntry(pAd, pEntry->Aid, pEntry->Addr);
-		}
-	}
-	else // no INFRA nor ADHOC connection
-	{
-
-		if (pAd->StaCfg.bScanReqIsFromWebUI &&
-            ((pAd->StaCfg.LastScanTime + 30 * OS_HZ) > pAd->Mlme.Now32))
-			goto SKIP_AUTO_SCAN_CONN;
-        else
-            pAd->StaCfg.bScanReqIsFromWebUI = FALSE;
-
-		if ((pAd->StaCfg.bAutoReconnect == TRUE)
-			&& RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP)
-			&& (MlmeValidateSSID(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen) == TRUE))
-		{
-			if ((pAd->ScanTab.BssNr==0) && (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE))
-			{
-				MLME_SCAN_REQ_STRUCT	   ScanReq;
-
-				if ((pAd->StaCfg.LastScanTime + 10 * OS_HZ) < pAd->Mlme.Now32)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("STAMlmePeriodicExec():CNTL - ScanTab.BssNr==0, start a new ACTIVE scan SSID[%s]\n", pAd->MlmeAux.AutoReconnectSsid));
-					ScanParmFill(pAd, &ScanReq, pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen, BSS_ANY, SCAN_ACTIVE);
-					MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-					pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-					// Reset Missed scan number
-					pAd->StaCfg.LastScanTime = pAd->Mlme.Now32;
-				}
-				else if (pAd->StaCfg.BssType == BSS_ADHOC)	// Quit the forever scan when in a very clean room
-					MlmeAutoReconnectLastSSID(pAd);
-			}
-			else if (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE)
-			{
-				if ((pAd->Mlme.OneSecPeriodicRound % 7) == 0)
-				{
-					MlmeAutoScan(pAd);
-					pAd->StaCfg.LastScanTime = pAd->Mlme.Now32;
-				}
-				else
-				{
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-					if (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-					{
-						if ((pAd->Mlme.OneSecPeriodicRound % 5) == 1)
-							MlmeAutoReconnectLastSSID(pAd);
-					}
-					else
-#endif // CARRIER_DETECTION_SUPPORT //
-						MlmeAutoReconnectLastSSID(pAd);
-				}
-			}
-		}
-	}
-
-SKIP_AUTO_SCAN_CONN:
-
-#ifdef DOT11_N_SUPPORT
-    if ((pAd->MacTab.Content[BSSID_WCID].TXBAbitmap !=0) && (pAd->MacTab.fAnyBASession == FALSE))
-	{
-		pAd->MacTab.fAnyBASession = TRUE;
-		AsicUpdateProtect(pAd, HT_FORCERTSCTS,  ALLN_SETPROTECT, FALSE, FALSE);
-	}
-	else if ((pAd->MacTab.Content[BSSID_WCID].TXBAbitmap ==0) && (pAd->MacTab.fAnyBASession == TRUE))
-	{
-		pAd->MacTab.fAnyBASession = FALSE;
-		AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode,  ALLN_SETPROTECT, FALSE, FALSE);
-	}
-#endif // DOT11_N_SUPPORT //
-
-
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SCAN_2040))
-		TriEventCounterMaintenance(pAd);
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-	return;
-}
-
-// Link down report
-VOID LinkDownExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	pAd->IndicateMediaState = NdisMediaStateDisconnected;
-	RTMP_IndicateMediaState(pAd);
-    pAd->ExtraInfo = GENERAL_LINK_DOWN;
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID MlmeAutoScan(
-	IN PRTMP_ADAPTER pAd)
-{
-	// check CntlMachine.CurrState to avoid collision with NDIS SetOID request
-	if (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - Driver auto scan\n"));
-		MlmeEnqueue(pAd,
-					MLME_CNTL_STATE_MACHINE,
-					OID_802_11_BSSID_LIST_SCAN,
-					0,
-					NULL);
-		RT28XX_MLME_HANDLER(pAd);
-	}
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID MlmeAutoReconnectLastSSID(
-	IN PRTMP_ADAPTER pAd)
-{
-
-
-	// check CntlMachine.CurrState to avoid collision with NDIS SetOID request
-	if ((pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE) &&
-		(MlmeValidateSSID(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen) == TRUE))
-	{
-		NDIS_802_11_SSID OidSsid;
-		OidSsid.SsidLength = pAd->MlmeAux.AutoReconnectSsidLen;
-		NdisMoveMemory(OidSsid.Ssid, pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Driver auto reconnect to last OID_802_11_SSID setting - %s, len - %d\n", pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen));
-		MlmeEnqueue(pAd,
-					MLME_CNTL_STATE_MACHINE,
-					OID_802_11_SSID,
-					sizeof(NDIS_802_11_SSID),
-					&OidSsid);
-		RT28XX_MLME_HANDLER(pAd);
-	}
-}
-#endif // CONFIG_STA_SUPPORT //
-
-/*
-	==========================================================================
-	Validate SSID for connection try and rescan purpose
-	Valid SSID will have visible chars only.
-	The valid length is from 0 to 32.
-	IRQL = DISPATCH_LEVEL
-	==========================================================================
- */
-BOOLEAN MlmeValidateSSID(
-	IN PUCHAR	pSsid,
-	IN UCHAR	SsidLen)
-{
-	int	index;
-
-	if (SsidLen > MAX_LEN_OF_SSID)
-		return (FALSE);
-
-	// Check each character value
-	for (index = 0; index < SsidLen; index++)
-	{
-		if (pSsid[index] < 0x20)
-			return (FALSE);
-	}
-
-	// All checked
-	return (TRUE);
-}
-
-VOID MlmeSelectTxRateTable(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PUCHAR				*ppTable,
-	IN PUCHAR				pTableSize,
-	IN PUCHAR				pInitTxRateIdx)
-{
-	do
-	{
-		// decide the rate table for tuning
-		if (pAd->CommonCfg.TxRateTableSize > 0)
-		{
-			*ppTable = RateSwitchTable;
-			*pTableSize = RateSwitchTable[0];
-			*pInitTxRateIdx = RateSwitchTable[1];
-
-			break;
-		}
-
-#ifdef CONFIG_STA_SUPPORT
-		if ((pAd->OpMode == OPMODE_STA) && ADHOC_ON(pAd))
-		{
-#ifdef DOT11_N_SUPPORT
-			if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED) &&
-				(pEntry->HTCapability.MCSSet[0] == 0xff) &&
-				((pEntry->HTCapability.MCSSet[1] == 0x00) || (pAd->Antenna.field.TxPath == 1)))
-			{// 11N 1S Adhoc
-				*ppTable = RateSwitchTable11N1S;
-				*pTableSize = RateSwitchTable11N1S[0];
-				*pInitTxRateIdx = RateSwitchTable11N1S[1];
-
-			}
-			else if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED) &&
-					(pEntry->HTCapability.MCSSet[0] == 0xff) &&
-					(pEntry->HTCapability.MCSSet[1] == 0xff) &&
-					(pAd->Antenna.field.TxPath == 2))
-			{// 11N 2S Adhoc
-				if (pAd->LatchRfRegs.Channel <= 14)
-				{
-					*ppTable = RateSwitchTable11N2S;
-					*pTableSize = RateSwitchTable11N2S[0];
-					*pInitTxRateIdx = RateSwitchTable11N2S[1];
-				}
-				else
-				{
-					*ppTable = RateSwitchTable11N2SForABand;
-					*pTableSize = RateSwitchTable11N2SForABand[0];
-					*pInitTxRateIdx = RateSwitchTable11N2SForABand[1];
-				}
-
-			}
-			else
-#endif // DOT11_N_SUPPORT //
-				if ((pEntry->RateLen == 4)
-#ifdef DOT11_N_SUPPORT
-					&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
-#endif // DOT11_N_SUPPORT //
-					)
-			{
-				*ppTable = RateSwitchTable11B;
-				*pTableSize = RateSwitchTable11B[0];
-				*pInitTxRateIdx = RateSwitchTable11B[1];
-
-			}
-			else if (pAd->LatchRfRegs.Channel <= 14)
-			{
-				*ppTable = RateSwitchTable11BG;
-				*pTableSize = RateSwitchTable11BG[0];
-				*pInitTxRateIdx = RateSwitchTable11BG[1];
-
-			}
-			else
-			{
-				*ppTable = RateSwitchTable11G;
-				*pTableSize = RateSwitchTable11G[0];
-				*pInitTxRateIdx = RateSwitchTable11G[1];
-
-			}
-			break;
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-		//if ((pAd->StaActive.SupRateLen + pAd->StaActive.ExtRateLen == 12) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0xff) &&
-		//	((pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0x00) || (pAd->Antenna.field.TxPath == 1)))
-		if ((pEntry->RateLen == 12) && (pEntry->HTCapability.MCSSet[0] == 0xff) &&
-			((pEntry->HTCapability.MCSSet[1] == 0x00) || (pAd->CommonCfg.TxStream == 1)))
-		{// 11BGN 1S AP
-			*ppTable = RateSwitchTable11BGN1S;
-			*pTableSize = RateSwitchTable11BGN1S[0];
-			*pInitTxRateIdx = RateSwitchTable11BGN1S[1];
-
-			break;
-		}
-
-		//else if ((pAd->StaActive.SupRateLen + pAd->StaActive.ExtRateLen == 12) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0xff) &&
-		//	(pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0xff) && (pAd->Antenna.field.TxPath == 2))
-		if ((pEntry->RateLen == 12) && (pEntry->HTCapability.MCSSet[0] == 0xff) &&
-			(pEntry->HTCapability.MCSSet[1] == 0xff) && (pAd->CommonCfg.TxStream == 2))
-		{// 11BGN 2S AP
-			if (pAd->LatchRfRegs.Channel <= 14)
-			{
-				*ppTable = RateSwitchTable11BGN2S;
-				*pTableSize = RateSwitchTable11BGN2S[0];
-				*pInitTxRateIdx = RateSwitchTable11BGN2S[1];
-
-			}
-			else
-			{
-				*ppTable = RateSwitchTable11BGN2SForABand;
-				*pTableSize = RateSwitchTable11BGN2SForABand[0];
-				*pInitTxRateIdx = RateSwitchTable11BGN2SForABand[1];
-
-			}
-			break;
-		}
-
-		//else if ((pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0xff) && ((pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0x00) || (pAd->Antenna.field.TxPath == 1)))
-		if ((pEntry->HTCapability.MCSSet[0] == 0xff) && ((pEntry->HTCapability.MCSSet[1] == 0x00) || (pAd->CommonCfg.TxStream == 1)))
-		{// 11N 1S AP
-			*ppTable = RateSwitchTable11N1S;
-			*pTableSize = RateSwitchTable11N1S[0];
-			*pInitTxRateIdx = RateSwitchTable11N1S[1];
-
-			break;
-		}
-
-		//else if ((pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0xff) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0xff) && (pAd->Antenna.field.TxPath == 2))
-		if ((pEntry->HTCapability.MCSSet[0] == 0xff) && (pEntry->HTCapability.MCSSet[1] == 0xff) && (pAd->CommonCfg.TxStream == 2))
-		{// 11N 2S AP
-			if (pAd->LatchRfRegs.Channel <= 14)
-			{
-			*ppTable = RateSwitchTable11N2S;
-			*pTableSize = RateSwitchTable11N2S[0];
-			*pInitTxRateIdx = RateSwitchTable11N2S[1];
-            }
-			else
-			{
-				*ppTable = RateSwitchTable11N2SForABand;
-				*pTableSize = RateSwitchTable11N2SForABand[0];
-				*pInitTxRateIdx = RateSwitchTable11N2SForABand[1];
-			}
-
-			break;
-		}
-#endif // DOT11_N_SUPPORT //
-		//else if ((pAd->StaActive.SupRateLen == 4) && (pAd->StaActive.ExtRateLen == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
-		if ((pEntry->RateLen == 4)
-#ifdef DOT11_N_SUPPORT
-			&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
-#endif // DOT11_N_SUPPORT //
-			)
-		{// B only AP
-			*ppTable = RateSwitchTable11B;
-			*pTableSize = RateSwitchTable11B[0];
-			*pInitTxRateIdx = RateSwitchTable11B[1];
-
-			break;
-		}
-
-		//else if ((pAd->StaActive.SupRateLen + pAd->StaActive.ExtRateLen > 8) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
-		if ((pEntry->RateLen > 8)
-#ifdef DOT11_N_SUPPORT
-			&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
-#endif // DOT11_N_SUPPORT //
-			)
-		{// B/G  mixed AP
-			*ppTable = RateSwitchTable11BG;
-			*pTableSize = RateSwitchTable11BG[0];
-			*pInitTxRateIdx = RateSwitchTable11BG[1];
-
-			break;
-		}
-
-		//else if ((pAd->StaActive.SupRateLen + pAd->StaActive.ExtRateLen == 8) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
-		if ((pEntry->RateLen == 8)
-#ifdef DOT11_N_SUPPORT
-			&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
-#endif // DOT11_N_SUPPORT //
-			)
-		{// G only AP
-			*ppTable = RateSwitchTable11G;
-			*pTableSize = RateSwitchTable11G[0];
-			*pInitTxRateIdx = RateSwitchTable11G[1];
-
-			break;
-		}
-#ifdef DOT11_N_SUPPORT
-#endif // DOT11_N_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-#ifdef DOT11_N_SUPPORT
-			//else if ((pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
-			if ((pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0))
-#endif // DOT11_N_SUPPORT //
-			{	// Legacy mode
-				if (pAd->CommonCfg.MaxTxRate <= RATE_11)
-				{
-					*ppTable = RateSwitchTable11B;
-					*pTableSize = RateSwitchTable11B[0];
-					*pInitTxRateIdx = RateSwitchTable11B[1];
-				}
-				else if ((pAd->CommonCfg.MaxTxRate > RATE_11) && (pAd->CommonCfg.MinTxRate > RATE_11))
-				{
-					*ppTable = RateSwitchTable11G;
-					*pTableSize = RateSwitchTable11G[0];
-					*pInitTxRateIdx = RateSwitchTable11G[1];
-
-				}
-				else
-				{
-					*ppTable = RateSwitchTable11BG;
-					*pTableSize = RateSwitchTable11BG[0];
-					*pInitTxRateIdx = RateSwitchTable11BG[1];
-				}
-				break;
-			}
-#ifdef DOT11_N_SUPPORT
-			if (pAd->LatchRfRegs.Channel <= 14)
-			{
-				if (pAd->CommonCfg.TxStream == 1)
-				{
-					*ppTable = RateSwitchTable11N1S;
-					*pTableSize = RateSwitchTable11N1S[0];
-					*pInitTxRateIdx = RateSwitchTable11N1S[1];
-					DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode,default use 11N 1S AP \n"));
-				}
-				else
-				{
-					*ppTable = RateSwitchTable11N2S;
-					*pTableSize = RateSwitchTable11N2S[0];
-					*pInitTxRateIdx = RateSwitchTable11N2S[1];
-					DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode,default use 11N 2S AP \n"));
-				}
-			}
-			else
-			{
-				if (pAd->CommonCfg.TxStream == 1)
-				{
-					*ppTable = RateSwitchTable11N1S;
-					*pTableSize = RateSwitchTable11N1S[0];
-					*pInitTxRateIdx = RateSwitchTable11N1S[1];
-					DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode,default use 11N 1S AP \n"));
-				}
-				else
-				{
-					*ppTable = RateSwitchTable11N2SForABand;
-					*pTableSize = RateSwitchTable11N2SForABand[0];
-					*pInitTxRateIdx = RateSwitchTable11N2SForABand[1];
-					DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode,default use 11N 2S AP \n"));
-				}
-			}
-#endif // DOT11_N_SUPPORT //
-			DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode (SupRateLen=%d, ExtRateLen=%d, MCSSet[0]=0x%x, MCSSet[1]=0x%x)\n",
-				pAd->StaActive.SupRateLen, pAd->StaActive.ExtRateLen, pAd->StaActive.SupportedPhyInfo.MCSSet[0], pAd->StaActive.SupportedPhyInfo.MCSSet[1]));
-		}
-#endif // CONFIG_STA_SUPPORT //
-	} while(FALSE);
-}
-
-#ifdef CONFIG_STA_SUPPORT
-/*
-	==========================================================================
-	Description:
-		This routine checks if there're other APs out there capable for
-		roaming. Caller should call this routine only when Link up in INFRA mode
-		and channel quality is below CQI_GOOD_THRESHOLD.
-
-	IRQL = DISPATCH_LEVEL
-
-	Output:
-	==========================================================================
- */
-VOID MlmeCheckForRoaming(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG	Now32)
-{
-	USHORT	   i;
-	BSS_TABLE  *pRoamTab = &pAd->MlmeAux.RoamTab;
-	BSS_ENTRY  *pBss;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==> MlmeCheckForRoaming\n"));
-	// put all roaming candidates into RoamTab, and sort in RSSI order
-	BssTableInit(pRoamTab);
-	for (i = 0; i < pAd->ScanTab.BssNr; i++)
-	{
-		pBss = &pAd->ScanTab.BssEntry[i];
-
-		if ((pBss->LastBeaconRxTime + BEACON_LOST_TIME) < Now32)
-			continue;	 // AP disappear
-		if (pBss->Rssi <= RSSI_THRESHOLD_FOR_ROAMING)
-			continue;	 // RSSI too weak. forget it.
-		if (MAC_ADDR_EQUAL(pBss->Bssid, pAd->CommonCfg.Bssid))
-			continue;	 // skip current AP
-		if (pBss->Rssi < (pAd->StaCfg.RssiSample.LastRssi0 + RSSI_DELTA))
-			continue;	 // only AP with stronger RSSI is eligible for roaming
-
-		// AP passing all above rules is put into roaming candidate table
-		NdisMoveMemory(&pRoamTab->BssEntry[pRoamTab->BssNr], pBss, sizeof(BSS_ENTRY));
-		pRoamTab->BssNr += 1;
-	}
-
-	if (pRoamTab->BssNr > 0)
-	{
-		// check CntlMachine.CurrState to avoid collision with NDIS SetOID request
-		if (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE)
-		{
-			pAd->RalinkCounters.PoorCQIRoamingCount ++;
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - Roaming attempt #%ld\n", pAd->RalinkCounters.PoorCQIRoamingCount));
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_MLME_ROAMING_REQ, 0, NULL);
-			RT28XX_MLME_HANDLER(pAd);
-		}
-	}
-	DBGPRINT(RT_DEBUG_TRACE, ("<== MlmeCheckForRoaming(# of candidate= %d)\n",pRoamTab->BssNr));
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine checks if there're other APs out there capable for
-		roaming. Caller should call this routine only when link up in INFRA mode
-		and channel quality is below CQI_GOOD_THRESHOLD.
-
-	IRQL = DISPATCH_LEVEL
-
-	Output:
-	==========================================================================
- */
-VOID MlmeCheckForFastRoaming(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	ULONG			Now)
-{
-	USHORT		i;
-	BSS_TABLE	*pRoamTab = &pAd->MlmeAux.RoamTab;
-	BSS_ENTRY	*pBss;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==> MlmeCheckForFastRoaming\n"));
-	// put all roaming candidates into RoamTab, and sort in RSSI order
-	BssTableInit(pRoamTab);
-	for (i = 0; i < pAd->ScanTab.BssNr; i++)
-	{
-		pBss = &pAd->ScanTab.BssEntry[i];
-
-        if ((pBss->Rssi <= -50) && (pBss->Channel == pAd->CommonCfg.Channel))
-			continue;	 // RSSI too weak. forget it.
-		if (MAC_ADDR_EQUAL(pBss->Bssid, pAd->CommonCfg.Bssid))
-			continue;	 // skip current AP
-		if (!SSID_EQUAL(pBss->Ssid, pBss->SsidLen, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen))
-			continue;	 // skip different SSID
-        if (pBss->Rssi < (RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2) + RSSI_DELTA))
-			continue;	 // skip AP without better RSSI
-
-        DBGPRINT(RT_DEBUG_TRACE, ("LastRssi0 = %d, pBss->Rssi = %d\n", RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2), pBss->Rssi));
-		// AP passing all above rules is put into roaming candidate table
-		NdisMoveMemory(&pRoamTab->BssEntry[pRoamTab->BssNr], pBss, sizeof(BSS_ENTRY));
-		pRoamTab->BssNr += 1;
-	}
-
-	if (pRoamTab->BssNr > 0)
-	{
-		// check CntlMachine.CurrState to avoid collision with NDIS SetOID request
-		if (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE)
-		{
-			pAd->RalinkCounters.PoorCQIRoamingCount ++;
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - Roaming attempt #%ld\n", pAd->RalinkCounters.PoorCQIRoamingCount));
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_MLME_ROAMING_REQ, 0, NULL);
-			RT28XX_MLME_HANDLER(pAd);
-		}
-	}
-	// Maybe site survey required
-	else
-	{
-		if ((pAd->StaCfg.LastScanTime + 10 * 1000) < Now)
-		{
-			// check CntlMachine.CurrState to avoid collision with NDIS SetOID request
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - Roaming, No eligable entry, try new scan!\n"));
-			pAd->StaCfg.ScanCnt = 2;
-			pAd->StaCfg.LastScanTime = Now;
-			MlmeAutoScan(pAd);
-		}
-	}
-
-    DBGPRINT(RT_DEBUG_TRACE, ("<== MlmeCheckForFastRoaming (BssNr=%d)\n", pRoamTab->BssNr));
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine calculates TxPER, RxPER of the past N-sec period. And
-		according to the calculation result, ChannelQuality is calculated here
-		to decide if current AP is still doing the job.
-
-		If ChannelQuality is not good, a ROAMing attempt may be tried later.
-	Output:
-		StaCfg.ChannelQuality - 0..100
-
-	IRQL = DISPATCH_LEVEL
-
-	NOTE: This routine decide channle quality based on RX CRC error ratio.
-		Caller should make sure a function call to NICUpdateRawCounters(pAd)
-		is performed right before this routine, so that this routine can decide
-		channel quality based on the most up-to-date information
-	==========================================================================
- */
-VOID MlmeCalculateChannelQuality(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG Now32)
-{
-	ULONG TxOkCnt, TxCnt, TxPER, TxPRR;
-	ULONG RxCnt, RxPER;
-	UCHAR NorRssi;
-	CHAR  MaxRssi;
-	ULONG BeaconLostTime = BEACON_LOST_TIME;
-
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-	// longer beacon lost time when carrier detection enabled
-	if (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-	{
-		BeaconLostTime = BEACON_LOST_TIME + BEACON_LOST_TIME/2;
-	}
-#endif // CARRIER_DETECTION_SUPPORT //
-
-	MaxRssi = RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2);
-
-	//
-	// calculate TX packet error ratio and TX retry ratio - if too few TX samples, skip TX related statistics
-	//
-	TxOkCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount + pAd->RalinkCounters.OneSecTxRetryOkCount;
-	TxCnt = TxOkCnt + pAd->RalinkCounters.OneSecTxFailCount;
-	if (TxCnt < 5)
-	{
-		TxPER = 0;
-		TxPRR = 0;
-	}
-	else
-	{
-		TxPER = (pAd->RalinkCounters.OneSecTxFailCount * 100) / TxCnt;
-		TxPRR = ((TxCnt - pAd->RalinkCounters.OneSecTxNoRetryOkCount) * 100) / TxCnt;
-	}
-
-	//
-	// calculate RX PER - don't take RxPER into consideration if too few sample
-	//
-	RxCnt = pAd->RalinkCounters.OneSecRxOkCnt + pAd->RalinkCounters.OneSecRxFcsErrCnt;
-	if (RxCnt < 5)
-		RxPER = 0;
-	else
-		RxPER = (pAd->RalinkCounters.OneSecRxFcsErrCnt * 100) / RxCnt;
-
-	//
-	// decide ChannelQuality based on: 1)last BEACON received time, 2)last RSSI, 3)TxPER, and 4)RxPER
-	//
-	if (INFRA_ON(pAd) &&
-		(pAd->RalinkCounters.OneSecTxNoRetryOkCount < 2) && // no heavy traffic
-		(pAd->StaCfg.LastBeaconRxTime + BeaconLostTime < Now32))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("BEACON lost > %ld msec with TxOkCnt=%ld -> CQI=0\n", BeaconLostTime, TxOkCnt));
-		pAd->Mlme.ChannelQuality = 0;
-	}
-	else
-	{
-		// Normalize Rssi
-		if (MaxRssi > -40)
-			NorRssi = 100;
-		else if (MaxRssi < -90)
-			NorRssi = 0;
-		else
-			NorRssi = (MaxRssi + 90) * 2;
-
-		// ChannelQuality = W1*RSSI + W2*TxPRR + W3*RxPER	 (RSSI 0..100), (TxPER 100..0), (RxPER 100..0)
-		pAd->Mlme.ChannelQuality = (RSSI_WEIGHTING * NorRssi +
-								   TX_WEIGHTING * (100 - TxPRR) +
-								   RX_WEIGHTING* (100 - RxPER)) / 100;
-		if (pAd->Mlme.ChannelQuality >= 100)
-			pAd->Mlme.ChannelQuality = 100;
-	}
-
-}
-
-VOID MlmeSetTxRate(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PRTMP_TX_RATE_SWITCH	pTxRate)
-{
-	UCHAR	MaxMode = MODE_OFDM;
-
-#ifdef DOT11_N_SUPPORT
-	MaxMode = MODE_HTGREENFIELD;
-
-	if (pTxRate->STBC && (pAd->StaCfg.MaxHTPhyMode.field.STBC) && (pAd->Antenna.field.TxPath == 2))
-		pAd->StaCfg.HTPhyMode.field.STBC = STBC_USE;
-	else
-#endif // DOT11_N_SUPPORT //
-		pAd->StaCfg.HTPhyMode.field.STBC = STBC_NONE;
-
-	if (pTxRate->CurrMCS < MCS_AUTO)
-		pAd->StaCfg.HTPhyMode.field.MCS = pTxRate->CurrMCS;
-
-	if (pAd->StaCfg.HTPhyMode.field.MCS > 7)
-		pAd->StaCfg.HTPhyMode.field.STBC = STBC_NONE;
-
-   	if (ADHOC_ON(pAd))
-	{
-		// If peer adhoc is b-only mode, we can't send 11g rate.
-		pAd->StaCfg.HTPhyMode.field.ShortGI = GI_800;
-		pEntry->HTPhyMode.field.STBC	= STBC_NONE;
-
-		//
-		// For Adhoc MODE_CCK, driver will use AdhocBOnlyJoined flag to roll back to B only if necessary
-		//
-		pEntry->HTPhyMode.field.MODE	= pTxRate->Mode;
-		pEntry->HTPhyMode.field.ShortGI	= pAd->StaCfg.HTPhyMode.field.ShortGI;
-		pEntry->HTPhyMode.field.MCS		= pAd->StaCfg.HTPhyMode.field.MCS;
-
-		// Patch speed error in status page
-		pAd->StaCfg.HTPhyMode.field.MODE = pEntry->HTPhyMode.field.MODE;
-	}
-	else
-	{
-		if (pTxRate->Mode <= MaxMode)
-			pAd->StaCfg.HTPhyMode.field.MODE = pTxRate->Mode;
-
-#ifdef DOT11_N_SUPPORT
-		if (pTxRate->ShortGI && (pAd->StaCfg.MaxHTPhyMode.field.ShortGI))
-			pAd->StaCfg.HTPhyMode.field.ShortGI = GI_400;
-		else
-#endif // DOT11_N_SUPPORT //
-			pAd->StaCfg.HTPhyMode.field.ShortGI = GI_800;
-
-#ifdef DOT11_N_SUPPORT
-		// Reexam each bandwidth's SGI support.
-		if (pAd->StaCfg.HTPhyMode.field.ShortGI == GI_400)
-		{
-			if ((pEntry->HTPhyMode.field.BW == BW_20) && (!CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE)))
-				pAd->StaCfg.HTPhyMode.field.ShortGI = GI_800;
-			if ((pEntry->HTPhyMode.field.BW == BW_40) && (!CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE)))
-				pAd->StaCfg.HTPhyMode.field.ShortGI = GI_800;
-		}
-
-		// Turn RTS/CTS rate to 6Mbps.
-		if ((pEntry->HTPhyMode.field.MCS == 0) && (pAd->StaCfg.HTPhyMode.field.MCS != 0))
-		{
-			pEntry->HTPhyMode.field.MCS		= pAd->StaCfg.HTPhyMode.field.MCS;
-			if (pAd->MacTab.fAnyBASession)
-			{
-				AsicUpdateProtect(pAd, HT_FORCERTSCTS, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-			}
-			else
-			{
-				AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-			}
-		}
-		else if ((pEntry->HTPhyMode.field.MCS == 8) && (pAd->StaCfg.HTPhyMode.field.MCS != 8))
-		{
-			pEntry->HTPhyMode.field.MCS		= pAd->StaCfg.HTPhyMode.field.MCS;
-			if (pAd->MacTab.fAnyBASession)
-			{
-				AsicUpdateProtect(pAd, HT_FORCERTSCTS, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-			}
-			else
-			{
-				AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-			}
-		}
-		else if ((pEntry->HTPhyMode.field.MCS != 0) && (pAd->StaCfg.HTPhyMode.field.MCS == 0))
-		{
-			AsicUpdateProtect(pAd, HT_RTSCTS_6M, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-
-		}
-		else if ((pEntry->HTPhyMode.field.MCS != 8) && (pAd->StaCfg.HTPhyMode.field.MCS == 8))
-		{
-			AsicUpdateProtect(pAd, HT_RTSCTS_6M, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-		}
-#endif // DOT11_N_SUPPORT //
-
-		pEntry->HTPhyMode.field.STBC	= pAd->StaCfg.HTPhyMode.field.STBC;
-		pEntry->HTPhyMode.field.ShortGI	= pAd->StaCfg.HTPhyMode.field.ShortGI;
-		pEntry->HTPhyMode.field.MCS		= pAd->StaCfg.HTPhyMode.field.MCS;
-		pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-#ifdef DOT11_N_SUPPORT
-		if ((pAd->StaCfg.MaxHTPhyMode.field.MODE == MODE_HTGREENFIELD) &&
-		    pAd->WIFItestbed.bGreenField)
-		    pEntry->HTPhyMode.field.MODE = MODE_HTGREENFIELD;
-#endif // DOT11_N_SUPPORT //
-	}
-
-	pAd->LastTxRate = (USHORT)(pEntry->HTPhyMode.word);
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine calculates the acumulated TxPER of eaxh TxRate. And
-		according to the calculation result, change CommonCfg.TxRate which
-		is the stable TX Rate we expect the Radio situation could sustained.
-
-		CommonCfg.TxRate will change dynamically within {RATE_1/RATE_6, MaxTxRate}
-	Output:
-		CommonCfg.TxRate -
-
-	IRQL = DISPATCH_LEVEL
-
-	NOTE:
-		call this routine every second
-	==========================================================================
- */
-VOID MlmeDynamicTxRateSwitching(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR					UpRateIdx = 0, DownRateIdx = 0, CurrRateIdx;
-	ULONG					i, AccuTxTotalCnt = 0, TxTotalCnt;
-	ULONG					TxErrorRatio = 0;
-	BOOLEAN					bTxRateChanged, bUpgradeQuality = FALSE;
-	PRTMP_TX_RATE_SWITCH	pCurrTxRate, pNextTxRate = NULL;
-	PUCHAR					pTable;
-	UCHAR					TableSize = 0;
-	UCHAR					InitTxRateIdx = 0, TrainUp, TrainDown;
-	CHAR					Rssi, RssiOffset = 0;
-	TX_STA_CNT1_STRUC		StaTx1;
-	TX_STA_CNT0_STRUC		TxStaCnt0;
-	ULONG					TxRetransmit = 0, TxSuccess = 0, TxFailCount = 0;
-	MAC_TABLE_ENTRY			*pEntry;
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-		return;
-	}
-#endif // RALINK_ATE //
-
-	//
-	// walk through MAC table, see if need to change AP's TX rate toward each entry
-	//
-   	for (i = 1; i < MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		pEntry = &pAd->MacTab.Content[i];
-
-		// check if this entry need to switch rate automatically
-		if (RTMPCheckEntryEnableAutoRateSwitch(pAd, pEntry) == FALSE)
-			continue;
-
-		if ((pAd->MacTab.Size == 1) || (pEntry->ValidAsDls))
-		{
-			Rssi = RTMPMaxRssi(pAd,
-							   pAd->StaCfg.RssiSample.AvgRssi0,
-							   pAd->StaCfg.RssiSample.AvgRssi1,
-							   pAd->StaCfg.RssiSample.AvgRssi2);
-
-			// Update statistic counter
-			RTMP_IO_READ32(pAd, TX_STA_CNT0, &TxStaCnt0.word);
-			RTMP_IO_READ32(pAd, TX_STA_CNT1, &StaTx1.word);
-			pAd->bUpdateBcnCntDone = TRUE;
-			TxRetransmit = StaTx1.field.TxRetransmit;
-			TxSuccess = StaTx1.field.TxSuccess;
-			TxFailCount = TxStaCnt0.field.TxFailCount;
-			TxTotalCnt = TxRetransmit + TxSuccess + TxFailCount;
-
-			pAd->RalinkCounters.OneSecTxRetryOkCount += StaTx1.field.TxRetransmit;
-			pAd->RalinkCounters.OneSecTxNoRetryOkCount += StaTx1.field.TxSuccess;
-			pAd->RalinkCounters.OneSecTxFailCount += TxStaCnt0.field.TxFailCount;
-			pAd->WlanCounters.TransmittedFragmentCount.u.LowPart += StaTx1.field.TxSuccess;
-			pAd->WlanCounters.RetryCount.u.LowPart += StaTx1.field.TxRetransmit;
-			pAd->WlanCounters.FailedCount.u.LowPart += TxStaCnt0.field.TxFailCount;
-
-			// if no traffic in the past 1-sec period, don't change TX rate,
-			// but clear all bad history. because the bad history may affect the next
-			// Chariot throughput test
-			AccuTxTotalCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount +
-						 pAd->RalinkCounters.OneSecTxRetryOkCount +
-						 pAd->RalinkCounters.OneSecTxFailCount;
-
-			if (TxTotalCnt)
-				TxErrorRatio = ((TxRetransmit + TxFailCount) * 100) / TxTotalCnt;
-		}
-		else
-		{
-			if (INFRA_ON(pAd) && (i == 1))
-				Rssi = RTMPMaxRssi(pAd,
-								   pAd->StaCfg.RssiSample.AvgRssi0,
-								   pAd->StaCfg.RssiSample.AvgRssi1,
-								   pAd->StaCfg.RssiSample.AvgRssi2);
-			else
-				Rssi = RTMPMaxRssi(pAd,
-								   pEntry->RssiSample.AvgRssi0,
-								   pEntry->RssiSample.AvgRssi1,
-								   pEntry->RssiSample.AvgRssi2);
-
-			TxTotalCnt = pEntry->OneSecTxNoRetryOkCount +
-				 pEntry->OneSecTxRetryOkCount +
-				 pEntry->OneSecTxFailCount;
-
-			if (TxTotalCnt)
-				TxErrorRatio = ((pEntry->OneSecTxRetryOkCount + pEntry->OneSecTxFailCount) * 100) / TxTotalCnt;
-		}
-
-		CurrRateIdx = pEntry->CurrTxRateIndex;
-
-		MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &InitTxRateIdx);
-
-		if (CurrRateIdx >= TableSize)
-		{
-			CurrRateIdx = TableSize - 1;
-		}
-
-		// When switch from Fixed rate -> auto rate, the REAL TX rate might be different from pAd->CommonCfg.TxRateIndex.
-		// So need to sync here.
-		pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(CurrRateIdx+1)*5];
-		if ((pEntry->HTPhyMode.field.MCS != pCurrTxRate->CurrMCS)
-			//&& (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-			)
-		{
-
-			// Need to sync Real Tx rate and our record.
-			// Then return for next DRS.
-			pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(InitTxRateIdx+1)*5];
-			pEntry->CurrTxRateIndex = InitTxRateIdx;
-			MlmeSetTxRate(pAd, pEntry, pCurrTxRate);
-
-			// reset all OneSecTx counters
-			RESET_ONE_SEC_TX_CNT(pEntry);
-			continue;
-		}
-
-		// decide the next upgrade rate and downgrade rate, if any
-		if ((CurrRateIdx > 0) && (CurrRateIdx < (TableSize - 1)))
-		{
-			UpRateIdx = CurrRateIdx + 1;
-			DownRateIdx = CurrRateIdx -1;
-		}
-		else if (CurrRateIdx == 0)
-		{
-			UpRateIdx = CurrRateIdx + 1;
-			DownRateIdx = CurrRateIdx;
-		}
-		else if (CurrRateIdx == (TableSize - 1))
-		{
-			UpRateIdx = CurrRateIdx;
-			DownRateIdx = CurrRateIdx - 1;
-		}
-
-		pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(CurrRateIdx+1)*5];
-
-#ifdef DOT11_N_SUPPORT
-		if ((Rssi > -65) && (pCurrTxRate->Mode >= MODE_HTMIX))
-		{
-			TrainUp		= (pCurrTxRate->TrainUp + (pCurrTxRate->TrainUp >> 1));
-			TrainDown	= (pCurrTxRate->TrainDown + (pCurrTxRate->TrainDown >> 1));
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			TrainUp		= pCurrTxRate->TrainUp;
-			TrainDown	= pCurrTxRate->TrainDown;
-		}
-
-		//pAd->DrsCounters.LastTimeTxRateChangeAction = pAd->DrsCounters.LastSecTxRateChangeAction;
-
-		//
-		// Keep the last time TxRateChangeAction status.
-		//
-		pEntry->LastTimeTxRateChangeAction = pEntry->LastSecTxRateChangeAction;
-
-
-
-		//
-		// CASE 1. when TX samples are fewer than 15, then decide TX rate solely on RSSI
-		//         (criteria copied from RT2500 for Netopia case)
-		//
-		if (TxTotalCnt <= 15)
-		{
-			CHAR	idx = 0;
-			UCHAR	TxRateIdx;
-			//UCHAR	MCS0 = 0, MCS1 = 0, MCS2 = 0, MCS3 = 0, MCS4 = 0, MCS7 = 0, MCS12 = 0, MCS13 = 0, MCS14 = 0, MCS15 = 0;
-			UCHAR	MCS0 = 0, MCS1 = 0, MCS2 = 0, MCS3 = 0, MCS4 = 0,  MCS5 =0, MCS6 = 0, MCS7 = 0;
-	        UCHAR	MCS12 = 0, MCS13 = 0, MCS14 = 0, MCS15 = 0;
-			UCHAR	MCS20 = 0, MCS21 = 0, MCS22 = 0, MCS23 = 0; // 3*3
-
-			// check the existence and index of each needed MCS
-			while (idx < pTable[0])
-			{
-				pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(idx+1)*5];
-
-				if (pCurrTxRate->CurrMCS == MCS_0)
-				{
-					MCS0 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_1)
-				{
-					MCS1 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_2)
-				{
-					MCS2 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_3)
-				{
-					MCS3 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_4)
-				{
-					MCS4 = idx;
-				}
-	            else if (pCurrTxRate->CurrMCS == MCS_5)
-	            {
-	                MCS5 = idx;
-	            }
-	            else if (pCurrTxRate->CurrMCS == MCS_6)
-	            {
-	                MCS6 = idx;
-	            }
-				//else if (pCurrTxRate->CurrMCS == MCS_7)
-				else if ((pCurrTxRate->CurrMCS == MCS_7) && (pCurrTxRate->ShortGI == GI_800))	// prevent the highest MCS using short GI when 1T and low throughput
-				{
-					MCS7 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_12)
-				{
-					MCS12 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_13)
-				{
-					MCS13 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_14)
-				{
-					MCS14 = idx;
-				}
-				//else if ((pCurrTxRate->CurrMCS == MCS_15)/* && (pCurrTxRate->ShortGI == GI_800)*/)	//we hope to use ShortGI as initial rate
-				else if ((pCurrTxRate->CurrMCS == MCS_15) && (pCurrTxRate->ShortGI == GI_800))	//we hope to use ShortGI as initial rate, however Atheros's chip has bugs when short GI
-				{
-					MCS15 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_20) // 3*3
-				{
-					MCS20 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_21)
-				{
-					MCS21 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_22)
-				{
-					MCS22 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_23)
-				{
-					MCS23 = idx;
-				}
-				idx ++;
-			}
-
-			if (pAd->LatchRfRegs.Channel <= 14)
-			{
-				if (pAd->NicConfig2.field.ExternalLNAForG)
-				{
-					RssiOffset = 2;
-				}
-				else
-				{
-					RssiOffset = 5;
-				}
-			}
-			else
-			{
-				if (pAd->NicConfig2.field.ExternalLNAForA)
-				{
-					RssiOffset = 5;
-				}
-				else
-				{
-					RssiOffset = 8;
-				}
-			}
-#ifdef DOT11_N_SUPPORT
-			/*if (MCS15)*/
-			if ((pTable == RateSwitchTable11BGN3S) ||
-				(pTable == RateSwitchTable11N3S) ||
-				(pTable == RateSwitchTable))
-			{// N mode with 3 stream // 3*3
-				if (MCS23 && (Rssi >= -70))
-					TxRateIdx = MCS15;
-				else if (MCS22 && (Rssi >= -72))
-					TxRateIdx = MCS14;
-        	    else if (MCS21 && (Rssi >= -76))
-					TxRateIdx = MCS13;
-				else if (MCS20 && (Rssi >= -78))
-					TxRateIdx = MCS12;
-			else if (MCS4 && (Rssi >= -82))
-				TxRateIdx = MCS4;
-			else if (MCS3 && (Rssi >= -84))
-				TxRateIdx = MCS3;
-			else if (MCS2 && (Rssi >= -86))
-				TxRateIdx = MCS2;
-			else if (MCS1 && (Rssi >= -88))
-				TxRateIdx = MCS1;
-			else
-				TxRateIdx = MCS0;
-		}
-//		else if ((pTable == RateSwitchTable11BGN2S) || (pTable == RateSwitchTable11BGN2SForABand) ||(pTable == RateSwitchTable11N2S) ||(pTable == RateSwitchTable11N2SForABand) || (pTable == RateSwitchTable))
-		else if ((pTable == RateSwitchTable11BGN2S) || (pTable == RateSwitchTable11BGN2SForABand) ||(pTable == RateSwitchTable11N2S) ||(pTable == RateSwitchTable11N2SForABand)) // 3*3
-			{// N mode with 2 stream
-				if (MCS15 && (Rssi >= (-70+RssiOffset)))
-					TxRateIdx = MCS15;
-				else if (MCS14 && (Rssi >= (-72+RssiOffset)))
-					TxRateIdx = MCS14;
-				else if (MCS13 && (Rssi >= (-76+RssiOffset)))
-					TxRateIdx = MCS13;
-				else if (MCS12 && (Rssi >= (-78+RssiOffset)))
-					TxRateIdx = MCS12;
-				else if (MCS4 && (Rssi >= (-82+RssiOffset)))
-					TxRateIdx = MCS4;
-				else if (MCS3 && (Rssi >= (-84+RssiOffset)))
-					TxRateIdx = MCS3;
-				else if (MCS2 && (Rssi >= (-86+RssiOffset)))
-					TxRateIdx = MCS2;
-				else if (MCS1 && (Rssi >= (-88+RssiOffset)))
-					TxRateIdx = MCS1;
-				else
-					TxRateIdx = MCS0;
-			}
-			else if ((pTable == RateSwitchTable11BGN1S) || (pTable == RateSwitchTable11N1S))
-			{// N mode with 1 stream
-				if (MCS7 && (Rssi > (-72+RssiOffset)))
-					TxRateIdx = MCS7;
-				else if (MCS6 && (Rssi > (-74+RssiOffset)))
-					TxRateIdx = MCS6;
-				else if (MCS5 && (Rssi > (-77+RssiOffset)))
-					TxRateIdx = MCS5;
-				else if (MCS4 && (Rssi > (-79+RssiOffset)))
-					TxRateIdx = MCS4;
-				else if (MCS3 && (Rssi > (-81+RssiOffset)))
-					TxRateIdx = MCS3;
-				else if (MCS2 && (Rssi > (-83+RssiOffset)))
-					TxRateIdx = MCS2;
-				else if (MCS1 && (Rssi > (-86+RssiOffset)))
-					TxRateIdx = MCS1;
-				else
-					TxRateIdx = MCS0;
-			}
-			else
-#endif // DOT11_N_SUPPORT //
-			{// Legacy mode
-				if (MCS7 && (Rssi > -70))
-					TxRateIdx = MCS7;
-				else if (MCS6 && (Rssi > -74))
-					TxRateIdx = MCS6;
-				else if (MCS5 && (Rssi > -78))
-					TxRateIdx = MCS5;
-				else if (MCS4 && (Rssi > -82))
-					TxRateIdx = MCS4;
-				else if (MCS4 == 0)	// for B-only mode
-					TxRateIdx = MCS3;
-				else if (MCS3 && (Rssi > -85))
-					TxRateIdx = MCS3;
-				else if (MCS2 && (Rssi > -87))
-					TxRateIdx = MCS2;
-				else if (MCS1 && (Rssi > -90))
-					TxRateIdx = MCS1;
-				else
-					TxRateIdx = MCS0;
-			}
-
-	//		if (TxRateIdx != pAd->CommonCfg.TxRateIndex)
-			{
-				pEntry->CurrTxRateIndex = TxRateIdx;
-				pNextTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(pEntry->CurrTxRateIndex+1)*5];
-				MlmeSetTxRate(pAd, pEntry, pNextTxRate);
-			}
-
-			NdisZeroMemory(pEntry->TxQuality, sizeof(USHORT) * MAX_STEP_OF_TX_RATE_SWITCH);
-			NdisZeroMemory(pEntry->PER, sizeof(UCHAR) * MAX_STEP_OF_TX_RATE_SWITCH);
-			pEntry->fLastSecAccordingRSSI = TRUE;
-			// reset all OneSecTx counters
-			RESET_ONE_SEC_TX_CNT(pEntry);
-
-			continue;
-		}
-
-		if (pEntry->fLastSecAccordingRSSI == TRUE)
-		{
-			pEntry->fLastSecAccordingRSSI = FALSE;
-			pEntry->LastSecTxRateChangeAction = 0;
-			// reset all OneSecTx counters
-			RESET_ONE_SEC_TX_CNT(pEntry);
-
-			continue;
-		}
-
-		do
-		{
-			BOOLEAN	bTrainUpDown = FALSE;
-
-			pEntry->CurrTxRateStableTime ++;
-
-			// downgrade TX quality if PER >= Rate-Down threshold
-			if (TxErrorRatio >= TrainDown)
-			{
-				bTrainUpDown = TRUE;
-				pEntry->TxQuality[CurrRateIdx] = DRS_TX_QUALITY_WORST_BOUND;
-			}
-			// upgrade TX quality if PER <= Rate-Up threshold
-			else if (TxErrorRatio <= TrainUp)
-			{
-				bTrainUpDown = TRUE;
-				bUpgradeQuality = TRUE;
-				if (pEntry->TxQuality[CurrRateIdx])
-					pEntry->TxQuality[CurrRateIdx] --;  // quality very good in CurrRate
-
-				if (pEntry->TxRateUpPenalty)
-					pEntry->TxRateUpPenalty --;
-				else if (pEntry->TxQuality[UpRateIdx])
-					pEntry->TxQuality[UpRateIdx] --;    // may improve next UP rate's quality
-			}
-
-			pEntry->PER[CurrRateIdx] = (UCHAR)TxErrorRatio;
-
-			if (bTrainUpDown)
-			{
-				// perform DRS - consider TxRate Down first, then rate up.
-				if ((CurrRateIdx != DownRateIdx) && (pEntry->TxQuality[CurrRateIdx] >= DRS_TX_QUALITY_WORST_BOUND))
-				{
-					pEntry->CurrTxRateIndex = DownRateIdx;
-				}
-				else if ((CurrRateIdx != UpRateIdx) && (pEntry->TxQuality[UpRateIdx] <= 0))
-				{
-					pEntry->CurrTxRateIndex = UpRateIdx;
-				}
-			}
-		} while (FALSE);
-
-		// if rate-up happen, clear all bad history of all TX rates
-		if (pEntry->CurrTxRateIndex > CurrRateIdx)
-		{
-			pEntry->CurrTxRateStableTime = 0;
-			pEntry->TxRateUpPenalty = 0;
-			pEntry->LastSecTxRateChangeAction = 1; // rate UP
-			NdisZeroMemory(pEntry->TxQuality, sizeof(USHORT) * MAX_STEP_OF_TX_RATE_SWITCH);
-			NdisZeroMemory(pEntry->PER, sizeof(UCHAR) * MAX_STEP_OF_TX_RATE_SWITCH);
-
-			//
-			// For TxRate fast train up
-			//
-			if (!pAd->StaCfg.StaQuickResponeForRateUpTimerRunning)
-			{
-				RTMPSetTimer(&pAd->StaCfg.StaQuickResponeForRateUpTimer, 100);
-
-				pAd->StaCfg.StaQuickResponeForRateUpTimerRunning = TRUE;
-			}
-			bTxRateChanged = TRUE;
-		}
-		// if rate-down happen, only clear DownRate's bad history
-		else if (pEntry->CurrTxRateIndex < CurrRateIdx)
-		{
-			pEntry->CurrTxRateStableTime = 0;
-			pEntry->TxRateUpPenalty = 0;           // no penalty
-			pEntry->LastSecTxRateChangeAction = 2; // rate DOWN
-			pEntry->TxQuality[pEntry->CurrTxRateIndex] = 0;
-			pEntry->PER[pEntry->CurrTxRateIndex] = 0;
-
-			//
-			// For TxRate fast train down
-			//
-			if (!pAd->StaCfg.StaQuickResponeForRateUpTimerRunning)
-			{
-				RTMPSetTimer(&pAd->StaCfg.StaQuickResponeForRateUpTimer, 100);
-
-				pAd->StaCfg.StaQuickResponeForRateUpTimerRunning = TRUE;
-			}
-			bTxRateChanged = TRUE;
-		}
-		else
-		{
-			pEntry->LastSecTxRateChangeAction = 0; // rate no change
-			bTxRateChanged = FALSE;
-		}
-
-		pEntry->LastTxOkCount = TxSuccess;
-
-		// reset all OneSecTx counters
-		RESET_ONE_SEC_TX_CNT(pEntry);
-
-		pNextTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(pEntry->CurrTxRateIndex+1)*5];
-		if (bTxRateChanged && pNextTxRate)
-		{
-			MlmeSetTxRate(pAd, pEntry, pNextTxRate);
-		}
-	}
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Station side, Auto TxRate faster train up timer call back function.
-
-	Arguments:
-		SystemSpecific1			- Not used.
-		FunctionContext			- Pointer to our Adapter context.
-		SystemSpecific2			- Not used.
-		SystemSpecific3			- Not used.
-
-	Return Value:
-		None
-
-	========================================================================
-*/
-VOID StaQuickResponeForRateUpExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	PRTMP_ADAPTER			pAd = (PRTMP_ADAPTER)FunctionContext;
-	UCHAR					UpRateIdx = 0, DownRateIdx = 0, CurrRateIdx = 0;
-	ULONG					TxTotalCnt;
-	ULONG					TxErrorRatio = 0;
-	BOOLEAN					bTxRateChanged; //, bUpgradeQuality = FALSE;
-	PRTMP_TX_RATE_SWITCH	pCurrTxRate, pNextTxRate = NULL;
-	PUCHAR					pTable;
-	UCHAR					TableSize = 0;
-	UCHAR					InitTxRateIdx = 0, TrainUp, TrainDown;
-	TX_STA_CNT1_STRUC		StaTx1;
-	TX_STA_CNT0_STRUC		TxStaCnt0;
-	CHAR					Rssi, ratio;
-	ULONG					TxRetransmit = 0, TxSuccess = 0, TxFailCount = 0;
-	MAC_TABLE_ENTRY			*pEntry;
-	ULONG					i;
-
-	pAd->StaCfg.StaQuickResponeForRateUpTimerRunning = FALSE;
-
-    //
-    // walk through MAC table, see if need to change AP's TX rate toward each entry
-    //
-	for (i = 1; i < MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		pEntry = &pAd->MacTab.Content[i];
-
-		// check if this entry need to switch rate automatically
-		if (RTMPCheckEntryEnableAutoRateSwitch(pAd, pEntry) == FALSE)
-			continue;
-
-		if (INFRA_ON(pAd) && (i == 1))
-			Rssi = RTMPMaxRssi(pAd,
-							   pAd->StaCfg.RssiSample.AvgRssi0,
-							   pAd->StaCfg.RssiSample.AvgRssi1,
-							   pAd->StaCfg.RssiSample.AvgRssi2);
-		else
-			Rssi = RTMPMaxRssi(pAd,
-							   pEntry->RssiSample.AvgRssi0,
-							   pEntry->RssiSample.AvgRssi1,
-							   pEntry->RssiSample.AvgRssi2);
-
-		CurrRateIdx = pAd->CommonCfg.TxRateIndex;
-
-			MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &InitTxRateIdx);
-
-		// decide the next upgrade rate and downgrade rate, if any
-		if ((CurrRateIdx > 0) && (CurrRateIdx < (TableSize - 1)))
-		{
-			UpRateIdx = CurrRateIdx + 1;
-			DownRateIdx = CurrRateIdx -1;
-		}
-		else if (CurrRateIdx == 0)
-		{
-			UpRateIdx = CurrRateIdx + 1;
-			DownRateIdx = CurrRateIdx;
-		}
-		else if (CurrRateIdx == (TableSize - 1))
-		{
-			UpRateIdx = CurrRateIdx;
-			DownRateIdx = CurrRateIdx - 1;
-		}
-
-		pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(CurrRateIdx+1)*5];
-
-#ifdef DOT11_N_SUPPORT
-		if ((Rssi > -65) && (pCurrTxRate->Mode >= MODE_HTMIX))
-		{
-			TrainUp		= (pCurrTxRate->TrainUp + (pCurrTxRate->TrainUp >> 1));
-			TrainDown	= (pCurrTxRate->TrainDown + (pCurrTxRate->TrainDown >> 1));
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			TrainUp		= pCurrTxRate->TrainUp;
-			TrainDown	= pCurrTxRate->TrainDown;
-		}
-
-		if (pAd->MacTab.Size == 1)
-		{
-			// Update statistic counter
-			RTMP_IO_READ32(pAd, TX_STA_CNT0, &TxStaCnt0.word);
-			RTMP_IO_READ32(pAd, TX_STA_CNT1, &StaTx1.word);
-
-			TxRetransmit = StaTx1.field.TxRetransmit;
-			TxSuccess = StaTx1.field.TxSuccess;
-			TxFailCount = TxStaCnt0.field.TxFailCount;
-			TxTotalCnt = TxRetransmit + TxSuccess + TxFailCount;
-
-			pAd->RalinkCounters.OneSecTxRetryOkCount += StaTx1.field.TxRetransmit;
-			pAd->RalinkCounters.OneSecTxNoRetryOkCount += StaTx1.field.TxSuccess;
-			pAd->RalinkCounters.OneSecTxFailCount += TxStaCnt0.field.TxFailCount;
-			pAd->WlanCounters.TransmittedFragmentCount.u.LowPart += StaTx1.field.TxSuccess;
-			pAd->WlanCounters.RetryCount.u.LowPart += StaTx1.field.TxRetransmit;
-			pAd->WlanCounters.FailedCount.u.LowPart += TxStaCnt0.field.TxFailCount;
-
-#if 0 // test by Gary.
-			// if no traffic in the past 1-sec period, don't change TX rate,
-			// but clear all bad history. because the bad history may affect the next
-			// Chariot throughput test
-			TxTotalCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount +
-						 pAd->RalinkCounters.OneSecTxRetryOkCount +
-						 pAd->RalinkCounters.OneSecTxFailCount;
-#endif
-			if (TxTotalCnt)
-				TxErrorRatio = ((TxRetransmit + TxFailCount) * 100) / TxTotalCnt;
-		}
-		else
-		{
-			TxTotalCnt = pEntry->OneSecTxNoRetryOkCount +
-				 pEntry->OneSecTxRetryOkCount +
-				 pEntry->OneSecTxFailCount;
-
-			if (TxTotalCnt)
-				TxErrorRatio = ((pEntry->OneSecTxRetryOkCount + pEntry->OneSecTxFailCount) * 100) / TxTotalCnt;
-		}
-
-
-		//
-		// CASE 1. when TX samples are fewer than 15, then decide TX rate solely on RSSI
-		//         (criteria copied from RT2500 for Netopia case)
-		//
-		if (TxTotalCnt <= 12)
-		{
-			NdisZeroMemory(pAd->DrsCounters.TxQuality, sizeof(USHORT) * MAX_STEP_OF_TX_RATE_SWITCH);
-			NdisZeroMemory(pAd->DrsCounters.PER, sizeof(UCHAR) * MAX_STEP_OF_TX_RATE_SWITCH);
-
-			if ((pAd->DrsCounters.LastSecTxRateChangeAction == 1) && (CurrRateIdx != DownRateIdx))
-			{
-				pAd->CommonCfg.TxRateIndex = DownRateIdx;
-				pAd->DrsCounters.TxQuality[CurrRateIdx] = DRS_TX_QUALITY_WORST_BOUND;
-			}
-			else if ((pAd->DrsCounters.LastSecTxRateChangeAction == 2) && (CurrRateIdx != UpRateIdx))
-			{
-				pAd->CommonCfg.TxRateIndex = UpRateIdx;
-			}
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE,("QuickDRS: TxTotalCnt <= 15, train back to original rate \n"));
-			return;
-		}
-
-		do
-		{
-			ULONG OneSecTxNoRetryOKRationCount;
-
-			if (pAd->DrsCounters.LastTimeTxRateChangeAction == 0)
-				ratio = 5;
-			else
-				ratio = 4;
-
-			// downgrade TX quality if PER >= Rate-Down threshold
-			if (TxErrorRatio >= TrainDown)
-			{
-				pAd->DrsCounters.TxQuality[CurrRateIdx] = DRS_TX_QUALITY_WORST_BOUND;
-			}
-
-			pAd->DrsCounters.PER[CurrRateIdx] = (UCHAR)TxErrorRatio;
-
-			OneSecTxNoRetryOKRationCount = (TxSuccess * ratio);
-
-			// perform DRS - consider TxRate Down first, then rate up.
-			if ((pAd->DrsCounters.LastSecTxRateChangeAction == 1) && (CurrRateIdx != DownRateIdx))
-			{
-				if ((pAd->DrsCounters.LastTxOkCount + 2) >= OneSecTxNoRetryOKRationCount)
-				{
-					pAd->CommonCfg.TxRateIndex = DownRateIdx;
-					pAd->DrsCounters.TxQuality[CurrRateIdx] = DRS_TX_QUALITY_WORST_BOUND;
-
-				}
-
-			}
-			else if ((pAd->DrsCounters.LastSecTxRateChangeAction == 2) && (CurrRateIdx != UpRateIdx))
-			{
-				if ((TxErrorRatio >= 50) || (TxErrorRatio >= TrainDown))
-				{
-
-				}
-				else if ((pAd->DrsCounters.LastTxOkCount + 2) >= OneSecTxNoRetryOKRationCount)
-				{
-					pAd->CommonCfg.TxRateIndex = UpRateIdx;
-				}
-			}
-		}while (FALSE);
-
-		// if rate-up happen, clear all bad history of all TX rates
-		if (pAd->CommonCfg.TxRateIndex > CurrRateIdx)
-		{
-			pAd->DrsCounters.TxRateUpPenalty = 0;
-			NdisZeroMemory(pAd->DrsCounters.TxQuality, sizeof(USHORT) * MAX_STEP_OF_TX_RATE_SWITCH);
-			NdisZeroMemory(pAd->DrsCounters.PER, sizeof(UCHAR) * MAX_STEP_OF_TX_RATE_SWITCH);
-			bTxRateChanged = TRUE;
-		}
-		// if rate-down happen, only clear DownRate's bad history
-		else if (pAd->CommonCfg.TxRateIndex < CurrRateIdx)
-		{
-			DBGPRINT_RAW(RT_DEBUG_TRACE,("QuickDRS: --TX rate from %d to %d \n", CurrRateIdx, pAd->CommonCfg.TxRateIndex));
-
-			pAd->DrsCounters.TxRateUpPenalty = 0;           // no penalty
-			pAd->DrsCounters.TxQuality[pAd->CommonCfg.TxRateIndex] = 0;
-			pAd->DrsCounters.PER[pAd->CommonCfg.TxRateIndex] = 0;
-			bTxRateChanged = TRUE;
-		}
-		else
-		{
-			bTxRateChanged = FALSE;
-		}
-
-		pNextTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(pAd->CommonCfg.TxRateIndex+1)*5];
-		if (bTxRateChanged && pNextTxRate)
-		{
-			MlmeSetTxRate(pAd, pEntry, pNextTxRate);
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine is executed periodically inside MlmePeriodicExec() after
-		association with an AP.
-		It checks if StaCfg.Psm is consistent with user policy (recorded in
-		StaCfg.WindowsPowerMode). If not, enforce user policy. However,
-		there're some conditions to consider:
-		1. we don't support power-saving in ADHOC mode, so Psm=PWR_ACTIVE all
-		   the time when Mibss==TRUE
-		2. When link up in INFRA mode, Psm should not be switch to PWR_SAVE
-		   if outgoing traffic available in TxRing or MgmtRing.
-	Output:
-		1. change pAd->StaCfg.Psm to PWR_SAVE or leave it untouched
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID MlmeCheckPsmChange(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG	Now32)
-{
-	ULONG	PowerMode;
-
-	// condition -
-	// 1. Psm maybe ON only happen in INFRASTRUCTURE mode
-	// 2. user wants either MAX_PSP or FAST_PSP
-	// 3. but current psm is not in PWR_SAVE
-	// 4. CNTL state machine is not doing SCANning
-	// 5. no TX SUCCESS event for the past 1-sec period
-#ifdef NDIS51_MINIPORT
-	if (pAd->StaCfg.WindowsPowerProfile == NdisPowerProfileBattery)
-		PowerMode = pAd->StaCfg.WindowsBatteryPowerMode;
-	else
-#endif
-		PowerMode = pAd->StaCfg.WindowsPowerMode;
-
-	if (INFRA_ON(pAd) &&
-		(PowerMode != Ndis802_11PowerModeCAM) &&
-		(pAd->StaCfg.Psm == PWR_ACTIVE) &&
-//		(! RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-		(pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE) /*&&
-		(pAd->RalinkCounters.OneSecTxNoRetryOkCount == 0) &&
-		(pAd->RalinkCounters.OneSecTxRetryOkCount == 0)*/)
-	{
-		NdisGetSystemUpTime(&pAd->Mlme.LastSendNULLpsmTime);
-		pAd->RalinkCounters.RxCountSinceLastNULL = 0;
-		MlmeSetPsmBit(pAd, PWR_SAVE);
-		if (!(pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable))
-		{
-			RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, FALSE);
-		}
-		else
-		{
-			RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, TRUE);
-		}
-	}
-}
-
-// IRQL = PASSIVE_LEVEL
-// IRQL = DISPATCH_LEVEL
-VOID MlmeSetPsmBit(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT psm)
-{
-	AUTO_RSP_CFG_STRUC csr4;
-
-	pAd->StaCfg.Psm = psm;
-	RTMP_IO_READ32(pAd, AUTO_RSP_CFG, &csr4.word);
-	csr4.field.AckCtsPsmBit = (psm == PWR_SAVE)? 1:0;
-	RTMP_IO_WRITE32(pAd, AUTO_RSP_CFG, csr4.word);
-	DBGPRINT(RT_DEBUG_TRACE, ("MlmeSetPsmBit = %d\n", psm));
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-// IRQL = DISPATCH_LEVEL
-VOID MlmeSetTxPreamble(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT TxPreamble)
-{
-	AUTO_RSP_CFG_STRUC csr4;
-
-	//
-	// Always use Long preamble before verifiation short preamble functionality works well.
-	// Todo: remove the following line if short preamble functionality works
-	//
-	//TxPreamble = Rt802_11PreambleLong;
-
-	RTMP_IO_READ32(pAd, AUTO_RSP_CFG, &csr4.word);
-	if (TxPreamble == Rt802_11PreambleLong)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("MlmeSetTxPreamble (= LONG PREAMBLE)\n"));
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-		csr4.field.AutoResponderPreamble = 0;
-	}
-	else
-	{
-		// NOTE: 1Mbps should always use long preamble
-		DBGPRINT(RT_DEBUG_TRACE, ("MlmeSetTxPreamble (= SHORT PREAMBLE)\n"));
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-		csr4.field.AutoResponderPreamble = 1;
-	}
-
-	RTMP_IO_WRITE32(pAd, AUTO_RSP_CFG, csr4.word);
-}
-
-/*
-    ==========================================================================
-    Description:
-        Update basic rate bitmap
-    ==========================================================================
- */
-
-VOID UpdateBasicRateBitmap(
-    IN  PRTMP_ADAPTER   pAdapter)
-{
-    INT  i, j;
-                  /* 1  2  5.5, 11,  6,  9, 12, 18, 24, 36, 48,  54 */
-    UCHAR rate[] = { 2, 4,  11, 22, 12, 18, 24, 36, 48, 72, 96, 108 };
-    UCHAR *sup_p = pAdapter->CommonCfg.SupRate;
-    UCHAR *ext_p = pAdapter->CommonCfg.ExtRate;
-    ULONG bitmap = pAdapter->CommonCfg.BasicRateBitmap;
-
-
-    /* if A mode, always use fix BasicRateBitMap */
-    //if (pAdapter->CommonCfg.Channel == PHY_11A)
-	if (pAdapter->CommonCfg.Channel > 14)
-        pAdapter->CommonCfg.BasicRateBitmap = 0x150; /* 6, 12, 24M */
-    /* End of if */
-
-    if (pAdapter->CommonCfg.BasicRateBitmap > 4095)
-    {
-        /* (2 ^ MAX_LEN_OF_SUPPORTED_RATES) -1 */
-        return;
-    } /* End of if */
-
-    for(i=0; i<MAX_LEN_OF_SUPPORTED_RATES; i++)
-    {
-        sup_p[i] &= 0x7f;
-        ext_p[i] &= 0x7f;
-    } /* End of for */
-
-    for(i=0; i<MAX_LEN_OF_SUPPORTED_RATES; i++)
-    {
-        if (bitmap & (1 << i))
-        {
-            for(j=0; j<MAX_LEN_OF_SUPPORTED_RATES; j++)
-            {
-                if (sup_p[j] == rate[i])
-                    sup_p[j] |= 0x80;
-                /* End of if */
-            } /* End of for */
-
-            for(j=0; j<MAX_LEN_OF_SUPPORTED_RATES; j++)
-            {
-                if (ext_p[j] == rate[i])
-                    ext_p[j] |= 0x80;
-                /* End of if */
-            } /* End of for */
-        } /* End of if */
-    } /* End of for */
-} /* End of UpdateBasicRateBitmap */
-
-// IRQL = PASSIVE_LEVEL
-// IRQL = DISPATCH_LEVEL
-// bLinkUp is to identify the inital link speed.
-// TRUE indicates the rate update at linkup, we should not try to set the rate at 54Mbps.
-VOID MlmeUpdateTxRates(
-	IN PRTMP_ADAPTER 		pAd,
-	IN 	BOOLEAN		 		bLinkUp,
-	IN	UCHAR				apidx)
-{
-	int i, num;
-	UCHAR Rate = RATE_6, MaxDesire = RATE_1, MaxSupport = RATE_1;
-	UCHAR MinSupport = RATE_54;
-	ULONG BasicRateBitmap = 0;
-	UCHAR CurrBasicRate = RATE_1;
-	UCHAR *pSupRate, SupRateLen, *pExtRate, ExtRateLen;
-	PHTTRANSMIT_SETTING		pHtPhy = NULL;
-	PHTTRANSMIT_SETTING		pMaxHtPhy = NULL;
-	PHTTRANSMIT_SETTING		pMinHtPhy = NULL;
-	BOOLEAN 				*auto_rate_cur_p;
-	UCHAR					HtMcs = MCS_AUTO;
-
-	// find max desired rate
-	UpdateBasicRateBitmap(pAd);
-
-	num = 0;
-	auto_rate_cur_p = NULL;
-	for (i=0; i<MAX_LEN_OF_SUPPORTED_RATES; i++)
-	{
-		switch (pAd->CommonCfg.DesireRate[i] & 0x7f)
-		{
-			case 2:  Rate = RATE_1;   num++;   break;
-			case 4:  Rate = RATE_2;   num++;   break;
-			case 11: Rate = RATE_5_5; num++;   break;
-			case 22: Rate = RATE_11;  num++;   break;
-			case 12: Rate = RATE_6;   num++;   break;
-			case 18: Rate = RATE_9;   num++;   break;
-			case 24: Rate = RATE_12;  num++;   break;
-			case 36: Rate = RATE_18;  num++;   break;
-			case 48: Rate = RATE_24;  num++;   break;
-			case 72: Rate = RATE_36;  num++;   break;
-			case 96: Rate = RATE_48;  num++;   break;
-			case 108: Rate = RATE_54; num++;   break;
-			//default: Rate = RATE_1;   break;
-		}
-		if (MaxDesire < Rate)  MaxDesire = Rate;
-	}
-
-//===========================================================================
-//===========================================================================
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		pHtPhy 		= &pAd->StaCfg.HTPhyMode;
-		pMaxHtPhy	= &pAd->StaCfg.MaxHTPhyMode;
-		pMinHtPhy	= &pAd->StaCfg.MinHTPhyMode;
-
-		auto_rate_cur_p = &pAd->StaCfg.bAutoTxRateSwitch;
-		HtMcs 		= pAd->StaCfg.DesiredTransmitSetting.field.MCS;
-
-		if ((pAd->StaCfg.BssType == BSS_ADHOC) &&
-			(pAd->CommonCfg.PhyMode == PHY_11B) &&
-			(MaxDesire > RATE_11))
-		{
-			MaxDesire = RATE_11;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	pAd->CommonCfg.MaxDesiredRate = MaxDesire;
-	pMinHtPhy->word = 0;
-	pMaxHtPhy->word = 0;
-	pHtPhy->word = 0;
-
-	// Auto rate switching is enabled only if more than one DESIRED RATES are
-	// specified; otherwise disabled
-	if (num <= 1)
-	{
-		//OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED);
-		//pAd->CommonCfg.bAutoTxRateSwitch	= FALSE;
-		*auto_rate_cur_p = FALSE;
-	}
-	else
-	{
-		//OPSTATUS_SET_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED);
-		//pAd->CommonCfg.bAutoTxRateSwitch	= TRUE;
-		*auto_rate_cur_p = TRUE;
-	}
-
-#if 1
-	if (HtMcs != MCS_AUTO)
-	{
-		//OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED);
-		//pAd->CommonCfg.bAutoTxRateSwitch	= FALSE;
-		*auto_rate_cur_p = FALSE;
-	}
-	else
-	{
-		//OPSTATUS_SET_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED);
-		//pAd->CommonCfg.bAutoTxRateSwitch	= TRUE;
-		*auto_rate_cur_p = TRUE;
-	}
-#endif
-
-#ifdef CONFIG_STA_SUPPORT
-	if ((ADHOC_ON(pAd) || INFRA_ON(pAd)) && (pAd->OpMode == OPMODE_STA))
-	{
-		pSupRate = &pAd->StaActive.SupRate[0];
-		pExtRate = &pAd->StaActive.ExtRate[0];
-		SupRateLen = pAd->StaActive.SupRateLen;
-		ExtRateLen = pAd->StaActive.ExtRateLen;
-	}
-	else
-#endif // CONFIG_STA_SUPPORT //
-	{
-		pSupRate = &pAd->CommonCfg.SupRate[0];
-		pExtRate = &pAd->CommonCfg.ExtRate[0];
-		SupRateLen = pAd->CommonCfg.SupRateLen;
-		ExtRateLen = pAd->CommonCfg.ExtRateLen;
-	}
-
-	// find max supported rate
-	for (i=0; i<SupRateLen; i++)
-	{
-		switch (pSupRate[i] & 0x7f)
-		{
-			case 2:   Rate = RATE_1;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0001;	 break;
-			case 4:   Rate = RATE_2;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0002;	 break;
-			case 11:  Rate = RATE_5_5;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0004;	 break;
-			case 22:  Rate = RATE_11;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0008;	 break;
-			case 12:  Rate = RATE_6;	/*if (pSupRate[i] & 0x80)*/  BasicRateBitmap |= 0x0010;  break;
-			case 18:  Rate = RATE_9;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0020;	 break;
-			case 24:  Rate = RATE_12;	/*if (pSupRate[i] & 0x80)*/  BasicRateBitmap |= 0x0040;  break;
-			case 36:  Rate = RATE_18;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0080;	 break;
-			case 48:  Rate = RATE_24;	/*if (pSupRate[i] & 0x80)*/  BasicRateBitmap |= 0x0100;  break;
-			case 72:  Rate = RATE_36;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0200;	 break;
-			case 96:  Rate = RATE_48;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0400;	 break;
-			case 108: Rate = RATE_54;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0800;	 break;
-			default:  Rate = RATE_1;	break;
-		}
-		if (MaxSupport < Rate)	MaxSupport = Rate;
-
-		if (MinSupport > Rate) MinSupport = Rate;
-	}
-
-	for (i=0; i<ExtRateLen; i++)
-	{
-		switch (pExtRate[i] & 0x7f)
-		{
-			case 2:   Rate = RATE_1;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0001;	 break;
-			case 4:   Rate = RATE_2;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0002;	 break;
-			case 11:  Rate = RATE_5_5;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0004;	 break;
-			case 22:  Rate = RATE_11;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0008;	 break;
-			case 12:  Rate = RATE_6;	/*if (pExtRate[i] & 0x80)*/  BasicRateBitmap |= 0x0010;  break;
-			case 18:  Rate = RATE_9;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0020;	 break;
-			case 24:  Rate = RATE_12;	/*if (pExtRate[i] & 0x80)*/  BasicRateBitmap |= 0x0040;  break;
-			case 36:  Rate = RATE_18;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0080;	 break;
-			case 48:  Rate = RATE_24;	/*if (pExtRate[i] & 0x80)*/  BasicRateBitmap |= 0x0100;  break;
-			case 72:  Rate = RATE_36;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0200;	 break;
-			case 96:  Rate = RATE_48;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0400;	 break;
-			case 108: Rate = RATE_54;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0800;	 break;
-			default:  Rate = RATE_1;	break;
-		}
-		if (MaxSupport < Rate)	MaxSupport = Rate;
-
-		if (MinSupport > Rate) MinSupport = Rate;
-	}
-
-	RTMP_IO_WRITE32(pAd, LEGACY_BASIC_RATE, BasicRateBitmap);
-
-	// bug fix
-	// pAd->CommonCfg.BasicRateBitmap = BasicRateBitmap;
-
-	// calculate the exptected ACK rate for each TX rate. This info is used to caculate
-	// the DURATION field of outgoing uniicast DATA/MGMT frame
-	for (i=0; i<MAX_LEN_OF_SUPPORTED_RATES; i++)
-	{
-		if (BasicRateBitmap & (0x01 << i))
-			CurrBasicRate = (UCHAR)i;
-		pAd->CommonCfg.ExpectedACKRate[i] = CurrBasicRate;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("MlmeUpdateTxRates[MaxSupport = %d] = MaxDesire %d Mbps\n", RateIdToMbps[MaxSupport], RateIdToMbps[MaxDesire]));
-	// max tx rate = min {max desire rate, max supported rate}
-	if (MaxSupport < MaxDesire)
-		pAd->CommonCfg.MaxTxRate = MaxSupport;
-	else
-		pAd->CommonCfg.MaxTxRate = MaxDesire;
-
-	pAd->CommonCfg.MinTxRate = MinSupport;
-	// 2003-07-31 john - 2500 doesn't have good sensitivity at high OFDM rates. to increase the success
-	// ratio of initial DHCP packet exchange, TX rate starts from a lower rate depending
-	// on average RSSI
-	//	 1. RSSI >= -70db, start at 54 Mbps (short distance)
-	//	 2. -70 > RSSI >= -75, start at 24 Mbps (mid distance)
-	//	 3. -75 > RSSI, start at 11 Mbps (long distance)
-	//if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED)/* &&
-	//	OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)*/)
-	if (*auto_rate_cur_p)
-	{
-		short dbm = 0;
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			dbm = pAd->StaCfg.RssiSample.AvgRssi0 - pAd->BbpRssiToDbmDelta;
-#endif // CONFIG_STA_SUPPORT //
-		if (bLinkUp == TRUE)
-			pAd->CommonCfg.TxRate = RATE_24;
-		else
-			pAd->CommonCfg.TxRate = pAd->CommonCfg.MaxTxRate;
-
-		if (dbm < -75)
-			pAd->CommonCfg.TxRate = RATE_11;
-		else if (dbm < -70)
-			pAd->CommonCfg.TxRate = RATE_24;
-
-		// should never exceed MaxTxRate (consider 11B-only mode)
-		if (pAd->CommonCfg.TxRate > pAd->CommonCfg.MaxTxRate)
-			pAd->CommonCfg.TxRate = pAd->CommonCfg.MaxTxRate;
-
-		pAd->CommonCfg.TxRateIndex = 0;
-	}
-	else
-	{
-		pAd->CommonCfg.TxRate = pAd->CommonCfg.MaxTxRate;
-		pHtPhy->field.MCS	= (pAd->CommonCfg.MaxTxRate > 3) ? (pAd->CommonCfg.MaxTxRate - 4) : pAd->CommonCfg.MaxTxRate;
-		pHtPhy->field.MODE	= (pAd->CommonCfg.MaxTxRate > 3) ? MODE_OFDM : MODE_CCK;
-
-		pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.STBC	= pHtPhy->field.STBC;
-		pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.ShortGI	= pHtPhy->field.ShortGI;
-		pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MCS		= pHtPhy->field.MCS;
-		pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE	= pHtPhy->field.MODE;
-	}
-
-	if (pAd->CommonCfg.TxRate <= RATE_11)
-	{
-		pMaxHtPhy->field.MODE = MODE_CCK;
-		pMaxHtPhy->field.MCS = pAd->CommonCfg.TxRate;
-		pMinHtPhy->field.MCS = pAd->CommonCfg.MinTxRate;
-	}
-	else
-	{
-		pMaxHtPhy->field.MODE = MODE_OFDM;
-		pMaxHtPhy->field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.TxRate];
-		if (pAd->CommonCfg.MinTxRate >= RATE_6 && (pAd->CommonCfg.MinTxRate <= RATE_54))
-			{pMinHtPhy->field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MinTxRate];}
-		else
-			{pMinHtPhy->field.MCS = pAd->CommonCfg.MinTxRate;}
-	}
-
-	pHtPhy->word = (pMaxHtPhy->word);
-	if (bLinkUp && (pAd->OpMode == OPMODE_STA))
-	{
-			pAd->MacTab.Content[BSSID_WCID].HTPhyMode.word = pHtPhy->word;
-			pAd->MacTab.Content[BSSID_WCID].MaxHTPhyMode.word = pMaxHtPhy->word;
-			pAd->MacTab.Content[BSSID_WCID].MinHTPhyMode.word = pMinHtPhy->word;
-	}
-	else
-	{
-		switch (pAd->CommonCfg.PhyMode)
-		{
-			case PHY_11BG_MIXED:
-			case PHY_11B:
-#ifdef DOT11_N_SUPPORT
-			case PHY_11BGN_MIXED:
-#endif // DOT11_N_SUPPORT //
-				pAd->CommonCfg.MlmeRate = RATE_1;
-				pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_CCK;
-				pAd->CommonCfg.MlmeTransmit.field.MCS = RATE_1;
-
-//#ifdef	WIFI_TEST
-				pAd->CommonCfg.RtsRate = RATE_11;
-//#else
-//				pAd->CommonCfg.RtsRate = RATE_1;
-//#endif
-				break;
-			case PHY_11G:
-			case PHY_11A:
-#ifdef DOT11_N_SUPPORT
-			case PHY_11AGN_MIXED:
-			case PHY_11GN_MIXED:
-			case PHY_11N_2_4G:
-			case PHY_11AN_MIXED:
-			case PHY_11N_5G:
-#endif // DOT11_N_SUPPORT //
-				pAd->CommonCfg.MlmeRate = RATE_6;
-				pAd->CommonCfg.RtsRate = RATE_6;
-				pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-				pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-				break;
-			case PHY_11ABG_MIXED:
-#ifdef DOT11_N_SUPPORT
-			case PHY_11ABGN_MIXED:
-#endif // DOT11_N_SUPPORT //
-				if (pAd->CommonCfg.Channel <= 14)
-				{
-					pAd->CommonCfg.MlmeRate = RATE_1;
-					pAd->CommonCfg.RtsRate = RATE_1;
-					pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_CCK;
-					pAd->CommonCfg.MlmeTransmit.field.MCS = RATE_1;
-				}
-				else
-				{
-					pAd->CommonCfg.MlmeRate = RATE_6;
-					pAd->CommonCfg.RtsRate = RATE_6;
-					pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-					pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-				}
-				break;
-			default: // error
-				pAd->CommonCfg.MlmeRate = RATE_6;
-                        	pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-				pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-				pAd->CommonCfg.RtsRate = RATE_1;
-				break;
-		}
-		//
-		// Keep Basic Mlme Rate.
-		//
-		pAd->MacTab.Content[MCAST_WCID].HTPhyMode.word = pAd->CommonCfg.MlmeTransmit.word;
-		if (pAd->CommonCfg.MlmeTransmit.field.MODE == MODE_OFDM)
-			pAd->MacTab.Content[MCAST_WCID].HTPhyMode.field.MCS = OfdmRateToRxwiMCS[RATE_24];
-		else
-			pAd->MacTab.Content[MCAST_WCID].HTPhyMode.field.MCS = RATE_1;
-		pAd->CommonCfg.BasicMlmeRate = pAd->CommonCfg.MlmeRate;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (MaxDesire=%d, MaxSupport=%d, MaxTxRate=%d, MinRate=%d, Rate Switching =%d)\n",
-			 RateIdToMbps[MaxDesire], RateIdToMbps[MaxSupport], RateIdToMbps[pAd->CommonCfg.MaxTxRate], RateIdToMbps[pAd->CommonCfg.MinTxRate],
-			 /*OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED)*/*auto_rate_cur_p));
-	DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (TxRate=%d, RtsRate=%d, BasicRateBitmap=0x%04lx)\n",
-			 RateIdToMbps[pAd->CommonCfg.TxRate], RateIdToMbps[pAd->CommonCfg.RtsRate], BasicRateBitmap));
-	DBGPRINT(RT_DEBUG_TRACE, ("MlmeUpdateTxRates (MlmeTransmit=0x%x, MinHTPhyMode=%x, MaxHTPhyMode=0x%x, HTPhyMode=0x%x)\n",
-			 pAd->CommonCfg.MlmeTransmit.word, pAd->MacTab.Content[BSSID_WCID].MinHTPhyMode.word ,pAd->MacTab.Content[BSSID_WCID].MaxHTPhyMode.word ,pAd->MacTab.Content[BSSID_WCID].HTPhyMode.word ));
-}
-
-#ifdef DOT11_N_SUPPORT
-/*
-	==========================================================================
-	Description:
-		This function update HT Rate setting.
-		Input Wcid value is valid for 2 case :
-		1. it's used for Station in infra mode that copy AP rate to Mactable.
-		2. OR Station 	in adhoc mode to copy peer's HT rate to Mactable.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID MlmeUpdateHtTxRates(
-	IN PRTMP_ADAPTER 		pAd,
-	IN	UCHAR				apidx)
-{
-	UCHAR	StbcMcs; //j, StbcMcs, bitmask;
-	CHAR 	i; // 3*3
-	RT_HT_CAPABILITY 	*pRtHtCap = NULL;
-	RT_HT_PHY_INFO		*pActiveHtPhy = NULL;
-	ULONG		BasicMCS;
-	UCHAR j, bitmask;
-	PRT_HT_PHY_INFO			pDesireHtPhy = NULL;
-	PHTTRANSMIT_SETTING		pHtPhy = NULL;
-	PHTTRANSMIT_SETTING		pMaxHtPhy = NULL;
-	PHTTRANSMIT_SETTING		pMinHtPhy = NULL;
-	BOOLEAN 				*auto_rate_cur_p;
-
-	DBGPRINT(RT_DEBUG_TRACE,("MlmeUpdateHtTxRates===> \n"));
-
-	auto_rate_cur_p = NULL;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		pDesireHtPhy	= &pAd->StaCfg.DesiredHtPhyInfo;
-		pActiveHtPhy	= &pAd->StaCfg.DesiredHtPhyInfo;
-		pHtPhy 		= &pAd->StaCfg.HTPhyMode;
-		pMaxHtPhy	= &pAd->StaCfg.MaxHTPhyMode;
-		pMinHtPhy	= &pAd->StaCfg.MinHTPhyMode;
-
-		auto_rate_cur_p = &pAd->StaCfg.bAutoTxRateSwitch;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-	if ((ADHOC_ON(pAd) || INFRA_ON(pAd)) && (pAd->OpMode == OPMODE_STA))
-	{
-		if (pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE)
-			return;
-
-		pRtHtCap = &pAd->StaActive.SupportedHtPhy;
-		pActiveHtPhy = &pAd->StaActive.SupportedPhyInfo;
-		StbcMcs = (UCHAR)pAd->MlmeAux.AddHtInfo.AddHtInfo3.StbcMcs;
-		BasicMCS =pAd->MlmeAux.AddHtInfo.MCSSet[0]+(pAd->MlmeAux.AddHtInfo.MCSSet[1]<<8)+(StbcMcs<<16);
-		if ((pAd->CommonCfg.DesiredHtPhy.TxSTBC) && (pRtHtCap->RxSTBC) && (pAd->Antenna.field.TxPath == 2))
-			pMaxHtPhy->field.STBC = STBC_USE;
-		else
-			pMaxHtPhy->field.STBC = STBC_NONE;
-	}
-	else
-#endif // CONFIG_STA_SUPPORT //
-	{
-		if (pDesireHtPhy->bHtEnable == FALSE)
-			return;
-
-		pRtHtCap = &pAd->CommonCfg.DesiredHtPhy;
-		StbcMcs = (UCHAR)pAd->CommonCfg.AddHTInfo.AddHtInfo3.StbcMcs;
-		BasicMCS = pAd->CommonCfg.AddHTInfo.MCSSet[0]+(pAd->CommonCfg.AddHTInfo.MCSSet[1]<<8)+(StbcMcs<<16);
-		if ((pAd->CommonCfg.DesiredHtPhy.TxSTBC) && (pRtHtCap->RxSTBC) && (pAd->Antenna.field.TxPath == 2))
-			pMaxHtPhy->field.STBC = STBC_USE;
-		else
-			pMaxHtPhy->field.STBC = STBC_NONE;
-	}
-
-	// Decide MAX ht rate.
-	if ((pRtHtCap->GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-		pMaxHtPhy->field.MODE = MODE_HTGREENFIELD;
-	else
-		pMaxHtPhy->field.MODE = MODE_HTMIX;
-
-    if ((pAd->CommonCfg.DesiredHtPhy.ChannelWidth) && (pRtHtCap->ChannelWidth))
-		pMaxHtPhy->field.BW = BW_40;
-	else
-		pMaxHtPhy->field.BW = BW_20;
-
-    if (pMaxHtPhy->field.BW == BW_20)
-		pMaxHtPhy->field.ShortGI = (pAd->CommonCfg.DesiredHtPhy.ShortGIfor20 & pRtHtCap->ShortGIfor20);
-	else
-		pMaxHtPhy->field.ShortGI = (pAd->CommonCfg.DesiredHtPhy.ShortGIfor40 & pRtHtCap->ShortGIfor40);
-
-	for (i=23; i>=0; i--) // 3*3
-	{
-		j = i/8;
-		bitmask = (1<<(i-(j*8)));
-
-		if ((pActiveHtPhy->MCSSet[j] & bitmask) && (pDesireHtPhy->MCSSet[j] & bitmask))
-		{
-			pMaxHtPhy->field.MCS = i;
-			break;
-		}
-
-		if (i==0)
-			break;
-	}
-
-	// Copy MIN ht rate.  rt2860???
-	pMinHtPhy->field.BW = BW_20;
-	pMinHtPhy->field.MCS = 0;
-	pMinHtPhy->field.STBC = 0;
-	pMinHtPhy->field.ShortGI = 0;
-	//If STA assigns fixed rate. update to fixed here.
-#ifdef CONFIG_STA_SUPPORT
-	if ( (pAd->OpMode == OPMODE_STA) && (pDesireHtPhy->MCSSet[0] != 0xff))
-	{
-		if (pDesireHtPhy->MCSSet[4] != 0)
-		{
-			pMaxHtPhy->field.MCS = 32;
-			pMinHtPhy->field.MCS = 32;
-			DBGPRINT(RT_DEBUG_TRACE,("MlmeUpdateHtTxRates<=== Use Fixed MCS = %d\n",pMinHtPhy->field.MCS));
-		}
-
-		for (i=23; (CHAR)i >= 0; i--) // 3*3
-		{
-			j = i/8;
-			bitmask = (1<<(i-(j*8)));
-			if ( (pDesireHtPhy->MCSSet[j] & bitmask) && (pActiveHtPhy->MCSSet[j] & bitmask))
-			{
-				pMaxHtPhy->field.MCS = i;
-				pMinHtPhy->field.MCS = i;
-				break;
-			}
-			if (i==0)
-				break;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-
-	// Decide ht rate
-	pHtPhy->field.STBC = pMaxHtPhy->field.STBC;
-	pHtPhy->field.BW = pMaxHtPhy->field.BW;
-	pHtPhy->field.MODE = pMaxHtPhy->field.MODE;
-	pHtPhy->field.MCS = pMaxHtPhy->field.MCS;
-	pHtPhy->field.ShortGI = pMaxHtPhy->field.ShortGI;
-
-	// use default now. rt2860
-	if (pDesireHtPhy->MCSSet[0] != 0xff)
-		*auto_rate_cur_p = FALSE;
-	else
-		*auto_rate_cur_p = TRUE;
-
-	DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateHtTxRates<---.AMsduSize = %d  \n", pAd->CommonCfg.DesiredHtPhy.AmsduSize ));
-	DBGPRINT(RT_DEBUG_TRACE,("TX: MCS[0] = %x (choose %d), BW = %d, ShortGI = %d, MODE = %d,  \n", pActiveHtPhy->MCSSet[0],pHtPhy->field.MCS,
-		pHtPhy->field.BW, pHtPhy->field.ShortGI, pHtPhy->field.MODE));
-	DBGPRINT(RT_DEBUG_TRACE,("MlmeUpdateHtTxRates<=== \n"));
-}
-#endif // DOT11_N_SUPPORT //
-
-// IRQL = DISPATCH_LEVEL
-VOID MlmeRadioOff(
-	IN PRTMP_ADAPTER pAd)
-{
-	RT28XX_MLME_RADIO_OFF(pAd);
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID MlmeRadioOn(
-	IN PRTMP_ADAPTER pAd)
-{
-	RT28XX_MLME_RADIO_ON(pAd);
-}
-
-// ===========================================================================================
-// bss_table.c
-// ===========================================================================================
-
-
-/*! \brief initialize BSS table
- *	\param p_tab pointer to the table
- *	\return none
- *	\pre
- *	\post
-
- IRQL = PASSIVE_LEVEL
- IRQL = DISPATCH_LEVEL
-
- */
-VOID BssTableInit(
-	IN BSS_TABLE *Tab)
-{
-	int i;
-
-	Tab->BssNr = 0;
-    Tab->BssOverlapNr = 0;
-	for (i = 0; i < MAX_LEN_OF_BSS_TABLE; i++)
-	{
-		NdisZeroMemory(&Tab->BssEntry[i], sizeof(BSS_ENTRY));
-		Tab->BssEntry[i].Rssi = -127;	// initial the rssi as a minimum value
-	}
-}
-
-#ifdef DOT11_N_SUPPORT
-VOID BATableInit(
-	IN PRTMP_ADAPTER pAd,
-    IN BA_TABLE *Tab)
-{
-	int i;
-
-	Tab->numAsOriginator = 0;
-	Tab->numAsRecipient = 0;
-	NdisAllocateSpinLock(&pAd->BATabLock);
-	for (i = 0; i < MAX_LEN_OF_BA_REC_TABLE; i++)
-	{
-		Tab->BARecEntry[i].REC_BA_Status = Recipient_NONE;
-		NdisAllocateSpinLock(&(Tab->BARecEntry[i].RxReRingLock));
-	}
-	for (i = 0; i < MAX_LEN_OF_BA_ORI_TABLE; i++)
-	{
-		Tab->BAOriEntry[i].ORI_BA_Status = Originator_NONE;
-	}
-}
-#endif // DOT11_N_SUPPORT //
-
-/*! \brief search the BSS table by SSID
- *	\param p_tab pointer to the bss table
- *	\param ssid SSID string
- *	\return index of the table, BSS_NOT_FOUND if not in the table
- *	\pre
- *	\post
- *	\note search by sequential search
-
- IRQL = DISPATCH_LEVEL
-
- */
-ULONG BssTableSearch(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR	 pBssid,
-	IN UCHAR	 Channel)
-{
-	UCHAR i;
-
-	for (i = 0; i < Tab->BssNr; i++)
-	{
-		//
-		// Some AP that support A/B/G mode that may used the same BSSID on 11A and 11B/G.
-		// We should distinguish this case.
-		//
-		if ((((Tab->BssEntry[i].Channel <= 14) && (Channel <= 14)) ||
-			 ((Tab->BssEntry[i].Channel > 14) && (Channel > 14))) &&
-			MAC_ADDR_EQUAL(Tab->BssEntry[i].Bssid, pBssid))
-		{
-			return i;
-		}
-	}
-	return (ULONG)BSS_NOT_FOUND;
-}
-
-ULONG BssSsidTableSearch(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR	 pBssid,
-	IN PUCHAR	 pSsid,
-	IN UCHAR	 SsidLen,
-	IN UCHAR	 Channel)
-{
-	UCHAR i;
-
-	for (i = 0; i < Tab->BssNr; i++)
-	{
-		//
-		// Some AP that support A/B/G mode that may used the same BSSID on 11A and 11B/G.
-		// We should distinguish this case.
-		//
-		if ((((Tab->BssEntry[i].Channel <= 14) && (Channel <= 14)) ||
-			 ((Tab->BssEntry[i].Channel > 14) && (Channel > 14))) &&
-			MAC_ADDR_EQUAL(Tab->BssEntry[i].Bssid, pBssid) &&
-			SSID_EQUAL(pSsid, SsidLen, Tab->BssEntry[i].Ssid, Tab->BssEntry[i].SsidLen))
-		{
-			return i;
-		}
-	}
-	return (ULONG)BSS_NOT_FOUND;
-}
-
-ULONG BssTableSearchWithSSID(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR	 Bssid,
-	IN PUCHAR	 pSsid,
-	IN UCHAR	 SsidLen,
-	IN UCHAR	 Channel)
-{
-	UCHAR i;
-
-	for (i = 0; i < Tab->BssNr; i++)
-	{
-		if ((((Tab->BssEntry[i].Channel <= 14) && (Channel <= 14)) ||
-			((Tab->BssEntry[i].Channel > 14) && (Channel > 14))) &&
-			MAC_ADDR_EQUAL(&(Tab->BssEntry[i].Bssid), Bssid) &&
-			(SSID_EQUAL(pSsid, SsidLen, Tab->BssEntry[i].Ssid, Tab->BssEntry[i].SsidLen) ||
-			(NdisEqualMemory(pSsid, ZeroSsid, SsidLen)) ||
-			(NdisEqualMemory(Tab->BssEntry[i].Ssid, ZeroSsid, Tab->BssEntry[i].SsidLen))))
-		{
-			return i;
-		}
-	}
-	return (ULONG)BSS_NOT_FOUND;
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID BssTableDeleteEntry(
-	IN OUT	BSS_TABLE *Tab,
-	IN		PUCHAR	  pBssid,
-	IN		UCHAR	  Channel)
-{
-	UCHAR i, j;
-
-	for (i = 0; i < Tab->BssNr; i++)
-	{
-		if ((Tab->BssEntry[i].Channel == Channel) &&
-			(MAC_ADDR_EQUAL(Tab->BssEntry[i].Bssid, pBssid)))
-		{
-			for (j = i; j < Tab->BssNr - 1; j++)
-			{
-				NdisMoveMemory(&(Tab->BssEntry[j]), &(Tab->BssEntry[j + 1]), sizeof(BSS_ENTRY));
-			}
-			NdisZeroMemory(&(Tab->BssEntry[Tab->BssNr - 1]), sizeof(BSS_ENTRY));
-			Tab->BssNr -= 1;
-			return;
-		}
-	}
-}
-
-#ifdef DOT11_N_SUPPORT
-/*
-	========================================================================
-	Routine Description:
-		Delete the Originator Entry in BAtable. Or decrease numAs Originator by 1 if needed.
-
-	Arguments:
-	// IRQL = DISPATCH_LEVEL
-	========================================================================
-*/
-VOID BATableDeleteORIEntry(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		BA_ORI_ENTRY	*pBAORIEntry)
-{
-
-	if (pBAORIEntry->ORI_BA_Status != Originator_NONE)
-	{
-		NdisAcquireSpinLock(&pAd->BATabLock);
-		if (pBAORIEntry->ORI_BA_Status == Originator_Done)
-		{
-			pAd->BATable.numAsOriginator -= 1;
-			DBGPRINT(RT_DEBUG_TRACE, ("BATableDeleteORIEntry numAsOriginator= %ld\n", pAd->BATable.numAsRecipient));
-			// Erase Bitmap flag.
-		}
-		pAd->MacTab.Content[pBAORIEntry->Wcid].TXBAbitmap &= (~(1<<(pBAORIEntry->TID) ));	// If STA mode,  erase flag here
-		pAd->MacTab.Content[pBAORIEntry->Wcid].BAOriWcidArray[pBAORIEntry->TID] = 0;	// If STA mode,  erase flag here
-		pBAORIEntry->ORI_BA_Status = Originator_NONE;
-		pBAORIEntry->Token = 1;
-		// Not clear Sequence here.
-		NdisReleaseSpinLock(&pAd->BATabLock);
-	}
-}
-#endif // DOT11_N_SUPPORT //
-
-/*! \brief
- *	\param
- *	\return
- *	\pre
- *	\post
-
- IRQL = DISPATCH_LEVEL
-
- */
-VOID BssEntrySet(
-	IN PRTMP_ADAPTER	pAd,
-	OUT BSS_ENTRY *pBss,
-	IN PUCHAR pBssid,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR BssType,
-	IN USHORT BeaconPeriod,
-	IN PCF_PARM pCfParm,
-	IN USHORT AtimWin,
-	IN USHORT CapabilityInfo,
-	IN UCHAR SupRate[],
-	IN UCHAR SupRateLen,
-	IN UCHAR ExtRate[],
-	IN UCHAR ExtRateLen,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN ADD_HT_INFO_IE *pAddHtInfo,	// AP might use this additional ht info IE
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			AddHtInfoLen,
-	IN UCHAR			NewExtChanOffset,
-	IN UCHAR Channel,
-	IN CHAR Rssi,
-	IN LARGE_INTEGER TimeStamp,
-	IN UCHAR CkipFlag,
-	IN PEDCA_PARM pEdcaParm,
-	IN PQOS_CAPABILITY_PARM pQosCapability,
-	IN PQBSS_LOAD_PARM pQbssLoad,
-	IN USHORT LengthVIE,
-	IN PNDIS_802_11_VARIABLE_IEs pVIE)
-{
-	COPY_MAC_ADDR(pBss->Bssid, pBssid);
-	// Default Hidden SSID to be TRUE, it will be turned to FALSE after coping SSID
-	pBss->Hidden = 1;
-	if (SsidLen > 0)
-	{
-		// For hidden SSID AP, it might send beacon with SSID len equal to 0
-		// Or send beacon /probe response with SSID len matching real SSID length,
-		// but SSID is all zero. such as "00-00-00-00" with length 4.
-		// We have to prevent this case overwrite correct table
-		if (NdisEqualMemory(Ssid, ZeroSsid, SsidLen) == 0)
-		{
-		    NdisZeroMemory(pBss->Ssid, MAX_LEN_OF_SSID);
-			NdisMoveMemory(pBss->Ssid, Ssid, SsidLen);
-			pBss->SsidLen = SsidLen;
-			pBss->Hidden = 0;
-		}
-	}
-	else
-		pBss->SsidLen = 0;
-	pBss->BssType = BssType;
-	pBss->BeaconPeriod = BeaconPeriod;
-	if (BssType == BSS_INFRA)
-	{
-		if (pCfParm->bValid)
-		{
-			pBss->CfpCount = pCfParm->CfpCount;
-			pBss->CfpPeriod = pCfParm->CfpPeriod;
-			pBss->CfpMaxDuration = pCfParm->CfpMaxDuration;
-			pBss->CfpDurRemaining = pCfParm->CfpDurRemaining;
-		}
-	}
-	else
-	{
-		pBss->AtimWin = AtimWin;
-	}
-
-	pBss->CapabilityInfo = CapabilityInfo;
-	// The privacy bit indicate security is ON, it maight be WEP, TKIP or AES
-	// Combine with AuthMode, they will decide the connection methods.
-	pBss->Privacy = CAP_IS_PRIVACY_ON(pBss->CapabilityInfo);
-	ASSERT(SupRateLen <= MAX_LEN_OF_SUPPORTED_RATES);
-	if (SupRateLen <= MAX_LEN_OF_SUPPORTED_RATES)
-		NdisMoveMemory(pBss->SupRate, SupRate, SupRateLen);
-	else
-		NdisMoveMemory(pBss->SupRate, SupRate, MAX_LEN_OF_SUPPORTED_RATES);
-	pBss->SupRateLen = SupRateLen;
-	ASSERT(ExtRateLen <= MAX_LEN_OF_SUPPORTED_RATES);
-	NdisMoveMemory(pBss->ExtRate, ExtRate, ExtRateLen);
-	NdisMoveMemory(&pBss->HtCapability, pHtCapability, HtCapabilityLen);
-	NdisMoveMemory(&pBss->AddHtInfo, pAddHtInfo, AddHtInfoLen);
-	pBss->NewExtChanOffset = NewExtChanOffset;
-	pBss->ExtRateLen = ExtRateLen;
-	pBss->Channel = Channel;
-	pBss->CentralChannel = Channel;
-	pBss->Rssi = Rssi;
-	// Update CkipFlag. if not exists, the value is 0x0
-	pBss->CkipFlag = CkipFlag;
-
-	// New for microsoft Fixed IEs
-	NdisMoveMemory(pBss->FixIEs.Timestamp, &TimeStamp, 8);
-	pBss->FixIEs.BeaconInterval = BeaconPeriod;
-	pBss->FixIEs.Capabilities = CapabilityInfo;
-
-	// New for microsoft Variable IEs
-	if (LengthVIE != 0)
-	{
-		pBss->VarIELen = LengthVIE;
-		NdisMoveMemory(pBss->VarIEs, pVIE, pBss->VarIELen);
-	}
-	else
-	{
-		pBss->VarIELen = 0;
-	}
-
-	pBss->AddHtInfoLen = 0;
-	pBss->HtCapabilityLen = 0;
-#ifdef DOT11_N_SUPPORT
-	if (HtCapabilityLen> 0)
-	{
-		pBss->HtCapabilityLen = HtCapabilityLen;
-		NdisMoveMemory(&pBss->HtCapability, pHtCapability, HtCapabilityLen);
-		if (AddHtInfoLen > 0)
-		{
-			pBss->AddHtInfoLen = AddHtInfoLen;
-			NdisMoveMemory(&pBss->AddHtInfo, pAddHtInfo, AddHtInfoLen);
-
-	 			if ((pAddHtInfo->ControlChan > 2)&& (pAddHtInfo->AddHtInfo.ExtChanOffset == EXTCHA_BELOW) && (pHtCapability->HtCapInfo.ChannelWidth == BW_40))
-	 			{
-	 				pBss->CentralChannel = pAddHtInfo->ControlChan - 2;
-	 			}
-	 			else if ((pAddHtInfo->AddHtInfo.ExtChanOffset == EXTCHA_ABOVE) && (pHtCapability->HtCapInfo.ChannelWidth == BW_40))
-				{
-		 				pBss->CentralChannel = pAddHtInfo->ControlChan + 2;
-				}
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-	BssCipherParse(pBss);
-
-	// new for QOS
-	if (pEdcaParm)
-		NdisMoveMemory(&pBss->EdcaParm, pEdcaParm, sizeof(EDCA_PARM));
-	else
-		pBss->EdcaParm.bValid = FALSE;
-	if (pQosCapability)
-		NdisMoveMemory(&pBss->QosCapability, pQosCapability, sizeof(QOS_CAPABILITY_PARM));
-	else
-		pBss->QosCapability.bValid = FALSE;
-	if (pQbssLoad)
-		NdisMoveMemory(&pBss->QbssLoad, pQbssLoad, sizeof(QBSS_LOAD_PARM));
-	else
-		pBss->QbssLoad.bValid = FALSE;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		PEID_STRUCT     pEid;
-		USHORT          Length = 0;
-
-
-		NdisZeroMemory(&pBss->WpaIE.IE[0], MAX_CUSTOM_LEN);
-		NdisZeroMemory(&pBss->RsnIE.IE[0], MAX_CUSTOM_LEN);
-#ifdef EXT_BUILD_CHANNEL_LIST
-		NdisZeroMemory(&pBss->CountryString[0], 3);
-		pBss->bHasCountryIE = FALSE;
-#endif // EXT_BUILD_CHANNEL_LIST //
-		pEid = (PEID_STRUCT) pVIE;
-		while ((Length + 2 + (USHORT)pEid->Len) <= LengthVIE)
-		{
-			switch(pEid->Eid)
-			{
-				case IE_WPA:
-					if (NdisEqualMemory(pEid->Octet, WPA_OUI, 4))
-					{
-						if ((pEid->Len + 2) > MAX_CUSTOM_LEN)
-						{
-							pBss->WpaIE.IELen = 0;
-							break;
-						}
-						pBss->WpaIE.IELen = pEid->Len + 2;
-						NdisMoveMemory(pBss->WpaIE.IE, pEid, pBss->WpaIE.IELen);
-					}
-					break;
-                case IE_RSN:
-                    if (NdisEqualMemory(pEid->Octet + 2, RSN_OUI, 3))
-					{
-						if ((pEid->Len + 2) > MAX_CUSTOM_LEN)
-						{
-							pBss->RsnIE.IELen = 0;
-							break;
-						}
-						pBss->RsnIE.IELen = pEid->Len + 2;
-						NdisMoveMemory(pBss->RsnIE.IE, pEid, pBss->RsnIE.IELen);
-			}
-				break;
-#ifdef EXT_BUILD_CHANNEL_LIST
-				case IE_COUNTRY:
-					NdisMoveMemory(&pBss->CountryString[0], pEid->Octet, 3);
-					pBss->bHasCountryIE = TRUE;
-					break;
-#endif // EXT_BUILD_CHANNEL_LIST //
-            }
-			Length = Length + 2 + (USHORT)pEid->Len;  // Eid[1] + Len[1]+ content[Len]
-			pEid = (PEID_STRUCT)((UCHAR*)pEid + 2 + pEid->Len);
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-}
-
-/*!
- *	\brief insert an entry into the bss table
- *	\param p_tab The BSS table
- *	\param Bssid BSSID
- *	\param ssid SSID
- *	\param ssid_len Length of SSID
- *	\param bss_type
- *	\param beacon_period
- *	\param timestamp
- *	\param p_cf
- *	\param atim_win
- *	\param cap
- *	\param rates
- *	\param rates_len
- *	\param channel_idx
- *	\return none
- *	\pre
- *	\post
- *	\note If SSID is identical, the old entry will be replaced by the new one
-
- IRQL = DISPATCH_LEVEL
-
- */
-ULONG BssTableSetEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT BSS_TABLE *Tab,
-	IN PUCHAR pBssid,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR BssType,
-	IN USHORT BeaconPeriod,
-	IN CF_PARM *CfParm,
-	IN USHORT AtimWin,
-	IN USHORT CapabilityInfo,
-	IN UCHAR SupRate[],
-	IN UCHAR SupRateLen,
-	IN UCHAR ExtRate[],
-	IN UCHAR ExtRateLen,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN ADD_HT_INFO_IE *pAddHtInfo,	// AP might use this additional ht info IE
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			AddHtInfoLen,
-	IN UCHAR			NewExtChanOffset,
-	IN UCHAR ChannelNo,
-	IN CHAR Rssi,
-	IN LARGE_INTEGER TimeStamp,
-	IN UCHAR CkipFlag,
-	IN PEDCA_PARM pEdcaParm,
-	IN PQOS_CAPABILITY_PARM pQosCapability,
-	IN PQBSS_LOAD_PARM pQbssLoad,
-	IN USHORT LengthVIE,
-	IN PNDIS_802_11_VARIABLE_IEs pVIE)
-{
-	ULONG	Idx;
-
-	Idx = BssTableSearchWithSSID(Tab, pBssid,  Ssid, SsidLen, ChannelNo);
-	if (Idx == BSS_NOT_FOUND)
-	{
-		if (Tab->BssNr >= MAX_LEN_OF_BSS_TABLE)
-	    {
-			//
-			// It may happen when BSS Table was full.
-			// The desired AP will not be added into BSS Table
-			// In this case, if we found the desired AP then overwrite BSS Table.
-			//
-			if(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-			{
-				if (MAC_ADDR_EQUAL(pAd->MlmeAux.Bssid, pBssid) ||
-					SSID_EQUAL(pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen, Ssid, SsidLen))
-				{
-					Idx = Tab->BssOverlapNr;
-					BssEntrySet(pAd, &Tab->BssEntry[Idx], pBssid, Ssid, SsidLen, BssType, BeaconPeriod, CfParm, AtimWin,
-						CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,pHtCapability, pAddHtInfo,HtCapabilityLen, AddHtInfoLen,
-						NewExtChanOffset, ChannelNo, Rssi, TimeStamp, CkipFlag, pEdcaParm, pQosCapability, pQbssLoad, LengthVIE, pVIE);
-                    Tab->BssOverlapNr = (Tab->BssOverlapNr++) % MAX_LEN_OF_BSS_TABLE;
-				}
-				return Idx;
-			}
-			else
-			{
-			return BSS_NOT_FOUND;
-			}
-		}
-		Idx = Tab->BssNr;
-		BssEntrySet(pAd, &Tab->BssEntry[Idx], pBssid, Ssid, SsidLen, BssType, BeaconPeriod, CfParm, AtimWin,
-					CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,pHtCapability, pAddHtInfo,HtCapabilityLen, AddHtInfoLen,
-					NewExtChanOffset, ChannelNo, Rssi, TimeStamp, CkipFlag, pEdcaParm, pQosCapability, pQbssLoad, LengthVIE, pVIE);
-		Tab->BssNr++;
-	}
-	else
-	{
-		BssEntrySet(pAd, &Tab->BssEntry[Idx], pBssid, Ssid, SsidLen, BssType, BeaconPeriod,CfParm, AtimWin,
-					CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,pHtCapability, pAddHtInfo,HtCapabilityLen, AddHtInfoLen,
-					NewExtChanOffset, ChannelNo, Rssi, TimeStamp, CkipFlag, pEdcaParm, pQosCapability, pQbssLoad, LengthVIE, pVIE);
-	}
-
-	return Idx;
-}
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-VOID  TriEventInit(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UCHAR		i;
-
-	for (i = 0;i < MAX_TRIGGER_EVENT;i++)
-		pAd->CommonCfg.TriggerEventTab.EventA[i].bValid = FALSE;
-
-	pAd->CommonCfg.TriggerEventTab.EventANo = 0;
-	pAd->CommonCfg.TriggerEventTab.EventBCountDown = 0;
-}
-
-ULONG TriEventTableSetEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT TRIGGER_EVENT_TAB *Tab,
-	IN PUCHAR pBssid,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			RegClass,
-	IN UCHAR ChannelNo)
-{
-	// Event A
-	if (HtCapabilityLen == 0)
-	{
-		if (Tab->EventANo < MAX_TRIGGER_EVENT)
-		{
-			RTMPMoveMemory(Tab->EventA[Tab->EventANo].BSSID, pBssid, 6);
-			Tab->EventA[Tab->EventANo].bValid = TRUE;
-			Tab->EventA[Tab->EventANo].Channel = ChannelNo;
-			Tab->EventA[Tab->EventANo].CDCounter = pAd->CommonCfg.Dot11BssWidthChanTranDelay;
-			if (RegClass != 0)
-			{
-				// Beacon has Regulatory class IE. So use beacon's
-				Tab->EventA[Tab->EventANo].RegClass = RegClass;
-			}
-			else
-			{
-				// Use Station's Regulatory class instead.
-				if (pAd->StaActive.SupportedHtPhy.bHtEnable == TRUE)
-				{
-					if (pAd->CommonCfg.CentralChannel > pAd->CommonCfg.Channel)
-					{
-						Tab->EventA[Tab->EventANo].RegClass = 32;
-					}
-					else if (pAd->CommonCfg.CentralChannel < pAd->CommonCfg.Channel)
-						Tab->EventA[Tab->EventANo].RegClass = 33;
-				}
-				else
-					Tab->EventA[Tab->EventANo].RegClass = ??;
-
-			}
-
-			Tab->EventANo ++;
-		}
-	}
-	else if (pHtCapability->HtCapInfo.Intolerant40)
-	{
-		Tab->EventBCountDown = pAd->CommonCfg.Dot11BssWidthChanTranDelay;
-	}
-
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Trigger Event table Maintainence called once every second.
-
-	Arguments:
-	// IRQL = DISPATCH_LEVEL
-	========================================================================
-*/
-VOID TriEventCounterMaintenance(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UCHAR		i;
-	BOOLEAN			bNotify = FALSE;
-	for (i = 0;i < MAX_TRIGGER_EVENT;i++)
-	{
-		if (pAd->CommonCfg.TriggerEventTab.EventA[i].bValid && (pAd->CommonCfg.TriggerEventTab.EventA[i].CDCounter > 0))
-		{
-			pAd->CommonCfg.TriggerEventTab.EventA[i].CDCounter--;
-			if (pAd->CommonCfg.TriggerEventTab.EventA[i].CDCounter == 0)
-			{
-				pAd->CommonCfg.TriggerEventTab.EventA[i].bValid = FALSE;
-				pAd->CommonCfg.TriggerEventTab.EventANo --;
-				// Need to send 20/40 Coexistence Notify frame if has status change.
-				bNotify = TRUE;
-			}
-		}
-	}
-	if (pAd->CommonCfg.TriggerEventTab.EventBCountDown > 0)
-	{
-		pAd->CommonCfg.TriggerEventTab.EventBCountDown--;
-		if (pAd->CommonCfg.TriggerEventTab.EventBCountDown == 0)
-			bNotify = TRUE;
-	}
-
-	if (bNotify == TRUE)
-		Update2040CoexistFrameAndNotify(pAd, BSSID_WCID, TRUE);
-}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-// IRQL = DISPATCH_LEVEL
-VOID BssTableSsidSort(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT BSS_TABLE *OutTab,
-	IN	CHAR Ssid[],
-	IN	UCHAR SsidLen)
-{
-	INT i;
-	BssTableInit(OutTab);
-
-	for (i = 0; i < pAd->ScanTab.BssNr; i++)
-	{
-		BSS_ENTRY *pInBss = &pAd->ScanTab.BssEntry[i];
-		BOOLEAN	bIsHiddenApIncluded = FALSE;
-
-		if (((pAd->CommonCfg.bIEEE80211H == 1) &&
-            (pAd->MlmeAux.Channel > 14) &&
-             RadarChannelCheck(pAd, pInBss->Channel))
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-             || (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-#endif // CARRIER_DETECTION_SUPPORT //
-            )
-		{
-			if (pInBss->Hidden)
-				bIsHiddenApIncluded = TRUE;
-		}
-
-		if ((pInBss->BssType == pAd->StaCfg.BssType) &&
-			(SSID_EQUAL(Ssid, SsidLen, pInBss->Ssid, pInBss->SsidLen) || bIsHiddenApIncluded))
-		{
-			BSS_ENTRY *pOutBss = &OutTab->BssEntry[OutTab->BssNr];
-
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-			// If no Country IE exists no Connection will be established when IEEE80211dClientMode is strict.
-			if ((pAd->StaCfg.IEEE80211dClientMode == Rt802_11_D_Strict) &&
-				(pInBss->bHasCountryIE == FALSE))
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("StaCfg.IEEE80211dClientMode == Rt802_11_D_Strict, but this AP doesn't have country IE.\n"));
-				continue;
-			}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef DOT11_N_SUPPORT
-			// 2.4G/5G N only mode
-			if ((pInBss->HtCapabilityLen == 0) &&
-				((pAd->CommonCfg.PhyMode == PHY_11N_2_4G) || (pAd->CommonCfg.PhyMode == PHY_11N_5G)))
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("STA is in N-only Mode, this AP don't have Ht capability in Beacon.\n"));
-				continue;
-			}
-#endif // DOT11_N_SUPPORT //
-
-			// New for WPA2
-			// Check the Authmode first
-			if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-			{
-				// Check AuthMode and AuthModeAux for matching, in case AP support dual-mode
-				if ((pAd->StaCfg.AuthMode != pInBss->AuthMode) && (pAd->StaCfg.AuthMode != pInBss->AuthModeAux))
-					// None matched
-					continue;
-
-				// Check cipher suite, AP must have more secured cipher than station setting
-				if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-				{
-					// If it's not mixed mode, we should only let BSS pass with the same encryption
-					if (pInBss->WPA.bMixMode == FALSE)
-						if (pAd->StaCfg.WepStatus != pInBss->WPA.GroupCipher)
-							continue;
-
-					// check group cipher
-					if ((pAd->StaCfg.WepStatus < pInBss->WPA.GroupCipher) &&
-						(pInBss->WPA.GroupCipher != Ndis802_11GroupWEP40Enabled) &&
-						(pInBss->WPA.GroupCipher != Ndis802_11GroupWEP104Enabled))
-						continue;
-
-					// check pairwise cipher, skip if none matched
-					// If profile set to AES, let it pass without question.
-					// If profile set to TKIP, we must find one mateched
-					if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA.PairCipher) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA.PairCipherAux))
-						continue;
-				}
-				else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-				{
-					// If it's not mixed mode, we should only let BSS pass with the same encryption
-					if (pInBss->WPA2.bMixMode == FALSE)
-						if (pAd->StaCfg.WepStatus != pInBss->WPA2.GroupCipher)
-							continue;
-
-					// check group cipher
-					if ((pAd->StaCfg.WepStatus < pInBss->WPA.GroupCipher) &&
-						(pInBss->WPA2.GroupCipher != Ndis802_11GroupWEP40Enabled) &&
-						(pInBss->WPA2.GroupCipher != Ndis802_11GroupWEP104Enabled))
-						continue;
-
-					// check pairwise cipher, skip if none matched
-					// If profile set to AES, let it pass without question.
-					// If profile set to TKIP, we must find one mateched
-					if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA2.PairCipher) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA2.PairCipherAux))
-						continue;
-				}
-			}
-			// Bss Type matched, SSID matched.
-			// We will check wepstatus for qualification Bss
-			else if (pAd->StaCfg.WepStatus != pInBss->WepStatus)
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("StaCfg.WepStatus=%d, while pInBss->WepStatus=%d\n", pAd->StaCfg.WepStatus, pInBss->WepStatus));
-				//
-				// For the SESv2 case, we will not qualify WepStatus.
-				//
-				if (!pInBss->bSES)
-					continue;
-			}
-
-			// Since the AP is using hidden SSID, and we are trying to connect to ANY
-			// It definitely will fail. So, skip it.
-			// CCX also require not even try to connect it!!
-			if (SsidLen == 0)
-				continue;
-
-#ifdef DOT11_N_SUPPORT
-			// If both station and AP use 40MHz, still need to check if the 40MHZ band's legality in my country region
-			// If this 40MHz wideband is not allowed in my country list, use bandwidth 20MHZ instead,
-			if ((pInBss->CentralChannel != pInBss->Channel) &&
-				(pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40))
-			{
-				if (RTMPCheckChannel(pAd, pInBss->CentralChannel, pInBss->Channel) == FALSE)
-				{
-					pAd->CommonCfg.RegTransmitSetting.field.BW = BW_20;
-					SetCommonHT(pAd);
-					pAd->CommonCfg.RegTransmitSetting.field.BW = BW_40;
-				}
-				else
-				{
-					if (pAd->CommonCfg.DesiredHtPhy.ChannelWidth == BAND_WIDTH_20)
-					{
-						SetCommonHT(pAd);
-					}
-				}
-			}
-#endif // DOT11_N_SUPPORT //
-
-			// copy matching BSS from InTab to OutTab
-			NdisMoveMemory(pOutBss, pInBss, sizeof(BSS_ENTRY));
-
-			OutTab->BssNr++;
-		}
-		else if ((pInBss->BssType == pAd->StaCfg.BssType) && (SsidLen == 0))
-		{
-			BSS_ENTRY *pOutBss = &OutTab->BssEntry[OutTab->BssNr];
-
-
-#ifdef DOT11_N_SUPPORT
-			// 2.4G/5G N only mode
-			if ((pInBss->HtCapabilityLen == 0) &&
-				((pAd->CommonCfg.PhyMode == PHY_11N_2_4G) || (pAd->CommonCfg.PhyMode == PHY_11N_5G)))
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("STA is in N-only Mode, this AP don't have Ht capability in Beacon.\n"));
-				continue;
-			}
-#endif // DOT11_N_SUPPORT //
-
-			// New for WPA2
-			// Check the Authmode first
-			if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-			{
-				// Check AuthMode and AuthModeAux for matching, in case AP support dual-mode
-				if ((pAd->StaCfg.AuthMode != pInBss->AuthMode) && (pAd->StaCfg.AuthMode != pInBss->AuthModeAux))
-					// None matched
-					continue;
-
-				// Check cipher suite, AP must have more secured cipher than station setting
-				if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-				{
-					// If it's not mixed mode, we should only let BSS pass with the same encryption
-					if (pInBss->WPA.bMixMode == FALSE)
-						if (pAd->StaCfg.WepStatus != pInBss->WPA.GroupCipher)
-							continue;
-
-					// check group cipher
-					if (pAd->StaCfg.WepStatus < pInBss->WPA.GroupCipher)
-						continue;
-
-					// check pairwise cipher, skip if none matched
-					// If profile set to AES, let it pass without question.
-					// If profile set to TKIP, we must find one mateched
-					if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA.PairCipher) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA.PairCipherAux))
-						continue;
-				}
-				else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-				{
-					// If it's not mixed mode, we should only let BSS pass with the same encryption
-					if (pInBss->WPA2.bMixMode == FALSE)
-						if (pAd->StaCfg.WepStatus != pInBss->WPA2.GroupCipher)
-							continue;
-
-					// check group cipher
-					if (pAd->StaCfg.WepStatus < pInBss->WPA2.GroupCipher)
-						continue;
-
-					// check pairwise cipher, skip if none matched
-					// If profile set to AES, let it pass without question.
-					// If profile set to TKIP, we must find one mateched
-					if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA2.PairCipher) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA2.PairCipherAux))
-						continue;
-				}
-			}
-			// Bss Type matched, SSID matched.
-			// We will check wepstatus for qualification Bss
-			else if (pAd->StaCfg.WepStatus != pInBss->WepStatus)
-					continue;
-
-#ifdef DOT11_N_SUPPORT
-			// If both station and AP use 40MHz, still need to check if the 40MHZ band's legality in my country region
-			// If this 40MHz wideband is not allowed in my country list, use bandwidth 20MHZ instead,
-			if ((pInBss->CentralChannel != pInBss->Channel) &&
-				(pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40))
-			{
-				if (RTMPCheckChannel(pAd, pInBss->CentralChannel, pInBss->Channel) == FALSE)
-				{
-					pAd->CommonCfg.RegTransmitSetting.field.BW = BW_20;
-					SetCommonHT(pAd);
-					pAd->CommonCfg.RegTransmitSetting.field.BW = BW_40;
-				}
-			}
-#endif // DOT11_N_SUPPORT //
-
-			// copy matching BSS from InTab to OutTab
-			NdisMoveMemory(pOutBss, pInBss, sizeof(BSS_ENTRY));
-
-			OutTab->BssNr++;
-		}
-
-		if (OutTab->BssNr >= MAX_LEN_OF_BSS_TABLE)
-			break;
-	}
-
-	BssTableSortByRssi(OutTab);
-}
-
-
-// IRQL = DISPATCH_LEVEL
-VOID BssTableSortByRssi(
-	IN OUT BSS_TABLE *OutTab)
-{
-	INT 	  i, j;
-	BSS_ENTRY TmpBss;
-
-	for (i = 0; i < OutTab->BssNr - 1; i++)
-	{
-		for (j = i+1; j < OutTab->BssNr; j++)
-		{
-			if (OutTab->BssEntry[j].Rssi > OutTab->BssEntry[i].Rssi)
-			{
-				NdisMoveMemory(&TmpBss, &OutTab->BssEntry[j], sizeof(BSS_ENTRY));
-				NdisMoveMemory(&OutTab->BssEntry[j], &OutTab->BssEntry[i], sizeof(BSS_ENTRY));
-				NdisMoveMemory(&OutTab->BssEntry[i], &TmpBss, sizeof(BSS_ENTRY));
-			}
-		}
-	}
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-VOID BssCipherParse(
-	IN OUT	PBSS_ENTRY	pBss)
-{
-	PEID_STRUCT 		 pEid;
-	PUCHAR				pTmp;
-	PRSN_IE_HEADER_STRUCT			pRsnHeader;
-	PCIPHER_SUITE_STRUCT			pCipher;
-	PAKM_SUITE_STRUCT				pAKM;
-	USHORT							Count;
-	INT								Length;
-	NDIS_802_11_ENCRYPTION_STATUS	TmpCipher;
-
-	//
-	// WepStatus will be reset later, if AP announce TKIP or AES on the beacon frame.
-	//
-	if (pBss->Privacy)
-	{
-		pBss->WepStatus 	= Ndis802_11WEPEnabled;
-	}
-	else
-	{
-		pBss->WepStatus 	= Ndis802_11WEPDisabled;
-	}
-	// Set default to disable & open authentication before parsing variable IE
-	pBss->AuthMode		= Ndis802_11AuthModeOpen;
-	pBss->AuthModeAux	= Ndis802_11AuthModeOpen;
-
-	// Init WPA setting
-	pBss->WPA.PairCipher	= Ndis802_11WEPDisabled;
-	pBss->WPA.PairCipherAux = Ndis802_11WEPDisabled;
-	pBss->WPA.GroupCipher	= Ndis802_11WEPDisabled;
-	pBss->WPA.RsnCapability = 0;
-	pBss->WPA.bMixMode		= FALSE;
-
-	// Init WPA2 setting
-	pBss->WPA2.PairCipher	 = Ndis802_11WEPDisabled;
-	pBss->WPA2.PairCipherAux = Ndis802_11WEPDisabled;
-	pBss->WPA2.GroupCipher	 = Ndis802_11WEPDisabled;
-	pBss->WPA2.RsnCapability = 0;
-	pBss->WPA2.bMixMode 	 = FALSE;
-
-
-	Length = (INT) pBss->VarIELen;
-
-	while (Length > 0)
-	{
-		// Parse cipher suite base on WPA1 & WPA2, they should be parsed differently
-		pTmp = ((PUCHAR) pBss->VarIEs) + pBss->VarIELen - Length;
-		pEid = (PEID_STRUCT) pTmp;
-		switch (pEid->Eid)
-		{
-			case IE_WPA:
-				//Parse Cisco IE_WPA (LEAP, CCKM, etc.)
-				if ( NdisEqualMemory((pTmp+8), CISCO_OUI, 3))
-				{
-					pTmp   += 11;
-					switch (*pTmp)
-					{
-						case 1:
-						case 5:	// Although WEP is not allowed in WPA related auth mode, we parse it anyway
-							pBss->WepStatus = Ndis802_11Encryption1Enabled;
-							pBss->WPA.PairCipher = Ndis802_11Encryption1Enabled;
-							pBss->WPA.GroupCipher = Ndis802_11Encryption1Enabled;
-							break;
-						case 2:
-							pBss->WepStatus = Ndis802_11Encryption2Enabled;
-							pBss->WPA.PairCipher = Ndis802_11Encryption1Enabled;
-							pBss->WPA.GroupCipher = Ndis802_11Encryption1Enabled;
-							break;
-						case 4:
-							pBss->WepStatus = Ndis802_11Encryption3Enabled;
-							pBss->WPA.PairCipher = Ndis802_11Encryption1Enabled;
-							pBss->WPA.GroupCipher = Ndis802_11Encryption1Enabled;
-							break;
-						default:
-							break;
-					}
-
-					// if Cisco IE_WPA, break
-					break;
-				}
-				else if (NdisEqualMemory(pEid->Octet, SES_OUI, 3) && (pEid->Len == 7))
-				{
-					pBss->bSES = TRUE;
-					break;
-				}
-				else if (NdisEqualMemory(pEid->Octet, WPA_OUI, 4) != 1)
-				{
-					// if unsupported vendor specific IE
-					break;
-				}
-				// Skip OUI, version, and multicast suite
-				// This part should be improved in the future when AP supported multiple cipher suite.
-				// For now, it's OK since almost all APs have fixed cipher suite supported.
-				// pTmp = (PUCHAR) pEid->Octet;
-				pTmp   += 11;
-
-				// Cipher Suite Selectors from Spec P802.11i/D3.2 P26.
-				//	Value	   Meaning
-				//	0			None
-				//	1			WEP-40
-				//	2			Tkip
-				//	3			WRAP
-				//	4			AES
-				//	5			WEP-104
-				// Parse group cipher
-				switch (*pTmp)
-				{
-					case 1:
-						pBss->WPA.GroupCipher = Ndis802_11GroupWEP40Enabled;
-						break;
-					case 5:
-						pBss->WPA.GroupCipher = Ndis802_11GroupWEP104Enabled;
-						break;
-					case 2:
-						pBss->WPA.GroupCipher = Ndis802_11Encryption2Enabled;
-						break;
-					case 4:
-						pBss->WPA.GroupCipher = Ndis802_11Encryption3Enabled;
-						break;
-					default:
-						break;
-				}
-				// number of unicast suite
-				pTmp   += 1;
-
-				// skip all unicast cipher suites
-				//Count = *(PUSHORT) pTmp;
-				Count = (pTmp[1]<<8) + pTmp[0];
-				pTmp   += sizeof(USHORT);
-
-				// Parsing all unicast cipher suite
-				while (Count > 0)
-				{
-					// Skip OUI
-					pTmp += 3;
-					TmpCipher = Ndis802_11WEPDisabled;
-					switch (*pTmp)
-					{
-						case 1:
-						case 5: // Although WEP is not allowed in WPA related auth mode, we parse it anyway
-							TmpCipher = Ndis802_11Encryption1Enabled;
-							break;
-						case 2:
-							TmpCipher = Ndis802_11Encryption2Enabled;
-							break;
-						case 4:
-							TmpCipher = Ndis802_11Encryption3Enabled;
-							break;
-						default:
-							break;
-					}
-					if (TmpCipher > pBss->WPA.PairCipher)
-					{
-						// Move the lower cipher suite to PairCipherAux
-						pBss->WPA.PairCipherAux = pBss->WPA.PairCipher;
-						pBss->WPA.PairCipher	= TmpCipher;
-					}
-					else
-					{
-						pBss->WPA.PairCipherAux = TmpCipher;
-					}
-					pTmp++;
-					Count--;
-				}
-
-				// 4. get AKM suite counts
-				//Count	= *(PUSHORT) pTmp;
-				Count = (pTmp[1]<<8) + pTmp[0];
-				pTmp   += sizeof(USHORT);
-				pTmp   += 3;
-
-				switch (*pTmp)
-				{
-					case 1:
-						// Set AP support WPA mode
-						if (pBss->AuthMode == Ndis802_11AuthModeOpen)
-							pBss->AuthMode = Ndis802_11AuthModeWPA;
-						else
-							pBss->AuthModeAux = Ndis802_11AuthModeWPA;
-						break;
-					case 2:
-						// Set AP support WPA mode
-						if (pBss->AuthMode == Ndis802_11AuthModeOpen)
-							pBss->AuthMode = Ndis802_11AuthModeWPAPSK;
-						else
-							pBss->AuthModeAux = Ndis802_11AuthModeWPAPSK;
-						break;
-					default:
-						break;
-				}
-				pTmp   += 1;
-
-				// Fixed for WPA-None
-				if (pBss->BssType == BSS_ADHOC)
-				{
-					pBss->AuthMode	  = Ndis802_11AuthModeWPANone;
-					pBss->AuthModeAux = Ndis802_11AuthModeWPANone;
-					pBss->WepStatus   = pBss->WPA.GroupCipher;
-					// Patched bugs for old driver
-					if (pBss->WPA.PairCipherAux == Ndis802_11WEPDisabled)
-						pBss->WPA.PairCipherAux = pBss->WPA.GroupCipher;
-				}
-				else
-					pBss->WepStatus   = pBss->WPA.PairCipher;
-
-				// Check the Pair & Group, if different, turn on mixed mode flag
-				if (pBss->WPA.GroupCipher != pBss->WPA.PairCipher)
-					pBss->WPA.bMixMode = TRUE;
-
-				break;
-
-			case IE_RSN:
-				pRsnHeader = (PRSN_IE_HEADER_STRUCT) pTmp;
-
-				// 0. Version must be 1
-				if (le2cpu16(pRsnHeader->Version) != 1)
-					break;
-				pTmp   += sizeof(RSN_IE_HEADER_STRUCT);
-
-				// 1. Check group cipher
-				pCipher = (PCIPHER_SUITE_STRUCT) pTmp;
-				if (!RTMPEqualMemory(pTmp, RSN_OUI, 3))
-					break;
-
-				// Parse group cipher
-				switch (pCipher->Type)
-				{
-					case 1:
-						pBss->WPA2.GroupCipher = Ndis802_11GroupWEP40Enabled;
-						break;
-					case 5:
-						pBss->WPA2.GroupCipher = Ndis802_11GroupWEP104Enabled;
-						break;
-					case 2:
-						pBss->WPA2.GroupCipher = Ndis802_11Encryption2Enabled;
-						break;
-					case 4:
-						pBss->WPA2.GroupCipher = Ndis802_11Encryption3Enabled;
-						break;
-					default:
-						break;
-				}
-				// set to correct offset for next parsing
-				pTmp   += sizeof(CIPHER_SUITE_STRUCT);
-
-				// 2. Get pairwise cipher counts
-				//Count = *(PUSHORT) pTmp;
-				Count = (pTmp[1]<<8) + pTmp[0];
-				pTmp   += sizeof(USHORT);
-
-				// 3. Get pairwise cipher
-				// Parsing all unicast cipher suite
-				while (Count > 0)
-				{
-					// Skip OUI
-					pCipher = (PCIPHER_SUITE_STRUCT) pTmp;
-					TmpCipher = Ndis802_11WEPDisabled;
-					switch (pCipher->Type)
-					{
-						case 1:
-						case 5: // Although WEP is not allowed in WPA related auth mode, we parse it anyway
-							TmpCipher = Ndis802_11Encryption1Enabled;
-							break;
-						case 2:
-							TmpCipher = Ndis802_11Encryption2Enabled;
-							break;
-						case 4:
-							TmpCipher = Ndis802_11Encryption3Enabled;
-							break;
-						default:
-							break;
-					}
-					if (TmpCipher > pBss->WPA2.PairCipher)
-					{
-						// Move the lower cipher suite to PairCipherAux
-						pBss->WPA2.PairCipherAux = pBss->WPA2.PairCipher;
-						pBss->WPA2.PairCipher	 = TmpCipher;
-					}
-					else
-					{
-						pBss->WPA2.PairCipherAux = TmpCipher;
-					}
-					pTmp += sizeof(CIPHER_SUITE_STRUCT);
-					Count--;
-				}
-
-				// 4. get AKM suite counts
-				//Count	= *(PUSHORT) pTmp;
-				Count = (pTmp[1]<<8) + pTmp[0];
-				pTmp   += sizeof(USHORT);
-
-				// 5. Get AKM ciphers
-				pAKM = (PAKM_SUITE_STRUCT) pTmp;
-				if (!RTMPEqualMemory(pTmp, RSN_OUI, 3))
-					break;
-
-				switch (pAKM->Type)
-				{
-					case 1:
-						// Set AP support WPA mode
-						if (pBss->AuthMode == Ndis802_11AuthModeOpen)
-							pBss->AuthMode = Ndis802_11AuthModeWPA2;
-						else
-							pBss->AuthModeAux = Ndis802_11AuthModeWPA2;
-						break;
-					case 2:
-						// Set AP support WPA mode
-						if (pBss->AuthMode == Ndis802_11AuthModeOpen)
-							pBss->AuthMode = Ndis802_11AuthModeWPA2PSK;
-						else
-							pBss->AuthModeAux = Ndis802_11AuthModeWPA2PSK;
-						break;
-					default:
-						break;
-				}
-				pTmp   += (Count * sizeof(AKM_SUITE_STRUCT));
-
-				// Fixed for WPA-None
-				if (pBss->BssType == BSS_ADHOC)
-				{
-					pBss->AuthMode = Ndis802_11AuthModeWPANone;
-					pBss->AuthModeAux = Ndis802_11AuthModeWPANone;
-					pBss->WPA.PairCipherAux = pBss->WPA2.PairCipherAux;
-					pBss->WPA.GroupCipher	= pBss->WPA2.GroupCipher;
-					pBss->WepStatus 		= pBss->WPA.GroupCipher;
-					// Patched bugs for old driver
-					if (pBss->WPA.PairCipherAux == Ndis802_11WEPDisabled)
-						pBss->WPA.PairCipherAux = pBss->WPA.GroupCipher;
-				}
-				pBss->WepStatus   = pBss->WPA2.PairCipher;
-
-				// 6. Get RSN capability
-				//pBss->WPA2.RsnCapability = *(PUSHORT) pTmp;
-				pBss->WPA2.RsnCapability = (pTmp[1]<<8) + pTmp[0];
-				pTmp += sizeof(USHORT);
-
-				// Check the Pair & Group, if different, turn on mixed mode flag
-				if (pBss->WPA2.GroupCipher != pBss->WPA2.PairCipher)
-					pBss->WPA2.bMixMode = TRUE;
-
-				break;
-			default:
-				break;
-		}
-		Length -= (pEid->Len + 2);
-	}
-}
-
-// ===========================================================================================
-// mac_table.c
-// ===========================================================================================
-
-/*! \brief generates a random mac address value for IBSS BSSID
- *	\param Addr the bssid location
- *	\return none
- *	\pre
- *	\post
- */
-VOID MacAddrRandomBssid(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pAddr)
-{
-	INT i;
-
-	for (i = 0; i < MAC_ADDR_LEN; i++)
-	{
-		pAddr[i] = RandomByte(pAd);
-	}
-
-	pAddr[0] = (pAddr[0] & 0xfe) | 0x02;  // the first 2 bits must be 01xxxxxxxx
-}
-
-/*! \brief init the management mac frame header
- *	\param p_hdr mac header
- *	\param subtype subtype of the frame
- *	\param p_ds destination address, don't care if it is a broadcast address
- *	\return none
- *	\pre the station has the following information in the pAd->StaCfg
- *	 - bssid
- *	 - station address
- *	\post
- *	\note this function initializes the following field
-
- IRQL = PASSIVE_LEVEL
- IRQL = DISPATCH_LEVEL
-
- */
-VOID MgtMacHeaderInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN OUT PHEADER_802_11 pHdr80211,
-	IN UCHAR SubType,
-	IN UCHAR ToDs,
-	IN PUCHAR pDA,
-	IN PUCHAR pBssid)
-{
-	NdisZeroMemory(pHdr80211, sizeof(HEADER_802_11));
-
-	pHdr80211->FC.Type = BTYPE_MGMT;
-	pHdr80211->FC.SubType = SubType;
-//	if (SubType == SUBTYPE_ACK)	// sample, no use, it will conflict with ACTION frame sub type
-//		pHdr80211->FC.Type = BTYPE_CNTL;
-	pHdr80211->FC.ToDs = ToDs;
-	COPY_MAC_ADDR(pHdr80211->Addr1, pDA);
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		COPY_MAC_ADDR(pHdr80211->Addr2, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
-	COPY_MAC_ADDR(pHdr80211->Addr3, pBssid);
-}
-
-// ===========================================================================================
-// mem_mgmt.c
-// ===========================================================================================
-
-/*!***************************************************************************
- * This routine build an outgoing frame, and fill all information specified
- * in argument list to the frame body. The actual frame size is the summation
- * of all arguments.
- * input params:
- *		Buffer - pointer to a pre-allocated memory segment
- *		args - a list of <int arg_size, arg> pairs.
- *		NOTE NOTE NOTE!!!! the last argument must be NULL, otherwise this
- *						   function will FAIL!!!
- * return:
- *		Size of the buffer
- * usage:
- *		MakeOutgoingFrame(Buffer, output_length, 2, &fc, 2, &dur, 6, p_addr1, 6,p_addr2, END_OF_ARGS);
-
- IRQL = PASSIVE_LEVEL
- IRQL = DISPATCH_LEVEL
-
- ****************************************************************************/
-ULONG MakeOutgoingFrame(
-	OUT CHAR *Buffer,
-	OUT ULONG *FrameLen, ...)
-{
-	CHAR   *p;
-	int 	leng;
-	ULONG	TotLeng;
-	va_list Args;
-
-	// calculates the total length
-	TotLeng = 0;
-	va_start(Args, FrameLen);
-	do
-	{
-		leng = va_arg(Args, int);
-		if (leng == END_OF_ARGS)
-		{
-			break;
-		}
-		p = va_arg(Args, PVOID);
-		NdisMoveMemory(&Buffer[TotLeng], p, leng);
-		TotLeng = TotLeng + leng;
-	} while(TRUE);
-
-	va_end(Args); /* clean up */
-	*FrameLen = TotLeng;
-	return TotLeng;
-}
-
-// ===========================================================================================
-// mlme_queue.c
-// ===========================================================================================
-
-/*! \brief	Initialize The MLME Queue, used by MLME Functions
- *	\param	*Queue	   The MLME Queue
- *	\return Always	   Return NDIS_STATE_SUCCESS in this implementation
- *	\pre
- *	\post
- *	\note	Because this is done only once (at the init stage), no need to be locked
-
- IRQL = PASSIVE_LEVEL
-
- */
-NDIS_STATUS MlmeQueueInit(
-	IN MLME_QUEUE *Queue)
-{
-	INT i;
-
-	NdisAllocateSpinLock(&Queue->Lock);
-
-	Queue->Num	= 0;
-	Queue->Head = 0;
-	Queue->Tail = 0;
-
-	for (i = 0; i < MAX_LEN_OF_MLME_QUEUE; i++)
-	{
-		Queue->Entry[i].Occupied = FALSE;
-		Queue->Entry[i].MsgLen = 0;
-		NdisZeroMemory(Queue->Entry[i].Msg, MGMT_DMA_BUFFER_SIZE);
-	}
-
-	return NDIS_STATUS_SUCCESS;
-}
-
-/*! \brief	 Enqueue a message for other threads, if they want to send messages to MLME thread
- *	\param	*Queue	  The MLME Queue
- *	\param	 Machine  The State Machine Id
- *	\param	 MsgType  The Message Type
- *	\param	 MsgLen   The Message length
- *	\param	*Msg	  The message pointer
- *	\return  TRUE if enqueue is successful, FALSE if the queue is full
- *	\pre
- *	\post
- *	\note	 The message has to be initialized
-
- IRQL = PASSIVE_LEVEL
- IRQL = DISPATCH_LEVEL
-
- */
-BOOLEAN MlmeEnqueue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN ULONG Machine,
-	IN ULONG MsgType,
-	IN ULONG MsgLen,
-	IN VOID *Msg)
-{
-	INT Tail;
-	MLME_QUEUE	*Queue = (MLME_QUEUE *)&pAd->Mlme.Queue;
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return FALSE;
-
-	// First check the size, it MUST not exceed the mlme queue size
-	if (MsgLen > MGMT_DMA_BUFFER_SIZE)
-	{
-		DBGPRINT_ERR(("MlmeEnqueue: msg too large, size = %ld \n", MsgLen));
-		return FALSE;
-	}
-
-	if (MlmeQueueFull(Queue))
-	{
-		return FALSE;
-	}
-
-	NdisAcquireSpinLock(&(Queue->Lock));
-	Tail = Queue->Tail;
-	Queue->Tail++;
-	Queue->Num++;
-	if (Queue->Tail == MAX_LEN_OF_MLME_QUEUE)
-	{
-		Queue->Tail = 0;
-	}
-
-	Queue->Entry[Tail].Wcid = RESERVED_WCID;
-	Queue->Entry[Tail].Occupied = TRUE;
-	Queue->Entry[Tail].Machine = Machine;
-	Queue->Entry[Tail].MsgType = MsgType;
-	Queue->Entry[Tail].MsgLen  = MsgLen;
-
-	if (Msg != NULL)
-	{
-		NdisMoveMemory(Queue->Entry[Tail].Msg, Msg, MsgLen);
-	}
-
-	NdisReleaseSpinLock(&(Queue->Lock));
-	return TRUE;
-}
-
-/*! \brief	 This function is used when Recv gets a MLME message
- *	\param	*Queue			 The MLME Queue
- *	\param	 TimeStampHigh	 The upper 32 bit of timestamp
- *	\param	 TimeStampLow	 The lower 32 bit of timestamp
- *	\param	 Rssi			 The receiving RSSI strength
- *	\param	 MsgLen 		 The length of the message
- *	\param	*Msg			 The message pointer
- *	\return  TRUE if everything ok, FALSE otherwise (like Queue Full)
- *	\pre
- *	\post
-
- IRQL = DISPATCH_LEVEL
-
- */
-BOOLEAN MlmeEnqueueForRecv(
-	IN	PRTMP_ADAPTER	pAd,
-	IN ULONG Wcid,
-	IN ULONG TimeStampHigh,
-	IN ULONG TimeStampLow,
-	IN UCHAR Rssi0,
-	IN UCHAR Rssi1,
-	IN UCHAR Rssi2,
-	IN ULONG MsgLen,
-	IN VOID *Msg,
-	IN UCHAR Signal)
-{
-	INT 		 Tail, Machine;
-	PFRAME_802_11 pFrame = (PFRAME_802_11)Msg;
-	INT		 MsgType;
-	MLME_QUEUE	*Queue = (MLME_QUEUE *)&pAd->Mlme.Queue;
-
-#ifdef RALINK_ATE
-	/* Nothing to do in ATE mode */
-	if(ATE_ON(pAd))
-		return FALSE;
-#endif // RALINK_ATE //
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-	{
-		DBGPRINT_ERR(("MlmeEnqueueForRecv: fRTMP_ADAPTER_HALT_IN_PROGRESS\n"));
-		return FALSE;
-	}
-
-	// First check the size, it MUST not exceed the mlme queue size
-	if (MsgLen > MGMT_DMA_BUFFER_SIZE)
-	{
-		DBGPRINT_ERR(("MlmeEnqueueForRecv: frame too large, size = %ld \n", MsgLen));
-		return FALSE;
-	}
-
-	if (MlmeQueueFull(Queue))
-	{
-		return FALSE;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (!MsgTypeSubst(pAd, pFrame, &Machine, &MsgType))
-		{
-			DBGPRINT_ERR(("MlmeEnqueueForRecv: un-recongnized mgmt->subtype=%d\n",pFrame->Hdr.FC.SubType));
-			return FALSE;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// OK, we got all the informations, it is time to put things into queue
-	NdisAcquireSpinLock(&(Queue->Lock));
-	Tail = Queue->Tail;
-	Queue->Tail++;
-	Queue->Num++;
-	if (Queue->Tail == MAX_LEN_OF_MLME_QUEUE)
-	{
-		Queue->Tail = 0;
-	}
-	Queue->Entry[Tail].Occupied = TRUE;
-	Queue->Entry[Tail].Machine = Machine;
-	Queue->Entry[Tail].MsgType = MsgType;
-	Queue->Entry[Tail].MsgLen  = MsgLen;
-	Queue->Entry[Tail].TimeStamp.u.LowPart = TimeStampLow;
-	Queue->Entry[Tail].TimeStamp.u.HighPart = TimeStampHigh;
-	Queue->Entry[Tail].Rssi0 = Rssi0;
-	Queue->Entry[Tail].Rssi1 = Rssi1;
-	Queue->Entry[Tail].Rssi2 = Rssi2;
-	Queue->Entry[Tail].Signal = Signal;
-	Queue->Entry[Tail].Wcid = (UCHAR)Wcid;
-
-	Queue->Entry[Tail].Channel = pAd->LatchRfRegs.Channel;
-
-	if (Msg != NULL)
-	{
-		NdisMoveMemory(Queue->Entry[Tail].Msg, Msg, MsgLen);
-	}
-
-	NdisReleaseSpinLock(&(Queue->Lock));
-
-	RT28XX_MLME_HANDLER(pAd);
-
-	return TRUE;
-}
-
-
-/*! \brief	 Dequeue a message from the MLME Queue
- *	\param	*Queue	  The MLME Queue
- *	\param	*Elem	  The message dequeued from MLME Queue
- *	\return  TRUE if the Elem contains something, FALSE otherwise
- *	\pre
- *	\post
-
- IRQL = DISPATCH_LEVEL
-
- */
-BOOLEAN MlmeDequeue(
-	IN MLME_QUEUE *Queue,
-	OUT MLME_QUEUE_ELEM **Elem)
-{
-	NdisAcquireSpinLock(&(Queue->Lock));
-	*Elem = &(Queue->Entry[Queue->Head]);
-	Queue->Num--;
-	Queue->Head++;
-	if (Queue->Head == MAX_LEN_OF_MLME_QUEUE)
-	{
-		Queue->Head = 0;
-	}
-	NdisReleaseSpinLock(&(Queue->Lock));
-	return TRUE;
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID	MlmeRestartStateMachine(
-	IN	PRTMP_ADAPTER	pAd)
-{
-#ifdef CONFIG_STA_SUPPORT
-	BOOLEAN				Cancelled;
-#endif // CONFIG_STA_SUPPORT //
-
-	DBGPRINT(RT_DEBUG_TRACE, ("MlmeRestartStateMachine \n"));
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-#ifdef QOS_DLS_SUPPORT
-		UCHAR i;
-#endif // QOS_DLS_SUPPORT //
-		// Cancel all timer events
-		// Be careful to cancel new added timer
-		RTMPCancelTimer(&pAd->MlmeAux.AssocTimer,	  &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer,   &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer,  &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.AuthTimer,	   &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer,	   &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer,	   &Cancelled);
-
-#ifdef QOS_DLS_SUPPORT
-		for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &Cancelled);
-		}
-#endif // QOS_DLS_SUPPORT //
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Change back to original channel in case of doing scan
-	AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-	AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-
-	// Resume MSDU which is turned off durning scan
-	RTMPResumeMsduTransmission(pAd);
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Set all state machines back IDLE
-		pAd->Mlme.CntlMachine.CurrState    = CNTL_IDLE;
-		pAd->Mlme.AssocMachine.CurrState   = ASSOC_IDLE;
-		pAd->Mlme.AuthMachine.CurrState    = AUTH_REQ_IDLE;
-		pAd->Mlme.AuthRspMachine.CurrState = AUTH_RSP_IDLE;
-		pAd->Mlme.SyncMachine.CurrState    = SYNC_IDLE;
-		pAd->Mlme.ActMachine.CurrState    = ACT_IDLE;
-#ifdef QOS_DLS_SUPPORT
-		pAd->Mlme.DlsMachine.CurrState    = DLS_IDLE;
-#endif // QOS_DLS_SUPPORT //
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-}
-
-/*! \brief	test if the MLME Queue is empty
- *	\param	*Queue	  The MLME Queue
- *	\return TRUE if the Queue is empty, FALSE otherwise
- *	\pre
- *	\post
-
- IRQL = DISPATCH_LEVEL
-
- */
-BOOLEAN MlmeQueueEmpty(
-	IN MLME_QUEUE *Queue)
-{
-	BOOLEAN Ans;
-
-	NdisAcquireSpinLock(&(Queue->Lock));
-	Ans = (Queue->Num == 0);
-	NdisReleaseSpinLock(&(Queue->Lock));
-
-	return Ans;
-}
-
-/*! \brief	 test if the MLME Queue is full
- *	\param	 *Queue 	 The MLME Queue
- *	\return  TRUE if the Queue is empty, FALSE otherwise
- *	\pre
- *	\post
-
- IRQL = PASSIVE_LEVEL
- IRQL = DISPATCH_LEVEL
-
- */
-BOOLEAN MlmeQueueFull(
-	IN MLME_QUEUE *Queue)
-{
-	BOOLEAN Ans;
-
-	NdisAcquireSpinLock(&(Queue->Lock));
-	Ans = (Queue->Num == MAX_LEN_OF_MLME_QUEUE || Queue->Entry[Queue->Tail].Occupied);
-	NdisReleaseSpinLock(&(Queue->Lock));
-
-	return Ans;
-}
-
-/*! \brief	 The destructor of MLME Queue
- *	\param
- *	\return
- *	\pre
- *	\post
- *	\note	Clear Mlme Queue, Set Queue->Num to Zero.
-
- IRQL = PASSIVE_LEVEL
-
- */
-VOID MlmeQueueDestroy(
-	IN MLME_QUEUE *pQueue)
-{
-	NdisAcquireSpinLock(&(pQueue->Lock));
-	pQueue->Num  = 0;
-	pQueue->Head = 0;
-	pQueue->Tail = 0;
-	NdisReleaseSpinLock(&(pQueue->Lock));
-	NdisFreeSpinLock(&(pQueue->Lock));
-}
-
-/*! \brief	 To substitute the message type if the message is coming from external
- *	\param	pFrame		   The frame received
- *	\param	*Machine	   The state machine
- *	\param	*MsgType	   the message type for the state machine
- *	\return TRUE if the substitution is successful, FALSE otherwise
- *	\pre
- *	\post
-
- IRQL = DISPATCH_LEVEL
-
- */
-#ifdef CONFIG_STA_SUPPORT
-BOOLEAN MsgTypeSubst(
-	IN PRTMP_ADAPTER  pAd,
-	IN PFRAME_802_11 pFrame,
-	OUT INT *Machine,
-	OUT INT *MsgType)
-{
-	USHORT	Seq;
-	UCHAR	EAPType;
-	PUCHAR	pData;
-
-	// Pointer to start of data frames including SNAP header
-	pData = (PUCHAR) pFrame + LENGTH_802_11;
-
-	// The only data type will pass to this function is EAPOL frame
-	if (pFrame->Hdr.FC.Type == BTYPE_DATA)
-	{
-		if (NdisEqualMemory(SNAP_AIRONET, pData, LENGTH_802_1_H))
-		{
-			// Cisco Aironet SNAP header
-			*Machine = AIRONET_STATE_MACHINE;
-			*MsgType = MT2_AIRONET_MSG;
-			return (TRUE);
-		}
-#ifdef LEAP_SUPPORT
-		if ( pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP ) //LEAP
-		{
-			// LEAP frames
-			*Machine = LEAP_STATE_MACHINE;
-			EAPType = *((UCHAR*)pFrame + LENGTH_802_11 + LENGTH_802_1_H + 1);
-			return (LeapMsgTypeSubst(EAPType, MsgType));
-		}
-		else
-#endif // LEAP_SUPPORT //
-		{
-			*Machine = WPA_PSK_STATE_MACHINE;
-			EAPType = *((UCHAR*)pFrame + LENGTH_802_11 + LENGTH_802_1_H + 1);
-			return(WpaMsgTypeSubst(EAPType, MsgType));
-		}
-	}
-
-	switch (pFrame->Hdr.FC.SubType)
-	{
-		case SUBTYPE_ASSOC_REQ:
-			*Machine = ASSOC_STATE_MACHINE;
-			*MsgType = MT2_PEER_ASSOC_REQ;
-			break;
-		case SUBTYPE_ASSOC_RSP:
-			*Machine = ASSOC_STATE_MACHINE;
-			*MsgType = MT2_PEER_ASSOC_RSP;
-			break;
-		case SUBTYPE_REASSOC_REQ:
-			*Machine = ASSOC_STATE_MACHINE;
-			*MsgType = MT2_PEER_REASSOC_REQ;
-			break;
-		case SUBTYPE_REASSOC_RSP:
-			*Machine = ASSOC_STATE_MACHINE;
-			*MsgType = MT2_PEER_REASSOC_RSP;
-			break;
-		case SUBTYPE_PROBE_REQ:
-			*Machine = SYNC_STATE_MACHINE;
-			*MsgType = MT2_PEER_PROBE_REQ;
-			break;
-		case SUBTYPE_PROBE_RSP:
-			*Machine = SYNC_STATE_MACHINE;
-			*MsgType = MT2_PEER_PROBE_RSP;
-			break;
-		case SUBTYPE_BEACON:
-			*Machine = SYNC_STATE_MACHINE;
-			*MsgType = MT2_PEER_BEACON;
-			break;
-		case SUBTYPE_ATIM:
-			*Machine = SYNC_STATE_MACHINE;
-			*MsgType = MT2_PEER_ATIM;
-			break;
-		case SUBTYPE_DISASSOC:
-			*Machine = ASSOC_STATE_MACHINE;
-			*MsgType = MT2_PEER_DISASSOC_REQ;
-			break;
-		case SUBTYPE_AUTH:
-			// get the sequence number from payload 24 Mac Header + 2 bytes algorithm
-			NdisMoveMemory(&Seq, &pFrame->Octet[2], sizeof(USHORT));
-			if (Seq == 1 || Seq == 3)
-			{
-				*Machine = AUTH_RSP_STATE_MACHINE;
-				*MsgType = MT2_PEER_AUTH_ODD;
-			}
-			else if (Seq == 2 || Seq == 4)
-			{
-				*Machine = AUTH_STATE_MACHINE;
-				*MsgType = MT2_PEER_AUTH_EVEN;
-			}
-			else
-			{
-				return FALSE;
-			}
-			break;
-		case SUBTYPE_DEAUTH:
-			*Machine = AUTH_RSP_STATE_MACHINE;
-			*MsgType = MT2_PEER_DEAUTH;
-			break;
-		case SUBTYPE_ACTION:
-			*Machine = ACTION_STATE_MACHINE;
-			//  Sometimes Sta will return with category bytes with MSB = 1, if they receive catogory out of their support
-			if ((pFrame->Octet[0]&0x7F) > MAX_PEER_CATE_MSG)
-			{
-				*MsgType = MT2_ACT_INVALID;
-			}
-			else
-			{
-				*MsgType = (pFrame->Octet[0]&0x7F);
-			}
-			break;
-		default:
-			return FALSE;
-			break;
-	}
-
-	return TRUE;
-}
-#endif // CONFIG_STA_SUPPORT //
-
-// ===========================================================================================
-// state_machine.c
-// ===========================================================================================
-
-/*! \brief Initialize the state machine.
- *	\param *S			pointer to the state machine
- *	\param	Trans		State machine transition function
- *	\param	StNr		number of states
- *	\param	MsgNr		number of messages
- *	\param	DefFunc 	default function, when there is invalid state/message combination
- *	\param	InitState	initial state of the state machine
- *	\param	Base		StateMachine base, internal use only
- *	\pre p_sm should be a legal pointer
- *	\post
-
- IRQL = PASSIVE_LEVEL
-
- */
-VOID StateMachineInit(
-	IN STATE_MACHINE *S,
-	IN STATE_MACHINE_FUNC Trans[],
-	IN ULONG StNr,
-	IN ULONG MsgNr,
-	IN STATE_MACHINE_FUNC DefFunc,
-	IN ULONG InitState,
-	IN ULONG Base)
-{
-	ULONG i, j;
-
-	// set number of states and messages
-	S->NrState = StNr;
-	S->NrMsg   = MsgNr;
-	S->Base    = Base;
-
-	S->TransFunc  = Trans;
-
-	// init all state transition to default function
-	for (i = 0; i < StNr; i++)
-	{
-		for (j = 0; j < MsgNr; j++)
-		{
-			S->TransFunc[i * MsgNr + j] = DefFunc;
-		}
-	}
-
-	// set the starting state
-	S->CurrState = InitState;
-}
-
-/*! \brief This function fills in the function pointer into the cell in the state machine
- *	\param *S	pointer to the state machine
- *	\param St	state
- *	\param Msg	incoming message
- *	\param f	the function to be executed when (state, message) combination occurs at the state machine
- *	\pre *S should be a legal pointer to the state machine, st, msg, should be all within the range, Base should be set in the initial state
- *	\post
-
- IRQL = PASSIVE_LEVEL
-
- */
-VOID StateMachineSetAction(
-	IN STATE_MACHINE *S,
-	IN ULONG St,
-	IN ULONG Msg,
-	IN STATE_MACHINE_FUNC Func)
-{
-	ULONG MsgIdx;
-
-	MsgIdx = Msg - S->Base;
-
-	if (St < S->NrState && MsgIdx < S->NrMsg)
-	{
-		// boundary checking before setting the action
-		S->TransFunc[St * S->NrMsg + MsgIdx] = Func;
-	}
-}
-
-/*! \brief	 This function does the state transition
- *	\param	 *Adapter the NIC adapter pointer
- *	\param	 *S 	  the state machine
- *	\param	 *Elem	  the message to be executed
- *	\return   None
-
- IRQL = DISPATCH_LEVEL
-
- */
-VOID StateMachinePerformAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN STATE_MACHINE *S,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	(*(S->TransFunc[S->CurrState * S->NrMsg + Elem->MsgType - S->Base]))(pAd, Elem);
-}
-
-/*
-	==========================================================================
-	Description:
-		The drop function, when machine executes this, the message is simply
-		ignored. This function does nothing, the message is freed in
-		StateMachinePerformAction()
-	==========================================================================
- */
-VOID Drop(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-}
-
-// ===========================================================================================
-// lfsr.c
-// ===========================================================================================
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
- */
-VOID LfsrInit(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG Seed)
-{
-	if (Seed == 0)
-		pAd->Mlme.ShiftReg = 1;
-	else
-		pAd->Mlme.ShiftReg = Seed;
-}
-
-/*
-	==========================================================================
-	Description:
-	==========================================================================
- */
-UCHAR RandomByte(
-	IN PRTMP_ADAPTER pAd)
-{
-	ULONG i;
-	UCHAR R, Result;
-
-	R = 0;
-
-	if (pAd->Mlme.ShiftReg == 0)
-	NdisGetSystemUpTime((ULONG *)&pAd->Mlme.ShiftReg);
-
-	for (i = 0; i < 8; i++)
-	{
-		if (pAd->Mlme.ShiftReg & 0x00000001)
-		{
-			pAd->Mlme.ShiftReg = ((pAd->Mlme.ShiftReg ^ LFSR_MASK) >> 1) | 0x80000000;
-			Result = 1;
-		}
-		else
-		{
-			pAd->Mlme.ShiftReg = pAd->Mlme.ShiftReg >> 1;
-			Result = 0;
-		}
-		R = (R << 1) | Result;
-	}
-
-	return R;
-}
-
-VOID AsicUpdateAutoFallBackTable(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pRateTable)
-{
-	UCHAR					i;
-	HT_FBK_CFG0_STRUC		HtCfg0;
-	HT_FBK_CFG1_STRUC		HtCfg1;
-	LG_FBK_CFG0_STRUC		LgCfg0;
-	LG_FBK_CFG1_STRUC		LgCfg1;
-	PRTMP_TX_RATE_SWITCH	pCurrTxRate, pNextTxRate;
-
-	// set to initial value
-	HtCfg0.word = 0x65432100;
-	HtCfg1.word = 0xedcba988;
-	LgCfg0.word = 0xedcba988;
-	LgCfg1.word = 0x00002100;
-
-	pNextTxRate = (PRTMP_TX_RATE_SWITCH)pRateTable+1;
-	for (i = 1; i < *((PUCHAR) pRateTable); i++)
-	{
-		pCurrTxRate = (PRTMP_TX_RATE_SWITCH)pRateTable+1+i;
-		switch (pCurrTxRate->Mode)
-		{
-			case 0:		//CCK
-				break;
-			case 1:		//OFDM
-				{
-					switch(pCurrTxRate->CurrMCS)
-					{
-						case 0:
-							LgCfg0.field.OFDMMCS0FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 1:
-							LgCfg0.field.OFDMMCS1FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 2:
-							LgCfg0.field.OFDMMCS2FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 3:
-							LgCfg0.field.OFDMMCS3FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 4:
-							LgCfg0.field.OFDMMCS4FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 5:
-							LgCfg0.field.OFDMMCS5FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 6:
-							LgCfg0.field.OFDMMCS6FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 7:
-							LgCfg0.field.OFDMMCS7FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-					}
-				}
-				break;
-#ifdef DOT11_N_SUPPORT
-			case 2:		//HT-MIX
-			case 3:		//HT-GF
-				{
-					if ((pNextTxRate->Mode >= MODE_HTMIX) && (pCurrTxRate->CurrMCS != pNextTxRate->CurrMCS))
-					{
-						switch(pCurrTxRate->CurrMCS)
-						{
-							case 0:
-								HtCfg0.field.HTMCS0FBK = pNextTxRate->CurrMCS;
-								break;
-							case 1:
-								HtCfg0.field.HTMCS1FBK = pNextTxRate->CurrMCS;
-								break;
-							case 2:
-								HtCfg0.field.HTMCS2FBK = pNextTxRate->CurrMCS;
-								break;
-							case 3:
-								HtCfg0.field.HTMCS3FBK = pNextTxRate->CurrMCS;
-								break;
-							case 4:
-								HtCfg0.field.HTMCS4FBK = pNextTxRate->CurrMCS;
-								break;
-							case 5:
-								HtCfg0.field.HTMCS5FBK = pNextTxRate->CurrMCS;
-								break;
-							case 6:
-								HtCfg0.field.HTMCS6FBK = pNextTxRate->CurrMCS;
-								break;
-							case 7:
-								HtCfg0.field.HTMCS7FBK = pNextTxRate->CurrMCS;
-								break;
-							case 8:
-								HtCfg1.field.HTMCS8FBK = pNextTxRate->CurrMCS;
-								break;
-							case 9:
-								HtCfg1.field.HTMCS9FBK = pNextTxRate->CurrMCS;
-								break;
-							case 10:
-								HtCfg1.field.HTMCS10FBK = pNextTxRate->CurrMCS;
-								break;
-							case 11:
-								HtCfg1.field.HTMCS11FBK = pNextTxRate->CurrMCS;
-								break;
-							case 12:
-								HtCfg1.field.HTMCS12FBK = pNextTxRate->CurrMCS;
-								break;
-							case 13:
-								HtCfg1.field.HTMCS13FBK = pNextTxRate->CurrMCS;
-								break;
-							case 14:
-								HtCfg1.field.HTMCS14FBK = pNextTxRate->CurrMCS;
-								break;
-							case 15:
-								HtCfg1.field.HTMCS15FBK = pNextTxRate->CurrMCS;
-								break;
-							default:
-								DBGPRINT(RT_DEBUG_ERROR, ("AsicUpdateAutoFallBackTable: not support CurrMCS=%d\n", pCurrTxRate->CurrMCS));
-						}
-					}
-				}
-				break;
-#endif // DOT11_N_SUPPORT //
-		}
-
-		pNextTxRate = pCurrTxRate;
-	}
-
-	RTMP_IO_WRITE32(pAd, HT_FBK_CFG0, HtCfg0.word);
-	RTMP_IO_WRITE32(pAd, HT_FBK_CFG1, HtCfg1.word);
-	RTMP_IO_WRITE32(pAd, LG_FBK_CFG0, LgCfg0.word);
-	RTMP_IO_WRITE32(pAd, LG_FBK_CFG1, LgCfg1.word);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Set MAC register value according operation mode.
-		OperationMode AND bNonGFExist are for MM and GF Proteciton.
-		If MM or GF mask is not set, those passing argument doesn't not take effect.
-
-		Operation mode meaning:
-		= 0 : Pure HT, no preotection.
-		= 0x01; there may be non-HT devices in both the control and extension channel, protection is optional in BSS.
-		= 0x10: No Transmission in 40M is protected.
-		= 0x11: Transmission in both 40M and 20M shall be protected
-		if (bNonGFExist)
-			we should choose not to use GF. But still set correct ASIC registers.
-	========================================================================
-*/
-VOID 	AsicUpdateProtect(
-	IN		PRTMP_ADAPTER	pAd,
-	IN 		USHORT			OperationMode,
-	IN 		UCHAR			SetMask,
-	IN		BOOLEAN			bDisableBGProtect,
-	IN		BOOLEAN			bNonGFExist)
-{
-	PROT_CFG_STRUC	ProtCfg, ProtCfg4;
-	UINT32 Protect[6];
-	USHORT			offset;
-	UCHAR			i;
-	UINT32 MacReg = 0;
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-#ifdef DOT11_N_SUPPORT
-	if (!(pAd->CommonCfg.bHTProtect) && (OperationMode != 8))
-	{
-		return;
-	}
-
-	if (pAd->BATable.numAsOriginator)
-	{
-		//
-		// enable the RTS/CTS to avoid channel collision
-		//
-		SetMask = ALLN_SETPROTECT;
-		OperationMode = 8;
-	}
-#endif // DOT11_N_SUPPORT //
-
-	// Config ASIC RTS threshold register
-	RTMP_IO_READ32(pAd, TX_RTS_CFG, &MacReg);
-	MacReg &= 0xFF0000FF;
-#if 0
-	MacReg |= (pAd->CommonCfg.RtsThreshold << 8);
-#else
-	// If the user want disable RtsThreshold and enable Amsdu/Ralink-Aggregation, set the RtsThreshold as 4096
-        if ((
-#ifdef DOT11_N_SUPPORT
-			(pAd->CommonCfg.BACapability.field.AmsduEnable) ||
-#endif // DOT11_N_SUPPORT //
-			(pAd->CommonCfg.bAggregationCapable == TRUE))
-            && pAd->CommonCfg.RtsThreshold == MAX_RTS_THRESHOLD)
-        {
-			MacReg |= (0x1000 << 8);
-        }
-        else
-        {
-			MacReg |= (pAd->CommonCfg.RtsThreshold << 8);
-        }
-#endif
-
-	RTMP_IO_WRITE32(pAd, TX_RTS_CFG, MacReg);
-
-	// Initial common protection settings
-	RTMPZeroMemory(Protect, sizeof(Protect));
-	ProtCfg4.word = 0;
-	ProtCfg.word = 0;
-	ProtCfg.field.TxopAllowGF40 = 1;
-	ProtCfg.field.TxopAllowGF20 = 1;
-	ProtCfg.field.TxopAllowMM40 = 1;
-	ProtCfg.field.TxopAllowMM20 = 1;
-	ProtCfg.field.TxopAllowOfdm = 1;
-	ProtCfg.field.TxopAllowCck = 1;
-	ProtCfg.field.RTSThEn = 1;
-	ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
-
-	// update PHY mode and rate
-	if (pAd->CommonCfg.Channel > 14)
-		ProtCfg.field.ProtectRate = 0x4000;
-	ProtCfg.field.ProtectRate |= pAd->CommonCfg.RtsRate;
-
-	// Handle legacy(B/G) protection
-	if (bDisableBGProtect)
-	{
-		//ProtCfg.field.ProtectRate = pAd->CommonCfg.RtsRate;
-		ProtCfg.field.ProtectCtrl = 0;
-		Protect[0] = ProtCfg.word;
-		Protect[1] = ProtCfg.word;
-	}
-	else
-	{
-		//ProtCfg.field.ProtectRate = pAd->CommonCfg.RtsRate;
-		ProtCfg.field.ProtectCtrl = 0;			// CCK do not need to be protected
-		Protect[0] = ProtCfg.word;
-		ProtCfg.field.ProtectCtrl = ASIC_CTS;	// OFDM needs using CCK to protect
-		Protect[1] = ProtCfg.word;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	// Decide HT frame protection.
-	if ((SetMask & ALLN_SETPROTECT) != 0)
-	{
-		switch(OperationMode)
-		{
-			case 0x0:
-				// NO PROTECT
-				// 1.All STAs in the BSS are 20/40 MHz HT
-				// 2. in ai 20/40MHz BSS
-				// 3. all STAs are 20MHz in a 20MHz BSS
-				// Pure HT. no protection.
-
-				// MM20_PROT_CFG
-				//	Reserved (31:27)
-				// 	PROT_TXOP(25:20) -- 010111
-				//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-				//  PROT_CTRL(17:16) -- 00 (None)
-				// 	PROT_RATE(15:0)  -- 0x4004 (OFDM 24M)
-				Protect[2] = 0x01744004;
-
-				// MM40_PROT_CFG
-				//	Reserved (31:27)
-				// 	PROT_TXOP(25:20) -- 111111
-				//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-				//  PROT_CTRL(17:16) -- 00 (None)
-				// 	PROT_RATE(15:0)  -- 0x4084 (duplicate OFDM 24M)
-				Protect[3] = 0x03f44084;
-
-				// CF20_PROT_CFG
-				//	Reserved (31:27)
-				// 	PROT_TXOP(25:20) -- 010111
-				//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-				//  PROT_CTRL(17:16) -- 00 (None)
-				// 	PROT_RATE(15:0)  -- 0x4004 (OFDM 24M)
-				Protect[4] = 0x01744004;
-
-				// CF40_PROT_CFG
-				//	Reserved (31:27)
-				// 	PROT_TXOP(25:20) -- 111111
-				//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-				//  PROT_CTRL(17:16) -- 00 (None)
-				// 	PROT_RATE(15:0)  -- 0x4084 (duplicate OFDM 24M)
-				Protect[5] = 0x03f44084;
-
-				if (bNonGFExist)
-				{
-					// PROT_NAV(19:18)  -- 01 (Short NAV protectiion)
-					// PROT_CTRL(17:16) -- 01 (RTS/CTS)
-					Protect[4] = 0x01754004;
-					Protect[5] = 0x03f54084;
-				}
-				pAd->CommonCfg.IOTestParm.bRTSLongProtOn = FALSE;
-				break;
-
- 			case 1:
-				// This is "HT non-member protection mode."
-				// If there may be non-HT STAs my BSS
-				ProtCfg.word = 0x01744004;	// PROT_CTRL(17:16) : 0 (None)
-				ProtCfg4.word = 0x03f44084; // duplicaet legacy 24M. BW set 1.
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED))
-				{
-					ProtCfg.word = 0x01740003;	//ERP use Protection bit is set, use protection rate at Clause 18..
-					ProtCfg4.word = 0x03f40003; // Don't duplicate RTS/CTS in CCK mode. 0x03f40083;
-				}
-				//Assign Protection method for 20&40 MHz packets
-				ProtCfg.field.ProtectCtrl = ASIC_RTS;
-				ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
-				ProtCfg4.field.ProtectCtrl = ASIC_RTS;
-				ProtCfg4.field.ProtectNav = ASIC_SHORTNAV;
-				Protect[2] = ProtCfg.word;
-				Protect[3] = ProtCfg4.word;
-				Protect[4] = ProtCfg.word;
-				Protect[5] = ProtCfg4.word;
-				pAd->CommonCfg.IOTestParm.bRTSLongProtOn = TRUE;
-				break;
-
-			case 2:
-				// If only HT STAs are in BSS. at least one is 20MHz. Only protect 40MHz packets
-				ProtCfg.word = 0x01744004;  // PROT_CTRL(17:16) : 0 (None)
-				ProtCfg4.word = 0x03f44084; // duplicaet legacy 24M. BW set 1.
-
-				//Assign Protection method for 40MHz packets
-				ProtCfg4.field.ProtectCtrl = ASIC_RTS;
-				ProtCfg4.field.ProtectNav = ASIC_SHORTNAV;
-				Protect[2] = ProtCfg.word;
-				Protect[3] = ProtCfg4.word;
-				if (bNonGFExist)
-				{
-					ProtCfg.field.ProtectCtrl = ASIC_RTS;
-					ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
-				}
-				Protect[4] = ProtCfg.word;
-				Protect[5] = ProtCfg4.word;
-
-				pAd->CommonCfg.IOTestParm.bRTSLongProtOn = FALSE;
-				break;
-
-			case 3:
-				// HT mixed mode.	 PROTECT ALL!
-				// Assign Rate
-				ProtCfg.word = 0x01744004;	//duplicaet legacy 24M. BW set 1.
-				ProtCfg4.word = 0x03f44084;
-				// both 20MHz and 40MHz are protected. Whether use RTS or CTS-to-self depends on the
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED))
-				{
-					ProtCfg.word = 0x01740003;	//ERP use Protection bit is set, use protection rate at Clause 18..
-					ProtCfg4.word = 0x03f40003; // Don't duplicate RTS/CTS in CCK mode. 0x03f40083
-				}
-				//Assign Protection method for 20&40 MHz packets
-				ProtCfg.field.ProtectCtrl = ASIC_RTS;
-				ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
-				ProtCfg4.field.ProtectCtrl = ASIC_RTS;
-				ProtCfg4.field.ProtectNav = ASIC_SHORTNAV;
-				Protect[2] = ProtCfg.word;
-				Protect[3] = ProtCfg4.word;
-				Protect[4] = ProtCfg.word;
-				Protect[5] = ProtCfg4.word;
-				pAd->CommonCfg.IOTestParm.bRTSLongProtOn = TRUE;
-				break;
-
-			case 8:
-				// Special on for Atheros problem n chip.
-				Protect[2] = 0x01754004;
-				Protect[3] = 0x03f54084;
-				Protect[4] = 0x01754004;
-				Protect[5] = 0x03f54084;
-				pAd->CommonCfg.IOTestParm.bRTSLongProtOn = TRUE;
-				break;
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-	offset = CCK_PROT_CFG;
-	for (i = 0;i < 6;i++)
-	{
-		if ((SetMask & (1<< i)))
-		{
-			RTMP_IO_WRITE32(pAd, offset + i*4, Protect[i]);
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicSwitchChannel(
-					  IN PRTMP_ADAPTER pAd,
-	IN	UCHAR			Channel,
-	IN	BOOLEAN			bScan)
-{
-	ULONG			R2 = 0, R3 = DEFAULT_RF_TX_POWER, R4 = 0;
-	CHAR    TxPwer = 0, TxPwer2 = DEFAULT_RF_TX_POWER; //Bbp94 = BBPR94_DEFAULT, TxPwer2 = DEFAULT_RF_TX_POWER;
-	UCHAR	index;
-	UINT32 	Value = 0; //BbpReg, Value;
-	RTMP_RF_REGS *RFRegTable;
-
-	// Search Tx power value
-	for (index = 0; index < pAd->ChannelListNum; index++)
-	{
-		if (Channel == pAd->ChannelList[index].Channel)
-		{
-			TxPwer = pAd->ChannelList[index].Power;
-			TxPwer2 = pAd->ChannelList[index].Power2;
-			break;
-		}
-	}
-
-	if (index == MAX_NUM_OF_CHANNELS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("AsicSwitchChannel: Cant find the Channel#%d \n", Channel));
-	}
-
-#ifdef RT2870
-	// The RF programming sequence is difference between 3xxx and 2xxx
-	if (IS_RT3070(pAd) && ((pAd->RfIcType == RFIC_3020) || (pAd->RfIcType == RFIC_2020)))
-	{
-		/* modify by WY for Read RF Reg. error */
-		UCHAR RFValue;
-
-		for (index = 0; index < NUM_OF_3020_CHNL; index++)
-		{
-			if (Channel == FreqItems3020[index].Channel)
-			{
-				// Programming channel parameters
-				RT30xxWriteRFRegister(pAd, RF_R02, FreqItems3020[index].N);
-				RT30xxWriteRFRegister(pAd, RF_R03, FreqItems3020[index].K);
-
-				RT30xxReadRFRegister(pAd, RF_R06, (PUCHAR)&RFValue);
-				RFValue = (RFValue & 0xFC) | FreqItems3020[index].R;
-				RT30xxWriteRFRegister(pAd, RF_R06, (UCHAR)RFValue);
-
-				// Set Tx Power
-				RT30xxReadRFRegister(pAd, RF_R12, (PUCHAR)&RFValue);
-				RFValue = (RFValue & 0xE0) | TxPwer;
-				RT30xxWriteRFRegister(pAd, RF_R12, (UCHAR)RFValue);
-
-				// Set RF offset
-				RT30xxReadRFRegister(pAd, RF_R23, (PUCHAR)&RFValue);
-				RFValue = (RFValue & 0x80) | pAd->RfFreqOffset;
-				RT30xxWriteRFRegister(pAd, RF_R23, (UCHAR)RFValue);
-
-				// Set BW
-				if (!bScan && (pAd->CommonCfg.BBPCurrentBW == BW_40))
-				{
-					RFValue = pAd->Mlme.CaliBW40RfR24;
-					//DISABLE_11N_CHECK(pAd);
-				}
-				else
-				{
-					RFValue = pAd->Mlme.CaliBW20RfR24;
-				}
-				RT30xxWriteRFRegister(pAd, RF_R24, (UCHAR)RFValue);
-
-				// Enable RF tuning
-				RT30xxReadRFRegister(pAd, RF_R07, (PUCHAR)&RFValue);
-				RFValue = RFValue | 0x1;
-				RT30xxWriteRFRegister(pAd, RF_R07, (UCHAR)RFValue);
-
-				// latch channel for future usage.
-				pAd->LatchRfRegs.Channel = Channel;
-
-				break;
-			}
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%d, Pwr1=%d, %dT), N=0x%02X, K=0x%02X, R=0x%02X\n",
-			Channel,
-			pAd->RfIcType,
-			TxPwer,
-			TxPwer2,
-			pAd->Antenna.field.TxPath,
-			FreqItems3020[index].N,
-			FreqItems3020[index].K,
-			FreqItems3020[index].R));
-	}
-	else
-#endif // RT2870 //
-	{
-		RFRegTable = RF2850RegTable;
-
-		switch (pAd->RfIcType)
-		{
-			case RFIC_2820:
-			case RFIC_2850:
-			case RFIC_2720:
-			case RFIC_2750:
-
-			for (index = 0; index < NUM_OF_2850_CHNL; index++)
-			{
-				if (Channel == RFRegTable[index].Channel)
-				{
-					R2 = RFRegTable[index].R2;
-					if (pAd->Antenna.field.TxPath == 1)
-					{
-						R2 |= 0x4000;	// If TXpath is 1, bit 14 = 1;
-					}
-
-					if (pAd->Antenna.field.RxPath == 2)
-					{
-						R2 |= 0x40;	// write 1 to off Rxpath.
-					}
-					else if (pAd->Antenna.field.RxPath == 1)
-					{
-						R2 |= 0x20040;	// write 1 to off RxPath
-					}
-
-					if (Channel > 14)
-					{
-						// initialize R3, R4
-						R3 = (RFRegTable[index].R3 & 0xffffc1ff);
-						R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->RfFreqOffset << 15);
-
-						// 5G band power range: 0xF9~0X0F, TX0 Reg3 bit9/TX1 Reg4 bit6="0" means the TX power reduce 7dB
-						// R3
-						if ((TxPwer >= -7) && (TxPwer < 0))
-						{
-							TxPwer = (7+TxPwer);
-							TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
-							R3 |= (TxPwer << 10);
-							DBGPRINT(RT_DEBUG_ERROR, ("AsicSwitchChannel: TxPwer=%d \n", TxPwer));
-						}
-						else
-						{
-							TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
-							R3 |= (TxPwer << 10) | (1 << 9);
-						}
-
-						// R4
-						if ((TxPwer2 >= -7) && (TxPwer2 < 0))
-						{
-							TxPwer2 = (7+TxPwer2);
-							TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
-							R4 |= (TxPwer2 << 7);
-							DBGPRINT(RT_DEBUG_ERROR, ("AsicSwitchChannel: TxPwer2=%d \n", TxPwer2));
-						}
-						else
-						{
-							TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
-							R4 |= (TxPwer2 << 7) | (1 << 6);
-						}
-					}
-					else
-					{
-						R3 = (RFRegTable[index].R3 & 0xffffc1ff) | (TxPwer << 9); // set TX power0
-					R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->RfFreqOffset << 15) | (TxPwer2 <<6);// Set freq Offset & TxPwr1
-					}
-
-					// Based on BBP current mode before changing RF channel.
-					if (!bScan && (pAd->CommonCfg.BBPCurrentBW == BW_40))
-					{
-						R4 |=0x200000;
-					}
-
-					// Update variables
-					pAd->LatchRfRegs.Channel = Channel;
-					pAd->LatchRfRegs.R1 = RFRegTable[index].R1;
-					pAd->LatchRfRegs.R2 = R2;
-					pAd->LatchRfRegs.R3 = R3;
-					pAd->LatchRfRegs.R4 = R4;
-
-					// Set RF value 1's set R3[bit2] = [0]
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-					RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-					RTMPusecDelay(200);
-
-					// Set RF value 2's set R3[bit2] = [1]
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-					RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 | 0x04));
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-					RTMPusecDelay(200);
-
-					// Set RF value 3's set R3[bit2] = [0]
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-					RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-					break;
-				}
-			}
-			break;
-
-			default:
-			break;
-		}
-	}
-
-	// Change BBP setting during siwtch from a->g, g->a
-	if (Channel <= 14)
-	{
-	    ULONG	TxPinCfg = 0x00050F0A;//Gary 2007/08/09 0x050A0A
-
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0);//(0x44 - GET_LNA_GAIN(pAd)));	// According the Rory's suggestion to solve the middle range issue.
-		//RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x62);
-
-		// Rx High power VGA offset for LNA select
-	    if (pAd->NicConfig2.field.ExternalLNAForG)
-	    {
-	        RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x62);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x46);
-	    }
-	    else
-	    {
-	        RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x84);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x50);
-	    }
-
-		// 5G band selection PIN, bit1 and bit2 are complement
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		Value &= (~0x6);
-		Value |= (0x04);
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-
-        // Turn off unused PA or LNA when only 1T or 1R
-		if (pAd->Antenna.field.TxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFFFF3;
-		}
-		if (pAd->Antenna.field.RxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFF3FF;
-		}
-
-		RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
-	}
-	else
-	{
-	    ULONG	TxPinCfg = 0x00050F05;//Gary 2007/8/9 0x050505
-
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0);//(0x44 - GET_LNA_GAIN(pAd)));   // According the Rory's suggestion to solve the middle range issue.
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0xF2);
-
-		// Rx High power VGA offset for LNA select
-		if (pAd->NicConfig2.field.ExternalLNAForA)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x46);
-		}
-		else
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x50);
-		}
-
-		// 5G band selection PIN, bit1 and bit2 are complement
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		Value &= (~0x6);
-		Value |= (0x02);
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-
-        // Turn off unused PA or LNA when only 1T or 1R
-		if (pAd->Antenna.field.TxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFFFF3;
-	}
-		if (pAd->Antenna.field.RxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFF3FF;
-	}
-
-		RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
-	}
-
-    // R66 should be set according to Channel and use 20MHz when scanning
-	//RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, (0x2E + GET_LNA_GAIN(pAd)));
-	if (bScan)
-		RTMPSetAGCInitValue(pAd, BW_20);
-	else
-		RTMPSetAGCInitValue(pAd, pAd->CommonCfg.BBPCurrentBW);
-
-	//
-	// On 11A, We should delay and wait RF/BBP to be stable
-	// and the appropriate time should be 1000 micro seconds
-	// 2005/06/05 - On 11G, We also need this delay time. Otherwise it's difficult to pass the WHQL.
-	//
-	RTMPusecDelay(1000);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%lu, Pwr1=%lu, %dT) to , R1=0x%08lx, R2=0x%08lx, R3=0x%08lx, R4=0x%08lx\n",
-							  Channel,
-							  pAd->RfIcType,
-							  (R3 & 0x00003e00) >> 9,
-							  (R4 & 0x000007c0) >> 6,
-							  pAd->Antenna.field.TxPath,
-							  pAd->LatchRfRegs.R1,
-							  pAd->LatchRfRegs.R2,
-							  pAd->LatchRfRegs.R3,
-							  pAd->LatchRfRegs.R4));
-}
-
-/*
-	==========================================================================
-	Description:
-		This function is required for 2421 only, and should not be used during
-		site survey. It's only required after NIC decided to stay at a channel
-		for a longer period.
-		When this function is called, it's always after AsicSwitchChannel().
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicLockChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR Channel)
-{
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID	AsicAntennaSelect(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Channel)
-{
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Antenna miscellaneous setting.
-
-	Arguments:
-		pAd						Pointer to our adapter
-		BandState				Indicate current Band State.
-
-	Return Value:
-		None
-
-	IRQL <= DISPATCH_LEVEL
-
-	Note:
-		1.) Frame End type control
-			only valid for G only (RF_2527 & RF_2529)
-			0: means DPDT, set BBP R4 bit 5 to 1
-			1: means SPDT, set BBP R4 bit 5 to 0
-
-
-	========================================================================
-*/
-VOID	AsicAntennaSetting(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	ABGBAND_STATE	BandState)
-{
-}
-
-VOID AsicRfTuningExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-}
-
-/*
-	==========================================================================
-	Description:
-		Gives CCK TX rate 2 more dB TX power.
-		This routine works only in LINK UP in INFRASTRUCTURE mode.
-
-		calculate desired Tx power in RF R3.Tx0~5,	should consider -
-		0. if current radio is a noisy environment (pAd->DrsCounters.fNoisyEnvironment)
-		1. TxPowerPercentage
-		2. auto calibration based on TSSI feedback
-		3. extra 2 db for CCK
-		4. -10 db upon very-short distance (AvgRSSI >= -40db) to AP
-
-	NOTE: Since this routine requires the value of (pAd->DrsCounters.fNoisyEnvironment),
-		it should be called AFTER MlmeDynamicTxRatSwitching()
-	==========================================================================
- */
-VOID AsicAdjustTxPower(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT			i, j;
-	CHAR		DeltaPwr = 0;
-	BOOLEAN		bAutoTxAgc = FALSE;
-	UCHAR		TssiRef, *pTssiMinusBoundary, *pTssiPlusBoundary, TxAgcStep;
-	UCHAR		BbpR1 = 0, BbpR49 = 0, idx;
-	PCHAR		pTxAgcCompensate;
-	ULONG		TxPwr[5];
-	CHAR		Value;
-
-	if (pAd->CommonCfg.BBPCurrentBW == BW_40)
-	{
-		if (pAd->CommonCfg.CentralChannel > 14)
-		{
-			TxPwr[0] = pAd->Tx40MPwrCfgABand[0];
-			TxPwr[1] = pAd->Tx40MPwrCfgABand[1];
-			TxPwr[2] = pAd->Tx40MPwrCfgABand[2];
-			TxPwr[3] = pAd->Tx40MPwrCfgABand[3];
-			TxPwr[4] = pAd->Tx40MPwrCfgABand[4];
-		}
-		else
-		{
-			TxPwr[0] = pAd->Tx40MPwrCfgGBand[0];
-			TxPwr[1] = pAd->Tx40MPwrCfgGBand[1];
-			TxPwr[2] = pAd->Tx40MPwrCfgGBand[2];
-			TxPwr[3] = pAd->Tx40MPwrCfgGBand[3];
-			TxPwr[4] = pAd->Tx40MPwrCfgGBand[4];
-		}
-	}
-	else
-	{
-		if (pAd->CommonCfg.Channel > 14)
-		{
-			TxPwr[0] = pAd->Tx20MPwrCfgABand[0];
-			TxPwr[1] = pAd->Tx20MPwrCfgABand[1];
-			TxPwr[2] = pAd->Tx20MPwrCfgABand[2];
-			TxPwr[3] = pAd->Tx20MPwrCfgABand[3];
-			TxPwr[4] = pAd->Tx20MPwrCfgABand[4];
-		}
-		else
-		{
-			TxPwr[0] = pAd->Tx20MPwrCfgGBand[0];
-			TxPwr[1] = pAd->Tx20MPwrCfgGBand[1];
-			TxPwr[2] = pAd->Tx20MPwrCfgGBand[2];
-			TxPwr[3] = pAd->Tx20MPwrCfgGBand[3];
-			TxPwr[4] = pAd->Tx20MPwrCfgGBand[4];
-		}
-	}
-
-	// TX power compensation for temperature variation based on TSSI. try every 4 second
-	if (pAd->Mlme.OneSecPeriodicRound % 4 == 0)
-	{
-		if (pAd->CommonCfg.Channel <= 14)
-		{
-			/* bg channel */
-			bAutoTxAgc         = pAd->bAutoTxAgcG;
-			TssiRef            = pAd->TssiRefG;
-			pTssiMinusBoundary = &pAd->TssiMinusBoundaryG[0];
-			pTssiPlusBoundary  = &pAd->TssiPlusBoundaryG[0];
-			TxAgcStep          = pAd->TxAgcStepG;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateG;
-		}
-		else
-		{
-			/* a channel */
-			bAutoTxAgc         = pAd->bAutoTxAgcA;
-			TssiRef            = pAd->TssiRefA;
-			pTssiMinusBoundary = &pAd->TssiMinusBoundaryA[0];
-			pTssiPlusBoundary  = &pAd->TssiPlusBoundaryA[0];
-			TxAgcStep          = pAd->TxAgcStepA;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateA;
-		}
-
-		if (bAutoTxAgc)
-		{
-			/* BbpR1 is unsigned char */
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R49, &BbpR49);
-
-			/* (p) TssiPlusBoundaryG[0] = 0 = (m) TssiMinusBoundaryG[0] */
-			/* compensate: +4     +3   +2   +1    0   -1   -2   -3   -4 * steps */
-			/* step value is defined in pAd->TxAgcStepG for tx power value */
-
-			/* [4]+1+[4]   p4     p3   p2   p1   o1   m1   m2   m3   m4 */
-			/* ex:         0x00 0x15 0x25 0x45 0x88 0xA0 0xB5 0xD0 0xF0
-			   above value are examined in mass factory production */
-			/*             [4]    [3]  [2]  [1]  [0]  [1]  [2]  [3]  [4] */
-
-			/* plus (+) is 0x00 ~ 0x45, minus (-) is 0xa0 ~ 0xf0 */
-			/* if value is between p1 ~ o1 or o1 ~ s1, no need to adjust tx power */
-			/* if value is 0xa5, tx power will be -= TxAgcStep*(2-1) */
-
-			if (BbpR49 > pTssiMinusBoundary[1])
-			{
-				// Reading is larger than the reference value
-				// check for how large we need to decrease the Tx power
-				for (idx = 1; idx < 5; idx++)
-				{
-					if (BbpR49 <= pTssiMinusBoundary[idx])  // Found the range
-						break;
-				}
-				// The index is the step we should decrease, idx = 0 means there is nothing to compensate
-//				if (R3 > (ULONG) (TxAgcStep * (idx-1)))
-					*pTxAgcCompensate = -(TxAgcStep * (idx-1));
-//				else
-//					*pTxAgcCompensate = -((UCHAR)R3);
-
-				DeltaPwr += (*pTxAgcCompensate);
-				DBGPRINT(RT_DEBUG_TRACE, ("-- Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = -%d\n",
-					BbpR49, TssiRef, TxAgcStep, idx-1));
-			}
-			else if (BbpR49 < pTssiPlusBoundary[1])
-			{
-				// Reading is smaller than the reference value
-				// check for how large we need to increase the Tx power
-				for (idx = 1; idx < 5; idx++)
-				{
-					if (BbpR49 >= pTssiPlusBoundary[idx])   // Found the range
-						break;
-				}
-				// The index is the step we should increase, idx = 0 means there is nothing to compensate
-				*pTxAgcCompensate = TxAgcStep * (idx-1);
-				DeltaPwr += (*pTxAgcCompensate);
-				DBGPRINT(RT_DEBUG_TRACE, ("++ Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
-					BbpR49, TssiRef, TxAgcStep, idx-1));
-			}
-			else
-			{
-				*pTxAgcCompensate = 0;
-				DBGPRINT(RT_DEBUG_TRACE, ("   Tx Power, BBP R49=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
-					BbpR49, TssiRef, TxAgcStep, 0));
-			}
-		}
-	}
-	else
-	{
-		if (pAd->CommonCfg.Channel <= 14)
-		{
-			bAutoTxAgc         = pAd->bAutoTxAgcG;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateG;
-		}
-		else
-		{
-			bAutoTxAgc         = pAd->bAutoTxAgcA;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateA;
-		}
-
-		if (bAutoTxAgc)
-			DeltaPwr += (*pTxAgcCompensate);
-	}
-
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpR1);
-	BbpR1 &= 0xFC;
-
-#ifdef SINGLE_SKU
-	// Handle regulatory max tx power constrain
-	do
-	{
-		UCHAR    TxPwrInEEPROM = 0xFF, CountryTxPwr = 0xFF, criterion;
-		UCHAR    AdjustMaxTxPwr[40];
-
-		if (pAd->CommonCfg.Channel > 14) // 5G band
-			TxPwrInEEPROM = ((pAd->CommonCfg.DefineMaxTxPwr & 0xFF00) >> 8);
-		else // 2.4G band
-			TxPwrInEEPROM = (pAd->CommonCfg.DefineMaxTxPwr & 0x00FF);
-		CountryTxPwr = GetCuntryMaxTxPwr(pAd, pAd->CommonCfg.Channel);
-
-		// error handling, range check
-		if ((TxPwrInEEPROM > 0x50) || (CountryTxPwr > 0x50))
-		{
-			DBGPRINT(RT_DEBUG_ERROR,("AsicAdjustTxPower - Invalid max tx power (=0x%02x), CountryTxPwr=%d\n", TxPwrInEEPROM, CountryTxPwr));
-			break;
-		}
-
-		criterion = *((PUCHAR)TxPwr + 2) & 0xF;        // FAE use OFDM 6M as criterion
-
-		DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (criterion=%d, TxPwrInEEPROM=%d, CountryTxPwr=%d)\n", criterion, TxPwrInEEPROM, CountryTxPwr));
-
-		// Adjust max tx power according to the relationship of tx power in E2PROM
-		for (i=0; i<5; i++)
-		{
-			// CCK will have 4dBm larger than OFDM
-			// Therefore, we should separate to parse the tx power field
-			if (i == 0)
-			{
-				for (j=0; j<8; j++)
-				{
-					Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F);
-
-					if (j < 4)
-					{
-						// CCK will have 4dBm larger than OFDM
-						AdjustMaxTxPwr[i*8+j] = TxPwrInEEPROM + (Value - criterion) + 4;
-					}
-					else
-					{
-						AdjustMaxTxPwr[i*8+j] = TxPwrInEEPROM + (Value - criterion);
-					}
-					DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-				}
-			}
-			else
-			{
-				for (j=0; j<8; j++)
-				{
-					Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F);
-
-					AdjustMaxTxPwr[i*8+j] = TxPwrInEEPROM + (Value - criterion);
-					DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-				}
-			}
-		}
-
-		// Adjust tx power according to the relationship
-		for (i=0; i<5; i++)
-		{
-			if (TxPwr[i] != 0xffffffff)
-			{
-				for (j=0; j<8; j++)
-				{
-					Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F);
-
-					// The system tx power is larger than the regulatory, the power should be restrain
-					if (AdjustMaxTxPwr[i*8+j] > CountryTxPwr)
-					{
-						// decrease to zero and don't need to take care BBPR1
-						if ((Value - (AdjustMaxTxPwr[i*8+j] - CountryTxPwr)) > 0)
-							Value -= (AdjustMaxTxPwr[i*8+j] - CountryTxPwr);
-						else
-							Value = 0;
-
-						DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-					}
-					else
-						DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d, no change)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-
-						TxPwr[i] = (TxPwr[i] & ~(0x0000000F << j*4)) | (Value << j*4);
-				}
-			}
-		}
-	} while (FALSE);
-#endif // SINGLE_SKU //
-
-	/* calculate delta power based on the percentage specified from UI */
-	// E2PROM setting is calibrated for maximum TX power (i.e. 100%)
-	// We lower TX power here according to the percentage specified from UI
-	if (pAd->CommonCfg.TxPowerPercentage == 0xffffffff)       // AUTO TX POWER control
-		;
-	else if (pAd->CommonCfg.TxPowerPercentage > 90)  // 91 ~ 100% & AUTO, treat as 100% in terms of mW
-		;
-	else if (pAd->CommonCfg.TxPowerPercentage > 60)  // 61 ~ 90%, treat as 75% in terms of mW		// DeltaPwr -= 1;
-	{
-		DeltaPwr -= 1;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 30)  // 31 ~ 60%, treat as 50% in terms of mW		// DeltaPwr -= 3;
-	{
-		DeltaPwr -= 3;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 15)  // 16 ~ 30%, treat as 25% in terms of mW		// DeltaPwr -= 6;
-	{
-		BbpR1 |= 0x01;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 9)   // 10 ~ 15%, treat as 12.5% in terms of mW		// DeltaPwr -= 9;
-	{
-		BbpR1 |= 0x01;
-		DeltaPwr -= 3;
-	}
-	else                                           // 0 ~ 9 %, treat as MIN(~3%) in terms of mW		// DeltaPwr -= 12;
-	{
-		BbpR1 |= 0x02;
-	}
-
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpR1);
-
-	/* reset different new tx power for different TX rate */
-	for(i=0; i<5; i++)
-	{
-		if (TxPwr[i] != 0xffffffff)
-		{
-			for (j=0; j<8; j++)
-			{
-				Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F); /* 0 ~ 15 */
-
-				if ((Value + DeltaPwr) < 0)
-				{
-					Value = 0; /* min */
-				}
-				else if ((Value + DeltaPwr) > 0xF)
-				{
-					Value = 0xF; /* max */
-				}
-				else
-				{
-					Value += DeltaPwr; /* temperature compensation */
-				}
-
-				/* fill new value to CSR offset */
-				TxPwr[i] = (TxPwr[i] & ~(0x0000000F << j*4)) | (Value << j*4);
-			}
-
-			/* write tx power value to CSR */
-			/* TX_PWR_CFG_0 (8 tx rate) for	TX power for OFDM 12M/18M
-											TX power for OFDM 6M/9M
-											TX power for CCK5.5M/11M
-											TX power for CCK1M/2M */
-			/* TX_PWR_CFG_1 ~ TX_PWR_CFG_4 */
-			RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, TxPwr[i]);
-		}
-	}
-
-}
-
-#ifdef CONFIG_STA_SUPPORT
-/*
-	==========================================================================
-	Description:
-		put PHY to sleep here, and set next wakeup timer. PHY doesn't not wakeup
-		automatically. Instead, MCU will issue a TwakeUpInterrupt to host after
-		the wakeup timer timeout. Driver has to issue a separate command to wake
-		PHY up.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicSleepThenAutoWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT TbttNumToNextWakeUp)
-{
-    RT28XX_STA_SLEEP_THEN_AUTO_WAKEUP(pAd, TbttNumToNextWakeUp);
-}
-
-/*
-	==========================================================================
-	Description:
-		AsicForceWakeup() is used whenever manual wakeup is required
-		AsicForceSleep() should only be used when not in INFRA BSS. When
-		in INFRA BSS, we should use AsicSleepThenAutoWakeup() instead.
-	==========================================================================
- */
-VOID AsicForceSleep(
-	IN PRTMP_ADAPTER pAd)
-{
-
-}
-
-/*
-	==========================================================================
-	Description:
-		AsicForceWakeup() is used whenever Twakeup timer (set via AsicSleepThenAutoWakeup)
-		expired.
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-	==========================================================================
- */
-VOID AsicForceWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN    bFromTx)
-{
-    DBGPRINT(RT_DEBUG_TRACE, ("--> AsicForceWakeup \n"));
-    RT28XX_STA_FORCE_WAKEUP(pAd, bFromTx);
-}
-#endif // CONFIG_STA_SUPPORT //
-/*
-	==========================================================================
-	Description:
-		Set My BSSID
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicSetBssid(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pBssid)
-{
-	ULONG		  Addr4;
-	DBGPRINT(RT_DEBUG_TRACE, ("==============> AsicSetBssid %x:%x:%x:%x:%x:%x\n",
-		pBssid[0],pBssid[1],pBssid[2],pBssid[3], pBssid[4],pBssid[5]));
-
-	Addr4 = (ULONG)(pBssid[0])		 |
-			(ULONG)(pBssid[1] << 8)  |
-			(ULONG)(pBssid[2] << 16) |
-			(ULONG)(pBssid[3] << 24);
-	RTMP_IO_WRITE32(pAd, MAC_BSSID_DW0, Addr4);
-
-	Addr4 = 0;
-	// always one BSSID in STA mode
-	Addr4 = (ULONG)(pBssid[4]) | (ULONG)(pBssid[5] << 8);
-
-	RTMP_IO_WRITE32(pAd, MAC_BSSID_DW1, Addr4);
-}
-
-VOID AsicSetMcastWC(
-	IN PRTMP_ADAPTER pAd)
-{
-	MAC_TABLE_ENTRY *pEntry = &pAd->MacTab.Content[MCAST_WCID];
-	USHORT		offset;
-
-	pEntry->Sst        = SST_ASSOC;
-	pEntry->Aid        = MCAST_WCID;	// Softap supports 1 BSSID and use WCID=0 as multicast Wcid index
-	pEntry->PsMode     = PWR_ACTIVE;
-	pEntry->CurrTxRate = pAd->CommonCfg.MlmeRate;
-	offset = MAC_WCID_BASE + BSS0Mcast_WCID * HW_WCID_ENTRY_SIZE;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicDelWcidTab(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR	Wcid)
-{
-	ULONG		  Addr0 = 0x0, Addr1 = 0x0;
-	ULONG 		offset;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AsicDelWcidTab==>Wcid = 0x%x\n",Wcid));
-	offset = MAC_WCID_BASE + Wcid * HW_WCID_ENTRY_SIZE;
-	RTMP_IO_WRITE32(pAd, offset, Addr0);
-	offset += 4;
-	RTMP_IO_WRITE32(pAd, offset, Addr1);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicEnableRDG(
-	IN PRTMP_ADAPTER pAd)
-{
-	TX_LINK_CFG_STRUC	TxLinkCfg;
-	UINT32				Data = 0;
-
-	RTMP_IO_READ32(pAd, TX_LINK_CFG, &TxLinkCfg.word);
-	TxLinkCfg.field.TxRDGEn = 1;
-	RTMP_IO_WRITE32(pAd, TX_LINK_CFG, TxLinkCfg.word);
-
-	RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
-	Data  &= 0xFFFFFF00;
-	Data  |= 0x80;
-	RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
-
-	//OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicDisableRDG(
-	IN PRTMP_ADAPTER pAd)
-{
-	TX_LINK_CFG_STRUC	TxLinkCfg;
-	UINT32				Data = 0;
-
-
-	RTMP_IO_READ32(pAd, TX_LINK_CFG, &TxLinkCfg.word);
-	TxLinkCfg.field.TxRDGEn = 0;
-	RTMP_IO_WRITE32(pAd, TX_LINK_CFG, TxLinkCfg.word);
-
-	RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
-
-	Data  &= 0xFFFFFF00;
-	//Data  |= 0x20;
-#ifndef WIFI_TEST
-	//if ( pAd->CommonCfg.bEnableTxBurst )
-	//	Data |= 0x60; // for performance issue not set the TXOP to 0
-#endif
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_DYNAMIC_BE_TXOP_ACTIVE)
-#ifdef DOT11_N_SUPPORT
-		&& (pAd->MacTab.fAnyStationMIMOPSDynamic == FALSE)
-#endif // DOT11_N_SUPPORT //
-	)
-	{
-		// For CWC test, change txop from 0x30 to 0x20 in TxBurst mode
-		if (pAd->CommonCfg.bEnableTxBurst)
-			Data |= 0x20;
-	}
-	RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicDisableSync(
-	IN PRTMP_ADAPTER pAd)
-{
-	BCN_TIME_CFG_STRUC csr;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--->Disable TSF synchronization\n"));
-
-	// 2003-12-20 disable TSF and TBTT while NIC in power-saving have side effect
-	//			  that NIC will never wakes up because TSF stops and no more
-	//			  TBTT interrupts
-	pAd->TbttTickCount = 0;
-	RTMP_IO_READ32(pAd, BCN_TIME_CFG, &csr.word);
-	csr.field.bBeaconGen = 0;
-	csr.field.bTBTTEnable = 0;
-	csr.field.TsfSyncMode = 0;
-	csr.field.bTsfTicking = 0;
-	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr.word);
-
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicEnableBssSync(
-	IN PRTMP_ADAPTER pAd)
-{
-	BCN_TIME_CFG_STRUC csr;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--->AsicEnableBssSync(INFRA mode)\n"));
-
-	RTMP_IO_READ32(pAd, BCN_TIME_CFG, &csr.word);
-//	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, 0x00000000);
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		csr.field.BeaconInterval = pAd->CommonCfg.BeaconPeriod << 4; // ASIC register in units of 1/16 TU
-		csr.field.bTsfTicking = 1;
-		csr.field.TsfSyncMode = 1; // sync TSF in INFRASTRUCTURE mode
-		csr.field.bBeaconGen  = 0; // do NOT generate BEACON
-		csr.field.bTBTTEnable = 1;
-	}
-#endif // CONFIG_STA_SUPPORT //
-	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr.word);
-}
-
-/*
-	==========================================================================
-	Description:
-	Note:
-		BEACON frame in shared memory should be built ok before this routine
-		can be called. Otherwise, a garbage frame maybe transmitted out every
-		Beacon period.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicEnableIbssSync(
-	IN PRTMP_ADAPTER pAd)
-{
-	BCN_TIME_CFG_STRUC csr9;
-	PUCHAR			ptr;
-	UINT i;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--->AsicEnableIbssSync(ADHOC mode. MPDUtotalByteCount = %d)\n", pAd->BeaconTxWI.MPDUtotalByteCount));
-
-	RTMP_IO_READ32(pAd, BCN_TIME_CFG, &csr9.word);
-	csr9.field.bBeaconGen = 0;
-	csr9.field.bTBTTEnable = 0;
-	csr9.field.bTsfTicking = 0;
-	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr9.word);
-
-
-#ifdef RT2870
-	// move BEACON TXD and frame content to on-chip memory
-	ptr = (PUCHAR)&pAd->BeaconTxWI;
-	for (i=0; i<TXWI_SIZE; i+=2)  // 16-byte TXWI field
-	{
-		//UINT32 longptr =  *ptr + (*(ptr+1)<<8) + (*(ptr+2)<<16) + (*(ptr+3)<<24);
-		//RTMP_IO_WRITE32(pAd, HW_BEACON_BASE0 + i, longptr);
-		RTUSBMultiWrite(pAd, HW_BEACON_BASE0 + i, ptr, 2);
-		ptr += 2;
-	}
-
-	// start right after the 16-byte TXWI field
-	ptr = pAd->BeaconBuf;
-	for (i=0; i< pAd->BeaconTxWI.MPDUtotalByteCount; i+=2)
-	{
-		//UINT32 longptr =  *ptr + (*(ptr+1)<<8) + (*(ptr+2)<<16) + (*(ptr+3)<<24);
-		//RTMP_IO_WRITE32(pAd, HW_BEACON_BASE0 + TXWI_SIZE + i, longptr);
-		RTUSBMultiWrite(pAd, HW_BEACON_BASE0 + TXWI_SIZE + i, ptr, 2);
-		ptr +=2;
-	}
-#endif // RT2870 //
-
-	//
-	// For Wi-Fi faily generated beacons between participating stations.
-	// Set TBTT phase adaptive adjustment step to 8us (default 16us)
-	// don't change settings 2006-5- by Jerry
-	//RTMP_IO_WRITE32(pAd, TBTT_SYNC_CFG, 0x00001010);
-
-	// start sending BEACON
-	csr9.field.BeaconInterval = pAd->CommonCfg.BeaconPeriod << 4; // ASIC register in units of 1/16 TU
-	csr9.field.bTsfTicking = 1;
-	csr9.field.TsfSyncMode = 2; // sync TSF in IBSS mode
-	csr9.field.bTBTTEnable = 1;
-	csr9.field.bBeaconGen = 1;
-	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr9.word);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicSetEdcaParm(
-	IN PRTMP_ADAPTER pAd,
-	IN PEDCA_PARM	 pEdcaParm)
-{
-	EDCA_AC_CFG_STRUC   Ac0Cfg, Ac1Cfg, Ac2Cfg, Ac3Cfg;
-	AC_TXOP_CSR0_STRUC csr0;
-	AC_TXOP_CSR1_STRUC csr1;
-	AIFSN_CSR_STRUC    AifsnCsr;
-	CWMIN_CSR_STRUC    CwminCsr;
-	CWMAX_CSR_STRUC    CwmaxCsr;
-	int i;
-
-	Ac0Cfg.word = 0;
-	Ac1Cfg.word = 0;
-	Ac2Cfg.word = 0;
-	Ac3Cfg.word = 0;
-	if ((pEdcaParm == NULL) || (pEdcaParm->bValid == FALSE))
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("AsicSetEdcaParm\n"));
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_WMM_INUSED);
-		for (i=0; i<MAX_LEN_OF_MAC_TABLE; i++)
-		{
-			if (pAd->MacTab.Content[i].ValidAsCLI || pAd->MacTab.Content[i].ValidAsApCli)
-				CLIENT_STATUS_CLEAR_FLAG(&pAd->MacTab.Content[i], fCLIENT_STATUS_WMM_CAPABLE);
-		}
-
-		//========================================================
-		//      MAC Register has a copy .
-		//========================================================
-//#ifndef WIFI_TEST
-		if( pAd->CommonCfg.bEnableTxBurst )
-		{
-			// For CWC test, change txop from 0x30 to 0x20 in TxBurst mode
-			Ac0Cfg.field.AcTxop = 0x20; // Suggest by John for TxBurst in HT Mode
-		}
-		else
-			Ac0Cfg.field.AcTxop = 0;	// QID_AC_BE
-//#else
-//		Ac0Cfg.field.AcTxop = 0;	// QID_AC_BE
-//#endif
-		Ac0Cfg.field.Cwmin = CW_MIN_IN_BITS;
-		Ac0Cfg.field.Cwmax = CW_MAX_IN_BITS;
-		Ac0Cfg.field.Aifsn = 2;
-		RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Ac0Cfg.word);
-
-		Ac1Cfg.field.AcTxop = 0;	// QID_AC_BK
-		Ac1Cfg.field.Cwmin = CW_MIN_IN_BITS;
-		Ac1Cfg.field.Cwmax = CW_MAX_IN_BITS;
-		Ac1Cfg.field.Aifsn = 2;
-		RTMP_IO_WRITE32(pAd, EDCA_AC1_CFG, Ac1Cfg.word);
-
-		if (pAd->CommonCfg.PhyMode == PHY_11B)
-		{
-			Ac2Cfg.field.AcTxop = 192;	// AC_VI: 192*32us ~= 6ms
-			Ac3Cfg.field.AcTxop = 96;	// AC_VO: 96*32us  ~= 3ms
-		}
-		else
-		{
-			Ac2Cfg.field.AcTxop = 96;	// AC_VI: 96*32us ~= 3ms
-			Ac3Cfg.field.AcTxop = 48;	// AC_VO: 48*32us ~= 1.5ms
-		}
-		Ac2Cfg.field.Cwmin = CW_MIN_IN_BITS;
-		Ac2Cfg.field.Cwmax = CW_MAX_IN_BITS;
-		Ac2Cfg.field.Aifsn = 2;
-		RTMP_IO_WRITE32(pAd, EDCA_AC2_CFG, Ac2Cfg.word);
-		Ac3Cfg.field.Cwmin = CW_MIN_IN_BITS;
-		Ac3Cfg.field.Cwmax = CW_MAX_IN_BITS;
-		Ac3Cfg.field.Aifsn = 2;
-		RTMP_IO_WRITE32(pAd, EDCA_AC3_CFG, Ac3Cfg.word);
-
-		//========================================================
-		//      DMA Register has a copy too.
-		//========================================================
-		csr0.field.Ac0Txop = 0;		// QID_AC_BE
-		csr0.field.Ac1Txop = 0;		// QID_AC_BK
-		RTMP_IO_WRITE32(pAd, WMM_TXOP0_CFG, csr0.word);
-		if (pAd->CommonCfg.PhyMode == PHY_11B)
-		{
-			csr1.field.Ac2Txop = 192;		// AC_VI: 192*32us ~= 6ms
-			csr1.field.Ac3Txop = 96;		// AC_VO: 96*32us  ~= 3ms
-		}
-		else
-		{
-			csr1.field.Ac2Txop = 96;		// AC_VI: 96*32us ~= 3ms
-			csr1.field.Ac3Txop = 48;		// AC_VO: 48*32us ~= 1.5ms
-		}
-		RTMP_IO_WRITE32(pAd, WMM_TXOP1_CFG, csr1.word);
-
-		CwminCsr.word = 0;
-		CwminCsr.field.Cwmin0 = CW_MIN_IN_BITS;
-		CwminCsr.field.Cwmin1 = CW_MIN_IN_BITS;
-		CwminCsr.field.Cwmin2 = CW_MIN_IN_BITS;
-		CwminCsr.field.Cwmin3 = CW_MIN_IN_BITS;
-		RTMP_IO_WRITE32(pAd, WMM_CWMIN_CFG, CwminCsr.word);
-
-		CwmaxCsr.word = 0;
-		CwmaxCsr.field.Cwmax0 = CW_MAX_IN_BITS;
-		CwmaxCsr.field.Cwmax1 = CW_MAX_IN_BITS;
-		CwmaxCsr.field.Cwmax2 = CW_MAX_IN_BITS;
-		CwmaxCsr.field.Cwmax3 = CW_MAX_IN_BITS;
-		RTMP_IO_WRITE32(pAd, WMM_CWMAX_CFG, CwmaxCsr.word);
-
-		RTMP_IO_WRITE32(pAd, WMM_AIFSN_CFG, 0x00002222);
-
-		NdisZeroMemory(&pAd->CommonCfg.APEdcaParm, sizeof(EDCA_PARM));
-	}
-	else
-	{
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_WMM_INUSED);
-		//========================================================
-		//      MAC Register has a copy.
-		//========================================================
-		//
-		// Modify Cwmin/Cwmax/Txop on queue[QID_AC_VI], Recommend by Jerry 2005/07/27
-		// To degrade our VIDO Queue's throughput for WiFi WMM S3T07 Issue.
-		//
-		//pEdcaParm->Txop[QID_AC_VI] = pEdcaParm->Txop[QID_AC_VI] * 7 / 10; // rt2860c need this
-
-		Ac0Cfg.field.AcTxop =  pEdcaParm->Txop[QID_AC_BE];
-		Ac0Cfg.field.Cwmin= pEdcaParm->Cwmin[QID_AC_BE];
-		Ac0Cfg.field.Cwmax = pEdcaParm->Cwmax[QID_AC_BE];
-		Ac0Cfg.field.Aifsn = pEdcaParm->Aifsn[QID_AC_BE]; //+1;
-
-		Ac1Cfg.field.AcTxop =  pEdcaParm->Txop[QID_AC_BK];
-		Ac1Cfg.field.Cwmin = pEdcaParm->Cwmin[QID_AC_BK]; //+2;
-		Ac1Cfg.field.Cwmax = pEdcaParm->Cwmax[QID_AC_BK];
-		Ac1Cfg.field.Aifsn = pEdcaParm->Aifsn[QID_AC_BK]; //+1;
-
-		Ac2Cfg.field.AcTxop = (pEdcaParm->Txop[QID_AC_VI] * 6) / 10;
-		Ac2Cfg.field.Cwmin = pEdcaParm->Cwmin[QID_AC_VI];
-		Ac2Cfg.field.Cwmax = pEdcaParm->Cwmax[QID_AC_VI];
-		Ac2Cfg.field.Aifsn = pEdcaParm->Aifsn[QID_AC_VI];
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			// Tuning for Wi-Fi WMM S06
-			if (pAd->CommonCfg.bWiFiTest &&
-				pEdcaParm->Aifsn[QID_AC_VI] == 10)
-				Ac2Cfg.field.Aifsn -= 1;
-
-			// Tuning for TGn Wi-Fi 5.2.32
-			// STA TestBed changes in this item: conexant legacy sta ==> broadcom 11n sta
-			if (STA_TGN_WIFI_ON(pAd) &&
-				pEdcaParm->Aifsn[QID_AC_VI] == 10)
-			{
-				Ac0Cfg.field.Aifsn = 3;
-				Ac2Cfg.field.AcTxop = 5;
-			}
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		Ac3Cfg.field.AcTxop = pEdcaParm->Txop[QID_AC_VO];
-		Ac3Cfg.field.Cwmin = pEdcaParm->Cwmin[QID_AC_VO];
-		Ac3Cfg.field.Cwmax = pEdcaParm->Cwmax[QID_AC_VO];
-		Ac3Cfg.field.Aifsn = pEdcaParm->Aifsn[QID_AC_VO];
-
-//#ifdef WIFI_TEST
-		if (pAd->CommonCfg.bWiFiTest)
-		{
-			if (Ac3Cfg.field.AcTxop == 102)
-			{
-			Ac0Cfg.field.AcTxop = pEdcaParm->Txop[QID_AC_BE] ? pEdcaParm->Txop[QID_AC_BE] : 10;
-				Ac0Cfg.field.Aifsn  = pEdcaParm->Aifsn[QID_AC_BE]-1; /* AIFSN must >= 1 */
-			Ac1Cfg.field.AcTxop = pEdcaParm->Txop[QID_AC_BK];
-				Ac1Cfg.field.Aifsn  = pEdcaParm->Aifsn[QID_AC_BK];
-			Ac2Cfg.field.AcTxop = pEdcaParm->Txop[QID_AC_VI];
-			} /* End of if */
-		}
-//#endif // WIFI_TEST //
-
-		RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Ac0Cfg.word);
-		RTMP_IO_WRITE32(pAd, EDCA_AC1_CFG, Ac1Cfg.word);
-		RTMP_IO_WRITE32(pAd, EDCA_AC2_CFG, Ac2Cfg.word);
-		RTMP_IO_WRITE32(pAd, EDCA_AC3_CFG, Ac3Cfg.word);
-
-
-		//========================================================
-		//      DMA Register has a copy too.
-		//========================================================
-		csr0.field.Ac0Txop = Ac0Cfg.field.AcTxop;
-		csr0.field.Ac1Txop = Ac1Cfg.field.AcTxop;
-		RTMP_IO_WRITE32(pAd, WMM_TXOP0_CFG, csr0.word);
-
-		csr1.field.Ac2Txop = Ac2Cfg.field.AcTxop;
-		csr1.field.Ac3Txop = Ac3Cfg.field.AcTxop;
-		RTMP_IO_WRITE32(pAd, WMM_TXOP1_CFG, csr1.word);
-
-		CwminCsr.word = 0;
-		CwminCsr.field.Cwmin0 = pEdcaParm->Cwmin[QID_AC_BE];
-		CwminCsr.field.Cwmin1 = pEdcaParm->Cwmin[QID_AC_BK];
-		CwminCsr.field.Cwmin2 = pEdcaParm->Cwmin[QID_AC_VI];
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			CwminCsr.field.Cwmin3 = pEdcaParm->Cwmin[QID_AC_VO] - 1; //for TGn wifi test
-#endif // CONFIG_STA_SUPPORT //
-		RTMP_IO_WRITE32(pAd, WMM_CWMIN_CFG, CwminCsr.word);
-
-		CwmaxCsr.word = 0;
-		CwmaxCsr.field.Cwmax0 = pEdcaParm->Cwmax[QID_AC_BE];
-		CwmaxCsr.field.Cwmax1 = pEdcaParm->Cwmax[QID_AC_BK];
-		CwmaxCsr.field.Cwmax2 = pEdcaParm->Cwmax[QID_AC_VI];
-		CwmaxCsr.field.Cwmax3 = pEdcaParm->Cwmax[QID_AC_VO];
-		RTMP_IO_WRITE32(pAd, WMM_CWMAX_CFG, CwmaxCsr.word);
-
-		AifsnCsr.word = 0;
-		AifsnCsr.field.Aifsn0 = Ac0Cfg.field.Aifsn; //pEdcaParm->Aifsn[QID_AC_BE];
-		AifsnCsr.field.Aifsn1 = Ac1Cfg.field.Aifsn; //pEdcaParm->Aifsn[QID_AC_BK];
-		AifsnCsr.field.Aifsn2 = Ac2Cfg.field.Aifsn; //pEdcaParm->Aifsn[QID_AC_VI];
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			// Tuning for Wi-Fi WMM S06
-			if (pAd->CommonCfg.bWiFiTest &&
-				pEdcaParm->Aifsn[QID_AC_VI] == 10)
-				AifsnCsr.field.Aifsn2 = Ac2Cfg.field.Aifsn - 4;
-
-			// Tuning for TGn Wi-Fi 5.2.32
-			// STA TestBed changes in this item: conexant legacy sta ==> broadcom 11n sta
-			if (STA_TGN_WIFI_ON(pAd) &&
-				pEdcaParm->Aifsn[QID_AC_VI] == 10)
-			{
-				AifsnCsr.field.Aifsn0 = 3;
-				AifsnCsr.field.Aifsn2 = 7;
-			}
-
-			if (INFRA_ON(pAd))
-				CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_WMM_CAPABLE);
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			AifsnCsr.field.Aifsn3 = Ac3Cfg.field.Aifsn - 1; //pEdcaParm->Aifsn[QID_AC_VO]; //for TGn wifi test
-#endif // CONFIG_STA_SUPPORT //
-		RTMP_IO_WRITE32(pAd, WMM_AIFSN_CFG, AifsnCsr.word);
-
-		NdisMoveMemory(&pAd->CommonCfg.APEdcaParm, pEdcaParm, sizeof(EDCA_PARM));
-		if (!ADHOC_ON(pAd))
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("EDCA [#%d]: AIFSN CWmin CWmax  TXOP(us)  ACM\n", pEdcaParm->EdcaUpdateCount));
-			DBGPRINT(RT_DEBUG_TRACE,("     AC_BE      %2d     %2d     %2d      %4d     %d\n",
-									 pEdcaParm->Aifsn[0],
-									 pEdcaParm->Cwmin[0],
-									 pEdcaParm->Cwmax[0],
-									 pEdcaParm->Txop[0]<<5,
-									 pEdcaParm->bACM[0]));
-			DBGPRINT(RT_DEBUG_TRACE,("     AC_BK      %2d     %2d     %2d      %4d     %d\n",
-									 pEdcaParm->Aifsn[1],
-									 pEdcaParm->Cwmin[1],
-									 pEdcaParm->Cwmax[1],
-									 pEdcaParm->Txop[1]<<5,
-									 pEdcaParm->bACM[1]));
-			DBGPRINT(RT_DEBUG_TRACE,("     AC_VI      %2d     %2d     %2d      %4d     %d\n",
-									 pEdcaParm->Aifsn[2],
-									 pEdcaParm->Cwmin[2],
-									 pEdcaParm->Cwmax[2],
-									 pEdcaParm->Txop[2]<<5,
-									 pEdcaParm->bACM[2]));
-			DBGPRINT(RT_DEBUG_TRACE,("     AC_VO      %2d     %2d     %2d      %4d     %d\n",
-									 pEdcaParm->Aifsn[3],
-									 pEdcaParm->Cwmin[3],
-									 pEdcaParm->Cwmax[3],
-									 pEdcaParm->Txop[3]<<5,
-									 pEdcaParm->bACM[3]));
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID 	AsicSetSlotTime(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN bUseShortSlotTime)
-{
-	ULONG	SlotTime;
-	UINT32	RegValue = 0;
-
-#ifdef CONFIG_STA_SUPPORT
-	if (pAd->CommonCfg.Channel > 14)
-		bUseShortSlotTime = TRUE;
-#endif // CONFIG_STA_SUPPORT //
-
-	if (bUseShortSlotTime)
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_SHORT_SLOT_INUSED);
-	else
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_SLOT_INUSED);
-
-	SlotTime = (bUseShortSlotTime)? 9 : 20;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// force using short SLOT time for FAE to demo performance when TxBurst is ON
-		if (((pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE) && (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED)))
-#ifdef DOT11_N_SUPPORT
-			|| ((pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE) && (pAd->CommonCfg.BACapability.field.Policy == BA_NOTUSE))
-#endif // DOT11_N_SUPPORT //
-			)
-		{
-			// In this case, we will think it is doing Wi-Fi test
-			// And we will not set to short slot when bEnableTxBurst is TRUE.
-		}
-		else if (pAd->CommonCfg.bEnableTxBurst)
-			SlotTime = 9;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	//
-	// For some reasons, always set it to short slot time.
-	//
-	// ToDo: Should consider capability with 11B
-	//
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pAd->StaCfg.BssType == BSS_ADHOC)
-			SlotTime = 20;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	RTMP_IO_READ32(pAd, BKOFF_SLOT_CFG, &RegValue);
-	RegValue = RegValue & 0xFFFFFF00;
-
-	RegValue |= SlotTime;
-
-	RTMP_IO_WRITE32(pAd, BKOFF_SLOT_CFG, RegValue);
-}
-
-/*
-	========================================================================
-	Description:
-		Add Shared key information into ASIC.
-		Update shared key, TxMic and RxMic to Asic Shared key table
-		Update its cipherAlg to Asic Shared key Mode.
-
-    Return:
-	========================================================================
-*/
-VOID AsicAddSharedKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		 BssIndex,
-	IN UCHAR		 KeyIdx,
-	IN UCHAR		 CipherAlg,
-	IN PUCHAR		 pKey,
-	IN PUCHAR		 pTxMic,
-	IN PUCHAR		 pRxMic)
-{
-	ULONG offset; //, csr0;
-	SHAREDKEY_MODE_STRUC csr1;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AsicAddSharedKeyEntry BssIndex=%d, KeyIdx=%d\n", BssIndex,KeyIdx));
-//============================================================================================
-
-	DBGPRINT(RT_DEBUG_TRACE,("AsicAddSharedKeyEntry: %s key #%d\n", CipherName[CipherAlg], BssIndex*4 + KeyIdx));
-	DBGPRINT_RAW(RT_DEBUG_TRACE, (" 	Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pKey[0],pKey[1],pKey[2],pKey[3],pKey[4],pKey[5],pKey[6],pKey[7],pKey[8],pKey[9],pKey[10],pKey[11],pKey[12],pKey[13],pKey[14],pKey[15]));
-	if (pRxMic)
-	{
-		DBGPRINT_RAW(RT_DEBUG_TRACE, (" 	Rx MIC Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-			pRxMic[0],pRxMic[1],pRxMic[2],pRxMic[3],pRxMic[4],pRxMic[5],pRxMic[6],pRxMic[7]));
-	}
-	if (pTxMic)
-	{
-		DBGPRINT_RAW(RT_DEBUG_TRACE, (" 	Tx MIC Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-			pTxMic[0],pTxMic[1],pTxMic[2],pTxMic[3],pTxMic[4],pTxMic[5],pTxMic[6],pTxMic[7]));
-	}
-//============================================================================================
-	//
-	// fill key material - key + TX MIC + RX MIC
-	//
-
-#ifdef RT2870
-{
-	offset = SHARED_KEY_TABLE_BASE + (4*BssIndex + KeyIdx)*HW_KEY_ENTRY_SIZE;
-	RTUSBMultiWrite(pAd, offset, pKey, MAX_LEN_OF_SHARE_KEY);
-
-	offset += MAX_LEN_OF_SHARE_KEY;
-	if (pTxMic)
-	{
-		RTUSBMultiWrite(pAd, offset, pTxMic, 8);
-	}
-
-	offset += 8;
-	if (pRxMic)
-	{
-		RTUSBMultiWrite(pAd, offset, pRxMic, 8);
-	}
-}
-#endif // RT2870 //
-
-	//
-	// Update cipher algorithm. WSTA always use BSS0
-	//
-	RTMP_IO_READ32(pAd, SHARED_KEY_MODE_BASE+4*(BssIndex/2), &csr1.word);
-	DBGPRINT(RT_DEBUG_TRACE,("Read: SHARED_KEY_MODE_BASE at this Bss[%d] KeyIdx[%d]= 0x%x \n", BssIndex,KeyIdx, csr1.word));
-	if ((BssIndex%2) == 0)
-	{
-		if (KeyIdx == 0)
-			csr1.field.Bss0Key0CipherAlg = CipherAlg;
-		else if (KeyIdx == 1)
-			csr1.field.Bss0Key1CipherAlg = CipherAlg;
-		else if (KeyIdx == 2)
-			csr1.field.Bss0Key2CipherAlg = CipherAlg;
-		else
-			csr1.field.Bss0Key3CipherAlg = CipherAlg;
-	}
-	else
-	{
-		if (KeyIdx == 0)
-			csr1.field.Bss1Key0CipherAlg = CipherAlg;
-		else if (KeyIdx == 1)
-			csr1.field.Bss1Key1CipherAlg = CipherAlg;
-		else if (KeyIdx == 2)
-			csr1.field.Bss1Key2CipherAlg = CipherAlg;
-		else
-			csr1.field.Bss1Key3CipherAlg = CipherAlg;
-	}
-	DBGPRINT(RT_DEBUG_TRACE,("Write: SHARED_KEY_MODE_BASE at this Bss[%d] = 0x%x \n", BssIndex, csr1.word));
-	RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE+4*(BssIndex/2), csr1.word);
-
-}
-
-//	IRQL = DISPATCH_LEVEL
-VOID AsicRemoveSharedKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		 BssIndex,
-	IN UCHAR		 KeyIdx)
-{
-	//ULONG SecCsr0;
-	SHAREDKEY_MODE_STRUC csr1;
-
-	DBGPRINT(RT_DEBUG_TRACE,("AsicRemoveSharedKeyEntry: #%d \n", BssIndex*4 + KeyIdx));
-
-	RTMP_IO_READ32(pAd, SHARED_KEY_MODE_BASE+4*(BssIndex/2), &csr1.word);
-	if ((BssIndex%2) == 0)
-	{
-		if (KeyIdx == 0)
-			csr1.field.Bss0Key0CipherAlg = 0;
-		else if (KeyIdx == 1)
-			csr1.field.Bss0Key1CipherAlg = 0;
-		else if (KeyIdx == 2)
-			csr1.field.Bss0Key2CipherAlg = 0;
-		else
-			csr1.field.Bss0Key3CipherAlg = 0;
-	}
-	else
-	{
-		if (KeyIdx == 0)
-			csr1.field.Bss1Key0CipherAlg = 0;
-		else if (KeyIdx == 1)
-			csr1.field.Bss1Key1CipherAlg = 0;
-		else if (KeyIdx == 2)
-			csr1.field.Bss1Key2CipherAlg = 0;
-		else
-			csr1.field.Bss1Key3CipherAlg = 0;
-	}
-	DBGPRINT(RT_DEBUG_TRACE,("Write: SHARED_KEY_MODE_BASE at this Bss[%d] = 0x%x \n", BssIndex, csr1.word));
-	RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE+4*(BssIndex/2), csr1.word);
-	ASSERT(BssIndex < 4);
-	ASSERT(KeyIdx < 4);
-
-}
-
-
-VOID AsicUpdateWCIDAttribute(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN UCHAR		BssIndex,
-	IN UCHAR        CipherAlg,
-	IN BOOLEAN		bUsePairewiseKeyTable)
-{
-	ULONG   WCIDAttri = 0, offset;
-
-	//
-	// Update WCID attribute.
-	// Only TxKey could update WCID attribute.
-	//
-	offset = MAC_WCID_ATTRIBUTE_BASE + (WCID * HW_WCID_ATTRI_SIZE);
-	WCIDAttri = (BssIndex << 4) | (CipherAlg << 1) | (bUsePairewiseKeyTable);
-	RTMP_IO_WRITE32(pAd, offset, WCIDAttri);
-}
-
-VOID AsicUpdateWCIDIVEIV(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN ULONG        uIV,
-	IN ULONG        uEIV)
-{
-	ULONG	offset;
-
-	offset = MAC_IVEIV_TABLE_BASE + (WCID * HW_IVEIV_ENTRY_SIZE);
-
-	RTMP_IO_WRITE32(pAd, offset, uIV);
-	RTMP_IO_WRITE32(pAd, offset + 4, uEIV);
-}
-
-VOID AsicUpdateRxWCIDTable(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN PUCHAR        pAddr)
-{
-	ULONG offset;
-	ULONG Addr;
-
-	offset = MAC_WCID_BASE + (WCID * HW_WCID_ENTRY_SIZE);
-	Addr = pAddr[0] + (pAddr[1] << 8) +(pAddr[2] << 16) +(pAddr[3] << 24);
-	RTMP_IO_WRITE32(pAd, offset, Addr);
-	Addr = pAddr[4] + (pAddr[5] << 8);
-	RTMP_IO_WRITE32(pAd, offset + 4, Addr);
-}
-
-
-/*
-    ========================================================================
-
-    Routine Description:
-        Set Cipher Key, Cipher algorithm, IV/EIV to Asic
-
-    Arguments:
-        pAd                     Pointer to our adapter
-        WCID                    WCID Entry number.
-        BssIndex                BSSID index, station or none multiple BSSID support
-                                this value should be 0.
-        KeyIdx                  This KeyIdx will set to IV's KeyID if bTxKey enabled
-        pCipherKey              Pointer to Cipher Key.
-        bUsePairewiseKeyTable   TRUE means saved the key in SharedKey table,
-                                otherwise PairewiseKey table
-        bTxKey                  This is the transmit key if enabled.
-
-    Return Value:
-        None
-
-    Note:
-        This routine will set the relative key stuff to Asic including WCID attribute,
-        Cipher Key, Cipher algorithm and IV/EIV.
-
-        IV/EIV will be update if this CipherKey is the transmission key because
-        ASIC will base on IV's KeyID value to select Cipher Key.
-
-        If bTxKey sets to FALSE, this is not the TX key, but it could be
-        RX key
-
-    	For AP mode bTxKey must be always set to TRUE.
-    ========================================================================
-*/
-VOID AsicAddKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN UCHAR		BssIndex,
-	IN UCHAR		KeyIdx,
-	IN PCIPHER_KEY	pCipherKey,
-	IN BOOLEAN		bUsePairewiseKeyTable,
-	IN BOOLEAN		bTxKey)
-{
-	ULONG	offset;
-//	ULONG   WCIDAttri = 0;
-	UCHAR	IV4 = 0;
-	PUCHAR		pKey = pCipherKey->Key;
-//	ULONG		KeyLen = pCipherKey->KeyLen;
-	PUCHAR		pTxMic = pCipherKey->TxMic;
-	PUCHAR		pRxMic = pCipherKey->RxMic;
-	PUCHAR		pTxtsc = pCipherKey->TxTsc;
-	UCHAR		CipherAlg = pCipherKey->CipherAlg;
-	SHAREDKEY_MODE_STRUC csr1;
-
-//	ASSERT(KeyLen <= MAX_LEN_OF_PEER_KEY);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==> AsicAddKeyEntry\n"));
-	//
-	// 1.) decide key table offset
-	//
-	if (bUsePairewiseKeyTable)
-		offset = PAIRWISE_KEY_TABLE_BASE + (WCID * HW_KEY_ENTRY_SIZE);
-	else
-		offset = SHARED_KEY_TABLE_BASE + (4 * BssIndex + KeyIdx) * HW_KEY_ENTRY_SIZE;
-
-	//
-	// 2.) Set Key to Asic
-	//
-	//for (i = 0; i < KeyLen; i++)
-
-#ifdef RT2870
-	RTUSBMultiWrite(pAd, offset, pKey, MAX_LEN_OF_PEER_KEY);
-	offset += MAX_LEN_OF_PEER_KEY;
-
-	//
-	// 3.) Set MIC key if available
-	//
-	if (pTxMic)
-	{
-		RTUSBMultiWrite(pAd, offset, pTxMic, 8);
-	}
-	offset += LEN_TKIP_TXMICK;
-
-	if (pRxMic)
-	{
-		RTUSBMultiWrite(pAd, offset, pRxMic, 8);
-	}
-#endif // RT2870 //
-
-	//
-	// 4.) Modify IV/EIV if needs
-	//     This will force Asic to use this key ID by setting IV.
-	//
-	if (bTxKey)
-	{
-
-#ifdef RT2870
-		UINT32 tmpVal;
-
-		//
-		// Write IV
-		//
-		IV4 = (KeyIdx << 6);
-		if ((CipherAlg == CIPHER_TKIP) || (CipherAlg == CIPHER_TKIP_NO_MIC) ||(CipherAlg == CIPHER_AES))
-			IV4 |= 0x20;  // turn on extension bit means EIV existence
-
-		tmpVal = pTxtsc[1] + (((pTxtsc[1] | 0x20) & 0x7f) << 8) + (pTxtsc[0] << 16) + (IV4 << 24);
-		RTMP_IO_WRITE32(pAd, offset, tmpVal);
-
-		//
-		// Write EIV
-		//
-		offset += 4;
-		RTMP_IO_WRITE32(pAd, offset, *(PUINT32)&pCipherKey->TxTsc[2]);
-#endif // RT2870 //
-		AsicUpdateWCIDAttribute(pAd, WCID, BssIndex, CipherAlg, bUsePairewiseKeyTable);
-	}
-
-	if (!bUsePairewiseKeyTable)
-	{
-		//
-		// Only update the shared key security mode
-		//
-		RTMP_IO_READ32(pAd, SHARED_KEY_MODE_BASE + 4 * (BssIndex / 2), &csr1.word);
-		if ((BssIndex % 2) == 0)
-		{
-			if (KeyIdx == 0)
-				csr1.field.Bss0Key0CipherAlg = CipherAlg;
-			else if (KeyIdx == 1)
-				csr1.field.Bss0Key1CipherAlg = CipherAlg;
-			else if (KeyIdx == 2)
-				csr1.field.Bss0Key2CipherAlg = CipherAlg;
-			else
-				csr1.field.Bss0Key3CipherAlg = CipherAlg;
-		}
-		else
-		{
-			if (KeyIdx == 0)
-				csr1.field.Bss1Key0CipherAlg = CipherAlg;
-			else if (KeyIdx == 1)
-				csr1.field.Bss1Key1CipherAlg = CipherAlg;
-			else if (KeyIdx == 2)
-				csr1.field.Bss1Key2CipherAlg = CipherAlg;
-			else
-				csr1.field.Bss1Key3CipherAlg = CipherAlg;
-		}
-		RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE + 4 * (BssIndex / 2), csr1.word);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<== AsicAddKeyEntry\n"));
-}
-
-
-/*
-	========================================================================
-	Description:
-		Add Pair-wise key material into ASIC.
-		Update pairwise key, TxMic and RxMic to Asic Pair-wise key table
-
-    Return:
-	========================================================================
-*/
-VOID AsicAddPairwiseKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR        pAddr,
-	IN UCHAR		WCID,
-	IN CIPHER_KEY		 *pCipherKey)
-{
-	INT i;
-	ULONG 		offset;
-	PUCHAR		 pKey = pCipherKey->Key;
-	PUCHAR		 pTxMic = pCipherKey->TxMic;
-	PUCHAR		 pRxMic = pCipherKey->RxMic;
-#ifdef DBG
-	UCHAR		CipherAlg = pCipherKey->CipherAlg;
-#endif // DBG //
-
-	// EKEY
-	offset = PAIRWISE_KEY_TABLE_BASE + (WCID * HW_KEY_ENTRY_SIZE);
-#ifdef RT2870
-	RTUSBMultiWrite(pAd, offset, &pCipherKey->Key[0], MAX_LEN_OF_PEER_KEY);
-#endif // RT2870 //
-	for (i=0; i<MAX_LEN_OF_PEER_KEY; i+=4)
-	{
-		UINT32 Value;
-		RTMP_IO_READ32(pAd, offset + i, &Value);
-	}
-
-	offset += MAX_LEN_OF_PEER_KEY;
-
-	//  MIC KEY
-	if (pTxMic)
-	{
-#ifdef RT2870
-		RTUSBMultiWrite(pAd, offset, &pCipherKey->TxMic[0], 8);
-#endif // RT2870 //
-	}
-	offset += 8;
-	if (pRxMic)
-	{
-#ifdef RT2870
-		RTUSBMultiWrite(pAd, offset, &pCipherKey->RxMic[0], 8);
-#endif // RT2870 //
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("AsicAddPairwiseKeyEntry: WCID #%d Alg=%s\n",WCID, CipherName[CipherAlg]));
-	DBGPRINT(RT_DEBUG_TRACE,("	Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pKey[0],pKey[1],pKey[2],pKey[3],pKey[4],pKey[5],pKey[6],pKey[7],pKey[8],pKey[9],pKey[10],pKey[11],pKey[12],pKey[13],pKey[14],pKey[15]));
-	if (pRxMic)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("	Rx MIC Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-			pRxMic[0],pRxMic[1],pRxMic[2],pRxMic[3],pRxMic[4],pRxMic[5],pRxMic[6],pRxMic[7]));
-	}
-	if (pTxMic)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("	Tx MIC Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-			pTxMic[0],pTxMic[1],pTxMic[2],pTxMic[3],pTxMic[4],pTxMic[5],pTxMic[6],pTxMic[7]));
-	}
-}
-/*
-	========================================================================
-	Description:
-		Remove Pair-wise key material from ASIC.
-
-    Return:
-	========================================================================
-*/
-VOID AsicRemovePairwiseKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		 BssIdx,
-	IN UCHAR		 Wcid)
-{
-	ULONG		WCIDAttri;
-	USHORT		offset;
-
-	// re-set the entry's WCID attribute as OPEN-NONE.
-	offset = MAC_WCID_ATTRIBUTE_BASE + (Wcid * HW_WCID_ATTRI_SIZE);
-	WCIDAttri = (BssIdx<<4) | PAIRWISEKEYTABLE;
-	RTMP_IO_WRITE32(pAd, offset, WCIDAttri);
-}
-
-BOOLEAN AsicSendCommandToMcu(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		 Command,
-	IN UCHAR		 Token,
-	IN UCHAR		 Arg0,
-	IN UCHAR		 Arg1)
-{
-	HOST_CMD_CSR_STRUC	H2MCmd;
-	H2M_MAILBOX_STRUC	H2MMailbox;
-	ULONG				i = 0;
-	do
-	{
-		RTMP_IO_READ32(pAd, H2M_MAILBOX_CSR, &H2MMailbox.word);
-		if (H2MMailbox.field.Owner == 0)
-			break;
-
-		RTMPusecDelay(2);
-	} while(i++ < 100);
-
-	if (i >= 100)
-	{
-		{
-		DBGPRINT_ERR(("H2M_MAILBOX still hold by MCU. command fail\n"));
-		}
-		return FALSE;
-	}
-
-
-	H2MMailbox.field.Owner	  = 1;	   // pass ownership to MCU
-	H2MMailbox.field.CmdToken = Token;
-	H2MMailbox.field.HighByte = Arg1;
-	H2MMailbox.field.LowByte  = Arg0;
-	RTMP_IO_WRITE32(pAd, H2M_MAILBOX_CSR, H2MMailbox.word);
-
-	H2MCmd.word 			  = 0;
-	H2MCmd.field.HostCommand  = Command;
-	RTMP_IO_WRITE32(pAd, HOST_CMD_CSR, H2MCmd.word);
-
-	if (Command != 0x80)
-	{
-	}
-
-	return TRUE;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Verify the support rate for different PHY type
-
-	Arguments:
-		pAd 				Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-VOID	RTMPCheckRates(
-	IN		PRTMP_ADAPTER	pAd,
-	IN OUT	UCHAR			SupRate[],
-	IN OUT	UCHAR			*SupRateLen)
-{
-	UCHAR	RateIdx, i, j;
-	UCHAR	NewRate[12], NewRateLen;
-
-	NewRateLen = 0;
-
-	if (pAd->CommonCfg.PhyMode == PHY_11B)
-		RateIdx = 4;
-	else
-		RateIdx = 12;
-
-	// Check for support rates exclude basic rate bit
-	for (i = 0; i < *SupRateLen; i++)
-		for (j = 0; j < RateIdx; j++)
-			if ((SupRate[i] & 0x7f) == RateIdTo500Kbps[j])
-				NewRate[NewRateLen++] = SupRate[i];
-
-	*SupRateLen = NewRateLen;
-	NdisMoveMemory(SupRate, NewRate, NewRateLen);
-}
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
-BOOLEAN RTMPCheckChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		CentralChannel,
-	IN UCHAR		Channel)
-{
-	UCHAR		k;
-	UCHAR		UpperChannel = 0, LowerChannel = 0;
-	UCHAR		NoEffectChannelinList = 0;
-
-	// Find upper and lower channel according to 40MHz current operation.
-	if (CentralChannel < Channel)
-	{
-		UpperChannel = Channel;
-		if (CentralChannel > 2)
-			LowerChannel = CentralChannel - 2;
-		else
-			return FALSE;
-	}
-	else if (CentralChannel > Channel)
-	{
-		UpperChannel = CentralChannel + 2;
-		LowerChannel = Channel;
-	}
-
-	for (k = 0;k < pAd->ChannelListNum;k++)
-	{
-		if (pAd->ChannelList[k].Channel == UpperChannel)
-		{
-			NoEffectChannelinList ++;
-		}
-		if (pAd->ChannelList[k].Channel == LowerChannel)
-		{
-			NoEffectChannelinList ++;
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("Total Channel in Channel List = [%d]\n", NoEffectChannelinList));
-	if (NoEffectChannelinList == 2)
-		return TRUE;
-	else
-		return FALSE;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Verify the support rate for HT phy type
-
-	Arguments:
-		pAd 				Pointer to our adapter
-
-	Return Value:
-		FALSE if pAd->CommonCfg.SupportedHtPhy doesn't accept the pHtCapability.  (AP Mode)
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-BOOLEAN 	RTMPCheckHt(
-	IN	PRTMP_ADAPTER			pAd,
-	IN	UCHAR					Wcid,
-	IN 	HT_CAPABILITY_IE		*pHtCapability,
-	IN 	ADD_HT_INFO_IE			*pAddHtInfo)
-{
-	if (Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return FALSE;
-
-	// If use AMSDU, set flag.
-	if (pAd->CommonCfg.DesiredHtPhy.AmsduEnable)
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_AMSDU_INUSED);
-	// Save Peer Capability
-	if (pHtCapability->HtCapInfo.ShortGIfor20)
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_SGI20_CAPABLE);
-	if (pHtCapability->HtCapInfo.ShortGIfor40)
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_SGI40_CAPABLE);
-	if (pHtCapability->HtCapInfo.TxSTBC)
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_TxSTBC_CAPABLE);
-	if (pHtCapability->HtCapInfo.RxSTBC)
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_RxSTBC_CAPABLE);
-	if (pAd->CommonCfg.bRdg && pHtCapability->ExtHtCapInfo.RDGSupport)
-	{
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_RDG_CAPABLE);
-	}
-
-	if (Wcid < MAX_LEN_OF_MAC_TABLE)
-	{
-		pAd->MacTab.Content[Wcid].MpduDensity = pHtCapability->HtCapParm.MpduDensity;
-	}
-
-	// Will check ChannelWidth for MCSSet[4] below
-	pAd->MlmeAux.HtCapability.MCSSet[4] = 0x1;
-    switch (pAd->CommonCfg.RxStream)
-	{
-		case 1:
-			pAd->MlmeAux.HtCapability.MCSSet[0] = 0xff;
-			pAd->MlmeAux.HtCapability.MCSSet[1] = 0x00;
-            pAd->MlmeAux.HtCapability.MCSSet[2] = 0x00;
-            pAd->MlmeAux.HtCapability.MCSSet[3] = 0x00;
-			break;
-		case 2:
-			pAd->MlmeAux.HtCapability.MCSSet[0] = 0xff;
-			pAd->MlmeAux.HtCapability.MCSSet[1] = 0xff;
-            pAd->MlmeAux.HtCapability.MCSSet[2] = 0x00;
-            pAd->MlmeAux.HtCapability.MCSSet[3] = 0x00;
-			break;
-		case 3:
-			pAd->MlmeAux.HtCapability.MCSSet[0] = 0xff;
-			pAd->MlmeAux.HtCapability.MCSSet[1] = 0xff;
-            pAd->MlmeAux.HtCapability.MCSSet[2] = 0xff;
-            pAd->MlmeAux.HtCapability.MCSSet[3] = 0x00;
-			break;
-	}
-
-	pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth = pAddHtInfo->AddHtInfo.RecomWidth & pAd->CommonCfg.DesiredHtPhy.ChannelWidth;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("RTMPCheckHt:: HtCapInfo.ChannelWidth=%d, RecomWidth=%d, DesiredHtPhy.ChannelWidth=%d, BW40MAvailForA/G=%d/%d, PhyMode=%d \n",
-		pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth, pAddHtInfo->AddHtInfo.RecomWidth, pAd->CommonCfg.DesiredHtPhy.ChannelWidth,
-		pAd->NicConfig2.field.BW40MAvailForA, pAd->NicConfig2.field.BW40MAvailForG, pAd->CommonCfg.PhyMode));
-
-	pAd->MlmeAux.HtCapability.HtCapInfo.GF =  pHtCapability->HtCapInfo.GF &pAd->CommonCfg.DesiredHtPhy.GF;
-
-	// Send Assoc Req with my HT capability.
-	pAd->MlmeAux.HtCapability.HtCapInfo.AMsduSize =  pAd->CommonCfg.DesiredHtPhy.AmsduSize;
-	pAd->MlmeAux.HtCapability.HtCapInfo.MimoPs =  pAd->CommonCfg.DesiredHtPhy.MimoPs;
-	pAd->MlmeAux.HtCapability.HtCapInfo.ShortGIfor20 =  (pAd->CommonCfg.DesiredHtPhy.ShortGIfor20) & (pHtCapability->HtCapInfo.ShortGIfor20);
-	pAd->MlmeAux.HtCapability.HtCapInfo.ShortGIfor40 =  (pAd->CommonCfg.DesiredHtPhy.ShortGIfor40) & (pHtCapability->HtCapInfo.ShortGIfor40);
-	pAd->MlmeAux.HtCapability.HtCapInfo.TxSTBC =  (pAd->CommonCfg.DesiredHtPhy.TxSTBC)&(pHtCapability->HtCapInfo.RxSTBC);
-	pAd->MlmeAux.HtCapability.HtCapInfo.RxSTBC =  (pAd->CommonCfg.DesiredHtPhy.RxSTBC)&(pHtCapability->HtCapInfo.TxSTBC);
-	pAd->MlmeAux.HtCapability.HtCapParm.MaxRAmpduFactor = pAd->CommonCfg.DesiredHtPhy.MaxRAmpduFactor;
-    pAd->MlmeAux.HtCapability.HtCapParm.MpduDensity = pAd->CommonCfg.HtCapability.HtCapParm.MpduDensity;
-	pAd->MlmeAux.HtCapability.ExtHtCapInfo.PlusHTC = pHtCapability->ExtHtCapInfo.PlusHTC;
-	pAd->MacTab.Content[Wcid].HTCapability.ExtHtCapInfo.PlusHTC = pHtCapability->ExtHtCapInfo.PlusHTC;
-	if (pAd->CommonCfg.bRdg)
-	{
-		pAd->MlmeAux.HtCapability.ExtHtCapInfo.RDGSupport = pHtCapability->ExtHtCapInfo.RDGSupport;
-        pAd->MlmeAux.HtCapability.ExtHtCapInfo.PlusHTC = 1;
-	}
-
-    if (pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth == BW_20)
-        pAd->MlmeAux.HtCapability.MCSSet[4] = 0x0;  // BW20 can't transmit MCS32
-
-	COPY_AP_HTSETTINGS_FROM_BEACON(pAd, pHtCapability);
-	return TRUE;
-}
-#endif // DOT11_N_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-/*
-	========================================================================
-
-	Routine Description:
-		Verify the support rate for different PHY type
-
-	Arguments:
-		pAd 				Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-VOID RTMPUpdateMlmeRate(
-	IN PRTMP_ADAPTER	pAd)
-{
-	UCHAR	MinimumRate;
-	UCHAR	ProperMlmeRate; //= RATE_54;
-	UCHAR	i, j, RateIdx = 12; //1, 2, 5.5, 11, 6, 9, 12, 18, 24, 36, 48, 54
-	BOOLEAN	bMatch = FALSE;
-
-	switch (pAd->CommonCfg.PhyMode)
-	{
-		case PHY_11B:
-			ProperMlmeRate = RATE_11;
-			MinimumRate = RATE_1;
-			break;
-		case PHY_11BG_MIXED:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11ABGN_MIXED:
-		case PHY_11BGN_MIXED:
-#endif // DOT11_N_SUPPORT //
-			if ((pAd->MlmeAux.SupRateLen == 4) &&
-				(pAd->MlmeAux.ExtRateLen == 0))
-				// B only AP
-				ProperMlmeRate = RATE_11;
-			else
-				ProperMlmeRate = RATE_24;
-
-			if (pAd->MlmeAux.Channel <= 14)
-				MinimumRate = RATE_1;
-			else
-				MinimumRate = RATE_6;
-			break;
-		case PHY_11A:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11N_2_4G:	// rt2860 need to check mlmerate for 802.11n
-		case PHY_11GN_MIXED:
-		case PHY_11AGN_MIXED:
-		case PHY_11AN_MIXED:
-		case PHY_11N_5G:
-#endif // DOT11_N_SUPPORT //
-			ProperMlmeRate = RATE_24;
-			MinimumRate = RATE_6;
-			break;
-		case PHY_11ABG_MIXED:
-			ProperMlmeRate = RATE_24;
-			if (pAd->MlmeAux.Channel <= 14)
-			   MinimumRate = RATE_1;
-			else
-				MinimumRate = RATE_6;
-			break;
-		default: // error
-			ProperMlmeRate = RATE_1;
-			MinimumRate = RATE_1;
-			break;
-	}
-
-	for (i = 0; i < pAd->MlmeAux.SupRateLen; i++)
-	{
-		for (j = 0; j < RateIdx; j++)
-		{
-			if ((pAd->MlmeAux.SupRate[i] & 0x7f) == RateIdTo500Kbps[j])
-			{
-				if (j == ProperMlmeRate)
-				{
-					bMatch = TRUE;
-					break;
-				}
-			}
-		}
-
-		if (bMatch)
-			break;
-	}
-
-	if (bMatch == FALSE)
-	{
-		for (i = 0; i < pAd->MlmeAux.ExtRateLen; i++)
-		{
-			for (j = 0; j < RateIdx; j++)
-			{
-				if ((pAd->MlmeAux.ExtRate[i] & 0x7f) == RateIdTo500Kbps[j])
-				{
-					if (j == ProperMlmeRate)
-					{
-						bMatch = TRUE;
-						break;
-					}
-				}
-			}
-
-			if (bMatch)
-				break;
-		}
-	}
-
-	if (bMatch == FALSE)
-	{
-		ProperMlmeRate = MinimumRate;
-	}
-
-	pAd->CommonCfg.MlmeRate = MinimumRate;
-	pAd->CommonCfg.RtsRate = ProperMlmeRate;
-	if (pAd->CommonCfg.MlmeRate >= RATE_6)
-	{
-		pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-		pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MODE = MODE_OFDM;
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-	}
-	else
-	{
-		pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_CCK;
-		pAd->CommonCfg.MlmeTransmit.field.MCS = pAd->CommonCfg.MlmeRate;
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MODE = MODE_CCK;
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MCS = pAd->CommonCfg.MlmeRate;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPUpdateMlmeRate ==>   MlmeTransmit = 0x%x  \n" , pAd->CommonCfg.MlmeTransmit.word));
-}
-
-CHAR RTMPMaxRssi(
-	IN PRTMP_ADAPTER	pAd,
-	IN CHAR				Rssi0,
-	IN CHAR				Rssi1,
-	IN CHAR				Rssi2)
-{
-	CHAR	larger = -127;
-
-	if ((pAd->Antenna.field.RxPath == 1) && (Rssi0 != 0))
-	{
-		larger = Rssi0;
-	}
-
-	if ((pAd->Antenna.field.RxPath >= 2) && (Rssi1 != 0))
-	{
-		larger = max(Rssi0, Rssi1);
-	}
-
-	if ((pAd->Antenna.field.RxPath == 3) && (Rssi2 != 0))
-	{
-		larger = max(larger, Rssi2);
-	}
-
-	if (larger == -127)
-		larger = 0;
-
-	return larger;
-}
-
-/*
-    ========================================================================
-    Routine Description:
-        Periodic evaluate antenna link status
-
-    Arguments:
-        pAd         - Adapter pointer
-
-    Return Value:
-        None
-
-    ========================================================================
-*/
-VOID AsicEvaluateRxAnt(
-	IN PRTMP_ADAPTER	pAd)
-{
-	UCHAR	BBPR3 = 0;
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS	|
-								fRTMP_ADAPTER_HALT_IN_PROGRESS	|
-								fRTMP_ADAPTER_RADIO_OFF			|
-								fRTMP_ADAPTER_NIC_NOT_EXIST		|
-								fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-			return;
-
-		if (pAd->StaCfg.Psm == PWR_SAVE)
-			return;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPR3);
-	BBPR3 &= (~0x18);
-	if(pAd->Antenna.field.RxPath == 3)
-	{
-		BBPR3 |= (0x10);
-	}
-	else if(pAd->Antenna.field.RxPath == 2)
-	{
-		BBPR3 |= (0x8);
-	}
-	else if(pAd->Antenna.field.RxPath == 1)
-	{
-		BBPR3 |= (0x0);
-	}
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPR3);
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)
-		)
-	{
-		ULONG	TxTotalCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount +
-								pAd->RalinkCounters.OneSecTxRetryOkCount +
-								pAd->RalinkCounters.OneSecTxFailCount;
-
-		if (TxTotalCnt > 50)
-		{
-			RTMPSetTimer(&pAd->Mlme.RxAntEvalTimer, 20);
-			pAd->Mlme.bLowThroughput = FALSE;
-		}
-		else
-		{
-			RTMPSetTimer(&pAd->Mlme.RxAntEvalTimer, 300);
-			pAd->Mlme.bLowThroughput = TRUE;
-		}
-	}
-}
-
-/*
-    ========================================================================
-    Routine Description:
-        After evaluation, check antenna link status
-
-    Arguments:
-        pAd         - Adapter pointer
-
-    Return Value:
-        None
-
-    ========================================================================
-*/
-VOID AsicRxAntEvalTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER	*pAd = (RTMP_ADAPTER *)FunctionContext;
-#ifdef CONFIG_STA_SUPPORT
-	UCHAR			BBPR3 = 0;
-	CHAR			larger = -127, rssi0, rssi1, rssi2;
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)	||
-			RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)		||
-			RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF)			||
-			RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
-			return;
-
-		if (pAd->StaCfg.Psm == PWR_SAVE)
-			return;
-
-
-		// if the traffic is low, use average rssi as the criteria
-		if (pAd->Mlme.bLowThroughput == TRUE)
-		{
-			rssi0 = pAd->StaCfg.RssiSample.LastRssi0;
-			rssi1 = pAd->StaCfg.RssiSample.LastRssi1;
-			rssi2 = pAd->StaCfg.RssiSample.LastRssi2;
-		}
-		else
-		{
-			rssi0 = pAd->StaCfg.RssiSample.AvgRssi0;
-			rssi1 = pAd->StaCfg.RssiSample.AvgRssi1;
-			rssi2 = pAd->StaCfg.RssiSample.AvgRssi2;
-		}
-
-		if(pAd->Antenna.field.RxPath == 3)
-		{
-			larger = max(rssi0, rssi1);
-
-			if (larger > (rssi2 + 20))
-				pAd->Mlme.RealRxPath = 2;
-			else
-				pAd->Mlme.RealRxPath = 3;
-		}
-		else if(pAd->Antenna.field.RxPath == 2)
-		{
-			if (rssi0 > (rssi1 + 20))
-				pAd->Mlme.RealRxPath = 1;
-			else
-				pAd->Mlme.RealRxPath = 2;
-		}
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPR3);
-		BBPR3 &= (~0x18);
-		if(pAd->Mlme.RealRxPath == 3)
-		{
-			BBPR3 |= (0x10);
-		}
-		else if(pAd->Mlme.RealRxPath == 2)
-		{
-			BBPR3 |= (0x8);
-		}
-		else if(pAd->Mlme.RealRxPath == 1)
-		{
-			BBPR3 |= (0x0);
-		}
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPR3);
-	}
-
-#endif // CONFIG_STA_SUPPORT //
-
-}
-
-
-
-VOID APSDPeriodicExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-		return;
-
-	pAd->CommonCfg.TriggerTimerCount++;
-
-// Driver should not send trigger frame, it should be send by application layer
-/*
-	if (pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable
-		&& (pAd->CommonCfg.bNeedSendTriggerFrame ||
-		(((pAd->CommonCfg.TriggerTimerCount%20) == 19) && (!pAd->CommonCfg.bAPSDAC_BE || !pAd->CommonCfg.bAPSDAC_BK || !pAd->CommonCfg.bAPSDAC_VI || !pAd->CommonCfg.bAPSDAC_VO))))
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("Sending trigger frame and enter service period when support APSD\n"));
-		RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, TRUE);
-		pAd->CommonCfg.bNeedSendTriggerFrame = FALSE;
-		pAd->CommonCfg.TriggerTimerCount = 0;
-		pAd->CommonCfg.bInServicePeriod = TRUE;
-	}*/
-}
-
-/*
-    ========================================================================
-    Routine Description:
-        Set/reset MAC registers according to bPiggyBack parameter
-
-    Arguments:
-        pAd         - Adapter pointer
-        bPiggyBack  - Enable / Disable Piggy-Back
-
-    Return Value:
-        None
-
-    ========================================================================
-*/
-VOID RTMPSetPiggyBack(
-    IN PRTMP_ADAPTER    pAd,
-    IN BOOLEAN          bPiggyBack)
-{
-	TX_LINK_CFG_STRUC  TxLinkCfg;
-
-	RTMP_IO_READ32(pAd, TX_LINK_CFG, &TxLinkCfg.word);
-
-	TxLinkCfg.field.TxCFAckEn = bPiggyBack;
-	RTMP_IO_WRITE32(pAd, TX_LINK_CFG, TxLinkCfg.word);
-}
-
-/*
-    ========================================================================
-    Routine Description:
-        check if this entry need to switch rate automatically
-
-    Arguments:
-        pAd
-        pEntry
-
-    Return Value:
-        TURE
-        FALSE
-
-    ========================================================================
-*/
-BOOLEAN RTMPCheckEntryEnableAutoRateSwitch(
-	IN PRTMP_ADAPTER    pAd,
-	IN PMAC_TABLE_ENTRY	pEntry)
-{
-	BOOLEAN		result = TRUE;
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// only associated STA counts
-		if (pEntry && (pEntry->ValidAsCLI) && (pEntry->Sst == SST_ASSOC))
-		{
-			result = pAd->StaCfg.bAutoTxRateSwitch;
-		}
-		else
-			result = FALSE;
-
-#ifdef QOS_DLS_SUPPORT
-		if (pEntry && (pEntry->ValidAsDls))
-			result = pAd->StaCfg.bAutoTxRateSwitch;
-#endif // QOS_DLS_SUPPORT //
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-	return result;
-}
-
-
-BOOLEAN RTMPAutoRateSwitchCheck(
-	IN PRTMP_ADAPTER    pAd)
-{
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pAd->StaCfg.bAutoTxRateSwitch)
-			return TRUE;
-	}
-#endif // CONFIG_STA_SUPPORT //
-	return FALSE;
-}
-
-
-/*
-    ========================================================================
-    Routine Description:
-        check if this entry need to fix tx legacy rate
-
-    Arguments:
-        pAd
-        pEntry
-
-    Return Value:
-        TURE
-        FALSE
-
-    ========================================================================
-*/
-UCHAR RTMPStaFixedTxMode(
-	IN PRTMP_ADAPTER    pAd,
-	IN PMAC_TABLE_ENTRY	pEntry)
-{
-	UCHAR	tx_mode = FIXED_TXMODE_HT;
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		tx_mode = (UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	return tx_mode;
-}
-
-/*
-    ========================================================================
-    Routine Description:
-        Overwrite HT Tx Mode by Fixed Legency Tx Mode, if specified.
-
-    Arguments:
-        pAd
-        pEntry
-
-    Return Value:
-        TURE
-        FALSE
-
-    ========================================================================
-*/
-VOID RTMPUpdateLegacyTxSetting(
-		UCHAR				fixed_tx_mode,
-		PMAC_TABLE_ENTRY	pEntry)
-{
-	HTTRANSMIT_SETTING TransmitSetting;
-
-	if (fixed_tx_mode == FIXED_TXMODE_HT)
-		return;
-
-	TransmitSetting.word = 0;
-
-	TransmitSetting.field.MODE = pEntry->HTPhyMode.field.MODE;
-	TransmitSetting.field.MCS = pEntry->HTPhyMode.field.MCS;
-
-	if (fixed_tx_mode == FIXED_TXMODE_CCK)
-	{
-		TransmitSetting.field.MODE = MODE_CCK;
-		// CCK mode allow MCS 0~3
-		if (TransmitSetting.field.MCS > MCS_3)
-			TransmitSetting.field.MCS = MCS_3;
-	}
-	else
-	{
-		TransmitSetting.field.MODE = MODE_OFDM;
-		// OFDM mode allow MCS 0~7
-		if (TransmitSetting.field.MCS > MCS_7)
-			TransmitSetting.field.MCS = MCS_7;
-	}
-
-	if (pEntry->HTPhyMode.field.MODE >= TransmitSetting.field.MODE)
-	{
-		pEntry->HTPhyMode.word = TransmitSetting.word;
-		DBGPRINT(RT_DEBUG_TRACE, ("RTMPUpdateLegacyTxSetting : wcid-%d, MODE=%s, MCS=%d \n",
-				pEntry->Aid, GetPhyMode(pEntry->HTPhyMode.field.MODE), pEntry->HTPhyMode.field.MCS));
-	}
-}
-
-#ifdef CONFIG_STA_SUPPORT
-/*
-	==========================================================================
-	Description:
-		dynamic tune BBP R66 to find a balance between sensibility and
-		noise isolation
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicStaBbpTuning(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR	OrigR66Value = 0, R66;//, R66UpperBound = 0x30, R66LowerBound = 0x30;
-	CHAR	Rssi;
-
-	// 2860C did not support Fase CCA, therefore can't tune
-	if (pAd->MACVersion == 0x28600100)
-		return;
-
-	//
-	// work as a STA
-	//
-	if (pAd->Mlme.CntlMachine.CurrState != CNTL_IDLE)  // no R66 tuning when SCANNING
-		return;
-
-	if ((pAd->OpMode == OPMODE_STA)
-		&& (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)
-			)
-		&& !(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-		)
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &OrigR66Value);
-		R66 = OrigR66Value;
-
-		if (pAd->Antenna.field.RxPath > 1)
-			Rssi = (pAd->StaCfg.RssiSample.AvgRssi0 + pAd->StaCfg.RssiSample.AvgRssi1) >> 1;
-		else
-			Rssi = pAd->StaCfg.RssiSample.AvgRssi0;
-
-		if (pAd->LatchRfRegs.Channel <= 14)
-		{	//BG band
-#ifdef RT2870
-			// RT3070 is a no LNA solution, it should have different control regarding to AGC gain control
-			// Otherwise, it will have some throughput side effect when low RSSI
-			if (IS_RT3070(pAd))
-			{
-				if (Rssi > RSSI_FOR_MID_LOW_SENSIBILITY)
-				{
-					R66 = 0x1C + 2*GET_LNA_GAIN(pAd) + 0x20;
-					if (OrigR66Value != R66)
-					{
-						RTUSBWriteBBPRegister(pAd, BBP_R66, R66);
-					}
-				}
-				else
-				{
-					R66 = 0x1C + 2*GET_LNA_GAIN(pAd);
-					if (OrigR66Value != R66)
-					{
-						RTUSBWriteBBPRegister(pAd, BBP_R66, R66);
-					}
-				}
-			}
-			else
-#endif // RT2870 //
-			{
-				if (Rssi > RSSI_FOR_MID_LOW_SENSIBILITY)
-				{
-					R66 = (0x2E + GET_LNA_GAIN(pAd)) + 0x10;
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-				else
-				{
-					R66 = 0x2E + GET_LNA_GAIN(pAd);
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-			}
-		}
-		else
-		{	//A band
-			if (pAd->CommonCfg.BBPCurrentBW == BW_20)
-			{
-				if (Rssi > RSSI_FOR_MID_LOW_SENSIBILITY)
-				{
-					R66 = 0x32 + (GET_LNA_GAIN(pAd)*5)/3 + 0x10;
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-				else
-				{
-					R66 = 0x32 + (GET_LNA_GAIN(pAd)*5)/3;
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-			}
-			else
-			{
-				if (Rssi > RSSI_FOR_MID_LOW_SENSIBILITY)
-				{
-					R66 = 0x3A + (GET_LNA_GAIN(pAd)*5)/3 + 0x10;
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-				else
-				{
-					R66 = 0x3A + (GET_LNA_GAIN(pAd)*5)/3;
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-			}
-		}
-
-
-	}
-}
-#endif // CONFIG_STA_SUPPORT //
-
-VOID RTMPSetAGCInitValue(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			BandWidth)
-{
-	UCHAR	R66 = 0x30;
-
-	if (pAd->LatchRfRegs.Channel <= 14)
-	{	// BG band
-		R66 = 0x2E + GET_LNA_GAIN(pAd);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-	}
-	else
-	{	//A band
-		if (BandWidth == BW_20)
-		{
-			R66 = (UCHAR)(0x32 + (GET_LNA_GAIN(pAd)*5)/3);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-		}
-#ifdef DOT11_N_SUPPORT
-		else
-		{
-			R66 = (UCHAR)(0x3A + (GET_LNA_GAIN(pAd)*5)/3);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-		}
-#endif // DOT11_N_SUPPORT //
-	}
-
-}
-
-VOID AsicTurnOffRFClk(
-	IN PRTMP_ADAPTER pAd,
-	IN	UCHAR		Channel)
-{
-
-	// RF R2 bit 18 = 0
-	UINT32			R1 = 0, R2 = 0, R3 = 0;
-	UCHAR			index;
-	RTMP_RF_REGS	*RFRegTable;
-
-	RFRegTable = RF2850RegTable;
-
-	switch (pAd->RfIcType)
-	{
-		case RFIC_2820:
-		case RFIC_2850:
-		case RFIC_2720:
-		case RFIC_2750:
-
-			for (index = 0; index < NUM_OF_2850_CHNL; index++)
-			{
-				if (Channel == RFRegTable[index].Channel)
-				{
-					R1 = RFRegTable[index].R1 & 0xffffdfff;
-					R2 = RFRegTable[index].R2 & 0xfffbffff;
-					R3 = RFRegTable[index].R3 & 0xfff3ffff;
-
-					RTMP_RF_IO_WRITE32(pAd, R1);
-					RTMP_RF_IO_WRITE32(pAd, R2);
-
-					// Program R1b13 to 1, R3/b18,19 to 0, R2b18 to 0.
-					// Set RF R2 bit18=0, R3 bit[18:19]=0
-					//if (pAd->StaCfg.bRadio == FALSE)
-					if (1)
-					{
-						RTMP_RF_IO_WRITE32(pAd, R3);
-
-						DBGPRINT(RT_DEBUG_TRACE, ("AsicTurnOffRFClk#%d(RF=%d, ) , R2=0x%08x,  R3 = 0x%08x \n",
-							Channel, pAd->RfIcType, R2, R3));
-					}
-					else
-						DBGPRINT(RT_DEBUG_TRACE, ("AsicTurnOffRFClk#%d(RF=%d, ) , R2=0x%08x \n",
-							Channel, pAd->RfIcType, R2));
-					break;
-				}
-			}
-			break;
-
-		default:
-			break;
-	}
-}
-
-
-VOID AsicTurnOnRFClk(
-	IN PRTMP_ADAPTER pAd,
-	IN	UCHAR			Channel)
-{
-
-	// RF R2 bit 18 = 0
-	UINT32			R1 = 0, R2 = 0, R3 = 0;
-	UCHAR			index;
-	RTMP_RF_REGS	*RFRegTable;
-
-	RFRegTable = RF2850RegTable;
-
-	switch (pAd->RfIcType)
-	{
-		case RFIC_2820:
-		case RFIC_2850:
-		case RFIC_2720:
-		case RFIC_2750:
-
-			for (index = 0; index < NUM_OF_2850_CHNL; index++)
-			{
-				if (Channel == RFRegTable[index].Channel)
-				{
-					R3 = pAd->LatchRfRegs.R3;
-					R3 &= 0xfff3ffff;
-					R3 |= 0x00080000;
-					RTMP_RF_IO_WRITE32(pAd, R3);
-
-					R1 = RFRegTable[index].R1;
-					RTMP_RF_IO_WRITE32(pAd, R1);
-
-					R2 = RFRegTable[index].R2;
-					if (pAd->Antenna.field.TxPath == 1)
-					{
-						R2 |= 0x4000;	// If TXpath is 1, bit 14 = 1;
-					}
-
-					if (pAd->Antenna.field.RxPath == 2)
-					{
-						R2 |= 0x40;	// write 1 to off Rxpath.
-					}
-					else if (pAd->Antenna.field.RxPath == 1)
-					{
-						R2 |= 0x20040;	// write 1 to off RxPath
-					}
-					RTMP_RF_IO_WRITE32(pAd, R2);
-
-					break;
-				}
-			}
-			break;
-
-		default:
-			break;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AsicTurnOnRFClk#%d(RF=%d, ) , R2=0x%08x\n",
-		Channel,
-		pAd->RfIcType,
-		R2));
-}
-
+#include "../../rt2860/common/mlme.c"
diff --git a/drivers/staging/rt2870/common/netif_block.c b/drivers/staging/rt2870/common/netif_block.c
deleted file mode 100644
index d3f7d08..0000000
--- a/drivers/staging/rt2870/common/netif_block.c
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#include "../rt_config.h"
-#include "netif_block.h"
-
-static NETIF_ENTRY freeNetIfEntryPool[FREE_NETIF_POOL_SIZE];
-static LIST_HEADER freeNetIfEntryList;
-
-void initblockQueueTab(
-	IN PRTMP_ADAPTER pAd)
-{
-	int i;
-
-	initList(&freeNetIfEntryList);
-	for (i = 0; i < FREE_NETIF_POOL_SIZE; i++)
-		insertTailList(&freeNetIfEntryList, (PLIST_ENTRY)&freeNetIfEntryPool[i]);
-
-	for (i=0; i < NUM_OF_TX_RING; i++)
-		initList(&pAd->blockQueueTab[i].NetIfList);
-
-	return;
-}
-
-BOOLEAN blockNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry,
-	IN PNET_DEV pNetDev)
-{
-	PNETIF_ENTRY pNetIfEntry = NULL;
-
-	if ((pNetIfEntry = (PNETIF_ENTRY)removeHeadList(&freeNetIfEntryList)) != NULL)
-	{
-		netif_stop_queue(pNetDev);
-		pNetIfEntry->pNetDev = pNetDev;
-		insertTailList(&pBlockQueueEntry->NetIfList, (PLIST_ENTRY)pNetIfEntry);
-
-		pBlockQueueEntry->SwTxQueueBlockFlag = TRUE;
-		DBGPRINT(RT_DEBUG_TRACE, ("netif_stop_queue(%s)\n", pNetDev->name));
-	}
-	else
-		return FALSE;
-
-	return TRUE;
-}
-
-VOID releaseNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry)
-{
-	PNETIF_ENTRY pNetIfEntry = NULL;
-	PLIST_HEADER pNetIfList = &pBlockQueueEntry->NetIfList;
-
-	while((pNetIfEntry = (PNETIF_ENTRY)removeHeadList(pNetIfList)) !=  NULL)
-	{
-		PNET_DEV pNetDev = pNetIfEntry->pNetDev;
-		netif_wake_queue(pNetDev);
-		insertTailList(&freeNetIfEntryList, (PLIST_ENTRY)pNetIfEntry);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("netif_wake_queue(%s)\n", pNetDev->name));
-	}
-	pBlockQueueEntry->SwTxQueueBlockFlag = FALSE;
-	return;
-}
-
-
-VOID StopNetIfQueue(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR QueIdx,
-	IN PNDIS_PACKET pPacket)
-{
-	PNET_DEV NetDev = NULL;
-	UCHAR IfIdx = 0;
-	BOOLEAN valid = FALSE;
-
-#ifdef APCLI_SUPPORT
-	if (RTMP_GET_PACKET_NET_DEVICE(pPacket) >= MIN_NET_DEVICE_FOR_APCLI)
-	{
-		IfIdx = (RTMP_GET_PACKET_NET_DEVICE(pPacket) - MIN_NET_DEVICE_FOR_APCLI) % MAX_APCLI_NUM;
-		NetDev = pAd->ApCfg.ApCliTab[IfIdx].dev;
-	}
-	else
-#endif // APCLI_SUPPORT //
-#ifdef WDS_SUPPORT
-	if (RTMP_GET_PACKET_NET_DEVICE(pPacket) >= MIN_NET_DEVICE_FOR_WDS)
-	{
-		IfIdx = (RTMP_GET_PACKET_NET_DEVICE(pPacket) - MIN_NET_DEVICE_FOR_WDS) % MAX_WDS_ENTRY;
-		NetDev = pAd->WdsTab.WdsEntry[IfIdx].dev;
-	}
-	else
-#endif // WDS_SUPPORT //
-	{
-#ifdef MBSS_SUPPORT
-		if (pAd->OpMode == OPMODE_AP)
-		{
-			IfIdx = (RTMP_GET_PACKET_NET_DEVICE(pPacket) - MIN_NET_DEVICE_FOR_MBSSID) % MAX_MBSSID_NUM;
-			NetDev = pAd->ApCfg.MBSSID[IfIdx].MSSIDDev;
-		}
-		else
-		{
-			IfIdx = MAIN_MBSSID;
-			NetDev = pAd->net_dev;
-		}
-#else
-		IfIdx = MAIN_MBSSID;
-		NetDev = pAd->net_dev;
-#endif
-	}
-
-	// WMM support 4 software queues.
-	// One software queue full doesn't mean device have no capbility to transmit packet.
-	// So disable block Net-If queue function while WMM enable.
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		valid = (pAd->CommonCfg.bWmmCapable == TRUE) ? FALSE : TRUE;
-#endif // CONFIG_STA_SUPPORT //
-
-	if (valid)
-		blockNetIf(&pAd->blockQueueTab[QueIdx], NetDev);
-	return;
-}
-
diff --git a/drivers/staging/rt2870/common/rtmp_init.c b/drivers/staging/rt2870/common/rtmp_init.c
index 099b6a8..eef10ef 100644
--- a/drivers/staging/rt2870/common/rtmp_init.c
+++ b/drivers/staging/rt2870/common/rtmp_init.c
@@ -1,4132 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtmp_init.c
-
-	Abstract:
-	Miniport generic portion header file
-
-	Revision History:
-	Who         When          What
-	--------    ----------    ----------------------------------------------
-	Paul Lin    2002-08-01    created
-    John Chang  2004-08-20    RT2561/2661 use scatter-gather scheme
-    Jan Lee  2006-09-15    RT2860. Change for 802.11n , EEPROM, Led, BA, HT.
-*/
-#include "../rt_config.h"
-#include "firmware.h"
-
-//#define BIN_IN_FILE /* use *.bin firmware */
-
-UCHAR    BIT8[] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
-ULONG    BIT32[] = {0x00000001, 0x00000002, 0x00000004, 0x00000008,
-					0x00000010, 0x00000020, 0x00000040, 0x00000080,
-					0x00000100, 0x00000200, 0x00000400, 0x00000800,
-					0x00001000, 0x00002000, 0x00004000, 0x00008000,
-					0x00010000, 0x00020000, 0x00040000, 0x00080000,
-					0x00100000, 0x00200000, 0x00400000, 0x00800000,
-					0x01000000, 0x02000000, 0x04000000, 0x08000000,
-					0x10000000, 0x20000000, 0x40000000, 0x80000000};
-
-char*   CipherName[] = {"none","wep64","wep128","TKIP","AES","CKIP64","CKIP128"};
-
-const unsigned short ccitt_16Table[] = {
-	0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
-	0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
-	0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
-	0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
-	0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
-	0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
-	0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
-	0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
-	0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
-	0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
-	0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
-	0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
-	0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
-	0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
-	0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
-	0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
-	0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
-	0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
-	0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
-	0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
-	0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
-	0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
-	0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
-	0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
-	0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
-	0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
-	0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
-	0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
-	0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
-	0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
-	0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
-	0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
-};
-#define ByteCRC16(v, crc) \
-	(unsigned short)((crc << 8) ^  ccitt_16Table[((crc >> 8) ^ (v)) & 255])
-
-unsigned char BitReverse(unsigned char x)
-{
-	int i;
-	unsigned char Temp=0;
-	for(i=0; ; i++)
-	{
-		if(x & 0x80)	Temp |= 0x80;
-		if(i==7)		break;
-		x	<<= 1;
-		Temp >>= 1;
-	}
-	return Temp;
-}
-
-//
-// BBP register initialization set
-//
-REG_PAIR   BBPRegTable[] = {
-	{BBP_R65,		0x2C},		// fix rssi issue
-	{BBP_R66,		0x38},	// Also set this default value to pAd->BbpTuning.R66CurrentValue at initial
-	{BBP_R69,		0x12},
-	{BBP_R70,		0xa},	// BBP_R70 will change to 0x8 in ApStartUp and LinkUp for rt2860C, otherwise value is 0xa
-	{BBP_R73,		0x10},
-	{BBP_R81,		0x37},
-	{BBP_R82,		0x62},
-	{BBP_R83,		0x6A},
-	{BBP_R84,		0x99},	// 0x19 is for rt2860E and after. This is for extension channel overlapping IOT. 0x99 is for rt2860D and before
-	{BBP_R86,		0x00},	// middle range issue, Rory @2008-01-28
-	{BBP_R91,		0x04},	// middle range issue, Rory @2008-01-28
-	{BBP_R92,		0x00},	// middle range issue, Rory @2008-01-28
-	{BBP_R103,  	0x00}, 	// near range high-power issue, requested from Gary @2008-0528
-	{BBP_R105,		0x05},	// 0x05 is for rt2860E to turn on FEQ control. It is safe for rt2860D and before, because Bit 7:2 are reserved in rt2860D and before.
-};
-#define	NUM_BBP_REG_PARMS	(sizeof(BBPRegTable) / sizeof(REG_PAIR))
-
-//
-// RF register initialization set
-//
-#ifdef RT2870
-REG_PAIR   RT30xx_RFRegTable[] = {
-        {RF_R04,          0x40},
-        {RF_R05,          0x03},
-        {RF_R06,          0x02},
-        {RF_R07,          0x70},
-        {RF_R09,          0x0F},
-        {RF_R10,          0x71},
-        {RF_R11,          0x21},
-        {RF_R12,          0x7B},
-        {RF_R14,          0x90},
-        {RF_R15,          0x58},
-        {RF_R16,          0xB3},
-        {RF_R17,          0x92},
-        {RF_R18,          0x2C},
-        {RF_R19,          0x02},
-        {RF_R20,          0xBA},
-        {RF_R21,          0xDB},
-        {RF_R24,          0x16},
-        {RF_R25,          0x01},
-        {RF_R27,          0x03},
-        {RF_R29,          0x1F},
-};
-#define	NUM_RF_REG_PARMS	(sizeof(RT30xx_RFRegTable) / sizeof(REG_PAIR))
-#endif // RT2870 //
-
-//
-// ASIC register initialization sets
-//
-
-RTMP_REG_PAIR	MACRegTable[] =	{
-#if defined(HW_BEACON_OFFSET) && (HW_BEACON_OFFSET == 0x200)
-	{BCN_OFFSET0,			0xf8f0e8e0}, /* 0x3800(e0), 0x3A00(e8), 0x3C00(f0), 0x3E00(f8), 512B for each beacon */
-	{BCN_OFFSET1,			0x6f77d0c8}, /* 0x3200(c8), 0x3400(d0), 0x1DC0(77), 0x1BC0(6f), 512B for each beacon */
-#elif defined(HW_BEACON_OFFSET) && (HW_BEACON_OFFSET == 0x100)
-	{BCN_OFFSET0,			0xece8e4e0}, /* 0x3800, 0x3A00, 0x3C00, 0x3E00, 512B for each beacon */
-	{BCN_OFFSET1,			0xfcf8f4f0}, /* 0x3800, 0x3A00, 0x3C00, 0x3E00, 512B for each beacon */
-#else
-    #error You must re-calculate new value for BCN_OFFSET0 & BCN_OFFSET1 in MACRegTable[]!!!
-#endif // HW_BEACON_OFFSET //
-
-	{LEGACY_BASIC_RATE,		0x0000013f}, //  Basic rate set bitmap
-	{HT_BASIC_RATE,		0x00008003}, // Basic HT rate set , 20M, MCS=3, MM. Format is the same as in TXWI.
-	{MAC_SYS_CTRL,		0x00}, // 0x1004, , default Disable RX
-	{RX_FILTR_CFG,		0x17f97}, //0x1400  , RX filter control,
-	{BKOFF_SLOT_CFG,	0x209}, // default set short slot time, CC_DELAY_TIME should be 2
-	{TX_SW_CFG0,		0x0}, 		// Gary,2008-05-21 for CWC test
-	{TX_SW_CFG1,		0x80606}, // Gary,2006-08-23
-	{TX_LINK_CFG,		0x1020},		// Gary,2006-08-23
-	//{TX_TIMEOUT_CFG,	0x00182090},	// CCK has some problem. So increase timieout value. 2006-10-09// MArvek RT
-	{TX_TIMEOUT_CFG,	0x000a2090},	// CCK has some problem. So increase timieout value. 2006-10-09// MArvek RT , Modify for 2860E ,2007-08-01
-	{MAX_LEN_CFG,		MAX_AGGREGATION_SIZE | 0x00001000},	// 0x3018, MAX frame length. Max PSDU = 16kbytes.
-	{LED_CFG,		0x7f031e46}, // Gary, 2006-08-23
-	{PBF_MAX_PCNT,			0x1F3FBF9F}, 	//0x1F3f7f9f},		//Jan, 2006/04/20
-	//{TX_RTY_CFG,			0x6bb80408},	// Jan, 2006/11/16
-	{TX_RTY_CFG,			0x47d01f0f},	// Jan, 2006/11/16, Set TxWI->ACK =0 in Probe Rsp Modify for 2860E ,2007-08-03
-	{AUTO_RSP_CFG,			0x00000013},	// Initial Auto_Responder, because QA will turn off Auto-Responder
-	{CCK_PROT_CFG,			0x05740003 /*0x01740003*/},	// Initial Auto_Responder, because QA will turn off Auto-Responder. And RTS threshold is enabled.
-	{OFDM_PROT_CFG,			0x05740003 /*0x01740003*/},	// Initial Auto_Responder, because QA will turn off Auto-Responder. And RTS threshold is enabled.
-#ifdef RT2870
-	{PBF_CFG, 				0xf40006}, 		// Only enable Queue 2
-	{MM40_PROT_CFG,			0x3F44084},		// Initial Auto_Responder, because QA will turn off Auto-Responder
-	{WPDMA_GLO_CFG,			0x00000030},
-#endif // RT2870 //
-	{GF20_PROT_CFG,			0x01744004},    // set 19:18 --> Short NAV for MIMO PS
-	{GF40_PROT_CFG,			0x03F44084},
-	{MM20_PROT_CFG,			0x01744004},
-	{TXOP_CTRL_CFG,			0x0000583f, /*0x0000243f*/ /*0x000024bf*/},	//Extension channel backoff.
-	{TX_RTS_CFG,			0x00092b20},
-//#ifdef WIFI_TEST
-	{EXP_ACK_TIME,			0x002400ca},	// default value
-//#else
-//	{EXP_ACK_TIME,			0x005400ca},	// suggested by Gray @ 20070323 for 11n intel-sta throughput
-//#endif // end - WIFI_TEST //
-	{TXOP_HLDR_ET, 			0x00000002},
-
-	/* Jerry comments 2008/01/16: we use SIFS = 10us in CCK defaultly, but it seems that 10us
-		is too small for INTEL 2200bg card, so in MBSS mode, the delta time between beacon0
-		and beacon1 is SIFS (10us), so if INTEL 2200bg card connects to BSS0, the ping
-		will always lost. So we change the SIFS of CCK from 10us to 16us. */
-	{XIFS_TIME_CFG,			0x33a41010},
-	{PWR_PIN_CFG,			0x00000003},	// patch for 2880-E
-};
-
-
-#ifdef CONFIG_STA_SUPPORT
-RTMP_REG_PAIR	STAMACRegTable[] =	{
-	{WMM_AIFSN_CFG,		0x00002273},
-	{WMM_CWMIN_CFG,	0x00002344},
-	{WMM_CWMAX_CFG,	0x000034aa},
-};
-#endif // CONFIG_STA_SUPPORT //
-
-#define	NUM_MAC_REG_PARMS		(sizeof(MACRegTable) / sizeof(RTMP_REG_PAIR))
-#ifdef CONFIG_STA_SUPPORT
-#define	NUM_STA_MAC_REG_PARMS	(sizeof(STAMACRegTable) / sizeof(RTMP_REG_PAIR))
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef RT2870
-//
-// RT2870 Firmware Spec only used 1 oct for version expression
-//
-#define FIRMWARE_MINOR_VERSION	7
-
-#endif // RT2870 //
-
-// New 8k byte firmware size for RT3071/RT3072
-#define FIRMWAREIMAGE_MAX_LENGTH	0x2000
-#define FIRMWAREIMAGE_LENGTH		(sizeof (FirmwareImage) / sizeof(UCHAR))
-#define FIRMWARE_MAJOR_VERSION	0
-
-#define FIRMWAREIMAGEV1_LENGTH	0x1000
-#define FIRMWAREIMAGEV2_LENGTH	0x1000
-
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Allocate RTMP_ADAPTER data block and do some initialization
-
-	Arguments:
-		Adapter		Pointer to our adapter
-
-	Return Value:
-		NDIS_STATUS_SUCCESS
-		NDIS_STATUS_FAILURE
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS	RTMPAllocAdapterBlock(
-	IN  PVOID	handle,
-	OUT	PRTMP_ADAPTER	*ppAdapter)
-{
-	PRTMP_ADAPTER	pAd;
-	NDIS_STATUS		Status;
-	INT 			index;
-	UCHAR			*pBeaconBuf = NULL;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> RTMPAllocAdapterBlock\n"));
-
-	*ppAdapter = NULL;
-
-	do
-	{
-		// Allocate RTMP_ADAPTER memory block
-		pBeaconBuf = kmalloc(MAX_BEACON_SIZE, MEM_ALLOC_FLAG);
-		if (pBeaconBuf == NULL)
-		{
-			Status = NDIS_STATUS_FAILURE;
-			DBGPRINT_ERR(("Failed to allocate memory - BeaconBuf!\n"));
-			break;
-		}
-
-		Status = AdapterBlockAllocateMemory(handle, (PVOID *)&pAd);
-		if (Status != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT_ERR(("Failed to allocate memory - ADAPTER\n"));
-			break;
-		}
-		pAd->BeaconBuf = pBeaconBuf;
-		printk("\n\n=== pAd = %p, size = %d ===\n\n", pAd, (UINT32)sizeof(RTMP_ADAPTER));
-
-
-		// Init spin locks
-		NdisAllocateSpinLock(&pAd->MgmtRingLock);
-
-		for (index =0 ; index < NUM_OF_TX_RING; index++)
-		{
-			NdisAllocateSpinLock(&pAd->TxSwQueueLock[index]);
-			NdisAllocateSpinLock(&pAd->DeQueueLock[index]);
-			pAd->DeQueueRunning[index] = FALSE;
-		}
-
-		NdisAllocateSpinLock(&pAd->irq_lock);
-
-	} while (FALSE);
-
-	if ((Status != NDIS_STATUS_SUCCESS) && (pBeaconBuf))
-		kfree(pBeaconBuf);
-
-	*ppAdapter = pAd;
-
-	DBGPRINT_S(Status, ("<-- RTMPAllocAdapterBlock, Status=%x\n", Status));
-	return Status;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Read initial Tx power per MCS and BW from EEPROM
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPReadTxPwrPerRate(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	ULONG		data, Adata, Gdata;
-	USHORT		i, value, value2;
-	INT			Apwrdelta, Gpwrdelta;
-	UCHAR		t1,t2,t3,t4;
-	BOOLEAN		bValid, bApwrdeltaMinus = TRUE, bGpwrdeltaMinus = TRUE;
-
-	//
-	// Get power delta for 20MHz and 40MHz.
-	//
-	DBGPRINT(RT_DEBUG_TRACE, ("Txpower per Rate\n"));
-	RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_DELTA, value2);
-	Apwrdelta = 0;
-	Gpwrdelta = 0;
-
-	if ((value2 & 0xff) != 0xff)
-	{
-		if ((value2 & 0x80))
-			Gpwrdelta = (value2&0xf);
-
-		if ((value2 & 0x40))
-			bGpwrdeltaMinus = FALSE;
-		else
-			bGpwrdeltaMinus = TRUE;
-	}
-	if ((value2 & 0xff00) != 0xff00)
-	{
-		if ((value2 & 0x8000))
-			Apwrdelta = ((value2&0xf00)>>8);
-
-		if ((value2 & 0x4000))
-			bApwrdeltaMinus = FALSE;
-		else
-			bApwrdeltaMinus = TRUE;
-	}
-	DBGPRINT(RT_DEBUG_TRACE, ("Gpwrdelta = %x, Apwrdelta = %x .\n", Gpwrdelta, Apwrdelta));
-
-	//
-	// Get Txpower per MCS for 20MHz in 2.4G.
-	//
-	for (i=0; i<5; i++)
-	{
-		RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_20MHZ_2_4G + i*4, value);
-		data = value;
-		if (bApwrdeltaMinus == FALSE)
-		{
-			t1 = (value&0xf)+(Apwrdelta);
-			if (t1 > 0xf)
-				t1 = 0xf;
-			t2 = ((value&0xf0)>>4)+(Apwrdelta);
-			if (t2 > 0xf)
-				t2 = 0xf;
-			t3 = ((value&0xf00)>>8)+(Apwrdelta);
-			if (t3 > 0xf)
-				t3 = 0xf;
-			t4 = ((value&0xf000)>>12)+(Apwrdelta);
-			if (t4 > 0xf)
-				t4 = 0xf;
-		}
-		else
-		{
-			if ((value&0xf) > Apwrdelta)
-				t1 = (value&0xf)-(Apwrdelta);
-			else
-				t1 = 0;
-			if (((value&0xf0)>>4) > Apwrdelta)
-				t2 = ((value&0xf0)>>4)-(Apwrdelta);
-			else
-				t2 = 0;
-			if (((value&0xf00)>>8) > Apwrdelta)
-				t3 = ((value&0xf00)>>8)-(Apwrdelta);
-			else
-				t3 = 0;
-			if (((value&0xf000)>>12) > Apwrdelta)
-				t4 = ((value&0xf000)>>12)-(Apwrdelta);
-			else
-				t4 = 0;
-		}
-		Adata = t1 + (t2<<4) + (t3<<8) + (t4<<12);
-		if (bGpwrdeltaMinus == FALSE)
-		{
-			t1 = (value&0xf)+(Gpwrdelta);
-			if (t1 > 0xf)
-				t1 = 0xf;
-			t2 = ((value&0xf0)>>4)+(Gpwrdelta);
-			if (t2 > 0xf)
-				t2 = 0xf;
-			t3 = ((value&0xf00)>>8)+(Gpwrdelta);
-			if (t3 > 0xf)
-				t3 = 0xf;
-			t4 = ((value&0xf000)>>12)+(Gpwrdelta);
-			if (t4 > 0xf)
-				t4 = 0xf;
-		}
-		else
-		{
-			if ((value&0xf) > Gpwrdelta)
-				t1 = (value&0xf)-(Gpwrdelta);
-			else
-				t1 = 0;
-			if (((value&0xf0)>>4) > Gpwrdelta)
-				t2 = ((value&0xf0)>>4)-(Gpwrdelta);
-			else
-				t2 = 0;
-			if (((value&0xf00)>>8) > Gpwrdelta)
-				t3 = ((value&0xf00)>>8)-(Gpwrdelta);
-			else
-				t3 = 0;
-			if (((value&0xf000)>>12) > Gpwrdelta)
-				t4 = ((value&0xf000)>>12)-(Gpwrdelta);
-			else
-				t4 = 0;
-		}
-		Gdata = t1 + (t2<<4) + (t3<<8) + (t4<<12);
-
-		RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_20MHZ_2_4G + i*4 + 2, value);
-		if (bApwrdeltaMinus == FALSE)
-		{
-			t1 = (value&0xf)+(Apwrdelta);
-			if (t1 > 0xf)
-				t1 = 0xf;
-			t2 = ((value&0xf0)>>4)+(Apwrdelta);
-			if (t2 > 0xf)
-				t2 = 0xf;
-			t3 = ((value&0xf00)>>8)+(Apwrdelta);
-			if (t3 > 0xf)
-				t3 = 0xf;
-			t4 = ((value&0xf000)>>12)+(Apwrdelta);
-			if (t4 > 0xf)
-				t4 = 0xf;
-		}
-		else
-		{
-			if ((value&0xf) > Apwrdelta)
-				t1 = (value&0xf)-(Apwrdelta);
-			else
-				t1 = 0;
-			if (((value&0xf0)>>4) > Apwrdelta)
-				t2 = ((value&0xf0)>>4)-(Apwrdelta);
-			else
-				t2 = 0;
-			if (((value&0xf00)>>8) > Apwrdelta)
-				t3 = ((value&0xf00)>>8)-(Apwrdelta);
-			else
-				t3 = 0;
-			if (((value&0xf000)>>12) > Apwrdelta)
-				t4 = ((value&0xf000)>>12)-(Apwrdelta);
-			else
-				t4 = 0;
-		}
-		Adata |= ((t1<<16) + (t2<<20) + (t3<<24) + (t4<<28));
-		if (bGpwrdeltaMinus == FALSE)
-		{
-			t1 = (value&0xf)+(Gpwrdelta);
-			if (t1 > 0xf)
-				t1 = 0xf;
-			t2 = ((value&0xf0)>>4)+(Gpwrdelta);
-			if (t2 > 0xf)
-				t2 = 0xf;
-			t3 = ((value&0xf00)>>8)+(Gpwrdelta);
-			if (t3 > 0xf)
-				t3 = 0xf;
-			t4 = ((value&0xf000)>>12)+(Gpwrdelta);
-			if (t4 > 0xf)
-				t4 = 0xf;
-		}
-		else
-		{
-			if ((value&0xf) > Gpwrdelta)
-				t1 = (value&0xf)-(Gpwrdelta);
-			else
-				t1 = 0;
-			if (((value&0xf0)>>4) > Gpwrdelta)
-				t2 = ((value&0xf0)>>4)-(Gpwrdelta);
-			else
-				t2 = 0;
-			if (((value&0xf00)>>8) > Gpwrdelta)
-				t3 = ((value&0xf00)>>8)-(Gpwrdelta);
-			else
-				t3 = 0;
-			if (((value&0xf000)>>12) > Gpwrdelta)
-				t4 = ((value&0xf000)>>12)-(Gpwrdelta);
-			else
-				t4 = 0;
-		}
-		Gdata |= ((t1<<16) + (t2<<20) + (t3<<24) + (t4<<28));
-		data |= (value<<16);
-
-		pAd->Tx20MPwrCfgABand[i] = pAd->Tx40MPwrCfgABand[i] = Adata;
-		pAd->Tx20MPwrCfgGBand[i] = pAd->Tx40MPwrCfgGBand[i] = Gdata;
-
-		if (data != 0xffffffff)
-			RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, data);
-		DBGPRINT_RAW(RT_DEBUG_TRACE, ("20MHz BW, 2.4G band-%lx,  Adata = %lx,  Gdata = %lx \n", data, Adata, Gdata));
-	}
-
-	//
-	// Check this block is valid for 40MHz in 2.4G. If invalid, use parameter for 20MHz in 2.4G
-	//
-	bValid = TRUE;
-	for (i=0; i<6; i++)
-	{
-		RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_2_4G + 2 + i*2, value);
-		if (((value & 0x00FF) == 0x00FF) || ((value & 0xFF00) == 0xFF00))
-		{
-			bValid = FALSE;
-			break;
-		}
-	}
-
-	//
-	// Get Txpower per MCS for 40MHz in 2.4G.
-	//
-	if (bValid)
-	{
-		for (i=0; i<4; i++)
-		{
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_2_4G + i*4, value);
-			if (bGpwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Gpwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Gpwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Gpwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Gpwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Gpwrdelta)
-					t1 = (value&0xf)-(Gpwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Gpwrdelta)
-					t2 = ((value&0xf0)>>4)-(Gpwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Gpwrdelta)
-					t3 = ((value&0xf00)>>8)-(Gpwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Gpwrdelta)
-					t4 = ((value&0xf000)>>12)-(Gpwrdelta);
-				else
-					t4 = 0;
-			}
-			Gdata = t1 + (t2<<4) + (t3<<8) + (t4<<12);
-
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_2_4G + i*4 + 2, value);
-			if (bGpwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Gpwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Gpwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Gpwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Gpwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Gpwrdelta)
-					t1 = (value&0xf)-(Gpwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Gpwrdelta)
-					t2 = ((value&0xf0)>>4)-(Gpwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Gpwrdelta)
-					t3 = ((value&0xf00)>>8)-(Gpwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Gpwrdelta)
-					t4 = ((value&0xf000)>>12)-(Gpwrdelta);
-				else
-					t4 = 0;
-			}
-			Gdata |= ((t1<<16) + (t2<<20) + (t3<<24) + (t4<<28));
-
-			if (i == 0)
-				pAd->Tx40MPwrCfgGBand[i+1] = (pAd->Tx40MPwrCfgGBand[i+1] & 0x0000FFFF) | (Gdata & 0xFFFF0000);
-			else
-				pAd->Tx40MPwrCfgGBand[i+1] = Gdata;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE, ("40MHz BW, 2.4G band, Gdata = %lx \n", Gdata));
-		}
-	}
-
-	//
-	// Check this block is valid for 20MHz in 5G. If invalid, use parameter for 20MHz in 2.4G
-	//
-	bValid = TRUE;
-	for (i=0; i<8; i++)
-	{
-		RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_20MHZ_5G + 2 + i*2, value);
-		if (((value & 0x00FF) == 0x00FF) || ((value & 0xFF00) == 0xFF00))
-		{
-			bValid = FALSE;
-			break;
-		}
-	}
-
-	//
-	// Get Txpower per MCS for 20MHz in 5G.
-	//
-	if (bValid)
-	{
-		for (i=0; i<5; i++)
-		{
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_20MHZ_5G + i*4, value);
-			if (bApwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Apwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Apwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Apwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Apwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Apwrdelta)
-					t1 = (value&0xf)-(Apwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Apwrdelta)
-					t2 = ((value&0xf0)>>4)-(Apwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Apwrdelta)
-					t3 = ((value&0xf00)>>8)-(Apwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Apwrdelta)
-					t4 = ((value&0xf000)>>12)-(Apwrdelta);
-				else
-					t4 = 0;
-			}
-			Adata = t1 + (t2<<4) + (t3<<8) + (t4<<12);
-
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_20MHZ_5G + i*4 + 2, value);
-			if (bApwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Apwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Apwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Apwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Apwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Apwrdelta)
-					t1 = (value&0xf)-(Apwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Apwrdelta)
-					t2 = ((value&0xf0)>>4)-(Apwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Apwrdelta)
-					t3 = ((value&0xf00)>>8)-(Apwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Apwrdelta)
-					t4 = ((value&0xf000)>>12)-(Apwrdelta);
-				else
-					t4 = 0;
-			}
-			Adata |= ((t1<<16) + (t2<<20) + (t3<<24) + (t4<<28));
-
-			if (i == 0)
-				pAd->Tx20MPwrCfgABand[i] = (pAd->Tx20MPwrCfgABand[i] & 0x0000FFFF) | (Adata & 0xFFFF0000);
-			else
-				pAd->Tx20MPwrCfgABand[i] = Adata;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE, ("20MHz BW, 5GHz band, Adata = %lx \n", Adata));
-		}
-	}
-
-	//
-	// Check this block is valid for 40MHz in 5G. If invalid, use parameter for 20MHz in 2.4G
-	//
-	bValid = TRUE;
-	for (i=0; i<6; i++)
-	{
-		RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_5G + 2 + i*2, value);
-		if (((value & 0x00FF) == 0x00FF) || ((value & 0xFF00) == 0xFF00))
-		{
-			bValid = FALSE;
-			break;
-		}
-	}
-
-	//
-	// Get Txpower per MCS for 40MHz in 5G.
-	//
-	if (bValid)
-	{
-		for (i=0; i<4; i++)
-		{
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_5G + i*4, value);
-			if (bApwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Apwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Apwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Apwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Apwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Apwrdelta)
-					t1 = (value&0xf)-(Apwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Apwrdelta)
-					t2 = ((value&0xf0)>>4)-(Apwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Apwrdelta)
-					t3 = ((value&0xf00)>>8)-(Apwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Apwrdelta)
-					t4 = ((value&0xf000)>>12)-(Apwrdelta);
-				else
-					t4 = 0;
-			}
-			Adata = t1 + (t2<<4) + (t3<<8) + (t4<<12);
-
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_5G + i*4 + 2, value);
-			if (bApwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Apwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Apwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Apwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Apwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Apwrdelta)
-					t1 = (value&0xf)-(Apwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Apwrdelta)
-					t2 = ((value&0xf0)>>4)-(Apwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Apwrdelta)
-					t3 = ((value&0xf00)>>8)-(Apwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Apwrdelta)
-					t4 = ((value&0xf000)>>12)-(Apwrdelta);
-				else
-					t4 = 0;
-			}
-			Adata |= ((t1<<16) + (t2<<20) + (t3<<24) + (t4<<28));
-
-			if (i == 0)
-				pAd->Tx40MPwrCfgABand[i+1] = (pAd->Tx40MPwrCfgABand[i+1] & 0x0000FFFF) | (Adata & 0xFFFF0000);
-			else
-				pAd->Tx40MPwrCfgABand[i+1] = Adata;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE, ("40MHz BW, 5GHz band, Adata = %lx \n", Adata));
-		}
-	}
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Read initial channel power parameters from EEPROM
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPReadChannelPwr(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UCHAR				i, choffset;
-	EEPROM_TX_PWR_STRUC	    Power;
-	EEPROM_TX_PWR_STRUC	    Power2;
-
-	// Read Tx power value for all channels
-	// Value from 1 - 0x7f. Default value is 24.
-	// Power value : 2.4G 0x00 (0) ~ 0x1F (31)
-	//             : 5.5G 0xF9 (-7) ~ 0x0F (15)
-
-	// 0. 11b/g, ch1 - ch 14
-	for (i = 0; i < 7; i++)
-	{
-//		Power.word = RTMP_EEPROM_READ16(pAd, EEPROM_G_TX_PWR_OFFSET + i * 2);
-//		Power2.word = RTMP_EEPROM_READ16(pAd, EEPROM_G_TX2_PWR_OFFSET + i * 2);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_G_TX_PWR_OFFSET + i * 2, Power.word);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_G_TX2_PWR_OFFSET + i * 2, Power2.word);
-		pAd->TxPower[i * 2].Channel = i * 2 + 1;
-		pAd->TxPower[i * 2 + 1].Channel = i * 2 + 2;
-
-		if ((Power.field.Byte0 > 31) || (Power.field.Byte0 < 0))
-			pAd->TxPower[i * 2].Power = DEFAULT_RF_TX_POWER;
-		else
-			pAd->TxPower[i * 2].Power = Power.field.Byte0;
-
-		if ((Power.field.Byte1 > 31) || (Power.field.Byte1 < 0))
-			pAd->TxPower[i * 2 + 1].Power = DEFAULT_RF_TX_POWER;
-		else
-			pAd->TxPower[i * 2 + 1].Power = Power.field.Byte1;
-
-		if ((Power2.field.Byte0 > 31) || (Power2.field.Byte0 < 0))
-			pAd->TxPower[i * 2].Power2 = DEFAULT_RF_TX_POWER;
-		else
-			pAd->TxPower[i * 2].Power2 = Power2.field.Byte0;
-
-		if ((Power2.field.Byte1 > 31) || (Power2.field.Byte1 < 0))
-			pAd->TxPower[i * 2 + 1].Power2 = DEFAULT_RF_TX_POWER;
-		else
-			pAd->TxPower[i * 2 + 1].Power2 = Power2.field.Byte1;
-	}
-
-	// 1. U-NII lower/middle band: 36, 38, 40; 44, 46, 48; 52, 54, 56; 60, 62, 64 (including central frequency in BW 40MHz)
-	// 1.1 Fill up channel
-	choffset = 14;
-	for (i = 0; i < 4; i++)
-	{
-		pAd->TxPower[3 * i + choffset + 0].Channel	= 36 + i * 8 + 0;
-		pAd->TxPower[3 * i + choffset + 0].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 0].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 1].Channel	= 36 + i * 8 + 2;
-		pAd->TxPower[3 * i + choffset + 1].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 1].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 2].Channel	= 36 + i * 8 + 4;
-		pAd->TxPower[3 * i + choffset + 2].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 2].Power2	= DEFAULT_RF_TX_POWER;
-	}
-
-	// 1.2 Fill up power
-	for (i = 0; i < 6; i++)
-	{
-//		Power.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + i * 2);
-//		Power2.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + i * 2);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + i * 2, Power.word);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + i * 2, Power2.word);
-
-		if ((Power.field.Byte0 < 16) && (Power.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power = Power.field.Byte0;
-
-		if ((Power.field.Byte1 < 16) && (Power.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power = Power.field.Byte1;
-
-		if ((Power2.field.Byte0 < 16) && (Power2.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power2 = Power2.field.Byte0;
-
-		if ((Power2.field.Byte1 < 16) && (Power2.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power2 = Power2.field.Byte1;
-	}
-
-	// 2. HipperLAN 2 100, 102 ,104; 108, 110, 112; 116, 118, 120; 124, 126, 128; 132, 134, 136; 140 (including central frequency in BW 40MHz)
-	// 2.1 Fill up channel
-	choffset = 14 + 12;
-	for (i = 0; i < 5; i++)
-	{
-		pAd->TxPower[3 * i + choffset + 0].Channel	= 100 + i * 8 + 0;
-		pAd->TxPower[3 * i + choffset + 0].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 0].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 1].Channel	= 100 + i * 8 + 2;
-		pAd->TxPower[3 * i + choffset + 1].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 1].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 2].Channel	= 100 + i * 8 + 4;
-		pAd->TxPower[3 * i + choffset + 2].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 2].Power2	= DEFAULT_RF_TX_POWER;
-	}
-	pAd->TxPower[3 * 5 + choffset + 0].Channel		= 140;
-	pAd->TxPower[3 * 5 + choffset + 0].Power		= DEFAULT_RF_TX_POWER;
-	pAd->TxPower[3 * 5 + choffset + 0].Power2		= DEFAULT_RF_TX_POWER;
-
-	// 2.2 Fill up power
-	for (i = 0; i < 8; i++)
-	{
-//		Power.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + (choffset - 14) + i * 2);
-//		Power2.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + (choffset - 14) + i * 2);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + (choffset - 14) + i * 2, Power.word);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + (choffset - 14) + i * 2, Power2.word);
-
-		if ((Power.field.Byte0 < 16) && (Power.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power = Power.field.Byte0;
-
-		if ((Power.field.Byte1 < 16) && (Power.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power = Power.field.Byte1;
-
-		if ((Power2.field.Byte0 < 16) && (Power2.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power2 = Power2.field.Byte0;
-
-		if ((Power2.field.Byte1 < 16) && (Power2.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power2 = Power2.field.Byte1;
-	}
-
-	// 3. U-NII upper band: 149, 151, 153; 157, 159, 161; 165 (including central frequency in BW 40MHz)
-	// 3.1 Fill up channel
-	choffset = 14 + 12 + 16;
-	for (i = 0; i < 2; i++)
-	{
-		pAd->TxPower[3 * i + choffset + 0].Channel	= 149 + i * 8 + 0;
-		pAd->TxPower[3 * i + choffset + 0].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 0].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 1].Channel	= 149 + i * 8 + 2;
-		pAd->TxPower[3 * i + choffset + 1].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 1].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 2].Channel	= 149 + i * 8 + 4;
-		pAd->TxPower[3 * i + choffset + 2].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 2].Power2	= DEFAULT_RF_TX_POWER;
-	}
-	pAd->TxPower[3 * 2 + choffset + 0].Channel		= 165;
-	pAd->TxPower[3 * 2 + choffset + 0].Power		= DEFAULT_RF_TX_POWER;
-	pAd->TxPower[3 * 2 + choffset + 0].Power2		= DEFAULT_RF_TX_POWER;
-
-	// 3.2 Fill up power
-	for (i = 0; i < 4; i++)
-	{
-//		Power.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + (choffset - 14) + i * 2);
-//		Power2.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + (choffset - 14) + i * 2);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + (choffset - 14) + i * 2, Power.word);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + (choffset - 14) + i * 2, Power2.word);
-
-		if ((Power.field.Byte0 < 16) && (Power.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power = Power.field.Byte0;
-
-		if ((Power.field.Byte1 < 16) && (Power.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power = Power.field.Byte1;
-
-		if ((Power2.field.Byte0 < 16) && (Power2.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power2 = Power2.field.Byte0;
-
-		if ((Power2.field.Byte1 < 16) && (Power2.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power2 = Power2.field.Byte1;
-	}
-
-	// 4. Print and Debug
-	choffset = 14 + 12 + 16 + 7;
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Read the following from the registry
-		1. All the parameters
-		2. NetworkAddres
-
-	Arguments:
-		Adapter						Pointer to our adapter
-		WrapperConfigurationContext	For use by NdisOpenConfiguration
-
-	Return Value:
-		NDIS_STATUS_SUCCESS
-		NDIS_STATUS_FAILURE
-		NDIS_STATUS_RESOURCES
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS	NICReadRegParameters(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	NDIS_HANDLE			WrapperConfigurationContext
-	)
-{
-	NDIS_STATUS						Status = NDIS_STATUS_SUCCESS;
-	DBGPRINT_S(Status, ("<-- NICReadRegParameters, Status=%x\n", Status));
-	return Status;
-}
-
-
-#ifdef RT2870
-/*
-	========================================================================
-
-	Routine Description:
-		For RF filter calibration purpose
-
-	Arguments:
-		pAd                          Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-VOID RTUSBFilterCalibration(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR	R55x = 0, value, FilterTarget = 0x1E, BBPValue;
-	UINT	loop = 0, count = 0, loopcnt = 0, ReTry = 0;
-	UCHAR	RF_R24_Value = 0;
-
-	// Give bbp filter initial value
-	pAd->Mlme.CaliBW20RfR24 = 0x16;
-	pAd->Mlme.CaliBW40RfR24 = 0x36;  //Bit[5] must be 1 for BW 40
-
-	do
-	{
-		if (loop == 1)	//BandWidth = 40 MHz
-		{
-			// Write 0x27 to RF_R24 to program filter
-			RF_R24_Value = 0x27;
-			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
-			FilterTarget = 0x19;
-
-			// when calibrate BW40, BBP mask must set to BW40.
-			RTUSBReadBBPRegister(pAd, BBP_R4, &BBPValue);
-			BBPValue&= (~0x18);
-			BBPValue|= (0x10);
-			RTUSBWriteBBPRegister(pAd, BBP_R4, BBPValue);
-		}
-		else			//BandWidth = 20 MHz
-		{
-			// Write 0x07 to RF_R24 to program filter
-			RF_R24_Value = 0x07;
-			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
-			FilterTarget = 0x16;
-		}
-
-		// Write 0x01 to RF_R22 to enable baseband loopback mode
-		RT30xxReadRFRegister(pAd, RF_R22, &value);
-		value |= 0x01;
-		RT30xxWriteRFRegister(pAd, RF_R22, value);
-
-		// Write 0x00 to BBP_R24 to set power & frequency of passband test tone
-		RTUSBWriteBBPRegister(pAd, BBP_R24, 0);
-
-		do
-		{
-			// Write 0x90 to BBP_R25 to transmit test tone
-			RTUSBWriteBBPRegister(pAd, BBP_R25, 0x90);
-
-			RTMPusecDelay(1000);
-			// Read BBP_R55[6:0] for received power, set R55x = BBP_R55[6:0]
-			RTUSBReadBBPRegister(pAd, BBP_R55, &value);
-			R55x = value & 0xFF;
-
-		} while ((ReTry++ < 100) && (R55x == 0));
-
-		// Write 0x06 to BBP_R24 to set power & frequency of stopband test tone
-		RTUSBWriteBBPRegister(pAd, BBP_R24, 0x06);
-
-		while(TRUE)
-		{
-			// Write 0x90 to BBP_R25 to transmit test tone
-			RTUSBWriteBBPRegister(pAd, BBP_R25, 0x90);
-
-			//We need to wait for calibration
-			RTMPusecDelay(1000);
-			RTUSBReadBBPRegister(pAd, BBP_R55, &value);
-			value &= 0xFF;
-			if ((R55x - value) < FilterTarget)
-			{
-				RF_R24_Value ++;
-			}
-			else if ((R55x - value) == FilterTarget)
-			{
-				RF_R24_Value ++;
-				count ++;
-			}
-			else
-			{
-				break;
-			}
-
-			// prevent infinite loop cause driver hang.
-			if (loopcnt++ > 100)
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("RTUSBFilterCalibration - can't find a valid value, loopcnt=%d stop calibrating", loopcnt));
-				break;
-			}
-
-			// Write RF_R24 to program filter
-			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
-		}
-
-		if (count > 0)
-		{
-			RF_R24_Value = RF_R24_Value - ((count) ? (1) : (0));
-		}
-
-		// Store for future usage
-		if (loopcnt < 100)
-		{
-			if (loop++ == 0)
-			{
-				//BandWidth = 20 MHz
-				pAd->Mlme.CaliBW20RfR24 = (UCHAR)RF_R24_Value;
-			}
-			else
-			{
-				//BandWidth = 40 MHz
-				pAd->Mlme.CaliBW40RfR24 = (UCHAR)RF_R24_Value;
-				break;
-			}
-		}
-		else
-			break;
-
-		RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
-
-		// reset count
-		count = 0;
-	} while(TRUE);
-
-	//
-	// Set back to initial state
-	//
-	RTUSBWriteBBPRegister(pAd, BBP_R24, 0);
-
-	RT30xxReadRFRegister(pAd, RF_R22, &value);
-	value &= ~(0x01);
-	RT30xxWriteRFRegister(pAd, RF_R22, value);
-
-	// set BBP back to BW20
-	RTUSBReadBBPRegister(pAd, BBP_R4, &BBPValue);
-	BBPValue&= (~0x18);
-	RTUSBWriteBBPRegister(pAd, BBP_R4, BBPValue);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTUSBFilterCalibration - CaliBW20RfR24=0x%x, CaliBW40RfR24=0x%x\n", pAd->Mlme.CaliBW20RfR24, pAd->Mlme.CaliBW40RfR24));
-}
-
-
-VOID NICInitRT30xxRFRegisters(IN PRTMP_ADAPTER pAd)
-{
-	INT i;
-	// Driver must read EEPROM to get RfIcType before initial RF registers
-	// Initialize RF register to default value
-        if (IS_RT3070(pAd) && ((pAd->RfIcType == RFIC_3020) ||(pAd->RfIcType == RFIC_2020)))
-        {
-                // Init RF calibration
-                // Driver should toggle RF R30 bit7 before init RF registers
-                ULONG RfReg = 0;
-                RT30xxReadRFRegister(pAd, RF_R30, (PUCHAR)&RfReg);
-                RfReg |= 0x80;
-                RT30xxWriteRFRegister(pAd, RF_R30, (UCHAR)RfReg);
-                RTMPusecDelay(1000);
-                RfReg &= 0x7F;
-                RT30xxWriteRFRegister(pAd, RF_R30, (UCHAR)RfReg);
-
-                // Initialize RF register to default value
-                for (i = 0; i < NUM_RF_REG_PARMS; i++)
-                {
-                        RT30xxWriteRFRegister(pAd, RT30xx_RFRegTable[i].Register, RT30xx_RFRegTable[i].Value);
-                }
-
-                //For RF filter Calibration
-                RTUSBFilterCalibration(pAd);
-        }
-
-}
-#endif // RT2870 //
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Read initial parameters from EEPROM
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	NICReadEEPROMParameters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			mac_addr)
-{
-	UINT32			data = 0;
-	USHORT			i, value, value2;
-	UCHAR			TmpPhy;
-	EEPROM_TX_PWR_STRUC	    Power;
-	EEPROM_VERSION_STRUC    Version;
-	EEPROM_ANTENNA_STRUC	Antenna;
-	EEPROM_NIC_CONFIG2_STRUC    NicConfig2;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICReadEEPROMParameters\n"));
-
-	// Init EEPROM Address Number, before access EEPROM; if 93c46, EEPROMAddressNum=6, else if 93c66, EEPROMAddressNum=8
-	RTMP_IO_READ32(pAd, E2PROM_CSR, &data);
-	DBGPRINT(RT_DEBUG_TRACE, ("--> E2PROM_CSR = 0x%x\n", data));
-
-	if((data & 0x30) == 0)
-		pAd->EEPROMAddressNum = 6;		// 93C46
-	else if((data & 0x30) == 0x10)
-		pAd->EEPROMAddressNum = 8;     // 93C66
-	else
-		pAd->EEPROMAddressNum = 8;     // 93C86
-	DBGPRINT(RT_DEBUG_TRACE, ("--> EEPROMAddressNum = %d\n", pAd->EEPROMAddressNum ));
-
-	// RT2860 MAC no longer auto load MAC address from E2PROM. Driver has to intialize
-	// MAC address registers according to E2PROM setting
-	if (mac_addr == NULL ||
-		strlen(mac_addr) != 17 ||
-		mac_addr[2] != ':'  || mac_addr[5] != ':'  || mac_addr[8] != ':' ||
-		mac_addr[11] != ':' || mac_addr[14] != ':')
-	{
-		USHORT  Addr01,Addr23,Addr45 ;
-
-		RT28xx_EEPROM_READ16(pAd, 0x04, Addr01);
-		RT28xx_EEPROM_READ16(pAd, 0x06, Addr23);
-		RT28xx_EEPROM_READ16(pAd, 0x08, Addr45);
-
-		pAd->PermanentAddress[0] = (UCHAR)(Addr01 & 0xff);
-		pAd->PermanentAddress[1] = (UCHAR)(Addr01 >> 8);
-		pAd->PermanentAddress[2] = (UCHAR)(Addr23 & 0xff);
-		pAd->PermanentAddress[3] = (UCHAR)(Addr23 >> 8);
-		pAd->PermanentAddress[4] = (UCHAR)(Addr45 & 0xff);
-		pAd->PermanentAddress[5] = (UCHAR)(Addr45 >> 8);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Initialize MAC Address from E2PROM \n"));
-	}
-	else
-	{
-		INT		j;
-		PUCHAR	macptr;
-
-		macptr = mac_addr;
-
-		for (j=0; j<MAC_ADDR_LEN; j++)
-		{
-			AtoH(macptr, &pAd->PermanentAddress[j], 1);
-			macptr=macptr+3;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Initialize MAC Address from module parameter \n"));
-	}
-
-
-	{
-#if 0
-		USHORT  Addr01,Addr23,Addr45 ;
-
-		Addr01=RTMP_EEPROM_READ16(pAd, 0x04);
-		Addr23=RTMP_EEPROM_READ16(pAd, 0x06);
-		Addr45=RTMP_EEPROM_READ16(pAd, 0x08);
-
-		pAd->PermanentAddress[0] = (UCHAR)(Addr01 & 0xff);
-		pAd->PermanentAddress[1] = (UCHAR)(Addr01 >> 8);
-		pAd->PermanentAddress[2] = (UCHAR)(Addr23 & 0xff);
-		pAd->PermanentAddress[3] = (UCHAR)(Addr23 >> 8);
-		pAd->PermanentAddress[4] = (UCHAR)(Addr45 & 0xff);
-		pAd->PermanentAddress[5] = (UCHAR)(Addr45 >> 8);
-#endif
-		//more conveninet to test mbssid, so ap's bssid &0xf1
-		if (pAd->PermanentAddress[0] == 0xff)
-			pAd->PermanentAddress[0] = RandomByte(pAd)&0xf8;
-
-		//if (pAd->PermanentAddress[5] == 0xff)
-		//	pAd->PermanentAddress[5] = RandomByte(pAd)&0xf8;
-
-		DBGPRINT_RAW(RT_DEBUG_TRACE,("E2PROM MAC: =%02x:%02x:%02x:%02x:%02x:%02x\n",
-			pAd->PermanentAddress[0], pAd->PermanentAddress[1],
-			pAd->PermanentAddress[2], pAd->PermanentAddress[3],
-			pAd->PermanentAddress[4], pAd->PermanentAddress[5]));
-		if (pAd->bLocalAdminMAC == FALSE)
-		{
-			MAC_DW0_STRUC csr2;
-			MAC_DW1_STRUC csr3;
-			COPY_MAC_ADDR(pAd->CurrentAddress, pAd->PermanentAddress);
-			csr2.field.Byte0 = pAd->CurrentAddress[0];
-			csr2.field.Byte1 = pAd->CurrentAddress[1];
-			csr2.field.Byte2 = pAd->CurrentAddress[2];
-			csr2.field.Byte3 = pAd->CurrentAddress[3];
-			RTMP_IO_WRITE32(pAd, MAC_ADDR_DW0, csr2.word);
-			csr3.word = 0;
-			csr3.field.Byte4 = pAd->CurrentAddress[4];
-			csr3.field.Byte5 = pAd->CurrentAddress[5];
-			csr3.field.U2MeMask = 0xff;
-			RTMP_IO_WRITE32(pAd, MAC_ADDR_DW1, csr3.word);
-			DBGPRINT_RAW(RT_DEBUG_TRACE,("E2PROM MAC: =%02x:%02x:%02x:%02x:%02x:%02x\n",
-				pAd->PermanentAddress[0], pAd->PermanentAddress[1],
-				pAd->PermanentAddress[2], pAd->PermanentAddress[3],
-				pAd->PermanentAddress[4], pAd->PermanentAddress[5]));
-		}
-	}
-
-	// if not return early. cause fail at emulation.
-	// Init the channel number for TX channel power
-	RTMPReadChannelPwr(pAd);
-
-	// if E2PROM version mismatch with driver's expectation, then skip
-	// all subsequent E2RPOM retieval and set a system error bit to notify GUI
-	RT28xx_EEPROM_READ16(pAd, EEPROM_VERSION_OFFSET, Version.word);
-	pAd->EepromVersion = Version.field.Version + Version.field.FaeReleaseNumber * 256;
-	DBGPRINT(RT_DEBUG_TRACE, ("E2PROM: Version = %d, FAE release #%d\n", Version.field.Version, Version.field.FaeReleaseNumber));
-
-	if (Version.field.Version > VALID_EEPROM_VERSION)
-	{
-		DBGPRINT_ERR(("E2PROM: WRONG VERSION 0x%x, should be %d\n",Version.field.Version, VALID_EEPROM_VERSION));
-		/*pAd->SystemErrorBitmap |= 0x00000001;
-
-		// hard-code default value when no proper E2PROM installed
-		pAd->bAutoTxAgcA = FALSE;
-		pAd->bAutoTxAgcG = FALSE;
-
-		// Default the channel power
-		for (i = 0; i < MAX_NUM_OF_CHANNELS; i++)
-			pAd->TxPower[i].Power = DEFAULT_RF_TX_POWER;
-
-		// Default the channel power
-		for (i = 0; i < MAX_NUM_OF_11JCHANNELS; i++)
-			pAd->TxPower11J[i].Power = DEFAULT_RF_TX_POWER;
-
-		for(i = 0; i < NUM_EEPROM_BBP_PARMS; i++)
-			pAd->EEPROMDefaultValue[i] = 0xffff;
-		return;  */
-	}
-
-	// Read BBP default value from EEPROM and store to array(EEPROMDefaultValue) in pAd
-	RT28xx_EEPROM_READ16(pAd, EEPROM_NIC1_OFFSET, value);
-	pAd->EEPROMDefaultValue[0] = value;
-
-	RT28xx_EEPROM_READ16(pAd, EEPROM_NIC2_OFFSET, value);
-	pAd->EEPROMDefaultValue[1] = value;
-
-	RT28xx_EEPROM_READ16(pAd, 0x38, value);	// Country Region
-	pAd->EEPROMDefaultValue[2] = value;
-
-	for(i = 0; i < 8; i++)
-	{
-		RT28xx_EEPROM_READ16(pAd, EEPROM_BBP_BASE_OFFSET + i*2, value);
-		pAd->EEPROMDefaultValue[i+3] = value;
-	}
-
-	// We have to parse NIC configuration 0 at here.
-	// If TSSI did not have preloaded value, it should reset the TxAutoAgc to false
-	// Therefore, we have to read TxAutoAgc control beforehand.
-	// Read Tx AGC control bit
-	Antenna.word = pAd->EEPROMDefaultValue[0];
-	if (Antenna.word == 0xFFFF)
-	{
-		Antenna.word = 0;
-		Antenna.field.RfIcType = RFIC_2820;
-		Antenna.field.TxPath = 1;
-		Antenna.field.RxPath = 2;
-		DBGPRINT(RT_DEBUG_WARN, ("E2PROM error, hard code as 0x%04x\n", Antenna.word));
-	}
-
-	// Choose the desired Tx&Rx stream.
-	if ((pAd->CommonCfg.TxStream == 0) || (pAd->CommonCfg.TxStream > Antenna.field.TxPath))
-		pAd->CommonCfg.TxStream = Antenna.field.TxPath;
-
-	if ((pAd->CommonCfg.RxStream == 0) || (pAd->CommonCfg.RxStream > Antenna.field.RxPath))
-	{
-		pAd->CommonCfg.RxStream = Antenna.field.RxPath;
-
-		if ((pAd->MACVersion < RALINK_2883_VERSION) &&
-			(pAd->CommonCfg.RxStream > 2))
-		{
-			// only 2 Rx streams for RT2860 series
-			pAd->CommonCfg.RxStream = 2;
-		}
-	}
-
-	// 3*3
-	// read value from EEPROM and set them to CSR174 ~ 177 in chain0 ~ chain2
-	// yet implement
-	for(i=0; i<3; i++)
-	{
-	}
-
-	NicConfig2.word = pAd->EEPROMDefaultValue[1];
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		NicConfig2.word = 0;
-		if ((NicConfig2.word & 0x00ff) == 0xff)
-		{
-			NicConfig2.word &= 0xff00;
-		}
-
-		if ((NicConfig2.word >> 8) == 0xff)
-		{
-			NicConfig2.word &= 0x00ff;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	if (NicConfig2.field.DynamicTxAgcControl == 1)
-		pAd->bAutoTxAgcA = pAd->bAutoTxAgcG = TRUE;
-	else
-		pAd->bAutoTxAgcA = pAd->bAutoTxAgcG = FALSE;
-
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("NICReadEEPROMParameters: RxPath = %d, TxPath = %d\n", Antenna.field.RxPath, Antenna.field.TxPath));
-
-	// Save the antenna for future use
-	pAd->Antenna.word = Antenna.word;
-
-	//
-	// Reset PhyMode if we don't support 802.11a
-	// Only RFIC_2850 & RFIC_2750 support 802.11a
-	//
-	if ((Antenna.field.RfIcType != RFIC_2850) && (Antenna.field.RfIcType != RFIC_2750))
-	{
-		if ((pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED) ||
-			(pAd->CommonCfg.PhyMode == PHY_11A))
-			pAd->CommonCfg.PhyMode = PHY_11BG_MIXED;
-#ifdef DOT11_N_SUPPORT
-		else if ((pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED)	||
-				 (pAd->CommonCfg.PhyMode == PHY_11AN_MIXED) 	||
-				 (pAd->CommonCfg.PhyMode == PHY_11AGN_MIXED) 	||
-				 (pAd->CommonCfg.PhyMode == PHY_11N_5G))
-			pAd->CommonCfg.PhyMode = PHY_11BGN_MIXED;
-#endif // DOT11_N_SUPPORT //
-	}
-
-	// Read TSSI reference and TSSI boundary for temperature compensation. This is ugly
-	// 0. 11b/g
-	{
-		/* these are tempature reference value (0x00 ~ 0xFE)
-		   ex: 0x00 0x15 0x25 0x45 0x88 0xA0 0xB5 0xD0 0xF0
-		   TssiPlusBoundaryG [4] [3] [2] [1] [0] (smaller) +
-		   TssiMinusBoundaryG[0] [1] [2] [3] [4] (larger) */
-		RT28xx_EEPROM_READ16(pAd, 0x6E, Power.word);
-		pAd->TssiMinusBoundaryG[4] = Power.field.Byte0;
-		pAd->TssiMinusBoundaryG[3] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0x70, Power.word);
-		pAd->TssiMinusBoundaryG[2] = Power.field.Byte0;
-		pAd->TssiMinusBoundaryG[1] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0x72, Power.word);
-		pAd->TssiRefG   = Power.field.Byte0; /* reference value [0] */
-		pAd->TssiPlusBoundaryG[1] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0x74, Power.word);
-		pAd->TssiPlusBoundaryG[2] = Power.field.Byte0;
-		pAd->TssiPlusBoundaryG[3] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0x76, Power.word);
-		pAd->TssiPlusBoundaryG[4] = Power.field.Byte0;
-		pAd->TxAgcStepG = Power.field.Byte1;
-		pAd->TxAgcCompensateG = 0;
-		pAd->TssiMinusBoundaryG[0] = pAd->TssiRefG;
-		pAd->TssiPlusBoundaryG[0]  = pAd->TssiRefG;
-
-		// Disable TxAgc if the based value is not right
-		if (pAd->TssiRefG == 0xff)
-			pAd->bAutoTxAgcG = FALSE;
-
-		DBGPRINT(RT_DEBUG_TRACE,("E2PROM: G Tssi[-4 .. +4] = %d %d %d %d - %d -%d %d %d %d, step=%d, tuning=%d\n",
-			pAd->TssiMinusBoundaryG[4], pAd->TssiMinusBoundaryG[3], pAd->TssiMinusBoundaryG[2], pAd->TssiMinusBoundaryG[1],
-			pAd->TssiRefG,
-			pAd->TssiPlusBoundaryG[1], pAd->TssiPlusBoundaryG[2], pAd->TssiPlusBoundaryG[3], pAd->TssiPlusBoundaryG[4],
-			pAd->TxAgcStepG, pAd->bAutoTxAgcG));
-	}
-	// 1. 11a
-	{
-		RT28xx_EEPROM_READ16(pAd, 0xD4, Power.word);
-		pAd->TssiMinusBoundaryA[4] = Power.field.Byte0;
-		pAd->TssiMinusBoundaryA[3] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0xD6, Power.word);
-		pAd->TssiMinusBoundaryA[2] = Power.field.Byte0;
-		pAd->TssiMinusBoundaryA[1] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0xD8, Power.word);
-		pAd->TssiRefA   = Power.field.Byte0;
-		pAd->TssiPlusBoundaryA[1] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0xDA, Power.word);
-		pAd->TssiPlusBoundaryA[2] = Power.field.Byte0;
-		pAd->TssiPlusBoundaryA[3] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0xDC, Power.word);
-		pAd->TssiPlusBoundaryA[4] = Power.field.Byte0;
-		pAd->TxAgcStepA = Power.field.Byte1;
-		pAd->TxAgcCompensateA = 0;
-		pAd->TssiMinusBoundaryA[0] = pAd->TssiRefA;
-		pAd->TssiPlusBoundaryA[0]  = pAd->TssiRefA;
-
-		// Disable TxAgc if the based value is not right
-		if (pAd->TssiRefA == 0xff)
-			pAd->bAutoTxAgcA = FALSE;
-
-		DBGPRINT(RT_DEBUG_TRACE,("E2PROM: A Tssi[-4 .. +4] = %d %d %d %d - %d -%d %d %d %d, step=%d, tuning=%d\n",
-			pAd->TssiMinusBoundaryA[4], pAd->TssiMinusBoundaryA[3], pAd->TssiMinusBoundaryA[2], pAd->TssiMinusBoundaryA[1],
-			pAd->TssiRefA,
-			pAd->TssiPlusBoundaryA[1], pAd->TssiPlusBoundaryA[2], pAd->TssiPlusBoundaryA[3], pAd->TssiPlusBoundaryA[4],
-			pAd->TxAgcStepA, pAd->bAutoTxAgcA));
-	}
-	pAd->BbpRssiToDbmDelta = 0x0;
-
-	// Read frequency offset setting for RF
-	RT28xx_EEPROM_READ16(pAd, EEPROM_FREQ_OFFSET, value);
-	if ((value & 0x00FF) != 0x00FF)
-		pAd->RfFreqOffset = (ULONG) (value & 0x00FF);
-	else
-		pAd->RfFreqOffset = 0;
-	DBGPRINT(RT_DEBUG_TRACE, ("E2PROM: RF FreqOffset=0x%lx \n", pAd->RfFreqOffset));
-
-	//CountryRegion byte offset (38h)
-	value = pAd->EEPROMDefaultValue[2] >> 8;		// 2.4G band
-	value2 = pAd->EEPROMDefaultValue[2] & 0x00FF;	// 5G band
-
-	if ((value <= REGION_MAXIMUM_BG_BAND) && (value2 <= REGION_MAXIMUM_A_BAND))
-	{
-		pAd->CommonCfg.CountryRegion = ((UCHAR) value) | 0x80;
-		pAd->CommonCfg.CountryRegionForABand = ((UCHAR) value2) | 0x80;
-		TmpPhy = pAd->CommonCfg.PhyMode;
-		pAd->CommonCfg.PhyMode = 0xff;
-		RTMPSetPhyMode(pAd, TmpPhy);
-#ifdef DOT11_N_SUPPORT
-		SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-	}
-
-	//
-	// Get RSSI Offset on EEPROM 0x9Ah & 0x9Ch.
-	// The valid value are (-10 ~ 10)
-	//
-	RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_BG_OFFSET, value);
-	pAd->BGRssiOffset0 = value & 0x00ff;
-	pAd->BGRssiOffset1 = (value >> 8);
-	RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_BG_OFFSET+2, value);
-	pAd->BGRssiOffset2 = value & 0x00ff;
-	pAd->ALNAGain1 = (value >> 8);
-	RT28xx_EEPROM_READ16(pAd, EEPROM_LNA_OFFSET, value);
-	pAd->BLNAGain = value & 0x00ff;
-	pAd->ALNAGain0 = (value >> 8);
-
-	// Validate 11b/g RSSI_0 offset.
-	if ((pAd->BGRssiOffset0 < -10) || (pAd->BGRssiOffset0 > 10))
-		pAd->BGRssiOffset0 = 0;
-
-	// Validate 11b/g RSSI_1 offset.
-	if ((pAd->BGRssiOffset1 < -10) || (pAd->BGRssiOffset1 > 10))
-		pAd->BGRssiOffset1 = 0;
-
-	// Validate 11b/g RSSI_2 offset.
-	if ((pAd->BGRssiOffset2 < -10) || (pAd->BGRssiOffset2 > 10))
-		pAd->BGRssiOffset2 = 0;
-
-	RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_A_OFFSET, value);
-	pAd->ARssiOffset0 = value & 0x00ff;
-	pAd->ARssiOffset1 = (value >> 8);
-	RT28xx_EEPROM_READ16(pAd, (EEPROM_RSSI_A_OFFSET+2), value);
-	pAd->ARssiOffset2 = value & 0x00ff;
-	pAd->ALNAGain2 = (value >> 8);
-
-	if (((UCHAR)pAd->ALNAGain1 == 0xFF) || (pAd->ALNAGain1 == 0x00))
-		pAd->ALNAGain1 = pAd->ALNAGain0;
-	if (((UCHAR)pAd->ALNAGain2 == 0xFF) || (pAd->ALNAGain2 == 0x00))
-		pAd->ALNAGain2 = pAd->ALNAGain0;
-
-	// Validate 11a RSSI_0 offset.
-	if ((pAd->ARssiOffset0 < -10) || (pAd->ARssiOffset0 > 10))
-		pAd->ARssiOffset0 = 0;
-
-	// Validate 11a RSSI_1 offset.
-	if ((pAd->ARssiOffset1 < -10) || (pAd->ARssiOffset1 > 10))
-		pAd->ARssiOffset1 = 0;
-
-	//Validate 11a RSSI_2 offset.
-	if ((pAd->ARssiOffset2 < -10) || (pAd->ARssiOffset2 > 10))
-		pAd->ARssiOffset2 = 0;
-
-	//
-	// Get LED Setting.
-	//
-	RT28xx_EEPROM_READ16(pAd, 0x3a, value);
-	pAd->LedCntl.word = (value&0xff00) >> 8;
-	RT28xx_EEPROM_READ16(pAd, EEPROM_LED1_OFFSET, value);
-	pAd->Led1 = value;
-	RT28xx_EEPROM_READ16(pAd, EEPROM_LED2_OFFSET, value);
-	pAd->Led2 = value;
-	RT28xx_EEPROM_READ16(pAd, EEPROM_LED3_OFFSET, value);
-	pAd->Led3 = value;
-
-	RTMPReadTxPwrPerRate(pAd);
-
-#ifdef SINGLE_SKU
-	//pAd->CommonCfg.DefineMaxTxPwr = RTMP_EEPROM_READ16(pAd, EEPROM_DEFINE_MAX_TXPWR);
-	RT28xx_EEPROM_READ16(pAd, EEPROM_DEFINE_MAX_TXPWR, pAd->CommonCfg.DefineMaxTxPwr);
-#endif // SINGLE_SKU //
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICReadEEPROMParameters\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Set default value from EEPROM
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	NICInitAsicFromEEPROM(
-	IN	PRTMP_ADAPTER	pAd)
-{
-#ifdef CONFIG_STA_SUPPORT
-	UINT32					data = 0;
-	UCHAR	BBPR1 = 0;
-#endif // CONFIG_STA_SUPPORT //
-	USHORT					i;
-	EEPROM_ANTENNA_STRUC	Antenna;
-	EEPROM_NIC_CONFIG2_STRUC    NicConfig2;
-	UCHAR	BBPR3 = 0;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICInitAsicFromEEPROM\n"));
-	for(i = 3; i < NUM_EEPROM_BBP_PARMS; i++)
-	{
-		UCHAR BbpRegIdx, BbpValue;
-
-		if ((pAd->EEPROMDefaultValue[i] != 0xFFFF) && (pAd->EEPROMDefaultValue[i] != 0))
-		{
-			BbpRegIdx = (UCHAR)(pAd->EEPROMDefaultValue[i] >> 8);
-			BbpValue  = (UCHAR)(pAd->EEPROMDefaultValue[i] & 0xff);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BbpRegIdx, BbpValue);
-		}
-	}
-
-	Antenna.word = pAd->Antenna.word;
-	pAd->Mlme.RealRxPath = (UCHAR) Antenna.field.RxPath;
-	pAd->RfIcType = (UCHAR) Antenna.field.RfIcType;
-
-	NicConfig2.word = pAd->EEPROMDefaultValue[1];
-
-
-	// Save the antenna for future use
-	pAd->NicConfig2.word = NicConfig2.word;
-
-	//
-	// Send LED Setting to MCU.
-	//
-	if (pAd->LedCntl.word == 0xFF)
-	{
-		pAd->LedCntl.word = 0x01;
-		pAd->Led1 = 0x5555;
-		pAd->Led2 = 0x2221;
-
-#ifdef RT2870
-		pAd->Led3 = 0x5627;
-#endif // RT2870 //
-	}
-
-	AsicSendCommandToMcu(pAd, 0x52, 0xff, (UCHAR)pAd->Led1, (UCHAR)(pAd->Led1 >> 8));
-	AsicSendCommandToMcu(pAd, 0x53, 0xff, (UCHAR)pAd->Led2, (UCHAR)(pAd->Led2 >> 8));
-	AsicSendCommandToMcu(pAd, 0x54, 0xff, (UCHAR)pAd->Led3, (UCHAR)(pAd->Led3 >> 8));
-    pAd->LedIndicatorStregth = 0xFF;
-    RTMPSetSignalLED(pAd, -100);	// Force signal strength Led to be turned off, before link up
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Read Hardware controlled Radio state enable bit
-		if (NicConfig2.field.HardwareRadioControl == 1)
-		{
-			pAd->StaCfg.bHardwareRadio = TRUE;
-
-			// Read GPIO pin2 as Hardware controlled radio state
-			RTMP_IO_READ32(pAd, GPIO_CTRL_CFG, &data);
-			if ((data & 0x04) == 0)
-			{
-				pAd->StaCfg.bHwRadio = FALSE;
-				pAd->StaCfg.bRadio = FALSE;
-//				RTMP_IO_WRITE32(pAd, PWR_PIN_CFG, 0x00001818);
-				RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
-			}
-		}
-		else
-			pAd->StaCfg.bHardwareRadio = FALSE;
-
-		if (pAd->StaCfg.bRadio == FALSE)
-		{
-			RTMPSetLED(pAd, LED_RADIO_OFF);
-		}
-		else
-		{
-			RTMPSetLED(pAd, LED_RADIO_ON);
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Turn off patching for cardbus controller
-	if (NicConfig2.field.CardbusAcceleration == 1)
-	{
-//		pAd->bTest1 = TRUE;
-	}
-
-	if (NicConfig2.field.DynamicTxAgcControl == 1)
-		pAd->bAutoTxAgcA = pAd->bAutoTxAgcG = TRUE;
-	else
-		pAd->bAutoTxAgcA = pAd->bAutoTxAgcG = FALSE;
-	//
-	// Since BBP has been progamed, to make sure BBP setting will be
-	// upate inside of AsicAntennaSelect, so reset to UNKNOWN_BAND!!
-	//
-	pAd->CommonCfg.BandState = UNKNOWN_BAND;
-
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPR3);
-	BBPR3 &= (~0x18);
-	if(pAd->Antenna.field.RxPath == 3)
-	{
-		BBPR3 |= (0x10);
-	}
-	else if(pAd->Antenna.field.RxPath == 2)
-	{
-		BBPR3 |= (0x8);
-	}
-	else if(pAd->Antenna.field.RxPath == 1)
-	{
-		BBPR3 |= (0x0);
-	}
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPR3);
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Handle the difference when 1T
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BBPR1);
-		if(pAd->Antenna.field.TxPath == 1)
-		{
-		BBPR1 &= (~0x18);
-		}
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BBPR1);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Use Hw Radio Control Pin=%d; if used Pin=%d;\n", pAd->CommonCfg.bHardwareRadio, pAd->CommonCfg.bHardwareRadio));
-	}
-#endif // CONFIG_STA_SUPPORT //
-	DBGPRINT(RT_DEBUG_TRACE, ("TxPath = %d, RxPath = %d, RFIC=%d, Polar+LED mode=%x\n", pAd->Antenna.field.TxPath, pAd->Antenna.field.RxPath, pAd->RfIcType, pAd->LedCntl.word));
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICInitAsicFromEEPROM\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Initialize NIC hardware
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS	NICInitializeAdapter(
-	IN	PRTMP_ADAPTER	pAd,
-	IN   BOOLEAN    bHardReset)
-{
-	NDIS_STATUS     Status = NDIS_STATUS_SUCCESS;
-	WPDMA_GLO_CFG_STRUC	GloCfg;
-//	INT_MASK_CSR_STRUC		IntMask;
-	ULONG	i =0, j=0;
-	AC_TXOP_CSR0_STRUC	csr0;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICInitializeAdapter\n"));
-
-	// 3. Set DMA global configuration except TX_DMA_EN and RX_DMA_EN bits:
-retry:
-	i = 0;
-	do
-	{
-		RTMP_IO_READ32(pAd, WPDMA_GLO_CFG, &GloCfg.word);
-		if ((GloCfg.field.TxDMABusy == 0)  && (GloCfg.field.RxDMABusy == 0))
-			break;
-
-		RTMPusecDelay(1000);
-		i++;
-	}while ( i<100);
-	DBGPRINT(RT_DEBUG_TRACE, ("<== DMA offset 0x208 = 0x%x\n", GloCfg.word));
-	GloCfg.word &= 0xff0;
-	GloCfg.field.EnTXWriteBackDDONE =1;
-	RTMP_IO_WRITE32(pAd, WPDMA_GLO_CFG, GloCfg.word);
-
-	// Record HW Beacon offset
-	pAd->BeaconOffset[0] = HW_BEACON_BASE0;
-	pAd->BeaconOffset[1] = HW_BEACON_BASE1;
-	pAd->BeaconOffset[2] = HW_BEACON_BASE2;
-	pAd->BeaconOffset[3] = HW_BEACON_BASE3;
-	pAd->BeaconOffset[4] = HW_BEACON_BASE4;
-	pAd->BeaconOffset[5] = HW_BEACON_BASE5;
-	pAd->BeaconOffset[6] = HW_BEACON_BASE6;
-	pAd->BeaconOffset[7] = HW_BEACON_BASE7;
-
-	//
-	// write all shared Ring's base address into ASIC
-	//
-
-	// asic simulation sequence put this ahead before loading firmware.
-	// pbf hardware reset
-
-	// Initialze ASIC for TX & Rx operation
-	if (NICInitializeAsic(pAd , bHardReset) != NDIS_STATUS_SUCCESS)
-	{
-		if (j++ == 0)
-		{
-			NICLoadFirmware(pAd);
-			goto retry;
-		}
-		return NDIS_STATUS_FAILURE;
-	}
-
-
-
-
-	// WMM parameter
-	csr0.word = 0;
-	RTMP_IO_WRITE32(pAd, WMM_TXOP0_CFG, csr0.word);
-	if (pAd->CommonCfg.PhyMode == PHY_11B)
-	{
-		csr0.field.Ac0Txop = 192;	// AC_VI: 192*32us ~= 6ms
-		csr0.field.Ac1Txop = 96;	// AC_VO: 96*32us  ~= 3ms
-	}
-	else
-	{
-		csr0.field.Ac0Txop = 96;	// AC_VI: 96*32us ~= 3ms
-		csr0.field.Ac1Txop = 48;	// AC_VO: 48*32us ~= 1.5ms
-	}
-	RTMP_IO_WRITE32(pAd, WMM_TXOP1_CFG, csr0.word);
-
-
-
-
-	// reset action
-	// Load firmware
-	//  Status = NICLoadFirmware(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICInitializeAdapter\n"));
-	return Status;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Initialize ASIC
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS	NICInitializeAsic(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  BOOLEAN		bHardReset)
-{
-	ULONG			Index = 0;
-	UCHAR			R0 = 0xff;
-	UINT32			MacCsr12 = 0, Counter = 0;
-#ifdef RT2870
-	UINT32			MacCsr0 = 0;
-	NTSTATUS		Status;
-	UCHAR			Value = 0xff;
-#endif // RT2870 //
-	USHORT			KeyIdx;
-	INT				i,apidx;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICInitializeAsic\n"));
-
-
-#ifdef RT2870
-	//
-	// Make sure MAC gets ready after NICLoadFirmware().
-	//
-	Index = 0;
-
-	//To avoid hang-on issue when interface up in kernel 2.4,
-	//we use a local variable "MacCsr0" instead of using "pAd->MACVersion" directly.
-	do
-	{
-		RTMP_IO_READ32(pAd, MAC_CSR0, &MacCsr0);
-
-		if ((MacCsr0 != 0x00) && (MacCsr0 != 0xFFFFFFFF))
-			break;
-
-		RTMPusecDelay(10);
-	} while (Index++ < 100);
-
-	pAd->MACVersion = MacCsr0;
-	DBGPRINT(RT_DEBUG_TRACE, ("MAC_CSR0  [ Ver:Rev=0x%08x]\n", pAd->MACVersion));
-	// turn on bit13 (set to zero) after rt2860D. This is to solve high-current issue.
-	RTMP_IO_READ32(pAd, PBF_SYS_CTRL, &MacCsr12);
-	MacCsr12 &= (~0x2000);
-	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, MacCsr12);
-
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x3);
-	RTMP_IO_WRITE32(pAd, USB_DMA_CFG, 0x0);
-	Status = RTUSBVenderReset(pAd);
-
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x0);
-
-	// Initialize MAC register to default value
-	for(Index=0; Index<NUM_MAC_REG_PARMS; Index++)
-	{
-		RTMP_IO_WRITE32(pAd, (USHORT)MACRegTable[Index].Register, MACRegTable[Index].Value);
-	}
-
-	if(IS_RT3070(pAd))
-	{
-		// According to Frank Hsu (from Gary Tsao)
-		RTMP_IO_WRITE32(pAd, (USHORT)TX_SW_CFG0, 0x00000400);
-
-		// Initialize RT3070 serial MAC registers which is different from RT2870 serial
-		RTUSBWriteMACRegister(pAd, TX_SW_CFG1, 0);
-		RTUSBWriteMACRegister(pAd, TX_SW_CFG2, 0);
-	}
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		for (Index = 0; Index < NUM_STA_MAC_REG_PARMS; Index++)
-		{
-			RTMP_IO_WRITE32(pAd, (USHORT)STAMACRegTable[Index].Register, STAMACRegTable[Index].Value);
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-#endif // RT2870 //
-
-	//
-	// Before program BBP, we need to wait BBP/RF get wake up.
-	//
-	Index = 0;
-	do
-	{
-		RTMP_IO_READ32(pAd, MAC_STATUS_CFG, &MacCsr12);
-
-		if ((MacCsr12 & 0x03) == 0)	// if BB.RF is stable
-			break;
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Check MAC_STATUS_CFG  = Busy = %x\n", MacCsr12));
-		RTMPusecDelay(1000);
-	} while (Index++ < 100);
-
-    // The commands to firmware should be after these commands, these commands will init firmware
-	// PCI and USB are not the same because PCI driver needs to wait for PCI bus ready
-	RTMP_IO_WRITE32(pAd, H2M_BBP_AGENT, 0);	// initialize BBP R/W access agent
-	RTMP_IO_WRITE32(pAd, H2M_MAILBOX_CSR, 0);
-	RTMPusecDelay(1000);
-
-	// Read BBP register, make sure BBP is up and running before write new data
-	Index = 0;
-	do
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R0, &R0);
-		DBGPRINT(RT_DEBUG_TRACE, ("BBP version = %x\n", R0));
-	} while ((++Index < 20) && ((R0 == 0xff) || (R0 == 0x00)));
-	//ASSERT(Index < 20); //this will cause BSOD on Check-build driver
-
-	if ((R0 == 0xff) || (R0 == 0x00))
-		return NDIS_STATUS_FAILURE;
-
-	// Initialize BBP register to default value
-	for (Index = 0; Index < NUM_BBP_REG_PARMS; Index++)
-	{
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBPRegTable[Index].Register, BBPRegTable[Index].Value);
-	}
-
-	// for rt2860E and after, init BBP_R84 with 0x19. This is for extension channel overlapping IOT.
-	if ((pAd->MACVersion&0xffff) != 0x0101)
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R84, 0x19);
-
-#ifdef RT2870
-	//write RT3070 BBP wchich different with 2870 after write RT2870 BBP
-	if (IS_RT3070(pAd))
-	{
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0a);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R84, 0x99);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R105, 0x05);
-	}
-#endif // RT2870 //
-
-	if (pAd->MACVersion == 0x28600100)
-	{
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x16);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x12);
-    }
-
-	if (pAd->MACVersion >= RALINK_2880E_VERSION && pAd->MACVersion < RALINK_3070_VERSION) // 3*3
-	{
-		// enlarge MAX_LEN_CFG
-		UINT32 csr;
-		RTMP_IO_READ32(pAd, MAX_LEN_CFG, &csr);
-		csr &= 0xFFF;
-		csr |= 0x2000;
-		RTMP_IO_WRITE32(pAd, MAX_LEN_CFG, csr);
-	}
-
-#ifdef RT2870
-{
-	UCHAR	MAC_Value[]={0xff,0xff,0xff,0xff,0xff,0xff,0xff,0,0};
-
-	//Initialize WCID table
-	Value = 0xff;
-	for(Index =0 ;Index < 254;Index++)
-	{
-		RTUSBMultiWrite(pAd, (USHORT)(MAC_WCID_BASE + Index * 8), MAC_Value, 8);
-	}
-}
-#endif // RT2870 //
-
-	// Add radio off control
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pAd->StaCfg.bRadio == FALSE)
-		{
-//			RTMP_IO_WRITE32(pAd, PWR_PIN_CFG, 0x00001818);
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
-			DBGPRINT(RT_DEBUG_TRACE, ("Set Radio Off\n"));
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Clear raw counters
-	RTMP_IO_READ32(pAd, RX_STA_CNT0, &Counter);
-	RTMP_IO_READ32(pAd, RX_STA_CNT1, &Counter);
-	RTMP_IO_READ32(pAd, RX_STA_CNT2, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT0, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT1, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT2, &Counter);
-
-	// ASIC will keep garbage value after boot
-	// Clear all seared key table when initial
-	// This routine can be ignored in radio-ON/OFF operation.
-	if (bHardReset)
-	{
-		for (KeyIdx = 0; KeyIdx < 4; KeyIdx++)
-		{
-			RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE + 4*KeyIdx, 0);
-		}
-
-		// Clear all pairwise key table when initial
-		for (KeyIdx = 0; KeyIdx < 256; KeyIdx++)
-		{
-			RTMP_IO_WRITE32(pAd, MAC_WCID_ATTRIBUTE_BASE + (KeyIdx * HW_WCID_ATTRI_SIZE), 1);
-		}
-	}
-
-	// assert HOST ready bit
-//  RTMP_IO_WRITE32(pAd, MAC_CSR1, 0x0); // 2004-09-14 asked by Mark
-//  RTMP_IO_WRITE32(pAd, MAC_CSR1, 0x4);
-
-	// It isn't necessary to clear this space when not hard reset.
-	if (bHardReset == TRUE)
-	{
-		// clear all on-chip BEACON frame space
-		for (apidx = 0; apidx < HW_BEACON_MAX_COUNT; apidx++)
-		{
-			for (i = 0; i < HW_BEACON_OFFSET>>2; i+=4)
-				RTMP_IO_WRITE32(pAd, pAd->BeaconOffset[apidx] + i, 0x00);
-		}
-	}
-#ifdef RT2870
-	AsicDisableSync(pAd);
-	// Clear raw counters
-	RTMP_IO_READ32(pAd, RX_STA_CNT0, &Counter);
-	RTMP_IO_READ32(pAd, RX_STA_CNT1, &Counter);
-	RTMP_IO_READ32(pAd, RX_STA_CNT2, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT0, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT1, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT2, &Counter);
-	// Default PCI clock cycle per ms is different as default setting, which is based on PCI.
-	RTMP_IO_READ32(pAd, USB_CYC_CFG, &Counter);
-	Counter&=0xffffff00;
-	Counter|=0x000001e;
-	RTMP_IO_WRITE32(pAd, USB_CYC_CFG, Counter);
-#endif // RT2870 //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// for rt2860E and after, init TXOP_CTRL_CFG with 0x583f. This is for extension channel overlapping IOT.
-		if ((pAd->MACVersion&0xffff) != 0x0101)
-			RTMP_IO_WRITE32(pAd, TXOP_CTRL_CFG, 0x583f);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICInitializeAsic\n"));
-	return NDIS_STATUS_SUCCESS;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Reset NIC Asics
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-		Reset NIC to initial state AS IS system boot up time.
-
-	========================================================================
-*/
-VOID	NICIssueReset(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UINT32	Value = 0;
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICIssueReset\n"));
-
-	// Abort Tx, prevent ASIC from writing to Host memory
-	//RTMP_IO_WRITE32(pAd, TX_CNTL_CSR, 0x001f0000);
-
-	// Disable Rx, register value supposed will remain after reset
-	RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-	Value &= (0xfffffff3);
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-	// Issue reset and clear from reset state
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x03); // 2004-09-17 change from 0x01
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x00);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICIssueReset\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Check ASIC registers and find any reason the system might hang
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-BOOLEAN	NICCheckForHang(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	return (FALSE);
-}
-
-VOID NICUpdateFifoStaCounters(
-	IN PRTMP_ADAPTER pAd)
-{
-	TX_STA_FIFO_STRUC	StaFifo;
-	MAC_TABLE_ENTRY		*pEntry;
-	UCHAR				i = 0;
-	UCHAR			pid = 0, wcid = 0;
-	CHAR				reTry;
-	UCHAR				succMCS;
-
-#ifdef RALINK_ATE
-	/* Nothing to do in ATE mode */
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-		do
-		{
-			RTMP_IO_READ32(pAd, TX_STA_FIFO, &StaFifo.word);
-
-			if (StaFifo.field.bValid == 0)
-				break;
-
-			wcid = (UCHAR)StaFifo.field.wcid;
-
-
-		/* ignore NoACK and MGMT frame use 0xFF as WCID */
-			if ((StaFifo.field.TxAckRequired == 0) || (wcid >= MAX_LEN_OF_MAC_TABLE))
-			{
-				i++;
-				continue;
-			}
-
-			/* PID store Tx MCS Rate */
-			pid = (UCHAR)StaFifo.field.PidType;
-
-			pEntry = &pAd->MacTab.Content[wcid];
-
-			pEntry->DebugFIFOCount++;
-
-#ifdef DOT11_N_SUPPORT
-			if (StaFifo.field.TxBF) // 3*3
-				pEntry->TxBFCount++;
-#endif // DOT11_N_SUPPORT //
-
-#ifdef UAPSD_AP_SUPPORT
-			UAPSD_SP_AUE_Handle(pAd, pEntry, StaFifo.field.TxSuccess);
-#endif // UAPSD_AP_SUPPORT //
-
-			if (!StaFifo.field.TxSuccess)
-			{
-				pEntry->FIFOCount++;
-				pEntry->OneSecTxFailCount++;
-
-				if (pEntry->FIFOCount >= 1)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("#"));
-#if 0
-					SendRefreshBAR(pAd, pEntry);
-					pEntry->NoBADataCountDown = 64;
-#else
-#ifdef DOT11_N_SUPPORT
-					pEntry->NoBADataCountDown = 64;
-#endif // DOT11_N_SUPPORT //
-
-					if(pEntry->PsMode == PWR_ACTIVE)
-					{
-#ifdef DOT11_N_SUPPORT
-						int tid;
-						for (tid=0; tid<NUM_OF_TID; tid++)
-						{
-							BAOriSessionTearDown(pAd, pEntry->Aid,  tid, FALSE, FALSE);
-						}
-#endif // DOT11_N_SUPPORT //
-
-						// Update the continuous transmission counter except PS mode
-						pEntry->ContinueTxFailCnt++;
-					}
-					else
-					{
-						// Clear the FIFOCount when sta in Power Save mode. Basically we assume
-						//     this tx error happened due to sta just go to sleep.
-						pEntry->FIFOCount = 0;
-						pEntry->ContinueTxFailCnt = 0;
-					}
-#endif
-					//pEntry->FIFOCount = 0;
-				}
-				//pEntry->bSendBAR = TRUE;
-			}
-			else
-			{
-#ifdef DOT11_N_SUPPORT
-				if ((pEntry->PsMode != PWR_SAVE) && (pEntry->NoBADataCountDown > 0))
-				{
-					pEntry->NoBADataCountDown--;
-					if (pEntry->NoBADataCountDown==0)
-					{
-						DBGPRINT(RT_DEBUG_TRACE, ("@\n"));
-					}
-				}
-#endif // DOT11_N_SUPPORT //
-				pEntry->FIFOCount = 0;
-				pEntry->OneSecTxNoRetryOkCount++;
-				// update NoDataIdleCount when sucessful send packet to STA.
-				pEntry->NoDataIdleCount = 0;
-				pEntry->ContinueTxFailCnt = 0;
-			}
-
-			succMCS = StaFifo.field.SuccessRate & 0x7F;
-
-			reTry = pid - succMCS;
-
-			if (StaFifo.field.TxSuccess)
-			{
-				pEntry->TXMCSExpected[pid]++;
-				if (pid == succMCS)
-				{
-					pEntry->TXMCSSuccessful[pid]++;
-				}
-				else
-				{
-					pEntry->TXMCSAutoFallBack[pid][succMCS]++;
-				}
-			}
-			else
-			{
-				pEntry->TXMCSFailed[pid]++;
-			}
-
-			if (reTry > 0)
-			{
-				if ((pid >= 12) && succMCS <=7)
-				{
-					reTry -= 4;
-				}
-				pEntry->OneSecTxRetryOkCount += reTry;
-			}
-
-			i++;
-			// ASIC store 16 stack
-		} while ( i < (2*TX_RING_SIZE) );
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Read statistical counters from hardware registers and record them
-		in software variables for later on query
-
-	Arguments:
-		pAd					Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-VOID NICUpdateRawCounters(
-	IN PRTMP_ADAPTER pAd)
-{
-	UINT32	OldValue;
-	RX_STA_CNT0_STRUC	 RxStaCnt0;
-	RX_STA_CNT1_STRUC   RxStaCnt1;
-	RX_STA_CNT2_STRUC   RxStaCnt2;
-	TX_STA_CNT0_STRUC 	 TxStaCnt0;
-	TX_STA_CNT1_STRUC	 StaTx1;
-	TX_STA_CNT2_STRUC	 StaTx2;
-	TX_AGG_CNT_STRUC	TxAggCnt;
-	TX_AGG_CNT0_STRUC	TxAggCnt0;
-	TX_AGG_CNT1_STRUC	TxAggCnt1;
-	TX_AGG_CNT2_STRUC	TxAggCnt2;
-	TX_AGG_CNT3_STRUC	TxAggCnt3;
-	TX_AGG_CNT4_STRUC	TxAggCnt4;
-	TX_AGG_CNT5_STRUC	TxAggCnt5;
-	TX_AGG_CNT6_STRUC	TxAggCnt6;
-	TX_AGG_CNT7_STRUC	TxAggCnt7;
-
-
-	RTMP_IO_READ32(pAd, RX_STA_CNT0, &RxStaCnt0.word);
-	RTMP_IO_READ32(pAd, RX_STA_CNT2, &RxStaCnt2.word);
-
-	{
-		RTMP_IO_READ32(pAd, RX_STA_CNT1, &RxStaCnt1.word);
-	    // Update RX PLCP error counter
-	    pAd->PrivateInfo.PhyRxErrCnt += RxStaCnt1.field.PlcpErr;
-		// Update False CCA counter
-		pAd->RalinkCounters.OneSecFalseCCACnt += RxStaCnt1.field.FalseCca;
-	}
-
-	// Update FCS counters
-	OldValue= pAd->WlanCounters.FCSErrorCount.u.LowPart;
-	pAd->WlanCounters.FCSErrorCount.u.LowPart += (RxStaCnt0.field.CrcErr); // >> 7);
-	if (pAd->WlanCounters.FCSErrorCount.u.LowPart < OldValue)
-		pAd->WlanCounters.FCSErrorCount.u.HighPart++;
-
-	// Add FCS error count to private counters
-	pAd->RalinkCounters.OneSecRxFcsErrCnt += RxStaCnt0.field.CrcErr;
-	OldValue = pAd->RalinkCounters.RealFcsErrCount.u.LowPart;
-	pAd->RalinkCounters.RealFcsErrCount.u.LowPart += RxStaCnt0.field.CrcErr;
-	if (pAd->RalinkCounters.RealFcsErrCount.u.LowPart < OldValue)
-		pAd->RalinkCounters.RealFcsErrCount.u.HighPart++;
-
-	// Update Duplicate Rcv check
-	pAd->RalinkCounters.DuplicateRcv += RxStaCnt2.field.RxDupliCount;
-	pAd->WlanCounters.FrameDuplicateCount.u.LowPart += RxStaCnt2.field.RxDupliCount;
-	// Update RX Overflow counter
-	pAd->Counters8023.RxNoBuffer += (RxStaCnt2.field.RxFifoOverflowCount);
-
-	//pAd->RalinkCounters.RxCount = 0;
-#ifdef RT2870
-	if (pAd->RalinkCounters.RxCount != pAd->watchDogRxCnt)
-	{
-		pAd->watchDogRxCnt = pAd->RalinkCounters.RxCount;
-		pAd->watchDogRxOverFlowCnt = 0;
-	}
-	else
-	{
-		if (RxStaCnt2.field.RxFifoOverflowCount)
-			pAd->watchDogRxOverFlowCnt++;
-		else
-			pAd->watchDogRxOverFlowCnt = 0;
-	}
-#endif // RT2870 //
-
-
-	//if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED) ||
-	//	(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED) && (pAd->MacTab.Size != 1)))
-	if (!pAd->bUpdateBcnCntDone)
-	{
-	// Update BEACON sent count
-	RTMP_IO_READ32(pAd, TX_STA_CNT0, &TxStaCnt0.word);
-	RTMP_IO_READ32(pAd, TX_STA_CNT1, &StaTx1.word);
-	RTMP_IO_READ32(pAd, TX_STA_CNT2, &StaTx2.word);
-	pAd->RalinkCounters.OneSecBeaconSentCnt += TxStaCnt0.field.TxBeaconCount;
-	pAd->RalinkCounters.OneSecTxRetryOkCount += StaTx1.field.TxRetransmit;
-	pAd->RalinkCounters.OneSecTxNoRetryOkCount += StaTx1.field.TxSuccess;
-	pAd->RalinkCounters.OneSecTxFailCount += TxStaCnt0.field.TxFailCount;
-	pAd->WlanCounters.TransmittedFragmentCount.u.LowPart += StaTx1.field.TxSuccess;
-	pAd->WlanCounters.RetryCount.u.LowPart += StaTx1.field.TxRetransmit;
-	pAd->WlanCounters.FailedCount.u.LowPart += TxStaCnt0.field.TxFailCount;
-	}
-
-#if 0
-	Retry = StaTx1.field.TxRetransmit;
-	Fail = TxStaCnt0.field.TxFailCount;
-	TxErrorRatio = 0;
-	OneSecTransmitCount = pAd->WlanCounters.TransmittedFragmentCount.u.LowPart- pAd->WlanCounters.LastTransmittedFragmentCount.u.LowPart;
-	if ((OneSecTransmitCount+Retry + Fail) > 0)
-		TxErrorRatio = (( Retry + Fail) *100) / (OneSecTransmitCount+Retry + Fail);
-
-	if ((OneSecTransmitCount+Retry + Fail) > 0)
-		TxErrorRatio = (( Retry + Fail) *100) / (OneSecTransmitCount+Retry + Fail);
-	DBGPRINT(RT_DEBUG_INFO, ("TX ERROR Rate = %ld %%, Retry = %ld, Fail = %ld, Total = %ld  \n",TxErrorRatio, Retry, Fail, (OneSecTransmitCount+Retry + Fail)));
-	pAd->WlanCounters.LastTransmittedFragmentCount.u.LowPart = pAd->WlanCounters.TransmittedFragmentCount.u.LowPart;
-#endif
-
-	//if (pAd->bStaFifoTest == TRUE)
-	{
-		RTMP_IO_READ32(pAd, TX_AGG_CNT, &TxAggCnt.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT0, &TxAggCnt0.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT1, &TxAggCnt1.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT2, &TxAggCnt2.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT3, &TxAggCnt3.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT4, &TxAggCnt4.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT5, &TxAggCnt5.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT6, &TxAggCnt6.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT7, &TxAggCnt7.word);
-		pAd->RalinkCounters.TxAggCount += TxAggCnt.field.AggTxCount;
-		pAd->RalinkCounters.TxNonAggCount += TxAggCnt.field.NonAggTxCount;
-		pAd->RalinkCounters.TxAgg1MPDUCount += TxAggCnt0.field.AggSize1Count;
-		pAd->RalinkCounters.TxAgg2MPDUCount += TxAggCnt0.field.AggSize2Count;
-
-		pAd->RalinkCounters.TxAgg3MPDUCount += TxAggCnt1.field.AggSize3Count;
-		pAd->RalinkCounters.TxAgg4MPDUCount += TxAggCnt1.field.AggSize4Count;
-		pAd->RalinkCounters.TxAgg5MPDUCount += TxAggCnt2.field.AggSize5Count;
-		pAd->RalinkCounters.TxAgg6MPDUCount += TxAggCnt2.field.AggSize6Count;
-
-		pAd->RalinkCounters.TxAgg7MPDUCount += TxAggCnt3.field.AggSize7Count;
-		pAd->RalinkCounters.TxAgg8MPDUCount += TxAggCnt3.field.AggSize8Count;
-		pAd->RalinkCounters.TxAgg9MPDUCount += TxAggCnt4.field.AggSize9Count;
-		pAd->RalinkCounters.TxAgg10MPDUCount += TxAggCnt4.field.AggSize10Count;
-
-		pAd->RalinkCounters.TxAgg11MPDUCount += TxAggCnt5.field.AggSize11Count;
-		pAd->RalinkCounters.TxAgg12MPDUCount += TxAggCnt5.field.AggSize12Count;
-		pAd->RalinkCounters.TxAgg13MPDUCount += TxAggCnt6.field.AggSize13Count;
-		pAd->RalinkCounters.TxAgg14MPDUCount += TxAggCnt6.field.AggSize14Count;
-
-		pAd->RalinkCounters.TxAgg15MPDUCount += TxAggCnt7.field.AggSize15Count;
-		pAd->RalinkCounters.TxAgg16MPDUCount += TxAggCnt7.field.AggSize16Count;
-
-		// Calculate the transmitted A-MPDU count
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += TxAggCnt0.field.AggSize1Count;
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt0.field.AggSize2Count / 2);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt1.field.AggSize3Count / 3);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt1.field.AggSize4Count / 4);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt2.field.AggSize5Count / 5);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt2.field.AggSize6Count / 6);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt3.field.AggSize7Count / 7);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt3.field.AggSize8Count / 8);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt4.field.AggSize9Count / 9);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt4.field.AggSize10Count / 10);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt5.field.AggSize11Count / 11);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt5.field.AggSize12Count / 12);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt6.field.AggSize13Count / 13);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt6.field.AggSize14Count / 14);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt7.field.AggSize15Count / 15);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt7.field.AggSize16Count / 16);
-	}
-
-#ifdef DBG_DIAGNOSE
-	{
-		RtmpDiagStruct	*pDiag;
-		COUNTER_RALINK	*pRalinkCounters;
-		UCHAR			ArrayCurIdx, i;
-
-		pDiag = &pAd->DiagStruct;
-		pRalinkCounters = &pAd->RalinkCounters;
-		ArrayCurIdx = pDiag->ArrayCurIdx;
-
-		if (pDiag->inited == 0)
-		{
-			NdisZeroMemory(pDiag, sizeof(struct _RtmpDiagStrcut_));
-			pDiag->ArrayStartIdx = pDiag->ArrayCurIdx = 0;
-			pDiag->inited = 1;
-		}
-		else
-		{
-			// Tx
-			pDiag->TxFailCnt[ArrayCurIdx] = TxStaCnt0.field.TxFailCount;
-			pDiag->TxAggCnt[ArrayCurIdx] = TxAggCnt.field.AggTxCount;
-			pDiag->TxNonAggCnt[ArrayCurIdx] = TxAggCnt.field.NonAggTxCount;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][0] = TxAggCnt0.field.AggSize1Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][1] = TxAggCnt0.field.AggSize2Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][2] = TxAggCnt1.field.AggSize3Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][3] = TxAggCnt1.field.AggSize4Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][4] = TxAggCnt2.field.AggSize5Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][5] = TxAggCnt2.field.AggSize6Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][6] = TxAggCnt3.field.AggSize7Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][7] = TxAggCnt3.field.AggSize8Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][8] = TxAggCnt4.field.AggSize9Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][9] = TxAggCnt4.field.AggSize10Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][10] = TxAggCnt5.field.AggSize11Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][11] = TxAggCnt5.field.AggSize12Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][12] = TxAggCnt6.field.AggSize13Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][13] = TxAggCnt6.field.AggSize14Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][14] = TxAggCnt7.field.AggSize15Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][15] = TxAggCnt7.field.AggSize16Count;
-
-			pDiag->RxCrcErrCnt[ArrayCurIdx] = RxStaCnt0.field.CrcErr;
-
-			INC_RING_INDEX(pDiag->ArrayCurIdx,  DIAGNOSE_TIME);
-			ArrayCurIdx = pDiag->ArrayCurIdx;
-			for (i =0; i < 9; i++)
-			{
-				pDiag->TxDescCnt[ArrayCurIdx][i]= 0;
-				pDiag->TxSWQueCnt[ArrayCurIdx][i] =0;
-				pDiag->TxMcsCnt[ArrayCurIdx][i] = 0;
-				pDiag->RxMcsCnt[ArrayCurIdx][i] = 0;
-			}
-			pDiag->TxDataCnt[ArrayCurIdx] = 0;
-			pDiag->TxFailCnt[ArrayCurIdx] = 0;
-			pDiag->RxDataCnt[ArrayCurIdx] = 0;
-			pDiag->RxCrcErrCnt[ArrayCurIdx]  = 0;
-//			for (i = 9; i < 16; i++)
-			for (i = 9; i < 24; i++) // 3*3
-			{
-				pDiag->TxDescCnt[ArrayCurIdx][i] = 0;
-				pDiag->TxMcsCnt[ArrayCurIdx][i] = 0;
-				pDiag->RxMcsCnt[ArrayCurIdx][i] = 0;
-}
-
-			if (pDiag->ArrayCurIdx == pDiag->ArrayStartIdx)
-				INC_RING_INDEX(pDiag->ArrayStartIdx,  DIAGNOSE_TIME);
-		}
-
-	}
-#endif // DBG_DIAGNOSE //
-
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Reset NIC from error
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-		Reset NIC from error state
-
-	========================================================================
-*/
-VOID	NICResetFromError(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	// Reset BBP (according to alex, reset ASIC will force reset BBP
-	// Therefore, skip the reset BBP
-	// RTMP_IO_WRITE32(pAd, MAC_CSR1, 0x2);
-
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x1);
-	// Remove ASIC from reset state
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x0);
-
-	NICInitializeAdapter(pAd, FALSE);
-	NICInitAsicFromEEPROM(pAd);
-
-	// Switch to current channel, since during reset process, the connection should remains on.
-	AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-	AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		erase 8051 firmware image in MAC ASIC
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-VOID NICEraseFirmware(
-	IN PRTMP_ADAPTER pAd)
-{
-	ULONG i;
-
-	for(i=0; i<MAX_FIRMWARE_IMAGE_SIZE; i+=4)
-		RTMP_IO_WRITE32(pAd, FIRMWARE_IMAGE_BASE + i, 0);
-
-}/* End of NICEraseFirmware */
-
-/*
-	========================================================================
-
-	Routine Description:
-		Load 8051 firmware RT2561.BIN file into MAC ASIC
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		NDIS_STATUS_SUCCESS         firmware image load ok
-		NDIS_STATUS_FAILURE         image not found
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-NDIS_STATUS NICLoadFirmware(
-	IN PRTMP_ADAPTER pAd)
-{
-#ifdef BIN_IN_FILE
-#define NICLF_DEFAULT_USE()	\
-	flg_default_firm_use = TRUE; \
-	printk("%s - Use default firmware!\n", __func__);
-
-	NDIS_STATUS		Status = NDIS_STATUS_SUCCESS;
-	PUCHAR			src;
-	struct file		*srcf;
-	INT 			retval, orgfsuid, orgfsgid, i;
-   	mm_segment_t	orgfs;
-	PUCHAR			pFirmwareImage;
-	UINT			FileLength = 0;
-	UINT32			MacReg;
-	ULONG			Index;
-	ULONG			firm;
-	BOOLEAN			flg_default_firm_use = FALSE;
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("===> %s\n", __func__));
-
-	/* init */
-	pFirmwareImage = NULL;
-	src = RTMP_FIRMWARE_FILE_NAME;
-
-	/* save uid and gid used for filesystem access.
-	   set user and group to 0 (root) */
-	orgfsuid = current->fsuid;
-	orgfsgid = current->fsgid;
-	current->fsuid = current->fsgid = 0;
-    orgfs = get_fs();
-    set_fs(KERNEL_DS);
-
-	pAd->FirmwareVersion = (FIRMWARE_MAJOR_VERSION << 8) + \
-						   FIRMWARE_MINOR_VERSION;
-
-
-	/* allocate firmware buffer */
-    pFirmwareImage = kmalloc(MAX_FIRMWARE_IMAGE_SIZE, MEM_ALLOC_FLAG);
-    if (pFirmwareImage == NULL)
-	{
-		/* allocate fail, use default firmware array in firmware.h */
-		printk("%s - Allocate memory fail!\n", __func__);
-		NICLF_DEFAULT_USE();
-    }
-	else
-	{
-		/* allocate ok! zero the firmware buffer */
-		memset(pFirmwareImage, 0x00, MAX_FIRMWARE_IMAGE_SIZE);
-	} /* End of if */
-
-
-	/* if ok, read firmware file from *.bin file */
-	if (flg_default_firm_use == FALSE)
-	{
-		do
-		{
-			/* open the bin file */
-			srcf = filp_open(src, O_RDONLY, 0);
-
-			if (IS_ERR(srcf))
-			{
-				printk("%s - Error %ld opening %s\n",
-					   __func__, -PTR_ERR(srcf), src);
-				NICLF_DEFAULT_USE();
-				break;
-			} /* End of if */
-
-			/* the object must have a read method */
-			if ((srcf->f_op == NULL) || (srcf->f_op->read == NULL))
-			{
-				printk("%s - %s does not have a write method\n", __func__, src);
-				NICLF_DEFAULT_USE();
-				break;
-			} /* End of if */
-
-			/* read the firmware from the file *.bin */
-			FileLength = srcf->f_op->read(srcf,
-										  pFirmwareImage,
-										  MAX_FIRMWARE_IMAGE_SIZE,
-										  &srcf->f_pos);
-
-			if (FileLength != MAX_FIRMWARE_IMAGE_SIZE)
-			{
-				printk("%s: error file length (=%d) in RT2860AP.BIN\n",
-					   __func__, FileLength);
-				NICLF_DEFAULT_USE();
-				break;
-			}
-			else
-			{
-				PUCHAR ptr = pFirmwareImage;
-				USHORT crc = 0xffff;
-
-
-				/* calculate firmware CRC */
-				for(i=0; i<(MAX_FIRMWARE_IMAGE_SIZE-2); i++, ptr++)
-					crc = ByteCRC16(BitReverse(*ptr), crc);
-				/* End of for */
-
-				if ((pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-2] != \
-								(UCHAR)BitReverse((UCHAR)(crc>>8))) ||
-					(pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-1] != \
-								(UCHAR)BitReverse((UCHAR)crc)))
-				{
-					/* CRC fail */
-					printk("%s: CRC = 0x%02x 0x%02x "
-						   "error, should be 0x%02x 0x%02x\n",
-						   __func__,
-						   pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-2],
-						   pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-1],
-						   (UCHAR)(crc>>8), (UCHAR)(crc));
-					NICLF_DEFAULT_USE();
-					break;
-				}
-				else
-				{
-					/* firmware is ok */
-					pAd->FirmwareVersion = \
-						(pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-4] << 8) +
-						pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-3];
-
-					/* check if firmware version of the file is too old */
-					if ((pAd->FirmwareVersion) < \
-											((FIRMWARE_MAJOR_VERSION << 8) +
-									  	 	 FIRMWARE_MINOR_VERSION))
-					{
-						printk("%s: firmware version too old!\n", __func__);
-						NICLF_DEFAULT_USE();
-						break;
-					} /* End of if */
-				} /* End of if */
-
-				DBGPRINT(RT_DEBUG_TRACE,
-						 ("NICLoadFirmware: CRC ok, ver=%d.%d\n",
-						  pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-4],
-						  pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-3]));
-			} /* End of if (FileLength == MAX_FIRMWARE_IMAGE_SIZE) */
-			break;
-		} while(TRUE);
-
-		/* close firmware file */
-		if (IS_ERR(srcf))
-			;
-		else
-		{
-			retval = filp_close(srcf, NULL);
-			if (retval)
-			{
-				DBGPRINT(RT_DEBUG_ERROR,
-						 ("--> Error %d closing %s\n", -retval, src));
-			} /* End of if */
-		} /* End of if */
-	} /* End of if */
-
-
-	/* write firmware to ASIC */
-	if (flg_default_firm_use == TRUE)
-	{
-		/* use default fimeware, free allocated buffer */
-		if (pFirmwareImage != NULL)
-			kfree(pFirmwareImage);
-		/* End of if */
-
-		/* use default *.bin array */
-		pFirmwareImage = FirmwareImage;
-		FileLength = sizeof(FirmwareImage);
-	} /* End of if */
-
-	/* enable Host program ram write selection */
-	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, 0x10000);
-
-	for(i=0; i<FileLength; i+=4)
-	{
-		firm = pFirmwareImage[i] +
-			   (pFirmwareImage[i+3] << 24) +
-			   (pFirmwareImage[i+2] << 16) +
-			   (pFirmwareImage[i+1] << 8);
-
-		RTMP_IO_WRITE32(pAd, FIRMWARE_IMAGE_BASE + i, firm);
-	} /* End of for */
-
-	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, 0x00000);
-	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, 0x00001);
-
-	/* initialize BBP R/W access agent */
-	RTMP_IO_WRITE32(pAd, H2M_BBP_AGENT, 0);
-	RTMP_IO_WRITE32(pAd, H2M_MAILBOX_CSR, 0);
-
-	if (flg_default_firm_use == FALSE)
-	{
-		/* use file firmware, free allocated buffer */
-		if (pFirmwareImage != NULL)
-			kfree(pFirmwareImage);
-		/* End of if */
-	} /* End of if */
-
-	set_fs(orgfs);
-	current->fsuid = orgfsuid;
-	current->fsgid = orgfsgid;
-#else
-
-	NDIS_STATUS		Status = NDIS_STATUS_SUCCESS;
-	PUCHAR			pFirmwareImage;
-	ULONG			FileLength, Index;
-	//ULONG			firm;
-	UINT32			MacReg = 0;
-#ifdef RT2870
-	UINT32			Version = (pAd->MACVersion >> 16);
-#endif // RT2870 //
-
-	pFirmwareImage = FirmwareImage;
-	FileLength = sizeof(FirmwareImage);
-#ifdef RT2870
-	// New 8k byte firmware size for RT3071/RT3072
-	//printk("Usb Chip\n");
-	if (FIRMWAREIMAGE_LENGTH == FIRMWAREIMAGE_MAX_LENGTH)
-	//The firmware image consists of two parts. One is the origianl and the other is the new.
-	//Use Second Part
-	{
-		if ((Version != 0x2860) && (Version != 0x2872) && (Version != 0x3070))
-		{	// Use Firmware V2.
-			//printk("KH:Use New Version,part2\n");
-			pFirmwareImage = (PUCHAR)&FirmwareImage[FIRMWAREIMAGEV1_LENGTH];
-			FileLength = FIRMWAREIMAGEV2_LENGTH;
-		}
-		else
-		{
-			//printk("KH:Use New Version,part1\n");
-			pFirmwareImage = FirmwareImage;
-			FileLength = FIRMWAREIMAGEV1_LENGTH;
-		}
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("KH: bin file should be 8KB.\n"));
-		Status = NDIS_STATUS_FAILURE;
-	}
-
-#endif // RT2870 //
-
-#if 0
-	/* enable Host program ram write selection */
-	RT28XX_FIRMUD_INIT(pAd);
-
-	for(i=0; i<FileLength; i+=4)
-	{
-		firm = pFirmwareImage[i] +
-			   (pFirmwareImage[i+3] << 24) +
-			   (pFirmwareImage[i+2] << 16) +
-			   (pFirmwareImage[i+1] << 8);
-
-		RTMP_IO_WRITE32(pAd, FIRMWARE_IMAGE_BASE + i, firm);
-	} /* End of for */
-
-	RT28XX_FIRMUD_END(pAd);
-#else
-	RT28XX_WRITE_FIRMWARE(pAd, pFirmwareImage, FileLength);
-#endif
-
-#endif
-
-	/* check if MCU is ready */
-	Index = 0;
-	do
-	{
-		RTMP_IO_READ32(pAd, PBF_SYS_CTRL, &MacReg);
-
-		if (MacReg & 0x80)
-			break;
-
-		RTMPusecDelay(1000);
-	} while (Index++ < 1000);
-
-    if (Index >= 1000)
-	{
-		Status = NDIS_STATUS_FAILURE;
-		DBGPRINT(RT_DEBUG_ERROR, ("NICLoadFirmware: MCU is not ready\n\n\n"));
-	} /* End of if */
-
-#if 0
-    DBGPRINT(RT_DEBUG_TRACE,
-			 ("<=== %s (src=%s, status=%d)\n", __func__, src, Status));
-#else
-    DBGPRINT(RT_DEBUG_TRACE,
-			 ("<=== %s (status=%d)\n", __func__, Status));
-#endif
-    return Status;
-} /* End of NICLoadFirmware */
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Load Tx rate switching parameters
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		NDIS_STATUS_SUCCESS         firmware image load ok
-		NDIS_STATUS_FAILURE         image not found
-
-	IRQL = PASSIVE_LEVEL
-
-	Rate Table Format:
-		1. (B0: Valid Item number) (B1:Initial item from zero)
-		2. Item Number(Dec)      Mode(Hex)     Current MCS(Dec)    TrainUp(Dec)    TrainDown(Dec)
-
-	========================================================================
-*/
-NDIS_STATUS NICLoadRateSwitchingParams(
-	IN PRTMP_ADAPTER pAd)
-{
-#if 0
-	NDIS_STATUS Status;
-
-	NDIS_HANDLE FileHandle;
-	UINT FileLength = 0, i, j;
-	PUCHAR pFirmwareImage;
-	NDIS_STRING FileName;
-	NDIS_PHYSICAL_ADDRESS HighestAcceptableMax = NDIS_PHYSICAL_ADDRESS_CONST(-1, -1);
-
-	DBGPRINT(RT_DEBUG_TRACE,("===> NICLoadRateSwitchingParams \n"));
-	pAd->CommonCfg.TxRateTableSize = 0;
-
-	if ((pAd->DeviceID == NIC2860_PCI_DEVICE_ID) || (pAd->DeviceID == NIC2860_PCIe_DEVICE_ID))
-	{
-		NdisInitializeString(&FileName,"rate.bin");
-		DBGPRINT(RT_DEBUG_TRACE, ("NICLoadRateSwitchingParams: load file - rate.bin for tx rate switch \n"));
-	}
-	else
-	{
-		DBGPRINT_ERR(("NICLoadRateSwitchingParams: wrong DeviceID = 0x%04x, can't find Tx rate switch parameters file\n", pAd->DeviceID));
-		return NDIS_STATUS_SUCCESS;
-	}
-	NdisOpenFile(&Status, &FileHandle, &FileLength, &FileName, HighestAcceptableMax);
-	NdisFreeString(FileName);
-
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("NICLoadRateSwitchingParams: NdisOpenFile() failed, used RateSwitchTable instead\n"));
-		return NDIS_STATUS_SUCCESS;
-	}
-
-	if ((FileLength == 0) || (FileLength > (MAX_STEP_OF_TX_RATE_SWITCH+1)*16))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("NICLoadRateSwitchingParams: file size is not reasonable, used RateSwitchTable instead\n"));
-
-		NdisCloseFile(FileHandle);
-		return NDIS_STATUS_SUCCESS;
-	}
-	else
-	{
-		//
-		// NDIS_STATUS_SUCCESS means
-		// The handle at FileHandle is valid for a subsequent call to NdisMapFile.
-		//
-		NdisMapFile(&Status, &pFirmwareImage, FileHandle);
-		DBGPRINT(RT_DEBUG_TRACE, ("NdisMapFile FileLength=%d\n", FileLength));
-	}
-
-	for (i=0, j=0; i<FileLength; i++)
-	{
-		if ((i%16) <= 4)	// trim reserved field
-		{
-			if (i%16 == 1)	// deal with DEC and HEX, only row0 is Hex, others are Dec
-			{
-				RateSwitchTable[j] = *(pFirmwareImage + i);
-			}
-			else
-			{
-				RateSwitchTable[j] = (*(pFirmwareImage + i)>>4) * 10 + (*(pFirmwareImage + i) & 0x0F);
-			}
-
-			j++;
-		}
-	}
-
-	pAd->CommonCfg.TxRateTableSize = RateSwitchTable[0];		// backup table size
-
-	if (Status == NDIS_STATUS_SUCCESS)
-	{
-		NdisUnmapFile(FileHandle);
-		NdisCloseFile(FileHandle);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("<=== NICLoadRateSwitchingParams(Valid TxRateTable item number=%d)\n", pAd->CommonCfg.TxRateTableSize));
-#endif
-	return NDIS_STATUS_SUCCESS;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		if  pSrc1 all zero with length Length, return 0.
-		If not all zero, return 1
-
-	Arguments:
-		pSrc1
-
-	Return Value:
-		1:			not all zero
-		0:			all zero
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-ULONG	RTMPNotAllZero(
-	IN	PVOID	pSrc1,
-	IN	ULONG	Length)
-{
-	PUCHAR	pMem1;
-	ULONG	Index = 0;
-
-	pMem1 = (PUCHAR) pSrc1;
-
-	for (Index = 0; Index < Length; Index++)
-	{
-		if (pMem1[Index] != 0x0)
-		{
-			break;
-		}
-	}
-
-	if (Index == Length)
-	{
-		return (0);
-	}
-	else
-	{
-		return (1);
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Compare two memory block
-
-	Arguments:
-		pSrc1		Pointer to first memory address
-		pSrc2		Pointer to second memory address
-
-	Return Value:
-		0:			memory is equal
-		1:			pSrc1 memory is larger
-		2:			pSrc2 memory is larger
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-ULONG	RTMPCompareMemory(
-	IN	PVOID	pSrc1,
-	IN	PVOID	pSrc2,
-	IN	ULONG	Length)
-{
-	PUCHAR	pMem1;
-	PUCHAR	pMem2;
-	ULONG	Index = 0;
-
-	pMem1 = (PUCHAR) pSrc1;
-	pMem2 = (PUCHAR) pSrc2;
-
-	for (Index = 0; Index < Length; Index++)
-	{
-		if (pMem1[Index] > pMem2[Index])
-			return (1);
-		else if (pMem1[Index] < pMem2[Index])
-			return (2);
-	}
-
-	// Equal
-	return (0);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Zero out memory block
-
-	Arguments:
-		pSrc1		Pointer to memory address
-		Length		Size
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPZeroMemory(
-	IN	PVOID	pSrc,
-	IN	ULONG	Length)
-{
-	PUCHAR	pMem;
-	ULONG	Index = 0;
-
-	pMem = (PUCHAR) pSrc;
-
-	for (Index = 0; Index < Length; Index++)
-	{
-		pMem[Index] = 0x00;
-	}
-}
-
-VOID	RTMPFillMemory(
-	IN	PVOID	pSrc,
-	IN	ULONG	Length,
-	IN	UCHAR	Fill)
-{
-	PUCHAR	pMem;
-	ULONG	Index = 0;
-
-	pMem = (PUCHAR) pSrc;
-
-	for (Index = 0; Index < Length; Index++)
-	{
-		pMem[Index] = Fill;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Copy data from memory block 1 to memory block 2
-
-	Arguments:
-		pDest		Pointer to destination memory address
-		pSrc		Pointer to source memory address
-		Length		Copy size
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPMoveMemory(
-	OUT	PVOID	pDest,
-	IN	PVOID	pSrc,
-	IN	ULONG	Length)
-{
-	PUCHAR	pMem1;
-	PUCHAR	pMem2;
-	UINT	Index;
-
-	ASSERT((Length==0) || (pDest && pSrc));
-
-	pMem1 = (PUCHAR) pDest;
-	pMem2 = (PUCHAR) pSrc;
-
-	for (Index = 0; Index < Length; Index++)
-	{
-		pMem1[Index] = pMem2[Index];
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Initialize port configuration structure
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	UserCfgInit(
-	IN	PRTMP_ADAPTER pAd)
-{
-//	EDCA_PARM DefaultEdcaParm;
-    UINT key_index, bss_index;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> UserCfgInit\n"));
-
-	//
-	//  part I. intialize common configuration
-	//
-#ifdef RT2870
-	pAd->BulkOutReq = 0;
-
-	pAd->BulkOutComplete = 0;
-	pAd->BulkOutCompleteOther = 0;
-	pAd->BulkOutCompleteCancel = 0;
-	pAd->BulkInReq = 0;
-	pAd->BulkInComplete = 0;
-	pAd->BulkInCompleteFail = 0;
-
-	//pAd->QuickTimerP = 100;
-	//pAd->TurnAggrBulkInCount = 0;
-	pAd->bUsbTxBulkAggre = 0;
-
-	// init as unsed value to ensure driver will set to MCU once.
-	pAd->LedIndicatorStregth = 0xFF;
-
-	pAd->CommonCfg.MaxPktOneTxBulk = 2;
-	pAd->CommonCfg.TxBulkFactor = 1;
-	pAd->CommonCfg.RxBulkFactor =1;
-
-	pAd->CommonCfg.TxPower = 100; //mW
-
-	NdisZeroMemory(&pAd->CommonCfg.IOTestParm, sizeof(pAd->CommonCfg.IOTestParm));
-#endif // RT2870 //
-
-	for(key_index=0; key_index<SHARE_KEY_NUM; key_index++)
-	{
-		for(bss_index = 0; bss_index < MAX_MBSSID_NUM; bss_index++)
-		{
-			pAd->SharedKey[bss_index][key_index].KeyLen = 0;
-			pAd->SharedKey[bss_index][key_index].CipherAlg = CIPHER_NONE;
-		}
-	}
-
-	pAd->Antenna.word = 0;
-	pAd->CommonCfg.BBPCurrentBW = BW_20;
-
-	pAd->LedCntl.word = 0;
-
-	pAd->bAutoTxAgcA = FALSE;			// Default is OFF
-	pAd->bAutoTxAgcG = FALSE;			// Default is OFF
-	pAd->RfIcType = RFIC_2820;
-
-	// Init timer for reset complete event
-	pAd->CommonCfg.CentralChannel = 1;
-	pAd->bForcePrintTX = FALSE;
-	pAd->bForcePrintRX = FALSE;
-	pAd->bStaFifoTest = FALSE;
-	pAd->bProtectionTest = FALSE;
-	pAd->bHCCATest = FALSE;
-	pAd->bGenOneHCCA = FALSE;
-	pAd->CommonCfg.Dsifs = 10;      // in units of usec
-	pAd->CommonCfg.TxPower = 100; //mW
-	pAd->CommonCfg.TxPowerPercentage = 0xffffffff; // AUTO
-	pAd->CommonCfg.TxPowerDefault = 0xffffffff; // AUTO
-	pAd->CommonCfg.TxPreamble = Rt802_11PreambleAuto; // use Long preamble on TX by defaut
-	pAd->CommonCfg.bUseZeroToDisableFragment = FALSE;
-	pAd->CommonCfg.RtsThreshold = 2347;
-	pAd->CommonCfg.FragmentThreshold = 2346;
-	pAd->CommonCfg.UseBGProtection = 0;    // 0: AUTO
-	pAd->CommonCfg.bEnableTxBurst = TRUE; //0;
-	pAd->CommonCfg.PhyMode = 0xff;     // unknown
-	pAd->CommonCfg.BandState = UNKNOWN_BAND;
-	pAd->CommonCfg.RadarDetect.CSPeriod = 10;
-	pAd->CommonCfg.RadarDetect.CSCount = 0;
-	pAd->CommonCfg.RadarDetect.RDMode = RD_NORMAL_MODE;
-	pAd->CommonCfg.RadarDetect.ChMovingTime = 65;
-	pAd->CommonCfg.RadarDetect.LongPulseRadarTh = 3;
-	pAd->CommonCfg.bAPSDCapable = FALSE;
-	pAd->CommonCfg.bNeedSendTriggerFrame = FALSE;
-	pAd->CommonCfg.TriggerTimerCount = 0;
-	pAd->CommonCfg.bAPSDForcePowerSave = FALSE;
-	pAd->CommonCfg.bCountryFlag = FALSE;
-	pAd->CommonCfg.TxStream = 0;
-	pAd->CommonCfg.RxStream = 0;
-
-	NdisZeroMemory(&pAd->BeaconTxWI, sizeof(pAd->BeaconTxWI));
-
-#ifdef DOT11_N_SUPPORT
-	NdisZeroMemory(&pAd->CommonCfg.HtCapability, sizeof(pAd->CommonCfg.HtCapability));
-	pAd->HTCEnable = FALSE;
-	pAd->bBroadComHT = FALSE;
-	pAd->CommonCfg.bRdg = FALSE;
-
-#ifdef DOT11N_DRAFT3
-	pAd->CommonCfg.Dot11OBssScanPassiveDwell = dot11OBSSScanPassiveDwell;	// Unit : TU. 5~1000
-	pAd->CommonCfg.Dot11OBssScanActiveDwell = dot11OBSSScanActiveDwell;	// Unit : TU. 10~1000
-	pAd->CommonCfg.Dot11BssWidthTriggerScanInt = dot11BSSWidthTriggerScanInterval;	// Unit : Second
-	pAd->CommonCfg.Dot11OBssScanPassiveTotalPerChannel = dot11OBSSScanPassiveTotalPerChannel;	// Unit : TU. 200~10000
-	pAd->CommonCfg.Dot11OBssScanActiveTotalPerChannel = dot11OBSSScanActiveTotalPerChannel;	// Unit : TU. 20~10000
-	pAd->CommonCfg.Dot11BssWidthChanTranDelayFactor = dot11BSSWidthChannelTransactionDelayFactor;
-	pAd->CommonCfg.Dot11OBssScanActivityThre = dot11BSSScanActivityThreshold;	// Unit : percentage
-	pAd->CommonCfg.Dot11BssWidthChanTranDelay = (pAd->CommonCfg.Dot11BssWidthTriggerScanInt * pAd->CommonCfg.Dot11BssWidthChanTranDelayFactor);
-#endif  // DOT11N_DRAFT3 //
-
-	NdisZeroMemory(&pAd->CommonCfg.AddHTInfo, sizeof(pAd->CommonCfg.AddHTInfo));
-	pAd->CommonCfg.BACapability.field.MMPSmode = MMPS_ENABLE;
-	pAd->CommonCfg.BACapability.field.MpduDensity = 0;
-	pAd->CommonCfg.BACapability.field.Policy = IMMED_BA;
-	pAd->CommonCfg.BACapability.field.RxBAWinLimit = 64; //32;
-	pAd->CommonCfg.BACapability.field.TxBAWinLimit = 64; //32;
-	DBGPRINT(RT_DEBUG_TRACE, ("--> UserCfgInit. BACapability = 0x%x\n", pAd->CommonCfg.BACapability.word));
-
-	pAd->CommonCfg.BACapability.field.AutoBA = FALSE;
-	BATableInit(pAd, &pAd->BATable);
-
-	pAd->CommonCfg.bExtChannelSwitchAnnouncement = 1;
-	pAd->CommonCfg.bHTProtect = 1;
-	pAd->CommonCfg.bMIMOPSEnable = TRUE;
-	pAd->CommonCfg.bBADecline = FALSE;
-	pAd->CommonCfg.bDisableReordering = FALSE;
-
-	pAd->CommonCfg.TxBASize = 7;
-
-	pAd->CommonCfg.REGBACapability.word = pAd->CommonCfg.BACapability.word;
-#endif // DOT11_N_SUPPORT //
-
-	//pAd->CommonCfg.HTPhyMode.field.BW = BW_20;
-	//pAd->CommonCfg.HTPhyMode.field.MCS = MCS_AUTO;
-	//pAd->CommonCfg.HTPhyMode.field.ShortGI = GI_800;
-	//pAd->CommonCfg.HTPhyMode.field.STBC = STBC_NONE;
-	pAd->CommonCfg.TxRate = RATE_6;
-
-	pAd->CommonCfg.MlmeTransmit.field.MCS = MCS_RATE_6;
-	pAd->CommonCfg.MlmeTransmit.field.BW = BW_20;
-	pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-
-	pAd->CommonCfg.BeaconPeriod = 100;     // in mSec
-
-	//
-	// part II. intialize STA specific configuration
-	//
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		RX_FILTER_SET_FLAG(pAd, fRX_FILTER_ACCEPT_DIRECT);
-		RX_FILTER_CLEAR_FLAG(pAd, fRX_FILTER_ACCEPT_MULTICAST);
-		RX_FILTER_SET_FLAG(pAd, fRX_FILTER_ACCEPT_BROADCAST);
-		RX_FILTER_SET_FLAG(pAd, fRX_FILTER_ACCEPT_ALL_MULTICAST);
-
-		pAd->StaCfg.Psm = PWR_ACTIVE;
-
-		pAd->StaCfg.OrigWepStatus = Ndis802_11EncryptionDisabled;
-		pAd->StaCfg.PairCipher = Ndis802_11EncryptionDisabled;
-		pAd->StaCfg.GroupCipher = Ndis802_11EncryptionDisabled;
-		pAd->StaCfg.bMixCipher = FALSE;
-		pAd->StaCfg.DefaultKeyId = 0;
-
-		// 802.1x port control
-		pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilter8021xWEP;
-		pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-		pAd->StaCfg.LastMicErrorTime = 0;
-		pAd->StaCfg.MicErrCnt        = 0;
-		pAd->StaCfg.bBlockAssoc      = FALSE;
-		pAd->StaCfg.WpaState         = SS_NOTUSE;
-
-		pAd->CommonCfg.NdisRadioStateOff = FALSE;		// New to support microsoft disable radio with OID command
-
-		pAd->StaCfg.RssiTrigger = 0;
-		NdisZeroMemory(&pAd->StaCfg.RssiSample, sizeof(RSSI_SAMPLE));
-		pAd->StaCfg.RssiTriggerMode = RSSI_TRIGGERED_UPON_BELOW_THRESHOLD;
-		pAd->StaCfg.AtimWin = 0;
-		pAd->StaCfg.DefaultListenCount = 3;//default listen count;
-		pAd->StaCfg.BssType = BSS_INFRA;  // BSS_INFRA or BSS_ADHOC or BSS_MONITOR
-		pAd->StaCfg.bScanReqIsFromWebUI = FALSE;
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_DOZE);
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_WAKEUP_NOW);
-
-		pAd->StaCfg.bAutoTxRateSwitch = TRUE;
-		pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-	}
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-	pAd->StaCfg.IEEE80211dClientMode = Rt802_11_D_None;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
-
-	// global variables mXXXX used in MAC protocol state machines
-	OPSTATUS_SET_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM);
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_ADHOC_ON);
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_INFRA_ON);
-
-	// PHY specification
-	pAd->CommonCfg.PhyMode = PHY_11BG_MIXED;		// default PHY mode
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);  // CCK use LONG preamble
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// user desired power mode
-		pAd->StaCfg.WindowsPowerMode = Ndis802_11PowerModeCAM;
-		pAd->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeCAM;
-		pAd->StaCfg.bWindowsACCAMEnable = FALSE;
-
-#ifdef LEAP_SUPPORT
-		// CCX v1.0 releated init value
-		RTMPInitTimer(pAd, &pAd->StaCfg.LeapAuthTimer, GET_TIMER_FUNCTION(LeapAuthTimeout), pAd, FALSE);
-		pAd->StaCfg.LeapAuthMode = CISCO_AuthModeLEAPNone;
-		pAd->StaCfg.bCkipOn = FALSE;
-#endif // LEAP_SUPPORT //
-
-		RTMPInitTimer(pAd, &pAd->StaCfg.StaQuickResponeForRateUpTimer, GET_TIMER_FUNCTION(StaQuickResponeForRateUpExec), pAd, FALSE);
-		pAd->StaCfg.StaQuickResponeForRateUpTimerRunning = FALSE;
-
-		// Patch for Ndtest
-		pAd->StaCfg.ScanCnt = 0;
-
-		// CCX 2.0 control flag init
-		pAd->StaCfg.CCXEnable = FALSE;
-		pAd->StaCfg.CCXReqType = MSRN_TYPE_UNUSED;
-		pAd->StaCfg.CCXQosECWMin	= 4;
-		pAd->StaCfg.CCXQosECWMax	= 10;
-
-		pAd->StaCfg.bHwRadio  = TRUE; // Default Hardware Radio status is On
-		pAd->StaCfg.bSwRadio  = TRUE; // Default Software Radio status is On
-		pAd->StaCfg.bRadio    = TRUE; // bHwRadio && bSwRadio
-		pAd->StaCfg.bHardwareRadio = FALSE;		// Default is OFF
-		pAd->StaCfg.bShowHiddenSSID = FALSE;		// Default no show
-
-		// Nitro mode control
-		pAd->StaCfg.bAutoReconnect = TRUE;
-
-		// Save the init time as last scan time, the system should do scan after 2 seconds.
-		// This patch is for driver wake up from standby mode, system will do scan right away.
-		pAd->StaCfg.LastScanTime = 0;
-		NdisZeroMemory(pAd->nickname, IW_ESSID_MAX_SIZE+1);
-		sprintf(pAd->nickname, "%s", STA_NIC_DEVICE_NAME);
-		RTMPInitTimer(pAd, &pAd->StaCfg.WpaDisassocAndBlockAssocTimer, GET_TIMER_FUNCTION(WpaDisassocApAndBlockAssoc), pAd, FALSE);
-#ifdef WPA_SUPPLICANT_SUPPORT
-		pAd->StaCfg.IEEE8021X = FALSE;
-		pAd->StaCfg.IEEE8021x_required_keys = FALSE;
-		pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_DISABLE;
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-		pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_ENABLE;
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Default for extra information is not valid
-	pAd->ExtraInfo = EXTRA_INFO_CLEAR;
-
-	// Default Config change flag
-	pAd->bConfigChanged = FALSE;
-
-	//
-	// part III. AP configurations
-	//
-
-
-	//
-	// part IV. others
-	//
-	// dynamic BBP R66:sensibity tuning to overcome background noise
-	pAd->BbpTuning.bEnable                = TRUE;
-	pAd->BbpTuning.FalseCcaLowerThreshold = 100;
-	pAd->BbpTuning.FalseCcaUpperThreshold = 512;
-	pAd->BbpTuning.R66Delta               = 4;
-	pAd->Mlme.bEnableAutoAntennaCheck = TRUE;
-
-	//
-	// Also initial R66CurrentValue, RTUSBResumeMsduTransmission might use this value.
-	// if not initial this value, the default value will be 0.
-	//
-	pAd->BbpTuning.R66CurrentValue = 0x38;
-
-	pAd->Bbp94 = BBPR94_DEFAULT;
-	pAd->BbpForCCK = FALSE;
-
-	// Default is FALSE for test bit 1
-	//pAd->bTest1 = FALSE;
-
-	// initialize MAC table and allocate spin lock
-	NdisZeroMemory(&pAd->MacTab, sizeof(MAC_TABLE));
-	InitializeQueueHeader(&pAd->MacTab.McastPsQueue);
-	NdisAllocateSpinLock(&pAd->MacTabLock);
-
-	//RTMPInitTimer(pAd, &pAd->RECBATimer, RECBATimerTimeout, pAd, TRUE);
-	//RTMPSetTimer(&pAd->RECBATimer, REORDER_EXEC_INTV);
-
-#ifdef RALINK_ATE
-	NdisZeroMemory(&pAd->ate, sizeof(ATE_INFO));
-	pAd->ate.Mode = ATE_STOP;
-	pAd->ate.TxCount = 200;/* to exceed TX_RING_SIZE ... */
-	pAd->ate.TxLength = 1024;
-	pAd->ate.TxWI.ShortGI = 0;// LONG GI : 800 ns
-	pAd->ate.TxWI.PHYMODE = MODE_CCK;
-	pAd->ate.TxWI.MCS = 3;
-	pAd->ate.TxWI.BW = BW_20;
-	pAd->ate.Channel = 1;
-	pAd->ate.QID = QID_AC_BE;
-	pAd->ate.Addr1[0] = 0x00;
-	pAd->ate.Addr1[1] = 0x11;
-	pAd->ate.Addr1[2] = 0x22;
-	pAd->ate.Addr1[3] = 0xAA;
-	pAd->ate.Addr1[4] = 0xBB;
-	pAd->ate.Addr1[5] = 0xCC;
-	NdisMoveMemory(pAd->ate.Addr2, pAd->ate.Addr1, ETH_LENGTH_OF_ADDRESS);
-	NdisMoveMemory(pAd->ate.Addr3, pAd->ate.Addr1, ETH_LENGTH_OF_ADDRESS);
-	pAd->ate.bRxFer = 0;
-	pAd->ate.bQATxStart = FALSE;
-	pAd->ate.bQARxStart = FALSE;
-#ifdef RALINK_28xx_QA
-	//pAd->ate.Repeat = 0;
-	pAd->ate.TxStatus = 0;
-	pAd->ate.AtePid = NULL;
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-
-	pAd->CommonCfg.bWiFiTest = FALSE;
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- UserCfgInit\n"));
-}
-
-// IRQL = PASSIVE_LEVEL
-UCHAR BtoH(char ch)
-{
-	if (ch >= '0' && ch <= '9') return (ch - '0');        // Handle numerals
-	if (ch >= 'A' && ch <= 'F') return (ch - 'A' + 0xA);  // Handle capitol hex digits
-	if (ch >= 'a' && ch <= 'f') return (ch - 'a' + 0xA);  // Handle small hex digits
-	return(255);
-}
-
-//
-//  FUNCTION: AtoH(char *, UCHAR *, int)
-//
-//  PURPOSE:  Converts ascii string to network order hex
-//
-//  PARAMETERS:
-//    src    - pointer to input ascii string
-//    dest   - pointer to output hex
-//    destlen - size of dest
-//
-//  COMMENTS:
-//
-//    2 ascii bytes make a hex byte so must put 1st ascii byte of pair
-//    into upper nibble and 2nd ascii byte of pair into lower nibble.
-//
-// IRQL = PASSIVE_LEVEL
-
-void AtoH(char * src, UCHAR * dest, int destlen)
-{
-	char * srcptr;
-	PUCHAR destTemp;
-
-	srcptr = src;
-	destTemp = (PUCHAR) dest;
-
-	while(destlen--)
-	{
-		*destTemp = BtoH(*srcptr++) << 4;    // Put 1st ascii byte in upper nibble.
-		*destTemp += BtoH(*srcptr++);      // Add 2nd ascii byte to above.
-		destTemp++;
-	}
-}
-
-VOID	RTMPPatchMacBbpBug(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	ULONG	Index;
-
-	// Initialize BBP register to default value
-	for (Index = 0; Index < NUM_BBP_REG_PARMS; Index++)
-	{
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBPRegTable[Index].Register, (UCHAR)BBPRegTable[Index].Value);
-	}
-
-	// Initialize RF register to default value
-	AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-	AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-
-	// Re-init BBP register from EEPROM value
-	NICInitAsicFromEEPROM(pAd);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Init timer objects
-
-	Arguments:
-		pAd			Pointer to our adapter
-		pTimer				Timer structure
-		pTimerFunc			Function to execute when timer expired
-		Repeat				Ture for period timer
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPInitTimer(
-	IN	PRTMP_ADAPTER			pAd,
-	IN	PRALINK_TIMER_STRUCT	pTimer,
-	IN	PVOID					pTimerFunc,
-	IN	PVOID					pData,
-	IN	BOOLEAN					Repeat)
-{
-	//
-	// Set Valid to TRUE for later used.
-	// It will crash if we cancel a timer or set a timer
-	// that we haven't initialize before.
-	//
-	pTimer->Valid      = TRUE;
-
-	pTimer->PeriodicType = Repeat;
-	pTimer->State      = FALSE;
-	pTimer->cookie = (ULONG) pData;
-
-#ifdef RT2870
-	pTimer->pAd = pAd;
-#endif // RT2870 //
-
-	RTMP_OS_Init_Timer(pAd,	&pTimer->TimerObj,	pTimerFunc, (PVOID) pTimer);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Init timer objects
-
-	Arguments:
-		pTimer				Timer structure
-		Value				Timer value in milliseconds
-
-	Return Value:
-		None
-
-	Note:
-		To use this routine, must call RTMPInitTimer before.
-
-	========================================================================
-*/
-VOID	RTMPSetTimer(
-	IN	PRALINK_TIMER_STRUCT	pTimer,
-	IN	ULONG					Value)
-{
-	if (pTimer->Valid)
-	{
-		pTimer->TimerValue = Value;
-		pTimer->State      = FALSE;
-		if (pTimer->PeriodicType == TRUE)
-		{
-			pTimer->Repeat = TRUE;
-			RTMP_SetPeriodicTimer(&pTimer->TimerObj, Value);
-		}
-		else
-		{
-			pTimer->Repeat = FALSE;
-			RTMP_OS_Add_Timer(&pTimer->TimerObj, Value);
-		}
-	}
-	else
-	{
-		DBGPRINT_ERR(("RTMPSetTimer failed, Timer hasn't been initialize!\n"));
-	}
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Init timer objects
-
-	Arguments:
-		pTimer				Timer structure
-		Value				Timer value in milliseconds
-
-	Return Value:
-		None
-
-	Note:
-		To use this routine, must call RTMPInitTimer before.
-
-	========================================================================
-*/
-VOID	RTMPModTimer(
-	IN	PRALINK_TIMER_STRUCT	pTimer,
-	IN	ULONG					Value)
-{
-	BOOLEAN	Cancel;
-
-	if (pTimer->Valid)
-	{
-		pTimer->TimerValue = Value;
-		pTimer->State      = FALSE;
-		if (pTimer->PeriodicType == TRUE)
-		{
-			RTMPCancelTimer(pTimer, &Cancel);
-			RTMPSetTimer(pTimer, Value);
-		}
-		else
-		{
-			RTMP_OS_Mod_Timer(&pTimer->TimerObj, Value);
-		}
-	}
-	else
-	{
-		DBGPRINT_ERR(("RTMPModTimer failed, Timer hasn't been initialize!\n"));
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Cancel timer objects
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-		1.) To use this routine, must call RTMPInitTimer before.
-		2.) Reset NIC to initial state AS IS system boot up time.
-
-	========================================================================
-*/
-VOID	RTMPCancelTimer(
-	IN	PRALINK_TIMER_STRUCT	pTimer,
-	OUT	BOOLEAN					*pCancelled)
-{
-	if (pTimer->Valid)
-	{
-		if (pTimer->State == FALSE)
-			pTimer->Repeat = FALSE;
-			RTMP_OS_Del_Timer(&pTimer->TimerObj, pCancelled);
-
-		if (*pCancelled == TRUE)
-			pTimer->State = TRUE;
-
-#ifdef RT2870
-		// We need to go-through the TimerQ to findout this timer handler and remove it if
-		//		it's still waiting for execution.
-
-		RT2870_TimerQ_Remove(pTimer->pAd, pTimer);
-#endif // RT2870 //
-	}
-	else
-	{
-		//
-		// NdisMCancelTimer just canced the timer and not mean release the timer.
-		// And don't set the "Valid" to False. So that we can use this timer again.
-		//
-		DBGPRINT_ERR(("RTMPCancelTimer failed, Timer hasn't been initialize!\n"));
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Set LED Status
-
-	Arguments:
-		pAd						Pointer to our adapter
-		Status					LED Status
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID RTMPSetLED(
-	IN PRTMP_ADAPTER 	pAd,
-	IN UCHAR			Status)
-{
-	//ULONG			data;
-	UCHAR			HighByte = 0;
-	UCHAR			LowByte;
-
-// In ATE mode of RT2860 AP/STA, we have erased 8051 firmware.
-// So LED mode is not supported when ATE is running.
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	LowByte = pAd->LedCntl.field.LedMode&0x7f;
-	switch (Status)
-	{
-		case LED_LINK_DOWN:
-			HighByte = 0x20;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			pAd->LedIndicatorStregth = 0;
-			break;
-		case LED_LINK_UP:
-			if (pAd->CommonCfg.Channel > 14)
-				HighByte = 0xa0;
-			else
-				HighByte = 0x60;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-		case LED_RADIO_ON:
-			HighByte = 0x20;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-		case LED_HALT:
-			LowByte = 0; // Driver sets MAC register and MAC controls LED
-		case LED_RADIO_OFF:
-			HighByte = 0;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-        case LED_WPS:
-			HighByte = 0x10;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-		case LED_ON_SITE_SURVEY:
-			HighByte = 0x08;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-		case LED_POWER_UP:
-			HighByte = 0x04;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-		default:
-			DBGPRINT(RT_DEBUG_WARN, ("RTMPSetLED::Unknown Status %d\n", Status));
-			break;
-	}
-
-    //
-	// Keep LED status for LED SiteSurvey mode.
-	// After SiteSurvey, we will set the LED mode to previous status.
-	//
-	if ((Status != LED_ON_SITE_SURVEY) && (Status != LED_POWER_UP))
-		pAd->LedStatus = Status;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSetLED::Mode=%d,HighByte=0x%02x,LowByte=0x%02x\n", pAd->LedCntl.field.LedMode, HighByte, LowByte));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Set LED Signal Stregth
-
-	Arguments:
-		pAd						Pointer to our adapter
-		Dbm						Signal Stregth
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-		Can be run on any IRQL level.
-
-		According to Microsoft Zero Config Wireless Signal Stregth definition as belows.
-		<= -90  No Signal
-		<= -81  Very Low
-		<= -71  Low
-		<= -67  Good
-		<= -57  Very Good
-		 > -57  Excellent
-	========================================================================
-*/
-VOID RTMPSetSignalLED(
-	IN PRTMP_ADAPTER 	pAd,
-	IN NDIS_802_11_RSSI Dbm)
-{
-	UCHAR		nLed = 0;
-
-	//
-	// if not Signal Stregth, then do nothing.
-	//
-	if (pAd->LedCntl.field.LedMode != LED_MODE_SIGNAL_STREGTH)
-	{
-		return;
-	}
-
-	if (Dbm <= -90)
-		nLed = 0;
-	else if (Dbm <= -81)
-		nLed = 1;
-	else if (Dbm <= -71)
-		nLed = 3;
-	else if (Dbm <= -67)
-		nLed = 7;
-	else if (Dbm <= -57)
-		nLed = 15;
-	else
-		nLed = 31;
-
-	//
-	// Update Signal Stregth to firmware if changed.
-	//
-	if (pAd->LedIndicatorStregth != nLed)
-	{
-		AsicSendCommandToMcu(pAd, 0x51, 0xff, nLed, pAd->LedCntl.field.Polarity);
-		pAd->LedIndicatorStregth = nLed;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Enable RX
-
-	Arguments:
-		pAd						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL <= DISPATCH_LEVEL
-
-	Note:
-		Before Enable RX, make sure you have enabled Interrupt.
-	========================================================================
-*/
-VOID RTMPEnableRxTx(
-	IN PRTMP_ADAPTER	pAd)
-{
-//	WPDMA_GLO_CFG_STRUC	GloCfg;
-//	ULONG	i = 0;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==> RTMPEnableRxTx\n"));
-
-#if 0
-	// Enable Rx DMA.
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x4);
-	do
-	{
-		RTMP_IO_READ32(pAd, WPDMA_GLO_CFG, &GloCfg.word);
-		if ((GloCfg.field.TxDMABusy == 0)  && (GloCfg.field.RxDMABusy == 0))
-			break;
-
-		DBGPRINT(RT_DEBUG_TRACE, ("==>  DMABusy\n"));
-		RTMPusecDelay(1000);
-		i++;
-	}while ( i <200);
-
-	RTMPusecDelay(50);
-	RT28XX_DMA_WRITE_INIT(GloCfg);
-	DBGPRINT(RT_DEBUG_TRACE, ("<== WRITE DMA offset 0x208 = 0x%x\n", GloCfg.word));
-	RTMP_IO_WRITE32(pAd, WPDMA_GLO_CFG, GloCfg.word);
-
-	RT28XX_DMA_POST_WRITE(pAd);
-#else
-	// Enable Rx DMA.
-	RT28XXDMAEnable(pAd);
-#endif
-
-	// enable RX of MAC block
-	if (pAd->OpMode == OPMODE_AP)
-	{
-		UINT32 rx_filter_flag = APNORMAL;
-
-
-		RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, rx_filter_flag);     // enable RX of DMA block
-	}
-	else
-	{
-		RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, STANORMAL);     // Staion not drop control frame will fail WiFi Certification.
-	}
-
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0xc);
-	DBGPRINT(RT_DEBUG_TRACE, ("<== RTMPEnableRxTx\n"));
-}
-
-
+#include "../../rt2860/common/rtmp_init.c"
diff --git a/drivers/staging/rt2870/common/rtmp_tkip.c b/drivers/staging/rt2870/common/rtmp_tkip.c
index 2847409..240bf67 100644
--- a/drivers/staging/rt2870/common/rtmp_tkip.c
+++ b/drivers/staging/rt2870/common/rtmp_tkip.c
@@ -1,1613 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtmp_tkip.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Paul Wu		02-25-02		Initial
-*/
-
-#include "../rt_config.h"
-
-// Rotation functions on 32 bit values
-#define ROL32( A, n ) \
-	( ((A) << (n)) | ( ((A)>>(32-(n))) & ( (1UL << (n)) - 1 ) ) )
-#define ROR32( A, n ) ROL32( (A), 32-(n) )
-
-UINT Tkip_Sbox_Lower[256] =
-{
-	0xA5,0x84,0x99,0x8D,0x0D,0xBD,0xB1,0x54,
-	0x50,0x03,0xA9,0x7D,0x19,0x62,0xE6,0x9A,
-	0x45,0x9D,0x40,0x87,0x15,0xEB,0xC9,0x0B,
-	0xEC,0x67,0xFD,0xEA,0xBF,0xF7,0x96,0x5B,
-	0xC2,0x1C,0xAE,0x6A,0x5A,0x41,0x02,0x4F,
-	0x5C,0xF4,0x34,0x08,0x93,0x73,0x53,0x3F,
-	0x0C,0x52,0x65,0x5E,0x28,0xA1,0x0F,0xB5,
-	0x09,0x36,0x9B,0x3D,0x26,0x69,0xCD,0x9F,
-	0x1B,0x9E,0x74,0x2E,0x2D,0xB2,0xEE,0xFB,
-	0xF6,0x4D,0x61,0xCE,0x7B,0x3E,0x71,0x97,
-	0xF5,0x68,0x00,0x2C,0x60,0x1F,0xC8,0xED,
-	0xBE,0x46,0xD9,0x4B,0xDE,0xD4,0xE8,0x4A,
-	0x6B,0x2A,0xE5,0x16,0xC5,0xD7,0x55,0x94,
-	0xCF,0x10,0x06,0x81,0xF0,0x44,0xBA,0xE3,
-	0xF3,0xFE,0xC0,0x8A,0xAD,0xBC,0x48,0x04,
-	0xDF,0xC1,0x75,0x63,0x30,0x1A,0x0E,0x6D,
-	0x4C,0x14,0x35,0x2F,0xE1,0xA2,0xCC,0x39,
-	0x57,0xF2,0x82,0x47,0xAC,0xE7,0x2B,0x95,
-	0xA0,0x98,0xD1,0x7F,0x66,0x7E,0xAB,0x83,
-	0xCA,0x29,0xD3,0x3C,0x79,0xE2,0x1D,0x76,
-	0x3B,0x56,0x4E,0x1E,0xDB,0x0A,0x6C,0xE4,
-	0x5D,0x6E,0xEF,0xA6,0xA8,0xA4,0x37,0x8B,
-	0x32,0x43,0x59,0xB7,0x8C,0x64,0xD2,0xE0,
-	0xB4,0xFA,0x07,0x25,0xAF,0x8E,0xE9,0x18,
-	0xD5,0x88,0x6F,0x72,0x24,0xF1,0xC7,0x51,
-	0x23,0x7C,0x9C,0x21,0xDD,0xDC,0x86,0x85,
-	0x90,0x42,0xC4,0xAA,0xD8,0x05,0x01,0x12,
-	0xA3,0x5F,0xF9,0xD0,0x91,0x58,0x27,0xB9,
-	0x38,0x13,0xB3,0x33,0xBB,0x70,0x89,0xA7,
-	0xB6,0x22,0x92,0x20,0x49,0xFF,0x78,0x7A,
-	0x8F,0xF8,0x80,0x17,0xDA,0x31,0xC6,0xB8,
-	0xC3,0xB0,0x77,0x11,0xCB,0xFC,0xD6,0x3A
-};
-
-UINT Tkip_Sbox_Upper[256] =
-{
-	0xC6,0xF8,0xEE,0xF6,0xFF,0xD6,0xDE,0x91,
-	0x60,0x02,0xCE,0x56,0xE7,0xB5,0x4D,0xEC,
-	0x8F,0x1F,0x89,0xFA,0xEF,0xB2,0x8E,0xFB,
-	0x41,0xB3,0x5F,0x45,0x23,0x53,0xE4,0x9B,
-	0x75,0xE1,0x3D,0x4C,0x6C,0x7E,0xF5,0x83,
-	0x68,0x51,0xD1,0xF9,0xE2,0xAB,0x62,0x2A,
-	0x08,0x95,0x46,0x9D,0x30,0x37,0x0A,0x2F,
-	0x0E,0x24,0x1B,0xDF,0xCD,0x4E,0x7F,0xEA,
-	0x12,0x1D,0x58,0x34,0x36,0xDC,0xB4,0x5B,
-	0xA4,0x76,0xB7,0x7D,0x52,0xDD,0x5E,0x13,
-	0xA6,0xB9,0x00,0xC1,0x40,0xE3,0x79,0xB6,
-	0xD4,0x8D,0x67,0x72,0x94,0x98,0xB0,0x85,
-	0xBB,0xC5,0x4F,0xED,0x86,0x9A,0x66,0x11,
-	0x8A,0xE9,0x04,0xFE,0xA0,0x78,0x25,0x4B,
-	0xA2,0x5D,0x80,0x05,0x3F,0x21,0x70,0xF1,
-	0x63,0x77,0xAF,0x42,0x20,0xE5,0xFD,0xBF,
-	0x81,0x18,0x26,0xC3,0xBE,0x35,0x88,0x2E,
-	0x93,0x55,0xFC,0x7A,0xC8,0xBA,0x32,0xE6,
-	0xC0,0x19,0x9E,0xA3,0x44,0x54,0x3B,0x0B,
-	0x8C,0xC7,0x6B,0x28,0xA7,0xBC,0x16,0xAD,
-	0xDB,0x64,0x74,0x14,0x92,0x0C,0x48,0xB8,
-	0x9F,0xBD,0x43,0xC4,0x39,0x31,0xD3,0xF2,
-	0xD5,0x8B,0x6E,0xDA,0x01,0xB1,0x9C,0x49,
-	0xD8,0xAC,0xF3,0xCF,0xCA,0xF4,0x47,0x10,
-	0x6F,0xF0,0x4A,0x5C,0x38,0x57,0x73,0x97,
-	0xCB,0xA1,0xE8,0x3E,0x96,0x61,0x0D,0x0F,
-	0xE0,0x7C,0x71,0xCC,0x90,0x06,0xF7,0x1C,
-	0xC2,0x6A,0xAE,0x69,0x17,0x99,0x3A,0x27,
-	0xD9,0xEB,0x2B,0x22,0xD2,0xA9,0x07,0x33,
-	0x2D,0x3C,0x15,0xC9,0x87,0xAA,0x50,0xA5,
-	0x03,0x59,0x09,0x1A,0x65,0xD7,0x84,0xD0,
-	0x82,0x29,0x5A,0x1E,0x7B,0xA8,0x6D,0x2C
-};
-
-/*****************************/
-/******** SBOX Table *********/
-/*****************************/
-
-UCHAR SboxTable[256] =
-{
-	0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
-	0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
-	0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
-	0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
-	0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
-	0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
-	0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
-	0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
-	0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
-	0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
-	0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
-	0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
-	0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
-	0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
-	0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
-	0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
-	0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
-	0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
-	0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
-	0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
-	0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
-	0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
-	0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
-	0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
-	0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
-	0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
-	0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
-	0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
-	0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
-	0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
-	0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
-	0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
-};
-
-VOID xor_32(
-	IN  PUCHAR              a,
-	IN  PUCHAR              b,
-	OUT PUCHAR              out);
-
-VOID xor_128(
-	IN  PUCHAR              a,
-	IN  PUCHAR              b,
-	OUT PUCHAR              out);
-
-VOID next_key(
-	IN  PUCHAR              key,
-	IN  INT                 round);
-
-VOID byte_sub(
-	IN  PUCHAR              in,
-	OUT PUCHAR              out);
-
-VOID shift_row(
-	IN  PUCHAR              in,
-	OUT PUCHAR              out);
-
-VOID mix_column(
-	IN  PUCHAR              in,
-	OUT PUCHAR              out);
-
-UCHAR RTMPCkipSbox(
-	IN  UCHAR               a);
-//
-// Expanded IV for TKIP function.
-//
-typedef	struct	PACKED _IV_CONTROL_
-{
-	union PACKED
-	{
-		struct PACKED
-		{
-			UCHAR		rc0;
-			UCHAR		rc1;
-			UCHAR		rc2;
-
-			union PACKED
-			{
-				struct PACKED
-				{
-#ifdef RT_BIG_ENDIAN
-					UCHAR	KeyID:2;
-					UCHAR	ExtIV:1;
-					UCHAR	Rsvd:5;
-#else
-					UCHAR	Rsvd:5;
-					UCHAR	ExtIV:1;
-					UCHAR	KeyID:2;
-#endif
-				}	field;
-				UCHAR		Byte;
-			}	CONTROL;
-		}	field;
-
-		ULONG	word;
-	}	IV16;
-
-	ULONG	IV32;
-}	TKIP_IV, *PTKIP_IV;
-
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Convert from UCHAR[] to ULONG in a portable way
-
-	Arguments:
-      pMICKey		pointer to MIC Key
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-ULONG	RTMPTkipGetUInt32(
-	IN	PUCHAR	pMICKey)
-{
-	ULONG	res = 0;
-	INT		i;
-
-	for (i = 0; i < 4; i++)
-	{
-		res |= (*pMICKey++) << (8 * i);
-	}
-
-	return res;
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Convert from ULONG to UCHAR[] in a portable way
-
-	Arguments:
-      pDst			pointer to destination for convert ULONG to UCHAR[]
-      val			the value for convert
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPTkipPutUInt32(
-	IN OUT	PUCHAR		pDst,
-	IN		ULONG		val)
-{
-	INT i;
-
-	for(i = 0; i < 4; i++)
-	{
-		*pDst++ = (UCHAR) (val & 0xff);
-		val >>= 8;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Set the MIC Key.
-
-	Arguments:
-      pAd		Pointer to our adapter
-      pMICKey		pointer to MIC Key
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID RTMPTkipSetMICKey(
-	IN	PTKIP_KEY_INFO	pTkip,
-	IN	PUCHAR			pMICKey)
-{
-	// Set the key
-	pTkip->K0 = RTMPTkipGetUInt32(pMICKey);
-	pTkip->K1 = RTMPTkipGetUInt32(pMICKey + 4);
-	// and reset the message
-	pTkip->L = pTkip->K0;
-	pTkip->R = pTkip->K1;
-	pTkip->nBytesInM = 0;
-	pTkip->M = 0;
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Calculate the MIC Value.
-
-	Arguments:
-      pAd		Pointer to our adapter
-      uChar			Append this uChar
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPTkipAppendByte(
-	IN	PTKIP_KEY_INFO	pTkip,
-	IN	UCHAR 			uChar)
-{
-	// Append the byte to our word-sized buffer
-	pTkip->M |= (uChar << (8* pTkip->nBytesInM));
-	pTkip->nBytesInM++;
-	// Process the word if it is full.
-	if( pTkip->nBytesInM >= 4 )
-	{
-		pTkip->L ^= pTkip->M;
-		pTkip->R ^= ROL32( pTkip->L, 17 );
-		pTkip->L += pTkip->R;
-		pTkip->R ^= ((pTkip->L & 0xff00ff00) >> 8) | ((pTkip->L & 0x00ff00ff) << 8);
-		pTkip->L += pTkip->R;
-		pTkip->R ^= ROL32( pTkip->L, 3 );
-		pTkip->L += pTkip->R;
-		pTkip->R ^= ROR32( pTkip->L, 2 );
-		pTkip->L += pTkip->R;
-		// Clear the buffer
-		pTkip->M = 0;
-		pTkip->nBytesInM = 0;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Calculate the MIC Value.
-
-	Arguments:
-      pAd		Pointer to our adapter
-      pSrc			Pointer to source data for Calculate MIC Value
-      Len			Indicate the length of the source data
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPTkipAppend(
-	IN	PTKIP_KEY_INFO	pTkip,
-	IN	PUCHAR			pSrc,
-	IN	UINT			nBytes)
-{
-	// This is simple
-	while(nBytes > 0)
-	{
-		RTMPTkipAppendByte(pTkip, *pSrc++);
-		nBytes--;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Get the MIC Value.
-
-	Arguments:
-      pAd		Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-		the MIC Value is store in pAd->PrivateInfo.MIC
-	========================================================================
-*/
-VOID	RTMPTkipGetMIC(
-	IN	PTKIP_KEY_INFO	pTkip)
-{
-	// Append the minimum padding
-	RTMPTkipAppendByte(pTkip, 0x5a );
-	RTMPTkipAppendByte(pTkip, 0 );
-	RTMPTkipAppendByte(pTkip, 0 );
-	RTMPTkipAppendByte(pTkip, 0 );
-	RTMPTkipAppendByte(pTkip, 0 );
-	// and then zeroes until the length is a multiple of 4
-	while( pTkip->nBytesInM != 0 )
-	{
-		RTMPTkipAppendByte(pTkip, 0 );
-	}
-	// The appendByte function has already computed the result.
-	RTMPTkipPutUInt32(pTkip->MIC, pTkip->L);
-	RTMPTkipPutUInt32(pTkip->MIC + 4, pTkip->R);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Init Tkip function.
-
-	Arguments:
-      pAd		Pointer to our adapter
-		pTKey       Pointer to the Temporal Key (TK), TK shall be 128bits.
-		KeyId		TK Key ID
-		pTA			Pointer to transmitter address
-		pMICKey		pointer to MIC Key
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPInitTkipEngine(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pKey,
-	IN	UCHAR			KeyId,
-	IN	PUCHAR			pTA,
-	IN	PUCHAR			pMICKey,
-	IN	PUCHAR			pTSC,
-	OUT	PULONG			pIV16,
-	OUT	PULONG			pIV32)
-{
-	TKIP_IV	tkipIv;
-
-	// Prepare 8 bytes TKIP encapsulation for MPDU
-	NdisZeroMemory(&tkipIv, sizeof(TKIP_IV));
-	tkipIv.IV16.field.rc0 = *(pTSC + 1);
-	tkipIv.IV16.field.rc1 = (tkipIv.IV16.field.rc0 | 0x20) & 0x7f;
-	tkipIv.IV16.field.rc2 = *pTSC;
-	tkipIv.IV16.field.CONTROL.field.ExtIV = 1;  // 0: non-extended IV, 1: an extended IV
-	tkipIv.IV16.field.CONTROL.field.KeyID = KeyId;
-//	tkipIv.IV32 = *(PULONG)(pTSC + 2);
-	NdisMoveMemory(&tkipIv.IV32, (pTSC + 2), 4);   // Copy IV
-
-	*pIV16 = tkipIv.IV16.word;
-	*pIV32 = tkipIv.IV32;
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Init MIC Value calculation function which include set MIC key &
-		calculate first 16 bytes (DA + SA + priority +  0)
-
-	Arguments:
-      pAd		Pointer to our adapter
-		pTKey       Pointer to the Temporal Key (TK), TK shall be 128bits.
-		pDA			Pointer to DA address
-		pSA			Pointer to SA address
-		pMICKey		pointer to MIC Key
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPInitMICEngine(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pKey,
-	IN	PUCHAR			pDA,
-	IN	PUCHAR			pSA,
-	IN  UCHAR           UserPriority,
-	IN	PUCHAR			pMICKey)
-{
-	ULONG Priority = UserPriority;
-
-	// Init MIC value calculation
-	RTMPTkipSetMICKey(&pAd->PrivateInfo.Tx, pMICKey);
-	// DA
-	RTMPTkipAppend(&pAd->PrivateInfo.Tx, pDA, MAC_ADDR_LEN);
-	// SA
-	RTMPTkipAppend(&pAd->PrivateInfo.Tx, pSA, MAC_ADDR_LEN);
-	// Priority + 3 bytes of 0
-	RTMPTkipAppend(&pAd->PrivateInfo.Tx, (PUCHAR)&Priority, 4);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Compare MIC value of received MSDU
-
-	Arguments:
-		pAd	Pointer to our adapter
-		pSrc        Pointer to the received Plain text data
-		pDA			Pointer to DA address
-		pSA			Pointer to SA address
-		pMICKey		pointer to MIC Key
-		Len         the length of the received plain text data exclude MIC value
-
-	Return Value:
-		TRUE        MIC value matched
-		FALSE       MIC value mismatched
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-BOOLEAN	RTMPTkipCompareMICValue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pSrc,
-	IN	PUCHAR			pDA,
-	IN	PUCHAR			pSA,
-	IN	PUCHAR			pMICKey,
-	IN	UCHAR			UserPriority,
-	IN	UINT			Len)
-{
-	UCHAR	OldMic[8];
-	ULONG	Priority = UserPriority;
-
-	// Init MIC value calculation
-	RTMPTkipSetMICKey(&pAd->PrivateInfo.Rx, pMICKey);
-	// DA
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pDA, MAC_ADDR_LEN);
-	// SA
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pSA, MAC_ADDR_LEN);
-	// Priority + 3 bytes of 0
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, (PUCHAR)&Priority, 4);
-
-	// Calculate MIC value from plain text data
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pSrc, Len);
-
-	// Get MIC valude from received frame
-	NdisMoveMemory(OldMic, pSrc + Len, 8);
-
-	// Get MIC value from decrypted plain data
-	RTMPTkipGetMIC(&pAd->PrivateInfo.Rx);
-
-	// Move MIC value from MSDU, this steps should move to data path.
-	// Since the MIC value might cross MPDUs.
-	if(!NdisEqualMemory(pAd->PrivateInfo.Rx.MIC, OldMic, 8))
-	{
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("RTMPTkipCompareMICValue(): TKIP MIC Error !\n"));  //MIC error.
-
-
-		return (FALSE);
-	}
-	return (TRUE);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Compare MIC value of received MSDU
-
-	Arguments:
-		pAd	Pointer to our adapter
-		pLLC		LLC header
-		pSrc        Pointer to the received Plain text data
-		pDA			Pointer to DA address
-		pSA			Pointer to SA address
-		pMICKey		pointer to MIC Key
-		Len         the length of the received plain text data exclude MIC value
-
-	Return Value:
-		TRUE        MIC value matched
-		FALSE       MIC value mismatched
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-BOOLEAN	RTMPTkipCompareMICValueWithLLC(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pLLC,
-	IN	PUCHAR			pSrc,
-	IN	PUCHAR			pDA,
-	IN	PUCHAR			pSA,
-	IN	PUCHAR			pMICKey,
-	IN	UINT			Len)
-{
-	UCHAR	OldMic[8];
-	ULONG	Priority = 0;
-
-	// Init MIC value calculation
-	RTMPTkipSetMICKey(&pAd->PrivateInfo.Rx, pMICKey);
-	// DA
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pDA, MAC_ADDR_LEN);
-	// SA
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pSA, MAC_ADDR_LEN);
-	// Priority + 3 bytes of 0
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, (PUCHAR)&Priority, 4);
-
-	// Start with LLC header
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pLLC, 8);
-
-	// Calculate MIC value from plain text data
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pSrc, Len);
-
-	// Get MIC valude from received frame
-	NdisMoveMemory(OldMic, pSrc + Len, 8);
-
-	// Get MIC value from decrypted plain data
-	RTMPTkipGetMIC(&pAd->PrivateInfo.Rx);
-
-	// Move MIC value from MSDU, this steps should move to data path.
-	// Since the MIC value might cross MPDUs.
-	if(!NdisEqualMemory(pAd->PrivateInfo.Rx.MIC, OldMic, 8))
-	{
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("RTMPTkipCompareMICValueWithLLC(): TKIP MIC Error !\n"));  //MIC error.
-
-
-		return (FALSE);
-	}
-	return (TRUE);
-}
-/*
-	========================================================================
-
-	Routine	Description:
-		Copy frame from waiting queue into relative ring buffer and set
-	appropriate ASIC register to kick hardware transmit function
-
-	Arguments:
-		pAd		Pointer	to our adapter
-		PNDIS_PACKET	Pointer to Ndis Packet for MIC calculation
-		pEncap			Pointer to LLC encap data
-		LenEncap		Total encap length, might be 0 which indicates no encap
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPCalculateMICValue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR			pEncap,
-	IN	PCIPHER_KEY		pKey,
-	IN	UCHAR			apidx)
-{
-	PACKET_INFO		PacketInfo;
-	PUCHAR			pSrcBufVA;
-	UINT			SrcBufLen;
-	PUCHAR			pSrc;
-    UCHAR           UserPriority;
-	UCHAR			vlan_offset = 0;
-
-	RTMP_QueryPacketInfo(pPacket, &PacketInfo, &pSrcBufVA, &SrcBufLen);
-
-	UserPriority = RTMP_GET_PACKET_UP(pPacket);
-	pSrc = pSrcBufVA;
-
-	// determine if this is a vlan packet
-	if (((*(pSrc + 12) << 8) + *(pSrc + 13)) == 0x8100)
-		vlan_offset = 4;
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-	{
-		RTMPInitMICEngine(
-			pAd,
-			pKey->Key,
-			pSrc,
-			pSrc + 6,
-			UserPriority,
-			pKey->TxMic);
-	}
-
-
-	if (pEncap != NULL)
-	{
-		// LLC encapsulation
-		RTMPTkipAppend(&pAd->PrivateInfo.Tx, pEncap, 6);
-		// Protocol Type
-		RTMPTkipAppend(&pAd->PrivateInfo.Tx, pSrc + 12 + vlan_offset, 2);
-	}
-	SrcBufLen -= (14 + vlan_offset);
-	pSrc += (14 + vlan_offset);
-	do
-	{
-		if (SrcBufLen > 0)
-		{
-			RTMPTkipAppend(&pAd->PrivateInfo.Tx, pSrc, SrcBufLen);
-		}
-
-		break;	// No need handle next packet
-
-	}	while (TRUE);		// End of copying payload
-
-	// Compute the final MIC Value
-	RTMPTkipGetMIC(&pAd->PrivateInfo.Tx);
-}
-
-
-/************************************************************/
-/* tkip_sbox()																*/
-/* Returns a 16 bit value from a 64K entry table. The Table */
-/* is synthesized from two 256 entry byte wide tables.		*/
-/************************************************************/
-
-UINT tkip_sbox(UINT index)
-{
-	UINT index_low;
-	UINT index_high;
-	UINT left, right;
-
-	index_low = (index % 256);
-	index_high = ((index >> 8) % 256);
-
-	left = Tkip_Sbox_Lower[index_low] + (Tkip_Sbox_Upper[index_low] * 256);
-	right = Tkip_Sbox_Upper[index_high] + (Tkip_Sbox_Lower[index_high] * 256);
-
-	return (left ^ right);
-}
-
-UINT rotr1(UINT a)
-{
-	unsigned int b;
-
-	if ((a & 0x01) == 0x01)
-	{
-		b = (a >> 1) | 0x8000;
-	}
-	else
-	{
-		b = (a >> 1) & 0x7fff;
-	}
-	b = b % 65536;
-	return b;
-}
-
-VOID RTMPTkipMixKey(
-	UCHAR *key,
-	UCHAR *ta,
-	ULONG pnl, /* Least significant 16 bits of PN */
-	ULONG pnh, /* Most significant 32 bits of PN */
-	UCHAR *rc4key,
-	UINT *p1k)
-{
-
-	UINT tsc0;
-	UINT tsc1;
-	UINT tsc2;
-
-	UINT ppk0;
-	UINT ppk1;
-	UINT ppk2;
-	UINT ppk3;
-	UINT ppk4;
-	UINT ppk5;
-
-	INT i;
-	INT j;
-
-	tsc0 = (unsigned int)((pnh >> 16) % 65536); /* msb */
-	tsc1 = (unsigned int)(pnh % 65536);
-	tsc2 = (unsigned int)(pnl % 65536); /* lsb */
-
-	/* Phase 1, step 1 */
-	p1k[0] = tsc1;
-	p1k[1] = tsc0;
-	p1k[2] = (UINT)(ta[0] + (ta[1]*256));
-	p1k[3] = (UINT)(ta[2] + (ta[3]*256));
-	p1k[4] = (UINT)(ta[4] + (ta[5]*256));
-
-	/* Phase 1, step 2 */
-	for (i=0; i<8; i++)
-	{
-		j = 2*(i & 1);
-		p1k[0] = (p1k[0] + tkip_sbox( (p1k[4] ^ ((256*key[1+j]) + key[j])) % 65536 )) % 65536;
-		p1k[1] = (p1k[1] + tkip_sbox( (p1k[0] ^ ((256*key[5+j]) + key[4+j])) % 65536 )) % 65536;
-		p1k[2] = (p1k[2] + tkip_sbox( (p1k[1] ^ ((256*key[9+j]) + key[8+j])) % 65536 )) % 65536;
-		p1k[3] = (p1k[3] + tkip_sbox( (p1k[2] ^ ((256*key[13+j]) + key[12+j])) % 65536 )) % 65536;
-		p1k[4] = (p1k[4] + tkip_sbox( (p1k[3] ^ (((256*key[1+j]) + key[j]))) % 65536 )) % 65536;
-		p1k[4] = (p1k[4] + i) % 65536;
-	}
-
-	/* Phase 2, Step 1 */
-	ppk0 = p1k[0];
-	ppk1 = p1k[1];
-	ppk2 = p1k[2];
-	ppk3 = p1k[3];
-	ppk4 = p1k[4];
-	ppk5 = (p1k[4] + tsc2) % 65536;
-
-	/* Phase2, Step 2 */
-	ppk0 = ppk0 + tkip_sbox( (ppk5 ^ ((256*key[1]) + key[0])) % 65536);
-	ppk1 = ppk1 + tkip_sbox( (ppk0 ^ ((256*key[3]) + key[2])) % 65536);
-	ppk2 = ppk2 + tkip_sbox( (ppk1 ^ ((256*key[5]) + key[4])) % 65536);
-	ppk3 = ppk3 + tkip_sbox( (ppk2 ^ ((256*key[7]) + key[6])) % 65536);
-	ppk4 = ppk4 + tkip_sbox( (ppk3 ^ ((256*key[9]) + key[8])) % 65536);
-	ppk5 = ppk5 + tkip_sbox( (ppk4 ^ ((256*key[11]) + key[10])) % 65536);
-
-	ppk0 = ppk0 + rotr1(ppk5 ^ ((256*key[13]) + key[12]));
-	ppk1 = ppk1 + rotr1(ppk0 ^ ((256*key[15]) + key[14]));
-	ppk2 = ppk2 + rotr1(ppk1);
-	ppk3 = ppk3 + rotr1(ppk2);
-	ppk4 = ppk4 + rotr1(ppk3);
-	ppk5 = ppk5 + rotr1(ppk4);
-
-	/* Phase 2, Step 3 */
-    /* Phase 2, Step 3 */
-
-	tsc0 = (unsigned int)((pnh >> 16) % 65536); /* msb */
-	tsc1 = (unsigned int)(pnh % 65536);
-	tsc2 = (unsigned int)(pnl % 65536); /* lsb */
-
-	rc4key[0] = (tsc2 >> 8) % 256;
-	rc4key[1] = (((tsc2 >> 8) % 256) | 0x20) & 0x7f;
-	rc4key[2] = tsc2 % 256;
-	rc4key[3] = ((ppk5 ^ ((256*key[1]) + key[0])) >> 1) % 256;
-
-	rc4key[4] = ppk0 % 256;
-	rc4key[5] = (ppk0 >> 8) % 256;
-
-	rc4key[6] = ppk1 % 256;
-	rc4key[7] = (ppk1 >> 8) % 256;
-
-	rc4key[8] = ppk2 % 256;
-	rc4key[9] = (ppk2 >> 8) % 256;
-
-	rc4key[10] = ppk3 % 256;
-	rc4key[11] = (ppk3 >> 8) % 256;
-
-	rc4key[12] = ppk4 % 256;
-	rc4key[13] = (ppk4 >> 8) % 256;
-
-	rc4key[14] = ppk5 % 256;
-	rc4key[15] = (ppk5 >> 8) % 256;
-}
-
-
-/************************************************/
-/* construct_mic_header1()                      */
-/* Builds the first MIC header block from       */
-/* header fields.                               */
-/************************************************/
-
-void construct_mic_header1(
-	unsigned char *mic_header1,
-	int header_length,
-	unsigned char *mpdu)
-{
-	mic_header1[0] = (unsigned char)((header_length - 2) / 256);
-	mic_header1[1] = (unsigned char)((header_length - 2) % 256);
-	mic_header1[2] = mpdu[0] & 0xcf;    /* Mute CF poll & CF ack bits */
-	mic_header1[3] = mpdu[1] & 0xc7;    /* Mute retry, more data and pwr mgt bits */
-	mic_header1[4] = mpdu[4];       /* A1 */
-	mic_header1[5] = mpdu[5];
-	mic_header1[6] = mpdu[6];
-	mic_header1[7] = mpdu[7];
-	mic_header1[8] = mpdu[8];
-	mic_header1[9] = mpdu[9];
-	mic_header1[10] = mpdu[10];     /* A2 */
-	mic_header1[11] = mpdu[11];
-	mic_header1[12] = mpdu[12];
-	mic_header1[13] = mpdu[13];
-	mic_header1[14] = mpdu[14];
-	mic_header1[15] = mpdu[15];
-}
-
-/************************************************/
-/* construct_mic_header2()                      */
-/* Builds the last MIC header block from        */
-/* header fields.                               */
-/************************************************/
-
-void construct_mic_header2(
-	unsigned char *mic_header2,
-	unsigned char *mpdu,
-	int a4_exists,
-	int qc_exists)
-{
-	int i;
-
-	for (i = 0; i<16; i++) mic_header2[i]=0x00;
-
-	mic_header2[0] = mpdu[16];    /* A3 */
-	mic_header2[1] = mpdu[17];
-	mic_header2[2] = mpdu[18];
-	mic_header2[3] = mpdu[19];
-	mic_header2[4] = mpdu[20];
-	mic_header2[5] = mpdu[21];
-
-	// In Sequence Control field, mute sequence numer bits (12-bit)
-	mic_header2[6] = mpdu[22] & 0x0f;   /* SC */
-	mic_header2[7] = 0x00; /* mpdu[23]; */
-
-	if ((!qc_exists) & a4_exists)
-	{
-		for (i=0;i<6;i++) mic_header2[8+i] = mpdu[24+i];   /* A4 */
-
-	}
-
-	if (qc_exists && (!a4_exists))
-	{
-		mic_header2[8] = mpdu[24] & 0x0f; /* mute bits 15 - 4 */
-		mic_header2[9] = mpdu[25] & 0x00;
-	}
-
-	if (qc_exists && a4_exists)
-	{
-		for (i=0;i<6;i++) mic_header2[8+i] = mpdu[24+i];   /* A4 */
-
-		mic_header2[14] = mpdu[30] & 0x0f;
-		mic_header2[15] = mpdu[31] & 0x00;
-	}
-}
-
-
-/************************************************/
-/* construct_mic_iv()                           */
-/* Builds the MIC IV from header fields and PN  */
-/************************************************/
-
-void construct_mic_iv(
-	unsigned char *mic_iv,
-	int qc_exists,
-	int a4_exists,
-	unsigned char *mpdu,
-	unsigned int payload_length,
-	unsigned char *pn_vector)
-{
-	int i;
-
-	mic_iv[0] = 0x59;
-	if (qc_exists && a4_exists)
-		mic_iv[1] = mpdu[30] & 0x0f;    /* QoS_TC           */
-	if (qc_exists && !a4_exists)
-		mic_iv[1] = mpdu[24] & 0x0f;   /* mute bits 7-4    */
-	if (!qc_exists)
-		mic_iv[1] = 0x00;
-	for (i = 2; i < 8; i++)
-		mic_iv[i] = mpdu[i + 8];                    /* mic_iv[2:7] = A2[0:5] = mpdu[10:15] */
-#ifdef CONSISTENT_PN_ORDER
-		for (i = 8; i < 14; i++)
-			mic_iv[i] = pn_vector[i - 8];           /* mic_iv[8:13] = PN[0:5] */
-#else
-		for (i = 8; i < 14; i++)
-			mic_iv[i] = pn_vector[13 - i];          /* mic_iv[8:13] = PN[5:0] */
-#endif
-	i = (payload_length / 256);
-	i = (payload_length % 256);
-	mic_iv[14] = (unsigned char) (payload_length / 256);
-	mic_iv[15] = (unsigned char) (payload_length % 256);
-
-}
-
-
-
-/************************************/
-/* bitwise_xor()                    */
-/* A 128 bit, bitwise exclusive or  */
-/************************************/
-
-void bitwise_xor(unsigned char *ina, unsigned char *inb, unsigned char *out)
-{
-	int i;
-	for (i=0; i<16; i++)
-	{
-		out[i] = ina[i] ^ inb[i];
-	}
-}
-
-
-void aes128k128d(unsigned char *key, unsigned char *data, unsigned char *ciphertext)
-{
-	int round;
-	int i;
-	unsigned char intermediatea[16];
-	unsigned char intermediateb[16];
-	unsigned char round_key[16];
-
-	for(i=0; i<16; i++) round_key[i] = key[i];
-
-	for (round = 0; round < 11; round++)
-	{
-		if (round == 0)
-		{
-			xor_128(round_key, data, ciphertext);
-			next_key(round_key, round);
-		}
-		else if (round == 10)
-		{
-			byte_sub(ciphertext, intermediatea);
-			shift_row(intermediatea, intermediateb);
-			xor_128(intermediateb, round_key, ciphertext);
-		}
-		else    /* 1 - 9 */
-		{
-			byte_sub(ciphertext, intermediatea);
-			shift_row(intermediatea, intermediateb);
-			mix_column(&intermediateb[0], &intermediatea[0]);
-			mix_column(&intermediateb[4], &intermediatea[4]);
-			mix_column(&intermediateb[8], &intermediatea[8]);
-			mix_column(&intermediateb[12], &intermediatea[12]);
-			xor_128(intermediatea, round_key, ciphertext);
-			next_key(round_key, round);
-		}
-	}
-
-}
-
-void construct_ctr_preload(
-	unsigned char *ctr_preload,
-	int a4_exists,
-	int qc_exists,
-	unsigned char *mpdu,
-	unsigned char *pn_vector,
-	int c)
-{
-
-	int i = 0;
-	for (i=0; i<16; i++) ctr_preload[i] = 0x00;
-	i = 0;
-
-	ctr_preload[0] = 0x01;                                  /* flag */
-	if (qc_exists && a4_exists) ctr_preload[1] = mpdu[30] & 0x0f;   /* QoC_Control  */
-	if (qc_exists && !a4_exists) ctr_preload[1] = mpdu[24] & 0x0f;
-
-	for (i = 2; i < 8; i++)
-		ctr_preload[i] = mpdu[i + 8];                       /* ctr_preload[2:7] = A2[0:5] = mpdu[10:15] */
-#ifdef CONSISTENT_PN_ORDER
-	  for (i = 8; i < 14; i++)
-			ctr_preload[i] =    pn_vector[i - 8];           /* ctr_preload[8:13] = PN[0:5] */
-#else
-	  for (i = 8; i < 14; i++)
-			ctr_preload[i] =    pn_vector[13 - i];          /* ctr_preload[8:13] = PN[5:0] */
-#endif
-	ctr_preload[14] =  (unsigned char) (c / 256); // Ctr
-	ctr_preload[15] =  (unsigned char) (c % 256);
-
-}
-
-
-//
-// TRUE: Success!
-// FALSE: Decrypt Error!
-//
-BOOLEAN RTMPSoftDecryptTKIP(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pData,
-	IN ULONG	DataByteCnt,
-	IN UCHAR    UserPriority,
-	IN PCIPHER_KEY	pWpaKey)
-{
-	UCHAR			KeyID;
-	UINT			HeaderLen;
-    UCHAR			fc0;
-	UCHAR			fc1;
-	USHORT			fc;
-	UINT			frame_type;
-	UINT			frame_subtype;
-    UINT			from_ds;
-    UINT			to_ds;
-	INT				a4_exists;
-	INT				qc_exists;
-	USHORT			duration;
-	USHORT			seq_control;
-	USHORT			qos_control;
-	UCHAR			TA[MAC_ADDR_LEN];
-	UCHAR			DA[MAC_ADDR_LEN];
-	UCHAR			SA[MAC_ADDR_LEN];
-	UCHAR			RC4Key[16];
-	UINT			p1k[5]; //for mix_key;
-	ULONG			pnl;/* Least significant 16 bits of PN */
-	ULONG			pnh;/* Most significant 32 bits of PN */
-	UINT			num_blocks;
-	UINT			payload_remainder;
-	ARCFOURCONTEXT 	ArcFourContext;
-	UINT			crc32 = 0;
-	UINT			trailfcs = 0;
-	UCHAR			MIC[8];
-	UCHAR			TrailMIC[8];
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
-
-	fc0 = *pData;
-	fc1 = *(pData + 1);
-
-	fc = *((PUSHORT)pData);
-
-	frame_type = ((fc0 >> 2) & 0x03);
-	frame_subtype = ((fc0 >> 4) & 0x0f);
-
-    from_ds = (fc1 & 0x2) >> 1;
-    to_ds = (fc1 & 0x1);
-
-    a4_exists = (from_ds & to_ds);
-    qc_exists = ((frame_subtype == 0x08) ||    /* Assumed QoS subtypes */
-                  (frame_subtype == 0x09) ||   /* Likely to change.    */
-                  (frame_subtype == 0x0a) ||
-                  (frame_subtype == 0x0b)
-                 );
-
-	HeaderLen = 24;
-	if (a4_exists)
-		HeaderLen += 6;
-
-	KeyID = *((PUCHAR)(pData+ HeaderLen + 3));
-	KeyID = KeyID >> 6;
-
-	if (pWpaKey[KeyID].KeyLen == 0)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("RTMPSoftDecryptTKIP failed!(KeyID[%d] Length can not be 0)\n", KeyID));
-		return FALSE;
-	}
-
-	duration = *((PUSHORT)(pData+2));
-
-	seq_control = *((PUSHORT)(pData+22));
-
-	if (qc_exists)
-	{
-		if (a4_exists)
-		{
-			qos_control = *((PUSHORT)(pData+30));
-		}
-		else
-		{
-			qos_control = *((PUSHORT)(pData+24));
-		}
-	}
-
-	if (to_ds == 0 && from_ds == 1)
-	{
-		NdisMoveMemory(DA, pData+4, MAC_ADDR_LEN);
-		NdisMoveMemory(SA, pData+16, MAC_ADDR_LEN);
-		NdisMoveMemory(TA, pData+10, MAC_ADDR_LEN);  //BSSID
-	}
-	else if (to_ds == 0 && from_ds == 0 )
-	{
-		NdisMoveMemory(TA, pData+10, MAC_ADDR_LEN);
-		NdisMoveMemory(DA, pData+4, MAC_ADDR_LEN);
-		NdisMoveMemory(SA, pData+10, MAC_ADDR_LEN);
-	}
-	else if (to_ds == 1 && from_ds == 0)
-	{
-		NdisMoveMemory(SA, pData+10, MAC_ADDR_LEN);
-		NdisMoveMemory(TA, pData+10, MAC_ADDR_LEN);
-		NdisMoveMemory(DA, pData+16, MAC_ADDR_LEN);
-	}
-	else if (to_ds == 1 && from_ds == 1)
-	{
-		NdisMoveMemory(TA, pData+10, MAC_ADDR_LEN);
-		NdisMoveMemory(DA, pData+16, MAC_ADDR_LEN);
-		NdisMoveMemory(SA, pData+22, MAC_ADDR_LEN);
-	}
-
-	num_blocks = (DataByteCnt - 16) / 16;
-	payload_remainder = (DataByteCnt - 16) % 16;
-
-	pnl = (*(pData + HeaderLen)) * 256 + *(pData + HeaderLen + 2);
-	pnh = *((PULONG)(pData + HeaderLen + 4));
-	pnh = cpu2le32(pnh);
-	RTMPTkipMixKey(pWpaKey[KeyID].Key, TA, pnl, pnh, RC4Key, p1k);
-
-	ARCFOUR_INIT(&ArcFourContext, RC4Key, 16);
-
-	ARCFOUR_DECRYPT(&ArcFourContext, pData + HeaderLen, pData + HeaderLen + 8, DataByteCnt - HeaderLen - 8);
-	NdisMoveMemory(&trailfcs, pData + DataByteCnt - 8 - 4, 4);
-	crc32 = RTMP_CALC_FCS32(PPPINITFCS32, pData + HeaderLen, DataByteCnt - HeaderLen - 8 - 4);  //Skip IV+EIV 8 bytes & Skip last 4 bytes(FCS).
-	crc32 ^= 0xffffffff;             /* complement */
-
-    if(crc32 != cpu2le32(trailfcs))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("RTMPSoftDecryptTKIP, WEP Data ICV Error !\n"));	 //ICV error.
-
-		return (FALSE);
-	}
-
-	NdisMoveMemory(TrailMIC, pData + DataByteCnt - 8 - 8 - 4, 8);
-	RTMPInitMICEngine(pAd, pWpaKey[KeyID].Key, DA, SA, UserPriority, pWpaKey[KeyID].RxMic);
-	RTMPTkipAppend(&pAd->PrivateInfo.Tx, pData + HeaderLen, DataByteCnt - HeaderLen - 8 - 12);
-	RTMPTkipGetMIC(&pAd->PrivateInfo.Tx);
-	NdisMoveMemory(MIC, pAd->PrivateInfo.Tx.MIC, 8);
-
-	if (!NdisEqualMemory(MIC, TrailMIC, 8))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RTMPSoftDecryptTKIP, WEP Data MIC Error !\n"));	 //MIC error.
-		//RTMPReportMicError(pAd, &pWpaKey[KeyID]);	// marked by AlbertY @ 20060630
-		return (FALSE);
-	}
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
-	//DBGPRINT(RT_DEBUG_TRACE, "RTMPSoftDecryptTKIP Decript done!!\n");
-	return TRUE;
-}
-
-
-
-
-BOOLEAN RTMPSoftDecryptAES(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pData,
-	IN ULONG	DataByteCnt,
-	IN PCIPHER_KEY	pWpaKey)
-{
-	UCHAR			KeyID;
-	UINT			HeaderLen;
-	UCHAR			PN[6];
-	UINT			payload_len;
-	UINT			num_blocks;
-	UINT			payload_remainder;
-	USHORT			fc;
-	UCHAR			fc0;
-	UCHAR			fc1;
-	UINT			frame_type;
-	UINT			frame_subtype;
-	UINT			from_ds;
-	UINT			to_ds;
-	INT				a4_exists;
-	INT				qc_exists;
-	UCHAR			aes_out[16];
-	int 			payload_index;
-	UINT 			i;
-	UCHAR 			ctr_preload[16];
-	UCHAR 			chain_buffer[16];
-	UCHAR 			padded_buffer[16];
-	UCHAR 			mic_iv[16];
-	UCHAR 			mic_header1[16];
-	UCHAR 			mic_header2[16];
-	UCHAR			MIC[8];
-	UCHAR			TrailMIC[8];
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
-
-	fc0 = *pData;
-	fc1 = *(pData + 1);
-
-	fc = *((PUSHORT)pData);
-
-	frame_type = ((fc0 >> 2) & 0x03);
-	frame_subtype = ((fc0 >> 4) & 0x0f);
-
-	from_ds = (fc1 & 0x2) >> 1;
-	to_ds = (fc1 & 0x1);
-
-	a4_exists = (from_ds & to_ds);
-	qc_exists = ((frame_subtype == 0x08) ||    /* Assumed QoS subtypes */
-				  (frame_subtype == 0x09) ||   /* Likely to change.    */
-				  (frame_subtype == 0x0a) ||
-				  (frame_subtype == 0x0b)
-				 );
-
-	HeaderLen = 24;
-	if (a4_exists)
-		HeaderLen += 6;
-
-	KeyID = *((PUCHAR)(pData+ HeaderLen + 3));
-	KeyID = KeyID >> 6;
-
-	if (pWpaKey[KeyID].KeyLen == 0)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("RTMPSoftDecryptAES failed!(KeyID[%d] Length can not be 0)\n", KeyID));
-		return FALSE;
-	}
-
-	PN[0] = *(pData+ HeaderLen);
-	PN[1] = *(pData+ HeaderLen + 1);
-	PN[2] = *(pData+ HeaderLen + 4);
-	PN[3] = *(pData+ HeaderLen + 5);
-	PN[4] = *(pData+ HeaderLen + 6);
-	PN[5] = *(pData+ HeaderLen + 7);
-
-	payload_len = DataByteCnt - HeaderLen - 8 - 8;	// 8 bytes for CCMP header , 8 bytes for MIC
-	payload_remainder = (payload_len) % 16;
-	num_blocks = (payload_len) / 16;
-
-
-
-	// Find start of payload
-	payload_index = HeaderLen + 8; //IV+EIV
-
-	for (i=0; i< num_blocks; i++)
-	{
-		construct_ctr_preload(ctr_preload,
-								a4_exists,
-								qc_exists,
-								pData,
-								PN,
-								i+1 );
-
-		aes128k128d(pWpaKey[KeyID].Key, ctr_preload, aes_out);
-
-		bitwise_xor(aes_out, pData + payload_index, chain_buffer);
-		NdisMoveMemory(pData + payload_index - 8, chain_buffer, 16);
-		payload_index += 16;
-	}
-
-	//
-	// If there is a short final block, then pad it
-	// encrypt it and copy the unpadded part back
-	//
-	if (payload_remainder > 0)
-	{
-		construct_ctr_preload(ctr_preload,
-								a4_exists,
-								qc_exists,
-								pData,
-								PN,
-								num_blocks + 1);
-
-		NdisZeroMemory(padded_buffer, 16);
-		NdisMoveMemory(padded_buffer, pData + payload_index, payload_remainder);
-
-		aes128k128d(pWpaKey[KeyID].Key, ctr_preload, aes_out);
-
-		bitwise_xor(aes_out, padded_buffer, chain_buffer);
-		NdisMoveMemory(pData + payload_index - 8, chain_buffer, payload_remainder);
-		payload_index += payload_remainder;
-	}
-
-	//
-	// Descrypt the MIC
-	//
-	construct_ctr_preload(ctr_preload,
-							a4_exists,
-							qc_exists,
-							pData,
-							PN,
-							0);
-	NdisZeroMemory(padded_buffer, 16);
-	NdisMoveMemory(padded_buffer, pData + payload_index, 8);
-
-	aes128k128d(pWpaKey[KeyID].Key, ctr_preload, aes_out);
-
-	bitwise_xor(aes_out, padded_buffer, chain_buffer);
-
-	NdisMoveMemory(TrailMIC, chain_buffer, 8);
-
-	//
-	// Calculate MIC
-	//
-
-	//Force the protected frame bit on
-	*(pData + 1) = *(pData + 1) | 0x40;
-
-	// Find start of payload
-	// Because the CCMP header has been removed
-	payload_index = HeaderLen;
-
-	construct_mic_iv(
-					mic_iv,
-					qc_exists,
-					a4_exists,
-					pData,
-					payload_len,
-					PN);
-
-	construct_mic_header1(
-						mic_header1,
-						HeaderLen,
-						pData);
-
-	construct_mic_header2(
-						mic_header2,
-						pData,
-						a4_exists,
-						qc_exists);
-
-	aes128k128d(pWpaKey[KeyID].Key, mic_iv, aes_out);
-	bitwise_xor(aes_out, mic_header1, chain_buffer);
-	aes128k128d(pWpaKey[KeyID].Key, chain_buffer, aes_out);
-	bitwise_xor(aes_out, mic_header2, chain_buffer);
-	aes128k128d(pWpaKey[KeyID].Key, chain_buffer, aes_out);
-
-	// iterate through each 16 byte payload block
-	for (i = 0; i < num_blocks; i++)
-	{
-		bitwise_xor(aes_out, pData + payload_index, chain_buffer);
-		payload_index += 16;
-		aes128k128d(pWpaKey[KeyID].Key, chain_buffer, aes_out);
-	}
-
-	// Add on the final payload block if it needs padding
-	if (payload_remainder > 0)
-	{
-		NdisZeroMemory(padded_buffer, 16);
-		NdisMoveMemory(padded_buffer, pData + payload_index, payload_remainder);
-
-		bitwise_xor(aes_out, padded_buffer, chain_buffer);
-		aes128k128d(pWpaKey[KeyID].Key, chain_buffer, aes_out);
-	}
-
-	// aes_out contains padded mic, discard most significant
-	// 8 bytes to generate 64 bit MIC
-	for (i = 0 ; i < 8; i++) MIC[i] = aes_out[i];
-
-	if (!NdisEqualMemory(MIC, TrailMIC, 8))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RTMPSoftDecryptAES, MIC Error !\n"));	 //MIC error.
-		return FALSE;
-	}
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
-
-	return TRUE;
-}
-
-/****************************************/
-/* aes128k128d()                        */
-/* Performs a 128 bit AES encrypt with  */
-/* 128 bit data.                        */
-/****************************************/
-VOID xor_128(
-	IN  PUCHAR  a,
-	IN  PUCHAR  b,
-	OUT PUCHAR  out)
-{
-	INT i;
-
-	for (i=0;i<16; i++)
-	{
-		out[i] = a[i] ^ b[i];
-	}
-}
-
-VOID next_key(
-	IN  PUCHAR  key,
-	IN  INT     round)
-{
-	UCHAR       rcon;
-	UCHAR       sbox_key[4];
-	UCHAR       rcon_table[12] =
-	{
-		0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
-		0x1b, 0x36, 0x36, 0x36
-	};
-
-	sbox_key[0] = RTMPCkipSbox(key[13]);
-	sbox_key[1] = RTMPCkipSbox(key[14]);
-	sbox_key[2] = RTMPCkipSbox(key[15]);
-	sbox_key[3] = RTMPCkipSbox(key[12]);
-
-	rcon = rcon_table[round];
-
-	xor_32(&key[0], sbox_key, &key[0]);
-	key[0] = key[0] ^ rcon;
-
-	xor_32(&key[4], &key[0], &key[4]);
-	xor_32(&key[8], &key[4], &key[8]);
-	xor_32(&key[12], &key[8], &key[12]);
-}
-
-VOID xor_32(
-	IN  PUCHAR  a,
-	IN  PUCHAR  b,
-	OUT PUCHAR  out)
-{
-	INT i;
-
-	for (i=0;i<4; i++)
-	{
-		out[i] = a[i] ^ b[i];
-	}
-}
-
-VOID byte_sub(
-	IN  PUCHAR  in,
-	OUT PUCHAR  out)
-{
-	INT i;
-
-	for (i=0; i< 16; i++)
-	{
-		out[i] = RTMPCkipSbox(in[i]);
-	}
-}
-
-UCHAR RTMPCkipSbox(
-	IN  UCHAR   a)
-{
-	return SboxTable[(int)a];
-}
-
-VOID shift_row(
-	IN  PUCHAR  in,
-	OUT PUCHAR  out)
-{
-	out[0] =  in[0];
-	out[1] =  in[5];
-	out[2] =  in[10];
-	out[3] =  in[15];
-	out[4] =  in[4];
-	out[5] =  in[9];
-	out[6] =  in[14];
-	out[7] =  in[3];
-	out[8] =  in[8];
-	out[9] =  in[13];
-	out[10] = in[2];
-	out[11] = in[7];
-	out[12] = in[12];
-	out[13] = in[1];
-	out[14] = in[6];
-	out[15] = in[11];
-}
-
-VOID mix_column(
-	IN  PUCHAR  in,
-	OUT PUCHAR  out)
-{
-	INT         i;
-	UCHAR       add1b[4];
-	UCHAR       add1bf7[4];
-	UCHAR       rotl[4];
-	UCHAR       swap_halfs[4];
-	UCHAR       andf7[4];
-	UCHAR       rotr[4];
-	UCHAR       temp[4];
-	UCHAR       tempb[4];
-
-	for (i=0 ; i<4; i++)
-	{
-		if ((in[i] & 0x80)== 0x80)
-			add1b[i] = 0x1b;
-		else
-			add1b[i] = 0x00;
-	}
-
-	swap_halfs[0] = in[2];    /* Swap halfs */
-	swap_halfs[1] = in[3];
-	swap_halfs[2] = in[0];
-	swap_halfs[3] = in[1];
-
-	rotl[0] = in[3];        /* Rotate left 8 bits */
-	rotl[1] = in[0];
-	rotl[2] = in[1];
-	rotl[3] = in[2];
-
-	andf7[0] = in[0] & 0x7f;
-	andf7[1] = in[1] & 0x7f;
-	andf7[2] = in[2] & 0x7f;
-	andf7[3] = in[3] & 0x7f;
-
-	for (i = 3; i>0; i--)    /* logical shift left 1 bit */
-	{
-		andf7[i] = andf7[i] << 1;
-		if ((andf7[i-1] & 0x80) == 0x80)
-		{
-			andf7[i] = (andf7[i] | 0x01);
-		}
-	}
-	andf7[0] = andf7[0] << 1;
-	andf7[0] = andf7[0] & 0xfe;
-
-	xor_32(add1b, andf7, add1bf7);
-
-	xor_32(in, add1bf7, rotr);
-
-	temp[0] = rotr[0];         /* Rotate right 8 bits */
-	rotr[0] = rotr[1];
-	rotr[1] = rotr[2];
-	rotr[2] = rotr[3];
-	rotr[3] = temp[0];
-
-	xor_32(add1bf7, rotr, temp);
-	xor_32(swap_halfs, rotl,tempb);
-	xor_32(temp, tempb, out);
-}
-
+#include "../../rt2860/common/rtmp_tkip.c"
diff --git a/drivers/staging/rt2870/common/rtmp_wep.c b/drivers/staging/rt2870/common/rtmp_wep.c
index 62f9e58..ae255ad 100644
--- a/drivers/staging/rt2870/common/rtmp_wep.c
+++ b/drivers/staging/rt2870/common/rtmp_wep.c
@@ -1,508 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtmp_wep.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Paul Wu		10-28-02		Initial
-*/
-
-#include "../rt_config.h"
-
-UINT FCSTAB_32[256] =
-{
-	0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
-	0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
-	0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
-	0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
-	0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
-	0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
-	0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
-	0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
-	0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
-	0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
-	0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
-	0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
-	0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
-	0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
-	0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
-	0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
-	0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
-	0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
-	0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
-	0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
-	0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
-	0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
-	0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
-	0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
-	0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
-	0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
-	0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
-	0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
-	0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
-	0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
-	0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
-	0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
-	0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
-	0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
-	0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
-	0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
-	0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
-	0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
-	0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
-	0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
-	0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
-	0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
-	0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
-	0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
-	0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
-	0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
-	0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
-	0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
-	0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
-	0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
-	0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
-	0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
-	0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
-	0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
-	0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
-	0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
-	0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
-	0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
-	0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
-	0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
-	0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
-	0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
-	0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
-	0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
-};
-
-/*
-UCHAR   WEPKEY[] = {
-		//IV
-		0x00, 0x11, 0x22,
-		//WEP KEY
-		0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC
-	};
- */
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Init WEP function.
-
-	Arguments:
-      pAd		Pointer to our adapter
-		pKey        Pointer to the WEP KEY
-		KeyId		   WEP Key ID
-		KeyLen      the length of WEP KEY
-		pDest       Pointer to the destination which Encryption data will store in.
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPInitWepEngine(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pKey,
-	IN	UCHAR			KeyId,
-	IN	UCHAR			KeyLen,
-	IN OUT	PUCHAR		pDest)
-{
-	UINT i;
-	UCHAR   WEPKEY[] = {
-		//IV
-		0x00, 0x11, 0x22,
-		//WEP KEY
-		0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC
-	};
-
-	pAd->PrivateInfo.FCSCRC32 = PPPINITFCS32;   //Init crc32.
-
-#ifdef CONFIG_STA_SUPPORT
-    if (pAd->StaCfg.bCkipOn && (pAd->StaCfg.CkipFlag & 0x10) && (pAd->OpMode == OPMODE_STA))
-    {
-        ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, pKey, KeyLen);  //INIT SBOX, KEYLEN+3(IV)
-        NdisMoveMemory(pDest, pKey, 3);  //Append Init Vector
-    }
-    else
-#endif // CONFIG_STA_SUPPORT //
-    {
-		NdisMoveMemory(WEPKEY + 3, pKey, KeyLen);
-
-        for(i = 0; i < 3; i++)
-			WEPKEY[i] = RandomByte(pAd);   //Call mlme RandomByte() function.
-		ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, WEPKEY, KeyLen + 3);  //INIT SBOX, KEYLEN+3(IV)
-
-		NdisMoveMemory(pDest, WEPKEY, 3);  //Append Init Vector
-    }
-	*(pDest+3) = (KeyId << 6);       //Append KEYID
-
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Encrypt transimitted data
-
-	Arguments:
-      pAd		Pointer to our adapter
-      pSrc        Pointer to the transimitted source data that will be encrypt
-      pDest       Pointer to the destination where entryption data will be store in.
-      Len			Indicate the length of the source data
-
-	Return Value:
-      None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPEncryptData(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pSrc,
-	IN	PUCHAR			pDest,
-	IN	UINT			Len)
-{
-	pAd->PrivateInfo.FCSCRC32 = RTMP_CALC_FCS32(pAd->PrivateInfo.FCSCRC32, pSrc, Len);
-	ARCFOUR_ENCRYPT(&pAd->PrivateInfo.WEPCONTEXT, pDest, pSrc, Len);
-}
-
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Decrypt received WEP data
-
-	Arguments:
-		pAdapter		Pointer to our adapter
-		pSrc        Pointer to the received data
-		Len         the length of the received data
-
-	Return Value:
-		TRUE        Decrypt WEP data success
-		FALSE       Decrypt WEP data failed
-
-	Note:
-
-	========================================================================
-*/
-BOOLEAN	RTMPSoftDecryptWEP(
-	IN PRTMP_ADAPTER 	pAd,
-	IN PUCHAR			pData,
-	IN ULONG			DataByteCnt,
-	IN PCIPHER_KEY		pGroupKey)
-{
-	UINT	trailfcs;
-	UINT    crc32;
-	UCHAR	KeyIdx;
-	UCHAR   WEPKEY[] = {
-		//IV
-		0x00, 0x11, 0x22,
-		//WEP KEY
-		0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC
-	};
-	UCHAR 	*pPayload = (UCHAR *)pData + LENGTH_802_11;
-	ULONG	payload_len = DataByteCnt - LENGTH_802_11;
-
-	NdisMoveMemory(WEPKEY, pPayload, 3);    //Get WEP IV
-
-	KeyIdx = (*(pPayload + 3) & 0xc0) >> 6;
-	if (pGroupKey[KeyIdx].KeyLen == 0)
-		return (FALSE);
-
-	NdisMoveMemory(WEPKEY + 3, pGroupKey[KeyIdx].Key, pGroupKey[KeyIdx].KeyLen);
-	ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, WEPKEY, pGroupKey[KeyIdx].KeyLen + 3);
-	ARCFOUR_DECRYPT(&pAd->PrivateInfo.WEPCONTEXT, pPayload, pPayload + 4, payload_len - 4);
-	NdisMoveMemory(&trailfcs, pPayload + payload_len - 8, 4);
-	crc32 = RTMP_CALC_FCS32(PPPINITFCS32, pPayload, payload_len - 8);  //Skip last 4 bytes(FCS).
-	crc32 ^= 0xffffffff;             /* complement */
-
-    if(crc32 != cpu2le32(trailfcs))
-    {
-		DBGPRINT(RT_DEBUG_TRACE, ("! WEP Data CRC Error !\n"));	 //CRC error.
-		return (FALSE);
-	}
-	return (TRUE);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		The Stream Cipher Encryption Algorithm "ARCFOUR" initialize
-
-	Arguments:
-	   Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-		pKey        Pointer to the WEP KEY
-		KeyLen      Indicate the length fo the WEP KEY
-
-	Return Value:
-	   None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	ARCFOUR_INIT(
-	IN	PARCFOURCONTEXT	Ctx,
-	IN	PUCHAR			pKey,
-	IN	UINT			KeyLen)
-{
-	UCHAR	t, u;
-	UINT	keyindex;
-	UINT	stateindex;
-	PUCHAR	state;
-	UINT	counter;
-
-	state = Ctx->STATE;
-	Ctx->X = 0;
-	Ctx->Y = 0;
-	for (counter = 0; counter < 256; counter++)
-		state[counter] = (UCHAR)counter;
-	keyindex = 0;
-	stateindex = 0;
-	for (counter = 0; counter < 256; counter++)
-	{
-		t = state[counter];
-		stateindex = (stateindex + pKey[keyindex] + t) & 0xff;
-		u = state[stateindex];
-		state[stateindex] = t;
-		state[counter] = u;
-		if (++keyindex >= KeyLen)
-			keyindex = 0;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Get bytes from ARCFOUR CONTEXT (S-BOX)
-
-	Arguments:
-	   Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-
-	Return Value:
-	   UCHAR  - the value of the ARCFOUR CONTEXT (S-BOX)
-
-	Note:
-
-	========================================================================
-*/
-UCHAR	ARCFOUR_BYTE(
-	IN	PARCFOURCONTEXT		Ctx)
-{
-  UINT x;
-  UINT y;
-  UCHAR sx, sy;
-  PUCHAR state;
-
-  state = Ctx->STATE;
-  x = (Ctx->X + 1) & 0xff;
-  sx = state[x];
-  y = (sx + Ctx->Y) & 0xff;
-  sy = state[y];
-  Ctx->X = x;
-  Ctx->Y = y;
-  state[y] = sx;
-  state[x] = sy;
-
-  return(state[(sx + sy) & 0xff]);
-
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		The Stream Cipher Decryption Algorithm
-
-	Arguments:
-		Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-		pDest			Pointer to the Destination
-		pSrc        Pointer to the Source data
-		Len         Indicate the length of the Source data
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	ARCFOUR_DECRYPT(
-	IN	PARCFOURCONTEXT	Ctx,
-	IN	PUCHAR			pDest,
-	IN	PUCHAR			pSrc,
-	IN	UINT			Len)
-{
-	UINT i;
-
-	for (i = 0; i < Len; i++)
-		pDest[i] = pSrc[i] ^ ARCFOUR_BYTE(Ctx);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		The Stream Cipher Encryption Algorithm
-
-	Arguments:
-		Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-		pDest			Pointer to the Destination
-		pSrc        Pointer to the Source data
-		Len         Indicate the length of the Source dta
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	ARCFOUR_ENCRYPT(
-	IN	PARCFOURCONTEXT	Ctx,
-	IN	PUCHAR			pDest,
-	IN	PUCHAR			pSrc,
-	IN	UINT			Len)
-{
-	UINT i;
-
-	for (i = 0; i < Len; i++)
-		pDest[i] = pSrc[i] ^ ARCFOUR_BYTE(Ctx);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		The Stream Cipher Encryption Algorithm which conform to the special requirement to encrypt  GTK.
-
-	Arguments:
-		Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-		pDest			Pointer to the Destination
-		pSrc        Pointer to the Source data
-		Len         Indicate the length of the Source dta
-
-
-	========================================================================
-*/
-
-VOID	WPAARCFOUR_ENCRYPT(
-	IN	PARCFOURCONTEXT	Ctx,
-	IN	PUCHAR			pDest,
-	IN	PUCHAR			pSrc,
-	IN	UINT			Len)
-{
-	UINT i;
-        //discard first 256 bytes
-	for (i = 0; i < 256; i++)
-            ARCFOUR_BYTE(Ctx);
-
-	for (i = 0; i < Len; i++)
-		pDest[i] = pSrc[i] ^ ARCFOUR_BYTE(Ctx);
-}
-
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Calculate a new FCS given the current FCS and the new data.
-
-	Arguments:
-		Fcs	      the original FCS value
-		Cp          pointer to the data which will be calculate the FCS
-		Len         the length of the data
-
-	Return Value:
-		UINT - FCS 32 bits
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-UINT	RTMP_CALC_FCS32(
-	IN	UINT	Fcs,
-	IN	PUCHAR	Cp,
-	IN	INT		Len)
-{
-	while (Len--)
-	   Fcs = (((Fcs) >> 8) ^ FCSTAB_32[((Fcs) ^ (*Cp++)) & 0xff]);
-
-	return (Fcs);
-}
-
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Get last FCS and encrypt it to the destination
-
-	Arguments:
-		pDest			Pointer to the Destination
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPSetICV(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR	pDest)
-{
-	pAd->PrivateInfo.FCSCRC32 ^= 0xffffffff;             /* complement */
-	pAd->PrivateInfo.FCSCRC32 = cpu2le32(pAd->PrivateInfo.FCSCRC32);
-
-	ARCFOUR_ENCRYPT(&pAd->PrivateInfo.WEPCONTEXT, pDest, (PUCHAR) &pAd->PrivateInfo.FCSCRC32, 4);
-}
-
+#include "../../rt2860/common/rtmp_wep.c"
diff --git a/drivers/staging/rt2870/common/rtusb_bulk.c b/drivers/staging/rt2870/common/rtusb_bulk.c
index c46d916..7ae3e95 100644
--- a/drivers/staging/rt2870/common/rtusb_bulk.c
+++ b/drivers/staging/rt2870/common/rtusb_bulk.c
@@ -52,11 +52,7 @@
 	void *pContext)
 {
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
 	usb_fill_bulk_urb(pUrb, pUsb_Dev, bulkpipe, pTransferBuf, BufSize, (usb_complete_t)Complete, pContext);
-#else
-	FILL_BULK_URB(pUrb, pUsb_Dev, bulkpipe, pTransferBuf, BufSize, Complete, pContext);
-#endif
 
 }
 
@@ -95,14 +91,12 @@
 						Func,
 						pTxContext);
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
 	if (pTxContext->bAggregatible)
 		pUrb->transfer_dma	= (pTxContext->data_dma + TX_BUFFER_NORMSIZE + 2);
 	else
 		pUrb->transfer_dma	= pTxContext->data_dma;
 
 	pUrb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
-#endif
 
 }
 
@@ -135,10 +129,8 @@
 						Func,
 						pTxContext);
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
 	pUrb->transfer_dma	= (pTxContext->data_dma + pTxContext->NextBulkOutPosition);
 	pUrb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
-#endif
 
 }
 
@@ -168,10 +160,8 @@
 						(usb_complete_t)RTUSBBulkRxComplete,
 						(void *)pRxContext);
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
 	pUrb->transfer_dma	= pRxContext->data_dma + pAd->NextRxBulkInPosition;
 	pUrb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
-#endif
 
 
 }
@@ -327,6 +317,7 @@
 			break;
 		}
 
+		//PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
 		if (pTxInfo->QSEL != FIFO_EDCA)
 		{
 			printk("%s(): ====> pTxInfo->QueueSel(%d)!= FIFO_EDCA!!!!\n", __func__, pTxInfo->QSEL);
@@ -359,7 +350,7 @@
 		pLastTxInfo = pTxInfo;
 
 		// Make sure we use EDCA QUEUE.
-		pTxInfo->QSEL = FIFO_EDCA;
+		pTxInfo->QSEL = FIFO_EDCA;  //PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
 		ThisBulkSize += (pTxInfo->USBDMATxPktLen+4);
 		TmpBulkEndPos += (pTxInfo->USBDMATxPktLen+4);
 
@@ -375,31 +366,14 @@
 			bTxQLastRound = TRUE;
 			pHTTXContext->ENextBulkOutPosition = 8;
 
-	#ifdef RT_BIG_ENDIAN
-			RTMPDescriptorEndianChange((PUCHAR)pTxInfo, TYPE_TXINFO);
-			RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-	#endif // RT_BIG_ENDIAN //
-
 			break;
 		}
-
-#ifdef RT_BIG_ENDIAN
-		RTMPDescriptorEndianChange((PUCHAR)pTxInfo, TYPE_TXINFO);
-		RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-#endif // RT_BIG_ENDIAN //
-
 	}while (TRUE);
 
 	// adjust the pTxInfo->USBDMANextVLD value of last pTxInfo.
 	if (pLastTxInfo)
 	{
-#ifdef RT_BIG_ENDIAN
-		RTMPDescriptorEndianChange((PUCHAR)pLastTxInfo, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
 		pLastTxInfo->USBDMANextVLD = 0;
-#ifdef RT_BIG_ENDIAN
-		RTMPDescriptorEndianChange((PUCHAR)pLastTxInfo, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
 	}
 
 	/*
@@ -475,115 +449,6 @@
 
 VOID RTUSBBulkOutDataPacketComplete(purbb_t pUrb, struct pt_regs *pt_regs)
 {
-#if 0 // sample, IRQ LOCK
-	PRTMP_ADAPTER		pAd;
-	POS_COOKIE			pObj;
-	PHT_TX_CONTEXT		pHTTXContext;
-	UCHAR				BulkOutPipeId;
-	NTSTATUS			Status;
-	unsigned long		IrqFlags;
-
-	DBGPRINT_RAW(RT_DEBUG_INFO, ("--->RTUSBBulkOutDataPacketComplete\n"));
-
-	pHTTXContext	= (PHT_TX_CONTEXT)pUrb->context;
-	pAd			= pHTTXContext->pAd;
-	pObj 		= (POS_COOKIE) pAd->OS_Cookie;
-	Status		= pUrb->status;
-
-	// Store BulkOut PipeId
-	BulkOutPipeId = pHTTXContext->BulkOutPipeId;
-	pAd->BulkOutDataOneSecCount++;
-
-	//DBGPRINT(RT_DEBUG_LOUD, ("Done-B(%d):I=0x%lx, CWPos=%ld, NBPos=%ld, ENBPos=%ld, bCopy=%d!\n", BulkOutPipeId, in_interrupt(), pHTTXContext->CurWritePosition,
-	//		pHTTXContext->NextBulkOutPosition, pHTTXContext->ENextBulkOutPosition, pHTTXContext->bCopySavePad));
-
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-	pAd->BulkOutPending[BulkOutPipeId] = FALSE;
-	pHTTXContext->IRPPending = FALSE;
-	RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-
-	if (Status == USB_ST_NOERROR)
-	{
-		pAd->BulkOutComplete++;
-
-		pAd->Counters8023.GoodTransmits++;
-		//RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-		FREE_HTTX_RING(pAd, BulkOutPipeId, pHTTXContext);
-		//RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-
-
-	}
-	else	// STATUS_OTHER
-	{
-		PUCHAR	pBuf;
-
-		pAd->BulkOutCompleteOther++;
-
-		pBuf = &pHTTXContext->TransferBuffer->WirelessPacket[pHTTXContext->NextBulkOutPosition];
-
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("BulkOutDataPacket failed: ReasonCode=%d!\n", Status));
-		DBGPRINT_RAW(RT_DEBUG_ERROR, (">>BulkOut Req=0x%lx, Complete=0x%lx, Other=0x%lx\n", pAd->BulkOutReq, pAd->BulkOutComplete, pAd->BulkOutCompleteOther));
-		DBGPRINT_RAW(RT_DEBUG_ERROR, (">>BulkOut Header:%x %x %x %x %x %x %x %x\n", pBuf[0], pBuf[1], pBuf[2], pBuf[3], pBuf[4], pBuf[5], pBuf[6], pBuf[7]));
-		//DBGPRINT_RAW(RT_DEBUG_ERROR, (">>BulkOutCompleteCancel=0x%x, BulkOutCompleteOther=0x%x\n", pAd->BulkOutCompleteCancel, pAd->BulkOutCompleteOther));
-
-		if (!RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
-									fRTMP_ADAPTER_HALT_IN_PROGRESS |
-									fRTMP_ADAPTER_NIC_NOT_EXIST |
-									fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			pAd->bulkResetPipeid = BulkOutPipeId;
-		}
-	}
-
-	//
-	// bInUse = TRUE, means some process are filling TX data, after that must turn on bWaitingBulkOut
-	// bWaitingBulkOut = TRUE, means the TX data are waiting for bulk out.
-	//
-	//RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-	if ((pHTTXContext->ENextBulkOutPosition != pHTTXContext->CurWritePosition) &&
-		(pHTTXContext->ENextBulkOutPosition != (pHTTXContext->CurWritePosition+8)) &&
-		!RTUSB_TEST_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_FRAG << BulkOutPipeId)))
-	{
-		// Indicate There is data avaliable
-		RTUSB_SET_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << BulkOutPipeId));
-	}
-	//RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-
-	// Always call Bulk routine, even reset bulk.
-	// The protection of rest bulk should be in BulkOut routine
-	RTUSBKickBulkOut(pAd);
-
-
-	//DBGPRINT(RT_DEBUG_LOUD,("Done-A(%d):I=0x%lx, CWPos=%ld, NBPos=%ld, ENBPos=%ld, bCopy=%d\n", BulkOutPipeId, in_interrupt(),
-	//		pHTTXContext->CurWritePosition, pHTTXContext->NextBulkOutPosition, pHTTXContext->ENextBulkOutPosition, pHTTXContext->bCopySavePad));
-
-	switch (BulkOutPipeId)
-	{
-		case 0:
-				pObj->ac0_dma_done_task.data = (unsigned long)pAd;
-				tasklet_hi_schedule(&pObj->ac0_dma_done_task);
-				break;
-		case 1:
-				pObj->ac1_dma_done_task.data = (unsigned long)pAd;
-				tasklet_hi_schedule(&pObj->ac1_dma_done_task);
-				break;
-		case 2:
-				pObj->ac2_dma_done_task.data = (unsigned long)pAd;
-				tasklet_hi_schedule(&pObj->ac2_dma_done_task);
-				break;
-		case 3:
-				pObj->ac3_dma_done_task.data = (unsigned long)pAd;
-				tasklet_hi_schedule(&pObj->ac3_dma_done_task);
-				break;
-		case 4:
-				pObj->hcca_dma_done_task.data = (unsigned long)pAd;
-				tasklet_hi_schedule(&pObj->hcca_dma_done_task);
-				break;
-	}
-#else
-
-{
 	PHT_TX_CONTEXT	pHTTXContext;
 	PRTMP_ADAPTER	pAd;
 	POS_COOKIE 		pObj;
@@ -622,10 +487,6 @@
 				break;
 	}
 }
-#endif
-
-
-}
 
 
 /*
@@ -667,10 +528,6 @@
 	// Clear Null frame bulk flag
 	RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NULL);
 
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pNullContext->TransferBuffer, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-
 	// Init Tx context descriptor
 	RTUSBInitTxDesc(pAd, pNullContext, 0, (usb_complete_t)RTUSBBulkOutNullFrameComplete);
 
@@ -695,9 +552,6 @@
 	PRTMP_ADAPTER		pAd;
 	PTX_CONTEXT			pNullContext;
 	NTSTATUS			Status;
-#if 0 // sample, IRQ LOCK
-	unsigned long		IrqFlags;
-#endif
 	POS_COOKIE			pObj;
 
 
@@ -705,174 +559,11 @@
 	pAd 			= pNullContext->pAd;
 	Status 			= pUrb->status;
 
-#if 0 // sample, IRQ LOCK
-	// Reset Null frame context flags
-	pNullContext->IRPPending 	= FALSE;
-	pNullContext->InUse 		= FALSE;
-
-	if (Status == USB_ST_NOERROR)
-	{
-		// Don't worry about the queue is empty or not, this function will check itself
-		//RTMPUSBDeQueuePacket(pAd, 0);
-		RTMPDeQueuePacket(pAd, TRUE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-	else	// STATUS_OTHER
-	{
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("Bulk Out Null Frame Failed\n"));
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-	}
-
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[0], IrqFlags);
-	pAd->BulkOutPending[0] = FALSE;
-	RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);
-
-	// Always call Bulk routine, even reset bulk.
-	// The protectioon of rest bulk should be in BulkOut routine
-	RTUSBKickBulkOut(pAd);
-#else
-
 	pObj = (POS_COOKIE) pAd->OS_Cookie;
 	pObj->null_frame_complete_task.data = (unsigned long)pUrb;
 	tasklet_hi_schedule(&pObj->null_frame_complete_task);
-#endif
-
 }
 
-#if 0	// For RT2870, RTS frame not used now, but maybe will use it latter.
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note: RTS frame use BulkOutPipeId = 0
-
-	========================================================================
-*/
-VOID	RTUSBBulkOutRTSFrame(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	PTX_CONTEXT		pRTSContext = &(pAd->RTSContext);
-	PURB			pUrb;
-	int				ret = 0;
-	unsigned long	IrqFlags;
-	UCHAR			PipeID=0;
-
-	if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL_4))
-		PipeID= 3;
-	else if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL_3))
-		PipeID= 2;
-	else if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL_2))
-		PipeID= 1;
-	else if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL))
-		PipeID= 0;
-
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[PipeID], IrqFlags);
-	if ((pAd->BulkOutPending[PipeID] == TRUE) || RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NEED_STOP_TX))
-	{
-		RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[PipeID], IrqFlags);
-		return;
-	}
-	pAd->BulkOutPending[PipeID] = TRUE;
-	RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[PipeID], IrqFlags);
-
-	// Increase Total transmit byte counter
-	pAd->RalinkCounters.TransmittedByteCount +=  pRTSContext->BulkOutSize;
-
-	DBGPRINT_RAW(RT_DEBUG_INFO, ("--->RTUSBBulkOutRTSFrame \n"));
-
-	// Clear RTS frame bulk flag
-	RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_RTS);
-
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pRTSContext->TransferBuffer, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-
-	// Init Tx context descriptor
-	RTUSBInitTxDesc(pAd, pRTSContext, PipeID, (usb_complete_t)RTUSBBulkOutRTSFrameComplete);
-	pRTSContext->IRPPending = TRUE;
-
-	pUrb = pRTSContext->pUrb;
-	if((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RTUSBBulkOutRTSFrame: Submit Tx URB failed %d\n", ret));
-		return;
-	}
-
-	DBGPRINT_RAW(RT_DEBUG_INFO, ("<---RTUSBBulkOutRTSFrame \n"));
-
-}
-
-// RTS frame use BulkOutPipeId = 0
-VOID RTUSBBulkOutRTSFrameComplete(purbb_t pUrb, struct pt_regs *pt_regs)
-{
-	PRTMP_ADAPTER	pAd;
-	PTX_CONTEXT		pRTSContext;
-	NTSTATUS		Status;
-#if 0 // sample, IRQ LOCK
-	unsigned long	IrqFlags;
-#endif
-	POS_COOKIE		pObj;
-
-	DBGPRINT_RAW(RT_DEBUG_INFO, ("--->RTUSBBulkOutRTSFrameComplete\n"));
-
-	pRTSContext	= (PTX_CONTEXT)pUrb->context;
-	pAd			= pRTSContext->pAd;
-	Status		= pUrb->status;
-
-#if 0 // sample, IRQ LOCK
-	// Reset RTS frame context flags
-	pRTSContext->IRPPending = FALSE;
-	pRTSContext->InUse		= FALSE;
-
-	if (Status == USB_ST_NOERROR)
-	{
-		// Don't worry about the queue is empty or not, this function will check itself
-		//RTMPUSBDeQueuePacket(pAd, pRTSContext->BulkOutPipeId);
-		RTMPDeQueuePacket(pAd, TRUE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-	else	// STATUS_OTHER
-	{
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("Bulk Out RTS Frame Failed\n"));
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-	}
-
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[pRTSContext->BulkOutPipeId], IrqFlags);
-	pAd->BulkOutPending[pRTSContext->BulkOutPipeId] = FALSE;
-	RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[pRTSContext->BulkOutPipeId], IrqFlags);
-
-	// Always call Bulk routine, even reset bulk.
-	// The protectioon of rest bulk should be in BulkOut routine
-	RTUSBKickBulkOut(pAd);
-#else
-
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-	pObj->rts_frame_complete_task.data = (unsigned long)pUrb;
-	tasklet_hi_schedule(&pObj->rts_frame_complete_task);
-#endif
-
-	DBGPRINT_RAW(RT_DEBUG_INFO, ("<---RTUSBBulkOutRTSFrameComplete\n"));
-
-}
-#endif
-
 /*
 	========================================================================
 
@@ -930,37 +621,12 @@
 	// Clear MLME bulk flag
 	RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_MLME);
 
-
-	//DBGPRINT_RAW(RT_DEBUG_INFO, ("--->RTUSBBulkOutMLMEPacket\n"));
-#if 0 // for debug
-{
-	printk("MLME-Out, C=%d!, D=%d, F=%d!\n", pAd->MgmtRing.TxCpuIdx, pAd->MgmtRing.TxDmaIdx, pAd->MgmtRing.TxSwFreeIdx);
-
-	//TODO: Need to remove it when formal release
-	PTXINFO_STRUC pTxInfo;
-
-	pTxInfo = (PTXINFO_STRUC)pMLMEContext->TransferBuffer;
-	if (pTxInfo->QSEL != FIFO_EDCA)
-	{
-			printk("%s(): ====> pTxInfo->QueueSel(%d)!= FIFO_EDCA!!!!\n", __func__, pTxInfo->QSEL);
-			printk("\tMLME_Index=%d!\n", Index);
-			hex_dump("Wrong QSel Pkt:", (PUCHAR)pMLMEContext->TransferBuffer, pTxInfo->USBDMATxPktLen);
-	}
-}
-#endif
-
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pMLMEContext->TransferBuffer, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-
 	// Init Tx context descriptor
 	RTUSBInitTxDesc(pAd, pMLMEContext, MGMTPIPEIDX, (usb_complete_t)RTUSBBulkOutMLMEPacketComplete);
 
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
 	//For mgmt urb buffer, because we use sk_buff, so we need to notify the USB controller do dma mapping.
 	pUrb->transfer_dma	= 0;
 	pUrb->transfer_flags &= (~URB_NO_TRANSFER_DMA_MAP);
-#endif
 
 	pUrb = pMLMEContext->pUrb;
 	if((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
@@ -988,11 +654,6 @@
 	NTSTATUS			Status;
 	POS_COOKIE 			pObj;
 	int					index;
-#if 0 // sample, IRQ LOCK
-	unsigned long		IrqFlags;
-	PNDIS_PACKET		pPacket;
-#endif
-
 
 	//DBGPRINT_RAW(RT_DEBUG_INFO, ("--->RTUSBBulkOutMLMEPacketComplete\n"));
 	pMLMEContext	= (PTX_CONTEXT)pUrb->context;
@@ -1001,82 +662,8 @@
 	Status			= pUrb->status;
 	index 			= pMLMEContext->SelfIdx;
 
-
-#if 0 // sample, IRQ LOCK
-	ASSERT((pAd->MgmtRing.TxDmaIdx == index));
-	//printk("MLME-Done-B: C=%d, D=%d, F=%d, Self=%d!\n", pAd->MgmtRing.TxCpuIdx, pAd->MgmtRing.TxDmaIdx, pAd->MgmtRing.TxSwFreeIdx, pMLMEContext->SelfIdx);
-
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[MGMTPIPEIDX], IrqFlags);
-
-
-	if (Status != USB_ST_NOERROR)
-	{
-		//Bulk-Out fail status handle
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("Bulk Out MLME Failed, Status=%d!\n", Status));
-			// TODO: How to handle about the MLMEBulkOut failed issue. Need to resend the mgmt pkt?
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			pAd->bulkResetPipeid = (MGMTPIPEIDX | BULKOUT_MGMT_RESET_FLAG);
-		}
-	}
-	pAd->BulkOutPending[MGMTPIPEIDX] = FALSE;
-	RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[MGMTPIPEIDX], IrqFlags);
-
-	RTMP_IRQ_LOCK(&pAd->MLMEBulkOutLock, IrqFlags);
-	// Reset MLME context flags
-	pMLMEContext->IRPPending = FALSE;
-	pMLMEContext->InUse = FALSE;
-	pMLMEContext->bWaitingBulkOut = FALSE;
-	pMLMEContext->BulkOutSize = 0;
-
-	pPacket = pAd->MgmtRing.Cell[index].pNdisPacket;
-	pAd->MgmtRing.Cell[index].pNdisPacket = NULL;
-
-	// Increase MgmtRing Index
-	INC_RING_INDEX(pAd->MgmtRing.TxDmaIdx, MGMT_RING_SIZE);
-	pAd->MgmtRing.TxSwFreeIdx++;
-
-	RTMP_IRQ_UNLOCK(&pAd->MLMEBulkOutLock, IrqFlags);
-
-	// No-matter success or fail, we free the mgmt packet.
-	if (pPacket)
-		RTMPFreeNdisPacket(pAd, pPacket);
-
-#if 0
-	//Bulk-Out fail status handle
-	if (Status != USB_ST_NOERROR)
-	{
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("Bulk Out MLME Failed, Status=%d!\n", Status));
-			// TODO: How to handle about the MLMEBulkOut failed issue. Need to reset the endpoint?
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			pAd->bulkResetPipeid = (MGMTPIPEIDX | BULKOUT_MGMT_RESET_FLAG);
-		}
-	}
-#endif
-
-	//printk("MLME-Done-A: C=%d, D=%d, F=%d!\n", pAd->MgmtRing.TxCpuIdx, pAd->MgmtRing.TxDmaIdx, pAd->MgmtRing.TxSwFreeIdx);
-
-	pObj->mgmt_dma_done_task.data = (unsigned long)pAd;
-	tasklet_hi_schedule(&pObj->mgmt_dma_done_task);
-
-	//DBGPRINT_RAW(RT_DEBUG_INFO, ("<---RTUSBBulkOutMLMEPacketComplete\n"));
-//	printk("<---RTUSBBulkOutMLMEPacketComplete, Cpu=%d, Dma=%d, SwIdx=%d!\n",
-//				pAd->MgmtRing.TxCpuIdx, pAd->MgmtRing.TxDmaIdx, pAd->MgmtRing.TxSwFreeIdx);
-
-#else
-
 	pObj->mgmt_dma_done_task.data = (unsigned long)pUrb;
 	tasklet_hi_schedule(&pObj->mgmt_dma_done_task);
-#endif
 }
 
 
@@ -1116,10 +703,6 @@
 	// Clear PS-Poll bulk flag
 	RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_PSPOLL);
 
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pPsPollContext->TransferBuffer, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-
 	// Init Tx context descriptor
 	RTUSBInitTxDesc(pAd, pPsPollContext, MGMTPIPEIDX, (usb_complete_t)RTUSBBulkOutPsPollComplete);
 
@@ -1144,9 +727,6 @@
 	PRTMP_ADAPTER		pAd;
 	PTX_CONTEXT			pPsPollContext;
 	NTSTATUS			Status;
-#if 0 // sample, IRQ LOCK
-	unsigned long		IrqFlags;
-#endif
 	POS_COOKIE			pObj;
 
 
@@ -1154,255 +734,11 @@
 	pAd = pPsPollContext->pAd;
 	Status = pUrb->status;
 
-#if 0 // sample, IRQ LOCK
-	// Reset PsPoll context flags
-	pPsPollContext->IRPPending	= FALSE;
-	pPsPollContext->InUse		= FALSE;
-
-	if (Status == USB_ST_NOERROR)
-	{
-		// Don't worry about the queue is empty or not, this function will check itself
-		RTMPDeQueuePacket(pAd, TRUE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-	else // STATUS_OTHER
-	{
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("Bulk Out PSPoll Failed\n"));
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-	}
-
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[0], IrqFlags);
-	pAd->BulkOutPending[0] = FALSE;
-	RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);
-
-	// Always call Bulk routine, even reset bulk.
-	// The protectioon of rest bulk should be in BulkOut routine
-	RTUSBKickBulkOut(pAd);
-#else
-
 	pObj = (POS_COOKIE) pAd->OS_Cookie;
 	pObj->pspoll_frame_complete_task.data = (unsigned long)pUrb;
 	tasklet_hi_schedule(&pObj->pspoll_frame_complete_task);
-#endif
 }
 
-
-#if 0
-/*
-	========================================================================
-
-	Routine Description:
-	USB_RxPacket initializes a URB and uses the Rx IRP to submit it
-	to USB. It checks if an Rx Descriptor is available and passes the
-	the coresponding buffer to be filled. If no descriptor is available
-	fails the request. When setting the completion routine we pass our
-	Adapter Object as Context.
-
-	Arguments:
-
-	Return Value:
-		TRUE			found matched tuple cache
-		FALSE			no matched found
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTUSBBulkReceive(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	PRX_CONTEXT		pRxContext;
-	PURB			pUrb;
-	int				ret = 0;
-	unsigned long	IrqFlags;
-
-
-	/* device had been closed */
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_REMOVE_IN_PROGRESS))
-		return;
-
-	RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-
-	// Last is time point between 2 separate URB.
-	if (pAd->NextRxBulkInPosition == 0)
-	{
-		//pAd->NextRxBulkInIndex = (pAd->NextRxBulkInIndex + 1) % (RX_RING_SIZE);
-		INC_RING_INDEX(pAd->NextRxBulkInIndex, RX_RING_SIZE);
-	}
-	else if ((pAd->NextRxBulkInPosition&0x1ff) != 0)
-	{
-		//pAd->NextRxBulkInIndex = (pAd->NextRxBulkInIndex + 1) % (RX_RING_SIZE);
-		INC_RING_INDEX(pAd->NextRxBulkInIndex, RX_RING_SIZE);
-		DBGPRINT_RAW(RT_DEBUG_TRACE, ("pAd->NextRxBulkInPosition = 0x%lx.  End of URB.\n", pAd->NextRxBulkInPosition ));
-		pAd->NextRxBulkInPosition = 0;
-	}
-
-	if (pAd->NextRxBulkInPosition == MAX_RXBULK_SIZE)
-		pAd->NextRxBulkInPosition = 0;
-
-	pRxContext = &(pAd->RxContext[pAd->NextRxBulkInIndex]);
-
-	// TODO: Why need to check if pRxContext->InUsed == TRUE?
-	//if ((pRxContext->InUse == TRUE) || (pRxContext->Readable == TRUE))
-	if ((pRxContext->InUse == FALSE) && (pRxContext->Readable == TRUE))
-	{
-		DBGPRINT_RAW(RT_DEBUG_TRACE, ("pRxContext[%d] InUse = %d.pRxContext->Readable = %d.  Return.\n", pAd->NextRxBulkInIndex,pRxContext->InUse, pRxContext->Readable ));
-		RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-
-		// read RxContext, Since not
-#ifdef CONFIG_STA_SUPPORT
-		STARxDoneInterruptHandle(pAd, TRUE);
-#endif // CONFIG_STA_SUPPORT //
-
-		//return;
-	}
-	pRxContext->InUse = TRUE;
-	pRxContext->IRPPending= TRUE;
-
-	RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-
-	// Init Rx context descriptor
-	NdisZeroMemory(pRxContext->TransferBuffer, BUFFER_SIZE);
-	RTUSBInitRxDesc(pAd, pRxContext);
-
-	pUrb = pRxContext->pUrb;
-	if ((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RTUSBBulkReceive: Submit Rx URB failed %d\n", ret));
-		return;
-	}
-	else // success
-	{
-		NdisInterlockedIncrement(&pAd->PendingRx);
-		pAd->BulkInReq++;
-	}
-
-	// read RxContext, Since not
-#ifdef CONFIG_STA_SUPPORT
-	STARxDoneInterruptHandle(pAd, FALSE);
-#endif // CONFIG_STA_SUPPORT //
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		This routine process Rx Irp and call rx complete function.
-
-	Arguments:
-		DeviceObject	Pointer to the device object for next lower
-						device. DeviceObject passed in here belongs to
-						the next lower driver in the stack because we
-						were invoked via IoCallDriver in USB_RxPacket
-						AND it is not OUR device object
-	  Irp				Ptr to completed IRP
-	  Context			Ptr to our Adapter object (context specified
-						in IoSetCompletionRoutine
-
-	Return Value:
-		Always returns STATUS_MORE_PROCESSING_REQUIRED
-
-	Note:
-		Always returns STATUS_MORE_PROCESSING_REQUIRED
-	========================================================================
-*/
-VOID RTUSBBulkRxComplete(purbb_t pUrb, struct pt_regs *pt_regs)
-{
-#if 0
-	PRX_CONTEXT			pRxContext;
-	PRTMP_ADAPTER		pAd;
-	NTSTATUS			Status;
-//	POS_COOKIE			pObj;
-
-	pRxContext	= (PRX_CONTEXT)pUrb->context;
-	pAd 		= pRxContext->pAd;
-//	pObj		= (POS_COOKIE) pAd->OS_Cookie;
-
-
-	Status = pUrb->status;
-	//pRxContext->pIrp = NULL;
-
-	pRxContext->InUse = FALSE;
-	pRxContext->IRPPending = FALSE;
-
-	if (Status == USB_ST_NOERROR)
-	{
-		pAd->BulkInComplete++;
-		pRxContext->Readable = TRUE;
-		pAd->NextRxBulkInPosition = 0;
-
-	}
-	else	 // STATUS_OTHER
-	{
-		pAd->BulkInCompleteFail++;
-		// Still read this packet although it may comtain wrong bytes.
-		pRxContext->Readable = FALSE;
-		// Parsing all packets. because after reset, the index will reset to all zero.
-
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKIN_RESET)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-		{
-
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("Bulk In Failed. Status = %d\n", Status));
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("==>NextRxBulkInIndex=0x%x, NextRxBulkInReadIndex=0x%x, TransferBufferLength= 0x%x\n",
-				pAd->NextRxBulkInIndex, pAd->NextRxBulkInReadIndex, pRxContext->pUrb->actual_length));
-
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKIN_RESET);
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_IN, NULL, 0);
-		}
-		//pUrb = NULL;
-	}
-
-	if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-		(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKIN_RESET)) &&
-//		(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)) &&
-		(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF)) &&
-		(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-		(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-	{
-		RTUSBBulkReceive(pAd);
-#if 0
-#if 1
-		STARxDoneInterruptHandle(pAd, FALSE);
-#else
-		pObj->rx_bh.data = (unsigned long)pUrb;
-		tasklet_schedule(&pObj->rx_bh);
-#endif
-#endif
-	}
-
-	// Call RxPacket to process packet and return the status
-	NdisInterlockedDecrement(&pAd->PendingRx);
-#else
-
-
-	// use a receive tasklet to handle received packets;
-	// or sometimes hardware IRQ will be disabled here, so we can not
-	// use spin_lock_bh()/spin_unlock_bh() after IRQ is disabled. :<
-	PRX_CONTEXT		pRxContext;
-	PRTMP_ADAPTER	pAd;
-	POS_COOKIE 		pObj;
-
-
-	pRxContext	= (PRX_CONTEXT)pUrb->context;
-	pAd 		= pRxContext->pAd;
-	pObj 		= (POS_COOKIE) pAd->OS_Cookie;
-
-	pObj->rx_done_task.data = (unsigned long)pUrb;
-	tasklet_hi_schedule(&pObj->rx_done_task);
-#endif
-}
-
-#else
-
 VOID DoBulkIn(IN RTMP_ADAPTER *pAd)
 {
 	PRX_CONTEXT		pRxContext;
@@ -1441,14 +777,6 @@
 	}
 	else
 	{	// success
-#if 0
-		RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-		pRxContext->IRPPending = TRUE;
-		//NdisInterlockedIncrement(&pAd->PendingRx);
-		pAd->PendingRx++;
-		RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-		pAd->BulkInReq++;
-#endif
 		ASSERT((pRxContext->InUse == pRxContext->IRPPending));
 		//printk("BIDone, Pend=%d,BIIdx=%d,BIRIdx=%d!\n", pAd->PendingRx, pAd->NextRxBulkInIndex, pAd->NextRxBulkInReadIndex);
 	}
@@ -1508,10 +836,7 @@
 			RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
 
 			// read RxContext, Since not
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				STARxDoneInterruptHandle(pAd, TRUE);
-#endif // CONFIG_STA_SUPPORT //
+			STARxDoneInterruptHandle(pAd, TRUE);
 
 			// Finish to handle this bulkIn buffer.
 			RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
@@ -1579,8 +904,6 @@
 
 }
 
-#endif
-
 
 
 /*
@@ -1601,51 +924,8 @@
 {
 	// BulkIn Reset will reset whole USB PHY. So we need to make sure fRTMP_ADAPTER_BULKIN_RESET not flaged.
 	if (!RTMP_TEST_FLAG(pAd ,fRTMP_ADAPTER_NEED_STOP_TX)
-#ifdef RALINK_ATE
-		&& !(ATE_ON(pAd))
-#endif // RALINK_ATE //
 		)
 	{
-#if 0	// not used now in RT28xx, but may used latter.
-		// 1. Data Fragment has highest priority
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_FRAG))
-		{
-			if (((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) ||
-				(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				))
-			{
-				RTUSBBulkOutDataPacket(pAd, 0, pAd->NextBulkOutIndex[0]);
-			}
-		}
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_FRAG_2))
-		{
-			if (((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) ||
-				(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				))
-			{
-				RTUSBBulkOutDataPacket(pAd, 1, pAd->NextBulkOutIndex[1]);
-			}
-		}
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_FRAG_3))
-		{
-			if (((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) ||
-				(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				))
-			{
-				RTUSBBulkOutDataPacket(pAd, 2, pAd->NextBulkOutIndex[2]);
-			}
-		}
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_FRAG_4))
-		{
-			if (((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) ||
-				(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				))
-			{
-				RTUSBBulkOutDataPacket(pAd, 3, pAd->NextBulkOutIndex[3]);
-			}
-		}
-#endif
-
 		// 2. PS-Poll frame is next
 		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_PSPOLL))
 		{
@@ -1696,6 +976,17 @@
 				RTUSBBulkOutDataPacket(pAd, 3, pAd->NextBulkOutIndex[3]);
 			}
 		}
+#ifdef RT30xx
+		//PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
+		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL_5))
+		{
+			if (((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) ||
+				(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
+				))
+			{
+			}
+		}
+#endif
 
 		// 7. Null frame is the last
 		else if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NULL))
@@ -1712,18 +1003,6 @@
 
 		}
 	}
-#ifdef RALINK_ATE
-	/* If the mode is in ATE mode. */
-	else if((ATE_ON(pAd)) &&
-		!RTMP_TEST_FLAG(pAd ,fRTMP_ADAPTER_NEED_STOP_TX))// PETER : watch out !
-	{
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE))
-		{
-			ATE_RTUSBBulkOutDataPacket(pAd, 0);
-		}
-	}
-#endif // RALINK_ATE //
-
 }
 
 /*
@@ -1778,24 +1057,6 @@
 	IN	PRTMP_ADAPTER	pAd)
 {
 	DBGPRINT(RT_DEBUG_TRACE, ("--->CleanUpMLMEBulkOutQueue\n"));
-
-#if 0	// Do nothing!
-	NdisAcquireSpinLock(&pAd->MLMEBulkOutLock);
-	while (pAd->PrioRingTxCnt > 0)
-	{
-		pAd->MLMEContext[pAd->PrioRingFirstIndex].InUse = FALSE;
-
-		pAd->PrioRingFirstIndex++;
-		if (pAd->PrioRingFirstIndex >= MGMT_RING_SIZE)
-		{
-			pAd->PrioRingFirstIndex = 0;
-		}
-
-		pAd->PrioRingTxCnt--;
-	}
-	NdisReleaseSpinLock(&pAd->MLMEBulkOutLock);
-#endif
-
 	DBGPRINT(RT_DEBUG_TRACE, ("<---CleanUpMLMEBulkOutQueue\n"));
 }
 
@@ -1906,14 +1167,6 @@
 			RTMPusecDelay(200);
 		}
 
-#ifdef RALINK_ATE
-		pHTTXContext->bCopySavePad = 0;
-		pHTTXContext->CurWritePosition = 0;
-		pHTTXContext->CurWriteRealPos = 0;
-		pHTTXContext->bCurWriting = FALSE;
-		pHTTXContext->NextBulkOutPosition = 0;
-		pHTTXContext->ENextBulkOutPosition = 0;
-#endif // RALINK_ATE //
 		pAd->BulkOutPending[Idx] = FALSE;
 	}
 
diff --git a/drivers/staging/rt2870/common/rtusb_data.c b/drivers/staging/rt2870/common/rtusb_data.c
index 5a0d783..6b003f6 100644
--- a/drivers/staging/rt2870/common/rtusb_data.c
+++ b/drivers/staging/rt2870/common/rtusb_data.c
@@ -135,24 +135,11 @@
 	RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
 	if ((pHTTXContext->IRPPending == TRUE)  /*&& (pAd->TxSwQueue[BulkOutPipeId].Number == 0) */)
 	{
-#if 0
-		if ((pHTTXContext->CurWritePosition <= 8) &&
-			(pHTTXContext->NextBulkOutPosition > 8 && (pHTTXContext->NextBulkOutPosition+MAX_AGGREGATION_SIZE) < MAX_TXBULK_LIMIT))
-		{
-			needQueBack = TRUE;
-		}
-		else if ((pHTTXContext->CurWritePosition < pHTTXContext->NextBulkOutPosition) &&
-				 ((pHTTXContext->NextBulkOutPosition + MAX_AGGREGATION_SIZE) < MAX_TXBULK_LIMIT))
-		{
-			needQueBack = TRUE;
-		}
-#else
 		if ((pHTTXContext->CurWritePosition < pHTTXContext->ENextBulkOutPosition) &&
 			(((pHTTXContext->ENextBulkOutPosition+MAX_AGGREGATION_SIZE) < MAX_TXBULK_LIMIT) || (pHTTXContext->CurWritePosition > MAX_AGGREGATION_SIZE)))
 		{
 			needQueBack = TRUE;
 		}
-#endif
 		else if ((pHTTXContext->CurWritePosition > pHTTXContext->ENextBulkOutPosition) &&
 				 ((pHTTXContext->ENextBulkOutPosition + MAX_AGGREGATION_SIZE) < pHTTXContext->CurWritePosition))
 		{
diff --git a/drivers/staging/rt2870/common/rtusb_io.c b/drivers/staging/rt2870/common/rtusb_io.c
index afde136..fd1b0c1 100644
--- a/drivers/staging/rt2870/common/rtusb_io.c
+++ b/drivers/staging/rt2870/common/rtusb_io.c
@@ -110,6 +110,12 @@
 	Status = RTUSBWriteMACRegister(pAd, 0x701c, 0xffffffff);
 	Status = RTUSBFirmwareRun(pAd);
 
+#ifdef RT30xx
+	RTMPusecDelay(10000);
+	RTUSBWriteMACRegister(pAd,H2M_MAILBOX_CSR,0);
+	AsicSendCommandToMcu(pAd, 0x72, 0x00, 0x00, 0x00);//reset rf by MCU supported by new firmware
+#endif
+
 	return Status;
 }
 
@@ -665,6 +671,7 @@
 	return STATUS_SUCCESS;
 }
 
+#ifndef RT30xx
 /*
 	========================================================================
 
@@ -772,6 +779,7 @@
 
 	return STATUS_SUCCESS;
 }
+#endif /* RT30xx */
 
 /*
 	========================================================================
@@ -796,6 +804,14 @@
 {
 	NTSTATUS	Status = STATUS_SUCCESS;
 
+#ifdef RT30xx
+	if(pAd->bUseEfuse)
+	{
+		Status =eFuseRead(pAd, Offset, pData, length);
+	}
+	else
+#endif // RT30xx //
+	{
 	Status = RTUSB_VendorRequest(
 		pAd,
 		(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
@@ -805,6 +821,7 @@
 		Offset,
 		pData,
 		length);
+	}
 
 	return Status;
 }
@@ -832,6 +849,14 @@
 {
 	NTSTATUS	Status = STATUS_SUCCESS;
 
+#ifdef RT30xx
+	if(pAd->bUseEfuse)
+	{
+		Status = eFuseWrite(pAd, Offset, pData, length);
+	}
+	else
+#endif // RT30xx //
+	{
 	Status = RTUSB_VendorRequest(
 		pAd,
 		USBD_TRANSFER_DIRECTION_OUT,
@@ -841,6 +866,7 @@
 		Offset,
 		pData,
 		length);
+	}
 
 	return Status;
 }
@@ -957,9 +983,13 @@
 	PCmdQElmt	cmdqelmt = NULL;
 	POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;
 
-
+#ifndef RT30xx
 	BUG_ON(pObj->RTUSBCmdThr_task == NULL);
 	CHECK_PID_LEGALITY(task_pid(pObj->RTUSBCmdThr_task))
+#endif
+#ifdef RT30xx
+	if (pObj->RTUSBCmdThr_pid < 0)
+#endif
 		return (NDIS_STATUS_RESOURCES);
 
 	status = RTMPAllocateMemory((PVOID *)&cmdqelmt, sizeof(CmdQElmt));
@@ -1194,21 +1224,6 @@
 		void	*tmpBuf = TransferBuffer;
 
 		// Acquire Control token
-#ifdef INF_AMAZON_SE
-		//Semaphore fix INF_AMAZON_SE hang
-		//pAd->UsbVendorReqBuf is the swap for DEVICE_VENDOR_REQUEST_IN to fix dma bug.
-		ret = down_interruptible(&(pAd->UsbVendorReq_semaphore));
-		if (pAd->UsbVendorReqBuf)
-		{
-			ASSERT(TransferBufferLength <MAX_PARAM_BUFFER_SIZE);
-
-		   	tmpBuf = (void *)pAd->UsbVendorReqBuf;
-		   	NdisZeroMemory(pAd->UsbVendorReqBuf, TransferBufferLength);
-
-		   	if (RequestType == DEVICE_VENDOR_REQUEST_OUT)
-		   	 NdisMoveMemory(tmpBuf, TransferBuffer, TransferBufferLength);
-		}
-#endif // INF_AMAZON_SE //
 		do {
 		if( RequestType == DEVICE_VENDOR_REQUEST_OUT)
 			ret=usb_control_msg(pObj->pUsb_Dev, usb_sndctrlpipe( pObj->pUsb_Dev, 0 ), Request, RequestType, Value,Index, tmpBuf, TransferBufferLength, CONTROL_TIMEOUT_JIFFIES);
@@ -1227,12 +1242,6 @@
 			}
 		} while((ret < 0) && (retryCount < MAX_RETRY_COUNT));
 
-#ifdef INF_AMAZON_SE
-	  	if ((pAd->UsbVendorReqBuf) && (RequestType == DEVICE_VENDOR_REQUEST_IN))
-			NdisMoveMemory(TransferBuffer, tmpBuf, TransferBufferLength);
-	  	up(&(pAd->UsbVendorReq_semaphore));
-#endif // INF_AMAZON_SE //
-
         if (ret < 0) {
 //			DBGPRINT(RT_DEBUG_ERROR, ("USBVendorRequest failed ret=%d \n",ret));
 			DBGPRINT(RT_DEBUG_ERROR, ("RTUSB_VendorRequest failed(%d),TxFlags=0x%x, ReqType=%s, Req=0x%x, Index=0x%x\n",
@@ -1243,28 +1252,6 @@
 			if ((TransferBuffer!= NULL) && (TransferBufferLength > 0))
 				hex_dump("Failed TransferBuffer value", TransferBuffer, TransferBufferLength);
         }
-
-#if 0
-        // retry
-		if (ret < 0) {
-			int temp_i=0;
-			DBGPRINT(RT_DEBUG_ERROR, ("USBVendorRequest failed ret=%d, \n",ret));
-			ret = 0;
-			do
-			{
-				if( RequestType == DEVICE_VENDOR_REQUEST_OUT)
-					ret=usb_control_msg(pObj->pUsb_Dev, usb_sndctrlpipe( pObj->pUsb_Dev, 0 ), Request, RequestType, Value,Index, TransferBuffer, TransferBufferLength, CONTROL_TIMEOUT_JIFFIES);
-				else if(RequestType == DEVICE_VENDOR_REQUEST_IN)
-					ret=usb_control_msg(pObj->pUsb_Dev, usb_rcvctrlpipe( pObj->pUsb_Dev, 0 ), Request, RequestType, Value,Index, TransferBuffer, TransferBufferLength, CONTROL_TIMEOUT_JIFFIES);
-				temp_i++;
-			} while( (ret < 0) && (temp_i <= 1) );
-
-			if( ret >= 0)
-				return ret;
-
-		}
-#endif
-
 	}
 	return ret;
 }
@@ -1324,21 +1311,8 @@
 			{
 				case CMDTHREAD_CHECK_GPIO:
 					{
-#ifdef CONFIG_STA_SUPPORT
 						UINT32 data;
-#endif // CONFIG_STA_SUPPORT //
-#ifdef RALINK_ATE
-       					if(ATE_ON(pAd))
-						{
-							DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-							break;
-						}
-#endif // RALINK_ATE //
 
-#ifdef CONFIG_STA_SUPPORT
-
-
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 						{
 							// Read GPIO pin2 as Hardware controlled radio state
 
@@ -1374,17 +1348,14 @@
 								}
 							}
 						}
-#endif // CONFIG_STA_SUPPORT //
 					}
 					break;
 
-#ifdef CONFIG_STA_SUPPORT
 				case CMDTHREAD_QKERIODIC_EXECUT:
 					{
 						StaQuickResponeForRateUpExec(NULL, pAd, NULL, NULL);
 					}
 					break;
-#endif // CONFIG_STA_SUPPORT //
 
 				case CMDTHREAD_RESET_BULK_OUT:
 					{
@@ -1394,9 +1365,7 @@
 						PHT_TX_CONTEXT	pHTTXContext;
 //						RTMP_TX_RING *pTxRing;
 						unsigned long IrqFlags;
-#ifdef RALINK_ATE
-						PTX_CONTEXT		pNullContext = &(pAd->NullContext);
-#endif // RALINK_ATE //
+
 						DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_RESET_BULK_OUT(ResetPipeid=0x%0x)===>\n", pAd->bulkResetPipeid));
 						// All transfers must be aborted or cancelled before attempting to reset the pipe.
 						//RTUSBCancelPendingBulkOutIRP(pAd);
@@ -1459,32 +1428,6 @@
 								//NdisReleaseSpinLock(&pAd->BulkOutLock[pAd->bulkResetPipeid]);
 								RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
 /*-----------------------------------------------------------------------------------------------*/
-#ifdef RALINK_ATE
-								if(ATE_ON(pAd))
-							    {
-									pNullContext->IRPPending = TRUE;
-									//
-									// If driver is still in ATE TXFRAME mode,
-									// keep on transmitting ATE frames.
-									//
-									DBGPRINT_RAW(RT_DEBUG_TRACE, ("pAd->ate.Mode == %d\npAd->ContinBulkOut == %d\npAd->BulkOutRemained == %d\n", pAd->ate.Mode, pAd->ContinBulkOut, atomic_read(&pAd->BulkOutRemained)));
-									if((pAd->ate.Mode == ATE_TXFRAME) && ((pAd->ContinBulkOut == TRUE) || (atomic_read(&pAd->BulkOutRemained) > 0)))
-								    {
-										DBGPRINT_RAW(RT_DEBUG_TRACE, ("After CMDTHREAD_RESET_BULK_OUT, continue to bulk out frames !\n"));
-
-										// Init Tx context descriptor
-										RTUSBInitTxDesc(pAd, pNullContext, 0/* pAd->bulkResetPipeid */, (usb_complete_t)ATE_RTUSBBulkOutDataPacketComplete);
-
-										if((ret = RTUSB_SUBMIT_URB(pNullContext->pUrb))!=0)
-										{
-											DBGPRINT(RT_DEBUG_ERROR, ("ATE_RTUSBBulkOutDataPacket: Submit Tx URB failed %d\n", ret));
-										}
-
-										pAd->BulkOutReq++;
-									}
-								}
-								else
-#endif // RALINK_ATE //
 /*-----------------------------------------------------------------------------------------------*/
 								{
 								RTUSBInitHTTxDesc(pAd, pHTTXContext, pAd->bulkResetPipeid, pHTTXContext->BulkOutSize, (usb_complete_t)RTUSBBulkOutDataPacketComplete);
@@ -1597,19 +1540,6 @@
 					{
 						UINT32		MACValue;
 /*-----------------------------------------------------------------------------------------------*/
-#ifdef RALINK_ATE
-						if (ATE_ON(pAd))
-						{
-							if((pAd->PendingRx > 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-							{
-								DBGPRINT_RAW(RT_DEBUG_ERROR, ("ATE : BulkIn IRP Pending!!!\n"));
-								ATE_RTUSBCancelPendingBulkInIRP(pAd);
-								RTMPusecDelay(100000);
-								pAd->PendingRx = 0;
-							}
-						}
-						else
-#endif // RALINK_ATE //
 /*-----------------------------------------------------------------------------------------------*/
 						{
 						//while ((atomic_read(&pAd->PendingRx) > 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
@@ -1699,15 +1629,6 @@
 								}
 								else
 								{	// success
-#if 0
-									RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-									pRxContext->IRPPending = TRUE;
-									//NdisInterlockedIncrement(&pAd->PendingRx);
-									pAd->PendingRx++;
-									RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-									pAd->BulkInReq++;
-#endif
-									//printk("BIDone, Pend=%d,BIIdx=%d,BIRIdx=%d!\n", pAd->PendingRx, pAd->NextRxBulkInIndex, pAd->NextRxBulkInReadIndex);
 									DBGPRINT_RAW(RT_DEBUG_TRACE, ("CMDTHREAD_RESET_BULK_IN: Submit Rx URB Done, status=%d!\n", pUrb->status));
 									ASSERT((pRxContext->InUse == pRxContext->IRPPending));
 								}
@@ -1765,7 +1686,6 @@
 
 				case CMDTHREAD_SET_ASIC_WCID_CIPHER:
 					{
-#ifdef CONFIG_STA_SUPPORT
 						RT_SET_ASIC_WCID_ATTRI	SetAsicWcidAttri;
 						USHORT		offset;
 						UINT32		MACRValue = 0;
@@ -1817,46 +1737,46 @@
 
 							RTUSBWriteMACRegister(pAd, SHARED_KEY_MODE_BASE+4*(0/2), csr1.word);
 						}
-#endif // CONFIG_STA_SUPPORT //
 					}
 					break;
 
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-				// avoid in interrupt when write key
+#ifdef RT30xx
+//Benson modified for USB interface, avoid in interrupt when write key, 20080724 -->
 				case RT_CMD_SET_KEY_TABLE: //General call for AsicAddPairwiseKeyEntry()
-					{
-						RT_ADD_PAIRWISE_KEY_ENTRY KeyInfo;
-						KeyInfo  = *((PRT_ADD_PAIRWISE_KEY_ENTRY)(pData));
-						AsicAddPairwiseKeyEntry(pAd,
-												KeyInfo.MacAddr,
-												(UCHAR)KeyInfo.MacTabMatchWCID,
-												&KeyInfo.CipherKey);
-					}
+				{
+					RT_ADD_PAIRWISE_KEY_ENTRY KeyInfo;
+					KeyInfo = *((PRT_ADD_PAIRWISE_KEY_ENTRY)(pData));
+					AsicAddPairwiseKeyEntry(pAd,
+											KeyInfo.MacAddr,
+											(UCHAR)KeyInfo.MacTabMatchWCID,
+											&KeyInfo.CipherKey);
+				}
 					break;
-
 				case RT_CMD_SET_RX_WCID_TABLE: //General call for RTMPAddWcidAttributeEntry()
-					{
-						PMAC_TABLE_ENTRY pEntry ;
-						pEntry = (PMAC_TABLE_ENTRY)(pData);
-						RTMPAddWcidAttributeEntry(pAd,
-													BSS0,
-													0,
-													pEntry->PairwiseKey.CipherAlg,
-													pEntry);
+				{
+					PMAC_TABLE_ENTRY pEntry;
+					UCHAR KeyIdx;
+					UCHAR CipherAlg;
+					UCHAR ApIdx;
+
+					pEntry = (PMAC_TABLE_ENTRY)(pData);
+
+						RTMPAddWcidAttributeEntry(
+										  pAd,
+										  ApIdx,
+										  KeyIdx,
+										  CipherAlg,
+										  pEntry);
 					}
-					break;
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
+						break;
+//Benson modified for USB interface, avoid in interrupt when write key, 20080724 <--
+#endif
 
 				case CMDTHREAD_SET_CLIENT_MAC_ENTRY:
 					{
 						MAC_TABLE_ENTRY *pEntry;
 						pEntry = (MAC_TABLE_ENTRY *)pData;
 
-
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
 						{
 							AsicRemovePairwiseKeyEntry(pAd, pEntry->apidx, (UCHAR)pEntry->Aid);
 							if ((pEntry->AuthMode <= Ndis802_11AuthModeAutoSwitch) && (pEntry->WepStatus == Ndis802_11Encryption1Enabled))
@@ -1891,7 +1811,6 @@
 								RTUSBWriteMACRegister(pAd, offset, 0);
 							}
 						}
-#endif // CONFIG_STA_SUPPORT //
 
 						AsicUpdateRxWCIDTable(pAd, pEntry->Aid, pEntry->Addr);
 						printk("UpdateRxWCIDTable(): Aid=%d, Addr=%02x:%02x:%02x:%02x:%02x:%02x!\n", pEntry->Aid,
@@ -1899,9 +1818,18 @@
 					}
 					break;
 
+#ifdef RT30xx
+// add by johnli, fix "in_interrupt" error when call "MacTableDeleteEntry" in Rx tasklet
+				case CMDTHREAD_UPDATE_PROTECT:
+					{
+						AsicUpdateProtect(pAd, 0, (ALLN_SETPROTECT), TRUE, 0);
+					}
+					break;
+// end johnli
+#endif
+
 				case OID_802_11_ADD_WEP:
 					{
-#ifdef CONFIG_STA_SUPPORT
 						UINT	i;
 						UINT32	KeyIdx;
 						PNDIS_802_11_WEP	pWepKey;
@@ -1975,7 +1903,6 @@
 							AsicAddSharedKeyEntry(pAd, BSS0, (UCHAR)KeyIdx, CipherAlg, pWepKey->KeyMaterial, NULL, NULL);
 							DBGPRINT(RT_DEBUG_TRACE, ("CmdThread::OID_802_11_ADD_WEP (KeyIdx=%d, Len=%d-byte)\n", KeyIdx, pWepKey->KeyLength));
 						}
-#endif // CONFIG_STA_SUPPORT //
 					}
 					break;
 
diff --git a/drivers/staging/rt2870/common/spectrum.c b/drivers/staging/rt2870/common/spectrum.c
index 7438095..1cf2c26 100644
--- a/drivers/staging/rt2870/common/spectrum.c
+++ b/drivers/staging/rt2870/common/spectrum.c
@@ -1,1876 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-	action.c
-
-    Abstract:
-    Handle association related requests either from WSTA or from local MLME
-
-    Revision History:
-    Who          When          What
-    ---------    ----------    ----------------------------------------------
-	Fonchi Wu    2008	  	   created for 802.11h
- */
-
-#include "../rt_config.h"
-#include "action.h"
-
-VOID MeasureReqTabInit(
-	IN PRTMP_ADAPTER pAd)
-{
-	NdisAllocateSpinLock(&pAd->CommonCfg.MeasureReqTabLock);
-
-	pAd->CommonCfg.pMeasureReqTab = kmalloc(sizeof(MEASURE_REQ_TAB), GFP_ATOMIC);
-	if (pAd->CommonCfg.pMeasureReqTab)
-		NdisZeroMemory(pAd->CommonCfg.pMeasureReqTab, sizeof(MEASURE_REQ_TAB));
-	else
-		DBGPRINT(RT_DEBUG_ERROR, ("%s Fail to alloc memory for pAd->CommonCfg.pMeasureReqTab.\n", __func__));
-
-	return;
-}
-
-VOID MeasureReqTabExit(
-	IN PRTMP_ADAPTER pAd)
-{
-	NdisFreeSpinLock(pAd->CommonCfg.MeasureReqTabLock);
-
-	if (pAd->CommonCfg.pMeasureReqTab)
-		kfree(pAd->CommonCfg.pMeasureReqTab);
-	pAd->CommonCfg.pMeasureReqTab = NULL;
-
-	return;
-}
-
-static PMEASURE_REQ_ENTRY MeasureReqLookUp(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	UINT HashIdx;
-	PMEASURE_REQ_TAB pTab = pAd->CommonCfg.pMeasureReqTab;
-	PMEASURE_REQ_ENTRY pEntry = NULL;
-	PMEASURE_REQ_ENTRY pPrevEntry = NULL;
-
-	if (pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab doesn't exist.\n", __func__));
-		return NULL;
-	}
-
-	RTMP_SEM_LOCK(&pAd->CommonCfg.MeasureReqTabLock);
-
-	HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(DialogToken);
-	pEntry = pTab->Hash[HashIdx];
-
-	while (pEntry)
-	{
-		if (pEntry->DialogToken == DialogToken)
-			break;
-		else
-		{
-			pPrevEntry = pEntry;
-			pEntry = pEntry->pNext;
-		}
-	}
-
-	RTMP_SEM_UNLOCK(&pAd->CommonCfg.MeasureReqTabLock);
-
-	return pEntry;
-}
-
-static PMEASURE_REQ_ENTRY MeasureReqInsert(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	INT i;
-	ULONG HashIdx;
-	PMEASURE_REQ_TAB pTab = pAd->CommonCfg.pMeasureReqTab;
-	PMEASURE_REQ_ENTRY pEntry = NULL, pCurrEntry;
-	ULONG Now;
-
-	if(pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab doesn't exist.\n", __func__));
-		return NULL;
-	}
-
-	pEntry = MeasureReqLookUp(pAd, DialogToken);
-	if (pEntry == NULL)
-	{
-		RTMP_SEM_LOCK(&pAd->CommonCfg.MeasureReqTabLock);
-		for (i = 0; i < MAX_MEASURE_REQ_TAB_SIZE; i++)
-		{
-			NdisGetSystemUpTime(&Now);
-			pEntry = &pTab->Content[i];
-
-			if ((pEntry->Valid == TRUE)
-				&& RTMP_TIME_AFTER((unsigned long)Now, (unsigned long)(pEntry->lastTime + MQ_REQ_AGE_OUT)))
-			{
-				PMEASURE_REQ_ENTRY pPrevEntry = NULL;
-				ULONG HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
-				PMEASURE_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
-
-				// update Hash list
-				do
-				{
-					if (pProbeEntry == pEntry)
-					{
-						if (pPrevEntry == NULL)
-						{
-							pTab->Hash[HashIdx] = pEntry->pNext;
-						}
-						else
-						{
-							pPrevEntry->pNext = pEntry->pNext;
-						}
-						break;
-					}
-
-					pPrevEntry = pProbeEntry;
-					pProbeEntry = pProbeEntry->pNext;
-				} while (pProbeEntry);
-
-				NdisZeroMemory(pEntry, sizeof(MEASURE_REQ_ENTRY));
-				pTab->Size--;
-
-				break;
-			}
-
-			if (pEntry->Valid == FALSE)
-				break;
-		}
-
-		if (i < MAX_MEASURE_REQ_TAB_SIZE)
-		{
-			NdisGetSystemUpTime(&Now);
-			pEntry->lastTime = Now;
-			pEntry->Valid = TRUE;
-			pEntry->DialogToken = DialogToken;
-			pTab->Size++;
-		}
-		else
-		{
-			pEntry = NULL;
-			DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab tab full.\n", __func__));
-		}
-
-		// add this Neighbor entry into HASH table
-		if (pEntry)
-		{
-			HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(DialogToken);
-			if (pTab->Hash[HashIdx] == NULL)
-			{
-				pTab->Hash[HashIdx] = pEntry;
-			}
-			else
-			{
-				pCurrEntry = pTab->Hash[HashIdx];
-				while (pCurrEntry->pNext != NULL)
-					pCurrEntry = pCurrEntry->pNext;
-				pCurrEntry->pNext = pEntry;
-			}
-		}
-
-		RTMP_SEM_UNLOCK(&pAd->CommonCfg.MeasureReqTabLock);
-	}
-
-	return pEntry;
-}
-
-static VOID MeasureReqDelete(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	PMEASURE_REQ_TAB pTab = pAd->CommonCfg.pMeasureReqTab;
-	PMEASURE_REQ_ENTRY pEntry = NULL;
-
-	if(pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab doesn't exist.\n", __func__));
-		return;
-	}
-
-	// if empty, return
-	if (pTab->Size == 0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("pMeasureReqTab empty.\n"));
-		return;
-	}
-
-	pEntry = MeasureReqLookUp(pAd, DialogToken);
-	if (pEntry != NULL)
-	{
-		PMEASURE_REQ_ENTRY pPrevEntry = NULL;
-		ULONG HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
-		PMEASURE_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
-
-		RTMP_SEM_LOCK(&pAd->CommonCfg.MeasureReqTabLock);
-		// update Hash list
-		do
-		{
-			if (pProbeEntry == pEntry)
-			{
-				if (pPrevEntry == NULL)
-				{
-					pTab->Hash[HashIdx] = pEntry->pNext;
-				}
-				else
-				{
-					pPrevEntry->pNext = pEntry->pNext;
-				}
-				break;
-			}
-
-			pPrevEntry = pProbeEntry;
-			pProbeEntry = pProbeEntry->pNext;
-		} while (pProbeEntry);
-
-		NdisZeroMemory(pEntry, sizeof(MEASURE_REQ_ENTRY));
-		pTab->Size--;
-
-		RTMP_SEM_UNLOCK(&pAd->CommonCfg.MeasureReqTabLock);
-	}
-
-	return;
-}
-
-VOID TpcReqTabInit(
-	IN PRTMP_ADAPTER pAd)
-{
-	NdisAllocateSpinLock(&pAd->CommonCfg.TpcReqTabLock);
-
-	pAd->CommonCfg.pTpcReqTab = kmalloc(sizeof(TPC_REQ_TAB), GFP_ATOMIC);
-	if (pAd->CommonCfg.pTpcReqTab)
-		NdisZeroMemory(pAd->CommonCfg.pTpcReqTab, sizeof(TPC_REQ_TAB));
-	else
-		DBGPRINT(RT_DEBUG_ERROR, ("%s Fail to alloc memory for pAd->CommonCfg.pTpcReqTab.\n", __func__));
-
-	return;
-}
-
-VOID TpcReqTabExit(
-	IN PRTMP_ADAPTER pAd)
-{
-	NdisFreeSpinLock(pAd->CommonCfg.TpcReqTabLock);
-
-	if (pAd->CommonCfg.pTpcReqTab)
-		kfree(pAd->CommonCfg.pTpcReqTab);
-	pAd->CommonCfg.pTpcReqTab = NULL;
-
-	return;
-}
-
-static PTPC_REQ_ENTRY TpcReqLookUp(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	UINT HashIdx;
-	PTPC_REQ_TAB pTab = pAd->CommonCfg.pTpcReqTab;
-	PTPC_REQ_ENTRY pEntry = NULL;
-	PTPC_REQ_ENTRY pPrevEntry = NULL;
-
-	if (pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab doesn't exist.\n", __func__));
-		return NULL;
-	}
-
-	RTMP_SEM_LOCK(&pAd->CommonCfg.TpcReqTabLock);
-
-	HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(DialogToken);
-	pEntry = pTab->Hash[HashIdx];
-
-	while (pEntry)
-	{
-		if (pEntry->DialogToken == DialogToken)
-			break;
-		else
-		{
-			pPrevEntry = pEntry;
-			pEntry = pEntry->pNext;
-		}
-	}
-
-	RTMP_SEM_UNLOCK(&pAd->CommonCfg.TpcReqTabLock);
-
-	return pEntry;
-}
-
-
-static PTPC_REQ_ENTRY TpcReqInsert(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	INT i;
-	ULONG HashIdx;
-	PTPC_REQ_TAB pTab = pAd->CommonCfg.pTpcReqTab;
-	PTPC_REQ_ENTRY pEntry = NULL, pCurrEntry;
-	ULONG Now;
-
-	if(pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab doesn't exist.\n", __func__));
-		return NULL;
-	}
-
-	pEntry = TpcReqLookUp(pAd, DialogToken);
-	if (pEntry == NULL)
-	{
-		RTMP_SEM_LOCK(&pAd->CommonCfg.TpcReqTabLock);
-		for (i = 0; i < MAX_TPC_REQ_TAB_SIZE; i++)
-		{
-			NdisGetSystemUpTime(&Now);
-			pEntry = &pTab->Content[i];
-
-			if ((pEntry->Valid == TRUE)
-				&& RTMP_TIME_AFTER((unsigned long)Now, (unsigned long)(pEntry->lastTime + TPC_REQ_AGE_OUT)))
-			{
-				PTPC_REQ_ENTRY pPrevEntry = NULL;
-				ULONG HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
-				PTPC_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
-
-				// update Hash list
-				do
-				{
-					if (pProbeEntry == pEntry)
-					{
-						if (pPrevEntry == NULL)
-						{
-							pTab->Hash[HashIdx] = pEntry->pNext;
-						}
-						else
-						{
-							pPrevEntry->pNext = pEntry->pNext;
-						}
-						break;
-					}
-
-					pPrevEntry = pProbeEntry;
-					pProbeEntry = pProbeEntry->pNext;
-				} while (pProbeEntry);
-
-				NdisZeroMemory(pEntry, sizeof(TPC_REQ_ENTRY));
-				pTab->Size--;
-
-				break;
-			}
-
-			if (pEntry->Valid == FALSE)
-				break;
-		}
-
-		if (i < MAX_TPC_REQ_TAB_SIZE)
-		{
-			NdisGetSystemUpTime(&Now);
-			pEntry->lastTime = Now;
-			pEntry->Valid = TRUE;
-			pEntry->DialogToken = DialogToken;
-			pTab->Size++;
-		}
-		else
-		{
-			pEntry = NULL;
-			DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab tab full.\n", __func__));
-		}
-
-		// add this Neighbor entry into HASH table
-		if (pEntry)
-		{
-			HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(DialogToken);
-			if (pTab->Hash[HashIdx] == NULL)
-			{
-				pTab->Hash[HashIdx] = pEntry;
-			}
-			else
-			{
-				pCurrEntry = pTab->Hash[HashIdx];
-				while (pCurrEntry->pNext != NULL)
-					pCurrEntry = pCurrEntry->pNext;
-				pCurrEntry->pNext = pEntry;
-			}
-		}
-
-		RTMP_SEM_UNLOCK(&pAd->CommonCfg.TpcReqTabLock);
-	}
-
-	return pEntry;
-}
-
-static VOID TpcReqDelete(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	PTPC_REQ_TAB pTab = pAd->CommonCfg.pTpcReqTab;
-	PTPC_REQ_ENTRY pEntry = NULL;
-
-	if(pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab doesn't exist.\n", __func__));
-		return;
-	}
-
-	// if empty, return
-	if (pTab->Size == 0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("pTpcReqTab empty.\n"));
-		return;
-	}
-
-	pEntry = TpcReqLookUp(pAd, DialogToken);
-	if (pEntry != NULL)
-	{
-		PTPC_REQ_ENTRY pPrevEntry = NULL;
-		ULONG HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
-		PTPC_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
-
-		RTMP_SEM_LOCK(&pAd->CommonCfg.TpcReqTabLock);
-		// update Hash list
-		do
-		{
-			if (pProbeEntry == pEntry)
-			{
-				if (pPrevEntry == NULL)
-				{
-					pTab->Hash[HashIdx] = pEntry->pNext;
-				}
-				else
-				{
-					pPrevEntry->pNext = pEntry->pNext;
-				}
-				break;
-			}
-
-			pPrevEntry = pProbeEntry;
-			pProbeEntry = pProbeEntry->pNext;
-		} while (pProbeEntry);
-
-		NdisZeroMemory(pEntry, sizeof(TPC_REQ_ENTRY));
-		pTab->Size--;
-
-		RTMP_SEM_UNLOCK(&pAd->CommonCfg.TpcReqTabLock);
-	}
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Get Current TimeS tamp.
-
-	Parametrs:
-
-	Return	: Current Time Stamp.
-	==========================================================================
- */
-static UINT64 GetCurrentTimeStamp(
-	IN PRTMP_ADAPTER pAd)
-{
-	// get current time stamp.
-	return 0;
-}
-
-/*
-	==========================================================================
-	Description:
-		Get Current Transmit Power.
-
-	Parametrs:
-
-	Return	: Current Time Stamp.
-	==========================================================================
- */
-static UINT8 GetCurTxPwr(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT8 Wcid)
-{
-	return 16; /* 16 dBm */
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert Dialog Token into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. Dialog token.
-
-	Return	: None.
-	==========================================================================
- */
-static VOID InsertDialogToken(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN UINT8 DialogToken)
-{
-	ULONG TempLen;
-	MakeOutgoingFrame(pFrameBuf,	&TempLen,
-					1,				&DialogToken,
-					END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert TPC Request IE into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-
-	Return	: None.
-	==========================================================================
- */
- static VOID InsertTpcReqIE(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen)
-{
-	ULONG TempLen;
-	ULONG Len = 0;
-	UINT8 ElementID = IE_TPC_REQUEST;
-
-	MakeOutgoingFrame(pFrameBuf,					&TempLen,
-						1,							&ElementID,
-						1,							&Len,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert TPC Report IE into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. Transmit Power.
-		4. Link Margin.
-
-	Return	: None.
-	==========================================================================
- */
- static VOID InsertTpcReportIE(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN UINT8 TxPwr,
-	IN UINT8 LinkMargin)
-{
-	ULONG TempLen;
-	ULONG Len = sizeof(TPC_REPORT_INFO);
-	UINT8 ElementID = IE_TPC_REPORT;
-	TPC_REPORT_INFO TpcReportIE;
-
-	TpcReportIE.TxPwr = TxPwr;
-	TpcReportIE.LinkMargin = LinkMargin;
-
-	MakeOutgoingFrame(pFrameBuf,					&TempLen,
-						1,							&ElementID,
-						1,							&Len,
-						Len,						&TpcReportIE,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert Channel Switch Announcement IE into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. channel switch announcement mode.
-		4. new selected channel.
-		5. channel switch announcement count.
-
-	Return	: None.
-	==========================================================================
- */
-static VOID InsertChSwAnnIE(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN UINT8 ChSwMode,
-	IN UINT8 NewChannel,
-	IN UINT8 ChSwCnt)
-{
-	ULONG TempLen;
-	ULONG Len = sizeof(CH_SW_ANN_INFO);
-	UINT8 ElementID = IE_CHANNEL_SWITCH_ANNOUNCEMENT;
-	CH_SW_ANN_INFO ChSwAnnIE;
-
-	ChSwAnnIE.ChSwMode = ChSwMode;
-	ChSwAnnIE.Channel = NewChannel;
-	ChSwAnnIE.ChSwCnt = ChSwCnt;
-
-	MakeOutgoingFrame(pFrameBuf,				&TempLen,
-						1,						&ElementID,
-						1,						&Len,
-						Len,					&ChSwAnnIE,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert Measure Request IE into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. Measure Token.
-		4. Measure Request Mode.
-		5. Measure Request Type.
-		6. Measure Channel.
-		7. Measure Start time.
-		8. Measure Duration.
-
-
-	Return	: None.
-	==========================================================================
- */
-static VOID InsertMeasureReqIE(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN PMEASURE_REQ_INFO pMeasureReqIE)
-{
-	ULONG TempLen;
-	UINT8 Len = sizeof(MEASURE_REQ_INFO);
-	UINT8 ElementID = IE_MEASUREMENT_REQUEST;
-
-	MakeOutgoingFrame(pFrameBuf,					&TempLen,
-						1,							&ElementID,
-						1,							&Len,
-						Len,						pMeasureReqIE,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert Measure Report IE into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. Measure Token.
-		4. Measure Request Mode.
-		5. Measure Request Type.
-		6. Length of Report Infomation
-		7. Pointer of Report Infomation Buffer.
-
-	Return	: None.
-	==========================================================================
- */
-static VOID InsertMeasureReportIE(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN PMEASURE_REPORT_INFO pMeasureReportIE,
-	IN UINT8 ReportLnfoLen,
-	IN PUINT8 pReportInfo)
-{
-	ULONG TempLen;
-	ULONG Len;
-	UINT8 ElementID = IE_MEASUREMENT_REPORT;
-
-	Len = sizeof(MEASURE_REPORT_INFO) + ReportLnfoLen;
-
-	MakeOutgoingFrame(pFrameBuf,					&TempLen,
-						1,							&ElementID,
-						1,							&Len,
-						Len,						pMeasureReportIE,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-	if ((ReportLnfoLen > 0) && (pReportInfo != NULL))
-	{
-		MakeOutgoingFrame(pFrameBuf + *pFrameLen,		&TempLen,
-							ReportLnfoLen,				pReportInfo,
-							END_OF_ARGS);
-
-		*pFrameLen = *pFrameLen + TempLen;
-	}
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Prepare Measurement request action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueMeasurementReq(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 MeasureToken,
-	IN UINT8 MeasureReqMode,
-	IN UINT8 MeasureReqType,
-	IN UINT8 MeasureCh,
-	IN UINT16 MeasureDuration)
-{
-	PUCHAR pOutBuffer = NULL;
-	NDIS_STATUS NStatus;
-	ULONG FrameLen;
-	HEADER_802_11 ActHdr;
-	MEASURE_REQ_INFO MeasureReqIE;
-	UINT8 RmReqDailogToken = RandomByte(pAd);
-	UINT64 MeasureStartTime = GetCurrentTimeStamp(pAd);
-
-	// build action frame header.
-	MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
-						pAd->CurrentAddress);
-
-	NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __func__));
-		return;
-	}
-	NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
-	FrameLen = sizeof(HEADER_802_11);
-
-	InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_MRQ);
-
-	// fill Dialog Token
-	InsertDialogToken(pAd, (pOutBuffer + FrameLen), &FrameLen, MeasureToken);
-
-	// prepare Measurement IE.
-	NdisZeroMemory(&MeasureReqIE, sizeof(MEASURE_REQ_INFO));
-	MeasureReqIE.Token = RmReqDailogToken;
-	MeasureReqIE.ReqMode.word = MeasureReqMode;
-	MeasureReqIE.ReqType = MeasureReqType;
-	MeasureReqIE.MeasureReq.ChNum = MeasureCh;
-	MeasureReqIE.MeasureReq.MeasureStartTime = cpu2le64(MeasureStartTime);
-	MeasureReqIE.MeasureReq.MeasureDuration = cpu2le16(MeasureDuration);
-	InsertMeasureReqIE(pAd, (pOutBuffer + FrameLen), &FrameLen, &MeasureReqIE);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Prepare Measurement report action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueMeasurementRep(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 DialogToken,
-	IN UINT8 MeasureToken,
-	IN UINT8 MeasureReqMode,
-	IN UINT8 MeasureReqType,
-	IN UINT8 ReportInfoLen,
-	IN PUINT8 pReportInfo)
-{
-	PUCHAR pOutBuffer = NULL;
-	NDIS_STATUS NStatus;
-	ULONG FrameLen;
-	HEADER_802_11 ActHdr;
-	MEASURE_REPORT_INFO MeasureRepIE;
-
-	// build action frame header.
-	MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
-						pAd->CurrentAddress);
-
-	NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __func__));
-		return;
-	}
-	NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
-	FrameLen = sizeof(HEADER_802_11);
-
-	InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_MRP);
-
-	// fill Dialog Token
-	InsertDialogToken(pAd, (pOutBuffer + FrameLen), &FrameLen, DialogToken);
-
-	// prepare Measurement IE.
-	NdisZeroMemory(&MeasureRepIE, sizeof(MEASURE_REPORT_INFO));
-	MeasureRepIE.Token = MeasureToken;
-	MeasureRepIE.ReportMode.word = MeasureReqMode;
-	MeasureRepIE.ReportType = MeasureReqType;
-	InsertMeasureReportIE(pAd, (pOutBuffer + FrameLen), &FrameLen, &MeasureRepIE, ReportInfoLen, pReportInfo);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Prepare TPC Request action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueTPCReq(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UCHAR DialogToken)
-{
-	PUCHAR pOutBuffer = NULL;
-	NDIS_STATUS NStatus;
-	ULONG FrameLen;
-
-	HEADER_802_11 ActHdr;
-
-	// build action frame header.
-	MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
-						pAd->CurrentAddress);
-
-	NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __func__));
-		return;
-	}
-	NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
-	FrameLen = sizeof(HEADER_802_11);
-
-	InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_TPCRQ);
-
-	// fill Dialog Token
-	InsertDialogToken(pAd, (pOutBuffer + FrameLen), &FrameLen, DialogToken);
-
-	// Insert TPC Request IE.
-	InsertTpcReqIE(pAd, (pOutBuffer + FrameLen), &FrameLen);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Prepare TPC Report action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueTPCRep(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 DialogToken,
-	IN UINT8 TxPwr,
-	IN UINT8 LinkMargin)
-{
-	PUCHAR pOutBuffer = NULL;
-	NDIS_STATUS NStatus;
-	ULONG FrameLen;
-
-	HEADER_802_11 ActHdr;
-
-	// build action frame header.
-	MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
-						pAd->CurrentAddress);
-
-	NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __func__));
-		return;
-	}
-	NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
-	FrameLen = sizeof(HEADER_802_11);
-
-	InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_TPCRP);
-
-	// fill Dialog Token
-	InsertDialogToken(pAd, (pOutBuffer + FrameLen), &FrameLen, DialogToken);
-
-	// Insert TPC Request IE.
-	InsertTpcReportIE(pAd, (pOutBuffer + FrameLen), &FrameLen, TxPwr, LinkMargin);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Prepare Channel Switch Announcement action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-		2. Channel switch announcement mode.
-		2. a New selected channel.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueChSwAnn(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 ChSwMode,
-	IN UINT8 NewCh)
-{
-	PUCHAR pOutBuffer = NULL;
-	NDIS_STATUS NStatus;
-	ULONG FrameLen;
-
-	HEADER_802_11 ActHdr;
-
-	// build action frame header.
-	MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
-						pAd->CurrentAddress);
-
-	NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __func__));
-		return;
-	}
-	NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
-	FrameLen = sizeof(HEADER_802_11);
-
-	InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_CHANNEL_SWITCH);
-
-	InsertChSwAnnIE(pAd, (pOutBuffer + FrameLen), &FrameLen, ChSwMode, NewCh, 0);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	return;
-}
-
-static BOOLEAN DfsRequirementCheck(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT8 Channel)
-{
-	BOOLEAN Result = FALSE;
-	INT i;
-
-	do
-	{
-		// check DFS procedure is running.
-		// make sure DFS procedure won't start twice.
-		if (pAd->CommonCfg.RadarDetect.RDMode != RD_NORMAL_MODE)
-		{
-			Result = FALSE;
-			break;
-		}
-
-		// check the new channel carried from Channel Switch Announcemnet is valid.
-		for (i=0; i<pAd->ChannelListNum; i++)
-		{
-			if ((Channel == pAd->ChannelList[i].Channel)
-				&&(pAd->ChannelList[i].RemainingTimeForUse == 0))
-			{
-				// found radar signal in the channel. the channel can't use at least for 30 minutes.
-				pAd->ChannelList[i].RemainingTimeForUse = 1800;//30 min = 1800 sec
-				Result = TRUE;
-				break;
-			}
-		}
-	} while(FALSE);
-
-	return Result;
-}
-
-VOID NotifyChSwAnnToPeerAPs(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pRA,
-	IN PUCHAR pTA,
-	IN UINT8 ChSwMode,
-	IN UINT8 Channel)
-{
-#ifdef WDS_SUPPORT
-	if (!((pRA[0] & 0xff) == 0xff)) // is pRA a broadcase address.
-	{
-		INT i;
-		// info neighbor APs that Radar signal found throgh WDS link.
-		for (i = 0; i < MAX_WDS_ENTRY; i++)
-		{
-			if (ValidWdsEntry(pAd, i))
-			{
-				PUCHAR pDA = pAd->WdsTab.WdsEntry[i].PeerWdsAddr;
-
-				// DA equal to SA. have no necessary orignal AP which found Radar signal.
-				if (MAC_ADDR_EQUAL(pTA, pDA))
-					continue;
-
-				// send Channel Switch Action frame to info Neighbro APs.
-				EnqueueChSwAnn(pAd, pDA, ChSwMode, Channel);
-			}
-		}
-	}
-#endif // WDS_SUPPORT //
-}
-
-static VOID StartDFSProcedure(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR Channel,
-	IN UINT8 ChSwMode)
-{
-	// start DFS procedure
-	pAd->CommonCfg.Channel = Channel;
-#ifdef DOT11_N_SUPPORT
-	N_ChannelCheck(pAd);
-#endif // DOT11_N_SUPPORT //
-	pAd->CommonCfg.RadarDetect.RDMode = RD_SWITCHING_MODE;
-	pAd->CommonCfg.RadarDetect.CSCount = 0;
-}
-
-/*
-	==========================================================================
-	Description:
-		Channel Switch Announcement action frame sanity check.
-
-	Parametrs:
-		1. MLME message containing the received frame
-		2. message length.
-		3. Channel switch announcement infomation buffer.
-
-
-	Return	: None.
-	==========================================================================
- */
-
-/*
-  Channel Switch Announcement IE.
-  +----+-----+-----------+------------+-----------+
-  | ID | Len |Ch Sw Mode | New Ch Num | Ch Sw Cnt |
-  +----+-----+-----------+------------+-----------+
-    1    1        1           1            1
-*/
-static BOOLEAN PeerChSwAnnSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *pMsg,
-	IN ULONG MsgLen,
-	OUT PCH_SW_ANN_INFO pChSwAnnInfo)
-{
-	PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
-	PUCHAR pFramePtr = Fr->Octet;
-	BOOLEAN result = FALSE;
-	PEID_STRUCT eid_ptr;
-
-	// skip 802.11 header.
-	MsgLen -= sizeof(HEADER_802_11);
-
-	// skip category and action code.
-	pFramePtr += 2;
-	MsgLen -= 2;
-
-	if (pChSwAnnInfo == NULL)
-		return result;
-
-	eid_ptr = (PEID_STRUCT)pFramePtr;
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_CHANNEL_SWITCH_ANNOUNCEMENT:
-				NdisMoveMemory(&pChSwAnnInfo->ChSwMode, eid_ptr->Octet, 1);
-				NdisMoveMemory(&pChSwAnnInfo->Channel, eid_ptr->Octet + 1, 1);
-				NdisMoveMemory(&pChSwAnnInfo->ChSwCnt, eid_ptr->Octet + 2, 1);
-
-				result = TRUE;
-                break;
-
-			default:
-				break;
-		}
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-	return result;
-}
-
-/*
-	==========================================================================
-	Description:
-		Measurement request action frame sanity check.
-
-	Parametrs:
-		1. MLME message containing the received frame
-		2. message length.
-		3. Measurement request infomation buffer.
-
-	Return	: None.
-	==========================================================================
- */
-static BOOLEAN PeerMeasureReqSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *pMsg,
-	IN ULONG MsgLen,
-	OUT PUINT8 pDialogToken,
-	OUT PMEASURE_REQ_INFO pMeasureReqInfo)
-{
-	PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
-	PUCHAR pFramePtr = Fr->Octet;
-	BOOLEAN result = FALSE;
-	PEID_STRUCT eid_ptr;
-	PUCHAR ptr;
-	UINT64 MeasureStartTime;
-	UINT16 MeasureDuration;
-
-	// skip 802.11 header.
-	MsgLen -= sizeof(HEADER_802_11);
-
-	// skip category and action code.
-	pFramePtr += 2;
-	MsgLen -= 2;
-
-	if (pMeasureReqInfo == NULL)
-		return result;
-
-	NdisMoveMemory(pDialogToken, pFramePtr, 1);
-	pFramePtr += 1;
-	MsgLen -= 1;
-
-	eid_ptr = (PEID_STRUCT)pFramePtr;
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_MEASUREMENT_REQUEST:
-				NdisMoveMemory(&pMeasureReqInfo->Token, eid_ptr->Octet, 1);
-				NdisMoveMemory(&pMeasureReqInfo->ReqMode.word, eid_ptr->Octet + 1, 1);
-				NdisMoveMemory(&pMeasureReqInfo->ReqType, eid_ptr->Octet + 2, 1);
-				ptr = eid_ptr->Octet + 3;
-				NdisMoveMemory(&pMeasureReqInfo->MeasureReq.ChNum, ptr, 1);
-				NdisMoveMemory(&MeasureStartTime, ptr + 1, 8);
-				pMeasureReqInfo->MeasureReq.MeasureStartTime = SWAP64(MeasureStartTime);
-				NdisMoveMemory(&MeasureDuration, ptr + 9, 2);
-				pMeasureReqInfo->MeasureReq.MeasureDuration = SWAP16(MeasureDuration);
-
-				result = TRUE;
-				break;
-
-			default:
-				break;
-		}
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-	return result;
-}
-
-/*
-	==========================================================================
-	Description:
-		Measurement report action frame sanity check.
-
-	Parametrs:
-		1. MLME message containing the received frame
-		2. message length.
-		3. Measurement report infomation buffer.
-		4. basic report infomation buffer.
-
-	Return	: None.
-	==========================================================================
- */
-
-/*
-  Measurement Report IE.
-  +----+-----+-------+-------------+--------------+----------------+
-  | ID | Len | Token | Report Mode | Measure Type | Measure Report |
-  +----+-----+-------+-------------+--------------+----------------+
-    1     1      1          1             1            variable
-
-  Basic Report.
-  +--------+------------+----------+-----+
-  | Ch Num | Start Time | Duration | Map |
-  +--------+------------+----------+-----+
-      1          8           2        1
-
-  Map Field Bit Format.
-  +-----+---------------+---------------------+-------+------------+----------+
-  | Bss | OFDM Preamble | Unidentified signal | Radar | Unmeasured | Reserved |
-  +-----+---------------+---------------------+-------+------------+----------+
-     0          1                  2              3         4          5-7
-*/
-static BOOLEAN PeerMeasureReportSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *pMsg,
-	IN ULONG MsgLen,
-	OUT PUINT8 pDialogToken,
-	OUT PMEASURE_REPORT_INFO pMeasureReportInfo,
-	OUT PUINT8 pReportBuf)
-{
-	PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
-	PUCHAR pFramePtr = Fr->Octet;
-	BOOLEAN result = FALSE;
-	PEID_STRUCT eid_ptr;
-	PUCHAR ptr;
-
-	// skip 802.11 header.
-	MsgLen -= sizeof(HEADER_802_11);
-
-	// skip category and action code.
-	pFramePtr += 2;
-	MsgLen -= 2;
-
-	if (pMeasureReportInfo == NULL)
-		return result;
-
-	NdisMoveMemory(pDialogToken, pFramePtr, 1);
-	pFramePtr += 1;
-	MsgLen -= 1;
-
-	eid_ptr = (PEID_STRUCT)pFramePtr;
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_MEASUREMENT_REPORT:
-				NdisMoveMemory(&pMeasureReportInfo->Token, eid_ptr->Octet, 1);
-				NdisMoveMemory(&pMeasureReportInfo->ReportMode, eid_ptr->Octet + 1, 1);
-				NdisMoveMemory(&pMeasureReportInfo->ReportType, eid_ptr->Octet + 2, 1);
-				if (pMeasureReportInfo->ReportType == RM_BASIC)
-				{
-					PMEASURE_BASIC_REPORT pReport = (PMEASURE_BASIC_REPORT)pReportBuf;
-					ptr = eid_ptr->Octet + 3;
-					NdisMoveMemory(&pReport->ChNum, ptr, 1);
-					NdisMoveMemory(&pReport->MeasureStartTime, ptr + 1, 8);
-					NdisMoveMemory(&pReport->MeasureDuration, ptr + 9, 2);
-					NdisMoveMemory(&pReport->Map, ptr + 11, 1);
-
-				}
-				else if (pMeasureReportInfo->ReportType == RM_CCA)
-				{
-					PMEASURE_CCA_REPORT pReport = (PMEASURE_CCA_REPORT)pReportBuf;
-					ptr = eid_ptr->Octet + 3;
-					NdisMoveMemory(&pReport->ChNum, ptr, 1);
-					NdisMoveMemory(&pReport->MeasureStartTime, ptr + 1, 8);
-					NdisMoveMemory(&pReport->MeasureDuration, ptr + 9, 2);
-					NdisMoveMemory(&pReport->CCA_Busy_Fraction, ptr + 11, 1);
-
-				}
-				else if (pMeasureReportInfo->ReportType == RM_RPI_HISTOGRAM)
-				{
-					PMEASURE_RPI_REPORT pReport = (PMEASURE_RPI_REPORT)pReportBuf;
-					ptr = eid_ptr->Octet + 3;
-					NdisMoveMemory(&pReport->ChNum, ptr, 1);
-					NdisMoveMemory(&pReport->MeasureStartTime, ptr + 1, 8);
-					NdisMoveMemory(&pReport->MeasureDuration, ptr + 9, 2);
-					NdisMoveMemory(&pReport->RPI_Density, ptr + 11, 8);
-				}
-				result = TRUE;
-                break;
-
-			default:
-				break;
-		}
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-	return result;
-}
-
-/*
-	==========================================================================
-	Description:
-		TPC Request action frame sanity check.
-
-	Parametrs:
-		1. MLME message containing the received frame
-		2. message length.
-		3. Dialog Token.
-
-	Return	: None.
-	==========================================================================
- */
-static BOOLEAN PeerTpcReqSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *pMsg,
-	IN ULONG MsgLen,
-	OUT PUINT8 pDialogToken)
-{
-	PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
-	PUCHAR pFramePtr = Fr->Octet;
-	BOOLEAN result = FALSE;
-	PEID_STRUCT eid_ptr;
-
-	MsgLen -= sizeof(HEADER_802_11);
-
-	// skip category and action code.
-	pFramePtr += 2;
-	MsgLen -= 2;
-
-	if (pDialogToken == NULL)
-		return result;
-
-	NdisMoveMemory(pDialogToken, pFramePtr, 1);
-	pFramePtr += 1;
-	MsgLen -= 1;
-
-	eid_ptr = (PEID_STRUCT)pFramePtr;
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_TPC_REQUEST:
-				result = TRUE;
-                break;
-
-			default:
-				break;
-		}
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-	return result;
-}
-
-/*
-	==========================================================================
-	Description:
-		TPC Report action frame sanity check.
-
-	Parametrs:
-		1. MLME message containing the received frame
-		2. message length.
-		3. Dialog Token.
-		4. TPC Report IE.
-
-	Return	: None.
-	==========================================================================
- */
-static BOOLEAN PeerTpcRepSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *pMsg,
-	IN ULONG MsgLen,
-	OUT PUINT8 pDialogToken,
-	OUT PTPC_REPORT_INFO pTpcRepInfo)
-{
-	PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
-	PUCHAR pFramePtr = Fr->Octet;
-	BOOLEAN result = FALSE;
-	PEID_STRUCT eid_ptr;
-
-	MsgLen -= sizeof(HEADER_802_11);
-
-	// skip category and action code.
-	pFramePtr += 2;
-	MsgLen -= 2;
-
-	if (pDialogToken == NULL)
-		return result;
-
-	NdisMoveMemory(pDialogToken, pFramePtr, 1);
-	pFramePtr += 1;
-	MsgLen -= 1;
-
-	eid_ptr = (PEID_STRUCT)pFramePtr;
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_TPC_REPORT:
-				NdisMoveMemory(&pTpcRepInfo->TxPwr, eid_ptr->Octet, 1);
-				NdisMoveMemory(&pTpcRepInfo->LinkMargin, eid_ptr->Octet + 1, 1);
-				result = TRUE;
-                break;
-
-			default:
-				break;
-		}
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-	return result;
-}
-
-/*
-	==========================================================================
-	Description:
-		Channel Switch Announcement action frame handler.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-static VOID PeerChSwAnnAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	CH_SW_ANN_INFO ChSwAnnInfo;
-	PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
-#ifdef CONFIG_STA_SUPPORT
-	UCHAR index = 0, Channel = 0, NewChannel = 0;
-	ULONG Bssidx = 0;
-#endif // CONFIG_STA_SUPPORT //
-
-	NdisZeroMemory(&ChSwAnnInfo, sizeof(CH_SW_ANN_INFO));
-	if (! PeerChSwAnnSanity(pAd, Elem->Msg, Elem->MsgLen, &ChSwAnnInfo))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("Invalid Channel Switch Action Frame.\n"));
-		return;
-	}
-
-
-#ifdef CONFIG_STA_SUPPORT
-	if (pAd->OpMode == OPMODE_STA)
-	{
-		Bssidx = BssTableSearch(&pAd->ScanTab, pFr->Hdr.Addr3, pAd->CommonCfg.Channel);
-		if (Bssidx == BSS_NOT_FOUND)
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("PeerChSwAnnAction - Bssidx is not found\n"));
-			return;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("\n****Bssidx is %d, Channel = %d\n", index, pAd->ScanTab.BssEntry[Bssidx].Channel));
-		hex_dump("SSID",pAd->ScanTab.BssEntry[Bssidx].Bssid ,6);
-
-		Channel = pAd->CommonCfg.Channel;
-		NewChannel = ChSwAnnInfo.Channel;
-
-		if ((pAd->CommonCfg.bIEEE80211H == 1) && (NewChannel != 0) && (Channel != NewChannel))
-		{
-			// Switching to channel 1 can prevent from rescanning the current channel immediately (by auto reconnection).
-			// In addition, clear the MLME queue and the scan table to discard the RX packets and previous scanning results.
-			AsicSwitchChannel(pAd, 1, FALSE);
-			AsicLockChannel(pAd, 1);
-		    LinkDown(pAd, FALSE);
-			MlmeQueueInit(&pAd->Mlme.Queue);
-			BssTableInit(&pAd->ScanTab);
-		    RTMPusecDelay(1000000);		// use delay to prevent STA do reassoc
-
-			// channel sanity check
-			for (index = 0 ; index < pAd->ChannelListNum; index++)
-			{
-				if (pAd->ChannelList[index].Channel == NewChannel)
-				{
-					pAd->ScanTab.BssEntry[Bssidx].Channel = NewChannel;
-					pAd->CommonCfg.Channel = NewChannel;
-					AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-					AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-					DBGPRINT(RT_DEBUG_TRACE, ("&&&&&&&&&&&&&&&&PeerChSwAnnAction - STA receive channel switch announcement IE (New Channel =%d)\n", NewChannel));
-					break;
-				}
-			}
-
-			if (index >= pAd->ChannelListNum)
-			{
-				DBGPRINT_ERR(("&&&&&&&&&&&&&&&&&&&&&&&&&&PeerChSwAnnAction(can not find New Channel=%d in ChannelList[%d]\n", pAd->CommonCfg.Channel, pAd->ChannelListNum));
-			}
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	return;
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Measurement Request action frame handler.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-static VOID PeerMeasureReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
-	UINT8 DialogToken;
-	MEASURE_REQ_INFO MeasureReqInfo;
-	MEASURE_REPORT_MODE ReportMode;
-
-	if(PeerMeasureReqSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken, &MeasureReqInfo))
-	{
-		ReportMode.word = 0;
-		ReportMode.field.Incapable = 1;
-		EnqueueMeasurementRep(pAd, pFr->Hdr.Addr2, DialogToken, MeasureReqInfo.Token, ReportMode.word, MeasureReqInfo.ReqType, 0, NULL);
-	}
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Measurement Report action frame handler.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-static VOID PeerMeasureReportAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	MEASURE_REPORT_INFO MeasureReportInfo;
-	PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
-	UINT8 DialogToken;
-	PUINT8 pMeasureReportInfo;
-
-//	if (pAd->CommonCfg.bIEEE80211H != TRUE)
-//		return;
-
-	if ((pMeasureReportInfo = kmalloc(sizeof(MEASURE_RPI_REPORT), GFP_ATOMIC)) == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s unable to alloc memory for measure report buffer (size=%zu).\n", __func__, sizeof(MEASURE_RPI_REPORT)));
-		return;
-	}
-
-	NdisZeroMemory(&MeasureReportInfo, sizeof(MEASURE_REPORT_INFO));
-	NdisZeroMemory(pMeasureReportInfo, sizeof(MEASURE_RPI_REPORT));
-	if (PeerMeasureReportSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken, &MeasureReportInfo, pMeasureReportInfo))
-	{
-		do {
-			PMEASURE_REQ_ENTRY pEntry = NULL;
-
-			// Not a autonomous measure report.
-			// check the dialog token field. drop it if the dialog token doesn't match.
-			if ((DialogToken != 0)
-				&& ((pEntry = MeasureReqLookUp(pAd, DialogToken)) == NULL))
-				break;
-
-			if (pEntry != NULL)
-				MeasureReqDelete(pAd, pEntry->DialogToken);
-
-			if (MeasureReportInfo.ReportType == RM_BASIC)
-			{
-				PMEASURE_BASIC_REPORT pBasicReport = (PMEASURE_BASIC_REPORT)pMeasureReportInfo;
-				if ((pBasicReport->Map.field.Radar)
-					&& (DfsRequirementCheck(pAd, pBasicReport->ChNum) == TRUE))
-				{
-					NotifyChSwAnnToPeerAPs(pAd, pFr->Hdr.Addr1, pFr->Hdr.Addr2, 1, pBasicReport->ChNum);
-					StartDFSProcedure(pAd, pBasicReport->ChNum, 1);
-				}
-			}
-		} while (FALSE);
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, ("Invalid Measurement Report Frame.\n"));
-
-	kfree(pMeasureReportInfo);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		TPC Request action frame handler.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-static VOID PeerTpcReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
-	PUCHAR pFramePtr = pFr->Octet;
-	UINT8 DialogToken;
-	UINT8 TxPwr = GetCurTxPwr(pAd, Elem->Wcid);
-	UINT8 LinkMargin = 0;
-	CHAR RealRssi;
-
-	// link margin: Ratio of the received signal power to the minimum desired by the station (STA). The
-	//				STA may incorporate rate information and channel conditions, including interference, into its computation
-	//				of link margin.
-
-	RealRssi = RTMPMaxRssi(pAd, ConvertToRssi(pAd, Elem->Rssi0, RSSI_0),
-								ConvertToRssi(pAd, Elem->Rssi1, RSSI_1),
-								ConvertToRssi(pAd, Elem->Rssi2, RSSI_2));
-
-	// skip Category and action code.
-	pFramePtr += 2;
-
-	// Dialog token.
-	NdisMoveMemory(&DialogToken, pFramePtr, 1);
-
-	LinkMargin = (RealRssi / MIN_RCV_PWR);
-	if (PeerTpcReqSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken))
-		EnqueueTPCRep(pAd, pFr->Hdr.Addr2, DialogToken, TxPwr, LinkMargin);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		TPC Report action frame handler.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-static VOID PeerTpcRepAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UINT8 DialogToken;
-	TPC_REPORT_INFO TpcRepInfo;
-	PTPC_REQ_ENTRY pEntry = NULL;
-
-	NdisZeroMemory(&TpcRepInfo, sizeof(TPC_REPORT_INFO));
-	if (PeerTpcRepSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken, &TpcRepInfo))
-	{
-		if ((pEntry = TpcReqLookUp(pAd, DialogToken)) != NULL)
-		{
-			TpcReqDelete(pAd, pEntry->DialogToken);
-			DBGPRINT(RT_DEBUG_TRACE, ("%s: DialogToken=%x, TxPwr=%d, LinkMargin=%d\n",
-				__func__, DialogToken, TpcRepInfo.TxPwr, TpcRepInfo.LinkMargin));
-		}
-	}
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Spectrun action frames Handler such as channel switch annoucement,
-		measurement report, measurement request actions frames.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-VOID PeerSpectrumAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-
-	if (pAd->CommonCfg.bIEEE80211H != TRUE)
-		return;
-
-	switch(Action)
-	{
-		case SPEC_MRQ:
-			// current rt2860 unable do such measure specified in Measurement Request.
-			// reject all measurement request.
-			PeerMeasureReqAction(pAd, Elem);
-			break;
-
-		case SPEC_MRP:
-			PeerMeasureReportAction(pAd, Elem);
-			break;
-
-		case SPEC_TPCRQ:
-			PeerTpcReqAction(pAd, Elem);
-			break;
-
-		case SPEC_TPCRP:
-			PeerTpcRepAction(pAd, Elem);
-			break;
-
-		case SPEC_CHANNEL_SWITCH:
-{
-#ifdef DOT11N_DRAFT3
-				SEC_CHA_OFFSET_IE	Secondary;
-				CHA_SWITCH_ANNOUNCE_IE	ChannelSwitch;
-
-				// 802.11h only has Channel Switch Announcement IE.
-				RTMPMoveMemory(&ChannelSwitch, &Elem->Msg[LENGTH_802_11+4], sizeof (CHA_SWITCH_ANNOUNCE_IE));
-
-				// 802.11n D3.03 adds secondary channel offset element in the end.
-				if (Elem->MsgLen ==  (LENGTH_802_11 + 2 + sizeof (CHA_SWITCH_ANNOUNCE_IE) + sizeof (SEC_CHA_OFFSET_IE)))
-				{
-					RTMPMoveMemory(&Secondary, &Elem->Msg[LENGTH_802_11+9], sizeof (SEC_CHA_OFFSET_IE));
-				}
-				else
-				{
-					Secondary.SecondaryChannelOffset = 0;
-				}
-
-				if ((Elem->Msg[LENGTH_802_11+2] == IE_CHANNEL_SWITCH_ANNOUNCEMENT) && (Elem->Msg[LENGTH_802_11+3] == 3))
-				{
-					ChannelSwitchAction(pAd, Elem->Wcid, ChannelSwitch.NewChannel, Secondary.SecondaryChannelOffset);
-				}
-#endif // DOT11N_DRAFT3 //
-}
-			PeerChSwAnnAction(pAd, Elem);
-			break;
-	}
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	Parametrs:
-
-	Return	: None.
-	==========================================================================
- */
-INT Set_MeasureReq_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT Aid = 1;
-	UINT ArgIdx;
-	PUCHAR thisChar;
-
-	MEASURE_REQ_MODE MeasureReqMode;
-	UINT8 MeasureReqToken = RandomByte(pAd);
-	UINT8 MeasureReqType = RM_BASIC;
-	UINT8 MeasureCh = 1;
-
-	ArgIdx = 1;
-	while ((thisChar = strsep((char **)&arg, "-")) != NULL)
-	{
-		switch(ArgIdx)
-		{
-			case 1:	// Aid.
-				Aid = simple_strtol(thisChar, 0, 16);
-				break;
-
-			case 2: // Measurement Request Type.
-				MeasureReqType = simple_strtol(thisChar, 0, 16);
-				if (MeasureReqType > 3)
-				{
-					DBGPRINT(RT_DEBUG_ERROR, ("%s: unknow MeasureReqType(%d)\n", __func__, MeasureReqType));
-					return TRUE;
-				}
-				break;
-
-			case 3: // Measurement channel.
-				MeasureCh = simple_strtol(thisChar, 0, 16);
-				break;
-		}
-		ArgIdx++;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s::Aid = %d, MeasureReqType=%d MeasureCh=%d\n", __func__, Aid, MeasureReqType, MeasureCh));
-	if (!VALID_WCID(Aid))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: unknow sta of Aid(%d)\n", __func__, Aid));
-		return TRUE;
-	}
-
-	MeasureReqMode.word = 0;
-	MeasureReqMode.field.Enable = 1;
-
-	MeasureReqInsert(pAd, MeasureReqToken);
-
-	EnqueueMeasurementReq(pAd, pAd->MacTab.Content[Aid].Addr,
-		MeasureReqToken, MeasureReqMode.word, MeasureReqType, MeasureCh, 2000);
-
-	return TRUE;
-}
-
-INT Set_TpcReq_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT Aid;
-
-	UINT8 TpcReqToken = RandomByte(pAd);
-
-	Aid = simple_strtol(arg, 0, 16);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s::Aid = %d\n", __func__, Aid));
-	if (!VALID_WCID(Aid))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: unknow sta of Aid(%d)\n", __func__, Aid));
-		return TRUE;
-	}
-
-	TpcReqInsert(pAd, TpcReqToken);
-
-	EnqueueTPCReq(pAd, pAd->MacTab.Content[Aid].Addr, TpcReqToken);
-
-	return TRUE;
-}
-
+#include "../../rt2860/common/spectrum.c"
diff --git a/drivers/staging/rt2870/dfs.h b/drivers/staging/rt2870/dfs.h
index 752a635..1fdbd7b 100644
--- a/drivers/staging/rt2870/dfs.h
+++ b/drivers/staging/rt2870/dfs.h
@@ -1,100 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    dfs.h
-
-    Abstract:
-    Support DFS function.
-
-    Revision History:
-    Who       When            What
-    --------  ----------      ----------------------------------------------
-    Fonchi    03-12-2007      created
-*/
-
-#define RADAR_PULSE 1
-#define RADAR_WIDTH 2
-
-#define WIDTH_RD_IDLE 0
-#define WIDTH_RD_CHECK 1
-
-
-VOID BbpRadarDetectionStart(
-	IN PRTMP_ADAPTER pAd);
-
-VOID BbpRadarDetectionStop(
-	IN PRTMP_ADAPTER pAd);
-
-VOID RadarDetectionStart(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN CTS_Protect,
-	IN UINT8 CTSPeriod);
-
-VOID RadarDetectionStop(
-	IN PRTMP_ADAPTER	pAd);
-
-VOID RadarDetectPeriodic(
-	IN PRTMP_ADAPTER	pAd);
-
-
-BOOLEAN RadarChannelCheck(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			Ch);
-
-ULONG JapRadarType(
-	IN PRTMP_ADAPTER pAd);
-
-ULONG RTMPBbpReadRadarDuration(
-	IN PRTMP_ADAPTER	pAd);
-
-ULONG RTMPReadRadarDuration(
-	IN PRTMP_ADAPTER	pAd);
-
-VOID RTMPCleanRadarDuration(
-	IN PRTMP_ADAPTER	pAd);
-
-VOID RTMPPrepareRDCTSFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA,
-	IN	ULONG			Duration,
-	IN  UCHAR           RTSRate,
-	IN  ULONG           CTSBaseAddr,
-	IN  UCHAR			FrameGap);
-
-VOID RTMPPrepareRadarDetectParams(
-	IN PRTMP_ADAPTER	pAd);
-
-
-INT Set_ChMovingTime_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg);
-
-INT Set_LongPulseRadarTh_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg);
-
-
+#include "../rt2860/dfs.h"
diff --git a/drivers/staging/rt2870/leap.h b/drivers/staging/rt2870/leap.h
deleted file mode 100644
index 6818c1f..0000000
--- a/drivers/staging/rt2870/leap.h
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	leap.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-*/
-#ifndef __LEAP_H__
-#define __LEAP_H__
-
-// Messages for Associate state machine
-#define LEAP_MACHINE_BASE                   30
-
-#define LEAP_MSG_REQUEST_IDENTITY           31
-#define LEAP_MSG_REQUEST_LEAP               32
-#define LEAP_MSG_SUCCESS                    33
-#define LEAP_MSG_FAILED                     34
-#define LEAP_MSG_RESPONSE_LEAP              35
-#define LEAP_MSG_EAPOLKEY                   36
-#define LEAP_MSG_UNKNOWN                    37
-#define LEAP_MSG                            38
-//! assoc state-machine states
-#define LEAP_IDLE                           0
-#define LEAP_WAIT_IDENTITY_REQUEST          1
-#define LEAP_WAIT_CHANLLENGE_REQUEST        2
-#define LEAP_WAIT_SUCCESS                   3
-#define LEAP_WAIT_CHANLLENGE_RESPONSE       4
-#define LEAP_WAIT_EAPOLKEY                  5
-
-#define LEAP_REASON_INVALID_AUTH                    0x01
-#define LEAP_REASON_AUTH_TIMEOUT                    0x02
-#define LEAP_REASON_CHALLENGE_FROM_AP_FAILED        0x03
-#define LEAP_REASON_CHALLENGE_TO_AP_FAILED          0x04
-
-#define CISCO_AuthModeLEAP                          0x80
-#define CISCO_AuthModeLEAPNone                      0x00
-#define LEAP_AUTH_TIMEOUT                           30000
-#define LEAP_CHALLENGE_RESPONSE_LENGTH              24
-#define LEAP_CHALLENGE_REQUEST_LENGTH               8
-
-typedef struct _LEAP_EAPOL_HEADER_ {
-    UCHAR       Version;
-    UCHAR       Type;
-    UCHAR       Length[2];
-} LEAP_EAPOL_HEADER, *PLEAP_EAPOL_HEADER;
-
-typedef struct _LEAP_EAPOL_PACKET_ {
-    UCHAR       Code;
-    UCHAR       Identifier;
-    UCHAR       Length[2];
-    UCHAR       Type;
-} LEAP_EAPOL_PACKET, *PLEAP_EAPOL_PACKET;
-
-typedef struct _LEAP_EAP_CONTENTS_ {
-    UCHAR       Version;
-    UCHAR       Reserved;
-    UCHAR       Length;
-} LEAP_EAP_CONTENTS, *PLEAP_EAP_CONTENTS;
-
-/*** EAPOL key ***/
-typedef struct _EAPOL_KEY_HEADER_ {
-    UCHAR       Type;
-    UCHAR       Length[2];
-    UCHAR       Counter[8];
-    UCHAR       IV[16];
-    UCHAR       Index;
-    UCHAR       Signature[16];
-} EAPOL_KEY_HEADER, *PEAPOL_KEY_HEADER;
-
-BOOLEAN LeapMsgTypeSubst(
-    IN  UCHAR   EAPType,
-    OUT ULONG   *MsgType);
-
-VOID LeapMachinePerformAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN STATE_MACHINE    *S,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapMacHeaderInit(
-    IN  PRTMP_ADAPTER       pAd,
-    IN  OUT PHEADER_802_11  pHdr80211,
-    IN  UCHAR               wep,
-    IN  PUCHAR              pAddr3);
-
-VOID LeapStartAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapIdentityAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapPeerChallengeAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID HashPwd(
-    IN  PUCHAR  pwd,
-    IN  INT     pwdlen,
-    OUT PUCHAR  hash);
-
-VOID PeerChallengeResponse(
-    IN  PUCHAR  szChallenge,
-    IN  PUCHAR  smbPasswd,
-    OUT PUCHAR  szResponse);
-
-VOID ParityKey(
-    OUT PUCHAR  szOut,
-    IN  PUCHAR  szIn);
-
-VOID DesKey(
-    OUT ULONG   k[16][2],
-    IN  PUCHAR  key,
-    IN  INT     decrypt);
-
-VOID Des(
-    IN  ULONG   ks[16][2],
-    OUT UCHAR   block[8]);
-
-VOID DesEncrypt(
-    IN  PUCHAR  szClear,
-    IN  PUCHAR  szKey,
-    OUT PUCHAR  szOut);
-
-VOID LeapNetworkChallengeAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapNetworkChallengeResponse(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID HashpwdHash(
-    IN  PUCHAR  hash,
-    IN  PUCHAR  hashhash);
-
-VOID ProcessSessionKey(
-    OUT PUCHAR  SessionKey,
-    IN  PUCHAR  hash2,
-    IN  PUCHAR  ChallengeToRadius,
-    IN  PUCHAR  ChallengeResponseFromRadius,
-    IN  PUCHAR  ChallengeFromRadius,
-    IN  PUCHAR  ChallengeResponseToRadius);
-
-VOID LeapEapolKeyAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID RogueApTableInit(
-    IN ROGUEAP_TABLE    *Tab);
-
-ULONG RogueApTableSearch(
-    IN ROGUEAP_TABLE    *Tab,
-    IN PUCHAR           pAddr);
-
-VOID RogueApEntrySet(
-    IN  PRTMP_ADAPTER   pAd,
-    OUT ROGUEAP_ENTRY   *pRogueAp,
-    IN PUCHAR           pAddr,
-    IN UCHAR            FaileCode);
-
-ULONG RogueApTableSetEntry(
-    IN  PRTMP_ADAPTER   pAd,
-    OUT ROGUEAP_TABLE  *Tab,
-    IN PUCHAR           pAddr,
-    IN UCHAR            FaileCode);
-
-VOID RogueApTableDeleteEntry(
-    IN OUT ROGUEAP_TABLE *Tab,
-    IN PUCHAR          pAddr);
-
-VOID LeapAuthTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-VOID LeapSendRogueAPReport(
-    IN  PRTMP_ADAPTER   pAd);
-
-BOOLEAN CCKMAssocRspSanity(
-    IN PRTMP_ADAPTER    pAd,
-    IN VOID             *Msg,
-    IN ULONG            MsgLen);
-
-#endif  // __LEAP_H__
diff --git a/drivers/staging/rt2870/link_list.h b/drivers/staging/rt2870/link_list.h
index f652113..2589f34 100644
--- a/drivers/staging/rt2870/link_list.h
+++ b/drivers/staging/rt2870/link_list.h
@@ -1,134 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#ifndef __LINK_LIST_H__
-#define __LINK_LIST_H__
-
-typedef struct _LIST_ENTRY
-{
-	struct _LIST_ENTRY *pNext;
-} LIST_ENTRY, *PLIST_ENTRY;
-
-typedef struct _LIST_HEADR
-{
-	PLIST_ENTRY pHead;
-	PLIST_ENTRY pTail;
-	UCHAR size;
-} LIST_HEADER, *PLIST_HEADER;
-
-static inline VOID initList(
-	IN PLIST_HEADER pList)
-{
-	pList->pHead = pList->pTail = NULL;
-	pList->size = 0;
-	return;
-}
-
-static inline VOID insertTailList(
-	IN PLIST_HEADER pList,
-	IN PLIST_ENTRY pEntry)
-{
-	pEntry->pNext = NULL;
-	if (pList->pTail)
-		pList->pTail->pNext = pEntry;
-	else
-		pList->pHead = pEntry;
-	pList->pTail = pEntry;
-	pList->size++;
-
-	return;
-}
-
-static inline PLIST_ENTRY removeHeadList(
-	IN PLIST_HEADER pList)
-{
-	PLIST_ENTRY pNext;
-	PLIST_ENTRY pEntry;
-
-	pEntry = pList->pHead;
-	if (pList->pHead != NULL)
-	{
-		pNext = pList->pHead->pNext;
-		pList->pHead = pNext;
-		if (pNext == NULL)
-			pList->pTail = NULL;
-		pList->size--;
-	}
-	return pEntry;
-}
-
-static inline int getListSize(
-	IN PLIST_HEADER pList)
-{
-	return pList->size;
-}
-
-static inline PLIST_ENTRY delEntryList(
-	IN PLIST_HEADER pList,
-	IN PLIST_ENTRY pEntry)
-{
-	PLIST_ENTRY pCurEntry;
-	PLIST_ENTRY pPrvEntry;
-
-	if(pList->pHead == NULL)
-		return NULL;
-
-	if(pEntry == pList->pHead)
-	{
-		pCurEntry = pList->pHead;
-		pList->pHead = pCurEntry->pNext;
-
-		if(pList->pHead == NULL)
-			pList->pTail = NULL;
-
-		pList->size--;
-		return pCurEntry;
-	}
-
-	pPrvEntry = pList->pHead;
-	pCurEntry = pPrvEntry->pNext;
-	while(pCurEntry != NULL)
-	{
-		if (pEntry == pCurEntry)
-		{
-			pPrvEntry->pNext = pCurEntry->pNext;
-
-			if(pEntry == pList->pTail)
-				pList->pTail = pPrvEntry;
-
-			pList->size--;
-			break;
-		}
-		pPrvEntry = pCurEntry;
-		pCurEntry = pPrvEntry->pNext;
-	}
-
-	return pCurEntry;
-}
-
-#endif // ___LINK_LIST_H__ //
-
+#include "../rt2860/link_list.h"
diff --git a/drivers/staging/rt2870/md5.h b/drivers/staging/rt2870/md5.h
index d85db12..d60cd05 100644
--- a/drivers/staging/rt2870/md5.h
+++ b/drivers/staging/rt2870/md5.h
@@ -1,107 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	md5.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-	jan			10-28-03		Initial
-	Rita    	11-23-04		Modify MD5 and SHA-1
-*/
-
-#ifndef	uint8
-#define	uint8  unsigned	char
-#endif
-
-#ifndef	uint32
-#define	uint32 unsigned	long int
-#endif
-
-
-#ifndef	__MD5_H__
-#define	__MD5_H__
-
-#define MD5_MAC_LEN 16
-
-typedef struct _MD5_CTX {
-    UINT32   Buf[4];             // buffers of four states
-	UCHAR   Input[64];          // input message
-	UINT32   LenInBitCount[2];   // length counter for input message, 0 up to 64 bits
-}   MD5_CTX;
-
-VOID MD5Init(MD5_CTX *pCtx);
-VOID MD5Update(MD5_CTX *pCtx, UCHAR *pData, UINT32 LenInBytes);
-VOID MD5Final(UCHAR Digest[16], MD5_CTX *pCtx);
-VOID MD5Transform(UINT32 Buf[4], UINT32 Mes[16]);
-
-void md5_mac(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac);
-void hmac_md5(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac);
-
-//
-// SHA context
-//
-typedef	struct _SHA_CTX
-{
-	UINT32   Buf[5];             // buffers of five states
-	UCHAR   Input[80];          // input message
-	UINT32   LenInBitCount[2];   // length counter for input message, 0 up to 64 bits
-
-}	SHA_CTX;
-
-VOID SHAInit(SHA_CTX *pCtx);
-UCHAR SHAUpdate(SHA_CTX *pCtx, UCHAR *pData, UINT32 LenInBytes);
-VOID SHAFinal(SHA_CTX *pCtx, UCHAR Digest[20]);
-VOID SHATransform(UINT32 Buf[5], UINT32 Mes[20]);
-
-#define SHA_DIGEST_LEN 20
-#endif // __MD5_H__
-
-/******************************************************************************/
-#ifndef	_AES_H
-#define	_AES_H
-
-typedef	struct
-{
-	uint32 erk[64];		/* encryption round	keys */
-	uint32 drk[64];		/* decryption round	keys */
-	int	nr;				/* number of rounds	*/
-}
-aes_context;
-
-int	 rtmp_aes_set_key( aes_context *ctx,	uint8 *key,	int	nbits );
-void rtmp_aes_encrypt( aes_context *ctx,	uint8 input[16], uint8 output[16] );
-void rtmp_aes_decrypt( aes_context *ctx,	uint8 input[16], uint8 output[16] );
-
-void F(char *password, unsigned char *ssid, int ssidlength, int iterations, int count, unsigned char *output);
-int PasswordHash(char *password, unsigned char *ssid, int ssidlength, unsigned char *output);
-
-#endif /* aes.h	*/
-
+#include "../rt2860/md5.h"
diff --git a/drivers/staging/rt2870/mlme.h b/drivers/staging/rt2870/mlme.h
index 52fb8e1..58753ac 100644
--- a/drivers/staging/rt2870/mlme.h
+++ b/drivers/staging/rt2870/mlme.h
@@ -1,1471 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	mlme.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang	2003-08-28		Created
-	John Chang  2004-09-06      modified for RT2600
-
-*/
-#ifndef __MLME_H__
-#define __MLME_H__
-
-//extern UCHAR BROADCAST_ADDR[];
-
-// maximum supported capability information -
-// ESS, IBSS, Privacy, Short Preamble, Spectrum mgmt, Short Slot
-#define SUPPORTED_CAPABILITY_INFO   0x0533
-
-#define END_OF_ARGS                 -1
-#define LFSR_MASK                   0x80000057
-#define MLME_TASK_EXEC_INTV         100/*200*/       //
-#define LEAD_TIME                   5
-#define MLME_TASK_EXEC_MULTIPLE       10  /*5*/       // MLME_TASK_EXEC_MULTIPLE * MLME_TASK_EXEC_INTV = 1 sec
-#define REORDER_EXEC_INTV         	100       // 0.1 sec
-//#define TBTT_PRELOAD_TIME         384        // usec. LomgPreamble + 24-byte at 1Mbps
-
-// The definition of Radar detection duration region
-#define CE		0
-#define FCC		1
-#define JAP		2
-#define JAP_W53	3
-#define JAP_W56	4
-#define MAX_RD_REGION 5
-
-#ifdef	NDIS51_MINIPORT
-#define BEACON_LOST_TIME            4000       // 2048 msec = 2 sec
-#else
-#define BEACON_LOST_TIME            4 * OS_HZ    // 2048 msec = 2 sec
-#endif
-
-#define DLS_TIMEOUT                 1200      // unit: msec
-#define AUTH_TIMEOUT                300       // unit: msec
-#define ASSOC_TIMEOUT               300       // unit: msec
-#define JOIN_TIMEOUT                2 * OS_HZ      // unit: msec
-#define SHORT_CHANNEL_TIME          90        // unit: msec
-#define MIN_CHANNEL_TIME            110        // unit: msec, for dual band scan
-#define MAX_CHANNEL_TIME            140       // unit: msec, for single band scan
-#define	FAST_ACTIVE_SCAN_TIME	    30 		  // Active scan waiting for probe response time
-#define CW_MIN_IN_BITS              4         // actual CwMin = 2^CW_MIN_IN_BITS - 1
-
-
-#ifdef CONFIG_STA_SUPPORT
-#ifndef CONFIG_AP_SUPPORT
-#define CW_MAX_IN_BITS              10        // actual CwMax = 2^CW_MAX_IN_BITS - 1
-#endif
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-extern UINT32 CW_MAX_IN_BITS;
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-// Note: RSSI_TO_DBM_OFFSET has been changed to variable for new RF (2004-0720).
-// SHould not refer to this constant anymore
-//#define RSSI_TO_DBM_OFFSET          120 // for RT2530 RSSI-115 = dBm
-#define RSSI_FOR_MID_TX_POWER       -55  // -55 db is considered mid-distance
-#define RSSI_FOR_LOW_TX_POWER       -45  // -45 db is considered very short distance and
-                                        // eligible to use a lower TX power
-#define RSSI_FOR_LOWEST_TX_POWER    -30
-//#define MID_TX_POWER_DELTA          0   // 0 db from full TX power upon mid-distance to AP
-#define LOW_TX_POWER_DELTA          6    // -3 db from full TX power upon very short distance. 1 grade is 0.5 db
-#define LOWEST_TX_POWER_DELTA       16   // -8 db from full TX power upon shortest distance. 1 grade is 0.5 db
-
-#define RSSI_TRIGGERED_UPON_BELOW_THRESHOLD     0
-#define RSSI_TRIGGERED_UPON_EXCCEED_THRESHOLD   1
-#define RSSI_THRESHOLD_FOR_ROAMING              25
-#define RSSI_DELTA                              5
-
-// Channel Quality Indication
-#define CQI_IS_GOOD(cqi)            ((cqi) >= 50)
-//#define CQI_IS_FAIR(cqi)          (((cqi) >= 20) && ((cqi) < 50))
-#define CQI_IS_POOR(cqi)            (cqi < 50)  //(((cqi) >= 5) && ((cqi) < 20))
-#define CQI_IS_BAD(cqi)             (cqi < 5)
-#define CQI_IS_DEAD(cqi)            (cqi == 0)
-
-// weighting factor to calculate Channel quality, total should be 100%
-#define RSSI_WEIGHTING                   50
-#define TX_WEIGHTING                     30
-#define RX_WEIGHTING                     20
-
-//#define PEER_KEY_NOT_USED                0
-//#define PEER_KEY_64_BIT                  64
-//#define PEER_KEY_128_BIT                 128
-
-//#define PEER_KEY_64BIT_LEN               8
-//#define PEER_KEY_128BIT_LEN              16
-
-#define BSS_NOT_FOUND                    0xFFFFFFFF
-
-
-#ifdef CONFIG_STA_SUPPORT
-#define MAX_LEN_OF_MLME_QUEUE            40 //10
-#endif // CONFIG_STA_SUPPORT //
-
-#define SCAN_PASSIVE                     18		// scan with no probe request, only wait beacon and probe response
-#define SCAN_ACTIVE                      19		// scan with probe request, and wait beacon and probe response
-#define	SCAN_CISCO_PASSIVE				 20		// Single channel passive scan
-#define	SCAN_CISCO_ACTIVE				 21		// Single channel active scan
-#define	SCAN_CISCO_NOISE				 22		// Single channel passive scan for noise histogram collection
-#define	SCAN_CISCO_CHANNEL_LOAD			 23		// Single channel passive scan for channel load collection
-#define FAST_SCAN_ACTIVE                 24		// scan with probe request, and wait beacon and probe response
-
-#ifdef DOT11N_DRAFT3
-#define SCAN_2040_BSS_COEXIST                  26
-#endif // DOT11N_DRAFT3 //
-
-//#define BSS_TABLE_EMPTY(x)             ((x).BssNr == 0)
-#define MAC_ADDR_IS_GROUP(Addr)       (((Addr[0]) & 0x01))
-#define MAC_ADDR_HASH(Addr)            (Addr[0] ^ Addr[1] ^ Addr[2] ^ Addr[3] ^ Addr[4] ^ Addr[5])
-#define MAC_ADDR_HASH_INDEX(Addr)      (MAC_ADDR_HASH(Addr) % HASH_TABLE_SIZE)
-#define TID_MAC_HASH(Addr,TID)            (TID^Addr[0] ^ Addr[1] ^ Addr[2] ^ Addr[3] ^ Addr[4] ^ Addr[5])
-#define TID_MAC_HASH_INDEX(Addr,TID)      (TID_MAC_HASH(Addr,TID) % HASH_TABLE_SIZE)
-
-// LED Control
-// assoiation ON. one LED ON. another blinking when TX, OFF when idle
-// no association, both LED off
-#define ASIC_LED_ACT_ON(pAd)        RTMP_IO_WRITE32(pAd, MAC_CSR14, 0x00031e46)
-#define ASIC_LED_ACT_OFF(pAd)       RTMP_IO_WRITE32(pAd, MAC_CSR14, 0x00001e46)
-
-// bit definition of the 2-byte pBEACON->Capability field
-#define CAP_IS_ESS_ON(x)                 (((x) & 0x0001) != 0)
-#define CAP_IS_IBSS_ON(x)                (((x) & 0x0002) != 0)
-#define CAP_IS_CF_POLLABLE_ON(x)         (((x) & 0x0004) != 0)
-#define CAP_IS_CF_POLL_REQ_ON(x)         (((x) & 0x0008) != 0)
-#define CAP_IS_PRIVACY_ON(x)             (((x) & 0x0010) != 0)
-#define CAP_IS_SHORT_PREAMBLE_ON(x)      (((x) & 0x0020) != 0)
-#define CAP_IS_PBCC_ON(x)                (((x) & 0x0040) != 0)
-#define CAP_IS_AGILITY_ON(x)             (((x) & 0x0080) != 0)
-#define CAP_IS_SPECTRUM_MGMT(x)          (((x) & 0x0100) != 0)  // 802.11e d9
-#define CAP_IS_QOS(x)                    (((x) & 0x0200) != 0)  // 802.11e d9
-#define CAP_IS_SHORT_SLOT(x)             (((x) & 0x0400) != 0)
-#define CAP_IS_APSD(x)                   (((x) & 0x0800) != 0)  // 802.11e d9
-#define CAP_IS_IMMED_BA(x)               (((x) & 0x1000) != 0)  // 802.11e d9
-#define CAP_IS_DSSS_OFDM(x)              (((x) & 0x2000) != 0)
-#define CAP_IS_DELAY_BA(x)               (((x) & 0x4000) != 0)  // 802.11e d9
-
-#define CAP_GENERATE(ess,ibss,priv,s_pre,s_slot,spectrum)  (((ess) ? 0x0001 : 0x0000) | ((ibss) ? 0x0002 : 0x0000) | ((priv) ? 0x0010 : 0x0000) | ((s_pre) ? 0x0020 : 0x0000) | ((s_slot) ? 0x0400 : 0x0000) | ((spectrum) ? 0x0100 : 0x0000))
-
-//#define STA_QOS_CAPABILITY               0 // 1-byte. see 802.11e d9.0 for bit definition
-
-#define ERP_IS_NON_ERP_PRESENT(x)        (((x) & 0x01) != 0)    // 802.11g
-#define ERP_IS_USE_PROTECTION(x)         (((x) & 0x02) != 0)    // 802.11g
-#define ERP_IS_USE_BARKER_PREAMBLE(x)    (((x) & 0x04) != 0)    // 802.11g
-
-#define DRS_TX_QUALITY_WORST_BOUND       8// 3  // just test by gary
-#define DRS_PENALTY                      8
-
-#define BA_NOTUSE 	2
-//BA Policy subfiled value in ADDBA frame
-#define IMMED_BA 	1
-#define DELAY_BA	0
-
-// BA Initiator subfield in DELBA frame
-#define ORIGINATOR	1
-#define RECIPIENT	0
-
-// ADDBA Status Code
-#define ADDBA_RESULTCODE_SUCCESS					0
-#define ADDBA_RESULTCODE_REFUSED					37
-#define ADDBA_RESULTCODE_INVALID_PARAMETERS			38
-
-// DELBA Reason Code
-#define DELBA_REASONCODE_QSTA_LEAVING				36
-#define DELBA_REASONCODE_END_BA						37
-#define DELBA_REASONCODE_UNKNOWN_BA					38
-#define DELBA_REASONCODE_TIMEOUT					39
-
-// reset all OneSecTx counters
-#define RESET_ONE_SEC_TX_CNT(__pEntry) \
-if (((__pEntry)) != NULL) \
-{ \
-	(__pEntry)->OneSecTxRetryOkCount = 0; \
-	(__pEntry)->OneSecTxFailCount = 0; \
-	(__pEntry)->OneSecTxNoRetryOkCount = 0; \
-}
-
-//
-// 802.11 frame formats
-//
-//  HT Capability INFO field in HT Cap IE .
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	USHORT	LSIGTxopProSup:1;
-	USHORT	Forty_Mhz_Intolerant:1;
-	USHORT	PSMP:1;
-	USHORT	CCKmodein40:1;
-	USHORT	AMsduSize:1;
-	USHORT	DelayedBA:1;	//rt2860c not support
-	USHORT	RxSTBC:2;
-	USHORT	TxSTBC:1;
-	USHORT	ShortGIfor40:1;	//for40MHz
-	USHORT	ShortGIfor20:1;
-	USHORT	GF:1;	//green field
-	USHORT	MimoPs:2;//momi power safe
-	USHORT	ChannelWidth:1;
-	USHORT	AdvCoding:1;
-#else
-	USHORT	AdvCoding:1;
-	USHORT	ChannelWidth:1;
-	USHORT	MimoPs:2;//momi power safe
-	USHORT	GF:1;	//green field
-	USHORT	ShortGIfor20:1;
-	USHORT	ShortGIfor40:1;	//for40MHz
-	USHORT	TxSTBC:1;
-	USHORT	RxSTBC:2;
-	USHORT	DelayedBA:1;	//rt2860c not support
-	USHORT	AMsduSize:1;	// only support as zero
-	USHORT	CCKmodein40:1;
-	USHORT	PSMP:1;
-	USHORT	Forty_Mhz_Intolerant:1;
-	USHORT	LSIGTxopProSup:1;
-#endif	/* !RT_BIG_ENDIAN */
-} HT_CAP_INFO, *PHT_CAP_INFO;
-
-//  HT Capability INFO field in HT Cap IE .
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:3;//momi power safe
-	UCHAR	MpduDensity:3;
-	UCHAR	MaxRAmpduFactor:2;
-#else
-	UCHAR	MaxRAmpduFactor:2;
-	UCHAR	MpduDensity:3;
-	UCHAR	rsv:3;//momi power safe
-#endif /* !RT_BIG_ENDIAN */
-} HT_CAP_PARM, *PHT_CAP_PARM;
-
-//  HT Capability INFO field in HT Cap IE .
-typedef struct PACKED {
-	UCHAR	MCSSet[10];
-	UCHAR	SupRate[2];  // unit : 1Mbps
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:3;
-	UCHAR	MpduDensity:1;
-	UCHAR	TxStream:2;
-	UCHAR	TxRxNotEqual:1;
-	UCHAR	TxMCSSetDefined:1;
-#else
-	UCHAR	TxMCSSetDefined:1;
-	UCHAR	TxRxNotEqual:1;
-	UCHAR	TxStream:2;
-	UCHAR	MpduDensity:1;
-	UCHAR	rsv:3;
-#endif // RT_BIG_ENDIAN //
-	UCHAR	rsv3[3];
-} HT_MCS_SET, *PHT_MCS_SET;
-
-//  HT Capability INFO field in HT Cap IE .
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv2:4;
-	USHORT	RDGSupport:1;	//reverse Direction Grant  support
-	USHORT	PlusHTC:1;	//+HTC control field support
-	USHORT	MCSFeedback:2;	//0:no MCS feedback, 2:unsolicited MCS feedback, 3:Full MCS feedback,  1:rsv.
-	USHORT	rsv:5;//momi power safe
-	USHORT	TranTime:2;
-	USHORT	Pco:1;
-#else
-	USHORT	Pco:1;
-	USHORT	TranTime:2;
-	USHORT	rsv:5;//momi power safe
-	USHORT	MCSFeedback:2;	//0:no MCS feedback, 2:unsolicited MCS feedback, 3:Full MCS feedback,  1:rsv.
-	USHORT	PlusHTC:1;	//+HTC control field support
-	USHORT	RDGSupport:1;	//reverse Direction Grant  support
-	USHORT	rsv2:4;
-#endif /* RT_BIG_ENDIAN */
-} EXT_HT_CAP_INFO, *PEXT_HT_CAP_INFO;
-
-//  HT Beamforming field in HT Cap IE .
-typedef struct PACKED _HT_BF_CAP{
-#ifdef RT_BIG_ENDIAN
-	ULONG	rsv:3;
-	ULONG	ChanEstimation:2;
-	ULONG	CSIRowBFSup:2;
-	ULONG	ComSteerBFAntSup:2;
-	ULONG	NoComSteerBFAntSup:2;
-	ULONG	CSIBFAntSup:2;
-	ULONG	MinGrouping:2;
-	ULONG	ExpComBF:2;
-	ULONG	ExpNoComBF:2;
-	ULONG	ExpCSIFbk:2;
-	ULONG	ExpComSteerCapable:1;
-	ULONG	ExpNoComSteerCapable:1;
-	ULONG	ExpCSICapable:1;
-	ULONG	Calibration:2;
-	ULONG	ImpTxBFCapable:1;
-	ULONG	TxNDPCapable:1;
-	ULONG	RxNDPCapable:1;
-	ULONG	TxSoundCapable:1;
-	ULONG	RxSoundCapable:1;
-	ULONG	TxBFRecCapable:1;
-#else
-	ULONG	TxBFRecCapable:1;
-	ULONG	RxSoundCapable:1;
-	ULONG	TxSoundCapable:1;
-	ULONG	RxNDPCapable:1;
-	ULONG	TxNDPCapable:1;
-	ULONG	ImpTxBFCapable:1;
-	ULONG	Calibration:2;
-	ULONG	ExpCSICapable:1;
-	ULONG	ExpNoComSteerCapable:1;
-	ULONG	ExpComSteerCapable:1;
-	ULONG	ExpCSIFbk:2;
-	ULONG	ExpNoComBF:2;
-	ULONG	ExpComBF:2;
-	ULONG	MinGrouping:2;
-	ULONG	CSIBFAntSup:2;
-	ULONG	NoComSteerBFAntSup:2;
-	ULONG	ComSteerBFAntSup:2;
-	ULONG	CSIRowBFSup:2;
-	ULONG	ChanEstimation:2;
-	ULONG	rsv:3;
-#endif // RT_BIG_ENDIAN //
-} HT_BF_CAP, *PHT_BF_CAP;
-
-//  HT antenna selection field in HT Cap IE .
-typedef struct PACKED _HT_AS_CAP{
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:1;
-	UCHAR	TxSoundPPDU:1;
-	UCHAR	RxASel:1;
-	UCHAR	AntIndFbk:1;
-	UCHAR	ExpCSIFbk:1;
-	UCHAR	AntIndFbkTxASEL:1;
-	UCHAR	ExpCSIFbkTxASEL:1;
-	UCHAR	AntSelect:1;
-#else
-	UCHAR	AntSelect:1;
-	UCHAR	ExpCSIFbkTxASEL:1;
-	UCHAR	AntIndFbkTxASEL:1;
-	UCHAR	ExpCSIFbk:1;
-	UCHAR	AntIndFbk:1;
-	UCHAR	RxASel:1;
-	UCHAR	TxSoundPPDU:1;
-	UCHAR	rsv:1;
-#endif // RT_BIG_ENDIAN //
-} HT_AS_CAP, *PHT_AS_CAP;
-
-// Draft 1.0 set IE length 26, but is extensible..
-#define SIZE_HT_CAP_IE		26
-// The structure for HT Capability IE.
-typedef struct PACKED _HT_CAPABILITY_IE{
-	HT_CAP_INFO		HtCapInfo;
-	HT_CAP_PARM		HtCapParm;
-//	HT_MCS_SET		HtMCSSet;
-	UCHAR			MCSSet[16];
-	EXT_HT_CAP_INFO	ExtHtCapInfo;
-	HT_BF_CAP		TxBFCap;	// beamforming cap. rt2860c not support beamforming.
-	HT_AS_CAP		ASCap;	//antenna selection.
-} HT_CAPABILITY_IE, *PHT_CAPABILITY_IE;
-
-
-// 802.11n draft3 related structure definitions.
-// 7.3.2.60
-#define dot11OBSSScanPassiveDwell							20	// in TU. min amount of time that the STA continously scans each channel when performing an active OBSS scan.
-#define dot11OBSSScanActiveDwell							10	// in TU.min amount of time that the STA continously scans each channel when performing an passive OBSS scan.
-#define dot11BSSWidthTriggerScanInterval					300  // in sec. max interval between scan operations to be performed to detect BSS channel width trigger events.
-#define dot11OBSSScanPassiveTotalPerChannel					200	// in TU. min total amount of time that the STA scans each channel when performing a passive OBSS scan.
-#define dot11OBSSScanActiveTotalPerChannel					20	//in TU. min total amount of time that the STA scans each channel when performing a active OBSS scan
-#define dot11BSSWidthChannelTransactionDelayFactor			5	// min ratio between the delay time in performing a switch from 20MHz BSS to 20/40 BSS operation and the maxima
-																//	interval between overlapping BSS scan operations.
-#define dot11BSSScanActivityThreshold						25	// in %%, max total time that a STA may be active on the medium during a period of
-																//	(dot11BSSWidthChannelTransactionDelayFactor * dot11BSSWidthTriggerScanInterval) seconds without
-																//	being obligated to perform OBSS Scan operations. default is 25(== 0.25%)
-
-typedef struct PACKED _OVERLAP_BSS_SCAN_IE{
-	USHORT		ScanPassiveDwell;
-	USHORT		ScanActiveDwell;
-	USHORT		TriggerScanInt;				// Trigger scan interval
-	USHORT		PassiveTalPerChannel;		// passive total per channel
-	USHORT		ActiveTalPerChannel;		// active total per channel
-	USHORT		DelayFactor;				// BSS width channel transition delay factor
-	USHORT		ScanActThre;				// Scan Activity threshold
-}OVERLAP_BSS_SCAN_IE, *POVERLAP_BSS_SCAN_IE;
-
-
-//  7.3.2.56. 20/40 Coexistence element used in  Element ID = 72 = IE_2040_BSS_COEXIST
-typedef union PACKED _BSS_2040_COEXIST_IE{
- struct PACKED {
- #ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:5;
-	UCHAR	BSS20WidthReq:1;
-	UCHAR	Intolerant40:1;
-	UCHAR	InfoReq:1;
- #else
-	UCHAR	InfoReq:1;
-	UCHAR	Intolerant40:1;			// Inter-BSS. set 1 when prohibits a receiving BSS from operating as a 20/40 Mhz BSS.
-	UCHAR	BSS20WidthReq:1;		// Intra-BSS set 1 when prohibits a receiving AP from operating its BSS as a 20/40MHz BSS.
-	UCHAR	rsv:5;
-#endif // RT_BIG_ENDIAN //
-    } field;
- UCHAR   word;
-} BSS_2040_COEXIST_IE, *PBSS_2040_COEXIST_IE;
-
-
-typedef struct  _TRIGGER_EVENTA{
-	BOOLEAN			bValid;
-	UCHAR	BSSID[6];
-	UCHAR	RegClass;	// Regulatory Class
-	USHORT	Channel;
-	ULONG	CDCounter;   // Maintain a seperate count down counter for each Event A.
-} TRIGGER_EVENTA, *PTRIGGER_EVENTA;
-
-// 20/40 trigger event table
-// If one Event A delete or created, or if Event B is detected or not detected, STA should send 2040BSSCoexistence to AP.
-#define MAX_TRIGGER_EVENT		64
-typedef struct  _TRIGGER_EVENT_TAB{
-	UCHAR	EventANo;
-	TRIGGER_EVENTA	EventA[MAX_TRIGGER_EVENT];
-	ULONG			EventBCountDown;	// Count down counter for Event B.
-} TRIGGER_EVENT_TAB, *PTRIGGER_EVENT_TAB;
-
-// 7.3.27 20/40 Bss Coexistence Mgmt capability used in extended capabilities information IE( ID = 127 = IE_EXT_CAPABILITY).
-//	This is the first octet and was defined in 802.11n D3.03 and 802.11yD9.0
-typedef struct PACKED _EXT_CAP_INFO_ELEMENT{
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv2:5;
-	UCHAR	ExtendChannelSwitch:1;
-	UCHAR	rsv:1;
-	UCHAR	BssCoexistMgmtSupport:1;
-#else
-	UCHAR	BssCoexistMgmtSupport:1;
-	UCHAR	rsv:1;
-	UCHAR	ExtendChannelSwitch:1;
-	UCHAR	rsv2:5;
-#endif // RT_BIG_ENDIAN //
-}EXT_CAP_INFO_ELEMENT, *PEXT_CAP_INFO_ELEMENT;
-
-
-// 802.11n 7.3.2.61
-typedef struct PACKED _BSS_2040_COEXIST_ELEMENT{
-	UCHAR					ElementID;		// ID = IE_2040_BSS_COEXIST = 72
-	UCHAR					Len;
-	BSS_2040_COEXIST_IE		BssCoexistIe;
-}BSS_2040_COEXIST_ELEMENT, *PBSS_2040_COEXIST_ELEMENT;
-
-
-//802.11n 7.3.2.59
-typedef struct PACKED _BSS_2040_INTOLERANT_CH_REPORT{
-	UCHAR				ElementID;		// ID = IE_2040_BSS_INTOLERANT_REPORT = 73
-	UCHAR				Len;
-	UCHAR				RegulatoryClass;
-	UCHAR				ChList[0];
-}BSS_2040_INTOLERANT_CH_REPORT, *PBSS_2040_INTOLERANT_CH_REPORT;
-
-
-// The structure for channel switch annoucement IE. This is in 802.11n D3.03
-typedef struct PACKED _CHA_SWITCH_ANNOUNCE_IE{
-	UCHAR			SwitchMode;	//channel switch mode
-	UCHAR			NewChannel;	//
-	UCHAR			SwitchCount;	//
-} CHA_SWITCH_ANNOUNCE_IE, *PCHA_SWITCH_ANNOUNCE_IE;
-
-
-// The structure for channel switch annoucement IE. This is in 802.11n D3.03
-typedef struct PACKED _SEC_CHA_OFFSET_IE{
-	UCHAR			SecondaryChannelOffset;	 // 1: Secondary above, 3: Secondary below, 0: no Secondary
-} SEC_CHA_OFFSET_IE, *PSEC_CHA_OFFSET_IE;
-
-
-// This structure is extracted from struct RT_HT_CAPABILITY
-typedef struct {
-	BOOLEAN			bHtEnable;	 // If we should use ht rate.
-	BOOLEAN			bPreNHt;	 // If we should use ht rate.
-	//Substract from HT Capability IE
-	UCHAR			MCSSet[16];	//only supoort MCS=0-15,32 ,
-} RT_HT_PHY_INFO, *PRT_HT_PHY_INFO;
-
-//This structure substracts ralink supports from all 802.11n-related features.
-//Features not listed here but contained in 802.11n spec are not supported in rt2860.
-typedef struct {
-#if 0	// move to
-	BOOLEAN			bHtEnable;	 // If we should use ht rate.
-	BOOLEAN			bPreNHt;	 // If we should use ht rate.
-	//Substract from HT Capability IE
-	UCHAR			MCSSet[16];	//only supoort MCS=0-15,32 ,
-#endif
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv:5;
-	USHORT	AmsduSize:1;	// Max receiving A-MSDU size
-	USHORT	AmsduEnable:1;	// Enable to transmit A-MSDU. Suggest disable. We should use A-MPDU to gain best benifit of 802.11n
-	USHORT	RxSTBC:2;	// 2 bits
-	USHORT	TxSTBC:1;
-	USHORT	ShortGIfor40:1;	//for40MHz
-	USHORT	ShortGIfor20:1;
-	USHORT	GF:1;	//green field
-	USHORT	MimoPs:2;//mimo power safe MMPS_
-	USHORT	ChannelWidth:1;
-#else
-	USHORT	ChannelWidth:1;
-	USHORT	MimoPs:2;//mimo power safe MMPS_
-	USHORT	GF:1;	//green field
-	USHORT	ShortGIfor20:1;
-	USHORT	ShortGIfor40:1;	//for40MHz
-	USHORT	TxSTBC:1;
-	USHORT	RxSTBC:2;	// 2 bits
-	USHORT	AmsduEnable:1;	// Enable to transmit A-MSDU. Suggest disable. We should use A-MPDU to gain best benifit of 802.11n
-	USHORT	AmsduSize:1;	// Max receiving A-MSDU size
-	USHORT	rsv:5;
-#endif
-
-	//Substract from Addiont HT INFO IE
-#ifdef RT_BIG_ENDIAN
-	UCHAR	RecomWidth:1;
-	UCHAR	ExtChanOffset:2;	// Please not the difference with following 	UCHAR	NewExtChannelOffset; from 802.11n
-	UCHAR	MpduDensity:3;
-	UCHAR	MaxRAmpduFactor:2;
-#else
-	UCHAR	MaxRAmpduFactor:2;
-	UCHAR	MpduDensity:3;
-	UCHAR	ExtChanOffset:2;	// Please not the difference with following 	UCHAR	NewExtChannelOffset; from 802.11n
-	UCHAR	RecomWidth:1;
-#endif
-
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv2:11;
-	USHORT	OBSS_NonHTExist:1;
-	USHORT	rsv3:1;
-	USHORT	NonGfPresent:1;
-	USHORT	OperaionMode:2;
-#else
-	USHORT	OperaionMode:2;
-	USHORT	NonGfPresent:1;
-	USHORT	rsv3:1;
-	USHORT	OBSS_NonHTExist:1;
-	USHORT	rsv2:11;
-#endif
-
-	// New Extension Channel Offset IE
-	UCHAR	NewExtChannelOffset;
-	// Extension Capability IE = 127
-	UCHAR	BSSCoexist2040;
-} RT_HT_CAPABILITY, *PRT_HT_CAPABILITY;
-
-//   field in Addtional HT Information IE .
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR	SerInterGranu:3;
-	UCHAR	S_PSMPSup:1;
-	UCHAR	RifsMode:1;
-	UCHAR	RecomWidth:1;
-	UCHAR	ExtChanOffset:2;
-#else
-	UCHAR	ExtChanOffset:2;
-	UCHAR	RecomWidth:1;
-	UCHAR	RifsMode:1;
-	UCHAR	S_PSMPSup:1;	 //Indicate support for scheduled PSMP
-	UCHAR	SerInterGranu:3;	 //service interval granularity
-#endif
-} ADD_HTINFO, *PADD_HTINFO;
-
-typedef struct PACKED{
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv2:11;
-	USHORT	OBSS_NonHTExist:1;
-	USHORT	rsv:1;
-	USHORT	NonGfPresent:1;
-	USHORT	OperaionMode:2;
-#else
-	USHORT	OperaionMode:2;
-	USHORT	NonGfPresent:1;
-	USHORT	rsv:1;
-	USHORT	OBSS_NonHTExist:1;
-	USHORT	rsv2:11;
-#endif
-} ADD_HTINFO2, *PADD_HTINFO2;
-
-
-// TODO: Need sync with spec about the definition of StbcMcs. In Draft 3.03, it's reserved.
-typedef struct PACKED{
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv:4;
-	USHORT	PcoPhase:1;
-	USHORT	PcoActive:1;
-	USHORT	LsigTxopProt:1;
-	USHORT	STBCBeacon:1;
-	USHORT	DualCTSProtect:1;
-	USHORT	DualBeacon:1;
-	USHORT	StbcMcs:6;
-#else
-	USHORT	StbcMcs:6;
-	USHORT	DualBeacon:1;
-	USHORT	DualCTSProtect:1;
-	USHORT	STBCBeacon:1;
-	USHORT	LsigTxopProt:1;	// L-SIG TXOP protection full support
-	USHORT	PcoActive:1;
-	USHORT	PcoPhase:1;
-	USHORT	rsv:4;
-#endif // RT_BIG_ENDIAN //
-} ADD_HTINFO3, *PADD_HTINFO3;
-
-#define SIZE_ADD_HT_INFO_IE		22
-typedef struct  PACKED{
-	UCHAR				ControlChan;
-	ADD_HTINFO			AddHtInfo;
-	ADD_HTINFO2			AddHtInfo2;
-	ADD_HTINFO3			AddHtInfo3;
-	UCHAR				MCSSet[16];		// Basic MCS set
-} ADD_HT_INFO_IE, *PADD_HT_INFO_IE;
-
-typedef struct  PACKED{
-	UCHAR				NewExtChanOffset;
-} NEW_EXT_CHAN_IE, *PNEW_EXT_CHAN_IE;
-
-
-// 4-byte HTC field.  maybe included in any frame except non-QOS data frame.  The Order bit must set 1.
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    UINT32		RDG:1;	//RDG / More PPDU
-    UINT32		ACConstraint:1;	//feedback request
-    UINT32		rsv:5;  //calibration sequence
-    UINT32		ZLFAnnouce:1;	// ZLF announcement
-    UINT32		CSISTEERING:2;	//CSI/ STEERING
-    UINT32		FBKReq:2;	//feedback request
-    UINT32		CalSeq:2;  //calibration sequence
-    UINT32		CalPos:2;	// calibration position
-    UINT32		MFBorASC:7;	//Link adaptation feedback containing recommended MCS. 0x7f for no feedback or not available
-    UINT32		MFS:3;	//SET to the received value of MRS. 0x111 for unsolicited MFB.
-    UINT32		MRSorASI:3;	// MRQ Sequence identifier. unchanged during entire procedure. 0x000-0x110.
-    UINT32		MRQ:1;	//MCS feedback. Request for a MCS feedback
-    UINT32		TRQ:1;	//sounding request
-    UINT32		MA:1;	//management action payload exist in (QoS Null+HTC)
-#else
-    UINT32		MA:1;	//management action payload exist in (QoS Null+HTC)
-    UINT32		TRQ:1;	//sounding request
-    UINT32		MRQ:1;	//MCS feedback. Request for a MCS feedback
-    UINT32		MRSorASI:3;	// MRQ Sequence identifier. unchanged during entire procedure. 0x000-0x110.
-    UINT32		MFS:3;	//SET to the received value of MRS. 0x111 for unsolicited MFB.
-    UINT32		MFBorASC:7;	//Link adaptation feedback containing recommended MCS. 0x7f for no feedback or not available
-    UINT32		CalPos:2;	// calibration position
-    UINT32		CalSeq:2;  //calibration sequence
-    UINT32		FBKReq:2;	//feedback request
-    UINT32		CSISTEERING:2;	//CSI/ STEERING
-    UINT32		ZLFAnnouce:1;	// ZLF announcement
-    UINT32		rsv:5;  //calibration sequence
-    UINT32		ACConstraint:1;	//feedback request
-    UINT32		RDG:1;	//RDG / More PPDU
-#endif /* !RT_BIG_ENDIAN */
-} HT_CONTROL, *PHT_CONTROL;
-
-// 2-byte QOS CONTROL field
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      Txop_QueueSize:8;
-    USHORT      AMsduPresent:1;
-    USHORT      AckPolicy:2;  //0: normal ACK 1:No ACK 2:scheduled under MTBA/PSMP  3: BA
-    USHORT      EOSP:1;
-    USHORT      TID:4;
-#else
-    USHORT      TID:4;
-    USHORT      EOSP:1;
-    USHORT      AckPolicy:2;  //0: normal ACK 1:No ACK 2:scheduled under MTBA/PSMP  3: BA
-    USHORT      AMsduPresent:1;
-    USHORT      Txop_QueueSize:8;
-#endif /* !RT_BIG_ENDIAN */
-} QOS_CONTROL, *PQOS_CONTROL;
-
-// 2-byte Frame control field
-typedef	struct	PACKED {
-#ifdef RT_BIG_ENDIAN
-	USHORT		Order:1;			// Strict order expected
-	USHORT		Wep:1;				// Wep data
-	USHORT		MoreData:1;			// More data bit
-	USHORT		PwrMgmt:1;			// Power management bit
-	USHORT		Retry:1;			// Retry status bit
-	USHORT		MoreFrag:1;			// More fragment bit
-	USHORT		FrDs:1;				// From DS indication
-	USHORT		ToDs:1;				// To DS indication
-	USHORT		SubType:4;			// MSDU subtype
-	USHORT		Type:2;				// MSDU type
-	USHORT		Ver:2;				// Protocol version
-#else
-	USHORT		Ver:2;				// Protocol version
-	USHORT		Type:2;				// MSDU type
-	USHORT		SubType:4;			// MSDU subtype
-	USHORT		ToDs:1;				// To DS indication
-	USHORT		FrDs:1;				// From DS indication
-	USHORT		MoreFrag:1;			// More fragment bit
-	USHORT		Retry:1;			// Retry status bit
-	USHORT		PwrMgmt:1;			// Power management bit
-	USHORT		MoreData:1;			// More data bit
-	USHORT		Wep:1;				// Wep data
-	USHORT		Order:1;			// Strict order expected
-#endif /* !RT_BIG_ENDIAN */
-} FRAME_CONTROL, *PFRAME_CONTROL;
-
-typedef	struct	PACKED _HEADER_802_11	{
-    FRAME_CONTROL   FC;
-    USHORT          Duration;
-    UCHAR           Addr1[MAC_ADDR_LEN];
-    UCHAR           Addr2[MAC_ADDR_LEN];
-	UCHAR			Addr3[MAC_ADDR_LEN];
-#ifdef RT_BIG_ENDIAN
-	USHORT			Sequence:12;
-	USHORT			Frag:4;
-#else
-	USHORT			Frag:4;
-	USHORT			Sequence:12;
-#endif /* !RT_BIG_ENDIAN */
-	UCHAR			Octet[0];
-}	HEADER_802_11, *PHEADER_802_11;
-
-typedef struct PACKED _FRAME_802_11 {
-    HEADER_802_11   Hdr;
-    UCHAR            Octet[1];
-}   FRAME_802_11, *PFRAME_802_11;
-
-// QoSNull embedding of management action. When HT Control MA field set to 1.
-typedef struct PACKED _MA_BODY {
-    UCHAR            Category;
-    UCHAR            Action;
-    UCHAR            Octet[1];
-}   MA_BODY, *PMA_BODY;
-
-typedef	struct	PACKED _HEADER_802_3	{
-    UCHAR           DAAddr1[MAC_ADDR_LEN];
-    UCHAR           SAAddr2[MAC_ADDR_LEN];
-    UCHAR           Octet[2];
-}	HEADER_802_3, *PHEADER_802_3;
-////Block ACK related format
-// 2-byte BA Parameter  field  in 	DELBA frames to terminate an already set up bA
-typedef struct PACKED{
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;	// value of TC os TS
-    USHORT      Initiator:1;	// 1: originator    0:recipient
-    USHORT      Rsv:11;	// always set to 0
-#else
-    USHORT      Rsv:11;	// always set to 0
-    USHORT      Initiator:1;	// 1: originator    0:recipient
-    USHORT      TID:4;	// value of TC os TS
-#endif /* !RT_BIG_ENDIAN */
-} DELBA_PARM, *PDELBA_PARM;
-
-// 2-byte BA Parameter Set field  in ADDBA frames to signal parm for setting up a BA
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      BufSize:10;	// number of buffe of size 2304 octetsr
-    USHORT      TID:4;	// value of TC os TS
-    USHORT      BAPolicy:1;	// 1: immediately BA    0:delayed BA
-    USHORT      AMSDUSupported:1;	// 0: not permitted		1: permitted
-#else
-    USHORT      AMSDUSupported:1;	// 0: not permitted		1: permitted
-    USHORT      BAPolicy:1;	// 1: immediately BA    0:delayed BA
-    USHORT      TID:4;	// value of TC os TS
-    USHORT      BufSize:10;	// number of buffe of size 2304 octetsr
-#endif /* !RT_BIG_ENDIAN */
-} BA_PARM, *PBA_PARM;
-
-// 2-byte BA Starting Seq CONTROL field
-typedef union PACKED {
-    struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      StartSeq:12;   // sequence number of the 1st MSDU for which this BAR is sent
-	USHORT      FragNum:4;	// always set to 0
-#else
-    USHORT      FragNum:4;	// always set to 0
-	USHORT      StartSeq:12;   // sequence number of the 1st MSDU for which this BAR is sent
-#endif /* RT_BIG_ENDIAN */
-    }   field;
-    USHORT           word;
-} BASEQ_CONTROL, *PBASEQ_CONTROL;
-
-//BAControl and BARControl are the same
-// 2-byte BA CONTROL field in BA frame
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;
-    USHORT      Rsv:9;
-    USHORT      Compressed:1;
-    USHORT      MTID:1;		//EWC V1.24
-    USHORT      ACKPolicy:1; // only related to N-Delayed BA. But not support in RT2860b. 0:NormalACK  1:No ACK
-#else
-    USHORT      ACKPolicy:1; // only related to N-Delayed BA. But not support in RT2860b. 0:NormalACK  1:No ACK
-    USHORT      MTID:1;		//EWC V1.24
-    USHORT      Compressed:1;
-    USHORT      Rsv:9;
-    USHORT      TID:4;
-#endif /* !RT_BIG_ENDIAN */
-} BA_CONTROL, *PBA_CONTROL;
-
-// 2-byte BAR CONTROL field in BAR frame
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;
-    USHORT      Rsv1:9;
-    USHORT      Compressed:1;
-    USHORT      MTID:1;		//if this bit1, use  FRAME_MTBA_REQ,  if 0, use FRAME_BA_REQ
-    USHORT      ACKPolicy:1;
-#else
-    USHORT      ACKPolicy:1; // 0:normal ack,  1:no ack.
-    USHORT      MTID:1;		//if this bit1, use  FRAME_MTBA_REQ,  if 0, use FRAME_BA_REQ
-    USHORT      Compressed:1;
-    USHORT      Rsv1:9;
-    USHORT      TID:4;
-#endif /* !RT_BIG_ENDIAN */
-} BAR_CONTROL, *PBAR_CONTROL;
-
-// BARControl in MTBAR frame
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      NumTID:4;
-    USHORT      Rsv1:9;
-    USHORT      Compressed:1;
-    USHORT      MTID:1;
-    USHORT      ACKPolicy:1;
-#else
-    USHORT      ACKPolicy:1;
-    USHORT      MTID:1;
-    USHORT      Compressed:1;
-    USHORT      Rsv1:9;
-    USHORT      NumTID:4;
-#endif /* !RT_BIG_ENDIAN */
-} MTBAR_CONTROL, *PMTBAR_CONTROL;
-
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;
-    USHORT      Rsv1:12;
-#else
-    USHORT      Rsv1:12;
-    USHORT      TID:4;
-#endif /* !RT_BIG_ENDIAN */
-} PER_TID_INFO, *PPER_TID_INFO;
-
-typedef struct {
-	PER_TID_INFO      PerTID;
-	BASEQ_CONTROL 	 BAStartingSeq;
-} EACH_TID, *PEACH_TID;
-
-
-typedef struct PACKED _PSPOLL_FRAME {
-    FRAME_CONTROL   FC;
-    USHORT          Aid;
-    UCHAR           Bssid[MAC_ADDR_LEN];
-    UCHAR           Ta[MAC_ADDR_LEN];
-}   PSPOLL_FRAME, *PPSPOLL_FRAME;
-
-typedef	struct	PACKED _RTS_FRAME	{
-    FRAME_CONTROL   FC;
-    USHORT          Duration;
-    UCHAR           Addr1[MAC_ADDR_LEN];
-    UCHAR           Addr2[MAC_ADDR_LEN];
-}RTS_FRAME, *PRTS_FRAME;
-
-// BAREQ AND MTBAREQ have the same subtype BAR, 802.11n BAR use compressed bitmap.
-typedef struct PACKED _FRAME_BA_REQ {
-	FRAME_CONTROL   FC;
-	USHORT          Duration;
-	UCHAR           Addr1[MAC_ADDR_LEN];
-	UCHAR           Addr2[MAC_ADDR_LEN];
-	BAR_CONTROL  BARControl;
-	BASEQ_CONTROL 	 BAStartingSeq;
-}   FRAME_BA_REQ, *PFRAME_BA_REQ;
-
-typedef struct PACKED _FRAME_MTBA_REQ {
-	FRAME_CONTROL   FC;
-	USHORT          Duration;
-	UCHAR           Addr1[MAC_ADDR_LEN];
-	UCHAR           Addr2[MAC_ADDR_LEN];
-	MTBAR_CONTROL  MTBARControl;
-	PER_TID_INFO	PerTIDInfo;
-	BASEQ_CONTROL 	 BAStartingSeq;
-}   FRAME_MTBA_REQ, *PFRAME_MTBA_REQ;
-
-// Compressed format is mandantory in HT STA
-typedef struct PACKED _FRAME_MTBA {
-	FRAME_CONTROL   FC;
-	USHORT          Duration;
-	UCHAR           Addr1[MAC_ADDR_LEN];
-	UCHAR           Addr2[MAC_ADDR_LEN];
-	BA_CONTROL  BAControl;
-	BASEQ_CONTROL 	 BAStartingSeq;
-	UCHAR		BitMap[8];
-}   FRAME_MTBA, *PFRAME_MTBA;
-
-typedef struct PACKED _FRAME_PSMP_ACTION {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	UCHAR	Psmp;	// 7.3.1.25
-}   FRAME_PSMP_ACTION, *PFRAME_PSMP_ACTION;
-
-typedef struct PACKED _FRAME_ACTION_HDR {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-}   FRAME_ACTION_HDR, *PFRAME_ACTION_HDR;
-
-//Action Frame
-//Action Frame  Category:Spectrum,  Action:Channel Switch. 7.3.2.20
-typedef struct PACKED _CHAN_SWITCH_ANNOUNCE {
-	UCHAR					ElementID;	// ID = IE_CHANNEL_SWITCH_ANNOUNCEMENT = 37
-	UCHAR					Len;
-	CHA_SWITCH_ANNOUNCE_IE	CSAnnounceIe;
-}   CHAN_SWITCH_ANNOUNCE, *PCHAN_SWITCH_ANNOUNCE;
-
-
-//802.11n : 7.3.2.20a
-typedef struct PACKED _SECOND_CHAN_OFFSET {
-	UCHAR				ElementID;		// ID = IE_SECONDARY_CH_OFFSET = 62
-	UCHAR				Len;
-	SEC_CHA_OFFSET_IE	SecChOffsetIe;
-}   SECOND_CHAN_OFFSET, *PSECOND_CHAN_OFFSET;
-
-
-typedef struct PACKED _FRAME_SPETRUM_CS {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	CHAN_SWITCH_ANNOUNCE	CSAnnounce;
-	SECOND_CHAN_OFFSET		SecondChannel;
-}   FRAME_SPETRUM_CS, *PFRAME_SPETRUM_CS;
-
-
-typedef struct PACKED _FRAME_ADDBA_REQ {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	UCHAR	Token;	// 1
-	BA_PARM		BaParm;	      //  2 - 10
-	USHORT		TimeOutValue;	// 0 - 0
-	BASEQ_CONTROL	BaStartSeq; // 0-0
-}   FRAME_ADDBA_REQ, *PFRAME_ADDBA_REQ;
-
-typedef struct PACKED _FRAME_ADDBA_RSP {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	UCHAR	Token;
-	USHORT	StatusCode;
-	BA_PARM		BaParm; //0 - 2
-	USHORT		TimeOutValue;
-}   FRAME_ADDBA_RSP, *PFRAME_ADDBA_RSP;
-
-typedef struct PACKED _FRAME_DELBA_REQ {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	DELBA_PARM		DelbaParm;
-	USHORT	ReasonCode;
-}   FRAME_DELBA_REQ, *PFRAME_DELBA_REQ;
-
-
-//7.2.1.7
-typedef struct PACKED _FRAME_BAR {
-	FRAME_CONTROL   FC;
-	USHORT          Duration;
-	UCHAR           Addr1[MAC_ADDR_LEN];
-	UCHAR           Addr2[MAC_ADDR_LEN];
-	BAR_CONTROL		BarControl;
-	BASEQ_CONTROL	StartingSeq;
-}   FRAME_BAR, *PFRAME_BAR;
-
-//7.2.1.7
-typedef struct PACKED _FRAME_BA {
-	FRAME_CONTROL   FC;
-	USHORT          Duration;
-	UCHAR           Addr1[MAC_ADDR_LEN];
-	UCHAR           Addr2[MAC_ADDR_LEN];
-	BAR_CONTROL		BarControl;
-	BASEQ_CONTROL	StartingSeq;
-	UCHAR		bitmask[8];
-}   FRAME_BA, *PFRAME_BA;
-
-
-// Radio Measuement Request Frame Format
-typedef struct PACKED _FRAME_RM_REQ_ACTION {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	UCHAR	Token;
-	USHORT	Repetition;
-	UCHAR   data[0];
-}   FRAME_RM_REQ_ACTION, *PFRAME_RM_REQ_ACTION;
-
-typedef struct PACKED {
-	UCHAR		ID;
-	UCHAR		Length;
-	UCHAR		ChannelSwitchMode;
-	UCHAR		NewRegClass;
-	UCHAR		NewChannelNum;
-	UCHAR		ChannelSwitchCount;
-} HT_EXT_CHANNEL_SWITCH_ANNOUNCEMENT_IE, *PHT_EXT_CHANNEL_SWITCH_ANNOUNCEMENT_IE;
-
-
-//
-// _Limit must be the 2**n - 1
-// _SEQ1 , _SEQ2 must be within 0 ~ _Limit
-//
-#define SEQ_STEPONE(_SEQ1, _SEQ2, _Limit)	((_SEQ1 == ((_SEQ2+1) & _Limit)))
-#define SEQ_SMALLER(_SEQ1, _SEQ2, _Limit)	(((_SEQ1-_SEQ2) & ((_Limit+1)>>1)))
-#define SEQ_LARGER(_SEQ1, _SEQ2, _Limit)	((_SEQ1 != _SEQ2) && !(((_SEQ1-_SEQ2) & ((_Limit+1)>>1))))
-#define SEQ_WITHIN_WIN(_SEQ1, _SEQ2, _WIN, _Limit) (SEQ_LARGER(_SEQ1, _SEQ2, _Limit) &&  \
-												SEQ_SMALLER(_SEQ1, ((_SEQ2+_WIN+1)&_Limit), _Limit))
-
-//
-// Contention-free parameter (without ID and Length)
-//
-typedef struct PACKED {
-    BOOLEAN     bValid;         // 1: variable contains valid value
-    UCHAR       CfpCount;
-    UCHAR       CfpPeriod;
-    USHORT      CfpMaxDuration;
-    USHORT      CfpDurRemaining;
-} CF_PARM, *PCF_PARM;
-
-typedef	struct	_CIPHER_SUITE	{
-	NDIS_802_11_ENCRYPTION_STATUS	PairCipher;		// Unicast cipher 1, this one has more secured cipher suite
-	NDIS_802_11_ENCRYPTION_STATUS	PairCipherAux;	// Unicast cipher 2 if AP announce two unicast cipher suite
-	NDIS_802_11_ENCRYPTION_STATUS	GroupCipher;	// Group cipher
-	USHORT							RsnCapability;	// RSN capability from beacon
-	BOOLEAN							bMixMode;		// Indicate Pair & Group cipher might be different
-}	CIPHER_SUITE, *PCIPHER_SUITE;
-
-// EDCA configuration from AP's BEACON/ProbeRsp
-typedef struct {
-    BOOLEAN     bValid;         // 1: variable contains valid value
-    BOOLEAN     bAdd;         // 1: variable contains valid value
-    BOOLEAN     bQAck;
-    BOOLEAN     bQueueRequest;
-    BOOLEAN     bTxopRequest;
-    BOOLEAN     bAPSDCapable;
-//  BOOLEAN     bMoreDataAck;
-    UCHAR       EdcaUpdateCount;
-    UCHAR       Aifsn[4];       // 0:AC_BK, 1:AC_BE, 2:AC_VI, 3:AC_VO
-    UCHAR       Cwmin[4];
-    UCHAR       Cwmax[4];
-    USHORT      Txop[4];      // in unit of 32-us
-    BOOLEAN     bACM[4];      // 1: Admission Control of AC_BK is mandattory
-} EDCA_PARM, *PEDCA_PARM;
-
-// QBSS LOAD information from QAP's BEACON/ProbeRsp
-typedef struct {
-    BOOLEAN     bValid;                     // 1: variable contains valid value
-    USHORT      StaNum;
-    UCHAR       ChannelUtilization;
-    USHORT      RemainingAdmissionControl;  // in unit of 32-us
-} QBSS_LOAD_PARM, *PQBSS_LOAD_PARM;
-
-// QBSS Info field in QSTA's assoc req
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR		Rsv2:1;
-	UCHAR		MaxSPLength:2;
-	UCHAR		Rsv1:1;
-	UCHAR		UAPSD_AC_BE:1;
-	UCHAR		UAPSD_AC_BK:1;
-	UCHAR		UAPSD_AC_VI:1;
-	UCHAR		UAPSD_AC_VO:1;
-#else
-    UCHAR		UAPSD_AC_VO:1;
-	UCHAR		UAPSD_AC_VI:1;
-	UCHAR		UAPSD_AC_BK:1;
-	UCHAR		UAPSD_AC_BE:1;
-	UCHAR		Rsv1:1;
-	UCHAR		MaxSPLength:2;
-	UCHAR		Rsv2:1;
-#endif /* !RT_BIG_ENDIAN */
-} QBSS_STA_INFO_PARM, *PQBSS_STA_INFO_PARM;
-
-// QBSS Info field in QAP's Beacon/ProbeRsp
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR		UAPSD:1;
-	UCHAR		Rsv:3;
-    UCHAR		ParamSetCount:4;
-#else
-    UCHAR		ParamSetCount:4;
-	UCHAR		Rsv:3;
-	UCHAR		UAPSD:1;
-#endif /* !RT_BIG_ENDIAN */
-} QBSS_AP_INFO_PARM, *PQBSS_AP_INFO_PARM;
-
-// QOS Capability reported in QAP's BEACON/ProbeRsp
-// QOS Capability sent out in QSTA's AssociateReq/ReAssociateReq
-typedef struct {
-    BOOLEAN     bValid;                     // 1: variable contains valid value
-    BOOLEAN     bQAck;
-    BOOLEAN     bQueueRequest;
-    BOOLEAN     bTxopRequest;
-//  BOOLEAN     bMoreDataAck;
-    UCHAR       EdcaUpdateCount;
-} QOS_CAPABILITY_PARM, *PQOS_CAPABILITY_PARM;
-
-#ifdef CONFIG_STA_SUPPORT
-typedef struct {
-    UCHAR       IELen;
-    UCHAR       IE[MAX_CUSTOM_LEN];
-} WPA_IE_;
-#endif // CONFIG_STA_SUPPORT //
-
-
-typedef struct {
-    UCHAR   Bssid[MAC_ADDR_LEN];
-    UCHAR   Channel;
-	UCHAR   CentralChannel;	//Store the wide-band central channel for 40MHz.  .used in 40MHz AP. Or this is the same as Channel.
-    UCHAR   BssType;
-    USHORT  AtimWin;
-    USHORT  BeaconPeriod;
-
-    UCHAR   SupRate[MAX_LEN_OF_SUPPORTED_RATES];
-    UCHAR   SupRateLen;
-    UCHAR   ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-    UCHAR   ExtRateLen;
-	HT_CAPABILITY_IE HtCapability;
-	UCHAR			HtCapabilityLen;
-	ADD_HT_INFO_IE AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChanOffset;
-	CHAR    Rssi;
-    UCHAR   Privacy;			// Indicate security function ON/OFF. Don't mess up with auth mode.
-	UCHAR	Hidden;
-
-    USHORT  DtimPeriod;
-    USHORT  CapabilityInfo;
-
-    USHORT  CfpCount;
-    USHORT  CfpPeriod;
-    USHORT  CfpMaxDuration;
-    USHORT  CfpDurRemaining;
-    UCHAR   SsidLen;
-    CHAR    Ssid[MAX_LEN_OF_SSID];
-
-    ULONG   LastBeaconRxTime; // OS's timestamp
-
-	BOOLEAN	bSES;
-
-	// New for WPA2
-	CIPHER_SUITE					WPA;			// AP announced WPA cipher suite
-	CIPHER_SUITE					WPA2;			// AP announced WPA2 cipher suite
-
-	// New for microsoft WPA support
-	NDIS_802_11_FIXED_IEs	FixIEs;
-	NDIS_802_11_AUTHENTICATION_MODE	AuthModeAux;	// Addition mode for WPA2 / WPA capable AP
-	NDIS_802_11_AUTHENTICATION_MODE	AuthMode;
-	NDIS_802_11_WEP_STATUS	WepStatus;				// Unicast Encryption Algorithm extract from VAR_IE
-	USHORT					VarIELen;				// Length of next VIE include EID & Length
-	UCHAR					VarIEs[MAX_VIE_LEN];
-
-	// CCX Ckip information
-    UCHAR   CkipFlag;
-
-	// CCX 2 TSF
-	UCHAR	PTSF[4];		// Parent TSF
-	UCHAR	TTSF[8];		// Target TSF
-
-    // 802.11e d9, and WMM
-	EDCA_PARM           EdcaParm;
-	QOS_CAPABILITY_PARM QosCapability;
-	QBSS_LOAD_PARM      QbssLoad;
-#ifdef CONFIG_STA_SUPPORT
-    WPA_IE_     WpaIE;
-    WPA_IE_     RsnIE;
-#ifdef EXT_BUILD_CHANNEL_LIST
-	UCHAR		CountryString[3];
-	BOOLEAN		bHasCountryIE;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
-} BSS_ENTRY, *PBSS_ENTRY;
-
-typedef struct {
-    UCHAR           BssNr;
-    UCHAR           BssOverlapNr;
-    BSS_ENTRY       BssEntry[MAX_LEN_OF_BSS_TABLE];
-} BSS_TABLE, *PBSS_TABLE;
-
-
-typedef struct _MLME_QUEUE_ELEM {
-    ULONG             Machine;
-    ULONG             MsgType;
-    ULONG             MsgLen;
-    UCHAR             Msg[MGMT_DMA_BUFFER_SIZE];
-    LARGE_INTEGER     TimeStamp;
-    UCHAR             Rssi0;
-    UCHAR             Rssi1;
-    UCHAR             Rssi2;
-    UCHAR             Signal;
-    UCHAR             Channel;
-    UCHAR             Wcid;
-    BOOLEAN           Occupied;
-} MLME_QUEUE_ELEM, *PMLME_QUEUE_ELEM;
-
-typedef struct _MLME_QUEUE {
-    ULONG             Num;
-    ULONG             Head;
-    ULONG             Tail;
-    NDIS_SPIN_LOCK   Lock;
-    MLME_QUEUE_ELEM  Entry[MAX_LEN_OF_MLME_QUEUE];
-} MLME_QUEUE, *PMLME_QUEUE;
-
-typedef VOID (*STATE_MACHINE_FUNC)(VOID *Adaptor, MLME_QUEUE_ELEM *Elem);
-
-typedef struct _STATE_MACHINE {
-    ULONG                           Base;
-    ULONG                           NrState;
-    ULONG                           NrMsg;
-    ULONG                           CurrState;
-    STATE_MACHINE_FUNC             *TransFunc;
-} STATE_MACHINE, *PSTATE_MACHINE;
-
-
-// MLME AUX data structure that hold temporarliy settings during a connection attempt.
-// Once this attemp succeeds, all settings will be copy to pAd->StaActive.
-// A connection attempt (user set OID, roaming, CCX fast roaming,..) consists of
-// several steps (JOIN, AUTH, ASSOC or REASSOC) and may fail at any step. We purposely
-// separate this under-trial settings away from pAd->StaActive so that once
-// this new attempt failed, driver can auto-recover back to the active settings.
-typedef struct _MLME_AUX {
-    UCHAR               BssType;
-    UCHAR               Ssid[MAX_LEN_OF_SSID];
-    UCHAR               SsidLen;
-    UCHAR               Bssid[MAC_ADDR_LEN];
-	UCHAR				AutoReconnectSsid[MAX_LEN_OF_SSID];
-	UCHAR				AutoReconnectSsidLen;
-    USHORT              Alg;
-    UCHAR               ScanType;
-    UCHAR               Channel;
-	UCHAR               CentralChannel;
-    USHORT              Aid;
-    USHORT              CapabilityInfo;
-    USHORT              BeaconPeriod;
-    USHORT              CfpMaxDuration;
-    USHORT              CfpPeriod;
-    USHORT              AtimWin;
-
-	// Copy supported rate from desired AP's beacon. We are trying to match
-	// AP's supported and extended rate settings.
-	UCHAR		        SupRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		        ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		        SupRateLen;
-	UCHAR		        ExtRateLen;
-	HT_CAPABILITY_IE		HtCapability;
-	UCHAR		        	HtCapabilityLen;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			NewExtChannelOffset;
-	//RT_HT_CAPABILITY	SupportedHtPhy;
-
-    // new for QOS
-    QOS_CAPABILITY_PARM APQosCapability;    // QOS capability of the current associated AP
-    EDCA_PARM           APEdcaParm;         // EDCA parameters of the current associated AP
-    QBSS_LOAD_PARM      APQbssLoad;         // QBSS load of the current associated AP
-
-    // new to keep Ralink specific feature
-    ULONG               APRalinkIe;
-
-    BSS_TABLE           SsidBssTab;     // AP list for the same SSID
-    BSS_TABLE           RoamTab;        // AP list eligible for roaming
-    ULONG               BssIdx;
-    ULONG               RoamIdx;
-
-	BOOLEAN				CurrReqIsFromNdis;
-
-    RALINK_TIMER_STRUCT BeaconTimer, ScanTimer;
-    RALINK_TIMER_STRUCT AuthTimer;
-    RALINK_TIMER_STRUCT AssocTimer, ReassocTimer, DisassocTimer;
-} MLME_AUX, *PMLME_AUX;
-
-typedef struct _MLME_ADDBA_REQ_STRUCT{
-	UCHAR   Wcid;	//
-	UCHAR   pAddr[MAC_ADDR_LEN];
-	UCHAR   BaBufSize;
-	USHORT	TimeOutValue;
-	UCHAR   TID;
-	UCHAR   Token;
-	USHORT	BaStartSeq;
-} MLME_ADDBA_REQ_STRUCT, *PMLME_ADDBA_REQ_STRUCT;
-
-
-typedef struct _MLME_DELBA_REQ_STRUCT{
-	UCHAR   Wcid;	//
-	UCHAR     Addr[MAC_ADDR_LEN];
-	UCHAR   TID;
-	UCHAR	Initiator;
-} MLME_DELBA_REQ_STRUCT, *PMLME_DELBA_REQ_STRUCT;
-
-// assoc struct is equal to reassoc
-typedef struct _MLME_ASSOC_REQ_STRUCT{
-    UCHAR     Addr[MAC_ADDR_LEN];
-    USHORT    CapabilityInfo;
-    USHORT    ListenIntv;
-    ULONG     Timeout;
-} MLME_ASSOC_REQ_STRUCT, *PMLME_ASSOC_REQ_STRUCT, MLME_REASSOC_REQ_STRUCT, *PMLME_REASSOC_REQ_STRUCT;
-
-typedef struct _MLME_DISASSOC_REQ_STRUCT{
-    UCHAR     Addr[MAC_ADDR_LEN];
-    USHORT    Reason;
-} MLME_DISASSOC_REQ_STRUCT, *PMLME_DISASSOC_REQ_STRUCT;
-
-typedef struct _MLME_AUTH_REQ_STRUCT {
-    UCHAR        Addr[MAC_ADDR_LEN];
-    USHORT       Alg;
-    ULONG        Timeout;
-} MLME_AUTH_REQ_STRUCT, *PMLME_AUTH_REQ_STRUCT;
-
-typedef struct _MLME_DEAUTH_REQ_STRUCT {
-    UCHAR        Addr[MAC_ADDR_LEN];
-    USHORT       Reason;
-} MLME_DEAUTH_REQ_STRUCT, *PMLME_DEAUTH_REQ_STRUCT;
-
-typedef struct {
-    ULONG      BssIdx;
-} MLME_JOIN_REQ_STRUCT;
-
-typedef struct _MLME_SCAN_REQ_STRUCT {
-    UCHAR      Bssid[MAC_ADDR_LEN];
-    UCHAR      BssType;
-    UCHAR      ScanType;
-    UCHAR      SsidLen;
-    CHAR       Ssid[MAX_LEN_OF_SSID];
-} MLME_SCAN_REQ_STRUCT, *PMLME_SCAN_REQ_STRUCT;
-
-typedef struct _MLME_START_REQ_STRUCT {
-    CHAR        Ssid[MAX_LEN_OF_SSID];
-    UCHAR       SsidLen;
-} MLME_START_REQ_STRUCT, *PMLME_START_REQ_STRUCT;
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-// structure for DLS
-typedef struct _RT_802_11_DLS {
-	USHORT						TimeOut;		// Use to time out while slience, unit: second , set by UI
-	USHORT						CountDownTimer;	// Use to time out while slience,unit: second , used by driver only
-	NDIS_802_11_MAC_ADDRESS		MacAddr;		// set by UI
-	UCHAR						Status;			// 0: none , 1: wait STAkey, 2: finish DLS setup , set by driver only
-	BOOLEAN						Valid;			// 1: valid , 0: invalid , set by UI, use to setup or tear down DLS link
-	RALINK_TIMER_STRUCT			Timer;			// Use to time out while handshake
-	USHORT						Sequence;
-	USHORT						MacTabMatchWCID;	// ASIC
-	BOOLEAN						bHTCap;
-	PVOID						pAd;
-} RT_802_11_DLS, *PRT_802_11_DLS;
-
-typedef struct _MLME_DLS_REQ_STRUCT {
-    PRT_802_11_DLS	pDLS;
-    USHORT			Reason;
-} MLME_DLS_REQ_STRUCT, *PMLME_DLS_REQ_STRUCT;
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-typedef struct PACKED {
-    UCHAR   Eid;
-    UCHAR   Len;
-    CHAR   Octet[1];
-} EID_STRUCT,*PEID_STRUCT, BEACON_EID_STRUCT, *PBEACON_EID_STRUCT;
-
-typedef struct PACKED _RTMP_TX_RATE_SWITCH
-{
-	UCHAR   ItemNo;
-#ifdef RT_BIG_ENDIAN
-	UCHAR	Rsv2:2;
-	UCHAR	Mode:2;
-	UCHAR	Rsv1:1;
-	UCHAR	BW:1;
-	UCHAR	ShortGI:1;
-	UCHAR	STBC:1;
-#else
-	UCHAR	STBC:1;
-	UCHAR	ShortGI:1;
-	UCHAR	BW:1;
-	UCHAR	Rsv1:1;
-	UCHAR	Mode:2;
-	UCHAR	Rsv2:2;
-#endif
-	UCHAR   CurrMCS;
-	UCHAR   TrainUp;
-	UCHAR   TrainDown;
-} RRTMP_TX_RATE_SWITCH, *PRTMP_TX_RATE_SWITCH;
-
-// ========================== AP mlme.h ===============================
-#define TBTT_PRELOAD_TIME       384        // usec. LomgPreamble + 24-byte at 1Mbps
-#define DEFAULT_DTIM_PERIOD     1
-
-// weighting factor to calculate Channel quality, total should be 100%
-//#define RSSI_WEIGHTING                   0
-//#define TX_WEIGHTING                     40
-//#define RX_WEIGHTING                     60
-
-#define MAC_TABLE_AGEOUT_TIME			300			// unit: sec
-#define MAC_TABLE_ASSOC_TIMEOUT			5			// unit: sec
-#define MAC_TABLE_FULL(Tab)				((Tab).size == MAX_LEN_OF_MAC_TABLE)
-
-// AP shall drop the sta if contine Tx fail count reach it.
-#define MAC_ENTRY_LIFE_CHECK_CNT		20			// packet cnt.
-
-// Value domain of pMacEntry->Sst
-typedef enum _Sst {
-    SST_NOT_AUTH,   // 0: equivalent to IEEE 802.11/1999 state 1
-    SST_AUTH,       // 1: equivalent to IEEE 802.11/1999 state 2
-    SST_ASSOC       // 2: equivalent to IEEE 802.11/1999 state 3
-} SST;
-
-// value domain of pMacEntry->AuthState
-typedef enum _AuthState {
-    AS_NOT_AUTH,
-    AS_AUTH_OPEN,       // STA has been authenticated using OPEN SYSTEM
-    AS_AUTH_KEY,        // STA has been authenticated using SHARED KEY
-    AS_AUTHENTICATING   // STA is waiting for AUTH seq#3 using SHARED KEY
-} AUTH_STATE;
-
-//for-wpa value domain of pMacEntry->WpaState  802.1i D3   p.114
-typedef enum _ApWpaState {
-    AS_NOTUSE,              // 0
-    AS_DISCONNECT,          // 1
-    AS_DISCONNECTED,        // 2
-    AS_INITIALIZE,          // 3
-    AS_AUTHENTICATION,      // 4
-    AS_AUTHENTICATION2,     // 5
-    AS_INITPMK,             // 6
-    AS_INITPSK,             // 7
-    AS_PTKSTART,            // 8
-    AS_PTKINIT_NEGOTIATING, // 9
-    AS_PTKINITDONE,         // 10
-    AS_UPDATEKEYS,          // 11
-    AS_INTEGRITY_FAILURE,   // 12
-    AS_KEYUPDATE,           // 13
-} AP_WPA_STATE;
-
-// for-wpa value domain of pMacEntry->WpaState  802.1i D3   p.114
-typedef enum _GTKState {
-    REKEY_NEGOTIATING,
-    REKEY_ESTABLISHED,
-    KEYERROR,
-} GTK_STATE;
-
-//  for-wpa  value domain of pMacEntry->WpaState  802.1i D3   p.114
-typedef enum _WpaGTKState {
-    SETKEYS,
-    SETKEYS_DONE,
-} WPA_GTK_STATE;
-// ====================== end of AP mlme.h ============================
-
-
-#endif	// MLME_H__
+#include "../rt2860/mlme.h"
diff --git a/drivers/staging/rt2870/netif_block.h b/drivers/staging/rt2870/netif_block.h
deleted file mode 100644
index 6e5151c..0000000
--- a/drivers/staging/rt2870/netif_block.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#ifndef __NET_IF_BLOCK_H__
-#define __NET_IF_BLOCK_H__
-
-//#include <linux/device.h>
-#include "link_list.h"
-#include "rtmp.h"
-
-#define FREE_NETIF_POOL_SIZE 32
-
-typedef struct _NETIF_ENTRY
-{
-	struct _NETIF_ENTRY *pNext;
-	PNET_DEV pNetDev;
-} NETIF_ENTRY, *PNETIF_ENTRY;
-
-void initblockQueueTab(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN blockNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry,
-	IN PNET_DEV pNetDev);
-
-VOID releaseNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry);
-
-VOID StopNetIfQueue(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR QueIdx,
-	IN PNDIS_PACKET pPacket);
-#endif // __NET_IF_BLOCK_H__
-
diff --git a/drivers/staging/rt2870/oid.h b/drivers/staging/rt2870/oid.h
index d788db6..1223d81b 100644
--- a/drivers/staging/rt2870/oid.h
+++ b/drivers/staging/rt2870/oid.h
@@ -1,1091 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	oid.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-*/
-#ifndef _OID_H_
-#define _OID_H_
-
-#define TRUE				1
-#define FALSE				0
-//
-// IEEE 802.11 Structures and definitions
-//
-#define MAX_TX_POWER_LEVEL              100   /* mW */
-#define MAX_RSSI_TRIGGER                -10    /* dBm */
-#define MIN_RSSI_TRIGGER                -200   /* dBm */
-#define MAX_FRAG_THRESHOLD              2346  /* byte count */
-#define MIN_FRAG_THRESHOLD              256   /* byte count */
-#define MAX_RTS_THRESHOLD               2347  /* byte count */
-
-// new types for Media Specific Indications
-// Extension channel offset
-#define EXTCHA_NONE			0
-#define EXTCHA_ABOVE		0x1
-#define EXTCHA_BELOW		0x3
-
-// BW
-#define BAND_WIDTH_20		0
-#define BAND_WIDTH_40		1
-#define BAND_WIDTH_BOTH		2
-#define BAND_WIDTH_10		3	// 802.11j has 10MHz. This definition is for internal usage. doesn't fill in the IE or other field.
-// SHORTGI
-#define GAP_INTERVAL_400	1	// only support in HT mode
-#define GAP_INTERVAL_800	0
-#define GAP_INTERVAL_BOTH	2
-
-#define NdisMediaStateConnected			1
-#define NdisMediaStateDisconnected		0
-
-#define NDIS_802_11_LENGTH_SSID         32
-#define NDIS_802_11_LENGTH_RATES        8
-#define NDIS_802_11_LENGTH_RATES_EX     16
-#define MAC_ADDR_LENGTH                 6
-#define MAX_NUM_OF_CHS					49 // 14 channels @2.4G +  12@UNII + 4 @MMAC + 11 @HiperLAN2 + 7 @Japan + 1 as NULL terminationc
-#define MAX_NUMBER_OF_EVENT				10  // entry # in EVENT table
-#define MAX_NUMBER_OF_MAC				32 // if MAX_MBSSID_NUM is 8, this value can't be larger than 211
-#define MAX_NUMBER_OF_ACL				64
-#define MAX_LENGTH_OF_SUPPORT_RATES		12    // 1, 2, 5.5, 11, 6, 9, 12, 18, 24, 36, 48, 54
-#define MAX_NUMBER_OF_DLS_ENTRY			4
-
-#ifndef UNDER_CE
-// OID definition, since NDIS 5.0 didn't define these, we need to define for our own
-//#if _WIN32_WINNT<=0x0500
-
-#define OID_GEN_MACHINE_NAME               0x0001021A
-
-#ifdef RALINK_ATE
-#define RT_QUERY_ATE_TXDONE_COUNT			0x0401
-#endif // RALINK_ATE //
-#define RT_QUERY_SIGNAL_CONTEXT				0x0402
-#define RT_SET_IAPP_PID                 	0x0404
-#define RT_SET_APD_PID						0x0405
-#define RT_SET_DEL_MAC_ENTRY				0x0406
-
-//
-// IEEE 802.11 OIDs
-//
-#define	OID_GET_SET_TOGGLE			0x8000
-
-#define	OID_802_11_NETWORK_TYPES_SUPPORTED			0x0103
-#define	OID_802_11_NETWORK_TYPE_IN_USE				0x0104
-#define	OID_802_11_RSSI_TRIGGER						0x0107
-#define	RT_OID_802_11_RSSI							0x0108 //rt2860	only , kathy
-#define	RT_OID_802_11_RSSI_1						0x0109 //rt2860	only , kathy
-#define	RT_OID_802_11_RSSI_2						0x010A //rt2860	only , kathy
-#define	OID_802_11_NUMBER_OF_ANTENNAS				0x010B
-#define	OID_802_11_RX_ANTENNA_SELECTED				0x010C
-#define	OID_802_11_TX_ANTENNA_SELECTED				0x010D
-#define	OID_802_11_SUPPORTED_RATES					0x010E
-#define	OID_802_11_ADD_WEP							0x0112
-#define	OID_802_11_REMOVE_WEP						0x0113
-#define	OID_802_11_DISASSOCIATE						0x0114
-#define	OID_802_11_PRIVACY_FILTER					0x0118
-#define	OID_802_11_ASSOCIATION_INFORMATION			0x011E
-#define	OID_802_11_TEST								0x011F
-#define	RT_OID_802_11_COUNTRY_REGION				0x0507
-#define	OID_802_11_BSSID_LIST_SCAN					0x0508
-#define	OID_802_11_SSID								0x0509
-#define	OID_802_11_BSSID							0x050A
-#define	RT_OID_802_11_RADIO							0x050B
-#define	RT_OID_802_11_PHY_MODE						0x050C
-#define	RT_OID_802_11_STA_CONFIG					0x050D
-#define	OID_802_11_DESIRED_RATES					0x050E
-#define	RT_OID_802_11_PREAMBLE						0x050F
-#define	OID_802_11_WEP_STATUS						0x0510
-#define	OID_802_11_AUTHENTICATION_MODE				0x0511
-#define	OID_802_11_INFRASTRUCTURE_MODE				0x0512
-#define	RT_OID_802_11_RESET_COUNTERS				0x0513
-#define	OID_802_11_RTS_THRESHOLD					0x0514
-#define	OID_802_11_FRAGMENTATION_THRESHOLD			0x0515
-#define	OID_802_11_POWER_MODE						0x0516
-#define	OID_802_11_TX_POWER_LEVEL					0x0517
-#define	RT_OID_802_11_ADD_WPA						0x0518
-#define	OID_802_11_REMOVE_KEY						0x0519
-#define	OID_802_11_ADD_KEY							0x0520
-#define	OID_802_11_CONFIGURATION					0x0521
-#define	OID_802_11_TX_PACKET_BURST					0x0522
-#define	RT_OID_802_11_QUERY_NOISE_LEVEL				0x0523
-#define	RT_OID_802_11_EXTRA_INFO					0x0524
-#ifdef	DBG
-#define	RT_OID_802_11_HARDWARE_REGISTER				0x0525
-#endif
-#define OID_802_11_ENCRYPTION_STATUS            OID_802_11_WEP_STATUS
-#define OID_802_11_DEAUTHENTICATION                 0x0526
-#define OID_802_11_DROP_UNENCRYPTED                 0x0527
-#define OID_802_11_MIC_FAILURE_REPORT_FRAME         0x0528
-
-// For 802.1x daemin using to require current driver configuration
-#define OID_802_11_RADIUS_QUERY_SETTING				0x0540
-
-#define	RT_OID_DEVICE_NAME							0x0607
-#define	RT_OID_VERSION_INFO							0x0608
-#define	OID_802_11_BSSID_LIST						0x0609
-#define	OID_802_3_CURRENT_ADDRESS					0x060A
-#define	OID_GEN_MEDIA_CONNECT_STATUS				0x060B
-#define	RT_OID_802_11_QUERY_LINK_STATUS				0x060C
-#define	OID_802_11_RSSI								0x060D
-#define	OID_802_11_STATISTICS						0x060E
-#define	OID_GEN_RCV_OK								0x060F
-#define	OID_GEN_RCV_NO_BUFFER						0x0610
-#define	RT_OID_802_11_QUERY_EEPROM_VERSION			0x0611
-#define	RT_OID_802_11_QUERY_FIRMWARE_VERSION		0x0612
-#define	RT_OID_802_11_QUERY_LAST_RX_RATE			0x0613
-#define	RT_OID_802_11_TX_POWER_LEVEL_1				0x0614
-#define	RT_OID_802_11_QUERY_PIDVID					0x0615
-//for WPA_SUPPLICANT_SUPPORT
-#define OID_SET_COUNTERMEASURES                     0x0616
-#define OID_802_11_SET_IEEE8021X                    0x0617
-#define OID_802_11_SET_IEEE8021X_REQUIRE_KEY        0x0618
-#define OID_802_11_PMKID                            0x0620
-#define RT_OID_WPA_SUPPLICANT_SUPPORT               0x0621
-#define RT_OID_WE_VERSION_COMPILED                  0x0622
-#define RT_OID_NEW_DRIVER                           0x0623
-
-
-//rt2860 , kathy
-#define	RT_OID_802_11_SNR_0							0x0630
-#define	RT_OID_802_11_SNR_1							0x0631
-#define	RT_OID_802_11_QUERY_LAST_TX_RATE			0x0632
-#define	RT_OID_802_11_QUERY_HT_PHYMODE				0x0633
-#define	RT_OID_802_11_SET_HT_PHYMODE				0x0634
-#define	OID_802_11_RELOAD_DEFAULTS					0x0635
-#define	RT_OID_802_11_QUERY_APSD_SETTING			0x0636
-#define	RT_OID_802_11_SET_APSD_SETTING				0x0637
-#define	RT_OID_802_11_QUERY_APSD_PSM				0x0638
-#define	RT_OID_802_11_SET_APSD_PSM					0x0639
-#define	RT_OID_802_11_QUERY_DLS						0x063A
-#define	RT_OID_802_11_SET_DLS						0x063B
-#define	RT_OID_802_11_QUERY_DLS_PARAM				0x063C
-#define	RT_OID_802_11_SET_DLS_PARAM					0x063D
-#define RT_OID_802_11_QUERY_WMM              		0x063E
-#define RT_OID_802_11_SET_WMM      					0x063F
-#define RT_OID_802_11_QUERY_IMME_BA_CAP				0x0640
-#define RT_OID_802_11_SET_IMME_BA_CAP				0x0641
-#define RT_OID_802_11_QUERY_BATABLE					0x0642
-#define RT_OID_802_11_ADD_IMME_BA					0x0643
-#define RT_OID_802_11_TEAR_IMME_BA					0x0644
-#define RT_OID_DRIVER_DEVICE_NAME                   0x0645
-#define RT_OID_802_11_QUERY_DAT_HT_PHYMODE          0x0646
-#define RT_OID_QUERY_MULTIPLE_CARD_SUPPORT          0x0647
-
-// Ralink defined OIDs
-// Dennis Lee move to platform specific
-
-#define	RT_OID_802_11_BSSID					  (OID_GET_SET_TOGGLE |	OID_802_11_BSSID)
-#define	RT_OID_802_11_SSID					  (OID_GET_SET_TOGGLE |	OID_802_11_SSID)
-#define	RT_OID_802_11_INFRASTRUCTURE_MODE	  (OID_GET_SET_TOGGLE |	OID_802_11_INFRASTRUCTURE_MODE)
-#define	RT_OID_802_11_ADD_WEP				  (OID_GET_SET_TOGGLE |	OID_802_11_ADD_WEP)
-#define	RT_OID_802_11_ADD_KEY				  (OID_GET_SET_TOGGLE |	OID_802_11_ADD_KEY)
-#define	RT_OID_802_11_REMOVE_WEP			  (OID_GET_SET_TOGGLE |	OID_802_11_REMOVE_WEP)
-#define	RT_OID_802_11_REMOVE_KEY			  (OID_GET_SET_TOGGLE |	OID_802_11_REMOVE_KEY)
-#define	RT_OID_802_11_DISASSOCIATE			  (OID_GET_SET_TOGGLE |	OID_802_11_DISASSOCIATE)
-#define	RT_OID_802_11_AUTHENTICATION_MODE	  (OID_GET_SET_TOGGLE |	OID_802_11_AUTHENTICATION_MODE)
-#define	RT_OID_802_11_PRIVACY_FILTER		  (OID_GET_SET_TOGGLE |	OID_802_11_PRIVACY_FILTER)
-#define	RT_OID_802_11_BSSID_LIST_SCAN		  (OID_GET_SET_TOGGLE |	OID_802_11_BSSID_LIST_SCAN)
-#define	RT_OID_802_11_WEP_STATUS			  (OID_GET_SET_TOGGLE |	OID_802_11_WEP_STATUS)
-#define	RT_OID_802_11_RELOAD_DEFAULTS		  (OID_GET_SET_TOGGLE |	OID_802_11_RELOAD_DEFAULTS)
-#define	RT_OID_802_11_NETWORK_TYPE_IN_USE	  (OID_GET_SET_TOGGLE |	OID_802_11_NETWORK_TYPE_IN_USE)
-#define	RT_OID_802_11_TX_POWER_LEVEL		  (OID_GET_SET_TOGGLE |	OID_802_11_TX_POWER_LEVEL)
-#define	RT_OID_802_11_RSSI_TRIGGER			  (OID_GET_SET_TOGGLE |	OID_802_11_RSSI_TRIGGER)
-#define	RT_OID_802_11_FRAGMENTATION_THRESHOLD (OID_GET_SET_TOGGLE |	OID_802_11_FRAGMENTATION_THRESHOLD)
-#define	RT_OID_802_11_RTS_THRESHOLD			  (OID_GET_SET_TOGGLE |	OID_802_11_RTS_THRESHOLD)
-#define	RT_OID_802_11_RX_ANTENNA_SELECTED	  (OID_GET_SET_TOGGLE |	OID_802_11_RX_ANTENNA_SELECTED)
-#define	RT_OID_802_11_TX_ANTENNA_SELECTED	  (OID_GET_SET_TOGGLE |	OID_802_11_TX_ANTENNA_SELECTED)
-#define	RT_OID_802_11_SUPPORTED_RATES		  (OID_GET_SET_TOGGLE |	OID_802_11_SUPPORTED_RATES)
-#define	RT_OID_802_11_DESIRED_RATES			  (OID_GET_SET_TOGGLE |	OID_802_11_DESIRED_RATES)
-#define	RT_OID_802_11_CONFIGURATION			  (OID_GET_SET_TOGGLE |	OID_802_11_CONFIGURATION)
-#define	RT_OID_802_11_POWER_MODE			  (OID_GET_SET_TOGGLE |	OID_802_11_POWER_MODE)
-
-typedef enum _NDIS_802_11_STATUS_TYPE
-{
-    Ndis802_11StatusType_Authentication,
-    Ndis802_11StatusType_MediaStreamMode,
-    Ndis802_11StatusType_PMKID_CandidateList,
-    Ndis802_11StatusTypeMax    // not a real type, defined as an upper bound
-} NDIS_802_11_STATUS_TYPE, *PNDIS_802_11_STATUS_TYPE;
-
-typedef UCHAR   NDIS_802_11_MAC_ADDRESS[6];
-
-typedef struct _NDIS_802_11_STATUS_INDICATION
-{
-    NDIS_802_11_STATUS_TYPE StatusType;
-} NDIS_802_11_STATUS_INDICATION, *PNDIS_802_11_STATUS_INDICATION;
-
-// mask for authentication/integrity fields
-#define NDIS_802_11_AUTH_REQUEST_AUTH_FIELDS        0x0f
-
-#define NDIS_802_11_AUTH_REQUEST_REAUTH             0x01
-#define NDIS_802_11_AUTH_REQUEST_KEYUPDATE          0x02
-#define NDIS_802_11_AUTH_REQUEST_PAIRWISE_ERROR     0x06
-#define NDIS_802_11_AUTH_REQUEST_GROUP_ERROR        0x0E
-
-typedef struct _NDIS_802_11_AUTHENTICATION_REQUEST
-{
-    ULONG Length;            // Length of structure
-    NDIS_802_11_MAC_ADDRESS Bssid;
-    ULONG Flags;
-} NDIS_802_11_AUTHENTICATION_REQUEST, *PNDIS_802_11_AUTHENTICATION_REQUEST;
-
-//Added new types for PMKID Candidate lists.
-typedef struct _PMKID_CANDIDATE {
-    NDIS_802_11_MAC_ADDRESS BSSID;
-    ULONG Flags;
-} PMKID_CANDIDATE, *PPMKID_CANDIDATE;
-
-typedef struct _NDIS_802_11_PMKID_CANDIDATE_LIST
-{
-    ULONG Version;       // Version of the structure
-    ULONG NumCandidates; // No. of pmkid candidates
-    PMKID_CANDIDATE CandidateList[1];
-} NDIS_802_11_PMKID_CANDIDATE_LIST, *PNDIS_802_11_PMKID_CANDIDATE_LIST;
-
-//Flags for PMKID Candidate list structure
-#define NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED	0x01
-
-// Added new types for OFDM 5G and 2.4G
-typedef enum _NDIS_802_11_NETWORK_TYPE
-{
-   Ndis802_11FH,
-   Ndis802_11DS,
-    Ndis802_11OFDM5,
-    Ndis802_11OFDM5_N,
-    Ndis802_11OFDM24,
-    Ndis802_11OFDM24_N,
-   Ndis802_11Automode,
-    Ndis802_11NetworkTypeMax    // not a real type, defined as an upper bound
-} NDIS_802_11_NETWORK_TYPE, *PNDIS_802_11_NETWORK_TYPE;
-
-typedef struct _NDIS_802_11_NETWORK_TYPE_LIST
-{
-    UINT                       NumberOfItems;  // in list below, at least 1
-   NDIS_802_11_NETWORK_TYPE    NetworkType [1];
-} NDIS_802_11_NETWORK_TYPE_LIST, *PNDIS_802_11_NETWORK_TYPE_LIST;
-
-typedef enum _NDIS_802_11_POWER_MODE
-{
-    Ndis802_11PowerModeCAM,
-    Ndis802_11PowerModeMAX_PSP,
-    Ndis802_11PowerModeFast_PSP,
-    Ndis802_11PowerModeLegacy_PSP,
-    Ndis802_11PowerModeMax      // not a real mode, defined as an upper bound
-} NDIS_802_11_POWER_MODE, *PNDIS_802_11_POWER_MODE;
-
-typedef ULONG   NDIS_802_11_TX_POWER_LEVEL; // in milliwatts
-
-//
-// Received Signal Strength Indication
-//
-typedef LONG    NDIS_802_11_RSSI;           // in dBm
-
-typedef struct _NDIS_802_11_CONFIGURATION_FH
-{
-   ULONG           Length;            // Length of structure
-   ULONG           HopPattern;        // As defined by 802.11, MSB set
-   ULONG           HopSet;            // to one if non-802.11
-   ULONG           DwellTime;         // units are Kusec
-} NDIS_802_11_CONFIGURATION_FH, *PNDIS_802_11_CONFIGURATION_FH;
-
-typedef struct _NDIS_802_11_CONFIGURATION
-{
-   ULONG                           Length;             // Length of structure
-   ULONG                           BeaconPeriod;       // units are Kusec
-   ULONG                           ATIMWindow;         // units are Kusec
-   ULONG                           DSConfig;           // Frequency, units are kHz
-   NDIS_802_11_CONFIGURATION_FH    FHConfig;
-} NDIS_802_11_CONFIGURATION, *PNDIS_802_11_CONFIGURATION;
-
-typedef struct _NDIS_802_11_STATISTICS
-{
-   ULONG           Length;             // Length of structure
-   LARGE_INTEGER   TransmittedFragmentCount;
-   LARGE_INTEGER   MulticastTransmittedFrameCount;
-   LARGE_INTEGER   FailedCount;
-   LARGE_INTEGER   RetryCount;
-   LARGE_INTEGER   MultipleRetryCount;
-   LARGE_INTEGER   RTSSuccessCount;
-   LARGE_INTEGER   RTSFailureCount;
-   LARGE_INTEGER   ACKFailureCount;
-   LARGE_INTEGER   FrameDuplicateCount;
-   LARGE_INTEGER   ReceivedFragmentCount;
-   LARGE_INTEGER   MulticastReceivedFrameCount;
-   LARGE_INTEGER   FCSErrorCount;
-   LARGE_INTEGER   TKIPLocalMICFailures;
-   LARGE_INTEGER   TKIPRemoteMICErrors;
-   LARGE_INTEGER   TKIPICVErrors;
-   LARGE_INTEGER   TKIPCounterMeasuresInvoked;
-   LARGE_INTEGER   TKIPReplays;
-   LARGE_INTEGER   CCMPFormatErrors;
-   LARGE_INTEGER   CCMPReplays;
-   LARGE_INTEGER   CCMPDecryptErrors;
-   LARGE_INTEGER   FourWayHandshakeFailures;
-} NDIS_802_11_STATISTICS, *PNDIS_802_11_STATISTICS;
-
-typedef  ULONG  NDIS_802_11_KEY_INDEX;
-typedef ULONGLONG   NDIS_802_11_KEY_RSC;
-
-#define MAX_RADIUS_SRV_NUM			2	  // 802.1x failover number
-
-typedef struct PACKED _RADIUS_SRV_INFO {
-	UINT32			radius_ip;
-	UINT32			radius_port;
-	UCHAR			radius_key[64];
-	UCHAR			radius_key_len;
-} RADIUS_SRV_INFO, *PRADIUS_SRV_INFO;
-
-typedef struct PACKED _RADIUS_KEY_INFO
-{
-	UCHAR			radius_srv_num;
-	RADIUS_SRV_INFO	radius_srv_info[MAX_RADIUS_SRV_NUM];
-	UCHAR			ieee8021xWEP;		 // dynamic WEP
-    UCHAR           key_index;
-    UCHAR           key_length;          // length of key in bytes
-    UCHAR           key_material[13];
-} RADIUS_KEY_INFO, *PRADIUS_KEY_INFO;
-
-// It's used by 802.1x daemon to require relative configuration
-typedef struct PACKED _RADIUS_CONF
-{
-    UINT32          Length;             // Length of this structure
-    UCHAR			mbss_num;			// indicate multiple BSS number
-	UINT32			own_ip_addr;
-	UINT32			retry_interval;
-	UINT32			session_timeout_interval;
-	UCHAR			EAPifname[IFNAMSIZ];
-	UCHAR			EAPifname_len;
-	UCHAR 			PreAuthifname[IFNAMSIZ];
-	UCHAR			PreAuthifname_len;
-	RADIUS_KEY_INFO	RadiusInfo[8/*MAX_MBSSID_NUM*/];
-} RADIUS_CONF, *PRADIUS_CONF;
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-// Key mapping keys require a BSSID
-typedef struct _NDIS_802_11_KEY
-{
-    UINT           Length;             // Length of this structure
-    UINT           KeyIndex;
-    UINT           KeyLength;          // length of key in bytes
-    NDIS_802_11_MAC_ADDRESS BSSID;
-    NDIS_802_11_KEY_RSC KeyRSC;
-    UCHAR           KeyMaterial[1];     // variable length depending on above field
-} NDIS_802_11_KEY, *PNDIS_802_11_KEY;
-#endif // CONFIG_STA_SUPPORT //
-
-typedef struct _NDIS_802_11_REMOVE_KEY
-{
-    UINT           Length;             // Length of this structure
-    UINT           KeyIndex;
-    NDIS_802_11_MAC_ADDRESS BSSID;
-} NDIS_802_11_REMOVE_KEY, *PNDIS_802_11_REMOVE_KEY;
-
-typedef struct _NDIS_802_11_WEP
-{
-   UINT     Length;        // Length of this structure
-   UINT     KeyIndex;           // 0 is the per-client key, 1-N are the
-                                        // global keys
-   UINT     KeyLength;     // length of key in bytes
-   UCHAR     KeyMaterial[1];// variable length depending on above field
-} NDIS_802_11_WEP, *PNDIS_802_11_WEP;
-
-
-typedef enum _NDIS_802_11_NETWORK_INFRASTRUCTURE
-{
-   Ndis802_11IBSS,
-   Ndis802_11Infrastructure,
-   Ndis802_11AutoUnknown,
-   Ndis802_11Monitor,
-   Ndis802_11InfrastructureMax     // Not a real value, defined as upper bound
-} NDIS_802_11_NETWORK_INFRASTRUCTURE, *PNDIS_802_11_NETWORK_INFRASTRUCTURE;
-
-// Add new authentication modes
-typedef enum _NDIS_802_11_AUTHENTICATION_MODE
-{
-   Ndis802_11AuthModeOpen,
-   Ndis802_11AuthModeShared,
-   Ndis802_11AuthModeAutoSwitch,
-    Ndis802_11AuthModeWPA,
-    Ndis802_11AuthModeWPAPSK,
-    Ndis802_11AuthModeWPANone,
-   Ndis802_11AuthModeWPA2,
-   Ndis802_11AuthModeWPA2PSK,
-   	Ndis802_11AuthModeWPA1WPA2,
-	Ndis802_11AuthModeWPA1PSKWPA2PSK,
-   Ndis802_11AuthModeMax           // Not a real mode, defined as upper bound
-} NDIS_802_11_AUTHENTICATION_MODE, *PNDIS_802_11_AUTHENTICATION_MODE;
-
-typedef UCHAR   NDIS_802_11_RATES[NDIS_802_11_LENGTH_RATES];        // Set of 8 data rates
-typedef UCHAR   NDIS_802_11_RATES_EX[NDIS_802_11_LENGTH_RATES_EX];  // Set of 16 data rates
-
-typedef struct PACKED _NDIS_802_11_SSID
-{
-    UINT   SsidLength;         // length of SSID field below, in bytes;
-                                // this can be zero.
-    UCHAR   Ssid[NDIS_802_11_LENGTH_SSID];           // SSID information field
-} NDIS_802_11_SSID, *PNDIS_802_11_SSID;
-
-
-typedef struct PACKED _NDIS_WLAN_BSSID
-{
-   ULONG                               Length;     // Length of this structure
-   NDIS_802_11_MAC_ADDRESS             MacAddress; // BSSID
-   UCHAR                               Reserved[2];
-   NDIS_802_11_SSID                    Ssid;       // SSID
-   ULONG                               Privacy;    // WEP encryption requirement
-   NDIS_802_11_RSSI                    Rssi;       // receive signal strength in dBm
-   NDIS_802_11_NETWORK_TYPE            NetworkTypeInUse;
-   NDIS_802_11_CONFIGURATION           Configuration;
-   NDIS_802_11_NETWORK_INFRASTRUCTURE  InfrastructureMode;
-   NDIS_802_11_RATES                   SupportedRates;
-} NDIS_WLAN_BSSID, *PNDIS_WLAN_BSSID;
-
-typedef struct PACKED _NDIS_802_11_BSSID_LIST
-{
-   UINT           NumberOfItems;      // in list below, at least 1
-   NDIS_WLAN_BSSID Bssid[1];
-} NDIS_802_11_BSSID_LIST, *PNDIS_802_11_BSSID_LIST;
-
-// Added Capabilities, IELength and IEs for each BSSID
-typedef struct PACKED _NDIS_WLAN_BSSID_EX
-{
-    ULONG                               Length;             // Length of this structure
-    NDIS_802_11_MAC_ADDRESS             MacAddress;         // BSSID
-    UCHAR                               Reserved[2];
-    NDIS_802_11_SSID                    Ssid;               // SSID
-    UINT                                Privacy;            // WEP encryption requirement
-    NDIS_802_11_RSSI                    Rssi;               // receive signal
-                                                            // strength in dBm
-    NDIS_802_11_NETWORK_TYPE            NetworkTypeInUse;
-    NDIS_802_11_CONFIGURATION           Configuration;
-    NDIS_802_11_NETWORK_INFRASTRUCTURE  InfrastructureMode;
-    NDIS_802_11_RATES_EX                SupportedRates;
-    ULONG                               IELength;
-    UCHAR                               IEs[1];
-} NDIS_WLAN_BSSID_EX, *PNDIS_WLAN_BSSID_EX;
-
-typedef struct PACKED _NDIS_802_11_BSSID_LIST_EX
-{
-    UINT                   NumberOfItems;      // in list below, at least 1
-    NDIS_WLAN_BSSID_EX      Bssid[1];
-} NDIS_802_11_BSSID_LIST_EX, *PNDIS_802_11_BSSID_LIST_EX;
-
-typedef struct PACKED _NDIS_802_11_FIXED_IEs
-{
-    UCHAR Timestamp[8];
-    USHORT BeaconInterval;
-    USHORT Capabilities;
-} NDIS_802_11_FIXED_IEs, *PNDIS_802_11_FIXED_IEs;
-
-typedef struct _NDIS_802_11_VARIABLE_IEs
-{
-    UCHAR ElementID;
-    UCHAR Length;    // Number of bytes in data field
-    UCHAR data[1];
-} NDIS_802_11_VARIABLE_IEs, *PNDIS_802_11_VARIABLE_IEs;
-
-typedef  ULONG   NDIS_802_11_FRAGMENTATION_THRESHOLD;
-
-typedef  ULONG   NDIS_802_11_RTS_THRESHOLD;
-
-typedef  ULONG   NDIS_802_11_ANTENNA;
-
-typedef enum _NDIS_802_11_PRIVACY_FILTER
-{
-   Ndis802_11PrivFilterAcceptAll,
-   Ndis802_11PrivFilter8021xWEP
-} NDIS_802_11_PRIVACY_FILTER, *PNDIS_802_11_PRIVACY_FILTER;
-
-// Added new encryption types
-// Also aliased typedef to new name
-typedef enum _NDIS_802_11_WEP_STATUS
-{
-   Ndis802_11WEPEnabled,
-    Ndis802_11Encryption1Enabled = Ndis802_11WEPEnabled,
-   Ndis802_11WEPDisabled,
-    Ndis802_11EncryptionDisabled = Ndis802_11WEPDisabled,
-   Ndis802_11WEPKeyAbsent,
-    Ndis802_11Encryption1KeyAbsent = Ndis802_11WEPKeyAbsent,
-   Ndis802_11WEPNotSupported,
-    Ndis802_11EncryptionNotSupported = Ndis802_11WEPNotSupported,
-    Ndis802_11Encryption2Enabled,
-    Ndis802_11Encryption2KeyAbsent,
-    Ndis802_11Encryption3Enabled,
-    Ndis802_11Encryption3KeyAbsent,
-    Ndis802_11Encryption4Enabled,	// TKIP or AES mix
-    Ndis802_11Encryption4KeyAbsent,
-    Ndis802_11GroupWEP40Enabled,
-	Ndis802_11GroupWEP104Enabled,
-} NDIS_802_11_WEP_STATUS, *PNDIS_802_11_WEP_STATUS,
-  NDIS_802_11_ENCRYPTION_STATUS, *PNDIS_802_11_ENCRYPTION_STATUS;
-
-typedef enum _NDIS_802_11_RELOAD_DEFAULTS
-{
-   Ndis802_11ReloadWEPKeys
-} NDIS_802_11_RELOAD_DEFAULTS, *PNDIS_802_11_RELOAD_DEFAULTS;
-
-#define NDIS_802_11_AI_REQFI_CAPABILITIES      1
-#define NDIS_802_11_AI_REQFI_LISTENINTERVAL    2
-#define NDIS_802_11_AI_REQFI_CURRENTAPADDRESS  4
-
-#define NDIS_802_11_AI_RESFI_CAPABILITIES      1
-#define NDIS_802_11_AI_RESFI_STATUSCODE        2
-#define NDIS_802_11_AI_RESFI_ASSOCIATIONID     4
-
-typedef struct _NDIS_802_11_AI_REQFI
-{
-    USHORT Capabilities;
-    USHORT ListenInterval;
-    NDIS_802_11_MAC_ADDRESS  CurrentAPAddress;
-} NDIS_802_11_AI_REQFI, *PNDIS_802_11_AI_REQFI;
-
-typedef struct _NDIS_802_11_AI_RESFI
-{
-    USHORT Capabilities;
-    USHORT StatusCode;
-    USHORT AssociationId;
-} NDIS_802_11_AI_RESFI, *PNDIS_802_11_AI_RESFI;
-
-typedef struct _NDIS_802_11_ASSOCIATION_INFORMATION
-{
-    ULONG                   Length;
-    USHORT                  AvailableRequestFixedIEs;
-    NDIS_802_11_AI_REQFI    RequestFixedIEs;
-    ULONG                   RequestIELength;
-    ULONG                   OffsetRequestIEs;
-    USHORT                  AvailableResponseFixedIEs;
-    NDIS_802_11_AI_RESFI    ResponseFixedIEs;
-    ULONG                   ResponseIELength;
-    ULONG                   OffsetResponseIEs;
-} NDIS_802_11_ASSOCIATION_INFORMATION, *PNDIS_802_11_ASSOCIATION_INFORMATION;
-
-typedef struct _NDIS_802_11_AUTHENTICATION_EVENT
-{
-    NDIS_802_11_STATUS_INDICATION       Status;
-    NDIS_802_11_AUTHENTICATION_REQUEST  Request[1];
-} NDIS_802_11_AUTHENTICATION_EVENT, *PNDIS_802_11_AUTHENTICATION_EVENT;
-
-/*
-typedef struct _NDIS_802_11_TEST
-{
-    ULONG Length;
-    ULONG Type;
-    union
-    {
-        NDIS_802_11_AUTHENTICATION_EVENT AuthenticationEvent;
-        NDIS_802_11_RSSI RssiTrigger;
-    };
-} NDIS_802_11_TEST, *PNDIS_802_11_TEST;
- */
-
-// 802.11 Media stream constraints, associated with OID_802_11_MEDIA_STREAM_MODE
-typedef enum _NDIS_802_11_MEDIA_STREAM_MODE
-{
-    Ndis802_11MediaStreamOff,
-    Ndis802_11MediaStreamOn,
-} NDIS_802_11_MEDIA_STREAM_MODE, *PNDIS_802_11_MEDIA_STREAM_MODE;
-
-// PMKID Structures
-typedef UCHAR   NDIS_802_11_PMKID_VALUE[16];
-
-#ifdef CONFIG_STA_SUPPORT
-typedef struct _BSSID_INFO
-{
-    NDIS_802_11_MAC_ADDRESS BSSID;
-    NDIS_802_11_PMKID_VALUE PMKID;
-} BSSID_INFO, *PBSSID_INFO;
-
-typedef struct _NDIS_802_11_PMKID
-{
-    UINT    Length;
-    UINT    BSSIDInfoCount;
-    BSSID_INFO BSSIDInfo[1];
-} NDIS_802_11_PMKID, *PNDIS_802_11_PMKID;
-#endif // CONFIG_STA_SUPPORT //
-
-
-typedef struct _NDIS_802_11_AUTHENTICATION_ENCRYPTION
-{
-    NDIS_802_11_AUTHENTICATION_MODE AuthModeSupported;
-    NDIS_802_11_ENCRYPTION_STATUS EncryptStatusSupported;
-} NDIS_802_11_AUTHENTICATION_ENCRYPTION, *PNDIS_802_11_AUTHENTICATION_ENCRYPTION;
-
-typedef struct _NDIS_802_11_CAPABILITY
-{
-     ULONG Length;
-     ULONG Version;
-     ULONG NoOfPMKIDs;
-     ULONG NoOfAuthEncryptPairsSupported;
-     NDIS_802_11_AUTHENTICATION_ENCRYPTION AuthenticationEncryptionSupported[1];
-} NDIS_802_11_CAPABILITY, *PNDIS_802_11_CAPABILITY;
-
-//#endif //of WIN 2k
-#endif //UNDER_CE
-
-#if WIRELESS_EXT <= 11
-#ifndef SIOCDEVPRIVATE
-#define SIOCDEVPRIVATE                              0x8BE0
-#endif
-#define SIOCIWFIRSTPRIV								SIOCDEVPRIVATE
-#endif
-
-#ifdef CONFIG_STA_SUPPORT
-#define RTPRIV_IOCTL_SET							(SIOCIWFIRSTPRIV + 0x02)
-
-#ifdef DBG
-#define RTPRIV_IOCTL_BBP                            (SIOCIWFIRSTPRIV + 0x03)
-#define RTPRIV_IOCTL_MAC                            (SIOCIWFIRSTPRIV + 0x05)
-#define RTPRIV_IOCTL_E2P                            (SIOCIWFIRSTPRIV + 0x07)
-#endif
-
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-#define RTPRIV_IOCTL_ATE							(SIOCIWFIRSTPRIV + 0x08)
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-#define RTPRIV_IOCTL_STATISTICS                     (SIOCIWFIRSTPRIV + 0x09)
-#define RTPRIV_IOCTL_ADD_PMKID_CACHE                (SIOCIWFIRSTPRIV + 0x0A)
-#define RTPRIV_IOCTL_RADIUS_DATA                    (SIOCIWFIRSTPRIV + 0x0C)
-#define RTPRIV_IOCTL_GSITESURVEY					(SIOCIWFIRSTPRIV + 0x0D)
-#define RT_PRIV_IOCTL								(SIOCIWFIRSTPRIV + 0x0E) // Sync. with RT61 (for wpa_supplicant)
-#define RTPRIV_IOCTL_GET_MAC_TABLE					(SIOCIWFIRSTPRIV + 0x0F)
-
-#define RTPRIV_IOCTL_SHOW							(SIOCIWFIRSTPRIV + 0x11)
-enum {
-    SHOW_CONN_STATUS = 4,
-    SHOW_DRVIER_VERION = 5,
-    SHOW_BA_INFO = 6,
-	SHOW_DESC_INFO = 7,
-#ifdef RT2870
-	SHOW_RXBULK_INFO = 8,
-	SHOW_TXBULK_INFO = 9,
-#endif // RT2870 //
-    RAIO_OFF = 10,
-    RAIO_ON = 11,
-#ifdef QOS_DLS_SUPPORT
-	SHOW_DLS_ENTRY_INFO = 19,
-#endif // QOS_DLS_SUPPORT //
-	SHOW_CFG_VALUE = 20,
-	SHOW_ADHOC_ENTRY_INFO = 21,
-};
-
-
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef SNMP_SUPPORT
-//SNMP ieee 802dot11, kathy , 2008_0220
-// dot11res(3)
-#define RT_OID_802_11_MANUFACTUREROUI			0x0700
-#define RT_OID_802_11_MANUFACTURERNAME			0x0701
-#define RT_OID_802_11_RESOURCETYPEIDNAME		0x0702
-
-// dot11smt(1)
-#define RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED	0x0703
-#define RT_OID_802_11_POWERMANAGEMENTMODE		0x0704
-#define OID_802_11_WEPDEFAULTKEYVALUE			0x0705 // read , write
-#define OID_802_11_WEPDEFAULTKEYID				0x0706
-#define RT_OID_802_11_WEPKEYMAPPINGLENGTH		0x0707
-#define OID_802_11_SHORTRETRYLIMIT				0x0708
-#define OID_802_11_LONGRETRYLIMIT				0x0709
-#define RT_OID_802_11_PRODUCTID					0x0710
-#define RT_OID_802_11_MANUFACTUREID				0x0711
-
-// //dot11Phy(4)
-#define OID_802_11_CURRENTCHANNEL				0x0712
-
-//dot11mac
-#define RT_OID_802_11_MAC_ADDRESS				0x0713
-#endif // SNMP_SUPPORT //
-
-#define OID_802_11_BUILD_CHANNEL_EX				0x0714
-#define OID_802_11_GET_CH_LIST					0x0715
-#define OID_802_11_GET_COUNTRY_CODE				0x0716
-#define OID_802_11_GET_CHANNEL_GEOGRAPHY		0x0717
-
-#ifdef LLTD_SUPPORT
-// for consistency with RT61
-#define RT_OID_GET_PHY_MODE                         0x761
-#endif // LLTD_SUPPORT //
-
-// MIMO Tx parameter, ShortGI, MCS, STBC, etc.  these are fields in TXWI. Don't change this definition!!!
-typedef union  _HTTRANSMIT_SETTING {
-#ifdef RT_BIG_ENDIAN
-	struct	{
-	USHORT		MODE:2;	// Use definition MODE_xxx.
-//	USHORT		rsv:3;
-	USHORT		TxBF:1;
-	USHORT		rsv:2;
-	USHORT		STBC:2;	//SPACE
-	USHORT		ShortGI:1;
-	USHORT		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	USHORT   	MCS:7;                 // MCS
-	}	field;
-#else
-	struct	{
-	USHORT   	MCS:7;                 // MCS
-	USHORT		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	USHORT		ShortGI:1;
-	USHORT		STBC:2;	//SPACE
-//	USHORT		rsv:3;
-	USHORT		rsv:2;
-	USHORT		TxBF:1;
-	USHORT		MODE:2;	// Use definition MODE_xxx.
-	}	field;
-#endif
-	USHORT		word;
- } HTTRANSMIT_SETTING, *PHTTRANSMIT_SETTING;
-
-typedef enum _RT_802_11_PREAMBLE {
-    Rt802_11PreambleLong,
-    Rt802_11PreambleShort,
-    Rt802_11PreambleAuto
-} RT_802_11_PREAMBLE, *PRT_802_11_PREAMBLE;
-
-// Only for STA, need to sync with AP
-typedef enum _RT_802_11_PHY_MODE {
-	PHY_11BG_MIXED = 0,
-	PHY_11B,
-	PHY_11A,
-	PHY_11ABG_MIXED,
-	PHY_11G,
-#ifdef DOT11_N_SUPPORT
-	PHY_11ABGN_MIXED,	// both band   5
-	PHY_11N_2_4G,		// 11n-only with 2.4G band   	6
-	PHY_11GN_MIXED,	// 2.4G band      7
-	PHY_11AN_MIXED,	// 5G  band       8
-	PHY_11BGN_MIXED,	// if check 802.11b.      9
-	PHY_11AGN_MIXED,	// if check 802.11b.      10
-	PHY_11N_5G,			// 11n-only with 5G band		11
-#endif // DOT11_N_SUPPORT //
-} RT_802_11_PHY_MODE;
-
-// put all proprietery for-query objects here to reduce # of Query_OID
-typedef struct _RT_802_11_LINK_STATUS {
-    ULONG   CurrTxRate;         // in units of 0.5Mbps
-    ULONG   ChannelQuality;     // 0..100 %
-    ULONG   TxByteCount;        // both ok and fail
-    ULONG   RxByteCount;        // both ok and fail
-    ULONG	CentralChannel;		// 40MHz central channel number
-} RT_802_11_LINK_STATUS, *PRT_802_11_LINK_STATUS;
-
-typedef struct _RT_802_11_EVENT_LOG {
-    LARGE_INTEGER   SystemTime;  // timestammp via NdisGetCurrentSystemTime()
-    UCHAR           Addr[MAC_ADDR_LENGTH];
-    USHORT          Event;       // EVENT_xxx
-} RT_802_11_EVENT_LOG, *PRT_802_11_EVENT_LOG;
-
-typedef struct _RT_802_11_EVENT_TABLE {
-    ULONG       Num;
-    ULONG       Rsv;     // to align Log[] at LARGE_INEGER boundary
-    RT_802_11_EVENT_LOG   Log[MAX_NUMBER_OF_EVENT];
-} RT_802_11_EVENT_TABLE, PRT_802_11_EVENT_TABLE;
-
-// MIMO Tx parameter, ShortGI, MCS, STBC, etc.  these are fields in TXWI. Don't change this definition!!!
-typedef union  _MACHTTRANSMIT_SETTING {
-	struct	{
-	USHORT   	MCS:7;                 // MCS
-	USHORT		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	USHORT		ShortGI:1;
-	USHORT		STBC:2;	//SPACE
-	USHORT		rsv:3;
-	USHORT		MODE:2;	// Use definition MODE_xxx.
-	}	field;
-	USHORT		word;
- } MACHTTRANSMIT_SETTING, *PMACHTTRANSMIT_SETTING;
-
-typedef struct _RT_802_11_MAC_ENTRY {
-    UCHAR       Addr[MAC_ADDR_LENGTH];
-    UCHAR       Aid;
-    UCHAR       Psm;     // 0:PWR_ACTIVE, 1:PWR_SAVE
-    UCHAR		MimoPs;  // 0:MMPS_STATIC, 1:MMPS_DYNAMIC, 3:MMPS_Enabled
-    CHAR		AvgRssi0;
-	CHAR		AvgRssi1;
-	CHAR		AvgRssi2;
-	UINT32		ConnectedTime;
-    MACHTTRANSMIT_SETTING	TxRate;
-} RT_802_11_MAC_ENTRY, *PRT_802_11_MAC_ENTRY;
-
-typedef struct _RT_802_11_MAC_TABLE {
-    ULONG       Num;
-    RT_802_11_MAC_ENTRY Entry[MAX_NUMBER_OF_MAC];
-} RT_802_11_MAC_TABLE, *PRT_802_11_MAC_TABLE;
-
-// structure for query/set hardware register - MAC, BBP, RF register
-typedef struct _RT_802_11_HARDWARE_REGISTER {
-    ULONG   HardwareType;       // 0:MAC, 1:BBP, 2:RF register, 3:EEPROM
-    ULONG   Offset;             // Q/S register offset addr
-    ULONG   Data;               // R/W data buffer
-} RT_802_11_HARDWARE_REGISTER, *PRT_802_11_HARDWARE_REGISTER;
-
-// structure to tune BBP R17 "RX AGC VGC init"
-//typedef struct _RT_802_11_RX_AGC_VGC_TUNING {
-//    UCHAR   FalseCcaLowerThreshold;  // 0-255, def 10
-//    UCHAR   FalseCcaUpperThreshold;  // 0-255, def 100
-//    UCHAR   VgcDelta;                // R17 +-= VgcDelta whenever flase CCA over UpprThreshold
-//                                     // or lower than LowerThresholdupper threshold
-//    UCHAR   VgcUpperBound;           // max value of R17
-//} RT_802_11_RX_AGC_VGC_TUNING, *PRT_802_11_RX_AGC_VGC_TUNING;
-
-typedef struct _RT_802_11_AP_CONFIG {
-    ULONG   EnableTxBurst;      // 0-disable, 1-enable
-    ULONG   EnableTurboRate;    // 0-disable, 1-enable 72/100mbps turbo rate
-    ULONG   IsolateInterStaTraffic;     // 0-disable, 1-enable isolation
-    ULONG   HideSsid;           // 0-disable, 1-enable hiding
-    ULONG   UseBGProtection;    // 0-AUTO, 1-always ON, 2-always OFF
-    ULONG   UseShortSlotTime;   // 0-no use, 1-use 9-us short slot time
-    ULONG   Rsv1;               // must be 0
-    ULONG   SystemErrorBitmap;  // ignore upon SET, return system error upon QUERY
-} RT_802_11_AP_CONFIG, *PRT_802_11_AP_CONFIG;
-
-// structure to query/set STA_CONFIG
-typedef struct _RT_802_11_STA_CONFIG {
-    ULONG   EnableTxBurst;      // 0-disable, 1-enable
-    ULONG   EnableTurboRate;    // 0-disable, 1-enable 72/100mbps turbo rate
-    ULONG   UseBGProtection;    // 0-AUTO, 1-always ON, 2-always OFF
-    ULONG   UseShortSlotTime;   // 0-no use, 1-use 9-us short slot time when applicable
-    ULONG   AdhocMode; 			// 0-11b rates only (WIFI spec), 1 - b/g mixed, 2 - g only
-    ULONG   HwRadioStatus;      // 0-OFF, 1-ON, default is 1, Read-Only
-    ULONG   Rsv1;               // must be 0
-    ULONG   SystemErrorBitmap;  // ignore upon SET, return system error upon QUERY
-} RT_802_11_STA_CONFIG, *PRT_802_11_STA_CONFIG;
-
-//
-//  For OID Query or Set about BA structure
-//
-typedef	struct	_OID_BACAP_STRUC	{
-		UCHAR		RxBAWinLimit;
-		UCHAR		TxBAWinLimit;
-		UCHAR		Policy;	// 0: DELAY_BA 1:IMMED_BA  (//BA Policy subfiled value in ADDBA frame)   2:BA-not use. other value invalid
-		UCHAR		MpduDensity;	// 0: DELAY_BA 1:IMMED_BA  (//BA Policy subfiled value in ADDBA frame)   2:BA-not use. other value invalid
-		UCHAR       	AmsduEnable;	//Enable AMSDU transmisstion
-		UCHAR       	AmsduSize;	// 0:3839, 1:7935 bytes. UINT  MSDUSizeToBytes[]	= { 3839, 7935};
-		UCHAR       	MMPSmode;	// MIMO power save more, 0:static, 1:dynamic, 2:rsv, 3:mimo enable
-		BOOLEAN		AutoBA;	// Auto BA will automatically
-} OID_BACAP_STRUC, *POID_BACAP_STRUC;
-
-typedef struct _RT_802_11_ACL_ENTRY {
-    UCHAR   Addr[MAC_ADDR_LENGTH];
-    USHORT  Rsv;
-} RT_802_11_ACL_ENTRY, *PRT_802_11_ACL_ENTRY;
-
-typedef struct PACKED _RT_802_11_ACL {
-    ULONG   Policy;             // 0-disable, 1-positive list, 2-negative list
-    ULONG   Num;
-    RT_802_11_ACL_ENTRY Entry[MAX_NUMBER_OF_ACL];
-} RT_802_11_ACL, *PRT_802_11_ACL;
-
-typedef struct _RT_802_11_WDS {
-    ULONG						Num;
-    NDIS_802_11_MAC_ADDRESS		Entry[24/*MAX_NUM_OF_WDS_LINK*/];
-	ULONG						KeyLength;
-	UCHAR						KeyMaterial[32];
-} RT_802_11_WDS, *PRT_802_11_WDS;
-
-typedef struct _RT_802_11_TX_RATES_ {
-    UCHAR       SupRateLen;
-    UCHAR       SupRate[MAX_LENGTH_OF_SUPPORT_RATES];
-    UCHAR       ExtRateLen;
-    UCHAR       ExtRate[MAX_LENGTH_OF_SUPPORT_RATES];
-} RT_802_11_TX_RATES, *PRT_802_11_TX_RATES;
-
-
-// Definition of extra information code
-#define	GENERAL_LINK_UP			0x0			// Link is Up
-#define	GENERAL_LINK_DOWN		0x1			// Link is Down
-#define	HW_RADIO_OFF			0x2			// Hardware radio off
-#define	SW_RADIO_OFF			0x3			// Software radio off
-#define	AUTH_FAIL				0x4			// Open authentication fail
-#define	AUTH_FAIL_KEYS			0x5			// Shared authentication fail
-#define	ASSOC_FAIL				0x6			// Association failed
-#define	EAP_MIC_FAILURE			0x7			// Deauthencation because MIC failure
-#define	EAP_4WAY_TIMEOUT		0x8			// Deauthencation on 4-way handshake timeout
-#define	EAP_GROUP_KEY_TIMEOUT	0x9			// Deauthencation on group key handshake timeout
-#define	EAP_SUCCESS				0xa			// EAP succeed
-#define	DETECT_RADAR_SIGNAL		0xb         // Radar signal occur in current channel
-#define EXTRA_INFO_MAX			0xb			// Indicate Last OID
-
-#define EXTRA_INFO_CLEAR		0xffffffff
-
-// This is OID setting structure. So only GF or MM as Mode. This is valid when our wirelss mode has 802.11n in use.
-typedef struct {
-	RT_802_11_PHY_MODE		PhyMode; 	//
-	UCHAR		TransmitNo;
-	UCHAR		HtMode; 	//HTMODE_GF or HTMODE_MM
-	UCHAR		ExtOffset;	//extension channel above or below
-	UCHAR		MCS;
-	UCHAR   	BW;
-	UCHAR		STBC;
-	UCHAR		SHORTGI;
-	UCHAR		rsv;
-} OID_SET_HT_PHYMODE, *POID_SET_HT_PHYMODE;
-
-#ifdef NINTENDO_AP
-#define NINTENDO_MAX_ENTRY 16
-#define NINTENDO_SSID_NAME_LN 8
-#define NINTENDO_SSID_NAME "NWCUSBAP"
-#define NINTENDO_PROBE_REQ_FLAG_MASK 0x03
-#define NINTENDO_PROBE_REQ_ON 0x01
-#define NINTENDO_PROBE_REQ_SIGNAL 0x02
-#define NINTENDO_PROBE_RSP_ON 0x01
-#define NINTENDO_SSID_NICKNAME_LN 20
-
-#define NINTENDO_WEPKEY_LN 13
-
-typedef struct _NINTENDO_SSID
-{
-	UCHAR	NINTENDOFixChar[NINTENDO_SSID_NAME_LN];
-	UCHAR	zero1;
-	UCHAR	registe;
-	UCHAR	ID;
-	UCHAR	zero2;
-	UCHAR	NICKname[NINTENDO_SSID_NICKNAME_LN];
-} RT_NINTENDO_SSID, *PRT_NINTENDO_SSID;
-
-typedef struct _NINTENDO_ENTRY
-{
-	UCHAR	NICKname[NINTENDO_SSID_NICKNAME_LN];
-    UCHAR   DS_Addr[ETH_LENGTH_OF_ADDRESS];
-	UCHAR	registe;
-	UCHAR	UserSpaceAck;
-} RT_NINTENDO_ENTRY, *PRT_NINTENDO_ENTRY;
-
-//RTPRIV_IOCTL_NINTENDO_GET_TABLE
-//RTPRIV_IOCTL_NINTENDO_SET_TABLE
-typedef struct _NINTENDO_TABLE
-{
-	UINT				number;
-	RT_NINTENDO_ENTRY	entry[NINTENDO_MAX_ENTRY];
-} RT_NINTENDO_TABLE, *PRT_NINTENDO_TABLE;
-
-//RTPRIV_IOCTL_NINTENDO_SEED_WEPKEY
-typedef struct _NINTENDO_SEED_WEPKEY
-{
-	UCHAR	seed[NINTENDO_SSID_NICKNAME_LN];
-	UCHAR	wepkey[16];//use 13 for 104 bits wep key
-} RT_NINTENDO_SEED_WEPKEY, *PRT_NINTENDO_SEED_WEPKEY;
-#endif // NINTENDO_AP //
-
-#ifdef LLTD_SUPPORT
-typedef struct _RT_LLTD_ASSOICATION_ENTRY {
-    UCHAR           Addr[ETH_LENGTH_OF_ADDRESS];
-    unsigned short  MOR;        // maximum operational rate
-    UCHAR           phyMode;
-} RT_LLTD_ASSOICATION_ENTRY, *PRT_LLTD_ASSOICATION_ENTRY;
-
-typedef struct _RT_LLTD_ASSOICATION_TABLE {
-    unsigned int                Num;
-    RT_LLTD_ASSOICATION_ENTRY   Entry[MAX_NUMBER_OF_MAC];
-} RT_LLTD_ASSOICATION_TABLE, *PRT_LLTD_ASSOICATION_TABLE;
-#endif // LLTD_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-//rt2860, kathy 2007-0118
-// structure for DLS
-typedef struct _RT_802_11_DLS_UI {
-	USHORT						TimeOut;		// unit: second , set by UI
-	USHORT						CountDownTimer;	// unit: second , used by driver only
-	NDIS_802_11_MAC_ADDRESS		MacAddr;		// set by UI
-	UCHAR						Status;			// 0: none , 1: wait STAkey, 2: finish DLS setup , set by driver only
-	BOOLEAN						Valid;			// 1: valid , 0: invalid , set by UI, use to setup or tear down DLS link
-} RT_802_11_DLS_UI, *PRT_802_11_DLS_UI;
-
-typedef struct _RT_802_11_DLS_INFO {
-	RT_802_11_DLS_UI	Entry[MAX_NUMBER_OF_DLS_ENTRY];
-	UCHAR				num;
-} RT_802_11_DLS_INFO, *PRT_802_11_DLS_INFO;
-
-typedef enum _RT_802_11_DLS_MODE {
-    DLS_NONE,
-    DLS_WAIT_KEY,
-    DLS_FINISH
-} RT_802_11_DLS_MODE;
-#endif // QOS_DLS_SUPPORT //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-#define	RT_ASSOC_EVENT_FLAG                         0x0101
-#define	RT_DISASSOC_EVENT_FLAG                      0x0102
-#define	RT_REQIE_EVENT_FLAG                         0x0103
-#define	RT_RESPIE_EVENT_FLAG                        0x0104
-#define	RT_ASSOCINFO_EVENT_FLAG                     0x0105
-#define RT_PMKIDCAND_FLAG                           0x0106
-#define RT_INTERFACE_DOWN                           0x0107
-#define RT_INTERFACE_UP                             0x0108
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-
-#define MAX_CUSTOM_LEN 128
-
-#ifdef CONFIG_STA_SUPPORT
-typedef enum _RT_802_11_D_CLIENT_MODE
-{
-   Rt802_11_D_None,
-   Rt802_11_D_Flexible,
-   Rt802_11_D_Strict,
-} RT_802_11_D_CLIENT_MODE, *PRT_802_11_D_CLIENT_MODE;
-#endif // CONFIG_STA_SUPPORT //
-
-typedef struct _RT_CHANNEL_LIST_INFO
-{
-	UCHAR ChannelList[MAX_NUM_OF_CHS];   // list all supported channels for site survey
-	UCHAR ChannelListNum; // number of channel in ChannelList[]
-} RT_CHANNEL_LIST_INFO, *PRT_CHANNEL_LIST_INFO;
-
-// WSC configured credential
-typedef	struct	_WSC_CREDENTIAL
-{
-	NDIS_802_11_SSID	SSID;				// mandatory
-	USHORT				AuthType;			// mandatory, 1: open, 2: wpa-psk, 4: shared, 8:wpa, 0x10: wpa2, 0x20: wpa2-psk
-	USHORT				EncrType;			// mandatory, 1: none, 2: wep, 4: tkip, 8: aes
-	UCHAR				Key[64];			// mandatory, Maximum 64 byte
-	USHORT				KeyLength;
-	UCHAR				MacAddr[6];			// mandatory, AP MAC address
-	UCHAR				KeyIndex;			// optional, default is 1
-	UCHAR				Rsvd[3];			// Make alignment
-}	WSC_CREDENTIAL, *PWSC_CREDENTIAL;
-
-// WSC configured profiles
-typedef	struct	_WSC_PROFILE
-{
-	UINT			ProfileCnt;
-	WSC_CREDENTIAL	Profile[8];				// Support up to 8 profiles
-}	WSC_PROFILE, *PWSC_PROFILE;
-
-
-#endif // _OID_H_
-
+#include "../rt2860/oid.h"
diff --git a/drivers/staging/rt2870/rt2870.h b/drivers/staging/rt2870/rt2870.h
index a69cf33..5e5b3f2 100644
--- a/drivers/staging/rt2870/rt2870.h
+++ b/drivers/staging/rt2870/rt2870.h
@@ -33,7 +33,6 @@
 
 /* rtmp_def.h */
 //
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
 #define BULKAGGRE_ZISE          100
 #define RT28XX_DRVDATA_SET(_a)                                             usb_set_intfdata(_a, pAd);
 #define RT28XX_PUT_DEVICE                                                  usb_put_dev
@@ -41,22 +40,15 @@
 #define RTUSB_SUBMIT_URB(pUrb)                                             usb_submit_urb(pUrb, GFP_ATOMIC)
 #define	RTUSB_URB_ALLOC_BUFFER(pUsb_Dev, BufSize, pDma_addr)               usb_buffer_alloc(pUsb_Dev, BufSize, GFP_ATOMIC, pDma_addr)
 #define	RTUSB_URB_FREE_BUFFER(pUsb_Dev, BufSize, pTransferBuf, Dma_addr)   usb_buffer_free(pUsb_Dev, BufSize, pTransferBuf, Dma_addr)
-#else
-#define BULKAGGRE_ZISE          60
-#define RT28XX_DRVDATA_SET(_a)
-#define RT28XX_PUT_DEVICE(dev_p)
-#define RTUSB_ALLOC_URB(iso)                                               usb_alloc_urb(iso)
-#define RTUSB_SUBMIT_URB(pUrb)                                             usb_submit_urb(pUrb)
-#define RTUSB_URB_ALLOC_BUFFER(pUsb_Dev, BufSize, pDma_addr)               kmalloc(BufSize, GFP_ATOMIC)
-#define	RTUSB_URB_FREE_BUFFER(pUsb_Dev, BufSize, pTransferBuf, Dma_addr)   kfree(pTransferBuf)
-#endif
 
 #define RXBULKAGGRE_ZISE        12
 #define MAX_TXBULK_LIMIT        (LOCAL_TXBUF_SIZE*(BULKAGGRE_ZISE-1))
 #define MAX_TXBULK_SIZE         (LOCAL_TXBUF_SIZE*BULKAGGRE_ZISE)
 #define MAX_RXBULK_SIZE         (LOCAL_TXBUF_SIZE*RXBULKAGGRE_ZISE)
 #define MAX_MLME_HANDLER_MEMORY 20
+#ifndef RT30xx
 #define	RETRY_LIMIT             10
+#endif
 #define BUFFER_SIZE				2400	//2048
 #define	TX_RING					0xa
 #define	PRIO_RING				0xc
@@ -72,6 +64,9 @@
 #define	fRTUSB_BULK_OUT_DATA_NORMAL_2			0x00020000
 #define	fRTUSB_BULK_OUT_DATA_NORMAL_3			0x00040000
 #define	fRTUSB_BULK_OUT_DATA_NORMAL_4			0x00080000
+#ifdef RT30xx
+#define	fRTUSB_BULK_OUT_DATA_NORMAL_5			0x00100000
+#endif
 
 #define	fRTUSB_BULK_OUT_PSPOLL					0x00000020
 #define	fRTUSB_BULK_OUT_DATA_FRAG				0x00000040
@@ -79,10 +74,7 @@
 #define	fRTUSB_BULK_OUT_DATA_FRAG_3				0x00000100
 #define	fRTUSB_BULK_OUT_DATA_FRAG_4				0x00000200
 
-#ifdef RALINK_ATE
-#define	fRTUSB_BULK_OUT_DATA_ATE				0x00100000
-#endif // RALINK_ATE //
-
+#ifndef RT30xx
 #define RT2870_USB_DEVICES	\
 {	\
 	{USB_DEVICE(0x148F,0x2770)}, /* Ralink */		\
@@ -148,6 +140,84 @@
 	{USB_DEVICE(0x7392,0x7717)}, /* Edimax */		\
 	{ }/* Terminating entry */                      \
 }
+#endif
+#ifdef RT30xx
+#define RT2870_USB_DEVICES	\
+{	\
+	{USB_DEVICE(0x148F,0x2770)}, /* Ralink */		\
+	{USB_DEVICE(0x148F,0x2870)}, /* Ralink */		\
+	{USB_DEVICE(0x148F,0x3070)}, /* Ralink 3070 */	\
+	{USB_DEVICE(0x148F,0x3071)}, /* Ralink 3071 */	\
+	{USB_DEVICE(0x148F,0x3072)}, /* Ralink 3072 */	\
+	{USB_DEVICE(0x0B05,0x1731)}, /* Asus */			\
+	{USB_DEVICE(0x0B05,0x1732)}, /* Asus */			\
+	{USB_DEVICE(0x0B05,0x1742)}, /* Asus */			\
+	{USB_DEVICE(0x0DF6,0x0017)}, /* Sitecom */		\
+	{USB_DEVICE(0x0DF6,0x002B)}, /* Sitecom */		\
+	{USB_DEVICE(0x0DF6,0x002C)}, /* Sitecom */		\
+	{USB_DEVICE(0x0DF6,0x003E)}, /* Sitecom 3070 */	\
+	{USB_DEVICE(0x0DF6,0x002D)}, /* Sitecom */		\
+	{USB_DEVICE(0x0DF6,0x0039)}, /* Sitecom 2770 */	\
+	{USB_DEVICE(0x14B2,0x3C06)}, /* Conceptronic */		\
+	{USB_DEVICE(0x14B2,0x3C28)}, /* Conceptronic */		\
+	{USB_DEVICE(0x2019,0xED06)}, /* Planex Communications, Inc. */		\
+	{USB_DEVICE(0x2019,0xAB25)}, /* Planex Communications, Inc. RT3070 */		\
+	{USB_DEVICE(0x07D1,0x3C09)}, /* D-Link */		\
+	{USB_DEVICE(0x07D1,0x3C11)}, /* D-Link */		\
+	{USB_DEVICE(0x2001,0x3C09)}, /* D-Link */		\
+	{USB_DEVICE(0x2001,0x3C0A)}, /* D-Link 3072*/	\
+	{USB_DEVICE(0x14B2,0x3C07)}, /* AL */			\
+	{USB_DEVICE(0x14B2,0x3C12)}, /* AL 3070 */		\
+	{USB_DEVICE(0x050D,0x8053)}, /* Belkin */		\
+	{USB_DEVICE(0x14B2,0x3C23)}, /* Airlink */		\
+	{USB_DEVICE(0x14B2,0x3C27)}, /* Airlink */		\
+	{USB_DEVICE(0x07AA,0x002F)}, /* Corega */		\
+	{USB_DEVICE(0x07AA,0x003C)}, /* Corega */		\
+	{USB_DEVICE(0x07AA,0x003F)}, /* Corega */		\
+	{USB_DEVICE(0x18C5,0x0012)}, /* Corega 3070 */	\
+	{USB_DEVICE(0x1044,0x800B)}, /* Gigabyte */		\
+	{USB_DEVICE(0x1044,0x800D)}, /* Gigabyte GN-WB32L 3070 */		\
+	{USB_DEVICE(0x15A9,0x0006)}, /* Sparklan */		\
+	{USB_DEVICE(0x083A,0xB522)}, /* SMC */			\
+	{USB_DEVICE(0x083A,0xA618)}, /* SMC */			\
+	{USB_DEVICE(0x083A,0x8522)}, /* Arcadyan */		\
+	{USB_DEVICE(0x083A,0x7512)}, /* Arcadyan 2770 */		\
+	{USB_DEVICE(0x083A,0x7522)}, /* Arcadyan */		\
+	{USB_DEVICE(0x083A,0x7511)}, /* Arcadyan 3070 */ \
+	{USB_DEVICE(0x0CDE,0x0022)}, /* ZCOM */			\
+	{USB_DEVICE(0x0586,0x3416)}, /* Zyxel */		\
+	{USB_DEVICE(0x0CDE,0x0025)}, /* Zyxel */		\
+	{USB_DEVICE(0x1740,0x9701)}, /* EnGenius */		\
+	{USB_DEVICE(0x1740,0x9702)}, /* EnGenius */		\
+	{USB_DEVICE(0x1740,0x9703)}, /* EnGenius 3070 */		\
+	{USB_DEVICE(0x0471,0x200f)}, /* Philips */		\
+	{USB_DEVICE(0x14B2,0x3C25)}, /* Draytek */		\
+	{USB_DEVICE(0x13D3,0x3247)}, /* AzureWave */	\
+	{USB_DEVICE(0x13D3,0x3273)}, /* AzureWave 3070*/	\
+	{USB_DEVICE(0x083A,0x6618)}, /* Accton */		\
+	{USB_DEVICE(0x15c5,0x0008)}, /* Amit */			\
+	{USB_DEVICE(0x0E66,0x0001)}, /* Hawking */		\
+	{USB_DEVICE(0x0E66,0x0003)}, /* Hawking */		\
+	{USB_DEVICE(0x129B,0x1828)}, /* Siemens */		\
+	{USB_DEVICE(0x157E,0x300E)},	/* U-Media */	\
+	{USB_DEVICE(0x050d,0x805c)},					\
+	{USB_DEVICE(0x1482,0x3C09)}, /* Abocom*/		\
+	{USB_DEVICE(0x14B2,0x3C09)}, /* Alpha */		\
+	{USB_DEVICE(0x04E8,0x2018)}, /* samsung */  	\
+	{USB_DEVICE(0x07B8,0x3070)}, /* AboCom 3070 */	\
+	{USB_DEVICE(0x07B8,0x3071)}, /* AboCom 3071 */	\
+	{USB_DEVICE(0x07B8,0x3072)}, /* Abocom 3072 */	\
+	{USB_DEVICE(0x7392,0x7711)}, /* Edimax 3070 */	\
+	{USB_DEVICE(0x5A57,0x0280)}, /* Zinwell */		\
+	{USB_DEVICE(0x5A57,0x0282)}, /* Zinwell */		\
+	{USB_DEVICE(0x1A32,0x0304)}, /* Quanta 3070 */		\
+	{USB_DEVICE(0x0789,0x0162)}, /* Logitec 2870 */		\
+	{USB_DEVICE(0x0789,0x0163)}, /* Logitec 2870 */		\
+	{USB_DEVICE(0x0789,0x0164)}, /* Logitec 2870 */		\
+	{USB_DEVICE(0x1EDA,0x2310)}, /* AirTies 3070 */		\
+	{ }/* Terminating entry */                      \
+}
+#endif
 
 #define	FREE_HTTX_RING(_p, _b, _t)			\
 {										\
@@ -161,30 +231,6 @@
 //
 // RXINFO appends at the end of each rx packet.
 //
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _RXINFO_STRUC {
-	UINT32		PlcpSignal:12;
-	UINT32		LastAMSDU:1;
-	UINT32		CipherAlg:1;
-	UINT32		PlcpRssil:1;
-	UINT32		Decrypted:1;
-	UINT32		AMPDU:1;		// To be moved
-	UINT32		L2PAD:1;
-	UINT32		RSSI:1;
-	UINT32		HTC:1;
-	UINT32		AMSDU:1;		// rx with 802.3 header, not 802.11 header.
-	UINT32		CipherErr:2;        // 0: decryption okay, 1:ICV error, 2:MIC error, 3:KEY not valid
-	UINT32		Crc:1;              // 1: CRC error
-	UINT32		MyBss:1;  	// 1: this frame belongs to the same BSSID
-	UINT32		Bcast:1;            // 1: this is a broadcast frame
-	UINT32		Mcast:1;            // 1: this is a multicast frame
-	UINT32		U2M:1;              // 1: this RX frame is unicast to me
-	UINT32		FRAG:1;
-	UINT32		NULLDATA:1;
-	UINT32		DATA:1;
-	UINT32		BA:1;
-}	RXINFO_STRUC, *PRXINFO_STRUC, RT28XX_RXD_STRUC, *PRT28XX_RXD_STRUC;
-#else
 typedef	struct	PACKED _RXINFO_STRUC {
 	UINT32		BA:1;
 	UINT32		DATA:1;
@@ -207,25 +253,10 @@
 	UINT32		LastAMSDU:1;
 	UINT32		PlcpSignal:12;
 }	RXINFO_STRUC, *PRXINFO_STRUC, RT28XX_RXD_STRUC, *PRT28XX_RXD_STRUC;
-#endif
-
 
 //
 // TXINFO
 //
-#ifdef RT_BIG_ENDIAN
-typedef	struct	_TXINFO_STRUC {
-	// Word	0
-	UINT32		USBDMATxburst:1;//used ONLY in USB bulk Aggre. Force USB DMA transmit frame from current selected endpoint
-	UINT32		USBDMANextVLD:1;	//used ONLY in USB bulk Aggregation, NextValid
-	UINT32		rsv2:2;  // Software use.
-	UINT32		SwUseLastRound:1; // Software use.
-	UINT32		QSEL:2;	// select on-chip FIFO ID for 2nd-stage output scheduler.0:MGMT, 1:HCCA 2:EDCA
-	UINT32		WIV:1;	// Wireless Info Valid. 1 if Driver already fill WI,  o if DMA needs to copy WI to correctposition
-	UINT32		rsv:8;
-	UINT32		USBDMATxPktLen:16;	//used ONLY in USB bulk Aggregation,  Total byte counts of all sub-frame.
-}	TXINFO_STRUC, *PTXINFO_STRUC;
-#else
 typedef	struct	_TXINFO_STRUC {
 	// Word	0
 	UINT32		USBDMATxPktLen:16;	//used ONLY in USB bulk Aggregation,  Total byte counts of all sub-frame.
@@ -237,7 +268,6 @@
 	UINT32		USBDMANextVLD:1;	//used ONLY in USB bulk Aggregation, NextValid
 	UINT32		USBDMATxburst:1;//used ONLY in USB bulk Aggre. Force USB DMA transmit frame from current selected endpoint
 }	TXINFO_STRUC, *PTXINFO_STRUC;
-#endif
 
 #define TXINFO_SIZE				4
 #define RXINFO_SIZE				4
@@ -254,6 +284,23 @@
 
 
 /* ----------------- EEPROM Related MACRO ----------------- */
+#ifdef RT30xx
+#define RT28xx_EEPROM_READ16(pAd, offset, var)					\
+	do {														\
+		RTUSBReadEEPROM(pAd, offset, (PUCHAR)&(var), 2);		\
+		if(!pAd->bUseEfuse)										\
+		var = le2cpu16(var);									\
+	}while(0)
+
+#define RT28xx_EEPROM_WRITE16(pAd, offset, var)					\
+	do{															\
+		USHORT _tmpVar=var;										\
+		if(!pAd->bUseEfuse)									\
+		_tmpVar = cpu2le16(var);								\
+		RTUSBWriteEEPROM(pAd, offset, (PUCHAR)&(_tmpVar), 2);	\
+	}while(0)
+#endif // RT30xx //
+#ifndef RT30xx
 #define RT28xx_EEPROM_READ16(pAd, offset, var)					\
 	do {														\
 		RTUSBReadEEPROM(pAd, offset, (PUCHAR)&(var), 2);		\
@@ -266,6 +313,7 @@
 		_tmpVar = cpu2le16(var);								\
 		RTUSBWriteEEPROM(pAd, offset, (PUCHAR)&(_tmpVar), 2);	\
 	}while(0)
+#endif // RT30xx //
 
 /* ----------------- TASK/THREAD Related MACRO ----------------- */
 #define RT28XX_TASK_THREAD_INIT(pAd, Status)		\
@@ -273,19 +321,8 @@
 
 
 /* ----------------- Frimware Related MACRO ----------------- */
-#if 0
-#define RT28XX_FIRMUD_INIT(pAd)		\
-	{	UINT32	MacReg;				\
-		RTUSBReadMACRegister(pAd, MAC_CSR0, &MacReg); }
-
-#define RT28XX_FIRMUD_END(pAd)	\
-	RTUSBWriteMACRegister(pAd, 0x7014, 0xffffffff);	\
-	RTUSBWriteMACRegister(pAd, 0x701c, 0xffffffff);	\
-	RTUSBFirmwareRun(pAd);
-#else
 #define RT28XX_WRITE_FIRMWARE(_pAd, _pFwImage, _FwLen)		\
 	RTUSBFirmwareWrite(_pAd, _pFwImage, _FwLen)
-#endif
 
 /* ----------------- TX Related MACRO ----------------- */
 #define RT28XX_START_DEQUEUE(pAd, QueIdx, irqFlags)				\
@@ -370,13 +407,6 @@
 /* ----------------- RX Related MACRO ----------------- */
 //#define RT28XX_RX_ERROR_CHECK				RTMPCheckRxWI
 
-#if 0
-#define RT28XX_RCV_INIT(pAd)					\
-	pAd->TransferBufferLength = 0;				\
-	pAd->ReadPosition = 0;						\
-	pAd->pCurrRxContext = NULL;
-#endif
-
 #define RT28XX_RV_ALL_BUF_END(bBulkReceive)		\
 	/* We return STATUS_MORE_PROCESSING_REQUIRED so that the completion */	\
 	/* routine (IofCompleteRequest) will stop working on the irp. */		\
@@ -384,27 +414,6 @@
 
 
 /* ----------------- ASIC Related MACRO ----------------- */
-#if 0
-#define RT28XX_DMA_WRITE_INIT(GloCfg)			\
-	{	GloCfg.field.EnTXWriteBackDDONE = 1;	\
-		GloCfg.field.EnableRxDMA = 1;			\
-		GloCfg.field.EnableTxDMA = 1; }
-
-#define RT28XX_DMA_POST_WRITE(_pAd)				\
-	do{	USB_DMA_CFG_STRUC	UsbCfg;				\
-		UsbCfg.word = 0;						\
-		/* for last packet, PBF might use more than limited, so minus 2 to prevent from error */ \
-		UsbCfg.field.RxBulkAggLmt = (MAX_RXBULK_SIZE /1024)-3;	\
-		UsbCfg.field.phyclear = 0;								\
-		/* usb version is 1.1,do not use bulk in aggregation */	\
-		if (_pAd->BulkInMaxPacketSize == 512)					\
-			UsbCfg.field.RxBulkAggEn = 1;						\
-		UsbCfg.field.RxBulkEn = 1;								\
-		UsbCfg.field.TxBulkEn = 1;								\
-		UsbCfg.field.RxBulkAggTOut = 0x80; /* 2006-10-18 */		\
-		RTUSBWriteMACRegister(_pAd, USB_DMA_CFG, UsbCfg.word); 	\
-	}while(0)
-#endif
 
 // reset MAC of a station entry to 0xFFFFFFFFFFFF
 #define RT28XX_STA_ENTRY_MAC_RESET(pAd, Wcid)					\
@@ -420,6 +429,14 @@
 	RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_SET_CLIENT_MAC_ENTRY, 	\
 							pEntry, sizeof(MAC_TABLE_ENTRY));
 
+#ifdef RT30xx
+// add by johnli, fix "in_interrupt" error when call "MacTableDeleteEntry" in Rx tasklet
+// Set MAC register value according operation mode
+#define RT28XX_UPDATE_PROTECT(pAd)	\
+ 	RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_UPDATE_PROTECT, NULL, 0);
+// end johnli
+#endif
+
 // remove Pair-wise key material from ASIC
 // yet implement
 #define RT28XX_STA_ENTRY_KEY_DEL(pAd, BssIdx, Wcid)
@@ -507,8 +524,10 @@
 
 #define RT28xx_CHIP_NAME            "RT2870"
 #define USB_CYC_CFG                 0x02a4
+#ifndef RT30xx
 #define STATUS_SUCCESS				0x00
 #define STATUS_UNSUCCESSFUL 		0x01
+#endif
 #define NT_SUCCESS(status)			(((status) > 0) ? (1):(0))
 #define InterlockedIncrement 	 	atomic_inc
 #define NdisInterlockedIncrement 	atomic_inc
@@ -533,7 +552,9 @@
 //#undef MlmeAllocateMemory
 //#undef MlmeFreeMemory
 
+#ifndef RT30xx
 typedef int				NTSTATUS;
+#endif
 typedef struct usb_device	* PUSB_DEV;
 
 /* MACRO for linux usb */
@@ -551,23 +572,9 @@
 #define UNLINK_TIMEOUT_MS		3
 
 /* unlink urb	*/
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,7)
 #define RTUSB_UNLINK_URB(pUrb)		usb_kill_urb(pUrb)
-#else
-#define RTUSB_UNLINK_URB(pUrb)		usb_unlink_urb(pUrb)
-#endif
 
 // Prototypes of completion funuc.
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-#define RTUSBBulkOutDataPacketComplete(purb, pt_regs)    RTUSBBulkOutDataPacketComplete(purb)
-#define RTUSBBulkOutMLMEPacketComplete(pUrb, pt_regs)    RTUSBBulkOutMLMEPacketComplete(pUrb)
-#define RTUSBBulkOutNullFrameComplete(pUrb, pt_regs)     RTUSBBulkOutNullFrameComplete(pUrb)
-#define RTUSBBulkOutRTSFrameComplete(pUrb, pt_regs)      RTUSBBulkOutRTSFrameComplete(pUrb)
-#define RTUSBBulkOutPsPollComplete(pUrb, pt_regs)        RTUSBBulkOutPsPollComplete(pUrb)
-#define RTUSBBulkRxComplete(pUrb, pt_regs)               RTUSBBulkRxComplete(pUrb)
-#endif
-
-
 VOID RTUSBBulkOutDataPacketComplete(purbb_t purb, struct pt_regs *pt_regs);
 VOID RTUSBBulkOutMLMEPacketComplete(purbb_t pUrb, struct pt_regs *pt_regs);
 VOID RTUSBBulkOutNullFrameComplete(purbb_t pUrb, struct pt_regs *pt_regs);
@@ -575,7 +582,7 @@
 VOID RTUSBBulkOutPsPollComplete(purbb_t pUrb, struct pt_regs *pt_regs);
 VOID RTUSBBulkRxComplete(purbb_t pUrb, struct pt_regs *pt_regs);
 
-
+#ifndef RT30xx
 #define RTUSBMlmeUp(pAd)	        \
 {								    \
 	POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;	\
@@ -591,7 +598,22 @@
 	CHECK_PID_LEGALITY(task_pid(pObj->RTUSBCmdThr_task))	    \
 	    up(&(pAd->RTUSBCmd_semaphore)); \
 }
+#endif
+#ifdef RT30xx
+#define RTUSBMlmeUp(pAd)	        \
+{								    \
+	POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;	\
+	if(pObj->MLMEThr_pid>0)		    \
+        up(&(pAd->mlme_semaphore)); \
+}
 
+#define RTUSBCMDUp(pAd)	                \
+{									    \
+	POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;	\
+	if(pObj->RTUSBCmdThr_pid>0)		    \
+	    up(&(pAd->RTUSBCmd_semaphore)); \
+}
+#endif
 
 static inline NDIS_STATUS RTMPAllocateMemory(
 	OUT PVOID *ptr,
@@ -633,7 +655,9 @@
 	ULONG WCID;          // mechanism for rekeying: 0:disable, 1: time-based, 2: packet-based
 	ULONG SetTid;        // time-based: seconds, packet-based: kilo-packets
 	ULONG DeleteTid;        // time-based: seconds, packet-based: kilo-packets
+#ifndef RT30xx
 	UCHAR Addr[MAC_ADDR_LEN];	// avoid in interrupt when write key
+#endif
 } RT_SET_ASIC_WCID,*PRT_SET_ASIC_WCID;
 
 typedef struct   _RT_SET_ASIC_WCID_ATTRI {
@@ -676,13 +700,6 @@
 	UINT32		CmdQState;
 }CmdQ, *PCmdQ;
 
-//
-// For WPA SUPPLICANT: WIRELESS EXT support wireless events: v14 or newer
-//
-#if WIRELESS_EXT >= 14
-//#define WPA_SUPPLICANT_SUPPORT  1
-#endif
-
 /* oid.h */
 // Cipher suite type for mixed mode group cipher, P802.11i-2004
 typedef enum _RT_802_11_CIPHER_SUITE_TYPE {
@@ -742,6 +759,11 @@
 #define CMDTHREAD_802_11_SET_PREAMBLE               0x0D790101	// cmd
 #define CMDTHREAD_802_11_COUNTER_MEASURE			0x0D790102	// cmd
 
+#ifdef RT30xx
+// add by johnli, fix "in_interrupt" error when call "MacTableDeleteEntry" in Rx tasklet
+#define CMDTHREAD_UPDATE_PROTECT					0x0D790103	// cmd
+// end johnli
+#endif
 
 #define WPA1AKMBIT	    0x01
 #define WPA2AKMBIT	    0x02
diff --git a/drivers/staging/rt2870/rt28xx.h b/drivers/staging/rt2870/rt28xx.h
index 3927d22..29bad95 100644
--- a/drivers/staging/rt2870/rt28xx.h
+++ b/drivers/staging/rt2870/rt28xx.h
@@ -1,2689 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rt28xx.h
-
-	Abstract:
-	RT28xx ASIC related definition & structures
-
-	Revision History:
-	Who			When		  What
-	--------	----------	  ----------------------------------------------
-       Jan Lee           Jan-3-2006     created for RT2860c
-*/
-
-#ifndef	__RT28XX_H__
-#define	__RT28XX_H__
-
-
-//
-// PCI registers - base address 0x0000
-//
-#define PCI_CFG			0x0000
-#define PCI_EECTRL			0x0004
-#define PCI_MCUCTRL			0x0008
-
-//
-// SCH/DMA registers - base address 0x0200
-//
-// INT_SOURCE_CSR: Interrupt source register. Write one to clear corresponding bit
-//
-#define DMA_CSR0      0x200
-#define INT_SOURCE_CSR      0x200
-#ifdef RT_BIG_ENDIAN
-typedef	union	_INT_SOURCE_CSR_STRUC	{
-	struct	{
-		UINT32       	:14;
-		UINT32       	TxCoherent:1;
-		UINT32       	RxCoherent:1;
-		UINT32       	GPTimer:1;
-		UINT32       	AutoWakeup:1;//bit14
-		UINT32       	TXFifoStatusInt:1;//FIFO Statistics is full, sw should read 0x171c
-		UINT32       	PreTBTT:1;
-		UINT32       	TBTTInt:1;
-		UINT32       	RxTxCoherent:1;
-		UINT32       	MCUCommandINT:1;
-		UINT32       	MgmtDmaDone:1;
-		UINT32       	HccaDmaDone:1;
-		UINT32       	Ac3DmaDone:1;
-		UINT32       	Ac2DmaDone:1;
-		UINT32       	Ac1DmaDone:1;
-		UINT32		Ac0DmaDone:1;
-		UINT32		RxDone:1;
-		UINT32		TxDelayINT:1;	//delayed interrupt, not interrupt until several int or time limit hit
-		UINT32		RxDelayINT:1; //dealyed interrupt
-	}	field;
-	UINT32			word;
-}	INT_SOURCE_CSR_STRUC, *PINT_SOURCE_CSR_STRUC;
-#else
-typedef	union	_INT_SOURCE_CSR_STRUC	{
-	struct	{
-		UINT32		RxDelayINT:1;
-		UINT32		TxDelayINT:1;
-		UINT32		RxDone:1;
-		UINT32		Ac0DmaDone:1;//4
-		UINT32       	Ac1DmaDone:1;
-		UINT32       	Ac2DmaDone:1;
-		UINT32       	Ac3DmaDone:1;
-		UINT32       	HccaDmaDone:1; // bit7
-		UINT32       	MgmtDmaDone:1;
-		UINT32       	MCUCommandINT:1;//bit 9
-		UINT32       	RxTxCoherent:1;
-		UINT32       	TBTTInt:1;
-		UINT32       	PreTBTT:1;
-		UINT32       	TXFifoStatusInt:1;//FIFO Statistics is full, sw should read 0x171c
-		UINT32       	AutoWakeup:1;//bit14
-		UINT32       	GPTimer:1;
-		UINT32       	RxCoherent:1;//bit16
-		UINT32       	TxCoherent:1;
-		UINT32       	:14;
-	}	field;
-	UINT32			word;
-} INT_SOURCE_CSR_STRUC, *PINT_SOURCE_CSR_STRUC;
-#endif
-
-//
-// INT_MASK_CSR:   Interrupt MASK register.   1: the interrupt is mask OFF
-//
-#define INT_MASK_CSR        0x204
-#ifdef RT_BIG_ENDIAN
-typedef	union	_INT_MASK_CSR_STRUC	{
-	struct	{
-		UINT32       	TxCoherent:1;
-		UINT32       	RxCoherent:1;
-		UINT32       	:20;
-		UINT32       	MCUCommandINT:1;
-		UINT32       	MgmtDmaDone:1;
-		UINT32       	HccaDmaDone:1;
-		UINT32       	Ac3DmaDone:1;
-		UINT32       	Ac2DmaDone:1;
-		UINT32       	Ac1DmaDone:1;
-		UINT32		Ac0DmaDone:1;
-		UINT32		RxDone:1;
-		UINT32		TxDelay:1;
-		UINT32		RXDelay_INT_MSK:1;
-	}	field;
-	UINT32			word;
-}INT_MASK_CSR_STRUC, *PINT_MASK_CSR_STRUC;
-#else
-typedef	union	_INT_MASK_CSR_STRUC	{
-	struct	{
-		UINT32		RXDelay_INT_MSK:1;
-		UINT32		TxDelay:1;
-		UINT32		RxDone:1;
-		UINT32		Ac0DmaDone:1;
-		UINT32       	Ac1DmaDone:1;
-		UINT32       	Ac2DmaDone:1;
-		UINT32       	Ac3DmaDone:1;
-		UINT32       	HccaDmaDone:1;
-		UINT32       	MgmtDmaDone:1;
-		UINT32       	MCUCommandINT:1;
-		UINT32       	:20;
-		UINT32       	RxCoherent:1;
-		UINT32       	TxCoherent:1;
-	}	field;
-	UINT32			word;
-} INT_MASK_CSR_STRUC, *PINT_MASK_CSR_STRUC;
-#endif
-#define WPDMA_GLO_CFG 	0x208
-#ifdef RT_BIG_ENDIAN
-typedef	union	_WPDMA_GLO_CFG_STRUC	{
-	struct	{
-		UINT32       	HDR_SEG_LEN:16;
-		UINT32       	RXHdrScater:8;
-		UINT32       	BigEndian:1;
-		UINT32       	EnTXWriteBackDDONE:1;
-		UINT32       	WPDMABurstSIZE:2;
-		UINT32		RxDMABusy:1;
-		UINT32		EnableRxDMA:1;
-		UINT32		TxDMABusy:1;
-		UINT32		EnableTxDMA:1;
-	}	field;
-	UINT32			word;
-}WPDMA_GLO_CFG_STRUC, *PWPDMA_GLO_CFG_STRUC;
-#else
-typedef	union	_WPDMA_GLO_CFG_STRUC	{
-	struct	{
-		UINT32		EnableTxDMA:1;
-		UINT32		TxDMABusy:1;
-		UINT32		EnableRxDMA:1;
-		UINT32		RxDMABusy:1;
-		UINT32       	WPDMABurstSIZE:2;
-		UINT32       	EnTXWriteBackDDONE:1;
-		UINT32       	BigEndian:1;
-		UINT32       	RXHdrScater:8;
-		UINT32       	HDR_SEG_LEN:16;
-	}	field;
-	UINT32			word;
-} WPDMA_GLO_CFG_STRUC, *PWPDMA_GLO_CFG_STRUC;
-#endif
-#define WPDMA_RST_IDX 	0x20c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_WPDMA_RST_IDX_STRUC	{
-	struct	{
-		UINT32       	:15;
-		UINT32       	RST_DRX_IDX0:1;
-		UINT32       	rsv:10;
-		UINT32       	RST_DTX_IDX5:1;
-		UINT32       	RST_DTX_IDX4:1;
-		UINT32		RST_DTX_IDX3:1;
-		UINT32		RST_DTX_IDX2:1;
-		UINT32		RST_DTX_IDX1:1;
-		UINT32		RST_DTX_IDX0:1;
-	}	field;
-	UINT32			word;
-}WPDMA_RST_IDX_STRUC, *PWPDMA_RST_IDX_STRUC;
-#else
-typedef	union	_WPDMA_RST_IDX_STRUC	{
-	struct	{
-		UINT32		RST_DTX_IDX0:1;
-		UINT32		RST_DTX_IDX1:1;
-		UINT32		RST_DTX_IDX2:1;
-		UINT32		RST_DTX_IDX3:1;
-		UINT32       	RST_DTX_IDX4:1;
-		UINT32       	RST_DTX_IDX5:1;
-		UINT32       	rsv:10;
-		UINT32       	RST_DRX_IDX0:1;
-		UINT32       	:15;
-	}	field;
-	UINT32			word;
-} WPDMA_RST_IDX_STRUC, *PWPDMA_RST_IDX_STRUC;
-#endif
-#define DELAY_INT_CFG  0x0210
-#ifdef RT_BIG_ENDIAN
-typedef	union	_DELAY_INT_CFG_STRUC	{
-	struct	{
-		UINT32       	TXDLY_INT_EN:1;
-		UINT32       	TXMAX_PINT:7;
-		UINT32       	TXMAX_PTIME:8;
-		UINT32       	RXDLY_INT_EN:1;
-		UINT32       	RXMAX_PINT:7;
-		UINT32		RXMAX_PTIME:8;
-	}	field;
-	UINT32			word;
-}DELAY_INT_CFG_STRUC, *PDELAY_INT_CFG_STRUC;
-#else
-typedef	union	_DELAY_INT_CFG_STRUC	{
-	struct	{
-		UINT32		RXMAX_PTIME:8;
-		UINT32       	RXMAX_PINT:7;
-		UINT32       	RXDLY_INT_EN:1;
-		UINT32       	TXMAX_PTIME:8;
-		UINT32       	TXMAX_PINT:7;
-		UINT32       	TXDLY_INT_EN:1;
-	}	field;
-	UINT32			word;
-} DELAY_INT_CFG_STRUC, *PDELAY_INT_CFG_STRUC;
-#endif
-#define WMM_AIFSN_CFG   0x0214
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AIFSN_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:16;
-	    UINT32   Aifsn3:4;       // for AC_VO
-	    UINT32   Aifsn2:4;       // for AC_VI
-	    UINT32   Aifsn1:4;       // for AC_BK
-	    UINT32   Aifsn0:4;       // for AC_BE
-	}	field;
-	UINT32			word;
-}	AIFSN_CSR_STRUC, *PAIFSN_CSR_STRUC;
-#else
-typedef	union	_AIFSN_CSR_STRUC	{
-	struct	{
-	    UINT32   Aifsn0:4;       // for AC_BE
-	    UINT32   Aifsn1:4;       // for AC_BK
-	    UINT32   Aifsn2:4;       // for AC_VI
-	    UINT32   Aifsn3:4;       // for AC_VO
-	    UINT32   Rsv:16;
-	}	field;
-	UINT32			word;
-}	AIFSN_CSR_STRUC, *PAIFSN_CSR_STRUC;
-#endif
-//
-// CWMIN_CSR: CWmin for each EDCA AC
-//
-#define WMM_CWMIN_CFG   0x0218
-#ifdef RT_BIG_ENDIAN
-typedef	union	_CWMIN_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:16;
-	    UINT32   Cwmin3:4;       // for AC_VO
-	    UINT32   Cwmin2:4;       // for AC_VI
-	    UINT32   Cwmin1:4;       // for AC_BK
-	    UINT32   Cwmin0:4;       // for AC_BE
-	}	field;
-	UINT32			word;
-}	CWMIN_CSR_STRUC, *PCWMIN_CSR_STRUC;
-#else
-typedef	union	_CWMIN_CSR_STRUC	{
-	struct	{
-	    UINT32   Cwmin0:4;       // for AC_BE
-	    UINT32   Cwmin1:4;       // for AC_BK
-	    UINT32   Cwmin2:4;       // for AC_VI
-	    UINT32   Cwmin3:4;       // for AC_VO
-	    UINT32   Rsv:16;
-	}	field;
-	UINT32			word;
-}	CWMIN_CSR_STRUC, *PCWMIN_CSR_STRUC;
-#endif
-
-//
-// CWMAX_CSR: CWmin for each EDCA AC
-//
-#define WMM_CWMAX_CFG   0x021c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_CWMAX_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:16;
-	    UINT32   Cwmax3:4;       // for AC_VO
-	    UINT32   Cwmax2:4;       // for AC_VI
-	    UINT32   Cwmax1:4;       // for AC_BK
-	    UINT32   Cwmax0:4;       // for AC_BE
-	}	field;
-	UINT32			word;
-}	CWMAX_CSR_STRUC, *PCWMAX_CSR_STRUC;
-#else
-typedef	union	_CWMAX_CSR_STRUC	{
-	struct	{
-	    UINT32   Cwmax0:4;       // for AC_BE
-	    UINT32   Cwmax1:4;       // for AC_BK
-	    UINT32   Cwmax2:4;       // for AC_VI
-	    UINT32   Cwmax3:4;       // for AC_VO
-	    UINT32   Rsv:16;
-	}	field;
-	UINT32			word;
-}	CWMAX_CSR_STRUC, *PCWMAX_CSR_STRUC;
-#endif
-
-
-//
-// AC_TXOP_CSR0: AC_BK/AC_BE TXOP register
-//
-#define WMM_TXOP0_CFG    0x0220
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AC_TXOP_CSR0_STRUC	{
-	struct	{
-	    USHORT  Ac1Txop;        // for AC_BE, in unit of 32us
-	    USHORT  Ac0Txop;        // for AC_BK, in unit of 32us
-	}	field;
-	UINT32			word;
-}	AC_TXOP_CSR0_STRUC, *PAC_TXOP_CSR0_STRUC;
-#else
-typedef	union	_AC_TXOP_CSR0_STRUC	{
-	struct	{
-	    USHORT  Ac0Txop;        // for AC_BK, in unit of 32us
-	    USHORT  Ac1Txop;        // for AC_BE, in unit of 32us
-	}	field;
-	UINT32			word;
-}	AC_TXOP_CSR0_STRUC, *PAC_TXOP_CSR0_STRUC;
-#endif
-
-//
-// AC_TXOP_CSR1: AC_VO/AC_VI TXOP register
-//
-#define WMM_TXOP1_CFG    0x0224
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AC_TXOP_CSR1_STRUC	{
-	struct	{
-	    USHORT  Ac3Txop;        // for AC_VO, in unit of 32us
-	    USHORT  Ac2Txop;        // for AC_VI, in unit of 32us
-	}	field;
-	UINT32			word;
-}	AC_TXOP_CSR1_STRUC, *PAC_TXOP_CSR1_STRUC;
-#else
-typedef	union	_AC_TXOP_CSR1_STRUC	{
-	struct	{
-	    USHORT  Ac2Txop;        // for AC_VI, in unit of 32us
-	    USHORT  Ac3Txop;        // for AC_VO, in unit of 32us
-	}	field;
-	UINT32			word;
-}	AC_TXOP_CSR1_STRUC, *PAC_TXOP_CSR1_STRUC;
-#endif
-#define RINGREG_DIFF			0x10
-#define GPIO_CTRL_CFG    0x0228	//MAC_CSR13
-#define MCU_CMD_CFG    0x022c
-#define TX_BASE_PTR0     0x0230	//AC_BK base address
-#define TX_MAX_CNT0      0x0234
-#define TX_CTX_IDX0       0x0238
-#define TX_DTX_IDX0      0x023c
-#define TX_BASE_PTR1     0x0240 	//AC_BE base address
-#define TX_MAX_CNT1      0x0244
-#define TX_CTX_IDX1       0x0248
-#define TX_DTX_IDX1      0x024c
-#define TX_BASE_PTR2     0x0250 	//AC_VI base address
-#define TX_MAX_CNT2      0x0254
-#define TX_CTX_IDX2       0x0258
-#define TX_DTX_IDX2      0x025c
-#define TX_BASE_PTR3     0x0260 	//AC_VO base address
-#define TX_MAX_CNT3      0x0264
-#define TX_CTX_IDX3       0x0268
-#define TX_DTX_IDX3      0x026c
-#define TX_BASE_PTR4     0x0270 	//HCCA base address
-#define TX_MAX_CNT4      0x0274
-#define TX_CTX_IDX4       0x0278
-#define TX_DTX_IDX4      0x027c
-#define TX_BASE_PTR5     0x0280 	//MGMT base address
-#define  TX_MAX_CNT5     0x0284
-#define TX_CTX_IDX5       0x0288
-#define TX_DTX_IDX5      0x028c
-#define TX_MGMTMAX_CNT      TX_MAX_CNT5
-#define TX_MGMTCTX_IDX       TX_CTX_IDX5
-#define TX_MGMTDTX_IDX      TX_DTX_IDX5
-#define RX_BASE_PTR     0x0290 	//RX base address
-#define RX_MAX_CNT      0x0294
-#define RX_CRX_IDX       0x0298
-#define RX_DRX_IDX      0x029c
-#define USB_DMA_CFG      0x02a0
-#ifdef RT_BIG_ENDIAN
-typedef	union	_USB_DMA_CFG_STRUC	{
-	struct	{
-	    UINT32  TxBusy:1;   	//USB DMA TX FSM busy . debug only
-	    UINT32  RxBusy:1;        //USB DMA RX FSM busy . debug only
-	    UINT32  EpoutValid:6;        //OUT endpoint data valid. debug only
-	    UINT32  TxBulkEn:1;        //Enable USB DMA Tx
-	    UINT32  RxBulkEn:1;        //Enable USB DMA Rx
-	    UINT32  RxBulkAggEn:1;        //Enable Rx Bulk Aggregation
-	    UINT32  TxopHalt:1;        //Halt TXOP count down when TX buffer is full.
-	    UINT32  TxClear:1;        //Clear USB DMA TX path
-	    UINT32  rsv:2;
-	    UINT32  phyclear:1;        		//phy watch dog enable. write 1
-	    UINT32  RxBulkAggLmt:8;        //Rx Bulk Aggregation Limit  in unit of 1024 bytes
-	    UINT32  RxBulkAggTOut:8;        //Rx Bulk Aggregation TimeOut  in unit of 33ns
-	}	field;
-	UINT32			word;
-}	USB_DMA_CFG_STRUC, *PUSB_DMA_CFG_STRUC;
-#else
-typedef	union	_USB_DMA_CFG_STRUC	{
-	struct	{
-	    UINT32  RxBulkAggTOut:8;        //Rx Bulk Aggregation TimeOut  in unit of 33ns
-	    UINT32  RxBulkAggLmt:8;        //Rx Bulk Aggregation Limit  in unit of 256 bytes
-	    UINT32  phyclear:1;        		//phy watch dog enable. write 1
-	    UINT32  rsv:2;
-	    UINT32  TxClear:1;        //Clear USB DMA TX path
-	    UINT32  TxopHalt:1;        //Halt TXOP count down when TX buffer is full.
-	    UINT32  RxBulkAggEn:1;        //Enable Rx Bulk Aggregation
-	    UINT32  RxBulkEn:1;        //Enable USB DMA Rx
-	    UINT32  TxBulkEn:1;        //Enable USB DMA Tx
-	    UINT32  EpoutValid:6;        //OUT endpoint data valid
-	    UINT32  RxBusy:1;        //USB DMA RX FSM busy
-	    UINT32  TxBusy:1;   	//USB DMA TX FSM busy
-	}	field;
-	UINT32			word;
-}	USB_DMA_CFG_STRUC, *PUSB_DMA_CFG_STRUC;
-#endif
-
-//
-//  3  PBF  registers
-//
-//
-// Most are for debug. Driver doesn't touch PBF register.
-#define 	PBF_SYS_CTRL 	 0x0400
-#define     PBF_CFG                 0x0408
-#define 	PBF_MAX_PCNT 	 0x040C
-#define 	PBF_CTRL	 	0x0410
-#define 	PBF_INT_STA	 0x0414
-#define 	PBF_INT_ENA	 0x0418
-#define 	TXRXQ_PCNT  	 0x0438
-#define 	PBF_DBG 	 	 0x043c
-#define     PBF_CAP_CTRL     0x0440
-
-//
-//  4  MAC  registers
-//
-//
-//  4.1 MAC SYSTEM  configuration registers (offset:0x1000)
-//
-#define MAC_CSR0            0x1000
-#ifdef RT_BIG_ENDIAN
-typedef	union	_ASIC_VER_ID_STRUC	{
-	struct	{
-	    USHORT  ASICVer;        // version : 2860
-	    USHORT  ASICRev;        // reversion  : 0
-	}	field;
-	UINT32			word;
-}	ASIC_VER_ID_STRUC, *PASIC_VER_ID_STRUC;
-#else
-typedef	union	_ASIC_VER_ID_STRUC	{
-	struct	{
-	    USHORT  ASICRev;        // reversion  : 0
-	    USHORT  ASICVer;        // version : 2860
-	}	field;
-	UINT32			word;
-}	ASIC_VER_ID_STRUC, *PASIC_VER_ID_STRUC;
-#endif
-#define MAC_SYS_CTRL            0x1004		//MAC_CSR1
-#define MAC_ADDR_DW0            		0x1008		// MAC ADDR DW0
-#define MAC_ADDR_DW1           		 0x100c		// MAC ADDR DW1
-//
-// MAC_CSR2: STA MAC register 0
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MAC_DW0_STRUC	{
-	struct	{
-		UCHAR		Byte3;		// MAC address byte 3
-		UCHAR		Byte2;		// MAC address byte 2
-		UCHAR		Byte1;		// MAC address byte 1
-		UCHAR		Byte0;		// MAC address byte 0
-	}	field;
-	UINT32			word;
-}	MAC_DW0_STRUC, *PMAC_DW0_STRUC;
-#else
-typedef	union	_MAC_DW0_STRUC	{
-	struct	{
-		UCHAR		Byte0;		// MAC address byte 0
-		UCHAR		Byte1;		// MAC address byte 1
-		UCHAR		Byte2;		// MAC address byte 2
-		UCHAR		Byte3;		// MAC address byte 3
-	}	field;
-	UINT32			word;
-}	MAC_DW0_STRUC, *PMAC_DW0_STRUC;
-#endif
-
-//
-// MAC_CSR3: STA MAC register 1
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MAC_DW1_STRUC	{
-	struct	{
-		UCHAR		Rsvd1;
-		UCHAR		U2MeMask;
-		UCHAR		Byte5;		// MAC address byte 5
-		UCHAR		Byte4;		// MAC address byte 4
-	}	field;
-	UINT32			word;
-}	MAC_DW1_STRUC, *PMAC_DW1_STRUC;
-#else
-typedef	union	_MAC_DW1_STRUC	{
-	struct	{
-		UCHAR		Byte4;		// MAC address byte 4
-		UCHAR		Byte5;		// MAC address byte 5
-		UCHAR		U2MeMask;
-		UCHAR		Rsvd1;
-	}	field;
-	UINT32			word;
-}	MAC_DW1_STRUC, *PMAC_DW1_STRUC;
-#endif
-
-#define MAC_BSSID_DW0            		0x1010		// MAC BSSID DW0
-#define MAC_BSSID_DW1            		0x1014		// MAC BSSID DW1
-
-//
-// MAC_CSR5: BSSID register 1
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MAC_CSR5_STRUC	{
-	struct	{
-		USHORT		Rsvd:11;
-		USHORT		MBssBcnNum:3;
-		USHORT		BssIdMode:2; // 0: one BSSID, 10: 4 BSSID,  01: 2 BSSID , 11: 8BSSID
-		UCHAR		Byte5;		 // BSSID byte 5
-		UCHAR		Byte4;		 // BSSID byte 4
-	}	field;
-	UINT32			word;
-}	MAC_CSR5_STRUC, *PMAC_CSR5_STRUC;
-#else
-typedef	union	_MAC_CSR5_STRUC	{
-	struct	{
-		UCHAR		Byte4;		 // BSSID byte 4
-		UCHAR		Byte5;		 // BSSID byte 5
-		USHORT      	BssIdMask:2; // 0: one BSSID, 10: 4 BSSID,  01: 2 BSSID , 11: 8BSSID
-		USHORT		MBssBcnNum:3;
-		USHORT		Rsvd:11;
-	}	field;
-	UINT32			word;
-}	MAC_CSR5_STRUC, *PMAC_CSR5_STRUC;
-#endif
-
-#define MAX_LEN_CFG              0x1018		// rt2860b max 16k bytes. bit12:13 Maximum PSDU length (power factor) 0:2^13, 1:2^14, 2:2^15, 3:2^16
-#define BBP_CSR_CFG            		0x101c		//
-//
-// BBP_CSR_CFG: BBP serial control register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_BBP_CSR_CFG_STRUC	{
-	struct	{
-		UINT32		:12;
-		UINT32		BBP_RW_MODE:1;		// 0: use serial mode  1:parallel
-		UINT32		BBP_PAR_DUR:1;		    // 0: 4 MAC clock cycles  1: 8 MAC clock cycles
-		UINT32		Busy:1;				// 1: ASIC is busy execute BBP programming.
-		UINT32		fRead:1;		    // 0: Write	BBP, 1:	Read BBP
-		UINT32		RegNum:8;			// Selected	BBP	register
-		UINT32		Value:8;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	BBP_CSR_CFG_STRUC, *PBBP_CSR_CFG_STRUC;
-#else
-typedef	union	_BBP_CSR_CFG_STRUC	{
-	struct	{
-		UINT32		Value:8;			// Register	value to program into BBP
-		UINT32		RegNum:8;			// Selected	BBP	register
-		UINT32		fRead:1;		    // 0: Write	BBP, 1:	Read BBP
-		UINT32		Busy:1;				// 1: ASIC is busy execute BBP programming.
-		UINT32		BBP_PAR_DUR:1;		     // 0: 4 MAC clock cycles  1: 8 MAC clock cycles
-		UINT32		BBP_RW_MODE:1;		// 0: use serial mode  1:parallel
-		UINT32		:12;
-	}	field;
-	UINT32			word;
-}	BBP_CSR_CFG_STRUC, *PBBP_CSR_CFG_STRUC;
-#endif
-#define RF_CSR_CFG0            		0x1020
-//
-// RF_CSR_CFG: RF control register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG0_STRUC	{
-	struct	{
-		UINT32		Busy:1;		    // 0: idle 1: 8busy
-		UINT32		Sel:1;				// 0:RF_LE0 activate  1:RF_LE1 activate
-		UINT32		StandbyMode:1;		    // 0: high when stand by 1:	low when standby
-		UINT32		bitwidth:5;			// Selected	BBP	register
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG0_STRUC, *PRF_CSR_CFG0_STRUC;
-#else
-typedef	union	_RF_CSR_CFG0_STRUC	{
-	struct	{
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-		UINT32		bitwidth:5;			// Selected	BBP	register
-		UINT32		StandbyMode:1;		    // 0: high when stand by 1:	low when standby
-		UINT32		Sel:1;				// 0:RF_LE0 activate  1:RF_LE1 activate
-		UINT32		Busy:1;		    // 0: idle 1: 8busy
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG0_STRUC, *PRF_CSR_CFG0_STRUC;
-#endif
-#define RF_CSR_CFG1           		0x1024
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG1_STRUC	{
-	struct	{
-		UINT32		rsv:7;		    // 0: idle 1: 8busy
-		UINT32		RFGap:5;			// Gap between BB_CONTROL_RF and RF_LE. 0: 3 system clock cycle (37.5usec) 1: 5 system clock cycle (62.5usec)
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG1_STRUC, *PRF_CSR_CFG1_STRUC;
-#else
-typedef	union	_RF_CSR_CFG1_STRUC	{
-	struct	{
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-		UINT32		RFGap:5;			// Gap between BB_CONTROL_RF and RF_LE. 0: 3 system clock cycle (37.5usec) 1: 5 system clock cycle (62.5usec)
-		UINT32		rsv:7;		    // 0: idle 1: 8busy
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG1_STRUC, *PRF_CSR_CFG1_STRUC;
-#endif
-#define RF_CSR_CFG2           		0x1028		//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG2_STRUC	{
-	struct	{
-		UINT32		rsv:8;		    // 0: idle 1: 8busy
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG2_STRUC, *PRF_CSR_CFG2_STRUC;
-#else
-typedef	union	_RF_CSR_CFG2_STRUC	{
-	struct	{
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-		UINT32		rsv:8;		    // 0: idle 1: 8busy
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG2_STRUC, *PRF_CSR_CFG2_STRUC;
-#endif
-#define LED_CFG           		0x102c		//  MAC_CSR14
-#ifdef RT_BIG_ENDIAN
-typedef	union	_LED_CFG_STRUC	{
-	struct	{
-		UINT32		:1;
-		UINT32		LedPolar:1;			// Led Polarity.  0: active low1: active high
-		UINT32		YLedMode:2;			// yellow Led Mode
-		UINT32		GLedMode:2;			// green Led Mode
-		UINT32		RLedMode:2;			// red Led Mode    0: off1: blinking upon TX2: periodic slow blinking3: always on
-		UINT32		rsv:2;
-		UINT32		SlowBlinkPeriod:6;			// slow blinking period. unit:1ms
-		UINT32		OffPeriod:8;			// blinking off period unit 1ms
-		UINT32		OnPeriod:8;			// blinking on period unit 1ms
-	}	field;
-	UINT32			word;
-}	LED_CFG_STRUC, *PLED_CFG_STRUC;
-#else
-typedef	union	_LED_CFG_STRUC	{
-	struct	{
-		UINT32		OnPeriod:8;			// blinking on period unit 1ms
-		UINT32		OffPeriod:8;			// blinking off period unit 1ms
-		UINT32		SlowBlinkPeriod:6;			// slow blinking period. unit:1ms
-		UINT32		rsv:2;
-		UINT32		RLedMode:2;			// red Led Mode    0: off1: blinking upon TX2: periodic slow blinking3: always on
-		UINT32		GLedMode:2;			// green Led Mode
-		UINT32		YLedMode:2;			// yellow Led Mode
-		UINT32		LedPolar:1;			// Led Polarity.  0: active low1: active high
-		UINT32		:1;
-	}	field;
-	UINT32			word;
-}	LED_CFG_STRUC, *PLED_CFG_STRUC;
-#endif
-//
-//  4.2 MAC TIMING  configuration registers (offset:0x1100)
-//
-#define XIFS_TIME_CFG             0x1100		 // MAC_CSR8  MAC_CSR9
-#ifdef RT_BIG_ENDIAN
-typedef	union	_IFS_SLOT_CFG_STRUC	{
-	struct	{
-	    UINT32  rsv:2;
-	    UINT32  BBRxendEnable:1;        //  reference RXEND signal to begin XIFS defer
-	    UINT32  EIFS:9;        //  unit 1us
-	    UINT32  OfdmXifsTime:4;        //OFDM SIFS. unit 1us. Applied after OFDM RX when MAC doesn't reference BBP signal BBRXEND
-	    UINT32  OfdmSifsTime:8;        //  unit 1us. Applied after OFDM RX/TX
-	    UINT32  CckmSifsTime:8;        //  unit 1us. Applied after CCK RX/TX
-	}	field;
-	UINT32			word;
-}	IFS_SLOT_CFG_STRUC, *PIFS_SLOT_CFG_STRUC;
-#else
-typedef	union	_IFS_SLOT_CFG_STRUC	{
-	struct	{
-	    UINT32  CckmSifsTime:8;        //  unit 1us. Applied after CCK RX/TX
-	    UINT32  OfdmSifsTime:8;        //  unit 1us. Applied after OFDM RX/TX
-	    UINT32  OfdmXifsTime:4;        //OFDM SIFS. unit 1us. Applied after OFDM RX when MAC doesn't reference BBP signal BBRXEND
-	    UINT32  EIFS:9;        //  unit 1us
-	    UINT32  BBRxendEnable:1;        //  reference RXEND signal to begin XIFS defer
-	    UINT32  rsv:2;
-	}	field;
-	UINT32			word;
-}	IFS_SLOT_CFG_STRUC, *PIFS_SLOT_CFG_STRUC;
-#endif
-
-#define BKOFF_SLOT_CFG             0x1104		 //  mac_csr9 last 8 bits
-#define NAV_TIME_CFG             0x1108		 // NAV  (MAC_CSR15)
-#define CH_TIME_CFG             0x110C		 	// Count as channel busy
-#define PBF_LIFE_TIMER             0x1110		 //TX/RX MPDU timestamp timer (free run)Unit: 1us
-#define BCN_TIME_CFG             0x1114		 // TXRX_CSR9
-
-#define BCN_OFFSET0				0x042C
-#define BCN_OFFSET1				0x0430
-
-//
-// BCN_TIME_CFG : Synchronization control register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_BCN_TIME_CFG_STRUC	{
-	struct	{
-		UINT32		TxTimestampCompensate:8;
-        UINT32       :3;
-		UINT32		bBeaconGen:1;		// Enable beacon generator
-        UINT32       bTBTTEnable:1;
-		UINT32		TsfSyncMode:2;		// Enable TSF sync, 00: disable, 01: infra mode, 10: ad-hoc mode
-		UINT32		bTsfTicking:1;		// Enable TSF auto counting
-		UINT32       BeaconInterval:16;  // in unit of 1/16 TU
-	}	field;
-	UINT32			word;
-}	BCN_TIME_CFG_STRUC, *PBCN_TIME_CFG_STRUC;
-#else
-typedef	union	_BCN_TIME_CFG_STRUC	{
-	struct	{
-		UINT32       BeaconInterval:16;  // in unit of 1/16 TU
-		UINT32		bTsfTicking:1;		// Enable TSF auto counting
-		UINT32		TsfSyncMode:2;		// Enable TSF sync, 00: disable, 01: infra mode, 10: ad-hoc mode
-        UINT32       bTBTTEnable:1;
-		UINT32		bBeaconGen:1;		// Enable beacon generator
-        UINT32       :3;
-		UINT32		TxTimestampCompensate:8;
-	}	field;
-	UINT32			word;
-}	BCN_TIME_CFG_STRUC, *PBCN_TIME_CFG_STRUC;
-#endif
-#define TBTT_SYNC_CFG            0x1118  		// txrx_csr10
-#define TSF_TIMER_DW0             0x111C  		// Local TSF timer lsb 32 bits. Read-only
-#define TSF_TIMER_DW1             0x1120  		// msb 32 bits. Read-only.
-#define TBTT_TIMER             	0x1124  		// TImer remains till next TBTT. Read-only.  TXRX_CSR14
-#define INT_TIMER_CFG              	0x1128  		//
-#define INT_TIMER_EN             	0x112c  		//  GP-timer and pre-tbtt Int enable
-#define CH_IDLE_STA              	0x1130  		//  channel idle time
-#define CH_BUSY_STA              	0x1134  		//  channle busy time
-//
-//  4.2 MAC POWER  configuration registers (offset:0x1200)
-//
-#define MAC_STATUS_CFG             0x1200		 // old MAC_CSR12
-#define PWR_PIN_CFG             0x1204		 // old MAC_CSR12
-#define AUTO_WAKEUP_CFG             0x1208		 // old MAC_CSR10
-//
-// AUTO_WAKEUP_CFG: Manual power control / status register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AUTO_WAKEUP_STRUC	{
-	struct	{
-		UINT32		:16;
-		UINT32		EnableAutoWakeup:1;	// 0:sleep, 1:awake
-		UINT32       NumofSleepingTbtt:7;          // ForceWake has high privilege than PutToSleep when both set
-		UINT32       AutoLeadTime:8;
-	}	field;
-	UINT32			word;
-}	AUTO_WAKEUP_STRUC, *PAUTO_WAKEUP_STRUC;
-#else
-typedef	union	_AUTO_WAKEUP_STRUC	{
-	struct	{
-		UINT32       AutoLeadTime:8;
-		UINT32       NumofSleepingTbtt:7;          // ForceWake has high privilege than PutToSleep when both set
-		UINT32		EnableAutoWakeup:1;	// 0:sleep, 1:awake
-		UINT32		:16;
-	}	field;
-	UINT32			word;
-}	AUTO_WAKEUP_STRUC, *PAUTO_WAKEUP_STRUC;
-#endif
-//
-//  4.3 MAC TX  configuration registers (offset:0x1300)
-//
-
-#define EDCA_AC0_CFG	0x1300		//AC_TXOP_CSR0 0x3474
-#define EDCA_AC1_CFG	0x1304
-#define EDCA_AC2_CFG	0x1308
-#define EDCA_AC3_CFG	0x130c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EDCA_AC_CFG_STRUC	{
-	struct	{
-	    UINT32  :12;        //
-	    UINT32  Cwmax:4;        //unit power of 2
-	    UINT32  Cwmin:4;        //
-	    UINT32  Aifsn:4;        // # of slot time
-	    UINT32  AcTxop:8;        //  in unit of 32us
-	}	field;
-	UINT32			word;
-}	EDCA_AC_CFG_STRUC, *PEDCA_AC_CFG_STRUC;
-#else
-typedef	union	_EDCA_AC_CFG_STRUC	{
-	struct	{
-	    UINT32  AcTxop:8;        //  in unit of 32us
-	    UINT32  Aifsn:4;        // # of slot time
-	    UINT32  Cwmin:4;        //
-	    UINT32  Cwmax:4;        //unit power of 2
-	    UINT32  :12;       //
-	}	field;
-	UINT32			word;
-}	EDCA_AC_CFG_STRUC, *PEDCA_AC_CFG_STRUC;
-#endif
-
-#define EDCA_TID_AC_MAP	0x1310
-#define TX_PWR_CFG_0	0x1314
-#define TX_PWR_CFG_1	0x1318
-#define TX_PWR_CFG_2	0x131C
-#define TX_PWR_CFG_3	0x1320
-#define TX_PWR_CFG_4	0x1324
-#define TX_PIN_CFG		0x1328
-#define TX_BAND_CFG	0x132c		// 0x1 use upper 20MHz. 0 juse lower 20MHz
-#define TX_SW_CFG0		0x1330
-#define TX_SW_CFG1		0x1334
-#define TX_SW_CFG2		0x1338
-#define TXOP_THRES_CFG		0x133c
-#define TXOP_CTRL_CFG		0x1340
-#define TX_RTS_CFG		0x1344
-
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_RTS_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv:7;
-	    UINT32       RtsFbkEn:1;    // enable rts rate fallback
-	    UINT32       RtsThres:16;    // unit:byte
-	    UINT32       AutoRtsRetryLimit:8;
-	}	field;
-	UINT32			word;
-}	TX_RTS_CFG_STRUC, *PTX_RTS_CFG_STRUC;
-#else
-typedef	union	_TX_RTS_CFG_STRUC	{
-	struct	{
-	    UINT32       AutoRtsRetryLimit:8;
-	    UINT32       RtsThres:16;    // unit:byte
-	    UINT32       RtsFbkEn:1;    // enable rts rate fallback
-	    UINT32       rsv:7;     // 1: HT non-STBC control frame enable
-	}	field;
-	UINT32			word;
-}	TX_RTS_CFG_STRUC, *PTX_RTS_CFG_STRUC;
-#endif
-#define TX_TIMEOUT_CFG	0x1348
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_TIMEOUT_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv2:8;
-	    UINT32       TxopTimeout:8;	//TXOP timeout value for TXOP truncation.  It is recommended that (SLOT_TIME) > (TX_OP_TIMEOUT) > (RX_ACK_TIMEOUT)
-	    UINT32       RxAckTimeout:8;	// unit:slot. Used for TX precedure
-	    UINT32       MpduLifeTime:4;    //  expiration time = 2^(9+MPDU LIFE TIME)  us
-	    UINT32       rsv:4;
-	}	field;
-	UINT32			word;
-}	TX_TIMEOUT_CFG_STRUC, *PTX_TIMEOUT_CFG_STRUC;
-#else
-typedef	union	_TX_TIMEOUT_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv:4;
-	    UINT32       MpduLifeTime:4;    //  expiration time = 2^(9+MPDU LIFE TIME)  us
-	    UINT32       RxAckTimeout:8;	// unit:slot. Used for TX precedure
-	    UINT32       TxopTimeout:8;	//TXOP timeout value for TXOP truncation.  It is recommended that (SLOT_TIME) > (TX_OP_TIMEOUT) > (RX_ACK_TIMEOUT)
-	    UINT32       rsv2:8;     // 1: HT non-STBC control frame enable
-	}	field;
-	UINT32			word;
-}	TX_TIMEOUT_CFG_STRUC, *PTX_TIMEOUT_CFG_STRUC;
-#endif
-#define TX_RTY_CFG	0x134c
-#ifdef RT_BIG_ENDIAN
-typedef	union PACKED _TX_RTY_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv:1;
-	    UINT32       TxautoFBEnable:1;    // Tx retry PHY rate auto fallback enable
-	    UINT32       AggRtyMode:1;	// Aggregate MPDU retry mode.  0:expired by retry limit, 1: expired by mpdu life timer
-	    UINT32       NonAggRtyMode:1;	// Non-Aggregate MPDU retry mode.  0:expired by retry limit, 1: expired by mpdu life timer
-	    UINT32       LongRtyThre:12;	// Long retry threshoold
-	    UINT32       LongRtyLimit:8;	//long retry limit
-	    UINT32       ShortRtyLimit:8;	//  short retry limit
-
-	}	field;
-	UINT32			word;
-}	TX_RTY_CFG_STRUC, *PTX_RTY_CFG_STRUC;
-#else
-typedef	union PACKED _TX_RTY_CFG_STRUC	{
-	struct	{
-	    UINT32       ShortRtyLimit:8;	//  short retry limit
-	    UINT32       LongRtyLimit:8;	//long retry limit
-	    UINT32       LongRtyThre:12;	// Long retry threshoold
-	    UINT32       NonAggRtyMode:1;	// Non-Aggregate MPDU retry mode.  0:expired by retry limit, 1: expired by mpdu life timer
-	    UINT32       AggRtyMode:1;	// Aggregate MPDU retry mode.  0:expired by retry limit, 1: expired by mpdu life timer
-	    UINT32       TxautoFBEnable:1;    // Tx retry PHY rate auto fallback enable
-	    UINT32       rsv:1;     // 1: HT non-STBC control frame enable
-	}	field;
-	UINT32			word;
-}	TX_RTY_CFG_STRUC, *PTX_RTY_CFG_STRUC;
-#endif
-#define TX_LINK_CFG	0x1350
-#ifdef RT_BIG_ENDIAN
-typedef	union	PACKED _TX_LINK_CFG_STRUC	{
-	struct PACKED {
-	    UINT32       RemotMFS:8;	//remote MCS feedback sequence number
-	    UINT32       RemotMFB:8;    //  remote MCS feedback
-	    UINT32       rsv:3;	//
-	    UINT32       TxCFAckEn:1;	//   Piggyback CF-ACK enable
-	    UINT32       TxRDGEn:1;	// RDG TX enable
-	    UINT32       TxMRQEn:1;	//  MCS request TX enable
-	    UINT32       RemoteUMFSEnable:1;	//  remote unsolicit  MFB enable.  0: not apply remote remote unsolicit (MFS=7)
-	    UINT32       MFBEnable:1;	//  TX apply remote MFB 1:enable
-	    UINT32       RemoteMFBLifeTime:8;	//remote MFB life time. unit : 32us
-	}	field;
-	UINT32			word;
-}	TX_LINK_CFG_STRUC, *PTX_LINK_CFG_STRUC;
-#else
-typedef	union	PACKED _TX_LINK_CFG_STRUC	{
-	struct PACKED {
-	    UINT32       RemoteMFBLifeTime:8;	//remote MFB life time. unit : 32us
-	    UINT32       MFBEnable:1;	//  TX apply remote MFB 1:enable
-	    UINT32       RemoteUMFSEnable:1;	//  remote unsolicit  MFB enable.  0: not apply remote remote unsolicit (MFS=7)
-	    UINT32       TxMRQEn:1;	//  MCS request TX enable
-	    UINT32       TxRDGEn:1;	// RDG TX enable
-	    UINT32       TxCFAckEn:1;	//   Piggyback CF-ACK enable
-	    UINT32       rsv:3;	//
-	    UINT32       RemotMFB:8;    //  remote MCS feedback
-	    UINT32       RemotMFS:8;	//remote MCS feedback sequence number
-	}	field;
-	UINT32			word;
-}	TX_LINK_CFG_STRUC, *PTX_LINK_CFG_STRUC;
-#endif
-#define HT_FBK_CFG0	0x1354
-#ifdef RT_BIG_ENDIAN
-typedef	union PACKED _HT_FBK_CFG0_STRUC	{
-	struct	{
-	    UINT32       HTMCS7FBK:4;
-	    UINT32       HTMCS6FBK:4;
-	    UINT32       HTMCS5FBK:4;
-	    UINT32       HTMCS4FBK:4;
-	    UINT32       HTMCS3FBK:4;
-	    UINT32       HTMCS2FBK:4;
-	    UINT32       HTMCS1FBK:4;
-	    UINT32       HTMCS0FBK:4;
-	}	field;
-	UINT32			word;
-}	HT_FBK_CFG0_STRUC, *PHT_FBK_CFG0_STRUC;
-#else
-typedef	union PACKED _HT_FBK_CFG0_STRUC	{
-	struct	{
-	    UINT32       HTMCS0FBK:4;
-	    UINT32       HTMCS1FBK:4;
-	    UINT32       HTMCS2FBK:4;
-	    UINT32       HTMCS3FBK:4;
-	    UINT32       HTMCS4FBK:4;
-	    UINT32       HTMCS5FBK:4;
-	    UINT32       HTMCS6FBK:4;
-	    UINT32       HTMCS7FBK:4;
-	}	field;
-	UINT32			word;
-}	HT_FBK_CFG0_STRUC, *PHT_FBK_CFG0_STRUC;
-#endif
-#define HT_FBK_CFG1	0x1358
-#ifdef RT_BIG_ENDIAN
-typedef	union	_HT_FBK_CFG1_STRUC	{
-	struct	{
-	    UINT32       HTMCS15FBK:4;
-	    UINT32       HTMCS14FBK:4;
-	    UINT32       HTMCS13FBK:4;
-	    UINT32       HTMCS12FBK:4;
-	    UINT32       HTMCS11FBK:4;
-	    UINT32       HTMCS10FBK:4;
-	    UINT32       HTMCS9FBK:4;
-	    UINT32       HTMCS8FBK:4;
-	}	field;
-	UINT32			word;
-}	HT_FBK_CFG1_STRUC, *PHT_FBK_CFG1_STRUC;
-#else
-typedef	union	_HT_FBK_CFG1_STRUC	{
-	struct	{
-	    UINT32       HTMCS8FBK:4;
-	    UINT32       HTMCS9FBK:4;
-	    UINT32       HTMCS10FBK:4;
-	    UINT32       HTMCS11FBK:4;
-	    UINT32       HTMCS12FBK:4;
-	    UINT32       HTMCS13FBK:4;
-	    UINT32       HTMCS14FBK:4;
-	    UINT32       HTMCS15FBK:4;
-	}	field;
-	UINT32			word;
-}	HT_FBK_CFG1_STRUC, *PHT_FBK_CFG1_STRUC;
-#endif
-#define LG_FBK_CFG0	0x135c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_LG_FBK_CFG0_STRUC	{
-	struct	{
-	    UINT32       OFDMMCS7FBK:4;	//initial value is 6
-	    UINT32       OFDMMCS6FBK:4;	//initial value is 5
-	    UINT32       OFDMMCS5FBK:4;	//initial value is 4
-	    UINT32       OFDMMCS4FBK:4;	//initial value is 3
-	    UINT32       OFDMMCS3FBK:4;	//initial value is 2
-	    UINT32       OFDMMCS2FBK:4;	//initial value is 1
-	    UINT32       OFDMMCS1FBK:4;	//initial value is 0
-	    UINT32       OFDMMCS0FBK:4;	//initial value is 0
-	}	field;
-	UINT32			word;
-}	LG_FBK_CFG0_STRUC, *PLG_FBK_CFG0_STRUC;
-#else
-typedef	union	_LG_FBK_CFG0_STRUC	{
-	struct	{
-	    UINT32       OFDMMCS0FBK:4;	//initial value is 0
-	    UINT32       OFDMMCS1FBK:4;	//initial value is 0
-	    UINT32       OFDMMCS2FBK:4;	//initial value is 1
-	    UINT32       OFDMMCS3FBK:4;	//initial value is 2
-	    UINT32       OFDMMCS4FBK:4;	//initial value is 3
-	    UINT32       OFDMMCS5FBK:4;	//initial value is 4
-	    UINT32       OFDMMCS6FBK:4;	//initial value is 5
-	    UINT32       OFDMMCS7FBK:4;	//initial value is 6
-	}	field;
-	UINT32			word;
-}	LG_FBK_CFG0_STRUC, *PLG_FBK_CFG0_STRUC;
-#endif
-#define LG_FBK_CFG1		0x1360
-#ifdef RT_BIG_ENDIAN
-typedef	union	_LG_FBK_CFG1_STRUC	{
-	struct	{
-	    UINT32       rsv:16;
-	    UINT32       CCKMCS3FBK:4;	//initial value is 2
-	    UINT32       CCKMCS2FBK:4;	//initial value is 1
-	    UINT32       CCKMCS1FBK:4;	//initial value is 0
-	    UINT32       CCKMCS0FBK:4;	//initial value is 0
-	}	field;
-	UINT32			word;
-}	LG_FBK_CFG1_STRUC, *PLG_FBK_CFG1_STRUC;
-#else
-typedef	union	_LG_FBK_CFG1_STRUC	{
-	struct	{
-	    UINT32       CCKMCS0FBK:4;	//initial value is 0
-	    UINT32       CCKMCS1FBK:4;	//initial value is 0
-	    UINT32       CCKMCS2FBK:4;	//initial value is 1
-	    UINT32       CCKMCS3FBK:4;	//initial value is 2
-	    UINT32       rsv:16;
-	}	field;
-	UINT32			word;
-}	LG_FBK_CFG1_STRUC, *PLG_FBK_CFG1_STRUC;
-#endif
-
-//=======================================================
-//================ Protection Paramater================================
-//=======================================================
-#define CCK_PROT_CFG	0x1364		//CCK Protection
-#define ASIC_SHORTNAV		1
-#define ASIC_LONGNAV		2
-#define ASIC_RTS		1
-#define ASIC_CTS		2
-#ifdef RT_BIG_ENDIAN
-typedef	union	_PROT_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv:5;
-	    UINT32       RTSThEn:1;	//RTS threshold enable on CCK TX
-	    UINT32       TxopAllowGF40:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowGF20:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowMM40:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowMM20:1;	//CCK TXOP allowance. 0:disallow.
-	    UINT32       TxopAllowOfdm:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowCck:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       ProtectNav:2;	//TXOP protection type for CCK TX. 0:None, 1:ShortNAVprotect,  2:LongNAVProtect, 3:rsv
-	    UINT32       ProtectCtrl:2;	//Protection control frame type for CCK TX. 1:RTS/CTS, 2:CTS-to-self, 0:None, 3:rsv
-	    UINT32       ProtectRate:16;	//Protection control frame rate for CCK TX(RTS/CTS/CFEnd).
-	}	field;
-	UINT32			word;
-}	PROT_CFG_STRUC, *PPROT_CFG_STRUC;
-#else
-typedef	union	_PROT_CFG_STRUC	{
-	struct	{
-	    UINT32       ProtectRate:16;	//Protection control frame rate for CCK TX(RTS/CTS/CFEnd).
-	    UINT32       ProtectCtrl:2;	//Protection control frame type for CCK TX. 1:RTS/CTS, 2:CTS-to-self, 0:None, 3:rsv
-	    UINT32       ProtectNav:2;	//TXOP protection type for CCK TX. 0:None, 1:ShortNAVprotect,  2:LongNAVProtect, 3:rsv
-	    UINT32       TxopAllowCck:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowOfdm:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowMM20:1;	//CCK TXOP allowance. 0:disallow.
-	    UINT32       TxopAllowMM40:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowGF20:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowGF40:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       RTSThEn:1;	//RTS threshold enable on CCK TX
-	    UINT32       rsv:5;
-	}	field;
-	UINT32			word;
-}	PROT_CFG_STRUC, *PPROT_CFG_STRUC;
-#endif
-
-#define OFDM_PROT_CFG	0x1368		//OFDM Protection
-#define MM20_PROT_CFG	0x136C		//MM20 Protection
-#define MM40_PROT_CFG	0x1370		//MM40 Protection
-#define GF20_PROT_CFG	0x1374		//GF20 Protection
-#define GF40_PROT_CFG	0x1378		//GR40 Protection
-#define EXP_CTS_TIME	0x137C		//
-#define EXP_ACK_TIME	0x1380		//
-
-//
-//  4.4 MAC RX configuration registers (offset:0x1400)
-//
-#define RX_FILTR_CFG	0x1400			//TXRX_CSR0
-#define AUTO_RSP_CFG	0x1404			//TXRX_CSR4
-//
-// TXRX_CSR4: Auto-Responder/
-//
-#ifdef RT_BIG_ENDIAN
-typedef union _AUTO_RSP_CFG_STRUC {
- struct {
-     UINT32        :24;
-     UINT32       AckCtsPsmBit:1;   // Power bit value in conrtrol frame
-     UINT32       DualCTSEn:1;   // Power bit value in conrtrol frame
-     UINT32       rsv:1;   // Power bit value in conrtrol frame
-     UINT32       AutoResponderPreamble:1;    // 0:long, 1:short preamble
-     UINT32       CTS40MRef:1;  // Response CTS 40MHz duplicate mode
-     UINT32       CTS40MMode:1;  // Response CTS 40MHz duplicate mode
-     UINT32       BACAckPolicyEnable:1;    // 0:long, 1:short preamble
-     UINT32       AutoResponderEnable:1;
- } field;
- UINT32   word;
-} AUTO_RSP_CFG_STRUC, *PAUTO_RSP_CFG_STRUC;
-#else
-typedef union _AUTO_RSP_CFG_STRUC {
- struct {
-     UINT32       AutoResponderEnable:1;
-     UINT32       BACAckPolicyEnable:1;    // 0:long, 1:short preamble
-     UINT32       CTS40MMode:1;  // Response CTS 40MHz duplicate mode
-     UINT32       CTS40MRef:1;  // Response CTS 40MHz duplicate mode
-     UINT32       AutoResponderPreamble:1;    // 0:long, 1:short preamble
-     UINT32       rsv:1;   // Power bit value in conrtrol frame
-     UINT32       DualCTSEn:1;   // Power bit value in conrtrol frame
-     UINT32       AckCtsPsmBit:1;   // Power bit value in conrtrol frame
-     UINT32        :24;
- } field;
- UINT32   word;
-} AUTO_RSP_CFG_STRUC, *PAUTO_RSP_CFG_STRUC;
-#endif
-
-#define LEGACY_BASIC_RATE	0x1408	//  TXRX_CSR5           0x3054
-#define HT_BASIC_RATE		0x140c
-#define HT_CTRL_CFG		0x1410
-#define SIFS_COST_CFG		0x1414
-#define RX_PARSER_CFG		0x1418	//Set NAV for all received frames
-
-//
-//  4.5 MAC Security configuration (offset:0x1500)
-//
-#define TX_SEC_CNT0		0x1500		//
-#define RX_SEC_CNT0		0x1504		//
-#define CCMP_FC_MUTE		0x1508		//
-//
-//  4.6 HCCA/PSMP (offset:0x1600)
-//
-#define TXOP_HLDR_ADDR0		0x1600
-#define TXOP_HLDR_ADDR1		0x1604
-#define TXOP_HLDR_ET		0x1608
-#define QOS_CFPOLL_RA_DW0		0x160c
-#define QOS_CFPOLL_A1_DW1		0x1610
-#define QOS_CFPOLL_QC		0x1614
-//
-//  4.7 MAC Statistis registers (offset:0x1700)
-//
-#define RX_STA_CNT0		0x1700		//
-#define RX_STA_CNT1		0x1704		//
-#define RX_STA_CNT2		0x1708		//
-
-//
-// RX_STA_CNT0_STRUC: RX PLCP error count & RX CRC error count
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RX_STA_CNT0_STRUC	{
-	struct	{
-	    USHORT  PhyErr;
-	    USHORT  CrcErr;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT0_STRUC, *PRX_STA_CNT0_STRUC;
-#else
-typedef	union	_RX_STA_CNT0_STRUC	{
-	struct	{
-	    USHORT  CrcErr;
-	    USHORT  PhyErr;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT0_STRUC, *PRX_STA_CNT0_STRUC;
-#endif
-
-//
-// RX_STA_CNT1_STRUC: RX False CCA count & RX LONG frame count
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RX_STA_CNT1_STRUC	{
-	struct	{
-	    USHORT  PlcpErr;
-	    USHORT  FalseCca;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT1_STRUC, *PRX_STA_CNT1_STRUC;
-#else
-typedef	union	_RX_STA_CNT1_STRUC	{
-	struct	{
-	    USHORT  FalseCca;
-	    USHORT  PlcpErr;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT1_STRUC, *PRX_STA_CNT1_STRUC;
-#endif
-
-//
-// RX_STA_CNT2_STRUC:
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RX_STA_CNT2_STRUC	{
-	struct	{
-	    USHORT  RxFifoOverflowCount;
-	    USHORT  RxDupliCount;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT2_STRUC, *PRX_STA_CNT2_STRUC;
-#else
-typedef	union	_RX_STA_CNT2_STRUC	{
-	struct	{
-	    USHORT  RxDupliCount;
-	    USHORT  RxFifoOverflowCount;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT2_STRUC, *PRX_STA_CNT2_STRUC;
-#endif
-#define TX_STA_CNT0		0x170C		//
-//
-// STA_CSR3: TX Beacon count
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_STA_CNT0_STRUC	{
-	struct	{
-	    USHORT  TxBeaconCount;
-	    USHORT  TxFailCount;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT0_STRUC, *PTX_STA_CNT0_STRUC;
-#else
-typedef	union	_TX_STA_CNT0_STRUC	{
-	struct	{
-	    USHORT  TxFailCount;
-	    USHORT  TxBeaconCount;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT0_STRUC, *PTX_STA_CNT0_STRUC;
-#endif
-#define TX_STA_CNT1		0x1710		//
-//
-// TX_STA_CNT1: TX tx count
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_STA_CNT1_STRUC	{
-	struct	{
-	    USHORT  TxRetransmit;
-	    USHORT  TxSuccess;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT1_STRUC, *PTX_STA_CNT1_STRUC;
-#else
-typedef	union	_TX_STA_CNT1_STRUC	{
-	struct	{
-	    USHORT  TxSuccess;
-	    USHORT  TxRetransmit;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT1_STRUC, *PTX_STA_CNT1_STRUC;
-#endif
-#define TX_STA_CNT2		0x1714		//
-//
-// TX_STA_CNT2: TX tx count
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_STA_CNT2_STRUC	{
-	struct	{
-	    USHORT  TxUnderFlowCount;
-	    USHORT  TxZeroLenCount;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT2_STRUC, *PTX_STA_CNT2_STRUC;
-#else
-typedef	union	_TX_STA_CNT2_STRUC	{
-	struct	{
-	    USHORT  TxZeroLenCount;
-	    USHORT  TxUnderFlowCount;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT2_STRUC, *PTX_STA_CNT2_STRUC;
-#endif
-#define TX_STA_FIFO		0x1718		//
-//
-// TX_STA_FIFO_STRUC: TX Result for specific PID status fifo register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union PACKED _TX_STA_FIFO_STRUC	{
-	struct	{
-		UINT32		Reserve:2;
-		UINT32		TxBF:1; // 3*3
-		UINT32		SuccessRate:13;	//include MCS, mode ,shortGI, BW settingSame format as TXWI Word 0 Bit 31-16.
-//		UINT32		SuccessRate:16;	//include MCS, mode ,shortGI, BW settingSame format as TXWI Word 0 Bit 31-16.
-		UINT32		wcid:8;		//wireless client index
-		UINT32       	TxAckRequired:1;    // ack required
-		UINT32       	TxAggre:1;    // Tx is aggregated
-		UINT32       	TxSuccess:1;   // Tx success. whether success or not
-		UINT32       	PidType:4;
-		UINT32       	bValid:1;   // 1:This register contains a valid TX result
-	}	field;
-	UINT32			word;
-}	TX_STA_FIFO_STRUC, *PTX_STA_FIFO_STRUC;
-#else
-typedef	union PACKED _TX_STA_FIFO_STRUC	{
-	struct	{
-		UINT32       	bValid:1;   // 1:This register contains a valid TX result
-		UINT32       	PidType:4;
-		UINT32       	TxSuccess:1;   // Tx No retry success
-		UINT32       	TxAggre:1;    // Tx Retry Success
-		UINT32       	TxAckRequired:1;    // Tx fail
-		UINT32		wcid:8;		//wireless client index
-//		UINT32		SuccessRate:16;	//include MCS, mode ,shortGI, BW settingSame format as TXWI Word 0 Bit 31-16.
-		UINT32		SuccessRate:13;	//include MCS, mode ,shortGI, BW settingSame format as TXWI Word 0 Bit 31-16.
-		UINT32		TxBF:1;
-		UINT32		Reserve:2;
-	}	field;
-	UINT32			word;
-}	TX_STA_FIFO_STRUC, *PTX_STA_FIFO_STRUC;
-#endif
-// Debug counter
-#define TX_AGG_CNT	0x171c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT_STRUC	{
-	struct	{
-	    USHORT  AggTxCount;
-	    USHORT  NonAggTxCount;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT_STRUC, *PTX_AGG_CNT_STRUC;
-#else
-typedef	union	_TX_AGG_CNT_STRUC	{
-	struct	{
-	    USHORT  NonAggTxCount;
-	    USHORT  AggTxCount;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT_STRUC, *PTX_AGG_CNT_STRUC;
-#endif
-// Debug counter
-#define TX_AGG_CNT0	0x1720
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT0_STRUC	{
-	struct	{
-	    USHORT  AggSize2Count;
-	    USHORT  AggSize1Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT0_STRUC, *PTX_AGG_CNT0_STRUC;
-#else
-typedef	union	_TX_AGG_CNT0_STRUC	{
-	struct	{
-	    USHORT  AggSize1Count;
-	    USHORT  AggSize2Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT0_STRUC, *PTX_AGG_CNT0_STRUC;
-#endif
-// Debug counter
-#define TX_AGG_CNT1	0x1724
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT1_STRUC	{
-	struct	{
-	    USHORT  AggSize4Count;
-	    USHORT  AggSize3Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT1_STRUC, *PTX_AGG_CNT1_STRUC;
-#else
-typedef	union	_TX_AGG_CNT1_STRUC	{
-	struct	{
-	    USHORT  AggSize3Count;
-	    USHORT  AggSize4Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT1_STRUC, *PTX_AGG_CNT1_STRUC;
-#endif
-#define TX_AGG_CNT2	0x1728
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT2_STRUC	{
-	struct	{
-	    USHORT  AggSize6Count;
-	    USHORT  AggSize5Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT2_STRUC, *PTX_AGG_CNT2_STRUC;
-#else
-typedef	union	_TX_AGG_CNT2_STRUC	{
-	struct	{
-	    USHORT  AggSize5Count;
-	    USHORT  AggSize6Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT2_STRUC, *PTX_AGG_CNT2_STRUC;
-#endif
-// Debug counter
-#define TX_AGG_CNT3	0x172c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT3_STRUC	{
-	struct	{
-	    USHORT  AggSize8Count;
-	    USHORT  AggSize7Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT3_STRUC, *PTX_AGG_CNT3_STRUC;
-#else
-typedef	union	_TX_AGG_CNT3_STRUC	{
-	struct	{
-	    USHORT  AggSize7Count;
-	    USHORT  AggSize8Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT3_STRUC, *PTX_AGG_CNT3_STRUC;
-#endif
-// Debug counter
-#define TX_AGG_CNT4	0x1730
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT4_STRUC	{
-	struct	{
-	    USHORT  AggSize10Count;
-	    USHORT  AggSize9Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT4_STRUC, *PTX_AGG_CNT4_STRUC;
-#else
-typedef	union	_TX_AGG_CNT4_STRUC	{
-	struct	{
-	    USHORT  AggSize9Count;
-	    USHORT  AggSize10Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT4_STRUC, *PTX_AGG_CNT4_STRUC;
-#endif
-#define TX_AGG_CNT5	0x1734
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT5_STRUC	{
-	struct	{
-	    USHORT  AggSize12Count;
-	    USHORT  AggSize11Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT5_STRUC, *PTX_AGG_CNT5_STRUC;
-#else
-typedef	union	_TX_AGG_CNT5_STRUC	{
-	struct	{
-	    USHORT  AggSize11Count;
-	    USHORT  AggSize12Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT5_STRUC, *PTX_AGG_CNT5_STRUC;
-#endif
-#define TX_AGG_CNT6		0x1738
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT6_STRUC	{
-	struct	{
-	    USHORT  AggSize14Count;
-	    USHORT  AggSize13Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT6_STRUC, *PTX_AGG_CNT6_STRUC;
-#else
-typedef	union	_TX_AGG_CNT6_STRUC	{
-	struct	{
-	    USHORT  AggSize13Count;
-	    USHORT  AggSize14Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT6_STRUC, *PTX_AGG_CNT6_STRUC;
-#endif
-#define TX_AGG_CNT7		0x173c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT7_STRUC	{
-	struct	{
-	    USHORT  AggSize16Count;
-	    USHORT  AggSize15Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT7_STRUC, *PTX_AGG_CNT7_STRUC;
-#else
-typedef	union	_TX_AGG_CNT7_STRUC	{
-	struct	{
-	    USHORT  AggSize15Count;
-	    USHORT  AggSize16Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT7_STRUC, *PTX_AGG_CNT7_STRUC;
-#endif
-#define MPDU_DENSITY_CNT		0x1740
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MPDU_DEN_CNT_STRUC	{
-	struct	{
-	    USHORT  RXZeroDelCount;	//RX zero length delimiter count
-	    USHORT  TXZeroDelCount;	//TX zero length delimiter count
-	}	field;
-	UINT32			word;
-}	MPDU_DEN_CNT_STRUC, *PMPDU_DEN_CNT_STRUC;
-#else
-typedef	union	_MPDU_DEN_CNT_STRUC	{
-	struct	{
-	    USHORT  TXZeroDelCount;	//TX zero length delimiter count
-	    USHORT  RXZeroDelCount;	//RX zero length delimiter count
-	}	field;
-	UINT32			word;
-}	MPDU_DEN_CNT_STRUC, *PMPDU_DEN_CNT_STRUC;
-#endif
-//
-// TXRX control registers - base address 0x3000
-//
-// rt2860b  UNKNOWN reg use R/O Reg Addr 0x77d0 first..
-#define TXRX_CSR1           0x77d0
-
-//
-// Security key table memory, base address = 0x1000
-//
-#define MAC_WCID_BASE		0x1800 //8-bytes(use only 6-bytes) * 256 entry =
-#define HW_WCID_ENTRY_SIZE   8
-#define PAIRWISE_KEY_TABLE_BASE     0x4000      // 32-byte * 256-entry =  -byte
-#define HW_KEY_ENTRY_SIZE           0x20
-#define PAIRWISE_IVEIV_TABLE_BASE     0x6000      // 8-byte * 256-entry =  -byte
-#define MAC_IVEIV_TABLE_BASE     0x6000      // 8-byte * 256-entry =  -byte
-#define HW_IVEIV_ENTRY_SIZE   8
-#define MAC_WCID_ATTRIBUTE_BASE     0x6800      // 4-byte * 256-entry =  -byte
-#define HW_WCID_ATTRI_SIZE   4
-#define WCID_RESERVED          		0x6bfc
-#define SHARED_KEY_TABLE_BASE       0x6c00      // 32-byte * 16-entry = 512-byte
-#define SHARED_KEY_MODE_BASE       0x7000      // 32-byte * 16-entry = 512-byte
-#define HW_SHARED_KEY_MODE_SIZE   4
-#define SHAREDKEYTABLE			0
-#define PAIRWISEKEYTABLE			1
-
-
-#ifdef RT_BIG_ENDIAN
-typedef	union	_SHAREDKEY_MODE_STRUC	{
-	struct	{
-		UINT32       :1;
-		UINT32       Bss1Key3CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key0CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key3CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key0CipherAlg:3;
-	}	field;
-	UINT32			word;
-}	SHAREDKEY_MODE_STRUC, *PSHAREDKEY_MODE_STRUC;
-#else
-typedef	union	_SHAREDKEY_MODE_STRUC	{
-	struct	{
-		UINT32       Bss0Key0CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key3CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key0CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key3CipherAlg:3;
-		UINT32       :1;
-	}	field;
-	UINT32			word;
-}	SHAREDKEY_MODE_STRUC, *PSHAREDKEY_MODE_STRUC;
-#endif
-// 64-entry for pairwise key table
-typedef struct _HW_WCID_ENTRY {  // 8-byte per entry
-    UCHAR   Address[6];
-    UCHAR   Rsv[2];
-} HW_WCID_ENTRY, PHW_WCID_ENTRY;
-
-
-
-//
-// Other on-chip shared memory space, base = 0x2000
-//
-
-// CIS space - base address = 0x2000
-#define HW_CIS_BASE             0x2000
-
-// Carrier-sense CTS frame base address. It's where mac stores carrier-sense frame for carrier-sense function.
-#define HW_CS_CTS_BASE			0x7700
-// DFS CTS frame base address. It's where mac stores CTS frame for DFS.
-#define HW_DFS_CTS_BASE			0x7780
-#define HW_CTS_FRAME_SIZE		0x80
-
-// 2004-11-08 john - since NULL frame won't be that long (256 byte). We steal 16 tail bytes
-// to save debugging settings
-#define HW_DEBUG_SETTING_BASE   0x77f0  // 0x77f0~0x77ff total 16 bytes
-#define HW_DEBUG_SETTING_BASE2   0x7770  // 0x77f0~0x77ff total 16 bytes
-
-#if 0
-// on-chip BEACON frame space - base address = 0x7800
-#define HW_BEACON_MAX_SIZE      0x0800 /* unit: byte */
-#define HW_BEACON_BASE0         0x7800
-#define HW_BEACON_BASE1         0x7900
-#define HW_BEACON_BASE2         0x7a00
-#define HW_BEACON_BASE3         0x7b00
-#define HW_BEACON_BASE4         0x7c00
-#define HW_BEACON_BASE5         0x7d00
-#define HW_BEACON_BASE6         0x7e00
-#define HW_BEACON_BASE7         0x7f00
-/* 1. HW_BEACON_OFFSET/64B must be 0;
-   2. BCN_OFFSET0 must also be changed in NICInitializeAsic();
-   3. max 0x0800 for 8 beacon frames; */
-#else
-// In order to support maximum 8 MBSS and its maximum length is 512 for each beacon
-// Three section discontinue memory segments will be used.
-// 1. The original region for BCN 0~3
-// 2. Extract memory from FCE table for BCN 4~5
-// 3. Extract memory from Pair-wise key table for BCN 6~7
-//	  It occupied those memory of wcid 238~253 for BCN 6
-//						      and wcid 222~237 for BCN 7
-#define HW_BEACON_MAX_SIZE      0x1000 /* unit: byte */
-#define HW_BEACON_BASE0         0x7800
-#define HW_BEACON_BASE1         0x7A00
-#define HW_BEACON_BASE2         0x7C00
-#define HW_BEACON_BASE3         0x7E00
-#define HW_BEACON_BASE4         0x7200
-#define HW_BEACON_BASE5         0x7400
-#define HW_BEACON_BASE6         0x5DC0
-#define HW_BEACON_BASE7         0x5BC0
-#endif
-
-#define HW_BEACON_MAX_COUNT     8
-#define HW_BEACON_OFFSET		0x0200
-#define HW_BEACON_CONTENT_LEN	(HW_BEACON_OFFSET - TXWI_SIZE)
-
-// HOST-MCU shared memory - base address = 0x2100
-#define HOST_CMD_CSR		0x404
-#define H2M_MAILBOX_CSR         0x7010
-#define H2M_MAILBOX_CID         0x7014
-#define H2M_MAILBOX_STATUS      0x701c
-#define H2M_INT_SRC             0x7024
-#define H2M_BBP_AGENT           0x7028
-#define M2H_CMD_DONE_CSR        0x000c
-#define MCU_TXOP_ARRAY_BASE     0x000c   // TODO: to be provided by Albert
-#define MCU_TXOP_ENTRY_SIZE     32       // TODO: to be provided by Albert
-#define MAX_NUM_OF_TXOP_ENTRY   16       // TODO: must be same with 8051 firmware
-#define MCU_MBOX_VERSION        0x01     // TODO: to be confirmed by Albert
-#define MCU_MBOX_VERSION_OFFSET 5        // TODO: to be provided by Albert
-
-//
-// Host DMA registers - base address 0x200 .  TX0-3=EDCAQid0-3, TX4=HCCA, TX5=MGMT,
-//
-//
-//  DMA RING DESCRIPTOR
-//
-#define E2PROM_CSR          0x0004
-#define IO_CNTL_CSR         0x77d0
-
-#ifdef RT2870
-// 8051 firmware image for usb - use last-half base address = 0x3000
-#define FIRMWARE_IMAGE_BASE     0x3000
-#define MAX_FIRMWARE_IMAGE_SIZE 0x1000    // 4kbyte
-#endif // RT2870 //
-
-// TODO: ????? old RT2560 registers. to keep them or remove them?
-//#define MCAST0                  0x0178  // multicast filter register 0
-//#define MCAST1                  0x017c  // multicast filter register 1
-
-
-// ================================================================
-// Tx /	Rx / Mgmt ring descriptor definition
-// ================================================================
-
-// the following PID values are used to mark outgoing frame type in TXD->PID so that
-// proper TX statistics can be collected based on these categories
-// b3-2 of PID field -
-#define PID_MGMT			0x05
-#define PID_BEACON			0x0c
-#define PID_DATA_NORMALUCAST	 	0x02
-#define PID_DATA_AMPDU	 	0x04
-#define PID_DATA_NO_ACK    	0x08
-#define PID_DATA_NOT_NORM_ACK	 	0x03
-#if 0
-#define PTYPE_DATA_REQUIRE_ACK  0x00 // b7-6:00, b5-0: 0~59 is MAC table index (AID?), 60~63 is WDS index
-#define PTYPE_NULL_AT_HIGH_RATE 0x04 // b7-6:01, b5-0: 0~59 is MAC table index (AID?), 60~63 is WDS index
-#define PTYPE_RESERVED          0x08 // b7-6:10
-#define PTYPE_SPECIAL           0x0c // b7-6:11
-
-// when b3-2=11 (PTYPE_SPECIAL), b1-0 coube be ...
-#define PSUBTYPE_DATA_NO_ACK    0x00
-#define PSUBTYPE_MGMT           0x01
-#define PSUBTYPE_OTHER_CNTL     0x02
-#define PSUBTYPE_RTS            0x03
-#endif
-// value domain of pTxD->HostQId (4-bit: 0~15)
-#define QID_AC_BK               1   // meet ACI definition in 802.11e
-#define QID_AC_BE               0   // meet ACI definition in 802.11e
-#define QID_AC_VI               2
-#define QID_AC_VO               3
-#define QID_HCCA                4
-#define NUM_OF_TX_RING          5
-#define QID_MGMT                13
-#define QID_RX                  14
-#define QID_OTHER               15
-
-
-// ------------------------------------------------------
-// BBP & RF	definition
-// ------------------------------------------------------
-#define	BUSY		                1
-#define	IDLE		                0
-
-#define	RF_R00					    0
-#define	RF_R01					    1
-#define	RF_R02					    2
-#define	RF_R03					    3
-#define	RF_R04					    4
-#define	RF_R05					    5
-#define	RF_R06					    6
-#define	RF_R07					    7
-#define	RF_R08					    8
-#define	RF_R09					    9
-#define	RF_R10					    10
-#define	RF_R11					    11
-#define	RF_R12					    12
-#define	RF_R13					    13
-#define	RF_R14					    14
-#define	RF_R15					    15
-#define	RF_R16					    16
-#define	RF_R17					    17
-#define	RF_R18					    18
-#define	RF_R19					    19
-#define	RF_R20					    20
-#define	RF_R21					    21
-#define	RF_R22					    22
-#define	RF_R23					    23
-#define	RF_R24					    24
-#define	RF_R25					    25
-#define	RF_R26					    26
-#define	RF_R27					    27
-#define	RF_R28					    28
-#define	RF_R29					    29
-#define	RF_R30					    30
-#define	RF_R31					    31
-
-#define	BBP_R0					    0  // version
-#define	BBP_R1				        1  // TSSI
-#define	BBP_R2          			2  // TX configure
-#define BBP_R3                      3
-#define BBP_R4                      4
-#define BBP_R5                      5
-#define BBP_R6                      6
-#define	BBP_R14			            14 // RX configure
-#define BBP_R16                     16
-#define BBP_R17                     17 // RX sensibility
-#define BBP_R18                     18
-#define BBP_R21                     21
-#define BBP_R22                     22
-#define BBP_R24                     24
-#define BBP_R25                     25
-#define BBP_R49                     49 //TSSI
-#define BBP_R50                     50
-#define BBP_R51                     51
-#define BBP_R52                     52
-#define BBP_R55                     55
-#define BBP_R62                     62 // Rx SQ0 Threshold HIGH
-#define BBP_R63                     63
-#define BBP_R64                     64
-#define BBP_R65                     65
-#define BBP_R66                     66
-#define BBP_R67                     67
-#define BBP_R68                     68
-#define BBP_R69                     69
-#define BBP_R70                     70 // Rx AGC SQ CCK Xcorr threshold
-#define BBP_R73                     73
-#define BBP_R75						75
-#define BBP_R77                     77
-#define BBP_R81                     81
-#define BBP_R82                     82
-#define BBP_R83                     83
-#define BBP_R84                     84
-#define BBP_R86						86
-#define BBP_R91						91
-#define BBP_R92						92
-#define BBP_R94                     94 // Tx Gain Control
-#define BBP_R103                    103
-#define BBP_R105                    105
-#define BBP_R113                    113
-#define BBP_R114                    114
-#define BBP_R115                    115
-#define BBP_R116                    116
-#define BBP_R117                    117
-#define BBP_R118                    118
-#define BBP_R119                    119
-#define BBP_R120                    120
-#define BBP_R121                    121
-#define BBP_R122                    122
-#define BBP_R123                    123
-
-
-#define BBPR94_DEFAULT              0x06 // Add 1 value will gain 1db
-
-//#define PHY_TR_SWITCH_TIME          5  // usec
-
-//#define BBP_R17_LOW_SENSIBILITY     0x50
-//#define BBP_R17_MID_SENSIBILITY     0x41
-//#define BBP_R17_DYNAMIC_UP_BOUND    0x40
-#define RSSI_FOR_VERY_LOW_SENSIBILITY -35
-#define RSSI_FOR_LOW_SENSIBILITY      -58
-#define RSSI_FOR_MID_LOW_SENSIBILITY  -80
-#define RSSI_FOR_MID_SENSIBILITY      -90
-
-//-------------------------------------------------------------------------
-// EEPROM definition
-//-------------------------------------------------------------------------
-#define EEDO                        0x08
-#define EEDI                        0x04
-#define EECS                        0x02
-#define EESK                        0x01
-#define EERL                        0x80
-
-#define EEPROM_WRITE_OPCODE         0x05
-#define EEPROM_READ_OPCODE          0x06
-#define EEPROM_EWDS_OPCODE          0x10
-#define EEPROM_EWEN_OPCODE          0x13
-
-#define	NUM_EEPROM_BBP_PARMS		19			// Include NIC Config 0, 1, CR, TX ALC step, BBPs
-#define	NUM_EEPROM_TX_G_PARMS		7
-#define	EEPROM_NIC1_OFFSET          0x34		// The address is from NIC config 0, not BBP register ID
-#define	EEPROM_NIC2_OFFSET          0x36		// The address is from NIC config 0, not BBP register ID
-#define	EEPROM_BBP_BASE_OFFSET		0xf0		// The address is from NIC config 0, not BBP register ID
-#define	EEPROM_G_TX_PWR_OFFSET		0x52
-#define	EEPROM_G_TX2_PWR_OFFSET		0x60
-#define EEPROM_LED1_OFFSET			0x3c
-#define EEPROM_LED2_OFFSET			0x3e
-#define EEPROM_LED3_OFFSET			0x40
-#define EEPROM_LNA_OFFSET			0x44
-#define EEPROM_RSSI_BG_OFFSET		0x46
-#define EEPROM_RSSI_A_OFFSET		0x4a
-#define EEPROM_DEFINE_MAX_TXPWR		0x4e
-#define EEPROM_TXPOWER_BYRATE_20MHZ_2_4G	0xde	// 20MHZ 2.4G tx power.
-#define EEPROM_TXPOWER_BYRATE_40MHZ_2_4G	0xee	// 40MHZ 2.4G tx power.
-#define EEPROM_TXPOWER_BYRATE_20MHZ_5G		0xfa	// 20MHZ 5G tx power.
-#define EEPROM_TXPOWER_BYRATE_40MHZ_5G		0x10a	// 40MHZ 5G tx power.
-#define EEPROM_A_TX_PWR_OFFSET      0x78
-#define EEPROM_A_TX2_PWR_OFFSET      0xa6
-//#define EEPROM_Japan_TX_PWR_OFFSET      0x90 // 802.11j
-//#define EEPROM_Japan_TX2_PWR_OFFSET      0xbe
-//#define EEPROM_TSSI_REF_OFFSET	0x54
-//#define EEPROM_TSSI_DELTA_OFFSET	0x24
-//#define EEPROM_CCK_TX_PWR_OFFSET  0x62
-//#define EEPROM_CALIBRATE_OFFSET	0x7c
-#define EEPROM_VERSION_OFFSET       0x02
-#define	EEPROM_FREQ_OFFSET			0x3a
-#define EEPROM_TXPOWER_BYRATE 	0xde	// 20MHZ power.
-#define EEPROM_TXPOWER_DELTA		0x50	// 20MHZ AND 40 MHZ use different power. This is delta in 40MHZ.
-#define VALID_EEPROM_VERSION        1
-
-// PairKeyMode definition
-#define PKMODE_NONE                 0
-#define PKMODE_WEP64                1
-#define PKMODE_WEP128               2
-#define PKMODE_TKIP                 3
-#define PKMODE_AES                  4
-#define PKMODE_CKIP64               5
-#define PKMODE_CKIP128              6
-#define PKMODE_TKIP_NO_MIC          7       // MIC appended by driver: not a valid value in hardware key table
-
-// =================================================================================
-// WCID  format
-// =================================================================================
-//7.1	WCID  ENTRY  format  : 8bytes
-typedef	struct	_WCID_ENTRY_STRUC {
-	UCHAR		RXBABitmap7;    // bit0 for TID8, bit7 for TID 15
-	UCHAR		RXBABitmap0;    // bit0 for TID0, bit7 for TID 7
-	UCHAR		MAC[6];	// 0 for shared key table.  1 for pairwise key table
-}	WCID_ENTRY_STRUC, *PWCID_ENTRY_STRUC;
-
-//8.1.1	SECURITY  KEY  format  : 8DW
-// 32-byte per entry, total 16-entry for shared key table, 64-entry for pairwise key table
-typedef struct _HW_KEY_ENTRY {          // 32-byte per entry
-    UCHAR   Key[16];
-    UCHAR   TxMic[8];
-    UCHAR   RxMic[8];
-} HW_KEY_ENTRY, *PHW_KEY_ENTRY;
-
-//8.1.2	IV/EIV  format  : 2DW
-
-//8.1.3	RX attribute entry format  : 1DW
-#ifdef RT_BIG_ENDIAN
-typedef	struct	_MAC_ATTRIBUTE_STRUC {
-	UINT32		rsv:22;
-	UINT32		RXWIUDF:3;
-	UINT32		BSSIDIdx:3; //multipleBSS index for the WCID
-	UINT32		PairKeyMode:3;
-	UINT32		KeyTab:1;	// 0 for shared key table.  1 for pairwise key table
-}	MAC_ATTRIBUTE_STRUC, *PMAC_ATTRIBUTE_STRUC;
-#else
-typedef	struct	_MAC_ATTRIBUTE_STRUC {
-	UINT32		KeyTab:1;	// 0 for shared key table.  1 for pairwise key table
-	UINT32		PairKeyMode:3;
-	UINT32		BSSIDIdx:3; //multipleBSS index for the WCID
-	UINT32		RXWIUDF:3;
-	UINT32		rsv:22;
-}	MAC_ATTRIBUTE_STRUC, *PMAC_ATTRIBUTE_STRUC;
-#endif
-
-
-// =================================================================================
-// TX / RX ring descriptor format
-// =================================================================================
-
-// the first 24-byte in TXD is called TXINFO and will be DMAed to MAC block through TXFIFO.
-// MAC block use this TXINFO to control the transmission behavior of this frame.
-#define FIFO_MGMT                 0
-#define FIFO_HCCA                 1
-#define FIFO_EDCA                 2
-
-//
-// TX descriptor format, Tx	ring, Mgmt Ring
-//
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _TXD_STRUC {
-	// Word 0
-	UINT32		SDPtr0;
-	// Word 1
-	UINT32		DMADONE:1;
-	UINT32		LastSec0:1;
-	UINT32		SDLen0:14;
-	UINT32		Burst:1;
-	UINT32		LastSec1:1;
-	UINT32		SDLen1:14;
-	// Word 2
-	UINT32		SDPtr1;
-	// Word 3
-	UINT32		ICO:1;
-	UINT32		UCO:1;
-	UINT32		TCO:1;
-	UINT32		rsv:2;
-	UINT32		QSEL:2;	// select on-chip FIFO ID for 2nd-stage output scheduler.0:MGMT, 1:HCCA 2:EDCA
-	UINT32		WIV:1;	// Wireless Info Valid. 1 if Driver already fill WI,  o if DMA needs to copy WI to correctposition
-	UINT32		rsv2:24;
-}	TXD_STRUC, *PTXD_STRUC;
-#else
-typedef	struct	PACKED _TXD_STRUC {
-	// Word	0
-	UINT32		SDPtr0;
-	// Word	1
-	UINT32		SDLen1:14;
-	UINT32		LastSec1:1;
-	UINT32		Burst:1;
-	UINT32		SDLen0:14;
-	UINT32		LastSec0:1;
-	UINT32		DMADONE:1;
-	//Word2
-	UINT32		SDPtr1;
-	//Word3
-	UINT32		rsv2:24;
-	UINT32		WIV:1;	// Wireless Info Valid. 1 if Driver already fill WI,  o if DMA needs to copy WI to correctposition
-	UINT32		QSEL:2;	// select on-chip FIFO ID for 2nd-stage output scheduler.0:MGMT, 1:HCCA 2:EDCA
-	UINT32		rsv:2;
-	UINT32		TCO:1;	//
-	UINT32		UCO:1;	//
-	UINT32		ICO:1;	//
-}	TXD_STRUC, *PTXD_STRUC;
-#endif
-
-
-//
-// TXD Wireless Information format for Tx ring and Mgmt Ring
-//
-//txop : for txop mode
-// 0:txop for the MPDU frame will be handles by ASIC by register
-// 1/2/3:the MPDU frame is send after PIFS/backoff/SIFS
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _TXWI_STRUC {
-	// Word 0
-	UINT32		PHYMODE:2;
-	UINT32		TxBF:1;	// 3*3
-	UINT32		rsv2:1;
-//	UINT32		rsv2:2;
-	UINT32		Ifs:1;	//
-	UINT32		STBC:2;	//channel bandwidth 20MHz or 40 MHz
-	UINT32		ShortGI:1;
-	UINT32		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	UINT32		MCS:7;
-
-	UINT32		rsv:6;
-	UINT32		txop:2;	//tx back off mode 0:HT TXOP rule , 1:PIFS TX ,2:Backoff, 3:sifs only when previous frame exchange is successful.
-	UINT32		MpduDensity:3;
-	UINT32		AMPDU:1;
-
-	UINT32		TS:1;
-	UINT32		CFACK:1;
-	UINT32		MIMOps:1;	// the remote peer is in dynamic MIMO-PS mode
-	UINT32		FRAG:1;		// 1 to inform TKIP engine this is a fragment.
-	// Word 1
-	UINT32		PacketId:4;
-	UINT32		MPDUtotalByteCount:12;
-	UINT32		WirelessCliID:8;
-	UINT32		BAWinSize:6;
-	UINT32		NSEQ:1;
-	UINT32		ACK:1;
-	// Word 2
-	UINT32		IV;
-	// Word 3
-	UINT32		EIV;
-}	TXWI_STRUC, *PTXWI_STRUC;
-#else
-typedef	struct	PACKED _TXWI_STRUC {
-	// Word	0
-	UINT32		FRAG:1;		// 1 to inform TKIP engine this is a fragment.
-	UINT32		MIMOps:1;	// the remote peer is in dynamic MIMO-PS mode
-	UINT32		CFACK:1;
-	UINT32		TS:1;
-
-	UINT32		AMPDU:1;
-	UINT32		MpduDensity:3;
-	UINT32		txop:2;	//FOR "THIS" frame. 0:HT TXOP rule , 1:PIFS TX ,2:Backoff, 3:sifs only when previous frame exchange is successful.
-	UINT32		rsv:6;
-
-	UINT32		MCS:7;
-	UINT32		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	UINT32		ShortGI:1;
-	UINT32		STBC:2;	// 1: STBC support MCS =0-7,   2,3 : RESERVE
-	UINT32		Ifs:1;	//
-//	UINT32		rsv2:2;	//channel bandwidth 20MHz or 40 MHz
-	UINT32		rsv2:1;
-	UINT32		TxBF:1;	// 3*3
-	UINT32		PHYMODE:2;
-	// Word	1
-	UINT32		ACK:1;
-	UINT32		NSEQ:1;
-	UINT32		BAWinSize:6;
-	UINT32		WirelessCliID:8;
-	UINT32		MPDUtotalByteCount:12;
-	UINT32		PacketId:4;
-	//Word2
-	UINT32		IV;
-	//Word3
-	UINT32		EIV;
-}	TXWI_STRUC, *PTXWI_STRUC;
-#endif
-//
-// Rx descriptor format, Rx	Ring
-//
-//
-// RXWI wireless information format, in PBF. invisible in driver.
-//
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _RXWI_STRUC {
-	// Word 0
-	UINT32		TID:4;
-	UINT32		MPDUtotalByteCount:12;
-	UINT32		UDF:3;
-	UINT32		BSSID:3;
-	UINT32		KeyIndex:2;
-	UINT32		WirelessCliID:8;
-	// Word 1
-	UINT32		PHYMODE:2;              // 1: this RX frame is unicast to me
-	UINT32		rsv:3;
-	UINT32		STBC:2;
-	UINT32		ShortGI:1;
-	UINT32		BW:1;
-	UINT32		MCS:7;
-	UINT32		SEQUENCE:12;
-	UINT32		FRAG:4;
-	// Word 2
-	UINT32		rsv1:8;
-	UINT32		RSSI2:8;
-	UINT32		RSSI1:8;
-	UINT32		RSSI0:8;
-	// Word 3
-	UINT32		rsv2:16;
-	UINT32		SNR1:8;
-	UINT32		SNR0:8;
-}	RXWI_STRUC, *PRXWI_STRUC;
-#else
-typedef	struct	PACKED _RXWI_STRUC {
-	// Word	0
-	UINT32		WirelessCliID:8;
-	UINT32		KeyIndex:2;
-	UINT32		BSSID:3;
-	UINT32		UDF:3;
-	UINT32		MPDUtotalByteCount:12;
-	UINT32		TID:4;
-	// Word	1
-	UINT32		FRAG:4;
-	UINT32		SEQUENCE:12;
-	UINT32		MCS:7;
-	UINT32		BW:1;
-	UINT32		ShortGI:1;
-	UINT32		STBC:2;
-	UINT32		rsv:3;
-	UINT32		PHYMODE:2;              // 1: this RX frame is unicast to me
-	//Word2
-	UINT32		RSSI0:8;
-	UINT32		RSSI1:8;
-	UINT32		RSSI2:8;
-	UINT32		rsv1:8;
-	//Word3
-	UINT32		SNR0:8;
-	UINT32		SNR1:8;
-	UINT32		rsv2:16;
-}	RXWI_STRUC, *PRXWI_STRUC;
-#endif
-
-
-// =================================================================================
-// HOST-MCU communication data structure
-// =================================================================================
-
-//
-// H2M_MAILBOX_CSR: Host-to-MCU Mailbox
-//
-#ifdef RT_BIG_ENDIAN
-typedef union  _H2M_MAILBOX_STRUC {
-    struct {
-        UINT32       Owner:8;
-        UINT32       CmdToken:8;    // 0xff tells MCU not to report CmdDoneInt after excuting the command
-        UINT32       HighByte:8;
-        UINT32       LowByte:8;
-    }   field;
-    UINT32           word;
-} H2M_MAILBOX_STRUC, *PH2M_MAILBOX_STRUC;
-#else
-typedef union  _H2M_MAILBOX_STRUC {
-    struct {
-        UINT32       LowByte:8;
-        UINT32       HighByte:8;
-        UINT32       CmdToken:8;
-        UINT32       Owner:8;
-    }   field;
-    UINT32           word;
-} H2M_MAILBOX_STRUC, *PH2M_MAILBOX_STRUC;
-#endif
-
-//
-// M2H_CMD_DONE_CSR: MCU-to-Host command complete indication
-//
-#ifdef RT_BIG_ENDIAN
-typedef union _M2H_CMD_DONE_STRUC {
-    struct  {
-        UINT32       CmdToken3;
-        UINT32       CmdToken2;
-        UINT32       CmdToken1;
-        UINT32       CmdToken0;
-    } field;
-    UINT32           word;
-} M2H_CMD_DONE_STRUC, *PM2H_CMD_DONE_STRUC;
-#else
-typedef union _M2H_CMD_DONE_STRUC {
-    struct  {
-        UINT32       CmdToken0;
-        UINT32       CmdToken1;
-        UINT32       CmdToken2;
-        UINT32       CmdToken3;
-    } field;
-    UINT32           word;
-} M2H_CMD_DONE_STRUC, *PM2H_CMD_DONE_STRUC;
-#endif
-
-
-
-//
-// MCU_LEDCS: MCU LED Control Setting.
-//
-#ifdef RT_BIG_ENDIAN
-typedef union  _MCU_LEDCS_STRUC {
-	struct	{
-		UCHAR		Polarity:1;
-		UCHAR		LedMode:7;
-	} field;
-	UCHAR				word;
-} MCU_LEDCS_STRUC, *PMCU_LEDCS_STRUC;
-#else
-typedef union  _MCU_LEDCS_STRUC {
-	struct	{
-		UCHAR		LedMode:7;
-		UCHAR		Polarity:1;
-	} field;
-	UCHAR			word;
-} MCU_LEDCS_STRUC, *PMCU_LEDCS_STRUC;
-#endif
-// =================================================================================
-// Register format
-// =================================================================================
-
-
-
-//NAV_TIME_CFG :NAV
-#ifdef RT_BIG_ENDIAN
-typedef	union	_NAV_TIME_CFG_STRUC	{
-	struct	{
-		USHORT		rsv:6;
-		USHORT		ZeroSifs:1;               // Applied zero SIFS timer after OFDM RX 0: disable
-		USHORT		Eifs:9;               // in unit of 1-us
-		UCHAR       SlotTime;    // in unit of 1-us
-		UCHAR		Sifs;               // in unit of 1-us
-	}	field;
-	UINT32			word;
-}	NAV_TIME_CFG_STRUC, *PNAV_TIME_CFG_STRUC;
-#else
-typedef	union	_NAV_TIME_CFG_STRUC	{
-	struct	{
-		UCHAR		Sifs;               // in unit of 1-us
-		UCHAR       SlotTime;    // in unit of 1-us
-		USHORT		Eifs:9;               // in unit of 1-us
-		USHORT		ZeroSifs:1;               // Applied zero SIFS timer after OFDM RX 0: disable
-		USHORT		rsv:6;
-	}	field;
-	UINT32			word;
-}	NAV_TIME_CFG_STRUC, *PNAV_TIME_CFG_STRUC;
-#endif
-
-
-
-
-
-//
-// RX_FILTR_CFG:  /RX configuration register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	RX_FILTR_CFG_STRUC	{
-	struct	{
-		UINT32		:15;
-		UINT32       DropRsvCntlType:1;
-
-        	UINT32       	DropBAR:1;       //
-		UINT32		DropBA:1;		//
-		UINT32		DropPsPoll:1;		// Drop Ps-Poll
-		UINT32		DropRts:1;		// Drop Ps-Poll
-
-		UINT32		DropCts:1;		// Drop Ps-Poll
-		UINT32		DropAck:1;		// Drop Ps-Poll
-		UINT32		DropCFEnd:1;		// Drop Ps-Poll
-		UINT32		DropCFEndAck:1;		// Drop Ps-Poll
-
-		UINT32		DropDuplicate:1;		// Drop duplicate frame
-		UINT32		DropBcast:1;		// Drop broadcast frames
-		UINT32		DropMcast:1;		// Drop multicast frames
-		UINT32		DropVerErr:1;	    // Drop version error frame
-
-		UINT32		DropNotMyBSSID:1;			// Drop fram ToDs bit is true
-		UINT32		DropNotToMe:1;		// Drop not to me unicast frame
-		UINT32		DropPhyErr:1;		// Drop physical error
-		UINT32		DropCRCErr:1;		// Drop CRC error
-	}	field;
-	UINT32			word;
-}	RX_FILTR_CFG_STRUC, *PRX_FILTR_CFG_STRUC;
-#else
-typedef	union	_RX_FILTR_CFG_STRUC	{
-	struct	{
-		UINT32		DropCRCErr:1;		// Drop CRC error
-		UINT32		DropPhyErr:1;		// Drop physical error
-		UINT32		DropNotToMe:1;		// Drop not to me unicast frame
-		UINT32		DropNotMyBSSID:1;			// Drop fram ToDs bit is true
-
-		UINT32		DropVerErr:1;	    // Drop version error frame
-		UINT32		DropMcast:1;		// Drop multicast frames
-		UINT32		DropBcast:1;		// Drop broadcast frames
-		UINT32		DropDuplicate:1;		// Drop duplicate frame
-
-		UINT32		DropCFEndAck:1;		// Drop Ps-Poll
-		UINT32		DropCFEnd:1;		// Drop Ps-Poll
-		UINT32		DropAck:1;		// Drop Ps-Poll
-		UINT32		DropCts:1;		// Drop Ps-Poll
-
-		UINT32		DropRts:1;		// Drop Ps-Poll
-		UINT32		DropPsPoll:1;		// Drop Ps-Poll
-		UINT32		DropBA:1;		//
-        	UINT32       	DropBAR:1;       //
-
-		UINT32       	DropRsvCntlType:1;
-		UINT32		:15;
-	}	field;
-	UINT32			word;
-}	RX_FILTR_CFG_STRUC, *PRX_FILTR_CFG_STRUC;
-#endif
-
-
-
-
-//
-// PHY_CSR4: RF serial control register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_PHY_CSR4_STRUC	{
-	struct	{
-		UINT32		Busy:1;				// 1: ASIC is busy execute RF programming.
-		UINT32		PLL_LD:1;			// RF PLL_LD status
-		UINT32		IFSelect:1;			// 1: select IF	to program,	0: select RF to	program
-		UINT32		NumberOfBits:5;		// Number of bits used in RFRegValue (I:20,	RFMD:22)
-		UINT32		RFRegValue:24;		// Register	value (include register	id)	serial out to RF/IF	chip.
-	}	field;
-	UINT32			word;
-}	PHY_CSR4_STRUC, *PPHY_CSR4_STRUC;
-#else
-typedef	union	_PHY_CSR4_STRUC	{
-	struct	{
-		UINT32		RFRegValue:24;		// Register	value (include register	id)	serial out to RF/IF	chip.
-		UINT32		NumberOfBits:5;		// Number of bits used in RFRegValue (I:20,	RFMD:22)
-		UINT32		IFSelect:1;			// 1: select IF	to program,	0: select RF to	program
-		UINT32		PLL_LD:1;			// RF PLL_LD status
-		UINT32		Busy:1;				// 1: ASIC is busy execute RF programming.
-	}	field;
-	UINT32			word;
-}	PHY_CSR4_STRUC, *PPHY_CSR4_STRUC;
-#endif
-
-
-//
-// SEC_CSR5: shared key table security mode register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_SEC_CSR5_STRUC	{
-	struct	{
-        UINT32       :1;
-        UINT32       Bss3Key3CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key2CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key1CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key0CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key3CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key2CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key1CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key0CipherAlg:3;
-	}	field;
-	UINT32			word;
-}	SEC_CSR5_STRUC, *PSEC_CSR5_STRUC;
-#else
-typedef	union	_SEC_CSR5_STRUC	{
-	struct	{
-        UINT32       Bss2Key0CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key1CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key2CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key3CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key0CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key1CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key2CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key3CipherAlg:3;
-        UINT32       :1;
-	}	field;
-	UINT32			word;
-}	SEC_CSR5_STRUC, *PSEC_CSR5_STRUC;
-#endif
-
-
-//
-// HOST_CMD_CSR: For HOST to interrupt embedded processor
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_HOST_CMD_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:24;
-	    UINT32   HostCommand:8;
-	}	field;
-	UINT32			word;
-}	HOST_CMD_CSR_STRUC, *PHOST_CMD_CSR_STRUC;
-#else
-typedef	union	_HOST_CMD_CSR_STRUC	{
-	struct	{
-	    UINT32   HostCommand:8;
-	    UINT32   Rsv:24;
-	}	field;
-	UINT32			word;
-}	HOST_CMD_CSR_STRUC, *PHOST_CMD_CSR_STRUC;
-#endif
-
-
-//
-// AIFSN_CSR: AIFSN for each EDCA AC
-//
-
-
-
-//
-// E2PROM_CSR: EEPROM control register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_E2PROM_CSR_STRUC	{
-	struct	{
-		UINT32		Rsvd:25;
-		UINT32       LoadStatus:1;   // 1:loading, 0:done
-		UINT32		Type:1;			// 1: 93C46, 0:93C66
-		UINT32		EepromDO:1;
-		UINT32		EepromDI:1;
-		UINT32		EepromCS:1;
-		UINT32		EepromSK:1;
-		UINT32		Reload:1;		// Reload EEPROM content, write one to reload, self-cleared.
-	}	field;
-	UINT32			word;
-}	E2PROM_CSR_STRUC, *PE2PROM_CSR_STRUC;
-#else
-typedef	union	_E2PROM_CSR_STRUC	{
-	struct	{
-		UINT32		Reload:1;		// Reload EEPROM content, write one to reload, self-cleared.
-		UINT32		EepromSK:1;
-		UINT32		EepromCS:1;
-		UINT32		EepromDI:1;
-		UINT32		EepromDO:1;
-		UINT32		Type:1;			// 1: 93C46, 0:93C66
-		UINT32       LoadStatus:1;   // 1:loading, 0:done
-		UINT32		Rsvd:25;
-	}	field;
-	UINT32			word;
-}	E2PROM_CSR_STRUC, *PE2PROM_CSR_STRUC;
-#endif
-
-
-// -------------------------------------------------------------------
-//  E2PROM data layout
-// -------------------------------------------------------------------
-
-//
-// EEPROM antenna select format
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_ANTENNA_STRUC	{
-	struct	{
-		USHORT      Rsv:4;
-		USHORT      RfIcType:4;             // see E2PROM document
-		USHORT		TxPath:4;	// 1: 1T, 2: 2T
-		USHORT		RxPath:4;	// 1: 1R, 2: 2R, 3: 3R
-	}	field;
-	USHORT			word;
-}	EEPROM_ANTENNA_STRUC, *PEEPROM_ANTENNA_STRUC;
-#else
-typedef	union	_EEPROM_ANTENNA_STRUC	{
-	struct	{
-		USHORT		RxPath:4;	// 1: 1R, 2: 2R, 3: 3R
-		USHORT		TxPath:4;	// 1: 1T, 2: 2T
-		USHORT      RfIcType:4;             // see E2PROM document
-		USHORT      Rsv:4;
-	}	field;
-	USHORT			word;
-}	EEPROM_ANTENNA_STRUC, *PEEPROM_ANTENNA_STRUC;
-#endif
-
-#ifdef RT_BIG_ENDIAN
-typedef	union _EEPROM_NIC_CINFIG2_STRUC	{
-	struct	{
-        USHORT		Rsv2:6;					// must be 0
-		USHORT		BW40MAvailForA:1;			// 0:enable, 1:disable
-		USHORT		BW40MAvailForG:1;			// 0:enable, 1:disable
-		USHORT		EnableWPSPBC:1;                 // WPS PBC Control bit
-		USHORT		BW40MSidebandForA:1;
-		USHORT		BW40MSidebandForG:1;
-		USHORT		CardbusAcceleration:1;	// !!! NOTE: 0 - enable, 1 - disable
-		USHORT		ExternalLNAForA:1;			// external LNA enable for 5G
-		USHORT		ExternalLNAForG:1;			// external LNA enable for 2.4G
-		USHORT		DynamicTxAgcControl:1;			//
-		USHORT		HardwareRadioControl:1;	// Whether RF is controlled by driver or HW. 1:enable hw control, 0:disable
-	}	field;
-	USHORT			word;
-}	EEPROM_NIC_CONFIG2_STRUC, *PEEPROM_NIC_CONFIG2_STRUC;
-#else
-typedef	union _EEPROM_NIC_CINFIG2_STRUC	{
-	struct {
-		USHORT		HardwareRadioControl:1;	// 1:enable, 0:disable
-		USHORT		DynamicTxAgcControl:1;			//
-		USHORT		ExternalLNAForG:1;				//
-		USHORT		ExternalLNAForA:1;			// external LNA enable for 2.4G
-		USHORT		CardbusAcceleration:1;	// !!! NOTE: 0 - enable, 1 - disable
-		USHORT		BW40MSidebandForG:1;
-		USHORT		BW40MSidebandForA:1;
-		USHORT		EnableWPSPBC:1;                 // WPS PBC Control bit
-		USHORT		BW40MAvailForG:1;			// 0:enable, 1:disable
-		USHORT		BW40MAvailForA:1;			// 0:enable, 1:disable
-		USHORT		Rsv2:6;                 // must be 0
-	}	field;
-	USHORT			word;
-}	EEPROM_NIC_CONFIG2_STRUC, *PEEPROM_NIC_CONFIG2_STRUC;
-#endif
-
-//
-// TX_PWR Value valid range 0xFA(-6) ~ 0x24(36)
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_TX_PWR_STRUC	{
-	struct	{
-		CHAR	Byte1;				// High Byte
-		CHAR	Byte0;				// Low Byte
-	}	field;
-	USHORT	word;
-}	EEPROM_TX_PWR_STRUC, *PEEPROM_TX_PWR_STRUC;
-#else
-typedef	union	_EEPROM_TX_PWR_STRUC	{
-	struct	{
-		CHAR	Byte0;				// Low Byte
-		CHAR	Byte1;				// High Byte
-	}	field;
-	USHORT	word;
-}	EEPROM_TX_PWR_STRUC, *PEEPROM_TX_PWR_STRUC;
-#endif
-
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_VERSION_STRUC	{
-	struct	{
-		UCHAR	Version;			// High Byte
-		UCHAR	FaeReleaseNumber;	// Low Byte
-	}	field;
-	USHORT	word;
-}	EEPROM_VERSION_STRUC, *PEEPROM_VERSION_STRUC;
-#else
-typedef	union	_EEPROM_VERSION_STRUC	{
-	struct	{
-		UCHAR	FaeReleaseNumber;	// Low Byte
-		UCHAR	Version;			// High Byte
-	}	field;
-	USHORT	word;
-}	EEPROM_VERSION_STRUC, *PEEPROM_VERSION_STRUC;
-#endif
-
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_LED_STRUC	{
-	struct	{
-		USHORT	Rsvd:3;				// Reserved
-		USHORT	LedMode:5;			// Led mode.
-		USHORT	PolarityGPIO_4:1;	// Polarity GPIO#4 setting.
-		USHORT	PolarityGPIO_3:1;	// Polarity GPIO#3 setting.
-		USHORT	PolarityGPIO_2:1;	// Polarity GPIO#2 setting.
-		USHORT	PolarityGPIO_1:1;	// Polarity GPIO#1 setting.
-		USHORT	PolarityGPIO_0:1;	// Polarity GPIO#0 setting.
-		USHORT	PolarityACT:1;		// Polarity ACT setting.
-		USHORT	PolarityRDY_A:1;		// Polarity RDY_A setting.
-		USHORT	PolarityRDY_G:1;		// Polarity RDY_G setting.
-	}	field;
-	USHORT	word;
-}	EEPROM_LED_STRUC, *PEEPROM_LED_STRUC;
-#else
-typedef	union	_EEPROM_LED_STRUC	{
-	struct	{
-		USHORT	PolarityRDY_G:1;		// Polarity RDY_G setting.
-		USHORT	PolarityRDY_A:1;		// Polarity RDY_A setting.
-		USHORT	PolarityACT:1;		// Polarity ACT setting.
-		USHORT	PolarityGPIO_0:1;	// Polarity GPIO#0 setting.
-		USHORT	PolarityGPIO_1:1;	// Polarity GPIO#1 setting.
-		USHORT	PolarityGPIO_2:1;	// Polarity GPIO#2 setting.
-		USHORT	PolarityGPIO_3:1;	// Polarity GPIO#3 setting.
-		USHORT	PolarityGPIO_4:1;	// Polarity GPIO#4 setting.
-		USHORT	LedMode:5;			// Led mode.
-		USHORT	Rsvd:3;				// Reserved
-	}	field;
-	USHORT	word;
-}	EEPROM_LED_STRUC, *PEEPROM_LED_STRUC;
-#endif
-
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_TXPOWER_DELTA_STRUC	{
-	struct	{
-		UCHAR	TxPowerEnable:1;// Enable
-		UCHAR	Type:1;			// 1: plus the delta value, 0: minus the delta value
-		UCHAR	DeltaValue:6;	// Tx Power dalta value (MAX=4)
-	}	field;
-	UCHAR	value;
-}	EEPROM_TXPOWER_DELTA_STRUC, *PEEPROM_TXPOWER_DELTA_STRUC;
-#else
-typedef	union	_EEPROM_TXPOWER_DELTA_STRUC	{
-	struct	{
-		UCHAR	DeltaValue:6;	// Tx Power dalta value (MAX=4)
-		UCHAR	Type:1;			// 1: plus the delta value, 0: minus the delta value
-		UCHAR	TxPowerEnable:1;// Enable
-	}	field;
-	UCHAR	value;
-}	EEPROM_TXPOWER_DELTA_STRUC, *PEEPROM_TXPOWER_DELTA_STRUC;
-#endif
-
-//
-// QOS_CSR0: TXOP holder address0 register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_QOS_CSR0_STRUC	{
-	struct	{
-		UCHAR		Byte3;		// MAC address byte 3
-		UCHAR		Byte2;		// MAC address byte 2
-		UCHAR		Byte1;		// MAC address byte 1
-		UCHAR		Byte0;		// MAC address byte 0
-	}	field;
-	UINT32			word;
-}	QOS_CSR0_STRUC, *PQOS_CSR0_STRUC;
-#else
-typedef	union	_QOS_CSR0_STRUC	{
-	struct	{
-		UCHAR		Byte0;		// MAC address byte 0
-		UCHAR		Byte1;		// MAC address byte 1
-		UCHAR		Byte2;		// MAC address byte 2
-		UCHAR		Byte3;		// MAC address byte 3
-	}	field;
-	UINT32			word;
-}	QOS_CSR0_STRUC, *PQOS_CSR0_STRUC;
-#endif
-
-//
-// QOS_CSR1: TXOP holder address1 register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_QOS_CSR1_STRUC	{
-	struct	{
-		UCHAR		Rsvd1;
-		UCHAR		Rsvd0;
-		UCHAR		Byte5;		// MAC address byte 5
-		UCHAR		Byte4;		// MAC address byte 4
-	}	field;
-	UINT32			word;
-}	QOS_CSR1_STRUC, *PQOS_CSR1_STRUC;
-#else
-typedef	union	_QOS_CSR1_STRUC	{
-	struct	{
-		UCHAR		Byte4;		// MAC address byte 4
-		UCHAR		Byte5;		// MAC address byte 5
-		UCHAR		Rsvd0;
-		UCHAR		Rsvd1;
-	}	field;
-	UINT32			word;
-}	QOS_CSR1_STRUC, *PQOS_CSR1_STRUC;
-#endif
-
-#define	RF_CSR_CFG	0x500
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG_STRUC	{
-	struct	{
-		UINT	Rsvd1:14;				// Reserved
-		UINT	RF_CSR_KICK:1;			// kick RF register read/write
-		UINT	RF_CSR_WR:1;			// 0: read  1: write
-		UINT	Rsvd2:3;				// Reserved
-		UINT	TESTCSR_RFACC_REGNUM:5;	// RF register ID
-		UINT	RF_CSR_DATA:8;			// DATA
-	}	field;
-	UINT	word;
-}	RF_CSR_CFG_STRUC, *PRF_CSR_CFG_STRUC;
-#else
-typedef	union	_RF_CSR_CFG_STRUC	{
-	struct	{
-		UINT	RF_CSR_DATA:8;			// DATA
-		UINT	TESTCSR_RFACC_REGNUM:5;	// RF register ID
-		UINT	Rsvd2:3;				// Reserved
-		UINT	RF_CSR_WR:1;			// 0: read  1: write
-		UINT	RF_CSR_KICK:1;			// kick RF register read/write
-		UINT	Rsvd1:14;				// Reserved
-	}	field;
-	UINT	word;
-}	RF_CSR_CFG_STRUC, *PRF_CSR_CFG_STRUC;
-#endif
-
-#endif	// __RT28XX_H__
+#include "../rt2860/rt28xx.h"
diff --git a/drivers/staging/rt2870/rt_ate.c b/drivers/staging/rt2870/rt_ate.c
deleted file mode 100644
index 27c763ee..0000000
--- a/drivers/staging/rt2870/rt_ate.c
+++ /dev/null
@@ -1,6452 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#include "rt_config.h"
-
-#ifdef UCOS
-INT IoctlResponse(PUCHAR payload, PUCHAR msg, INT len);
-#endif // UCOS //
-
-#ifdef RALINK_ATE
-UCHAR TemplateFrame[24] = {0x08/* Data type */,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0xAA,0xBB,0x12,0x34,0x56,0x00,0x11,0x22,0xAA,0xBB,0xCC,0x00,0x00};	// 802.11 MAC Header, Type:Data, Length:24bytes
-extern RTMP_RF_REGS RF2850RegTable[];
-extern UCHAR NUM_OF_2850_CHNL;
-
-#ifdef RT2870
-extern UCHAR EpToQueue[];
-extern VOID	RTUSBRejectPendingPackets(	IN	PRTMP_ADAPTER	pAd);
-#endif // RT2870 //
-
-#ifdef UCOS
-extern INT ConsoleResponse(IN PUCHAR buff);
-extern int (*remote_display)(char *);
-#endif // UCOS //
-
-static CHAR CCKRateTable[] = {0, 1, 2, 3, 8, 9, 10, 11, -1}; /* CCK Mode. */
-static CHAR OFDMRateTable[] = {0, 1, 2, 3, 4, 5, 6, 7, -1}; /* OFDM Mode. */
-static CHAR HTMIXRateTable[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1}; /* HT Mix Mode. */
-
-static INT TxDmaBusy(
-	IN PRTMP_ADAPTER pAd);
-
-static INT RxDmaBusy(
-	IN PRTMP_ADAPTER pAd);
-
-static VOID RtmpDmaEnable(
-	IN PRTMP_ADAPTER pAd,
-	IN INT Enable);
-
-static VOID BbpSoftReset(
-	IN PRTMP_ADAPTER pAd);
-
-static VOID RtmpRfIoWrite(
-	IN PRTMP_ADAPTER pAd);
-
-static INT ATESetUpFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT32 TxIdx);
-
-static INT ATETxPwrHandler(
-	IN PRTMP_ADAPTER pAd,
-	IN char index);
-
-static INT ATECmdHandler(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-static int CheckMCSValid(
-	IN UCHAR Mode,
-	IN UCHAR Mcs);
-
-
-#ifdef RT2870
-static VOID ATEWriteTxInfo(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXINFO_STRUC 	pTxInfo,
-	IN	  USHORT		USBDMApktLen,
-	IN	  BOOLEAN		bWiv,
-	IN	  UCHAR			QueueSel,
-	IN	  UCHAR			NextValid,
-	IN	  UCHAR			TxBurst);
-
-static VOID ATEWriteTxWI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXWI_STRUC 	pTxWI,
-	IN	BOOLEAN			FRAG,
-	IN	BOOLEAN			InsTimestamp,
-	IN	BOOLEAN 		AMPDU,
-	IN	BOOLEAN 		Ack,
-	IN	BOOLEAN 		NSeq,		// HW new a sequence.
-	IN	UCHAR			BASize,
-	IN	UCHAR			WCID,
-	IN	ULONG			Length,
-	IN	UCHAR 			PID,
-	IN	UCHAR			MIMOps,
-	IN	UCHAR			Txopmode,
-	IN	BOOLEAN			CfAck,
-	IN	HTTRANSMIT_SETTING	Transmit);
-
-#endif // RT2870 //
-
-static VOID SetJapanFilter(
-	IN	PRTMP_ADAPTER	pAd);
-
-/*=========================end of prototype=========================*/
-
-
-#ifdef RT2870
-static INT TxDmaBusy(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT result;
-	USB_DMA_CFG_STRUC UsbCfg;
-
-	RTMP_IO_READ32(pAd, USB_DMA_CFG, &UsbCfg.word);	// disable DMA
-	if (UsbCfg.field.TxBusy)
-		result = 1;
-	else
-		result = 0;
-
-	return result;
-}
-
-static INT RxDmaBusy(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT result;
-	USB_DMA_CFG_STRUC UsbCfg;
-
-	RTMP_IO_READ32(pAd, USB_DMA_CFG, &UsbCfg.word);	// disable DMA
-	if (UsbCfg.field.RxBusy)
-		result = 1;
-	else
-		result = 0;
-
-	return result;
-}
-
-static VOID RtmpDmaEnable(
-	IN PRTMP_ADAPTER pAd,
-	IN INT Enable)
-{
-	BOOLEAN value;
-	ULONG WaitCnt;
-	USB_DMA_CFG_STRUC UsbCfg;
-
-	value = Enable > 0 ? 1 : 0;
-
-	// check DMA is in busy mode.
-	WaitCnt = 0;
-	while (TxDmaBusy(pAd) || RxDmaBusy(pAd))
-	{
-		RTMPusecDelay(10);
-		if (WaitCnt++ > 100)
-			break;
-	}
-
-	//Why not to clear USB DMA TX path first ???
-	RTMP_IO_READ32(pAd, USB_DMA_CFG, &UsbCfg.word);	// disable DMA
-	UsbCfg.field.TxBulkEn = value;
-	UsbCfg.field.RxBulkEn = value;
-	RTMP_IO_WRITE32(pAd, USB_DMA_CFG, UsbCfg.word);	// abort all TX rings
-	RTMPusecDelay(5000);
-
-	return;
-}
-#endif // RT2870 //
-
-static VOID BbpSoftReset(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR BbpData = 0;
-
-	// Soft reset, set BBP R21 bit0=1->0
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R21, &BbpData);
-	BbpData |= 0x00000001; //set bit0=1
-	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R21, BbpData);
-
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R21, &BbpData);
-	BbpData &= ~(0x00000001); //set bit0=0
-	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R21, BbpData);
-
-	return;
-}
-
-static VOID RtmpRfIoWrite(
-	IN PRTMP_ADAPTER pAd)
-{
-	// Set RF value 1's set R3[bit2] = [0]
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-	RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-	RTMPusecDelay(200);
-
-	// Set RF value 2's set R3[bit2] = [1]
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-	RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 | 0x04));
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-	RTMPusecDelay(200);
-
-	// Set RF value 3's set R3[bit2] = [0]
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-	RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-	return;
-}
-
-static int CheckMCSValid(
-	UCHAR Mode,
-	UCHAR Mcs)
-{
-	int i;
-	PCHAR pRateTab;
-
-	switch(Mode)
-	{
-		case 0:
-			pRateTab = CCKRateTable;
-			break;
-		case 1:
-			pRateTab = OFDMRateTable;
-			break;
-		case 2:
-		case 3:
-			pRateTab = HTMIXRateTable;
-			break;
-		default:
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("unrecognizable Tx Mode %d\n", Mode));
-			return -1;
-			break;
-	}
-
-	i = 0;
-	while(pRateTab[i] != -1)
-	{
-		if (pRateTab[i] == Mcs)
-			return 0;
-		i++;
-	}
-
-	return -1;
-}
-
-#if 1
-static INT ATETxPwrHandler(
-	IN PRTMP_ADAPTER pAd,
-	IN char index)
-{
-	ULONG R;
-	CHAR TxPower;
-	UCHAR Bbp94 = 0;
-	BOOLEAN bPowerReduce = FALSE;
-
-#ifdef RALINK_28xx_QA
-	if ((pAd->ate.bQATxStart == TRUE) || (pAd->ate.bQARxStart == TRUE))
-	{
-		/* When QA is used for Tx, pAd->ate.TxPower0/1 and real tx power
-		** are not synchronized.
-		*/
-/*
-		pAd->ate.TxPower0 = pAd->LatchRfRegs.xxx;
-		pAd->ate.TxPower1 = pAd->LatchRfRegs.xxx;
-*/
-		return 0;
-	}
-	else
-#endif // RALINK_28xx_QA //
-	{
-		TxPower = index == 0 ? pAd->ate.TxPower0 : pAd->ate.TxPower1;
-
-		if (pAd->ate.Channel <= 14)
-		{
-			if (TxPower > 31)
-			{
-				//
-				// R3, R4 can't large than 31 (0x24), 31 ~ 36 used by BBP 94
-				//
-				R = 31;
-				if (TxPower <= 36)
-					Bbp94 = BBPR94_DEFAULT + (UCHAR)(TxPower - 31);
-			}
-			else if (TxPower < 0)
-			{
-				//
-				// R3, R4 can't less than 0, -1 ~ -6 used by BBP 94
-				//
-				R = 0;
-				if (TxPower >= -6)
-					Bbp94 = BBPR94_DEFAULT + TxPower;
-			}
-			else
-			{
-				// 0 ~ 31
-				R = (ULONG) TxPower;
-				Bbp94 = BBPR94_DEFAULT;
-			}
-
-			ATEDBGPRINT(RT_DEBUG_TRACE, ("%s (TxPower=%d, R=%ld, BBP_R94=%d)\n", __func__, TxPower, R, Bbp94));
-		}
-		else// 5.5 GHz
-		{
-			if (TxPower > 15)
-			{
-				//
-				// R3, R4 can't large than 15 (0x0F)
-				//
-				R = 15;
-			}
-			else if (TxPower < 0)
-			{
-				//
-				// R3, R4 can't less than 0
-				//
-				// -1 ~ -7
-				ASSERT((TxPower >= -7));
-				R = (ULONG)(TxPower + 7);
-				bPowerReduce = TRUE;
-			}
-			else
-			{
-				// 0 ~ 15
-				R = (ULONG) TxPower;
-			}
-
-			ATEDBGPRINT(RT_DEBUG_TRACE, ("%s (TxPower=%d, R=%lu)\n", __func__, TxPower, R));
-		}
-
-		if (pAd->ate.Channel <= 14)
-		{
-			if (index == 0)
-			{
-				R = R << 9;		// shift TX power control to correct RF(R3) register bit position
-				R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-				pAd->LatchRfRegs.R3 = R;
-			}
-			else
-			{
-				R = R << 6;		// shift TX power control to correct RF(R4) register bit position
-				R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-				pAd->LatchRfRegs.R4 = R;
-			}
-		}
-		else// 5.5GHz
-		{
-			if (bPowerReduce == FALSE)
-			{
-				if (index == 0)
-				{
-					R = (R << 10) | (1 << 9);		// shift TX power control to correct RF(R3) register bit position
-					R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-					pAd->LatchRfRegs.R3 = R;
-				}
-				else
-				{
-					R = (R << 7) | (1 << 6);		// shift TX power control to correct RF(R4) register bit position
-					R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-					pAd->LatchRfRegs.R4 = R;
-				}
-			}
-			else
-			{
-				if (index == 0)
-				{
-					R = (R << 10);		// shift TX power control to correct RF(R3) register bit position
-					R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-
-					/* Clear bit 9 of R3 to reduce 7dB. */
-					pAd->LatchRfRegs.R3 = (R & (~(1 << 9)));
-				}
-				else
-				{
-					R = (R << 7);		// shift TX power control to correct RF(R4) register bit position
-					R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-
-					/* Clear bit 6 of R4 to reduce 7dB. */
-					pAd->LatchRfRegs.R4 = (R & (~(1 << 6)));
-				}
-			}
-		}
-
-		RtmpRfIoWrite(pAd);
-
-		return 0;
-	}
-}
-#else// 1 //
-static INT ATETxPwrHandler(
-	IN PRTMP_ADAPTER pAd,
-	IN char index)
-{
-	ULONG R;
-	CHAR TxPower;
-	UCHAR Bbp94 = 0;
-
-#ifdef RALINK_28xx_QA
-	if ((pAd->ate.bQATxStart == TRUE) || (pAd->ate.bQARxStart == TRUE))
-	{
-		// TODO: how to get current TxPower0/1 from pAd->LatchRfRegs ?
-		/* When QA is used for Tx, pAd->ate.TxPower0/1 and real tx power
-		** are not synchronized.
-		*/
-/*
-		pAd->ate.TxPower0 = pAd->LatchRfRegs.xxx;
-		pAd->ate.TxPower1 = pAd->LatchRfRegs.xxx;
-*/
-		return 0;
-	}
-	else
-#endif // RALINK_28xx_QA //
-	{
-		TxPower = index == 0 ? pAd->ate.TxPower0 : pAd->ate.TxPower1;
-
-	if (TxPower > 31)
-	{
-		//
-		// R3, R4 can't large than 36 (0x24), 31 ~ 36 used by BBP 94
-		//
-		R = 31;
-		if (TxPower <= 36)
-			Bbp94 = BBPR94_DEFAULT + (UCHAR)(TxPower - 31);
-	}
-	else if (TxPower < 0)
-	{
-		//
-		// R3, R4 can't less than 0, -1 ~ -6 used by BBP 94
-		//
-		R = 0;
-		if (TxPower >= -6)
-			Bbp94 = BBPR94_DEFAULT + TxPower;
-	}
-	else
-	{
-		// 0 ~ 31
-		R = (ULONG) TxPower;
-		Bbp94 = BBPR94_DEFAULT;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("%s (TxPower=%d, R3=%ld, BBP_R94=%d)\n", __func__, TxPower, R, Bbp94));
-
-		if (pAd->ate.Channel <= 14)
-		{
-	if (index == 0)
-	{
-		R = R << 9;		// shift TX power control to correct RF(R3) register bit position
-		R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-		pAd->LatchRfRegs.R3 = R;
-	}
-	else
-	{
-		R = R << 6;		// shift TX power control to correct RF(R4) register bit position
-		R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-		pAd->LatchRfRegs.R4 = R;
-	}
-		}
-		else
-		{
-			if (index == 0)
-			{
-				R = (R << 10) | (1 << 9);		// shift TX power control to correct RF(R3) register bit position
-				R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-				pAd->LatchRfRegs.R3 = R;
-			}
-			else
-			{
-				R = (R << 7) | (1 << 6);		// shift TX power control to correct RF(R4) register bit position
-				R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-				pAd->LatchRfRegs.R4 = R;
-			}
-		}
-
-	RtmpRfIoWrite(pAd);
-
-	return 0;
-	}
-}
-#endif // 1 //
-/*
-    ==========================================================================
-    Description:
-        Set ATE operation mode to
-        0. ATESTART  = Start ATE Mode
-        1. ATESTOP   = Stop ATE Mode
-        2. TXCONT    = Continuous Transmit
-        3. TXCARR    = Transmit Carrier
-        4. TXFRAME   = Transmit Frames
-        5. RXFRAME   = Receive Frames
-#ifdef RALINK_28xx_QA
-        6. TXSTOP    = Stop Any Type of Transmition
-        7. RXSTOP    = Stop Receiving Frames
-#endif // RALINK_28xx_QA //
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-/*                                                           */
-/*                                                           */
-/*=======================End of RT2860=======================*/
-
-
-/*======================Start of RT2870======================*/
-/*                                                           */
-/*                                                           */
-
-#ifdef RT2870
-static INT	ATECmdHandler(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT32			Value;
-	UCHAR			BbpData;
-	UINT32          MacData;
-	UINT			i=0, atemode;
-	//NDIS_STATUS		Status = NDIS_STATUS_SUCCESS;
-	//PUCHAR			pDest;
-	UINT32 			temp;
-	ULONG			IrqFlags;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("===> ATECmdHandler()\n"));
-	ATEAsicSwitchChannel(pAd);
-	/* AsicLockChannel() is empty function so far in fact */
-	AsicLockChannel(pAd, pAd->ate.Channel);
-
-	RTMPusecDelay(5000);
-
-	// Default value in BBP R22 is 0x0.
-	BbpData = 0;
-
-	/* Enter ATE mode and set Tx/Rx Idle */
-	if (!strcmp(arg, "ATESTART"))
-	{
-#ifdef CONFIG_STA_SUPPORT
-		BOOLEAN       Cancelled;
-#endif // CONFIG_STA_SUPPORT //
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: ATESTART\n"));
-
-		netif_stop_queue(pAd->net_dev);
-
-		atemode = pAd->ate.Mode;
-		pAd->ate.Mode = ATE_START;
-//		pAd->ate.TxDoneCount = pAd->ate.TxCount;
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Disable auto responder
-		RTMP_IO_READ32(pAd, AUTO_RSP_CFG, &temp);
-		temp = temp & 0xFFFFFFFE;
-		RTMP_IO_WRITE32(pAd, AUTO_RSP_CFG, temp);
-
-		// read MAC_SYS_CTRL and backup MAC_SYS_CTRL value.
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-		// clean bit4 to stop continuous Tx production test.
-		MacData &= 0xFFFFFFEF;
-		// Stop continuous TX production test.
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);//disable or cancel pending irp first ???
-
-        if (atemode & ATE_TXCARR)
-		{
-			// No Carrier Test set BBP R22 bit7=0, bit6=0, bit[5~0]=0x0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF00; //clear bit7, bit6, bit[5~0]
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		}
-		else if (atemode & ATE_TXCARRSUPP)
-		{
-			// No Cont. TX set BBP R22 bit7=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= ~(1 << 7); //set bit7=0
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-			// No Carrier Suppression set BBP R24 bit0=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R24, &BbpData);
-			BbpData &= 0xFFFFFFFE; //clear bit0
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, BbpData);
-		}
-		// We should free some resource which allocate when ATE_TXFRAME , ATE_STOP, and ATE_TXCONT.
-		// TODO:Should we free some resource which was allocated when LoopBack and ATE_STOP ?
-		else if ((atemode & ATE_TXFRAME) || (atemode == ATE_STOP))
-		{
-			if (atemode & ATE_TXCONT)
-			{
-				// Not Cont. TX anymore, so set BBP R22 bit7=0
-				ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-				BbpData &= ~(1 << 7); //set bit7=0
-				ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-			}
-			// Abort Tx, Rx DMA.
-			RtmpDmaEnable(pAd, 0);
-
-			{
-				// It seems nothing to free,
-				// because we didn't allocate any resource when we entered ATE_TXFRAME mode latestly.
-			}
-
-			// Start Tx, RX DMA
-			RtmpDmaEnable(pAd, 1);
-		}
-
-		RTUSBRejectPendingPackets(pAd);
-		RTUSBCleanUpDataBulkOutQueue(pAd);
-
-#ifdef CONFIG_STA_SUPPORT
-		//
-		// It will be called in MlmeSuspend().
-		//
-		// Cancel pending timers
-		RTMPCancelTimer(&pAd->MlmeAux.AssocTimer,     &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer,   &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer,   &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.AuthTimer,       &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer,     &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer,       &Cancelled);
-#endif // CONFIG_STA_SUPPORT //
-
-		//RTUSBCleanUpMLMEWaitQueue(pAd);	/* not used in RT28xx */
-		RTUSBCleanUpMLMEBulkOutQueue(pAd);
-
-		// Sometimes kernel will hang on, so we avoid calling MlmeSuspend().
-//		MlmeSuspend(pAd, TRUE);
-		//RTMPCancelTimer(&pAd->Mlme.PeriodicTimer, &Cancelled);
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-		// Disable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Make sure there are no pending bulk in/out IRPs before we go on.
-/*=========================================================================*/
-		/* pAd->PendingRx is not of type atomic_t anymore in 28xx */
-//		while ((atomic_read(&pAd->PendingRx) > 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		while ((pAd->PendingRx > 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		{
-#if 1
-			ATE_RTUSBCancelPendingBulkInIRP(pAd);
-#else
-			NdisInterlockedDecrement(&pAd->PendingRx);
-#endif
-			/* delay 0.5 seconds */
-			RTMPusecDelay(500000);
-			pAd->PendingRx = 0;
-		}
-		/* peter : why don't we have to get BulkOutLock first ? */
-		while (((pAd->BulkOutPending[0] == TRUE) ||
-				(pAd->BulkOutPending[1] == TRUE) ||
-				(pAd->BulkOutPending[2] == TRUE) ||
-				(pAd->BulkOutPending[3] == TRUE)) && (pAd->BulkFlags != 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		{
-			do
-			{
-				/* pAd->BulkOutPending[y] will be set to FALSE in RTUSBCancelPendingBulkOutIRP(pAd) */
-				RTUSBCancelPendingBulkOutIRP(pAd);
-			} while (FALSE);
-
-			/* we have enough time delay in RTUSBCancelPendingBulkOutIRP(pAd)
-			** so this is not necessary
-			*/
-//			RTMPusecDelay(500000);
-		}
-
-		/* pAd->PendingRx is not of type atomic_t anymore in 28xx */
-//		ASSERT(atomic_read(&pAd->PendingRx) == 0);
-		ASSERT(pAd->PendingRx == 0);
-/*=========================================================================*/
-
-		// reset Rx statistics.
-		pAd->ate.LastSNR0 = 0;
-		pAd->ate.LastSNR1 = 0;
-		pAd->ate.LastRssi0 = 0;
-		pAd->ate.LastRssi1 = 0;
-		pAd->ate.LastRssi2 = 0;
-		pAd->ate.AvgRssi0 = 0;
-		pAd->ate.AvgRssi1 = 0;
-		pAd->ate.AvgRssi2 = 0;
-		pAd->ate.AvgRssi0X8 = 0;
-		pAd->ate.AvgRssi1X8 = 0;
-		pAd->ate.AvgRssi2X8 = 0;
-		pAd->ate.NumOfAvgRssiSample = 0;
-
-#ifdef RALINK_28xx_QA
-		// Tx frame
-		pAd->ate.bQATxStart = FALSE;
-		pAd->ate.bQARxStart = FALSE;
-		pAd->ate.seq = 0;
-
-		// counters
-		pAd->ate.U2M = 0;
-		pAd->ate.OtherData = 0;
-		pAd->ate.Beacon = 0;
-		pAd->ate.OtherCount = 0;
-		pAd->ate.TxAc0 = 0;
-		pAd->ate.TxAc1 = 0;
-		pAd->ate.TxAc2 = 0;
-		pAd->ate.TxAc3 = 0;
-		pAd->ate.TxHCCA = 0;
-		pAd->ate.TxMgmt = 0;
-		pAd->ate.RSSI0 = 0;
-		pAd->ate.RSSI1 = 0;
-		pAd->ate.RSSI2 = 0;
-		pAd->ate.SNR0 = 0;
-		pAd->ate.SNR1 = 0;
-
-		// control
-		pAd->ate.TxDoneCount = 0;
-		pAd->ate.TxStatus = 0; // task Tx status // 0 --> task is idle, 1 --> task is running
-#endif // RALINK_28xx_QA //
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-
-#ifdef CONFIG_STA_SUPPORT
-		AsicDisableSync(pAd);
-
-		/*
-		** If we skip "LinkDown()", we should disable protection
-		** to prevent from sending out RTS or CTS-to-self.
-		*/
-		ATEDisableAsicProtect(pAd);
-		RTMPStationStop(pAd);
-#endif // CONFIG_STA_SUPPORT //
-
-		// Default value in BBP R22 is 0x0.
-		BbpData = 0;
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-
-		// Clean bit4 to stop continuous Tx production test.
-		MacData &= 0xFFFFFFEF;
-	   	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-	    	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-		//Clean ATE Bulk in/out counter and continue setup
-		InterlockedExchange(&pAd->BulkOutRemained, 0);
-
-		/* NdisAcquireSpinLock()/NdisReleaseSpinLock() need only one argument in RT28xx */
-		NdisAcquireSpinLock(&pAd->GenericLock);
-		pAd->ContinBulkOut = FALSE;
-		pAd->ContinBulkIn = FALSE;
-		NdisReleaseSpinLock(&pAd->GenericLock);
-
-		RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-	}
-	else if (!strcmp(arg, "ATESTOP"))
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE : ATESTOP ===>\n"));
-
-		// Default value in BBP R22 is 0x0.
-		BbpData = 0;
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);//0820
-		// Clean bit4 to stop continuous Tx production test.
-		MacData &= 0xFFFFFFEF;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData); // recover the MAC_SYS_CTRL register back.
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		/*
-		** Abort Tx, RX DMA.
-		** Q   : How to do the following I/O if Tx, Rx DMA is aborted ?
-		** Ans : Bulk endpoints are aborted, while the control endpoint is not.
-		*/
-		RtmpDmaEnable(pAd, 0);
-
-		// Disable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		/* Make sure there are no pending bulk in/out IRPs before we go on. */
-/*=========================================================================*/
-//		while ((atomic_read(&pAd->PendingRx) > 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		while (pAd->PendingRx > 0)
-		{
-#if 1
-			ATE_RTUSBCancelPendingBulkInIRP(pAd);
-#else
-//			NdisInterlockedDecrement(&pAd->PendingRx);
-			pAd->PendingRx--;
-#endif
-			RTMPusecDelay(500000);
-		}
-
-		while (((pAd->BulkOutPending[0] == TRUE) ||
-				(pAd->BulkOutPending[1] == TRUE) ||
-				(pAd->BulkOutPending[2] == TRUE) ||
-				(pAd->BulkOutPending[3] == TRUE)) && (pAd->BulkFlags != 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		{
-			do
-			{
-				RTUSBCancelPendingBulkOutIRP(pAd);
-			} while (FALSE);
-
-			RTMPusecDelay(500000);
-		}
-
-//		ASSERT(atomic_read(&pAd->PendingRx) == 0);
-		ASSERT(pAd->PendingRx == 0);
-/*=========================================================================*/
-/*      Reset Rx RING                                                      */
-/*=========================================================================*/
-//		InterlockedExchange(&pAd->PendingRx, 0);
-		pAd->PendingRx = 0;
-		pAd->NextRxBulkInReadIndex = 0;	// Next Rx Read index
-		pAd->NextRxBulkInIndex = RX_RING_SIZE - 1;	// Rx Bulk pointer
-		pAd->NextRxBulkInPosition = 0;
-		for (i = 0; i < (RX_RING_SIZE); i++)
-		{
-			PRX_CONTEXT  pRxContext = &(pAd->RxContext[i]);
-			NdisZeroMemory(pRxContext->TransferBuffer, MAX_RXBULK_SIZE);
-			/* peter : why don't we have to get BulkInLock first ? */
-			pRxContext->pAd	= pAd;
-			pRxContext->pIrp = NULL;
-            /* peter debug ++ */
-			pRxContext->BulkInOffset = 0;
-			pRxContext->bRxHandling = FALSE;
-            /* peter debug -- */
-			pRxContext->InUse		= FALSE;
-			pRxContext->IRPPending	= FALSE;
-			pRxContext->Readable	= FALSE;
-//			pRxContext->ReorderInUse = FALSE;
-//			pRxContext->ReadPosOffset = 0;
-		}
-
-/*=========================================================================*/
-/*      Reset Tx RING                                                      */
-/*=========================================================================*/
-		do
-		{
-			RTUSBCancelPendingBulkOutIRP(pAd);
-		} while (FALSE);
-
-/*=========================================================================*/
-		// Enable auto responder.
-		RTMP_IO_READ32(pAd, AUTO_RSP_CFG, &temp);
-		temp = temp | (0x01);
-		RTMP_IO_WRITE32(pAd, AUTO_RSP_CFG, temp);
-
-/*================================================*/
-		AsicEnableBssSync(pAd);
-
-		/* Soft reset BBP.*/
-		/* In 2870 chipset, ATE_BBP_IO_READ8_BY_REG_ID() == RTMP_BBP_IO_READ8_BY_REG_ID() */
-		/* Both rt2870ap and rt2870sta use BbpSoftReset(pAd) to do BBP soft reset */
-		BbpSoftReset(pAd);
-/*================================================*/
-		{
-#ifdef CONFIG_STA_SUPPORT
-			// Set all state machines back IDLE
-			pAd->Mlme.CntlMachine.CurrState    = CNTL_IDLE;
-			pAd->Mlme.AssocMachine.CurrState   = ASSOC_IDLE;
-			pAd->Mlme.AuthMachine.CurrState    = AUTH_REQ_IDLE;
-			pAd->Mlme.AuthRspMachine.CurrState = AUTH_RSP_IDLE;
-			pAd->Mlme.SyncMachine.CurrState    = SYNC_IDLE;
-			pAd->Mlme.ActMachine.CurrState    = ACT_IDLE;
-#endif // CONFIG_STA_SUPPORT //
-
-			//
-			// ===> refer to MlmeRestartStateMachine().
-			// When we entered ATE_START mode, PeriodicTimer was not cancelled.
-			// So we don't have to set it here.
-			//
-			//RTMPSetTimer(pAd, &pAd->Mlme.PeriodicTimer, MLME_TASK_EXEC_INTV);
-
-			ASSERT(pAd->CommonCfg.Channel != 0);
-
-			AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-			AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-
-
-#ifdef CONFIG_STA_SUPPORT
-		    RTMPStationStart(pAd);
-#endif // CONFIG_STA_SUPPORT //
-		}
-//
-// These two steps have been done when entering ATE_STOP mode.
-//
-#if 0
-	    RTUSBWriteBBPRegister(pAd, BBP_R22, BbpData);
-	   	RTUSBWriteMACRegister(pAd, MAC_SYS_CTRL, MacData);
-#endif
-		// Clean ATE Bulk in/out counter and continue setup.
-		InterlockedExchange(&pAd->BulkOutRemained, 0);
-		NdisAcquireSpinLock(&pAd->GenericLock);
-		pAd->ContinBulkOut = FALSE;
-		pAd->ContinBulkIn = FALSE;
-		NdisReleaseSpinLock(&pAd->GenericLock);
-
-		/* Wait 50ms to prevent next URB to bulkout during HW reset. */
-		/* todo : remove this if not necessary */
-		NdisMSleep(50000);
-
-		pAd->ate.Mode = ATE_STOP;
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-/*=========================================================================*/
-		/* restore RX_FILTR_CFG */
-#ifdef CONFIG_STA_SUPPORT
-		/* restore RX_FILTR_CFG in order that QA maybe set it to 0x3 */
-		RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, STANORMAL);
-#endif // CONFIG_STA_SUPPORT //
-/*=========================================================================*/
-
-		// Enable Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		// Enable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Wait 10ms to wait all of the bulk-in URBs to complete.
-		/* todo : remove this if not necessary */
-		NdisMSleep(10000);
-
-		// Everything is ready to start normal Tx/Rx.
-		RTUSBBulkReceive(pAd);
-		netif_start_queue(pAd->net_dev);
-
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("<=== ATE : ATESTOP \n"));
-	}
-	else if (!strcmp(arg, "TXCARR"))	// Tx Carrier
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXCARR\n"));
-		pAd->ate.Mode |= ATE_TXCARR;
-
-		// Disable Rx
-		// May be we need not to do this, because these have been done in ATE_START mode ???
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// QA has done the following steps if it is used.
-		if (pAd->ate.bQATxStart == FALSE)
-		{
-			// Soft reset BBP.
-			BbpSoftReset(pAd);
-
-			// Carrier Test set BBP R22 bit7=1, bit6=1, bit[5~0]=0x01
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF00; //clear bit7, bit6, bit[5~0]
-			BbpData |= 0x000000C1; //set bit7=1, bit6=1, bit[5~0]=0x01
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-			// set MAC_SYS_CTRL(0x1004) Continuous Tx Production Test (bit4) = 1
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-			Value = Value | 0x00000010;
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-		}
-	}
-	else if (!strcmp(arg, "TXCONT"))	// Tx Continue
-	{
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			/* set MAC_SYS_CTRL(0x1004) bit4(Continuous Tx Production Test)
-			   and bit2(MAC TX enable) back to zero. */
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-			MacData &= 0xFFFFFFEB;
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-			// set BBP R22 bit7=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF7F; //set bit7=0
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		}
-
-		/* for TxCont mode.
-		** Step 1: Send 50 packets first then wait for a moment.
-		** Step 2: Send more 50 packet then start continue mode.
-		*/
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXCONT\n"));
-		// Step 1: send 50 packets first.
-		pAd->ate.Mode |= ATE_TXCONT;
-		pAd->ate.TxCount = 50;
-		pAd->ate.TxDoneCount = 0;
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-
-		/* Only needed if we have to send some normal frames. */
-		SetJapanFilter(pAd);
-
-		// Setup frame format.
-		ATESetUpFrame(pAd, 0);
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Start Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		InterlockedExchange(&pAd->BulkOutRemained, pAd->ate.TxCount);
-
-#ifdef	RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			pAd->ate.TxStatus = 1;
-			//pAd->ate.Repeat = 0;
-		}
-#endif	// RALINK_28xx_QA //
-
-		NdisAcquireSpinLock(&pAd->GenericLock);//0820
-		pAd->ContinBulkOut = FALSE;
-		NdisReleaseSpinLock(&pAd->GenericLock);
-
-		RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-
-		// Kick bulk out
-		RTUSBKickBulkOut(pAd);
-
-		/* To make sure all the 50 frames have been bulk out before executing step 2 */
-		while (atomic_read(&pAd->BulkOutRemained) > 0)
-		{
-			RTMPusecDelay(5000);
-		}
-
-		// Step 2: send more 50 packets then start continue mode.
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-		// Cont. TX set BBP R22 bit7=1
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-		BbpData |= 0x00000080; //set bit7=1
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-		pAd->ate.TxCount = 50;
-		pAd->ate.TxDoneCount = 0;
-
-		SetJapanFilter(pAd);
-
-		// Setup frame format.
-		ATESetUpFrame(pAd, 0);
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-
-		// Start Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		InterlockedExchange(&pAd->BulkOutRemained, pAd->ate.TxCount);
-
-#ifdef	RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			pAd->ate.TxStatus = 1;
-			//pAd->ate.Repeat = 0;
-		}
-#endif	// RALINK_28xx_QA //
-
-		NdisAcquireSpinLock(&pAd->GenericLock);//0820
-		pAd->ContinBulkOut = FALSE;
-		NdisReleaseSpinLock(&pAd->GenericLock);
-
-		RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-		// Kick bulk out
-		RTUSBKickBulkOut(pAd);
-
-#if 1
-		RTMPusecDelay(500);
-#else
-		while (atomic_read(&pAd->BulkOutRemained) > 0)
-		{
-			RTMPusecDelay(5000);
-		}
-#endif // 1 //
-
-		// Set MAC_SYS_CTRL(0x1004) Continuous Tx Production Test (bit4) = 1.
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-		MacData |= 0x00000010;
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-	}
-	else if (!strcmp(arg, "TXFRAME"))	// Tx Frames
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXFRAME(Count=0x%08x)\n", pAd->ate.TxCount));
-		pAd->ate.Mode |= ATE_TXFRAME;
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-		// Default value in BBP R22 is 0x0.
-		BbpData = 0;
-
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-
-		// Clean bit4 to stop continuous Tx production test.
-		MacData &= 0xFFFFFFEF;
-
-	   	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-#ifdef RALINK_28xx_QA
-		// add this for LoopBack mode
-		if (pAd->ate.bQARxStart == FALSE)
-		{
-			// Disable Rx
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-			Value &= ~(1 << 3);
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-		}
-
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			pAd->ate.TxStatus = 1;
-			//pAd->ate.Repeat = 0;
-		}
-#else
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-#endif // RALINK_28xx_QA //
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-        SetJapanFilter(pAd);
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-		pAd->ate.TxDoneCount = 0;
-
-        // Setup frame format
-		ATESetUpFrame(pAd, 0);
-
-		// Start Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		// Check count is continuous or not yet.
-		//
-		// Due to the type mismatch between "pAd->BulkOutRemained"(atomic_t) and "pAd->ate.TxCount"(UINT32)
-		//
-		if (pAd->ate.TxCount == 0)
-		{
-			InterlockedExchange(&pAd->BulkOutRemained, 0);
-		}
-		else
-		{
-			InterlockedExchange(&pAd->BulkOutRemained, pAd->ate.TxCount);
-		}
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("bulk out count = %d\n", atomic_read(&pAd->BulkOutRemained)));
-		ASSERT((atomic_read(&pAd->BulkOutRemained) >= 0));
-
-		if (atomic_read(&pAd->BulkOutRemained) == 0)
-		{
-			ATEDBGPRINT(RT_DEBUG_TRACE, ("Send packet countinuously\n"));
-
-			/* In 28xx, NdisAcquireSpinLock() == spin_lock_bh() */
-			/* NdisAcquireSpinLock only need one argument in 28xx. */
-			NdisAcquireSpinLock(&pAd->GenericLock);
-			pAd->ContinBulkOut = TRUE;
-			NdisReleaseSpinLock(&pAd->GenericLock);
-
-			/* In 28xx, BULK_OUT_LOCK() == spin_lock_irqsave() */
-			BULK_OUT_LOCK(&pAd->BulkOutLock[0], IrqFlags);// peter : NdisAcquireSpinLock ==> BULK_OUT_LOCK
-			pAd->BulkOutPending[0] = FALSE;
-			BULK_OUT_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);// peter : NdisAcquireSpinLock ==> BULK_OUT_LOCK
-		}
-		else
-		{
-			ATEDBGPRINT(RT_DEBUG_TRACE, ("Send packets depend on counter\n"));
-
-			NdisAcquireSpinLock(&pAd->GenericLock);
-			pAd->ContinBulkOut = FALSE;
-			NdisReleaseSpinLock(&pAd->GenericLock);
-
-			BULK_OUT_LOCK(&pAd->BulkOutLock[0], IrqFlags);
-			pAd->BulkOutPending[0] = FALSE;
-			BULK_OUT_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);
-		}
-
-		RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-
-		// Kick bulk out
-		RTUSBKickBulkOut(pAd);
-	}
-#ifdef RALINK_28xx_QA
-	else if (!strcmp(arg, "TXSTOP")) 		//Enter ATE mode and set Tx/Rx Idle
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXSTOP\n"));
-
-		atemode = pAd->ate.Mode;
-		pAd->ate.Mode &= ATE_TXSTOP;
-		pAd->ate.bQATxStart = FALSE;
-//		pAd->ate.TxDoneCount = pAd->ate.TxCount;
-
-/*=========================================================================*/
-		if (atemode & ATE_TXCARR)
-		{
-			// No Carrier Test set BBP R22 bit7=0, bit6=0, bit[5~0]=0x0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF00; //clear bit7, bit6, bit[5~0]
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		}
-		else if (atemode & ATE_TXCARRSUPP)
-		{
-			// No Cont. TX set BBP R22 bit7=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= ~(1 << 7); //set bit7=0
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-			// No Carrier Suppression set BBP R24 bit0=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R24, &BbpData);
-			BbpData &= 0xFFFFFFFE; //clear bit0
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, BbpData);
-		}
-		else if ((atemode & ATE_TXFRAME) || (atemode == ATE_STOP))
-		{
-			if (atemode & ATE_TXCONT)
-			{
-				// No Cont. TX set BBP R22 bit7=0
-				ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-				BbpData &= ~(1 << 7); //set bit7=0
-				ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-			}
-		}
-
-/*=========================================================================*/
-		RTUSBRejectPendingPackets(pAd);
-		RTUSBCleanUpDataBulkOutQueue(pAd);
-
-		/* not used in RT28xx */
-		//RTUSBCleanUpMLMEWaitQueue(pAd);
-		/* empty function so far */
-		RTUSBCleanUpMLMEBulkOutQueue(pAd);
-/*=========================================================================*/
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-/*=========================================================================*/
-
-		/* In 28xx, pAd->PendingRx is not of type atomic_t anymore */
-//		while ((atomic_read(&pAd->PendingRx) > 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		/* peter todo : BulkInLock */
-		while (pAd->PendingRx > 0)
-		{
-#if 1
-			ATE_RTUSBCancelPendingBulkInIRP(pAd);
-#else
-//			NdisInterlockedDecrement(&pAd->PendingRx);
-			pAd->PendingRx--;
-#endif
-			RTMPusecDelay(500000);
-		}
-
-		while (((pAd->BulkOutPending[0] == TRUE) ||
-				(pAd->BulkOutPending[1] == TRUE) ||
-				(pAd->BulkOutPending[2] == TRUE) ||
-				(pAd->BulkOutPending[3] == TRUE)) && (pAd->BulkFlags != 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		{
-			do
-			{
-				RTUSBCancelPendingBulkOutIRP(pAd);
-			} while (FALSE);
-
-			RTMPusecDelay(500000);
-		}
-
-		ASSERT(pAd->PendingRx == 0);
-/*=========================================================================*/
-		// Enable Tx, Rx DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		/* task Tx status : 0 --> task is idle, 1 --> task is running */
-		pAd->ate.TxStatus = 0;
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-		// Disable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-		MacData &= (0xfffffffb);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-		//Clean ATE Bulk in/out counter and continue setup
-		InterlockedExchange(&pAd->BulkOutRemained, 0);
-
-		pAd->ContinBulkOut = FALSE;
-	}
-	else if (!strcmp(arg, "RXSTOP"))
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: RXSTOP\n"));
-		atemode = pAd->ate.Mode;
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		pAd->ate.Mode &= ATE_RXSTOP;
-		pAd->ate.bQARxStart = FALSE;
-//		pAd->ate.TxDoneCount = pAd->ate.TxCount;
-
-/*=========================================================================*/
-		RTUSBRejectPendingPackets(pAd);
-		RTUSBCleanUpDataBulkOutQueue(pAd);
-
-		/* not used in RT28xx */
-		//RTUSBCleanUpMLMEWaitQueue(pAd);
-		RTUSBCleanUpMLMEBulkOutQueue(pAd);
-/*=========================================================================*/
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-/*=========================================================================*/
-//		while ((atomic_read(&pAd->PendingRx) > 0))
-		while (pAd->PendingRx > 0)
-		{
-#if 1
-			ATE_RTUSBCancelPendingBulkInIRP(pAd);
-#else
-//			NdisInterlockedDecrement(&pAd->PendingRx);
-			pAd->PendingRx--;
-#endif
-			RTMPusecDelay(500000);
-		}
-
-		while (((pAd->BulkOutPending[0] == TRUE) ||
-				(pAd->BulkOutPending[1] == TRUE) ||
-				(pAd->BulkOutPending[2] == TRUE) ||
-				(pAd->BulkOutPending[3] == TRUE)) && (pAd->BulkFlags != 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		{
-			do
-			{
-				RTUSBCancelPendingBulkOutIRP(pAd);
-			} while (FALSE);
-
-			RTMPusecDelay(500000);
-		}
-
-		ASSERT(pAd->PendingRx == 0);
-/*=========================================================================*/
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-		pAd->ContinBulkIn = FALSE;
-	}
-#endif // RALINK_28xx_QA //
-	else if (!strcmp(arg, "RXFRAME")) // Rx Frames
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: RXFRAME\n"));
-
-		// Disable Rx of MAC block
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Default value in BBP R22 is 0x0.
-		BbpData = 0;
-
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-		// Clean bit4 to stop continuous Tx production test.
-		MacData &= 0xFFFFFFEF;
-
-	   	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-		pAd->ate.Mode |= ATE_RXFRAME;
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-		// Disable TX of MAC block
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-        // Reset Rx RING.
-		for ( i = 0; i < (RX_RING_SIZE); i++)
-		{
-			PRX_CONTEXT  pRxContext = &(pAd->RxContext[i]);
-
-			pRxContext->InUse = FALSE;
-			pRxContext->IRPPending = FALSE;
-			pRxContext->Readable = FALSE;
-
-			//
-			// Get the urb from kernel back to driver.
-			//
-			RTUSB_UNLINK_URB(pRxContext->pUrb);
-
-			/* Sleep 200 microsecs to give cancellation time to work. */
-			NdisMSleep(200);
-			pAd->BulkInReq = 0;
-
-//			InterlockedExchange(&pAd->PendingRx, 0);
-			pAd->PendingRx = 0;
-			pAd->NextRxBulkInReadIndex = 0;	// Next Rx Read index
-			pAd->NextRxBulkInIndex		= RX_RING_SIZE - 1;	// Rx Bulk pointer
-			pAd->NextRxBulkInPosition = 0;
-		}
-
-		// read to clear counters
-		RTUSBReadMACRegister(pAd, RX_STA_CNT0, &temp); //RX PHY & RX CRC count
-		RTUSBReadMACRegister(pAd, RX_STA_CNT1, &temp); //RX PLCP error count & CCA false alarm count
-		RTUSBReadMACRegister(pAd, RX_STA_CNT2, &temp); //RX FIFO overflow frame count & RX duplicated filtered frame count
-
-		pAd->ContinBulkIn = TRUE;
-
-		// Enable Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		// Enable RX of MAC block
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Kick bulk in
-		RTUSBBulkReceive(pAd);
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: Invalid arg!\n"));
-		return FALSE;
-	}
-	RTMPusecDelay(5000);
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("<=== ATECmdHandler()\n"));
-
-	return TRUE;
-}
-#endif // RT2870 //
-
-INT	Set_ATE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	if (ATECmdHandler(pAd, arg))
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_Proc Success\n"));
-
-
-		return TRUE;
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_Proc Failed\n"));
-		return FALSE;
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE ADDR1=DA for TxFrame(AP  : To DS = 0 ; From DS = 1)
-        or
-        Set ATE ADDR3=DA for TxFrame(STA : To DS = 1 ; From DS = 0)
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_DA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR				*value;
-	INT					i;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-    for (i=0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-		AtoH(value, &pAd->ate.Addr3[i++], 1);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	if(i != 6)
-		return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_DA_Proc (DA = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAd->ate.Addr3[0],
-		pAd->ate.Addr3[1], pAd->ate.Addr3[2], pAd->ate.Addr3[3], pAd->ate.Addr3[4], pAd->ate.Addr3[5]));
-#endif // CONFIG_STA_SUPPORT //
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_DA_Proc Success\n"));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE ADDR3=SA for TxFrame(AP  : To DS = 0 ; From DS = 1)
-        or
-        Set ATE ADDR2=SA for TxFrame(STA : To DS = 1 ; From DS = 0)
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_SA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR				*value;
-	INT					i;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-    for (i=0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-		AtoH(value, &pAd->ate.Addr2[i++], 1);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	if(i != 6)
-		return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_SA_Proc (SA = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAd->ate.Addr2[0],
-		pAd->ate.Addr2[1], pAd->ate.Addr2[2], pAd->ate.Addr2[3], pAd->ate.Addr2[4], pAd->ate.Addr2[5]));
-#endif // CONFIG_STA_SUPPORT //
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_SA_Proc Success\n"));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE ADDR2=BSSID for TxFrame(AP  : To DS = 0 ; From DS = 1)
-        or
-        Set ATE ADDR1=BSSID for TxFrame(STA : To DS = 1 ; From DS = 0)
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_BSSID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR				*value;
-	INT					i;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-    for (i=0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-		AtoH(value, &pAd->ate.Addr1[i++], 1);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	if(i != 6)
-		return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_BSSID_Proc (BSSID = %2X:%2X:%2X:%2X:%2X:%2X)\n",	pAd->ate.Addr1[0],
-		pAd->ate.Addr1[1], pAd->ate.Addr1[2], pAd->ate.Addr1[3], pAd->ate.Addr1[4], pAd->ate.Addr1[5]));
-#endif // CONFIG_STA_SUPPORT //
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_BSSID_Proc Success\n"));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Channel
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_CHANNEL_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR channel;
-
-	channel = simple_strtol(arg, 0, 10);
-
-	if ((channel < 1) || (channel > 216))// to allow A band channel : ((channel < 1) || (channel > 14))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_CHANNEL_Proc::Out of range, it should be in range of 1~14.\n"));
-		return FALSE;
-	}
-	pAd->ate.Channel = channel;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_CHANNEL_Proc (ATE Channel = %d)\n", pAd->ate.Channel));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_CHANNEL_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Power0
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_POWER0_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR TxPower;
-
-	TxPower = simple_strtol(arg, 0, 10);
-
-	if (pAd->ate.Channel <= 14)
-	{
-		if ((TxPower > 31) || (TxPower < 0))
-		{
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER0_Proc::Out of range (Value=%d)\n", TxPower));
-			return FALSE;
-		}
-	}
-	else// 5.5GHz
-	{
-		if ((TxPower > 15) || (TxPower < -7))
-		{
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER0_Proc::Out of range (Value=%d)\n", TxPower));
-			return FALSE;
-		}
-	}
-
-	pAd->ate.TxPower0 = TxPower;
-	ATETxPwrHandler(pAd, 0);
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_POWER0_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Power1
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_POWER1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR TxPower;
-
-	TxPower = simple_strtol(arg, 0, 10);
-
-	if (pAd->ate.Channel <= 14)
-	{
-	if ((TxPower > 31) || (TxPower < 0))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER1_Proc::Out of range (Value=%d)\n", TxPower));
-		return FALSE;
-	}
-	}
-	else
-	{
-		if ((TxPower > 15) || (TxPower < -7))
-		{
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER1_Proc::Out of range (Value=%d)\n", TxPower));
-			return FALSE;
-		}
-	}
-
-	pAd->ate.TxPower1 = TxPower;
-	ATETxPwrHandler(pAd, 1);
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_POWER1_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Antenna
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR value;
-
-	value = simple_strtol(arg, 0, 10);
-
-	if ((value > 2) || (value < 0))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_Antenna_Proc::Out of range (Value=%d)\n", value));
-		return FALSE;
-	}
-
-	pAd->ate.TxAntennaSel = value;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_Antenna_Proc (Antenna = %d)\n", pAd->ate.TxAntennaSel));
-	ATEDBGPRINT(RT_DEBUG_TRACE,("Ralink: Set_ATE_TX_Antenna_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Rx Antenna
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_RX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR value;
-
-	value = simple_strtol(arg, 0, 10);
-
-	if ((value > 3) || (value < 0))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_RX_Antenna_Proc::Out of range (Value=%d)\n", value));
-		return FALSE;
-	}
-
-	pAd->ate.RxAntennaSel = value;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_RX_Antenna_Proc (Antenna = %d)\n", pAd->ate.RxAntennaSel));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_RX_Antenna_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE RF frequence offset
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_FREQOFFSET_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR RFFreqOffset;
-	ULONG R4;
-
-	RFFreqOffset = simple_strtol(arg, 0, 10);
-
-	if(RFFreqOffset >= 64)
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_FREQOFFSET_Proc::Out of range, it should be in range of 0~63.\n"));
-		return FALSE;
-	}
-
-	pAd->ate.RFFreqOffset = RFFreqOffset;
-	R4 = pAd->ate.RFFreqOffset << 15;		// shift TX power control to correct RF register bit position
-	R4 |= (pAd->LatchRfRegs.R4 & ((~0x001f8000)));
-	pAd->LatchRfRegs.R4 = R4;
-
-	RtmpRfIoWrite(pAd);
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_FREQOFFSET_Proc (RFFreqOffset = %d)\n", pAd->ate.RFFreqOffset));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_FREQOFFSET_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE RF BW
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_BW_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	int i;
-	UCHAR value = 0;
-	UCHAR BBPCurrentBW;
-
-	BBPCurrentBW = simple_strtol(arg, 0, 10);
-
-	if(BBPCurrentBW == 0)
-		pAd->ate.TxWI.BW = BW_20;
-	else
-		pAd->ate.TxWI.BW = BW_40;
-
-	if(pAd->ate.TxWI.BW == BW_20)
-	{
-		if(pAd->ate.Channel <= 14)
-		{
- 		for (i=0; i<5; i++)
- 		{
-				if (pAd->Tx20MPwrCfgGBand[i] != 0xffffffff)
-				{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx20MPwrCfgGBand[i]);
-					RTMPusecDelay(5000);
-				}
-			}
-		}
-		else
-		{
-			for (i=0; i<5; i++)
-			{
-				if (pAd->Tx20MPwrCfgABand[i] != 0xffffffff)
- 			{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx20MPwrCfgABand[i]);
- 				RTMPusecDelay(5000);
- 			}
- 		}
-		}
-
-		//Set BBP R4 bit[4:3]=0:0
- 		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
- 		value &= (~0x18);
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
-
-  		//Set BBP R66=0x3C
- 		value = 0x3C;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, value);
-		//Set BBP R68=0x0B
-		//to improve Rx sensitivity.
-		value = 0x0B;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R68, value);
-		//Set BBP R69=0x16
-		value = 0x16;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, value);
-		//Set BBP R70=0x08
-		value = 0x08;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, value);
-		//Set BBP R73=0x11
-		value = 0x11;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, value);
-
-	    // If Channel=14, Bandwidth=20M and Mode=CCK, Set BBP R4 bit5=1
-	    // (Japan filter coefficients)
-	    // This segment of code will only works when ATETXMODE and ATECHANNEL
-	    // were set to MODE_CCK and 14 respectively before ATETXBW is set to 0.
-	    //=====================================================================
-		if (pAd->ate.Channel == 14)
-		{
-			int TxMode = pAd->ate.TxWI.PHYMODE;
-			if (TxMode == MODE_CCK)
-			{
-				// when Channel==14 && Mode==CCK && BandWidth==20M, BBP R4 bit5=1
- 				ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
-				value |= 0x20; //set bit5=1
- 				ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
-			}
-		}
-
-	    //=====================================================================
-		// If bandwidth != 40M, RF Reg4 bit 21 = 0.
-		pAd->LatchRfRegs.R4 &= ~0x00200000;
-		RtmpRfIoWrite(pAd);
-	}
-	else if(pAd->ate.TxWI.BW == BW_40)
-	{
-		if(pAd->ate.Channel <= 14)
-		{
-			for (i=0; i<5; i++)
-			{
-				if (pAd->Tx40MPwrCfgGBand[i] != 0xffffffff)
-				{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx40MPwrCfgGBand[i]);
-					RTMPusecDelay(5000);
-				}
-			}
-		}
-		else
-		{
-			for (i=0; i<5; i++)
-			{
-				if (pAd->Tx40MPwrCfgABand[i] != 0xffffffff)
-				{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx40MPwrCfgABand[i]);
-					RTMPusecDelay(5000);
-				}
-			}
-#ifdef DOT11_N_SUPPORT
-			if ((pAd->ate.TxWI.PHYMODE >= MODE_HTMIX) && (pAd->ate.TxWI.MCS == 7))
-			{
-    			value = 0x28;
-    			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R67, value);
-			}
-#endif // DOT11_N_SUPPORT //
-		}
-
-		//Set BBP R4 bit[4:3]=1:0
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
-		value &= (~0x18);
-		value |= 0x10;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
-
-		//Set BBP R66=0x3C
-		value = 0x3C;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, value);
-		//Set BBP R68=0x0C
-		//to improve Rx sensitivity.
-		value = 0x0C;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R68, value);
-		//Set BBP R69=0x1A
-		value = 0x1A;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, value);
-		//Set BBP R70=0x0A
-		value = 0x0A;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, value);
-		//Set BBP R73=0x16
-		value = 0x16;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, value);
-
-		// If bandwidth = 40M, set RF Reg4 bit 21 = 1.
-		pAd->LatchRfRegs.R4 |= 0x00200000;
-		RtmpRfIoWrite(pAd);
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_BW_Proc (BBPCurrentBW = %d)\n", pAd->ate.TxWI.BW));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_BW_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame length
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_LENGTH_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxLength = simple_strtol(arg, 0, 10);
-
-	if((pAd->ate.TxLength < 24) || (pAd->ate.TxLength > (MAX_FRAME_SIZE - 34/* == 2312 */)))
-	{
-		pAd->ate.TxLength = (MAX_FRAME_SIZE - 34/* == 2312 */);
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_LENGTH_Proc::Out of range, it should be in range of 24~%d.\n", (MAX_FRAME_SIZE - 34/* == 2312 */)));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_LENGTH_Proc (TxLength = %d)\n", pAd->ate.TxLength));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_LENGTH_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame count
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_COUNT_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxCount = simple_strtol(arg, 0, 10);
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_COUNT_Proc (TxCount = %d)\n", pAd->ate.TxCount));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_COUNT_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame MCS
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_MCS_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR MCS;
-	int result;
-
-	MCS = simple_strtol(arg, 0, 10);
-	result = CheckMCSValid(pAd->ate.TxWI.PHYMODE, MCS);
-
-	if (result != -1)
-	{
-		pAd->ate.TxWI.MCS = (UCHAR)MCS;
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_MCS_Proc::Out of range, refer to rate table.\n"));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_MCS_Proc (MCS = %d)\n", pAd->ate.TxWI.MCS));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_MCS_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame Mode
-        0: MODE_CCK
-        1: MODE_OFDM
-        2: MODE_HTMIX
-        3: MODE_HTGREENFIELD
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_MODE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxWI.PHYMODE = simple_strtol(arg, 0, 10);
-
-	if(pAd->ate.TxWI.PHYMODE > 3)
-	{
-		pAd->ate.TxWI.PHYMODE = 0;
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_MODE_Proc::Out of range. it should be in range of 0~3\n"));
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("0: CCK, 1: OFDM, 2: HT_MIX, 3: HT_GREEN_FIELD.\n"));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_MODE_Proc (TxMode = %d)\n", pAd->ate.TxWI.PHYMODE));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_MODE_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame GI
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_GI_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxWI.ShortGI = simple_strtol(arg, 0, 10);
-
-	if(pAd->ate.TxWI.ShortGI > 1)
-	{
-		pAd->ate.TxWI.ShortGI = 0;
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_GI_Proc::Out of range\n"));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_GI_Proc (GI = %d)\n", pAd->ate.TxWI.ShortGI));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_GI_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-    ==========================================================================
- */
-INT	Set_ATE_RX_FER_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.bRxFer = simple_strtol(arg, 0, 10);
-
-	if (pAd->ate.bRxFer == 1)
-	{
-		pAd->ate.RxCntPerSec = 0;
-		pAd->ate.RxTotalCnt = 0;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_RX_FER_Proc (bRxFer = %d)\n", pAd->ate.bRxFer));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_RX_FER_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-INT Set_ATE_Read_RF_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ate_print(KERN_EMERG "R1 = %lx\n", pAd->LatchRfRegs.R1);
-	ate_print(KERN_EMERG "R2 = %lx\n", pAd->LatchRfRegs.R2);
-	ate_print(KERN_EMERG "R3 = %lx\n", pAd->LatchRfRegs.R3);
-	ate_print(KERN_EMERG "R4 = %lx\n", pAd->LatchRfRegs.R4);
-
-	return TRUE;
-}
-
-INT Set_ATE_Write_RF1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT32 value = simple_strtol(arg, 0, 16);
-
-	pAd->LatchRfRegs.R1 = value;
-	RtmpRfIoWrite(pAd);
-
-	return TRUE;
-}
-
-INT Set_ATE_Write_RF2_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT32 value = simple_strtol(arg, 0, 16);
-
-	pAd->LatchRfRegs.R2 = value;
-	RtmpRfIoWrite(pAd);
-
-	return TRUE;
-}
-
-INT Set_ATE_Write_RF3_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT32 value = simple_strtol(arg, 0, 16);
-
-	pAd->LatchRfRegs.R3 = value;
-	RtmpRfIoWrite(pAd);
-
-	return TRUE;
-}
-
-INT Set_ATE_Write_RF4_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT32 value = simple_strtol(arg, 0, 16);
-
-	pAd->LatchRfRegs.R4 = value;
-	RtmpRfIoWrite(pAd);
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Load and Write EEPROM from a binary file prepared in advance.
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-#ifndef UCOS
-INT Set_ATE_Load_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	BOOLEAN		    ret = FALSE;
-	PUCHAR			src = EEPROM_BIN_FILE_NAME;
-	struct file		*srcf;
-	INT32 			retval, orgfsuid, orgfsgid;
-   	mm_segment_t	orgfs;
-	USHORT 			WriteEEPROM[(EEPROM_SIZE/2)];
-	UINT32			FileLength = 0;
-	UINT32 			value = simple_strtol(arg, 0, 10);
-
-	ATEDBGPRINT(RT_DEBUG_ERROR, ("===> %s (value=%d)\n\n", __func__, value));
-
-	if (value > 0)
-	{
-		/* zero the e2p buffer */
-		NdisZeroMemory((PUCHAR)WriteEEPROM, EEPROM_SIZE);
-
-		/* save uid and gid used for filesystem access.
-	    ** set user and group to 0 (root)
-	    */
-		orgfsuid = current->fsuid;
-		orgfsgid = current->fsgid;
-		/* as root */
-		current->fsuid = current->fsgid = 0;
-    	orgfs = get_fs();
-    	set_fs(KERNEL_DS);
-
-		do
-		{
-			/* open the bin file */
-			srcf = filp_open(src, O_RDONLY, 0);
-
-			if (IS_ERR(srcf))
-			{
-				ate_print("%s - Error %ld opening %s\n", __func__, -PTR_ERR(srcf), src);
-				break;
-			}
-
-			/* the object must have a read method */
-			if ((srcf->f_op == NULL) || (srcf->f_op->read == NULL))
-			{
-				ate_print("%s - %s does not have a read method\n", __func__, src);
-				break;
-			}
-
-			/* read the firmware from the file *.bin */
-			FileLength = srcf->f_op->read(srcf,
-										  (PUCHAR)WriteEEPROM,
-										  EEPROM_SIZE,
-										  &srcf->f_pos);
-
-			if (FileLength != EEPROM_SIZE)
-			{
-				ate_print("%s: error file length (=%d) in e2p.bin\n",
-					   __func__, FileLength);
-				break;
-			}
-			else
-			{
-				/* write the content of .bin file to EEPROM */
-				rt_ee_write_all(pAd, WriteEEPROM);
-				ret = TRUE;
-			}
-			break;
-		} while(TRUE);
-
-		/* close firmware file */
-		if (IS_ERR(srcf))
-		{
-				;
-		}
-		else
-		{
-			retval = filp_close(srcf, NULL);
-			if (retval)
-			{
-				ATEDBGPRINT(RT_DEBUG_ERROR, ("--> Error %d closing %s\n", -retval, src));
-
-			}
-		}
-
-		/* restore */
-		set_fs(orgfs);
-		current->fsuid = orgfsuid;
-		current->fsgid = orgfsgid;
-	}
-    ATEDBGPRINT(RT_DEBUG_ERROR, ("<=== %s (ret=%d)\n", __func__, ret));
-
-    return ret;
-
-}
-#else
-INT Set_ATE_Load_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	USHORT 			WriteEEPROM[(EEPROM_SIZE/2)];
-	struct iwreq	*wrq = (struct iwreq *)arg;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("===> %s (wrq->u.data.length = %d)\n\n", __func__, wrq->u.data.length));
-
-	if (wrq->u.data.length != EEPROM_SIZE)
-	{
-		ate_print("%s: error length (=%d) from host\n",
-			   __func__, wrq->u.data.length);
-		return FALSE;
-	}
-	else/* (wrq->u.data.length == EEPROM_SIZE) */
-	{
-		/* zero the e2p buffer */
-		NdisZeroMemory((PUCHAR)WriteEEPROM, EEPROM_SIZE);
-
-		/* fill the local buffer */
-		NdisMoveMemory((PUCHAR)WriteEEPROM, wrq->u.data.pointer, wrq->u.data.length);
-
-		do
-		{
-				/* write the content of .bin file to EEPROM */
-				rt_ee_write_all(pAd, WriteEEPROM);
-
-		} while(FALSE);
-		}
-
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("<=== %s\n", __func__));
-
-    return TRUE;
-
-}
-#endif // !UCOS //
-
-INT Set_ATE_Read_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	USHORT buffer[EEPROM_SIZE/2];
-	USHORT *p;
-	int i;
-
-	rt_ee_read_all(pAd, (USHORT *)buffer);
-	p = buffer;
-	for (i = 0; i < (EEPROM_SIZE/2); i++)
-	{
-		ate_print("%4.4x ", *p);
-		if (((i+1) % 16) == 0)
-			ate_print("\n");
-		p++;
-	}
-	return TRUE;
-}
-
-INT	Set_ATE_Show_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ate_print("Mode=%d\n", pAd->ate.Mode);
-	ate_print("TxPower0=%d\n", pAd->ate.TxPower0);
-	ate_print("TxPower1=%d\n", pAd->ate.TxPower1);
-	ate_print("TxAntennaSel=%d\n", pAd->ate.TxAntennaSel);
-	ate_print("RxAntennaSel=%d\n", pAd->ate.RxAntennaSel);
-	ate_print("BBPCurrentBW=%d\n", pAd->ate.TxWI.BW);
-	ate_print("GI=%d\n", pAd->ate.TxWI.ShortGI);
-	ate_print("MCS=%d\n", pAd->ate.TxWI.MCS);
-	ate_print("TxMode=%d\n", pAd->ate.TxWI.PHYMODE);
-	ate_print("Addr1=%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pAd->ate.Addr1[0], pAd->ate.Addr1[1], pAd->ate.Addr1[2], pAd->ate.Addr1[3], pAd->ate.Addr1[4], pAd->ate.Addr1[5]);
-	ate_print("Addr2=%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pAd->ate.Addr2[0], pAd->ate.Addr2[1], pAd->ate.Addr2[2], pAd->ate.Addr2[3], pAd->ate.Addr2[4], pAd->ate.Addr2[5]);
-	ate_print("Addr3=%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pAd->ate.Addr3[0], pAd->ate.Addr3[1], pAd->ate.Addr3[2], pAd->ate.Addr3[3], pAd->ate.Addr3[4], pAd->ate.Addr3[5]);
-	ate_print("Channel=%d\n", pAd->ate.Channel);
-	ate_print("TxLength=%d\n", pAd->ate.TxLength);
-	ate_print("TxCount=%u\n", pAd->ate.TxCount);
-	ate_print("RFFreqOffset=%d\n", pAd->ate.RFFreqOffset);
-	ate_print(KERN_EMERG "Set_ATE_Show_Proc Success\n");
-	return TRUE;
-}
-
-INT	Set_ATE_Help_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ate_print("ATE=ATESTART, ATESTOP, TXCONT, TXCARR, TXFRAME, RXFRAME\n");
-	ate_print("ATEDA\n");
-	ate_print("ATESA\n");
-	ate_print("ATEBSSID\n");
-	ate_print("ATECHANNEL, range:0~14(unless A band !)\n");
-	ate_print("ATETXPOW0, set power level of antenna 1.\n");
-	ate_print("ATETXPOW1, set power level of antenna 2.\n");
-	ate_print("ATETXANT, set TX antenna. 0:all, 1:antenna one, 2:antenna two.\n");
-	ate_print("ATERXANT, set RX antenna.0:all, 1:antenna one, 2:antenna two, 3:antenna three.\n");
-	ate_print("ATETXFREQOFFSET, set frequency offset, range 0~63\n");
-	ate_print("ATETXBW, set BandWidth, 0:20MHz, 1:40MHz.\n");
-	ate_print("ATETXLEN, set Frame length, range 24~%d\n", (MAX_FRAME_SIZE - 34/* == 2312 */));
-	ate_print("ATETXCNT, set how many frame going to transmit.\n");
-	ate_print("ATETXMCS, set MCS, reference to rate table.\n");
-	ate_print("ATETXMODE, set Mode 0:CCK, 1:OFDM, 2:HT-Mix, 3:GreenField, reference to rate table.\n");
-	ate_print("ATETXGI, set GI interval, 0:Long, 1:Short\n");
-	ate_print("ATERXFER, 0:disable Rx Frame error rate. 1:enable Rx Frame error rate.\n");
-	ate_print("ATERRF, show all RF registers.\n");
-	ate_print("ATEWRF1, set RF1 register.\n");
-	ate_print("ATEWRF2, set RF2 register.\n");
-	ate_print("ATEWRF3, set RF3 register.\n");
-	ate_print("ATEWRF4, set RF4 register.\n");
-	ate_print("ATELDE2P, load EEPROM from .bin file.\n");
-	ate_print("ATERE2P, display all EEPROM content.\n");
-	ate_print("ATESHOW, display all parameters of ATE.\n");
-	ate_print("ATEHELP, online help.\n");
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	AsicSwitchChannel() dedicated for ATE.
-
-    ==========================================================================
-*/
-VOID ATEAsicSwitchChannel(
-    IN PRTMP_ADAPTER pAd)
-{
-	UINT32 R2 = 0, R3 = DEFAULT_RF_TX_POWER, R4 = 0, Value = 0;
-	CHAR TxPwer = 0, TxPwer2 = 0;
-	UCHAR index, BbpValue = 0, R66 = 0x30;
-	RTMP_RF_REGS *RFRegTable;
-	UCHAR Channel;
-
-#ifdef RALINK_28xx_QA
-	if ((pAd->ate.bQATxStart == TRUE) || (pAd->ate.bQARxStart == TRUE))
-	{
-		if (pAd->ate.Channel != pAd->LatchRfRegs.Channel)
-		{
-			pAd->ate.Channel = pAd->LatchRfRegs.Channel;
-		}
-		return;
-	}
-	else
-#endif // RALINK_28xx_QA //
-	Channel = pAd->ate.Channel;
-
-	// Select antenna
-	AsicAntennaSelect(pAd, Channel);
-
-	// fill Tx power value
-	TxPwer = pAd->ate.TxPower0;
-	TxPwer2 = pAd->ate.TxPower1;
-
-	RFRegTable = RF2850RegTable;
-
-	switch (pAd->RfIcType)
-	{
-		/* But only 2850 and 2750 support 5.5GHz band... */
-		case RFIC_2820:
-		case RFIC_2850:
-		case RFIC_2720:
-		case RFIC_2750:
-
-			for (index = 0; index < NUM_OF_2850_CHNL; index++)
-			{
-				if (Channel == RFRegTable[index].Channel)
-				{
-					R2 = RFRegTable[index].R2;
-					if (pAd->Antenna.field.TxPath == 1)
-					{
-						R2 |= 0x4000;	// If TXpath is 1, bit 14 = 1;
-					}
-
-					if (pAd->Antenna.field.RxPath == 2)
-					{
-						switch (pAd->ate.RxAntennaSel)
-						{
-							case 1:
-								R2 |= 0x20040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x00;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							case 2:
-								R2 |= 0x10040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x01;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							default:
-								R2 |= 0x40;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								/* Only enable two Antenna to receive. */
-								BbpValue |= 0x08;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-						}
-					}
-					else if (pAd->Antenna.field.RxPath == 1)
-					{
-						R2 |= 0x20040;	// write 1 to off RxPath
-					}
-
-					if (pAd->Antenna.field.TxPath == 2)
-					{
-						if (pAd->ate.TxAntennaSel == 1)
-						{
-							R2 |= 0x4000;	// If TX Antenna select is 1 , bit 14 = 1; Disable Ant 2
-							ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
-							BbpValue &= 0xE7;		//11100111B
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
-						}
-						else if (pAd->ate.TxAntennaSel == 2)
-						{
-							R2 |= 0x8000;	// If TX Antenna select is 2 , bit 15 = 1; Disable Ant 1
-							ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
-							BbpValue &= 0xE7;
-							BbpValue |= 0x08;
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
-						}
-						else
-						{
-							ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
-							BbpValue &= 0xE7;
-							BbpValue |= 0x10;
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
-						}
-					}
-					if (pAd->Antenna.field.RxPath == 3)
-					{
-						switch (pAd->ate.RxAntennaSel)
-						{
-							case 1:
-								R2 |= 0x20040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x00;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							case 2:
-								R2 |= 0x10040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x01;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							case 3:
-								R2 |= 0x30000;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x02;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							default:
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x10;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-						}
-					}
-
-					if (Channel > 14)
-					{
-						// initialize R3, R4
-						R3 = (RFRegTable[index].R3 & 0xffffc1ff);
-						R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->ate.RFFreqOffset << 15);
-
-                        // According the Rory's suggestion to solve the middle range issue.
-						// 5.5G band power range: 0xF9~0X0F, TX0 Reg3 bit9/TX1 Reg4 bit6="0" means the TX power reduce 7dB
-						// R3
-						if ((TxPwer >= -7) && (TxPwer < 0))
-						{
-							TxPwer = (7+TxPwer);
-							TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
-							R3 |= (TxPwer << 10);
-							ATEDBGPRINT(RT_DEBUG_TRACE, ("ATEAsicSwitchChannel: TxPwer=%d \n", TxPwer));
-						}
-						else
-						{
-							TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
-							R3 |= (TxPwer << 10) | (1 << 9);
-						}
-
-						// R4
-						if ((TxPwer2 >= -7) && (TxPwer2 < 0))
-						{
-							TxPwer2 = (7+TxPwer2);
-							TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
-							R4 |= (TxPwer2 << 7);
-							ATEDBGPRINT(RT_DEBUG_TRACE, ("ATEAsicSwitchChannel: TxPwer2=%d \n", TxPwer2));
-						}
-						else
-						{
-							TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
-							R4 |= (TxPwer2 << 7) | (1 << 6);
-						}
-					}
-					else
-					{
-						R3 = (RFRegTable[index].R3 & 0xffffc1ff) | (TxPwer << 9); // set TX power0
-						R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->ate.RFFreqOffset << 15) | (TxPwer2 <<6);// Set freq offset & TxPwr1
-					}
-
-					// Based on BBP current mode before changing RF channel.
-					if (pAd->ate.TxWI.BW == BW_40)
-					{
-						R4 |=0x200000;
-					}
-
-					// Update variables
-					pAd->LatchRfRegs.Channel = Channel;
-					pAd->LatchRfRegs.R1 = RFRegTable[index].R1;
-					pAd->LatchRfRegs.R2 = R2;
-					pAd->LatchRfRegs.R3 = R3;
-					pAd->LatchRfRegs.R4 = R4;
-
-					RtmpRfIoWrite(pAd);
-
-					break;
-				}
-			}
-			break;
-
-		default:
-			break;
-	}
-
-	// Change BBP setting during switch from a->g, g->a
-	if (Channel <= 14)
-	{
-	    ULONG	TxPinCfg = 0x00050F0A;// 2007.10.09 by Brian : 0x0005050A ==> 0x00050F0A
-
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
-
-		/* For 1T/2R chip only... */
-	    if (pAd->NicConfig2.field.ExternalLNAForG)
-	    {
-	        ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x62);
-	    }
-	    else
-	    {
-	        ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x84);
-	    }
-
-        // According the Rory's suggestion to solve the middle range issue.
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R86, &BbpValue);
-		ASSERT((BbpValue == 0x00));
-		if ((BbpValue != 0x00))
-		{
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0x00);
-		}
-
-		// 5.5GHz band selection PIN, bit1 and bit2 are complement
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		Value &= (~0x6);
-		Value |= (0x04);
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-
-        // Turn off unused PA or LNA when only 1T or 1R.
-		if (pAd->Antenna.field.TxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFFFF3;
-		}
-		if (pAd->Antenna.field.RxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFF3FF;
-		}
-
-		RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
-	}
-	else
-	{
-	    ULONG	TxPinCfg = 0x00050F05;//2007.10.09 by Brian : 0x00050505 ==> 0x00050F05
-
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0xF2);
-
-        // According the Rory's suggestion to solve the middle range issue.
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R86, &BbpValue);
-		ASSERT((BbpValue == 0x00));
-		if ((BbpValue != 0x00))
-		{
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0x00);
-		}
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R91, &BbpValue);
-		ASSERT((BbpValue == 0x04));
-
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R92, &BbpValue);
-		ASSERT((BbpValue == 0x00));
-
-		// 5.5GHz band selection PIN, bit1 and bit2 are complement
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		Value &= (~0x6);
-		Value |= (0x02);
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-
-        // Turn off unused PA or LNA when only 1T or 1R.
-		if (pAd->Antenna.field.TxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFFFF3;
-	    }
-		if (pAd->Antenna.field.RxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFF3FF;
-		}
-
-		RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
-	}
-
-    // R66 should be set according to Channel and use 20MHz when scanning
-	if (Channel <= 14)
-	{
-		// BG band
-		R66 = 0x2E + GET_LNA_GAIN(pAd);
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-	}
-	else
-	{
-		// 5.5 GHz band
-		if (pAd->ate.TxWI.BW == BW_20)
-		{
-			R66 = (UCHAR)(0x32 + (GET_LNA_GAIN(pAd)*5)/3);
-    		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-		}
-		else
-		{
-			R66 = (UCHAR)(0x3A + (GET_LNA_GAIN(pAd)*5)/3);
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-		}
-	}
-
-	//
-	// On 11A, We should delay and wait RF/BBP to be stable
-	// and the appropriate time should be 1000 micro seconds
-	// 2005/06/05 - On 11G, We also need this delay time. Otherwise it's difficult to pass the WHQL.
-	//
-	RTMPusecDelay(1000);
-
-	if (Channel > 14)
-	{
-		// When 5.5GHz band the LSB of TxPwr will be used to reduced 7dB or not.
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, %dT) to , R1=0x%08lx, R2=0x%08lx, R3=0x%08lx, R4=0x%08lx\n",
-								  Channel,
-								  pAd->RfIcType,
-								  pAd->Antenna.field.TxPath,
-								  pAd->LatchRfRegs.R1,
-								  pAd->LatchRfRegs.R2,
-								  pAd->LatchRfRegs.R3,
-								  pAd->LatchRfRegs.R4));
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%u, Pwr1=%u, %dT) to , R1=0x%08lx, R2=0x%08lx, R3=0x%08lx, R4=0x%08lx\n",
-								  Channel,
-								  pAd->RfIcType,
-								  (R3 & 0x00003e00) >> 9,
-								  (R4 & 0x000007c0) >> 6,
-								  pAd->Antenna.field.TxPath,
-								  pAd->LatchRfRegs.R1,
-								  pAd->LatchRfRegs.R2,
-								  pAd->LatchRfRegs.R3,
-								  pAd->LatchRfRegs.R4));
-    }
-}
-
-//
-// In fact, no one will call this routine so far !
-//
-/*
-	==========================================================================
-	Description:
-		Gives CCK TX rate 2 more dB TX power.
-		This routine works only in ATE mode.
-
-		calculate desired Tx power in RF R3.Tx0~5,	should consider -
-		0. if current radio is a noisy environment (pAd->DrsCounters.fNoisyEnvironment)
-		1. TxPowerPercentage
-		2. auto calibration based on TSSI feedback
-		3. extra 2 db for CCK
-		4. -10 db upon very-short distance (AvgRSSI >= -40db) to AP
-
-	NOTE: Since this routine requires the value of (pAd->DrsCounters.fNoisyEnvironment),
-		it should be called AFTER MlmeDynamicTxRateSwitching()
-	==========================================================================
- */
-VOID ATEAsicAdjustTxPower(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT			i, j;
-	CHAR		DeltaPwr = 0;
-	BOOLEAN		bAutoTxAgc = FALSE;
-	UCHAR		TssiRef, *pTssiMinusBoundary, *pTssiPlusBoundary, TxAgcStep;
-	UCHAR		BbpR49 = 0, idx;
-	PCHAR		pTxAgcCompensate;
-	ULONG		TxPwr[5];
-	CHAR		Value;
-
-	/* no one calls this procedure so far */
-	if (pAd->ate.TxWI.BW == BW_40)
-	{
-		if (pAd->ate.Channel > 14)
-		{
-			TxPwr[0] = pAd->Tx40MPwrCfgABand[0];
-			TxPwr[1] = pAd->Tx40MPwrCfgABand[1];
-			TxPwr[2] = pAd->Tx40MPwrCfgABand[2];
-			TxPwr[3] = pAd->Tx40MPwrCfgABand[3];
-			TxPwr[4] = pAd->Tx40MPwrCfgABand[4];
-		}
-		else
-		{
-			TxPwr[0] = pAd->Tx40MPwrCfgGBand[0];
-			TxPwr[1] = pAd->Tx40MPwrCfgGBand[1];
-			TxPwr[2] = pAd->Tx40MPwrCfgGBand[2];
-			TxPwr[3] = pAd->Tx40MPwrCfgGBand[3];
-			TxPwr[4] = pAd->Tx40MPwrCfgGBand[4];
-		}
-	}
-	else
-	{
-		if (pAd->ate.Channel > 14)
-		{
-			TxPwr[0] = pAd->Tx20MPwrCfgABand[0];
-			TxPwr[1] = pAd->Tx20MPwrCfgABand[1];
-			TxPwr[2] = pAd->Tx20MPwrCfgABand[2];
-			TxPwr[3] = pAd->Tx20MPwrCfgABand[3];
-			TxPwr[4] = pAd->Tx20MPwrCfgABand[4];
-		}
-		else
-		{
-			TxPwr[0] = pAd->Tx20MPwrCfgGBand[0];
-			TxPwr[1] = pAd->Tx20MPwrCfgGBand[1];
-			TxPwr[2] = pAd->Tx20MPwrCfgGBand[2];
-			TxPwr[3] = pAd->Tx20MPwrCfgGBand[3];
-			TxPwr[4] = pAd->Tx20MPwrCfgGBand[4];
-		}
-	}
-
-	// TX power compensation for temperature variation based on TSSI.
-	// Do it per 4 seconds.
-	if (pAd->Mlme.OneSecPeriodicRound % 4 == 0)
-	{
-		if (pAd->ate.Channel <= 14)
-		{
-			/* bg channel */
-			bAutoTxAgc         = pAd->bAutoTxAgcG;
-			TssiRef            = pAd->TssiRefG;
-			pTssiMinusBoundary = &pAd->TssiMinusBoundaryG[0];
-			pTssiPlusBoundary  = &pAd->TssiPlusBoundaryG[0];
-			TxAgcStep          = pAd->TxAgcStepG;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateG;
-		}
-		else
-		{
-			/* a channel */
-			bAutoTxAgc         = pAd->bAutoTxAgcA;
-			TssiRef            = pAd->TssiRefA;
-			pTssiMinusBoundary = &pAd->TssiMinusBoundaryA[0];
-			pTssiPlusBoundary  = &pAd->TssiPlusBoundaryA[0];
-			TxAgcStep          = pAd->TxAgcStepA;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateA;
-		}
-
-		if (bAutoTxAgc)
-		{
-			/* BbpR49 is unsigned char */
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R49, &BbpR49);
-
-			/* (p) TssiPlusBoundaryG[0] = 0 = (m) TssiMinusBoundaryG[0] */
-			/* compensate: +4     +3   +2   +1    0   -1   -2   -3   -4 * steps */
-			/* step value is defined in pAd->TxAgcStepG for tx power value */
-
-			/* [4]+1+[4]   p4     p3   p2   p1   o1   m1   m2   m3   m4 */
-			/* ex:         0x00 0x15 0x25 0x45 0x88 0xA0 0xB5 0xD0 0xF0
-			   above value are examined in mass factory production */
-			/*             [4]    [3]  [2]  [1]  [0]  [1]  [2]  [3]  [4] */
-
-			/* plus is 0x10 ~ 0x40, minus is 0x60 ~ 0x90 */
-			/* if value is between p1 ~ o1 or o1 ~ s1, no need to adjust tx power */
-			/* if value is 0x65, tx power will be -= TxAgcStep*(2-1) */
-
-			if (BbpR49 > pTssiMinusBoundary[1])
-			{
-				// Reading is larger than the reference value.
-				// Check for how large we need to decrease the Tx power.
-				for (idx = 1; idx < 5; idx++)
-				{
-					if (BbpR49 <= pTssiMinusBoundary[idx])  // Found the range
-						break;
-				}
-				// The index is the step we should decrease, idx = 0 means there is nothing to compensate
-//				if (R3 > (ULONG) (TxAgcStep * (idx-1)))
-					*pTxAgcCompensate = -(TxAgcStep * (idx-1));
-//				else
-//					*pTxAgcCompensate = -((UCHAR)R3);
-
-				DeltaPwr += (*pTxAgcCompensate);
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("-- Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = -%d\n",
-					BbpR49, TssiRef, TxAgcStep, idx-1));
-			}
-			else if (BbpR49 < pTssiPlusBoundary[1])
-			{
-				// Reading is smaller than the reference value
-				// check for how large we need to increase the Tx power
-				for (idx = 1; idx < 5; idx++)
-				{
-					if (BbpR49 >= pTssiPlusBoundary[idx])   // Found the range
-						break;
-				}
-				// The index is the step we should increase, idx = 0 means there is nothing to compensate
-				*pTxAgcCompensate = TxAgcStep * (idx-1);
-				DeltaPwr += (*pTxAgcCompensate);
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("++ Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
-					BbpR49, TssiRef, TxAgcStep, idx-1));
-			}
-			else
-			{
-				*pTxAgcCompensate = 0;
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("   Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
-					BbpR49, TssiRef, TxAgcStep, 0));
-			}
-		}
-	}
-	else
-	{
-		if (pAd->ate.Channel <= 14)
-		{
-			bAutoTxAgc         = pAd->bAutoTxAgcG;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateG;
-		}
-		else
-		{
-			bAutoTxAgc         = pAd->bAutoTxAgcA;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateA;
-		}
-
-		if (bAutoTxAgc)
-			DeltaPwr += (*pTxAgcCompensate);
-	}
-
-	/* calculate delta power based on the percentage specified from UI */
-	// E2PROM setting is calibrated for maximum TX power (i.e. 100%)
-	// We lower TX power here according to the percentage specified from UI
-	if (pAd->CommonCfg.TxPowerPercentage == 0xffffffff)       // AUTO TX POWER control
-		;
-	else if (pAd->CommonCfg.TxPowerPercentage > 90)  // 91 ~ 100% & AUTO, treat as 100% in terms of mW
-		;
-	else if (pAd->CommonCfg.TxPowerPercentage > 60)  // 61 ~ 90%, treat as 75% in terms of mW
-	{
-		DeltaPwr -= 1;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 30)  // 31 ~ 60%, treat as 50% in terms of mW
-	{
-		DeltaPwr -= 3;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 15)  // 16 ~ 30%, treat as 25% in terms of mW
-	{
-		DeltaPwr -= 6;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 9)   // 10 ~ 15%, treat as 12.5% in terms of mW
-	{
-		DeltaPwr -= 9;
-	}
-	else                                           // 0 ~ 9 %, treat as MIN(~3%) in terms of mW
-	{
-		DeltaPwr -= 12;
-	}
-
-	/* reset different new tx power for different TX rate */
-	for(i=0; i<5; i++)
-	{
-		if (TxPwr[i] != 0xffffffff)
-		{
-			for (j=0; j<8; j++)
-			{
-				Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F); /* 0 ~ 15 */
-
-				if ((Value + DeltaPwr) < 0)
-				{
-					Value = 0; /* min */
-				}
-				else if ((Value + DeltaPwr) > 0xF)
-				{
-					Value = 0xF; /* max */
-				}
-				else
-				{
-					Value += DeltaPwr; /* temperature compensation */
-				}
-
-				/* fill new value to CSR offset */
-				TxPwr[i] = (TxPwr[i] & ~(0x0000000F << j*4)) | (Value << j*4);
-			}
-
-			/* write tx power value to CSR */
-			/* TX_PWR_CFG_0 (8 tx rate) for	TX power for OFDM 12M/18M
-											TX power for OFDM 6M/9M
-											TX power for CCK5.5M/11M
-											TX power for CCK1M/2M */
-			/* TX_PWR_CFG_1 ~ TX_PWR_CFG_4 */
-			RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, TxPwr[i]);
-
-
-		}
-	}
-
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Write TxWI for ATE mode.
-
-	Return Value:
-		None
-	========================================================================
-*/
-
-#ifdef RT2870
-static VOID ATEWriteTxWI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXWI_STRUC 	pTxWI,
-	IN	BOOLEAN			FRAG,
-	IN	BOOLEAN			InsTimestamp,
-	IN	BOOLEAN 		AMPDU,
-	IN	BOOLEAN 		Ack,
-	IN	BOOLEAN 		NSeq,		// HW new a sequence.
-	IN	UCHAR			BASize,
-	IN	UCHAR			WCID,
-	IN	ULONG			Length,
-	IN	UCHAR 			PID,
-	IN	UCHAR			MIMOps,
-	IN	UCHAR			Txopmode,
-	IN	BOOLEAN			CfAck,
-	IN	HTTRANSMIT_SETTING	Transmit)
-{
-	//
-	// Always use Long preamble before verifiation short preamble functionality works well.
-	// Todo: remove the following line if short preamble functionality works
-	//
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-	pTxWI->FRAG= FRAG;
-	pTxWI->TS= InsTimestamp;
-	pTxWI->AMPDU = AMPDU;
-
-	pTxWI->MIMOps = PWR_ACTIVE;
-	pTxWI->MpduDensity = 4;
-	pTxWI->ACK = Ack;
-	pTxWI->txop = Txopmode;
-	pTxWI->NSEQ = NSeq;
-	pTxWI->BAWinSize = BASize;
-
-	pTxWI->WirelessCliID = WCID;
-	pTxWI->MPDUtotalByteCount = Length;
-	pTxWI->PacketId = PID;
-
-	pTxWI->BW = Transmit.field.BW;
-	pTxWI->ShortGI = Transmit.field.ShortGI;
-	pTxWI->STBC= Transmit.field.STBC;
-
-	pTxWI->MCS = Transmit.field.MCS;
-	pTxWI->PHYMODE= Transmit.field.MODE;
-
-#ifdef DOT11_N_SUPPORT
-	//
-	// MMPS is 802.11n features. Because TxWI->MCS > 7 must be HT mode,
-	// so need not check if it's HT rate.
-	//
-	if ((MIMOps == MMPS_STATIC) && (pTxWI->MCS > 7))
-		pTxWI->MCS = 7;
-
-	if ((MIMOps == MMPS_DYNAMIC) && (pTxWI->MCS > 7)) // SMPS protect 2 spatial.
-		pTxWI->MIMOps = 1;
-#endif // DOT11_N_SUPPORT //
-
-	pTxWI->CFACK = CfAck;
-
-	return;
-}
-#endif // RT2870 //
-/*
-	========================================================================
-
-	Routine Description:
-		Disable protection for ATE.
-	========================================================================
-*/
-VOID ATEDisableAsicProtect(
-	IN		PRTMP_ADAPTER	pAd)
-{
-	PROT_CFG_STRUC	ProtCfg, ProtCfg4;
-	UINT32 Protect[6];
-	USHORT			offset;
-	UCHAR			i;
-	UINT32 MacReg = 0;
-
-	// Config ASIC RTS threshold register
-	RTMP_IO_READ32(pAd, TX_RTS_CFG, &MacReg);
-	MacReg &= 0xFF0000FF;
-	MacReg |= (pAd->CommonCfg.RtsThreshold << 8);
-	RTMP_IO_WRITE32(pAd, TX_RTS_CFG, MacReg);
-
-	// Initial common protection settings
-	RTMPZeroMemory(Protect, sizeof(Protect));
-	ProtCfg4.word = 0;
-	ProtCfg.word = 0;
-	ProtCfg.field.TxopAllowGF40 = 1;
-	ProtCfg.field.TxopAllowGF20 = 1;
-	ProtCfg.field.TxopAllowMM40 = 1;
-	ProtCfg.field.TxopAllowMM20 = 1;
-	ProtCfg.field.TxopAllowOfdm = 1;
-	ProtCfg.field.TxopAllowCck = 1;
-	ProtCfg.field.RTSThEn = 1;
-	ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
-
-	// Handle legacy(B/G) protection
-	ProtCfg.field.ProtectRate = pAd->CommonCfg.RtsRate;
-	ProtCfg.field.ProtectCtrl = 0;
-	Protect[0] = ProtCfg.word;
-	Protect[1] = ProtCfg.word;
-
-	// NO PROTECT
-	// 1.All STAs in the BSS are 20/40 MHz HT
-	// 2. in ai 20/40MHz BSS
-	// 3. all STAs are 20MHz in a 20MHz BSS
-	// Pure HT. no protection.
-
-	// MM20_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 010111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4004 (OFDM 24M)
-	Protect[2] = 0x01744004;
-
-	// MM40_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 111111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4084 (duplicate OFDM 24M)
-	Protect[3] = 0x03f44084;
-
-	// CF20_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 010111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4004 (OFDM 24M)
-	Protect[4] = 0x01744004;
-
-	// CF40_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 111111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4084 (duplicate OFDM 24M)
-	Protect[5] = 0x03f44084;
-
-	pAd->CommonCfg.IOTestParm.bRTSLongProtOn = FALSE;
-
-	offset = CCK_PROT_CFG;
-	for (i = 0;i < 6;i++)
-		RTMP_IO_WRITE32(pAd, offset + i*4, Protect[i]);
-
-}
-
-#ifdef RT2870
-/*
-	========================================================================
-	Routine	Description:
-		Write TxInfo for ATE mode.
-
-	Return Value:
-		None
-	========================================================================
-*/
-static VOID ATEWriteTxInfo(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXINFO_STRUC 	pTxInfo,
-	IN	USHORT		USBDMApktLen,
-	IN	BOOLEAN		bWiv,
-	IN	UCHAR			QueueSel,
-	IN	UCHAR			NextValid,
-	IN	UCHAR			TxBurst)
-{
-	pTxInfo->USBDMATxPktLen = USBDMApktLen;
-	pTxInfo->QSEL = QueueSel;
-
-	if (QueueSel != FIFO_EDCA)
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("=======> QueueSel != FIFO_EDCA<=======\n"));
-
-	pTxInfo->USBDMANextVLD = NextValid;
-	pTxInfo->USBDMATxburst = TxBurst;
-	pTxInfo->WIV = bWiv;
-	pTxInfo->SwUseLastRound = 0;
-	pTxInfo->rsv = 0;
-	pTxInfo->rsv2 = 0;
-
-	return;
-}
-#endif // RT2870 //
-
-/* There are two ways to convert Rssi */
-#if 1
-//
-// The way used with GET_LNA_GAIN().
-//
-CHAR ATEConvertToRssi(
-	IN PRTMP_ADAPTER pAd,
-	IN	CHAR	Rssi,
-	IN  UCHAR   RssiNumber)
-{
-	UCHAR	RssiOffset, LNAGain;
-
-	// Rssi equals to zero should be an invalid value
-	if (Rssi == 0)
-		return -99;
-
-	LNAGain = GET_LNA_GAIN(pAd);
-	if (pAd->LatchRfRegs.Channel > 14)
-	{
-		if (RssiNumber == 0)
-			RssiOffset = pAd->ARssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->ARssiOffset1;
-		else
-			RssiOffset = pAd->ARssiOffset2;
-	}
-	else
-	{
-		if (RssiNumber == 0)
-			RssiOffset = pAd->BGRssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->BGRssiOffset1;
-		else
-			RssiOffset = pAd->BGRssiOffset2;
-	}
-
-	return (-12 - RssiOffset - LNAGain - Rssi);
-}
-#else
-//
-// The way originally used in ATE of rt2860ap.
-//
-CHAR ATEConvertToRssi(
-	IN PRTMP_ADAPTER pAd,
-	IN	CHAR			Rssi,
-	IN  UCHAR   RssiNumber)
-{
-	UCHAR	RssiOffset, LNAGain;
-
-	// Rssi equals to zero should be an invalid value
-	if (Rssi == 0)
-		return -99;
-
-    if (pAd->LatchRfRegs.Channel > 14)
-    {
-        LNAGain = pAd->ALNAGain;
-        if (RssiNumber == 0)
-			RssiOffset = pAd->ARssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->ARssiOffset1;
-		else
-			RssiOffset = pAd->ARssiOffset2;
-    }
-    else
-    {
-        LNAGain = pAd->BLNAGain;
-        if (RssiNumber == 0)
-			RssiOffset = pAd->BGRssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->BGRssiOffset1;
-		else
-			RssiOffset = pAd->BGRssiOffset2;
-    }
-
-    return (-32 - RssiOffset + LNAGain - Rssi);
-}
-#endif /* end of #if 1 */
-
-/*
-	========================================================================
-
-	Routine Description:
-		Set Japan filter coefficients if needed.
-	Note:
-		This routine should only be called when
-		entering TXFRAME mode or TXCONT mode.
-
-	========================================================================
-*/
-static VOID SetJapanFilter(
-	IN		PRTMP_ADAPTER	pAd)
-{
-	UCHAR			BbpData = 0;
-
-	//
-	// If Channel=14 and Bandwidth=20M and Mode=CCK, set BBP R4 bit5=1
-	// (Japan Tx filter coefficients)when (TXFRAME or TXCONT).
-	//
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BbpData);
-
-    if ((pAd->ate.TxWI.PHYMODE == MODE_CCK) && (pAd->ate.Channel == 14) && (pAd->ate.TxWI.BW == BW_20))
-    {
-        BbpData |= 0x20;    // turn on
-        ATEDBGPRINT(RT_DEBUG_TRACE, ("SetJapanFilter!!!\n"));
-    }
-    else
-    {
-		BbpData &= 0xdf;    // turn off
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ClearJapanFilter!!!\n"));
-    }
-
-	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BbpData);
-}
-
-VOID ATESampleRssi(
-	IN PRTMP_ADAPTER	pAd,
-	IN PRXWI_STRUC		pRxWI)
-{
-	/* There are two ways to collect RSSI. */
-#if 1
-	//pAd->LastRxRate = (USHORT)((pRxWI->MCS) + (pRxWI->BW <<7) + (pRxWI->ShortGI <<8)+ (pRxWI->PHYMODE <<14)) ;
-	if (pRxWI->RSSI0 != 0)
-	{
-		pAd->ate.LastRssi0	= ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI0, RSSI_0);
-		pAd->ate.AvgRssi0X8	= (pAd->ate.AvgRssi0X8 - pAd->ate.AvgRssi0) + pAd->ate.LastRssi0;
-		pAd->ate.AvgRssi0  	= pAd->ate.AvgRssi0X8 >> 3;
-	}
-	if (pRxWI->RSSI1 != 0)
-	{
-		pAd->ate.LastRssi1	= ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI1, RSSI_1);
-		pAd->ate.AvgRssi1X8	= (pAd->ate.AvgRssi1X8 - pAd->ate.AvgRssi1) + pAd->ate.LastRssi1;
-		pAd->ate.AvgRssi1	= pAd->ate.AvgRssi1X8 >> 3;
-	}
-	if (pRxWI->RSSI2 != 0)
-	{
-		pAd->ate.LastRssi2	= ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI2, RSSI_2);
-		pAd->ate.AvgRssi2X8	= (pAd->ate.AvgRssi2X8 - pAd->ate.AvgRssi2) + pAd->ate.LastRssi2;
-		pAd->ate.AvgRssi2	= pAd->ate.AvgRssi2X8 >> 3;
-	}
-
-	pAd->ate.LastSNR0 = (CHAR)(pRxWI->SNR0);// CHAR ==> UCHAR ?
-	pAd->ate.LastSNR1 = (CHAR)(pRxWI->SNR1);// CHAR ==> UCHAR ?
-
-	pAd->ate.NumOfAvgRssiSample ++;
-#else
-	pAd->ate.LastSNR0 = (CHAR)(pRxWI->SNR0);
-	pAd->ate.LastSNR1 = (CHAR)(pRxWI->SNR1);
-	pAd->ate.RxCntPerSec++;
-	pAd->ate.LastRssi0 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI0, RSSI_0);
-	pAd->ate.LastRssi1 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI1, RSSI_1);
-	pAd->ate.LastRssi2 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI2, RSSI_2);
-	pAd->ate.AvgRssi0X8 = (pAd->ate.AvgRssi0X8 - pAd->ate.AvgRssi0) + pAd->ate.LastRssi0;
-	pAd->ate.AvgRssi0 = pAd->ate.AvgRssi0X8 >> 3;
-	pAd->ate.AvgRssi1X8 = (pAd->ate.AvgRssi1X8 - pAd->ate.AvgRssi1) + pAd->ate.LastRssi1;
-	pAd->ate.AvgRssi1 = pAd->ate.AvgRssi1X8 >> 3;
-	pAd->ate.AvgRssi2X8 = (pAd->ate.AvgRssi2X8 - pAd->ate.AvgRssi2) + pAd->ate.LastRssi2;
-	pAd->ate.AvgRssi2 = pAd->ate.AvgRssi2X8 >> 3;
-	pAd->ate.NumOfAvgRssiSample ++;
-#endif
-}
-
-#ifdef CONFIG_STA_SUPPORT
-VOID RTMPStationStop(
-    IN  PRTMP_ADAPTER   pAd)
-{
-//	BOOLEAN       Cancelled;
-
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("==> RTMPStationStop\n"));
-
-#if 0
-	RTMPCancelTimer(&pAd->MlmeAux.AssocTimer,      &Cancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer,    &Cancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer,   &Cancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.AuthTimer,       &Cancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer,     &Cancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.ScanTimer,       &Cancelled);
-#endif
-	// For rx statistics, we need to keep this timer running.
-//	RTMPCancelTimer(&pAd->Mlme.PeriodicTimer,      &Cancelled);
-
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("<== RTMPStationStop\n"));
-}
-
-VOID RTMPStationStart(
-    IN  PRTMP_ADAPTER   pAd)
-{
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("==> RTMPStationStart\n"));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("<== RTMPStationStart\n"));
-}
-#endif // CONFIG_STA_SUPPORT //
-
-/*
-	==========================================================================
-	Description:
-		Setup Frame format.
-	NOTE:
-		This routine should only be used in ATE mode.
-	==========================================================================
- */
-
-#ifdef RT2870
-/*======================Start of RT2870======================*/
-/*                                                           */
-/*                                                           */
-static INT ATESetUpFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT32 TxIdx)
-{
-	UINT j;
-	PTX_CONTEXT	pNullContext;
-	PUCHAR			pDest;
-	HTTRANSMIT_SETTING	TxHTPhyMode;
-	PTXWI_STRUC		pTxWI;
-	PTXINFO_STRUC		pTxInfo;
-	UINT32			TransferBufferLength, OrgBufferLength = 0;
-	UCHAR			padLen = 0;
-#ifdef RALINK_28xx_QA
-	PHEADER_802_11	pHeader80211 = NULL;
-#endif // RALINK_28xx_QA //
-
-	if ((RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) ||
-		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)) ||
-		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) ||
-		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-	{
-		return -1;
-	}
-
-	/* We always use QID_AC_BE and FIFO_EDCA in ATE mode. */
-
-	pNullContext = &(pAd->NullContext);
-	ASSERT(pNullContext != NULL);
-
-	if (pNullContext->InUse == FALSE)
-	{
-		// Set the in use bit
-		pNullContext->InUse = TRUE;
-		NdisZeroMemory(&(pAd->NullFrame), sizeof(HEADER_802_11));
-
-		// Fill 802.11 header.
-#ifdef RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			pHeader80211 = NdisMoveMemory(&(pAd->NullFrame), pAd->ate.Header, pAd->ate.HLen);
-//			pDest = NdisMoveMemory(&(pAd->NullFrame), pAd->ate.Header, pAd->ate.HLen);
-//			pHeader80211 = (PHEADER_802_11)pDest;
-		}
-		else
-#endif // RALINK_28xx_QA //
-		{
-			// Fill 802.11 header.
-			NdisMoveMemory(&(pAd->NullFrame), TemplateFrame, sizeof(HEADER_802_11));
-		}
-#ifdef RT_BIG_ENDIAN
-		RTMPFrameEndianChange(pAd, (PUCHAR)&(pAd->NullFrame), DIR_READ, FALSE);
-#endif // RT_BIG_ENDIAN //
-
-#ifdef RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			/* modify sequence number.... */
-			if (pAd->ate.TxDoneCount == 0)
-			{
-				pAd->ate.seq = pHeader80211->Sequence;
-			}
-			else
-			{
-				pHeader80211->Sequence = ++pAd->ate.seq;
-			}
-			/* We already got all the addr. fields from QA GUI. */
-		}
-		else
-#endif // RALINK_28xx_QA //
-		{
-			COPY_MAC_ADDR(pAd->NullFrame.Addr1, pAd->ate.Addr1);
-			COPY_MAC_ADDR(pAd->NullFrame.Addr2, pAd->ate.Addr2);
-			COPY_MAC_ADDR(pAd->NullFrame.Addr3, pAd->ate.Addr3);
-		}
-
-		RTMPZeroMemory(&pAd->NullContext.TransferBuffer->field.WirelessPacket[0], TX_BUFFER_NORMSIZE);//???
-		pTxInfo = (PTXINFO_STRUC)&pAd->NullContext.TransferBuffer->field.WirelessPacket[0];
-
-#ifdef RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			// Avoid to exceed the range of WirelessPacket[].
-			ASSERT(pAd->ate.TxInfo.USBDMATxPktLen <= (MAX_FRAME_SIZE - 34/* == 2312 */));
-			NdisMoveMemory(pTxInfo, &(pAd->ate.TxInfo), sizeof(pAd->ate.TxInfo));
-		}
-		else
-#endif // RALINK_28xx_QA //
-		{
-			// Avoid to exceed the range of WirelessPacket[].
-			ASSERT(pAd->ate.TxLength <= (MAX_FRAME_SIZE - 34/* == 2312 */));
-
-			// pTxInfo->USBDMATxPktLen will be updated to include padding later.
-			ATEWriteTxInfo(pAd, pTxInfo, (USHORT)(TXWI_SIZE + pAd->ate.TxLength), TRUE, EpToQueue[MGMTPIPEIDX], FALSE,  FALSE);
-			pTxInfo->QSEL = FIFO_EDCA;
-		}
-
-		pTxWI = (PTXWI_STRUC)&pAd->NullContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE];
-
-		// Fill TxWI.
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			TxHTPhyMode.field.BW = pAd->ate.TxWI.BW;
-			TxHTPhyMode.field.ShortGI = pAd->ate.TxWI.ShortGI;
-			TxHTPhyMode.field.STBC = pAd->ate.TxWI.STBC;
-			TxHTPhyMode.field.MCS = pAd->ate.TxWI.MCS;
-			TxHTPhyMode.field.MODE = pAd->ate.TxWI.PHYMODE;
-			ATEWriteTxWI(pAd, pTxWI, pAd->ate.TxWI.FRAG, pAd->ate.TxWI.TS, pAd->ate.TxWI.AMPDU, pAd->ate.TxWI.ACK, pAd->ate.TxWI.NSEQ,
-				pAd->ate.TxWI.BAWinSize, BSSID_WCID, pAd->ate.TxWI.MPDUtotalByteCount/* include 802.11 header */, pAd->ate.TxWI.PacketId, 0, pAd->ate.TxWI.txop/*IFS_HTTXOP*/, pAd->ate.TxWI.CFACK/*FALSE*/, TxHTPhyMode);
-		}
-		else
-		{
-			TxHTPhyMode.field.BW = pAd->ate.TxWI.BW;
-			TxHTPhyMode.field.ShortGI = pAd->ate.TxWI.ShortGI;
-			TxHTPhyMode.field.STBC = 0;
-			TxHTPhyMode.field.MCS = pAd->ate.TxWI.MCS;
-			TxHTPhyMode.field.MODE = pAd->ate.TxWI.PHYMODE;
-
-			ATEWriteTxWI(pAd, pTxWI,  FALSE, FALSE, FALSE, FALSE/* No ack required. */, FALSE, 0, BSSID_WCID, pAd->ate.TxLength,
-				0, 0, IFS_HTTXOP, FALSE, TxHTPhyMode);// "MMPS_STATIC" instead of "MMPS_DYNAMIC" ???
-		}
-
-		RTMPMoveMemory(&pAd->NullContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE+TXWI_SIZE], &pAd->NullFrame, sizeof(HEADER_802_11));
-
-		pDest = &(pAd->NullContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE+TXWI_SIZE+sizeof(HEADER_802_11)]);
-
-		// Prepare frame payload
-#ifdef RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			// copy pattern
-			if ((pAd->ate.PLen != 0))
-			{
-				for (j = 0; j < pAd->ate.DLen; j+=pAd->ate.PLen)
-				{
-					RTMPMoveMemory(pDest, pAd->ate.Pattern, pAd->ate.PLen);
-					pDest += pAd->ate.PLen;
-				}
-			}
-			TransferBufferLength = TXINFO_SIZE + TXWI_SIZE + pAd->ate.TxWI.MPDUtotalByteCount;
-		}
-		else
-#endif // RALINK_28xx_QA //
-		{
-		    for (j = 0; j < (pAd->ate.TxLength - sizeof(HEADER_802_11)); j++)
-		    {
-				*pDest = 0xA5;
-				pDest += 1;
-		    }
-			TransferBufferLength = TXINFO_SIZE + TXWI_SIZE + pAd->ate.TxLength;
-		}
-
-#if 1
-		OrgBufferLength = TransferBufferLength;
-		TransferBufferLength = (TransferBufferLength + 3) & (~3);
-
-		// Always add 4 extra bytes at every packet.
-		padLen = TransferBufferLength - OrgBufferLength + 4;/* 4 == last packet padding */
-		ASSERT((padLen <= (RTMP_PKT_TAIL_PADDING - 4/* 4 == MaxBulkOutsize alignment padding */)));
-
-		/* Now memzero all extra padding bytes. */
-		NdisZeroMemory(pDest, padLen);
-		pDest += padLen;
-#else
-		if ((TransferBufferLength % 4) == 1)
-		{
-			NdisZeroMemory(pDest, 7);
-			pDest += 7;
-			TransferBufferLength  += 3;
-		}
-		else if ((TransferBufferLength % 4) == 2)
-		{
-			NdisZeroMemory(pDest, 6);
-			pDest += 6;
-			TransferBufferLength  += 2;
-		}
-		else if ((TransferBufferLength % 4) == 3)
-		{
-			NdisZeroMemory(pDest, 5);
-			pDest += 5;
-			TransferBufferLength  += 1;
-		}
-#endif // 1 //
-
-		// Update pTxInfo->USBDMATxPktLen to include padding.
-		pTxInfo->USBDMATxPktLen = TransferBufferLength - TXINFO_SIZE;
-
-		TransferBufferLength += 4;
-
-		// If TransferBufferLength is multiple of 64, add extra 4 bytes again.
-		if ((TransferBufferLength % pAd->BulkOutMaxPacketSize) == 0)
-		{
-			NdisZeroMemory(pDest, 4);
-			TransferBufferLength += 4;
-		}
-
-		// Fill out frame length information for global Bulk out arbitor
-		pAd->NullContext.BulkOutSize = TransferBufferLength;
-	}
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-	RTMPFrameEndianChange(pAd, (((PUCHAR)pTxInfo)+TXWI_SIZE+TXINFO_SIZE), DIR_WRITE, FALSE);
-    RTMPDescriptorEndianChange((PUCHAR)pTxInfo, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-	return 0;
-}
-
-VOID ATE_RTUSBBulkOutDataPacketComplete(purbb_t pUrb, struct pt_regs *pt_regs)
-{
-	PRTMP_ADAPTER		pAd;
-	PTX_CONTEXT		    pNullContext;
-	UCHAR				BulkOutPipeId;
-	NTSTATUS			Status;
-	unsigned long		IrqFlags;
-	ULONG			    OldValue;
-
-	pNullContext = (PTX_CONTEXT)pUrb->context;
-	pAd = pNullContext->pAd;
-
-
-	// Reset Null frame context flags
-	pNullContext->IRPPending = FALSE;
-	pNullContext->InUse = FALSE;
-	Status = pUrb->status;
-
-	// Store BulkOut PipeId
-	BulkOutPipeId = pNullContext->BulkOutPipeId;
-	pAd->BulkOutDataOneSecCount++;
-
-	if (Status == USB_ST_NOERROR)
-	{
-#ifdef RALINK_28xx_QA
-		if ((ATE_ON(pAd)) && (pAd->ate.bQATxStart == TRUE))
-		{
-			if (pAd->ate.QID == BulkOutPipeId)
-			{
-				// Let Rx can have a chance to break in during Tx process,
-				// especially for loopback mode in QA ATE.
-				// To trade off between tx performance and loopback mode integrity.
-				/* Q   : Now Rx is handled by tasklet, do we still need this delay ? */
-				/* Ans : Even tasklet is used, Rx/Tx < 1 if we do not delay for a while right here. */
-				RTMPusecDelay(500);
-				pAd->ate.TxDoneCount++;
-				pAd->RalinkCounters.KickTxCount++;
-				ASSERT(pAd->ate.QID == 0);
-				pAd->ate.TxAc0++;
-			}
-		}
-#endif // RALINK_28xx_QA //
-		pAd->BulkOutComplete++;
-
-		pAd->Counters8023.GoodTransmits++;
-
-		/* Don't worry about the queue is empty or not. This function will check itself. */
-		RTMPDeQueuePacket(pAd, TRUE, BulkOutPipeId, MAX_TX_PROCESS);
-
-		/* In 28xx, SendTxWaitQueue ==> TxSwQueue  */
-/*
-		if (pAd->SendTxWaitQueue[BulkOutPipeId].Number > 0)
-		{
-			RTMPDeQueuePacket(pAd, BulkOutPipeId);
-		}
-*/
-	}
-	else	// STATUS_OTHER
-	{
-		pAd->BulkOutCompleteOther++;
-
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("BulkOutDataPacket Failed STATUS_OTHER = 0x%x . \n", Status));
-		ATEDBGPRINT(RT_DEBUG_ERROR, (">>BulkOutReq=0x%lx, BulkOutComplete=0x%lx\n", pAd->BulkOutReq, pAd->BulkOutComplete));
-
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			/* In 28xx, RT_OID_USB_RESET_BULK_OUT ==> CMDTHREAD_RESET_BULK_OUT */
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-			// Check
-			BULK_OUT_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-			pAd->BulkOutPending[BulkOutPipeId] = FALSE;
-			pAd->bulkResetPipeid = BulkOutPipeId;
-			BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-			return;
-		}
-	}
-
-
-
-	if (atomic_read(&pAd->BulkOutRemained) > 0)
-	{
-		atomic_dec(&pAd->BulkOutRemained);
-	}
-
-	// 1st - Transmit Success
-	OldValue = pAd->WlanCounters.TransmittedFragmentCount.u.LowPart;
-	pAd->WlanCounters.TransmittedFragmentCount.u.LowPart++;
-
-	if (pAd->WlanCounters.TransmittedFragmentCount.u.LowPart < OldValue)
-	{
-		pAd->WlanCounters.TransmittedFragmentCount.u.HighPart++;
-	}
-
-	if(((pAd->ContinBulkOut == TRUE ) ||(atomic_read(&pAd->BulkOutRemained) > 0)) && (pAd->ate.Mode & ATE_TXFRAME))
-	{
-		RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-	}
-	else
-	{
-		RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-#ifdef RALINK_28xx_QA
-		pAd->ate.TxStatus = 0;
-#endif // RALINK_28xx_QA //
-	}
-
-	BULK_OUT_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-	pAd->BulkOutPending[BulkOutPipeId] = FALSE;
-	BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-
-	// Always call Bulk routine, even reset bulk.
-	// The protection of rest bulk should be in BulkOut routine.
-	RTUSBKickBulkOut(pAd);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	ATE_RTUSBBulkOutDataPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BulkOutPipeId)
-{
-	PTX_CONTEXT		pNullContext = &(pAd->NullContext);
-	PURB			pUrb;
-	int				ret = 0;
-	unsigned long	IrqFlags;
-
-
-	ASSERT(BulkOutPipeId == 0);
-
-	/* Build up the frame first. */
-//	ATESetUpFrame(pAd, 0);
-
-	BULK_OUT_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-
-	if (pAd->BulkOutPending[BulkOutPipeId] == TRUE)
-	{
-		BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-		return;
-	}
-
-	pAd->BulkOutPending[BulkOutPipeId] = TRUE;
-	BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-
-	// Increase Total transmit byte counter
-	pAd->RalinkCounters.OneSecTransmittedByteCount +=  pNullContext->BulkOutSize;
-	pAd->RalinkCounters.TransmittedByteCount +=  pNullContext->BulkOutSize;
-
-	// Clear ATE frame bulk out flag
-	RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-
-	// Init Tx context descriptor
-	pNullContext->IRPPending = TRUE;
-	RTUSBInitTxDesc(pAd, pNullContext, BulkOutPipeId, (usb_complete_t)ATE_RTUSBBulkOutDataPacketComplete);
-	pUrb = pNullContext->pUrb;
-
-	if((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("ATE_RTUSBBulkOutDataPacket: Submit Tx URB failed %d\n", ret));
-		return;
-	}
-
-	pAd->BulkOutReq++;
-	return;
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	ATE_RTUSBCancelPendingBulkInIRP(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	PRX_CONTEXT		pRxContext;
-	UINT			i;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("--->ATE_RTUSBCancelPendingBulkInIRP\n"));
-#if 1
-	for ( i = 0; i < (RX_RING_SIZE); i++)
-	{
-		pRxContext = &(pAd->RxContext[i]);
-		if(pRxContext->IRPPending == TRUE)
-		{
-			RTUSB_UNLINK_URB(pRxContext->pUrb);
-			pRxContext->IRPPending = FALSE;
-			pRxContext->InUse = FALSE;
-			//NdisInterlockedDecrement(&pAd->PendingRx);
-			//pAd->PendingRx--;
-		}
-	}
-#else
-	for ( i = 0; i < (RX_RING_SIZE); i++)
-	{
-		pRxContext = &(pAd->RxContext[i]);
-		if(atomic_read(&pRxContext->IrpLock) == IRPLOCK_CANCELABLE)
-		{
-			RTUSB_UNLINK_URB(pRxContext->pUrb);
-		}
-		InterlockedExchange(&pRxContext->IrpLock, IRPLOCK_CANCE_START);
-	}
-#endif // 1 //
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("<---ATE_RTUSBCancelPendingBulkInIRP\n"));
-	return;
-}
-#endif // RT2870 //
-
-VOID rt_ee_read_all(PRTMP_ADAPTER pAd, USHORT *Data)
-{
-	USHORT i;
-	USHORT value;
-
-	for (i = 0 ; i < EEPROM_SIZE/2 ; )
-	{
-		/* "value" is expecially for some compilers... */
-		RT28xx_EEPROM_READ16(pAd, i*2, value);
-		Data[i] = value;
-		i++;
-	}
-}
-
-VOID rt_ee_write_all(PRTMP_ADAPTER pAd, USHORT *Data)
-{
-	USHORT i;
-	USHORT value;
-
-	for (i = 0 ; i < EEPROM_SIZE/2 ; )
-	{
-		/* "value" is expecially for some compilers... */
-		value = Data[i];
-		RT28xx_EEPROM_WRITE16(pAd, i*2, value);
-		i ++;
-	}
-}
-#ifdef RALINK_28xx_QA
-VOID ATE_QA_Statistics(
-	IN PRTMP_ADAPTER			pAd,
-	IN PRXWI_STRUC				pRxWI,
-	IN PRT28XX_RXD_STRUC		pRxD,
-	IN PHEADER_802_11			pHeader)
-{
-	// update counter first
-	if (pHeader != NULL)
-	{
-		if (pHeader->FC.Type == BTYPE_DATA)
-		{
-			if (pRxD->U2M)
-				pAd->ate.U2M++;
-			else
-				pAd->ate.OtherData++;
-		}
-		else if (pHeader->FC.Type == BTYPE_MGMT)
-		{
-			if (pHeader->FC.SubType == SUBTYPE_BEACON)
-				pAd->ate.Beacon++;
-			else
-				pAd->ate.OtherCount++;
-		}
-		else if (pHeader->FC.Type == BTYPE_CNTL)
-		{
-			pAd->ate.OtherCount++;
-		}
-	}
-	pAd->ate.RSSI0 = pRxWI->RSSI0;
-	pAd->ate.RSSI1 = pRxWI->RSSI1;
-	pAd->ate.RSSI2 = pRxWI->RSSI2;
-	pAd->ate.SNR0 = pRxWI->SNR0;
-	pAd->ate.SNR1 = pRxWI->SNR1;
-}
-
-/* command id with Cmd Type == 0x0008(for 28xx)/0x0005(for iNIC) */
-#define RACFG_CMD_RF_WRITE_ALL		0x0000
-#define RACFG_CMD_E2PROM_READ16		0x0001
-#define RACFG_CMD_E2PROM_WRITE16	0x0002
-#define RACFG_CMD_E2PROM_READ_ALL	0x0003
-#define RACFG_CMD_E2PROM_WRITE_ALL	0x0004
-#define RACFG_CMD_IO_READ			0x0005
-#define RACFG_CMD_IO_WRITE			0x0006
-#define RACFG_CMD_IO_READ_BULK		0x0007
-#define RACFG_CMD_BBP_READ8			0x0008
-#define RACFG_CMD_BBP_WRITE8		0x0009
-#define RACFG_CMD_BBP_READ_ALL		0x000a
-#define RACFG_CMD_GET_COUNTER		0x000b
-#define RACFG_CMD_CLEAR_COUNTER		0x000c
-
-#define RACFG_CMD_RSV1				0x000d
-#define RACFG_CMD_RSV2				0x000e
-#define RACFG_CMD_RSV3				0x000f
-
-#define RACFG_CMD_TX_START			0x0010
-#define RACFG_CMD_GET_TX_STATUS		0x0011
-#define RACFG_CMD_TX_STOP			0x0012
-#define RACFG_CMD_RX_START			0x0013
-#define RACFG_CMD_RX_STOP			0x0014
-#define RACFG_CMD_GET_NOISE_LEVEL	0x0015
-
-#define RACFG_CMD_ATE_START			0x0080
-#define RACFG_CMD_ATE_STOP			0x0081
-
-#define RACFG_CMD_ATE_START_TX_CARRIER		0x0100
-#define RACFG_CMD_ATE_START_TX_CONT			0x0101
-#define RACFG_CMD_ATE_START_TX_FRAME		0x0102
-#define RACFG_CMD_ATE_SET_BW	            0x0103
-#define RACFG_CMD_ATE_SET_TX_POWER0	        0x0104
-#define RACFG_CMD_ATE_SET_TX_POWER1			0x0105
-#define RACFG_CMD_ATE_SET_FREQ_OFFSET		0x0106
-#define RACFG_CMD_ATE_GET_STATISTICS		0x0107
-#define RACFG_CMD_ATE_RESET_COUNTER			0x0108
-#define RACFG_CMD_ATE_SEL_TX_ANTENNA		0x0109
-#define RACFG_CMD_ATE_SEL_RX_ANTENNA		0x010a
-#define RACFG_CMD_ATE_SET_PREAMBLE			0x010b
-#define RACFG_CMD_ATE_SET_CHANNEL			0x010c
-#define RACFG_CMD_ATE_SET_ADDR1				0x010d
-#define RACFG_CMD_ATE_SET_ADDR2				0x010e
-#define RACFG_CMD_ATE_SET_ADDR3				0x010f
-#define RACFG_CMD_ATE_SET_RATE				0x0110
-#define RACFG_CMD_ATE_SET_TX_FRAME_LEN		0x0111
-#define RACFG_CMD_ATE_SET_TX_FRAME_COUNT	0x0112
-#define RACFG_CMD_ATE_START_RX_FRAME		0x0113
-#define RACFG_CMD_ATE_E2PROM_READ_BULK	0x0114
-#define RACFG_CMD_ATE_E2PROM_WRITE_BULK	0x0115
-#define RACFG_CMD_ATE_IO_WRITE_BULK		0x0116
-#define RACFG_CMD_ATE_BBP_READ_BULK		0x0117
-#define RACFG_CMD_ATE_BBP_WRITE_BULK	0x0118
-#define RACFG_CMD_ATE_RF_READ_BULK		0x0119
-#define RACFG_CMD_ATE_RF_WRITE_BULK		0x011a
-
-
-
-#define A2Hex(_X, _p) 				\
-{									\
-	UCHAR *p;						\
-	_X = 0;							\
-	p = _p;							\
-	while (((*p >= 'a') && (*p <= 'f')) || ((*p >= 'A') && (*p <= 'F')) || ((*p >= '0') && (*p <= '9')))		\
-	{												\
-		if ((*p >= 'a') && (*p <= 'f'))				\
-			_X = _X * 16 + *p - 87;					\
-		else if ((*p >= 'A') && (*p <= 'F'))		\
-			_X = _X * 16 + *p - 55;					\
-		else if ((*p >= '0') && (*p <= '9'))		\
-			_X = _X * 16 + *p - 48;					\
-		p++;										\
-	}												\
-}
-
-
-static VOID memcpy_exl(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len);
-static VOID memcpy_exs(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len);
-static VOID RTMP_IO_READ_BULK(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, UINT32 len);
-
-#ifdef UCOS
-int ate_copy_to_user(
-	IN PUCHAR payload,
-	IN PUCHAR msg,
-	IN INT    len)
-{
-	memmove(payload, msg, len);
-	return 0;
-}
-
-#undef	copy_to_user
-#define copy_to_user(x,y,z) ate_copy_to_user((PUCHAR)x, (PUCHAR)y, z)
-#endif // UCOS //
-
-#define	LEN_OF_ARG 16
-
-VOID RtmpDoAte(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	unsigned short Command_Id;
-	struct ate_racfghdr *pRaCfg;
-	INT	Status = NDIS_STATUS_SUCCESS;
-
-
-
-	if((pRaCfg = kmalloc(sizeof(struct ate_racfghdr), GFP_KERNEL)) == NULL)
-	{
-		Status = -EINVAL;
-		return;
-	}
-
-	NdisZeroMemory(pRaCfg, sizeof(struct ate_racfghdr));
-
-    if (copy_from_user((PUCHAR)pRaCfg, wrq->u.data.pointer, wrq->u.data.length))
-	{
-		Status = -EFAULT;
-		kfree(pRaCfg);
-		return;
-	}
-
-
-	Command_Id = ntohs(pRaCfg->command_id);
-
-	ATEDBGPRINT(RT_DEBUG_TRACE,("\n%s: Command_Id = 0x%04x !\n", __func__, Command_Id));
-
-	switch (Command_Id)
-	{
- 		// We will get this command when QA starts.
-		case RACFG_CMD_ATE_START:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START\n"));
-
-				// prepare feedback as soon as we can to avoid QA timeout.
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_TRACE, ("copy_to_user() fail in case RACFG_CMD_ATE_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START is done !\n"));
-				}
-				Set_ATE_Proc(pAdapter, "ATESTART");
-			}
-			break;
-
- 		// We will get this command either QA is closed or ated is killed by user.
-		case RACFG_CMD_ATE_STOP:
-			{
-#ifndef UCOS
-				INT32 ret;
-#endif // !UCOS //
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_STOP\n"));
-
-				// Distinguish this command came from QA(via ated)
-				// or ate daemon according to the existence of pid in payload.
-				// No need to prepare feedback if this cmd came directly from ate daemon.
-				pRaCfg->length = ntohs(pRaCfg->length);
-
-				if (pRaCfg->length == sizeof(pAdapter->ate.AtePid))
-				{
-					// This command came from QA.
-					// Get the pid of ATE daemon.
-					memcpy((UCHAR *)&pAdapter->ate.AtePid,
-						(&pRaCfg->data[0]) - 2/* == &(pRaCfg->status) */,
-						sizeof(pAdapter->ate.AtePid));
-
-					// prepare feedback as soon as we can to avoid QA timeout.
-					pRaCfg->length = htons(2);
-					pRaCfg->status = htons(0);
-
-					wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-										+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-										+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-	            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-	            	{
-	            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_STOP\n"));
-	                    Status = -EFAULT;
-	            	}
-
-					//
-					// kill ATE daemon when leaving ATE mode.
-					// We must kill ATE daemon first before setting ATESTOP,
-					// or Microsoft will report sth. wrong.
-#ifndef UCOS
-					ret = KILL_THREAD_PID(pAdapter->ate.AtePid, SIGTERM, 1);
-					if (ret)
-					{
-						ATEDBGPRINT(RT_DEBUG_ERROR, ("%s: unable to signal thread\n", pAdapter->net_dev->name));
-					}
-#endif // !UCOS //
-				}
-
-				// AP might have in ATE_STOP mode due to cmd from QA.
-				if (ATE_ON(pAdapter))
-				{
-					// Someone has killed ate daemon while QA GUI is still open.
-					Set_ATE_Proc(pAdapter, "ATESTOP");
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_AP_START is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_RF_WRITE_ALL:
-			{
-				UINT32 R1, R2, R3, R4;
-				USHORT channel;
-
-				memcpy(&R1, pRaCfg->data-2, 4);
-				memcpy(&R2, pRaCfg->data+2, 4);
-				memcpy(&R3, pRaCfg->data+6, 4);
-				memcpy(&R4, pRaCfg->data+10, 4);
-				memcpy(&channel, pRaCfg->data+14, 2);
-
-				pAdapter->LatchRfRegs.R1 = ntohl(R1);
-				pAdapter->LatchRfRegs.R2 = ntohl(R2);
-				pAdapter->LatchRfRegs.R3 = ntohl(R3);
-				pAdapter->LatchRfRegs.R4 = ntohl(R4);
-				pAdapter->LatchRfRegs.Channel = ntohs(channel);
-
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R1);
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R2);
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R3);
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R4);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RF_WRITE_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RF_WRITE_ALL is done !\n"));
-				}
-			}
-            break;
-
-		case RACFG_CMD_E2PROM_READ16:
-			{
-				USHORT	offset, value, tmp;
-
-				offset = ntohs(pRaCfg->status);
-				/* "tmp" is expecially for some compilers... */
-				RT28xx_EEPROM_READ16(pAdapter, offset, tmp);
-				value = tmp;
-				value = htons(value);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("EEPROM Read offset = 0x%04x, value = 0x%04x\n", offset, value));
-
-				// prepare feedback
-				pRaCfg->length = htons(4);
-				pRaCfg->status = htons(0);
-				memcpy(pRaCfg->data, &value, 2);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("sizeof(struct ate_racfghdr) = %d\n", sizeof(struct ate_racfghdr)));
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_READ16\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_E2PROM_READ16 is done !\n"));
-				}
-           	}
-			break;
-
-		case RACFG_CMD_E2PROM_WRITE16:
-			{
-				USHORT	offset, value;
-
-				offset = ntohs(pRaCfg->status);
-				memcpy(&value, pRaCfg->data, 2);
-				value = ntohs(value);
-				RT28xx_EEPROM_WRITE16(pAdapter, offset, value);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_WRITE16\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_E2PROM_WRITE16 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_E2PROM_READ_ALL:
-			{
-				USHORT buffer[EEPROM_SIZE/2];
-
-				rt_ee_read_all(pAdapter,(USHORT *)buffer);
-				memcpy_exs(pAdapter, pRaCfg->data, (UCHAR *)buffer, EEPROM_SIZE);
-
-				// prepare feedback
-				pRaCfg->length = htons(2+EEPROM_SIZE);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_READ_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_E2PROM_READ_ALL is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_E2PROM_WRITE_ALL:
-			{
-				USHORT buffer[EEPROM_SIZE/2];
-
-				NdisZeroMemory((UCHAR *)buffer, EEPROM_SIZE);
-				memcpy_exs(pAdapter, (UCHAR *)buffer, (UCHAR *)&pRaCfg->status, EEPROM_SIZE);
-				rt_ee_write_all(pAdapter,(USHORT *)buffer);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_WRITE_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_ERROR, ("RACFG_CMD_E2PROM_WRITE_ALL is done !\n"));
-				}
-
-			}
-			break;
-
-		case RACFG_CMD_IO_READ:
-			{
-				UINT32	offset;
-				UINT32	value;
-
-				memcpy(&offset, &pRaCfg->status, 4);
-				offset = ntohl(offset);
-
-				// We do not need the base address.
-				// So just extract the offset out.
-				offset &= 0x0000FFFF;
-				RTMP_IO_READ32(pAdapter, offset, &value);
-				value = htonl(value);
-
-				// prepare feedback
-				pRaCfg->length = htons(6);
-				pRaCfg->status = htons(0);
-				memcpy(pRaCfg->data, &value, 4);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_IO_READ\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_IO_READ is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_IO_WRITE:
-			{
-				UINT32	offset, value;
-
-				memcpy(&offset, pRaCfg->data-2, 4);
-				memcpy(&value, pRaCfg->data+2, 4);
-
-				offset = ntohl(offset);
-
-				// We do not need the base address.
-				// So just extract out the offset.
-				offset &= 0x0000FFFF;
-				value = ntohl(value);
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_IO_WRITE: offset = %x, value = %x\n", offset, value));
-				RTMP_IO_WRITE32(pAdapter, offset, value);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_IO_WRITE\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_IO_WRITE is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_IO_READ_BULK:
-			{
-				UINT32	offset;
-				USHORT	len;
-
-				memcpy(&offset, &pRaCfg->status, 4);
-				offset = ntohl(offset);
-
-				// We do not need the base address.
-				// So just extract the offset.
-				offset &= 0x0000FFFF;
-				memcpy(&len, pRaCfg->data+2, 2);
-				len = ntohs(len);
-
-				if (len > 371)
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE,("len is too large, make it smaller\n"));
-					pRaCfg->length = htons(2);
-					pRaCfg->status = htons(1);
-					break;
-				}
-
-				RTMP_IO_READ_BULK(pAdapter, pRaCfg->data, (UCHAR *)offset, len*4);// unit in four bytes
-
-				// prepare feedback
-				pRaCfg->length = htons(2+len*4);// unit in four bytes
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_IO_READ_BULK\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_IO_READ_BULK is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_BBP_READ8:
-			{
-				USHORT	offset;
-				UCHAR	value;
-
-				value = 0;
-				offset = ntohs(pRaCfg->status);
-
-				if (ATE_ON(pAdapter))
-				{
-					ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, offset,  &value);
-				}
-				else
-				{
-					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, offset,  &value);
-				}
-				// prepare feedback
-				pRaCfg->length = htons(3);
-				pRaCfg->status = htons(0);
-				pRaCfg->data[0] = value;
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("BBP value = %x\n", value));
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_BBP_READ8\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_BBP_READ8 is done !\n"));
-				}
-			}
-			break;
-		case RACFG_CMD_BBP_WRITE8:
-			{
-				USHORT	offset;
-				UCHAR	value;
-
-				offset = ntohs(pRaCfg->status);
-				memcpy(&value, pRaCfg->data, 1);
-
-				if (ATE_ON(pAdapter))
-				{
-					ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, offset,  value);
-				}
-				else
-				{
-					RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, offset,  value);
-				}
-
-				if ((offset == BBP_R1) || (offset == BBP_R3))
-				{
-					SyncTxRxConfig(pAdapter, offset, value);
-				}
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_BBP_WRITE8\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_BBP_WRITE8 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_BBP_READ_ALL:
-			{
-				USHORT j;
-
-				for (j = 0; j < 137; j++)
-				{
-					pRaCfg->data[j] = 0;
-
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j]);
-					}
-					else
-					{
-						RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j]);
-					}
-				}
-
-				// prepare feedback
-				pRaCfg->length = htons(2+137);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_BBP_READ_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_BBP_READ_ALL is done !\n"));
-				}
-			}
-
-			break;
-
-		case RACFG_CMD_ATE_E2PROM_READ_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT buffer[EEPROM_SIZE/2];
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			rt_ee_read_all(pAdapter,(USHORT *)buffer);
-			if (offset + len <= EEPROM_SIZE)
-				memcpy_exs(pAdapter, pRaCfg->data, (UCHAR *)buffer+offset, len);
-			else
-				ATEDBGPRINT(RT_DEBUG_ERROR, ("exceed EEPROM size\n"));
-
-			// prepare feedback
-			pRaCfg->length = htons(2+len);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_E2PROM_READ_BULK\n"));
-                Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_E2PROM_READ_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_E2PROM_WRITE_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT buffer[EEPROM_SIZE/2];
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			rt_ee_read_all(pAdapter,(USHORT *)buffer);
-			memcpy_exs(pAdapter, (UCHAR *)buffer + offset, (UCHAR *)pRaCfg->data + 2, len);
-			rt_ee_write_all(pAdapter,(USHORT *)buffer);
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_E2PROM_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_ERROR, ("RACFG_CMD_ATE_E2PROM_WRITE_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_IO_WRITE_BULK:
-		{
-			UINT32 offset, i, value;
-			USHORT len;
-
-			memcpy(&offset, &pRaCfg->status, 4);
-			offset = ntohl(offset);
-			memcpy(&len, pRaCfg->data+2, 2);
-			len = ntohs(len);
-
-			for (i = 0; i < len; i += 4)
-			{
-				memcpy_exl(pAdapter, (UCHAR *)&value, pRaCfg->data+4+i, 4);
-				printk("Write %x %x\n", offset + i, value);
-				RTMP_IO_WRITE32(pAdapter, (offset +i) & 0xffff, value);
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_IO_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_ERROR, ("RACFG_CMD_ATE_IO_WRITE_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_BBP_READ_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				pRaCfg->data[j - offset] = 0;
-
-				if (pAdapter->ate.Mode == ATE_STOP)
-				{
-					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j - offset]);
-				}
-				else
-				{
-					ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j - offset]);
-				}
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2+len);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_BBP_READ_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_BBP_READ_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_BBP_WRITE_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-			UCHAR *value;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				value = pRaCfg->data + 2 + (j - offset);
-				if (pAdapter->ate.Mode == ATE_STOP)
-				{
-					RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, j,  *value);
-				}
-				else
-				{
-					ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, j,  *value);
-				}
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_BBP_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_BBP_WRITE_BULK is done !\n"));
-			}
-		}
-			break;
-
-#ifdef CONFIG_RALINK_RT3052
-		case RACFG_CMD_ATE_RF_READ_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				pRaCfg->data[j - offset] = 0;
-				RT30xxReadRFRegister(pAdapter, j,  &pRaCfg->data[j - offset]);
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2+len);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_RF_READ_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_RF_READ_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_RF_WRITE_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-			UCHAR *value;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				value = pRaCfg->data + 2 + (j - offset);
-				RT30xxWriteRFRegister(pAdapter, j,  *value);
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_RF_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_RF_WRITE_BULK is done !\n"));
-			}
-
-		}
-			break;
-#endif
-
-
-		case RACFG_CMD_GET_NOISE_LEVEL:
-			{
-				UCHAR	channel;
-				INT32   buffer[3][10];/* 3 : RxPath ; 10 : no. of per rssi samples */
-
-				channel = (ntohs(pRaCfg->status) & 0x00FF);
-				CalNoiseLevel(pAdapter, channel, buffer);
-				memcpy_exl(pAdapter, (UCHAR *)pRaCfg->data, (UCHAR *)&(buffer[0][0]), (sizeof(INT32)*3*10));
-
-				// prepare feedback
-				pRaCfg->length = htons(2 + (sizeof(INT32)*3*10));
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_GET_NOISE_LEVEL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_GET_NOISE_LEVEL is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_GET_COUNTER:
-			{
-				memcpy_exl(pAdapter, &pRaCfg->data[0], (UCHAR *)&pAdapter->ate.U2M, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[4], (UCHAR *)&pAdapter->ate.OtherData, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[8], (UCHAR *)&pAdapter->ate.Beacon, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[12], (UCHAR *)&pAdapter->ate.OtherCount, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[16], (UCHAR *)&pAdapter->ate.TxAc0, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[20], (UCHAR *)&pAdapter->ate.TxAc1, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[24], (UCHAR *)&pAdapter->ate.TxAc2, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[28], (UCHAR *)&pAdapter->ate.TxAc3, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[32], (UCHAR *)&pAdapter->ate.TxHCCA, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[36], (UCHAR *)&pAdapter->ate.TxMgmt, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&pAdapter->ate.RSSI0, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[44], (UCHAR *)&pAdapter->ate.RSSI1, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[48], (UCHAR *)&pAdapter->ate.RSSI2, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[52], (UCHAR *)&pAdapter->ate.SNR0, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[56], (UCHAR *)&pAdapter->ate.SNR1, 4);
-
-				pRaCfg->length = htons(2+60);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_GET_COUNTER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_GET_COUNTER is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_CLEAR_COUNTER:
-			{
-				pAdapter->ate.U2M = 0;
-				pAdapter->ate.OtherData = 0;
-				pAdapter->ate.Beacon = 0;
-				pAdapter->ate.OtherCount = 0;
-				pAdapter->ate.TxAc0 = 0;
-				pAdapter->ate.TxAc1 = 0;
-				pAdapter->ate.TxAc2 = 0;
-				pAdapter->ate.TxAc3 = 0;
-				pAdapter->ate.TxHCCA = 0;
-				pAdapter->ate.TxMgmt = 0;
-				pAdapter->ate.TxDoneCount = 0;
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_CLEAR_COUNTER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_CLEAR_COUNTER is done !\n"));
-				}
-			}
-
-			break;
-
-		case RACFG_CMD_TX_START:
-			{
-				USHORT *p;
-				USHORT	err = 1;
-				UCHAR   Bbp22Value = 0, Bbp24Value = 0;
-
-				if ((pAdapter->ate.TxStatus != 0) && (pAdapter->ate.Mode & ATE_TXFRAME))
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE,("Ate Tx is already running, to run next Tx, you must stop it first\n"));
-					err = 2;
-					goto TX_START_ERROR;
-				}
-				else if ((pAdapter->ate.TxStatus != 0) && !(pAdapter->ate.Mode & ATE_TXFRAME))
-				{
-					int i = 0;
-
-					while ((i++ < 10) && (pAdapter->ate.TxStatus != 0))
-					{
-						RTMPusecDelay(5000);
-					}
-
-					// force it to stop
-					pAdapter->ate.TxStatus = 0;
-					pAdapter->ate.TxDoneCount = 0;
-					//pAdapter->ate.Repeat = 0;
-					pAdapter->ate.bQATxStart = FALSE;
-				}
-
-				// If pRaCfg->length == 0, this "RACFG_CMD_TX_START" is for Carrier test or Carrier Suppression.
-				if (ntohs(pRaCfg->length) != 0)
-				{
-					// Get frame info
-#ifdef RT2870
-					NdisMoveMemory(&pAdapter->ate.TxInfo, pRaCfg->data - 2, 4);
-#ifdef RT_BIG_ENDIAN
-					RTMPDescriptorEndianChange((PUCHAR) &pAdapter->ate.TxInfo, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-#endif // RT2870 //
-
-					NdisMoveMemory(&pAdapter->ate.TxWI, pRaCfg->data + 2, 16);
-#ifdef RT_BIG_ENDIAN
-					RTMPWIEndianChange((PUCHAR)&pAdapter->ate.TxWI, TYPE_TXWI);
-#endif // RT_BIG_ENDIAN //
-
-					NdisMoveMemory(&pAdapter->ate.TxCount, pRaCfg->data + 18, 4);
-					pAdapter->ate.TxCount = ntohl(pAdapter->ate.TxCount);
-
-					p = (USHORT *)(&pRaCfg->data[22]);
-					//p = pRaCfg->data + 22;
-					// always use QID_AC_BE
-					pAdapter->ate.QID = 0;
-					p = (USHORT *)(&pRaCfg->data[24]);
-					//p = pRaCfg->data + 24;
-					pAdapter->ate.HLen = ntohs(*p);
-
-					if (pAdapter->ate.HLen > 32)
-					{
-						ATEDBGPRINT(RT_DEBUG_ERROR,("pAdapter->ate.HLen > 32\n"));
-						err = 3;
-						goto TX_START_ERROR;
-					}
-
-					NdisMoveMemory(&pAdapter->ate.Header, pRaCfg->data + 26, pAdapter->ate.HLen);
-
-
-					pAdapter->ate.PLen = ntohs(pRaCfg->length) - (pAdapter->ate.HLen + 28);
-
-					if (pAdapter->ate.PLen > 32)
-					{
-						ATEDBGPRINT(RT_DEBUG_ERROR,("pAdapter->ate.PLen > 32\n"));
-						err = 4;
-						goto TX_START_ERROR;
-					}
-
-					NdisMoveMemory(&pAdapter->ate.Pattern, pRaCfg->data + 26 + pAdapter->ate.HLen, pAdapter->ate.PLen);
-					pAdapter->ate.DLen = pAdapter->ate.TxWI.MPDUtotalByteCount - pAdapter->ate.HLen;
-				}
-
-				ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R22, &Bbp22Value);
-
-				switch (Bbp22Value)
-				{
-					case BBP22_TXFRAME:
-						{
-							if (pAdapter->ate.TxCount == 0)
-							{
-							}
-							ATEDBGPRINT(RT_DEBUG_TRACE,("START TXFRAME\n"));
-							pAdapter->ate.bQATxStart = TRUE;
-							Set_ATE_Proc(pAdapter, "TXFRAME");
-						}
-						break;
-
-					case BBP22_TXCONT_OR_CARRSUPP:
-						{
-							ATEDBGPRINT(RT_DEBUG_TRACE,("BBP22_TXCONT_OR_CARRSUPP\n"));
-							ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, 24, &Bbp24Value);
-
-							switch (Bbp24Value)
-							{
-								case BBP24_TXCONT:
-									{
-										ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCONT\n"));
-										pAdapter->ate.bQATxStart = TRUE;
-										Set_ATE_Proc(pAdapter, "TXCONT");
-									}
-									break;
-
-								case BBP24_CARRSUPP:
-									{
-										ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCARRSUPP\n"));
-										pAdapter->ate.bQATxStart = TRUE;
-										pAdapter->ate.Mode |= ATE_TXCARRSUPP;
-									}
-									break;
-
-								default:
-									{
-										ATEDBGPRINT(RT_DEBUG_ERROR,("Unknown Start TX subtype !"));
-									}
-									break;
-							}
-						}
-						break;
-
-					case BBP22_TXCARR:
-						{
-							ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCARR\n"));
-							pAdapter->ate.bQATxStart = TRUE;
-							Set_ATE_Proc(pAdapter, "TXCARR");
-						}
-						break;
-
-					default:
-						{
-							ATEDBGPRINT(RT_DEBUG_ERROR,("Unknown Start TX subtype !"));
-						}
-						break;
-				}
-
-				if (pAdapter->ate.bQATxStart == TRUE)
-				{
-					// prepare feedback
-					pRaCfg->length = htons(2);
-					pRaCfg->status = htons(0);
-
-					wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-										+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-										+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-	            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-	            	{
-	            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() was failed in case RACFG_CMD_TX_START\n"));
-	                    Status = -EFAULT;
-	            	}
-					else
-					{
-	                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_TX_START is done !\n"));
-					}
-					break;
-				}
-
-TX_START_ERROR:
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(err);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_TX_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("feedback of TX_START_ERROR is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_GET_TX_STATUS:
-			{
-				UINT32 count;
-
-				// prepare feedback
-				pRaCfg->length = htons(6);
-				pRaCfg->status = htons(0);
-				count = htonl(pAdapter->ate.TxDoneCount);
-				NdisMoveMemory(pRaCfg->data, &count, 4);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_GET_TX_STATUS\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_GET_TX_STATUS is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_TX_STOP:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_TX_STOP\n"));
-
-				Set_ATE_Proc(pAdapter, "TXSTOP");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_TRACE, ("copy_to_user() fail in case RACFG_CMD_TX_STOP\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_TX_STOP is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_RX_START:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_START\n"));
-
-				pAdapter->ate.bQARxStart = TRUE;
-				Set_ATE_Proc(pAdapter, "RXFRAME");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RX_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RX_START is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_RX_STOP:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_STOP\n"));
-
-				Set_ATE_Proc(pAdapter, "RXSTOP");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RX_STOP\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RX_STOP is done !\n"));
-				}
-			}
-			break;
-
-		/* The following cases are for new ATE GUI(not QA). */
-		/*==================================================*/
-		case RACFG_CMD_ATE_START_TX_CARRIER:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_CARRIER\n"));
-
-				Set_ATE_Proc(pAdapter, "TXCARR");
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_START_TX_CARRIER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START_TX_CARRIER is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_START_TX_CONT:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_CONT\n"));
-
-				Set_ATE_Proc(pAdapter, "TXCONT");
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_START_TX_CONT\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START_TX_CONT is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_START_TX_FRAME:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_FRAME\n"));
-
-				Set_ATE_Proc(pAdapter, "TXFRAME");
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_START_TX_FRAME\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START_TX_FRAME is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_BW:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_BW\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-
-				Set_ATE_TX_BW_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_BW\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_BW is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_POWER0:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_POWER0\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_POWER0_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_POWER0\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_POWER0 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_POWER1:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_POWER1\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_POWER1_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_POWER1\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_POWER1 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_FREQ_OFFSET:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_FREQ_OFFSET\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_FREQOFFSET_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_FREQ_OFFSET\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_FREQ_OFFSET is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_GET_STATISTICS:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_GET_STATISTICS\n"));
-
-				memcpy_exl(pAdapter, &pRaCfg->data[0], (UCHAR *)&pAdapter->ate.TxDoneCount, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[4], (UCHAR *)&pAdapter->WlanCounters.RetryCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[8], (UCHAR *)&pAdapter->WlanCounters.FailedCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[12], (UCHAR *)&pAdapter->WlanCounters.RTSSuccessCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[16], (UCHAR *)&pAdapter->WlanCounters.RTSFailureCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[20], (UCHAR *)&pAdapter->WlanCounters.ReceivedFragmentCount.QuadPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[24], (UCHAR *)&pAdapter->WlanCounters.FCSErrorCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[28], (UCHAR *)&pAdapter->Counters8023.RxNoBuffer, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[32], (UCHAR *)&pAdapter->WlanCounters.FrameDuplicateCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[36], (UCHAR *)&pAdapter->RalinkCounters.OneSecFalseCCACnt, 4);
-
-				if (pAdapter->ate.RxAntennaSel == 0)
-				{
-					INT32 RSSI0 = 0;
-					INT32 RSSI1 = 0;
-					INT32 RSSI2 = 0;
-
-					RSSI0 = (INT32)(pAdapter->ate.LastRssi0 - pAdapter->BbpRssiToDbmDelta);
-					RSSI1 = (INT32)(pAdapter->ate.LastRssi1 - pAdapter->BbpRssiToDbmDelta);
-					RSSI2 = (INT32)(pAdapter->ate.LastRssi2 - pAdapter->BbpRssiToDbmDelta);
-					memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&RSSI0, 4);
-					memcpy_exl(pAdapter, &pRaCfg->data[44], (UCHAR *)&RSSI1, 4);
-					memcpy_exl(pAdapter, &pRaCfg->data[48], (UCHAR *)&RSSI2, 4);
-					pRaCfg->length = htons(2+52);
-				}
-				else
-				{
-					INT32 RSSI0 = 0;
-
-					RSSI0 = (INT32)(pAdapter->ate.LastRssi0 - pAdapter->BbpRssiToDbmDelta);
-					memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&RSSI0, 4);
-					pRaCfg->length = htons(2+44);
-				}
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_GET_STATISTICS\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_GET_STATISTICS is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_RESET_COUNTER:
-			{
-				SHORT    value = 1;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_RESET_COUNTER\n"));
-
-				sprintf((PCHAR)str, "%d", value);
-				Set_ResetStatCounter_Proc(pAdapter, str);
-
-				pAdapter->ate.TxDoneCount = 0;
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_RESET_COUNTER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_RESET_COUNTER is done !\n"));
-				}
-			}
-
-			break;
-
-		case RACFG_CMD_ATE_SEL_TX_ANTENNA:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SEL_TX_ANTENNA\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_Antenna_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SEL_TX_ANTENNA\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SEL_TX_ANTENNA is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SEL_RX_ANTENNA:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SEL_RX_ANTENNA\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_RX_Antenna_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SEL_RX_ANTENNA\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SEL_RX_ANTENNA is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_PREAMBLE:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_PREAMBLE\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_MODE_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_PREAMBLE\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_PREAMBLE is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_CHANNEL:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_CHANNEL\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_CHANNEL_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_CHANNEL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_CHANNEL is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_ADDR1:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR1\n"));
-
-				// Addr is an array of UCHAR,
-				// so no need to perform endian swap.
-				memcpy(pAdapter->ate.Addr1, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_ADDR1\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_ADDR1 is done !\n (ADDR1 = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAdapter->ate.Addr1[0],
-						pAdapter->ate.Addr1[1], pAdapter->ate.Addr1[2], pAdapter->ate.Addr1[3], pAdapter->ate.Addr1[4], pAdapter->ate.Addr1[5]));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_ADDR2:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR2\n"));
-
-				// Addr is an array of UCHAR,
-				// so no need to perform endian swap.
-				memcpy(pAdapter->ate.Addr2, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_ADDR2\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_ADDR2 is done !\n (ADDR2 = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAdapter->ate.Addr2[0],
-						pAdapter->ate.Addr2[1], pAdapter->ate.Addr2[2], pAdapter->ate.Addr2[3], pAdapter->ate.Addr2[4], pAdapter->ate.Addr2[5]));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_ADDR3:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR3\n"));
-
-				// Addr is an array of UCHAR,
-				// so no need to perform endian swap.
-				memcpy(pAdapter->ate.Addr3, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_ADDR3\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_ADDR3 is done !\n (ADDR3 = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAdapter->ate.Addr3[0],
-						pAdapter->ate.Addr3[1], pAdapter->ate.Addr3[2], pAdapter->ate.Addr3[3], pAdapter->ate.Addr3[4], pAdapter->ate.Addr3[5]));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_RATE:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_RATE\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_MCS_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_RATE\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_RATE is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_FRAME_LEN:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_FRAME_LEN\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_LENGTH_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_FRAME_LEN\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_FRAME_LEN is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_FRAME_COUNT:
-			{
-				USHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_FRAME_COUNT\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				{
-					sprintf((PCHAR)str, "%d", value);
-					Set_ATE_TX_COUNT_Proc(pAdapter, str);
-				}
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_FRAME_COUNT\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_FRAME_COUNT is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_START_RX_FRAME:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_START\n"));
-
-				Set_ATE_Proc(pAdapter, "RXFRAME");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RX_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RX_START is done !\n"));
-				}
-			}
-			break;
-		default:
-			break;
-	}
-    ASSERT(pRaCfg != NULL);
-    if (pRaCfg != NULL)
-    {
-    kfree(pRaCfg);
-    }
-	return;
-}
-
-VOID BubbleSort(INT32 n, INT32 a[])
-{
-	INT32 k, j, temp;
-
-	for (k = n-1;  k>0;  k--)
-	{
-		for (j = 0; j<k; j++)
-		{
-			if(a[j] > a[j+1])
-			{
-				temp = a[j];
-				a[j]=a[j+1];
-				a[j+1]=temp;
-			}
-		}
-	}
-}
-
-VOID CalNoiseLevel(PRTMP_ADAPTER pAd, UCHAR channel, INT32 RSSI[3][10])
-{
-	INT32		RSSI0, RSSI1, RSSI2;
- 	CHAR		Rssi0Offset, Rssi1Offset, Rssi2Offset;
-	UCHAR		BbpR50Rssi0 = 0, BbpR51Rssi1 = 0, BbpR52Rssi2 = 0;
-	UCHAR		Org_BBP66value = 0, Org_BBP69value = 0, Org_BBP70value = 0, data = 0;
-	USHORT		LNA_Gain = 0;
-	INT32       j = 0;
-	UCHAR		Org_Channel = pAd->ate.Channel;
-	USHORT	    GainValue = 0, OffsetValue = 0;
-
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &Org_BBP66value);
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R69, &Org_BBP69value);
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R70, &Org_BBP70value);
-
-	//**********************************************************************
-	// Read the value of LNA gain and Rssi offset
-	//**********************************************************************
-	RT28xx_EEPROM_READ16(pAd, EEPROM_LNA_OFFSET, GainValue);
-
-	// for Noise Level
-	if (channel <= 14)
-	{
-		LNA_Gain = GainValue & 0x00FF;
-
-		RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_BG_OFFSET, OffsetValue);
-		Rssi0Offset = OffsetValue & 0x00FF;
-		Rssi1Offset = (OffsetValue & 0xFF00) >> 8;
-		RT28xx_EEPROM_READ16(pAd, (EEPROM_RSSI_BG_OFFSET + 2)/* 0x48 */, OffsetValue);
-		Rssi2Offset = OffsetValue & 0x00FF;
-	}
-	else
-	{
-		LNA_Gain = (GainValue & 0xFF00) >> 8;
-
-		RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_A_OFFSET, OffsetValue);
-		Rssi0Offset = OffsetValue & 0x00FF;
-		Rssi1Offset = (OffsetValue & 0xFF00) >> 8;
-		RT28xx_EEPROM_READ16(pAd, (EEPROM_RSSI_A_OFFSET + 2)/* 0x4C */, OffsetValue);
-		Rssi2Offset = OffsetValue & 0x00FF;
-	}
-	//**********************************************************************
-	{
-		pAd->ate.Channel = channel;
-		ATEAsicSwitchChannel(pAd);
-		mdelay(5);
-
-		data = 0x10;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, data);
-		data = 0x40;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, data);
-		data = 0x40;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, data);
-		mdelay(5);
-
-		// Start Rx
-		pAd->ate.bQARxStart = TRUE;
-		Set_ATE_Proc(pAd, "RXFRAME");
-
-		mdelay(5);
-
-		for (j = 0; j < 10; j++)
-		{
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R50, &BbpR50Rssi0);
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R51, &BbpR51Rssi1);
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R52, &BbpR52Rssi2);
-
-			mdelay(10);
-
-			// Calculate RSSI 0
-			if (BbpR50Rssi0 == 0)
-			{
-				RSSI0 = -100;
-			}
-			else
-			{
-				RSSI0 = (INT32)(-12 - BbpR50Rssi0 - LNA_Gain - Rssi0Offset);
-			}
-			RSSI[0][j] = RSSI0;
-
-			if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
-			{
-				// Calculate RSSI 1
-				if (BbpR51Rssi1 == 0)
-				{
-					RSSI1 = -100;
-				}
-				else
-				{
-					RSSI1 = (INT32)(-12 - BbpR51Rssi1 - LNA_Gain - Rssi1Offset);
-				}
-				RSSI[1][j] = RSSI1;
-			}
-
-			if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
-			{
-				// Calculate RSSI 2
-				if (BbpR52Rssi2 == 0)
-					RSSI2 = -100;
-				else
-					RSSI2 = (INT32)(-12 - BbpR52Rssi2 - LNA_Gain - Rssi2Offset);
-
-				RSSI[2][j] = RSSI2;
-			}
-		}
-
-		// Stop Rx
-		Set_ATE_Proc(pAd, "RXSTOP");
-
-		mdelay(5);
-
-#if 0// Debug Message................
-		ate_print("\n**********************************************************\n");
-		ate_print("Noise Level: Channel %d\n", channel);
-		ate_print("RSSI0 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-			RSSI[0][0], RSSI[0][1], RSSI[0][2],
-			RSSI[0][3], RSSI[0][4], RSSI[0][5],
-			RSSI[0][6], RSSI[0][7], RSSI[0][8],
-			RSSI[0][9]);
-		if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
-		{
-			ate_print("RSSI1 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-				RSSI[1][0], RSSI[1][1], RSSI[1][2],
-				RSSI[1][3], RSSI[1][4], RSSI[1][5],
-				RSSI[1][6], RSSI[1][7], RSSI[1][8],
-				RSSI[1][9]);
-		}
-		if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
-		{
-			ate_print("RSSI2 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-				RSSI[2][0], RSSI[2][1], RSSI[2][2],
-				RSSI[2][3], RSSI[2][4], RSSI[2][5],
-				RSSI[2][6], RSSI[2][7], RSSI[2][8],
-				RSSI[2][9]);
-		}
-#endif // 0 //
-		BubbleSort(10, RSSI[0]);	// 1R
-
-		if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
-		{
-			BubbleSort(10, RSSI[1]);
-		}
-
-		if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
-		{
-			BubbleSort(10, RSSI[2]);
-		}
-
-#if 0// Debug Message................
-		ate_print("\nAfter Sorting....Channel %d\n", channel);
-		ate_print("RSSI0 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-			RSSI[0][0], RSSI[0][1], RSSI[0][2],
-			RSSI[0][3], RSSI[0][4], RSSI[0][5],
-			RSSI[0][6], RSSI[0][7], RSSI[0][8],
-			RSSI[0][9]);
-		if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
-		{
-			ate_print("RSSI1 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-				RSSI[1][0], RSSI[1][1], RSSI[1][2],
-				RSSI[1][3], RSSI[1][4], RSSI[1][5],
-				RSSI[1][6], RSSI[1][7], RSSI[1][8],
-				RSSI[1][9]);
-		}
-		if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
-		{
-			ate_print("RSSI2 = %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
-				RSSI[2][0], RSSI[2][1], RSSI[2][2],
-				RSSI[2][3], RSSI[2][4], RSSI[2][5],
-				RSSI[2][6], RSSI[2][7], RSSI[2][8],
-				RSSI[2][9]);
-		}
-		ate_print("**********************************************************\n");
-#endif // 0 //
-	}
-
-	pAd->ate.Channel = Org_Channel;
-	ATEAsicSwitchChannel(pAd);
-
-	// Restore original value
-    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, Org_BBP66value);
-    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, Org_BBP69value);
-    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, Org_BBP70value);
-
-	return;
-}
-
-BOOLEAN SyncTxRxConfig(PRTMP_ADAPTER pAd, USHORT offset, UCHAR value)
-{
-	UCHAR tmp = 0, bbp_data = 0;
-
-	if (ATE_ON(pAd))
-	{
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, offset, &bbp_data);
-	}
-	else
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, offset, &bbp_data);
-	}
-
-	/* confirm again */
-	ASSERT(bbp_data == value);
-
-	switch(offset)
-	{
-		case BBP_R1:
-			/* Need to sync. tx configuration with legacy ATE. */
-			tmp = (bbp_data & ((1 << 4) | (1 << 3))/* 0x18 */) >> 3;
-		    switch(tmp)
-		    {
-				/* The BBP R1 bit[4:3] = 2 :: Both DACs will be used by QA. */
-		        case 2:
-					/* All */
-					pAd->ate.TxAntennaSel = 0;
-		            break;
-				/* The BBP R1 bit[4:3] = 0 :: DAC 0 will be used by QA. */
-		        case 0:
-					/* Antenna one */
-					pAd->ate.TxAntennaSel = 1;
-		            break;
-				/* The BBP R1 bit[4:3] = 1 :: DAC 1 will be used by QA. */
-		        case 1:
-					/* Antenna two */
-					pAd->ate.TxAntennaSel = 2;
-		            break;
-		        default:
-		            DBGPRINT(RT_DEBUG_TRACE, ("%s -- Sth. wrong!  : return FALSE; \n", __func__));
-		            return FALSE;
-		    }
-			break;/* case BBP_R1 */
-
-		case BBP_R3:
-			/* Need to sync. rx configuration with legacy ATE. */
-			tmp = (bbp_data & ((1 << 1) | (1 << 0))/* 0x03 */);
-		    switch(tmp)
-		    {
-				/* The BBP R3 bit[1:0] = 3 :: All ADCs will be used by QA. */
-		        case 3:
-					/* All */
-					pAd->ate.RxAntennaSel = 0;
-		            break;
-				/* The BBP R3 bit[1:0] = 0 :: ADC 0 will be used by QA, */
-				/* unless the BBP R3 bit[4:3] = 2 */
-		        case 0:
-					/* Antenna one */
-					pAd->ate.RxAntennaSel = 1;
-					tmp = ((bbp_data & ((1 << 4) | (1 << 3))/* 0x03 */) >> 3);
-					if (tmp == 2)// 3R
-					{
-						/* Default : All ADCs will be used by QA */
-						pAd->ate.RxAntennaSel = 0;
-					}
-		            break;
-				/* The BBP R3 bit[1:0] = 1 :: ADC 1 will be used by QA. */
-		        case 1:
-					/* Antenna two */
-					pAd->ate.RxAntennaSel = 2;
-		            break;
-				/* The BBP R3 bit[1:0] = 2 :: ADC 2 will be used by QA. */
-		        case 2:
-					/* Antenna three */
-					pAd->ate.RxAntennaSel = 3;
-		            break;
-		        default:
-		            DBGPRINT(RT_DEBUG_ERROR, ("%s -- Impossible!  : return FALSE; \n", __func__));
-		            return FALSE;
-		    }
-			break;/* case BBP_R3 */
-
-        default:
-            DBGPRINT(RT_DEBUG_ERROR, ("%s -- Sth. wrong!  : return FALSE; \n", __func__));
-            return FALSE;
-
-	}
-	return TRUE;
-}
-
-static VOID memcpy_exl(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len)
-{
-	ULONG i, Value = 0;
-	ULONG *pDst, *pSrc;
-	UCHAR *p8;
-
-	p8 = src;
-	pDst = (ULONG *) dst;
-	pSrc = (ULONG *) src;
-
-	for (i = 0 ; i < (len/4); i++)
-	{
-		/* For alignment issue, we need a variable "Value". */
-		memmove(&Value, pSrc, 4);
-		Value = htonl(Value);
-		memmove(pDst, &Value, 4);
-		pDst++;
-		pSrc++;
-	}
-	if ((len % 4) != 0)
-	{
-		/* wish that it will never reach here */
-		memmove(&Value, pSrc, (len % 4));
-		Value = htonl(Value);
-		memmove(pDst, &Value, (len % 4));
-	}
-}
-
-static VOID memcpy_exs(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len)
-{
-	ULONG i;
-	UCHAR *pDst, *pSrc;
-
-	pDst = dst;
-	pSrc = src;
-
-	for (i = 0; i < (len/2); i++)
-	{
-		memmove(pDst, pSrc, 2);
-		*((USHORT *)pDst) = htons(*((USHORT *)pDst));
-		pDst+=2;
-		pSrc+=2;
-	}
-
-	if ((len % 2) != 0)
-	{
-		memmove(pDst, pSrc, 1);
-	}
-}
-
-static VOID RTMP_IO_READ_BULK(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, UINT32 len)
-{
-	UINT32 i, Value;
-	UINT32 *pDst, *pSrc;
-
-	pDst = (UINT32 *) dst;
-	pSrc = (UINT32 *) src;
-
-	for (i = 0 ; i < (len/4); i++)
-	{
-		RTMP_IO_READ32(pAd, (ULONG)pSrc, &Value);
-		Value = htonl(Value);
-		memmove(pDst, &Value, 4);
-		pDst++;
-		pSrc++;
-	}
-	return;
-}
-
-// TODO:
-#if 0
-/* These work only when RALINK_ATE is defined */
-INT Set_TxStart_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG value = simple_strtol(arg, 0, 10);
-	UCHAR buffer[26] = {0x88, 0x02, 0x2c, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x00, 0x55, 0x44, 0x33, 0x22, 0x11, 0xc0, 0x22, 0x00, 0x00};
-	POS_COOKIE pObj;
-
-	if (pAd->ate.TxStatus != 0)
-		return FALSE;
-
-	pAd->ate.TxInfo = 0x04000000;
-	bzero(&pAd->ate.TxWI, sizeof(TXWI_STRUC));
-	pAd->ate.TxWI.PHYMODE = 0;// MODE_CCK
-	pAd->ate.TxWI.MPDUtotalByteCount = 1226;
-	pAd->ate.TxWI.MCS = 3;
-	//pAd->ate.Mode = ATE_START;
-	pAd->ate.Mode |= ATE_TXFRAME;
-	pAd->ate.TxCount = value;
-	pAd->ate.QID = 0;
-	pAd->ate.HLen = 26;
-	pAd->ate.PLen = 0;
-	pAd->ate.DLen = 1200;
-	memcpy(pAd->ate.Header, buffer, 26);
-	pAd->ate.bQATxStart = TRUE;
-	//pObj = (POS_COOKIE) pAd->OS_Cookie;
-	//tasklet_hi_schedule(&pObj->AteTxTask);
-	return TRUE;
-}
-#endif  /* end of #if 0 */
-
-INT Set_TxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ATEDBGPRINT(RT_DEBUG_TRACE,("Set_TxStop_Proc\n"));
-
-	if (Set_ATE_Proc(pAd, "TXSTOP"))
-	{
-	return TRUE;
-}
-	else
-	{
-		return FALSE;
-	}
-}
-
-INT Set_RxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ATEDBGPRINT(RT_DEBUG_TRACE,("Set_RxStop_Proc\n"));
-
-	if (Set_ATE_Proc(pAd, "RXSTOP"))
-	{
-	return TRUE;
-}
-	else
-	{
-		return FALSE;
-	}
-}
-
-#if 0
-INT Set_EEWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	USHORT offset = 0, value;
-	PUCHAR p2 = arg;
-
-	while((*p2 != ':') && (*p2 != '\0'))
-	{
-		p2++;
-	}
-
-	if (*p2 == ':')
-	{
-		A2Hex(offset, arg);
-		A2Hex(value, p2+ 1);
-	}
-	else
-	{
-		A2Hex(value, arg);
-	}
-
-	if (offset >= EEPROM_SIZE)
-	{
-		ate_print("Offset can not exceed EEPROM_SIZE( == 0x%04x)\n", EEPROM_SIZE);
-		return FALSE;
-	}
-
-	RTMP_EEPROM_WRITE16(pAd, offset, value);
-
-	return TRUE;
-}
-
-INT Set_BBPRead_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR value = 0, offset;
-
-	A2Hex(offset, arg);
-
-	if (ATE_ON(pAd))
-	{
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, offset,  &value);
-	}
-	else
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, offset,  &value);
-	}
-
-	ate_print("%x\n", value);
-
-	return TRUE;
-}
-
-
-INT Set_BBPWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	USHORT offset = 0;
-	PUCHAR p2 = arg;
-	UCHAR value;
-
-	while((*p2 != ':') && (*p2 != '\0'))
-	{
-		p2++;
-	}
-
-	if (*p2 == ':')
-	{
-		A2Hex(offset, arg);
-		A2Hex(value, p2+ 1);
-	}
-	else
-	{
-		A2Hex(value, arg);
-	}
-
-	if (ATE_ON(pAd))
-	{
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, offset,  value);
-	}
-	else
-	{
-		RTNP_BBP_IO_WRITE8_BY_REG_ID(pAd, offset,  value);
-	}
-
-	return TRUE;
-}
-
-INT Set_RFWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	PUCHAR p2, p3, p4;
-	ULONG R1, R2, R3, R4;
-
-	p2 = arg;
-
-	while((*p2 != ':') && (*p2 != '\0'))
-	{
-		p2++;
-	}
-
-	if (*p2 != ':')
-		return FALSE;
-
-	p3 = p2 + 1;
-
-	while((*p3 != ':') && (*p3 != '\0'))
-	{
-		p3++;
-	}
-
-	if (*p3 != ':')
-		return FALSE;
-
-	p4 = p3 + 1;
-
-	while((*p4 != ':') && (*p4 != '\0'))
-	{
-		p4++;
-	}
-
-	if (*p4 != ':')
-		return FALSE;
-
-
-	A2Hex(R1, arg);
-	A2Hex(R2, p2 + 1);
-	A2Hex(R3, p3 + 1);
-	A2Hex(R4, p4 + 1);
-
-	RTMP_RF_IO_WRITE32(pAd, R1);
-	RTMP_RF_IO_WRITE32(pAd, R2);
-	RTMP_RF_IO_WRITE32(pAd, R3);
-	RTMP_RF_IO_WRITE32(pAd, R4);
-
-	return TRUE;
-}
-#endif  // end of #if 0 //
-#endif	// RALINK_28xx_QA //
-
-#endif	// RALINK_ATE //
-
diff --git a/drivers/staging/rt2870/rt_ate.h b/drivers/staging/rt2870/rt_ate.h
deleted file mode 100644
index b618ce3..0000000
--- a/drivers/staging/rt2870/rt_ate.h
+++ /dev/null
@@ -1,315 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#ifndef __ATE_H__
-#define __ATE_H__
-
-#ifndef UCOS
-#define ate_print printk
-#define ATEDBGPRINT DBGPRINT
-
-#ifdef RT2870
-#define EEPROM_SIZE								0x400
-#ifdef CONFIG_STA_SUPPORT
-#define EEPROM_BIN_FILE_NAME  "/etc/Wireless/RT2870STA/e2p.bin"
-#endif // CONFIG_STA_SUPPORT //
-#endif // RT2870 //
-#else // !UCOS //
-#define fATE_LOAD_EEPROM						0x0C43
-#ifdef CONFIG_PRINTK
-extern INT ConsoleResponse(IN PUCHAR buff);
-extern int (*remote_display)(char *);
-extern void puts (const char *s);
-
-/* specificly defined to redirect and show ate-related messages to host. */
-/* Try to define ate_print as a macro. */
-#define ate_print(fmt, args...)                 \
-do{   int (*org_remote_display)(char *) = NULL;   \
-	org_remote_display = remote_display;\
-	/* Save original "remote_display" */\
-	remote_display = (int (*)(char *))ConsoleResponse;           \
-	printk(fmt, ## args);                       \
-	/* Restore the remote_display function pointer */        \
-	remote_display = org_remote_display; }while(0)
-
-#define ATEDBGPRINT(Level, Fmt)    	\
-{                                   \
-    if ((Level) <= RTDebugLevel)      \
-    {                               \
-        ate_print Fmt;					\
-    }                               \
-}
-#endif // CONFIG_PRINTK //
-#endif // !UCOS //
-
-#define ATE_ON(_p)              (((_p)->ate.Mode) != ATE_STOP)
-
-/* RT2880_iNIC will define "RT2860". */
-
-/* RT2880_iNIC will define RT2860. */
-
-#ifdef RT2870
-#define EEPROM_SIZE								0x400
-#ifdef CONFIG_STA_SUPPORT
-#define EEPROM_BIN_FILE_NAME  "/etc/Wireless/RT2870STA/e2p.bin"
-#endif // CONFIG_STA_SUPPORT //
-#endif // RT2870 //
-
-#ifdef RT2870
-#define ATE_BBP_IO_READ8_BY_REG_ID(_A, _I, _pV)    RTMP_BBP_IO_READ8_BY_REG_ID(_A, _I, _pV)
-#define ATE_BBP_IO_WRITE8_BY_REG_ID(_A, _I, _V)    RTMP_BBP_IO_WRITE8_BY_REG_ID(_A, _I, _V)
-
-#define BULK_OUT_LOCK(pLock, IrqFlags)	\
-		if(1 /*!(in_interrupt() & 0xffff0000)*/)	\
-			RTMP_IRQ_LOCK((pLock), IrqFlags);
-
-#define BULK_OUT_UNLOCK(pLock, IrqFlags)	\
-		if(1 /*!(in_interrupt() & 0xffff0000)*/)	\
-			RTMP_IRQ_UNLOCK((pLock), IrqFlags);
-
-// Prototypes of completion funuc.
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-#define ATE_RTUSBBulkOutDataPacketComplete(purb, pt_regs)    ATE_RTUSBBulkOutDataPacketComplete(purb)
-#endif
-
-VOID ATE_RTUSBBulkOutDataPacketComplete(
-	IN purbb_t purb,
-	OUT struct pt_regs *pt_regs);
-
-VOID ATE_RTUSBBulkOutDataPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BulkOutPipeId);
-
-VOID ATE_RTUSBCancelPendingBulkInIRP(
-	IN	PRTMP_ADAPTER	pAd);
-#endif // RT2870 //
-
-VOID rt_ee_read_all(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT USHORT *Data);
-
-
-VOID rt_ee_write_all(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  USHORT *Data);
-
-INT Set_ATE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_DA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_SA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_BSSID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_CHANNEL_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_POWER0_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_POWER1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_RX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_FREQOFFSET_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_BW_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_LENGTH_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_COUNT_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_MCS_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_MODE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_GI_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-
-INT	Set_ATE_RX_FER_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Read_RF_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF2_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF3_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF4_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Load_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Read_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_Show_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_Help_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-VOID ATE_QA_Statistics(
-	IN PRTMP_ADAPTER		pAd,
-	IN PRXWI_STRUC			pRxWI,
-	IN PRT28XX_RXD_STRUC    p28xxRxD,
-	IN PHEADER_802_11		pHeader);
-
-VOID RtmpDoAte(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID BubbleSort(
-	IN  INT32 n,
-	IN  INT32 a[]);
-
-VOID CalNoiseLevel(
-	IN  PRTMP_ADAPTER   pAdapter,
-	IN  UCHAR           channel,
-	OUT INT32           buffer[3][10]);
-
-BOOLEAN SyncTxRxConfig(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	USHORT			offset,
-	IN	UCHAR			value);
-
-#if 0
-INT Set_TxStart_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif  // 0 //
-
-INT Set_TxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_RxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#if 0
-INT Set_EERead_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_EEWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_BBPRead_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_BBPWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_RFWrite_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // end of #if 0 //
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-VOID ATEAsicSwitchChannel(
-	IN PRTMP_ADAPTER pAd);
-
-VOID ATEAsicAdjustTxPower(
-	IN PRTMP_ADAPTER pAd);
-
-VOID ATEDisableAsicProtect(
-	IN		PRTMP_ADAPTER	pAd);
-
-CHAR ATEConvertToRssi(
-	IN PRTMP_ADAPTER  pAd,
-	IN CHAR				Rssi,
-	IN UCHAR    RssiNumber);
-
-VOID ATESampleRssi(
-	IN PRTMP_ADAPTER	pAd,
-	IN PRXWI_STRUC		pRxWI);
-
-
-#ifdef CONFIG_STA_SUPPORT
-VOID RTMPStationStop(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPStationStart(
-    IN  PRTMP_ADAPTER   pAd);
-#endif // CONFIG_STA_SUPPORT //
-#endif // __ATE_H__ //
diff --git a/drivers/staging/rt2870/rt_config.h b/drivers/staging/rt2870/rt_config.h
index e3fe264..1f6d6ed 100644
--- a/drivers/staging/rt2870/rt_config.h
+++ b/drivers/staging/rt2870/rt_config.h
@@ -1,104 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rt_config.h
-
-	Abstract:
-	Central header file to maintain all include files for all NDIS
-	miniport driver routines.
-
-	Revision History:
-	Who         When          What
-	--------    ----------    ----------------------------------------------
-	Paul Lin    08-01-2002    created
-
-*/
-#ifndef	__RT_CONFIG_H__
-#define	__RT_CONFIG_H__
-
-#include    "rtmp_type.h"
-#ifdef UCOS
-#include "includes.h"
-#include <stdio.h>
-#include 	"rt_ucos.h"
-#endif
-
-#ifdef LINUX
-#include	"rt_linux.h"
-#endif
-#include    "rtmp_def.h"
-#include    "rt28xx.h"
-
-
-#ifdef RT2870
-#include	"rt2870.h"
-#endif // RT2870 //
-
-#include    "oid.h"
-#include    "mlme.h"
-#include    "wpa.h"
-#include    "md5.h"
-#include    "rtmp.h"
-#include	"ap.h"
-#include	"dfs.h"
-#include	"chlist.h"
-#include	"spectrum.h"
-
-
-#ifdef LEAP_SUPPORT
-#include    "leap.h"
-#endif // LEAP_SUPPORT //
-
-#ifdef BLOCK_NET_IF
-#include "netif_block.h"
-#endif // BLOCK_NET_IF //
-
-#ifdef IGMP_SNOOP_SUPPORT
-#include "igmp_snoop.h"
-#endif // IGMP_SNOOP_SUPPORT //
-
-#ifdef RALINK_ATE
-#include "rt_ate.h"
-#endif // RALINK_ATE //
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-#ifndef WPA_SUPPLICANT_SUPPORT
-#error "Build for being controlled by NetworkManager or wext, please set HAS_WPA_SUPPLICANT=y and HAS_NATIVE_WPA_SUPPLICANT_SUPPORT=y"
-#endif // WPA_SUPPLICANT_SUPPORT //
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef IKANOS_VX_1X0
-#include	"vr_ikans.h"
-#endif // IKANOS_VX_1X0 //
-
-#endif	// __RT_CONFIG_H__
-
+#include "../rt2860/rt_config.h"
diff --git a/drivers/staging/rt2870/rt_linux.c b/drivers/staging/rt2870/rt_linux.c
index e38552c..88c697b 100644
--- a/drivers/staging/rt2870/rt_linux.c
+++ b/drivers/staging/rt2870/rt_linux.c
@@ -1,1095 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#include "rt_config.h"
-
-ULONG	RTDebugLevel = RT_DEBUG_ERROR;
-
-BUILD_TIMER_FUNCTION(MlmePeriodicExec);
-//BUILD_TIMER_FUNCTION(MlmeRssiReportExec);
-BUILD_TIMER_FUNCTION(AsicRxAntEvalTimeout);
-BUILD_TIMER_FUNCTION(APSDPeriodicExec);
-BUILD_TIMER_FUNCTION(AsicRfTuningExec);
-#ifdef RT2870
-BUILD_TIMER_FUNCTION(BeaconUpdateExec);
-#endif // RT2870 //
-
-
-#ifdef CONFIG_STA_SUPPORT
-BUILD_TIMER_FUNCTION(BeaconTimeout);
-BUILD_TIMER_FUNCTION(ScanTimeout);
-BUILD_TIMER_FUNCTION(AuthTimeout);
-BUILD_TIMER_FUNCTION(AssocTimeout);
-BUILD_TIMER_FUNCTION(ReassocTimeout);
-BUILD_TIMER_FUNCTION(DisassocTimeout);
-BUILD_TIMER_FUNCTION(LinkDownExec);
-#ifdef LEAP_SUPPORT
-BUILD_TIMER_FUNCTION(LeapAuthTimeout);
-#endif
-BUILD_TIMER_FUNCTION(StaQuickResponeForRateUpExec);
-BUILD_TIMER_FUNCTION(WpaDisassocApAndBlockAssoc);
-#ifdef QOS_DLS_SUPPORT
-BUILD_TIMER_FUNCTION(DlsTimeoutAction);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-// for wireless system event message
-char const *pWirelessSysEventText[IW_SYS_EVENT_TYPE_NUM] = {
-	// system status event
-    "had associated successfully",							/* IW_ASSOC_EVENT_FLAG */
-    "had disassociated",									/* IW_DISASSOC_EVENT_FLAG */
-    "had deauthenticated",									/* IW_DEAUTH_EVENT_FLAG */
-    "had been aged-out and disassociated",					/* IW_AGEOUT_EVENT_FLAG */
-    "occurred CounterMeasures attack",						/* IW_COUNTER_MEASURES_EVENT_FLAG */
-    "occurred replay counter different in Key Handshaking",	/* IW_REPLAY_COUNTER_DIFF_EVENT_FLAG */
-    "occurred RSNIE different in Key Handshaking",			/* IW_RSNIE_DIFF_EVENT_FLAG */
-    "occurred MIC different in Key Handshaking",			/* IW_MIC_DIFF_EVENT_FLAG */
-    "occurred ICV error in RX",								/* IW_ICV_ERROR_EVENT_FLAG */
-    "occurred MIC error in RX",								/* IW_MIC_ERROR_EVENT_FLAG */
-	"Group Key Handshaking timeout",						/* IW_GROUP_HS_TIMEOUT_EVENT_FLAG */
-	"Pairwise Key Handshaking timeout",						/* IW_PAIRWISE_HS_TIMEOUT_EVENT_FLAG */
-	"RSN IE sanity check failure",							/* IW_RSNIE_SANITY_FAIL_EVENT_FLAG */
-	"set key done in WPA/WPAPSK",							/* IW_SET_KEY_DONE_WPA1_EVENT_FLAG */
-	"set key done in WPA2/WPA2PSK",                         /* IW_SET_KEY_DONE_WPA2_EVENT_FLAG */
-	"connects with our wireless client",                    /* IW_STA_LINKUP_EVENT_FLAG */
-	"disconnects with our wireless client",                 /* IW_STA_LINKDOWN_EVENT_FLAG */
-	"scan completed"										/* IW_SCAN_COMPLETED_EVENT_FLAG */
-	"scan terminate!! Busy!! Enqueue fail!!"				/* IW_SCAN_ENQUEUE_FAIL_EVENT_FLAG */
-	};
-
-// for wireless IDS_spoof_attack event message
-char const *pWirelessSpoofEventText[IW_SPOOF_EVENT_TYPE_NUM] = {
-    "detected conflict SSID",								/* IW_CONFLICT_SSID_EVENT_FLAG */
-    "detected spoofed association response",				/* IW_SPOOF_ASSOC_RESP_EVENT_FLAG */
-    "detected spoofed reassociation responses",				/* IW_SPOOF_REASSOC_RESP_EVENT_FLAG */
-    "detected spoofed probe response",						/* IW_SPOOF_PROBE_RESP_EVENT_FLAG */
-    "detected spoofed beacon",								/* IW_SPOOF_BEACON_EVENT_FLAG */
-    "detected spoofed disassociation",						/* IW_SPOOF_DISASSOC_EVENT_FLAG */
-    "detected spoofed authentication",						/* IW_SPOOF_AUTH_EVENT_FLAG */
-    "detected spoofed deauthentication",					/* IW_SPOOF_DEAUTH_EVENT_FLAG */
-    "detected spoofed unknown management frame",			/* IW_SPOOF_UNKNOWN_MGMT_EVENT_FLAG */
-	"detected replay attack"								/* IW_REPLAY_ATTACK_EVENT_FLAG */
-	};
-
-// for wireless IDS_flooding_attack event message
-char const *pWirelessFloodEventText[IW_FLOOD_EVENT_TYPE_NUM] = {
-	"detected authentication flooding",						/* IW_FLOOD_AUTH_EVENT_FLAG */
-    "detected association request flooding",				/* IW_FLOOD_ASSOC_REQ_EVENT_FLAG */
-    "detected reassociation request flooding",				/* IW_FLOOD_REASSOC_REQ_EVENT_FLAG */
-    "detected probe request flooding",						/* IW_FLOOD_PROBE_REQ_EVENT_FLAG */
-    "detected disassociation flooding",						/* IW_FLOOD_DISASSOC_EVENT_FLAG */
-    "detected deauthentication flooding",					/* IW_FLOOD_DEAUTH_EVENT_FLAG */
-    "detected 802.1x eap-request flooding"					/* IW_FLOOD_EAP_REQ_EVENT_FLAG */
-	};
-
-/* timeout -- ms */
-VOID RTMP_SetPeriodicTimer(
-	IN	NDIS_MINIPORT_TIMER *pTimer,
-	IN	unsigned long timeout)
-{
-	timeout = ((timeout*HZ) / 1000);
-	pTimer->expires = jiffies + timeout;
-	add_timer(pTimer);
-}
-
-/* convert NdisMInitializeTimer --> RTMP_OS_Init_Timer */
-VOID RTMP_OS_Init_Timer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	NDIS_MINIPORT_TIMER *pTimer,
-	IN	TIMER_FUNCTION function,
-	IN	PVOID data)
-{
-	init_timer(pTimer);
-    pTimer->data = (unsigned long)data;
-    pTimer->function = function;
-}
-
-
-VOID RTMP_OS_Add_Timer(
-	IN	NDIS_MINIPORT_TIMER		*pTimer,
-	IN	unsigned long timeout)
-{
-	if (timer_pending(pTimer))
-		return;
-
-	timeout = ((timeout*HZ) / 1000);
-	pTimer->expires = jiffies + timeout;
-	add_timer(pTimer);
-}
-
-VOID RTMP_OS_Mod_Timer(
-	IN	NDIS_MINIPORT_TIMER		*pTimer,
-	IN	unsigned long timeout)
-{
-	timeout = ((timeout*HZ) / 1000);
-	mod_timer(pTimer, jiffies + timeout);
-}
-
-VOID RTMP_OS_Del_Timer(
-	IN	NDIS_MINIPORT_TIMER		*pTimer,
-	OUT	BOOLEAN					*pCancelled)
-{
-	if (timer_pending(pTimer))
-	{
-		*pCancelled = del_timer_sync(pTimer);
-	}
-	else
-	{
-		*pCancelled = TRUE;
-	}
-
-}
-
-VOID RTMP_OS_Release_Packet(
-	IN	PRTMP_ADAPTER pAd,
-	IN	PQUEUE_ENTRY  pEntry)
-{
-	//RTMPFreeNdisPacket(pAd, (struct sk_buff *)pEntry);
-}
-
-// Unify all delay routine by using udelay
-VOID RTMPusecDelay(
-	IN	ULONG	usec)
-{
-	ULONG	i;
-
-	for (i = 0; i < (usec / 50); i++)
-		udelay(50);
-
-	if (usec % 50)
-		udelay(usec % 50);
-}
-
-void RTMP_GetCurrentSystemTime(LARGE_INTEGER *time)
-{
-	time->u.LowPart = jiffies;
-}
-
-// pAd MUST allow to be NULL
-NDIS_STATUS os_alloc_mem(
-	IN	PRTMP_ADAPTER pAd,
-	OUT	PUCHAR *mem,
-	IN	ULONG  size)
-{
-	*mem = (PUCHAR) kmalloc(size, GFP_ATOMIC);
-	if (*mem)
-		return (NDIS_STATUS_SUCCESS);
-	else
-		return (NDIS_STATUS_FAILURE);
-}
-
-// pAd MUST allow to be NULL
-NDIS_STATUS os_free_mem(
-	IN	PRTMP_ADAPTER pAd,
-	IN	PUCHAR mem)
-{
-
-	ASSERT(mem);
-	kfree(mem);
-	return (NDIS_STATUS_SUCCESS);
-}
-
-
-PNDIS_PACKET RTMP_AllocateFragPacketBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length)
-{
-	struct sk_buff *pkt;
-
-	pkt = dev_alloc_skb(Length);
-
-	if (pkt == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("can't allocate frag rx %ld size packet\n",Length));
-	}
-
-	if (pkt)
-	{
-		RTMP_SET_PACKET_SOURCE(OSPKT_TO_RTPKT(pkt), PKTSRC_NDIS);
-	}
-
-	return (PNDIS_PACKET) pkt;
-}
-
-
-PNDIS_PACKET RTMP_AllocateTxPacketBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress)
-{
-	struct sk_buff *pkt;
-
-	pkt = dev_alloc_skb(Length);
-
-	if (pkt == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("can't allocate tx %ld size packet\n",Length));
-	}
-
-	if (pkt)
-	{
-		RTMP_SET_PACKET_SOURCE(OSPKT_TO_RTPKT(pkt), PKTSRC_NDIS);
-		*VirtualAddress = (PVOID) pkt->data;
-	}
-	else
-	{
-		*VirtualAddress = (PVOID) NULL;
-	}
-
-	return (PNDIS_PACKET) pkt;
-}
-
-
-VOID build_tx_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR	pFrame,
-	IN	ULONG	FrameLen)
-{
-
-	struct sk_buff	*pTxPkt;
-
-	ASSERT(pPacket);
-	pTxPkt = RTPKT_TO_OSPKT(pPacket);
-
-	NdisMoveMemory(skb_put(pTxPkt, FrameLen), pFrame, FrameLen);
-}
-
-VOID	RTMPFreeAdapter(
-	IN	PRTMP_ADAPTER	pAd)
-{
-    POS_COOKIE os_cookie;
-	int index;
-
-	os_cookie=(POS_COOKIE)pAd->OS_Cookie;
-
-	kfree(pAd->BeaconBuf);
-
-
-	NdisFreeSpinLock(&pAd->MgmtRingLock);
-
-
-	for (index =0 ; index < NUM_OF_TX_RING; index++)
-	{
-    	NdisFreeSpinLock(&pAd->TxSwQueueLock[index]);
-		NdisFreeSpinLock(&pAd->DeQueueLock[index]);
-		pAd->DeQueueRunning[index] = FALSE;
-	}
-
-	NdisFreeSpinLock(&pAd->irq_lock);
-
-
-	vfree(pAd); // pci_free_consistent(os_cookie->pci_dev,sizeof(RTMP_ADAPTER),pAd,os_cookie->pAd_pa);
-	kfree(os_cookie);
-}
-
-BOOLEAN OS_Need_Clone_Packet(void)
-{
-	return (FALSE);
-}
-
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		clone an input NDIS PACKET to another one. The new internally created NDIS PACKET
-		must have only one NDIS BUFFER
-		return - byte copied. 0 means can't create NDIS PACKET
-		NOTE: internally created NDIS_PACKET should be destroyed by RTMPFreeNdisPacket
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pInsAMSDUHdr	EWC A-MSDU format has extra 14-bytes header. if TRUE, insert this 14-byte hdr in front of MSDU.
-		*pSrcTotalLen			return total packet length. This lenght is calculated with 802.3 format packet.
-
-	Return Value:
-		NDIS_STATUS_SUCCESS
-		NDIS_STATUS_FAILURE
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS RTMPCloneNdisPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	BOOLEAN			pInsAMSDUHdr,
-	IN	PNDIS_PACKET	pInPacket,
-	OUT PNDIS_PACKET   *ppOutPacket)
-{
-
-	struct sk_buff *pkt;
-
-	ASSERT(pInPacket);
-	ASSERT(ppOutPacket);
-
-	// 1. Allocate a packet
-	pkt = dev_alloc_skb(2048);
-
-	if (pkt == NULL)
-	{
-		return NDIS_STATUS_FAILURE;
-	}
-
- 	skb_put(pkt, GET_OS_PKT_LEN(pInPacket));
-	NdisMoveMemory(pkt->data, GET_OS_PKT_DATAPTR(pInPacket), GET_OS_PKT_LEN(pInPacket));
-	*ppOutPacket = OSPKT_TO_RTPKT(pkt);
-
-
-	RTMP_SET_PACKET_SOURCE(OSPKT_TO_RTPKT(pkt), PKTSRC_NDIS);
-
-	printk("###Clone###\n");
-
-	return NDIS_STATUS_SUCCESS;
-}
-
-
-// the allocated NDIS PACKET must be freed via RTMPFreeNdisPacket()
-NDIS_STATUS RTMPAllocateNdisPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT PNDIS_PACKET   *ppPacket,
-	IN	PUCHAR			pHeader,
-	IN	UINT			HeaderLen,
-	IN	PUCHAR			pData,
-	IN	UINT			DataLen)
-{
-	PNDIS_PACKET	pPacket;
-	ASSERT(pData);
-	ASSERT(DataLen);
-
-	// 1. Allocate a packet
-	pPacket = (PNDIS_PACKET *) dev_alloc_skb(HeaderLen + DataLen + TXPADDING_SIZE);
-	if (pPacket == NULL)
- 	{
-		*ppPacket = NULL;
-#ifdef DEBUG
-		printk("RTMPAllocateNdisPacket Fail\n\n");
-#endif
-		return NDIS_STATUS_FAILURE;
-	}
-
-	// 2. clone the frame content
-	if (HeaderLen > 0)
-		NdisMoveMemory(GET_OS_PKT_DATAPTR(pPacket), pHeader, HeaderLen);
-	if (DataLen > 0)
-		NdisMoveMemory(GET_OS_PKT_DATAPTR(pPacket) + HeaderLen, pData, DataLen);
-
-	// 3. update length of packet
- 	skb_put(GET_OS_PKT_TYPE(pPacket), HeaderLen+DataLen);
-
-	RTMP_SET_PACKET_SOURCE(pPacket, PKTSRC_NDIS);
-//	printk("%s : pPacket = %p, len = %d\n", __func__, pPacket, GET_OS_PKT_LEN(pPacket));
-	*ppPacket = pPacket;
-	return NDIS_STATUS_SUCCESS;
-}
-
-/*
-  ========================================================================
-  Description:
-	This routine frees a miniport internally allocated NDIS_PACKET and its
-	corresponding NDIS_BUFFER and allocated memory.
-  ========================================================================
-*/
-VOID RTMPFreeNdisPacket(
-	IN PRTMP_ADAPTER pAd,
-	IN PNDIS_PACKET  pPacket)
-{
-	dev_kfree_skb_any(RTPKT_TO_OSPKT(pPacket));
-}
-
-
-// IRQL = DISPATCH_LEVEL
-// NOTE: we do have an assumption here, that Byte0 and Byte1 always reasid at the same
-//			 scatter gather buffer
-NDIS_STATUS Sniff2BytesFromNdisBuffer(
-	IN	PNDIS_BUFFER	pFirstBuffer,
-	IN	UCHAR			DesiredOffset,
-	OUT PUCHAR			pByte0,
-	OUT PUCHAR			pByte1)
-{
-    *pByte0 = *(PUCHAR)(pFirstBuffer + DesiredOffset);
-    *pByte1 = *(PUCHAR)(pFirstBuffer + DesiredOffset + 1);
-
-	return NDIS_STATUS_SUCCESS;
-}
-
-
-void RTMP_QueryPacketInfo(
-	IN  PNDIS_PACKET pPacket,
-	OUT PACKET_INFO  *pPacketInfo,
-	OUT PUCHAR		 *pSrcBufVA,
-	OUT	UINT		 *pSrcBufLen)
-{
-	pPacketInfo->BufferCount = 1;
-	pPacketInfo->pFirstBuffer = GET_OS_PKT_DATAPTR(pPacket);
-	pPacketInfo->PhysicalBufferCount = 1;
-	pPacketInfo->TotalPacketLength = GET_OS_PKT_LEN(pPacket);
-
-	*pSrcBufVA = GET_OS_PKT_DATAPTR(pPacket);
-	*pSrcBufLen = GET_OS_PKT_LEN(pPacket);
-}
-
-void RTMP_QueryNextPacketInfo(
-	IN  PNDIS_PACKET *ppPacket,
-	OUT PACKET_INFO  *pPacketInfo,
-	OUT PUCHAR		 *pSrcBufVA,
-	OUT	UINT		 *pSrcBufLen)
-{
-	PNDIS_PACKET pPacket = NULL;
-
-	if (*ppPacket)
-		pPacket = GET_OS_PKT_NEXT(*ppPacket);
-
-	if (pPacket)
-	{
-		pPacketInfo->BufferCount = 1;
-		pPacketInfo->pFirstBuffer = GET_OS_PKT_DATAPTR(pPacket);
-		pPacketInfo->PhysicalBufferCount = 1;
-		pPacketInfo->TotalPacketLength = GET_OS_PKT_LEN(pPacket);
-
-		*pSrcBufVA = GET_OS_PKT_DATAPTR(pPacket);
-		*pSrcBufLen = GET_OS_PKT_LEN(pPacket);
-		*ppPacket = GET_OS_PKT_NEXT(pPacket);
-	}
-	else
-	{
-		pPacketInfo->BufferCount = 0;
-		pPacketInfo->pFirstBuffer = NULL;
-		pPacketInfo->PhysicalBufferCount = 0;
-		pPacketInfo->TotalPacketLength = 0;
-
-		*pSrcBufVA = NULL;
-		*pSrcBufLen = 0;
-		*ppPacket = NULL;
-	}
-}
-
-// not yet support MBSS
-PNET_DEV get_netdev_from_bssid(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			FromWhichBSSID)
-{
-    PNET_DEV dev_p = NULL;
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		dev_p = pAd->net_dev;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	ASSERT(dev_p);
-	return dev_p; /* return one of MBSS */
-}
-
-PNDIS_PACKET DuplicatePacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UCHAR			FromWhichBSSID)
-{
-	struct sk_buff	*skb;
-	PNDIS_PACKET	pRetPacket = NULL;
-	USHORT			DataSize;
-	UCHAR			*pData;
-
-	DataSize = (USHORT) GET_OS_PKT_LEN(pPacket);
-	pData = (PUCHAR) GET_OS_PKT_DATAPTR(pPacket);
-
-
-	skb = skb_clone(RTPKT_TO_OSPKT(pPacket), MEM_ALLOC_FLAG);
-	if (skb)
-	{
-		skb->dev = get_netdev_from_bssid(pAd, FromWhichBSSID);
-		pRetPacket = OSPKT_TO_RTPKT(skb);
-	}
-
-#if 0
-	if ((skb = __dev_alloc_skb(DataSize + 2+32, MEM_ALLOC_FLAG)) != NULL)
-	{
-		skb_reserve(skb, 2+32);
-		NdisMoveMemory(skb->tail, pData, DataSize);
-		skb_put(skb, DataSize);
-		skb->dev = get_netdev_from_bssid(pAd, FromWhichBSSID);
-		pRetPacket = OSPKT_TO_RTPKT(skb);
-	}
-#endif
-
-	return pRetPacket;
-
-}
-
-PNDIS_PACKET duplicate_pkt(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pHeader802_3,
-    IN  UINT            HdrLen,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	IN	UCHAR			FromWhichBSSID)
-{
-	struct sk_buff	*skb;
-	PNDIS_PACKET	pPacket = NULL;
-
-
-	if ((skb = __dev_alloc_skb(HdrLen + DataSize + 2, MEM_ALLOC_FLAG)) != NULL)
-	{
-		skb_reserve(skb, 2);
-		NdisMoveMemory(skb->tail, pHeader802_3, HdrLen);
-		skb_put(skb, HdrLen);
-		NdisMoveMemory(skb->tail, pData, DataSize);
-		skb_put(skb, DataSize);
-		skb->dev = get_netdev_from_bssid(pAd, FromWhichBSSID);
-		pPacket = OSPKT_TO_RTPKT(skb);
-	}
-
-	return pPacket;
-}
-
-
-#define TKIP_TX_MIC_SIZE		8
-PNDIS_PACKET duplicate_pkt_with_TKIP_MIC(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-	struct sk_buff	*skb, *newskb;
-
-
-	skb = RTPKT_TO_OSPKT(pPacket);
-	if (skb_tailroom(skb) < TKIP_TX_MIC_SIZE)
-	{
-		// alloc a new skb and copy the packet
-		newskb = skb_copy_expand(skb, skb_headroom(skb), TKIP_TX_MIC_SIZE, GFP_ATOMIC);
-		dev_kfree_skb_any(skb);
-		if (newskb == NULL)
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("Extend Tx.MIC for packet failed!, dropping packet!\n"));
-			return NULL;
-		}
-		skb = newskb;
-	}
-
-	return OSPKT_TO_RTPKT(skb);
-
-#if 0
-	if ((data = skb_put(skb, TKIP_TX_MIC_SIZE)) != NULL)
-	{	// If we can extend it, well, copy it first.
-		NdisMoveMemory(data, pAd->PrivateInfo.Tx.MIC, TKIP_TX_MIC_SIZE);
-	}
-	else
-	{
-		// Otherwise, copy the packet.
-		newskb = skb_copy_expand(skb, skb_headroom(skb), TKIP_TX_MIC_SIZE, GFP_ATOMIC);
-		dev_kfree_skb_any(skb);
-		if (newskb == NULL)
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("Extend Tx.MIC to packet failed!, dropping packet\n"));
-			return NULL;
-		}
-		skb = newskb;
-
-		NdisMoveMemory(skb->tail, pAd->PrivateInfo.Tx.MIC, TKIP_TX_MIC_SIZE);
-		skb_put(skb, TKIP_TX_MIC_SIZE);
-	}
-
-	return OSPKT_TO_RTPKT(skb);
-#endif
-
-}
-
-
-
-
-PNDIS_PACKET ClonePacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize)
-{
-	struct sk_buff	*pRxPkt;
-	struct sk_buff	*pClonedPkt;
-
-	ASSERT(pPacket);
-	pRxPkt = RTPKT_TO_OSPKT(pPacket);
-
-	// clone the packet
-	pClonedPkt = skb_clone(pRxPkt, MEM_ALLOC_FLAG);
-
-	if (pClonedPkt)
-	{
-    	// set the correct dataptr and data len
-    	pClonedPkt->dev = pRxPkt->dev;
-    	pClonedPkt->data = pData;
-    	pClonedPkt->len = DataSize;
-    	pClonedPkt->tail = pClonedPkt->data + pClonedPkt->len;
-		ASSERT(DataSize < 1530);
-	}
-	return pClonedPkt;
-}
-
-//
-// change OS packet DataPtr and DataLen
-//
-void  update_os_packet_info(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN  UCHAR			FromWhichBSSID)
-{
-	struct sk_buff	*pOSPkt;
-
-	ASSERT(pRxBlk->pRxPacket);
-	pOSPkt = RTPKT_TO_OSPKT(pRxBlk->pRxPacket);
-
-	pOSPkt->dev = get_netdev_from_bssid(pAd, FromWhichBSSID);
-	pOSPkt->data = pRxBlk->pData;
-	pOSPkt->len = pRxBlk->DataSize;
-	pOSPkt->tail = pOSPkt->data + pOSPkt->len;
-}
-
-
-void wlan_802_11_to_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	PUCHAR			pHeader802_3,
-	IN  UCHAR			FromWhichBSSID)
-{
-	struct sk_buff	*pOSPkt;
-
-	ASSERT(pRxBlk->pRxPacket);
-	ASSERT(pHeader802_3);
-
-	pOSPkt = RTPKT_TO_OSPKT(pRxBlk->pRxPacket);
-
-	pOSPkt->dev = get_netdev_from_bssid(pAd, FromWhichBSSID);
-	pOSPkt->data = pRxBlk->pData;
-	pOSPkt->len = pRxBlk->DataSize;
-	pOSPkt->tail = pOSPkt->data + pOSPkt->len;
-
-	//
-	// copy 802.3 header
-	//
-	//
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		NdisMoveMemory(skb_push(pOSPkt, LENGTH_802_3), pHeader802_3, LENGTH_802_3);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-
-
-void announce_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-
-	struct sk_buff	*pRxPkt;
-
-	ASSERT(pPacket);
-
-	pRxPkt = RTPKT_TO_OSPKT(pPacket);
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-    /* Push up the protocol stack */
-#ifdef IKANOS_VX_1X0
-	IKANOS_DataFrameRx(pAd, pRxPkt->dev, pRxPkt, pRxPkt->len);
-#else
-	pRxPkt->protocol = eth_type_trans(pRxPkt, pRxPkt->dev);
-
-//#ifdef CONFIG_5VT_ENHANCE
-//	*(int*)(pRxPkt->cb) = BRIDGE_TAG;
-//#endif
-	netif_rx(pRxPkt);
-#endif // IKANOS_VX_1X0 //
-}
-
-
-PRTMP_SCATTER_GATHER_LIST
-rt_get_sg_list_from_packet(PNDIS_PACKET pPacket, RTMP_SCATTER_GATHER_LIST *sg)
-{
-	sg->NumberOfElements = 1;
-	sg->Elements[0].Address =  GET_OS_PKT_DATAPTR(pPacket);
-	sg->Elements[0].Length = GET_OS_PKT_LEN(pPacket);
-	return (sg);
-}
-
-void hex_dump(char *str, unsigned char *pSrcBufVA, unsigned int SrcBufLen)
-{
-	unsigned char *pt;
-	int x;
-
-	if (RTDebugLevel < RT_DEBUG_TRACE)
-		return;
-
-	pt = pSrcBufVA;
-	printk("%s: %p, len = %d\n",str,  pSrcBufVA, SrcBufLen);
-	for (x=0; x<SrcBufLen; x++)
-	{
-		if (x % 16 == 0)
-			printk("0x%04x : ", x);
-		printk("%02x ", ((unsigned char)pt[x]));
-		if (x%16 == 15) printk("\n");
-	}
-	printk("\n");
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Send log message through wireless event
-
-		Support standard iw_event with IWEVCUSTOM. It is used below.
-
-		iwreq_data.data.flags is used to store event_flag that is defined by user.
-		iwreq_data.data.length is the length of the event log.
-
-		The format of the event log is composed of the entry's MAC address and
-		the desired log message (refer to pWirelessEventText).
-
-			ex: 11:22:33:44:55:66 has associated successfully
-
-		p.s. The requirement of Wireless Extension is v15 or newer.
-
-	========================================================================
-*/
-VOID RTMPSendWirelessEvent(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Event_flag,
-	IN	PUCHAR 			pAddr,
-	IN	UCHAR			BssIdx,
-	IN	CHAR			Rssi)
-{
-#if WIRELESS_EXT >= 15
-
-	union 	iwreq_data      wrqu;
-	PUCHAR 	pBuf = NULL, pBufPtr = NULL;
-	USHORT	event, type, BufLen;
-	UCHAR	event_table_len = 0;
-
-	type = Event_flag & 0xFF00;
-	event = Event_flag & 0x00FF;
-
-	switch (type)
-	{
-		case IW_SYS_EVENT_FLAG_START:
-			event_table_len = IW_SYS_EVENT_TYPE_NUM;
-			break;
-
-		case IW_SPOOF_EVENT_FLAG_START:
-			event_table_len = IW_SPOOF_EVENT_TYPE_NUM;
-			break;
-
-		case IW_FLOOD_EVENT_FLAG_START:
-			event_table_len = IW_FLOOD_EVENT_TYPE_NUM;
-			break;
-	}
-
-	if (event_table_len == 0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s : The type(%0x02x) is not valid.\n", __func__, type));
-		return;
-	}
-
-	if (event >= event_table_len)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s : The event(%0x02x) is not valid.\n", __func__, event));
-		return;
-	}
-
-	//Allocate memory and copy the msg.
-	if((pBuf = kmalloc(IW_CUSTOM_MAX_LEN, GFP_ATOMIC)) != NULL)
-	{
-		//Prepare the payload
-		memset(pBuf, 0, IW_CUSTOM_MAX_LEN);
-
-		pBufPtr = pBuf;
-
-		if (pAddr)
-			pBufPtr += sprintf(pBufPtr, "(RT2860) STA(%02x:%02x:%02x:%02x:%02x:%02x) ", PRINT_MAC(pAddr));
-		else if (BssIdx < MAX_MBSSID_NUM)
-			pBufPtr += sprintf(pBufPtr, "(RT2860) BSS(ra%d) ", BssIdx);
-		else
-			pBufPtr += sprintf(pBufPtr, "(RT2860) ");
-
-		if (type == IW_SYS_EVENT_FLAG_START)
-			pBufPtr += sprintf(pBufPtr, "%s", pWirelessSysEventText[event]);
-		else if (type == IW_SPOOF_EVENT_FLAG_START)
-			pBufPtr += sprintf(pBufPtr, "%s (RSSI=%d)", pWirelessSpoofEventText[event], Rssi);
-		else if (type == IW_FLOOD_EVENT_FLAG_START)
-			pBufPtr += sprintf(pBufPtr, "%s", pWirelessFloodEventText[event]);
-		else
-			pBufPtr += sprintf(pBufPtr, "%s", "unknown event");
-
-		pBufPtr[pBufPtr - pBuf] = '\0';
-		BufLen = pBufPtr - pBuf;
-
-		memset(&wrqu, 0, sizeof(wrqu));
-	    wrqu.data.flags = Event_flag;
-		wrqu.data.length = BufLen;
-
-		//send wireless event
-	    wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, pBuf);
-
-		//DBGPRINT(RT_DEBUG_TRACE, ("%s : %s\n", __func__, pBuf));
-
-		kfree(pBuf);
-	}
-	else
-		DBGPRINT(RT_DEBUG_ERROR, ("%s : Can't allocate memory for wireless event.\n", __func__));
-#else
-	DBGPRINT(RT_DEBUG_ERROR, ("%s : The Wireless Extension MUST be v15 or newer.\n", __func__));
-#endif  /* WIRELESS_EXT >= 15 */
-}
-
-
-#ifdef CONFIG_STA_SUPPORT
-void send_monitor_packets(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk)
-{
-    struct sk_buff	*pOSPkt;
-    wlan_ng_prism2_header *ph;
-    int rate_index = 0;
-    USHORT header_len = 0;
-    UCHAR temp_header[40] = {0};
-
-    u_int32_t ralinkrate[256] = {2,4,11,22, 12,18,24,36,48,72,96,  108,   109, 110, 111, 112, 13, 26, 39, 52,78,104, 117, 130, 26, 52, 78,104, 156, 208, 234, 260, 27, 54,81,108,162, 216, 243, 270, // Last 38
-	54, 108, 162, 216, 324, 432, 486, 540,  14, 29, 43, 57, 87, 115, 130, 144, 29, 59,87,115, 173, 230,260, 288, 30, 60,90,120,180,240,270,300,60,120,180,240,360,480,540,600, 0,1,2,3,4,5,6,7,8,9,10,
-	11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80};
-
-
-    ASSERT(pRxBlk->pRxPacket);
-    if (pRxBlk->DataSize < 10)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("%s : Size is too small! (%d)\n", __func__, pRxBlk->DataSize));
-		goto err_free_sk_buff;
-    }
-
-    if (pRxBlk->DataSize + sizeof(wlan_ng_prism2_header) > RX_BUFFER_AGGRESIZE)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("%s : Size is too large! (%zu)\n", __func__, pRxBlk->DataSize + sizeof(wlan_ng_prism2_header)));
-		goto err_free_sk_buff;
-    }
-
-    pOSPkt = RTPKT_TO_OSPKT(pRxBlk->pRxPacket);
-	pOSPkt->dev = get_netdev_from_bssid(pAd, BSS0);
-    if (pRxBlk->pHeader->FC.Type == BTYPE_DATA)
-    {
-        pRxBlk->DataSize -= LENGTH_802_11;
-        if ((pRxBlk->pHeader->FC.ToDs == 1) &&
-            (pRxBlk->pHeader->FC.FrDs == 1))
-            header_len = LENGTH_802_11_WITH_ADDR4;
-        else
-            header_len = LENGTH_802_11;
-
-        // QOS
-    	if (pRxBlk->pHeader->FC.SubType & 0x08)
-    	{
-    	    header_len += 2;
-    		// Data skip QOS contorl field
-    		pRxBlk->DataSize -=2;
-    	}
-
-    	// Order bit: A-Ralink or HTC+
-    	if (pRxBlk->pHeader->FC.Order)
-    	{
-    	    header_len += 4;
-			// Data skip HTC contorl field
-			pRxBlk->DataSize -= 4;
-    	}
-
-        // Copy Header
-        if (header_len <= 40)
-            NdisMoveMemory(temp_header, pRxBlk->pData, header_len);
-
-        // skip HW padding
-    	if (pRxBlk->RxD.L2PAD)
-    	    pRxBlk->pData += (header_len + 2);
-        else
-            pRxBlk->pData += header_len;
-    } //end if
-
-
-	if (pRxBlk->DataSize < pOSPkt->len) {
-        skb_trim(pOSPkt,pRxBlk->DataSize);
-    } else {
-        skb_put(pOSPkt,(pRxBlk->DataSize - pOSPkt->len));
-    } //end if
-
-    if ((pRxBlk->pData - pOSPkt->data) > 0) {
-	    skb_put(pOSPkt,(pRxBlk->pData - pOSPkt->data));
-	    skb_pull(pOSPkt,(pRxBlk->pData - pOSPkt->data));
-    } //end if
-
-    if (skb_headroom(pOSPkt) < (sizeof(wlan_ng_prism2_header)+ header_len)) {
-        if (pskb_expand_head(pOSPkt, (sizeof(wlan_ng_prism2_header) + header_len), 0, GFP_ATOMIC)) {
-	        DBGPRINT(RT_DEBUG_ERROR, ("%s : Reallocate header size of sk_buff fail!\n", __func__));
-			goto err_free_sk_buff;
-	    } //end if
-    } //end if
-
-    if (header_len > 0)
-        NdisMoveMemory(skb_push(pOSPkt, header_len), temp_header, header_len);
-
-    ph = (wlan_ng_prism2_header *) skb_push(pOSPkt, sizeof(wlan_ng_prism2_header));
-	NdisZeroMemory(ph, sizeof(wlan_ng_prism2_header));
-
-    ph->msgcode		    = DIDmsg_lnxind_wlansniffrm;
-	ph->msglen		    = sizeof(wlan_ng_prism2_header);
-	strcpy(ph->devname, pAd->net_dev->name);
-
-    ph->hosttime.did = DIDmsg_lnxind_wlansniffrm_hosttime;
-	ph->hosttime.status = 0;
-	ph->hosttime.len = 4;
-	ph->hosttime.data = jiffies;
-
-	ph->mactime.did = DIDmsg_lnxind_wlansniffrm_mactime;
-	ph->mactime.status = 0;
-	ph->mactime.len = 0;
-	ph->mactime.data = 0;
-
-    ph->istx.did = DIDmsg_lnxind_wlansniffrm_istx;
-	ph->istx.status = 0;
-	ph->istx.len = 0;
-	ph->istx.data = 0;
-
-    ph->channel.did = DIDmsg_lnxind_wlansniffrm_channel;
-	ph->channel.status = 0;
-	ph->channel.len = 4;
-
-    ph->channel.data = (u_int32_t)pAd->CommonCfg.Channel;
-
-    ph->rssi.did = DIDmsg_lnxind_wlansniffrm_rssi;
-	ph->rssi.status = 0;
-	ph->rssi.len = 4;
-    ph->rssi.data = (u_int32_t)RTMPMaxRssi(pAd, ConvertToRssi(pAd, pRxBlk->pRxWI->RSSI0, RSSI_0), ConvertToRssi(pAd, pRxBlk->pRxWI->RSSI1, RSSI_1), ConvertToRssi(pAd, pRxBlk->pRxWI->RSSI2, RSSI_2));;
-
-	ph->signal.did = DIDmsg_lnxind_wlansniffrm_signal;
-	ph->signal.status = 0;
-	ph->signal.len = 4;
-	ph->signal.data = 0; //rssi + noise;
-
-	ph->noise.did = DIDmsg_lnxind_wlansniffrm_noise;
-	ph->noise.status = 0;
-	ph->noise.len = 4;
-	ph->noise.data = 0;
-
-#ifdef DOT11_N_SUPPORT
-    if (pRxBlk->pRxWI->PHYMODE >= MODE_HTMIX)
-    {
-    	rate_index = 16 + ((UCHAR)pRxBlk->pRxWI->BW *16) + ((UCHAR)pRxBlk->pRxWI->ShortGI *32) + ((UCHAR)pRxBlk->pRxWI->MCS);
-    }
-    else
-#endif // DOT11_N_SUPPORT //
-	if (pRxBlk->pRxWI->PHYMODE == MODE_OFDM)
-    	rate_index = (UCHAR)(pRxBlk->pRxWI->MCS) + 4;
-    else
-    	rate_index = (UCHAR)(pRxBlk->pRxWI->MCS);
-    if (rate_index < 0)
-        rate_index = 0;
-    if (rate_index > 255)
-        rate_index = 255;
-
-	ph->rate.did = DIDmsg_lnxind_wlansniffrm_rate;
-	ph->rate.status = 0;
-	ph->rate.len = 4;
-    ph->rate.data = ralinkrate[rate_index];
-
-	ph->frmlen.did = DIDmsg_lnxind_wlansniffrm_frmlen;
-    ph->frmlen.status = 0;
-	ph->frmlen.len = 4;
-	ph->frmlen.data	= (u_int32_t)pRxBlk->DataSize;
-
-
-    pOSPkt->pkt_type = PACKET_OTHERHOST;
-    pOSPkt->protocol = eth_type_trans(pOSPkt, pOSPkt->dev);
-    pOSPkt->ip_summed = CHECKSUM_NONE;
-    netif_rx(pOSPkt);
-
-    return;
-
-err_free_sk_buff:
-	RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-	return;
-
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-void rtmp_os_thread_init(PUCHAR pThreadName, PVOID pNotify)
-{
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-	daemonize(pThreadName /*"%s",pAd->net_dev->name*/);
-
-	allow_signal(SIGTERM);
-	allow_signal(SIGKILL);
-	current->flags |= PF_NOFREEZE;
-#else
-	unsigned long flags;
-
-	daemonize();
-	reparent_to_init();
-	strcpy(current->comm, pThreadName);
-
-	siginitsetinv(&current->blocked, sigmask(SIGTERM) | sigmask(SIGKILL));
-
-	/* Allow interception of SIGKILL only
-	 * Don't allow other signals to interrupt the transmission */
-#if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,22)
-	spin_lock_irqsave(&current->sigmask_lock, flags);
-	flush_signals(current);
-	recalc_sigpending(current);
-	spin_unlock_irqrestore(&current->sigmask_lock, flags);
-#endif
-#endif
-
-    /* signal that we've started the thread */
-	complete(pNotify);
-
-}
-
-void RTMP_IndicateMediaState(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	if (pAd->CommonCfg.bWirelessEvent)
-	{
-		if (pAd->IndicateMediaState == NdisMediaStateConnected)
-		{
-			RTMPSendWirelessEvent(pAd, IW_STA_LINKUP_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-		}
-		else
-		{
-			RTMPSendWirelessEvent(pAd, IW_STA_LINKDOWN_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-		}
-	}
-}
-
+#include "../rt2860/rt_linux.c"
diff --git a/drivers/staging/rt2870/rt_linux.h b/drivers/staging/rt2870/rt_linux.h
index 5a6ee6a..b2aeafb 100644
--- a/drivers/staging/rt2870/rt_linux.h
+++ b/drivers/staging/rt2870/rt_linux.h
@@ -1,906 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-/***********************************************************************/
-/*                                                                     */
-/*   Program:    rt_linux.c                                            */
-/*   Created:    4/21/2006 1:17:38 PM                                  */
-/*   Author:     Wu Xi-Kun                                             */
-/*   Comments:   `description`                                         */
-/*                                                                     */
-/*---------------------------------------------------------------------*/
-/*                                                                     */
-/* History:                                                            */
-/*    Revision 1.1 4/21/2006 1:17:38 PM  xsikun                        */
-/*    Initial revision                                                 */
-/*                                                                     */
-/***********************************************************************/
-
-#include "rtmp_type.h"
-#include <linux/module.h>
-#include <linux/version.h>
-#include <linux/kernel.h>
-#include <linux/kthread.h>
-
-#include <linux/spinlock.h>
-#include <linux/init.h>
-#include <linux/string.h>
-#include <linux/timer.h>
-#include <linux/errno.h>
-#include <linux/slab.h>
-#include <linux/interrupt.h>
-#include <linux/pci.h>
-#include <linux/netdevice.h>
-#include <linux/etherdevice.h>
-#include <linux/skbuff.h>
-#include <linux/ethtool.h>
-#include <linux/wireless.h>
-#include <linux/proc_fs.h>
-#include <linux/delay.h>
-#include <linux/if_arp.h>
-#include <linux/ctype.h>
-#include <linux/vmalloc.h>
-
-
-#include <net/iw_handler.h>
-
-// load firmware
-#define __KERNEL_SYSCALLS__
-#include <linux/unistd.h>
-#include <asm/uaccess.h>
-
-
-#define MEM_ALLOC_FLAG      (GFP_ATOMIC) //(GFP_DMA | GFP_ATOMIC)
-
-#ifndef IFNAMSIZ
-#define IFNAMSIZ 16
-#endif
-
-//#define CONFIG_CKIP_SUPPORT
-
-#undef __inline
-#define __inline	   static inline
-
-typedef int (*HARD_START_XMIT_FUNC)(struct sk_buff *skb, struct net_device *net_dev);
-
-// add by kathy
-
-#ifdef CONFIG_STA_SUPPORT
-
-#ifdef RT2870
-#define STA_PROFILE_PATH			"/etc/Wireless/RT2870STA/RT2870STA.dat"
-#define STA_RT2870_IMAGE_FILE_NAME  "/etc/Wireless/RT2870STA/rt2870.bin"
-#define STA_NIC_DEVICE_NAME			"RT2870STA"
-#define STA_DRIVER_VERSION			"1.4.0.0"
-#ifdef MULTIPLE_CARD_SUPPORT
-#define CARD_INFO_PATH			"/etc/Wireless/RT2870STA/RT2870STACard.dat"
-#endif // MULTIPLE_CARD_SUPPORT //
-#endif // RT2870 //
-
-#endif // CONFIG_STA_SUPPORT //
-
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-
-#define RTMP_TIME_AFTER(a,b)		\
-	(typecheck(unsigned long, (unsigned long)a) && \
-	 typecheck(unsigned long, (unsigned long)b) && \
-	 ((long)(b) - (long)(a) < 0))
-
-#define RTMP_TIME_AFTER_EQ(a,b)	\
-	(typecheck(unsigned long, (unsigned long)a) && \
-	 typecheck(unsigned long, (unsigned long)b) && \
-	 ((long)(a) - (long)(b) >= 0))
-#define RTMP_TIME_BEFORE(a,b)	RTMP_TIME_AFTER_EQ(b,a)
-#else
-#define RTMP_TIME_AFTER(a,b) time_after(a, b)
-#endif
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-#define RT_MOD_INC_USE_COUNT() \
-	if (!try_module_get(THIS_MODULE)) \
-	{ \
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: cannot reserve module\n", __func__)); \
-		return -1; \
-	}
-
-#define RT_MOD_DEC_USE_COUNT() module_put(THIS_MODULE);
-#else
-#define RT_MOD_INC_USE_COUNT()	MOD_INC_USE_COUNT;
-#define RT_MOD_DEC_USE_COUNT() MOD_DEC_USE_COUNT;
-#endif
-
-#define OS_HZ			HZ
-
-#define ETH_LENGTH_OF_ADDRESS	6
-
-#define IN
-#define OUT
-
-#define NDIS_STATUS                             INT
-#define NDIS_STATUS_SUCCESS                     0x00
-#define NDIS_STATUS_FAILURE                     0x01
-#define NDIS_STATUS_INVALID_DATA				0x02
-#define NDIS_STATUS_RESOURCES                   0x03
-
-#define MIN_NET_DEVICE_FOR_AID			0x00		//0x00~0x3f
-#define MIN_NET_DEVICE_FOR_MBSSID		0x00		//0x00,0x10,0x20,0x30
-#define MIN_NET_DEVICE_FOR_WDS			0x10		//0x40,0x50,0x60,0x70
-#define MIN_NET_DEVICE_FOR_APCLI		0x20
-#define MIN_NET_DEVICE_FOR_MESH			0x30
-#ifdef CONFIG_STA_SUPPORT
-#define MIN_NET_DEVICE_FOR_DLS			0x40
-#endif // CONFIG_STA_SUPPORT //
-
-
-#ifdef CONFIG_STA_SUPPORT
-#define NDIS_PACKET_TYPE_DIRECTED		0
-#define NDIS_PACKET_TYPE_MULTICAST		1
-#define NDIS_PACKET_TYPE_BROADCAST		2
-#define NDIS_PACKET_TYPE_ALL_MULTICAST	3
-#endif // CONFIG_STA_SUPPORT //
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
-typedef	struct pid *	THREAD_PID;
-#define	GET_PID(_v)	find_get_pid(_v)
-#define	GET_PID_NUMBER(_v)	pid_nr(_v)
-#define CHECK_PID_LEGALITY(_pid)	if (pid_nr(_pid) >= 0)
-#define KILL_THREAD_PID(_A, _B, _C)	kill_pid(_A, _B, _C)
-#else
-typedef	pid_t	THREAD_PID;
-#define	GET_PID(_v)	_v
-#define	GET_PID_NUMBER(_v)	_v
-#define CHECK_PID_LEGALITY(_pid)	if (_pid >= 0)
-#define KILL_THREAD_PID(_A, _B, _C)	kill_proc(_A, _B, _C)
-#endif
-
-struct os_lock  {
-	spinlock_t		lock;
-	unsigned long  	flags;
-};
-
-
-struct os_cookie {
-
-#ifdef RT2870
-	struct usb_device	*pUsb_Dev;
-
-	struct task_struct	*MLMEThr_task;
-	struct task_struct	*RTUSBCmdThr_task;
-	struct task_struct	*TimerQThr_task;
-#endif // RT2870 //
-
-	struct tasklet_struct 	rx_done_task;
-	struct tasklet_struct 	mgmt_dma_done_task;
-	struct tasklet_struct 	ac0_dma_done_task;
-	struct tasklet_struct 	ac1_dma_done_task;
-	struct tasklet_struct 	ac2_dma_done_task;
-	struct tasklet_struct 	ac3_dma_done_task;
-	struct tasklet_struct 	hcca_dma_done_task;
-	struct tasklet_struct	tbtt_task;
-#ifdef RT2870
-	struct tasklet_struct	null_frame_complete_task;
-	struct tasklet_struct	rts_frame_complete_task;
-	struct tasklet_struct	pspoll_frame_complete_task;
-#endif // RT2870 //
-
-
-	unsigned long			apd_pid; //802.1x daemon pid
-	INT						ioctl_if_type;
-	INT 					ioctl_if;
-};
-
-typedef struct _VIRTUAL_ADAPTER
-{
-	struct net_device		*RtmpDev;
-	struct net_device		*VirtualDev;
-} VIRTUAL_ADAPTER, PVIRTUAL_ADAPTER;
-
-#undef  ASSERT
-#define ASSERT(x)                                                               \
-{                                                                               \
-    if (!(x))                                                                   \
-    {                                                                           \
-        printk(KERN_WARNING __FILE__ ":%d assert " #x "failed\n", __LINE__);    \
-    }                                                                           \
-}
-
-typedef struct os_cookie	* POS_COOKIE;
-typedef struct pci_dev 		* PPCI_DEV;
-typedef struct net_device	* PNET_DEV;
-typedef void				* PNDIS_PACKET;
-typedef char				NDIS_PACKET;
-typedef PNDIS_PACKET		* PPNDIS_PACKET;
-typedef	dma_addr_t			NDIS_PHYSICAL_ADDRESS;
-typedef	dma_addr_t			* PNDIS_PHYSICAL_ADDRESS;
-//typedef struct timer_list	RALINK_TIMER_STRUCT;
-//typedef struct timer_list	* PRALINK_TIMER_STRUCT;
-//typedef struct os_lock		NDIS_SPIN_LOCK;
-typedef spinlock_t			NDIS_SPIN_LOCK;
-typedef struct timer_list	NDIS_MINIPORT_TIMER;
-typedef void				* NDIS_HANDLE;
-typedef char 				* PNDIS_BUFFER;
-
-
-
-void hex_dump(char *str, unsigned char *pSrcBufVA, unsigned int SrcBufLen);
-
-dma_addr_t linux_pci_map_single(void *handle, void *ptr, size_t size, int sd_idx, int direction);
-void linux_pci_unmap_single(void *handle, dma_addr_t dma_addr, size_t size, int direction);
-
-
-////////////////////////////////////////
-// MOVE TO rtmp.h ?
-/////////////////////////////////////////
-#define PKTSRC_NDIS             0x7f
-#define PKTSRC_DRIVER           0x0f
-#define PRINT_MAC(addr)	\
-	addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]
-
-
-#define RT2860_PCI_DEVICE_ID		0x0601
-
-
-#ifdef RT2870
-#define PCI_MAP_SINGLE(_handle, _ptr, _size, _dir) (ULONG)0
-
-#define PCI_UNMAP_SINGLE(_handle, _ptr, _size, _dir)
-#endif // RT2870 //
-
-
-#define BEACON_FRAME_DMA_CACHE_WBACK(_ptr, _size)	\
-	dma_cache_wback(_ptr, _size)
-
-
-//////////////////////////////////////////
-//
-//////////////////////////////////////////
-
-
-#define NdisMIndicateStatus(_w, _x, _y, _z)
-
-typedef struct timer_list	RTMP_OS_TIMER;
-
-#ifdef RT2870
-/* ----------------- Timer Related MARCO ---------------*/
-// In RT2870, we have a lot of timer functions and will read/write register, it's
-//	not allowed in Linux USB sub-system to do it ( because of sleep issue when submit
-//  to ctrl pipe). So we need a wrapper function to take care it.
-
-typedef VOID (*RT2870_TIMER_HANDLE)(
-	IN  PVOID   SystemSpecific1,
-	IN  PVOID   FunctionContext,
-	IN  PVOID   SystemSpecific2,
-	IN  PVOID   SystemSpecific3);
-#endif // RT2870 //
-
-
-typedef struct  _RALINK_TIMER_STRUCT    {
-    RTMP_OS_TIMER		TimerObj;       // Ndis Timer object
-	BOOLEAN				Valid;			// Set to True when call RTMPInitTimer
-    BOOLEAN             State;          // True if timer cancelled
-    BOOLEAN	      		PeriodicType;	// True if timer is periodic timer
-    BOOLEAN             Repeat;         // True if periodic timer
-    ULONG               TimerValue;     // Timer value in milliseconds
-	ULONG				cookie;			// os specific object
-#ifdef RT2870
-	RT2870_TIMER_HANDLE	handle;
-	void				*pAd;
-#endif // RT2870 //
-}   RALINK_TIMER_STRUCT, *PRALINK_TIMER_STRUCT;
-
-
-#ifdef RT2870
-
-typedef enum _RT2870_KERNEL_THREAD_STATUS_
-{
-	RT2870_THREAD_UNKNOWN = 0,
-	RT2870_THREAD_INITED = 1,
-	RT2870_THREAD_RUNNING = 2,
-	RT2870_THREAD_STOPED = 4,
-}RT2870_KERNEL_THREAD_STATUS;
-
-#define RT2870_THREAD_CAN_DO_INSERT		(RT2870_THREAD_INITED |RT2870_THREAD_RUNNING)
-
-typedef struct _RT2870_TIMER_ENTRY_
-{
-	RALINK_TIMER_STRUCT 			*pRaTimer;
-	struct _RT2870_TIMER_ENTRY_ 	*pNext;
-}RT2870_TIMER_ENTRY;
-
-
-#define TIMER_QUEUE_SIZE_MAX	128
-typedef struct _RT2870_TIMER_QUEUE_
-{
-	unsigned int		status;
-	//wait_queue_head_t 	timerWaitQ;
-	//atomic_t			count;
-	UCHAR				*pTimerQPoll;
-	RT2870_TIMER_ENTRY	*pQPollFreeList;
-	RT2870_TIMER_ENTRY 	*pQHead;
-	RT2870_TIMER_ENTRY 	*pQTail;
-}RT2870_TIMER_QUEUE;
-#endif // RT2870 //
-
-
-//#define DBG	1
-
-//
-//  MACRO for debugging information
-//
-
-#ifdef DBG
-extern ULONG    RTDebugLevel;
-
-#define DBGPRINT_RAW(Level, Fmt)    \
-{                                   \
-    if (Level <= RTDebugLevel)      \
-    {                               \
-        printk Fmt;               \
-    }                               \
-}
-
-#define DBGPRINT(Level, Fmt)    DBGPRINT_RAW(Level, Fmt)
-
-
-#define DBGPRINT_ERR(Fmt)           \
-{                                   \
-    printk("ERROR!!! ");          \
-    printk Fmt;                  \
-}
-
-#define DBGPRINT_S(Status, Fmt)		\
-{									\
-	printk Fmt;					\
-}
-
-
-#else
-#define DBGPRINT(Level, Fmt)
-#define DBGPRINT_RAW(Level, Fmt)
-#define DBGPRINT_S(Status, Fmt)
-#define DBGPRINT_ERR(Fmt)
-#endif
-
-
-//
-//  spin_lock enhanced for Nested spin lock
-//
-#define NdisAllocateSpinLock(__lock)      \
-{                                       \
-    spin_lock_init((spinlock_t *)(__lock));               \
-}
-
-#define NdisFreeSpinLock(lock)          \
-{                                       \
-}
-
-
-#define RTMP_SEM_LOCK(__lock)					\
-{												\
-	spin_lock_bh((spinlock_t *)(__lock));				\
-}
-
-#define RTMP_SEM_UNLOCK(__lock)					\
-{												\
-	spin_unlock_bh((spinlock_t *)(__lock));				\
-}
-
-#if 0 // sample, IRQ LOCK
-#define RTMP_IRQ_LOCK(__lock, __irqflags)					\
-{													\
-	spin_lock_irqsave((spinlock_t *)__lock, __irqflags);	\
-	pAd->irq_disabled |= 1; \
-}
-
-#define RTMP_IRQ_UNLOCK(__lock, __irqflag)						\
-{														\
-	pAd->irq_disabled &= 0; \
-	spin_unlock_irqrestore((spinlock_t *)(__lock), ((unsigned long)__irqflag));	\
-}
-#else
-
-// sample, use semaphore lock to replace IRQ lock, 2007/11/15
-#define RTMP_IRQ_LOCK(__lock, __irqflags)			\
-{													\
-	__irqflags = 0;									\
-	spin_lock_bh((spinlock_t *)(__lock));			\
-	pAd->irq_disabled |= 1; \
-}
-
-#define RTMP_IRQ_UNLOCK(__lock, __irqflag)			\
-{													\
-	pAd->irq_disabled &= 0; \
-	spin_unlock_bh((spinlock_t *)(__lock));			\
-}
-
-#define RTMP_INT_LOCK(__lock, __irqflags)			\
-{													\
-	spin_lock_irqsave((spinlock_t *)__lock, __irqflags);	\
-}
-
-#define RTMP_INT_UNLOCK(__lock, __irqflag)			\
-{													\
-	spin_unlock_irqrestore((spinlock_t *)(__lock), ((unsigned long)__irqflag));	\
-}
-#endif
-
-
-
-#ifdef RT2870
-//Patch for ASIC turst read/write bug, needs to remove after metel fix
-#define RTMP_IO_READ32(_A, _R, _pV)								\
-	RTUSBReadMACRegister(_A, _R, _pV)
-
-#define RTMP_IO_READ8(_A, _R, _pV)								\
-{																\
-}
-
-#define RTMP_IO_WRITE32(_A, _R, _V)								\
-	RTUSBWriteMACRegister(_A, _R, _V)
-
-
-#define RTMP_IO_WRITE8(_A, _R, _V)								\
-{																\
-	USHORT	_Val = _V;											\
-	RTUSBSingleWrite(_A, _R, _Val);								\
-}
-
-
-#define RTMP_IO_WRITE16(_A, _R, _V)								\
-{																\
-	RTUSBSingleWrite(_A, _R, _V);								\
-}
-#endif // RT2870 //
-
-#ifndef wait_event_interruptible_timeout
-#define __wait_event_interruptible_timeout(wq, condition, ret) \
-do { \
-        wait_queue_t __wait; \
-        init_waitqueue_entry(&__wait, current); \
-        add_wait_queue(&wq, &__wait); \
-        for (;;) { \
-                set_current_state(TASK_INTERRUPTIBLE); \
-                if (condition) \
-                        break; \
-                if (!signal_pending(current)) { \
-                        ret = schedule_timeout(ret); \
-                        if (!ret) \
-                                break; \
-                        continue; \
-                } \
-                ret = -ERESTARTSYS; \
-                break; \
-        } \
-        current->state = TASK_RUNNING; \
-        remove_wait_queue(&wq, &__wait); \
-} while (0)
-
-#define wait_event_interruptible_timeout(wq, condition, timeout) \
-({ \
-        long __ret = timeout; \
-        if (!(condition)) \
-                __wait_event_interruptible_timeout(wq, condition, __ret); \
-        __ret; \
-})
-#endif
-#define ONE_TICK 1
-#define OS_WAIT(_time) \
-{	int _i; \
-	long _loop = ((_time)/(1000/OS_HZ)) > 0 ? ((_time)/(1000/OS_HZ)) : 1;\
-	wait_queue_head_t _wait; \
-	init_waitqueue_head(&_wait); \
-	for (_i=0; _i<(_loop); _i++) \
-		wait_event_interruptible_timeout(_wait, 0, ONE_TICK); }
-
-
-typedef void (*TIMER_FUNCTION)(unsigned long);
-
-#define COPY_MAC_ADDR(Addr1, Addr2)             memcpy((Addr1), (Addr2), MAC_ADDR_LEN)
-
-#define MlmeAllocateMemory(_pAd, _ppVA) os_alloc_mem(_pAd, _ppVA, MGMT_DMA_BUFFER_SIZE)
-#define MlmeFreeMemory(_pAd, _pVA)     os_free_mem(_pAd, _pVA)
-
-
-#ifdef RT2870
-#define BUILD_TIMER_FUNCTION(_func)													\
-void linux_##_func(unsigned long data)												\
-{																					\
-	PRALINK_TIMER_STRUCT	_pTimer = (PRALINK_TIMER_STRUCT)data;					\
-	RT2870_TIMER_ENTRY		*_pQNode;												\
-	RTMP_ADAPTER			*_pAd;													\
-																				\
-	_pTimer->handle = _func;															\
-	_pAd = (RTMP_ADAPTER *)_pTimer->pAd;												\
-	_pQNode = RT2870_TimerQ_Insert(_pAd, _pTimer); 									\
-	if ((_pQNode == NULL) && (_pAd->TimerQ.status & RT2870_THREAD_CAN_DO_INSERT))	\
-		RTMP_OS_Add_Timer(&_pTimer->TimerObj, HZ);               					\
-}
-#endif // RT2870 //
-
-
-#define DECLARE_TIMER_FUNCTION(_func)			\
-void linux_##_func(unsigned long data)
-
-#define GET_TIMER_FUNCTION(_func)				\
-		linux_##_func
-
-DECLARE_TIMER_FUNCTION(MlmePeriodicExec);
-DECLARE_TIMER_FUNCTION(MlmeRssiReportExec);
-DECLARE_TIMER_FUNCTION(AsicRxAntEvalTimeout);
-DECLARE_TIMER_FUNCTION(APSDPeriodicExec);
-DECLARE_TIMER_FUNCTION(AsicRfTuningExec);
-#ifdef RT2870
-DECLARE_TIMER_FUNCTION(BeaconUpdateExec);
-#endif // RT2870 //
-
-
-#ifdef CONFIG_STA_SUPPORT
-DECLARE_TIMER_FUNCTION(BeaconTimeout);
-DECLARE_TIMER_FUNCTION(ScanTimeout);
-DECLARE_TIMER_FUNCTION(AuthTimeout);
-DECLARE_TIMER_FUNCTION(AssocTimeout);
-DECLARE_TIMER_FUNCTION(ReassocTimeout);
-DECLARE_TIMER_FUNCTION(DisassocTimeout);
-DECLARE_TIMER_FUNCTION(LinkDownExec);
-#ifdef LEAP_SUPPORT
-DECLARE_TIMER_FUNCTION(LeapAuthTimeout);
-#endif
-DECLARE_TIMER_FUNCTION(StaQuickResponeForRateUpExec);
-DECLARE_TIMER_FUNCTION(WpaDisassocApAndBlockAssoc);
-DECLARE_TIMER_FUNCTION(PsPollWakeExec);
-DECLARE_TIMER_FUNCTION(RadioOnExec);
-
-#ifdef QOS_DLS_SUPPORT
-DECLARE_TIMER_FUNCTION(DlsTimeoutAction);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-void RTMP_GetCurrentSystemTime(LARGE_INTEGER *time);
-
-
-/*
- * packet helper
- * 	- convert internal rt packet to os packet or
- *             os packet to rt packet
- */
-#define RTPKT_TO_OSPKT(_p)		((struct sk_buff *)(_p))
-#define OSPKT_TO_RTPKT(_p)		((PNDIS_PACKET)(_p))
-
-#define GET_OS_PKT_DATAPTR(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->data)
-
-#define GET_OS_PKT_LEN(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->len)
-
-#define GET_OS_PKT_DATATAIL(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->tail)
-
-#define GET_OS_PKT_HEAD(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->head)
-
-#define GET_OS_PKT_END(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->end)
-
-#define GET_OS_PKT_NETDEV(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->dev)
-
-#define GET_OS_PKT_TYPE(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt))
-
-#define GET_OS_PKT_NEXT(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->next)
-
-
-#define OS_NTOHS(_Val) \
-		(ntohs(_Val))
-#define OS_HTONS(_Val) \
-		(htons(_Val))
-#define OS_NTOHL(_Val) \
-		(ntohl(_Val))
-#define OS_HTONL(_Val) \
-		(htonl(_Val))
-
-/* statistics counter */
-#define STATS_INC_RX_PACKETS(_pAd, _dev)
-#define STATS_INC_TX_PACKETS(_pAd, _dev)
-
-#define STATS_INC_RX_BYTESS(_pAd, _dev, len)
-#define STATS_INC_TX_BYTESS(_pAd, _dev, len)
-
-#define STATS_INC_RX_ERRORS(_pAd, _dev)
-#define STATS_INC_TX_ERRORS(_pAd, _dev)
-
-#define STATS_INC_RX_DROPPED(_pAd, _dev)
-#define STATS_INC_TX_DROPPED(_pAd, _dev)
-
-
-#define CB_OFF  10
-
-
-//   check DDK NDIS_PACKET data structure and find out only MiniportReservedEx[0..7] can be used by our driver without
-//   ambiguity. Fields after pPacket->MiniportReservedEx[8] may be used by other wrapper layer thus crashes the driver
-//
-//#define RTMP_GET_PACKET_MR(_p)			(RTPKT_TO_OSPKT(_p))
-
-// User Priority
-#define RTMP_SET_PACKET_UP(_p, _prio)			(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+0] = _prio)
-#define RTMP_GET_PACKET_UP(_p)					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+0])
-
-// Fragment #
-#define RTMP_SET_PACKET_FRAGMENTS(_p, _num)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+1] = _num)
-#define RTMP_GET_PACKET_FRAGMENTS(_p)			(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+1])
-
-// 0x0 ~0x7f: TX to AP's own BSS which has the specified AID. if AID>127, set bit 7 in RTMP_SET_PACKET_EMACTAB too.
-//(this value also as MAC(on-chip WCID) table index)
-// 0x80~0xff: TX to a WDS link. b0~6: WDS index
-#define RTMP_SET_PACKET_WCID(_p, _wdsidx)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+2] = _wdsidx)
-#define RTMP_GET_PACKET_WCID(_p)          		((UCHAR)(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+2]))
-
-// 0xff: PKTSRC_NDIS, others: local TX buffer index. This value affects how to a packet
-#define RTMP_SET_PACKET_SOURCE(_p, _pktsrc)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+3] = _pktsrc)
-#define RTMP_GET_PACKET_SOURCE(_p)       		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+3])
-
-// RTS/CTS-to-self protection method
-#define RTMP_SET_PACKET_RTS(_p, _num)      		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+4] = _num)
-#define RTMP_GET_PACKET_RTS(_p)          		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+4])
-// see RTMP_S(G)ET_PACKET_EMACTAB
-
-// TX rate index
-#define RTMP_SET_PACKET_TXRATE(_p, _rate)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+5] = _rate)
-#define RTMP_GET_PACKET_TXRATE(_p)		  		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+5])
-
-// From which Interface
-#define RTMP_SET_PACKET_IF(_p, _ifdx)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+6] = _ifdx)
-#define RTMP_GET_PACKET_IF(_p)		  		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+6])
-#define RTMP_SET_PACKET_NET_DEVICE_MBSSID(_p, _bss)		RTMP_SET_PACKET_IF((_p), (_bss))
-#define RTMP_SET_PACKET_NET_DEVICE_WDS(_p, _bss)		RTMP_SET_PACKET_IF((_p), ((_bss) + MIN_NET_DEVICE_FOR_WDS))
-#define RTMP_SET_PACKET_NET_DEVICE_APCLI(_p, _idx)   	RTMP_SET_PACKET_IF((_p), ((_idx) + MIN_NET_DEVICE_FOR_APCLI))
-#define RTMP_SET_PACKET_NET_DEVICE_MESH(_p, _idx)   	RTMP_SET_PACKET_IF((_p), ((_idx) + MIN_NET_DEVICE_FOR_MESH))
-#define RTMP_GET_PACKET_NET_DEVICE_MBSSID(_p)			RTMP_GET_PACKET_IF((_p))
-#define RTMP_GET_PACKET_NET_DEVICE(_p)					RTMP_GET_PACKET_IF((_p))
-
-#define RTMP_SET_PACKET_MOREDATA(_p, _morebit)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+7] = _morebit)
-#define RTMP_GET_PACKET_MOREDATA(_p)				(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+7])
-
-//#define RTMP_SET_PACKET_NET_DEVICE_MBSSID(_p, _bss)	(RTPKT_TO_OSPKT(_p)->cb[8] = _bss)
-//#define RTMP_GET_PACKET_NET_DEVICE_MBSSID(_p)		(RTPKT_TO_OSPKT(_p)->cb[8])
-
-
-
-
-#if 0
-//#define RTMP_SET_PACKET_DHCP(_p, _flg)   	(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] = _flg)
-//#define RTMP_GET_PACKET_DHCP(_p)         	(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11])
-#else
-//
-//	Sepcific Pakcet Type definition
-//
-#define RTMP_PACKET_SPECIFIC_CB_OFFSET	11
-
-#define RTMP_PACKET_SPECIFIC_DHCP		0x01
-#define RTMP_PACKET_SPECIFIC_EAPOL		0x02
-#define RTMP_PACKET_SPECIFIC_IPV4		0x04
-#define RTMP_PACKET_SPECIFIC_WAI		0x08
-#define RTMP_PACKET_SPECIFIC_VLAN		0x10
-#define RTMP_PACKET_SPECIFIC_LLCSNAP	0x20
-
-//Specific
-#define RTMP_SET_PACKET_SPECIFIC(_p, _flg)	   	(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] = _flg)
-
-//DHCP
-#define RTMP_SET_PACKET_DHCP(_p, _flg)   													\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_DHCP);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_DHCP);	\
-			}while(0)
-#define RTMP_GET_PACKET_DHCP(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_DHCP)
-
-//EAPOL
-#define RTMP_SET_PACKET_EAPOL(_p, _flg)   													\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_EAPOL);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_EAPOL);	\
-			}while(0)
-#define RTMP_GET_PACKET_EAPOL(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_EAPOL)
-
-//WAI
-#define RTMP_SET_PACKET_WAI(_p, _flg)   													\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_WAI);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_WAI);	\
-			}while(0)
-#define RTMP_GET_PACKET_WAI(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_WAI)
-
-#define RTMP_GET_PACKET_LOWRATE(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & (RTMP_PACKET_SPECIFIC_EAPOL | RTMP_PACKET_SPECIFIC_DHCP | RTMP_PACKET_SPECIFIC_WAI))
-
-//VLAN
-#define RTMP_SET_PACKET_VLAN(_p, _flg)   													\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_VLAN);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_VLAN);	\
-			}while(0)
-#define RTMP_GET_PACKET_VLAN(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_VLAN)
-
-//LLC/SNAP
-#define RTMP_SET_PACKET_LLCSNAP(_p, _flg)   													\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_LLCSNAP);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_LLCSNAP);		\
-			}while(0)
-
-#define RTMP_GET_PACKET_LLCSNAP(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_LLCSNAP)
-
-// IP
-#define RTMP_SET_PACKET_IPV4(_p, _flg)														\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_IPV4);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_IPV4);	\
-			}while(0)
-
-#define RTMP_GET_PACKET_IPV4(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_IPV4)
-
-#endif
-
-
-// If this flag is set, it indicates that this EAPoL frame MUST be clear.
-#define RTMP_SET_PACKET_CLEAR_EAP_FRAME(_p, _flg)   (RTPKT_TO_OSPKT(_p)->cb[CB_OFF+12] = _flg)
-#define RTMP_GET_PACKET_CLEAR_EAP_FRAME(_p)         (RTPKT_TO_OSPKT(_p)->cb[CB_OFF+12])
-
-#define RTMP_SET_PACKET_5VT(_p, _flg)   (RTPKT_TO_OSPKT(_p)->cb[CB_OFF+22] = _flg)
-#define RTMP_GET_PACKET_5VT(_p)         (RTPKT_TO_OSPKT(_p)->cb[CB_OFF+22])
-
-
-#ifdef CONFIG_5VT_ENHANCE
-#define BRIDGE_TAG 0x35564252    // depends on 5VT define in br_input.c
-#endif
-
-
-#define NDIS_SET_PACKET_STATUS(_p, _status)
-
-
-#define GET_SG_LIST_FROM_PACKET(_p, _sc)	\
-    rt_get_sg_list_from_packet(_p, _sc)
-
-
-#define NdisMoveMemory(Destination, Source, Length) memmove(Destination, Source, Length)
-#define NdisZeroMemory(Destination, Length)         memset(Destination, 0, Length)
-#define NdisFillMemory(Destination, Length, Fill)   memset(Destination, Fill, Length)
-#define NdisEqualMemory(Source1, Source2, Length)   (!memcmp(Source1, Source2, Length))
-#define RTMPEqualMemory(Source1, Source2, Length)	(!memcmp(Source1, Source2, Length))
-
-
-#define RTMP_INC_REF(_A)		0
-#define RTMP_DEC_REF(_A)		0
-#define RTMP_GET_REF(_A)		0
-
-
-
-/*
- * ULONG
- * RTMP_GetPhysicalAddressLow(
- *   IN NDIS_PHYSICAL_ADDRESS  PhysicalAddress);
- */
-#define RTMP_GetPhysicalAddressLow(PhysicalAddress)		(PhysicalAddress)
-
-/*
- * ULONG
- * RTMP_GetPhysicalAddressHigh(
- *   IN NDIS_PHYSICAL_ADDRESS  PhysicalAddress);
- */
-#define RTMP_GetPhysicalAddressHigh(PhysicalAddress)		(0)
-
-/*
- * VOID
- * RTMP_SetPhysicalAddressLow(
- *   IN NDIS_PHYSICAL_ADDRESS  PhysicalAddress,
- *   IN ULONG  Value);
- */
-#define RTMP_SetPhysicalAddressLow(PhysicalAddress, Value)	\
-			PhysicalAddress = Value;
-
-/*
- * VOID
- * RTMP_SetPhysicalAddressHigh(
- *   IN NDIS_PHYSICAL_ADDRESS  PhysicalAddress,
- *   IN ULONG  Value);
- */
-#define RTMP_SetPhysicalAddressHigh(PhysicalAddress, Value)
-
-
-//CONTAINING_RECORD(pEntry, NDIS_PACKET, MiniportReservedEx);
-#define QUEUE_ENTRY_TO_PACKET(pEntry) \
-	(PNDIS_PACKET)(pEntry)
-
-#define PACKET_TO_QUEUE_ENTRY(pPacket) \
-	(PQUEUE_ENTRY)(pPacket)
-
-
-#ifndef CONTAINING_RECORD
-#define CONTAINING_RECORD(address, type, field)			\
-((type *)((PCHAR)(address) - offsetof(type, field)))
-#endif
-
-
-#define RELEASE_NDIS_PACKET(_pAd, _pPacket, _Status)                    \
-{                                                                       \
-        RTMPFreeNdisPacket(_pAd, _pPacket);                             \
-}
-
-
-#define SWITCH_PhyAB(_pAA, _pBB)    \
-{                                                                           \
-    ULONG	AABasePaHigh;                           \
-    ULONG	AABasePaLow;                           \
-    ULONG	BBBasePaHigh;                           \
-    ULONG	BBBasePaLow;                           \
-    BBBasePaHigh = RTMP_GetPhysicalAddressHigh(_pBB);                                                 \
-    BBBasePaLow = RTMP_GetPhysicalAddressLow(_pBB);                                                 \
-    AABasePaHigh = RTMP_GetPhysicalAddressHigh(_pAA);                                                 \
-    AABasePaLow = RTMP_GetPhysicalAddressLow(_pAA);                                                 \
-    RTMP_SetPhysicalAddressHigh(_pAA, BBBasePaHigh);                                                 \
-    RTMP_SetPhysicalAddressLow(_pAA, BBBasePaLow);                                                 \
-    RTMP_SetPhysicalAddressHigh(_pBB, AABasePaHigh);                                                 \
-    RTMP_SetPhysicalAddressLow(_pBB, AABasePaLow);                                                 \
-}
-
-
-#define NdisWriteErrorLogEntry(_a, _b, _c, _d)
-#define NdisMAllocateMapRegisters(_a, _b, _c, _d, _e)		NDIS_STATUS_SUCCESS
-
-
-#define NdisAcquireSpinLock		RTMP_SEM_LOCK
-#define NdisReleaseSpinLock		RTMP_SEM_UNLOCK
-
-static inline void NdisGetSystemUpTime(ULONG *time)
-{
-	*time = jiffies;
-}
-
-//pPacket = CONTAINING_RECORD(pEntry, NDIS_PACKET, MiniportReservedEx);
-#define QUEUE_ENTRY_TO_PKT(pEntry) \
-		((PNDIS_PACKET) (pEntry))
-
-int rt28xx_packet_xmit(struct sk_buff *skb);
-
-
-
-void rtmp_os_thread_init(PUCHAR pThreadName, PVOID pNotify);
-
-
+#include "../rt2860/rt_linux.h"
diff --git a/drivers/staging/rt2870/rt_main_dev.c b/drivers/staging/rt2870/rt_main_dev.c
index 48ad411..121e163 100644
--- a/drivers/staging/rt2870/rt_main_dev.c
+++ b/drivers/staging/rt2870/rt_main_dev.c
@@ -1,1865 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    rt_main_dev.c
-
-    Abstract:
-    Create and register network interface.
-
-    Revision History:
-    Who         When            What
-    --------    ----------      ----------------------------------------------
-	Sample		Mar/21/07		Merge RT2870 and RT2860 drivers.
-*/
-
-#include "rt_config.h"
-
-#define FORTY_MHZ_INTOLERANT_INTERVAL	(60*1000) // 1 min
-
-#ifdef MULTIPLE_CARD_SUPPORT
-// record whether the card in the card list is used in the card file
-UINT8  MC_CardUsed[MAX_NUM_OF_MULTIPLE_CARD];
-// record used card mac address in the card list
-static UINT8  MC_CardMac[MAX_NUM_OF_MULTIPLE_CARD][6];
-#endif // MULTIPLE_CARD_SUPPORT //
-
-/*---------------------------------------------------------------------*/
-/* Private Variables Used                                              */
-/*---------------------------------------------------------------------*/
-//static RALINK_TIMER_STRUCT     PeriodicTimer;
-
-char *mac = "";		   // default 00:00:00:00:00:00
-char *hostname = "";
-#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,12)
-MODULE_PARM (mac, "s");
-#else
-module_param (mac, charp, 0);
-#endif
-MODULE_PARM_DESC (mac, "rt28xx: wireless mac addr");
-
-
-/*---------------------------------------------------------------------*/
-/* Prototypes of Functions Used                                        */
-/*---------------------------------------------------------------------*/
-#ifdef DOT11_N_SUPPORT
-extern BOOLEAN ba_reordering_resource_init(PRTMP_ADAPTER pAd, int num);
-extern void ba_reordering_resource_release(PRTMP_ADAPTER pAd);
-#endif // DOT11_N_SUPPORT //
-extern NDIS_STATUS NICLoadRateSwitchingParams(IN PRTMP_ADAPTER pAd);
-
-
-// public function prototype
-INT __devinit rt28xx_probe(IN void *_dev_p, IN void *_dev_id_p,
-							IN UINT argc, OUT PRTMP_ADAPTER *ppAd);
-
-// private function prototype
-static int rt28xx_init(IN struct net_device *net_dev);
-INT rt28xx_send_packets(IN struct sk_buff *skb_p, IN struct net_device *net_dev);
-
-#if LINUX_VERSION_CODE <= 0x20402	// Red Hat 7.1
-struct net_device *alloc_netdev(
-	int sizeof_priv,
-	const char *mask,
-	void (*setup)(struct net_device *));
-#endif // LINUX_VERSION_CODE //
-
-static void CfgInitHook(PRTMP_ADAPTER pAd);
-//static BOOLEAN RT28XXAvailRANameAssign(IN CHAR *name_p);
-
-#ifdef CONFIG_STA_SUPPORT
-extern	const struct iw_handler_def rt28xx_iw_handler_def;
-#endif // CONFIG_STA_SUPPORT //
-
-#if WIRELESS_EXT >= 12
-// This function will be called when query /proc
-struct iw_statistics *rt28xx_get_wireless_stats(
-    IN struct net_device *net_dev);
-#endif
-
-struct net_device_stats *RT28xx_get_ether_stats(
-    IN  struct net_device *net_dev);
-
-/*
-========================================================================
-Routine Description:
-    Close raxx interface.
-
-Arguments:
-	*net_dev			the raxx interface pointer
-
-Return Value:
-    0					Open OK
-	otherwise			Open Fail
-
-Note:
-	1. if open fail, kernel will not call the close function.
-	2. Free memory for
-		(1) Mlme Memory Handler:		MlmeHalt()
-		(2) TX & RX:					RTMPFreeTxRxRingMemory()
-		(3) BA Reordering: 				ba_reordering_resource_release()
-========================================================================
-*/
-int MainVirtualIF_close(IN struct net_device *net_dev)
-{
-    RTMP_ADAPTER *pAd = net_dev->ml_priv;
-
-	// Sanity check for pAd
-	if (pAd == NULL)
-		return 0; // close ok
-
-	netif_carrier_off(pAd->net_dev);
-	netif_stop_queue(pAd->net_dev);
-
-
-
-	VIRTUAL_IF_DOWN(pAd);
-
-	RT_MOD_DEC_USE_COUNT();
-
-	return 0; // close ok
-}
-
-/*
-========================================================================
-Routine Description:
-    Open raxx interface.
-
-Arguments:
-	*net_dev			the raxx interface pointer
-
-Return Value:
-    0					Open OK
-	otherwise			Open Fail
-
-Note:
-	1. if open fail, kernel will not call the close function.
-	2. Free memory for
-		(1) Mlme Memory Handler:		MlmeHalt()
-		(2) TX & RX:					RTMPFreeTxRxRingMemory()
-		(3) BA Reordering: 				ba_reordering_resource_release()
-========================================================================
-*/
-int MainVirtualIF_open(IN struct net_device *net_dev)
-{
-    RTMP_ADAPTER *pAd = net_dev->ml_priv;
-
-	// Sanity check for pAd
-	if (pAd == NULL)
-		return 0; // close ok
-
-	if (VIRTUAL_IF_UP(pAd) != 0)
-		return -1;
-
-	// increase MODULE use count
-	RT_MOD_INC_USE_COUNT();
-
-	netif_start_queue(net_dev);
-	netif_carrier_on(net_dev);
-	netif_wake_queue(net_dev);
-
-	return 0;
-}
-
-/*
-========================================================================
-Routine Description:
-    Close raxx interface.
-
-Arguments:
-	*net_dev			the raxx interface pointer
-
-Return Value:
-    0					Open OK
-	otherwise			Open Fail
-
-Note:
-	1. if open fail, kernel will not call the close function.
-	2. Free memory for
-		(1) Mlme Memory Handler:		MlmeHalt()
-		(2) TX & RX:					RTMPFreeTxRxRingMemory()
-		(3) BA Reordering: 				ba_reordering_resource_release()
-========================================================================
-*/
-int rt28xx_close(IN PNET_DEV dev)
-{
-	struct net_device * net_dev = (struct net_device *)dev;
-    RTMP_ADAPTER	*pAd = net_dev->ml_priv;
-	BOOLEAN 		Cancelled = FALSE;
-	UINT32			i = 0;
-#ifdef RT2870
-	DECLARE_WAIT_QUEUE_HEAD(unlink_wakeup);
-	DECLARE_WAITQUEUE(wait, current);
-
-	//RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_REMOVE_IN_PROGRESS);
-#endif // RT2870 //
-
-
-    DBGPRINT(RT_DEBUG_TRACE, ("===> rt28xx_close\n"));
-
-	// Sanity check for pAd
-	if (pAd == NULL)
-		return 0; // close ok
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-
-		// If dirver doesn't wake up firmware here,
-		// NICLoadFirmware will hang forever when interface is up again.
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-        {
-		    AsicForceWakeup(pAd, TRUE);
-        }
-
-#ifdef QOS_DLS_SUPPORT
-		// send DLS-TEAR_DOWN message,
-		if (pAd->CommonCfg.bDLSCapable)
-		{
-			UCHAR i;
-
-			// tear down local dls table entry
-			for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-				{
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-					pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				}
-			}
-
-			// tear down peer dls table entry
-			for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-				{
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				}
-			}
-			RT28XX_MLME_HANDLER(pAd);
-		}
-#endif // QOS_DLS_SUPPORT //
-
-		if (INFRA_ON(pAd) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-		{
-			MLME_DISASSOC_REQ_STRUCT	DisReq;
-			MLME_QUEUE_ELEM *MsgElem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-
-			COPY_MAC_ADDR(DisReq.Addr, pAd->CommonCfg.Bssid);
-			DisReq.Reason =  REASON_DEAUTH_STA_LEAVING;
-
-			MsgElem->Machine = ASSOC_STATE_MACHINE;
-			MsgElem->MsgType = MT2_MLME_DISASSOC_REQ;
-			MsgElem->MsgLen = sizeof(MLME_DISASSOC_REQ_STRUCT);
-			NdisMoveMemory(MsgElem->Msg, &DisReq, sizeof(MLME_DISASSOC_REQ_STRUCT));
-
-			// Prevent to connect AP again in STAMlmePeriodicExec
-			pAd->MlmeAux.AutoReconnectSsidLen= 32;
-			NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen);
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_DISASSOC;
-			MlmeDisassocReqAction(pAd, MsgElem);
-			kfree(MsgElem);
-
-			RTMPusecDelay(1000);
-		}
-
-#ifdef RT2870
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_REMOVE_IN_PROGRESS);
-#endif // RT2870 //
-
-#ifdef CCX_SUPPORT
-		RTMPCancelTimer(&pAd->StaCfg.LeapAuthTimer, &Cancelled);
-#endif
-
-		RTMPCancelTimer(&pAd->StaCfg.StaQuickResponeForRateUpTimer, &Cancelled);
-		RTMPCancelTimer(&pAd->StaCfg.WpaDisassocAndBlockAssocTimer, &Cancelled);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-		{
-			union iwreq_data    wrqu;
-			// send wireless event to wpa_supplicant for infroming interface down.
-			memset(&wrqu, 0, sizeof(wrqu));
-			wrqu.data.flags = RT_INTERFACE_DOWN;
-			wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-		}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-		MlmeRadioOff(pAd);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS);
-
-	for (i = 0 ; i < NUM_OF_TX_RING; i++)
-	{
-		while (pAd->DeQueueRunning[i] == TRUE)
-		{
-			printk("Waiting for TxQueue[%d] done..........\n", i);
-			RTMPusecDelay(1000);
-		}
-	}
-
-#ifdef RT2870
-	// ensure there are no more active urbs.
-	add_wait_queue (&unlink_wakeup, &wait);
-	pAd->wait = &unlink_wakeup;
-
-	// maybe wait for deletions to finish.
-	i = 0;
-	//while((i < 25) && atomic_read(&pAd->PendingRx) > 0)
-	while(i < 25)
-	{
-		unsigned long IrqFlags;
-
-		RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-		if (pAd->PendingRx == 0)
-		{
-			RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-			break;
-		}
-		RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-
-#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,9)
-		msleep(UNLINK_TIMEOUT_MS);	//Time in millisecond
-#else
-		RTMPusecDelay(UNLINK_TIMEOUT_MS*1000);	//Time in microsecond
-#endif
-		i++;
-	}
-	pAd->wait = NULL;
-	remove_wait_queue (&unlink_wakeup, &wait);
-#endif // RT2870 //
-
-	//RTUSBCleanUpMLMEWaitQueue(pAd);	/*not used in RT28xx*/
-
-
-#ifdef RT2870
-	// We need clear timerQ related structure before exits of the timer thread.
-	RT2870_TimerQ_Exit(pAd);
-	// Close kernel threads or tasklets
-	RT28xxThreadTerminate(pAd);
-#endif // RT2870 //
-
-	// Stop Mlme state machine
-	MlmeHalt(pAd);
-
-	// Close kernel threads or tasklets
-	kill_thread_task(pAd);
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		MacTableReset(pAd);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-
-	MeasureReqTabExit(pAd);
-	TpcReqTabExit(pAd);
-
-
-
-
-	// Free Ring or USB buffers
-	RTMPFreeTxRxRingMemory(pAd);
-
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS);
-
-#ifdef DOT11_N_SUPPORT
-	// Free BA reorder resource
-	ba_reordering_resource_release(pAd);
-#endif // DOT11_N_SUPPORT //
-
-#ifdef RT2870
-#ifdef INF_AMAZON_SE
-	if (pAd->UsbVendorReqBuf)
-		os_free_mem(pAd, pAd->UsbVendorReqBuf);
-#endif // INF_AMAZON_SE //
-#endif // RT2870 //
-
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_START_UP);
-
-	return 0; // close ok
-} /* End of rt28xx_close */
-
-static int rt28xx_init(IN struct net_device *net_dev)
-{
-	PRTMP_ADAPTER 			pAd = net_dev->ml_priv;
-	UINT					index;
-	UCHAR					TmpPhy;
-	NDIS_STATUS				Status;
-	UINT32 		MacCsr0 = 0;
-
-#ifdef RT2870
-#ifdef INF_AMAZON_SE
-	init_MUTEX(&(pAd->UsbVendorReq_semaphore));
-	os_alloc_mem(pAd, (PUCHAR)&pAd->UsbVendorReqBuf, MAX_PARAM_BUFFER_SIZE - 1);
-	if (pAd->UsbVendorReqBuf == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Allocate vendor request temp buffer failed!\n"));
-		goto err0;
-	}
-#endif // INF_AMAZON_SE //
-#endif // RT2870 //
-
-#ifdef DOT11_N_SUPPORT
-	// Allocate BA Reordering memory
-	ba_reordering_resource_init(pAd, MAX_REORDERING_MPDU_NUM);
-#endif // DOT11_N_SUPPORT //
-
-	// Make sure MAC gets ready.
-	index = 0;
-	do
-	{
-		RTMP_IO_READ32(pAd, MAC_CSR0, &MacCsr0);
-		pAd->MACVersion = MacCsr0;
-
-		if ((pAd->MACVersion != 0x00) && (pAd->MACVersion != 0xFFFFFFFF))
-			break;
-
-		RTMPusecDelay(10);
-	} while (index++ < 100);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("MAC_CSR0  [ Ver:Rev=0x%08x]\n", pAd->MACVersion));
-
-	// Disable DMA
-	RT28XXDMADisable(pAd);
-
-
-	// Load 8051 firmware
-	Status = NICLoadFirmware(pAd);
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT_ERR(("NICLoadFirmware failed, Status[=0x%08x]\n", Status));
-		goto err1;
-	}
-
-	NICLoadRateSwitchingParams(pAd);
-
-	// Disable interrupts here which is as soon as possible
-	// This statement should never be true. We might consider to remove it later
-
-	Status = RTMPAllocTxRxRingMemory(pAd);
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT_ERR(("RTMPAllocDMAMemory failed, Status[=0x%08x]\n", Status));
-		goto err1;
-	}
-
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE);
-
-	// initialize MLME
-	//
-
-	Status = MlmeInit(pAd);
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT_ERR(("MlmeInit failed, Status[=0x%08x]\n", Status));
-		goto err2;
-	}
-
-	// Initialize pAd->StaCfg, pAd->ApCfg, pAd->CommonCfg to manufacture default
-	//
-	UserCfgInit(pAd);
-
-#ifdef RT2870
-	// We need init timerQ related structure before create the timer thread.
-	RT2870_TimerQ_Init(pAd);
-#endif // RT2870 //
-
-	RT28XX_TASK_THREAD_INIT(pAd, Status);
-	if (Status != NDIS_STATUS_SUCCESS)
-		goto err1;
-
-//	COPY_MAC_ADDR(pAd->ApCfg.MBSSID[apidx].Bssid, netif->hwaddr);
-//	pAd->bForcePrintTX = TRUE;
-
-	CfgInitHook(pAd);
-
-
-#ifdef BLOCK_NET_IF
-	initblockQueueTab(pAd);
-#endif // BLOCK_NET_IF //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		NdisAllocateSpinLock(&pAd->MacTabLock);
-#endif // CONFIG_STA_SUPPORT //
-
-	MeasureReqTabInit(pAd);
-	TpcReqTabInit(pAd);
-
-	//
-	// Init the hardware, we need to init asic before read registry, otherwise mac register will be reset
-	//
-	Status = NICInitializeAdapter(pAd, TRUE);
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT_ERR(("NICInitializeAdapter failed, Status[=0x%08x]\n", Status));
-		if (Status != NDIS_STATUS_SUCCESS)
-		goto err3;
-	}
-
-	// Read parameters from Config File
-	Status = RTMPReadParametersHook(pAd);
-
-	printk("1. Phy Mode = %d\n", pAd->CommonCfg.PhyMode);
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT_ERR(("NICReadRegParameters failed, Status[=0x%08x]\n",Status));
-		goto err4;
-	}
-
-#ifdef RT2870
-	pAd->CommonCfg.bMultipleIRP = FALSE;
-
-	if (pAd->CommonCfg.bMultipleIRP)
-		pAd->CommonCfg.NumOfBulkInIRP = RX_RING_SIZE;
-	else
-		pAd->CommonCfg.NumOfBulkInIRP = 1;
-#endif // RT2870 //
-
-
-   	//Init Ba Capability parameters.
-//	RT28XX_BA_INIT(pAd);
-#ifdef DOT11_N_SUPPORT
-	pAd->CommonCfg.DesiredHtPhy.MpduDensity = (UCHAR)pAd->CommonCfg.BACapability.field.MpduDensity;
-	pAd->CommonCfg.DesiredHtPhy.AmsduEnable = (USHORT)pAd->CommonCfg.BACapability.field.AmsduEnable;
-	pAd->CommonCfg.DesiredHtPhy.AmsduSize = (USHORT)pAd->CommonCfg.BACapability.field.AmsduSize;
-	pAd->CommonCfg.DesiredHtPhy.MimoPs = (USHORT)pAd->CommonCfg.BACapability.field.MMPSmode;
-	// UPdata to HT IE
-	pAd->CommonCfg.HtCapability.HtCapInfo.MimoPs = (USHORT)pAd->CommonCfg.BACapability.field.MMPSmode;
-	pAd->CommonCfg.HtCapability.HtCapInfo.AMsduSize = (USHORT)pAd->CommonCfg.BACapability.field.AmsduSize;
-	pAd->CommonCfg.HtCapability.HtCapParm.MpduDensity = (UCHAR)pAd->CommonCfg.BACapability.field.MpduDensity;
-#endif // DOT11_N_SUPPORT //
-
-	// after reading Registry, we now know if in AP mode or STA mode
-
-	// Load 8051 firmware; crash when FW image not existent
-	// Status = NICLoadFirmware(pAd);
-	// if (Status != NDIS_STATUS_SUCCESS)
-	//    break;
-
-	printk("2. Phy Mode = %d\n", pAd->CommonCfg.PhyMode);
-
-	// We should read EEPROM for all cases.  rt2860b
-	NICReadEEPROMParameters(pAd, mac);
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-	printk("3. Phy Mode = %d\n", pAd->CommonCfg.PhyMode);
-
-	NICInitAsicFromEEPROM(pAd); //rt2860b
-
-	// Set PHY to appropriate mode
-	TmpPhy = pAd->CommonCfg.PhyMode;
-	pAd->CommonCfg.PhyMode = 0xff;
-	RTMPSetPhyMode(pAd, TmpPhy);
-#ifdef DOT11_N_SUPPORT
-	SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-
-	// No valid channels.
-	if (pAd->ChannelListNum == 0)
-	{
-		printk("Wrong configuration. No valid channel found. Check \"ContryCode\" and \"ChannelGeography\" setting.\n");
-		goto err4;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	printk("MCS Set = %02x %02x %02x %02x %02x\n", pAd->CommonCfg.HtCapability.MCSSet[0],
-           pAd->CommonCfg.HtCapability.MCSSet[1], pAd->CommonCfg.HtCapability.MCSSet[2],
-           pAd->CommonCfg.HtCapability.MCSSet[3], pAd->CommonCfg.HtCapability.MCSSet[4]);
-#endif // DOT11_N_SUPPORT //
-
-#ifdef RT2870
-    //Init RT30xx RFRegisters after read RFIC type from EEPROM
-	NICInitRT30xxRFRegisters(pAd);
-#endif // RT2870 //
-
-#if 0
-	// Patch cardbus controller if EEPROM said so.
-	if (pAd->bTest1 == FALSE)
-		RTMPPatchCardBus(pAd);
-#endif
-
-
-//		APInitialize(pAd);
-
-#ifdef IKANOS_VX_1X0
-	VR_IKANOS_FP_Init(pAd->ApCfg.BssidNum, pAd->PermanentAddress);
-#endif // IKANOS_VX_1X0 //
-
-		//
-	// Initialize RF register to default value
-	//
-	AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-	AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-
-	// 8051 firmware require the signal during booting time.
-	AsicSendCommandToMcu(pAd, 0x72, 0xFF, 0x00, 0x00);
-
-	if (pAd && (Status != NDIS_STATUS_SUCCESS))
-	{
-		//
-		// Undo everything if it failed
-		//
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-		{
-//			NdisMDeregisterInterrupt(&pAd->Interrupt);
-			RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE);
-		}
-//		RTMPFreeAdapter(pAd); // we will free it in disconnect()
-	}
-	else if (pAd)
-	{
-		// Microsoft HCT require driver send a disconnect event after driver initialization.
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-//		pAd->IndicateMediaState = NdisMediaStateDisconnected;
-		RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_MEDIA_STATE_CHANGE);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event B!\n"));
-
-
-#ifdef RT2870
-		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS);
-		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_REMOVE_IN_PROGRESS);
-
-		//
-		// Support multiple BulkIn IRP,
-		// the value on pAd->CommonCfg.NumOfBulkInIRP may be large than 1.
-		//
-		for(index=0; index<pAd->CommonCfg.NumOfBulkInIRP; index++)
-		{
-			RTUSBBulkReceive(pAd);
-			DBGPRINT(RT_DEBUG_TRACE, ("RTUSBBulkReceive!\n" ));
-		}
-#endif // RT2870 //
-	}// end of else
-
-
-	DBGPRINT_S(Status, ("<==== RTMPInitialize, Status=%x\n", Status));
-
-	return TRUE;
-
-
-err4:
-err3:
-	MlmeHalt(pAd);
-err2:
-	RTMPFreeTxRxRingMemory(pAd);
-//	RTMPFreeAdapter(pAd);
-err1:
-
-#ifdef DOT11_N_SUPPORT
-	os_free_mem(pAd, pAd->mpdu_blk_pool.mem); // free BA pool
-#endif // DOT11_N_SUPPORT //
-	RT28XX_IRQ_RELEASE(net_dev);
-
-	// shall not set ml_priv to NULL here because the ml_priv didn't been free yet.
-	//net_dev->ml_priv = 0;
-#ifdef INF_AMAZON_SE
-err0:
-#endif // INF_AMAZON_SE //
-	printk("!!! %s Initialized fail !!!\n", RT28xx_CHIP_NAME);
-	return FALSE;
-} /* End of rt28xx_init */
-
-
-/*
-========================================================================
-Routine Description:
-    Open raxx interface.
-
-Arguments:
-	*net_dev			the raxx interface pointer
-
-Return Value:
-    0					Open OK
-	otherwise			Open Fail
-
-Note:
-========================================================================
-*/
-int rt28xx_open(IN PNET_DEV dev)
-{
-	struct net_device * net_dev = (struct net_device *)dev;
-	PRTMP_ADAPTER pAd = net_dev->ml_priv;
-	int retval = 0;
- 	POS_COOKIE pObj;
-
-
-	// Sanity check for pAd
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -1;
-	}
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	if (pAd->OpMode == OPMODE_AP)
-	{
-		CW_MAX_IN_BITS = 6;
-	}
-	else if (pAd->OpMode == OPMODE_STA)
-	{
-		CW_MAX_IN_BITS = 10;
-	}
-
-#if WIRELESS_EXT >= 12
-	if (net_dev->priv_flags == INT_MAIN)
-	{
-		if (pAd->OpMode == OPMODE_AP)
-			net_dev->wireless_handlers = (struct iw_handler_def *) &rt28xx_ap_iw_handler_def;
-		else if (pAd->OpMode == OPMODE_STA)
-			net_dev->wireless_handlers = (struct iw_handler_def *) &rt28xx_iw_handler_def;
-	}
-#endif // WIRELESS_EXT >= 12 //
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-	// Init
- 	pObj = (POS_COOKIE)pAd->OS_Cookie;
-
-	// reset Adapter flags
-	RTMP_CLEAR_FLAGS(pAd);
-
-	// Request interrupt service routine for PCI device
-	// register the interrupt routine with the os
-	RT28XX_IRQ_REQUEST(net_dev);
-
-
-	// Init BssTab & ChannelInfo tabbles for auto channel select.
-
-
-	// Chip & other init
-	if (rt28xx_init(net_dev) == FALSE)
-		goto err;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		NdisZeroMemory(pAd->StaCfg.dev_name, 16);
-		NdisMoveMemory(pAd->StaCfg.dev_name, net_dev->name, strlen(net_dev->name));
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Set up the Mac address
-	NdisMoveMemory(net_dev->dev_addr, (void *) pAd->CurrentAddress, 6);
-
-	// Init IRQ parameters
-	RT28XX_IRQ_INIT(pAd);
-
-	// Various AP function init
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-		{
-			union iwreq_data    wrqu;
-			// send wireless event to wpa_supplicant for infroming interface down.
-			memset(&wrqu, 0, sizeof(wrqu));
-			wrqu.data.flags = RT_INTERFACE_UP;
-			wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-		}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Enable Interrupt
-	RT28XX_IRQ_ENABLE(pAd);
-
-	// Now Enable RxTx
-	RTMPEnableRxTx(pAd);
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_START_UP);
-
-	{
-	UINT32 reg = 0;
-	RTMP_IO_READ32(pAd, 0x1300, &reg);  // clear garbage interrupts
-	printk("0x1300 = %08x\n", reg);
-	}
-
-	{
-//	u32 reg;
-//	u8  byte;
-//	u16 tmp;
-
-//	RTMP_IO_READ32(pAd, XIFS_TIME_CFG, &reg);
-
-//	tmp = 0x0805;
-//	reg  = (reg & 0xffff0000) | tmp;
-//	RTMP_IO_WRITE32(pAd, XIFS_TIME_CFG, reg);
-
-	}
-
-#if 0
-	/*
-	 * debugging helper
-	 * 		show the size of main table in Adapter structure
-	 *		MacTab  -- 185K
-	 *		BATable -- 137K
-	 * 		Total 	-- 385K  !!!!! (5/26/2006)
-	 */
-	printk("sizeof(pAd->MacTab) = %ld\n", sizeof(pAd->MacTab));
-	printk("sizeof(pAd->AccessControlList) = %ld\n", sizeof(pAd->AccessControlList));
-	printk("sizeof(pAd->ApCfg) = %ld\n", sizeof(pAd->ApCfg));
-	printk("sizeof(pAd->BATable) = %ld\n", sizeof(pAd->BATable));
-	BUG();
-#endif
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-	return (retval);
-
-err:
-	return (-1);
-} /* End of rt28xx_open */
-
-static const struct net_device_ops rt2870_netdev_ops = {
-	.ndo_open		= MainVirtualIF_open,
-	.ndo_stop		= MainVirtualIF_close,
-	.ndo_do_ioctl		= rt28xx_ioctl,
-	.ndo_get_stats		= RT28xx_get_ether_stats,
-	.ndo_validate_addr	= NULL,
-	.ndo_set_mac_address	= eth_mac_addr,
-	.ndo_change_mtu		= eth_change_mtu,
-#ifdef IKANOS_VX_1X0
-	.ndo_start_xmit		= IKANOS_DataFramesTx,
-#else
-	.ndo_start_xmit		= rt28xx_send_packets,
-#endif
-};
-
-/* Must not be called for mdev and apdev */
-static NDIS_STATUS rt_ieee80211_if_setup(struct net_device *dev, PRTMP_ADAPTER pAd)
-{
-	NDIS_STATUS Status;
-	INT     i=0;
-	CHAR    slot_name[IFNAMSIZ];
-	struct net_device   *device;
-
-
-	//ether_setup(dev);
-//	dev->set_multicast_list = ieee80211_set_multicast_list;
-//	dev->change_mtu = ieee80211_change_mtu;
-#ifdef CONFIG_STA_SUPPORT
-#if WIRELESS_EXT >= 12
-	if (pAd->OpMode == OPMODE_STA)
-	{
-		dev->wireless_handlers = &rt28xx_iw_handler_def;
-	}
-#endif //WIRELESS_EXT >= 12
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-#if WIRELESS_EXT >= 12
-	if (pAd->OpMode == OPMODE_AP)
-	{
-		dev->wireless_handlers = &rt28xx_ap_iw_handler_def;
-	}
-#endif //WIRELESS_EXT >= 12
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-#if WIRELESS_EXT < 21
-		dev->get_wireless_stats = rt28xx_get_wireless_stats;
-#endif
-//	dev->uninit = ieee80211_if_reinit;
-//	dev->destructor = ieee80211_if_free;
-	dev->priv_flags = INT_MAIN;
-	dev->netdev_ops = &rt2870_netdev_ops;
-	// find available device name
-	for (i = 0; i < 8; i++)
-	{
-#ifdef MULTIPLE_CARD_SUPPORT
-		if (pAd->MC_RowID >= 0)
-			sprintf(slot_name, "ra%02d_%d", pAd->MC_RowID, i);
-		else
-#endif // MULTIPLE_CARD_SUPPORT //
-		sprintf(slot_name, "ra%d", i);
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,26)
-        device = dev_get_by_name(dev_net(dev), slot_name);
-#else
-        device = dev_get_by_name(dev->nd_net, slot_name);
-#endif
-#else
-		device = dev_get_by_name(slot_name);
-#endif
-		if (device != NULL) dev_put(device);
-#else
-		for (device = dev_base; device != NULL; device = device->next)
-		{
-			if (strncmp(device->name, slot_name, 4) == 0)
-				break;
-		}
-#endif
-		if(device == NULL)
-			break;
-	}
-
-	if(i == 8)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("No available slot name\n"));
-		Status = NDIS_STATUS_FAILURE;
-	}
-	else
-	{
-#ifdef MULTIPLE_CARD_SUPPORT
-		if (pAd->MC_RowID >= 0)
-	        sprintf(dev->name, "ra%02d_%d", pAd->MC_RowID, i);
-		else
-#endif // MULTIPLE_CARD_SUPPORT //
-		sprintf(dev->name, "ra%d", i);
-		Status = NDIS_STATUS_SUCCESS;
-	}
-
-	return Status;
-
-}
-
-
-#ifdef MULTIPLE_CARD_SUPPORT
-/*
-========================================================================
-Routine Description:
-    Get card profile path.
-
-Arguments:
-    pAd
-
-Return Value:
-    TRUE		- Find a card profile
-	FALSE		- use default profile
-
-Note:
-========================================================================
-*/
-extern INT RTMPGetKeyParameter(
-    IN  PCHAR   key,
-    OUT PCHAR   dest,
-    IN  INT     destsize,
-    IN  PCHAR   buffer);
-
-BOOLEAN RTMP_CardInfoRead(
-	IN	PRTMP_ADAPTER pAd)
-{
-#define MC_SELECT_CARDID		0	/* use CARD ID (0 ~ 31) to identify different cards */
-#define MC_SELECT_MAC			1	/* use CARD MAC to identify different cards */
-#define MC_SELECT_CARDTYPE		2	/* use CARD type (abgn or bgn) to identify different cards */
-
-#define LETTER_CASE_TRANSLATE(txt_p, card_id)			\
-	{	UINT32 _len; char _char;						\
-		for(_len=0; _len<strlen(card_id); _len++) {		\
-			_char = *(txt_p + _len);					\
-			if (('A' <= _char) && (_char <= 'Z'))		\
-				*(txt_p+_len) = 'a'+(_char-'A');		\
-		} }
-
-	struct file *srcf;
-	INT retval, orgfsuid, orgfsgid;
-   	mm_segment_t orgfs;
-	CHAR *buffer, *tmpbuf, card_id_buf[30], RFIC_word[30];
-	BOOLEAN flg_match_ok = FALSE;
-	INT32 card_select_method;
-	INT32 card_free_id, card_nouse_id, card_same_mac_id, card_match_id;
-	EEPROM_ANTENNA_STRUC antenna;
-	USHORT addr01, addr23, addr45;
-	UINT8 mac[6];
-	UINT32 data, card_index;
-	UCHAR *start_ptr;
-
-
-	// init
-	buffer = kmalloc(MAX_INI_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	if (buffer == NULL)
-        return FALSE;
-
-	tmpbuf = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	if(tmpbuf == NULL)
-	{
-		kfree(buffer);
-        return NDIS_STATUS_FAILURE;
-	}
-
-	orgfsuid = current->fsuid;
-	orgfsgid = current->fsgid;
-	current->fsuid = current->fsgid = 0;
-    orgfs = get_fs();
-    set_fs(KERNEL_DS);
-
-	// get RF IC type
-	RTMP_IO_READ32(pAd, E2PROM_CSR, &data);
-
-	if ((data & 0x30) == 0)
-		pAd->EEPROMAddressNum = 6;	// 93C46
-	else if ((data & 0x30) == 0x10)
-		pAd->EEPROMAddressNum = 8;	// 93C66
-	else
-		pAd->EEPROMAddressNum = 8;	// 93C86
-
-	//antenna.word = RTMP_EEPROM_READ16(pAd, EEPROM_NIC1_OFFSET);
-	RT28xx_EEPROM_READ16(pAd, EEPROM_NIC1_OFFSET, antenna.word);
-
-	if ((antenna.field.RfIcType == RFIC_2850) ||
-		(antenna.field.RfIcType == RFIC_2750))
-	{
-		/* ABGN card */
-		strcpy(RFIC_word, "abgn");
-	}
-	else
-	{
-		/* BGN card */
-		strcpy(RFIC_word, "bgn");
-	}
-
-	// get MAC address
-	//addr01 = RTMP_EEPROM_READ16(pAd, 0x04);
-	//addr23 = RTMP_EEPROM_READ16(pAd, 0x06);
-	//addr45 = RTMP_EEPROM_READ16(pAd, 0x08);
-	RT28xx_EEPROM_READ16(pAd, 0x04, addr01);
-	RT28xx_EEPROM_READ16(pAd, 0x06, addr23);
-	RT28xx_EEPROM_READ16(pAd, 0x08, addr45);
-
-	mac[0] = (UCHAR)(addr01 & 0xff);
-	mac[1] = (UCHAR)(addr01 >> 8);
-	mac[2] = (UCHAR)(addr23 & 0xff);
-	mac[3] = (UCHAR)(addr23 >> 8);
-	mac[4] = (UCHAR)(addr45 & 0xff);
-	mac[5] = (UCHAR)(addr45 >> 8);
-
-	// open card information file
-	srcf = filp_open(CARD_INFO_PATH, O_RDONLY, 0);
-	if (IS_ERR(srcf))
-	{
-		/* card information file does not exist */
-			DBGPRINT(RT_DEBUG_TRACE,
-				("--> Error %ld opening %s\n", -PTR_ERR(srcf), CARD_INFO_PATH));
-		return FALSE;
-	}
-
-	if (srcf->f_op && srcf->f_op->read)
-	{
-		/* card information file exists so reading the card information */
-		memset(buffer, 0x00, MAX_INI_BUFFER_SIZE);
-		retval = srcf->f_op->read(srcf, buffer, MAX_INI_BUFFER_SIZE, &srcf->f_pos);
-		if (retval < 0)
-		{
-			/* read fail */
-				DBGPRINT(RT_DEBUG_TRACE,
-					("--> Read %s error %d\n", CARD_INFO_PATH, -retval));
-		}
-		else
-		{
-			/* get card selection method */
-			memset(tmpbuf, 0x00, MAX_PARAM_BUFFER_SIZE);
-			card_select_method = MC_SELECT_CARDTYPE; // default
-
-			if (RTMPGetKeyParameter("SELECT", tmpbuf, 256, buffer))
-			{
-				if (strcmp(tmpbuf, "CARDID") == 0)
-					card_select_method = MC_SELECT_CARDID;
-				else if (strcmp(tmpbuf, "MAC") == 0)
-					card_select_method = MC_SELECT_MAC;
-				else if (strcmp(tmpbuf, "CARDTYPE") == 0)
-					card_select_method = MC_SELECT_CARDTYPE;
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE,
-					("MC> Card Selection = %d\n", card_select_method));
-
-			// init
-			card_free_id = -1;
-			card_nouse_id = -1;
-			card_same_mac_id = -1;
-			card_match_id = -1;
-
-			// search current card information records
-			for(card_index=0;
-				card_index<MAX_NUM_OF_MULTIPLE_CARD;
-				card_index++)
-			{
-				if ((*(UINT32 *)&MC_CardMac[card_index][0] == 0) &&
-					(*(UINT16 *)&MC_CardMac[card_index][4] == 0))
-				{
-					// MAC is all-0 so the entry is available
-					MC_CardUsed[card_index] = 0;
-
-					if (card_free_id < 0)
-						card_free_id = card_index; // 1st free entry
-				}
-				else
-				{
-					if (memcmp(MC_CardMac[card_index], mac, 6) == 0)
-					{
-						// we find the entry with same MAC
-						if (card_same_mac_id < 0)
-							card_same_mac_id = card_index; // 1st same entry
-					}
-					else
-					{
-						// MAC is not all-0 but used flag == 0
-						if ((MC_CardUsed[card_index] == 0) &&
-							(card_nouse_id < 0))
-						{
-							card_nouse_id = card_index; // 1st available entry
-						}
-					}
-				}
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE,
-					("MC> Free = %d, Same = %d, NOUSE = %d\n",
-					card_free_id, card_same_mac_id, card_nouse_id));
-
-			if ((card_same_mac_id >= 0) &&
-				((card_select_method == MC_SELECT_CARDID) ||
-				(card_select_method == MC_SELECT_CARDTYPE)))
-			{
-				// same MAC entry is found
-				card_match_id = card_same_mac_id;
-
-				if (card_select_method == MC_SELECT_CARDTYPE)
-				{
-					// for CARDTYPE
-					sprintf(card_id_buf, "%02dCARDTYPE%s",
-							card_match_id, RFIC_word);
-
-					if ((start_ptr=rtstrstruncasecmp(buffer, card_id_buf)) != NULL)
-					{
-						// we found the card ID
-						LETTER_CASE_TRANSLATE(start_ptr, card_id_buf);
-					}
-				}
-			}
-			else
-			{
-				// the card is 1st plug-in, try to find the match card profile
-				switch(card_select_method)
-				{
-					case MC_SELECT_CARDID: // CARDID
-					default:
-						if (card_free_id >= 0)
-							card_match_id = card_free_id;
-						else
-							card_match_id = card_nouse_id;
-						break;
-
-					case MC_SELECT_MAC: // MAC
-						sprintf(card_id_buf, "MAC%02x:%02x:%02x:%02x:%02x:%02x",
-								mac[0], mac[1], mac[2],
-								mac[3], mac[4], mac[5]);
-
-						/* try to find the key word in the card file */
-						if ((start_ptr=rtstrstruncasecmp(buffer, card_id_buf)) != NULL)
-						{
-							LETTER_CASE_TRANSLATE(start_ptr, card_id_buf);
-
-							/* get the row ID (2 ASCII characters) */
-							start_ptr -= 2;
-							card_id_buf[0] = *(start_ptr);
-							card_id_buf[1] = *(start_ptr+1);
-							card_id_buf[2] = 0x00;
-
-							card_match_id = simple_strtol(card_id_buf, 0, 10);
-						}
-						break;
-
-					case MC_SELECT_CARDTYPE: // CARDTYPE
-						card_nouse_id = -1;
-
-						for(card_index=0;
-							card_index<MAX_NUM_OF_MULTIPLE_CARD;
-							card_index++)
-						{
-							sprintf(card_id_buf, "%02dCARDTYPE%s",
-									card_index, RFIC_word);
-
-							if ((start_ptr=rtstrstruncasecmp(buffer,
-														card_id_buf)) != NULL)
-							{
-								LETTER_CASE_TRANSLATE(start_ptr, card_id_buf);
-
-								if (MC_CardUsed[card_index] == 0)
-								{
-									/* current the card profile is not used */
-									if ((*(UINT32 *)&MC_CardMac[card_index][0] == 0) &&
-										(*(UINT16 *)&MC_CardMac[card_index][4] == 0))
-									{
-										// find it and no previous card use it
-										card_match_id = card_index;
-										break;
-									}
-									else
-									{
-										// ever a card use it
-										if (card_nouse_id < 0)
-											card_nouse_id = card_index;
-									}
-								}
-							}
-						}
-
-						// if not find a free one, use the available one
-						if (card_match_id < 0)
-							card_match_id = card_nouse_id;
-						break;
-				}
-			}
-
-			if (card_match_id >= 0)
-			{
-				// make up search keyword
-				switch(card_select_method)
-				{
-					case MC_SELECT_CARDID: // CARDID
-						sprintf(card_id_buf, "%02dCARDID", card_match_id);
-						break;
-
-					case MC_SELECT_MAC: // MAC
-						sprintf(card_id_buf,
-								"%02dmac%02x:%02x:%02x:%02x:%02x:%02x",
-								card_match_id,
-								mac[0], mac[1], mac[2],
-								mac[3], mac[4], mac[5]);
-						break;
-
-					case MC_SELECT_CARDTYPE: // CARDTYPE
-					default:
-						sprintf(card_id_buf, "%02dcardtype%s",
-								card_match_id, RFIC_word);
-						break;
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Search Keyword = %s\n", card_id_buf));
-
-				// read card file path
-				if (RTMPGetKeyParameter(card_id_buf, tmpbuf, 256, buffer))
-				{
-					if (strlen(tmpbuf) < sizeof(pAd->MC_FileName))
-					{
-						// backup card information
-						pAd->MC_RowID = card_match_id; /* base 0 */
-						MC_CardUsed[card_match_id] = 1;
-						memcpy(MC_CardMac[card_match_id], mac, sizeof(mac));
-
-						// backup card file path
-						NdisMoveMemory(pAd->MC_FileName, tmpbuf , strlen(tmpbuf));
-						pAd->MC_FileName[strlen(tmpbuf)] = '\0';
-						flg_match_ok = TRUE;
-
-						DBGPRINT(RT_DEBUG_TRACE,
-								("Card Profile Name = %s\n", pAd->MC_FileName));
-					}
-					else
-					{
-						DBGPRINT(RT_DEBUG_ERROR,
-								("Card Profile Name length too large!\n"));
-					}
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_ERROR,
-							("Can not find search key word in card.dat!\n"));
-				}
-
-				if ((flg_match_ok != TRUE) &&
-					(card_match_id < MAX_NUM_OF_MULTIPLE_CARD))
-				{
-					MC_CardUsed[card_match_id] = 0;
-					memset(MC_CardMac[card_match_id], 0, sizeof(mac));
-				}
-			} // if (card_match_id >= 0)
-		}
-	}
-
-	// close file
-	retval = filp_close(srcf, NULL);
-	set_fs(orgfs);
-	current->fsuid = orgfsuid;
-	current->fsgid = orgfsgid;
-	kfree(buffer);
-	kfree(tmpbuf);
-	return flg_match_ok;
-}
-#endif // MULTIPLE_CARD_SUPPORT //
-
-
-/*
-========================================================================
-Routine Description:
-    Probe RT28XX chipset.
-
-Arguments:
-    _dev_p				Point to the PCI or USB device
-	_dev_id_p			Point to the PCI or USB device ID
-
-Return Value:
-    0					Probe OK
-	-ENODEV				Probe Fail
-
-Note:
-========================================================================
-*/
-INT __devinit   rt28xx_probe(
-    IN  void *_dev_p,
-    IN  void *_dev_id_p,
-	IN  UINT argc,
-	OUT PRTMP_ADAPTER *ppAd)
-{
-    struct  net_device	*net_dev;
-    PRTMP_ADAPTER       pAd = (PRTMP_ADAPTER) NULL;
-    INT                 status;
-	PVOID				handle;
-#ifdef RT2870
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	struct usb_device *dev_p = (struct usb_device *)_dev_p;
-#else
-	struct usb_interface *intf = (struct usb_interface *)_dev_p;
-	struct usb_device *dev_p = interface_to_usbdev(intf);
-
-	dev_p = usb_get_dev(dev_p);
-#endif // LINUX_VERSION_CODE //
-#endif // RT2870 //
-
-
-#ifdef CONFIG_STA_SUPPORT
-    DBGPRINT(RT_DEBUG_TRACE, ("STA Driver version-%s\n", STA_DRIVER_VERSION));
-#endif // CONFIG_STA_SUPPORT //
-
-	// Check chipset vendor/product ID
-//	if (RT28XXChipsetCheck(_dev_p) == FALSE)
-//		goto err_out;
-
-#if LINUX_VERSION_CODE <= 0x20402       // Red Hat 7.1
-    net_dev = alloc_netdev(sizeof(PRTMP_ADAPTER), "eth%d", ether_setup);
-#else
-    net_dev = alloc_etherdev(sizeof(PRTMP_ADAPTER));
-#endif
-    if (net_dev == NULL)
-    {
-        printk("alloc_netdev failed\n");
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,15)
-		module_put(THIS_MODULE);
-#endif //LINUX_VERSION_CODE < KERNEL_VERSION(2,6,15)
-#else
-		MOD_DEC_USE_COUNT;
-#endif
-        goto err_out;
-    }
-
-// sample
-//	if (rt_ieee80211_if_setup(net_dev) != NDIS_STATUS_SUCCESS)
-//		goto err_out;
-
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24)
-    SET_MODULE_OWNER(net_dev);
-#endif
-
-	netif_stop_queue(net_dev);
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-/* for supporting Network Manager */
-/* Set the sysfs physical device reference for the network logical device
- * if set prior to registration will cause a symlink during initialization.
- */
-#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0))
-    SET_NETDEV_DEV(net_dev, &(dev_p->dev));
-#endif
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-	// Allocate RTMP_ADAPTER miniport adapter structure
-	handle = kmalloc(sizeof(struct os_cookie), GFP_KERNEL);
-	RT28XX_HANDLE_DEV_ASSIGN(handle, dev_p);
-
-	status = RTMPAllocAdapterBlock(handle, &pAd);
-	if (status != NDIS_STATUS_SUCCESS)
-		goto err_out_free_netdev;
-
-	net_dev->ml_priv = (PVOID)pAd;
-    pAd->net_dev = net_dev; // must be before RT28XXNetDevInit()
-
-	RT28XXNetDevInit(_dev_p, net_dev, pAd);
-
-#ifdef CONFIG_STA_SUPPORT
-    pAd->StaCfg.OriDevType = net_dev->type;
-#endif // CONFIG_STA_SUPPORT //
-
-	// Find and assign a free interface name, raxx
-//	RT28XXAvailRANameAssign(net_dev->name);
-
-	// Post config
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-	if (RT28XXProbePostConfig(_dev_p, pAd, argc) == FALSE)
-		goto err_out_unmap;
-#else
-	if (RT28XXProbePostConfig(_dev_p, pAd, 0) == FALSE)
-		goto err_out_unmap;
-#endif // LINUX_VERSION_CODE //
-
-#ifdef CONFIG_STA_SUPPORT
-	pAd->OpMode = OPMODE_STA;
-#endif // CONFIG_STA_SUPPORT //
-
-
-#ifdef MULTIPLE_CARD_SUPPORT
-	// find its profile path
-	pAd->MC_RowID = -1; // use default profile path
-	RTMP_CardInfoRead(pAd);
-
-	if (pAd->MC_RowID == -1)
-#ifdef CONFIG_STA_SUPPORT
-		strcpy(pAd->MC_FileName, STA_PROFILE_PATH);
-#endif // CONFIG_STA_SUPPORT //
-
-	DBGPRINT(RT_DEBUG_TRACE,
-			("MC> ROW = %d, PATH = %s\n", pAd->MC_RowID, pAd->MC_FileName));
-#endif // MULTIPLE_CARD_SUPPORT //
-
-	// sample move
-	if (rt_ieee80211_if_setup(net_dev, pAd) != NDIS_STATUS_SUCCESS)
-		goto err_out_unmap;
-
-    // Register this device
-    status = register_netdev(net_dev);
-    if (status)
-        goto err_out_unmap;
-
-    // Set driver data
-	RT28XX_DRVDATA_SET(_dev_p);
-
-
-
-	*ppAd = pAd;
-    return 0; // probe ok
-
-
-	/* --------------------------- ERROR HANDLE --------------------------- */
-err_out_unmap:
-	RTMPFreeAdapter(pAd);
-	RT28XX_UNMAP();
-
-err_out_free_netdev:
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-    free_netdev(net_dev);
-#else
-	kfree(net_dev);
-#endif
-
-err_out:
-	RT28XX_PUT_DEVICE(dev_p);
-
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-	return (LONG)NULL;
-#else
-    return -ENODEV; /* probe fail */
-#endif // LINUX_VERSION_CODE //
-} /* End of rt28xx_probe */
-
-
-/*
-========================================================================
-Routine Description:
-    The entry point for Linux kernel sent packet to our driver.
-
-Arguments:
-    sk_buff *skb		the pointer refer to a sk_buffer.
-
-Return Value:
-    0
-
-Note:
-	This function is the entry point of Tx Path for Os delivery packet to
-	our driver. You only can put OS-depened & STA/AP common handle procedures
-	in here.
-========================================================================
-*/
-int rt28xx_packet_xmit(struct sk_buff *skb)
-{
-	struct net_device *net_dev = skb->dev;
-	PRTMP_ADAPTER pAd = net_dev->ml_priv;
-	int status = 0;
-	PNDIS_PACKET pPacket = (PNDIS_PACKET) skb;
-
-	/* RT2870STA does this in RTMPSendPackets() */
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_RESOURCES);
-		return 0;
-	}
-#endif // RALINK_ATE //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Drop send request since we are in monitor mode
-		if (MONITOR_ON(pAd))
-		{
-			RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-			goto done;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-        // EapolStart size is 18
-	if (skb->len < 14)
-	{
-		//printk("bad packet size: %d\n", pkt->len);
-		hex_dump("bad packet", skb->data, skb->len);
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-		goto done;
-	}
-
-#if 0
-//	if ((pkt->data[0] & 0x1) == 0)
-	{
-		//hex_dump(__func__, pkt->data, pkt->len);
-		printk("pPacket = %x\n", pPacket);
-	}
-#endif
-
-	RTMP_SET_PACKET_5VT(pPacket, 0);
-//	MiniportMMRequest(pAd, pkt->data, pkt->len);
-#ifdef CONFIG_5VT_ENHANCE
-    if (*(int*)(skb->cb) == BRIDGE_TAG) {
-		RTMP_SET_PACKET_5VT(pPacket, 1);
-    }
-#endif
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-
-		STASendPackets((NDIS_HANDLE)pAd, (PPNDIS_PACKET) &pPacket, 1);
-	}
-
-#endif // CONFIG_STA_SUPPORT //
-
-	status = 0;
-done:
-
-	return status;
-}
-
-
-/*
-========================================================================
-Routine Description:
-    Send a packet to WLAN.
-
-Arguments:
-    skb_p           points to our adapter
-    dev_p           which WLAN network interface
-
-Return Value:
-    0: transmit successfully
-    otherwise: transmit fail
-
-Note:
-========================================================================
-*/
-INT rt28xx_send_packets(
-	IN struct sk_buff 		*skb_p,
-	IN struct net_device 	*net_dev)
-{
-    RTMP_ADAPTER *pAd = net_dev->ml_priv;
-
-	if (!(net_dev->flags & IFF_UP))
-	{
-		RELEASE_NDIS_PACKET(pAd, (PNDIS_PACKET)skb_p, NDIS_STATUS_FAILURE);
-		return 0;
-	}
-
-	NdisZeroMemory((PUCHAR)&skb_p->cb[CB_OFF], 15);
-	RTMP_SET_PACKET_NET_DEVICE_MBSSID(skb_p, MAIN_MBSSID);
-
-	return rt28xx_packet_xmit(skb_p);
-} /* End of MBSS_VirtualIF_PacketSend */
-
-
-
-
-#if LINUX_VERSION_CODE <= 0x20402	// Red Hat 7.1
-//static struct net_device *alloc_netdev(int sizeof_priv, const char *mask, void (*setup)(struct net_device *)) //sample
-struct net_device *alloc_netdev(
-	int sizeof_priv,
-	const char *mask,
-	void (*setup)(struct net_device *))
-{
-    struct net_device	*dev;
-    INT					alloc_size;
-
-
-    /* ensure 32-byte alignment of the private area */
-    alloc_size = sizeof (*dev) + sizeof_priv + 31;
-
-    dev = (struct net_device *) kmalloc(alloc_size, GFP_KERNEL);
-    if (dev == NULL)
-    {
-        DBGPRINT(RT_DEBUG_ERROR,
-				("alloc_netdev: Unable to allocate device memory.\n"));
-        return NULL;
-    }
-
-    memset(dev, 0, alloc_size);
-
-    if (sizeof_priv)
-        dev->priv = (void *) (((long)(dev + 1) + 31) & ~31);
-
-    setup(dev);
-    strcpy(dev->name, mask);
-
-    return dev;
-}
-#endif // LINUX_VERSION_CODE //
-
-
-void CfgInitHook(PRTMP_ADAPTER pAd)
-{
-	pAd->bBroadComHT = TRUE;
-} /* End of CfgInitHook */
-
-
-#if 0	// Not used now, should keep it in our source tree??
-/*
-========================================================================
-Routine Description:
-    Find and assign a free interface name (raxx).
-
-Arguments:
-    *name_p				the interface name pointer
-
-Return Value:
-	TRUE				OK
-	FALSE				FAIL
-
-Note:
-========================================================================
-*/
-static BOOLEAN RT28XXAvailRANameAssign(
-	IN CHAR			*name_p)
-{
-    CHAR				slot_name[IFNAMSIZ];
-    struct net_device	*device;
-	UINT32				if_id;
-
-
-    for(if_id=0; if_id<8; if_id++)
-    {
-        sprintf(slot_name, "ra%d", if_id);
-
-        for(device=dev_base; device!=NULL; device=device->next)
-        {
-            if (strncmp(device->name, slot_name, 4) == 0)
-                break;
-        }
-
-        if (device == NULL)
-			break;
-    }
-
-    if (if_id == 8)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("No available slot name\n"));
-        return FALSE;
-    }
-
-    sprintf(name_p, "ra%d", if_id);
-	return TRUE;
-} /* End of RT28XXAvailRANameAssign */
-#endif
-
-#if WIRELESS_EXT >= 12
-// This function will be called when query /proc
-struct iw_statistics *rt28xx_get_wireless_stats(
-    IN struct net_device *net_dev)
-{
-	PRTMP_ADAPTER pAd = net_dev->ml_priv;
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("rt28xx_get_wireless_stats --->\n"));
-
-	pAd->iw_stats.status = 0; // Status - device dependent for now
-
-	// link quality
-	pAd->iw_stats.qual.qual = ((pAd->Mlme.ChannelQuality * 12)/10 + 10);
-	if(pAd->iw_stats.qual.qual > 100)
-		pAd->iw_stats.qual.qual = 100;
-
-#ifdef CONFIG_STA_SUPPORT
-	if (pAd->OpMode == OPMODE_STA)
-		pAd->iw_stats.qual.level = RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2);
-#endif // CONFIG_STA_SUPPORT //
-
-	pAd->iw_stats.qual.noise = pAd->BbpWriteLatch[66]; // noise level (dBm)
-
-	pAd->iw_stats.qual.noise += 256 - 143;
-	pAd->iw_stats.qual.updated = 1;     // Flags to know if updated
-#ifdef IW_QUAL_DBM
-	pAd->iw_stats.qual.updated |= IW_QUAL_DBM;	// Level + Noise are dBm
-#endif // IW_QUAL_DBM //
-
-	pAd->iw_stats.discard.nwid = 0;     // Rx : Wrong nwid/essid
-	pAd->iw_stats.miss.beacon = 0;      // Missed beacons/superframe
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<--- rt28xx_get_wireless_stats\n"));
-	return &pAd->iw_stats;
-} /* End of rt28xx_get_wireless_stats */
-#endif // WIRELESS_EXT //
-
-
-
-void tbtt_tasklet(unsigned long data)
-{
-#define MAX_TX_IN_TBTT		(16)
-
-}
-
-INT rt28xx_ioctl(
-	IN	struct net_device	*net_dev,
-	IN	OUT	struct ifreq	*rq,
-	IN	INT					cmd)
-{
-	VIRTUAL_ADAPTER	*pVirtualAd = NULL;
-	RTMP_ADAPTER	*pAd = NULL;
-	INT				ret = 0;
-
-	if (net_dev->priv_flags == INT_MAIN)
-	{
-		pAd = net_dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = net_dev->ml_priv;
-		pAd = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		ret = rt28xx_sta_ioctl(net_dev, rq, cmd);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	return ret;
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-        return ethernet statistics counter
-
-    Arguments:
-        net_dev                     Pointer to net_device
-
-    Return Value:
-        net_device_stats*
-
-    Note:
-
-    ========================================================================
-*/
-struct net_device_stats *RT28xx_get_ether_stats(
-    IN  struct net_device *net_dev)
-{
-    RTMP_ADAPTER *pAd = NULL;
-
-	if (net_dev)
-		pAd = net_dev->ml_priv;
-
-	if (pAd)
-	{
-
-		pAd->stats.rx_packets = pAd->WlanCounters.ReceivedFragmentCount.QuadPart;
-		pAd->stats.tx_packets = pAd->WlanCounters.TransmittedFragmentCount.QuadPart;
-
-		pAd->stats.rx_bytes = pAd->RalinkCounters.ReceivedByteCount;
-		pAd->stats.tx_bytes = pAd->RalinkCounters.TransmittedByteCount;
-
-		pAd->stats.rx_errors = pAd->Counters8023.RxErrors;
-		pAd->stats.tx_errors = pAd->Counters8023.TxErrors;
-
-		pAd->stats.rx_dropped = 0;
-		pAd->stats.tx_dropped = 0;
-
-	    pAd->stats.multicast = pAd->WlanCounters.MulticastReceivedFrameCount.QuadPart;   // multicast packets received
-	    pAd->stats.collisions = pAd->Counters8023.OneCollision + pAd->Counters8023.MoreCollisions;  // Collision packets
-
-	    pAd->stats.rx_length_errors = 0;
-	    pAd->stats.rx_over_errors = pAd->Counters8023.RxNoBuffer;                   // receiver ring buff overflow
-	    pAd->stats.rx_crc_errors = 0;//pAd->WlanCounters.FCSErrorCount;     // recved pkt with crc error
-	    pAd->stats.rx_frame_errors = pAd->Counters8023.RcvAlignmentErrors;          // recv'd frame alignment error
-	    pAd->stats.rx_fifo_errors = pAd->Counters8023.RxNoBuffer;                   // recv'r fifo overrun
-	    pAd->stats.rx_missed_errors = 0;                                            // receiver missed packet
-
-	    // detailed tx_errors
-	    pAd->stats.tx_aborted_errors = 0;
-	    pAd->stats.tx_carrier_errors = 0;
-	    pAd->stats.tx_fifo_errors = 0;
-	    pAd->stats.tx_heartbeat_errors = 0;
-	    pAd->stats.tx_window_errors = 0;
-
-	    // for cslip etc
-	    pAd->stats.rx_compressed = 0;
-	    pAd->stats.tx_compressed = 0;
-
-		return &pAd->stats;
-	}
-	else
-    	return NULL;
-}
-
+#include "../rt2860/rt_main_dev.c"
diff --git a/drivers/staging/rt2870/rt_profile.c b/drivers/staging/rt2870/rt_profile.c
index 467fea3..15988c5 100644
--- a/drivers/staging/rt2870/rt_profile.c
+++ b/drivers/staging/rt2870/rt_profile.c
@@ -1,2020 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#include "rt_config.h"
-
-#ifdef DOT11_N_SUPPORT
-static void HTParametersHook(
-	IN	PRTMP_ADAPTER pAd,
-	IN	CHAR		  *pValueStr,
-	IN	CHAR		  *pInput);
-#endif // DOT11_N_SUPPORT //
-
-#define ETH_MAC_ADDR_STR_LEN 17  // in format of xx:xx:xx:xx:xx:xx
-
-// We assume the s1 is a sting, s2 is a memory space with 6 bytes. and content of s1 will be changed.
-BOOLEAN rtstrmactohex(char *s1, char *s2)
-{
-	int i = 0;
-	char *ptokS = s1, *ptokE = s1;
-
-	if (strlen(s1) != ETH_MAC_ADDR_STR_LEN)
-		return FALSE;
-
-	while((*ptokS) != '\0')
-	{
-		if((ptokE = strchr(ptokS, ':')) != NULL)
-			*ptokE++ = '\0';
-		if ((strlen(ptokS) != 2) || (!isxdigit(*ptokS)) || (!isxdigit(*(ptokS+1))))
-			break; // fail
-		AtoH(ptokS, &s2[i++], 1);
-		ptokS = ptokE;
-		if (i == 6)
-			break; // parsing finished
-	}
-
-	return ( i == 6 ? TRUE : FALSE);
-
-}
-
-
-// we assume the s1 and s2 both are strings.
-BOOLEAN rtstrcasecmp(char *s1, char *s2)
-{
-	char *p1 = s1, *p2 = s2;
-
-	if (strlen(s1) != strlen(s2))
-		return FALSE;
-
-	while(*p1 != '\0')
-	{
-		if((*p1 != *p2) && ((*p1 ^ *p2) != 0x20))
-			return FALSE;
-		p1++;
-		p2++;
-	}
-
-	return TRUE;
-}
-
-// we assume the s1 (buffer) and s2 (key) both are strings.
-char * rtstrstruncasecmp(char * s1, char * s2)
-{
-	INT l1, l2, i;
-	char temp1, temp2;
-
-	l2 = strlen(s2);
-	if (!l2)
-		return (char *) s1;
-
-	l1 = strlen(s1);
-
-	while (l1 >= l2)
-	{
-		l1--;
-
-		for(i=0; i<l2; i++)
-		{
-			temp1 = *(s1+i);
-			temp2 = *(s2+i);
-
-			if (('a' <= temp1) && (temp1 <= 'z'))
-				temp1 = 'A'+(temp1-'a');
-			if (('a' <= temp2) && (temp2 <= 'z'))
-				temp2 = 'A'+(temp2-'a');
-
-			if (temp1 != temp2)
-				break;
-		}
-
-		if (i == l2)
-			return (char *) s1;
-
-		s1++;
-	}
-
-	return NULL; // not found
-}
-
-//add by kathy
-
- /**
-  * strstr - Find the first substring in a %NUL terminated string
-  * @s1: The string to be searched
-  * @s2: The string to search for
-  */
-char * rtstrstr(const char * s1,const char * s2)
-{
-	INT l1, l2;
-
-	l2 = strlen(s2);
-	if (!l2)
-		return (char *) s1;
-
-	l1 = strlen(s1);
-
-	while (l1 >= l2)
-	{
-		l1--;
-		if (!memcmp(s1,s2,l2))
-			return (char *) s1;
-		s1++;
-	}
-
-	return NULL;
-}
-
-/**
- * rstrtok - Split a string into tokens
- * @s: The string to be searched
- * @ct: The characters to search for
- * * WARNING: strtok is deprecated, use strsep instead. However strsep is not compatible with old architecture.
- */
-char * __rstrtok;
-char * rstrtok(char * s,const char * ct)
-{
-	char *sbegin, *send;
-
-	sbegin  = s ? s : __rstrtok;
-	if (!sbegin)
-	{
-		return NULL;
-	}
-
-	sbegin += strspn(sbegin,ct);
-	if (*sbegin == '\0')
-	{
-		__rstrtok = NULL;
-		return( NULL );
-	}
-
-	send = strpbrk( sbegin, ct);
-	if (send && *send != '\0')
-		*send++ = '\0';
-
-	__rstrtok = send;
-
-	return (sbegin);
-}
-
-/**
- * delimitcnt - return the count of a given delimiter in a given string.
- * @s: The string to be searched.
- * @ct: The delimiter to search for.
- * Notice : We suppose the delimiter is a single-char string(for example : ";").
- */
-INT delimitcnt(char * s,const char * ct)
-{
-	INT count = 0;
-	/* point to the beginning of the line */
-	const char *token = s;
-
-	for ( ;; )
-	{
-		token = strpbrk(token, ct); /* search for delimiters */
-
-        if ( token == NULL )
-		{
-			/* advanced to the terminating null character */
-			break;
-		}
-		/* skip the delimiter */
-	    ++token;
-
-		/*
-		 * Print the found text: use len with %.*s to specify field width.
-		 */
-
-		/* accumulate delimiter count */
-	    ++count;
-	}
-    return count;
-}
-
-/*
-  * converts the Internet host address from the standard numbers-and-dots notation
-  * into binary data.
-  * returns nonzero if the address is valid, zero if not.
-  */
-int rtinet_aton(const char *cp, unsigned int *addr)
-{
-	unsigned int 	val;
-	int         	base, n;
-	char        	c;
-	unsigned int    parts[4];
-	unsigned int    *pp = parts;
-
-	for (;;)
-    {
-         /*
-          * Collect number up to ``.''.
-          * Values are specified as for C:
-          *	0x=hex, 0=octal, other=decimal.
-          */
-         val = 0;
-         base = 10;
-         if (*cp == '0')
-         {
-             if (*++cp == 'x' || *cp == 'X')
-                 base = 16, cp++;
-             else
-                 base = 8;
-         }
-         while ((c = *cp) != '\0')
-         {
-             if (isdigit((unsigned char) c))
-             {
-                 val = (val * base) + (c - '0');
-                 cp++;
-                 continue;
-             }
-             if (base == 16 && isxdigit((unsigned char) c))
-             {
-                 val = (val << 4) +
-                     (c + 10 - (islower((unsigned char) c) ? 'a' : 'A'));
-                 cp++;
-                 continue;
-             }
-             break;
-         }
-         if (*cp == '.')
-         {
-             /*
-              * Internet format: a.b.c.d a.b.c   (with c treated as 16-bits)
-              * a.b     (with b treated as 24 bits)
-              */
-             if (pp >= parts + 3 || val > 0xff)
-                 return 0;
-             *pp++ = val, cp++;
-         }
-         else
-             break;
-     }
-
-     /*
-      * Check for trailing junk.
-      */
-     while (*cp)
-         if (!isspace((unsigned char) *cp++))
-             return 0;
-
-     /*
-      * Concoct the address according to the number of parts specified.
-      */
-     n = pp - parts + 1;
-     switch (n)
-     {
-
-         case 1:         /* a -- 32 bits */
-             break;
-
-         case 2:         /* a.b -- 8.24 bits */
-             if (val > 0xffffff)
-                 return 0;
-             val |= parts[0] << 24;
-             break;
-
-         case 3:         /* a.b.c -- 8.8.16 bits */
-             if (val > 0xffff)
-                 return 0;
-             val |= (parts[0] << 24) | (parts[1] << 16);
-             break;
-
-         case 4:         /* a.b.c.d -- 8.8.8.8 bits */
-             if (val > 0xff)
-                 return 0;
-             val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
-             break;
-     }
-
-     *addr = htonl(val);
-     return 1;
-
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-        Find key section for Get key parameter.
-
-    Arguments:
-        buffer                      Pointer to the buffer to start find the key section
-        section                     the key of the secion to be find
-
-    Return Value:
-        NULL                        Fail
-        Others                      Success
-    ========================================================================
-*/
-PUCHAR  RTMPFindSection(
-    IN  PCHAR   buffer)
-{
-    CHAR temp_buf[32];
-    PUCHAR  ptr;
-
-    strcpy(temp_buf, "Default");
-
-    if((ptr = rtstrstr(buffer, temp_buf)) != NULL)
-            return (ptr+strlen("\n"));
-        else
-            return NULL;
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-        Get key parameter.
-
-    Arguments:
-        key                         Pointer to key string
-        dest                        Pointer to destination
-        destsize                    The datasize of the destination
-        buffer                      Pointer to the buffer to start find the key
-
-    Return Value:
-        TRUE                        Success
-        FALSE                       Fail
-
-    Note:
-        This routine get the value with the matched key (case case-sensitive)
-    ========================================================================
-*/
-INT RTMPGetKeyParameter(
-    IN  PCHAR   key,
-    OUT PCHAR   dest,
-    IN  INT     destsize,
-    IN  PCHAR   buffer)
-{
-    UCHAR *temp_buf1 = NULL;
-    UCHAR *temp_buf2 = NULL;
-    CHAR *start_ptr;
-    CHAR *end_ptr;
-    CHAR *ptr;
-    CHAR *offset = 0;
-    INT  len;
-
-	//temp_buf1 = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	os_alloc_mem(NULL, &temp_buf1, MAX_PARAM_BUFFER_SIZE);
-
-	if(temp_buf1 == NULL)
-        return (FALSE);
-
-	//temp_buf2 = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	os_alloc_mem(NULL, &temp_buf2, MAX_PARAM_BUFFER_SIZE);
-	if(temp_buf2 == NULL)
-	{
-		os_free_mem(NULL, temp_buf1);
-        return (FALSE);
-	}
-
-    //find section
-    if((offset = RTMPFindSection(buffer)) == NULL)
-    {
-    	os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    strcpy(temp_buf1, "\n");
-    strcat(temp_buf1, key);
-    strcat(temp_buf1, "=");
-
-    //search key
-    if((start_ptr=rtstrstr(offset, temp_buf1))==NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    start_ptr+=strlen("\n");
-    if((end_ptr=rtstrstr(start_ptr, "\n"))==NULL)
-       end_ptr=start_ptr+strlen(start_ptr);
-
-    if (end_ptr<start_ptr)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    NdisMoveMemory(temp_buf2, start_ptr, end_ptr-start_ptr);
-    temp_buf2[end_ptr-start_ptr]='\0';
-    len = strlen(temp_buf2);
-    strcpy(temp_buf1, temp_buf2);
-    if((start_ptr=rtstrstr(temp_buf1, "=")) == NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    strcpy(temp_buf2, start_ptr+1);
-    ptr = temp_buf2;
-    //trim space or tab
-    while(*ptr != 0x00)
-    {
-        if( (*ptr == ' ') || (*ptr == '\t') )
-            ptr++;
-        else
-           break;
-    }
-
-    len = strlen(ptr);
-    memset(dest, 0x00, destsize);
-    strncpy(dest, ptr, len >= destsize ?  destsize: len);
-
-	os_free_mem(NULL, temp_buf1);
-    os_free_mem(NULL, temp_buf2);
-    return TRUE;
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-        Get key parameter.
-
-    Arguments:
-        key                         Pointer to key string
-        dest                        Pointer to destination
-        destsize                    The datasize of the destination
-        buffer                      Pointer to the buffer to start find the key
-
-    Return Value:
-        TRUE                        Success
-        FALSE                       Fail
-
-    Note:
-        This routine get the value with the matched key (case case-sensitive).
-        It is called for parsing SSID and any key string.
-    ========================================================================
-*/
-INT RTMPGetCriticalParameter(
-    IN  PCHAR   key,
-    OUT PCHAR   dest,
-    IN  INT     destsize,
-    IN  PCHAR   buffer)
-{
-    UCHAR *temp_buf1 = NULL;
-    UCHAR *temp_buf2 = NULL;
-    CHAR *start_ptr;
-    CHAR *end_ptr;
-    CHAR *ptr;
-    CHAR *offset = 0;
-    INT  len;
-
-	//temp_buf1 = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	os_alloc_mem(NULL, &temp_buf1, MAX_PARAM_BUFFER_SIZE);
-
-	if(temp_buf1 == NULL)
-        return (FALSE);
-
-	//temp_buf2 = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	os_alloc_mem(NULL, &temp_buf2, MAX_PARAM_BUFFER_SIZE);
-	if(temp_buf2 == NULL)
-	{
-		os_free_mem(NULL, temp_buf1);
-        return (FALSE);
-	}
-
-    //find section
-    if((offset = RTMPFindSection(buffer)) == NULL)
-    {
-    	os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    strcpy(temp_buf1, "\n");
-    strcat(temp_buf1, key);
-    strcat(temp_buf1, "=");
-
-    //search key
-    if((start_ptr=rtstrstr(offset, temp_buf1))==NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    start_ptr+=strlen("\n");
-    if((end_ptr=rtstrstr(start_ptr, "\n"))==NULL)
-       end_ptr=start_ptr+strlen(start_ptr);
-
-    if (end_ptr<start_ptr)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    NdisMoveMemory(temp_buf2, start_ptr, end_ptr-start_ptr);
-    temp_buf2[end_ptr-start_ptr]='\0';
-    len = strlen(temp_buf2);
-    strcpy(temp_buf1, temp_buf2);
-    if((start_ptr=rtstrstr(temp_buf1, "=")) == NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    strcpy(temp_buf2, start_ptr+1);
-    ptr = temp_buf2;
-
-    //trim tab
-    /* We cannot trim space(' ') for SSID and key string. */
-    while(*ptr != 0x00)
-    {
-        //if( (*ptr == ' ') || (*ptr == '\t') )
-        if( (*ptr == '\t') )
-            ptr++;
-        else
-           break;
-    }
-
-    len = strlen(ptr);
-    memset(dest, 0x00, destsize);
-    strncpy(dest, ptr, len >= destsize ?  destsize: len);
-
-	os_free_mem(NULL, temp_buf1);
-    os_free_mem(NULL, temp_buf2);
-    return TRUE;
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-        Get multiple key parameter.
-
-    Arguments:
-        key                         Pointer to key string
-        dest                        Pointer to destination
-        destsize                    The datasize of the destination
-        buffer                      Pointer to the buffer to start find the key
-
-    Return Value:
-        TRUE                        Success
-        FALSE                       Fail
-
-    Note:
-        This routine get the value with the matched key (case case-sensitive)
-    ========================================================================
-*/
-INT RTMPGetKeyParameterWithOffset(
-    IN  PCHAR   key,
-    OUT PCHAR   dest,
-    OUT	USHORT	*end_offset,
-    IN  INT     destsize,
-    IN  PCHAR   buffer,
-    IN	BOOLEAN	bTrimSpace)
-{
-    UCHAR *temp_buf1 = NULL;
-    UCHAR *temp_buf2 = NULL;
-    CHAR *start_ptr;
-    CHAR *end_ptr;
-    CHAR *ptr;
-    CHAR *offset = 0;
-    INT  len;
-
-	if (*end_offset >= MAX_INI_BUFFER_SIZE)
-		return (FALSE);
-
-	os_alloc_mem(NULL, &temp_buf1, MAX_PARAM_BUFFER_SIZE);
-
-	if(temp_buf1 == NULL)
-        return (FALSE);
-
-	os_alloc_mem(NULL, &temp_buf2, MAX_PARAM_BUFFER_SIZE);
-	if(temp_buf2 == NULL)
-	{
-		os_free_mem(NULL, temp_buf1);
-        return (FALSE);
-	}
-
-    //find section
-	if(*end_offset == 0)
-    {
-		if ((offset = RTMPFindSection(buffer)) == NULL)
-		{
-			os_free_mem(NULL, temp_buf1);
-	    	os_free_mem(NULL, temp_buf2);
-    	    return (FALSE);
-		}
-    }
-	else
-		offset = buffer + (*end_offset);
-
-    strcpy(temp_buf1, "\n");
-    strcat(temp_buf1, key);
-    strcat(temp_buf1, "=");
-
-    //search key
-    if((start_ptr=rtstrstr(offset, temp_buf1))==NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    start_ptr+=strlen("\n");
-    if((end_ptr=rtstrstr(start_ptr, "\n"))==NULL)
-       end_ptr=start_ptr+strlen(start_ptr);
-
-    if (end_ptr<start_ptr)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-	*end_offset = end_ptr - buffer;
-
-    NdisMoveMemory(temp_buf2, start_ptr, end_ptr-start_ptr);
-    temp_buf2[end_ptr-start_ptr]='\0';
-    len = strlen(temp_buf2);
-    strcpy(temp_buf1, temp_buf2);
-    if((start_ptr=rtstrstr(temp_buf1, "=")) == NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    strcpy(temp_buf2, start_ptr+1);
-    ptr = temp_buf2;
-    //trim space or tab
-    while(*ptr != 0x00)
-    {
-        if((bTrimSpace && (*ptr == ' ')) || (*ptr == '\t') )
-            ptr++;
-        else
-           break;
-    }
-
-    len = strlen(ptr);
-    memset(dest, 0x00, destsize);
-    strncpy(dest, ptr, len >= destsize ?  destsize: len);
-
-	os_free_mem(NULL, temp_buf1);
-    os_free_mem(NULL, temp_buf2);
-    return TRUE;
-}
-
-
-static int rtmp_parse_key_buffer_from_file(IN  PRTMP_ADAPTER pAd,IN  char *buffer,IN  ULONG KeyType,IN  INT BSSIdx,IN  INT KeyIdx)
-{
-	PUCHAR		keybuff;
-	INT			i = BSSIdx, idx = KeyIdx;
-	ULONG		KeyLen;
-	UCHAR		CipherAlg = CIPHER_WEP64;
-
-	keybuff = buffer;
-	KeyLen = strlen(keybuff);
-
-	if (KeyType == 1)
-	{//Ascii
-		if( (KeyLen == 5) || (KeyLen == 13))
-		{
-			pAd->SharedKey[i][idx].KeyLen = KeyLen;
-			NdisMoveMemory(pAd->SharedKey[i][idx].Key, keybuff, KeyLen);
-			if (KeyLen == 5)
-				CipherAlg = CIPHER_WEP64;
-			else
-				CipherAlg = CIPHER_WEP128;
-			pAd->SharedKey[i][idx].CipherAlg = CipherAlg;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("I/F(ra%d) Key%dStr=%s and type=%s\n", i, idx+1, keybuff, (KeyType == 0) ? "Hex":"Ascii"));
-			return 1;
-		}
-		else
-		{//Invalid key length
-			DBGPRINT(RT_DEBUG_ERROR, ("Key%dStr is Invalid key length! KeyLen = %ld!\n", idx+1, KeyLen));
-			return 0;
-		}
-	}
-	else
-	{//Hex type
-		if( (KeyLen == 10) || (KeyLen == 26))
-		{
-			pAd->SharedKey[i][idx].KeyLen = KeyLen / 2;
-			AtoH(keybuff, pAd->SharedKey[i][idx].Key, KeyLen / 2);
-			if (KeyLen == 10)
-				CipherAlg = CIPHER_WEP64;
-			else
-				CipherAlg = CIPHER_WEP128;
-			pAd->SharedKey[i][idx].CipherAlg = CipherAlg;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("I/F(ra%d) Key%dStr=%s and type=%s\n", i, idx+1, keybuff, (KeyType == 0) ? "Hex":"Ascii"));
-			return 1;
-		}
-		else
-		{//Invalid key length
-			DBGPRINT(RT_DEBUG_ERROR, ("I/F(ra%d) Key%dStr is Invalid key length! KeyLen = %ld!\n", i, idx+1, KeyLen));
-			return 0;
-		}
-	}
-}
-static void rtmp_read_key_parms_from_file(IN  PRTMP_ADAPTER pAd, char *tmpbuf, char *buffer)
-{
-	char		tok_str[16];
-	PUCHAR		macptr;
-	INT			i = 0, idx;
-	ULONG		KeyType[MAX_MBSSID_NUM];
-	ULONG		KeyIdx;
-
-	NdisZeroMemory(KeyType, MAX_MBSSID_NUM);
-
-	//DefaultKeyID
-	if(RTMPGetKeyParameter("DefaultKeyID", tmpbuf, 25, buffer))
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			KeyIdx = simple_strtol(tmpbuf, 0, 10);
-			if((KeyIdx >= 1 ) && (KeyIdx <= 4))
-				pAd->StaCfg.DefaultKeyId = (UCHAR) (KeyIdx - 1);
-			else
-				pAd->StaCfg.DefaultKeyId = 0;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("DefaultKeyID(0~3)=%d\n", pAd->StaCfg.DefaultKeyId));
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-
-	for (idx = 0; idx < 4; idx++)
-	{
-		sprintf(tok_str, "Key%dType", idx + 1);
-		//Key1Type
-		if (RTMPGetKeyParameter(tok_str, tmpbuf, 128, buffer))
-		{
-		    for (i = 0, macptr = rstrtok(tmpbuf,";"); macptr; macptr = rstrtok(NULL,";"), i++)
-		    {
-			    KeyType[i] = simple_strtol(macptr, 0, 10);
-		    }
-
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			{
-				sprintf(tok_str, "Key%dStr", idx + 1);
-				if (RTMPGetCriticalParameter(tok_str, tmpbuf, 128, buffer))
-				{
-					rtmp_parse_key_buffer_from_file(pAd, tmpbuf, KeyType[BSS0], BSS0, idx);
-				}
-			}
-#endif // CONFIG_STA_SUPPORT //
-		}
-	}
-}
-
-
-#ifdef CONFIG_STA_SUPPORT
-static void rtmp_read_sta_wmm_parms_from_file(IN  PRTMP_ADAPTER pAd, char *tmpbuf, char *buffer)
-{
-	PUCHAR					macptr;
-	INT						i=0;
-	BOOLEAN					bWmmEnable = FALSE;
-
-	//WmmCapable
-	if(RTMPGetKeyParameter("WmmCapable", tmpbuf, 32, buffer))
-	{
-		if(simple_strtol(tmpbuf, 0, 10) != 0) //Enable
-		{
-			pAd->CommonCfg.bWmmCapable = TRUE;
-			bWmmEnable = TRUE;
-		}
-		else //Disable
-		{
-			pAd->CommonCfg.bWmmCapable = FALSE;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("WmmCapable=%d\n", pAd->CommonCfg.bWmmCapable));
-	}
-
-#ifdef QOS_DLS_SUPPORT
-	//DLSCapable
-	if(RTMPGetKeyParameter("DLSCapable", tmpbuf, 32, buffer))
-	{
-		if(simple_strtol(tmpbuf, 0, 10) != 0)  //Enable
-		{
-			pAd->CommonCfg.bDLSCapable = TRUE;
-		}
-		else //Disable
-		{
-			pAd->CommonCfg.bDLSCapable = FALSE;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("bDLSCapable=%d\n", pAd->CommonCfg.bDLSCapable));
-	}
-#endif // QOS_DLS_SUPPORT //
-
-	//AckPolicy for AC_BK, AC_BE, AC_VI, AC_VO
-	if(RTMPGetKeyParameter("AckPolicy", tmpbuf, 32, buffer))
-	{
-		for (i = 0, macptr = rstrtok(tmpbuf,";"); macptr; macptr = rstrtok(NULL,";"), i++)
-		{
-			pAd->CommonCfg.AckPolicy[i] = (UCHAR)simple_strtol(macptr, 0, 10);
-
-			DBGPRINT(RT_DEBUG_TRACE, ("AckPolicy[%d]=%d\n", i, pAd->CommonCfg.AckPolicy[i]));
-		}
-	}
-
-	if (bWmmEnable)
-	{
-		//APSDCapable
-		if(RTMPGetKeyParameter("APSDCapable", tmpbuf, 10, buffer))
-		{
-			if(simple_strtol(tmpbuf, 0, 10) != 0)  //Enable
-				pAd->CommonCfg.bAPSDCapable = TRUE;
-			else
-				pAd->CommonCfg.bAPSDCapable = FALSE;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("APSDCapable=%d\n", pAd->CommonCfg.bAPSDCapable));
-		}
-
-		//APSDAC for AC_BE, AC_BK, AC_VI, AC_VO
-		if(RTMPGetKeyParameter("APSDAC", tmpbuf, 32, buffer))
-		{
-			BOOLEAN apsd_ac[4];
-
-			for (i = 0, macptr = rstrtok(tmpbuf,";"); macptr; macptr = rstrtok(NULL,";"), i++)
-			{
-				apsd_ac[i] = (BOOLEAN)simple_strtol(macptr, 0, 10);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("APSDAC%d  %d\n", i,  apsd_ac[i]));
-			}
-
-			pAd->CommonCfg.bAPSDAC_BE = apsd_ac[0];
-			pAd->CommonCfg.bAPSDAC_BK = apsd_ac[1];
-			pAd->CommonCfg.bAPSDAC_VI = apsd_ac[2];
-			pAd->CommonCfg.bAPSDAC_VO = apsd_ac[3];
-		}
-	}
-
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-NDIS_STATUS	RTMPReadParametersHook(
-	IN	PRTMP_ADAPTER pAd)
-{
-	PUCHAR					src = NULL;
-	struct file				*srcf;
-	INT 					retval, orgfsuid, orgfsgid;
-   	mm_segment_t			orgfs;
-	CHAR					*buffer;
-	CHAR					*tmpbuf;
-	ULONG					RtsThresh;
-	ULONG					FragThresh;
-#ifdef CONFIG_STA_SUPPORT
-	UCHAR	                keyMaterial[40];
-#endif // CONFIG_STA_SUPPORT //
-
-
-	PUCHAR					macptr;
-	INT						i = 0;
-
-	buffer = kmalloc(MAX_INI_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	if(buffer == NULL)
-        return NDIS_STATUS_FAILURE;
-
-	tmpbuf = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	if(tmpbuf == NULL)
-	{
-		kfree(buffer);
-        return NDIS_STATUS_FAILURE;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		src = STA_PROFILE_PATH;
-#endif // CONFIG_STA_SUPPORT //
-#ifdef MULTIPLE_CARD_SUPPORT
-	src = pAd->MC_FileName;
-#endif // MULTIPLE_CARD_SUPPORT //
-
-	// Save uid and gid used for filesystem access.
-	// Set user and group to 0 (root)
-	orgfsuid = current_fsuid();
-	orgfsgid = current_fsgid();
-	/* Hm, can't really do this nicely anymore, so rely on these files
-	 * being set to the proper permission to read them... */
-	/* current->cred->fsuid = current->cred->fsgid = 0; */
-    orgfs = get_fs();
-    set_fs(KERNEL_DS);
-
-	if (src && *src)
-	{
-		srcf = filp_open(src, O_RDONLY, 0);
-		if (IS_ERR(srcf))
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("--> Error %ld opening %s\n", -PTR_ERR(srcf),src));
-		}
-		else
-		{
-			// The object must have a read method
-			if (srcf->f_op && srcf->f_op->read)
-			{
-				memset(buffer, 0x00, MAX_INI_BUFFER_SIZE);
-				retval=srcf->f_op->read(srcf, buffer, MAX_INI_BUFFER_SIZE, &srcf->f_pos);
-				if (retval < 0)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("--> Read %s error %d\n", src, -retval));
-				}
-				else
-				{
-					// set file parameter to portcfg
-					//CountryRegion
-					if(RTMPGetKeyParameter("CountryRegion", tmpbuf, 25, buffer))
-					{
-						pAd->CommonCfg.CountryRegion = (UCHAR) simple_strtol(tmpbuf, 0, 10);
-						DBGPRINT(RT_DEBUG_TRACE, ("CountryRegion=%d\n", pAd->CommonCfg.CountryRegion));
-					}
-					//CountryRegionABand
-					if(RTMPGetKeyParameter("CountryRegionABand", tmpbuf, 25, buffer))
-					{
-						pAd->CommonCfg.CountryRegionForABand= (UCHAR) simple_strtol(tmpbuf, 0, 10);
-						DBGPRINT(RT_DEBUG_TRACE, ("CountryRegionABand=%d\n", pAd->CommonCfg.CountryRegionForABand));
-					}
-					//CountryCode
-					if(RTMPGetKeyParameter("CountryCode", tmpbuf, 25, buffer))
-					{
-						NdisMoveMemory(pAd->CommonCfg.CountryCode, tmpbuf , 2);
-#ifdef CONFIG_STA_SUPPORT
-#ifdef EXT_BUILD_CHANNEL_LIST
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-							NdisMoveMemory(pAd->StaCfg.StaOriCountryCode, tmpbuf , 2);
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
-						if (strlen(pAd->CommonCfg.CountryCode) != 0)
-						{
-							pAd->CommonCfg.bCountryFlag = TRUE;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, ("CountryCode=%s\n", pAd->CommonCfg.CountryCode));
-					}
-					//ChannelGeography
-					if(RTMPGetKeyParameter("ChannelGeography", tmpbuf, 25, buffer))
-					{
-						UCHAR Geography = (UCHAR) simple_strtol(tmpbuf, 0, 10);
-						if (Geography <= BOTH)
-						{
-							pAd->CommonCfg.Geography = Geography;
-							pAd->CommonCfg.CountryCode[2] =
-								(pAd->CommonCfg.Geography == BOTH) ? ' ' : ((pAd->CommonCfg.Geography == IDOR) ? 'I' : 'O');
-#ifdef CONFIG_STA_SUPPORT
-#ifdef EXT_BUILD_CHANNEL_LIST
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-							pAd->StaCfg.StaOriGeography = pAd->CommonCfg.Geography;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
-							DBGPRINT(RT_DEBUG_TRACE, ("ChannelGeography=%d\n", pAd->CommonCfg.Geography));
-						}
-					}
-					else
-					{
-						pAd->CommonCfg.Geography = BOTH;
-						pAd->CommonCfg.CountryCode[2] = ' ';
-					}
-
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-					{
-						//SSID
-						if (RTMPGetCriticalParameter("SSID", tmpbuf, 256, buffer))
-						{
-							if (strlen(tmpbuf) <= 32)
-							{
-			 					pAd->CommonCfg.SsidLen = (UCHAR) strlen(tmpbuf);
-								NdisZeroMemory(pAd->CommonCfg.Ssid, NDIS_802_11_LENGTH_SSID);
-								NdisMoveMemory(pAd->CommonCfg.Ssid, tmpbuf, pAd->CommonCfg.SsidLen);
-								pAd->MlmeAux.AutoReconnectSsidLen = pAd->CommonCfg.SsidLen;
-								NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, NDIS_802_11_LENGTH_SSID);
-								NdisMoveMemory(pAd->MlmeAux.AutoReconnectSsid, tmpbuf, pAd->MlmeAux.AutoReconnectSsidLen);
-								pAd->MlmeAux.SsidLen = pAd->CommonCfg.SsidLen;
-								NdisZeroMemory(pAd->MlmeAux.Ssid, NDIS_802_11_LENGTH_SSID);
-								NdisMoveMemory(pAd->MlmeAux.Ssid, tmpbuf, pAd->MlmeAux.SsidLen);
-								DBGPRINT(RT_DEBUG_TRACE, ("%s::(SSID=%s)\n", __func__, tmpbuf));
-							}
-						}
-					}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-					{
-						//NetworkType
-						if (RTMPGetKeyParameter("NetworkType", tmpbuf, 25, buffer))
-						{
-							pAd->bConfigChanged = TRUE;
-							if (strcmp(tmpbuf, "Adhoc") == 0)
-								pAd->StaCfg.BssType = BSS_ADHOC;
-							else //Default Infrastructure mode
-								pAd->StaCfg.BssType = BSS_INFRA;
-							// Reset Ralink supplicant to not use, it will be set to start when UI set PMK key
-							pAd->StaCfg.WpaState = SS_NOTUSE;
-							DBGPRINT(RT_DEBUG_TRACE, ("%s::(NetworkType=%d)\n", __func__, pAd->StaCfg.BssType));
-						}
-					}
-#endif // CONFIG_STA_SUPPORT //
-					//Channel
-					if(RTMPGetKeyParameter("Channel", tmpbuf, 10, buffer))
-					{
-						pAd->CommonCfg.Channel = (UCHAR) simple_strtol(tmpbuf, 0, 10);
-						DBGPRINT(RT_DEBUG_TRACE, ("Channel=%d\n", pAd->CommonCfg.Channel));
-					}
-					//WirelessMode
-					if(RTMPGetKeyParameter("WirelessMode", tmpbuf, 10, buffer))
-					{
-						int value  = 0, maxPhyMode = PHY_11G;
-
-#ifdef DOT11_N_SUPPORT
-						maxPhyMode = PHY_11N_5G;
-#endif // DOT11_N_SUPPORT //
-
-						value = simple_strtol(tmpbuf, 0, 10);
-
-						if (value <= maxPhyMode)
-						{
-							pAd->CommonCfg.PhyMode = value;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, ("PhyMode=%d\n", pAd->CommonCfg.PhyMode));
-					}
-                    //BasicRate
-					if(RTMPGetKeyParameter("BasicRate", tmpbuf, 10, buffer))
-					{
-						pAd->CommonCfg.BasicRateBitmap = (ULONG) simple_strtol(tmpbuf, 0, 10);
-						DBGPRINT(RT_DEBUG_TRACE, ("BasicRate=%ld\n", pAd->CommonCfg.BasicRateBitmap));
-					}
-					//BeaconPeriod
-					if(RTMPGetKeyParameter("BeaconPeriod", tmpbuf, 10, buffer))
-					{
-						pAd->CommonCfg.BeaconPeriod = (USHORT) simple_strtol(tmpbuf, 0, 10);
-						DBGPRINT(RT_DEBUG_TRACE, ("BeaconPeriod=%d\n", pAd->CommonCfg.BeaconPeriod));
-					}
-                    //TxPower
-					if(RTMPGetKeyParameter("TxPower", tmpbuf, 10, buffer))
-					{
-						pAd->CommonCfg.TxPowerPercentage = (ULONG) simple_strtol(tmpbuf, 0, 10);
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-							pAd->CommonCfg.TxPowerDefault = pAd->CommonCfg.TxPowerPercentage;
-#endif // CONFIG_STA_SUPPORT //
-						DBGPRINT(RT_DEBUG_TRACE, ("TxPower=%ld\n", pAd->CommonCfg.TxPowerPercentage));
-					}
-					//BGProtection
-					if(RTMPGetKeyParameter("BGProtection", tmpbuf, 10, buffer))
-					{
-						switch (simple_strtol(tmpbuf, 0, 10))
-						{
-							case 1: //Always On
-								pAd->CommonCfg.UseBGProtection = 1;
-								break;
-							case 2: //Always OFF
-								pAd->CommonCfg.UseBGProtection = 2;
-								break;
-							case 0: //AUTO
-							default:
-								pAd->CommonCfg.UseBGProtection = 0;
-								break;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, ("BGProtection=%ld\n", pAd->CommonCfg.UseBGProtection));
-					}
-					//OLBCDetection
-					if(RTMPGetKeyParameter("DisableOLBC", tmpbuf, 10, buffer))
-					{
-						switch (simple_strtol(tmpbuf, 0, 10))
-						{
-							case 1: //disable OLBC Detection
-								pAd->CommonCfg.DisableOLBCDetect = 1;
-								break;
-							case 0: //enable OLBC Detection
-								pAd->CommonCfg.DisableOLBCDetect = 0;
-								break;
-							default:
-								pAd->CommonCfg.DisableOLBCDetect= 0;
-								break;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, ("OLBCDetection=%ld\n", pAd->CommonCfg.DisableOLBCDetect));
-					}
-					//TxPreamble
-					if(RTMPGetKeyParameter("TxPreamble", tmpbuf, 10, buffer))
-					{
-						switch (simple_strtol(tmpbuf, 0, 10))
-						{
-							case Rt802_11PreambleShort:
-								pAd->CommonCfg.TxPreamble = Rt802_11PreambleShort;
-								break;
-							case Rt802_11PreambleLong:
-							default:
-								pAd->CommonCfg.TxPreamble = Rt802_11PreambleLong;
-								break;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, ("TxPreamble=%ld\n", pAd->CommonCfg.TxPreamble));
-					}
-					//RTSThreshold
-					if(RTMPGetKeyParameter("RTSThreshold", tmpbuf, 10, buffer))
-					{
-						RtsThresh = simple_strtol(tmpbuf, 0, 10);
-						if( (RtsThresh >= 1) && (RtsThresh <= MAX_RTS_THRESHOLD) )
-							pAd->CommonCfg.RtsThreshold  = (USHORT)RtsThresh;
-						else
-							pAd->CommonCfg.RtsThreshold = MAX_RTS_THRESHOLD;
-
-						DBGPRINT(RT_DEBUG_TRACE, ("RTSThreshold=%d\n", pAd->CommonCfg.RtsThreshold));
-					}
-					//FragThreshold
-					if(RTMPGetKeyParameter("FragThreshold", tmpbuf, 10, buffer))
-					{
-						FragThresh = simple_strtol(tmpbuf, 0, 10);
-						pAd->CommonCfg.bUseZeroToDisableFragment = FALSE;
-
-						if (FragThresh > MAX_FRAG_THRESHOLD || FragThresh < MIN_FRAG_THRESHOLD)
-						{ //illegal FragThresh so we set it to default
-							pAd->CommonCfg.FragmentThreshold = MAX_FRAG_THRESHOLD;
-							pAd->CommonCfg.bUseZeroToDisableFragment = TRUE;
-						}
-						else if (FragThresh % 2 == 1)
-						{
-							// The length of each fragment shall always be an even number of octets, except for the last fragment
-							// of an MSDU or MMPDU, which may be either an even or an odd number of octets.
-							pAd->CommonCfg.FragmentThreshold = (USHORT)(FragThresh - 1);
-						}
-						else
-						{
-							pAd->CommonCfg.FragmentThreshold = (USHORT)FragThresh;
-						}
-						//pAd->CommonCfg.AllowFragSize = (pAd->CommonCfg.FragmentThreshold) - LENGTH_802_11 - LENGTH_CRC;
-						DBGPRINT(RT_DEBUG_TRACE, ("FragThreshold=%d\n", pAd->CommonCfg.FragmentThreshold));
-					}
-					//TxBurst
-					if(RTMPGetKeyParameter("TxBurst", tmpbuf, 10, buffer))
-					{
-//#ifdef WIFI_TEST
-//						pAd->CommonCfg.bEnableTxBurst = FALSE;
-//#else
-						if(simple_strtol(tmpbuf, 0, 10) != 0)  //Enable
-							pAd->CommonCfg.bEnableTxBurst = TRUE;
-						else //Disable
-							pAd->CommonCfg.bEnableTxBurst = FALSE;
-//#endif
-						DBGPRINT(RT_DEBUG_TRACE, ("TxBurst=%d\n", pAd->CommonCfg.bEnableTxBurst));
-					}
-
-#ifdef AGGREGATION_SUPPORT
-					//PktAggregate
-					if(RTMPGetKeyParameter("PktAggregate", tmpbuf, 10, buffer))
-					{
-						if(simple_strtol(tmpbuf, 0, 10) != 0)  //Enable
-							pAd->CommonCfg.bAggregationCapable = TRUE;
-						else //Disable
-							pAd->CommonCfg.bAggregationCapable = FALSE;
-#ifdef PIGGYBACK_SUPPORT
-						pAd->CommonCfg.bPiggyBackCapable = pAd->CommonCfg.bAggregationCapable;
-#endif // PIGGYBACK_SUPPORT //
-						DBGPRINT(RT_DEBUG_TRACE, ("PktAggregate=%d\n", pAd->CommonCfg.bAggregationCapable));
-					}
-#else
-					pAd->CommonCfg.bAggregationCapable = FALSE;
-					pAd->CommonCfg.bPiggyBackCapable = FALSE;
-#endif // AGGREGATION_SUPPORT //
-
-					// WmmCapable
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-						rtmp_read_sta_wmm_parms_from_file(pAd, tmpbuf, buffer);
-#endif // CONFIG_STA_SUPPORT //
-
-					//ShortSlot
-					if(RTMPGetKeyParameter("ShortSlot", tmpbuf, 10, buffer))
-					{
-						if(simple_strtol(tmpbuf, 0, 10) != 0)  //Enable
-							pAd->CommonCfg.bUseShortSlotTime = TRUE;
-						else //Disable
-							pAd->CommonCfg.bUseShortSlotTime = FALSE;
-
-						DBGPRINT(RT_DEBUG_TRACE, ("ShortSlot=%d\n", pAd->CommonCfg.bUseShortSlotTime));
-					}
-					//IEEE80211H
-					if(RTMPGetKeyParameter("IEEE80211H", tmpbuf, 10, buffer))
-					{
-					    for (i = 0, macptr = rstrtok(tmpbuf,";"); macptr; macptr = rstrtok(NULL,";"), i++)
-					    {
-    						if(simple_strtol(macptr, 0, 10) != 0)  //Enable
-    							pAd->CommonCfg.bIEEE80211H = TRUE;
-    						else //Disable
-    							pAd->CommonCfg.bIEEE80211H = FALSE;
-
-    						DBGPRINT(RT_DEBUG_TRACE, ("IEEE80211H=%d\n", pAd->CommonCfg.bIEEE80211H));
-					    }
-					}
-					//CSPeriod
-					if(RTMPGetKeyParameter("CSPeriod", tmpbuf, 10, buffer))
-					{
-					    if(simple_strtol(tmpbuf, 0, 10) != 0)
-							pAd->CommonCfg.RadarDetect.CSPeriod = simple_strtol(tmpbuf, 0, 10);
-						else
-							pAd->CommonCfg.RadarDetect.CSPeriod = 0;
-
-   						DBGPRINT(RT_DEBUG_TRACE, ("CSPeriod=%d\n", pAd->CommonCfg.RadarDetect.CSPeriod));
-					}
-
-					//RDRegion
-					if(RTMPGetKeyParameter("RDRegion", tmpbuf, 128, buffer))
-					{
-						if ((strncmp(tmpbuf, "JAP_W53", 7) == 0) || (strncmp(tmpbuf, "jap_w53", 7) == 0))
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = JAP_W53;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 15;
-						}
-						else if ((strncmp(tmpbuf, "JAP_W56", 7) == 0) || (strncmp(tmpbuf, "jap_w56", 7) == 0))
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = JAP_W56;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 13;
-						}
-						else if ((strncmp(tmpbuf, "JAP", 3) == 0) || (strncmp(tmpbuf, "jap", 3) == 0))
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = JAP;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 5;
-						}
-						else  if ((strncmp(tmpbuf, "FCC", 3) == 0) || (strncmp(tmpbuf, "fcc", 3) == 0))
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = FCC;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 5;
-						}
-						else if ((strncmp(tmpbuf, "CE", 2) == 0) || (strncmp(tmpbuf, "ce", 2) == 0))
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = CE;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 13;
-						}
-						else
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = CE;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 13;
-						}
-
-						DBGPRINT(RT_DEBUG_TRACE, ("RDRegion=%d\n", pAd->CommonCfg.RadarDetect.RDDurRegion));
-					}
-					else
-					{
-						pAd->CommonCfg.RadarDetect.RDDurRegion = CE;
-						pAd->CommonCfg.RadarDetect.DfsSessionTime = 13;
-					}
-
-					//WirelessEvent
-					if(RTMPGetKeyParameter("WirelessEvent", tmpbuf, 10, buffer))
-					{
-#if WIRELESS_EXT >= 15
-					    if(simple_strtol(tmpbuf, 0, 10) != 0)
-							pAd->CommonCfg.bWirelessEvent = simple_strtol(tmpbuf, 0, 10);
-						else
-							pAd->CommonCfg.bWirelessEvent = 0;	// disable
-#else
-						pAd->CommonCfg.bWirelessEvent = 0;	// disable
-#endif
-   						DBGPRINT(RT_DEBUG_TRACE, ("WirelessEvent=%d\n", pAd->CommonCfg.bWirelessEvent));
-					}
-					if(RTMPGetKeyParameter("WiFiTest", tmpbuf, 10, buffer))
-					{
-					    if(simple_strtol(tmpbuf, 0, 10) != 0)
-							pAd->CommonCfg.bWiFiTest= simple_strtol(tmpbuf, 0, 10);
-						else
-							pAd->CommonCfg.bWiFiTest = 0;	// disable
-
-   						DBGPRINT(RT_DEBUG_TRACE, ("WiFiTest=%d\n", pAd->CommonCfg.bWiFiTest));
-					}
-					//AuthMode
-					if(RTMPGetKeyParameter("AuthMode", tmpbuf, 128, buffer))
-					{
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-						{
-							if ((strcmp(tmpbuf, "WEPAUTO") == 0) || (strcmp(tmpbuf, "wepauto") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeAutoSwitch;
-							else if ((strcmp(tmpbuf, "SHARED") == 0) || (strcmp(tmpbuf, "shared") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-							else if ((strcmp(tmpbuf, "WPAPSK") == 0) || (strcmp(tmpbuf, "wpapsk") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPAPSK;
-							else if ((strcmp(tmpbuf, "WPANONE") == 0) || (strcmp(tmpbuf, "wpanone") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
-							else if ((strcmp(tmpbuf, "WPA2PSK") == 0) || (strcmp(tmpbuf, "wpa2psk") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-#ifdef WPA_SUPPLICANT_SUPPORT
-							else if ((strcmp(tmpbuf, "WPA") == 0) || (strcmp(tmpbuf, "wpa") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
-							else if ((strcmp(tmpbuf, "WPA2") == 0) || (strcmp(tmpbuf, "wpa2") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#endif // WPA_SUPPLICANT_SUPPORT //
-				                        else
-				                            pAd->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-
-				                        pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-
-							DBGPRINT(RT_DEBUG_TRACE, ("%s::(EncrypType=%d)\n", __func__, pAd->StaCfg.WepStatus));
-						}
-#endif // CONFIG_STA_SUPPORT //
-					}
-					//EncrypType
-					if(RTMPGetKeyParameter("EncrypType", tmpbuf, 128, buffer))
-					{
-
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-						{
-							if ((strcmp(tmpbuf, "WEP") == 0) || (strcmp(tmpbuf, "wep") == 0))
-								pAd->StaCfg.WepStatus	= Ndis802_11WEPEnabled;
-							else if ((strcmp(tmpbuf, "TKIP") == 0) || (strcmp(tmpbuf, "tkip") == 0))
-								pAd->StaCfg.WepStatus	= Ndis802_11Encryption2Enabled;
-							else if ((strcmp(tmpbuf, "AES") == 0) || (strcmp(tmpbuf, "aes") == 0))
-								pAd->StaCfg.WepStatus	= Ndis802_11Encryption3Enabled;
-							else
-								pAd->StaCfg.WepStatus	= Ndis802_11WEPDisabled;
-
-							// Update all wepstatus related
-							pAd->StaCfg.PairCipher		= pAd->StaCfg.WepStatus;
-							pAd->StaCfg.GroupCipher 	= pAd->StaCfg.WepStatus;
-							pAd->StaCfg.OrigWepStatus 	= pAd->StaCfg.WepStatus;
-							pAd->StaCfg.bMixCipher 		= FALSE;
-
-							//RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, 0);
-							DBGPRINT(RT_DEBUG_TRACE, ("%s::(EncrypType=%d)\n", __func__, pAd->StaCfg.WepStatus));
-						}
-#endif // CONFIG_STA_SUPPORT //
-					}
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-					{
-						if(RTMPGetCriticalParameter("WPAPSK", tmpbuf, 512, buffer))
-						{
-							int     err=0;
-
-							tmpbuf[strlen(tmpbuf)] = '\0'; // make STA can process .$^& for WPAPSK input
-
-							if ((pAd->StaCfg.AuthMode != Ndis802_11AuthModeWPAPSK) &&
-								(pAd->StaCfg.AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-								(pAd->StaCfg.AuthMode != Ndis802_11AuthModeWPANone)
-								)
-							{
-								err = 1;
-							}
-							else if ((strlen(tmpbuf) >= 8) && (strlen(tmpbuf) < 64))
-							{
-								PasswordHash((char *)tmpbuf, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen, keyMaterial);
-								NdisMoveMemory(pAd->StaCfg.PMK, keyMaterial, 32);
-
-							}
-							else if (strlen(tmpbuf) == 64)
-							{
-								AtoH(tmpbuf, keyMaterial, 32);
-								NdisMoveMemory(pAd->StaCfg.PMK, keyMaterial, 32);
-							}
-							else
-							{
-								err = 1;
-								DBGPRINT(RT_DEBUG_ERROR, ("%s::(WPAPSK key-string required 8 ~ 64 characters!)\n", __func__));
-							}
-
-							if (err == 0)
-	                        			{
-	                        				if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-									(pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-								{
-									// Start STA supplicant state machine
-									pAd->StaCfg.WpaState = SS_START;
-								}
-								else if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-								{
-	/*
-									NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-									pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-									NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, pAd->StaCfg.PMK, LEN_TKIP_EK);
-									NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, &pAd->StaCfg.PMK[16], LEN_TKIP_RXMICK);
-									NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, &pAd->StaCfg.PMK[16], LEN_TKIP_TXMICK);
-
-									// Decide its ChiperAlg
-									if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-										pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-									else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-										pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-									else
-										pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_NONE;
-	*/
-									pAd->StaCfg.WpaState = SS_NOTUSE;
-								}
-
-								DBGPRINT(RT_DEBUG_TRACE, ("%s::(WPAPSK=%s)\n", __func__, tmpbuf));
-							}
-						}
-					}
-#endif // CONFIG_STA_SUPPORT //
-
-					//DefaultKeyID, KeyType, KeyStr
-					rtmp_read_key_parms_from_file(pAd, tmpbuf, buffer);
-
-
-					//HSCounter
-					/*if(RTMPGetKeyParameter("HSCounter", tmpbuf, 10, buffer))
-					{
-						switch (simple_strtol(tmpbuf, 0, 10))
-						{
-							case 1: //Enable
-								pAd->CommonCfg.bEnableHSCounter = TRUE;
-								break;
-							case 0: //Disable
-							default:
-								pAd->CommonCfg.bEnableHSCounter = FALSE;
-								break;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, "HSCounter=%d\n", pAd->CommonCfg.bEnableHSCounter);
-					}*/
-
-#ifdef DOT11_N_SUPPORT
-					HTParametersHook(pAd, tmpbuf, buffer);
-#endif // DOT11_N_SUPPORT //
-
-
-#ifdef CARRIER_DETECTION_SUPPORT
-						//CarrierDetect
-						if(RTMPGetKeyParameter("CarrierDetect", tmpbuf, 128, buffer))
-						{
-							if ((strncmp(tmpbuf, "0", 1) == 0))
-								pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-							else if ((strncmp(tmpbuf, "1", 1) == 0))
-								pAd->CommonCfg.CarrierDetect.Enable = TRUE;
-							else
-								pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-
-							DBGPRINT(RT_DEBUG_TRACE, ("CarrierDetect.Enable=%d\n", pAd->CommonCfg.CarrierDetect.Enable));
-						}
-						else
-							pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-#endif // CARRIER_DETECTION_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-					{
-						//PSMode
-						if (RTMPGetKeyParameter("PSMode", tmpbuf, 10, buffer))
-						{
-							if (pAd->StaCfg.BssType == BSS_INFRA)
-							{
-								if ((strcmp(tmpbuf, "MAX_PSP") == 0) || (strcmp(tmpbuf, "max_psp") == 0))
-								{
-									// do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-									// to exclude certain situations.
-									//	   MlmeSetPsm(pAd, PWR_SAVE);
-									OPSTATUS_SET_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM);
-									if (pAd->StaCfg.bWindowsACCAMEnable == FALSE)
-										pAd->StaCfg.WindowsPowerMode = Ndis802_11PowerModeMAX_PSP;
-									pAd->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeMAX_PSP;
-									pAd->StaCfg.DefaultListenCount = 5;
-								}
-								else if ((strcmp(tmpbuf, "Fast_PSP") == 0) || (strcmp(tmpbuf, "fast_psp") == 0)
-									|| (strcmp(tmpbuf, "FAST_PSP") == 0))
-								{
-									// do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-									// to exclude certain situations.
-									//	   MlmeSetPsmBit(pAd, PWR_SAVE);
-									OPSTATUS_SET_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM);
-									if (pAd->StaCfg.bWindowsACCAMEnable == FALSE)
-										pAd->StaCfg.WindowsPowerMode = Ndis802_11PowerModeFast_PSP;
-									pAd->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeFast_PSP;
-									pAd->StaCfg.DefaultListenCount = 3;
-								}
-								else if ((strcmp(tmpbuf, "Legacy_PSP") == 0) || (strcmp(tmpbuf, "legacy_psp") == 0)
-									|| (strcmp(tmpbuf, "LEGACY_PSP") == 0))
-								{
-									// do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-									// to exclude certain situations.
-									//	   MlmeSetPsmBit(pAd, PWR_SAVE);
-									OPSTATUS_SET_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM);
-									if (pAd->StaCfg.bWindowsACCAMEnable == FALSE)
-										pAd->StaCfg.WindowsPowerMode = Ndis802_11PowerModeLegacy_PSP;
-									pAd->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeLegacy_PSP;
-									pAd->StaCfg.DefaultListenCount = 3;
-								}
-								else
-								{ //Default Ndis802_11PowerModeCAM
-									// clear PSM bit immediately
-									MlmeSetPsmBit(pAd, PWR_ACTIVE);
-									OPSTATUS_SET_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM);
-									if (pAd->StaCfg.bWindowsACCAMEnable == FALSE)
-										pAd->StaCfg.WindowsPowerMode = Ndis802_11PowerModeCAM;
-									pAd->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeCAM;
-								}
-								DBGPRINT(RT_DEBUG_TRACE, ("PSMode=%ld\n", pAd->StaCfg.WindowsPowerMode));
-							}
-						}
-						// FastRoaming
-						if (RTMPGetKeyParameter("FastRoaming", tmpbuf, 32, buffer))
-						{
-							if (simple_strtol(tmpbuf, 0, 10) == 0)
-								pAd->StaCfg.bFastRoaming = FALSE;
-							else
-								pAd->StaCfg.bFastRoaming = TRUE;
-
-							DBGPRINT(RT_DEBUG_TRACE, ("FastRoaming=%d\n", pAd->StaCfg.bFastRoaming));
-						}
-						// RoamThreshold
-						if (RTMPGetKeyParameter("RoamThreshold", tmpbuf, 32, buffer))
-						{
-							long lInfo = simple_strtol(tmpbuf, 0, 10);
-
-							if (lInfo > 90 || lInfo < 60)
-								pAd->StaCfg.dBmToRoam = -70;
-							else
-								pAd->StaCfg.dBmToRoam = (CHAR)(-1)*lInfo;
-
-							DBGPRINT(RT_DEBUG_TRACE, ("RoamThreshold=%d  dBm\n", pAd->StaCfg.dBmToRoam));
-						}
-
-						if(RTMPGetKeyParameter("TGnWifiTest", tmpbuf, 10, buffer))
-						{
-							if(simple_strtol(tmpbuf, 0, 10) == 0)
-								pAd->StaCfg.bTGnWifiTest = FALSE;
-							else
-								pAd->StaCfg.bTGnWifiTest = TRUE;
-								DBGPRINT(RT_DEBUG_TRACE, ("TGnWifiTest=%d\n", pAd->StaCfg.bTGnWifiTest));
-						}
-					}
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-				}
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("--> %s does not have a write method\n", src));
-			}
-
-			retval=filp_close(srcf,NULL);
-
-			if (retval)
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("--> Error %d closing %s\n", -retval, src));
-			}
-		}
-	}
-
-	set_fs(orgfs);
-#if 0
-	current->fsuid = orgfsuid;
-	current->fsgid = orgfsgid;
-#endif
-
-	kfree(buffer);
-	kfree(tmpbuf);
-
-	return (NDIS_STATUS_SUCCESS);
-}
-
-#ifdef DOT11_N_SUPPORT
-static void	HTParametersHook(
-	IN	PRTMP_ADAPTER pAd,
-	IN	CHAR		  *pValueStr,
-	IN	CHAR		  *pInput)
-{
-
-	INT Value;
-
-    if (RTMPGetKeyParameter("HT_PROTECT", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value == 0)
-        {
-            pAd->CommonCfg.bHTProtect = FALSE;
-        }
-        else
-        {
-            pAd->CommonCfg.bHTProtect = TRUE;
-        }
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: Protection  = %s\n", (Value==0) ? "Disable" : "Enable"));
-    }
-
-    if (RTMPGetKeyParameter("HT_MIMOPSEnable", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value == 0)
-        {
-            pAd->CommonCfg.bMIMOPSEnable = FALSE;
-        }
-        else
-        {
-            pAd->CommonCfg.bMIMOPSEnable = TRUE;
-        }
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: MIMOPSEnable  = %s\n", (Value==0) ? "Disable" : "Enable"));
-    }
-
-
-    if (RTMPGetKeyParameter("HT_MIMOPSMode", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value > MMPS_ENABLE)
-        {
-			pAd->CommonCfg.BACapability.field.MMPSmode = MMPS_ENABLE;
-        }
-        else
-        {
-            //TODO: add mimo power saving mechanism
-            pAd->CommonCfg.BACapability.field.MMPSmode = MMPS_ENABLE;
-			//pAd->CommonCfg.BACapability.field.MMPSmode = Value;
-        }
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: MIMOPS Mode  = %d\n", Value));
-    }
-
-    if (RTMPGetKeyParameter("HT_BADecline", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value == 0)
-        {
-            pAd->CommonCfg.bBADecline = FALSE;
-        }
-        else
-        {
-            pAd->CommonCfg.bBADecline = TRUE;
-        }
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: BA Decline  = %s\n", (Value==0) ? "Disable" : "Enable"));
-    }
-
-
-    if (RTMPGetKeyParameter("HT_DisableReordering", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value == 0)
-        {
-            pAd->CommonCfg.bDisableReordering = FALSE;
-        }
-        else
-        {
-            pAd->CommonCfg.bDisableReordering = TRUE;
-        }
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: DisableReordering  = %s\n", (Value==0) ? "Disable" : "Enable"));
-    }
-
-    if (RTMPGetKeyParameter("HT_AutoBA", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value == 0)
-        {
-            pAd->CommonCfg.BACapability.field.AutoBA = FALSE;
-        }
-        else
-        {
-            pAd->CommonCfg.BACapability.field.AutoBA = TRUE;
-        }
-        pAd->CommonCfg.REGBACapability.field.AutoBA = pAd->CommonCfg.BACapability.field.AutoBA;
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: Auto BA  = %s\n", (Value==0) ? "Disable" : "Enable"));
-    }
-
-	// Tx_+HTC frame
-    if (RTMPGetKeyParameter("HT_HTC", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == 0)
-		{
-			pAd->HTCEnable = FALSE;
-		}
-		else
-		{
-            		pAd->HTCEnable = TRUE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Tx +HTC frame = %s\n", (Value==0) ? "Disable" : "Enable"));
-	}
-
-	// Enable HT Link Adaptation Control
-	if (RTMPGetKeyParameter("HT_LinkAdapt", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == 0)
-		{
-			pAd->bLinkAdapt = FALSE;
-		}
-		else
-		{
-			pAd->HTCEnable = TRUE;
-			pAd->bLinkAdapt = TRUE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Link Adaptation Control = %s\n", (Value==0) ? "Disable" : "Enable(+HTC)"));
-	}
-
-	// Reverse Direction Mechanism
-    if (RTMPGetKeyParameter("HT_RDG", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == 0)
-		{
-			pAd->CommonCfg.bRdg = FALSE;
-		}
-		else
-		{
-			pAd->HTCEnable = TRUE;
-            pAd->CommonCfg.bRdg = TRUE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: RDG = %s\n", (Value==0) ? "Disable" : "Enable(+HTC)"));
-	}
-
-
-
-
-	// Tx A-MSUD ?
-    if (RTMPGetKeyParameter("HT_AMSDU", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == 0)
-		{
-			pAd->CommonCfg.BACapability.field.AmsduEnable = FALSE;
-		}
-		else
-		{
-            pAd->CommonCfg.BACapability.field.AmsduEnable = TRUE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Tx A-MSDU = %s\n", (Value==0) ? "Disable" : "Enable"));
-	}
-
-	// MPDU Density
-    if (RTMPGetKeyParameter("HT_MpduDensity", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value <=7 && Value >= 0)
-		{
-			pAd->CommonCfg.BACapability.field.MpduDensity = Value;
-			DBGPRINT(RT_DEBUG_TRACE, ("HT: MPDU Density = %d\n", Value));
-		}
-		else
-		{
-			pAd->CommonCfg.BACapability.field.MpduDensity = 4;
-			DBGPRINT(RT_DEBUG_TRACE, ("HT: MPDU Density = %d (Default)\n", 4));
-		}
-	}
-
-	// Max Rx BA Window Size
-    if (RTMPGetKeyParameter("HT_BAWinSize", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-
-		if (Value >=1 && Value <= 64)
-		{
-			pAd->CommonCfg.REGBACapability.field.RxBAWinLimit = Value;
-			pAd->CommonCfg.BACapability.field.RxBAWinLimit = Value;
-			DBGPRINT(RT_DEBUG_TRACE, ("HT: BA Windw Size = %d\n", Value));
-		}
-		else
-		{
-            pAd->CommonCfg.REGBACapability.field.RxBAWinLimit = 64;
-			pAd->CommonCfg.BACapability.field.RxBAWinLimit = 64;
-			DBGPRINT(RT_DEBUG_TRACE, ("HT: BA Windw Size = 64 (Defualt)\n"));
-		}
-
-	}
-
-	// Guard Interval
-	if (RTMPGetKeyParameter("HT_GI", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-
-		if (Value == GI_400)
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.ShortGI = GI_400;
-		}
-		else
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.ShortGI = GI_800;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Guard Interval = %s\n", (Value==GI_400) ? "400" : "800" ));
-	}
-
-	// HT Operation Mode : Mixed Mode , Green Field
-	if (RTMPGetKeyParameter("HT_OpMode", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-
-		if (Value == HTMODE_GF)
-		{
-
-			pAd->CommonCfg.RegTransmitSetting.field.HTMODE  = HTMODE_GF;
-		}
-		else
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.HTMODE  = HTMODE_MM;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Operate Mode = %s\n", (Value==HTMODE_GF) ? "Green Field" : "Mixed Mode" ));
-	}
-
-	// Fixed Tx mode : CCK, OFDM
-	if (RTMPGetKeyParameter("FixedTxMode", pValueStr, 25, pInput))
-	{
-		UCHAR	fix_tx_mode;
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			fix_tx_mode = FIXED_TXMODE_HT;
-
-			if (strcmp(pValueStr, "OFDM") == 0 || strcmp(pValueStr, "ofdm") == 0)
-			{
-				fix_tx_mode = FIXED_TXMODE_OFDM;
-			}
-			else if (strcmp(pValueStr, "CCK") == 0 || strcmp(pValueStr, "cck") == 0)
-			{
-		        fix_tx_mode = FIXED_TXMODE_CCK;
-			}
-			else if (strcmp(pValueStr, "HT") == 0 || strcmp(pValueStr, "ht") == 0)
-			{
-		        fix_tx_mode = FIXED_TXMODE_HT;
-		}
-		else
-		{
-				Value = simple_strtol(pValueStr, 0, 10);
-				// 1 : CCK
-				// 2 : OFDM
-				// otherwise : HT
-				if (Value == FIXED_TXMODE_CCK || Value == FIXED_TXMODE_OFDM)
-					fix_tx_mode = Value;
-				else
-					fix_tx_mode = FIXED_TXMODE_HT;
-		}
-
-			pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode = fix_tx_mode;
-			DBGPRINT(RT_DEBUG_TRACE, ("Fixed Tx Mode = %d\n", fix_tx_mode));
-
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-
-	// Channel Width
-	if (RTMPGetKeyParameter("HT_BW", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-
-		if (Value == BW_40)
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_40;
-		}
-		else
-		{
-            pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-		}
-
-#ifdef MCAST_RATE_SPECIFIC
-		pAd->CommonCfg.MCastPhyMode.field.BW = pAd->CommonCfg.RegTransmitSetting.field.BW;
-#endif // MCAST_RATE_SPECIFIC //
-
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Channel Width = %s\n", (Value==BW_40) ? "40 MHz" : "20 MHz" ));
-	}
-
-	if (RTMPGetKeyParameter("HT_EXTCHA", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-
-		if (Value == 0)
-		{
-
-			pAd->CommonCfg.RegTransmitSetting.field.EXTCHA  = EXTCHA_BELOW;
-		}
-		else
-		{
-            pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Ext Channel = %s\n", (Value==0) ? "BELOW" : "ABOVE" ));
-	}
-
-	// MSC
-	if (RTMPGetKeyParameter("HT_MCS", pValueStr, 50, pInput))
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			Value = simple_strtol(pValueStr, 0, 10);
-
-//			if ((Value >= 0 && Value <= 15) || (Value == 32))
-			if ((Value >= 0 && Value <= 23) || (Value == 32)) // 3*3
-		{
-				pAd->StaCfg.DesiredTransmitSetting.field.MCS  = Value;
-				pAd->StaCfg.bAutoTxRateSwitch = FALSE;
-				DBGPRINT(RT_DEBUG_TRACE, ("HT: MCS = %d\n", pAd->StaCfg.DesiredTransmitSetting.field.MCS));
-		}
-		else
-		{
-				pAd->StaCfg.DesiredTransmitSetting.field.MCS  = MCS_AUTO;
-				pAd->StaCfg.bAutoTxRateSwitch = TRUE;
-				DBGPRINT(RT_DEBUG_TRACE, ("HT: MCS = AUTO\n"));
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	// STBC
-    if (RTMPGetKeyParameter("HT_STBC", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == STBC_USE)
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.STBC = STBC_USE;
-		}
-		else
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.STBC = STBC_NONE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: STBC = %d\n", pAd->CommonCfg.RegTransmitSetting.field.STBC));
-	}
-
-	// 40_Mhz_Intolerant
-	if (RTMPGetKeyParameter("HT_40MHZ_INTOLERANT", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == 0)
-		{
-			pAd->CommonCfg.bForty_Mhz_Intolerant = FALSE;
-		}
-		else
-		{
-			pAd->CommonCfg.bForty_Mhz_Intolerant = TRUE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: 40MHZ INTOLERANT = %d\n", pAd->CommonCfg.bForty_Mhz_Intolerant));
-	}
-	//HT_TxStream
-	if(RTMPGetKeyParameter("HT_TxStream", pValueStr, 10, pInput))
-	{
-		switch (simple_strtol(pValueStr, 0, 10))
-		{
-			case 1:
-				pAd->CommonCfg.TxStream = 1;
-				break;
-			case 2:
-				pAd->CommonCfg.TxStream = 2;
-				break;
-			case 3: // 3*3
-			default:
-				pAd->CommonCfg.TxStream = 3;
-
-				if (pAd->MACVersion < RALINK_2883_VERSION)
-					pAd->CommonCfg.TxStream = 2; // only 2 tx streams for RT2860 series
-				break;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Tx Stream = %d\n", pAd->CommonCfg.TxStream));
-	}
-	//HT_RxStream
-	if(RTMPGetKeyParameter("HT_RxStream", pValueStr, 10, pInput))
-	{
-		switch (simple_strtol(pValueStr, 0, 10))
-		{
-			case 1:
-				pAd->CommonCfg.RxStream = 1;
-				break;
-			case 2:
-				pAd->CommonCfg.RxStream = 2;
-				break;
-			case 3:
-			default:
-				pAd->CommonCfg.RxStream = 3;
-
-				if (pAd->MACVersion < RALINK_2883_VERSION)
-					pAd->CommonCfg.RxStream = 2; // only 2 rx streams for RT2860 series
-				break;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Rx Stream = %d\n", pAd->CommonCfg.RxStream));
-	}
-
-}
-#endif // DOT11_N_SUPPORT //
-
+#include "../rt2860/rt_profile.c"
diff --git a/drivers/staging/rt2870/rtmp.h b/drivers/staging/rt2870/rtmp.h
index c2a4784..e5ef89f 100644
--- a/drivers/staging/rt2870/rtmp.h
+++ b/drivers/staging/rt2870/rtmp.h
@@ -1,7586 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    rtmp.h
-
-    Abstract:
-    Miniport generic portion header file
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Paul Lin    2002-08-01    created
-    James Tan   2002-09-06    modified (Revise NTCRegTable)
-    John Chang  2004-09-06    modified for RT2600
-*/
-#ifndef __RTMP_H__
-#define __RTMP_H__
-
-#include "link_list.h"
-#include "spectrum_def.h"
-
-
-#ifdef CONFIG_STA_SUPPORT
-#include "aironet.h"
-#endif // CONFIG_STA_SUPPORT //
-
-//#define DBG		1
-
-//#define DBG_DIAGNOSE		1
-
-#if defined(CONFIG_AP_SUPPORT) && defined(CONFIG_STA_SUPPORT)
-#define IF_DEV_CONFIG_OPMODE_ON_AP(_pAd)	if(_pAd->OpMode == OPMODE_AP)
-#define IF_DEV_CONFIG_OPMODE_ON_STA(_pAd)	if(_pAd->OpMode == OPMODE_STA)
-#else
-#define IF_DEV_CONFIG_OPMODE_ON_AP(_pAd)
-#define IF_DEV_CONFIG_OPMODE_ON_STA(_pAd)
-#endif
-
-#define VIRTUAL_IF_INC(__pAd) ((__pAd)->VirtualIfCnt++)
-#define VIRTUAL_IF_DEC(__pAd) ((__pAd)->VirtualIfCnt--)
-#define VIRTUAL_IF_NUM(__pAd) ((__pAd)->VirtualIfCnt)
-
-#ifdef RT2870
-////////////////////////////////////////////////////////////////////////////
-// The TX_BUFFER structure forms the transmitted USB packet to the device
-////////////////////////////////////////////////////////////////////////////
-typedef struct __TX_BUFFER{
-	union	{
-		UCHAR			WirelessPacket[TX_BUFFER_NORMSIZE];
-		HEADER_802_11	NullFrame;
-		PSPOLL_FRAME	PsPollPacket;
-		RTS_FRAME		RTSFrame;
-	}field;
-	UCHAR			Aggregation[4];  //Buffer for save Aggregation size.
-} TX_BUFFER, *PTX_BUFFER;
-
-typedef struct __HTTX_BUFFER{
-	union	{
-		UCHAR			WirelessPacket[MAX_TXBULK_SIZE];
-		HEADER_802_11	NullFrame;
-		PSPOLL_FRAME	PsPollPacket;
-		RTS_FRAME		RTSFrame;
-	}field;
-	UCHAR			Aggregation[4];  //Buffer for save Aggregation size.
-} HTTX_BUFFER, *PHTTX_BUFFER;
-
-
-// used to track driver-generated write irps
-typedef struct _TX_CONTEXT
-{
-	PVOID			pAd;		//Initialized in MiniportInitialize
-	PURB			pUrb;			//Initialized in MiniportInitialize
-	PIRP			pIrp;			//used to cancel pending bulk out.
-									//Initialized in MiniportInitialize
-	PTX_BUFFER		TransferBuffer;	//Initialized in MiniportInitialize
-	ULONG			BulkOutSize;
-	UCHAR			BulkOutPipeId;
-	UCHAR			SelfIdx;
-	BOOLEAN			InUse;
-	BOOLEAN			bWaitingBulkOut; // at least one packet is in this TxContext, ready for making IRP anytime.
-	BOOLEAN			bFullForBulkOut; // all tx buffer are full , so waiting for tx bulkout.
-	BOOLEAN			IRPPending;
-	BOOLEAN			LastOne;
-	BOOLEAN			bAggregatible;
-	UCHAR			Header_802_3[LENGTH_802_3];
-	UCHAR			Rsv[2];
-	ULONG			DataOffset;
-	UINT			TxRate;
-	dma_addr_t		data_dma;		// urb dma on linux
-
-}	TX_CONTEXT, *PTX_CONTEXT, **PPTX_CONTEXT;
-
-
-// used to track driver-generated write irps
-typedef struct _HT_TX_CONTEXT
-{
-	PVOID			pAd;		//Initialized in MiniportInitialize
-	PURB			pUrb;			//Initialized in MiniportInitialize
-	PIRP			pIrp;			//used to cancel pending bulk out.
-									//Initialized in MiniportInitialize
-	PHTTX_BUFFER	TransferBuffer;	//Initialized in MiniportInitialize
-	ULONG			BulkOutSize;	// Indicate the total bulk-out size in bytes in one bulk-transmission
-	UCHAR			BulkOutPipeId;
-	BOOLEAN			IRPPending;
-	BOOLEAN			LastOne;
-	BOOLEAN			bCurWriting;
-	BOOLEAN			bRingEmpty;
-	BOOLEAN			bCopySavePad;
-	UCHAR			SavedPad[8];
-	UCHAR			Header_802_3[LENGTH_802_3];
-	ULONG			CurWritePosition;		// Indicate the buffer offset which packet will be inserted start from.
-	ULONG			CurWriteRealPos;		// Indicate the buffer offset which packet now are writing to.
-	ULONG			NextBulkOutPosition;	// Indicate the buffer start offset of a bulk-transmission
-	ULONG			ENextBulkOutPosition;	// Indicate the buffer end offset of a bulk-transmission
-	UINT			TxRate;
-	dma_addr_t		data_dma;		// urb dma on linux
-}	HT_TX_CONTEXT, *PHT_TX_CONTEXT, **PPHT_TX_CONTEXT;
-
-
-//
-// Structure to keep track of receive packets and buffers to indicate
-// receive data to the protocol.
-//
-typedef struct _RX_CONTEXT
-{
-	PUCHAR				TransferBuffer;
-	PVOID				pAd;
-	PIRP				pIrp;//used to cancel pending bulk in.
-	PURB				pUrb;
-	//These 2 Boolean shouldn't both be 1 at the same time.
-	ULONG				BulkInOffset;	// number of packets waiting for reordering .
-//	BOOLEAN				ReorderInUse;	// At least one packet in this buffer are in reordering buffer and wait for receive indication
-	BOOLEAN				bRxHandling;	// Notify this packet is being process now.
-	BOOLEAN				InUse;			// USB Hardware Occupied. Wait for USB HW to put packet.
-	BOOLEAN				Readable;		// Receive Complete back. OK for driver to indicate receiving packet.
-	BOOLEAN				IRPPending;		// TODO: To be removed
-	atomic_t			IrpLock;
-	NDIS_SPIN_LOCK		RxContextLock;
-	dma_addr_t			data_dma;		// urb dma on linux
-}	RX_CONTEXT, *PRX_CONTEXT;
-#endif // RT2870 //
-
-
-//
-//  NDIS Version definitions
-//
-#ifdef  NDIS50_MINIPORT
-#define RTMP_NDIS_MAJOR_VERSION     5
-#define RTMP_NDIS_MINOR_VERSION     0
-#endif
-
-#ifdef  NDIS51_MINIPORT
-#define RTMP_NDIS_MAJOR_VERSION     5
-#define RTMP_NDIS_MINOR_VERSION     1
-#endif
-
-extern  char    NIC_VENDOR_DESC[];
-extern  int     NIC_VENDOR_DESC_LEN;
-
-extern  unsigned char   SNAP_AIRONET[];
-extern  unsigned char   CipherSuiteCiscoCCKM[];
-extern  unsigned char   CipherSuiteCiscoCCKMLen;
-extern	unsigned char	CipherSuiteCiscoCCKM24[];
-extern	unsigned char	CipherSuiteCiscoCCKM24Len;
-extern  unsigned char   CipherSuiteCCXTkip[];
-extern  unsigned char   CipherSuiteCCXTkipLen;
-extern  unsigned char   CISCO_OUI[];
-extern  UCHAR	BaSizeArray[4];
-
-extern UCHAR BROADCAST_ADDR[MAC_ADDR_LEN];
-extern UCHAR MULTICAST_ADDR[MAC_ADDR_LEN];
-extern UCHAR ZERO_MAC_ADDR[MAC_ADDR_LEN];
-extern ULONG BIT32[32];
-extern UCHAR BIT8[8];
-extern char* CipherName[];
-extern char* MCSToMbps[];
-extern UCHAR	 RxwiMCSToOfdmRate[12];
-extern UCHAR SNAP_802_1H[6];
-extern UCHAR SNAP_BRIDGE_TUNNEL[6];
-extern UCHAR SNAP_AIRONET[8];
-extern UCHAR CKIP_LLC_SNAP[8];
-extern UCHAR EAPOL_LLC_SNAP[8];
-extern UCHAR EAPOL[2];
-extern UCHAR IPX[2];
-extern UCHAR APPLE_TALK[2];
-extern UCHAR RateIdToPlcpSignal[12]; // see IEEE802.11a-1999 p.14
-extern UCHAR	 OfdmRateToRxwiMCS[];
-extern UCHAR OfdmSignalToRateId[16] ;
-extern UCHAR default_cwmin[4];
-extern UCHAR default_cwmax[4];
-extern UCHAR default_sta_aifsn[4];
-extern UCHAR MapUserPriorityToAccessCategory[8];
-
-extern USHORT RateUpPER[];
-extern USHORT RateDownPER[];
-extern UCHAR  Phy11BNextRateDownward[];
-extern UCHAR  Phy11BNextRateUpward[];
-extern UCHAR  Phy11BGNextRateDownward[];
-extern UCHAR  Phy11BGNextRateUpward[];
-extern UCHAR  Phy11ANextRateDownward[];
-extern UCHAR  Phy11ANextRateUpward[];
-extern CHAR   RssiSafeLevelForTxRate[];
-extern UCHAR  RateIdToMbps[];
-extern USHORT RateIdTo500Kbps[];
-
-extern UCHAR  CipherSuiteWpaNoneTkip[];
-extern UCHAR  CipherSuiteWpaNoneTkipLen;
-
-extern UCHAR  CipherSuiteWpaNoneAes[];
-extern UCHAR  CipherSuiteWpaNoneAesLen;
-
-extern UCHAR  SsidIe;
-extern UCHAR  SupRateIe;
-extern UCHAR  ExtRateIe;
-
-#ifdef DOT11_N_SUPPORT
-extern UCHAR  HtCapIe;
-extern UCHAR  AddHtInfoIe;
-extern UCHAR  NewExtChanIe;
-#ifdef DOT11N_DRAFT3
-extern UCHAR  ExtHtCapIe;
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-extern UCHAR  ErpIe;
-extern UCHAR  DsIe;
-extern UCHAR  TimIe;
-extern UCHAR  WpaIe;
-extern UCHAR  Wpa2Ie;
-extern UCHAR  IbssIe;
-extern UCHAR  Ccx2Ie;
-
-extern UCHAR  WPA_OUI[];
-extern UCHAR  RSN_OUI[];
-extern UCHAR  WME_INFO_ELEM[];
-extern UCHAR  WME_PARM_ELEM[];
-extern UCHAR  Ccx2QosInfo[];
-extern UCHAR  Ccx2IeInfo[];
-extern UCHAR  RALINK_OUI[];
-extern UCHAR  PowerConstraintIE[];
-
-
-extern UCHAR  RateSwitchTable[];
-extern UCHAR  RateSwitchTable11B[];
-extern UCHAR  RateSwitchTable11G[];
-extern UCHAR  RateSwitchTable11BG[];
-
-#ifdef DOT11_N_SUPPORT
-extern UCHAR  RateSwitchTable11BGN1S[];
-extern UCHAR  RateSwitchTable11BGN2S[];
-extern UCHAR  RateSwitchTable11BGN2SForABand[];
-extern UCHAR  RateSwitchTable11N1S[];
-extern UCHAR  RateSwitchTable11N2S[];
-extern UCHAR  RateSwitchTable11N2SForABand[];
-
-#ifdef CONFIG_STA_SUPPORT
-extern UCHAR  PRE_N_HT_OUI[];
-#endif // CONFIG_STA_SUPPORT //
-#endif // DOT11_N_SUPPORT //
-
-#define	MAXSEQ		(0xFFF)
-
-#ifdef RALINK_ATE
-typedef	struct _ATE_INFO {
-	UCHAR	Mode;
-	CHAR	TxPower0;
-	CHAR	TxPower1;
-	CHAR    TxAntennaSel;
-	CHAR    RxAntennaSel;
-	TXWI_STRUC  TxWI; 	  // TXWI
-	USHORT	QID;
-	UCHAR	Addr1[MAC_ADDR_LEN];
-	UCHAR	Addr2[MAC_ADDR_LEN];
-	UCHAR	Addr3[MAC_ADDR_LEN];
-	UCHAR	Channel;
-	UINT32	TxLength;
-	UINT32	TxCount;
-	UINT32	TxDoneCount; // Tx DMA Done
-	UINT32	RFFreqOffset;
-	BOOLEAN	bRxFer;
-	BOOLEAN	bQATxStart; // Have compiled QA in and use it to ATE tx.
-	BOOLEAN	bQARxStart;	// Have compiled QA in and use it to ATE rx.
-	UINT32	RxTotalCnt;
-	UINT32	RxCntPerSec;
-
-	CHAR	LastSNR0;             // last received SNR
-	CHAR    LastSNR1;             // last received SNR for 2nd  antenna
-	CHAR    LastRssi0;            // last received RSSI
-	CHAR    LastRssi1;            // last received RSSI for 2nd  antenna
-	CHAR    LastRssi2;            // last received RSSI for 3rd  antenna
-	CHAR    AvgRssi0;             // last 8 frames' average RSSI
-	CHAR    AvgRssi1;             // last 8 frames' average RSSI
-	CHAR    AvgRssi2;             // last 8 frames' average RSSI
-	SHORT   AvgRssi0X8;           // sum of last 8 frames' RSSI
-	SHORT   AvgRssi1X8;           // sum of last 8 frames' RSSI
-	SHORT   AvgRssi2X8;           // sum of last 8 frames' RSSI
-
-	UINT32	NumOfAvgRssiSample;
-
-#ifdef RALINK_28xx_QA
-	// Tx frame
-#ifdef RT2870
-	/* not used in RT2860 */
-	TXINFO_STRUC		TxInfo; // TxInfo
-#endif // RT2870 //
-	USHORT		HLen; // Header Length
-	USHORT		PLen; // Pattern Length
-	UCHAR 		Header[32]; // Header buffer
-	UCHAR		Pattern[32]; // Pattern buffer
-	USHORT		DLen; // Data Length
-	USHORT		seq;
-	UINT32		CID;
-	THREAD_PID 		AtePid;
-	// counters
-	UINT32		U2M;
-	UINT32		OtherData;
-	UINT32		Beacon;
-	UINT32		OtherCount;
-	UINT32		TxAc0;
-	UINT32		TxAc1;
-	UINT32		TxAc2;
-	UINT32		TxAc3;
-	UINT32		TxHCCA;
-	UINT32		TxMgmt;
-	UINT32		RSSI0;
-	UINT32		RSSI1;
-	UINT32		RSSI2;
-	UINT32		SNR0;
-	UINT32		SNR1;
-	// control
-	//UINT32		Repeat; // Tx Cpu count
-	UCHAR		TxStatus; // task Tx status // 0 --> task is idle, 1 --> task is running
-#endif // RALINK_28xx_QA //
-}	ATE_INFO, *PATE_INFO;
-
-#ifdef RALINK_28xx_QA
-struct ate_racfghdr {
- 	UINT32		magic_no;
-	USHORT		command_type;
-	USHORT		command_id;
-	USHORT		length;
-	USHORT		sequence;
-	USHORT		status;
-	UCHAR		data[2046];
-}  __attribute__((packed));
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-#ifdef DOT11_N_SUPPORT
-struct reordering_mpdu
-{
-	struct reordering_mpdu	*next;
-	PNDIS_PACKET			pPacket;		/* coverted to 802.3 frame */
-	int						Sequence;		/* sequence number of MPDU */
-	BOOLEAN					bAMSDU;
-};
-
-struct reordering_list
-{
-	struct reordering_mpdu *next;
-	int 	qlen;
-};
-
-struct reordering_mpdu_pool
-{
-	PVOID					mem;
-	NDIS_SPIN_LOCK			lock;
-	struct reordering_list 	freelist;
-};
-#endif // DOT11_N_SUPPORT //
-
-typedef struct 	_RSSI_SAMPLE {
-	CHAR			LastRssi0;             // last received RSSI
-	CHAR			LastRssi1;             // last received RSSI
-	CHAR			LastRssi2;             // last received RSSI
-	CHAR			AvgRssi0;
-	CHAR			AvgRssi1;
-	CHAR			AvgRssi2;
-	SHORT			AvgRssi0X8;
-	SHORT			AvgRssi1X8;
-	SHORT			AvgRssi2X8;
-} RSSI_SAMPLE;
-
-//
-//  Queue structure and macros
-//
-typedef struct  _QUEUE_ENTRY    {
-	struct _QUEUE_ENTRY     *Next;
-}   QUEUE_ENTRY, *PQUEUE_ENTRY;
-
-// Queue structure
-typedef struct  _QUEUE_HEADER   {
-	PQUEUE_ENTRY    Head;
-	PQUEUE_ENTRY    Tail;
-	ULONG           Number;
-}   QUEUE_HEADER, *PQUEUE_HEADER;
-
-#define InitializeQueueHeader(QueueHeader)              \
-{                                                       \
-	(QueueHeader)->Head = (QueueHeader)->Tail = NULL;   \
-	(QueueHeader)->Number = 0;                          \
-}
-
-#define RemoveHeadQueue(QueueHeader)                \
-(QueueHeader)->Head;                                \
-{                                                   \
-	PQUEUE_ENTRY pNext;                             \
-	if ((QueueHeader)->Head != NULL)				\
-	{												\
-		pNext = (QueueHeader)->Head->Next;          \
-		(QueueHeader)->Head = pNext;                \
-		if (pNext == NULL)                          \
-			(QueueHeader)->Tail = NULL;             \
-		(QueueHeader)->Number--;                    \
-	}												\
-}
-
-#define InsertHeadQueue(QueueHeader, QueueEntry)            \
-{                                                           \
-		((PQUEUE_ENTRY)QueueEntry)->Next = (QueueHeader)->Head; \
-		(QueueHeader)->Head = (PQUEUE_ENTRY)(QueueEntry);       \
-		if ((QueueHeader)->Tail == NULL)                        \
-			(QueueHeader)->Tail = (PQUEUE_ENTRY)(QueueEntry);   \
-		(QueueHeader)->Number++;                                \
-}
-
-#define InsertTailQueue(QueueHeader, QueueEntry)                \
-{                                                               \
-	((PQUEUE_ENTRY)QueueEntry)->Next = NULL;                    \
-	if ((QueueHeader)->Tail)                                    \
-		(QueueHeader)->Tail->Next = (PQUEUE_ENTRY)(QueueEntry); \
-	else                                                        \
-		(QueueHeader)->Head = (PQUEUE_ENTRY)(QueueEntry);       \
-	(QueueHeader)->Tail = (PQUEUE_ENTRY)(QueueEntry);           \
-	(QueueHeader)->Number++;                                    \
-}
-
-//
-//  Macros for flag and ref count operations
-//
-#define RTMP_SET_FLAG(_M, _F)       ((_M)->Flags |= (_F))
-#define RTMP_CLEAR_FLAG(_M, _F)     ((_M)->Flags &= ~(_F))
-#define RTMP_CLEAR_FLAGS(_M)        ((_M)->Flags = 0)
-#define RTMP_TEST_FLAG(_M, _F)      (((_M)->Flags & (_F)) != 0)
-#define RTMP_TEST_FLAGS(_M, _F)     (((_M)->Flags & (_F)) == (_F))
-
-#define OPSTATUS_SET_FLAG(_pAd, _F)     ((_pAd)->CommonCfg.OpStatusFlags |= (_F))
-#define OPSTATUS_CLEAR_FLAG(_pAd, _F)   ((_pAd)->CommonCfg.OpStatusFlags &= ~(_F))
-#define OPSTATUS_TEST_FLAG(_pAd, _F)    (((_pAd)->CommonCfg.OpStatusFlags & (_F)) != 0)
-
-#define CLIENT_STATUS_SET_FLAG(_pEntry,_F)      ((_pEntry)->ClientStatusFlags |= (_F))
-#define CLIENT_STATUS_CLEAR_FLAG(_pEntry,_F)    ((_pEntry)->ClientStatusFlags &= ~(_F))
-#define CLIENT_STATUS_TEST_FLAG(_pEntry,_F)     (((_pEntry)->ClientStatusFlags & (_F)) != 0)
-
-#define RX_FILTER_SET_FLAG(_pAd, _F)    ((_pAd)->CommonCfg.PacketFilter |= (_F))
-#define RX_FILTER_CLEAR_FLAG(_pAd, _F)  ((_pAd)->CommonCfg.PacketFilter &= ~(_F))
-#define RX_FILTER_TEST_FLAG(_pAd, _F)   (((_pAd)->CommonCfg.PacketFilter & (_F)) != 0)
-
-#ifdef CONFIG_STA_SUPPORT
-#define STA_NO_SECURITY_ON(_p)          (_p->StaCfg.WepStatus == Ndis802_11EncryptionDisabled)
-#define STA_WEP_ON(_p)                  (_p->StaCfg.WepStatus == Ndis802_11Encryption1Enabled)
-#define STA_TKIP_ON(_p)                 (_p->StaCfg.WepStatus == Ndis802_11Encryption2Enabled)
-#define STA_AES_ON(_p)                  (_p->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-
-#define STA_TGN_WIFI_ON(_p)             (_p->StaCfg.bTGnWifiTest == TRUE)
-#endif // CONFIG_STA_SUPPORT //
-
-#define CKIP_KP_ON(_p)				((((_p)->StaCfg.CkipFlag) & 0x10) && ((_p)->StaCfg.bCkipCmicOn == TRUE))
-#define CKIP_CMIC_ON(_p)			((((_p)->StaCfg.CkipFlag) & 0x08) && ((_p)->StaCfg.bCkipCmicOn == TRUE))
-
-
-#define INC_RING_INDEX(_idx, _RingSize)    \
-{                                          \
-    (_idx) = (_idx+1) % (_RingSize);       \
-}
-
-#define IS_RT3070(_pAd)				(((_pAd)->MACVersion & 0xffff0000) == 0x30700000)
-
-#define RING_PACKET_INIT(_TxRing, _idx)    \
-{                                          \
-    _TxRing->Cell[_idx].pNdisPacket = NULL;                              \
-    _TxRing->Cell[_idx].pNextNdisPacket = NULL;                              \
-}
-
-#define TXDT_INIT(_TxD)    \
-{                                          \
-	NdisZeroMemory(_TxD, TXD_SIZE);	\
-	_TxD->DMADONE = 1;                              \
-}
-
-//Set last data segment
-#define RING_SET_LASTDS(_TxD, _IsSD0)    \
-{                                          \
-    if (_IsSD0) {_TxD->LastSec0 = 1;}     \
-    else {_TxD->LastSec1 = 1;}     \
-}
-
-// Increase TxTsc value for next transmission
-// TODO:
-// When i==6, means TSC has done one full cycle, do re-keying stuff follow specs
-// Should send a special event microsoft defined to request re-key
-#define INC_TX_TSC(_tsc)                                \
-{                                                       \
-    int i=0;                                            \
-    while (++_tsc[i] == 0x0)                            \
-    {                                                   \
-        i++;                                            \
-        if (i == 6)                                     \
-            break;                                      \
-    }                                                   \
-}
-
-#ifdef DOT11_N_SUPPORT
-// StaActive.SupportedHtPhy.MCSSet is copied from AP beacon.  Don't need to update here.
-#define COPY_HTSETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(_pAd)                                 \
-{                                                                                       \
-	_pAd->StaActive.SupportedHtPhy.ChannelWidth = _pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth;      \
-	_pAd->StaActive.SupportedHtPhy.MimoPs = _pAd->MlmeAux.HtCapability.HtCapInfo.MimoPs;      \
-	_pAd->StaActive.SupportedHtPhy.GF = _pAd->MlmeAux.HtCapability.HtCapInfo.GF;      \
-	_pAd->StaActive.SupportedHtPhy.ShortGIfor20 = _pAd->MlmeAux.HtCapability.HtCapInfo.ShortGIfor20;      \
-	_pAd->StaActive.SupportedHtPhy.ShortGIfor40 = _pAd->MlmeAux.HtCapability.HtCapInfo.ShortGIfor40;      \
-	_pAd->StaActive.SupportedHtPhy.TxSTBC = _pAd->MlmeAux.HtCapability.HtCapInfo.TxSTBC;      \
-	_pAd->StaActive.SupportedHtPhy.RxSTBC = _pAd->MlmeAux.HtCapability.HtCapInfo.RxSTBC;      \
-	_pAd->StaActive.SupportedHtPhy.ExtChanOffset = _pAd->MlmeAux.AddHtInfo.AddHtInfo.ExtChanOffset;      \
-	_pAd->StaActive.SupportedHtPhy.RecomWidth = _pAd->MlmeAux.AddHtInfo.AddHtInfo.RecomWidth;      \
-	_pAd->StaActive.SupportedHtPhy.OperaionMode = _pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode;      \
-	_pAd->StaActive.SupportedHtPhy.NonGfPresent = _pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent;      \
-	NdisMoveMemory((_pAd)->MacTab.Content[BSSID_WCID].HTCapability.MCSSet, (_pAd)->StaActive.SupportedPhyInfo.MCSSet, sizeof(UCHAR) * 16);\
-}
-
-#define COPY_AP_HTSETTINGS_FROM_BEACON(_pAd, _pHtCapability)                                 \
-{                                                                                       \
-	_pAd->MacTab.Content[BSSID_WCID].AMsduSize = (UCHAR)(_pHtCapability->HtCapInfo.AMsduSize);	\
-	_pAd->MacTab.Content[BSSID_WCID].MmpsMode= (UCHAR)(_pHtCapability->HtCapInfo.MimoPs);	\
-	_pAd->MacTab.Content[BSSID_WCID].MaxRAmpduFactor = (UCHAR)(_pHtCapability->HtCapParm.MaxRAmpduFactor);	\
-}
-#endif // DOT11_N_SUPPORT //
-
-//
-// BBP & RF are using indirect access. Before write any value into it.
-// We have to make sure there is no outstanding command pending via checking busy bit.
-//
-#define MAX_BUSY_COUNT  100         // Number of retry before failing access BBP & RF indirect register
-//
-
-#ifdef RT2870
-#define RTMP_RF_IO_WRITE32(_A, _V)                 RTUSBWriteRFRegister(_A, _V)
-#define RTMP_BBP_IO_READ8_BY_REG_ID(_A, _I, _pV)   RTUSBReadBBPRegister(_A, _I, _pV)
-#define RTMP_BBP_IO_WRITE8_BY_REG_ID(_A, _I, _V)   RTUSBWriteBBPRegister(_A, _I, _V)
-
-#define BBP_IO_WRITE8_BY_REG_ID(_A, _I, _V)			RTUSBWriteBBPRegister(_A, _I, _V)
-#define BBP_IO_READ8_BY_REG_ID(_A, _I, _pV)   		RTUSBReadBBPRegister(_A, _I, _pV)
-#endif // RT2870 //
-
-#define     MAP_CHANNEL_ID_TO_KHZ(ch, khz)  {               \
-                switch (ch)                                 \
-                {                                           \
-                    case 1:     khz = 2412000;   break;     \
-                    case 2:     khz = 2417000;   break;     \
-                    case 3:     khz = 2422000;   break;     \
-                    case 4:     khz = 2427000;   break;     \
-                    case 5:     khz = 2432000;   break;     \
-                    case 6:     khz = 2437000;   break;     \
-                    case 7:     khz = 2442000;   break;     \
-                    case 8:     khz = 2447000;   break;     \
-                    case 9:     khz = 2452000;   break;     \
-                    case 10:    khz = 2457000;   break;     \
-                    case 11:    khz = 2462000;   break;     \
-                    case 12:    khz = 2467000;   break;     \
-                    case 13:    khz = 2472000;   break;     \
-                    case 14:    khz = 2484000;   break;     \
-                    case 36:  /* UNII */  khz = 5180000;   break;     \
-                    case 40:  /* UNII */  khz = 5200000;   break;     \
-                    case 44:  /* UNII */  khz = 5220000;   break;     \
-                    case 48:  /* UNII */  khz = 5240000;   break;     \
-                    case 52:  /* UNII */  khz = 5260000;   break;     \
-                    case 56:  /* UNII */  khz = 5280000;   break;     \
-                    case 60:  /* UNII */  khz = 5300000;   break;     \
-                    case 64:  /* UNII */  khz = 5320000;   break;     \
-                    case 149: /* UNII */  khz = 5745000;   break;     \
-                    case 153: /* UNII */  khz = 5765000;   break;     \
-                    case 157: /* UNII */  khz = 5785000;   break;     \
-                    case 161: /* UNII */  khz = 5805000;   break;     \
-                    case 165: /* UNII */  khz = 5825000;   break;     \
-                    case 100: /* HiperLAN2 */  khz = 5500000;   break;     \
-                    case 104: /* HiperLAN2 */  khz = 5520000;   break;     \
-                    case 108: /* HiperLAN2 */  khz = 5540000;   break;     \
-                    case 112: /* HiperLAN2 */  khz = 5560000;   break;     \
-                    case 116: /* HiperLAN2 */  khz = 5580000;   break;     \
-                    case 120: /* HiperLAN2 */  khz = 5600000;   break;     \
-                    case 124: /* HiperLAN2 */  khz = 5620000;   break;     \
-                    case 128: /* HiperLAN2 */  khz = 5640000;   break;     \
-                    case 132: /* HiperLAN2 */  khz = 5660000;   break;     \
-                    case 136: /* HiperLAN2 */  khz = 5680000;   break;     \
-                    case 140: /* HiperLAN2 */  khz = 5700000;   break;     \
-                    case 34:  /* Japan MMAC */   khz = 5170000;   break;   \
-                    case 38:  /* Japan MMAC */   khz = 5190000;   break;   \
-                    case 42:  /* Japan MMAC */   khz = 5210000;   break;   \
-                    case 46:  /* Japan MMAC */   khz = 5230000;   break;   \
-                    case 184: /* Japan */   khz = 4920000;   break;   \
-                    case 188: /* Japan */   khz = 4940000;   break;   \
-                    case 192: /* Japan */   khz = 4960000;   break;   \
-                    case 196: /* Japan */   khz = 4980000;   break;   \
-                    case 208: /* Japan, means J08 */   khz = 5040000;   break;   \
-                    case 212: /* Japan, means J12 */   khz = 5060000;   break;   \
-                    case 216: /* Japan, means J16 */   khz = 5080000;   break;   \
-                    default:    khz = 2412000;   break;     \
-                }                                           \
-            }
-
-#define     MAP_KHZ_TO_CHANNEL_ID(khz, ch)  {               \
-                switch (khz)                                \
-                {                                           \
-                    case 2412000:    ch = 1;     break;     \
-                    case 2417000:    ch = 2;     break;     \
-                    case 2422000:    ch = 3;     break;     \
-                    case 2427000:    ch = 4;     break;     \
-                    case 2432000:    ch = 5;     break;     \
-                    case 2437000:    ch = 6;     break;     \
-                    case 2442000:    ch = 7;     break;     \
-                    case 2447000:    ch = 8;     break;     \
-                    case 2452000:    ch = 9;     break;     \
-                    case 2457000:    ch = 10;    break;     \
-                    case 2462000:    ch = 11;    break;     \
-                    case 2467000:    ch = 12;    break;     \
-                    case 2472000:    ch = 13;    break;     \
-                    case 2484000:    ch = 14;    break;     \
-                    case 5180000:    ch = 36;  /* UNII */  break;     \
-                    case 5200000:    ch = 40;  /* UNII */  break;     \
-                    case 5220000:    ch = 44;  /* UNII */  break;     \
-                    case 5240000:    ch = 48;  /* UNII */  break;     \
-                    case 5260000:    ch = 52;  /* UNII */  break;     \
-                    case 5280000:    ch = 56;  /* UNII */  break;     \
-                    case 5300000:    ch = 60;  /* UNII */  break;     \
-                    case 5320000:    ch = 64;  /* UNII */  break;     \
-                    case 5745000:    ch = 149; /* UNII */  break;     \
-                    case 5765000:    ch = 153; /* UNII */  break;     \
-                    case 5785000:    ch = 157; /* UNII */  break;     \
-                    case 5805000:    ch = 161; /* UNII */  break;     \
-                    case 5825000:    ch = 165; /* UNII */  break;     \
-                    case 5500000:    ch = 100; /* HiperLAN2 */  break;     \
-                    case 5520000:    ch = 104; /* HiperLAN2 */  break;     \
-                    case 5540000:    ch = 108; /* HiperLAN2 */  break;     \
-                    case 5560000:    ch = 112; /* HiperLAN2 */  break;     \
-                    case 5580000:    ch = 116; /* HiperLAN2 */  break;     \
-                    case 5600000:    ch = 120; /* HiperLAN2 */  break;     \
-                    case 5620000:    ch = 124; /* HiperLAN2 */  break;     \
-                    case 5640000:    ch = 128; /* HiperLAN2 */  break;     \
-                    case 5660000:    ch = 132; /* HiperLAN2 */  break;     \
-                    case 5680000:    ch = 136; /* HiperLAN2 */  break;     \
-                    case 5700000:    ch = 140; /* HiperLAN2 */  break;     \
-                    case 5170000:    ch = 34;  /* Japan MMAC */   break;   \
-                    case 5190000:    ch = 38;  /* Japan MMAC */   break;   \
-                    case 5210000:    ch = 42;  /* Japan MMAC */   break;   \
-                    case 5230000:    ch = 46;  /* Japan MMAC */   break;   \
-                    case 4920000:    ch = 184; /* Japan */  break;   \
-                    case 4940000:    ch = 188; /* Japan */  break;   \
-                    case 4960000:    ch = 192; /* Japan */  break;   \
-                    case 4980000:    ch = 196; /* Japan */  break;   \
-                    case 5040000:    ch = 208; /* Japan, means J08 */  break;   \
-                    case 5060000:    ch = 212; /* Japan, means J12 */  break;   \
-                    case 5080000:    ch = 216; /* Japan, means J16 */  break;   \
-                    default:         ch = 1;     break;     \
-                }                                           \
-            }
-
-//
-// Common fragment list structure -  Identical to the scatter gather frag list structure
-//
-//#define RTMP_SCATTER_GATHER_ELEMENT         SCATTER_GATHER_ELEMENT
-//#define PRTMP_SCATTER_GATHER_ELEMENT        PSCATTER_GATHER_ELEMENT
-#define NIC_MAX_PHYS_BUF_COUNT              8
-
-typedef struct _RTMP_SCATTER_GATHER_ELEMENT {
-    PVOID		Address;
-    ULONG		Length;
-    PULONG		Reserved;
-} RTMP_SCATTER_GATHER_ELEMENT, *PRTMP_SCATTER_GATHER_ELEMENT;
-
-
-typedef struct _RTMP_SCATTER_GATHER_LIST {
-    ULONG  NumberOfElements;
-    PULONG Reserved;
-    RTMP_SCATTER_GATHER_ELEMENT Elements[NIC_MAX_PHYS_BUF_COUNT];
-} RTMP_SCATTER_GATHER_LIST, *PRTMP_SCATTER_GATHER_LIST;
-
-//
-//  Some utility macros
-//
-#ifndef min
-#define min(_a, _b)     (((_a) < (_b)) ? (_a) : (_b))
-#endif
-
-#ifndef max
-#define max(_a, _b)     (((_a) > (_b)) ? (_a) : (_b))
-#endif
-
-#define GET_LNA_GAIN(_pAd)	((_pAd->LatchRfRegs.Channel <= 14) ? (_pAd->BLNAGain) : ((_pAd->LatchRfRegs.Channel <= 64) ? (_pAd->ALNAGain0) : ((_pAd->LatchRfRegs.Channel <= 128) ? (_pAd->ALNAGain1) : (_pAd->ALNAGain2))))
-
-#define INC_COUNTER64(Val)          (Val.QuadPart++)
-
-#define INFRA_ON(_p)                (OPSTATUS_TEST_FLAG(_p, fOP_STATUS_INFRA_ON))
-#define ADHOC_ON(_p)                (OPSTATUS_TEST_FLAG(_p, fOP_STATUS_ADHOC_ON))
-#define MONITOR_ON(_p)              (((_p)->StaCfg.BssType) == BSS_MONITOR)
-#define IDLE_ON(_p)                 (!INFRA_ON(_p) && !ADHOC_ON(_p))
-
-// Check LEAP & CCKM flags
-#define LEAP_ON(_p)                 (((_p)->StaCfg.LeapAuthMode) == CISCO_AuthModeLEAP)
-#define LEAP_CCKM_ON(_p)            ((((_p)->StaCfg.LeapAuthMode) == CISCO_AuthModeLEAP) && ((_p)->StaCfg.LeapAuthInfo.CCKM == TRUE))
-
-// if orginal Ethernet frame contains no LLC/SNAP, then an extra LLC/SNAP encap is required
-#define EXTRA_LLCSNAP_ENCAP_FROM_PKT_START(_pBufVA, _pExtraLlcSnapEncap)		\
-{																\
-	if (((*(_pBufVA + 12) << 8) + *(_pBufVA + 13)) > 1500)		\
-	{															\
-		_pExtraLlcSnapEncap = SNAP_802_1H;						\
-		if (NdisEqualMemory(IPX, _pBufVA + 12, 2) || 			\
-			NdisEqualMemory(APPLE_TALK, _pBufVA + 12, 2))		\
-		{														\
-			_pExtraLlcSnapEncap = SNAP_BRIDGE_TUNNEL;			\
-		}														\
-	}															\
-	else														\
-	{															\
-		_pExtraLlcSnapEncap = NULL;								\
-	}															\
-}
-
-// New Define for new Tx Path.
-#define EXTRA_LLCSNAP_ENCAP_FROM_PKT_OFFSET(_pBufVA, _pExtraLlcSnapEncap)	\
-{																\
-	if (((*(_pBufVA) << 8) + *(_pBufVA + 1)) > 1500)			\
-	{															\
-		_pExtraLlcSnapEncap = SNAP_802_1H;						\
-		if (NdisEqualMemory(IPX, _pBufVA, 2) || 				\
-			NdisEqualMemory(APPLE_TALK, _pBufVA, 2))			\
-		{														\
-			_pExtraLlcSnapEncap = SNAP_BRIDGE_TUNNEL;			\
-		}														\
-	}															\
-	else														\
-	{															\
-		_pExtraLlcSnapEncap = NULL;								\
-	}															\
-}
-
-
-#define MAKE_802_3_HEADER(_p, _pMac1, _pMac2, _pType)                   \
-{                                                                       \
-    NdisMoveMemory(_p, _pMac1, MAC_ADDR_LEN);                           \
-    NdisMoveMemory((_p + MAC_ADDR_LEN), _pMac2, MAC_ADDR_LEN);          \
-    NdisMoveMemory((_p + MAC_ADDR_LEN * 2), _pType, LENGTH_802_3_TYPE); \
-}
-
-// if pData has no LLC/SNAP (neither RFC1042 nor Bridge tunnel), keep it that way.
-// else if the received frame is LLC/SNAP-encaped IPX or APPLETALK, preserve the LLC/SNAP field
-// else remove the LLC/SNAP field from the result Ethernet frame
-// Patch for WHQL only, which did not turn on Netbios but use IPX within its payload
-// Note:
-//     _pData & _DataSize may be altered (remove 8-byte LLC/SNAP) by this MACRO
-//     _pRemovedLLCSNAP: pointer to removed LLC/SNAP; NULL is not removed
-#define CONVERT_TO_802_3(_p8023hdr, _pDA, _pSA, _pData, _DataSize, _pRemovedLLCSNAP)      \
-{                                                                       \
-    char LLC_Len[2];                                                    \
-                                                                        \
-    _pRemovedLLCSNAP = NULL;                                            \
-    if (NdisEqualMemory(SNAP_802_1H, _pData, 6)  ||                     \
-        NdisEqualMemory(SNAP_BRIDGE_TUNNEL, _pData, 6))                 \
-    {                                                                   \
-        PUCHAR pProto = _pData + 6;                                     \
-                                                                        \
-        if ((NdisEqualMemory(IPX, pProto, 2) || NdisEqualMemory(APPLE_TALK, pProto, 2)) &&  \
-            NdisEqualMemory(SNAP_802_1H, _pData, 6))                    \
-        {                                                               \
-            LLC_Len[0] = (UCHAR)(_DataSize / 256);                      \
-            LLC_Len[1] = (UCHAR)(_DataSize % 256);                      \
-            MAKE_802_3_HEADER(_p8023hdr, _pDA, _pSA, LLC_Len);          \
-        }                                                               \
-        else                                                            \
-        {                                                               \
-            MAKE_802_3_HEADER(_p8023hdr, _pDA, _pSA, pProto);           \
-            _pRemovedLLCSNAP = _pData;                                  \
-            _DataSize -= LENGTH_802_1_H;                                \
-            _pData += LENGTH_802_1_H;                                   \
-        }                                                               \
-    }                                                                   \
-    else                                                                \
-    {                                                                   \
-        LLC_Len[0] = (UCHAR)(_DataSize / 256);                          \
-        LLC_Len[1] = (UCHAR)(_DataSize % 256);                          \
-        MAKE_802_3_HEADER(_p8023hdr, _pDA, _pSA, LLC_Len);              \
-    }                                                                   \
-}
-
-#define SWITCH_AB( _pAA, _pBB)    \
-{                                                                           \
-    PVOID pCC;                                                          \
-    pCC = _pBB;                                                 \
-    _pBB = _pAA;                                                 \
-    _pAA = pCC;                                                 \
-}
-
-// Enqueue this frame to MLME engine
-// We need to enqueue the whole frame because MLME need to pass data type
-// information from 802.11 header
-#ifdef RT2870
-#define REPORT_MGMT_FRAME_TO_MLME(_pAd, Wcid, _pFrame, _FrameSize, _Rssi0, _Rssi1, _Rssi2, _PlcpSignal)        \
-{                                                                                       \
-    UINT32 High32TSF=0, Low32TSF=0;                                                          \
-    MlmeEnqueueForRecv(_pAd, Wcid, High32TSF, Low32TSF, (UCHAR)_Rssi0, (UCHAR)_Rssi1,(UCHAR)_Rssi2,_FrameSize, _pFrame, (UCHAR)_PlcpSignal);   \
-}
-#endif // RT2870 //
-
-#define NDIS_QUERY_BUFFER(_NdisBuf, _ppVA, _pBufLen)                    \
-    NdisQueryBuffer(_NdisBuf, _ppVA, _pBufLen)
-
-#define MAC_ADDR_EQUAL(pAddr1,pAddr2)           RTMPEqualMemory((PVOID)(pAddr1), (PVOID)(pAddr2), MAC_ADDR_LEN)
-#define SSID_EQUAL(ssid1, len1, ssid2, len2)    ((len1==len2) && (RTMPEqualMemory(ssid1, ssid2, len1)))
-
-//
-// Check if it is Japan W53(ch52,56,60,64) channel.
-//
-#define JapanChannelCheck(channel)  ((channel == 52) || (channel == 56) || (channel == 60) || (channel == 64))
-
-#ifdef CONFIG_STA_SUPPORT
-#define STA_PORT_SECURED(_pAd) \
-{ \
-	_pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED; \
-	NdisAcquireSpinLock(&_pAd->MacTabLock); \
-	_pAd->MacTab.Content[BSSID_WCID].PortSecured = _pAd->StaCfg.PortSecured; \
-	NdisReleaseSpinLock(&_pAd->MacTabLock); \
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-//
-// Register set pair for initialzation register set definition
-//
-typedef struct  _RTMP_REG_PAIR
-{
-	ULONG   Register;
-	ULONG   Value;
-} RTMP_REG_PAIR, *PRTMP_REG_PAIR;
-
-typedef struct  _REG_PAIR
-{
-	UCHAR   Register;
-	UCHAR   Value;
-} REG_PAIR, *PREG_PAIR;
-
-//
-// Register set pair for initialzation register set definition
-//
-typedef struct  _RTMP_RF_REGS
-{
-	UCHAR   Channel;
-	ULONG   R1;
-	ULONG   R2;
-	ULONG   R3;
-	ULONG   R4;
-} RTMP_RF_REGS, *PRTMP_RF_REGS;
-
-typedef struct _FREQUENCY_ITEM {
-	UCHAR	Channel;
-	UCHAR	N;
-	UCHAR	R;
-	UCHAR	K;
-} FREQUENCY_ITEM, *PFREQUENCY_ITEM;
-
-//
-//  Data buffer for DMA operation, the buffer must be contiguous physical memory
-//  Both DMA to / from CPU use the same structure.
-//
-typedef struct  _RTMP_DMABUF
-{
-	ULONG                   AllocSize;
-	PVOID                   AllocVa;            // TxBuf virtual address
-	NDIS_PHYSICAL_ADDRESS   AllocPa;            // TxBuf physical address
-} RTMP_DMABUF, *PRTMP_DMABUF;
-
-
-typedef	union	_HEADER_802_11_SEQ{
-#ifdef RT_BIG_ENDIAN
-    struct {
-   	USHORT			Sequence:12;
-	USHORT			Frag:4;
-    }   field;
-#else
-    struct {
-	USHORT			Frag:4;
-	USHORT			Sequence:12;
-    }   field;
-#endif
-    USHORT           value;
-}	HEADER_802_11_SEQ, *PHEADER_802_11_SEQ;
-
-//
-//  Data buffer for DMA operation, the buffer must be contiguous physical memory
-//  Both DMA to / from CPU use the same structure.
-//
-typedef struct  _RTMP_REORDERBUF
-{
-	BOOLEAN			IsFull;
-	PVOID                   AllocVa;            // TxBuf virtual address
-	UCHAR			Header802_3[14];
-	HEADER_802_11_SEQ			Sequence;	//support compressed bitmap BA, so no consider fragment in BA
-	UCHAR 		DataOffset;
-	USHORT 		Datasize;
-	ULONG                   AllocSize;
-#ifdef RT2870
-	PUCHAR					AllocPa;
-#endif // RT2870 //
-}   RTMP_REORDERBUF, *PRTMP_REORDERBUF;
-
-//
-// Control block (Descriptor) for all ring descriptor DMA operation, buffer must be
-// contiguous physical memory. NDIS_PACKET stored the binding Rx packet descriptor
-// which won't be released, driver has to wait until upper layer return the packet
-// before giveing up this rx ring descriptor to ASIC. NDIS_BUFFER is assocaited pair
-// to describe the packet buffer. For Tx, NDIS_PACKET stored the tx packet descriptor
-// which driver should ACK upper layer when the tx is physically done or failed.
-//
-typedef struct _RTMP_DMACB
-{
-	ULONG                   AllocSize;          // Control block size
-	PVOID                   AllocVa;            // Control block virtual address
-	NDIS_PHYSICAL_ADDRESS   AllocPa;            // Control block physical address
-	PNDIS_PACKET pNdisPacket;
-	PNDIS_PACKET pNextNdisPacket;
-
-	RTMP_DMABUF             DmaBuf;             // Associated DMA buffer structure
-} RTMP_DMACB, *PRTMP_DMACB;
-
-typedef struct _RTMP_TX_BUF
-{
-	PQUEUE_ENTRY    Next;
-	UCHAR           Index;
-	ULONG                   AllocSize;          // Control block size
-	PVOID                   AllocVa;            // Control block virtual address
-	NDIS_PHYSICAL_ADDRESS   AllocPa;            // Control block physical address
-} RTMP_TXBUF, *PRTMP_TXBUF;
-
-typedef struct _RTMP_RX_BUF
-{
-	BOOLEAN           InUse;
-	ULONG           	ByBaRecIndex;
-	RTMP_REORDERBUF	MAP_RXBuf[MAX_RX_REORDERBUF];
-} RTMP_RXBUF, *PRTMP_RXBUF;
-typedef struct _RTMP_TX_RING
-{
-	RTMP_DMACB  Cell[TX_RING_SIZE];
-	UINT32		TxCpuIdx;
-	UINT32		TxDmaIdx;
-	UINT32		TxSwFreeIdx; 	// software next free tx index
-} RTMP_TX_RING, *PRTMP_TX_RING;
-
-typedef struct _RTMP_RX_RING
-{
-	RTMP_DMACB  Cell[RX_RING_SIZE];
-	UINT32		RxCpuIdx;
-	UINT32		RxDmaIdx;
-	INT32		RxSwReadIdx; 	// software next read index
-} RTMP_RX_RING, *PRTMP_RX_RING;
-
-typedef struct _RTMP_MGMT_RING
-{
-	RTMP_DMACB  Cell[MGMT_RING_SIZE];
-	UINT32		TxCpuIdx;
-	UINT32		TxDmaIdx;
-	UINT32		TxSwFreeIdx; // software next free tx index
-} RTMP_MGMT_RING, *PRTMP_MGMT_RING;
-
-//
-//  Statistic counter structure
-//
-typedef struct _COUNTER_802_3
-{
-	// General Stats
-	ULONG       GoodTransmits;
-	ULONG       GoodReceives;
-	ULONG       TxErrors;
-	ULONG       RxErrors;
-	ULONG       RxNoBuffer;
-
-	// Ethernet Stats
-	ULONG       RcvAlignmentErrors;
-	ULONG       OneCollision;
-	ULONG       MoreCollisions;
-
-} COUNTER_802_3, *PCOUNTER_802_3;
-
-typedef struct _COUNTER_802_11 {
-	ULONG           Length;
-	LARGE_INTEGER   LastTransmittedFragmentCount;
-	LARGE_INTEGER   TransmittedFragmentCount;
-	LARGE_INTEGER   MulticastTransmittedFrameCount;
-	LARGE_INTEGER   FailedCount;
-	LARGE_INTEGER   RetryCount;
-	LARGE_INTEGER   MultipleRetryCount;
-	LARGE_INTEGER   RTSSuccessCount;
-	LARGE_INTEGER   RTSFailureCount;
-	LARGE_INTEGER   ACKFailureCount;
-	LARGE_INTEGER   FrameDuplicateCount;
-	LARGE_INTEGER   ReceivedFragmentCount;
-	LARGE_INTEGER   MulticastReceivedFrameCount;
-	LARGE_INTEGER   FCSErrorCount;
-} COUNTER_802_11, *PCOUNTER_802_11;
-
-typedef struct _COUNTER_RALINK {
-	ULONG           TransmittedByteCount;   // both successful and failure, used to calculate TX throughput
-	ULONG           ReceivedByteCount;      // both CRC okay and CRC error, used to calculate RX throughput
-	ULONG           BeenDisassociatedCount;
-	ULONG           BadCQIAutoRecoveryCount;
-	ULONG           PoorCQIRoamingCount;
-	ULONG           MgmtRingFullCount;
-	ULONG           RxCountSinceLastNULL;
-	ULONG           RxCount;
-	ULONG           RxRingErrCount;
-	ULONG           KickTxCount;
-	ULONG           TxRingErrCount;
-	LARGE_INTEGER   RealFcsErrCount;
-	ULONG           PendingNdisPacketCount;
-
-	ULONG           OneSecOsTxCount[NUM_OF_TX_RING];
-	ULONG           OneSecDmaDoneCount[NUM_OF_TX_RING];
-	UINT32          OneSecTxDoneCount;
-	ULONG           OneSecRxCount;
-	UINT32          OneSecTxAggregationCount;
-	UINT32          OneSecRxAggregationCount;
-
-	UINT32   		OneSecFrameDuplicateCount;
-
-#ifdef RT2870
-	ULONG           OneSecTransmittedByteCount;   // both successful and failure, used to calculate TX throughput
-#endif // RT2870 //
-
-	UINT32          OneSecTxNoRetryOkCount;
-	UINT32          OneSecTxRetryOkCount;
-	UINT32          OneSecTxFailCount;
-	UINT32          OneSecFalseCCACnt;      // CCA error count, for debug purpose, might move to global counter
-	UINT32          OneSecRxOkCnt;          // RX without error
-	UINT32          OneSecRxOkDataCnt;      // unicast-to-me DATA frame count
-	UINT32          OneSecRxFcsErrCnt;      // CRC error
-	UINT32          OneSecBeaconSentCnt;
-	UINT32          LastOneSecTotalTxCount; // OneSecTxNoRetryOkCount + OneSecTxRetryOkCount + OneSecTxFailCount
-	UINT32          LastOneSecRxOkDataCnt;  // OneSecRxOkDataCnt
-	ULONG		DuplicateRcv;
-	ULONG		TxAggCount;
-	ULONG		TxNonAggCount;
-	ULONG		TxAgg1MPDUCount;
-	ULONG		TxAgg2MPDUCount;
-	ULONG		TxAgg3MPDUCount;
-	ULONG		TxAgg4MPDUCount;
-	ULONG		TxAgg5MPDUCount;
-	ULONG		TxAgg6MPDUCount;
-	ULONG		TxAgg7MPDUCount;
-	ULONG		TxAgg8MPDUCount;
-	ULONG		TxAgg9MPDUCount;
-	ULONG		TxAgg10MPDUCount;
-	ULONG		TxAgg11MPDUCount;
-	ULONG		TxAgg12MPDUCount;
-	ULONG		TxAgg13MPDUCount;
-	ULONG		TxAgg14MPDUCount;
-	ULONG		TxAgg15MPDUCount;
-	ULONG		TxAgg16MPDUCount;
-
-	LARGE_INTEGER       TransmittedOctetsInAMSDU;
-	LARGE_INTEGER       TransmittedAMSDUCount;
-	LARGE_INTEGER       ReceivedOctesInAMSDUCount;
-	LARGE_INTEGER       ReceivedAMSDUCount;
-	LARGE_INTEGER       TransmittedAMPDUCount;
-	LARGE_INTEGER       TransmittedMPDUsInAMPDUCount;
-	LARGE_INTEGER       TransmittedOctetsInAMPDUCount;
-	LARGE_INTEGER       MPDUInReceivedAMPDUCount;
-} COUNTER_RALINK, *PCOUNTER_RALINK;
-
-typedef struct _PID_COUNTER {
-	ULONG           TxAckRequiredCount;      // CRC error
-	ULONG           TxAggreCount;
-	ULONG           TxSuccessCount; // OneSecTxNoRetryOkCount + OneSecTxRetryOkCount + OneSecTxFailCount
-	ULONG		LastSuccessRate;
-} PID_COUNTER, *PPID_COUNTER;
-
-typedef struct _COUNTER_DRS {
-	// to record the each TX rate's quality. 0 is best, the bigger the worse.
-	USHORT          TxQuality[MAX_STEP_OF_TX_RATE_SWITCH];
-	UCHAR           PER[MAX_STEP_OF_TX_RATE_SWITCH];
-	UCHAR           TxRateUpPenalty;      // extra # of second penalty due to last unstable condition
-	ULONG           CurrTxRateStableTime; // # of second in current TX rate
-	BOOLEAN         fNoisyEnvironment;
-	BOOLEAN         fLastSecAccordingRSSI;
-	UCHAR           LastSecTxRateChangeAction; // 0: no change, 1:rate UP, 2:rate down
-	UCHAR			LastTimeTxRateChangeAction; //Keep last time value of LastSecTxRateChangeAction
-	ULONG			LastTxOkCount;
-} COUNTER_DRS, *PCOUNTER_DRS;
-
-//
-//  Arcfour Structure Added by PaulWu
-//
-typedef struct  _ARCFOUR
-{
-	UINT            X;
-	UINT            Y;
-	UCHAR           STATE[256];
-} ARCFOURCONTEXT, *PARCFOURCONTEXT;
-
-// MIMO Tx parameter, ShortGI, MCS, STBC, etc.  these are fields in TXWI too. just copy to TXWI.
-typedef struct  _RECEIVE_SETTING {
-#ifdef RT_BIG_ENDIAN
-	USHORT		MIMO:1;
-	USHORT		OFDM:1;
-	USHORT		rsv:3;
-	USHORT		STBC:2;	//SPACE
-	USHORT		ShortGI:1;
-	USHORT		Mode:2;	//channel bandwidth 20MHz or 40 MHz
-	USHORT   	NumOfRX:2;                 // MIMO. WE HAVE 3R
-#else
-	USHORT   	NumOfRX:2;                 // MIMO. WE HAVE 3R
-	USHORT		Mode:2;	//channel bandwidth 20MHz or 40 MHz
-	USHORT		ShortGI:1;
-	USHORT		STBC:2;	//SPACE
-	USHORT		rsv:3;
-	USHORT		OFDM:1;
-	USHORT		MIMO:1;
-#endif
- } RECEIVE_SETTING, *PRECEIVE_SETTING;
-
-// Shared key data structure
-typedef struct  _WEP_KEY {
-	UCHAR   KeyLen;                     // Key length for each key, 0: entry is invalid
-	UCHAR   Key[MAX_LEN_OF_KEY];        // right now we implement 4 keys, 128 bits max
-} WEP_KEY, *PWEP_KEY;
-
-typedef struct _CIPHER_KEY {
-	UCHAR   Key[16];            // right now we implement 4 keys, 128 bits max
-	UCHAR   RxMic[8];			// make alignment
-	UCHAR   TxMic[8];
-	UCHAR   TxTsc[6];           // 48bit TSC value
-	UCHAR   RxTsc[6];           // 48bit TSC value
-	UCHAR   CipherAlg;          // 0-none, 1:WEP64, 2:WEP128, 3:TKIP, 4:AES, 5:CKIP64, 6:CKIP128
-	UCHAR   KeyLen;
-#ifdef CONFIG_STA_SUPPORT
-	UCHAR   BssId[6];
-#endif // CONFIG_STA_SUPPORT //
-            // Key length for each key, 0: entry is invalid
-	UCHAR   Type;               // Indicate Pairwise/Group when reporting MIC error
-} CIPHER_KEY, *PCIPHER_KEY;
-
-typedef struct _BBP_TUNING_STRUCT {
-	BOOLEAN     Enable;
-	UCHAR       FalseCcaCountUpperBound;  // 100 per sec
-	UCHAR       FalseCcaCountLowerBound;  // 10 per sec
-	UCHAR       R17LowerBound;            // specified in E2PROM
-	UCHAR       R17UpperBound;            // 0x68 according to David Tung
-	UCHAR       CurrentR17Value;
-} BBP_TUNING, *PBBP_TUNING;
-
-typedef struct _SOFT_RX_ANT_DIVERSITY_STRUCT {
-	UCHAR     EvaluatePeriod;		 // 0:not evalute status, 1: evaluate status, 2: switching status
-	UCHAR     Pair1PrimaryRxAnt;     // 0:Ant-E1, 1:Ant-E2
-	UCHAR     Pair1SecondaryRxAnt;   // 0:Ant-E1, 1:Ant-E2
-	UCHAR     Pair2PrimaryRxAnt;     // 0:Ant-E3, 1:Ant-E4
-	UCHAR     Pair2SecondaryRxAnt;   // 0:Ant-E3, 1:Ant-E4
-	SHORT     Pair1AvgRssi[2];       // AvgRssi[0]:E1, AvgRssi[1]:E2
-	SHORT     Pair2AvgRssi[2];       // AvgRssi[0]:E3, AvgRssi[1]:E4
-	SHORT     Pair1LastAvgRssi;      //
-	SHORT     Pair2LastAvgRssi;      //
-	ULONG     RcvPktNumWhenEvaluate;
-	BOOLEAN   FirstPktArrivedWhenEvaluate;
-	RALINK_TIMER_STRUCT    RxAntDiversityTimer;
-} SOFT_RX_ANT_DIVERSITY, *PSOFT_RX_ANT_DIVERSITY;
-
-typedef struct _LEAP_AUTH_INFO {
-	BOOLEAN         Enabled;        //Ture: Enable LEAP Authentication
-	BOOLEAN         CCKM;           //Ture: Use Fast Reauthentication with CCKM
-	UCHAR           Reserve[2];
-	UCHAR           UserName[256];  //LEAP, User name
-	ULONG           UserNameLen;
-	UCHAR           Password[256];  //LEAP, User Password
-	ULONG           PasswordLen;
-} LEAP_AUTH_INFO, *PLEAP_AUTH_INFO;
-
-typedef struct {
-	UCHAR        Addr[MAC_ADDR_LEN];
-	UCHAR        ErrorCode[2];  //00 01-Invalid authentication type
-								//00 02-Authentication timeout
-								//00 03-Challenge from AP failed
-								//00 04-Challenge to AP failed
-	BOOLEAN      Reported;
-} ROGUEAP_ENTRY, *PROGUEAP_ENTRY;
-
-typedef struct {
-	UCHAR               RogueApNr;
-	ROGUEAP_ENTRY       RogueApEntry[MAX_LEN_OF_BSS_TABLE];
-} ROGUEAP_TABLE, *PROGUEAP_TABLE;
-
-typedef struct {
-	BOOLEAN     Enable;
-	UCHAR       Delta;
-	BOOLEAN     PlusSign;
-} CCK_TX_POWER_CALIBRATE, *PCCK_TX_POWER_CALIBRATE;
-
-//
-// Receive Tuple Cache Format
-//
-typedef struct  _TUPLE_CACHE    {
-	BOOLEAN         Valid;
-	UCHAR           MacAddress[MAC_ADDR_LEN];
-	USHORT          Sequence;
-	USHORT          Frag;
-} TUPLE_CACHE, *PTUPLE_CACHE;
-
-//
-// Fragment Frame structure
-//
-typedef struct  _FRAGMENT_FRAME {
-	PNDIS_PACKET    pFragPacket;
-	ULONG       RxSize;
-	USHORT      Sequence;
-	USHORT      LastFrag;
-	ULONG       Flags;          // Some extra frame information. bit 0: LLC presented
-} FRAGMENT_FRAME, *PFRAGMENT_FRAME;
-
-
-//
-// Packet information for NdisQueryPacket
-//
-typedef struct  _PACKET_INFO    {
-	UINT            PhysicalBufferCount;    // Physical breaks of buffer descripor chained
-	UINT            BufferCount ;           // Number of Buffer descriptor chained
-	UINT            TotalPacketLength ;     // Self explained
-	PNDIS_BUFFER    pFirstBuffer;           // Pointer to first buffer descriptor
-} PACKET_INFO, *PPACKET_INFO;
-
-//
-// Tkip Key structure which RC4 key & MIC calculation
-//
-typedef struct  _TKIP_KEY_INFO  {
-	UINT        nBytesInM;  // # bytes in M for MICKEY
-	ULONG       IV16;
-	ULONG       IV32;
-	ULONG       K0;         // for MICKEY Low
-	ULONG       K1;         // for MICKEY Hig
-	ULONG       L;          // Current state for MICKEY
-	ULONG       R;          // Current state for MICKEY
-	ULONG       M;          // Message accumulator for MICKEY
-	UCHAR       RC4KEY[16];
-	UCHAR       MIC[8];
-} TKIP_KEY_INFO, *PTKIP_KEY_INFO;
-
-//
-// Private / Misc data, counters for driver internal use
-//
-typedef struct  __PRIVATE_STRUC {
-	UINT       SystemResetCnt;         // System reset counter
-	UINT       TxRingFullCnt;          // Tx ring full occurrance number
-	UINT       PhyRxErrCnt;            // PHY Rx error count, for debug purpose, might move to global counter
-	// Variables for WEP encryption / decryption in rtmp_wep.c
-	UINT       FCSCRC32;
-	ARCFOURCONTEXT  WEPCONTEXT;
-	// Tkip stuff
-	TKIP_KEY_INFO   Tx;
-	TKIP_KEY_INFO   Rx;
-} PRIVATE_STRUC, *PPRIVATE_STRUC;
-
-// structure to tune BBP R66 (BBP TUNING)
-typedef struct _BBP_R66_TUNING {
-	BOOLEAN     bEnable;
-	USHORT      FalseCcaLowerThreshold;  // default 100
-	USHORT      FalseCcaUpperThreshold;  // default 512
-	UCHAR       R66Delta;
-	UCHAR       R66CurrentValue;
-	BOOLEAN		R66LowerUpperSelect; //Before LinkUp, Used LowerBound or UpperBound as R66 value.
-} BBP_R66_TUNING, *PBBP_R66_TUNING;
-
-// structure to store channel TX power
-typedef struct _CHANNEL_TX_POWER {
-	USHORT     RemainingTimeForUse;		//unit: sec
-	UCHAR      Channel;
-#ifdef DOT11N_DRAFT3
-	BOOLEAN       bEffectedChannel;	// For BW 40 operating in 2.4GHz , the "effected channel" is the channel that is covered in 40Mhz.
-#endif // DOT11N_DRAFT3 //
-	CHAR       Power;
-	CHAR       Power2;
-	UCHAR      MaxTxPwr;
-	UCHAR      DfsReq;
-} CHANNEL_TX_POWER, *PCHANNEL_TX_POWER;
-
-// structure to store 802.11j channel TX power
-typedef struct _CHANNEL_11J_TX_POWER {
-	UCHAR      Channel;
-	UCHAR      BW;	// BW_10 or BW_20
-	CHAR       Power;
-	CHAR       Power2;
-	USHORT     RemainingTimeForUse;		//unit: sec
-} CHANNEL_11J_TX_POWER, *PCHANNEL_11J_TX_POWER;
-
-typedef enum _ABGBAND_STATE_ {
-	UNKNOWN_BAND,
-	BG_BAND,
-	A_BAND,
-} ABGBAND_STATE;
-
-typedef struct _MLME_STRUCT {
-#ifdef CONFIG_STA_SUPPORT
-	// STA state machines
-	STATE_MACHINE           CntlMachine;
-	STATE_MACHINE           AssocMachine;
-	STATE_MACHINE           AuthMachine;
-	STATE_MACHINE           AuthRspMachine;
-	STATE_MACHINE           SyncMachine;
-	STATE_MACHINE           WpaPskMachine;
-	STATE_MACHINE           LeapMachine;
-	STATE_MACHINE           AironetMachine;
-	STATE_MACHINE_FUNC      AssocFunc[ASSOC_FUNC_SIZE];
-	STATE_MACHINE_FUNC      AuthFunc[AUTH_FUNC_SIZE];
-	STATE_MACHINE_FUNC      AuthRspFunc[AUTH_RSP_FUNC_SIZE];
-	STATE_MACHINE_FUNC      SyncFunc[SYNC_FUNC_SIZE];
-	STATE_MACHINE_FUNC      WpaPskFunc[WPA_PSK_FUNC_SIZE];
-	STATE_MACHINE_FUNC      AironetFunc[AIRONET_FUNC_SIZE];
-#endif // CONFIG_STA_SUPPORT //
-	STATE_MACHINE_FUNC      ActFunc[ACT_FUNC_SIZE];
-	// Action
-	STATE_MACHINE           ActMachine;
-
-
-#ifdef QOS_DLS_SUPPORT
-	STATE_MACHINE			DlsMachine;
-	STATE_MACHINE_FUNC      DlsFunc[DLS_FUNC_SIZE];
-#endif // QOS_DLS_SUPPORT //
-
-
-
-
-	ULONG                   ChannelQuality;  // 0..100, Channel Quality Indication for Roaming
-	ULONG                   Now32;           // latch the value of NdisGetSystemUpTime()
-	ULONG                   LastSendNULLpsmTime;
-
-	BOOLEAN                 bRunning;
-	NDIS_SPIN_LOCK          TaskLock;
-	MLME_QUEUE              Queue;
-
-	UINT                    ShiftReg;
-
-	RALINK_TIMER_STRUCT     PeriodicTimer;
-	RALINK_TIMER_STRUCT     APSDPeriodicTimer;
-	RALINK_TIMER_STRUCT     LinkDownTimer;
-	RALINK_TIMER_STRUCT     LinkUpTimer;
-	ULONG                   PeriodicRound;
-	ULONG                   OneSecPeriodicRound;
-
-	UCHAR					RealRxPath;
-	BOOLEAN					bLowThroughput;
-	BOOLEAN					bEnableAutoAntennaCheck;
-	RALINK_TIMER_STRUCT		RxAntEvalTimer;
-
-#ifdef RT2870
-	UCHAR CaliBW40RfR24;
-	UCHAR CaliBW20RfR24;
-#endif // RT2870 //
-
-} MLME_STRUCT, *PMLME_STRUCT;
-
-// structure for radar detection and channel switch
-typedef struct _RADAR_DETECT_STRUCT {
-    //BOOLEAN		IEEE80211H;			// 0: disable, 1: enable IEEE802.11h
-	UCHAR		CSCount;			//Channel switch counter
-	UCHAR		CSPeriod;			//Channel switch period (beacon count)
-	UCHAR		RDCount;			//Radar detection counter
-	UCHAR		RDMode;				//Radar Detection mode
-	UCHAR		RDDurRegion;		//Radar detection duration region
-	UCHAR		BBPR16;
-	UCHAR		BBPR17;
-	UCHAR		BBPR18;
-	UCHAR		BBPR21;
-	UCHAR		BBPR22;
-	UCHAR		BBPR64;
-	ULONG		InServiceMonitorCount; // unit: sec
-	UINT8		DfsSessionTime;
-	BOOLEAN		bFastDfs;
-	UINT8		ChMovingTime;
-	UINT8		LongPulseRadarTh;
-} RADAR_DETECT_STRUCT, *PRADAR_DETECT_STRUCT;
-
-#ifdef CARRIER_DETECTION_SUPPORT
-typedef enum CD_STATE_n
-{
-	CD_NORMAL,
-	CD_SILENCE,
-	CD_MAX_STATE
-} CD_STATE;
-
-typedef struct CARRIER_DETECTION_s
-{
-	BOOLEAN					Enable;
-	UINT8					CDSessionTime;
-	UINT8					CDPeriod;
-	CD_STATE				CD_State;
-} CARRIER_DETECTION, *PCARRIER_DETECTION;
-#endif // CARRIER_DETECTION_SUPPORT //
-
-typedef enum _REC_BLOCKACK_STATUS
-{
-    Recipient_NONE=0,
-	Recipient_USED,
-	Recipient_HandleRes,
-    Recipient_Accept
-} REC_BLOCKACK_STATUS, *PREC_BLOCKACK_STATUS;
-
-typedef enum _ORI_BLOCKACK_STATUS
-{
-    Originator_NONE=0,
-	Originator_USED,
-    Originator_WaitRes,
-    Originator_Done
-} ORI_BLOCKACK_STATUS, *PORI_BLOCKACK_STATUS;
-
-#ifdef DOT11_N_SUPPORT
-typedef struct _BA_ORI_ENTRY{
-	UCHAR   Wcid;
-	UCHAR   TID;
-	UCHAR   BAWinSize;
-	UCHAR   Token;
-// Sequence is to fill every outgoing QoS DATA frame's sequence field in 802.11 header.
-	USHORT	Sequence;
-	USHORT	TimeOutValue;
-	ORI_BLOCKACK_STATUS  ORI_BA_Status;
-	RALINK_TIMER_STRUCT ORIBATimer;
-	PVOID	pAdapter;
-} BA_ORI_ENTRY, *PBA_ORI_ENTRY;
-
-typedef struct _BA_REC_ENTRY {
-	UCHAR   Wcid;
-	UCHAR   TID;
-	UCHAR   BAWinSize;	// 7.3.1.14. each buffer is capable of holding a max AMSDU or MSDU.
-	//UCHAR	NumOfRxPkt;
-	//UCHAR    Curindidx; // the head in the RX reordering buffer
-	USHORT		LastIndSeq;
-//	USHORT		LastIndSeqAtTimer;
-	USHORT		TimeOutValue;
-	RALINK_TIMER_STRUCT RECBATimer;
-	ULONG		LastIndSeqAtTimer;
-	ULONG		nDropPacket;
-	ULONG		rcvSeq;
-	REC_BLOCKACK_STATUS  REC_BA_Status;
-//	UCHAR	RxBufIdxUsed;
-	// corresponding virtual address for RX reordering packet storage.
-	//RTMP_REORDERDMABUF MAP_RXBuf[MAX_RX_REORDERBUF];
-	NDIS_SPIN_LOCK          RxReRingLock;                 // Rx Ring spinlock
-//	struct _BA_REC_ENTRY *pNext;
-	PVOID	pAdapter;
-	struct reordering_list	list;
-} BA_REC_ENTRY, *PBA_REC_ENTRY;
-
-
-typedef struct {
-	ULONG		numAsRecipient;		// I am recipient of numAsRecipient clients. These client are in the BARecEntry[]
-	ULONG		numAsOriginator;	// I am originator of 	numAsOriginator clients. These clients are in the BAOriEntry[]
-	BA_ORI_ENTRY       BAOriEntry[MAX_LEN_OF_BA_ORI_TABLE];
-	BA_REC_ENTRY       BARecEntry[MAX_LEN_OF_BA_REC_TABLE];
-} BA_TABLE, *PBA_TABLE;
-
-//For QureyBATableOID use;
-typedef struct  PACKED _OID_BA_REC_ENTRY{
-	UCHAR   MACAddr[MAC_ADDR_LEN];
-	UCHAR   BaBitmap;   // if (BaBitmap&(1<<TID)), this session with{MACAddr, TID}exists, so read BufSize[TID] for BufferSize
-	UCHAR   rsv;
-	UCHAR   BufSize[8];
-	REC_BLOCKACK_STATUS	REC_BA_Status[8];
-} OID_BA_REC_ENTRY, *POID_BA_REC_ENTRY;
-
-//For QureyBATableOID use;
-typedef struct  PACKED _OID_BA_ORI_ENTRY{
-	UCHAR   MACAddr[MAC_ADDR_LEN];
-	UCHAR   BaBitmap;  // if (BaBitmap&(1<<TID)), this session with{MACAddr, TID}exists, so read BufSize[TID] for BufferSize, read ORI_BA_Status[TID] for status
-	UCHAR   rsv;
-	UCHAR   BufSize[8];
-	ORI_BLOCKACK_STATUS  ORI_BA_Status[8];
-} OID_BA_ORI_ENTRY, *POID_BA_ORI_ENTRY;
-
-typedef struct _QUERYBA_TABLE{
-	OID_BA_ORI_ENTRY       BAOriEntry[32];
-	OID_BA_REC_ENTRY       BARecEntry[32];
-	UCHAR   OriNum;// Number of below BAOriEntry
-	UCHAR   RecNum;// Number of below BARecEntry
-} QUERYBA_TABLE, *PQUERYBA_TABLE;
-
-typedef	union	_BACAP_STRUC	{
-#ifdef RT_BIG_ENDIAN
-	struct	{
-		UINT32     :4;
-		UINT32     b2040CoexistScanSup:1;		//As Sta, support do 2040 coexistence scan for AP. As Ap, support monitor trigger event to check if can use BW 40MHz.
-		UINT32     bHtAdhoc:1;			// adhoc can use ht rate.
-		UINT32     MMPSmode:2;	// MIMO power save more, 0:static, 1:dynamic, 2:rsv, 3:mimo enable
-		UINT32     AmsduSize:1;	// 0:3839, 1:7935 bytes. UINT  MSDUSizeToBytes[]	= { 3839, 7935};
-		UINT32     AmsduEnable:1;	//Enable AMSDU transmisstion
-		UINT32		MpduDensity:3;
-		UINT32		Policy:2;	// 0: DELAY_BA 1:IMMED_BA  (//BA Policy subfiled value in ADDBA frame)   2:BA-not use
-		UINT32		AutoBA:1;	// automatically BA
-		UINT32		TxBAWinLimit:8;
-		UINT32		RxBAWinLimit:8;
-	}	field;
-#else
-	struct	{
-		UINT32		RxBAWinLimit:8;
-		UINT32		TxBAWinLimit:8;
-		UINT32		AutoBA:1;	// automatically BA
-		UINT32		Policy:2;	// 0: DELAY_BA 1:IMMED_BA  (//BA Policy subfiled value in ADDBA frame)   2:BA-not use
-		UINT32		MpduDensity:3;
-		UINT32       	AmsduEnable:1;	//Enable AMSDU transmisstion
-		UINT32       	AmsduSize:1;	// 0:3839, 1:7935 bytes. UINT  MSDUSizeToBytes[]	= { 3839, 7935};
-		UINT32       	MMPSmode:2;	// MIMO power save more, 0:static, 1:dynamic, 2:rsv, 3:mimo enable
-		UINT32       	bHtAdhoc:1;			// adhoc can use ht rate.
-		UINT32       	b2040CoexistScanSup:1;		//As Sta, support do 2040 coexistence scan for AP. As Ap, support monitor trigger event to check if can use BW 40MHz.
-		UINT32       	:4;
-	}	field;
-#endif
-	UINT32			word;
-} BACAP_STRUC, *PBACAP_STRUC;
-#endif // DOT11_N_SUPPORT //
-
-//This structure is for all 802.11n card InterOptibilityTest action. Reset all Num every n second.  (Details see MLMEPeriodic)
-typedef	struct	_IOT_STRUC	{
-	UCHAR			Threshold[2];
-	UCHAR			ReorderTimeOutNum[MAX_LEN_OF_BA_REC_TABLE];	// compare with threshold[0]
-	UCHAR			RefreshNum[MAX_LEN_OF_BA_REC_TABLE];	// compare with threshold[1]
-	ULONG			OneSecInWindowCount;
-	ULONG			OneSecFrameDuplicateCount;
-	ULONG			OneSecOutWindowCount;
-	UCHAR			DelOriAct;
-	UCHAR			DelRecAct;
-	UCHAR			RTSShortProt;
-	UCHAR			RTSLongProt;
-	BOOLEAN			bRTSLongProtOn;
-#ifdef CONFIG_STA_SUPPORT
-	BOOLEAN			bLastAtheros;
-    BOOLEAN			bCurrentAtheros;
-    BOOLEAN         bNowAtherosBurstOn;
-	BOOLEAN			bNextDisableRxBA;
-    BOOLEAN			bToggle;
-#endif // CONFIG_STA_SUPPORT //
-} IOT_STRUC, *PIOT_STRUC;
-
-// This is the registry setting for 802.11n transmit setting.  Used in advanced page.
-typedef union _REG_TRANSMIT_SETTING {
-#ifdef RT_BIG_ENDIAN
- struct {
-         UINT32  rsv:13;
-		 UINT32  EXTCHA:2;
-		 UINT32  HTMODE:1;
-		 UINT32  TRANSNO:2;
-		 UINT32  STBC:1; //SPACE
-		 UINT32  ShortGI:1;
-		 UINT32  BW:1; //channel bandwidth 20MHz or 40 MHz
-		 UINT32  TxBF:1; // 3*3
-		 UINT32  rsv0:10;
-		 //UINT32  MCS:7;                 // MCS
-         //UINT32  PhyMode:4;
-    } field;
-#else
- struct {
-         //UINT32  PhyMode:4;
-         //UINT32  MCS:7;                 // MCS
-		 UINT32  rsv0:10;
-		 UINT32  TxBF:1;
-         UINT32  BW:1; //channel bandwidth 20MHz or 40 MHz
-         UINT32  ShortGI:1;
-         UINT32  STBC:1; //SPACE
-         UINT32  TRANSNO:2;
-         UINT32  HTMODE:1;
-         UINT32  EXTCHA:2;
-         UINT32  rsv:13;
-    } field;
-#endif
- UINT32   word;
-} REG_TRANSMIT_SETTING, *PREG_TRANSMIT_SETTING;
-
-typedef union  _DESIRED_TRANSMIT_SETTING {
-#ifdef RT_BIG_ENDIAN
-	struct	{
-			USHORT		rsv:3;
-			USHORT		FixedTxMode:2;			// If MCS isn't AUTO, fix rate in CCK, OFDM or HT mode.
-			USHORT		PhyMode:4;
-			USHORT   	MCS:7;                 // MCS
-	}	field;
-#else
-	struct	{
-			USHORT   	MCS:7;                 	// MCS
-			USHORT		PhyMode:4;
-			USHORT	 	FixedTxMode:2;			// If MCS isn't AUTO, fix rate in CCK, OFDM or HT mode.
-			USHORT		rsv:3;
-	}	field;
-#endif
-	USHORT		word;
- } DESIRED_TRANSMIT_SETTING, *PDESIRED_TRANSMIT_SETTING;
-
-typedef struct {
-	BOOLEAN		IsRecipient;
-	UCHAR   MACAddr[MAC_ADDR_LEN];
-	UCHAR   TID;
-	UCHAR   nMSDU;
-	USHORT   TimeOut;
-	BOOLEAN bAllTid;  // If True, delete all TID for BA sessions with this MACaddr.
-} OID_ADD_BA_ENTRY, *POID_ADD_BA_ENTRY;
-
-//
-// Multiple SSID structure
-//
-#define WLAN_MAX_NUM_OF_TIM			((MAX_LEN_OF_MAC_TABLE >> 3) + 1) /* /8 + 1 */
-#define WLAN_CT_TIM_BCMC_OFFSET		0 /* unit: 32B */
-
-/* clear bcmc TIM bit */
-#define WLAN_MR_TIM_BCMC_CLEAR(apidx) \
-	pAd->ApCfg.MBSSID[apidx].TimBitmaps[WLAN_CT_TIM_BCMC_OFFSET] &= ~BIT8[0];
-
-/* set bcmc TIM bit */
-#define WLAN_MR_TIM_BCMC_SET(apidx) \
-	pAd->ApCfg.MBSSID[apidx].TimBitmaps[WLAN_CT_TIM_BCMC_OFFSET] |= BIT8[0];
-
-/* clear a station PS TIM bit */
-#define WLAN_MR_TIM_BIT_CLEAR(ad_p, apidx, wcid) \
-	{	UCHAR tim_offset = wcid >> 3; \
-		UCHAR bit_offset = wcid & 0x7; \
-		ad_p->ApCfg.MBSSID[apidx].TimBitmaps[tim_offset] &= (~BIT8[bit_offset]); }
-
-/* set a station PS TIM bit */
-#define WLAN_MR_TIM_BIT_SET(ad_p, apidx, wcid) \
-	{	UCHAR tim_offset = wcid >> 3; \
-		UCHAR bit_offset = wcid & 0x7; \
-		ad_p->ApCfg.MBSSID[apidx].TimBitmaps[tim_offset] |= BIT8[bit_offset]; }
-
-#ifdef RT2870
-#define BEACON_BITMAP_MASK		0xff
-typedef struct _BEACON_SYNC_STRUCT_
-{
-	UCHAR        			BeaconBuf[HW_BEACON_MAX_COUNT][HW_BEACON_OFFSET];
-	UCHAR					BeaconTxWI[HW_BEACON_MAX_COUNT][TXWI_SIZE];
-	ULONG 					TimIELocationInBeacon[HW_BEACON_MAX_COUNT];
-	ULONG					CapabilityInfoLocationInBeacon[HW_BEACON_MAX_COUNT];
-	BOOLEAN					EnableBeacon;		// trigger to enable beacon transmission.
-	UCHAR					BeaconBitMap;		// NOTE: If the MAX_MBSSID_NUM is larger than 8, this parameter need to change.
-	UCHAR					DtimBitOn;			// NOTE: If the MAX_MBSSID_NUM is larger than 8, this parameter need to change.
-}BEACON_SYNC_STRUCT;
-#endif // RT2870 //
-
-typedef struct _MULTISSID_STRUCT {
-	UCHAR								Bssid[MAC_ADDR_LEN];
-    UCHAR                               SsidLen;
-    CHAR                                Ssid[MAX_LEN_OF_SSID];
-    USHORT                              CapabilityInfo;
-
-    PNET_DEV                   			MSSIDDev;
-
-	NDIS_802_11_AUTHENTICATION_MODE     AuthMode;
-	NDIS_802_11_WEP_STATUS              WepStatus;
-	NDIS_802_11_WEP_STATUS				GroupKeyWepStatus;
-	WPA_MIX_PAIR_CIPHER					WpaMixPairCipher;
-
-	ULONG								TxCount;
-	ULONG								RxCount;
-	ULONG								ReceivedByteCount;
-	ULONG								TransmittedByteCount;
-	ULONG								RxErrorCount;
-	ULONG								RxDropCount;
-
-	HTTRANSMIT_SETTING					HTPhyMode, MaxHTPhyMode, MinHTPhyMode;// For transmit phy setting in TXWI.
-	RT_HT_PHY_INFO						DesiredHtPhyInfo;
-	DESIRED_TRANSMIT_SETTING        	DesiredTransmitSetting; // Desired transmit setting. this is for reading registry setting only. not useful.
-	BOOLEAN								bAutoTxRateSwitch;
-
-	//CIPHER_KEY                          SharedKey[SHARE_KEY_NUM]; // ref pAd->SharedKey[BSS][4]
-	UCHAR                               DefaultKeyId;
-
-	UCHAR								TxRate;       // RATE_1, RATE_2, RATE_5_5, RATE_11, ...
-	UCHAR     							DesiredRates[MAX_LEN_OF_SUPPORTED_RATES];// OID_802_11_DESIRED_RATES
-	UCHAR								DesiredRatesIndex;
-	UCHAR     							MaxTxRate;            // RATE_1, RATE_2, RATE_5_5, RATE_11
-
-//	ULONG           					TimBitmap;      // bit0 for broadcast, 1 for AID1, 2 for AID2, ...so on
-//    ULONG           					TimBitmap2;     // b0 for AID32, b1 for AID33, ... and so on
-	UCHAR								TimBitmaps[WLAN_MAX_NUM_OF_TIM];
-
-    // WPA
-    UCHAR                               GMK[32];
-    UCHAR                               PMK[32];
-	UCHAR								GTK[32];
-    BOOLEAN                             IEEE8021X;
-    BOOLEAN                             PreAuth;
-    UCHAR                               GNonce[32];
-    UCHAR                               PortSecured;
-    NDIS_802_11_PRIVACY_FILTER          PrivacyFilter;
-    UCHAR                               BANClass3Data;
-    ULONG                               IsolateInterStaTraffic;
-
-    UCHAR                               RSNIE_Len[2];
-    UCHAR                               RSN_IE[2][MAX_LEN_OF_RSNIE];
-
-
-    UCHAR                   			TimIELocationInBeacon;
-    UCHAR                   			CapabilityInfoLocationInBeacon;
-    // outgoing BEACON frame buffer and corresponding TXWI
-	// PTXWI_STRUC                           BeaconTxWI; //
-    CHAR                                BeaconBuf[MAX_BEACON_SIZE]; // NOTE: BeaconBuf should be 4-byte aligned
-
-    BOOLEAN                             bHideSsid;
-	UINT16								StationKeepAliveTime; // unit: second
-
-    USHORT                              VLAN_VID;
-    USHORT                              VLAN_Priority;
-
-    RT_802_11_ACL						AccessControlList;
-
-	// EDCA Qos
-    BOOLEAN								bWmmCapable;	// 0:disable WMM, 1:enable WMM
-    BOOLEAN								bDLSCapable;	// 0:disable DLS, 1:enable DLS
-
-	UCHAR           					DlsPTK[64];		// Due to windows dirver count on meetinghouse to handle 4-way shake
-
-	// For 802.1x daemon setting per BSS
-	UCHAR								radius_srv_num;
-	RADIUS_SRV_INFO						radius_srv_info[MAX_RADIUS_SRV_NUM];
-
-#ifdef RTL865X_SOC
-	unsigned int						mylinkid;
-#endif
-
-
-	UINT32					RcvdConflictSsidCount;
-	UINT32					RcvdSpoofedAssocRespCount;
-	UINT32					RcvdSpoofedReassocRespCount;
-	UINT32					RcvdSpoofedProbeRespCount;
-	UINT32					RcvdSpoofedBeaconCount;
-	UINT32					RcvdSpoofedDisassocCount;
-	UINT32					RcvdSpoofedAuthCount;
-	UINT32					RcvdSpoofedDeauthCount;
-	UINT32					RcvdSpoofedUnknownMgmtCount;
-	UINT32					RcvdReplayAttackCount;
-
-	CHAR					RssiOfRcvdConflictSsid;
-	CHAR					RssiOfRcvdSpoofedAssocResp;
-	CHAR					RssiOfRcvdSpoofedReassocResp;
-	CHAR					RssiOfRcvdSpoofedProbeResp;
-	CHAR					RssiOfRcvdSpoofedBeacon;
-	CHAR					RssiOfRcvdSpoofedDisassoc;
-	CHAR					RssiOfRcvdSpoofedAuth;
-	CHAR					RssiOfRcvdSpoofedDeauth;
-	CHAR					RssiOfRcvdSpoofedUnknownMgmt;
-	CHAR					RssiOfRcvdReplayAttack;
-
-	BOOLEAN					bBcnSntReq;
-	UCHAR					BcnBufIdx;
-} MULTISSID_STRUCT, *PMULTISSID_STRUCT;
-
-
-
-#ifdef DOT11N_DRAFT3
-typedef enum _BSS2040COEXIST_FLAG{
-	BSS_2040_COEXIST_DISABLE = 0,
-	BSS_2040_COEXIST_TIMER_FIRED  = 1,
-	BSS_2040_COEXIST_INFO_SYNC = 2,
-	BSS_2040_COEXIST_INFO_NOTIFY = 4,
-}BSS2040COEXIST_FLAG;
-#endif // DOT11N_DRAFT3 //
-
-// configuration common to OPMODE_AP as well as OPMODE_STA
-typedef struct _COMMON_CONFIG {
-
-	BOOLEAN		bCountryFlag;
-	UCHAR		CountryCode[3];
-	UCHAR		Geography;
-	UCHAR       CountryRegion;      // Enum of country region, 0:FCC, 1:IC, 2:ETSI, 3:SPAIN, 4:France, 5:MKK, 6:MKK1, 7:Israel
-	UCHAR       CountryRegionForABand;	// Enum of country region for A band
-	UCHAR       PhyMode;            // PHY_11A, PHY_11B, PHY_11BG_MIXED, PHY_ABG_MIXED
-	USHORT      Dsifs;              // in units of usec
-	ULONG       PacketFilter;       // Packet filter for receiving
-
-	CHAR        Ssid[MAX_LEN_OF_SSID]; // NOT NULL-terminated
-	UCHAR       SsidLen;               // the actual ssid length in used
-	UCHAR       LastSsidLen;               // the actual ssid length in used
-	CHAR        LastSsid[MAX_LEN_OF_SSID]; // NOT NULL-terminated
-	UCHAR		LastBssid[MAC_ADDR_LEN];
-
-	UCHAR       Bssid[MAC_ADDR_LEN];
-	USHORT      BeaconPeriod;
-	UCHAR       Channel;
-	UCHAR       CentralChannel;    	// Central Channel when using 40MHz is indicating. not real channel.
-
-#if 0	// move to STA_ADMIN_CONFIG
-	UCHAR       DefaultKeyId;
-
-	NDIS_802_11_PRIVACY_FILTER          PrivacyFilter;  // PrivacyFilter enum for 802.1X
-	NDIS_802_11_AUTHENTICATION_MODE     AuthMode;       // This should match to whatever microsoft defined
-	NDIS_802_11_WEP_STATUS              WepStatus;
-	NDIS_802_11_WEP_STATUS				OrigWepStatus;	// Original wep status set from OID
-
-	// Add to support different cipher suite for WPA2/WPA mode
-	NDIS_802_11_ENCRYPTION_STATUS		GroupCipher;		// Multicast cipher suite
-	NDIS_802_11_ENCRYPTION_STATUS		PairCipher;			// Unicast cipher suite
-	BOOLEAN								bMixCipher;			// Indicate current Pair & Group use different cipher suites
-	USHORT								RsnCapability;
-
-	NDIS_802_11_WEP_STATUS              GroupKeyWepStatus;
-#endif
-
-	UCHAR       SupRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR       SupRateLen;
-	UCHAR       ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR       ExtRateLen;
-	UCHAR       DesireRate[MAX_LEN_OF_SUPPORTED_RATES];      // OID_802_11_DESIRED_RATES
-	UCHAR       MaxDesiredRate;
-	UCHAR       ExpectedACKRate[MAX_LEN_OF_SUPPORTED_RATES];
-
-	ULONG       BasicRateBitmap;        // backup basic ratebitmap
-
-	BOOLEAN		bAPSDCapable;
-	BOOLEAN		bInServicePeriod;
-	BOOLEAN		bAPSDAC_BE;
-	BOOLEAN		bAPSDAC_BK;
-	BOOLEAN		bAPSDAC_VI;
-	BOOLEAN		bAPSDAC_VO;
-	BOOLEAN		bNeedSendTriggerFrame;
-	BOOLEAN		bAPSDForcePowerSave;	// Force power save mode, should only use in APSD-STAUT
-	ULONG		TriggerTimerCount;
-	UCHAR		MaxSPLength;
-	UCHAR		BBPCurrentBW;	// BW_10, 	BW_20, BW_40
-	// move to MULTISSID_STRUCT for MBSS
-	//HTTRANSMIT_SETTING	HTPhyMode, MaxHTPhyMode, MinHTPhyMode;// For transmit phy setting in TXWI.
-	REG_TRANSMIT_SETTING        RegTransmitSetting; //registry transmit setting. this is for reading registry setting only. not useful.
-	//UCHAR       FixedTxMode;              // Fixed Tx Mode (CCK, OFDM), for HT fixed tx mode (GF, MIX) , refer to RegTransmitSetting.field.HTMode
-	UCHAR       TxRate;                 // Same value to fill in TXD. TxRate is 6-bit
-	UCHAR       MaxTxRate;              // RATE_1, RATE_2, RATE_5_5, RATE_11
-	UCHAR       TxRateIndex;            // Tx rate index in RateSwitchTable
-	UCHAR       TxRateTableSize;        // Valid Tx rate table size in RateSwitchTable
-	//BOOLEAN		bAutoTxRateSwitch;
-	UCHAR       MinTxRate;              // RATE_1, RATE_2, RATE_5_5, RATE_11
-	UCHAR       RtsRate;                // RATE_xxx
-	HTTRANSMIT_SETTING	MlmeTransmit;   // MGMT frame PHY rate setting when operatin at Ht rate.
-	UCHAR       MlmeRate;               // RATE_xxx, used to send MLME frames
-	UCHAR       BasicMlmeRate;          // Default Rate for sending MLME frames
-
-	USHORT      RtsThreshold;           // in unit of BYTE
-	USHORT      FragmentThreshold;      // in unit of BYTE
-
-	UCHAR       TxPower;                // in unit of mW
-	ULONG       TxPowerPercentage;      // 0~100 %
-	ULONG       TxPowerDefault;         // keep for TxPowerPercentage
-
-#ifdef DOT11_N_SUPPORT
-	BACAP_STRUC        BACapability; //   NO USE = 0XFF  ;  IMMED_BA =1  ;  DELAY_BA=0
-	BACAP_STRUC        REGBACapability; //   NO USE = 0XFF  ;  IMMED_BA =1  ;  DELAY_BA=0
-#endif // DOT11_N_SUPPORT //
-	IOT_STRUC		IOTestParm;	// 802.11n InterOpbility Test Parameter;
-	ULONG       TxPreamble;             // Rt802_11PreambleLong, Rt802_11PreambleShort, Rt802_11PreambleAuto
-	BOOLEAN     bUseZeroToDisableFragment;     // Microsoft use 0 as disable
-	ULONG       UseBGProtection;        // 0: auto, 1: always use, 2: always not use
-	BOOLEAN     bUseShortSlotTime;      // 0: disable, 1 - use short slot (9us)
-	BOOLEAN     bEnableTxBurst;         // 1: enble TX PACKET BURST, 0: disable TX PACKET BURST
-	BOOLEAN     bAggregationCapable;      // 1: enable TX aggregation when the peer supports it
-	BOOLEAN     bPiggyBackCapable;		// 1: enable TX piggy-back according MAC's version
-	BOOLEAN     bIEEE80211H;			// 1: enable IEEE802.11h spec.
-	ULONG		DisableOLBCDetect;		// 0: enable OLBC detect; 1 disable OLBC detect
-
-#ifdef DOT11_N_SUPPORT
-	BOOLEAN				bRdg;
-#endif // DOT11_N_SUPPORT //
-	BOOLEAN             bWmmCapable;        // 0:disable WMM, 1:enable WMM
-	QOS_CAPABILITY_PARM APQosCapability;    // QOS capability of the current associated AP
-	EDCA_PARM           APEdcaParm;         // EDCA parameters of the current associated AP
-	QBSS_LOAD_PARM      APQbssLoad;         // QBSS load of the current associated AP
-	UCHAR               AckPolicy[4];       // ACK policy of the specified AC. see ACK_xxx
-#ifdef CONFIG_STA_SUPPORT
-	BOOLEAN				bDLSCapable;		// 0:disable DLS, 1:enable DLS
-#endif // CONFIG_STA_SUPPORT //
-	// a bitmap of BOOLEAN flags. each bit represent an operation status of a particular
-	// BOOLEAN control, either ON or OFF. These flags should always be accessed via
-	// OPSTATUS_TEST_FLAG(), OPSTATUS_SET_FLAG(), OP_STATUS_CLEAR_FLAG() macros.
-	// see fOP_STATUS_xxx in RTMP_DEF.C for detail bit definition
-	ULONG               OpStatusFlags;
-
-	BOOLEAN				NdisRadioStateOff; //For HCT 12.0, set this flag to TRUE instead of called MlmeRadioOff.
-	ABGBAND_STATE		BandState;		// For setting BBP used on B/G or A mode.
-
-	// IEEE802.11H--DFS.
-	RADAR_DETECT_STRUCT	RadarDetect;
-
-#ifdef CARRIER_DETECTION_SUPPORT
-	CARRIER_DETECTION		CarrierDetect;
-#endif // CARRIER_DETECTION_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-	// HT
-	UCHAR			BASize;		// USer desired BAWindowSize. Should not exceed our max capability
-	//RT_HT_CAPABILITY	SupportedHtPhy;
-	RT_HT_CAPABILITY	DesiredHtPhy;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHTInfo;	// Useful as AP.
-	//This IE is used with channel switch announcement element when changing to a new 40MHz.
-	//This IE is included in channel switch ammouncement frames 7.4.1.5, beacons, probe Rsp.
-	NEW_EXT_CHAN_IE	NewExtChanOffset;	//7.3.2.20A, 1 if extension channel is above the control channel, 3 if below, 0 if not present
-
-#ifdef DOT11N_DRAFT3
-	UCHAR					Bss2040CoexistFlag;		// bit 0: bBssCoexistTimerRunning, bit 1: NeedSyncAddHtInfo.
-	RALINK_TIMER_STRUCT	Bss2040CoexistTimer;
-
-	//This IE is used for 20/40 BSS Coexistence.
-	BSS_2040_COEXIST_IE		BSS2040CoexistInfo;
-	// ====== 11n D3.0 =======================>
-	USHORT					Dot11OBssScanPassiveDwell;				// Unit : TU. 5~1000
-	USHORT					Dot11OBssScanActiveDwell;				// Unit : TU. 10~1000
-	USHORT					Dot11BssWidthTriggerScanInt;			// Unit : Second
-	USHORT					Dot11OBssScanPassiveTotalPerChannel;	// Unit : TU. 200~10000
-	USHORT					Dot11OBssScanActiveTotalPerChannel;	// Unit : TU. 20~10000
-	USHORT					Dot11BssWidthChanTranDelayFactor;
-	USHORT					Dot11OBssScanActivityThre;				// Unit : percentage
-
-	ULONG					Dot11BssWidthChanTranDelay;			// multiple of (Dot11BssWidthTriggerScanInt * Dot11BssWidthChanTranDelayFactor)
-	ULONG					CountDownCtr;	// CountDown Counter from (Dot11BssWidthTriggerScanInt * Dot11BssWidthChanTranDelayFactor)
-
-	NDIS_SPIN_LOCK          TriggerEventTabLock;
-	BSS_2040_COEXIST_IE		LastBSSCoexist2040;
-	BSS_2040_COEXIST_IE		BSSCoexist2040;
-	TRIGGER_EVENT_TAB		TriggerEventTab;
-	UCHAR					ChannelListIdx;
-	// <====== 11n D3.0 =======================
-	BOOLEAN					bOverlapScanning;
-#endif // DOT11N_DRAFT3 //
-
-    BOOLEAN                 bHTProtect;
-    BOOLEAN                 bMIMOPSEnable;
-    BOOLEAN					bBADecline;
-	BOOLEAN					bDisableReordering;
-	BOOLEAN					bForty_Mhz_Intolerant;
-	BOOLEAN					bExtChannelSwitchAnnouncement;
-	BOOLEAN					bRcvBSSWidthTriggerEvents;
-	ULONG					LastRcvBSSWidthTriggerEventsTime;
-
-	UCHAR					TxBASize;
-#endif // DOT11_N_SUPPORT //
-
-	// Enable wireless event
-	BOOLEAN				bWirelessEvent;
-	BOOLEAN				bWiFiTest;				// Enable this parameter for WiFi test
-
-	// Tx & Rx Stream number selection
-	UCHAR				TxStream;
-	UCHAR				RxStream;
-
-	// transmit phy mode, trasmit rate for Multicast.
-#ifdef MCAST_RATE_SPECIFIC
-	UCHAR				McastTransmitMcs;
-	UCHAR				McastTransmitPhyMode;
-#endif // MCAST_RATE_SPECIFIC //
-
-	BOOLEAN     		bHardwareRadio;     // Hardware controlled Radio enabled
-
-#ifdef RT2870
-	BOOLEAN     		bMultipleIRP;       // Multiple Bulk IN flag
-	UCHAR       		NumOfBulkInIRP;     // if bMultipleIRP == TRUE, NumOfBulkInIRP will be 4 otherwise be 1
- 	RT_HT_CAPABILITY	SupportedHtPhy;
-	ULONG				MaxPktOneTxBulk;
-	UCHAR				TxBulkFactor;
-	UCHAR				RxBulkFactor;
-
-	BEACON_SYNC_STRUCT	*pBeaconSync;
-	RALINK_TIMER_STRUCT	BeaconUpdateTimer;
-	UINT32				BeaconAdjust;
-	UINT32				BeaconFactor;
-	UINT32				BeaconRemain;
-#endif // RT2870 //
-
-
- 	NDIS_SPIN_LOCK			MeasureReqTabLock;
-	PMEASURE_REQ_TAB		pMeasureReqTab;
-
-	NDIS_SPIN_LOCK			TpcReqTabLock;
-	PTPC_REQ_TAB			pTpcReqTab;
-
-	// transmit phy mode, trasmit rate for Multicast.
-#ifdef MCAST_RATE_SPECIFIC
-	HTTRANSMIT_SETTING		MCastPhyMode;
-#endif // MCAST_RATE_SPECIFIC //
-
-#ifdef SINGLE_SKU
-	UINT16					DefineMaxTxPwr;
-#endif // SINGLE_SKU //
-
-
-} COMMON_CONFIG, *PCOMMON_CONFIG;
-
-
-#ifdef CONFIG_STA_SUPPORT
-/* Modified by Wu Xi-Kun 4/21/2006 */
-// STA configuration and status
-typedef struct _STA_ADMIN_CONFIG {
-	// GROUP 1 -
-	//   User configuration loaded from Registry, E2PROM or OID_xxx. These settings describe
-	//   the user intended configuration, but not necessary fully equal to the final
-	//   settings in ACTIVE BSS after negotiation/compromize with the BSS holder (either
-	//   AP or IBSS holder).
-	//   Once initialized, user configuration can only be changed via OID_xxx
-	UCHAR       BssType;              // BSS_INFRA or BSS_ADHOC
-	USHORT      AtimWin;          // used when starting a new IBSS
-
-	// GROUP 2 -
-	//   User configuration loaded from Registry, E2PROM or OID_xxx. These settings describe
-	//   the user intended configuration, and should be always applied to the final
-	//   settings in ACTIVE BSS without compromising with the BSS holder.
-	//   Once initialized, user configuration can only be changed via OID_xxx
-	UCHAR       RssiTrigger;
-	UCHAR       RssiTriggerMode;      // RSSI_TRIGGERED_UPON_BELOW_THRESHOLD or RSSI_TRIGGERED_UPON_EXCCEED_THRESHOLD
-	USHORT      DefaultListenCount;   // default listen count;
-	ULONG       WindowsPowerMode;           // Power mode for AC power
-	ULONG       WindowsBatteryPowerMode;    // Power mode for battery if exists
-	BOOLEAN     bWindowsACCAMEnable;        // Enable CAM power mode when AC on
-	BOOLEAN     bAutoReconnect;         // Set to TRUE when setting OID_802_11_SSID with no matching BSSID
-	ULONG       WindowsPowerProfile;    // Windows power profile, for NDIS5.1 PnP
-
-	// MIB:ieee802dot11.dot11smt(1).dot11StationConfigTable(1)
-	USHORT      Psm;                  // power management mode   (PWR_ACTIVE|PWR_SAVE)
-	USHORT      DisassocReason;
-	UCHAR       DisassocSta[MAC_ADDR_LEN];
-	USHORT      DeauthReason;
-	UCHAR       DeauthSta[MAC_ADDR_LEN];
-	USHORT      AuthFailReason;
-	UCHAR       AuthFailSta[MAC_ADDR_LEN];
-
-	NDIS_802_11_PRIVACY_FILTER          PrivacyFilter;  // PrivacyFilter enum for 802.1X
-	NDIS_802_11_AUTHENTICATION_MODE     AuthMode;       // This should match to whatever microsoft defined
-	NDIS_802_11_WEP_STATUS              WepStatus;
-	NDIS_802_11_WEP_STATUS				OrigWepStatus;	// Original wep status set from OID
-
-	// Add to support different cipher suite for WPA2/WPA mode
-	NDIS_802_11_ENCRYPTION_STATUS		GroupCipher;		// Multicast cipher suite
-	NDIS_802_11_ENCRYPTION_STATUS		PairCipher;			// Unicast cipher suite
-	BOOLEAN								bMixCipher;			// Indicate current Pair & Group use different cipher suites
-	USHORT								RsnCapability;
-
-	NDIS_802_11_WEP_STATUS              GroupKeyWepStatus;
-
-	UCHAR		PMK[32];                // WPA PSK mode PMK
-	UCHAR       PTK[64];                // WPA PSK mode PTK
-	UCHAR		GTK[32];				// GTK from authenticator
-	BSSID_INFO	SavedPMK[PMKID_NO];
-	UINT		SavedPMKNum;			// Saved PMKID number
-
-	UCHAR		DefaultKeyId;
-
-
-	// WPA 802.1x port control, WPA_802_1X_PORT_SECURED, WPA_802_1X_PORT_NOT_SECURED
-	UCHAR       PortSecured;
-
-	// For WPA countermeasures
-	ULONG       LastMicErrorTime;   // record last MIC error time
-	ULONG       MicErrCnt;          // Should be 0, 1, 2, then reset to zero (after disassoiciation).
-	BOOLEAN     bBlockAssoc;        // Block associate attempt for 60 seconds after counter measure occurred.
-	// For WPA-PSK supplicant state
-	WPA_STATE   WpaState;           // Default is SS_NOTUSE and handled by microsoft 802.1x
-	UCHAR       ReplayCounter[8];
-	UCHAR       ANonce[32];         // ANonce for WPA-PSK from aurhenticator
-	UCHAR       SNonce[32];         // SNonce for WPA-PSK
-
-	UCHAR       LastSNR0;             // last received BEACON's SNR
-	UCHAR       LastSNR1;            // last received BEACON's SNR for 2nd  antenna
-	RSSI_SAMPLE RssiSample;
-	ULONG       NumOfAvgRssiSample;
-
-	ULONG       LastBeaconRxTime;     // OS's timestamp of the last BEACON RX time
-	ULONG       Last11bBeaconRxTime;  // OS's timestamp of the last 11B BEACON RX time
-	ULONG		Last11gBeaconRxTime;	// OS's timestamp of the last 11G BEACON RX time
-	ULONG		Last20NBeaconRxTime;	// OS's timestamp of the last 20MHz N BEACON RX time
-
-	ULONG       LastScanTime;       // Record last scan time for issue BSSID_SCAN_LIST
-	ULONG       ScanCnt;            // Scan counts since most recent SSID, BSSID, SCAN OID request
-	BOOLEAN     bSwRadio;           // Software controlled Radio On/Off, TRUE: On
-	BOOLEAN     bHwRadio;           // Hardware controlled Radio On/Off, TRUE: On
-	BOOLEAN     bRadio;             // Radio state, And of Sw & Hw radio state
-	BOOLEAN     bHardwareRadio;     // Hardware controlled Radio enabled
-	BOOLEAN     bShowHiddenSSID;    // Show all known SSID in SSID list get operation
-
-
-	// New for WPA, windows want us to to keep association information and
-	// Fixed IEs from last association response
-	NDIS_802_11_ASSOCIATION_INFORMATION     AssocInfo;
-	USHORT       ReqVarIELen;                // Length of next VIE include EID & Length
-	UCHAR       ReqVarIEs[MAX_VIE_LEN];		// The content saved here should be little-endian format.
-	USHORT       ResVarIELen;                // Length of next VIE include EID & Length
-	UCHAR       ResVarIEs[MAX_VIE_LEN];
-
-	UCHAR       RSNIE_Len;
-	UCHAR       RSN_IE[MAX_LEN_OF_RSNIE];	// The content saved here should be little-endian format.
-
-	// New variables used for CCX 1.0
-	BOOLEAN             bCkipOn;
-	BOOLEAN             bCkipCmicOn;
-	UCHAR               CkipFlag;
-	UCHAR               GIV[3];  //for CCX iv
-	UCHAR               RxSEQ[4];
-	UCHAR               TxSEQ[4];
-	UCHAR               CKIPMIC[4];
-	UCHAR               LeapAuthMode;
-	LEAP_AUTH_INFO      LeapAuthInfo;
-	UCHAR               HashPwd[16];
-	UCHAR               NetworkChallenge[8];
-	UCHAR               NetworkChallengeResponse[24];
-	UCHAR               PeerChallenge[8];
-
-	UCHAR               PeerChallengeResponse[24];
-	UCHAR               SessionKey[16]; //Network session keys (NSK)
-	RALINK_TIMER_STRUCT LeapAuthTimer;
-	ROGUEAP_TABLE       RogueApTab;   //Cisco CCX1 Rogue AP Detection
-
-	// New control flags for CCX
-	CCX_CONTROL         CCXControl;                 // Master administration state
-	BOOLEAN             CCXEnable;                  // Actual CCX state
-	UCHAR               CCXScanChannel;             // Selected channel for CCX beacon request
-	USHORT              CCXScanTime;                // Time out to wait for beacon and probe response
-	UCHAR               CCXReqType;                 // Current processing CCX request type
-	BSS_TABLE           CCXBssTab;                  // BSS Table
-	UCHAR               FrameReportBuf[2048];       // Buffer for creating frame report
-	USHORT              FrameReportLen;             // Current Frame report length
-	ULONG               CLBusyBytes;                // Save the total bytes received durning channel load scan time
-	USHORT              RPIDensity[8];              // Array for RPI density collection
-	// Start address of each BSS table within FrameReportBuf
-	// It's important to update the RxPower of the corresponding Bss
-	USHORT              BssReportOffset[MAX_LEN_OF_BSS_TABLE];
-	USHORT              BeaconToken;                // Token for beacon report
-	ULONG               LastBssIndex;               // Most current reported Bss index
-	RM_REQUEST_ACTION   MeasurementRequest[16];     // Saved measurement request
-	UCHAR               RMReqCnt;                   // Number of measurement request saved.
-	UCHAR               CurrentRMReqIdx;            // Number of measurement request saved.
-	BOOLEAN             ParallelReq;                // Parallel measurement, only one request performed,
-													// It must be the same channel with maximum duration
-	USHORT              ParallelDuration;           // Maximum duration for parallel measurement
-	UCHAR               ParallelChannel;            // Only one channel with parallel measurement
-	USHORT              IAPPToken;                  // IAPP dialog token
-	UCHAR               CCXQosECWMin;               // Cisco QOS ECWMin for AC 0
-	UCHAR               CCXQosECWMax;               // Cisco QOS ECWMax for AC 0
-	// Hack for channel load and noise histogram parameters
-	UCHAR               NHFactor;                   // Parameter for Noise histogram
-	UCHAR               CLFactor;                   // Parameter for channel load
-
-	UCHAR               KRK[16];        //Key Refresh Key.
-	UCHAR               BTK[32];        //Base Transient Key
-	BOOLEAN             CCKMLinkUpFlag;
-	ULONG               CCKMRN;    //(Re)Association request number.
-	LARGE_INTEGER       CCKMBeaconAtJoinTimeStamp;  //TSF timer for Re-assocaite to the new AP
-	UCHAR               AironetCellPowerLimit;      //in dBm
-	UCHAR               AironetIPAddress[4];        //eg. 192.168.1.1
-	BOOLEAN             CCXAdjacentAPReportFlag;    //flag for determining report Assoc Lost time
-	CHAR                CCXAdjacentAPSsid[MAX_LEN_OF_SSID]; //Adjacent AP's SSID report
-	UCHAR               CCXAdjacentAPSsidLen;               // the actual ssid length in used
-	UCHAR               CCXAdjacentAPBssid[MAC_ADDR_LEN];         //Adjacent AP's BSSID report
-	USHORT              CCXAdjacentAPChannel;
-	ULONG               CCXAdjacentAPLinkDownTime;  //for Spec S32.
-
-	RALINK_TIMER_STRUCT	StaQuickResponeForRateUpTimer;
-	BOOLEAN				StaQuickResponeForRateUpTimerRunning;
-
-	UCHAR           	DtimCount;      // 0.. DtimPeriod-1
-	UCHAR           	DtimPeriod;     // default = 3
-
-#ifdef QOS_DLS_SUPPORT
-	RT_802_11_DLS		DLSEntry[MAX_NUM_OF_DLS_ENTRY];
-	UCHAR				DlsReplayCounter[8];
-#endif // QOS_DLS_SUPPORT //
-	////////////////////////////////////////////////////////////////////////////////////////
-	// This is only for WHQL test.
-	BOOLEAN				WhqlTest;
-	////////////////////////////////////////////////////////////////////////////////////////
-
-    RALINK_TIMER_STRUCT WpaDisassocAndBlockAssocTimer;
-    // Fast Roaming
-	BOOLEAN		        bFastRoaming;       // 0:disable fast roaming, 1:enable fast roaming
-	CHAR		        dBmToRoam;          // the condition to roam when receiving Rssi less than this value. It's negative value.
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-    BOOLEAN             IEEE8021X;
-    BOOLEAN             IEEE8021x_required_keys;
-    CIPHER_KEY	        DesireSharedKey[4];	// Record user desired WEP keys
-    UCHAR               DesireSharedKeyId;
-
-    // 0: driver ignores wpa_supplicant
-    // 1: wpa_supplicant initiates scanning and AP selection
-    // 2: driver takes care of scanning, AP selection, and IEEE 802.11 association parameters
-    UCHAR               WpaSupplicantUP;
-	UCHAR				WpaSupplicantScanCount;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-    CHAR                dev_name[16];
-    USHORT              OriDevType;
-
-    BOOLEAN             bTGnWifiTest;
-	BOOLEAN			    bScanReqIsFromWebUI;
-
-	HTTRANSMIT_SETTING				HTPhyMode, MaxHTPhyMode, MinHTPhyMode;// For transmit phy setting in TXWI.
-	DESIRED_TRANSMIT_SETTING       	DesiredTransmitSetting;
-	RT_HT_PHY_INFO					DesiredHtPhyInfo;
-	BOOLEAN							bAutoTxRateSwitch;
-
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-	UCHAR				IEEE80211dClientMode;
-	UCHAR				StaOriCountryCode[3];
-	UCHAR				StaOriGeography;
-#endif // EXT_BUILD_CHANNEL_LIST //
-} STA_ADMIN_CONFIG, *PSTA_ADMIN_CONFIG;
-
-// This data structure keep the current active BSS/IBSS's configuration that this STA
-// had agreed upon joining the network. Which means these parameters are usually decided
-// by the BSS/IBSS creator instead of user configuration. Data in this data structurre
-// is valid only when either ADHOC_ON(pAd) or INFRA_ON(pAd) is TRUE.
-// Normally, after SCAN or failed roaming attempts, we need to recover back to
-// the current active settings.
-typedef struct _STA_ACTIVE_CONFIG {
-	USHORT      Aid;
-	USHORT      AtimWin;                // in kusec; IBSS parameter set element
-	USHORT      CapabilityInfo;
-	USHORT      CfpMaxDuration;
-	USHORT      CfpPeriod;
-
-	// Copy supported rate from desired AP's beacon. We are trying to match
-	// AP's supported and extended rate settings.
-	UCHAR       SupRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR       ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR       SupRateLen;
-	UCHAR       ExtRateLen;
-	// Copy supported ht from desired AP's beacon. We are trying to match
-	RT_HT_PHY_INFO		SupportedPhyInfo;
-	RT_HT_CAPABILITY	SupportedHtPhy;
-} STA_ACTIVE_CONFIG, *PSTA_ACTIVE_CONFIG;
-
-#ifdef RT2870
-// for USB interface, avoid in interrupt when write key
-typedef struct   RT_ADD_PAIRWISE_KEY_ENTRY {
-        NDIS_802_11_MAC_ADDRESS         MacAddr;
-        USHORT                          MacTabMatchWCID;        // ASIC
-        CIPHER_KEY                      CipherKey;
-} RT_ADD_PAIRWISE_KEY_ENTRY,*PRT_ADD_PAIRWISE_KEY_ENTRY;
-#endif // RT2870 //
-#endif // CONFIG_STA_SUPPORT //
-
-// ----------- start of AP --------------------------
-// AUTH-RSP State Machine Aux data structure
-typedef struct _AP_MLME_AUX {
-	UCHAR               Addr[MAC_ADDR_LEN];
-	USHORT              Alg;
-	CHAR                Challenge[CIPHER_TEXT_LEN];
-} AP_MLME_AUX, *PAP_MLME_AUX;
-
-// structure to define WPA Group Key Rekey Interval
-typedef struct PACKED _RT_802_11_WPA_REKEY {
-	ULONG ReKeyMethod;          // mechanism for rekeying: 0:disable, 1: time-based, 2: packet-based
-	ULONG ReKeyInterval;        // time-based: seconds, packet-based: kilo-packets
-} RT_WPA_REKEY,*PRT_WPA_REKEY, RT_802_11_WPA_REKEY, *PRT_802_11_WPA_REKEY;
-
-typedef struct _MAC_TABLE_ENTRY {
-	//Choose 1 from ValidAsWDS and ValidAsCLI  to validize.
-	BOOLEAN		ValidAsCLI;		// Sta mode, set this TRUE after Linkup,too.
-	BOOLEAN		ValidAsWDS;	// This is WDS Entry. only for AP mode.
-	BOOLEAN		ValidAsApCli;   //This is a AP-Client entry, only for AP mode which enable AP-Client functions.
-	BOOLEAN		ValidAsMesh;
-	BOOLEAN		ValidAsDls;	// This is DLS Entry. only for STA mode.
-	BOOLEAN		isCached;
-	BOOLEAN		bIAmBadAtheros;	// Flag if this is Atheros chip that has IOT problem.  We need to turn on RTS/CTS protection.
-
-	UCHAR         	EnqueueEapolStartTimerRunning;  // Enqueue EAPoL-Start for triggering EAP SM
-	//jan for wpa
-	// record which entry revoke MIC Failure , if it leaves the BSS itself, AP won't update aMICFailTime MIB
-	UCHAR           CMTimerRunning;
-	UCHAR           apidx;			// MBSS number
-	UCHAR           RSNIE_Len;
-	UCHAR           RSN_IE[MAX_LEN_OF_RSNIE];
-	UCHAR           ANonce[LEN_KEY_DESC_NONCE];
-	UCHAR           R_Counter[LEN_KEY_DESC_REPLAY];
-	UCHAR           PTK[64];
-	UCHAR           ReTryCounter;
-	RALINK_TIMER_STRUCT                 RetryTimer;
-	RALINK_TIMER_STRUCT					EnqueueStartForPSKTimer;	// A timer which enqueue EAPoL-Start for triggering PSK SM
-	NDIS_802_11_AUTHENTICATION_MODE     AuthMode;   // This should match to whatever microsoft defined
-	NDIS_802_11_WEP_STATUS              WepStatus;
-	AP_WPA_STATE    WpaState;
-	GTK_STATE       GTKState;
-	USHORT          PortSecured;
-	NDIS_802_11_PRIVACY_FILTER  PrivacyFilter;      // PrivacyFilter enum for 802.1X
-	CIPHER_KEY      PairwiseKey;
-	PVOID           pAd;
-    INT				PMKID_CacheIdx;
-    UCHAR			PMKID[LEN_PMKID];
-
-
-	UCHAR           Addr[MAC_ADDR_LEN];
-	UCHAR           PsMode;
-	SST             Sst;
-	AUTH_STATE      AuthState; // for SHARED KEY authentication state machine used only
-	BOOLEAN			IsReassocSta;	// Indicate whether this is a reassociation procedure
-	USHORT          Aid;
-	USHORT          CapabilityInfo;
-	UCHAR           LastRssi;
-	ULONG           NoDataIdleCount;
-	UINT16			StationKeepAliveCount; // unit: second
-	ULONG           PsQIdleCount;
-	QUEUE_HEADER    PsQueue;
-
-	UINT32			StaConnectTime;		// the live time of this station since associated with AP
-
-
-#ifdef DOT11_N_SUPPORT
-	BOOLEAN			bSendBAR;
-	USHORT			NoBADataCountDown;
-
-	UINT32   		CachedBuf[16];		// UINT (4 bytes) for alignment
-	UINT			TxBFCount; // 3*3
-#endif // DOT11_N_SUPPORT //
-	UINT			FIFOCount;
-	UINT			DebugFIFOCount;
-	UINT			DebugTxCount;
-    BOOLEAN			bDlsInit;
-
-
-//====================================================
-//WDS entry needs these
-// rt2860 add this. if ValidAsWDS==TRUE, MatchWDSTabIdx is the index in WdsTab.MacTab
-	UINT			MatchWDSTabIdx;
-	UCHAR           MaxSupportedRate;
-	UCHAR           CurrTxRate;
-	UCHAR           CurrTxRateIndex;
-	// to record the each TX rate's quality. 0 is best, the bigger the worse.
-	USHORT          TxQuality[MAX_STEP_OF_TX_RATE_SWITCH];
-//	USHORT          OneSecTxOkCount;
-	UINT32			OneSecTxNoRetryOkCount;
-	UINT32          OneSecTxRetryOkCount;
-	UINT32          OneSecTxFailCount;
-	UINT32			ContinueTxFailCnt;
-	UINT32          CurrTxRateStableTime; // # of second in current TX rate
-	UCHAR           TxRateUpPenalty;      // extra # of second penalty due to last unstable condition
-//====================================================
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-	UINT			MatchDlsEntryIdx; // indicate the index in pAd->StaCfg.DLSEntry
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-	BOOLEAN         fNoisyEnvironment;
-	BOOLEAN			fLastSecAccordingRSSI;
-	UCHAR           LastSecTxRateChangeAction; // 0: no change, 1:rate UP, 2:rate down
-	CHAR			LastTimeTxRateChangeAction; //Keep last time value of LastSecTxRateChangeAction
-	ULONG			LastTxOkCount;
-	UCHAR           PER[MAX_STEP_OF_TX_RATE_SWITCH];
-
-	// a bitmap of BOOLEAN flags. each bit represent an operation status of a particular
-	// BOOLEAN control, either ON or OFF. These flags should always be accessed via
-	// CLIENT_STATUS_TEST_FLAG(), CLIENT_STATUS_SET_FLAG(), CLIENT_STATUS_CLEAR_FLAG() macros.
-	// see fOP_STATUS_xxx in RTMP_DEF.C for detail bit definition. fCLIENT_STATUS_AMSDU_INUSED
-	ULONG           ClientStatusFlags;
-
-	// TODO: Shall we move that to DOT11_N_SUPPORT???
-	HTTRANSMIT_SETTING	HTPhyMode, MaxHTPhyMode, MinHTPhyMode;// For transmit phy setting in TXWI.
-
-#ifdef DOT11_N_SUPPORT
-	// HT EWC MIMO-N used parameters
-	USHORT		RXBAbitmap;	// fill to on-chip  RXWI_BA_BITMASK in 8.1.3RX attribute entry format
-	USHORT		TXBAbitmap;	// This bitmap as originator, only keep in software used to mark AMPDU bit in TXWI
-	USHORT		TXAutoBAbitmap;
-	USHORT		BADeclineBitmap;
-	USHORT		BARecWcidArray[NUM_OF_TID];	// The mapping wcid of recipient session. if RXBAbitmap bit is masked
-	USHORT		BAOriWcidArray[NUM_OF_TID]; // The mapping wcid of originator session. if TXBAbitmap bit is masked
-	USHORT		BAOriSequence[NUM_OF_TID]; // The mapping wcid of originator session. if TXBAbitmap bit is masked
-
-	// 802.11n features.
-	UCHAR		MpduDensity;
-	UCHAR		MaxRAmpduFactor;
-	UCHAR		AMsduSize;
-	UCHAR		MmpsMode;	// MIMO power save more.
-
-	HT_CAPABILITY_IE		HTCapability;
-
-#ifdef DOT11N_DRAFT3
-	UCHAR		BSS2040CoexistenceMgmtSupport;
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-	BOOLEAN		bAutoTxRateSwitch;
-
-	UCHAR       RateLen;
-	struct _MAC_TABLE_ENTRY *pNext;
-    USHORT      TxSeq[NUM_OF_TID];
-	USHORT		NonQosDataSeq;
-
-	RSSI_SAMPLE	RssiSample;
-
-	UINT32			TXMCSExpected[16];
-	UINT32			TXMCSSuccessful[16];
-	UINT32			TXMCSFailed[16];
-	UINT32			TXMCSAutoFallBack[16][16];
-
-#ifdef CONFIG_STA_SUPPORT
-	ULONG   		LastBeaconRxTime;
-#endif // CONFIG_STA_SUPPORT //
-} MAC_TABLE_ENTRY, *PMAC_TABLE_ENTRY;
-
-typedef struct _MAC_TABLE {
-	USHORT			Size;
-	MAC_TABLE_ENTRY *Hash[HASH_TABLE_SIZE];
-	MAC_TABLE_ENTRY Content[MAX_LEN_OF_MAC_TABLE];
-	QUEUE_HEADER    McastPsQueue;
-	ULONG           PsQIdleCount;
-	BOOLEAN         fAnyStationInPsm;
-	BOOLEAN         fAnyStationBadAtheros;	// Check if any Station is atheros 802.11n Chip.  We need to use RTS/CTS with Atheros 802,.11n chip.
-	BOOLEAN			fAnyTxOPForceDisable;	// Check if it is necessary to disable BE TxOP
-	BOOLEAN			fAllStationAsRalink; 	// Check if all stations are ralink-chipset
-#ifdef DOT11_N_SUPPORT
-	BOOLEAN         fAnyStationIsLegacy;	// Check if I use legacy rate to transmit to my BSS Station/
-	BOOLEAN         fAnyStationNonGF;		// Check if any Station can't support GF.
-	BOOLEAN         fAnyStation20Only;		// Check if any Station can't support GF.
-	BOOLEAN			fAnyStationMIMOPSDynamic; // Check if any Station is MIMO Dynamic
-	BOOLEAN         fAnyBASession;   // Check if there is BA session.  Force turn on RTS/CTS
-#endif // DOT11_N_SUPPORT //
-} MAC_TABLE, *PMAC_TABLE;
-
-#ifdef DOT11_N_SUPPORT
-#define IS_HT_STA(_pMacEntry)	\
-	(_pMacEntry->MaxHTPhyMode.field.MODE >= MODE_HTMIX)
-
-#define IS_HT_RATE(_pMacEntry)	\
-	(_pMacEntry->HTPhyMode.field.MODE >= MODE_HTMIX)
-
-#define PEER_IS_HT_RATE(_pMacEntry)	\
-	(_pMacEntry->HTPhyMode.field.MODE >= MODE_HTMIX)
-#endif // DOT11_N_SUPPORT //
-
-typedef struct _WDS_ENTRY {
-	BOOLEAN         Valid;
-	UCHAR           Addr[MAC_ADDR_LEN];
-	ULONG           NoDataIdleCount;
-	struct _WDS_ENTRY *pNext;
-} WDS_ENTRY, *PWDS_ENTRY;
-
-typedef struct  _WDS_TABLE_ENTRY {
-	USHORT			Size;
-	UCHAR           WdsAddr[MAC_ADDR_LEN];
-	WDS_ENTRY       *Hash[HASH_TABLE_SIZE];
-	WDS_ENTRY       Content[MAX_LEN_OF_MAC_TABLE];
-	UCHAR           MaxSupportedRate;
-	UCHAR           CurrTxRate;
-	USHORT          TxQuality[MAX_LEN_OF_SUPPORTED_RATES];
-	USHORT          OneSecTxOkCount;
-	USHORT          OneSecTxRetryOkCount;
-	USHORT          OneSecTxFailCount;
-	ULONG           CurrTxRateStableTime; // # of second in current TX rate
-	UCHAR           TxRateUpPenalty;      // extra # of second penalty due to last unstable condition
-} WDS_TABLE_ENTRY, *PWDS_TABLE_ENTRY;
-
-typedef struct _RT_802_11_WDS_ENTRY {
-	PNET_DEV			dev;
-	UCHAR				Valid;
-	UCHAR				PhyMode;
-	UCHAR				PeerWdsAddr[MAC_ADDR_LEN];
-	UCHAR				MacTabMatchWCID;	// ASIC
-	NDIS_802_11_WEP_STATUS  WepStatus;
-	UCHAR					KeyIdx;
-	CIPHER_KEY          	WdsKey;
-	HTTRANSMIT_SETTING				HTPhyMode, MaxHTPhyMode, MinHTPhyMode;
-	RT_HT_PHY_INFO					DesiredHtPhyInfo;
-	BOOLEAN							bAutoTxRateSwitch;
-	DESIRED_TRANSMIT_SETTING       	DesiredTransmitSetting; // Desired transmit setting.
-} RT_802_11_WDS_ENTRY, *PRT_802_11_WDS_ENTRY;
-
-typedef struct _WDS_TABLE {
-	UCHAR               Mode;
-	ULONG               Size;
-	RT_802_11_WDS_ENTRY	WdsEntry[MAX_WDS_ENTRY];
-} WDS_TABLE, *PWDS_TABLE;
-
-typedef struct _APCLI_STRUCT {
-	PNET_DEV				dev;
-#ifdef RTL865X_SOC
-	unsigned int            mylinkid;
-#endif
-	BOOLEAN                 Enable;	// Set it as 1 if the apcli interface was configured to "1"  or by iwpriv cmd "ApCliEnable"
-	BOOLEAN                 Valid;	// Set it as 1 if the apcli interface associated success to remote AP.
-	UCHAR					MacTabWCID;	//WCID value, which point to the entry of ASIC Mac table.
-	UCHAR                   SsidLen;
-	CHAR                    Ssid[MAX_LEN_OF_SSID];
-
-	UCHAR                   CfgSsidLen;
-	CHAR                    CfgSsid[MAX_LEN_OF_SSID];
-	UCHAR                   CfgApCliBssid[ETH_LENGTH_OF_ADDRESS];
-	UCHAR                   CurrentAddress[ETH_LENGTH_OF_ADDRESS];
-
-	ULONG                   ApCliRcvBeaconTime;
-
-	ULONG                   CtrlCurrState;
-	ULONG                   SyncCurrState;
-	ULONG                   AuthCurrState;
-	ULONG                   AssocCurrState;
-	ULONG					WpaPskCurrState;
-
-	USHORT                  AuthReqCnt;
-	USHORT                  AssocReqCnt;
-
-	ULONG                   ClientStatusFlags;
-	UCHAR                   MpduDensity;
-
-	NDIS_802_11_AUTHENTICATION_MODE     AuthMode;   // This should match to whatever microsoft defined
-	NDIS_802_11_WEP_STATUS              WepStatus;
-
-	// Add to support different cipher suite for WPA2/WPA mode
-	NDIS_802_11_ENCRYPTION_STATUS		GroupCipher;		// Multicast cipher suite
-	NDIS_802_11_ENCRYPTION_STATUS		PairCipher;			// Unicast cipher suite
-	BOOLEAN								bMixCipher;			// Indicate current Pair & Group use different cipher suites
-	USHORT								RsnCapability;
-
-	UCHAR		PSK[100];				// reserve PSK key material
-	UCHAR       PSKLen;
-	UCHAR       PMK[32];                // WPA PSK mode PMK
-	//UCHAR       PTK[64];                // WPA PSK mode PTK
-	UCHAR		GTK[32];				// GTK from authenticator
-
-	//CIPHER_KEY		PairwiseKey;
-	CIPHER_KEY      SharedKey[SHARE_KEY_NUM];
-	UCHAR           DefaultKeyId;
-
-	// WPA 802.1x port control, WPA_802_1X_PORT_SECURED, WPA_802_1X_PORT_NOT_SECURED
-	//UCHAR       PortSecured;
-
-	// store RSN_IE built by driver
-	UCHAR		RSN_IE[MAX_LEN_OF_RSNIE];  // The content saved here should be convert to little-endian format.
-	UCHAR		RSNIE_Len;
-
-	// For WPA countermeasures
-	ULONG       LastMicErrorTime;   // record last MIC error time
-	//ULONG       MicErrCnt;          // Should be 0, 1, 2, then reset to zero (after disassoiciation).
-	BOOLEAN                 bBlockAssoc; // Block associate attempt for 60 seconds after counter measure occurred.
-
-	// For WPA-PSK supplicant state
-	//WPA_STATE   	WpaState;           // Default is SS_NOTUSE
-	//UCHAR       	ReplayCounter[8];
-	//UCHAR       	ANonce[32];         // ANonce for WPA-PSK from authenticator
-	UCHAR       	SNonce[32];         // SNonce for WPA-PSK
-	UCHAR			GNonce[32];			// GNonce for WPA-PSK from authenticator
-
-	HTTRANSMIT_SETTING				HTPhyMode, MaxHTPhyMode, MinHTPhyMode;
-	RT_HT_PHY_INFO					DesiredHtPhyInfo;
-	BOOLEAN							bAutoTxRateSwitch;
-	DESIRED_TRANSMIT_SETTING       	DesiredTransmitSetting; // Desired transmit setting.
-} APCLI_STRUCT, *PAPCLI_STRUCT;
-
-// ----------- end of AP ----------------------------
-
-#ifdef BLOCK_NET_IF
-typedef struct _BLOCK_QUEUE_ENTRY
-{
-	BOOLEAN SwTxQueueBlockFlag;
-	LIST_HEADER NetIfList;
-} BLOCK_QUEUE_ENTRY, *PBLOCK_QUEUE_ENTRY;
-#endif // BLOCK_NET_IF //
-
-struct wificonf
-{
-	BOOLEAN	bShortGI;
-	BOOLEAN bGreenField;
-};
-
-
-
-typedef struct _INF_PCI_CONFIG
-{
-	PUCHAR                  CSRBaseAddress;     // PCI MMIO Base Address, all access will use
-}INF_PCI_CONFIG;
-
-typedef struct _INF_USB_CONFIG
-{
-	UINT                BulkInEpAddr;		// bulk-in endpoint address
-	UINT                BulkOutEpAddr[6];	// bulk-out endpoint address
-
-}INF_USB_CONFIG;
-
-#ifdef IKANOS_VX_1X0
-	typedef void (*IkanosWlanTxCbFuncP)(void *, void *);
-
-	struct IKANOS_TX_INFO
-	{
-		struct net_device *netdev;
-		IkanosWlanTxCbFuncP *fp;
-	};
-#endif // IKANOS_VX_1X0 //
-
-#ifdef NINTENDO_AP
-typedef struct _NINDO_CTRL_BLOCK {
-
-	RT_NINTENDO_TABLE	DS_TABLE;
-
-#ifdef CHIP25XX
-	spinlock_t			NINTENDO_TABLE_Lock;
-#else
-	NDIS_SPIN_LOCK		NINTENDO_TABLE_Lock;
-#endif // CHIP25XX //
-
-	UCHAR				NINTENDO_UP_BUFFER[512];
-	UCHAR				Local_KeyIdx;
-	CIPHER_KEY			Local_SharedKey;
-	UCHAR				Local_bHideSsid;
-	UCHAR				Local_AuthMode;
-	UCHAR				Local_WepStatus;
-	USHORT				Local_CapabilityInfo;
-} NINDO_CTRL_BLOCK;
-#endif // NINTENDO_AP //
-
-
-#ifdef DBG_DIAGNOSE
-#define DIAGNOSE_TIME	10   // 10 sec
-typedef struct _RtmpDiagStrcut_
-{	// Diagnosis Related element
-	unsigned char		inited;
-	unsigned char 	qIdx;
-	unsigned char 	ArrayStartIdx;
-	unsigned char		ArrayCurIdx;
-	// Tx Related Count
-	USHORT			TxDataCnt[DIAGNOSE_TIME];
-	USHORT			TxFailCnt[DIAGNOSE_TIME];
-//	USHORT			TxDescCnt[DIAGNOSE_TIME][16];		// TxDesc queue length in scale of 0~14, >=15
-	USHORT			TxDescCnt[DIAGNOSE_TIME][24]; // 3*3	// TxDesc queue length in scale of 0~14, >=15
-//	USHORT			TxMcsCnt[DIAGNOSE_TIME][16];			// TxDate MCS Count in range from 0 to 15, step in 1.
-	USHORT			TxMcsCnt[DIAGNOSE_TIME][24]; // 3*3
-	USHORT			TxSWQueCnt[DIAGNOSE_TIME][9];		// TxSwQueue length in scale of 0, 1, 2, 3, 4, 5, 6, 7, >=8
-
-	USHORT			TxAggCnt[DIAGNOSE_TIME];
-	USHORT			TxNonAggCnt[DIAGNOSE_TIME];
-//	USHORT			TxAMPDUCnt[DIAGNOSE_TIME][16];		// 10 sec, TxDMA APMDU Aggregation count in range from 0 to 15, in setp of 1.
-	USHORT			TxAMPDUCnt[DIAGNOSE_TIME][24]; // 3*3 // 10 sec, TxDMA APMDU Aggregation count in range from 0 to 15, in setp of 1.
-	USHORT			TxRalinkCnt[DIAGNOSE_TIME];			// TxRalink Aggregation Count in 1 sec scale.
-	USHORT			TxAMSDUCnt[DIAGNOSE_TIME];			// TxAMSUD Aggregation Count in 1 sec scale.
-
-	// Rx Related Count
-	USHORT			RxDataCnt[DIAGNOSE_TIME];			// Rx Total Data count.
-	USHORT			RxCrcErrCnt[DIAGNOSE_TIME];
-//	USHORT			RxMcsCnt[DIAGNOSE_TIME][16];		// Rx MCS Count in range from 0 to 15, step in 1.
-	USHORT			RxMcsCnt[DIAGNOSE_TIME][24]; // 3*3
-}RtmpDiagStruct;
-#endif // DBG_DIAGNOSE //
-
-
-//
-//  The miniport adapter structure
-//
-typedef struct _RTMP_ADAPTER
-{
-	PVOID					OS_Cookie;	// save specific structure relative to OS
-	PNET_DEV				net_dev;
-	ULONG					VirtualIfCnt;
-
-
-
-	NDIS_SPIN_LOCK          irq_lock;
-	UCHAR                   irq_disabled;
-
-#ifdef RT2870
-/*****************************************************************************************/
-/*      USB related parameters                                                           */
-/*****************************************************************************************/
-	struct usb_config_descriptor		*config;
-	UINT								BulkInEpAddr;		// bulk-in endpoint address
-	UINT								BulkOutEpAddr[6];	// bulk-out endpoint address
-
-	UINT								NumberOfPipes;
-	USHORT								BulkOutMaxPacketSize;
-	USHORT								BulkInMaxPacketSize;
-
-	//======Control Flags
-	LONG                    	PendingIoCount;
-	ULONG						BulkFlags;
-	BOOLEAN                     bUsbTxBulkAggre;	// Flags for bulk out data priority
-
-
-	//======Timer Thread
-	RT2870_TIMER_QUEUE		TimerQ;
-	NDIS_SPIN_LOCK			TimerQLock;
-
-
-	//======Cmd Thread
-	CmdQ					CmdQ;
-	NDIS_SPIN_LOCK			CmdQLock;				// CmdQLock spinlock
-
-	BOOLEAN					TimerFunc_kill;
-	BOOLEAN					mlme_kill;
-
-
-	//======Semaphores (event)
-	struct semaphore			mlme_semaphore;			/* to sleep thread on	*/
-	struct semaphore			RTUSBCmd_semaphore;		/* to sleep thread on	*/
-	struct semaphore			RTUSBTimer_semaphore;
-#ifdef INF_AMAZON_SE
-	struct semaphore			UsbVendorReq_semaphore;
-	PVOID						UsbVendorReqBuf;
-#endif // INF_AMAZON_SE //
-	struct completion			TimerQComplete;
-	struct completion			mlmeComplete;
-	struct completion			CmdQComplete;
-	wait_queue_head_t			*wait;
-
-	//======Lock for 2870 ATE
-#ifdef RALINK_ATE
-	NDIS_SPIN_LOCK			GenericLock;		// ATE Tx/Rx generic spinlock
-#endif // RALINK_ATE //
-
-#endif // RT2870 //
-
-
-/*****************************************************************************************/
-	/*      Both PCI/USB related parameters                                                  */
-/*****************************************************************************************/
-
-
-/*****************************************************************************************/
-/*      Tx related parameters                                                           */
-/*****************************************************************************************/
-	BOOLEAN                 DeQueueRunning[NUM_OF_TX_RING];  // for ensuring RTUSBDeQueuePacket get call once
-	NDIS_SPIN_LOCK          DeQueueLock[NUM_OF_TX_RING];
-
-#ifdef RT2870
-	// Data related context and AC specified, 4 AC supported
-	NDIS_SPIN_LOCK			BulkOutLock[6];			// BulkOut spinlock for 4 ACs
-	NDIS_SPIN_LOCK			MLMEBulkOutLock;	// MLME BulkOut lock
-
-	HT_TX_CONTEXT			TxContext[NUM_OF_TX_RING];
-	NDIS_SPIN_LOCK			TxContextQueueLock[NUM_OF_TX_RING];		// TxContextQueue spinlock
-
-	// 4 sets of Bulk Out index and pending flag
-	UCHAR					NextBulkOutIndex[4];	// only used for 4 EDCA bulkout pipe
-
-	BOOLEAN					BulkOutPending[6];	// used for total 6 bulkout pipe
-	UCHAR					bulkResetPipeid;
-	BOOLEAN					MgmtBulkPending;
-	ULONG					bulkResetReq[6];
-#endif // RT2870 //
-
-	// resource for software backlog queues
-	QUEUE_HEADER            TxSwQueue[NUM_OF_TX_RING];  // 4 AC + 1 HCCA
-	NDIS_SPIN_LOCK          TxSwQueueLock[NUM_OF_TX_RING];	// TxSwQueue spinlock
-
-	RTMP_DMABUF             MgmtDescRing;               	// Shared memory for MGMT descriptors
-	RTMP_MGMT_RING          MgmtRing;
-	NDIS_SPIN_LOCK          MgmtRingLock;               	// Prio Ring spinlock
-
-
-/*****************************************************************************************/
-/*      Rx related parameters                                                           */
-/*****************************************************************************************/
-
-
-#ifdef RT2870
-	RX_CONTEXT				RxContext[RX_RING_SIZE];  // 1 for redundant multiple IRP bulk in.
-	NDIS_SPIN_LOCK			BulkInLock;				// BulkIn spinlock for 4 ACs
-	UCHAR					PendingRx;				// The Maxima pending Rx value should be 	RX_RING_SIZE.
-	UCHAR					NextRxBulkInIndex;		// Indicate the current RxContext Index which hold by Host controller.
-	UCHAR					NextRxBulkInReadIndex;	// Indicate the current RxContext Index which driver can read & process it.
-	ULONG					NextRxBulkInPosition;   // Want to contatenate 2 URB buffer while 1st is bulkin failed URB. This Position is 1st URB TransferLength.
-	ULONG					TransferBufferLength;	// current length of the packet buffer
-	ULONG					ReadPosition;			// current read position in a packet buffer
-#endif // RT2870 //
-
-
-/*****************************************************************************************/
-/*      ASIC related parameters                                                          */
-/*****************************************************************************************/
-	UINT32               	MACVersion;      	// MAC version. Record rt2860C(0x28600100) or rt2860D (0x28600101)..
-
-	// ---------------------------
-	// E2PROM
-	// ---------------------------
-	ULONG                   EepromVersion;          // byte 0: version, byte 1: revision, byte 2~3: unused
-	UCHAR                   EEPROMAddressNum;       // 93c46=6  93c66=8
-	USHORT                  EEPROMDefaultValue[NUM_EEPROM_BBP_PARMS];
-	ULONG                   FirmwareVersion;        // byte 0: Minor version, byte 1: Major version, otherwise unused.
-
-	// ---------------------------
-	// BBP Control
-	// ---------------------------
-	UCHAR                   BbpWriteLatch[140];     // record last BBP register value written via BBP_IO_WRITE/BBP_IO_WRITE_VY_REG_ID
-	UCHAR                   BbpRssiToDbmDelta;
-	BBP_R66_TUNING          BbpTuning;
-
-	// ----------------------------
-	// RFIC control
-	// ----------------------------
-	UCHAR                   RfIcType;       // RFIC_xxx
-	ULONG                   RfFreqOffset;   // Frequency offset for channel switching
-	RTMP_RF_REGS            LatchRfRegs;    // latch th latest RF programming value since RF IC doesn't support READ
-
-	EEPROM_ANTENNA_STRUC    Antenna;                            // Since ANtenna definition is different for a & g. We need to save it for future reference.
-	EEPROM_NIC_CONFIG2_STRUC    NicConfig2;
-
-	// This soft Rx Antenna Diversity mechanism is used only when user set
-	// RX Antenna = DIVERSITY ON
-	SOFT_RX_ANT_DIVERSITY   RxAnt;
-
-	UCHAR                   RFProgSeq;
-	CHANNEL_TX_POWER        TxPower[MAX_NUM_OF_CHANNELS];       // Store Tx power value for all channels.
-	CHANNEL_TX_POWER        ChannelList[MAX_NUM_OF_CHANNELS];   // list all supported channels for site survey
-	CHANNEL_11J_TX_POWER    TxPower11J[MAX_NUM_OF_11JCHANNELS];       // 802.11j channel and bw
-	CHANNEL_11J_TX_POWER    ChannelList11J[MAX_NUM_OF_11JCHANNELS];   // list all supported channels for site survey
-
-	UCHAR                   ChannelListNum;                     // number of channel in ChannelList[]
-	UCHAR					Bbp94;
-	BOOLEAN					BbpForCCK;
-	ULONG		Tx20MPwrCfgABand[5];
-	ULONG		Tx20MPwrCfgGBand[5];
-	ULONG		Tx40MPwrCfgABand[5];
-	ULONG		Tx40MPwrCfgGBand[5];
-
-	BOOLEAN     bAutoTxAgcA;                // Enable driver auto Tx Agc control
-	UCHAR	    TssiRefA;					// Store Tssi reference value as 25 temperature.
-	UCHAR	    TssiPlusBoundaryA[5];		// Tssi boundary for increase Tx power to compensate.
-	UCHAR	    TssiMinusBoundaryA[5];		// Tssi boundary for decrease Tx power to compensate.
-	UCHAR	    TxAgcStepA;					// Store Tx TSSI delta increment / decrement value
-	CHAR		TxAgcCompensateA;			// Store the compensation (TxAgcStep * (idx-1))
-
-	BOOLEAN     bAutoTxAgcG;                // Enable driver auto Tx Agc control
-	UCHAR	    TssiRefG;					// Store Tssi reference value as 25 temperature.
-	UCHAR	    TssiPlusBoundaryG[5];		// Tssi boundary for increase Tx power to compensate.
-	UCHAR	    TssiMinusBoundaryG[5];		// Tssi boundary for decrease Tx power to compensate.
-	UCHAR	    TxAgcStepG;					// Store Tx TSSI delta increment / decrement value
-	CHAR		TxAgcCompensateG;			// Store the compensation (TxAgcStep * (idx-1))
-
-	//+++For RT2870, the parameteres is start from BGRssiOffset1 ~ BGRssiOffset3
-	CHAR		BGRssiOffset0;				// Store B/G RSSI#0 Offset value on EEPROM 0x46h
-	CHAR		BGRssiOffset1;				// Store B/G RSSI#1 Offset value
-	CHAR		BGRssiOffset2;				// Store B/G RSSI#2 Offset value
-	//---
-
-	//+++For RT2870, the parameteres is start from ARssiOffset1 ~ ARssiOffset3
-	CHAR		ARssiOffset0;				// Store A RSSI#0 Offset value on EEPROM 0x4Ah
-	CHAR		ARssiOffset1;				// Store A RSSI#1 Offset value
-	CHAR		ARssiOffset2;				// Store A RSSI#2 Offset value
-	//---
-
-	CHAR		BLNAGain;					// Store B/G external LNA#0 value on EEPROM 0x44h
-	CHAR		ALNAGain0;					// Store A external LNA#0 value for ch36~64
-	CHAR		ALNAGain1;					// Store A external LNA#1 value for ch100~128
-	CHAR		ALNAGain2;					// Store A external LNA#2 value for ch132~165
-
-	// ----------------------------
-	// LED control
-	// ----------------------------
-	MCU_LEDCS_STRUC		LedCntl;
-	USHORT				Led1;	// read from EEPROM 0x3c
-	USHORT				Led2;	// EEPROM 0x3e
-	USHORT				Led3;	// EEPROM 0x40
-	UCHAR				LedIndicatorStregth;
-	UCHAR				RssiSingalstrengthOffet;
-    BOOLEAN				bLedOnScanning;
-	UCHAR				LedStatus;
-
-/*****************************************************************************************/
-/*      802.11 related parameters                                                        */
-/*****************************************************************************************/
-	// outgoing BEACON frame buffer and corresponding TXD
-	TXWI_STRUC              	BeaconTxWI;
-	PUCHAR						BeaconBuf;
-	USHORT						BeaconOffset[HW_BEACON_MAX_COUNT];
-
-	// pre-build PS-POLL and NULL frame upon link up. for efficiency purpose.
-	PSPOLL_FRAME            	PsPollFrame;
-	HEADER_802_11           	NullFrame;
-
-#ifdef RT2870
-	TX_CONTEXT				BeaconContext[BEACON_RING_SIZE];
-	TX_CONTEXT				NullContext;
-	TX_CONTEXT				PsPollContext;
-	TX_CONTEXT				RTSContext;
-#endif // RT2870 //
-
-
-
-//=========AP===========
-
-
-//=======STA===========
-#ifdef CONFIG_STA_SUPPORT
-/* Modified by Wu Xi-Kun 4/21/2006 */
-	// -----------------------------------------------
-	// STA specific configuration & operation status
-	// used only when pAd->OpMode == OPMODE_STA
-	// -----------------------------------------------
-	STA_ADMIN_CONFIG        StaCfg;           // user desired settings
-	STA_ACTIVE_CONFIG       StaActive;         // valid only when ADHOC_ON(pAd) || INFRA_ON(pAd)
-	CHAR                    nickname[IW_ESSID_MAX_SIZE+1]; // nickname, only used in the iwconfig i/f
-	NDIS_MEDIA_STATE        PreMediaState;
-#endif // CONFIG_STA_SUPPORT //
-
-//=======Common===========
-	// OP mode: either AP or STA
-	UCHAR                   OpMode;                     // OPMODE_STA, OPMODE_AP
-
-	NDIS_MEDIA_STATE        IndicateMediaState;			// Base on Indication state, default is NdisMediaStateDisConnected
-
-
-	// configuration: read from Registry & E2PROM
-	BOOLEAN                 bLocalAdminMAC;             // Use user changed MAC
-	UCHAR                   PermanentAddress[MAC_ADDR_LEN];    // Factory default MAC address
-	UCHAR                   CurrentAddress[MAC_ADDR_LEN];      // User changed MAC address
-
-	// ------------------------------------------------------
-	// common configuration to both OPMODE_STA and OPMODE_AP
-	// ------------------------------------------------------
-	COMMON_CONFIG           CommonCfg;
-	MLME_STRUCT             Mlme;
-
-	// AP needs those vaiables for site survey feature.
-	MLME_AUX                MlmeAux;           // temporary settings used during MLME state machine
-	BSS_TABLE               ScanTab;           // store the latest SCAN result
-
-	//About MacTab, the sta driver will use #0 and #1 for multicast and AP.
-	MAC_TABLE                 MacTab;     // ASIC on-chip WCID entry table.  At TX, ASIC always use key according to this on-chip table.
-	NDIS_SPIN_LOCK          MacTabLock;
-
-#ifdef DOT11_N_SUPPORT
-	BA_TABLE			BATable;
-#endif // DOT11_N_SUPPORT //
-	NDIS_SPIN_LOCK          BATabLock;
-	RALINK_TIMER_STRUCT RECBATimer;
-
-	// encryption/decryption KEY tables
-	CIPHER_KEY              SharedKey[MAX_MBSSID_NUM][4]; // STA always use SharedKey[BSS0][0..3]
-
-		// RX re-assembly buffer for fragmentation
-	FRAGMENT_FRAME          FragFrame;                  // Frame storage for fragment frame
-
-	// various Counters
-	COUNTER_802_3           Counters8023;               // 802.3 counters
-	COUNTER_802_11          WlanCounters;               // 802.11 MIB counters
-	COUNTER_RALINK          RalinkCounters;             // Ralink propriety counters
-	COUNTER_DRS             DrsCounters;                // counters for Dynamic TX Rate Switching
-	PRIVATE_STRUC           PrivateInfo;                // Private information & counters
-
-	// flags, see fRTMP_ADAPTER_xxx flags
-	ULONG                   Flags;                      // Represent current device status
-
-	// current TX sequence #
-	USHORT                  Sequence;
-
-	// Control disconnect / connect event generation
-	//+++Didn't used anymore
-	ULONG                   LinkDownTime;
-	//---
-	ULONG                   LastRxRate;
-	ULONG                   LastTxRate;
-	//+++Used only for Station
-	BOOLEAN                 bConfigChanged;         // Config Change flag for the same SSID setting
-	//---
-
-	ULONG                   ExtraInfo;              // Extra information for displaying status
-	ULONG                   SystemErrorBitmap;      // b0: E2PROM version error
-
-	//+++Didn't used anymore
-	ULONG                   MacIcVersion;           // MAC/BBP serial interface issue solved after ver.D
-	//---
-
-	// ---------------------------
-	// System event log
-	// ---------------------------
-	RT_802_11_EVENT_TABLE   EventTab;
-
-
-	BOOLEAN		HTCEnable;
-
-	/*****************************************************************************************/
-	/*      Statistic related parameters                                                     */
-	/*****************************************************************************************/
-#ifdef RT2870
-	ULONG						BulkOutDataOneSecCount;
-	ULONG						BulkInDataOneSecCount;
-	ULONG						BulkLastOneSecCount; // BulkOutDataOneSecCount + BulkInDataOneSecCount
-	ULONG						watchDogRxCnt;
-	ULONG						watchDogRxOverFlowCnt;
-	ULONG						watchDogTxPendingCnt[NUM_OF_TX_RING];
-#endif // RT2870 //
-
-	BOOLEAN						bUpdateBcnCntDone;
-	ULONG						watchDogMacDeadlock;	// prevent MAC/BBP into deadlock condition
-	// ----------------------------
-	// DEBUG paramerts
-	// ----------------------------
-	//ULONG		DebugSetting[4];
-	BOOLEAN		bBanAllBaSetup;
-	BOOLEAN		bPromiscuous;
-
-	// ----------------------------
-	// rt2860c emulation-use Parameters
-	// ----------------------------
-	ULONG		rtsaccu[30];
-	ULONG		ctsaccu[30];
-	ULONG		cfendaccu[30];
-	ULONG		bacontent[16];
-	ULONG		rxint[RX_RING_SIZE+1];
-	UCHAR		rcvba[60];
-	BOOLEAN		bLinkAdapt;
-	BOOLEAN		bForcePrintTX;
-	BOOLEAN		bForcePrintRX;
-	BOOLEAN		bDisablescanning;		//defined in RT2870 USB
-	BOOLEAN		bStaFifoTest;
-	BOOLEAN		bProtectionTest;
-	BOOLEAN		bHCCATest;
-	BOOLEAN		bGenOneHCCA;
-	BOOLEAN		bBroadComHT;
-	//+++Following add from RT2870 USB.
-	ULONG		BulkOutReq;
-	ULONG		BulkOutComplete;
-	ULONG		BulkOutCompleteOther;
-	ULONG		BulkOutCompleteCancel;	// seems not use now?
-	ULONG		BulkInReq;
-	ULONG		BulkInComplete;
-	ULONG		BulkInCompleteFail;
-	//---
-
-    struct wificonf			WIFItestbed;
-
-#ifdef RALINK_ATE
-	ATE_INFO				ate;
-#ifdef RT2870
-	BOOLEAN					ContinBulkOut;		//ATE bulk out control
-	BOOLEAN					ContinBulkIn;		//ATE bulk in control
-	atomic_t				BulkOutRemained;
-	atomic_t				BulkInRemained;
-#endif // RT2870 //
-#endif // RALINK_ATE //
-
-#ifdef DOT11_N_SUPPORT
-	struct reordering_mpdu_pool mpdu_blk_pool;
-#endif // DOT11_N_SUPPORT //
-
-	ULONG					OneSecondnonBEpackets;		// record non BE packets per second
-
-#if WIRELESS_EXT >= 12
-    struct iw_statistics    iw_stats;
-#endif
-
-	struct net_device_stats	stats;
-
-#ifdef BLOCK_NET_IF
-	BLOCK_QUEUE_ENTRY		blockQueueTab[NUM_OF_TX_RING];
-#endif // BLOCK_NET_IF //
-
-
-
-#ifdef MULTIPLE_CARD_SUPPORT
-	INT32					MC_RowID;
-	UCHAR					MC_FileName[256];
-#endif // MULTIPLE_CARD_SUPPORT //
-
-	ULONG					TbttTickCount;
-#ifdef PCI_MSI_SUPPORT
-	BOOLEAN					HaveMsi;
-#endif // PCI_MSI_SUPPORT //
-
-
-	UCHAR					is_on;
-
-#define TIME_BASE			(1000000/OS_HZ)
-#define TIME_ONE_SECOND		(1000000/TIME_BASE)
-	UCHAR					flg_be_adjust;
-	ULONG					be_adjust_last_time;
-
-
-#ifdef IKANOS_VX_1X0
-	struct IKANOS_TX_INFO	IkanosTxInfo;
-	struct IKANOS_TX_INFO	IkanosRxInfo[MAX_MBSSID_NUM + MAX_WDS_ENTRY + MAX_APCLI_NUM + MAX_MESH_NUM];
-#endif // IKANOS_VX_1X0 //
-
-
-#ifdef DBG_DIAGNOSE
-	RtmpDiagStruct	DiagStruct;
-#endif // DBG_DIAGNOSE //
-
-
-	UINT8					PM_FlgSuspend;
-} RTMP_ADAPTER, *PRTMP_ADAPTER;
-
-//
-// Cisco IAPP format
-//
-typedef struct  _CISCO_IAPP_CONTENT_
-{
-	USHORT     Length;        //IAPP Length
-	UCHAR      MessageType;      //IAPP type
-	UCHAR      FunctionCode;     //IAPP function type
-	UCHAR      DestinaionMAC[MAC_ADDR_LEN];
-	UCHAR      SourceMAC[MAC_ADDR_LEN];
-	USHORT     Tag;           //Tag(element IE) - Adjacent AP report
-	USHORT     TagLength;     //Length of element not including 4 byte header
-	UCHAR      OUI[4];           //0x00, 0x40, 0x96, 0x00
-	UCHAR      PreviousAP[MAC_ADDR_LEN];       //MAC Address of access point
-	USHORT     Channel;
-	USHORT     SsidLen;
-	UCHAR      Ssid[MAX_LEN_OF_SSID];
-	USHORT     Seconds;          //Seconds that the client has been disassociated.
-} CISCO_IAPP_CONTENT, *PCISCO_IAPP_CONTENT;
-
-#define DELAYINTMASK		0x0003fffb
-#define INTMASK				0x0003fffb
-#define IndMask				0x0003fffc
-#define RxINT				0x00000005	// Delayed Rx or indivi rx
-#define TxDataInt			0x000000fa	// Delayed Tx or indivi tx
-#define TxMgmtInt			0x00000102	// Delayed Tx or indivi tx
-#define TxCoherent			0x00020000	// tx coherent
-#define RxCoherent			0x00010000	// rx coherent
-#define McuCommand			0x00000200	// mcu
-#define PreTBTTInt			0x00001000	// Pre-TBTT interrupt
-#define TBTTInt				0x00000800		// TBTT interrupt
-#define GPTimeOutInt			0x00008000		// GPtimeout interrupt
-#define AutoWakeupInt		0x00004000		// AutoWakeupInt interrupt
-#define FifoStaFullInt			0x00002000	//  fifo statistics full interrupt
-
-
-typedef struct _RX_BLK_
-{
-//	RXD_STRUC		RxD; // sample
-	RT28XX_RXD_STRUC	RxD;
-	PRXWI_STRUC			pRxWI;
-	PHEADER_802_11		pHeader;
-	PNDIS_PACKET		pRxPacket;
-	UCHAR				*pData;
-	USHORT				DataSize;
-	USHORT				Flags;
-	UCHAR				UserPriority;	// for calculate TKIP MIC using
-} RX_BLK;
-
-
-#define RX_BLK_SET_FLAG(_pRxBlk, _flag)		(_pRxBlk->Flags |= _flag)
-#define RX_BLK_TEST_FLAG(_pRxBlk, _flag)	(_pRxBlk->Flags & _flag)
-#define RX_BLK_CLEAR_FLAG(_pRxBlk, _flag)	(_pRxBlk->Flags &= ~(_flag))
-
-
-#define fRX_WDS			0x0001
-#define fRX_AMSDU       0x0002
-#define fRX_ARALINK     0x0004
-#define fRX_HTC         0x0008
-#define fRX_PAD         0x0010
-#define fRX_AMPDU       0x0020
-#define fRX_QOS			0x0040
-#define fRX_INFRA		0x0080
-#define fRX_EAP			0x0100
-#define fRX_MESH		0x0200
-#define fRX_APCLI		0x0400
-#define fRX_DLS			0x0800
-#define fRX_WPI			0x1000
-
-#define LENGTH_AMSDU_SUBFRAMEHEAD	14
-#define LENGTH_ARALINK_SUBFRAMEHEAD	14
-#define LENGTH_ARALINK_HEADER_FIELD	 2
-
-#define TX_UNKOWN_FRAME			0x00
-#define TX_MCAST_FRAME			0x01
-#define TX_LEGACY_FRAME			0x02
-#define TX_AMPDU_FRAME			0x04
-#define TX_AMSDU_FRAME			0x08
-#define TX_RALINK_FRAME			0x10
-#define TX_FRAG_FRAME			0x20
-
-
-//	Currently the sizeof(TX_BLK) is 148 bytes.
-typedef struct _TX_BLK_
-{
-	UCHAR				QueIdx;
-	UCHAR				TxFrameType;				// Indicate the Transmission type of the all frames in one batch
-	UCHAR				TotalFrameNum;				// Total frame number want to send-out in one batch
-	USHORT				TotalFragNum;				// Total frame fragments required in one batch
-	USHORT				TotalFrameLen;				// Total length of all frames want to send-out in one batch
-
-	QUEUE_HEADER		TxPacketList;
-	MAC_TABLE_ENTRY		*pMacEntry;					// NULL: packet with 802.11 RA field is multicast/broadcast address
-	HTTRANSMIT_SETTING	*pTransmit;
-
-	// Following structure used for the characteristics of a specific packet.
-	PNDIS_PACKET		pPacket;
-	PUCHAR				pSrcBufHeader;				// Reference to the head of sk_buff->data
-	PUCHAR				pSrcBufData;				// Reference to the sk_buff->data, will changed depends on hanlding progresss
-	UINT				SrcBufLen;					// Length of packet payload which not including Layer 2 header
-	PUCHAR				pExtraLlcSnapEncap;			// NULL means no extra LLC/SNAP is required
-	UCHAR				HeaderBuf[80];				// TempBuffer for TX_INFO + TX_WI + 802.11 Header + padding + AMSDU SubHeader + LLC/SNAP
-	UCHAR				MpduHeaderLen;				// 802.11 header length NOT including the padding
-	UCHAR				HdrPadLen;					// recording Header Padding Length;
-	UCHAR				apidx;						// The interface associated to this packet
-	UCHAR				Wcid;						// The MAC entry associated to this packet
-	UCHAR				UserPriority;				// priority class of packet
-	UCHAR				FrameGap;					// what kind of IFS this packet use
-	UCHAR				MpduReqNum;					// number of fragments of this frame
-	UCHAR				TxRate;						// TODO: Obsoleted? Should change to MCS?
-	UCHAR				CipherAlg;					// cipher alogrithm
-	PCIPHER_KEY			pKey;
-
-
-
-	USHORT				Flags;						//See following definitions for detail.
-
-	//YOU SHOULD NOT TOUCH IT! Following parameters are used for hardware-depended layer.
-	ULONG				Priv;						// Hardware specific value saved in here.
-} TX_BLK, *PTX_BLK;
-
-
-#define fTX_bRtsRequired		0x0001	// Indicate if need send RTS frame for protection. Not used in RT2860/RT2870.
-#define fTX_bAckRequired       	0x0002	// the packet need ack response
-#define fTX_bPiggyBack     		0x0004	// Legacy device use Piggback or not
-#define fTX_bHTRate         	0x0008	// allow to use HT rate
-//#define fTX_bForceLowRate       0x0010	// force to use Low Rate
-#define fTX_bForceNonQoS       	0x0010	// force to transmit frame without WMM-QoS in HT mode
-#define fTX_bAllowFrag       	0x0020	// allow to fragment the packet, A-MPDU, A-MSDU, A-Ralink is not allowed to fragment
-#define fTX_bMoreData			0x0040	// there are more data packets in PowerSave Queue
-#define fTX_bWMM				0x0080	// QOS Data
-
-#define fTX_bClearEAPFrame		0x0100
-
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-#define TX_BLK_ASSIGN_FLAG(_pTxBlk, _flag, value)	\
-		do {										\
-			if (value) 								\
-				(_pTxBlk->Flags |= _flag) 			\
-			else 									\
-				(_pTxBlk->Flags &= ~(_flag))		\
-		}while(0)
-
-#define TX_BLK_SET_FLAG(_pTxBlk, _flag)		(_pTxBlk->Flags |= _flag)
-#define TX_BLK_TEST_FLAG(_pTxBlk, _flag)	(((_pTxBlk->Flags & _flag) == _flag) ? 1 : 0)
-#define TX_BLK_CLEAR_FLAG(_pTxBlk, _flag)	(_pTxBlk->Flags &= ~(_flag))
-
-
-
-
-
-//------------------------------------------------------------------------------------------
-
-
-
-#ifdef RT_BIG_ENDIAN
-static inline VOID	WriteBackToDescriptor(
-	IN  PUCHAR			Dest,
- 	IN	PUCHAR			Src,
-    IN  BOOLEAN			DoEncrypt,
-	IN  ULONG           DescriptorType)
-{
-	UINT32 *p1, *p2;
-
-	p1 = ((UINT32 *)Dest);
-	p2 = ((UINT32 *)Src);
-
-	*p1 = *p2;
-	*(p1+2) = *(p2+2);
-	*(p1+3) = *(p2+3);
-	*(p1+1) = *(p2+1); // Word 1; this must be written back last
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Endian conversion of Tx/Rx descriptor .
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pData			Pointer to Tx/Rx descriptor
-		DescriptorType	Direction of the frame
-
-	Return Value:
-		None
-
-	Note:
-		Call this function when read or update descriptor
-	========================================================================
-*/
-static inline VOID	RTMPWIEndianChange(
-	IN	PUCHAR			pData,
-	IN	ULONG			DescriptorType)
-{
-	int size;
-	int i;
-
-	size = ((DescriptorType == TYPE_TXWI) ? TXWI_SIZE : RXWI_SIZE);
-
-	if(DescriptorType == TYPE_TXWI)
-	{
-		*((UINT32 *)(pData)) = SWAP32(*((UINT32 *)(pData)));		// Byte 0~3
-		*((UINT32 *)(pData + 4)) = SWAP32(*((UINT32 *)(pData+4)));	// Byte 4~7
-	}
-	else
-	{
-		for(i=0; i < size/4 ; i++)
-			*(((UINT32 *)pData) +i) = SWAP32(*(((UINT32 *)pData)+i));
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Endian conversion of Tx/Rx descriptor .
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pData			Pointer to Tx/Rx descriptor
-		DescriptorType	Direction of the frame
-
-	Return Value:
-		None
-
-	Note:
-		Call this function when read or update descriptor
-	========================================================================
-*/
-
-#ifdef RT2870
-static inline VOID	RTMPDescriptorEndianChange(
-	IN	PUCHAR			pData,
-	IN	ULONG			DescriptorType)
-{
-	*((UINT32 *)(pData)) = SWAP32(*((UINT32 *)(pData)));
-}
-#endif // RT2870 //
-/*
-	========================================================================
-
-	Routine Description:
-		Endian conversion of all kinds of 802.11 frames .
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pData			Pointer to the 802.11 frame structure
-		Dir 			Direction of the frame
-		FromRxDoneInt	Caller is from RxDone interrupt
-
-	Return Value:
-		None
-
-	Note:
-		Call this function when read or update buffer data
-	========================================================================
-*/
-static inline VOID	RTMPFrameEndianChange(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pData,
-	IN	ULONG			Dir,
-	IN	BOOLEAN 		FromRxDoneInt)
-{
-	PHEADER_802_11 pFrame;
-	PUCHAR	pMacHdr;
-
-	// swab 16 bit fields - Frame Control field
-	if(Dir == DIR_READ)
-	{
-		*(USHORT *)pData = SWAP16(*(USHORT *)pData);
-	}
-
-	pFrame = (PHEADER_802_11) pData;
-	pMacHdr = (PUCHAR) pFrame;
-
-	// swab 16 bit fields - Duration/ID field
-	*(USHORT *)(pMacHdr + 2) = SWAP16(*(USHORT *)(pMacHdr + 2));
-
-	// swab 16 bit fields - Sequence Control field
-	*(USHORT *)(pMacHdr + 22) = SWAP16(*(USHORT *)(pMacHdr + 22));
-
-	if(pFrame->FC.Type == BTYPE_MGMT)
-	{
-		switch(pFrame->FC.SubType)
-		{
-			case SUBTYPE_ASSOC_REQ:
-			case SUBTYPE_REASSOC_REQ:
-				// swab 16 bit fields - CapabilityInfo field
-				pMacHdr += sizeof(HEADER_802_11);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - Listen Interval field
-				pMacHdr += 2;
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-
-			case SUBTYPE_ASSOC_RSP:
-			case SUBTYPE_REASSOC_RSP:
-				// swab 16 bit fields - CapabilityInfo field
-				pMacHdr += sizeof(HEADER_802_11);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - Status Code field
-				pMacHdr += 2;
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - AID field
-				pMacHdr += 2;
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-
-			case SUBTYPE_AUTH:
-				// If from APHandleRxDoneInterrupt routine, it is still a encrypt format.
-				// The convertion is delayed to RTMPHandleDecryptionDoneInterrupt.
-				if(!FromRxDoneInt && pFrame->FC.Wep == 1)
-					break;
-				else
-				{
-					// swab 16 bit fields - Auth Alg No. field
-					pMacHdr += sizeof(HEADER_802_11);
-					*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-					// swab 16 bit fields - Auth Seq No. field
-					pMacHdr += 2;
-					*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-					// swab 16 bit fields - Status Code field
-					pMacHdr += 2;
-					*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				}
-				break;
-
-			case SUBTYPE_BEACON:
-			case SUBTYPE_PROBE_RSP:
-				// swab 16 bit fields - BeaconInterval field
-				pMacHdr += (sizeof(HEADER_802_11) + TIMESTAMP_LEN);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - CapabilityInfo field
-				pMacHdr += sizeof(USHORT);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-
-			case SUBTYPE_DEAUTH:
-			case SUBTYPE_DISASSOC:
-				// swab 16 bit fields - Reason code field
-				pMacHdr += sizeof(HEADER_802_11);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-		}
-	}
-	else if( pFrame->FC.Type == BTYPE_DATA )
-	{
-	}
-	else if(pFrame->FC.Type == BTYPE_CNTL)
-	{
-		switch(pFrame->FC.SubType)
-		{
-			case SUBTYPE_BLOCK_ACK_REQ:
-				{
-					PFRAME_BA_REQ pBAReq = (PFRAME_BA_REQ)pFrame;
-					*(USHORT *)(&pBAReq->BARControl) = SWAP16(*(USHORT *)(&pBAReq->BARControl));
-					pBAReq->BAStartingSeq.word = SWAP16(pBAReq->BAStartingSeq.word);
-				}
-				break;
-			case SUBTYPE_BLOCK_ACK:
-				// For Block Ack packet, the HT_CONTROL field is in the same offset with Addr3
-				*(UINT32 *)(&pFrame->Addr3[0]) = SWAP32(*(UINT32 *)(&pFrame->Addr3[0]));
-				break;
-
-			case SUBTYPE_ACK:
-				//For ACK packet, the HT_CONTROL field is in the same offset with Addr2
-				*(UINT32 *)(&pFrame->Addr2[0])=	SWAP32(*(UINT32 *)(&pFrame->Addr2[0]));
-				break;
-		}
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("Invalid Frame Type!!!\n"));
-	}
-
-	// swab 16 bit fields - Frame Control
-	if(Dir == DIR_WRITE)
-	{
-		*(USHORT *)pData = SWAP16(*(USHORT *)pData);
-	}
-}
-#endif // RT_BIG_ENDIAN //
-
-
-static inline VOID ConvertMulticastIP2MAC(
-	IN PUCHAR pIpAddr,
-	IN PUCHAR *ppMacAddr,
-	IN UINT16 ProtoType)
-{
-	if (pIpAddr == NULL)
-		return;
-
-	if (ppMacAddr == NULL || *ppMacAddr == NULL)
-		return;
-
-	switch (ProtoType)
-	{
-		case ETH_P_IPV6:
-//			memset(*ppMacAddr, 0, ETH_LENGTH_OF_ADDRESS);
-			*(*ppMacAddr) = 0x33;
-			*(*ppMacAddr + 1) = 0x33;
-			*(*ppMacAddr + 2) = pIpAddr[12];
-			*(*ppMacAddr + 3) = pIpAddr[13];
-			*(*ppMacAddr + 4) = pIpAddr[14];
-			*(*ppMacAddr + 5) = pIpAddr[15];
-			break;
-
-		case ETH_P_IP:
-		default:
-//			memset(*ppMacAddr, 0, ETH_LENGTH_OF_ADDRESS);
-			*(*ppMacAddr) = 0x01;
-			*(*ppMacAddr + 1) = 0x00;
-			*(*ppMacAddr + 2) = 0x5e;
-			*(*ppMacAddr + 3) = pIpAddr[1] & 0x7f;
-			*(*ppMacAddr + 4) = pIpAddr[2];
-			*(*ppMacAddr + 5) = pIpAddr[3];
-			break;
-	}
-
-	return;
-}
-
-BOOLEAN RTMPCheckForHang(
-	IN  NDIS_HANDLE MiniportAdapterContext
-	);
-
-VOID  RTMPHalt(
-	IN  NDIS_HANDLE MiniportAdapterContext
-	);
-
-//
-//  Private routines in rtmp_init.c
-//
-NDIS_STATUS RTMPAllocAdapterBlock(
-	IN PVOID			handle,
-	OUT PRTMP_ADAPTER   *ppAdapter
-	);
-
-NDIS_STATUS RTMPAllocTxRxRingMemory(
-	IN  PRTMP_ADAPTER   pAd
-	);
-
-NDIS_STATUS RTMPFindAdapter(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  NDIS_HANDLE     WrapperConfigurationContext
-	);
-
-NDIS_STATUS	RTMPReadParametersHook(
-	IN	PRTMP_ADAPTER pAd
-	);
-
-VOID RTMPFreeAdapter(
-	IN  PRTMP_ADAPTER   pAd
-	);
-
-NDIS_STATUS NICReadRegParameters(
-	IN  PRTMP_ADAPTER       pAd,
-	IN  NDIS_HANDLE         WrapperConfigurationContext
-	);
-
-#ifdef RT2870
-VOID NICInitRT30xxRFRegisters(
-	IN PRTMP_ADAPTER pAd);
-#endif // RT2870 //
-
-VOID NICReadEEPROMParameters(
-	IN  PRTMP_ADAPTER       pAd,
-	IN	PUCHAR				mac_addr);
-
-VOID NICInitAsicFromEEPROM(
-	IN  PRTMP_ADAPTER       pAd);
-
-VOID NICInitTxRxRingAndBacklogQueue(
-	IN  PRTMP_ADAPTER   pAd);
-
-NDIS_STATUS NICInitializeAdapter(
-	IN  PRTMP_ADAPTER   pAd,
-	IN   BOOLEAN    bHardReset);
-
-NDIS_STATUS NICInitializeAsic(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  BOOLEAN		bHardReset);
-
-VOID NICIssueReset(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPRingCleanUp(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           RingType);
-
-VOID RxTest(
-	IN  PRTMP_ADAPTER   pAd);
-
-NDIS_STATUS DbgSendPacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PNDIS_PACKET    pPacket);
-
-VOID UserCfgInit(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID NICResetFromError(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID NICEraseFirmware(
-	IN PRTMP_ADAPTER pAd);
-
-NDIS_STATUS NICLoadFirmware(
-	IN  PRTMP_ADAPTER   pAd);
-
-NDIS_STATUS NICLoadRateSwitchingParams(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN NICCheckForHang(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID NICUpdateFifoStaCounters(
-	IN PRTMP_ADAPTER pAd);
-
-VOID NICUpdateRawCounters(
-	IN  PRTMP_ADAPTER   pAd);
-
-#if 0
-ULONG RTMPEqualMemory(
-	IN  PVOID   pSrc1,
-	IN  PVOID   pSrc2,
-	IN  ULONG   Length);
-#endif
-
-ULONG	RTMPNotAllZero(
-	IN	PVOID	pSrc1,
-	IN	ULONG	Length);
-
-VOID RTMPZeroMemory(
-	IN  PVOID   pSrc,
-	IN  ULONG   Length);
-
-ULONG RTMPCompareMemory(
-	IN  PVOID   pSrc1,
-	IN  PVOID   pSrc2,
-	IN  ULONG   Length);
-
-VOID RTMPMoveMemory(
-	OUT PVOID   pDest,
-	IN  PVOID   pSrc,
-	IN  ULONG   Length);
-
-VOID AtoH(
-	char	*src,
-	UCHAR	*dest,
-	int		destlen);
-
-UCHAR BtoH(
-	char ch);
-
-VOID RTMPPatchMacBbpBug(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPPatchCardBus(
-	IN	PRTMP_ADAPTER	pAdapter);
-
-VOID RTMPPatchRalinkCardBus(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	ULONG			Bus);
-
-ULONG RTMPReadCBConfig(
-	IN	ULONG	Bus,
-	IN	ULONG	Slot,
-	IN	ULONG	Func,
-	IN	ULONG	Offset);
-
-VOID RTMPWriteCBConfig(
-	IN	ULONG	Bus,
-	IN	ULONG	Slot,
-	IN	ULONG	Func,
-	IN	ULONG	Offset,
-	IN	ULONG	Value);
-
-VOID RTMPInitTimer(
-	IN  PRTMP_ADAPTER           pAd,
-	IN  PRALINK_TIMER_STRUCT    pTimer,
-	IN  PVOID                   pTimerFunc,
-	IN	PVOID					pData,
-	IN  BOOLEAN                 Repeat);
-
-VOID RTMPSetTimer(
-	IN  PRALINK_TIMER_STRUCT    pTimer,
-	IN  ULONG                   Value);
-
-
-VOID RTMPModTimer(
-	IN	PRALINK_TIMER_STRUCT	pTimer,
-	IN	ULONG					Value);
-
-VOID RTMPCancelTimer(
-	IN  PRALINK_TIMER_STRUCT    pTimer,
-	OUT BOOLEAN                 *pCancelled);
-
-VOID RTMPSetLED(
-	IN PRTMP_ADAPTER 	pAd,
-	IN UCHAR			Status);
-
-VOID RTMPSetSignalLED(
-	IN PRTMP_ADAPTER 	pAd,
-	IN NDIS_802_11_RSSI Dbm);
-
-VOID RTMPEnableRxTx(
-	IN PRTMP_ADAPTER	pAd);
-
-//
-// prototype in action.c
-//
-VOID ActionStateMachineInit(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  STATE_MACHINE *S,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID MlmeADDBAAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeDELBAAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeDLSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeInvalidAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeQOSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-#ifdef DOT11_N_SUPPORT
-VOID PeerAddBAReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerAddBARspAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerDelBAAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerBAAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-#endif // DOT11_N_SUPPORT //
-
-VOID SendPSMPAction(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			Wcid,
-	IN UCHAR			Psmp);
-
-
-#ifdef DOT11N_DRAFT3
-VOID SendBSS2040CoexistMgmtAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR	Wcid,
-	IN	UCHAR	apidx,
-	IN	UCHAR	InfoReq);
-
-VOID SendNotifyBWActionFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR  Wcid,
-	IN UCHAR apidx);
-
-BOOLEAN ChannelSwitchSanityCheck(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  NewChannel,
-	IN    UCHAR  Secondary);
-
-VOID ChannelSwitchAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  Channel,
-	IN    UCHAR  Secondary);
-
-ULONG BuildIntolerantChannelRep(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    PUCHAR  pDest);
-
-VOID Update2040CoexistFrameAndNotify(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha);
-
-VOID Send2040CoexistAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha);
-#endif // DOT11N_DRAFT3 //
-
-VOID PeerRMAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerPublicAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-#ifdef CONFIG_STA_SUPPORT
-VOID StaPublicAction(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR Bss2040Coexist);
-#endif // CONFIG_STA_SUPPORT //
-
-
-VOID PeerBSSTranAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-#ifdef DOT11_N_SUPPORT
-VOID PeerHTAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-#endif // DOT11_N_SUPPORT //
-
-VOID PeerQOSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-#ifdef QOS_DLS_SUPPORT
-VOID PeerDLSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-#endif // QOS_DLS_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-VOID DlsParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_DLS_REQ_STRUCT *pDlsReq,
-	IN PRT_802_11_DLS pDls,
-	IN USHORT reason);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-VOID RECBATimerTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-VOID ORIBATimerTimeout(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID SendRefreshBAR(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry);
-#endif // DOT11_N_SUPPORT //
-
-VOID ActHeaderInit(
-    IN	PRTMP_ADAPTER	pAd,
-    IN OUT PHEADER_802_11 pHdr80211,
-    IN PUCHAR Addr1,
-    IN PUCHAR Addr2,
-    IN PUCHAR Addr3);
-
-VOID BarHeaderInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN OUT PFRAME_BAR pCntlBar,
-	IN PUCHAR pDA,
-	IN PUCHAR pSA);
-
-VOID InsertActField(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN UINT8 Category,
-	IN UINT8 ActCode);
-
-BOOLEAN QosBADataParse(
-	IN PRTMP_ADAPTER	pAd,
-	IN BOOLEAN bAMSDU,
-	IN PUCHAR p8023Header,
-	IN UCHAR	WCID,
-	IN UCHAR	TID,
-	IN USHORT Sequence,
-	IN UCHAR DataOffset,
-	IN USHORT Datasize,
-	IN UINT   CurRxIndex);
-
-#ifdef DOT11_N_SUPPORT
-BOOLEAN CntlEnqueueForRecv(
-    IN	PRTMP_ADAPTER	pAd,
-	IN ULONG Wcid,
-    IN ULONG MsgLen,
-	IN PFRAME_BA_REQ pMsg);
-
-VOID BaAutoManSwitch(
-	IN	PRTMP_ADAPTER	pAd);
-#endif // DOT11_N_SUPPORT //
-
-VOID HTIOTCheck(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR     BatRecIdx);
-
-//
-// Private routines in rtmp_data.c
-//
-BOOLEAN RTMPHandleRxDoneInterrupt(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPHandleTxDoneInterrupt(
-	IN  PRTMP_ADAPTER   pAd);
-
-BOOLEAN RTMPHandleTxRingDmaDoneInterrupt(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  INT_SOURCE_CSR_STRUC TxRingBitmap);
-
-VOID RTMPHandleMgmtRingDmaDoneInterrupt(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPHandleTBTTInterrupt(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPHandlePreTBTTInterrupt(
-	IN  PRTMP_ADAPTER   pAd);
-
-void RTMPHandleTwakeupInterrupt(
-	IN PRTMP_ADAPTER pAd);
-
-VOID	RTMPHandleRxCoherentInterrupt(
-	IN	PRTMP_ADAPTER	pAd);
-
-BOOLEAN TxFrameIsAggregatible(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pPrevAddr1,
-	IN  PUCHAR          p8023hdr);
-
-BOOLEAN PeerIsAggreOn(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  ULONG          TxRate,
-    IN  PMAC_TABLE_ENTRY pMacEntry);
-
-#if 0	// It's not be used
-HTTRANSMIT_SETTING  *GetTxMode(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk);
-#endif
-
-NDIS_STATUS Sniff2BytesFromNdisBuffer(
-	IN  PNDIS_BUFFER    pFirstBuffer,
-	IN  UCHAR           DesiredOffset,
-	OUT PUCHAR          pByte0,
-	OUT PUCHAR          pByte1);
-
-NDIS_STATUS STASendPacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PNDIS_PACKET    pPacket);
-
-VOID STASendPackets(
-	IN  NDIS_HANDLE     MiniportAdapterContext,
-	IN  PPNDIS_PACKET   ppPacketArray,
-	IN  UINT            NumberOfPackets);
-
-VOID RTMPDeQueuePacket(
-	IN  PRTMP_ADAPTER   pAd,
-   	IN	BOOLEAN			bIntContext,
-	IN  UCHAR			QueIdx,
-	IN	UCHAR			Max_Tx_Packets);
-
-NDIS_STATUS	RTMPHardTransmit(
-	IN PRTMP_ADAPTER	pAd,
-	IN PNDIS_PACKET		pPacket,
-	IN  UCHAR			QueIdx,
-	OUT	PULONG			pFreeTXDLeft);
-
-NDIS_STATUS	STAHardTransmit(
-	IN PRTMP_ADAPTER	pAd,
-	IN TX_BLK			*pTxBlk,
-	IN  UCHAR			QueIdx);
-
-VOID STARxEAPOLFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-NDIS_STATUS RTMPFreeTXDRequest(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           RingType,
-	IN  UCHAR           NumberRequired,
-	IN 	PUCHAR          FreeNumberIs);
-
-NDIS_STATUS MlmeHardTransmit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR	QueIdx,
-	IN  PNDIS_PACKET    pPacket);
-
-NDIS_STATUS MlmeHardTransmitMgmtRing(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR	QueIdx,
-	IN  PNDIS_PACKET    pPacket);
-
-NDIS_STATUS MlmeHardTransmitTxRing(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR	QueIdx,
-	IN  PNDIS_PACKET    pPacket);
-
-USHORT  RTMPCalcDuration(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Rate,
-	IN  ULONG           Size);
-
-VOID RTMPWriteTxWI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXWI_STRUC		pTxWI,
-	IN  BOOLEAN    		FRAG,
-	IN  BOOLEAN    		CFACK,
-	IN  BOOLEAN    		InsTimestamp,
-	IN	BOOLEAN			AMPDU,
-	IN	BOOLEAN			Ack,
-	IN	BOOLEAN			NSeq,		// HW new a sequence.
-	IN	UCHAR			BASize,
-	IN	UCHAR			WCID,
-	IN	ULONG			Length,
-	IN  UCHAR      		PID,
-	IN	UCHAR			TID,
-	IN	UCHAR			TxRate,
-	IN	UCHAR			Txopmode,
-	IN	BOOLEAN			CfAck,
-	IN	HTTRANSMIT_SETTING	*pTransmit);
-
-
-VOID RTMPWriteTxWI_Data(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	OUT PTXWI_STRUC		pTxWI,
-	IN	TX_BLK				*pTxBlk);
-
-
-VOID RTMPWriteTxWI_Cache(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	OUT PTXWI_STRUC		pTxWI,
-	IN	TX_BLK				*pTxBlk);
-
-VOID RTMPWriteTxDescriptor(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXD_STRUC		pTxD,
-	IN	BOOLEAN			bWIV,
-	IN	UCHAR			QSEL);
-
-VOID RTMPSuspendMsduTransmission(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPResumeMsduTransmission(
-	IN  PRTMP_ADAPTER   pAd);
-
-NDIS_STATUS MiniportMMRequest(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			QueIdx,
-	IN	PUCHAR			pData,
-	IN  UINT            Length);
-
-NDIS_STATUS MiniportDataMMRequest(
-	 IN  PRTMP_ADAPTER   pAd,
-	 IN  UCHAR           QueIdx,
-	 IN  PUCHAR          pData,
-	 IN  UINT            Length);
-
-VOID RTMPSendNullFrame(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           TxRate,
-	IN	BOOLEAN			bQosNull);
-
-VOID RTMPSendDisassociationFrame(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTMPSendRTSFrame(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pDA,
-	IN	unsigned int	NextMpduSize,
-	IN  UCHAR           TxRate,
-	IN  UCHAR           RTSRate,
-	IN  USHORT          AckDuration,
-	IN  UCHAR           QueIdx,
-	IN  UCHAR			FrameGap);
-
-
-NDIS_STATUS RTMPApplyPacketFilter(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PRT28XX_RXD_STRUC      pRxD,
-	IN  PHEADER_802_11  pHeader);
-
-PQUEUE_HEADER   RTMPCheckTxSwQueue(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT UCHAR           *QueIdx);
-
-#ifdef CONFIG_STA_SUPPORT
-VOID RTMPReportMicError(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PCIPHER_KEY     pWpaKey);
-
-VOID	WpaMicFailureReportFrame(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    WpaDisassocApAndBlockAssoc(
-    IN  PVOID SystemSpecific1,
-    IN  PVOID FunctionContext,
-    IN  PVOID SystemSpecific2,
-    IN  PVOID SystemSpecific3);
-#endif // CONFIG_STA_SUPPORT //
-
-NDIS_STATUS RTMPCloneNdisPacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	BOOLEAN    pInsAMSDUHdr,
-	IN  PNDIS_PACKET    pInPacket,
-	OUT PNDIS_PACKET   *ppOutPacket);
-
-NDIS_STATUS RTMPAllocateNdisPacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PNDIS_PACKET    *pPacket,
-	IN  PUCHAR          pHeader,
-	IN  UINT            HeaderLen,
-	IN  PUCHAR          pData,
-	IN  UINT            DataLen);
-
-VOID RTMPFreeNdisPacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PNDIS_PACKET    pPacket);
-
-BOOLEAN RTMPFreeTXDUponTxDmaDone(
-	IN PRTMP_ADAPTER    pAd,
-	IN UCHAR            QueIdx);
-
-BOOLEAN RTMPCheckDHCPFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket);
-
-
-BOOLEAN RTMPCheckEtherType(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket);
-
-
-VOID RTMPCckBbpTuning(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UINT			TxRate);
-
-//
-// Private routines in rtmp_wep.c
-//
-VOID RTMPInitWepEngine(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pKey,
-	IN  UCHAR           KeyId,
-	IN  UCHAR           KeyLen,
-	IN  PUCHAR          pDest);
-
-VOID RTMPEncryptData(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pSrc,
-	IN  PUCHAR          pDest,
-	IN  UINT            Len);
-
-BOOLEAN	RTMPDecryptData(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			pSrc,
-	IN	UINT			Len,
-	IN	UINT			idx);
-
-BOOLEAN	RTMPSoftDecryptWEP(
-	IN PRTMP_ADAPTER 	pAd,
-	IN PUCHAR			pData,
-	IN ULONG			DataByteCnt,
-	IN PCIPHER_KEY		pGroupKey);
-
-VOID RTMPSetICV(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pDest);
-
-VOID ARCFOUR_INIT(
-	IN  PARCFOURCONTEXT Ctx,
-	IN  PUCHAR          pKey,
-	IN  UINT            KeyLen);
-
-UCHAR   ARCFOUR_BYTE(
-	IN  PARCFOURCONTEXT     Ctx);
-
-VOID ARCFOUR_DECRYPT(
-	IN  PARCFOURCONTEXT Ctx,
-	IN  PUCHAR          pDest,
-	IN  PUCHAR          pSrc,
-	IN  UINT            Len);
-
-VOID ARCFOUR_ENCRYPT(
-	IN  PARCFOURCONTEXT Ctx,
-	IN  PUCHAR          pDest,
-	IN  PUCHAR          pSrc,
-	IN  UINT            Len);
-
-VOID WPAARCFOUR_ENCRYPT(
-	IN  PARCFOURCONTEXT Ctx,
-	IN  PUCHAR          pDest,
-	IN  PUCHAR          pSrc,
-	IN  UINT            Len);
-
-UINT RTMP_CALC_FCS32(
-	IN  UINT   Fcs,
-	IN  PUCHAR  Cp,
-	IN  INT     Len);
-
-//
-// MLME routines
-//
-
-// Asic/RF/BBP related functions
-
-VOID AsicAdjustTxPower(
-	IN PRTMP_ADAPTER pAd);
-
-VOID 	AsicUpdateProtect(
-	IN		PRTMP_ADAPTER	pAd,
-	IN 		USHORT			OperaionMode,
-	IN 		UCHAR			SetMask,
-	IN		BOOLEAN			bDisableBGProtect,
-	IN		BOOLEAN			bNonGFExist);
-
-VOID AsicSwitchChannel(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			Channel,
-	IN	BOOLEAN			bScan);
-
-VOID AsicLockChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR Channel) ;
-
-VOID AsicAntennaSelect(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Channel);
-
-VOID AsicAntennaSetting(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	ABGBAND_STATE	BandState);
-
-VOID AsicRfTuningExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-#ifdef CONFIG_STA_SUPPORT
-VOID AsicSleepThenAutoWakeup(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  USHORT TbttNumToNextWakeUp);
-
-VOID AsicForceSleep(
-	IN PRTMP_ADAPTER pAd);
-
-VOID AsicForceWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN    bFromTx);
-#endif // CONFIG_STA_SUPPORT //
-
-VOID AsicSetBssid(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR pBssid);
-
-VOID AsicSetMcastWC(
-	IN PRTMP_ADAPTER pAd);
-
-#if 0	// removed by AlbertY
-VOID AsicSetBssidWC(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pBssid);
-#endif
-
-VOID AsicDelWcidTab(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR	Wcid);
-
-VOID AsicEnableRDG(
-	IN PRTMP_ADAPTER pAd);
-
-VOID AsicDisableRDG(
-	IN PRTMP_ADAPTER pAd);
-
-VOID AsicDisableSync(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID AsicEnableBssSync(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID AsicEnableIbssSync(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID AsicSetEdcaParm(
-	IN PRTMP_ADAPTER pAd,
-	IN PEDCA_PARM    pEdcaParm);
-
-VOID AsicSetSlotTime(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN bUseShortSlotTime);
-
-#if 0
-VOID AsicAddWcidCipherEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		 WCID,
-	IN UCHAR		 BssIndex,
-	IN UCHAR		 KeyTable,
-	IN UCHAR		 CipherAlg,
-	IN PUCHAR		 pAddr,
-	IN CIPHER_KEY		 *pCipherKey);
-#endif
-
-VOID AsicAddSharedKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR         BssIndex,
-	IN UCHAR         KeyIdx,
-	IN UCHAR         CipherAlg,
-	IN PUCHAR        pKey,
-	IN PUCHAR        pTxMic,
-	IN PUCHAR        pRxMic);
-
-VOID AsicRemoveSharedKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR         BssIndex,
-	IN UCHAR         KeyIdx);
-
-VOID AsicUpdateWCIDAttribute(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN UCHAR		BssIndex,
-	IN UCHAR        CipherAlg,
-	IN BOOLEAN		bUsePairewiseKeyTable);
-
-VOID AsicUpdateWCIDIVEIV(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN ULONG        uIV,
-	IN ULONG        uEIV);
-
-VOID AsicUpdateRxWCIDTable(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN PUCHAR        pAddr);
-
-VOID AsicAddKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN UCHAR		BssIndex,
-	IN UCHAR		KeyIdx,
-	IN PCIPHER_KEY	pCipherKey,
-	IN BOOLEAN		bUsePairewiseKeyTable,
-	IN BOOLEAN		bTxKey);
-
-VOID AsicAddPairwiseKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR        pAddr,
-	IN UCHAR		WCID,
-	IN CIPHER_KEY		 *pCipherKey);
-
-VOID AsicRemovePairwiseKeyEntry(
-	IN PRTMP_ADAPTER  pAd,
-	IN UCHAR		 BssIdx,
-	IN UCHAR		 Wcid);
-
-BOOLEAN AsicSendCommandToMcu(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR         Command,
-	IN UCHAR         Token,
-	IN UCHAR         Arg0,
-	IN UCHAR         Arg1);
-
-
-VOID MacAddrRandomBssid(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT PUCHAR pAddr);
-
-VOID MgtMacHeaderInit(
-	IN  PRTMP_ADAPTER     pAd,
-	IN OUT PHEADER_802_11 pHdr80211,
-	IN UCHAR SubType,
-	IN UCHAR ToDs,
-	IN PUCHAR pDA,
-	IN PUCHAR pBssid);
-
-VOID MlmeRadioOff(
-	IN PRTMP_ADAPTER pAd);
-
-VOID MlmeRadioOn(
-	IN PRTMP_ADAPTER pAd);
-
-
-VOID BssTableInit(
-	IN BSS_TABLE *Tab);
-
-#ifdef DOT11_N_SUPPORT
-VOID BATableInit(
-	IN PRTMP_ADAPTER pAd,
-    IN BA_TABLE *Tab);
-#endif // DOT11_N_SUPPORT //
-
-ULONG BssTableSearch(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR pBssid,
-	IN UCHAR Channel);
-
-ULONG BssSsidTableSearch(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR    pBssid,
-	IN PUCHAR    pSsid,
-	IN UCHAR     SsidLen,
-	IN UCHAR     Channel);
-
-ULONG BssTableSearchWithSSID(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR    Bssid,
-	IN PUCHAR    pSsid,
-	IN UCHAR     SsidLen,
-	IN UCHAR     Channel);
-
-VOID BssTableDeleteEntry(
-	IN OUT  PBSS_TABLE pTab,
-	IN      PUCHAR pBssid,
-	IN      UCHAR Channel);
-
-#ifdef DOT11_N_SUPPORT
-VOID BATableDeleteORIEntry(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		BA_ORI_ENTRY	*pBAORIEntry);
-
-VOID BATableDeleteRECEntry(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		BA_REC_ENTRY	*pBARECEntry);
-
-VOID BATableTearORIEntry(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		UCHAR TID,
-	IN		UCHAR Wcid,
-	IN		BOOLEAN bForceDelete,
-	IN		BOOLEAN ALL);
-
-VOID BATableTearRECEntry(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		UCHAR TID,
-	IN		UCHAR WCID,
-	IN		BOOLEAN ALL);
-#endif // DOT11_N_SUPPORT //
-
-VOID  BssEntrySet(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT PBSS_ENTRY pBss,
-	IN PUCHAR pBssid,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR BssType,
-	IN USHORT BeaconPeriod,
-	IN PCF_PARM CfParm,
-	IN USHORT AtimWin,
-	IN USHORT CapabilityInfo,
-	IN UCHAR SupRate[],
-	IN UCHAR SupRateLen,
-	IN UCHAR ExtRate[],
-	IN UCHAR ExtRateLen,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN ADD_HT_INFO_IE *pAddHtInfo,	// AP might use this additional ht info IE
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			AddHtInfoLen,
-	IN UCHAR			NewExtChanOffset,
-	IN UCHAR Channel,
-	IN CHAR Rssi,
-	IN LARGE_INTEGER TimeStamp,
-	IN UCHAR CkipFlag,
-	IN PEDCA_PARM pEdcaParm,
-	IN PQOS_CAPABILITY_PARM pQosCapability,
-	IN PQBSS_LOAD_PARM pQbssLoad,
-	IN USHORT LengthVIE,
-	IN PNDIS_802_11_VARIABLE_IEs pVIE);
-
-ULONG  BssTableSetEntry(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT PBSS_TABLE pTab,
-	IN PUCHAR pBssid,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR BssType,
-	IN USHORT BeaconPeriod,
-	IN CF_PARM *CfParm,
-	IN USHORT AtimWin,
-	IN USHORT CapabilityInfo,
-	IN UCHAR SupRate[],
-	IN UCHAR SupRateLen,
-	IN UCHAR ExtRate[],
-	IN UCHAR ExtRateLen,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN ADD_HT_INFO_IE *pAddHtInfo,	// AP might use this additional ht info IE
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			AddHtInfoLen,
-	IN UCHAR			NewExtChanOffset,
-	IN UCHAR Channel,
-	IN CHAR Rssi,
-	IN LARGE_INTEGER TimeStamp,
-	IN UCHAR CkipFlag,
-	IN PEDCA_PARM pEdcaParm,
-	IN PQOS_CAPABILITY_PARM pQosCapability,
-	IN PQBSS_LOAD_PARM pQbssLoad,
-	IN USHORT LengthVIE,
-	IN PNDIS_802_11_VARIABLE_IEs pVIE);
-
-#ifdef DOT11_N_SUPPORT
-VOID BATableInsertEntry(
-    IN	PRTMP_ADAPTER	pAd,
-	IN USHORT Aid,
-    IN USHORT		TimeOutValue,
-	IN USHORT		StartingSeq,
-    IN UCHAR TID,
-	IN UCHAR BAWinSize,
-	IN UCHAR OriginatorStatus,
-    IN BOOLEAN IsRecipient);
-
-#ifdef DOT11N_DRAFT3
-VOID Bss2040CoexistTimeOut(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-
-VOID  TriEventInit(
-	IN	PRTMP_ADAPTER	pAd);
-
-ULONG TriEventTableSetEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT TRIGGER_EVENT_TAB *Tab,
-	IN PUCHAR pBssid,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			RegClass,
-	IN UCHAR ChannelNo);
-
-VOID TriEventCounterMaintenance(
-	IN	PRTMP_ADAPTER	pAd);
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-VOID BssTableSsidSort(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT BSS_TABLE *OutTab,
-	IN  CHAR Ssid[],
-	IN  UCHAR SsidLen);
-
-VOID  BssTableSortByRssi(
-	IN OUT BSS_TABLE *OutTab);
-
-VOID BssCipherParse(
-	IN OUT  PBSS_ENTRY  pBss);
-
-NDIS_STATUS  MlmeQueueInit(
-	IN MLME_QUEUE *Queue);
-
-VOID  MlmeQueueDestroy(
-	IN MLME_QUEUE *Queue);
-
-BOOLEAN MlmeEnqueue(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG Machine,
-	IN ULONG MsgType,
-	IN ULONG MsgLen,
-	IN VOID *Msg);
-
-BOOLEAN MlmeEnqueueForRecv(
-	IN  PRTMP_ADAPTER   pAd,
-	IN ULONG Wcid,
-	IN ULONG TimeStampHigh,
-	IN ULONG TimeStampLow,
-	IN UCHAR Rssi0,
-	IN UCHAR Rssi1,
-	IN UCHAR Rssi2,
-	IN ULONG MsgLen,
-	IN PVOID Msg,
-	IN UCHAR Signal);
-
-
-BOOLEAN MlmeDequeue(
-	IN MLME_QUEUE *Queue,
-	OUT MLME_QUEUE_ELEM **Elem);
-
-VOID    MlmeRestartStateMachine(
-	IN  PRTMP_ADAPTER   pAd);
-
-BOOLEAN  MlmeQueueEmpty(
-	IN MLME_QUEUE *Queue);
-
-BOOLEAN  MlmeQueueFull(
-	IN MLME_QUEUE *Queue);
-
-BOOLEAN  MsgTypeSubst(
-	IN PRTMP_ADAPTER pAd,
-	IN PFRAME_802_11 pFrame,
-	OUT INT *Machine,
-	OUT INT *MsgType);
-
-VOID StateMachineInit(
-	IN STATE_MACHINE *Sm,
-	IN STATE_MACHINE_FUNC Trans[],
-	IN ULONG StNr,
-	IN ULONG MsgNr,
-	IN STATE_MACHINE_FUNC DefFunc,
-	IN ULONG InitState,
-	IN ULONG Base);
-
-VOID StateMachineSetAction(
-	IN STATE_MACHINE *S,
-	IN ULONG St,
-	ULONG Msg,
-	IN STATE_MACHINE_FUNC F);
-
-VOID StateMachinePerformAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN STATE_MACHINE *S,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID Drop(
-	IN  PRTMP_ADAPTER   pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID AssocStateMachineInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  STATE_MACHINE *Sm,
-	OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID ReassocTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID AssocTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID DisassocTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-//----------------------------------------------
-VOID MlmeDisassocReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeAssocReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeReassocReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeDisassocReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerAssocRspAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerReassocRspAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerDisassocAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID DisassocTimeoutAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID AssocTimeoutAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID  ReassocTimeoutAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID  Cls3errAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR pAddr);
-
-VOID SwitchBetweenWepAndCkip(
-	IN PRTMP_ADAPTER pAd);
-
-VOID  InvalidStateWhenAssoc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID  InvalidStateWhenReassoc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID InvalidStateWhenDisassociate(
-	IN  PRTMP_ADAPTER pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-#ifdef RT2870
-VOID MlmeCntlConfirm(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG MsgType,
-	IN USHORT Msg);
-#endif // RT2870 //
-
-VOID  ComposePsPoll(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID  ComposeNullFrame(
-	IN  PRTMP_ADAPTER pAd);
-
-VOID  AssocPostProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR pAddr2,
-	IN  USHORT CapabilityInfo,
-	IN  USHORT Aid,
-	IN  UCHAR SupRate[],
-	IN  UCHAR SupRateLen,
-	IN  UCHAR ExtRate[],
-	IN  UCHAR ExtRateLen,
-	IN PEDCA_PARM pEdcaParm,
-	IN HT_CAPABILITY_IE		*pHtCapability,
-	IN  UCHAR HtCapabilityLen,
-	IN ADD_HT_INFO_IE		*pAddHtInfo);
-
-VOID AuthStateMachineInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN PSTATE_MACHINE sm,
-	OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID AuthTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID MlmeAuthReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerAuthRspAtSeq2Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerAuthRspAtSeq4Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID AuthTimeoutAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID Cls2errAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR pAddr);
-
-VOID MlmeDeauthReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID InvalidStateWhenAuth(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-//=============================================
-
-VOID AuthRspStateMachineInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PSTATE_MACHINE Sm,
-	IN  STATE_MACHINE_FUNC Trans[]);
-
-VOID PeerDeauthAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerAuthSimpleRspGenAndSend(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PHEADER_802_11  pHdr80211,
-	IN  USHORT Alg,
-	IN  USHORT Seq,
-	IN  USHORT Reason,
-	IN  USHORT Status);
-
-//
-// Private routines in dls.c
-//
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-void DlsStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID MlmeDlsReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerDlsReqAction(
-    IN PRTMP_ADAPTER	pAd,
-    IN MLME_QUEUE_ELEM	*Elem);
-
-VOID PeerDlsRspAction(
-    IN PRTMP_ADAPTER	pAd,
-    IN MLME_QUEUE_ELEM	*Elem);
-
-VOID MlmeDlsTearDownAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerDlsTearDownAction(
-    IN PRTMP_ADAPTER	pAd,
-    IN MLME_QUEUE_ELEM	*Elem);
-
-VOID RTMPCheckDLSTimeOut(
-	IN PRTMP_ADAPTER	pAd);
-
-BOOLEAN RTMPRcvFrameDLSCheck(
-	IN PRTMP_ADAPTER	pAd,
-	IN PHEADER_802_11	pHeader,
-	IN ULONG			Len,
-	IN PRT28XX_RXD_STRUC	pRxD);
-
-INT	RTMPCheckDLSFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA);
-
-VOID RTMPSendDLSTearDownFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA);
-
-NDIS_STATUS RTMPSendSTAKeyRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA);
-
-NDIS_STATUS RTMPSendSTAKeyHandShake(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA);
-
-VOID DlsTimeoutAction(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-BOOLEAN MlmeDlsReqSanity(
-	IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PRT_802_11_DLS *pDLS,
-    OUT PUSHORT pReason);
-
-INT Set_DlsEntryInfo_Display_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg);
-
-MAC_TABLE_ENTRY *MacTableInsertDlsEntry(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR	pAddr,
-	IN  UINT	DlsEntryIdx);
-
-BOOLEAN MacTableDeleteDlsEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT wcid,
-	IN PUCHAR pAddr);
-
-MAC_TABLE_ENTRY *DlsEntryTableLookup(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount);
-
-MAC_TABLE_ENTRY *DlsEntryTableLookupByWcid(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR	wcid,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount);
-
-INT	Set_DlsAddEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_DlsTearDownEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef QOS_DLS_SUPPORT
-BOOLEAN PeerDlsReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pDlsTimeout,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-    OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability);
-
-BOOLEAN PeerDlsRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pStatus,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-    OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability);
-
-BOOLEAN PeerDlsTearDownSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pReason);
-#endif // QOS_DLS_SUPPORT //
-
-//========================================
-
-VOID SyncStateMachineInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  STATE_MACHINE *Sm,
-	OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID BeaconTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID ScanTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID MlmeScanReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID InvalidStateWhenScan(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID InvalidStateWhenJoin(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID InvalidStateWhenStart(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerBeacon(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID EnqueueProbeRequest(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN ScanRunning(
-		IN PRTMP_ADAPTER pAd);
-//=========================================
-
-VOID MlmeCntlInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  STATE_MACHINE *S,
-	OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID MlmeCntlMachinePerformAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  STATE_MACHINE *S,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlIdleProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlOidScanProc(
-	IN  PRTMP_ADAPTER pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlOidSsidProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM * Elem);
-
-VOID CntlOidRTBssidProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM * Elem);
-
-VOID CntlMlmeRoamingProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM * Elem);
-
-VOID CntlWaitDisassocProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitJoinProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitReassocProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitStartProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitAuthProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitAuthProc2(
-	IN  PRTMP_ADAPTER pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitAssocProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-#ifdef QOS_DLS_SUPPORT
-VOID CntlOidDLSSetupProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-#endif // QOS_DLS_SUPPORT //
-
-VOID LinkUp(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR BssType);
-
-VOID LinkDown(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  BOOLEAN         IsReqFromAP);
-
-VOID IterateOnBssTab(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID IterateOnBssTab2(
-	IN  PRTMP_ADAPTER   pAd);;
-
-VOID JoinParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  OUT MLME_JOIN_REQ_STRUCT *JoinReq,
-	IN  ULONG BssIdx);
-
-VOID AssocParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN OUT MLME_ASSOC_REQ_STRUCT *AssocReq,
-	IN  PUCHAR pAddr,
-	IN  USHORT CapabilityInfo,
-	IN  ULONG Timeout,
-	IN  USHORT ListenIntv);
-
-VOID ScanParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  OUT MLME_SCAN_REQ_STRUCT *ScanReq,
-	IN  CHAR Ssid[],
-	IN  UCHAR SsidLen,
-	IN  UCHAR BssType,
-	IN  UCHAR ScanType);
-
-VOID DisassocParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  OUT MLME_DISASSOC_REQ_STRUCT *DisassocReq,
-	IN  PUCHAR pAddr,
-	IN  USHORT Reason);
-
-VOID StartParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  OUT MLME_START_REQ_STRUCT *StartReq,
-	IN  CHAR Ssid[],
-	IN  UCHAR SsidLen);
-
-VOID AuthParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  OUT MLME_AUTH_REQ_STRUCT *AuthReq,
-	IN  PUCHAR pAddr,
-	IN  USHORT Alg);
-
-VOID EnqueuePsPoll(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID EnqueueBeaconFrame(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID MlmeJoinReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeScanReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeStartReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID ScanTimeoutAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID BeaconTimeoutAtJoinAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerBeaconAtScanAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerBeaconAtJoinAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerBeacon(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerProbeReqAction(
-	IN  PRTMP_ADAPTER pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID ScanNextChannel(
-	IN  PRTMP_ADAPTER   pAd);
-
-ULONG MakeIbssBeacon(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID CCXAdjacentAPReport(
-	IN  PRTMP_ADAPTER   pAd);
-
-BOOLEAN MlmeScanReqSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT UCHAR *BssType,
-	OUT CHAR ssid[],
-	OUT UCHAR *SsidLen,
-	OUT UCHAR *ScanType);
-
-BOOLEAN PeerBeaconAndProbeRspSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	IN  UCHAR MsgChannel,
-	OUT PUCHAR pAddr2,
-	OUT PUCHAR pBssid,
-	OUT CHAR Ssid[],
-	OUT UCHAR *pSsidLen,
-	OUT UCHAR *pBssType,
-	OUT USHORT *pBeaconPeriod,
-	OUT UCHAR *pChannel,
-	OUT UCHAR *pNewChannel,
-	OUT LARGE_INTEGER *pTimestamp,
-	OUT CF_PARM *pCfParm,
-	OUT USHORT *pAtimWin,
-	OUT USHORT *pCapabilityInfo,
-	OUT UCHAR *pErp,
-	OUT UCHAR *pDtimCount,
-	OUT UCHAR *pDtimPeriod,
-	OUT UCHAR *pBcastFlag,
-	OUT UCHAR *pMessageToMe,
-	OUT UCHAR SupRate[],
-	OUT UCHAR *pSupRateLen,
-	OUT UCHAR ExtRate[],
-	OUT UCHAR *pExtRateLen,
-	OUT	UCHAR *pCkipFlag,
-	OUT	UCHAR *pAironetCellPowerLimit,
-	OUT PEDCA_PARM       pEdcaParm,
-	OUT PQBSS_LOAD_PARM  pQbssLoad,
-	OUT PQOS_CAPABILITY_PARM pQosCapability,
-	OUT ULONG *pRalinkIe,
-	OUT UCHAR		 *pHtCapabilityLen,
-#ifdef CONFIG_STA_SUPPORT
-	OUT UCHAR		 *pPreNHtCapabilityLen,
-#endif // CONFIG_STA_SUPPORT //
-	OUT HT_CAPABILITY_IE *pHtCapability,
-	OUT UCHAR		 *AddHtInfoLen,
-	OUT ADD_HT_INFO_IE *AddHtInfo,
-	OUT UCHAR *NewExtChannel,
-	OUT USHORT *LengthVIE,
-	OUT PNDIS_802_11_VARIABLE_IEs pVIE);
-
-BOOLEAN PeerAddBAReqActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *pMsg,
-    IN ULONG MsgLen,
-	OUT PUCHAR pAddr2);
-
-BOOLEAN PeerAddBARspActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *pMsg,
-    IN ULONG MsgLen);
-
-BOOLEAN PeerDelBAActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN UCHAR Wcid,
-    IN VOID *pMsg,
-    IN ULONG MsgLen);
-
-BOOLEAN MlmeAssocReqSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pApAddr,
-	OUT USHORT *CapabilityInfo,
-	OUT ULONG *Timeout,
-	OUT USHORT *ListenIntv);
-
-BOOLEAN MlmeAuthReqSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr,
-	OUT ULONG *Timeout,
-	OUT USHORT *Alg);
-
-BOOLEAN MlmeStartReqSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT CHAR Ssid[],
-	OUT UCHAR *Ssidlen);
-
-BOOLEAN PeerAuthSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr,
-	OUT USHORT *Alg,
-	OUT USHORT *Seq,
-	OUT USHORT *Status,
-	OUT CHAR ChlgText[]);
-
-BOOLEAN PeerAssocRspSanity(
-	IN  PRTMP_ADAPTER   pAd,
-    IN VOID *pMsg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr2,
-	OUT USHORT *pCapabilityInfo,
-	OUT USHORT *pStatus,
-	OUT USHORT *pAid,
-	OUT UCHAR SupRate[],
-	OUT UCHAR *pSupRateLen,
-	OUT UCHAR ExtRate[],
-	OUT UCHAR *pExtRateLen,
-    OUT HT_CAPABILITY_IE		*pHtCapability,
-    OUT ADD_HT_INFO_IE		*pAddHtInfo,	// AP might use this additional ht info IE
-    OUT UCHAR			*pHtCapabilityLen,
-    OUT UCHAR			*pAddHtInfoLen,
-    OUT UCHAR			*pNewExtChannelOffset,
-	OUT PEDCA_PARM pEdcaParm,
-	OUT UCHAR *pCkipFlag);
-
-BOOLEAN PeerDisassocSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr2,
-	OUT USHORT *Reason);
-
-BOOLEAN PeerWpaMessageSanity(
-    IN 	PRTMP_ADAPTER 		pAd,
-    IN 	PEAPOL_PACKET 		pMsg,
-    IN 	ULONG 				MsgLen,
-    IN 	UCHAR				MsgType,
-    IN 	MAC_TABLE_ENTRY  	*pEntry);
-
-BOOLEAN PeerDeauthSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr2,
-	OUT USHORT *Reason);
-
-BOOLEAN PeerProbeReqSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr2,
-	OUT CHAR Ssid[],
-	OUT UCHAR *pSsidLen);
-
-BOOLEAN GetTimBit(
-	IN  CHAR *Ptr,
-	IN  USHORT Aid,
-	OUT UCHAR *TimLen,
-	OUT UCHAR *BcastFlag,
-	OUT UCHAR *DtimCount,
-	OUT UCHAR *DtimPeriod,
-	OUT UCHAR *MessageToMe);
-
-UCHAR ChannelSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR channel);
-
-NDIS_802_11_NETWORK_TYPE NetworkTypeInUseSanity(
-	IN PBSS_ENTRY pBss);
-
-#if 0	// It's omitted
-NDIS_STATUS	RTMPWepKeySanity(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PVOID			pBuf);
-#endif
-
-BOOLEAN MlmeDelBAReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen);
-
-BOOLEAN MlmeAddBAReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2);
-
-ULONG MakeOutgoingFrame(
-	OUT CHAR *Buffer,
-	OUT ULONG *Length, ...);
-
-VOID  LfsrInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  ULONG Seed);
-
-UCHAR RandomByte(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID AsicUpdateAutoFallBackTable(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pTxRate);
-
-VOID  MlmePeriodicExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID LinkDownExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID LinkUpExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID STAMlmePeriodicExec(
-	PRTMP_ADAPTER pAd);
-
-VOID MlmeAutoScan(
-	IN PRTMP_ADAPTER pAd);
-
-VOID MlmeAutoReconnectLastSSID(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN MlmeValidateSSID(
-	IN PUCHAR pSsid,
-	IN UCHAR  SsidLen);
-
-VOID MlmeCheckForRoaming(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG    Now32);
-
-VOID MlmeCheckForFastRoaming(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  ULONG           Now);
-
-VOID MlmeDynamicTxRateSwitching(
-	IN PRTMP_ADAPTER pAd);
-
-VOID MlmeSetTxRate(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PRTMP_TX_RATE_SWITCH	pTxRate);
-
-VOID MlmeSelectTxRateTable(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PUCHAR				*ppTable,
-	IN PUCHAR				pTableSize,
-	IN PUCHAR				pInitTxRateIdx);
-
-VOID MlmeCalculateChannelQuality(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG Now);
-
-VOID MlmeCheckPsmChange(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG    Now32);
-
-VOID MlmeSetPsmBit(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT psm);
-
-VOID MlmeSetTxPreamble(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT TxPreamble);
-
-VOID UpdateBasicRateBitmap(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID MlmeUpdateTxRates(
-	IN PRTMP_ADAPTER 	pAd,
-	IN 	BOOLEAN		 	bLinkUp,
-	IN	UCHAR			apidx);
-
-#ifdef DOT11_N_SUPPORT
-VOID MlmeUpdateHtTxRates(
-	IN PRTMP_ADAPTER 		pAd,
-	IN	UCHAR				apidx);
-#endif // DOT11_N_SUPPORT //
-
-VOID    RTMPCheckRates(
-	IN      PRTMP_ADAPTER   pAd,
-	IN OUT  UCHAR           SupRate[],
-	IN OUT  UCHAR           *SupRateLen);
-
-#ifdef CONFIG_STA_SUPPORT
-BOOLEAN RTMPCheckChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		CentralChannel,
-	IN UCHAR		Channel);
-#endif // CONFIG_STA_SUPPORT //
-
-BOOLEAN 	RTMPCheckHt(
-	IN		PRTMP_ADAPTER	pAd,
-	IN		UCHAR	Wcid,
-	IN OUT	HT_CAPABILITY_IE			*pHtCapability,
-	IN OUT	ADD_HT_INFO_IE			*pAddHtInfo);
-
-VOID StaQuickResponeForRateUpExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID AsicBbpTuning1(
-	IN PRTMP_ADAPTER pAd);
-
-VOID AsicBbpTuning2(
-	IN PRTMP_ADAPTER pAd);
-
-VOID RTMPUpdateMlmeRate(
-	IN PRTMP_ADAPTER	pAd);
-
-CHAR RTMPMaxRssi(
-	IN PRTMP_ADAPTER	pAd,
-	IN CHAR				Rssi0,
-	IN CHAR				Rssi1,
-	IN CHAR				Rssi2);
-
-VOID AsicEvaluateRxAnt(
-	IN PRTMP_ADAPTER	pAd);
-
-VOID AsicRxAntEvalTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID APSDPeriodicExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-BOOLEAN RTMPCheckEntryEnableAutoRateSwitch(
-	IN PRTMP_ADAPTER    pAd,
-	IN PMAC_TABLE_ENTRY	pEntry);
-
-UCHAR RTMPStaFixedTxMode(
-	IN PRTMP_ADAPTER    pAd,
-	IN PMAC_TABLE_ENTRY	pEntry);
-
-VOID RTMPUpdateLegacyTxSetting(
-		UCHAR				fixed_tx_mode,
-		PMAC_TABLE_ENTRY	pEntry);
-
-BOOLEAN RTMPAutoRateSwitchCheck(
-	IN PRTMP_ADAPTER    pAd);
-
-NDIS_STATUS MlmeInit(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID MlmeHandler(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID MlmeHalt(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID MlmeResetRalinkCounters(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID BuildChannelList(
-	IN PRTMP_ADAPTER pAd);
-
-UCHAR FirstChannel(
-	IN  PRTMP_ADAPTER   pAd);
-
-UCHAR NextChannel(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR channel);
-
-VOID ChangeToCellPowerLimit(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR         AironetCellPowerLimit);
-
-VOID RaiseClock(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UINT32 *x);
-
-VOID LowerClock(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UINT32 *x);
-
-USHORT ShiftInBits(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID ShiftOutBits(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  USHORT data,
-	IN  USHORT count);
-
-VOID EEpromCleanup(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID EWDS(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID EWEN(
-	IN  PRTMP_ADAPTER   pAd);
-
-USHORT RTMP_EEPROM_READ16(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  USHORT Offset);
-
-VOID RTMP_EEPROM_WRITE16(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  USHORT Offset,
-	IN  USHORT Data);
-
-//
-// Prototypes of function definition in rtmp_tkip.c
-//
-VOID    RTMPInitTkipEngine(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pTKey,
-	IN  UCHAR           KeyId,
-	IN  PUCHAR          pTA,
-	IN  PUCHAR          pMICKey,
-	IN  PUCHAR          pTSC,
-	OUT PULONG          pIV16,
-	OUT PULONG          pIV32);
-
-VOID    RTMPInitMICEngine(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pKey,
-	IN  PUCHAR          pDA,
-	IN  PUCHAR          pSA,
-	IN  UCHAR           UserPriority,
-	IN  PUCHAR          pMICKey);
-
-BOOLEAN RTMPTkipCompareMICValue(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pSrc,
-	IN  PUCHAR          pDA,
-	IN  PUCHAR          pSA,
-	IN  PUCHAR          pMICKey,
-	IN	UCHAR			UserPriority,
-	IN  UINT            Len);
-
-VOID    RTMPCalculateMICValue(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PNDIS_PACKET    pPacket,
-	IN  PUCHAR          pEncap,
-	IN  PCIPHER_KEY     pKey,
-	IN	UCHAR			apidx);
-
-BOOLEAN RTMPTkipCompareMICValueWithLLC(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pLLC,
-	IN  PUCHAR          pSrc,
-	IN  PUCHAR          pDA,
-	IN  PUCHAR          pSA,
-	IN  PUCHAR          pMICKey,
-	IN  UINT            Len);
-
-VOID    RTMPTkipAppendByte(
-	IN  PTKIP_KEY_INFO  pTkip,
-	IN  UCHAR           uChar);
-
-VOID    RTMPTkipAppend(
-	IN  PTKIP_KEY_INFO  pTkip,
-	IN  PUCHAR          pSrc,
-	IN  UINT            nBytes);
-
-VOID    RTMPTkipGetMIC(
-	IN  PTKIP_KEY_INFO  pTkip);
-
-BOOLEAN RTMPSoftDecryptTKIP(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pData,
-	IN ULONG	DataByteCnt,
-	IN UCHAR    UserPriority,
-	IN PCIPHER_KEY	pWpaKey);
-
-BOOLEAN RTMPSoftDecryptAES(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pData,
-	IN ULONG	DataByteCnt,
-	IN PCIPHER_KEY	pWpaKey);
-
-#if 0	// removed by AlbertY
-NDIS_STATUS RTMPWPAAddKeyProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PVOID           pBuf);
-#endif
-
-//
-// Prototypes of function definition in cmm_info.c
-//
-NDIS_STATUS RTMPWPARemoveKeyProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PVOID           pBuf);
-
-VOID    RTMPWPARemoveAllKeys(
-	IN  PRTMP_ADAPTER   pAd);
-
-BOOLEAN RTMPCheckStrPrintAble(
-    IN  CHAR *pInPutStr,
-    IN  UCHAR strLen);
-
-VOID    RTMPSetPhyMode(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  ULONG phymode);
-
-VOID	RTMPUpdateHTIE(
-	IN	RT_HT_CAPABILITY	*pRtHt,
-	IN		UCHAR				*pMcsSet,
-	OUT		HT_CAPABILITY_IE *pHtCapability,
-	OUT		ADD_HT_INFO_IE		*pAddHtInfo);
-
-VOID	RTMPAddWcidAttributeEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BssIdx,
-	IN 	UCHAR		 	KeyIdx,
-	IN 	UCHAR		 	CipherAlg,
-	IN 	MAC_TABLE_ENTRY *pEntry);
-
-CHAR *GetEncryptType(
-	CHAR enc);
-
-CHAR *GetAuthMode(
-	CHAR auth);
-
-VOID RTMPIoctlGetSiteSurvey(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID RTMPIoctlGetMacTable(
-	IN PRTMP_ADAPTER pAd,
-	IN struct iwreq *wrq);
-
-VOID RTMPIndicateWPA2Status(
-	IN  PRTMP_ADAPTER  pAdapter);
-
-VOID	RTMPOPModeSwitching(
-	IN	PRTMP_ADAPTER	pAd);
-
-#ifdef CONFIG_STA_SUPPORT
-VOID    RTMPAddBSSIDCipher(
-    IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR	Aid,
-    IN  PNDIS_802_11_KEY    pKey,
-    IN  UCHAR   CipherAlg);
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-VOID	RTMPSetHT(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	OID_SET_HT_PHYMODE *pHTPhyMode);
-
-VOID	RTMPSetIndividualHT(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	UCHAR				apidx);
-#endif // DOT11_N_SUPPORT //
-
-VOID RTMPSendWirelessEvent(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Event_flag,
-	IN	PUCHAR 			pAddr,
-	IN  UCHAR			BssIdx,
-	IN	CHAR			Rssi);
-
-VOID	NICUpdateCntlCounters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PHEADER_802_11	pHeader,
-	IN    UCHAR			SubType,
-	IN	PRXWI_STRUC 	pRxWI);
-//
-// prototype in wpa.c
-//
-BOOLEAN WpaMsgTypeSubst(
-	IN  UCHAR   EAPType,
-	OUT INT		*MsgType);
-
-VOID WpaPskStateMachineInit(
-	IN  PRTMP_ADAPTER       pAd,
-	IN  STATE_MACHINE       *S,
-	OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID WpaEAPOLKeyAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    WpaPairMsg1Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    WpaPairMsg3Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    WpaGroupMsg1Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    WpaMacHeaderInit(
-	IN      PRTMP_ADAPTER   pAd,
-	IN OUT  PHEADER_802_11  pHdr80211,
-	IN      UCHAR           wep,
-	IN      PUCHAR          pAddr1);
-
-VOID    Wpa2PairMsg1Action(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    Wpa2PairMsg3Action(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-BOOLEAN ParseKeyData(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pKeyData,
-    IN  UCHAR           KeyDataLen,
-	IN	UCHAR			bPairewise);
-
-VOID    RTMPToWirelessSta(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pHeader802_3,
-    IN  UINT            HdrLen,
-	IN  PUCHAR          pData,
-    IN  UINT            DataLen,
-    IN	BOOLEAN			is4wayFrame);
-
-VOID    HMAC_SHA1(
-	IN  UCHAR   *text,
-	IN  UINT    text_len,
-	IN  UCHAR   *key,
-	IN  UINT    key_len,
-	IN  UCHAR   *digest);
-
-VOID    PRF(
-	IN  UCHAR   *key,
-	IN  INT     key_len,
-	IN  UCHAR   *prefix,
-	IN  INT     prefix_len,
-	IN  UCHAR   *data,
-	IN  INT     data_len,
-	OUT UCHAR   *output,
-	IN  INT     len);
-
-VOID    CCKMPRF(
-	IN  UCHAR   *key,
-	IN  INT     key_len,
-	IN  UCHAR   *data,
-	IN  INT     data_len,
-	OUT UCHAR   *output,
-	IN  INT     len);
-
-VOID WpaCountPTK(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR   *PMK,
-	IN  UCHAR   *ANonce,
-	IN  UCHAR   *AA,
-	IN  UCHAR   *SNonce,
-	IN  UCHAR   *SA,
-	OUT UCHAR   *output,
-	IN  UINT    len);
-
-VOID    GenRandom(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			*macAddr,
-	OUT	UCHAR			*random);
-
-//
-// prototype in aironet.c
-//
-VOID    AironetStateMachineInit(
-	IN  PRTMP_ADAPTER       pAd,
-	IN  STATE_MACHINE       *S,
-	OUT STATE_MACHINE_FUNC  Trans[]);
-
-VOID    AironetMsgAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    AironetRequestAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    ChannelLoadRequestAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    NoiseHistRequestAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    BeaconRequestAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    AironetReportAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    ChannelLoadReportAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    NoiseHistReportAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    AironetFinalReportAction(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID    BeaconReportAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    AironetAddBeaconReport(
-	IN  PRTMP_ADAPTER       pAd,
-	IN  ULONG               Index,
-	IN  PMLME_QUEUE_ELEM    pElem);
-
-VOID    AironetCreateBeaconReportFromBssTable(
-	IN  PRTMP_ADAPTER       pAd);
-
-VOID    DBGPRINT_TX_RING(
-	IN PRTMP_ADAPTER  pAd,
-	IN UCHAR          QueIdx);
-
-VOID DBGPRINT_RX_RING(
-	IN PRTMP_ADAPTER  pAd);
-
-CHAR    ConvertToRssi(
-	IN PRTMP_ADAPTER  pAd,
-	IN CHAR				Rssi,
-	IN UCHAR    RssiNumber);
-
-
-#ifdef DOT11N_DRAFT3
-VOID BuildEffectedChannelList(
-	IN PRTMP_ADAPTER pAd);
-#endif // DOT11N_DRAFT3 //
-
-
-VOID APAsicEvaluateRxAnt(
-	IN PRTMP_ADAPTER	pAd);
-
-
-VOID APAsicRxAntEvalTimeout(
-	IN PRTMP_ADAPTER	pAd);
-
-//
-// function prototype in cmm_wpa.c
-//
-BOOLEAN RTMPCheckWPAframe(
-	IN PRTMP_ADAPTER pAd,
-	IN PMAC_TABLE_ENTRY	pEntry,
-	IN PUCHAR 			pData,
-	IN ULONG 			DataByteCount,
-	IN UCHAR			FromWhichBSSID);
-
-VOID AES_GTK_KEY_UNWRAP(
-	IN  UCHAR   *key,
-	OUT UCHAR   *plaintext,
-	IN	UCHAR	c_len,
-	IN  UCHAR   *ciphertext);
-
-BOOLEAN RTMPCheckRSNIE(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pData,
-	IN  UCHAR           DataLen,
-	IN  MAC_TABLE_ENTRY *pEntry,
-	OUT	UCHAR			*Offset);
-
-BOOLEAN RTMPParseEapolKeyData(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pKeyData,
-	IN  UCHAR           KeyDataLen,
-	IN	UCHAR			GroupKeyIndex,
-	IN	UCHAR			MsgType,
-	IN	BOOLEAN			bWPA2,
-	IN  MAC_TABLE_ENTRY *pEntry);
-
-VOID	ConstructEapolMsg(
-	IN 	PRTMP_ADAPTER    	pAd,
-    IN 	UCHAR				PeerAuthMode,
-    IN 	UCHAR				PeerWepStatus,
-    IN 	UCHAR				MyGroupKeyWepStatus,
-    IN 	UCHAR				MsgType,
-    IN	UCHAR				DefaultKeyIdx,
-    IN 	UCHAR				*ReplayCounter,
-	IN 	UCHAR				*KeyNonce,
-	IN	UCHAR				*TxRSC,
-	IN	UCHAR				*PTK,
-	IN	UCHAR				*GTK,
-	IN	UCHAR				*RSNIE,
-	IN	UCHAR				RSNIE_Len,
-    OUT PEAPOL_PACKET       pMsg);
-
-VOID	CalculateMIC(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			PeerWepStatus,
-	IN	UCHAR			*PTK,
-	OUT PEAPOL_PACKET   pMsg);
-
-NDIS_STATUS	RTMPSoftDecryptBroadCastData(
-	IN	PRTMP_ADAPTER					pAd,
-	IN	RX_BLK							*pRxBlk,
-	IN  NDIS_802_11_ENCRYPTION_STATUS 	GroupCipher,
-	IN  PCIPHER_KEY						pShard_key);
-
-VOID	ConstructEapolKeyData(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			PeerAuthMode,
-	IN	UCHAR			PeerWepStatus,
-	IN	UCHAR			GroupKeyWepStatus,
-	IN 	UCHAR			MsgType,
-	IN	UCHAR			DefaultKeyIdx,
-	IN	BOOLEAN			bWPA2Capable,
-	IN	UCHAR			*PTK,
-	IN	UCHAR			*GTK,
-	IN	UCHAR			*RSNIE,
-	IN	UCHAR			RSNIE_LEN,
-	OUT PEAPOL_PACKET   pMsg);
-
-VOID RTMPMakeRSNIE(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UINT            AuthMode,
-	IN  UINT            WepStatus,
-	IN	UCHAR			apidx);
-
-//
-// function prototype in ap_wpa.c
-//
-
-BOOLEAN APWpaMsgTypeSubst(
-	IN UCHAR    EAPType,
-	OUT INT *MsgType) ;
-
-MAC_TABLE_ENTRY *PACInquiry(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  ULONG           Wcid);
-
-BOOLEAN RTMPCheckMcast(
-	IN PRTMP_ADAPTER pAd,
-	IN PEID_STRUCT      eid_ptr,
-	IN MAC_TABLE_ENTRY  *pEntry);
-
-BOOLEAN RTMPCheckUcast(
-	IN PRTMP_ADAPTER pAd,
-	IN PEID_STRUCT      eid_ptr,
-	IN MAC_TABLE_ENTRY  *pEntry);
-
-BOOLEAN RTMPCheckAUTH(
-	IN PRTMP_ADAPTER pAd,
-	IN PEID_STRUCT      eid_ptr,
-	IN MAC_TABLE_ENTRY  *pEntry);
-
-VOID WPAStart4WayHS(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MAC_TABLE_ENTRY *pEntry,
-	IN	ULONG			TimeInterval);
-
-VOID WPAStart2WayGroupHS(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MAC_TABLE_ENTRY *pEntry);
-
-VOID APWpaEAPPacketAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APWpaEAPOLStartAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APWpaEAPOLLogoffAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APWpaEAPOLKeyAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APWpaEAPOLASFAlertAction(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  MLME_QUEUE_ELEM  *Elem);
-
-VOID HandleCounterMeasure(
-	IN PRTMP_ADAPTER pAd,
-	IN MAC_TABLE_ENTRY  *pEntry);
-
-VOID PeerPairMsg2Action(
-	IN PRTMP_ADAPTER pAd,
-	IN MAC_TABLE_ENTRY  *pEntry,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerPairMsg4Action(
-	IN PRTMP_ADAPTER pAd,
-	IN MAC_TABLE_ENTRY  *pEntry,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID CMTimerExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID WPARetryExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID EnqueueStartForPSKExec(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-VOID RTMPHandleSTAKey(
-    IN PRTMP_ADAPTER    pAdapter,
-    IN MAC_TABLE_ENTRY  *pEntry,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-#if 0 // merge into PeerPairMsg4Action
-VOID Wpa1PeerPairMsg4Action(
-	IN PRTMP_ADAPTER pAd,
-	IN MAC_TABLE_ENTRY  *pEntry,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID Wpa2PeerPairMsg4Action(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  PMAC_TABLE_ENTRY pEntry,
-	IN  MLME_QUEUE_ELEM  *Elem);
-#endif // 0 //
-
-VOID PeerGroupMsg2Action(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  PMAC_TABLE_ENTRY pEntry,
-	IN  VOID             *Msg,
-	IN  UINT             MsgLen);
-
-#if 0	// replaced by WPAStart2WayGroupHS
-NDIS_STATUS APWpaHardTransmit(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  PMAC_TABLE_ENTRY pEntry);
-#endif // 0 //
-
-VOID PairDisAssocAction(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  PMAC_TABLE_ENTRY pEntry,
-	IN  USHORT           Reason);
-
-VOID MlmeDeAuthAction(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  PMAC_TABLE_ENTRY pEntry,
-	IN  USHORT           Reason);
-
-VOID GREKEYPeriodicExec(
-	IN  PVOID   SystemSpecific1,
-	IN  PVOID   FunctionContext,
-	IN  PVOID   SystemSpecific2,
-	IN  PVOID   SystemSpecific3);
-
-VOID CountGTK(
-	IN  UCHAR   *PMK,
-	IN  UCHAR   *GNonce,
-	IN  UCHAR   *AA,
-	OUT UCHAR   *output,
-	IN  UINT    len);
-
-VOID    GetSmall(
-	IN  PVOID   pSrc1,
-	IN  PVOID   pSrc2,
-	OUT PUCHAR  out,
-	IN  ULONG   Length);
-
-VOID    GetLarge(
-	IN  PVOID   pSrc1,
-	IN  PVOID   pSrc2,
-	OUT PUCHAR  out,
-	IN  ULONG   Length);
-
-VOID APGenRandom(
-	IN PRTMP_ADAPTER pAd,
-	OUT UCHAR       *random);
-
-VOID AES_GTK_KEY_WRAP(
-	IN UCHAR *key,
-	IN UCHAR *plaintext,
-	IN UCHAR p_len,
-	OUT UCHAR *ciphertext);
-
-VOID    WpaSend(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          pPacket,
-    IN  ULONG           Len);
-
-VOID    APToWirelessSta(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MAC_TABLE_ENTRY *pEntry,
-	IN  PUCHAR          pHeader802_3,
-	IN  UINT            HdrLen,
-	IN  PUCHAR          pData,
-	IN  UINT            DataLen,
-    IN	BOOLEAN			bClearFrame);
-
-VOID RTMPAddPMKIDCache(
-	IN  PRTMP_ADAPTER   		pAd,
-	IN	INT						apidx,
-	IN	PUCHAR				pAddr,
-	IN	UCHAR					*PMKID,
-	IN	UCHAR					*PMK);
-
-INT RTMPSearchPMKIDCache(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	INT				apidx,
-	IN	PUCHAR		pAddr);
-
-VOID RTMPDeletePMKIDCache(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	INT				apidx,
-	IN  INT				idx);
-
-VOID RTMPMaintainPMKIDCache(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID	RTMPSendTriggerFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PVOID			pBuffer,
-	IN	ULONG			Length,
-	IN  UCHAR           TxRate,
-	IN	BOOLEAN			bQosNull);
-
-
-//typedef void (*TIMER_FUNCTION)(unsigned long);
-
-
-/* timeout -- ms */
-VOID RTMP_SetPeriodicTimer(
-	IN	NDIS_MINIPORT_TIMER *pTimer,
-	IN	unsigned long timeout);
-
-VOID RTMP_OS_Init_Timer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	NDIS_MINIPORT_TIMER *pTimer,
-	IN	TIMER_FUNCTION function,
-	IN	PVOID data);
-
-VOID RTMP_OS_Add_Timer(
-	IN	NDIS_MINIPORT_TIMER	*pTimer,
-	IN	unsigned long timeout);
-
-VOID RTMP_OS_Mod_Timer(
-	IN	NDIS_MINIPORT_TIMER	*pTimer,
-	IN	unsigned long timeout);
-
-
-VOID RTMP_OS_Del_Timer(
-	IN	NDIS_MINIPORT_TIMER	*pTimer,
-	OUT	BOOLEAN				 *pCancelled);
-
-
-VOID RTMP_OS_Release_Packet(
-	IN	PRTMP_ADAPTER pAd,
-	IN	PQUEUE_ENTRY  pEntry);
-
-VOID RTMPusecDelay(
-	IN	ULONG	usec);
-
-NDIS_STATUS os_alloc_mem(
-	IN	PRTMP_ADAPTER pAd,
-	OUT	PUCHAR *mem,
-	IN	ULONG  size);
-
-NDIS_STATUS os_free_mem(
-	IN	PRTMP_ADAPTER pAd,
-	IN	PUCHAR mem);
-
-
-void RTMP_AllocateSharedMemory(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-VOID RTMPFreeTxRxRingMemory(
-    IN  PRTMP_ADAPTER   pAd);
-
-NDIS_STATUS AdapterBlockAllocateMemory(
-	IN PVOID	handle,
-	OUT	PVOID	*ppAd);
-
-void RTMP_AllocateTxDescMemory(
-	IN	PRTMP_ADAPTER pAd,
-	IN	UINT	Index,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-void RTMP_AllocateFirstTxBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	UINT	Index,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-void RTMP_AllocateMgmtDescMemory(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-void RTMP_AllocateRxDescMemory(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-PNDIS_PACKET RTMP_AllocateRxPacketBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-PNDIS_PACKET RTMP_AllocateTxPacketBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress);
-
-PNDIS_PACKET RTMP_AllocateFragPacketBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length);
-
-void RTMP_QueryPacketInfo(
-	IN  PNDIS_PACKET pPacket,
-	OUT PACKET_INFO  *pPacketInfo,
-	OUT PUCHAR		 *pSrcBufVA,
-	OUT	UINT		 *pSrcBufLen);
-
-void RTMP_QueryNextPacketInfo(
-	IN  PNDIS_PACKET *ppPacket,
-	OUT PACKET_INFO  *pPacketInfo,
-	OUT PUCHAR		 *pSrcBufVA,
-	OUT	UINT		 *pSrcBufLen);
-
-
-BOOLEAN RTMP_FillTxBlkInfo(
-	IN RTMP_ADAPTER *pAd,
-	IN TX_BLK *pTxBlk);
-
-
-PRTMP_SCATTER_GATHER_LIST
-rt_get_sg_list_from_packet(PNDIS_PACKET pPacket, RTMP_SCATTER_GATHER_LIST *sg);
-
-
- void announce_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket);
-
-
-UINT BA_Reorder_AMSDU_Annnounce(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket);
-
-
-UINT Handle_AMSDU_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	IN  UCHAR			FromWhichBSSID);
-
-
-void convert_802_11_to_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR			p8023hdr,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	IN  UCHAR			FromWhichBSSID);
-
-
-PNET_DEV get_netdev_from_bssid(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			FromWhichBSSID);
-
-
-PNDIS_PACKET duplicate_pkt(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pHeader802_3,
-    IN  UINT            HdrLen,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	IN	UCHAR			FromWhichBSSID);
-
-
-PNDIS_PACKET duplicate_pkt_with_TKIP_MIC(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pOldPkt);
-
-PNDIS_PACKET duplicate_pkt_with_VLAN(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pHeader802_3,
-    IN  UINT            HdrLen,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	IN	UCHAR			FromWhichBSSID);
-
-PNDIS_PACKET duplicate_pkt_with_WPI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UINT32			ext_head_len,
-	IN	UINT32			ext_tail_len);
-
-UCHAR VLAN_8023_Header_Copy(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pHeader802_3,
-	IN	UINT            HdrLen,
-	OUT PUCHAR			pData,
-	IN	UCHAR			FromWhichBSSID);
-
-#ifdef DOT11_N_SUPPORT
-void ba_flush_reordering_timeout_mpdus(
-	IN PRTMP_ADAPTER	pAd,
-	IN PBA_REC_ENTRY	pBAEntry,
-	IN ULONG			Now32);
-
-
-VOID BAOriSessionSetUp(
-			IN PRTMP_ADAPTER    pAd,
-			IN MAC_TABLE_ENTRY	*pEntry,
-			IN UCHAR			TID,
-			IN USHORT			TimeOut,
-			IN ULONG			DelayTime,
-			IN BOOLEAN		isForced);
-
-VOID BASessionTearDownALL(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		UCHAR Wcid);
-#endif // DOT11_N_SUPPORT //
-
-BOOLEAN OS_Need_Clone_Packet(void);
-
-
-VOID build_tx_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR	pFrame,
-	IN	ULONG	FrameLen);
-
-
-VOID BAOriSessionTearDown(
-	IN OUT	PRTMP_ADAPTER	pAd,
-	IN		UCHAR			Wcid,
-	IN		UCHAR			TID,
-	IN		BOOLEAN			bPassive,
-	IN		BOOLEAN			bForceSend);
-
-VOID BARecSessionTearDown(
-	IN OUT	PRTMP_ADAPTER	pAd,
-	IN		UCHAR			Wcid,
-	IN		UCHAR			TID,
-	IN		BOOLEAN			bPassive);
-
-BOOLEAN ba_reordering_resource_init(PRTMP_ADAPTER pAd, int num);
-void ba_reordering_resource_release(PRTMP_ADAPTER pAd);
-
-ULONG AutoChBssInsertEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pBssid,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR ChannelNo,
-	IN CHAR Rssi);
-
-void AutoChBssTableInit(
-	IN PRTMP_ADAPTER pAd);
-
-void ChannelInfoInit(
-	IN PRTMP_ADAPTER pAd);
-
-void AutoChBssTableDestroy(
-	IN PRTMP_ADAPTER pAd);
-
-void ChannelInfoDestroy(
-	IN PRTMP_ADAPTER pAd);
-
-UCHAR New_ApAutoSelectChannel(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN rtstrmactohex(
-	IN char *s1,
-	IN char *s2);
-
-BOOLEAN rtstrcasecmp(
-	IN char *s1,
-	IN char *s2);
-
-char *rtstrstruncasecmp(
-	IN char *s1,
-	IN char *s2);
-
-char    *rtstrstr(
-	IN	const char * s1,
-	IN	const char * s2);
-
-char *rstrtok(
-	IN char * s,
-	IN const char * ct);
-
-int rtinet_aton(
-	const char *cp,
-	unsigned int *addr);
-
-////////// common ioctl functions //////////
-INT Set_DriverVersion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_CountryRegion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_CountryRegionABand_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_WirelessMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_Channel_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ShortSlot_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_TxPower_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_BGProtection_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-
-INT Set_TxPreamble_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-
-INT Set_RTSThreshold_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-
-INT Set_FragThreshold_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-
-INT Set_TxBurst_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-
-#ifdef AGGREGATION_SUPPORT
-INT	Set_PktAggregate_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-#endif
-
-INT	Set_IEEE80211H_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#ifdef DBG
-INT	Set_Debug_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif
-
-INT	Show_DescInfo_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ResetStatCounter_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#ifdef DOT11_N_SUPPORT
-INT	Set_BASetup_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_BADecline_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_BAOriTearDown_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_BARecTearDown_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtBw_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtMcs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtGi_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtOpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtStbc_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtHtc_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtExtcha_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtMpduDensity_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtBaWinSize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtRdg_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtLinkAdapt_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtAmsdu_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtAutoBa_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtProtect_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtMimoPs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-
-INT	Set_ForceShortGI_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ForceGF_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	SetCommonHT(
-	IN	PRTMP_ADAPTER	pAd);
-
-INT	Set_SendPSMPAction_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtMIMOPSmode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-
-INT	Set_HtTxBASize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // DOT11_N_SUPPORT //
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-//Dls ,	kathy
-VOID RTMPSendDLSTearDownFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA);
-
-#ifdef DOT11_N_SUPPORT
-//Block ACK
-VOID QueryBATABLE(
-	IN  PRTMP_ADAPTER pAd,
-	OUT PQUERYBA_TABLE pBAT);
-#endif // DOT11_N_SUPPORT //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-INT	    WpaCheckEapCode(
-	IN  PRTMP_ADAPTER   	pAd,
-	IN  PUCHAR				pFrame,
-	IN  USHORT				FrameLen,
-	IN  USHORT				OffSet);
-
-VOID    WpaSendMicFailureToWpaSupplicant(
-    IN  PRTMP_ADAPTER       pAd,
-    IN  BOOLEAN             bUnicast);
-
-VOID    SendAssocIEsToWpaSupplicant(
-    IN  PRTMP_ADAPTER       pAd);
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-int wext_notify_event_assoc(
-	IN  RTMP_ADAPTER *pAd);
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-#ifdef DOT11_N_SUPPORT
-VOID Handle_BSS_Width_Trigger_Events(
-	IN PRTMP_ADAPTER pAd);
-
-void build_ext_channel_switch_ie(
-	IN PRTMP_ADAPTER pAd,
-	IN HT_EXT_CHANNEL_SWITCH_ANNOUNCEMENT_IE *pIE);
-#endif // DOT11_N_SUPPORT //
-
-
-BOOLEAN APRxDoneInterruptHandle(
-	IN	PRTMP_ADAPTER	pAd);
-
-BOOLEAN STARxDoneInterruptHandle(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	BOOLEAN			argc);
-
-#ifdef DOT11_N_SUPPORT
-// AMPDU packet indication
-VOID Indicate_AMPDU_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-// AMSDU packet indication
-VOID Indicate_AMSDU_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-#endif // DOT11_N_SUPPORT //
-
-// Normal legacy Rx packet indication
-VOID Indicate_Legacy_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-VOID Indicate_EAPOL_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-void  update_os_packet_info(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-void wlan_802_11_to_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	PUCHAR			pHeader802_3,
-	IN  UCHAR			FromWhichBSSID);
-
-UINT deaggregate_AMSDU_announce(
-	IN	PRTMP_ADAPTER	pAd,
-	PNDIS_PACKET		pPacket,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize);
-
-
-#ifdef CONFIG_STA_SUPPORT
-// remove LLC and get 802_3 Header
-#define  RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(_pRxBlk, _pHeader802_3)	\
-{																				\
-	PUCHAR _pRemovedLLCSNAP = NULL, _pDA, _pSA;                                 \
-																				\
-	if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_MESH))                                    \
-	{                                                                           \
-		_pDA = _pRxBlk->pHeader->Addr3;                                         \
-		_pSA = (PUCHAR)_pRxBlk->pHeader + sizeof(HEADER_802_11);                \
-	}                                                                           \
-	else                                                                        \
-	{                                                                           \
-		if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_INFRA))                              	\
-		{                                                                       \
-			_pDA = _pRxBlk->pHeader->Addr1;                                     \
-		if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_DLS))									\
-			_pSA = _pRxBlk->pHeader->Addr2;										\
-		else																	\
-			_pSA = _pRxBlk->pHeader->Addr3;                                     \
-		}                                                                       \
-		else                                                                    \
-		{                                                                       \
-			_pDA = _pRxBlk->pHeader->Addr1;                                     \
-			_pSA = _pRxBlk->pHeader->Addr2;                                     \
-		}                                                                       \
-	}                                                                           \
-																				\
-	CONVERT_TO_802_3(_pHeader802_3, _pDA, _pSA, _pRxBlk->pData, 				\
-		_pRxBlk->DataSize, _pRemovedLLCSNAP);                                   \
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-BOOLEAN APFowardWirelessStaToWirelessSta(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	ULONG			FromWhichBSSID);
-
-VOID Announce_or_Forward_802_3_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UCHAR			FromWhichBSSID);
-
-VOID Sta_Announce_or_Forward_802_3_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UCHAR			FromWhichBSSID);
-
-
-#ifdef CONFIG_STA_SUPPORT
-#define ANNOUNCE_OR_FORWARD_802_3_PACKET(_pAd, _pPacket, _FromWhichBSS)\
-			Sta_Announce_or_Forward_802_3_Packet(_pAd, _pPacket, _FromWhichBSS);
-			//announce_802_3_packet(_pAd, _pPacket);
-#endif // CONFIG_STA_SUPPORT //
-
-
-PNDIS_PACKET DuplicatePacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UCHAR			FromWhichBSSID);
-
-
-PNDIS_PACKET ClonePacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize);
-
-
-// Normal, AMPDU or AMSDU
-VOID CmmRxnonRalinkFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-VOID CmmRxRalinkFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-VOID Update_Rssi_Sample(
-	IN PRTMP_ADAPTER	pAd,
-	IN RSSI_SAMPLE		*pRssi,
-	IN PRXWI_STRUC		pRxWI);
-
-PNDIS_PACKET GetPacketFromRxRing(
-	IN		PRTMP_ADAPTER	pAd,
-	OUT		PRT28XX_RXD_STRUC		pSaveRxD,
-	OUT		BOOLEAN			*pbReschedule,
-	IN OUT	UINT32			*pRxPending);
-
-PNDIS_PACKET RTMPDeFragmentDataFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk);
-
-////////////////////////////////////////
-
-
-
-
-
-#ifdef SNMP_SUPPORT
-//for snmp , kathy
-typedef struct _DefaultKeyIdxValue
-{
-	UCHAR	KeyIdx;
-	UCHAR	Value[16];
-} DefaultKeyIdxValue, *PDefaultKeyIdxValue;
-#endif
-
-
-#ifdef CONFIG_STA_SUPPORT
-enum {
-	DIDmsg_lnxind_wlansniffrm		= 0x00000044,
-	DIDmsg_lnxind_wlansniffrm_hosttime	= 0x00010044,
-	DIDmsg_lnxind_wlansniffrm_mactime	= 0x00020044,
-	DIDmsg_lnxind_wlansniffrm_channel	= 0x00030044,
-	DIDmsg_lnxind_wlansniffrm_rssi		= 0x00040044,
-	DIDmsg_lnxind_wlansniffrm_sq		= 0x00050044,
-	DIDmsg_lnxind_wlansniffrm_signal	= 0x00060044,
-	DIDmsg_lnxind_wlansniffrm_noise		= 0x00070044,
-	DIDmsg_lnxind_wlansniffrm_rate		= 0x00080044,
-	DIDmsg_lnxind_wlansniffrm_istx		= 0x00090044,
-	DIDmsg_lnxind_wlansniffrm_frmlen	= 0x000A0044
-};
-enum {
-	P80211ENUM_msgitem_status_no_value	= 0x00
-};
-enum {
-	P80211ENUM_truth_false			= 0x00,
-	P80211ENUM_truth_true			= 0x01
-};
-
-/* Definition from madwifi */
-typedef struct {
-        UINT32 did;
-        UINT16 status;
-        UINT16 len;
-        UINT32 data;
-} p80211item_uint32_t;
-
-typedef struct {
-        UINT32 msgcode;
-        UINT32 msglen;
-#define WLAN_DEVNAMELEN_MAX 16
-        UINT8 devname[WLAN_DEVNAMELEN_MAX];
-        p80211item_uint32_t hosttime;
-        p80211item_uint32_t mactime;
-        p80211item_uint32_t channel;
-        p80211item_uint32_t rssi;
-        p80211item_uint32_t sq;
-        p80211item_uint32_t signal;
-        p80211item_uint32_t noise;
-        p80211item_uint32_t rate;
-        p80211item_uint32_t istx;
-        p80211item_uint32_t frmlen;
-} wlan_ng_prism2_header;
-
-/* The radio capture header precedes the 802.11 header. */
-typedef struct PACKED _ieee80211_radiotap_header {
-    UINT8	it_version;	/* Version 0. Only increases
-				 * for drastic changes,
-				 * introduction of compatible
-				 * new fields does not count.
-				 */
-    UINT8	it_pad;
-    UINT16     it_len;         /* length of the whole
-				 * header in bytes, including
-				 * it_version, it_pad,
-				 * it_len, and data fields.
-				 */
-    UINT32   it_present;	/* A bitmap telling which
-					 * fields are present. Set bit 31
-					 * (0x80000000) to extend the
-					 * bitmap by another 32 bits.
-					 * Additional extensions are made
-					 * by setting bit 31.
-					 */
-}ieee80211_radiotap_header ;
-
-enum ieee80211_radiotap_type {
-    IEEE80211_RADIOTAP_TSFT = 0,
-    IEEE80211_RADIOTAP_FLAGS = 1,
-    IEEE80211_RADIOTAP_RATE = 2,
-    IEEE80211_RADIOTAP_CHANNEL = 3,
-    IEEE80211_RADIOTAP_FHSS = 4,
-    IEEE80211_RADIOTAP_DBM_ANTSIGNAL = 5,
-    IEEE80211_RADIOTAP_DBM_ANTNOISE = 6,
-    IEEE80211_RADIOTAP_LOCK_QUALITY = 7,
-    IEEE80211_RADIOTAP_TX_ATTENUATION = 8,
-    IEEE80211_RADIOTAP_DB_TX_ATTENUATION = 9,
-    IEEE80211_RADIOTAP_DBM_TX_POWER = 10,
-    IEEE80211_RADIOTAP_ANTENNA = 11,
-    IEEE80211_RADIOTAP_DB_ANTSIGNAL = 12,
-    IEEE80211_RADIOTAP_DB_ANTNOISE = 13
-};
-
-#define WLAN_RADIOTAP_PRESENT (			\
-	(1 << IEEE80211_RADIOTAP_TSFT)	|	\
-	(1 << IEEE80211_RADIOTAP_FLAGS) |	\
-	(1 << IEEE80211_RADIOTAP_RATE)  | 	\
-	 0)
-
-typedef struct _wlan_radiotap_header {
-	ieee80211_radiotap_header wt_ihdr;
-	INT64 wt_tsft;
-	UINT8 wt_flags;
-	UINT8 wt_rate;
-} wlan_radiotap_header;
-/* Definition from madwifi */
-
-void send_monitor_packets(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk);
-
-#if WIRELESS_EXT >= 12
-// This function will be called when query /proc
-struct iw_statistics *rt28xx_get_wireless_stats(
-    IN struct net_device *net_dev);
-#endif
-
-VOID    RTMPSetDesiredRates(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  LONG            Rates);
-#endif // CONFIG_STA_SUPPORT //
-
-INT	Set_FixedTxMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-INT	Set_OpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-static inline char* GetPhyMode(
-	int Mode)
-{
-	switch(Mode)
-	{
-		case MODE_CCK:
-			return "CCK";
-
-		case MODE_OFDM:
-			return "OFDM";
-#ifdef DOT11_N_SUPPORT
-		case MODE_HTMIX:
-			return "HTMIX";
-
-		case MODE_HTGREENFIELD:
-			return "GREEN";
-#endif // DOT11_N_SUPPORT //
-		default:
-			return "N/A";
-	}
-}
-
-
-static inline char* GetBW(
-	int BW)
-{
-	switch(BW)
-	{
-		case BW_10:
-			return "10M";
-
-		case BW_20:
-			return "20M";
-#ifdef DOT11_N_SUPPORT
-		case BW_40:
-			return "40M";
-#endif // DOT11_N_SUPPORT //
-		default:
-			return "N/A";
-	}
-}
-
-
-VOID RT28xxThreadTerminate(
-	IN RTMP_ADAPTER *pAd);
-
-BOOLEAN RT28XXChipsetCheck(
-	IN void *_dev_p);
-
-BOOLEAN RT28XXNetDevInit(
-	IN void 				*_dev_p,
-	IN struct  net_device	*net_dev,
-	IN RTMP_ADAPTER 		*pAd);
-
-BOOLEAN RT28XXProbePostConfig(
-	IN void 				*_dev_p,
-	IN RTMP_ADAPTER 		*pAd,
-	IN INT32				argc);
-
-VOID RT28XXDMADisable(
-	IN RTMP_ADAPTER 		*pAd);
-
-VOID RT28XXDMAEnable(
-	IN RTMP_ADAPTER 		*pAd);
-
-VOID RT28xx_UpdateBeaconToAsic(
-	IN RTMP_ADAPTER * pAd,
-	IN INT apidx,
-	IN ULONG BeaconLen,
-	IN ULONG UpdatePos);
-
-INT rt28xx_ioctl(
-	IN	struct net_device	*net_dev,
-	IN	OUT	struct ifreq	*rq,
-	IN	INT			cmd);
-
-
-#ifdef CONFIG_STA_SUPPORT
-INT rt28xx_sta_ioctl(
-	IN	struct net_device	*net_dev,
-	IN	OUT	struct ifreq	*rq,
-	IN	INT			cmd);
-#endif // CONFIG_STA_SUPPORT //
-
-BOOLEAN RT28XXSecurityKeyAdd(
-	IN		PRTMP_ADAPTER		pAd,
-	IN		ULONG				apidx,
-	IN		ULONG				KeyIdx,
-	IN		MAC_TABLE_ENTRY 	*pEntry);
-
-////////////////////////////////////////
-PNDIS_PACKET GetPacketFromRxRing(
-	IN		PRTMP_ADAPTER	pAd,
-	OUT		PRT28XX_RXD_STRUC	pSaveRxD,
-	OUT		BOOLEAN			*pbReschedule,
-	IN OUT	UINT32			*pRxPending);
-
-
-void kill_thread_task(PRTMP_ADAPTER pAd);
-
-void tbtt_tasklet(unsigned long data);
-
-
-VOID AsicTurnOffRFClk(
-	IN PRTMP_ADAPTER    pAd,
-	IN	UCHAR           Channel);
-
-VOID AsicTurnOnRFClk(
-	IN PRTMP_ADAPTER 	pAd,
-	IN	UCHAR			Channel);
-
-#ifdef RT2870
-//
-// Function Prototype in rtusb_bulk.c
-//
-VOID	RTUSBInitTxDesc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTX_CONTEXT		pTxContext,
-	IN	UCHAR			BulkOutPipeId,
-	IN	usb_complete_t	Func);
-
-VOID	RTUSBInitHTTxDesc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PHT_TX_CONTEXT	pTxContext,
-	IN	UCHAR			BulkOutPipeId,
-	IN	ULONG			BulkOutSize,
-	IN	usb_complete_t	Func);
-
-VOID	RTUSBInitRxDesc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PRX_CONTEXT		pRxContext);
-
-VOID RTUSBCleanUpDataBulkOutQueue(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBCancelPendingBulkOutIRP(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBBulkOutDataPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BulkOutPipeId,
-	IN	UCHAR			Index);
-
-VOID RTUSBBulkOutNullFrame(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBBulkOutRTSFrame(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBCancelPendingBulkInIRP(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBCancelPendingIRPs(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBBulkOutMLMEPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index);
-
-VOID RTUSBBulkOutPsPoll(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBCleanUpMLMEBulkOutQueue(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBKickBulkOut(
-	IN	PRTMP_ADAPTER pAd);
-
-VOID	RTUSBBulkReceive(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID DoBulkIn(
-	IN RTMP_ADAPTER *pAd);
-
-VOID RTUSBInitRxDesc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PRX_CONTEXT		pRxContext);
-
-VOID RTUSBBulkRxHandle(
-	IN unsigned long data);
-
-//
-// Function Prototype in rtusb_io.c
-//
-NTSTATUS RTUSBMultiRead(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	OUT	PUCHAR			pData,
-	IN	USHORT			length);
-
-NTSTATUS RTUSBMultiWrite(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	PUCHAR			pData,
-	IN	USHORT			length);
-
-NTSTATUS RTUSBMultiWrite_OneByte(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	PUCHAR			pData);
-
-NTSTATUS RTUSBReadBBPRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Id,
-	IN	PUCHAR			pValue);
-
-NTSTATUS RTUSBWriteBBPRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Id,
-	IN	UCHAR			Value);
-
-NTSTATUS RTUSBWriteRFRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UINT32			Value);
-
-NTSTATUS	RT30xxWriteRFRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			RegID,
-	IN	UCHAR			Value);
-
-NTSTATUS	RT30xxReadRFRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			RegID,
-	IN	PUCHAR			pValue);
-
-NTSTATUS RTUSB_VendorRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UINT32			TransferFlags,
-	IN	UCHAR			ReservedBits,
-	IN	UCHAR			Request,
-	IN	USHORT			Value,
-	IN	USHORT			Index,
-	IN	PVOID			TransferBuffer,
-	IN	UINT32			TransferBufferLength);
-
-NTSTATUS RTUSBReadEEPROM(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	OUT	PUCHAR			pData,
-	IN	USHORT			length);
-
-NTSTATUS RTUSBWriteEEPROM(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	PUCHAR			pData,
-	IN	USHORT			length);
-
-VOID RTUSBPutToSleep(
-	IN	PRTMP_ADAPTER	pAd);
-
-NTSTATUS RTUSBWakeUp(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBInitializeCmdQ(
-	IN	PCmdQ	cmdq);
-
-NDIS_STATUS	RTUSBEnqueueCmdFromNdis(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	NDIS_OID		Oid,
-	IN	BOOLEAN			SetInformation,
-	IN	PVOID			pInformationBuffer,
-	IN	UINT32			InformationBufferLength);
-
-NDIS_STATUS RTUSBEnqueueInternalCmd(
-	IN	PRTMP_ADAPTER	pAd,
-	IN NDIS_OID			Oid,
-	IN PVOID			pInformationBuffer,
-	IN UINT32			InformationBufferLength);
-
-VOID RTUSBDequeueCmd(
-	IN	PCmdQ		cmdq,
-	OUT	PCmdQElmt	*pcmdqelmt);
-
-INT RTUSBCmdThread(
-	IN OUT PVOID Context);
-
-INT TimerQThread(
-	IN OUT PVOID Context);
-
-RT2870_TIMER_ENTRY *RT2870_TimerQ_Insert(
-	IN RTMP_ADAPTER *pAd,
-	IN RALINK_TIMER_STRUCT *pTimer);
-
-BOOLEAN RT2870_TimerQ_Remove(
-	IN RTMP_ADAPTER *pAd,
-	IN RALINK_TIMER_STRUCT *pTimer);
-
-void RT2870_TimerQ_Exit(
-	IN RTMP_ADAPTER *pAd);
-
-void RT2870_TimerQ_Init(
-	IN RTMP_ADAPTER *pAd);
-
-VOID RT2870_BssBeaconExit(
-	IN RTMP_ADAPTER *pAd);
-
-VOID RT2870_BssBeaconStop(
-	IN RTMP_ADAPTER *pAd);
-
-VOID RT2870_BssBeaconStart(
-	IN RTMP_ADAPTER * pAd);
-
-VOID RT2870_BssBeaconInit(
-	IN RTMP_ADAPTER *pAd);
-
-VOID RT2870_WatchDog(
-	IN RTMP_ADAPTER *pAd);
-
-NTSTATUS RTUSBWriteMACRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	UINT32			Value);
-
-NTSTATUS RTUSBReadMACRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	OUT	PUINT32			pValue);
-
-NTSTATUS RTUSBSingleWrite(
-	IN 	RTMP_ADAPTER 	*pAd,
-	IN	USHORT			Offset,
-	IN	USHORT			Value);
-
-NTSTATUS RTUSBFirmwareRun(
-	IN	PRTMP_ADAPTER	pAd);
-
-NTSTATUS RTUSBFirmwareWrite(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR		pFwImage,
-	IN ULONG		FwLen);
-
-NTSTATUS	RTUSBFirmwareOpmode(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUINT32			pValue);
-
-NTSTATUS	RTUSBVenderReset(
-	IN	PRTMP_ADAPTER	pAd);
-
-NDIS_STATUS RTUSBSetHardWareRegister(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PVOID			pBuf);
-
-NDIS_STATUS RTUSBQueryHardWareRegister(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PVOID			pBuf);
-
-VOID CMDHandler(
-    IN PRTMP_ADAPTER pAd);
-
-
-NDIS_STATUS	 CreateThreads(
-	IN	struct net_device *net_dev );
-
-
-VOID MacTableInitialize(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID MlmeSetPsm(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT psm);
-
-NDIS_STATUS RTMPWPAAddKeyProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PVOID           pBuf);
-
-VOID AsicRxAntEvalAction(
-	IN PRTMP_ADAPTER pAd);
-
-#if 0 // Mark because not used in RT28xx.
-NTSTATUS RTUSBRxPacket(
-	IN	PRTMP_ADAPTER  pAd,
-	IN    BOOLEAN          bBulkReceive);
-
-VOID RTUSBDequeueMLMEPacket(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBCleanUpMLMEWaitQueue(
-	IN	PRTMP_ADAPTER	pAd);
-#endif
-
-void append_pkt(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pHeader802_3,
-    IN  UINT            HdrLen,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	OUT  PNDIS_PACKET	*ppPacket);
-
-UINT deaggregate_AMSDU_announce(
-	IN	PRTMP_ADAPTER	pAd,
-	PNDIS_PACKET		pPacket,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize);
-
-NDIS_STATUS	RTMPCheckRxError(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PHEADER_802_11	pHeader,
-	IN	PRXWI_STRUC	pRxWI,
-	IN	PRT28XX_RXD_STRUC	pRxINFO);
-
-
-VOID RTUSBMlmeHardTransmit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PMGMT_STRUC		pMgmt);
-
-INT MlmeThread(
-	IN PVOID Context);
-
-#if 0
-VOID    RTUSBResumeMsduTransmission(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID    RTUSBSuspendMsduTransmission(
-	IN	PRTMP_ADAPTER	pAd);
-#endif
-
-//
-// Function Prototype in rtusb_data.c
-//
-NDIS_STATUS	RTUSBFreeDescriptorRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BulkOutPipeId,
-	IN	UINT32			NumberRequired);
-
-
-BOOLEAN	RTUSBNeedQueueBackForAgg(
-	IN RTMP_ADAPTER *pAd,
-	IN UCHAR		BulkOutPipeId);
-
-
-VOID RTMPWriteTxInfo(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXINFO_STRUC 	pTxInfo,
-	IN	  USHORT		USBDMApktLen,
-	IN	  BOOLEAN		bWiv,
-	IN	  UCHAR			QueueSel,
-	IN	  UCHAR			NextValid,
-	IN	  UCHAR			TxBurst);
-
-//
-// Function Prototype in cmm_data_2870.c
-//
-USHORT RtmpUSB_WriteSubTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	BOOLEAN			bIsLast,
-	OUT	USHORT			*FreeNumber);
-
-USHORT RtmpUSB_WriteSingleTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	BOOLEAN			bIsLast,
-	OUT	USHORT			*FreeNumber);
-
-USHORT	RtmpUSB_WriteFragTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	UCHAR			fragNum,
-	OUT	USHORT			*FreeNumber);
-
-USHORT RtmpUSB_WriteMultiTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	UCHAR			frameNum,
-	OUT	USHORT			*FreeNumber);
-
-VOID RtmpUSB_FinalWriteTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	USHORT			totalMPDUSize,
-	IN	USHORT			TxIdx);
-
-VOID RtmpUSBDataLastTxIdx(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			QueIdx,
-	IN	USHORT			TxIdx);
-
-VOID RtmpUSBDataKickOut(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	UCHAR			QueIdx);
-
-
-int RtmpUSBMgmtKickOut(
-	IN RTMP_ADAPTER 	*pAd,
-	IN UCHAR 			QueIdx,
-	IN PNDIS_PACKET		pPacket,
-	IN PUCHAR			pSrcBufVA,
-	IN UINT 			SrcBufLen);
-
-VOID RtmpUSBNullFrameKickOut(
-	IN RTMP_ADAPTER *pAd,
-	IN UCHAR		QueIdx,
-	IN UCHAR		*pNullFrame,
-	IN UINT32		frameLen);
-
-VOID RT28xxUsbStaAsicForceWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN       bFromTx);
-
-VOID RT28xxUsbStaAsicSleepThenAutoWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT TbttNumToNextWakeUp);
-
-VOID RT28xxUsbMlmeRadioOn(
-	IN PRTMP_ADAPTER pAd);
-
-VOID RT28xxUsbMlmeRadioOFF(
-	IN PRTMP_ADAPTER pAd);
-#endif // RT2870 //
-
-////////////////////////////////////////
-
-VOID QBSS_LoadInit(
- 	IN		RTMP_ADAPTER	*pAd);
-
-UINT32 QBSS_LoadElementAppend(
- 	IN		RTMP_ADAPTER	*pAd,
-	OUT		UINT8			*buf_p);
-
-VOID QBSS_LoadUpdate(
- 	IN		RTMP_ADAPTER	*pAd);
-
-///////////////////////////////////////
-INT RTMPShowCfgValue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pName,
-	IN	PUCHAR			pBuf);
-
-PCHAR   RTMPGetRalinkAuthModeStr(
-    IN  NDIS_802_11_AUTHENTICATION_MODE authMode);
-
-PCHAR   RTMPGetRalinkEncryModeStr(
-    IN  USHORT encryMode);
-//////////////////////////////////////
-
-#ifdef CONFIG_STA_SUPPORT
-VOID AsicStaBbpTuning(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN StaAddMacTableEntry(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PMAC_TABLE_ENTRY	pEntry,
-	IN  UCHAR				MaxSupportedRateIn500Kbps,
-	IN  HT_CAPABILITY_IE	*pHtCapability,
-	IN  UCHAR				HtCapabilityLen,
-	IN  USHORT        		CapabilityInfo);
-#endif // CONFIG_STA_SUPPORT //
-
-void RTMP_IndicateMediaState(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID ReSyncBeaconTime(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPSetAGCInitValue(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			BandWidth);
-
-int rt28xx_close(IN PNET_DEV dev);
-int rt28xx_open(IN PNET_DEV dev);
-
-__inline INT VIRTUAL_IF_UP(PRTMP_ADAPTER pAd)
-{
-extern VOID MeshMakeBeacon(IN PRTMP_ADAPTER pAd, IN UCHAR idx);
-extern VOID MeshUpdateBeaconFrame(IN PRTMP_ADAPTER pAd, IN UCHAR idx);
-
-	if (VIRTUAL_IF_NUM(pAd) == 0)
-	{
-		if (rt28xx_open(pAd->net_dev) != 0)
-			return -1;
-	}
-	else
-	{
-	}
-	VIRTUAL_IF_INC(pAd);
-	return 0;
-}
-
-__inline VOID VIRTUAL_IF_DOWN(PRTMP_ADAPTER pAd)
-{
-	VIRTUAL_IF_DEC(pAd);
-	if (VIRTUAL_IF_NUM(pAd) == 0)
-		rt28xx_close(pAd->net_dev);
-	return;
-}
-
-
-#endif  // __RTMP_H__
-
+#include "../rt2860/rtmp.h"
diff --git a/drivers/staging/rt2870/rtmp_ckipmic.h b/drivers/staging/rt2870/rtmp_ckipmic.h
index a3d949a..0e7f1df 100644
--- a/drivers/staging/rt2870/rtmp_ckipmic.h
+++ b/drivers/staging/rt2870/rtmp_ckipmic.h
@@ -1,113 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtmp_ckipmic.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-*/
-#ifndef	__RTMP_CKIPMIC_H__
-#define	__RTMP_CKIPMIC_H__
-
-typedef	struct	_MIC_CONTEXT	{
-	/* --- MMH context                            */
-	UCHAR		CK[16];				/* the key                                    */
-	UCHAR		coefficient[16];	/* current aes counter mode coefficients      */
-	ULONGLONG	accum;				/* accumulated mic, reduced to u32 in final() */
-	UINT		position;			/* current position (byte offset) in message  */
-	UCHAR		part[4];			/* for conversion of message to u32 for mmh   */
-}	MIC_CONTEXT, *PMIC_CONTEXT;
-
-VOID	CKIP_key_permute(
-	OUT	UCHAR	*PK,			/* output permuted key */
-	IN	UCHAR	*CK,			/* input CKIP key */
-	IN	UCHAR	toDsFromDs,		/* input toDs/FromDs bits */
-	IN	UCHAR	*piv);			/* input pointer to IV */
-
-VOID	RTMPCkipMicInit(
-	IN	PMIC_CONTEXT		pContext,
-	IN	PUCHAR				CK);
-
-VOID RTMPMicUpdate(
-    IN  PMIC_CONTEXT        pContext,
-    IN  PUCHAR              pOctets,
-    IN  INT                 len);
-
-ULONG RTMPMicGetCoefficient(
-    IN  PMIC_CONTEXT         pContext);
-
-VOID xor_128(
-    IN  PUCHAR              a,
-    IN  PUCHAR              b,
-    OUT PUCHAR              out);
-
-UCHAR RTMPCkipSbox(
-    IN  UCHAR               a);
-
-VOID xor_32(
-    IN  PUCHAR              a,
-    IN  PUCHAR              b,
-    OUT PUCHAR              out);
-
-VOID next_key(
-    IN  PUCHAR              key,
-    IN  INT                 round);
-
-VOID byte_sub(
-    IN  PUCHAR              in,
-    OUT PUCHAR              out);
-
-VOID shift_row(
-    IN  PUCHAR              in,
-    OUT PUCHAR              out);
-
-VOID mix_column(
-    IN  PUCHAR              in,
-    OUT PUCHAR              out);
-
-VOID RTMPAesEncrypt(
-    IN  PUCHAR              key,
-    IN  PUCHAR              data,
-    IN  PUCHAR              ciphertext);
-
-VOID RTMPMicFinal(
-    IN  PMIC_CONTEXT        pContext,
-    OUT UCHAR               digest[4]);
-
-VOID RTMPCkipInsertCMIC(
-    IN  PRTMP_ADAPTER   pAd,
-    OUT PUCHAR          pMIC,
-    IN  PUCHAR          p80211hdr,
-    IN  PNDIS_PACKET    pPacket,
-    IN  PCIPHER_KEY     pKey,
-    IN  PUCHAR          mic_snap);
-
-#endif //__RTMP_CKIPMIC_H__
+#include "../rt2860/rtmp_ckipmic.h"
diff --git a/drivers/staging/rt2870/rtmp_def.h b/drivers/staging/rt2870/rtmp_def.h
index c0f7561..839d791 100644
--- a/drivers/staging/rt2870/rtmp_def.h
+++ b/drivers/staging/rt2870/rtmp_def.h
@@ -1,1622 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    rtmp_def.h
-
-    Abstract:
-    Miniport related definition header
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Paul Lin    08-01-2002    created
-    John Chang  08-05-2003    add definition for 11g & other drafts
-*/
-#ifndef __RTMP_DEF_H__
-#define __RTMP_DEF_H__
-
-#include "oid.h"
-
-//
-//  Debug information verbosity: lower values indicate higher urgency
-//
-#define RT_DEBUG_OFF        0
-#define RT_DEBUG_ERROR      1
-#define RT_DEBUG_WARN       2
-#define RT_DEBUG_TRACE      3
-#define RT_DEBUG_INFO       4
-#define RT_DEBUG_LOUD       5
-
-#define NIC_TAG             ((ULONG)'0682')
-#define NIC_DBG_STRING      ("**RT28xx**")
-
-#ifdef SNMP_SUPPORT
-// for snmp
-// to get manufacturer OUI, kathy, 2008_0220
-#define ManufacturerOUI_LEN			3
-#define ManufacturerNAME			("Ralink Technology Company.")
-#define	ResourceTypeIdName			("Ralink_ID")
-#endif
-
-
-//#define PACKED
-
-#define RALINK_2883_VERSION		((UINT32)0x28830300)
-#define RALINK_2880E_VERSION	((UINT32)0x28720200)
-#define RALINK_3070_VERSION		((UINT32)0x30700200)
-
-//
-// NDIS version in use by the NIC driver.
-// The high byte is the major version. The low byte is the minor version.
-//
-#ifdef  NDIS51_MINIPORT
-#define NIC_DRIVER_VERSION      0x0501
-#else
-#define NIC_DRIVER_VERSION      0x0500
-#endif
-
-//
-// NDIS media type, current is ethernet, change if native wireless supported
-//
-#define NIC_MEDIA_TYPE          NdisMedium802_3
-#define NIC_PCI_HDR_LENGTH      0xe2
-#define NIC_MAX_PACKET_SIZE     2304
-#define NIC_HEADER_SIZE         14
-#define MAX_MAP_REGISTERS_NEEDED 32
-#define MIN_MAP_REGISTERS_NEEDED 2   //Todo: should consider fragment issue.
-
-//
-// interface type, we use PCI
-//
-#define NIC_INTERFACE_TYPE      NdisInterfacePci
-#define NIC_INTERRUPT_MODE      NdisInterruptLevelSensitive
-
-//
-// buffer size passed in NdisMQueryAdapterResources
-// We should only need three adapter resources (IO, interrupt and memory),
-// Some devices get extra resources, so have room for 10 resources
-//                    UF_SIZE   (sizeof(NDIS_RESOURCE_LIST) + (10*sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR)))
-
-
-#define NIC_RESOURCE_B//
-// IO space length
-//
-#define NIC_MAP_IOSPACE_LENGTH  sizeof(CSR_STRUC)
-
-#define MAX_RX_PKT_LEN	1520
-
-//
-// Entry number for each DMA descriptor ring
-//
-
-
-#ifdef RT2870
-#define TX_RING_SIZE            8 // 1
-#define PRIO_RING_SIZE          8
-#define MGMT_RING_SIZE       32 // PRIO_RING_SIZE
-#define RX_RING_SIZE            8
-#define MAX_TX_PROCESS          4
-#define LOCAL_TXBUF_SIZE        2048
-#endif // RT2870 //
-
-#ifdef MULTIPLE_CARD_SUPPORT
-// MC: Multple Cards
-#define MAX_NUM_OF_MULTIPLE_CARD		32
-#endif // MULTIPLE_CARD_SUPPORT //
-
-#define MAX_RX_PROCESS          128 //64 //32
-#define NUM_OF_LOCAL_TXBUF      2
-#define TXD_SIZE                16
-#define TXWI_SIZE               16
-#define RXD_SIZE               	16
-#define RXWI_SIZE             	16
-// TXINFO_SIZE + TXWI_SIZE + 802.11 Header Size + AMSDU sub frame header
-#define TX_DMA_1ST_BUFFER_SIZE  96    // only the 1st physical buffer is pre-allocated
-#define MGMT_DMA_BUFFER_SIZE    1536 //2048
-#define RX_BUFFER_AGGRESIZE     3840 //3904 //3968 //4096 //2048 //4096
-#define RX_BUFFER_NORMSIZE      3840 //3904 //3968 //4096 //2048 //4096
-#define TX_BUFFER_NORMSIZE		RX_BUFFER_NORMSIZE
-#define MAX_FRAME_SIZE          2346                    // Maximum 802.11 frame size
-#define MAX_AGGREGATION_SIZE    3840 //3904 //3968 //4096
-#define MAX_NUM_OF_TUPLE_CACHE  2
-#define MAX_MCAST_LIST_SIZE     32
-#define MAX_LEN_OF_VENDOR_DESC  64
-//#define MAX_SIZE_OF_MCAST_PSQ   (NUM_OF_LOCAL_TXBUF >> 2) // AP won't spend more than 1/4 of total buffers on M/BCAST PSQ
-#define MAX_SIZE_OF_MCAST_PSQ               32
-
-#define MAX_RX_PROCESS_CNT	(RX_RING_SIZE)
-
-
-#define MAX_PACKETS_IN_QUEUE				(512) //(512)    // to pass WMM A5-WPAPSK
-#define MAX_PACKETS_IN_MCAST_PS_QUEUE		32
-#define MAX_PACKETS_IN_PS_QUEUE				128	//32
-#define WMM_NUM_OF_AC                       4  /* AC0, AC1, AC2, and AC3 */
-
-
-
-// RxFilter
-#define STANORMAL	 0x17f97
-#define APNORMAL	 0x15f97
-//
-//  RTMP_ADAPTER flags
-//
-#define fRTMP_ADAPTER_MAP_REGISTER          0x00000001
-#define fRTMP_ADAPTER_INTERRUPT_IN_USE      0x00000002
-#define fRTMP_ADAPTER_HARDWARE_ERROR        0x00000004
-#define fRTMP_ADAPTER_SCATTER_GATHER        0x00000008
-#define fRTMP_ADAPTER_SEND_PACKET_ERROR     0x00000010
-#define fRTMP_ADAPTER_MLME_RESET_IN_PROGRESS 0x00000020
-#define fRTMP_ADAPTER_HALT_IN_PROGRESS      0x00000040
-#define fRTMP_ADAPTER_RESET_IN_PROGRESS     0x00000080
-#define fRTMP_ADAPTER_NIC_NOT_EXIST         0x00000100
-#define fRTMP_ADAPTER_TX_RING_ALLOCATED     0x00000200
-#define fRTMP_ADAPTER_REMOVE_IN_PROGRESS    0x00000400
-#define fRTMP_ADAPTER_MIMORATE_INUSED       0x00000800
-#define fRTMP_ADAPTER_RX_RING_ALLOCATED     0x00001000
-#define fRTMP_ADAPTER_INTERRUPT_ACTIVE      0x00002000
-#define fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS  0x00004000
-#define	fRTMP_ADAPTER_REASSOC_IN_PROGRESS	0x00008000
-#define	fRTMP_ADAPTER_MEDIA_STATE_PENDING	0x00010000
-#define	fRTMP_ADAPTER_RADIO_OFF				0x00020000
-#define fRTMP_ADAPTER_BULKOUT_RESET			0x00040000
-#define	fRTMP_ADAPTER_BULKIN_RESET			0x00080000
-#define fRTMP_ADAPTER_RDG_ACTIVE			0x00100000
-#define fRTMP_ADAPTER_DYNAMIC_BE_TXOP_ACTIVE 0x00200000
-#define fRTMP_ADAPTER_SCAN_2040 			0x04000000
-#define	fRTMP_ADAPTER_RADIO_MEASUREMENT		0x08000000
-
-#define fRTMP_ADAPTER_START_UP         		0x10000000	//Devive already initialized and enabled Tx/Rx.
-#define fRTMP_ADAPTER_MEDIA_STATE_CHANGE    0x20000000
-#define fRTMP_ADAPTER_IDLE_RADIO_OFF        0x40000000
-
-// Lock bit for accessing different ring buffers
-//#define fRTMP_ADAPTER_TX_RING_BUSY        0x80000000
-//#define fRTMP_ADAPTER_MGMT_RING_BUSY      0x40000000
-//#define fRTMP_ADAPTER_ATIM_RING_BUSY      0x20000000
-//#define fRTMP_ADAPTER_RX_RING_BUSY        0x10000000
-
-// Lock bit for accessing different queue
-//#define   fRTMP_ADAPTER_TX_QUEUE_BUSY     0x08000000
-//#define   fRTMP_ADAPTER_MGMT_QUEUE_BUSY   0x04000000
-
-//
-//  STA operation status flags
-//
-#define fOP_STATUS_INFRA_ON                 0x00000001
-#define fOP_STATUS_ADHOC_ON                 0x00000002
-#define fOP_STATUS_BG_PROTECTION_INUSED     0x00000004
-#define fOP_STATUS_SHORT_SLOT_INUSED        0x00000008
-#define fOP_STATUS_SHORT_PREAMBLE_INUSED    0x00000010
-#define fOP_STATUS_RECEIVE_DTIM             0x00000020
-//#define fOP_STATUS_TX_RATE_SWITCH_ENABLED   0x00000040
-#define fOP_STATUS_MEDIA_STATE_CONNECTED    0x00000080
-#define fOP_STATUS_WMM_INUSED               0x00000100
-#define fOP_STATUS_AGGREGATION_INUSED       0x00000200
-#define fOP_STATUS_DOZE                     0x00000400  // debug purpose
-#define fOP_STATUS_PIGGYBACK_INUSED         0x00000800  // piggy-back, and aggregation
-#define fOP_STATUS_APSD_INUSED				0x00001000
-#define fOP_STATUS_TX_AMSDU_INUSED			0x00002000
-#define fOP_STATUS_MAX_RETRY_ENABLED		0x00004000
-#define fOP_STATUS_WAKEUP_NOW               0x00008000
-#define fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE       0x00020000
-
-#ifdef DOT11N_DRAFT3
-#define fOP_STATUS_SCAN_2040               	    0x00040000
-#endif // DOT11N_DRAFT3 //
-
-#define CCKSETPROTECT		0x1
-#define OFDMSETPROTECT		0x2
-#define MM20SETPROTECT		0x4
-#define MM40SETPROTECT		0x8
-#define GF20SETPROTECT		0x10
-#define GR40SETPROTECT		0x20
-#define ALLN_SETPROTECT		(GR40SETPROTECT | GF20SETPROTECT | MM40SETPROTECT | MM20SETPROTECT)
-
-//
-//  AP's client table operation status flags
-//
-#define fCLIENT_STATUS_WMM_CAPABLE          0x00000001  // CLIENT can parse QOS DATA frame
-#define fCLIENT_STATUS_AGGREGATION_CAPABLE  0x00000002  // CLIENT can receive Ralink's proprietary TX aggregation frame
-#define fCLIENT_STATUS_PIGGYBACK_CAPABLE    0x00000004  // CLIENT support piggy-back
-#define fCLIENT_STATUS_AMSDU_INUSED			0x00000008
-#define fCLIENT_STATUS_SGI20_CAPABLE		0x00000010
-#define fCLIENT_STATUS_SGI40_CAPABLE		0x00000020
-#define fCLIENT_STATUS_TxSTBC_CAPABLE		0x00000040
-#define fCLIENT_STATUS_RxSTBC_CAPABLE		0x00000080
-#define fCLIENT_STATUS_HTC_CAPABLE			0x00000100
-#define fCLIENT_STATUS_RDG_CAPABLE			0x00000200
-#define fCLIENT_STATUS_MCSFEEDBACK_CAPABLE  0x00000400
-#define fCLIENT_STATUS_APSD_CAPABLE         0x00000800  /* UAPSD STATION */
-
-#ifdef DOT11N_DRAFT3
-#define fCLIENT_STATUS_BSSCOEXIST_CAPABLE	0x00001000
-#endif // DOT11N_DRAFT3 //
-
-#define fCLIENT_STATUS_RALINK_CHIPSET		0x00100000
-//
-//  STA configuration flags
-//
-//#define fSTA_CFG_ENABLE_TX_BURST          0x00000001
-
-// 802.11n Operating Mode Definition. 0-3 also used in ASICUPdateProtect switch case
-#define HT_NO_PROTECT	0
-#define HT_LEGACY_PROTECT	1
-#define HT_40_PROTECT	2
-#define HT_2040_PROTECT	3
-#define HT_RTSCTS_6M	7
-//following is our own definition in order to turn on our ASIC protection register in INFRASTRUCTURE.
-#define HT_ATHEROS	8	// rt2860c has problem with atheros chip. we need to turn on RTS/CTS .
-#define HT_FORCERTSCTS	9	// Force turn on RTS/CTS first. then go to evaluate if this force RTS is necessary.
-
-//
-// RX Packet Filter control flags. Apply on pAd->PacketFilter
-//
-#define fRX_FILTER_ACCEPT_DIRECT            NDIS_PACKET_TYPE_DIRECTED
-#define fRX_FILTER_ACCEPT_MULTICAST         NDIS_PACKET_TYPE_MULTICAST
-#define fRX_FILTER_ACCEPT_BROADCAST         NDIS_PACKET_TYPE_BROADCAST
-#define fRX_FILTER_ACCEPT_ALL_MULTICAST     NDIS_PACKET_TYPE_ALL_MULTICAST
-
-//
-// Error code section
-//
-// NDIS_ERROR_CODE_ADAPTER_NOT_FOUND
-#define ERRLOG_READ_PCI_SLOT_FAILED     0x00000101L
-#define ERRLOG_WRITE_PCI_SLOT_FAILED    0x00000102L
-#define ERRLOG_VENDOR_DEVICE_NOMATCH    0x00000103L
-
-// NDIS_ERROR_CODE_ADAPTER_DISABLED
-#define ERRLOG_BUS_MASTER_DISABLED      0x00000201L
-
-// NDIS_ERROR_CODE_UNSUPPORTED_CONFIGURATION
-#define ERRLOG_INVALID_SPEED_DUPLEX     0x00000301L
-#define ERRLOG_SET_SECONDARY_FAILED     0x00000302L
-
-// NDIS_ERROR_CODE_OUT_OF_RESOURCES
-#define ERRLOG_OUT_OF_MEMORY            0x00000401L
-#define ERRLOG_OUT_OF_SHARED_MEMORY     0x00000402L
-#define ERRLOG_OUT_OF_MAP_REGISTERS     0x00000403L
-#define ERRLOG_OUT_OF_BUFFER_POOL       0x00000404L
-#define ERRLOG_OUT_OF_NDIS_BUFFER       0x00000405L
-#define ERRLOG_OUT_OF_PACKET_POOL       0x00000406L
-#define ERRLOG_OUT_OF_NDIS_PACKET       0x00000407L
-#define ERRLOG_OUT_OF_LOOKASIDE_MEMORY  0x00000408L
-
-// NDIS_ERROR_CODE_HARDWARE_FAILURE
-#define ERRLOG_SELFTEST_FAILED          0x00000501L
-#define ERRLOG_INITIALIZE_ADAPTER       0x00000502L
-#define ERRLOG_REMOVE_MINIPORT          0x00000503L
-
-// NDIS_ERROR_CODE_RESOURCE_CONFLICT
-#define ERRLOG_MAP_IO_SPACE             0x00000601L
-#define ERRLOG_QUERY_ADAPTER_RESOURCES  0x00000602L
-#define ERRLOG_NO_IO_RESOURCE           0x00000603L
-#define ERRLOG_NO_INTERRUPT_RESOURCE    0x00000604L
-#define ERRLOG_NO_MEMORY_RESOURCE       0x00000605L
-
-
-// WDS definition
-#define	MAX_WDS_ENTRY               4
-#define WDS_PAIRWISE_KEY_OFFSET     60    // WDS links uses pairwise key#60 ~ 63 in ASIC pairwise key table
-
-#define	WDS_DISABLE_MODE            0
-#define	WDS_RESTRICT_MODE           1
-#define	WDS_BRIDGE_MODE             2
-#define	WDS_REPEATER_MODE           3
-#define	WDS_LAZY_MODE               4
-
-
-#define MAX_MESH_NUM				0
-
-#define MAX_APCLI_NUM				0
-#ifdef APCLI_SUPPORT
-#undef	MAX_APCLI_NUM
-#define MAX_APCLI_NUM				1
-#endif // APCLI_SUPPORT //
-
-#define MAX_MBSSID_NUM				1
-
-/* sanity check for apidx */
-#define MBSS_MR_APIDX_SANITY_CHECK(apidx) \
-    { if (apidx > MAX_MBSSID_NUM) { \
-          printk("%s> Error! apidx = %d > MAX_MBSSID_NUM!\n", __func__, apidx); \
-	  apidx = MAIN_MBSSID; } }
-
-#define VALID_WCID(_wcid)	((_wcid) > 0 && (_wcid) < MAX_LEN_OF_MAC_TABLE )
-
-#define MAIN_MBSSID                 0
-#define FIRST_MBSSID                1
-
-
-#define MAX_BEACON_SIZE				512
-// If the MAX_MBSSID_NUM is larger than 6,
-// it shall reserve some WCID space(wcid 222~253) for beacon frames.
-// -	these wcid 238~253 are reserved for beacon#6(ra6).
-// -	these wcid 222~237 are reserved for beacon#7(ra7).
-#if defined(MAX_MBSSID_NUM) && (MAX_MBSSID_NUM == 8)
-#define HW_RESERVED_WCID	222
-#elif defined(MAX_MBSSID_NUM) && (MAX_MBSSID_NUM == 7)
-#define HW_RESERVED_WCID	238
-#else
-#define HW_RESERVED_WCID	255
-#endif
-
-// Then dedicate wcid of DFS and Carrier-Sense.
-#define DFS_CTS_WCID 		(HW_RESERVED_WCID - 1)
-#define CS_CTS_WCID 		(HW_RESERVED_WCID - 2)
-#define LAST_SPECIFIC_WCID	(HW_RESERVED_WCID - 2)
-
-// If MAX_MBSSID_NUM is 8, the maximum available wcid for the associated STA is 211.
-// If MAX_MBSSID_NUM is 7, the maximum available wcid for the associated STA is 228.
-#define MAX_AVAILABLE_CLIENT_WCID	(LAST_SPECIFIC_WCID - MAX_MBSSID_NUM - 1)
-
-// TX need WCID to find Cipher Key
-// these wcid 212 ~ 219 are reserved for bc/mc packets if MAX_MBSSID_NUM is 8.
-#define GET_GroupKey_WCID(__wcid, __bssidx) \
-	{										\
-		__wcid = LAST_SPECIFIC_WCID - (MAX_MBSSID_NUM) + __bssidx;	\
-	}
-
-#define IsGroupKeyWCID(__wcid) (((__wcid) < LAST_SPECIFIC_WCID) && ((__wcid) >= (LAST_SPECIFIC_WCID - (MAX_MBSSID_NUM))))
-
-
-// definition to support multiple BSSID
-#define BSS0                            0
-#define BSS1                            1
-#define BSS2                            2
-#define BSS3                            3
-#define BSS4                            4
-#define BSS5                            5
-#define BSS6                            6
-#define BSS7                            7
-
-
-//============================================================
-// Length definitions
-#define PEER_KEY_NO                     2
-#define MAC_ADDR_LEN                    6
-#define TIMESTAMP_LEN                   8
-#define MAX_LEN_OF_SUPPORTED_RATES      MAX_LENGTH_OF_SUPPORT_RATES // 1, 2, 5.5, 11, 6, 9, 12, 18, 24, 36, 48, 54
-#define MAX_LEN_OF_KEY                  32      // 32 octets == 256 bits, Redefine for WPA
-#define MAX_NUM_OF_CHANNELS             MAX_NUM_OF_CHS      // 14 channels @2.4G +  12@UNII + 4 @MMAC + 11 @HiperLAN2 + 7 @Japan + 1 as NULL termination
-#define MAX_NUM_OF_11JCHANNELS             20      // 14 channels @2.4G +  12@UNII + 4 @MMAC + 11 @HiperLAN2 + 7 @Japan + 1 as NULL termination
-#define MAX_LEN_OF_SSID                 32
-#define CIPHER_TEXT_LEN                 128
-#define HASH_TABLE_SIZE                 256
-#define MAX_VIE_LEN                     1024   // New for WPA cipher suite variable IE sizes.
-#define MAX_SUPPORT_MCS             32
-
-//============================================================
-// ASIC WCID Table definition.
-//============================================================
-#define BSSID_WCID		1	// in infra mode, always put bssid with this WCID
-#define MCAST_WCID	0x0
-#define BSS0Mcast_WCID	0x0
-#define BSS1Mcast_WCID	0xf8
-#define BSS2Mcast_WCID	0xf9
-#define BSS3Mcast_WCID	0xfa
-#define BSS4Mcast_WCID	0xfb
-#define BSS5Mcast_WCID	0xfc
-#define BSS6Mcast_WCID	0xfd
-#define BSS7Mcast_WCID	0xfe
-#define RESERVED_WCID		0xff
-
-#define MAX_NUM_OF_ACL_LIST				MAX_NUMBER_OF_ACL
-
-#define MAX_LEN_OF_MAC_TABLE            MAX_NUMBER_OF_MAC // if MAX_MBSSID_NUM is 8, this value can't be larger than 211
-
-#if MAX_LEN_OF_MAC_TABLE>MAX_AVAILABLE_CLIENT_WCID
-#error MAX_LEN_OF_MAC_TABLE can not be larger than MAX_AVAILABLE_CLIENT_WCID!!!!
-#endif
-
-#define MAX_NUM_OF_WDS_LINK_PERBSSID	            3
-#define MAX_NUM_OF_WDS_LINK	            (MAX_NUM_OF_WDS_LINK_PERBSSID*MAX_MBSSID_NUM)
-#define MAX_NUM_OF_EVENT                MAX_NUMBER_OF_EVENT
-#define WDS_LINK_START_WCID				(MAX_LEN_OF_MAC_TABLE-1)
-
-#define NUM_OF_TID			8
-#define MAX_AID_BA                    4
-#define MAX_LEN_OF_BA_REC_TABLE          ((NUM_OF_TID * MAX_LEN_OF_MAC_TABLE)/2)//   (NUM_OF_TID*MAX_AID_BA + 32)	 //Block ACK recipient
-#define MAX_LEN_OF_BA_ORI_TABLE          ((NUM_OF_TID * MAX_LEN_OF_MAC_TABLE)/2)//   (NUM_OF_TID*MAX_AID_BA + 32)   // Block ACK originator
-#define MAX_LEN_OF_BSS_TABLE             64
-#define MAX_REORDERING_MPDU_NUM			 512
-
-// key related definitions
-#define SHARE_KEY_NUM                   4
-#define MAX_LEN_OF_SHARE_KEY            16    // byte count
-#define MAX_LEN_OF_PEER_KEY             16    // byte count
-#define PAIRWISE_KEY_NUM                64    // in MAC ASIC pairwise key table
-#define GROUP_KEY_NUM                   4
-#define PMK_LEN                         32
-#define WDS_PAIRWISE_KEY_OFFSET         60    // WDS links uses pairwise key#60 ~ 63 in ASIC pairwise key table
-#define	PMKID_NO                        4     // Number of PMKID saved supported
-#define MAX_LEN_OF_MLME_BUFFER          2048
-
-// power status related definitions
-#define PWR_ACTIVE                      0
-#define PWR_SAVE                        1
-#define PWR_MMPS                        2			//MIMO power save
-//#define PWR_UNKNOWN                   2
-
-// Auth and Assoc mode related definitions
-#define AUTH_MODE_OPEN                  0x00
-#define AUTH_MODE_KEY                   0x01
-//#define AUTH_MODE_AUTO_SWITCH         0x03
-//#define AUTH_MODE_DEAUTH              0x04
-//#define AUTH_MODE_UPLAYER             0x05 // reserved for 802.11i use
-
-// BSS Type definitions
-#define BSS_ADHOC                       0  // = Ndis802_11IBSS
-#define BSS_INFRA                       1  // = Ndis802_11Infrastructure
-#define BSS_ANY                         2  // = Ndis802_11AutoUnknown
-#define BSS_MONITOR			            3  // = Ndis802_11Monitor
-
-
-// Reason code definitions
-#define REASON_RESERVED                 0
-#define REASON_UNSPECIFY                1
-#define REASON_NO_LONGER_VALID          2
-#define REASON_DEAUTH_STA_LEAVING       3
-#define REASON_DISASSOC_INACTIVE        4
-#define REASON_DISASSPC_AP_UNABLE       5
-#define REASON_CLS2ERR                  6
-#define REASON_CLS3ERR                  7
-#define REASON_DISASSOC_STA_LEAVING     8
-#define REASON_STA_REQ_ASSOC_NOT_AUTH   9
-#define REASON_INVALID_IE               13
-#define REASON_MIC_FAILURE              14
-#define REASON_4_WAY_TIMEOUT            15
-#define REASON_GROUP_KEY_HS_TIMEOUT     16
-#define REASON_IE_DIFFERENT             17
-#define REASON_MCIPHER_NOT_VALID        18
-#define REASON_UCIPHER_NOT_VALID        19
-#define REASON_AKMP_NOT_VALID           20
-#define REASON_UNSUPPORT_RSNE_VER       21
-#define REASON_INVALID_RSNE_CAP         22
-#define REASON_8021X_AUTH_FAIL          23
-#define REASON_CIPHER_SUITE_REJECTED    24
-#define REASON_DECLINED                 37
-
-#define REASON_QOS_UNSPECIFY              32
-#define REASON_QOS_LACK_BANDWIDTH         33
-#define REASON_POOR_CHANNEL_CONDITION     34
-#define REASON_QOS_OUTSIDE_TXOP_LIMITION  35
-#define REASON_QOS_QSTA_LEAVING_QBSS      36
-#define REASON_QOS_UNWANTED_MECHANISM     37
-#define REASON_QOS_MECH_SETUP_REQUIRED    38
-#define REASON_QOS_REQUEST_TIMEOUT        39
-#define REASON_QOS_CIPHER_NOT_SUPPORT     45
-
-// Status code definitions
-#define MLME_SUCCESS                    0
-#define MLME_UNSPECIFY_FAIL             1
-#define MLME_CANNOT_SUPPORT_CAP         10
-#define MLME_REASSOC_DENY_ASSOC_EXIST   11
-#define MLME_ASSOC_DENY_OUT_SCOPE       12
-#define MLME_ALG_NOT_SUPPORT            13
-#define MLME_SEQ_NR_OUT_OF_SEQUENCE     14
-#define MLME_REJ_CHALLENGE_FAILURE      15
-#define MLME_REJ_TIMEOUT                  16
-#define MLME_ASSOC_REJ_UNABLE_HANDLE_STA  17
-#define MLME_ASSOC_REJ_DATA_RATE          18
-
-#define MLME_ASSOC_REJ_NO_EXT_RATE        22
-#define MLME_ASSOC_REJ_NO_EXT_RATE_PBCC   23
-#define MLME_ASSOC_REJ_NO_CCK_OFDM        24
-
-#define MLME_QOS_UNSPECIFY                32
-#define MLME_REQUEST_DECLINED             37
-#define MLME_REQUEST_WITH_INVALID_PARAM   38
-#define MLME_DLS_NOT_ALLOW_IN_QBSS        48
-#define MLME_DEST_STA_NOT_IN_QBSS         49
-#define MLME_DEST_STA_IS_NOT_A_QSTA       50
-
-#define MLME_INVALID_FORMAT             0x51
-#define MLME_FAIL_NO_RESOURCE           0x52
-#define MLME_STATE_MACHINE_REJECT       0x53
-#define MLME_MAC_TABLE_FAIL             0x54
-
-// IE code
-#define IE_SSID                         0
-#define IE_SUPP_RATES                   1
-#define IE_FH_PARM                      2
-#define IE_DS_PARM                      3
-#define IE_CF_PARM                      4
-#define IE_TIM                          5
-#define IE_IBSS_PARM                    6
-#define IE_COUNTRY                      7     // 802.11d
-#define IE_802_11D_REQUEST              10    // 802.11d
-#define IE_QBSS_LOAD                    11    // 802.11e d9
-#define IE_EDCA_PARAMETER               12    // 802.11e d9
-#define IE_TSPEC                        13    // 802.11e d9
-#define IE_TCLAS                        14    // 802.11e d9
-#define IE_SCHEDULE                     15    // 802.11e d9
-#define IE_CHALLENGE_TEXT               16
-#define IE_POWER_CONSTRAINT             32    // 802.11h d3.3
-#define IE_POWER_CAPABILITY             33    // 802.11h d3.3
-#define IE_TPC_REQUEST                  34    // 802.11h d3.3
-#define IE_TPC_REPORT                   35    // 802.11h d3.3
-#define IE_SUPP_CHANNELS                36    // 802.11h d3.3
-#define IE_CHANNEL_SWITCH_ANNOUNCEMENT  37    // 802.11h d3.3
-#define IE_MEASUREMENT_REQUEST          38    // 802.11h d3.3
-#define IE_MEASUREMENT_REPORT           39    // 802.11h d3.3
-#define IE_QUIET                        40    // 802.11h d3.3
-#define IE_IBSS_DFS                     41    // 802.11h d3.3
-#define IE_ERP                          42    // 802.11g
-#define IE_TS_DELAY                     43    // 802.11e d9
-#define IE_TCLAS_PROCESSING             44    // 802.11e d9
-#define IE_QOS_CAPABILITY               46    // 802.11e d6
-#define IE_HT_CAP                       45    // 802.11n d1. HT CAPABILITY. ELEMENT ID TBD
-#define IE_AP_CHANNEL_REPORT			51    // 802.11k d6
-#define IE_HT_CAP2                         52    // 802.11n d1. HT CAPABILITY. ELEMENT ID TBD
-#define IE_RSN                          48    // 802.11i d3.0
-#define IE_WPA2                         48    // WPA2
-#define IE_EXT_SUPP_RATES               50    // 802.11g
-#define IE_SUPP_REG_CLASS               59    // 802.11y. Supported regulatory classes.
-#define IE_EXT_CHANNEL_SWITCH_ANNOUNCEMENT	60	// 802.11n
-#define IE_ADD_HT                         61    // 802.11n d1. ADDITIONAL HT CAPABILITY. ELEMENT ID TBD
-#define IE_ADD_HT2                        53    // 802.11n d1. ADDITIONAL HT CAPABILITY. ELEMENT ID TBD
-
-
-// For 802.11n D3.03
-//#define IE_NEW_EXT_CHA_OFFSET             62    // 802.11n d1. New extension channel offset elemet
-#define IE_SECONDARY_CH_OFFSET		62	// 802.11n D3.03	Secondary Channel Offset element
-#define IE_WAPI							68		// WAPI information element
-#define IE_2040_BSS_COEXIST               72    // 802.11n D3.0.3
-#define IE_2040_BSS_INTOLERANT_REPORT     73    // 802.11n D3.03
-#define IE_OVERLAPBSS_SCAN_PARM           74    // 802.11n D3.03
-#define IE_EXT_CAPABILITY                127   // 802.11n D3.03
-
-
-#define IE_WPA                          221   // WPA
-#define IE_VENDOR_SPECIFIC              221   // Wifi WMM (WME)
-
-#define OUI_BROADCOM_HT              51   //
-#define OUI_BROADCOM_HTADD              52   //
-#define OUI_PREN_HT_CAP              51   //
-#define OUI_PREN_ADD_HT              52   //
-
-// CCX information
-#define IE_AIRONET_CKIP                 133   // CCX1.0 ID 85H for CKIP
-#define IE_AP_TX_POWER                  150   // CCX 2.0 for AP transmit power
-#define IE_MEASUREMENT_CAPABILITY       221   // CCX 2.0
-#define IE_CCX_V2                       221
-#define IE_AIRONET_IPADDRESS            149   // CCX ID 95H for IP Address
-#define IE_AIRONET_CCKMREASSOC          156   // CCX ID 9CH for CCKM Reassociation Request element
-#define CKIP_NEGOTIATION_LENGTH         30
-#define AIRONET_IPADDRESS_LENGTH        10
-#define AIRONET_CCKMREASSOC_LENGTH      24
-
-// ========================================================
-// MLME state machine definition
-// ========================================================
-
-// STA MLME state mahcines
-#define ASSOC_STATE_MACHINE             1
-#define AUTH_STATE_MACHINE              2
-#define AUTH_RSP_STATE_MACHINE          3
-#define SYNC_STATE_MACHINE              4
-#define MLME_CNTL_STATE_MACHINE         5
-#define WPA_PSK_STATE_MACHINE           6
-#define LEAP_STATE_MACHINE              7
-#define AIRONET_STATE_MACHINE           8
-#define ACTION_STATE_MACHINE           9
-
-// AP MLME state machines
-#define AP_ASSOC_STATE_MACHINE          11
-#define AP_AUTH_STATE_MACHINE           12
-#define AP_AUTH_RSP_STATE_MACHINE       13
-#define AP_SYNC_STATE_MACHINE           14
-#define AP_CNTL_STATE_MACHINE           15
-#define AP_WPA_STATE_MACHINE            16
-
-#ifdef QOS_DLS_SUPPORT
-#define DLS_STATE_MACHINE               26
-#endif // QOS_DLS_SUPPORT //
-
-//
-// STA's CONTROL/CONNECT state machine: states, events, total function #
-//
-#define CNTL_IDLE                       0
-#define CNTL_WAIT_DISASSOC              1
-#define CNTL_WAIT_JOIN                  2
-#define CNTL_WAIT_REASSOC               3
-#define CNTL_WAIT_START                 4
-#define CNTL_WAIT_AUTH                  5
-#define CNTL_WAIT_ASSOC                 6
-#define CNTL_WAIT_AUTH2                 7
-#define CNTL_WAIT_OID_LIST_SCAN         8
-#define CNTL_WAIT_OID_DISASSOC          9
-#ifdef RT2870
-#define CNTL_WAIT_SCAN_FOR_CONNECT      10
-#endif // RT2870 //
-
-#define MT2_ASSOC_CONF                  34
-#define MT2_AUTH_CONF                   35
-#define MT2_DEAUTH_CONF                 36
-#define MT2_DISASSOC_CONF               37
-#define MT2_REASSOC_CONF                38
-#define MT2_PWR_MGMT_CONF               39
-#define MT2_JOIN_CONF                   40
-#define MT2_SCAN_CONF                   41
-#define MT2_START_CONF                  42
-#define MT2_GET_CONF                    43
-#define MT2_SET_CONF                    44
-#define MT2_RESET_CONF                  45
-#define MT2_MLME_ROAMING_REQ            52
-
-#define CNTL_FUNC_SIZE                  1
-
-//
-// STA's ASSOC state machine: states, events, total function #
-//
-#define ASSOC_IDLE                      0
-#define ASSOC_WAIT_RSP                  1
-#define REASSOC_WAIT_RSP                2
-#define DISASSOC_WAIT_RSP               3
-#define MAX_ASSOC_STATE                 4
-
-#define ASSOC_MACHINE_BASE              0
-#define MT2_MLME_ASSOC_REQ              0
-#define MT2_MLME_REASSOC_REQ            1
-#define MT2_MLME_DISASSOC_REQ           2
-#define MT2_PEER_DISASSOC_REQ           3
-#define MT2_PEER_ASSOC_REQ              4
-#define MT2_PEER_ASSOC_RSP              5
-#define MT2_PEER_REASSOC_REQ            6
-#define MT2_PEER_REASSOC_RSP            7
-#define MT2_DISASSOC_TIMEOUT            8
-#define MT2_ASSOC_TIMEOUT               9
-#define MT2_REASSOC_TIMEOUT             10
-#define MAX_ASSOC_MSG                   11
-
-#define ASSOC_FUNC_SIZE                 (MAX_ASSOC_STATE * MAX_ASSOC_MSG)
-
-//
-// ACT state machine: states, events, total function #
-//
-#define ACT_IDLE                      0
-#define MAX_ACT_STATE                 1
-
-#define ACT_MACHINE_BASE              0
-
-//Those PEER_xx_CATE number is based on real Categary value in IEEE spec. Please don'es modify it by your self.
-//Category
-#define MT2_PEER_SPECTRUM_CATE              0
-#define MT2_PEER_QOS_CATE              1
-#define MT2_PEER_DLS_CATE             2
-#define MT2_PEER_BA_CATE             3
-#define MT2_PEER_PUBLIC_CATE             4
-#define MT2_PEER_RM_CATE             5
-#define MT2_PEER_HT_CATE             7	//	7.4.7
-#define MAX_PEER_CATE_MSG                   7
-#define MT2_MLME_ADD_BA_CATE             8
-#define MT2_MLME_ORI_DELBA_CATE             9
-#define MT2_MLME_REC_DELBA_CATE             10
-#define MT2_MLME_QOS_CATE              11
-#define MT2_MLME_DLS_CATE             12
-#define MT2_ACT_INVALID             13
-#define MAX_ACT_MSG                   14
-
-//Category field
-#define CATEGORY_SPECTRUM		0
-#define CATEGORY_QOS			1
-#define CATEGORY_DLS			2
-#define CATEGORY_BA			3
-#define CATEGORY_PUBLIC		4
-#define CATEGORY_RM			5
-#define CATEGORY_HT			7
-
-
-// DLS Action frame definition
-#define ACTION_DLS_REQUEST			0
-#define ACTION_DLS_RESPONSE			1
-#define ACTION_DLS_TEARDOWN			2
-
-//Spectrum  Action field value 802.11h 7.4.1
-#define SPEC_MRQ	0	// Request
-#define SPEC_MRP	1	//Report
-#define SPEC_TPCRQ	2
-#define SPEC_TPCRP	3
-#define SPEC_CHANNEL_SWITCH	4
-
-
-//BA  Action field value
-#define ADDBA_REQ	0
-#define ADDBA_RESP	1
-#define DELBA   2
-
-//Public's  Action field value in Public Category.  Some in 802.11y and some in 11n
-#define ACTION_BSS_2040_COEXIST				0	// 11n
-#define ACTION_DSE_ENABLEMENT					1	// 11y D9.0
-#define ACTION_DSE_DEENABLEMENT				2	// 11y D9.0
-#define ACTION_DSE_REG_LOCATION_ANNOUNCE	3	// 11y D9.0
-#define ACTION_EXT_CH_SWITCH_ANNOUNCE		4	// 11y D9.0
-#define ACTION_DSE_MEASUREMENT_REQ			5	// 11y D9.0
-#define ACTION_DSE_MEASUREMENT_REPORT		6	// 11y D9.0
-#define ACTION_MEASUREMENT_PILOT_ACTION		7  	// 11y D9.0
-#define ACTION_DSE_POWER_CONSTRAINT			8	// 11y D9.0
-
-
-//HT  Action field value
-#define NOTIFY_BW_ACTION				0
-#define SMPS_ACTION						1
-#define PSMP_ACTION   					2
-#define SETPCO_ACTION					3
-#define MIMO_CHA_MEASURE_ACTION			4
-#define MIMO_N_BEACONFORM				5
-#define MIMO_BEACONFORM					6
-#define ANTENNA_SELECT					7
-#define HT_INFO_EXCHANGE				8
-
-#define ACT_FUNC_SIZE                 (MAX_ACT_STATE * MAX_ACT_MSG)
-//
-// STA's AUTHENTICATION state machine: states, evvents, total function #
-//
-#define AUTH_REQ_IDLE                   0
-#define AUTH_WAIT_SEQ2                  1
-#define AUTH_WAIT_SEQ4                  2
-#define MAX_AUTH_STATE                  3
-
-#define AUTH_MACHINE_BASE               0
-#define MT2_MLME_AUTH_REQ               0
-#define MT2_PEER_AUTH_EVEN              1
-#define MT2_AUTH_TIMEOUT                2
-#define MAX_AUTH_MSG                    3
-
-#define AUTH_FUNC_SIZE                  (MAX_AUTH_STATE * MAX_AUTH_MSG)
-
-//
-// STA's AUTH_RSP state machine: states, events, total function #
-//
-#define AUTH_RSP_IDLE                   0
-#define AUTH_RSP_WAIT_CHAL              1
-#define MAX_AUTH_RSP_STATE              2
-
-#define AUTH_RSP_MACHINE_BASE           0
-#define MT2_AUTH_CHALLENGE_TIMEOUT      0
-#define MT2_PEER_AUTH_ODD               1
-#define MT2_PEER_DEAUTH                 2
-#define MAX_AUTH_RSP_MSG                3
-
-#define AUTH_RSP_FUNC_SIZE              (MAX_AUTH_RSP_STATE * MAX_AUTH_RSP_MSG)
-
-//
-// STA's SYNC state machine: states, events, total function #
-//
-#define SYNC_IDLE                       0  // merge NO_BSS,IBSS_IDLE,IBSS_ACTIVE and BSS in to 1 state
-#define JOIN_WAIT_BEACON                1
-#define SCAN_LISTEN                     2
-#define MAX_SYNC_STATE                  3
-
-#define SYNC_MACHINE_BASE               0
-#define MT2_MLME_SCAN_REQ               0
-#define MT2_MLME_JOIN_REQ               1
-#define MT2_MLME_START_REQ              2
-#define MT2_PEER_BEACON                 3
-#define MT2_PEER_PROBE_RSP              4
-#define MT2_PEER_ATIM                   5
-#define MT2_SCAN_TIMEOUT                6
-#define MT2_BEACON_TIMEOUT              7
-#define MT2_ATIM_TIMEOUT                8
-#define MT2_PEER_PROBE_REQ              9
-#define MAX_SYNC_MSG                    10
-
-#define SYNC_FUNC_SIZE                  (MAX_SYNC_STATE * MAX_SYNC_MSG)
-
-//Messages for the DLS state machine
-#define DLS_IDLE						0
-#define MAX_DLS_STATE					1
-
-#define DLS_MACHINE_BASE				0
-#define MT2_MLME_DLS_REQ			    0
-#define MT2_PEER_DLS_REQ			    1
-#define MT2_PEER_DLS_RSP			    2
-#define MT2_MLME_DLS_TEAR_DOWN		    3
-#define MT2_PEER_DLS_TEAR_DOWN		    4
-#define MAX_DLS_MSG				        5
-
-#define DLS_FUNC_SIZE					(MAX_DLS_STATE * MAX_DLS_MSG)
-
-//
-// STA's WPA-PSK State machine: states, events, total function #
-//
-#define WPA_PSK_IDLE					0
-#define MAX_WPA_PSK_STATE				1
-
-#define WPA_MACHINE_BASE                0
-#define MT2_EAPPacket                   0
-#define MT2_EAPOLStart                  1
-#define MT2_EAPOLLogoff                 2
-#define MT2_EAPOLKey                    3
-#define MT2_EAPOLASFAlert               4
-#define MAX_WPA_PSK_MSG                 5
-
-#define	WPA_PSK_FUNC_SIZE				(MAX_WPA_PSK_STATE * MAX_WPA_PSK_MSG)
-
-//
-// STA's CISCO-AIRONET State machine: states, events, total function #
-//
-#define AIRONET_IDLE					0
-#define	AIRONET_SCANNING				1
-#define MAX_AIRONET_STATE				2
-
-#define AIRONET_MACHINE_BASE		    0
-#define MT2_AIRONET_MSG				    0
-#define MT2_AIRONET_SCAN_REQ		    1
-#define MT2_AIRONET_SCAN_DONE		    2
-#define MAX_AIRONET_MSG				    3
-
-#define	AIRONET_FUNC_SIZE				(MAX_AIRONET_STATE * MAX_AIRONET_MSG)
-
-//
-// AP's CONTROL/CONNECT state machine: states, events, total function #
-//
-#define AP_CNTL_FUNC_SIZE               1
-
-//
-// AP's ASSOC state machine: states, events, total function #
-//
-#define AP_ASSOC_IDLE                   0
-#define AP_MAX_ASSOC_STATE              1
-
-#define AP_ASSOC_MACHINE_BASE           0
-#define APMT2_MLME_DISASSOC_REQ         0
-#define APMT2_PEER_DISASSOC_REQ         1
-#define APMT2_PEER_ASSOC_REQ            2
-#define APMT2_PEER_REASSOC_REQ          3
-#define APMT2_CLS3ERR                   4
-#define AP_MAX_ASSOC_MSG                5
-
-#define AP_ASSOC_FUNC_SIZE              (AP_MAX_ASSOC_STATE * AP_MAX_ASSOC_MSG)
-
-//
-// AP's AUTHENTICATION state machine: states, events, total function #
-//
-#define AP_AUTH_REQ_IDLE                0
-#define AP_MAX_AUTH_STATE               1
-
-#define AP_AUTH_MACHINE_BASE            0
-#define APMT2_MLME_DEAUTH_REQ           0
-#define APMT2_CLS2ERR                   1
-#define AP_MAX_AUTH_MSG                 2
-
-#define AP_AUTH_FUNC_SIZE               (AP_MAX_AUTH_STATE * AP_MAX_AUTH_MSG)
-
-//
-// AP's AUTH-RSP state machine: states, events, total function #
-//
-#define AP_AUTH_RSP_IDLE                0
-#define AP_MAX_AUTH_RSP_STATE           1
-
-#define AP_AUTH_RSP_MACHINE_BASE        0
-#define APMT2_AUTH_CHALLENGE_TIMEOUT    0
-#define APMT2_PEER_AUTH_ODD             1
-#define APMT2_PEER_DEAUTH               2
-#define AP_MAX_AUTH_RSP_MSG             3
-
-#define AP_AUTH_RSP_FUNC_SIZE           (AP_MAX_AUTH_RSP_STATE * AP_MAX_AUTH_RSP_MSG)
-
-//
-// AP's SYNC state machine: states, events, total function #
-//
-#define AP_SYNC_IDLE                    0
-#define AP_SCAN_LISTEN					1
-#define AP_MAX_SYNC_STATE               2
-
-#define AP_SYNC_MACHINE_BASE            0
-#define APMT2_PEER_PROBE_REQ            0
-#define APMT2_PEER_BEACON               1
-#define APMT2_MLME_SCAN_REQ				2
-#define APMT2_PEER_PROBE_RSP			3
-#define APMT2_SCAN_TIMEOUT				4
-#define APMT2_MLME_SCAN_CNCL			5
-#define AP_MAX_SYNC_MSG                 6
-
-#define AP_SYNC_FUNC_SIZE               (AP_MAX_SYNC_STATE * AP_MAX_SYNC_MSG)
-
-//
-// AP's WPA state machine: states, events, total function #
-//
-#define AP_WPA_PTK                      0
-#define AP_MAX_WPA_PTK_STATE            1
-
-#define AP_WPA_MACHINE_BASE             0
-#define APMT2_EAPPacket                 0
-#define APMT2_EAPOLStart                1
-#define APMT2_EAPOLLogoff               2
-#define APMT2_EAPOLKey                  3
-#define APMT2_EAPOLASFAlert             4
-#define AP_MAX_WPA_MSG                  5
-
-#define AP_WPA_FUNC_SIZE                (AP_MAX_WPA_PTK_STATE * AP_MAX_WPA_MSG)
-
-#ifdef APCLI_SUPPORT
-//ApCli authentication state machine
-#define APCLI_AUTH_REQ_IDLE                0
-#define APCLI_AUTH_WAIT_SEQ2               1
-#define APCLI_AUTH_WAIT_SEQ4               2
-#define APCLI_MAX_AUTH_STATE               3
-
-#define APCLI_AUTH_MACHINE_BASE            0
-#define APCLI_MT2_MLME_AUTH_REQ            0
-#define APCLI_MT2_MLME_DEAUTH_REQ          1
-#define APCLI_MT2_PEER_AUTH_EVEN           2
-#define APCLI_MT2_PEER_DEAUTH              3
-#define APCLI_MT2_AUTH_TIMEOUT             4
-#define APCLI_MAX_AUTH_MSG                 5
-
-#define APCLI_AUTH_FUNC_SIZE               (APCLI_MAX_AUTH_STATE * APCLI_MAX_AUTH_MSG)
-
-//ApCli association state machine
-#define APCLI_ASSOC_IDLE                   0
-#define APCLI_ASSOC_WAIT_RSP               1
-#define APCLI_MAX_ASSOC_STATE              2
-
-#define APCLI_ASSOC_MACHINE_BASE           0
-#define APCLI_MT2_MLME_ASSOC_REQ           0
-#define APCLI_MT2_MLME_DISASSOC_REQ        1
-#define APCLI_MT2_PEER_DISASSOC_REQ        2
-#define APCLI_MT2_PEER_ASSOC_RSP           3
-#define APCLI_MT2_ASSOC_TIMEOUT            4
-#define APCLI_MAX_ASSOC_MSG                5
-
-#define APCLI_ASSOC_FUNC_SIZE              (APCLI_MAX_ASSOC_STATE * APCLI_MAX_ASSOC_MSG)
-
-//ApCli sync state machine
-#define APCLI_SYNC_IDLE                   0  // merge NO_BSS,IBSS_IDLE,IBSS_ACTIVE and BSS in to 1 state
-#define APCLI_JOIN_WAIT_PROBE_RSP         1
-#define APCLI_MAX_SYNC_STATE              2
-
-#define APCLI_SYNC_MACHINE_BASE           0
-#define APCLI_MT2_MLME_PROBE_REQ          0
-#define APCLI_MT2_PEER_PROBE_RSP          1
-#define APCLI_MT2_PROBE_TIMEOUT           2
-#define APCLI_MAX_SYNC_MSG                3
-
-#define APCLI_SYNC_FUNC_SIZE              (APCLI_MAX_SYNC_STATE * APCLI_MAX_SYNC_MSG)
-
-//ApCli ctrl state machine
-#define APCLI_CTRL_DISCONNECTED           0  // merge NO_BSS,IBSS_IDLE,IBSS_ACTIVE and BSS in to 1 state
-#define APCLI_CTRL_PROBE                  1
-#define APCLI_CTRL_AUTH                   2
-#define APCLI_CTRL_AUTH_2                 3
-#define APCLI_CTRL_ASSOC                  4
-#define APCLI_CTRL_DEASSOC                5
-#define APCLI_CTRL_CONNECTED              6
-#define APCLI_MAX_CTRL_STATE              7
-
-#define APCLI_CTRL_MACHINE_BASE           0
-#define APCLI_CTRL_JOIN_REQ               0
-#define APCLI_CTRL_PROBE_RSP              1
-#define APCLI_CTRL_AUTH_RSP               2
-#define APCLI_CTRL_DISCONNECT_REQ         3
-#define APCLI_CTRL_PEER_DISCONNECT_REQ    4
-#define APCLI_CTRL_ASSOC_RSP              5
-#define APCLI_CTRL_DEASSOC_RSP            6
-#define APCLI_CTRL_JOIN_REQ_TIMEOUT       7
-#define APCLI_CTRL_AUTH_REQ_TIMEOUT       8
-#define APCLI_CTRL_ASSOC_REQ_TIMEOUT      9
-#define APCLI_MAX_CTRL_MSG                10
-
-#define APCLI_CTRL_FUNC_SIZE              (APCLI_MAX_CTRL_STATE * APCLI_MAX_CTRL_MSG)
-
-#if 0	// remove those variables by AlbertY
-// ApCli WPA state machine
-#define APCLI_WPA_PSK_IDLE				0
-#define APCLI_MAX_WPA_PSK_STATE			1
-
-// ApCli WPA MSG Type
-#define APCLI_WPA_MACHINE_BASE			0
-#define APCLI_MT2_EAPPacket				0
-#define APCLI_MT2_EAPOLStart			1
-#define APCLI_MT2_EAPOLLogoff			2
-#define APCLI_MT2_EAPOLKey				3
-#define APCLI_MT2_EAPOLASFAlert			4
-#define APCLI_MAX_WPA_PSK_MSG			5
-
-#define	APCLI_WPA_PSK_FUNC_SIZE			(APCLI_MAX_WPA_PSK_STATE * APCLI_MAX_WPA_PSK_MSG)
-#endif // end - 0 //
-
-#endif	// APCLI_SUPPORT //
-
-
-// =============================================================================
-
-// value domain of 802.11 header FC.Tyte, which is b3..b2 of the 1st-byte of MAC header
-#define BTYPE_MGMT                  0
-#define BTYPE_CNTL                  1
-#define BTYPE_DATA                  2
-
-// value domain of 802.11 MGMT frame's FC.subtype, which is b7..4 of the 1st-byte of MAC header
-#define SUBTYPE_ASSOC_REQ           0
-#define SUBTYPE_ASSOC_RSP           1
-#define SUBTYPE_REASSOC_REQ         2
-#define SUBTYPE_REASSOC_RSP         3
-#define SUBTYPE_PROBE_REQ           4
-#define SUBTYPE_PROBE_RSP           5
-#define SUBTYPE_BEACON              8
-#define SUBTYPE_ATIM                9
-#define SUBTYPE_DISASSOC            10
-#define SUBTYPE_AUTH                11
-#define SUBTYPE_DEAUTH              12
-#define SUBTYPE_ACTION              13
-#define SUBTYPE_ACTION_NO_ACK              14
-
-// value domain of 802.11 CNTL frame's FC.subtype, which is b7..4 of the 1st-byte of MAC header
-#define SUBTYPE_WRAPPER       	7
-#define SUBTYPE_BLOCK_ACK_REQ       8
-#define SUBTYPE_BLOCK_ACK           9
-#define SUBTYPE_PS_POLL             10
-#define SUBTYPE_RTS                 11
-#define SUBTYPE_CTS                 12
-#define SUBTYPE_ACK                 13
-#define SUBTYPE_CFEND               14
-#define SUBTYPE_CFEND_CFACK         15
-
-// value domain of 802.11 DATA frame's FC.subtype, which is b7..4 of the 1st-byte of MAC header
-#define SUBTYPE_DATA                0
-#define SUBTYPE_DATA_CFACK          1
-#define SUBTYPE_DATA_CFPOLL         2
-#define SUBTYPE_DATA_CFACK_CFPOLL   3
-#define SUBTYPE_NULL_FUNC           4
-#define SUBTYPE_CFACK               5
-#define SUBTYPE_CFPOLL              6
-#define SUBTYPE_CFACK_CFPOLL        7
-#define SUBTYPE_QDATA               8
-#define SUBTYPE_QDATA_CFACK         9
-#define SUBTYPE_QDATA_CFPOLL        10
-#define SUBTYPE_QDATA_CFACK_CFPOLL  11
-#define SUBTYPE_QOS_NULL            12
-#define SUBTYPE_QOS_CFACK           13
-#define SUBTYPE_QOS_CFPOLL          14
-#define SUBTYPE_QOS_CFACK_CFPOLL    15
-
-// ACK policy of QOS Control field bit 6:5
-#define NORMAL_ACK                  0x00  // b6:5 = 00
-#define NO_ACK                      0x20  // b6:5 = 01
-#define NO_EXPLICIT_ACK             0x40  // b6:5 = 10
-#define BLOCK_ACK                   0x60  // b6:5 = 11
-
-//
-// rtmp_data.c use these definition
-//
-#define LENGTH_802_11               24
-#define LENGTH_802_11_AND_H         30
-#define LENGTH_802_11_CRC_H         34
-#define LENGTH_802_11_CRC           28
-#define LENGTH_802_11_WITH_ADDR4    30
-#define LENGTH_802_3                14
-#define LENGTH_802_3_TYPE           2
-#define LENGTH_802_1_H              8
-#define LENGTH_EAPOL_H              4
-#define LENGTH_WMMQOS_H				2
-#define LENGTH_CRC                  4
-#define MAX_SEQ_NUMBER              0x0fff
-#define LENGTH_802_3_NO_TYPE		12
-#define LENGTH_802_1Q				4 /* VLAN related */
-
-// STA_CSR4.field.TxResult
-#define TX_RESULT_SUCCESS           0
-#define TX_RESULT_ZERO_LENGTH       1
-#define TX_RESULT_UNDER_RUN         2
-#define TX_RESULT_OHY_ERROR         4
-#define TX_RESULT_RETRY_FAIL        6
-
-// All PHY rate summary in TXD
-// Preamble MODE in TxD
-#define MODE_CCK	0
-#define MODE_OFDM   1
-#ifdef DOT11_N_SUPPORT
-#define MODE_HTMIX	2
-#define MODE_HTGREENFIELD	3
-#endif // DOT11_N_SUPPORT //
-// MCS for CCK.  BW.SGI.STBC are reserved
-#define MCS_LONGP_RATE_1                      0	 // long preamble CCK 1Mbps
-#define MCS_LONGP_RATE_2                      1	// long preamble CCK 1Mbps
-#define MCS_LONGP_RATE_5_5                    2
-#define MCS_LONGP_RATE_11                     3
-#define MCS_SHORTP_RATE_1                      4	 // long preamble CCK 1Mbps. short is forbidden in 1Mbps
-#define MCS_SHORTP_RATE_2                      5	// short preamble CCK 2Mbps
-#define MCS_SHORTP_RATE_5_5                    6
-#define MCS_SHORTP_RATE_11                     7
-// To send duplicate legacy OFDM. set BW=BW_40.  SGI.STBC are reserved
-#define MCS_RATE_6                      0   // legacy OFDM
-#define MCS_RATE_9                      1   // OFDM
-#define MCS_RATE_12                     2   // OFDM
-#define MCS_RATE_18                     3   // OFDM
-#define MCS_RATE_24                     4  // OFDM
-#define MCS_RATE_36                     5   // OFDM
-#define MCS_RATE_48                     6  // OFDM
-#define MCS_RATE_54                     7 // OFDM
-// HT
-#define MCS_0		0	// 1S
-#define MCS_1		1
-#define MCS_2		2
-#define MCS_3		3
-#define MCS_4		4
-#define MCS_5		5
-#define MCS_6		6
-#define MCS_7		7
-#define MCS_8		8	// 2S
-#define MCS_9		9
-#define MCS_10		10
-#define MCS_11		11
-#define MCS_12		12
-#define MCS_13		13
-#define MCS_14		14
-#define MCS_15		15
-#define MCS_16		16	// 3*3
-#define MCS_17		17
-#define MCS_18		18
-#define MCS_19		19
-#define MCS_20		20
-#define MCS_21		21
-#define MCS_22		22
-#define MCS_23		23
-#define MCS_32		32
-#define MCS_AUTO		33
-
-#ifdef DOT11_N_SUPPORT
-// OID_HTPHYMODE
-// MODE
-#define HTMODE_MM	0
-#define HTMODE_GF	1
-#endif // DOT11_N_SUPPORT //
-
-// Fixed Tx MODE - HT, CCK or OFDM
-#define FIXED_TXMODE_HT		0
-#define FIXED_TXMODE_CCK	1
-#define FIXED_TXMODE_OFDM 	2
-// BW
-#define BW_20		BAND_WIDTH_20
-#define BW_40		BAND_WIDTH_40
-#define BW_BOTH		BAND_WIDTH_BOTH
-#define BW_10		BAND_WIDTH_10	// 802.11j has 10MHz. This definition is for internal usage. doesn't fill in the IE or other field.
-
-#ifdef DOT11_N_SUPPORT
-// SHORTGI
-#define GI_400		GAP_INTERVAL_400	// only support in HT mode
-#define GI_BOTH		GAP_INTERVAL_BOTH
-#endif // DOT11_N_SUPPORT //
-#define GI_800		GAP_INTERVAL_800
-// STBC
-#define STBC_NONE	0
-#ifdef DOT11_N_SUPPORT
-#define STBC_USE	1	// limited use in rt2860b phy
-#define RXSTBC_ONE	1	// rx support of one spatial stream
-#define RXSTBC_TWO	2	// rx support of 1 and 2 spatial stream
-#define RXSTBC_THR	3	// rx support of 1~3 spatial stream
-// MCS FEEDBACK
-#define MCSFBK_NONE	0  // not support mcs feedback /
-#define MCSFBK_RSV	1	// reserved
-#define MCSFBK_UNSOLICIT	2	// only support unsolict mcs feedback
-#define MCSFBK_MRQ	3	// response to both MRQ and unsolict mcs feedback
-
-// MIMO power safe
-#define	MMPS_STATIC	0
-#define	MMPS_DYNAMIC		1
-#define   MMPS_RSV		2
-#define MMPS_ENABLE		3
-
-
-// A-MSDU size
-#define	AMSDU_0	0
-#define	AMSDU_1		1
-
-#endif // DOT11_N_SUPPORT //
-
-// MCS use 7 bits
-#define TXRATEMIMO		0x80
-#define TXRATEMCS		0x7F
-#define TXRATEOFDM		0x7F
-#define RATE_1                      0
-#define RATE_2                      1
-#define RATE_5_5                    2
-#define RATE_11                     3
-#define RATE_6                      4   // OFDM
-#define RATE_9                      5   // OFDM
-#define RATE_12                     6   // OFDM
-#define RATE_18                     7   // OFDM
-#define RATE_24                     8   // OFDM
-#define RATE_36                     9   // OFDM
-#define RATE_48                     10  // OFDM
-#define RATE_54                     11  // OFDM
-#define RATE_FIRST_OFDM_RATE        RATE_6
-#define RATE_LAST_OFDM_RATE        	RATE_54
-#define RATE_6_5                    12  // HT mix
-#define RATE_13                     13  // HT mix
-#define RATE_19_5                   14  // HT mix
-#define RATE_26                     15  // HT mix
-#define RATE_39                     16  // HT mix
-#define RATE_52                     17  // HT mix
-#define RATE_58_5                   18  // HT mix
-#define RATE_65                     19  // HT mix
-#define RATE_78                     20  // HT mix
-#define RATE_104                    21  // HT mix
-#define RATE_117                    22  // HT mix
-#define RATE_130                    23  // HT mix
-//#define RATE_AUTO_SWITCH            255 // for StaCfg.FixedTxRate only
-#define HTRATE_0                      12
-#define RATE_FIRST_MM_RATE        HTRATE_0
-#define RATE_FIRST_HT_RATE        HTRATE_0
-#define RATE_LAST_HT_RATE        HTRATE_0
-
-// pTxWI->txop
-#define IFS_HTTXOP                 0	// The txop will be handles by ASIC.
-#define IFS_PIFS                    1
-#define IFS_SIFS                    2
-#define IFS_BACKOFF                 3
-
-// pTxD->RetryMode
-#define LONG_RETRY                  1
-#define SHORT_RETRY                 0
-
-// Country Region definition
-#define REGION_MINIMUM_BG_BAND            0
-#define REGION_0_BG_BAND                  0       // 1-11
-#define REGION_1_BG_BAND                  1       // 1-13
-#define REGION_2_BG_BAND                  2       // 10-11
-#define REGION_3_BG_BAND                  3       // 10-13
-#define REGION_4_BG_BAND                  4       // 14
-#define REGION_5_BG_BAND                  5       // 1-14
-#define REGION_6_BG_BAND                  6       // 3-9
-#define REGION_7_BG_BAND                  7       // 5-13
-#define REGION_31_BG_BAND                 31       // 5-13
-#define REGION_MAXIMUM_BG_BAND            7
-
-#define REGION_MINIMUM_A_BAND             0
-#define REGION_0_A_BAND                   0       // 36, 40, 44, 48, 52, 56, 60, 64, 149, 153, 157, 161, 165
-#define REGION_1_A_BAND                   1       // 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140
-#define REGION_2_A_BAND                   2       // 36, 40, 44, 48, 52, 56, 60, 64
-#define REGION_3_A_BAND                   3       // 52, 56, 60, 64, 149, 153, 157, 161
-#define REGION_4_A_BAND                   4       // 149, 153, 157, 161, 165
-#define REGION_5_A_BAND                   5       // 149, 153, 157, 161
-#define REGION_6_A_BAND                   6       // 36, 40, 44, 48
-#define REGION_7_A_BAND                   7       // 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 149, 153, 157, 161, 165
-#define REGION_8_A_BAND                   8       // 52, 56, 60, 64
-#define REGION_9_A_BAND                   9       // 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 132, 136, 140, 149, 153, 157, 161, 165
-#define REGION_10_A_BAND                  10	  // 36, 40, 44, 48, 149, 153, 157, 161, 165
-#define REGION_11_A_BAND                  11	  // 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 149, 153, 157, 161
-#define REGION_MAXIMUM_A_BAND             11
-
-// pTxD->CipherAlg
-#define CIPHER_NONE                 0
-#define CIPHER_WEP64                1
-#define CIPHER_WEP128               2
-#define CIPHER_TKIP                 3
-#define CIPHER_AES                  4
-#define CIPHER_CKIP64               5
-#define CIPHER_CKIP128              6
-#define CIPHER_TKIP_NO_MIC          7       // MIC appended by driver: not a valid value in hardware key table
-#define CIPHER_SMS4					8
-
-// value domain of pAd->RfIcType
-#define RFIC_2820                   1       // 2.4G 2T3R
-#define RFIC_2850                   2       // 2.4G/5G 2T3R
-#define RFIC_2720                   3       // 2.4G 1T2R
-#define RFIC_2750                   4       // 2.4G/5G 1T2R
-#define RFIC_3020                   5       // 2.4G 1T1R
-#define RFIC_2020                   6       // 2.4G B/G
-
-// LED Status.
-#define LED_LINK_DOWN               0
-#define LED_LINK_UP                 1
-#define LED_RADIO_OFF               2
-#define LED_RADIO_ON                3
-#define LED_HALT                    4
-#define LED_WPS                     5
-#define LED_ON_SITE_SURVEY          6
-#define LED_POWER_UP                7
-
-// value domain of pAd->LedCntl.LedMode and E2PROM
-#define LED_MODE_DEFAULT            0
-#define LED_MODE_TWO_LED			1
-#define LED_MODE_SIGNAL_STREGTH		8  // EEPROM define =8
-
-// RC4 init value, used fro WEP & TKIP
-#define PPPINITFCS32                0xffffffff   /* Initial FCS value */
-
-// value domain of pAd->StaCfg.PortSecured. 802.1X controlled port definition
-#define WPA_802_1X_PORT_SECURED     1
-#define WPA_802_1X_PORT_NOT_SECURED 2
-
-#define PAIRWISE_KEY                1
-#define GROUP_KEY                   2
-
-//definition of DRS
-#define MAX_STEP_OF_TX_RATE_SWITCH	32
-
-
-// pre-allocated free NDIS PACKET/BUFFER poll for internal usage
-#define MAX_NUM_OF_FREE_NDIS_PACKET 128
-
-//Block ACK
-#define MAX_TX_REORDERBUF   64
-#define MAX_RX_REORDERBUF   64
-#define DEFAULT_TX_TIMEOUT   30
-#define DEFAULT_RX_TIMEOUT   30
-
-// definition of Recipient or Originator
-#define I_RECIPIENT                  TRUE
-#define I_ORIGINATOR                   FALSE
-
-#define DEFAULT_BBP_TX_POWER        0
-#define DEFAULT_RF_TX_POWER         5
-
-#define MAX_INI_BUFFER_SIZE			4096
-#define MAX_PARAM_BUFFER_SIZE		(2048) // enough for ACL (18*64)
-											//18 : the length of Mac address acceptable format "01:02:03:04:05:06;")
-											//64 : MAX_NUM_OF_ACL_LIST
-// definition of pAd->OpMode
-#define OPMODE_STA                  0
-#define OPMODE_AP                   1
-//#define OPMODE_L3_BRG               2       // as AP and STA at the same time
-
-#ifdef RT_BIG_ENDIAN
-#define DIR_READ                    0
-#define DIR_WRITE                   1
-#define TYPE_TXD                    0
-#define TYPE_RXD                    1
-#define TYPE_TXINFO					0
-#define TYPE_RXINFO					1
-#define TYPE_TXWI					0
-#define TYPE_RXWI					1
-#endif
-
-// ========================= AP rtmp_def.h ===========================
-// value domain for pAd->EventTab.Log[].Event
-#define EVENT_RESET_ACCESS_POINT    0 // Log = "hh:mm:ss   Restart Access Point"
-#define EVENT_ASSOCIATED            1 // Log = "hh:mm:ss   STA 00:01:02:03:04:05 associated"
-#define EVENT_DISASSOCIATED         2 // Log = "hh:mm:ss   STA 00:01:02:03:04:05 left this BSS"
-#define EVENT_AGED_OUT              3 // Log = "hh:mm:ss   STA 00:01:02:03:04:05 was aged-out and removed from this BSS"
-#define EVENT_COUNTER_M             4
-#define EVENT_INVALID_PSK           5
-#define EVENT_MAX_EVENT_TYPE        6
-// ==== end of AP rtmp_def.h ============
-
-// definition RSSI Number
-#define RSSI_0					0
-#define RSSI_1					1
-#define RSSI_2					2
-
-// definition of radar detection
-#define RD_NORMAL_MODE				0	// Not found radar signal
-#define RD_SWITCHING_MODE			1	// Found radar signal, and doing channel switch
-#define RD_SILENCE_MODE				2	// After channel switch, need to be silence a while to ensure radar not found
-
-//Driver defined cid for mapping status and command.
-#define  SLEEPCID	0x11
-#define  WAKECID	0x22
-#define  QUERYPOWERCID	0x33
-#define  OWNERMCU	0x1
-#define  OWNERCPU	0x0
-
-// MBSSID definition
-#define ENTRY_NOT_FOUND             0xFF
-
-
-/* After Linux 2.6.9,
- * VLAN module use Private (from user) interface flags (netdevice->priv_flags).
- * #define IFF_802_1Q_VLAN 0x1         --    802.1Q VLAN device.  in if.h
- * ref to ip_sabotage_out() [ out->priv_flags & IFF_802_1Q_VLAN ] in br_netfilter.c
- *
- * For this reason, we MUST use EVEN value in priv_flags
- */
-#define INT_MAIN                    0x0100
-#define INT_MBSSID                  0x0200
-#define INT_WDS                     0x0300
-#define INT_APCLI                   0x0400
-#define INT_MESH                   	0x0500
-
-// Use bitmap to allow coexist of ATE_TXFRAME and ATE_RXFRAME(i.e.,to support LoopBack mode)
-#ifdef RALINK_ATE
-#define	ATE_START                   0x00   // Start ATE
-#define	ATE_STOP                    0x80   // Stop ATE
-#define	ATE_TXCONT                  0x05   // Continuous Transmit
-#define	ATE_TXCARR                  0x09   // Transmit Carrier
-#define	ATE_TXCARRSUPP              0x11   // Transmit Carrier Suppression
-#define	ATE_TXFRAME                 0x01   // Transmit Frames
-#define	ATE_RXFRAME                 0x02   // Receive Frames
-#ifdef RALINK_28xx_QA
-#define ATE_TXSTOP                  0xe2   // Stop Transmition(i.e., TXCONT, TXCARR, TXCARRSUPP, and TXFRAME)
-#define ATE_RXSTOP					0xfd   // Stop receiving Frames
-#define	BBP22_TXFRAME     			0x00   // Transmit Frames
-#define	BBP22_TXCONT_OR_CARRSUPP    0x80   // Continuous Transmit or Carrier Suppression
-#define	BBP22_TXCARR                0xc1   // Transmit Carrier
-#define	BBP24_TXCONT                0x00   // Continuous Transmit
-#define	BBP24_CARRSUPP              0x01   // Carrier Suppression
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-// WEP Key TYPE
-#define WEP_HEXADECIMAL_TYPE    0
-#define WEP_ASCII_TYPE          1
-
-
-
-// WIRELESS EVENTS definition
-/* Max number of char in custom event, refer to wireless_tools.28/wireless.20.h */
-#define IW_CUSTOM_MAX_LEN				  			255	/* In bytes */
-
-// For system event - start
-#define	IW_SYS_EVENT_FLAG_START                     0x0200
-#define	IW_ASSOC_EVENT_FLAG                         0x0200
-#define	IW_DISASSOC_EVENT_FLAG                      0x0201
-#define	IW_DEAUTH_EVENT_FLAG                      	0x0202
-#define	IW_AGEOUT_EVENT_FLAG                      	0x0203
-#define	IW_COUNTER_MEASURES_EVENT_FLAG              0x0204
-#define	IW_REPLAY_COUNTER_DIFF_EVENT_FLAG           0x0205
-#define	IW_RSNIE_DIFF_EVENT_FLAG           			0x0206
-#define	IW_MIC_DIFF_EVENT_FLAG           			0x0207
-#define IW_ICV_ERROR_EVENT_FLAG						0x0208
-#define IW_MIC_ERROR_EVENT_FLAG						0x0209
-#define IW_GROUP_HS_TIMEOUT_EVENT_FLAG				0x020A
-#define	IW_PAIRWISE_HS_TIMEOUT_EVENT_FLAG			0x020B
-#define IW_RSNIE_SANITY_FAIL_EVENT_FLAG				0x020C
-#define IW_SET_KEY_DONE_WPA1_EVENT_FLAG				0x020D
-#define IW_SET_KEY_DONE_WPA2_EVENT_FLAG				0x020E
-#define IW_STA_LINKUP_EVENT_FLAG					0x020F
-#define IW_STA_LINKDOWN_EVENT_FLAG					0x0210
-#define IW_SCAN_COMPLETED_EVENT_FLAG				0x0211
-#define IW_SCAN_ENQUEUE_FAIL_EVENT_FLAG				0x0212
-// if add new system event flag, please upadte the IW_SYS_EVENT_FLAG_END
-#define	IW_SYS_EVENT_FLAG_END                       0x0212
-#define	IW_SYS_EVENT_TYPE_NUM						(IW_SYS_EVENT_FLAG_END - IW_SYS_EVENT_FLAG_START + 1)
-// For system event - end
-
-// For spoof attack event - start
-#define	IW_SPOOF_EVENT_FLAG_START                   0x0300
-#define IW_CONFLICT_SSID_EVENT_FLAG					0x0300
-#define IW_SPOOF_ASSOC_RESP_EVENT_FLAG				0x0301
-#define IW_SPOOF_REASSOC_RESP_EVENT_FLAG			0x0302
-#define IW_SPOOF_PROBE_RESP_EVENT_FLAG				0x0303
-#define IW_SPOOF_BEACON_EVENT_FLAG					0x0304
-#define IW_SPOOF_DISASSOC_EVENT_FLAG				0x0305
-#define IW_SPOOF_AUTH_EVENT_FLAG					0x0306
-#define IW_SPOOF_DEAUTH_EVENT_FLAG					0x0307
-#define IW_SPOOF_UNKNOWN_MGMT_EVENT_FLAG			0x0308
-#define IW_REPLAY_ATTACK_EVENT_FLAG					0x0309
-// if add new spoof attack event flag, please upadte the IW_SPOOF_EVENT_FLAG_END
-#define	IW_SPOOF_EVENT_FLAG_END                     0x0309
-#define	IW_SPOOF_EVENT_TYPE_NUM						(IW_SPOOF_EVENT_FLAG_END - IW_SPOOF_EVENT_FLAG_START + 1)
-// For spoof attack event - end
-
-// For flooding attack event - start
-#define	IW_FLOOD_EVENT_FLAG_START                   0x0400
-#define IW_FLOOD_AUTH_EVENT_FLAG					0x0400
-#define IW_FLOOD_ASSOC_REQ_EVENT_FLAG				0x0401
-#define IW_FLOOD_REASSOC_REQ_EVENT_FLAG				0x0402
-#define IW_FLOOD_PROBE_REQ_EVENT_FLAG				0x0403
-#define IW_FLOOD_DISASSOC_EVENT_FLAG				0x0404
-#define IW_FLOOD_DEAUTH_EVENT_FLAG					0x0405
-#define IW_FLOOD_EAP_REQ_EVENT_FLAG					0x0406
-// if add new flooding attack event flag, please upadte the IW_FLOOD_EVENT_FLAG_END
-#define	IW_FLOOD_EVENT_FLAG_END                   	0x0406
-#define	IW_FLOOD_EVENT_TYPE_NUM						(IW_FLOOD_EVENT_FLAG_END - IW_FLOOD_EVENT_FLAG_START + 1)
-// For flooding attack - end
-
-// End - WIRELESS EVENTS definition
-
-#ifdef CONFIG_STA_SUPPORT
-// definition for DLS, kathy
-#define	MAX_NUM_OF_INIT_DLS_ENTRY   1
-#define	MAX_NUM_OF_DLS_ENTRY        MAX_NUMBER_OF_DLS_ENTRY
-
-//Block ACK , rt2860, kathy
-#define MAX_TX_REORDERBUF		64
-#define MAX_RX_REORDERBUF		64
-#define DEFAULT_TX_TIMEOUT		30
-#define DEFAULT_RX_TIMEOUT		30
-#ifndef CONFIG_AP_SUPPORT
-#define MAX_BARECI_SESSION		8
-#endif
-
-#ifndef IW_ESSID_MAX_SIZE
-/* Maximum size of the ESSID and pAd->nickname strings */
-#define IW_ESSID_MAX_SIZE   		32
-#endif
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef MCAST_RATE_SPECIFIC
-#define MCAST_DISABLE	0
-#define MCAST_CCK		1
-#define MCAST_OFDM		2
-#define MCAST_HTMIX		3
-#endif // MCAST_RATE_SPECIFIC //
-
-// For AsicRadioOff/AsicRadioOn function
-#define DOT11POWERSAVE		0
-#define GUIRADIO_OFF		1
-#define RTMP_HALT		    2
-#define GUI_IDLE_POWER_SAVE		3
-// --
-
-
-// definition for WpaSupport flag
-#define WPA_SUPPLICANT_DISABLE				0
-#define WPA_SUPPLICANT_ENABLE				1
-#define	WPA_SUPPLICANT_ENABLE_WITH_WEB_UI	2
-
-// Endian byte swapping codes
-#define SWAP16(x) \
-    ((UINT16)( \
-    (((UINT16)(x) & (UINT16) 0x00ffU) << 8) | \
-    (((UINT16)(x) & (UINT16) 0xff00U) >> 8) ))
-
-#define SWAP32(x) \
-    ((UINT32)( \
-    (((UINT32)(x) & (UINT32) 0x000000ffUL) << 24) | \
-    (((UINT32)(x) & (UINT32) 0x0000ff00UL) <<  8) | \
-    (((UINT32)(x) & (UINT32) 0x00ff0000UL) >>  8) | \
-    (((UINT32)(x) & (UINT32) 0xff000000UL) >> 24) ))
-
-#define SWAP64(x) \
-    ((UINT64)( \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x00000000000000ffULL) << 56) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x000000000000ff00ULL) << 40) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x0000000000ff0000ULL) << 24) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x00000000ff000000ULL) <<  8) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x000000ff00000000ULL) >>  8) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x0000ff0000000000ULL) >> 24) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x00ff000000000000ULL) >> 40) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0xff00000000000000ULL) >> 56) ))
-
-#ifdef RT_BIG_ENDIAN
-
-#define cpu2le64(x) SWAP64((x))
-#define le2cpu64(x) SWAP64((x))
-#define cpu2le32(x) SWAP32((x))
-#define le2cpu32(x) SWAP32((x))
-#define cpu2le16(x) SWAP16((x))
-#define le2cpu16(x) SWAP16((x))
-#define cpu2be64(x) ((UINT64)(x))
-#define be2cpu64(x) ((UINT64)(x))
-#define cpu2be32(x) ((UINT32)(x))
-#define be2cpu32(x) ((UINT32)(x))
-#define cpu2be16(x) ((UINT16)(x))
-#define be2cpu16(x) ((UINT16)(x))
-
-#else   // Little_Endian
-
-#define cpu2le64(x) ((UINT64)(x))
-#define le2cpu64(x) ((UINT64)(x))
-#define cpu2le32(x) ((UINT32)(x))
-#define le2cpu32(x) ((UINT32)(x))
-#define cpu2le16(x) ((UINT16)(x))
-#define le2cpu16(x) ((UINT16)(x))
-#define cpu2be64(x) SWAP64((x))
-#define be2cpu64(x) SWAP64((x))
-#define cpu2be32(x) SWAP32((x))
-#define be2cpu32(x) SWAP32((x))
-#define cpu2be16(x) SWAP16((x))
-#define be2cpu16(x) SWAP16((x))
-
-#endif  // RT_BIG_ENDIAN
-
-#endif  // __RTMP_DEF_H__
-
-
+#include "../rt2860/rtmp_def.h"
diff --git a/drivers/staging/rt2870/rtmp_type.h b/drivers/staging/rt2870/rtmp_type.h
index 1fd7df1..fbf97d0 100644
--- a/drivers/staging/rt2870/rtmp_type.h
+++ b/drivers/staging/rt2870/rtmp_type.h
@@ -1,94 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    rtmp_type.h
-
-    Abstract:
-
-    Revision History:
-    Who         When            What
-    --------    ----------      ----------------------------------------------
-    Name        Date            Modification logs
-    Paul Lin    1-2-2004
-*/
-#ifndef __RTMP_TYPE_H__
-#define __RTMP_TYPE_H__
-
-#define PACKED  __attribute__ ((packed))
-
-// Put platform dependent declaration here
-// For example, linux type definition
-typedef unsigned char		UINT8;
-typedef unsigned short		UINT16;
-typedef unsigned int		UINT32;
-typedef unsigned long long	UINT64;
-typedef int					INT32;
-typedef long long 			INT64;
-
-typedef unsigned char *			PUINT8;
-typedef unsigned short *		PUINT16;
-typedef unsigned int *			PUINT32;
-typedef unsigned long long *	PUINT64;
-typedef int	*					PINT32;
-typedef long long * 			PINT64;
-
-typedef signed char			CHAR;
-typedef signed short		SHORT;
-typedef signed int			INT;
-typedef signed long			LONG;
-typedef signed long long	LONGLONG;
-
-
-typedef unsigned char		UCHAR;
-typedef unsigned short		USHORT;
-typedef unsigned int		UINT;
-typedef unsigned long		ULONG;
-typedef unsigned long long	ULONGLONG;
-
-typedef unsigned char		BOOLEAN;
-typedef void				VOID;
-
-typedef VOID *				PVOID;
-typedef CHAR *				PCHAR;
-typedef UCHAR * 			PUCHAR;
-typedef USHORT *			PUSHORT;
-typedef LONG *				PLONG;
-typedef ULONG *				PULONG;
-typedef UINT *				PUINT;
-
-typedef unsigned int	NDIS_MEDIA_STATE;
-
-typedef union _LARGE_INTEGER {
-    struct {
-        UINT LowPart;
-        INT32 HighPart;
-    } u;
-    INT64 QuadPart;
-} LARGE_INTEGER;
-
-#endif  // __RTMP_TYPE_H__
-
+#include "../rt2860/rtmp_type.h"
diff --git a/drivers/staging/rt2870/spectrum.h b/drivers/staging/rt2870/spectrum.h
index 94cfa5b..8aa23a18 100644
--- a/drivers/staging/rt2870/spectrum.h
+++ b/drivers/staging/rt2870/spectrum.h
@@ -1,322 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#ifndef __SPECTRUM_H__
-#define __SPECTRUM_H__
-
-#include "rtmp_type.h"
-#include "spectrum_def.h"
-
-typedef struct PACKED _TPC_REPORT_INFO
-{
-	UINT8 TxPwr;
-	UINT8 LinkMargin;
-} TPC_REPORT_INFO, *PTPC_REPORT_INFO;
-
-typedef struct PACKED _CH_SW_ANN_INFO
-{
-	UINT8 ChSwMode;
-	UINT8 Channel;
-	UINT8 ChSwCnt;
-} CH_SW_ANN_INFO, *PCH_SW_ANN_INFO;
-
-typedef union PACKED _MEASURE_REQ_MODE
-{
-#ifdef RT_BIG_ENDIAN
-	struct PACKED
-	{
-		UINT8 Rev1:4;
-		UINT8 Report:1;
-		UINT8 Request:1;
-		UINT8 Enable:1;
-		UINT8 Rev0:1;
-	} field;
-#else
-	struct PACKED
-	{
-		UINT8 Rev0:1;
-		UINT8 Enable:1;
-		UINT8 Request:1;
-		UINT8 Report:1;
-		UINT8 Rev1:4;
-	} field;
-#endif // RT_BIG_ENDIAN //
-	UINT8 word;
-} MEASURE_REQ_MODE, *PMEASURE_REQ_MODE;
-
-typedef struct PACKED _MEASURE_REQ
-{
-	UINT8 ChNum;
-	UINT64 MeasureStartTime;
-	UINT16 MeasureDuration;
-} MEASURE_REQ, *PMEASURE_REQ;
-
-typedef struct PACKED _MEASURE_REQ_INFO
-{
-	UINT8 Token;
-	MEASURE_REQ_MODE ReqMode;
-	UINT8 ReqType;
-	MEASURE_REQ MeasureReq;
-} MEASURE_REQ_INFO, *PMEASURE_REQ_INFO;
-
-typedef union PACKED _MEASURE_BASIC_REPORT_MAP
-{
-#ifdef RT_BIG_ENDIAN
-	struct PACKED
-	{
-		UINT8 Rev:3;
-		UINT8 Unmeasure:1;
-		UINT8 Radar:1;
-		UINT8 UnidentifiedSignal:1;
-		UINT8 OfdmPreamble:1;
-		UINT8 BSS:1;
-	} field;
-#else
-	struct PACKED
-	{
-		UINT8 BSS:1;
-		UINT8 OfdmPreamble:1;
-		UINT8 UnidentifiedSignal:1;
-		UINT8 Radar:1;
-		UINT8 Unmeasure:1;
-		UINT8 Rev:3;
-	} field;
-#endif // RT_BIG_ENDIAN //
-	UINT8 word;
-} MEASURE_BASIC_REPORT_MAP, *PMEASURE_BASIC_REPORT_MAP;
-
-typedef struct PACKED _MEASURE_BASIC_REPORT
-{
-	UINT8 ChNum;
-	UINT64 MeasureStartTime;
-	UINT16 MeasureDuration;
-	MEASURE_BASIC_REPORT_MAP Map;
-} MEASURE_BASIC_REPORT, *PMEASURE_BASIC_REPORT;
-
-typedef struct PACKED _MEASURE_CCA_REPORT
-{
-	UINT8 ChNum;
-	UINT64 MeasureStartTime;
-	UINT16 MeasureDuration;
-	UINT8 CCA_Busy_Fraction;
-} MEASURE_CCA_REPORT, *PMEASURE_CCA_REPORT;
-
-typedef struct PACKED _MEASURE_RPI_REPORT
-{
-	UINT8 ChNum;
-	UINT64 MeasureStartTime;
-	UINT16 MeasureDuration;
-	UINT8 RPI_Density[8];
-} MEASURE_RPI_REPORT, *PMEASURE_RPI_REPORT;
-
-typedef union PACKED _MEASURE_REPORT_MODE
-{
-	struct PACKED
-	{
-#ifdef RT_BIG_ENDIAN
-		UINT8 Rev:5;
-		UINT8 Refused:1;
-		UINT8 Incapable:1;
-		UINT8 Late:1;
-#else
-		UINT8 Late:1;
-		UINT8 Incapable:1;
-		UINT8 Refused:1;
-		UINT8 Rev:5;
-#endif // RT_BIG_ENDIAN //
-	} field;
-	UINT8 word;
-} MEASURE_REPORT_MODE, *PMEASURE_REPORT_MODE;
-
-typedef struct PACKED _MEASURE_REPORT_INFO
-{
-	UINT8 Token;
-	MEASURE_REPORT_MODE ReportMode;
-	UINT8 ReportType;
-	UINT8 Octect[0];
-} MEASURE_REPORT_INFO, *PMEASURE_REPORT_INFO;
-
-typedef struct PACKED _QUIET_INFO
-{
-	UINT8 QuietCnt;
-	UINT8 QuietPeriod;
-	UINT8 QuietDuration;
-	UINT8 QuietOffset;
-} QUIET_INFO, *PQUIET_INFO;
-
-/*
-	==========================================================================
-	Description:
-		Prepare Measurement request action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueMeasurementReq(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 MeasureToken,
-	IN UINT8 MeasureReqMode,
-	IN UINT8 MeasureReqType,
-	IN UINT8 MeasureCh,
-	IN UINT16 MeasureDuration);
-
-/*
-	==========================================================================
-	Description:
-		Prepare Measurement report action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueMeasurementRep(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 DialogToken,
-	IN UINT8 MeasureToken,
-	IN UINT8 MeasureReqMode,
-	IN UINT8 MeasureReqType,
-	IN UINT8 ReportInfoLen,
-	IN PUINT8 pReportInfo);
-
-/*
-	==========================================================================
-	Description:
-		Prepare TPC Request action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueTPCReq(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UCHAR DialogToken);
-
-/*
-	==========================================================================
-	Description:
-		Prepare TPC Report action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueTPCRep(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 DialogToken,
-	IN UINT8 TxPwr,
-	IN UINT8 LinkMargin);
-
-/*
-	==========================================================================
-	Description:
-		Prepare Channel Switch Announcement action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-		2. Channel switch announcement mode.
-		2. a New selected channel.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueChSwAnn(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 ChSwMode,
-	IN UINT8 NewCh);
-
-/*
-	==========================================================================
-	Description:
-		Spectrun action frames Handler such as channel switch annoucement,
-		measurement report, measurement request actions frames.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-VOID PeerSpectrumAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-/*
-	==========================================================================
-	Description:
-
-	Parametrs:
-
-	Return	: None.
-	==========================================================================
- */
-INT Set_MeasureReq_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_TpcReq_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-VOID MeasureReqTabInit(
-	IN PRTMP_ADAPTER pAd);
-
-VOID MeasureReqTabExit(
-	IN PRTMP_ADAPTER pAd);
-
-VOID TpcReqTabInit(
-	IN PRTMP_ADAPTER pAd);
-
-VOID TpcReqTabExit(
-	IN PRTMP_ADAPTER pAd);
-
-VOID NotifyChSwAnnToPeerAPs(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pRA,
-	IN PUCHAR pTA,
-	IN UINT8 ChSwMode,
-	IN UINT8 Channel);
-#endif // __SPECTRUM_H__ //
-
+#include "../rt2860/spectrum.h"
diff --git a/drivers/staging/rt2870/spectrum_def.h b/drivers/staging/rt2870/spectrum_def.h
index 4ca4817..a65f551 100644
--- a/drivers/staging/rt2870/spectrum_def.h
+++ b/drivers/staging/rt2870/spectrum_def.h
@@ -1,95 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-	spectrum_def.h
-
-    Abstract:
-    Handle association related requests either from WSTA or from local MLME
-
-    Revision History:
-    Who          When          What
-    ---------    ----------    ----------------------------------------------
-	Fonchi Wu    2008	  	   created for 802.11h
- */
-
-#ifndef __SPECTRUM_DEF_H__
-#define __SPECTRUM_DEF_H__
-
-#define MAX_MEASURE_REQ_TAB_SIZE		3
-#define MAX_HASH_MEASURE_REQ_TAB_SIZE	MAX_MEASURE_REQ_TAB_SIZE
-
-#define MAX_TPC_REQ_TAB_SIZE			3
-#define MAX_HASH_TPC_REQ_TAB_SIZE		MAX_TPC_REQ_TAB_SIZE
-
-#define MIN_RCV_PWR				100		/* Negative value ((dBm) */
-
-#define RM_TPC_REQ				0
-#define RM_MEASURE_REQ			1
-
-#define RM_BASIC				0
-#define RM_CCA					1
-#define RM_RPI_HISTOGRAM		2
-
-#define TPC_REQ_AGE_OUT			500		/* ms */
-#define MQ_REQ_AGE_OUT			500		/* ms */
-
-#define TPC_DIALOGTOKEN_HASH_INDEX(_DialogToken)	((_DialogToken) % MAX_HASH_TPC_REQ_TAB_SIZE)
-#define MQ_DIALOGTOKEN_HASH_INDEX(_DialogToken)		((_DialogToken) % MAX_MEASURE_REQ_TAB_SIZE)
-
-typedef struct _MEASURE_REQ_ENTRY
-{
-	struct _MEASURE_REQ_ENTRY *pNext;
-	ULONG lastTime;
-	BOOLEAN	Valid;
-	UINT8 DialogToken;
-	UINT8 MeasureDialogToken[3];	// 0:basic measure, 1: CCA measure, 2: RPI_Histogram measure.
-} MEASURE_REQ_ENTRY, *PMEASURE_REQ_ENTRY;
-
-typedef struct _MEASURE_REQ_TAB
-{
-	UCHAR Size;
-	PMEASURE_REQ_ENTRY Hash[MAX_HASH_MEASURE_REQ_TAB_SIZE];
-	MEASURE_REQ_ENTRY Content[MAX_MEASURE_REQ_TAB_SIZE];
-} MEASURE_REQ_TAB, *PMEASURE_REQ_TAB;
-
-typedef struct _TPC_REQ_ENTRY
-{
-	struct _TPC_REQ_ENTRY *pNext;
-	ULONG lastTime;
-	BOOLEAN Valid;
-	UINT8 DialogToken;
-} TPC_REQ_ENTRY, *PTPC_REQ_ENTRY;
-
-typedef struct _TPC_REQ_TAB
-{
-	UCHAR Size;
-	PTPC_REQ_ENTRY Hash[MAX_HASH_TPC_REQ_TAB_SIZE];
-	TPC_REQ_ENTRY Content[MAX_TPC_REQ_TAB_SIZE];
-} TPC_REQ_TAB, *PTPC_REQ_TAB;
-
-#endif // __SPECTRUM_DEF_H__ //
-
+#include "../rt2860/spectrum_def.h"
diff --git a/drivers/staging/rt2870/sta/aironet.c b/drivers/staging/rt2870/sta/aironet.c
index 4af4a19..72b7f2e 100644
--- a/drivers/staging/rt2870/sta/aironet.c
+++ b/drivers/staging/rt2870/sta/aironet.c
@@ -1,1312 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	aironet.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Paul Lin	04-06-15		Initial
-*/
-#include "../rt_config.h"
-
-/*
-	==========================================================================
-	Description:
-		association	state machine init,	including state	transition and timer init
-	Parameters:
-		S -	pointer	to the association state machine
-	==========================================================================
- */
-VOID	AironetStateMachineInit(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	STATE_MACHINE		*S,
-	OUT	STATE_MACHINE_FUNC	Trans[])
-{
-	StateMachineInit(S,	Trans, MAX_AIRONET_STATE, MAX_AIRONET_MSG, (STATE_MACHINE_FUNC)Drop, AIRONET_IDLE, AIRONET_MACHINE_BASE);
-	StateMachineSetAction(S, AIRONET_IDLE, MT2_AIRONET_MSG, (STATE_MACHINE_FUNC)AironetMsgAction);
-	StateMachineSetAction(S, AIRONET_IDLE, MT2_AIRONET_SCAN_REQ, (STATE_MACHINE_FUNC)AironetRequestAction);
-	StateMachineSetAction(S, AIRONET_SCANNING, MT2_AIRONET_SCAN_DONE, (STATE_MACHINE_FUNC)AironetReportAction);
-}
-
-/*
-	==========================================================================
-	Description:
-		This is	state machine function.
-		When receiving EAPOL packets which is  for 802.1x key management.
-		Use	both in	WPA, and WPAPSK	case.
-		In this	function, further dispatch to different	functions according	to the received	packet.	 3 categories are :
-		  1.  normal 4-way pairwisekey and 2-way groupkey handshake
-		  2.  MIC error	(Countermeasures attack)  report packet	from STA.
-		  3.  Request for pairwise/group key update	from STA
-	Return:
-	==========================================================================
-*/
-VOID	AironetMsgAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-{
-	USHORT							Length;
-	UCHAR							Index, i;
-	PUCHAR							pData;
-	PAIRONET_RM_REQUEST_FRAME		pRMReq;
-	PRM_REQUEST_ACTION				pReqElem;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("-----> AironetMsgAction\n"));
-
-	// 0. Get Aironet IAPP header first
-	pRMReq = (PAIRONET_RM_REQUEST_FRAME) &Elem->Msg[LENGTH_802_11];
-	pData  = (PUCHAR) &Elem->Msg[LENGTH_802_11];
-
-	// 1. Change endian format form network to little endian
-	Length = be2cpu16(pRMReq->IAPP.Length);
-
-	// 2.0 Sanity check, this should only happen when CCX 2.0 support is enabled
-	if (pAd->StaCfg.CCXEnable != TRUE)
-		return;
-
-	// 2.1 Radio measurement must be on
-	if (pAd->StaCfg.CCXControl.field.RMEnable != 1)
-		return;
-
-	// 2.2. Debug print all bit information
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP ID & Length %d\n", Length));
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP Type %x\n", pRMReq->IAPP.Type));
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP SubType %x\n", pRMReq->IAPP.SubType));
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP Dialog Token %x\n", pRMReq->IAPP.Token));
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP Activation Delay %x\n", pRMReq->Delay));
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP Measurement Offset %x\n", pRMReq->Offset));
-
-	// 3. Check IAPP frame type, it must be 0x32 for Cisco Aironet extension
-	if (pRMReq->IAPP.Type != AIRONET_IAPP_TYPE)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Wrong IAPP type for Cisco Aironet extension\n"));
-		return;
-	}
-
-	// 4. Check IAPP frame subtype, it must be 0x01 for Cisco Aironet extension request.
-	//    Since we are acting as client only, we will disregards reply subtype.
-	if (pRMReq->IAPP.SubType != AIRONET_IAPP_SUBTYPE_REQUEST)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Wrong IAPP subtype for Cisco Aironet extension\n"));
-		return;
-	}
-
-	// 5. Verify Destination MAC and Source MAC, both should be all zeros.
-	if (! MAC_ADDR_EQUAL(pRMReq->IAPP.DA, ZERO_MAC_ADDR))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Wrong IAPP DA for Cisco Aironet extension, it's not Zero\n"));
-		return;
-	}
-
-	if (! MAC_ADDR_EQUAL(pRMReq->IAPP.SA, ZERO_MAC_ADDR))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Wrong IAPP SA for Cisco Aironet extension, it's not Zero\n"));
-		return;
-	}
-
-	// 6. Reinit all report related fields
-	NdisZeroMemory(pAd->StaCfg.FrameReportBuf, 2048);
-	NdisZeroMemory(pAd->StaCfg.BssReportOffset, sizeof(USHORT) * MAX_LEN_OF_BSS_TABLE);
-	NdisZeroMemory(pAd->StaCfg.MeasurementRequest, sizeof(RM_REQUEST_ACTION) * 4);
-
-	// 7. Point to the start of first element report element
-	pAd->StaCfg.FrameReportLen   = LENGTH_802_11 + sizeof(AIRONET_IAPP_HEADER);
-	DBGPRINT(RT_DEBUG_TRACE, ("FR len = %d\n", pAd->StaCfg.FrameReportLen));
-	pAd->StaCfg.LastBssIndex     = 0xff;
-	pAd->StaCfg.RMReqCnt         = 0;
-	pAd->StaCfg.ParallelReq      = FALSE;
-	pAd->StaCfg.ParallelDuration = 0;
-	pAd->StaCfg.ParallelChannel  = 0;
-	pAd->StaCfg.IAPPToken        = pRMReq->IAPP.Token;
-	pAd->StaCfg.CurrentRMReqIdx  = 0;
-	pAd->StaCfg.CLBusyBytes      = 0;
-	// Reset the statistics
-	for (i = 0; i < 8; i++)
-		pAd->StaCfg.RPIDensity[i] = 0;
-
-	Index = 0;
-
-	// 8. Save dialog token for report
-	pAd->StaCfg.IAPPToken = pRMReq->IAPP.Token;
-
-	// Save Activation delay & measurement offset, Not really needed
-
-	// 9. Point to the first request element
-	pData += sizeof(AIRONET_RM_REQUEST_FRAME);
-	//    Length should exclude the CISCO Aironet SNAP header
-	Length -= (sizeof(AIRONET_RM_REQUEST_FRAME) - LENGTH_802_1_H);
-
-	// 10. Start Parsing the Measurement elements.
-	//    Be careful about multiple MR elements within one frames.
-	while (Length > 0)
-	{
-		pReqElem = (PRM_REQUEST_ACTION) pData;
-		switch (pReqElem->ReqElem.Eid)
-		{
-			case IE_MEASUREMENT_REQUEST:
-				// From the example, it seems we only need to support one request in one frame
-				// There is no multiple request in one frame.
-				// Besides, looks like we need to take care the measurement request only.
-				// The measurement request is always 4 bytes.
-
-				// Start parsing this type of request.
-				// 0. Eid is IE_MEASUREMENT_REQUEST
-				// 1. Length didn't include Eid and Length field, it always be 8.
-				// 2. Measurement Token, we nned to save it for the corresponding report.
-				// 3. Measurement Mode, Although there are definitions, but we din't see value other than
-				//    0 from test specs examples.
-				// 4. Measurement Type, this is what we need to do.
-				switch (pReqElem->ReqElem.Type)
-				{
-					case MSRN_TYPE_CHANNEL_LOAD_REQ:
-					case MSRN_TYPE_NOISE_HIST_REQ:
-					case MSRN_TYPE_BEACON_REQ:
-						// Check the Enable non-serving channel measurement control
-						if (pAd->StaCfg.CCXControl.field.DCRMEnable == 0)
-						{
-							// Check channel before enqueue the action
-							if (pReqElem->Measurement.Channel != pAd->CommonCfg.Channel)
-								break;
-						}
-						else
-						{
-							// If off channel measurement, check the TU duration limit
-							if (pReqElem->Measurement.Channel != pAd->CommonCfg.Channel)
-								if (pReqElem->Measurement.Duration > pAd->StaCfg.CCXControl.field.TuLimit)
-									break;
-						}
-
-						// Save requests and execute actions later
-						NdisMoveMemory(&pAd->StaCfg.MeasurementRequest[Index], pReqElem, sizeof(RM_REQUEST_ACTION));
-						Index += 1;
-						break;
-
-					case MSRN_TYPE_FRAME_REQ:
-						// Since it's option, we will support later
-						// FrameRequestAction(pAd, pData);
-						break;
-
-					default:
-						break;
-				}
-
-				// Point to next Measurement request
-				pData  += sizeof(RM_REQUEST_ACTION);
-				Length -= sizeof(RM_REQUEST_ACTION);
-				break;
-
-			// We accept request only, all others are dropped
-			case IE_MEASUREMENT_REPORT:
-			case IE_AP_TX_POWER:
-			case IE_MEASUREMENT_CAPABILITY:
-			default:
-				return;
-		}
-	}
-
-	// 11. Update some flags and index
-	pAd->StaCfg.RMReqCnt = Index;
-
-	if (Index)
-	{
-		MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_REQ, 0, NULL);
-		RT28XX_MLME_HANDLER(pAd);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<----- AironetMsgAction\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	AironetRequestAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-{
-	PRM_REQUEST_ACTION	pReq;
-
-	// 1. Point to next request element
-	pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[pAd->StaCfg.CurrentRMReqIdx];
-
-	// 2. Parse measurement type and call appropriate functions
-	if (pReq->ReqElem.Type == MSRN_TYPE_CHANNEL_LOAD_REQ)
-		// Channel Load measurement request
-		ChannelLoadRequestAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else if (pReq->ReqElem.Type == MSRN_TYPE_NOISE_HIST_REQ)
-		// Noise Histogram measurement request
-		NoiseHistRequestAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else if (pReq->ReqElem.Type == MSRN_TYPE_BEACON_REQ)
-		// Beacon measurement request
-		BeaconRequestAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else
-		// Unknown. Do nothing and return, this should never happen
-		return;
-
-	// 3. Peek into the next request, if it's parallel, we will update the scan time to the largest one
-	if ((pAd->StaCfg.CurrentRMReqIdx + 1) < pAd->StaCfg.RMReqCnt)
-	{
-		pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[pAd->StaCfg.CurrentRMReqIdx + 1];
-		// Check for parallel bit
-		if ((pReq->ReqElem.Mode & 0x01) && (pReq->Measurement.Channel == pAd->StaCfg.CCXScanChannel))
-		{
-			// Update parallel mode request information
-			pAd->StaCfg.ParallelReq = TRUE;
-			pAd->StaCfg.CCXScanTime = ((pReq->Measurement.Duration > pAd->StaCfg.CCXScanTime) ?
-			(pReq->Measurement.Duration) : (pAd->StaCfg.CCXScanTime));
-		}
-	}
-
-	// 4. Call RT28XX_MLME_HANDLER to execute the request mlme commands, Scan request is the only one used
-	RT28XX_MLME_HANDLER(pAd);
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Prepare channel load report action, special scan operation added
-		to support
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		pData		Start from element ID
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	ChannelLoadRequestAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	PRM_REQUEST_ACTION				pReq;
-	MLME_SCAN_REQ_STRUCT			ScanReq;
-	UCHAR							ZeroSsid[32];
-	NDIS_STATUS						NStatus;
-	PUCHAR							pOutBuffer = NULL;
-	PHEADER_802_11					pNullFrame;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ChannelLoadRequestAction ----->\n"));
-
-	pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[Index];
-	NdisZeroMemory(ZeroSsid, 32);
-
-	// Prepare for special scan request
-	// The scan definition is different with our Active, Passive scan definition.
-	// For CCX2, Active means send out probe request with broadcast BSSID.
-	// Passive means no probe request sent, only listen to the beacons.
-	// The channel scanned is fixed as specified, no need to scan all channels.
-	// The scan wait time is specified in the request too.
-	// Passive scan Mode
-
-	// Control state machine is not idle, reject the request
-	if ((pAd->Mlme.CntlMachine.CurrState != CNTL_IDLE) && (Index == 0))
-		return;
-
-	// Fill out stuff for scan request
-	ScanParmFill(pAd, &ScanReq, ZeroSsid, 0, BSS_ANY, SCAN_CISCO_CHANNEL_LOAD);
-	MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-	pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-
-	// Reset some internal control flags to make sure this scan works.
-	BssTableInit(&pAd->StaCfg.CCXBssTab);
-	pAd->StaCfg.ScanCnt        = 0;
-	pAd->StaCfg.CCXScanChannel = pReq->Measurement.Channel;
-	pAd->StaCfg.CCXScanTime    = pReq->Measurement.Duration;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Duration %d, Channel %d!\n", pReq->Measurement.Duration, pReq->Measurement.Channel));
-
-	// If it's non serving channel scan, send out a null frame with PSM bit on.
-	if (pAd->StaCfg.CCXScanChannel != pAd->CommonCfg.Channel)
-	{
-		// Use MLME enqueue method
-		NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-		if (NStatus	!= NDIS_STATUS_SUCCESS)
-			return;
-
-		pNullFrame = (PHEADER_802_11) pOutBuffer;;
-		// Make the power save Null frame with PSM bit on
-		MgtMacHeaderInit(pAd, pNullFrame, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-		pNullFrame->Duration 	= 0;
-		pNullFrame->FC.Type 	= BTYPE_DATA;
-		pNullFrame->FC.PwrMgmt	= PWR_SAVE;
-
-		// Send using priority queue
-		MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-		MlmeFreeMemory(pAd, pOutBuffer);
-		DBGPRINT(RT_DEBUG_TRACE, ("Send PSM Data frame for off channel RM\n"));
-		RTMPusecDelay(5000);
-	}
-
-	pAd->StaCfg.CCXReqType     = MSRN_TYPE_CHANNEL_LOAD_REQ;
-	pAd->StaCfg.CLBusyBytes    = 0;
-	// Enable Rx with promiscuous reception
-	RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, 0x1010);
-
-	// Set channel load measurement flag
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_MEASUREMENT);
-
-	pAd->Mlme.AironetMachine.CurrState = AIRONET_SCANNING;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ChannelLoadRequestAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Prepare noise histogram report action, special scan operation added
-		to support
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		pData		Start from element ID
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	NoiseHistRequestAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	PRM_REQUEST_ACTION				pReq;
-	MLME_SCAN_REQ_STRUCT			ScanReq;
-	UCHAR							ZeroSsid[32], i;
-	NDIS_STATUS						NStatus;
-	PUCHAR							pOutBuffer = NULL;
-	PHEADER_802_11					pNullFrame;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("NoiseHistRequestAction ----->\n"));
-
-	pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[Index];
-	NdisZeroMemory(ZeroSsid, 32);
-
-	// Prepare for special scan request
-	// The scan definition is different with our Active, Passive scan definition.
-	// For CCX2, Active means send out probe request with broadcast BSSID.
-	// Passive means no probe request sent, only listen to the beacons.
-	// The channel scanned is fixed as specified, no need to scan all channels.
-	// The scan wait time is specified in the request too.
-	// Passive scan Mode
-
-	// Control state machine is not idle, reject the request
-	if ((pAd->Mlme.CntlMachine.CurrState != CNTL_IDLE) && (Index == 0))
-		return;
-
-	// Fill out stuff for scan request
-	ScanParmFill(pAd, &ScanReq, ZeroSsid, 0, BSS_ANY, SCAN_CISCO_NOISE);
-	MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-	pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-
-	// Reset some internal control flags to make sure this scan works.
-	BssTableInit(&pAd->StaCfg.CCXBssTab);
-	pAd->StaCfg.ScanCnt        = 0;
-	pAd->StaCfg.CCXScanChannel = pReq->Measurement.Channel;
-	pAd->StaCfg.CCXScanTime    = pReq->Measurement.Duration;
-	pAd->StaCfg.CCXReqType     = MSRN_TYPE_NOISE_HIST_REQ;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Duration %d, Channel %d!\n", pReq->Measurement.Duration, pReq->Measurement.Channel));
-
-	// If it's non serving channel scan, send out a null frame with PSM bit on.
-	if (pAd->StaCfg.CCXScanChannel != pAd->CommonCfg.Channel)
-	{
-		// Use MLME enqueue method
-		NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-		if (NStatus	!= NDIS_STATUS_SUCCESS)
-			return;
-
-		pNullFrame = (PHEADER_802_11) pOutBuffer;
-		// Make the power save Null frame with PSM bit on
-		MgtMacHeaderInit(pAd, pNullFrame, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-		pNullFrame->Duration 	= 0;
-		pNullFrame->FC.Type  	= BTYPE_DATA;
-		pNullFrame->FC.PwrMgmt	= PWR_SAVE;
-
-		// Send using priority queue
-		MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-		MlmeFreeMemory(pAd, pOutBuffer);
-		DBGPRINT(RT_DEBUG_TRACE, ("Send PSM Data frame for off channel RM\n"));
-		RTMPusecDelay(5000);
-	}
-
-	// Reset the statistics
-	for (i = 0; i < 8; i++)
-		pAd->StaCfg.RPIDensity[i] = 0;
-
-	// Enable Rx with promiscuous reception
-	RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, 0x1010);
-
-	// Set channel load measurement flag
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_MEASUREMENT);
-
-	pAd->Mlme.AironetMachine.CurrState = AIRONET_SCANNING;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("NoiseHistRequestAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Prepare Beacon report action, special scan operation added
-		to support
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		pData		Start from element ID
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	BeaconRequestAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	PRM_REQUEST_ACTION				pReq;
-	NDIS_STATUS						NStatus;
-	PUCHAR							pOutBuffer = NULL;
-	PHEADER_802_11					pNullFrame;
-	MLME_SCAN_REQ_STRUCT			ScanReq;
-	UCHAR							ZeroSsid[32];
-
-	DBGPRINT(RT_DEBUG_TRACE, ("BeaconRequestAction ----->\n"));
-
-	pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[Index];
-	NdisZeroMemory(ZeroSsid, 32);
-
-	// Prepare for special scan request
-	// The scan definition is different with our Active, Passive scan definition.
-	// For CCX2, Active means send out probe request with broadcast BSSID.
-	// Passive means no probe request sent, only listen to the beacons.
-	// The channel scanned is fixed as specified, no need to scan all channels.
-	// The scan wait time is specified in the request too.
-	if (pReq->Measurement.ScanMode == MSRN_SCAN_MODE_PASSIVE)
-	{
-		// Passive scan Mode
-		DBGPRINT(RT_DEBUG_TRACE, ("Passive Scan Mode!\n"));
-
-		// Control state machine is not idle, reject the request
-		if ((pAd->Mlme.CntlMachine.CurrState != CNTL_IDLE) && (Index == 0))
-			return;
-
-		// Fill out stuff for scan request
-		ScanParmFill(pAd, &ScanReq, ZeroSsid, 0, BSS_ANY, SCAN_CISCO_PASSIVE);
-		MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-
-		// Reset some internal control flags to make sure this scan works.
-		BssTableInit(&pAd->StaCfg.CCXBssTab);
-		pAd->StaCfg.ScanCnt        = 0;
-		pAd->StaCfg.CCXScanChannel = pReq->Measurement.Channel;
-		pAd->StaCfg.CCXScanTime    = pReq->Measurement.Duration;
-		pAd->StaCfg.CCXReqType     = MSRN_TYPE_BEACON_REQ;
-		DBGPRINT(RT_DEBUG_TRACE, ("Duration %d!\n", pReq->Measurement.Duration));
-
-		// If it's non serving channel scan, send out a null frame with PSM bit on.
-		if (pAd->StaCfg.CCXScanChannel != pAd->CommonCfg.Channel)
-		{
-			// Use MLME enqueue method
-			NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-			if (NStatus	!= NDIS_STATUS_SUCCESS)
-				return;
-
-			pNullFrame = (PHEADER_802_11) pOutBuffer;
-			// Make the power save Null frame with PSM bit on
-			MgtMacHeaderInit(pAd, pNullFrame, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-			pNullFrame->Duration 	= 0;
-			pNullFrame->FC.Type     = BTYPE_DATA;
-			pNullFrame->FC.PwrMgmt  = PWR_SAVE;
-
-			// Send using priority queue
-			MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-			MlmeFreeMemory(pAd, pOutBuffer);
-			DBGPRINT(RT_DEBUG_TRACE, ("Send PSM Data frame for off channel RM\n"));
-			RTMPusecDelay(5000);
-		}
-
-		pAd->Mlme.AironetMachine.CurrState = AIRONET_SCANNING;
-	}
-	else if (pReq->Measurement.ScanMode == MSRN_SCAN_MODE_ACTIVE)
-	{
-		// Active scan Mode
-		DBGPRINT(RT_DEBUG_TRACE, ("Active Scan Mode!\n"));
-
-		// Control state machine is not idle, reject the request
-		if (pAd->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-			return;
-
-		// Fill out stuff for scan request
-		ScanParmFill(pAd, &ScanReq, ZeroSsid, 0, BSS_ANY, SCAN_CISCO_ACTIVE);
-		MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-
-		// Reset some internal control flags to make sure this scan works.
-		BssTableInit(&pAd->StaCfg.CCXBssTab);
-		pAd->StaCfg.ScanCnt        = 0;
-		pAd->StaCfg.CCXScanChannel = pReq->Measurement.Channel;
-		pAd->StaCfg.CCXScanTime    = pReq->Measurement.Duration;
-		pAd->StaCfg.CCXReqType     = MSRN_TYPE_BEACON_REQ;
-		DBGPRINT(RT_DEBUG_TRACE, ("Duration %d!\n", pReq->Measurement.Duration));
-
-		// If it's non serving channel scan, send out a null frame with PSM bit on.
-		if (pAd->StaCfg.CCXScanChannel != pAd->CommonCfg.Channel)
-		{
-			// Use MLME enqueue method
-			NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-			if (NStatus	!= NDIS_STATUS_SUCCESS)
-				return;
-
-			pNullFrame = (PHEADER_802_11) pOutBuffer;
-			// Make the power save Null frame with PSM bit on
-			MgtMacHeaderInit(pAd, pNullFrame, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-			pNullFrame->Duration 	= 0;
-			pNullFrame->FC.Type     = BTYPE_DATA;
-			pNullFrame->FC.PwrMgmt  = PWR_SAVE;
-
-			// Send using priority queue
-			MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-			MlmeFreeMemory(pAd, pOutBuffer);
-			DBGPRINT(RT_DEBUG_TRACE, ("Send PSM Data frame for off channel RM\n"));
-			RTMPusecDelay(5000);
-		}
-
-		pAd->Mlme.AironetMachine.CurrState = AIRONET_SCANNING;
-	}
-	else if (pReq->Measurement.ScanMode == MSRN_SCAN_MODE_BEACON_TABLE)
-	{
-		// Beacon report Mode, report all the APS in current bss table
-		DBGPRINT(RT_DEBUG_TRACE, ("Beacon Report Mode!\n"));
-
-		// Copy current BSS table to CCX table, we can omit this step later on.
-		NdisMoveMemory(&pAd->StaCfg.CCXBssTab, &pAd->ScanTab, sizeof(BSS_TABLE));
-
-		// Create beacon report from Bss table
-		AironetCreateBeaconReportFromBssTable(pAd);
-
-		// Set state to scanning
-		pAd->Mlme.AironetMachine.CurrState = AIRONET_SCANNING;
-
-		// Enqueue report request
-		// Cisco scan request is finished, prepare beacon report
-		MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_DONE, 0, NULL);
-	}
-	else
-	{
-		// Wrong scan Mode
-		DBGPRINT(RT_DEBUG_TRACE, ("Wrong Scan Mode!\n"));
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("BeaconRequestAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	AironetReportAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-{
-	PRM_REQUEST_ACTION	pReq;
-	ULONG				Now32;
-
-    NdisGetSystemUpTime(&Now32);
-	pAd->StaCfg.LastBeaconRxTime = Now32;
-
-	pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[pAd->StaCfg.CurrentRMReqIdx];
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AironetReportAction ----->\n"));
-
-	// 1. Parse measurement type and call appropriate functions
-	if (pReq->ReqElem.Type == MSRN_TYPE_CHANNEL_LOAD_REQ)
-		// Channel Load measurement request
-		ChannelLoadReportAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else if (pReq->ReqElem.Type == MSRN_TYPE_NOISE_HIST_REQ)
-		// Noise Histogram measurement request
-		NoiseHistReportAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else if (pReq->ReqElem.Type == MSRN_TYPE_BEACON_REQ)
-		// Beacon measurement request
-		BeaconReportAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else
-		// Unknown. Do nothing and return
-		;
-
-	// 2. Point to the correct index of action element, start from 0
-	pAd->StaCfg.CurrentRMReqIdx++;
-
-	// 3. Check for parallel actions
-	if (pAd->StaCfg.ParallelReq == TRUE)
-	{
-		pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[pAd->StaCfg.CurrentRMReqIdx];
-
-		// Process next action right away
-		if (pReq->ReqElem.Type == MSRN_TYPE_CHANNEL_LOAD_REQ)
-			// Channel Load measurement request
-			ChannelLoadReportAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-		else if (pReq->ReqElem.Type == MSRN_TYPE_NOISE_HIST_REQ)
-			// Noise Histogram measurement request
-			NoiseHistReportAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-
-		pAd->StaCfg.ParallelReq = FALSE;
-		pAd->StaCfg.CurrentRMReqIdx++;
-	}
-
-	if (pAd->StaCfg.CurrentRMReqIdx >= pAd->StaCfg.RMReqCnt)
-	{
-		// 4. There is no more unprocessed measurement request, go for transmit this report
-		AironetFinalReportAction(pAd);
-		pAd->Mlme.AironetMachine.CurrState = AIRONET_IDLE;
-	}
-	else
-	{
-		pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[pAd->StaCfg.CurrentRMReqIdx];
-
-		if (pReq->Measurement.Channel != pAd->CommonCfg.Channel)
-		{
-			RTMPusecDelay(100000);
-		}
-
-		// 5. There are more requests to be measure
-		MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_REQ, 0, NULL);
-		RT28XX_MLME_HANDLER(pAd);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AironetReportAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	AironetFinalReportAction(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	PUCHAR					pDest;
-	PAIRONET_IAPP_HEADER	pIAPP;
-	PHEADER_802_11			pHeader;
-	UCHAR					AckRate = RATE_2;
-	USHORT					AckDuration = 0;
-	NDIS_STATUS				NStatus;
-	PUCHAR					pOutBuffer = NULL;
-	ULONG					FrameLen = 0;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AironetFinalReportAction ----->\n"));
-
-	// 0. Set up the frame pointer, Frame was inited at the end of message action
-	pDest = &pAd->StaCfg.FrameReportBuf[LENGTH_802_11];
-
-	// 1. Update report IAPP fields
-	pIAPP = (PAIRONET_IAPP_HEADER) pDest;
-
-	// 2. Copy Cisco SNAP header
-	NdisMoveMemory(pIAPP->CiscoSnapHeader, SNAP_AIRONET, LENGTH_802_1_H);
-
-	// 3. network order for this 16bit length
-	pIAPP->Length  = cpu2be16(pAd->StaCfg.FrameReportLen - LENGTH_802_11 - LENGTH_802_1_H);
-
-	// 3.1 sanity check the report length, ignore it if there is nothing to report
-	if (be2cpu16(pIAPP->Length) <= 18)
-		return;
-
-	// 4. Type must be 0x32
-	pIAPP->Type    = AIRONET_IAPP_TYPE;
-
-	// 5. SubType for report must be 0x81
-	pIAPP->SubType = AIRONET_IAPP_SUBTYPE_REPORT;
-
-	// 6. DA is not used and must be zero, although the whole frame was cleared at the start of function
-	//    We will do it again here. We can use BSSID instead
-	COPY_MAC_ADDR(pIAPP->DA, pAd->CommonCfg.Bssid);
-
-	// 7. SA is the client reporting which must be our MAC
-	COPY_MAC_ADDR(pIAPP->SA, pAd->CurrentAddress);
-
-	// 8. Copy the saved dialog token
-	pIAPP->Token = pAd->StaCfg.IAPPToken;
-
-	// 9. Make the Report frame 802.11 header
-	//    Reuse function in wpa.c
-	pHeader = (PHEADER_802_11) pAd->StaCfg.FrameReportBuf;
-	pAd->Sequence ++;
-	WpaMacHeaderInit(pAd, pHeader, 0, pAd->CommonCfg.Bssid);
-
-	// ACK size	is 14 include CRC, and its rate	is based on real time information
-	AckRate     = pAd->CommonCfg.ExpectedACKRate[pAd->CommonCfg.MlmeRate];
-	AckDuration = RTMPCalcDuration(pAd, AckRate, 14);
-	pHeader->Duration = pAd->CommonCfg.Dsifs + AckDuration;
-
-	// Use MLME enqueue method
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus	!= NDIS_STATUS_SUCCESS)
-		return;
-
-	// 10. Prepare report frame with dynamic outbuffer. Just simply copy everything.
-	MakeOutgoingFrame(pOutBuffer,                       &FrameLen,
-	                  pAd->StaCfg.FrameReportLen, pAd->StaCfg.FrameReportBuf,
-		              END_OF_ARGS);
-
-	// 11. Send using priority queue
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	pAd->StaCfg.CCXReqType = MSRN_TYPE_UNUSED;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AironetFinalReportAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	ChannelLoadReportAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	PMEASUREMENT_REPORT_ELEMENT	pReport;
-	PCHANNEL_LOAD_REPORT		pLoad;
-	PUCHAR						pDest;
-	UCHAR						CCABusyFraction;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ChannelLoadReportAction ----->\n"));
-
-	// Disable Rx with promiscuous reception, make it back to normal
-	RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, STANORMAL); // Staion not drop control frame will fail WiFi Certification.
-
-	// 0. Setup pointer for processing beacon & probe response
-	pDest = (PUCHAR) &pAd->StaCfg.FrameReportBuf[pAd->StaCfg.FrameReportLen];
-	pReport = (PMEASUREMENT_REPORT_ELEMENT) pDest;
-
-	// 1. Fill Measurement report element field.
-	pReport->Eid    = IE_MEASUREMENT_REPORT;
-	// Fixed Length at 9, not include Eid and length fields
-	pReport->Length = 9;
-	pReport->Token  = pAd->StaCfg.MeasurementRequest[Index].ReqElem.Token;
-	pReport->Mode   = pAd->StaCfg.MeasurementRequest[Index].ReqElem.Mode;
-	pReport->Type   = MSRN_TYPE_CHANNEL_LOAD_REQ;
-
-	// 2. Fill channel report measurement data
-	pDest += sizeof(MEASUREMENT_REPORT_ELEMENT);
-	pLoad  = (PCHANNEL_LOAD_REPORT) pDest;
-	pLoad->Channel  = pAd->StaCfg.MeasurementRequest[Index].Measurement.Channel;
-	pLoad->Spare    = 0;
-	pLoad->Duration = pAd->StaCfg.MeasurementRequest[Index].Measurement.Duration;
-
-	// 3. Calculate the CCA Busy Fraction
-	//    (Bytes + ACK size) * 8 / Tx speed * 255 / 1000 / measurement duration, use 24 us Tx speed
-	//     =  (Bytes + ACK) / 12 / duration
-	//     9 is the good value for pAd->StaCfg.CLFactor
-	// CCABusyFraction = (UCHAR) (pAd->StaCfg.CLBusyBytes / 9 / pLoad->Duration);
-	CCABusyFraction = (UCHAR) (pAd->StaCfg.CLBusyBytes / pAd->StaCfg.CLFactor / pLoad->Duration);
-	if (CCABusyFraction < 10)
-			CCABusyFraction = (UCHAR) (pAd->StaCfg.CLBusyBytes / 3 / pLoad->Duration) + 1;
-
-	pLoad->CCABusy = CCABusyFraction;
-	DBGPRINT(RT_DEBUG_TRACE, ("CLBusyByte %ld, Duration %d, Result, %d\n", pAd->StaCfg.CLBusyBytes, pLoad->Duration, CCABusyFraction));
-
-	DBGPRINT(RT_DEBUG_TRACE, ("FrameReportLen %d\n", pAd->StaCfg.FrameReportLen));
-	pAd->StaCfg.FrameReportLen += (sizeof(MEASUREMENT_REPORT_ELEMENT) + sizeof(CHANNEL_LOAD_REPORT));
-	DBGPRINT(RT_DEBUG_TRACE, ("FrameReportLen %d\n", pAd->StaCfg.FrameReportLen));
-
-	// 4. Clear channel load measurement flag
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_RADIO_MEASUREMENT);
-
-	// 5. reset to idle state
-	pAd->Mlme.AironetMachine.CurrState = AIRONET_IDLE;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ChannelLoadReportAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	NoiseHistReportAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	PMEASUREMENT_REPORT_ELEMENT	pReport;
-	PNOISE_HIST_REPORT			pNoise;
-	PUCHAR						pDest;
-	UCHAR						i,NoiseCnt;
-	USHORT						TotalRPICnt, TotalRPISum;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("NoiseHistReportAction ----->\n"));
-
-	// 0. Disable Rx with promiscuous reception, make it back to normal
-	RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, STANORMAL); // Staion not drop control frame will fail WiFi Certification.
-	// 1. Setup pointer for processing beacon & probe response
-	pDest = (PUCHAR) &pAd->StaCfg.FrameReportBuf[pAd->StaCfg.FrameReportLen];
-	pReport = (PMEASUREMENT_REPORT_ELEMENT) pDest;
-
-	// 2. Fill Measurement report element field.
-	pReport->Eid    = IE_MEASUREMENT_REPORT;
-	// Fixed Length at 16, not include Eid and length fields
-	pReport->Length = 16;
-	pReport->Token  = pAd->StaCfg.MeasurementRequest[Index].ReqElem.Token;
-	pReport->Mode   = pAd->StaCfg.MeasurementRequest[Index].ReqElem.Mode;
-	pReport->Type   = MSRN_TYPE_NOISE_HIST_REQ;
-
-	// 3. Fill noise histogram report measurement data
-	pDest += sizeof(MEASUREMENT_REPORT_ELEMENT);
-	pNoise  = (PNOISE_HIST_REPORT) pDest;
-	pNoise->Channel  = pAd->StaCfg.MeasurementRequest[Index].Measurement.Channel;
-	pNoise->Spare    = 0;
-	pNoise->Duration = pAd->StaCfg.MeasurementRequest[Index].Measurement.Duration;
-	// 4. Fill Noise histogram, the total RPI counts should be 0.4 * TU
-	//    We estimate 4000 normal packets received durning 10 seconds test.
-	//    Adjust it if required.
-	// 3 is a good value for pAd->StaCfg.NHFactor
-	// TotalRPICnt = pNoise->Duration * 3 / 10;
-	TotalRPICnt = pNoise->Duration * pAd->StaCfg.NHFactor / 10;
-	TotalRPISum = 0;
-
-	for (i = 0; i < 8; i++)
-	{
-		TotalRPISum += pAd->StaCfg.RPIDensity[i];
-		DBGPRINT(RT_DEBUG_TRACE, ("RPI %d Conuts %d\n", i, pAd->StaCfg.RPIDensity[i]));
-	}
-
-	// Double check if the counter is larger than our expectation.
-	// We will replace it with the total number plus a fraction.
-	if (TotalRPISum > TotalRPICnt)
-		TotalRPICnt = TotalRPISum + pNoise->Duration / 20;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Total RPI Conuts %d\n", TotalRPICnt));
-
-	// 5. Initialize noise count for the total summation of 0xff
-	NoiseCnt = 0;
-	for (i = 1; i < 8; i++)
-	{
-		pNoise->Density[i] = (UCHAR) (pAd->StaCfg.RPIDensity[i] * 255 / TotalRPICnt);
-		if ((pNoise->Density[i] == 0) && (pAd->StaCfg.RPIDensity[i] != 0))
-			pNoise->Density[i]++;
-		NoiseCnt += pNoise->Density[i];
-		DBGPRINT(RT_DEBUG_TRACE, ("Reported RPI[%d]  = 0x%02x\n", i, pNoise->Density[i]));
-	}
-
-	// 6. RPI[0] represents the rest of counts
-	pNoise->Density[0] = 0xff - NoiseCnt;
-	DBGPRINT(RT_DEBUG_TRACE, ("Reported RPI[0]  = 0x%02x\n", pNoise->Density[0]));
-
-	pAd->StaCfg.FrameReportLen += (sizeof(MEASUREMENT_REPORT_ELEMENT) + sizeof(NOISE_HIST_REPORT));
-
-	// 7. Clear channel load measurement flag
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_RADIO_MEASUREMENT);
-
-	// 8. reset to idle state
-	pAd->Mlme.AironetMachine.CurrState = AIRONET_IDLE;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("NoiseHistReportAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Prepare Beacon report action,
-
-	Arguments:
-		pAd	Pointer	to our adapter
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	BeaconReportAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	DBGPRINT(RT_DEBUG_TRACE, ("BeaconReportAction ----->\n"));
-
-	// Looks like we don't have anything thing need to do here.
-	// All measurement report already finished in AddBeaconReport
-	// The length is in the FrameReportLen
-
-	// reset Beacon index for next beacon request
-	pAd->StaCfg.LastBssIndex = 0xff;
-
-	// reset to idle state
-	pAd->Mlme.AironetMachine.CurrState = AIRONET_IDLE;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("BeaconReportAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-		Index		Current BSSID in CCXBsstab entry index
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	AironetAddBeaconReport(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	ULONG				Index,
-	IN	PMLME_QUEUE_ELEM	pElem)
-{
-	PVOID						pMsg;
-	PUCHAR						pSrc, pDest;
-	UCHAR						ReqIdx;
-	ULONG						MsgLen;
-	USHORT						Length;
-	PFRAME_802_11				pFrame;
-	PMEASUREMENT_REPORT_ELEMENT	pReport;
-	PEID_STRUCT			        pEid;
-	PBEACON_REPORT				pBeaconReport;
-	PBSS_ENTRY					pBss;
-
-	// 0. Setup pointer for processing beacon & probe response
-	pMsg   = pElem->Msg;
-	MsgLen = pElem->MsgLen;
-	pFrame = (PFRAME_802_11) pMsg;
-	pSrc   = pFrame->Octet;				// Start from AP TSF
-	pBss   = (PBSS_ENTRY) &pAd->StaCfg.CCXBssTab.BssEntry[Index];
-	ReqIdx = pAd->StaCfg.CurrentRMReqIdx;
-
-	// 1 Check the Index, if we already create this entry, only update the average RSSI
-	if ((Index <= pAd->StaCfg.LastBssIndex) && (pAd->StaCfg.LastBssIndex != 0xff))
-	{
-		pDest  = (PUCHAR) &pAd->StaCfg.FrameReportBuf[pAd->StaCfg.BssReportOffset[Index]];
-		// Point to bss report information
-		pDest += sizeof(MEASUREMENT_REPORT_ELEMENT);
-		pBeaconReport = (PBEACON_REPORT) pDest;
-
-		// Update Rx power, in dBm
-		// Get the original RSSI readback from BBP
-		pBeaconReport->RxPower += pAd->BbpRssiToDbmDelta;
-		// Average the Rssi reading
-		pBeaconReport->RxPower  = (pBeaconReport->RxPower + pBss->Rssi) / 2;
-		// Get to dBm format
-		pBeaconReport->RxPower -= pAd->BbpRssiToDbmDelta;
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Bssid %02x:%02x:%02x:%02x:%02x:%02x ",
-			pBss->Bssid[0], pBss->Bssid[1], pBss->Bssid[2],
-			pBss->Bssid[3], pBss->Bssid[4], pBss->Bssid[5]));
-		DBGPRINT(RT_DEBUG_TRACE, ("RxPower[%ld] Rssi %d, Avg Rssi %d\n", Index, (pBss->Rssi - pAd->BbpRssiToDbmDelta), pBeaconReport->RxPower - 256));
-		DBGPRINT(RT_DEBUG_TRACE, ("FrameReportLen = %d\n", pAd->StaCfg.BssReportOffset[Index]));
-
-		// Update other information here
-
-		// Done
-		return;
-	}
-
-	// 2. Update reported Index
-	pAd->StaCfg.LastBssIndex = Index;
-
-	// 3. Setup the buffer address for copying this BSSID into reporting frame
-	//    The offset should start after 802.11 header and report frame header.
-	pDest = (PUCHAR) &pAd->StaCfg.FrameReportBuf[pAd->StaCfg.FrameReportLen];
-
-	// 4. Save the start offset of each Bss in report frame
-	pAd->StaCfg.BssReportOffset[Index] = pAd->StaCfg.FrameReportLen;
-
-	// 5. Fill Measurement report fields
-	pReport = (PMEASUREMENT_REPORT_ELEMENT) pDest;
-	pReport->Eid = IE_MEASUREMENT_REPORT;
-	pReport->Length = 0;
-	pReport->Token  = pAd->StaCfg.MeasurementRequest[ReqIdx].ReqElem.Token;
-	pReport->Mode   = pAd->StaCfg.MeasurementRequest[ReqIdx].ReqElem.Mode;
-	pReport->Type   = MSRN_TYPE_BEACON_REQ;
-	Length          = sizeof(MEASUREMENT_REPORT_ELEMENT);
-	pDest          += sizeof(MEASUREMENT_REPORT_ELEMENT);
-
-	// 6. Start thebeacon report format
-	pBeaconReport = (PBEACON_REPORT) pDest;
-	pDest        += sizeof(BEACON_REPORT);
-	Length       += sizeof(BEACON_REPORT);
-
-	// 7. Copy Channel number
-	pBeaconReport->Channel        = pBss->Channel;
-	pBeaconReport->Spare          = 0;
-	pBeaconReport->Duration       = pAd->StaCfg.MeasurementRequest[ReqIdx].Measurement.Duration;
-	pBeaconReport->PhyType        = ((pBss->SupRateLen+pBss->ExtRateLen > 4) ? PHY_ERP : PHY_DSS);
-	// 8. Rx power, in dBm
-	pBeaconReport->RxPower        = pBss->Rssi - pAd->BbpRssiToDbmDelta;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Bssid %02x:%02x:%02x:%02x:%02x:%02x ",
-		pBss->Bssid[0], pBss->Bssid[1], pBss->Bssid[2],
-		pBss->Bssid[3], pBss->Bssid[4], pBss->Bssid[5]));
-	DBGPRINT(RT_DEBUG_TRACE, ("RxPower[%ld], Rssi %d\n", Index, pBeaconReport->RxPower - 256));
-	DBGPRINT(RT_DEBUG_TRACE, ("FrameReportLen = %d\n", pAd->StaCfg.FrameReportLen));
-
-	pBeaconReport->BeaconInterval = pBss->BeaconPeriod;
-	COPY_MAC_ADDR(pBeaconReport->BSSID, pFrame->Hdr.Addr3);
-	NdisMoveMemory(pBeaconReport->ParentTSF, pSrc, 4);
-	NdisMoveMemory(pBeaconReport->TargetTSF, &pElem->TimeStamp.u.LowPart, 4);
-	NdisMoveMemory(&pBeaconReport->TargetTSF[4], &pElem->TimeStamp.u.HighPart, 4);
-
-	// 9. Skip the beacon frame and offset to start of capabilityinfo since we already processed capabilityinfo
-	pSrc += (TIMESTAMP_LEN + 2);
-	pBeaconReport->CapabilityInfo = *(USHORT *)pSrc;
-
-	// 10. Point to start of element ID
-	pSrc += 2;
-	pEid = (PEID_STRUCT) pSrc;
-
-	// 11. Start process all variable Eid oayload and add the appropriate to the frame report
-	while (((PUCHAR) pEid + pEid->Len + 1) < ((PUCHAR) pFrame + MsgLen))
-	{
-		// Only limited EID are required to report for CCX 2. It includes SSID, Supported rate,
-		// FH paramenter set, DS parameter set, CF parameter set, IBSS parameter set,
-		// TIM (report first 4 bytes only, radio measurement capability
-		switch (pEid->Eid)
-		{
-			case IE_SSID:
-			case IE_SUPP_RATES:
-			case IE_FH_PARM:
-			case IE_DS_PARM:
-			case IE_CF_PARM:
-			case IE_IBSS_PARM:
-				NdisMoveMemory(pDest, pEid, pEid->Len + 2);
-				pDest  += (pEid->Len + 2);
-				Length += (pEid->Len + 2);
-				break;
-
-			case IE_MEASUREMENT_CAPABILITY:
-				// Since this IE is duplicated with WPA security IE, we has to do sanity check before
-				// recognize it.
-				// 1. It also has fixed 6 bytes IE length.
-				if (pEid->Len != 6)
-					break;
-				// 2. Check the Cisco Aironet OUI
-				if (NdisEqualMemory(CISCO_OUI, (pSrc + 2), 3))
-				{
-					// Matched, this is what we want
-					NdisMoveMemory(pDest, pEid, pEid->Len + 2);
-					pDest  += (pEid->Len + 2);
-					Length += (pEid->Len + 2);
-				}
-				break;
-
-			case IE_TIM:
-				if (pEid->Len > 4)
-				{
-					// May truncate and report the first 4 bytes only, with the eid & len, total should be 6
-					NdisMoveMemory(pDest, pEid, 6);
-					pDest  += 6;
-					Length += 6;
-				}
-				else
-				{
-					NdisMoveMemory(pDest, pEid, pEid->Len + 2);
-					pDest  += (pEid->Len + 2);
-					Length += (pEid->Len + 2);
-				}
-				break;
-
-			default:
-				break;
-		}
-		// 12. Move to next element ID
-		pSrc += (2 + pEid->Len);
-		pEid = (PEID_STRUCT) pSrc;
-	}
-
-	// 13. Update the length in the header, not include EID and length
-	pReport->Length = Length - 4;
-
-	// 14. Update the frame report buffer data length
-	pAd->StaCfg.FrameReportLen += Length;
-	DBGPRINT(RT_DEBUG_TRACE, ("FR len = %d\n", pAd->StaCfg.FrameReportLen));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-		Index		Current BSSID in CCXBsstab entry index
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	AironetCreateBeaconReportFromBssTable(
-	IN	PRTMP_ADAPTER		pAd)
-{
-	PMEASUREMENT_REPORT_ELEMENT	pReport;
-	PBEACON_REPORT				pBeaconReport;
-	UCHAR						Index, ReqIdx;
-	USHORT						Length;
-	PUCHAR						pDest;
-	PBSS_ENTRY					pBss;
-
-	// 0. setup base pointer
-	ReqIdx = pAd->StaCfg.CurrentRMReqIdx;
-
-	for (Index = 0; Index < pAd->StaCfg.CCXBssTab.BssNr; Index++)
-	{
-		// 1. Setup the buffer address for copying this BSSID into reporting frame
-		//    The offset should start after 802.11 header and report frame header.
-		pDest  = (PUCHAR) &pAd->StaCfg.FrameReportBuf[pAd->StaCfg.FrameReportLen];
-		pBss   = (PBSS_ENTRY) &pAd->StaCfg.CCXBssTab.BssEntry[Index];
-		Length = 0;
-
-		// 2. Fill Measurement report fields
-		pReport         = (PMEASUREMENT_REPORT_ELEMENT) pDest;
-		pReport->Eid    = IE_MEASUREMENT_REPORT;
-		pReport->Length = 0;
-		pReport->Token  = pAd->StaCfg.MeasurementRequest[ReqIdx].ReqElem.Token;
-		pReport->Mode   = pAd->StaCfg.MeasurementRequest[ReqIdx].ReqElem.Mode;
-		pReport->Type   = MSRN_TYPE_BEACON_REQ;
-		Length          = sizeof(MEASUREMENT_REPORT_ELEMENT);
-		pDest          += sizeof(MEASUREMENT_REPORT_ELEMENT);
-
-		// 3. Start the beacon report format
-		pBeaconReport = (PBEACON_REPORT) pDest;
-		pDest        += sizeof(BEACON_REPORT);
-		Length       += sizeof(BEACON_REPORT);
-
-		// 4. Copy Channel number
-		pBeaconReport->Channel        = pBss->Channel;
-		pBeaconReport->Spare          = 0;
-		pBeaconReport->Duration       = pAd->StaCfg.MeasurementRequest[ReqIdx].Measurement.Duration;
-		pBeaconReport->PhyType        = ((pBss->SupRateLen+pBss->ExtRateLen > 4) ? PHY_ERP : PHY_DSS);
-		pBeaconReport->RxPower        = pBss->Rssi - pAd->BbpRssiToDbmDelta;
-		pBeaconReport->BeaconInterval = pBss->BeaconPeriod;
-		pBeaconReport->CapabilityInfo = pBss->CapabilityInfo;
-		COPY_MAC_ADDR(pBeaconReport->BSSID, pBss->Bssid);
-		NdisMoveMemory(pBeaconReport->ParentTSF, pBss->PTSF, 4);
-		NdisMoveMemory(pBeaconReport->TargetTSF, pBss->TTSF, 8);
-
-		// 5. Create SSID
-		*pDest++ = 0x00;
-		*pDest++ = pBss->SsidLen;
-		NdisMoveMemory(pDest, pBss->Ssid, pBss->SsidLen);
-		pDest  += pBss->SsidLen;
-		Length += (2 + pBss->SsidLen);
-
-		// 6. Create SupportRates
-		*pDest++ = 0x01;
-		*pDest++ = pBss->SupRateLen;
-		NdisMoveMemory(pDest, pBss->SupRate, pBss->SupRateLen);
-		pDest  += pBss->SupRateLen;
-		Length += (2 + pBss->SupRateLen);
-
-		// 7. DS Parameter
-		*pDest++ = 0x03;
-		*pDest++ = 1;
-		*pDest++ = pBss->Channel;
-		Length  += 3;
-
-		// 8. IBSS parameter if presents
-		if (pBss->BssType == BSS_ADHOC)
-		{
-			*pDest++ = 0x06;
-			*pDest++ = 2;
-			*(PUSHORT) pDest = pBss->AtimWin;
-			pDest   += 2;
-			Length  += 4;
-		}
-
-		// 9. Update length field, not include EID and length
-		pReport->Length = Length - 4;
-
-		// 10. Update total frame size
-		pAd->StaCfg.FrameReportLen += Length;
-	}
-}
+#include "../../rt2860/sta/aironet.c"
diff --git a/drivers/staging/rt2870/sta/assoc.c b/drivers/staging/rt2870/sta/assoc.c
index a76dab5..46564d7 100644
--- a/drivers/staging/rt2870/sta/assoc.c
+++ b/drivers/staging/rt2870/sta/assoc.c
@@ -1,2039 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	assoc.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John		2004-9-3		porting from RT2500
-*/
-#include "../rt_config.h"
-
-UCHAR	CipherWpaTemplate[] = {
-		0xdd, 					// WPA IE
-		0x16,					// Length
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x02,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x02,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x01	// authentication
-		};
-
-UCHAR	CipherWpa2Template[] = {
-		0x30,					// RSN IE
-		0x14,					// Length
-		0x01, 0x00,				// Version
-		0x00, 0x0f, 0xac, 0x02,	// group cipher, TKIP
-		0x01, 0x00,				// number of pairwise
-		0x00, 0x0f, 0xac, 0x02,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x0f, 0xac, 0x02,	// authentication
-		0x00, 0x00,				// RSN capability
-		};
-
-UCHAR	Ccx2IeInfo[] = { 0x00, 0x40, 0x96, 0x03, 0x02};
-
-/*
-	==========================================================================
-	Description:
-		association state machine init, including state transition and timer init
-	Parameters:
-		S - pointer to the association state machine
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
- */
-VOID AssocStateMachineInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  STATE_MACHINE *S,
-	OUT STATE_MACHINE_FUNC Trans[])
-{
-	StateMachineInit(S, Trans, MAX_ASSOC_STATE, MAX_ASSOC_MSG, (STATE_MACHINE_FUNC)Drop, ASSOC_IDLE, ASSOC_MACHINE_BASE);
-
-	// first column
-	StateMachineSetAction(S, ASSOC_IDLE, MT2_MLME_ASSOC_REQ, (STATE_MACHINE_FUNC)MlmeAssocReqAction);
-	StateMachineSetAction(S, ASSOC_IDLE, MT2_MLME_REASSOC_REQ, (STATE_MACHINE_FUNC)MlmeReassocReqAction);
-	StateMachineSetAction(S, ASSOC_IDLE, MT2_MLME_DISASSOC_REQ, (STATE_MACHINE_FUNC)MlmeDisassocReqAction);
-	StateMachineSetAction(S, ASSOC_IDLE, MT2_PEER_DISASSOC_REQ, (STATE_MACHINE_FUNC)PeerDisassocAction);
-
-	// second column
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_MLME_ASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenAssoc);
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_MLME_REASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenReassoc);
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_MLME_DISASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenDisassociate);
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_PEER_DISASSOC_REQ, (STATE_MACHINE_FUNC)PeerDisassocAction);
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_PEER_ASSOC_RSP, (STATE_MACHINE_FUNC)PeerAssocRspAction);
-	//
-	// Patch 3Com AP MOde:3CRWE454G72
-	// We send Assoc request frame to this AP, it always send Reassoc Rsp not Associate Rsp.
-	//
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_PEER_REASSOC_RSP, (STATE_MACHINE_FUNC)PeerAssocRspAction);
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_ASSOC_TIMEOUT, (STATE_MACHINE_FUNC)AssocTimeoutAction);
-
-	// third column
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_MLME_ASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenAssoc);
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_MLME_REASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenReassoc);
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_MLME_DISASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenDisassociate);
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_PEER_DISASSOC_REQ, (STATE_MACHINE_FUNC)PeerDisassocAction);
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_PEER_REASSOC_RSP, (STATE_MACHINE_FUNC)PeerReassocRspAction);
-	//
-	// Patch, AP doesn't send Reassociate Rsp frame to Station.
-	//
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_PEER_ASSOC_RSP, (STATE_MACHINE_FUNC)PeerReassocRspAction);
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_REASSOC_TIMEOUT, (STATE_MACHINE_FUNC)ReassocTimeoutAction);
-
-	// fourth column
-	StateMachineSetAction(S, DISASSOC_WAIT_RSP, MT2_MLME_ASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenAssoc);
-	StateMachineSetAction(S, DISASSOC_WAIT_RSP, MT2_MLME_REASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenReassoc);
-	StateMachineSetAction(S, DISASSOC_WAIT_RSP, MT2_MLME_DISASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenDisassociate);
-	StateMachineSetAction(S, DISASSOC_WAIT_RSP, MT2_PEER_DISASSOC_REQ, (STATE_MACHINE_FUNC)PeerDisassocAction);
-	StateMachineSetAction(S, DISASSOC_WAIT_RSP, MT2_DISASSOC_TIMEOUT, (STATE_MACHINE_FUNC)DisassocTimeoutAction);
-
-	// initialize the timer
-	RTMPInitTimer(pAd, &pAd->MlmeAux.AssocTimer, GET_TIMER_FUNCTION(AssocTimeout), pAd, FALSE);
-	RTMPInitTimer(pAd, &pAd->MlmeAux.ReassocTimer, GET_TIMER_FUNCTION(ReassocTimeout), pAd, FALSE);
-	RTMPInitTimer(pAd, &pAd->MlmeAux.DisassocTimer, GET_TIMER_FUNCTION(DisassocTimeout), pAd, FALSE);
-}
-
-/*
-	==========================================================================
-	Description:
-		Association timeout procedure. After association timeout, this function
-		will be called and it will put a message into the MLME queue
-	Parameters:
-		Standard timer parameters
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AssocTimeout(IN PVOID SystemSpecific1,
-				 IN PVOID FunctionContext,
-				 IN PVOID SystemSpecific2,
-				 IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return;
-
-	MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_ASSOC_TIMEOUT, 0, NULL);
-	RT28XX_MLME_HANDLER(pAd);
-}
-
-/*
-	==========================================================================
-	Description:
-		Reassociation timeout procedure. After reassociation timeout, this
-		function will be called and put a message into the MLME queue
-	Parameters:
-		Standard timer parameters
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID ReassocTimeout(IN PVOID SystemSpecific1,
-					IN PVOID FunctionContext,
-					IN PVOID SystemSpecific2,
-					IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return;
-
-	MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_REASSOC_TIMEOUT, 0, NULL);
-	RT28XX_MLME_HANDLER(pAd);
-}
-
-/*
-	==========================================================================
-	Description:
-		Disassociation timeout procedure. After disassociation timeout, this
-		function will be called and put a message into the MLME queue
-	Parameters:
-		Standard timer parameters
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID DisassocTimeout(IN PVOID SystemSpecific1,
-					IN PVOID FunctionContext,
-					IN PVOID SystemSpecific2,
-					IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return;
-
-	MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_DISASSOC_TIMEOUT, 0, NULL);
-	RT28XX_MLME_HANDLER(pAd);
-}
-
-/*
-	==========================================================================
-	Description:
-		mlme assoc req handling procedure
-	Parameters:
-		Adapter - Adapter pointer
-		Elem - MLME Queue Element
-	Pre:
-		the station has been authenticated and the following information is stored in the config
-			-# SSID
-			-# supported rates and their length
-			-# listen interval (Adapter->StaCfg.default_listen_count)
-			-# Transmit power  (Adapter->StaCfg.tx_power)
-	Post  :
-		-# An association request frame is generated and sent to the air
-		-# Association timer starts
-		-# Association state -> ASSOC_WAIT_RSP
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID MlmeAssocReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR			ApAddr[6];
-	HEADER_802_11	AssocHdr;
-	UCHAR			Ccx2Len = 5;
-	UCHAR			WmeIe[9] = {IE_VENDOR_SPECIFIC, 0x07, 0x00, 0x50, 0xf2, 0x02, 0x00, 0x01, 0x00};
-	USHORT			ListenIntv;
-	ULONG			Timeout;
-	USHORT			CapabilityInfo;
-	BOOLEAN			TimerCancelled;
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen = 0;
-	ULONG			tmp;
-	USHORT			VarIesOffset;
-	UCHAR			CkipFlag;
-	UCHAR			CkipNegotiationBuffer[CKIP_NEGOTIATION_LENGTH];
-	UCHAR			AironetCkipIe = IE_AIRONET_CKIP;
-	UCHAR			AironetCkipLen = CKIP_NEGOTIATION_LENGTH;
-	UCHAR			AironetIPAddressIE = IE_AIRONET_IPADDRESS;
-	UCHAR			AironetIPAddressLen = AIRONET_IPADDRESS_LENGTH;
-	UCHAR			AironetIPAddressBuffer[AIRONET_IPADDRESS_LENGTH] = {0x00, 0x40, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00};
-	USHORT			Status;
-
-	// Block all authentication request durning WPA block period
-	if (pAd->StaCfg.bBlockAssoc == TRUE)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Block Assoc request durning WPA block period!\n"));
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-		Status = MLME_STATE_MACHINE_REJECT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-	}
-	// check sanity first
-	else if (MlmeAssocReqSanity(pAd, Elem->Msg, Elem->MsgLen, ApAddr, &CapabilityInfo, &Timeout, &ListenIntv))
-	{
-		RTMPCancelTimer(&pAd->MlmeAux.AssocTimer, &TimerCancelled);
-		COPY_MAC_ADDR(pAd->MlmeAux.Bssid, ApAddr);
-
-		// Get an unused nonpaged memory
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-		if (NStatus != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("ASSOC - MlmeAssocReqAction() allocate memory failed \n"));
-			pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-			Status = MLME_FAIL_NO_RESOURCE;
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-			return;
-		}
-
-		// Add by James 03/06/27
-		pAd->StaCfg.AssocInfo.Length = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION);
-		// Association don't need to report MAC address
-		pAd->StaCfg.AssocInfo.AvailableRequestFixedIEs =
-			NDIS_802_11_AI_REQFI_CAPABILITIES | NDIS_802_11_AI_REQFI_LISTENINTERVAL;
-		pAd->StaCfg.AssocInfo.RequestFixedIEs.Capabilities = CapabilityInfo;
-		pAd->StaCfg.AssocInfo.RequestFixedIEs.ListenInterval = ListenIntv;
-		// Only reassociate need this
-		//COPY_MAC_ADDR(pAd->StaCfg.AssocInfo.RequestFixedIEs.CurrentAPAddress, ApAddr);
-		pAd->StaCfg.AssocInfo.OffsetRequestIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION);
-
-        NdisZeroMemory(pAd->StaCfg.ReqVarIEs, MAX_VIE_LEN);
-		// First add SSID
-		VarIesOffset = 0;
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &SsidIe, 1);
-		VarIesOffset += 1;
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &pAd->MlmeAux.SsidLen, 1);
-		VarIesOffset += 1;
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-		VarIesOffset += pAd->MlmeAux.SsidLen;
-
-		// Second add Supported rates
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &SupRateIe, 1);
-		VarIesOffset += 1;
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &pAd->MlmeAux.SupRateLen, 1);
-		VarIesOffset += 1;
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, pAd->MlmeAux.SupRate, pAd->MlmeAux.SupRateLen);
-		VarIesOffset += pAd->MlmeAux.SupRateLen;
-		// End Add by James
-
-        if ((pAd->CommonCfg.Channel > 14) &&
-            (pAd->CommonCfg.bIEEE80211H == TRUE))
-            CapabilityInfo |= 0x0100;
-
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Send ASSOC request...\n"));
-		MgtMacHeaderInit(pAd, &AssocHdr, SUBTYPE_ASSOC_REQ, 0, ApAddr, ApAddr);
-
-		// Build basic frame first
-		MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-						  sizeof(HEADER_802_11),	&AssocHdr,
-						  2,						&CapabilityInfo,
-						  2,						&ListenIntv,
-						  1,						&SsidIe,
-						  1,						&pAd->MlmeAux.SsidLen,
-						  pAd->MlmeAux.SsidLen, 	pAd->MlmeAux.Ssid,
-						  1,						&SupRateIe,
-						  1,						&pAd->MlmeAux.SupRateLen,
-						  pAd->MlmeAux.SupRateLen,  pAd->MlmeAux.SupRate,
-						  END_OF_ARGS);
-
-		if (pAd->MlmeAux.ExtRateLen != 0)
-		{
-			MakeOutgoingFrame(pOutBuffer + FrameLen,    &tmp,
-							  1,                        &ExtRateIe,
-							  1,                        &pAd->MlmeAux.ExtRateLen,
-							  pAd->MlmeAux.ExtRateLen,  pAd->MlmeAux.ExtRate,
-							  END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-#ifdef DOT11_N_SUPPORT
-		// HT
-		if ((pAd->MlmeAux.HtCapabilityLen > 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-		{
-			ULONG TmpLen;
-			UCHAR HtLen;
-			UCHAR BROADCOM[4] = {0x0, 0x90, 0x4c, 0x33};
-			if (pAd->StaActive.SupportedPhyInfo.bPreNHt == TRUE)
-			{
-				HtLen = SIZE_HT_CAP_IE + 4;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-							  1,                                &WpaIe,
-							  1,                                &HtLen,
-							  4,                                &BROADCOM[0],
-							 pAd->MlmeAux.HtCapabilityLen,          &pAd->MlmeAux.HtCapability,
-							  END_OF_ARGS);
-			}
-			else
-			{
-#ifdef RT_BIG_ENDIAN
-		        HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
-
-#ifndef RT_BIG_ENDIAN
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-							  1,                                &HtCapIe,
-							  1,                                &pAd->MlmeAux.HtCapabilityLen,
-							 pAd->MlmeAux.HtCapabilityLen,          &pAd->MlmeAux.HtCapability,
-							  END_OF_ARGS);
-#else
-                NdisZeroMemory(&HtCapabilityTmp, sizeof(HT_CAPABILITY_IE));
-                NdisMoveMemory(&HtCapabilityTmp, &pAd->MlmeAux.HtCapability, pAd->MlmeAux.HtCapabilityLen);
-        		*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-        		*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-        		MakeOutgoingFrame(pOutBuffer + FrameLen,         &TmpLen,
-        							1,                           &HtCapIe,
-        							1,                           &pAd->MlmeAux.HtCapabilityLen,
-        							pAd->MlmeAux.HtCapabilityLen,&HtCapabilityTmp,
-        							END_OF_ARGS);
-#endif
-			}
-			FrameLen += TmpLen;
-		}
-#endif // DOT11_N_SUPPORT //
-
-		// add Ralink proprietary IE to inform AP this STA is going to use AGGREGATION or PIGGY-BACK+AGGREGATION
-		// Case I: (Aggregation + Piggy-Back)
-		// 1. user enable aggregation, AND
-		// 2. Mac support piggy-back
-		// 3. AP annouces it's PIGGY-BACK+AGGREGATION-capable in BEACON
-		// Case II: (Aggregation)
-		// 1. user enable aggregation, AND
-		// 2. AP annouces it's AGGREGATION-capable in BEACON
-		if (pAd->CommonCfg.bAggregationCapable)
-		{
-			if ((pAd->CommonCfg.bPiggyBackCapable) && ((pAd->MlmeAux.APRalinkIe & 0x00000003) == 3))
-			{
-				ULONG TmpLen;
-				UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x03, 0x00, 0x00, 0x00};
-				MakeOutgoingFrame(pOutBuffer+FrameLen,           &TmpLen,
-								  9,                             RalinkIe,
-								  END_OF_ARGS);
-				FrameLen += TmpLen;
-			}
-			else if (pAd->MlmeAux.APRalinkIe & 0x00000001)
-			{
-				ULONG TmpLen;
-				UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x01, 0x00, 0x00, 0x00};
-				MakeOutgoingFrame(pOutBuffer+FrameLen,           &TmpLen,
-								  9,                             RalinkIe,
-								  END_OF_ARGS);
-				FrameLen += TmpLen;
-			}
-		}
-		else
-		{
-			ULONG TmpLen;
-			UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x06, 0x00, 0x00, 0x00};
-			MakeOutgoingFrame(pOutBuffer+FrameLen,		 &TmpLen,
-							  9,						 RalinkIe,
-							  END_OF_ARGS);
-			FrameLen += TmpLen;
-		}
-
-		if (pAd->MlmeAux.APEdcaParm.bValid)
-		{
-			if (pAd->CommonCfg.bAPSDCapable && pAd->MlmeAux.APEdcaParm.bAPSDCapable)
-			{
-				QBSS_STA_INFO_PARM QosInfo;
-
-				NdisZeroMemory(&QosInfo, sizeof(QBSS_STA_INFO_PARM));
-				QosInfo.UAPSD_AC_BE = pAd->CommonCfg.bAPSDAC_BE;
-				QosInfo.UAPSD_AC_BK = pAd->CommonCfg.bAPSDAC_BK;
-				QosInfo.UAPSD_AC_VI = pAd->CommonCfg.bAPSDAC_VI;
-				QosInfo.UAPSD_AC_VO = pAd->CommonCfg.bAPSDAC_VO;
-				QosInfo.MaxSPLength = pAd->CommonCfg.MaxSPLength;
-				WmeIe[8] |= *(PUCHAR)&QosInfo;
-			}
-			else
-			{
-                // The Parameter Set Count is set to ¡§0¡¨ in the association request frames
-                // WmeIe[8] |= (pAd->MlmeAux.APEdcaParm.EdcaUpdateCount & 0x0f);
-			}
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen,    &tmp,
-							  9,                        &WmeIe[0],
-							  END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-		//
-		// Let WPA(#221) Element ID on the end of this association frame.
-		// Otherwise some AP will fail on parsing Element ID and set status fail on Assoc Rsp.
-		// For example: Put Vendor Specific IE on the front of WPA IE.
-		// This happens on AP (Model No:Linksys WRK54G)
-		//
-		if (((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-            (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-            (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-            (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2)
-			)
-            )
-		{
-			UCHAR RSNIe = IE_WPA;
-
-			if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-                (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2))
-			{
-				RSNIe = IE_WPA2;
-			}
-
-            	RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, BSS0);
-
-            // Check for WPA PMK cache list
-			if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2)
-			{
-			    INT     idx;
-                BOOLEAN FoundPMK = FALSE;
-				// Search chched PMKID, append it if existed
-				for (idx = 0; idx < PMKID_NO; idx++)
-				{
-					if (NdisEqualMemory(ApAddr, &pAd->StaCfg.SavedPMK[idx].BSSID, 6))
-					{
-						FoundPMK = TRUE;
-						break;
-					}
-				}
-
-				if (FoundPMK)
-				{
-					// Set PMK number
-					*(PUSHORT) &pAd->StaCfg.RSN_IE[pAd->StaCfg.RSNIE_Len] = 1;
-					NdisMoveMemory(&pAd->StaCfg.RSN_IE[pAd->StaCfg.RSNIE_Len + 2], &pAd->StaCfg.SavedPMK[idx].PMKID, 16);
-                    pAd->StaCfg.RSNIE_Len += 18;
-				}
-			}
-
-			{
-				MakeOutgoingFrame(pOutBuffer + FrameLen,    		&tmp,
-				              		1,                              &RSNIe,
-		                        	1,                              &pAd->StaCfg.RSNIE_Len,
-		                        	pAd->StaCfg.RSNIE_Len,			pAd->StaCfg.RSN_IE,
-		                        	END_OF_ARGS);
-			}
-
-			FrameLen += tmp;
-
-			{
-	            // Append Variable IE
-	            NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &RSNIe, 1);
-	            VarIesOffset += 1;
-	            NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &pAd->StaCfg.RSNIE_Len, 1);
-	            VarIesOffset += 1;
-			}
-			NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, pAd->StaCfg.RSN_IE, pAd->StaCfg.RSNIE_Len);
-			VarIesOffset += pAd->StaCfg.RSNIE_Len;
-
-			// Set Variable IEs Length
-			pAd->StaCfg.ReqVarIELen = VarIesOffset;
-		}
-
-		// We have update that at PeerBeaconAtJoinRequest()
-		CkipFlag = pAd->StaCfg.CkipFlag;
-		if (CkipFlag != 0)
-		{
-			NdisZeroMemory(CkipNegotiationBuffer, CKIP_NEGOTIATION_LENGTH);
-			CkipNegotiationBuffer[2] = 0x66;
-			// Make it try KP & MIC, since we have to follow the result from AssocRsp
-			CkipNegotiationBuffer[8] = 0x18;
-			CkipNegotiationBuffer[CKIP_NEGOTIATION_LENGTH - 1] = 0x22;
-			CkipFlag = 0x18;
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen, 	&tmp,
-						1,						  		&AironetCkipIe,
-						1,						  		&AironetCkipLen,
-						AironetCkipLen, 		  		CkipNegotiationBuffer,
-						END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-		// Add CCX v2 request if CCX2 admin state is on
-		if (pAd->StaCfg.CCXControl.field.Enable == 1)
-		{
-
-			//
-			// Add AironetIPAddressIE for Cisco CCX 2.X
-			// Add CCX Version
-			//
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-						1,							&AironetIPAddressIE,
-						1,							&AironetIPAddressLen,
-						AironetIPAddressLen,		AironetIPAddressBuffer,
-						1,							&Ccx2Ie,
-						1,							&Ccx2Len,
-						Ccx2Len,				    Ccx2IeInfo,
-						END_OF_ARGS);
-			FrameLen += tmp;
-
-			//
-			// Add CipherSuite CCKM or LeapTkip if setting.
-			//
-#ifdef LEAP_SUPPORT
-			if (LEAP_CCKM_ON(pAd))
-			{
-				MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-						CipherSuiteCiscoCCKMLen,		CipherSuiteCiscoCCKM,
-						END_OF_ARGS);
-				FrameLen += tmp;
-
-				// Third add RSN
-				NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, CipherSuiteCiscoCCKM, CipherSuiteCiscoCCKMLen); //Save CipherSuite
-				VarIesOffset += CipherSuiteCiscoCCKMLen;
-			}
-			else if ((pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP) && (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled))
-			{
-				MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-						CipherSuiteCCXTkipLen,	    CipherSuiteCCXTkip,
-						END_OF_ARGS);
-				FrameLen += tmp;
-
-				// Third add RSN
-				NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, CipherSuiteCCXTkip, CipherSuiteCCXTkipLen);
-				VarIesOffset += CipherSuiteCCXTkipLen;
-			}
-#endif // LEAP_SUPPORT //
-
-			// Add by James 03/06/27
-			// Set Variable IEs Length
-			pAd->StaCfg.ReqVarIELen = VarIesOffset;
-			pAd->StaCfg.AssocInfo.RequestIELength = VarIesOffset;
-
-			// OffsetResponseIEs follow ReqVarIE
-			pAd->StaCfg.AssocInfo.OffsetResponseIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION) + pAd->StaCfg.ReqVarIELen;
-			// End Add by James
-		}
-
-
-		MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer);
-
-		RTMPSetTimer(&pAd->MlmeAux.AssocTimer, Timeout);
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_WAIT_RSP;
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("ASSOC - MlmeAssocReqAction() sanity check failed. BUG!!!!!! \n"));
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-		Status = MLME_INVALID_FORMAT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-	}
-
-}
-
-/*
-	==========================================================================
-	Description:
-		mlme reassoc req handling procedure
-	Parameters:
-		Elem -
-	Pre:
-		-# SSID  (Adapter->StaCfg.ssid[])
-		-# BSSID (AP address, Adapter->StaCfg.bssid)
-		-# Supported rates (Adapter->StaCfg.supported_rates[])
-		-# Supported rates length (Adapter->StaCfg.supported_rates_len)
-		-# Tx power (Adapter->StaCfg.tx_power)
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID MlmeReassocReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR			ApAddr[6];
-	HEADER_802_11	ReassocHdr;
-	UCHAR			Ccx2Len = 5;
-	UCHAR			WmeIe[9] = {IE_VENDOR_SPECIFIC, 0x07, 0x00, 0x50, 0xf2, 0x02, 0x00, 0x01, 0x00};
-	USHORT			CapabilityInfo, ListenIntv;
-	ULONG			Timeout;
-	ULONG			FrameLen = 0;
-	BOOLEAN			TimerCancelled;
-	NDIS_STATUS		NStatus;
-	ULONG			tmp;
-	PUCHAR			pOutBuffer = NULL;
-//CCX 2.X
-#ifdef LEAP_SUPPORT
-	UCHAR			CkipFlag;
-	UCHAR			CkipNegotiationBuffer[CKIP_NEGOTIATION_LENGTH];
-	UCHAR			AironetCkipIe = IE_AIRONET_CKIP;
-	UCHAR			AironetCkipLen = CKIP_NEGOTIATION_LENGTH;
-	UCHAR			AironetIPAddressIE = IE_AIRONET_IPADDRESS;
-	UCHAR			AironetIPAddressLen = AIRONET_IPADDRESS_LENGTH;
-	UCHAR			AironetIPAddressBuffer[AIRONET_IPADDRESS_LENGTH] = {0x00, 0x40, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00};
-	UCHAR			AironetCCKMReassocIE = IE_AIRONET_CCKMREASSOC;
-	UCHAR			AironetCCKMReassocLen = AIRONET_CCKMREASSOC_LENGTH;
-	UCHAR			AironetCCKMReassocBuffer[AIRONET_CCKMREASSOC_LENGTH];
-	UCHAR			AironetOUI[] = {0x00, 0x40, 0x96, 0x00};
-	UCHAR			MICMN[16];
-	UCHAR			CalcMicBuffer[80];
-	ULONG			CalcMicBufferLen = 0;
-#endif // LEAP_SUPPORT //
-	USHORT			Status;
-
-	// Block all authentication request durning WPA block period
-	if (pAd->StaCfg.bBlockAssoc == TRUE)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Block ReAssoc request durning WPA block period!\n"));
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-		Status = MLME_STATE_MACHINE_REJECT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-	}
-	// the parameters are the same as the association
-	else if(MlmeAssocReqSanity(pAd, Elem->Msg, Elem->MsgLen, ApAddr, &CapabilityInfo, &Timeout, &ListenIntv))
-	{
-		RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer, &TimerCancelled);
-
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-		if(NStatus != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("ASSOC - MlmeReassocReqAction() allocate memory failed \n"));
-			pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-			Status = MLME_FAIL_NO_RESOURCE;
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-			return;
-		}
-
-		COPY_MAC_ADDR(pAd->MlmeAux.Bssid, ApAddr);
-
-		// make frame, use bssid as the AP address??
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Send RE-ASSOC request...\n"));
-		MgtMacHeaderInit(pAd, &ReassocHdr, SUBTYPE_REASSOC_REQ, 0, ApAddr, ApAddr);
-		MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-						  sizeof(HEADER_802_11),    &ReassocHdr,
-						  2,                        &CapabilityInfo,
-						  2,                        &ListenIntv,
-						  MAC_ADDR_LEN,             ApAddr,
-						  1,                        &SsidIe,
-						  1,                        &pAd->MlmeAux.SsidLen,
-						  pAd->MlmeAux.SsidLen,     pAd->MlmeAux.Ssid,
-						  1,                        &SupRateIe,
-						  1,						&pAd->MlmeAux.SupRateLen,
-						  pAd->MlmeAux.SupRateLen,  pAd->MlmeAux.SupRate,
-						  END_OF_ARGS);
-
-		if (pAd->MlmeAux.ExtRateLen != 0)
-		{
-			MakeOutgoingFrame(pOutBuffer + FrameLen,        &tmp,
-							  1,                            &ExtRateIe,
-							  1,                            &pAd->MlmeAux.ExtRateLen,
-							  pAd->MlmeAux.ExtRateLen,	    pAd->MlmeAux.ExtRate,
-							  END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-		if (pAd->MlmeAux.APEdcaParm.bValid)
-		{
-			if (pAd->CommonCfg.bAPSDCapable && pAd->MlmeAux.APEdcaParm.bAPSDCapable)
-			{
-				QBSS_STA_INFO_PARM QosInfo;
-
-				NdisZeroMemory(&QosInfo, sizeof(QBSS_STA_INFO_PARM));
-				QosInfo.UAPSD_AC_BE = pAd->CommonCfg.bAPSDAC_BE;
-				QosInfo.UAPSD_AC_BK = pAd->CommonCfg.bAPSDAC_BK;
-				QosInfo.UAPSD_AC_VI = pAd->CommonCfg.bAPSDAC_VI;
-				QosInfo.UAPSD_AC_VO = pAd->CommonCfg.bAPSDAC_VO;
-				QosInfo.MaxSPLength = pAd->CommonCfg.MaxSPLength;
-				WmeIe[8] |= *(PUCHAR)&QosInfo;
-			}
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen,    &tmp,
-							  9,                        &WmeIe[0],
-							  END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-#ifdef DOT11_N_SUPPORT
-		// HT
-		if ((pAd->MlmeAux.HtCapabilityLen > 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-		{
-			ULONG TmpLen;
-			UCHAR HtLen;
-			UCHAR BROADCOM[4] = {0x0, 0x90, 0x4c, 0x33};
-			if (pAd->StaActive.SupportedPhyInfo.bPreNHt == TRUE)
-			{
-				HtLen = SIZE_HT_CAP_IE + 4;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-							  1,                                &WpaIe,
-							  1,                                &HtLen,
-							  4,                                &BROADCOM[0],
-							 pAd->MlmeAux.HtCapabilityLen,          &pAd->MlmeAux.HtCapability,
-							  END_OF_ARGS);
-			}
-			else
-			{
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-							  1,                                &HtCapIe,
-							  1,                                &pAd->MlmeAux.HtCapabilityLen,
-							 pAd->MlmeAux.HtCapabilityLen,          &pAd->MlmeAux.HtCapability,
-							  END_OF_ARGS);
-			}
-			FrameLen += TmpLen;
-		}
-#endif // DOT11_N_SUPPORT //
-
-		// add Ralink proprietary IE to inform AP this STA is going to use AGGREGATION or PIGGY-BACK+AGGREGATION
-		// Case I: (Aggregation + Piggy-Back)
-		// 1. user enable aggregation, AND
-		// 2. Mac support piggy-back
-		// 3. AP annouces it's PIGGY-BACK+AGGREGATION-capable in BEACON
-		// Case II: (Aggregation)
-		// 1. user enable aggregation, AND
-		// 2. AP annouces it's AGGREGATION-capable in BEACON
-		if (pAd->CommonCfg.bAggregationCapable)
-		{
-			if ((pAd->CommonCfg.bPiggyBackCapable) && ((pAd->MlmeAux.APRalinkIe & 0x00000003) == 3))
-			{
-				ULONG TmpLen;
-				UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x03, 0x00, 0x00, 0x00};
-				MakeOutgoingFrame(pOutBuffer+FrameLen,           &TmpLen,
-								  9,                             RalinkIe,
-								  END_OF_ARGS);
-				FrameLen += TmpLen;
-			}
-			else if (pAd->MlmeAux.APRalinkIe & 0x00000001)
-			{
-				ULONG TmpLen;
-				UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x01, 0x00, 0x00, 0x00};
-				MakeOutgoingFrame(pOutBuffer+FrameLen,           &TmpLen,
-								  9,                             RalinkIe,
-								  END_OF_ARGS);
-				FrameLen += TmpLen;
-			}
-		}
-		else
-		{
-			ULONG TmpLen;
-			UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x04, 0x00, 0x00, 0x00};
-			MakeOutgoingFrame(pOutBuffer+FrameLen,		 &TmpLen,
-							  9,						 RalinkIe,
-							  END_OF_ARGS);
-			FrameLen += TmpLen;
-		}
-#ifdef LEAP_SUPPORT
-		if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-		{
-			CkipFlag = pAd->StaCfg.CkipFlag;	// We have update that at PeerBeaconAtJoinRequest()
-			if (CkipFlag != 0)
-			{
-				NdisZeroMemory(CkipNegotiationBuffer, CKIP_NEGOTIATION_LENGTH);
-				CkipNegotiationBuffer[2] = 0x66;
-				// Make it try KP & MIC, since we have to follow the result from AssocRsp
-				CkipNegotiationBuffer[8] = 0x18;
-				CkipNegotiationBuffer[CKIP_NEGOTIATION_LENGTH - 1] = 0x22;
-
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &tmp,
-									1,                              &AironetCkipIe,
-									1,                              &AironetCkipLen,
-									AironetCkipLen,                 CkipNegotiationBuffer,
-									END_OF_ARGS);
-				FrameLen += tmp;
-			}
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-							1,                              &AironetIPAddressIE,
-							1,                              &AironetIPAddressLen,
-							AironetIPAddressLen,            AironetIPAddressBuffer,
-							END_OF_ARGS);
-			FrameLen += tmp;
-
-			//
-			// The RN is incremented before each reassociation request.
-			//
-			pAd->StaCfg.CCKMRN++;
-			//
-			// Calculate MIC = hmac-md5(krk, STA-ID|BSSID|RSNIE|TSF|RN);
-			//
-			COPY_MAC_ADDR(CalcMicBuffer, pAd->CurrentAddress);
-			CalcMicBufferLen = MAC_ADDR_LEN;
-			COPY_MAC_ADDR(CalcMicBuffer + CalcMicBufferLen, pAd->MlmeAux.Bssid);
-			CalcMicBufferLen += MAC_ADDR_LEN;
-			NdisMoveMemory(CalcMicBuffer + CalcMicBufferLen, CipherSuiteCiscoCCKM, CipherSuiteCiscoCCKMLen);
-			CalcMicBufferLen += CipherSuiteCiscoCCKMLen;
-			NdisMoveMemory(CalcMicBuffer + CalcMicBufferLen, (PUCHAR) &pAd->StaCfg.CCKMBeaconAtJoinTimeStamp, sizeof(pAd->StaCfg.CCKMBeaconAtJoinTimeStamp));
-			CalcMicBufferLen += sizeof(pAd->StaCfg.CCKMBeaconAtJoinTimeStamp);
-			NdisMoveMemory(CalcMicBuffer + CalcMicBufferLen, (PUCHAR)&pAd->StaCfg.CCKMRN, sizeof(pAd->StaCfg.CCKMRN));
-			CalcMicBufferLen += sizeof(pAd->StaCfg.CCKMRN);
-			hmac_md5(pAd->StaCfg.KRK, LEN_EAP_MICK, CalcMicBuffer, CalcMicBufferLen, MICMN);
-
-			//
-			// fill up CCKM reassociation request element
-			//
-			NdisMoveMemory(AironetCCKMReassocBuffer, AironetOUI, 4);
-			NdisMoveMemory(AironetCCKMReassocBuffer + 4, (PUCHAR)&pAd->StaCfg.CCKMBeaconAtJoinTimeStamp, 8);
-			NdisMoveMemory(AironetCCKMReassocBuffer + 12, (PUCHAR) &pAd->StaCfg.CCKMRN, 4);
-			NdisMoveMemory(AironetCCKMReassocBuffer +16, MICMN, 8);
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-							1,                      &AironetCCKMReassocIE,
-							1,                      &AironetCCKMReassocLen,
-							AironetCCKMReassocLen,  AironetCCKMReassocBuffer,
-							END_OF_ARGS);
-			FrameLen += tmp;
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-							CipherSuiteCiscoCCKMLen,CipherSuiteCiscoCCKM,
-							END_OF_ARGS);
-			FrameLen += tmp;
-		}
-#endif // LEAP_SUPPORT //
-
-		// Add CCX v2 request if CCX2 admin state is on
-		if (pAd->StaCfg.CCXControl.field.Enable == 1)
-		{
-			//
-			// Add CCX Version
-			//
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-						1,							&Ccx2Ie,
-						1,							&Ccx2Len,
-						Ccx2Len,				    Ccx2IeInfo,
-						END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-		MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer);
-
-		RTMPSetTimer(&pAd->MlmeAux.ReassocTimer, Timeout); /* in mSec */
-		pAd->Mlme.AssocMachine.CurrState = REASSOC_WAIT_RSP;
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("ASSOC - MlmeReassocReqAction() sanity check failed. BUG!!!! \n"));
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-		Status = MLME_INVALID_FORMAT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		Upper layer issues disassoc request
-	Parameters:
-		Elem -
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
- */
-VOID MlmeDisassocReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PMLME_DISASSOC_REQ_STRUCT pDisassocReq;
-	HEADER_802_11         DisassocHdr;
-	PHEADER_802_11        pDisassocHdr;
-	PUCHAR                pOutBuffer = NULL;
-	ULONG                 FrameLen = 0;
-	NDIS_STATUS           NStatus;
-	BOOLEAN               TimerCancelled;
-	ULONG                 Timeout = 0;
-	USHORT                Status;
-
-#ifdef QOS_DLS_SUPPORT
-	// send DLS-TEAR_DOWN message,
-	if (pAd->CommonCfg.bDLSCapable)
-	{
-		UCHAR i;
-
-		// tear down local dls table entry
-		for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-			{
-				RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			}
-		}
-
-		// tear down peer dls table entry
-		for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-			{
-				RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			}
-		}
-	}
-#endif // QOS_DLS_SUPPORT //
-
-	// skip sanity check
-	pDisassocReq = (PMLME_DISASSOC_REQ_STRUCT)(Elem->Msg);
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - MlmeDisassocReqAction() allocate memory failed\n"));
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-		Status = MLME_FAIL_NO_RESOURCE;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_DISASSOC_CONF, 2, &Status);
-		return;
-	}
-
-
-
-	RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer, &TimerCancelled);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Send DISASSOC request[BSSID::%02x:%02x:%02x:%02x:%02x:%02x (Reason=%d)\n",
-				pDisassocReq->Addr[0], pDisassocReq->Addr[1], pDisassocReq->Addr[2],
-				pDisassocReq->Addr[3], pDisassocReq->Addr[4], pDisassocReq->Addr[5], pDisassocReq->Reason));
-	MgtMacHeaderInit(pAd, &DisassocHdr, SUBTYPE_DISASSOC, 0, pDisassocReq->Addr, pDisassocReq->Addr);	// patch peap ttls switching issue
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-					  sizeof(HEADER_802_11),&DisassocHdr,
-					  2,                    &pDisassocReq->Reason,
-					  END_OF_ARGS);
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-
-	// To patch Instance and Buffalo(N) AP
-	// Driver has to send deauth to Instance AP, but Buffalo(N) needs to send disassoc to reset Authenticator's state machine
-	// Therefore, we send both of them.
-	pDisassocHdr = (PHEADER_802_11)pOutBuffer;
-	pDisassocHdr->FC.SubType = SUBTYPE_DEAUTH;
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	pAd->StaCfg.DisassocReason = REASON_DISASSOC_STA_LEAVING;
-	COPY_MAC_ADDR(pAd->StaCfg.DisassocSta, pDisassocReq->Addr);
-
-	RTMPSetTimer(&pAd->MlmeAux.DisassocTimer, Timeout); /* in mSec */
-	pAd->Mlme.AssocMachine.CurrState = DISASSOC_WAIT_RSP;
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-    if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-	{
-        union iwreq_data    wrqu;
-        //send disassociate event to wpa_supplicant
-        memset(&wrqu, 0, sizeof(wrqu));
-        wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-    }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-    {
-        union iwreq_data    wrqu;
-        memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-        wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-    }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-}
-
-/*
-	==========================================================================
-	Description:
-		peer sends assoc rsp back
-	Parameters:
-		Elme - MLME message containing the received frame
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID PeerAssocRspAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT        CapabilityInfo, Status, Aid;
-	UCHAR         SupRate[MAX_LEN_OF_SUPPORTED_RATES], SupRateLen;
-	UCHAR         ExtRate[MAX_LEN_OF_SUPPORTED_RATES], ExtRateLen;
-	UCHAR         Addr2[MAC_ADDR_LEN];
-	BOOLEAN       TimerCancelled;
-	UCHAR         CkipFlag;
-	EDCA_PARM     EdcaParm;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			HtCapabilityLen;
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChannelOffset = 0xff;
-
-	if (PeerAssocRspSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &CapabilityInfo, &Status, &Aid, SupRate, &SupRateLen, ExtRate, &ExtRateLen,
-		&HtCapability,&AddHtInfo, &HtCapabilityLen,&AddHtInfoLen,&NewExtChannelOffset, &EdcaParm, &CkipFlag))
-	{
-		// The frame is for me ?
-		if(MAC_ADDR_EQUAL(Addr2, pAd->MlmeAux.Bssid))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("PeerAssocRspAction():ASSOC - receive ASSOC_RSP to me (status=%d)\n", Status));
-#ifdef DOT11_N_SUPPORT
-			DBGPRINT(RT_DEBUG_TRACE, ("PeerAssocRspAction():MacTable [%d].AMsduSize = %d. ClientStatusFlags = 0x%lx \n",Elem->Wcid, pAd->MacTab.Content[BSSID_WCID].AMsduSize, pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
-#endif // DOT11_N_SUPPORT //
-			RTMPCancelTimer(&pAd->MlmeAux.AssocTimer, &TimerCancelled);
-			if(Status == MLME_SUCCESS)
-			{
-				UCHAR			MaxSupportedRateIn500Kbps = 0;
-				UCHAR			idx;
-
-				// supported rates array may not be sorted. sort it and find the maximum rate
-			    for (idx=0; idx<SupRateLen; idx++)
-			    {
-			        if (MaxSupportedRateIn500Kbps < (SupRate[idx] & 0x7f))
-			            MaxSupportedRateIn500Kbps = SupRate[idx] & 0x7f;
-			    }
-
-				for (idx=0; idx<ExtRateLen; idx++)
-			    {
-			        if (MaxSupportedRateIn500Kbps < (ExtRate[idx] & 0x7f))
-			            MaxSupportedRateIn500Kbps = ExtRate[idx] & 0x7f;
-			    }
-				// go to procedure listed on page 376
-				AssocPostProc(pAd, Addr2, CapabilityInfo, Aid, SupRate, SupRateLen, ExtRate, ExtRateLen,
-					&EdcaParm, &HtCapability, HtCapabilityLen, &AddHtInfo);
-
-				StaAddMacTableEntry(pAd, &pAd->MacTab.Content[BSSID_WCID], MaxSupportedRateIn500Kbps, &HtCapability, HtCapabilityLen, CapabilityInfo);
-
-				pAd->StaCfg.CkipFlag = CkipFlag;
-				if (CkipFlag & 0x18)
-				{
-					NdisZeroMemory(pAd->StaCfg.TxSEQ, 4);
-					NdisZeroMemory(pAd->StaCfg.RxSEQ, 4);
-					NdisZeroMemory(pAd->StaCfg.CKIPMIC, 4);
-					pAd->StaCfg.GIV[0] = RandomByte(pAd);
-					pAd->StaCfg.GIV[1] = RandomByte(pAd);
-					pAd->StaCfg.GIV[2] = RandomByte(pAd);
-					pAd->StaCfg.bCkipOn = TRUE;
-					DBGPRINT(RT_DEBUG_TRACE, ("<CCX> pAd->StaCfg.CkipFlag = 0x%02x\n", pAd->StaCfg.CkipFlag));
-				}
-			}
-			else
-			{
-				// Faile on Association, we need to check the status code
-				// Is that a Rogue AP?
-#ifdef LEAP_SUPPORT
-				if ((pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP) && (Status == MLME_ALG_NOT_SUPPORT))
-				{ //Possibly Rogue AP
-					RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, pAd->MlmeAux.Bssid, LEAP_REASON_INVALID_AUTH);
-				}
-#endif // LEAP_SUPPORT //
-			}
-			pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-		}
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - PeerAssocRspAction() sanity check fail\n"));
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		peer sends reassoc rsp
-	Parametrs:
-		Elem - MLME message cntaining the received frame
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID PeerReassocRspAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT      CapabilityInfo;
-	USHORT      Status;
-	USHORT      Aid;
-	UCHAR       SupRate[MAX_LEN_OF_SUPPORTED_RATES], SupRateLen;
-	UCHAR       ExtRate[MAX_LEN_OF_SUPPORTED_RATES], ExtRateLen;
-	UCHAR       Addr2[MAC_ADDR_LEN];
-	UCHAR       CkipFlag;
-	BOOLEAN     TimerCancelled;
-	EDCA_PARM   EdcaParm;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			HtCapabilityLen;
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChannelOffset = 0xff;
-
-	if(PeerAssocRspSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &CapabilityInfo, &Status, &Aid, SupRate, &SupRateLen, ExtRate, &ExtRateLen,
-								&HtCapability,	&AddHtInfo, &HtCapabilityLen, &AddHtInfoLen,&NewExtChannelOffset, &EdcaParm, &CkipFlag))
-	{
-		if(MAC_ADDR_EQUAL(Addr2, pAd->MlmeAux.Bssid)) // The frame is for me ?
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - receive REASSOC_RSP to me (status=%d)\n", Status));
-			RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer, &TimerCancelled);
-
-			if(Status == MLME_SUCCESS)
-			{
-				// go to procedure listed on page 376
-				AssocPostProc(pAd, Addr2, CapabilityInfo, Aid, SupRate, SupRateLen, ExtRate, ExtRateLen,
-					 &EdcaParm, &HtCapability, HtCapabilityLen, &AddHtInfo);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-                if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-                {
-                    union iwreq_data    wrqu;
-
-                    SendAssocIEsToWpaSupplicant(pAd);
-                    memset(&wrqu, 0, sizeof(wrqu));
-                    wrqu.data.flags = RT_ASSOC_EVENT_FLAG;
-                    wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-                }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-                {
-                    union iwreq_data    wrqu;
-                    wext_notify_event_assoc(pAd);
-
-                    memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                    memcpy(wrqu.ap_addr.sa_data, pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
-                    wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-
-                }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-			}
-
-			//
-			// Cisco Leap CCKM supported Re-association.
-			//
-#ifdef LEAP_SUPPORT
-			if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-			{
-				if (CCKMAssocRspSanity(pAd, Elem->Msg, Elem->MsgLen) == TRUE)
-				{
-					pAd->StaCfg.CkipFlag = CkipFlag;
-					if (CkipFlag & 0x18)
-					{
-						NdisZeroMemory(pAd->StaCfg.TxSEQ, 4);
-						NdisZeroMemory(pAd->StaCfg.RxSEQ, 4);
-						NdisZeroMemory(pAd->StaCfg.CKIPMIC, 4);
-						pAd->StaCfg.GIV[0] = RandomByte(pAd);
-						pAd->StaCfg.GIV[1] = RandomByte(pAd);
-						pAd->StaCfg.GIV[2] = RandomByte(pAd);
-						pAd->StaCfg.bCkipOn = TRUE;
-						DBGPRINT(RT_DEBUG_TRACE, ("<CCX> pAd->StaCfg.CkipFlag = 0x%02x\n", pAd->StaCfg.CkipFlag));
-					}
-
-					pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-					MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - CCKMAssocRspSanity() sanity check fail\n"));
-				}
-			}
-			else
-#endif // LEAP_SUPPORT //
-			{
-				// CkipFlag is no use for reassociate
-				pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-				MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-			}
-		}
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - PeerReassocRspAction() sanity check fail\n"));
-	}
-
-}
-
-/*
-	==========================================================================
-	Description:
-		procedures on IEEE 802.11/1999 p.376
-	Parametrs:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AssocPostProc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pAddr2,
-	IN USHORT CapabilityInfo,
-	IN USHORT Aid,
-	IN UCHAR SupRate[],
-	IN UCHAR SupRateLen,
-	IN UCHAR ExtRate[],
-	IN UCHAR ExtRateLen,
-	IN PEDCA_PARM pEdcaParm,
-	IN HT_CAPABILITY_IE		*pHtCapability,
-	IN UCHAR HtCapabilityLen,
-	IN ADD_HT_INFO_IE		*pAddHtInfo)	// AP might use this additional ht info IE
-{
-	ULONG Idx;
-
-	pAd->MlmeAux.BssType = BSS_INFRA;
-	COPY_MAC_ADDR(pAd->MlmeAux.Bssid, pAddr2);
-	pAd->MlmeAux.Aid = Aid;
-	pAd->MlmeAux.CapabilityInfo = CapabilityInfo & SUPPORTED_CAPABILITY_INFO;
-#ifdef DOT11_N_SUPPORT
-	// Some HT AP might lost WMM IE. We add WMM ourselves. beacuase HT requires QoS on.
-	if ((HtCapabilityLen > 0) && (pEdcaParm->bValid == FALSE))
-	{
-		pEdcaParm->bValid = TRUE;
-		pEdcaParm->Aifsn[0] = 3;
-		pEdcaParm->Aifsn[1] = 7;
-		pEdcaParm->Aifsn[2] = 2;
-		pEdcaParm->Aifsn[3] = 2;
-
-		pEdcaParm->Cwmin[0] = 4;
-		pEdcaParm->Cwmin[1] = 4;
-		pEdcaParm->Cwmin[2] = 3;
-		pEdcaParm->Cwmin[3] = 2;
-
-		pEdcaParm->Cwmax[0] = 10;
-		pEdcaParm->Cwmax[1] = 10;
-		pEdcaParm->Cwmax[2] = 4;
-		pEdcaParm->Cwmax[3] = 3;
-
-		pEdcaParm->Txop[0]  = 0;
-		pEdcaParm->Txop[1]  = 0;
-		pEdcaParm->Txop[2]  = 96;
-		pEdcaParm->Txop[3]  = 48;
-
-	}
-#endif // DOT11_N_SUPPORT //
-
-	NdisMoveMemory(&pAd->MlmeAux.APEdcaParm, pEdcaParm, sizeof(EDCA_PARM));
-
-	// filter out un-supported rates
-	pAd->MlmeAux.SupRateLen = SupRateLen;
-	NdisMoveMemory(pAd->MlmeAux.SupRate, SupRate, SupRateLen);
-	RTMPCheckRates(pAd, pAd->MlmeAux.SupRate, &pAd->MlmeAux.SupRateLen);
-
-	// filter out un-supported rates
-	pAd->MlmeAux.ExtRateLen = ExtRateLen;
-	NdisMoveMemory(pAd->MlmeAux.ExtRate, ExtRate, ExtRateLen);
-	RTMPCheckRates(pAd, pAd->MlmeAux.ExtRate, &pAd->MlmeAux.ExtRateLen);
-
-#ifdef DOT11_N_SUPPORT
-	if (HtCapabilityLen > 0)
-	{
-		RTMPCheckHt(pAd, BSSID_WCID, pHtCapability, pAddHtInfo);
-	}
-	DBGPRINT(RT_DEBUG_TRACE, ("AssocPostProc===>  AP.AMsduSize = %d. ClientStatusFlags = 0x%lx \n", pAd->MacTab.Content[BSSID_WCID].AMsduSize, pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AssocPostProc===>    (Mmps=%d, AmsduSize=%d, )\n",
-		pAd->MacTab.Content[BSSID_WCID].MmpsMode, pAd->MacTab.Content[BSSID_WCID].AMsduSize));
-#endif // DOT11_N_SUPPORT //
-
-	// Set New WPA information
-	Idx = BssTableSearch(&pAd->ScanTab, pAddr2, pAd->MlmeAux.Channel);
-	if (Idx == BSS_NOT_FOUND)
-	{
-		DBGPRINT_ERR(("ASSOC - Can't find BSS after receiving Assoc response\n"));
-	}
-	else
-	{
-		// Init variable
-		pAd->MacTab.Content[BSSID_WCID].RSNIE_Len = 0;
-		NdisZeroMemory(pAd->MacTab.Content[BSSID_WCID].RSN_IE, MAX_LEN_OF_RSNIE);
-
-		// Store appropriate RSN_IE for WPA SM negotiation later
-		if ((pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA) && (pAd->ScanTab.BssEntry[Idx].VarIELen != 0))
-		{
-			PUCHAR              pVIE;
-			USHORT              len;
-			PEID_STRUCT         pEid;
-
-			pVIE = pAd->ScanTab.BssEntry[Idx].VarIEs;
-			len	 = pAd->ScanTab.BssEntry[Idx].VarIELen;
-
-			while (len > 0)
-			{
-				pEid = (PEID_STRUCT) pVIE;
-				// For WPA/WPAPSK
-				if ((pEid->Eid == IE_WPA) && (NdisEqualMemory(pEid->Octet, WPA_OUI, 4))
-					&& (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA || pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-				{
-					NdisMoveMemory(pAd->MacTab.Content[BSSID_WCID].RSN_IE, pVIE, (pEid->Len + 2));
-					pAd->MacTab.Content[BSSID_WCID].RSNIE_Len = (pEid->Len + 2);
-					DBGPRINT(RT_DEBUG_TRACE, ("AssocPostProc===> Store RSN_IE for WPA SM negotiation \n"));
-				}
-				// For WPA2/WPA2PSK
-				else if ((pEid->Eid == IE_RSN) && (NdisEqualMemory(pEid->Octet + 2, RSN_OUI, 3))
-					&& (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2 || pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-				{
-					NdisMoveMemory(pAd->MacTab.Content[BSSID_WCID].RSN_IE, pVIE, (pEid->Len + 2));
-					pAd->MacTab.Content[BSSID_WCID].RSNIE_Len = (pEid->Len + 2);
-					DBGPRINT(RT_DEBUG_TRACE, ("AssocPostProc===> Store RSN_IE for WPA2 SM negotiation \n"));
-				}
-
-				pVIE += (pEid->Len + 2);
-				len  -= (pEid->Len + 2);
-			}
-		}
-
-		if (pAd->MacTab.Content[BSSID_WCID].RSNIE_Len == 0)
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("AssocPostProc===> no RSN_IE \n"));
-		}
-		else
-		{
-			hex_dump("RSN_IE", pAd->MacTab.Content[BSSID_WCID].RSN_IE, pAd->MacTab.Content[BSSID_WCID].RSNIE_Len);
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		left part of IEEE 802.11/1999 p.374
-	Parameters:
-		Elem - MLME message containing the received frame
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID PeerDisassocAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR         Addr2[MAC_ADDR_LEN];
-	USHORT        Reason;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - PeerDisassocAction()\n"));
-	if(PeerDisassocSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &Reason))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - PeerDisassocAction() Reason = %d\n", Reason));
-		if (INFRA_ON(pAd) && MAC_ADDR_EQUAL(pAd->CommonCfg.Bssid, Addr2))
-		{
-
-			if (pAd->CommonCfg.bWirelessEvent)
-			{
-				RTMPSendWirelessEvent(pAd, IW_DISASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-			}
-
-
-#ifdef LEAP_SUPPORT
-			if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-			{
-				// Cisco_LEAP has start a timer
-				// We should cancel it if using LEAP
-				RTMPCancelTimer(&pAd->StaCfg.LeapAuthTimer, &TimerCancelled);
-				//Check is it mach the LEAP Authentication failed as possible a Rogue AP
-				//on it's PortSecured not equal to WPA_802_1X_PORT_SECURED while process the Association.
-				if ((pAd->Mlme.LeapMachine.CurrState != LEAP_IDLE) && (pAd->StaCfg.PortSecured != WPA_802_1X_PORT_SECURED))
-				{
-					RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, Addr2, LEAP_REASON_AUTH_TIMEOUT);
-				}
-			}
-#endif	// LEAP_SUPPORT //
-			//
-			// Get Current System time and Turn on AdjacentAPReport
-			//
-			NdisGetSystemUpTime(&pAd->StaCfg.CCXAdjacentAPLinkDownTime);
-			pAd->StaCfg.CCXAdjacentAPReportFlag = TRUE;
-			LinkDown(pAd, TRUE);
-			pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-			{
-                union iwreq_data    wrqu;
-                //send disassociate event to wpa_supplicant
-                memset(&wrqu, 0, sizeof(wrqu));
-                wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-                wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-            {
-                union iwreq_data    wrqu;
-                memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-		}
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - PeerDisassocAction() sanity check fail\n"));
-	}
-
-}
-
-/*
-	==========================================================================
-	Description:
-		what the state machine will do after assoc timeout
-	Parameters:
-		Elme -
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AssocTimeoutAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT  Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - AssocTimeoutAction\n"));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_REJ_TIMEOUT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-		what the state machine will do after reassoc timeout
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID ReassocTimeoutAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT  Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - ReassocTimeoutAction\n"));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_REJ_TIMEOUT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-		what the state machine will do after disassoc timeout
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID DisassocTimeoutAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT  Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - DisassocTimeoutAction\n"));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_SUCCESS;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_DISASSOC_CONF, 2, &Status);
-}
-
-VOID InvalidStateWhenAssoc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT  Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - InvalidStateWhenAssoc(state=%ld), reset ASSOC state machine\n",
-		pAd->Mlme.AssocMachine.CurrState));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-}
-
-VOID InvalidStateWhenReassoc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - InvalidStateWhenReassoc(state=%ld), reset ASSOC state machine\n",
-		pAd->Mlme.AssocMachine.CurrState));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-}
-
-VOID InvalidStateWhenDisassociate(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - InvalidStateWhenDisassoc(state=%ld), reset ASSOC state machine\n",
-		pAd->Mlme.AssocMachine.CurrState));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_DISASSOC_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-		right part of IEEE 802.11/1999 page 374
-	Note:
-		This event should never cause ASSOC state machine perform state
-		transition, and has no relationship with CNTL machine. So we separate
-		this routine as a service outside of ASSOC state transition table.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID Cls3errAction(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR        pAddr)
-{
-	HEADER_802_11         DisassocHdr;
-	PHEADER_802_11        pDisassocHdr;
-	PUCHAR                pOutBuffer = NULL;
-	ULONG                 FrameLen = 0;
-	NDIS_STATUS           NStatus;
-	USHORT                Reason = REASON_CLS3ERR;
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Class 3 Error, Send DISASSOC frame\n"));
-	MgtMacHeaderInit(pAd, &DisassocHdr, SUBTYPE_DISASSOC, 0, pAddr, pAd->CommonCfg.Bssid);	// patch peap ttls switching issue
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-					  sizeof(HEADER_802_11),&DisassocHdr,
-					  2,                    &Reason,
-					  END_OF_ARGS);
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-
-	// To patch Instance and Buffalo(N) AP
-	// Driver has to send deauth to Instance AP, but Buffalo(N) needs to send disassoc to reset Authenticator's state machine
-	// Therefore, we send both of them.
-	pDisassocHdr = (PHEADER_802_11)pOutBuffer;
-	pDisassocHdr->FC.SubType = SUBTYPE_DEAUTH;
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	pAd->StaCfg.DisassocReason = REASON_CLS3ERR;
-	COPY_MAC_ADDR(pAd->StaCfg.DisassocSta, pAddr);
-}
-
- /*
-	 ==========================================================================
-	 Description:
-		 Switch between WEP and CKIP upon new association up.
-	 Parameters:
-
-	 IRQL = DISPATCH_LEVEL
-
-	 ==========================================================================
-  */
-VOID SwitchBetweenWepAndCkip(
-	IN PRTMP_ADAPTER pAd)
-{
-	int            i;
-	SHAREDKEY_MODE_STRUC  csr1;
-
-	// if KP is required. change the CipherAlg in hardware shard key table from WEP
-	// to CKIP. else remain as WEP
-	if (pAd->StaCfg.bCkipOn && (pAd->StaCfg.CkipFlag & 0x10))
-	{
-		// modify hardware key table so that MAC use correct algorithm to decrypt RX
-		RTMP_IO_READ32(pAd, SHARED_KEY_MODE_BASE, &csr1.word);
-		if (csr1.field.Bss0Key0CipherAlg == CIPHER_WEP64)
-			csr1.field.Bss0Key0CipherAlg = CIPHER_CKIP64;
-		else if (csr1.field.Bss0Key0CipherAlg == CIPHER_WEP128)
-			csr1.field.Bss0Key0CipherAlg = CIPHER_CKIP128;
-
-		if (csr1.field.Bss0Key1CipherAlg == CIPHER_WEP64)
-			csr1.field.Bss0Key1CipherAlg = CIPHER_CKIP64;
-		else if (csr1.field.Bss0Key1CipherAlg == CIPHER_WEP128)
-			csr1.field.Bss0Key1CipherAlg = CIPHER_CKIP128;
-
-		if (csr1.field.Bss0Key2CipherAlg == CIPHER_WEP64)
-			csr1.field.Bss0Key2CipherAlg = CIPHER_CKIP64;
-		else if (csr1.field.Bss0Key2CipherAlg == CIPHER_WEP128)
-			csr1.field.Bss0Key2CipherAlg = CIPHER_CKIP128;
-
-		if (csr1.field.Bss0Key3CipherAlg == CIPHER_WEP64)
-			csr1.field.Bss0Key3CipherAlg = CIPHER_CKIP64;
-		else if (csr1.field.Bss0Key3CipherAlg == CIPHER_WEP128)
-			csr1.field.Bss0Key3CipherAlg = CIPHER_CKIP128;
-		RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE, csr1.word);
-		DBGPRINT(RT_DEBUG_TRACE, ("SwitchBetweenWepAndCkip: modify BSS0 cipher to %s\n", CipherName[csr1.field.Bss0Key0CipherAlg]));
-
-		// modify software key table so that driver can specify correct algorithm in TXD upon TX
-		for (i=0; i<SHARE_KEY_NUM; i++)
-		{
-			if (pAd->SharedKey[BSS0][i].CipherAlg == CIPHER_WEP64)
-				pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_CKIP64;
-			else if (pAd->SharedKey[BSS0][i].CipherAlg == CIPHER_WEP128)
-				pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_CKIP128;
-		}
-	}
-
-	// else if KP NOT inused. change the CipherAlg in hardware shard key table from CKIP
-	// to WEP.
-	else
-	{
-		// modify hardware key table so that MAC use correct algorithm to decrypt RX
-		RTMP_IO_READ32(pAd, SHARED_KEY_MODE_BASE, &csr1.word);
-		if (csr1.field.Bss0Key0CipherAlg == CIPHER_CKIP64)
-			csr1.field.Bss0Key0CipherAlg = CIPHER_WEP64;
-		else if (csr1.field.Bss0Key0CipherAlg == CIPHER_CKIP128)
-			csr1.field.Bss0Key0CipherAlg = CIPHER_WEP128;
-
-		if (csr1.field.Bss0Key1CipherAlg == CIPHER_CKIP64)
-			csr1.field.Bss0Key1CipherAlg = CIPHER_WEP64;
-		else if (csr1.field.Bss0Key1CipherAlg == CIPHER_CKIP128)
-			csr1.field.Bss0Key1CipherAlg = CIPHER_WEP128;
-
-		if (csr1.field.Bss0Key2CipherAlg == CIPHER_CKIP64)
-			csr1.field.Bss0Key2CipherAlg = CIPHER_WEP64;
-		else if (csr1.field.Bss0Key2CipherAlg == CIPHER_CKIP128)
-			csr1.field.Bss0Key2CipherAlg = CIPHER_WEP128;
-
-		if (csr1.field.Bss0Key3CipherAlg == CIPHER_CKIP64)
-			csr1.field.Bss0Key3CipherAlg = CIPHER_WEP64;
-		else if (csr1.field.Bss0Key3CipherAlg == CIPHER_CKIP128)
-			csr1.field.Bss0Key3CipherAlg = CIPHER_WEP128;
-
-		// modify software key table so that driver can specify correct algorithm in TXD upon TX
-		for (i=0; i<SHARE_KEY_NUM; i++)
-		{
-			if (pAd->SharedKey[BSS0][i].CipherAlg == CIPHER_CKIP64)
-				pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_WEP64;
-			else if (pAd->SharedKey[BSS0][i].CipherAlg == CIPHER_CKIP128)
-				pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_WEP128;
-		}
-
-		//
-		// On WPA-NONE, must update CipherAlg.
-		// Because the OID_802_11_WEP_STATUS was been set after OID_802_11_ADD_KEY
-		// and CipherAlg will be CIPHER_NONE by Windows ZeroConfig.
-		// So we need to update CipherAlg after connect.
-		//
-		if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-		{
-			for (i = 0; i < SHARE_KEY_NUM; i++)
-			{
-				if (pAd->SharedKey[BSS0][i].KeyLen != 0)
-				{
-					if (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled)
-					{
-						pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_TKIP;
-					}
-					else if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-					{
-						pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_AES;
-					}
-				}
-				else
-				{
-					pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_NONE;
-				}
-			}
-
-			csr1.field.Bss0Key0CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-			csr1.field.Bss0Key1CipherAlg = pAd->SharedKey[BSS0][1].CipherAlg;
-			csr1.field.Bss0Key2CipherAlg = pAd->SharedKey[BSS0][2].CipherAlg;
-			csr1.field.Bss0Key3CipherAlg = pAd->SharedKey[BSS0][3].CipherAlg;
-		}
-		RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE, csr1.word);
-		DBGPRINT(RT_DEBUG_TRACE, ("SwitchBetweenWepAndCkip: modify BSS0 cipher to %s\n", CipherName[csr1.field.Bss0Key0CipherAlg]));
-	}
-}
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-VOID    SendAssocIEsToWpaSupplicant(
-    IN  PRTMP_ADAPTER pAd)
-{
-    union iwreq_data    wrqu;
-    unsigned char custom[IW_CUSTOM_MAX] = {0};
-
-    if ((pAd->StaCfg.ReqVarIELen + 17) <= IW_CUSTOM_MAX)
-    {
-        sprintf(custom, "ASSOCINFO_ReqIEs=");
-	    NdisMoveMemory(custom+17, pAd->StaCfg.ReqVarIEs, pAd->StaCfg.ReqVarIELen);
-	    memset(&wrqu, 0, sizeof(wrqu));
-        wrqu.data.length = pAd->StaCfg.ReqVarIELen + 17;
-        wrqu.data.flags = RT_REQIE_EVENT_FLAG;
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, custom);
-
-        memset(&wrqu, 0, sizeof(wrqu));
-        wrqu.data.flags = RT_ASSOCINFO_EVENT_FLAG;
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-    }
-    else
-        DBGPRINT(RT_DEBUG_TRACE, ("pAd->StaCfg.ReqVarIELen + 17 > MAX_CUSTOM_LEN\n"));
-
-    return;
-}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-int wext_notify_event_assoc(
-	IN  RTMP_ADAPTER *pAd)
-{
-    union iwreq_data    wrqu;
-    char custom[IW_CUSTOM_MAX] = {0};
-
-#if WIRELESS_EXT > 17
-    if (pAd->StaCfg.ReqVarIELen <= IW_CUSTOM_MAX)
-    {
-        wrqu.data.length = pAd->StaCfg.ReqVarIELen;
-        memcpy(custom, pAd->StaCfg.ReqVarIEs, pAd->StaCfg.ReqVarIELen);
-        wireless_send_event(pAd->net_dev, IWEVASSOCREQIE, &wrqu, custom);
-    }
-    else
-        DBGPRINT(RT_DEBUG_TRACE, ("pAd->StaCfg.ReqVarIELen > MAX_CUSTOM_LEN\n"));
-#else
-    if (((pAd->StaCfg.ReqVarIELen*2) + 17) <= IW_CUSTOM_MAX)
-    {
-        UCHAR   idx;
-        wrqu.data.length = (pAd->StaCfg.ReqVarIELen*2) + 17;
-        sprintf(custom, "ASSOCINFO(ReqIEs=");
-        for (idx=0; idx<pAd->StaCfg.ReqVarIELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAd->StaCfg.ReqVarIEs[idx]);
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, custom);
-    }
-    else
-        DBGPRINT(RT_DEBUG_TRACE, ("(pAd->StaCfg.ReqVarIELen*2) + 17 > MAX_CUSTOM_LEN\n"));
-#endif
-
-	return 0;
-
-}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-
-BOOLEAN StaAddMacTableEntry(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PMAC_TABLE_ENTRY	pEntry,
-	IN  UCHAR				MaxSupportedRateIn500Kbps,
-	IN  HT_CAPABILITY_IE	*pHtCapability,
-	IN  UCHAR				HtCapabilityLen,
-	IN  USHORT        		CapabilityInfo)
-{
-	UCHAR            MaxSupportedRate = RATE_11;
-
-	if (ADHOC_ON(pAd))
-		CLIENT_STATUS_CLEAR_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-
-	switch (MaxSupportedRateIn500Kbps)
-    {
-        case 108: MaxSupportedRate = RATE_54;   break;
-        case 96:  MaxSupportedRate = RATE_48;   break;
-        case 72:  MaxSupportedRate = RATE_36;   break;
-        case 48:  MaxSupportedRate = RATE_24;   break;
-        case 36:  MaxSupportedRate = RATE_18;   break;
-        case 24:  MaxSupportedRate = RATE_12;   break;
-        case 18:  MaxSupportedRate = RATE_9;    break;
-        case 12:  MaxSupportedRate = RATE_6;    break;
-        case 22:  MaxSupportedRate = RATE_11;   break;
-        case 11:  MaxSupportedRate = RATE_5_5;  break;
-        case 4:   MaxSupportedRate = RATE_2;    break;
-        case 2:   MaxSupportedRate = RATE_1;    break;
-        default:  MaxSupportedRate = RATE_11;   break;
-    }
-
-    if ((pAd->CommonCfg.PhyMode == PHY_11G) && (MaxSupportedRate < RATE_FIRST_OFDM_RATE))
-        return FALSE;
-
-#ifdef DOT11_N_SUPPORT
-	// 11n only
-	if (((pAd->CommonCfg.PhyMode == PHY_11N_2_4G) || (pAd->CommonCfg.PhyMode == PHY_11N_5G))&& (HtCapabilityLen == 0))
-		return FALSE;
-#endif // DOT11_N_SUPPORT //
-
-	if (!pEntry)
-        return FALSE;
-
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-	if (pEntry)
-	{
-		pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
-		if ((MaxSupportedRate < RATE_FIRST_OFDM_RATE) ||
-			(pAd->CommonCfg.PhyMode == PHY_11B))
-		{
-			pEntry->RateLen = 4;
-			if (MaxSupportedRate >= RATE_FIRST_OFDM_RATE)
-				MaxSupportedRate = RATE_11;
-		}
-		else
-			pEntry->RateLen = 12;
-
-		pEntry->MaxHTPhyMode.word = 0;
-		pEntry->MinHTPhyMode.word = 0;
-		pEntry->HTPhyMode.word = 0;
-		pEntry->MaxSupportedRate = MaxSupportedRate;
-		if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
-		{
-			pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
-			pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-			pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
-			pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-			pEntry->HTPhyMode.field.MODE = MODE_CCK;
-			pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-		}
-		else
-		{
-			pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
-			pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-			pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
-			pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-			pEntry->HTPhyMode.field.MODE = MODE_OFDM;
-			pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-		}
-		pEntry->CapabilityInfo = CapabilityInfo;
-		CLIENT_STATUS_CLEAR_FLAG(pEntry, fCLIENT_STATUS_AGGREGATION_CAPABLE);
-		CLIENT_STATUS_CLEAR_FLAG(pEntry, fCLIENT_STATUS_PIGGYBACK_CAPABLE);
-	}
-
-#ifdef DOT11_N_SUPPORT
-	// If this Entry supports 802.11n, upgrade to HT rate.
-	if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-	{
-		UCHAR	j, bitmask; //k,bitmask;
-		CHAR    i;
-
-		if (ADHOC_ON(pAd))
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-		if ((pHtCapability->HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-		{
-			pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
-		}
-		else
-		{
-			pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-			pAd->MacTab.fAnyStationNonGF = TRUE;
-			pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
-		}
-
-		if ((pHtCapability->HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
-		{
-			pEntry->MaxHTPhyMode.field.BW= BW_40;
-			pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(pHtCapability->HtCapInfo.ShortGIfor40));
-		}
-		else
-		{
-			pEntry->MaxHTPhyMode.field.BW = BW_20;
-			pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(pHtCapability->HtCapInfo.ShortGIfor20));
-			pAd->MacTab.fAnyStation20Only = TRUE;
-		}
-
-		// 3*3
-		if (pAd->MACVersion >= RALINK_2883_VERSION && pAd->MACVersion < RALINK_3070_VERSION)
-			pEntry->MaxHTPhyMode.field.TxBF = pAd->CommonCfg.RegTransmitSetting.field.TxBF;
-
-		// find max fixed rate
-		for (i=23; i>=0; i--) // 3*3
-		{
-			j = i/8;
-			bitmask = (1<<(i-(j*8)));
-			if ((pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j] & bitmask) && (pHtCapability->MCSSet[j] & bitmask))
-			{
-				pEntry->MaxHTPhyMode.field.MCS = i;
-				break;
-			}
-			if (i==0)
-				break;
-		}
-
-
-		if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
-		{
-			if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
-			{
-				// Fix MCS as HT Duplicated Mode
-				pEntry->MaxHTPhyMode.field.BW = 1;
-				pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-				pEntry->MaxHTPhyMode.field.STBC = 0;
-				pEntry->MaxHTPhyMode.field.ShortGI = 0;
-				pEntry->MaxHTPhyMode.field.MCS = 32;
-			}
-			else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
-			{
-				// STA supports fixed MCS
-				pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
-			}
-		}
-
-		pEntry->MaxHTPhyMode.field.STBC = (pHtCapability->HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
-		pEntry->MpduDensity = pHtCapability->HtCapParm.MpduDensity;
-		pEntry->MaxRAmpduFactor = pHtCapability->HtCapParm.MaxRAmpduFactor;
-		pEntry->MmpsMode = (UCHAR)pHtCapability->HtCapInfo.MimoPs;
-		pEntry->AMsduSize = (UCHAR)pHtCapability->HtCapInfo.AMsduSize;
-		pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-
-		if (pAd->CommonCfg.DesiredHtPhy.AmsduEnable && (pAd->CommonCfg.REGBACapability.field.AutoBA == FALSE))
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_AMSDU_INUSED);
-		if (pHtCapability->HtCapInfo.ShortGIfor20)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
-		if (pHtCapability->HtCapInfo.ShortGIfor40)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
-		if (pHtCapability->HtCapInfo.TxSTBC)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
-		if (pHtCapability->HtCapInfo.RxSTBC)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
-		if (pHtCapability->ExtHtCapInfo.PlusHTC)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
-		if (pAd->CommonCfg.bRdg && pHtCapability->ExtHtCapInfo.RDGSupport)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
-		if (pHtCapability->ExtHtCapInfo.MCSFeedback == 0x03)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
-	}
-	else
-	{
-		pAd->MacTab.fAnyStationIsLegacy = TRUE;
-	}
-
-	NdisMoveMemory(&pEntry->HTCapability, pHtCapability, sizeof(HT_CAPABILITY_IE));
-#endif // DOT11_N_SUPPORT //
-
-	pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-	pEntry->CurrTxRate = pEntry->MaxSupportedRate;
-
-	// Set asic auto fall back
-	if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-	{
-		PUCHAR					pTable;
-		UCHAR					TableSize = 0;
-
-		MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
-		pEntry->bAutoTxRateSwitch = TRUE;
-	}
-	else
-	{
-		pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-		pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
-		pEntry->bAutoTxRateSwitch = FALSE;
-
-		// If the legacy mode is set, overwrite the transmit setting of this entry.
-		RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-	}
-
-	pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
-	pEntry->Sst = SST_ASSOC;
-	pEntry->AuthState = AS_AUTH_OPEN;
-	pEntry->AuthMode = pAd->StaCfg.AuthMode;
-	pEntry->WepStatus = pAd->StaCfg.WepStatus;
-
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-    if (pAd->StaCfg.WpaSupplicantUP)
-    {
-        union iwreq_data    wrqu;
-
-        SendAssocIEsToWpaSupplicant(pAd);
-        memset(&wrqu, 0, sizeof(wrqu));
-        wrqu.data.flags = RT_ASSOC_EVENT_FLAG;
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-    }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-    {
-        union iwreq_data    wrqu;
-        wext_notify_event_assoc(pAd);
-
-        memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-        memcpy(wrqu.ap_addr.sa_data, pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
-        wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-
-    }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-	return TRUE;
-}
-
-
+#include "../../rt2860/sta/assoc.c"
diff --git a/drivers/staging/rt2870/sta/auth.c b/drivers/staging/rt2870/sta/auth.c
index 73fb8d6e..57632f9 100644
--- a/drivers/staging/rt2870/sta/auth.c
+++ b/drivers/staging/rt2870/sta/auth.c
@@ -1,474 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	auth.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John		2004-9-3		porting from RT2500
-*/
-#include "../rt_config.h"
-
-/*
-    ==========================================================================
-    Description:
-        authenticate state machine init, including state transition and timer init
-    Parameters:
-        Sm - pointer to the auth state machine
-    Note:
-        The state machine looks like this
-
-                        AUTH_REQ_IDLE           AUTH_WAIT_SEQ2                   AUTH_WAIT_SEQ4
-    MT2_MLME_AUTH_REQ   mlme_auth_req_action    invalid_state_when_auth          invalid_state_when_auth
-    MT2_PEER_AUTH_EVEN  drop                    peer_auth_even_at_seq2_action    peer_auth_even_at_seq4_action
-    MT2_AUTH_TIMEOUT    Drop                    auth_timeout_action              auth_timeout_action
-
-	IRQL = PASSIVE_LEVEL
-
-    ==========================================================================
- */
-
-void AuthStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[])
-{
-    StateMachineInit(Sm, Trans, MAX_AUTH_STATE, MAX_AUTH_MSG, (STATE_MACHINE_FUNC)Drop, AUTH_REQ_IDLE, AUTH_MACHINE_BASE);
-
-    // the first column
-    StateMachineSetAction(Sm, AUTH_REQ_IDLE, MT2_MLME_AUTH_REQ, (STATE_MACHINE_FUNC)MlmeAuthReqAction);
-
-    // the second column
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ2, MT2_MLME_AUTH_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenAuth);
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ2, MT2_PEER_AUTH_EVEN, (STATE_MACHINE_FUNC)PeerAuthRspAtSeq2Action);
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ2, MT2_AUTH_TIMEOUT, (STATE_MACHINE_FUNC)AuthTimeoutAction);
-
-    // the third column
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ4, MT2_MLME_AUTH_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenAuth);
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ4, MT2_PEER_AUTH_EVEN, (STATE_MACHINE_FUNC)PeerAuthRspAtSeq4Action);
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ4, MT2_AUTH_TIMEOUT, (STATE_MACHINE_FUNC)AuthTimeoutAction);
-
-	RTMPInitTimer(pAd, &pAd->MlmeAux.AuthTimer, GET_TIMER_FUNCTION(AuthTimeout), pAd, FALSE);
-}
-
-/*
-    ==========================================================================
-    Description:
-        function to be executed at timer thread when auth timer expires
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID AuthTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3)
-{
-    RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-    DBGPRINT(RT_DEBUG_TRACE,("AUTH - AuthTimeout\n"));
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return;
-
-	// send a de-auth to reset AP's state machine (Patch AP-Dir635)
-	if (pAd->Mlme.AuthMachine.CurrState == AUTH_WAIT_SEQ2)
-		Cls2errAction(pAd, pAd->MlmeAux.Bssid);
-
-
-    MlmeEnqueue(pAd, AUTH_STATE_MACHINE, MT2_AUTH_TIMEOUT, 0, NULL);
-    RT28XX_MLME_HANDLER(pAd);
-}
-
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeAuthReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    UCHAR              Addr[6];
-    USHORT             Alg, Seq, Status;
-    ULONG              Timeout;
-    HEADER_802_11      AuthHdr;
-    BOOLEAN            TimerCancelled;
-    NDIS_STATUS        NStatus;
-    PUCHAR             pOutBuffer = NULL;
-    ULONG              FrameLen = 0;
-
-	// Block all authentication request durning WPA block period
-	if (pAd->StaCfg.bBlockAssoc == TRUE)
-	{
-        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Block Auth request durning WPA block period!\n"));
-        pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-        Status = MLME_STATE_MACHINE_REJECT;
-        MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-	}
-    else if(MlmeAuthReqSanity(pAd, Elem->Msg, Elem->MsgLen, Addr, &Timeout, &Alg))
-    {
-        // reset timer
-        RTMPCancelTimer(&pAd->MlmeAux.AuthTimer, &TimerCancelled);
-        COPY_MAC_ADDR(pAd->MlmeAux.Bssid, Addr);
-        pAd->MlmeAux.Alg  = Alg;
-        Seq = 1;
-        Status = MLME_SUCCESS;
-
-        NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-        if(NStatus != NDIS_STATUS_SUCCESS)
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("AUTH - MlmeAuthReqAction(Alg:%d) allocate memory failed\n", Alg));
-            pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-            Status = MLME_FAIL_NO_RESOURCE;
-            MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-            return;
-        }
-
-        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Send AUTH request seq#1 (Alg=%d)...\n", Alg));
-        MgtMacHeaderInit(pAd, &AuthHdr, SUBTYPE_AUTH, 0, Addr, pAd->MlmeAux.Bssid);
-        MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-                          sizeof(HEADER_802_11),&AuthHdr,
-                          2,                    &Alg,
-                          2,                    &Seq,
-                          2,                    &Status,
-                          END_OF_ARGS);
-        MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-    	MlmeFreeMemory(pAd, pOutBuffer);
-
-        RTMPSetTimer(&pAd->MlmeAux.AuthTimer, Timeout);
-        pAd->Mlme.AuthMachine.CurrState = AUTH_WAIT_SEQ2;
-    }
-    else
-    {
-        DBGPRINT_ERR(("AUTH - MlmeAuthReqAction() sanity check failed\n"));
-        pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-        Status = MLME_INVALID_FORMAT;
-        MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerAuthRspAtSeq2Action(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    UCHAR         Addr2[MAC_ADDR_LEN];
-    USHORT        Seq, Status, RemoteStatus, Alg;
-    UCHAR         ChlgText[CIPHER_TEXT_LEN];
-    UCHAR         CyperChlgText[CIPHER_TEXT_LEN + 8 + 8];
-    UCHAR         Element[2];
-    HEADER_802_11 AuthHdr;
-    BOOLEAN       TimerCancelled;
-    PUCHAR        pOutBuffer = NULL;
-    NDIS_STATUS   NStatus;
-    ULONG         FrameLen = 0;
-    USHORT        Status2;
-
-    if (PeerAuthSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &Alg, &Seq, &Status, ChlgText))
-    {
-        if (MAC_ADDR_EQUAL(pAd->MlmeAux.Bssid, Addr2) && Seq == 2)
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Receive AUTH_RSP seq#2 to me (Alg=%d, Status=%d)\n", Alg, Status));
-            RTMPCancelTimer(&pAd->MlmeAux.AuthTimer, &TimerCancelled);
-
-            if (Status == MLME_SUCCESS)
-            {
-                // Authentication Mode "LEAP" has allow for CCX 1.X
-                if ((pAd->MlmeAux.Alg == Ndis802_11AuthModeOpen)
-#ifdef LEAP_SUPPORT
-					|| (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
-				)
-                {
-                    pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-#ifdef LEAP_SUPPORT
-                    pAd->Mlme.LeapMachine.CurrState = LEAP_IDLE;
-#endif // LEAP_SUPPORT //
-                    MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-                }
-                else
-                {
-                    // 2. shared key, need to be challenged
-                    Seq++;
-                    RemoteStatus = MLME_SUCCESS;
-
-					// Get an unused nonpaged memory
-                    NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-                    if(NStatus != NDIS_STATUS_SUCCESS)
-                    {
-                        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - PeerAuthRspAtSeq2Action() allocate memory fail\n"));
-                        pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-                        Status2 = MLME_FAIL_NO_RESOURCE;
-                        MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status2);
-                        return;
-                    }
-
-                    DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Send AUTH request seq#3...\n"));
-                    MgtMacHeaderInit(pAd, &AuthHdr, SUBTYPE_AUTH, 0, Addr2, pAd->MlmeAux.Bssid);
-                    AuthHdr.FC.Wep = 1;
-                    // Encrypt challenge text & auth information
-                    RTMPInitWepEngine(
-                    	pAd,
-                    	pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key,
-                    	pAd->StaCfg.DefaultKeyId,
-                    	pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].KeyLen,
-                    	CyperChlgText);
-
-					Alg = cpu2le16(*(USHORT *)&Alg);
-					Seq = cpu2le16(*(USHORT *)&Seq);
-					RemoteStatus= cpu2le16(*(USHORT *)&RemoteStatus);
-
-					RTMPEncryptData(pAd, (PUCHAR) &Alg, CyperChlgText + 4, 2);
-					RTMPEncryptData(pAd, (PUCHAR) &Seq, CyperChlgText + 6, 2);
-					RTMPEncryptData(pAd, (PUCHAR) &RemoteStatus, CyperChlgText + 8, 2);
-					Element[0] = 16;
-					Element[1] = 128;
-					RTMPEncryptData(pAd, Element, CyperChlgText + 10, 2);
-					RTMPEncryptData(pAd, ChlgText, CyperChlgText + 12, 128);
-					RTMPSetICV(pAd, CyperChlgText + 140);
-                    MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-                                      sizeof(HEADER_802_11),    &AuthHdr,
-                                      CIPHER_TEXT_LEN + 16,     CyperChlgText,
-                                      END_OF_ARGS);
-                    MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-                	MlmeFreeMemory(pAd, pOutBuffer);
-
-                    RTMPSetTimer(&pAd->MlmeAux.AuthTimer, AUTH_TIMEOUT);
-                    pAd->Mlme.AuthMachine.CurrState = AUTH_WAIT_SEQ4;
-                }
-            }
-            else
-            {
-#ifdef LEAP_SUPPORT
-                if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-                {
-                    //Invalid Authentication possible rogue AP
-                    //Add this Ap to Rogue AP.
-                    RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, Addr2, LEAP_REASON_INVALID_AUTH);
-				}
-#endif // LEAP_SUPPORT //
-                pAd->StaCfg.AuthFailReason = Status;
-                COPY_MAC_ADDR(pAd->StaCfg.AuthFailSta, Addr2);
-                pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-                MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-            }
-        }
-    }
-    else
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - PeerAuthSanity() sanity check fail\n"));
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerAuthRspAtSeq4Action(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    UCHAR         Addr2[MAC_ADDR_LEN];
-    USHORT        Alg, Seq, Status;
-    CHAR          ChlgText[CIPHER_TEXT_LEN];
-    BOOLEAN       TimerCancelled;
-
-    if(PeerAuthSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &Alg, &Seq, &Status, ChlgText))
-    {
-        if(MAC_ADDR_EQUAL(pAd->MlmeAux.Bssid, Addr2) && Seq == 4)
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Receive AUTH_RSP seq#4 to me\n"));
-            RTMPCancelTimer(&pAd->MlmeAux.AuthTimer, &TimerCancelled);
-
-            if (Status != MLME_SUCCESS)
-            {
-                pAd->StaCfg.AuthFailReason = Status;
-                COPY_MAC_ADDR(pAd->StaCfg.AuthFailSta, Addr2);
-            }
-
-            pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-            MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-        }
-    }
-    else
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - PeerAuthRspAtSeq4Action() sanity check fail\n"));
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeDeauthReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    MLME_DEAUTH_REQ_STRUCT *pInfo;
-    HEADER_802_11 DeauthHdr;
-    PUCHAR        pOutBuffer = NULL;
-    NDIS_STATUS   NStatus;
-    ULONG         FrameLen = 0;
-    USHORT        Status;
-
-    pInfo = (MLME_DEAUTH_REQ_STRUCT *)Elem->Msg;
-
-    NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-    if (NStatus != NDIS_STATUS_SUCCESS)
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - MlmeDeauthReqAction() allocate memory fail\n"));
-        pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-        Status = MLME_FAIL_NO_RESOURCE;
-        MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_DEAUTH_CONF, 2, &Status);
-        return;
-    }
-
-    DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Send DE-AUTH request (Reason=%d)...\n", pInfo->Reason));
-    MgtMacHeaderInit(pAd, &DeauthHdr, SUBTYPE_DEAUTH, 0, pInfo->Addr, pAd->MlmeAux.Bssid);
-    MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-                      sizeof(HEADER_802_11),&DeauthHdr,
-                      2,                    &pInfo->Reason,
-                      END_OF_ARGS);
-    MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-    pAd->StaCfg.DeauthReason = pInfo->Reason;
-    COPY_MAC_ADDR(pAd->StaCfg.DeauthSta, pInfo->Addr);
-    pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-    Status = MLME_SUCCESS;
-    MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_DEAUTH_CONF, 2, &Status);
-
-	// send wireless event - for deauthentication
-	if (pAd->CommonCfg.bWirelessEvent)
-		RTMPSendWirelessEvent(pAd, IW_DEAUTH_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID AuthTimeoutAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    USHORT Status;
-    DBGPRINT(RT_DEBUG_TRACE, ("AUTH - AuthTimeoutAction\n"));
-    pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-    Status = MLME_REJ_TIMEOUT;
-    MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID InvalidStateWhenAuth(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    USHORT Status;
-    DBGPRINT(RT_DEBUG_TRACE, ("AUTH - InvalidStateWhenAuth (state=%ld), reset AUTH state machine\n", pAd->Mlme.AuthMachine.CurrState));
-    pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-    Status = MLME_STATE_MACHINE_REJECT;
-    MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-}
-
-/*
-    ==========================================================================
-    Description:
-        Some STA/AP
-    Note:
-        This action should never trigger AUTH state transition, therefore we
-        separate it from AUTH state machine, and make it as a standalone service
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID Cls2errAction(
-    IN PRTMP_ADAPTER pAd,
-    IN PUCHAR pAddr)
-{
-    HEADER_802_11 DeauthHdr;
-    PUCHAR        pOutBuffer = NULL;
-    NDIS_STATUS   NStatus;
-    ULONG         FrameLen = 0;
-    USHORT        Reason = REASON_CLS2ERR;
-
-    NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-    if (NStatus != NDIS_STATUS_SUCCESS)
-        return;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Class 2 error, Send DEAUTH frame...\n"));
-    MgtMacHeaderInit(pAd, &DeauthHdr, SUBTYPE_DEAUTH, 0, pAddr, pAd->MlmeAux.Bssid);
-    MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-                      sizeof(HEADER_802_11),&DeauthHdr,
-                      2,                    &Reason,
-                      END_OF_ARGS);
-    MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-    pAd->StaCfg.DeauthReason = Reason;
-    COPY_MAC_ADDR(pAd->StaCfg.DeauthSta, pAddr);
-}
-
-
+#include "../../rt2860/sta/auth.c"
diff --git a/drivers/staging/rt2870/sta/auth_rsp.c b/drivers/staging/rt2870/sta/auth_rsp.c
index 6e3c2d2..783e266 100644
--- a/drivers/staging/rt2870/sta/auth_rsp.c
+++ b/drivers/staging/rt2870/sta/auth_rsp.c
@@ -1,166 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	auth_rsp.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John		2004-10-1		copy from RT2560
-*/
-#include "../rt_config.h"
-
-/*
-    ==========================================================================
-    Description:
-        authentication state machine init procedure
-    Parameters:
-        Sm - the state machine
-
-	IRQL = PASSIVE_LEVEL
-
-    ==========================================================================
- */
-VOID AuthRspStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN PSTATE_MACHINE Sm,
-    IN STATE_MACHINE_FUNC Trans[])
-{
-    StateMachineInit(Sm, Trans, MAX_AUTH_RSP_STATE, MAX_AUTH_RSP_MSG, (STATE_MACHINE_FUNC)Drop, AUTH_RSP_IDLE, AUTH_RSP_MACHINE_BASE);
-
-    // column 1
-    StateMachineSetAction(Sm, AUTH_RSP_IDLE, MT2_PEER_DEAUTH, (STATE_MACHINE_FUNC)PeerDeauthAction);
-
-    // column 2
-    StateMachineSetAction(Sm, AUTH_RSP_WAIT_CHAL, MT2_PEER_DEAUTH, (STATE_MACHINE_FUNC)PeerDeauthAction);
-
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
-*/
-VOID PeerAuthSimpleRspGenAndSend(
-    IN PRTMP_ADAPTER pAd,
-    IN PHEADER_802_11 pHdr80211,
-    IN USHORT Alg,
-    IN USHORT Seq,
-    IN USHORT Reason,
-    IN USHORT Status)
-{
-    HEADER_802_11     AuthHdr;
-    ULONG             FrameLen = 0;
-    PUCHAR            pOutBuffer = NULL;
-    NDIS_STATUS       NStatus;
-
-    if (Reason != MLME_SUCCESS)
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("Peer AUTH fail...\n"));
-        return;
-    }
-
-	//Get an unused nonpaged memory
-    NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-    if (NStatus != NDIS_STATUS_SUCCESS)
-        return;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Send AUTH response (seq#2)...\n"));
-    MgtMacHeaderInit(pAd, &AuthHdr, SUBTYPE_AUTH, 0, pHdr80211->Addr2, pAd->MlmeAux.Bssid);
-    MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-                      sizeof(HEADER_802_11),    &AuthHdr,
-                      2,                        &Alg,
-                      2,                        &Seq,
-                      2,                        &Reason,
-                      END_OF_ARGS);
-    MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
-*/
-VOID PeerDeauthAction(
-    IN PRTMP_ADAPTER pAd,
-    IN PMLME_QUEUE_ELEM Elem)
-{
-    UCHAR       Addr2[MAC_ADDR_LEN];
-    USHORT      Reason;
-
-    if (PeerDeauthSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &Reason))
-    {
-        if (INFRA_ON(pAd) && MAC_ADDR_EQUAL(Addr2, pAd->CommonCfg.Bssid))
-        {
-            DBGPRINT(RT_DEBUG_TRACE,("AUTH_RSP - receive DE-AUTH from our AP (Reason=%d)\n", Reason));
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-            {
-                union iwreq_data    wrqu;
-                memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-
-			// send wireless event - for deauthentication
-			if (pAd->CommonCfg.bWirelessEvent)
-				RTMPSendWirelessEvent(pAd, IW_DEAUTH_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-
-            LinkDown(pAd, TRUE);
-
-            // Authentication Mode Cisco_LEAP has start a timer
-            // We should cancel it if using LEAP
-#ifdef LEAP_SUPPORT
-            if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-            {
-                RTMPCancelTimer(&pAd->StaCfg.LeapAuthTimer, &TimerCancelled);
-                //Check is it mach the LEAP Authentication failed as possible a Rogue AP
-                //on it's PortSecured not equal to WPA_802_1X_PORT_SECURED while process the Authenticaton.
-                if ((pAd->StaCfg.PortSecured != WPA_802_1X_PORT_SECURED) && (pAd->Mlme.LeapMachine.CurrState != LEAP_IDLE))
-                {
-                    RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, Addr2, LEAP_REASON_AUTH_TIMEOUT);
-                }
-            }
-#endif // LEAP_SUPPORT //
-        }
-    }
-    else
-    {
-        DBGPRINT(RT_DEBUG_TRACE,("AUTH_RSP - PeerDeauthAction() sanity check fail\n"));
-    }
-}
-
+#include "../../rt2860/sta/auth_rsp.c"
diff --git a/drivers/staging/rt2870/sta/connect.c b/drivers/staging/rt2870/sta/connect.c
index c93140a..f6c7bbf 100644
--- a/drivers/staging/rt2870/sta/connect.c
+++ b/drivers/staging/rt2870/sta/connect.c
@@ -1,2822 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	connect.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John			2004-08-08			Major modification from RT2560
-*/
-#include "../rt_config.h"
-
-UCHAR	CipherSuiteWpaNoneTkip[] = {
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x02,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x02,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x00	// authentication
-		};
-UCHAR	CipherSuiteWpaNoneTkipLen = (sizeof(CipherSuiteWpaNoneTkip) / sizeof(UCHAR));
-
-UCHAR	CipherSuiteWpaNoneAes[] = {
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x04,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x04,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x00	// authentication
-		};
-UCHAR	CipherSuiteWpaNoneAesLen = (sizeof(CipherSuiteWpaNoneAes) / sizeof(UCHAR));
-
-// The following MACRO is called after 1. starting an new IBSS, 2. succesfully JOIN an IBSS,
-// or 3. succesfully ASSOCIATE to a BSS, 4. successfully RE_ASSOCIATE to a BSS
-// All settings successfuly negotiated furing MLME state machines become final settings
-// and are copied to pAd->StaActive
-#define COPY_SETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(_pAd)                                 \
-{                                                                                       \
-	(_pAd)->CommonCfg.SsidLen = (_pAd)->MlmeAux.SsidLen;                                \
-	NdisMoveMemory((_pAd)->CommonCfg.Ssid, (_pAd)->MlmeAux.Ssid, (_pAd)->MlmeAux.SsidLen); \
-	COPY_MAC_ADDR((_pAd)->CommonCfg.Bssid, (_pAd)->MlmeAux.Bssid);                      \
-	(_pAd)->CommonCfg.Channel = (_pAd)->MlmeAux.Channel;                                \
-	(_pAd)->CommonCfg.CentralChannel = (_pAd)->MlmeAux.CentralChannel;                  \
-	(_pAd)->StaActive.Aid = (_pAd)->MlmeAux.Aid;                                        \
-	(_pAd)->StaActive.AtimWin = (_pAd)->MlmeAux.AtimWin;                                \
-	(_pAd)->StaActive.CapabilityInfo = (_pAd)->MlmeAux.CapabilityInfo;                  \
-	(_pAd)->CommonCfg.BeaconPeriod = (_pAd)->MlmeAux.BeaconPeriod;                      \
-	(_pAd)->StaActive.CfpMaxDuration = (_pAd)->MlmeAux.CfpMaxDuration;                  \
-	(_pAd)->StaActive.CfpPeriod = (_pAd)->MlmeAux.CfpPeriod;                            \
-	(_pAd)->StaActive.SupRateLen = (_pAd)->MlmeAux.SupRateLen;                          \
-	NdisMoveMemory((_pAd)->StaActive.SupRate, (_pAd)->MlmeAux.SupRate, (_pAd)->MlmeAux.SupRateLen);\
-	(_pAd)->StaActive.ExtRateLen = (_pAd)->MlmeAux.ExtRateLen;                          \
-	NdisMoveMemory((_pAd)->StaActive.ExtRate, (_pAd)->MlmeAux.ExtRate, (_pAd)->MlmeAux.ExtRateLen);\
-	NdisMoveMemory(&(_pAd)->CommonCfg.APEdcaParm, &(_pAd)->MlmeAux.APEdcaParm, sizeof(EDCA_PARM));\
-	NdisMoveMemory(&(_pAd)->CommonCfg.APQosCapability, &(_pAd)->MlmeAux.APQosCapability, sizeof(QOS_CAPABILITY_PARM));\
-	NdisMoveMemory(&(_pAd)->CommonCfg.APQbssLoad, &(_pAd)->MlmeAux.APQbssLoad, sizeof(QBSS_LOAD_PARM));\
-	COPY_MAC_ADDR((_pAd)->MacTab.Content[BSSID_WCID].Addr, (_pAd)->MlmeAux.Bssid);      \
-	(_pAd)->MacTab.Content[BSSID_WCID].Aid = (_pAd)->MlmeAux.Aid;                       \
-	(_pAd)->MacTab.Content[BSSID_WCID].PairwiseKey.CipherAlg = (_pAd)->StaCfg.PairCipher;\
-	COPY_MAC_ADDR((_pAd)->MacTab.Content[BSSID_WCID].PairwiseKey.BssId, (_pAd)->MlmeAux.Bssid);\
-	(_pAd)->MacTab.Content[BSSID_WCID].RateLen = (_pAd)->StaActive.SupRateLen + (_pAd)->StaActive.ExtRateLen;\
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
-*/
-VOID MlmeCntlInit(
-	IN PRTMP_ADAPTER pAd,
-	IN STATE_MACHINE *S,
-	OUT STATE_MACHINE_FUNC Trans[])
-{
-	// Control state machine differs from other state machines, the interface
-	// follows the standard interface
-	pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID MlmeCntlMachinePerformAction(
-	IN PRTMP_ADAPTER pAd,
-	IN STATE_MACHINE *S,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	switch(pAd->Mlme.CntlMachine.CurrState)
-	{
-		case CNTL_IDLE:
-				CntlIdleProc(pAd, Elem);
-			break;
-		case CNTL_WAIT_DISASSOC:
-			CntlWaitDisassocProc(pAd, Elem);
-			break;
-		case CNTL_WAIT_JOIN:
-			CntlWaitJoinProc(pAd, Elem);
-			break;
-
-		// CNTL_WAIT_REASSOC is the only state in CNTL machine that does
-		// not triggered directly or indirectly by "RTMPSetInformation(OID_xxx)".
-		// Therefore not protected by NDIS's "only one outstanding OID request"
-		// rule. Which means NDIS may SET OID in the middle of ROAMing attempts.
-		// Current approach is to block new SET request at RTMPSetInformation()
-		// when CntlMachine.CurrState is not CNTL_IDLE
-		case CNTL_WAIT_REASSOC:
-			CntlWaitReassocProc(pAd, Elem);
-			break;
-
-		case CNTL_WAIT_START:
-			CntlWaitStartProc(pAd, Elem);
-			break;
-		case CNTL_WAIT_AUTH:
-			CntlWaitAuthProc(pAd, Elem);
-			break;
-		case CNTL_WAIT_AUTH2:
-			CntlWaitAuthProc2(pAd, Elem);
-			break;
-		case CNTL_WAIT_ASSOC:
-			CntlWaitAssocProc(pAd, Elem);
-			break;
-
-		case CNTL_WAIT_OID_LIST_SCAN:
-			if(Elem->MsgType == MT2_SCAN_CONF)
-			{
-				// Resume TxRing after SCANING complete. We hope the out-of-service time
-				// won't be too long to let upper layer time-out the waiting frames
-				RTMPResumeMsduTransmission(pAd);
-				if (pAd->StaCfg.CCXReqType != MSRN_TYPE_UNUSED)
-				{
-					// Cisco scan request is finished, prepare beacon report
-					MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_DONE, 0, NULL);
-				}
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-
-                //
-				// Set LED status to previous status.
-				//
-				if (pAd->bLedOnScanning)
-				{
-					pAd->bLedOnScanning = FALSE;
-					RTMPSetLED(pAd, pAd->LedStatus);
-				}
-#ifdef DOT11N_DRAFT3
-				// AP sent a 2040Coexistence mgmt frame, then station perform a scan, and then send back the respone.
-				if (pAd->CommonCfg.BSSCoexist2040.field.InfoReq == 1)
-				{
-					Update2040CoexistFrameAndNotify(pAd, BSSID_WCID, TRUE);
-				}
-#endif // DOT11N_DRAFT3 //
-			}
-			break;
-
-		case CNTL_WAIT_OID_DISASSOC:
-			if (Elem->MsgType == MT2_DISASSOC_CONF)
-			{
-				LinkDown(pAd, FALSE);
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-			}
-			break;
-#ifdef RT2870
-		//
-		// This state is for that we want to connect to an AP but
-		// it didn't find on BSS List table. So we need to scan the air first,
-		// after that we can try to connect to the desired AP if available.
-		//
-		case CNTL_WAIT_SCAN_FOR_CONNECT:
-			if(Elem->MsgType == MT2_SCAN_CONF)
-			{
-				// Resume TxRing after SCANING complete. We hope the out-of-service time
-				// won't be too long to let upper layer time-out the waiting frames
-				RTMPResumeMsduTransmission(pAd);
-#ifdef CCX_SUPPORT
-				if (pAd->StaCfg.CCXReqType != MSRN_TYPE_UNUSED)
-				{
-					// Cisco scan request is finished, prepare beacon report
-					MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_DONE, 0, NULL);
-				}
-#endif // CCX_SUPPORT //
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-
-				//
-				// Check if we can connect to.
-				//
-				BssTableSsidSort(pAd, &pAd->MlmeAux.SsidBssTab, pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen);
-				if (pAd->MlmeAux.SsidBssTab.BssNr > 0)
-				{
-					MlmeAutoReconnectLastSSID(pAd);
-				}
-			}
-			break;
-#endif // RT2870 //
-		default:
-			DBGPRINT_ERR(("!ERROR! CNTL - Illegal message type(=%ld)", Elem->MsgType));
-			break;
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlIdleProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	MLME_DISASSOC_REQ_STRUCT   DisassocReq;
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))
-		return;
-
-	switch(Elem->MsgType)
-	{
-		case OID_802_11_SSID:
-			CntlOidSsidProc(pAd, Elem);
-			break;
-
-		case OID_802_11_BSSID:
-			CntlOidRTBssidProc(pAd,Elem);
-			break;
-
-		case OID_802_11_BSSID_LIST_SCAN:
-			CntlOidScanProc(pAd,Elem);
-			break;
-
-		case OID_802_11_DISASSOCIATE:
-#ifdef RALINK_ATE
-			if(ATE_ON(pAd))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-			DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-			MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ, sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_DISASSOC;
-#ifdef WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_ENABLE_WITH_WEB_UI)
-#endif // WPA_SUPPLICANT_SUPPORT //
-            {
-    			// Set the AutoReconnectSsid to prevent it reconnect to old SSID
-    			// Since calling this indicate user don't want to connect to that SSID anymore.
-    			pAd->MlmeAux.AutoReconnectSsidLen= 32;
-    			NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen);
-            }
-			break;
-
-		case MT2_MLME_ROAMING_REQ:
-			CntlMlmeRoamingProc(pAd, Elem);
-			break;
-
-        case OID_802_11_MIC_FAILURE_REPORT_FRAME:
-            WpaMicFailureReportFrame(pAd, Elem);
-            break;
-
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_SET_DLS_PARAM:
-			CntlOidDLSSetupProc(pAd, Elem);
-			break;
-#endif // QOS_DLS_SUPPORT //
-
-		default:
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Illegal message in CntlIdleProc(MsgType=%ld)\n",Elem->MsgType));
-			break;
-	}
-}
-
-VOID CntlOidScanProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	MLME_SCAN_REQ_STRUCT       ScanReq;
-	ULONG                      BssIdx = BSS_NOT_FOUND;
-	BSS_ENTRY                  CurrBss;
-
-#ifdef RALINK_ATE
-/* Disable scanning when ATE is running. */
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-
-	// record current BSS if network is connected.
-	// 2003-2-13 do not include current IBSS if this is the only STA in this IBSS.
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-	{
-		BssIdx = BssSsidTableSearch(&pAd->ScanTab, pAd->CommonCfg.Bssid, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen, pAd->CommonCfg.Channel);
-		if (BssIdx != BSS_NOT_FOUND)
-		{
-			NdisMoveMemory(&CurrBss, &pAd->ScanTab.BssEntry[BssIdx], sizeof(BSS_ENTRY));
-		}
-	}
-
-	// clean up previous SCAN result, add current BSS back to table if any
-	BssTableInit(&pAd->ScanTab);
-	if (BssIdx != BSS_NOT_FOUND)
-	{
-		// DDK Note: If the NIC is associated with a particular BSSID and SSID
-		//    that are not contained in the list of BSSIDs generated by this scan, the
-		//    BSSID description of the currently associated BSSID and SSID should be
-		//    appended to the list of BSSIDs in the NIC's database.
-		// To ensure this, we append this BSS as the first entry in SCAN result
-		NdisMoveMemory(&pAd->ScanTab.BssEntry[0], &CurrBss, sizeof(BSS_ENTRY));
-		pAd->ScanTab.BssNr = 1;
-	}
-
-	ScanParmFill(pAd, &ScanReq, "", 0, BSS_ANY, SCAN_ACTIVE);
-	MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ,
-		sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-	pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-}
-
-/*
-	==========================================================================
-	Description:
-		Before calling this routine, user desired SSID should already been
-		recorded in CommonCfg.Ssid[]
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlOidSsidProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM * Elem)
-{
-	PNDIS_802_11_SSID          pOidSsid = (NDIS_802_11_SSID *)Elem->Msg;
-	MLME_DISASSOC_REQ_STRUCT   DisassocReq;
-	ULONG					   Now;
-
-	// Step 1. record the desired user settings to MlmeAux
-	NdisZeroMemory(pAd->MlmeAux.Ssid, MAX_LEN_OF_SSID);
-	NdisMoveMemory(pAd->MlmeAux.Ssid, pOidSsid->Ssid, pOidSsid->SsidLength);
-	pAd->MlmeAux.SsidLen = (UCHAR)pOidSsid->SsidLength;
-	NdisZeroMemory(pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
-	pAd->MlmeAux.BssType = pAd->StaCfg.BssType;
-
-
-	//
-	// Update Reconnect Ssid, that user desired to connect.
-	//
-	NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, MAX_LEN_OF_SSID);
-	NdisMoveMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-	pAd->MlmeAux.AutoReconnectSsidLen = pAd->MlmeAux.SsidLen;
-
-	// step 2. find all matching BSS in the lastest SCAN result (inBssTab)
-	//    & log them into MlmeAux.SsidBssTab for later-on iteration. Sort by RSSI order
-	BssTableSsidSort(pAd, &pAd->MlmeAux.SsidBssTab, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - %d BSS of %d BSS match the desire (%d)SSID - %s\n",
-			pAd->MlmeAux.SsidBssTab.BssNr, pAd->ScanTab.BssNr, pAd->MlmeAux.SsidLen, pAd->MlmeAux.Ssid));
-	NdisGetSystemUpTime(&Now);
-
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) &&
-		(pAd->CommonCfg.SsidLen == pAd->MlmeAux.SsidBssTab.BssEntry[0].SsidLen) &&
-		NdisEqualMemory(pAd->CommonCfg.Ssid, pAd->MlmeAux.SsidBssTab.BssEntry[0].Ssid, pAd->CommonCfg.SsidLen) &&
-		MAC_ADDR_EQUAL(pAd->CommonCfg.Bssid, pAd->MlmeAux.SsidBssTab.BssEntry[0].Bssid))
-	{
-		// Case 1. already connected with an AP who has the desired SSID
-		//         with highest RSSI
-
-		// Add checking Mode "LEAP" for CCX 1.0
-		if (((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-			 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-			 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
-			 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-#ifdef LEAP_SUPPORT
-			 || (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
-			 ) &&
-			(pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-		{
-			// case 1.1 For WPA, WPA-PSK, if the 1x port is not secured, we have to redo
-			//          connection process
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - disassociate with current AP...\n"));
-			DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-			MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
-						sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
-		}
-		else if (pAd->bConfigChanged == TRUE)
-		{
-			// case 1.2 Important Config has changed, we have to reconnect to the same AP
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - disassociate with current AP Because config changed...\n"));
-			DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-			MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
-						sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
-		}
-		else
-		{
-			// case 1.3. already connected to the SSID with highest RSSI.
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - already with this BSSID. ignore this SET_SSID request\n"));
-			//
-			// (HCT 12.1) 1c_wlan_mediaevents required
-			// media connect events are indicated when associating with the same AP
-			//
-			if (INFRA_ON(pAd))
-			{
-				//
-				// Since MediaState already is NdisMediaStateConnected
-				// We just indicate the connect event again to meet the WHQL required.
-				//
-				pAd->IndicateMediaState = NdisMediaStateConnected;
-				RTMP_IndicateMediaState(pAd);
-                pAd->ExtraInfo = GENERAL_LINK_UP;   // Update extra information to link is up
-			}
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-            {
-                union iwreq_data    wrqu;
-
-                memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                memcpy(wrqu.ap_addr.sa_data, pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
-                wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-		}
-	}
-	else if (INFRA_ON(pAd))
-	{
-		//
-		// For RT61
-		// [88888] OID_802_11_SSID should have returned NDTEST_WEP_AP2(Returned: )
-		// RT61 may lost SSID, and not connect to NDTEST_WEP_AP2 and will connect to NDTEST_WEP_AP2 by Autoreconnect
-		// But media status is connected, so the SSID not report correctly.
-		//
-		if (!SSID_EQUAL(pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen))
-		{
-			//
-			// Different SSID means not Roaming case, so we let LinkDown() to Indicate a disconnect event.
-			//
-			pAd->MlmeAux.CurrReqIsFromNdis = TRUE;
-		}
-		// case 2. active INFRA association existent
-		//    roaming is done within miniport driver, nothing to do with configuration
-		//    utility. so upon a new SET(OID_802_11_SSID) is received, we just
-		//    disassociate with the current associated AP,
-		//    then perform a new association with this new SSID, no matter the
-		//    new/old SSID are the same or not.
-		DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - disassociate with current AP...\n"));
-		DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-		MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
-					sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
-	}
-	else
-	{
-		if (ADHOC_ON(pAd))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - drop current ADHOC\n"));
-			LinkDown(pAd, FALSE);
-			OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-			pAd->IndicateMediaState = NdisMediaStateDisconnected;
-			RTMP_IndicateMediaState(pAd);
-            pAd->ExtraInfo = GENERAL_LINK_DOWN;
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():NDIS_STATUS_MEDIA_DISCONNECT Event C!\n"));
-		}
-
-		if ((pAd->MlmeAux.SsidBssTab.BssNr == 0) &&
-			(pAd->StaCfg.bAutoReconnect == TRUE) &&
-			(pAd->MlmeAux.BssType == BSS_INFRA) &&
-			(MlmeValidateSSID(pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen) == TRUE)
-			)
-		{
-			MLME_SCAN_REQ_STRUCT       ScanReq;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - No matching BSS, start a new scan\n"));
-			ScanParmFill(pAd, &ScanReq, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen, BSS_ANY, SCAN_ACTIVE);
-			MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-			// Reset Missed scan number
-			pAd->StaCfg.LastScanTime = Now;
-		}
-		else
-		{
-			pAd->MlmeAux.BssIdx = 0;
-			IterateOnBssTab(pAd);
-		}
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlOidRTBssidProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM * Elem)
-{
-	ULONG       BssIdx;
-	PUCHAR      pOidBssid = (PUCHAR)Elem->Msg;
-	MLME_DISASSOC_REQ_STRUCT    DisassocReq;
-	MLME_JOIN_REQ_STRUCT        JoinReq;
-
-#ifdef RALINK_ATE
-/* No need to perform this routine when ATE is running. */
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	// record user desired settings
-	COPY_MAC_ADDR(pAd->MlmeAux.Bssid, pOidBssid);
-	pAd->MlmeAux.BssType = pAd->StaCfg.BssType;
-
-	//
-	// Update Reconnect Ssid, that user desired to connect.
-	//
-	NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, MAX_LEN_OF_SSID);
-	pAd->MlmeAux.AutoReconnectSsidLen = pAd->MlmeAux.SsidLen;
-	NdisMoveMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-
-	// find the desired BSS in the latest SCAN result table
-	BssIdx = BssTableSearch(&pAd->ScanTab, pOidBssid, pAd->MlmeAux.Channel);
-	if (BssIdx == BSS_NOT_FOUND)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - BSSID not found. reply NDIS_STATUS_NOT_ACCEPTED\n"));
-		pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-		return;
-	}
-
-	// copy the matched BSS entry from ScanTab to MlmeAux.SsidBssTab. Why?
-	// Because we need this entry to become the JOIN target in later on SYNC state machine
-	pAd->MlmeAux.BssIdx = 0;
-	pAd->MlmeAux.SsidBssTab.BssNr = 1;
-	NdisMoveMemory(&pAd->MlmeAux.SsidBssTab.BssEntry[0], &pAd->ScanTab.BssEntry[BssIdx], sizeof(BSS_ENTRY));
-
-	//pAd->MlmeAux.AutoReconnectSsidLen = pAd->ScanTab.BssEntry[BssIdx].SsidLen;
-	//NdisMoveMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->ScanTab.BssEntry[BssIdx].Ssid, pAd->ScanTab.BssEntry[BssIdx].SsidLen);
-
-	// Add SSID into MlmeAux for site surey joining hidden SSID
-	//pAd->MlmeAux.SsidLen = pAd->ScanTab.BssEntry[BssIdx].SsidLen;
-	//NdisMoveMemory(pAd->MlmeAux.Ssid, pAd->ScanTab.BssEntry[BssIdx].Ssid, pAd->MlmeAux.SsidLen);
-
-	// 2002-11-26 skip the following checking. i.e. if user wants to re-connect to same AP
-	//   we just follow normal procedure. The reason of user doing this may because he/she changed
-	//   AP to another channel, but we still received BEACON from it thus don't claim Link Down.
-	//   Since user knows he's changed AP channel, he'll re-connect again. By skipping the following
-	//   checking, we'll disassociate then re-do normal association with this AP at the new channel.
-	// 2003-1-6 Re-enable this feature based on microsoft requirement which prefer not to re-do
-	//   connection when setting the same BSSID.
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) &&
-		MAC_ADDR_EQUAL(pAd->CommonCfg.Bssid, pOidBssid))
-	{
-		// already connected to the same BSSID, go back to idle state directly
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - already in this BSSID. ignore this SET_BSSID request\n"));
-		pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-            {
-                union iwreq_data    wrqu;
-
-                memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                memcpy(wrqu.ap_addr.sa_data, pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
-                wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-	}
-	else
-	{
-		if (INFRA_ON(pAd))
-		{
-			// disassoc from current AP first
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - disassociate with current AP ...\n"));
-			DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-			MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
-						sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
-		}
-		else
-		{
-			if (ADHOC_ON(pAd))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - drop current ADHOC\n"));
-				LinkDown(pAd, FALSE);
-				OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-				pAd->IndicateMediaState = NdisMediaStateDisconnected;
-				RTMP_IndicateMediaState(pAd);
-                pAd->ExtraInfo = GENERAL_LINK_DOWN;
-				DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event C!\n"));
-			}
-
-			// Change the wepstatus to original wepstatus
-			pAd->StaCfg.WepStatus   = pAd->StaCfg.OrigWepStatus;
-			pAd->StaCfg.PairCipher  = pAd->StaCfg.OrigWepStatus;
-			pAd->StaCfg.GroupCipher = pAd->StaCfg.OrigWepStatus;
-
-			// Check cipher suite, AP must have more secured cipher than station setting
-			// Set the Pairwise and Group cipher to match the intended AP setting
-			// We can only connect to AP with less secured cipher setting
-			if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-			{
-				pAd->StaCfg.GroupCipher = pAd->ScanTab.BssEntry[BssIdx].WPA.GroupCipher;
-
-				if (pAd->StaCfg.WepStatus == pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipher)
-					pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipher;
-				else if (pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipherAux != Ndis802_11WEPDisabled)
-					pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipherAux;
-				else	// There is no PairCipher Aux, downgrade our capability to TKIP
-					pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-			}
-			else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-			{
-				pAd->StaCfg.GroupCipher = pAd->ScanTab.BssEntry[BssIdx].WPA2.GroupCipher;
-
-				if (pAd->StaCfg.WepStatus == pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipher)
-					pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipher;
-				else if (pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipherAux != Ndis802_11WEPDisabled)
-					pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipherAux;
-				else	// There is no PairCipher Aux, downgrade our capability to TKIP
-					pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-
-				// RSN capability
-				pAd->StaCfg.RsnCapability = pAd->ScanTab.BssEntry[BssIdx].WPA2.RsnCapability;
-			}
-
-			// Set Mix cipher flag
-			pAd->StaCfg.bMixCipher = (pAd->StaCfg.PairCipher == pAd->StaCfg.GroupCipher) ? FALSE : TRUE;
-			if (pAd->StaCfg.bMixCipher == TRUE)
-			{
-				// If mix cipher, re-build RSNIE
-				RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, 0);
-			}
-			// No active association, join the BSS immediately
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - joining %02x:%02x:%02x:%02x:%02x:%02x ...\n",
-				pOidBssid[0],pOidBssid[1],pOidBssid[2],pOidBssid[3],pOidBssid[4],pOidBssid[5]));
-
-			JoinParmFill(pAd, &JoinReq, pAd->MlmeAux.BssIdx);
-			MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_JOIN_REQ, sizeof(MLME_JOIN_REQ_STRUCT), &JoinReq);
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_JOIN;
-		}
-	}
-}
-
-// Roaming is the only external request triggering CNTL state machine
-// despite of other "SET OID" operation. All "SET OID" related oerations
-// happen in sequence, because no other SET OID will be sent to this device
-// until the the previous SET operation is complete (successful o failed).
-// So, how do we quarantee this ROAMING request won't corrupt other "SET OID"?
-// or been corrupted by other "SET OID"?
-//
-// IRQL = DISPATCH_LEVEL
-VOID CntlMlmeRoamingProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	// TODO:
-	// AP in different channel may show lower RSSI than actual value??
-	// should we add a weighting factor to compensate it?
-	DBGPRINT(RT_DEBUG_TRACE,("CNTL - Roaming in MlmeAux.RoamTab...\n"));
-
-	NdisMoveMemory(&pAd->MlmeAux.SsidBssTab, &pAd->MlmeAux.RoamTab, sizeof(pAd->MlmeAux.RoamTab));
-	pAd->MlmeAux.SsidBssTab.BssNr = pAd->MlmeAux.RoamTab.BssNr;
-
-	BssTableSortByRssi(&pAd->MlmeAux.SsidBssTab);
-	pAd->MlmeAux.BssIdx = 0;
-	IterateOnBssTab(pAd);
-}
-
-#ifdef QOS_DLS_SUPPORT
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlOidDLSSetupProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PRT_802_11_DLS		pDLS = (PRT_802_11_DLS)Elem->Msg;
-	MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-	INT					i;
-	USHORT				reason = REASON_UNSPECIFY;
-
-	DBGPRINT(RT_DEBUG_TRACE,("CNTL - (OID set %02x:%02x:%02x:%02x:%02x:%02x with Valid=%d, Status=%d, TimeOut=%d, CountDownTimer=%d)\n",
-		pDLS->MacAddr[0], pDLS->MacAddr[1], pDLS->MacAddr[2], pDLS->MacAddr[3], pDLS->MacAddr[4], pDLS->MacAddr[5],
-		pDLS->Valid, pDLS->Status, pDLS->TimeOut, pDLS->CountDownTimer));
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return;
-
-	// DLS will not be supported when Adhoc mode
-	if (INFRA_ON(pAd))
-	{
-		for (i = 0; i < MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				(pDLS->TimeOut == pAd->StaCfg.DLSEntry[i].TimeOut) && MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 1. Same setting, just drop it
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - setting unchanged\n"));
-				break;
-			}
-			else if (!pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 2. Disable DLS link case, just tear down DLS link
-				reason = REASON_QOS_UNWANTED_MECHANISM;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - start tear down procedure\n"));
-				break;
-			}
-			else if ((i < MAX_NUM_OF_DLS_ENTRY) && pDLS->Valid && !pAd->StaCfg.DLSEntry[i].Valid)
-			{
-				// 3. Enable case, start DLS setup procedure
-				NdisMoveMemory(&pAd->StaCfg.DLSEntry[i], pDLS, sizeof(RT_802_11_DLS_UI));
-
-				//Update countdown timer
-				pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS setup case\n"));
-				break;
-			}
-			else if ((i < MAX_NUM_OF_DLS_ENTRY) && pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
-				(pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) && !MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 4. update mac case, tear down old DLS and setup new DLS
-				reason = REASON_QOS_UNWANTED_MECHANISM;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				NdisMoveMemory(&pAd->StaCfg.DLSEntry[i], pDLS, sizeof(RT_802_11_DLS_UI));
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS tear down and restart case\n"));
-				break;
-			}
-			else if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
-				MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr) && (pAd->StaCfg.DLSEntry[i].TimeOut != pDLS->TimeOut))
-			{
-				// 5. update timeout case, start DLS setup procedure (no tear down)
-				pAd->StaCfg.DLSEntry[i].TimeOut	= pDLS->TimeOut;
-				//Update countdown timer
-				pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS update timeout case\n"));
-				break;
-			}
-			else if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
-				(pAd->StaCfg.DLSEntry[i].Status != DLS_FINISH) && MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 6. re-setup case, start DLS setup procedure (no tear down)
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS retry setup procedure\n"));
-				break;
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN,("CNTL - DLS not changed in entry - %d - Valid=%d, Status=%d, TimeOut=%d\n",
-					i, pAd->StaCfg.DLSEntry[i].Valid, pAd->StaCfg.DLSEntry[i].Status, pAd->StaCfg.DLSEntry[i].TimeOut));
-			}
-		}
-	}
-}
-#endif // QOS_DLS_SUPPORT //
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitDisassocProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	MLME_START_REQ_STRUCT     StartReq;
-
-	if (Elem->MsgType == MT2_DISASSOC_CONF)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Dis-associate successful\n"));
-
-	    if (pAd->CommonCfg.bWirelessEvent)
-		{
-			RTMPSendWirelessEvent(pAd, IW_DISASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-		}
-
-		LinkDown(pAd, FALSE);
-
-		// case 1. no matching BSS, and user wants ADHOC, so we just start a new one
-		if ((pAd->MlmeAux.SsidBssTab.BssNr==0) && (pAd->StaCfg.BssType == BSS_ADHOC))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - No matching BSS, start a new ADHOC (Ssid=%s)...\n",pAd->MlmeAux.Ssid));
-			StartParmFill(pAd, &StartReq, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-			MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_START_REQ, sizeof(MLME_START_REQ_STRUCT), &StartReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_START;
-		}
-		// case 2. try each matched BSS
-		else
-		{
-			pAd->MlmeAux.BssIdx = 0;
-
-			IterateOnBssTab(pAd);
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitJoinProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT                      Reason;
-	MLME_AUTH_REQ_STRUCT        AuthReq;
-
-	if (Elem->MsgType == MT2_JOIN_CONF)
-	{
-		NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
-		if (Reason == MLME_SUCCESS)
-		{
-			// 1. joined an IBSS, we are pretty much done here
-			if (pAd->MlmeAux.BssType == BSS_ADHOC)
-			{
-			    //
-				// 5G bands rules of Japan:
-				// Ad hoc must be disabled in W53(ch52,56,60,64) channels.
-				//
-				if ( (pAd->CommonCfg.bIEEE80211H == 1) &&
-                      RadarChannelCheck(pAd, pAd->CommonCfg.Channel)
-				   )
-				{
-					pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-					DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Channel=%d, Join adhoc on W53(52,56,60,64) Channels are not accepted\n", pAd->CommonCfg.Channel));
-					return;
-				}
-
-				LinkUp(pAd, BSS_ADHOC);
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - join the IBSS = %02x:%02x:%02x:%02x:%02x:%02x ...\n",
-				pAd->CommonCfg.Bssid[0],pAd->CommonCfg.Bssid[1],pAd->CommonCfg.Bssid[2],
-				pAd->CommonCfg.Bssid[3],pAd->CommonCfg.Bssid[4],pAd->CommonCfg.Bssid[5]));
-
-                pAd->IndicateMediaState = NdisMediaStateConnected;
-                pAd->ExtraInfo = GENERAL_LINK_UP;
-			}
-			// 2. joined a new INFRA network, start from authentication
-			else
-			{
-#ifdef LEAP_SUPPORT
-				// Add AuthMode "LEAP" for CCX 1.X
-				if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-				{
-					AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, CISCO_AuthModeLEAP);
-				}
-				else
-#endif // LEAP_SUPPORT //
-				{
-					// either Ndis802_11AuthModeShared or Ndis802_11AuthModeAutoSwitch, try shared key first
-					if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeShared) ||
-						(pAd->StaCfg.AuthMode == Ndis802_11AuthModeAutoSwitch))
-					{
-						AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeShared);
-					}
-					else
-					{
-						AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeOpen);
-					}
-				}
-				MlmeEnqueue(pAd, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
-							sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
-
-				pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH;
-			}
-		}
-		else
-		{
-			// 3. failed, try next BSS
-			pAd->MlmeAux.BssIdx++;
-			IterateOnBssTab(pAd);
-		}
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitStartProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT      Result;
-
-	if (Elem->MsgType == MT2_START_CONF)
-	{
-		NdisMoveMemory(&Result, Elem->Msg, sizeof(USHORT));
-		if (Result == MLME_SUCCESS)
-		{
-		    //
-			// 5G bands rules of Japan:
-			// Ad hoc must be disabled in W53(ch52,56,60,64) channels.
-			//
-			if ( (pAd->CommonCfg.bIEEE80211H == 1) &&
-                  RadarChannelCheck(pAd, pAd->CommonCfg.Channel)
-			   )
-			{
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Channel=%d, Start adhoc on W53(52,56,60,64) Channels are not accepted\n", pAd->CommonCfg.Channel));
-				return;
-			}
-#ifdef DOT11_N_SUPPORT
-			if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-			{
-				N_ChannelCheck(pAd);
-				SetCommonHT(pAd);
-				NdisMoveMemory(&pAd->MlmeAux.AddHtInfo, &pAd->CommonCfg.AddHTInfo, sizeof(ADD_HT_INFO_IE));
-				RTMPCheckHt(pAd, BSSID_WCID, &pAd->CommonCfg.HtCapability, &pAd->CommonCfg.AddHTInfo);
-				pAd->StaActive.SupportedPhyInfo.bHtEnable = TRUE;
-				NdisZeroMemory(&pAd->StaActive.SupportedPhyInfo.MCSSet[0], 16);
-				NdisMoveMemory(&pAd->StaActive.SupportedPhyInfo.MCSSet[0], &pAd->CommonCfg.HtCapability.MCSSet[0], 16);
-				COPY_HTSETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(pAd);
-
-				if ((pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth  == BW_40) &&
-					(pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_ABOVE))
-				{
-					pAd->MlmeAux.CentralChannel = pAd->CommonCfg.Channel + 2;
-				}
-				else if ((pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth  == BW_40) &&
-						 (pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_BELOW))
-				{
-					pAd->MlmeAux.CentralChannel = pAd->CommonCfg.Channel - 2;
-				}
-			}
-			else
-#endif // DOT11_N_SUPPORT //
-			{
-				pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
-			}
-			LinkUp(pAd, BSS_ADHOC);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-			// Before send beacon, driver need do radar detection
-			if ((pAd->CommonCfg.Channel > 14 )
-				&& (pAd->CommonCfg.bIEEE80211H == 1)
-				&& RadarChannelCheck(pAd, pAd->CommonCfg.Channel))
-			{
-				pAd->CommonCfg.RadarDetect.RDMode = RD_SILENCE_MODE;
-				pAd->CommonCfg.RadarDetect.RDCount = 0;
-#ifdef DFS_SUPPORT
-				BbpRadarDetectionStart(pAd);
-#endif // DFS_SUPPORT //
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - start a new IBSS = %02x:%02x:%02x:%02x:%02x:%02x ...\n",
-				pAd->CommonCfg.Bssid[0],pAd->CommonCfg.Bssid[1],pAd->CommonCfg.Bssid[2],
-				pAd->CommonCfg.Bssid[3],pAd->CommonCfg.Bssid[4],pAd->CommonCfg.Bssid[5]));
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Start IBSS fail. BUG!!!!!\n"));
-			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitAuthProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT                       Reason;
-	MLME_ASSOC_REQ_STRUCT        AssocReq;
-	MLME_AUTH_REQ_STRUCT         AuthReq;
-
-	if (Elem->MsgType == MT2_AUTH_CONF)
-	{
-		NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
-		if (Reason == MLME_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH OK\n"));
-			AssocParmFill(pAd, &AssocReq, pAd->MlmeAux.Bssid, pAd->MlmeAux.CapabilityInfo,
-						  ASSOC_TIMEOUT, pAd->StaCfg.DefaultListenCount);
-
-#ifdef LEAP_SUPPORT
-			//
-			// Cisco Leap CCKM supported Re-association.
-			//
-			if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-			{
-				//if CCKM is turn on , that's mean Fast Reauthentication
-				//Use CCKM Reassociation instead of normal association for Fast Roaming.
-				MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_REASSOC_REQ,
-							sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
-
-				pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_REASSOC;
-			}
-			else
-#endif // LEAP_SUPPORT //
-			{
-				MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_ASSOC_REQ,
-							sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
-
-				pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_ASSOC;
-			}
-		}
-		else
-		{
-			// This fail may because of the AP already keep us in its MAC table without
-			// ageing-out. The previous authentication attempt must have let it remove us.
-			// so try Authentication again may help. For D-Link DWL-900AP+ compatibility.
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH FAIL, try again...\n"));
-#ifdef LEAP_SUPPORT
-			//Add AuthMode "LEAP" for CCX 1.X
-			if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-			{
-				AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, CISCO_AuthModeLEAP);
-			}
-			else
-#endif // LEAP_SUPPORT //
-			{
-				if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeShared) ||
-					(pAd->StaCfg.AuthMode == Ndis802_11AuthModeAutoSwitch))
-				{
-					// either Ndis802_11AuthModeShared or Ndis802_11AuthModeAutoSwitch, try shared key first
-					AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeShared);
-				}
-				else
-				{
-					AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeOpen);
-				}
-			}
-			MlmeEnqueue(pAd, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
-						sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH2;
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitAuthProc2(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT                       Reason;
-	MLME_ASSOC_REQ_STRUCT        AssocReq;
-	MLME_AUTH_REQ_STRUCT         AuthReq;
-
-	if (Elem->MsgType == MT2_AUTH_CONF)
-	{
-		NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
-		if (Reason == MLME_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH OK\n"));
-			AssocParmFill(pAd, &AssocReq, pAd->MlmeAux.Bssid, pAd->MlmeAux.CapabilityInfo,
-						  ASSOC_TIMEOUT, pAd->StaCfg.DefaultListenCount);
-			MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_ASSOC_REQ,
-						sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_ASSOC;
-		}
-		else
-		{
-#ifdef LEAP_SUPPORT
-			// Process LEAP first, since it use different control variable
-			// We don't want to affect other poven operation
-			if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-			{
-				// LEAP Auth not success, try next BSS
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - *LEAP* AUTH FAIL, give up; try next BSS\n"));
-				DBGPRINT(RT_DEBUG_TRACE, ("Total match BSSID [=%d]\n", pAd->MlmeAux.SsidBssTab.BssNr));
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-				pAd->MlmeAux.BssIdx++;
-				IterateOnBssTab(pAd);
-			}
-			else
-#endif // LEAP_SUPPORT //
-			if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeAutoSwitch) &&
-				 (pAd->MlmeAux.Alg == Ndis802_11AuthModeShared))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH FAIL, try OPEN system...\n"));
-				AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeOpen);
-				MlmeEnqueue(pAd, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
-							sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
-
-				pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH2;
-			}
-			else
-			{
-				// not success, try next BSS
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH FAIL, give up; try next BSS\n"));
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE; //???????
-				pAd->MlmeAux.BssIdx++;
-				IterateOnBssTab(pAd);
-			}
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitAssocProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT      Reason;
-
-	if (Elem->MsgType == MT2_ASSOC_CONF)
-	{
-		NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
-		if (Reason == MLME_SUCCESS)
-		{
-			LinkUp(pAd, BSS_INFRA);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Association successful on BSS #%ld\n",pAd->MlmeAux.BssIdx));
-
-			if (pAd->CommonCfg.bWirelessEvent)
-			{
-				RTMPSendWirelessEvent(pAd, IW_ASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-			}
-		}
-		else
-		{
-			// not success, try next BSS
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Association fails on BSS #%ld\n",pAd->MlmeAux.BssIdx));
-			pAd->MlmeAux.BssIdx++;
-			IterateOnBssTab(pAd);
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitReassocProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT      Result;
-
-	if (Elem->MsgType == MT2_REASSOC_CONF)
-	{
-		NdisMoveMemory(&Result, Elem->Msg, sizeof(USHORT));
-		if (Result == MLME_SUCCESS)
-		{
-			//
-			// NDIS requires a new Link UP indication but no Link Down for RE-ASSOC
-			//
-			LinkUp(pAd, BSS_INFRA);
-
-			// send wireless event - for association
-			if (pAd->CommonCfg.bWirelessEvent)
-				RTMPSendWirelessEvent(pAd, IW_ASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-
-
-#ifdef LEAP_SUPPORT
-			if (LEAP_CCKM_ON(pAd))
-			{
-				STA_PORT_SECURED(pAd);
-				pAd->StaCfg.WpaState = SS_FINISH;
-			}
-#endif // LEAP_SUPPORT //
-			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Re-assocition successful on BSS #%ld\n", pAd->MlmeAux.RoamIdx));
-		}
-		else
-		{
-			// reassoc failed, try to pick next BSS in the BSS Table
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Re-assocition fails on BSS #%ld\n", pAd->MlmeAux.RoamIdx));
-			pAd->MlmeAux.RoamIdx++;
-			IterateOnBssTab2(pAd);
-		}
-	}
-}
-
-
-VOID	AdhocTurnOnQos(
-	IN  PRTMP_ADAPTER pAd)
-{
-#define AC0_DEF_TXOP		0
-#define AC1_DEF_TXOP		0
-#define AC2_DEF_TXOP		94
-#define AC3_DEF_TXOP		47
-
-	// Turn on QOs if use HT rate.
-	if (pAd->CommonCfg.APEdcaParm.bValid == FALSE)
-	{
-		pAd->CommonCfg.APEdcaParm.bValid = TRUE;
-		pAd->CommonCfg.APEdcaParm.Aifsn[0] = 3;
-		pAd->CommonCfg.APEdcaParm.Aifsn[1] = 7;
-		pAd->CommonCfg.APEdcaParm.Aifsn[2] = 1;
-		pAd->CommonCfg.APEdcaParm.Aifsn[3] = 1;
-
-		pAd->CommonCfg.APEdcaParm.Cwmin[0] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmin[1] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmin[2] = 3;
-		pAd->CommonCfg.APEdcaParm.Cwmin[3] = 2;
-
-		pAd->CommonCfg.APEdcaParm.Cwmax[0] = 10;
-		pAd->CommonCfg.APEdcaParm.Cwmax[1] = 6;
-		pAd->CommonCfg.APEdcaParm.Cwmax[2] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmax[3] = 3;
-
-		pAd->CommonCfg.APEdcaParm.Txop[0]  = 0;
-		pAd->CommonCfg.APEdcaParm.Txop[1]  = 0;
-		pAd->CommonCfg.APEdcaParm.Txop[2]  = AC2_DEF_TXOP;
-		pAd->CommonCfg.APEdcaParm.Txop[3]  = AC3_DEF_TXOP;
-	}
-	AsicSetEdcaParm(pAd, &pAd->CommonCfg.APEdcaParm);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID LinkUp(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR BssType)
-{
-	ULONG	Now;
-	UINT32	Data;
-	BOOLEAN	Cancelled;
-	UCHAR	Value = 0, idx;
-	MAC_TABLE_ENTRY *pEntry = NULL, *pCurrEntry;
-
-	pEntry = &pAd->MacTab.Content[BSSID_WCID];
-
-	//
-	// ASSOC - DisassocTimeoutAction
-	// CNTL - Dis-associate successful
-	// !!! LINK DOWN !!!
-	// [88888] OID_802_11_SSID should have returned NDTEST_WEP_AP2(Returned: )
-	//
-	// To prevent DisassocTimeoutAction to call Link down after we link up,
-	// cancel the DisassocTimer no matter what it start or not.
-	//
-	RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer,  &Cancelled);
-
-	COPY_SETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(pAd);
-
-#ifdef DOT11_N_SUPPORT
-	COPY_HTSETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(pAd);
-#endif // DOT11_N_SUPPORT //
-	// It's quite difficult to tell if a newly added KEY is WEP or CKIP until a new BSS
-	// is formed (either ASSOC/RE-ASSOC done or IBSS started. LinkUP should be a safe place
-	// to examine if cipher algorithm switching is required.
-	//rt2860b. Don't know why need this
-	SwitchBetweenWepAndCkip(pAd);
-
-
-	if (BssType == BSS_ADHOC)
-	{
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_ADHOC_ON);
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_INFRA_ON);
-
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-		// No carrier detection when adhoc
-		// CarrierDetectionStop(pAd);
-		pAd->CommonCfg.CarrierDetect.CD_State = CD_NORMAL;
-#endif // CARRIER_DETECTION_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-		if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-			AdhocTurnOnQos(pAd);
-#endif // DOT11_N_SUPPORT //
-
-		DBGPRINT(RT_DEBUG_TRACE, ("!!!Adhoc LINK UP !!! \n" ));
-	}
-	else
-	{
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_INFRA_ON);
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_ADHOC_ON);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("!!!Infra LINK UP !!! \n" ));
-	}
-
-	// 3*3
-	// reset Tx beamforming bit
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
-	Value &= (~0x01);
-	Value |= pAd->CommonCfg.RegTransmitSetting.field.TxBF;
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
-
-#ifdef DOT11_N_SUPPORT
-	// Change to AP channel
-    if ((pAd->CommonCfg.CentralChannel > pAd->CommonCfg.Channel) && (pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth == BW_40))
-	{
-		// Must using 40MHz.
-		pAd->CommonCfg.BBPCurrentBW = BW_40;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
-		Value &= (~0x18);
-		Value |= 0x10;
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
-
-		//  RX : control channel at lower
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
-		Value &= (~0x20);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
-
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Data);
-		Data &= 0xfffffffe;
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Data);
-
-		if (pAd->MACVersion == 0x28600100)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x1A);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0A);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x16);
-            DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("!!!40MHz Lower LINK UP !!! Control Channel at Below. Central = %d \n", pAd->CommonCfg.CentralChannel ));
-	}
-	else if ((pAd->CommonCfg.CentralChannel < pAd->CommonCfg.Channel) && (pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth == BW_40))
-    {
-	    // Must using 40MHz.
-		pAd->CommonCfg.BBPCurrentBW = BW_40;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-	    AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
-		Value &= (~0x18);
-		Value |= 0x10;
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
-
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Data);
-		Data |= 0x1;
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Data);
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
-	    Value |= (0x20);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
-
-		if (pAd->MACVersion == 0x28600100)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x1A);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0A);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x16);
-			    DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
-		}
-
-	    DBGPRINT(RT_DEBUG_TRACE, ("!!! 40MHz Upper LINK UP !!! Control Channel at UpperCentral = %d \n", pAd->CommonCfg.CentralChannel ));
-    }
-    else
-#endif // DOT11_N_SUPPORT //
-    {
-	    pAd->CommonCfg.BBPCurrentBW = BW_20;
-		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
-		Value &= (~0x18);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
-
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Data);
-		Data &= 0xfffffffe;
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Data);
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
-		Value &= (~0x20);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
-
-		if (pAd->MACVersion == 0x28600100)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x16);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x08);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x11);
-            DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
-		}
-
-	    DBGPRINT(RT_DEBUG_TRACE, ("!!! 20MHz LINK UP !!! \n" ));
-    }
-
-	RTMPSetAGCInitValue(pAd, pAd->CommonCfg.BBPCurrentBW);
-	//
-	// Save BBP_R66 value, it will be used in RTUSBResumeMsduTransmission
-	//
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &pAd->BbpTuning.R66CurrentValue);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !!! (BssType=%d, AID=%d, ssid=%s, Channel=%d, CentralChannel = %d)\n",
-		BssType, pAd->StaActive.Aid, pAd->CommonCfg.Ssid, pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel));
-
-#ifdef DOT11_N_SUPPORT
-	DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !!! (Density =%d, )\n", pAd->MacTab.Content[BSSID_WCID].MpduDensity));
-#endif // DOT11_N_SUPPORT //
-
-		AsicSetBssid(pAd, pAd->CommonCfg.Bssid);
-
-	AsicSetSlotTime(pAd, TRUE);
-	AsicSetEdcaParm(pAd, &pAd->CommonCfg.APEdcaParm);
-
-	// Call this for RTS protectionfor legacy rate, we will always enable RTS threshold, but normally it will not hit
-	AsicUpdateProtect(pAd, 0, (OFDMSETPROTECT | CCKSETPROTECT), TRUE, FALSE);
-
-#ifdef DOT11_N_SUPPORT
-	if ((pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE))
-	{
-		// Update HT protectionfor based on AP's operating mode.
-    	if (pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1)
-    	{
-    		AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode,  ALLN_SETPROTECT, FALSE, TRUE);
-    	}
-    	else
-   			AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode,  ALLN_SETPROTECT, FALSE, FALSE);
-	}
-#endif // DOT11_N_SUPPORT //
-
-	NdisZeroMemory(&pAd->DrsCounters, sizeof(COUNTER_DRS));
-
-	NdisGetSystemUpTime(&Now);
-	pAd->StaCfg.LastBeaconRxTime = Now;   // last RX timestamp
-
-	if ((pAd->CommonCfg.TxPreamble != Rt802_11PreambleLong) &&
-		CAP_IS_SHORT_PREAMBLE_ON(pAd->StaActive.CapabilityInfo))
-	{
-		MlmeSetTxPreamble(pAd, Rt802_11PreambleShort);
-	}
-
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
-
-	if (pAd->CommonCfg.RadarDetect.RDMode == RD_SILENCE_MODE)
-	{
-#ifdef DFS_SUPPORT
-		RadarDetectionStop(pAd);
-#endif // DFS_SUPPORT //
-	}
-	pAd->CommonCfg.RadarDetect.RDMode = RD_NORMAL_MODE;
-
-	if (BssType == BSS_ADHOC)
-	{
-		MakeIbssBeacon(pAd);
-		if ((pAd->CommonCfg.Channel > 14)
-			&& (pAd->CommonCfg.bIEEE80211H == 1)
-			&& RadarChannelCheck(pAd, pAd->CommonCfg.Channel))
-		{
-			; //Do nothing
-		}
-		else
-		{
-			AsicEnableIbssSync(pAd);
-		}
-
-		// In ad hoc mode, use MAC table from index 1.
-		// p.s ASIC use all 0xff as termination of WCID table search.To prevent it's 0xff-ff-ff-ff-ff-ff, Write 0 here.
-		RTMP_IO_WRITE32(pAd, MAC_WCID_BASE, 0x00);
-		RTMP_IO_WRITE32(pAd, 0x1808, 0x00);
-
-		// If WEP is enabled, add key material and cipherAlg into Asic
-		// Fill in Shared Key Table(offset: 0x6c00) and Shared Key Mode(offset: 0x7000)
-
-		if (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)
-		{
-			PUCHAR	Key;
-			UCHAR 	CipherAlg;
-
-			for (idx=0; idx < SHARE_KEY_NUM; idx++)
-        	{
-				CipherAlg = pAd->SharedKey[BSS0][idx].CipherAlg;
-    			Key = pAd->SharedKey[BSS0][idx].Key;
-
-				if (pAd->SharedKey[BSS0][idx].KeyLen > 0)
-				{
-					// Set key material and cipherAlg to Asic
-    				AsicAddSharedKeyEntry(pAd, BSS0, idx, CipherAlg, Key, NULL, NULL);
-
-                    if (idx == pAd->StaCfg.DefaultKeyId)
-					{
-						// Update WCID attribute table and IVEIV table for this group key table
-						RTMPAddWcidAttributeEntry(pAd, BSS0, idx, CipherAlg, NULL);
-					}
-				}
-
-
-			}
-		}
-		// If WPANone is enabled, add key material and cipherAlg into Asic
-		// Fill in Shared Key Table(offset: 0x6c00) and Shared Key Mode(offset: 0x7000)
-		else if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-		{
-			pAd->StaCfg.DefaultKeyId = 0;	// always be zero
-
-            NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-							pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-			NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, pAd->StaCfg.PMK, LEN_TKIP_EK);
-
-            if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-            {
-    			NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, &pAd->StaCfg.PMK[16], LEN_TKIP_RXMICK);
-    			NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, &pAd->StaCfg.PMK[16], LEN_TKIP_TXMICK);
-            }
-
-			// Decide its ChiperAlg
-			if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-				pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-			else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-				pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-			else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Unknow Cipher (=%d), set Cipher to AES\n", pAd->StaCfg.PairCipher));
-				pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-            }
-
-			// Set key material and cipherAlg to Asic
-			AsicAddSharedKeyEntry(pAd,
-								  BSS0,
-								  0,
-								  pAd->SharedKey[BSS0][0].CipherAlg,
-								  pAd->SharedKey[BSS0][0].Key,
-								  pAd->SharedKey[BSS0][0].TxMic,
-								  pAd->SharedKey[BSS0][0].RxMic);
-
-            // Update WCID attribute table and IVEIV table for this group key table
-			RTMPAddWcidAttributeEntry(pAd, BSS0, 0, pAd->SharedKey[BSS0][0].CipherAlg, NULL);
-
-		}
-
-	}
-	else // BSS_INFRA
-	{
-		// Check the new SSID with last SSID
-		while (Cancelled == TRUE)
-		{
-			if (pAd->CommonCfg.LastSsidLen == pAd->CommonCfg.SsidLen)
-			{
-				if (RTMPCompareMemory(pAd->CommonCfg.LastSsid, pAd->CommonCfg.Ssid, pAd->CommonCfg.LastSsidLen) == 0)
-				{
-					// Link to the old one no linkdown is required.
-					break;
-				}
-			}
-			// Send link down event before set to link up
-			pAd->IndicateMediaState = NdisMediaStateDisconnected;
-			RTMP_IndicateMediaState(pAd);
-            pAd->ExtraInfo = GENERAL_LINK_DOWN;
-			DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event AA!\n"));
-			break;
-		}
-
-		//
-		// On WPA mode, Remove All Keys if not connect to the last BSSID
-		// Key will be set after 4-way handshake.
-		//
-		if ((pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA))
-		{
-			ULONG 		IV;
-
-			// Remove all WPA keys
-			RTMPWPARemoveAllKeys(pAd);
-			pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilter8021xWEP;
-
-			// Fixed connection failed with Range Maximizer - 515 AP (Marvell Chip) when security is WPAPSK/TKIP
-			// If IV related values are too large in GroupMsg2, AP would ignore this message.
-			IV = 0;
-			IV |= (pAd->StaCfg.DefaultKeyId << 30);
-			AsicUpdateWCIDIVEIV(pAd, BSSID_WCID, IV, 0);
-		}
-		// NOTE:
-		// the decision of using "short slot time" or not may change dynamically due to
-		// new STA association to the AP. so we have to decide that upon parsing BEACON, not here
-
-		// NOTE:
-		// the decision to use "RTC/CTS" or "CTS-to-self" protection or not may change dynamically
-		// due to new STA association to the AP. so we have to decide that upon parsing BEACON, not here
-
-		ComposePsPoll(pAd);
-		ComposeNullFrame(pAd);
-
-			AsicEnableBssSync(pAd);
-
-		// Add BSSID to WCID search table
-		AsicUpdateRxWCIDTable(pAd, BSSID_WCID, pAd->CommonCfg.Bssid);
-
-		NdisAcquireSpinLock(&pAd->MacTabLock);
-		// add this BSSID entry into HASH table
-		{
-			UCHAR HashIdx;
-
-			//pEntry = &pAd->MacTab.Content[BSSID_WCID];
-			HashIdx = MAC_ADDR_HASH_INDEX(pAd->CommonCfg.Bssid);
-			if (pAd->MacTab.Hash[HashIdx] == NULL)
-			{
-				pAd->MacTab.Hash[HashIdx] = pEntry;
-			}
-			else
-			{
-				pCurrEntry = pAd->MacTab.Hash[HashIdx];
-				while (pCurrEntry->pNext != NULL)
-					pCurrEntry = pCurrEntry->pNext;
-				pCurrEntry->pNext = pEntry;
-			}
-		}
-		NdisReleaseSpinLock(&pAd->MacTabLock);
-
-
-		// If WEP is enabled, add paiewise and shared key
-#ifdef WPA_SUPPLICANT_SUPPORT
-        if (((pAd->StaCfg.WpaSupplicantUP)&&
-             (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)&&
-             (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED)) ||
-            ((pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_DISABLE)&&
-              (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)))
-#else
-		if (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)
-#endif // WPA_SUPPLICANT_SUPPORT //
-		{
-			PUCHAR	Key;
-			UCHAR 	CipherAlg;
-
-			for (idx=0; idx < SHARE_KEY_NUM; idx++)
-        	{
-				CipherAlg = pAd->SharedKey[BSS0][idx].CipherAlg;
-    			Key = pAd->SharedKey[BSS0][idx].Key;
-
-				if (pAd->SharedKey[BSS0][idx].KeyLen > 0)
-				{
-					// Set key material and cipherAlg to Asic
-    				AsicAddSharedKeyEntry(pAd, BSS0, idx, CipherAlg, Key, NULL, NULL);
-
-					if (idx == pAd->StaCfg.DefaultKeyId)
-					{
-						// Assign group key info
-						RTMPAddWcidAttributeEntry(pAd, BSS0, idx, CipherAlg, NULL);
-
-						// Assign pairwise key info
-						RTMPAddWcidAttributeEntry(pAd, BSS0, idx, CipherAlg, pEntry);
-					}
-				}
-			}
-		}
-
-		// only INFRASTRUCTURE mode need to indicate connectivity immediately; ADHOC mode
-		// should wait until at least 2 active nodes in this BSSID.
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-
-        // For GUI ++
-		if (pAd->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-		{
-			pAd->IndicateMediaState = NdisMediaStateConnected;
-			pAd->ExtraInfo = GENERAL_LINK_UP;
-			RTMP_IndicateMediaState(pAd);
-		}
-        // --
-
-		// Add BSSID in my MAC Table.
-        NdisAcquireSpinLock(&pAd->MacTabLock);
-		RTMPMoveMemory(pAd->MacTab.Content[BSSID_WCID].Addr, pAd->CommonCfg.Bssid, MAC_ADDR_LEN);
-		pAd->MacTab.Content[BSSID_WCID].Aid = BSSID_WCID;
-		pAd->MacTab.Content[BSSID_WCID].pAd = pAd;
-		pAd->MacTab.Content[BSSID_WCID].ValidAsCLI = TRUE;	//Although this is bssid..still set ValidAsCl
-		pAd->MacTab.Size = 1;	// infra mode always set MACtab size =1.
-		pAd->MacTab.Content[BSSID_WCID].Sst = SST_ASSOC;
-		pAd->MacTab.Content[BSSID_WCID].AuthState = SST_ASSOC;
-		pAd->MacTab.Content[BSSID_WCID].WepStatus = pAd->StaCfg.WepStatus;
-        NdisReleaseSpinLock(&pAd->MacTabLock);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !!!  ClientStatusFlags=%lx)\n",
-			pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
-
-		MlmeUpdateTxRates(pAd, TRUE, BSS0);
-#ifdef DOT11_N_SUPPORT
-		MlmeUpdateHtTxRates(pAd, BSS0);
-		DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !! (StaActive.bHtEnable =%d, )\n", pAd->StaActive.SupportedPhyInfo.bHtEnable));
-#endif // DOT11_N_SUPPORT //
-
-		//
-		// Report Adjacent AP report.
-		//
-#ifdef LEAP_SUPPORT
-		CCXAdjacentAPReport(pAd);
-#endif // LEAP_SUPPORT //
-
-		if (pAd->CommonCfg.bAggregationCapable)
-		{
-			if ((pAd->CommonCfg.bPiggyBackCapable) && (pAd->MlmeAux.APRalinkIe & 0x00000003) == 3)
-			{
-
-				OPSTATUS_SET_FLAG(pAd, fOP_STATUS_PIGGYBACK_INUSED);
-				OPSTATUS_SET_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
-                RTMPSetPiggyBack(pAd, TRUE);
-				DBGPRINT(RT_DEBUG_TRACE, ("Turn on Piggy-Back\n"));
-			}
-			else if (pAd->MlmeAux.APRalinkIe & 0x00000001)
-			{
-				OPSTATUS_SET_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
-			}
-		}
-
-		if (pAd->MlmeAux.APRalinkIe != 0x0)
-		{
-#ifdef DOT11_N_SUPPORT
-			if (CLIENT_STATUS_TEST_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_RDG_CAPABLE))
-			{
-				AsicEnableRDG(pAd);
-			}
-#endif // DOT11_N_SUPPORT //
-			OPSTATUS_SET_FLAG(pAd, fCLIENT_STATUS_RALINK_CHIPSET);
-			CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_RALINK_CHIPSET);
-		}
-		else
-		{
-			OPSTATUS_CLEAR_FLAG(pAd, fCLIENT_STATUS_RALINK_CHIPSET);
-			CLIENT_STATUS_CLEAR_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_RALINK_CHIPSET);
-		}
-	}
-
-#ifdef DOT11_N_SUPPORT
-	DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_CONNECT Event B!.BACapability = %x. ClientStatusFlags = %lx\n", pAd->CommonCfg.BACapability.word, pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
-#endif // DOT11_N_SUPPORT //
-
-	// Set LED
-	RTMPSetLED(pAd, LED_LINK_UP);
-
-	pAd->Mlme.PeriodicRound = 0;
-	pAd->Mlme.OneSecPeriodicRound = 0;
-	pAd->bConfigChanged = FALSE;        // Reset config flag
-	pAd->ExtraInfo = GENERAL_LINK_UP;   // Update extra information to link is up
-
-	// Set asic auto fall back
-	{
-		PUCHAR					pTable;
-		UCHAR					TableSize = 0;
-
-		MlmeSelectTxRateTable(pAd, &pAd->MacTab.Content[BSSID_WCID], &pTable, &TableSize, &pAd->CommonCfg.TxRateIndex);
-		AsicUpdateAutoFallBackTable(pAd, pTable);
-	}
-
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-    pEntry->HTPhyMode.word = pAd->StaCfg.HTPhyMode.word;
-    pEntry->MaxHTPhyMode.word = pAd->StaCfg.HTPhyMode.word;
-	if (pAd->StaCfg.bAutoTxRateSwitch == FALSE)
-	{
-		pEntry->bAutoTxRateSwitch = FALSE;
-#ifdef DOT11_N_SUPPORT
-		if (pEntry->HTPhyMode.field.MCS == 32)
-			pEntry->HTPhyMode.field.ShortGI = GI_800;
-
-		if ((pEntry->HTPhyMode.field.MCS > MCS_7) || (pEntry->HTPhyMode.field.MCS == 32))
-			pEntry->HTPhyMode.field.STBC = STBC_NONE;
-#endif // DOT11_N_SUPPORT //
-		// If the legacy mode is set, overwrite the transmit setting of this entry.
-		if (pEntry->HTPhyMode.field.MODE <= MODE_OFDM)
-			RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-	}
-	else
-		pEntry->bAutoTxRateSwitch = TRUE;
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-
-	//  Let Link Status Page display first initial rate.
-	pAd->LastTxRate = (USHORT)(pEntry->HTPhyMode.word);
-	// Select DAC according to HT or Legacy
-	if (pAd->StaActive.SupportedPhyInfo.MCSSet[0] != 0x00)
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &Value);
-		Value &= (~0x18);
-		if (pAd->Antenna.field.TxPath == 2)
-		{
-		    Value |= 0x10;
-		}
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, Value);
-	}
-	else
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &Value);
-		Value &= (~0x18);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, Value);
-	}
-
-#ifdef DOT11_N_SUPPORT
-	if (pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE)
-	{
-	}
-	else if (pEntry->MaxRAmpduFactor == 0)
-	{
-	    // If HT AP doesn't support MaxRAmpduFactor = 1, we need to set max PSDU to 0.
-	    // Because our Init value is 1 at MACRegTable.
-		RTMP_IO_WRITE32(pAd, MAX_LEN_CFG, 0x0fff);
-	}
-#endif // DOT11_N_SUPPORT //
-
-	// Patch for Marvel AP to gain high throughput
-	// Need to set as following,
-	// 1. Set txop in register-EDCA_AC0_CFG as 0x60
-	// 2. Set EnTXWriteBackDDONE in register-WPDMA_GLO_CFG as zero
-	// 3. PBF_MAX_PCNT as 0x1F3FBF9F
-	// 4. kick per two packets when dequeue
-	//
-	// Txop can only be modified when RDG is off, WMM is disable and TxBurst is enable
-	//
-	// if 1. Legacy AP WMM on,  or 2. 11n AP, AMPDU disable.  Force turn off burst no matter what bEnableTxBurst is.
-#ifdef DOT11_N_SUPPORT
-	if (((pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE) && (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED)))
-		|| ((pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE) && (pAd->CommonCfg.BACapability.field.Policy == BA_NOTUSE)))
-	{
-		RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
-		Data  &= 0xFFFFFF00;
-		RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
-
-		RTMP_IO_WRITE32(pAd, PBF_MAX_PCNT, 0x1F3F7F9F);
-		DBGPRINT(RT_DEBUG_TRACE, ("Txburst 1\n"));
-	}
-	else
-#endif // DOT11_N_SUPPORT //
-	if (pAd->CommonCfg.bEnableTxBurst)
-	{
-		RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
-		Data  &= 0xFFFFFF00;
-		Data  |= 0x60;
-		RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
-		pAd->CommonCfg.IOTestParm.bNowAtherosBurstOn = TRUE;
-
-		RTMP_IO_WRITE32(pAd, PBF_MAX_PCNT, 0x1F3FBF9F);
-		DBGPRINT(RT_DEBUG_TRACE, ("Txburst 2\n"));
-	}
-	else
-	{
-		RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
-		Data  &= 0xFFFFFF00;
-		RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
-
-		RTMP_IO_WRITE32(pAd, PBF_MAX_PCNT, 0x1F3F7F9F);
-		DBGPRINT(RT_DEBUG_TRACE, ("Txburst 3\n"));
-	}
-
-#ifdef DOT11_N_SUPPORT
-	// Re-check to turn on TX burst or not.
-	if ((pAd->CommonCfg.IOTestParm.bLastAtheros == TRUE) && ((STA_WEP_ON(pAd))||(STA_TKIP_ON(pAd))))
-	{
-		pAd->CommonCfg.IOTestParm.bNextDisableRxBA = TRUE;
-		if (pAd->CommonCfg.bEnableTxBurst)
-		{
-		    UINT32 MACValue = 0;
-			// Force disable  TXOP value in this case. The same action in MLMEUpdateProtect too.
-			// I didn't change PBF_MAX_PCNT setting.
-			RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &MACValue);
-			MACValue  &= 0xFFFFFF00;
-			RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, MACValue);
-			pAd->CommonCfg.IOTestParm.bNowAtherosBurstOn = FALSE;
-		}
-	}
-	else
-	{
-		pAd->CommonCfg.IOTestParm.bNextDisableRxBA = FALSE;
-	}
-#endif // DOT11_N_SUPPORT //
-
-	pAd->CommonCfg.IOTestParm.bLastAtheros = FALSE;
-	COPY_MAC_ADDR(pAd->CommonCfg.LastBssid, pAd->CommonCfg.Bssid);
-	DBGPRINT(RT_DEBUG_TRACE, ("!!!pAd->bNextDisableRxBA= %d \n", pAd->CommonCfg.IOTestParm.bNextDisableRxBA));
-	// BSSID add in one MAC entry too.  Because in Tx, ASIC need to check Cipher and IV/EIV, BAbitmap
-	// Pther information in MACTab.Content[BSSID_WCID] is not necessary for driver.
-	// Note: As STA, The MACTab.Content[BSSID_WCID]. PairwiseKey and Shared Key for BSS0 are the same.
-
-    if (pAd->StaCfg.WepStatus <= Ndis802_11WEPDisabled)
-    {
-        pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-		pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilterAcceptAll;
-	}
-
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-	pEntry->PortSecured = pAd->StaCfg.PortSecured;
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-
-    //
-	// Patch Atheros AP TX will breakdown issue.
-	// AP Model: DLink DWL-8200AP
-	//
-	if (INFRA_ON(pAd) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) && STA_TKIP_ON(pAd))
-	{
-		RTMP_IO_WRITE32(pAd, RX_PARSER_CFG, 0x01);
-	}
-	else
-	{
-		RTMP_IO_WRITE32(pAd, RX_PARSER_CFG, 0x00);
-	}
-
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-
-
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	if ((pAd->CommonCfg.BACapability.field.b2040CoexistScanSup) && (pAd->CommonCfg.Channel <= 11))
-	{
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_SCAN_2040);
-		BuildEffectedChannelList(pAd);
-	}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-}
-
-/*
-	==========================================================================
-
-	Routine	Description:
-		Disconnect current BSSID
-
-	Arguments:
-		pAd				- Pointer to our adapter
-		IsReqFromAP		- Request from AP
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-		We need more information to know it's this requst from AP.
-		If yes! we need to do extra handling, for example, remove the WPA key.
-		Otherwise on 4-way handshaking will faied, since the WPA key didn't be
-		remove while auto reconnect.
-		Disconnect request from AP, it means we will start afresh 4-way handshaking
-		on WPA mode.
-
-	==========================================================================
-*/
-VOID LinkDown(
-	IN PRTMP_ADAPTER pAd,
-	IN  BOOLEAN      IsReqFromAP)
-{
-	UCHAR			    i, ByteValue = 0;
-
-	// Do nothing if monitor mode is on
-	if (MONITOR_ON(pAd))
-		return;
-
-#ifdef RALINK_ATE
-	// Nothing to do in ATE mode.
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-    if (pAd->CommonCfg.bWirelessEvent)
-	{
-		RTMPSendWirelessEvent(pAd, IW_STA_LINKDOWN_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN !!!\n"));
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
-
-	if (ADHOC_ON(pAd))		// Adhoc mode link down
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN 1!!!\n"));
-
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_ADHOC_ON);
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-		pAd->IndicateMediaState = NdisMediaStateDisconnected;
-		RTMP_IndicateMediaState(pAd);
-        pAd->ExtraInfo = GENERAL_LINK_DOWN;
-		BssTableDeleteEntry(&pAd->ScanTab, pAd->CommonCfg.Bssid, pAd->CommonCfg.Channel);
-		DBGPRINT(RT_DEBUG_TRACE, ("!!! MacTab.Size=%d !!!\n", pAd->MacTab.Size));
-	}
-	else					// Infra structure mode
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN 2!!!\n"));
-
-#ifdef QOS_DLS_SUPPORT
-		// DLS tear down frame must be sent before link down
-		// send DLS-TEAR_DOWN message
-		if (pAd->CommonCfg.bDLSCapable)
-		{
-			// tear down local dls table entry
-			for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-				{
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				}
-			}
-
-			// tear down peer dls table entry
-			for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status ==  DLS_FINISH))
-				{
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				}
-			}
-		}
-#endif // QOS_DLS_SUPPORT //
-
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_INFRA_ON);
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-
-		// Saved last SSID for linkup comparison
-		pAd->CommonCfg.LastSsidLen = pAd->CommonCfg.SsidLen;
-		NdisMoveMemory(pAd->CommonCfg.LastSsid, pAd->CommonCfg.Ssid, pAd->CommonCfg.LastSsidLen);
-		COPY_MAC_ADDR(pAd->CommonCfg.LastBssid, pAd->CommonCfg.Bssid);
-		if (pAd->MlmeAux.CurrReqIsFromNdis == TRUE)
-		{
-			pAd->IndicateMediaState = NdisMediaStateDisconnected;
-			RTMP_IndicateMediaState(pAd);
-            pAd->ExtraInfo = GENERAL_LINK_DOWN;
-			DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event A!\n"));
-			pAd->MlmeAux.CurrReqIsFromNdis = FALSE;
-		}
-		else
-		{
-            //
-			// If disassociation request is from NDIS, then we don't need to delete BSSID from entry.
-			// Otherwise lost beacon or receive De-Authentication from AP,
-			// then we should delete BSSID from BssTable.
-			// If we don't delete from entry, roaming will fail.
-			//
-			BssTableDeleteEntry(&pAd->ScanTab, pAd->CommonCfg.Bssid, pAd->CommonCfg.Channel);
-		}
-
-		// restore back to -
-		//      1. long slot (20 us) or short slot (9 us) time
-		//      2. turn on/off RTS/CTS and/or CTS-to-self protection
-		//      3. short preamble
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED);
-
-		if (pAd->StaCfg.CCXAdjacentAPReportFlag == TRUE)
-		{
-			//
-			// Record current AP's information.
-			// for later used reporting Adjacent AP report.
-			//
-			pAd->StaCfg.CCXAdjacentAPChannel = pAd->CommonCfg.Channel;
-			pAd->StaCfg.CCXAdjacentAPSsidLen = pAd->CommonCfg.SsidLen;
-			NdisMoveMemory(pAd->StaCfg.CCXAdjacentAPSsid, pAd->CommonCfg.Ssid, pAd->StaCfg.CCXAdjacentAPSsidLen);
-			COPY_MAC_ADDR(pAd->StaCfg.CCXAdjacentAPBssid, pAd->CommonCfg.Bssid);
-		}
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-		// Country IE of the AP will be evaluated and will be used.
-		if (pAd->StaCfg.IEEE80211dClientMode != Rt802_11_D_None)
-		{
-			NdisMoveMemory(&pAd->CommonCfg.CountryCode[0], &pAd->StaCfg.StaOriCountryCode[0], 2);
-			pAd->CommonCfg.Geography = pAd->StaCfg.StaOriGeography;
-			BuildChannelListEx(pAd);
-		}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-	}
-
-	for (i=1; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		if (pAd->MacTab.Content[i].ValidAsCLI == TRUE)
-			MacTableDeleteEntry(pAd, pAd->MacTab.Content[i].Aid, pAd->MacTab.Content[i].Addr);
-	}
-
-	pAd->StaCfg.CCXQosECWMin	= 4;
-	pAd->StaCfg.CCXQosECWMax	= 10;
-
-	AsicSetSlotTime(pAd, TRUE); //FALSE);
-	AsicSetEdcaParm(pAd, NULL);
-
-	// Set LED
-	RTMPSetLED(pAd, LED_LINK_DOWN);
-    pAd->LedIndicatorStregth = 0xF0;
-    RTMPSetSignalLED(pAd, -100);	// Force signal strength Led to be turned off, firmware is not done it.
-
-		AsicDisableSync(pAd);
-
-	pAd->Mlme.PeriodicRound = 0;
-	pAd->Mlme.OneSecPeriodicRound = 0;
-
-	if (pAd->StaCfg.BssType == BSS_INFRA)
-	{
-		// Remove StaCfg Information after link down
-		NdisZeroMemory(pAd->CommonCfg.Bssid, MAC_ADDR_LEN);
-		NdisZeroMemory(pAd->CommonCfg.Ssid, MAX_LEN_OF_SSID);
-		pAd->CommonCfg.SsidLen = 0;
-	}
-#ifdef DOT11_N_SUPPORT
-	NdisZeroMemory(&pAd->MlmeAux.HtCapability, sizeof(HT_CAPABILITY_IE));
-	NdisZeroMemory(&pAd->MlmeAux.AddHtInfo, sizeof(ADD_HT_INFO_IE));
-	pAd->MlmeAux.HtCapabilityLen = 0;
-	pAd->MlmeAux.NewExtChannelOffset = 0xff;
-#endif // DOT11_N_SUPPORT //
-
-	// Reset WPA-PSK state. Only reset when supplicant enabled
-	if (pAd->StaCfg.WpaState != SS_NOTUSE)
-	{
-		pAd->StaCfg.WpaState = SS_START;
-		// Clear Replay counter
-		NdisZeroMemory(pAd->StaCfg.ReplayCounter, 8);
-
-#ifdef QOS_DLS_SUPPORT
-		if (pAd->CommonCfg.bDLSCapable)
-			NdisZeroMemory(pAd->StaCfg.DlsReplayCounter, 8);
-#endif // QOS_DLS_SUPPORT //
-	}
-
-
-	//
-	// if link down come from AP, we need to remove all WPA keys on WPA mode.
-	// otherwise will cause 4-way handshaking failed, since the WPA key not empty.
-	//
-	if ((IsReqFromAP) && (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA))
-	{
-		// Remove all WPA keys
-		RTMPWPARemoveAllKeys(pAd);
-	}
-
-	// 802.1x port control
-#ifdef WPA_SUPPLICANT_SUPPORT
-	// Prevent clear PortSecured here with static WEP
-	// NetworkManger set security policy first then set SSID to connect AP.
-	if (pAd->StaCfg.WpaSupplicantUP &&
-		(pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled) &&
-		(pAd->StaCfg.IEEE8021X == FALSE))
-	{
-		pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-	}
-	else
-#endif // WPA_SUPPLICANT_SUPPORT //
-	{
-		pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-		pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilter8021xWEP;
-	}
-
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-	pAd->MacTab.Content[BSSID_WCID].PortSecured = pAd->StaCfg.PortSecured;
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-
-	pAd->StaCfg.MicErrCnt = 0;
-
-	// Turn off Ckip control flag
-	pAd->StaCfg.bCkipOn = FALSE;
-	pAd->StaCfg.CCXEnable = FALSE;
-
-    pAd->IndicateMediaState = NdisMediaStateDisconnected;
-	// Update extra information to link is up
-	pAd->ExtraInfo = GENERAL_LINK_DOWN;
-
-    //pAd->StaCfg.AdhocBOnlyJoined = FALSE;
-	//pAd->StaCfg.AdhocBGJoined = FALSE;
-	//pAd->StaCfg.Adhoc20NJoined = FALSE;
-    pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
-
-	// Reset the Current AP's IP address
-	NdisZeroMemory(pAd->StaCfg.AironetIPAddress, 4);
-#ifdef RT2870
-	pAd->bUsbTxBulkAggre = FALSE;
-#endif // RT2870 //
-
-	// Clean association information
-	NdisZeroMemory(&pAd->StaCfg.AssocInfo, sizeof(NDIS_802_11_ASSOCIATION_INFORMATION));
-	pAd->StaCfg.AssocInfo.Length = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION);
-	pAd->StaCfg.ReqVarIELen = 0;
-	pAd->StaCfg.ResVarIELen = 0;
-
-	//
-	// Reset RSSI value after link down
-	//
-	pAd->StaCfg.RssiSample.AvgRssi0 = 0;
-	pAd->StaCfg.RssiSample.AvgRssi0X8 = 0;
-	pAd->StaCfg.RssiSample.AvgRssi1 = 0;
-	pAd->StaCfg.RssiSample.AvgRssi1X8 = 0;
-	pAd->StaCfg.RssiSample.AvgRssi2 = 0;
-	pAd->StaCfg.RssiSample.AvgRssi2X8 = 0;
-
-	// Restore MlmeRate
-	pAd->CommonCfg.MlmeRate = pAd->CommonCfg.BasicMlmeRate;
-	pAd->CommonCfg.RtsRate = pAd->CommonCfg.BasicMlmeRate;
-
-#ifdef DOT11_N_SUPPORT
-	//
-	// After Link down, reset piggy-back setting in ASIC. Disable RDG.
-	//
-	if (pAd->CommonCfg.BBPCurrentBW == BW_40)
-	{
-		pAd->CommonCfg.BBPCurrentBW = BW_20;
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &ByteValue);
-		ByteValue &= (~0x18);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, ByteValue);
-	}
-#endif // DOT11_N_SUPPORT //
-	// Reset DAC
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &ByteValue);
-	ByteValue &= (~0x18);
-	if (pAd->Antenna.field.TxPath == 2)
-	{
-		ByteValue |= 0x10;
-	}
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, ByteValue);
-
-	RTMPSetPiggyBack(pAd,FALSE);
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_PIGGYBACK_INUSED);
-
-#ifdef DOT11_N_SUPPORT
-	pAd->CommonCfg.BACapability.word = pAd->CommonCfg.REGBACapability.word;
-#endif // DOT11_N_SUPPORT //
-
-	// Restore all settings in the following.
-	AsicUpdateProtect(pAd, 0, (ALLN_SETPROTECT|CCKSETPROTECT|OFDMSETPROTECT), TRUE, FALSE);
-	AsicDisableRDG(pAd);
-	pAd->CommonCfg.IOTestParm.bCurrentAtheros = FALSE;
-	pAd->CommonCfg.IOTestParm.bNowAtherosBurstOn = FALSE;
-
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SCAN_2040);
-	pAd->CommonCfg.BSSCoexist2040.word = 0;
-	TriEventInit(pAd);
-	for (i = 0; i < (pAd->ChannelListNum - 1); i++)
-	{
-		pAd->ChannelList[i].bEffectedChannel = FALSE;
-	}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-	RTMP_IO_WRITE32(pAd, MAX_LEN_CFG, 0x1fff);
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-	if (pAd->StaCfg.WpaSupplicantUP) {
-		union iwreq_data    wrqu;
-		//send disassociate event to wpa_supplicant
-		memset(&wrqu, 0, sizeof(wrqu));
-		wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-		wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-	}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-	{
-		union iwreq_data    wrqu;
-		memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-		wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-	}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID IterateOnBssTab(
-	IN PRTMP_ADAPTER pAd)
-{
-	MLME_START_REQ_STRUCT   StartReq;
-	MLME_JOIN_REQ_STRUCT    JoinReq;
-	ULONG                   BssIdx;
-
-	// Change the wepstatus to original wepstatus
-	pAd->StaCfg.WepStatus   = pAd->StaCfg.OrigWepStatus;
-	pAd->StaCfg.PairCipher  = pAd->StaCfg.OrigWepStatus;
-	pAd->StaCfg.GroupCipher = pAd->StaCfg.OrigWepStatus;
-
-	BssIdx = pAd->MlmeAux.BssIdx;
-	if (BssIdx < pAd->MlmeAux.SsidBssTab.BssNr)
-	{
-		// Check cipher suite, AP must have more secured cipher than station setting
-		// Set the Pairwise and Group cipher to match the intended AP setting
-		// We can only connect to AP with less secured cipher setting
-		if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-		{
-			pAd->StaCfg.GroupCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.GroupCipher;
-
-			if (pAd->StaCfg.WepStatus == pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipher)
-				pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipher;
-			else if (pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipherAux != Ndis802_11WEPDisabled)
-				pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipherAux;
-			else	// There is no PairCipher Aux, downgrade our capability to TKIP
-				pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-		}
-		else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-		{
-			pAd->StaCfg.GroupCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.GroupCipher;
-
-			if (pAd->StaCfg.WepStatus == pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipher)
-				pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipher;
-			else if (pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipherAux != Ndis802_11WEPDisabled)
-				pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipherAux;
-			else	// There is no PairCipher Aux, downgrade our capability to TKIP
-				pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-
-			// RSN capability
-			pAd->StaCfg.RsnCapability = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.RsnCapability;
-		}
-
-		// Set Mix cipher flag
-		pAd->StaCfg.bMixCipher = (pAd->StaCfg.PairCipher == pAd->StaCfg.GroupCipher) ? FALSE : TRUE;
-		if (pAd->StaCfg.bMixCipher == TRUE)
-		{
-			// If mix cipher, re-build RSNIE
-			RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, 0);
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - iterate BSS %ld of %d\n", BssIdx, pAd->MlmeAux.SsidBssTab.BssNr));
-		JoinParmFill(pAd, &JoinReq, BssIdx);
-		MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_JOIN_REQ, sizeof(MLME_JOIN_REQ_STRUCT),
-					&JoinReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_JOIN;
-	}
-	else if (pAd->StaCfg.BssType == BSS_ADHOC)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - All BSS fail; start a new ADHOC (Ssid=%s)...\n",pAd->MlmeAux.Ssid));
-		StartParmFill(pAd, &StartReq, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-		MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_START_REQ, sizeof(MLME_START_REQ_STRUCT), &StartReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_START;
-	}
-	else // no more BSS
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - All roaming failed, stay @ ch #%d\n", pAd->CommonCfg.Channel));
-		AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-	}
-}
-
-// for re-association only
-// IRQL = DISPATCH_LEVEL
-VOID IterateOnBssTab2(
-	IN PRTMP_ADAPTER pAd)
-{
-	MLME_REASSOC_REQ_STRUCT ReassocReq;
-	ULONG                   BssIdx;
-	BSS_ENTRY               *pBss;
-
-	BssIdx = pAd->MlmeAux.RoamIdx;
-	pBss = &pAd->MlmeAux.RoamTab.BssEntry[BssIdx];
-
-	if (BssIdx < pAd->MlmeAux.RoamTab.BssNr)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - iterate BSS %ld of %d\n", BssIdx, pAd->MlmeAux.RoamTab.BssNr));
-
-		AsicSwitchChannel(pAd, pBss->Channel, FALSE);
-		AsicLockChannel(pAd, pBss->Channel);
-
-		// reassociate message has the same structure as associate message
-		AssocParmFill(pAd, &ReassocReq, pBss->Bssid, pBss->CapabilityInfo,
-					  ASSOC_TIMEOUT, pAd->StaCfg.DefaultListenCount);
-		MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_REASSOC_REQ,
-					sizeof(MLME_REASSOC_REQ_STRUCT), &ReassocReq);
-
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_REASSOC;
-	}
-	else // no more BSS
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - All fast roaming failed, back to ch #%d\n",pAd->CommonCfg.Channel));
-		AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID JoinParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_JOIN_REQ_STRUCT *JoinReq,
-	IN ULONG BssIdx)
-{
-	JoinReq->BssIdx = BssIdx;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID ScanParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_SCAN_REQ_STRUCT *ScanReq,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR BssType,
-	IN UCHAR ScanType)
-{
-    NdisZeroMemory(ScanReq->Ssid, MAX_LEN_OF_SSID);
-	ScanReq->SsidLen = SsidLen;
-	NdisMoveMemory(ScanReq->Ssid, Ssid, SsidLen);
-	ScanReq->BssType = BssType;
-	ScanReq->ScanType = ScanType;
-}
-
-#ifdef QOS_DLS_SUPPORT
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID DlsParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_DLS_REQ_STRUCT *pDlsReq,
-	IN PRT_802_11_DLS pDls,
-	IN USHORT reason)
-{
-	pDlsReq->pDLS = pDls;
-	pDlsReq->Reason = reason;
-}
-#endif // QOS_DLS_SUPPORT //
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID StartParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_START_REQ_STRUCT *StartReq,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen)
-{
-	ASSERT(SsidLen <= MAX_LEN_OF_SSID);
-	NdisMoveMemory(StartReq->Ssid, Ssid, SsidLen);
-	StartReq->SsidLen = SsidLen;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID AuthParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_AUTH_REQ_STRUCT *AuthReq,
-	IN PUCHAR pAddr,
-	IN USHORT Alg)
-{
-	COPY_MAC_ADDR(AuthReq->Addr, pAddr);
-	AuthReq->Alg = Alg;
-	AuthReq->Timeout = AUTH_TIMEOUT;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-
-
-#ifdef RT2870
-
-VOID MlmeCntlConfirm(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG MsgType,
-	IN USHORT Msg)
-{
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MsgType, sizeof(USHORT), &Msg);
-}
-
-VOID ComposePsPoll(
-	IN PRTMP_ADAPTER pAd)
-{
-	PTXINFO_STRUC		pTxInfo;
-	PTXWI_STRUC		pTxWI;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ComposePsPoll\n"));
-	NdisZeroMemory(&pAd->PsPollFrame, sizeof(PSPOLL_FRAME));
-
-	pAd->PsPollFrame.FC.PwrMgmt = 0;
-	pAd->PsPollFrame.FC.Type = BTYPE_CNTL;
-	pAd->PsPollFrame.FC.SubType = SUBTYPE_PS_POLL;
-	pAd->PsPollFrame.Aid = pAd->StaActive.Aid | 0xC000;
-	COPY_MAC_ADDR(pAd->PsPollFrame.Bssid, pAd->CommonCfg.Bssid);
-	COPY_MAC_ADDR(pAd->PsPollFrame.Ta, pAd->CurrentAddress);
-
-	RTMPZeroMemory(&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[0], 100);
-	pTxInfo = (PTXINFO_STRUC)&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[0];
-	RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(sizeof(PSPOLL_FRAME)+TXWI_SIZE), TRUE, EpToQueue[MGMTPIPEIDX], FALSE,  FALSE);
-	pTxWI = (PTXWI_STRUC)&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE];
-	RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, 0, BSSID_WCID, (sizeof(PSPOLL_FRAME)),
-		0,  0, (UCHAR)pAd->CommonCfg.MlmeTransmit.field.MCS, IFS_BACKOFF, FALSE, &pAd->CommonCfg.MlmeTransmit);
-	RTMPMoveMemory(&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[TXWI_SIZE+TXINFO_SIZE], &pAd->PsPollFrame, sizeof(PSPOLL_FRAME));
-	// Append 4 extra zero bytes.
-	pAd->PsPollContext.BulkOutSize =  TXINFO_SIZE + TXWI_SIZE + sizeof(PSPOLL_FRAME) + 4;
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID ComposeNullFrame(
-	IN PRTMP_ADAPTER pAd)
-{
-	PTXINFO_STRUC		pTxInfo;
-	PTXWI_STRUC		pTxWI;
-
-	NdisZeroMemory(&pAd->NullFrame, sizeof(HEADER_802_11));
-	pAd->NullFrame.FC.Type = BTYPE_DATA;
-	pAd->NullFrame.FC.SubType = SUBTYPE_NULL_FUNC;
-	pAd->NullFrame.FC.ToDs = 1;
-	COPY_MAC_ADDR(pAd->NullFrame.Addr1, pAd->CommonCfg.Bssid);
-	COPY_MAC_ADDR(pAd->NullFrame.Addr2, pAd->CurrentAddress);
-	COPY_MAC_ADDR(pAd->NullFrame.Addr3, pAd->CommonCfg.Bssid);
-	RTMPZeroMemory(&pAd->NullContext.TransferBuffer->field.WirelessPacket[0], 100);
-	pTxInfo = (PTXINFO_STRUC)&pAd->NullContext.TransferBuffer->field.WirelessPacket[0];
-	RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(sizeof(HEADER_802_11)+TXWI_SIZE), TRUE, EpToQueue[MGMTPIPEIDX], FALSE,  FALSE);
-	pTxWI = (PTXWI_STRUC)&pAd->NullContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE];
-	RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, 0, BSSID_WCID, (sizeof(HEADER_802_11)),
-		0, 0, (UCHAR)pAd->CommonCfg.MlmeTransmit.field.MCS, IFS_BACKOFF, FALSE, &pAd->CommonCfg.MlmeTransmit);
-	RTMPMoveMemory(&pAd->NullContext.TransferBuffer->field.WirelessPacket[TXWI_SIZE+TXINFO_SIZE], &pAd->NullFrame, sizeof(HEADER_802_11));
-	pAd->NullContext.BulkOutSize =  TXINFO_SIZE + TXWI_SIZE + sizeof(pAd->NullFrame) + 4;
-}
-#endif // RT2870 //
-
-
-/*
-	==========================================================================
-	Description:
-		Pre-build a BEACON frame in the shared memory
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-ULONG MakeIbssBeacon(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR         DsLen = 1, IbssLen = 2;
-	UCHAR         LocalErpIe[3] = {IE_ERP, 1, 0x04};
-	HEADER_802_11 BcnHdr;
-	USHORT        CapabilityInfo;
-	LARGE_INTEGER FakeTimestamp;
-	ULONG         FrameLen = 0;
-	PTXWI_STRUC	  pTxWI = &pAd->BeaconTxWI;
-	CHAR         *pBeaconFrame = pAd->BeaconBuf;
-	BOOLEAN       Privacy;
-	UCHAR         SupRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR         SupRateLen = 0;
-	UCHAR         ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR         ExtRateLen = 0;
-	UCHAR         RSNIe = IE_WPA;
-
-	if ((pAd->CommonCfg.PhyMode == PHY_11B) && (pAd->CommonCfg.Channel <= 14))
-	{
-		SupRate[0] = 0x82; // 1 mbps
-		SupRate[1] = 0x84; // 2 mbps
-		SupRate[2] = 0x8b; // 5.5 mbps
-		SupRate[3] = 0x96; // 11 mbps
-		SupRateLen = 4;
-		ExtRateLen = 0;
-	}
-	else if (pAd->CommonCfg.Channel > 14)
-	{
-		SupRate[0]  = 0x8C;    // 6 mbps, in units of 0.5 Mbps, basic rate
-		SupRate[1]  = 0x12;    // 9 mbps, in units of 0.5 Mbps
-		SupRate[2]  = 0x98;    // 12 mbps, in units of 0.5 Mbps, basic rate
-		SupRate[3]  = 0x24;    // 18 mbps, in units of 0.5 Mbps
-		SupRate[4]  = 0xb0;    // 24 mbps, in units of 0.5 Mbps, basic rate
-		SupRate[5]  = 0x48;    // 36 mbps, in units of 0.5 Mbps
-		SupRate[6]  = 0x60;    // 48 mbps, in units of 0.5 Mbps
-		SupRate[7]  = 0x6c;    // 54 mbps, in units of 0.5 Mbps
-		SupRateLen  = 8;
-		ExtRateLen  = 0;
-
-		//
-		// Also Update MlmeRate & RtsRate for G only & A only
-		//
-		pAd->CommonCfg.MlmeRate = RATE_6;
-		pAd->CommonCfg.RtsRate = RATE_6;
-		pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-		pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MODE = MODE_OFDM;
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-	}
-	else
-	{
-		SupRate[0] = 0x82; // 1 mbps
-		SupRate[1] = 0x84; // 2 mbps
-		SupRate[2] = 0x8b; // 5.5 mbps
-		SupRate[3] = 0x96; // 11 mbps
-		SupRateLen = 4;
-
-		ExtRate[0]  = 0x0C;    // 6 mbps, in units of 0.5 Mbps,
-		ExtRate[1]  = 0x12;    // 9 mbps, in units of 0.5 Mbps
-		ExtRate[2]  = 0x18;    // 12 mbps, in units of 0.5 Mbps,
-		ExtRate[3]  = 0x24;    // 18 mbps, in units of 0.5 Mbps
-		ExtRate[4]  = 0x30;    // 24 mbps, in units of 0.5 Mbps,
-		ExtRate[5]  = 0x48;    // 36 mbps, in units of 0.5 Mbps
-		ExtRate[6]  = 0x60;    // 48 mbps, in units of 0.5 Mbps
-		ExtRate[7]  = 0x6c;    // 54 mbps, in units of 0.5 Mbps
-		ExtRateLen  = 8;
-	}
-
-	pAd->StaActive.SupRateLen = SupRateLen;
-	NdisMoveMemory(pAd->StaActive.SupRate, SupRate, SupRateLen);
-	pAd->StaActive.ExtRateLen = ExtRateLen;
-	NdisMoveMemory(pAd->StaActive.ExtRate, ExtRate, ExtRateLen);
-
-	// compose IBSS beacon frame
-	MgtMacHeaderInit(pAd, &BcnHdr, SUBTYPE_BEACON, 0, BROADCAST_ADDR, pAd->CommonCfg.Bssid);
-	Privacy = (pAd->StaCfg.WepStatus == Ndis802_11Encryption1Enabled) ||
-			  (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
-			  (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled);
-	CapabilityInfo = CAP_GENERATE(0, 1, Privacy, (pAd->CommonCfg.TxPreamble == Rt802_11PreambleShort), 0, 0);
-
-	MakeOutgoingFrame(pBeaconFrame,                &FrameLen,
-					  sizeof(HEADER_802_11),           &BcnHdr,
-					  TIMESTAMP_LEN,                   &FakeTimestamp,
-					  2,                               &pAd->CommonCfg.BeaconPeriod,
-					  2,                               &CapabilityInfo,
-					  1,                               &SsidIe,
-					  1,                               &pAd->CommonCfg.SsidLen,
-					  pAd->CommonCfg.SsidLen,          pAd->CommonCfg.Ssid,
-					  1,                               &SupRateIe,
-					  1,                               &SupRateLen,
-					  SupRateLen,                      SupRate,
-					  1,                               &DsIe,
-					  1,                               &DsLen,
-					  1,                               &pAd->CommonCfg.Channel,
-					  1,                               &IbssIe,
-					  1,                               &IbssLen,
-					  2,                               &pAd->StaActive.AtimWin,
-					  END_OF_ARGS);
-
-	// add ERP_IE and EXT_RAE IE of in 802.11g
-	if (ExtRateLen)
-	{
-		ULONG	tmp;
-
-		MakeOutgoingFrame(pBeaconFrame + FrameLen,         &tmp,
-						  3,                               LocalErpIe,
-						  1,                               &ExtRateIe,
-						  1,                               &ExtRateLen,
-						  ExtRateLen,                      ExtRate,
-						  END_OF_ARGS);
-		FrameLen += tmp;
-	}
-
-	// If adhoc secruity is set for WPA-None, append the cipher suite IE
-	if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-	{
-		ULONG tmp;
-        RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, BSS0);
-
-		MakeOutgoingFrame(pBeaconFrame + FrameLen,        	&tmp,
-						  1,                              	&RSNIe,
-						  1,                            	&pAd->StaCfg.RSNIE_Len,
-						  pAd->StaCfg.RSNIE_Len,      		pAd->StaCfg.RSN_IE,
-						  END_OF_ARGS);
-		FrameLen += tmp;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-	{
-		ULONG TmpLen;
-		UCHAR HtLen, HtLen1;
-
-#ifdef RT_BIG_ENDIAN
-		HT_CAPABILITY_IE HtCapabilityTmp;
-		ADD_HT_INFO_IE	addHTInfoTmp;
-		USHORT	b2lTmp, b2lTmp2;
-#endif
-
-		// add HT Capability IE
-		HtLen = sizeof(pAd->CommonCfg.HtCapability);
-		HtLen1 = sizeof(pAd->CommonCfg.AddHTInfo);
-#ifndef RT_BIG_ENDIAN
-		MakeOutgoingFrame(pBeaconFrame+FrameLen,	&TmpLen,
-						  1,						&HtCapIe,
-						  1,						&HtLen,
-						  HtLen,					&pAd->CommonCfg.HtCapability,
-						  1,						&AddHtInfoIe,
-						  1,						&HtLen1,
-						  HtLen1,					&pAd->CommonCfg.AddHTInfo,
-						  END_OF_ARGS);
-#else
-		NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, HtLen);
-		*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-		*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-		NdisMoveMemory(&addHTInfoTmp, &pAd->CommonCfg.AddHTInfo, HtLen1);
-		*(USHORT *)(&addHTInfoTmp.AddHtInfo2) = SWAP16(*(USHORT *)(&addHTInfoTmp.AddHtInfo2));
-		*(USHORT *)(&addHTInfoTmp.AddHtInfo3) = SWAP16(*(USHORT *)(&addHTInfoTmp.AddHtInfo3));
-
-		MakeOutgoingFrame(pBeaconFrame+FrameLen,	&TmpLen,
-						  1,						&HtCapIe,
-						  1,						&HtLen,
-						  HtLen,					&HtCapabilityTmp,
-						  1,						&AddHtInfoIe,
-						  1,						&HtLen1,
-						  HtLen1,					&addHTInfoTmp,
-						  END_OF_ARGS);
-#endif
-		FrameLen += TmpLen;
-	}
-#endif // DOT11_N_SUPPORT //
-
-	//beacon use reserved WCID 0xff
-    if (pAd->CommonCfg.Channel > 14)
-    {
-		RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE,  TRUE, FALSE, FALSE, TRUE, 0, 0xff, FrameLen,
-			PID_MGMT, PID_BEACON, RATE_1, IFS_HTTXOP, FALSE, &pAd->CommonCfg.MlmeTransmit);
-    }
-    else
-    {
-        // Set to use 1Mbps for Adhoc beacon.
-		HTTRANSMIT_SETTING Transmit;
-        Transmit.word = 0;
-        RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE,  TRUE, FALSE, FALSE, TRUE, 0, 0xff, FrameLen,
-    		PID_MGMT, PID_BEACON, RATE_1, IFS_HTTXOP, FALSE, &Transmit);
-    }
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, pBeaconFrame, DIR_WRITE, FALSE);
-	RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-#endif
-
-    DBGPRINT(RT_DEBUG_TRACE, ("MakeIbssBeacon (len=%ld), SupRateLen=%d, ExtRateLen=%d, Channel=%d, PhyMode=%d\n",
-					FrameLen, SupRateLen, ExtRateLen, pAd->CommonCfg.Channel, pAd->CommonCfg.PhyMode));
-	return FrameLen;
-}
-
-
+#include "../../rt2860/sta/connect.c"
diff --git a/drivers/staging/rt2870/sta/dls.c b/drivers/staging/rt2870/sta/dls.c
deleted file mode 100644
index 56bfbc3..0000000
--- a/drivers/staging/rt2870/sta/dls.c
+++ /dev/null
@@ -1,2210 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    dls.c
-
-    Abstract:
-    Handle WMM-DLS state machine
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Rory Chen   02-14-2006
-	Arvin Tai	06-03-2008	  Modified for RT28xx
- */
-
-#include "../rt_config.h"
-
-/*
-    ==========================================================================
-    Description:
-        dls state machine init, including state transition and timer init
-    Parameters:
-        Sm - pointer to the dls state machine
-    Note:
-        The state machine looks like this
-
-                            DLS_IDLE
-    MT2_MLME_DLS_REQUEST   MlmeDlsReqAction
-    MT2_PEER_DLS_REQUEST   PeerDlsReqAction
-    MT2_PEER_DLS_RESPONSE  PeerDlsRspAction
-    MT2_MLME_DLS_TEARDOWN  MlmeTearDownAction
-    MT2_PEER_DLS_TEARDOWN  PeerTearDownAction
-
-	IRQL = PASSIVE_LEVEL
-
-    ==========================================================================
- */
-void DlsStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[])
-{
-	UCHAR	i;
-
-    StateMachineInit(Sm, (STATE_MACHINE_FUNC*)Trans, MAX_DLS_STATE, MAX_DLS_MSG, (STATE_MACHINE_FUNC)Drop, DLS_IDLE, DLS_MACHINE_BASE);
-
-    // the first column
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_MLME_DLS_REQ, (STATE_MACHINE_FUNC)MlmeDlsReqAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_PEER_DLS_REQ, (STATE_MACHINE_FUNC)PeerDlsReqAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_PEER_DLS_RSP, (STATE_MACHINE_FUNC)PeerDlsRspAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_MLME_DLS_TEAR_DOWN, (STATE_MACHINE_FUNC)MlmeDlsTearDownAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_PEER_DLS_TEAR_DOWN, (STATE_MACHINE_FUNC)PeerDlsTearDownAction);
-
-	for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		pAd->StaCfg.DLSEntry[i].pAd = pAd;
-		RTMPInitTimer(pAd, &pAd->StaCfg.DLSEntry[i].Timer, GET_TIMER_FUNCTION(DlsTimeoutAction), pAd, FALSE);
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeDlsReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen = 0;
-	HEADER_802_11	DlsReqHdr;
-	PRT_802_11_DLS	pDLS = NULL;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_REQUEST;
-	ULONG			tmp;
-	USHORT			reason;
-	ULONG			Timeout;
-	BOOLEAN			TimerCancelled;
-
-	if(!MlmeDlsReqSanity(pAd, Elem->Msg, Elem->MsgLen, &pDLS, &reason))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - MlmeDlsReqAction() \n"));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("DLS - MlmeDlsReqAction() allocate memory failed \n"));
-		return;
-	}
-
-	ActHeaderInit(pAd, &DlsReqHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-
-	// Build basic frame first
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-					sizeof(HEADER_802_11),		&DlsReqHdr,
-					1,							&Category,
-					1,							&Action,
-					6,							&pDLS->MacAddr,
-					6,							pAd->CurrentAddress,
-					2,							&pAd->StaActive.CapabilityInfo,
-					2,							&pDLS->TimeOut,
-					1,							&SupRateIe,
-					1,							&pAd->MlmeAux.SupRateLen,
-					pAd->MlmeAux.SupRateLen,	pAd->MlmeAux.SupRate,
-					END_OF_ARGS);
-
-	if (pAd->MlmeAux.ExtRateLen != 0)
-	{
-		MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-						  1,						&ExtRateIe,
-						  1,						&pAd->MlmeAux.ExtRateLen,
-						  pAd->MlmeAux.ExtRateLen,	pAd->MlmeAux.ExtRate,
-						  END_OF_ARGS);
-		FrameLen += tmp;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-	{
-		UCHAR HtLen;
-
-#ifdef RT_BIG_ENDIAN
-		HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
-
-		// add HT Capability IE
-		HtLen = sizeof(HT_CAPABILITY_IE);
-#ifndef RT_BIG_ENDIAN
-		MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-							1,						&HtCapIe,
-							1,						&HtLen,
-							HtLen,					&pAd->CommonCfg.HtCapability,
-							END_OF_ARGS);
-#else
-		NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, HtLen);
-							*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-							*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-		MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-							1,						&HtCapIe,
-							1,						&HtLen,
-							HtLen,					&HtCapabilityTmp,
-							END_OF_ARGS);
-#endif
-		FrameLen = FrameLen + tmp;
-	}
-#endif // DOT11_N_SUPPORT //
-
-	RTMPCancelTimer(&pDLS->Timer, &TimerCancelled);
-	Timeout = DLS_TIMEOUT;
-	RTMPSetTimer(&pDLS->Timer, Timeout);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerDlsReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen = 0;
-	USHORT			StatusCode = MLME_SUCCESS;
-	HEADER_802_11	DlsRspHdr;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_RESPONSE;
-	ULONG			tmp;
-	USHORT			CapabilityInfo;
-	UCHAR			DA[MAC_ADDR_LEN], SA[MAC_ADDR_LEN];
-	USHORT			DLSTimeOut;
-	SHORT			i;
-	ULONG			Timeout;
-	BOOLEAN			TimerCancelled;
-	PRT_802_11_DLS	pDLS = NULL;
-	UCHAR			MaxSupportedRateIn500Kbps = 0;
-    UCHAR			SupportedRatesLen;
-    UCHAR			SupportedRates[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR			HtCapabilityLen;
-	HT_CAPABILITY_IE	HtCapability;
-
-	if (!PeerDlsReqSanity(pAd, Elem->Msg, Elem->MsgLen, DA, SA, &CapabilityInfo, &DLSTimeOut,
-							&SupportedRatesLen, &SupportedRates[0], &HtCapabilityLen, &HtCapability))
-		return;
-
-    // supported rates array may not be sorted. sort it and find the maximum rate
-    for (i = 0; i < SupportedRatesLen; i++)
-    {
-        if (MaxSupportedRateIn500Kbps < (SupportedRates[i] & 0x7f))
-            MaxSupportedRateIn500Kbps = SupportedRates[i] & 0x7f;
-    }
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsReqAction() from %02x:%02x:%02x:%02x:%02x:%02x\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsReqAction() allocate memory failed \n"));
-		return;
-	}
-
-	if (!INFRA_ON(pAd))
-	{
-		StatusCode = MLME_REQUEST_DECLINED;
-	}
-	else if (!pAd->CommonCfg.bWmmCapable)
-	{
-		StatusCode = MLME_DEST_STA_IS_NOT_A_QSTA;
-	}
-	else if (!pAd->CommonCfg.bDLSCapable)
-	{
-		StatusCode = MLME_REQUEST_DECLINED;
-	}
-	else
-	{
-		// find table to update parameters
-		for (i = (MAX_NUM_OF_DLS_ENTRY-1); i >= 0; i--)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-					pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-				else
-				{
-					RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-					pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-				}
-
-				pAd->StaCfg.DLSEntry[i].Sequence = 0;
-				pAd->StaCfg.DLSEntry[i].TimeOut = DLSTimeOut;
-				pAd->StaCfg.DLSEntry[i].CountDownTimer = DLSTimeOut;
-				if (HtCapabilityLen != 0)
-					pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-				else
-					pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-				pDLS = &pAd->StaCfg.DLSEntry[i];
-				break;
-			}
-		}
-
-		// can not find in table, create a new one
-		if (i < 0)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsReqAction() can not find same entry \n"));
-			for (i=(MAX_NUM_OF_DLS_ENTRY - 1); i >= MAX_NUM_OF_INIT_DLS_ENTRY; i--)
-			{
-				if (!pAd->StaCfg.DLSEntry[i].Valid)
-				{
-					MAC_TABLE_ENTRY *pEntry;
-					UCHAR MaxSupportedRate = RATE_11;
-
-					if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-					{
-						pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-					}
-					else
-					{
-						RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-						pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-					}
-
-					pAd->StaCfg.DLSEntry[i].Sequence = 0;
-					pAd->StaCfg.DLSEntry[i].Valid = TRUE;
-					pAd->StaCfg.DLSEntry[i].TimeOut = DLSTimeOut;
-					pAd->StaCfg.DLSEntry[i].CountDownTimer = DLSTimeOut;
-					NdisMoveMemory(pAd->StaCfg.DLSEntry[i].MacAddr, SA, MAC_ADDR_LEN);
-					if (HtCapabilityLen != 0)
-						pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-					else
-						pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-					pDLS = &pAd->StaCfg.DLSEntry[i];
-					pEntry = MacTableInsertDlsEntry(pAd, SA, i);
-
-					switch (MaxSupportedRateIn500Kbps)
-					{
-						case 108: MaxSupportedRate = RATE_54;   break;
-						case 96:  MaxSupportedRate = RATE_48;   break;
-						case 72:  MaxSupportedRate = RATE_36;   break;
-						case 48:  MaxSupportedRate = RATE_24;   break;
-						case 36:  MaxSupportedRate = RATE_18;   break;
-						case 24:  MaxSupportedRate = RATE_12;   break;
-						case 18:  MaxSupportedRate = RATE_9;    break;
-						case 12:  MaxSupportedRate = RATE_6;    break;
-						case 22:  MaxSupportedRate = RATE_11;   break;
-						case 11:  MaxSupportedRate = RATE_5_5;  break;
-						case 4:   MaxSupportedRate = RATE_2;    break;
-						case 2:   MaxSupportedRate = RATE_1;    break;
-						default:  MaxSupportedRate = RATE_11;   break;
-					}
-
-					pEntry->MaxSupportedRate = min(pAd->CommonCfg.MaxTxRate, MaxSupportedRate);
-
-					if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->HTPhyMode.field.MODE = MODE_CCK;
-						pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->HTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					}
-
-					pEntry->MaxHTPhyMode.field.BW = BW_20;
-					pEntry->MinHTPhyMode.field.BW = BW_20;
-
-#ifdef DOT11_N_SUPPORT
-					pEntry->HTCapability.MCSSet[0] = 0;
-					pEntry->HTCapability.MCSSet[1] = 0;
-
-					// If this Entry supports 802.11n, upgrade to HT rate.
-					if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-					{
-						UCHAR	j, bitmask; //k,bitmask;
-						CHAR    ii;
-
-						DBGPRINT(RT_DEBUG_OFF, ("DLS - PeerDlsReqAction() Receive Peer HT Capable STA from %02x:%02x:%02x:%02x:%02x:%02x\n",
-									SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-
-						if ((HtCapability.HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-							pAd->MacTab.fAnyStationNonGF = TRUE;
-							pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
-						}
-
-						if ((HtCapability.HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
-						{
-							pEntry->MaxHTPhyMode.field.BW= BW_40;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(HtCapability.HtCapInfo.ShortGIfor40));
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.BW = BW_20;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(HtCapability.HtCapInfo.ShortGIfor20));
-							pAd->MacTab.fAnyStation20Only = TRUE;
-						}
-
-						// find max fixed rate
-						for (ii=15; ii>=0; ii--)
-						{
-							j = ii/8;
-							bitmask = (1<<(ii-(j*8)));
-							if ( (pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j]&bitmask) && (HtCapability.MCSSet[j]&bitmask))
-							{
-								pEntry->MaxHTPhyMode.field.MCS = ii;
-								break;
-							}
-							if (ii==0)
-								break;
-						}
-
-
-						if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
-						{
-
-							printk("@@@ pAd->CommonCfg.RegTransmitSetting.field.MCS = %d\n",
-								pAd->StaCfg.DesiredTransmitSetting.field.MCS);
-							if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
-							{
-								// Fix MCS as HT Duplicated Mode
-								pEntry->MaxHTPhyMode.field.BW = 1;
-								pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-								pEntry->MaxHTPhyMode.field.STBC = 0;
-								pEntry->MaxHTPhyMode.field.ShortGI = 0;
-								pEntry->MaxHTPhyMode.field.MCS = 32;
-							}
-							else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
-							{
-								// STA supports fixed MCS
-								pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
-							}
-						}
-
-						pEntry->MaxHTPhyMode.field.STBC = (HtCapability.HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
-						pEntry->MpduDensity = HtCapability.HtCapParm.MpduDensity;
-						pEntry->MaxRAmpduFactor = HtCapability.HtCapParm.MaxRAmpduFactor;
-						pEntry->MmpsMode = (UCHAR)HtCapability.HtCapInfo.MimoPs;
-						pEntry->AMsduSize = (UCHAR)HtCapability.HtCapInfo.AMsduSize;
-						pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-
-						if (HtCapability.HtCapInfo.ShortGIfor20)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
-						if (HtCapability.HtCapInfo.ShortGIfor40)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
-						if (HtCapability.HtCapInfo.TxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
-						if (HtCapability.HtCapInfo.RxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.PlusHTC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
-						if (pAd->CommonCfg.bRdg && HtCapability.ExtHtCapInfo.RDGSupport)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.MCSFeedback == 0x03)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
-
-						NdisMoveMemory(&pEntry->HTCapability, &HtCapability, sizeof(HT_CAPABILITY_IE));
-					}
-#endif // DOT11_N_SUPPORT //
-
-					pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-					pEntry->CurrTxRate = pEntry->MaxSupportedRate;
-					CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-
-					if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-					{
-						PUCHAR pTable;
-						UCHAR TableSize = 0;
-
-						MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
-						pEntry->bAutoTxRateSwitch = TRUE;
-					}
-					else
-					{
-						pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-						pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
-						pEntry->bAutoTxRateSwitch = FALSE;
-
-						RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-					}
-					pEntry->RateLen = SupportedRatesLen;
-
-					break;
-				}
-			}
-		}
-		StatusCode = MLME_SUCCESS;
-
-		// can not find in table, create a new one
-		if (i < 0)
-		{
-			StatusCode = MLME_QOS_UNSPECIFY;
-			DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsReqAction() DLSEntry table full(only can support %d DLS session) \n", MAX_NUM_OF_DLS_ENTRY - MAX_NUM_OF_INIT_DLS_ENTRY));
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsReqAction() use entry(%d) %02x:%02x:%02x:%02x:%02x:%02x\n",
-				i, SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-		}
-	}
-
-	ActHeaderInit(pAd, &DlsRspHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-
-	// Build basic frame first
-	if (StatusCode == MLME_SUCCESS)
-	{
-		MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-						sizeof(HEADER_802_11),		&DlsRspHdr,
-						1,							&Category,
-						1,							&Action,
-						2,							&StatusCode,
-						6,							SA,
-						6,							pAd->CurrentAddress,
-						2,							&pAd->StaActive.CapabilityInfo,
-						1,							&SupRateIe,
-						1,							&pAd->MlmeAux.SupRateLen,
-						pAd->MlmeAux.SupRateLen,	pAd->MlmeAux.SupRate,
-						END_OF_ARGS);
-
-		if (pAd->MlmeAux.ExtRateLen != 0)
-		{
-			MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-							  1,						&ExtRateIe,
-							  1,						&pAd->MlmeAux.ExtRateLen,
-							  pAd->MlmeAux.ExtRateLen, 	pAd->MlmeAux.ExtRate,
-							  END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-#ifdef DOT11_N_SUPPORT
-		if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-		{
-			UCHAR HtLen;
-
-#ifdef RT_BIG_ENDIAN
-			HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
-
-			// add HT Capability IE
-			HtLen = sizeof(HT_CAPABILITY_IE);
-#ifndef RT_BIG_ENDIAN
-			MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-								1,						&HtCapIe,
-								1,						&HtLen,
-								HtLen,					&pAd->CommonCfg.HtCapability,
-								END_OF_ARGS);
-#else
-			NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, HtLen);
-								*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-								*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-								1,						&HtCapIe,
-								1,						&HtLen,
-								HtLen,					&HtCapabilityTmp,
-								END_OF_ARGS);
-#endif
-			FrameLen = FrameLen + tmp;
-		}
-#endif // DOT11_N_SUPPORT //
-
-		if (pDLS && (pDLS->Status != DLS_FINISH))
-		{
-			RTMPCancelTimer(&pDLS->Timer, &TimerCancelled);
-			Timeout = DLS_TIMEOUT;
-			RTMPSetTimer(&pDLS->Timer, Timeout);
-		}
-	}
-	else
-	{
-		MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-						sizeof(HEADER_802_11),		&DlsRspHdr,
-						1,							&Category,
-						1,							&Action,
-						2,							&StatusCode,
-						6,							SA,
-						6,							pAd->CurrentAddress,
-						END_OF_ARGS);
-	}
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerDlsRspAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT		CapabilityInfo;
-	UCHAR		DA[MAC_ADDR_LEN], SA[MAC_ADDR_LEN];
-	USHORT		StatusCode;
-	SHORT		i;
-	BOOLEAN		TimerCancelled;
-	UCHAR		MaxSupportedRateIn500Kbps = 0;
-    UCHAR		SupportedRatesLen;
-    UCHAR		SupportedRates[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		HtCapabilityLen;
-	HT_CAPABILITY_IE	HtCapability;
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return;
-
-	if (!INFRA_ON(pAd))
-		return;
-
-	if (!PeerDlsRspSanity(pAd, Elem->Msg, Elem->MsgLen, DA, SA, &CapabilityInfo, &StatusCode,
-							&SupportedRatesLen, &SupportedRates[0], &HtCapabilityLen, &HtCapability))
-		return;
-
-    // supported rates array may not be sorted. sort it and find the maximum rate
-    for (i=0; i<SupportedRatesLen; i++)
-    {
-        if (MaxSupportedRateIn500Kbps < (SupportedRates[i] & 0x7f))
-            MaxSupportedRateIn500Kbps = SupportedRates[i] & 0x7f;
-    }
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() from %02x:%02x:%02x:%02x:%02x:%02x with StatusCode=%d, CapabilityInfo=0x%x\n",
-		SA[0], SA[1], SA[2], SA[3], SA[4], SA[5], StatusCode, CapabilityInfo));
-
-	for (i = 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			if (StatusCode == MLME_SUCCESS)
-			{
-				MAC_TABLE_ENTRY *pEntry;
-				UCHAR MaxSupportedRate = RATE_11;
-
-				pEntry = MacTableInsertDlsEntry(pAd, SA, i);
-
-				switch (MaxSupportedRateIn500Kbps)
-				{
-					case 108: MaxSupportedRate = RATE_54;   break;
-					case 96:  MaxSupportedRate = RATE_48;   break;
-					case 72:  MaxSupportedRate = RATE_36;   break;
-					case 48:  MaxSupportedRate = RATE_24;   break;
-					case 36:  MaxSupportedRate = RATE_18;   break;
-					case 24:  MaxSupportedRate = RATE_12;   break;
-					case 18:  MaxSupportedRate = RATE_9;    break;
-					case 12:  MaxSupportedRate = RATE_6;    break;
-					case 22:  MaxSupportedRate = RATE_11;   break;
-					case 11:  MaxSupportedRate = RATE_5_5;  break;
-					case 4:   MaxSupportedRate = RATE_2;    break;
-					case 2:   MaxSupportedRate = RATE_1;    break;
-					default:  MaxSupportedRate = RATE_11;   break;
-				}
-
-				pEntry->MaxSupportedRate = min(pAd->CommonCfg.MaxTxRate, MaxSupportedRate);
-
-				if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
-				{
-					pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
-					pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
-					pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					pEntry->HTPhyMode.field.MODE = MODE_CCK;
-					pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-				}
-				else
-				{
-					pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
-					pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
-					pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					pEntry->HTPhyMode.field.MODE = MODE_OFDM;
-					pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-				}
-
-				pEntry->MaxHTPhyMode.field.BW = BW_20;
-				pEntry->MinHTPhyMode.field.BW = BW_20;
-
-#ifdef DOT11_N_SUPPORT
-				pEntry->HTCapability.MCSSet[0] = 0;
-				pEntry->HTCapability.MCSSet[1] = 0;
-
-				// If this Entry supports 802.11n, upgrade to HT rate.
-				if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-				{
-					UCHAR	j, bitmask; //k,bitmask;
-					CHAR    ii;
-
-					DBGPRINT(RT_DEBUG_OFF, ("DLS - PeerDlsRspAction Receive Peer HT Capable STA from %02x:%02x:%02x:%02x:%02x:%02x\n",
-								SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-
-					if ((HtCapability.HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-						pAd->MacTab.fAnyStationNonGF = TRUE;
-						pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
-					}
-
-					if ((HtCapability.HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
-					{
-						pEntry->MaxHTPhyMode.field.BW= BW_40;
-						pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(HtCapability.HtCapInfo.ShortGIfor40));
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.BW = BW_20;
-						pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(HtCapability.HtCapInfo.ShortGIfor20));
-						pAd->MacTab.fAnyStation20Only = TRUE;
-					}
-
-					// find max fixed rate
-					for (ii=15; ii>=0; ii--)
-					{
-						j = ii/8;
-						bitmask = (1<<(ii-(j*8)));
-						if ( (pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j]&bitmask) && (HtCapability.MCSSet[j]&bitmask))
-						{
-							pEntry->MaxHTPhyMode.field.MCS = ii;
-							break;
-						}
-						if (ii==0)
-							break;
-					}
-
-					if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
-					{
-						if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
-						{
-							// Fix MCS as HT Duplicated Mode
-							pEntry->MaxHTPhyMode.field.BW = 1;
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-							pEntry->MaxHTPhyMode.field.STBC = 0;
-							pEntry->MaxHTPhyMode.field.ShortGI = 0;
-							pEntry->MaxHTPhyMode.field.MCS = 32;
-						}
-						else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
-						{
-							// STA supports fixed MCS
-							pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
-						}
-					}
-
-					pEntry->MaxHTPhyMode.field.STBC = (HtCapability.HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
-					pEntry->MpduDensity = HtCapability.HtCapParm.MpduDensity;
-					pEntry->MaxRAmpduFactor = HtCapability.HtCapParm.MaxRAmpduFactor;
-					pEntry->MmpsMode = (UCHAR)HtCapability.HtCapInfo.MimoPs;
-					pEntry->AMsduSize = (UCHAR)HtCapability.HtCapInfo.AMsduSize;
-					pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-
-					if (HtCapability.HtCapInfo.ShortGIfor20)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
-					if (HtCapability.HtCapInfo.ShortGIfor40)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
-					if (HtCapability.HtCapInfo.TxSTBC)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
-					if (HtCapability.HtCapInfo.RxSTBC)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
-					if (HtCapability.ExtHtCapInfo.PlusHTC)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
-					if (pAd->CommonCfg.bRdg && HtCapability.ExtHtCapInfo.RDGSupport)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
-					if (HtCapability.ExtHtCapInfo.MCSFeedback == 0x03)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
-
-					NdisMoveMemory(&pEntry->HTCapability, &HtCapability, sizeof(HT_CAPABILITY_IE));
-				}
-#endif // DOT11_N_SUPPORT //
-				pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-				pEntry->CurrTxRate = pEntry->MaxSupportedRate;
-				CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-
-				if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-				{
-					PUCHAR pTable;
-					UCHAR TableSize = 0;
-
-					MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
-					pEntry->bAutoTxRateSwitch = TRUE;
-				}
-				else
-				{
-					pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-					pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
-					pEntry->bAutoTxRateSwitch = FALSE;
-
-					RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-				}
-				pEntry->RateLen = SupportedRatesLen;
-
-				if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-				{
-					// If support WPA or WPA2, start STAKey hand shake,
-					// If failed hand shake, just tear down peer DLS
-					if (RTMPSendSTAKeyRequest(pAd, pAd->StaCfg.DLSEntry[i].MacAddr) != NDIS_STATUS_SUCCESS)
-					{
-						MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-						USHORT				reason = REASON_QOS_CIPHER_NOT_SUPPORT;
-
-						DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-						MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-						pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-						pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-						DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed when call RTMPSendSTAKeyRequest \n"));
-					}
-					else
-					{
-						pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-						DBGPRINT(RT_DEBUG_TRACE,("DLS - waiting for STAKey handshake procedure\n"));
-					}
-				}
-				else
-				{
-					RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-					pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-					DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() from %02x:%02x:%02x:%02x:%02x:%02x Succeed with WEP or no security\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-				}
-
-				//initialize seq no for DLS frames.
-				pAd->StaCfg.DLSEntry[i].Sequence = 0;
-				if (HtCapabilityLen != 0)
-					pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-				else
-					pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-			}
-			else
-			{
-				// DLS setup procedure failed.
-				pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-				DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed with StatusCode=%d \n", StatusCode));
-			}
-		}
-	}
-
-	if (i >= MAX_NUM_OF_INIT_DLS_ENTRY)
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() update timeout value \n"));
-		for (i=(MAX_NUM_OF_DLS_ENTRY-1); i>=MAX_NUM_OF_INIT_DLS_ENTRY; i--)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				if (StatusCode == MLME_SUCCESS)
-				{
-					MAC_TABLE_ENTRY *pEntry;
-					UCHAR MaxSupportedRate = RATE_11;
-
-					pEntry = MacTableInsertDlsEntry(pAd, SA, i);
-
-					switch (MaxSupportedRateIn500Kbps)
-					{
-						case 108: MaxSupportedRate = RATE_54;   break;
-						case 96:  MaxSupportedRate = RATE_48;   break;
-						case 72:  MaxSupportedRate = RATE_36;   break;
-						case 48:  MaxSupportedRate = RATE_24;   break;
-						case 36:  MaxSupportedRate = RATE_18;   break;
-						case 24:  MaxSupportedRate = RATE_12;   break;
-						case 18:  MaxSupportedRate = RATE_9;    break;
-						case 12:  MaxSupportedRate = RATE_6;    break;
-						case 22:  MaxSupportedRate = RATE_11;   break;
-						case 11:  MaxSupportedRate = RATE_5_5;  break;
-						case 4:   MaxSupportedRate = RATE_2;    break;
-						case 2:   MaxSupportedRate = RATE_1;    break;
-						default:  MaxSupportedRate = RATE_11;   break;
-					}
-
-					pEntry->MaxSupportedRate = min(pAd->CommonCfg.MaxTxRate, MaxSupportedRate);
-
-					if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->HTPhyMode.field.MODE = MODE_CCK;
-						pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->HTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					}
-
-					pEntry->MaxHTPhyMode.field.BW = BW_20;
-					pEntry->MinHTPhyMode.field.BW = BW_20;
-
-#ifdef DOT11_N_SUPPORT
-					pEntry->HTCapability.MCSSet[0] = 0;
-					pEntry->HTCapability.MCSSet[1] = 0;
-
-					// If this Entry supports 802.11n, upgrade to HT rate.
-					if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-					{
-						UCHAR	j, bitmask; //k,bitmask;
-						CHAR    ii;
-
-						DBGPRINT(RT_DEBUG_OFF, ("DLS - PeerDlsRspAction Receive Peer HT Capable STA from %02x:%02x:%02x:%02x:%02x:%02x\n",
-									SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-
-						if ((HtCapability.HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-							pAd->MacTab.fAnyStationNonGF = TRUE;
-							pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
-						}
-
-						if ((HtCapability.HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
-						{
-							pEntry->MaxHTPhyMode.field.BW= BW_40;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(HtCapability.HtCapInfo.ShortGIfor40));
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.BW = BW_20;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(HtCapability.HtCapInfo.ShortGIfor20));
-							pAd->MacTab.fAnyStation20Only = TRUE;
-						}
-
-						// find max fixed rate
-						for (ii=15; ii>=0; ii--)
-						{
-							j = ii/8;
-							bitmask = (1<<(ii-(j*8)));
-							if ( (pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j]&bitmask) && (HtCapability.MCSSet[j]&bitmask))
-							{
-								pEntry->MaxHTPhyMode.field.MCS = ii;
-								break;
-							}
-							if (ii==0)
-								break;
-						}
-
-						if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
-						{
-							printk("@@@ pAd->CommonCfg.RegTransmitSetting.field.MCS = %d\n",
-								pAd->StaCfg.DesiredTransmitSetting.field.MCS);
-							if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
-							{
-								// Fix MCS as HT Duplicated Mode
-								pEntry->MaxHTPhyMode.field.BW = 1;
-								pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-								pEntry->MaxHTPhyMode.field.STBC = 0;
-								pEntry->MaxHTPhyMode.field.ShortGI = 0;
-								pEntry->MaxHTPhyMode.field.MCS = 32;
-							}
-							else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
-							{
-								// STA supports fixed MCS
-								pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
-							}
-						}
-
-						pEntry->MaxHTPhyMode.field.STBC = (HtCapability.HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
-						pEntry->MpduDensity = HtCapability.HtCapParm.MpduDensity;
-						pEntry->MaxRAmpduFactor = HtCapability.HtCapParm.MaxRAmpduFactor;
-						pEntry->MmpsMode = (UCHAR)HtCapability.HtCapInfo.MimoPs;
-						pEntry->AMsduSize = (UCHAR)HtCapability.HtCapInfo.AMsduSize;
-						pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-
-						if (HtCapability.HtCapInfo.ShortGIfor20)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
-						if (HtCapability.HtCapInfo.ShortGIfor40)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
-						if (HtCapability.HtCapInfo.TxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
-						if (HtCapability.HtCapInfo.RxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.PlusHTC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
-						if (pAd->CommonCfg.bRdg && HtCapability.ExtHtCapInfo.RDGSupport)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.MCSFeedback == 0x03)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
-
-						NdisMoveMemory(&pEntry->HTCapability, &HtCapability, sizeof(HT_CAPABILITY_IE));
-					}
-#endif // DOT11_N_SUPPORT //
-
-					pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-					pEntry->CurrTxRate = pEntry->MaxSupportedRate;
-					CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-
-					if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-					{
-						PUCHAR pTable;
-						UCHAR TableSize = 0;
-
-						MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
-						pEntry->bAutoTxRateSwitch = TRUE;
-					}
-					else
-					{
-						pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-						pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
-						pEntry->bAutoTxRateSwitch = FALSE;
-
-						RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-					}
-					pEntry->RateLen = SupportedRatesLen;
-
-					if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-					{
-						// If support WPA or WPA2, start STAKey hand shake,
-						// If failed hand shake, just tear down peer DLS
-						if (RTMPSendSTAKeyRequest(pAd, pAd->StaCfg.DLSEntry[i].MacAddr) != NDIS_STATUS_SUCCESS)
-						{
-							MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-							USHORT				reason = REASON_QOS_CIPHER_NOT_SUPPORT;
-
-							DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-							MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-							pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-							pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-							DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed when call RTMPSendSTAKeyRequest \n"));
-						}
-						else
-						{
-							pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-							DBGPRINT(RT_DEBUG_TRACE,("DLS - waiting for STAKey handshake procedure\n"));
-						}
-					}
-					else
-					{
-						RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-						pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-						DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() from %02x:%02x:%02x:%02x:%02x:%02x Succeed with WEP or no security\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-					}
-					pAd->StaCfg.DLSEntry[i].Sequence = 0;
-					if (HtCapabilityLen != 0)
-						pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-					else
-						pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-				}
-				else
-				{
-					// DLS setup procedure failed.
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-					RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-					DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed with StatusCode=%d \n", StatusCode));
-				}
-			}
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeDlsTearDownAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen = 0;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_TEARDOWN;
-	USHORT			ReasonCode = REASON_QOS_UNSPECIFY;
-	HEADER_802_11	DlsTearDownHdr;
-	PRT_802_11_DLS	pDLS;
-	BOOLEAN			TimerCancelled;
-	UCHAR			i;
-
-	if(!MlmeDlsReqSanity(pAd, Elem->Msg, Elem->MsgLen, &pDLS, &ReasonCode))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - MlmeDlsTearDownAction() with ReasonCode=%d \n", ReasonCode));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("DLS - MlmeDlsTearDownAction() allocate memory failed \n"));
-		return;
-	}
-
-	ActHeaderInit(pAd, &DlsTearDownHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-
-	// Build basic frame first
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-					sizeof(HEADER_802_11),		&DlsTearDownHdr,
-					1,							&Category,
-					1,							&Action,
-					6,							&pDLS->MacAddr,
-					6,							pAd->CurrentAddress,
-					2,							&ReasonCode,
-					END_OF_ARGS);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-	RTMPCancelTimer(&pDLS->Timer, &TimerCancelled);
-
-	// Remove key in local dls table entry
-	for (i = 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	// clear peer dls table entry
-	for (i = MAX_NUM_OF_INIT_DLS_ENTRY; i < MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-			pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerDlsTearDownAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR			DA[MAC_ADDR_LEN], SA[MAC_ADDR_LEN];
-	USHORT			ReasonCode;
-	UINT			i;
-	BOOLEAN			TimerCancelled;
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return;
-
-	if (!INFRA_ON(pAd))
-		return;
-
-	if (!PeerDlsTearDownSanity(pAd, Elem->Msg, Elem->MsgLen, DA, SA, &ReasonCode))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsTearDownAction() from %02x:%02x:%02x:%02x:%02x:%02x with ReasonCode=%d\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5], ReasonCode));
-
-	// clear local dls table entry
-	for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-			pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-			//AsicDelWcidTab(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			//AsicRemovePairwiseKeyEntry(pAd, BSS0, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	// clear peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-			pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-			//AsicDelWcidTab(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			//AsicRemovePairwiseKeyEntry(pAd, BSS0, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID RTMPCheckDLSTimeOut(
-	IN PRTMP_ADAPTER	pAd)
-{
-	ULONG				i;
-	MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-	USHORT				reason = REASON_QOS_UNSPECIFY;
-
-	if (! pAd->CommonCfg.bDLSCapable)
-		return;
-
-	if (! INFRA_ON(pAd))
-		return;
-
-	// If timeout value is equaled to zero, it means always not be timeout.
-
-	// update local dls table entry
-	for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if ((pAd->StaCfg.DLSEntry[i].Valid) && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& (pAd->StaCfg.DLSEntry[i].TimeOut != 0))
-		{
-			pAd->StaCfg.DLSEntry[i].CountDownTimer --;
-
-			if (pAd->StaCfg.DLSEntry[i].CountDownTimer == 0)
-			{
-				reason = REASON_QOS_REQUEST_TIMEOUT;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-			}
-		}
-	}
-
-	// update peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if ((pAd->StaCfg.DLSEntry[i].Valid) && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& (pAd->StaCfg.DLSEntry[i].TimeOut != 0))
-		{
-			pAd->StaCfg.DLSEntry[i].CountDownTimer --;
-
-			if (pAd->StaCfg.DLSEntry[i].CountDownTimer == 0)
-			{
-				reason = REASON_QOS_REQUEST_TIMEOUT;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-			}
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN RTMPRcvFrameDLSCheck(
-	IN PRTMP_ADAPTER	pAd,
-	IN PHEADER_802_11	pHeader,
-	IN ULONG			Len,
-	IN PRT28XX_RXD_STRUC	pRxD)
-{
-	ULONG			i;
-	BOOLEAN			bFindEntry = FALSE;
-	BOOLEAN			bSTAKeyFrame = FALSE;
-	PEAPOL_PACKET	pEap;
-	PUCHAR			pProto, pAddr = NULL;
-	PUCHAR			pSTAKey = NULL;
-	UCHAR			ZeroReplay[LEN_KEY_DESC_REPLAY];
-	UCHAR			Mic[16], OldMic[16];
-	UCHAR			digest[80];
-	UCHAR			DlsPTK[80];
-	UCHAR			temp[64];
-	BOOLEAN			TimerCancelled;
-	CIPHER_KEY		PairwiseKey;
-
-
-	if (! pAd->CommonCfg.bDLSCapable)
-		return bSTAKeyFrame;
-
-	if (! INFRA_ON(pAd))
-		return bSTAKeyFrame;
-
-	if (! (pHeader->FC.SubType & 0x08))
-		return bSTAKeyFrame;
-
-	if (Len < LENGTH_802_11 + 6 + 2 + 2)
-		return bSTAKeyFrame;
-
-	pProto	= (PUCHAR)pHeader + LENGTH_802_11 + 2 + 6;	// QOS Control field , 0xAA 0xAA 0xAA 0x00 0x00 0x00
-	pAddr	= pHeader->Addr2;
-
-	// L2PAD bit on will pad 2 bytes at LLC
-	if (pRxD->L2PAD)
-	{
-		pProto += 2;
-	}
-
-	if (RTMPEqualMemory(EAPOL, pProto, 2) && (pAd->StaCfg.AuthMode >=  Ndis802_11AuthModeWPA))
-	{
-		pEap = (PEAPOL_PACKET) (pProto + 2);
-
-		DBGPRINT(RT_DEBUG_TRACE,("DLS - Sniff Len=%ld, DataLen=%d, KeyMic=%d, Install=%d, KeyAck=%d, Secure=%d, EKD_DL=%d, Error=%d, Request=%d\n", Len,
-			                                                             (LENGTH_802_11 + 6 + 2 + 2 + sizeof(EAPOL_PACKET) - MAX_LEN_OF_RSNIE + 16),
-			                                                             pEap->KeyDesc.KeyInfo.KeyMic,
-			                                                             pEap->KeyDesc.KeyInfo.Install,
-			                                                             pEap->KeyDesc.KeyInfo.KeyAck,
-			                                                             pEap->KeyDesc.KeyInfo.Secure,
-			                                                             pEap->KeyDesc.KeyInfo.EKD_DL,
-			                                                             pEap->KeyDesc.KeyInfo.Error,
-			                                                             pEap->KeyDesc.KeyInfo.Request));
-
-		if ((Len >= (LENGTH_802_11 + 6 + 2 + 2 + sizeof(EAPOL_PACKET) - MAX_LEN_OF_RSNIE + 16)) && pEap->KeyDesc.KeyInfo.KeyMic
-			&& pEap->KeyDesc.KeyInfo.Install && pEap->KeyDesc.KeyInfo.KeyAck && pEap->KeyDesc.KeyInfo.Secure
-			&& pEap->KeyDesc.KeyInfo.EKD_DL && !pEap->KeyDesc.KeyInfo.Error && !pEap->KeyDesc.KeyInfo.Request)
-		{
-			// First validate replay counter, only accept message with larger replay counter
-			// Let equal pass, some AP start with all zero replay counter
-			NdisZeroMemory(ZeroReplay, LEN_KEY_DESC_REPLAY);
-			if ((RTMPCompareMemory(pEap->KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1) &&
-				(RTMPCompareMemory(pEap->KeyDesc.ReplayCounter, ZeroReplay, LEN_KEY_DESC_REPLAY) != 0))
-				return bSTAKeyFrame;
-
-			//RTMPMoveMemory(pAd->StaCfg.ReplayCounter, pEap->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-			RTMPMoveMemory(pAd->StaCfg.DlsReplayCounter, pEap->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - Sniff replay counter (%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x) Len=%ld, KeyDataLen=%d\n",
-				pAd->StaCfg.ReplayCounter[0], pAd->StaCfg.ReplayCounter[1], pAd->StaCfg.ReplayCounter[2],
-				pAd->StaCfg.ReplayCounter[3], pAd->StaCfg.ReplayCounter[4],	pAd->StaCfg.ReplayCounter[5],
-				pAd->StaCfg.ReplayCounter[6], pAd->StaCfg.ReplayCounter[7], Len, pEap->KeyDesc.KeyData[1]));
-
-			// put these code segment to get the replay counter
-			if (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED)
-				return bSTAKeyFrame;
-
-			// Check MIC value
-			// Save the MIC and replace with zero
-			// use proprietary PTK
-			NdisZeroMemory(temp, 64);
-			NdisMoveMemory(temp, "IEEE802.11 WIRELESS ACCESS POINT", 32);
-			WpaCountPTK(pAd, temp, temp, pAd->CommonCfg.Bssid, temp, pAd->CurrentAddress, DlsPTK, LEN_PTK);
-
-			NdisMoveMemory(OldMic, pEap->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-			NdisZeroMemory(pEap->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-			if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-			{
-				// AES
-				HMAC_SHA1((PUCHAR) pEap, pEap->Body_Len[1] + 4, DlsPTK, LEN_EAP_MICK, digest);
-				NdisMoveMemory(Mic,	digest,	LEN_KEY_DESC_MIC);
-			}
-			else
-			{
-				hmac_md5(DlsPTK, LEN_EAP_MICK, (PUCHAR) pEap, pEap->Body_Len[1] + 4, Mic);
-			}
-
-			if (!NdisEqualMemory(OldMic, Mic, LEN_KEY_DESC_MIC))
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("MIC Different in Msg1 of STAKey handshake! \n"));
-				return bSTAKeyFrame;
-			}
-			else
-				DBGPRINT(RT_DEBUG_TRACE, ("MIC VALID in Msg1 of STAKey handshake! \n"));
-#if 1
-			if ((pEap->KeyDesc.KeyData[0] == 0xDD) && (pEap->KeyDesc.KeyData[2] == 0x00) && (pEap->KeyDesc.KeyData[3] == 0x0C)
-				&& (pEap->KeyDesc.KeyData[4] == 0x43) && (pEap->KeyDesc.KeyData[5] == 0x02))
-			{
-				pAddr			= pEap->KeyDesc.KeyData + 8;		// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2)
-				pSTAKey			= pEap->KeyDesc.KeyData + 14;	// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2), STAKey_Mac_Addr(6)
-
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 from %02x:%02x:%02x:%02x:%02x:%02x Len=%ld, KeyDataLen=%d\n",
-					pAddr[0], pAddr[1], pAddr[2], pAddr[3], pAddr[4], pAddr[5], Len, pEap->KeyDesc.KeyData[1]));
-
-				bSTAKeyFrame = TRUE;
-			}
-#else
-			if ((pEap->KeyDesc.KeyData[0] == 0xDD) && (pEap->KeyDesc.KeyData[2] == 0x00) && (pEap->KeyDesc.KeyData[3] == 0x0F)
-				&& (pEap->KeyDesc.KeyData[4] == 0xAC) && (pEap->KeyDesc.KeyData[5] == 0x02))
-			{
-				pAddr			= pEap->KeyDesc.KeyData + 8;		// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2)
-				pSTAKey			= pEap->KeyDesc.KeyData + 14;	// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2), STAKey_Mac_Addr(6)
-
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 from %02x:%02x:%02x:%02x:%02x:%02x Len=%d, KeyDataLen=%d\n",
-					pAddr[0], pAddr[1], pAddr[2], pAddr[3], pAddr[4], pAddr[5], Len, pEap->KeyDesc.KeyData[1]));
-
-				bSTAKeyFrame = TRUE;
-			}
-#endif
-
-		}
-		else if (Len >= (LENGTH_802_11 + 6 + 2 + 2 + sizeof(EAPOL_PACKET) - MAX_LEN_OF_RSNIE))
-		{
-#if 0
-			RTMPMoveMemory(pAd->StaCfg.ReplayCounter, pEap->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-#endif
-			RTMPMoveMemory(pAd->StaCfg.DlsReplayCounter, pEap->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - Sniff replay counter 2(%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x) Len=%ld, KeyDataLen=%d\n",
-				pAd->StaCfg.ReplayCounter[0], pAd->StaCfg.ReplayCounter[1], pAd->StaCfg.ReplayCounter[2],
-				pAd->StaCfg.ReplayCounter[3], pAd->StaCfg.ReplayCounter[4],	pAd->StaCfg.ReplayCounter[5],
-				pAd->StaCfg.ReplayCounter[6], pAd->StaCfg.ReplayCounter[7], Len, pEap->KeyDesc.KeyData[1]));
-
-		}
-	}
-
-	// If timeout value is equaled to zero, it means always not be timeout.
-	// update local dls table entry
-	for (i= 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(pAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			if (bSTAKeyFrame)
-			{
-				PMAC_TABLE_ENTRY pEntry;
-
-				// STAKey frame, add pairwise key table
-				pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-				RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-
-				PairwiseKey.KeyLen = LEN_TKIP_EK;
-				NdisMoveMemory(PairwiseKey.Key, &pSTAKey[0], LEN_TKIP_EK);
-				NdisMoveMemory(PairwiseKey.TxMic, &pSTAKey[16], LEN_TKIP_RXMICK);
-				NdisMoveMemory(PairwiseKey.RxMic, &pSTAKey[24], LEN_TKIP_TXMICK);
-
-				PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg;
-
-				pEntry = DlsEntryTableLookup(pAd, pAd->StaCfg.DLSEntry[i].MacAddr, TRUE);
-				//AsicAddKeyEntry(pAd, (USHORT)(i + 2), BSS0, 0, &PairwiseKey, TRUE, TRUE);	// reserve 0 for multicast, 1 for unicast
-				//AsicUpdateRxWCIDTable(pAd, (USHORT)(i + 2), pAddr);
-				// Add Pair-wise key to Asic
-#ifdef RT2870
-				{
-					RT_ADD_PAIRWISE_KEY_ENTRY KeyInfo;
-					COPY_MAC_ADDR(KeyInfo.MacAddr,pAd->StaCfg.DLSEntry[i].MacAddr);
-					KeyInfo.MacTabMatchWCID=pAd->StaCfg.DLSEntry[i].MacTabMatchWCID;
-					NdisMoveMemory(&KeyInfo.CipherKey,  &PairwiseKey,sizeof(CIPHER_KEY));
-					RTUSBEnqueueInternalCmd(pAd, RT_CMD_SET_KEY_TABLE, &KeyInfo, sizeof(RT_ADD_PAIRWISE_KEY_ENTRY));
-				}
-				{
-					PMAC_TABLE_ENTRY pDLSEntry;
-					pDLSEntry = DlsEntryTableLookup(pAd, pAd->StaCfg.DLSEntry[i].MacAddr, TRUE);
-					pDLSEntry->PairwiseKey.CipherAlg=PairwiseKey.CipherAlg;
-					RTUSBEnqueueInternalCmd(pAd, RT_CMD_SET_RX_WCID_TABLE, pDLSEntry, sizeof(MAC_TABLE_ENTRY));
-				}
-#endif // RT2870 //
-				NdisMoveMemory(&pEntry->PairwiseKey, &PairwiseKey, sizeof(CIPHER_KEY));
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 (Peer STA MAC Address STAKey) \n"));
-
-				RTMPSendSTAKeyHandShake(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Finish STAKey handshake procedure (Initiator side)\n"));
-			}
-			else
-			{
-				// Data frame, update timeout value
-				if (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-				{
-					pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-					//AsicUpdateRxWCIDTable(pAd, (USHORT)(i + 2), pAddr);
-				}
-			}
-
-			bFindEntry = TRUE;
-		}
-	}
-
-	// update peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(pAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			if (bSTAKeyFrame)
-			{
-				PMAC_TABLE_ENTRY pEntry = NULL;
-
-				// STAKey frame, add pairwise key table, and send STAkey Msg-2
-				pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-				RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-
-				PairwiseKey.KeyLen = LEN_TKIP_EK;
-				NdisMoveMemory(PairwiseKey.Key, &pSTAKey[0], LEN_TKIP_EK);
-				NdisMoveMemory(PairwiseKey.TxMic, &pSTAKey[16], LEN_TKIP_RXMICK);
-				NdisMoveMemory(PairwiseKey.RxMic, &pSTAKey[24], LEN_TKIP_TXMICK);
-
-				PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg;
-
-				pEntry = DlsEntryTableLookup(pAd, pAd->StaCfg.DLSEntry[i].MacAddr, TRUE);
-				//AsicAddKeyEntry(pAd, (USHORT)(i + 2), BSS0, 0, &PairwiseKey, TRUE, TRUE);	// reserve 0 for multicast, 1 for unicast
-				//AsicUpdateRxWCIDTable(pAd, (USHORT)(i + 2), pAddr);
-				// Add Pair-wise key to Asic
-#ifdef RT2870
-				{
-					RT_ADD_PAIRWISE_KEY_ENTRY KeyInfo;
-					COPY_MAC_ADDR(KeyInfo.MacAddr,pAd->StaCfg.DLSEntry[i].MacAddr);
-					KeyInfo.MacTabMatchWCID=pAd->StaCfg.DLSEntry[i].MacTabMatchWCID;
-					NdisMoveMemory(&KeyInfo.CipherKey,  &PairwiseKey,sizeof(CIPHER_KEY));
-					RTUSBEnqueueInternalCmd(pAd, RT_CMD_SET_KEY_TABLE, &KeyInfo, sizeof(RT_ADD_PAIRWISE_KEY_ENTRY));
-				}
-				{
-					PMAC_TABLE_ENTRY pDLSEntry;
-					pDLSEntry = DlsEntryTableLookup(pAd, pAd->StaCfg.DLSEntry[i].MacAddr, TRUE);
-					pDLSEntry->PairwiseKey.CipherAlg=PairwiseKey.CipherAlg;
-					RTUSBEnqueueInternalCmd(pAd, RT_CMD_SET_RX_WCID_TABLE, pDLSEntry, sizeof(MAC_TABLE_ENTRY));
-				}
-#endif // RT2870 //
-				NdisMoveMemory(&pEntry->PairwiseKey, &PairwiseKey, sizeof(CIPHER_KEY));
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 (Initiator STA MAC Address STAKey)\n"));
-
-				// If support WPA or WPA2, start STAKey hand shake,
-				// If failed hand shake, just tear down peer DLS
-				if (RTMPSendSTAKeyHandShake(pAd, pAddr) != NDIS_STATUS_SUCCESS)
-				{
-					MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-					USHORT				reason = REASON_QOS_CIPHER_NOT_SUPPORT;
-
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-					pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-					DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-					MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE,("DLS - Finish STAKey handshake procedure (Peer side)\n"));
-				}
-			}
-			else
-			{
-				// Data frame, update timeout value
-				if (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-				{
-					pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-				}
-			}
-
-			bFindEntry = TRUE;
-		}
-	}
-
-
-	return bSTAKeyFrame;
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Check if the frame can be sent through DLS direct link interface
-
-	Arguments:
-		pAd		Pointer	to adapter
-
-	Return Value:
-		DLS entry index
-
-	Note:
-
-	========================================================================
-*/
-INT	RTMPCheckDLSFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA)
-{
-	INT rval = -1;
-	INT	i;
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return rval;
-
-	if (!INFRA_ON(pAd))
-		return rval;
-
-	do{
-		// check local dls table entry
-		for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				rval = i;
-				break;
-			}
-		}
-
-		// check peer dls table entry
-		for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				rval = i;
-				break;
-			}
-		}
-	} while (FALSE);
-
-	return rval;
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID RTMPSendDLSTearDownFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	HEADER_802_11	DlsTearDownHdr;
-	ULONG			FrameLen = 0;
-	USHORT			Reason = REASON_QOS_QSTA_LEAVING_QBSS;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_TEARDOWN;
-	UCHAR			i = 0;
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS) ||
-		RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Send DLS TearDown Frame \n"));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("ASSOC - RTMPSendDLSTearDownFrame() allocate memory failed \n"));
-		return;
-	}
-
-	ActHeaderInit(pAd, &DlsTearDownHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-					sizeof(HEADER_802_11),		&DlsTearDownHdr,
-					1,							&Category,
-					1,							&Action,
-					6,							pDA,
-					6,							pAd->CurrentAddress,
-					2,							&Reason,
-					END_OF_ARGS);
-
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	// Remove key in local dls table entry
-	for (i = 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	// Remove key in peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Send DLS TearDown Frame and remove key in (i=%d) \n", i));
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-NDIS_STATUS RTMPSendSTAKeyRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA)
-{
-	UCHAR				Header802_3[14];
-	NDIS_STATUS			NStatus;
-	ULONG				FrameLen = 0;
-	EAPOL_PACKET		Packet;
-	UCHAR				Mic[16];
-	UCHAR				digest[80];
-	PUCHAR				pOutBuffer = NULL;
-	PNDIS_PACKET		pNdisPacket;
-	UCHAR				temp[64];
-	UCHAR				DlsPTK[80];
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - RTMPSendSTAKeyRequest() to %02x:%02x:%02x:%02x:%02x:%02x\n", pDA[0], pDA[1], pDA[2], pDA[3], pDA[4], pDA[5]));
-
-	pAd->Sequence ++;
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero message body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer = EAPOL_VER;
-	Packet.ProType    = EAPOLKey;
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE + 6 + MAC_ADDR_LEN;		// data field contain KDE andPeer MAC address
-
-	// STAKey Message is as EAPOL-Key(1,1,0,0,G/0,0,0, MIC, 0,Peer MAC KDE)
-	if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-    {
-        Packet.KeyDesc.Type = WPA1_KEY_DESC;
-    }
-    else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-    {
-        Packet.KeyDesc.Type = WPA2_KEY_DESC;
-    }
-
-	// Key descriptor version
-	Packet.KeyDesc.KeyInfo.KeyDescVer =
-		(((pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled) || (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)) ? (DESC_TYPE_AES) : (DESC_TYPE_TKIP));
-
-	Packet.KeyDesc.KeyInfo.KeyMic	= 1;
-	Packet.KeyDesc.KeyInfo.Secure	= 1;
-	Packet.KeyDesc.KeyInfo.Request	= 1;
-
-	Packet.KeyDesc.KeyDataLen[1]	= 12;
-
-	// use our own OUI to distinguish proprietary with standard.
-	Packet.KeyDesc.KeyData[0]		= 0xDD;
-	Packet.KeyDesc.KeyData[1]		= 0x0A;
-	Packet.KeyDesc.KeyData[2]		= 0x00;
-	Packet.KeyDesc.KeyData[3]		= 0x0C;
-	Packet.KeyDesc.KeyData[4]		= 0x43;
-	Packet.KeyDesc.KeyData[5]		= 0x03;
-	NdisMoveMemory(&Packet.KeyDesc.KeyData[6], pDA, MAC_ADDR_LEN);
-
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.DlsReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Allocate buffer for transmitting message
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-	if (NStatus	!= NDIS_STATUS_SUCCESS)
-		return NStatus;
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		              Packet.Body_Len[1] + 4,    &Packet,
-		              END_OF_ARGS);
-
-	// use proprietary PTK
-	NdisZeroMemory(temp, 64);
-	NdisMoveMemory(temp, "IEEE802.11 WIRELESS ACCESS POINT", 32);
-	WpaCountPTK(pAd, temp, temp, pAd->CommonCfg.Bssid, temp, pAd->CurrentAddress, DlsPTK, LEN_PTK);
-
-	// calculate MIC
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		NdisZeroMemory(digest,	sizeof(digest));
-		HMAC_SHA1(pOutBuffer, FrameLen, DlsPTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		NdisZeroMemory(Mic,	sizeof(Mic));
-		hmac_md5(DlsPTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-	}
-
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-	                  sizeof(Header802_3),	Header802_3,
-		              Packet.Body_Len[1] + 4,	&Packet,
-		              END_OF_ARGS);
-
-	NStatus = RTMPAllocateNdisPacket(pAd, &pNdisPacket, NULL, 0, pOutBuffer, FrameLen);
-	if (NStatus == NDIS_STATUS_SUCCESS)
-	{
-		RTMP_SET_PACKET_WCID(pNdisPacket, BSSID_WCID);
-		STASendPacket(pAd, pNdisPacket);
-		RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSendSTAKeyRequest- Send STAKey request (NStatus=%x, FrameLen=%ld)\n", NStatus, FrameLen));
-
-	return NStatus;
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-NDIS_STATUS RTMPSendSTAKeyHandShake(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA)
-{
-	UCHAR				Header802_3[14];
-	NDIS_STATUS			NStatus;
-	ULONG				FrameLen = 0;
-	EAPOL_PACKET		Packet;
-	UCHAR				Mic[16];
-	UCHAR				digest[80];
-	PUCHAR				pOutBuffer = NULL;
-	PNDIS_PACKET		pNdisPacket;
-	UCHAR				temp[64];
-	UCHAR				DlsPTK[80];			// Due to dirver can not get PTK, use proprietary PTK
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - RTMPSendSTAKeyHandShake() to %02x:%02x:%02x:%02x:%02x:%02x\n", pDA[0], pDA[1], pDA[2], pDA[3], pDA[4], pDA[5]));
-
-	pAd->Sequence ++;
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero message body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer = EAPOL_VER;
-	Packet.ProType    = EAPOLKey;
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE + 6 + MAC_ADDR_LEN;		// data field contain KDE and Peer MAC address
-
-	// STAKey Message is as EAPOL-Key(1,1,0,0,G/0,0,0, MIC, 0,Peer MAC KDE)
-	if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-    {
-        Packet.KeyDesc.Type = WPA1_KEY_DESC;
-    }
-    else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-    {
-        Packet.KeyDesc.Type = WPA2_KEY_DESC;
-    }
-
-	// Key descriptor version
-	Packet.KeyDesc.KeyInfo.KeyDescVer =
-		(((pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled) || (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)) ? (DESC_TYPE_AES) : (DESC_TYPE_TKIP));
-
-	Packet.KeyDesc.KeyInfo.KeyMic	= 1;
-	Packet.KeyDesc.KeyInfo.Secure	= 1;
-
-	Packet.KeyDesc.KeyDataLen[1]	= 12;
-
-	// use our own OUI to distinguish proprietary with standard.
-	Packet.KeyDesc.KeyData[0]		= 0xDD;
-	Packet.KeyDesc.KeyData[1]		= 0x0A;
-	Packet.KeyDesc.KeyData[2]		= 0x00;
-	Packet.KeyDesc.KeyData[3]		= 0x0C;
-	Packet.KeyDesc.KeyData[4]		= 0x43;
-	Packet.KeyDesc.KeyData[5]		= 0x03;
-	NdisMoveMemory(&Packet.KeyDesc.KeyData[6], pDA, MAC_ADDR_LEN);
-
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.DlsReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Allocate buffer for transmitting message
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-	if (NStatus	!= NDIS_STATUS_SUCCESS)
-		return NStatus;
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		              Packet.Body_Len[1] + 4,    &Packet,
-		              END_OF_ARGS);
-
-	// use proprietary PTK
-	NdisZeroMemory(temp, 64);
-	NdisMoveMemory(temp, "IEEE802.11 WIRELESS ACCESS POINT", 32);
-	WpaCountPTK(pAd, temp, temp, pAd->CommonCfg.Bssid, temp, pAd->CurrentAddress, DlsPTK, LEN_PTK);
-
-	// calculate MIC
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		NdisZeroMemory(digest,	sizeof(digest));
-		HMAC_SHA1(pOutBuffer, FrameLen, DlsPTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		NdisZeroMemory(Mic,	sizeof(Mic));
-		hmac_md5(DlsPTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-	}
-
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-	                  sizeof(Header802_3),	Header802_3,
-		              Packet.Body_Len[1] + 4,	&Packet,
-		              END_OF_ARGS);
-
-	NStatus = RTMPAllocateNdisPacket(pAd, &pNdisPacket, NULL, 0, pOutBuffer, FrameLen);
-	if (NStatus == NDIS_STATUS_SUCCESS)
-	{
-		RTMP_SET_PACKET_WCID(pNdisPacket, BSSID_WCID);
-		STASendPacket(pAd, pNdisPacket);
-		RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSendSTAKeyHandShake- Send STAKey Message-2 (NStatus=%x, FrameLen=%ld)\n", NStatus, FrameLen));
-
-	return NStatus;
-}
-
-VOID DlsTimeoutAction(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	MLME_DLS_REQ_STRUCT		MlmeDlsReq;
-	USHORT					reason;
-	PRT_802_11_DLS			pDLS = (PRT_802_11_DLS)FunctionContext;
-	PRTMP_ADAPTER			pAd = pDLS->pAd;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("DlsTimeout - Tear down DLS links (%02x:%02x:%02x:%02x:%02x:%02x)\n",
-		pDLS->MacAddr[0], pDLS->MacAddr[1], pDLS->MacAddr[2], pDLS->MacAddr[3], pDLS->MacAddr[4], pDLS->MacAddr[5]));
-
-	if ((pDLS) && (pDLS->Valid))
-	{
-		reason			= REASON_QOS_REQUEST_TIMEOUT;
-		pDLS->Valid		= FALSE;
-		pDLS->Status	= DLS_NONE;
-		DlsParmFill(pAd, &MlmeDlsReq, pDLS, reason);
-		MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-		RT28XX_MLME_HANDLER(pAd);
-	}
-}
-
-/*
-================================================================
-Description : because DLS and CLI share the same WCID table in ASIC.
-Mesh entry also insert to pAd->MacTab.content[].  Such is marked as ValidAsDls = TRUE.
-Also fills the pairwise key.
-Because front MAX_AID_BA entries have direct mapping to BAEntry, which is only used as CLI. So we insert Dls
-from index MAX_AID_BA.
-================================================================
-*/
-MAC_TABLE_ENTRY *MacTableInsertDlsEntry(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR	pAddr,
-	IN  UINT	DlsEntryIdx)
-{
-	PMAC_TABLE_ENTRY pEntry = NULL;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("====> MacTableInsertDlsEntry\n"));
-	// if FULL, return
-	if (pAd->MacTab.Size >= MAX_LEN_OF_MAC_TABLE)
-		return NULL;
-
-	do
-	{
-		if((pEntry = DlsEntryTableLookup(pAd, pAddr, TRUE)) != NULL)
-			break;
-
-		// allocate one MAC entry
-		pEntry = MacTableInsertEntry(pAd, pAddr, DlsEntryIdx + MIN_NET_DEVICE_FOR_DLS, TRUE);
-		if (pEntry)
-		{
-			pAd->StaCfg.DLSEntry[DlsEntryIdx].MacTabMatchWCID = pEntry->Aid;
-			pEntry->MatchDlsEntryIdx = DlsEntryIdx;
-			pEntry->AuthMode = pAd->StaCfg.AuthMode;
-			pEntry->WepStatus = pAd->StaCfg.WepStatus;
-			pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("MacTableInsertDlsEntry - allocate entry #%d, Total= %d\n",pEntry->Aid, pAd->MacTab.Size));
-
-			// If legacy WEP is used, set pair-wise cipherAlg into WCID attribute table for this entry
-			if ((pEntry->ValidAsDls) && (pEntry->WepStatus == Ndis802_11WEPEnabled))
-			{
-				UCHAR KeyIdx = 0;
-				UCHAR CipherAlg = 0;
-
-				KeyIdx	= pAd->StaCfg.DefaultKeyId;
-
-				CipherAlg 	= pAd->SharedKey[BSS0][KeyIdx].CipherAlg;
-
-				RTMPAddWcidAttributeEntry(pAd,
-											BSS0,
-											pAd->StaCfg.DefaultKeyId,
-											pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-											pEntry);
-			}
-
-			break;
-		}
-	} while(FALSE);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==== MacTableInsertDlsEntry\n"));
-
-	return pEntry;
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Delete all Mesh Entry in pAd->MacTab
-	==========================================================================
- */
-BOOLEAN MacTableDeleteDlsEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT wcid,
-	IN PUCHAR pAddr)
-{
-	DBGPRINT(RT_DEBUG_TRACE, ("====> MacTableDeleteDlsEntry\n"));
-
-	if (!VALID_WCID(wcid))
-		return FALSE;
-
-	MacTableDeleteEntry(pAd, wcid, pAddr);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==== MacTableDeleteDlsEntry\n"));
-
-	return TRUE;
-}
-
-MAC_TABLE_ENTRY *DlsEntryTableLookup(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount)
-{
-	ULONG HashIdx;
-	MAC_TABLE_ENTRY *pEntry = NULL;
-
-	RTMP_SEM_LOCK(&pAd->MacTabLock);
-	HashIdx = MAC_ADDR_HASH_INDEX(pAddr);
-	pEntry = pAd->MacTab.Hash[HashIdx];
-
-	while (pEntry)
-	{
-		if ((pEntry->ValidAsDls == TRUE)
-			&& MAC_ADDR_EQUAL(pEntry->Addr, pAddr))
-		{
-			if(bResetIdelCount)
-				pEntry->NoDataIdleCount = 0;
-			break;
-		}
-		else
-			pEntry = pEntry->pNext;
-	}
-
-	RTMP_SEM_UNLOCK(&pAd->MacTabLock);
-	return pEntry;
-}
-
-MAC_TABLE_ENTRY *DlsEntryTableLookupByWcid(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR	wcid,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount)
-{
-	ULONG DLsIndex;
-	PMAC_TABLE_ENTRY pCurEntry = NULL;
-	PMAC_TABLE_ENTRY pEntry = NULL;
-
-	if (!VALID_WCID(wcid))
-		return NULL;
-
-	RTMP_SEM_LOCK(&pAd->MacTabLock);
-
-	do
-	{
-		pCurEntry = &pAd->MacTab.Content[wcid];
-
-		DLsIndex = 0xff;
-		if ((pCurEntry) && (pCurEntry->ValidAsDls== TRUE))
-		{
-			DLsIndex = pCurEntry->MatchDlsEntryIdx;
-		}
-
-		if (DLsIndex == 0xff)
-			break;
-
-		if (MAC_ADDR_EQUAL(pCurEntry->Addr, pAddr))
-		{
-			if(bResetIdelCount)
-				pCurEntry->NoDataIdleCount = 0;
-			pEntry = pCurEntry;
-			break;
-		}
-	} while(FALSE);
-
-	RTMP_SEM_UNLOCK(&pAd->MacTabLock);
-
-	return pEntry;
-}
-
-INT Set_DlsEntryInfo_Display_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg)
-{
-	INT i;
-
-	printk("\n%-19s%-8s\n", "MAC", "TIMEOUT\n");
-	for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if ((pAd->StaCfg.DLSEntry[i].Valid) && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-		{
-			PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[pAd->StaCfg.DLSEntry[i].MacTabMatchWCID];
-
-			printk("%02x:%02x:%02x:%02x:%02x:%02x  ",
-				pAd->StaCfg.DLSEntry[i].MacAddr[0], pAd->StaCfg.DLSEntry[i].MacAddr[1], pAd->StaCfg.DLSEntry[i].MacAddr[2],
-				pAd->StaCfg.DLSEntry[i].MacAddr[3], pAd->StaCfg.DLSEntry[i].MacAddr[4], pAd->StaCfg.DLSEntry[i].MacAddr[5]);
-			printk("%-8d\n", pAd->StaCfg.DLSEntry[i].TimeOut);
-
-			printk("\n");
-			printk("\n%-19s%-4s%-4s%-4s%-4s%-7s%-7s%-7s","MAC", "AID", "BSS", "PSM", "WMM", "RSSI0", "RSSI1", "RSSI2");
-#ifdef DOT11_N_SUPPORT
-			printk("%-8s%-10s%-6s%-6s%-6s%-6s", "MIMOPS", "PhMd", "BW", "MCS", "SGI", "STBC");
-#endif // DOT11_N_SUPPORT //
-			printk("\n%02X:%02X:%02X:%02X:%02X:%02X  ",
-				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
-				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5]);
-			printk("%-4d", (int)pEntry->Aid);
-			printk("%-4d", (int)pEntry->apidx);
-			printk("%-4d", (int)pEntry->PsMode);
-			printk("%-4d", (int)CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE));
-			printk("%-7d", pEntry->RssiSample.AvgRssi0);
-			printk("%-7d", pEntry->RssiSample.AvgRssi1);
-			printk("%-7d", pEntry->RssiSample.AvgRssi2);
-#ifdef DOT11_N_SUPPORT
-			printk("%-8d", (int)pEntry->MmpsMode);
-			printk("%-10s", GetPhyMode(pEntry->HTPhyMode.field.MODE));
-			printk("%-6s", GetBW(pEntry->HTPhyMode.field.BW));
-			printk("%-6d", pEntry->HTPhyMode.field.MCS);
-			printk("%-6d", pEntry->HTPhyMode.field.ShortGI);
-			printk("%-6d", pEntry->HTPhyMode.field.STBC);
-#endif // DOT11_N_SUPPORT //
-			printk("%-10d, %d, %d%%\n", pEntry->DebugFIFOCount, pEntry->DebugTxCount,
-						(pEntry->DebugTxCount) ? ((pEntry->DebugTxCount-pEntry->DebugFIFOCount)*100/pEntry->DebugTxCount) : 0);
-			printk("\n");
-
-		}
-	}
-
-	return TRUE;
-}
-
-INT	Set_DlsAddEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    UCHAR	mac[MAC_ADDR_LEN];
-	USHORT	Timeout;
-	char *token, sepValue[] = ":", DASH = '-';
-	INT i;
-    RT_802_11_DLS	Dls;
-
-    if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and timeout value in decimal format.
-		return FALSE;
-
-	token = strchr(arg, DASH);
-	if ((token != NULL) && (strlen(token)>1))
-	{
-		Timeout = simple_strtol((token+1), 0, 10);
-
-		*token = '\0';
-		for (i = 0, token = rstrtok(arg, &sepValue[0]); token; token = rstrtok(NULL, &sepValue[0]), i++)
-		{
-			if((strlen(token) != 2) || (!isxdigit(*token)) || (!isxdigit(*(token+1))))
-				return FALSE;
-			AtoH(token, (PUCHAR)(&mac[i]), 1);
-		}
-		if(i != 6)
-			return FALSE;
-
-	    printk("\n%02x:%02x:%02x:%02x:%02x:%02x-%d", mac[0], mac[1],
-	           mac[2], mac[3], mac[4], mac[5], (int)Timeout);
-
-		NdisZeroMemory(&Dls, sizeof(RT_802_11_DLS));
-		Dls.TimeOut = Timeout;
-		COPY_MAC_ADDR(Dls.MacAddr, mac);
-		Dls.Valid = 1;
-
-		MlmeEnqueue(pAd,
-					MLME_CNTL_STATE_MACHINE,
-					RT_OID_802_11_SET_DLS_PARAM,
-					sizeof(RT_802_11_DLS),
-					&Dls);
-
-		return TRUE;
-	}
-
-	return FALSE;
-
-}
-
-INT	Set_DlsTearDownEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR			macAddr[MAC_ADDR_LEN];
-	CHAR			*value;
-	INT				i;
-	RT_802_11_DLS	Dls;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-	for (i=0, value = rstrtok(arg,":"); value; value = rstrtok(NULL,":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-		AtoH(value, &macAddr[i++], 2);
-	}
-
-	printk("\n%02x:%02x:%02x:%02x:%02x:%02x", macAddr[0], macAddr[1],
-	           macAddr[2], macAddr[3], macAddr[4], macAddr[5]);
-
-	NdisZeroMemory(&Dls, sizeof(RT_802_11_DLS));
-	COPY_MAC_ADDR(Dls.MacAddr, macAddr);
-	Dls.Valid = 0;
-
-	MlmeEnqueue(pAd,
-				MLME_CNTL_STATE_MACHINE,
-				RT_OID_802_11_SET_DLS_PARAM,
-				sizeof(RT_802_11_DLS),
-				&Dls);
-
-	return TRUE;
-}
-
diff --git a/drivers/staging/rt2870/sta/rtmp_data.c b/drivers/staging/rt2870/sta/rtmp_data.c
index 9942eca..b67e069 100644
--- a/drivers/staging/rt2870/sta/rtmp_data.c
+++ b/drivers/staging/rt2870/sta/rtmp_data.c
@@ -1,2619 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtmp_data.c
-
-	Abstract:
-	Data path subroutines
-
-	Revision History:
-	Who 		When			What
-	--------	----------		----------------------------------------------
-	John		      Aug/17/04		major modification for RT2561/2661
-	Jan Lee	      Mar/17/06		major modification for RT2860 New Ring Design
-*/
-#include "../rt_config.h"
-
-
-VOID STARxEAPOLFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	PRT28XX_RXD_STRUC	pRxD = &(pRxBlk->RxD);
-	PRXWI_STRUC		pRxWI = pRxBlk->pRxWI;
-	UCHAR			*pTmpBuf;
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-	if (pAd->StaCfg.WpaSupplicantUP)
-	{
-		// All EAPoL frames have to pass to upper layer (ex. WPA_SUPPLICANT daemon)
-		// TBD : process fragmented EAPol frames
-		{
-			// In 802.1x mode, if the received frame is EAP-SUCCESS packet, turn on the PortSecured variable
-			if ( pAd->StaCfg.IEEE8021X == TRUE &&
-				 (EAP_CODE_SUCCESS == WpaCheckEapCode(pAd, pRxBlk->pData, pRxBlk->DataSize, LENGTH_802_1_H)))
-			{
-				PUCHAR	Key;
-				UCHAR 	CipherAlg;
-				int     idx = 0;
-
-				DBGPRINT_RAW(RT_DEBUG_TRACE, ("Receive EAP-SUCCESS Packet\n"));
-				//pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAd);
-
-                if (pAd->StaCfg.IEEE8021x_required_keys == FALSE)
-                {
-                    idx = pAd->StaCfg.DesireSharedKeyId;
-                    CipherAlg = pAd->StaCfg.DesireSharedKey[idx].CipherAlg;
-					Key = pAd->StaCfg.DesireSharedKey[idx].Key;
-
-                    if (pAd->StaCfg.DesireSharedKey[idx].KeyLen > 0)
-    				{
-#ifdef RT2870
-						union
-						{
-							char buf[sizeof(NDIS_802_11_WEP)+MAX_LEN_OF_KEY- 1];
-							NDIS_802_11_WEP keyinfo;
-						}  WepKey;
-						int len;
-
-
-						NdisZeroMemory(&WepKey, sizeof(WepKey));
-						len =pAd->StaCfg.DesireSharedKey[idx].KeyLen;
-
-						NdisMoveMemory(WepKey.keyinfo.KeyMaterial,
-							pAd->StaCfg.DesireSharedKey[idx].Key,
-							pAd->StaCfg.DesireSharedKey[idx].KeyLen);
-
-						WepKey.keyinfo.KeyIndex = 0x80000000 + idx;
-						WepKey.keyinfo.KeyLength = len;
-						pAd->SharedKey[BSS0][idx].KeyLen =(UCHAR) (len <= 5 ? 5 : 13);
-
-						pAd->IndicateMediaState = NdisMediaStateConnected;
-						pAd->ExtraInfo = GENERAL_LINK_UP;
-						// need to enqueue cmd to thread
-						RTUSBEnqueueCmdFromNdis(pAd, OID_802_11_ADD_WEP, TRUE, &WepKey, sizeof(WepKey.keyinfo) + len - 1);
-#endif // RT2870 //
-						// For Preventing ShardKey Table is cleared by remove key procedure.
-    					pAd->SharedKey[BSS0][idx].CipherAlg = CipherAlg;
-						pAd->SharedKey[BSS0][idx].KeyLen = pAd->StaCfg.DesireSharedKey[idx].KeyLen;
-						NdisMoveMemory(pAd->SharedKey[BSS0][idx].Key,
-									   pAd->StaCfg.DesireSharedKey[idx].Key,
-									   pAd->StaCfg.DesireSharedKey[idx].KeyLen);
-    				}
-				}
-			}
-
-			Indicate_Legacy_Packet(pAd, pRxBlk, FromWhichBSSID);
-			return;
-		}
-	}
-	else
-#endif // WPA_SUPPLICANT_SUPPORT //
-	{
-		// Special DATA frame that has to pass to MLME
-		//	 1. Cisco Aironet frames for CCX2. We need pass it to MLME for special process
-		//	 2. EAPOL handshaking frames when driver supplicant enabled, pass to MLME for special process
-		{
-			pTmpBuf = pRxBlk->pData - LENGTH_802_11;
-			NdisMoveMemory(pTmpBuf, pRxBlk->pHeader, LENGTH_802_11);
-			REPORT_MGMT_FRAME_TO_MLME(pAd, pRxWI->WirelessCliID, pTmpBuf, pRxBlk->DataSize + LENGTH_802_11, pRxWI->RSSI0, pRxWI->RSSI1, pRxWI->RSSI2, pRxD->PlcpSignal);
-			DBGPRINT_RAW(RT_DEBUG_TRACE, ("!!! report EAPOL/AIRONET DATA to MLME (len=%d) !!!\n", pRxBlk->DataSize));
-		}
-	}
-
-	RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-	return;
-
-}
-
-VOID STARxDataFrameAnnounce(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-
-	// non-EAP frame
-	if (!RTMPCheckWPAframe(pAd, pEntry, pRxBlk->pData, pRxBlk->DataSize, FromWhichBSSID))
-	{
-		{
-			// drop all non-EAP DATA frame before
-			// this client's Port-Access-Control is secured
-			if (pRxBlk->pHeader->FC.Wep)
-			{
-				// unsupported cipher suite
-				if (pAd->StaCfg.WepStatus == Ndis802_11EncryptionDisabled)
-				{
-					// release packet
-					RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-					return;
-				}
-			}
-			else
-			{
-				// encryption in-use but receive a non-EAPOL clear text frame, drop it
-				if ((pAd->StaCfg.WepStatus != Ndis802_11EncryptionDisabled) &&
-					(pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-				{
-					// release packet
-					RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-					return;
-				}
-			}
-		}
-		RX_BLK_CLEAR_FLAG(pRxBlk, fRX_EAP);
-		if (!RX_BLK_TEST_FLAG(pRxBlk, fRX_ARALINK))
-		{
-			// Normal legacy, AMPDU or AMSDU
-			CmmRxnonRalinkFrameIndicate(pAd, pRxBlk, FromWhichBSSID);
-
-		}
-		else
-		{
-			// ARALINK
-			CmmRxRalinkFrameIndicate(pAd, pEntry, pRxBlk, FromWhichBSSID);
-		}
-#ifdef QOS_DLS_SUPPORT
-		RX_BLK_CLEAR_FLAG(pRxBlk, fRX_DLS);
-#endif // QOS_DLS_SUPPORT //
-	}
-	else
-	{
-		RX_BLK_SET_FLAG(pRxBlk, fRX_EAP);
-#ifdef DOT11_N_SUPPORT
-		if (RX_BLK_TEST_FLAG(pRxBlk, fRX_AMPDU) && (pAd->CommonCfg.bDisableReordering == 0))
-		{
-			Indicate_AMPDU_Packet(pAd, pRxBlk, FromWhichBSSID);
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			// Determin the destination of the EAP frame
-			//  to WPA state machine or upper layer
-			STARxEAPOLFrameIndicate(pAd, pEntry, pRxBlk, FromWhichBSSID);
-		}
-	}
-}
-
-
-// For TKIP frame, calculate the MIC value
-BOOLEAN STACheckTkipMICValue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk)
-{
-	PHEADER_802_11	pHeader = pRxBlk->pHeader;
-	UCHAR			*pData = pRxBlk->pData;
-	USHORT			DataSize = pRxBlk->DataSize;
-	UCHAR			UserPriority = pRxBlk->UserPriority;
-	PCIPHER_KEY		pWpaKey;
-	UCHAR			*pDA, *pSA;
-
-	pWpaKey = &pAd->SharedKey[BSS0][pRxBlk->pRxWI->KeyIndex];
-
-	pDA = pHeader->Addr1;
-	if (RX_BLK_TEST_FLAG(pRxBlk, fRX_INFRA))
-	{
-		pSA = pHeader->Addr3;
-	}
-	else
-	{
-		pSA = pHeader->Addr2;
-	}
-
-	if (RTMPTkipCompareMICValue(pAd,
-								pData,
-								pDA,
-								pSA,
-								pWpaKey->RxMic,
-								UserPriority,
-								DataSize) == FALSE)
-	{
-		DBGPRINT_RAW(RT_DEBUG_ERROR,("Rx MIC Value error 2\n"));
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-		if (pAd->StaCfg.WpaSupplicantUP)
-		{
-			WpaSendMicFailureToWpaSupplicant(pAd, (pWpaKey->Type == PAIRWISEKEY) ? TRUE : FALSE);
-		}
-		else
-#endif // WPA_SUPPLICANT_SUPPORT //
-		{
-			RTMPReportMicError(pAd, pWpaKey);
-		}
-
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return FALSE;
-	}
-
-	return TRUE;
-}
-
-
-//
-// All Rx routines use RX_BLK structure to hande rx events
-// It is very important to build pRxBlk attributes
-//  1. pHeader pointer to 802.11 Header
-//  2. pData pointer to payload including LLC (just skip Header)
-//  3. set payload size including LLC to DataSize
-//  4. set some flags with RX_BLK_SET_FLAG()
-//
-VOID STAHandleRxDataFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk)
-{
-	PRT28XX_RXD_STRUC				pRxD = &(pRxBlk->RxD);
-	PRXWI_STRUC						pRxWI = pRxBlk->pRxWI;
-	PHEADER_802_11					pHeader = pRxBlk->pHeader;
-	PNDIS_PACKET					pRxPacket = pRxBlk->pRxPacket;
-	BOOLEAN 						bFragment = FALSE;
-	MAC_TABLE_ENTRY	    			*pEntry = NULL;
-	UCHAR							FromWhichBSSID = BSS0;
-	UCHAR                           UserPriority = 0;
-
-	{
-		// before LINK UP, all DATA frames are rejected
-		if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-		{
-			// release packet
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-			return;
-		}
-
-#ifdef QOS_DLS_SUPPORT
-		//if ((pHeader->FC.FrDs == 0) && (pHeader->FC.ToDs == 0))
-		if (RTMPRcvFrameDLSCheck(pAd, pHeader, pRxWI->MPDUtotalByteCount, pRxD))
-		{
-			return;
-		}
-#endif // QOS_DLS_SUPPORT //
-
-		// Drop not my BSS frames
-		if (pRxD->MyBss == 0)
-		{
-			{
-				// release packet
-				RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-				return;
-			}
-		}
-
-		pAd->RalinkCounters.RxCountSinceLastNULL++;
-		if (pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable && (pHeader->FC.SubType & 0x08))
-		{
-			UCHAR *pData;
-			DBGPRINT(RT_DEBUG_TRACE,("bAPSDCapable\n"));
-
-			// Qos bit 4
-			pData = (PUCHAR)pHeader + LENGTH_802_11;
-			if ((*pData >> 4) & 0x01)
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("RxDone- Rcv EOSP frame, driver may fall into sleep\n"));
-				pAd->CommonCfg.bInServicePeriod = FALSE;
-
-				// Force driver to fall into sleep mode when rcv EOSP frame
-				if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-				{
-					USHORT  TbttNumToNextWakeUp;
-					USHORT  NextDtim = pAd->StaCfg.DtimPeriod;
-					ULONG   Now;
-
-					NdisGetSystemUpTime(&Now);
-					NextDtim -= (USHORT)(Now - pAd->StaCfg.LastBeaconRxTime)/pAd->CommonCfg.BeaconPeriod;
-
-					TbttNumToNextWakeUp = pAd->StaCfg.DefaultListenCount;
-					if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM) && (TbttNumToNextWakeUp > NextDtim))
-						TbttNumToNextWakeUp = NextDtim;
-
-					MlmeSetPsmBit(pAd, PWR_SAVE);
-					// if WMM-APSD is failed, try to disable following line
-					AsicSleepThenAutoWakeup(pAd, TbttNumToNextWakeUp);
-				}
-			}
-
-			if ((pHeader->FC.MoreData) && (pAd->CommonCfg.bInServicePeriod))
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("Sending another trigger frame when More Data bit is set to 1\n"));
-			}
-		}
-
-		// Drop NULL, CF-ACK(no data), CF-POLL(no data), and CF-ACK+CF-POLL(no data) data frame
-		if ((pHeader->FC.SubType & 0x04)) // bit 2 : no DATA
-		{
-			// release packet
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-			return;
-		}
-
-	    // Drop not my BSS frame (we can not only check the MyBss bit in RxD)
-#ifdef QOS_DLS_SUPPORT
-	    if (!pAd->CommonCfg.bDLSCapable)
-	    {
-#endif // QOS_DLS_SUPPORT //
-		if (INFRA_ON(pAd))
-		{
-			// Infrastructure mode, check address 2 for BSSID
-			if (!RTMPEqualMemory(&pHeader->Addr2, &pAd->CommonCfg.Bssid, 6))
-			{
-				// Receive frame not my BSSID
-	            // release packet
-	            RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-				return;
-			}
-		}
-		else	// Ad-Hoc mode or Not associated
-		{
-			// Ad-Hoc mode, check address 3 for BSSID
-			if (!RTMPEqualMemory(&pHeader->Addr3, &pAd->CommonCfg.Bssid, 6))
-			{
-				// Receive frame not my BSSID
-	            // release packet
-	            RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-				return;
-			}
-		}
-#ifdef QOS_DLS_SUPPORT
-	    }
-#endif // QOS_DLS_SUPPORT //
-
-		//
-		// find pEntry
-		//
-		if (pRxWI->WirelessCliID < MAX_LEN_OF_MAC_TABLE)
-		{
-			pEntry = &pAd->MacTab.Content[pRxWI->WirelessCliID];
-		}
-		else
-		{
-			// 1. release packet if infra mode
-			// 2. new a pEntry if ad-hoc mode
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-			return;
-		}
-
-		// infra or ad-hoc
-		if (INFRA_ON(pAd))
-		{
-			RX_BLK_SET_FLAG(pRxBlk, fRX_INFRA);
-#ifdef QOS_DLS_SUPPORT
-			if ((pHeader->FC.FrDs == 0) && (pHeader->FC.ToDs == 0))
-				RX_BLK_SET_FLAG(pRxBlk, fRX_DLS);
-			else
-#endif // QOS_DLS_SUPPORT //
-			ASSERT(pRxWI->WirelessCliID == BSSID_WCID);
-		}
-
-		// check Atheros Client
-		if ((pEntry->bIAmBadAtheros == FALSE) &&  (pRxD->AMPDU == 1) && (pHeader->FC.Retry ))
-		{
-			pEntry->bIAmBadAtheros = TRUE;
-			pAd->CommonCfg.IOTestParm.bCurrentAtheros = TRUE;
-			pAd->CommonCfg.IOTestParm.bLastAtheros = TRUE;
-			if (!STA_AES_ON(pAd))
-			{
-				AsicUpdateProtect(pAd, 8, ALLN_SETPROTECT, TRUE, FALSE);
-			}
-		}
-	}
-
-	pRxBlk->pData = (UCHAR *)pHeader;
-
-	//
-	// update RxBlk->pData, DataSize
-	// 802.11 Header, QOS, HTC, Hw Padding
-	//
-
-	// 1. skip 802.11 HEADER
-	{
-		pRxBlk->pData += LENGTH_802_11;
-		pRxBlk->DataSize -= LENGTH_802_11;
-	}
-
-	// 2. QOS
-	if (pHeader->FC.SubType & 0x08)
-	{
-		RX_BLK_SET_FLAG(pRxBlk, fRX_QOS);
-		UserPriority = *(pRxBlk->pData) & 0x0f;
-		// bit 7 in QoS Control field signals the HT A-MSDU format
-		if ((*pRxBlk->pData) & 0x80)
-		{
-			RX_BLK_SET_FLAG(pRxBlk, fRX_AMSDU);
-		}
-
-		// skip QOS contorl field
-		pRxBlk->pData += 2;
-		pRxBlk->DataSize -=2;
-	}
-	pRxBlk->UserPriority = UserPriority;
-
-	// 3. Order bit: A-Ralink or HTC+
-	if (pHeader->FC.Order)
-	{
-#ifdef AGGREGATION_SUPPORT
-		if ((pRxWI->PHYMODE <= MODE_OFDM) && (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED)))
-		{
-			RX_BLK_SET_FLAG(pRxBlk, fRX_ARALINK);
-		}
-		else
-#endif
-		{
-#ifdef DOT11_N_SUPPORT
-			RX_BLK_SET_FLAG(pRxBlk, fRX_HTC);
-			// skip HTC contorl field
-			pRxBlk->pData += 4;
-			pRxBlk->DataSize -= 4;
-#endif // DOT11_N_SUPPORT //
-		}
-	}
-
-	// 4. skip HW padding
-	if (pRxD->L2PAD)
-	{
-		// just move pData pointer
-		// because DataSize excluding HW padding
-		RX_BLK_SET_FLAG(pRxBlk, fRX_PAD);
-		pRxBlk->pData += 2;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	if (pRxD->BA)
-	{
-		RX_BLK_SET_FLAG(pRxBlk, fRX_AMPDU);
-	}
-#endif // DOT11_N_SUPPORT //
-
-
-	//
-	// Case I  Process Broadcast & Multicast data frame
-	//
-	if (pRxD->Bcast || pRxD->Mcast)
-	{
-		INC_COUNTER64(pAd->WlanCounters.MulticastReceivedFrameCount);
-
-		// Drop Mcast/Bcast frame with fragment bit on
-		if (pHeader->FC.MoreFrag)
-		{
-			// release packet
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-			return;
-		}
-
-		// Filter out Bcast frame which AP relayed for us
-		if (pHeader->FC.FrDs && MAC_ADDR_EQUAL(pHeader->Addr3, pAd->CurrentAddress))
-		{
-			// release packet
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-			return;
-		}
-
-		Indicate_Legacy_Packet(pAd, pRxBlk, FromWhichBSSID);
-		return;
-	}
-	else if (pRxD->U2M)
-	{
-		pAd->LastRxRate = (USHORT)((pRxWI->MCS) + (pRxWI->BW <<7) + (pRxWI->ShortGI <<8)+ (pRxWI->PHYMODE <<14)) ;
-
-
-#ifdef QOS_DLS_SUPPORT
-        if (RX_BLK_TEST_FLAG(pRxBlk, fRX_DLS))
-		{
-			MAC_TABLE_ENTRY *pDlsEntry = NULL;
-
-			pDlsEntry = DlsEntryTableLookupByWcid(pAd, pRxWI->WirelessCliID, pHeader->Addr2, TRUE);
-										                        if(pDlsEntry)
-			Update_Rssi_Sample(pAd, &pDlsEntry->RssiSample, pRxWI);
-		}
-		else
-#endif // QOS_DLS_SUPPORT //
-		if (ADHOC_ON(pAd))
-		{
-			pEntry = MacTableLookup(pAd, pHeader->Addr2);
-			if (pEntry)
-				Update_Rssi_Sample(pAd, &pEntry->RssiSample, pRxWI);
-		}
-
-
-		Update_Rssi_Sample(pAd, &pAd->StaCfg.RssiSample, pRxWI);
-
-		pAd->StaCfg.LastSNR0 = (UCHAR)(pRxWI->SNR0);
-		pAd->StaCfg.LastSNR1 = (UCHAR)(pRxWI->SNR1);
-
-		pAd->RalinkCounters.OneSecRxOkDataCnt++;
-
-
-    	if (!((pHeader->Frag == 0) && (pHeader->FC.MoreFrag == 0)))
-    	{
-    		// re-assemble the fragmented packets
-    		// return complete frame (pRxPacket) or NULL
-    		bFragment = TRUE;
-    		pRxPacket = RTMPDeFragmentDataFrame(pAd, pRxBlk);
-    	}
-
-    	if (pRxPacket)
-    	{
-			pEntry = &pAd->MacTab.Content[pRxWI->WirelessCliID];
-
-    		// process complete frame
-    		if (bFragment && (pRxD->Decrypted) && (pEntry->WepStatus == Ndis802_11Encryption2Enabled))
-    		{
-				// Minus MIC length
-				pRxBlk->DataSize -= 8;
-
-    			// For TKIP frame, calculate the MIC value
-    			if (STACheckTkipMICValue(pAd, pEntry, pRxBlk) == FALSE)
-    			{
-    				return;
-    			}
-    		}
-
-    		STARxDataFrameAnnounce(pAd, pEntry, pRxBlk, FromWhichBSSID);
-			return;
-    	}
-    	else
-    	{
-    		// just return
-    		// because RTMPDeFragmentDataFrame() will release rx packet,
-    		// if packet is fragmented
-    		return;
-    	}
-	}
-
-	ASSERT(0);
-	// release packet
-	RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-}
-
-VOID STAHandleRxMgmtFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk)
-{
-	PRT28XX_RXD_STRUC	pRxD = &(pRxBlk->RxD);
-	PRXWI_STRUC		pRxWI = pRxBlk->pRxWI;
-	PHEADER_802_11	pHeader = pRxBlk->pHeader;
-	PNDIS_PACKET	pRxPacket = pRxBlk->pRxPacket;
-
-	do
-	{
-
-		// We should collect RSSI not only U2M data but also my beacon
-		if ((pHeader->FC.SubType == SUBTYPE_BEACON) && (MAC_ADDR_EQUAL(&pAd->CommonCfg.Bssid, &pHeader->Addr2)))
-		{
-			Update_Rssi_Sample(pAd, &pAd->StaCfg.RssiSample, pRxWI);
-
-			pAd->StaCfg.LastSNR0 = (UCHAR)(pRxWI->SNR0);
-			pAd->StaCfg.LastSNR1 = (UCHAR)(pRxWI->SNR1);
-		}
-
-		// First check the size, it MUST not exceed the mlme queue size
-		if (pRxWI->MPDUtotalByteCount > MGMT_DMA_BUFFER_SIZE)
-		{
-			DBGPRINT_ERR(("STAHandleRxMgmtFrame: frame too large, size = %d \n", pRxWI->MPDUtotalByteCount));
-			break;
-		}
-
-		REPORT_MGMT_FRAME_TO_MLME(pAd, pRxWI->WirelessCliID, pHeader, pRxWI->MPDUtotalByteCount,
-									pRxWI->RSSI0, pRxWI->RSSI1, pRxWI->RSSI2, pRxD->PlcpSignal);
-	} while (FALSE);
-
-	RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_SUCCESS);
-}
-
-VOID STAHandleRxControlFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk)
-{
-#ifdef DOT11_N_SUPPORT
-	PRXWI_STRUC		pRxWI = pRxBlk->pRxWI;
-#endif // DOT11_N_SUPPORT //
-	PHEADER_802_11	pHeader = pRxBlk->pHeader;
-	PNDIS_PACKET	pRxPacket = pRxBlk->pRxPacket;
-
-	switch (pHeader->FC.SubType)
-	{
-		case SUBTYPE_BLOCK_ACK_REQ:
-#ifdef DOT11_N_SUPPORT
-			{
-				CntlEnqueueForRecv(pAd, pRxWI->WirelessCliID, (pRxWI->MPDUtotalByteCount), (PFRAME_BA_REQ)pHeader);
-			}
-			break;
-#endif // DOT11_N_SUPPORT //
-		case SUBTYPE_BLOCK_ACK:
-		case SUBTYPE_ACK:
-		default:
-			break;
-	}
-
-	RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Process RxDone interrupt, running in DPC level
-
-	Arguments:
-		pAd Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-		This routine has to maintain Rx ring read pointer.
-		Need to consider QOS DATA format when converting to 802.3
-	========================================================================
-*/
-BOOLEAN STARxDoneInterruptHandle(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	BOOLEAN			argc)
-{
-	NDIS_STATUS			Status;
-	UINT32			RxProcessed, RxPending;
-	BOOLEAN			bReschedule = FALSE;
-	RT28XX_RXD_STRUC	*pRxD;
-	UCHAR			*pData;
-	PRXWI_STRUC		pRxWI;
-	PNDIS_PACKET	pRxPacket;
-	PHEADER_802_11	pHeader;
-	RX_BLK			RxCell;
-
-	RxProcessed = RxPending = 0;
-
-	// process whole rx ring
-	while (1)
-	{
-
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF |
-								fRTMP_ADAPTER_RESET_IN_PROGRESS |
-								fRTMP_ADAPTER_HALT_IN_PROGRESS |
-								fRTMP_ADAPTER_NIC_NOT_EXIST) ||
-			!RTMP_TEST_FLAG(pAd,fRTMP_ADAPTER_START_UP))
-		{
-			break;
-		}
-
-
-		RxProcessed ++; // test
-
-		// 1. allocate a new data packet into rx ring to replace received packet
-		//    then processing the received packet
-		// 2. the callee must take charge of release of packet
-		// 3. As far as driver is concerned ,
-		//    the rx packet must
-		//      a. be indicated to upper layer or
-		//      b. be released if it is discarded
-		pRxPacket = GetPacketFromRxRing(pAd, &(RxCell.RxD), &bReschedule, &RxPending);
-		if (pRxPacket == NULL)
-		{
-			// no more packet to process
-			break;
-		}
-
-		// get rx ring descriptor
-		pRxD = &(RxCell.RxD);
-		// get rx data buffer
-		pData	= GET_OS_PKT_DATAPTR(pRxPacket);
-		pRxWI	= (PRXWI_STRUC) pData;
-		pHeader = (PHEADER_802_11) (pData+RXWI_SIZE) ;
-
-#ifdef RT_BIG_ENDIAN
-	    RTMPFrameEndianChange(pAd, (PUCHAR)pHeader, DIR_READ, TRUE);
-		RTMPWIEndianChange((PUCHAR)pRxWI, TYPE_RXWI);
-#endif
-
-		// build RxCell
-		RxCell.pRxWI = pRxWI;
-		RxCell.pHeader = pHeader;
-		RxCell.pRxPacket = pRxPacket;
-		RxCell.pData = (UCHAR *) pHeader;
-		RxCell.DataSize = pRxWI->MPDUtotalByteCount;
-		RxCell.Flags = 0;
-
-		// Increase Total receive byte counter after real data received no mater any error or not
-		pAd->RalinkCounters.ReceivedByteCount +=  pRxWI->MPDUtotalByteCount;
-		pAd->RalinkCounters.RxCount ++;
-
-		INC_COUNTER64(pAd->WlanCounters.ReceivedFragmentCount);
-
-		if (pRxWI->MPDUtotalByteCount < 14)
-			Status = NDIS_STATUS_FAILURE;
-
-        if (MONITOR_ON(pAd))
-		{
-            send_monitor_packets(pAd, &RxCell);
-			break;
-		}
-		/* RT2870 invokes STARxDoneInterruptHandle() in rtusb_bulk.c */
-#ifdef RALINK_ATE
-		if (ATE_ON(pAd))
-		{
-			pAd->ate.RxCntPerSec++;
-			ATESampleRssi(pAd, pRxWI);
-#ifdef RALINK_28xx_QA
-			if (pAd->ate.bQARxStart == TRUE)
-			{
-				/* (*pRxD) has been swapped in GetPacketFromRxRing() */
-				ATE_QA_Statistics(pAd, pRxWI, pRxD,	pHeader);
-			}
-#endif // RALINK_28xx_QA //
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_SUCCESS);
-			continue;
-		}
-#endif // RALINK_ATE //
-
-		// Check for all RxD errors
-		Status = RTMPCheckRxError(pAd, pHeader, pRxWI, pRxD);
-
-		// Handle the received frame
-		if (Status == NDIS_STATUS_SUCCESS)
-		{
-			switch (pHeader->FC.Type)
-			{
-				// CASE I, receive a DATA frame
-				case BTYPE_DATA:
-				{
-					// process DATA frame
-					STAHandleRxDataFrame(pAd, &RxCell);
-				}
-				break;
-				// CASE II, receive a MGMT frame
-				case BTYPE_MGMT:
-				{
-					STAHandleRxMgmtFrame(pAd, &RxCell);
-				}
-				break;
-				// CASE III. receive a CNTL frame
-				case BTYPE_CNTL:
-				{
-					STAHandleRxControlFrame(pAd, &RxCell);
-				}
-				break;
-				// discard other type
-				default:
-					RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-					break;
-			}
-		}
-		else
-		{
-			pAd->Counters8023.RxErrors++;
-			// discard this frame
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-		}
-	}
-
-	return bReschedule;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-VOID	RTMPHandleTwakeupInterrupt(
-	IN PRTMP_ADAPTER pAd)
-{
-	AsicForceWakeup(pAd, FALSE);
-}
-
-/*
-========================================================================
-Routine Description:
-    Early checking and OS-depened parsing for Tx packet send to our STA driver.
-
-Arguments:
-    NDIS_HANDLE 	MiniportAdapterContext	Pointer refer to the device handle, i.e., the pAd.
-	PPNDIS_PACKET	ppPacketArray			The packet array need to do transmission.
-	UINT			NumberOfPackets			Number of packet in packet array.
-
-Return Value:
-	NONE
-
-Note:
-	This function do early checking and classification for send-out packet.
-	You only can put OS-depened & STA related code in here.
-========================================================================
-*/
-VOID STASendPackets(
-	IN	NDIS_HANDLE		MiniportAdapterContext,
-	IN	PPNDIS_PACKET	ppPacketArray,
-	IN	UINT			NumberOfPackets)
-{
-	UINT			Index;
-	PRTMP_ADAPTER	pAd = (PRTMP_ADAPTER) MiniportAdapterContext;
-	PNDIS_PACKET	pPacket;
-	BOOLEAN			allowToSend = FALSE;
-
-
-	for (Index = 0; Index < NumberOfPackets; Index++)
-	{
-		pPacket = ppPacketArray[Index];
-
-		do
-		{
-			if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS) ||
-				RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS) ||
-				RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))
-			{
-				// Drop send request since hardware is in reset state
-					break;
-			}
-			else if (!INFRA_ON(pAd) && !ADHOC_ON(pAd))
-			{
-				// Drop send request since there are no physical connection yet
-					break;
-			}
-			else
-			{
-				// Record that orignal packet source is from NDIS layer,so that
-				// later on driver knows how to release this NDIS PACKET
-#ifdef QOS_DLS_SUPPORT
-				MAC_TABLE_ENTRY *pEntry;
-				PUCHAR pSrcBufVA = GET_OS_PKT_DATAPTR(pPacket);
-
-				pEntry = MacTableLookup(pAd, pSrcBufVA);
-				if (pEntry && (pEntry->ValidAsDls == TRUE))
-				{
-					RTMP_SET_PACKET_WCID(pPacket, pEntry->Aid);
-				}
-				else
-#endif // QOS_DLS_SUPPORT //
-				RTMP_SET_PACKET_WCID(pPacket, 0); // this field is useless when in STA mode
-				RTMP_SET_PACKET_SOURCE(pPacket, PKTSRC_NDIS);
-				NDIS_SET_PACKET_STATUS(pPacket, NDIS_STATUS_PENDING);
-				pAd->RalinkCounters.PendingNdisPacketCount++;
-
-				allowToSend = TRUE;
-			}
-		} while(FALSE);
-
-		if (allowToSend == TRUE)
-			STASendPacket(pAd, pPacket);
-		else
-			RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-	}
-
-	// Dequeue outgoing frames from TxSwQueue[] and process it
-	RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-
-}
-
-
-/*
-========================================================================
-Routine Description:
-	This routine is used to do packet parsing and classification for Tx packet
-	to STA device, and it will en-queue packets to our TxSwQueue depends on AC
-	class.
-
-Arguments:
-	pAd    		Pointer to our adapter
-	pPacket 	Pointer to send packet
-
-Return Value:
-	NDIS_STATUS_SUCCESS			If succes to queue the packet into TxSwQueue.
-	NDIS_STATUS_FAILURE			If failed to do en-queue.
-
-Note:
-	You only can put OS-indepened & STA related code in here.
-========================================================================
-*/
-NDIS_STATUS STASendPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-	PACKET_INFO 	PacketInfo;
-	PUCHAR			pSrcBufVA;
-	UINT			SrcBufLen;
-	UINT			AllowFragSize;
-	UCHAR			NumberOfFrag;
-//	UCHAR			RTSRequired;
-	UCHAR			QueIdx, UserPriority;
-	MAC_TABLE_ENTRY *pEntry = NULL;
-	unsigned int 	IrqFlags;
-	UCHAR			FlgIsIP = 0;
-	UCHAR			Rate;
-
-	// Prepare packet information structure for buffer descriptor
-	// chained within a single NDIS packet.
-	RTMP_QueryPacketInfo(pPacket, &PacketInfo, &pSrcBufVA, &SrcBufLen);
-
-	if (pSrcBufVA == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("STASendPacket --> pSrcBufVA == NULL !!!SrcBufLen=%x\n",SrcBufLen));
-		// Resourece is low, system did not allocate virtual address
-		// return NDIS_STATUS_FAILURE directly to upper layer
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-		return NDIS_STATUS_FAILURE;
-	}
-
-
-	if (SrcBufLen < 14)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("STASendPacket --> Ndis Packet buffer error !!!\n"));
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-		return (NDIS_STATUS_FAILURE);
-	}
-
-	// In HT rate adhoc mode, A-MPDU is often used. So need to lookup BA Table and MAC Entry.
-	// Note multicast packets in adhoc also use BSSID_WCID index.
-	{
-		if(INFRA_ON(pAd))
-		{
-#ifdef QOS_DLS_SUPPORT
-			USHORT	tmpWcid;
-
-			tmpWcid = RTMP_GET_PACKET_WCID(pPacket);
-			if (VALID_WCID(tmpWcid) &&
-				(pAd->MacTab.Content[tmpWcid].ValidAsDls== TRUE))
-			{
-				pEntry = &pAd->MacTab.Content[tmpWcid];
-				Rate = pAd->MacTab.Content[tmpWcid].CurrTxRate;
-			}
-			else
-#endif // QOS_DLS_SUPPORT //
-			{
-			pEntry = &pAd->MacTab.Content[BSSID_WCID];
-			RTMP_SET_PACKET_WCID(pPacket, BSSID_WCID);
-			Rate = pAd->CommonCfg.TxRate;
-		}
-		}
-		else if (ADHOC_ON(pAd))
-		{
-			if (*pSrcBufVA & 0x01)
-			{
-				RTMP_SET_PACKET_WCID(pPacket, MCAST_WCID);
-				pEntry = &pAd->MacTab.Content[MCAST_WCID];
-			}
-			else
-			{
-				pEntry = MacTableLookup(pAd, pSrcBufVA);
-			}
-			Rate = pAd->CommonCfg.TxRate;
-		}
-	}
-
-	if (!pEntry)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("STASendPacket->Cannot find pEntry(%2x:%2x:%2x:%2x:%2x:%2x) in MacTab!\n", PRINT_MAC(pSrcBufVA)));
-		// Resourece is low, system did not allocate virtual address
-		// return NDIS_STATUS_FAILURE directly to upper layer
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-		return NDIS_STATUS_FAILURE;
-	}
-
-	if (ADHOC_ON(pAd)
-		)
-	{
-		RTMP_SET_PACKET_WCID(pPacket, (UCHAR)pEntry->Aid);
-	}
-
-	//
-	// Check the Ethernet Frame type of this packet, and set the RTMP_SET_PACKET_SPECIFIC flags.
-	//		Here we set the PACKET_SPECIFIC flags(LLC, VLAN, DHCP/ARP, EAPOL).
-	RTMPCheckEtherType(pAd, pPacket);
-
-
-
-	//
-	// WPA 802.1x secured port control - drop all non-802.1x frame before port secured
-	//
-	if (((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-		 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-		 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
-		 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-#ifdef WPA_SUPPLICANT_SUPPORT
-		  || (pAd->StaCfg.IEEE8021X == TRUE)
-#endif // WPA_SUPPLICANT_SUPPORT //
-#ifdef LEAP_SUPPORT
-		  || (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
-		  )
-		  && ((pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED) || (pAd->StaCfg.MicErrCnt >= 2))
-		  && (RTMP_GET_PACKET_EAPOL(pPacket)== FALSE)
-		  )
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("STASendPacket --> Drop packet before port secured !!!\n"));
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-
-		return (NDIS_STATUS_FAILURE);
-	}
-
-
-	// STEP 1. Decide number of fragments required to deliver this MSDU.
-	//	   The estimation here is not very accurate because difficult to
-	//	   take encryption overhead into consideration here. The result
-	//	   "NumberOfFrag" is then just used to pre-check if enough free
-	//	   TXD are available to hold this MSDU.
-
-
-	if (*pSrcBufVA & 0x01)	// fragmentation not allowed on multicast & broadcast
-		NumberOfFrag = 1;
-	else if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED))
-		NumberOfFrag = 1;	// Aggregation overwhelms fragmentation
-	else if (CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_AMSDU_INUSED))
-		NumberOfFrag = 1;	// Aggregation overwhelms fragmentation
-#ifdef DOT11_N_SUPPORT
-	else if ((pAd->StaCfg.HTPhyMode.field.MODE == MODE_HTMIX) || (pAd->StaCfg.HTPhyMode.field.MODE == MODE_HTGREENFIELD))
-		NumberOfFrag = 1;	// MIMO RATE overwhelms fragmentation
-#endif // DOT11_N_SUPPORT //
-	else
-	{
-		// The calculated "NumberOfFrag" is a rough estimation because of various
-		// encryption/encapsulation overhead not taken into consideration. This number is just
-		// used to make sure enough free TXD are available before fragmentation takes place.
-		// In case the actual required number of fragments of an NDIS packet
-		// excceeds "NumberOfFrag"caculated here and not enough free TXD available, the
-		// last fragment (i.e. last MPDU) will be dropped in RTMPHardTransmit() due to out of
-		// resource, and the NDIS packet will be indicated NDIS_STATUS_FAILURE. This should
-		// rarely happen and the penalty is just like a TX RETRY fail. Affordable.
-
-		AllowFragSize = (pAd->CommonCfg.FragmentThreshold) - LENGTH_802_11 - LENGTH_CRC;
-		NumberOfFrag = ((PacketInfo.TotalPacketLength - LENGTH_802_3 + LENGTH_802_1_H) / AllowFragSize) + 1;
-		// To get accurate number of fragmentation, Minus 1 if the size just match to allowable fragment size
-		if (((PacketInfo.TotalPacketLength - LENGTH_802_3 + LENGTH_802_1_H) % AllowFragSize) == 0)
-		{
-			NumberOfFrag--;
-		}
-	}
-
-	// Save fragment number to Ndis packet reserved field
-	RTMP_SET_PACKET_FRAGMENTS(pPacket, NumberOfFrag);
-
-
-	// STEP 2. Check the requirement of RTS:
-	//	   If multiple fragment required, RTS is required only for the first fragment
-	//	   if the fragment size large than RTS threshold
-	//     For RT28xx, Let ASIC send RTS/CTS
-	RTMP_SET_PACKET_RTS(pPacket, 0);
-	RTMP_SET_PACKET_TXRATE(pPacket, pAd->CommonCfg.TxRate);
-
-	//
-	// STEP 3. Traffic classification. outcome = <UserPriority, QueIdx>
-	//
-	UserPriority = 0;
-	QueIdx		 = QID_AC_BE;
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) &&
-		CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE))
-	{
-		USHORT Protocol;
-		UCHAR  LlcSnapLen = 0, Byte0, Byte1;
-		do
-		{
-			// get Ethernet protocol field
-			Protocol = (USHORT)((pSrcBufVA[12] << 8) + pSrcBufVA[13]);
-			if (Protocol <= 1500)
-			{
-				// get Ethernet protocol field from LLC/SNAP
-				if (Sniff2BytesFromNdisBuffer(PacketInfo.pFirstBuffer, LENGTH_802_3 + 6, &Byte0, &Byte1) != NDIS_STATUS_SUCCESS)
-					break;
-
-				Protocol = (USHORT)((Byte0 << 8) + Byte1);
-				LlcSnapLen = 8;
-			}
-
-			// always AC_BE for non-IP packet
-			if (Protocol != 0x0800)
-				break;
-
-			// get IP header
-			if (Sniff2BytesFromNdisBuffer(PacketInfo.pFirstBuffer, LENGTH_802_3 + LlcSnapLen, &Byte0, &Byte1) != NDIS_STATUS_SUCCESS)
-				break;
-
-			// return AC_BE if packet is not IPv4
-			if ((Byte0 & 0xf0) != 0x40)
-				break;
-
-			FlgIsIP = 1;
-			UserPriority = (Byte1 & 0xe0) >> 5;
-			QueIdx = MapUserPriorityToAccessCategory[UserPriority];
-
-			// TODO: have to check ACM bit. apply TSPEC if ACM is ON
-			// TODO: downgrade UP & QueIdx before passing ACM
-			if (pAd->CommonCfg.APEdcaParm.bACM[QueIdx])
-			{
-				UserPriority = 0;
-				QueIdx		 = QID_AC_BE;
-			}
-		} while (FALSE);
-	}
-
-	RTMP_SET_PACKET_UP(pPacket, UserPriority);
-
-
-
-	// Make sure SendTxWait queue resource won't be used by other threads
-	RTMP_IRQ_LOCK(&pAd->irq_lock, IrqFlags);
-	if (pAd->TxSwQueue[QueIdx].Number >= MAX_PACKETS_IN_QUEUE)
-	{
-		RTMP_IRQ_UNLOCK(&pAd->irq_lock, IrqFlags);
-#ifdef BLOCK_NET_IF
-		StopNetIfQueue(pAd, QueIdx, pPacket);
-#endif // BLOCK_NET_IF //
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-
-		return NDIS_STATUS_FAILURE;
-	}
-	else
-	{
-		InsertTailQueue(&pAd->TxSwQueue[QueIdx], PACKET_TO_QUEUE_ENTRY(pPacket));
-	}
-	RTMP_IRQ_UNLOCK(&pAd->irq_lock, IrqFlags);
-
-#ifdef DOT11_N_SUPPORT
-    if ((pAd->CommonCfg.BACapability.field.AutoBA == TRUE)&&
-        IS_HT_STA(pEntry))
-	{
-	    //PMAC_TABLE_ENTRY pMacEntry = &pAd->MacTab.Content[BSSID_WCID];
-		if (((pEntry->TXBAbitmap & (1<<UserPriority)) == 0) &&
-            ((pEntry->BADeclineBitmap & (1<<UserPriority)) == 0) &&
-            (pEntry->PortSecured == WPA_802_1X_PORT_SECURED)
-			 // For IOT compatibility, if
-			 // 1. It is Ralink chip or
-			 // 2. It is OPEN or AES mode,
-			 // then BA session can be bulit.
-			 && ((pEntry->ValidAsCLI && pAd->MlmeAux.APRalinkIe != 0x0) ||
-			 	 (pEntry->WepStatus == Ndis802_11WEPDisabled || pEntry->WepStatus == Ndis802_11Encryption3Enabled))
-			)
-		{
-			BAOriSessionSetUp(pAd, pEntry, 0, 0, 10, FALSE);
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-	pAd->RalinkCounters.OneSecOsTxCount[QueIdx]++; // TODO: for debug only. to be removed
-	return NDIS_STATUS_SUCCESS;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		This subroutine will scan through releative ring descriptor to find
-		out avaliable free ring descriptor and compare with request size.
-
-	Arguments:
-		pAd Pointer to our adapter
-		QueIdx		Selected TX Ring
-
-	Return Value:
-		NDIS_STATUS_FAILURE 	Not enough free descriptor
-		NDIS_STATUS_SUCCESS 	Enough free descriptor
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-
-#ifdef RT2870
-/*
-	Actually, this function used to check if the TxHardware Queue still has frame need to send.
-	If no frame need to send, go to sleep, else, still wake up.
-*/
-NDIS_STATUS RTMPFreeTXDRequest(
-	IN		PRTMP_ADAPTER	pAd,
-	IN		UCHAR			QueIdx,
-	IN		UCHAR			NumberRequired,
-	IN		PUCHAR			FreeNumberIs)
-{
-	//ULONG		FreeNumber = 0;
-	NDIS_STATUS 	Status = NDIS_STATUS_FAILURE;
-	unsigned long   IrqFlags;
-	HT_TX_CONTEXT	*pHTTXContext;
-
-	switch (QueIdx)
-	{
-		case QID_AC_BK:
-		case QID_AC_BE:
-		case QID_AC_VI:
-		case QID_AC_VO:
-		case QID_HCCA:
-			{
-				pHTTXContext = &pAd->TxContext[QueIdx];
-				RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-				if ((pHTTXContext->CurWritePosition != pHTTXContext->ENextBulkOutPosition) ||
-					(pHTTXContext->IRPPending == TRUE))
-				{
-					Status = NDIS_STATUS_FAILURE;
-				}
-				else
-				{
-					Status = NDIS_STATUS_SUCCESS;
-				}
-				RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-			}
-			break;
-
-		case QID_MGMT:
-			if (pAd->MgmtRing.TxSwFreeIdx != MGMT_RING_SIZE)
-				Status = NDIS_STATUS_FAILURE;
-			else
-				Status = NDIS_STATUS_SUCCESS;
-			break;
-
-		default:
-			DBGPRINT(RT_DEBUG_ERROR,("RTMPFreeTXDRequest::Invalid QueIdx(=%d)\n", QueIdx));
-			break;
-	}
-
-	return (Status);
-
-}
-#endif // RT2870 //
-
-
-VOID RTMPSendDisassociationFrame(
-	IN	PRTMP_ADAPTER	pAd)
-{
-}
-
-VOID	RTMPSendNullFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			TxRate,
-	IN	BOOLEAN 		bQosNull)
-{
-	UCHAR	NullFrame[48];
-	ULONG	Length;
-	PHEADER_802_11	pHeader_802_11;
-
-
-#ifdef RALINK_ATE
-	if(ATE_ON(pAd))
-	{
-		return;
-	}
-#endif // RALINK_ATE //
-
-    // WPA 802.1x secured port control
-    if (((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-         (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-         (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
-         (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-#ifdef WPA_SUPPLICANT_SUPPORT
-			  || (pAd->StaCfg.IEEE8021X == TRUE)
-#endif
-        ) &&
-       (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-	{
-		return;
-	}
-
-	NdisZeroMemory(NullFrame, 48);
-	Length = sizeof(HEADER_802_11);
-
-	pHeader_802_11 = (PHEADER_802_11) NullFrame;
-
-	pHeader_802_11->FC.Type = BTYPE_DATA;
-	pHeader_802_11->FC.SubType = SUBTYPE_NULL_FUNC;
-	pHeader_802_11->FC.ToDs = 1;
-	COPY_MAC_ADDR(pHeader_802_11->Addr1, pAd->CommonCfg.Bssid);
-	COPY_MAC_ADDR(pHeader_802_11->Addr2, pAd->CurrentAddress);
-	COPY_MAC_ADDR(pHeader_802_11->Addr3, pAd->CommonCfg.Bssid);
-
-	if (pAd->CommonCfg.bAPSDForcePowerSave)
-	{
-		pHeader_802_11->FC.PwrMgmt = PWR_SAVE;
-	}
-	else
-	{
-		pHeader_802_11->FC.PwrMgmt = (pAd->StaCfg.Psm == PWR_SAVE) ? 1: 0;
-	}
-	pHeader_802_11->Duration = pAd->CommonCfg.Dsifs + RTMPCalcDuration(pAd, TxRate, 14);
-
-	pAd->Sequence++;
-	pHeader_802_11->Sequence = pAd->Sequence;
-
-	// Prepare QosNull function frame
-	if (bQosNull)
-	{
-		pHeader_802_11->FC.SubType = SUBTYPE_QOS_NULL;
-
-		// copy QOS control bytes
-		NullFrame[Length]	=  0;
-		NullFrame[Length+1] =  0;
-		Length += 2;// if pad with 2 bytes for alignment, APSD will fail
-	}
-
-	HAL_KickOutNullFrameTx(pAd, 0, NullFrame, Length);
-
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID	RTMPSendRTSFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA,
-	IN	unsigned int	NextMpduSize,
-	IN	UCHAR			TxRate,
-	IN	UCHAR			RTSRate,
-	IN	USHORT			AckDuration,
-	IN	UCHAR			QueIdx,
-	IN	UCHAR			FrameGap)
-{
-}
-
-
-
-// --------------------------------------------------------
-//  FIND ENCRYPT KEY AND DECIDE CIPHER ALGORITHM
-//		Find the WPA key, either Group or Pairwise Key
-//		LEAP + TKIP also use WPA key.
-// --------------------------------------------------------
-// Decide WEP bit and cipher suite to be used. Same cipher suite should be used for whole fragment burst
-// In Cisco CCX 2.0 Leap Authentication
-//		   WepStatus is Ndis802_11Encryption1Enabled but the key will use PairwiseKey
-//		   Instead of the SharedKey, SharedKey Length may be Zero.
-VOID STAFindCipherAlgorithm(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk)
-{
-	NDIS_802_11_ENCRYPTION_STATUS	Cipher;				// To indicate cipher used for this packet
-	UCHAR							CipherAlg = CIPHER_NONE;		// cipher alogrithm
-	UCHAR							KeyIdx = 0xff;
-	PUCHAR							pSrcBufVA;
-	PCIPHER_KEY						pKey = NULL;
-
-	pSrcBufVA = GET_OS_PKT_DATAPTR(pTxBlk->pPacket);
-
-	{
-	    // Select Cipher
-	    if ((*pSrcBufVA & 0x01) && (ADHOC_ON(pAd)))
-	        Cipher = pAd->StaCfg.GroupCipher; // Cipher for Multicast or Broadcast
-	    else
-	        Cipher = pAd->StaCfg.PairCipher; // Cipher for Unicast
-
-		if (RTMP_GET_PACKET_EAPOL(pTxBlk->pPacket))
-		{
-			ASSERT(pAd->SharedKey[BSS0][0].CipherAlg <= CIPHER_CKIP128);
-
-			// 4-way handshaking frame must be clear
-			if (!(TX_BLK_TEST_FLAG(pTxBlk, fTX_bClearEAPFrame)) && (pAd->SharedKey[BSS0][0].CipherAlg) &&
-				(pAd->SharedKey[BSS0][0].KeyLen))
-			{
-				CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-				KeyIdx = 0;
-			}
-		}
-		else if (Cipher == Ndis802_11Encryption1Enabled)
-		{
-#ifdef LEAP_SUPPORT
-			if (pAd->StaCfg.CkipFlag & 0x10) // Cisco CKIP KP is on
-			{
-				if (LEAP_CCKM_ON(pAd))
-				{
-					if (((*pSrcBufVA & 0x01) && (ADHOC_ON(pAd))))
-						KeyIdx = 1;
-					else
-						KeyIdx = 0;
-				}
-				else
-					KeyIdx = pAd->StaCfg.DefaultKeyId;
-			}
-			else if (pAd->StaCfg.CkipFlag & 0x08) // only CKIP CMIC
-				KeyIdx = pAd->StaCfg.DefaultKeyId;
-			else if (LEAP_CCKM_ON(pAd))
-			{
-				if ((*pSrcBufVA & 0x01) && (ADHOC_ON(pAd)))
-					KeyIdx = 1;
-				else
-					KeyIdx = 0;
-			}
-			else	// standard WEP64 or WEP128
-#endif // LEAP_SUPPORT //
-				KeyIdx = pAd->StaCfg.DefaultKeyId;
-		}
-		else if ((Cipher == Ndis802_11Encryption2Enabled) ||
-				 (Cipher == Ndis802_11Encryption3Enabled))
-		{
-			if ((*pSrcBufVA & 0x01) && (ADHOC_ON(pAd))) // multicast
-				KeyIdx = pAd->StaCfg.DefaultKeyId;
-			else if (pAd->SharedKey[BSS0][0].KeyLen)
-				KeyIdx = 0;
-			else
-				KeyIdx = pAd->StaCfg.DefaultKeyId;
-		}
-
-		if (KeyIdx == 0xff)
-			CipherAlg = CIPHER_NONE;
-		else if ((Cipher == Ndis802_11EncryptionDisabled) || (pAd->SharedKey[BSS0][KeyIdx].KeyLen == 0))
-			CipherAlg = CIPHER_NONE;
-#ifdef WPA_SUPPLICANT_SUPPORT
-	    else if ( pAd->StaCfg.WpaSupplicantUP &&
-	             (Cipher == Ndis802_11Encryption1Enabled) &&
-	             (pAd->StaCfg.IEEE8021X == TRUE) &&
-	             (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-	        CipherAlg = CIPHER_NONE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-		else
-		{
-			//Header_802_11.FC.Wep = 1;
-			CipherAlg = pAd->SharedKey[BSS0][KeyIdx].CipherAlg;
-			pKey = &pAd->SharedKey[BSS0][KeyIdx];
-		}
-	}
-
-	pTxBlk->CipherAlg = CipherAlg;
-	pTxBlk->pKey = pKey;
-}
-
-
-VOID STABuildCommon802_11Header(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  TX_BLK          *pTxBlk)
-{
-
-	HEADER_802_11	*pHeader_802_11;
-#ifdef QOS_DLS_SUPPORT
-	BOOLEAN	bDLSFrame = FALSE;
-	INT	DlsEntryIndex = 0;
-#endif // QOS_DLS_SUPPORT //
-
-	//
-	// MAKE A COMMON 802.11 HEADER
-	//
-
-	// normal wlan header size : 24 octets
-	pTxBlk->MpduHeaderLen = sizeof(HEADER_802_11);
-
-	pHeader_802_11 = (HEADER_802_11 *) &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-
-	NdisZeroMemory(pHeader_802_11, sizeof(HEADER_802_11));
-
-	pHeader_802_11->FC.FrDs = 0;
-	pHeader_802_11->FC.Type = BTYPE_DATA;
-	pHeader_802_11->FC.SubType = ((TX_BLK_TEST_FLAG(pTxBlk, fTX_bWMM)) ? SUBTYPE_QDATA : SUBTYPE_DATA);
-
-#ifdef QOS_DLS_SUPPORT
-	if (INFRA_ON(pAd))
-	{
-		// Check if the frame can be sent through DLS direct link interface
-		// If packet can be sent through DLS, then force aggregation disable. (Hard to determine peer STA's capability)
-		DlsEntryIndex = RTMPCheckDLSFrame(pAd, pTxBlk->pSrcBufHeader);
-		if (DlsEntryIndex >= 0)
-			bDLSFrame = TRUE;
-		else
-			bDLSFrame = FALSE;
-	}
-#endif // QOS_DLS_SUPPORT //
-
-    if (pTxBlk->pMacEntry)
-	{
-		if (TX_BLK_TEST_FLAG(pTxBlk, fTX_bForceNonQoS))
-		{
-			pHeader_802_11->Sequence = pTxBlk->pMacEntry->NonQosDataSeq;
-			pTxBlk->pMacEntry->NonQosDataSeq = (pTxBlk->pMacEntry->NonQosDataSeq+1) & MAXSEQ;
-		}
-		else
-		{
-    	    pHeader_802_11->Sequence = pTxBlk->pMacEntry->TxSeq[pTxBlk->UserPriority];
-    	    pTxBlk->pMacEntry->TxSeq[pTxBlk->UserPriority] = (pTxBlk->pMacEntry->TxSeq[pTxBlk->UserPriority]+1) & MAXSEQ;
-    	}
-	}
-	else
-	{
-		pHeader_802_11->Sequence = pAd->Sequence;
-		pAd->Sequence = (pAd->Sequence+1) & MAXSEQ; // next sequence
-	}
-
-	pHeader_802_11->Frag = 0;
-
-	pHeader_802_11->FC.MoreData = TX_BLK_TEST_FLAG(pTxBlk, fTX_bMoreData);
-
-	{
-		if (INFRA_ON(pAd))
-		{
-#ifdef QOS_DLS_SUPPORT
-			if (bDLSFrame)
-			{
-				COPY_MAC_ADDR(pHeader_802_11->Addr1, pTxBlk->pSrcBufHeader);
-				COPY_MAC_ADDR(pHeader_802_11->Addr2, pAd->CurrentAddress);
-				COPY_MAC_ADDR(pHeader_802_11->Addr3, pAd->CommonCfg.Bssid);
-				pHeader_802_11->FC.ToDs = 0;
-			}
-			else
-#endif // QOS_DLS_SUPPORT //
-			{
-			COPY_MAC_ADDR(pHeader_802_11->Addr1, pAd->CommonCfg.Bssid);
-			COPY_MAC_ADDR(pHeader_802_11->Addr2, pAd->CurrentAddress);
-			COPY_MAC_ADDR(pHeader_802_11->Addr3, pTxBlk->pSrcBufHeader);
-			pHeader_802_11->FC.ToDs = 1;
-		}
-		}
-		else if (ADHOC_ON(pAd))
-		{
-			COPY_MAC_ADDR(pHeader_802_11->Addr1, pTxBlk->pSrcBufHeader);
-			COPY_MAC_ADDR(pHeader_802_11->Addr2, pAd->CurrentAddress);
-			COPY_MAC_ADDR(pHeader_802_11->Addr3, pAd->CommonCfg.Bssid);
-			pHeader_802_11->FC.ToDs = 0;
-		}
-	}
-
-	if (pTxBlk->CipherAlg != CIPHER_NONE)
-		pHeader_802_11->FC.Wep = 1;
-
-	// -----------------------------------------------------------------
-	// STEP 2. MAKE A COMMON 802.11 HEADER SHARED BY ENTIRE FRAGMENT BURST. Fill sequence later.
-	// -----------------------------------------------------------------
-	if (pAd->CommonCfg.bAPSDForcePowerSave)
-    	pHeader_802_11->FC.PwrMgmt = PWR_SAVE;
-	else
-    	pHeader_802_11->FC.PwrMgmt = (pAd->StaCfg.Psm == PWR_SAVE);
-}
-
-#ifdef DOT11_N_SUPPORT
-VOID STABuildCache802_11Header(
-	IN RTMP_ADAPTER		*pAd,
-	IN TX_BLK			*pTxBlk,
-	IN UCHAR			*pHeader)
-{
-	MAC_TABLE_ENTRY	*pMacEntry;
-	PHEADER_802_11	pHeader80211;
-
-	pHeader80211 = (PHEADER_802_11)pHeader;
-	pMacEntry = pTxBlk->pMacEntry;
-
-	//
-	// Update the cached 802.11 HEADER
-	//
-
-	// normal wlan header size : 24 octets
-	pTxBlk->MpduHeaderLen = sizeof(HEADER_802_11);
-
-	// More Bit
-	pHeader80211->FC.MoreData = TX_BLK_TEST_FLAG(pTxBlk, fTX_bMoreData);
-
-	// Sequence
-	pHeader80211->Sequence = pMacEntry->TxSeq[pTxBlk->UserPriority];
-    pMacEntry->TxSeq[pTxBlk->UserPriority] = (pMacEntry->TxSeq[pTxBlk->UserPriority]+1) & MAXSEQ;
-
-	{
-		// Check if the frame can be sent through DLS direct link interface
-		// If packet can be sent through DLS, then force aggregation disable. (Hard to determine peer STA's capability)
-#ifdef QOS_DLS_SUPPORT
-		BOOLEAN	bDLSFrame = FALSE;
-		INT	DlsEntryIndex = 0;
-
-		DlsEntryIndex = RTMPCheckDLSFrame(pAd, pTxBlk->pSrcBufHeader);
-		if (DlsEntryIndex >= 0)
-			bDLSFrame = TRUE;
-		else
-			bDLSFrame = FALSE;
-#endif // QOS_DLS_SUPPORT //
-
-		// The addr3 of normal packet send from DS is Dest Mac address.
-#ifdef QOS_DLS_SUPPORT
-		if (bDLSFrame)
-		{
-			COPY_MAC_ADDR(pHeader80211->Addr1, pTxBlk->pSrcBufHeader);
-			COPY_MAC_ADDR(pHeader80211->Addr3, pAd->CommonCfg.Bssid);
-			pHeader80211->FC.ToDs = 0;
-		}
-		else
-#endif // QOS_DLS_SUPPORT //
-		if (ADHOC_ON(pAd))
-			COPY_MAC_ADDR(pHeader80211->Addr3, pAd->CommonCfg.Bssid);
-		else
-			COPY_MAC_ADDR(pHeader80211->Addr3, pTxBlk->pSrcBufHeader);
-	}
-
-	// -----------------------------------------------------------------
-	// STEP 2. MAKE A COMMON 802.11 HEADER SHARED BY ENTIRE FRAGMENT BURST. Fill sequence later.
-	// -----------------------------------------------------------------
-	if (pAd->CommonCfg.bAPSDForcePowerSave)
-    	pHeader80211->FC.PwrMgmt = PWR_SAVE;
-	else
-    	pHeader80211->FC.PwrMgmt = (pAd->StaCfg.Psm == PWR_SAVE);
-}
-#endif // DOT11_N_SUPPORT //
-
-static inline PUCHAR STA_Build_ARalink_Frame_Header(
-	IN RTMP_ADAPTER *pAd,
-	IN TX_BLK		*pTxBlk)
-{
-	PUCHAR			pHeaderBufPtr;
-	HEADER_802_11	*pHeader_802_11;
-	PNDIS_PACKET	pNextPacket;
-	UINT32			nextBufLen;
-	PQUEUE_ENTRY	pQEntry;
-
-	STAFindCipherAlgorithm(pAd, pTxBlk);
-	STABuildCommon802_11Header(pAd, pTxBlk);
-
-
-	pHeaderBufPtr = &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-	pHeader_802_11 = (HEADER_802_11 *) pHeaderBufPtr;
-
-	// steal "order" bit to mark "aggregation"
-	pHeader_802_11->FC.Order = 1;
-
-	// skip common header
-	pHeaderBufPtr += pTxBlk->MpduHeaderLen;
-
-	if (TX_BLK_TEST_FLAG(pTxBlk, fTX_bWMM))
-	{
-		//
-		// build QOS Control bytes
-		//
-		*pHeaderBufPtr = (pTxBlk->UserPriority & 0x0F);
-
-		*(pHeaderBufPtr+1) = 0;
-		pHeaderBufPtr +=2;
-		pTxBlk->MpduHeaderLen += 2;
-	}
-
-	// padding at front of LLC header. LLC header should at 4-bytes aligment.
-	pTxBlk->HdrPadLen = (ULONG)pHeaderBufPtr;
-	pHeaderBufPtr = (PCHAR)ROUND_UP(pHeaderBufPtr, 4);
-	pTxBlk->HdrPadLen = (ULONG)(pHeaderBufPtr - pTxBlk->HdrPadLen);
-
-	// For RA Aggregation,
-	// put the 2nd MSDU length(extra 2-byte field) after QOS_CONTROL in little endian format
-	pQEntry = pTxBlk->TxPacketList.Head;
-	pNextPacket = QUEUE_ENTRY_TO_PKT(pQEntry);
-	nextBufLen = GET_OS_PKT_LEN(pNextPacket);
-	if (RTMP_GET_PACKET_VLAN(pNextPacket))
-		nextBufLen -= LENGTH_802_1Q;
-
-	*pHeaderBufPtr = (UCHAR)nextBufLen & 0xff;
-	*(pHeaderBufPtr+1) = (UCHAR)(nextBufLen >> 8);
-
-	pHeaderBufPtr += 2;
-	pTxBlk->MpduHeaderLen += 2;
-
-	return pHeaderBufPtr;
-
-}
-
-#ifdef DOT11_N_SUPPORT
-static inline PUCHAR STA_Build_AMSDU_Frame_Header(
-	IN RTMP_ADAPTER *pAd,
-	IN TX_BLK		*pTxBlk)
-{
-	PUCHAR			pHeaderBufPtr;//, pSaveBufPtr;
-	HEADER_802_11	*pHeader_802_11;
-
-
-	STAFindCipherAlgorithm(pAd, pTxBlk);
-	STABuildCommon802_11Header(pAd, pTxBlk);
-
-	pHeaderBufPtr = &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-	pHeader_802_11 = (HEADER_802_11 *) pHeaderBufPtr;
-
-	// skip common header
-	pHeaderBufPtr += pTxBlk->MpduHeaderLen;
-
-	//
-	// build QOS Control bytes
-	//
-	*pHeaderBufPtr = (pTxBlk->UserPriority & 0x0F);
-
-	//
-	// A-MSDU packet
-	//
-	*pHeaderBufPtr |= 0x80;
-
-	*(pHeaderBufPtr+1) = 0;
-	pHeaderBufPtr +=2;
-	pTxBlk->MpduHeaderLen += 2;
-
-	//pSaveBufPtr = pHeaderBufPtr;
-
-	//
-	// padding at front of LLC header
-	// LLC header should locate at 4-octets aligment
-	//
-	// @@@ MpduHeaderLen excluding padding @@@
-	//
-	pTxBlk->HdrPadLen = (ULONG)pHeaderBufPtr;
-	pHeaderBufPtr = (PCHAR) ROUND_UP(pHeaderBufPtr, 4);
-	pTxBlk->HdrPadLen = (ULONG)(pHeaderBufPtr - pTxBlk->HdrPadLen);
-
-	return pHeaderBufPtr;
-
-}
-
-
-VOID STA_AMPDU_Frame_Tx(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk)
-{
-	HEADER_802_11	*pHeader_802_11;
-	PUCHAR			pHeaderBufPtr;
-	USHORT			FreeNumber;
-	MAC_TABLE_ENTRY	*pMacEntry;
-	BOOLEAN			bVLANPkt;
-	PQUEUE_ENTRY	pQEntry;
-
-	ASSERT(pTxBlk);
-
-	while(pTxBlk->TxPacketList.Head)
-	{
-		pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-		pTxBlk->pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-		if ( RTMP_FillTxBlkInfo(pAd, pTxBlk) != TRUE)
-		{
-			RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-			continue;
-		}
-
-		bVLANPkt = (RTMP_GET_PACKET_VLAN(pTxBlk->pPacket) ? TRUE : FALSE);
-
-		pMacEntry = pTxBlk->pMacEntry;
-		if (pMacEntry->isCached)
-		{
-			// NOTE: Please make sure the size of pMacEntry->CachedBuf[] is smaller than pTxBlk->HeaderBuf[]!!!!
-			NdisMoveMemory((PUCHAR)&pTxBlk->HeaderBuf[TXINFO_SIZE], (PUCHAR)&pMacEntry->CachedBuf[0], TXWI_SIZE + sizeof(HEADER_802_11));
-			pHeaderBufPtr = (PUCHAR)(&pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE]);
-			STABuildCache802_11Header(pAd, pTxBlk, pHeaderBufPtr);
-		}
-		else
-		{
-			STAFindCipherAlgorithm(pAd, pTxBlk);
-			STABuildCommon802_11Header(pAd, pTxBlk);
-
-			pHeaderBufPtr = &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-		}
-
-
-		pHeader_802_11 = (HEADER_802_11 *) pHeaderBufPtr;
-
-		// skip common header
-		pHeaderBufPtr += pTxBlk->MpduHeaderLen;
-
-		//
-		// build QOS Control bytes
-		//
-		*pHeaderBufPtr = (pTxBlk->UserPriority & 0x0F);
-		*(pHeaderBufPtr+1) = 0;
-		pHeaderBufPtr +=2;
-		pTxBlk->MpduHeaderLen += 2;
-
-		//
-		// build HTC+
-		// HTC control filed following QoS field
-		//
-		if ((pAd->CommonCfg.bRdg == TRUE) && CLIENT_STATUS_TEST_FLAG(pTxBlk->pMacEntry, fCLIENT_STATUS_RDG_CAPABLE))
-		{
-			if (pMacEntry->isCached == FALSE)
-			{
-				// mark HTC bit
-				pHeader_802_11->FC.Order = 1;
-
-				NdisZeroMemory(pHeaderBufPtr, 4);
-				*(pHeaderBufPtr+3) |= 0x80;
-			}
-			pHeaderBufPtr += 4;
-			pTxBlk->MpduHeaderLen += 4;
-		}
-
-		//pTxBlk->MpduHeaderLen = pHeaderBufPtr - pTxBlk->HeaderBuf - TXWI_SIZE - TXINFO_SIZE;
-		ASSERT(pTxBlk->MpduHeaderLen >= 24);
-
-		// skip 802.3 header
-		pTxBlk->pSrcBufData = pTxBlk->pSrcBufHeader + LENGTH_802_3;
-		pTxBlk->SrcBufLen  -= LENGTH_802_3;
-
-		// skip vlan tag
-		if (bVLANPkt)
-		{
-			pTxBlk->pSrcBufData	+= LENGTH_802_1Q;
-			pTxBlk->SrcBufLen	-= LENGTH_802_1Q;
-		}
-
-		//
-		// padding at front of LLC header
-		// LLC header should locate at 4-octets aligment
-		//
-		// @@@ MpduHeaderLen excluding padding @@@
-		//
-		pTxBlk->HdrPadLen = (ULONG)pHeaderBufPtr;
-		pHeaderBufPtr = (PCHAR) ROUND_UP(pHeaderBufPtr, 4);
-		pTxBlk->HdrPadLen = (ULONG)(pHeaderBufPtr - pTxBlk->HdrPadLen);
-
-		{
-
-			//
-			// Insert LLC-SNAP encapsulation - 8 octets
-			//
-			EXTRA_LLCSNAP_ENCAP_FROM_PKT_OFFSET(pTxBlk->pSrcBufData-2, pTxBlk->pExtraLlcSnapEncap);
-			if (pTxBlk->pExtraLlcSnapEncap)
-			{
-				NdisMoveMemory(pHeaderBufPtr, pTxBlk->pExtraLlcSnapEncap, 6);
-				pHeaderBufPtr += 6;
-				// get 2 octets (TypeofLen)
-				NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufData-2, 2);
-				pHeaderBufPtr += 2;
-				pTxBlk->MpduHeaderLen += LENGTH_802_1_H;
-			}
-
-		}
-
-		if (pMacEntry->isCached)
-		{
-            RTMPWriteTxWI_Cache(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-		}
-		else
-		{
-			RTMPWriteTxWI_Data(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-
-			NdisZeroMemory((PUCHAR)(&pMacEntry->CachedBuf[0]), sizeof(pMacEntry->CachedBuf));
-			NdisMoveMemory((PUCHAR)(&pMacEntry->CachedBuf[0]), (PUCHAR)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), (pHeaderBufPtr - (PUCHAR)(&pTxBlk->HeaderBuf[TXINFO_SIZE])));
-			pMacEntry->isCached = TRUE;
-		}
-
-		// calculate Transmitted AMPDU count and ByteCount
-		{
-			pAd->RalinkCounters.TransmittedMPDUsInAMPDUCount.u.LowPart ++;
-			pAd->RalinkCounters.TransmittedOctetsInAMPDUCount.QuadPart += pTxBlk->SrcBufLen;
-		}
-
-		//FreeNumber = GET_TXRING_FREENO(pAd, QueIdx);
-
-		HAL_WriteTxResource(pAd, pTxBlk, TRUE, &FreeNumber);
-
-		//
-		// Kick out Tx
-		//
-		HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
-
-		pAd->RalinkCounters.KickTxCount++;
-		pAd->RalinkCounters.OneSecTxDoneCount++;
-	}
-
-}
-
-
-VOID STA_AMSDU_Frame_Tx(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk)
-{
-	PUCHAR			pHeaderBufPtr;
-	USHORT			FreeNumber;
-	USHORT			subFramePayloadLen = 0;	// AMSDU Subframe length without AMSDU-Header / Padding.
-	USHORT			totalMPDUSize=0;
-	UCHAR			*subFrameHeader;
-	UCHAR			padding = 0;
-	USHORT			FirstTx = 0, LastTxIdx = 0;
-	BOOLEAN			bVLANPkt;
-	int 			frameNum = 0;
-	PQUEUE_ENTRY	pQEntry;
-
-
-	ASSERT(pTxBlk);
-
-	ASSERT((pTxBlk->TxPacketList.Number > 1));
-
-	while(pTxBlk->TxPacketList.Head)
-	{
-		pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-		pTxBlk->pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-		if (RTMP_FillTxBlkInfo(pAd, pTxBlk) != TRUE)
-		{
-			RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-			continue;
-		}
-
-		bVLANPkt = (RTMP_GET_PACKET_VLAN(pTxBlk->pPacket) ? TRUE : FALSE);
-
-		// skip 802.3 header
-		pTxBlk->pSrcBufData = pTxBlk->pSrcBufHeader + LENGTH_802_3;
-		pTxBlk->SrcBufLen  -= LENGTH_802_3;
-
-		// skip vlan tag
-		if (bVLANPkt)
-		{
-			pTxBlk->pSrcBufData	+= LENGTH_802_1Q;
-			pTxBlk->SrcBufLen	-= LENGTH_802_1Q;
-		}
-
-		if (frameNum == 0)
-		{
-			pHeaderBufPtr = STA_Build_AMSDU_Frame_Header(pAd, pTxBlk);
-
-			// NOTE: TxWI->MPDUtotalByteCount will be updated after final frame was handled.
-			RTMPWriteTxWI_Data(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-		}
-		else
-		{
-			pHeaderBufPtr = &pTxBlk->HeaderBuf[0];
-			padding = ROUND_UP(LENGTH_AMSDU_SUBFRAMEHEAD + subFramePayloadLen, 4) - (LENGTH_AMSDU_SUBFRAMEHEAD + subFramePayloadLen);
-			NdisZeroMemory(pHeaderBufPtr, padding + LENGTH_AMSDU_SUBFRAMEHEAD);
-			pHeaderBufPtr += padding;
-			pTxBlk->MpduHeaderLen = padding;
-		}
-
-		//
-		// A-MSDU subframe
-		//   DA(6)+SA(6)+Length(2) + LLC/SNAP Encap
-		//
-		subFrameHeader = pHeaderBufPtr;
-		subFramePayloadLen = pTxBlk->SrcBufLen;
-
-		NdisMoveMemory(subFrameHeader, pTxBlk->pSrcBufHeader, 12);
-
-
-		pHeaderBufPtr += LENGTH_AMSDU_SUBFRAMEHEAD;
-		pTxBlk->MpduHeaderLen += LENGTH_AMSDU_SUBFRAMEHEAD;
-
-
-		//
-		// Insert LLC-SNAP encapsulation - 8 octets
-		//
-		EXTRA_LLCSNAP_ENCAP_FROM_PKT_OFFSET(pTxBlk->pSrcBufData-2, pTxBlk->pExtraLlcSnapEncap);
-
-		subFramePayloadLen = pTxBlk->SrcBufLen;
-
-		if (pTxBlk->pExtraLlcSnapEncap)
-		{
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pExtraLlcSnapEncap, 6);
-			pHeaderBufPtr += 6;
-			// get 2 octets (TypeofLen)
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufData-2, 2);
-			pHeaderBufPtr += 2;
-			pTxBlk->MpduHeaderLen += LENGTH_802_1_H;
-			subFramePayloadLen += LENGTH_802_1_H;
-		}
-
-		// update subFrame Length field
-		subFrameHeader[12] = (subFramePayloadLen & 0xFF00) >> 8;
-		subFrameHeader[13] = subFramePayloadLen & 0xFF;
-
-		totalMPDUSize += pTxBlk->MpduHeaderLen + pTxBlk->SrcBufLen;
-
-		if (frameNum ==0)
-			FirstTx = HAL_WriteMultiTxResource(pAd, pTxBlk, frameNum, &FreeNumber);
-		else
-			LastTxIdx = HAL_WriteMultiTxResource(pAd, pTxBlk, frameNum, &FreeNumber);
-
-		frameNum++;
-
-		pAd->RalinkCounters.KickTxCount++;
-		pAd->RalinkCounters.OneSecTxDoneCount++;
-
-		// calculate Transmitted AMSDU Count and ByteCount
-		{
-			pAd->RalinkCounters.TransmittedAMSDUCount.u.LowPart ++;
-			pAd->RalinkCounters.TransmittedOctetsInAMSDU.QuadPart += totalMPDUSize;
-		}
-
-	}
-
-	HAL_FinalWriteTxResource(pAd, pTxBlk, totalMPDUSize, FirstTx);
-	HAL_LastTxIdx(pAd, pTxBlk->QueIdx, LastTxIdx);
-
-	//
-	// Kick out Tx
-	//
-	HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
-}
-#endif // DOT11_N_SUPPORT //
-
-VOID STA_Legacy_Frame_Tx(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk)
-{
-	HEADER_802_11	*pHeader_802_11;
-	PUCHAR			pHeaderBufPtr;
-	USHORT			FreeNumber;
-	BOOLEAN			bVLANPkt;
-	PQUEUE_ENTRY	pQEntry;
-
-	ASSERT(pTxBlk);
-
-
-	pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-	pTxBlk->pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-	if (RTMP_FillTxBlkInfo(pAd, pTxBlk) != TRUE)
-	{
-		RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-	if (pTxBlk->TxFrameType == TX_MCAST_FRAME)
-	{
-		INC_COUNTER64(pAd->WlanCounters.MulticastTransmittedFrameCount);
-	}
-
-	if (RTMP_GET_PACKET_RTS(pTxBlk->pPacket))
-		TX_BLK_SET_FLAG(pTxBlk, fTX_bRtsRequired);
-	else
-		TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bRtsRequired);
-
-	bVLANPkt = (RTMP_GET_PACKET_VLAN(pTxBlk->pPacket) ? TRUE : FALSE);
-
-	if (pTxBlk->TxRate < pAd->CommonCfg.MinTxRate)
-		pTxBlk->TxRate = pAd->CommonCfg.MinTxRate;
-
-	STAFindCipherAlgorithm(pAd, pTxBlk);
-	STABuildCommon802_11Header(pAd, pTxBlk);
-
-
-	// skip 802.3 header
-	pTxBlk->pSrcBufData = pTxBlk->pSrcBufHeader + LENGTH_802_3;
-	pTxBlk->SrcBufLen  -= LENGTH_802_3;
-
-	// skip vlan tag
-	if (bVLANPkt)
-	{
-		pTxBlk->pSrcBufData	+= LENGTH_802_1Q;
-		pTxBlk->SrcBufLen	-= LENGTH_802_1Q;
-	}
-
-	pHeaderBufPtr = &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-	pHeader_802_11 = (HEADER_802_11 *) pHeaderBufPtr;
-
-	// skip common header
-	pHeaderBufPtr += pTxBlk->MpduHeaderLen;
-
-	if (TX_BLK_TEST_FLAG(pTxBlk, fTX_bWMM))
-	{
-		//
-		// build QOS Control bytes
-		//
-		*pHeaderBufPtr = (pTxBlk->UserPriority & 0x0F);
-		*(pHeaderBufPtr+1) = 0;
-		pHeaderBufPtr +=2;
-		pTxBlk->MpduHeaderLen += 2;
-	}
-
-	// The remaining content of MPDU header should locate at 4-octets aligment
-	pTxBlk->HdrPadLen = (ULONG)pHeaderBufPtr;
-	pHeaderBufPtr = (PCHAR) ROUND_UP(pHeaderBufPtr, 4);
-	pTxBlk->HdrPadLen = (ULONG)(pHeaderBufPtr - pTxBlk->HdrPadLen);
-
-	{
-
-		//
-		// Insert LLC-SNAP encapsulation - 8 octets
-		//
-		//
-   		// if original Ethernet frame contains no LLC/SNAP,
-		// then an extra LLC/SNAP encap is required
-		//
-		EXTRA_LLCSNAP_ENCAP_FROM_PKT_START(pTxBlk->pSrcBufHeader, pTxBlk->pExtraLlcSnapEncap);
-		if (pTxBlk->pExtraLlcSnapEncap)
-		{
-			UCHAR vlan_size;
-
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pExtraLlcSnapEncap, 6);
-			pHeaderBufPtr += 6;
-			// skip vlan tag
-			vlan_size =  (bVLANPkt) ? LENGTH_802_1Q : 0;
-			// get 2 octets (TypeofLen)
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufHeader+12+vlan_size, 2);
-			pHeaderBufPtr += 2;
-			pTxBlk->MpduHeaderLen += LENGTH_802_1_H;
-		}
-
-	}
-
-	//
-	// prepare for TXWI
-	// use Wcid as Key Index
-	//
-
-	RTMPWriteTxWI_Data(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-
-	//FreeNumber = GET_TXRING_FREENO(pAd, QueIdx);
-
-	HAL_WriteTxResource(pAd, pTxBlk, TRUE, &FreeNumber);
-
-	pAd->RalinkCounters.KickTxCount++;
-	pAd->RalinkCounters.OneSecTxDoneCount++;
-
-	//
-	// Kick out Tx
-	//
-	HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
-}
-
-
-VOID STA_ARalink_Frame_Tx(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk)
-{
-	PUCHAR			pHeaderBufPtr;
-	USHORT			FreeNumber;
-	USHORT			totalMPDUSize=0;
-	USHORT			FirstTx, LastTxIdx;
-	int 			frameNum = 0;
-	BOOLEAN			bVLANPkt;
-	PQUEUE_ENTRY	pQEntry;
-
-
-	ASSERT(pTxBlk);
-
-	ASSERT((pTxBlk->TxPacketList.Number== 2));
-
-
-	FirstTx = LastTxIdx = 0;  // Is it ok init they as 0?
-	while(pTxBlk->TxPacketList.Head)
-	{
-		pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-		pTxBlk->pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-
-		if (RTMP_FillTxBlkInfo(pAd, pTxBlk) != TRUE)
-		{
-			RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-			continue;
-		}
-
-		bVLANPkt = (RTMP_GET_PACKET_VLAN(pTxBlk->pPacket) ? TRUE : FALSE);
-
-		// skip 802.3 header
-		pTxBlk->pSrcBufData = pTxBlk->pSrcBufHeader + LENGTH_802_3;
-		pTxBlk->SrcBufLen  -= LENGTH_802_3;
-
-		// skip vlan tag
-		if (bVLANPkt)
-		{
-			pTxBlk->pSrcBufData	+= LENGTH_802_1Q;
-			pTxBlk->SrcBufLen	-= LENGTH_802_1Q;
-		}
-
-		if (frameNum == 0)
-		{	// For first frame, we need to create the 802.11 header + padding(optional) + RA-AGG-LEN + SNAP Header
-
-			pHeaderBufPtr = STA_Build_ARalink_Frame_Header(pAd, pTxBlk);
-
-			// It's ok write the TxWI here, because the TxWI->MPDUtotalByteCount
-			//	will be updated after final frame was handled.
-			RTMPWriteTxWI_Data(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-
-
-			//
-			// Insert LLC-SNAP encapsulation - 8 octets
-			//
-			EXTRA_LLCSNAP_ENCAP_FROM_PKT_OFFSET(pTxBlk->pSrcBufData-2, pTxBlk->pExtraLlcSnapEncap);
-
-			if (pTxBlk->pExtraLlcSnapEncap)
-			{
-				NdisMoveMemory(pHeaderBufPtr, pTxBlk->pExtraLlcSnapEncap, 6);
-				pHeaderBufPtr += 6;
-				// get 2 octets (TypeofLen)
-				NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufData-2, 2);
-				pHeaderBufPtr += 2;
-				pTxBlk->MpduHeaderLen += LENGTH_802_1_H;
-			}
-		}
-		else
-		{	// For second aggregated frame, we need create the 802.3 header to headerBuf, because PCI will copy it to SDPtr0.
-
-			pHeaderBufPtr = &pTxBlk->HeaderBuf[0];
-			pTxBlk->MpduHeaderLen = 0;
-
-			// A-Ralink sub-sequent frame header is the same as 802.3 header.
-			//   DA(6)+SA(6)+FrameType(2)
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufHeader, 12);
-			pHeaderBufPtr += 12;
-			// get 2 octets (TypeofLen)
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufData-2, 2);
-			pHeaderBufPtr += 2;
-			pTxBlk->MpduHeaderLen = LENGTH_ARALINK_SUBFRAMEHEAD;
-		}
-
-		totalMPDUSize += pTxBlk->MpduHeaderLen + pTxBlk->SrcBufLen;
-
-		//FreeNumber = GET_TXRING_FREENO(pAd, QueIdx);
-		if (frameNum ==0)
-			FirstTx = HAL_WriteMultiTxResource(pAd, pTxBlk, frameNum, &FreeNumber);
-		else
-			LastTxIdx = HAL_WriteMultiTxResource(pAd, pTxBlk, frameNum, &FreeNumber);
-
-		frameNum++;
-
-		pAd->RalinkCounters.OneSecTxAggregationCount++;
-		pAd->RalinkCounters.KickTxCount++;
-		pAd->RalinkCounters.OneSecTxDoneCount++;
-
-	}
-
-	HAL_FinalWriteTxResource(pAd, pTxBlk, totalMPDUSize, FirstTx);
-	HAL_LastTxIdx(pAd, pTxBlk->QueIdx, LastTxIdx);
-
-	//
-	// Kick out Tx
-	//
-	HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
-
-}
-
-
-VOID STA_Fragment_Frame_Tx(
-	IN RTMP_ADAPTER *pAd,
-	IN TX_BLK		*pTxBlk)
-{
-	HEADER_802_11	*pHeader_802_11;
-	PUCHAR			pHeaderBufPtr;
-	USHORT			FreeNumber;
-	UCHAR 			fragNum = 0;
-	PACKET_INFO		PacketInfo;
-	USHORT			EncryptionOverhead = 0;
-	UINT32			FreeMpduSize, SrcRemainingBytes;
-	USHORT			AckDuration;
-	UINT 			NextMpduSize;
-	BOOLEAN			bVLANPkt;
-	PQUEUE_ENTRY	pQEntry;
-
-
-	ASSERT(pTxBlk);
-
-	pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-	pTxBlk->pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-	if (RTMP_FillTxBlkInfo(pAd, pTxBlk) != TRUE)
-	{
-		RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-	ASSERT(TX_BLK_TEST_FLAG(pTxBlk, fTX_bAllowFrag));
-	bVLANPkt = (RTMP_GET_PACKET_VLAN(pTxBlk->pPacket) ? TRUE : FALSE);
-
-	STAFindCipherAlgorithm(pAd, pTxBlk);
-	STABuildCommon802_11Header(pAd, pTxBlk);
-
-	if (pTxBlk->CipherAlg == CIPHER_TKIP)
-	{
-		pTxBlk->pPacket = duplicate_pkt_with_TKIP_MIC(pAd, pTxBlk->pPacket);
-		if (pTxBlk->pPacket == NULL)
-			return;
-		RTMP_QueryPacketInfo(pTxBlk->pPacket, &PacketInfo, &pTxBlk->pSrcBufHeader, &pTxBlk->SrcBufLen);
-	}
-
-	// skip 802.3 header
-	pTxBlk->pSrcBufData = pTxBlk->pSrcBufHeader + LENGTH_802_3;
-	pTxBlk->SrcBufLen  -= LENGTH_802_3;
-
-
-	// skip vlan tag
-	if (bVLANPkt)
-	{
-		pTxBlk->pSrcBufData	+= LENGTH_802_1Q;
-		pTxBlk->SrcBufLen	-= LENGTH_802_1Q;
-	}
-
-	pHeaderBufPtr = &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-	pHeader_802_11 = (HEADER_802_11 *)pHeaderBufPtr;
-
-
-	// skip common header
-	pHeaderBufPtr += pTxBlk->MpduHeaderLen;
-
-	if (TX_BLK_TEST_FLAG(pTxBlk, fTX_bWMM))
-	{
-		//
-		// build QOS Control bytes
-		//
-		*pHeaderBufPtr = (pTxBlk->UserPriority & 0x0F);
-
-		*(pHeaderBufPtr+1) = 0;
-		pHeaderBufPtr +=2;
-		pTxBlk->MpduHeaderLen += 2;
-	}
-
-	//
-	// padding at front of LLC header
-	// LLC header should locate at 4-octets aligment
-	//
-	pTxBlk->HdrPadLen = (ULONG)pHeaderBufPtr;
-	pHeaderBufPtr = (PCHAR) ROUND_UP(pHeaderBufPtr, 4);
-	pTxBlk->HdrPadLen = (ULONG)(pHeaderBufPtr - pTxBlk->HdrPadLen);
-
-
-
-	//
-	// Insert LLC-SNAP encapsulation - 8 octets
-	//
-	//
-   	// if original Ethernet frame contains no LLC/SNAP,
-	// then an extra LLC/SNAP encap is required
-	//
-	EXTRA_LLCSNAP_ENCAP_FROM_PKT_START(pTxBlk->pSrcBufHeader, pTxBlk->pExtraLlcSnapEncap);
-	if (pTxBlk->pExtraLlcSnapEncap)
-	{
-		UCHAR vlan_size;
-
-		NdisMoveMemory(pHeaderBufPtr, pTxBlk->pExtraLlcSnapEncap, 6);
-		pHeaderBufPtr += 6;
-		// skip vlan tag
-		vlan_size =  (bVLANPkt) ? LENGTH_802_1Q : 0;
-		// get 2 octets (TypeofLen)
-		NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufHeader+12+vlan_size, 2);
-		pHeaderBufPtr += 2;
-		pTxBlk->MpduHeaderLen += LENGTH_802_1_H;
-	}
-
-
-	// If TKIP is used and fragmentation is required. Driver has to
-	//	append TKIP MIC at tail of the scatter buffer
-	//	MAC ASIC will only perform IV/EIV/ICV insertion but no TKIP MIC
-	if (pTxBlk->CipherAlg == CIPHER_TKIP)
-	{
-
-		// NOTE: DON'T refer the skb->len directly after following copy. Becasue the length is not adjust
-		//			to correct lenght, refer to pTxBlk->SrcBufLen for the packet length in following progress.
-		NdisMoveMemory(pTxBlk->pSrcBufData + pTxBlk->SrcBufLen, &pAd->PrivateInfo.Tx.MIC[0], 8);
-		//skb_put((RTPKT_TO_OSPKT(pTxBlk->pPacket))->tail, 8);
-		pTxBlk->SrcBufLen += 8;
-		pTxBlk->TotalFrameLen += 8;
-		pTxBlk->CipherAlg = CIPHER_TKIP_NO_MIC;
-	}
-
-	//
-	// calcuate the overhead bytes that encryption algorithm may add. This
-	// affects the calculate of "duration" field
-	//
-	if ((pTxBlk->CipherAlg == CIPHER_WEP64) || (pTxBlk->CipherAlg == CIPHER_WEP128))
-		EncryptionOverhead = 8; //WEP: IV[4] + ICV[4];
-	else if (pTxBlk->CipherAlg == CIPHER_TKIP_NO_MIC)
-		EncryptionOverhead = 12;//TKIP: IV[4] + EIV[4] + ICV[4], MIC will be added to TotalPacketLength
-	else if (pTxBlk->CipherAlg == CIPHER_TKIP)
-		EncryptionOverhead = 20;//TKIP: IV[4] + EIV[4] + ICV[4] + MIC[8]
-	else if (pTxBlk->CipherAlg == CIPHER_AES)
-		EncryptionOverhead = 16;	// AES: IV[4] + EIV[4] + MIC[8]
-	else
-		EncryptionOverhead = 0;
-
-	// decide how much time an ACK/CTS frame will consume in the air
-	AckDuration = RTMPCalcDuration(pAd, pAd->CommonCfg.ExpectedACKRate[pTxBlk->TxRate], 14);
-
-	// Init the total payload length of this frame.
-	SrcRemainingBytes = pTxBlk->SrcBufLen;
-
-	pTxBlk->TotalFragNum = 0xff;
-
-	do {
-
-		FreeMpduSize = pAd->CommonCfg.FragmentThreshold - LENGTH_CRC;
-
-		FreeMpduSize -= pTxBlk->MpduHeaderLen;
-
-		if (SrcRemainingBytes <= FreeMpduSize)
-		{	// this is the last or only fragment
-
-			pTxBlk->SrcBufLen = SrcRemainingBytes;
-
-			pHeader_802_11->FC.MoreFrag = 0;
-			pHeader_802_11->Duration = pAd->CommonCfg.Dsifs + AckDuration;
-
-			// Indicate the lower layer that this's the last fragment.
-			pTxBlk->TotalFragNum = fragNum;
-		}
-		else
-		{	// more fragment is required
-
-			pTxBlk->SrcBufLen = FreeMpduSize;
-
-			NextMpduSize = min(((UINT)SrcRemainingBytes - pTxBlk->SrcBufLen), ((UINT)pAd->CommonCfg.FragmentThreshold));
-			pHeader_802_11->FC.MoreFrag = 1;
-			pHeader_802_11->Duration = (3 * pAd->CommonCfg.Dsifs) + (2 * AckDuration) + RTMPCalcDuration(pAd, pTxBlk->TxRate, NextMpduSize + EncryptionOverhead);
-		}
-
-		if (fragNum == 0)
-			pTxBlk->FrameGap = IFS_HTTXOP;
-		else
-			pTxBlk->FrameGap = IFS_SIFS;
-
-		RTMPWriteTxWI_Data(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-
-		HAL_WriteFragTxResource(pAd, pTxBlk, fragNum, &FreeNumber);
-
-		pAd->RalinkCounters.KickTxCount++;
-		pAd->RalinkCounters.OneSecTxDoneCount++;
-
-		// Update the frame number, remaining size of the NDIS packet payload.
-
-		// space for 802.11 header.
-		if (fragNum == 0 && pTxBlk->pExtraLlcSnapEncap)
-			pTxBlk->MpduHeaderLen -= LENGTH_802_1_H;
-
-		fragNum++;
-		SrcRemainingBytes -= pTxBlk->SrcBufLen;
-		pTxBlk->pSrcBufData += pTxBlk->SrcBufLen;
-
-		pHeader_802_11->Frag++;	 // increase Frag #
-
-	}while(SrcRemainingBytes > 0);
-
-	//
-	// Kick out Tx
-	//
-	HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
-}
-
-
-#define RELEASE_FRAMES_OF_TXBLK(_pAd, _pTxBlk, _pQEntry, _Status) 										\
-		while(_pTxBlk->TxPacketList.Head)														\
-		{																						\
-			_pQEntry = RemoveHeadQueue(&_pTxBlk->TxPacketList);									\
-			RELEASE_NDIS_PACKET(_pAd, QUEUE_ENTRY_TO_PACKET(_pQEntry), _Status);	\
-		}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Copy frame from waiting queue into relative ring buffer and set
-	appropriate ASIC register to kick hardware encryption before really
-	sent out to air.
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		PNDIS_PACKET	Pointer to outgoing Ndis frame
-		NumberOfFrag	Number of fragment required
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS STAHardTransmit(
-	IN PRTMP_ADAPTER	pAd,
-	IN TX_BLK 			*pTxBlk,
-	IN	UCHAR			QueIdx)
-{
-	NDIS_PACKET		*pPacket;
-	PQUEUE_ENTRY	pQEntry;
-
-	// ---------------------------------------------
-	// STEP 0. DO SANITY CHECK AND SOME EARLY PREPARATION.
-	// ---------------------------------------------
-	//
-	ASSERT(pTxBlk->TxPacketList.Number);
-	if (pTxBlk->TxPacketList.Head == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("pTxBlk->TotalFrameNum == %ld!\n", pTxBlk->TxPacketList.Number));
-		return NDIS_STATUS_FAILURE;
-	}
-
-	pPacket = QUEUE_ENTRY_TO_PACKET(pTxBlk->TxPacketList.Head);
-
-#if 0 //def CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-		if ((pAd->CommonCfg.CarrierDetect.Enable == TRUE) && (isCarrierDetectExist(pAd) == TRUE))
-	{
-		DBGPRINT(RT_DEBUG_INFO,("STAHardTransmit --> radar detect not in normal mode !!!\n"));
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-		return (NDIS_STATUS_FAILURE);
-	}
-#endif // CARRIER_DETECTION_SUPPORT //
-
-	// ------------------------------------------------------------------
-	// STEP 1. WAKE UP PHY
-	//		outgoing frame always wakeup PHY to prevent frame lost and
-	//		turn off PSM bit to improve performance
-	// ------------------------------------------------------------------
-	// not to change PSM bit, just send this frame out?
-	if ((pAd->StaCfg.Psm == PWR_SAVE) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-	{
-	    DBGPRINT_RAW(RT_DEBUG_TRACE, ("AsicForceWakeup At HardTx\n"));
-		AsicForceWakeup(pAd, TRUE);
-	}
-
-	// It should not change PSM bit, when APSD turn on.
-	if ((!(pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable) && (pAd->CommonCfg.bAPSDForcePowerSave == FALSE))
-		|| (RTMP_GET_PACKET_EAPOL(pTxBlk->pPacket))
-		|| (RTMP_GET_PACKET_WAI(pTxBlk->pPacket)))
-	{
-		if ((pAd->StaCfg.Psm == PWR_SAVE) &&
-            (pAd->StaCfg.WindowsPowerMode == Ndis802_11PowerModeFast_PSP))
-			MlmeSetPsmBit(pAd, PWR_ACTIVE);
-	}
-
-	switch (pTxBlk->TxFrameType)
-	{
-#ifdef DOT11_N_SUPPORT
-		case TX_AMPDU_FRAME:
-				STA_AMPDU_Frame_Tx(pAd, pTxBlk);
-			break;
-		case TX_AMSDU_FRAME:
-				STA_AMSDU_Frame_Tx(pAd, pTxBlk);
-			break;
-#endif // DOT11_N_SUPPORT //
-		case TX_LEGACY_FRAME:
-				STA_Legacy_Frame_Tx(pAd, pTxBlk);
-			break;
-		case TX_MCAST_FRAME:
-				STA_Legacy_Frame_Tx(pAd, pTxBlk);
-			break;
-		case TX_RALINK_FRAME:
-				STA_ARalink_Frame_Tx(pAd, pTxBlk);
-			break;
-		case TX_FRAG_FRAME:
-				STA_Fragment_Frame_Tx(pAd, pTxBlk);
-			break;
-		default:
-			{
-				// It should not happened!
-				DBGPRINT(RT_DEBUG_ERROR, ("Send a pacekt was not classified!! It should not happen!\n"));
-				while(pTxBlk->TxPacketList.Number)
-				{
-					pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-					pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-					if (pPacket)
-						RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-				}
-			}
-			break;
-	}
-
-	return (NDIS_STATUS_SUCCESS);
-
-}
-
-ULONG  HashBytesPolynomial(UCHAR *value, unsigned int len)
-{
-   unsigned char *word = value;
-   unsigned int ret = 0;
-   unsigned int i;
-
-   for(i=0; i < len; i++)
-   {
-	  int mod = i % 32;
-	  ret ^=(unsigned int) (word[i]) << mod;
-	  ret ^=(unsigned int) (word[i]) >> (32 - mod);
-   }
-   return ret;
-}
-
-VOID Sta_Announce_or_Forward_802_3_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UCHAR			FromWhichBSSID)
-{
-	if (TRUE
-		)
-	{
-		announce_802_3_packet(pAd, pPacket);
-	}
-	else
-	{
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-	}
-}
-
+#include "../../rt2860/sta/rtmp_data.c"
diff --git a/drivers/staging/rt2870/sta/sanity.c b/drivers/staging/rt2870/sta/sanity.c
index 2398724..f1f2333 100644
--- a/drivers/staging/rt2870/sta/sanity.c
+++ b/drivers/staging/rt2870/sta/sanity.c
@@ -1,420 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	sanity.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang  2004-09-01      add WMM support
-*/
-#include "../rt_config.h"
-
-extern UCHAR	CISCO_OUI[];
-
-extern UCHAR	WPA_OUI[];
-extern UCHAR	RSN_OUI[];
-extern UCHAR	WME_INFO_ELEM[];
-extern UCHAR	WME_PARM_ELEM[];
-extern UCHAR	Ccx2QosInfo[];
-extern UCHAR	RALINK_OUI[];
-extern UCHAR	BROADCOM_OUI[];
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
- */
-BOOLEAN MlmeStartReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT CHAR Ssid[],
-    OUT UCHAR *pSsidLen)
-{
-    MLME_START_REQ_STRUCT *Info;
-
-    Info = (MLME_START_REQ_STRUCT *)(Msg);
-
-    if (Info->SsidLen > MAX_LEN_OF_SSID)
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeStartReqSanity fail - wrong SSID length\n"));
-        return FALSE;
-    }
-
-    *pSsidLen = Info->SsidLen;
-    NdisMoveMemory(Ssid, Info->Ssid, *pSsidLen);
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-    IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerAssocRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *pMsg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pStatus,
-    OUT USHORT *pAid,
-    OUT UCHAR SupRate[],
-    OUT UCHAR *pSupRateLen,
-    OUT UCHAR ExtRate[],
-    OUT UCHAR *pExtRateLen,
-    OUT HT_CAPABILITY_IE		*pHtCapability,
-    OUT ADD_HT_INFO_IE		*pAddHtInfo,	// AP might use this additional ht info IE
-    OUT UCHAR			*pHtCapabilityLen,
-    OUT UCHAR			*pAddHtInfoLen,
-    OUT UCHAR			*pNewExtChannelOffset,
-    OUT PEDCA_PARM pEdcaParm,
-    OUT UCHAR *pCkipFlag)
-{
-    CHAR          IeType, *Ptr;
-    PFRAME_802_11 pFrame = (PFRAME_802_11)pMsg;
-    PEID_STRUCT   pEid;
-    ULONG         Length = 0;
-
-	*pNewExtChannelOffset = 0xff;
-	*pHtCapabilityLen = 0;
-	*pAddHtInfoLen = 0;
-    COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-    Ptr = pFrame->Octet;
-    Length += LENGTH_802_11;
-
-    NdisMoveMemory(pCapabilityInfo, &pFrame->Octet[0], 2);
-    Length += 2;
-    NdisMoveMemory(pStatus,         &pFrame->Octet[2], 2);
-    Length += 2;
-    *pCkipFlag = 0;
-    *pExtRateLen = 0;
-    pEdcaParm->bValid = FALSE;
-
-    if (*pStatus != MLME_SUCCESS)
-        return TRUE;
-
-    NdisMoveMemory(pAid, &pFrame->Octet[4], 2);
-    Length += 2;
-
-    // Aid already swaped byte order in RTMPFrameEndianChange() for big endian platform
-    *pAid = (*pAid) & 0x3fff; // AID is low 14-bit
-
-    // -- get supported rates from payload and advance the pointer
-    IeType = pFrame->Octet[6];
-    *pSupRateLen = pFrame->Octet[7];
-    if ((IeType != IE_SUPP_RATES) || (*pSupRateLen > MAX_LEN_OF_SUPPORTED_RATES))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("PeerAssocRspSanity fail - wrong SupportedRates IE\n"));
-        return FALSE;
-    }
-    else
-        NdisMoveMemory(SupRate, &pFrame->Octet[8], *pSupRateLen);
-
-    Length = Length + 2 + *pSupRateLen;
-
-    // many AP implement proprietary IEs in non-standard order, we'd better
-    // tolerate mis-ordered IEs to get best compatibility
-    pEid = (PEID_STRUCT) &pFrame->Octet[8 + (*pSupRateLen)];
-
-    // get variable fields from payload and advance the pointer
-    while ((Length + 2 + pEid->Len) <= MsgLen)
-    {
-        switch (pEid->Eid)
-        {
-            case IE_EXT_SUPP_RATES:
-                if (pEid->Len <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    NdisMoveMemory(ExtRate, pEid->Octet, pEid->Len);
-                    *pExtRateLen = pEid->Len;
-                }
-                break;
-
-             case IE_HT_CAP:
-            case IE_HT_CAP2:
-			if (pEid->Len >= SIZE_HT_CAP_IE)  //Note: allow extension.!!
-			{
-				NdisMoveMemory(pHtCapability, pEid->Octet, SIZE_HT_CAP_IE);
-
-				*(USHORT *)(&pHtCapability->HtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->HtCapInfo));
-				*(USHORT *)(&pHtCapability->ExtHtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->ExtHtCapInfo));
-
-				*pHtCapabilityLen = SIZE_HT_CAP_IE;
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerAssocRspSanity - wrong IE_HT_CAP. \n"));
-			}
-
-		break;
-#ifdef DOT11_N_SUPPORT
-            case IE_ADD_HT:
-            case IE_ADD_HT2:
-			if (pEid->Len >= sizeof(ADD_HT_INFO_IE))
-			{
-				// This IE allows extension, but we can ignore extra bytes beyond our knowledge , so only
-				// copy first sizeof(ADD_HT_INFO_IE)
-				NdisMoveMemory(pAddHtInfo, pEid->Octet, sizeof(ADD_HT_INFO_IE));
-
-				*(USHORT *)(&pAddHtInfo->AddHtInfo2) = cpu2le16(*(USHORT *)(&pAddHtInfo->AddHtInfo2));
-				*(USHORT *)(&pAddHtInfo->AddHtInfo3) = cpu2le16(*(USHORT *)(&pAddHtInfo->AddHtInfo3));
-
-				*pAddHtInfoLen = SIZE_ADD_HT_INFO_IE;
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerAssocRspSanity - wrong IE_ADD_HT. \n"));
-			}
-
-		break;
-            case IE_SECONDARY_CH_OFFSET:
-			if (pEid->Len == 1)
-			{
-				*pNewExtChannelOffset = pEid->Octet[0];
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerAssocRspSanity - wrong IE_SECONDARY_CH_OFFSET. \n"));
-			}
-#endif // DOT11_N_SUPPORT //
-		break;
-            case IE_AIRONET_CKIP:
-                // 0. Check Aironet IE length, it must be larger or equal to 28
-                //    Cisco's AP VxWork version(will not be supported) used this IE length as 28
-                //    Cisco's AP IOS version used this IE length as 30
-                if (pEid->Len < (CKIP_NEGOTIATION_LENGTH - 2))
-                break;
-
-                // 1. Copy CKIP flag byte to buffer for process
-                *pCkipFlag = *(pEid->Octet + 8);
-                break;
-
-            case IE_AIRONET_IPADDRESS:
-                if (pEid->Len != 0x0A)
-                break;
-
-                // Get Cisco Aironet IP information
-                if (NdisEqualMemory(pEid->Octet, CISCO_OUI, 3) == 1)
-                    NdisMoveMemory(pAd->StaCfg.AironetIPAddress, pEid->Octet + 4, 4);
-                break;
-
-            // CCX2, WMM use the same IE value
-            // case IE_CCX_V2:
-            case IE_VENDOR_SPECIFIC:
-                // handle WME PARAMTER ELEMENT
-                if (NdisEqualMemory(pEid->Octet, WME_PARM_ELEM, 6) && (pEid->Len == 24))
-                {
-                    PUCHAR ptr;
-                    int i;
-
-                    // parsing EDCA parameters
-                    pEdcaParm->bValid          = TRUE;
-                    pEdcaParm->bQAck           = FALSE; // pEid->Octet[0] & 0x10;
-                    pEdcaParm->bQueueRequest   = FALSE; // pEid->Octet[0] & 0x20;
-                    pEdcaParm->bTxopRequest    = FALSE; // pEid->Octet[0] & 0x40;
-                    //pEdcaParm->bMoreDataAck    = FALSE; // pEid->Octet[0] & 0x80;
-                    pEdcaParm->EdcaUpdateCount = pEid->Octet[6] & 0x0f;
-                    pEdcaParm->bAPSDCapable    = (pEid->Octet[6] & 0x80) ? 1 : 0;
-                    ptr = &pEid->Octet[8];
-                    for (i=0; i<4; i++)
-                    {
-                        UCHAR aci = (*ptr & 0x60) >> 5; // b5~6 is AC INDEX
-                        pEdcaParm->bACM[aci]  = (((*ptr) & 0x10) == 0x10);   // b5 is ACM
-                        pEdcaParm->Aifsn[aci] = (*ptr) & 0x0f;               // b0~3 is AIFSN
-                        pEdcaParm->Cwmin[aci] = *(ptr+1) & 0x0f;             // b0~4 is Cwmin
-                        pEdcaParm->Cwmax[aci] = *(ptr+1) >> 4;               // b5~8 is Cwmax
-                        pEdcaParm->Txop[aci]  = *(ptr+2) + 256 * (*(ptr+3)); // in unit of 32-us
-                        ptr += 4; // point to next AC
-                    }
-                }
-
-                // handle CCX IE
-                else
-                {
-                    // 0. Check the size and CCX admin control
-                    if (pAd->StaCfg.CCXControl.field.Enable == 0)
-                        break;
-                    if (pEid->Len != 5)
-                        break;
-
-                    // Turn CCX2 if matched
-                    if (NdisEqualMemory(pEid->Octet, Ccx2IeInfo, 5) == 1)
-                        pAd->StaCfg.CCXEnable = TRUE;
-                    break;
-                }
-                break;
-
-            default:
-                DBGPRINT(RT_DEBUG_TRACE, ("PeerAssocRspSanity - ignore unrecognized EID = %d\n", pEid->Eid));
-                break;
-        }
-
-        Length = Length + 2 + pEid->Len;
-        pEid = (PEID_STRUCT)((UCHAR*)pEid + 2 + pEid->Len);
-    }
-
-    // Force CCX2 enable to TRUE for those AP didn't replay CCX v2 IE, we still force it to be on
-    if (pAd->StaCfg.CCXControl.field.Enable == 1)
-        pAd->StaCfg.CCXEnable = TRUE;
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerProbeReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT CHAR Ssid[],
-    OUT UCHAR *pSsidLen)
-{
-    UCHAR         Idx;
-    UCHAR	      RateLen;
-    CHAR          IeType;
-    PFRAME_802_11 pFrame = (PFRAME_802_11)Msg;
-
-    COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-
-    if ((pFrame->Octet[0] != IE_SSID) || (pFrame->Octet[1] > MAX_LEN_OF_SSID))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("PeerProbeReqSanity fail - wrong SSID IE(Type=%d,Len=%d)\n",pFrame->Octet[0],pFrame->Octet[1]));
-        return FALSE;
-    }
-
-    *pSsidLen = pFrame->Octet[1];
-    NdisMoveMemory(Ssid, &pFrame->Octet[2], *pSsidLen);
-
-    Idx = *pSsidLen + 2;
-
-    // -- get supported rates from payload and advance the pointer
-    IeType = pFrame->Octet[Idx];
-    RateLen = pFrame->Octet[Idx + 1];
-    if (IeType != IE_SUPP_RATES)
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("PeerProbeReqSanity fail - wrong SupportRates IE(Type=%d,Len=%d)\n",pFrame->Octet[Idx],pFrame->Octet[Idx+1]));
-        return FALSE;
-    }
-    else
-    {
-        if ((pAd->CommonCfg.PhyMode == PHY_11G) && (RateLen < 8))
-            return (FALSE);
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN GetTimBit(
-    IN CHAR *Ptr,
-    IN USHORT Aid,
-    OUT UCHAR *TimLen,
-    OUT UCHAR *BcastFlag,
-    OUT UCHAR *DtimCount,
-    OUT UCHAR *DtimPeriod,
-    OUT UCHAR *MessageToMe)
-{
-    UCHAR          BitCntl, N1, N2, MyByte, MyBit;
-    CHAR          *IdxPtr;
-
-    IdxPtr = Ptr;
-
-    IdxPtr ++;
-    *TimLen = *IdxPtr;
-
-    // get DTIM Count from TIM element
-    IdxPtr ++;
-    *DtimCount = *IdxPtr;
-
-    // get DTIM Period from TIM element
-    IdxPtr++;
-    *DtimPeriod = *IdxPtr;
-
-    // get Bitmap Control from TIM element
-    IdxPtr++;
-    BitCntl = *IdxPtr;
-
-    if ((*DtimCount == 0) && (BitCntl & 0x01))
-        *BcastFlag = TRUE;
-    else
-        *BcastFlag = FALSE;
-
-    // Parse Partial Virtual Bitmap from TIM element
-    N1 = BitCntl & 0xfe;    // N1 is the first bitmap byte#
-    N2 = *TimLen - 4 + N1;  // N2 is the last bitmap byte#
-
-    if ((Aid < (N1 << 3)) || (Aid >= ((N2 + 1) << 3)))
-        *MessageToMe = FALSE;
-    else
-    {
-        MyByte = (Aid >> 3) - N1;                       // my byte position in the bitmap byte-stream
-        MyBit = Aid % 16 - ((MyByte & 0x01)? 8:0);
-
-        IdxPtr += (MyByte + 1);
-
-        //if (*IdxPtr)
-        //    DBGPRINT(RT_DEBUG_WARN, ("TIM bitmap = 0x%02x\n", *IdxPtr));
-
-        if (*IdxPtr & (0x01 << MyBit))
-            *MessageToMe = TRUE;
-        else
-            *MessageToMe = FALSE;
-    }
-
-    return TRUE;
-}
-
+#include "../../rt2860/sta/sanity.c"
diff --git a/drivers/staging/rt2870/sta/sync.c b/drivers/staging/rt2870/sta/sync.c
index a489755..66c8772 100644
--- a/drivers/staging/rt2870/sta/sync.c
+++ b/drivers/staging/rt2870/sta/sync.c
@@ -1,1753 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	sync.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang	2004-09-01      modified for rt2561/2661
-	Jan Lee		2006-08-01      modified for rt2860 for 802.11n
-*/
-#include "../rt_config.h"
-
-#define ADHOC_ENTRY_BEACON_LOST_TIME	(2*OS_HZ)	// 2 sec
-
-/*
-	==========================================================================
-	Description:
-		The sync state machine,
-	Parameters:
-		Sm - pointer to the state machine
-	Note:
-		the state machine looks like the following
-
-	==========================================================================
- */
-VOID SyncStateMachineInit(
-	IN PRTMP_ADAPTER pAd,
-	IN STATE_MACHINE *Sm,
-	OUT STATE_MACHINE_FUNC Trans[])
-{
-	StateMachineInit(Sm, Trans, MAX_SYNC_STATE, MAX_SYNC_MSG, (STATE_MACHINE_FUNC)Drop, SYNC_IDLE, SYNC_MACHINE_BASE);
-
-	// column 1
-	StateMachineSetAction(Sm, SYNC_IDLE, MT2_MLME_SCAN_REQ, (STATE_MACHINE_FUNC)MlmeScanReqAction);
-	StateMachineSetAction(Sm, SYNC_IDLE, MT2_MLME_JOIN_REQ, (STATE_MACHINE_FUNC)MlmeJoinReqAction);
-	StateMachineSetAction(Sm, SYNC_IDLE, MT2_MLME_START_REQ, (STATE_MACHINE_FUNC)MlmeStartReqAction);
-	StateMachineSetAction(Sm, SYNC_IDLE, MT2_PEER_BEACON, (STATE_MACHINE_FUNC)PeerBeacon);
-	StateMachineSetAction(Sm, SYNC_IDLE, MT2_PEER_PROBE_REQ, (STATE_MACHINE_FUNC)PeerProbeReqAction);
-
-	//column 2
-	StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_MLME_SCAN_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenScan);
-	StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_MLME_JOIN_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenJoin);
-	StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_MLME_START_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenStart);
-	StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_PEER_BEACON, (STATE_MACHINE_FUNC)PeerBeaconAtJoinAction);
-	StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_BEACON_TIMEOUT, (STATE_MACHINE_FUNC)BeaconTimeoutAtJoinAction);
-
-	// column 3
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_MLME_SCAN_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenScan);
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_MLME_JOIN_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenJoin);
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_MLME_START_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenStart);
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_PEER_BEACON, (STATE_MACHINE_FUNC)PeerBeaconAtScanAction);
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_PEER_PROBE_RSP, (STATE_MACHINE_FUNC)PeerBeaconAtScanAction);
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_SCAN_TIMEOUT, (STATE_MACHINE_FUNC)ScanTimeoutAction);
-
-	// timer init
-	RTMPInitTimer(pAd, &pAd->MlmeAux.BeaconTimer, GET_TIMER_FUNCTION(BeaconTimeout), pAd, FALSE);
-	RTMPInitTimer(pAd, &pAd->MlmeAux.ScanTimer, GET_TIMER_FUNCTION(ScanTimeout), pAd, FALSE);
-}
-
-/*
-	==========================================================================
-	Description:
-		Beacon timeout handler, executed in timer thread
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID BeaconTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	DBGPRINT(RT_DEBUG_TRACE,("SYNC - BeaconTimeout\n"));
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS))
-		return;
-
-#ifdef DOT11_N_SUPPORT
-	if ((pAd->CommonCfg.BBPCurrentBW == BW_40)
-		)
-	{
-		UCHAR        BBPValue = 0;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-		BBPValue &= (~0x18);
-		BBPValue |= 0x10;
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-		DBGPRINT(RT_DEBUG_TRACE, ("SYNC - End of SCAN, restore to 40MHz channel %d, Total BSS[%02d]\n",pAd->CommonCfg.CentralChannel, pAd->ScanTab.BssNr));
-	}
-#endif // DOT11_N_SUPPORT //
-
-	MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_BEACON_TIMEOUT, 0, NULL);
-	RT28XX_MLME_HANDLER(pAd);
-}
-
-/*
-	==========================================================================
-	Description:
-		Scan timeout handler, executed in timer thread
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID ScanTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS))
-		return;
-
-	if (MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_SCAN_TIMEOUT, 0, NULL))
-	{
-		RT28XX_MLME_HANDLER(pAd);
-	}
-	else
-	{
-		// To prevent SyncMachine.CurrState is SCAN_LISTEN forever.
-		pAd->MlmeAux.Channel = 0;
-		ScanNextChannel(pAd);
-		if (pAd->CommonCfg.bWirelessEvent)
-		{
-			RTMPSendWirelessEvent(pAd, IW_SCAN_ENQUEUE_FAIL_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		MLME SCAN req state machine procedure
-	==========================================================================
- */
-VOID MlmeScanReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR          Ssid[MAX_LEN_OF_SSID], SsidLen, ScanType, BssType, BBPValue = 0;
-	BOOLEAN        TimerCancelled;
-	ULONG		   Now;
-	USHORT         Status;
-	PHEADER_802_11 pHdr80211;
-	PUCHAR         pOutBuffer = NULL;
-	NDIS_STATUS    NStatus;
-
-	// Check the total scan tries for one single OID command
-	// If this is the CCX 2.0 Case, skip that!
-	if ( !RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeScanReqAction before Startup\n"));
-		return;
-	}
-
-	// Increase the scan retry counters.
-	pAd->StaCfg.ScanCnt++;
-
-
-	// first check the parameter sanity
-	if (MlmeScanReqSanity(pAd,
-						  Elem->Msg,
-						  Elem->MsgLen,
-						  &BssType,
-						  Ssid,
-						  &SsidLen,
-						  &ScanType))
-	{
-
-		// Check for channel load and noise hist request
-		// Suspend MSDU only at scan request, not the last two mentioned
-		if ((ScanType == SCAN_CISCO_NOISE) || (ScanType == SCAN_CISCO_CHANNEL_LOAD))
-		{
-			if (pAd->StaCfg.CCXScanChannel != pAd->CommonCfg.Channel)
-				RTMPSuspendMsduTransmission(pAd);			// Suspend MSDU transmission here
-		}
-		else
-		{
-			// Suspend MSDU transmission here
-			RTMPSuspendMsduTransmission(pAd);
-		}
-
-		//
-		// To prevent data lost.
-		// Send an NULL data with turned PSM bit on to current associated AP before SCAN progress.
-		// And should send an NULL data with turned PSM bit off to AP, when scan progress done
-		//
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) && (INFRA_ON(pAd)))
-		{
-			NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);
-			if (NStatus	== NDIS_STATUS_SUCCESS)
-			{
-				pHdr80211 = (PHEADER_802_11) pOutBuffer;
-				MgtMacHeaderInit(pAd, pHdr80211, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-				pHdr80211->Duration = 0;
-				pHdr80211->FC.Type = BTYPE_DATA;
-				pHdr80211->FC.PwrMgmt = PWR_SAVE;
-
-				// Send using priority queue
-				MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-				DBGPRINT(RT_DEBUG_TRACE, ("MlmeScanReqAction -- Send PSM Data frame for off channel RM\n"));
-				MlmeFreeMemory(pAd, pOutBuffer);
-				RTMPusecDelay(5000);
-			}
-		}
-
-		NdisGetSystemUpTime(&Now);
-		pAd->StaCfg.LastScanTime = Now;
-		// reset all the timers
-		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled);
-
-		// record desired BSS parameters
-		pAd->MlmeAux.BssType = BssType;
-		pAd->MlmeAux.ScanType = ScanType;
-		pAd->MlmeAux.SsidLen = SsidLen;
-        NdisZeroMemory(pAd->MlmeAux.Ssid, MAX_LEN_OF_SSID);
-		NdisMoveMemory(pAd->MlmeAux.Ssid, Ssid, SsidLen);
-
-		// start from the first channel
-		pAd->MlmeAux.Channel = FirstChannel(pAd);
-
-		// Change the scan channel when dealing with CCX beacon report
-		if ((ScanType == SCAN_CISCO_PASSIVE) || (ScanType == SCAN_CISCO_ACTIVE) ||
-			(ScanType == SCAN_CISCO_CHANNEL_LOAD) || (ScanType == SCAN_CISCO_NOISE))
-			pAd->MlmeAux.Channel = pAd->StaCfg.CCXScanChannel;
-
-		// Let BBP register at 20MHz to do scan
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-		BBPValue &= (~0x18);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-		DBGPRINT(RT_DEBUG_TRACE, ("SYNC - BBP R4 to 20MHz.l\n"));
-		ScanNextChannel(pAd);
-	}
-	else
-	{
-		DBGPRINT_ERR(("SYNC - MlmeScanReqAction() sanity check fail\n"));
-		pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-		Status = MLME_INVALID_FORMAT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status);
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		MLME JOIN req state machine procedure
-	==========================================================================
- */
-VOID MlmeJoinReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR        BBPValue = 0;
-	BSS_ENTRY    *pBss;
-	BOOLEAN       TimerCancelled;
-	HEADER_802_11 Hdr80211;
-	NDIS_STATUS   NStatus;
-	ULONG         FrameLen = 0;
-	PUCHAR        pOutBuffer = NULL;
-	PUCHAR        pSupRate = NULL;
-	UCHAR         SupRateLen;
-	PUCHAR        pExtRate = NULL;
-	UCHAR         ExtRateLen;
-	UCHAR         ASupRate[] = {0x8C, 0x12, 0x98, 0x24, 0xb0, 0x48, 0x60, 0x6C};
-	UCHAR         ASupRateLen = sizeof(ASupRate)/sizeof(UCHAR);
-	MLME_JOIN_REQ_STRUCT *pInfo = (MLME_JOIN_REQ_STRUCT *)(Elem->Msg);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeJoinReqAction(BSS #%ld)\n", pInfo->BssIdx));
-
-
-	// reset all the timers
-	RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled);
-
-	pBss = &pAd->MlmeAux.SsidBssTab.BssEntry[pInfo->BssIdx];
-
-	// record the desired SSID & BSSID we're waiting for
-	COPY_MAC_ADDR(pAd->MlmeAux.Bssid, pBss->Bssid);
-
-	// If AP's SSID is not hidden, it is OK for updating ssid to MlmeAux again.
-	if (pBss->Hidden == 0)
-	{
-		NdisMoveMemory(pAd->MlmeAux.Ssid, pBss->Ssid, pBss->SsidLen);
-		pAd->MlmeAux.SsidLen = pBss->SsidLen;
-	}
-
-	pAd->MlmeAux.BssType = pBss->BssType;
-	pAd->MlmeAux.Channel = pBss->Channel;
-	pAd->MlmeAux.CentralChannel = pBss->CentralChannel;
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-	// Country IE of the AP will be evaluated and will be used.
-	if ((pAd->StaCfg.IEEE80211dClientMode != Rt802_11_D_None) &&
-		(pBss->bHasCountryIE == TRUE))
-	{
-		NdisMoveMemory(&pAd->CommonCfg.CountryCode[0], &pBss->CountryString[0], 2);
-		if (pBss->CountryString[2] == 'I')
-			pAd->CommonCfg.Geography = IDOR;
-		else if (pBss->CountryString[2] == 'O')
-			pAd->CommonCfg.Geography = ODOR;
-		else
-			pAd->CommonCfg.Geography = BOTH;
-		BuildChannelListEx(pAd);
-	}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-	// Let BBP register at 20MHz to do scan
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-	BBPValue &= (~0x18);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-	DBGPRINT(RT_DEBUG_TRACE, ("SYNC - BBP R4 to 20MHz.l\n"));
-
-	// switch channel and waiting for beacon timer
-	AsicSwitchChannel(pAd, pAd->MlmeAux.Channel, FALSE);
-	AsicLockChannel(pAd, pAd->MlmeAux.Channel);
-	RTMPSetTimer(&pAd->MlmeAux.BeaconTimer, JOIN_TIMEOUT);
-
-    do
-	{
-		if (((pAd->CommonCfg.bIEEE80211H == 1) &&
-            (pAd->MlmeAux.Channel > 14) &&
-             RadarChannelCheck(pAd, pAd->MlmeAux.Channel))
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-             || (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-#endif // CARRIER_DETECTION_SUPPORT //
-            )
-		{
-			//
-			// We can't send any Probe request frame to meet 802.11h.
-			//
-			if (pBss->Hidden == 0)
-				break;
-		}
-
-		//
-		// send probe request
-		//
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-		if (NStatus == NDIS_STATUS_SUCCESS)
-		{
-			if (pAd->MlmeAux.Channel <= 14)
-			{
-				pSupRate = pAd->CommonCfg.SupRate;
-				SupRateLen = pAd->CommonCfg.SupRateLen;
-				pExtRate = pAd->CommonCfg.ExtRate;
-				ExtRateLen = pAd->CommonCfg.ExtRateLen;
-			}
-			else
-			{
-				//
-				// Overwrite Support Rate, CCK rate are not allowed
-				//
-				pSupRate = ASupRate;
-				SupRateLen = ASupRateLen;
-				ExtRateLen = 0;
-			}
-
-			if (pAd->MlmeAux.BssType == BSS_INFRA)
-				MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, pAd->MlmeAux.Bssid, pAd->MlmeAux.Bssid);
-			else
-				MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, BROADCAST_ADDR, BROADCAST_ADDR);
-
-			MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-							  sizeof(HEADER_802_11),    &Hdr80211,
-							  1,                        &SsidIe,
-							  1,                        &pAd->MlmeAux.SsidLen,
-							  pAd->MlmeAux.SsidLen,	    pAd->MlmeAux.Ssid,
-							  1,                        &SupRateIe,
-							  1,                        &SupRateLen,
-							  SupRateLen,               pSupRate,
-							  END_OF_ARGS);
-
-			if (ExtRateLen)
-			{
-				ULONG Tmp;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &Tmp,
-								  1,                                &ExtRateIe,
-								  1,                                &ExtRateLen,
-								  ExtRateLen,                       pExtRate,
-								  END_OF_ARGS);
-				FrameLen += Tmp;
-			}
-
-
-			MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-			MlmeFreeMemory(pAd, pOutBuffer);
-		}
-    } while (FALSE);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("SYNC - Switch to ch %d, Wait BEACON from %02x:%02x:%02x:%02x:%02x:%02x\n",
-		pBss->Channel, pBss->Bssid[0], pBss->Bssid[1], pBss->Bssid[2], pBss->Bssid[3], pBss->Bssid[4], pBss->Bssid[5]));
-
-	pAd->Mlme.SyncMachine.CurrState = JOIN_WAIT_BEACON;
-}
-
-/*
-	==========================================================================
-	Description:
-		MLME START Request state machine procedure, starting an IBSS
-	==========================================================================
- */
-VOID MlmeStartReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR         Ssid[MAX_LEN_OF_SSID], SsidLen;
-	BOOLEAN       TimerCancelled;
-
-	// New for WPA security suites
-	UCHAR						VarIE[MAX_VIE_LEN]; 	// Total VIE length = MAX_VIE_LEN - -5
-	NDIS_802_11_VARIABLE_IEs	*pVIE = NULL;
-	LARGE_INTEGER				TimeStamp;
-	BOOLEAN Privacy;
-	USHORT Status;
-
-	// Init Variable IE structure
-	pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
-	pVIE->Length = 0;
-	TimeStamp.u.LowPart  = 0;
-	TimeStamp.u.HighPart = 0;
-
-	if (MlmeStartReqSanity(pAd, Elem->Msg, Elem->MsgLen, Ssid, &SsidLen))
-	{
-		// reset all the timers
-		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled);
-
-		//
-		// Start a new IBSS. All IBSS parameters are decided now....
-		//
-		DBGPRINT(RT_DEBUG_TRACE, ("MlmeStartReqAction - Start a new IBSS. All IBSS parameters are decided now.... \n"));
-		pAd->MlmeAux.BssType           = BSS_ADHOC;
-		NdisMoveMemory(pAd->MlmeAux.Ssid, Ssid, SsidLen);
-		pAd->MlmeAux.SsidLen           = SsidLen;
-
-		// generate a radom number as BSSID
-		MacAddrRandomBssid(pAd, pAd->MlmeAux.Bssid);
-		DBGPRINT(RT_DEBUG_TRACE, ("MlmeStartReqAction - generate a radom number as BSSID \n"));
-
-		Privacy = (pAd->StaCfg.WepStatus == Ndis802_11Encryption1Enabled) ||
-				  (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
-				  (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled);
-		pAd->MlmeAux.CapabilityInfo    = CAP_GENERATE(0,1,Privacy, (pAd->CommonCfg.TxPreamble == Rt802_11PreambleShort), 1, 0);
-		pAd->MlmeAux.BeaconPeriod      = pAd->CommonCfg.BeaconPeriod;
-		pAd->MlmeAux.AtimWin           = pAd->StaCfg.AtimWin;
-		pAd->MlmeAux.Channel           = pAd->CommonCfg.Channel;
-
-		pAd->CommonCfg.CentralChannel  = pAd->CommonCfg.Channel;
-		pAd->MlmeAux.CentralChannel    = pAd->CommonCfg.CentralChannel;
-
-		pAd->MlmeAux.SupRateLen= pAd->CommonCfg.SupRateLen;
-		NdisMoveMemory(pAd->MlmeAux.SupRate, pAd->CommonCfg.SupRate, MAX_LEN_OF_SUPPORTED_RATES);
-		RTMPCheckRates(pAd, pAd->MlmeAux.SupRate, &pAd->MlmeAux.SupRateLen);
-		pAd->MlmeAux.ExtRateLen = pAd->CommonCfg.ExtRateLen;
-		NdisMoveMemory(pAd->MlmeAux.ExtRate, pAd->CommonCfg.ExtRate, MAX_LEN_OF_SUPPORTED_RATES);
-		RTMPCheckRates(pAd, pAd->MlmeAux.ExtRate, &pAd->MlmeAux.ExtRateLen);
-#ifdef DOT11_N_SUPPORT
-		if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-		{
-			RTMPUpdateHTIE(&pAd->CommonCfg.DesiredHtPhy, &pAd->StaCfg.DesiredHtPhyInfo.MCSSet[0], &pAd->MlmeAux.HtCapability, &pAd->MlmeAux.AddHtInfo);
-			pAd->MlmeAux.HtCapabilityLen = sizeof(HT_CAPABILITY_IE);
-			// Not turn pAd->StaActive.SupportedHtPhy.bHtEnable = TRUE here.
-			DBGPRINT(RT_DEBUG_TRACE, ("SYNC -pAd->StaActive.SupportedHtPhy.bHtEnable = TRUE\n"));
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			pAd->MlmeAux.HtCapabilityLen = 0;
-			pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
-		}
-		// temporarily not support QOS in IBSS
-		NdisZeroMemory(&pAd->MlmeAux.APEdcaParm, sizeof(EDCA_PARM));
-		NdisZeroMemory(&pAd->MlmeAux.APQbssLoad, sizeof(QBSS_LOAD_PARM));
-		NdisZeroMemory(&pAd->MlmeAux.APQosCapability, sizeof(QOS_CAPABILITY_PARM));
-
-		AsicSwitchChannel(pAd, pAd->MlmeAux.Channel, FALSE);
-		AsicLockChannel(pAd, pAd->MlmeAux.Channel);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeStartReqAction(ch= %d,sup rates= %d, ext rates=%d)\n",
-			pAd->MlmeAux.Channel, pAd->MlmeAux.SupRateLen, pAd->MlmeAux.ExtRateLen));
-
-		pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-		Status = MLME_SUCCESS;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_START_CONF, 2, &Status);
-	}
-	else
-	{
-		DBGPRINT_ERR(("SYNC - MlmeStartReqAction() sanity check fail.\n"));
-		pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-		Status = MLME_INVALID_FORMAT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_START_CONF, 2, &Status);
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		peer sends beacon back when scanning
-	==========================================================================
- */
-VOID PeerBeaconAtScanAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR           Bssid[MAC_ADDR_LEN], Addr2[MAC_ADDR_LEN];
-	UCHAR           Ssid[MAX_LEN_OF_SSID], BssType, Channel, NewChannel,
-					SsidLen, DtimCount, DtimPeriod, BcastFlag, MessageToMe;
-	CF_PARM         CfParm;
-	USHORT          BeaconPeriod, AtimWin, CapabilityInfo;
-	PFRAME_802_11   pFrame;
-	LARGE_INTEGER   TimeStamp;
-	UCHAR           Erp;
-	UCHAR         	SupRate[MAX_LEN_OF_SUPPORTED_RATES], ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		  	SupRateLen, ExtRateLen;
-	USHORT 			LenVIE;
-	UCHAR			CkipFlag;
-	UCHAR			AironetCellPowerLimit;
-	EDCA_PARM       EdcaParm;
-	QBSS_LOAD_PARM  QbssLoad;
-	QOS_CAPABILITY_PARM QosCapability;
-	ULONG						RalinkIe;
-	UCHAR						VarIE[MAX_VIE_LEN];		// Total VIE length = MAX_VIE_LEN - -5
-	NDIS_802_11_VARIABLE_IEs	*pVIE = NULL;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			HtCapabilityLen = 0, PreNHtCapabilityLen = 0;
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChannelOffset = 0xff;
-
-
-	// NdisFillMemory(Ssid, MAX_LEN_OF_SSID, 0x00);
-	pFrame = (PFRAME_802_11) Elem->Msg;
-	// Init Variable IE structure
-	pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
-	pVIE->Length = 0;
-#ifdef DOT11_N_SUPPORT
-    RTMPZeroMemory(&HtCapability, sizeof(HtCapability));
-	RTMPZeroMemory(&AddHtInfo, sizeof(ADD_HT_INFO_IE));
-#endif // DOT11_N_SUPPORT //
-
-	if (PeerBeaconAndProbeRspSanity(pAd,
-								Elem->Msg,
-								Elem->MsgLen,
-								Elem->Channel,
-								Addr2,
-								Bssid,
-								Ssid,
-								&SsidLen,
-								&BssType,
-								&BeaconPeriod,
-								&Channel,
-								&NewChannel,
-								&TimeStamp,
-								&CfParm,
-								&AtimWin,
-								&CapabilityInfo,
-								&Erp,
-								&DtimCount,
-								&DtimPeriod,
-								&BcastFlag,
-								&MessageToMe,
-								SupRate,
-								&SupRateLen,
-								ExtRate,
-								&ExtRateLen,
-								&CkipFlag,
-								&AironetCellPowerLimit,
-								&EdcaParm,
-								&QbssLoad,
-								&QosCapability,
-								&RalinkIe,
-								&HtCapabilityLen,
-								&PreNHtCapabilityLen,
-								&HtCapability,
-								&AddHtInfoLen,
-								&AddHtInfo,
-								&NewExtChannelOffset,
-								&LenVIE,
-								pVIE))
-	{
-		ULONG Idx;
-		CHAR Rssi = 0;
-
-		Idx = BssTableSearch(&pAd->ScanTab, Bssid, Channel);
-		if (Idx != BSS_NOT_FOUND)
-			Rssi = pAd->ScanTab.BssEntry[Idx].Rssi;
-
-		Rssi = RTMPMaxRssi(pAd, ConvertToRssi(pAd, Elem->Rssi0, RSSI_0), ConvertToRssi(pAd, Elem->Rssi1, RSSI_1), ConvertToRssi(pAd, Elem->Rssi2, RSSI_2));
-
-
-#ifdef DOT11_N_SUPPORT
-		if ((HtCapabilityLen > 0) || (PreNHtCapabilityLen > 0))
-			HtCapabilityLen = SIZE_HT_CAP_IE;
-#endif // DOT11_N_SUPPORT //
-		if ((pAd->StaCfg.CCXReqType != MSRN_TYPE_UNUSED) && (Channel == pAd->StaCfg.CCXScanChannel))
-		{
-			Idx = BssTableSetEntry(pAd, &pAd->StaCfg.CCXBssTab, Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
-						 &CfParm, AtimWin, CapabilityInfo, SupRate, SupRateLen,ExtRate, ExtRateLen, &HtCapability,
-						 &AddHtInfo, HtCapabilityLen, AddHtInfoLen, NewExtChannelOffset, Channel, Rssi, TimeStamp, CkipFlag,
-						 &EdcaParm, &QosCapability, &QbssLoad, LenVIE, pVIE);
-			if (Idx != BSS_NOT_FOUND)
-			{
-				NdisMoveMemory(pAd->StaCfg.CCXBssTab.BssEntry[Idx].PTSF, &Elem->Msg[24], 4);
-				NdisMoveMemory(&pAd->StaCfg.CCXBssTab.BssEntry[Idx].TTSF[0], &Elem->TimeStamp.u.LowPart, 4);
-				NdisMoveMemory(&pAd->StaCfg.CCXBssTab.BssEntry[Idx].TTSF[4], &Elem->TimeStamp.u.LowPart, 4);
-				if (pAd->StaCfg.CCXReqType == MSRN_TYPE_BEACON_REQ)
-					AironetAddBeaconReport(pAd, Idx, Elem);
-			}
-		}
-		else
-		{
-			Idx = BssTableSetEntry(pAd, &pAd->ScanTab, Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
-						  &CfParm, AtimWin, CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,  &HtCapability,
-						 &AddHtInfo, HtCapabilityLen, AddHtInfoLen, NewExtChannelOffset, Channel, Rssi, TimeStamp, CkipFlag,
-						 &EdcaParm, &QosCapability, &QbssLoad, LenVIE, pVIE);
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-			if (pAd->ChannelList[pAd->CommonCfg.ChannelListIdx].bEffectedChannel == TRUE)
-			{
-				UCHAR		RegClass;
-				PeerBeaconAndProbeRspSanity2(pAd, Elem->Msg, Elem->MsgLen, &RegClass);
-				TriEventTableSetEntry(pAd, &pAd->CommonCfg.TriggerEventTab, Bssid, &HtCapability, HtCapabilityLen, RegClass, Channel);
-			}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-			if (Idx != BSS_NOT_FOUND)
-			{
-				NdisMoveMemory(pAd->ScanTab.BssEntry[Idx].PTSF, &Elem->Msg[24], 4);
-				NdisMoveMemory(&pAd->ScanTab.BssEntry[Idx].TTSF[0], &Elem->TimeStamp.u.LowPart, 4);
-				NdisMoveMemory(&pAd->ScanTab.BssEntry[Idx].TTSF[4], &Elem->TimeStamp.u.LowPart, 4);
-			}
-		}
-	}
-	// sanity check fail, ignored
-}
-
-/*
-	==========================================================================
-	Description:
-		When waiting joining the (I)BSS, beacon received from external
-	==========================================================================
- */
-VOID PeerBeaconAtJoinAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR         Bssid[MAC_ADDR_LEN], Addr2[MAC_ADDR_LEN];
-	UCHAR         Ssid[MAX_LEN_OF_SSID], SsidLen, BssType, Channel, MessageToMe,
-				  DtimCount, DtimPeriod, BcastFlag, NewChannel;
-	LARGE_INTEGER TimeStamp;
-	USHORT        BeaconPeriod, AtimWin, CapabilityInfo;
-	CF_PARM       Cf;
-	BOOLEAN       TimerCancelled;
-	UCHAR         Erp;
-	UCHAR         SupRate[MAX_LEN_OF_SUPPORTED_RATES], ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		  SupRateLen, ExtRateLen;
-	UCHAR         CkipFlag;
-	USHORT 		  LenVIE;
-	UCHAR		  AironetCellPowerLimit;
-	EDCA_PARM       EdcaParm;
-	QBSS_LOAD_PARM  QbssLoad;
-	QOS_CAPABILITY_PARM QosCapability;
-	USHORT        Status;
-	UCHAR						VarIE[MAX_VIE_LEN];		// Total VIE length = MAX_VIE_LEN - -5
-	NDIS_802_11_VARIABLE_IEs	*pVIE = NULL;
-	ULONG           RalinkIe;
-	ULONG         Idx;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR				HtCapabilityLen = 0, PreNHtCapabilityLen = 0;
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChannelOffset = 0xff;
-#ifdef DOT11_N_SUPPORT
-	UCHAR			CentralChannel;
-#endif // DOT11_N_SUPPORT //
-
-	// Init Variable IE structure
-	pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
-	pVIE->Length = 0;
-    RTMPZeroMemory(&HtCapability, sizeof(HtCapability));
-	RTMPZeroMemory(&AddHtInfo, sizeof(ADD_HT_INFO_IE));
-
-
-	if (PeerBeaconAndProbeRspSanity(pAd,
-								Elem->Msg,
-								Elem->MsgLen,
-								Elem->Channel,
-								Addr2,
-								Bssid,
-								Ssid,
-								&SsidLen,
-								&BssType,
-								&BeaconPeriod,
-								&Channel,
-								&NewChannel,
-								&TimeStamp,
-								&Cf,
-								&AtimWin,
-								&CapabilityInfo,
-								&Erp,
-								&DtimCount,
-								&DtimPeriod,
-								&BcastFlag,
-								&MessageToMe,
-								SupRate,
-								&SupRateLen,
-								ExtRate,
-								&ExtRateLen,
-								&CkipFlag,
-								&AironetCellPowerLimit,
-								&EdcaParm,
-								&QbssLoad,
-								&QosCapability,
-								&RalinkIe,
-								&HtCapabilityLen,
-								&PreNHtCapabilityLen,
-								&HtCapability,
-								&AddHtInfoLen,
-								&AddHtInfo,
-								&NewExtChannelOffset,
-								&LenVIE,
-								pVIE))
-	{
-		// Disqualify 11b only adhoc when we are in 11g only adhoc mode
-		if ((BssType == BSS_ADHOC) && (pAd->CommonCfg.PhyMode == PHY_11G) && ((SupRateLen+ExtRateLen)< 12))
-			return;
-
-		// BEACON from desired BSS/IBSS found. We should be able to decide most
-		// BSS parameters here.
-		// Q. But what happen if this JOIN doesn't conclude a successful ASSOCIATEION?
-		//    Do we need to receover back all parameters belonging to previous BSS?
-		// A. Should be not. There's no back-door recover to previous AP. It still need
-		//    a new JOIN-AUTH-ASSOC sequence.
-		if (MAC_ADDR_EQUAL(pAd->MlmeAux.Bssid, Bssid))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("SYNC - receive desired BEACON at JoinWaitBeacon... Channel = %d\n", Channel));
-			RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled);
-
-			// Update RSSI to prevent No signal display when cards first initialized
-			pAd->StaCfg.RssiSample.LastRssi0	= ConvertToRssi(pAd, Elem->Rssi0, RSSI_0);
-			pAd->StaCfg.RssiSample.LastRssi1	= ConvertToRssi(pAd, Elem->Rssi1, RSSI_1);
-			pAd->StaCfg.RssiSample.LastRssi2	= ConvertToRssi(pAd, Elem->Rssi2, RSSI_2);
-			pAd->StaCfg.RssiSample.AvgRssi0	= pAd->StaCfg.RssiSample.LastRssi0;
-			pAd->StaCfg.RssiSample.AvgRssi0X8	= pAd->StaCfg.RssiSample.AvgRssi0 << 3;
-			pAd->StaCfg.RssiSample.AvgRssi1	= pAd->StaCfg.RssiSample.LastRssi1;
-			pAd->StaCfg.RssiSample.AvgRssi1X8	= pAd->StaCfg.RssiSample.AvgRssi1 << 3;
-			pAd->StaCfg.RssiSample.AvgRssi2	= pAd->StaCfg.RssiSample.LastRssi2;
-			pAd->StaCfg.RssiSample.AvgRssi2X8	= pAd->StaCfg.RssiSample.AvgRssi2 << 3;
-
-			//
-			// We need to check if SSID only set to any, then we can record the current SSID.
-			// Otherwise will cause hidden SSID association failed.
-			//
-			if (pAd->MlmeAux.SsidLen == 0)
-			{
-				NdisMoveMemory(pAd->MlmeAux.Ssid, Ssid, SsidLen);
-				pAd->MlmeAux.SsidLen = SsidLen;
-			}
-			else
-			{
-				Idx = BssSsidTableSearch(&pAd->ScanTab, Bssid, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen, Channel);
-
-				if (Idx != BSS_NOT_FOUND)
-				{
-					//
-					// Multiple SSID case, used correct CapabilityInfo
-					//
-					CapabilityInfo = pAd->ScanTab.BssEntry[Idx].CapabilityInfo;
-				}
-			}
-			NdisMoveMemory(pAd->MlmeAux.Bssid, Bssid, MAC_ADDR_LEN);
-			pAd->MlmeAux.CapabilityInfo = CapabilityInfo & SUPPORTED_CAPABILITY_INFO;
-			pAd->MlmeAux.BssType = BssType;
-			pAd->MlmeAux.BeaconPeriod = BeaconPeriod;
-			pAd->MlmeAux.Channel = Channel;
-			pAd->MlmeAux.AtimWin = AtimWin;
-			pAd->MlmeAux.CfpPeriod = Cf.CfpPeriod;
-			pAd->MlmeAux.CfpMaxDuration = Cf.CfpMaxDuration;
-			pAd->MlmeAux.APRalinkIe = RalinkIe;
-
-			// Copy AP's supported rate to MlmeAux for creating assoication request
-			// Also filter out not supported rate
-			pAd->MlmeAux.SupRateLen = SupRateLen;
-			NdisMoveMemory(pAd->MlmeAux.SupRate, SupRate, SupRateLen);
-			RTMPCheckRates(pAd, pAd->MlmeAux.SupRate, &pAd->MlmeAux.SupRateLen);
-			pAd->MlmeAux.ExtRateLen = ExtRateLen;
-			NdisMoveMemory(pAd->MlmeAux.ExtRate, ExtRate, ExtRateLen);
-			RTMPCheckRates(pAd, pAd->MlmeAux.ExtRate, &pAd->MlmeAux.ExtRateLen);
-
-            NdisZeroMemory(pAd->StaActive.SupportedPhyInfo.MCSSet, 16);
-#ifdef DOT11_N_SUPPORT
-			pAd->MlmeAux.NewExtChannelOffset = NewExtChannelOffset;
-			pAd->MlmeAux.HtCapabilityLen = HtCapabilityLen;
-
-			// filter out un-supported ht rates
-			if (((HtCapabilityLen > 0) || (PreNHtCapabilityLen > 0)) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-			{
-				RTMPZeroMemory(&pAd->MlmeAux.HtCapability, SIZE_HT_CAP_IE);
-   				RTMPMoveMemory(&pAd->MlmeAux.AddHtInfo, &AddHtInfo, SIZE_ADD_HT_INFO_IE);
-
-				// StaActive.SupportedHtPhy.MCSSet stores Peer AP's 11n Rx capability
-				NdisMoveMemory(pAd->StaActive.SupportedPhyInfo.MCSSet, HtCapability.MCSSet, 16);
-				pAd->MlmeAux.NewExtChannelOffset = NewExtChannelOffset;
-				pAd->MlmeAux.HtCapabilityLen = SIZE_HT_CAP_IE;
-				pAd->StaActive.SupportedPhyInfo.bHtEnable = TRUE;
-				if (PreNHtCapabilityLen > 0)
-					pAd->StaActive.SupportedPhyInfo.bPreNHt = TRUE;
-				RTMPCheckHt(pAd, BSSID_WCID, &HtCapability, &AddHtInfo);
-				// Copy AP Parameter to StaActive.  This is also in LinkUp.
-				DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAtJoinAction! (MpduDensity=%d, MaxRAmpduFactor=%d, BW=%d)\n",
-					pAd->StaActive.SupportedHtPhy.MpduDensity, pAd->StaActive.SupportedHtPhy.MaxRAmpduFactor, HtCapability.HtCapInfo.ChannelWidth));
-
-				if (AddHtInfoLen > 0)
-				{
-					CentralChannel = AddHtInfo.ControlChan;
-		 			// Check again the Bandwidth capability of this AP.
-		 			if ((AddHtInfo.ControlChan > 2)&& (AddHtInfo.AddHtInfo.ExtChanOffset == EXTCHA_BELOW) && (HtCapability.HtCapInfo.ChannelWidth == BW_40))
-		 			{
-		 				CentralChannel = AddHtInfo.ControlChan - 2;
-		 			}
-		 			else if ((AddHtInfo.AddHtInfo.ExtChanOffset == EXTCHA_ABOVE) && (HtCapability.HtCapInfo.ChannelWidth == BW_40))
-		 			{
-		 				CentralChannel = AddHtInfo.ControlChan + 2;
-		 			}
-
-					// Check Error .
-					if (pAd->MlmeAux.CentralChannel != CentralChannel)
-		 				DBGPRINT(RT_DEBUG_ERROR, ("PeerBeaconAtJoinAction HT===>Beacon Central Channel = %d, Control Channel = %d. Mlmeaux CentralChannel = %d\n", CentralChannel, AddHtInfo.ControlChan, pAd->MlmeAux.CentralChannel));
-
-		 			DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAtJoinAction HT===>Central Channel = %d, Control Channel = %d,  .\n", CentralChannel, AddHtInfo.ControlChan));
-
-				}
-
-			}
-			else
-#endif // DOT11_N_SUPPORT //
-			{
-   				// To prevent error, let legacy AP must have same CentralChannel and Channel.
-				if ((HtCapabilityLen == 0) && (PreNHtCapabilityLen == 0))
-					pAd->MlmeAux.CentralChannel = pAd->MlmeAux.Channel;
-
-				pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
-				RTMPZeroMemory(&pAd->MlmeAux.HtCapability, SIZE_HT_CAP_IE);
-				RTMPZeroMemory(&pAd->MlmeAux.AddHtInfo, SIZE_ADD_HT_INFO_IE);
-			}
-
-			RTMPUpdateMlmeRate(pAd);
-
-			// copy QOS related information
-			if ((pAd->CommonCfg.bWmmCapable)
-#ifdef DOT11_N_SUPPORT
-				 || (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-#endif // DOT11_N_SUPPORT //
-				)
-			{
-				NdisMoveMemory(&pAd->MlmeAux.APEdcaParm, &EdcaParm, sizeof(EDCA_PARM));
-				NdisMoveMemory(&pAd->MlmeAux.APQbssLoad, &QbssLoad, sizeof(QBSS_LOAD_PARM));
-				NdisMoveMemory(&pAd->MlmeAux.APQosCapability, &QosCapability, sizeof(QOS_CAPABILITY_PARM));
-			}
-			else
-			{
-				NdisZeroMemory(&pAd->MlmeAux.APEdcaParm, sizeof(EDCA_PARM));
-				NdisZeroMemory(&pAd->MlmeAux.APQbssLoad, sizeof(QBSS_LOAD_PARM));
-				NdisZeroMemory(&pAd->MlmeAux.APQosCapability, sizeof(QOS_CAPABILITY_PARM));
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE, ("SYNC - after JOIN, SupRateLen=%d, ExtRateLen=%d\n",
-										pAd->MlmeAux.SupRateLen, pAd->MlmeAux.ExtRateLen));
-
-#ifdef LEAP_SUPPORT
-			// Update CkipFlag
-			pAd->StaCfg.CkipFlag = CkipFlag;
-
-			// Keep TimeStamp for Re-Association used.
-			if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-				pAd->StaCfg.CCKMBeaconAtJoinTimeStamp = TimeStamp;
-#endif // LEAP_SUPPORT //
-
-			if (AironetCellPowerLimit != 0xFF)
-			{
-				//We need to change our TxPower for CCX 2.0 AP Control of Client Transmit Power
-				ChangeToCellPowerLimit(pAd, AironetCellPowerLimit);
-			}
-			else  //Used the default TX Power Percentage.
-				pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault;
-
-			pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-			Status = MLME_SUCCESS;
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_JOIN_CONF, 2, &Status);
-		}
-		// not to me BEACON, ignored
-	}
-	// sanity check fail, ignore this frame
-}
-
-/*
-	==========================================================================
-	Description:
-		receive BEACON from peer
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID PeerBeacon(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR         Bssid[MAC_ADDR_LEN], Addr2[MAC_ADDR_LEN];
-	CHAR          Ssid[MAX_LEN_OF_SSID];
-	CF_PARM       CfParm;
-	UCHAR         SsidLen, MessageToMe=0, BssType, Channel, NewChannel, index=0;
-	UCHAR         DtimCount=0, DtimPeriod=0, BcastFlag=0;
-	USHORT        CapabilityInfo, AtimWin, BeaconPeriod;
-	LARGE_INTEGER TimeStamp;
-	USHORT        TbttNumToNextWakeUp;
-	UCHAR         Erp;
-	UCHAR         SupRate[MAX_LEN_OF_SUPPORTED_RATES], ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		  SupRateLen, ExtRateLen;
-	UCHAR		  CkipFlag;
-	USHORT        LenVIE;
-	UCHAR		  AironetCellPowerLimit;
-	EDCA_PARM       EdcaParm;
-	QBSS_LOAD_PARM  QbssLoad;
-	QOS_CAPABILITY_PARM QosCapability;
-	ULONG           RalinkIe;
-	// New for WPA security suites
-	UCHAR						VarIE[MAX_VIE_LEN];		// Total VIE length = MAX_VIE_LEN - -5
-	NDIS_802_11_VARIABLE_IEs	*pVIE = NULL;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			HtCapabilityLen, PreNHtCapabilityLen;
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChannelOffset = 0xff;
-
-
-#ifdef RALINK_ATE
-    if (ATE_ON(pAd))
-    {
-		return;
-    }
-#endif // RALINK_ATE //
-
-	if (!(INFRA_ON(pAd) || ADHOC_ON(pAd)
-		))
-		return;
-
-	// Init Variable IE structure
-	pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
-	pVIE->Length = 0;
-    RTMPZeroMemory(&HtCapability, sizeof(HtCapability));
-	RTMPZeroMemory(&AddHtInfo, sizeof(ADD_HT_INFO_IE));
-
-	if (PeerBeaconAndProbeRspSanity(pAd,
-								Elem->Msg,
-								Elem->MsgLen,
-								Elem->Channel,
-								Addr2,
-								Bssid,
-								Ssid,
-								&SsidLen,
-								&BssType,
-								&BeaconPeriod,
-								&Channel,
-								&NewChannel,
-								&TimeStamp,
-								&CfParm,
-								&AtimWin,
-								&CapabilityInfo,
-								&Erp,
-								&DtimCount,
-								&DtimPeriod,
-								&BcastFlag,
-								&MessageToMe,
-								SupRate,
-								&SupRateLen,
-								ExtRate,
-								&ExtRateLen,
-								&CkipFlag,
-								&AironetCellPowerLimit,
-								&EdcaParm,
-								&QbssLoad,
-								&QosCapability,
-								&RalinkIe,
-								&HtCapabilityLen,
-								&PreNHtCapabilityLen,
-								&HtCapability,
-								&AddHtInfoLen,
-								&AddHtInfo,
-								&NewExtChannelOffset,
-								&LenVIE,
-								pVIE))
-	{
-		BOOLEAN is_my_bssid, is_my_ssid;
-		ULONG   Bssidx, Now;
-		BSS_ENTRY *pBss;
-		CHAR		RealRssi = RTMPMaxRssi(pAd, ConvertToRssi(pAd, Elem->Rssi0, RSSI_0), ConvertToRssi(pAd, Elem->Rssi1, RSSI_1), ConvertToRssi(pAd, Elem->Rssi2, RSSI_2));
-
-		is_my_bssid = MAC_ADDR_EQUAL(Bssid, pAd->CommonCfg.Bssid)? TRUE : FALSE;
-		is_my_ssid = SSID_EQUAL(Ssid, SsidLen, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen)? TRUE:FALSE;
-
-
-		// ignore BEACON not for my SSID
-		if ((! is_my_ssid) && (! is_my_bssid))
-			return;
-
-		// It means STA waits disassoc completely from this AP, ignores this beacon.
-		if (pAd->Mlme.CntlMachine.CurrState == CNTL_WAIT_DISASSOC)
-			return;
-
-#ifdef DOT11_N_SUPPORT
-		// Copy Control channel for this BSSID.
-		if (AddHtInfoLen != 0)
-			Channel = AddHtInfo.ControlChan;
-
-		if ((HtCapabilityLen > 0) || (PreNHtCapabilityLen > 0))
-			HtCapabilityLen = SIZE_HT_CAP_IE;
-#endif // DOT11_N_SUPPORT //
-
-		//
-		// Housekeeping "SsidBssTab" table for later-on ROAMing usage.
-		//
-		Bssidx = BssTableSearch(&pAd->ScanTab, Bssid, Channel);
-		if (Bssidx == BSS_NOT_FOUND)
-		{
-			// discover new AP of this network, create BSS entry
-			Bssidx = BssTableSetEntry(pAd, &pAd->ScanTab, Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
-						 &CfParm, AtimWin, CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,
-						&HtCapability, &AddHtInfo,HtCapabilityLen,AddHtInfoLen,NewExtChannelOffset, Channel,
-						RealRssi, TimeStamp, CkipFlag, &EdcaParm, &QosCapability,
-						&QbssLoad, LenVIE, pVIE);
-			if (Bssidx == BSS_NOT_FOUND) // return if BSS table full
-				return;
-
-			NdisMoveMemory(pAd->ScanTab.BssEntry[Bssidx].PTSF, &Elem->Msg[24], 4);
-			NdisMoveMemory(&pAd->ScanTab.BssEntry[Bssidx].TTSF[0], &Elem->TimeStamp.u.LowPart, 4);
-			NdisMoveMemory(&pAd->ScanTab.BssEntry[Bssidx].TTSF[4], &Elem->TimeStamp.u.LowPart, 4);
-
-
-
-		}
-
-		if ((pAd->CommonCfg.bIEEE80211H == 1) && (NewChannel != 0) && (Channel != NewChannel))
-		{
-			// Switching to channel 1 can prevent from rescanning the current channel immediately (by auto reconnection).
-			// In addition, clear the MLME queue and the scan table to discard the RX packets and previous scanning results.
-			AsicSwitchChannel(pAd, 1, FALSE);
-			AsicLockChannel(pAd, 1);
-		    LinkDown(pAd, FALSE);
-			MlmeQueueInit(&pAd->Mlme.Queue);
-			BssTableInit(&pAd->ScanTab);
-		    RTMPusecDelay(1000000);		// use delay to prevent STA do reassoc
-
-			// channel sanity check
-			for (index = 0 ; index < pAd->ChannelListNum; index++)
-			{
-				if (pAd->ChannelList[index].Channel == NewChannel)
-				{
-					pAd->ScanTab.BssEntry[Bssidx].Channel = NewChannel;
-					pAd->CommonCfg.Channel = NewChannel;
-					AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-					AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerBeacon - STA receive channel switch announcement IE (New Channel =%d)\n", NewChannel));
-					break;
-				}
-			}
-
-			if (index >= pAd->ChannelListNum)
-			{
-				DBGPRINT_ERR(("PeerBeacon(can not find New Channel=%d in ChannelList[%d]\n", pAd->CommonCfg.Channel, pAd->ChannelListNum));
-			}
-		}
-
-		// if the ssid matched & bssid unmatched, we should select the bssid with large value.
-		// This might happened when two STA start at the same time
-		if ((! is_my_bssid) && ADHOC_ON(pAd))
-		{
-			INT	i;
-
-			// Add the safeguard against the mismatch of adhoc wep status
-			if (pAd->StaCfg.WepStatus != pAd->ScanTab.BssEntry[Bssidx].WepStatus)
-			{
-				return;
-			}
-
-			// collapse into the ADHOC network which has bigger BSSID value.
-			for (i = 0; i < 6; i++)
-			{
-				if (Bssid[i] > pAd->CommonCfg.Bssid[i])
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("SYNC - merge to the IBSS with bigger BSSID=%02x:%02x:%02x:%02x:%02x:%02x\n",
-						Bssid[0], Bssid[1], Bssid[2], Bssid[3], Bssid[4], Bssid[5]));
-					AsicDisableSync(pAd);
-					COPY_MAC_ADDR(pAd->CommonCfg.Bssid, Bssid);
-					AsicSetBssid(pAd, pAd->CommonCfg.Bssid);
-					MakeIbssBeacon(pAd);        // re-build BEACON frame
-					AsicEnableIbssSync(pAd);    // copy BEACON frame to on-chip memory
-					is_my_bssid = TRUE;
-					break;
-				}
-				else if (Bssid[i] < pAd->CommonCfg.Bssid[i])
-					break;
-			}
-		}
-
-
-		NdisGetSystemUpTime(&Now);
-		pBss = &pAd->ScanTab.BssEntry[Bssidx];
-		pBss->Rssi = RealRssi;       // lastest RSSI
-		pBss->LastBeaconRxTime = Now;   // last RX timestamp
-
-		//
-		// BEACON from my BSSID - either IBSS or INFRA network
-		//
-		if (is_my_bssid)
-		{
-			RXWI_STRUC	RxWI;
-
-			pAd->StaCfg.DtimCount = DtimCount;
-			pAd->StaCfg.DtimPeriod = DtimPeriod;
-			pAd->StaCfg.LastBeaconRxTime = Now;
-
-
-			RxWI.RSSI0 = Elem->Rssi0;
-			RxWI.RSSI1 = Elem->Rssi1;
-			RxWI.RSSI2 = Elem->Rssi2;
-
-			Update_Rssi_Sample(pAd, &pAd->StaCfg.RssiSample, &RxWI);
-			if (AironetCellPowerLimit != 0xFF)
-			{
-				//
-				// We get the Cisco (ccx) "TxPower Limit" required
-				// Changed to appropriate TxPower Limit for Ciso Compatible Extensions
-				//
-				ChangeToCellPowerLimit(pAd, AironetCellPowerLimit);
-			}
-			else
-			{
-				//
-				// AironetCellPowerLimit equal to 0xFF means the Cisco (ccx) "TxPower Limit" not exist.
-				// Used the default TX Power Percentage, that set from UI.
-				//
-				pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault;
-			}
-
-			if (ADHOC_ON(pAd) && (CAP_IS_IBSS_ON(CapabilityInfo)))
-			{
-				UCHAR			MaxSupportedRateIn500Kbps = 0;
-				UCHAR			idx;
-				MAC_TABLE_ENTRY *pEntry;
-
-				// supported rates array may not be sorted. sort it and find the maximum rate
-			    for (idx=0; idx<SupRateLen; idx++)
-			    {
-			        if (MaxSupportedRateIn500Kbps < (SupRate[idx] & 0x7f))
-			            MaxSupportedRateIn500Kbps = SupRate[idx] & 0x7f;
-			    }
-
-				for (idx=0; idx<ExtRateLen; idx++)
-			    {
-			        if (MaxSupportedRateIn500Kbps < (ExtRate[idx] & 0x7f))
-			            MaxSupportedRateIn500Kbps = ExtRate[idx] & 0x7f;
-			    }
-
-				// look up the existing table
-				pEntry = MacTableLookup(pAd, Addr2);
-
-				// Ad-hoc mode is using MAC address as BA session. So we need to continuously find newly joined adhoc station by receiving beacon.
-				// To prevent always check this, we use wcid == RESERVED_WCID to recognize it as newly joined adhoc station.
-				if ((ADHOC_ON(pAd) && (Elem->Wcid == RESERVED_WCID)) ||
-					(pEntry && ((pEntry->LastBeaconRxTime + ADHOC_ENTRY_BEACON_LOST_TIME) < Now)))
-				{
-					if (pEntry == NULL)
-						// Another adhoc joining, add to our MAC table.
-						pEntry = MacTableInsertEntry(pAd, Addr2, BSS0, FALSE);
-
-					if (StaAddMacTableEntry(pAd, pEntry, MaxSupportedRateIn500Kbps, &HtCapability, HtCapabilityLen, CapabilityInfo) == FALSE)
-					{
-						DBGPRINT(RT_DEBUG_TRACE, ("ADHOC - Add Entry failed.\n"));
-						return;
-					}
-
-					if (pEntry &&
-						(Elem->Wcid == RESERVED_WCID))
-					{
-						idx = pAd->StaCfg.DefaultKeyId;
-						RT28XX_STA_SECURITY_INFO_ADD(pAd, BSS0, idx, pEntry);
-					}
-				}
-
-				if (pEntry && pEntry->ValidAsCLI)
-					pEntry->LastBeaconRxTime = Now;
-
-				// At least another peer in this IBSS, declare MediaState as CONNECTED
-				if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				{
-					OPSTATUS_SET_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-
-					pAd->IndicateMediaState = NdisMediaStateConnected;
-					RTMP_IndicateMediaState(pAd);
-	                pAd->ExtraInfo = GENERAL_LINK_UP;
-					AsicSetBssid(pAd, pAd->CommonCfg.Bssid);
-
-					// 2003/03/12 - john
-					// Make sure this entry in "ScanTab" table, thus complies to Microsoft's policy that
-					// "site survey" result should always include the current connected network.
-					//
-					Bssidx = BssTableSearch(&pAd->ScanTab, Bssid, Channel);
-					if (Bssidx == BSS_NOT_FOUND)
-					{
-						Bssidx = BssTableSetEntry(pAd, &pAd->ScanTab, Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
-									&CfParm, AtimWin, CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen, &HtCapability,
-									&AddHtInfo, HtCapabilityLen, AddHtInfoLen, NewExtChannelOffset, Channel, RealRssi, TimeStamp, 0,
-									&EdcaParm, &QosCapability, &QbssLoad, LenVIE, pVIE);
-					}
-					DBGPRINT(RT_DEBUG_TRACE, ("ADHOC  fOP_STATUS_MEDIA_STATE_CONNECTED.\n"));
-				}
-			}
-
-			if (INFRA_ON(pAd))
-			{
-				BOOLEAN bUseShortSlot, bUseBGProtection;
-
-				// decide to use/change to -
-				//      1. long slot (20 us) or short slot (9 us) time
-				//      2. turn on/off RTS/CTS and/or CTS-to-self protection
-				//      3. short preamble
-
-				//bUseShortSlot = pAd->CommonCfg.bUseShortSlotTime && CAP_IS_SHORT_SLOT(CapabilityInfo);
-				bUseShortSlot = CAP_IS_SHORT_SLOT(CapabilityInfo);
-				if (bUseShortSlot != OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SHORT_SLOT_INUSED))
-					AsicSetSlotTime(pAd, bUseShortSlot);
-
-				bUseBGProtection = (pAd->CommonCfg.UseBGProtection == 1) ||    // always use
-								   ((pAd->CommonCfg.UseBGProtection == 0) && ERP_IS_USE_PROTECTION(Erp));
-
-				if (pAd->CommonCfg.Channel > 14) // always no BG protection in A-band. falsely happened when switching A/G band to a dual-band AP
-					bUseBGProtection = FALSE;
-
-				if (bUseBGProtection != OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED))
-				{
-					if (bUseBGProtection)
-					{
-						OPSTATUS_SET_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED);
-						AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, (OFDMSETPROTECT|CCKSETPROTECT|ALLN_SETPROTECT),FALSE,(pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1));
-					}
-					else
-					{
-						OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED);
-						AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, (OFDMSETPROTECT|CCKSETPROTECT|ALLN_SETPROTECT),TRUE,(pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1));
-					}
-
-					DBGPRINT(RT_DEBUG_WARN, ("SYNC - AP changed B/G protection to %d\n", bUseBGProtection));
-				}
-
-#ifdef DOT11_N_SUPPORT
-				// check Ht protection mode. and adhere to the Non-GF device indication by AP.
-				if ((AddHtInfoLen != 0) &&
-					((AddHtInfo.AddHtInfo2.OperaionMode != pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode) ||
-					(AddHtInfo.AddHtInfo2.NonGfPresent != pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent)))
-				{
-					pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent = AddHtInfo.AddHtInfo2.NonGfPresent;
-					pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode = AddHtInfo.AddHtInfo2.OperaionMode;
-					if (pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1)
-				{
-						AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, ALLN_SETPROTECT, FALSE, TRUE);
-					}
-					else
-						AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, ALLN_SETPROTECT, FALSE, FALSE);
-
-					DBGPRINT(RT_DEBUG_TRACE, ("SYNC - AP changed N OperaionMode to %d\n", pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode));
-				}
-#endif // DOT11_N_SUPPORT //
-
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED) &&
-					ERP_IS_USE_BARKER_PREAMBLE(Erp))
-				{
-					MlmeSetTxPreamble(pAd, Rt802_11PreambleLong);
-					DBGPRINT(RT_DEBUG_TRACE, ("SYNC - AP forced to use LONG preamble\n"));
-				}
-
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED)    &&
-					(EdcaParm.bValid == TRUE)                          &&
-					(EdcaParm.EdcaUpdateCount != pAd->CommonCfg.APEdcaParm.EdcaUpdateCount))
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("SYNC - AP change EDCA parameters(from %d to %d)\n",
-						pAd->CommonCfg.APEdcaParm.EdcaUpdateCount,
-						EdcaParm.EdcaUpdateCount));
-					AsicSetEdcaParm(pAd, &EdcaParm);
-				}
-
-				// copy QOS related information
-				NdisMoveMemory(&pAd->CommonCfg.APQbssLoad, &QbssLoad, sizeof(QBSS_LOAD_PARM));
-				NdisMoveMemory(&pAd->CommonCfg.APQosCapability, &QosCapability, sizeof(QOS_CAPABILITY_PARM));
-			}
-
-			// only INFRASTRUCTURE mode support power-saving feature
-			if ((INFRA_ON(pAd) && (pAd->StaCfg.Psm == PWR_SAVE)) || (pAd->CommonCfg.bAPSDForcePowerSave))
-			{
-				UCHAR FreeNumber;
-				//  1. AP has backlogged unicast-to-me frame, stay AWAKE, send PSPOLL
-				//  2. AP has backlogged broadcast/multicast frame and we want those frames, stay AWAKE
-				//  3. we have outgoing frames in TxRing or MgmtRing, better stay AWAKE
-				//  4. Psm change to PWR_SAVE, but AP not been informed yet, we better stay AWAKE
-				//  5. otherwise, put PHY back to sleep to save battery.
-				if (MessageToMe)
-				{
-					if (pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable &&
-						pAd->CommonCfg.bAPSDAC_BE && pAd->CommonCfg.bAPSDAC_BK && pAd->CommonCfg.bAPSDAC_VI && pAd->CommonCfg.bAPSDAC_VO)
-					{
-						pAd->CommonCfg.bNeedSendTriggerFrame = TRUE;
-					}
-					else
-						RT28XX_PS_POLL_ENQUEUE(pAd);
-				}
-				else if (BcastFlag && (DtimCount == 0) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM))
-				{
-				}
-				else if ((pAd->TxSwQueue[QID_AC_BK].Number != 0)													||
-						(pAd->TxSwQueue[QID_AC_BE].Number != 0)														||
-						(pAd->TxSwQueue[QID_AC_VI].Number != 0)														||
-						(pAd->TxSwQueue[QID_AC_VO].Number != 0)														||
-						(RTMPFreeTXDRequest(pAd, QID_AC_BK, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS)	||
-						(RTMPFreeTXDRequest(pAd, QID_AC_BE, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS)	||
-						(RTMPFreeTXDRequest(pAd, QID_AC_VI, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS)	||
-						(RTMPFreeTXDRequest(pAd, QID_AC_VO, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS)	||
-						(RTMPFreeTXDRequest(pAd, QID_MGMT, MGMT_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS))
-				{
-					// TODO: consider scheduled HCCA. might not be proper to use traditional DTIM-based power-saving scheme
-					// can we cheat here (i.e. just check MGMT & AC_BE) for better performance?
-				}
-				else
-				{
-					USHORT NextDtim = DtimCount;
-
-					if (NextDtim == 0)
-						NextDtim = DtimPeriod;
-
-					TbttNumToNextWakeUp = pAd->StaCfg.DefaultListenCount;
-					if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM) && (TbttNumToNextWakeUp > NextDtim))
-						TbttNumToNextWakeUp = NextDtim;
-
-					if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-					{
-						AsicSleepThenAutoWakeup(pAd, TbttNumToNextWakeUp);
-					}
-				}
-			}
-		}
-		// not my BSSID, ignore it
-	}
-	// sanity check fail, ignore this frame
-}
-
-/*
-	==========================================================================
-	Description:
-		Receive PROBE REQ from remote peer when operating in IBSS mode
-	==========================================================================
- */
-VOID PeerProbeReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR         Addr2[MAC_ADDR_LEN];
-	CHAR          Ssid[MAX_LEN_OF_SSID];
-	UCHAR         SsidLen;
-#ifdef DOT11_N_SUPPORT
-	UCHAR		  HtLen, AddHtLen, NewExtLen;
-#endif // DOT11_N_SUPPORT //
-	HEADER_802_11 ProbeRspHdr;
-	NDIS_STATUS   NStatus;
-	PUCHAR        pOutBuffer = NULL;
-	ULONG         FrameLen = 0;
-	LARGE_INTEGER FakeTimestamp;
-	UCHAR         DsLen = 1, IbssLen = 2;
-	UCHAR         LocalErpIe[3] = {IE_ERP, 1, 0};
-	BOOLEAN       Privacy;
-	USHORT        CapabilityInfo;
-	UCHAR		  RSNIe = IE_WPA;
-
-	if (! ADHOC_ON(pAd))
-		return;
-
-	if (PeerProbeReqSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, Ssid, &SsidLen))
-	{
-		if ((SsidLen == 0) || SSID_EQUAL(Ssid, SsidLen, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen))
-		{
-			// allocate and send out ProbeRsp frame
-			NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-			if (NStatus != NDIS_STATUS_SUCCESS)
-				return;
-
-			//pAd->StaCfg.AtimWin = 0;  // ??????
-
-			Privacy = (pAd->StaCfg.WepStatus == Ndis802_11Encryption1Enabled) ||
-					  (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
-					  (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled);
-			CapabilityInfo = CAP_GENERATE(0, 1, Privacy, (pAd->CommonCfg.TxPreamble == Rt802_11PreambleShort), 0, 0);
-
-			MakeOutgoingFrame(pOutBuffer,                   &FrameLen,
-							  sizeof(HEADER_802_11),        &ProbeRspHdr,
-							  TIMESTAMP_LEN,                &FakeTimestamp,
-							  2,                            &pAd->CommonCfg.BeaconPeriod,
-							  2,                            &CapabilityInfo,
-							  1,                            &SsidIe,
-							  1,                            &pAd->CommonCfg.SsidLen,
-							  pAd->CommonCfg.SsidLen,       pAd->CommonCfg.Ssid,
-							  1,                            &SupRateIe,
-							  1,                            &pAd->StaActive.SupRateLen,
-							  pAd->StaActive.SupRateLen,    pAd->StaActive.SupRate,
-							  1,                            &DsIe,
-							  1,                            &DsLen,
-							  1,                            &pAd->CommonCfg.Channel,
-							  1,                            &IbssIe,
-							  1,                            &IbssLen,
-							  2,                            &pAd->StaActive.AtimWin,
-							  END_OF_ARGS);
-
-			if (pAd->StaActive.ExtRateLen)
-			{
-				ULONG tmp;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,        &tmp,
-								  3,                            LocalErpIe,
-								  1,                            &ExtRateIe,
-								  1,                            &pAd->StaActive.ExtRateLen,
-								  pAd->StaActive.ExtRateLen,    &pAd->StaActive.ExtRate,
-								  END_OF_ARGS);
-				FrameLen += tmp;
-			}
-
-			// If adhoc secruity is set for WPA-None, append the cipher suite IE
-			if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-			{
-				ULONG tmp;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,        	&tmp,
-						  			1,                              &RSNIe,
-						  			1,                            	&pAd->StaCfg.RSNIE_Len,
-						  			pAd->StaCfg.RSNIE_Len,      	pAd->StaCfg.RSN_IE,
-						  			END_OF_ARGS);
-				FrameLen += tmp;
-			}
-#ifdef DOT11_N_SUPPORT
-			if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-			{
-				ULONG TmpLen;
-				UCHAR	BROADCOM[4] = {0x0, 0x90, 0x4c, 0x33};
-				HtLen = sizeof(pAd->CommonCfg.HtCapability);
-				AddHtLen = sizeof(pAd->CommonCfg.AddHTInfo);
-				NewExtLen = 1;
-				//New extension channel offset IE is included in Beacon, Probe Rsp or channel Switch Announcement Frame
-				if (pAd->bBroadComHT == TRUE)
-				{
-					MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-								  1,                                &WpaIe,
-								  4,                                &BROADCOM[0],
-								 pAd->MlmeAux.HtCapabilityLen,          &pAd->MlmeAux.HtCapability,
-								  END_OF_ARGS);
-				}
-				else
-				{
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-								  1,                                &HtCapIe,
-								  1,                                &HtLen,
-								 sizeof(HT_CAPABILITY_IE),          &pAd->CommonCfg.HtCapability,
-								  1,                                &AddHtInfoIe,
-								  1,                                &AddHtLen,
-								 sizeof(ADD_HT_INFO_IE),          &pAd->CommonCfg.AddHTInfo,
-								  1,                                &NewExtChanIe,
-								  1,                                &NewExtLen,
-								 sizeof(NEW_EXT_CHAN_IE),          &pAd->CommonCfg.NewExtChanOffset,
-								  END_OF_ARGS);
-				}
-				FrameLen += TmpLen;
-			}
-#endif // DOT11_N_SUPPORT //
-			MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-			MlmeFreeMemory(pAd, pOutBuffer);
-		}
-	}
-}
-
-VOID BeaconTimeoutAtJoinAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("SYNC - BeaconTimeoutAtJoinAction\n"));
-	pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-	Status = MLME_REJ_TIMEOUT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_JOIN_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-		Scan timeout procedure. basically add channel index by 1 and rescan
-	==========================================================================
- */
-VOID ScanTimeoutAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	pAd->MlmeAux.Channel = NextChannel(pAd, pAd->MlmeAux.Channel);
-
-	// Only one channel scanned for CISCO beacon request
-	if ((pAd->MlmeAux.ScanType == SCAN_CISCO_ACTIVE) ||
-		(pAd->MlmeAux.ScanType == SCAN_CISCO_PASSIVE) ||
-		(pAd->MlmeAux.ScanType == SCAN_CISCO_NOISE) ||
-		(pAd->MlmeAux.ScanType == SCAN_CISCO_CHANNEL_LOAD))
-		pAd->MlmeAux.Channel = 0;
-
-	// this routine will stop if pAd->MlmeAux.Channel == 0
-	ScanNextChannel(pAd);
-}
-
-/*
-	==========================================================================
-	Description:
-	==========================================================================
- */
-VOID InvalidStateWhenScan(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("AYNC - InvalidStateWhenScan(state=%ld). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState));
-	pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-	==========================================================================
- */
-VOID InvalidStateWhenJoin(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("InvalidStateWhenJoin(state=%ld). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState));
-	pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_JOIN_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-	==========================================================================
- */
-VOID InvalidStateWhenStart(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("InvalidStateWhenStart(state=%ld). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState));
-	pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_START_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID EnqueuePsPoll(
-	IN PRTMP_ADAPTER pAd)
-{
-#ifdef RALINK_ATE
-    if (ATE_ON(pAd))
-    {
-		return;
-    }
-#endif // RALINK_ATE //
-
-
-	if (pAd->StaCfg.WindowsPowerMode == Ndis802_11PowerModeLegacy_PSP)
-    	pAd->PsPollFrame.FC.PwrMgmt = PWR_SAVE;
-	MiniportMMRequest(pAd, 0, (PUCHAR)&pAd->PsPollFrame, sizeof(PSPOLL_FRAME));
-}
-
-
-/*
-	==========================================================================
-	Description:
-	==========================================================================
- */
-VOID EnqueueProbeRequest(
-	IN PRTMP_ADAPTER pAd)
-{
-	NDIS_STATUS     NState;
-	PUCHAR          pOutBuffer;
-	ULONG           FrameLen = 0;
-	HEADER_802_11   Hdr80211;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("force out a ProbeRequest ...\n"));
-
-	NState = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NState == NDIS_STATUS_SUCCESS)
-	{
-		MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, BROADCAST_ADDR, BROADCAST_ADDR);
-
-		// this ProbeRequest explicitly specify SSID to reduce unwanted ProbeResponse
-		MakeOutgoingFrame(pOutBuffer,                     &FrameLen,
-						  sizeof(HEADER_802_11),          &Hdr80211,
-						  1,                              &SsidIe,
-						  1,                              &pAd->CommonCfg.SsidLen,
-						  pAd->CommonCfg.SsidLen,		  pAd->CommonCfg.Ssid,
-						  1,                              &SupRateIe,
-						  1,                              &pAd->StaActive.SupRateLen,
-						  pAd->StaActive.SupRateLen,      pAd->StaActive.SupRate,
-						  END_OF_ARGS);
-		MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer);
-	}
-
-}
-
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-VOID BuildEffectedChannelList(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR		EChannel[11];
-	UCHAR		i, j, k;
-	UCHAR		UpperChannel = 0, LowerChannel = 0;
-
-	RTMPZeroMemory(EChannel, 11);
-	i = 0;
-	// Find upper channel and lower channel.
-	if (pAd->CommonCfg.CentralChannel < pAd->CommonCfg.Channel)
-	{
-		UpperChannel = pAd->CommonCfg.Channel;
-		LowerChannel = pAd->CommonCfg.CentralChannel;
-	}
-	else if (pAd->CommonCfg.CentralChannel > pAd->CommonCfg.Channel)
-	{
-		UpperChannel = pAd->CommonCfg.CentralChannel;
-		LowerChannel = pAd->CommonCfg.Channel;
-	}
-	else
-	{
-		return;
-	}
-
-	// Record channels that is below lower channel..
-	if (LowerChannel > 1)
-	{
-		EChannel[0] = LowerChannel - 1;
-		i = 1;
-		if (LowerChannel > 2)
-		{
-			EChannel[1] = LowerChannel - 2;
-			i = 2;
-			if (LowerChannel > 3)
-			{
-				EChannel[2] = LowerChannel - 3;
-				i = 3;
-			}
-		}
-	}
-	// Record channels that is between  lower channel and upper channel.
-	for (k = LowerChannel;k < UpperChannel;k++)
-	{
-		EChannel[i] = k;
-		i++;
-	}
-	// Record channels that is above upper channel..
-	if (LowerChannel < 11)
-	{
-		EChannel[i] = UpperChannel + 1;
-		i++;
-		if (LowerChannel < 10)
-		{
-			EChannel[i] = LowerChannel + 2;
-			i++;
-			if (LowerChannel < 9)
-			{
-				EChannel[i] = LowerChannel + 3;
-				i++;
-			}
-		}
-	}
-	//
-	for (j = 0;j < i;j++)
-	{
-		for (k = 0;k < pAd->ChannelListNum;k++)
-		{
-			if (pAd->ChannelList[k].Channel == EChannel[j])
-			{
-				pAd->ChannelList[k].bEffectedChannel = TRUE;
-				DBGPRINT(RT_DEBUG_TRACE,(" EffectedChannel( =%d)\n", EChannel[j]));
-				break;
-			}
-		}
-	}
-}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-BOOLEAN ScanRunning(
-		IN PRTMP_ADAPTER pAd)
-{
-	return (pAd->Mlme.SyncMachine.CurrState == SCAN_LISTEN) ? TRUE : FALSE;
-}
-
+#include "../../rt2860/sta/sync.c"
diff --git a/drivers/staging/rt2870/sta/wpa.c b/drivers/staging/rt2870/sta/wpa.c
index 8626dcd..57a2eb2 100644
--- a/drivers/staging/rt2870/sta/wpa.c
+++ b/drivers/staging/rt2870/sta/wpa.c
@@ -1,2107 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	wpa.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Jan	Lee		03-07-22		Initial
-	Paul Lin	03-11-28		Modify for supplicant
-*/
-#include "../rt_config.h"
-
-#define		WPARSNIE	0xdd
-#define		WPA2RSNIE	0x30
-
-//extern UCHAR BIT8[];
-UCHAR	CipherWpaPskTkip[] = {
-		0xDD, 0x16,				// RSN IE
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x02,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x02,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x02	// authentication
-		};
-UCHAR	CipherWpaPskTkipLen = (sizeof(CipherWpaPskTkip) / sizeof(UCHAR));
-
-UCHAR	CipherWpaPskAes[] = {
-		0xDD, 0x16, 			// RSN IE
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x04,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x04,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x02	// authentication
-		};
-UCHAR	CipherWpaPskAesLen = (sizeof(CipherWpaPskAes) / sizeof(UCHAR));
-
-UCHAR	CipherSuiteCiscoCCKM[] = {
-		0xDD, 0x16,				// RSN IE
-		0x00, 0x50, 0xf2, 0x01, // oui
-		0x01, 0x00,				// Version
-		0x00, 0x40, 0x96, 0x01, // Multicast
-		0x01, 0x00,				// Number of uicast
-		0x00, 0x40, 0x96, 0x01, // unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x40, 0x96, 0x00  // Authentication
-		};
-UCHAR	CipherSuiteCiscoCCKMLen = (sizeof(CipherSuiteCiscoCCKM) / sizeof(UCHAR));
-
-UCHAR	CipherSuiteCiscoCCKM24[] = {
-		0xDD, 0x18,				// RSN IE
-		0x00, 0x50, 0xf2, 0x01, // oui
-		0x01, 0x00,				// Version
-		0x00, 0x40, 0x96, 0x01, // Multicast
-		0x01, 0x00,				// Number of uicast
-		0x00, 0x40, 0x96, 0x01, // unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x40, 0x96, 0x00,
-		0x28, 0x00// Authentication
-		};
-
-UCHAR	CipherSuiteCiscoCCKM24Len = (sizeof(CipherSuiteCiscoCCKM24) / sizeof(UCHAR));
-
-UCHAR	CipherSuiteCCXTkip[] = {
-		0xDD, 0x16,				// RSN IE
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x02,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x02,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x01	// authentication
-		};
-UCHAR	CipherSuiteCCXTkipLen = (sizeof(CipherSuiteCCXTkip) / sizeof(UCHAR));
-
-UCHAR	CCX_LLC_HDR[] = {0xAA, 0xAA, 0x03, 0x00, 0x40, 0x96, 0x00, 0x02};
-UCHAR	LLC_NORMAL[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00};
-
-UCHAR	EAPOL_FRAME[] = {0x88, 0x8E};
-
-BOOLEAN CheckRSNIE(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pData,
-	IN  UCHAR           DataLen,
-	OUT	UCHAR			*Offset);
-
-void inc_byte_array(UCHAR *counter, int len);
-
-/*
-	========================================================================
-
-	Routine Description:
-		Classify WPA EAP message type
-
-	Arguments:
-		EAPType		Value of EAP message type
-		MsgType		Internal Message definition for MLME state machine
-
-	Return Value:
-		TRUE		Found appropriate message type
-		FALSE		No appropriate message type
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-		All these constants are defined in wpa.h
-		For supplicant, there is only EAPOL Key message avaliable
-
-	========================================================================
-*/
-BOOLEAN	WpaMsgTypeSubst(
-	IN	UCHAR	EAPType,
-	OUT	INT		*MsgType)
-{
-	switch (EAPType)
-	{
-		case EAPPacket:
-			*MsgType = MT2_EAPPacket;
-			break;
-		case EAPOLStart:
-			*MsgType = MT2_EAPOLStart;
-			break;
-		case EAPOLLogoff:
-			*MsgType = MT2_EAPOLLogoff;
-			break;
-		case EAPOLKey:
-			*MsgType = MT2_EAPOLKey;
-			break;
-		case EAPOLASFAlert:
-			*MsgType = MT2_EAPOLASFAlert;
-			break;
-		default:
-			return FALSE;
-	}
-	return TRUE;
-}
-
-/*
-	==========================================================================
-	Description:
-		association	state machine init,	including state	transition and timer init
-	Parameters:
-		S -	pointer	to the association state machine
-	==========================================================================
- */
-VOID WpaPskStateMachineInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	STATE_MACHINE *S,
-	OUT	STATE_MACHINE_FUNC Trans[])
-{
-	StateMachineInit(S,	Trans, MAX_WPA_PSK_STATE, MAX_WPA_PSK_MSG, (STATE_MACHINE_FUNC)Drop, WPA_PSK_IDLE, WPA_MACHINE_BASE);
-	StateMachineSetAction(S, WPA_PSK_IDLE, MT2_EAPOLKey, (STATE_MACHINE_FUNC)WpaEAPOLKeyAction);
-}
-
-/*
-	==========================================================================
-	Description:
-		This is	state machine function.
-		When receiving EAPOL packets which is  for 802.1x key management.
-		Use	both in	WPA, and WPAPSK	case.
-		In this	function, further dispatch to different	functions according	to the received	packet.	 3 categories are :
-		  1.  normal 4-way pairwisekey and 2-way groupkey handshake
-		  2.  MIC error	(Countermeasures attack)  report packet	from STA.
-		  3.  Request for pairwise/group key update	from STA
-	Return:
-	==========================================================================
-*/
-VOID WpaEAPOLKeyAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-
-{
-	INT             MsgType = EAPOL_MSG_INVALID;
-	PKEY_DESCRIPTER pKeyDesc;
-	PHEADER_802_11  pHeader; //red
-	UCHAR           ZeroReplay[LEN_KEY_DESC_REPLAY];
-	UCHAR EapolVr;
-	KEY_INFO		peerKeyInfo;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("-----> WpaEAPOLKeyAction\n"));
-
-	// Get 802.11 header first
-	pHeader = (PHEADER_802_11) Elem->Msg;
-
-	// Get EAPoL-Key Descriptor
-	pKeyDesc = (PKEY_DESCRIPTER) &Elem->Msg[(LENGTH_802_11 + LENGTH_802_1_H + LENGTH_EAPOL_H)];
-
-	NdisZeroMemory((PUCHAR)&peerKeyInfo, sizeof(peerKeyInfo));
-	NdisMoveMemory((PUCHAR)&peerKeyInfo, (PUCHAR)&pKeyDesc->KeyInfo, sizeof(KEY_INFO));
-
-	*((USHORT *)&peerKeyInfo) = cpu2le16(*((USHORT *)&peerKeyInfo));
-
-
-	// 1. Check EAPOL frame version and type
-	EapolVr	= (UCHAR) Elem->Msg[LENGTH_802_11+LENGTH_802_1_H];
-
-    if (((EapolVr != EAPOL_VER) && (EapolVr != EAPOL_VER2)) || ((pKeyDesc->Type != WPA1_KEY_DESC) && (pKeyDesc->Type != WPA2_KEY_DESC)))
-	{
-        DBGPRINT(RT_DEBUG_ERROR, ("Key descripter does not match with WPA rule\n"));
-			return;
-	}
-
-	// First validate replay counter, only accept message with larger replay counter
-	// Let equal pass, some AP start with all zero replay counter
-	NdisZeroMemory(ZeroReplay, LEN_KEY_DESC_REPLAY);
-
-	if((RTMPCompareMemory(pKeyDesc->ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1) &&
-		(RTMPCompareMemory(pKeyDesc->ReplayCounter, ZeroReplay, LEN_KEY_DESC_REPLAY) != 0))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("   ReplayCounter not match   \n"));
-		return;
-	}
-
-	// Process WPA2PSK frame
-	if(pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-	{
-		if((peerKeyInfo.KeyType == PAIRWISEKEY) &&
-			(peerKeyInfo.EKD_DL == 0) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 0) &&
-			(peerKeyInfo.Secure == 0) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_PAIR_MSG_1;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Pairwise Message 1\n"));
-		} else if((peerKeyInfo.KeyType == PAIRWISEKEY) &&
-			(peerKeyInfo.EKD_DL  == 1) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 1) &&
-			(peerKeyInfo.Secure == 1) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_PAIR_MSG_3;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Pairwise Message 3\n"));
-		} else if((peerKeyInfo.KeyType == GROUPKEY) &&
-			(peerKeyInfo.EKD_DL == 1) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 1) &&
-			(peerKeyInfo.Secure == 1) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_GROUP_MSG_1;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Group Message 1\n"));
-		}
-
-		// We will assume link is up (assoc suceess and port not secured).
-		// All state has to be able to process message from previous state
-		switch(pAd->StaCfg.WpaState)
-		{
-		case SS_START:
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-				Wpa2PairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-			}
-			break;
-
-		case SS_WAIT_MSG_3:
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-				Wpa2PairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-			}
-			else if(MsgType == EAPOL_PAIR_MSG_3)
-			{
-				Wpa2PairMsg3Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_GROUP;
-			}
-			break;
-
-		case SS_WAIT_GROUP:		// When doing group key exchange
-		case SS_FINISH:			// This happened when update group key
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-			    // Reset port secured variable
-				pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-				Wpa2PairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-			}
-			else if(MsgType == EAPOL_PAIR_MSG_3)
-			{
-			    // Reset port secured variable
-				pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-				Wpa2PairMsg3Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_GROUP;
-			}
-			else if(MsgType == EAPOL_GROUP_MSG_1)
-			{
-				WpaGroupMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_FINISH;
-			}
-			break;
-
-		default:
-			break;
-		}
-	}
-	// Process WPAPSK Frame
-	// Classify message Type, either pairwise message 1, 3, or group message 1 for supplicant
-	else if(pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)
-	{
-		if((peerKeyInfo.KeyType == PAIRWISEKEY) &&
-			(peerKeyInfo.KeyIndex == 0) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 0) &&
-			(peerKeyInfo.Secure == 0) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_PAIR_MSG_1;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Pairwise Message 1\n"));
-		}
-		else if((peerKeyInfo.KeyType == PAIRWISEKEY) &&
-			(peerKeyInfo.KeyIndex == 0) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 1) &&
-			(peerKeyInfo.Secure == 0) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_PAIR_MSG_3;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Pairwise Message 3\n"));
-		}
-		else if((peerKeyInfo.KeyType == GROUPKEY) &&
-			(peerKeyInfo.KeyIndex != 0) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 1) &&
-			(peerKeyInfo.Secure == 1) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_GROUP_MSG_1;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Group Message 1\n"));
-		}
-
-		// We will assume link is up (assoc suceess and port not secured).
-		// All state has to be able to process message from previous state
-		switch(pAd->StaCfg.WpaState)
-		{
-		case SS_START:
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-				WpaPairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-			}
-			break;
-
-		case SS_WAIT_MSG_3:
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-				WpaPairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-			}
-			else if(MsgType == EAPOL_PAIR_MSG_3)
-			{
-				WpaPairMsg3Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_GROUP;
-			}
-			break;
-
-		case SS_WAIT_GROUP:		// When doing group key exchange
-		case SS_FINISH:			// This happened when update group key
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-				WpaPairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-				// Reset port secured variable
-				pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			}
-			else if(MsgType == EAPOL_PAIR_MSG_3)
-			{
-				WpaPairMsg3Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_GROUP;
-				// Reset port secured variable
-				pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			}
-			else if(MsgType == EAPOL_GROUP_MSG_1)
-			{
-				WpaGroupMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_FINISH;
-			}
-			break;
-
-		default:
-			break;
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<----- WpaEAPOLKeyAction\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Process Pairwise key 4-way handshaking
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		Elem		Message body
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	WpaPairMsg1Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem)
-{
-	PHEADER_802_11      pHeader;
-	UCHAR				*mpool, *PTK, *digest;
-	PUCHAR              pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG               FrameLen = 0;
-	PEAPOL_PACKET       pMsg1;
-	EAPOL_PACKET        Packet;
-	UCHAR               Mic[16];
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaPairMsg1Action ----->\n"));
-
-	// allocate memory pool
-	os_alloc_mem(pAd, (PUCHAR *)&mpool, 256);
-
-	if (mpool == NULL)
-		return;
-
-	// PTK Len = 80.
-	PTK = (UCHAR *) ROUND_UP(mpool, 4);
-	// digest Len = 80.
-	digest = (UCHAR *) ROUND_UP(PTK + 80, 4);
-
-	pHeader = (PHEADER_802_11) Elem->Msg;
-
-	// Process message 1 from authenticator
-	pMsg1 = (PEAPOL_PACKET) &Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
-
-	// 1. Save Replay counter, it will use to verify message 3 and construct message 2
-	NdisMoveMemory(pAd->StaCfg.ReplayCounter, pMsg1->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// 2. Save ANonce
-	NdisMoveMemory(pAd->StaCfg.ANonce, pMsg1->KeyDesc.KeyNonce, LEN_KEY_DESC_NONCE);
-
-	// Generate random SNonce
-	GenRandom(pAd, pAd->CurrentAddress, pAd->StaCfg.SNonce);
-
-	// Calc PTK(ANonce, SNonce)
-	WpaCountPTK(pAd,
-		pAd->StaCfg.PMK,
-		pAd->StaCfg.ANonce,
-		pAd->CommonCfg.Bssid,
-		pAd->StaCfg.SNonce,
-		pAd->CurrentAddress,
-		PTK,
-		LEN_PTK);
-
-	// Save key to PTK entry
-	NdisMoveMemory(pAd->StaCfg.PTK, PTK, LEN_PTK);
-
-	// init 802.3 header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero Message 2 body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-	//
-	// Message 2 as  EAPOL-Key(0,1,0,0,0,P,0,SNonce,MIC,RSN IE)
-	//
-	Packet.KeyDesc.Type = WPA1_KEY_DESC;
-	// 1. Key descriptor version and appropriate RSN IE
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 2;
-	}
-	else	  // TKIP
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 1;
-	}
-
-	// fill in Data Material and its length
-	Packet.KeyDesc.KeyData[0] = IE_WPA;
-	Packet.KeyDesc.KeyData[1] = pAd->StaCfg.RSNIE_Len;
-	Packet.KeyDesc.KeyDataLen[1] = pAd->StaCfg.RSNIE_Len + 2;
-	NdisMoveMemory(&Packet.KeyDesc.KeyData[2], pAd->StaCfg.RSN_IE, pAd->StaCfg.RSNIE_Len);
-
-	// Update packet length after decide Key data payload
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE + Packet.KeyDesc.KeyDataLen[1];
-
-	// Update Key length
-	Packet.KeyDesc.KeyLength[0] = pMsg1->KeyDesc.KeyLength[0];
-	Packet.KeyDesc.KeyLength[1] = pMsg1->KeyDesc.KeyLength[1];
-	// 2. Key Type PeerKey
-	Packet.KeyDesc.KeyInfo.KeyType = PAIRWISEKEY;
-
-	// 3. KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-
-	//Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-
-	// 4. Fill SNonce
-	NdisMoveMemory(Packet.KeyDesc.KeyNonce, pAd->StaCfg.SNonce, LEN_KEY_DESC_NONCE);
-
-	// 5. Key Replay Count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Send EAPOL(0, 1, 0, 0, 0, P, 0, SNonce, MIC, RSN_IE)
-	// Out buffer for transmitting message 2
-	MlmeAllocateMemory(pAd, (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-	{
-		os_free_mem(pAd, mpool);
-		return;
-	}
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		Packet.Body_Len[1] + 4,    &Packet,
-		END_OF_ARGS);
-
-	// 6. Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{	// AES
-
-		HMAC_SHA1(pOutBuffer, FrameLen, PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{	// TKIP
-		hmac_md5(PTK,  LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-	//hex_dump("MIC", Mic, LEN_KEY_DESC_MIC);
-
-		MakeOutgoingFrame(pOutBuffer,           	&FrameLen,
-			  			LENGTH_802_3,     			&Header802_3,
-						Packet.Body_Len[1] + 4,    &Packet,
-						END_OF_ARGS);
-
-
-	// 5. Copy frame to Tx ring and send Msg 2 to authenticator
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, TRUE);
-
-	MlmeFreeMemory(pAd, (PUCHAR)pOutBuffer);
-	os_free_mem(pAd, (PUCHAR)mpool);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaPairMsg1Action <-----\n"));
-}
-
-VOID Wpa2PairMsg1Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem)
-{
-	PHEADER_802_11      pHeader;
-	UCHAR				*mpool, *PTK, *digest;
-	PUCHAR              pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG               FrameLen = 0;
-	PEAPOL_PACKET       pMsg1;
-	EAPOL_PACKET        Packet;
-	UCHAR               Mic[16];
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Wpa2PairMsg1Action ----->\n"));
-
-	// allocate memory pool
-	os_alloc_mem(pAd, (PUCHAR *)&mpool, 256);
-
-	if (mpool == NULL)
-		return;
-
-	// PTK Len = 80.
-	PTK = (UCHAR *) ROUND_UP(mpool, 4);
-	// digest Len = 80.
-	digest = (UCHAR *) ROUND_UP(PTK + 80, 4);
-
-	pHeader = (PHEADER_802_11) Elem->Msg;
-
-	// Process message 1 from authenticator
-		pMsg1 = (PEAPOL_PACKET)	&Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
-
-	// 1. Save Replay counter, it will use to verify message 3 and construct message 2
-	NdisMoveMemory(pAd->StaCfg.ReplayCounter, pMsg1->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// 2. Save ANonce
-	NdisMoveMemory(pAd->StaCfg.ANonce, pMsg1->KeyDesc.KeyNonce, LEN_KEY_DESC_NONCE);
-
-	// Generate random SNonce
-	GenRandom(pAd, pAd->CurrentAddress, pAd->StaCfg.SNonce);
-
-	if(pMsg1->KeyDesc.KeyDataLen[1] > 0 )
-	{
-		// cached PMKID
-	}
-
-	// Calc PTK(ANonce, SNonce)
-	WpaCountPTK(pAd,
-		pAd->StaCfg.PMK,
-		pAd->StaCfg.ANonce,
-		pAd->CommonCfg.Bssid,
-		pAd->StaCfg.SNonce,
-		pAd->CurrentAddress,
-		PTK,
-		LEN_PTK);
-
-	// Save key to PTK entry
-	NdisMoveMemory(pAd->StaCfg.PTK, PTK, LEN_PTK);
-
-	// init 802.3 header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero message 2 body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-	//
-	// Message 2 as  EAPOL-Key(0,1,0,0,0,P,0,SNonce,MIC,RSN IE)
-	//
-	Packet.KeyDesc.Type = WPA2_KEY_DESC;
-
-	// 1. Key descriptor version and appropriate RSN IE
-	if(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 2;
-	}
-	else	  // TKIP
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 1;
-	}
-
-	// fill in Data Material and its length
-	Packet.KeyDesc.KeyData[0] = IE_WPA2;
-	Packet.KeyDesc.KeyData[1] = pAd->StaCfg.RSNIE_Len;
-	Packet.KeyDesc.KeyDataLen[1] = pAd->StaCfg.RSNIE_Len + 2;
-	NdisMoveMemory(&Packet.KeyDesc.KeyData[2], pAd->StaCfg.RSN_IE, pAd->StaCfg.RSNIE_Len);
-
-	// Update packet length after decide Key data payload
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE + Packet.KeyDesc.KeyDataLen[1];
-
-	// 2. Key Type PeerKey
-	Packet.KeyDesc.KeyInfo.KeyType = PAIRWISEKEY;
-
-	// 3. KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-
-	// Update Key Length
-	Packet.KeyDesc.KeyLength[0] = 0;
-	Packet.KeyDesc.KeyLength[1] = pMsg1->KeyDesc.KeyLength[1];
-
-	// 4. Fill SNonce
-	NdisMoveMemory(Packet.KeyDesc.KeyNonce, pAd->StaCfg.SNonce, LEN_KEY_DESC_NONCE);
-
-	// 5. Key Replay Count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-	// Send EAPOL-Key(0,1,0,0,0,P,0,SNonce,MIC,RSN IE)
-	// Out buffer for transmitting message 2
-	MlmeAllocateMemory(pAd,  (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-	{
-		os_free_mem(pAd, mpool);
-		return;
-	}
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,        &FrameLen,
-		Packet.Body_Len[1] + 4, &Packet,
-		END_OF_ARGS);
-
-	// 6. Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		HMAC_SHA1(pOutBuffer, FrameLen, PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(PTK,  LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-
-	// Make  Transmitting frame
-	MakeOutgoingFrame(pOutBuffer,           	&FrameLen,
-			  			LENGTH_802_3,     		&Header802_3,
-						Packet.Body_Len[1] + 4, &Packet,
-						END_OF_ARGS);
-
-
-	// 5. Copy frame to Tx ring
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, TRUE);
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-	os_free_mem(pAd, mpool);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Wpa2PairMsg1Action <-----\n"));
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Process Pairwise key 4-way handshaking
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		Elem		Message body
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	WpaPairMsg3Action(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-
-{
-	PHEADER_802_11      pHeader;
-	PUCHAR          	pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG           	FrameLen = 0;
-	EAPOL_PACKET        Packet;
-	PEAPOL_PACKET       pMsg3;
-	UCHAR           	Mic[16], OldMic[16];
-	MAC_TABLE_ENTRY 	*pEntry = NULL;
-	UCHAR				skip_offset;
-	KEY_INFO			peerKeyInfo;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaPairMsg3Action ----->\n"));
-
-	// Record 802.11 header & the received EAPOL packet Msg3
-	pHeader = (PHEADER_802_11) Elem->Msg;
-	pMsg3 = (PEAPOL_PACKET)	&Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
-
-	NdisZeroMemory((PUCHAR)&peerKeyInfo, sizeof(peerKeyInfo));
-	NdisMoveMemory((PUCHAR)&peerKeyInfo, (PUCHAR)&pMsg3->KeyDesc.KeyInfo, sizeof(KEY_INFO));
-
-	*((USHORT*)&peerKeyInfo) = cpu2le16(*((USHORT*)&peerKeyInfo));
-
-
-	// 1. Verify cipher type match
-	if (pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled && (peerKeyInfo.KeyDescVer != 2))
-	{
-		return;
-	}
-	else if(pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled && (peerKeyInfo.KeyDescVer != 1))
-	{
-		return;
-	}
-
-	// Verify RSN IE
-	//if (!RTMPEqualMemory(pMsg3->KeyDesc.KeyData, pAd->MacTab.Content[BSSID_WCID].RSN_IE, pAd->MacTab.Content[BSSID_WCID].RSNIE_Len))
-	if (!CheckRSNIE(pAd, pMsg3->KeyDesc.KeyData, pMsg3->KeyDesc.KeyDataLen[1], &skip_offset))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RSN_IE Different in Msg 3 of WPA1 4-way handshake!! \n"));
-		hex_dump("The original RSN_IE", pAd->MacTab.Content[BSSID_WCID].RSN_IE, pAd->MacTab.Content[BSSID_WCID].RSNIE_Len);
-		hex_dump("The received RSN_IE", pMsg3->KeyDesc.KeyData, pMsg3->KeyDesc.KeyDataLen[1]);
-		return;
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, ("RSN_IE VALID in Msg 3 of WPA1 4-way handshake!! \n"));
-
-
-	// 2. Check MIC value
-	// Save the MIC and replace with zero
-	NdisMoveMemory(OldMic, pMsg3->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-	NdisZeroMemory(pMsg3->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		UCHAR digest[80];
-
-		HMAC_SHA1((PUCHAR) pMsg3, pMsg3->Body_Len[1] + 4, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else	// TKIP
-	{
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, (PUCHAR) pMsg3, pMsg3->Body_Len[1] + 4, Mic);
-	}
-
-	if(!NdisEqualMemory(OldMic, Mic, LEN_KEY_DESC_MIC))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, (" MIC Different in msg 3 of 4-way handshake!!!!!!!!!! \n"));
-		return;
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, (" MIC VALID in msg 3 of 4-way handshake!!!!!!!!!! \n"));
-
-	// 3. Check Replay Counter, it has to be larger than last one. No need to be exact one larger
-	if(RTMPCompareMemory(pMsg3->KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1)
-		return;
-
-	// Update new replay counter
-	NdisMoveMemory(pAd->StaCfg.ReplayCounter, pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// 4. Double check ANonce
-	if(!NdisEqualMemory(pAd->StaCfg.ANonce, pMsg3->KeyDesc.KeyNonce, LEN_KEY_DESC_NONCE))
-		return;
-
-	// init 802.3 header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero Message 4 body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE;		// No data field
-
-	//
-	// Message 4 as  EAPOL-Key(0,1,0,0,0,P,0,0,MIC,0)
-	//
-	Packet.KeyDesc.Type = WPA1_KEY_DESC;
-
-	// Key descriptor version and appropriate RSN IE
-	Packet.KeyDesc.KeyInfo.KeyDescVer = peerKeyInfo.KeyDescVer;
-
-	// Update Key Length
-	Packet.KeyDesc.KeyLength[0] = pMsg3->KeyDesc.KeyLength[0];
-	Packet.KeyDesc.KeyLength[1] = pMsg3->KeyDesc.KeyLength[1];
-
-	// Key Type PeerKey
-	Packet.KeyDesc.KeyInfo.KeyType = PAIRWISEKEY;
-
-	// KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-
-	// In Msg3,  KeyInfo.secure =0 if Group Key HS to come. 1 if no group key HS
-	// Station sends Msg4  KeyInfo.secure should be the same as that in Msg.3
-	Packet.KeyDesc.KeyInfo.Secure= peerKeyInfo.Secure;
-
-	// Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-	// Key Replay count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Out buffer for transmitting message 4
-	MlmeAllocateMemory(pAd, (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-		return;
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		Packet.Body_Len[1] + 4,    &Packet,
-		END_OF_ARGS);
-
-	// Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		UCHAR digest[80];
-
-		HMAC_SHA1(pOutBuffer, FrameLen, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-	// Update PTK
-	// Prepare pair-wise key information into shared key table
-	NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-	pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-    NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, &pAd->StaCfg.PTK[32], LEN_TKIP_EK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, &pAd->StaCfg.PTK[48], LEN_TKIP_RXMICK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, &pAd->StaCfg.PTK[48+LEN_TKIP_RXMICK], LEN_TKIP_TXMICK);
-
-	// Decide its ChiperAlg
-	if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-	else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-	else
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_NONE;
-
-	// Update these related information to MAC_TABLE_ENTRY
-	pEntry = &pAd->MacTab.Content[BSSID_WCID];
-	NdisMoveMemory(pEntry->PairwiseKey.Key, &pAd->StaCfg.PTK[32], LEN_TKIP_EK);
-	NdisMoveMemory(pEntry->PairwiseKey.RxMic, &pAd->StaCfg.PTK[48], LEN_TKIP_RXMICK);
-	NdisMoveMemory(pEntry->PairwiseKey.TxMic, &pAd->StaCfg.PTK[48+LEN_TKIP_RXMICK], LEN_TKIP_TXMICK);
-	pEntry->PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-
-	// Update pairwise key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAd,
-						  BSS0,
-						  0,
-						  pAd->SharedKey[BSS0][0].CipherAlg,
-						  pAd->SharedKey[BSS0][0].Key,
-						  pAd->SharedKey[BSS0][0].TxMic,
-						  pAd->SharedKey[BSS0][0].RxMic);
-
-	// Update ASIC WCID attribute table and IVEIV table
-	RTMPAddWcidAttributeEntry(pAd,
-							  BSS0,
-							  0,
-							  pAd->SharedKey[BSS0][0].CipherAlg,
-							  pEntry);
-
-	// Make transmitting frame
-	MakeOutgoingFrame(pOutBuffer,           	&FrameLen,
-			  			LENGTH_802_3,     		&Header802_3,
-						Packet.Body_Len[1] + 4, &Packet,
-						END_OF_ARGS);
-
-
-	// Copy frame to Tx ring and Send Message 4 to authenticator
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, TRUE);
-
-	MlmeFreeMemory(pAd, (PUCHAR)pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaPairMsg3Action <-----\n"));
-}
-
-VOID    Wpa2PairMsg3Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem)
-
-{
-	PHEADER_802_11      pHeader;
-	PUCHAR              pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG               FrameLen = 0;
-	EAPOL_PACKET        Packet;
-	PEAPOL_PACKET       pMsg3;
-	UCHAR               Mic[16], OldMic[16];
-	UCHAR               *mpool, *KEYDATA, *digest;
-	UCHAR               Key[32];
-	MAC_TABLE_ENTRY 	*pEntry = NULL;
-	KEY_INFO			peerKeyInfo;
-
-	// allocate memory
-	os_alloc_mem(pAd, (PUCHAR *)&mpool, 1024);
-
-	if(mpool == NULL)
-		return;
-
-	// KEYDATA Len = 512.
-	KEYDATA = (UCHAR *) ROUND_UP(mpool, 4);
-	// digest Len = 80.
-	digest = (UCHAR *) ROUND_UP(KEYDATA + 512, 4);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Wpa2PairMsg3Action ----->\n"));
-
-	pHeader = (PHEADER_802_11) Elem->Msg;
-
-	// Process message 3 frame.
-	pMsg3 = (PEAPOL_PACKET)	&Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
-
-	NdisZeroMemory((PUCHAR)&peerKeyInfo, sizeof(peerKeyInfo));
-	NdisMoveMemory((PUCHAR)&peerKeyInfo, (PUCHAR)&pMsg3->KeyDesc.KeyInfo, sizeof(KEY_INFO));
-
-	*((USHORT*)&peerKeyInfo) = cpu2le16(*((USHORT*)&peerKeyInfo));
-
-	// 1. Verify cipher type match
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled && (peerKeyInfo.KeyDescVer!= 2))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-	else if(pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled && (peerKeyInfo.KeyDescVer != 1))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// 2. Check MIC value
-	// Save the MIC and replace with zero
-	NdisMoveMemory(OldMic, pMsg3->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-	NdisZeroMemory(pMsg3->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		HMAC_SHA1((PUCHAR) pMsg3, pMsg3->Body_Len[1] + 4, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, (PUCHAR) pMsg3, pMsg3->Body_Len[1] + 4, Mic);
-	}
-
-	if(!NdisEqualMemory(OldMic, Mic, LEN_KEY_DESC_MIC))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, (" MIC Different in msg 3 of 4-way handshake!!!!!!!!!! \n"));
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, (" MIC VALID in msg 3 of 4-way handshake!!!!!!!!!! \n"));
-
-	// 3. Check Replay Counter, it has to be larger than last one. No need to be exact one larger
-	if(RTMPCompareMemory(pMsg3->KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1)
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Update new replay counter
-	NdisMoveMemory(pAd->StaCfg.ReplayCounter, pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// 4. Double check ANonce
-	if(!NdisEqualMemory(pAd->StaCfg.ANonce, pMsg3->KeyDesc.KeyNonce, LEN_KEY_DESC_NONCE))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Obtain GTK
-	// 5. Decrypt GTK from Key Data
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("EKD = %d\n", peerKeyInfo.EKD_DL));
-	if(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// Decrypt AES GTK
-		AES_GTK_KEY_UNWRAP(&pAd->StaCfg.PTK[16], KEYDATA, pMsg3->KeyDesc.KeyDataLen[1],pMsg3->KeyDesc.KeyData);
-	}
-	else	  // TKIP
-	{
-		INT i;
-		// Decrypt TKIP GTK
-		// Construct 32 bytes RC4 Key
-		NdisMoveMemory(Key, pMsg3->KeyDesc.KeyIv, 16);
-		NdisMoveMemory(&Key[16], &pAd->StaCfg.PTK[16], 16);
-		ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, Key, 32);
-		//discard first 256 bytes
-		for(i = 0; i < 256; i++)
-			ARCFOUR_BYTE(&pAd->PrivateInfo.WEPCONTEXT);
-		// Decrypt GTK. Becareful, there is no ICV to check the result is correct or not
-		ARCFOUR_DECRYPT(&pAd->PrivateInfo.WEPCONTEXT, KEYDATA, pMsg3->KeyDesc.KeyData, pMsg3->KeyDesc.KeyDataLen[1]);
-	}
-
-	if (!ParseKeyData(pAd, KEYDATA, pMsg3->KeyDesc.KeyDataLen[1], 1))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Update GTK to ASIC
-	// Update group key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAd,
-						  BSS0,
-						  pAd->StaCfg.DefaultKeyId,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic);
-
-	// Update ASIC WCID attribute table and IVEIV table
-	RTMPAddWcidAttributeEntry(pAd,
-							  BSS0,
-							  pAd->StaCfg.DefaultKeyId,
-							  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-							  NULL);
-
-	// init 802.3 header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero message 4 body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-	Packet.Body_Len[1]  	= sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE;		// No data field
-
-	//
-	// Message 4 as  EAPOL-Key(0,1,0,0,0,P,0,0,MIC,0)
-	//
-	Packet.KeyDesc.Type = WPA2_KEY_DESC;
-
-	// Key descriptor version and appropriate RSN IE
-	Packet.KeyDesc.KeyInfo.KeyDescVer = peerKeyInfo.KeyDescVer;
-
-	// Update Key Length
-	Packet.KeyDesc.KeyLength[0] = pMsg3->KeyDesc.KeyLength[0];
-	Packet.KeyDesc.KeyLength[1] = pMsg3->KeyDesc.KeyLength[1];
-
-	// Key Type PeerKey
-	Packet.KeyDesc.KeyInfo.KeyType = PAIRWISEKEY;
-
-	// KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-	Packet.KeyDesc.KeyInfo.Secure = 1;
-
-	// Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-	// Key Replay count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Out buffer for transmitting message 4
-	MlmeAllocateMemory(pAd, (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		Packet.Body_Len[1] + 4,    &Packet,
-		END_OF_ARGS);
-
-	// Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		HMAC_SHA1(pOutBuffer, FrameLen, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-	// Update PTK
-	// Prepare pair-wise key information into shared key table
-	NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-	pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-    NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, &pAd->StaCfg.PTK[32], LEN_TKIP_EK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, &pAd->StaCfg.PTK[48], LEN_TKIP_RXMICK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, &pAd->StaCfg.PTK[48+LEN_TKIP_RXMICK], LEN_TKIP_TXMICK);
-
-	// Decide its ChiperAlg
-	if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-	else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-	else
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_NONE;
-
-	// Update these related information to MAC_TABLE_ENTRY
-	pEntry = &pAd->MacTab.Content[BSSID_WCID];
-	NdisMoveMemory(&pEntry->PairwiseKey.Key, &pAd->StaCfg.PTK[32], LEN_TKIP_EK);
-	NdisMoveMemory(&pEntry->PairwiseKey.RxMic, &pAd->StaCfg.PTK[48], LEN_TKIP_RXMICK);
-	NdisMoveMemory(&pEntry->PairwiseKey.TxMic, &pAd->StaCfg.PTK[48+LEN_TKIP_RXMICK], LEN_TKIP_TXMICK);
-	pEntry->PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-
-	// Update pairwise key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAd,
-						  BSS0,
-						  0,
-						  pAd->SharedKey[BSS0][0].CipherAlg,
-						  pAd->SharedKey[BSS0][0].Key,
-						  pAd->SharedKey[BSS0][0].TxMic,
-						  pAd->SharedKey[BSS0][0].RxMic);
-
-	// Update ASIC WCID attribute table and IVEIV table
-	RTMPAddWcidAttributeEntry(pAd,
-							  BSS0,
-							  0,
-							  pAd->SharedKey[BSS0][0].CipherAlg,
-							  pEntry);
-
-	// Make  Transmitting frame
-	MakeOutgoingFrame(pOutBuffer,           	&FrameLen,
-			  			LENGTH_802_3,     		&Header802_3,
-						Packet.Body_Len[1] + 4, &Packet,
-						END_OF_ARGS);
-
-
-	// Copy frame to Tx ring and Send Message 4 to authenticator
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, TRUE);
-
-	// set 802.1x port control
-	//pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-	STA_PORT_SECURED(pAd);
-
-    // Indicate Connected for GUI
-    pAd->IndicateMediaState = NdisMediaStateConnected;
-
-	MlmeFreeMemory(pAd, (PUCHAR)pOutBuffer);
-	os_free_mem(pAd, (PUCHAR)mpool);
-
-
-	// send wireless event - for set key done WPA2
-	if (pAd->CommonCfg.bWirelessEvent)
-		RTMPSendWirelessEvent(pAd, IW_SET_KEY_DONE_WPA2_EVENT_FLAG, pEntry->Addr, BSS0, 0);
-
-	DBGPRINT(RT_DEBUG_ERROR, ("Wpa2PairMsg3Action <-----\n"));
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Process Group key 2-way handshaking
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		Elem		Message body
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	WpaGroupMsg1Action(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-
-{
-	PUCHAR              pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG               FrameLen = 0;
-	EAPOL_PACKET        Packet;
-	PEAPOL_PACKET       pGroup;
-	UCHAR               *mpool, *digest, *KEYDATA;
-	UCHAR               Mic[16], OldMic[16];
-	UCHAR               GTK[32], Key[32];
-	KEY_INFO			peerKeyInfo;
-
-	// allocate memory
-	os_alloc_mem(pAd, (PUCHAR *)&mpool, 1024);
-
-	if(mpool == NULL)
-		return;
-
-	// digest Len = 80.
-	digest = (UCHAR *) ROUND_UP(mpool, 4);
-	// KEYDATA Len = 512.
-	KEYDATA = (UCHAR *) ROUND_UP(digest + 80, 4);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaGroupMsg1Action ----->\n"));
-
-	// Process Group Message 1 frame. skip 802.11 header(24) & LLC_SNAP header(8)
-	pGroup = (PEAPOL_PACKET) &Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
-
-	NdisZeroMemory((PUCHAR)&peerKeyInfo, sizeof(peerKeyInfo));
-	NdisMoveMemory((PUCHAR)&peerKeyInfo, (PUCHAR)&pGroup->KeyDesc.KeyInfo, sizeof(KEY_INFO));
-
-	*((USHORT*)&peerKeyInfo) = cpu2le16(*((USHORT*)&peerKeyInfo));
-
-	// 0. Check cipher type match
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled && (peerKeyInfo.KeyDescVer != 2))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-	else if (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled && (peerKeyInfo.KeyDescVer != 1))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// 1. Verify Replay counter
-	//    Check Replay Counter, it has to be larger than last one. No need to be exact one larger
-	if(RTMPCompareMemory(pGroup->KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1)
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Update new replay counter
-	NdisMoveMemory(pAd->StaCfg.ReplayCounter, pGroup->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// 2. Verify MIC is valid
-	// Save the MIC and replace with zero
-	NdisMoveMemory(OldMic, pGroup->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-	NdisZeroMemory(pGroup->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{	// AES
-		HMAC_SHA1((PUCHAR) pGroup, pGroup->Body_Len[1] + 4, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{	// TKIP
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, (PUCHAR) pGroup, pGroup->Body_Len[1] + 4, Mic);
-	}
-
-	if(!NdisEqualMemory(OldMic, Mic, LEN_KEY_DESC_MIC))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, (" MIC Different in group msg 1 of 2-way handshake!!!!!!!!!! \n"));
-		MlmeFreeMemory(pAd, (PUCHAR)mpool);
-		return;
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, (" MIC VALID in group msg 1 of 2-way handshake!!!!!!!!!! \n"));
-
-
-	// 3. Decrypt GTK from Key Data
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// Decrypt AES GTK
-		AES_GTK_KEY_UNWRAP(&pAd->StaCfg.PTK[16], KEYDATA,  pGroup->KeyDesc.KeyDataLen[1], pGroup->KeyDesc.KeyData);
-	}
-	else	// TKIP
-	{
-		INT i;
-
-		// Decrypt TKIP GTK
-		// Construct 32 bytes RC4 Key
-		NdisMoveMemory(Key, pGroup->KeyDesc.KeyIv, 16);
-		NdisMoveMemory(&Key[16], &pAd->StaCfg.PTK[16], 16);
-		ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, Key, 32);
-		//discard first 256 bytes
-		for(i = 0; i < 256; i++)
-			ARCFOUR_BYTE(&pAd->PrivateInfo.WEPCONTEXT);
-		// Decrypt GTK. Becareful, there is no ICV to check the result is correct or not
-		ARCFOUR_DECRYPT(&pAd->PrivateInfo.WEPCONTEXT, KEYDATA, pGroup->KeyDesc.KeyData, pGroup->KeyDesc.KeyDataLen[1]);
-	}
-
-	// Process decrypted key data material
-	// Parse keyData to handle KDE format for WPA2PSK
-	if (peerKeyInfo.EKD_DL)
-	{
-		if (!ParseKeyData(pAd, KEYDATA, pGroup->KeyDesc.KeyDataLen[1], 0))
-		{
-			os_free_mem(pAd, (PUCHAR)mpool);
-			return;
-		}
-	}
-	else	// WPAPSK
-	{
-		// set key material, TxMic and RxMic for WPAPSK
-		NdisMoveMemory(GTK, KEYDATA, 32);
-		NdisMoveMemory(pAd->StaCfg.GTK, GTK, 32);
-		pAd->StaCfg.DefaultKeyId = peerKeyInfo.KeyIndex;
-
-		// Prepare pair-wise key information into shared key table
-		NdisZeroMemory(&pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId], sizeof(CIPHER_KEY));
-		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].KeyLen = LEN_TKIP_EK;
-		NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, GTK, LEN_TKIP_EK);
-		NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, &GTK[16], LEN_TKIP_RXMICK);
-		NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, &GTK[24], LEN_TKIP_TXMICK);
-
-		// Update Shared Key CipherAlg
-		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_NONE;
-		if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_TKIP;
-		else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
-			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_AES;
-		else if (pAd->StaCfg.GroupCipher == Ndis802_11GroupWEP40Enabled)
-			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_WEP64;
-		else if (pAd->StaCfg.GroupCipher == Ndis802_11GroupWEP104Enabled)
-			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_WEP128;
-
-    	//hex_dump("Group Key :", pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, LEN_TKIP_EK);
-	}
-
-	// Update group key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAd,
-						  BSS0,
-						  pAd->StaCfg.DefaultKeyId,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic);
-
-	// Update ASIC WCID attribute table and IVEIV table
-	RTMPAddWcidAttributeEntry(pAd,
-							  BSS0,
-							  pAd->StaCfg.DefaultKeyId,
-							  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-							  NULL);
-
-	// set 802.1x port control
-	//pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-	STA_PORT_SECURED(pAd);
-
-    // Indicate Connected for GUI
-    pAd->IndicateMediaState = NdisMediaStateConnected;
-
-	// init header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero Group message 1 body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE;		// No data field
-
-	//
-	// Group Message 2 as  EAPOL-Key(1,0,0,0,G,0,0,MIC,0)
-	//
-	if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-	{
-		Packet.KeyDesc.Type = WPA2_KEY_DESC;
-	}
-	else
-	{
-		Packet.KeyDesc.Type = WPA1_KEY_DESC;
-	}
-
-	// Key descriptor version and appropriate RSN IE
-	Packet.KeyDesc.KeyInfo.KeyDescVer = peerKeyInfo.KeyDescVer;
-
-	// Update Key Length
-	Packet.KeyDesc.KeyLength[0] = pGroup->KeyDesc.KeyLength[0];
-	Packet.KeyDesc.KeyLength[1] = pGroup->KeyDesc.KeyLength[1];
-
-	// Key Index as G-Msg 1
-	if(pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)
-		Packet.KeyDesc.KeyInfo.KeyIndex = peerKeyInfo.KeyIndex;
-
-	// Key Type Group key
-	Packet.KeyDesc.KeyInfo.KeyType = GROUPKEY;
-
-	// KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-
-	// Secure bit
-	Packet.KeyDesc.KeyInfo.Secure  = 1;
-
-	// Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-	// Key Replay count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pGroup->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Out buffer for transmitting group message 2
-	MlmeAllocateMemory(pAd, (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-	{
-		MlmeFreeMemory(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		Packet.Body_Len[1] + 4,    &Packet,
-		END_OF_ARGS);
-
-	// Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		HMAC_SHA1(pOutBuffer, FrameLen, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-
-	MakeOutgoingFrame(pOutBuffer,       		&FrameLen,
-						LENGTH_802_3,     		&Header802_3,
-						Packet.Body_Len[1] + 4, &Packet,
-						END_OF_ARGS);
-
-
-	// 5. Copy frame to Tx ring and prepare for encryption
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, FALSE);
-
-	// 6 Free allocated memory
-	MlmeFreeMemory(pAd, (PUCHAR)pOutBuffer);
-	os_free_mem(pAd, (PUCHAR)mpool);
-
-	// send wireless event - for set key done WPA2
-	if (pAd->CommonCfg.bWirelessEvent)
-		RTMPSendWirelessEvent(pAd, IW_SET_KEY_DONE_WPA2_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaGroupMsg1Action <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Init WPA MAC header
-
-	Arguments:
-		pAd	Pointer	to our adapter
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	WpaMacHeaderInit(
-	IN		PRTMP_ADAPTER	pAd,
-	IN OUT	PHEADER_802_11	pHdr80211,
-	IN		UCHAR			wep,
-	IN		PUCHAR		    pAddr1)
-{
-	NdisZeroMemory(pHdr80211, sizeof(HEADER_802_11));
-	pHdr80211->FC.Type	= BTYPE_DATA;
-	pHdr80211->FC.ToDs	= 1;
-	if (wep	== 1)
-		pHdr80211->FC.Wep = 1;
-
-	 //	Addr1: BSSID, Addr2: SA, Addr3:	DA
-	COPY_MAC_ADDR(pHdr80211->Addr1, pAddr1);
-	COPY_MAC_ADDR(pHdr80211->Addr2, pAd->CurrentAddress);
-	COPY_MAC_ADDR(pHdr80211->Addr3, pAd->CommonCfg.Bssid);
-	pHdr80211->Sequence =	pAd->Sequence;
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Copy frame from waiting queue into relative ring buffer and set
-	appropriate ASIC register to kick hardware encryption before really
-	sent out to air.
-
-	Arguments:
-		pAd		Pointer	to our adapter
-		PNDIS_PACKET	Pointer to outgoing Ndis frame
-		NumberOfFrag	Number of fragment required
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID    RTMPToWirelessSta(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pHeader802_3,
-    IN  UINT            HdrLen,
-	IN  PUCHAR          pData,
-    IN  UINT            DataLen,
-    IN	BOOLEAN			is4wayFrame)
-
-{
-	NDIS_STATUS     Status;
-	PNDIS_PACKET    pPacket;
-	UCHAR   Index;
-
-	do
-	{
-		// 1. build a NDIS packet and call RTMPSendPacket();
-		//    be careful about how/when to release this internal allocated NDIS PACKET buffer
-		Status = RTMPAllocateNdisPacket(pAd, &pPacket, pHeader802_3, HdrLen, pData, DataLen);
-		if (Status != NDIS_STATUS_SUCCESS)
-			break;
-
-		if (is4wayFrame)
-			RTMP_SET_PACKET_CLEAR_EAP_FRAME(pPacket, 1);
-		else
-			RTMP_SET_PACKET_CLEAR_EAP_FRAME(pPacket, 0);
-
-		// 2. send out the packet
-		Status = STASendPacket(pAd, pPacket);
-		if(Status == NDIS_STATUS_SUCCESS)
-		{
-			// Dequeue one frame from TxSwQueue0..3 queue and process it
-			// There are three place calling dequeue for TX ring.
-			// 1. Here, right after queueing the frame.
-			// 2. At the end of TxRingTxDone service routine.
-			// 3. Upon NDIS call RTMPSendPackets
-			if((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) &&
-				(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)))
-			{
-				for(Index = 0; Index < 5; Index ++)
-					if(pAd->TxSwQueue[Index].Number > 0)
-						RTMPDeQueuePacket(pAd, FALSE, Index, MAX_TX_PROCESS);
-			}
-		}
-	} while(FALSE);
-
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-    Check Sanity RSN IE form AP
-
-    Arguments:
-
-    Return Value:
-
-
-    ========================================================================
-*/
-BOOLEAN CheckRSNIE(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pData,
-	IN  UCHAR           DataLen,
-	OUT	UCHAR			*Offset)
-{
-	PUCHAR              pVIE;
-	UCHAR               len;
-	PEID_STRUCT         pEid;
-	BOOLEAN				result = FALSE;
-
-	pVIE = pData;
-	len	 = DataLen;
-	*Offset = 0;
-
-	while (len > sizeof(RSNIE2))
-	{
-		pEid = (PEID_STRUCT) pVIE;
-		// WPA RSN IE
-		if ((pEid->Eid == IE_WPA) && (NdisEqualMemory(pEid->Octet, WPA_OUI, 4)))
-		{
-			if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA || pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) &&
-				(NdisEqualMemory(pVIE, pAd->MacTab.Content[BSSID_WCID].RSN_IE, pAd->MacTab.Content[BSSID_WCID].RSNIE_Len)) &&
-				(pAd->MacTab.Content[BSSID_WCID].RSNIE_Len == (pEid->Len + 2)))
-			{
-					DBGPRINT(RT_DEBUG_TRACE, ("CheckRSNIE ==> WPA/WPAPSK RSN IE matched in Msg 3, Length(%d) \n", (pEid->Len + 2)));
-					result = TRUE;
-			}
-
-			*Offset += (pEid->Len + 2);
-		}
-		// WPA2 RSN IE
-		else if ((pEid->Eid == IE_RSN) && (NdisEqualMemory(pEid->Octet + 2, RSN_OUI, 3)))
-		{
-			if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2 || pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) &&
-				(NdisEqualMemory(pVIE, pAd->MacTab.Content[BSSID_WCID].RSN_IE, pAd->MacTab.Content[BSSID_WCID].RSNIE_Len)) &&
-				(pAd->MacTab.Content[BSSID_WCID].RSNIE_Len == (pEid->Len + 2)))
-			{
-					DBGPRINT(RT_DEBUG_TRACE, ("CheckRSNIE ==> WPA2/WPA2PSK RSN IE matched in Msg 3, Length(%d) \n", (pEid->Len + 2)));
-					result = TRUE;
-			}
-
-			*Offset += (pEid->Len + 2);
-		}
-		else
-		{
-			break;
-		}
-
-		pVIE += (pEid->Len + 2);
-		len  -= (pEid->Len + 2);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("CheckRSNIE ==> skip_offset(%d) \n", *Offset));
-
-	return result;
-
-}
-
-
-/*
-    ========================================================================
-
-    Routine Description:
-    Parse KEYDATA field.  KEYDATA[] May contain 2 RSN IE and optionally GTK.
-    GTK  is encaptulated in KDE format at  p.83 802.11i D10
-
-    Arguments:
-
-    Return Value:
-
-    Note:
-        802.11i D10
-
-    ========================================================================
-*/
-BOOLEAN ParseKeyData(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pKeyData,
-	IN  UCHAR           KeyDataLen,
-	IN	UCHAR			bPairewise)
-{
-    PKDE_ENCAP          pKDE = NULL;
-    PUCHAR              pMyKeyData = pKeyData;
-    UCHAR               KeyDataLength = KeyDataLen;
-    UCHAR               GTKLEN;
-	UCHAR				skip_offset;
-
-	// Verify The RSN IE contained in Pairewise-Msg 3 and skip it
-	if (bPairewise)
-    {
-		// Check RSN IE whether it is WPA2/WPA2PSK
-		if (!CheckRSNIE(pAd, pKeyData, KeyDataLen, &skip_offset))
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("ParseKeyData ==> WPA2/WPA2PSK RSN IE mismatched \n"));
-			hex_dump("Get KEYDATA :", pKeyData, KeyDataLen);
-			return FALSE;
-    	}
-    	else
-		{
-			// skip RSN IE
-			pMyKeyData += skip_offset;
-			KeyDataLength -= skip_offset;
-
-			//DBGPRINT(RT_DEBUG_TRACE, ("ParseKeyData ==> WPA2/WPA2PSK RSN IE matched in Msg 3, Length(%d) \n", skip_offset));
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("ParseKeyData ==> KeyDataLength %d without RSN_IE \n", KeyDataLength));
-
-	// Parse EKD format
-	if (KeyDataLength >= 8)
-    {
-        pKDE = (PKDE_ENCAP) pMyKeyData;
-    }
-	else
-    {
-		DBGPRINT(RT_DEBUG_ERROR, ("ERROR: KeyDataLength is too short \n"));
-        return FALSE;
-    }
-
-
-	// Sanity check - shared key index should not be 0
-	if (pKDE->GTKEncap.Kid == 0)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("ERROR: GTK Key index zero \n"));
-        return FALSE;
-    }
-
-	// Sanity check - KED length
-	if (KeyDataLength < (pKDE->Len + 2))
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("ERROR: The len from KDE is too short \n"));
-        return FALSE;
-    }
-
-	// Get GTK length - refer to IEEE 802.11i-2004 p.82
-	GTKLEN = pKDE->Len -6;
-
-	if (GTKLEN < MIN_LEN_OF_GTK)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("ERROR: GTK Key length is too short (%d) \n", GTKLEN));
-        return FALSE;
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, ("GTK Key with KDE formet got index=%d, len=%d \n", pKDE->GTKEncap.Kid, GTKLEN));
-
-	// Update GTK
-	// set key material, TxMic and RxMic for WPAPSK
-	NdisMoveMemory(pAd->StaCfg.GTK, pKDE->GTKEncap.GTK, 32);
-	pAd->StaCfg.DefaultKeyId = pKDE->GTKEncap.Kid;
-
-	// Update shared key table
-	NdisZeroMemory(&pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId], sizeof(CIPHER_KEY));
-	pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].KeyLen = LEN_TKIP_EK;
-	NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, pKDE->GTKEncap.GTK, LEN_TKIP_EK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, &pKDE->GTKEncap.GTK[16], LEN_TKIP_RXMICK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, &pKDE->GTKEncap.GTK[24], LEN_TKIP_TXMICK);
-
-	// Update Shared Key CipherAlg
-	pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_NONE;
-	if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_TKIP;
-	else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
-		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_AES;
-	else if (pAd->StaCfg.GroupCipher == Ndis802_11GroupWEP40Enabled)
-		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_WEP64;
-	else if (pAd->StaCfg.GroupCipher == Ndis802_11GroupWEP104Enabled)
-		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_WEP128;
-
-	return TRUE;
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Cisco CCKM PRF function
-
-	Arguments:
-		key				Cisco Base Transient Key (BTK)
-		key_len			The key length of the BTK
-		data			Ruquest Number(RN) + BSSID
-		data_len		The length of the data
-		output			Store for PTK(Pairwise transient keys)
-		len				The length of the output
-	Return Value:
-		None
-
-	Note:
-		802.1i	Annex F.9
-
-	========================================================================
-*/
-VOID CCKMPRF(
-	IN	UCHAR	*key,
-	IN	INT		key_len,
-	IN	UCHAR	*data,
-	IN	INT		data_len,
-	OUT	UCHAR	*output,
-	IN	INT		len)
-{
-	INT		i;
-	UCHAR	input[1024];
-	INT		currentindex = 0;
-	INT		total_len;
-
-	NdisMoveMemory(input, data, data_len);
-	total_len = data_len;
-	input[total_len] = 0;
-	total_len++;
-	for	(i = 0;	i <	(len + 19) / 20; i++)
-	{
-		HMAC_SHA1(input, total_len,	key, key_len, &output[currentindex]);
-		currentindex +=	20;
-		input[total_len - 1]++;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Process MIC error indication and record MIC error timer.
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pWpaKey 		Pointer to the WPA key structure
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPReportMicError(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PCIPHER_KEY 	pWpaKey)
-{
-	ULONG	Now;
-    UCHAR   unicastKey = (pWpaKey->Type == PAIRWISE_KEY ? 1:0);
-
-	// Record Last MIC error time and count
-	Now = jiffies;
-	if (pAd->StaCfg.MicErrCnt == 0)
-	{
-		pAd->StaCfg.MicErrCnt++;
-		pAd->StaCfg.LastMicErrorTime = Now;
-        NdisZeroMemory(pAd->StaCfg.ReplayCounter, 8);
-	}
-	else if (pAd->StaCfg.MicErrCnt == 1)
-	{
-		if ((pAd->StaCfg.LastMicErrorTime + (60 * OS_HZ)) < Now)
-		{
-			// Update Last MIC error time, this did not violate two MIC errors within 60 seconds
-			pAd->StaCfg.LastMicErrorTime = Now;
-		}
-		else
-		{
-
-			if (pAd->CommonCfg.bWirelessEvent)
-				RTMPSendWirelessEvent(pAd, IW_COUNTER_MEASURES_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-
-			pAd->StaCfg.LastMicErrorTime = Now;
-			// Violate MIC error counts, MIC countermeasures kicks in
-			pAd->StaCfg.MicErrCnt++;
-			// We shall block all reception
-			// We shall clean all Tx ring and disassoicate from AP after next EAPOL frame
-			//
-			// No necessary to clean all Tx ring, on RTMPHardTransmit will stop sending non-802.1X EAPOL packets
-			// if pAd->StaCfg.MicErrCnt greater than 2.
-			//
-			// RTMPRingCleanUp(pAd, QID_AC_BK);
-			// RTMPRingCleanUp(pAd, QID_AC_BE);
-			// RTMPRingCleanUp(pAd, QID_AC_VI);
-			// RTMPRingCleanUp(pAd, QID_AC_VO);
-			// RTMPRingCleanUp(pAd, QID_HCCA);
-		}
-	}
-	else
-	{
-		// MIC error count >= 2
-		// This should not happen
-		;
-	}
-    MlmeEnqueue(pAd,
-				MLME_CNTL_STATE_MACHINE,
-				OID_802_11_MIC_FAILURE_REPORT_FRAME,
-				1,
-				&unicastKey);
-
-    if (pAd->StaCfg.MicErrCnt == 2)
-    {
-        RTMPSetTimer(&pAd->StaCfg.WpaDisassocAndBlockAssocTimer, 100);
-    }
-}
-
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#define	LENGTH_EAP_H    4
-// If the received frame is EAP-Packet ,find out its EAP-Code (Request(0x01), Response(0x02), Success(0x03), Failure(0x04)).
-INT	    WpaCheckEapCode(
-	IN  PRTMP_ADAPTER   		pAd,
-	IN  PUCHAR				pFrame,
-	IN  USHORT				FrameLen,
-	IN  USHORT				OffSet)
-{
-
-	PUCHAR	pData;
-	INT	result = 0;
-
-	if( FrameLen < OffSet + LENGTH_EAPOL_H + LENGTH_EAP_H )
-		return result;
-
-	pData = pFrame + OffSet; // skip offset bytes
-
-	if(*(pData+1) == EAPPacket) 	// 802.1x header - Packet Type
-	{
-		 result = *(pData+4);		// EAP header - Code
-	}
-
-	return result;
-}
-
-VOID    WpaSendMicFailureToWpaSupplicant(
-    IN  PRTMP_ADAPTER    pAd,
-    IN  BOOLEAN          bUnicast)
-{
-    union iwreq_data    wrqu;
-    char custom[IW_CUSTOM_MAX] = {0};
-
-    sprintf(custom, "MLME-MICHAELMICFAILURE.indication");
-    if (bUnicast)
-        sprintf(custom, "%s unicast", custom);
-    wrqu.data.length = strlen(custom);
-    wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, custom);
-
-    return;
-}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-VOID	WpaMicFailureReportFrame(
-	IN  PRTMP_ADAPTER   pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR              pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG               FrameLen = 0;
-	EAPOL_PACKET        Packet;
-	UCHAR               Mic[16];
-    BOOLEAN             bUnicast;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaMicFailureReportFrame ----->\n"));
-
-    bUnicast = (Elem->Msg[0] == 1 ? TRUE:FALSE);
-	pAd->Sequence = ((pAd->Sequence) + 1) & (MAX_SEQ_NUMBER);
-
-	// init 802.3 header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-
-	Packet.KeyDesc.Type = WPA1_KEY_DESC;
-
-    // Request field presented
-    Packet.KeyDesc.KeyInfo.Request = 1;
-
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 2;
-	}
-	else	  // TKIP
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 1;
-	}
-
-    Packet.KeyDesc.KeyInfo.KeyType = (bUnicast ? PAIRWISEKEY : GROUPKEY);
-
-	// KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-
-    // Error field presented
-	Packet.KeyDesc.KeyInfo.Error  = 1;
-
-	// Update packet length after decide Key data payload
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE;
-
-	// Key Replay Count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY);
-    inc_byte_array(pAd->StaCfg.ReplayCounter, 8);
-
-	// Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-
-	MlmeAllocateMemory(pAd, (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-	{
-		return;
-	}
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-		              Packet.Body_Len[1] + 4,   &Packet,
-		              END_OF_ARGS);
-
-	// Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{	// AES
-        UCHAR digest[20] = {0};
-		HMAC_SHA1(pOutBuffer, FrameLen, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{	// TKIP
-		hmac_md5(pAd->StaCfg.PTK,  LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-    MakeOutgoingFrame(pOutBuffer,           	&FrameLen,
-    	  			LENGTH_802_3,     			&Header802_3,
-    				Packet.Body_Len[1] + 4,     &Packet,
-    				END_OF_ARGS);
-
-	// opy frame to Tx ring and send MIC failure report frame to authenticator
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, FALSE);
-
-	MlmeFreeMemory(pAd, (PUCHAR)pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaMicFailureReportFrame <-----\n"));
-}
-
-/** from wpa_supplicant
- * inc_byte_array - Increment arbitrary length byte array by one
- * @counter: Pointer to byte array
- * @len: Length of the counter in bytes
- *
- * This function increments the last byte of the counter by one and continues
- * rolling over to more significant bytes if the byte was incremented from
- * 0xff to 0x00.
- */
-void inc_byte_array(UCHAR *counter, int len)
-{
-	int pos = len - 1;
-	while (pos >= 0) {
-		counter[pos]++;
-		if (counter[pos] != 0)
-			break;
-		pos--;
-	}
-}
-
-VOID WpaDisassocApAndBlockAssoc(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3)
-{
-    RTMP_ADAPTER                *pAd = (PRTMP_ADAPTER)FunctionContext;
-    MLME_DISASSOC_REQ_STRUCT    DisassocReq;
-
-	// disassoc from current AP first
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPReportMicError - disassociate with current AP after sending second continuous EAPOL frame\n"));
-	DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_MIC_FAILURE);
-	MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ, sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-
-	pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
-	pAd->StaCfg.bBlockAssoc = TRUE;
-}
-
+#include "../../rt2860/sta/wpa.c"
diff --git a/drivers/staging/rt2870/sta_ioctl.c b/drivers/staging/rt2870/sta_ioctl.c
index 4b432ce..3553a6c 100644
--- a/drivers/staging/rt2870/sta_ioctl.c
+++ b/drivers/staging/rt2870/sta_ioctl.c
@@ -1,7068 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    sta_ioctl.c
-
-    Abstract:
-    IOCTL related subroutines
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Rory Chen   01-03-2003    created
-	Rory Chen   02-14-2005    modify to support RT61
-*/
-
-#include	"rt_config.h"
-
-#ifdef DBG
-extern ULONG    RTDebugLevel;
-#endif
-
-#define NR_WEP_KEYS 				4
-#define WEP_SMALL_KEY_LEN 			(40/8)
-#define WEP_LARGE_KEY_LEN 			(104/8)
-
-#define GROUP_KEY_NO                4
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
-#define IWE_STREAM_ADD_EVENT(_A, _B, _C, _D, _E)		iwe_stream_add_event(_A, _B, _C, _D, _E)
-#define IWE_STREAM_ADD_POINT(_A, _B, _C, _D, _E)		iwe_stream_add_point(_A, _B, _C, _D, _E)
-#define IWE_STREAM_ADD_VALUE(_A, _B, _C, _D, _E, _F)	iwe_stream_add_value(_A, _B, _C, _D, _E, _F)
-#else
-#define IWE_STREAM_ADD_EVENT(_A, _B, _C, _D, _E)		iwe_stream_add_event(_B, _C, _D, _E)
-#define IWE_STREAM_ADD_POINT(_A, _B, _C, _D, _E)		iwe_stream_add_point(_B, _C, _D, _E)
-#define IWE_STREAM_ADD_VALUE(_A, _B, _C, _D, _E, _F)	iwe_stream_add_value(_B, _C, _D, _E, _F)
-#endif
-
-extern UCHAR    CipherWpa2Template[];
-extern UCHAR    CipherWpaPskTkip[];
-extern UCHAR    CipherWpaPskTkipLen;
-
-typedef struct PACKED _RT_VERSION_INFO{
-    UCHAR       DriverVersionW;
-    UCHAR       DriverVersionX;
-    UCHAR       DriverVersionY;
-    UCHAR       DriverVersionZ;
-    UINT        DriverBuildYear;
-    UINT        DriverBuildMonth;
-    UINT        DriverBuildDay;
-} RT_VERSION_INFO, *PRT_VERSION_INFO;
-
-struct iw_priv_args privtab[] = {
-{ RTPRIV_IOCTL_SET,
-  IW_PRIV_TYPE_CHAR | 1024, 0,
-  "set"},
-
-{ RTPRIV_IOCTL_SHOW, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  ""},
-{ RTPRIV_IOCTL_SHOW, IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  ""},
-/* --- sub-ioctls definitions --- */
-    { SHOW_CONN_STATUS,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "connStatus" },
-	{ SHOW_DRVIER_VERION,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "driverVer" },
-    { SHOW_BA_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "bainfo" },
-	{ SHOW_DESC_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "descinfo" },
-    { RAIO_OFF,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "radio_off" },
-	{ RAIO_ON,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "radio_on" },
-#ifdef QOS_DLS_SUPPORT
-	{ SHOW_DLS_ENTRY_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "dlsentryinfo" },
-#endif // QOS_DLS_SUPPORT //
-	{ SHOW_CFG_VALUE,
-	  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "show" },
-	{ SHOW_ADHOC_ENTRY_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "adhocEntry" },
-
-/* --- sub-ioctls relations --- */
-
-#ifdef DBG
-{ RTPRIV_IOCTL_BBP,
-  IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  "bbp"},
-{ RTPRIV_IOCTL_MAC,
-  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | 1024,
-  "mac"},
-{ RTPRIV_IOCTL_E2P,
-  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | 1024,
-  "e2p"},
-#endif  /* DBG */
-
-{ RTPRIV_IOCTL_STATISTICS,
-  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  "stat"},
-{ RTPRIV_IOCTL_GSITESURVEY,
-  0, IW_PRIV_TYPE_CHAR | 1024,
-  "get_site_survey"},
-};
-
-INT Set_SSID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef WMM_SUPPORT
-INT	Set_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif
-
-INT Set_NetworkType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_AuthMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_EncrypType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_DefaultKeyID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key1_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key2_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key3_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key4_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_WPAPSK_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-
-INT Set_PSMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-INT Set_Wpa_Support(
-    IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef DBG
-VOID RTMPIoctlBBP(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID RTMPIoctlMAC(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID RTMPIoctlE2PROM(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  struct iwreq    *wrq);
-#endif // DBG //
-
-
-NDIS_STATUS RTMPWPANoneAddKeyProc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN	PVOID			pBuf);
-
-INT Set_FragTest_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef DOT11_N_SUPPORT
-INT Set_TGnWifiTest_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg);
-#endif // DOT11_N_SUPPORT //
-
-INT Set_LongRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg);
-
-INT Set_ShortRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg);
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-INT Set_Ieee80211dClientMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef CARRIER_DETECTION_SUPPORT
-INT Set_CarrierDetect_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg);
-#endif // CARRIER_DETECTION_SUPPORT //
-
-INT	Show_Adhoc_MacTable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PCHAR			extra);
-
-static struct {
-	CHAR *name;
-	INT (*set_proc)(PRTMP_ADAPTER pAdapter, PUCHAR arg);
-} *PRTMP_PRIVATE_SET_PROC, RTMP_PRIVATE_SUPPORT_PROC[] = {
-	{"DriverVersion",				Set_DriverVersion_Proc},
-	{"CountryRegion",				Set_CountryRegion_Proc},
-	{"CountryRegionABand",			Set_CountryRegionABand_Proc},
-	{"SSID",						Set_SSID_Proc},
-	{"WirelessMode",				Set_WirelessMode_Proc},
-	{"TxBurst",					Set_TxBurst_Proc},
-	{"TxPreamble",				Set_TxPreamble_Proc},
-	{"TxPower",					Set_TxPower_Proc},
-	{"Channel",					Set_Channel_Proc},
-	{"BGProtection",				Set_BGProtection_Proc},
-	{"RTSThreshold",				Set_RTSThreshold_Proc},
-	{"FragThreshold",				Set_FragThreshold_Proc},
-#ifdef DOT11_N_SUPPORT
-	{"HtBw",		                Set_HtBw_Proc},
-	{"HtMcs",		                Set_HtMcs_Proc},
-	{"HtGi",		                Set_HtGi_Proc},
-	{"HtOpMode",		            Set_HtOpMode_Proc},
-	{"HtExtcha",		            Set_HtExtcha_Proc},
-	{"HtMpduDensity",		        Set_HtMpduDensity_Proc},
-	{"HtBaWinSize",		        	Set_HtBaWinSize_Proc},
-	{"HtRdg",		        		Set_HtRdg_Proc},
-	{"HtAmsdu",		        		Set_HtAmsdu_Proc},
-	{"HtAutoBa",		        	Set_HtAutoBa_Proc},
-	{"HtBaDecline",					Set_BADecline_Proc},
-	{"HtProtect",		        	Set_HtProtect_Proc},
-	{"HtMimoPs",		        	Set_HtMimoPs_Proc},
-#endif // DOT11_N_SUPPORT //
-
-#ifdef AGGREGATION_SUPPORT
-	{"PktAggregate",				Set_PktAggregate_Proc},
-#endif
-
-#ifdef WMM_SUPPORT
-	{"WmmCapable",					Set_WmmCapable_Proc},
-#endif
-	{"IEEE80211H",					Set_IEEE80211H_Proc},
-    {"NetworkType",                 Set_NetworkType_Proc},
-	{"AuthMode",					Set_AuthMode_Proc},
-	{"EncrypType",					Set_EncrypType_Proc},
-	{"DefaultKeyID",				Set_DefaultKeyID_Proc},
-	{"Key1",						Set_Key1_Proc},
-	{"Key2",						Set_Key2_Proc},
-	{"Key3",						Set_Key3_Proc},
-	{"Key4",						Set_Key4_Proc},
-	{"WPAPSK",						Set_WPAPSK_Proc},
-	{"ResetCounter",				Set_ResetStatCounter_Proc},
-	{"PSMode",                      Set_PSMode_Proc},
-#ifdef DBG
-	{"Debug",						Set_Debug_Proc},
-#endif
-
-#ifdef RALINK_ATE
-	{"ATE",							Set_ATE_Proc},
-	{"ATEDA",						Set_ATE_DA_Proc},
-	{"ATESA",						Set_ATE_SA_Proc},
-	{"ATEBSSID",					Set_ATE_BSSID_Proc},
-	{"ATECHANNEL",					Set_ATE_CHANNEL_Proc},
-	{"ATETXPOW0",					Set_ATE_TX_POWER0_Proc},
-	{"ATETXPOW1",					Set_ATE_TX_POWER1_Proc},
-	{"ATETXANT",					Set_ATE_TX_Antenna_Proc},
-	{"ATERXANT",					Set_ATE_RX_Antenna_Proc},
-	{"ATETXFREQOFFSET",				Set_ATE_TX_FREQOFFSET_Proc},
-	{"ATETXBW",						Set_ATE_TX_BW_Proc},
-	{"ATETXLEN",					Set_ATE_TX_LENGTH_Proc},
-	{"ATETXCNT",					Set_ATE_TX_COUNT_Proc},
-	{"ATETXMCS",					Set_ATE_TX_MCS_Proc},
-	{"ATETXMODE",					Set_ATE_TX_MODE_Proc},
-	{"ATETXGI",						Set_ATE_TX_GI_Proc},
-	{"ATERXFER",					Set_ATE_RX_FER_Proc},
-	{"ATERRF",						Set_ATE_Read_RF_Proc},
-	{"ATEWRF1",						Set_ATE_Write_RF1_Proc},
-	{"ATEWRF2",						Set_ATE_Write_RF2_Proc},
-	{"ATEWRF3",						Set_ATE_Write_RF3_Proc},
-	{"ATEWRF4",						Set_ATE_Write_RF4_Proc},
-	{"ATELDE2P",				    Set_ATE_Load_E2P_Proc},
-	{"ATERE2P",						Set_ATE_Read_E2P_Proc},
-	{"ATESHOW",						Set_ATE_Show_Proc},
-	{"ATEHELP",						Set_ATE_Help_Proc},
-
-#ifdef RALINK_28xx_QA
-	{"TxStop",						Set_TxStop_Proc},
-	{"RxStop",						Set_RxStop_Proc},
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-    {"WpaSupport",                  Set_Wpa_Support},
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-
-	{"FixedTxMode",                 Set_FixedTxMode_Proc},
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	{"OpMode",						Set_OpMode_Proc},
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-#ifdef DOT11_N_SUPPORT
-    {"TGnWifiTest",                 Set_TGnWifiTest_Proc},
-    {"ForceGF",		        		Set_ForceGF_Proc},
-#endif // DOT11_N_SUPPORT //
-#ifdef QOS_DLS_SUPPORT
-	{"DlsAddEntry",					Set_DlsAddEntry_Proc},
-	{"DlsTearDownEntry",			Set_DlsTearDownEntry_Proc},
-#endif // QOS_DLS_SUPPORT //
-	{"LongRetry",	        		Set_LongRetryLimit_Proc},
-	{"ShortRetry",	        		Set_ShortRetryLimit_Proc},
-#ifdef EXT_BUILD_CHANNEL_LIST
-	{"11dClientMode",				Set_Ieee80211dClientMode_Proc},
-#endif // EXT_BUILD_CHANNEL_LIST //
-#ifdef CARRIER_DETECTION_SUPPORT
-	{"CarrierDetect",				Set_CarrierDetect_Proc},
-#endif // CARRIER_DETECTION_SUPPORT //
-
-	{NULL,}
-};
-
-
-VOID RTMPAddKey(
-	IN	PRTMP_ADAPTER	    pAd,
-	IN	PNDIS_802_11_KEY    pKey)
-{
-	ULONG				KeyIdx;
-	MAC_TABLE_ENTRY  	*pEntry;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("RTMPAddKey ------>\n"));
-
-	if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-	{
-		if (pKey->KeyIndex & 0x80000000)
-		{
-		    if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-            {
-                NdisZeroMemory(pAd->StaCfg.PMK, 32);
-                NdisMoveMemory(pAd->StaCfg.PMK, pKey->KeyMaterial, pKey->KeyLength);
-                goto end;
-            }
-		    // Update PTK
-		    NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-            pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-            NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, pKey->KeyMaterial, LEN_TKIP_EK);
-#ifdef WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-            {
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-            else
-#endif // WPA_SUPPLICANT_SUPPORT //
-            {
-            	NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-
-            // Decide its ChiperAlg
-        	if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-        	else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-        	else
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_NONE;
-
-            // Update these related information to MAC_TABLE_ENTRY
-        	pEntry = &pAd->MacTab.Content[BSSID_WCID];
-            NdisMoveMemory(pEntry->PairwiseKey.Key, pAd->SharedKey[BSS0][0].Key, LEN_TKIP_EK);
-        	NdisMoveMemory(pEntry->PairwiseKey.RxMic, pAd->SharedKey[BSS0][0].RxMic, LEN_TKIP_RXMICK);
-        	NdisMoveMemory(pEntry->PairwiseKey.TxMic, pAd->SharedKey[BSS0][0].TxMic, LEN_TKIP_TXMICK);
-        	pEntry->PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-
-        	// Update pairwise key information to ASIC Shared Key Table
-        	AsicAddSharedKeyEntry(pAd,
-        						  BSS0,
-        						  0,
-        						  pAd->SharedKey[BSS0][0].CipherAlg,
-        						  pAd->SharedKey[BSS0][0].Key,
-        						  pAd->SharedKey[BSS0][0].TxMic,
-        						  pAd->SharedKey[BSS0][0].RxMic);
-
-        	// Update ASIC WCID attribute table and IVEIV table
-        	RTMPAddWcidAttributeEntry(pAd,
-        							  BSS0,
-        							  0,
-        							  pAd->SharedKey[BSS0][0].CipherAlg,
-        							  pEntry);
-
-            if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-            {
-                // set 802.1x port control
-	            //pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAd);
-
-                // Indicate Connected for GUI
-                pAd->IndicateMediaState = NdisMediaStateConnected;
-            }
-		}
-        else
-        {
-            // Update GTK
-            pAd->StaCfg.DefaultKeyId = (pKey->KeyIndex & 0xFF);
-            NdisZeroMemory(&pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId], sizeof(CIPHER_KEY));
-            pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].KeyLen = LEN_TKIP_EK;
-            NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, pKey->KeyMaterial, LEN_TKIP_EK);
-#ifdef WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-            {
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-            else
-#endif // WPA_SUPPLICANT_SUPPORT //
-            {
-            	NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-
-            // Update Shared Key CipherAlg
-    		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_NONE;
-    		if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-    			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_TKIP;
-    		else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
-    			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_AES;
-
-            // Update group key information to ASIC Shared Key Table
-        	AsicAddSharedKeyEntry(pAd,
-        						  BSS0,
-        						  pAd->StaCfg.DefaultKeyId,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic);
-
-        	// Update ASIC WCID attribute table and IVEIV table
-        	RTMPAddWcidAttributeEntry(pAd,
-        							  BSS0,
-        							  pAd->StaCfg.DefaultKeyId,
-        							  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-        							  NULL);
-
-            // set 802.1x port control
-	        //pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-			STA_PORT_SECURED(pAd);
-
-            // Indicate Connected for GUI
-            pAd->IndicateMediaState = NdisMediaStateConnected;
-        }
-	}
-	else	// dynamic WEP from wpa_supplicant
-	{
-		UCHAR	CipherAlg;
-    	PUCHAR	Key;
-
-		if(pKey->KeyLength == 32)
-			goto end;
-
-		KeyIdx = pKey->KeyIndex & 0x0fffffff;
-
-		if (KeyIdx < 4)
-		{
-			// it is a default shared key, for Pairwise key setting
-			if (pKey->KeyIndex & 0x80000000)
-			{
-				pEntry = MacTableLookup(pAd, pKey->BSSID);
-
-				if (pEntry)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("RTMPAddKey: Set Pair-wise Key\n"));
-
-					// set key material and key length
- 					pEntry->PairwiseKey.KeyLen = (UCHAR)pKey->KeyLength;
-					NdisMoveMemory(pEntry->PairwiseKey.Key, &pKey->KeyMaterial, pKey->KeyLength);
-
-					// set Cipher type
-					if (pKey->KeyLength == 5)
-						pEntry->PairwiseKey.CipherAlg = CIPHER_WEP64;
-					else
-						pEntry->PairwiseKey.CipherAlg = CIPHER_WEP128;
-
-					// Add Pair-wise key to Asic
-					AsicAddPairwiseKeyEntry(
-						pAd,
-						pEntry->Addr,
-						(UCHAR)pEntry->Aid,
-                		&pEntry->PairwiseKey);
-
-					// update WCID attribute table and IVEIV table for this entry
-					RTMPAddWcidAttributeEntry(
-						pAd,
-						BSS0,
-						KeyIdx, // The value may be not zero
-						pEntry->PairwiseKey.CipherAlg,
-						pEntry);
-
-				}
-			}
-			else
-            {
-				// Default key for tx (shared key)
-				pAd->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-
-				// set key material and key length
-				pAd->SharedKey[BSS0][KeyIdx].KeyLen = (UCHAR) pKey->KeyLength;
-				NdisMoveMemory(pAd->SharedKey[BSS0][KeyIdx].Key, &pKey->KeyMaterial, pKey->KeyLength);
-
-				// Set Ciper type
-				if (pKey->KeyLength == 5)
-					pAd->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_WEP64;
-				else
-					pAd->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_WEP128;
-
-    			CipherAlg = pAd->SharedKey[BSS0][KeyIdx].CipherAlg;
-    			Key = pAd->SharedKey[BSS0][KeyIdx].Key;
-
-				// Set Group key material to Asic
-    			AsicAddSharedKeyEntry(pAd, BSS0, KeyIdx, CipherAlg, Key, NULL, NULL);
-
-				// Update WCID attribute table and IVEIV table for this group key table
-				RTMPAddWcidAttributeEntry(pAd, BSS0, KeyIdx, CipherAlg, NULL);
-
-			}
-		}
-	}
-end:
-	return;
-}
-
-char * rtstrchr(const char * s, int c)
-{
-    for(; *s != (char) c; ++s)
-        if (*s == '\0')
-            return NULL;
-    return (char *) s;
-}
-
-/*
-This is required for LinEX2004/kernel2.6.7 to provide iwlist scanning function
-*/
-
-int
-rt_ioctl_giwname(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-//	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-#ifdef RT2870
-	strncpy(name, "RT2870 Wireless", IFNAMSIZ);
-#endif // RT2870 //
-	return 0;
-}
-
-int rt_ioctl_siwfreq(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_freq *freq, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-	int 	chan = -1;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-
-	if (freq->e > 1)
-		return -EINVAL;
-
-	if((freq->e == 0) && (freq->m <= 1000))
-		chan = freq->m;	// Setting by channel number
-	else
-		MAP_KHZ_TO_CHANNEL_ID( (freq->m /100) , chan); // Setting by frequency - search the table , like 2.412G, 2.422G,
-
-    if (ChannelSanity(pAdapter, chan) == TRUE)
-    {
-	pAdapter->CommonCfg.Channel = chan;
-	DBGPRINT(RT_DEBUG_ERROR, ("==>rt_ioctl_siwfreq::SIOCSIWFREQ[cmd=0x%x] (Channel=%d)\n", SIOCSIWFREQ, pAdapter->CommonCfg.Channel));
-    }
-    else
-        return -EINVAL;
-
-	return 0;
-}
-int rt_ioctl_giwfreq(struct net_device *dev,
-		   struct iw_request_info *info,
-		   struct iw_freq *freq, char *extra)
-{
-    VIRTUAL_ADAPTER *pVirtualAd = NULL;
-	PRTMP_ADAPTER pAdapter = NULL;
-	UCHAR ch;
-	ULONG	m;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-		ch = pAdapter->CommonCfg.Channel;
-
-	DBGPRINT(RT_DEBUG_TRACE,("==>rt_ioctl_giwfreq  %d\n", ch));
-
-    MAP_CHANNEL_ID_TO_KHZ(ch, m);
-	freq->m = m * 100;
-	freq->e = 1;
-	return 0;
-}
-
-int rt_ioctl_siwmode(struct net_device *dev,
-		   struct iw_request_info *info,
-		   __u32 *mode, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-    	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	switch (*mode)
-	{
-		case IW_MODE_ADHOC:
-			Set_NetworkType_Proc(pAdapter, "Adhoc");
-			break;
-		case IW_MODE_INFRA:
-			Set_NetworkType_Proc(pAdapter, "Infra");
-			break;
-#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20))
-        case IW_MODE_MONITOR:
-			Set_NetworkType_Proc(pAdapter, "Monitor");
-			break;
-#endif
-		default:
-			DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_siwmode::SIOCSIWMODE (unknown %d)\n", *mode));
-			return -EINVAL;
-	}
-
-	// Reset Ralink supplicant to not use, it will be set to start when UI set PMK key
-	pAdapter->StaCfg.WpaState = SS_NOTUSE;
-
-	return 0;
-}
-
-int rt_ioctl_giwmode(struct net_device *dev,
-		   struct iw_request_info *info,
-		   __u32 *mode, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	if (ADHOC_ON(pAdapter))
-		*mode = IW_MODE_ADHOC;
-    else if (INFRA_ON(pAdapter))
-		*mode = IW_MODE_INFRA;
-#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20))
-    else if (MONITOR_ON(pAdapter))
-    {
-        *mode = IW_MODE_MONITOR;
-    }
-#endif
-    else
-        *mode = IW_MODE_AUTO;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==>rt_ioctl_giwmode(mode=%d)\n", *mode));
-	return 0;
-}
-
-int rt_ioctl_siwsens(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-        	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	return 0;
-}
-
-int rt_ioctl_giwsens(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-	return 0;
-}
-
-int rt_ioctl_giwrange(struct net_device *dev,
-		   struct iw_request_info *info,
-		   struct iw_point *data, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-	struct iw_range *range = (struct iw_range *) extra;
-	u16 val;
-	int i;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===>rt_ioctl_giwrange\n"));
-	data->length = sizeof(struct iw_range);
-	memset(range, 0, sizeof(struct iw_range));
-
-	range->txpower_capa = IW_TXPOW_DBM;
-
-	if (INFRA_ON(pAdapter)||ADHOC_ON(pAdapter))
-	{
-		range->min_pmp = 1 * 1024;
-		range->max_pmp = 65535 * 1024;
-		range->min_pmt = 1 * 1024;
-		range->max_pmt = 1000 * 1024;
-		range->pmp_flags = IW_POWER_PERIOD;
-		range->pmt_flags = IW_POWER_TIMEOUT;
-		range->pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT |
-			IW_POWER_UNICAST_R | IW_POWER_ALL_R;
-	}
-
-	range->we_version_compiled = WIRELESS_EXT;
-	range->we_version_source = 14;
-
-	range->retry_capa = IW_RETRY_LIMIT;
-	range->retry_flags = IW_RETRY_LIMIT;
-	range->min_retry = 0;
-	range->max_retry = 255;
-
-	range->num_channels =  pAdapter->ChannelListNum;
-
-	val = 0;
-	for (i = 1; i <= range->num_channels; i++)
-	{
-		u32 m;
-		range->freq[val].i = pAdapter->ChannelList[i-1].Channel;
-		MAP_CHANNEL_ID_TO_KHZ(pAdapter->ChannelList[i-1].Channel, m);
-		range->freq[val].m = m * 100; /* HZ */
-
-		range->freq[val].e = 1;
-		val++;
-		if (val == IW_MAX_FREQUENCIES)
-			break;
-	}
-	range->num_frequency = val;
-
-	range->max_qual.qual = 100; /* what is correct max? This was not
-					* documented exactly. At least
-					* 69 has been observed. */
-	range->max_qual.level = 0; /* dB */
-	range->max_qual.noise = 0; /* dB */
-
-	/* What would be suitable values for "average/typical" qual? */
-	range->avg_qual.qual = 20;
-	range->avg_qual.level = -60;
-	range->avg_qual.noise = -95;
-	range->sensitivity = 3;
-
-	range->max_encoding_tokens = NR_WEP_KEYS;
-	range->num_encoding_sizes = 2;
-	range->encoding_size[0] = 5;
-	range->encoding_size[1] = 13;
-
-	range->min_rts = 0;
-	range->max_rts = 2347;
-	range->min_frag = 256;
-	range->max_frag = 2346;
-
-#if WIRELESS_EXT > 17
-	/* IW_ENC_CAPA_* bit field */
-	range->enc_capa = IW_ENC_CAPA_WPA | IW_ENC_CAPA_WPA2 |
-					IW_ENC_CAPA_CIPHER_TKIP | IW_ENC_CAPA_CIPHER_CCMP;
-#endif
-
-	return 0;
-}
-
-int rt_ioctl_siwap(struct net_device *dev,
-		      struct iw_request_info *info,
-		      struct sockaddr *ap_addr, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-    NDIS_802_11_MAC_ADDRESS Bssid;
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-    {
-        RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-        DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-    }
-
-    // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-    // this request, because this request is initiated by NDIS.
-    pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-	// Prevent to connect AP again in STAMlmePeriodicExec
-	pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-
-    memset(Bssid, 0, MAC_ADDR_LEN);
-    memcpy(Bssid, ap_addr->sa_data, MAC_ADDR_LEN);
-    MlmeEnqueue(pAdapter,
-                MLME_CNTL_STATE_MACHINE,
-                OID_802_11_BSSID,
-                sizeof(NDIS_802_11_MAC_ADDRESS),
-                (VOID *)&Bssid);
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCSIWAP %02x:%02x:%02x:%02x:%02x:%02x\n",
-        Bssid[0], Bssid[1], Bssid[2], Bssid[3], Bssid[4], Bssid[5]));
-
-	return 0;
-}
-
-int rt_ioctl_giwap(struct net_device *dev,
-		      struct iw_request_info *info,
-		      struct sockaddr *ap_addr, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-	{
-		ap_addr->sa_family = ARPHRD_ETHER;
-		memcpy(ap_addr->sa_data, &pAdapter->CommonCfg.Bssid, ETH_ALEN);
-	}
-#ifdef WPA_SUPPLICANT_SUPPORT
-    // Add for RT2870
-    else if (pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-    {
-        ap_addr->sa_family = ARPHRD_ETHER;
-        memcpy(ap_addr->sa_data, &pAdapter->MlmeAux.Bssid, ETH_ALEN);
-    }
-#endif // WPA_SUPPLICANT_SUPPORT //
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCGIWAP(=EMPTY)\n"));
-		return -ENOTCONN;
-	}
-
-	return 0;
-}
-
-/*
- * Units are in db above the noise floor. That means the
- * rssi values reported in the tx/rx descriptors in the
- * driver are the SNR expressed in db.
- *
- * If you assume that the noise floor is -95, which is an
- * excellent assumption 99.5 % of the time, then you can
- * derive the absolute signal level (i.e. -95 + rssi).
- * There are some other slight factors to take into account
- * depending on whether the rssi measurement is from 11b,
- * 11g, or 11a.   These differences are at most 2db and
- * can be documented.
- *
- * NB: various calculations are based on the orinoco/wavelan
- *     drivers for compatibility
- */
-static void set_quality(PRTMP_ADAPTER pAdapter,
-                        struct iw_quality *iq,
-                        signed char rssi)
-{
-	__u8 ChannelQuality;
-
-	// Normalize Rssi
-	if (rssi >= -50)
-		ChannelQuality = 100;
-	else if (rssi >= -80) // between -50 ~ -80dbm
-		ChannelQuality = (__u8)(24 + ((rssi + 80) * 26)/10);
-	else if (rssi >= -90)   // between -80 ~ -90dbm
-        ChannelQuality = (__u8)((rssi + 90) * 26)/10;
-	else
-		ChannelQuality = 0;
-
-    iq->qual = (__u8)ChannelQuality;
-
-    iq->level = (__u8)(rssi);
-    iq->noise = (pAdapter->BbpWriteLatch[66] > pAdapter->BbpTuning.FalseCcaUpperThreshold) ? ((__u8)pAdapter->BbpTuning.FalseCcaUpperThreshold) : ((__u8) pAdapter->BbpWriteLatch[66]); 	// noise level (dBm)
-    iq->noise += 256 - 143;
-    iq->updated = pAdapter->iw_stats.qual.updated;
-}
-
-int rt_ioctl_iwaplist(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
- 	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	struct sockaddr addr[IW_MAX_AP];
-	struct iw_quality qual[IW_MAX_AP];
-	int i;
-
-   	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		data->length = 0;
-		return 0;
-        //return -ENETDOWN;
-	}
-
-	for (i = 0; i <IW_MAX_AP ; i++)
-	{
-		if (i >=  pAdapter->ScanTab.BssNr)
-			break;
-		addr[i].sa_family = ARPHRD_ETHER;
-			memcpy(addr[i].sa_data, &pAdapter->ScanTab.BssEntry[i].Bssid, MAC_ADDR_LEN);
-		set_quality(pAdapter, &qual[i], pAdapter->ScanTab.BssEntry[i].Rssi);
-	}
-	data->length = i;
-	memcpy(extra, &addr, i*sizeof(addr[0]));
-	data->flags = 1;		/* signal quality present (sort of) */
-	memcpy(extra + i*sizeof(addr[0]), &qual, i*sizeof(qual[i]));
-
-	return 0;
-}
-
-#ifdef SIOCGIWSCAN
-int rt_ioctl_siwscan(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	ULONG								Now;
-	int Status = NDIS_STATUS_SUCCESS;
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		return -ENETDOWN;
-	}
-
-	if (MONITOR_ON(pAdapter))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is in Monitor Mode now !!!\n"));
-        return -EINVAL;
-    }
-
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-	if (pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-		pAdapter->StaCfg.WpaSupplicantScanCount++;
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-    pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-		return 0;
-	do{
-		Now = jiffies;
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-		if ((pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE) &&
-			(pAdapter->StaCfg.WpaSupplicantScanCount > 3))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! WpaSupplicantScanCount > 3\n"));
-			Status = NDIS_STATUS_SUCCESS;
-			break;
-		}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-		if ((OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED)) &&
-			((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-			(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)) &&
-			(pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, Port Not Secured! ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-			Status = NDIS_STATUS_SUCCESS;
-			break;
-		}
-
-		if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-		{
-			RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-		}
-
-		// tell CNTL state machine to call NdisMSetInformationComplete() after completing
-		// this request, because this request is initiated by NDIS.
-		pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-		// Reset allowed scan retries
-		pAdapter->StaCfg.ScanCnt = 0;
-		pAdapter->StaCfg.LastScanTime = Now;
-
-		MlmeEnqueue(pAdapter,
-			MLME_CNTL_STATE_MACHINE,
-			OID_802_11_BSSID_LIST_SCAN,
-			0,
-			NULL);
-
-		Status = NDIS_STATUS_SUCCESS;
-		RT28XX_MLME_HANDLER(pAdapter);
-	}while(0);
-	return 0;
-}
-
-int rt_ioctl_giwscan(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
-
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-	int i=0;
-	char *current_ev = extra, *previous_ev = extra;
-	char *end_buf;
-	char *current_val, custom[MAX_CUSTOM_LEN] = {0};
-#ifndef IWEVGENIE
-	char idx;
-#endif // IWEVGENIE //
-	struct iw_event iwe;
-
-	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-    {
-		/*
-		 * Still scanning, indicate the caller should try again.
-		 */
-		return -EAGAIN;
-	}
-
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-	if (pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-		pAdapter->StaCfg.WpaSupplicantScanCount = 0;
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-	if (pAdapter->ScanTab.BssNr == 0)
-	{
-		data->length = 0;
-		return 0;
-	}
-
-#if WIRELESS_EXT >= 17
-    if (data->length > 0)
-        end_buf = extra + data->length;
-    else
-        end_buf = extra + IW_SCAN_MAX_DATA;
-#else
-    end_buf = extra + IW_SCAN_MAX_DATA;
-#endif
-
-	for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-	{
-		if (current_ev >= end_buf)
-        {
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-        }
-
-		//MAC address
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWAP;
-		iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
-				memcpy(iwe.u.ap_addr.sa_data, &pAdapter->ScanTab.BssEntry[i].Bssid, ETH_ALEN);
-
-        previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev,end_buf, &iwe, IW_EV_ADDR_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//ESSID
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWESSID;
-		iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].SsidLen;
-		iwe.u.data.flags = 1;
-
-        previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_POINT(info, current_ev,end_buf, &iwe, pAdapter->ScanTab.BssEntry[i].Ssid);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Network Type
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWMODE;
-		if (pAdapter->ScanTab.BssEntry[i].BssType == Ndis802_11IBSS)
-		{
-			iwe.u.mode = IW_MODE_ADHOC;
-		}
-		else if (pAdapter->ScanTab.BssEntry[i].BssType == Ndis802_11Infrastructure)
-		{
-			iwe.u.mode = IW_MODE_INFRA;
-		}
-		else
-		{
-			iwe.u.mode = IW_MODE_AUTO;
-		}
-		iwe.len = IW_EV_UINT_LEN;
-
-        previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev, end_buf, &iwe,  IW_EV_UINT_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Channel and Frequency
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWFREQ;
-		if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-			iwe.u.freq.m = pAdapter->ScanTab.BssEntry[i].Channel;
-		else
-			iwe.u.freq.m = pAdapter->ScanTab.BssEntry[i].Channel;
-		iwe.u.freq.e = 0;
-		iwe.u.freq.i = 0;
-
-		previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev,end_buf, &iwe, IW_EV_FREQ_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-        //Add quality statistics
-        //================================
-        memset(&iwe, 0, sizeof(iwe));
-    	iwe.cmd = IWEVQUAL;
-    	iwe.u.qual.level = 0;
-    	iwe.u.qual.noise = 0;
-        set_quality(pAdapter, &iwe.u.qual, pAdapter->ScanTab.BssEntry[i].Rssi);
-    	current_ev = IWE_STREAM_ADD_EVENT(info, current_ev, end_buf, &iwe, IW_EV_QUAL_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Encyption key
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWENCODE;
-		if (CAP_IS_PRIVACY_ON (pAdapter->ScanTab.BssEntry[i].CapabilityInfo ))
-			iwe.u.data.flags =IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
-		else
-			iwe.u.data.flags = IW_ENCODE_DISABLED;
-
-        previous_ev = current_ev;
-        current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf,&iwe, (char *)pAdapter->SharedKey[BSS0][(iwe.u.data.flags & IW_ENCODE_INDEX)-1].Key);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Bit Rate
-		//================================
-		if (pAdapter->ScanTab.BssEntry[i].SupRateLen)
-        {
-            UCHAR tmpRate = pAdapter->ScanTab.BssEntry[i].SupRate[pAdapter->ScanTab.BssEntry[i].SupRateLen-1];
-			memset(&iwe, 0, sizeof(iwe));
-			iwe.cmd = SIOCGIWRATE;
-    		current_val = current_ev + IW_EV_LCP_LEN;
-            if (tmpRate == 0x82)
-                iwe.u.bitrate.value =  1 * 1000000;
-            else if (tmpRate == 0x84)
-                iwe.u.bitrate.value =  2 * 1000000;
-            else if (tmpRate == 0x8B)
-                iwe.u.bitrate.value =  5.5 * 1000000;
-            else if (tmpRate == 0x96)
-                iwe.u.bitrate.value =  11 * 1000000;
-            else
-    		    iwe.u.bitrate.value =  (tmpRate/2) * 1000000;
-
-			iwe.u.bitrate.disabled = 0;
-			current_val = IWE_STREAM_ADD_VALUE(info, current_ev,
-				current_val, end_buf, &iwe,
-    			IW_EV_PARAM_LEN);
-
-        	if((current_val-current_ev)>IW_EV_LCP_LEN)
-            	current_ev = current_val;
-        	else
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-
-#ifdef IWEVGENIE
-		//WPA IE
-		if (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen > 0)
-		{
-			memset(&iwe, 0, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-			memcpy(custom, &(pAdapter->ScanTab.BssEntry[i].WpaIE.IE[0]),
-						   pAdapter->ScanTab.BssEntry[i].WpaIE.IELen);
-			iwe.cmd = IWEVGENIE;
-			iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].WpaIE.IELen;
-			current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe, custom);
-			if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-		}
-
-		//WPA2 IE
-        if (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen > 0)
-        {
-        	memset(&iwe, 0, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-			memcpy(custom, &(pAdapter->ScanTab.BssEntry[i].RsnIE.IE[0]),
-						   pAdapter->ScanTab.BssEntry[i].RsnIE.IELen);
-			iwe.cmd = IWEVGENIE;
-			iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].RsnIE.IELen;
-			current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe, custom);
-			if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-#else
-        //WPA IE
-		//================================
-        if (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen > 0)
-        {
-    		NdisZeroMemory(&iwe, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-    		iwe.cmd = IWEVCUSTOM;
-            iwe.u.data.length = (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen * 2) + 7;
-            NdisMoveMemory(custom, "wpa_ie=", 7);
-            for (idx = 0; idx < pAdapter->ScanTab.BssEntry[i].WpaIE.IELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAdapter->ScanTab.BssEntry[i].WpaIE.IE[idx]);
-            previous_ev = current_ev;
-    		current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe,  custom);
-            if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-
-        //WPA2 IE
-        if (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen > 0)
-        {
-    		NdisZeroMemory(&iwe, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-    		iwe.cmd = IWEVCUSTOM;
-            iwe.u.data.length = (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen * 2) + 7;
-            NdisMoveMemory(custom, "rsn_ie=", 7);
-			for (idx = 0; idx < pAdapter->ScanTab.BssEntry[i].RsnIE.IELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAdapter->ScanTab.BssEntry[i].RsnIE.IE[idx]);
-            previous_ev = current_ev;
-    		current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe,  custom);
-            if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-#endif // IWEVGENIE //
-	}
-
-	data->length = current_ev - extra;
-    pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-	DBGPRINT(RT_DEBUG_ERROR ,("===>rt_ioctl_giwscan. %d(%d) BSS returned, data->length = %d\n",i , pAdapter->ScanTab.BssNr, data->length));
-	return 0;
-}
-#endif
-
-int rt_ioctl_siwessid(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *essid)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	if (data->flags)
-	{
-		PCHAR	pSsidString = NULL;
-
-		// Includes null character.
-		if (data->length > (IW_ESSID_MAX_SIZE + 1))
-			return -E2BIG;
-
-		pSsidString = (CHAR *) kmalloc(MAX_LEN_OF_SSID+1, MEM_ALLOC_FLAG);
-		if (pSsidString)
-		{
-			NdisZeroMemory(pSsidString, MAX_LEN_OF_SSID+1);
-			NdisMoveMemory(pSsidString, essid, data->length);
-			if (Set_SSID_Proc(pAdapter, pSsidString) == FALSE)
-				return -EINVAL;
-		}
-		else
-			return -ENOMEM;
-	}
-	else
-	{
-		// ANY ssid
-		if (Set_SSID_Proc(pAdapter, "") == FALSE)
-			return -EINVAL;
-    }
-	return 0;
-}
-
-int rt_ioctl_giwessid(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *essid)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	data->flags = 1;
-    if (MONITOR_ON(pAdapter))
-    {
-        data->length  = 0;
-        return 0;
-    }
-
-	if (OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED))
-	{
-		DBGPRINT(RT_DEBUG_TRACE ,("MediaState is connected\n"));
-		data->length = pAdapter->CommonCfg.SsidLen;
-		memcpy(essid, pAdapter->CommonCfg.Ssid, pAdapter->CommonCfg.SsidLen);
-	}
-#ifdef RT2870
-#ifdef WPA_SUPPLICANT_SUPPORT
-    // Add for RT2870
-    else if (pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-    {
-        data->length = pAdapter->CommonCfg.SsidLen;
-		memcpy(essid, pAdapter->CommonCfg.Ssid, pAdapter->CommonCfg.SsidLen);
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-#endif // RT2870 //
-	else
-	{//the ANY ssid was specified
-		data->length  = 0;
-		DBGPRINT(RT_DEBUG_TRACE ,("MediaState is not connected, ess\n"));
-	}
-
-	return 0;
-
-}
-
-int rt_ioctl_siwnickn(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *nickname)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE ,("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-	if (data->length > IW_ESSID_MAX_SIZE)
-		return -EINVAL;
-
-	memset(pAdapter->nickname, 0, IW_ESSID_MAX_SIZE + 1);
-	memcpy(pAdapter->nickname, nickname, data->length);
-
-
-	return 0;
-}
-
-int rt_ioctl_giwnickn(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *nickname)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	if (data->length > strlen(pAdapter->nickname) + 1)
-		data->length = strlen(pAdapter->nickname) + 1;
-	if (data->length > 0) {
-		memcpy(nickname, pAdapter->nickname, data->length-1);
-		nickname[data->length-1] = '\0';
-	}
-	return 0;
-}
-
-int rt_ioctl_siwrts(struct net_device *dev,
-		       struct iw_request_info *info,
-		       struct iw_param *rts, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-	u16 val;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-	if (rts->disabled)
-		val = MAX_RTS_THRESHOLD;
-	else if (rts->value < 0 || rts->value > MAX_RTS_THRESHOLD)
-		return -EINVAL;
-	else if (rts->value == 0)
-	    val = MAX_RTS_THRESHOLD;
-	else
-		val = rts->value;
-
-	if (val != pAdapter->CommonCfg.RtsThreshold)
-		pAdapter->CommonCfg.RtsThreshold = val;
-
-	return 0;
-}
-
-int rt_ioctl_giwrts(struct net_device *dev,
-		       struct iw_request_info *info,
-		       struct iw_param *rts, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-	rts->value = pAdapter->CommonCfg.RtsThreshold;
-	rts->disabled = (rts->value == MAX_RTS_THRESHOLD);
-	rts->fixed = 1;
-
-	return 0;
-}
-
-int rt_ioctl_siwfrag(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_param *frag, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-	u16 val;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	if (frag->disabled)
-		val = MAX_FRAG_THRESHOLD;
-	else if (frag->value >= MIN_FRAG_THRESHOLD || frag->value <= MAX_FRAG_THRESHOLD)
-        val = __cpu_to_le16(frag->value & ~0x1); /* even numbers only */
-	else if (frag->value == 0)
-	    val = MAX_FRAG_THRESHOLD;
-	else
-		return -EINVAL;
-
-	pAdapter->CommonCfg.FragmentThreshold = val;
-	return 0;
-}
-
-int rt_ioctl_giwfrag(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_param *frag, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-	frag->value = pAdapter->CommonCfg.FragmentThreshold;
-	frag->disabled = (frag->value == MAX_FRAG_THRESHOLD);
-	frag->fixed = 1;
-
-	return 0;
-}
-
-#define MAX_WEP_KEY_SIZE 13
-#define MIN_WEP_KEY_SIZE 5
-int rt_ioctl_siwencode(struct net_device *dev,
-			  struct iw_request_info *info,
-			  struct iw_point *erq, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	if ((erq->length == 0) &&
-        (erq->flags & IW_ENCODE_DISABLED))
-	{
-		pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-		pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-		pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-        pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-        goto done;
-	}
-	else if ((erq->length == 0) &&
-             (erq->flags & IW_ENCODE_RESTRICTED || erq->flags & IW_ENCODE_OPEN))
-	{
-	    //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-		STA_PORT_SECURED(pAdapter);
-		pAdapter->StaCfg.PairCipher = Ndis802_11WEPEnabled;
-		pAdapter->StaCfg.GroupCipher = Ndis802_11WEPEnabled;
-		pAdapter->StaCfg.WepStatus = Ndis802_11WEPEnabled;
-        pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-		if (erq->flags & IW_ENCODE_RESTRICTED)
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-    	else
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-        goto done;
-	}
-
-    if (erq->length > 0)
-	{
-		int keyIdx = (erq->flags & IW_ENCODE_INDEX) - 1;
-		/* Check the size of the key */
-		if (erq->length > MAX_WEP_KEY_SIZE) {
-			return -EINVAL;
-		}
-		/* Check key index */
-		if ((keyIdx < 0) || (keyIdx >= NR_WEP_KEYS))
-        {
-            DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::Wrong keyIdx=%d! Using default key instead (%d)\n",
-                                        keyIdx, pAdapter->StaCfg.DefaultKeyId));
-
-            //Using default key
-			keyIdx = pAdapter->StaCfg.DefaultKeyId;
-        }
-
-        NdisZeroMemory(pAdapter->SharedKey[BSS0][keyIdx].Key,  16);
-
-		if (erq->length == MAX_WEP_KEY_SIZE)
-        {
-			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MAX_WEP_KEY_SIZE;
-            pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP128;
-		}
-		else if (erq->length == MIN_WEP_KEY_SIZE)
-        {
-            pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MIN_WEP_KEY_SIZE;
-            pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP64;
-		}
-		else
-			/* Disable the key */
-			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = 0;
-
-		/* Check if the key is not marked as invalid */
-		if(!(erq->flags & IW_ENCODE_NOKEY)) {
-			/* Copy the key in the driver */
-			NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, extra, erq->length);
-        }
-	}
-    else
-			{
-		/* Do we want to just set the transmit key index ? */
-		int index = (erq->flags & IW_ENCODE_INDEX) - 1;
-		if ((index >= 0) && (index < 4))
-        {
-			pAdapter->StaCfg.DefaultKeyId = index;
-            }
-        else
-			/* Don't complain if only change the mode */
-			if (!(erq->flags & IW_ENCODE_MODE)) {
-				return -EINVAL;
-		}
-	}
-
-done:
-    DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::erq->flags=%x\n",erq->flags));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::AuthMode=%x\n",pAdapter->StaCfg.AuthMode));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::DefaultKeyId=%x, KeyLen = %d\n",pAdapter->StaCfg.DefaultKeyId , pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::WepStatus=%x\n",pAdapter->StaCfg.WepStatus));
-	return 0;
-}
-
-int
-rt_ioctl_giwencode(struct net_device *dev,
-			  struct iw_request_info *info,
-			  struct iw_point *erq, char *key)
-{
-	int kid;
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-	kid = erq->flags & IW_ENCODE_INDEX;
-	DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_giwencode %d\n", erq->flags & IW_ENCODE_INDEX));
-
-	if (pAdapter->StaCfg.WepStatus == Ndis802_11WEPDisabled)
-	{
-		erq->length = 0;
-		erq->flags = IW_ENCODE_DISABLED;
-	}
-	else if ((kid > 0) && (kid <=4))
-	{
-		// copy wep key
-		erq->flags = kid ;			/* NB: base 1 */
-		if (erq->length > pAdapter->SharedKey[BSS0][kid-1].KeyLen)
-			erq->length = pAdapter->SharedKey[BSS0][kid-1].KeyLen;
-		memcpy(key, pAdapter->SharedKey[BSS0][kid-1].Key, erq->length);
-		//if ((kid == pAdapter->PortCfg.DefaultKeyId))
-		//erq->flags |= IW_ENCODE_ENABLED;	/* XXX */
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-
-	}
-	else if (kid == 0)
-	{
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-		erq->length = pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen;
-		memcpy(key, pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key, erq->length);
-		// copy default key ID
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-		erq->flags = pAdapter->StaCfg.DefaultKeyId + 1;			/* NB: base 1 */
-		erq->flags |= IW_ENCODE_ENABLED;	/* XXX */
-	}
-
-	return 0;
-
-}
-
-static int
-rt_ioctl_setparam(struct net_device *dev, struct iw_request_info *info,
-			 void *w, char *extra)
-{
-    VIRTUAL_ADAPTER	*pVirtualAd = NULL;
-	PRTMP_ADAPTER pAdapter;
-	POS_COOKIE pObj;
-	char *this_char = extra;
-	char *value;
-	int  Status=0;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-	pObj = (POS_COOKIE) pAdapter->OS_Cookie;
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	{
-		pObj->ioctl_if_type = INT_MAIN;
-        pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-			return -ENETDOWN;
-    	}
-
-	if (!*this_char)
-		return -EINVAL;
-
-	if ((value = rtstrchr(this_char, '=')) != NULL)
-	    *value++ = 0;
-
-	if (!value)
-	    return -EINVAL;
-
-	// reject setting nothing besides ANY ssid(ssidLen=0)
-    if (!*value && (strcmp(this_char, "SSID") != 0))
-        return -EINVAL;
-
-	for (PRTMP_PRIVATE_SET_PROC = RTMP_PRIVATE_SUPPORT_PROC; PRTMP_PRIVATE_SET_PROC->name; PRTMP_PRIVATE_SET_PROC++)
-	{
-	    if (strcmp(this_char, PRTMP_PRIVATE_SET_PROC->name) == 0)
-	    {
-	        if(!PRTMP_PRIVATE_SET_PROC->set_proc(pAdapter, value))
-	        {	//FALSE:Set private failed then return Invalid argument
-			    Status = -EINVAL;
-	        }
-		    break;	//Exit for loop.
-	    }
-	}
-
-	if(PRTMP_PRIVATE_SET_PROC->name == NULL)
-	{  //Not found argument
-	    Status = -EINVAL;
-	    DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_setparam:: (iwpriv) Not Support Set Command [%s=%s]\n", this_char, value));
-	}
-
-    return Status;
-}
-
-
-static int
-rt_private_get_statistics(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-{
-	INT				Status = 0;
-    PRTMP_ADAPTER   pAd = dev->ml_priv;
-
-    if (extra == NULL)
-    {
-        wrq->length = 0;
-        return -EIO;
-    }
-
-    memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-    sprintf(extra, "\n\n");
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-	    sprintf(extra+strlen(extra), "Tx success                      = %ld\n", (ULONG)pAd->ate.TxDoneCount);
-	    //sprintf(extra+strlen(extra), "Tx success without retry        = %ld\n", (ULONG)pAd->ate.TxDoneCount);
-	}
-	else
-#endif // RALINK_ATE //
-	{
-    sprintf(extra+strlen(extra), "Tx success                      = %ld\n", (ULONG)pAd->WlanCounters.TransmittedFragmentCount.QuadPart);
-    sprintf(extra+strlen(extra), "Tx success without retry        = %ld\n", (ULONG)pAd->WlanCounters.TransmittedFragmentCount.QuadPart - (ULONG)pAd->WlanCounters.RetryCount.QuadPart);
-	}
-    sprintf(extra+strlen(extra), "Tx success after retry          = %ld\n", (ULONG)pAd->WlanCounters.RetryCount.QuadPart);
-    sprintf(extra+strlen(extra), "Tx fail to Rcv ACK after retry  = %ld\n", (ULONG)pAd->WlanCounters.FailedCount.QuadPart);
-    sprintf(extra+strlen(extra), "RTS Success Rcv CTS             = %ld\n", (ULONG)pAd->WlanCounters.RTSSuccessCount.QuadPart);
-    sprintf(extra+strlen(extra), "RTS Fail Rcv CTS                = %ld\n", (ULONG)pAd->WlanCounters.RTSFailureCount.QuadPart);
-
-    sprintf(extra+strlen(extra), "Rx success                      = %ld\n", (ULONG)pAd->WlanCounters.ReceivedFragmentCount.QuadPart);
-    sprintf(extra+strlen(extra), "Rx with CRC                     = %ld\n", (ULONG)pAd->WlanCounters.FCSErrorCount.QuadPart);
-    sprintf(extra+strlen(extra), "Rx drop due to out of resource  = %ld\n", (ULONG)pAd->Counters8023.RxNoBuffer);
-    sprintf(extra+strlen(extra), "Rx duplicate frame              = %ld\n", (ULONG)pAd->WlanCounters.FrameDuplicateCount.QuadPart);
-
-    sprintf(extra+strlen(extra), "False CCA (one second)          = %ld\n", (ULONG)pAd->RalinkCounters.OneSecFalseCCACnt);
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-		if (pAd->ate.RxAntennaSel == 0)
-		{
-    		sprintf(extra+strlen(extra), "RSSI-A                          = %ld\n", (LONG)(pAd->ate.LastRssi0 - pAd->BbpRssiToDbmDelta));
-			sprintf(extra+strlen(extra), "RSSI-B (if available)           = %ld\n", (LONG)(pAd->ate.LastRssi1 - pAd->BbpRssiToDbmDelta));
-			sprintf(extra+strlen(extra), "RSSI-C (if available)           = %ld\n\n", (LONG)(pAd->ate.LastRssi2 - pAd->BbpRssiToDbmDelta));
-		}
-		else
-		{
-    		sprintf(extra+strlen(extra), "RSSI                            = %ld\n", (LONG)(pAd->ate.LastRssi0 - pAd->BbpRssiToDbmDelta));
-		}
-	}
-	else
-#endif // RALINK_ATE //
-	{
-    	sprintf(extra+strlen(extra), "RSSI-A                          = %ld\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi0 - pAd->BbpRssiToDbmDelta));
-        sprintf(extra+strlen(extra), "RSSI-B (if available)           = %ld\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi1 - pAd->BbpRssiToDbmDelta));
-        sprintf(extra+strlen(extra), "RSSI-C (if available)           = %ld\n\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi2 - pAd->BbpRssiToDbmDelta));
-	}
-#ifdef WPA_SUPPLICANT_SUPPORT
-    sprintf(extra+strlen(extra), "WpaSupplicantUP                 = %d\n\n", pAd->StaCfg.WpaSupplicantUP);
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-    DBGPRINT(RT_DEBUG_TRACE, ("<== rt_private_get_statistics, wrq->length = %d\n", wrq->length));
-
-    return Status;
-}
-
-#ifdef DOT11_N_SUPPORT
-void	getBaInfo(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pOutBuf)
-{
-	INT i, j;
-	BA_ORI_ENTRY *pOriBAEntry;
-	BA_REC_ENTRY *pRecBAEntry;
-
-	for (i=0; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[i];
-		if (((pEntry->ValidAsCLI || pEntry->ValidAsApCli) && (pEntry->Sst == SST_ASSOC))
-			|| (pEntry->ValidAsWDS) || (pEntry->ValidAsMesh))
-		{
-			sprintf(pOutBuf, "%s\n%02X:%02X:%02X:%02X:%02X:%02X (Aid = %d) (AP) -\n",
-                pOutBuf,
-				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
-				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5], pEntry->Aid);
-
-			sprintf(pOutBuf, "%s[Recipient]\n", pOutBuf);
-			for (j=0; j < NUM_OF_TID; j++)
-			{
-				if (pEntry->BARecWcidArray[j] != 0)
-				{
-					pRecBAEntry =&pAd->BATable.BARecEntry[pEntry->BARecWcidArray[j]];
-					sprintf(pOutBuf, "%sTID=%d, BAWinSize=%d, LastIndSeq=%d, ReorderingPkts=%d\n", pOutBuf, j, pRecBAEntry->BAWinSize, pRecBAEntry->LastIndSeq, pRecBAEntry->list.qlen);
-				}
-			}
-			sprintf(pOutBuf, "%s\n", pOutBuf);
-
-			sprintf(pOutBuf, "%s[Originator]\n", pOutBuf);
-			for (j=0; j < NUM_OF_TID; j++)
-			{
-				if (pEntry->BAOriWcidArray[j] != 0)
-				{
-					pOriBAEntry =&pAd->BATable.BAOriEntry[pEntry->BAOriWcidArray[j]];
-					sprintf(pOutBuf, "%sTID=%d, BAWinSize=%d, StartSeq=%d, CurTxSeq=%d\n", pOutBuf, j, pOriBAEntry->BAWinSize, pOriBAEntry->Sequence, pEntry->TxSeq[j]);
-				}
-			}
-			sprintf(pOutBuf, "%s\n\n", pOutBuf);
-		}
-        if (strlen(pOutBuf) > (IW_PRIV_SIZE_MASK - 30))
-                break;
-	}
-
-	return;
-}
-#endif // DOT11_N_SUPPORT //
-
-static int
-rt_private_show(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-{
-    INT				Status = 0;
-    VIRTUAL_ADAPTER	*pVirtualAd = NULL;
-    PRTMP_ADAPTER   pAd;
-	POS_COOKIE		pObj;
-    u32             subcmd = wrq->flags;
-
-	if (dev->priv_flags == INT_MAIN)
-		pAd = dev->ml_priv;
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		pAd = pVirtualAd->RtmpDev->ml_priv;
-	}
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-    if (extra == NULL)
-    {
-        wrq->length = 0;
-        return -EIO;
-    }
-    memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-
-	{
-		pObj->ioctl_if_type = INT_MAIN;
-        pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-    switch(subcmd)
-    {
-
-        case SHOW_CONN_STATUS:
-            if (MONITOR_ON(pAd))
-            {
-#ifdef DOT11_N_SUPPORT
-                if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-                    pAd->CommonCfg.RegTransmitSetting.field.BW)
-                    sprintf(extra, "Monitor Mode(CentralChannel %d)\n", pAd->CommonCfg.CentralChannel);
-                else
-#endif // DOT11_N_SUPPORT //
-                    sprintf(extra, "Monitor Mode(Channel %d)\n", pAd->CommonCfg.Channel);
-            }
-            else
-            {
-                if (pAd->IndicateMediaState == NdisMediaStateConnected)
-            	{
-            	    if (INFRA_ON(pAd))
-                    {
-                    sprintf(extra, "Connected(AP: %s[%02X:%02X:%02X:%02X:%02X:%02X])\n",
-                                    pAd->CommonCfg.Ssid,
-                                    pAd->CommonCfg.Bssid[0],
-                                    pAd->CommonCfg.Bssid[1],
-                                    pAd->CommonCfg.Bssid[2],
-                                    pAd->CommonCfg.Bssid[3],
-                                    pAd->CommonCfg.Bssid[4],
-                                    pAd->CommonCfg.Bssid[5]);
-            		DBGPRINT(RT_DEBUG_TRACE ,("Ssid=%s ,Ssidlen = %d\n",pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen));
-            	}
-                    else if (ADHOC_ON(pAd))
-                        sprintf(extra, "Connected\n");
-            	}
-            	else
-            	{
-            	    sprintf(extra, "Disconnected\n");
-            		DBGPRINT(RT_DEBUG_TRACE ,("ConnStatus is not connected\n"));
-            	}
-            }
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-        case SHOW_DRVIER_VERION:
-            sprintf(extra, "Driver version-%s, %s %s\n", STA_DRIVER_VERSION, __DATE__, __TIME__ );
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-#ifdef DOT11_N_SUPPORT
-        case SHOW_BA_INFO:
-            getBaInfo(pAd, extra);
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-#endif // DOT11_N_SUPPORT //
-		case SHOW_DESC_INFO:
-			{
-				Show_DescInfo_Proc(pAd, NULL);
-				wrq->length = 0; // 1: size of '\0'
-			}
-			break;
-        case RAIO_OFF:
-            if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-                sprintf(extra, "Scanning\n");
-                wrq->length = strlen(extra) + 1; // 1: size of '\0'
-                break;
-            }
-            pAd->StaCfg.bSwRadio = FALSE;
-            if (pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
-            {
-                pAd->StaCfg.bRadio = (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio);
-                if (pAd->StaCfg.bRadio == FALSE)
-                {
-                    MlmeRadioOff(pAd);
-                    // Update extra information
-					pAd->ExtraInfo = SW_RADIO_OFF;
-                }
-            }
-            sprintf(extra, "Radio Off\n");
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-        case RAIO_ON:
-            if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-                sprintf(extra, "Scanning\n");
-                wrq->length = strlen(extra) + 1; // 1: size of '\0'
-                break;
-            }
-            pAd->StaCfg.bSwRadio = TRUE;
-            //if (pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
-            {
-                pAd->StaCfg.bRadio = (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio);
-                if (pAd->StaCfg.bRadio == TRUE)
-                {
-                    MlmeRadioOn(pAd);
-                    // Update extra information
-					pAd->ExtraInfo = EXTRA_INFO_CLEAR;
-                }
-            }
-            sprintf(extra, "Radio On\n");
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-
-
-#ifdef QOS_DLS_SUPPORT
-		case SHOW_DLS_ENTRY_INFO:
-			{
-				Set_DlsEntryInfo_Display_Proc(pAd, NULL);
-				wrq->length = 0; // 1: size of '\0'
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-
-		case SHOW_CFG_VALUE:
-			{
-				Status = RTMPShowCfgValue(pAd, wrq->pointer, extra);
-				if (Status == 0)
-					wrq->length = strlen(extra) + 1; // 1: size of '\0'
-			}
-			break;
-		case SHOW_ADHOC_ENTRY_INFO:
-			Show_Adhoc_MacTable_Proc(pAd, extra);
-			wrq->length = strlen(extra) + 1; // 1: size of '\0'
-			break;
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("%s - unknow subcmd = %d\n", __func__, subcmd));
-            break;
-    }
-
-    return Status;
-}
-
-#ifdef SIOCSIWMLME
-int rt_ioctl_siwmlme(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-{
-	PRTMP_ADAPTER   pAd = dev->ml_priv;
-	struct iw_mlme *pMlme = (struct iw_mlme *)wrqu->data.pointer;
-	MLME_QUEUE_ELEM				MsgElem;
-	MLME_DISASSOC_REQ_STRUCT	DisAssocReq;
-	MLME_DEAUTH_REQ_STRUCT      DeAuthReq;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("====> %s\n", __func__));
-
-	if (pMlme == NULL)
-		return -EINVAL;
-
-	switch(pMlme->cmd)
-	{
-#ifdef IW_MLME_DEAUTH
-		case IW_MLME_DEAUTH:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - IW_MLME_DEAUTH\n", __func__));
-			COPY_MAC_ADDR(DeAuthReq.Addr, pAd->CommonCfg.Bssid);
-			DeAuthReq.Reason = pMlme->reason_code;
-			MsgElem.MsgLen = sizeof(MLME_DEAUTH_REQ_STRUCT);
-			NdisMoveMemory(MsgElem.Msg, &DeAuthReq, sizeof(MLME_DEAUTH_REQ_STRUCT));
-			MlmeDeauthReqAction(pAd, &MsgElem);
-			if (INFRA_ON(pAd))
-			{
-			    LinkDown(pAd, FALSE);
-			    pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-			}
-			break;
-#endif // IW_MLME_DEAUTH //
-#ifdef IW_MLME_DISASSOC
-		case IW_MLME_DISASSOC:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - IW_MLME_DISASSOC\n", __func__));
-			COPY_MAC_ADDR(DisAssocReq.Addr, pAd->CommonCfg.Bssid);
-			DisAssocReq.Reason =  pMlme->reason_code;
-
-			MsgElem.Machine = ASSOC_STATE_MACHINE;
-			MsgElem.MsgType = MT2_MLME_DISASSOC_REQ;
-			MsgElem.MsgLen = sizeof(MLME_DISASSOC_REQ_STRUCT);
-			NdisMoveMemory(MsgElem.Msg, &DisAssocReq, sizeof(MLME_DISASSOC_REQ_STRUCT));
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_DISASSOC;
-			MlmeDisassocReqAction(pAd, &MsgElem);
-			break;
-#endif // IW_MLME_DISASSOC //
-		default:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - Unknow Command\n", __func__));
-			break;
-	}
-
-	return 0;
-}
-#endif // SIOCSIWMLME //
-
-#if WIRELESS_EXT > 17
-int rt_ioctl_siwauth(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAdapter = dev->ml_priv;
-	struct iw_param *param = &wrqu->param;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-	switch (param->flags & IW_AUTH_INDEX) {
-    	case IW_AUTH_WPA_VERSION:
-            if (param->value == IW_AUTH_WPA_VERSION_WPA)
-            {
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPAPSK;
-				if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-					pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
-            }
-            else if (param->value == IW_AUTH_WPA_VERSION_WPA2)
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_VERSION - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_CIPHER_PAIRWISE:
-            if (param->value == IW_AUTH_CIPHER_NONE)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_WEP40 ||
-                     param->value == IW_AUTH_CIPHER_WEP104)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPEnabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPEnabled;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-            }
-            else if (param->value == IW_AUTH_CIPHER_TKIP)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11Encryption2Enabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_CCMP)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11Encryption3Enabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11Encryption3Enabled;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_CIPHER_PAIRWISE - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_CIPHER_GROUP:
-            if (param->value == IW_AUTH_CIPHER_NONE)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_WEP40 ||
-                     param->value == IW_AUTH_CIPHER_WEP104)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11WEPEnabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_TKIP)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11Encryption2Enabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_CCMP)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11Encryption3Enabled;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_CIPHER_GROUP - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_KEY_MGMT:
-            if (param->value == IW_AUTH_KEY_MGMT_802_1X)
-            {
-                if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)
-                {
-                    pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                    pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                }
-                else if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-                {
-                    pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                    pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                }
-#ifdef WPA_SUPPLICANT_SUPPORT
-                else
-                    // WEP 1x
-                    pAdapter->StaCfg.IEEE8021X = TRUE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-            }
-            else if (param->value == 0)
-            {
-                //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAdapter);
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_KEY_MGMT - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_RX_UNENCRYPTED_EAPOL:
-            break;
-    	case IW_AUTH_PRIVACY_INVOKED:
-            /*if (param->value == 0)
-			{
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-        	    pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-            }*/
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_PRIVACY_INVOKED - param->value = %d!\n", __func__, param->value));
-    		break;
-    	case IW_AUTH_DROP_UNENCRYPTED:
-            if (param->value != 0)
-                pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			else
-			{
-                //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAdapter);
-			}
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_VERSION - param->value = %d!\n", __func__, param->value));
-    		break;
-    	case IW_AUTH_80211_AUTH_ALG:
-			if (param->value & IW_AUTH_ALG_SHARED_KEY)
-            {
-				pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-			}
-            else if (param->value & IW_AUTH_ALG_OPEN_SYSTEM)
-            {
-				pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-			}
-            else
-				return -EINVAL;
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_80211_AUTH_ALG - param->value = %d!\n", __func__, param->value));
-			break;
-    	case IW_AUTH_WPA_ENABLED:
-    		DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_ENABLED - Driver supports WPA!(param->value = %d)\n", __func__, param->value));
-    		break;
-    	default:
-    		return -EOPNOTSUPP;
-}
-
-	return 0;
-}
-
-int rt_ioctl_giwauth(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAdapter = dev->ml_priv;
-	struct iw_param *param = &wrqu->param;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-    }
-
-	switch (param->flags & IW_AUTH_INDEX) {
-	case IW_AUTH_DROP_UNENCRYPTED:
-        param->value = (pAdapter->StaCfg.WepStatus == Ndis802_11WEPDisabled) ? 0 : 1;
-		break;
-
-	case IW_AUTH_80211_AUTH_ALG:
-        param->value = (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared) ? IW_AUTH_ALG_SHARED_KEY : IW_AUTH_ALG_OPEN_SYSTEM;
-		break;
-
-	case IW_AUTH_WPA_ENABLED:
-		param->value = (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA) ? 1 : 0;
-		break;
-
-	default:
-		return -EOPNOTSUPP;
-	}
-    DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_giwauth::param->value = %d!\n", param->value));
-	return 0;
-}
-
-void fnSetCipherKey(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  INT             keyIdx,
-    IN  UCHAR           CipherAlg,
-    IN  BOOLEAN         bGTK,
-    IN  struct iw_encode_ext *ext)
-{
-    NdisZeroMemory(&pAdapter->SharedKey[BSS0][keyIdx], sizeof(CIPHER_KEY));
-    pAdapter->SharedKey[BSS0][keyIdx].KeyLen = LEN_TKIP_EK;
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, ext->key, LEN_TKIP_EK);
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].TxMic, ext->key + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].RxMic, ext->key + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CipherAlg;
-
-    // Update group key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAdapter,
-						  BSS0,
-						  keyIdx,
-						  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-						  pAdapter->SharedKey[BSS0][keyIdx].Key,
-						  pAdapter->SharedKey[BSS0][keyIdx].TxMic,
-						  pAdapter->SharedKey[BSS0][keyIdx].RxMic);
-
-    if (bGTK)
-        // Update ASIC WCID attribute table and IVEIV table
-    	RTMPAddWcidAttributeEntry(pAdapter,
-    							  BSS0,
-    							  keyIdx,
-    							  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-    							  NULL);
-    else
-        // Update ASIC WCID attribute table and IVEIV table
-    	RTMPAddWcidAttributeEntry(pAdapter,
-    							  BSS0,
-    							  keyIdx,
-    							  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-    							  &pAdapter->MacTab.Content[BSSID_WCID]);
-}
-
-int rt_ioctl_siwencodeext(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-			{
-    PRTMP_ADAPTER   pAdapter = dev->ml_priv;
-	struct iw_point *encoding = &wrqu->encoding;
-	struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
-    int keyIdx, alg = ext->alg;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    if (encoding->flags & IW_ENCODE_DISABLED)
-	{
-        keyIdx = (encoding->flags & IW_ENCODE_INDEX) - 1;
-        // set BSSID wcid entry of the Pair-wise Key table as no-security mode
-	    AsicRemovePairwiseKeyEntry(pAdapter, BSS0, BSSID_WCID);
-        pAdapter->SharedKey[BSS0][keyIdx].KeyLen = 0;
-		pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_NONE;
-		AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)keyIdx);
-        NdisZeroMemory(&pAdapter->SharedKey[BSS0][keyIdx], sizeof(CIPHER_KEY));
-        DBGPRINT(RT_DEBUG_TRACE, ("%s::Remove all keys!(encoding->flags = %x)\n", __func__, encoding->flags));
-    }
-					else
-    {
-        // Get Key Index and convet to our own defined key index
-    	keyIdx = (encoding->flags & IW_ENCODE_INDEX) - 1;
-    	if((keyIdx < 0) || (keyIdx >= NR_WEP_KEYS))
-    		return -EINVAL;
-
-        if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-        {
-            pAdapter->StaCfg.DefaultKeyId = keyIdx;
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::DefaultKeyId = %d\n", __func__, pAdapter->StaCfg.DefaultKeyId));
-        }
-
-        switch (alg) {
-    		case IW_ENCODE_ALG_NONE:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_NONE\n", __func__));
-    			break;
-    		case IW_ENCODE_ALG_WEP:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_WEP - ext->key_len = %d, keyIdx = %d\n", __func__, ext->key_len, keyIdx));
-    			if (ext->key_len == MAX_WEP_KEY_SIZE)
-                {
-        			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MAX_WEP_KEY_SIZE;
-                    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP128;
-				}
-        		else if (ext->key_len == MIN_WEP_KEY_SIZE)
-                {
-                    pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MIN_WEP_KEY_SIZE;
-                    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP64;
-				}
-        		else
-                    return -EINVAL;
-
-                NdisZeroMemory(pAdapter->SharedKey[BSS0][keyIdx].Key,  16);
-			    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, ext->key, ext->key_len);
-
-				if (pAdapter->StaCfg.GroupCipher == Ndis802_11GroupWEP40Enabled ||
-					pAdapter->StaCfg.GroupCipher == Ndis802_11GroupWEP104Enabled)
-				{
-					// Set Group key material to Asic
-					AsicAddSharedKeyEntry(pAdapter, BSS0, keyIdx, pAdapter->SharedKey[BSS0][keyIdx].CipherAlg, pAdapter->SharedKey[BSS0][keyIdx].Key, NULL, NULL);
-
-					// Update WCID attribute table and IVEIV table for this group key table
-					RTMPAddWcidAttributeEntry(pAdapter, BSS0, keyIdx, pAdapter->SharedKey[BSS0][keyIdx].CipherAlg, NULL);
-
-					STA_PORT_SECURED(pAdapter);
-
-    				// Indicate Connected for GUI
-    				pAdapter->IndicateMediaState = NdisMediaStateConnected;
-				}
-    			break;
-            case IW_ENCODE_ALG_TKIP:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_TKIP - keyIdx = %d, ext->key_len = %d\n", __func__, keyIdx, ext->key_len));
-                if (ext->key_len == 32)
-                {
-                    if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-                    {
-                        fnSetCipherKey(pAdapter, keyIdx, CIPHER_TKIP, FALSE, ext);
-                        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-                        {
-                            //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-                            STA_PORT_SECURED(pAdapter);
-                        }
-		}
-                    else if (ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY)
-                    {
-                        fnSetCipherKey(pAdapter, keyIdx, CIPHER_TKIP, TRUE, ext);
-
-                        // set 802.1x port control
-            	        //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-            	        STA_PORT_SECURED(pAdapter);
-                    }
-                }
-                else
-                    return -EINVAL;
-                break;
-            case IW_ENCODE_ALG_CCMP:
-                if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-		{
-                    fnSetCipherKey(pAdapter, keyIdx, CIPHER_AES, FALSE, ext);
-                    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-                    	//pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-                    	STA_PORT_SECURED(pAdapter);
-                }
-                else if (ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY)
-                {
-                    fnSetCipherKey(pAdapter, keyIdx, CIPHER_AES, TRUE, ext);
-
-                    // set 802.1x port control
-        	        //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-        	        STA_PORT_SECURED(pAdapter);
-                }
-                break;
-    		default:
-    			return -EINVAL;
-		}
-    }
-
-    return 0;
-}
-
-int
-rt_ioctl_giwencodeext(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER pAd = dev->ml_priv;
-	PCHAR pKey = NULL;
-	struct iw_point *encoding = &wrqu->encoding;
-	struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
-	int idx, max_key_len;
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===> rt_ioctl_giwencodeext\n"));
-
-	max_key_len = encoding->length - sizeof(*ext);
-	if (max_key_len < 0)
-		return -EINVAL;
-
-	idx = encoding->flags & IW_ENCODE_INDEX;
-	if (idx)
-	{
-		if (idx < 1 || idx > 4)
-			return -EINVAL;
-		idx--;
-
-		if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
-			(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled))
-		{
-			if (idx != pAd->StaCfg.DefaultKeyId)
-			{
-				ext->key_len = 0;
-				return 0;
-			}
-		}
-	}
-	else
-		idx = pAd->StaCfg.DefaultKeyId;
-
-	encoding->flags = idx + 1;
-	memset(ext, 0, sizeof(*ext));
-
-	ext->key_len = 0;
-	switch(pAd->StaCfg.WepStatus) {
-		case Ndis802_11WEPDisabled:
-			ext->alg = IW_ENCODE_ALG_NONE;
-			encoding->flags |= IW_ENCODE_DISABLED;
-			break;
-		case Ndis802_11WEPEnabled:
-			ext->alg = IW_ENCODE_ALG_WEP;
-			if (pAd->SharedKey[BSS0][idx].KeyLen > max_key_len)
-				return -E2BIG;
-			else
-			{
-				ext->key_len = pAd->SharedKey[BSS0][idx].KeyLen;
-				pKey = &(pAd->SharedKey[BSS0][idx].Key[0]);
-			}
-			break;
-		case Ndis802_11Encryption2Enabled:
-		case Ndis802_11Encryption3Enabled:
-			if (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled)
-				ext->alg = IW_ENCODE_ALG_TKIP;
-			else
-				ext->alg = IW_ENCODE_ALG_CCMP;
-
-			if (max_key_len < 32)
-				return -E2BIG;
-			else
-			{
-				ext->key_len = 32;
-				pKey = &pAd->StaCfg.PMK[0];
-			}
-			break;
-		default:
-			return -EINVAL;
-	}
-
-	if (ext->key_len && pKey)
-	{
-		encoding->flags |= IW_ENCODE_ENABLED;
-		memcpy(ext->key, pKey, ext->key_len);
-	}
-
-	return 0;
-}
-
-#ifdef SIOCSIWGENIE
-int rt_ioctl_siwgenie(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAd = dev->ml_priv;
-
-	if (wrqu->data.length > MAX_LEN_OF_RSNIE ||
-	    (wrqu->data.length && extra == NULL))
-		return -EINVAL;
-
-	if (wrqu->data.length)
-	{
-		pAd->StaCfg.RSNIE_Len = wrqu->data.length;
-		NdisMoveMemory(&pAd->StaCfg.RSN_IE[0], extra, pAd->StaCfg.RSNIE_Len);
-	}
-	else
-	{
-		pAd->StaCfg.RSNIE_Len = 0;
-		NdisZeroMemory(&pAd->StaCfg.RSN_IE[0], MAX_LEN_OF_RSNIE);
-	}
-
-	return 0;
-}
-#endif // SIOCSIWGENIE //
-
-int rt_ioctl_giwgenie(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAd = dev->ml_priv;
-
-	if ((pAd->StaCfg.RSNIE_Len == 0) ||
-		(pAd->StaCfg.AuthMode < Ndis802_11AuthModeWPA))
-	{
-		wrqu->data.length = 0;
-		return 0;
-	}
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-#ifdef SIOCSIWGENIE
-	if (pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-	if (wrqu->data.length < pAd->StaCfg.RSNIE_Len)
-		return -E2BIG;
-
-	wrqu->data.length = pAd->StaCfg.RSNIE_Len;
-	memcpy(extra, &pAd->StaCfg.RSN_IE[0], pAd->StaCfg.RSNIE_Len);
-	}
-	else
-#endif // SIOCSIWGENIE //
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-	{
-		UCHAR RSNIe = IE_WPA;
-
-		if (wrqu->data.length < (pAd->StaCfg.RSNIE_Len + 2)) // ID, Len
-			return -E2BIG;
-		wrqu->data.length = pAd->StaCfg.RSNIE_Len + 2;
-
-		if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-            (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2))
-			RSNIe = IE_RSN;
-
-		extra[0] = (char)RSNIe;
-		extra[1] = pAd->StaCfg.RSNIE_Len;
-		memcpy(extra+2, &pAd->StaCfg.RSN_IE[0], pAd->StaCfg.RSNIE_Len);
-	}
-
-	return 0;
-}
-
-int rt_ioctl_siwpmksa(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-{
-	PRTMP_ADAPTER   pAd = dev->ml_priv;
-	struct iw_pmksa *pPmksa = (struct iw_pmksa *)wrqu->data.pointer;
-	INT	CachedIdx = 0, idx = 0;
-
-	if (pPmksa == NULL)
-		return -EINVAL;
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===> rt_ioctl_siwpmksa\n"));
-	switch(pPmksa->cmd)
-	{
-		case IW_PMKSA_FLUSH:
-			NdisZeroMemory(pAd->StaCfg.SavedPMK, sizeof(BSSID_INFO)*PMKID_NO);
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_FLUSH\n"));
-			break;
-		case IW_PMKSA_REMOVE:
-			for (CachedIdx = 0; CachedIdx < pAd->StaCfg.SavedPMKNum; CachedIdx++)
-			{
-		        // compare the BSSID
-		        if (NdisEqualMemory(pPmksa->bssid.sa_data, pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN))
-		        {
-		        	NdisZeroMemory(pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN);
-					NdisZeroMemory(pAd->StaCfg.SavedPMK[CachedIdx].PMKID, 16);
-					for (idx = CachedIdx; idx < (pAd->StaCfg.SavedPMKNum - 1); idx++)
-					{
-						NdisMoveMemory(&pAd->StaCfg.SavedPMK[idx].BSSID[0], &pAd->StaCfg.SavedPMK[idx+1].BSSID[0], MAC_ADDR_LEN);
-						NdisMoveMemory(&pAd->StaCfg.SavedPMK[idx].PMKID[0], &pAd->StaCfg.SavedPMK[idx+1].PMKID[0], 16);
-					}
-					pAd->StaCfg.SavedPMKNum--;
-			        break;
-		        }
-	        }
-
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_REMOVE\n"));
-			break;
-		case IW_PMKSA_ADD:
-			for (CachedIdx = 0; CachedIdx < pAd->StaCfg.SavedPMKNum; CachedIdx++)
-			{
-		        // compare the BSSID
-		        if (NdisEqualMemory(pPmksa->bssid.sa_data, pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN))
-			        break;
-	        }
-
-	        // Found, replace it
-	        if (CachedIdx < PMKID_NO)
-	        {
-		        DBGPRINT(RT_DEBUG_OFF, ("Update PMKID, idx = %d\n", CachedIdx));
-		        NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].BSSID[0], pPmksa->bssid.sa_data, MAC_ADDR_LEN);
-				NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].PMKID[0], pPmksa->pmkid, 16);
-		        pAd->StaCfg.SavedPMKNum++;
-	        }
-	        // Not found, replace the last one
-	        else
-	        {
-		        // Randomly replace one
-		        CachedIdx = (pPmksa->bssid.sa_data[5] % PMKID_NO);
-		        DBGPRINT(RT_DEBUG_OFF, ("Update PMKID, idx = %d\n", CachedIdx));
-		        NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].BSSID[0], pPmksa->bssid.sa_data, MAC_ADDR_LEN);
-				NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].PMKID[0], pPmksa->pmkid, 16);
-	        }
-
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_ADD\n"));
-			break;
-		default:
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - Unknow Command!!\n"));
-			break;
-	}
-
-	return 0;
-}
-#endif // #if WIRELESS_EXT > 17
-
-#ifdef DBG
-static int
-rt_private_ioctl_bbp(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-			{
-	CHAR				*this_char;
-	CHAR				*value = NULL;
-	UCHAR				regBBP = 0;
-//	CHAR				arg[255]={0};
-	UINT32				bbpId;
-	UINT32				bbpValue;
-	BOOLEAN				bIsPrintAllBBP = FALSE;
-	INT					Status = 0;
-    PRTMP_ADAPTER       pAdapter = dev->ml_priv;
-
-
-	memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-
-	if (wrq->length > 1) //No parameters.
-				{
-		sprintf(extra, "\n");
-
-		//Parsing Read or Write
-		this_char = wrq->pointer;
-		DBGPRINT(RT_DEBUG_TRACE, ("this_char=%s\n", this_char));
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-			DBGPRINT(RT_DEBUG_TRACE, ("this_char=%s, value=%s\n", this_char, value));
-			if (sscanf(this_char, "%d", &(bbpId)) == 1)
-			{
-				if (bbpId <= 136)
-				{
-#ifdef RALINK_ATE
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					else
-#endif // RALINK_ATE //
-					{
-					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X\n", bbpId, bbpId*2, regBBP);
-                    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-					DBGPRINT(RT_DEBUG_TRACE, ("msg=%s\n", extra));
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					bIsPrintAllBBP = TRUE;
-					goto next;
-				}
-			}
-			else
-			{ //Invalid parametes, so default printk all bbp
-				bIsPrintAllBBP = TRUE;
-				goto next;
-			}
-		}
-		else
-		{ //Write
-			if ((sscanf(this_char, "%d", &(bbpId)) == 1) && (sscanf(value, "%x", &(bbpValue)) == 1))
-			{
-				if (bbpId <= 136)
-				{
-#ifdef RALINK_ATE
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, bbpId, bbpValue);
-						//Read it back for showing
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					else
-#endif // RALINK_ATE //
-					{
-					    RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, bbpId, bbpValue);
-    					//Read it back for showing
-    					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			}
-					sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X\n", bbpId, bbpId*2, regBBP);
-                    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-					DBGPRINT(RT_DEBUG_TRACE, ("msg=%s\n", extra));
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					bIsPrintAllBBP = TRUE;
-					goto next;
-				}
-			}
-			else
-			{ //Invalid parametes, so default printk all bbp
-				bIsPrintAllBBP = TRUE;
-				goto next;
-			}
-		}
-		}
-	else
-		bIsPrintAllBBP = TRUE;
-
-next:
-	if (bIsPrintAllBBP)
-	{
-		memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-		sprintf(extra, "\n");
-		for (bbpId = 0; bbpId <= 136; bbpId++)
-		{
-		    if (strlen(extra) >= (IW_PRIV_SIZE_MASK - 10))
-                break;
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			}
-			else
-#endif // RALINK_ATE //
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X    ", bbpId, bbpId*2, regBBP);
-			if (bbpId%5 == 4)
-				sprintf(extra+strlen(extra), "\n");
-		}
-
-        wrq->length = strlen(extra) + 1; // 1: size of '\0'
-        DBGPRINT(RT_DEBUG_TRACE, ("wrq->length = %d\n", wrq->length));
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==rt_private_ioctl_bbp\n\n"));
-
-    return Status;
-}
-#endif // DBG //
-
-int rt_ioctl_siwrate(struct net_device *dev,
-			struct iw_request_info *info,
-			union iwreq_data *wrqu, char *extra)
-{
-    PRTMP_ADAPTER   pAd = dev->ml_priv;
-    UINT32          rate = wrqu->bitrate.value, fixed = wrqu->bitrate.fixed;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::(rate = %d, fixed = %d)\n", rate, fixed));
-    /* rate = -1 => auto rate
-       rate = X, fixed = 1 => (fixed rate X)
-    */
-    if (rate == -1)
-    {
-		//Auto Rate
-		pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-		pAd->StaCfg.bAutoTxRateSwitch = TRUE;
-		if ((pAd->CommonCfg.PhyMode <= PHY_11G) ||
-		    (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM))
-			RTMPSetDesiredRates(pAd, -1);
-
-#ifdef DOT11_N_SUPPORT
-		SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-    }
-    else
-    {
-        if (fixed)
-        {
-        	pAd->StaCfg.bAutoTxRateSwitch = FALSE;
-            if ((pAd->CommonCfg.PhyMode <= PHY_11G) ||
-                (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM))
-                RTMPSetDesiredRates(pAd, rate);
-            else
-            {
-                pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-#ifdef DOT11_N_SUPPORT
-                SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::(HtMcs=%d)\n",pAd->StaCfg.DesiredTransmitSetting.field.MCS));
-        }
-        else
-        {
-            // TODO: rate = X, fixed = 0 => (rates <= X)
-            return -EOPNOTSUPP;
-        }
-    }
-
-    return 0;
-}
-
-int rt_ioctl_giwrate(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-    PRTMP_ADAPTER   pAd = dev->ml_priv;
-    int rate_index = 0, rate_count = 0;
-    HTTRANSMIT_SETTING ht_setting;
-    __s32 ralinkrate[] =
-	{2,  4,   11,  22, // CCK
-	12, 18,   24,  36, 48, 72, 96, 108, // OFDM
-	13, 26,   39,  52,  78, 104, 117, 130, 26,  52,  78, 104, 156, 208, 234, 260, // 20MHz, 800ns GI, MCS: 0 ~ 15
-	39, 78,  117, 156, 234, 312, 351, 390,										  // 20MHz, 800ns GI, MCS: 16 ~ 23
-	27, 54,   81, 108, 162, 216, 243, 270, 54, 108, 162, 216, 324, 432, 486, 540, // 40MHz, 800ns GI, MCS: 0 ~ 15
-	81, 162, 243, 324, 486, 648, 729, 810,										  // 40MHz, 800ns GI, MCS: 16 ~ 23
-	14, 29,   43,  57,  87, 115, 130, 144, 29, 59,   87, 115, 173, 230, 260, 288, // 20MHz, 400ns GI, MCS: 0 ~ 15
-	43, 87,  130, 173, 260, 317, 390, 433,										  // 20MHz, 400ns GI, MCS: 16 ~ 23
-	30, 60,   90, 120, 180, 240, 270, 300, 60, 120, 180, 240, 360, 480, 540, 600, // 40MHz, 400ns GI, MCS: 0 ~ 15
-	90, 180, 270, 360, 540, 720, 810, 900};										  // 40MHz, 400ns GI, MCS: 16 ~ 23
-
-    rate_count = sizeof(ralinkrate)/sizeof(__s32);
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    if ((pAd->StaCfg.bAutoTxRateSwitch == FALSE) &&
-        (INFRA_ON(pAd)) &&
-        ((pAd->CommonCfg.PhyMode <= PHY_11G) || (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM)))
-        ht_setting.word = pAd->StaCfg.HTPhyMode.word;
-    else
-        ht_setting.word = pAd->MacTab.Content[BSSID_WCID].HTPhyMode.word;
-
-#ifdef DOT11_N_SUPPORT
-    if (ht_setting.field.MODE >= MODE_HTMIX)
-    {
-//    	rate_index = 12 + ((UCHAR)ht_setting.field.BW *16) + ((UCHAR)ht_setting.field.ShortGI *32) + ((UCHAR)ht_setting.field.MCS);
-    	rate_index = 12 + ((UCHAR)ht_setting.field.BW *24) + ((UCHAR)ht_setting.field.ShortGI *48) + ((UCHAR)ht_setting.field.MCS);
-    }
-    else
-#endif // DOT11_N_SUPPORT //
-    if (ht_setting.field.MODE == MODE_OFDM)
-    	rate_index = (UCHAR)(ht_setting.field.MCS) + 4;
-    else if (ht_setting.field.MODE == MODE_CCK)
-    	rate_index = (UCHAR)(ht_setting.field.MCS);
-
-    if (rate_index < 0)
-        rate_index = 0;
-
-    if (rate_index > rate_count)
-        rate_index = rate_count;
-
-    wrqu->bitrate.value = ralinkrate[rate_index] * 500000;
-    wrqu->bitrate.disabled = 0;
-
-    return 0;
-}
-
-static const iw_handler rt_handler[] =
-{
-	(iw_handler) NULL,			            /* SIOCSIWCOMMIT */
-	(iw_handler) rt_ioctl_giwname,			/* SIOCGIWNAME   */
-	(iw_handler) NULL,			            /* SIOCSIWNWID   */
-	(iw_handler) NULL,			            /* SIOCGIWNWID   */
-	(iw_handler) rt_ioctl_siwfreq,		    /* SIOCSIWFREQ   */
-	(iw_handler) rt_ioctl_giwfreq,		    /* SIOCGIWFREQ   */
-	(iw_handler) rt_ioctl_siwmode,		    /* SIOCSIWMODE   */
-	(iw_handler) rt_ioctl_giwmode,		    /* SIOCGIWMODE   */
-	(iw_handler) NULL,		                /* SIOCSIWSENS   */
-	(iw_handler) NULL,		                /* SIOCGIWSENS   */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWRANGE  */
-	(iw_handler) rt_ioctl_giwrange,		    /* SIOCGIWRANGE  */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWPRIV   */
-	(iw_handler) NULL /* kernel code */,    /* SIOCGIWPRIV   */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWSTATS  */
-	(iw_handler) rt28xx_get_wireless_stats /* kernel code */,    /* SIOCGIWSTATS  */
-	(iw_handler) NULL,		                /* SIOCSIWSPY    */
-	(iw_handler) NULL,		                /* SIOCGIWSPY    */
-	(iw_handler) NULL,				        /* SIOCSIWTHRSPY */
-	(iw_handler) NULL,				        /* SIOCGIWTHRSPY */
-	(iw_handler) rt_ioctl_siwap,            /* SIOCSIWAP     */
-	(iw_handler) rt_ioctl_giwap,		    /* SIOCGIWAP     */
-#ifdef SIOCSIWMLME
-	(iw_handler) rt_ioctl_siwmlme,	        /* SIOCSIWMLME   */
-#else
-	(iw_handler) NULL,				        /* SIOCSIWMLME */
-#endif // SIOCSIWMLME //
-	(iw_handler) rt_ioctl_iwaplist,		    /* SIOCGIWAPLIST */
-#ifdef SIOCGIWSCAN
-	(iw_handler) rt_ioctl_siwscan,		    /* SIOCSIWSCAN   */
-	(iw_handler) rt_ioctl_giwscan,		    /* SIOCGIWSCAN   */
-#else
-	(iw_handler) NULL,				        /* SIOCSIWSCAN   */
-	(iw_handler) NULL,				        /* SIOCGIWSCAN   */
-#endif /* SIOCGIWSCAN */
-	(iw_handler) rt_ioctl_siwessid,		    /* SIOCSIWESSID  */
-	(iw_handler) rt_ioctl_giwessid,		    /* SIOCGIWESSID  */
-	(iw_handler) rt_ioctl_siwnickn,		    /* SIOCSIWNICKN  */
-	(iw_handler) rt_ioctl_giwnickn,		    /* SIOCGIWNICKN  */
-	(iw_handler) NULL,				        /* -- hole --    */
-	(iw_handler) NULL,				        /* -- hole --    */
-	(iw_handler) rt_ioctl_siwrate,          /* SIOCSIWRATE   */
-	(iw_handler) rt_ioctl_giwrate,          /* SIOCGIWRATE   */
-	(iw_handler) rt_ioctl_siwrts,		    /* SIOCSIWRTS    */
-	(iw_handler) rt_ioctl_giwrts,		    /* SIOCGIWRTS    */
-	(iw_handler) rt_ioctl_siwfrag,		    /* SIOCSIWFRAG   */
-	(iw_handler) rt_ioctl_giwfrag,		    /* SIOCGIWFRAG   */
-	(iw_handler) NULL,		                /* SIOCSIWTXPOW  */
-	(iw_handler) NULL,		                /* SIOCGIWTXPOW  */
-	(iw_handler) NULL,		                /* SIOCSIWRETRY  */
-	(iw_handler) NULL,		                /* SIOCGIWRETRY  */
-	(iw_handler) rt_ioctl_siwencode,		/* SIOCSIWENCODE */
-	(iw_handler) rt_ioctl_giwencode,		/* SIOCGIWENCODE */
-	(iw_handler) NULL,		                /* SIOCSIWPOWER  */
-	(iw_handler) NULL,		                /* SIOCGIWPOWER  */
-	(iw_handler) NULL,						/* -- hole -- */
-	(iw_handler) NULL,						/* -- hole -- */
-#if WIRELESS_EXT > 17
-    (iw_handler) rt_ioctl_siwgenie,         /* SIOCSIWGENIE  */
-	(iw_handler) rt_ioctl_giwgenie,         /* SIOCGIWGENIE  */
-	(iw_handler) rt_ioctl_siwauth,		    /* SIOCSIWAUTH   */
-	(iw_handler) rt_ioctl_giwauth,		    /* SIOCGIWAUTH   */
-	(iw_handler) rt_ioctl_siwencodeext,	    /* SIOCSIWENCODEEXT */
-	(iw_handler) rt_ioctl_giwencodeext,		/* SIOCGIWENCODEEXT */
-	(iw_handler) rt_ioctl_siwpmksa,         /* SIOCSIWPMKSA  */
-#endif
-};
-
-static const iw_handler rt_priv_handlers[] = {
-	(iw_handler) NULL, /* + 0x00 */
-	(iw_handler) NULL, /* + 0x01 */
-#ifndef CONFIG_AP_SUPPORT
-	(iw_handler) rt_ioctl_setparam, /* + 0x02 */
-#else
-	(iw_handler) NULL, /* + 0x02 */
-#endif // CONFIG_AP_SUPPORT //
-#ifdef DBG
-	(iw_handler) rt_private_ioctl_bbp, /* + 0x03 */
-#else
-	(iw_handler) NULL, /* + 0x03 */
-#endif
-	(iw_handler) NULL, /* + 0x04 */
-	(iw_handler) NULL, /* + 0x05 */
-	(iw_handler) NULL, /* + 0x06 */
-	(iw_handler) NULL, /* + 0x07 */
-	(iw_handler) NULL, /* + 0x08 */
-	(iw_handler) rt_private_get_statistics, /* + 0x09 */
-	(iw_handler) NULL, /* + 0x0A */
-	(iw_handler) NULL, /* + 0x0B */
-	(iw_handler) NULL, /* + 0x0C */
-	(iw_handler) NULL, /* + 0x0D */
-	(iw_handler) NULL, /* + 0x0E */
-	(iw_handler) NULL, /* + 0x0F */
-	(iw_handler) NULL, /* + 0x10 */
-	(iw_handler) rt_private_show, /* + 0x11 */
-    (iw_handler) NULL, /* + 0x12 */
-	(iw_handler) NULL, /* + 0x13 */
-	(iw_handler) NULL, /* + 0x15 */
-	(iw_handler) NULL, /* + 0x17 */
-	(iw_handler) NULL, /* + 0x18 */
-};
-
-const struct iw_handler_def rt28xx_iw_handler_def =
-{
-#define	N(a)	(sizeof (a) / sizeof (a[0]))
-	.standard	= (iw_handler *) rt_handler,
-	.num_standard	= sizeof(rt_handler) / sizeof(iw_handler),
-	.private	= (iw_handler *) rt_priv_handlers,
-	.num_private		= N(rt_priv_handlers),
-	.private_args	= (struct iw_priv_args *) privtab,
-	.num_private_args	= N(privtab),
-#if IW_HANDLER_VERSION >= 7
-    .get_wireless_stats = rt28xx_get_wireless_stats,
-#endif
-};
-
-INT RTMPSetInformation(
-    IN  PRTMP_ADAPTER pAdapter,
-    IN  OUT struct ifreq    *rq,
-    IN  INT                 cmd)
-{
-    struct iwreq                        *wrq = (struct iwreq *) rq;
-    NDIS_802_11_SSID                    Ssid;
-    NDIS_802_11_MAC_ADDRESS             Bssid;
-    RT_802_11_PHY_MODE                  PhyMode;
-    RT_802_11_STA_CONFIG                StaConfig;
-    NDIS_802_11_RATES                   aryRates;
-    RT_802_11_PREAMBLE                  Preamble;
-    NDIS_802_11_WEP_STATUS              WepStatus;
-    NDIS_802_11_AUTHENTICATION_MODE     AuthMode = Ndis802_11AuthModeMax;
-    NDIS_802_11_NETWORK_INFRASTRUCTURE  BssType;
-    NDIS_802_11_RTS_THRESHOLD           RtsThresh;
-    NDIS_802_11_FRAGMENTATION_THRESHOLD FragThresh;
-    NDIS_802_11_POWER_MODE              PowerMode;
-    PNDIS_802_11_KEY                    pKey = NULL;
-    PNDIS_802_11_WEP			        pWepKey =NULL;
-    PNDIS_802_11_REMOVE_KEY             pRemoveKey = NULL;
-    NDIS_802_11_CONFIGURATION           Config, *pConfig = NULL;
-    NDIS_802_11_NETWORK_TYPE            NetType;
-    ULONG                               Now;
-    UINT                                KeyIdx = 0;
-    INT                                 Status = NDIS_STATUS_SUCCESS, MaxPhyMode = PHY_11G;
-    ULONG                               PowerTemp;
-    BOOLEAN                             RadioState;
-    BOOLEAN                             StateMachineTouched = FALSE;
-#ifdef DOT11_N_SUPPORT
-	OID_SET_HT_PHYMODE					HT_PhyMode;	//11n ,kathy
-#endif // DOT11_N_SUPPORT //
-#ifdef WPA_SUPPLICANT_SUPPORT
-    PNDIS_802_11_PMKID                  pPmkId = NULL;
-    BOOLEAN				                IEEE8021xState = FALSE;
-    BOOLEAN				                IEEE8021x_required_keys = FALSE;
-    UCHAR                               wpa_supplicant_enable = 0;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef SNMP_SUPPORT
-	TX_RTY_CFG_STRUC			tx_rty_cfg;
-	ULONG						ShortRetryLimit, LongRetryLimit;
-	UCHAR						ctmp;
-#endif // SNMP_SUPPORT //
-
-
-
-#ifdef DOT11_N_SUPPORT
-	MaxPhyMode = PHY_11N_5G;
-#endif // DOT11_N_SUPPORT //
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("-->RTMPSetInformation(),	0x%08x\n", cmd&0x7FFF));
-    switch(cmd & 0x7FFF) {
-        case RT_OID_802_11_COUNTRY_REGION:
-            if (wrq->u.data.length < sizeof(UCHAR))
-                Status = -EINVAL;
-			// Only avaliable when EEPROM not programming
-            else if (!(pAdapter->CommonCfg.CountryRegion & 0x80) && !(pAdapter->CommonCfg.CountryRegionForABand & 0x80))
-            {
-                ULONG   Country;
-                UCHAR	TmpPhy;
-
-				Status = copy_from_user(&Country, wrq->u.data.pointer, wrq->u.data.length);
-				pAdapter->CommonCfg.CountryRegion = (UCHAR)(Country & 0x000000FF);
-				pAdapter->CommonCfg.CountryRegionForABand = (UCHAR)((Country >> 8) & 0x000000FF);
-                TmpPhy = pAdapter->CommonCfg.PhyMode;
-				pAdapter->CommonCfg.PhyMode = 0xff;
-				// Build all corresponding channel information
-				RTMPSetPhyMode(pAdapter, TmpPhy);
-#ifdef DOT11_N_SUPPORT
-				SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_COUNTRY_REGION (A:%d  B/G:%d)\n", pAdapter->CommonCfg.CountryRegionForABand,
-				    pAdapter->CommonCfg.CountryRegion));
-            }
-            break;
-        case OID_802_11_BSSID_LIST_SCAN:
- #ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-            Now = jiffies;
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_BSSID_LIST_SCAN, TxCnt = %d \n", pAdapter->RalinkCounters.LastOneSecTotalTxCount));
-
-            if (MONITOR_ON(pAdapter))
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is in Monitor Mode now !!!\n"));
-                break;
-            }
-
-			//Benson add 20080527, when radio off, sta don't need to scan
-			if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_RADIO_OFF))
-				break;
-
-			if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-			{
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is scanning now !!!\n"));
-				pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-				Status = NDIS_STATUS_SUCCESS;
-                break;
-            }
-
-			if (pAdapter->RalinkCounters.LastOneSecTotalTxCount > 100)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-				Status = NDIS_STATUS_SUCCESS;
-				pAdapter->StaCfg.ScanCnt = 99;		// Prevent auto scan triggered by this OID
-				break;
-            }
-
-            if ((OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED)) &&
-				((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)) &&
-                (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, Port Not Secured! ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-				Status = NDIS_STATUS_SUCCESS;
-				pAdapter->StaCfg.ScanCnt = 99;		// Prevent auto scan triggered by this OID
-				break;
-            }
-
-
-            if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-            {
-                RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-            }
-
-            // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-            // this request, because this request is initiated by NDIS.
-            pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-            // Reset allowed scan retries
-            pAdapter->StaCfg.ScanCnt = 0;
-            pAdapter->StaCfg.LastScanTime = Now;
-
-			pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-            RTMP_SET_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-            MlmeEnqueue(pAdapter,
-                        MLME_CNTL_STATE_MACHINE,
-                        OID_802_11_BSSID_LIST_SCAN,
-                        0,
-                        NULL);
-
-            Status = NDIS_STATUS_SUCCESS;
-            StateMachineTouched = TRUE;
-            break;
-        case OID_802_11_SSID:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_SSID))
-                Status = -EINVAL;
-            else
-            {
-            	PCHAR pSsidString = NULL;
-                Status = copy_from_user(&Ssid, wrq->u.data.pointer, wrq->u.data.length);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SSID (Len=%d,Ssid=%s)\n", Ssid.SsidLength, Ssid.Ssid));
-                if (Ssid.SsidLength > MAX_LEN_OF_SSID)
-                    Status = -EINVAL;
-                else
-                {
-                	if (Ssid.SsidLength == 0)
-                	{
-                		Set_SSID_Proc(pAdapter, "");
-                	}
-					else
-                	{
-	                	pSsidString = (CHAR *) kmalloc(MAX_LEN_OF_SSID+1, MEM_ALLOC_FLAG);
-						if (pSsidString)
-						{
-							NdisZeroMemory(pSsidString, MAX_LEN_OF_SSID+1);
-							NdisMoveMemory(pSsidString, Ssid.Ssid, Ssid.SsidLength);
-	                		Set_SSID_Proc(pAdapter, pSsidString);
-							kfree(pSsidString);
-						}
-						else
-							Status = -ENOMEM;
-                	}
-                }
-            }
-            break;
-        case OID_802_11_BSSID:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-            if (wrq->u.data.length != sizeof(NDIS_802_11_MAC_ADDRESS))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Bssid, wrq->u.data.pointer, wrq->u.data.length);
-
-                // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-                // this request, because this request is initiated by NDIS.
-                pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-
-				// Prevent to connect AP again in STAMlmePeriodicExec
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-
-                // Reset allowed scan retries
-				pAdapter->StaCfg.ScanCnt = 0;
-
-                if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-                {
-                    RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-                    DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-                }
-                MlmeEnqueue(pAdapter,
-                            MLME_CNTL_STATE_MACHINE,
-                            OID_802_11_BSSID,
-                            sizeof(NDIS_802_11_MAC_ADDRESS),
-                            (VOID *)&Bssid);
-                Status = NDIS_STATUS_SUCCESS;
-                StateMachineTouched = TRUE;
-
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_BSSID %02x:%02x:%02x:%02x:%02x:%02x\n",
-                                        Bssid[0], Bssid[1], Bssid[2], Bssid[3], Bssid[4], Bssid[5]));
-            }
-            break;
-        case RT_OID_802_11_RADIO:
-            if (wrq->u.data.length != sizeof(BOOLEAN))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&RadioState, wrq->u.data.pointer, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_RADIO (=%d)\n", RadioState));
-                if (pAdapter->StaCfg.bSwRadio != RadioState)
-                {
-                    pAdapter->StaCfg.bSwRadio = RadioState;
-                    if (pAdapter->StaCfg.bRadio != (pAdapter->StaCfg.bHwRadio && pAdapter->StaCfg.bSwRadio))
-                    {
-                        pAdapter->StaCfg.bRadio = (pAdapter->StaCfg.bHwRadio && pAdapter->StaCfg.bSwRadio);
-                        if (pAdapter->StaCfg.bRadio == TRUE)
-                        {
-                            MlmeRadioOn(pAdapter);
-                            // Update extra information
-							pAdapter->ExtraInfo = EXTRA_INFO_CLEAR;
-                        }
-                        else
-                        {
-                            MlmeRadioOff(pAdapter);
-                            // Update extra information
-							pAdapter->ExtraInfo = SW_RADIO_OFF;
-                        }
-                    }
-                }
-            }
-            break;
-        case RT_OID_802_11_PHY_MODE:
-            if (wrq->u.data.length != sizeof(RT_802_11_PHY_MODE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&PhyMode, wrq->u.data.pointer, wrq->u.data.length);
-				if (PhyMode <= MaxPhyMode)
-				{
-                	RTMPSetPhyMode(pAdapter, PhyMode);
-#ifdef DOT11_N_SUPPORT
-					SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-				}
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_PHY_MODE (=%d)\n", PhyMode));
-            }
-            break;
-        case RT_OID_802_11_STA_CONFIG:
-            if (wrq->u.data.length != sizeof(RT_802_11_STA_CONFIG))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&StaConfig, wrq->u.data.pointer, wrq->u.data.length);
-                pAdapter->CommonCfg.bEnableTxBurst = StaConfig.EnableTxBurst;
-                pAdapter->CommonCfg.UseBGProtection = StaConfig.UseBGProtection;
-                pAdapter->CommonCfg.bUseShortSlotTime = 1; // 2003-10-30 always SHORT SLOT capable
-                if ((pAdapter->CommonCfg.PhyMode != StaConfig.AdhocMode) &&
-					(StaConfig.AdhocMode <= MaxPhyMode))
-                {
-                    // allow dynamic change of "USE OFDM rate or not" in ADHOC mode
-                    // if setting changed, need to reset current TX rate as well as BEACON frame format
-                    if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-                    {
-						pAdapter->CommonCfg.PhyMode = StaConfig.AdhocMode;
-                    	RTMPSetPhyMode(pAdapter, PhyMode);
-                        MlmeUpdateTxRates(pAdapter, FALSE, 0);
-                        MakeIbssBeacon(pAdapter);           // re-build BEACON frame
-                        AsicEnableIbssSync(pAdapter);   // copy to on-chip memory
-                    }
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_STA_CONFIG (Burst=%d, Protection=%ld,ShortSlot=%d\n",
-                                        pAdapter->CommonCfg.bEnableTxBurst,
-                                        pAdapter->CommonCfg.UseBGProtection,
-                                        pAdapter->CommonCfg.bUseShortSlotTime));
-            }
-            break;
-        case OID_802_11_DESIRED_RATES:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_RATES))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&aryRates, wrq->u.data.pointer, wrq->u.data.length);
-                NdisZeroMemory(pAdapter->CommonCfg.DesireRate, MAX_LEN_OF_SUPPORTED_RATES);
-                NdisMoveMemory(pAdapter->CommonCfg.DesireRate, &aryRates, sizeof(NDIS_802_11_RATES));
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DESIRED_RATES (%02x,%02x,%02x,%02x,%02x,%02x,%02x,%02x)\n",
-                    pAdapter->CommonCfg.DesireRate[0],pAdapter->CommonCfg.DesireRate[1],
-                    pAdapter->CommonCfg.DesireRate[2],pAdapter->CommonCfg.DesireRate[3],
-                    pAdapter->CommonCfg.DesireRate[4],pAdapter->CommonCfg.DesireRate[5],
-                    pAdapter->CommonCfg.DesireRate[6],pAdapter->CommonCfg.DesireRate[7] ));
-                // Changing DesiredRate may affect the MAX TX rate we used to TX frames out
-                MlmeUpdateTxRates(pAdapter, FALSE, 0);
-            }
-            break;
-        case RT_OID_802_11_PREAMBLE:
-            if (wrq->u.data.length != sizeof(RT_802_11_PREAMBLE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Preamble, wrq->u.data.pointer, wrq->u.data.length);
-                if (Preamble == Rt802_11PreambleShort)
-                {
-                    pAdapter->CommonCfg.TxPreamble = Preamble;
-                    MlmeSetTxPreamble(pAdapter, Rt802_11PreambleShort);
-                }
-                else if ((Preamble == Rt802_11PreambleLong) || (Preamble == Rt802_11PreambleAuto))
-                {
-                    // if user wants AUTO, initialize to LONG here, then change according to AP's
-                    // capability upon association.
-                    pAdapter->CommonCfg.TxPreamble = Preamble;
-                    MlmeSetTxPreamble(pAdapter, Rt802_11PreambleLong);
-                }
-                else
-                {
-                    Status = -EINVAL;
-                    break;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_PREAMBLE (=%d)\n", Preamble));
-            }
-            break;
-        case OID_802_11_WEP_STATUS:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_WEP_STATUS))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&WepStatus, wrq->u.data.pointer, wrq->u.data.length);
-                // Since TKIP, AES, WEP are all supported. It should not have any invalid setting
-                if (WepStatus <= Ndis802_11Encryption3KeyAbsent)
-                {
-                    if (pAdapter->StaCfg.WepStatus != WepStatus)
-                    {
-                        // Config has changed
-                        pAdapter->bConfigChanged = TRUE;
-                    }
-                    pAdapter->StaCfg.WepStatus     = WepStatus;
-                    pAdapter->StaCfg.OrigWepStatus = WepStatus;
-                    pAdapter->StaCfg.PairCipher    = WepStatus;
-                	pAdapter->StaCfg.GroupCipher   = WepStatus;
-                }
-                else
-                {
-                    Status  = -EINVAL;
-                    break;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEP_STATUS (=%d)\n",WepStatus));
-            }
-            break;
-        case OID_802_11_AUTHENTICATION_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_AUTHENTICATION_MODE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&AuthMode, wrq->u.data.pointer, wrq->u.data.length);
-                if (AuthMode > Ndis802_11AuthModeMax)
-                {
-                    Status  = -EINVAL;
-                    break;
-                }
-                else
-                {
-                    if (pAdapter->StaCfg.AuthMode != AuthMode)
-                    {
-                        // Config has changed
-                        pAdapter->bConfigChanged = TRUE;
-                    }
-                    pAdapter->StaCfg.AuthMode = AuthMode;
-                }
-                pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_AUTHENTICATION_MODE (=%d) \n",pAdapter->StaCfg.AuthMode));
-            }
-            break;
-        case OID_802_11_INFRASTRUCTURE_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_NETWORK_INFRASTRUCTURE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&BssType, wrq->u.data.pointer, wrq->u.data.length);
-
-				if (BssType == Ndis802_11IBSS)
-					Set_NetworkType_Proc(pAdapter, "Adhoc");
-				else if (BssType == Ndis802_11Infrastructure)
-					Set_NetworkType_Proc(pAdapter, "Infra");
-				else if (BssType == Ndis802_11Monitor)
-					Set_NetworkType_Proc(pAdapter, "Monitor");
-				else
-				{
-					Status  = -EINVAL;
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_INFRASTRUCTURE_MODE (unknown)\n"));
-				}
-			}
-			break;
-	 case OID_802_11_REMOVE_WEP:
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_WEP\n"));
-            if (wrq->u.data.length != sizeof(NDIS_802_11_KEY_INDEX))
-            {
-				Status = -EINVAL;
-            }
-            else
-            {
-				KeyIdx = *(NDIS_802_11_KEY_INDEX *) wrq->u.data.pointer;
-
-				if (KeyIdx & 0x80000000)
-				{
-					// Should never set default bit when remove key
-					Status = -EINVAL;
-				}
-				else
-				{
-					KeyIdx = KeyIdx & 0x0fffffff;
-					if (KeyIdx >= 4){
-						Status = -EINVAL;
-					}
-					else
-					{
-						pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = 0;
-						pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_NONE;
-						AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)KeyIdx);
-					}
-				}
-            }
-            break;
-        case RT_OID_802_11_RESET_COUNTERS:
-            NdisZeroMemory(&pAdapter->WlanCounters, sizeof(COUNTER_802_11));
-            NdisZeroMemory(&pAdapter->Counters8023, sizeof(COUNTER_802_3));
-            NdisZeroMemory(&pAdapter->RalinkCounters, sizeof(COUNTER_RALINK));
-            pAdapter->Counters8023.RxNoBuffer   = 0;
-			pAdapter->Counters8023.GoodReceives = 0;
-			pAdapter->Counters8023.RxNoBuffer   = 0;
-#ifdef RT2870
-			pAdapter->BulkOutComplete	= 0;
-			pAdapter->BulkOutCompleteOther= 0;
-			pAdapter->BulkOutCompleteCancel = 0;
-			pAdapter->BulkOutReq = 0;
-			pAdapter->BulkInReq= 0;
-			pAdapter->BulkInComplete = 0;
-			pAdapter->BulkInCompleteFail = 0;
-#endif // RT2870 //
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_RESET_COUNTERS \n"));
-            break;
-        case OID_802_11_RTS_THRESHOLD:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_RTS_THRESHOLD))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&RtsThresh, wrq->u.data.pointer, wrq->u.data.length);
-                if (RtsThresh > MAX_RTS_THRESHOLD)
-                    Status  = -EINVAL;
-                else
-                    pAdapter->CommonCfg.RtsThreshold = (USHORT)RtsThresh;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_RTS_THRESHOLD (=%ld)\n",RtsThresh));
-            break;
-        case OID_802_11_FRAGMENTATION_THRESHOLD:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_FRAGMENTATION_THRESHOLD))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&FragThresh, wrq->u.data.pointer, wrq->u.data.length);
-                pAdapter->CommonCfg.bUseZeroToDisableFragment = FALSE;
-                if (FragThresh > MAX_FRAG_THRESHOLD || FragThresh < MIN_FRAG_THRESHOLD)
-                {
-                    if (FragThresh == 0)
-                    {
-                        pAdapter->CommonCfg.FragmentThreshold = MAX_FRAG_THRESHOLD;
-                        pAdapter->CommonCfg.bUseZeroToDisableFragment = TRUE;
-                    }
-                    else
-                        Status  = -EINVAL;
-                }
-                else
-                    pAdapter->CommonCfg.FragmentThreshold = (USHORT)FragThresh;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_FRAGMENTATION_THRESHOLD (=%ld) \n",FragThresh));
-            break;
-        case OID_802_11_POWER_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_POWER_MODE))
-                Status = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&PowerMode, wrq->u.data.pointer, wrq->u.data.length);
-                if (PowerMode == Ndis802_11PowerModeCAM)
-                	Set_PSMode_Proc(pAdapter, "CAM");
-                else if (PowerMode == Ndis802_11PowerModeMAX_PSP)
-                	Set_PSMode_Proc(pAdapter, "Max_PSP");
-                else if (PowerMode == Ndis802_11PowerModeFast_PSP)
-					Set_PSMode_Proc(pAdapter, "Fast_PSP");
-                else if (PowerMode == Ndis802_11PowerModeLegacy_PSP)
-					Set_PSMode_Proc(pAdapter, "Legacy_PSP");
-                else
-                    Status = -EINVAL;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_POWER_MODE (=%d)\n",PowerMode));
-            break;
-         case RT_OID_802_11_TX_POWER_LEVEL_1:
-			if (wrq->u.data.length  < sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&PowerTemp, wrq->u.data.pointer, wrq->u.data.length);
-				if (PowerTemp > 100)
-					PowerTemp = 0xffffffff;  // AUTO
-				pAdapter->CommonCfg.TxPowerDefault = PowerTemp; //keep current setting.
-					pAdapter->CommonCfg.TxPowerPercentage = pAdapter->CommonCfg.TxPowerDefault;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_TX_POWER_LEVEL_1 (=%ld)\n", pAdapter->CommonCfg.TxPowerPercentage));
-			}
-	        break;
-		case OID_802_11_NETWORK_TYPE_IN_USE:
-			if (wrq->u.data.length != sizeof(NDIS_802_11_NETWORK_TYPE))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&NetType, wrq->u.data.pointer, wrq->u.data.length);
-
-				if (NetType == Ndis802_11DS)
-					RTMPSetPhyMode(pAdapter, PHY_11B);
-				else if (NetType == Ndis802_11OFDM24)
-					RTMPSetPhyMode(pAdapter, PHY_11BG_MIXED);
-				else if (NetType == Ndis802_11OFDM5)
-					RTMPSetPhyMode(pAdapter, PHY_11A);
-				else
-					Status = -EINVAL;
-#ifdef DOT11_N_SUPPORT
-				if (Status == NDIS_STATUS_SUCCESS)
-					SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_NETWORK_TYPE_IN_USE (=%d)\n",NetType));
-		    }
-			break;
-        // For WPA PSK PMK key
-        case RT_OID_802_11_ADD_WPA:
-            pKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-
-            Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA, Failed!!\n"));
-            }
-            else
-            {
-                if ((pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPAPSK) &&
-				    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-				    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone) )
-                {
-                    Status = -EOPNOTSUPP;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA, Failed!! [AuthMode != WPAPSK/WPA2PSK/WPANONE]\n"));
-                }
-                else if ((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-						 (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-						 (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPANone) )     // Only for WPA PSK mode
-				{
-                    NdisMoveMemory(pAdapter->StaCfg.PMK, &pKey->KeyMaterial, pKey->KeyLength);
-                    // Use RaConfig as PSK agent.
-                    // Start STA supplicant state machine
-                    if (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone)
-                        pAdapter->StaCfg.WpaState = SS_START;
-
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-                }
-                else
-                {
-                    pAdapter->StaCfg.WpaState = SS_NOTUSE;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-                }
-            }
-            kfree(pKey);
-            break;
-        case OID_802_11_REMOVE_KEY:
-            pRemoveKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pRemoveKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-
-            Status = copy_from_user(pRemoveKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pRemoveKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!\n"));
-            }
-            else
-            {
-                if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-                {
-                    RTMPWPARemoveKeyProc(pAdapter, pRemoveKey);
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Remove WPA Key!!\n"));
-                }
-                else
-                {
-                    KeyIdx = pRemoveKey->KeyIndex;
-
-                    if (KeyIdx & 0x80000000)
-                    {
-                        // Should never set default bit when remove key
-                        Status  = -EINVAL;
-                        DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!(Should never set default bit when remove key)\n"));
-                    }
-                    else
-                    {
-                        KeyIdx = KeyIdx & 0x0fffffff;
-                        if (KeyIdx > 3)
-                        {
-                            Status  = -EINVAL;
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!(KeyId[%d] out of range)\n", KeyIdx));
-                        }
-                        else
-                        {
-                            pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = 0;
-                            pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_NONE;
-                            AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)KeyIdx);
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY (id=0x%x, Len=%d-byte)\n", pRemoveKey->KeyIndex, pRemoveKey->Length));
-                        }
-                    }
-                }
-            }
-            kfree(pRemoveKey);
-            break;
-        // New for WPA
-        case OID_802_11_ADD_KEY:
-            pKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-            Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_KEY, Failed!!\n"));
-            }
-            else
-            {
-                RTMPAddKey(pAdapter, pKey);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_KEY (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-            }
-            kfree(pKey);
-            break;
-        case OID_802_11_CONFIGURATION:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_CONFIGURATION))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Config, wrq->u.data.pointer, wrq->u.data.length);
-                pConfig = &Config;
-
-                if ((pConfig->BeaconPeriod >= 20) && (pConfig->BeaconPeriod <=400))
-                     pAdapter->CommonCfg.BeaconPeriod = (USHORT) pConfig->BeaconPeriod;
-
-                pAdapter->StaActive.AtimWin = (USHORT) pConfig->ATIMWindow;
-                MAP_KHZ_TO_CHANNEL_ID(pConfig->DSConfig, pAdapter->CommonCfg.Channel);
-                //
-				// Save the channel on MlmeAux for CntlOidRTBssidProc used.
-				//
-				pAdapter->MlmeAux.Channel = pAdapter->CommonCfg.Channel;
-
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_CONFIGURATION (BeacnPeriod=%ld,AtimW=%ld,Ch=%d)\n",
-                    pConfig->BeaconPeriod, pConfig->ATIMWindow, pAdapter->CommonCfg.Channel));
-                // Config has changed
-                pAdapter->bConfigChanged = TRUE;
-            }
-            break;
-#ifdef DOT11_N_SUPPORT
-		case RT_OID_802_11_SET_HT_PHYMODE:
-			if (wrq->u.data.length	!= sizeof(OID_SET_HT_PHYMODE))
-				Status = -EINVAL;
-			else
-			{
-			    POID_SET_HT_PHYMODE	pHTPhyMode = &HT_PhyMode;
-
-				Status = copy_from_user(&HT_PhyMode, wrq->u.data.pointer, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::pHTPhyMode	(PhyMode = %d,TransmitNo = %d, HtMode =	%d,	ExtOffset =	%d , MCS = %d, BW =	%d,	STBC = %d, SHORTGI = %d) \n",
-				pHTPhyMode->PhyMode, pHTPhyMode->TransmitNo,pHTPhyMode->HtMode,pHTPhyMode->ExtOffset,
-				pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC,	pHTPhyMode->SHORTGI));
-				if (pAdapter->CommonCfg.PhyMode	>= PHY_11ABGN_MIXED)
-					RTMPSetHT(pAdapter,	pHTPhyMode);
-			}
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_HT_PHYMODE(MCS=%d,BW=%d,SGI=%d,STBC=%d)\n",
-				pAdapter->StaCfg.HTPhyMode.field.MCS, pAdapter->StaCfg.HTPhyMode.field.BW, pAdapter->StaCfg.HTPhyMode.field.ShortGI,
-				pAdapter->StaCfg.HTPhyMode.field.STBC));
-			break;
-#endif // DOT11_N_SUPPORT //
-		case RT_OID_802_11_SET_APSD_SETTING:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				ULONG apsd ;
-				Status = copy_from_user(&apsd, wrq->u.data.pointer,	wrq->u.data.length);
-
-				/*-------------------------------------------------------------------
-				|B31~B7	|	B6~B5	 |	 B4	 |	 B3	 |	B2	 |	B1	 |	   B0		|
-				---------------------------------------------------------------------
-				| Rsvd	| Max SP Len | AC_VO | AC_VI | AC_BK | AC_BE | APSD	Capable	|
-				---------------------------------------------------------------------*/
-				pAdapter->CommonCfg.bAPSDCapable = (apsd & 0x00000001) ? TRUE :	FALSE;
-				pAdapter->CommonCfg.bAPSDAC_BE = ((apsd	& 0x00000002) >> 1)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_BK = ((apsd	& 0x00000004) >> 2)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_VI = ((apsd	& 0x00000008) >> 3)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_VO = ((apsd	& 0x00000010) >> 4)	? TRUE : FALSE;
-				pAdapter->CommonCfg.MaxSPLength	= (UCHAR)((apsd	& 0x00000060) >> 5);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_APSD_SETTING (apsd=0x%lx, APSDCap=%d, [BE,BK,VI,VO]=[%d/%d/%d/%d],	MaxSPLen=%d)\n", apsd, pAdapter->CommonCfg.bAPSDCapable,
-					pAdapter->CommonCfg.bAPSDAC_BE,	pAdapter->CommonCfg.bAPSDAC_BK,	pAdapter->CommonCfg.bAPSDAC_VI,	pAdapter->CommonCfg.bAPSDAC_VO,	pAdapter->CommonCfg.MaxSPLength));
-			}
-			break;
-
-		case RT_OID_802_11_SET_APSD_PSM:
-			if (wrq->u.data.length	!= sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				// Driver needs	to notify AP when PSM changes
-				Status = copy_from_user(&pAdapter->CommonCfg.bAPSDForcePowerSave, wrq->u.data.pointer, wrq->u.data.length);
-				if (pAdapter->CommonCfg.bAPSDForcePowerSave	!= pAdapter->StaCfg.Psm)
-				{
-					MlmeSetPsmBit(pAdapter,	pAdapter->CommonCfg.bAPSDForcePowerSave);
-					RTMPSendNullFrame(pAdapter,	pAdapter->CommonCfg.TxRate,	TRUE);
-				}
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_APSD_PSM (bAPSDForcePowerSave:%d)\n",	pAdapter->CommonCfg.bAPSDForcePowerSave));
-			}
-			break;
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_SET_DLS:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				BOOLEAN	oldvalue = pAdapter->CommonCfg.bDLSCapable;
-				Status = copy_from_user(&pAdapter->CommonCfg.bDLSCapable, wrq->u.data.pointer, wrq->u.data.length);
-				if (oldvalue &&	!pAdapter->CommonCfg.bDLSCapable)
-				{
-					int	i;
-					// tear	down local dls table entry
-					for	(i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-					{
-						if (pAdapter->StaCfg.DLSEntry[i].Valid && (pAdapter->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-						{
-							pAdapter->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-							pAdapter->StaCfg.DLSEntry[i].Valid	= FALSE;
-							RTMPSendDLSTearDownFrame(pAdapter, pAdapter->StaCfg.DLSEntry[i].MacAddr);
-						}
-					}
-
-					// tear	down peer dls table	entry
-					for	(i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-					{
-						if (pAdapter->StaCfg.DLSEntry[i].Valid && (pAdapter->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-						{
-							pAdapter->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-							pAdapter->StaCfg.DLSEntry[i].Valid	= FALSE;
-							RTMPSendDLSTearDownFrame(pAdapter, pAdapter->StaCfg.DLSEntry[i].MacAddr);
-						}
-					}
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE,("Set::RT_OID_802_11_SET_DLS (=%d)\n", pAdapter->CommonCfg.bDLSCapable));
-			}
-			break;
-
-		case RT_OID_802_11_SET_DLS_PARAM:
-			if (wrq->u.data.length	!= sizeof(RT_802_11_DLS_UI))
-				Status = -EINVAL;
-			else
-			{
-				RT_802_11_DLS	Dls;
-
-				NdisZeroMemory(&Dls, sizeof(RT_802_11_DLS));
-				RTMPMoveMemory(&Dls, wrq->u.data.pointer, sizeof(RT_802_11_DLS_UI));
-				MlmeEnqueue(pAdapter,
-							MLME_CNTL_STATE_MACHINE,
-							RT_OID_802_11_SET_DLS_PARAM,
-							sizeof(RT_802_11_DLS),
-							&Dls);
-				DBGPRINT(RT_DEBUG_TRACE,("Set::RT_OID_802_11_SET_DLS_PARAM \n"));
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-		case RT_OID_802_11_SET_WMM:
-			if (wrq->u.data.length	!= sizeof(BOOLEAN))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&pAdapter->CommonCfg.bWmmCapable, wrq->u.data.pointer, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_WMM (=%d)	\n", pAdapter->CommonCfg.bWmmCapable));
-			}
-			break;
-
-		case OID_802_11_DISASSOCIATE:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-			//
-			// Set NdisRadioStateOff to	TRUE, instead of called	MlmeRadioOff.
-			// Later on, NDIS_802_11_BSSID_LIST_EX->NumberOfItems should be	0
-			// when	query OID_802_11_BSSID_LIST.
-			//
-			// TRUE:  NumberOfItems	will set to	0.
-			// FALSE: NumberOfItems	no change.
-			//
-			pAdapter->CommonCfg.NdisRadioStateOff =	TRUE;
-			// Set to immediately send the media disconnect	event
-			pAdapter->MlmeAux.CurrReqIsFromNdis	= TRUE;
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DISASSOCIATE	\n"));
-
-			if (INFRA_ON(pAdapter))
-			{
-				if (pAdapter->Mlme.CntlMachine.CurrState !=	CNTL_IDLE)
-				{
-					RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-					DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME	busy, reset	MLME state machine !!!\n"));
-				}
-
-				MlmeEnqueue(pAdapter,
-					MLME_CNTL_STATE_MACHINE,
-					OID_802_11_DISASSOCIATE,
-					0,
-					NULL);
-
-				StateMachineTouched	= TRUE;
-			}
-			break;
-
-#ifdef DOT11_N_SUPPORT
-		case RT_OID_802_11_SET_IMME_BA_CAP:
-				if (wrq->u.data.length != sizeof(OID_BACAP_STRUC))
-					Status = -EINVAL;
-				else
-				{
-					OID_BACAP_STRUC Orde ;
-					Status = copy_from_user(&Orde, wrq->u.data.pointer, wrq->u.data.length);
-					if (Orde.Policy > BA_NOTUSE)
-					{
-						Status = NDIS_STATUS_INVALID_DATA;
-					}
-					else if (Orde.Policy == BA_NOTUSE)
-					{
-						pAdapter->CommonCfg.BACapability.field.Policy = BA_NOTUSE;
-						pAdapter->CommonCfg.BACapability.field.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable = Orde.AmsduEnable;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize= Orde.AmsduSize;
-						pAdapter->CommonCfg.DesiredHtPhy.MimoPs= Orde.MMPSmode;
-						pAdapter->CommonCfg.BACapability.field.MMPSmode = Orde.MMPSmode;
-						// UPdata to HT IE
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.AMsduSize = Orde.AmsduSize;
-						pAdapter->CommonCfg.HtCapability.HtCapParm.MpduDensity = Orde.MpduDensity;
-					}
-					else
-					{
-                        pAdapter->CommonCfg.BACapability.field.AutoBA = Orde.AutoBA;
-						pAdapter->CommonCfg.BACapability.field.Policy = IMMED_BA; // we only support immediate BA.
-						pAdapter->CommonCfg.BACapability.field.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable = Orde.AmsduEnable;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize= Orde.AmsduSize;
-						pAdapter->CommonCfg.DesiredHtPhy.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.BACapability.field.MMPSmode = Orde.MMPSmode;
-
-						// UPdata to HT IE
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.AMsduSize = Orde.AmsduSize;
-						pAdapter->CommonCfg.HtCapability.HtCapParm.MpduDensity = Orde.MpduDensity;
-
-						if (pAdapter->CommonCfg.BACapability.field.RxBAWinLimit > MAX_RX_REORDERBUF)
-							pAdapter->CommonCfg.BACapability.field.RxBAWinLimit = MAX_RX_REORDERBUF;
-
-					}
-
-					pAdapter->CommonCfg.REGBACapability.word = pAdapter->CommonCfg.BACapability.word;
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::(Orde.AutoBA = %d) (Policy=%d)(ReBAWinLimit=%d)(TxBAWinLimit=%d)(AutoMode=%d)\n",Orde.AutoBA, pAdapter->CommonCfg.BACapability.field.Policy,
-						pAdapter->CommonCfg.BACapability.field.RxBAWinLimit,pAdapter->CommonCfg.BACapability.field.TxBAWinLimit, pAdapter->CommonCfg.BACapability.field.AutoBA));
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::(MimoPs = %d)(AmsduEnable = %d) (AmsduSize=%d)(MpduDensity=%d)\n",pAdapter->CommonCfg.DesiredHtPhy.MimoPs, pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable,
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize, pAdapter->CommonCfg.DesiredHtPhy.MpduDensity));
-				}
-
-				break;
-		case RT_OID_802_11_ADD_IMME_BA:
-			DBGPRINT(RT_DEBUG_TRACE, (" Set :: RT_OID_802_11_ADD_IMME_BA \n"));
-			if (wrq->u.data.length != sizeof(OID_ADD_BA_ENTRY))
-					Status = -EINVAL;
-			else
-			{
-				UCHAR		        index;
-				OID_ADD_BA_ENTRY    BA;
-				MAC_TABLE_ENTRY     *pEntry;
-
-				Status = copy_from_user(&BA, wrq->u.data.pointer, wrq->u.data.length);
-				if (BA.TID > 15)
-				{
-					Status = NDIS_STATUS_INVALID_DATA;
-					break;
-				}
-				else
-				{
-					//BATableInsertEntry
-					//As ad-hoc mode, BA pair is not limited to only BSSID. so add via OID.
-					index = BA.TID;
-					// in ad hoc mode, when adding BA pair, we should insert this entry into MACEntry too
-					pEntry = MacTableLookup(pAdapter, BA.MACAddr);
-					if (!pEntry)
-					{
-						DBGPRINT(RT_DEBUG_TRACE, ("RT_OID_802_11_ADD_IMME_BA. break on no connection.----:%x:%x\n", BA.MACAddr[4], BA.MACAddr[5]));
-						break;
-					}
-					if (BA.IsRecipient == FALSE)
-					{
-					    if (pEntry->bIAmBadAtheros == TRUE)
-							pAdapter->CommonCfg.BACapability.field.RxBAWinLimit = 0x10;
-
-						BAOriSessionSetUp(pAdapter, pEntry, index, 0, 100, TRUE);
-					}
-					else
-					{
-						//BATableInsertEntry(pAdapter, pEntry->Aid, BA.MACAddr, 0, 0xffff, BA.TID, BA.nMSDU, BA.IsRecipient);
-					}
-
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_IMME_BA. Rec = %d. Mac = %x:%x:%x:%x:%x:%x . \n",
-						BA.IsRecipient, BA.MACAddr[0], BA.MACAddr[1], BA.MACAddr[2], BA.MACAddr[2]
-						, BA.MACAddr[4], BA.MACAddr[5]));
-				}
-			}
-			break;
-
-		case RT_OID_802_11_TEAR_IMME_BA:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA \n"));
-			if (wrq->u.data.length != sizeof(OID_ADD_BA_ENTRY))
-					Status = -EINVAL;
-			else
-			{
-				POID_ADD_BA_ENTRY	pBA;
-				MAC_TABLE_ENTRY *pEntry;
-
-				pBA = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-				if (pBA == NULL)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA kmalloc() can't allocate enough memory\n"));
-					Status = NDIS_STATUS_FAILURE;
-				}
-				else
-				{
-					Status = copy_from_user(pBA, wrq->u.data.pointer, wrq->u.data.length);
-					DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA(TID=%d, bAllTid=%d)\n", pBA->TID, pBA->bAllTid));
-
-					if (!pBA->bAllTid && (pBA->TID > NUM_OF_TID))
-					{
-						Status = NDIS_STATUS_INVALID_DATA;
-						break;
-					}
-
-					if (pBA->IsRecipient == FALSE)
-					{
-						pEntry = MacTableLookup(pAdapter, pBA->MACAddr);
-						DBGPRINT(RT_DEBUG_TRACE, (" pBA->IsRecipient == FALSE\n"));
-						if (pEntry)
-						{
-							DBGPRINT(RT_DEBUG_TRACE, (" pBA->pEntry\n"));
-							BAOriSessionTearDown(pAdapter, pEntry->Aid, pBA->TID, FALSE, TRUE);
-						}
-						else
-							DBGPRINT(RT_DEBUG_TRACE, ("Set :: Not found pEntry \n"));
-					}
-					else
-					{
-						pEntry = MacTableLookup(pAdapter, pBA->MACAddr);
-						if (pEntry)
-						{
-							BARecSessionTearDown( pAdapter, (UCHAR)pEntry->Aid, pBA->TID, TRUE);
-						}
-						else
-							DBGPRINT(RT_DEBUG_TRACE, ("Set :: Not found pEntry \n"));
-					}
-					kfree(pBA);
-				}
-            }
-            break;
-#endif // DOT11_N_SUPPORT //
-
-        // For WPA_SUPPLICANT to set static wep key
-    	case OID_802_11_ADD_WEP:
-    	    pWepKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-    	    if(pWepKey == NULL)
-            {
-                Status = -ENOMEM;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed!!\n"));
-                break;
-            }
-            Status = copy_from_user(pWepKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (Status)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed (length mismatch)!!\n"));
-            }
-            else
-            {
-		        KeyIdx = pWepKey->KeyIndex & 0x0fffffff;
-                // KeyIdx must be 0 ~ 3
-                if (KeyIdx > 4)
-    			{
-                    Status  = -EINVAL;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed (KeyIdx must be smaller than 4)!!\n"));
-                }
-                else
-                {
-                    UCHAR CipherAlg = 0;
-                    PUCHAR Key;
-
-                    // set key material and key length
-                    NdisZeroMemory(pAdapter->SharedKey[BSS0][KeyIdx].Key, 16);
-                    pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = (UCHAR) pWepKey->KeyLength;
-                    NdisMoveMemory(pAdapter->SharedKey[BSS0][KeyIdx].Key, &pWepKey->KeyMaterial, pWepKey->KeyLength);
-
-                    switch(pWepKey->KeyLength)
-                    {
-                        case 5:
-                            CipherAlg = CIPHER_WEP64;
-                            break;
-                        case 13:
-                            CipherAlg = CIPHER_WEP128;
-                            break;
-                        default:
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, only support CIPHER_WEP64(len:5) & CIPHER_WEP128(len:13)!!\n"));
-                            Status = -EINVAL;
-                            break;
-                    }
-                    pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CipherAlg;
-
-                    // Default key for tx (shared key)
-                    if (pWepKey->KeyIndex & 0x80000000)
-                    {
-#ifdef WPA_SUPPLICANT_SUPPORT
-                        // set key material and key length
-                        NdisZeroMemory(pAdapter->StaCfg.DesireSharedKey[KeyIdx].Key, 16);
-                        pAdapter->StaCfg.DesireSharedKey[KeyIdx].KeyLen = (UCHAR) pWepKey->KeyLength;
-                        NdisMoveMemory(pAdapter->StaCfg.DesireSharedKey[KeyIdx].Key, &pWepKey->KeyMaterial, pWepKey->KeyLength);
-                        pAdapter->StaCfg.DesireSharedKeyId = KeyIdx;
-                        pAdapter->StaCfg.DesireSharedKey[KeyIdx].CipherAlg = CipherAlg;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                        pAdapter->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-                    }
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-					if ((pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE) &&
-						(pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA))
-					{
-						Key = pWepKey->KeyMaterial;
-
-						// Set Group key material to Asic
-    					AsicAddSharedKeyEntry(pAdapter, BSS0, KeyIdx, CipherAlg, Key, NULL, NULL);
-
-						// Update WCID attribute table and IVEIV table for this group key table
-						RTMPAddWcidAttributeEntry(pAdapter, BSS0, KeyIdx, CipherAlg, NULL);
-
-						STA_PORT_SECURED(pAdapter);
-
-        				// Indicate Connected for GUI
-        				pAdapter->IndicateMediaState = NdisMediaStateConnected;
-					}
-                    else if (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED)
-#endif // WPA_SUPPLICANT_SUPPORT
-                    {
-                        Key = pAdapter->SharedKey[BSS0][KeyIdx].Key;
-
-                        // Set key material and cipherAlg to Asic
-        				AsicAddSharedKeyEntry(pAdapter, BSS0, KeyIdx, CipherAlg, Key, NULL, NULL);
-
-                        if (pWepKey->KeyIndex & 0x80000000)
-                        {
-                            PMAC_TABLE_ENTRY pEntry = &pAdapter->MacTab.Content[BSSID_WCID];
-                            // Assign group key info
-    						RTMPAddWcidAttributeEntry(pAdapter, BSS0, KeyIdx, CipherAlg, NULL);
-    						// Assign pairwise key info
-    						RTMPAddWcidAttributeEntry(pAdapter, BSS0, KeyIdx, CipherAlg, pEntry);
-                        }
-                    }
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP (id=0x%x, Len=%d-byte), %s\n", pWepKey->KeyIndex, pWepKey->KeyLength, (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED) ? "Port Secured":"Port NOT Secured"));
-				}
-            }
-            kfree(pWepKey);
-            break;
-#ifdef WPA_SUPPLICANT_SUPPORT
-	    case OID_SET_COUNTERMEASURES:
-            if (wrq->u.data.length != sizeof(int))
-                Status  = -EINVAL;
-            else
-            {
-                int enabled = 0;
-                Status = copy_from_user(&enabled, wrq->u.data.pointer, wrq->u.data.length);
-                if (enabled == 1)
-                    pAdapter->StaCfg.bBlockAssoc = TRUE;
-                else
-                    // WPA MIC error should block association attempt for 60 seconds
-                    pAdapter->StaCfg.bBlockAssoc = FALSE;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_SET_COUNTERMEASURES bBlockAssoc=%s\n", pAdapter->StaCfg.bBlockAssoc ? "TRUE":"FALSE"));
-            }
-	        break;
-        case RT_OID_WPA_SUPPLICANT_SUPPORT:
-			if (wrq->u.data.length != sizeof(UCHAR))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&wpa_supplicant_enable, wrq->u.data.pointer, wrq->u.data.length);
-    			pAdapter->StaCfg.WpaSupplicantUP = wpa_supplicant_enable;
-    			DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_WPA_SUPPLICANT_SUPPORT (=%d)\n", pAdapter->StaCfg.WpaSupplicantUP));
-			}
-            break;
-        case OID_802_11_DEAUTHENTICATION:
-            if (wrq->u.data.length != sizeof(MLME_DEAUTH_REQ_STRUCT))
-                Status  = -EINVAL;
-            else
-            {
-                MLME_DEAUTH_REQ_STRUCT      *pInfo;
-				MLME_QUEUE_ELEM *MsgElem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-
-                pInfo = (MLME_DEAUTH_REQ_STRUCT *) MsgElem->Msg;
-                Status = copy_from_user(pInfo, wrq->u.data.pointer, wrq->u.data.length);
-                MlmeDeauthReqAction(pAdapter, MsgElem);
-				kfree(MsgElem);
-
-                if (INFRA_ON(pAdapter))
-                {
-                    LinkDown(pAdapter, FALSE);
-                    pAdapter->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DEAUTHENTICATION (Reason=%d)\n", pInfo->Reason));
-            }
-            break;
-        case OID_802_11_DROP_UNENCRYPTED:
-            if (wrq->u.data.length != sizeof(int))
-                Status  = -EINVAL;
-            else
-            {
-                int enabled = 0;
-                Status = copy_from_user(&enabled, wrq->u.data.pointer, wrq->u.data.length);
-                if (enabled == 1)
-                    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-                else
-                    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				NdisAcquireSpinLock(&pAdapter->MacTabLock);
-				pAdapter->MacTab.Content[BSSID_WCID].PortSecured = pAdapter->StaCfg.PortSecured;
-				NdisReleaseSpinLock(&pAdapter->MacTabLock);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DROP_UNENCRYPTED (=%d)\n", enabled));
-            }
-            break;
-        case OID_802_11_SET_IEEE8021X:
-            if (wrq->u.data.length != sizeof(BOOLEAN))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&IEEE8021xState, wrq->u.data.pointer, wrq->u.data.length);
-		        pAdapter->StaCfg.IEEE8021X = IEEE8021xState;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SET_IEEE8021X (=%d)\n", IEEE8021xState));
-            }
-            break;
-        case OID_802_11_SET_IEEE8021X_REQUIRE_KEY:
-			if (wrq->u.data.length != sizeof(BOOLEAN))
-				 Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&IEEE8021x_required_keys, wrq->u.data.pointer, wrq->u.data.length);
-				pAdapter->StaCfg.IEEE8021x_required_keys = IEEE8021x_required_keys;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SET_IEEE8021X_REQUIRE_KEY (%d)\n", IEEE8021x_required_keys));
-			}
-			break;
-        case OID_802_11_PMKID:
-	        pPmkId = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-	        if(pPmkId == NULL) {
-                Status = -ENOMEM;
-                break;
-            }
-            Status = copy_from_user(pPmkId, wrq->u.data.pointer, wrq->u.data.length);
-
-	        // check the PMKID information
-	        if (pPmkId->BSSIDInfoCount == 0)
-                NdisZeroMemory(pAdapter->StaCfg.SavedPMK, sizeof(BSSID_INFO)*PMKID_NO);
-	        else
-	        {
-		        PBSSID_INFO	pBssIdInfo;
-		        UINT		BssIdx;
-		        UINT		CachedIdx;
-
-		        for (BssIdx = 0; BssIdx < pPmkId->BSSIDInfoCount; BssIdx++)
-		        {
-			        // point to the indexed BSSID_INFO structure
-			        pBssIdInfo = (PBSSID_INFO) ((PUCHAR) pPmkId + 2 * sizeof(UINT) + BssIdx * sizeof(BSSID_INFO));
-			        // Find the entry in the saved data base.
-			        for (CachedIdx = 0; CachedIdx < pAdapter->StaCfg.SavedPMKNum; CachedIdx++)
-			        {
-				        // compare the BSSID
-				        if (NdisEqualMemory(pBssIdInfo->BSSID, pAdapter->StaCfg.SavedPMK[CachedIdx].BSSID, sizeof(NDIS_802_11_MAC_ADDRESS)))
-					        break;
-			        }
-
-			        // Found, replace it
-			        if (CachedIdx < PMKID_NO)
-			        {
-				        DBGPRINT(RT_DEBUG_OFF, ("Update OID_802_11_PMKID, idx = %d\n", CachedIdx));
-				        NdisMoveMemory(&pAdapter->StaCfg.SavedPMK[CachedIdx], pBssIdInfo, sizeof(BSSID_INFO));
-				        pAdapter->StaCfg.SavedPMKNum++;
-			        }
-			        // Not found, replace the last one
-			        else
-			        {
-				        // Randomly replace one
-				        CachedIdx = (pBssIdInfo->BSSID[5] % PMKID_NO);
-				        DBGPRINT(RT_DEBUG_OFF, ("Update OID_802_11_PMKID, idx = %d\n", CachedIdx));
-				        NdisMoveMemory(&pAdapter->StaCfg.SavedPMK[CachedIdx], pBssIdInfo, sizeof(BSSID_INFO));
-			        }
-		        }
-			}
-			if(pPmkId)
-				kfree(pPmkId);
-	        break;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-
-#ifdef SNMP_SUPPORT
-		case OID_802_11_SHORTRETRYLIMIT:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&ShortRetryLimit, wrq->u.data.pointer, wrq->u.data.length);
-				RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-				tx_rty_cfg.field.ShortRtyLimit = ShortRetryLimit;
-				RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SHORTRETRYLIMIT (tx_rty_cfg.field.ShortRetryLimit=%d, ShortRetryLimit=%ld)\n", tx_rty_cfg.field.ShortRtyLimit, ShortRetryLimit));
-			}
-			break;
-
-		case OID_802_11_LONGRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_LONGRETRYLIMIT \n"));
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&LongRetryLimit, wrq->u.data.pointer, wrq->u.data.length);
-				RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-				tx_rty_cfg.field.LongRtyLimit = LongRetryLimit;
-				RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_LONGRETRYLIMIT (tx_rty_cfg.field.LongRetryLimit= %d,LongRetryLimit=%ld)\n", tx_rty_cfg.field.LongRtyLimit, LongRetryLimit));
-			}
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYVALUE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYVALUE\n"));
-			pKey = kmalloc(wrq->u.data.length, GFP_KERNEL);
-			Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-			//pKey = &WepKey;
-
-			if ( pKey->Length != wrq->u.data.length)
-			{
-				Status = -EINVAL;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYVALUE, Failed!!\n"));
-			}
-			KeyIdx = pKey->KeyIndex & 0x0fffffff;
-			DBGPRINT(RT_DEBUG_TRACE,("pKey->KeyIndex =%d, pKey->KeyLength=%d\n", pKey->KeyIndex, pKey->KeyLength));
-
-			// it is a shared key
-			if (KeyIdx > 4)
-				Status = -EINVAL;
-			else
-			{
-				pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen = (UCHAR) pKey->KeyLength;
-				NdisMoveMemory(&pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key, &pKey->KeyMaterial, pKey->KeyLength);
-				if (pKey->KeyIndex & 0x80000000)
-				{
-					// Default key for tx (shared key)
-					pAdapter->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-				}
-				//RestartAPIsRequired = TRUE;
-			}
-			break;
-
-
-		case OID_802_11_WEPDEFAULTKEYID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYID \n"));
-
-			if (wrq->u.data.length != sizeof(UCHAR))
-				Status = -EINVAL;
-			else
-				Status = copy_from_user(&pAdapter->StaCfg.DefaultKeyId, wrq->u.data.pointer, wrq->u.data.length);
-
-			break;
-
-
-		case OID_802_11_CURRENTCHANNEL:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_CURRENTCHANNEL \n"));
-			if (wrq->u.data.length != sizeof(UCHAR))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&ctmp, wrq->u.data.pointer, wrq->u.data.length);
-				sprintf(&ctmp,"%d", ctmp);
-				Set_Channel_Proc(pAdapter, &ctmp);
-			}
-			break;
-#endif
-
-
-
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::unknown IOCTL's subcmd = 0x%08x\n", cmd));
-            Status = -EOPNOTSUPP;
-            break;
-    }
-
-
-    return Status;
-}
-
-INT RTMPQueryInformation(
-    IN  PRTMP_ADAPTER pAdapter,
-    IN  OUT struct ifreq    *rq,
-    IN  INT                 cmd)
-{
-    struct iwreq                        *wrq = (struct iwreq *) rq;
-    NDIS_802_11_BSSID_LIST_EX           *pBssidList = NULL;
-    PNDIS_WLAN_BSSID_EX                 pBss;
-    NDIS_802_11_SSID                    Ssid;
-    NDIS_802_11_CONFIGURATION           *pConfiguration = NULL;
-    RT_802_11_LINK_STATUS               *pLinkStatus = NULL;
-    RT_802_11_STA_CONFIG                *pStaConfig = NULL;
-    NDIS_802_11_STATISTICS              *pStatistics = NULL;
-    NDIS_802_11_RTS_THRESHOLD           RtsThresh;
-    NDIS_802_11_FRAGMENTATION_THRESHOLD FragThresh;
-    NDIS_802_11_POWER_MODE              PowerMode;
-    NDIS_802_11_NETWORK_INFRASTRUCTURE  BssType;
-    RT_802_11_PREAMBLE                  PreamType;
-    NDIS_802_11_AUTHENTICATION_MODE     AuthMode;
-    NDIS_802_11_WEP_STATUS              WepStatus;
-    NDIS_MEDIA_STATE                    MediaState;
-    ULONG                               BssBufSize, ulInfo=0, NetworkTypeList[4], apsd = 0;
-    USHORT                              BssLen = 0;
-    PUCHAR                              pBuf = NULL, pPtr;
-    INT                                 Status = NDIS_STATUS_SUCCESS;
-    UINT                                we_version_compiled;
-    UCHAR                               i, Padding = 0;
-    BOOLEAN                             RadioState;
-	UCHAR	driverVersion[8];
-    OID_SET_HT_PHYMODE			        *pHTPhyMode = NULL;
-
-
-#ifdef SNMP_SUPPORT
-	//for snmp, kathy
-	DefaultKeyIdxValue			*pKeyIdxValue;
-	INT							valueLen;
-	TX_RTY_CFG_STRUC			tx_rty_cfg;
-	ULONG						ShortRetryLimit, LongRetryLimit;
-	UCHAR						tmp[64];
-#endif //SNMP
-
-    switch(cmd)
-    {
-        case RT_OID_DEVICE_NAME:
-            wrq->u.data.length = sizeof(STA_NIC_DEVICE_NAME);
-            Status = copy_to_user(wrq->u.data.pointer, STA_NIC_DEVICE_NAME, wrq->u.data.length);
-            break;
-        case RT_OID_VERSION_INFO:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_VERSION_INFO \n"));
-			wrq->u.data.length = 8*sizeof(UCHAR);
-			sprintf(&driverVersion[0], "%s", STA_DRIVER_VERSION);
-			driverVersion[7] = '\0';
-			if (copy_to_user(wrq->u.data.pointer, &driverVersion, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            break;
-#ifdef RALINK_ATE
-		case RT_QUERY_ATE_TXDONE_COUNT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_QUERY_ATE_TXDONE_COUNT \n"));
-			wrq->u.data.length = sizeof(UINT32);
-			if (copy_to_user(wrq->u.data.pointer, &pAdapter->ate.TxDoneCount, wrq->u.data.length))
-			{
-				Status = -EFAULT;
-			}
-			break;
-#endif // RALINK_ATE //
-        case OID_802_11_BSSID_LIST:
-            if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-            	/*
-            	 * Still scanning, indicate the caller should try again.
-            	 */
-            	DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID_LIST (Still scanning)\n"));
-				return -EAGAIN;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID_LIST (%d BSS returned)\n",pAdapter->ScanTab.BssNr));
-			pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-            // Claculate total buffer size required
-            BssBufSize = sizeof(ULONG);
-
-            for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-            {
-                // Align pointer to 4 bytes boundary.
-                //Padding = 4 - (pAdapter->ScanTab.BssEntry[i].VarIELen & 0x0003);
-                //if (Padding == 4)
-                //    Padding = 0;
-                BssBufSize += (sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen + Padding);
-            }
-
-            // For safety issue, we add 256 bytes just in case
-            BssBufSize += 256;
-            // Allocate the same size as passed from higher layer
-            pBuf = kmalloc(BssBufSize, MEM_ALLOC_FLAG);
-            if(pBuf == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-            // Init 802_11_BSSID_LIST_EX structure
-            NdisZeroMemory(pBuf, BssBufSize);
-            pBssidList = (PNDIS_802_11_BSSID_LIST_EX) pBuf;
-            pBssidList->NumberOfItems = pAdapter->ScanTab.BssNr;
-
-            // Calculate total buffer length
-            BssLen = 4; // Consist of NumberOfItems
-            // Point to start of NDIS_WLAN_BSSID_EX
-            // pPtr = pBuf + sizeof(ULONG);
-            pPtr = (PUCHAR) &pBssidList->Bssid[0];
-            for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-            {
-                pBss = (PNDIS_WLAN_BSSID_EX) pPtr;
-                NdisMoveMemory(&pBss->MacAddress, &pAdapter->ScanTab.BssEntry[i].Bssid, MAC_ADDR_LEN);
-                if ((pAdapter->ScanTab.BssEntry[i].Hidden == 1) && (pAdapter->StaCfg.bShowHiddenSSID == FALSE))
-                {
-                    //
-					// We must return this SSID during 4way handshaking, otherwise Aegis will failed to parse WPA infomation
-					// and then failed to send EAPOl farame.
-					//
-					if ((pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA) && (pAdapter->StaCfg.PortSecured != WPA_802_1X_PORT_SECURED))
-					{
-						pBss->Ssid.SsidLength = pAdapter->ScanTab.BssEntry[i].SsidLen;
-						NdisMoveMemory(pBss->Ssid.Ssid, pAdapter->ScanTab.BssEntry[i].Ssid, pAdapter->ScanTab.BssEntry[i].SsidLen);
-					}
-					else
-                    	pBss->Ssid.SsidLength = 0;
-                }
-                else
-                {
-                    pBss->Ssid.SsidLength = pAdapter->ScanTab.BssEntry[i].SsidLen;
-                    NdisMoveMemory(pBss->Ssid.Ssid, pAdapter->ScanTab.BssEntry[i].Ssid, pAdapter->ScanTab.BssEntry[i].SsidLen);
-                }
-                pBss->Privacy = pAdapter->ScanTab.BssEntry[i].Privacy;
-                pBss->Rssi = pAdapter->ScanTab.BssEntry[i].Rssi - pAdapter->BbpRssiToDbmDelta;
-                pBss->NetworkTypeInUse = NetworkTypeInUseSanity(&pAdapter->ScanTab.BssEntry[i]);
-                pBss->Configuration.Length = sizeof(NDIS_802_11_CONFIGURATION);
-                pBss->Configuration.BeaconPeriod = pAdapter->ScanTab.BssEntry[i].BeaconPeriod;
-                pBss->Configuration.ATIMWindow = pAdapter->ScanTab.BssEntry[i].AtimWin;
-
-                MAP_CHANNEL_ID_TO_KHZ(pAdapter->ScanTab.BssEntry[i].Channel, pBss->Configuration.DSConfig);
-
-                if (pAdapter->ScanTab.BssEntry[i].BssType == BSS_INFRA)
-                    pBss->InfrastructureMode = Ndis802_11Infrastructure;
-                else
-                    pBss->InfrastructureMode = Ndis802_11IBSS;
-
-                NdisMoveMemory(pBss->SupportedRates, pAdapter->ScanTab.BssEntry[i].SupRate, pAdapter->ScanTab.BssEntry[i].SupRateLen);
-                NdisMoveMemory(pBss->SupportedRates + pAdapter->ScanTab.BssEntry[i].SupRateLen,
-                               pAdapter->ScanTab.BssEntry[i].ExtRate,
-                               pAdapter->ScanTab.BssEntry[i].ExtRateLen);
-
-                if (pAdapter->ScanTab.BssEntry[i].VarIELen == 0)
-                {
-                    pBss->IELength = sizeof(NDIS_802_11_FIXED_IEs);
-                    NdisMoveMemory(pBss->IEs, &pAdapter->ScanTab.BssEntry[i].FixIEs, sizeof(NDIS_802_11_FIXED_IEs));
-                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs);
-                }
-                else
-                {
-                    pBss->IELength = (ULONG)(sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen);
-                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs);
-                    NdisMoveMemory(pBss->IEs, &pAdapter->ScanTab.BssEntry[i].FixIEs, sizeof(NDIS_802_11_FIXED_IEs));
-                    NdisMoveMemory(pBss->IEs + sizeof(NDIS_802_11_FIXED_IEs), pAdapter->ScanTab.BssEntry[i].VarIEs, pAdapter->ScanTab.BssEntry[i].VarIELen);
-                    pPtr += pAdapter->ScanTab.BssEntry[i].VarIELen;
-                }
-                pBss->Length = (ULONG)(sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen + Padding);
-
-#if WIRELESS_EXT < 17
-                if ((BssLen + pBss->Length) < wrq->u.data.length)
-                BssLen += pBss->Length;
-                else
-                {
-                    pBssidList->NumberOfItems = i;
-                    break;
-                }
-#else
-                BssLen += pBss->Length;
-#endif
-            }
-
-#if WIRELESS_EXT < 17
-            wrq->u.data.length = BssLen;
-#else
-            if (BssLen > wrq->u.data.length)
-            {
-                kfree(pBssidList);
-                return -E2BIG;
-            }
-            else
-                wrq->u.data.length = BssLen;
-#endif
-            Status = copy_to_user(wrq->u.data.pointer, pBssidList, BssLen);
-            kfree(pBssidList);
-            break;
-        case OID_802_3_CURRENT_ADDRESS:
-            wrq->u.data.length = MAC_ADDR_LEN;
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-            break;
-        case OID_GEN_MEDIA_CONNECT_STATUS:
-            if (pAdapter->IndicateMediaState == NdisMediaStateConnected)
-                MediaState = NdisMediaStateConnected;
-            else
-                MediaState = NdisMediaStateDisconnected;
-
-            wrq->u.data.length = sizeof(NDIS_MEDIA_STATE);
-            Status = copy_to_user(wrq->u.data.pointer, &MediaState, wrq->u.data.length);
-            break;
-        case OID_802_11_BSSID:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				Status = NDIS_STATUS_RESOURCES;
-				break;
-			}
-#endif // RALINK_ATE //
-            if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-            {
-                Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Bssid, sizeof(NDIS_802_11_MAC_ADDRESS));
-
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID(=EMPTY)\n"));
-                Status = -ENOTCONN;
-            }
-            break;
-        case OID_802_11_SSID:
-			NdisZeroMemory(&Ssid, sizeof(NDIS_802_11_SSID));
-			NdisZeroMemory(Ssid.Ssid, MAX_LEN_OF_SSID);
-            Ssid.SsidLength = pAdapter->CommonCfg.SsidLen;
-			memcpy(Ssid.Ssid, pAdapter->CommonCfg.Ssid,	Ssid.SsidLength);
-            wrq->u.data.length = sizeof(NDIS_802_11_SSID);
-            Status = copy_to_user(wrq->u.data.pointer, &Ssid, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_SSID (Len=%d, ssid=%s)\n", Ssid.SsidLength,Ssid.Ssid));
-            break;
-        case RT_OID_802_11_QUERY_LINK_STATUS:
-            pLinkStatus = (RT_802_11_LINK_STATUS *) kmalloc(sizeof(RT_802_11_LINK_STATUS), MEM_ALLOC_FLAG);
-            if (pLinkStatus)
-            {
-                pLinkStatus->CurrTxRate = RateIdTo500Kbps[pAdapter->CommonCfg.TxRate];   // unit : 500 kbps
-                pLinkStatus->ChannelQuality = pAdapter->Mlme.ChannelQuality;
-                pLinkStatus->RxByteCount = pAdapter->RalinkCounters.ReceivedByteCount;
-                pLinkStatus->TxByteCount = pAdapter->RalinkCounters.TransmittedByteCount;
-        		pLinkStatus->CentralChannel = pAdapter->CommonCfg.CentralChannel;
-                wrq->u.data.length = sizeof(RT_802_11_LINK_STATUS);
-                Status = copy_to_user(wrq->u.data.pointer, pLinkStatus, wrq->u.data.length);
-                kfree(pLinkStatus);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LINK_STATUS\n"));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LINK_STATUS(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_802_11_CONFIGURATION:
-            pConfiguration = (NDIS_802_11_CONFIGURATION *) kmalloc(sizeof(NDIS_802_11_CONFIGURATION), MEM_ALLOC_FLAG);
-            if (pConfiguration)
-            {
-                pConfiguration->Length = sizeof(NDIS_802_11_CONFIGURATION);
-                pConfiguration->BeaconPeriod = pAdapter->CommonCfg.BeaconPeriod;
-                pConfiguration->ATIMWindow = pAdapter->StaActive.AtimWin;
-                MAP_CHANNEL_ID_TO_KHZ(pAdapter->CommonCfg.Channel, pConfiguration->DSConfig);
-                wrq->u.data.length = sizeof(NDIS_802_11_CONFIGURATION);
-                Status = copy_to_user(wrq->u.data.pointer, pConfiguration, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CONFIGURATION(BeaconPeriod=%ld,AtimW=%ld,Channel=%d) \n",
-                                        pConfiguration->BeaconPeriod, pConfiguration->ATIMWindow, pAdapter->CommonCfg.Channel));
-				kfree(pConfiguration);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CONFIGURATION(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-		case RT_OID_802_11_SNR_0:
-			if ((pAdapter->StaCfg.LastSNR0 > 0))
-			{
-				ulInfo = ((0xeb	- pAdapter->StaCfg.LastSNR0) * 3) /	16 ;
-				wrq->u.data.length = sizeof(ulInfo);
-				Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_SNR_0(0x=%lx)\n", ulInfo));
-			}
-            else
-			    Status = -EFAULT;
-			break;
-		case RT_OID_802_11_SNR_1:
-			if ((pAdapter->Antenna.field.RxPath	> 1) &&
-                (pAdapter->StaCfg.LastSNR1 > 0))
-			{
-				ulInfo = ((0xeb	- pAdapter->StaCfg.LastSNR1) * 3) /	16 ;
-				wrq->u.data.length = sizeof(ulInfo);
-				Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE,("Query::RT_OID_802_11_SNR_1(0x=%lx)\n",ulInfo));
-			}
-			else
-				Status = -EFAULT;
-            DBGPRINT(RT_DEBUG_TRACE,("Query::RT_OID_802_11_SNR_1(pAdapter->StaCfg.LastSNR1=%d)\n",pAdapter->StaCfg.LastSNR1));
-			break;
-        case OID_802_11_RSSI_TRIGGER:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi0 - pAdapter->BbpRssiToDbmDelta;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_RSSI_TRIGGER(=%ld)\n", ulInfo));
-            break;
-		case OID_802_11_RSSI:
-        case RT_OID_802_11_RSSI:
-			ulInfo = pAdapter->StaCfg.RssiSample.LastRssi0;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-		case RT_OID_802_11_RSSI_1:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi1;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-        case RT_OID_802_11_RSSI_2:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi2;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-        case OID_802_11_STATISTICS:
-            pStatistics = (NDIS_802_11_STATISTICS *) kmalloc(sizeof(NDIS_802_11_STATISTICS), MEM_ALLOC_FLAG);
-            if (pStatistics)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_STATISTICS \n"));
-                // add the most up-to-date h/w raw counters into software counters
-			    NICUpdateRawCounters(pAdapter);
-
-                // Sanity check for calculation of sucessful count
-                if (pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart < pAdapter->WlanCounters.RetryCount.QuadPart)
-                    pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart = pAdapter->WlanCounters.RetryCount.QuadPart;
-
-                pStatistics->TransmittedFragmentCount.QuadPart = pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart;
-                pStatistics->MulticastTransmittedFrameCount.QuadPart = pAdapter->WlanCounters.MulticastTransmittedFrameCount.QuadPart;
-                pStatistics->FailedCount.QuadPart = pAdapter->WlanCounters.FailedCount.QuadPart;
-                pStatistics->RetryCount.QuadPart = pAdapter->WlanCounters.RetryCount.QuadPart;
-                pStatistics->MultipleRetryCount.QuadPart = pAdapter->WlanCounters.MultipleRetryCount.QuadPart;
-                pStatistics->RTSSuccessCount.QuadPart = pAdapter->WlanCounters.RTSSuccessCount.QuadPart;
-                pStatistics->RTSFailureCount.QuadPart = pAdapter->WlanCounters.RTSFailureCount.QuadPart;
-                pStatistics->ACKFailureCount.QuadPart = pAdapter->WlanCounters.ACKFailureCount.QuadPart;
-                pStatistics->FrameDuplicateCount.QuadPart = pAdapter->WlanCounters.FrameDuplicateCount.QuadPart;
-                pStatistics->ReceivedFragmentCount.QuadPart = pAdapter->WlanCounters.ReceivedFragmentCount.QuadPart;
-                pStatistics->MulticastReceivedFrameCount.QuadPart = pAdapter->WlanCounters.MulticastReceivedFrameCount.QuadPart;
-#ifdef DBG
-                pStatistics->FCSErrorCount = pAdapter->RalinkCounters.RealFcsErrCount;
-#else
-                pStatistics->FCSErrorCount.QuadPart = pAdapter->WlanCounters.FCSErrorCount.QuadPart;
-                pStatistics->FrameDuplicateCount.u.LowPart = pAdapter->WlanCounters.FrameDuplicateCount.u.LowPart / 100;
-#endif
-                wrq->u.data.length = sizeof(NDIS_802_11_STATISTICS);
-                Status = copy_to_user(wrq->u.data.pointer, pStatistics, wrq->u.data.length);
-                kfree(pStatistics);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_STATISTICS(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_GEN_RCV_OK:
-            ulInfo = pAdapter->Counters8023.GoodReceives;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            break;
-        case OID_GEN_RCV_NO_BUFFER:
-            ulInfo = pAdapter->Counters8023.RxNoBuffer;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            break;
-        case RT_OID_802_11_PHY_MODE:
-            ulInfo = (ULONG)pAdapter->CommonCfg.PhyMode;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PHY_MODE (=%ld)\n", ulInfo));
-            break;
-        case RT_OID_802_11_STA_CONFIG:
-            pStaConfig = (RT_802_11_STA_CONFIG *) kmalloc(sizeof(RT_802_11_STA_CONFIG), MEM_ALLOC_FLAG);
-            if (pStaConfig)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG\n"));
-                pStaConfig->EnableTxBurst = pAdapter->CommonCfg.bEnableTxBurst;
-                pStaConfig->EnableTurboRate = 0;
-                pStaConfig->UseBGProtection = pAdapter->CommonCfg.UseBGProtection;
-                pStaConfig->UseShortSlotTime = pAdapter->CommonCfg.bUseShortSlotTime;
-                //pStaConfig->AdhocMode = pAdapter->StaCfg.AdhocMode;
-                pStaConfig->HwRadioStatus = (pAdapter->StaCfg.bHwRadio == TRUE) ? 1 : 0;
-                pStaConfig->Rsv1 = 0;
-                pStaConfig->SystemErrorBitmap = pAdapter->SystemErrorBitmap;
-                wrq->u.data.length = sizeof(RT_802_11_STA_CONFIG);
-                Status = copy_to_user(wrq->u.data.pointer, pStaConfig, wrq->u.data.length);
-                kfree(pStaConfig);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_802_11_RTS_THRESHOLD:
-            RtsThresh = pAdapter->CommonCfg.RtsThreshold;
-            wrq->u.data.length = sizeof(RtsThresh);
-            Status = copy_to_user(wrq->u.data.pointer, &RtsThresh, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_RTS_THRESHOLD(=%ld)\n", RtsThresh));
-            break;
-        case OID_802_11_FRAGMENTATION_THRESHOLD:
-            FragThresh = pAdapter->CommonCfg.FragmentThreshold;
-            if (pAdapter->CommonCfg.bUseZeroToDisableFragment == TRUE)
-                FragThresh = 0;
-            wrq->u.data.length = sizeof(FragThresh);
-            Status = copy_to_user(wrq->u.data.pointer, &FragThresh, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_FRAGMENTATION_THRESHOLD(=%ld)\n", FragThresh));
-            break;
-        case OID_802_11_POWER_MODE:
-            PowerMode = pAdapter->StaCfg.WindowsPowerMode;
-            wrq->u.data.length = sizeof(PowerMode);
-            Status = copy_to_user(wrq->u.data.pointer, &PowerMode, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_POWER_MODE(=%d)\n", PowerMode));
-            break;
-        case RT_OID_802_11_RADIO:
-            RadioState = (BOOLEAN) pAdapter->StaCfg.bSwRadio;
-            wrq->u.data.length = sizeof(RadioState);
-            Status = copy_to_user(wrq->u.data.pointer, &RadioState, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_RADIO (=%d)\n", RadioState));
-            break;
-        case OID_802_11_INFRASTRUCTURE_MODE:
-            if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-                BssType = Ndis802_11IBSS;
-            else if (pAdapter->StaCfg.BssType == BSS_INFRA)
-                BssType = Ndis802_11Infrastructure;
-            else if (pAdapter->StaCfg.BssType == BSS_MONITOR)
-                BssType = Ndis802_11Monitor;
-            else
-                BssType = Ndis802_11AutoUnknown;
-
-            wrq->u.data.length = sizeof(BssType);
-            Status = copy_to_user(wrq->u.data.pointer, &BssType, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_INFRASTRUCTURE_MODE(=%d)\n", BssType));
-            break;
-        case RT_OID_802_11_PREAMBLE:
-            PreamType = pAdapter->CommonCfg.TxPreamble;
-            wrq->u.data.length = sizeof(PreamType);
-            Status = copy_to_user(wrq->u.data.pointer, &PreamType, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PREAMBLE(=%d)\n", PreamType));
-            break;
-        case OID_802_11_AUTHENTICATION_MODE:
-            AuthMode = pAdapter->StaCfg.AuthMode;
-            wrq->u.data.length = sizeof(AuthMode);
-            Status = copy_to_user(wrq->u.data.pointer, &AuthMode, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_AUTHENTICATION_MODE(=%d)\n", AuthMode));
-            break;
-        case OID_802_11_WEP_STATUS:
-            WepStatus = pAdapter->StaCfg.WepStatus;
-            wrq->u.data.length = sizeof(WepStatus);
-            Status = copy_to_user(wrq->u.data.pointer, &WepStatus, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_WEP_STATUS(=%d)\n", WepStatus));
-            break;
-        case OID_802_11_TX_POWER_LEVEL:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.TxPower, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_TX_POWER_LEVEL %x\n",pAdapter->CommonCfg.TxPower));
-			break;
-        case RT_OID_802_11_TX_POWER_LEVEL_1:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.TxPowerPercentage, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_TX_POWER_LEVEL_1 (=%ld)\n", pAdapter->CommonCfg.TxPowerPercentage));
-			break;
-        case OID_802_11_NETWORK_TYPES_SUPPORTED:
-			if ((pAdapter->RfIcType	== RFIC_2850) || (pAdapter->RfIcType ==	RFIC_2750))
-			{
-				NetworkTypeList[0] = 3;                 // NumberOfItems = 3
-				NetworkTypeList[1] = Ndis802_11DS;      // NetworkType[1] = 11b
-				NetworkTypeList[2] = Ndis802_11OFDM24;  // NetworkType[2] = 11g
-				NetworkTypeList[3] = Ndis802_11OFDM5;   // NetworkType[3] = 11a
-                wrq->u.data.length = 16;
-				Status = copy_to_user(wrq->u.data.pointer, &NetworkTypeList[0], wrq->u.data.length);
-			}
-			else
-			{
-				NetworkTypeList[0] = 2;                 // NumberOfItems = 2
-				NetworkTypeList[1] = Ndis802_11DS;      // NetworkType[1] = 11b
-				NetworkTypeList[2] = Ndis802_11OFDM24;  // NetworkType[2] = 11g
-			    wrq->u.data.length = 12;
-				Status = copy_to_user(wrq->u.data.pointer, &NetworkTypeList[0], wrq->u.data.length);
-			}
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_NETWORK_TYPES_SUPPORTED\n"));
-				break;
-	    case OID_802_11_NETWORK_TYPE_IN_USE:
-            wrq->u.data.length = sizeof(ULONG);
-			if (pAdapter->CommonCfg.PhyMode == PHY_11A)
-				ulInfo = Ndis802_11OFDM5;
-			else if ((pAdapter->CommonCfg.PhyMode == PHY_11BG_MIXED) || (pAdapter->CommonCfg.PhyMode == PHY_11G))
-				ulInfo = Ndis802_11OFDM24;
-			else
-				ulInfo = Ndis802_11DS;
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-        case RT_OID_802_11_QUERY_LAST_RX_RATE:
-            ulInfo = (ULONG)pAdapter->LastRxRate;
-            wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LAST_RX_RATE (=%ld)\n", ulInfo));
-			break;
-		case RT_OID_802_11_QUERY_LAST_TX_RATE:
-			//ulInfo = (ULONG)pAdapter->LastTxRate;
-			ulInfo = (ULONG)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LAST_TX_RATE (=%lx)\n", ulInfo));
-			break;
-        case RT_OID_802_11_QUERY_EEPROM_VERSION:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->EepromVersion, wrq->u.data.length);
-            break;
-        case RT_OID_802_11_QUERY_FIRMWARE_VERSION:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->FirmwareVersion, wrq->u.data.length);
-			break;
-	    case RT_OID_802_11_QUERY_NOISE_LEVEL:
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->BbpWriteLatch[66], wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_NOISE_LEVEL (=%d)\n", pAdapter->BbpWriteLatch[66]));
-			break;
-	    case RT_OID_802_11_EXTRA_INFO:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->ExtraInfo, wrq->u.data.length);
-	        DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_EXTRA_INFO (=%ld)\n", pAdapter->ExtraInfo));
-	        break;
-	    case RT_OID_WE_VERSION_COMPILED:
-	        wrq->u.data.length = sizeof(UINT);
-	        we_version_compiled = WIRELESS_EXT;
-	        Status = copy_to_user(wrq->u.data.pointer, &we_version_compiled, wrq->u.data.length);
-	        break;
-		case RT_OID_802_11_QUERY_APSD_SETTING:
-			apsd = (pAdapter->CommonCfg.bAPSDCapable | (pAdapter->CommonCfg.bAPSDAC_BE << 1) | (pAdapter->CommonCfg.bAPSDAC_BK << 2)
-				| (pAdapter->CommonCfg.bAPSDAC_VI << 3)	| (pAdapter->CommonCfg.bAPSDAC_VO << 4)	| (pAdapter->CommonCfg.MaxSPLength << 5));
-
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &apsd, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_APSD_SETTING (=0x%lx,APSDCap=%d,AC_BE=%d,AC_BK=%d,AC_VI=%d,AC_VO=%d,MAXSPLen=%d)\n",
-				apsd,pAdapter->CommonCfg.bAPSDCapable,pAdapter->CommonCfg.bAPSDAC_BE,pAdapter->CommonCfg.bAPSDAC_BK,pAdapter->CommonCfg.bAPSDAC_VI,pAdapter->CommonCfg.bAPSDAC_VO,pAdapter->CommonCfg.MaxSPLength));
-			break;
-		case RT_OID_802_11_QUERY_APSD_PSM:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bAPSDForcePowerSave, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_APSD_PSM (=%d)\n", pAdapter->CommonCfg.bAPSDForcePowerSave));
-			break;
-		case RT_OID_802_11_QUERY_WMM:
-			wrq->u.data.length = sizeof(BOOLEAN);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bWmmCapable, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_WMM (=%d)\n",	pAdapter->CommonCfg.bWmmCapable));
-			break;
-#ifdef WPA_SUPPLICANT_SUPPORT
-        case RT_OID_NEW_DRIVER:
-            {
-                UCHAR enabled = 1;
-    	        wrq->u.data.length = sizeof(UCHAR);
-    	        Status = copy_to_user(wrq->u.data.pointer, &enabled, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_NEW_DRIVER (=%d)\n", enabled));
-            }
-	        break;
-        case RT_OID_WPA_SUPPLICANT_SUPPORT:
-	        wrq->u.data.length = sizeof(UCHAR);
-	        Status = copy_to_user(wrq->u.data.pointer, &pAdapter->StaCfg.WpaSupplicantUP, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_WPA_SUPPLICANT_SUPPORT (=%d)\n", pAdapter->StaCfg.WpaSupplicantUP));
-	        break;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-        case RT_OID_DRIVER_DEVICE_NAME:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_DRIVER_DEVICE_NAME \n"));
-			wrq->u.data.length = 16;
-			if (copy_to_user(wrq->u.data.pointer, pAdapter->StaCfg.dev_name, wrq->u.data.length))
-			{
-				Status = -EFAULT;
-			}
-            break;
-        case RT_OID_802_11_QUERY_HT_PHYMODE:
-            pHTPhyMode = (OID_SET_HT_PHYMODE *) kmalloc(sizeof(OID_SET_HT_PHYMODE), MEM_ALLOC_FLAG);
-            if (pHTPhyMode)
-            {
-                pHTPhyMode->PhyMode = pAdapter->CommonCfg.PhyMode;
-    			pHTPhyMode->HtMode = (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE;
-    			pHTPhyMode->BW = (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.BW;
-    			pHTPhyMode->MCS= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.MCS;
-    			pHTPhyMode->SHORTGI= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.ShortGI;
-    			pHTPhyMode->STBC= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.STBC;
-
-    			pHTPhyMode->ExtOffset = ((pAdapter->CommonCfg.CentralChannel < pAdapter->CommonCfg.Channel) ? (EXTCHA_BELOW) : (EXTCHA_ABOVE));
-                wrq->u.data.length = sizeof(OID_SET_HT_PHYMODE);
-                if (copy_to_user(wrq->u.data.pointer, pHTPhyMode, wrq->u.data.length))
-    			{
-    				Status = -EFAULT;
-    			}
-    			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_HT_PHYMODE (PhyMode = %d, MCS =%d, BW = %d, STBC = %d, ExtOffset=%d)\n",
-    				pHTPhyMode->HtMode, pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC, pHTPhyMode->ExtOffset));
-    			DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (.word = %x )\n", pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case RT_OID_802_11_COUNTRY_REGION:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_COUNTRY_REGION \n"));
-			wrq->u.data.length = sizeof(ulInfo);
-            ulInfo = pAdapter->CommonCfg.CountryRegionForABand;
-            ulInfo = (ulInfo << 8)|(pAdapter->CommonCfg.CountryRegion);
-			if (copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            break;
-        case RT_OID_802_11_QUERY_DAT_HT_PHYMODE:
-            pHTPhyMode = (OID_SET_HT_PHYMODE *) kmalloc(sizeof(OID_SET_HT_PHYMODE), MEM_ALLOC_FLAG);
-            if (pHTPhyMode)
-            {
-                pHTPhyMode->PhyMode = pAdapter->CommonCfg.PhyMode;
-    			pHTPhyMode->HtMode = (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.HTMODE;
-    			pHTPhyMode->BW = (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.BW;
-    			pHTPhyMode->MCS= (UCHAR)pAdapter->StaCfg.DesiredTransmitSetting.field.MCS;
-    			pHTPhyMode->SHORTGI= (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.ShortGI;
-    			pHTPhyMode->STBC= (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.STBC;
-
-                wrq->u.data.length = sizeof(OID_SET_HT_PHYMODE);
-                if (copy_to_user(wrq->u.data.pointer, pHTPhyMode, wrq->u.data.length))
-    			{
-    				Status = -EFAULT;
-    			}
-    			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_HT_PHYMODE (PhyMode = %d, MCS =%d, BW = %d, STBC = %d, ExtOffset=%d)\n",
-    				pHTPhyMode->HtMode, pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC, pHTPhyMode->ExtOffset));
-    			DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (.word = %x )\n", pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case RT_OID_QUERY_MULTIPLE_CARD_SUPPORT:
-			wrq->u.data.length = sizeof(UCHAR);
-            i = 0;
-#ifdef MULTIPLE_CARD_SUPPORT
-            i = 1;
-#endif // MULTIPLE_CARD_SUPPORT //
-			if (copy_to_user(wrq->u.data.pointer, &i, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_QUERY_MULTIPLE_CARD_SUPPORT(=%d) \n", i));
-            break;
-#ifdef SNMP_SUPPORT
-		case RT_OID_802_11_MAC_ADDRESS:
-            wrq->u.data.length = MAC_ADDR_LEN;
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTUREROUI:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTUREROUI \n"));
-			wrq->u.data.length = ManufacturerOUI_LEN;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTURERNAME:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTURERNAME \n"));
-			wrq->u.data.length = strlen(ManufacturerNAME);
-			Status = copy_to_user(wrq->u.data.pointer, ManufacturerNAME, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_RESOURCETYPEIDNAME:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_RESOURCETYPEIDNAME \n"));
-			wrq->u.data.length = strlen(ResourceTypeIdName);
-			Status = copy_to_user(wrq->u.data.pointer, ResourceTypeIdName, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED \n"));
-			ulInfo = 1; // 1 is support wep else 2 is not support.
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_POWERMANAGEMENTMODE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_POWERMANAGEMENTMODE \n"));
-			if (pAdapter->StaCfg.Psm == PSMP_ACTION)
-				ulInfo = 1; // 1 is power active else 2 is power save.
-			else
-				ulInfo = 2;
-
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYVALUE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_WEPDEFAULTKEYVALUE \n"));
-			//KeyIdxValue.KeyIdx = pAd->PortCfg.MBSSID[pAd->IoctlIF].DefaultKeyId;
-			pKeyIdxValue = wrq->u.data.pointer;
-			DBGPRINT(RT_DEBUG_TRACE,("KeyIdxValue.KeyIdx = %d, \n",pKeyIdxValue->KeyIdx));
-			valueLen = pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen;
-			NdisMoveMemory(pKeyIdxValue->Value,
-						   &pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key,
-						   valueLen);
-			pKeyIdxValue->Value[valueLen]='\0';
-
-			wrq->u.data.length = sizeof(DefaultKeyIdxValue);
-
-			Status = copy_to_user(wrq->u.data.pointer, pKeyIdxValue, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE,("DefaultKeyId = %d, total len = %d, str len=%d, KeyValue= %02x %02x %02x %02x \n", pAdapter->StaCfg.DefaultKeyId, wrq->u.data.length, pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen,
-			pAdapter->SharedKey[BSS0][0].Key[0],
-			pAdapter->SharedKey[BSS0][1].Key[0],
-			pAdapter->SharedKey[BSS0][2].Key[0],
-			pAdapter->SharedKey[BSS0][3].Key[0]));
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_WEPDEFAULTKEYID \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->StaCfg.DefaultKeyId, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("DefaultKeyId =%d \n", pAdapter->StaCfg.DefaultKeyId));
-			break;
-
-		case RT_OID_802_11_WEPKEYMAPPINGLENGTH:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_WEPKEYMAPPINGLENGTH \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer,
-									&pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen,
-									wrq->u.data.length);
-			break;
-
-		case OID_802_11_SHORTRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_SHORTRETRYLIMIT \n"));
-			wrq->u.data.length = sizeof(ULONG);
-			RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-			ShortRetryLimit = tx_rty_cfg.field.ShortRtyLimit;
-			DBGPRINT(RT_DEBUG_TRACE, ("ShortRetryLimit =%ld,  tx_rty_cfg.field.ShortRetryLimit=%d\n", ShortRetryLimit, tx_rty_cfg.field.ShortRtyLimit));
-			Status = copy_to_user(wrq->u.data.pointer, &ShortRetryLimit, wrq->u.data.length);
-			break;
-
-		case OID_802_11_LONGRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_LONGRETRYLIMIT \n"));
-			wrq->u.data.length = sizeof(ULONG);
-			RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-			LongRetryLimit = tx_rty_cfg.field.LongRtyLimit;
-			DBGPRINT(RT_DEBUG_TRACE, ("LongRetryLimit =%ld,  tx_rty_cfg.field.LongRtyLimit=%d\n", LongRetryLimit, tx_rty_cfg.field.LongRtyLimit));
-			Status = copy_to_user(wrq->u.data.pointer, &LongRetryLimit, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_PRODUCTID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PRODUCTID \n"));
-
-#ifdef RT2870
-			sprintf(tmp, "%04x %04x\n", ((POS_COOKIE)pAdapter->OS_Cookie)->pUsb_Dev->descriptor.idVendor ,((POS_COOKIE)pAdapter->OS_Cookie)->pUsb_Dev->descriptor.idProduct);
-
-#endif // RT2870 //
-			wrq->u.data.length = strlen(tmp);
-			Status = copy_to_user(wrq->u.data.pointer, tmp, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTUREID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTUREID \n"));
-			wrq->u.data.length = strlen(ManufacturerNAME);
-			Status = copy_to_user(wrq->u.data.pointer, ManufacturerNAME, wrq->u.data.length);
-			break;
-
-		case OID_802_11_CURRENTCHANNEL:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CURRENTCHANNEL \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			DBGPRINT(RT_DEBUG_TRACE, ("sizeof UCHAR=%d, channel=%d \n", sizeof(UCHAR), pAdapter->CommonCfg.Channel));
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Channel, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-#endif //SNMP_SUPPORT
-
-		case OID_802_11_BUILD_CHANNEL_EX:
-			{
-				UCHAR value;
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BUILD_CHANNEL_EX \n"));
-				wrq->u.data.length = sizeof(UCHAR);
-#ifdef EXT_BUILD_CHANNEL_LIST
-				DBGPRINT(RT_DEBUG_TRACE, ("Support EXT_BUILD_CHANNEL_LIST.\n"));
-				value = 1;
-#else
-				DBGPRINT(RT_DEBUG_TRACE, ("Doesn't support EXT_BUILD_CHANNEL_LIST.\n"));
-				value = 0;
-#endif // EXT_BUILD_CHANNEL_LIST //
-				Status = copy_to_user(wrq->u.data.pointer, &value, 1);
-				DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			}
-			break;
-
-		case OID_802_11_GET_CH_LIST:
-			{
-				PRT_CHANNEL_LIST_INFO pChListBuf;
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_CH_LIST \n"));
-				if (pAdapter->ChannelListNum == 0)
-				{
-					wrq->u.data.length = 0;
-					break;
-				}
-
-				pChListBuf = (RT_CHANNEL_LIST_INFO *) kmalloc(sizeof(RT_CHANNEL_LIST_INFO), MEM_ALLOC_FLAG);
-				if (pChListBuf == NULL)
-				{
-					wrq->u.data.length = 0;
-					break;
-				}
-
-				pChListBuf->ChannelListNum = pAdapter->ChannelListNum;
-				for (i = 0; i < pChListBuf->ChannelListNum; i++)
-					pChListBuf->ChannelList[i] = pAdapter->ChannelList[i].Channel;
-
-				wrq->u.data.length = sizeof(RT_CHANNEL_LIST_INFO);
-				Status = copy_to_user(wrq->u.data.pointer, pChListBuf, sizeof(RT_CHANNEL_LIST_INFO));
-				DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-
-				if (pChListBuf)
-					kfree(pChListBuf);
-			}
-			break;
-
-		case OID_802_11_GET_COUNTRY_CODE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_COUNTRY_CODE \n"));
-			wrq->u.data.length = 2;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.CountryCode, 2);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-
-		case OID_802_11_GET_CHANNEL_GEOGRAPHY:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_CHANNEL_GEOGRAPHY \n"));
-			wrq->u.data.length = 1;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Geography, 1);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-
-
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_QUERY_DLS:
-			wrq->u.data.length = sizeof(BOOLEAN);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bDLSCapable, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_DLS(=%d)\n", pAdapter->CommonCfg.bDLSCapable));
-			break;
-
-		case RT_OID_802_11_QUERY_DLS_PARAM:
-			{
-				PRT_802_11_DLS_INFO	pDlsInfo = kmalloc(sizeof(RT_802_11_DLS_INFO), GFP_ATOMIC);
-				if (pDlsInfo == NULL)
-					break;
-
-				for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-				{
-					RTMPMoveMemory(&pDlsInfo->Entry[i], &pAdapter->StaCfg.DLSEntry[i], sizeof(RT_802_11_DLS_UI));
-				}
-
-				pDlsInfo->num = MAX_NUM_OF_DLS_ENTRY;
-				wrq->u.data.length = sizeof(RT_802_11_DLS_INFO);
-				Status = copy_to_user(wrq->u.data.pointer, pDlsInfo, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_DLS_PARAM\n"));
-
-				if (pDlsInfo)
-					kfree(pDlsInfo);
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::unknown IOCTL's subcmd = 0x%08x\n", cmd));
-            Status = -EOPNOTSUPP;
-            break;
-    }
-    return Status;
-}
-
-INT rt28xx_sta_ioctl(
-	IN	struct net_device	*net_dev,
-	IN	OUT	struct ifreq	*rq,
-	IN	INT					cmd)
-{
-	POS_COOKIE			pObj;
-	VIRTUAL_ADAPTER		*pVirtualAd = NULL;
-	RTMP_ADAPTER        *pAd = NULL;
-	struct iwreq        *wrq = (struct iwreq *) rq;
-	BOOLEAN				StateMachineTouched = FALSE;
-	INT					Status = NDIS_STATUS_SUCCESS;
-	USHORT				subcmd;
-
-	if (net_dev->priv_flags == INT_MAIN)
-	{
-		pAd = net_dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = net_dev->ml_priv;
-		pAd = pVirtualAd->RtmpDev->ml_priv;
-	}
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	    if (wrq->u.data.pointer == NULL)
-	    {
-		    return Status;
-	    }
-
-	    if (strstr(wrq->u.data.pointer, "OpMode") == NULL)
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		    return -ENETDOWN;
-        }
-    }
-
-	{	// determine this ioctl command is comming from which interface.
-		pObj->ioctl_if_type = INT_MAIN;
-		pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-	switch(cmd)
-	{
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-		case RTPRIV_IOCTL_ATE:
-			{
-				RtmpDoAte(pAd, wrq);
-			}
-			break;
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-        case SIOCGIFHWADDR:
-			DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCGIFHWADDR\n"));
-			memcpy(wrq->u.name, pAd->CurrentAddress, ETH_ALEN);
-			break;
-		case SIOCGIWNAME:
-        {
-        	char *name=&wrq->u.name[0];
-        	rt_ioctl_giwname(net_dev, NULL, name, NULL);
-			break;
-		}
-		case SIOCGIWESSID:  //Get ESSID
-        {
-        	struct iw_point *essid=&wrq->u.essid;
-        	rt_ioctl_giwessid(net_dev, NULL, essid, essid->pointer);
-			break;
-		}
-		case SIOCSIWESSID:  //Set ESSID
-        {
-        	struct iw_point	*essid=&wrq->u.essid;
-        	rt_ioctl_siwessid(net_dev, NULL, essid, essid->pointer);
-			break;
-		}
-		case SIOCSIWNWID:   // set network id (the cell)
-		case SIOCGIWNWID:   // get network id
-			Status = -EOPNOTSUPP;
-			break;
-		case SIOCSIWFREQ:   //set channel/frequency (Hz)
-        {
-        	struct iw_freq *freq=&wrq->u.freq;
-        	rt_ioctl_siwfreq(net_dev, NULL, freq, NULL);
-			break;
-		}
-		case SIOCGIWFREQ:   // get channel/frequency (Hz)
-        {
-        	struct iw_freq *freq=&wrq->u.freq;
-        	rt_ioctl_giwfreq(net_dev, NULL, freq, NULL);
-			break;
-		}
-		case SIOCSIWNICKN: //set node name/nickname
-        {
-        	struct iw_point *data=&wrq->u.data;
-        	rt_ioctl_siwnickn(net_dev, NULL, data, NULL);
-			break;
-		}
-		case SIOCGIWNICKN: //get node name/nickname
-        {
-        	struct iw_point *data=&wrq->u.data;
-        	rt_ioctl_giwnickn(net_dev, NULL, data, NULL);
-			break;
-		}
-		case SIOCGIWRATE:   //get default bit rate (bps)
-		    rt_ioctl_giwrate(net_dev, NULL, &wrq->u, NULL);
-            break;
-	    case SIOCSIWRATE:  //set default bit rate (bps)
-	        rt_ioctl_siwrate(net_dev, NULL, &wrq->u, NULL);
-            break;
-        case SIOCGIWRTS:  // get RTS/CTS threshold (bytes)
-        {
-        	struct iw_param *rts=&wrq->u.rts;
-        	rt_ioctl_giwrts(net_dev, NULL, rts, NULL);
-			break;
-		}
-        case SIOCSIWRTS:  //set RTS/CTS threshold (bytes)
-        {
-        	struct iw_param *rts=&wrq->u.rts;
-        	rt_ioctl_siwrts(net_dev, NULL, rts, NULL);
-			break;
-		}
-        case SIOCGIWFRAG:  //get fragmentation thr (bytes)
-        {
-        	struct iw_param *frag=&wrq->u.frag;
-        	rt_ioctl_giwfrag(net_dev, NULL, frag, NULL);
-			break;
-		}
-        case SIOCSIWFRAG:  //set fragmentation thr (bytes)
-        {
-        	struct iw_param *frag=&wrq->u.frag;
-        	rt_ioctl_siwfrag(net_dev, NULL, frag, NULL);
-			break;
-		}
-        case SIOCGIWENCODE:  //get encoding token & mode
-        {
-        	struct iw_point *erq=&wrq->u.encoding;
-        	if(erq->pointer)
-        		rt_ioctl_giwencode(net_dev, NULL, erq, erq->pointer);
-			break;
-		}
-        case SIOCSIWENCODE:  //set encoding token & mode
-        {
-        	struct iw_point *erq=&wrq->u.encoding;
-        	if(erq->pointer)
-        		rt_ioctl_siwencode(net_dev, NULL, erq, erq->pointer);
-			break;
-		}
-		case SIOCGIWAP:     //get access point MAC addresses
-        {
-        	struct sockaddr *ap_addr=&wrq->u.ap_addr;
-        	rt_ioctl_giwap(net_dev, NULL, ap_addr, ap_addr->sa_data);
-			break;
-		}
-	    case SIOCSIWAP:  //set access point MAC addresses
-        {
-        	struct sockaddr *ap_addr=&wrq->u.ap_addr;
-        	rt_ioctl_siwap(net_dev, NULL, ap_addr, ap_addr->sa_data);
-			break;
-		}
-		case SIOCGIWMODE:   //get operation mode
-        {
-        	__u32 *mode=&wrq->u.mode;
-        	rt_ioctl_giwmode(net_dev, NULL, mode, NULL);
-			break;
-		}
-		case SIOCSIWMODE:   //set operation mode
-        {
-        	__u32 *mode=&wrq->u.mode;
-        	rt_ioctl_siwmode(net_dev, NULL, mode, NULL);
-			break;
-		}
-		case SIOCGIWSENS:   //get sensitivity (dBm)
-		case SIOCSIWSENS:	//set sensitivity (dBm)
-		case SIOCGIWPOWER:  //get Power Management settings
-		case SIOCSIWPOWER:  //set Power Management settings
-		case SIOCGIWTXPOW:  //get transmit power (dBm)
-		case SIOCSIWTXPOW:  //set transmit power (dBm)
-		case SIOCGIWRANGE:	//Get range of parameters
-		case SIOCGIWRETRY:	//get retry limits and lifetime
-		case SIOCSIWRETRY:	//set retry limits and lifetime
-			Status = -EOPNOTSUPP;
-			break;
-		case RT_PRIV_IOCTL:
-			subcmd = wrq->u.data.flags;
-			if( subcmd & OID_GET_SET_TOGGLE)
-				Status = RTMPSetInformation(pAd, rq, subcmd);
-			else
-				Status = RTMPQueryInformation(pAd, rq, subcmd);
-			break;
-		case SIOCGIWPRIV:
-			if (wrq->u.data.pointer)
-			{
-				if ( access_ok(VERIFY_WRITE, wrq->u.data.pointer, sizeof(privtab)) != TRUE)
-					break;
-				wrq->u.data.length = sizeof(privtab) / sizeof(privtab[0]);
-				if (copy_to_user(wrq->u.data.pointer, privtab, sizeof(privtab)))
-					Status = -EFAULT;
-			}
-			break;
-		case RTPRIV_IOCTL_SET:
-			if(access_ok(VERIFY_READ, wrq->u.data.pointer, wrq->u.data.length) != TRUE)
-				break;
-			rt_ioctl_setparam(net_dev, NULL, NULL, wrq->u.data.pointer);
-			break;
-		case RTPRIV_IOCTL_GSITESURVEY:
-			RTMPIoctlGetSiteSurvey(pAd, wrq);
-		    break;
-#ifdef DBG
-		case RTPRIV_IOCTL_MAC:
-			RTMPIoctlMAC(pAd, wrq);
-			break;
-		case RTPRIV_IOCTL_E2P:
-			RTMPIoctlE2PROM(pAd, wrq);
-			break;
-#endif // DBG //
-        case SIOCETHTOOL:
-                break;
-		default:
-			DBGPRINT(RT_DEBUG_ERROR, ("IOCTL::unknown IOCTL's cmd = 0x%08x\n", cmd));
-			Status = -EOPNOTSUPP;
-			break;
-	}
-
-    if(StateMachineTouched) // Upper layer sent a MLME-related operations
-    	RT28XX_MLME_HANDLER(pAd);
-
-	return Status;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set SSID
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_SSID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    NDIS_802_11_SSID                    Ssid, *pSsid=NULL;
-    BOOLEAN                             StateMachineTouched = FALSE;
-    int                                 success = TRUE;
-
-    if( strlen(arg) <= MAX_LEN_OF_SSID)
-    {
-        NdisZeroMemory(&Ssid, sizeof(NDIS_802_11_SSID));
-        if (strlen(arg) != 0)
-        {
-            NdisMoveMemory(Ssid.Ssid, arg, strlen(arg));
-            Ssid.SsidLength = strlen(arg);
-        }
-        else   //ANY ssid
-        {
-            Ssid.SsidLength = 0;
-		    memcpy(Ssid.Ssid, "", 0);
-			pAdapter->StaCfg.BssType = BSS_INFRA;
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-	        pAdapter->StaCfg.WepStatus  = Ndis802_11EncryptionDisabled;
-		}
-        pSsid = &Ssid;
-
-        if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-        {
-            RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-            DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-        }
-
-        pAdapter->MlmeAux.CurrReqIsFromNdis = TRUE;
-        pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-		pAdapter->bConfigChanged = TRUE;
-
-        MlmeEnqueue(pAdapter,
-                    MLME_CNTL_STATE_MACHINE,
-                    OID_802_11_SSID,
-                    sizeof(NDIS_802_11_SSID),
-                    (VOID *)pSsid);
-
-        StateMachineTouched = TRUE;
-        DBGPRINT(RT_DEBUG_TRACE, ("Set_SSID_Proc::(Len=%d,Ssid=%s)\n", Ssid.SsidLength, Ssid.Ssid));
-    }
-    else
-        success = FALSE;
-
-    if (StateMachineTouched) // Upper layer sent a MLME-related operations
-    	RT28XX_MLME_HANDLER(pAdapter);
-
-    return success;
-}
-
-#ifdef WMM_SUPPORT
-/*
-    ==========================================================================
-    Description:
-        Set WmmCapable Enable or Disable
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	BOOLEAN	bWmmCapable;
-
-	bWmmCapable = simple_strtol(arg, 0, 10);
-
-	if ((bWmmCapable == 1)
-#ifdef RT2870
-		&& (pAd->NumberOfPipes >= 5)
-#endif // RT2870 //
-		)
-		pAd->CommonCfg.bWmmCapable = TRUE;
-	else if (bWmmCapable == 0)
-		pAd->CommonCfg.bWmmCapable = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_WmmCapable_Proc::(bWmmCapable=%d)\n",
-		pAd->CommonCfg.bWmmCapable));
-
-	return TRUE;
-}
-#endif // WMM_SUPPORT //
-
-/*
-    ==========================================================================
-    Description:
-        Set Network Type(Infrastructure/Adhoc mode)
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_NetworkType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    UINT32	Value = 0;
-
-    if (strcmp(arg, "Adhoc") == 0)
-	{
-		if (pAdapter->StaCfg.BssType != BSS_ADHOC)
-		{
-			// Config has changed
-			pAdapter->bConfigChanged = TRUE;
-            if (MONITOR_ON(pAdapter))
-            {
-                RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, STANORMAL);
-                RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-				Value &= (~0x80);
-				RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-                OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-                pAdapter->StaCfg.bAutoReconnect = TRUE;
-                LinkDown(pAdapter, FALSE);
-            }
-			if (INFRA_ON(pAdapter))
-			{
-				//BOOLEAN Cancelled;
-				// Set the AutoReconnectSsid to prevent it reconnect to old SSID
-				// Since calling this indicate user don't want to connect to that SSID anymore.
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-				NdisZeroMemory(pAdapter->MlmeAux.AutoReconnectSsid, pAdapter->MlmeAux.AutoReconnectSsidLen);
-
-				LinkDown(pAdapter, FALSE);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event BB!\n"));
-			}
-		}
-		pAdapter->StaCfg.BssType = BSS_ADHOC;
-        pAdapter->net_dev->type = pAdapter->StaCfg.OriDevType;
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(AD-HOC)\n"));
-	}
-    else if (strcmp(arg, "Infra") == 0)
-	{
-		if (pAdapter->StaCfg.BssType != BSS_INFRA)
-		{
-			// Config has changed
-			pAdapter->bConfigChanged = TRUE;
-            if (MONITOR_ON(pAdapter))
-            {
-                RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, STANORMAL);
-                RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-				Value &= (~0x80);
-				RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-                OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-                pAdapter->StaCfg.bAutoReconnect = TRUE;
-                LinkDown(pAdapter, FALSE);
-            }
-			if (ADHOC_ON(pAdapter))
-			{
-				// Set the AutoReconnectSsid to prevent it reconnect to old SSID
-				// Since calling this indicate user don't want to connect to that SSID anymore.
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-				NdisZeroMemory(pAdapter->MlmeAux.AutoReconnectSsid, pAdapter->MlmeAux.AutoReconnectSsidLen);
-
-				LinkDown(pAdapter, FALSE);
-			}
-		}
-		pAdapter->StaCfg.BssType = BSS_INFRA;
-        pAdapter->net_dev->type = pAdapter->StaCfg.OriDevType;
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(INFRA)\n"));
-
-        pAdapter->StaCfg.BssType = BSS_INFRA;
-	}
-    else if (strcmp(arg, "Monitor") == 0)
-    {
-		UCHAR	bbpValue = 0;
-		BCN_TIME_CFG_STRUC csr;
-		OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_INFRA_ON);
-        OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_ADHOC_ON);
-		OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-		// disable all periodic state machine
-		pAdapter->StaCfg.bAutoReconnect = FALSE;
-		// reset all mlme state machine
-		RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-		DBGPRINT(RT_DEBUG_TRACE, ("fOP_STATUS_MEDIA_STATE_CONNECTED \n"));
-        if (pAdapter->CommonCfg.CentralChannel == 0)
-        {
-#ifdef DOT11_N_SUPPORT
-            if (pAdapter->CommonCfg.PhyMode == PHY_11AN_MIXED)
-                pAdapter->CommonCfg.CentralChannel = 36;
-            else
-#endif // DOT11_N_SUPPORT //
-                pAdapter->CommonCfg.CentralChannel = 6;
-        }
-#ifdef DOT11_N_SUPPORT
-        else
-            N_ChannelCheck(pAdapter);
-#endif // DOT11_N_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-	if (pAdapter->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-            pAdapter->CommonCfg.RegTransmitSetting.field.BW == BW_40 &&
-            pAdapter->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_ABOVE)
-		{
-			// 40MHz ,control channel at lower
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			bbpValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_40;
-			//  RX : control channel at lower
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R3, &bbpValue);
-			bbpValue &= (~0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R3, bbpValue);
-
-			RTMP_IO_READ32(pAdapter, TX_BAND_CFG, &Value);
-			Value &= 0xfffffffe;
-			RTMP_IO_WRITE32(pAdapter, TX_BAND_CFG, Value);
-			pAdapter->CommonCfg.CentralChannel = pAdapter->CommonCfg.Channel + 2;
-            AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.CentralChannel, FALSE);
-		    AsicLockChannel(pAdapter, pAdapter->CommonCfg.CentralChannel);
-            DBGPRINT(RT_DEBUG_TRACE, ("BW_40 ,control_channel(%d), CentralChannel(%d) \n",
-                                       pAdapter->CommonCfg.Channel,
-                                       pAdapter->CommonCfg.CentralChannel));
-		}
-		else if (pAdapter->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-                 pAdapter->CommonCfg.RegTransmitSetting.field.BW == BW_40 &&
-                 pAdapter->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_BELOW)
-		{
-			// 40MHz ,control channel at upper
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			bbpValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_40;
-			RTMP_IO_READ32(pAdapter, TX_BAND_CFG, &Value);
-			Value |= 0x1;
-			RTMP_IO_WRITE32(pAdapter, TX_BAND_CFG, Value);
-
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R3, &bbpValue);
-			bbpValue |= (0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R3, bbpValue);
-			pAdapter->CommonCfg.CentralChannel = pAdapter->CommonCfg.Channel - 2;
-            AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.CentralChannel, FALSE);
-		    AsicLockChannel(pAdapter, pAdapter->CommonCfg.CentralChannel);
-            DBGPRINT(RT_DEBUG_TRACE, ("BW_40 ,control_channel(%d), CentralChannel(%d) \n",
-                                       pAdapter->CommonCfg.Channel,
-                                       pAdapter->CommonCfg.CentralChannel));
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			// 20MHz
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_20;
-			AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.Channel, FALSE);
-			AsicLockChannel(pAdapter, pAdapter->CommonCfg.Channel);
-			DBGPRINT(RT_DEBUG_TRACE, ("BW_20, Channel(%d)\n", pAdapter->CommonCfg.Channel));
-		}
-		// Enable Rx with promiscuous reception
-		RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, 0x3);
-		// ASIC supporsts sniffer function with replacing RSSI with timestamp.
-		//RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-		//Value |= (0x80);
-		//RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-		// disable sync
-		RTMP_IO_READ32(pAdapter, BCN_TIME_CFG, &csr.word);
-		csr.field.bBeaconGen = 0;
-		csr.field.bTBTTEnable = 0;
-		csr.field.TsfSyncMode = 0;
-		RTMP_IO_WRITE32(pAdapter, BCN_TIME_CFG, csr.word);
-
-		pAdapter->StaCfg.BssType = BSS_MONITOR;
-        pAdapter->net_dev->type = ARPHRD_IEEE80211_PRISM; //ARPHRD_IEEE80211; // IEEE80211
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(MONITOR)\n"));
-    }
-
-    // Reset Ralink supplicant to not use, it will be set to start when UI set PMK key
-    pAdapter->StaCfg.WpaState = SS_NOTUSE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_NetworkType_Proc::(NetworkType=%d)\n", pAdapter->StaCfg.BssType));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Authentication mode
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_AuthMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if ((strcmp(arg, "WEPAUTO") == 0) || (strcmp(arg, "wepauto") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeAutoSwitch;
-    else if ((strcmp(arg, "OPEN") == 0) || (strcmp(arg, "open") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-    else if ((strcmp(arg, "SHARED") == 0) || (strcmp(arg, "shared") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-    else if ((strcmp(arg, "WPAPSK") == 0) || (strcmp(arg, "wpapsk") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPAPSK;
-    else if ((strcmp(arg, "WPANONE") == 0) || (strcmp(arg, "wpanone") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
-    else if ((strcmp(arg, "WPA2PSK") == 0) || (strcmp(arg, "wpa2psk") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-#ifdef WPA_SUPPLICANT_SUPPORT
-    else if ((strcmp(arg, "WPA") == 0) || (strcmp(arg, "wpa") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
-    else if ((strcmp(arg, "WPA2") == 0) || (strcmp(arg, "wpa2") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#endif // WPA_SUPPLICANT_SUPPORT //
-    else
-        return FALSE;
-
-    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_AuthMode_Proc::(AuthMode=%d)\n", pAdapter->StaCfg.AuthMode));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Encryption Type
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_EncrypType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if ((strcmp(arg, "NONE") == 0) || (strcmp(arg, "none") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11WEPDisabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11WEPDisabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11WEPDisabled;
-    }
-    else if ((strcmp(arg, "WEP") == 0) || (strcmp(arg, "wep") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11WEPEnabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11WEPEnabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11WEPEnabled;
-    }
-    else if ((strcmp(arg, "TKIP") == 0) || (strcmp(arg, "tkip") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11Encryption2Enabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11Encryption2Enabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11Encryption2Enabled;
-    }
-    else if ((strcmp(arg, "AES") == 0) || (strcmp(arg, "aes") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11Encryption3Enabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11Encryption3Enabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11Encryption3Enabled;
-    }
-    else
-        return FALSE;
-
-    pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_EncrypType_Proc::(EncrypType=%d)\n", pAdapter->StaCfg.WepStatus));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Default Key ID
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_DefaultKeyID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    ULONG                               KeyIdx;
-
-    KeyIdx = simple_strtol(arg, 0, 10);
-    if((KeyIdx >= 1 ) && (KeyIdx <= 4))
-        pAdapter->StaCfg.DefaultKeyId = (UCHAR) (KeyIdx - 1 );
-    else
-        return FALSE;  //Invalid argument
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_DefaultKeyID_Proc::(DefaultKeyID=%d)\n", pAdapter->StaCfg.DefaultKeyId));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY1
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key1_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][0].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][0].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][0].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][0].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-
-    pAdapter->SharedKey[BSS0][0].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              0,
-                              pAdapter->SharedKey[BSS0][0].CipherAlg,
-                              pAdapter->SharedKey[BSS0][0].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-
-    Description:
-        Set WEP KEY2
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key2_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][1].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][1].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][1].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][1].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][1].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              1,
-                              pAdapter->SharedKey[BSS0][1].CipherAlg,
-                              pAdapter->SharedKey[BSS0][1].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY3
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key3_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][2].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Ascii)\n", arg));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][2].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Hex)\n", arg));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][2].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Ascii)\n", arg));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][2].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Hex)\n", arg));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][2].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              2,
-                              pAdapter->SharedKey[BSS0][2].CipherAlg,
-                              pAdapter->SharedKey[BSS0][2].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY4
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key4_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][3].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][3].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][3].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][3].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][3].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              3,
-                              pAdapter->SharedKey[BSS0][3].CipherAlg,
-                              pAdapter->SharedKey[BSS0][3].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set WPA PSK key
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_WPAPSK_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    UCHAR                   keyMaterial[40];
-
-    if ((pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPAPSK) &&
-        (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-	    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone)
-		)
-        return TRUE;    // do nothing
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_WPAPSK_Proc::(WPAPSK=%s)\n", arg));
-
-    NdisZeroMemory(keyMaterial, 40);
-
-    if ((strlen(arg) < 8) || (strlen(arg) > 64))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("Set failed!!(WPAPSK=%s), WPAPSK key-string required 8 ~ 64 characters \n", arg));
-        return FALSE;
-    }
-
-    if (strlen(arg) == 64)
-    {
-        AtoH(arg, keyMaterial, 32);
-        NdisMoveMemory(pAdapter->StaCfg.PMK, keyMaterial, 32);
-
-    }
-    else
-    {
-        PasswordHash((char *)arg, pAdapter->MlmeAux.Ssid, pAdapter->MlmeAux.SsidLen, keyMaterial);
-        NdisMoveMemory(pAdapter->StaCfg.PMK, keyMaterial, 32);
-    }
-
-
-
-    if(pAdapter->StaCfg.BssType == BSS_ADHOC &&
-       pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-    {
-         pAdapter->StaCfg.WpaState = SS_NOTUSE;
-    }
-    else
-    {
-        // Start STA supplicant state machine
-        pAdapter->StaCfg.WpaState = SS_START;
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Power Saving mode
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_PSMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if (pAdapter->StaCfg.BssType == BSS_INFRA)
-    {
-        if ((strcmp(arg, "Max_PSP") == 0) ||
-			(strcmp(arg, "max_psp") == 0) ||
-			(strcmp(arg, "MAX_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeMAX_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeMAX_PSP;
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            pAdapter->StaCfg.DefaultListenCount = 5;
-
-        }
-        else if ((strcmp(arg, "Fast_PSP") == 0) ||
-				 (strcmp(arg, "fast_psp") == 0) ||
-                 (strcmp(arg, "FAST_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeFast_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeFast_PSP;
-            pAdapter->StaCfg.DefaultListenCount = 3;
-        }
-        else if ((strcmp(arg, "Legacy_PSP") == 0) ||
-                 (strcmp(arg, "legacy_psp") == 0) ||
-                 (strcmp(arg, "LEGACY_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeLegacy_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeLegacy_PSP;
-            pAdapter->StaCfg.DefaultListenCount = 3;
-        }
-        else
-        {
-            //Default Ndis802_11PowerModeCAM
-            // clear PSM bit immediately
-            MlmeSetPsmBit(pAdapter, PWR_ACTIVE);
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeCAM;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeCAM;
-        }
-
-        DBGPRINT(RT_DEBUG_TRACE, ("Set_PSMode_Proc::(PSMode=%ld)\n", pAdapter->StaCfg.WindowsPowerMode));
-    }
-    else
-        return FALSE;
-
-
-    return TRUE;
-}
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-/*
-    ==========================================================================
-    Description:
-        Set WpaSupport flag.
-    Value:
-        0: Driver ignore wpa_supplicant.
-        1: wpa_supplicant initiates scanning and AP selection.
-        2: driver takes care of scanning, AP selection, and IEEE 802.11 association parameters.
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Wpa_Support(
-    IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-    if ( simple_strtol(arg, 0, 10) == 0)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_DISABLE;
-    else if ( simple_strtol(arg, 0, 10) == 1)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_ENABLE;
-    else if ( simple_strtol(arg, 0, 10) == 2)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_ENABLE_WITH_WEB_UI;
-    else
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_DISABLE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_Wpa_Support::(WpaSupplicantUP=%d)\n", pAd->StaCfg.WpaSupplicantUP));
-
-    return TRUE;
-}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef DBG
-/*
-    ==========================================================================
-    Description:
-        Read / Write MAC
-    Arguments:
-        pAdapter                    Pointer to our adapter
-        wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-               1.) iwpriv ra0 mac 0        ==> read MAC where Addr=0x0
-               2.) iwpriv ra0 mac 0=12     ==> write MAC where Addr=0x0, value=12
-    ==========================================================================
-*/
-VOID RTMPIoctlMAC(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	CHAR				*this_char;
-	CHAR				*value;
-	INT					j = 0, k = 0;
-	CHAR				msg[1024];
-	CHAR				arg[255];
-	ULONG				macAddr = 0;
-	UCHAR				temp[16], temp2[16];
-	UINT32				macValue = 0;
-	INT					Status;
-
-
-	memset(msg, 0x00, 1024);
-	if (wrq->u.data.length > 1) //No parameters.
-	{
-	    Status = copy_from_user(arg, wrq->u.data.pointer, (wrq->u.data.length > 255) ? 255 : wrq->u.data.length);
-		sprintf(msg, "\n");
-
-		//Parsing Read or Write
-	    this_char = arg;
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-			// Sanity check
-			if(strlen(this_char) > 4)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			// Mac Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			if(strlen(this_char) == 4)
-			{
-				AtoH(this_char, temp, 2);
-				macAddr = *temp*256 + temp[1];
-				if (macAddr < 0xFFFF)
-				{
-					RTMP_IO_READ32(pAdapter, macAddr, &macValue);
-					DBGPRINT(RT_DEBUG_TRACE, ("MacAddr=%lx, MacValue=%x\n", macAddr, macValue));
-					sprintf(msg+strlen(msg), "[0x%08lX]:%08X  ", macAddr , macValue);
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					goto next;
-				}
-			}
-		}
-		else
-		{ //Write
-			memcpy(&temp2, value, strlen(value));
-			temp2[strlen(value)] = '\0';
-
-			// Sanity check
-			if((strlen(this_char) > 4) || strlen(temp2) > 8)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			j = strlen(temp2);
-			while(j-- > 0)
-			{
-				if(temp2[j] > 'f' || temp2[j] < '0')
-					return;
-			}
-
-			//MAC Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			//MAC value
-			k = j = strlen(temp2);
-			while(j-- > 0)
-			{
-				temp2[8-k+j] = temp2[j];
-			}
-
-			while(k < 8)
-				temp2[7-k++]='0';
-			temp2[8]='\0';
-
-			{
-				AtoH(this_char, temp, 2);
-				macAddr = *temp*256 + temp[1];
-
-				AtoH(temp2, temp, 4);
-				macValue = *temp*256*256*256 + temp[1]*256*256 + temp[2]*256 + temp[3];
-
-				// debug mode
-				if (macAddr == (HW_DEBUG_SETTING_BASE + 4))
-				{
-					// 0x2bf4: byte0 non-zero: enable R17 tuning, 0: disable R17 tuning
-                    if (macValue & 0x000000ff)
-                    {
-                        pAdapter->BbpTuning.bEnable = TRUE;
-                        DBGPRINT(RT_DEBUG_TRACE,("turn on R17 tuning\n"));
-                    }
-                    else
-                    {
-                        UCHAR R66;
-                        pAdapter->BbpTuning.bEnable = FALSE;
-                        R66 = 0x26 + GET_LNA_GAIN(pAdapter);
-#ifdef RALINK_ATE
-						if (ATE_ON(pAdapter))
-						{
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R66, (0x26 + GET_LNA_GAIN(pAdapter)));
-						}
-						else
-#endif // RALINK_ATE //
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R66, (0x26 + GET_LNA_GAIN(pAdapter)));
-                        DBGPRINT(RT_DEBUG_TRACE,("turn off R17 tuning, restore to 0x%02x\n", R66));
-                    }
-					return;
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE, ("MacAddr=%02lx, MacValue=0x%x\n", macAddr, macValue));
-
-				RTMP_IO_WRITE32(pAdapter, macAddr, macValue);
-				sprintf(msg+strlen(msg), "[0x%08lX]:%08X  ", macAddr, macValue);
-			}
-		}
-	}
-next:
-	if(strlen(msg) == 1)
-		sprintf(msg+strlen(msg), "===>Error command format!");
-
-	// Copy the information into the user buffer
-	wrq->u.data.length = strlen(msg);
-	Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==RTMPIoctlMAC\n\n"));
-}
-
-/*
-    ==========================================================================
-    Description:
-        Read / Write E2PROM
-    Arguments:
-        pAdapter                    Pointer to our adapter
-        wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-               1.) iwpriv ra0 e2p 0     	==> read E2PROM where Addr=0x0
-               2.) iwpriv ra0 e2p 0=1234    ==> write E2PROM where Addr=0x0, value=1234
-    ==========================================================================
-*/
-VOID RTMPIoctlE2PROM(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	CHAR				*this_char;
-	CHAR				*value;
-	INT					j = 0, k = 0;
-	CHAR				msg[1024];
-	CHAR				arg[255];
-	USHORT				eepAddr = 0;
-	UCHAR				temp[16], temp2[16];
-	USHORT				eepValue;
-	int					Status;
-
-
-	memset(msg, 0x00, 1024);
-	if (wrq->u.data.length > 1) //No parameters.
-	{
-	    Status = copy_from_user(arg, wrq->u.data.pointer, (wrq->u.data.length > 255) ? 255 : wrq->u.data.length);
-		sprintf(msg, "\n");
-
-	    //Parsing Read or Write
-		this_char = arg;
-
-
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-
-			// Sanity check
-			if(strlen(this_char) > 4)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			// E2PROM addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			if(strlen(this_char) == 4)
-			{
-				AtoH(this_char, temp, 2);
-				eepAddr = *temp*256 + temp[1];
-				if (eepAddr < 0xFFFF)
-				{
-					RT28xx_EEPROM_READ16(pAdapter, eepAddr, eepValue);
-					sprintf(msg+strlen(msg), "[0x%04X]:0x%04X  ", eepAddr , eepValue);
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					goto next;
-				}
-			}
-		}
-		else
-		{ //Write
-			memcpy(&temp2, value, strlen(value));
-			temp2[strlen(value)] = '\0';
-
-			// Sanity check
-			if((strlen(this_char) > 4) || strlen(temp2) > 8)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-			j = strlen(temp2);
-			while(j-- > 0)
-			{
-				if(temp2[j] > 'f' || temp2[j] < '0')
-					return;
-			}
-
-			//MAC Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			//MAC value
-			k = j = strlen(temp2);
-			while(j-- > 0)
-			{
-				temp2[4-k+j] = temp2[j];
-			}
-
-			while(k < 4)
-				temp2[3-k++]='0';
-			temp2[4]='\0';
-
-			AtoH(this_char, temp, 2);
-			eepAddr = *temp*256 + temp[1];
-
-			AtoH(temp2, temp, 2);
-			eepValue = *temp*256 + temp[1];
-
-			RT28xx_EEPROM_WRITE16(pAdapter, eepAddr, eepValue);
-			sprintf(msg+strlen(msg), "[0x%02X]:%02X  ", eepAddr, eepValue);
-		}
-	}
-next:
-	if(strlen(msg) == 1)
-		sprintf(msg+strlen(msg), "===>Error command format!");
-
-
-	// Copy the information into the user buffer
-	wrq->u.data.length = strlen(msg);
-	Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==RTMPIoctlE2PROM\n"));
-}
-#endif // DBG //
-
-
-
-
-INT Set_TGnWifiTest_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAd->StaCfg.bTGnWifiTest = FALSE;
-    else
-        pAd->StaCfg.bTGnWifiTest = TRUE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IF Set_TGnWifiTest_Proc::(bTGnWifiTest=%d)\n", pAd->StaCfg.bTGnWifiTest));
-	return TRUE;
-}
-
-INT Set_LongRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg)
-{
-	TX_RTY_CFG_STRUC	tx_rty_cfg;
-	UCHAR				LongRetryLimit = (UCHAR)simple_strtol(arg, 0, 10);
-
-	RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-	tx_rty_cfg.field.LongRtyLimit = LongRetryLimit;
-	RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-	DBGPRINT(RT_DEBUG_TRACE, ("IF Set_LongRetryLimit_Proc::(tx_rty_cfg=0x%x)\n", tx_rty_cfg.word));
-	return TRUE;
-}
-
-INT Set_ShortRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg)
-{
-	TX_RTY_CFG_STRUC	tx_rty_cfg;
-	UCHAR				ShortRetryLimit = (UCHAR)simple_strtol(arg, 0, 10);
-
-	RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-	tx_rty_cfg.field.ShortRtyLimit = ShortRetryLimit;
-	RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-	DBGPRINT(RT_DEBUG_TRACE, ("IF Set_ShortRetryLimit_Proc::(tx_rty_cfg=0x%x)\n", tx_rty_cfg.word));
-	return TRUE;
-}
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-INT Set_Ieee80211dClientMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_None;
-    else if (simple_strtol(arg, 0, 10) == 1)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_Flexible;
-    else if (simple_strtol(arg, 0, 10) == 2)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_Strict;
-    else
-        return FALSE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_Ieee802dMode_Proc::(IEEEE0211dMode=%d)\n", pAdapter->StaCfg.IEEE80211dClientMode));
-    return TRUE;
-}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef CARRIER_DETECTION_SUPPORT
-INT Set_CarrierDetect_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-    else
-        pAd->CommonCfg.CarrierDetect.Enable = TRUE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IF Set_CarrierDetect_Proc::(CarrierDetect.Enable=%d)\n", pAd->CommonCfg.CarrierDetect.Enable));
-	return TRUE;
-}
-#endif // CARRIER_DETECTION_SUPPORT //
-
-
-INT	Show_Adhoc_MacTable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PCHAR			extra)
-{
-	INT i;
-
-	sprintf(extra, "\n");
-
-#ifdef DOT11_N_SUPPORT
-	sprintf(extra, "%sHT Operating Mode : %d\n", extra, pAd->CommonCfg.AddHTInfo.AddHtInfo2.OperaionMode);
-#endif // DOT11_N_SUPPORT //
-
-	sprintf(extra, "%s\n%-19s%-4s%-4s%-7s%-7s%-7s%-10s%-6s%-6s%-6s%-6s\n", extra,
-			"MAC", "AID", "BSS", "RSSI0", "RSSI1", "RSSI2", "PhMd", "BW", "MCS", "SGI", "STBC");
-
-	for (i=1; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[i];
-
-		if (strlen(extra) > (IW_PRIV_SIZE_MASK - 30))
-		    break;
-		if ((pEntry->ValidAsCLI || pEntry->ValidAsApCli) && (pEntry->Sst == SST_ASSOC))
-		{
-			sprintf(extra, "%s%02X:%02X:%02X:%02X:%02X:%02X  ", extra,
-				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
-				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5]);
-			sprintf(extra, "%s%-4d", extra, (int)pEntry->Aid);
-			sprintf(extra, "%s%-4d", extra, (int)pEntry->apidx);
-			sprintf(extra, "%s%-7d", extra, pEntry->RssiSample.AvgRssi0);
-			sprintf(extra, "%s%-7d", extra, pEntry->RssiSample.AvgRssi1);
-			sprintf(extra, "%s%-7d", extra, pEntry->RssiSample.AvgRssi2);
-			sprintf(extra, "%s%-10s", extra, GetPhyMode(pEntry->HTPhyMode.field.MODE));
-			sprintf(extra, "%s%-6s", extra, GetBW(pEntry->HTPhyMode.field.BW));
-			sprintf(extra, "%s%-6d", extra, pEntry->HTPhyMode.field.MCS);
-			sprintf(extra, "%s%-6d", extra, pEntry->HTPhyMode.field.ShortGI);
-			sprintf(extra, "%s%-6d", extra, pEntry->HTPhyMode.field.STBC);
-			sprintf(extra, "%s%-10d, %d, %d%%\n", extra, pEntry->DebugFIFOCount, pEntry->DebugTxCount,
-						(pEntry->DebugTxCount) ? ((pEntry->DebugTxCount-pEntry->DebugFIFOCount)*100/pEntry->DebugTxCount) : 0);
-			sprintf(extra, "%s\n", extra);
-		}
-	}
-
-	return TRUE;
-}
-
-
+#include "../rt2860/sta_ioctl.c"
diff --git a/drivers/staging/rt2870/sta_ioctl.c.patch b/drivers/staging/rt2870/sta_ioctl.c.patch
deleted file mode 100644
index 8672b14..0000000
--- a/drivers/staging/rt2870/sta_ioctl.c.patch
+++ /dev/null
@@ -1,18 +0,0 @@
---- sta_ioctl.c	2008-09-19 14:37:52.000000000 +0800
-+++ sta_ioctl.c.fc9	2008-09-19 14:38:20.000000000 +0800
-@@ -49,15 +49,9 @@
-
- #define GROUP_KEY_NO                4
-
--#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
- #define IWE_STREAM_ADD_EVENT(_A, _B, _C, _D, _E)		iwe_stream_add_event(_A, _B, _C, _D, _E)
- #define IWE_STREAM_ADD_POINT(_A, _B, _C, _D, _E)		iwe_stream_add_point(_A, _B, _C, _D, _E)
- #define IWE_STREAM_ADD_VALUE(_A, _B, _C, _D, _E, _F)	iwe_stream_add_value(_A, _B, _C, _D, _E, _F)
--#else
--#define IWE_STREAM_ADD_EVENT(_A, _B, _C, _D, _E)		iwe_stream_add_event(_B, _C, _D, _E)
--#define IWE_STREAM_ADD_POINT(_A, _B, _C, _D, _E)		iwe_stream_add_point(_B, _C, _D, _E)
--#define IWE_STREAM_ADD_VALUE(_A, _B, _C, _D, _E, _F)	iwe_stream_add_value(_B, _C, _D, _E, _F)
--#endif
-
- extern UCHAR    CipherWpa2Template[];
- extern UCHAR    CipherWpaPskTkip[];
diff --git a/drivers/staging/rt2870/tmp60 b/drivers/staging/rt2870/tmp60
deleted file mode 100644
index 975e444..0000000
--- a/drivers/staging/rt2870/tmp60
+++ /dev/null
@@ -1,7037 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    sta_ioctl.c
-
-    Abstract:
-    IOCTL related subroutines
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Rory Chen   01-03-2003    created
-	Rory Chen   02-14-2005    modify to support RT61
-*/
-
-#include	"rt_config.h"
-
-#ifdef DBG
-extern ULONG    RTDebugLevel;
-#endif
-
-#define NR_WEP_KEYS 				4
-#define WEP_SMALL_KEY_LEN 			(40/8)
-#define WEP_LARGE_KEY_LEN 			(104/8)
-
-#define GROUP_KEY_NO                4
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
-#define IWE_STREAM_ADD_EVENT(_A, _B, _C, _D, _E)		iwe_stream_add_event(_A, _B, _C, _D, _E)
-#define IWE_STREAM_ADD_POINT(_A, _B, _C, _D, _E)		iwe_stream_add_point(_A, _B, _C, _D, _E)
-#define IWE_STREAM_ADD_VALUE(_A, _B, _C, _D, _E, _F)	iwe_stream_add_value(_A, _B, _C, _D, _E, _F)
-#else
-#define IWE_STREAM_ADD_EVENT(_A, _B, _C, _D, _E)		iwe_stream_add_event(_B, _C, _D, _E)
-#define IWE_STREAM_ADD_POINT(_A, _B, _C, _D, _E)		iwe_stream_add_point(_B, _C, _D, _E)
-#define IWE_STREAM_ADD_VALUE(_A, _B, _C, _D, _E, _F)	iwe_stream_add_value(_B, _C, _D, _E, _F)
-#endif
-
-extern UCHAR    CipherWpa2Template[];
-extern UCHAR    CipherWpaPskTkip[];
-extern UCHAR    CipherWpaPskTkipLen;
-
-typedef struct PACKED _RT_VERSION_INFO{
-    UCHAR       DriverVersionW;
-    UCHAR       DriverVersionX;
-    UCHAR       DriverVersionY;
-    UCHAR       DriverVersionZ;
-    UINT        DriverBuildYear;
-    UINT        DriverBuildMonth;
-    UINT        DriverBuildDay;
-} RT_VERSION_INFO, *PRT_VERSION_INFO;
-
-struct iw_priv_args privtab[] = {
-{ RTPRIV_IOCTL_SET,
-  IW_PRIV_TYPE_CHAR | 1024, 0,
-  "set"},
-
-{ RTPRIV_IOCTL_SHOW, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  ""},
-{ RTPRIV_IOCTL_SHOW, IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  ""},
-/* --- sub-ioctls definitions --- */
-    { SHOW_CONN_STATUS,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "connStatus" },
-	{ SHOW_DRVIER_VERION,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "driverVer" },
-    { SHOW_BA_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "bainfo" },
-	{ SHOW_DESC_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "descinfo" },
-    { RAIO_OFF,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "radio_off" },
-	{ RAIO_ON,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "radio_on" },
-#ifdef QOS_DLS_SUPPORT
-	{ SHOW_DLS_ENTRY_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "dlsentryinfo" },
-#endif // QOS_DLS_SUPPORT //
-	{ SHOW_CFG_VALUE,
-	  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "show" },
-	{ SHOW_ADHOC_ENTRY_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "adhocEntry" },
-
-/* --- sub-ioctls relations --- */
-
-#ifdef DBG
-{ RTPRIV_IOCTL_BBP,
-  IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  "bbp"},
-{ RTPRIV_IOCTL_MAC,
-  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | 1024,
-  "mac"},
-{ RTPRIV_IOCTL_E2P,
-  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | 1024,
-  "e2p"},
-#endif  /* DBG */
-
-{ RTPRIV_IOCTL_STATISTICS,
-  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  "stat"},
-{ RTPRIV_IOCTL_GSITESURVEY,
-  0, IW_PRIV_TYPE_CHAR | 1024,
-  "get_site_survey"},
-};
-
-INT Set_SSID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef WMM_SUPPORT
-INT	Set_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif
-
-INT Set_NetworkType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_AuthMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_EncrypType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_DefaultKeyID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key1_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key2_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key3_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key4_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_WPAPSK_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-
-INT Set_PSMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-INT Set_Wpa_Support(
-    IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef DBG
-VOID RTMPIoctlBBP(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID RTMPIoctlMAC(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID RTMPIoctlE2PROM(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  struct iwreq    *wrq);
-#endif // DBG //
-
-
-NDIS_STATUS RTMPWPANoneAddKeyProc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN	PVOID			pBuf);
-
-INT Set_FragTest_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef DOT11_N_SUPPORT
-INT Set_TGnWifiTest_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg);
-#endif // DOT11_N_SUPPORT //
-
-INT Set_LongRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg);
-
-INT Set_ShortRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg);
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-INT Set_Ieee80211dClientMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef CARRIER_DETECTION_SUPPORT
-INT Set_CarrierDetect_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg);
-#endif // CARRIER_DETECTION_SUPPORT //
-
-INT	Show_Adhoc_MacTable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PCHAR			extra);
-
-static struct {
-	CHAR *name;
-	INT (*set_proc)(PRTMP_ADAPTER pAdapter, PUCHAR arg);
-} *PRTMP_PRIVATE_SET_PROC, RTMP_PRIVATE_SUPPORT_PROC[] = {
-	{"DriverVersion",				Set_DriverVersion_Proc},
-	{"CountryRegion",				Set_CountryRegion_Proc},
-	{"CountryRegionABand",			Set_CountryRegionABand_Proc},
-	{"SSID",						Set_SSID_Proc},
-	{"WirelessMode",				Set_WirelessMode_Proc},
-	{"TxBurst",					Set_TxBurst_Proc},
-	{"TxPreamble",				Set_TxPreamble_Proc},
-	{"TxPower",					Set_TxPower_Proc},
-	{"Channel",					Set_Channel_Proc},
-	{"BGProtection",				Set_BGProtection_Proc},
-	{"RTSThreshold",				Set_RTSThreshold_Proc},
-	{"FragThreshold",				Set_FragThreshold_Proc},
-#ifdef DOT11_N_SUPPORT
-	{"HtBw",		                Set_HtBw_Proc},
-	{"HtMcs",		                Set_HtMcs_Proc},
-	{"HtGi",		                Set_HtGi_Proc},
-	{"HtOpMode",		            Set_HtOpMode_Proc},
-	{"HtExtcha",		            Set_HtExtcha_Proc},
-	{"HtMpduDensity",		        Set_HtMpduDensity_Proc},
-	{"HtBaWinSize",		        	Set_HtBaWinSize_Proc},
-	{"HtRdg",		        		Set_HtRdg_Proc},
-	{"HtAmsdu",		        		Set_HtAmsdu_Proc},
-	{"HtAutoBa",		        	Set_HtAutoBa_Proc},
-	{"HtBaDecline",					Set_BADecline_Proc},
-	{"HtProtect",		        	Set_HtProtect_Proc},
-	{"HtMimoPs",		        	Set_HtMimoPs_Proc},
-#endif // DOT11_N_SUPPORT //
-
-#ifdef AGGREGATION_SUPPORT
-	{"PktAggregate",				Set_PktAggregate_Proc},
-#endif
-
-#ifdef WMM_SUPPORT
-	{"WmmCapable",					Set_WmmCapable_Proc},
-#endif
-	{"IEEE80211H",					Set_IEEE80211H_Proc},
-    {"NetworkType",                 Set_NetworkType_Proc},
-	{"AuthMode",					Set_AuthMode_Proc},
-	{"EncrypType",					Set_EncrypType_Proc},
-	{"DefaultKeyID",				Set_DefaultKeyID_Proc},
-	{"Key1",						Set_Key1_Proc},
-	{"Key2",						Set_Key2_Proc},
-	{"Key3",						Set_Key3_Proc},
-	{"Key4",						Set_Key4_Proc},
-	{"WPAPSK",						Set_WPAPSK_Proc},
-	{"ResetCounter",				Set_ResetStatCounter_Proc},
-	{"PSMode",                      Set_PSMode_Proc},
-#ifdef DBG
-	{"Debug",						Set_Debug_Proc},
-#endif
-
-#ifdef RALINK_ATE
-	{"ATE",							Set_ATE_Proc},
-	{"ATEDA",						Set_ATE_DA_Proc},
-	{"ATESA",						Set_ATE_SA_Proc},
-	{"ATEBSSID",					Set_ATE_BSSID_Proc},
-	{"ATECHANNEL",					Set_ATE_CHANNEL_Proc},
-	{"ATETXPOW0",					Set_ATE_TX_POWER0_Proc},
-	{"ATETXPOW1",					Set_ATE_TX_POWER1_Proc},
-	{"ATETXANT",					Set_ATE_TX_Antenna_Proc},
-	{"ATERXANT",					Set_ATE_RX_Antenna_Proc},
-	{"ATETXFREQOFFSET",				Set_ATE_TX_FREQOFFSET_Proc},
-	{"ATETXBW",						Set_ATE_TX_BW_Proc},
-	{"ATETXLEN",					Set_ATE_TX_LENGTH_Proc},
-	{"ATETXCNT",					Set_ATE_TX_COUNT_Proc},
-	{"ATETXMCS",					Set_ATE_TX_MCS_Proc},
-	{"ATETXMODE",					Set_ATE_TX_MODE_Proc},
-	{"ATETXGI",						Set_ATE_TX_GI_Proc},
-	{"ATERXFER",					Set_ATE_RX_FER_Proc},
-	{"ATERRF",						Set_ATE_Read_RF_Proc},
-	{"ATEWRF1",						Set_ATE_Write_RF1_Proc},
-	{"ATEWRF2",						Set_ATE_Write_RF2_Proc},
-	{"ATEWRF3",						Set_ATE_Write_RF3_Proc},
-	{"ATEWRF4",						Set_ATE_Write_RF4_Proc},
-	{"ATELDE2P",				    Set_ATE_Load_E2P_Proc},
-	{"ATERE2P",						Set_ATE_Read_E2P_Proc},
-	{"ATESHOW",						Set_ATE_Show_Proc},
-	{"ATEHELP",						Set_ATE_Help_Proc},
-
-#ifdef RALINK_28xx_QA
-	{"TxStop",						Set_TxStop_Proc},
-	{"RxStop",						Set_RxStop_Proc},
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-    {"WpaSupport",                  Set_Wpa_Support},
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-
-	{"FixedTxMode",                 Set_FixedTxMode_Proc},
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	{"OpMode",						Set_OpMode_Proc},
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-#ifdef DOT11_N_SUPPORT
-    {"TGnWifiTest",                 Set_TGnWifiTest_Proc},
-    {"ForceGF",		        		Set_ForceGF_Proc},
-#endif // DOT11_N_SUPPORT //
-#ifdef QOS_DLS_SUPPORT
-	{"DlsAddEntry",					Set_DlsAddEntry_Proc},
-	{"DlsTearDownEntry",			Set_DlsTearDownEntry_Proc},
-#endif // QOS_DLS_SUPPORT //
-	{"LongRetry",	        		Set_LongRetryLimit_Proc},
-	{"ShortRetry",	        		Set_ShortRetryLimit_Proc},
-#ifdef EXT_BUILD_CHANNEL_LIST
-	{"11dClientMode",				Set_Ieee80211dClientMode_Proc},
-#endif // EXT_BUILD_CHANNEL_LIST //
-#ifdef CARRIER_DETECTION_SUPPORT
-	{"CarrierDetect",				Set_CarrierDetect_Proc},
-#endif // CARRIER_DETECTION_SUPPORT //
-
-	{NULL,}
-};
-
-
-VOID RTMPAddKey(
-	IN	PRTMP_ADAPTER	    pAd,
-	IN	PNDIS_802_11_KEY    pKey)
-{
-	ULONG				KeyIdx;
-	MAC_TABLE_ENTRY  	*pEntry;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("RTMPAddKey ------>\n"));
-
-	if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-	{
-		if (pKey->KeyIndex & 0x80000000)
-		{
-		    if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-            {
-                NdisZeroMemory(pAd->StaCfg.PMK, 32);
-                NdisMoveMemory(pAd->StaCfg.PMK, pKey->KeyMaterial, pKey->KeyLength);
-                goto end;
-            }
-		    // Update PTK
-		    NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-            pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-            NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, pKey->KeyMaterial, LEN_TKIP_EK);
-#ifdef WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-            {
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-            else
-#endif // WPA_SUPPLICANT_SUPPORT //
-            {
-            	NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-
-            // Decide its ChiperAlg
-        	if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-        	else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-        	else
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_NONE;
-
-            // Update these related information to MAC_TABLE_ENTRY
-        	pEntry = &pAd->MacTab.Content[BSSID_WCID];
-            NdisMoveMemory(pEntry->PairwiseKey.Key, pAd->SharedKey[BSS0][0].Key, LEN_TKIP_EK);
-        	NdisMoveMemory(pEntry->PairwiseKey.RxMic, pAd->SharedKey[BSS0][0].RxMic, LEN_TKIP_RXMICK);
-        	NdisMoveMemory(pEntry->PairwiseKey.TxMic, pAd->SharedKey[BSS0][0].TxMic, LEN_TKIP_TXMICK);
-        	pEntry->PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-
-        	// Update pairwise key information to ASIC Shared Key Table
-        	AsicAddSharedKeyEntry(pAd,
-        						  BSS0,
-        						  0,
-        						  pAd->SharedKey[BSS0][0].CipherAlg,
-        						  pAd->SharedKey[BSS0][0].Key,
-        						  pAd->SharedKey[BSS0][0].TxMic,
-        						  pAd->SharedKey[BSS0][0].RxMic);
-
-        	// Update ASIC WCID attribute table and IVEIV table
-        	RTMPAddWcidAttributeEntry(pAd,
-        							  BSS0,
-        							  0,
-        							  pAd->SharedKey[BSS0][0].CipherAlg,
-        							  pEntry);
-
-            if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-            {
-                // set 802.1x port control
-	            //pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAd);
-
-                // Indicate Connected for GUI
-                pAd->IndicateMediaState = NdisMediaStateConnected;
-            }
-		}
-        else
-        {
-            // Update GTK
-            pAd->StaCfg.DefaultKeyId = (pKey->KeyIndex & 0xFF);
-            NdisZeroMemory(&pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId], sizeof(CIPHER_KEY));
-            pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].KeyLen = LEN_TKIP_EK;
-            NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, pKey->KeyMaterial, LEN_TKIP_EK);
-#ifdef WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-            {
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-            else
-#endif // WPA_SUPPLICANT_SUPPORT //
-            {
-            	NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-
-            // Update Shared Key CipherAlg
-    		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_NONE;
-    		if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-    			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_TKIP;
-    		else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
-    			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_AES;
-
-            // Update group key information to ASIC Shared Key Table
-        	AsicAddSharedKeyEntry(pAd,
-        						  BSS0,
-        						  pAd->StaCfg.DefaultKeyId,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic);
-
-        	// Update ASIC WCID attribute table and IVEIV table
-        	RTMPAddWcidAttributeEntry(pAd,
-        							  BSS0,
-        							  pAd->StaCfg.DefaultKeyId,
-        							  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-        							  NULL);
-
-            // set 802.1x port control
-	        //pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-			STA_PORT_SECURED(pAd);
-
-            // Indicate Connected for GUI
-            pAd->IndicateMediaState = NdisMediaStateConnected;
-        }
-	}
-	else	// dynamic WEP from wpa_supplicant
-	{
-		UCHAR	CipherAlg;
-    	PUCHAR	Key;
-
-		if(pKey->KeyLength == 32)
-			goto end;
-
-		KeyIdx = pKey->KeyIndex & 0x0fffffff;
-
-		if (KeyIdx < 4)
-		{
-			// it is a default shared key, for Pairwise key setting
-			if (pKey->KeyIndex & 0x80000000)
-			{
-				pEntry = MacTableLookup(pAd, pKey->BSSID);
-
-				if (pEntry)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("RTMPAddKey: Set Pair-wise Key\n"));
-
-					// set key material and key length
- 					pEntry->PairwiseKey.KeyLen = (UCHAR)pKey->KeyLength;
-					NdisMoveMemory(pEntry->PairwiseKey.Key, &pKey->KeyMaterial, pKey->KeyLength);
-
-					// set Cipher type
-					if (pKey->KeyLength == 5)
-						pEntry->PairwiseKey.CipherAlg = CIPHER_WEP64;
-					else
-						pEntry->PairwiseKey.CipherAlg = CIPHER_WEP128;
-
-					// Add Pair-wise key to Asic
-					AsicAddPairwiseKeyEntry(
-						pAd,
-						pEntry->Addr,
-						(UCHAR)pEntry->Aid,
-                		&pEntry->PairwiseKey);
-
-					// update WCID attribute table and IVEIV table for this entry
-					RTMPAddWcidAttributeEntry(
-						pAd,
-						BSS0,
-						KeyIdx, // The value may be not zero
-						pEntry->PairwiseKey.CipherAlg,
-						pEntry);
-
-				}
-			}
-			else
-            {
-				// Default key for tx (shared key)
-				pAd->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-
-				// set key material and key length
-				pAd->SharedKey[BSS0][KeyIdx].KeyLen = (UCHAR) pKey->KeyLength;
-				NdisMoveMemory(pAd->SharedKey[BSS0][KeyIdx].Key, &pKey->KeyMaterial, pKey->KeyLength);
-
-				// Set Ciper type
-				if (pKey->KeyLength == 5)
-					pAd->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_WEP64;
-				else
-					pAd->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_WEP128;
-
-    			CipherAlg = pAd->SharedKey[BSS0][KeyIdx].CipherAlg;
-    			Key = pAd->SharedKey[BSS0][KeyIdx].Key;
-
-				// Set Group key material to Asic
-    			AsicAddSharedKeyEntry(pAd, BSS0, KeyIdx, CipherAlg, Key, NULL, NULL);
-
-				// Update WCID attribute table and IVEIV table for this group key table
-				RTMPAddWcidAttributeEntry(pAd, BSS0, KeyIdx, CipherAlg, NULL);
-
-			}
-		}
-	}
-end:
-	return;
-}
-
-char * rtstrchr(const char * s, int c)
-{
-    for(; *s != (char) c; ++s)
-        if (*s == '\0')
-            return NULL;
-    return (char *) s;
-}
-
-/*
-This is required for LinEX2004/kernel2.6.7 to provide iwlist scanning function
-*/
-
-int
-rt_ioctl_giwname(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-//	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-#ifdef RT2870
-	strncpy(name, "RT2870 Wireless", IFNAMSIZ);
-#endif // RT2870 //
-	return 0;
-}
-
-int rt_ioctl_siwfreq(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_freq *freq, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-	int 	chan = -1;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-
-	if (freq->e > 1)
-		return -EINVAL;
-
-	if((freq->e == 0) && (freq->m <= 1000))
-		chan = freq->m;	// Setting by channel number
-	else
-		MAP_KHZ_TO_CHANNEL_ID( (freq->m /100) , chan); // Setting by frequency - search the table , like 2.412G, 2.422G,
-
-    if (ChannelSanity(pAdapter, chan) == TRUE)
-    {
-	pAdapter->CommonCfg.Channel = chan;
-	DBGPRINT(RT_DEBUG_ERROR, ("==>rt_ioctl_siwfreq::SIOCSIWFREQ[cmd=0x%x] (Channel=%d)\n", SIOCSIWFREQ, pAdapter->CommonCfg.Channel));
-    }
-    else
-        return -EINVAL;
-
-	return 0;
-}
-int rt_ioctl_giwfreq(struct net_device *dev,
-		   struct iw_request_info *info,
-		   struct iw_freq *freq, char *extra)
-{
-    VIRTUAL_ADAPTER *pVirtualAd = NULL;
-	PRTMP_ADAPTER pAdapter = NULL;
-	UCHAR ch;
-	ULONG	m;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-		ch = pAdapter->CommonCfg.Channel;
-
-	DBGPRINT(RT_DEBUG_TRACE,("==>rt_ioctl_giwfreq  %d\n", ch));
-
-    MAP_CHANNEL_ID_TO_KHZ(ch, m);
-	freq->m = m * 100;
-	freq->e = 1;
-	return 0;
-}
-
-int rt_ioctl_siwmode(struct net_device *dev,
-		   struct iw_request_info *info,
-		   __u32 *mode, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-    	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	switch (*mode)
-	{
-		case IW_MODE_ADHOC:
-			Set_NetworkType_Proc(pAdapter, "Adhoc");
-			break;
-		case IW_MODE_INFRA:
-			Set_NetworkType_Proc(pAdapter, "Infra");
-			break;
-#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20))
-        case IW_MODE_MONITOR:
-			Set_NetworkType_Proc(pAdapter, "Monitor");
-			break;
-#endif
-		default:
-			DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_siwmode::SIOCSIWMODE (unknown %d)\n", *mode));
-			return -EINVAL;
-	}
-
-	// Reset Ralink supplicant to not use, it will be set to start when UI set PMK key
-	pAdapter->StaCfg.WpaState = SS_NOTUSE;
-
-	return 0;
-}
-
-int rt_ioctl_giwmode(struct net_device *dev,
-		   struct iw_request_info *info,
-		   __u32 *mode, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	if (ADHOC_ON(pAdapter))
-		*mode = IW_MODE_ADHOC;
-    else if (INFRA_ON(pAdapter))
-		*mode = IW_MODE_INFRA;
-#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20))
-    else if (MONITOR_ON(pAdapter))
-    {
-        *mode = IW_MODE_MONITOR;
-    }
-#endif
-    else
-        *mode = IW_MODE_AUTO;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==>rt_ioctl_giwmode(mode=%d)\n", *mode));
-	return 0;
-}
-
-int rt_ioctl_siwsens(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-        	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	return 0;
-}
-
-int rt_ioctl_giwsens(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-	return 0;
-}
-
-int rt_ioctl_giwrange(struct net_device *dev,
-		   struct iw_request_info *info,
-		   struct iw_point *data, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-	struct iw_range *range = (struct iw_range *) extra;
-	u16 val;
-	int i;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===>rt_ioctl_giwrange\n"));
-	data->length = sizeof(struct iw_range);
-	memset(range, 0, sizeof(struct iw_range));
-
-	range->txpower_capa = IW_TXPOW_DBM;
-
-	if (INFRA_ON(pAdapter)||ADHOC_ON(pAdapter))
-	{
-		range->min_pmp = 1 * 1024;
-		range->max_pmp = 65535 * 1024;
-		range->min_pmt = 1 * 1024;
-		range->max_pmt = 1000 * 1024;
-		range->pmp_flags = IW_POWER_PERIOD;
-		range->pmt_flags = IW_POWER_TIMEOUT;
-		range->pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT |
-			IW_POWER_UNICAST_R | IW_POWER_ALL_R;
-	}
-
-	range->we_version_compiled = WIRELESS_EXT;
-	range->we_version_source = 14;
-
-	range->retry_capa = IW_RETRY_LIMIT;
-	range->retry_flags = IW_RETRY_LIMIT;
-	range->min_retry = 0;
-	range->max_retry = 255;
-
-	range->num_channels =  pAdapter->ChannelListNum;
-
-	val = 0;
-	for (i = 1; i <= range->num_channels; i++)
-	{
-		u32 m;
-		range->freq[val].i = pAdapter->ChannelList[i-1].Channel;
-		MAP_CHANNEL_ID_TO_KHZ(pAdapter->ChannelList[i-1].Channel, m);
-		range->freq[val].m = m * 100; /* HZ */
-
-		range->freq[val].e = 1;
-		val++;
-		if (val == IW_MAX_FREQUENCIES)
-			break;
-	}
-	range->num_frequency = val;
-
-	range->max_qual.qual = 100; /* what is correct max? This was not
-					* documented exactly. At least
-					* 69 has been observed. */
-	range->max_qual.level = 0; /* dB */
-	range->max_qual.noise = 0; /* dB */
-
-	/* What would be suitable values for "average/typical" qual? */
-	range->avg_qual.qual = 20;
-	range->avg_qual.level = -60;
-	range->avg_qual.noise = -95;
-	range->sensitivity = 3;
-
-	range->max_encoding_tokens = NR_WEP_KEYS;
-	range->num_encoding_sizes = 2;
-	range->encoding_size[0] = 5;
-	range->encoding_size[1] = 13;
-
-	range->min_rts = 0;
-	range->max_rts = 2347;
-	range->min_frag = 256;
-	range->max_frag = 2346;
-
-#if WIRELESS_EXT > 17
-	/* IW_ENC_CAPA_* bit field */
-	range->enc_capa = IW_ENC_CAPA_WPA | IW_ENC_CAPA_WPA2 |
-					IW_ENC_CAPA_CIPHER_TKIP | IW_ENC_CAPA_CIPHER_CCMP;
-#endif
-
-	return 0;
-}
-
-int rt_ioctl_siwap(struct net_device *dev,
-		      struct iw_request_info *info,
-		      struct sockaddr *ap_addr, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-    NDIS_802_11_MAC_ADDRESS Bssid;
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-    {
-        RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-        DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-    }
-
-    // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-    // this request, because this request is initiated by NDIS.
-    pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-	// Prevent to connect AP again in STAMlmePeriodicExec
-	pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-
-    memset(Bssid, 0, MAC_ADDR_LEN);
-    memcpy(Bssid, ap_addr->sa_data, MAC_ADDR_LEN);
-    MlmeEnqueue(pAdapter,
-                MLME_CNTL_STATE_MACHINE,
-                OID_802_11_BSSID,
-                sizeof(NDIS_802_11_MAC_ADDRESS),
-                (VOID *)&Bssid);
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCSIWAP %02x:%02x:%02x:%02x:%02x:%02x\n",
-        Bssid[0], Bssid[1], Bssid[2], Bssid[3], Bssid[4], Bssid[5]));
-
-	return 0;
-}
-
-int rt_ioctl_giwap(struct net_device *dev,
-		      struct iw_request_info *info,
-		      struct sockaddr *ap_addr, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-	{
-		ap_addr->sa_family = ARPHRD_ETHER;
-		memcpy(ap_addr->sa_data, &pAdapter->CommonCfg.Bssid, ETH_ALEN);
-	}
-#ifdef WPA_SUPPLICANT_SUPPORT
-    // Add for RT2870
-    else if (pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-    {
-        ap_addr->sa_family = ARPHRD_ETHER;
-        memcpy(ap_addr->sa_data, &pAdapter->MlmeAux.Bssid, ETH_ALEN);
-    }
-#endif // WPA_SUPPLICANT_SUPPORT //
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCGIWAP(=EMPTY)\n"));
-		return -ENOTCONN;
-	}
-
-	return 0;
-}
-
-/*
- * Units are in db above the noise floor. That means the
- * rssi values reported in the tx/rx descriptors in the
- * driver are the SNR expressed in db.
- *
- * If you assume that the noise floor is -95, which is an
- * excellent assumption 99.5 % of the time, then you can
- * derive the absolute signal level (i.e. -95 + rssi).
- * There are some other slight factors to take into account
- * depending on whether the rssi measurement is from 11b,
- * 11g, or 11a.   These differences are at most 2db and
- * can be documented.
- *
- * NB: various calculations are based on the orinoco/wavelan
- *     drivers for compatibility
- */
-static void set_quality(PRTMP_ADAPTER pAdapter,
-                        struct iw_quality *iq,
-                        signed char rssi)
-{
-	__u8 ChannelQuality;
-
-	// Normalize Rssi
-	if (rssi >= -50)
-		ChannelQuality = 100;
-	else if (rssi >= -80) // between -50 ~ -80dbm
-		ChannelQuality = (__u8)(24 + ((rssi + 80) * 26)/10);
-	else if (rssi >= -90)   // between -80 ~ -90dbm
-        ChannelQuality = (__u8)((rssi + 90) * 26)/10;
-	else
-		ChannelQuality = 0;
-
-    iq->qual = (__u8)ChannelQuality;
-
-    iq->level = (__u8)(rssi);
-    iq->noise = (pAdapter->BbpWriteLatch[66] > pAdapter->BbpTuning.FalseCcaUpperThreshold) ? ((__u8)pAdapter->BbpTuning.FalseCcaUpperThreshold) : ((__u8) pAdapter->BbpWriteLatch[66]); 	// noise level (dBm)
-    iq->noise += 256 - 143;
-    iq->updated = pAdapter->iw_stats.qual.updated;
-}
-
-int rt_ioctl_iwaplist(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
- 	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	struct sockaddr addr[IW_MAX_AP];
-	struct iw_quality qual[IW_MAX_AP];
-	int i;
-
-   	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		data->length = 0;
-		return 0;
-        //return -ENETDOWN;
-	}
-
-	for (i = 0; i <IW_MAX_AP ; i++)
-	{
-		if (i >=  pAdapter->ScanTab.BssNr)
-			break;
-		addr[i].sa_family = ARPHRD_ETHER;
-			memcpy(addr[i].sa_data, &pAdapter->ScanTab.BssEntry[i].Bssid, MAC_ADDR_LEN);
-		set_quality(pAdapter, &qual[i], pAdapter->ScanTab.BssEntry[i].Rssi);
-	}
-	data->length = i;
-	memcpy(extra, &addr, i*sizeof(addr[0]));
-	data->flags = 1;		/* signal quality present (sort of) */
-	memcpy(extra + i*sizeof(addr[0]), &qual, i*sizeof(qual[i]));
-
-	return 0;
-}
-
-#ifdef SIOCGIWSCAN
-int rt_ioctl_siwscan(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	ULONG								Now;
-	int Status = NDIS_STATUS_SUCCESS;
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		return -ENETDOWN;
-	}
-
-	if (MONITOR_ON(pAdapter))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is in Monitor Mode now !!!\n"));
-        return -EINVAL;
-    }
-
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-	if (pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-		pAdapter->StaCfg.WpaSupplicantScanCount++;
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-    pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-		return 0;
-	do{
-		Now = jiffies;
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-		if ((pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE) &&
-			(pAdapter->StaCfg.WpaSupplicantScanCount > 3))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! WpaSupplicantScanCount > 3\n"));
-			Status = NDIS_STATUS_SUCCESS;
-			break;
-		}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-		if ((OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED)) &&
-			((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-			(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)) &&
-			(pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, Port Not Secured! ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-			Status = NDIS_STATUS_SUCCESS;
-			break;
-		}
-
-		if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-		{
-			RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-		}
-
-		// tell CNTL state machine to call NdisMSetInformationComplete() after completing
-		// this request, because this request is initiated by NDIS.
-		pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-		// Reset allowed scan retries
-		pAdapter->StaCfg.ScanCnt = 0;
-		pAdapter->StaCfg.LastScanTime = Now;
-
-		MlmeEnqueue(pAdapter,
-			MLME_CNTL_STATE_MACHINE,
-			OID_802_11_BSSID_LIST_SCAN,
-			0,
-			NULL);
-
-		Status = NDIS_STATUS_SUCCESS;
-		RT28XX_MLME_HANDLER(pAdapter);
-	}while(0);
-	return 0;
-}
-
-int rt_ioctl_giwscan(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
-
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-	int i=0;
-	char *current_ev = extra, *previous_ev = extra;
-	char *end_buf;
-	char *current_val, custom[MAX_CUSTOM_LEN] = {0};
-#ifndef IWEVGENIE
-	char idx;
-#endif // IWEVGENIE //
-	struct iw_event iwe;
-
-	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-    {
-		/*
-		 * Still scanning, indicate the caller should try again.
-		 */
-		return -EAGAIN;
-	}
-
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-	if (pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-		pAdapter->StaCfg.WpaSupplicantScanCount = 0;
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-	if (pAdapter->ScanTab.BssNr == 0)
-	{
-		data->length = 0;
-		return 0;
-	}
-
-#if WIRELESS_EXT >= 17
-    if (data->length > 0)
-        end_buf = extra + data->length;
-    else
-        end_buf = extra + IW_SCAN_MAX_DATA;
-#else
-    end_buf = extra + IW_SCAN_MAX_DATA;
-#endif
-
-	for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-	{
-		if (current_ev >= end_buf)
-        {
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-        }
-
-		//MAC address
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWAP;
-		iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
-				memcpy(iwe.u.ap_addr.sa_data, &pAdapter->ScanTab.BssEntry[i].Bssid, ETH_ALEN);
-
-        previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev,end_buf, &iwe, IW_EV_ADDR_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//ESSID
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWESSID;
-		iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].SsidLen;
-		iwe.u.data.flags = 1;
-
-        previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_POINT(info, current_ev,end_buf, &iwe, pAdapter->ScanTab.BssEntry[i].Ssid);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Network Type
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWMODE;
-		if (pAdapter->ScanTab.BssEntry[i].BssType == Ndis802_11IBSS)
-		{
-			iwe.u.mode = IW_MODE_ADHOC;
-		}
-		else if (pAdapter->ScanTab.BssEntry[i].BssType == Ndis802_11Infrastructure)
-		{
-			iwe.u.mode = IW_MODE_INFRA;
-		}
-		else
-		{
-			iwe.u.mode = IW_MODE_AUTO;
-		}
-		iwe.len = IW_EV_UINT_LEN;
-
-        previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev, end_buf, &iwe,  IW_EV_UINT_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Channel and Frequency
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWFREQ;
-		if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-			iwe.u.freq.m = pAdapter->ScanTab.BssEntry[i].Channel;
-		else
-			iwe.u.freq.m = pAdapter->ScanTab.BssEntry[i].Channel;
-		iwe.u.freq.e = 0;
-		iwe.u.freq.i = 0;
-
-		previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev,end_buf, &iwe, IW_EV_FREQ_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-        //Add quality statistics
-        //================================
-        memset(&iwe, 0, sizeof(iwe));
-    	iwe.cmd = IWEVQUAL;
-    	iwe.u.qual.level = 0;
-    	iwe.u.qual.noise = 0;
-        set_quality(pAdapter, &iwe.u.qual, pAdapter->ScanTab.BssEntry[i].Rssi);
-    	current_ev = IWE_STREAM_ADD_EVENT(info, current_ev, end_buf, &iwe, IW_EV_QUAL_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Encyption key
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWENCODE;
-		if (CAP_IS_PRIVACY_ON (pAdapter->ScanTab.BssEntry[i].CapabilityInfo ))
-			iwe.u.data.flags =IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
-		else
-			iwe.u.data.flags = IW_ENCODE_DISABLED;
-
-        previous_ev = current_ev;
-        current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf,&iwe, (char *)pAdapter->SharedKey[BSS0][(iwe.u.data.flags & IW_ENCODE_INDEX)-1].Key);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Bit Rate
-		//================================
-		if (pAdapter->ScanTab.BssEntry[i].SupRateLen)
-        {
-            UCHAR tmpRate = pAdapter->ScanTab.BssEntry[i].SupRate[pAdapter->ScanTab.BssEntry[i].SupRateLen-1];
-			memset(&iwe, 0, sizeof(iwe));
-			iwe.cmd = SIOCGIWRATE;
-    		current_val = current_ev + IW_EV_LCP_LEN;
-            if (tmpRate == 0x82)
-                iwe.u.bitrate.value =  1 * 1000000;
-            else if (tmpRate == 0x84)
-                iwe.u.bitrate.value =  2 * 1000000;
-            else if (tmpRate == 0x8B)
-                iwe.u.bitrate.value =  5.5 * 1000000;
-            else if (tmpRate == 0x96)
-                iwe.u.bitrate.value =  11 * 1000000;
-            else
-    		    iwe.u.bitrate.value =  (tmpRate/2) * 1000000;
-
-			iwe.u.bitrate.disabled = 0;
-			current_val = IWE_STREAM_ADD_VALUE(info, current_ev,
-				current_val, end_buf, &iwe,
-    			IW_EV_PARAM_LEN);
-
-        	if((current_val-current_ev)>IW_EV_LCP_LEN)
-            	current_ev = current_val;
-        	else
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-
-#ifdef IWEVGENIE
-		//WPA IE
-		if (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen > 0)
-		{
-			memset(&iwe, 0, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-			memcpy(custom, &(pAdapter->ScanTab.BssEntry[i].WpaIE.IE[0]),
-						   pAdapter->ScanTab.BssEntry[i].WpaIE.IELen);
-			iwe.cmd = IWEVGENIE;
-			iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].WpaIE.IELen;
-			current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe, custom);
-			if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-		}
-
-		//WPA2 IE
-        if (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen > 0)
-        {
-        	memset(&iwe, 0, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-			memcpy(custom, &(pAdapter->ScanTab.BssEntry[i].RsnIE.IE[0]),
-						   pAdapter->ScanTab.BssEntry[i].RsnIE.IELen);
-			iwe.cmd = IWEVGENIE;
-			iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].RsnIE.IELen;
-			current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe, custom);
-			if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-#else
-        //WPA IE
-		//================================
-        if (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen > 0)
-        {
-    		NdisZeroMemory(&iwe, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-    		iwe.cmd = IWEVCUSTOM;
-            iwe.u.data.length = (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen * 2) + 7;
-            NdisMoveMemory(custom, "wpa_ie=", 7);
-            for (idx = 0; idx < pAdapter->ScanTab.BssEntry[i].WpaIE.IELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAdapter->ScanTab.BssEntry[i].WpaIE.IE[idx]);
-            previous_ev = current_ev;
-    		current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe,  custom);
-            if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-
-        //WPA2 IE
-        if (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen > 0)
-        {
-    		NdisZeroMemory(&iwe, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-    		iwe.cmd = IWEVCUSTOM;
-            iwe.u.data.length = (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen * 2) + 7;
-            NdisMoveMemory(custom, "rsn_ie=", 7);
-			for (idx = 0; idx < pAdapter->ScanTab.BssEntry[i].RsnIE.IELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAdapter->ScanTab.BssEntry[i].RsnIE.IE[idx]);
-            previous_ev = current_ev;
-    		current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe,  custom);
-            if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-#endif // IWEVGENIE //
-	}
-
-	data->length = current_ev - extra;
-    pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-	DBGPRINT(RT_DEBUG_ERROR ,("===>rt_ioctl_giwscan. %d(%d) BSS returned, data->length = %d\n",i , pAdapter->ScanTab.BssNr, data->length));
-	return 0;
-}
-#endif
-
-int rt_ioctl_siwessid(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *essid)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	if (data->flags)
-	{
-		PCHAR	pSsidString = NULL;
-
-		// Includes null character.
-		if (data->length > (IW_ESSID_MAX_SIZE + 1))
-			return -E2BIG;
-
-		pSsidString = (CHAR *) kmalloc(MAX_LEN_OF_SSID+1, MEM_ALLOC_FLAG);
-		if (pSsidString)
-		{
-			NdisZeroMemory(pSsidString, MAX_LEN_OF_SSID+1);
-			NdisMoveMemory(pSsidString, essid, data->length);
-			if (Set_SSID_Proc(pAdapter, pSsidString) == FALSE)
-				return -EINVAL;
-		}
-		else
-			return -ENOMEM;
-	}
-	else
-	{
-		// ANY ssid
-		if (Set_SSID_Proc(pAdapter, "") == FALSE)
-			return -EINVAL;
-    }
-	return 0;
-}
-
-int rt_ioctl_giwessid(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *essid)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	data->flags = 1;
-    if (MONITOR_ON(pAdapter))
-    {
-        data->length  = 0;
-        return 0;
-    }
-
-	if (OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED))
-	{
-		DBGPRINT(RT_DEBUG_TRACE ,("MediaState is connected\n"));
-		data->length = pAdapter->CommonCfg.SsidLen;
-		memcpy(essid, pAdapter->CommonCfg.Ssid, pAdapter->CommonCfg.SsidLen);
-	}
-#ifdef RT2870
-#ifdef WPA_SUPPLICANT_SUPPORT
-    // Add for RT2870
-    else if (pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-    {
-        data->length = pAdapter->CommonCfg.SsidLen;
-		memcpy(essid, pAdapter->CommonCfg.Ssid, pAdapter->CommonCfg.SsidLen);
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-#endif // RT2870 //
-	else
-	{//the ANY ssid was specified
-		data->length  = 0;
-		DBGPRINT(RT_DEBUG_TRACE ,("MediaState is not connected, ess\n"));
-	}
-
-	return 0;
-
-}
-
-int rt_ioctl_siwnickn(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *nickname)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE ,("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-	if (data->length > IW_ESSID_MAX_SIZE)
-		return -EINVAL;
-
-	memset(pAdapter->nickname, 0, IW_ESSID_MAX_SIZE + 1);
-	memcpy(pAdapter->nickname, nickname, data->length);
-
-
-	return 0;
-}
-
-int rt_ioctl_giwnickn(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *nickname)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	if (data->length > strlen(pAdapter->nickname) + 1)
-		data->length = strlen(pAdapter->nickname) + 1;
-	if (data->length > 0) {
-		memcpy(nickname, pAdapter->nickname, data->length-1);
-		nickname[data->length-1] = '\0';
-	}
-	return 0;
-}
-
-int rt_ioctl_siwrts(struct net_device *dev,
-		       struct iw_request_info *info,
-		       struct iw_param *rts, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-	u16 val;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-	if (rts->disabled)
-		val = MAX_RTS_THRESHOLD;
-	else if (rts->value < 0 || rts->value > MAX_RTS_THRESHOLD)
-		return -EINVAL;
-	else if (rts->value == 0)
-	    val = MAX_RTS_THRESHOLD;
-	else
-		val = rts->value;
-
-	if (val != pAdapter->CommonCfg.RtsThreshold)
-		pAdapter->CommonCfg.RtsThreshold = val;
-
-	return 0;
-}
-
-int rt_ioctl_giwrts(struct net_device *dev,
-		       struct iw_request_info *info,
-		       struct iw_param *rts, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-	rts->value = pAdapter->CommonCfg.RtsThreshold;
-	rts->disabled = (rts->value == MAX_RTS_THRESHOLD);
-	rts->fixed = 1;
-
-	return 0;
-}
-
-int rt_ioctl_siwfrag(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_param *frag, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-	u16 val;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	if (frag->disabled)
-		val = MAX_FRAG_THRESHOLD;
-	else if (frag->value >= MIN_FRAG_THRESHOLD || frag->value <= MAX_FRAG_THRESHOLD)
-        val = __cpu_to_le16(frag->value & ~0x1); /* even numbers only */
-	else if (frag->value == 0)
-	    val = MAX_FRAG_THRESHOLD;
-	else
-		return -EINVAL;
-
-	pAdapter->CommonCfg.FragmentThreshold = val;
-	return 0;
-}
-
-int rt_ioctl_giwfrag(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_param *frag, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-	frag->value = pAdapter->CommonCfg.FragmentThreshold;
-	frag->disabled = (frag->value == MAX_FRAG_THRESHOLD);
-	frag->fixed = 1;
-
-	return 0;
-}
-
-#define MAX_WEP_KEY_SIZE 13
-#define MIN_WEP_KEY_SIZE 5
-int rt_ioctl_siwencode(struct net_device *dev,
-			  struct iw_request_info *info,
-			  struct iw_point *erq, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	if ((erq->length == 0) &&
-        (erq->flags & IW_ENCODE_DISABLED))
-	{
-		pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-		pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-		pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-        pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-        goto done;
-	}
-	else if ((erq->length == 0) &&
-             (erq->flags & IW_ENCODE_RESTRICTED || erq->flags & IW_ENCODE_OPEN))
-	{
-	    //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-		STA_PORT_SECURED(pAdapter);
-		pAdapter->StaCfg.PairCipher = Ndis802_11WEPEnabled;
-		pAdapter->StaCfg.GroupCipher = Ndis802_11WEPEnabled;
-		pAdapter->StaCfg.WepStatus = Ndis802_11WEPEnabled;
-        pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-		if (erq->flags & IW_ENCODE_RESTRICTED)
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-    	else
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-        goto done;
-	}
-
-    if (erq->length > 0)
-	{
-		int keyIdx = (erq->flags & IW_ENCODE_INDEX) - 1;
-		/* Check the size of the key */
-		if (erq->length > MAX_WEP_KEY_SIZE) {
-			return -EINVAL;
-		}
-		/* Check key index */
-		if ((keyIdx < 0) || (keyIdx >= NR_WEP_KEYS))
-        {
-            DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::Wrong keyIdx=%d! Using default key instead (%d)\n",
-                                        keyIdx, pAdapter->StaCfg.DefaultKeyId));
-
-            //Using default key
-			keyIdx = pAdapter->StaCfg.DefaultKeyId;
-        }
-
-        NdisZeroMemory(pAdapter->SharedKey[BSS0][keyIdx].Key,  16);
-
-		if (erq->length == MAX_WEP_KEY_SIZE)
-        {
-			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MAX_WEP_KEY_SIZE;
-            pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP128;
-		}
-		else if (erq->length == MIN_WEP_KEY_SIZE)
-        {
-            pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MIN_WEP_KEY_SIZE;
-            pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP64;
-		}
-		else
-			/* Disable the key */
-			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = 0;
-
-		/* Check if the key is not marked as invalid */
-		if(!(erq->flags & IW_ENCODE_NOKEY)) {
-			/* Copy the key in the driver */
-			NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, extra, erq->length);
-        }
-	}
-    else
-			{
-		/* Do we want to just set the transmit key index ? */
-		int index = (erq->flags & IW_ENCODE_INDEX) - 1;
-		if ((index >= 0) && (index < 4))
-        {
-			pAdapter->StaCfg.DefaultKeyId = index;
-            }
-        else
-			/* Don't complain if only change the mode */
-			if(!erq->flags & IW_ENCODE_MODE) {
-				return -EINVAL;
-		}
-	}
-
-done:
-    DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::erq->flags=%x\n",erq->flags));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::AuthMode=%x\n",pAdapter->StaCfg.AuthMode));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::DefaultKeyId=%x, KeyLen = %d\n",pAdapter->StaCfg.DefaultKeyId , pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::WepStatus=%x\n",pAdapter->StaCfg.WepStatus));
-	return 0;
-}
-
-int
-rt_ioctl_giwencode(struct net_device *dev,
-			  struct iw_request_info *info,
-			  struct iw_point *erq, char *key)
-{
-	int kid;
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-	kid = erq->flags & IW_ENCODE_INDEX;
-	DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_giwencode %d\n", erq->flags & IW_ENCODE_INDEX));
-
-	if (pAdapter->StaCfg.WepStatus == Ndis802_11WEPDisabled)
-	{
-		erq->length = 0;
-		erq->flags = IW_ENCODE_DISABLED;
-	}
-	else if ((kid > 0) && (kid <=4))
-	{
-		// copy wep key
-		erq->flags = kid ;			/* NB: base 1 */
-		if (erq->length > pAdapter->SharedKey[BSS0][kid-1].KeyLen)
-			erq->length = pAdapter->SharedKey[BSS0][kid-1].KeyLen;
-		memcpy(key, pAdapter->SharedKey[BSS0][kid-1].Key, erq->length);
-		//if ((kid == pAdapter->PortCfg.DefaultKeyId))
-		//erq->flags |= IW_ENCODE_ENABLED;	/* XXX */
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-
-	}
-	else if (kid == 0)
-	{
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-		erq->length = pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen;
-		memcpy(key, pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key, erq->length);
-		// copy default key ID
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-		erq->flags = pAdapter->StaCfg.DefaultKeyId + 1;			/* NB: base 1 */
-		erq->flags |= IW_ENCODE_ENABLED;	/* XXX */
-	}
-
-	return 0;
-
-}
-
-static int
-rt_ioctl_setparam(struct net_device *dev, struct iw_request_info *info,
-			 void *w, char *extra)
-{
-    VIRTUAL_ADAPTER	*pVirtualAd = NULL;
-	PRTMP_ADAPTER pAdapter;
-	POS_COOKIE pObj;
-	char *this_char = extra;
-	char *value;
-	int  Status=0;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-	pObj = (POS_COOKIE) pAdapter->OS_Cookie;
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	{
-		pObj->ioctl_if_type = INT_MAIN;
-        pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-			return -ENETDOWN;
-    	}
-
-	if (!*this_char)
-		return -EINVAL;
-
-	if ((value = rtstrchr(this_char, '=')) != NULL)
-	    *value++ = 0;
-
-	if (!value)
-	    return -EINVAL;
-
-	// reject setting nothing besides ANY ssid(ssidLen=0)
-    if (!*value && (strcmp(this_char, "SSID") != 0))
-        return -EINVAL;
-
-	for (PRTMP_PRIVATE_SET_PROC = RTMP_PRIVATE_SUPPORT_PROC; PRTMP_PRIVATE_SET_PROC->name; PRTMP_PRIVATE_SET_PROC++)
-	{
-	    if (strcmp(this_char, PRTMP_PRIVATE_SET_PROC->name) == 0)
-	    {
-	        if(!PRTMP_PRIVATE_SET_PROC->set_proc(pAdapter, value))
-	        {	//FALSE:Set private failed then return Invalid argument
-			    Status = -EINVAL;
-	        }
-		    break;	//Exit for loop.
-	    }
-	}
-
-	if(PRTMP_PRIVATE_SET_PROC->name == NULL)
-	{  //Not found argument
-	    Status = -EINVAL;
-	    DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_setparam:: (iwpriv) Not Support Set Command [%s=%s]\n", this_char, value));
-	}
-
-    return Status;
-}
-
-
-static int
-rt_private_get_statistics(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-{
-	INT				Status = 0;
-    PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-
-    if (extra == NULL)
-    {
-        wrq->length = 0;
-        return -EIO;
-    }
-
-    memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-    sprintf(extra, "\n\n");
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-	    sprintf(extra+strlen(extra), "Tx success                      = %ld\n", (ULONG)pAd->ate.TxDoneCount);
-	    //sprintf(extra+strlen(extra), "Tx success without retry        = %ld\n", (ULONG)pAd->ate.TxDoneCount);
-	}
-	else
-#endif // RALINK_ATE //
-	{
-    sprintf(extra+strlen(extra), "Tx success                      = %ld\n", (ULONG)pAd->WlanCounters.TransmittedFragmentCount.QuadPart);
-    sprintf(extra+strlen(extra), "Tx success without retry        = %ld\n", (ULONG)pAd->WlanCounters.TransmittedFragmentCount.QuadPart - (ULONG)pAd->WlanCounters.RetryCount.QuadPart);
-	}
-    sprintf(extra+strlen(extra), "Tx success after retry          = %ld\n", (ULONG)pAd->WlanCounters.RetryCount.QuadPart);
-    sprintf(extra+strlen(extra), "Tx fail to Rcv ACK after retry  = %ld\n", (ULONG)pAd->WlanCounters.FailedCount.QuadPart);
-    sprintf(extra+strlen(extra), "RTS Success Rcv CTS             = %ld\n", (ULONG)pAd->WlanCounters.RTSSuccessCount.QuadPart);
-    sprintf(extra+strlen(extra), "RTS Fail Rcv CTS                = %ld\n", (ULONG)pAd->WlanCounters.RTSFailureCount.QuadPart);
-
-    sprintf(extra+strlen(extra), "Rx success                      = %ld\n", (ULONG)pAd->WlanCounters.ReceivedFragmentCount.QuadPart);
-    sprintf(extra+strlen(extra), "Rx with CRC                     = %ld\n", (ULONG)pAd->WlanCounters.FCSErrorCount.QuadPart);
-    sprintf(extra+strlen(extra), "Rx drop due to out of resource  = %ld\n", (ULONG)pAd->Counters8023.RxNoBuffer);
-    sprintf(extra+strlen(extra), "Rx duplicate frame              = %ld\n", (ULONG)pAd->WlanCounters.FrameDuplicateCount.QuadPart);
-
-    sprintf(extra+strlen(extra), "False CCA (one second)          = %ld\n", (ULONG)pAd->RalinkCounters.OneSecFalseCCACnt);
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-		if (pAd->ate.RxAntennaSel == 0)
-		{
-    		sprintf(extra+strlen(extra), "RSSI-A                          = %ld\n", (LONG)(pAd->ate.LastRssi0 - pAd->BbpRssiToDbmDelta));
-			sprintf(extra+strlen(extra), "RSSI-B (if available)           = %ld\n", (LONG)(pAd->ate.LastRssi1 - pAd->BbpRssiToDbmDelta));
-			sprintf(extra+strlen(extra), "RSSI-C (if available)           = %ld\n\n", (LONG)(pAd->ate.LastRssi2 - pAd->BbpRssiToDbmDelta));
-		}
-		else
-		{
-    		sprintf(extra+strlen(extra), "RSSI                            = %ld\n", (LONG)(pAd->ate.LastRssi0 - pAd->BbpRssiToDbmDelta));
-		}
-	}
-	else
-#endif // RALINK_ATE //
-	{
-    	sprintf(extra+strlen(extra), "RSSI-A                          = %ld\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi0 - pAd->BbpRssiToDbmDelta));
-        sprintf(extra+strlen(extra), "RSSI-B (if available)           = %ld\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi1 - pAd->BbpRssiToDbmDelta));
-        sprintf(extra+strlen(extra), "RSSI-C (if available)           = %ld\n\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi2 - pAd->BbpRssiToDbmDelta));
-	}
-#ifdef WPA_SUPPLICANT_SUPPORT
-    sprintf(extra+strlen(extra), "WpaSupplicantUP                 = %d\n\n", pAd->StaCfg.WpaSupplicantUP);
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-    DBGPRINT(RT_DEBUG_TRACE, ("<== rt_private_get_statistics, wrq->length = %d\n", wrq->length));
-
-    return Status;
-}
-
-#ifdef DOT11_N_SUPPORT
-void	getBaInfo(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pOutBuf)
-{
-	INT i, j;
-	BA_ORI_ENTRY *pOriBAEntry;
-	BA_REC_ENTRY *pRecBAEntry;
-
-	for (i=0; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[i];
-		if (((pEntry->ValidAsCLI || pEntry->ValidAsApCli) && (pEntry->Sst == SST_ASSOC))
-			|| (pEntry->ValidAsWDS) || (pEntry->ValidAsMesh))
-		{
-			sprintf(pOutBuf, "%s\n%02X:%02X:%02X:%02X:%02X:%02X (Aid = %d) (AP) -\n",
-                pOutBuf,
-				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
-				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5], pEntry->Aid);
-
-			sprintf(pOutBuf, "%s[Recipient]\n", pOutBuf);
-			for (j=0; j < NUM_OF_TID; j++)
-			{
-				if (pEntry->BARecWcidArray[j] != 0)
-				{
-					pRecBAEntry =&pAd->BATable.BARecEntry[pEntry->BARecWcidArray[j]];
-					sprintf(pOutBuf, "%sTID=%d, BAWinSize=%d, LastIndSeq=%d, ReorderingPkts=%d\n", pOutBuf, j, pRecBAEntry->BAWinSize, pRecBAEntry->LastIndSeq, pRecBAEntry->list.qlen);
-				}
-			}
-			sprintf(pOutBuf, "%s\n", pOutBuf);
-
-			sprintf(pOutBuf, "%s[Originator]\n", pOutBuf);
-			for (j=0; j < NUM_OF_TID; j++)
-			{
-				if (pEntry->BAOriWcidArray[j] != 0)
-				{
-					pOriBAEntry =&pAd->BATable.BAOriEntry[pEntry->BAOriWcidArray[j]];
-					sprintf(pOutBuf, "%sTID=%d, BAWinSize=%d, StartSeq=%d, CurTxSeq=%d\n", pOutBuf, j, pOriBAEntry->BAWinSize, pOriBAEntry->Sequence, pEntry->TxSeq[j]);
-				}
-			}
-			sprintf(pOutBuf, "%s\n\n", pOutBuf);
-		}
-        if (strlen(pOutBuf) > (IW_PRIV_SIZE_MASK - 30))
-                break;
-	}
-
-	return;
-}
-#endif // DOT11_N_SUPPORT //
-
-static int
-rt_private_show(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-{
-    INT				Status = 0;
-    VIRTUAL_ADAPTER	*pVirtualAd = NULL;
-    PRTMP_ADAPTER   pAd;
-	POS_COOKIE		pObj;
-    u32             subcmd = wrq->flags;
-
-	if (dev->priv_flags == INT_MAIN)
-		pAd = dev->priv;
-	else
-	{
-		pVirtualAd = dev->priv;
-		pAd = pVirtualAd->RtmpDev->priv;
-	}
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-    if (extra == NULL)
-    {
-        wrq->length = 0;
-        return -EIO;
-    }
-    memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-
-	{
-		pObj->ioctl_if_type = INT_MAIN;
-        pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-    switch(subcmd)
-    {
-
-        case SHOW_CONN_STATUS:
-            if (MONITOR_ON(pAd))
-            {
-#ifdef DOT11_N_SUPPORT
-                if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-                    pAd->CommonCfg.RegTransmitSetting.field.BW)
-                    sprintf(extra, "Monitor Mode(CentralChannel %d)\n", pAd->CommonCfg.CentralChannel);
-                else
-#endif // DOT11_N_SUPPORT //
-                    sprintf(extra, "Monitor Mode(Channel %d)\n", pAd->CommonCfg.Channel);
-            }
-            else
-            {
-                if (pAd->IndicateMediaState == NdisMediaStateConnected)
-            	{
-            	    if (INFRA_ON(pAd))
-                    {
-                    sprintf(extra, "Connected(AP: %s[%02X:%02X:%02X:%02X:%02X:%02X])\n",
-                                    pAd->CommonCfg.Ssid,
-                                    pAd->CommonCfg.Bssid[0],
-                                    pAd->CommonCfg.Bssid[1],
-                                    pAd->CommonCfg.Bssid[2],
-                                    pAd->CommonCfg.Bssid[3],
-                                    pAd->CommonCfg.Bssid[4],
-                                    pAd->CommonCfg.Bssid[5]);
-            		DBGPRINT(RT_DEBUG_TRACE ,("Ssid=%s ,Ssidlen = %d\n",pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen));
-            	}
-                    else if (ADHOC_ON(pAd))
-                        sprintf(extra, "Connected\n");
-            	}
-            	else
-            	{
-            	    sprintf(extra, "Disconnected\n");
-            		DBGPRINT(RT_DEBUG_TRACE ,("ConnStatus is not connected\n"));
-            	}
-            }
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-        case SHOW_DRVIER_VERION:
-            sprintf(extra, "Driver version-%s, %s %s\n", STA_DRIVER_VERSION, __DATE__, __TIME__ );
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-#ifdef DOT11_N_SUPPORT
-        case SHOW_BA_INFO:
-            getBaInfo(pAd, extra);
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-#endif // DOT11_N_SUPPORT //
-		case SHOW_DESC_INFO:
-			{
-				Show_DescInfo_Proc(pAd, NULL);
-				wrq->length = 0; // 1: size of '\0'
-			}
-			break;
-        case RAIO_OFF:
-            if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-                sprintf(extra, "Scanning\n");
-                wrq->length = strlen(extra) + 1; // 1: size of '\0'
-                break;
-            }
-            pAd->StaCfg.bSwRadio = FALSE;
-            if (pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
-            {
-                pAd->StaCfg.bRadio = (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio);
-                if (pAd->StaCfg.bRadio == FALSE)
-                {
-                    MlmeRadioOff(pAd);
-                    // Update extra information
-					pAd->ExtraInfo = SW_RADIO_OFF;
-                }
-            }
-            sprintf(extra, "Radio Off\n");
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-        case RAIO_ON:
-            if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-                sprintf(extra, "Scanning\n");
-                wrq->length = strlen(extra) + 1; // 1: size of '\0'
-                break;
-            }
-            pAd->StaCfg.bSwRadio = TRUE;
-            //if (pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
-            {
-                pAd->StaCfg.bRadio = (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio);
-                if (pAd->StaCfg.bRadio == TRUE)
-                {
-                    MlmeRadioOn(pAd);
-                    // Update extra information
-					pAd->ExtraInfo = EXTRA_INFO_CLEAR;
-                }
-            }
-            sprintf(extra, "Radio On\n");
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-
-
-#ifdef QOS_DLS_SUPPORT
-		case SHOW_DLS_ENTRY_INFO:
-			{
-				Set_DlsEntryInfo_Display_Proc(pAd, NULL);
-				wrq->length = 0; // 1: size of '\0'
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-
-		case SHOW_CFG_VALUE:
-			{
-				Status = RTMPShowCfgValue(pAd, wrq->pointer, extra);
-				if (Status == 0)
-					wrq->length = strlen(extra) + 1; // 1: size of '\0'
-			}
-			break;
-		case SHOW_ADHOC_ENTRY_INFO:
-			Show_Adhoc_MacTable_Proc(pAd, extra);
-			wrq->length = strlen(extra) + 1; // 1: size of '\0'
-			break;
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("%s - unknow subcmd = %d\n", __func__, subcmd));
-            break;
-    }
-
-    return Status;
-}
-
-#ifdef SIOCSIWMLME
-int rt_ioctl_siwmlme(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-{
-	PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-	struct iw_mlme *pMlme = (struct iw_mlme *)wrqu->data.pointer;
-	MLME_QUEUE_ELEM				MsgElem;
-	MLME_DISASSOC_REQ_STRUCT	DisAssocReq;
-	MLME_DEAUTH_REQ_STRUCT      DeAuthReq;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("====> %s\n", __func__));
-
-	if (pMlme == NULL)
-		return -EINVAL;
-
-	switch(pMlme->cmd)
-	{
-#ifdef IW_MLME_DEAUTH
-		case IW_MLME_DEAUTH:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - IW_MLME_DEAUTH\n", __func__));
-			COPY_MAC_ADDR(DeAuthReq.Addr, pAd->CommonCfg.Bssid);
-			DeAuthReq.Reason = pMlme->reason_code;
-			MsgElem.MsgLen = sizeof(MLME_DEAUTH_REQ_STRUCT);
-			NdisMoveMemory(MsgElem.Msg, &DeAuthReq, sizeof(MLME_DEAUTH_REQ_STRUCT));
-			MlmeDeauthReqAction(pAd, &MsgElem);
-			if (INFRA_ON(pAd))
-			{
-			    LinkDown(pAd, FALSE);
-			    pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-			}
-			break;
-#endif // IW_MLME_DEAUTH //
-#ifdef IW_MLME_DISASSOC
-		case IW_MLME_DISASSOC:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - IW_MLME_DISASSOC\n", __func__));
-			COPY_MAC_ADDR(DisAssocReq.Addr, pAd->CommonCfg.Bssid);
-			DisAssocReq.Reason =  pMlme->reason_code;
-
-			MsgElem.Machine = ASSOC_STATE_MACHINE;
-			MsgElem.MsgType = MT2_MLME_DISASSOC_REQ;
-			MsgElem.MsgLen = sizeof(MLME_DISASSOC_REQ_STRUCT);
-			NdisMoveMemory(MsgElem.Msg, &DisAssocReq, sizeof(MLME_DISASSOC_REQ_STRUCT));
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_DISASSOC;
-			MlmeDisassocReqAction(pAd, &MsgElem);
-			break;
-#endif // IW_MLME_DISASSOC //
-		default:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - Unknow Command\n", __func__));
-			break;
-	}
-
-	return 0;
-}
-#endif // SIOCSIWMLME //
-
-#if WIRELESS_EXT > 17
-int rt_ioctl_siwauth(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAdapter = (PRTMP_ADAPTER) dev->priv;
-	struct iw_param *param = &wrqu->param;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-	switch (param->flags & IW_AUTH_INDEX) {
-    	case IW_AUTH_WPA_VERSION:
-            if (param->value == IW_AUTH_WPA_VERSION_WPA)
-            {
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPAPSK;
-				if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-					pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
-            }
-            else if (param->value == IW_AUTH_WPA_VERSION_WPA2)
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_VERSION - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_CIPHER_PAIRWISE:
-            if (param->value == IW_AUTH_CIPHER_NONE)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_WEP40 ||
-                     param->value == IW_AUTH_CIPHER_WEP104)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPEnabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPEnabled;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-            }
-            else if (param->value == IW_AUTH_CIPHER_TKIP)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11Encryption2Enabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_CCMP)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11Encryption3Enabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11Encryption3Enabled;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_CIPHER_PAIRWISE - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_CIPHER_GROUP:
-            if (param->value == IW_AUTH_CIPHER_NONE)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_WEP40 ||
-                     param->value == IW_AUTH_CIPHER_WEP104)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11WEPEnabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_TKIP)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11Encryption2Enabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_CCMP)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11Encryption3Enabled;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_CIPHER_GROUP - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_KEY_MGMT:
-            if (param->value == IW_AUTH_KEY_MGMT_802_1X)
-            {
-                if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)
-                {
-                    pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                    pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                }
-                else if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-                {
-                    pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                    pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                }
-#ifdef WPA_SUPPLICANT_SUPPORT
-                else
-                    // WEP 1x
-                    pAdapter->StaCfg.IEEE8021X = TRUE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-            }
-            else if (param->value == 0)
-            {
-                //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAdapter);
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_KEY_MGMT - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_RX_UNENCRYPTED_EAPOL:
-            break;
-    	case IW_AUTH_PRIVACY_INVOKED:
-            /*if (param->value == 0)
-			{
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-        	    pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-            }*/
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_PRIVACY_INVOKED - param->value = %d!\n", __func__, param->value));
-    		break;
-    	case IW_AUTH_DROP_UNENCRYPTED:
-            if (param->value != 0)
-                pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			else
-			{
-                //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAdapter);
-			}
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_VERSION - param->value = %d!\n", __func__, param->value));
-    		break;
-    	case IW_AUTH_80211_AUTH_ALG:
-			if (param->value & IW_AUTH_ALG_SHARED_KEY)
-            {
-				pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-			}
-            else if (param->value & IW_AUTH_ALG_OPEN_SYSTEM)
-            {
-				pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-			}
-            else
-				return -EINVAL;
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_80211_AUTH_ALG - param->value = %d!\n", __func__, param->value));
-			break;
-    	case IW_AUTH_WPA_ENABLED:
-    		DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_ENABLED - Driver supports WPA!(param->value = %d)\n", __func__, param->value));
-    		break;
-    	default:
-    		return -EOPNOTSUPP;
-}
-
-	return 0;
-}
-
-int rt_ioctl_giwauth(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAdapter = (PRTMP_ADAPTER) dev->priv;
-	struct iw_param *param = &wrqu->param;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-    }
-
-	switch (param->flags & IW_AUTH_INDEX) {
-	case IW_AUTH_DROP_UNENCRYPTED:
-        param->value = (pAdapter->StaCfg.WepStatus == Ndis802_11WEPDisabled) ? 0 : 1;
-		break;
-
-	case IW_AUTH_80211_AUTH_ALG:
-        param->value = (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared) ? IW_AUTH_ALG_SHARED_KEY : IW_AUTH_ALG_OPEN_SYSTEM;
-		break;
-
-	case IW_AUTH_WPA_ENABLED:
-		param->value = (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA) ? 1 : 0;
-		break;
-
-	default:
-		return -EOPNOTSUPP;
-	}
-    DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_giwauth::param->value = %d!\n", param->value));
-	return 0;
-}
-
-void fnSetCipherKey(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  INT             keyIdx,
-    IN  UCHAR           CipherAlg,
-    IN  BOOLEAN         bGTK,
-    IN  struct iw_encode_ext *ext)
-{
-    NdisZeroMemory(&pAdapter->SharedKey[BSS0][keyIdx], sizeof(CIPHER_KEY));
-    pAdapter->SharedKey[BSS0][keyIdx].KeyLen = LEN_TKIP_EK;
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, ext->key, LEN_TKIP_EK);
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].TxMic, ext->key + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].RxMic, ext->key + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CipherAlg;
-
-    // Update group key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAdapter,
-						  BSS0,
-						  keyIdx,
-						  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-						  pAdapter->SharedKey[BSS0][keyIdx].Key,
-						  pAdapter->SharedKey[BSS0][keyIdx].TxMic,
-						  pAdapter->SharedKey[BSS0][keyIdx].RxMic);
-
-    if (bGTK)
-        // Update ASIC WCID attribute table and IVEIV table
-    	RTMPAddWcidAttributeEntry(pAdapter,
-    							  BSS0,
-    							  keyIdx,
-    							  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-    							  NULL);
-    else
-        // Update ASIC WCID attribute table and IVEIV table
-    	RTMPAddWcidAttributeEntry(pAdapter,
-    							  BSS0,
-    							  keyIdx,
-    							  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-    							  &pAdapter->MacTab.Content[BSSID_WCID]);
-}
-
-int rt_ioctl_siwencodeext(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-			{
-    PRTMP_ADAPTER   pAdapter = (PRTMP_ADAPTER) dev->priv;
-	struct iw_point *encoding = &wrqu->encoding;
-	struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
-    int keyIdx, alg = ext->alg;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    if (encoding->flags & IW_ENCODE_DISABLED)
-	{
-        keyIdx = (encoding->flags & IW_ENCODE_INDEX) - 1;
-        // set BSSID wcid entry of the Pair-wise Key table as no-security mode
-	    AsicRemovePairwiseKeyEntry(pAdapter, BSS0, BSSID_WCID);
-        pAdapter->SharedKey[BSS0][keyIdx].KeyLen = 0;
-		pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_NONE;
-		AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)keyIdx);
-        NdisZeroMemory(&pAdapter->SharedKey[BSS0][keyIdx], sizeof(CIPHER_KEY));
-        DBGPRINT(RT_DEBUG_TRACE, ("%s::Remove all keys!(encoding->flags = %x)\n", __func__, encoding->flags));
-    }
-					else
-    {
-        // Get Key Index and convet to our own defined key index
-    	keyIdx = (encoding->flags & IW_ENCODE_INDEX) - 1;
-    	if((keyIdx < 0) || (keyIdx >= NR_WEP_KEYS))
-    		return -EINVAL;
-
-        if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-        {
-            pAdapter->StaCfg.DefaultKeyId = keyIdx;
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::DefaultKeyId = %d\n", __func__, pAdapter->StaCfg.DefaultKeyId));
-        }
-
-        switch (alg) {
-    		case IW_ENCODE_ALG_NONE:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_NONE\n", __func__));
-    			break;
-    		case IW_ENCODE_ALG_WEP:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_WEP - ext->key_len = %d, keyIdx = %d\n", __func__, ext->key_len, keyIdx));
-    			if (ext->key_len == MAX_WEP_KEY_SIZE)
-                {
-        			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MAX_WEP_KEY_SIZE;
-                    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP128;
-				}
-        		else if (ext->key_len == MIN_WEP_KEY_SIZE)
-                {
-                    pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MIN_WEP_KEY_SIZE;
-                    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP64;
-			}
-        		else
-                    return -EINVAL;
-
-                NdisZeroMemory(pAdapter->SharedKey[BSS0][keyIdx].Key,  16);
-			    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, ext->key, ext->key_len);
-    			break;
-            case IW_ENCODE_ALG_TKIP:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_TKIP - keyIdx = %d, ext->key_len = %d\n", __func__, keyIdx, ext->key_len));
-                if (ext->key_len == 32)
-                {
-                    if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-                    {
-                        fnSetCipherKey(pAdapter, keyIdx, CIPHER_TKIP, FALSE, ext);
-                        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-                        {
-                            //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-                            STA_PORT_SECURED(pAdapter);
-                        }
-		}
-                    else if (ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY)
-                    {
-                        fnSetCipherKey(pAdapter, keyIdx, CIPHER_TKIP, TRUE, ext);
-
-                        // set 802.1x port control
-            	        //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-            	        STA_PORT_SECURED(pAdapter);
-                    }
-                }
-                else
-                    return -EINVAL;
-                break;
-            case IW_ENCODE_ALG_CCMP:
-                if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-		{
-                    fnSetCipherKey(pAdapter, keyIdx, CIPHER_AES, FALSE, ext);
-                    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-                    	//pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-                    	STA_PORT_SECURED(pAdapter);
-                }
-                else if (ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY)
-                {
-                    fnSetCipherKey(pAdapter, keyIdx, CIPHER_AES, TRUE, ext);
-
-                    // set 802.1x port control
-        	        //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-        	        STA_PORT_SECURED(pAdapter);
-                }
-                break;
-    		default:
-    			return -EINVAL;
-		}
-    }
-
-    return 0;
-}
-
-int
-rt_ioctl_giwencodeext(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER pAd = (PRTMP_ADAPTER) dev->priv;
-	PCHAR pKey = NULL;
-	struct iw_point *encoding = &wrqu->encoding;
-	struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
-	int idx, max_key_len;
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===> rt_ioctl_giwencodeext\n"));
-
-	max_key_len = encoding->length - sizeof(*ext);
-	if (max_key_len < 0)
-		return -EINVAL;
-
-	idx = encoding->flags & IW_ENCODE_INDEX;
-	if (idx)
-	{
-		if (idx < 1 || idx > 4)
-			return -EINVAL;
-		idx--;
-
-		if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
-			(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled))
-		{
-			if (idx != pAd->StaCfg.DefaultKeyId)
-			{
-				ext->key_len = 0;
-				return 0;
-			}
-		}
-	}
-	else
-		idx = pAd->StaCfg.DefaultKeyId;
-
-	encoding->flags = idx + 1;
-	memset(ext, 0, sizeof(*ext));
-
-	ext->key_len = 0;
-	switch(pAd->StaCfg.WepStatus) {
-		case Ndis802_11WEPDisabled:
-			ext->alg = IW_ENCODE_ALG_NONE;
-			encoding->flags |= IW_ENCODE_DISABLED;
-			break;
-		case Ndis802_11WEPEnabled:
-			ext->alg = IW_ENCODE_ALG_WEP;
-			if (pAd->SharedKey[BSS0][idx].KeyLen > max_key_len)
-				return -E2BIG;
-			else
-			{
-				ext->key_len = pAd->SharedKey[BSS0][idx].KeyLen;
-				pKey = &(pAd->SharedKey[BSS0][idx].Key[0]);
-			}
-			break;
-		case Ndis802_11Encryption2Enabled:
-		case Ndis802_11Encryption3Enabled:
-			if (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled)
-				ext->alg = IW_ENCODE_ALG_TKIP;
-			else
-				ext->alg = IW_ENCODE_ALG_CCMP;
-
-			if (max_key_len < 32)
-				return -E2BIG;
-			else
-			{
-				ext->key_len = 32;
-				pKey = &pAd->StaCfg.PMK[0];
-			}
-			break;
-		default:
-			return -EINVAL;
-	}
-
-	if (ext->key_len && pKey)
-	{
-		encoding->flags |= IW_ENCODE_ENABLED;
-		memcpy(ext->key, pKey, ext->key_len);
-	}
-
-	return 0;
-}
-
-#ifdef SIOCSIWGENIE
-int rt_ioctl_siwgenie(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-
-	if (wrqu->data.length > MAX_LEN_OF_RSNIE ||
-	    (wrqu->data.length && extra == NULL))
-		return -EINVAL;
-
-	if (wrqu->data.length)
-	{
-		pAd->StaCfg.RSNIE_Len = wrqu->data.length;
-		NdisMoveMemory(&pAd->StaCfg.RSN_IE[0], extra, pAd->StaCfg.RSNIE_Len);
-	}
-	else
-	{
-		pAd->StaCfg.RSNIE_Len = 0;
-		NdisZeroMemory(&pAd->StaCfg.RSN_IE[0], MAX_LEN_OF_RSNIE);
-	}
-
-	return 0;
-}
-#endif // SIOCSIWGENIE //
-
-int rt_ioctl_giwgenie(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-
-	if ((pAd->StaCfg.RSNIE_Len == 0) ||
-		(pAd->StaCfg.AuthMode < Ndis802_11AuthModeWPA))
-	{
-		wrqu->data.length = 0;
-		return 0;
-	}
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-#ifdef SIOCSIWGENIE
-	if (pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-	if (wrqu->data.length < pAd->StaCfg.RSNIE_Len)
-		return -E2BIG;
-
-	wrqu->data.length = pAd->StaCfg.RSNIE_Len;
-	memcpy(extra, &pAd->StaCfg.RSN_IE[0], pAd->StaCfg.RSNIE_Len);
-	}
-	else
-#endif // SIOCSIWGENIE //
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-	{
-		UCHAR RSNIe = IE_WPA;
-
-		if (wrqu->data.length < (pAd->StaCfg.RSNIE_Len + 2)) // ID, Len
-			return -E2BIG;
-		wrqu->data.length = pAd->StaCfg.RSNIE_Len + 2;
-
-		if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-            (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2))
-			RSNIe = IE_RSN;
-
-		extra[0] = (char)RSNIe;
-		extra[1] = pAd->StaCfg.RSNIE_Len;
-		memcpy(extra+2, &pAd->StaCfg.RSN_IE[0], pAd->StaCfg.RSNIE_Len);
-	}
-
-	return 0;
-}
-
-int rt_ioctl_siwpmksa(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-{
-	PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-	struct iw_pmksa *pPmksa = (struct iw_pmksa *)wrqu->data.pointer;
-	INT	CachedIdx = 0, idx = 0;
-
-	if (pPmksa == NULL)
-		return -EINVAL;
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===> rt_ioctl_siwpmksa\n"));
-	switch(pPmksa->cmd)
-	{
-		case IW_PMKSA_FLUSH:
-			NdisZeroMemory(pAd->StaCfg.SavedPMK, sizeof(BSSID_INFO)*PMKID_NO);
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_FLUSH\n"));
-			break;
-		case IW_PMKSA_REMOVE:
-			for (CachedIdx = 0; CachedIdx < pAd->StaCfg.SavedPMKNum; CachedIdx++)
-			{
-		        // compare the BSSID
-		        if (NdisEqualMemory(pPmksa->bssid.sa_data, pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN))
-		        {
-		        	NdisZeroMemory(pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN);
-					NdisZeroMemory(pAd->StaCfg.SavedPMK[CachedIdx].PMKID, 16);
-					for (idx = CachedIdx; idx < (pAd->StaCfg.SavedPMKNum - 1); idx++)
-					{
-						NdisMoveMemory(&pAd->StaCfg.SavedPMK[idx].BSSID[0], &pAd->StaCfg.SavedPMK[idx+1].BSSID[0], MAC_ADDR_LEN);
-						NdisMoveMemory(&pAd->StaCfg.SavedPMK[idx].PMKID[0], &pAd->StaCfg.SavedPMK[idx+1].PMKID[0], 16);
-					}
-					pAd->StaCfg.SavedPMKNum--;
-			        break;
-		        }
-	        }
-
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_REMOVE\n"));
-			break;
-		case IW_PMKSA_ADD:
-			for (CachedIdx = 0; CachedIdx < pAd->StaCfg.SavedPMKNum; CachedIdx++)
-			{
-		        // compare the BSSID
-		        if (NdisEqualMemory(pPmksa->bssid.sa_data, pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN))
-			        break;
-	        }
-
-	        // Found, replace it
-	        if (CachedIdx < PMKID_NO)
-	        {
-		        DBGPRINT(RT_DEBUG_OFF, ("Update PMKID, idx = %d\n", CachedIdx));
-		        NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].BSSID[0], pPmksa->bssid.sa_data, MAC_ADDR_LEN);
-				NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].PMKID[0], pPmksa->pmkid, 16);
-		        pAd->StaCfg.SavedPMKNum++;
-	        }
-	        // Not found, replace the last one
-	        else
-	        {
-		        // Randomly replace one
-		        CachedIdx = (pPmksa->bssid.sa_data[5] % PMKID_NO);
-		        DBGPRINT(RT_DEBUG_OFF, ("Update PMKID, idx = %d\n", CachedIdx));
-		        NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].BSSID[0], pPmksa->bssid.sa_data, MAC_ADDR_LEN);
-				NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].PMKID[0], pPmksa->pmkid, 16);
-	        }
-
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_ADD\n"));
-			break;
-		default:
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - Unknow Command!!\n"));
-			break;
-	}
-
-	return 0;
-}
-#endif // #if WIRELESS_EXT > 17
-
-#ifdef DBG
-static int
-rt_private_ioctl_bbp(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-			{
-	CHAR				*this_char;
-	CHAR				*value = NULL;
-	UCHAR				regBBP = 0;
-//	CHAR				arg[255]={0};
-	UINT32				bbpId;
-	UINT32				bbpValue;
-	BOOLEAN				bIsPrintAllBBP = FALSE;
-	INT					Status = 0;
-    PRTMP_ADAPTER       pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-
-	memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-
-	if (wrq->length > 1) //No parameters.
-				{
-		sprintf(extra, "\n");
-
-		//Parsing Read or Write
-		this_char = wrq->pointer;
-		DBGPRINT(RT_DEBUG_TRACE, ("this_char=%s\n", this_char));
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-			DBGPRINT(RT_DEBUG_TRACE, ("this_char=%s, value=%s\n", this_char, value));
-			if (sscanf(this_char, "%d", &(bbpId)) == 1)
-			{
-				if (bbpId <= 136)
-				{
-#ifdef RALINK_ATE
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					else
-#endif // RALINK_ATE //
-					{
-					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X\n", bbpId, bbpId*2, regBBP);
-                    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-					DBGPRINT(RT_DEBUG_TRACE, ("msg=%s\n", extra));
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					bIsPrintAllBBP = TRUE;
-					goto next;
-				}
-			}
-			else
-			{ //Invalid parametes, so default printk all bbp
-				bIsPrintAllBBP = TRUE;
-				goto next;
-			}
-		}
-		else
-		{ //Write
-			if ((sscanf(this_char, "%d", &(bbpId)) == 1) && (sscanf(value, "%x", &(bbpValue)) == 1))
-			{
-				if (bbpId <= 136)
-				{
-#ifdef RALINK_ATE
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, bbpId, bbpValue);
-						//Read it back for showing
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					else
-#endif // RALINK_ATE //
-					{
-					    RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, bbpId, bbpValue);
-    					//Read it back for showing
-    					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			}
-					sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X\n", bbpId, bbpId*2, regBBP);
-                    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-					DBGPRINT(RT_DEBUG_TRACE, ("msg=%s\n", extra));
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					bIsPrintAllBBP = TRUE;
-					goto next;
-				}
-			}
-			else
-			{ //Invalid parametes, so default printk all bbp
-				bIsPrintAllBBP = TRUE;
-				goto next;
-			}
-		}
-		}
-	else
-		bIsPrintAllBBP = TRUE;
-
-next:
-	if (bIsPrintAllBBP)
-	{
-		memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-		sprintf(extra, "\n");
-		for (bbpId = 0; bbpId <= 136; bbpId++)
-		{
-		    if (strlen(extra) >= (IW_PRIV_SIZE_MASK - 10))
-                break;
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			}
-			else
-#endif // RALINK_ATE //
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X    ", bbpId, bbpId*2, regBBP);
-			if (bbpId%5 == 4)
-				sprintf(extra+strlen(extra), "\n");
-		}
-
-        wrq->length = strlen(extra) + 1; // 1: size of '\0'
-        DBGPRINT(RT_DEBUG_TRACE, ("wrq->length = %d\n", wrq->length));
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==rt_private_ioctl_bbp\n\n"));
-
-    return Status;
-}
-#endif // DBG //
-
-int rt_ioctl_siwrate(struct net_device *dev,
-			struct iw_request_info *info,
-			union iwreq_data *wrqu, char *extra)
-{
-    PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-    UINT32          rate = wrqu->bitrate.value, fixed = wrqu->bitrate.fixed;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::(rate = %d, fixed = %d)\n", rate, fixed));
-    /* rate = -1 => auto rate
-       rate = X, fixed = 1 => (fixed rate X)
-    */
-    if (rate == -1)
-    {
-		//Auto Rate
-		pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-		pAd->StaCfg.bAutoTxRateSwitch = TRUE;
-		if ((pAd->CommonCfg.PhyMode <= PHY_11G) ||
-		    (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM))
-			RTMPSetDesiredRates(pAd, -1);
-
-#ifdef DOT11_N_SUPPORT
-		SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-    }
-    else
-    {
-        if (fixed)
-        {
-        	pAd->StaCfg.bAutoTxRateSwitch = FALSE;
-            if ((pAd->CommonCfg.PhyMode <= PHY_11G) ||
-                (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM))
-                RTMPSetDesiredRates(pAd, rate);
-            else
-            {
-                pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-#ifdef DOT11_N_SUPPORT
-                SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::(HtMcs=%d)\n",pAd->StaCfg.DesiredTransmitSetting.field.MCS));
-        }
-        else
-        {
-            // TODO: rate = X, fixed = 0 => (rates <= X)
-            return -EOPNOTSUPP;
-        }
-    }
-
-    return 0;
-}
-
-int rt_ioctl_giwrate(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-    PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-    int rate_index = 0, rate_count = 0;
-    HTTRANSMIT_SETTING ht_setting;
-    __s32 ralinkrate[] =
-	{2,  4,   11,  22, // CCK
-	12, 18,   24,  36, 48, 72, 96, 108, // OFDM
-	13, 26,   39,  52,  78, 104, 117, 130, 26,  52,  78, 104, 156, 208, 234, 260, // 20MHz, 800ns GI, MCS: 0 ~ 15
-	39, 78,  117, 156, 234, 312, 351, 390,										  // 20MHz, 800ns GI, MCS: 16 ~ 23
-	27, 54,   81, 108, 162, 216, 243, 270, 54, 108, 162, 216, 324, 432, 486, 540, // 40MHz, 800ns GI, MCS: 0 ~ 15
-	81, 162, 243, 324, 486, 648, 729, 810,										  // 40MHz, 800ns GI, MCS: 16 ~ 23
-	14, 29,   43,  57,  87, 115, 130, 144, 29, 59,   87, 115, 173, 230, 260, 288, // 20MHz, 400ns GI, MCS: 0 ~ 15
-	43, 87,  130, 173, 260, 317, 390, 433,										  // 20MHz, 400ns GI, MCS: 16 ~ 23
-	30, 60,   90, 120, 180, 240, 270, 300, 60, 120, 180, 240, 360, 480, 540, 600, // 40MHz, 400ns GI, MCS: 0 ~ 15
-	90, 180, 270, 360, 540, 720, 810, 900};										  // 40MHz, 400ns GI, MCS: 16 ~ 23
-
-    rate_count = sizeof(ralinkrate)/sizeof(__s32);
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    if ((pAd->StaCfg.bAutoTxRateSwitch == FALSE) &&
-        (INFRA_ON(pAd)) &&
-        ((pAd->CommonCfg.PhyMode <= PHY_11G) || (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM)))
-        ht_setting.word = pAd->StaCfg.HTPhyMode.word;
-    else
-        ht_setting.word = pAd->MacTab.Content[BSSID_WCID].HTPhyMode.word;
-
-#ifdef DOT11_N_SUPPORT
-    if (ht_setting.field.MODE >= MODE_HTMIX)
-    {
-//    	rate_index = 12 + ((UCHAR)ht_setting.field.BW *16) + ((UCHAR)ht_setting.field.ShortGI *32) + ((UCHAR)ht_setting.field.MCS);
-    	rate_index = 12 + ((UCHAR)ht_setting.field.BW *24) + ((UCHAR)ht_setting.field.ShortGI *48) + ((UCHAR)ht_setting.field.MCS);
-    }
-    else
-#endif // DOT11_N_SUPPORT //
-    if (ht_setting.field.MODE == MODE_OFDM)
-    	rate_index = (UCHAR)(ht_setting.field.MCS) + 4;
-    else if (ht_setting.field.MODE == MODE_CCK)
-    	rate_index = (UCHAR)(ht_setting.field.MCS);
-
-    if (rate_index < 0)
-        rate_index = 0;
-
-    if (rate_index > rate_count)
-        rate_index = rate_count;
-
-    wrqu->bitrate.value = ralinkrate[rate_index] * 500000;
-    wrqu->bitrate.disabled = 0;
-
-    return 0;
-}
-
-static const iw_handler rt_handler[] =
-{
-	(iw_handler) NULL,			            /* SIOCSIWCOMMIT */
-	(iw_handler) rt_ioctl_giwname,			/* SIOCGIWNAME   */
-	(iw_handler) NULL,			            /* SIOCSIWNWID   */
-	(iw_handler) NULL,			            /* SIOCGIWNWID   */
-	(iw_handler) rt_ioctl_siwfreq,		    /* SIOCSIWFREQ   */
-	(iw_handler) rt_ioctl_giwfreq,		    /* SIOCGIWFREQ   */
-	(iw_handler) rt_ioctl_siwmode,		    /* SIOCSIWMODE   */
-	(iw_handler) rt_ioctl_giwmode,		    /* SIOCGIWMODE   */
-	(iw_handler) NULL,		                /* SIOCSIWSENS   */
-	(iw_handler) NULL,		                /* SIOCGIWSENS   */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWRANGE  */
-	(iw_handler) rt_ioctl_giwrange,		    /* SIOCGIWRANGE  */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWPRIV   */
-	(iw_handler) NULL /* kernel code */,    /* SIOCGIWPRIV   */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWSTATS  */
-	(iw_handler) rt28xx_get_wireless_stats /* kernel code */,    /* SIOCGIWSTATS  */
-	(iw_handler) NULL,		                /* SIOCSIWSPY    */
-	(iw_handler) NULL,		                /* SIOCGIWSPY    */
-	(iw_handler) NULL,				        /* SIOCSIWTHRSPY */
-	(iw_handler) NULL,				        /* SIOCGIWTHRSPY */
-	(iw_handler) rt_ioctl_siwap,            /* SIOCSIWAP     */
-	(iw_handler) rt_ioctl_giwap,		    /* SIOCGIWAP     */
-#ifdef SIOCSIWMLME
-	(iw_handler) rt_ioctl_siwmlme,	        /* SIOCSIWMLME   */
-#else
-	(iw_handler) NULL,				        /* SIOCSIWMLME */
-#endif // SIOCSIWMLME //
-	(iw_handler) rt_ioctl_iwaplist,		    /* SIOCGIWAPLIST */
-#ifdef SIOCGIWSCAN
-	(iw_handler) rt_ioctl_siwscan,		    /* SIOCSIWSCAN   */
-	(iw_handler) rt_ioctl_giwscan,		    /* SIOCGIWSCAN   */
-#else
-	(iw_handler) NULL,				        /* SIOCSIWSCAN   */
-	(iw_handler) NULL,				        /* SIOCGIWSCAN   */
-#endif /* SIOCGIWSCAN */
-	(iw_handler) rt_ioctl_siwessid,		    /* SIOCSIWESSID  */
-	(iw_handler) rt_ioctl_giwessid,		    /* SIOCGIWESSID  */
-	(iw_handler) rt_ioctl_siwnickn,		    /* SIOCSIWNICKN  */
-	(iw_handler) rt_ioctl_giwnickn,		    /* SIOCGIWNICKN  */
-	(iw_handler) NULL,				        /* -- hole --    */
-	(iw_handler) NULL,				        /* -- hole --    */
-	(iw_handler) rt_ioctl_siwrate,          /* SIOCSIWRATE   */
-	(iw_handler) rt_ioctl_giwrate,          /* SIOCGIWRATE   */
-	(iw_handler) rt_ioctl_siwrts,		    /* SIOCSIWRTS    */
-	(iw_handler) rt_ioctl_giwrts,		    /* SIOCGIWRTS    */
-	(iw_handler) rt_ioctl_siwfrag,		    /* SIOCSIWFRAG   */
-	(iw_handler) rt_ioctl_giwfrag,		    /* SIOCGIWFRAG   */
-	(iw_handler) NULL,		                /* SIOCSIWTXPOW  */
-	(iw_handler) NULL,		                /* SIOCGIWTXPOW  */
-	(iw_handler) NULL,		                /* SIOCSIWRETRY  */
-	(iw_handler) NULL,		                /* SIOCGIWRETRY  */
-	(iw_handler) rt_ioctl_siwencode,		/* SIOCSIWENCODE */
-	(iw_handler) rt_ioctl_giwencode,		/* SIOCGIWENCODE */
-	(iw_handler) NULL,		                /* SIOCSIWPOWER  */
-	(iw_handler) NULL,		                /* SIOCGIWPOWER  */
-	(iw_handler) NULL,						/* -- hole -- */
-	(iw_handler) NULL,						/* -- hole -- */
-#if WIRELESS_EXT > 17
-    (iw_handler) rt_ioctl_siwgenie,         /* SIOCSIWGENIE  */
-	(iw_handler) rt_ioctl_giwgenie,         /* SIOCGIWGENIE  */
-	(iw_handler) rt_ioctl_siwauth,		    /* SIOCSIWAUTH   */
-	(iw_handler) rt_ioctl_giwauth,		    /* SIOCGIWAUTH   */
-	(iw_handler) rt_ioctl_siwencodeext,	    /* SIOCSIWENCODEEXT */
-	(iw_handler) rt_ioctl_giwencodeext,		/* SIOCGIWENCODEEXT */
-	(iw_handler) rt_ioctl_siwpmksa,         /* SIOCSIWPMKSA  */
-#endif
-};
-
-static const iw_handler rt_priv_handlers[] = {
-	(iw_handler) NULL, /* + 0x00 */
-	(iw_handler) NULL, /* + 0x01 */
-#ifndef CONFIG_AP_SUPPORT
-	(iw_handler) rt_ioctl_setparam, /* + 0x02 */
-#else
-	(iw_handler) NULL, /* + 0x02 */
-#endif // CONFIG_AP_SUPPORT //
-#ifdef DBG
-	(iw_handler) rt_private_ioctl_bbp, /* + 0x03 */
-#else
-	(iw_handler) NULL, /* + 0x03 */
-#endif
-	(iw_handler) NULL, /* + 0x04 */
-	(iw_handler) NULL, /* + 0x05 */
-	(iw_handler) NULL, /* + 0x06 */
-	(iw_handler) NULL, /* + 0x07 */
-	(iw_handler) NULL, /* + 0x08 */
-	(iw_handler) rt_private_get_statistics, /* + 0x09 */
-	(iw_handler) NULL, /* + 0x0A */
-	(iw_handler) NULL, /* + 0x0B */
-	(iw_handler) NULL, /* + 0x0C */
-	(iw_handler) NULL, /* + 0x0D */
-	(iw_handler) NULL, /* + 0x0E */
-	(iw_handler) NULL, /* + 0x0F */
-	(iw_handler) NULL, /* + 0x10 */
-	(iw_handler) rt_private_show, /* + 0x11 */
-    (iw_handler) NULL, /* + 0x12 */
-	(iw_handler) NULL, /* + 0x13 */
-	(iw_handler) NULL, /* + 0x15 */
-	(iw_handler) NULL, /* + 0x17 */
-	(iw_handler) NULL, /* + 0x18 */
-};
-
-const struct iw_handler_def rt28xx_iw_handler_def =
-{
-#define	N(a)	(sizeof (a) / sizeof (a[0]))
-	.standard	= (iw_handler *) rt_handler,
-	.num_standard	= sizeof(rt_handler) / sizeof(iw_handler),
-	.private	= (iw_handler *) rt_priv_handlers,
-	.num_private		= N(rt_priv_handlers),
-	.private_args	= (struct iw_priv_args *) privtab,
-	.num_private_args	= N(privtab),
-#if IW_HANDLER_VERSION >= 7
-    .get_wireless_stats = rt28xx_get_wireless_stats,
-#endif
-};
-
-INT RTMPSetInformation(
-    IN  PRTMP_ADAPTER pAdapter,
-    IN  OUT struct ifreq    *rq,
-    IN  INT                 cmd)
-{
-    struct iwreq                        *wrq = (struct iwreq *) rq;
-    NDIS_802_11_SSID                    Ssid;
-    NDIS_802_11_MAC_ADDRESS             Bssid;
-    RT_802_11_PHY_MODE                  PhyMode;
-    RT_802_11_STA_CONFIG                StaConfig;
-    NDIS_802_11_RATES                   aryRates;
-    RT_802_11_PREAMBLE                  Preamble;
-    NDIS_802_11_WEP_STATUS              WepStatus;
-    NDIS_802_11_AUTHENTICATION_MODE     AuthMode = Ndis802_11AuthModeMax;
-    NDIS_802_11_NETWORK_INFRASTRUCTURE  BssType;
-    NDIS_802_11_RTS_THRESHOLD           RtsThresh;
-    NDIS_802_11_FRAGMENTATION_THRESHOLD FragThresh;
-    NDIS_802_11_POWER_MODE              PowerMode;
-    PNDIS_802_11_KEY                    pKey = NULL;
-    PNDIS_802_11_WEP			        pWepKey =NULL;
-    PNDIS_802_11_REMOVE_KEY             pRemoveKey = NULL;
-    NDIS_802_11_CONFIGURATION           Config, *pConfig = NULL;
-    NDIS_802_11_NETWORK_TYPE            NetType;
-    ULONG                               Now;
-    UINT                                KeyIdx = 0;
-    INT                                 Status = NDIS_STATUS_SUCCESS, MaxPhyMode = PHY_11G;
-    ULONG                               PowerTemp;
-    BOOLEAN                             RadioState;
-    BOOLEAN                             StateMachineTouched = FALSE;
-#ifdef DOT11_N_SUPPORT
-	OID_SET_HT_PHYMODE					HT_PhyMode;	//11n ,kathy
-#endif // DOT11_N_SUPPORT //
-#ifdef WPA_SUPPLICANT_SUPPORT
-    PNDIS_802_11_PMKID                  pPmkId = NULL;
-    BOOLEAN				                IEEE8021xState = FALSE;
-    BOOLEAN				                IEEE8021x_required_keys = FALSE;
-    UCHAR                               wpa_supplicant_enable = 0;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef SNMP_SUPPORT
-	TX_RTY_CFG_STRUC			tx_rty_cfg;
-	ULONG						ShortRetryLimit, LongRetryLimit;
-	UCHAR						ctmp;
-#endif // SNMP_SUPPORT //
-
-
-
-#ifdef DOT11_N_SUPPORT
-	MaxPhyMode = PHY_11N_5G;
-#endif // DOT11_N_SUPPORT //
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("-->RTMPSetInformation(),	0x%08x\n", cmd&0x7FFF));
-    switch(cmd & 0x7FFF) {
-        case RT_OID_802_11_COUNTRY_REGION:
-            if (wrq->u.data.length < sizeof(UCHAR))
-                Status = -EINVAL;
-			// Only avaliable when EEPROM not programming
-            else if (!(pAdapter->CommonCfg.CountryRegion & 0x80) && !(pAdapter->CommonCfg.CountryRegionForABand & 0x80))
-            {
-                ULONG   Country;
-                UCHAR	TmpPhy;
-
-				Status = copy_from_user(&Country, wrq->u.data.pointer, wrq->u.data.length);
-				pAdapter->CommonCfg.CountryRegion = (UCHAR)(Country & 0x000000FF);
-				pAdapter->CommonCfg.CountryRegionForABand = (UCHAR)((Country >> 8) & 0x000000FF);
-                TmpPhy = pAdapter->CommonCfg.PhyMode;
-				pAdapter->CommonCfg.PhyMode = 0xff;
-				// Build all corresponding channel information
-				RTMPSetPhyMode(pAdapter, TmpPhy);
-#ifdef DOT11_N_SUPPORT
-				SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_COUNTRY_REGION (A:%d  B/G:%d)\n", pAdapter->CommonCfg.CountryRegionForABand,
-				    pAdapter->CommonCfg.CountryRegion));
-            }
-            break;
-        case OID_802_11_BSSID_LIST_SCAN:
- #ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-            Now = jiffies;
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_BSSID_LIST_SCAN, TxCnt = %d \n", pAdapter->RalinkCounters.LastOneSecTotalTxCount));
-
-            if (MONITOR_ON(pAdapter))
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is in Monitor Mode now !!!\n"));
-                break;
-            }
-
-			//Benson add 20080527, when radio off, sta don't need to scan
-			if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_RADIO_OFF))
-				break;
-
-			if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-			{
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is scanning now !!!\n"));
-				pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-				Status = NDIS_STATUS_SUCCESS;
-                break;
-            }
-
-			if (pAdapter->RalinkCounters.LastOneSecTotalTxCount > 100)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-				Status = NDIS_STATUS_SUCCESS;
-				pAdapter->StaCfg.ScanCnt = 99;		// Prevent auto scan triggered by this OID
-				break;
-            }
-
-            if ((OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED)) &&
-				((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)) &&
-                (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, Port Not Secured! ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-				Status = NDIS_STATUS_SUCCESS;
-				pAdapter->StaCfg.ScanCnt = 99;		// Prevent auto scan triggered by this OID
-				break;
-            }
-
-
-            if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-            {
-                RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-            }
-
-            // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-            // this request, because this request is initiated by NDIS.
-            pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-            // Reset allowed scan retries
-            pAdapter->StaCfg.ScanCnt = 0;
-            pAdapter->StaCfg.LastScanTime = Now;
-
-			pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-            RTMP_SET_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-            MlmeEnqueue(pAdapter,
-                        MLME_CNTL_STATE_MACHINE,
-                        OID_802_11_BSSID_LIST_SCAN,
-                        0,
-                        NULL);
-
-            Status = NDIS_STATUS_SUCCESS;
-            StateMachineTouched = TRUE;
-            break;
-        case OID_802_11_SSID:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_SSID))
-                Status = -EINVAL;
-            else
-            {
-            	PCHAR pSsidString = NULL;
-                Status = copy_from_user(&Ssid, wrq->u.data.pointer, wrq->u.data.length);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SSID (Len=%d,Ssid=%s)\n", Ssid.SsidLength, Ssid.Ssid));
-                if (Ssid.SsidLength > MAX_LEN_OF_SSID)
-                    Status = -EINVAL;
-                else
-                {
-                	if (Ssid.SsidLength == 0)
-                	{
-                		Set_SSID_Proc(pAdapter, "");
-                	}
-					else
-                	{
-	                	pSsidString = (CHAR *) kmalloc(MAX_LEN_OF_SSID+1, MEM_ALLOC_FLAG);
-						if (pSsidString)
-						{
-							NdisZeroMemory(pSsidString, MAX_LEN_OF_SSID+1);
-							NdisMoveMemory(pSsidString, Ssid.Ssid, Ssid.SsidLength);
-	                		Set_SSID_Proc(pAdapter, pSsidString);
-							kfree(pSsidString);
-						}
-						else
-							Status = -ENOMEM;
-                	}
-                }
-            }
-            break;
-        case OID_802_11_BSSID:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-            if (wrq->u.data.length != sizeof(NDIS_802_11_MAC_ADDRESS))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Bssid, wrq->u.data.pointer, wrq->u.data.length);
-
-                // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-                // this request, because this request is initiated by NDIS.
-                pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-
-				// Prevent to connect AP again in STAMlmePeriodicExec
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-
-                // Reset allowed scan retries
-				pAdapter->StaCfg.ScanCnt = 0;
-
-                if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-                {
-                    RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-                    DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-                }
-                MlmeEnqueue(pAdapter,
-                            MLME_CNTL_STATE_MACHINE,
-                            OID_802_11_BSSID,
-                            sizeof(NDIS_802_11_MAC_ADDRESS),
-                            (VOID *)&Bssid);
-                Status = NDIS_STATUS_SUCCESS;
-                StateMachineTouched = TRUE;
-
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_BSSID %02x:%02x:%02x:%02x:%02x:%02x\n",
-                                        Bssid[0], Bssid[1], Bssid[2], Bssid[3], Bssid[4], Bssid[5]));
-            }
-            break;
-        case RT_OID_802_11_RADIO:
-            if (wrq->u.data.length != sizeof(BOOLEAN))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&RadioState, wrq->u.data.pointer, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_RADIO (=%d)\n", RadioState));
-                if (pAdapter->StaCfg.bSwRadio != RadioState)
-                {
-                    pAdapter->StaCfg.bSwRadio = RadioState;
-                    if (pAdapter->StaCfg.bRadio != (pAdapter->StaCfg.bHwRadio && pAdapter->StaCfg.bSwRadio))
-                    {
-                        pAdapter->StaCfg.bRadio = (pAdapter->StaCfg.bHwRadio && pAdapter->StaCfg.bSwRadio);
-                        if (pAdapter->StaCfg.bRadio == TRUE)
-                        {
-                            MlmeRadioOn(pAdapter);
-                            // Update extra information
-							pAdapter->ExtraInfo = EXTRA_INFO_CLEAR;
-                        }
-                        else
-                        {
-                            MlmeRadioOff(pAdapter);
-                            // Update extra information
-							pAdapter->ExtraInfo = SW_RADIO_OFF;
-                        }
-                    }
-                }
-            }
-            break;
-        case RT_OID_802_11_PHY_MODE:
-            if (wrq->u.data.length != sizeof(RT_802_11_PHY_MODE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&PhyMode, wrq->u.data.pointer, wrq->u.data.length);
-				if (PhyMode <= MaxPhyMode)
-				{
-                	RTMPSetPhyMode(pAdapter, PhyMode);
-#ifdef DOT11_N_SUPPORT
-					SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-				}
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_PHY_MODE (=%d)\n", PhyMode));
-            }
-            break;
-        case RT_OID_802_11_STA_CONFIG:
-            if (wrq->u.data.length != sizeof(RT_802_11_STA_CONFIG))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&StaConfig, wrq->u.data.pointer, wrq->u.data.length);
-                pAdapter->CommonCfg.bEnableTxBurst = StaConfig.EnableTxBurst;
-                pAdapter->CommonCfg.UseBGProtection = StaConfig.UseBGProtection;
-                pAdapter->CommonCfg.bUseShortSlotTime = 1; // 2003-10-30 always SHORT SLOT capable
-                if ((pAdapter->CommonCfg.PhyMode != StaConfig.AdhocMode) &&
-					(StaConfig.AdhocMode <= MaxPhyMode))
-                {
-                    // allow dynamic change of "USE OFDM rate or not" in ADHOC mode
-                    // if setting changed, need to reset current TX rate as well as BEACON frame format
-                    if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-                    {
-						pAdapter->CommonCfg.PhyMode = StaConfig.AdhocMode;
-                    	RTMPSetPhyMode(pAdapter, PhyMode);
-                        MlmeUpdateTxRates(pAdapter, FALSE, 0);
-                        MakeIbssBeacon(pAdapter);           // re-build BEACON frame
-                        AsicEnableIbssSync(pAdapter);   // copy to on-chip memory
-                    }
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_STA_CONFIG (Burst=%d, Protection=%ld,ShortSlot=%d\n",
-                                        pAdapter->CommonCfg.bEnableTxBurst,
-                                        pAdapter->CommonCfg.UseBGProtection,
-                                        pAdapter->CommonCfg.bUseShortSlotTime));
-            }
-            break;
-        case OID_802_11_DESIRED_RATES:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_RATES))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&aryRates, wrq->u.data.pointer, wrq->u.data.length);
-                NdisZeroMemory(pAdapter->CommonCfg.DesireRate, MAX_LEN_OF_SUPPORTED_RATES);
-                NdisMoveMemory(pAdapter->CommonCfg.DesireRate, &aryRates, sizeof(NDIS_802_11_RATES));
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DESIRED_RATES (%02x,%02x,%02x,%02x,%02x,%02x,%02x,%02x)\n",
-                    pAdapter->CommonCfg.DesireRate[0],pAdapter->CommonCfg.DesireRate[1],
-                    pAdapter->CommonCfg.DesireRate[2],pAdapter->CommonCfg.DesireRate[3],
-                    pAdapter->CommonCfg.DesireRate[4],pAdapter->CommonCfg.DesireRate[5],
-                    pAdapter->CommonCfg.DesireRate[6],pAdapter->CommonCfg.DesireRate[7] ));
-                // Changing DesiredRate may affect the MAX TX rate we used to TX frames out
-                MlmeUpdateTxRates(pAdapter, FALSE, 0);
-            }
-            break;
-        case RT_OID_802_11_PREAMBLE:
-            if (wrq->u.data.length != sizeof(RT_802_11_PREAMBLE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Preamble, wrq->u.data.pointer, wrq->u.data.length);
-                if (Preamble == Rt802_11PreambleShort)
-                {
-                    pAdapter->CommonCfg.TxPreamble = Preamble;
-                    MlmeSetTxPreamble(pAdapter, Rt802_11PreambleShort);
-                }
-                else if ((Preamble == Rt802_11PreambleLong) || (Preamble == Rt802_11PreambleAuto))
-                {
-                    // if user wants AUTO, initialize to LONG here, then change according to AP's
-                    // capability upon association.
-                    pAdapter->CommonCfg.TxPreamble = Preamble;
-                    MlmeSetTxPreamble(pAdapter, Rt802_11PreambleLong);
-                }
-                else
-                {
-                    Status = -EINVAL;
-                    break;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_PREAMBLE (=%d)\n", Preamble));
-            }
-            break;
-        case OID_802_11_WEP_STATUS:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_WEP_STATUS))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&WepStatus, wrq->u.data.pointer, wrq->u.data.length);
-                // Since TKIP, AES, WEP are all supported. It should not have any invalid setting
-                if (WepStatus <= Ndis802_11Encryption3KeyAbsent)
-                {
-                    if (pAdapter->StaCfg.WepStatus != WepStatus)
-                    {
-                        // Config has changed
-                        pAdapter->bConfigChanged = TRUE;
-                    }
-                    pAdapter->StaCfg.WepStatus     = WepStatus;
-                    pAdapter->StaCfg.OrigWepStatus = WepStatus;
-                    pAdapter->StaCfg.PairCipher    = WepStatus;
-                	pAdapter->StaCfg.GroupCipher   = WepStatus;
-                }
-                else
-                {
-                    Status  = -EINVAL;
-                    break;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEP_STATUS (=%d)\n",WepStatus));
-            }
-            break;
-        case OID_802_11_AUTHENTICATION_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_AUTHENTICATION_MODE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&AuthMode, wrq->u.data.pointer, wrq->u.data.length);
-                if (AuthMode > Ndis802_11AuthModeMax)
-                {
-                    Status  = -EINVAL;
-                    break;
-                }
-                else
-                {
-                    if (pAdapter->StaCfg.AuthMode != AuthMode)
-                    {
-                        // Config has changed
-                        pAdapter->bConfigChanged = TRUE;
-                    }
-                    pAdapter->StaCfg.AuthMode = AuthMode;
-                }
-                pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_AUTHENTICATION_MODE (=%d) \n",pAdapter->StaCfg.AuthMode));
-            }
-            break;
-        case OID_802_11_INFRASTRUCTURE_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_NETWORK_INFRASTRUCTURE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&BssType, wrq->u.data.pointer, wrq->u.data.length);
-
-				if (BssType == Ndis802_11IBSS)
-					Set_NetworkType_Proc(pAdapter, "Adhoc");
-				else if (BssType == Ndis802_11Infrastructure)
-					Set_NetworkType_Proc(pAdapter, "Infra");
-				else if (BssType == Ndis802_11Monitor)
-					Set_NetworkType_Proc(pAdapter, "Monitor");
-				else
-				{
-					Status  = -EINVAL;
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_INFRASTRUCTURE_MODE (unknown)\n"));
-				}
-			}
-			break;
-	 case OID_802_11_REMOVE_WEP:
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_WEP\n"));
-            if (wrq->u.data.length != sizeof(NDIS_802_11_KEY_INDEX))
-            {
-				Status = -EINVAL;
-            }
-            else
-            {
-				KeyIdx = *(NDIS_802_11_KEY_INDEX *) wrq->u.data.pointer;
-
-				if (KeyIdx & 0x80000000)
-				{
-					// Should never set default bit when remove key
-					Status = -EINVAL;
-				}
-				else
-				{
-					KeyIdx = KeyIdx & 0x0fffffff;
-					if (KeyIdx >= 4){
-						Status = -EINVAL;
-					}
-					else
-					{
-						pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = 0;
-						pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_NONE;
-						AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)KeyIdx);
-					}
-				}
-            }
-            break;
-        case RT_OID_802_11_RESET_COUNTERS:
-            NdisZeroMemory(&pAdapter->WlanCounters, sizeof(COUNTER_802_11));
-            NdisZeroMemory(&pAdapter->Counters8023, sizeof(COUNTER_802_3));
-            NdisZeroMemory(&pAdapter->RalinkCounters, sizeof(COUNTER_RALINK));
-            pAdapter->Counters8023.RxNoBuffer   = 0;
-			pAdapter->Counters8023.GoodReceives = 0;
-			pAdapter->Counters8023.RxNoBuffer   = 0;
-#ifdef RT2870
-			pAdapter->BulkOutComplete	= 0;
-			pAdapter->BulkOutCompleteOther= 0;
-			pAdapter->BulkOutCompleteCancel = 0;
-			pAdapter->BulkOutReq = 0;
-			pAdapter->BulkInReq= 0;
-			pAdapter->BulkInComplete = 0;
-			pAdapter->BulkInCompleteFail = 0;
-#endif // RT2870 //
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_RESET_COUNTERS \n"));
-            break;
-        case OID_802_11_RTS_THRESHOLD:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_RTS_THRESHOLD))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&RtsThresh, wrq->u.data.pointer, wrq->u.data.length);
-                if (RtsThresh > MAX_RTS_THRESHOLD)
-                    Status  = -EINVAL;
-                else
-                    pAdapter->CommonCfg.RtsThreshold = (USHORT)RtsThresh;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_RTS_THRESHOLD (=%ld)\n",RtsThresh));
-            break;
-        case OID_802_11_FRAGMENTATION_THRESHOLD:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_FRAGMENTATION_THRESHOLD))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&FragThresh, wrq->u.data.pointer, wrq->u.data.length);
-                pAdapter->CommonCfg.bUseZeroToDisableFragment = FALSE;
-                if (FragThresh > MAX_FRAG_THRESHOLD || FragThresh < MIN_FRAG_THRESHOLD)
-                {
-                    if (FragThresh == 0)
-                    {
-                        pAdapter->CommonCfg.FragmentThreshold = MAX_FRAG_THRESHOLD;
-                        pAdapter->CommonCfg.bUseZeroToDisableFragment = TRUE;
-                    }
-                    else
-                        Status  = -EINVAL;
-                }
-                else
-                    pAdapter->CommonCfg.FragmentThreshold = (USHORT)FragThresh;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_FRAGMENTATION_THRESHOLD (=%ld) \n",FragThresh));
-            break;
-        case OID_802_11_POWER_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_POWER_MODE))
-                Status = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&PowerMode, wrq->u.data.pointer, wrq->u.data.length);
-                if (PowerMode == Ndis802_11PowerModeCAM)
-                	Set_PSMode_Proc(pAdapter, "CAM");
-                else if (PowerMode == Ndis802_11PowerModeMAX_PSP)
-                	Set_PSMode_Proc(pAdapter, "Max_PSP");
-                else if (PowerMode == Ndis802_11PowerModeFast_PSP)
-					Set_PSMode_Proc(pAdapter, "Fast_PSP");
-                else if (PowerMode == Ndis802_11PowerModeLegacy_PSP)
-					Set_PSMode_Proc(pAdapter, "Legacy_PSP");
-                else
-                    Status = -EINVAL;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_POWER_MODE (=%d)\n",PowerMode));
-            break;
-         case RT_OID_802_11_TX_POWER_LEVEL_1:
-			if (wrq->u.data.length  < sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&PowerTemp, wrq->u.data.pointer, wrq->u.data.length);
-				if (PowerTemp > 100)
-					PowerTemp = 0xffffffff;  // AUTO
-				pAdapter->CommonCfg.TxPowerDefault = PowerTemp; //keep current setting.
-					pAdapter->CommonCfg.TxPowerPercentage = pAdapter->CommonCfg.TxPowerDefault;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_TX_POWER_LEVEL_1 (=%ld)\n", pAdapter->CommonCfg.TxPowerPercentage));
-			}
-	        break;
-		case OID_802_11_NETWORK_TYPE_IN_USE:
-			if (wrq->u.data.length != sizeof(NDIS_802_11_NETWORK_TYPE))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&NetType, wrq->u.data.pointer, wrq->u.data.length);
-
-				if (NetType == Ndis802_11DS)
-					RTMPSetPhyMode(pAdapter, PHY_11B);
-				else if (NetType == Ndis802_11OFDM24)
-					RTMPSetPhyMode(pAdapter, PHY_11BG_MIXED);
-				else if (NetType == Ndis802_11OFDM5)
-					RTMPSetPhyMode(pAdapter, PHY_11A);
-				else
-					Status = -EINVAL;
-#ifdef DOT11_N_SUPPORT
-				if (Status == NDIS_STATUS_SUCCESS)
-					SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_NETWORK_TYPE_IN_USE (=%d)\n",NetType));
-		    }
-			break;
-        // For WPA PSK PMK key
-        case RT_OID_802_11_ADD_WPA:
-            pKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-
-            Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA, Failed!!\n"));
-            }
-            else
-            {
-                if ((pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPAPSK) &&
-				    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-				    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone) )
-                {
-                    Status = -EOPNOTSUPP;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA, Failed!! [AuthMode != WPAPSK/WPA2PSK/WPANONE]\n"));
-                }
-                else if ((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-						 (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-						 (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPANone) )     // Only for WPA PSK mode
-				{
-                    NdisMoveMemory(pAdapter->StaCfg.PMK, &pKey->KeyMaterial, pKey->KeyLength);
-                    // Use RaConfig as PSK agent.
-                    // Start STA supplicant state machine
-                    if (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone)
-                        pAdapter->StaCfg.WpaState = SS_START;
-
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-                }
-                else
-                {
-                    pAdapter->StaCfg.WpaState = SS_NOTUSE;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-                }
-            }
-            kfree(pKey);
-            break;
-        case OID_802_11_REMOVE_KEY:
-            pRemoveKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pRemoveKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-
-            Status = copy_from_user(pRemoveKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pRemoveKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!\n"));
-            }
-            else
-            {
-                if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-                {
-                    RTMPWPARemoveKeyProc(pAdapter, pRemoveKey);
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Remove WPA Key!!\n"));
-                }
-                else
-                {
-                    KeyIdx = pRemoveKey->KeyIndex;
-
-                    if (KeyIdx & 0x80000000)
-                    {
-                        // Should never set default bit when remove key
-                        Status  = -EINVAL;
-                        DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!(Should never set default bit when remove key)\n"));
-                    }
-                    else
-                    {
-                        KeyIdx = KeyIdx & 0x0fffffff;
-                        if (KeyIdx > 3)
-                        {
-                            Status  = -EINVAL;
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!(KeyId[%d] out of range)\n", KeyIdx));
-                        }
-                        else
-                        {
-                            pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = 0;
-                            pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_NONE;
-                            AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)KeyIdx);
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY (id=0x%x, Len=%d-byte)\n", pRemoveKey->KeyIndex, pRemoveKey->Length));
-                        }
-                    }
-                }
-            }
-            kfree(pRemoveKey);
-            break;
-        // New for WPA
-        case OID_802_11_ADD_KEY:
-            pKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-            Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_KEY, Failed!!\n"));
-            }
-            else
-            {
-                RTMPAddKey(pAdapter, pKey);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_KEY (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-            }
-            kfree(pKey);
-            break;
-        case OID_802_11_CONFIGURATION:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_CONFIGURATION))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Config, wrq->u.data.pointer, wrq->u.data.length);
-                pConfig = &Config;
-
-                if ((pConfig->BeaconPeriod >= 20) && (pConfig->BeaconPeriod <=400))
-                     pAdapter->CommonCfg.BeaconPeriod = (USHORT) pConfig->BeaconPeriod;
-
-                pAdapter->StaActive.AtimWin = (USHORT) pConfig->ATIMWindow;
-                MAP_KHZ_TO_CHANNEL_ID(pConfig->DSConfig, pAdapter->CommonCfg.Channel);
-                //
-				// Save the channel on MlmeAux for CntlOidRTBssidProc used.
-				//
-				pAdapter->MlmeAux.Channel = pAdapter->CommonCfg.Channel;
-
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_CONFIGURATION (BeacnPeriod=%ld,AtimW=%ld,Ch=%d)\n",
-                    pConfig->BeaconPeriod, pConfig->ATIMWindow, pAdapter->CommonCfg.Channel));
-                // Config has changed
-                pAdapter->bConfigChanged = TRUE;
-            }
-            break;
-#ifdef DOT11_N_SUPPORT
-		case RT_OID_802_11_SET_HT_PHYMODE:
-			if (wrq->u.data.length	!= sizeof(OID_SET_HT_PHYMODE))
-				Status = -EINVAL;
-			else
-			{
-			    POID_SET_HT_PHYMODE	pHTPhyMode = &HT_PhyMode;
-
-				Status = copy_from_user(&HT_PhyMode, wrq->u.data.pointer, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::pHTPhyMode	(PhyMode = %d,TransmitNo = %d, HtMode =	%d,	ExtOffset =	%d , MCS = %d, BW =	%d,	STBC = %d, SHORTGI = %d) \n",
-				pHTPhyMode->PhyMode, pHTPhyMode->TransmitNo,pHTPhyMode->HtMode,pHTPhyMode->ExtOffset,
-				pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC,	pHTPhyMode->SHORTGI));
-				if (pAdapter->CommonCfg.PhyMode	>= PHY_11ABGN_MIXED)
-					RTMPSetHT(pAdapter,	pHTPhyMode);
-			}
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_HT_PHYMODE(MCS=%d,BW=%d,SGI=%d,STBC=%d)\n",
-				pAdapter->StaCfg.HTPhyMode.field.MCS, pAdapter->StaCfg.HTPhyMode.field.BW, pAdapter->StaCfg.HTPhyMode.field.ShortGI,
-				pAdapter->StaCfg.HTPhyMode.field.STBC));
-			break;
-#endif // DOT11_N_SUPPORT //
-		case RT_OID_802_11_SET_APSD_SETTING:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				ULONG apsd ;
-				Status = copy_from_user(&apsd, wrq->u.data.pointer,	wrq->u.data.length);
-
-				/*-------------------------------------------------------------------
-				|B31~B7	|	B6~B5	 |	 B4	 |	 B3	 |	B2	 |	B1	 |	   B0		|
-				---------------------------------------------------------------------
-				| Rsvd	| Max SP Len | AC_VO | AC_VI | AC_BK | AC_BE | APSD	Capable	|
-				---------------------------------------------------------------------*/
-				pAdapter->CommonCfg.bAPSDCapable = (apsd & 0x00000001) ? TRUE :	FALSE;
-				pAdapter->CommonCfg.bAPSDAC_BE = ((apsd	& 0x00000002) >> 1)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_BK = ((apsd	& 0x00000004) >> 2)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_VI = ((apsd	& 0x00000008) >> 3)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_VO = ((apsd	& 0x00000010) >> 4)	? TRUE : FALSE;
-				pAdapter->CommonCfg.MaxSPLength	= (UCHAR)((apsd	& 0x00000060) >> 5);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_APSD_SETTING (apsd=0x%lx, APSDCap=%d, [BE,BK,VI,VO]=[%d/%d/%d/%d],	MaxSPLen=%d)\n", apsd, pAdapter->CommonCfg.bAPSDCapable,
-					pAdapter->CommonCfg.bAPSDAC_BE,	pAdapter->CommonCfg.bAPSDAC_BK,	pAdapter->CommonCfg.bAPSDAC_VI,	pAdapter->CommonCfg.bAPSDAC_VO,	pAdapter->CommonCfg.MaxSPLength));
-			}
-			break;
-
-		case RT_OID_802_11_SET_APSD_PSM:
-			if (wrq->u.data.length	!= sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				// Driver needs	to notify AP when PSM changes
-				Status = copy_from_user(&pAdapter->CommonCfg.bAPSDForcePowerSave, wrq->u.data.pointer, wrq->u.data.length);
-				if (pAdapter->CommonCfg.bAPSDForcePowerSave	!= pAdapter->StaCfg.Psm)
-				{
-					MlmeSetPsmBit(pAdapter,	pAdapter->CommonCfg.bAPSDForcePowerSave);
-					RTMPSendNullFrame(pAdapter,	pAdapter->CommonCfg.TxRate,	TRUE);
-				}
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_APSD_PSM (bAPSDForcePowerSave:%d)\n",	pAdapter->CommonCfg.bAPSDForcePowerSave));
-			}
-			break;
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_SET_DLS:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				BOOLEAN	oldvalue = pAdapter->CommonCfg.bDLSCapable;
-				Status = copy_from_user(&pAdapter->CommonCfg.bDLSCapable, wrq->u.data.pointer, wrq->u.data.length);
-				if (oldvalue &&	!pAdapter->CommonCfg.bDLSCapable)
-				{
-					int	i;
-					// tear	down local dls table entry
-					for	(i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-					{
-						if (pAdapter->StaCfg.DLSEntry[i].Valid && (pAdapter->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-						{
-							pAdapter->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-							pAdapter->StaCfg.DLSEntry[i].Valid	= FALSE;
-							RTMPSendDLSTearDownFrame(pAdapter, pAdapter->StaCfg.DLSEntry[i].MacAddr);
-						}
-					}
-
-					// tear	down peer dls table	entry
-					for	(i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-					{
-						if (pAdapter->StaCfg.DLSEntry[i].Valid && (pAdapter->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-						{
-							pAdapter->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-							pAdapter->StaCfg.DLSEntry[i].Valid	= FALSE;
-							RTMPSendDLSTearDownFrame(pAdapter, pAdapter->StaCfg.DLSEntry[i].MacAddr);
-						}
-					}
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE,("Set::RT_OID_802_11_SET_DLS (=%d)\n", pAdapter->CommonCfg.bDLSCapable));
-			}
-			break;
-
-		case RT_OID_802_11_SET_DLS_PARAM:
-			if (wrq->u.data.length	!= sizeof(RT_802_11_DLS_UI))
-				Status = -EINVAL;
-			else
-			{
-				RT_802_11_DLS	Dls;
-
-				NdisZeroMemory(&Dls, sizeof(RT_802_11_DLS));
-				RTMPMoveMemory(&Dls, wrq->u.data.pointer, sizeof(RT_802_11_DLS_UI));
-				MlmeEnqueue(pAdapter,
-							MLME_CNTL_STATE_MACHINE,
-							RT_OID_802_11_SET_DLS_PARAM,
-							sizeof(RT_802_11_DLS),
-							&Dls);
-				DBGPRINT(RT_DEBUG_TRACE,("Set::RT_OID_802_11_SET_DLS_PARAM \n"));
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-		case RT_OID_802_11_SET_WMM:
-			if (wrq->u.data.length	!= sizeof(BOOLEAN))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&pAdapter->CommonCfg.bWmmCapable, wrq->u.data.pointer, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_WMM (=%d)	\n", pAdapter->CommonCfg.bWmmCapable));
-			}
-			break;
-
-		case OID_802_11_DISASSOCIATE:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-			//
-			// Set NdisRadioStateOff to	TRUE, instead of called	MlmeRadioOff.
-			// Later on, NDIS_802_11_BSSID_LIST_EX->NumberOfItems should be	0
-			// when	query OID_802_11_BSSID_LIST.
-			//
-			// TRUE:  NumberOfItems	will set to	0.
-			// FALSE: NumberOfItems	no change.
-			//
-			pAdapter->CommonCfg.NdisRadioStateOff =	TRUE;
-			// Set to immediately send the media disconnect	event
-			pAdapter->MlmeAux.CurrReqIsFromNdis	= TRUE;
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DISASSOCIATE	\n"));
-
-			if (INFRA_ON(pAdapter))
-			{
-				if (pAdapter->Mlme.CntlMachine.CurrState !=	CNTL_IDLE)
-				{
-					RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-					DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME	busy, reset	MLME state machine !!!\n"));
-				}
-
-				MlmeEnqueue(pAdapter,
-					MLME_CNTL_STATE_MACHINE,
-					OID_802_11_DISASSOCIATE,
-					0,
-					NULL);
-
-				StateMachineTouched	= TRUE;
-			}
-			break;
-
-#ifdef DOT11_N_SUPPORT
-		case RT_OID_802_11_SET_IMME_BA_CAP:
-				if (wrq->u.data.length != sizeof(OID_BACAP_STRUC))
-					Status = -EINVAL;
-				else
-				{
-					OID_BACAP_STRUC Orde ;
-					Status = copy_from_user(&Orde, wrq->u.data.pointer, wrq->u.data.length);
-					if (Orde.Policy > BA_NOTUSE)
-					{
-						Status = NDIS_STATUS_INVALID_DATA;
-					}
-					else if (Orde.Policy == BA_NOTUSE)
-					{
-						pAdapter->CommonCfg.BACapability.field.Policy = BA_NOTUSE;
-						pAdapter->CommonCfg.BACapability.field.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable = Orde.AmsduEnable;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize= Orde.AmsduSize;
-						pAdapter->CommonCfg.DesiredHtPhy.MimoPs= Orde.MMPSmode;
-						pAdapter->CommonCfg.BACapability.field.MMPSmode = Orde.MMPSmode;
-						// UPdata to HT IE
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.AMsduSize = Orde.AmsduSize;
-						pAdapter->CommonCfg.HtCapability.HtCapParm.MpduDensity = Orde.MpduDensity;
-					}
-					else
-					{
-                        pAdapter->CommonCfg.BACapability.field.AutoBA = Orde.AutoBA;
-						pAdapter->CommonCfg.BACapability.field.Policy = IMMED_BA; // we only support immediate BA.
-						pAdapter->CommonCfg.BACapability.field.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable = Orde.AmsduEnable;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize= Orde.AmsduSize;
-						pAdapter->CommonCfg.DesiredHtPhy.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.BACapability.field.MMPSmode = Orde.MMPSmode;
-
-						// UPdata to HT IE
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.AMsduSize = Orde.AmsduSize;
-						pAdapter->CommonCfg.HtCapability.HtCapParm.MpduDensity = Orde.MpduDensity;
-
-						if (pAdapter->CommonCfg.BACapability.field.RxBAWinLimit > MAX_RX_REORDERBUF)
-							pAdapter->CommonCfg.BACapability.field.RxBAWinLimit = MAX_RX_REORDERBUF;
-
-					}
-
-					pAdapter->CommonCfg.REGBACapability.word = pAdapter->CommonCfg.BACapability.word;
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::(Orde.AutoBA = %d) (Policy=%d)(ReBAWinLimit=%d)(TxBAWinLimit=%d)(AutoMode=%d)\n",Orde.AutoBA, pAdapter->CommonCfg.BACapability.field.Policy,
-						pAdapter->CommonCfg.BACapability.field.RxBAWinLimit,pAdapter->CommonCfg.BACapability.field.TxBAWinLimit, pAdapter->CommonCfg.BACapability.field.AutoBA));
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::(MimoPs = %d)(AmsduEnable = %d) (AmsduSize=%d)(MpduDensity=%d)\n",pAdapter->CommonCfg.DesiredHtPhy.MimoPs, pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable,
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize, pAdapter->CommonCfg.DesiredHtPhy.MpduDensity));
-				}
-
-				break;
-		case RT_OID_802_11_ADD_IMME_BA:
-			DBGPRINT(RT_DEBUG_TRACE, (" Set :: RT_OID_802_11_ADD_IMME_BA \n"));
-			if (wrq->u.data.length != sizeof(OID_ADD_BA_ENTRY))
-					Status = -EINVAL;
-			else
-			{
-				UCHAR		        index;
-				OID_ADD_BA_ENTRY    BA;
-				MAC_TABLE_ENTRY     *pEntry;
-
-				Status = copy_from_user(&BA, wrq->u.data.pointer, wrq->u.data.length);
-				if (BA.TID > 15)
-				{
-					Status = NDIS_STATUS_INVALID_DATA;
-					break;
-				}
-				else
-				{
-					//BATableInsertEntry
-					//As ad-hoc mode, BA pair is not limited to only BSSID. so add via OID.
-					index = BA.TID;
-					// in ad hoc mode, when adding BA pair, we should insert this entry into MACEntry too
-					pEntry = MacTableLookup(pAdapter, BA.MACAddr);
-					if (!pEntry)
-					{
-						DBGPRINT(RT_DEBUG_TRACE, ("RT_OID_802_11_ADD_IMME_BA. break on no connection.----:%x:%x\n", BA.MACAddr[4], BA.MACAddr[5]));
-						break;
-					}
-					if (BA.IsRecipient == FALSE)
-					{
-					    if (pEntry->bIAmBadAtheros == TRUE)
-							pAdapter->CommonCfg.BACapability.field.RxBAWinLimit = 0x10;
-
-						BAOriSessionSetUp(pAdapter, pEntry, index, 0, 100, TRUE);
-					}
-					else
-					{
-						//BATableInsertEntry(pAdapter, pEntry->Aid, BA.MACAddr, 0, 0xffff, BA.TID, BA.nMSDU, BA.IsRecipient);
-					}
-
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_IMME_BA. Rec = %d. Mac = %x:%x:%x:%x:%x:%x . \n",
-						BA.IsRecipient, BA.MACAddr[0], BA.MACAddr[1], BA.MACAddr[2], BA.MACAddr[2]
-						, BA.MACAddr[4], BA.MACAddr[5]));
-				}
-			}
-			break;
-
-		case RT_OID_802_11_TEAR_IMME_BA:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA \n"));
-			if (wrq->u.data.length != sizeof(OID_ADD_BA_ENTRY))
-					Status = -EINVAL;
-			else
-			{
-				POID_ADD_BA_ENTRY	pBA;
-				MAC_TABLE_ENTRY *pEntry;
-
-				pBA = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-				if (pBA == NULL)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA kmalloc() can't allocate enough memory\n"));
-					Status = NDIS_STATUS_FAILURE;
-				}
-				else
-				{
-					Status = copy_from_user(pBA, wrq->u.data.pointer, wrq->u.data.length);
-					DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA(TID=%d, bAllTid=%d)\n", pBA->TID, pBA->bAllTid));
-
-					if (!pBA->bAllTid && (pBA->TID > NUM_OF_TID))
-					{
-						Status = NDIS_STATUS_INVALID_DATA;
-						break;
-					}
-
-					if (pBA->IsRecipient == FALSE)
-					{
-						pEntry = MacTableLookup(pAdapter, pBA->MACAddr);
-						DBGPRINT(RT_DEBUG_TRACE, (" pBA->IsRecipient == FALSE\n"));
-						if (pEntry)
-						{
-							DBGPRINT(RT_DEBUG_TRACE, (" pBA->pEntry\n"));
-							BAOriSessionTearDown(pAdapter, pEntry->Aid, pBA->TID, FALSE, TRUE);
-						}
-						else
-							DBGPRINT(RT_DEBUG_TRACE, ("Set :: Not found pEntry \n"));
-					}
-					else
-					{
-						pEntry = MacTableLookup(pAdapter, pBA->MACAddr);
-						if (pEntry)
-						{
-							BARecSessionTearDown( pAdapter, (UCHAR)pEntry->Aid, pBA->TID, TRUE);
-						}
-						else
-							DBGPRINT(RT_DEBUG_TRACE, ("Set :: Not found pEntry \n"));
-					}
-					kfree(pBA);
-				}
-            }
-            break;
-#endif // DOT11_N_SUPPORT //
-
-        // For WPA_SUPPLICANT to set static wep key
-    	case OID_802_11_ADD_WEP:
-    	    pWepKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-    	    if(pWepKey == NULL)
-            {
-                Status = -ENOMEM;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed!!\n"));
-                break;
-            }
-            Status = copy_from_user(pWepKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (Status)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed (length mismatch)!!\n"));
-            }
-            else
-            {
-		        KeyIdx = pWepKey->KeyIndex & 0x0fffffff;
-                // KeyIdx must be 0 ~ 3
-                if (KeyIdx > 4)
-    			{
-                    Status  = -EINVAL;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed (KeyIdx must be smaller than 4)!!\n"));
-                }
-                else
-                {
-                    UCHAR CipherAlg = 0;
-                    PUCHAR Key;
-
-                    // set key material and key length
-                    NdisZeroMemory(pAdapter->SharedKey[BSS0][KeyIdx].Key, 16);
-                    pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = (UCHAR) pWepKey->KeyLength;
-                    NdisMoveMemory(pAdapter->SharedKey[BSS0][KeyIdx].Key, &pWepKey->KeyMaterial, pWepKey->KeyLength);
-
-                    switch(pWepKey->KeyLength)
-                    {
-                        case 5:
-                            CipherAlg = CIPHER_WEP64;
-                            break;
-                        case 13:
-                            CipherAlg = CIPHER_WEP128;
-                            break;
-                        default:
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, only support CIPHER_WEP64(len:5) & CIPHER_WEP128(len:13)!!\n"));
-                            Status = -EINVAL;
-                            break;
-                    }
-                    pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CipherAlg;
-
-                    // Default key for tx (shared key)
-                    if (pWepKey->KeyIndex & 0x80000000)
-                    {
-#ifdef WPA_SUPPLICANT_SUPPORT
-                        // set key material and key length
-                        NdisZeroMemory(pAdapter->StaCfg.DesireSharedKey[KeyIdx].Key, 16);
-                        pAdapter->StaCfg.DesireSharedKey[KeyIdx].KeyLen = (UCHAR) pWepKey->KeyLength;
-                        NdisMoveMemory(pAdapter->StaCfg.DesireSharedKey[KeyIdx].Key, &pWepKey->KeyMaterial, pWepKey->KeyLength);
-                        pAdapter->StaCfg.DesireSharedKeyId = KeyIdx;
-                        pAdapter->StaCfg.DesireSharedKey[KeyIdx].CipherAlg = CipherAlg;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                        pAdapter->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-                    }
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-                    if (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED)
-#endif // WPA_SUPPLICANT_SUPPORT
-                    {
-                        Key = pAdapter->SharedKey[BSS0][KeyIdx].Key;
-
-                        // Set key material and cipherAlg to Asic
-        				AsicAddSharedKeyEntry(pAdapter, BSS0, KeyIdx, CipherAlg, Key, NULL, NULL);
-
-                        if (pWepKey->KeyIndex & 0x80000000)
-                        {
-                            PMAC_TABLE_ENTRY pEntry = &pAdapter->MacTab.Content[BSSID_WCID];
-                            // Assign group key info
-    						RTMPAddWcidAttributeEntry(pAdapter, BSS0, KeyIdx, CipherAlg, NULL);
-    						// Assign pairwise key info
-    						RTMPAddWcidAttributeEntry(pAdapter, BSS0, KeyIdx, CipherAlg, pEntry);
-                        }
-                    }
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP (id=0x%x, Len=%d-byte), %s\n", pWepKey->KeyIndex, pWepKey->KeyLength, (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED) ? "Port Secured":"Port NOT Secured"));
-				}
-            }
-            kfree(pWepKey);
-            break;
-#ifdef WPA_SUPPLICANT_SUPPORT
-	    case OID_SET_COUNTERMEASURES:
-            if (wrq->u.data.length != sizeof(int))
-                Status  = -EINVAL;
-            else
-            {
-                int enabled = 0;
-                Status = copy_from_user(&enabled, wrq->u.data.pointer, wrq->u.data.length);
-                if (enabled == 1)
-                    pAdapter->StaCfg.bBlockAssoc = TRUE;
-                else
-                    // WPA MIC error should block association attempt for 60 seconds
-                    pAdapter->StaCfg.bBlockAssoc = FALSE;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_SET_COUNTERMEASURES bBlockAssoc=%s\n", pAdapter->StaCfg.bBlockAssoc ? "TRUE":"FALSE"));
-            }
-	        break;
-        case RT_OID_WPA_SUPPLICANT_SUPPORT:
-			if (wrq->u.data.length != sizeof(UCHAR))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&wpa_supplicant_enable, wrq->u.data.pointer, wrq->u.data.length);
-    			pAdapter->StaCfg.WpaSupplicantUP = wpa_supplicant_enable;
-    			DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_WPA_SUPPLICANT_SUPPORT (=%d)\n", pAdapter->StaCfg.WpaSupplicantUP));
-			}
-            break;
-        case OID_802_11_DEAUTHENTICATION:
-            if (wrq->u.data.length != sizeof(MLME_DEAUTH_REQ_STRUCT))
-                Status  = -EINVAL;
-            else
-            {
-                MLME_DEAUTH_REQ_STRUCT      *pInfo;
-				MLME_QUEUE_ELEM *MsgElem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-
-                pInfo = (MLME_DEAUTH_REQ_STRUCT *) MsgElem->Msg;
-                Status = copy_from_user(pInfo, wrq->u.data.pointer, wrq->u.data.length);
-                MlmeDeauthReqAction(pAdapter, MsgElem);
-				kfree(MsgElem);
-
-                if (INFRA_ON(pAdapter))
-                {
-                    LinkDown(pAdapter, FALSE);
-                    pAdapter->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DEAUTHENTICATION (Reason=%d)\n", pInfo->Reason));
-            }
-            break;
-        case OID_802_11_DROP_UNENCRYPTED:
-            if (wrq->u.data.length != sizeof(int))
-                Status  = -EINVAL;
-            else
-            {
-                int enabled = 0;
-                Status = copy_from_user(&enabled, wrq->u.data.pointer, wrq->u.data.length);
-                if (enabled == 1)
-                    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-                else
-                    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				NdisAcquireSpinLock(&pAdapter->MacTabLock);
-				pAdapter->MacTab.Content[BSSID_WCID].PortSecured = pAdapter->StaCfg.PortSecured;
-				NdisReleaseSpinLock(&pAdapter->MacTabLock);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DROP_UNENCRYPTED (=%d)\n", enabled));
-            }
-            break;
-        case OID_802_11_SET_IEEE8021X:
-            if (wrq->u.data.length != sizeof(BOOLEAN))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&IEEE8021xState, wrq->u.data.pointer, wrq->u.data.length);
-		        pAdapter->StaCfg.IEEE8021X = IEEE8021xState;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SET_IEEE8021X (=%d)\n", IEEE8021xState));
-            }
-            break;
-        case OID_802_11_SET_IEEE8021X_REQUIRE_KEY:
-			if (wrq->u.data.length != sizeof(BOOLEAN))
-				 Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&IEEE8021x_required_keys, wrq->u.data.pointer, wrq->u.data.length);
-				pAdapter->StaCfg.IEEE8021x_required_keys = IEEE8021x_required_keys;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SET_IEEE8021X_REQUIRE_KEY (%d)\n", IEEE8021x_required_keys));
-			}
-			break;
-        case OID_802_11_PMKID:
-	        pPmkId = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-	        if(pPmkId == NULL) {
-                Status = -ENOMEM;
-                break;
-            }
-            Status = copy_from_user(pPmkId, wrq->u.data.pointer, wrq->u.data.length);
-
-	        // check the PMKID information
-	        if (pPmkId->BSSIDInfoCount == 0)
-                NdisZeroMemory(pAdapter->StaCfg.SavedPMK, sizeof(BSSID_INFO)*PMKID_NO);
-	        else
-	        {
-		        PBSSID_INFO	pBssIdInfo;
-		        UINT		BssIdx;
-		        UINT		CachedIdx;
-
-		        for (BssIdx = 0; BssIdx < pPmkId->BSSIDInfoCount; BssIdx++)
-		        {
-			        // point to the indexed BSSID_INFO structure
-			        pBssIdInfo = (PBSSID_INFO) ((PUCHAR) pPmkId + 2 * sizeof(UINT) + BssIdx * sizeof(BSSID_INFO));
-			        // Find the entry in the saved data base.
-			        for (CachedIdx = 0; CachedIdx < pAdapter->StaCfg.SavedPMKNum; CachedIdx++)
-			        {
-				        // compare the BSSID
-				        if (NdisEqualMemory(pBssIdInfo->BSSID, pAdapter->StaCfg.SavedPMK[CachedIdx].BSSID, sizeof(NDIS_802_11_MAC_ADDRESS)))
-					        break;
-			        }
-
-			        // Found, replace it
-			        if (CachedIdx < PMKID_NO)
-			        {
-				        DBGPRINT(RT_DEBUG_OFF, ("Update OID_802_11_PMKID, idx = %d\n", CachedIdx));
-				        NdisMoveMemory(&pAdapter->StaCfg.SavedPMK[CachedIdx], pBssIdInfo, sizeof(BSSID_INFO));
-				        pAdapter->StaCfg.SavedPMKNum++;
-			        }
-			        // Not found, replace the last one
-			        else
-			        {
-				        // Randomly replace one
-				        CachedIdx = (pBssIdInfo->BSSID[5] % PMKID_NO);
-				        DBGPRINT(RT_DEBUG_OFF, ("Update OID_802_11_PMKID, idx = %d\n", CachedIdx));
-				        NdisMoveMemory(&pAdapter->StaCfg.SavedPMK[CachedIdx], pBssIdInfo, sizeof(BSSID_INFO));
-			        }
-		        }
-			}
-			if(pPmkId)
-				kfree(pPmkId);
-	        break;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-
-#ifdef SNMP_SUPPORT
-		case OID_802_11_SHORTRETRYLIMIT:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&ShortRetryLimit, wrq->u.data.pointer, wrq->u.data.length);
-				RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-				tx_rty_cfg.field.ShortRtyLimit = ShortRetryLimit;
-				RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SHORTRETRYLIMIT (tx_rty_cfg.field.ShortRetryLimit=%d, ShortRetryLimit=%ld)\n", tx_rty_cfg.field.ShortRtyLimit, ShortRetryLimit));
-			}
-			break;
-
-		case OID_802_11_LONGRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_LONGRETRYLIMIT \n"));
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&LongRetryLimit, wrq->u.data.pointer, wrq->u.data.length);
-				RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-				tx_rty_cfg.field.LongRtyLimit = LongRetryLimit;
-				RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_LONGRETRYLIMIT (tx_rty_cfg.field.LongRetryLimit= %d,LongRetryLimit=%ld)\n", tx_rty_cfg.field.LongRtyLimit, LongRetryLimit));
-			}
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYVALUE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYVALUE\n"));
-			pKey = kmalloc(wrq->u.data.length, GFP_KERNEL);
-			Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-			//pKey = &WepKey;
-
-			if ( pKey->Length != wrq->u.data.length)
-			{
-				Status = -EINVAL;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYVALUE, Failed!!\n"));
-			}
-			KeyIdx = pKey->KeyIndex & 0x0fffffff;
-			DBGPRINT(RT_DEBUG_TRACE,("pKey->KeyIndex =%d, pKey->KeyLength=%d\n", pKey->KeyIndex, pKey->KeyLength));
-
-			// it is a shared key
-			if (KeyIdx > 4)
-				Status = -EINVAL;
-			else
-			{
-				pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen = (UCHAR) pKey->KeyLength;
-				NdisMoveMemory(&pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key, &pKey->KeyMaterial, pKey->KeyLength);
-				if (pKey->KeyIndex & 0x80000000)
-				{
-					// Default key for tx (shared key)
-					pAdapter->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-				}
-				//RestartAPIsRequired = TRUE;
-			}
-			break;
-
-
-		case OID_802_11_WEPDEFAULTKEYID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYID \n"));
-
-			if (wrq->u.data.length != sizeof(UCHAR))
-				Status = -EINVAL;
-			else
-				Status = copy_from_user(&pAdapter->StaCfg.DefaultKeyId, wrq->u.data.pointer, wrq->u.data.length);
-
-			break;
-
-
-		case OID_802_11_CURRENTCHANNEL:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_CURRENTCHANNEL \n"));
-			if (wrq->u.data.length != sizeof(UCHAR))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&ctmp, wrq->u.data.pointer, wrq->u.data.length);
-				sprintf(&ctmp,"%d", ctmp);
-				Set_Channel_Proc(pAdapter, &ctmp);
-			}
-			break;
-#endif
-
-
-
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::unknown IOCTL's subcmd = 0x%08x\n", cmd));
-            Status = -EOPNOTSUPP;
-            break;
-    }
-
-
-    return Status;
-}
-
-INT RTMPQueryInformation(
-    IN  PRTMP_ADAPTER pAdapter,
-    IN  OUT struct ifreq    *rq,
-    IN  INT                 cmd)
-{
-    struct iwreq                        *wrq = (struct iwreq *) rq;
-    NDIS_802_11_BSSID_LIST_EX           *pBssidList = NULL;
-    PNDIS_WLAN_BSSID_EX                 pBss;
-    NDIS_802_11_SSID                    Ssid;
-    NDIS_802_11_CONFIGURATION           *pConfiguration = NULL;
-    RT_802_11_LINK_STATUS               *pLinkStatus = NULL;
-    RT_802_11_STA_CONFIG                *pStaConfig = NULL;
-    NDIS_802_11_STATISTICS              *pStatistics = NULL;
-    NDIS_802_11_RTS_THRESHOLD           RtsThresh;
-    NDIS_802_11_FRAGMENTATION_THRESHOLD FragThresh;
-    NDIS_802_11_POWER_MODE              PowerMode;
-    NDIS_802_11_NETWORK_INFRASTRUCTURE  BssType;
-    RT_802_11_PREAMBLE                  PreamType;
-    NDIS_802_11_AUTHENTICATION_MODE     AuthMode;
-    NDIS_802_11_WEP_STATUS              WepStatus;
-    NDIS_MEDIA_STATE                    MediaState;
-    ULONG                               BssBufSize, ulInfo=0, NetworkTypeList[4], apsd = 0;
-    USHORT                              BssLen = 0;
-    PUCHAR                              pBuf = NULL, pPtr;
-    INT                                 Status = NDIS_STATUS_SUCCESS;
-    UINT                                we_version_compiled;
-    UCHAR                               i, Padding = 0;
-    BOOLEAN                             RadioState;
-	UCHAR	driverVersion[8];
-    OID_SET_HT_PHYMODE			        *pHTPhyMode = NULL;
-
-
-#ifdef SNMP_SUPPORT
-	//for snmp, kathy
-	DefaultKeyIdxValue			*pKeyIdxValue;
-	INT							valueLen;
-	TX_RTY_CFG_STRUC			tx_rty_cfg;
-	ULONG						ShortRetryLimit, LongRetryLimit;
-	UCHAR						tmp[64];
-#endif //SNMP
-
-    switch(cmd)
-    {
-        case RT_OID_DEVICE_NAME:
-            wrq->u.data.length = sizeof(STA_NIC_DEVICE_NAME);
-            Status = copy_to_user(wrq->u.data.pointer, STA_NIC_DEVICE_NAME, wrq->u.data.length);
-            break;
-        case RT_OID_VERSION_INFO:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_VERSION_INFO \n"));
-			wrq->u.data.length = 8*sizeof(UCHAR);
-			sprintf(&driverVersion[0], "%s", STA_DRIVER_VERSION);
-			driverVersion[7] = '\0';
-			if (copy_to_user(wrq->u.data.pointer, &driverVersion, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            break;
-#ifdef RALINK_ATE
-		case RT_QUERY_ATE_TXDONE_COUNT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_QUERY_ATE_TXDONE_COUNT \n"));
-			wrq->u.data.length = sizeof(UINT32);
-			if (copy_to_user(wrq->u.data.pointer, &pAdapter->ate.TxDoneCount, wrq->u.data.length))
-			{
-				Status = -EFAULT;
-			}
-			break;
-#endif // RALINK_ATE //
-        case OID_802_11_BSSID_LIST:
-            if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-            	/*
-            	 * Still scanning, indicate the caller should try again.
-            	 */
-            	DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID_LIST (Still scanning)\n"));
-				return -EAGAIN;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID_LIST (%d BSS returned)\n",pAdapter->ScanTab.BssNr));
-			pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-            // Claculate total buffer size required
-            BssBufSize = sizeof(ULONG);
-
-            for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-            {
-                // Align pointer to 4 bytes boundary.
-                //Padding = 4 - (pAdapter->ScanTab.BssEntry[i].VarIELen & 0x0003);
-                //if (Padding == 4)
-                //    Padding = 0;
-                BssBufSize += (sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen + Padding);
-            }
-
-            // For safety issue, we add 256 bytes just in case
-            BssBufSize += 256;
-            // Allocate the same size as passed from higher layer
-            pBuf = kmalloc(BssBufSize, MEM_ALLOC_FLAG);
-            if(pBuf == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-            // Init 802_11_BSSID_LIST_EX structure
-            NdisZeroMemory(pBuf, BssBufSize);
-            pBssidList = (PNDIS_802_11_BSSID_LIST_EX) pBuf;
-            pBssidList->NumberOfItems = pAdapter->ScanTab.BssNr;
-
-            // Calculate total buffer length
-            BssLen = 4; // Consist of NumberOfItems
-            // Point to start of NDIS_WLAN_BSSID_EX
-            // pPtr = pBuf + sizeof(ULONG);
-            pPtr = (PUCHAR) &pBssidList->Bssid[0];
-            for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-            {
-                pBss = (PNDIS_WLAN_BSSID_EX) pPtr;
-                NdisMoveMemory(&pBss->MacAddress, &pAdapter->ScanTab.BssEntry[i].Bssid, MAC_ADDR_LEN);
-                if ((pAdapter->ScanTab.BssEntry[i].Hidden == 1) && (pAdapter->StaCfg.bShowHiddenSSID == FALSE))
-                {
-                    //
-					// We must return this SSID during 4way handshaking, otherwise Aegis will failed to parse WPA infomation
-					// and then failed to send EAPOl farame.
-					//
-					if ((pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA) && (pAdapter->StaCfg.PortSecured != WPA_802_1X_PORT_SECURED))
-					{
-						pBss->Ssid.SsidLength = pAdapter->ScanTab.BssEntry[i].SsidLen;
-						NdisMoveMemory(pBss->Ssid.Ssid, pAdapter->ScanTab.BssEntry[i].Ssid, pAdapter->ScanTab.BssEntry[i].SsidLen);
-					}
-					else
-                    	pBss->Ssid.SsidLength = 0;
-                }
-                else
-                {
-                    pBss->Ssid.SsidLength = pAdapter->ScanTab.BssEntry[i].SsidLen;
-                    NdisMoveMemory(pBss->Ssid.Ssid, pAdapter->ScanTab.BssEntry[i].Ssid, pAdapter->ScanTab.BssEntry[i].SsidLen);
-                }
-                pBss->Privacy = pAdapter->ScanTab.BssEntry[i].Privacy;
-                pBss->Rssi = pAdapter->ScanTab.BssEntry[i].Rssi - pAdapter->BbpRssiToDbmDelta;
-                pBss->NetworkTypeInUse = NetworkTypeInUseSanity(&pAdapter->ScanTab.BssEntry[i]);
-                pBss->Configuration.Length = sizeof(NDIS_802_11_CONFIGURATION);
-                pBss->Configuration.BeaconPeriod = pAdapter->ScanTab.BssEntry[i].BeaconPeriod;
-                pBss->Configuration.ATIMWindow = pAdapter->ScanTab.BssEntry[i].AtimWin;
-
-                MAP_CHANNEL_ID_TO_KHZ(pAdapter->ScanTab.BssEntry[i].Channel, pBss->Configuration.DSConfig);
-
-                if (pAdapter->ScanTab.BssEntry[i].BssType == BSS_INFRA)
-                    pBss->InfrastructureMode = Ndis802_11Infrastructure;
-                else
-                    pBss->InfrastructureMode = Ndis802_11IBSS;
-
-                NdisMoveMemory(pBss->SupportedRates, pAdapter->ScanTab.BssEntry[i].SupRate, pAdapter->ScanTab.BssEntry[i].SupRateLen);
-                NdisMoveMemory(pBss->SupportedRates + pAdapter->ScanTab.BssEntry[i].SupRateLen,
-                               pAdapter->ScanTab.BssEntry[i].ExtRate,
-                               pAdapter->ScanTab.BssEntry[i].ExtRateLen);
-
-                if (pAdapter->ScanTab.BssEntry[i].VarIELen == 0)
-                {
-                    pBss->IELength = sizeof(NDIS_802_11_FIXED_IEs);
-                    NdisMoveMemory(pBss->IEs, &pAdapter->ScanTab.BssEntry[i].FixIEs, sizeof(NDIS_802_11_FIXED_IEs));
-                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs);
-                }
-                else
-                {
-                    pBss->IELength = (ULONG)(sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen);
-                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs);
-                    NdisMoveMemory(pBss->IEs, &pAdapter->ScanTab.BssEntry[i].FixIEs, sizeof(NDIS_802_11_FIXED_IEs));
-                    NdisMoveMemory(pBss->IEs + sizeof(NDIS_802_11_FIXED_IEs), pAdapter->ScanTab.BssEntry[i].VarIEs, pAdapter->ScanTab.BssEntry[i].VarIELen);
-                    pPtr += pAdapter->ScanTab.BssEntry[i].VarIELen;
-                }
-                pBss->Length = (ULONG)(sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen + Padding);
-
-#if WIRELESS_EXT < 17
-                if ((BssLen + pBss->Length) < wrq->u.data.length)
-                BssLen += pBss->Length;
-                else
-                {
-                    pBssidList->NumberOfItems = i;
-                    break;
-                }
-#else
-                BssLen += pBss->Length;
-#endif
-            }
-
-#if WIRELESS_EXT < 17
-            wrq->u.data.length = BssLen;
-#else
-            if (BssLen > wrq->u.data.length)
-            {
-                kfree(pBssidList);
-                return -E2BIG;
-            }
-            else
-                wrq->u.data.length = BssLen;
-#endif
-            Status = copy_to_user(wrq->u.data.pointer, pBssidList, BssLen);
-            kfree(pBssidList);
-            break;
-        case OID_802_3_CURRENT_ADDRESS:
-            wrq->u.data.length = MAC_ADDR_LEN;
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-            break;
-        case OID_GEN_MEDIA_CONNECT_STATUS:
-            if (pAdapter->IndicateMediaState == NdisMediaStateConnected)
-                MediaState = NdisMediaStateConnected;
-            else
-                MediaState = NdisMediaStateDisconnected;
-
-            wrq->u.data.length = sizeof(NDIS_MEDIA_STATE);
-            Status = copy_to_user(wrq->u.data.pointer, &MediaState, wrq->u.data.length);
-            break;
-        case OID_802_11_BSSID:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				Status = NDIS_STATUS_RESOURCES;
-				break;
-			}
-#endif // RALINK_ATE //
-            if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-            {
-                Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Bssid, sizeof(NDIS_802_11_MAC_ADDRESS));
-
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID(=EMPTY)\n"));
-                Status = -ENOTCONN;
-            }
-            break;
-        case OID_802_11_SSID:
-			NdisZeroMemory(&Ssid, sizeof(NDIS_802_11_SSID));
-			NdisZeroMemory(Ssid.Ssid, MAX_LEN_OF_SSID);
-            Ssid.SsidLength = pAdapter->CommonCfg.SsidLen;
-			memcpy(Ssid.Ssid, pAdapter->CommonCfg.Ssid,	Ssid.SsidLength);
-            wrq->u.data.length = sizeof(NDIS_802_11_SSID);
-            Status = copy_to_user(wrq->u.data.pointer, &Ssid, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_SSID (Len=%d, ssid=%s)\n", Ssid.SsidLength,Ssid.Ssid));
-            break;
-        case RT_OID_802_11_QUERY_LINK_STATUS:
-            pLinkStatus = (RT_802_11_LINK_STATUS *) kmalloc(sizeof(RT_802_11_LINK_STATUS), MEM_ALLOC_FLAG);
-            if (pLinkStatus)
-            {
-                pLinkStatus->CurrTxRate = RateIdTo500Kbps[pAdapter->CommonCfg.TxRate];   // unit : 500 kbps
-                pLinkStatus->ChannelQuality = pAdapter->Mlme.ChannelQuality;
-                pLinkStatus->RxByteCount = pAdapter->RalinkCounters.ReceivedByteCount;
-                pLinkStatus->TxByteCount = pAdapter->RalinkCounters.TransmittedByteCount;
-        		pLinkStatus->CentralChannel = pAdapter->CommonCfg.CentralChannel;
-                wrq->u.data.length = sizeof(RT_802_11_LINK_STATUS);
-                Status = copy_to_user(wrq->u.data.pointer, pLinkStatus, wrq->u.data.length);
-                kfree(pLinkStatus);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LINK_STATUS\n"));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LINK_STATUS(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_802_11_CONFIGURATION:
-            pConfiguration = (NDIS_802_11_CONFIGURATION *) kmalloc(sizeof(NDIS_802_11_CONFIGURATION), MEM_ALLOC_FLAG);
-            if (pConfiguration)
-            {
-                pConfiguration->Length = sizeof(NDIS_802_11_CONFIGURATION);
-                pConfiguration->BeaconPeriod = pAdapter->CommonCfg.BeaconPeriod;
-                pConfiguration->ATIMWindow = pAdapter->StaActive.AtimWin;
-                MAP_CHANNEL_ID_TO_KHZ(pAdapter->CommonCfg.Channel, pConfiguration->DSConfig);
-                wrq->u.data.length = sizeof(NDIS_802_11_CONFIGURATION);
-                Status = copy_to_user(wrq->u.data.pointer, pConfiguration, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CONFIGURATION(BeaconPeriod=%ld,AtimW=%ld,Channel=%d) \n",
-                                        pConfiguration->BeaconPeriod, pConfiguration->ATIMWindow, pAdapter->CommonCfg.Channel));
-				kfree(pConfiguration);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CONFIGURATION(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-		case RT_OID_802_11_SNR_0:
-			if ((pAdapter->StaCfg.LastSNR0 > 0))
-			{
-				ulInfo = ((0xeb	- pAdapter->StaCfg.LastSNR0) * 3) /	16 ;
-				wrq->u.data.length = sizeof(ulInfo);
-				Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_SNR_0(0x=%lx)\n", ulInfo));
-			}
-            else
-			    Status = -EFAULT;
-			break;
-		case RT_OID_802_11_SNR_1:
-			if ((pAdapter->Antenna.field.RxPath	> 1) &&
-                (pAdapter->StaCfg.LastSNR1 > 0))
-			{
-				ulInfo = ((0xeb	- pAdapter->StaCfg.LastSNR1) * 3) /	16 ;
-				wrq->u.data.length = sizeof(ulInfo);
-				Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE,("Query::RT_OID_802_11_SNR_1(0x=%lx)\n",ulInfo));
-			}
-			else
-				Status = -EFAULT;
-            DBGPRINT(RT_DEBUG_TRACE,("Query::RT_OID_802_11_SNR_1(pAdapter->StaCfg.LastSNR1=%d)\n",pAdapter->StaCfg.LastSNR1));
-			break;
-        case OID_802_11_RSSI_TRIGGER:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi0 - pAdapter->BbpRssiToDbmDelta;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_RSSI_TRIGGER(=%ld)\n", ulInfo));
-            break;
-		case OID_802_11_RSSI:
-        case RT_OID_802_11_RSSI:
-			ulInfo = pAdapter->StaCfg.RssiSample.LastRssi0;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-		case RT_OID_802_11_RSSI_1:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi1;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-        case RT_OID_802_11_RSSI_2:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi2;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-        case OID_802_11_STATISTICS:
-            pStatistics = (NDIS_802_11_STATISTICS *) kmalloc(sizeof(NDIS_802_11_STATISTICS), MEM_ALLOC_FLAG);
-            if (pStatistics)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_STATISTICS \n"));
-                // add the most up-to-date h/w raw counters into software counters
-			    NICUpdateRawCounters(pAdapter);
-
-                // Sanity check for calculation of sucessful count
-                if (pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart < pAdapter->WlanCounters.RetryCount.QuadPart)
-                    pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart = pAdapter->WlanCounters.RetryCount.QuadPart;
-
-                pStatistics->TransmittedFragmentCount.QuadPart = pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart;
-                pStatistics->MulticastTransmittedFrameCount.QuadPart = pAdapter->WlanCounters.MulticastTransmittedFrameCount.QuadPart;
-                pStatistics->FailedCount.QuadPart = pAdapter->WlanCounters.FailedCount.QuadPart;
-                pStatistics->RetryCount.QuadPart = pAdapter->WlanCounters.RetryCount.QuadPart;
-                pStatistics->MultipleRetryCount.QuadPart = pAdapter->WlanCounters.MultipleRetryCount.QuadPart;
-                pStatistics->RTSSuccessCount.QuadPart = pAdapter->WlanCounters.RTSSuccessCount.QuadPart;
-                pStatistics->RTSFailureCount.QuadPart = pAdapter->WlanCounters.RTSFailureCount.QuadPart;
-                pStatistics->ACKFailureCount.QuadPart = pAdapter->WlanCounters.ACKFailureCount.QuadPart;
-                pStatistics->FrameDuplicateCount.QuadPart = pAdapter->WlanCounters.FrameDuplicateCount.QuadPart;
-                pStatistics->ReceivedFragmentCount.QuadPart = pAdapter->WlanCounters.ReceivedFragmentCount.QuadPart;
-                pStatistics->MulticastReceivedFrameCount.QuadPart = pAdapter->WlanCounters.MulticastReceivedFrameCount.QuadPart;
-#ifdef DBG
-                pStatistics->FCSErrorCount = pAdapter->RalinkCounters.RealFcsErrCount;
-#else
-                pStatistics->FCSErrorCount.QuadPart = pAdapter->WlanCounters.FCSErrorCount.QuadPart;
-                pStatistics->FrameDuplicateCount.u.LowPart = pAdapter->WlanCounters.FrameDuplicateCount.u.LowPart / 100;
-#endif
-                wrq->u.data.length = sizeof(NDIS_802_11_STATISTICS);
-                Status = copy_to_user(wrq->u.data.pointer, pStatistics, wrq->u.data.length);
-                kfree(pStatistics);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_STATISTICS(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_GEN_RCV_OK:
-            ulInfo = pAdapter->Counters8023.GoodReceives;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            break;
-        case OID_GEN_RCV_NO_BUFFER:
-            ulInfo = pAdapter->Counters8023.RxNoBuffer;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            break;
-        case RT_OID_802_11_PHY_MODE:
-            ulInfo = (ULONG)pAdapter->CommonCfg.PhyMode;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PHY_MODE (=%ld)\n", ulInfo));
-            break;
-        case RT_OID_802_11_STA_CONFIG:
-            pStaConfig = (RT_802_11_STA_CONFIG *) kmalloc(sizeof(RT_802_11_STA_CONFIG), MEM_ALLOC_FLAG);
-            if (pStaConfig)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG\n"));
-                pStaConfig->EnableTxBurst = pAdapter->CommonCfg.bEnableTxBurst;
-                pStaConfig->EnableTurboRate = 0;
-                pStaConfig->UseBGProtection = pAdapter->CommonCfg.UseBGProtection;
-                pStaConfig->UseShortSlotTime = pAdapter->CommonCfg.bUseShortSlotTime;
-                //pStaConfig->AdhocMode = pAdapter->StaCfg.AdhocMode;
-                pStaConfig->HwRadioStatus = (pAdapter->StaCfg.bHwRadio == TRUE) ? 1 : 0;
-                pStaConfig->Rsv1 = 0;
-                pStaConfig->SystemErrorBitmap = pAdapter->SystemErrorBitmap;
-                wrq->u.data.length = sizeof(RT_802_11_STA_CONFIG);
-                Status = copy_to_user(wrq->u.data.pointer, pStaConfig, wrq->u.data.length);
-                kfree(pStaConfig);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_802_11_RTS_THRESHOLD:
-            RtsThresh = pAdapter->CommonCfg.RtsThreshold;
-            wrq->u.data.length = sizeof(RtsThresh);
-            Status = copy_to_user(wrq->u.data.pointer, &RtsThresh, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_RTS_THRESHOLD(=%ld)\n", RtsThresh));
-            break;
-        case OID_802_11_FRAGMENTATION_THRESHOLD:
-            FragThresh = pAdapter->CommonCfg.FragmentThreshold;
-            if (pAdapter->CommonCfg.bUseZeroToDisableFragment == TRUE)
-                FragThresh = 0;
-            wrq->u.data.length = sizeof(FragThresh);
-            Status = copy_to_user(wrq->u.data.pointer, &FragThresh, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_FRAGMENTATION_THRESHOLD(=%ld)\n", FragThresh));
-            break;
-        case OID_802_11_POWER_MODE:
-            PowerMode = pAdapter->StaCfg.WindowsPowerMode;
-            wrq->u.data.length = sizeof(PowerMode);
-            Status = copy_to_user(wrq->u.data.pointer, &PowerMode, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_POWER_MODE(=%d)\n", PowerMode));
-            break;
-        case RT_OID_802_11_RADIO:
-            RadioState = (BOOLEAN) pAdapter->StaCfg.bSwRadio;
-            wrq->u.data.length = sizeof(RadioState);
-            Status = copy_to_user(wrq->u.data.pointer, &RadioState, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_RADIO (=%d)\n", RadioState));
-            break;
-        case OID_802_11_INFRASTRUCTURE_MODE:
-            if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-                BssType = Ndis802_11IBSS;
-            else if (pAdapter->StaCfg.BssType == BSS_INFRA)
-                BssType = Ndis802_11Infrastructure;
-            else if (pAdapter->StaCfg.BssType == BSS_MONITOR)
-                BssType = Ndis802_11Monitor;
-            else
-                BssType = Ndis802_11AutoUnknown;
-
-            wrq->u.data.length = sizeof(BssType);
-            Status = copy_to_user(wrq->u.data.pointer, &BssType, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_INFRASTRUCTURE_MODE(=%d)\n", BssType));
-            break;
-        case RT_OID_802_11_PREAMBLE:
-            PreamType = pAdapter->CommonCfg.TxPreamble;
-            wrq->u.data.length = sizeof(PreamType);
-            Status = copy_to_user(wrq->u.data.pointer, &PreamType, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PREAMBLE(=%d)\n", PreamType));
-            break;
-        case OID_802_11_AUTHENTICATION_MODE:
-            AuthMode = pAdapter->StaCfg.AuthMode;
-            wrq->u.data.length = sizeof(AuthMode);
-            Status = copy_to_user(wrq->u.data.pointer, &AuthMode, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_AUTHENTICATION_MODE(=%d)\n", AuthMode));
-            break;
-        case OID_802_11_WEP_STATUS:
-            WepStatus = pAdapter->StaCfg.WepStatus;
-            wrq->u.data.length = sizeof(WepStatus);
-            Status = copy_to_user(wrq->u.data.pointer, &WepStatus, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_WEP_STATUS(=%d)\n", WepStatus));
-            break;
-        case OID_802_11_TX_POWER_LEVEL:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.TxPower, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_TX_POWER_LEVEL %x\n",pAdapter->CommonCfg.TxPower));
-			break;
-        case RT_OID_802_11_TX_POWER_LEVEL_1:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.TxPowerPercentage, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_TX_POWER_LEVEL_1 (=%ld)\n", pAdapter->CommonCfg.TxPowerPercentage));
-			break;
-        case OID_802_11_NETWORK_TYPES_SUPPORTED:
-			if ((pAdapter->RfIcType	== RFIC_2850) || (pAdapter->RfIcType ==	RFIC_2750))
-			{
-				NetworkTypeList[0] = 3;                 // NumberOfItems = 3
-				NetworkTypeList[1] = Ndis802_11DS;      // NetworkType[1] = 11b
-				NetworkTypeList[2] = Ndis802_11OFDM24;  // NetworkType[2] = 11g
-				NetworkTypeList[3] = Ndis802_11OFDM5;   // NetworkType[3] = 11a
-                wrq->u.data.length = 16;
-				Status = copy_to_user(wrq->u.data.pointer, &NetworkTypeList[0], wrq->u.data.length);
-			}
-			else
-			{
-				NetworkTypeList[0] = 2;                 // NumberOfItems = 2
-				NetworkTypeList[1] = Ndis802_11DS;      // NetworkType[1] = 11b
-				NetworkTypeList[2] = Ndis802_11OFDM24;  // NetworkType[2] = 11g
-			    wrq->u.data.length = 12;
-				Status = copy_to_user(wrq->u.data.pointer, &NetworkTypeList[0], wrq->u.data.length);
-			}
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_NETWORK_TYPES_SUPPORTED\n"));
-				break;
-	    case OID_802_11_NETWORK_TYPE_IN_USE:
-            wrq->u.data.length = sizeof(ULONG);
-			if (pAdapter->CommonCfg.PhyMode == PHY_11A)
-				ulInfo = Ndis802_11OFDM5;
-			else if ((pAdapter->CommonCfg.PhyMode == PHY_11BG_MIXED) || (pAdapter->CommonCfg.PhyMode == PHY_11G))
-				ulInfo = Ndis802_11OFDM24;
-			else
-				ulInfo = Ndis802_11DS;
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-        case RT_OID_802_11_QUERY_LAST_RX_RATE:
-            ulInfo = (ULONG)pAdapter->LastRxRate;
-            wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LAST_RX_RATE (=%ld)\n", ulInfo));
-			break;
-		case RT_OID_802_11_QUERY_LAST_TX_RATE:
-			//ulInfo = (ULONG)pAdapter->LastTxRate;
-			ulInfo = (ULONG)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LAST_TX_RATE (=%lx)\n", ulInfo));
-			break;
-        case RT_OID_802_11_QUERY_EEPROM_VERSION:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->EepromVersion, wrq->u.data.length);
-            break;
-        case RT_OID_802_11_QUERY_FIRMWARE_VERSION:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->FirmwareVersion, wrq->u.data.length);
-			break;
-	    case RT_OID_802_11_QUERY_NOISE_LEVEL:
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->BbpWriteLatch[66], wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_NOISE_LEVEL (=%d)\n", pAdapter->BbpWriteLatch[66]));
-			break;
-	    case RT_OID_802_11_EXTRA_INFO:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->ExtraInfo, wrq->u.data.length);
-	        DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_EXTRA_INFO (=%ld)\n", pAdapter->ExtraInfo));
-	        break;
-	    case RT_OID_WE_VERSION_COMPILED:
-	        wrq->u.data.length = sizeof(UINT);
-	        we_version_compiled = WIRELESS_EXT;
-	        Status = copy_to_user(wrq->u.data.pointer, &we_version_compiled, wrq->u.data.length);
-	        break;
-		case RT_OID_802_11_QUERY_APSD_SETTING:
-			apsd = (pAdapter->CommonCfg.bAPSDCapable | (pAdapter->CommonCfg.bAPSDAC_BE << 1) | (pAdapter->CommonCfg.bAPSDAC_BK << 2)
-				| (pAdapter->CommonCfg.bAPSDAC_VI << 3)	| (pAdapter->CommonCfg.bAPSDAC_VO << 4)	| (pAdapter->CommonCfg.MaxSPLength << 5));
-
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &apsd, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_APSD_SETTING (=0x%lx,APSDCap=%d,AC_BE=%d,AC_BK=%d,AC_VI=%d,AC_VO=%d,MAXSPLen=%d)\n",
-				apsd,pAdapter->CommonCfg.bAPSDCapable,pAdapter->CommonCfg.bAPSDAC_BE,pAdapter->CommonCfg.bAPSDAC_BK,pAdapter->CommonCfg.bAPSDAC_VI,pAdapter->CommonCfg.bAPSDAC_VO,pAdapter->CommonCfg.MaxSPLength));
-			break;
-		case RT_OID_802_11_QUERY_APSD_PSM:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bAPSDForcePowerSave, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_APSD_PSM (=%d)\n", pAdapter->CommonCfg.bAPSDForcePowerSave));
-			break;
-		case RT_OID_802_11_QUERY_WMM:
-			wrq->u.data.length = sizeof(BOOLEAN);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bWmmCapable, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_WMM (=%d)\n",	pAdapter->CommonCfg.bWmmCapable));
-			break;
-#ifdef WPA_SUPPLICANT_SUPPORT
-        case RT_OID_NEW_DRIVER:
-            {
-                UCHAR enabled = 1;
-    	        wrq->u.data.length = sizeof(UCHAR);
-    	        Status = copy_to_user(wrq->u.data.pointer, &enabled, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_NEW_DRIVER (=%d)\n", enabled));
-            }
-	        break;
-        case RT_OID_WPA_SUPPLICANT_SUPPORT:
-	        wrq->u.data.length = sizeof(UCHAR);
-	        Status = copy_to_user(wrq->u.data.pointer, &pAdapter->StaCfg.WpaSupplicantUP, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_WPA_SUPPLICANT_SUPPORT (=%d)\n", pAdapter->StaCfg.WpaSupplicantUP));
-	        break;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-        case RT_OID_DRIVER_DEVICE_NAME:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_DRIVER_DEVICE_NAME \n"));
-			wrq->u.data.length = 16;
-			if (copy_to_user(wrq->u.data.pointer, pAdapter->StaCfg.dev_name, wrq->u.data.length))
-			{
-				Status = -EFAULT;
-			}
-            break;
-        case RT_OID_802_11_QUERY_HT_PHYMODE:
-            pHTPhyMode = (OID_SET_HT_PHYMODE *) kmalloc(sizeof(OID_SET_HT_PHYMODE), MEM_ALLOC_FLAG);
-            if (pHTPhyMode)
-            {
-                pHTPhyMode->PhyMode = pAdapter->CommonCfg.PhyMode;
-    			pHTPhyMode->HtMode = (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE;
-    			pHTPhyMode->BW = (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.BW;
-    			pHTPhyMode->MCS= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.MCS;
-    			pHTPhyMode->SHORTGI= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.ShortGI;
-    			pHTPhyMode->STBC= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.STBC;
-
-    			pHTPhyMode->ExtOffset = ((pAdapter->CommonCfg.CentralChannel < pAdapter->CommonCfg.Channel) ? (EXTCHA_BELOW) : (EXTCHA_ABOVE));
-                wrq->u.data.length = sizeof(OID_SET_HT_PHYMODE);
-                if (copy_to_user(wrq->u.data.pointer, pHTPhyMode, wrq->u.data.length))
-    			{
-    				Status = -EFAULT;
-    			}
-    			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_HT_PHYMODE (PhyMode = %d, MCS =%d, BW = %d, STBC = %d, ExtOffset=%d)\n",
-    				pHTPhyMode->HtMode, pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC, pHTPhyMode->ExtOffset));
-    			DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (.word = %x )\n", pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case RT_OID_802_11_COUNTRY_REGION:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_COUNTRY_REGION \n"));
-			wrq->u.data.length = sizeof(ulInfo);
-            ulInfo = pAdapter->CommonCfg.CountryRegionForABand;
-            ulInfo = (ulInfo << 8)|(pAdapter->CommonCfg.CountryRegion);
-			if (copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            break;
-        case RT_OID_802_11_QUERY_DAT_HT_PHYMODE:
-            pHTPhyMode = (OID_SET_HT_PHYMODE *) kmalloc(sizeof(OID_SET_HT_PHYMODE), MEM_ALLOC_FLAG);
-            if (pHTPhyMode)
-            {
-                pHTPhyMode->PhyMode = pAdapter->CommonCfg.PhyMode;
-    			pHTPhyMode->HtMode = (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.HTMODE;
-    			pHTPhyMode->BW = (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.BW;
-    			pHTPhyMode->MCS= (UCHAR)pAdapter->StaCfg.DesiredTransmitSetting.field.MCS;
-    			pHTPhyMode->SHORTGI= (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.ShortGI;
-    			pHTPhyMode->STBC= (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.STBC;
-
-                wrq->u.data.length = sizeof(OID_SET_HT_PHYMODE);
-                if (copy_to_user(wrq->u.data.pointer, pHTPhyMode, wrq->u.data.length))
-    			{
-    				Status = -EFAULT;
-    			}
-    			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_HT_PHYMODE (PhyMode = %d, MCS =%d, BW = %d, STBC = %d, ExtOffset=%d)\n",
-    				pHTPhyMode->HtMode, pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC, pHTPhyMode->ExtOffset));
-    			DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (.word = %x )\n", pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case RT_OID_QUERY_MULTIPLE_CARD_SUPPORT:
-			wrq->u.data.length = sizeof(UCHAR);
-            i = 0;
-#ifdef MULTIPLE_CARD_SUPPORT
-            i = 1;
-#endif // MULTIPLE_CARD_SUPPORT //
-			if (copy_to_user(wrq->u.data.pointer, &i, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_QUERY_MULTIPLE_CARD_SUPPORT(=%d) \n", i));
-            break;
-#ifdef SNMP_SUPPORT
-		case RT_OID_802_11_MAC_ADDRESS:
-            wrq->u.data.length = MAC_ADDR_LEN;
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTUREROUI:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTUREROUI \n"));
-			wrq->u.data.length = ManufacturerOUI_LEN;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTURERNAME:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTURERNAME \n"));
-			wrq->u.data.length = strlen(ManufacturerNAME);
-			Status = copy_to_user(wrq->u.data.pointer, ManufacturerNAME, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_RESOURCETYPEIDNAME:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_RESOURCETYPEIDNAME \n"));
-			wrq->u.data.length = strlen(ResourceTypeIdName);
-			Status = copy_to_user(wrq->u.data.pointer, ResourceTypeIdName, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED \n"));
-			ulInfo = 1; // 1 is support wep else 2 is not support.
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_POWERMANAGEMENTMODE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_POWERMANAGEMENTMODE \n"));
-			if (pAdapter->StaCfg.Psm == PSMP_ACTION)
-				ulInfo = 1; // 1 is power active else 2 is power save.
-			else
-				ulInfo = 2;
-
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYVALUE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_WEPDEFAULTKEYVALUE \n"));
-			//KeyIdxValue.KeyIdx = pAd->PortCfg.MBSSID[pAd->IoctlIF].DefaultKeyId;
-			pKeyIdxValue = wrq->u.data.pointer;
-			DBGPRINT(RT_DEBUG_TRACE,("KeyIdxValue.KeyIdx = %d, \n",pKeyIdxValue->KeyIdx));
-			valueLen = pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen;
-			NdisMoveMemory(pKeyIdxValue->Value,
-						   &pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key,
-						   valueLen);
-			pKeyIdxValue->Value[valueLen]='\0';
-
-			wrq->u.data.length = sizeof(DefaultKeyIdxValue);
-
-			Status = copy_to_user(wrq->u.data.pointer, pKeyIdxValue, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE,("DefaultKeyId = %d, total len = %d, str len=%d, KeyValue= %02x %02x %02x %02x \n", pAdapter->StaCfg.DefaultKeyId, wrq->u.data.length, pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen,
-			pAdapter->SharedKey[BSS0][0].Key[0],
-			pAdapter->SharedKey[BSS0][1].Key[0],
-			pAdapter->SharedKey[BSS0][2].Key[0],
-			pAdapter->SharedKey[BSS0][3].Key[0]));
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_WEPDEFAULTKEYID \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->StaCfg.DefaultKeyId, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("DefaultKeyId =%d \n", pAdapter->StaCfg.DefaultKeyId));
-			break;
-
-		case RT_OID_802_11_WEPKEYMAPPINGLENGTH:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_WEPKEYMAPPINGLENGTH \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer,
-									&pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen,
-									wrq->u.data.length);
-			break;
-
-		case OID_802_11_SHORTRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_SHORTRETRYLIMIT \n"));
-			wrq->u.data.length = sizeof(ULONG);
-			RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-			ShortRetryLimit = tx_rty_cfg.field.ShortRtyLimit;
-			DBGPRINT(RT_DEBUG_TRACE, ("ShortRetryLimit =%ld,  tx_rty_cfg.field.ShortRetryLimit=%d\n", ShortRetryLimit, tx_rty_cfg.field.ShortRtyLimit));
-			Status = copy_to_user(wrq->u.data.pointer, &ShortRetryLimit, wrq->u.data.length);
-			break;
-
-		case OID_802_11_LONGRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_LONGRETRYLIMIT \n"));
-			wrq->u.data.length = sizeof(ULONG);
-			RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-			LongRetryLimit = tx_rty_cfg.field.LongRtyLimit;
-			DBGPRINT(RT_DEBUG_TRACE, ("LongRetryLimit =%ld,  tx_rty_cfg.field.LongRtyLimit=%d\n", LongRetryLimit, tx_rty_cfg.field.LongRtyLimit));
-			Status = copy_to_user(wrq->u.data.pointer, &LongRetryLimit, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_PRODUCTID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PRODUCTID \n"));
-
-#ifdef RT2870
-			sprintf(tmp, "%04x %04x\n", ((POS_COOKIE)pAdapter->OS_Cookie)->pUsb_Dev->descriptor.idVendor ,((POS_COOKIE)pAdapter->OS_Cookie)->pUsb_Dev->descriptor.idProduct);
-
-#endif // RT2870 //
-			wrq->u.data.length = strlen(tmp);
-			Status = copy_to_user(wrq->u.data.pointer, tmp, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTUREID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTUREID \n"));
-			wrq->u.data.length = strlen(ManufacturerNAME);
-			Status = copy_to_user(wrq->u.data.pointer, ManufacturerNAME, wrq->u.data.length);
-			break;
-
-		case OID_802_11_CURRENTCHANNEL:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CURRENTCHANNEL \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			DBGPRINT(RT_DEBUG_TRACE, ("sizeof UCHAR=%d, channel=%d \n", sizeof(UCHAR), pAdapter->CommonCfg.Channel));
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Channel, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-#endif //SNMP_SUPPORT
-
-		case OID_802_11_BUILD_CHANNEL_EX:
-			{
-				UCHAR value;
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BUILD_CHANNEL_EX \n"));
-				wrq->u.data.length = sizeof(UCHAR);
-#ifdef EXT_BUILD_CHANNEL_LIST
-				DBGPRINT(RT_DEBUG_TRACE, ("Support EXT_BUILD_CHANNEL_LIST.\n"));
-				value = 1;
-#else
-				DBGPRINT(RT_DEBUG_TRACE, ("Doesn't support EXT_BUILD_CHANNEL_LIST.\n"));
-				value = 0;
-#endif // EXT_BUILD_CHANNEL_LIST //
-				Status = copy_to_user(wrq->u.data.pointer, &value, 1);
-				DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			}
-			break;
-
-		case OID_802_11_GET_CH_LIST:
-			{
-				PRT_CHANNEL_LIST_INFO pChListBuf;
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_CH_LIST \n"));
-				if (pAdapter->ChannelListNum == 0)
-				{
-					wrq->u.data.length = 0;
-					break;
-				}
-
-				pChListBuf = (RT_CHANNEL_LIST_INFO *) kmalloc(sizeof(RT_CHANNEL_LIST_INFO), MEM_ALLOC_FLAG);
-				if (pChListBuf == NULL)
-				{
-					wrq->u.data.length = 0;
-					break;
-				}
-
-				pChListBuf->ChannelListNum = pAdapter->ChannelListNum;
-				for (i = 0; i < pChListBuf->ChannelListNum; i++)
-					pChListBuf->ChannelList[i] = pAdapter->ChannelList[i].Channel;
-
-				wrq->u.data.length = sizeof(RT_CHANNEL_LIST_INFO);
-				Status = copy_to_user(wrq->u.data.pointer, pChListBuf, sizeof(RT_CHANNEL_LIST_INFO));
-				DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-
-				if (pChListBuf)
-					kfree(pChListBuf);
-			}
-			break;
-
-		case OID_802_11_GET_COUNTRY_CODE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_COUNTRY_CODE \n"));
-			wrq->u.data.length = 2;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.CountryCode, 2);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-
-		case OID_802_11_GET_CHANNEL_GEOGRAPHY:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_CHANNEL_GEOGRAPHY \n"));
-			wrq->u.data.length = 1;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Geography, 1);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-
-
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_QUERY_DLS:
-			wrq->u.data.length = sizeof(BOOLEAN);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bDLSCapable, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_DLS(=%d)\n", pAdapter->CommonCfg.bDLSCapable));
-			break;
-
-		case RT_OID_802_11_QUERY_DLS_PARAM:
-			{
-				PRT_802_11_DLS_INFO	pDlsInfo = kmalloc(sizeof(RT_802_11_DLS_INFO), GFP_ATOMIC);
-				if (pDlsInfo == NULL)
-					break;
-
-				for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-				{
-					RTMPMoveMemory(&pDlsInfo->Entry[i], &pAdapter->StaCfg.DLSEntry[i], sizeof(RT_802_11_DLS_UI));
-				}
-
-				pDlsInfo->num = MAX_NUM_OF_DLS_ENTRY;
-				wrq->u.data.length = sizeof(RT_802_11_DLS_INFO);
-				Status = copy_to_user(wrq->u.data.pointer, pDlsInfo, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_DLS_PARAM\n"));
-
-				if (pDlsInfo)
-					kfree(pDlsInfo);
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::unknown IOCTL's subcmd = 0x%08x\n", cmd));
-            Status = -EOPNOTSUPP;
-            break;
-    }
-    return Status;
-}
-
-INT rt28xx_sta_ioctl(
-	IN	struct net_device	*net_dev,
-	IN	OUT	struct ifreq	*rq,
-	IN	INT					cmd)
-{
-	POS_COOKIE			pObj;
-	VIRTUAL_ADAPTER		*pVirtualAd = NULL;
-	RTMP_ADAPTER        *pAd = NULL;
-	struct iwreq        *wrq = (struct iwreq *) rq;
-	BOOLEAN				StateMachineTouched = FALSE;
-	INT					Status = NDIS_STATUS_SUCCESS;
-	USHORT				subcmd;
-
-	if (net_dev->priv_flags == INT_MAIN)
-	{
-		pAd = net_dev->priv;
-	}
-	else
-	{
-		pVirtualAd = net_dev->priv;
-		pAd = pVirtualAd->RtmpDev->priv;
-	}
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	    if (wrq->u.data.pointer == NULL)
-	    {
-		    return Status;
-	    }
-
-	    if (strstr(wrq->u.data.pointer, "OpMode") == NULL)
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		    return -ENETDOWN;
-        }
-    }
-
-	{	// determine this ioctl command is comming from which interface.
-		pObj->ioctl_if_type = INT_MAIN;
-		pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-	switch(cmd)
-	{
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-		case RTPRIV_IOCTL_ATE:
-			{
-				RtmpDoAte(pAd, wrq);
-			}
-			break;
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-        case SIOCGIFHWADDR:
-			DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCGIFHWADDR\n"));
-			memcpy(wrq->u.name, pAd->CurrentAddress, ETH_ALEN);
-			break;
-		case SIOCGIWNAME:
-        {
-        	char *name=&wrq->u.name[0];
-        	rt_ioctl_giwname(net_dev, NULL, name, NULL);
-			break;
-		}
-		case SIOCGIWESSID:  //Get ESSID
-        {
-        	struct iw_point *essid=&wrq->u.essid;
-        	rt_ioctl_giwessid(net_dev, NULL, essid, essid->pointer);
-			break;
-		}
-		case SIOCSIWESSID:  //Set ESSID
-        {
-        	struct iw_point	*essid=&wrq->u.essid;
-        	rt_ioctl_siwessid(net_dev, NULL, essid, essid->pointer);
-			break;
-		}
-		case SIOCSIWNWID:   // set network id (the cell)
-		case SIOCGIWNWID:   // get network id
-			Status = -EOPNOTSUPP;
-			break;
-		case SIOCSIWFREQ:   //set channel/frequency (Hz)
-        {
-        	struct iw_freq *freq=&wrq->u.freq;
-        	rt_ioctl_siwfreq(net_dev, NULL, freq, NULL);
-			break;
-		}
-		case SIOCGIWFREQ:   // get channel/frequency (Hz)
-        {
-        	struct iw_freq *freq=&wrq->u.freq;
-        	rt_ioctl_giwfreq(net_dev, NULL, freq, NULL);
-			break;
-		}
-		case SIOCSIWNICKN: //set node name/nickname
-        {
-        	struct iw_point *data=&wrq->u.data;
-        	rt_ioctl_siwnickn(net_dev, NULL, data, NULL);
-			break;
-		}
-		case SIOCGIWNICKN: //get node name/nickname
-        {
-        	struct iw_point *data=&wrq->u.data;
-        	rt_ioctl_giwnickn(net_dev, NULL, data, NULL);
-			break;
-		}
-		case SIOCGIWRATE:   //get default bit rate (bps)
-		    rt_ioctl_giwrate(net_dev, NULL, &wrq->u, NULL);
-            break;
-	    case SIOCSIWRATE:  //set default bit rate (bps)
-	        rt_ioctl_siwrate(net_dev, NULL, &wrq->u, NULL);
-            break;
-        case SIOCGIWRTS:  // get RTS/CTS threshold (bytes)
-        {
-        	struct iw_param *rts=&wrq->u.rts;
-        	rt_ioctl_giwrts(net_dev, NULL, rts, NULL);
-			break;
-		}
-        case SIOCSIWRTS:  //set RTS/CTS threshold (bytes)
-        {
-        	struct iw_param *rts=&wrq->u.rts;
-        	rt_ioctl_siwrts(net_dev, NULL, rts, NULL);
-			break;
-		}
-        case SIOCGIWFRAG:  //get fragmentation thr (bytes)
-        {
-        	struct iw_param *frag=&wrq->u.frag;
-        	rt_ioctl_giwfrag(net_dev, NULL, frag, NULL);
-			break;
-		}
-        case SIOCSIWFRAG:  //set fragmentation thr (bytes)
-        {
-        	struct iw_param *frag=&wrq->u.frag;
-        	rt_ioctl_siwfrag(net_dev, NULL, frag, NULL);
-			break;
-		}
-        case SIOCGIWENCODE:  //get encoding token & mode
-        {
-        	struct iw_point *erq=&wrq->u.encoding;
-        	if(erq->pointer)
-        		rt_ioctl_giwencode(net_dev, NULL, erq, erq->pointer);
-			break;
-		}
-        case SIOCSIWENCODE:  //set encoding token & mode
-        {
-        	struct iw_point *erq=&wrq->u.encoding;
-        	if(erq->pointer)
-        		rt_ioctl_siwencode(net_dev, NULL, erq, erq->pointer);
-			break;
-		}
-		case SIOCGIWAP:     //get access point MAC addresses
-        {
-        	struct sockaddr *ap_addr=&wrq->u.ap_addr;
-        	rt_ioctl_giwap(net_dev, NULL, ap_addr, ap_addr->sa_data);
-			break;
-		}
-	    case SIOCSIWAP:  //set access point MAC addresses
-        {
-        	struct sockaddr *ap_addr=&wrq->u.ap_addr;
-        	rt_ioctl_siwap(net_dev, NULL, ap_addr, ap_addr->sa_data);
-			break;
-		}
-		case SIOCGIWMODE:   //get operation mode
-        {
-        	__u32 *mode=&wrq->u.mode;
-        	rt_ioctl_giwmode(net_dev, NULL, mode, NULL);
-			break;
-		}
-		case SIOCSIWMODE:   //set operation mode
-        {
-        	__u32 *mode=&wrq->u.mode;
-        	rt_ioctl_siwmode(net_dev, NULL, mode, NULL);
-			break;
-		}
-		case SIOCGIWSENS:   //get sensitivity (dBm)
-		case SIOCSIWSENS:	//set sensitivity (dBm)
-		case SIOCGIWPOWER:  //get Power Management settings
-		case SIOCSIWPOWER:  //set Power Management settings
-		case SIOCGIWTXPOW:  //get transmit power (dBm)
-		case SIOCSIWTXPOW:  //set transmit power (dBm)
-		case SIOCGIWRANGE:	//Get range of parameters
-		case SIOCGIWRETRY:	//get retry limits and lifetime
-		case SIOCSIWRETRY:	//set retry limits and lifetime
-			Status = -EOPNOTSUPP;
-			break;
-		case RT_PRIV_IOCTL:
-			subcmd = wrq->u.data.flags;
-			if( subcmd & OID_GET_SET_TOGGLE)
-				Status = RTMPSetInformation(pAd, rq, subcmd);
-			else
-				Status = RTMPQueryInformation(pAd, rq, subcmd);
-			break;
-		case SIOCGIWPRIV:
-			if (wrq->u.data.pointer)
-			{
-				if ( access_ok(VERIFY_WRITE, wrq->u.data.pointer, sizeof(privtab)) != TRUE)
-					break;
-				wrq->u.data.length = sizeof(privtab) / sizeof(privtab[0]);
-				if (copy_to_user(wrq->u.data.pointer, privtab, sizeof(privtab)))
-					Status = -EFAULT;
-			}
-			break;
-		case RTPRIV_IOCTL_SET:
-			if(access_ok(VERIFY_READ, wrq->u.data.pointer, wrq->u.data.length) != TRUE)
-				break;
-			rt_ioctl_setparam(net_dev, NULL, NULL, wrq->u.data.pointer);
-			break;
-		case RTPRIV_IOCTL_GSITESURVEY:
-			RTMPIoctlGetSiteSurvey(pAd, wrq);
-		    break;
-#ifdef DBG
-		case RTPRIV_IOCTL_MAC:
-			RTMPIoctlMAC(pAd, wrq);
-			break;
-		case RTPRIV_IOCTL_E2P:
-			RTMPIoctlE2PROM(pAd, wrq);
-			break;
-#endif // DBG //
-        case SIOCETHTOOL:
-                break;
-		default:
-			DBGPRINT(RT_DEBUG_ERROR, ("IOCTL::unknown IOCTL's cmd = 0x%08x\n", cmd));
-			Status = -EOPNOTSUPP;
-			break;
-	}
-
-    if(StateMachineTouched) // Upper layer sent a MLME-related operations
-    	RT28XX_MLME_HANDLER(pAd);
-
-	return Status;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set SSID
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_SSID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    NDIS_802_11_SSID                    Ssid, *pSsid=NULL;
-    BOOLEAN                             StateMachineTouched = FALSE;
-    int                                 success = TRUE;
-
-    if( strlen(arg) <= MAX_LEN_OF_SSID)
-    {
-        NdisZeroMemory(&Ssid, sizeof(NDIS_802_11_SSID));
-        if (strlen(arg) != 0)
-        {
-            NdisMoveMemory(Ssid.Ssid, arg, strlen(arg));
-            Ssid.SsidLength = strlen(arg);
-        }
-        else   //ANY ssid
-        {
-            Ssid.SsidLength = 0;
-		    memcpy(Ssid.Ssid, "", 0);
-			pAdapter->StaCfg.BssType = BSS_INFRA;
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-	        pAdapter->StaCfg.WepStatus  = Ndis802_11EncryptionDisabled;
-		}
-        pSsid = &Ssid;
-
-        if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-        {
-            RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-            DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-        }
-
-        pAdapter->MlmeAux.CurrReqIsFromNdis = TRUE;
-        pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-		pAdapter->bConfigChanged = TRUE;
-
-        MlmeEnqueue(pAdapter,
-                    MLME_CNTL_STATE_MACHINE,
-                    OID_802_11_SSID,
-                    sizeof(NDIS_802_11_SSID),
-                    (VOID *)pSsid);
-
-        StateMachineTouched = TRUE;
-        DBGPRINT(RT_DEBUG_TRACE, ("Set_SSID_Proc::(Len=%d,Ssid=%s)\n", Ssid.SsidLength, Ssid.Ssid));
-    }
-    else
-        success = FALSE;
-
-    if (StateMachineTouched) // Upper layer sent a MLME-related operations
-    	RT28XX_MLME_HANDLER(pAdapter);
-
-    return success;
-}
-
-#ifdef WMM_SUPPORT
-/*
-    ==========================================================================
-    Description:
-        Set WmmCapable Enable or Disable
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	BOOLEAN	bWmmCapable;
-
-	bWmmCapable = simple_strtol(arg, 0, 10);
-
-	if ((bWmmCapable == 1)
-#ifdef RT2870
-		&& (pAd->NumberOfPipes >= 5)
-#endif // RT2870 //
-		)
-		pAd->CommonCfg.bWmmCapable = TRUE;
-	else if (bWmmCapable == 0)
-		pAd->CommonCfg.bWmmCapable = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_WmmCapable_Proc::(bWmmCapable=%d)\n",
-		pAd->CommonCfg.bWmmCapable));
-
-	return TRUE;
-}
-#endif // WMM_SUPPORT //
-
-/*
-    ==========================================================================
-    Description:
-        Set Network Type(Infrastructure/Adhoc mode)
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_NetworkType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    UINT32	Value = 0;
-
-    if (strcmp(arg, "Adhoc") == 0)
-	{
-		if (pAdapter->StaCfg.BssType != BSS_ADHOC)
-		{
-			// Config has changed
-			pAdapter->bConfigChanged = TRUE;
-            if (MONITOR_ON(pAdapter))
-            {
-                RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, STANORMAL);
-                RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-				Value &= (~0x80);
-				RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-                OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-                pAdapter->StaCfg.bAutoReconnect = TRUE;
-                LinkDown(pAdapter, FALSE);
-            }
-			if (INFRA_ON(pAdapter))
-			{
-				//BOOLEAN Cancelled;
-				// Set the AutoReconnectSsid to prevent it reconnect to old SSID
-				// Since calling this indicate user don't want to connect to that SSID anymore.
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-				NdisZeroMemory(pAdapter->MlmeAux.AutoReconnectSsid, pAdapter->MlmeAux.AutoReconnectSsidLen);
-
-				LinkDown(pAdapter, FALSE);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event BB!\n"));
-			}
-		}
-		pAdapter->StaCfg.BssType = BSS_ADHOC;
-        pAdapter->net_dev->type = pAdapter->StaCfg.OriDevType;
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(AD-HOC)\n"));
-	}
-    else if (strcmp(arg, "Infra") == 0)
-	{
-		if (pAdapter->StaCfg.BssType != BSS_INFRA)
-		{
-			// Config has changed
-			pAdapter->bConfigChanged = TRUE;
-            if (MONITOR_ON(pAdapter))
-            {
-                RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, STANORMAL);
-                RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-				Value &= (~0x80);
-				RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-                OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-                pAdapter->StaCfg.bAutoReconnect = TRUE;
-                LinkDown(pAdapter, FALSE);
-            }
-			if (ADHOC_ON(pAdapter))
-			{
-				// Set the AutoReconnectSsid to prevent it reconnect to old SSID
-				// Since calling this indicate user don't want to connect to that SSID anymore.
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-				NdisZeroMemory(pAdapter->MlmeAux.AutoReconnectSsid, pAdapter->MlmeAux.AutoReconnectSsidLen);
-
-				LinkDown(pAdapter, FALSE);
-			}
-		}
-		pAdapter->StaCfg.BssType = BSS_INFRA;
-        pAdapter->net_dev->type = pAdapter->StaCfg.OriDevType;
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(INFRA)\n"));
-
-        pAdapter->StaCfg.BssType = BSS_INFRA;
-	}
-    else if (strcmp(arg, "Monitor") == 0)
-    {
-		UCHAR	bbpValue = 0;
-		BCN_TIME_CFG_STRUC csr;
-		OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_INFRA_ON);
-        OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_ADHOC_ON);
-		OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-		// disable all periodic state machine
-		pAdapter->StaCfg.bAutoReconnect = FALSE;
-		// reset all mlme state machine
-		RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-		DBGPRINT(RT_DEBUG_TRACE, ("fOP_STATUS_MEDIA_STATE_CONNECTED \n"));
-        if (pAdapter->CommonCfg.CentralChannel == 0)
-        {
-#ifdef DOT11_N_SUPPORT
-            if (pAdapter->CommonCfg.PhyMode == PHY_11AN_MIXED)
-                pAdapter->CommonCfg.CentralChannel = 36;
-            else
-#endif // DOT11_N_SUPPORT //
-                pAdapter->CommonCfg.CentralChannel = 6;
-        }
-#ifdef DOT11_N_SUPPORT
-        else
-            N_ChannelCheck(pAdapter);
-#endif // DOT11_N_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-	if (pAdapter->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-            pAdapter->CommonCfg.RegTransmitSetting.field.BW == BW_40 &&
-            pAdapter->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_ABOVE)
-		{
-			// 40MHz ,control channel at lower
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			bbpValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_40;
-			//  RX : control channel at lower
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R3, &bbpValue);
-			bbpValue &= (~0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R3, bbpValue);
-
-			RTMP_IO_READ32(pAdapter, TX_BAND_CFG, &Value);
-			Value &= 0xfffffffe;
-			RTMP_IO_WRITE32(pAdapter, TX_BAND_CFG, Value);
-			pAdapter->CommonCfg.CentralChannel = pAdapter->CommonCfg.Channel + 2;
-            AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.CentralChannel, FALSE);
-		    AsicLockChannel(pAdapter, pAdapter->CommonCfg.CentralChannel);
-            DBGPRINT(RT_DEBUG_TRACE, ("BW_40 ,control_channel(%d), CentralChannel(%d) \n",
-                                       pAdapter->CommonCfg.Channel,
-                                       pAdapter->CommonCfg.CentralChannel));
-		}
-		else if (pAdapter->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-                 pAdapter->CommonCfg.RegTransmitSetting.field.BW == BW_40 &&
-                 pAdapter->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_BELOW)
-		{
-			// 40MHz ,control channel at upper
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			bbpValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_40;
-			RTMP_IO_READ32(pAdapter, TX_BAND_CFG, &Value);
-			Value |= 0x1;
-			RTMP_IO_WRITE32(pAdapter, TX_BAND_CFG, Value);
-
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R3, &bbpValue);
-			bbpValue |= (0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R3, bbpValue);
-			pAdapter->CommonCfg.CentralChannel = pAdapter->CommonCfg.Channel - 2;
-            AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.CentralChannel, FALSE);
-		    AsicLockChannel(pAdapter, pAdapter->CommonCfg.CentralChannel);
-            DBGPRINT(RT_DEBUG_TRACE, ("BW_40 ,control_channel(%d), CentralChannel(%d) \n",
-                                       pAdapter->CommonCfg.Channel,
-                                       pAdapter->CommonCfg.CentralChannel));
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			// 20MHz
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_20;
-			AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.Channel, FALSE);
-			AsicLockChannel(pAdapter, pAdapter->CommonCfg.Channel);
-			DBGPRINT(RT_DEBUG_TRACE, ("BW_20, Channel(%d)\n", pAdapter->CommonCfg.Channel));
-		}
-		// Enable Rx with promiscuous reception
-		RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, 0x3);
-		// ASIC supporsts sniffer function with replacing RSSI with timestamp.
-		//RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-		//Value |= (0x80);
-		//RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-		// disable sync
-		RTMP_IO_READ32(pAdapter, BCN_TIME_CFG, &csr.word);
-		csr.field.bBeaconGen = 0;
-		csr.field.bTBTTEnable = 0;
-		csr.field.TsfSyncMode = 0;
-		RTMP_IO_WRITE32(pAdapter, BCN_TIME_CFG, csr.word);
-
-		pAdapter->StaCfg.BssType = BSS_MONITOR;
-        pAdapter->net_dev->type = ARPHRD_IEEE80211_PRISM; //ARPHRD_IEEE80211; // IEEE80211
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(MONITOR)\n"));
-    }
-
-    // Reset Ralink supplicant to not use, it will be set to start when UI set PMK key
-    pAdapter->StaCfg.WpaState = SS_NOTUSE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_NetworkType_Proc::(NetworkType=%d)\n", pAdapter->StaCfg.BssType));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Authentication mode
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_AuthMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if ((strcmp(arg, "WEPAUTO") == 0) || (strcmp(arg, "wepauto") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeAutoSwitch;
-    else if ((strcmp(arg, "OPEN") == 0) || (strcmp(arg, "open") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-    else if ((strcmp(arg, "SHARED") == 0) || (strcmp(arg, "shared") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-    else if ((strcmp(arg, "WPAPSK") == 0) || (strcmp(arg, "wpapsk") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPAPSK;
-    else if ((strcmp(arg, "WPANONE") == 0) || (strcmp(arg, "wpanone") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
-    else if ((strcmp(arg, "WPA2PSK") == 0) || (strcmp(arg, "wpa2psk") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-#ifdef WPA_SUPPLICANT_SUPPORT
-    else if ((strcmp(arg, "WPA") == 0) || (strcmp(arg, "wpa") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
-    else if ((strcmp(arg, "WPA2") == 0) || (strcmp(arg, "wpa2") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#endif // WPA_SUPPLICANT_SUPPORT //
-    else
-        return FALSE;
-
-    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_AuthMode_Proc::(AuthMode=%d)\n", pAdapter->StaCfg.AuthMode));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Encryption Type
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_EncrypType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if ((strcmp(arg, "NONE") == 0) || (strcmp(arg, "none") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11WEPDisabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11WEPDisabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11WEPDisabled;
-    }
-    else if ((strcmp(arg, "WEP") == 0) || (strcmp(arg, "wep") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11WEPEnabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11WEPEnabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11WEPEnabled;
-    }
-    else if ((strcmp(arg, "TKIP") == 0) || (strcmp(arg, "tkip") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11Encryption2Enabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11Encryption2Enabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11Encryption2Enabled;
-    }
-    else if ((strcmp(arg, "AES") == 0) || (strcmp(arg, "aes") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11Encryption3Enabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11Encryption3Enabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11Encryption3Enabled;
-    }
-    else
-        return FALSE;
-
-    pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_EncrypType_Proc::(EncrypType=%d)\n", pAdapter->StaCfg.WepStatus));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Default Key ID
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_DefaultKeyID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    ULONG                               KeyIdx;
-
-    KeyIdx = simple_strtol(arg, 0, 10);
-    if((KeyIdx >= 1 ) && (KeyIdx <= 4))
-        pAdapter->StaCfg.DefaultKeyId = (UCHAR) (KeyIdx - 1 );
-    else
-        return FALSE;  //Invalid argument
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_DefaultKeyID_Proc::(DefaultKeyID=%d)\n", pAdapter->StaCfg.DefaultKeyId));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY1
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key1_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][0].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][0].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][0].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][0].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-
-    pAdapter->SharedKey[BSS0][0].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              0,
-                              pAdapter->SharedKey[BSS0][0].CipherAlg,
-                              pAdapter->SharedKey[BSS0][0].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-
-    Description:
-        Set WEP KEY2
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key2_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][1].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][1].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][1].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][1].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][1].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              1,
-                              pAdapter->SharedKey[BSS0][1].CipherAlg,
-                              pAdapter->SharedKey[BSS0][1].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY3
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key3_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][2].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Ascii)\n", arg));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][2].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Hex)\n", arg));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][2].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Ascii)\n", arg));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][2].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Hex)\n", arg));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][2].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              2,
-                              pAdapter->SharedKey[BSS0][2].CipherAlg,
-                              pAdapter->SharedKey[BSS0][2].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY4
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key4_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][3].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][3].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][3].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][3].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][3].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              3,
-                              pAdapter->SharedKey[BSS0][3].CipherAlg,
-                              pAdapter->SharedKey[BSS0][3].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set WPA PSK key
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_WPAPSK_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    UCHAR                   keyMaterial[40];
-
-    if ((pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPAPSK) &&
-        (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-	    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone)
-		)
-        return TRUE;    // do nothing
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_WPAPSK_Proc::(WPAPSK=%s)\n", arg));
-
-    NdisZeroMemory(keyMaterial, 40);
-
-    if ((strlen(arg) < 8) || (strlen(arg) > 64))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("Set failed!!(WPAPSK=%s), WPAPSK key-string required 8 ~ 64 characters \n", arg));
-        return FALSE;
-    }
-
-    if (strlen(arg) == 64)
-    {
-        AtoH(arg, keyMaterial, 32);
-        NdisMoveMemory(pAdapter->StaCfg.PMK, keyMaterial, 32);
-
-    }
-    else
-    {
-        PasswordHash((char *)arg, pAdapter->MlmeAux.Ssid, pAdapter->MlmeAux.SsidLen, keyMaterial);
-        NdisMoveMemory(pAdapter->StaCfg.PMK, keyMaterial, 32);
-    }
-
-
-
-    if(pAdapter->StaCfg.BssType == BSS_ADHOC &&
-       pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-    {
-         pAdapter->StaCfg.WpaState = SS_NOTUSE;
-    }
-    else
-    {
-        // Start STA supplicant state machine
-        pAdapter->StaCfg.WpaState = SS_START;
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Power Saving mode
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_PSMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if (pAdapter->StaCfg.BssType == BSS_INFRA)
-    {
-        if ((strcmp(arg, "Max_PSP") == 0) ||
-			(strcmp(arg, "max_psp") == 0) ||
-			(strcmp(arg, "MAX_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeMAX_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeMAX_PSP;
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            pAdapter->StaCfg.DefaultListenCount = 5;
-
-        }
-        else if ((strcmp(arg, "Fast_PSP") == 0) ||
-				 (strcmp(arg, "fast_psp") == 0) ||
-                 (strcmp(arg, "FAST_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeFast_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeFast_PSP;
-            pAdapter->StaCfg.DefaultListenCount = 3;
-        }
-        else if ((strcmp(arg, "Legacy_PSP") == 0) ||
-                 (strcmp(arg, "legacy_psp") == 0) ||
-                 (strcmp(arg, "LEGACY_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeLegacy_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeLegacy_PSP;
-            pAdapter->StaCfg.DefaultListenCount = 3;
-        }
-        else
-        {
-            //Default Ndis802_11PowerModeCAM
-            // clear PSM bit immediately
-            MlmeSetPsmBit(pAdapter, PWR_ACTIVE);
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeCAM;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeCAM;
-        }
-
-        DBGPRINT(RT_DEBUG_TRACE, ("Set_PSMode_Proc::(PSMode=%ld)\n", pAdapter->StaCfg.WindowsPowerMode));
-    }
-    else
-        return FALSE;
-
-
-    return TRUE;
-}
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-/*
-    ==========================================================================
-    Description:
-        Set WpaSupport flag.
-    Value:
-        0: Driver ignore wpa_supplicant.
-        1: wpa_supplicant initiates scanning and AP selection.
-        2: driver takes care of scanning, AP selection, and IEEE 802.11 association parameters.
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Wpa_Support(
-    IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-    if ( simple_strtol(arg, 0, 10) == 0)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_DISABLE;
-    else if ( simple_strtol(arg, 0, 10) == 1)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_ENABLE;
-    else if ( simple_strtol(arg, 0, 10) == 2)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_ENABLE_WITH_WEB_UI;
-    else
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_DISABLE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_Wpa_Support::(WpaSupplicantUP=%d)\n", pAd->StaCfg.WpaSupplicantUP));
-
-    return TRUE;
-}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef DBG
-/*
-    ==========================================================================
-    Description:
-        Read / Write MAC
-    Arguments:
-        pAdapter                    Pointer to our adapter
-        wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-               1.) iwpriv ra0 mac 0        ==> read MAC where Addr=0x0
-               2.) iwpriv ra0 mac 0=12     ==> write MAC where Addr=0x0, value=12
-    ==========================================================================
-*/
-VOID RTMPIoctlMAC(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	CHAR				*this_char;
-	CHAR				*value;
-	INT					j = 0, k = 0;
-	CHAR				msg[1024];
-	CHAR				arg[255];
-	ULONG				macAddr = 0;
-	UCHAR				temp[16], temp2[16];
-	UINT32				macValue = 0;
-	INT					Status;
-
-
-	memset(msg, 0x00, 1024);
-	if (wrq->u.data.length > 1) //No parameters.
-	{
-	    Status = copy_from_user(arg, wrq->u.data.pointer, (wrq->u.data.length > 255) ? 255 : wrq->u.data.length);
-		sprintf(msg, "\n");
-
-		//Parsing Read or Write
-	    this_char = arg;
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-			// Sanity check
-			if(strlen(this_char) > 4)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			// Mac Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			if(strlen(this_char) == 4)
-			{
-				AtoH(this_char, temp, 2);
-				macAddr = *temp*256 + temp[1];
-				if (macAddr < 0xFFFF)
-				{
-					RTMP_IO_READ32(pAdapter, macAddr, &macValue);
-					DBGPRINT(RT_DEBUG_TRACE, ("MacAddr=%lx, MacValue=%x\n", macAddr, macValue));
-					sprintf(msg+strlen(msg), "[0x%08lX]:%08X  ", macAddr , macValue);
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					goto next;
-				}
-			}
-		}
-		else
-		{ //Write
-			memcpy(&temp2, value, strlen(value));
-			temp2[strlen(value)] = '\0';
-
-			// Sanity check
-			if((strlen(this_char) > 4) || strlen(temp2) > 8)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			j = strlen(temp2);
-			while(j-- > 0)
-			{
-				if(temp2[j] > 'f' || temp2[j] < '0')
-					return;
-			}
-
-			//MAC Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			//MAC value
-			k = j = strlen(temp2);
-			while(j-- > 0)
-			{
-				temp2[8-k+j] = temp2[j];
-			}
-
-			while(k < 8)
-				temp2[7-k++]='0';
-			temp2[8]='\0';
-
-			{
-				AtoH(this_char, temp, 2);
-				macAddr = *temp*256 + temp[1];
-
-				AtoH(temp2, temp, 4);
-				macValue = *temp*256*256*256 + temp[1]*256*256 + temp[2]*256 + temp[3];
-
-				// debug mode
-				if (macAddr == (HW_DEBUG_SETTING_BASE + 4))
-				{
-					// 0x2bf4: byte0 non-zero: enable R17 tuning, 0: disable R17 tuning
-                    if (macValue & 0x000000ff)
-                    {
-                        pAdapter->BbpTuning.bEnable = TRUE;
-                        DBGPRINT(RT_DEBUG_TRACE,("turn on R17 tuning\n"));
-                    }
-                    else
-                    {
-                        UCHAR R66;
-                        pAdapter->BbpTuning.bEnable = FALSE;
-                        R66 = 0x26 + GET_LNA_GAIN(pAdapter);
-#ifdef RALINK_ATE
-						if (ATE_ON(pAdapter))
-						{
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R66, (0x26 + GET_LNA_GAIN(pAdapter)));
-						}
-						else
-#endif // RALINK_ATE //
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R66, (0x26 + GET_LNA_GAIN(pAdapter)));
-                        DBGPRINT(RT_DEBUG_TRACE,("turn off R17 tuning, restore to 0x%02x\n", R66));
-                    }
-					return;
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE, ("MacAddr=%02lx, MacValue=0x%x\n", macAddr, macValue));
-
-				RTMP_IO_WRITE32(pAdapter, macAddr, macValue);
-				sprintf(msg+strlen(msg), "[0x%08lX]:%08X  ", macAddr, macValue);
-			}
-		}
-	}
-next:
-	if(strlen(msg) == 1)
-		sprintf(msg+strlen(msg), "===>Error command format!");
-
-	// Copy the information into the user buffer
-	wrq->u.data.length = strlen(msg);
-	Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==RTMPIoctlMAC\n\n"));
-}
-
-/*
-    ==========================================================================
-    Description:
-        Read / Write E2PROM
-    Arguments:
-        pAdapter                    Pointer to our adapter
-        wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-               1.) iwpriv ra0 e2p 0     	==> read E2PROM where Addr=0x0
-               2.) iwpriv ra0 e2p 0=1234    ==> write E2PROM where Addr=0x0, value=1234
-    ==========================================================================
-*/
-VOID RTMPIoctlE2PROM(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	CHAR				*this_char;
-	CHAR				*value;
-	INT					j = 0, k = 0;
-	CHAR				msg[1024];
-	CHAR				arg[255];
-	USHORT				eepAddr = 0;
-	UCHAR				temp[16], temp2[16];
-	USHORT				eepValue;
-	int					Status;
-
-
-	memset(msg, 0x00, 1024);
-	if (wrq->u.data.length > 1) //No parameters.
-	{
-	    Status = copy_from_user(arg, wrq->u.data.pointer, (wrq->u.data.length > 255) ? 255 : wrq->u.data.length);
-		sprintf(msg, "\n");
-
-	    //Parsing Read or Write
-		this_char = arg;
-
-
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-
-			// Sanity check
-			if(strlen(this_char) > 4)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			// E2PROM addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			if(strlen(this_char) == 4)
-			{
-				AtoH(this_char, temp, 2);
-				eepAddr = *temp*256 + temp[1];
-				if (eepAddr < 0xFFFF)
-				{
-					RT28xx_EEPROM_READ16(pAdapter, eepAddr, eepValue);
-					sprintf(msg+strlen(msg), "[0x%04X]:0x%04X  ", eepAddr , eepValue);
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					goto next;
-				}
-			}
-		}
-		else
-		{ //Write
-			memcpy(&temp2, value, strlen(value));
-			temp2[strlen(value)] = '\0';
-
-			// Sanity check
-			if((strlen(this_char) > 4) || strlen(temp2) > 8)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-			j = strlen(temp2);
-			while(j-- > 0)
-			{
-				if(temp2[j] > 'f' || temp2[j] < '0')
-					return;
-			}
-
-			//MAC Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			//MAC value
-			k = j = strlen(temp2);
-			while(j-- > 0)
-			{
-				temp2[4-k+j] = temp2[j];
-			}
-
-			while(k < 4)
-				temp2[3-k++]='0';
-			temp2[4]='\0';
-
-			AtoH(this_char, temp, 2);
-			eepAddr = *temp*256 + temp[1];
-
-			AtoH(temp2, temp, 2);
-			eepValue = *temp*256 + temp[1];
-
-			RT28xx_EEPROM_WRITE16(pAdapter, eepAddr, eepValue);
-			sprintf(msg+strlen(msg), "[0x%02X]:%02X  ", eepAddr, eepValue);
-		}
-	}
-next:
-	if(strlen(msg) == 1)
-		sprintf(msg+strlen(msg), "===>Error command format!");
-
-
-	// Copy the information into the user buffer
-	wrq->u.data.length = strlen(msg);
-	Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==RTMPIoctlE2PROM\n"));
-}
-#endif // DBG //
-
-
-
-
-INT Set_TGnWifiTest_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAd->StaCfg.bTGnWifiTest = FALSE;
-    else
-        pAd->StaCfg.bTGnWifiTest = TRUE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IF Set_TGnWifiTest_Proc::(bTGnWifiTest=%d)\n", pAd->StaCfg.bTGnWifiTest));
-	return TRUE;
-}
-
-INT Set_LongRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg)
-{
-	TX_RTY_CFG_STRUC	tx_rty_cfg;
-	UCHAR				LongRetryLimit = (UCHAR)simple_strtol(arg, 0, 10);
-
-	RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-	tx_rty_cfg.field.LongRtyLimit = LongRetryLimit;
-	RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-	DBGPRINT(RT_DEBUG_TRACE, ("IF Set_LongRetryLimit_Proc::(tx_rty_cfg=0x%x)\n", tx_rty_cfg.word));
-	return TRUE;
-}
-
-INT Set_ShortRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg)
-{
-	TX_RTY_CFG_STRUC	tx_rty_cfg;
-	UCHAR				ShortRetryLimit = (UCHAR)simple_strtol(arg, 0, 10);
-
-	RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-	tx_rty_cfg.field.ShortRtyLimit = ShortRetryLimit;
-	RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-	DBGPRINT(RT_DEBUG_TRACE, ("IF Set_ShortRetryLimit_Proc::(tx_rty_cfg=0x%x)\n", tx_rty_cfg.word));
-	return TRUE;
-}
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-INT Set_Ieee80211dClientMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_None;
-    else if (simple_strtol(arg, 0, 10) == 1)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_Flexible;
-    else if (simple_strtol(arg, 0, 10) == 2)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_Strict;
-    else
-        return FALSE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_Ieee802dMode_Proc::(IEEEE0211dMode=%d)\n", pAdapter->StaCfg.IEEE80211dClientMode));
-    return TRUE;
-}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef CARRIER_DETECTION_SUPPORT
-INT Set_CarrierDetect_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-    else
-        pAd->CommonCfg.CarrierDetect.Enable = TRUE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IF Set_CarrierDetect_Proc::(CarrierDetect.Enable=%d)\n", pAd->CommonCfg.CarrierDetect.Enable));
-	return TRUE;
-}
-#endif // CARRIER_DETECTION_SUPPORT //
-
-
-INT	Show_Adhoc_MacTable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PCHAR			extra)
-{
-	INT i;
-
-	sprintf(extra, "\n");
-
-#ifdef DOT11_N_SUPPORT
-	sprintf(extra, "%sHT Operating Mode : %d\n", extra, pAd->CommonCfg.AddHTInfo.AddHtInfo2.OperaionMode);
-#endif // DOT11_N_SUPPORT //
-
-	sprintf(extra, "%s\n%-19s%-4s%-4s%-7s%-7s%-7s%-10s%-6s%-6s%-6s%-6s\n", extra,
-			"MAC", "AID", "BSS", "RSSI0", "RSSI1", "RSSI2", "PhMd", "BW", "MCS", "SGI", "STBC");
-
-	for (i=1; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[i];
-
-		if (strlen(extra) > (IW_PRIV_SIZE_MASK - 30))
-		    break;
-		if ((pEntry->ValidAsCLI || pEntry->ValidAsApCli) && (pEntry->Sst == SST_ASSOC))
-		{
-			sprintf(extra, "%s%02X:%02X:%02X:%02X:%02X:%02X  ", extra,
-				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
-				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5]);
-			sprintf(extra, "%s%-4d", extra, (int)pEntry->Aid);
-			sprintf(extra, "%s%-4d", extra, (int)pEntry->apidx);
-			sprintf(extra, "%s%-7d", extra, pEntry->RssiSample.AvgRssi0);
-			sprintf(extra, "%s%-7d", extra, pEntry->RssiSample.AvgRssi1);
-			sprintf(extra, "%s%-7d", extra, pEntry->RssiSample.AvgRssi2);
-			sprintf(extra, "%s%-10s", extra, GetPhyMode(pEntry->HTPhyMode.field.MODE));
-			sprintf(extra, "%s%-6s", extra, GetBW(pEntry->HTPhyMode.field.BW));
-			sprintf(extra, "%s%-6d", extra, pEntry->HTPhyMode.field.MCS);
-			sprintf(extra, "%s%-6d", extra, pEntry->HTPhyMode.field.ShortGI);
-			sprintf(extra, "%s%-6d", extra, pEntry->HTPhyMode.field.STBC);
-			sprintf(extra, "%s%-10d, %d, %d%%\n", extra, pEntry->DebugFIFOCount, pEntry->DebugTxCount,
-						(pEntry->DebugTxCount) ? ((pEntry->DebugTxCount-pEntry->DebugFIFOCount)*100/pEntry->DebugTxCount) : 0);
-			sprintf(extra, "%s\n", extra);
-		}
-	}
-
-	return TRUE;
-}
-
-
diff --git a/drivers/staging/rt2870/tmp61 b/drivers/staging/rt2870/tmp61
deleted file mode 100644
index 975e444..0000000
--- a/drivers/staging/rt2870/tmp61
+++ /dev/null
@@ -1,7037 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    sta_ioctl.c
-
-    Abstract:
-    IOCTL related subroutines
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Rory Chen   01-03-2003    created
-	Rory Chen   02-14-2005    modify to support RT61
-*/
-
-#include	"rt_config.h"
-
-#ifdef DBG
-extern ULONG    RTDebugLevel;
-#endif
-
-#define NR_WEP_KEYS 				4
-#define WEP_SMALL_KEY_LEN 			(40/8)
-#define WEP_LARGE_KEY_LEN 			(104/8)
-
-#define GROUP_KEY_NO                4
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
-#define IWE_STREAM_ADD_EVENT(_A, _B, _C, _D, _E)		iwe_stream_add_event(_A, _B, _C, _D, _E)
-#define IWE_STREAM_ADD_POINT(_A, _B, _C, _D, _E)		iwe_stream_add_point(_A, _B, _C, _D, _E)
-#define IWE_STREAM_ADD_VALUE(_A, _B, _C, _D, _E, _F)	iwe_stream_add_value(_A, _B, _C, _D, _E, _F)
-#else
-#define IWE_STREAM_ADD_EVENT(_A, _B, _C, _D, _E)		iwe_stream_add_event(_B, _C, _D, _E)
-#define IWE_STREAM_ADD_POINT(_A, _B, _C, _D, _E)		iwe_stream_add_point(_B, _C, _D, _E)
-#define IWE_STREAM_ADD_VALUE(_A, _B, _C, _D, _E, _F)	iwe_stream_add_value(_B, _C, _D, _E, _F)
-#endif
-
-extern UCHAR    CipherWpa2Template[];
-extern UCHAR    CipherWpaPskTkip[];
-extern UCHAR    CipherWpaPskTkipLen;
-
-typedef struct PACKED _RT_VERSION_INFO{
-    UCHAR       DriverVersionW;
-    UCHAR       DriverVersionX;
-    UCHAR       DriverVersionY;
-    UCHAR       DriverVersionZ;
-    UINT        DriverBuildYear;
-    UINT        DriverBuildMonth;
-    UINT        DriverBuildDay;
-} RT_VERSION_INFO, *PRT_VERSION_INFO;
-
-struct iw_priv_args privtab[] = {
-{ RTPRIV_IOCTL_SET,
-  IW_PRIV_TYPE_CHAR | 1024, 0,
-  "set"},
-
-{ RTPRIV_IOCTL_SHOW, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  ""},
-{ RTPRIV_IOCTL_SHOW, IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  ""},
-/* --- sub-ioctls definitions --- */
-    { SHOW_CONN_STATUS,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "connStatus" },
-	{ SHOW_DRVIER_VERION,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "driverVer" },
-    { SHOW_BA_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "bainfo" },
-	{ SHOW_DESC_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "descinfo" },
-    { RAIO_OFF,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "radio_off" },
-	{ RAIO_ON,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "radio_on" },
-#ifdef QOS_DLS_SUPPORT
-	{ SHOW_DLS_ENTRY_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "dlsentryinfo" },
-#endif // QOS_DLS_SUPPORT //
-	{ SHOW_CFG_VALUE,
-	  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "show" },
-	{ SHOW_ADHOC_ENTRY_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "adhocEntry" },
-
-/* --- sub-ioctls relations --- */
-
-#ifdef DBG
-{ RTPRIV_IOCTL_BBP,
-  IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  "bbp"},
-{ RTPRIV_IOCTL_MAC,
-  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | 1024,
-  "mac"},
-{ RTPRIV_IOCTL_E2P,
-  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | 1024,
-  "e2p"},
-#endif  /* DBG */
-
-{ RTPRIV_IOCTL_STATISTICS,
-  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  "stat"},
-{ RTPRIV_IOCTL_GSITESURVEY,
-  0, IW_PRIV_TYPE_CHAR | 1024,
-  "get_site_survey"},
-};
-
-INT Set_SSID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef WMM_SUPPORT
-INT	Set_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif
-
-INT Set_NetworkType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_AuthMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_EncrypType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_DefaultKeyID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key1_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key2_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key3_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key4_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_WPAPSK_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-
-INT Set_PSMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-INT Set_Wpa_Support(
-    IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef DBG
-VOID RTMPIoctlBBP(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID RTMPIoctlMAC(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID RTMPIoctlE2PROM(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  struct iwreq    *wrq);
-#endif // DBG //
-
-
-NDIS_STATUS RTMPWPANoneAddKeyProc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN	PVOID			pBuf);
-
-INT Set_FragTest_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef DOT11_N_SUPPORT
-INT Set_TGnWifiTest_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg);
-#endif // DOT11_N_SUPPORT //
-
-INT Set_LongRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg);
-
-INT Set_ShortRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg);
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-INT Set_Ieee80211dClientMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef CARRIER_DETECTION_SUPPORT
-INT Set_CarrierDetect_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg);
-#endif // CARRIER_DETECTION_SUPPORT //
-
-INT	Show_Adhoc_MacTable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PCHAR			extra);
-
-static struct {
-	CHAR *name;
-	INT (*set_proc)(PRTMP_ADAPTER pAdapter, PUCHAR arg);
-} *PRTMP_PRIVATE_SET_PROC, RTMP_PRIVATE_SUPPORT_PROC[] = {
-	{"DriverVersion",				Set_DriverVersion_Proc},
-	{"CountryRegion",				Set_CountryRegion_Proc},
-	{"CountryRegionABand",			Set_CountryRegionABand_Proc},
-	{"SSID",						Set_SSID_Proc},
-	{"WirelessMode",				Set_WirelessMode_Proc},
-	{"TxBurst",					Set_TxBurst_Proc},
-	{"TxPreamble",				Set_TxPreamble_Proc},
-	{"TxPower",					Set_TxPower_Proc},
-	{"Channel",					Set_Channel_Proc},
-	{"BGProtection",				Set_BGProtection_Proc},
-	{"RTSThreshold",				Set_RTSThreshold_Proc},
-	{"FragThreshold",				Set_FragThreshold_Proc},
-#ifdef DOT11_N_SUPPORT
-	{"HtBw",		                Set_HtBw_Proc},
-	{"HtMcs",		                Set_HtMcs_Proc},
-	{"HtGi",		                Set_HtGi_Proc},
-	{"HtOpMode",		            Set_HtOpMode_Proc},
-	{"HtExtcha",		            Set_HtExtcha_Proc},
-	{"HtMpduDensity",		        Set_HtMpduDensity_Proc},
-	{"HtBaWinSize",		        	Set_HtBaWinSize_Proc},
-	{"HtRdg",		        		Set_HtRdg_Proc},
-	{"HtAmsdu",		        		Set_HtAmsdu_Proc},
-	{"HtAutoBa",		        	Set_HtAutoBa_Proc},
-	{"HtBaDecline",					Set_BADecline_Proc},
-	{"HtProtect",		        	Set_HtProtect_Proc},
-	{"HtMimoPs",		        	Set_HtMimoPs_Proc},
-#endif // DOT11_N_SUPPORT //
-
-#ifdef AGGREGATION_SUPPORT
-	{"PktAggregate",				Set_PktAggregate_Proc},
-#endif
-
-#ifdef WMM_SUPPORT
-	{"WmmCapable",					Set_WmmCapable_Proc},
-#endif
-	{"IEEE80211H",					Set_IEEE80211H_Proc},
-    {"NetworkType",                 Set_NetworkType_Proc},
-	{"AuthMode",					Set_AuthMode_Proc},
-	{"EncrypType",					Set_EncrypType_Proc},
-	{"DefaultKeyID",				Set_DefaultKeyID_Proc},
-	{"Key1",						Set_Key1_Proc},
-	{"Key2",						Set_Key2_Proc},
-	{"Key3",						Set_Key3_Proc},
-	{"Key4",						Set_Key4_Proc},
-	{"WPAPSK",						Set_WPAPSK_Proc},
-	{"ResetCounter",				Set_ResetStatCounter_Proc},
-	{"PSMode",                      Set_PSMode_Proc},
-#ifdef DBG
-	{"Debug",						Set_Debug_Proc},
-#endif
-
-#ifdef RALINK_ATE
-	{"ATE",							Set_ATE_Proc},
-	{"ATEDA",						Set_ATE_DA_Proc},
-	{"ATESA",						Set_ATE_SA_Proc},
-	{"ATEBSSID",					Set_ATE_BSSID_Proc},
-	{"ATECHANNEL",					Set_ATE_CHANNEL_Proc},
-	{"ATETXPOW0",					Set_ATE_TX_POWER0_Proc},
-	{"ATETXPOW1",					Set_ATE_TX_POWER1_Proc},
-	{"ATETXANT",					Set_ATE_TX_Antenna_Proc},
-	{"ATERXANT",					Set_ATE_RX_Antenna_Proc},
-	{"ATETXFREQOFFSET",				Set_ATE_TX_FREQOFFSET_Proc},
-	{"ATETXBW",						Set_ATE_TX_BW_Proc},
-	{"ATETXLEN",					Set_ATE_TX_LENGTH_Proc},
-	{"ATETXCNT",					Set_ATE_TX_COUNT_Proc},
-	{"ATETXMCS",					Set_ATE_TX_MCS_Proc},
-	{"ATETXMODE",					Set_ATE_TX_MODE_Proc},
-	{"ATETXGI",						Set_ATE_TX_GI_Proc},
-	{"ATERXFER",					Set_ATE_RX_FER_Proc},
-	{"ATERRF",						Set_ATE_Read_RF_Proc},
-	{"ATEWRF1",						Set_ATE_Write_RF1_Proc},
-	{"ATEWRF2",						Set_ATE_Write_RF2_Proc},
-	{"ATEWRF3",						Set_ATE_Write_RF3_Proc},
-	{"ATEWRF4",						Set_ATE_Write_RF4_Proc},
-	{"ATELDE2P",				    Set_ATE_Load_E2P_Proc},
-	{"ATERE2P",						Set_ATE_Read_E2P_Proc},
-	{"ATESHOW",						Set_ATE_Show_Proc},
-	{"ATEHELP",						Set_ATE_Help_Proc},
-
-#ifdef RALINK_28xx_QA
-	{"TxStop",						Set_TxStop_Proc},
-	{"RxStop",						Set_RxStop_Proc},
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-    {"WpaSupport",                  Set_Wpa_Support},
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-
-	{"FixedTxMode",                 Set_FixedTxMode_Proc},
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	{"OpMode",						Set_OpMode_Proc},
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-#ifdef DOT11_N_SUPPORT
-    {"TGnWifiTest",                 Set_TGnWifiTest_Proc},
-    {"ForceGF",		        		Set_ForceGF_Proc},
-#endif // DOT11_N_SUPPORT //
-#ifdef QOS_DLS_SUPPORT
-	{"DlsAddEntry",					Set_DlsAddEntry_Proc},
-	{"DlsTearDownEntry",			Set_DlsTearDownEntry_Proc},
-#endif // QOS_DLS_SUPPORT //
-	{"LongRetry",	        		Set_LongRetryLimit_Proc},
-	{"ShortRetry",	        		Set_ShortRetryLimit_Proc},
-#ifdef EXT_BUILD_CHANNEL_LIST
-	{"11dClientMode",				Set_Ieee80211dClientMode_Proc},
-#endif // EXT_BUILD_CHANNEL_LIST //
-#ifdef CARRIER_DETECTION_SUPPORT
-	{"CarrierDetect",				Set_CarrierDetect_Proc},
-#endif // CARRIER_DETECTION_SUPPORT //
-
-	{NULL,}
-};
-
-
-VOID RTMPAddKey(
-	IN	PRTMP_ADAPTER	    pAd,
-	IN	PNDIS_802_11_KEY    pKey)
-{
-	ULONG				KeyIdx;
-	MAC_TABLE_ENTRY  	*pEntry;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("RTMPAddKey ------>\n"));
-
-	if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-	{
-		if (pKey->KeyIndex & 0x80000000)
-		{
-		    if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-            {
-                NdisZeroMemory(pAd->StaCfg.PMK, 32);
-                NdisMoveMemory(pAd->StaCfg.PMK, pKey->KeyMaterial, pKey->KeyLength);
-                goto end;
-            }
-		    // Update PTK
-		    NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-            pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-            NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, pKey->KeyMaterial, LEN_TKIP_EK);
-#ifdef WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-            {
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-            else
-#endif // WPA_SUPPLICANT_SUPPORT //
-            {
-            	NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-
-            // Decide its ChiperAlg
-        	if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-        	else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-        	else
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_NONE;
-
-            // Update these related information to MAC_TABLE_ENTRY
-        	pEntry = &pAd->MacTab.Content[BSSID_WCID];
-            NdisMoveMemory(pEntry->PairwiseKey.Key, pAd->SharedKey[BSS0][0].Key, LEN_TKIP_EK);
-        	NdisMoveMemory(pEntry->PairwiseKey.RxMic, pAd->SharedKey[BSS0][0].RxMic, LEN_TKIP_RXMICK);
-        	NdisMoveMemory(pEntry->PairwiseKey.TxMic, pAd->SharedKey[BSS0][0].TxMic, LEN_TKIP_TXMICK);
-        	pEntry->PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-
-        	// Update pairwise key information to ASIC Shared Key Table
-        	AsicAddSharedKeyEntry(pAd,
-        						  BSS0,
-        						  0,
-        						  pAd->SharedKey[BSS0][0].CipherAlg,
-        						  pAd->SharedKey[BSS0][0].Key,
-        						  pAd->SharedKey[BSS0][0].TxMic,
-        						  pAd->SharedKey[BSS0][0].RxMic);
-
-        	// Update ASIC WCID attribute table and IVEIV table
-        	RTMPAddWcidAttributeEntry(pAd,
-        							  BSS0,
-        							  0,
-        							  pAd->SharedKey[BSS0][0].CipherAlg,
-        							  pEntry);
-
-            if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-            {
-                // set 802.1x port control
-	            //pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAd);
-
-                // Indicate Connected for GUI
-                pAd->IndicateMediaState = NdisMediaStateConnected;
-            }
-		}
-        else
-        {
-            // Update GTK
-            pAd->StaCfg.DefaultKeyId = (pKey->KeyIndex & 0xFF);
-            NdisZeroMemory(&pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId], sizeof(CIPHER_KEY));
-            pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].KeyLen = LEN_TKIP_EK;
-            NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, pKey->KeyMaterial, LEN_TKIP_EK);
-#ifdef WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-            {
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-            else
-#endif // WPA_SUPPLICANT_SUPPORT //
-            {
-            	NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-
-            // Update Shared Key CipherAlg
-    		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_NONE;
-    		if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-    			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_TKIP;
-    		else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
-    			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_AES;
-
-            // Update group key information to ASIC Shared Key Table
-        	AsicAddSharedKeyEntry(pAd,
-        						  BSS0,
-        						  pAd->StaCfg.DefaultKeyId,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic);
-
-        	// Update ASIC WCID attribute table and IVEIV table
-        	RTMPAddWcidAttributeEntry(pAd,
-        							  BSS0,
-        							  pAd->StaCfg.DefaultKeyId,
-        							  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-        							  NULL);
-
-            // set 802.1x port control
-	        //pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-			STA_PORT_SECURED(pAd);
-
-            // Indicate Connected for GUI
-            pAd->IndicateMediaState = NdisMediaStateConnected;
-        }
-	}
-	else	// dynamic WEP from wpa_supplicant
-	{
-		UCHAR	CipherAlg;
-    	PUCHAR	Key;
-
-		if(pKey->KeyLength == 32)
-			goto end;
-
-		KeyIdx = pKey->KeyIndex & 0x0fffffff;
-
-		if (KeyIdx < 4)
-		{
-			// it is a default shared key, for Pairwise key setting
-			if (pKey->KeyIndex & 0x80000000)
-			{
-				pEntry = MacTableLookup(pAd, pKey->BSSID);
-
-				if (pEntry)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("RTMPAddKey: Set Pair-wise Key\n"));
-
-					// set key material and key length
- 					pEntry->PairwiseKey.KeyLen = (UCHAR)pKey->KeyLength;
-					NdisMoveMemory(pEntry->PairwiseKey.Key, &pKey->KeyMaterial, pKey->KeyLength);
-
-					// set Cipher type
-					if (pKey->KeyLength == 5)
-						pEntry->PairwiseKey.CipherAlg = CIPHER_WEP64;
-					else
-						pEntry->PairwiseKey.CipherAlg = CIPHER_WEP128;
-
-					// Add Pair-wise key to Asic
-					AsicAddPairwiseKeyEntry(
-						pAd,
-						pEntry->Addr,
-						(UCHAR)pEntry->Aid,
-                		&pEntry->PairwiseKey);
-
-					// update WCID attribute table and IVEIV table for this entry
-					RTMPAddWcidAttributeEntry(
-						pAd,
-						BSS0,
-						KeyIdx, // The value may be not zero
-						pEntry->PairwiseKey.CipherAlg,
-						pEntry);
-
-				}
-			}
-			else
-            {
-				// Default key for tx (shared key)
-				pAd->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-
-				// set key material and key length
-				pAd->SharedKey[BSS0][KeyIdx].KeyLen = (UCHAR) pKey->KeyLength;
-				NdisMoveMemory(pAd->SharedKey[BSS0][KeyIdx].Key, &pKey->KeyMaterial, pKey->KeyLength);
-
-				// Set Ciper type
-				if (pKey->KeyLength == 5)
-					pAd->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_WEP64;
-				else
-					pAd->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_WEP128;
-
-    			CipherAlg = pAd->SharedKey[BSS0][KeyIdx].CipherAlg;
-    			Key = pAd->SharedKey[BSS0][KeyIdx].Key;
-
-				// Set Group key material to Asic
-    			AsicAddSharedKeyEntry(pAd, BSS0, KeyIdx, CipherAlg, Key, NULL, NULL);
-
-				// Update WCID attribute table and IVEIV table for this group key table
-				RTMPAddWcidAttributeEntry(pAd, BSS0, KeyIdx, CipherAlg, NULL);
-
-			}
-		}
-	}
-end:
-	return;
-}
-
-char * rtstrchr(const char * s, int c)
-{
-    for(; *s != (char) c; ++s)
-        if (*s == '\0')
-            return NULL;
-    return (char *) s;
-}
-
-/*
-This is required for LinEX2004/kernel2.6.7 to provide iwlist scanning function
-*/
-
-int
-rt_ioctl_giwname(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-//	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-#ifdef RT2870
-	strncpy(name, "RT2870 Wireless", IFNAMSIZ);
-#endif // RT2870 //
-	return 0;
-}
-
-int rt_ioctl_siwfreq(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_freq *freq, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-	int 	chan = -1;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-
-	if (freq->e > 1)
-		return -EINVAL;
-
-	if((freq->e == 0) && (freq->m <= 1000))
-		chan = freq->m;	// Setting by channel number
-	else
-		MAP_KHZ_TO_CHANNEL_ID( (freq->m /100) , chan); // Setting by frequency - search the table , like 2.412G, 2.422G,
-
-    if (ChannelSanity(pAdapter, chan) == TRUE)
-    {
-	pAdapter->CommonCfg.Channel = chan;
-	DBGPRINT(RT_DEBUG_ERROR, ("==>rt_ioctl_siwfreq::SIOCSIWFREQ[cmd=0x%x] (Channel=%d)\n", SIOCSIWFREQ, pAdapter->CommonCfg.Channel));
-    }
-    else
-        return -EINVAL;
-
-	return 0;
-}
-int rt_ioctl_giwfreq(struct net_device *dev,
-		   struct iw_request_info *info,
-		   struct iw_freq *freq, char *extra)
-{
-    VIRTUAL_ADAPTER *pVirtualAd = NULL;
-	PRTMP_ADAPTER pAdapter = NULL;
-	UCHAR ch;
-	ULONG	m;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-		ch = pAdapter->CommonCfg.Channel;
-
-	DBGPRINT(RT_DEBUG_TRACE,("==>rt_ioctl_giwfreq  %d\n", ch));
-
-    MAP_CHANNEL_ID_TO_KHZ(ch, m);
-	freq->m = m * 100;
-	freq->e = 1;
-	return 0;
-}
-
-int rt_ioctl_siwmode(struct net_device *dev,
-		   struct iw_request_info *info,
-		   __u32 *mode, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-    	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	switch (*mode)
-	{
-		case IW_MODE_ADHOC:
-			Set_NetworkType_Proc(pAdapter, "Adhoc");
-			break;
-		case IW_MODE_INFRA:
-			Set_NetworkType_Proc(pAdapter, "Infra");
-			break;
-#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20))
-        case IW_MODE_MONITOR:
-			Set_NetworkType_Proc(pAdapter, "Monitor");
-			break;
-#endif
-		default:
-			DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_siwmode::SIOCSIWMODE (unknown %d)\n", *mode));
-			return -EINVAL;
-	}
-
-	// Reset Ralink supplicant to not use, it will be set to start when UI set PMK key
-	pAdapter->StaCfg.WpaState = SS_NOTUSE;
-
-	return 0;
-}
-
-int rt_ioctl_giwmode(struct net_device *dev,
-		   struct iw_request_info *info,
-		   __u32 *mode, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	if (ADHOC_ON(pAdapter))
-		*mode = IW_MODE_ADHOC;
-    else if (INFRA_ON(pAdapter))
-		*mode = IW_MODE_INFRA;
-#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20))
-    else if (MONITOR_ON(pAdapter))
-    {
-        *mode = IW_MODE_MONITOR;
-    }
-#endif
-    else
-        *mode = IW_MODE_AUTO;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==>rt_ioctl_giwmode(mode=%d)\n", *mode));
-	return 0;
-}
-
-int rt_ioctl_siwsens(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-        	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	return 0;
-}
-
-int rt_ioctl_giwsens(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-	return 0;
-}
-
-int rt_ioctl_giwrange(struct net_device *dev,
-		   struct iw_request_info *info,
-		   struct iw_point *data, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-	struct iw_range *range = (struct iw_range *) extra;
-	u16 val;
-	int i;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===>rt_ioctl_giwrange\n"));
-	data->length = sizeof(struct iw_range);
-	memset(range, 0, sizeof(struct iw_range));
-
-	range->txpower_capa = IW_TXPOW_DBM;
-
-	if (INFRA_ON(pAdapter)||ADHOC_ON(pAdapter))
-	{
-		range->min_pmp = 1 * 1024;
-		range->max_pmp = 65535 * 1024;
-		range->min_pmt = 1 * 1024;
-		range->max_pmt = 1000 * 1024;
-		range->pmp_flags = IW_POWER_PERIOD;
-		range->pmt_flags = IW_POWER_TIMEOUT;
-		range->pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT |
-			IW_POWER_UNICAST_R | IW_POWER_ALL_R;
-	}
-
-	range->we_version_compiled = WIRELESS_EXT;
-	range->we_version_source = 14;
-
-	range->retry_capa = IW_RETRY_LIMIT;
-	range->retry_flags = IW_RETRY_LIMIT;
-	range->min_retry = 0;
-	range->max_retry = 255;
-
-	range->num_channels =  pAdapter->ChannelListNum;
-
-	val = 0;
-	for (i = 1; i <= range->num_channels; i++)
-	{
-		u32 m;
-		range->freq[val].i = pAdapter->ChannelList[i-1].Channel;
-		MAP_CHANNEL_ID_TO_KHZ(pAdapter->ChannelList[i-1].Channel, m);
-		range->freq[val].m = m * 100; /* HZ */
-
-		range->freq[val].e = 1;
-		val++;
-		if (val == IW_MAX_FREQUENCIES)
-			break;
-	}
-	range->num_frequency = val;
-
-	range->max_qual.qual = 100; /* what is correct max? This was not
-					* documented exactly. At least
-					* 69 has been observed. */
-	range->max_qual.level = 0; /* dB */
-	range->max_qual.noise = 0; /* dB */
-
-	/* What would be suitable values for "average/typical" qual? */
-	range->avg_qual.qual = 20;
-	range->avg_qual.level = -60;
-	range->avg_qual.noise = -95;
-	range->sensitivity = 3;
-
-	range->max_encoding_tokens = NR_WEP_KEYS;
-	range->num_encoding_sizes = 2;
-	range->encoding_size[0] = 5;
-	range->encoding_size[1] = 13;
-
-	range->min_rts = 0;
-	range->max_rts = 2347;
-	range->min_frag = 256;
-	range->max_frag = 2346;
-
-#if WIRELESS_EXT > 17
-	/* IW_ENC_CAPA_* bit field */
-	range->enc_capa = IW_ENC_CAPA_WPA | IW_ENC_CAPA_WPA2 |
-					IW_ENC_CAPA_CIPHER_TKIP | IW_ENC_CAPA_CIPHER_CCMP;
-#endif
-
-	return 0;
-}
-
-int rt_ioctl_siwap(struct net_device *dev,
-		      struct iw_request_info *info,
-		      struct sockaddr *ap_addr, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-    NDIS_802_11_MAC_ADDRESS Bssid;
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-    {
-        RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-        DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-    }
-
-    // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-    // this request, because this request is initiated by NDIS.
-    pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-	// Prevent to connect AP again in STAMlmePeriodicExec
-	pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-
-    memset(Bssid, 0, MAC_ADDR_LEN);
-    memcpy(Bssid, ap_addr->sa_data, MAC_ADDR_LEN);
-    MlmeEnqueue(pAdapter,
-                MLME_CNTL_STATE_MACHINE,
-                OID_802_11_BSSID,
-                sizeof(NDIS_802_11_MAC_ADDRESS),
-                (VOID *)&Bssid);
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCSIWAP %02x:%02x:%02x:%02x:%02x:%02x\n",
-        Bssid[0], Bssid[1], Bssid[2], Bssid[3], Bssid[4], Bssid[5]));
-
-	return 0;
-}
-
-int rt_ioctl_giwap(struct net_device *dev,
-		      struct iw_request_info *info,
-		      struct sockaddr *ap_addr, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-	{
-		ap_addr->sa_family = ARPHRD_ETHER;
-		memcpy(ap_addr->sa_data, &pAdapter->CommonCfg.Bssid, ETH_ALEN);
-	}
-#ifdef WPA_SUPPLICANT_SUPPORT
-    // Add for RT2870
-    else if (pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-    {
-        ap_addr->sa_family = ARPHRD_ETHER;
-        memcpy(ap_addr->sa_data, &pAdapter->MlmeAux.Bssid, ETH_ALEN);
-    }
-#endif // WPA_SUPPLICANT_SUPPORT //
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCGIWAP(=EMPTY)\n"));
-		return -ENOTCONN;
-	}
-
-	return 0;
-}
-
-/*
- * Units are in db above the noise floor. That means the
- * rssi values reported in the tx/rx descriptors in the
- * driver are the SNR expressed in db.
- *
- * If you assume that the noise floor is -95, which is an
- * excellent assumption 99.5 % of the time, then you can
- * derive the absolute signal level (i.e. -95 + rssi).
- * There are some other slight factors to take into account
- * depending on whether the rssi measurement is from 11b,
- * 11g, or 11a.   These differences are at most 2db and
- * can be documented.
- *
- * NB: various calculations are based on the orinoco/wavelan
- *     drivers for compatibility
- */
-static void set_quality(PRTMP_ADAPTER pAdapter,
-                        struct iw_quality *iq,
-                        signed char rssi)
-{
-	__u8 ChannelQuality;
-
-	// Normalize Rssi
-	if (rssi >= -50)
-		ChannelQuality = 100;
-	else if (rssi >= -80) // between -50 ~ -80dbm
-		ChannelQuality = (__u8)(24 + ((rssi + 80) * 26)/10);
-	else if (rssi >= -90)   // between -80 ~ -90dbm
-        ChannelQuality = (__u8)((rssi + 90) * 26)/10;
-	else
-		ChannelQuality = 0;
-
-    iq->qual = (__u8)ChannelQuality;
-
-    iq->level = (__u8)(rssi);
-    iq->noise = (pAdapter->BbpWriteLatch[66] > pAdapter->BbpTuning.FalseCcaUpperThreshold) ? ((__u8)pAdapter->BbpTuning.FalseCcaUpperThreshold) : ((__u8) pAdapter->BbpWriteLatch[66]); 	// noise level (dBm)
-    iq->noise += 256 - 143;
-    iq->updated = pAdapter->iw_stats.qual.updated;
-}
-
-int rt_ioctl_iwaplist(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
- 	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	struct sockaddr addr[IW_MAX_AP];
-	struct iw_quality qual[IW_MAX_AP];
-	int i;
-
-   	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		data->length = 0;
-		return 0;
-        //return -ENETDOWN;
-	}
-
-	for (i = 0; i <IW_MAX_AP ; i++)
-	{
-		if (i >=  pAdapter->ScanTab.BssNr)
-			break;
-		addr[i].sa_family = ARPHRD_ETHER;
-			memcpy(addr[i].sa_data, &pAdapter->ScanTab.BssEntry[i].Bssid, MAC_ADDR_LEN);
-		set_quality(pAdapter, &qual[i], pAdapter->ScanTab.BssEntry[i].Rssi);
-	}
-	data->length = i;
-	memcpy(extra, &addr, i*sizeof(addr[0]));
-	data->flags = 1;		/* signal quality present (sort of) */
-	memcpy(extra + i*sizeof(addr[0]), &qual, i*sizeof(qual[i]));
-
-	return 0;
-}
-
-#ifdef SIOCGIWSCAN
-int rt_ioctl_siwscan(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	ULONG								Now;
-	int Status = NDIS_STATUS_SUCCESS;
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		return -ENETDOWN;
-	}
-
-	if (MONITOR_ON(pAdapter))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is in Monitor Mode now !!!\n"));
-        return -EINVAL;
-    }
-
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-	if (pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-		pAdapter->StaCfg.WpaSupplicantScanCount++;
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-    pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-		return 0;
-	do{
-		Now = jiffies;
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-		if ((pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE) &&
-			(pAdapter->StaCfg.WpaSupplicantScanCount > 3))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! WpaSupplicantScanCount > 3\n"));
-			Status = NDIS_STATUS_SUCCESS;
-			break;
-		}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-		if ((OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED)) &&
-			((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-			(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)) &&
-			(pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, Port Not Secured! ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-			Status = NDIS_STATUS_SUCCESS;
-			break;
-		}
-
-		if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-		{
-			RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-		}
-
-		// tell CNTL state machine to call NdisMSetInformationComplete() after completing
-		// this request, because this request is initiated by NDIS.
-		pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-		// Reset allowed scan retries
-		pAdapter->StaCfg.ScanCnt = 0;
-		pAdapter->StaCfg.LastScanTime = Now;
-
-		MlmeEnqueue(pAdapter,
-			MLME_CNTL_STATE_MACHINE,
-			OID_802_11_BSSID_LIST_SCAN,
-			0,
-			NULL);
-
-		Status = NDIS_STATUS_SUCCESS;
-		RT28XX_MLME_HANDLER(pAdapter);
-	}while(0);
-	return 0;
-}
-
-int rt_ioctl_giwscan(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
-
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-	int i=0;
-	char *current_ev = extra, *previous_ev = extra;
-	char *end_buf;
-	char *current_val, custom[MAX_CUSTOM_LEN] = {0};
-#ifndef IWEVGENIE
-	char idx;
-#endif // IWEVGENIE //
-	struct iw_event iwe;
-
-	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-    {
-		/*
-		 * Still scanning, indicate the caller should try again.
-		 */
-		return -EAGAIN;
-	}
-
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-	if (pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-		pAdapter->StaCfg.WpaSupplicantScanCount = 0;
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-	if (pAdapter->ScanTab.BssNr == 0)
-	{
-		data->length = 0;
-		return 0;
-	}
-
-#if WIRELESS_EXT >= 17
-    if (data->length > 0)
-        end_buf = extra + data->length;
-    else
-        end_buf = extra + IW_SCAN_MAX_DATA;
-#else
-    end_buf = extra + IW_SCAN_MAX_DATA;
-#endif
-
-	for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-	{
-		if (current_ev >= end_buf)
-        {
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-        }
-
-		//MAC address
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWAP;
-		iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
-				memcpy(iwe.u.ap_addr.sa_data, &pAdapter->ScanTab.BssEntry[i].Bssid, ETH_ALEN);
-
-        previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev,end_buf, &iwe, IW_EV_ADDR_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//ESSID
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWESSID;
-		iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].SsidLen;
-		iwe.u.data.flags = 1;
-
-        previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_POINT(info, current_ev,end_buf, &iwe, pAdapter->ScanTab.BssEntry[i].Ssid);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Network Type
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWMODE;
-		if (pAdapter->ScanTab.BssEntry[i].BssType == Ndis802_11IBSS)
-		{
-			iwe.u.mode = IW_MODE_ADHOC;
-		}
-		else if (pAdapter->ScanTab.BssEntry[i].BssType == Ndis802_11Infrastructure)
-		{
-			iwe.u.mode = IW_MODE_INFRA;
-		}
-		else
-		{
-			iwe.u.mode = IW_MODE_AUTO;
-		}
-		iwe.len = IW_EV_UINT_LEN;
-
-        previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev, end_buf, &iwe,  IW_EV_UINT_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Channel and Frequency
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWFREQ;
-		if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-			iwe.u.freq.m = pAdapter->ScanTab.BssEntry[i].Channel;
-		else
-			iwe.u.freq.m = pAdapter->ScanTab.BssEntry[i].Channel;
-		iwe.u.freq.e = 0;
-		iwe.u.freq.i = 0;
-
-		previous_ev = current_ev;
-		current_ev = IWE_STREAM_ADD_EVENT(info, current_ev,end_buf, &iwe, IW_EV_FREQ_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-        //Add quality statistics
-        //================================
-        memset(&iwe, 0, sizeof(iwe));
-    	iwe.cmd = IWEVQUAL;
-    	iwe.u.qual.level = 0;
-    	iwe.u.qual.noise = 0;
-        set_quality(pAdapter, &iwe.u.qual, pAdapter->ScanTab.BssEntry[i].Rssi);
-    	current_ev = IWE_STREAM_ADD_EVENT(info, current_ev, end_buf, &iwe, IW_EV_QUAL_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Encyption key
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWENCODE;
-		if (CAP_IS_PRIVACY_ON (pAdapter->ScanTab.BssEntry[i].CapabilityInfo ))
-			iwe.u.data.flags =IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
-		else
-			iwe.u.data.flags = IW_ENCODE_DISABLED;
-
-        previous_ev = current_ev;
-        current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf,&iwe, (char *)pAdapter->SharedKey[BSS0][(iwe.u.data.flags & IW_ENCODE_INDEX)-1].Key);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Bit Rate
-		//================================
-		if (pAdapter->ScanTab.BssEntry[i].SupRateLen)
-        {
-            UCHAR tmpRate = pAdapter->ScanTab.BssEntry[i].SupRate[pAdapter->ScanTab.BssEntry[i].SupRateLen-1];
-			memset(&iwe, 0, sizeof(iwe));
-			iwe.cmd = SIOCGIWRATE;
-    		current_val = current_ev + IW_EV_LCP_LEN;
-            if (tmpRate == 0x82)
-                iwe.u.bitrate.value =  1 * 1000000;
-            else if (tmpRate == 0x84)
-                iwe.u.bitrate.value =  2 * 1000000;
-            else if (tmpRate == 0x8B)
-                iwe.u.bitrate.value =  5.5 * 1000000;
-            else if (tmpRate == 0x96)
-                iwe.u.bitrate.value =  11 * 1000000;
-            else
-    		    iwe.u.bitrate.value =  (tmpRate/2) * 1000000;
-
-			iwe.u.bitrate.disabled = 0;
-			current_val = IWE_STREAM_ADD_VALUE(info, current_ev,
-				current_val, end_buf, &iwe,
-    			IW_EV_PARAM_LEN);
-
-        	if((current_val-current_ev)>IW_EV_LCP_LEN)
-            	current_ev = current_val;
-        	else
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-
-#ifdef IWEVGENIE
-		//WPA IE
-		if (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen > 0)
-		{
-			memset(&iwe, 0, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-			memcpy(custom, &(pAdapter->ScanTab.BssEntry[i].WpaIE.IE[0]),
-						   pAdapter->ScanTab.BssEntry[i].WpaIE.IELen);
-			iwe.cmd = IWEVGENIE;
-			iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].WpaIE.IELen;
-			current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe, custom);
-			if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-		}
-
-		//WPA2 IE
-        if (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen > 0)
-        {
-        	memset(&iwe, 0, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-			memcpy(custom, &(pAdapter->ScanTab.BssEntry[i].RsnIE.IE[0]),
-						   pAdapter->ScanTab.BssEntry[i].RsnIE.IELen);
-			iwe.cmd = IWEVGENIE;
-			iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].RsnIE.IELen;
-			current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe, custom);
-			if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-#else
-        //WPA IE
-		//================================
-        if (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen > 0)
-        {
-    		NdisZeroMemory(&iwe, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-    		iwe.cmd = IWEVCUSTOM;
-            iwe.u.data.length = (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen * 2) + 7;
-            NdisMoveMemory(custom, "wpa_ie=", 7);
-            for (idx = 0; idx < pAdapter->ScanTab.BssEntry[i].WpaIE.IELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAdapter->ScanTab.BssEntry[i].WpaIE.IE[idx]);
-            previous_ev = current_ev;
-    		current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe,  custom);
-            if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-
-        //WPA2 IE
-        if (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen > 0)
-        {
-    		NdisZeroMemory(&iwe, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-    		iwe.cmd = IWEVCUSTOM;
-            iwe.u.data.length = (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen * 2) + 7;
-            NdisMoveMemory(custom, "rsn_ie=", 7);
-			for (idx = 0; idx < pAdapter->ScanTab.BssEntry[i].RsnIE.IELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAdapter->ScanTab.BssEntry[i].RsnIE.IE[idx]);
-            previous_ev = current_ev;
-    		current_ev = IWE_STREAM_ADD_POINT(info, current_ev, end_buf, &iwe,  custom);
-            if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-#endif // IWEVGENIE //
-	}
-
-	data->length = current_ev - extra;
-    pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-	DBGPRINT(RT_DEBUG_ERROR ,("===>rt_ioctl_giwscan. %d(%d) BSS returned, data->length = %d\n",i , pAdapter->ScanTab.BssNr, data->length));
-	return 0;
-}
-#endif
-
-int rt_ioctl_siwessid(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *essid)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	if (data->flags)
-	{
-		PCHAR	pSsidString = NULL;
-
-		// Includes null character.
-		if (data->length > (IW_ESSID_MAX_SIZE + 1))
-			return -E2BIG;
-
-		pSsidString = (CHAR *) kmalloc(MAX_LEN_OF_SSID+1, MEM_ALLOC_FLAG);
-		if (pSsidString)
-		{
-			NdisZeroMemory(pSsidString, MAX_LEN_OF_SSID+1);
-			NdisMoveMemory(pSsidString, essid, data->length);
-			if (Set_SSID_Proc(pAdapter, pSsidString) == FALSE)
-				return -EINVAL;
-		}
-		else
-			return -ENOMEM;
-	}
-	else
-	{
-		// ANY ssid
-		if (Set_SSID_Proc(pAdapter, "") == FALSE)
-			return -EINVAL;
-    }
-	return 0;
-}
-
-int rt_ioctl_giwessid(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *essid)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	data->flags = 1;
-    if (MONITOR_ON(pAdapter))
-    {
-        data->length  = 0;
-        return 0;
-    }
-
-	if (OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED))
-	{
-		DBGPRINT(RT_DEBUG_TRACE ,("MediaState is connected\n"));
-		data->length = pAdapter->CommonCfg.SsidLen;
-		memcpy(essid, pAdapter->CommonCfg.Ssid, pAdapter->CommonCfg.SsidLen);
-	}
-#ifdef RT2870
-#ifdef WPA_SUPPLICANT_SUPPORT
-    // Add for RT2870
-    else if (pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-    {
-        data->length = pAdapter->CommonCfg.SsidLen;
-		memcpy(essid, pAdapter->CommonCfg.Ssid, pAdapter->CommonCfg.SsidLen);
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-#endif // RT2870 //
-	else
-	{//the ANY ssid was specified
-		data->length  = 0;
-		DBGPRINT(RT_DEBUG_TRACE ,("MediaState is not connected, ess\n"));
-	}
-
-	return 0;
-
-}
-
-int rt_ioctl_siwnickn(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *nickname)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE ,("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-	if (data->length > IW_ESSID_MAX_SIZE)
-		return -EINVAL;
-
-	memset(pAdapter->nickname, 0, IW_ESSID_MAX_SIZE + 1);
-	memcpy(pAdapter->nickname, nickname, data->length);
-
-
-	return 0;
-}
-
-int rt_ioctl_giwnickn(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *nickname)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	if (data->length > strlen(pAdapter->nickname) + 1)
-		data->length = strlen(pAdapter->nickname) + 1;
-	if (data->length > 0) {
-		memcpy(nickname, pAdapter->nickname, data->length-1);
-		nickname[data->length-1] = '\0';
-	}
-	return 0;
-}
-
-int rt_ioctl_siwrts(struct net_device *dev,
-		       struct iw_request_info *info,
-		       struct iw_param *rts, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-	u16 val;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-	if (rts->disabled)
-		val = MAX_RTS_THRESHOLD;
-	else if (rts->value < 0 || rts->value > MAX_RTS_THRESHOLD)
-		return -EINVAL;
-	else if (rts->value == 0)
-	    val = MAX_RTS_THRESHOLD;
-	else
-		val = rts->value;
-
-	if (val != pAdapter->CommonCfg.RtsThreshold)
-		pAdapter->CommonCfg.RtsThreshold = val;
-
-	return 0;
-}
-
-int rt_ioctl_giwrts(struct net_device *dev,
-		       struct iw_request_info *info,
-		       struct iw_param *rts, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-	rts->value = pAdapter->CommonCfg.RtsThreshold;
-	rts->disabled = (rts->value == MAX_RTS_THRESHOLD);
-	rts->fixed = 1;
-
-	return 0;
-}
-
-int rt_ioctl_siwfrag(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_param *frag, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-	u16 val;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	if (frag->disabled)
-		val = MAX_FRAG_THRESHOLD;
-	else if (frag->value >= MIN_FRAG_THRESHOLD || frag->value <= MAX_FRAG_THRESHOLD)
-        val = __cpu_to_le16(frag->value & ~0x1); /* even numbers only */
-	else if (frag->value == 0)
-	    val = MAX_FRAG_THRESHOLD;
-	else
-		return -EINVAL;
-
-	pAdapter->CommonCfg.FragmentThreshold = val;
-	return 0;
-}
-
-int rt_ioctl_giwfrag(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_param *frag, char *extra)
-{
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-	frag->value = pAdapter->CommonCfg.FragmentThreshold;
-	frag->disabled = (frag->value == MAX_FRAG_THRESHOLD);
-	frag->fixed = 1;
-
-	return 0;
-}
-
-#define MAX_WEP_KEY_SIZE 13
-#define MIN_WEP_KEY_SIZE 5
-int rt_ioctl_siwencode(struct net_device *dev,
-			  struct iw_request_info *info,
-			  struct iw_point *erq, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	if ((erq->length == 0) &&
-        (erq->flags & IW_ENCODE_DISABLED))
-	{
-		pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-		pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-		pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-        pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-        goto done;
-	}
-	else if ((erq->length == 0) &&
-             (erq->flags & IW_ENCODE_RESTRICTED || erq->flags & IW_ENCODE_OPEN))
-	{
-	    //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-		STA_PORT_SECURED(pAdapter);
-		pAdapter->StaCfg.PairCipher = Ndis802_11WEPEnabled;
-		pAdapter->StaCfg.GroupCipher = Ndis802_11WEPEnabled;
-		pAdapter->StaCfg.WepStatus = Ndis802_11WEPEnabled;
-        pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-		if (erq->flags & IW_ENCODE_RESTRICTED)
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-    	else
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-        goto done;
-	}
-
-    if (erq->length > 0)
-	{
-		int keyIdx = (erq->flags & IW_ENCODE_INDEX) - 1;
-		/* Check the size of the key */
-		if (erq->length > MAX_WEP_KEY_SIZE) {
-			return -EINVAL;
-		}
-		/* Check key index */
-		if ((keyIdx < 0) || (keyIdx >= NR_WEP_KEYS))
-        {
-            DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::Wrong keyIdx=%d! Using default key instead (%d)\n",
-                                        keyIdx, pAdapter->StaCfg.DefaultKeyId));
-
-            //Using default key
-			keyIdx = pAdapter->StaCfg.DefaultKeyId;
-        }
-
-        NdisZeroMemory(pAdapter->SharedKey[BSS0][keyIdx].Key,  16);
-
-		if (erq->length == MAX_WEP_KEY_SIZE)
-        {
-			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MAX_WEP_KEY_SIZE;
-            pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP128;
-		}
-		else if (erq->length == MIN_WEP_KEY_SIZE)
-        {
-            pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MIN_WEP_KEY_SIZE;
-            pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP64;
-		}
-		else
-			/* Disable the key */
-			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = 0;
-
-		/* Check if the key is not marked as invalid */
-		if(!(erq->flags & IW_ENCODE_NOKEY)) {
-			/* Copy the key in the driver */
-			NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, extra, erq->length);
-        }
-	}
-    else
-			{
-		/* Do we want to just set the transmit key index ? */
-		int index = (erq->flags & IW_ENCODE_INDEX) - 1;
-		if ((index >= 0) && (index < 4))
-        {
-			pAdapter->StaCfg.DefaultKeyId = index;
-            }
-        else
-			/* Don't complain if only change the mode */
-			if(!erq->flags & IW_ENCODE_MODE) {
-				return -EINVAL;
-		}
-	}
-
-done:
-    DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::erq->flags=%x\n",erq->flags));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::AuthMode=%x\n",pAdapter->StaCfg.AuthMode));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::DefaultKeyId=%x, KeyLen = %d\n",pAdapter->StaCfg.DefaultKeyId , pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::WepStatus=%x\n",pAdapter->StaCfg.WepStatus));
-	return 0;
-}
-
-int
-rt_ioctl_giwencode(struct net_device *dev,
-			  struct iw_request_info *info,
-			  struct iw_point *erq, char *key)
-{
-	int kid;
-	PRTMP_ADAPTER 	pAdapter = NULL;
-	VIRTUAL_ADAPTER *pVirtualAd = NULL;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		if (pVirtualAd && pVirtualAd->RtmpDev)
-			pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-	kid = erq->flags & IW_ENCODE_INDEX;
-	DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_giwencode %d\n", erq->flags & IW_ENCODE_INDEX));
-
-	if (pAdapter->StaCfg.WepStatus == Ndis802_11WEPDisabled)
-	{
-		erq->length = 0;
-		erq->flags = IW_ENCODE_DISABLED;
-	}
-	else if ((kid > 0) && (kid <=4))
-	{
-		// copy wep key
-		erq->flags = kid ;			/* NB: base 1 */
-		if (erq->length > pAdapter->SharedKey[BSS0][kid-1].KeyLen)
-			erq->length = pAdapter->SharedKey[BSS0][kid-1].KeyLen;
-		memcpy(key, pAdapter->SharedKey[BSS0][kid-1].Key, erq->length);
-		//if ((kid == pAdapter->PortCfg.DefaultKeyId))
-		//erq->flags |= IW_ENCODE_ENABLED;	/* XXX */
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-
-	}
-	else if (kid == 0)
-	{
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-		erq->length = pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen;
-		memcpy(key, pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key, erq->length);
-		// copy default key ID
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-		erq->flags = pAdapter->StaCfg.DefaultKeyId + 1;			/* NB: base 1 */
-		erq->flags |= IW_ENCODE_ENABLED;	/* XXX */
-	}
-
-	return 0;
-
-}
-
-static int
-rt_ioctl_setparam(struct net_device *dev, struct iw_request_info *info,
-			 void *w, char *extra)
-{
-    VIRTUAL_ADAPTER	*pVirtualAd = NULL;
-	PRTMP_ADAPTER pAdapter;
-	POS_COOKIE pObj;
-	char *this_char = extra;
-	char *value;
-	int  Status=0;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->priv;
-	}
-	else
-	{
-		pVirtualAd = dev->priv;
-		pAdapter = pVirtualAd->RtmpDev->priv;
-	}
-	pObj = (POS_COOKIE) pAdapter->OS_Cookie;
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	{
-		pObj->ioctl_if_type = INT_MAIN;
-        pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-			return -ENETDOWN;
-    	}
-
-	if (!*this_char)
-		return -EINVAL;
-
-	if ((value = rtstrchr(this_char, '=')) != NULL)
-	    *value++ = 0;
-
-	if (!value)
-	    return -EINVAL;
-
-	// reject setting nothing besides ANY ssid(ssidLen=0)
-    if (!*value && (strcmp(this_char, "SSID") != 0))
-        return -EINVAL;
-
-	for (PRTMP_PRIVATE_SET_PROC = RTMP_PRIVATE_SUPPORT_PROC; PRTMP_PRIVATE_SET_PROC->name; PRTMP_PRIVATE_SET_PROC++)
-	{
-	    if (strcmp(this_char, PRTMP_PRIVATE_SET_PROC->name) == 0)
-	    {
-	        if(!PRTMP_PRIVATE_SET_PROC->set_proc(pAdapter, value))
-	        {	//FALSE:Set private failed then return Invalid argument
-			    Status = -EINVAL;
-	        }
-		    break;	//Exit for loop.
-	    }
-	}
-
-	if(PRTMP_PRIVATE_SET_PROC->name == NULL)
-	{  //Not found argument
-	    Status = -EINVAL;
-	    DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_setparam:: (iwpriv) Not Support Set Command [%s=%s]\n", this_char, value));
-	}
-
-    return Status;
-}
-
-
-static int
-rt_private_get_statistics(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-{
-	INT				Status = 0;
-    PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-
-    if (extra == NULL)
-    {
-        wrq->length = 0;
-        return -EIO;
-    }
-
-    memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-    sprintf(extra, "\n\n");
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-	    sprintf(extra+strlen(extra), "Tx success                      = %ld\n", (ULONG)pAd->ate.TxDoneCount);
-	    //sprintf(extra+strlen(extra), "Tx success without retry        = %ld\n", (ULONG)pAd->ate.TxDoneCount);
-	}
-	else
-#endif // RALINK_ATE //
-	{
-    sprintf(extra+strlen(extra), "Tx success                      = %ld\n", (ULONG)pAd->WlanCounters.TransmittedFragmentCount.QuadPart);
-    sprintf(extra+strlen(extra), "Tx success without retry        = %ld\n", (ULONG)pAd->WlanCounters.TransmittedFragmentCount.QuadPart - (ULONG)pAd->WlanCounters.RetryCount.QuadPart);
-	}
-    sprintf(extra+strlen(extra), "Tx success after retry          = %ld\n", (ULONG)pAd->WlanCounters.RetryCount.QuadPart);
-    sprintf(extra+strlen(extra), "Tx fail to Rcv ACK after retry  = %ld\n", (ULONG)pAd->WlanCounters.FailedCount.QuadPart);
-    sprintf(extra+strlen(extra), "RTS Success Rcv CTS             = %ld\n", (ULONG)pAd->WlanCounters.RTSSuccessCount.QuadPart);
-    sprintf(extra+strlen(extra), "RTS Fail Rcv CTS                = %ld\n", (ULONG)pAd->WlanCounters.RTSFailureCount.QuadPart);
-
-    sprintf(extra+strlen(extra), "Rx success                      = %ld\n", (ULONG)pAd->WlanCounters.ReceivedFragmentCount.QuadPart);
-    sprintf(extra+strlen(extra), "Rx with CRC                     = %ld\n", (ULONG)pAd->WlanCounters.FCSErrorCount.QuadPart);
-    sprintf(extra+strlen(extra), "Rx drop due to out of resource  = %ld\n", (ULONG)pAd->Counters8023.RxNoBuffer);
-    sprintf(extra+strlen(extra), "Rx duplicate frame              = %ld\n", (ULONG)pAd->WlanCounters.FrameDuplicateCount.QuadPart);
-
-    sprintf(extra+strlen(extra), "False CCA (one second)          = %ld\n", (ULONG)pAd->RalinkCounters.OneSecFalseCCACnt);
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-		if (pAd->ate.RxAntennaSel == 0)
-		{
-    		sprintf(extra+strlen(extra), "RSSI-A                          = %ld\n", (LONG)(pAd->ate.LastRssi0 - pAd->BbpRssiToDbmDelta));
-			sprintf(extra+strlen(extra), "RSSI-B (if available)           = %ld\n", (LONG)(pAd->ate.LastRssi1 - pAd->BbpRssiToDbmDelta));
-			sprintf(extra+strlen(extra), "RSSI-C (if available)           = %ld\n\n", (LONG)(pAd->ate.LastRssi2 - pAd->BbpRssiToDbmDelta));
-		}
-		else
-		{
-    		sprintf(extra+strlen(extra), "RSSI                            = %ld\n", (LONG)(pAd->ate.LastRssi0 - pAd->BbpRssiToDbmDelta));
-		}
-	}
-	else
-#endif // RALINK_ATE //
-	{
-    	sprintf(extra+strlen(extra), "RSSI-A                          = %ld\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi0 - pAd->BbpRssiToDbmDelta));
-        sprintf(extra+strlen(extra), "RSSI-B (if available)           = %ld\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi1 - pAd->BbpRssiToDbmDelta));
-        sprintf(extra+strlen(extra), "RSSI-C (if available)           = %ld\n\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi2 - pAd->BbpRssiToDbmDelta));
-	}
-#ifdef WPA_SUPPLICANT_SUPPORT
-    sprintf(extra+strlen(extra), "WpaSupplicantUP                 = %d\n\n", pAd->StaCfg.WpaSupplicantUP);
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-    DBGPRINT(RT_DEBUG_TRACE, ("<== rt_private_get_statistics, wrq->length = %d\n", wrq->length));
-
-    return Status;
-}
-
-#ifdef DOT11_N_SUPPORT
-void	getBaInfo(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pOutBuf)
-{
-	INT i, j;
-	BA_ORI_ENTRY *pOriBAEntry;
-	BA_REC_ENTRY *pRecBAEntry;
-
-	for (i=0; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[i];
-		if (((pEntry->ValidAsCLI || pEntry->ValidAsApCli) && (pEntry->Sst == SST_ASSOC))
-			|| (pEntry->ValidAsWDS) || (pEntry->ValidAsMesh))
-		{
-			sprintf(pOutBuf, "%s\n%02X:%02X:%02X:%02X:%02X:%02X (Aid = %d) (AP) -\n",
-                pOutBuf,
-				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
-				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5], pEntry->Aid);
-
-			sprintf(pOutBuf, "%s[Recipient]\n", pOutBuf);
-			for (j=0; j < NUM_OF_TID; j++)
-			{
-				if (pEntry->BARecWcidArray[j] != 0)
-				{
-					pRecBAEntry =&pAd->BATable.BARecEntry[pEntry->BARecWcidArray[j]];
-					sprintf(pOutBuf, "%sTID=%d, BAWinSize=%d, LastIndSeq=%d, ReorderingPkts=%d\n", pOutBuf, j, pRecBAEntry->BAWinSize, pRecBAEntry->LastIndSeq, pRecBAEntry->list.qlen);
-				}
-			}
-			sprintf(pOutBuf, "%s\n", pOutBuf);
-
-			sprintf(pOutBuf, "%s[Originator]\n", pOutBuf);
-			for (j=0; j < NUM_OF_TID; j++)
-			{
-				if (pEntry->BAOriWcidArray[j] != 0)
-				{
-					pOriBAEntry =&pAd->BATable.BAOriEntry[pEntry->BAOriWcidArray[j]];
-					sprintf(pOutBuf, "%sTID=%d, BAWinSize=%d, StartSeq=%d, CurTxSeq=%d\n", pOutBuf, j, pOriBAEntry->BAWinSize, pOriBAEntry->Sequence, pEntry->TxSeq[j]);
-				}
-			}
-			sprintf(pOutBuf, "%s\n\n", pOutBuf);
-		}
-        if (strlen(pOutBuf) > (IW_PRIV_SIZE_MASK - 30))
-                break;
-	}
-
-	return;
-}
-#endif // DOT11_N_SUPPORT //
-
-static int
-rt_private_show(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-{
-    INT				Status = 0;
-    VIRTUAL_ADAPTER	*pVirtualAd = NULL;
-    PRTMP_ADAPTER   pAd;
-	POS_COOKIE		pObj;
-    u32             subcmd = wrq->flags;
-
-	if (dev->priv_flags == INT_MAIN)
-		pAd = dev->priv;
-	else
-	{
-		pVirtualAd = dev->priv;
-		pAd = pVirtualAd->RtmpDev->priv;
-	}
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-    if (extra == NULL)
-    {
-        wrq->length = 0;
-        return -EIO;
-    }
-    memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-
-	{
-		pObj->ioctl_if_type = INT_MAIN;
-        pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-    switch(subcmd)
-    {
-
-        case SHOW_CONN_STATUS:
-            if (MONITOR_ON(pAd))
-            {
-#ifdef DOT11_N_SUPPORT
-                if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-                    pAd->CommonCfg.RegTransmitSetting.field.BW)
-                    sprintf(extra, "Monitor Mode(CentralChannel %d)\n", pAd->CommonCfg.CentralChannel);
-                else
-#endif // DOT11_N_SUPPORT //
-                    sprintf(extra, "Monitor Mode(Channel %d)\n", pAd->CommonCfg.Channel);
-            }
-            else
-            {
-                if (pAd->IndicateMediaState == NdisMediaStateConnected)
-            	{
-            	    if (INFRA_ON(pAd))
-                    {
-                    sprintf(extra, "Connected(AP: %s[%02X:%02X:%02X:%02X:%02X:%02X])\n",
-                                    pAd->CommonCfg.Ssid,
-                                    pAd->CommonCfg.Bssid[0],
-                                    pAd->CommonCfg.Bssid[1],
-                                    pAd->CommonCfg.Bssid[2],
-                                    pAd->CommonCfg.Bssid[3],
-                                    pAd->CommonCfg.Bssid[4],
-                                    pAd->CommonCfg.Bssid[5]);
-            		DBGPRINT(RT_DEBUG_TRACE ,("Ssid=%s ,Ssidlen = %d\n",pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen));
-            	}
-                    else if (ADHOC_ON(pAd))
-                        sprintf(extra, "Connected\n");
-            	}
-            	else
-            	{
-            	    sprintf(extra, "Disconnected\n");
-            		DBGPRINT(RT_DEBUG_TRACE ,("ConnStatus is not connected\n"));
-            	}
-            }
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-        case SHOW_DRVIER_VERION:
-            sprintf(extra, "Driver version-%s, %s %s\n", STA_DRIVER_VERSION, __DATE__, __TIME__ );
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-#ifdef DOT11_N_SUPPORT
-        case SHOW_BA_INFO:
-            getBaInfo(pAd, extra);
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-#endif // DOT11_N_SUPPORT //
-		case SHOW_DESC_INFO:
-			{
-				Show_DescInfo_Proc(pAd, NULL);
-				wrq->length = 0; // 1: size of '\0'
-			}
-			break;
-        case RAIO_OFF:
-            if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-                sprintf(extra, "Scanning\n");
-                wrq->length = strlen(extra) + 1; // 1: size of '\0'
-                break;
-            }
-            pAd->StaCfg.bSwRadio = FALSE;
-            if (pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
-            {
-                pAd->StaCfg.bRadio = (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio);
-                if (pAd->StaCfg.bRadio == FALSE)
-                {
-                    MlmeRadioOff(pAd);
-                    // Update extra information
-					pAd->ExtraInfo = SW_RADIO_OFF;
-                }
-            }
-            sprintf(extra, "Radio Off\n");
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-        case RAIO_ON:
-            if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-                sprintf(extra, "Scanning\n");
-                wrq->length = strlen(extra) + 1; // 1: size of '\0'
-                break;
-            }
-            pAd->StaCfg.bSwRadio = TRUE;
-            //if (pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
-            {
-                pAd->StaCfg.bRadio = (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio);
-                if (pAd->StaCfg.bRadio == TRUE)
-                {
-                    MlmeRadioOn(pAd);
-                    // Update extra information
-					pAd->ExtraInfo = EXTRA_INFO_CLEAR;
-                }
-            }
-            sprintf(extra, "Radio On\n");
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-
-
-#ifdef QOS_DLS_SUPPORT
-		case SHOW_DLS_ENTRY_INFO:
-			{
-				Set_DlsEntryInfo_Display_Proc(pAd, NULL);
-				wrq->length = 0; // 1: size of '\0'
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-
-		case SHOW_CFG_VALUE:
-			{
-				Status = RTMPShowCfgValue(pAd, wrq->pointer, extra);
-				if (Status == 0)
-					wrq->length = strlen(extra) + 1; // 1: size of '\0'
-			}
-			break;
-		case SHOW_ADHOC_ENTRY_INFO:
-			Show_Adhoc_MacTable_Proc(pAd, extra);
-			wrq->length = strlen(extra) + 1; // 1: size of '\0'
-			break;
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("%s - unknow subcmd = %d\n", __func__, subcmd));
-            break;
-    }
-
-    return Status;
-}
-
-#ifdef SIOCSIWMLME
-int rt_ioctl_siwmlme(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-{
-	PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-	struct iw_mlme *pMlme = (struct iw_mlme *)wrqu->data.pointer;
-	MLME_QUEUE_ELEM				MsgElem;
-	MLME_DISASSOC_REQ_STRUCT	DisAssocReq;
-	MLME_DEAUTH_REQ_STRUCT      DeAuthReq;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("====> %s\n", __func__));
-
-	if (pMlme == NULL)
-		return -EINVAL;
-
-	switch(pMlme->cmd)
-	{
-#ifdef IW_MLME_DEAUTH
-		case IW_MLME_DEAUTH:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - IW_MLME_DEAUTH\n", __func__));
-			COPY_MAC_ADDR(DeAuthReq.Addr, pAd->CommonCfg.Bssid);
-			DeAuthReq.Reason = pMlme->reason_code;
-			MsgElem.MsgLen = sizeof(MLME_DEAUTH_REQ_STRUCT);
-			NdisMoveMemory(MsgElem.Msg, &DeAuthReq, sizeof(MLME_DEAUTH_REQ_STRUCT));
-			MlmeDeauthReqAction(pAd, &MsgElem);
-			if (INFRA_ON(pAd))
-			{
-			    LinkDown(pAd, FALSE);
-			    pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-			}
-			break;
-#endif // IW_MLME_DEAUTH //
-#ifdef IW_MLME_DISASSOC
-		case IW_MLME_DISASSOC:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - IW_MLME_DISASSOC\n", __func__));
-			COPY_MAC_ADDR(DisAssocReq.Addr, pAd->CommonCfg.Bssid);
-			DisAssocReq.Reason =  pMlme->reason_code;
-
-			MsgElem.Machine = ASSOC_STATE_MACHINE;
-			MsgElem.MsgType = MT2_MLME_DISASSOC_REQ;
-			MsgElem.MsgLen = sizeof(MLME_DISASSOC_REQ_STRUCT);
-			NdisMoveMemory(MsgElem.Msg, &DisAssocReq, sizeof(MLME_DISASSOC_REQ_STRUCT));
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_DISASSOC;
-			MlmeDisassocReqAction(pAd, &MsgElem);
-			break;
-#endif // IW_MLME_DISASSOC //
-		default:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - Unknow Command\n", __func__));
-			break;
-	}
-
-	return 0;
-}
-#endif // SIOCSIWMLME //
-
-#if WIRELESS_EXT > 17
-int rt_ioctl_siwauth(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAdapter = (PRTMP_ADAPTER) dev->priv;
-	struct iw_param *param = &wrqu->param;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-	switch (param->flags & IW_AUTH_INDEX) {
-    	case IW_AUTH_WPA_VERSION:
-            if (param->value == IW_AUTH_WPA_VERSION_WPA)
-            {
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPAPSK;
-				if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-					pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
-            }
-            else if (param->value == IW_AUTH_WPA_VERSION_WPA2)
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_VERSION - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_CIPHER_PAIRWISE:
-            if (param->value == IW_AUTH_CIPHER_NONE)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_WEP40 ||
-                     param->value == IW_AUTH_CIPHER_WEP104)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPEnabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPEnabled;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-            }
-            else if (param->value == IW_AUTH_CIPHER_TKIP)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11Encryption2Enabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_CCMP)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11Encryption3Enabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11Encryption3Enabled;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_CIPHER_PAIRWISE - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_CIPHER_GROUP:
-            if (param->value == IW_AUTH_CIPHER_NONE)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_WEP40 ||
-                     param->value == IW_AUTH_CIPHER_WEP104)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11WEPEnabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_TKIP)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11Encryption2Enabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_CCMP)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11Encryption3Enabled;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_CIPHER_GROUP - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_KEY_MGMT:
-            if (param->value == IW_AUTH_KEY_MGMT_802_1X)
-            {
-                if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)
-                {
-                    pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                    pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                }
-                else if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-                {
-                    pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                    pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                }
-#ifdef WPA_SUPPLICANT_SUPPORT
-                else
-                    // WEP 1x
-                    pAdapter->StaCfg.IEEE8021X = TRUE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-            }
-            else if (param->value == 0)
-            {
-                //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAdapter);
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_KEY_MGMT - param->value = %d!\n", __func__, param->value));
-            break;
-    	case IW_AUTH_RX_UNENCRYPTED_EAPOL:
-            break;
-    	case IW_AUTH_PRIVACY_INVOKED:
-            /*if (param->value == 0)
-			{
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-        	    pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-            }*/
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_PRIVACY_INVOKED - param->value = %d!\n", __func__, param->value));
-    		break;
-    	case IW_AUTH_DROP_UNENCRYPTED:
-            if (param->value != 0)
-                pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			else
-			{
-                //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAdapter);
-			}
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_VERSION - param->value = %d!\n", __func__, param->value));
-    		break;
-    	case IW_AUTH_80211_AUTH_ALG:
-			if (param->value & IW_AUTH_ALG_SHARED_KEY)
-            {
-				pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-			}
-            else if (param->value & IW_AUTH_ALG_OPEN_SYSTEM)
-            {
-				pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-			}
-            else
-				return -EINVAL;
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_80211_AUTH_ALG - param->value = %d!\n", __func__, param->value));
-			break;
-    	case IW_AUTH_WPA_ENABLED:
-    		DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_ENABLED - Driver supports WPA!(param->value = %d)\n", __func__, param->value));
-    		break;
-    	default:
-    		return -EOPNOTSUPP;
-}
-
-	return 0;
-}
-
-int rt_ioctl_giwauth(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAdapter = (PRTMP_ADAPTER) dev->priv;
-	struct iw_param *param = &wrqu->param;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-    }
-
-	switch (param->flags & IW_AUTH_INDEX) {
-	case IW_AUTH_DROP_UNENCRYPTED:
-        param->value = (pAdapter->StaCfg.WepStatus == Ndis802_11WEPDisabled) ? 0 : 1;
-		break;
-
-	case IW_AUTH_80211_AUTH_ALG:
-        param->value = (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared) ? IW_AUTH_ALG_SHARED_KEY : IW_AUTH_ALG_OPEN_SYSTEM;
-		break;
-
-	case IW_AUTH_WPA_ENABLED:
-		param->value = (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA) ? 1 : 0;
-		break;
-
-	default:
-		return -EOPNOTSUPP;
-	}
-    DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_giwauth::param->value = %d!\n", param->value));
-	return 0;
-}
-
-void fnSetCipherKey(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  INT             keyIdx,
-    IN  UCHAR           CipherAlg,
-    IN  BOOLEAN         bGTK,
-    IN  struct iw_encode_ext *ext)
-{
-    NdisZeroMemory(&pAdapter->SharedKey[BSS0][keyIdx], sizeof(CIPHER_KEY));
-    pAdapter->SharedKey[BSS0][keyIdx].KeyLen = LEN_TKIP_EK;
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, ext->key, LEN_TKIP_EK);
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].TxMic, ext->key + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].RxMic, ext->key + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CipherAlg;
-
-    // Update group key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAdapter,
-						  BSS0,
-						  keyIdx,
-						  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-						  pAdapter->SharedKey[BSS0][keyIdx].Key,
-						  pAdapter->SharedKey[BSS0][keyIdx].TxMic,
-						  pAdapter->SharedKey[BSS0][keyIdx].RxMic);
-
-    if (bGTK)
-        // Update ASIC WCID attribute table and IVEIV table
-    	RTMPAddWcidAttributeEntry(pAdapter,
-    							  BSS0,
-    							  keyIdx,
-    							  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-    							  NULL);
-    else
-        // Update ASIC WCID attribute table and IVEIV table
-    	RTMPAddWcidAttributeEntry(pAdapter,
-    							  BSS0,
-    							  keyIdx,
-    							  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-    							  &pAdapter->MacTab.Content[BSSID_WCID]);
-}
-
-int rt_ioctl_siwencodeext(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-			{
-    PRTMP_ADAPTER   pAdapter = (PRTMP_ADAPTER) dev->priv;
-	struct iw_point *encoding = &wrqu->encoding;
-	struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
-    int keyIdx, alg = ext->alg;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    if (encoding->flags & IW_ENCODE_DISABLED)
-	{
-        keyIdx = (encoding->flags & IW_ENCODE_INDEX) - 1;
-        // set BSSID wcid entry of the Pair-wise Key table as no-security mode
-	    AsicRemovePairwiseKeyEntry(pAdapter, BSS0, BSSID_WCID);
-        pAdapter->SharedKey[BSS0][keyIdx].KeyLen = 0;
-		pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_NONE;
-		AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)keyIdx);
-        NdisZeroMemory(&pAdapter->SharedKey[BSS0][keyIdx], sizeof(CIPHER_KEY));
-        DBGPRINT(RT_DEBUG_TRACE, ("%s::Remove all keys!(encoding->flags = %x)\n", __func__, encoding->flags));
-    }
-					else
-    {
-        // Get Key Index and convet to our own defined key index
-    	keyIdx = (encoding->flags & IW_ENCODE_INDEX) - 1;
-    	if((keyIdx < 0) || (keyIdx >= NR_WEP_KEYS))
-    		return -EINVAL;
-
-        if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-        {
-            pAdapter->StaCfg.DefaultKeyId = keyIdx;
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::DefaultKeyId = %d\n", __func__, pAdapter->StaCfg.DefaultKeyId));
-        }
-
-        switch (alg) {
-    		case IW_ENCODE_ALG_NONE:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_NONE\n", __func__));
-    			break;
-    		case IW_ENCODE_ALG_WEP:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_WEP - ext->key_len = %d, keyIdx = %d\n", __func__, ext->key_len, keyIdx));
-    			if (ext->key_len == MAX_WEP_KEY_SIZE)
-                {
-        			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MAX_WEP_KEY_SIZE;
-                    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP128;
-				}
-        		else if (ext->key_len == MIN_WEP_KEY_SIZE)
-                {
-                    pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MIN_WEP_KEY_SIZE;
-                    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP64;
-			}
-        		else
-                    return -EINVAL;
-
-                NdisZeroMemory(pAdapter->SharedKey[BSS0][keyIdx].Key,  16);
-			    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, ext->key, ext->key_len);
-    			break;
-            case IW_ENCODE_ALG_TKIP:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_TKIP - keyIdx = %d, ext->key_len = %d\n", __func__, keyIdx, ext->key_len));
-                if (ext->key_len == 32)
-                {
-                    if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-                    {
-                        fnSetCipherKey(pAdapter, keyIdx, CIPHER_TKIP, FALSE, ext);
-                        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-                        {
-                            //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-                            STA_PORT_SECURED(pAdapter);
-                        }
-		}
-                    else if (ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY)
-                    {
-                        fnSetCipherKey(pAdapter, keyIdx, CIPHER_TKIP, TRUE, ext);
-
-                        // set 802.1x port control
-            	        //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-            	        STA_PORT_SECURED(pAdapter);
-                    }
-                }
-                else
-                    return -EINVAL;
-                break;
-            case IW_ENCODE_ALG_CCMP:
-                if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-		{
-                    fnSetCipherKey(pAdapter, keyIdx, CIPHER_AES, FALSE, ext);
-                    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-                    	//pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-                    	STA_PORT_SECURED(pAdapter);
-                }
-                else if (ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY)
-                {
-                    fnSetCipherKey(pAdapter, keyIdx, CIPHER_AES, TRUE, ext);
-
-                    // set 802.1x port control
-        	        //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-        	        STA_PORT_SECURED(pAdapter);
-                }
-                break;
-    		default:
-    			return -EINVAL;
-		}
-    }
-
-    return 0;
-}
-
-int
-rt_ioctl_giwencodeext(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER pAd = (PRTMP_ADAPTER) dev->priv;
-	PCHAR pKey = NULL;
-	struct iw_point *encoding = &wrqu->encoding;
-	struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
-	int idx, max_key_len;
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===> rt_ioctl_giwencodeext\n"));
-
-	max_key_len = encoding->length - sizeof(*ext);
-	if (max_key_len < 0)
-		return -EINVAL;
-
-	idx = encoding->flags & IW_ENCODE_INDEX;
-	if (idx)
-	{
-		if (idx < 1 || idx > 4)
-			return -EINVAL;
-		idx--;
-
-		if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
-			(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled))
-		{
-			if (idx != pAd->StaCfg.DefaultKeyId)
-			{
-				ext->key_len = 0;
-				return 0;
-			}
-		}
-	}
-	else
-		idx = pAd->StaCfg.DefaultKeyId;
-
-	encoding->flags = idx + 1;
-	memset(ext, 0, sizeof(*ext));
-
-	ext->key_len = 0;
-	switch(pAd->StaCfg.WepStatus) {
-		case Ndis802_11WEPDisabled:
-			ext->alg = IW_ENCODE_ALG_NONE;
-			encoding->flags |= IW_ENCODE_DISABLED;
-			break;
-		case Ndis802_11WEPEnabled:
-			ext->alg = IW_ENCODE_ALG_WEP;
-			if (pAd->SharedKey[BSS0][idx].KeyLen > max_key_len)
-				return -E2BIG;
-			else
-			{
-				ext->key_len = pAd->SharedKey[BSS0][idx].KeyLen;
-				pKey = &(pAd->SharedKey[BSS0][idx].Key[0]);
-			}
-			break;
-		case Ndis802_11Encryption2Enabled:
-		case Ndis802_11Encryption3Enabled:
-			if (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled)
-				ext->alg = IW_ENCODE_ALG_TKIP;
-			else
-				ext->alg = IW_ENCODE_ALG_CCMP;
-
-			if (max_key_len < 32)
-				return -E2BIG;
-			else
-			{
-				ext->key_len = 32;
-				pKey = &pAd->StaCfg.PMK[0];
-			}
-			break;
-		default:
-			return -EINVAL;
-	}
-
-	if (ext->key_len && pKey)
-	{
-		encoding->flags |= IW_ENCODE_ENABLED;
-		memcpy(ext->key, pKey, ext->key_len);
-	}
-
-	return 0;
-}
-
-#ifdef SIOCSIWGENIE
-int rt_ioctl_siwgenie(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-
-	if (wrqu->data.length > MAX_LEN_OF_RSNIE ||
-	    (wrqu->data.length && extra == NULL))
-		return -EINVAL;
-
-	if (wrqu->data.length)
-	{
-		pAd->StaCfg.RSNIE_Len = wrqu->data.length;
-		NdisMoveMemory(&pAd->StaCfg.RSN_IE[0], extra, pAd->StaCfg.RSNIE_Len);
-	}
-	else
-	{
-		pAd->StaCfg.RSNIE_Len = 0;
-		NdisZeroMemory(&pAd->StaCfg.RSN_IE[0], MAX_LEN_OF_RSNIE);
-	}
-
-	return 0;
-}
-#endif // SIOCSIWGENIE //
-
-int rt_ioctl_giwgenie(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-
-	if ((pAd->StaCfg.RSNIE_Len == 0) ||
-		(pAd->StaCfg.AuthMode < Ndis802_11AuthModeWPA))
-	{
-		wrqu->data.length = 0;
-		return 0;
-	}
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-#ifdef SIOCSIWGENIE
-	if (pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-	if (wrqu->data.length < pAd->StaCfg.RSNIE_Len)
-		return -E2BIG;
-
-	wrqu->data.length = pAd->StaCfg.RSNIE_Len;
-	memcpy(extra, &pAd->StaCfg.RSN_IE[0], pAd->StaCfg.RSNIE_Len);
-	}
-	else
-#endif // SIOCSIWGENIE //
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-	{
-		UCHAR RSNIe = IE_WPA;
-
-		if (wrqu->data.length < (pAd->StaCfg.RSNIE_Len + 2)) // ID, Len
-			return -E2BIG;
-		wrqu->data.length = pAd->StaCfg.RSNIE_Len + 2;
-
-		if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-            (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2))
-			RSNIe = IE_RSN;
-
-		extra[0] = (char)RSNIe;
-		extra[1] = pAd->StaCfg.RSNIE_Len;
-		memcpy(extra+2, &pAd->StaCfg.RSN_IE[0], pAd->StaCfg.RSNIE_Len);
-	}
-
-	return 0;
-}
-
-int rt_ioctl_siwpmksa(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-{
-	PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-	struct iw_pmksa *pPmksa = (struct iw_pmksa *)wrqu->data.pointer;
-	INT	CachedIdx = 0, idx = 0;
-
-	if (pPmksa == NULL)
-		return -EINVAL;
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===> rt_ioctl_siwpmksa\n"));
-	switch(pPmksa->cmd)
-	{
-		case IW_PMKSA_FLUSH:
-			NdisZeroMemory(pAd->StaCfg.SavedPMK, sizeof(BSSID_INFO)*PMKID_NO);
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_FLUSH\n"));
-			break;
-		case IW_PMKSA_REMOVE:
-			for (CachedIdx = 0; CachedIdx < pAd->StaCfg.SavedPMKNum; CachedIdx++)
-			{
-		        // compare the BSSID
-		        if (NdisEqualMemory(pPmksa->bssid.sa_data, pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN))
-		        {
-		        	NdisZeroMemory(pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN);
-					NdisZeroMemory(pAd->StaCfg.SavedPMK[CachedIdx].PMKID, 16);
-					for (idx = CachedIdx; idx < (pAd->StaCfg.SavedPMKNum - 1); idx++)
-					{
-						NdisMoveMemory(&pAd->StaCfg.SavedPMK[idx].BSSID[0], &pAd->StaCfg.SavedPMK[idx+1].BSSID[0], MAC_ADDR_LEN);
-						NdisMoveMemory(&pAd->StaCfg.SavedPMK[idx].PMKID[0], &pAd->StaCfg.SavedPMK[idx+1].PMKID[0], 16);
-					}
-					pAd->StaCfg.SavedPMKNum--;
-			        break;
-		        }
-	        }
-
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_REMOVE\n"));
-			break;
-		case IW_PMKSA_ADD:
-			for (CachedIdx = 0; CachedIdx < pAd->StaCfg.SavedPMKNum; CachedIdx++)
-			{
-		        // compare the BSSID
-		        if (NdisEqualMemory(pPmksa->bssid.sa_data, pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN))
-			        break;
-	        }
-
-	        // Found, replace it
-	        if (CachedIdx < PMKID_NO)
-	        {
-		        DBGPRINT(RT_DEBUG_OFF, ("Update PMKID, idx = %d\n", CachedIdx));
-		        NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].BSSID[0], pPmksa->bssid.sa_data, MAC_ADDR_LEN);
-				NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].PMKID[0], pPmksa->pmkid, 16);
-		        pAd->StaCfg.SavedPMKNum++;
-	        }
-	        // Not found, replace the last one
-	        else
-	        {
-		        // Randomly replace one
-		        CachedIdx = (pPmksa->bssid.sa_data[5] % PMKID_NO);
-		        DBGPRINT(RT_DEBUG_OFF, ("Update PMKID, idx = %d\n", CachedIdx));
-		        NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].BSSID[0], pPmksa->bssid.sa_data, MAC_ADDR_LEN);
-				NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].PMKID[0], pPmksa->pmkid, 16);
-	        }
-
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_ADD\n"));
-			break;
-		default:
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - Unknow Command!!\n"));
-			break;
-	}
-
-	return 0;
-}
-#endif // #if WIRELESS_EXT > 17
-
-#ifdef DBG
-static int
-rt_private_ioctl_bbp(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-			{
-	CHAR				*this_char;
-	CHAR				*value = NULL;
-	UCHAR				regBBP = 0;
-//	CHAR				arg[255]={0};
-	UINT32				bbpId;
-	UINT32				bbpValue;
-	BOOLEAN				bIsPrintAllBBP = FALSE;
-	INT					Status = 0;
-    PRTMP_ADAPTER       pAdapter = (PRTMP_ADAPTER) dev->priv;
-
-
-	memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-
-	if (wrq->length > 1) //No parameters.
-				{
-		sprintf(extra, "\n");
-
-		//Parsing Read or Write
-		this_char = wrq->pointer;
-		DBGPRINT(RT_DEBUG_TRACE, ("this_char=%s\n", this_char));
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-			DBGPRINT(RT_DEBUG_TRACE, ("this_char=%s, value=%s\n", this_char, value));
-			if (sscanf(this_char, "%d", &(bbpId)) == 1)
-			{
-				if (bbpId <= 136)
-				{
-#ifdef RALINK_ATE
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					else
-#endif // RALINK_ATE //
-					{
-					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X\n", bbpId, bbpId*2, regBBP);
-                    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-					DBGPRINT(RT_DEBUG_TRACE, ("msg=%s\n", extra));
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					bIsPrintAllBBP = TRUE;
-					goto next;
-				}
-			}
-			else
-			{ //Invalid parametes, so default printk all bbp
-				bIsPrintAllBBP = TRUE;
-				goto next;
-			}
-		}
-		else
-		{ //Write
-			if ((sscanf(this_char, "%d", &(bbpId)) == 1) && (sscanf(value, "%x", &(bbpValue)) == 1))
-			{
-				if (bbpId <= 136)
-				{
-#ifdef RALINK_ATE
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, bbpId, bbpValue);
-						//Read it back for showing
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					else
-#endif // RALINK_ATE //
-					{
-					    RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, bbpId, bbpValue);
-    					//Read it back for showing
-    					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			}
-					sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X\n", bbpId, bbpId*2, regBBP);
-                    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-					DBGPRINT(RT_DEBUG_TRACE, ("msg=%s\n", extra));
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					bIsPrintAllBBP = TRUE;
-					goto next;
-				}
-			}
-			else
-			{ //Invalid parametes, so default printk all bbp
-				bIsPrintAllBBP = TRUE;
-				goto next;
-			}
-		}
-		}
-	else
-		bIsPrintAllBBP = TRUE;
-
-next:
-	if (bIsPrintAllBBP)
-	{
-		memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-		sprintf(extra, "\n");
-		for (bbpId = 0; bbpId <= 136; bbpId++)
-		{
-		    if (strlen(extra) >= (IW_PRIV_SIZE_MASK - 10))
-                break;
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			}
-			else
-#endif // RALINK_ATE //
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X    ", bbpId, bbpId*2, regBBP);
-			if (bbpId%5 == 4)
-				sprintf(extra+strlen(extra), "\n");
-		}
-
-        wrq->length = strlen(extra) + 1; // 1: size of '\0'
-        DBGPRINT(RT_DEBUG_TRACE, ("wrq->length = %d\n", wrq->length));
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==rt_private_ioctl_bbp\n\n"));
-
-    return Status;
-}
-#endif // DBG //
-
-int rt_ioctl_siwrate(struct net_device *dev,
-			struct iw_request_info *info,
-			union iwreq_data *wrqu, char *extra)
-{
-    PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-    UINT32          rate = wrqu->bitrate.value, fixed = wrqu->bitrate.fixed;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::(rate = %d, fixed = %d)\n", rate, fixed));
-    /* rate = -1 => auto rate
-       rate = X, fixed = 1 => (fixed rate X)
-    */
-    if (rate == -1)
-    {
-		//Auto Rate
-		pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-		pAd->StaCfg.bAutoTxRateSwitch = TRUE;
-		if ((pAd->CommonCfg.PhyMode <= PHY_11G) ||
-		    (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM))
-			RTMPSetDesiredRates(pAd, -1);
-
-#ifdef DOT11_N_SUPPORT
-		SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-    }
-    else
-    {
-        if (fixed)
-        {
-        	pAd->StaCfg.bAutoTxRateSwitch = FALSE;
-            if ((pAd->CommonCfg.PhyMode <= PHY_11G) ||
-                (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM))
-                RTMPSetDesiredRates(pAd, rate);
-            else
-            {
-                pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-#ifdef DOT11_N_SUPPORT
-                SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::(HtMcs=%d)\n",pAd->StaCfg.DesiredTransmitSetting.field.MCS));
-        }
-        else
-        {
-            // TODO: rate = X, fixed = 0 => (rates <= X)
-            return -EOPNOTSUPP;
-        }
-    }
-
-    return 0;
-}
-
-int rt_ioctl_giwrate(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-    PRTMP_ADAPTER   pAd = (PRTMP_ADAPTER) dev->priv;
-    int rate_index = 0, rate_count = 0;
-    HTTRANSMIT_SETTING ht_setting;
-    __s32 ralinkrate[] =
-	{2,  4,   11,  22, // CCK
-	12, 18,   24,  36, 48, 72, 96, 108, // OFDM
-	13, 26,   39,  52,  78, 104, 117, 130, 26,  52,  78, 104, 156, 208, 234, 260, // 20MHz, 800ns GI, MCS: 0 ~ 15
-	39, 78,  117, 156, 234, 312, 351, 390,										  // 20MHz, 800ns GI, MCS: 16 ~ 23
-	27, 54,   81, 108, 162, 216, 243, 270, 54, 108, 162, 216, 324, 432, 486, 540, // 40MHz, 800ns GI, MCS: 0 ~ 15
-	81, 162, 243, 324, 486, 648, 729, 810,										  // 40MHz, 800ns GI, MCS: 16 ~ 23
-	14, 29,   43,  57,  87, 115, 130, 144, 29, 59,   87, 115, 173, 230, 260, 288, // 20MHz, 400ns GI, MCS: 0 ~ 15
-	43, 87,  130, 173, 260, 317, 390, 433,										  // 20MHz, 400ns GI, MCS: 16 ~ 23
-	30, 60,   90, 120, 180, 240, 270, 300, 60, 120, 180, 240, 360, 480, 540, 600, // 40MHz, 400ns GI, MCS: 0 ~ 15
-	90, 180, 270, 360, 540, 720, 810, 900};										  // 40MHz, 400ns GI, MCS: 16 ~ 23
-
-    rate_count = sizeof(ralinkrate)/sizeof(__s32);
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    if ((pAd->StaCfg.bAutoTxRateSwitch == FALSE) &&
-        (INFRA_ON(pAd)) &&
-        ((pAd->CommonCfg.PhyMode <= PHY_11G) || (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM)))
-        ht_setting.word = pAd->StaCfg.HTPhyMode.word;
-    else
-        ht_setting.word = pAd->MacTab.Content[BSSID_WCID].HTPhyMode.word;
-
-#ifdef DOT11_N_SUPPORT
-    if (ht_setting.field.MODE >= MODE_HTMIX)
-    {
-//    	rate_index = 12 + ((UCHAR)ht_setting.field.BW *16) + ((UCHAR)ht_setting.field.ShortGI *32) + ((UCHAR)ht_setting.field.MCS);
-    	rate_index = 12 + ((UCHAR)ht_setting.field.BW *24) + ((UCHAR)ht_setting.field.ShortGI *48) + ((UCHAR)ht_setting.field.MCS);
-    }
-    else
-#endif // DOT11_N_SUPPORT //
-    if (ht_setting.field.MODE == MODE_OFDM)
-    	rate_index = (UCHAR)(ht_setting.field.MCS) + 4;
-    else if (ht_setting.field.MODE == MODE_CCK)
-    	rate_index = (UCHAR)(ht_setting.field.MCS);
-
-    if (rate_index < 0)
-        rate_index = 0;
-
-    if (rate_index > rate_count)
-        rate_index = rate_count;
-
-    wrqu->bitrate.value = ralinkrate[rate_index] * 500000;
-    wrqu->bitrate.disabled = 0;
-
-    return 0;
-}
-
-static const iw_handler rt_handler[] =
-{
-	(iw_handler) NULL,			            /* SIOCSIWCOMMIT */
-	(iw_handler) rt_ioctl_giwname,			/* SIOCGIWNAME   */
-	(iw_handler) NULL,			            /* SIOCSIWNWID   */
-	(iw_handler) NULL,			            /* SIOCGIWNWID   */
-	(iw_handler) rt_ioctl_siwfreq,		    /* SIOCSIWFREQ   */
-	(iw_handler) rt_ioctl_giwfreq,		    /* SIOCGIWFREQ   */
-	(iw_handler) rt_ioctl_siwmode,		    /* SIOCSIWMODE   */
-	(iw_handler) rt_ioctl_giwmode,		    /* SIOCGIWMODE   */
-	(iw_handler) NULL,		                /* SIOCSIWSENS   */
-	(iw_handler) NULL,		                /* SIOCGIWSENS   */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWRANGE  */
-	(iw_handler) rt_ioctl_giwrange,		    /* SIOCGIWRANGE  */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWPRIV   */
-	(iw_handler) NULL /* kernel code */,    /* SIOCGIWPRIV   */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWSTATS  */
-	(iw_handler) rt28xx_get_wireless_stats /* kernel code */,    /* SIOCGIWSTATS  */
-	(iw_handler) NULL,		                /* SIOCSIWSPY    */
-	(iw_handler) NULL,		                /* SIOCGIWSPY    */
-	(iw_handler) NULL,				        /* SIOCSIWTHRSPY */
-	(iw_handler) NULL,				        /* SIOCGIWTHRSPY */
-	(iw_handler) rt_ioctl_siwap,            /* SIOCSIWAP     */
-	(iw_handler) rt_ioctl_giwap,		    /* SIOCGIWAP     */
-#ifdef SIOCSIWMLME
-	(iw_handler) rt_ioctl_siwmlme,	        /* SIOCSIWMLME   */
-#else
-	(iw_handler) NULL,				        /* SIOCSIWMLME */
-#endif // SIOCSIWMLME //
-	(iw_handler) rt_ioctl_iwaplist,		    /* SIOCGIWAPLIST */
-#ifdef SIOCGIWSCAN
-	(iw_handler) rt_ioctl_siwscan,		    /* SIOCSIWSCAN   */
-	(iw_handler) rt_ioctl_giwscan,		    /* SIOCGIWSCAN   */
-#else
-	(iw_handler) NULL,				        /* SIOCSIWSCAN   */
-	(iw_handler) NULL,				        /* SIOCGIWSCAN   */
-#endif /* SIOCGIWSCAN */
-	(iw_handler) rt_ioctl_siwessid,		    /* SIOCSIWESSID  */
-	(iw_handler) rt_ioctl_giwessid,		    /* SIOCGIWESSID  */
-	(iw_handler) rt_ioctl_siwnickn,		    /* SIOCSIWNICKN  */
-	(iw_handler) rt_ioctl_giwnickn,		    /* SIOCGIWNICKN  */
-	(iw_handler) NULL,				        /* -- hole --    */
-	(iw_handler) NULL,				        /* -- hole --    */
-	(iw_handler) rt_ioctl_siwrate,          /* SIOCSIWRATE   */
-	(iw_handler) rt_ioctl_giwrate,          /* SIOCGIWRATE   */
-	(iw_handler) rt_ioctl_siwrts,		    /* SIOCSIWRTS    */
-	(iw_handler) rt_ioctl_giwrts,		    /* SIOCGIWRTS    */
-	(iw_handler) rt_ioctl_siwfrag,		    /* SIOCSIWFRAG   */
-	(iw_handler) rt_ioctl_giwfrag,		    /* SIOCGIWFRAG   */
-	(iw_handler) NULL,		                /* SIOCSIWTXPOW  */
-	(iw_handler) NULL,		                /* SIOCGIWTXPOW  */
-	(iw_handler) NULL,		                /* SIOCSIWRETRY  */
-	(iw_handler) NULL,		                /* SIOCGIWRETRY  */
-	(iw_handler) rt_ioctl_siwencode,		/* SIOCSIWENCODE */
-	(iw_handler) rt_ioctl_giwencode,		/* SIOCGIWENCODE */
-	(iw_handler) NULL,		                /* SIOCSIWPOWER  */
-	(iw_handler) NULL,		                /* SIOCGIWPOWER  */
-	(iw_handler) NULL,						/* -- hole -- */
-	(iw_handler) NULL,						/* -- hole -- */
-#if WIRELESS_EXT > 17
-    (iw_handler) rt_ioctl_siwgenie,         /* SIOCSIWGENIE  */
-	(iw_handler) rt_ioctl_giwgenie,         /* SIOCGIWGENIE  */
-	(iw_handler) rt_ioctl_siwauth,		    /* SIOCSIWAUTH   */
-	(iw_handler) rt_ioctl_giwauth,		    /* SIOCGIWAUTH   */
-	(iw_handler) rt_ioctl_siwencodeext,	    /* SIOCSIWENCODEEXT */
-	(iw_handler) rt_ioctl_giwencodeext,		/* SIOCGIWENCODEEXT */
-	(iw_handler) rt_ioctl_siwpmksa,         /* SIOCSIWPMKSA  */
-#endif
-};
-
-static const iw_handler rt_priv_handlers[] = {
-	(iw_handler) NULL, /* + 0x00 */
-	(iw_handler) NULL, /* + 0x01 */
-#ifndef CONFIG_AP_SUPPORT
-	(iw_handler) rt_ioctl_setparam, /* + 0x02 */
-#else
-	(iw_handler) NULL, /* + 0x02 */
-#endif // CONFIG_AP_SUPPORT //
-#ifdef DBG
-	(iw_handler) rt_private_ioctl_bbp, /* + 0x03 */
-#else
-	(iw_handler) NULL, /* + 0x03 */
-#endif
-	(iw_handler) NULL, /* + 0x04 */
-	(iw_handler) NULL, /* + 0x05 */
-	(iw_handler) NULL, /* + 0x06 */
-	(iw_handler) NULL, /* + 0x07 */
-	(iw_handler) NULL, /* + 0x08 */
-	(iw_handler) rt_private_get_statistics, /* + 0x09 */
-	(iw_handler) NULL, /* + 0x0A */
-	(iw_handler) NULL, /* + 0x0B */
-	(iw_handler) NULL, /* + 0x0C */
-	(iw_handler) NULL, /* + 0x0D */
-	(iw_handler) NULL, /* + 0x0E */
-	(iw_handler) NULL, /* + 0x0F */
-	(iw_handler) NULL, /* + 0x10 */
-	(iw_handler) rt_private_show, /* + 0x11 */
-    (iw_handler) NULL, /* + 0x12 */
-	(iw_handler) NULL, /* + 0x13 */
-	(iw_handler) NULL, /* + 0x15 */
-	(iw_handler) NULL, /* + 0x17 */
-	(iw_handler) NULL, /* + 0x18 */
-};
-
-const struct iw_handler_def rt28xx_iw_handler_def =
-{
-#define	N(a)	(sizeof (a) / sizeof (a[0]))
-	.standard	= (iw_handler *) rt_handler,
-	.num_standard	= sizeof(rt_handler) / sizeof(iw_handler),
-	.private	= (iw_handler *) rt_priv_handlers,
-	.num_private		= N(rt_priv_handlers),
-	.private_args	= (struct iw_priv_args *) privtab,
-	.num_private_args	= N(privtab),
-#if IW_HANDLER_VERSION >= 7
-    .get_wireless_stats = rt28xx_get_wireless_stats,
-#endif
-};
-
-INT RTMPSetInformation(
-    IN  PRTMP_ADAPTER pAdapter,
-    IN  OUT struct ifreq    *rq,
-    IN  INT                 cmd)
-{
-    struct iwreq                        *wrq = (struct iwreq *) rq;
-    NDIS_802_11_SSID                    Ssid;
-    NDIS_802_11_MAC_ADDRESS             Bssid;
-    RT_802_11_PHY_MODE                  PhyMode;
-    RT_802_11_STA_CONFIG                StaConfig;
-    NDIS_802_11_RATES                   aryRates;
-    RT_802_11_PREAMBLE                  Preamble;
-    NDIS_802_11_WEP_STATUS              WepStatus;
-    NDIS_802_11_AUTHENTICATION_MODE     AuthMode = Ndis802_11AuthModeMax;
-    NDIS_802_11_NETWORK_INFRASTRUCTURE  BssType;
-    NDIS_802_11_RTS_THRESHOLD           RtsThresh;
-    NDIS_802_11_FRAGMENTATION_THRESHOLD FragThresh;
-    NDIS_802_11_POWER_MODE              PowerMode;
-    PNDIS_802_11_KEY                    pKey = NULL;
-    PNDIS_802_11_WEP			        pWepKey =NULL;
-    PNDIS_802_11_REMOVE_KEY             pRemoveKey = NULL;
-    NDIS_802_11_CONFIGURATION           Config, *pConfig = NULL;
-    NDIS_802_11_NETWORK_TYPE            NetType;
-    ULONG                               Now;
-    UINT                                KeyIdx = 0;
-    INT                                 Status = NDIS_STATUS_SUCCESS, MaxPhyMode = PHY_11G;
-    ULONG                               PowerTemp;
-    BOOLEAN                             RadioState;
-    BOOLEAN                             StateMachineTouched = FALSE;
-#ifdef DOT11_N_SUPPORT
-	OID_SET_HT_PHYMODE					HT_PhyMode;	//11n ,kathy
-#endif // DOT11_N_SUPPORT //
-#ifdef WPA_SUPPLICANT_SUPPORT
-    PNDIS_802_11_PMKID                  pPmkId = NULL;
-    BOOLEAN				                IEEE8021xState = FALSE;
-    BOOLEAN				                IEEE8021x_required_keys = FALSE;
-    UCHAR                               wpa_supplicant_enable = 0;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef SNMP_SUPPORT
-	TX_RTY_CFG_STRUC			tx_rty_cfg;
-	ULONG						ShortRetryLimit, LongRetryLimit;
-	UCHAR						ctmp;
-#endif // SNMP_SUPPORT //
-
-
-
-#ifdef DOT11_N_SUPPORT
-	MaxPhyMode = PHY_11N_5G;
-#endif // DOT11_N_SUPPORT //
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("-->RTMPSetInformation(),	0x%08x\n", cmd&0x7FFF));
-    switch(cmd & 0x7FFF) {
-        case RT_OID_802_11_COUNTRY_REGION:
-            if (wrq->u.data.length < sizeof(UCHAR))
-                Status = -EINVAL;
-			// Only avaliable when EEPROM not programming
-            else if (!(pAdapter->CommonCfg.CountryRegion & 0x80) && !(pAdapter->CommonCfg.CountryRegionForABand & 0x80))
-            {
-                ULONG   Country;
-                UCHAR	TmpPhy;
-
-				Status = copy_from_user(&Country, wrq->u.data.pointer, wrq->u.data.length);
-				pAdapter->CommonCfg.CountryRegion = (UCHAR)(Country & 0x000000FF);
-				pAdapter->CommonCfg.CountryRegionForABand = (UCHAR)((Country >> 8) & 0x000000FF);
-                TmpPhy = pAdapter->CommonCfg.PhyMode;
-				pAdapter->CommonCfg.PhyMode = 0xff;
-				// Build all corresponding channel information
-				RTMPSetPhyMode(pAdapter, TmpPhy);
-#ifdef DOT11_N_SUPPORT
-				SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_COUNTRY_REGION (A:%d  B/G:%d)\n", pAdapter->CommonCfg.CountryRegionForABand,
-				    pAdapter->CommonCfg.CountryRegion));
-            }
-            break;
-        case OID_802_11_BSSID_LIST_SCAN:
- #ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-            Now = jiffies;
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_BSSID_LIST_SCAN, TxCnt = %d \n", pAdapter->RalinkCounters.LastOneSecTotalTxCount));
-
-            if (MONITOR_ON(pAdapter))
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is in Monitor Mode now !!!\n"));
-                break;
-            }
-
-			//Benson add 20080527, when radio off, sta don't need to scan
-			if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_RADIO_OFF))
-				break;
-
-			if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-			{
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is scanning now !!!\n"));
-				pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-				Status = NDIS_STATUS_SUCCESS;
-                break;
-            }
-
-			if (pAdapter->RalinkCounters.LastOneSecTotalTxCount > 100)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-				Status = NDIS_STATUS_SUCCESS;
-				pAdapter->StaCfg.ScanCnt = 99;		// Prevent auto scan triggered by this OID
-				break;
-            }
-
-            if ((OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED)) &&
-				((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)) &&
-                (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, Port Not Secured! ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-				Status = NDIS_STATUS_SUCCESS;
-				pAdapter->StaCfg.ScanCnt = 99;		// Prevent auto scan triggered by this OID
-				break;
-            }
-
-
-            if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-            {
-                RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-            }
-
-            // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-            // this request, because this request is initiated by NDIS.
-            pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-            // Reset allowed scan retries
-            pAdapter->StaCfg.ScanCnt = 0;
-            pAdapter->StaCfg.LastScanTime = Now;
-
-			pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-            RTMP_SET_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-            MlmeEnqueue(pAdapter,
-                        MLME_CNTL_STATE_MACHINE,
-                        OID_802_11_BSSID_LIST_SCAN,
-                        0,
-                        NULL);
-
-            Status = NDIS_STATUS_SUCCESS;
-            StateMachineTouched = TRUE;
-            break;
-        case OID_802_11_SSID:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_SSID))
-                Status = -EINVAL;
-            else
-            {
-            	PCHAR pSsidString = NULL;
-                Status = copy_from_user(&Ssid, wrq->u.data.pointer, wrq->u.data.length);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SSID (Len=%d,Ssid=%s)\n", Ssid.SsidLength, Ssid.Ssid));
-                if (Ssid.SsidLength > MAX_LEN_OF_SSID)
-                    Status = -EINVAL;
-                else
-                {
-                	if (Ssid.SsidLength == 0)
-                	{
-                		Set_SSID_Proc(pAdapter, "");
-                	}
-					else
-                	{
-	                	pSsidString = (CHAR *) kmalloc(MAX_LEN_OF_SSID+1, MEM_ALLOC_FLAG);
-						if (pSsidString)
-						{
-							NdisZeroMemory(pSsidString, MAX_LEN_OF_SSID+1);
-							NdisMoveMemory(pSsidString, Ssid.Ssid, Ssid.SsidLength);
-	                		Set_SSID_Proc(pAdapter, pSsidString);
-							kfree(pSsidString);
-						}
-						else
-							Status = -ENOMEM;
-                	}
-                }
-            }
-            break;
-        case OID_802_11_BSSID:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-            if (wrq->u.data.length != sizeof(NDIS_802_11_MAC_ADDRESS))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Bssid, wrq->u.data.pointer, wrq->u.data.length);
-
-                // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-                // this request, because this request is initiated by NDIS.
-                pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-
-				// Prevent to connect AP again in STAMlmePeriodicExec
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-
-                // Reset allowed scan retries
-				pAdapter->StaCfg.ScanCnt = 0;
-
-                if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-                {
-                    RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-                    DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-                }
-                MlmeEnqueue(pAdapter,
-                            MLME_CNTL_STATE_MACHINE,
-                            OID_802_11_BSSID,
-                            sizeof(NDIS_802_11_MAC_ADDRESS),
-                            (VOID *)&Bssid);
-                Status = NDIS_STATUS_SUCCESS;
-                StateMachineTouched = TRUE;
-
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_BSSID %02x:%02x:%02x:%02x:%02x:%02x\n",
-                                        Bssid[0], Bssid[1], Bssid[2], Bssid[3], Bssid[4], Bssid[5]));
-            }
-            break;
-        case RT_OID_802_11_RADIO:
-            if (wrq->u.data.length != sizeof(BOOLEAN))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&RadioState, wrq->u.data.pointer, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_RADIO (=%d)\n", RadioState));
-                if (pAdapter->StaCfg.bSwRadio != RadioState)
-                {
-                    pAdapter->StaCfg.bSwRadio = RadioState;
-                    if (pAdapter->StaCfg.bRadio != (pAdapter->StaCfg.bHwRadio && pAdapter->StaCfg.bSwRadio))
-                    {
-                        pAdapter->StaCfg.bRadio = (pAdapter->StaCfg.bHwRadio && pAdapter->StaCfg.bSwRadio);
-                        if (pAdapter->StaCfg.bRadio == TRUE)
-                        {
-                            MlmeRadioOn(pAdapter);
-                            // Update extra information
-							pAdapter->ExtraInfo = EXTRA_INFO_CLEAR;
-                        }
-                        else
-                        {
-                            MlmeRadioOff(pAdapter);
-                            // Update extra information
-							pAdapter->ExtraInfo = SW_RADIO_OFF;
-                        }
-                    }
-                }
-            }
-            break;
-        case RT_OID_802_11_PHY_MODE:
-            if (wrq->u.data.length != sizeof(RT_802_11_PHY_MODE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&PhyMode, wrq->u.data.pointer, wrq->u.data.length);
-				if (PhyMode <= MaxPhyMode)
-				{
-                	RTMPSetPhyMode(pAdapter, PhyMode);
-#ifdef DOT11_N_SUPPORT
-					SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-				}
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_PHY_MODE (=%d)\n", PhyMode));
-            }
-            break;
-        case RT_OID_802_11_STA_CONFIG:
-            if (wrq->u.data.length != sizeof(RT_802_11_STA_CONFIG))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&StaConfig, wrq->u.data.pointer, wrq->u.data.length);
-                pAdapter->CommonCfg.bEnableTxBurst = StaConfig.EnableTxBurst;
-                pAdapter->CommonCfg.UseBGProtection = StaConfig.UseBGProtection;
-                pAdapter->CommonCfg.bUseShortSlotTime = 1; // 2003-10-30 always SHORT SLOT capable
-                if ((pAdapter->CommonCfg.PhyMode != StaConfig.AdhocMode) &&
-					(StaConfig.AdhocMode <= MaxPhyMode))
-                {
-                    // allow dynamic change of "USE OFDM rate or not" in ADHOC mode
-                    // if setting changed, need to reset current TX rate as well as BEACON frame format
-                    if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-                    {
-						pAdapter->CommonCfg.PhyMode = StaConfig.AdhocMode;
-                    	RTMPSetPhyMode(pAdapter, PhyMode);
-                        MlmeUpdateTxRates(pAdapter, FALSE, 0);
-                        MakeIbssBeacon(pAdapter);           // re-build BEACON frame
-                        AsicEnableIbssSync(pAdapter);   // copy to on-chip memory
-                    }
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_STA_CONFIG (Burst=%d, Protection=%ld,ShortSlot=%d\n",
-                                        pAdapter->CommonCfg.bEnableTxBurst,
-                                        pAdapter->CommonCfg.UseBGProtection,
-                                        pAdapter->CommonCfg.bUseShortSlotTime));
-            }
-            break;
-        case OID_802_11_DESIRED_RATES:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_RATES))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&aryRates, wrq->u.data.pointer, wrq->u.data.length);
-                NdisZeroMemory(pAdapter->CommonCfg.DesireRate, MAX_LEN_OF_SUPPORTED_RATES);
-                NdisMoveMemory(pAdapter->CommonCfg.DesireRate, &aryRates, sizeof(NDIS_802_11_RATES));
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DESIRED_RATES (%02x,%02x,%02x,%02x,%02x,%02x,%02x,%02x)\n",
-                    pAdapter->CommonCfg.DesireRate[0],pAdapter->CommonCfg.DesireRate[1],
-                    pAdapter->CommonCfg.DesireRate[2],pAdapter->CommonCfg.DesireRate[3],
-                    pAdapter->CommonCfg.DesireRate[4],pAdapter->CommonCfg.DesireRate[5],
-                    pAdapter->CommonCfg.DesireRate[6],pAdapter->CommonCfg.DesireRate[7] ));
-                // Changing DesiredRate may affect the MAX TX rate we used to TX frames out
-                MlmeUpdateTxRates(pAdapter, FALSE, 0);
-            }
-            break;
-        case RT_OID_802_11_PREAMBLE:
-            if (wrq->u.data.length != sizeof(RT_802_11_PREAMBLE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Preamble, wrq->u.data.pointer, wrq->u.data.length);
-                if (Preamble == Rt802_11PreambleShort)
-                {
-                    pAdapter->CommonCfg.TxPreamble = Preamble;
-                    MlmeSetTxPreamble(pAdapter, Rt802_11PreambleShort);
-                }
-                else if ((Preamble == Rt802_11PreambleLong) || (Preamble == Rt802_11PreambleAuto))
-                {
-                    // if user wants AUTO, initialize to LONG here, then change according to AP's
-                    // capability upon association.
-                    pAdapter->CommonCfg.TxPreamble = Preamble;
-                    MlmeSetTxPreamble(pAdapter, Rt802_11PreambleLong);
-                }
-                else
-                {
-                    Status = -EINVAL;
-                    break;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_PREAMBLE (=%d)\n", Preamble));
-            }
-            break;
-        case OID_802_11_WEP_STATUS:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_WEP_STATUS))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&WepStatus, wrq->u.data.pointer, wrq->u.data.length);
-                // Since TKIP, AES, WEP are all supported. It should not have any invalid setting
-                if (WepStatus <= Ndis802_11Encryption3KeyAbsent)
-                {
-                    if (pAdapter->StaCfg.WepStatus != WepStatus)
-                    {
-                        // Config has changed
-                        pAdapter->bConfigChanged = TRUE;
-                    }
-                    pAdapter->StaCfg.WepStatus     = WepStatus;
-                    pAdapter->StaCfg.OrigWepStatus = WepStatus;
-                    pAdapter->StaCfg.PairCipher    = WepStatus;
-                	pAdapter->StaCfg.GroupCipher   = WepStatus;
-                }
-                else
-                {
-                    Status  = -EINVAL;
-                    break;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEP_STATUS (=%d)\n",WepStatus));
-            }
-            break;
-        case OID_802_11_AUTHENTICATION_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_AUTHENTICATION_MODE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&AuthMode, wrq->u.data.pointer, wrq->u.data.length);
-                if (AuthMode > Ndis802_11AuthModeMax)
-                {
-                    Status  = -EINVAL;
-                    break;
-                }
-                else
-                {
-                    if (pAdapter->StaCfg.AuthMode != AuthMode)
-                    {
-                        // Config has changed
-                        pAdapter->bConfigChanged = TRUE;
-                    }
-                    pAdapter->StaCfg.AuthMode = AuthMode;
-                }
-                pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_AUTHENTICATION_MODE (=%d) \n",pAdapter->StaCfg.AuthMode));
-            }
-            break;
-        case OID_802_11_INFRASTRUCTURE_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_NETWORK_INFRASTRUCTURE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&BssType, wrq->u.data.pointer, wrq->u.data.length);
-
-				if (BssType == Ndis802_11IBSS)
-					Set_NetworkType_Proc(pAdapter, "Adhoc");
-				else if (BssType == Ndis802_11Infrastructure)
-					Set_NetworkType_Proc(pAdapter, "Infra");
-				else if (BssType == Ndis802_11Monitor)
-					Set_NetworkType_Proc(pAdapter, "Monitor");
-				else
-				{
-					Status  = -EINVAL;
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_INFRASTRUCTURE_MODE (unknown)\n"));
-				}
-			}
-			break;
-	 case OID_802_11_REMOVE_WEP:
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_WEP\n"));
-            if (wrq->u.data.length != sizeof(NDIS_802_11_KEY_INDEX))
-            {
-				Status = -EINVAL;
-            }
-            else
-            {
-				KeyIdx = *(NDIS_802_11_KEY_INDEX *) wrq->u.data.pointer;
-
-				if (KeyIdx & 0x80000000)
-				{
-					// Should never set default bit when remove key
-					Status = -EINVAL;
-				}
-				else
-				{
-					KeyIdx = KeyIdx & 0x0fffffff;
-					if (KeyIdx >= 4){
-						Status = -EINVAL;
-					}
-					else
-					{
-						pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = 0;
-						pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_NONE;
-						AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)KeyIdx);
-					}
-				}
-            }
-            break;
-        case RT_OID_802_11_RESET_COUNTERS:
-            NdisZeroMemory(&pAdapter->WlanCounters, sizeof(COUNTER_802_11));
-            NdisZeroMemory(&pAdapter->Counters8023, sizeof(COUNTER_802_3));
-            NdisZeroMemory(&pAdapter->RalinkCounters, sizeof(COUNTER_RALINK));
-            pAdapter->Counters8023.RxNoBuffer   = 0;
-			pAdapter->Counters8023.GoodReceives = 0;
-			pAdapter->Counters8023.RxNoBuffer   = 0;
-#ifdef RT2870
-			pAdapter->BulkOutComplete	= 0;
-			pAdapter->BulkOutCompleteOther= 0;
-			pAdapter->BulkOutCompleteCancel = 0;
-			pAdapter->BulkOutReq = 0;
-			pAdapter->BulkInReq= 0;
-			pAdapter->BulkInComplete = 0;
-			pAdapter->BulkInCompleteFail = 0;
-#endif // RT2870 //
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_RESET_COUNTERS \n"));
-            break;
-        case OID_802_11_RTS_THRESHOLD:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_RTS_THRESHOLD))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&RtsThresh, wrq->u.data.pointer, wrq->u.data.length);
-                if (RtsThresh > MAX_RTS_THRESHOLD)
-                    Status  = -EINVAL;
-                else
-                    pAdapter->CommonCfg.RtsThreshold = (USHORT)RtsThresh;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_RTS_THRESHOLD (=%ld)\n",RtsThresh));
-            break;
-        case OID_802_11_FRAGMENTATION_THRESHOLD:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_FRAGMENTATION_THRESHOLD))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&FragThresh, wrq->u.data.pointer, wrq->u.data.length);
-                pAdapter->CommonCfg.bUseZeroToDisableFragment = FALSE;
-                if (FragThresh > MAX_FRAG_THRESHOLD || FragThresh < MIN_FRAG_THRESHOLD)
-                {
-                    if (FragThresh == 0)
-                    {
-                        pAdapter->CommonCfg.FragmentThreshold = MAX_FRAG_THRESHOLD;
-                        pAdapter->CommonCfg.bUseZeroToDisableFragment = TRUE;
-                    }
-                    else
-                        Status  = -EINVAL;
-                }
-                else
-                    pAdapter->CommonCfg.FragmentThreshold = (USHORT)FragThresh;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_FRAGMENTATION_THRESHOLD (=%ld) \n",FragThresh));
-            break;
-        case OID_802_11_POWER_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_POWER_MODE))
-                Status = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&PowerMode, wrq->u.data.pointer, wrq->u.data.length);
-                if (PowerMode == Ndis802_11PowerModeCAM)
-                	Set_PSMode_Proc(pAdapter, "CAM");
-                else if (PowerMode == Ndis802_11PowerModeMAX_PSP)
-                	Set_PSMode_Proc(pAdapter, "Max_PSP");
-                else if (PowerMode == Ndis802_11PowerModeFast_PSP)
-					Set_PSMode_Proc(pAdapter, "Fast_PSP");
-                else if (PowerMode == Ndis802_11PowerModeLegacy_PSP)
-					Set_PSMode_Proc(pAdapter, "Legacy_PSP");
-                else
-                    Status = -EINVAL;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_POWER_MODE (=%d)\n",PowerMode));
-            break;
-         case RT_OID_802_11_TX_POWER_LEVEL_1:
-			if (wrq->u.data.length  < sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&PowerTemp, wrq->u.data.pointer, wrq->u.data.length);
-				if (PowerTemp > 100)
-					PowerTemp = 0xffffffff;  // AUTO
-				pAdapter->CommonCfg.TxPowerDefault = PowerTemp; //keep current setting.
-					pAdapter->CommonCfg.TxPowerPercentage = pAdapter->CommonCfg.TxPowerDefault;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_TX_POWER_LEVEL_1 (=%ld)\n", pAdapter->CommonCfg.TxPowerPercentage));
-			}
-	        break;
-		case OID_802_11_NETWORK_TYPE_IN_USE:
-			if (wrq->u.data.length != sizeof(NDIS_802_11_NETWORK_TYPE))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&NetType, wrq->u.data.pointer, wrq->u.data.length);
-
-				if (NetType == Ndis802_11DS)
-					RTMPSetPhyMode(pAdapter, PHY_11B);
-				else if (NetType == Ndis802_11OFDM24)
-					RTMPSetPhyMode(pAdapter, PHY_11BG_MIXED);
-				else if (NetType == Ndis802_11OFDM5)
-					RTMPSetPhyMode(pAdapter, PHY_11A);
-				else
-					Status = -EINVAL;
-#ifdef DOT11_N_SUPPORT
-				if (Status == NDIS_STATUS_SUCCESS)
-					SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_NETWORK_TYPE_IN_USE (=%d)\n",NetType));
-		    }
-			break;
-        // For WPA PSK PMK key
-        case RT_OID_802_11_ADD_WPA:
-            pKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-
-            Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA, Failed!!\n"));
-            }
-            else
-            {
-                if ((pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPAPSK) &&
-				    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-				    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone) )
-                {
-                    Status = -EOPNOTSUPP;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA, Failed!! [AuthMode != WPAPSK/WPA2PSK/WPANONE]\n"));
-                }
-                else if ((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-						 (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-						 (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPANone) )     // Only for WPA PSK mode
-				{
-                    NdisMoveMemory(pAdapter->StaCfg.PMK, &pKey->KeyMaterial, pKey->KeyLength);
-                    // Use RaConfig as PSK agent.
-                    // Start STA supplicant state machine
-                    if (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone)
-                        pAdapter->StaCfg.WpaState = SS_START;
-
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-                }
-                else
-                {
-                    pAdapter->StaCfg.WpaState = SS_NOTUSE;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-                }
-            }
-            kfree(pKey);
-            break;
-        case OID_802_11_REMOVE_KEY:
-            pRemoveKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pRemoveKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-
-            Status = copy_from_user(pRemoveKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pRemoveKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!\n"));
-            }
-            else
-            {
-                if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-                {
-                    RTMPWPARemoveKeyProc(pAdapter, pRemoveKey);
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Remove WPA Key!!\n"));
-                }
-                else
-                {
-                    KeyIdx = pRemoveKey->KeyIndex;
-
-                    if (KeyIdx & 0x80000000)
-                    {
-                        // Should never set default bit when remove key
-                        Status  = -EINVAL;
-                        DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!(Should never set default bit when remove key)\n"));
-                    }
-                    else
-                    {
-                        KeyIdx = KeyIdx & 0x0fffffff;
-                        if (KeyIdx > 3)
-                        {
-                            Status  = -EINVAL;
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!(KeyId[%d] out of range)\n", KeyIdx));
-                        }
-                        else
-                        {
-                            pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = 0;
-                            pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_NONE;
-                            AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)KeyIdx);
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY (id=0x%x, Len=%d-byte)\n", pRemoveKey->KeyIndex, pRemoveKey->Length));
-                        }
-                    }
-                }
-            }
-            kfree(pRemoveKey);
-            break;
-        // New for WPA
-        case OID_802_11_ADD_KEY:
-            pKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-            Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_KEY, Failed!!\n"));
-            }
-            else
-            {
-                RTMPAddKey(pAdapter, pKey);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_KEY (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-            }
-            kfree(pKey);
-            break;
-        case OID_802_11_CONFIGURATION:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_CONFIGURATION))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Config, wrq->u.data.pointer, wrq->u.data.length);
-                pConfig = &Config;
-
-                if ((pConfig->BeaconPeriod >= 20) && (pConfig->BeaconPeriod <=400))
-                     pAdapter->CommonCfg.BeaconPeriod = (USHORT) pConfig->BeaconPeriod;
-
-                pAdapter->StaActive.AtimWin = (USHORT) pConfig->ATIMWindow;
-                MAP_KHZ_TO_CHANNEL_ID(pConfig->DSConfig, pAdapter->CommonCfg.Channel);
-                //
-				// Save the channel on MlmeAux for CntlOidRTBssidProc used.
-				//
-				pAdapter->MlmeAux.Channel = pAdapter->CommonCfg.Channel;
-
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_CONFIGURATION (BeacnPeriod=%ld,AtimW=%ld,Ch=%d)\n",
-                    pConfig->BeaconPeriod, pConfig->ATIMWindow, pAdapter->CommonCfg.Channel));
-                // Config has changed
-                pAdapter->bConfigChanged = TRUE;
-            }
-            break;
-#ifdef DOT11_N_SUPPORT
-		case RT_OID_802_11_SET_HT_PHYMODE:
-			if (wrq->u.data.length	!= sizeof(OID_SET_HT_PHYMODE))
-				Status = -EINVAL;
-			else
-			{
-			    POID_SET_HT_PHYMODE	pHTPhyMode = &HT_PhyMode;
-
-				Status = copy_from_user(&HT_PhyMode, wrq->u.data.pointer, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::pHTPhyMode	(PhyMode = %d,TransmitNo = %d, HtMode =	%d,	ExtOffset =	%d , MCS = %d, BW =	%d,	STBC = %d, SHORTGI = %d) \n",
-				pHTPhyMode->PhyMode, pHTPhyMode->TransmitNo,pHTPhyMode->HtMode,pHTPhyMode->ExtOffset,
-				pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC,	pHTPhyMode->SHORTGI));
-				if (pAdapter->CommonCfg.PhyMode	>= PHY_11ABGN_MIXED)
-					RTMPSetHT(pAdapter,	pHTPhyMode);
-			}
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_HT_PHYMODE(MCS=%d,BW=%d,SGI=%d,STBC=%d)\n",
-				pAdapter->StaCfg.HTPhyMode.field.MCS, pAdapter->StaCfg.HTPhyMode.field.BW, pAdapter->StaCfg.HTPhyMode.field.ShortGI,
-				pAdapter->StaCfg.HTPhyMode.field.STBC));
-			break;
-#endif // DOT11_N_SUPPORT //
-		case RT_OID_802_11_SET_APSD_SETTING:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				ULONG apsd ;
-				Status = copy_from_user(&apsd, wrq->u.data.pointer,	wrq->u.data.length);
-
-				/*-------------------------------------------------------------------
-				|B31~B7	|	B6~B5	 |	 B4	 |	 B3	 |	B2	 |	B1	 |	   B0		|
-				---------------------------------------------------------------------
-				| Rsvd	| Max SP Len | AC_VO | AC_VI | AC_BK | AC_BE | APSD	Capable	|
-				---------------------------------------------------------------------*/
-				pAdapter->CommonCfg.bAPSDCapable = (apsd & 0x00000001) ? TRUE :	FALSE;
-				pAdapter->CommonCfg.bAPSDAC_BE = ((apsd	& 0x00000002) >> 1)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_BK = ((apsd	& 0x00000004) >> 2)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_VI = ((apsd	& 0x00000008) >> 3)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_VO = ((apsd	& 0x00000010) >> 4)	? TRUE : FALSE;
-				pAdapter->CommonCfg.MaxSPLength	= (UCHAR)((apsd	& 0x00000060) >> 5);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_APSD_SETTING (apsd=0x%lx, APSDCap=%d, [BE,BK,VI,VO]=[%d/%d/%d/%d],	MaxSPLen=%d)\n", apsd, pAdapter->CommonCfg.bAPSDCapable,
-					pAdapter->CommonCfg.bAPSDAC_BE,	pAdapter->CommonCfg.bAPSDAC_BK,	pAdapter->CommonCfg.bAPSDAC_VI,	pAdapter->CommonCfg.bAPSDAC_VO,	pAdapter->CommonCfg.MaxSPLength));
-			}
-			break;
-
-		case RT_OID_802_11_SET_APSD_PSM:
-			if (wrq->u.data.length	!= sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				// Driver needs	to notify AP when PSM changes
-				Status = copy_from_user(&pAdapter->CommonCfg.bAPSDForcePowerSave, wrq->u.data.pointer, wrq->u.data.length);
-				if (pAdapter->CommonCfg.bAPSDForcePowerSave	!= pAdapter->StaCfg.Psm)
-				{
-					MlmeSetPsmBit(pAdapter,	pAdapter->CommonCfg.bAPSDForcePowerSave);
-					RTMPSendNullFrame(pAdapter,	pAdapter->CommonCfg.TxRate,	TRUE);
-				}
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_APSD_PSM (bAPSDForcePowerSave:%d)\n",	pAdapter->CommonCfg.bAPSDForcePowerSave));
-			}
-			break;
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_SET_DLS:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				BOOLEAN	oldvalue = pAdapter->CommonCfg.bDLSCapable;
-				Status = copy_from_user(&pAdapter->CommonCfg.bDLSCapable, wrq->u.data.pointer, wrq->u.data.length);
-				if (oldvalue &&	!pAdapter->CommonCfg.bDLSCapable)
-				{
-					int	i;
-					// tear	down local dls table entry
-					for	(i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-					{
-						if (pAdapter->StaCfg.DLSEntry[i].Valid && (pAdapter->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-						{
-							pAdapter->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-							pAdapter->StaCfg.DLSEntry[i].Valid	= FALSE;
-							RTMPSendDLSTearDownFrame(pAdapter, pAdapter->StaCfg.DLSEntry[i].MacAddr);
-						}
-					}
-
-					// tear	down peer dls table	entry
-					for	(i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-					{
-						if (pAdapter->StaCfg.DLSEntry[i].Valid && (pAdapter->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-						{
-							pAdapter->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-							pAdapter->StaCfg.DLSEntry[i].Valid	= FALSE;
-							RTMPSendDLSTearDownFrame(pAdapter, pAdapter->StaCfg.DLSEntry[i].MacAddr);
-						}
-					}
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE,("Set::RT_OID_802_11_SET_DLS (=%d)\n", pAdapter->CommonCfg.bDLSCapable));
-			}
-			break;
-
-		case RT_OID_802_11_SET_DLS_PARAM:
-			if (wrq->u.data.length	!= sizeof(RT_802_11_DLS_UI))
-				Status = -EINVAL;
-			else
-			{
-				RT_802_11_DLS	Dls;
-
-				NdisZeroMemory(&Dls, sizeof(RT_802_11_DLS));
-				RTMPMoveMemory(&Dls, wrq->u.data.pointer, sizeof(RT_802_11_DLS_UI));
-				MlmeEnqueue(pAdapter,
-							MLME_CNTL_STATE_MACHINE,
-							RT_OID_802_11_SET_DLS_PARAM,
-							sizeof(RT_802_11_DLS),
-							&Dls);
-				DBGPRINT(RT_DEBUG_TRACE,("Set::RT_OID_802_11_SET_DLS_PARAM \n"));
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-		case RT_OID_802_11_SET_WMM:
-			if (wrq->u.data.length	!= sizeof(BOOLEAN))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&pAdapter->CommonCfg.bWmmCapable, wrq->u.data.pointer, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_WMM (=%d)	\n", pAdapter->CommonCfg.bWmmCapable));
-			}
-			break;
-
-		case OID_802_11_DISASSOCIATE:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-			//
-			// Set NdisRadioStateOff to	TRUE, instead of called	MlmeRadioOff.
-			// Later on, NDIS_802_11_BSSID_LIST_EX->NumberOfItems should be	0
-			// when	query OID_802_11_BSSID_LIST.
-			//
-			// TRUE:  NumberOfItems	will set to	0.
-			// FALSE: NumberOfItems	no change.
-			//
-			pAdapter->CommonCfg.NdisRadioStateOff =	TRUE;
-			// Set to immediately send the media disconnect	event
-			pAdapter->MlmeAux.CurrReqIsFromNdis	= TRUE;
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DISASSOCIATE	\n"));
-
-			if (INFRA_ON(pAdapter))
-			{
-				if (pAdapter->Mlme.CntlMachine.CurrState !=	CNTL_IDLE)
-				{
-					RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-					DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME	busy, reset	MLME state machine !!!\n"));
-				}
-
-				MlmeEnqueue(pAdapter,
-					MLME_CNTL_STATE_MACHINE,
-					OID_802_11_DISASSOCIATE,
-					0,
-					NULL);
-
-				StateMachineTouched	= TRUE;
-			}
-			break;
-
-#ifdef DOT11_N_SUPPORT
-		case RT_OID_802_11_SET_IMME_BA_CAP:
-				if (wrq->u.data.length != sizeof(OID_BACAP_STRUC))
-					Status = -EINVAL;
-				else
-				{
-					OID_BACAP_STRUC Orde ;
-					Status = copy_from_user(&Orde, wrq->u.data.pointer, wrq->u.data.length);
-					if (Orde.Policy > BA_NOTUSE)
-					{
-						Status = NDIS_STATUS_INVALID_DATA;
-					}
-					else if (Orde.Policy == BA_NOTUSE)
-					{
-						pAdapter->CommonCfg.BACapability.field.Policy = BA_NOTUSE;
-						pAdapter->CommonCfg.BACapability.field.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable = Orde.AmsduEnable;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize= Orde.AmsduSize;
-						pAdapter->CommonCfg.DesiredHtPhy.MimoPs= Orde.MMPSmode;
-						pAdapter->CommonCfg.BACapability.field.MMPSmode = Orde.MMPSmode;
-						// UPdata to HT IE
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.AMsduSize = Orde.AmsduSize;
-						pAdapter->CommonCfg.HtCapability.HtCapParm.MpduDensity = Orde.MpduDensity;
-					}
-					else
-					{
-                        pAdapter->CommonCfg.BACapability.field.AutoBA = Orde.AutoBA;
-						pAdapter->CommonCfg.BACapability.field.Policy = IMMED_BA; // we only support immediate BA.
-						pAdapter->CommonCfg.BACapability.field.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable = Orde.AmsduEnable;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize= Orde.AmsduSize;
-						pAdapter->CommonCfg.DesiredHtPhy.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.BACapability.field.MMPSmode = Orde.MMPSmode;
-
-						// UPdata to HT IE
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.AMsduSize = Orde.AmsduSize;
-						pAdapter->CommonCfg.HtCapability.HtCapParm.MpduDensity = Orde.MpduDensity;
-
-						if (pAdapter->CommonCfg.BACapability.field.RxBAWinLimit > MAX_RX_REORDERBUF)
-							pAdapter->CommonCfg.BACapability.field.RxBAWinLimit = MAX_RX_REORDERBUF;
-
-					}
-
-					pAdapter->CommonCfg.REGBACapability.word = pAdapter->CommonCfg.BACapability.word;
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::(Orde.AutoBA = %d) (Policy=%d)(ReBAWinLimit=%d)(TxBAWinLimit=%d)(AutoMode=%d)\n",Orde.AutoBA, pAdapter->CommonCfg.BACapability.field.Policy,
-						pAdapter->CommonCfg.BACapability.field.RxBAWinLimit,pAdapter->CommonCfg.BACapability.field.TxBAWinLimit, pAdapter->CommonCfg.BACapability.field.AutoBA));
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::(MimoPs = %d)(AmsduEnable = %d) (AmsduSize=%d)(MpduDensity=%d)\n",pAdapter->CommonCfg.DesiredHtPhy.MimoPs, pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable,
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize, pAdapter->CommonCfg.DesiredHtPhy.MpduDensity));
-				}
-
-				break;
-		case RT_OID_802_11_ADD_IMME_BA:
-			DBGPRINT(RT_DEBUG_TRACE, (" Set :: RT_OID_802_11_ADD_IMME_BA \n"));
-			if (wrq->u.data.length != sizeof(OID_ADD_BA_ENTRY))
-					Status = -EINVAL;
-			else
-			{
-				UCHAR		        index;
-				OID_ADD_BA_ENTRY    BA;
-				MAC_TABLE_ENTRY     *pEntry;
-
-				Status = copy_from_user(&BA, wrq->u.data.pointer, wrq->u.data.length);
-				if (BA.TID > 15)
-				{
-					Status = NDIS_STATUS_INVALID_DATA;
-					break;
-				}
-				else
-				{
-					//BATableInsertEntry
-					//As ad-hoc mode, BA pair is not limited to only BSSID. so add via OID.
-					index = BA.TID;
-					// in ad hoc mode, when adding BA pair, we should insert this entry into MACEntry too
-					pEntry = MacTableLookup(pAdapter, BA.MACAddr);
-					if (!pEntry)
-					{
-						DBGPRINT(RT_DEBUG_TRACE, ("RT_OID_802_11_ADD_IMME_BA. break on no connection.----:%x:%x\n", BA.MACAddr[4], BA.MACAddr[5]));
-						break;
-					}
-					if (BA.IsRecipient == FALSE)
-					{
-					    if (pEntry->bIAmBadAtheros == TRUE)
-							pAdapter->CommonCfg.BACapability.field.RxBAWinLimit = 0x10;
-
-						BAOriSessionSetUp(pAdapter, pEntry, index, 0, 100, TRUE);
-					}
-					else
-					{
-						//BATableInsertEntry(pAdapter, pEntry->Aid, BA.MACAddr, 0, 0xffff, BA.TID, BA.nMSDU, BA.IsRecipient);
-					}
-
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_IMME_BA. Rec = %d. Mac = %x:%x:%x:%x:%x:%x . \n",
-						BA.IsRecipient, BA.MACAddr[0], BA.MACAddr[1], BA.MACAddr[2], BA.MACAddr[2]
-						, BA.MACAddr[4], BA.MACAddr[5]));
-				}
-			}
-			break;
-
-		case RT_OID_802_11_TEAR_IMME_BA:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA \n"));
-			if (wrq->u.data.length != sizeof(OID_ADD_BA_ENTRY))
-					Status = -EINVAL;
-			else
-			{
-				POID_ADD_BA_ENTRY	pBA;
-				MAC_TABLE_ENTRY *pEntry;
-
-				pBA = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-				if (pBA == NULL)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA kmalloc() can't allocate enough memory\n"));
-					Status = NDIS_STATUS_FAILURE;
-				}
-				else
-				{
-					Status = copy_from_user(pBA, wrq->u.data.pointer, wrq->u.data.length);
-					DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA(TID=%d, bAllTid=%d)\n", pBA->TID, pBA->bAllTid));
-
-					if (!pBA->bAllTid && (pBA->TID > NUM_OF_TID))
-					{
-						Status = NDIS_STATUS_INVALID_DATA;
-						break;
-					}
-
-					if (pBA->IsRecipient == FALSE)
-					{
-						pEntry = MacTableLookup(pAdapter, pBA->MACAddr);
-						DBGPRINT(RT_DEBUG_TRACE, (" pBA->IsRecipient == FALSE\n"));
-						if (pEntry)
-						{
-							DBGPRINT(RT_DEBUG_TRACE, (" pBA->pEntry\n"));
-							BAOriSessionTearDown(pAdapter, pEntry->Aid, pBA->TID, FALSE, TRUE);
-						}
-						else
-							DBGPRINT(RT_DEBUG_TRACE, ("Set :: Not found pEntry \n"));
-					}
-					else
-					{
-						pEntry = MacTableLookup(pAdapter, pBA->MACAddr);
-						if (pEntry)
-						{
-							BARecSessionTearDown( pAdapter, (UCHAR)pEntry->Aid, pBA->TID, TRUE);
-						}
-						else
-							DBGPRINT(RT_DEBUG_TRACE, ("Set :: Not found pEntry \n"));
-					}
-					kfree(pBA);
-				}
-            }
-            break;
-#endif // DOT11_N_SUPPORT //
-
-        // For WPA_SUPPLICANT to set static wep key
-    	case OID_802_11_ADD_WEP:
-    	    pWepKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-    	    if(pWepKey == NULL)
-            {
-                Status = -ENOMEM;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed!!\n"));
-                break;
-            }
-            Status = copy_from_user(pWepKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (Status)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed (length mismatch)!!\n"));
-            }
-            else
-            {
-		        KeyIdx = pWepKey->KeyIndex & 0x0fffffff;
-                // KeyIdx must be 0 ~ 3
-                if (KeyIdx > 4)
-    			{
-                    Status  = -EINVAL;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed (KeyIdx must be smaller than 4)!!\n"));
-                }
-                else
-                {
-                    UCHAR CipherAlg = 0;
-                    PUCHAR Key;
-
-                    // set key material and key length
-                    NdisZeroMemory(pAdapter->SharedKey[BSS0][KeyIdx].Key, 16);
-                    pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = (UCHAR) pWepKey->KeyLength;
-                    NdisMoveMemory(pAdapter->SharedKey[BSS0][KeyIdx].Key, &pWepKey->KeyMaterial, pWepKey->KeyLength);
-
-                    switch(pWepKey->KeyLength)
-                    {
-                        case 5:
-                            CipherAlg = CIPHER_WEP64;
-                            break;
-                        case 13:
-                            CipherAlg = CIPHER_WEP128;
-                            break;
-                        default:
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, only support CIPHER_WEP64(len:5) & CIPHER_WEP128(len:13)!!\n"));
-                            Status = -EINVAL;
-                            break;
-                    }
-                    pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CipherAlg;
-
-                    // Default key for tx (shared key)
-                    if (pWepKey->KeyIndex & 0x80000000)
-                    {
-#ifdef WPA_SUPPLICANT_SUPPORT
-                        // set key material and key length
-                        NdisZeroMemory(pAdapter->StaCfg.DesireSharedKey[KeyIdx].Key, 16);
-                        pAdapter->StaCfg.DesireSharedKey[KeyIdx].KeyLen = (UCHAR) pWepKey->KeyLength;
-                        NdisMoveMemory(pAdapter->StaCfg.DesireSharedKey[KeyIdx].Key, &pWepKey->KeyMaterial, pWepKey->KeyLength);
-                        pAdapter->StaCfg.DesireSharedKeyId = KeyIdx;
-                        pAdapter->StaCfg.DesireSharedKey[KeyIdx].CipherAlg = CipherAlg;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                        pAdapter->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-                    }
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-                    if (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED)
-#endif // WPA_SUPPLICANT_SUPPORT
-                    {
-                        Key = pAdapter->SharedKey[BSS0][KeyIdx].Key;
-
-                        // Set key material and cipherAlg to Asic
-        				AsicAddSharedKeyEntry(pAdapter, BSS0, KeyIdx, CipherAlg, Key, NULL, NULL);
-
-                        if (pWepKey->KeyIndex & 0x80000000)
-                        {
-                            PMAC_TABLE_ENTRY pEntry = &pAdapter->MacTab.Content[BSSID_WCID];
-                            // Assign group key info
-    						RTMPAddWcidAttributeEntry(pAdapter, BSS0, KeyIdx, CipherAlg, NULL);
-    						// Assign pairwise key info
-    						RTMPAddWcidAttributeEntry(pAdapter, BSS0, KeyIdx, CipherAlg, pEntry);
-                        }
-                    }
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP (id=0x%x, Len=%d-byte), %s\n", pWepKey->KeyIndex, pWepKey->KeyLength, (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED) ? "Port Secured":"Port NOT Secured"));
-				}
-            }
-            kfree(pWepKey);
-            break;
-#ifdef WPA_SUPPLICANT_SUPPORT
-	    case OID_SET_COUNTERMEASURES:
-            if (wrq->u.data.length != sizeof(int))
-                Status  = -EINVAL;
-            else
-            {
-                int enabled = 0;
-                Status = copy_from_user(&enabled, wrq->u.data.pointer, wrq->u.data.length);
-                if (enabled == 1)
-                    pAdapter->StaCfg.bBlockAssoc = TRUE;
-                else
-                    // WPA MIC error should block association attempt for 60 seconds
-                    pAdapter->StaCfg.bBlockAssoc = FALSE;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_SET_COUNTERMEASURES bBlockAssoc=%s\n", pAdapter->StaCfg.bBlockAssoc ? "TRUE":"FALSE"));
-            }
-	        break;
-        case RT_OID_WPA_SUPPLICANT_SUPPORT:
-			if (wrq->u.data.length != sizeof(UCHAR))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&wpa_supplicant_enable, wrq->u.data.pointer, wrq->u.data.length);
-    			pAdapter->StaCfg.WpaSupplicantUP = wpa_supplicant_enable;
-    			DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_WPA_SUPPLICANT_SUPPORT (=%d)\n", pAdapter->StaCfg.WpaSupplicantUP));
-			}
-            break;
-        case OID_802_11_DEAUTHENTICATION:
-            if (wrq->u.data.length != sizeof(MLME_DEAUTH_REQ_STRUCT))
-                Status  = -EINVAL;
-            else
-            {
-                MLME_DEAUTH_REQ_STRUCT      *pInfo;
-				MLME_QUEUE_ELEM *MsgElem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-
-                pInfo = (MLME_DEAUTH_REQ_STRUCT *) MsgElem->Msg;
-                Status = copy_from_user(pInfo, wrq->u.data.pointer, wrq->u.data.length);
-                MlmeDeauthReqAction(pAdapter, MsgElem);
-				kfree(MsgElem);
-
-                if (INFRA_ON(pAdapter))
-                {
-                    LinkDown(pAdapter, FALSE);
-                    pAdapter->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DEAUTHENTICATION (Reason=%d)\n", pInfo->Reason));
-            }
-            break;
-        case OID_802_11_DROP_UNENCRYPTED:
-            if (wrq->u.data.length != sizeof(int))
-                Status  = -EINVAL;
-            else
-            {
-                int enabled = 0;
-                Status = copy_from_user(&enabled, wrq->u.data.pointer, wrq->u.data.length);
-                if (enabled == 1)
-                    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-                else
-                    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				NdisAcquireSpinLock(&pAdapter->MacTabLock);
-				pAdapter->MacTab.Content[BSSID_WCID].PortSecured = pAdapter->StaCfg.PortSecured;
-				NdisReleaseSpinLock(&pAdapter->MacTabLock);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DROP_UNENCRYPTED (=%d)\n", enabled));
-            }
-            break;
-        case OID_802_11_SET_IEEE8021X:
-            if (wrq->u.data.length != sizeof(BOOLEAN))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&IEEE8021xState, wrq->u.data.pointer, wrq->u.data.length);
-		        pAdapter->StaCfg.IEEE8021X = IEEE8021xState;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SET_IEEE8021X (=%d)\n", IEEE8021xState));
-            }
-            break;
-        case OID_802_11_SET_IEEE8021X_REQUIRE_KEY:
-			if (wrq->u.data.length != sizeof(BOOLEAN))
-				 Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&IEEE8021x_required_keys, wrq->u.data.pointer, wrq->u.data.length);
-				pAdapter->StaCfg.IEEE8021x_required_keys = IEEE8021x_required_keys;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SET_IEEE8021X_REQUIRE_KEY (%d)\n", IEEE8021x_required_keys));
-			}
-			break;
-        case OID_802_11_PMKID:
-	        pPmkId = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-	        if(pPmkId == NULL) {
-                Status = -ENOMEM;
-                break;
-            }
-            Status = copy_from_user(pPmkId, wrq->u.data.pointer, wrq->u.data.length);
-
-	        // check the PMKID information
-	        if (pPmkId->BSSIDInfoCount == 0)
-                NdisZeroMemory(pAdapter->StaCfg.SavedPMK, sizeof(BSSID_INFO)*PMKID_NO);
-	        else
-	        {
-		        PBSSID_INFO	pBssIdInfo;
-		        UINT		BssIdx;
-		        UINT		CachedIdx;
-
-		        for (BssIdx = 0; BssIdx < pPmkId->BSSIDInfoCount; BssIdx++)
-		        {
-			        // point to the indexed BSSID_INFO structure
-			        pBssIdInfo = (PBSSID_INFO) ((PUCHAR) pPmkId + 2 * sizeof(UINT) + BssIdx * sizeof(BSSID_INFO));
-			        // Find the entry in the saved data base.
-			        for (CachedIdx = 0; CachedIdx < pAdapter->StaCfg.SavedPMKNum; CachedIdx++)
-			        {
-				        // compare the BSSID
-				        if (NdisEqualMemory(pBssIdInfo->BSSID, pAdapter->StaCfg.SavedPMK[CachedIdx].BSSID, sizeof(NDIS_802_11_MAC_ADDRESS)))
-					        break;
-			        }
-
-			        // Found, replace it
-			        if (CachedIdx < PMKID_NO)
-			        {
-				        DBGPRINT(RT_DEBUG_OFF, ("Update OID_802_11_PMKID, idx = %d\n", CachedIdx));
-				        NdisMoveMemory(&pAdapter->StaCfg.SavedPMK[CachedIdx], pBssIdInfo, sizeof(BSSID_INFO));
-				        pAdapter->StaCfg.SavedPMKNum++;
-			        }
-			        // Not found, replace the last one
-			        else
-			        {
-				        // Randomly replace one
-				        CachedIdx = (pBssIdInfo->BSSID[5] % PMKID_NO);
-				        DBGPRINT(RT_DEBUG_OFF, ("Update OID_802_11_PMKID, idx = %d\n", CachedIdx));
-				        NdisMoveMemory(&pAdapter->StaCfg.SavedPMK[CachedIdx], pBssIdInfo, sizeof(BSSID_INFO));
-			        }
-		        }
-			}
-			if(pPmkId)
-				kfree(pPmkId);
-	        break;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-
-#ifdef SNMP_SUPPORT
-		case OID_802_11_SHORTRETRYLIMIT:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&ShortRetryLimit, wrq->u.data.pointer, wrq->u.data.length);
-				RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-				tx_rty_cfg.field.ShortRtyLimit = ShortRetryLimit;
-				RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SHORTRETRYLIMIT (tx_rty_cfg.field.ShortRetryLimit=%d, ShortRetryLimit=%ld)\n", tx_rty_cfg.field.ShortRtyLimit, ShortRetryLimit));
-			}
-			break;
-
-		case OID_802_11_LONGRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_LONGRETRYLIMIT \n"));
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&LongRetryLimit, wrq->u.data.pointer, wrq->u.data.length);
-				RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-				tx_rty_cfg.field.LongRtyLimit = LongRetryLimit;
-				RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_LONGRETRYLIMIT (tx_rty_cfg.field.LongRetryLimit= %d,LongRetryLimit=%ld)\n", tx_rty_cfg.field.LongRtyLimit, LongRetryLimit));
-			}
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYVALUE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYVALUE\n"));
-			pKey = kmalloc(wrq->u.data.length, GFP_KERNEL);
-			Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-			//pKey = &WepKey;
-
-			if ( pKey->Length != wrq->u.data.length)
-			{
-				Status = -EINVAL;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYVALUE, Failed!!\n"));
-			}
-			KeyIdx = pKey->KeyIndex & 0x0fffffff;
-			DBGPRINT(RT_DEBUG_TRACE,("pKey->KeyIndex =%d, pKey->KeyLength=%d\n", pKey->KeyIndex, pKey->KeyLength));
-
-			// it is a shared key
-			if (KeyIdx > 4)
-				Status = -EINVAL;
-			else
-			{
-				pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen = (UCHAR) pKey->KeyLength;
-				NdisMoveMemory(&pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key, &pKey->KeyMaterial, pKey->KeyLength);
-				if (pKey->KeyIndex & 0x80000000)
-				{
-					// Default key for tx (shared key)
-					pAdapter->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-				}
-				//RestartAPIsRequired = TRUE;
-			}
-			break;
-
-
-		case OID_802_11_WEPDEFAULTKEYID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYID \n"));
-
-			if (wrq->u.data.length != sizeof(UCHAR))
-				Status = -EINVAL;
-			else
-				Status = copy_from_user(&pAdapter->StaCfg.DefaultKeyId, wrq->u.data.pointer, wrq->u.data.length);
-
-			break;
-
-
-		case OID_802_11_CURRENTCHANNEL:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_CURRENTCHANNEL \n"));
-			if (wrq->u.data.length != sizeof(UCHAR))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&ctmp, wrq->u.data.pointer, wrq->u.data.length);
-				sprintf(&ctmp,"%d", ctmp);
-				Set_Channel_Proc(pAdapter, &ctmp);
-			}
-			break;
-#endif
-
-
-
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::unknown IOCTL's subcmd = 0x%08x\n", cmd));
-            Status = -EOPNOTSUPP;
-            break;
-    }
-
-
-    return Status;
-}
-
-INT RTMPQueryInformation(
-    IN  PRTMP_ADAPTER pAdapter,
-    IN  OUT struct ifreq    *rq,
-    IN  INT                 cmd)
-{
-    struct iwreq                        *wrq = (struct iwreq *) rq;
-    NDIS_802_11_BSSID_LIST_EX           *pBssidList = NULL;
-    PNDIS_WLAN_BSSID_EX                 pBss;
-    NDIS_802_11_SSID                    Ssid;
-    NDIS_802_11_CONFIGURATION           *pConfiguration = NULL;
-    RT_802_11_LINK_STATUS               *pLinkStatus = NULL;
-    RT_802_11_STA_CONFIG                *pStaConfig = NULL;
-    NDIS_802_11_STATISTICS              *pStatistics = NULL;
-    NDIS_802_11_RTS_THRESHOLD           RtsThresh;
-    NDIS_802_11_FRAGMENTATION_THRESHOLD FragThresh;
-    NDIS_802_11_POWER_MODE              PowerMode;
-    NDIS_802_11_NETWORK_INFRASTRUCTURE  BssType;
-    RT_802_11_PREAMBLE                  PreamType;
-    NDIS_802_11_AUTHENTICATION_MODE     AuthMode;
-    NDIS_802_11_WEP_STATUS              WepStatus;
-    NDIS_MEDIA_STATE                    MediaState;
-    ULONG                               BssBufSize, ulInfo=0, NetworkTypeList[4], apsd = 0;
-    USHORT                              BssLen = 0;
-    PUCHAR                              pBuf = NULL, pPtr;
-    INT                                 Status = NDIS_STATUS_SUCCESS;
-    UINT                                we_version_compiled;
-    UCHAR                               i, Padding = 0;
-    BOOLEAN                             RadioState;
-	UCHAR	driverVersion[8];
-    OID_SET_HT_PHYMODE			        *pHTPhyMode = NULL;
-
-
-#ifdef SNMP_SUPPORT
-	//for snmp, kathy
-	DefaultKeyIdxValue			*pKeyIdxValue;
-	INT							valueLen;
-	TX_RTY_CFG_STRUC			tx_rty_cfg;
-	ULONG						ShortRetryLimit, LongRetryLimit;
-	UCHAR						tmp[64];
-#endif //SNMP
-
-    switch(cmd)
-    {
-        case RT_OID_DEVICE_NAME:
-            wrq->u.data.length = sizeof(STA_NIC_DEVICE_NAME);
-            Status = copy_to_user(wrq->u.data.pointer, STA_NIC_DEVICE_NAME, wrq->u.data.length);
-            break;
-        case RT_OID_VERSION_INFO:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_VERSION_INFO \n"));
-			wrq->u.data.length = 8*sizeof(UCHAR);
-			sprintf(&driverVersion[0], "%s", STA_DRIVER_VERSION);
-			driverVersion[7] = '\0';
-			if (copy_to_user(wrq->u.data.pointer, &driverVersion, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            break;
-#ifdef RALINK_ATE
-		case RT_QUERY_ATE_TXDONE_COUNT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_QUERY_ATE_TXDONE_COUNT \n"));
-			wrq->u.data.length = sizeof(UINT32);
-			if (copy_to_user(wrq->u.data.pointer, &pAdapter->ate.TxDoneCount, wrq->u.data.length))
-			{
-				Status = -EFAULT;
-			}
-			break;
-#endif // RALINK_ATE //
-        case OID_802_11_BSSID_LIST:
-            if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-            	/*
-            	 * Still scanning, indicate the caller should try again.
-            	 */
-            	DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID_LIST (Still scanning)\n"));
-				return -EAGAIN;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID_LIST (%d BSS returned)\n",pAdapter->ScanTab.BssNr));
-			pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-            // Claculate total buffer size required
-            BssBufSize = sizeof(ULONG);
-
-            for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-            {
-                // Align pointer to 4 bytes boundary.
-                //Padding = 4 - (pAdapter->ScanTab.BssEntry[i].VarIELen & 0x0003);
-                //if (Padding == 4)
-                //    Padding = 0;
-                BssBufSize += (sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen + Padding);
-            }
-
-            // For safety issue, we add 256 bytes just in case
-            BssBufSize += 256;
-            // Allocate the same size as passed from higher layer
-            pBuf = kmalloc(BssBufSize, MEM_ALLOC_FLAG);
-            if(pBuf == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-            // Init 802_11_BSSID_LIST_EX structure
-            NdisZeroMemory(pBuf, BssBufSize);
-            pBssidList = (PNDIS_802_11_BSSID_LIST_EX) pBuf;
-            pBssidList->NumberOfItems = pAdapter->ScanTab.BssNr;
-
-            // Calculate total buffer length
-            BssLen = 4; // Consist of NumberOfItems
-            // Point to start of NDIS_WLAN_BSSID_EX
-            // pPtr = pBuf + sizeof(ULONG);
-            pPtr = (PUCHAR) &pBssidList->Bssid[0];
-            for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-            {
-                pBss = (PNDIS_WLAN_BSSID_EX) pPtr;
-                NdisMoveMemory(&pBss->MacAddress, &pAdapter->ScanTab.BssEntry[i].Bssid, MAC_ADDR_LEN);
-                if ((pAdapter->ScanTab.BssEntry[i].Hidden == 1) && (pAdapter->StaCfg.bShowHiddenSSID == FALSE))
-                {
-                    //
-					// We must return this SSID during 4way handshaking, otherwise Aegis will failed to parse WPA infomation
-					// and then failed to send EAPOl farame.
-					//
-					if ((pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA) && (pAdapter->StaCfg.PortSecured != WPA_802_1X_PORT_SECURED))
-					{
-						pBss->Ssid.SsidLength = pAdapter->ScanTab.BssEntry[i].SsidLen;
-						NdisMoveMemory(pBss->Ssid.Ssid, pAdapter->ScanTab.BssEntry[i].Ssid, pAdapter->ScanTab.BssEntry[i].SsidLen);
-					}
-					else
-                    	pBss->Ssid.SsidLength = 0;
-                }
-                else
-                {
-                    pBss->Ssid.SsidLength = pAdapter->ScanTab.BssEntry[i].SsidLen;
-                    NdisMoveMemory(pBss->Ssid.Ssid, pAdapter->ScanTab.BssEntry[i].Ssid, pAdapter->ScanTab.BssEntry[i].SsidLen);
-                }
-                pBss->Privacy = pAdapter->ScanTab.BssEntry[i].Privacy;
-                pBss->Rssi = pAdapter->ScanTab.BssEntry[i].Rssi - pAdapter->BbpRssiToDbmDelta;
-                pBss->NetworkTypeInUse = NetworkTypeInUseSanity(&pAdapter->ScanTab.BssEntry[i]);
-                pBss->Configuration.Length = sizeof(NDIS_802_11_CONFIGURATION);
-                pBss->Configuration.BeaconPeriod = pAdapter->ScanTab.BssEntry[i].BeaconPeriod;
-                pBss->Configuration.ATIMWindow = pAdapter->ScanTab.BssEntry[i].AtimWin;
-
-                MAP_CHANNEL_ID_TO_KHZ(pAdapter->ScanTab.BssEntry[i].Channel, pBss->Configuration.DSConfig);
-
-                if (pAdapter->ScanTab.BssEntry[i].BssType == BSS_INFRA)
-                    pBss->InfrastructureMode = Ndis802_11Infrastructure;
-                else
-                    pBss->InfrastructureMode = Ndis802_11IBSS;
-
-                NdisMoveMemory(pBss->SupportedRates, pAdapter->ScanTab.BssEntry[i].SupRate, pAdapter->ScanTab.BssEntry[i].SupRateLen);
-                NdisMoveMemory(pBss->SupportedRates + pAdapter->ScanTab.BssEntry[i].SupRateLen,
-                               pAdapter->ScanTab.BssEntry[i].ExtRate,
-                               pAdapter->ScanTab.BssEntry[i].ExtRateLen);
-
-                if (pAdapter->ScanTab.BssEntry[i].VarIELen == 0)
-                {
-                    pBss->IELength = sizeof(NDIS_802_11_FIXED_IEs);
-                    NdisMoveMemory(pBss->IEs, &pAdapter->ScanTab.BssEntry[i].FixIEs, sizeof(NDIS_802_11_FIXED_IEs));
-                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs);
-                }
-                else
-                {
-                    pBss->IELength = (ULONG)(sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen);
-                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs);
-                    NdisMoveMemory(pBss->IEs, &pAdapter->ScanTab.BssEntry[i].FixIEs, sizeof(NDIS_802_11_FIXED_IEs));
-                    NdisMoveMemory(pBss->IEs + sizeof(NDIS_802_11_FIXED_IEs), pAdapter->ScanTab.BssEntry[i].VarIEs, pAdapter->ScanTab.BssEntry[i].VarIELen);
-                    pPtr += pAdapter->ScanTab.BssEntry[i].VarIELen;
-                }
-                pBss->Length = (ULONG)(sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen + Padding);
-
-#if WIRELESS_EXT < 17
-                if ((BssLen + pBss->Length) < wrq->u.data.length)
-                BssLen += pBss->Length;
-                else
-                {
-                    pBssidList->NumberOfItems = i;
-                    break;
-                }
-#else
-                BssLen += pBss->Length;
-#endif
-            }
-
-#if WIRELESS_EXT < 17
-            wrq->u.data.length = BssLen;
-#else
-            if (BssLen > wrq->u.data.length)
-            {
-                kfree(pBssidList);
-                return -E2BIG;
-            }
-            else
-                wrq->u.data.length = BssLen;
-#endif
-            Status = copy_to_user(wrq->u.data.pointer, pBssidList, BssLen);
-            kfree(pBssidList);
-            break;
-        case OID_802_3_CURRENT_ADDRESS:
-            wrq->u.data.length = MAC_ADDR_LEN;
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-            break;
-        case OID_GEN_MEDIA_CONNECT_STATUS:
-            if (pAdapter->IndicateMediaState == NdisMediaStateConnected)
-                MediaState = NdisMediaStateConnected;
-            else
-                MediaState = NdisMediaStateDisconnected;
-
-            wrq->u.data.length = sizeof(NDIS_MEDIA_STATE);
-            Status = copy_to_user(wrq->u.data.pointer, &MediaState, wrq->u.data.length);
-            break;
-        case OID_802_11_BSSID:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				Status = NDIS_STATUS_RESOURCES;
-				break;
-			}
-#endif // RALINK_ATE //
-            if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-            {
-                Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Bssid, sizeof(NDIS_802_11_MAC_ADDRESS));
-
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID(=EMPTY)\n"));
-                Status = -ENOTCONN;
-            }
-            break;
-        case OID_802_11_SSID:
-			NdisZeroMemory(&Ssid, sizeof(NDIS_802_11_SSID));
-			NdisZeroMemory(Ssid.Ssid, MAX_LEN_OF_SSID);
-            Ssid.SsidLength = pAdapter->CommonCfg.SsidLen;
-			memcpy(Ssid.Ssid, pAdapter->CommonCfg.Ssid,	Ssid.SsidLength);
-            wrq->u.data.length = sizeof(NDIS_802_11_SSID);
-            Status = copy_to_user(wrq->u.data.pointer, &Ssid, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_SSID (Len=%d, ssid=%s)\n", Ssid.SsidLength,Ssid.Ssid));
-            break;
-        case RT_OID_802_11_QUERY_LINK_STATUS:
-            pLinkStatus = (RT_802_11_LINK_STATUS *) kmalloc(sizeof(RT_802_11_LINK_STATUS), MEM_ALLOC_FLAG);
-            if (pLinkStatus)
-            {
-                pLinkStatus->CurrTxRate = RateIdTo500Kbps[pAdapter->CommonCfg.TxRate];   // unit : 500 kbps
-                pLinkStatus->ChannelQuality = pAdapter->Mlme.ChannelQuality;
-                pLinkStatus->RxByteCount = pAdapter->RalinkCounters.ReceivedByteCount;
-                pLinkStatus->TxByteCount = pAdapter->RalinkCounters.TransmittedByteCount;
-        		pLinkStatus->CentralChannel = pAdapter->CommonCfg.CentralChannel;
-                wrq->u.data.length = sizeof(RT_802_11_LINK_STATUS);
-                Status = copy_to_user(wrq->u.data.pointer, pLinkStatus, wrq->u.data.length);
-                kfree(pLinkStatus);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LINK_STATUS\n"));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LINK_STATUS(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_802_11_CONFIGURATION:
-            pConfiguration = (NDIS_802_11_CONFIGURATION *) kmalloc(sizeof(NDIS_802_11_CONFIGURATION), MEM_ALLOC_FLAG);
-            if (pConfiguration)
-            {
-                pConfiguration->Length = sizeof(NDIS_802_11_CONFIGURATION);
-                pConfiguration->BeaconPeriod = pAdapter->CommonCfg.BeaconPeriod;
-                pConfiguration->ATIMWindow = pAdapter->StaActive.AtimWin;
-                MAP_CHANNEL_ID_TO_KHZ(pAdapter->CommonCfg.Channel, pConfiguration->DSConfig);
-                wrq->u.data.length = sizeof(NDIS_802_11_CONFIGURATION);
-                Status = copy_to_user(wrq->u.data.pointer, pConfiguration, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CONFIGURATION(BeaconPeriod=%ld,AtimW=%ld,Channel=%d) \n",
-                                        pConfiguration->BeaconPeriod, pConfiguration->ATIMWindow, pAdapter->CommonCfg.Channel));
-				kfree(pConfiguration);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CONFIGURATION(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-		case RT_OID_802_11_SNR_0:
-			if ((pAdapter->StaCfg.LastSNR0 > 0))
-			{
-				ulInfo = ((0xeb	- pAdapter->StaCfg.LastSNR0) * 3) /	16 ;
-				wrq->u.data.length = sizeof(ulInfo);
-				Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_SNR_0(0x=%lx)\n", ulInfo));
-			}
-            else
-			    Status = -EFAULT;
-			break;
-		case RT_OID_802_11_SNR_1:
-			if ((pAdapter->Antenna.field.RxPath	> 1) &&
-                (pAdapter->StaCfg.LastSNR1 > 0))
-			{
-				ulInfo = ((0xeb	- pAdapter->StaCfg.LastSNR1) * 3) /	16 ;
-				wrq->u.data.length = sizeof(ulInfo);
-				Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE,("Query::RT_OID_802_11_SNR_1(0x=%lx)\n",ulInfo));
-			}
-			else
-				Status = -EFAULT;
-            DBGPRINT(RT_DEBUG_TRACE,("Query::RT_OID_802_11_SNR_1(pAdapter->StaCfg.LastSNR1=%d)\n",pAdapter->StaCfg.LastSNR1));
-			break;
-        case OID_802_11_RSSI_TRIGGER:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi0 - pAdapter->BbpRssiToDbmDelta;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_RSSI_TRIGGER(=%ld)\n", ulInfo));
-            break;
-		case OID_802_11_RSSI:
-        case RT_OID_802_11_RSSI:
-			ulInfo = pAdapter->StaCfg.RssiSample.LastRssi0;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-		case RT_OID_802_11_RSSI_1:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi1;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-        case RT_OID_802_11_RSSI_2:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi2;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-        case OID_802_11_STATISTICS:
-            pStatistics = (NDIS_802_11_STATISTICS *) kmalloc(sizeof(NDIS_802_11_STATISTICS), MEM_ALLOC_FLAG);
-            if (pStatistics)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_STATISTICS \n"));
-                // add the most up-to-date h/w raw counters into software counters
-			    NICUpdateRawCounters(pAdapter);
-
-                // Sanity check for calculation of sucessful count
-                if (pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart < pAdapter->WlanCounters.RetryCount.QuadPart)
-                    pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart = pAdapter->WlanCounters.RetryCount.QuadPart;
-
-                pStatistics->TransmittedFragmentCount.QuadPart = pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart;
-                pStatistics->MulticastTransmittedFrameCount.QuadPart = pAdapter->WlanCounters.MulticastTransmittedFrameCount.QuadPart;
-                pStatistics->FailedCount.QuadPart = pAdapter->WlanCounters.FailedCount.QuadPart;
-                pStatistics->RetryCount.QuadPart = pAdapter->WlanCounters.RetryCount.QuadPart;
-                pStatistics->MultipleRetryCount.QuadPart = pAdapter->WlanCounters.MultipleRetryCount.QuadPart;
-                pStatistics->RTSSuccessCount.QuadPart = pAdapter->WlanCounters.RTSSuccessCount.QuadPart;
-                pStatistics->RTSFailureCount.QuadPart = pAdapter->WlanCounters.RTSFailureCount.QuadPart;
-                pStatistics->ACKFailureCount.QuadPart = pAdapter->WlanCounters.ACKFailureCount.QuadPart;
-                pStatistics->FrameDuplicateCount.QuadPart = pAdapter->WlanCounters.FrameDuplicateCount.QuadPart;
-                pStatistics->ReceivedFragmentCount.QuadPart = pAdapter->WlanCounters.ReceivedFragmentCount.QuadPart;
-                pStatistics->MulticastReceivedFrameCount.QuadPart = pAdapter->WlanCounters.MulticastReceivedFrameCount.QuadPart;
-#ifdef DBG
-                pStatistics->FCSErrorCount = pAdapter->RalinkCounters.RealFcsErrCount;
-#else
-                pStatistics->FCSErrorCount.QuadPart = pAdapter->WlanCounters.FCSErrorCount.QuadPart;
-                pStatistics->FrameDuplicateCount.u.LowPart = pAdapter->WlanCounters.FrameDuplicateCount.u.LowPart / 100;
-#endif
-                wrq->u.data.length = sizeof(NDIS_802_11_STATISTICS);
-                Status = copy_to_user(wrq->u.data.pointer, pStatistics, wrq->u.data.length);
-                kfree(pStatistics);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_STATISTICS(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_GEN_RCV_OK:
-            ulInfo = pAdapter->Counters8023.GoodReceives;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            break;
-        case OID_GEN_RCV_NO_BUFFER:
-            ulInfo = pAdapter->Counters8023.RxNoBuffer;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            break;
-        case RT_OID_802_11_PHY_MODE:
-            ulInfo = (ULONG)pAdapter->CommonCfg.PhyMode;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PHY_MODE (=%ld)\n", ulInfo));
-            break;
-        case RT_OID_802_11_STA_CONFIG:
-            pStaConfig = (RT_802_11_STA_CONFIG *) kmalloc(sizeof(RT_802_11_STA_CONFIG), MEM_ALLOC_FLAG);
-            if (pStaConfig)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG\n"));
-                pStaConfig->EnableTxBurst = pAdapter->CommonCfg.bEnableTxBurst;
-                pStaConfig->EnableTurboRate = 0;
-                pStaConfig->UseBGProtection = pAdapter->CommonCfg.UseBGProtection;
-                pStaConfig->UseShortSlotTime = pAdapter->CommonCfg.bUseShortSlotTime;
-                //pStaConfig->AdhocMode = pAdapter->StaCfg.AdhocMode;
-                pStaConfig->HwRadioStatus = (pAdapter->StaCfg.bHwRadio == TRUE) ? 1 : 0;
-                pStaConfig->Rsv1 = 0;
-                pStaConfig->SystemErrorBitmap = pAdapter->SystemErrorBitmap;
-                wrq->u.data.length = sizeof(RT_802_11_STA_CONFIG);
-                Status = copy_to_user(wrq->u.data.pointer, pStaConfig, wrq->u.data.length);
-                kfree(pStaConfig);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_802_11_RTS_THRESHOLD:
-            RtsThresh = pAdapter->CommonCfg.RtsThreshold;
-            wrq->u.data.length = sizeof(RtsThresh);
-            Status = copy_to_user(wrq->u.data.pointer, &RtsThresh, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_RTS_THRESHOLD(=%ld)\n", RtsThresh));
-            break;
-        case OID_802_11_FRAGMENTATION_THRESHOLD:
-            FragThresh = pAdapter->CommonCfg.FragmentThreshold;
-            if (pAdapter->CommonCfg.bUseZeroToDisableFragment == TRUE)
-                FragThresh = 0;
-            wrq->u.data.length = sizeof(FragThresh);
-            Status = copy_to_user(wrq->u.data.pointer, &FragThresh, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_FRAGMENTATION_THRESHOLD(=%ld)\n", FragThresh));
-            break;
-        case OID_802_11_POWER_MODE:
-            PowerMode = pAdapter->StaCfg.WindowsPowerMode;
-            wrq->u.data.length = sizeof(PowerMode);
-            Status = copy_to_user(wrq->u.data.pointer, &PowerMode, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_POWER_MODE(=%d)\n", PowerMode));
-            break;
-        case RT_OID_802_11_RADIO:
-            RadioState = (BOOLEAN) pAdapter->StaCfg.bSwRadio;
-            wrq->u.data.length = sizeof(RadioState);
-            Status = copy_to_user(wrq->u.data.pointer, &RadioState, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_RADIO (=%d)\n", RadioState));
-            break;
-        case OID_802_11_INFRASTRUCTURE_MODE:
-            if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-                BssType = Ndis802_11IBSS;
-            else if (pAdapter->StaCfg.BssType == BSS_INFRA)
-                BssType = Ndis802_11Infrastructure;
-            else if (pAdapter->StaCfg.BssType == BSS_MONITOR)
-                BssType = Ndis802_11Monitor;
-            else
-                BssType = Ndis802_11AutoUnknown;
-
-            wrq->u.data.length = sizeof(BssType);
-            Status = copy_to_user(wrq->u.data.pointer, &BssType, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_INFRASTRUCTURE_MODE(=%d)\n", BssType));
-            break;
-        case RT_OID_802_11_PREAMBLE:
-            PreamType = pAdapter->CommonCfg.TxPreamble;
-            wrq->u.data.length = sizeof(PreamType);
-            Status = copy_to_user(wrq->u.data.pointer, &PreamType, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PREAMBLE(=%d)\n", PreamType));
-            break;
-        case OID_802_11_AUTHENTICATION_MODE:
-            AuthMode = pAdapter->StaCfg.AuthMode;
-            wrq->u.data.length = sizeof(AuthMode);
-            Status = copy_to_user(wrq->u.data.pointer, &AuthMode, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_AUTHENTICATION_MODE(=%d)\n", AuthMode));
-            break;
-        case OID_802_11_WEP_STATUS:
-            WepStatus = pAdapter->StaCfg.WepStatus;
-            wrq->u.data.length = sizeof(WepStatus);
-            Status = copy_to_user(wrq->u.data.pointer, &WepStatus, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_WEP_STATUS(=%d)\n", WepStatus));
-            break;
-        case OID_802_11_TX_POWER_LEVEL:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.TxPower, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_TX_POWER_LEVEL %x\n",pAdapter->CommonCfg.TxPower));
-			break;
-        case RT_OID_802_11_TX_POWER_LEVEL_1:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.TxPowerPercentage, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_TX_POWER_LEVEL_1 (=%ld)\n", pAdapter->CommonCfg.TxPowerPercentage));
-			break;
-        case OID_802_11_NETWORK_TYPES_SUPPORTED:
-			if ((pAdapter->RfIcType	== RFIC_2850) || (pAdapter->RfIcType ==	RFIC_2750))
-			{
-				NetworkTypeList[0] = 3;                 // NumberOfItems = 3
-				NetworkTypeList[1] = Ndis802_11DS;      // NetworkType[1] = 11b
-				NetworkTypeList[2] = Ndis802_11OFDM24;  // NetworkType[2] = 11g
-				NetworkTypeList[3] = Ndis802_11OFDM5;   // NetworkType[3] = 11a
-                wrq->u.data.length = 16;
-				Status = copy_to_user(wrq->u.data.pointer, &NetworkTypeList[0], wrq->u.data.length);
-			}
-			else
-			{
-				NetworkTypeList[0] = 2;                 // NumberOfItems = 2
-				NetworkTypeList[1] = Ndis802_11DS;      // NetworkType[1] = 11b
-				NetworkTypeList[2] = Ndis802_11OFDM24;  // NetworkType[2] = 11g
-			    wrq->u.data.length = 12;
-				Status = copy_to_user(wrq->u.data.pointer, &NetworkTypeList[0], wrq->u.data.length);
-			}
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_NETWORK_TYPES_SUPPORTED\n"));
-				break;
-	    case OID_802_11_NETWORK_TYPE_IN_USE:
-            wrq->u.data.length = sizeof(ULONG);
-			if (pAdapter->CommonCfg.PhyMode == PHY_11A)
-				ulInfo = Ndis802_11OFDM5;
-			else if ((pAdapter->CommonCfg.PhyMode == PHY_11BG_MIXED) || (pAdapter->CommonCfg.PhyMode == PHY_11G))
-				ulInfo = Ndis802_11OFDM24;
-			else
-				ulInfo = Ndis802_11DS;
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-        case RT_OID_802_11_QUERY_LAST_RX_RATE:
-            ulInfo = (ULONG)pAdapter->LastRxRate;
-            wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LAST_RX_RATE (=%ld)\n", ulInfo));
-			break;
-		case RT_OID_802_11_QUERY_LAST_TX_RATE:
-			//ulInfo = (ULONG)pAdapter->LastTxRate;
-			ulInfo = (ULONG)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LAST_TX_RATE (=%lx)\n", ulInfo));
-			break;
-        case RT_OID_802_11_QUERY_EEPROM_VERSION:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->EepromVersion, wrq->u.data.length);
-            break;
-        case RT_OID_802_11_QUERY_FIRMWARE_VERSION:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->FirmwareVersion, wrq->u.data.length);
-			break;
-	    case RT_OID_802_11_QUERY_NOISE_LEVEL:
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->BbpWriteLatch[66], wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_NOISE_LEVEL (=%d)\n", pAdapter->BbpWriteLatch[66]));
-			break;
-	    case RT_OID_802_11_EXTRA_INFO:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->ExtraInfo, wrq->u.data.length);
-	        DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_EXTRA_INFO (=%ld)\n", pAdapter->ExtraInfo));
-	        break;
-	    case RT_OID_WE_VERSION_COMPILED:
-	        wrq->u.data.length = sizeof(UINT);
-	        we_version_compiled = WIRELESS_EXT;
-	        Status = copy_to_user(wrq->u.data.pointer, &we_version_compiled, wrq->u.data.length);
-	        break;
-		case RT_OID_802_11_QUERY_APSD_SETTING:
-			apsd = (pAdapter->CommonCfg.bAPSDCapable | (pAdapter->CommonCfg.bAPSDAC_BE << 1) | (pAdapter->CommonCfg.bAPSDAC_BK << 2)
-				| (pAdapter->CommonCfg.bAPSDAC_VI << 3)	| (pAdapter->CommonCfg.bAPSDAC_VO << 4)	| (pAdapter->CommonCfg.MaxSPLength << 5));
-
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &apsd, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_APSD_SETTING (=0x%lx,APSDCap=%d,AC_BE=%d,AC_BK=%d,AC_VI=%d,AC_VO=%d,MAXSPLen=%d)\n",
-				apsd,pAdapter->CommonCfg.bAPSDCapable,pAdapter->CommonCfg.bAPSDAC_BE,pAdapter->CommonCfg.bAPSDAC_BK,pAdapter->CommonCfg.bAPSDAC_VI,pAdapter->CommonCfg.bAPSDAC_VO,pAdapter->CommonCfg.MaxSPLength));
-			break;
-		case RT_OID_802_11_QUERY_APSD_PSM:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bAPSDForcePowerSave, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_APSD_PSM (=%d)\n", pAdapter->CommonCfg.bAPSDForcePowerSave));
-			break;
-		case RT_OID_802_11_QUERY_WMM:
-			wrq->u.data.length = sizeof(BOOLEAN);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bWmmCapable, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_WMM (=%d)\n",	pAdapter->CommonCfg.bWmmCapable));
-			break;
-#ifdef WPA_SUPPLICANT_SUPPORT
-        case RT_OID_NEW_DRIVER:
-            {
-                UCHAR enabled = 1;
-    	        wrq->u.data.length = sizeof(UCHAR);
-    	        Status = copy_to_user(wrq->u.data.pointer, &enabled, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_NEW_DRIVER (=%d)\n", enabled));
-            }
-	        break;
-        case RT_OID_WPA_SUPPLICANT_SUPPORT:
-	        wrq->u.data.length = sizeof(UCHAR);
-	        Status = copy_to_user(wrq->u.data.pointer, &pAdapter->StaCfg.WpaSupplicantUP, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_WPA_SUPPLICANT_SUPPORT (=%d)\n", pAdapter->StaCfg.WpaSupplicantUP));
-	        break;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-        case RT_OID_DRIVER_DEVICE_NAME:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_DRIVER_DEVICE_NAME \n"));
-			wrq->u.data.length = 16;
-			if (copy_to_user(wrq->u.data.pointer, pAdapter->StaCfg.dev_name, wrq->u.data.length))
-			{
-				Status = -EFAULT;
-			}
-            break;
-        case RT_OID_802_11_QUERY_HT_PHYMODE:
-            pHTPhyMode = (OID_SET_HT_PHYMODE *) kmalloc(sizeof(OID_SET_HT_PHYMODE), MEM_ALLOC_FLAG);
-            if (pHTPhyMode)
-            {
-                pHTPhyMode->PhyMode = pAdapter->CommonCfg.PhyMode;
-    			pHTPhyMode->HtMode = (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE;
-    			pHTPhyMode->BW = (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.BW;
-    			pHTPhyMode->MCS= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.MCS;
-    			pHTPhyMode->SHORTGI= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.ShortGI;
-    			pHTPhyMode->STBC= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.STBC;
-
-    			pHTPhyMode->ExtOffset = ((pAdapter->CommonCfg.CentralChannel < pAdapter->CommonCfg.Channel) ? (EXTCHA_BELOW) : (EXTCHA_ABOVE));
-                wrq->u.data.length = sizeof(OID_SET_HT_PHYMODE);
-                if (copy_to_user(wrq->u.data.pointer, pHTPhyMode, wrq->u.data.length))
-    			{
-    				Status = -EFAULT;
-    			}
-    			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_HT_PHYMODE (PhyMode = %d, MCS =%d, BW = %d, STBC = %d, ExtOffset=%d)\n",
-    				pHTPhyMode->HtMode, pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC, pHTPhyMode->ExtOffset));
-    			DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (.word = %x )\n", pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case RT_OID_802_11_COUNTRY_REGION:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_COUNTRY_REGION \n"));
-			wrq->u.data.length = sizeof(ulInfo);
-            ulInfo = pAdapter->CommonCfg.CountryRegionForABand;
-            ulInfo = (ulInfo << 8)|(pAdapter->CommonCfg.CountryRegion);
-			if (copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            break;
-        case RT_OID_802_11_QUERY_DAT_HT_PHYMODE:
-            pHTPhyMode = (OID_SET_HT_PHYMODE *) kmalloc(sizeof(OID_SET_HT_PHYMODE), MEM_ALLOC_FLAG);
-            if (pHTPhyMode)
-            {
-                pHTPhyMode->PhyMode = pAdapter->CommonCfg.PhyMode;
-    			pHTPhyMode->HtMode = (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.HTMODE;
-    			pHTPhyMode->BW = (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.BW;
-    			pHTPhyMode->MCS= (UCHAR)pAdapter->StaCfg.DesiredTransmitSetting.field.MCS;
-    			pHTPhyMode->SHORTGI= (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.ShortGI;
-    			pHTPhyMode->STBC= (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.STBC;
-
-                wrq->u.data.length = sizeof(OID_SET_HT_PHYMODE);
-                if (copy_to_user(wrq->u.data.pointer, pHTPhyMode, wrq->u.data.length))
-    			{
-    				Status = -EFAULT;
-    			}
-    			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_HT_PHYMODE (PhyMode = %d, MCS =%d, BW = %d, STBC = %d, ExtOffset=%d)\n",
-    				pHTPhyMode->HtMode, pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC, pHTPhyMode->ExtOffset));
-    			DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (.word = %x )\n", pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case RT_OID_QUERY_MULTIPLE_CARD_SUPPORT:
-			wrq->u.data.length = sizeof(UCHAR);
-            i = 0;
-#ifdef MULTIPLE_CARD_SUPPORT
-            i = 1;
-#endif // MULTIPLE_CARD_SUPPORT //
-			if (copy_to_user(wrq->u.data.pointer, &i, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_QUERY_MULTIPLE_CARD_SUPPORT(=%d) \n", i));
-            break;
-#ifdef SNMP_SUPPORT
-		case RT_OID_802_11_MAC_ADDRESS:
-            wrq->u.data.length = MAC_ADDR_LEN;
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTUREROUI:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTUREROUI \n"));
-			wrq->u.data.length = ManufacturerOUI_LEN;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTURERNAME:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTURERNAME \n"));
-			wrq->u.data.length = strlen(ManufacturerNAME);
-			Status = copy_to_user(wrq->u.data.pointer, ManufacturerNAME, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_RESOURCETYPEIDNAME:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_RESOURCETYPEIDNAME \n"));
-			wrq->u.data.length = strlen(ResourceTypeIdName);
-			Status = copy_to_user(wrq->u.data.pointer, ResourceTypeIdName, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED \n"));
-			ulInfo = 1; // 1 is support wep else 2 is not support.
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_POWERMANAGEMENTMODE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_POWERMANAGEMENTMODE \n"));
-			if (pAdapter->StaCfg.Psm == PSMP_ACTION)
-				ulInfo = 1; // 1 is power active else 2 is power save.
-			else
-				ulInfo = 2;
-
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYVALUE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_WEPDEFAULTKEYVALUE \n"));
-			//KeyIdxValue.KeyIdx = pAd->PortCfg.MBSSID[pAd->IoctlIF].DefaultKeyId;
-			pKeyIdxValue = wrq->u.data.pointer;
-			DBGPRINT(RT_DEBUG_TRACE,("KeyIdxValue.KeyIdx = %d, \n",pKeyIdxValue->KeyIdx));
-			valueLen = pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen;
-			NdisMoveMemory(pKeyIdxValue->Value,
-						   &pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key,
-						   valueLen);
-			pKeyIdxValue->Value[valueLen]='\0';
-
-			wrq->u.data.length = sizeof(DefaultKeyIdxValue);
-
-			Status = copy_to_user(wrq->u.data.pointer, pKeyIdxValue, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE,("DefaultKeyId = %d, total len = %d, str len=%d, KeyValue= %02x %02x %02x %02x \n", pAdapter->StaCfg.DefaultKeyId, wrq->u.data.length, pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen,
-			pAdapter->SharedKey[BSS0][0].Key[0],
-			pAdapter->SharedKey[BSS0][1].Key[0],
-			pAdapter->SharedKey[BSS0][2].Key[0],
-			pAdapter->SharedKey[BSS0][3].Key[0]));
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_WEPDEFAULTKEYID \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->StaCfg.DefaultKeyId, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("DefaultKeyId =%d \n", pAdapter->StaCfg.DefaultKeyId));
-			break;
-
-		case RT_OID_802_11_WEPKEYMAPPINGLENGTH:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_WEPKEYMAPPINGLENGTH \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer,
-									&pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen,
-									wrq->u.data.length);
-			break;
-
-		case OID_802_11_SHORTRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_SHORTRETRYLIMIT \n"));
-			wrq->u.data.length = sizeof(ULONG);
-			RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-			ShortRetryLimit = tx_rty_cfg.field.ShortRtyLimit;
-			DBGPRINT(RT_DEBUG_TRACE, ("ShortRetryLimit =%ld,  tx_rty_cfg.field.ShortRetryLimit=%d\n", ShortRetryLimit, tx_rty_cfg.field.ShortRtyLimit));
-			Status = copy_to_user(wrq->u.data.pointer, &ShortRetryLimit, wrq->u.data.length);
-			break;
-
-		case OID_802_11_LONGRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_LONGRETRYLIMIT \n"));
-			wrq->u.data.length = sizeof(ULONG);
-			RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-			LongRetryLimit = tx_rty_cfg.field.LongRtyLimit;
-			DBGPRINT(RT_DEBUG_TRACE, ("LongRetryLimit =%ld,  tx_rty_cfg.field.LongRtyLimit=%d\n", LongRetryLimit, tx_rty_cfg.field.LongRtyLimit));
-			Status = copy_to_user(wrq->u.data.pointer, &LongRetryLimit, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_PRODUCTID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PRODUCTID \n"));
-
-#ifdef RT2870
-			sprintf(tmp, "%04x %04x\n", ((POS_COOKIE)pAdapter->OS_Cookie)->pUsb_Dev->descriptor.idVendor ,((POS_COOKIE)pAdapter->OS_Cookie)->pUsb_Dev->descriptor.idProduct);
-
-#endif // RT2870 //
-			wrq->u.data.length = strlen(tmp);
-			Status = copy_to_user(wrq->u.data.pointer, tmp, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTUREID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTUREID \n"));
-			wrq->u.data.length = strlen(ManufacturerNAME);
-			Status = copy_to_user(wrq->u.data.pointer, ManufacturerNAME, wrq->u.data.length);
-			break;
-
-		case OID_802_11_CURRENTCHANNEL:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CURRENTCHANNEL \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			DBGPRINT(RT_DEBUG_TRACE, ("sizeof UCHAR=%d, channel=%d \n", sizeof(UCHAR), pAdapter->CommonCfg.Channel));
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Channel, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-#endif //SNMP_SUPPORT
-
-		case OID_802_11_BUILD_CHANNEL_EX:
-			{
-				UCHAR value;
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BUILD_CHANNEL_EX \n"));
-				wrq->u.data.length = sizeof(UCHAR);
-#ifdef EXT_BUILD_CHANNEL_LIST
-				DBGPRINT(RT_DEBUG_TRACE, ("Support EXT_BUILD_CHANNEL_LIST.\n"));
-				value = 1;
-#else
-				DBGPRINT(RT_DEBUG_TRACE, ("Doesn't support EXT_BUILD_CHANNEL_LIST.\n"));
-				value = 0;
-#endif // EXT_BUILD_CHANNEL_LIST //
-				Status = copy_to_user(wrq->u.data.pointer, &value, 1);
-				DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			}
-			break;
-
-		case OID_802_11_GET_CH_LIST:
-			{
-				PRT_CHANNEL_LIST_INFO pChListBuf;
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_CH_LIST \n"));
-				if (pAdapter->ChannelListNum == 0)
-				{
-					wrq->u.data.length = 0;
-					break;
-				}
-
-				pChListBuf = (RT_CHANNEL_LIST_INFO *) kmalloc(sizeof(RT_CHANNEL_LIST_INFO), MEM_ALLOC_FLAG);
-				if (pChListBuf == NULL)
-				{
-					wrq->u.data.length = 0;
-					break;
-				}
-
-				pChListBuf->ChannelListNum = pAdapter->ChannelListNum;
-				for (i = 0; i < pChListBuf->ChannelListNum; i++)
-					pChListBuf->ChannelList[i] = pAdapter->ChannelList[i].Channel;
-
-				wrq->u.data.length = sizeof(RT_CHANNEL_LIST_INFO);
-				Status = copy_to_user(wrq->u.data.pointer, pChListBuf, sizeof(RT_CHANNEL_LIST_INFO));
-				DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-
-				if (pChListBuf)
-					kfree(pChListBuf);
-			}
-			break;
-
-		case OID_802_11_GET_COUNTRY_CODE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_COUNTRY_CODE \n"));
-			wrq->u.data.length = 2;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.CountryCode, 2);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-
-		case OID_802_11_GET_CHANNEL_GEOGRAPHY:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_CHANNEL_GEOGRAPHY \n"));
-			wrq->u.data.length = 1;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Geography, 1);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-
-
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_QUERY_DLS:
-			wrq->u.data.length = sizeof(BOOLEAN);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bDLSCapable, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_DLS(=%d)\n", pAdapter->CommonCfg.bDLSCapable));
-			break;
-
-		case RT_OID_802_11_QUERY_DLS_PARAM:
-			{
-				PRT_802_11_DLS_INFO	pDlsInfo = kmalloc(sizeof(RT_802_11_DLS_INFO), GFP_ATOMIC);
-				if (pDlsInfo == NULL)
-					break;
-
-				for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-				{
-					RTMPMoveMemory(&pDlsInfo->Entry[i], &pAdapter->StaCfg.DLSEntry[i], sizeof(RT_802_11_DLS_UI));
-				}
-
-				pDlsInfo->num = MAX_NUM_OF_DLS_ENTRY;
-				wrq->u.data.length = sizeof(RT_802_11_DLS_INFO);
-				Status = copy_to_user(wrq->u.data.pointer, pDlsInfo, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_DLS_PARAM\n"));
-
-				if (pDlsInfo)
-					kfree(pDlsInfo);
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::unknown IOCTL's subcmd = 0x%08x\n", cmd));
-            Status = -EOPNOTSUPP;
-            break;
-    }
-    return Status;
-}
-
-INT rt28xx_sta_ioctl(
-	IN	struct net_device	*net_dev,
-	IN	OUT	struct ifreq	*rq,
-	IN	INT					cmd)
-{
-	POS_COOKIE			pObj;
-	VIRTUAL_ADAPTER		*pVirtualAd = NULL;
-	RTMP_ADAPTER        *pAd = NULL;
-	struct iwreq        *wrq = (struct iwreq *) rq;
-	BOOLEAN				StateMachineTouched = FALSE;
-	INT					Status = NDIS_STATUS_SUCCESS;
-	USHORT				subcmd;
-
-	if (net_dev->priv_flags == INT_MAIN)
-	{
-		pAd = net_dev->priv;
-	}
-	else
-	{
-		pVirtualAd = net_dev->priv;
-		pAd = pVirtualAd->RtmpDev->priv;
-	}
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	    if (wrq->u.data.pointer == NULL)
-	    {
-		    return Status;
-	    }
-
-	    if (strstr(wrq->u.data.pointer, "OpMode") == NULL)
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		    return -ENETDOWN;
-        }
-    }
-
-	{	// determine this ioctl command is comming from which interface.
-		pObj->ioctl_if_type = INT_MAIN;
-		pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-	switch(cmd)
-	{
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-		case RTPRIV_IOCTL_ATE:
-			{
-				RtmpDoAte(pAd, wrq);
-			}
-			break;
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-        case SIOCGIFHWADDR:
-			DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCGIFHWADDR\n"));
-			memcpy(wrq->u.name, pAd->CurrentAddress, ETH_ALEN);
-			break;
-		case SIOCGIWNAME:
-        {
-        	char *name=&wrq->u.name[0];
-        	rt_ioctl_giwname(net_dev, NULL, name, NULL);
-			break;
-		}
-		case SIOCGIWESSID:  //Get ESSID
-        {
-        	struct iw_point *essid=&wrq->u.essid;
-        	rt_ioctl_giwessid(net_dev, NULL, essid, essid->pointer);
-			break;
-		}
-		case SIOCSIWESSID:  //Set ESSID
-        {
-        	struct iw_point	*essid=&wrq->u.essid;
-        	rt_ioctl_siwessid(net_dev, NULL, essid, essid->pointer);
-			break;
-		}
-		case SIOCSIWNWID:   // set network id (the cell)
-		case SIOCGIWNWID:   // get network id
-			Status = -EOPNOTSUPP;
-			break;
-		case SIOCSIWFREQ:   //set channel/frequency (Hz)
-        {
-        	struct iw_freq *freq=&wrq->u.freq;
-        	rt_ioctl_siwfreq(net_dev, NULL, freq, NULL);
-			break;
-		}
-		case SIOCGIWFREQ:   // get channel/frequency (Hz)
-        {
-        	struct iw_freq *freq=&wrq->u.freq;
-        	rt_ioctl_giwfreq(net_dev, NULL, freq, NULL);
-			break;
-		}
-		case SIOCSIWNICKN: //set node name/nickname
-        {
-        	struct iw_point *data=&wrq->u.data;
-        	rt_ioctl_siwnickn(net_dev, NULL, data, NULL);
-			break;
-		}
-		case SIOCGIWNICKN: //get node name/nickname
-        {
-        	struct iw_point *data=&wrq->u.data;
-        	rt_ioctl_giwnickn(net_dev, NULL, data, NULL);
-			break;
-		}
-		case SIOCGIWRATE:   //get default bit rate (bps)
-		    rt_ioctl_giwrate(net_dev, NULL, &wrq->u, NULL);
-            break;
-	    case SIOCSIWRATE:  //set default bit rate (bps)
-	        rt_ioctl_siwrate(net_dev, NULL, &wrq->u, NULL);
-            break;
-        case SIOCGIWRTS:  // get RTS/CTS threshold (bytes)
-        {
-        	struct iw_param *rts=&wrq->u.rts;
-        	rt_ioctl_giwrts(net_dev, NULL, rts, NULL);
-			break;
-		}
-        case SIOCSIWRTS:  //set RTS/CTS threshold (bytes)
-        {
-        	struct iw_param *rts=&wrq->u.rts;
-        	rt_ioctl_siwrts(net_dev, NULL, rts, NULL);
-			break;
-		}
-        case SIOCGIWFRAG:  //get fragmentation thr (bytes)
-        {
-        	struct iw_param *frag=&wrq->u.frag;
-        	rt_ioctl_giwfrag(net_dev, NULL, frag, NULL);
-			break;
-		}
-        case SIOCSIWFRAG:  //set fragmentation thr (bytes)
-        {
-        	struct iw_param *frag=&wrq->u.frag;
-        	rt_ioctl_siwfrag(net_dev, NULL, frag, NULL);
-			break;
-		}
-        case SIOCGIWENCODE:  //get encoding token & mode
-        {
-        	struct iw_point *erq=&wrq->u.encoding;
-        	if(erq->pointer)
-        		rt_ioctl_giwencode(net_dev, NULL, erq, erq->pointer);
-			break;
-		}
-        case SIOCSIWENCODE:  //set encoding token & mode
-        {
-        	struct iw_point *erq=&wrq->u.encoding;
-        	if(erq->pointer)
-        		rt_ioctl_siwencode(net_dev, NULL, erq, erq->pointer);
-			break;
-		}
-		case SIOCGIWAP:     //get access point MAC addresses
-        {
-        	struct sockaddr *ap_addr=&wrq->u.ap_addr;
-        	rt_ioctl_giwap(net_dev, NULL, ap_addr, ap_addr->sa_data);
-			break;
-		}
-	    case SIOCSIWAP:  //set access point MAC addresses
-        {
-        	struct sockaddr *ap_addr=&wrq->u.ap_addr;
-        	rt_ioctl_siwap(net_dev, NULL, ap_addr, ap_addr->sa_data);
-			break;
-		}
-		case SIOCGIWMODE:   //get operation mode
-        {
-        	__u32 *mode=&wrq->u.mode;
-        	rt_ioctl_giwmode(net_dev, NULL, mode, NULL);
-			break;
-		}
-		case SIOCSIWMODE:   //set operation mode
-        {
-        	__u32 *mode=&wrq->u.mode;
-        	rt_ioctl_siwmode(net_dev, NULL, mode, NULL);
-			break;
-		}
-		case SIOCGIWSENS:   //get sensitivity (dBm)
-		case SIOCSIWSENS:	//set sensitivity (dBm)
-		case SIOCGIWPOWER:  //get Power Management settings
-		case SIOCSIWPOWER:  //set Power Management settings
-		case SIOCGIWTXPOW:  //get transmit power (dBm)
-		case SIOCSIWTXPOW:  //set transmit power (dBm)
-		case SIOCGIWRANGE:	//Get range of parameters
-		case SIOCGIWRETRY:	//get retry limits and lifetime
-		case SIOCSIWRETRY:	//set retry limits and lifetime
-			Status = -EOPNOTSUPP;
-			break;
-		case RT_PRIV_IOCTL:
-			subcmd = wrq->u.data.flags;
-			if( subcmd & OID_GET_SET_TOGGLE)
-				Status = RTMPSetInformation(pAd, rq, subcmd);
-			else
-				Status = RTMPQueryInformation(pAd, rq, subcmd);
-			break;
-		case SIOCGIWPRIV:
-			if (wrq->u.data.pointer)
-			{
-				if ( access_ok(VERIFY_WRITE, wrq->u.data.pointer, sizeof(privtab)) != TRUE)
-					break;
-				wrq->u.data.length = sizeof(privtab) / sizeof(privtab[0]);
-				if (copy_to_user(wrq->u.data.pointer, privtab, sizeof(privtab)))
-					Status = -EFAULT;
-			}
-			break;
-		case RTPRIV_IOCTL_SET:
-			if(access_ok(VERIFY_READ, wrq->u.data.pointer, wrq->u.data.length) != TRUE)
-				break;
-			rt_ioctl_setparam(net_dev, NULL, NULL, wrq->u.data.pointer);
-			break;
-		case RTPRIV_IOCTL_GSITESURVEY:
-			RTMPIoctlGetSiteSurvey(pAd, wrq);
-		    break;
-#ifdef DBG
-		case RTPRIV_IOCTL_MAC:
-			RTMPIoctlMAC(pAd, wrq);
-			break;
-		case RTPRIV_IOCTL_E2P:
-			RTMPIoctlE2PROM(pAd, wrq);
-			break;
-#endif // DBG //
-        case SIOCETHTOOL:
-                break;
-		default:
-			DBGPRINT(RT_DEBUG_ERROR, ("IOCTL::unknown IOCTL's cmd = 0x%08x\n", cmd));
-			Status = -EOPNOTSUPP;
-			break;
-	}
-
-    if(StateMachineTouched) // Upper layer sent a MLME-related operations
-    	RT28XX_MLME_HANDLER(pAd);
-
-	return Status;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set SSID
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_SSID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    NDIS_802_11_SSID                    Ssid, *pSsid=NULL;
-    BOOLEAN                             StateMachineTouched = FALSE;
-    int                                 success = TRUE;
-
-    if( strlen(arg) <= MAX_LEN_OF_SSID)
-    {
-        NdisZeroMemory(&Ssid, sizeof(NDIS_802_11_SSID));
-        if (strlen(arg) != 0)
-        {
-            NdisMoveMemory(Ssid.Ssid, arg, strlen(arg));
-            Ssid.SsidLength = strlen(arg);
-        }
-        else   //ANY ssid
-        {
-            Ssid.SsidLength = 0;
-		    memcpy(Ssid.Ssid, "", 0);
-			pAdapter->StaCfg.BssType = BSS_INFRA;
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-	        pAdapter->StaCfg.WepStatus  = Ndis802_11EncryptionDisabled;
-		}
-        pSsid = &Ssid;
-
-        if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-        {
-            RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-            DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-        }
-
-        pAdapter->MlmeAux.CurrReqIsFromNdis = TRUE;
-        pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-		pAdapter->bConfigChanged = TRUE;
-
-        MlmeEnqueue(pAdapter,
-                    MLME_CNTL_STATE_MACHINE,
-                    OID_802_11_SSID,
-                    sizeof(NDIS_802_11_SSID),
-                    (VOID *)pSsid);
-
-        StateMachineTouched = TRUE;
-        DBGPRINT(RT_DEBUG_TRACE, ("Set_SSID_Proc::(Len=%d,Ssid=%s)\n", Ssid.SsidLength, Ssid.Ssid));
-    }
-    else
-        success = FALSE;
-
-    if (StateMachineTouched) // Upper layer sent a MLME-related operations
-    	RT28XX_MLME_HANDLER(pAdapter);
-
-    return success;
-}
-
-#ifdef WMM_SUPPORT
-/*
-    ==========================================================================
-    Description:
-        Set WmmCapable Enable or Disable
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	BOOLEAN	bWmmCapable;
-
-	bWmmCapable = simple_strtol(arg, 0, 10);
-
-	if ((bWmmCapable == 1)
-#ifdef RT2870
-		&& (pAd->NumberOfPipes >= 5)
-#endif // RT2870 //
-		)
-		pAd->CommonCfg.bWmmCapable = TRUE;
-	else if (bWmmCapable == 0)
-		pAd->CommonCfg.bWmmCapable = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_WmmCapable_Proc::(bWmmCapable=%d)\n",
-		pAd->CommonCfg.bWmmCapable));
-
-	return TRUE;
-}
-#endif // WMM_SUPPORT //
-
-/*
-    ==========================================================================
-    Description:
-        Set Network Type(Infrastructure/Adhoc mode)
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_NetworkType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    UINT32	Value = 0;
-
-    if (strcmp(arg, "Adhoc") == 0)
-	{
-		if (pAdapter->StaCfg.BssType != BSS_ADHOC)
-		{
-			// Config has changed
-			pAdapter->bConfigChanged = TRUE;
-            if (MONITOR_ON(pAdapter))
-            {
-                RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, STANORMAL);
-                RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-				Value &= (~0x80);
-				RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-                OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-                pAdapter->StaCfg.bAutoReconnect = TRUE;
-                LinkDown(pAdapter, FALSE);
-            }
-			if (INFRA_ON(pAdapter))
-			{
-				//BOOLEAN Cancelled;
-				// Set the AutoReconnectSsid to prevent it reconnect to old SSID
-				// Since calling this indicate user don't want to connect to that SSID anymore.
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-				NdisZeroMemory(pAdapter->MlmeAux.AutoReconnectSsid, pAdapter->MlmeAux.AutoReconnectSsidLen);
-
-				LinkDown(pAdapter, FALSE);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event BB!\n"));
-			}
-		}
-		pAdapter->StaCfg.BssType = BSS_ADHOC;
-        pAdapter->net_dev->type = pAdapter->StaCfg.OriDevType;
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(AD-HOC)\n"));
-	}
-    else if (strcmp(arg, "Infra") == 0)
-	{
-		if (pAdapter->StaCfg.BssType != BSS_INFRA)
-		{
-			// Config has changed
-			pAdapter->bConfigChanged = TRUE;
-            if (MONITOR_ON(pAdapter))
-            {
-                RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, STANORMAL);
-                RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-				Value &= (~0x80);
-				RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-                OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-                pAdapter->StaCfg.bAutoReconnect = TRUE;
-                LinkDown(pAdapter, FALSE);
-            }
-			if (ADHOC_ON(pAdapter))
-			{
-				// Set the AutoReconnectSsid to prevent it reconnect to old SSID
-				// Since calling this indicate user don't want to connect to that SSID anymore.
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-				NdisZeroMemory(pAdapter->MlmeAux.AutoReconnectSsid, pAdapter->MlmeAux.AutoReconnectSsidLen);
-
-				LinkDown(pAdapter, FALSE);
-			}
-		}
-		pAdapter->StaCfg.BssType = BSS_INFRA;
-        pAdapter->net_dev->type = pAdapter->StaCfg.OriDevType;
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(INFRA)\n"));
-
-        pAdapter->StaCfg.BssType = BSS_INFRA;
-	}
-    else if (strcmp(arg, "Monitor") == 0)
-    {
-		UCHAR	bbpValue = 0;
-		BCN_TIME_CFG_STRUC csr;
-		OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_INFRA_ON);
-        OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_ADHOC_ON);
-		OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-		// disable all periodic state machine
-		pAdapter->StaCfg.bAutoReconnect = FALSE;
-		// reset all mlme state machine
-		RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-		DBGPRINT(RT_DEBUG_TRACE, ("fOP_STATUS_MEDIA_STATE_CONNECTED \n"));
-        if (pAdapter->CommonCfg.CentralChannel == 0)
-        {
-#ifdef DOT11_N_SUPPORT
-            if (pAdapter->CommonCfg.PhyMode == PHY_11AN_MIXED)
-                pAdapter->CommonCfg.CentralChannel = 36;
-            else
-#endif // DOT11_N_SUPPORT //
-                pAdapter->CommonCfg.CentralChannel = 6;
-        }
-#ifdef DOT11_N_SUPPORT
-        else
-            N_ChannelCheck(pAdapter);
-#endif // DOT11_N_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-	if (pAdapter->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-            pAdapter->CommonCfg.RegTransmitSetting.field.BW == BW_40 &&
-            pAdapter->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_ABOVE)
-		{
-			// 40MHz ,control channel at lower
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			bbpValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_40;
-			//  RX : control channel at lower
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R3, &bbpValue);
-			bbpValue &= (~0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R3, bbpValue);
-
-			RTMP_IO_READ32(pAdapter, TX_BAND_CFG, &Value);
-			Value &= 0xfffffffe;
-			RTMP_IO_WRITE32(pAdapter, TX_BAND_CFG, Value);
-			pAdapter->CommonCfg.CentralChannel = pAdapter->CommonCfg.Channel + 2;
-            AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.CentralChannel, FALSE);
-		    AsicLockChannel(pAdapter, pAdapter->CommonCfg.CentralChannel);
-            DBGPRINT(RT_DEBUG_TRACE, ("BW_40 ,control_channel(%d), CentralChannel(%d) \n",
-                                       pAdapter->CommonCfg.Channel,
-                                       pAdapter->CommonCfg.CentralChannel));
-		}
-		else if (pAdapter->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-                 pAdapter->CommonCfg.RegTransmitSetting.field.BW == BW_40 &&
-                 pAdapter->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_BELOW)
-		{
-			// 40MHz ,control channel at upper
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			bbpValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_40;
-			RTMP_IO_READ32(pAdapter, TX_BAND_CFG, &Value);
-			Value |= 0x1;
-			RTMP_IO_WRITE32(pAdapter, TX_BAND_CFG, Value);
-
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R3, &bbpValue);
-			bbpValue |= (0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R3, bbpValue);
-			pAdapter->CommonCfg.CentralChannel = pAdapter->CommonCfg.Channel - 2;
-            AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.CentralChannel, FALSE);
-		    AsicLockChannel(pAdapter, pAdapter->CommonCfg.CentralChannel);
-            DBGPRINT(RT_DEBUG_TRACE, ("BW_40 ,control_channel(%d), CentralChannel(%d) \n",
-                                       pAdapter->CommonCfg.Channel,
-                                       pAdapter->CommonCfg.CentralChannel));
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			// 20MHz
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_20;
-			AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.Channel, FALSE);
-			AsicLockChannel(pAdapter, pAdapter->CommonCfg.Channel);
-			DBGPRINT(RT_DEBUG_TRACE, ("BW_20, Channel(%d)\n", pAdapter->CommonCfg.Channel));
-		}
-		// Enable Rx with promiscuous reception
-		RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, 0x3);
-		// ASIC supporsts sniffer function with replacing RSSI with timestamp.
-		//RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-		//Value |= (0x80);
-		//RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-		// disable sync
-		RTMP_IO_READ32(pAdapter, BCN_TIME_CFG, &csr.word);
-		csr.field.bBeaconGen = 0;
-		csr.field.bTBTTEnable = 0;
-		csr.field.TsfSyncMode = 0;
-		RTMP_IO_WRITE32(pAdapter, BCN_TIME_CFG, csr.word);
-
-		pAdapter->StaCfg.BssType = BSS_MONITOR;
-        pAdapter->net_dev->type = ARPHRD_IEEE80211_PRISM; //ARPHRD_IEEE80211; // IEEE80211
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(MONITOR)\n"));
-    }
-
-    // Reset Ralink supplicant to not use, it will be set to start when UI set PMK key
-    pAdapter->StaCfg.WpaState = SS_NOTUSE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_NetworkType_Proc::(NetworkType=%d)\n", pAdapter->StaCfg.BssType));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Authentication mode
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_AuthMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if ((strcmp(arg, "WEPAUTO") == 0) || (strcmp(arg, "wepauto") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeAutoSwitch;
-    else if ((strcmp(arg, "OPEN") == 0) || (strcmp(arg, "open") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-    else if ((strcmp(arg, "SHARED") == 0) || (strcmp(arg, "shared") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-    else if ((strcmp(arg, "WPAPSK") == 0) || (strcmp(arg, "wpapsk") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPAPSK;
-    else if ((strcmp(arg, "WPANONE") == 0) || (strcmp(arg, "wpanone") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
-    else if ((strcmp(arg, "WPA2PSK") == 0) || (strcmp(arg, "wpa2psk") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-#ifdef WPA_SUPPLICANT_SUPPORT
-    else if ((strcmp(arg, "WPA") == 0) || (strcmp(arg, "wpa") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
-    else if ((strcmp(arg, "WPA2") == 0) || (strcmp(arg, "wpa2") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#endif // WPA_SUPPLICANT_SUPPORT //
-    else
-        return FALSE;
-
-    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_AuthMode_Proc::(AuthMode=%d)\n", pAdapter->StaCfg.AuthMode));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Encryption Type
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_EncrypType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if ((strcmp(arg, "NONE") == 0) || (strcmp(arg, "none") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11WEPDisabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11WEPDisabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11WEPDisabled;
-    }
-    else if ((strcmp(arg, "WEP") == 0) || (strcmp(arg, "wep") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11WEPEnabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11WEPEnabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11WEPEnabled;
-    }
-    else if ((strcmp(arg, "TKIP") == 0) || (strcmp(arg, "tkip") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11Encryption2Enabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11Encryption2Enabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11Encryption2Enabled;
-    }
-    else if ((strcmp(arg, "AES") == 0) || (strcmp(arg, "aes") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11Encryption3Enabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11Encryption3Enabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11Encryption3Enabled;
-    }
-    else
-        return FALSE;
-
-    pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_EncrypType_Proc::(EncrypType=%d)\n", pAdapter->StaCfg.WepStatus));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Default Key ID
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_DefaultKeyID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    ULONG                               KeyIdx;
-
-    KeyIdx = simple_strtol(arg, 0, 10);
-    if((KeyIdx >= 1 ) && (KeyIdx <= 4))
-        pAdapter->StaCfg.DefaultKeyId = (UCHAR) (KeyIdx - 1 );
-    else
-        return FALSE;  //Invalid argument
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_DefaultKeyID_Proc::(DefaultKeyID=%d)\n", pAdapter->StaCfg.DefaultKeyId));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY1
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key1_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][0].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][0].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][0].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][0].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-
-    pAdapter->SharedKey[BSS0][0].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              0,
-                              pAdapter->SharedKey[BSS0][0].CipherAlg,
-                              pAdapter->SharedKey[BSS0][0].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-
-    Description:
-        Set WEP KEY2
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key2_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][1].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][1].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][1].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][1].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][1].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              1,
-                              pAdapter->SharedKey[BSS0][1].CipherAlg,
-                              pAdapter->SharedKey[BSS0][1].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY3
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key3_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][2].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Ascii)\n", arg));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][2].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Hex)\n", arg));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][2].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Ascii)\n", arg));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][2].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Hex)\n", arg));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][2].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              2,
-                              pAdapter->SharedKey[BSS0][2].CipherAlg,
-                              pAdapter->SharedKey[BSS0][2].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY4
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key4_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][3].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][3].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][3].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][3].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][3].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              3,
-                              pAdapter->SharedKey[BSS0][3].CipherAlg,
-                              pAdapter->SharedKey[BSS0][3].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set WPA PSK key
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_WPAPSK_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    UCHAR                   keyMaterial[40];
-
-    if ((pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPAPSK) &&
-        (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-	    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone)
-		)
-        return TRUE;    // do nothing
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_WPAPSK_Proc::(WPAPSK=%s)\n", arg));
-
-    NdisZeroMemory(keyMaterial, 40);
-
-    if ((strlen(arg) < 8) || (strlen(arg) > 64))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("Set failed!!(WPAPSK=%s), WPAPSK key-string required 8 ~ 64 characters \n", arg));
-        return FALSE;
-    }
-
-    if (strlen(arg) == 64)
-    {
-        AtoH(arg, keyMaterial, 32);
-        NdisMoveMemory(pAdapter->StaCfg.PMK, keyMaterial, 32);
-
-    }
-    else
-    {
-        PasswordHash((char *)arg, pAdapter->MlmeAux.Ssid, pAdapter->MlmeAux.SsidLen, keyMaterial);
-        NdisMoveMemory(pAdapter->StaCfg.PMK, keyMaterial, 32);
-    }
-
-
-
-    if(pAdapter->StaCfg.BssType == BSS_ADHOC &&
-       pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-    {
-         pAdapter->StaCfg.WpaState = SS_NOTUSE;
-    }
-    else
-    {
-        // Start STA supplicant state machine
-        pAdapter->StaCfg.WpaState = SS_START;
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Power Saving mode
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_PSMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if (pAdapter->StaCfg.BssType == BSS_INFRA)
-    {
-        if ((strcmp(arg, "Max_PSP") == 0) ||
-			(strcmp(arg, "max_psp") == 0) ||
-			(strcmp(arg, "MAX_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeMAX_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeMAX_PSP;
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            pAdapter->StaCfg.DefaultListenCount = 5;
-
-        }
-        else if ((strcmp(arg, "Fast_PSP") == 0) ||
-				 (strcmp(arg, "fast_psp") == 0) ||
-                 (strcmp(arg, "FAST_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeFast_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeFast_PSP;
-            pAdapter->StaCfg.DefaultListenCount = 3;
-        }
-        else if ((strcmp(arg, "Legacy_PSP") == 0) ||
-                 (strcmp(arg, "legacy_psp") == 0) ||
-                 (strcmp(arg, "LEGACY_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeLegacy_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeLegacy_PSP;
-            pAdapter->StaCfg.DefaultListenCount = 3;
-        }
-        else
-        {
-            //Default Ndis802_11PowerModeCAM
-            // clear PSM bit immediately
-            MlmeSetPsmBit(pAdapter, PWR_ACTIVE);
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeCAM;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeCAM;
-        }
-
-        DBGPRINT(RT_DEBUG_TRACE, ("Set_PSMode_Proc::(PSMode=%ld)\n", pAdapter->StaCfg.WindowsPowerMode));
-    }
-    else
-        return FALSE;
-
-
-    return TRUE;
-}
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-/*
-    ==========================================================================
-    Description:
-        Set WpaSupport flag.
-    Value:
-        0: Driver ignore wpa_supplicant.
-        1: wpa_supplicant initiates scanning and AP selection.
-        2: driver takes care of scanning, AP selection, and IEEE 802.11 association parameters.
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Wpa_Support(
-    IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-    if ( simple_strtol(arg, 0, 10) == 0)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_DISABLE;
-    else if ( simple_strtol(arg, 0, 10) == 1)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_ENABLE;
-    else if ( simple_strtol(arg, 0, 10) == 2)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_ENABLE_WITH_WEB_UI;
-    else
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_DISABLE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_Wpa_Support::(WpaSupplicantUP=%d)\n", pAd->StaCfg.WpaSupplicantUP));
-
-    return TRUE;
-}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef DBG
-/*
-    ==========================================================================
-    Description:
-        Read / Write MAC
-    Arguments:
-        pAdapter                    Pointer to our adapter
-        wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-               1.) iwpriv ra0 mac 0        ==> read MAC where Addr=0x0
-               2.) iwpriv ra0 mac 0=12     ==> write MAC where Addr=0x0, value=12
-    ==========================================================================
-*/
-VOID RTMPIoctlMAC(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	CHAR				*this_char;
-	CHAR				*value;
-	INT					j = 0, k = 0;
-	CHAR				msg[1024];
-	CHAR				arg[255];
-	ULONG				macAddr = 0;
-	UCHAR				temp[16], temp2[16];
-	UINT32				macValue = 0;
-	INT					Status;
-
-
-	memset(msg, 0x00, 1024);
-	if (wrq->u.data.length > 1) //No parameters.
-	{
-	    Status = copy_from_user(arg, wrq->u.data.pointer, (wrq->u.data.length > 255) ? 255 : wrq->u.data.length);
-		sprintf(msg, "\n");
-
-		//Parsing Read or Write
-	    this_char = arg;
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-			// Sanity check
-			if(strlen(this_char) > 4)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			// Mac Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			if(strlen(this_char) == 4)
-			{
-				AtoH(this_char, temp, 2);
-				macAddr = *temp*256 + temp[1];
-				if (macAddr < 0xFFFF)
-				{
-					RTMP_IO_READ32(pAdapter, macAddr, &macValue);
-					DBGPRINT(RT_DEBUG_TRACE, ("MacAddr=%lx, MacValue=%x\n", macAddr, macValue));
-					sprintf(msg+strlen(msg), "[0x%08lX]:%08X  ", macAddr , macValue);
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					goto next;
-				}
-			}
-		}
-		else
-		{ //Write
-			memcpy(&temp2, value, strlen(value));
-			temp2[strlen(value)] = '\0';
-
-			// Sanity check
-			if((strlen(this_char) > 4) || strlen(temp2) > 8)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			j = strlen(temp2);
-			while(j-- > 0)
-			{
-				if(temp2[j] > 'f' || temp2[j] < '0')
-					return;
-			}
-
-			//MAC Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			//MAC value
-			k = j = strlen(temp2);
-			while(j-- > 0)
-			{
-				temp2[8-k+j] = temp2[j];
-			}
-
-			while(k < 8)
-				temp2[7-k++]='0';
-			temp2[8]='\0';
-
-			{
-				AtoH(this_char, temp, 2);
-				macAddr = *temp*256 + temp[1];
-
-				AtoH(temp2, temp, 4);
-				macValue = *temp*256*256*256 + temp[1]*256*256 + temp[2]*256 + temp[3];
-
-				// debug mode
-				if (macAddr == (HW_DEBUG_SETTING_BASE + 4))
-				{
-					// 0x2bf4: byte0 non-zero: enable R17 tuning, 0: disable R17 tuning
-                    if (macValue & 0x000000ff)
-                    {
-                        pAdapter->BbpTuning.bEnable = TRUE;
-                        DBGPRINT(RT_DEBUG_TRACE,("turn on R17 tuning\n"));
-                    }
-                    else
-                    {
-                        UCHAR R66;
-                        pAdapter->BbpTuning.bEnable = FALSE;
-                        R66 = 0x26 + GET_LNA_GAIN(pAdapter);
-#ifdef RALINK_ATE
-						if (ATE_ON(pAdapter))
-						{
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R66, (0x26 + GET_LNA_GAIN(pAdapter)));
-						}
-						else
-#endif // RALINK_ATE //
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R66, (0x26 + GET_LNA_GAIN(pAdapter)));
-                        DBGPRINT(RT_DEBUG_TRACE,("turn off R17 tuning, restore to 0x%02x\n", R66));
-                    }
-					return;
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE, ("MacAddr=%02lx, MacValue=0x%x\n", macAddr, macValue));
-
-				RTMP_IO_WRITE32(pAdapter, macAddr, macValue);
-				sprintf(msg+strlen(msg), "[0x%08lX]:%08X  ", macAddr, macValue);
-			}
-		}
-	}
-next:
-	if(strlen(msg) == 1)
-		sprintf(msg+strlen(msg), "===>Error command format!");
-
-	// Copy the information into the user buffer
-	wrq->u.data.length = strlen(msg);
-	Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==RTMPIoctlMAC\n\n"));
-}
-
-/*
-    ==========================================================================
-    Description:
-        Read / Write E2PROM
-    Arguments:
-        pAdapter                    Pointer to our adapter
-        wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-               1.) iwpriv ra0 e2p 0     	==> read E2PROM where Addr=0x0
-               2.) iwpriv ra0 e2p 0=1234    ==> write E2PROM where Addr=0x0, value=1234
-    ==========================================================================
-*/
-VOID RTMPIoctlE2PROM(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	CHAR				*this_char;
-	CHAR				*value;
-	INT					j = 0, k = 0;
-	CHAR				msg[1024];
-	CHAR				arg[255];
-	USHORT				eepAddr = 0;
-	UCHAR				temp[16], temp2[16];
-	USHORT				eepValue;
-	int					Status;
-
-
-	memset(msg, 0x00, 1024);
-	if (wrq->u.data.length > 1) //No parameters.
-	{
-	    Status = copy_from_user(arg, wrq->u.data.pointer, (wrq->u.data.length > 255) ? 255 : wrq->u.data.length);
-		sprintf(msg, "\n");
-
-	    //Parsing Read or Write
-		this_char = arg;
-
-
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-
-			// Sanity check
-			if(strlen(this_char) > 4)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			// E2PROM addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			if(strlen(this_char) == 4)
-			{
-				AtoH(this_char, temp, 2);
-				eepAddr = *temp*256 + temp[1];
-				if (eepAddr < 0xFFFF)
-				{
-					RT28xx_EEPROM_READ16(pAdapter, eepAddr, eepValue);
-					sprintf(msg+strlen(msg), "[0x%04X]:0x%04X  ", eepAddr , eepValue);
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					goto next;
-				}
-			}
-		}
-		else
-		{ //Write
-			memcpy(&temp2, value, strlen(value));
-			temp2[strlen(value)] = '\0';
-
-			// Sanity check
-			if((strlen(this_char) > 4) || strlen(temp2) > 8)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-			j = strlen(temp2);
-			while(j-- > 0)
-			{
-				if(temp2[j] > 'f' || temp2[j] < '0')
-					return;
-			}
-
-			//MAC Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			//MAC value
-			k = j = strlen(temp2);
-			while(j-- > 0)
-			{
-				temp2[4-k+j] = temp2[j];
-			}
-
-			while(k < 4)
-				temp2[3-k++]='0';
-			temp2[4]='\0';
-
-			AtoH(this_char, temp, 2);
-			eepAddr = *temp*256 + temp[1];
-
-			AtoH(temp2, temp, 2);
-			eepValue = *temp*256 + temp[1];
-
-			RT28xx_EEPROM_WRITE16(pAdapter, eepAddr, eepValue);
-			sprintf(msg+strlen(msg), "[0x%02X]:%02X  ", eepAddr, eepValue);
-		}
-	}
-next:
-	if(strlen(msg) == 1)
-		sprintf(msg+strlen(msg), "===>Error command format!");
-
-
-	// Copy the information into the user buffer
-	wrq->u.data.length = strlen(msg);
-	Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==RTMPIoctlE2PROM\n"));
-}
-#endif // DBG //
-
-
-
-
-INT Set_TGnWifiTest_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAd->StaCfg.bTGnWifiTest = FALSE;
-    else
-        pAd->StaCfg.bTGnWifiTest = TRUE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IF Set_TGnWifiTest_Proc::(bTGnWifiTest=%d)\n", pAd->StaCfg.bTGnWifiTest));
-	return TRUE;
-}
-
-INT Set_LongRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg)
-{
-	TX_RTY_CFG_STRUC	tx_rty_cfg;
-	UCHAR				LongRetryLimit = (UCHAR)simple_strtol(arg, 0, 10);
-
-	RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-	tx_rty_cfg.field.LongRtyLimit = LongRetryLimit;
-	RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-	DBGPRINT(RT_DEBUG_TRACE, ("IF Set_LongRetryLimit_Proc::(tx_rty_cfg=0x%x)\n", tx_rty_cfg.word));
-	return TRUE;
-}
-
-INT Set_ShortRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg)
-{
-	TX_RTY_CFG_STRUC	tx_rty_cfg;
-	UCHAR				ShortRetryLimit = (UCHAR)simple_strtol(arg, 0, 10);
-
-	RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-	tx_rty_cfg.field.ShortRtyLimit = ShortRetryLimit;
-	RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-	DBGPRINT(RT_DEBUG_TRACE, ("IF Set_ShortRetryLimit_Proc::(tx_rty_cfg=0x%x)\n", tx_rty_cfg.word));
-	return TRUE;
-}
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-INT Set_Ieee80211dClientMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_None;
-    else if (simple_strtol(arg, 0, 10) == 1)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_Flexible;
-    else if (simple_strtol(arg, 0, 10) == 2)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_Strict;
-    else
-        return FALSE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_Ieee802dMode_Proc::(IEEEE0211dMode=%d)\n", pAdapter->StaCfg.IEEE80211dClientMode));
-    return TRUE;
-}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef CARRIER_DETECTION_SUPPORT
-INT Set_CarrierDetect_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-    else
-        pAd->CommonCfg.CarrierDetect.Enable = TRUE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IF Set_CarrierDetect_Proc::(CarrierDetect.Enable=%d)\n", pAd->CommonCfg.CarrierDetect.Enable));
-	return TRUE;
-}
-#endif // CARRIER_DETECTION_SUPPORT //
-
-
-INT	Show_Adhoc_MacTable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PCHAR			extra)
-{
-	INT i;
-
-	sprintf(extra, "\n");
-
-#ifdef DOT11_N_SUPPORT
-	sprintf(extra, "%sHT Operating Mode : %d\n", extra, pAd->CommonCfg.AddHTInfo.AddHtInfo2.OperaionMode);
-#endif // DOT11_N_SUPPORT //
-
-	sprintf(extra, "%s\n%-19s%-4s%-4s%-7s%-7s%-7s%-10s%-6s%-6s%-6s%-6s\n", extra,
-			"MAC", "AID", "BSS", "RSSI0", "RSSI1", "RSSI2", "PhMd", "BW", "MCS", "SGI", "STBC");
-
-	for (i=1; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[i];
-
-		if (strlen(extra) > (IW_PRIV_SIZE_MASK - 30))
-		    break;
-		if ((pEntry->ValidAsCLI || pEntry->ValidAsApCli) && (pEntry->Sst == SST_ASSOC))
-		{
-			sprintf(extra, "%s%02X:%02X:%02X:%02X:%02X:%02X  ", extra,
-				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
-				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5]);
-			sprintf(extra, "%s%-4d", extra, (int)pEntry->Aid);
-			sprintf(extra, "%s%-4d", extra, (int)pEntry->apidx);
-			sprintf(extra, "%s%-7d", extra, pEntry->RssiSample.AvgRssi0);
-			sprintf(extra, "%s%-7d", extra, pEntry->RssiSample.AvgRssi1);
-			sprintf(extra, "%s%-7d", extra, pEntry->RssiSample.AvgRssi2);
-			sprintf(extra, "%s%-10s", extra, GetPhyMode(pEntry->HTPhyMode.field.MODE));
-			sprintf(extra, "%s%-6s", extra, GetBW(pEntry->HTPhyMode.field.BW));
-			sprintf(extra, "%s%-6d", extra, pEntry->HTPhyMode.field.MCS);
-			sprintf(extra, "%s%-6d", extra, pEntry->HTPhyMode.field.ShortGI);
-			sprintf(extra, "%s%-6d", extra, pEntry->HTPhyMode.field.STBC);
-			sprintf(extra, "%s%-10d, %d, %d%%\n", extra, pEntry->DebugFIFOCount, pEntry->DebugTxCount,
-						(pEntry->DebugTxCount) ? ((pEntry->DebugTxCount-pEntry->DebugFIFOCount)*100/pEntry->DebugTxCount) : 0);
-			sprintf(extra, "%s\n", extra);
-		}
-	}
-
-	return TRUE;
-}
-
-
diff --git a/drivers/staging/rt2870/wpa.h b/drivers/staging/rt2870/wpa.h
index 0134ae6..7125072 100644
--- a/drivers/staging/rt2870/wpa.h
+++ b/drivers/staging/rt2870/wpa.h
@@ -1,357 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	wpa.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-*/
-
-#ifndef	__WPA_H__
-#define	__WPA_H__
-
-// EAPOL Key descripter frame format related length
-#define LEN_KEY_DESC_NONCE			32
-#define LEN_KEY_DESC_IV				16
-#define LEN_KEY_DESC_RSC			8
-#define LEN_KEY_DESC_ID				8
-#define LEN_KEY_DESC_REPLAY			8
-#define LEN_KEY_DESC_MIC			16
-
-// The length is the EAPoL-Key frame except key data field.
-// Please refer to 802.11i-2004 ,Figure 43u in p.78
-#define LEN_EAPOL_KEY_MSG			(sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE)
-
-// EAP Code Type.
-#define EAP_CODE_REQUEST	1
-#define EAP_CODE_RESPONSE	2
-#define EAP_CODE_SUCCESS    3
-#define EAP_CODE_FAILURE    4
-
-// EAPOL frame Protocol Version
-#define	EAPOL_VER					1
-#define	EAPOL_VER2					2
-
-// EAPOL-KEY Descriptor Type
-#define	WPA1_KEY_DESC				0xfe
-#define WPA2_KEY_DESC               0x02
-
-// Key Descriptor Version of Key Information
-#define	DESC_TYPE_TKIP				1
-#define	DESC_TYPE_AES				2
-#define DESC_TYPE_MESH				3
-
-#define LEN_MSG1_2WAY               0x7f
-#define MAX_LEN_OF_EAP_HS           256
-
-#define LEN_MASTER_KEY				32
-
-// EAPOL EK, MK
-#define LEN_EAP_EK					16
-#define LEN_EAP_MICK				16
-#define LEN_EAP_KEY					((LEN_EAP_EK)+(LEN_EAP_MICK))
-// TKIP key related
-#define LEN_PMKID					16
-#define LEN_TKIP_EK					16
-#define LEN_TKIP_RXMICK				8
-#define LEN_TKIP_TXMICK				8
-#define LEN_AES_EK					16
-#define LEN_AES_KEY					LEN_AES_EK
-#define LEN_TKIP_KEY				((LEN_TKIP_EK)+(LEN_TKIP_RXMICK)+(LEN_TKIP_TXMICK))
-#define TKIP_AP_TXMICK_OFFSET		((LEN_EAP_KEY)+(LEN_TKIP_EK))
-#define TKIP_AP_RXMICK_OFFSET		(TKIP_AP_TXMICK_OFFSET+LEN_TKIP_TXMICK)
-#define TKIP_GTK_LENGTH				((LEN_TKIP_EK)+(LEN_TKIP_RXMICK)+(LEN_TKIP_TXMICK))
-#define LEN_PTK						((LEN_EAP_KEY)+(LEN_TKIP_KEY))
-#define MIN_LEN_OF_GTK				5
-
-// RSN IE Length definition
-#define MAX_LEN_OF_RSNIE         	90
-#define MIN_LEN_OF_RSNIE         	8
-
-//EAP Packet Type
-#define	EAPPacket		0
-#define	EAPOLStart		1
-#define	EAPOLLogoff		2
-#define	EAPOLKey		3
-#define	EAPOLASFAlert	4
-#define	EAPTtypeMax		5
-
-#define	EAPOL_MSG_INVALID	0
-#define	EAPOL_PAIR_MSG_1	1
-#define	EAPOL_PAIR_MSG_2	2
-#define	EAPOL_PAIR_MSG_3	3
-#define	EAPOL_PAIR_MSG_4	4
-#define	EAPOL_GROUP_MSG_1	5
-#define	EAPOL_GROUP_MSG_2	6
-
-#define PAIRWISEKEY					1
-#define GROUPKEY					0
-
-// Retry timer counter initial value
-#define PEER_MSG1_RETRY_TIMER_CTR           0
-#define PEER_MSG3_RETRY_TIMER_CTR           10
-#define GROUP_MSG1_RETRY_TIMER_CTR          20
-
-
-#define EAPOL_START_DISABLE					0
-#define EAPOL_START_PSK						1
-#define EAPOL_START_1X						2
-
-#define MIX_CIPHER_WPA_TKIP_ON(x)       (((x) & 0x08) != 0)
-#define MIX_CIPHER_WPA_AES_ON(x)        (((x) & 0x04) != 0)
-#define MIX_CIPHER_WPA2_TKIP_ON(x)      (((x) & 0x02) != 0)
-#define MIX_CIPHER_WPA2_AES_ON(x)       (((x) & 0x01) != 0)
-
-#define ROUND_UP(__x, __y) \
-	(((ULONG)((__x)+((__y)-1))) & ((ULONG)~((__y)-1)))
-
-#define	ADD_ONE_To_64BIT_VAR(_V)		\
-{										\
-	UCHAR	cnt = LEN_KEY_DESC_REPLAY;	\
-	do									\
-	{									\
-		cnt--;							\
-		_V[cnt]++;						\
-		if (cnt == 0)					\
-			break;						\
-	}while (_V[cnt] == 0);				\
-}
-
-#define IS_WPA_CAPABILITY(a)       (((a) >= Ndis802_11AuthModeWPA) && ((a) <= Ndis802_11AuthModeWPA1PSKWPA2PSK))
-
-// EAPOL Key Information definition within Key descriptor format
-typedef	struct PACKED _KEY_INFO
-{
-#ifdef RT_BIG_ENDIAN
-	UCHAR	KeyAck:1;
-    UCHAR	Install:1;
-    UCHAR	KeyIndex:2;
-    UCHAR	KeyType:1;
-    UCHAR	KeyDescVer:3;
-    UCHAR	Rsvd:3;
-    UCHAR	EKD_DL:1;		// EKD for AP; DL for STA
-    UCHAR	Request:1;
-    UCHAR	Error:1;
-    UCHAR	Secure:1;
-    UCHAR	KeyMic:1;
-#else
-	UCHAR	KeyMic:1;
-	UCHAR	Secure:1;
-	UCHAR	Error:1;
-	UCHAR	Request:1;
-	UCHAR	EKD_DL:1;       // EKD for AP; DL for STA
-	UCHAR	Rsvd:3;
-	UCHAR	KeyDescVer:3;
-	UCHAR	KeyType:1;
-	UCHAR	KeyIndex:2;
-	UCHAR	Install:1;
-	UCHAR	KeyAck:1;
-#endif
-}	KEY_INFO, *PKEY_INFO;
-
-// EAPOL Key descriptor format
-typedef	struct PACKED _KEY_DESCRIPTER
-{
-	UCHAR		Type;
-	KEY_INFO	KeyInfo;
-	UCHAR		KeyLength[2];
-	UCHAR		ReplayCounter[LEN_KEY_DESC_REPLAY];
-	UCHAR		KeyNonce[LEN_KEY_DESC_NONCE];
-	UCHAR		KeyIv[LEN_KEY_DESC_IV];
-	UCHAR		KeyRsc[LEN_KEY_DESC_RSC];
-	UCHAR		KeyId[LEN_KEY_DESC_ID];
-	UCHAR		KeyMic[LEN_KEY_DESC_MIC];
-	UCHAR		KeyDataLen[2];
-	UCHAR		KeyData[MAX_LEN_OF_RSNIE];
-}	KEY_DESCRIPTER, *PKEY_DESCRIPTER;
-
-typedef	struct PACKED _EAPOL_PACKET
-{
-	UCHAR	 			ProVer;
-	UCHAR	 			ProType;
-	UCHAR	 			Body_Len[2];
-	KEY_DESCRIPTER		KeyDesc;
-}	EAPOL_PACKET, *PEAPOL_PACKET;
-
-//802.11i D10 page 83
-typedef struct PACKED _GTK_ENCAP
-{
-#ifndef RT_BIG_ENDIAN
-    UCHAR               Kid:2;
-    UCHAR               tx:1;
-    UCHAR               rsv:5;
-    UCHAR               rsv1;
-#else
-    UCHAR               rsv:5;
-    UCHAR               tx:1;
-    UCHAR               Kid:2;
-    UCHAR               rsv1;
-#endif
-    UCHAR               GTK[TKIP_GTK_LENGTH];
-}   GTK_ENCAP, *PGTK_ENCAP;
-
-typedef struct PACKED _KDE_ENCAP
-{
-    UCHAR               Type;
-    UCHAR               Len;
-    UCHAR               OUI[3];
-    UCHAR               DataType;
-    GTK_ENCAP      GTKEncap;
-}   KDE_ENCAP, *PKDE_ENCAP;
-
-// For WPA1
-typedef struct PACKED _RSNIE {
-    UCHAR   oui[4];
-    USHORT  version;
-    UCHAR   mcast[4];
-    USHORT  ucount;
-    struct PACKED {
-        UCHAR oui[4];
-    }ucast[1];
-} RSNIE, *PRSNIE;
-
-// For WPA2
-typedef struct PACKED _RSNIE2 {
-    USHORT  version;
-    UCHAR   mcast[4];
-    USHORT  ucount;
-    struct PACKED {
-        UCHAR oui[4];
-    }ucast[1];
-} RSNIE2, *PRSNIE2;
-
-// AKM Suite
-typedef struct PACKED _RSNIE_AUTH {
-    USHORT acount;
-    struct PACKED {
-        UCHAR oui[4];
-    }auth[1];
-} RSNIE_AUTH,*PRSNIE_AUTH;
-
-typedef	union PACKED _RSN_CAPABILITIES	{
-	struct	PACKED {
-#ifdef RT_BIG_ENDIAN
-        USHORT		Rsvd:10;
-        USHORT		GTKSA_R_Counter:2;
-        USHORT		PTKSA_R_Counter:2;
-        USHORT		No_Pairwise:1;
-		USHORT		PreAuth:1;
-#else
-        USHORT		PreAuth:1;
-		USHORT		No_Pairwise:1;
-		USHORT		PTKSA_R_Counter:2;
-		USHORT		GTKSA_R_Counter:2;
-		USHORT		Rsvd:10;
-#endif
-	}	field;
-	USHORT			word;
-}	RSN_CAPABILITIES, *PRSN_CAPABILITIES;
-
-typedef struct PACKED _EAP_HDR {
-    UCHAR   ProVer;
-    UCHAR   ProType;
-    UCHAR   Body_Len[2];
-    UCHAR   code;
-    UCHAR   identifier;
-    UCHAR   length[2]; // including code and identifier, followed by length-2 octets of data
-} EAP_HDR, *PEAP_HDR;
-
-// For supplicant state machine states. 802.11i Draft 4.1, p. 97
-// We simplified it
-typedef	enum	_WpaState
-{
-	SS_NOTUSE,				// 0
-	SS_START,				// 1
-	SS_WAIT_MSG_3,			// 2
-	SS_WAIT_GROUP,			// 3
-	SS_FINISH,  			// 4
-	SS_KEYUPDATE,			// 5
-}	WPA_STATE;
-
-//
-//	The definition of the cipher combination
-//
-// 	 bit3	bit2  bit1   bit0
-//	+------------+------------+
-// 	|	  WPA	 |	   WPA2   |
-//	+------+-----+------+-----+
-//	| TKIP | AES | TKIP | AES |
-//	|	0  |  1  |   1  |  0  | -> 0x06
-//	|	0  |  1  |   1  |  1  | -> 0x07
-//	|	1  |  0  |   0  |  1  | -> 0x09
-//	|	1  |  0  |   1  |  1  | -> 0x0B
-//	|	1  |  1  |   0  |  1  | -> 0x0D
-//	|	1  |  1  |   1  |  0  | -> 0x0E
-//	|	1  |  1  |   1  |  1  |	-> 0x0F
-//	+------+-----+------+-----+
-//
-typedef	enum	_WpaMixPairCipher
-{
-	MIX_CIPHER_NOTUSE 			= 0x00,
-	WPA_NONE_WPA2_TKIPAES		= 0x03,		// WPA2-TKIPAES
-	WPA_AES_WPA2_TKIP 			= 0x06,
-	WPA_AES_WPA2_TKIPAES		= 0x07,
-	WPA_TKIP_WPA2_AES			= 0x09,
-	WPA_TKIP_WPA2_TKIPAES		= 0x0B,
-	WPA_TKIPAES_WPA2_NONE		= 0x0C,		// WPA-TKIPAES
-	WPA_TKIPAES_WPA2_AES		= 0x0D,
-	WPA_TKIPAES_WPA2_TKIP		= 0x0E,
-	WPA_TKIPAES_WPA2_TKIPAES	= 0x0F,
-}	WPA_MIX_PAIR_CIPHER;
-
-typedef struct PACKED _RSN_IE_HEADER_STRUCT	{
-	UCHAR		Eid;
-	UCHAR		Length;
-	USHORT		Version;	// Little endian format
-}	RSN_IE_HEADER_STRUCT, *PRSN_IE_HEADER_STRUCT;
-
-// Cipher suite selector types
-typedef struct PACKED _CIPHER_SUITE_STRUCT	{
-	UCHAR		Oui[3];
-	UCHAR		Type;
-}	CIPHER_SUITE_STRUCT, *PCIPHER_SUITE_STRUCT;
-
-// Authentication and Key Management suite selector
-typedef struct PACKED _AKM_SUITE_STRUCT	{
-	UCHAR		Oui[3];
-	UCHAR		Type;
-}	AKM_SUITE_STRUCT, *PAKM_SUITE_STRUCT;
-
-// RSN capability
-typedef struct	PACKED _RSN_CAPABILITY	{
-	USHORT		Rsv:10;
-	USHORT		GTKSAReplayCnt:2;
-	USHORT		PTKSAReplayCnt:2;
-	USHORT		NoPairwise:1;
-	USHORT		PreAuth:1;
-}	RSN_CAPABILITY, *PRSN_CAPABILITY;
-
-#endif
+#include "../rt2860/wpa.h"
diff --git a/drivers/staging/rt3070/2870_main_dev.c b/drivers/staging/rt3070/2870_main_dev.c
index 401ddb0..32427c0 100644
--- a/drivers/staging/rt3070/2870_main_dev.c
+++ b/drivers/staging/rt3070/2870_main_dev.c
@@ -1,1627 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    rtmp_main.c
-
-    Abstract:
-    main initialization routines
-
-    Revision History:
-    Who         When            What
-    --------    ----------      ----------------------------------------------
-    Name        Date            Modification logs
-    Jan Lee		01-10-2005	    modified
-	Sample		Jun/01/07		Merge RT2870 and RT2860 drivers.
-*/
-
-#include "rt_config.h"
-
-
-// Following information will be show when you run 'modinfo'
-// *** If you have a solution for the bug in current version of driver, please mail to me.
-// Otherwise post to forum in ralinktech's web site(www.ralinktech.com) and let all users help you. ***
-MODULE_AUTHOR("Paul Lin <paul_lin@ralinktech.com>");
-MODULE_DESCRIPTION("RT2870 Wireless Lan Linux Driver");
-#ifdef CONFIG_STA_SUPPORT
-MODULE_LICENSE("GPL");
-#ifdef MODULE_VERSION
-MODULE_VERSION(STA_DRIVER_VERSION);
-#endif
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef MULTIPLE_CARD_SUPPORT
-// record whether the card in the card list is used in the card file
-extern UINT8  MC_CardUsed[];
-#endif // MULTIPLE_CARD_SUPPORT //
-
-/* Kernel thread and vars, which handles packets that are completed. Only
- * packets that have a "complete" function are sent here. This way, the
- * completion is run out of kernel context, and doesn't block the rest of
- * the stack. */
-//static int mlme_kill = 0;		// Mlme kernel thread
-//static int RTUSBCmd_kill = 0;	// Command kernel thread
-//static int TimerFunc_kill = 0;	// TimerQ kernel thread
-
-//static wait_queue_head_t 	timerWaitQ;
-//static wait_queue_t 		waitQ;
-
-extern INT __devinit rt28xx_probe(IN void *_dev_p, IN void *_dev_id_p,
-									IN UINT argc, OUT PRTMP_ADAPTER *ppAd);
-
-
-/* module table */
-struct usb_device_id    rtusb_usb_id[] = RT2870_USB_DEVICES;
-INT const               rtusb_usb_id_len = sizeof(rtusb_usb_id) / sizeof(struct usb_device_id);
-MODULE_DEVICE_TABLE(usb, rtusb_usb_id);
-
-#ifndef PF_NOFREEZE
-#define PF_NOFREEZE  0
-#endif
-
-
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-
-/**************************************************************************/
-/**************************************************************************/
-//tested for kernel 2.4 series
-/**************************************************************************/
-/**************************************************************************/
-static void *rtusb_probe(struct usb_device *dev, UINT interface,
-						const struct usb_device_id *id_table);
-static void rtusb_disconnect(struct usb_device *dev, void *ptr);
-
-struct usb_driver rtusb_driver = {
-		name:"rt2870",
-		probe:rtusb_probe,
-		disconnect:rtusb_disconnect,
-		id_table:rtusb_usb_id,
-	};
-
-#else
-
-#ifdef CONFIG_PM
-static int rt2870_suspend(struct usb_interface *intf, pm_message_t state);
-static int rt2870_resume(struct usb_interface *intf);
-#endif // CONFIG_PM //
-
-/**************************************************************************/
-/**************************************************************************/
-//tested for kernel 2.6series
-/**************************************************************************/
-/**************************************************************************/
-static int rtusb_probe (struct usb_interface *intf,
-						const struct usb_device_id *id);
-static void rtusb_disconnect(struct usb_interface *intf);
-
-struct usb_driver rtusb_driver = {
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,15)
-	.owner = THIS_MODULE,
-#endif
-	.name="rt2870",
-	.probe=rtusb_probe,
-	.disconnect=rtusb_disconnect,
-	.id_table=rtusb_usb_id,
-
-#ifdef CONFIG_PM
-	suspend:	rt2870_suspend,
-	resume:		rt2870_resume,
-#endif
-	};
-
-#ifdef CONFIG_PM
-
-VOID RT2860RejectPendingPackets(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	// clear PS packets
-	// clear TxSw packets
-}
-
-static int rt2870_suspend(
-	struct usb_interface *intf,
-	pm_message_t state)
-{
-	struct net_device *net_dev;
-	PRTMP_ADAPTER pAd = usb_get_intfdata(intf);
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("===> rt2870_suspend()\n"));
-	net_dev = pAd->net_dev;
-			netif_device_detach(net_dev);
-
-	pAd->PM_FlgSuspend = 1;
-	if (netif_running(net_dev)) {
-		RTUSBCancelPendingBulkInIRP(pAd);
-		RTUSBCancelPendingBulkOutIRP(pAd);
-	}
-	DBGPRINT(RT_DEBUG_TRACE, ("<=== rt2870_suspend()\n"));
-	return 0;
-}
-
-static int rt2870_resume(
-	struct usb_interface *intf)
-{
-	struct net_device *net_dev;
-	PRTMP_ADAPTER pAd = usb_get_intfdata(intf);
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("===> rt2870_resume()\n"));
-
-	pAd->PM_FlgSuspend = 0;
-	net_dev = pAd->net_dev;
-			netif_device_attach(net_dev);
-			netif_start_queue(net_dev);
-			netif_carrier_on(net_dev);
-			netif_wake_queue(net_dev);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<=== rt2870_resume()\n"));
-	return 0;
-}
-#endif // CONFIG_PM //
-#endif // LINUX_VERSION_CODE //
-
-
-// Init driver module
-INT __init rtusb_init(void)
-{
-	printk("rtusb init --->\n");
-	return usb_register(&rtusb_driver);
-}
-
-// Deinit driver module
-VOID __exit rtusb_exit(void)
-{
-	usb_deregister(&rtusb_driver);
-	printk("<--- rtusb exit\n");
-}
-
-module_init(rtusb_init);
-module_exit(rtusb_exit);
-
-
-
-
-/*---------------------------------------------------------------------	*/
-/* function declarations												*/
-/*---------------------------------------------------------------------	*/
-
-/*
-========================================================================
-Routine Description:
-    MLME kernel thread.
-
-Arguments:
-	*Context			the pAd, driver control block pointer
-
-Return Value:
-    0					close the thread
-
-Note:
-========================================================================
-*/
-INT MlmeThread(
-	IN void *Context)
-{
-	PRTMP_ADAPTER	pAd = (PRTMP_ADAPTER)Context;
-	POS_COOKIE	pObj;
-	int status;
-
-	pObj = (POS_COOKIE)pAd->OS_Cookie;
-
-	rtmp_os_thread_init("rt2870MlmeThread", (PVOID)&(pAd->mlmeComplete));
-
-	while (pAd->mlme_kill == 0)
-	{
-		/* lock the device pointers */
-		//down(&(pAd->mlme_semaphore));
-		status = down_interruptible(&(pAd->mlme_semaphore));
-
-		/* lock the device pointers , need to check if required*/
-		//down(&(pAd->usbdev_semaphore));
-
-		if (!pAd->PM_FlgSuspend)
-		MlmeHandler(pAd);
-
-		/* unlock the device pointers */
-		//up(&(pAd->usbdev_semaphore));
-		if (status != 0)
-		{
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS);
-			break;
-		}
-	}
-
-	/* notify the exit routine that we're actually exiting now
-	 *
-	 * complete()/wait_for_completion() is similar to up()/down(),
-	 * except that complete() is safe in the case where the structure
-	 * is getting deleted in a parallel mode of execution (i.e. just
-	 * after the down() -- that's necessary for the thread-shutdown
-	 * case.
-	 *
-	 * complete_and_exit() goes even further than this -- it is safe in
-	 * the case that the thread of the caller is going away (not just
-	 * the structure) -- this is necessary for the module-remove case.
-	 * This is important in preemption kernels, which transfer the flow
-	 * of execution immediately upon a complete().
-	 */
-	DBGPRINT(RT_DEBUG_TRACE,( "<---%s\n",__FUNCTION__));
-
-	pObj->MLMEThr_pid = NULL;
-
-	complete_and_exit (&pAd->mlmeComplete, 0);
-	return 0;
-
-}
-
-
-/*
-========================================================================
-Routine Description:
-    USB command kernel thread.
-
-Arguments:
-	*Context			the pAd, driver control block pointer
-
-Return Value:
-    0					close the thread
-
-Note:
-========================================================================
-*/
-INT RTUSBCmdThread(
-	IN void * Context)
-{
-	PRTMP_ADAPTER	pAd = (PRTMP_ADAPTER)Context;
-	POS_COOKIE		pObj;
-	int status;
-
-	pObj = (POS_COOKIE)pAd->OS_Cookie;
-
-	rtmp_os_thread_init("rt2870CmdThread", (PVOID)&(pAd->CmdQComplete));
-
-	NdisAcquireSpinLock(&pAd->CmdQLock);
-	pAd->CmdQ.CmdQState = RT2870_THREAD_RUNNING;
-	NdisReleaseSpinLock(&pAd->CmdQLock);
-
-	while (pAd->CmdQ.CmdQState == RT2870_THREAD_RUNNING)
-	{
-		/* lock the device pointers */
-		//down(&(pAd->RTUSBCmd_semaphore));
-		status = down_interruptible(&(pAd->RTUSBCmd_semaphore));
-
-		if (pAd->CmdQ.CmdQState == RT2870_THREAD_STOPED)
-			break;
-
-		if (status != 0)
-		{
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS);
-			break;
-		}
-		/* lock the device pointers , need to check if required*/
-		//down(&(pAd->usbdev_semaphore));
-
-		if (!pAd->PM_FlgSuspend)
-		CMDHandler(pAd);
-
-		/* unlock the device pointers */
-		//up(&(pAd->usbdev_semaphore));
-	}
-
-	if (!pAd->PM_FlgSuspend)
-	{	// Clear the CmdQElements.
-		CmdQElmt	*pCmdQElmt = NULL;
-
-		NdisAcquireSpinLock(&pAd->CmdQLock);
-		pAd->CmdQ.CmdQState = RT2870_THREAD_STOPED;
-		while(pAd->CmdQ.size)
-		{
-			RTUSBDequeueCmd(&pAd->CmdQ, &pCmdQElmt);
-			if (pCmdQElmt)
-			{
-				if (pCmdQElmt->CmdFromNdis == TRUE)
-				{
-					if (pCmdQElmt->buffer != NULL)
-						NdisFreeMemory(pCmdQElmt->buffer, pCmdQElmt->bufferlength, 0);
-
-					NdisFreeMemory(pCmdQElmt, sizeof(CmdQElmt), 0);
-				}
-				else
-				{
-					if ((pCmdQElmt->buffer != NULL) && (pCmdQElmt->bufferlength != 0))
-						NdisFreeMemory(pCmdQElmt->buffer, pCmdQElmt->bufferlength, 0);
-		            {
-						NdisFreeMemory(pCmdQElmt, sizeof(CmdQElmt), 0);
-					}
-				}
-			}
-		}
-
-		NdisReleaseSpinLock(&pAd->CmdQLock);
-	}
-	/* notify the exit routine that we're actually exiting now
-	 *
-	 * complete()/wait_for_completion() is similar to up()/down(),
-	 * except that complete() is safe in the case where the structure
-	 * is getting deleted in a parallel mode of execution (i.e. just
-	 * after the down() -- that's necessary for the thread-shutdown
-	 * case.
-	 *
-	 * complete_and_exit() goes even further than this -- it is safe in
-	 * the case that the thread of the caller is going away (not just
-	 * the structure) -- this is necessary for the module-remove case.
-	 * This is important in preemption kernels, which transfer the flow
-	 * of execution immediately upon a complete().
-	 */
-	DBGPRINT(RT_DEBUG_TRACE,( "<---RTUSBCmdThread\n"));
-
-	pObj->RTUSBCmdThr_pid = NULL;
-
-	complete_and_exit (&pAd->CmdQComplete, 0);
-	return 0;
-
-}
-
-
-static void RT2870_TimerQ_Handle(RTMP_ADAPTER *pAd)
-{
-	int status;
-	RALINK_TIMER_STRUCT	*pTimer;
-	RT2870_TIMER_ENTRY	*pEntry;
-	unsigned long	irqFlag;
-
-	while(!pAd->TimerFunc_kill)
-	{
-//		printk("waiting for event!\n");
-		pTimer = NULL;
-
-		status = down_interruptible(&(pAd->RTUSBTimer_semaphore));
-
-		if (pAd->TimerQ.status == RT2870_THREAD_STOPED)
-			break;
-
-		// event happened.
-		while(pAd->TimerQ.pQHead)
-		{
-			RTMP_IRQ_LOCK(&pAd->TimerQLock, irqFlag);
-			pEntry = pAd->TimerQ.pQHead;
-			if (pEntry)
-			{
-				pTimer = pEntry->pRaTimer;
-
-				// update pQHead
-				pAd->TimerQ.pQHead = pEntry->pNext;
-				if (pEntry == pAd->TimerQ.pQTail)
-					pAd->TimerQ.pQTail = NULL;
-
-				// return this queue entry to timerQFreeList.
-				pEntry->pNext = pAd->TimerQ.pQPollFreeList;
-				pAd->TimerQ.pQPollFreeList = pEntry;
-			}
-			RTMP_IRQ_UNLOCK(&pAd->TimerQLock, irqFlag);
-
-			if (pTimer)
-			{
-				if (pTimer->handle != NULL)
-				if (!pAd->PM_FlgSuspend)
-					pTimer->handle(NULL, (PVOID) pTimer->cookie, NULL, pTimer);
-				if ((pTimer->Repeat) && (pTimer->State == FALSE))
-					RTMP_OS_Add_Timer(&pTimer->TimerObj, pTimer->TimerValue);
-			}
-		}
-
-		if (status != 0)
-		{
-			pAd->TimerQ.status = RT2870_THREAD_STOPED;
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS);
-			break;
-		}
-	}
-}
-
-
-INT TimerQThread(
-	IN OUT PVOID Context)
-{
-	PRTMP_ADAPTER	pAd;
-	POS_COOKIE	pObj;
-
-	pAd = (PRTMP_ADAPTER)Context;
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	rtmp_os_thread_init("rt2870TimerQHandle", (PVOID)&(pAd->TimerQComplete));
-
-	RT2870_TimerQ_Handle(pAd);
-
-	/* notify the exit routine that we're actually exiting now
-	 *
-	 * complete()/wait_for_completion() is similar to up()/down(),
-	 * except that complete() is safe in the case where the structure
-	 * is getting deleted in a parallel mode of execution (i.e. just
-	 * after the down() -- that's necessary for the thread-shutdown
-	 * case.
-	 *
-	 * complete_and_exit() goes even further than this -- it is safe in
-	 * the case that the thread of the caller is going away (not just
-	 * the structure) -- this is necessary for the module-remove case.
-	 * This is important in preemption kernels, which transfer the flow
-	 * of execution immediately upon a complete().
-	 */
-	DBGPRINT(RT_DEBUG_TRACE,( "<---%s\n",__FUNCTION__));
-
-	pObj->TimerQThr_pid = NULL;
-
-	complete_and_exit(&pAd->TimerQComplete, 0);
-	return 0;
-
-}
-
-
-RT2870_TIMER_ENTRY *RT2870_TimerQ_Insert(
-	IN RTMP_ADAPTER *pAd,
-	IN RALINK_TIMER_STRUCT *pTimer)
-{
-	RT2870_TIMER_ENTRY *pQNode = NULL, *pQTail;
-	unsigned long irqFlags;
-
-
-	RTMP_IRQ_LOCK(&pAd->TimerQLock, irqFlags);
-	if (pAd->TimerQ.status & RT2870_THREAD_CAN_DO_INSERT)
-	{
-		if(pAd->TimerQ.pQPollFreeList)
-		{
-			pQNode = pAd->TimerQ.pQPollFreeList;
-			pAd->TimerQ.pQPollFreeList = pQNode->pNext;
-
-			pQNode->pRaTimer = pTimer;
-			pQNode->pNext = NULL;
-
-			pQTail = pAd->TimerQ.pQTail;
-			if (pAd->TimerQ.pQTail != NULL)
-				pQTail->pNext = pQNode;
-			pAd->TimerQ.pQTail = pQNode;
-			if (pAd->TimerQ.pQHead == NULL)
-				pAd->TimerQ.pQHead = pQNode;
-		}
-		RTMP_IRQ_UNLOCK(&pAd->TimerQLock, irqFlags);
-
-		if (pQNode)
-			up(&pAd->RTUSBTimer_semaphore);
-			//wake_up(&timerWaitQ);
-	}
-	else
-	{
-		RTMP_IRQ_UNLOCK(&pAd->TimerQLock, irqFlags);
-	}
-	return pQNode;
-}
-
-
-BOOLEAN RT2870_TimerQ_Remove(
-	IN RTMP_ADAPTER *pAd,
-	IN RALINK_TIMER_STRUCT *pTimer)
-{
-	RT2870_TIMER_ENTRY *pNode, *pPrev = NULL;
-	unsigned long irqFlags;
-
-	RTMP_IRQ_LOCK(&pAd->TimerQLock, irqFlags);
-	if (pAd->TimerQ.status >= RT2870_THREAD_INITED)
-	{
-		pNode = pAd->TimerQ.pQHead;
-		while (pNode)
-		{
-			if (pNode->pRaTimer == pTimer)
-				break;
-			pPrev = pNode;
-			pNode = pNode->pNext;
-		}
-
-		// Now move it to freeList queue.
-		if (pNode)
-		{
-			if (pNode == pAd->TimerQ.pQHead)
-				pAd->TimerQ.pQHead = pNode->pNext;
-			if (pNode == pAd->TimerQ.pQTail)
-				pAd->TimerQ.pQTail = pPrev;
-			if (pPrev != NULL)
-				pPrev->pNext = pNode->pNext;
-
-			// return this queue entry to timerQFreeList.
-			pNode->pNext = pAd->TimerQ.pQPollFreeList;
-			pAd->TimerQ.pQPollFreeList = pNode;
-		}
-	}
-	RTMP_IRQ_UNLOCK(&pAd->TimerQLock, irqFlags);
-
-	return TRUE;
-}
-
-
-void RT2870_TimerQ_Exit(RTMP_ADAPTER *pAd)
-{
-	RT2870_TIMER_ENTRY *pTimerQ;
-	unsigned long irqFlags;
-
-	RTMP_IRQ_LOCK(&pAd->TimerQLock, irqFlags);
-	while (pAd->TimerQ.pQHead)
-	{
-		pTimerQ = pAd->TimerQ.pQHead;
-		pAd->TimerQ.pQHead = pTimerQ->pNext;
-		// remove the timeQ
-	}
-	pAd->TimerQ.pQPollFreeList = NULL;
-	os_free_mem(pAd, pAd->TimerQ.pTimerQPoll);
-	pAd->TimerQ.pQTail = NULL;
-	pAd->TimerQ.pQHead = NULL;
-	pAd->TimerQ.status = RT2870_THREAD_STOPED;
-	RTMP_IRQ_UNLOCK(&pAd->TimerQLock, irqFlags);
-
-}
-
-
-void RT2870_TimerQ_Init(RTMP_ADAPTER *pAd)
-{
-	int 	i;
-	RT2870_TIMER_ENTRY *pQNode, *pEntry;
-	unsigned long irqFlags;
-
-	NdisAllocateSpinLock(&pAd->TimerQLock);
-
-	RTMP_IRQ_LOCK(&pAd->TimerQLock, irqFlags);
-	NdisZeroMemory(&pAd->TimerQ, sizeof(pAd->TimerQ));
-	//InterlockedExchange(&pAd->TimerQ.count, 0);
-
-	/* Initialise the wait q head */
-	//init_waitqueue_head(&timerWaitQ);
-
-	os_alloc_mem(pAd, &pAd->TimerQ.pTimerQPoll, sizeof(RT2870_TIMER_ENTRY) * TIMER_QUEUE_SIZE_MAX);
-	if (pAd->TimerQ.pTimerQPoll)
-	{
-		pEntry = NULL;
-		pQNode = (RT2870_TIMER_ENTRY *)pAd->TimerQ.pTimerQPoll;
-		for (i = 0 ;i <TIMER_QUEUE_SIZE_MAX; i++)
-		{
-			pQNode->pNext = pEntry;
-			pEntry = pQNode;
-			pQNode++;
-		}
-		pAd->TimerQ.pQPollFreeList = pEntry;
-		pAd->TimerQ.pQHead = NULL;
-		pAd->TimerQ.pQTail = NULL;
-		pAd->TimerQ.status = RT2870_THREAD_INITED;
-	}
-	RTMP_IRQ_UNLOCK(&pAd->TimerQLock, irqFlags);
-}
-
-
-VOID RT2870_WatchDog(IN RTMP_ADAPTER *pAd)
-{
-	PHT_TX_CONTEXT		pHTTXContext;
-	int 					idx;
-	ULONG				irqFlags;
-	PURB		   		pUrb;
-	BOOLEAN				needDumpSeq = FALSE;
-	UINT32          	MACValue;
-
-
-	idx = 0;
-	RTMP_IO_READ32(pAd, TXRXQ_PCNT, &MACValue);
-	if ((MACValue & 0xff) !=0 )
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("TX QUEUE 0 Not EMPTY(Value=0x%0x). !!!!!!!!!!!!!!!\n", MACValue));
-		RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf40012);
-		while((MACValue &0xff) != 0 && (idx++ < 10))
-		{
-		        RTMP_IO_READ32(pAd, TXRXQ_PCNT, &MACValue);
-		        NdisMSleep(1);
-		}
-		RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf40006);
-	}
-
-//PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		idx = 0;
-		if ((MACValue & 0xff00) !=0 )
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("TX QUEUE 1 Not EMPTY(Value=0x%0x). !!!!!!!!!!!!!!!\n", MACValue));
-			RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf4000a);
-			while((MACValue &0xff00) != 0 && (idx++ < 10))
-			{
-				RTMP_IO_READ32(pAd, TXRXQ_PCNT, &MACValue);
-				NdisMSleep(1);
-			}
-			RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf40006);
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	if (pAd->watchDogRxOverFlowCnt >= 2)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("Maybe the Rx Bulk-In hanged! Cancel the pending Rx bulks request!\n"));
-		if ((!RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
-									fRTMP_ADAPTER_BULKIN_RESET |
-									fRTMP_ADAPTER_HALT_IN_PROGRESS |
-									fRTMP_ADAPTER_NIC_NOT_EXIST))))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("Call CMDTHREAD_RESET_BULK_IN to cancel the pending Rx Bulk!\n"));
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKIN_RESET);
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_IN, NULL, 0);
-			needDumpSeq = TRUE;
-		}
-		pAd->watchDogRxOverFlowCnt = 0;
-	}
-
-
-	for (idx = 0; idx < NUM_OF_TX_RING; idx++)
-	{
-		pUrb = NULL;
-
-		RTMP_IRQ_LOCK(&pAd->BulkOutLock[idx], irqFlags);
-		if ((pAd->BulkOutPending[idx] == TRUE) && pAd->watchDogTxPendingCnt)
-		{
-			pAd->watchDogTxPendingCnt[idx]++;
-
-			if ((pAd->watchDogTxPendingCnt[idx] > 2) &&
-				 (!RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS | fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST | fRTMP_ADAPTER_BULKOUT_RESET)))
-				)
-			{
-				// FIXME: Following code just support single bulk out. If you wanna support multiple bulk out. Modify it!
-				pHTTXContext = (PHT_TX_CONTEXT)(&pAd->TxContext[idx]);
-				if (pHTTXContext->IRPPending)
-				{	// Check TxContext.
-					pUrb = pHTTXContext->pUrb;
-				}
-				else if (idx == MGMTPIPEIDX)
-				{
-					PTX_CONTEXT pMLMEContext, pNULLContext, pPsPollContext;
-
-					//Check MgmtContext.
-					pMLMEContext = (PTX_CONTEXT)(pAd->MgmtRing.Cell[pAd->MgmtRing.TxDmaIdx].AllocVa);
-					pPsPollContext = (PTX_CONTEXT)(&pAd->PsPollContext);
-					pNULLContext = (PTX_CONTEXT)(&pAd->NullContext);
-
-					if (pMLMEContext->IRPPending)
-					{
-						ASSERT(pMLMEContext->IRPPending);
-						pUrb = pMLMEContext->pUrb;
-					}
-					else if (pNULLContext->IRPPending)
-					{
-						ASSERT(pNULLContext->IRPPending);
-						pUrb = pNULLContext->pUrb;
-					}
-					else if (pPsPollContext->IRPPending)
-					{
-						ASSERT(pPsPollContext->IRPPending);
-						pUrb = pPsPollContext->pUrb;
-					}
-				}
-
-				RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[idx], irqFlags);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Maybe the Tx Bulk-Out hanged! Cancel the pending Tx bulks request of idx(%d)!\n", idx));
-				if (pUrb)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("Unlink the pending URB!\n"));
-					// unlink it now
-					RTUSB_UNLINK_URB(pUrb);
-					// Sleep 200 microseconds to give cancellation time to work
-					RTMPusecDelay(200);
-					needDumpSeq = TRUE;
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_ERROR, ("Unkonw bulkOut URB maybe hanged!!!!!!!!!!!!\n"));
-				}
-			}
-			else
-			{
-				RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[idx], irqFlags);
-			}
-		}
-		else
-		{
-			RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[idx], irqFlags);
-		}
-	}
-
-#ifdef DOT11_N_SUPPORT
-	// For Sigma debug, dump the ba_reordering sequence.
-	if((needDumpSeq == TRUE) && (pAd->CommonCfg.bDisableReordering == 0))
-	{
-		USHORT				Idx;
-		PBA_REC_ENTRY		pBAEntry = NULL;
-		UCHAR				count = 0;
-		struct reordering_mpdu *mpdu_blk;
-
-		Idx = pAd->MacTab.Content[BSSID_WCID].BARecWcidArray[0];
-
-		pBAEntry = &pAd->BATable.BARecEntry[Idx];
-		if((pBAEntry->list.qlen > 0) && (pBAEntry->list.next != NULL))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("NICUpdateRawCounters():The Queueing pkt in reordering buffer:\n"));
-			NdisAcquireSpinLock(&pBAEntry->RxReRingLock);
-			mpdu_blk = pBAEntry->list.next;
-			while (mpdu_blk)
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("\t%d:Seq-%d, bAMSDU-%d!\n", count, mpdu_blk->Sequence, mpdu_blk->bAMSDU));
-				mpdu_blk = mpdu_blk->next;
-				count++;
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE, ("\npBAEntry->LastIndSeq=%d!\n", pBAEntry->LastIndSeq));
-			NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-}
-
-/*
-========================================================================
-Routine Description:
-    Release allocated resources.
-
-Arguments:
-    *dev				Point to the PCI or USB device
-	pAd					driver control block pointer
-
-Return Value:
-    None
-
-Note:
-========================================================================
-*/
-static void _rtusb_disconnect(struct usb_device *dev, PRTMP_ADAPTER pAd)
-{
-	struct net_device	*net_dev = NULL;
-
-
-	DBGPRINT(RT_DEBUG_ERROR, ("rtusb_disconnect: unregister usbnet usb-%s-%s\n",
-				dev->bus->bus_name, dev->devpath));
-	if (!pAd)
-	{
-#ifdef MULTIPLE_CARD_SUPPORT
-		if ((pAd->MC_RowID >= 0) && (pAd->MC_RowID <= MAX_NUM_OF_MULTIPLE_CARD))
-			MC_CardUsed[pAd->MC_RowID] = 0; // not clear MAC address
-#endif // MULTIPLE_CARD_SUPPORT //
-
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-		while(MOD_IN_USE > 0)
-		{
-			MOD_DEC_USE_COUNT;
-		}
-#else
-		usb_put_dev(dev);
-#endif // LINUX_VERSION_CODE //
-
-		printk("rtusb_disconnect: pAd == NULL!\n");
-		return;
-	}
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);
-
-
-
-	// for debug, wait to show some messages to /proc system
-	udelay(1);
-
-
-
-
-	net_dev = pAd->net_dev;
-	if (pAd->net_dev != NULL)
-	{
-		printk("rtusb_disconnect: unregister_netdev(), dev->name=%s!\n", net_dev->name);
-		unregister_netdev (pAd->net_dev);
-	}
-	udelay(1);
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-#else
-	flush_scheduled_work();
-#endif // LINUX_VERSION_CODE //
-	udelay(1);
-
-	// free net_device memory
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	kfree(net_dev);
-#else
-	free_netdev(net_dev);
-#endif // LINUX_VERSION_CODE //
-
-	// free adapter memory
-	RTMPFreeAdapter(pAd);
-
-	// release a use of the usb device structure
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	while(MOD_IN_USE > 0)
-	{
-		MOD_DEC_USE_COUNT;
-	}
-#else
-	usb_put_dev(dev);
-#endif // LINUX_VERSION_CODE //
-	udelay(1);
-
-	DBGPRINT(RT_DEBUG_ERROR, (" RTUSB disconnect successfully\n"));
-}
-
-
-/*
-========================================================================
-Routine Description:
-    Probe RT28XX chipset.
-
-Arguments:
-    *dev				Point to the PCI or USB device
-	interface
-	*id_table			Point to the PCI or USB device ID
-
-Return Value:
-    None
-
-Note:
-========================================================================
-*/
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-static void *rtusb_probe(struct usb_device *dev, UINT interface,
-						const struct usb_device_id *id)
-{
-	PRTMP_ADAPTER pAd;
-	rt28xx_probe((void *)dev, (void *)id, interface, &pAd);
-	return (void *)pAd;
-}
-
-//Disconnect function is called within exit routine
-static void rtusb_disconnect(struct usb_device *dev, void *ptr)
-{
-	_rtusb_disconnect(dev, ((PRTMP_ADAPTER)ptr));
-}
-
-#else	/* kernel 2.6 series */
-static int rtusb_probe (struct usb_interface *intf,
-						const struct usb_device_id *id)
-{
-	PRTMP_ADAPTER pAd;
-	return (int)rt28xx_probe((void *)intf, (void *)id, 0, &pAd);
-}
-
-
-static void rtusb_disconnect(struct usb_interface *intf)
-{
-	struct usb_device   *dev = interface_to_usbdev(intf);
-	PRTMP_ADAPTER       pAd;
-
-
-	pAd = usb_get_intfdata(intf);
-	usb_set_intfdata(intf, NULL);
-
-	_rtusb_disconnect(dev, pAd);
-}
-#endif // LINUX_VERSION_CODE //
-
-
-/*
-========================================================================
-Routine Description:
-    Close kernel threads.
-
-Arguments:
-	*pAd				the raxx interface data pointer
-
-Return Value:
-    NONE
-
-Note:
-========================================================================
-*/
-VOID RT28xxThreadTerminate(
-	IN RTMP_ADAPTER *pAd)
-{
-	POS_COOKIE	pObj = (POS_COOKIE) pAd->OS_Cookie;
-	INT			ret;
-
-
-	// Sleep 50 milliseconds so pending io might finish normally
-	RTMPusecDelay(50000);
-
-	// We want to wait until all pending receives and sends to the
-	// device object. We cancel any
-	// irps. Wait until sends and receives have stopped.
-	RTUSBCancelPendingIRPs(pAd);
-
-	// Terminate Threads
-	if (pObj->MLMEThr_pid)
-	{
-		printk("Terminate the MLMEThr_pid=%d!\n", pid_nr(pObj->MLMEThr_pid));
-		mb();
-		pAd->mlme_kill = 1;
-		//RT28XX_MLME_HANDLER(pAd);
-		mb();
-		ret = kill_pid(pObj->MLMEThr_pid, SIGTERM, 1);
-		if (ret)
-		{
-			printk (KERN_WARNING "%s: unable to Mlme thread, pid=%d, ret=%d!\n",
-					pAd->net_dev->name, pid_nr(pObj->MLMEThr_pid), ret);
-		}
-		else
-		{
-			//wait_for_completion (&pAd->notify);
-			wait_for_completion (&pAd->mlmeComplete);
-			pObj->MLMEThr_pid = NULL;
-		}
-	}
-
-	if (pObj->RTUSBCmdThr_pid >= 0)
-	{
-		printk("Terminate the RTUSBCmdThr_pid=%d!\n", pid_nr(pObj->RTUSBCmdThr_pid));
-		mb();
-		NdisAcquireSpinLock(&pAd->CmdQLock);
-		pAd->CmdQ.CmdQState = RT2870_THREAD_STOPED;
-		NdisReleaseSpinLock(&pAd->CmdQLock);
-		mb();
-		//RTUSBCMDUp(pAd);
-		ret = kill_pid(pObj->RTUSBCmdThr_pid, SIGTERM, 1);
-		if (ret)
-		{
-			printk(KERN_WARNING "%s: unable to RTUSBCmd thread, pid=%d, ret=%d!\n",
-					pAd->net_dev->name, pid_nr(pObj->RTUSBCmdThr_pid), ret);
-		}
-		else
-		{
-			//wait_for_completion (&pAd->notify);
-			wait_for_completion (&pAd->CmdQComplete);
-			pObj->RTUSBCmdThr_pid = NULL;
-		}
-	}
-	if (pObj->TimerQThr_pid >= 0)
-	{
-		POS_COOKIE pObj = (POS_COOKIE)pAd->OS_Cookie;
-
-		printk("Terminate the TimerQThr_pid=%d!\n", pid_nr(pObj->TimerQThr_pid));
-		mb();
-		pAd->TimerFunc_kill = 1;
-		mb();
-		ret = kill_pid(pObj->TimerQThr_pid, SIGTERM, 1);
-		if (ret)
-		{
-			printk(KERN_WARNING "%s: unable to stop TimerQThread, pid=%d, ret=%d!\n",
-					pAd->net_dev->name, pid_nr(pObj->TimerQThr_pid), ret);
-		}
-		else
-		{
-			printk("wait_for_completion TimerQThr\n");
-			wait_for_completion(&pAd->TimerQComplete);
-			pObj->TimerQThr_pid = NULL;
-		}
-	}
-	// Kill tasklets
-	pAd->mlme_kill = 0;
-	pAd->CmdQ.CmdQState = RT2870_THREAD_UNKNOWN;
-	pAd->TimerFunc_kill = 0;
-}
-
-
-void kill_thread_task(IN PRTMP_ADAPTER pAd)
-{
-	POS_COOKIE pObj;
-
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	tasklet_kill(&pObj->rx_done_task);
-	tasklet_kill(&pObj->mgmt_dma_done_task);
-	tasklet_kill(&pObj->ac0_dma_done_task);
-	tasklet_kill(&pObj->ac1_dma_done_task);
-	tasklet_kill(&pObj->ac2_dma_done_task);
-	tasklet_kill(&pObj->ac3_dma_done_task);
-	tasklet_kill(&pObj->hcca_dma_done_task);
-	tasklet_kill(&pObj->tbtt_task);
-
-}
-
-
-/*
-========================================================================
-Routine Description:
-    Check the chipset vendor/product ID.
-
-Arguments:
-    _dev_p				Point to the PCI or USB device
-
-Return Value:
-    TRUE				Check ok
-	FALSE				Check fail
-
-Note:
-========================================================================
-*/
-BOOLEAN RT28XXChipsetCheck(
-	IN void *_dev_p)
-{
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	struct usb_device *dev_p = (struct usb_device *)_dev_p;
-#else
-	struct usb_interface *intf = (struct usb_interface *)_dev_p;
-	struct usb_device *dev_p = interface_to_usbdev(intf);
-#endif // LINUX_VERSION_CODE //
-	UINT32 i;
-
-
-	for(i=0; i<rtusb_usb_id_len; i++)
-	{
-		if (dev_p->descriptor.idVendor == rtusb_usb_id[i].idVendor &&
-			dev_p->descriptor.idProduct == rtusb_usb_id[i].idProduct)
-		{
-			printk("rt2870: idVendor = 0x%x, idProduct = 0x%x\n",
-					dev_p->descriptor.idVendor, dev_p->descriptor.idProduct);
-			break;
-		}
-	}
-
-	if (i == rtusb_usb_id_len)
-	{
-		printk("rt2870: Error! Device Descriptor not matching!\n");
-		return FALSE;
-	}
-
-	return TRUE;
-}
-
-
-/*
-========================================================================
-Routine Description:
-    Init net device structure.
-
-Arguments:
-    _dev_p				Point to the PCI or USB device
-    *net_dev			Point to the net device
-	*pAd				the raxx interface data pointer
-
-Return Value:
-    TRUE				Init ok
-	FALSE				Init fail
-
-Note:
-========================================================================
-*/
-BOOLEAN RT28XXNetDevInit(
-	IN void 				*_dev_p,
-	IN struct  net_device	*net_dev,
-	IN RTMP_ADAPTER 		*pAd)
-{
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	struct usb_device *dev_p = (struct usb_device *)_dev_p;
-#else
-	struct usb_interface *intf = (struct usb_interface *)_dev_p;
-	struct usb_device *dev_p = interface_to_usbdev(intf);
-#endif // LINUX_VERSION_CODE //
-
-
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	pAd->config = dev_p->config;
-#else
-	pAd->config = &dev_p->config->desc;
-#endif // LINUX_VERSION_CODE //
-	return TRUE;
-}
-
-
-/*
-========================================================================
-Routine Description:
-    Init net device structure.
-
-Arguments:
-    _dev_p				Point to the PCI or USB device
-	*pAd				the raxx interface data pointer
-
-Return Value:
-    TRUE				Config ok
-	FALSE				Config fail
-
-Note:
-========================================================================
-*/
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-BOOLEAN RT28XXProbePostConfig(
-	IN void 				*_dev_p,
-	IN RTMP_ADAPTER 		*pAd,
-	IN INT32				interface)
-{
-	struct usb_device *dev_p = (struct usb_device *)_dev_p;
-	struct usb_interface *intf;
-	struct usb_interface_descriptor *iface_desc;
-	struct usb_endpoint_descriptor *endpoint;
-	ULONG BulkOutIdx;
-	UINT32 i;
-
-
-	/* get the active interface descriptor */
-	intf = &dev_p->actconfig->interface[interface];
-	iface_desc = &intf->altsetting[0];
-
-	/* get # of enpoints */
-	pAd->NumberOfPipes = iface_desc->bNumEndpoints;
-	DBGPRINT(RT_DEBUG_TRACE, ("NumEndpoints=%d\n", iface_desc->bNumEndpoints));
-
-	/* Configure Pipes */
-	endpoint = &iface_desc->endpoint[0];
-	BulkOutIdx = 0;
-
-	for(i=0; i<pAd->NumberOfPipes; i++)
-	{
-		if ((endpoint[i].bmAttributes == USB_ENDPOINT_XFER_BULK) &&
-			((endpoint[i].bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN))
-		{
-			pAd->BulkInEpAddr = endpoint[i].bEndpointAddress;
-			pAd->BulkInMaxPacketSize = endpoint[i].wMaxPacketSize;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("BULK IN MaximumPacketSize = %d\n", pAd->BulkInMaxPacketSize));
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("EP address = 0x%2x  \n", endpoint[i].bEndpointAddress));
-		}
-		else if ((endpoint[i].bmAttributes == USB_ENDPOINT_XFER_BULK) &&
-				((endpoint[i].bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT))
-		{
-			// There are 6 bulk out EP. EP6 highest priority.
-			// EP1-4 is EDCA.  EP5 is HCCA.
-			pAd->BulkOutEpAddr[BulkOutIdx++] = endpoint[i].bEndpointAddress;
-			pAd->BulkOutMaxPacketSize = endpoint[i].wMaxPacketSize;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("BULK OUT MaximumPacketSize = %d\n", pAd->BulkOutMaxPacketSize));
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("EP address = 0x%2x  \n", endpoint[i].bEndpointAddress));
-		}
-	}
-
-	if (!(pAd->BulkInEpAddr && pAd->BulkOutEpAddr[0]))
-	{
-		printk("Could not find both bulk-in and bulk-out endpoints\n");
-		return FALSE;
-	}
-
-	return TRUE;
-}
-
-#else
-BOOLEAN RT28XXProbePostConfig(
-	IN void 				*_dev_p,
-	IN RTMP_ADAPTER 		*pAd,
-	IN INT32				interface)
-{
-	struct usb_interface *intf = (struct usb_interface *)_dev_p;
-	struct usb_host_interface *iface_desc;
-	ULONG BulkOutIdx;
-	UINT32 i;
-
-
-	/* get the active interface descriptor */
-	iface_desc = intf->cur_altsetting;
-
-	/* get # of enpoints  */
-	pAd->NumberOfPipes = iface_desc->desc.bNumEndpoints;
-	DBGPRINT(RT_DEBUG_TRACE,
-			("NumEndpoints=%d\n", iface_desc->desc.bNumEndpoints));
-
-	/* Configure Pipes */
-	BulkOutIdx = 0;
-
-	for(i=0; i<pAd->NumberOfPipes; i++)
-	{
-		if ((iface_desc->endpoint[i].desc.bmAttributes ==
-				USB_ENDPOINT_XFER_BULK) &&
-			((iface_desc->endpoint[i].desc.bEndpointAddress &
-				USB_ENDPOINT_DIR_MASK) == USB_DIR_IN))
-		{
-			pAd->BulkInEpAddr = iface_desc->endpoint[i].desc.bEndpointAddress;
-			pAd->BulkInMaxPacketSize = iface_desc->endpoint[i].desc.wMaxPacketSize;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("BULK IN MaximumPacketSize = %d\n", pAd->BulkInMaxPacketSize));
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("EP address = 0x%2x\n", iface_desc->endpoint[i].desc.bEndpointAddress));
-		}
-		else if ((iface_desc->endpoint[i].desc.bmAttributes ==
-					USB_ENDPOINT_XFER_BULK) &&
-				((iface_desc->endpoint[i].desc.bEndpointAddress &
-					USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT))
-		{
-			// there are 6 bulk out EP. EP6 highest priority.
-			// EP1-4 is EDCA.  EP5 is HCCA.
-			pAd->BulkOutEpAddr[BulkOutIdx++] = iface_desc->endpoint[i].desc.bEndpointAddress;
-			pAd->BulkOutMaxPacketSize = iface_desc->endpoint[i].desc.wMaxPacketSize;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("BULK OUT MaximumPacketSize = %d\n", pAd->BulkOutMaxPacketSize));
-			DBGPRINT_RAW(RT_DEBUG_TRACE,
-				("EP address = 0x%2x  \n", iface_desc->endpoint[i].desc.bEndpointAddress));
-		}
-	}
-
-	if (!(pAd->BulkInEpAddr && pAd->BulkOutEpAddr[0]))
-	{
-		printk("%s: Could not find both bulk-in and bulk-out endpoints\n", __FUNCTION__);
-		return FALSE;
-	}
-
-	return TRUE;
-}
-#endif // LINUX_VERSION_CODE //
-
-
-/*
-========================================================================
-Routine Description:
-    Disable DMA.
-
-Arguments:
-	*pAd				the raxx interface data pointer
-
-Return Value:
-	None
-
-Note:
-========================================================================
-*/
-VOID RT28XXDMADisable(
-	IN RTMP_ADAPTER 		*pAd)
-{
-	// no use
-}
-
-
-
-/*
-========================================================================
-Routine Description:
-    Enable DMA.
-
-Arguments:
-	*pAd				the raxx interface data pointer
-
-Return Value:
-	None
-
-Note:
-========================================================================
-*/
-VOID RT28XXDMAEnable(
-	IN RTMP_ADAPTER 		*pAd)
-{
-	WPDMA_GLO_CFG_STRUC	GloCfg;
-	USB_DMA_CFG_STRUC	UsbCfg;
-	int					i = 0;
-
-
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x4);
-	do
-	{
-		RTMP_IO_READ32(pAd, WPDMA_GLO_CFG, &GloCfg.word);
-		if ((GloCfg.field.TxDMABusy == 0)  && (GloCfg.field.RxDMABusy == 0))
-			break;
-
-		DBGPRINT(RT_DEBUG_TRACE, ("==>  DMABusy\n"));
-		RTMPusecDelay(1000);
-		i++;
-	}while ( i <200);
-
-
-	RTMPusecDelay(50);
-	GloCfg.field.EnTXWriteBackDDONE = 1;
-	GloCfg.field.EnableRxDMA = 1;
-	GloCfg.field.EnableTxDMA = 1;
-	DBGPRINT(RT_DEBUG_TRACE, ("<== WRITE DMA offset 0x208 = 0x%x\n", GloCfg.word));
-	RTMP_IO_WRITE32(pAd, WPDMA_GLO_CFG, GloCfg.word);
-
-	UsbCfg.word = 0;
-	UsbCfg.field.phyclear = 0;
-	/* usb version is 1.1,do not use bulk in aggregation */
-	if (pAd->BulkInMaxPacketSize == 512)
-			UsbCfg.field.RxBulkAggEn = 1;
-	/* for last packet, PBF might use more than limited, so minus 2 to prevent from error */
-	UsbCfg.field.RxBulkAggLmt = (MAX_RXBULK_SIZE /1024)-3;
-	UsbCfg.field.RxBulkAggTOut = 0x80; /* 2006-10-18 */
-	UsbCfg.field.RxBulkEn = 1;
-	UsbCfg.field.TxBulkEn = 1;
-
-	RTUSBWriteMACRegister(pAd, USB_DMA_CFG, UsbCfg.word);
-
-}
-
-/*
-========================================================================
-Routine Description:
-    Write Beacon buffer to Asic.
-
-Arguments:
-	*pAd				the raxx interface data pointer
-
-Return Value:
-	None
-
-Note:
-========================================================================
-*/
-VOID RT28xx_UpdateBeaconToAsic(
-	IN RTMP_ADAPTER		*pAd,
-	IN INT				apidx,
-	IN ULONG			FrameLen,
-	IN ULONG			UpdatePos)
-{
-	PUCHAR        	pBeaconFrame = NULL;
-	UCHAR  			*ptr;
-	UINT  			i, padding;
-	BEACON_SYNC_STRUCT	*pBeaconSync = pAd->CommonCfg.pBeaconSync;
-	UINT32			longValue;
-//	USHORT			shortValue;
-	BOOLEAN			bBcnReq = FALSE;
-	UCHAR			bcn_idx = 0;
-
-
-	if (pBeaconFrame == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("pBeaconFrame is NULL!\n"));
-		return;
-	}
-
-	if (pBeaconSync == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("pBeaconSync is NULL!\n"));
-		return;
-	}
-
-	//if ((pAd->WdsTab.Mode == WDS_BRIDGE_MODE) ||
-	//	((pAd->ApCfg.MBSSID[apidx].MSSIDDev == NULL) || !(pAd->ApCfg.MBSSID[apidx].MSSIDDev->flags & IFF_UP))
-	//	)
-	if (bBcnReq == FALSE)
-	{
-		/* when the ra interface is down, do not send its beacon frame */
-		/* clear all zero */
-		for(i=0; i<TXWI_SIZE; i+=4) {
-			RTMP_IO_WRITE32(pAd, pAd->BeaconOffset[bcn_idx] + i, 0x00);
-		}
-		pBeaconSync->BeaconBitMap &= (~(BEACON_BITMAP_MASK & (1 << bcn_idx)));
-		NdisZeroMemory(pBeaconSync->BeaconTxWI[bcn_idx], TXWI_SIZE);
-	}
-	else
-	{
-		ptr = (PUCHAR)&pAd->BeaconTxWI;
-#ifdef RT_BIG_ENDIAN
-		RTMPWIEndianChange(ptr, TYPE_TXWI);
-#endif
-		if (NdisEqualMemory(pBeaconSync->BeaconTxWI[bcn_idx], &pAd->BeaconTxWI, TXWI_SIZE) == FALSE)
-		{	// If BeaconTxWI changed, we need to rewrite the TxWI for the Beacon frames.
-			pBeaconSync->BeaconBitMap &= (~(BEACON_BITMAP_MASK & (1 << bcn_idx)));
-			NdisMoveMemory(pBeaconSync->BeaconTxWI[bcn_idx], &pAd->BeaconTxWI, TXWI_SIZE);
-		}
-
-		if ((pBeaconSync->BeaconBitMap & (1 << bcn_idx)) != (1 << bcn_idx))
-		{
-			for (i=0; i<TXWI_SIZE; i+=4)  // 16-byte TXWI field
-			{
-				longValue =  *ptr + (*(ptr+1)<<8) + (*(ptr+2)<<16) + (*(ptr+3)<<24);
-				RTMP_IO_WRITE32(pAd, pAd->BeaconOffset[bcn_idx] + i, longValue);
-				ptr += 4;
-			}
-		}
-
-		ptr = pBeaconSync->BeaconBuf[bcn_idx];
-		padding = (FrameLen & 0x01);
-		NdisZeroMemory((PUCHAR)(pBeaconFrame + FrameLen), padding);
-		FrameLen += padding;
-		for (i = 0 ; i < FrameLen /*HW_BEACON_OFFSET*/; i += 2)
-		{
-			if (NdisEqualMemory(ptr, pBeaconFrame, 2) == FALSE)
-			{
-				NdisMoveMemory(ptr, pBeaconFrame, 2);
-				//shortValue = *ptr + (*(ptr+1)<<8);
-				//RTMP_IO_WRITE8(pAd, pAd->BeaconOffset[bcn_idx] + TXWI_SIZE + i, shortValue);
-				RTUSBMultiWrite(pAd, pAd->BeaconOffset[bcn_idx] + TXWI_SIZE + i, ptr, 2);
-			}
-			ptr +=2;
-			pBeaconFrame += 2;
-		}
-
-		pBeaconSync->BeaconBitMap |= (1 << bcn_idx);
-
-		// For AP interface, set the DtimBitOn so that we can send Bcast/Mcast frame out after this beacon frame.
-	}
-
-}
-
-
-VOID RT2870_BssBeaconStop(
-	IN RTMP_ADAPTER *pAd)
-{
-	BEACON_SYNC_STRUCT	*pBeaconSync;
-	int i, offset;
-	BOOLEAN	Cancelled = TRUE;
-
-	pBeaconSync = pAd->CommonCfg.pBeaconSync;
-	if (pBeaconSync && pBeaconSync->EnableBeacon)
-	{
-		INT NumOfBcn;
-
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			NumOfBcn = MAX_MESH_NUM;
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		RTMPCancelTimer(&pAd->CommonCfg.BeaconUpdateTimer, &Cancelled);
-
-		for(i=0; i<NumOfBcn; i++)
-		{
-			NdisZeroMemory(pBeaconSync->BeaconBuf[i], HW_BEACON_OFFSET);
-			NdisZeroMemory(pBeaconSync->BeaconTxWI[i], TXWI_SIZE);
-
-			for (offset=0; offset<HW_BEACON_OFFSET; offset+=4)
-				RTMP_IO_WRITE32(pAd, pAd->BeaconOffset[i] + offset, 0x00);
-
-			pBeaconSync->CapabilityInfoLocationInBeacon[i] = 0;
-			pBeaconSync->TimIELocationInBeacon[i] = 0;
-		}
-		pBeaconSync->BeaconBitMap = 0;
-		pBeaconSync->DtimBitOn = 0;
-	}
-}
-
-
-VOID RT2870_BssBeaconStart(
-	IN RTMP_ADAPTER *pAd)
-{
-	int apidx;
-	BEACON_SYNC_STRUCT	*pBeaconSync;
-//	LARGE_INTEGER 	tsfTime, deltaTime;
-
-	pBeaconSync = pAd->CommonCfg.pBeaconSync;
-	if (pBeaconSync && pBeaconSync->EnableBeacon)
-	{
-		INT NumOfBcn;
-
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			NumOfBcn = MAX_MESH_NUM;
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		for(apidx=0; apidx<NumOfBcn; apidx++)
-		{
-			UCHAR CapabilityInfoLocationInBeacon = 0;
-			UCHAR TimIELocationInBeacon = 0;
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-			NdisZeroMemory(pBeaconSync->BeaconBuf[apidx], HW_BEACON_OFFSET);
-			pBeaconSync->CapabilityInfoLocationInBeacon[apidx] = CapabilityInfoLocationInBeacon;
-			pBeaconSync->TimIELocationInBeacon[apidx] = TimIELocationInBeacon;
-			NdisZeroMemory(pBeaconSync->BeaconTxWI[apidx], TXWI_SIZE);
-		}
-		pBeaconSync->BeaconBitMap = 0;
-		pBeaconSync->DtimBitOn = 0;
-		pAd->CommonCfg.BeaconUpdateTimer.Repeat = TRUE;
-
-		pAd->CommonCfg.BeaconAdjust = 0;
-		pAd->CommonCfg.BeaconFactor = 0xffffffff / (pAd->CommonCfg.BeaconPeriod << 10);
-		pAd->CommonCfg.BeaconRemain = (0xffffffff % (pAd->CommonCfg.BeaconPeriod << 10)) + 1;
-		printk("RT2870_BssBeaconStart:BeaconFactor=%d, BeaconRemain=%d!\n", pAd->CommonCfg.BeaconFactor, pAd->CommonCfg.BeaconRemain);
-		RTMPSetTimer(&pAd->CommonCfg.BeaconUpdateTimer, pAd->CommonCfg.BeaconPeriod);
-
-	}
-}
-
-
-VOID RT2870_BssBeaconInit(
-	IN RTMP_ADAPTER *pAd)
-{
-	BEACON_SYNC_STRUCT	*pBeaconSync;
-	int i;
-
-	NdisAllocMemory(pAd->CommonCfg.pBeaconSync, sizeof(BEACON_SYNC_STRUCT), MEM_ALLOC_FLAG);
-	if (pAd->CommonCfg.pBeaconSync)
-	{
-		pBeaconSync = pAd->CommonCfg.pBeaconSync;
-		NdisZeroMemory(pBeaconSync, sizeof(BEACON_SYNC_STRUCT));
-		for(i=0; i < HW_BEACON_MAX_COUNT; i++)
-		{
-			NdisZeroMemory(pBeaconSync->BeaconBuf[i], HW_BEACON_OFFSET);
-			pBeaconSync->CapabilityInfoLocationInBeacon[i] = 0;
-			pBeaconSync->TimIELocationInBeacon[i] = 0;
-			NdisZeroMemory(pBeaconSync->BeaconTxWI[i], TXWI_SIZE);
-		}
-		pBeaconSync->BeaconBitMap = 0;
-
-		//RTMPInitTimer(pAd, &pAd->CommonCfg.BeaconUpdateTimer, GET_TIMER_FUNCTION(BeaconUpdateExec), pAd, TRUE);
-		pBeaconSync->EnableBeacon = TRUE;
-	}
-}
-
-
-VOID RT2870_BssBeaconExit(
-	IN RTMP_ADAPTER *pAd)
-{
-	BEACON_SYNC_STRUCT	*pBeaconSync;
-	BOOLEAN	Cancelled = TRUE;
-	int i;
-
-	if (pAd->CommonCfg.pBeaconSync)
-	{
-		pBeaconSync = pAd->CommonCfg.pBeaconSync;
-		pBeaconSync->EnableBeacon = FALSE;
-		RTMPCancelTimer(&pAd->CommonCfg.BeaconUpdateTimer, &Cancelled);
-		pBeaconSync->BeaconBitMap = 0;
-
-		for(i=0; i<HW_BEACON_MAX_COUNT; i++)
-		{
-			NdisZeroMemory(pBeaconSync->BeaconBuf[i], HW_BEACON_OFFSET);
-			pBeaconSync->CapabilityInfoLocationInBeacon[i] = 0;
-			pBeaconSync->TimIELocationInBeacon[i] = 0;
-			NdisZeroMemory(pBeaconSync->BeaconTxWI[i], TXWI_SIZE);
-		}
-
-		NdisFreeMemory(pAd->CommonCfg.pBeaconSync, HW_BEACON_OFFSET * HW_BEACON_MAX_COUNT, 0);
-		pAd->CommonCfg.pBeaconSync = NULL;
-	}
-}
-
-VOID BeaconUpdateExec(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3)
-{
-	PRTMP_ADAPTER	pAd = (PRTMP_ADAPTER)FunctionContext;
-	LARGE_INTEGER	tsfTime_a;//, tsfTime_b, deltaTime_exp, deltaTime_ab;
-	UINT32			delta, remain, remain_low, remain_high;
-//	BOOLEAN			positive;
-
-	ReSyncBeaconTime(pAd);
-
-
-
-	RTMP_IO_READ32(pAd, TSF_TIMER_DW0, &tsfTime_a.u.LowPart);
-	RTMP_IO_READ32(pAd, TSF_TIMER_DW1, &tsfTime_a.u.HighPart);
-
-
-	//positive=getDeltaTime(tsfTime_a, expectedTime, &deltaTime_exp);
-	remain_high = pAd->CommonCfg.BeaconRemain * tsfTime_a.u.HighPart;
-	remain_low = tsfTime_a.u.LowPart % (pAd->CommonCfg.BeaconPeriod << 10);
-	remain = (remain_high + remain_low)%(pAd->CommonCfg.BeaconPeriod << 10);
-	delta = (pAd->CommonCfg.BeaconPeriod << 10) - remain;
-
-	pAd->CommonCfg.BeaconUpdateTimer.TimerValue = (delta >> 10) + 10;
-
-}
-
+#include "../rt2870/2870_main_dev.c"
diff --git a/drivers/staging/rt3070/Makefile b/drivers/staging/rt3070/Makefile
index 55980c9..df7ac19 100644
--- a/drivers/staging/rt3070/Makefile
+++ b/drivers/staging/rt3070/Makefile
@@ -3,11 +3,7 @@
 # TODO: all of these should be removed
 EXTRA_CFLAGS += -DLINUX -DAGGREGATION_SUPPORT -DPIGGYBACK_SUPPORT -DWMM_SUPPORT
 EXTRA_CFLAGS += -DRT2870 -DRT30xx -DRT3070
-EXTRA_CFLAGS += -DCONFIG_STA_SUPPORT
 EXTRA_CFLAGS += -DDBG
-EXTRA_CFLAGS += -DDOT11_N_SUPPORT
-EXTRA_CFLAGS += -DWPA_SUPPLICANT_SUPPORT
-EXTRA_CFLAGS += -DNATIVE_WPA_SUPPLICANT_SUPPORT
 
 rt3070sta-objs :=		\
 	common/md5.o		\
diff --git a/drivers/staging/rt3070/action.h b/drivers/staging/rt3070/action.h
index ce3877d..345fa89 100644
--- a/drivers/staging/rt3070/action.h
+++ b/drivers/staging/rt3070/action.h
@@ -1,68 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	aironet.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-	Paul Lin	04-06-15		Initial
-*/
-
-#ifndef	__ACTION_H__
-#define	__ACTION_H__
-
-typedef struct PACKED __HT_INFO_OCTET
-{
-#ifdef RT_BIG_ENDIAN
-	UCHAR	Reserved:5;
-	UCHAR 	STA_Channel_Width:1;
-	UCHAR	Forty_MHz_Intolerant:1;
-	UCHAR	Request:1;
-#else
-	UCHAR	Request:1;
-	UCHAR	Forty_MHz_Intolerant:1;
-	UCHAR 	STA_Channel_Width:1;
-	UCHAR	Reserved:5;
-#endif
-} HT_INFORMATION_OCTET;
-
-
-typedef struct PACKED __FRAME_HT_INFO
-{
-	HEADER_802_11   		Hdr;
-	UCHAR					Category;
-	UCHAR					Action;
-	HT_INFORMATION_OCTET	HT_Info;
-}   FRAME_HT_INFO, *PFRAME_HT_INFO;
-
-#endif /* __ACTION_H__ */
-
-
+#include "../rt2870/common/action.h"
diff --git a/drivers/staging/rt3070/aironet.h b/drivers/staging/rt3070/aironet.h
index 1e07b19..78088f2 100644
--- a/drivers/staging/rt3070/aironet.h
+++ b/drivers/staging/rt3070/aironet.h
@@ -1,210 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	aironet.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-	Paul Lin	04-06-15		Initial
-*/
-
-#ifndef	__AIRONET_H__
-#define	__AIRONET_H__
-
-// Measurement Type definition
-#define	MSRN_TYPE_UNUSED				0
-#define	MSRN_TYPE_CHANNEL_LOAD_REQ		1
-#define	MSRN_TYPE_NOISE_HIST_REQ		2
-#define	MSRN_TYPE_BEACON_REQ			3
-#define	MSRN_TYPE_FRAME_REQ				4
-
-// Scan Mode in Beacon Request
-#define	MSRN_SCAN_MODE_PASSIVE			0
-#define	MSRN_SCAN_MODE_ACTIVE			1
-#define	MSRN_SCAN_MODE_BEACON_TABLE		2
-
-// PHY type definition for Aironet beacon report, CCX 2 table 36-9
-#define	PHY_FH							1
-#define	PHY_DSS							2
-#define	PHY_UNUSED						3
-#define	PHY_OFDM						4
-#define	PHY_HR_DSS						5
-#define	PHY_ERP							6
-
-// RPI table in dBm
-#define	RPI_0			0			//	Power <= -87
-#define	RPI_1			1			//	-87 < Power <= -82
-#define	RPI_2			2			//	-82 < Power <= -77
-#define	RPI_3			3			//	-77 < Power <= -72
-#define	RPI_4			4			//	-72 < Power <= -67
-#define	RPI_5			5			//	-67 < Power <= -62
-#define	RPI_6			6			//	-62 < Power <= -57
-#define	RPI_7			7			//	-57 < Power
-
-// Cisco Aironet IAPP definetions
-#define	AIRONET_IAPP_TYPE					0x32
-#define	AIRONET_IAPP_SUBTYPE_REQUEST		0x01
-#define	AIRONET_IAPP_SUBTYPE_REPORT			0x81
-
-// Measurement Request detail format
-typedef	struct	_MEASUREMENT_REQUEST	{
-	UCHAR	Channel;
-	UCHAR	ScanMode;			// Use only in beacon request, other requests did not use this field
-	USHORT	Duration;
-}	MEASUREMENT_REQUEST, *PMEASUREMENT_REQUEST;
-
-// Beacon Measurement Report
-// All these field might change to UCHAR, because we didn't do anything to these report.
-// We copy all these beacons and report to CCX 2 AP.
-typedef	struct	_BEACON_REPORT	{
-	UCHAR	Channel;
-	UCHAR	Spare;
-	USHORT	Duration;
-	UCHAR	PhyType;			// Definiation is listed above table 36-9
-	UCHAR	RxPower;
-	UCHAR	BSSID[6];
-	UCHAR	ParentTSF[4];
-	UCHAR	TargetTSF[8];
-	USHORT	BeaconInterval;
-	USHORT	CapabilityInfo;
-}	BEACON_REPORT, *PBEACON_REPORT;
-
-// Frame Measurement Report (Optional)
-typedef	struct	_FRAME_REPORT	{
-	UCHAR	Channel;
-	UCHAR	Spare;
-	USHORT	Duration;
-	UCHAR	TA;
-	UCHAR	BSSID[6];
-	UCHAR	RSSI;
-	UCHAR	Count;
-}	FRAME_REPORT, *PFRAME_REPORT;
-
-#pragma pack(1)
-// Channel Load Report
-typedef	struct	_CHANNEL_LOAD_REPORT	{
-	UCHAR	Channel;
-	UCHAR	Spare;
-	USHORT	Duration;
-	UCHAR	CCABusy;
-}	CHANNEL_LOAD_REPORT, *PCHANNEL_LOAD_REPORT;
-#pragma pack()
-
-// Nosie Histogram Report
-typedef	struct	_NOISE_HIST_REPORT	{
-	UCHAR	Channel;
-	UCHAR	Spare;
-	USHORT	Duration;
-	UCHAR	Density[8];
-}	NOISE_HIST_REPORT, *PNOISE_HIST_REPORT;
-
-// Radio Management Capability element
-typedef	struct	_RADIO_MANAGEMENT_CAPABILITY	{
-	UCHAR	Eid;				// TODO: Why the Eid is 1 byte, not normal 2 bytes???
-	UCHAR	Length;
-	UCHAR	AironetOui[3];		// AIronet OUI (00 40 96)
-	UCHAR	Type;				// Type / Version
-	USHORT	Status;				// swap16 required
-}	RADIO_MANAGEMENT_CAPABILITY, *PRADIO_MANAGEMENT_CAPABILITY;
-
-// Measurement Mode Bit definition
-typedef	struct	_MEASUREMENT_MODE	{
-	UCHAR	Rsvd:4;
-	UCHAR	Report:1;
-	UCHAR	NotUsed:1;
-	UCHAR	Enable:1;
-	UCHAR	Parallel:1;
-}	MEASUREMENT_MODE, *PMEASUREMENT_MODE;
-
-// Measurement Request element, This is little endian mode
-typedef	struct	_MEASUREMENT_REQUEST_ELEMENT	{
-	USHORT				Eid;
-	USHORT				Length;				// swap16 required
-	USHORT				Token;				// non-zero unique token
-	UCHAR				Mode;				// Measurement Mode
-	UCHAR				Type;				// Measurement type
-}	MEASUREMENT_REQUEST_ELEMENT, *PMEASUREMENT_REQUEST_ELEMENT;
-
-// Measurement Report element, This is little endian mode
-typedef	struct	_MEASUREMENT_REPORT_ELEMENT	{
-	USHORT				Eid;
-	USHORT				Length;				// swap16 required
-	USHORT				Token;				// non-zero unique token
-	UCHAR				Mode;				// Measurement Mode
-	UCHAR				Type;				// Measurement type
-}	MEASUREMENT_REPORT_ELEMENT, *PMEASUREMENT_REPORT_ELEMENT;
-
-// Cisco Aironet IAPP Frame Header, Network byte order used
-typedef	struct	_AIRONET_IAPP_HEADER {
-	UCHAR	CiscoSnapHeader[8];	// 8 bytes Cisco snap header
-	USHORT	Length;				// IAPP ID & length, remember to swap16 in LE system
-	UCHAR	Type;				// IAPP type
-	UCHAR	SubType;			// IAPP subtype
-	UCHAR	DA[6];				// Destination MAC address
-	UCHAR	SA[6];				// Source MAC address
-	USHORT	Token;				// Dialog token, no need to swap16 since it is for yoken usage only
-}	AIRONET_IAPP_HEADER, *PAIRONET_IAPP_HEADER;
-
-// Radio Measurement Request frame
-typedef	struct	_AIRONET_RM_REQUEST_FRAME	{
-    AIRONET_IAPP_HEADER	IAPP;			// Common header
-	UCHAR				Delay;			// Activation Delay
-	UCHAR				Offset;			// Measurement offset
-}	AIRONET_RM_REQUEST_FRAME, *PAIRONET_RM_REQUEST_FRAME;
-
-// Radio Measurement Report frame
-typedef	struct	_AIRONET_RM_REPORT_FRAME	{
-    AIRONET_IAPP_HEADER	IAPP;			// Common header
-}	AIRONET_RM_REPORT_FRAME, *PAIRONET_RM_REPORT_FRAME;
-
-// Saved element request actions which will saved in StaCfg.
-typedef	struct	_RM_REQUEST_ACTION	{
-	MEASUREMENT_REQUEST_ELEMENT	ReqElem;		// Saved request element
-	MEASUREMENT_REQUEST			Measurement;	// Saved measurement within the request element
-}	RM_REQUEST_ACTION, *PRM_REQUEST_ACTION;
-
-// CCX administration control
-typedef	union	_CCX_CONTROL	{
-	struct	{
-		UINT32		Enable:1;			// Enable CCX2
-		UINT32		LeapEnable:1;		// Enable LEAP at CCX2
-		UINT32		RMEnable:1;			// Radio Measurement Enable
-		UINT32		DCRMEnable:1;		// Non serving channel Radio Measurement enable
-		UINT32		QOSEnable:1;		// Enable QOS for CCX 2.0 support
-		UINT32		FastRoamEnable:1;	// Enable fast roaming
-		UINT32		Rsvd:2;				// Not used
-		UINT32		dBmToRoam:8;		// the condition to roam when receiving Rssi less than this value. It's negative value.
-		UINT32		TuLimit:16;			// Limit for different channel scan
-	}	field;
-	UINT32			word;
-}	CCX_CONTROL, *PCCX_CONTROL;
-
-#endif	// __AIRONET_H__
+#include "../rt2870/aironet.h"
diff --git a/drivers/staging/rt3070/ap.h b/drivers/staging/rt3070/ap.h
index f5ba042..ab8de4b 100644
--- a/drivers/staging/rt3070/ap.h
+++ b/drivers/staging/rt3070/ap.h
@@ -1,557 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    ap.h
-
-    Abstract:
-    Miniport generic portion header file
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Paul Lin    08-01-2002    created
-    James Tan   09-06-2002    modified (Revise NTCRegTable)
-    John Chang  12-22-2004    modified for RT2561/2661. merge with STA driver
-*/
-#ifndef __AP_H__
-#define __AP_H__
-
-
-
-// ========================= AP RTMP.h ================================
-
-
-
-// =============================================================
-//      Function Prototypes
-// =============================================================
-
-// ap_data.c
-
-BOOLEAN APBridgeToWirelessSta(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pHeader,
-    IN  UINT            HdrLen,
-    IN  PUCHAR          pData,
-    IN  UINT            DataLen,
-    IN  ULONG           fromwdsidx);
-
-BOOLEAN APHandleRxDoneInterrupt(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID	APSendPackets(
-	IN	NDIS_HANDLE		MiniportAdapterContext,
-	IN	PPNDIS_PACKET	ppPacketArray,
-	IN	UINT			NumberOfPackets);
-
-NDIS_STATUS APSendPacket(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PNDIS_PACKET    pPacket);
-
-
-NDIS_STATUS APHardTransmit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	UCHAR			QueIdx);
-
-VOID APRxEAPOLFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-NDIS_STATUS APCheckRxError(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PRT28XX_RXD_STRUC		pRxD,
-	IN	UCHAR			Wcid);
-
-BOOLEAN APCheckClass2Class3Error(
-    IN  PRTMP_ADAPTER   pAd,
-	IN ULONG Wcid,
-	IN  PHEADER_802_11  pHeader);
-
-VOID APHandleRxPsPoll(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pAddr,
-	IN	USHORT			Aid,
-    IN	BOOLEAN			isActive);
-
-VOID    RTMPDescriptorEndianChange(
-    IN  PUCHAR          pData,
-    IN  ULONG           DescriptorType);
-
-VOID    RTMPFrameEndianChange(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pData,
-    IN  ULONG           Dir,
-    IN  BOOLEAN         FromRxDoneInt);
-
-// ap_assoc.c
-
-VOID APAssocStateMachineInit(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  STATE_MACHINE *S,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID  APPeerAssocReqAction(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID  APPeerReassocReqAction(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID  APPeerDisassocReqAction(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MbssKickOutStas(
-	IN PRTMP_ADAPTER pAd,
-	IN INT apidx,
-	IN USHORT Reason);
-
-VOID APMlmeKickOutSta(
-    IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pStaAddr,
-	IN UCHAR Wcid,
-	IN USHORT Reason);
-
-VOID APMlmeDisassocReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID  APCls3errAction(
-    IN  PRTMP_ADAPTER   pAd,
-	IN 	ULONG Wcid,
-    IN	PHEADER_802_11	pHeader);
-
-
-USHORT APBuildAssociation(
-    IN PRTMP_ADAPTER pAd,
-    IN MAC_TABLE_ENTRY *pEntry,
-    IN USHORT CapabilityInfo,
-    IN UCHAR  MaxSupportedRateIn500Kbps,
-    IN UCHAR  *RSN,
-    IN UCHAR  *pRSNLen,
-    IN BOOLEAN bWmmCapable,
-    IN ULONG  RalinkIe,
-#ifdef DOT11N_DRAFT3
-    IN EXT_CAP_INFO_ELEMENT ExtCapInfo,
-#endif // DOT11N_DRAFT3 //
-	IN HT_CAPABILITY_IE		*pHtCapability,
-	IN UCHAR		 HtCapabilityLen,
-    OUT USHORT *pAid);
-
-/*
-VOID	RTMPAddClientSec(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR	BssIdx,
-	IN UCHAR		 KeyIdx,
-	IN UCHAR		 CipherAlg,
-	IN PUCHAR		 pKey,
-	IN PUCHAR		 pTxMic,
-	IN PUCHAR		 pRxMic,
-	IN MAC_TABLE_ENTRY *pEntry);
-*/
-
-// ap_auth.c
-
-void APAuthStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID APMlmeDeauthReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID APCls2errAction(
-    IN PRTMP_ADAPTER pAd,
-	IN 	ULONG Wcid,
-    IN	PHEADER_802_11	pHeader);
-
-// ap_authrsp.c
-
-VOID APAuthRspStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN PSTATE_MACHINE Sm,
-    IN STATE_MACHINE_FUNC Trans[]);
-
-VOID APPeerAuthAtAuthRspIdleAction(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID APPeerDeauthReqAction(
-    IN PRTMP_ADAPTER	pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID APPeerAuthSimpleRspGenAndSend(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PHEADER_802_11 pHdr80211,
-    IN  USHORT Alg,
-    IN  USHORT Seq,
-    IN  USHORT StatusCode);
-
-// ap_connect.c
-
-BOOLEAN BeaconTransmitRequired(
-	IN PRTMP_ADAPTER	pAd,
-	IN INT				apidx);
-
-VOID APMakeBssBeacon(
-    IN  PRTMP_ADAPTER   pAd,
-	IN	INT				apidx);
-
-VOID  APUpdateBeaconFrame(
-    IN  PRTMP_ADAPTER   pAd,
-	IN	INT				apidx);
-
-VOID APMakeAllBssBeacon(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID  APUpdateAllBeaconFrame(
-    IN  PRTMP_ADAPTER   pAd);
-
-
-// ap_sync.c
-
-VOID APSyncStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID APScanTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID APInvalidStateWhenScan(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APScanTimeoutAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APPeerProbeReqAction(
-    IN  PRTMP_ADAPTER pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID APPeerBeaconAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID APMlmeScanReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APPeerBeaconAtScanAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APScanCnclAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID ApSiteSurvey(
-	IN PRTMP_ADAPTER pAd);
-
-VOID SupportRate(
-	IN PUCHAR SupRate,
-	IN UCHAR SupRateLen,
-	IN PUCHAR ExtRate,
-	IN UCHAR ExtRateLen,
-	OUT PUCHAR *Rates,
-	OUT PUCHAR RatesLen,
-	OUT PUCHAR pMaxSupportRate);
-
-
-BOOLEAN ApScanRunning(
-	IN PRTMP_ADAPTER pAd);
-
-#ifdef DOT11N_DRAFT3
-VOID APOverlappingBSSScan(
-	IN RTMP_ADAPTER *pAd);
-#endif // DOT11N_DRAFT3 //
-
-// ap_wpa.c
-
-VOID APWpaStateMachineInit(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-// ap_mlme.c
-
-VOID APMlmePeriodicExec(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID APMlmeSelectTxRateTable(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PUCHAR				*ppTable,
-	IN PUCHAR				pTableSize,
-	IN PUCHAR				pInitTxRateIdx);
-
-VOID APMlmeSetTxRate(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PRTMP_TX_RATE_SWITCH	pTxRate);
-
-VOID APMlmeDynamicTxRateSwitching(
-    IN PRTMP_ADAPTER pAd);
-
-VOID APQuickResponeForRateUpExec(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-BOOLEAN APMsgTypeSubst(
-    IN PRTMP_ADAPTER pAd,
-    IN PFRAME_802_11 pFrame,
-    OUT INT *Machine,
-    OUT INT *MsgType);
-
-VOID APQuickResponeForRateUpExec(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-#ifdef RT2870
-VOID BeaconUpdateExec(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-#endif // RT2870 //
-
-VOID RTMPSetPiggyBack(
-	IN PRTMP_ADAPTER	pAd,
-	IN BOOLEAN			bPiggyBack);
-
-VOID APAsicEvaluateRxAnt(
-	IN PRTMP_ADAPTER	pAd);
-
-VOID APAsicRxAntEvalTimeout(
-	IN PRTMP_ADAPTER	pAd);
-
-// ap.c
-
-VOID APSwitchChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN INT Channel);
-
-NDIS_STATUS APInitialize(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID APShutdown(
-    IN PRTMP_ADAPTER    pAd);
-
-VOID APStartUp(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID APStop(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID APCleanupPsQueue(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PQUEUE_HEADER   pQueue);
-
-VOID MacTableReset(
-    IN  PRTMP_ADAPTER   pAd);
-
-MAC_TABLE_ENTRY *MacTableInsertEntry(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pAddr,
-	IN	UCHAR			apidx,
-	IN BOOLEAN	CleanAll);
-
-BOOLEAN MacTableDeleteEntry(
-    IN  PRTMP_ADAPTER   pAd,
-	IN USHORT wcid,
-    IN  PUCHAR          pAddr);
-
-MAC_TABLE_ENTRY *MacTableLookup(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pAddr);
-
-VOID MacTableMaintenance(
-    IN PRTMP_ADAPTER pAd);
-
-UINT32 MacTableAssocStaNumGet(
-	IN PRTMP_ADAPTER pAd);
-
-MAC_TABLE_ENTRY *APSsPsInquiry(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pAddr,
-    OUT SST             *Sst,
-    OUT USHORT          *Aid,
-    OUT UCHAR           *PsMode,
-    OUT UCHAR           *Rate);
-
-BOOLEAN APPsIndicate(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pAddr,
-	IN ULONG Wcid,
-    IN  UCHAR           Psm);
-
-VOID ApLogEvent(
-    IN PRTMP_ADAPTER    pAd,
-    IN PUCHAR           pAddr,
-    IN USHORT           Event);
-
-#ifdef DOT11_N_SUPPORT
-VOID APUpdateOperationMode(
-    IN PRTMP_ADAPTER pAd);
-#endif // DOT11_N_SUPPORT //
-
-VOID APUpdateCapabilityAndErpIe(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN ApCheckAccessControlList(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR        pAddr,
-	IN UCHAR         Apidx);
-
-VOID ApUpdateAccessControlList(
-    IN PRTMP_ADAPTER pAd,
-    IN UCHAR         Apidx);
-
-VOID ApEnqueueNullFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR        pAddr,
-	IN UCHAR         TxRate,
-	IN UCHAR         PID,
-	IN UCHAR         apidx,
-    IN BOOLEAN       bQosNull,
-    IN BOOLEAN       bEOSP,
-    IN UCHAR         OldUP);
-
-VOID ApSendFrame(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PVOID           pBuffer,
-    IN  ULONG           Length,
-    IN  UCHAR           TxRate,
-    IN  UCHAR           PID);
-
-VOID ApEnqueueAckFrame(
-    IN PRTMP_ADAPTER pAd,
-    IN PUCHAR        pAddr,
-    IN UCHAR         TxRate,
-	IN UCHAR         apidx);
-
-UCHAR APAutoSelectChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN Optimal);
-
-// ap_sanity.c
-
-
-BOOLEAN PeerAssocReqCmmSanity(
-    IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN isRessoc,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pListenInterval,
-    OUT PUCHAR pApAddr,
-    OUT UCHAR *pSsidLen,
-    OUT char *Ssid,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-    OUT UCHAR *RSN,
-    OUT UCHAR *pRSNLen,
-    OUT BOOLEAN *pbWmmCapable,
-    OUT ULONG  *pRalinkIe,
-#ifdef DOT11N_DRAFT3
-    OUT EXT_CAP_INFO_ELEMENT	*pExtCapInfo,
-#endif // DOT11N_DRAFT3 //
-    OUT UCHAR		 *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability);
-
-
-BOOLEAN PeerDisassocReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *Reason);
-
-BOOLEAN PeerDeauthReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *Reason);
-
-BOOLEAN APPeerAuthSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-	OUT PUCHAR pAddr1,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *Alg,
-    OUT USHORT *Seq,
-    OUT USHORT *Status,
-    CHAR *ChlgText);
-
-BOOLEAN APPeerProbeReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT CHAR Ssid[],
-    OUT UCHAR *SsidLen);
-
-BOOLEAN APPeerBeaconAndProbeRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT PUCHAR pBssid,
-    OUT CHAR Ssid[],
-    OUT UCHAR *SsidLen,
-    OUT UCHAR *BssType,
-    OUT USHORT *BeaconPeriod,
-    OUT UCHAR *Channel,
-    OUT LARGE_INTEGER *Timestamp,
-    OUT USHORT *CapabilityInfo,
-    OUT UCHAR Rate[],
-    OUT UCHAR *RateLen,
-    OUT BOOLEAN *ExtendedRateIeExist,
-    OUT UCHAR *Erp);
-
-
-// ================== end of AP RTMP.h ========================
-
-
-#endif  // __AP_H__
-
+#include "../rt2870/ap.h"
diff --git a/drivers/staging/rt3070/chlist.h b/drivers/staging/rt3070/chlist.h
index 7151e86..8ee1ff5 100644
--- a/drivers/staging/rt3070/chlist.h
+++ b/drivers/staging/rt3070/chlist.h
@@ -1,1253 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	chlist.c
-
-	Abstract:
-
-	Revision History:
-	Who         When          What
-	--------    ----------    ----------------------------------------------
-	Fonchi Wu   2007-12-19    created
-*/
-
-#ifndef __CHLIST_H__
-#define __CHLIST_H__
-
-#include "rtmp_type.h"
-#include "rtmp_def.h"
-
-
-#define ODOR			0
-#define IDOR			1
-#define BOTH			2
-
-#define BAND_5G         0
-#define BAND_24G        1
-#define BAND_BOTH       2
-
-typedef struct _CH_DESP {
-	UCHAR FirstChannel;
-	UCHAR NumOfCh;
-	CHAR MaxTxPwr;			// dBm
-	UCHAR Geography;			// 0:out door, 1:in door, 2:both
-	BOOLEAN DfsReq;			// Dfs require, 0: No, 1: yes.
-} CH_DESP, *PCH_DESP;
-
-typedef struct _CH_REGION {
-	UCHAR CountReg[3];
-	UCHAR DfsType;			// 0: CE, 1: FCC, 2: JAP, 3:JAP_W53, JAP_W56
-	CH_DESP ChDesp[10];
-} CH_REGION, *PCH_REGION;
-
-static CH_REGION ChRegion[] =
-{
-		{	// Antigua and Berbuda
-			"AG",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Argentina
-			"AR",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Aruba
-			"AW",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Australia
-			"AU",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Austria
-			"AT",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, IDOR, TRUE},		// 5G, ch 36~48
-				{ 52,  4,  23, IDOR, TRUE},		// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, TRUE},		// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Bahamas
-			"BS",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Barbados
-			"BB",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Bermuda
-			"BM",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Brazil
-			"BR",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 24, BOTH, FALSE},	// 5G, ch 100~140
-				{ 149, 5,  30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Belgium
-			"BE",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  18, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  18, IDOR, FALSE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Bulgaria
-			"BG",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11, 30, ODOR, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Canada
-			"CA",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Cayman IsLands
-			"KY",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Chile
-			"CL",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  20, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  20, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 5,  20, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// China
-			"CN",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149, 4,  27, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Colombia
-			"CO",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  17, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 149, 5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Costa Rica
-			"CR",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  17, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149, 4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Cyprus
-			"CY",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  24, IDOR, TRUE},		// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, TRUE},		// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Czech_Republic
-			"CZ",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, IDOR, TRUE},		// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Denmark
-			"DK",
-			CE,
-			{
-				{ 1,   13, 20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,  23, IDOR, TRUE},		// 5G, ch 52~64
-				{ 100, 11, 30, BOTH, TRUE},		// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Dominican Republic
-			"DO",
-			CE,
-			{
-				{ 1,   0,  20, BOTH, FALSE},	// 2.4 G, ch 0
-				{ 149, 4,  20, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Equador
-			"EC",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 100, 11,  27, BOTH, FALSE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// El Salvador
-			"SV",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   30, BOTH, TRUE},	// 5G, ch 52~64
-				{ 149, 4,   36, BOTH, TRUE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Finland
-			"FI",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// France
-			"FR",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Germany
-			"DE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Greece
-			"GR",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, ODOR, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Guam
-			"GU",
-			CE,
-			{
-				{ 1,   11,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 36,  4,   17, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, FALSE},	// 5G, ch 100~140
-				{ 149,  5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Guatemala
-			"GT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   17, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Haiti
-			"HT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,  4,   17, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,  4,   24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Honduras
-			"HN",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149,  4,  27, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Hong Kong
-			"HK",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Hungary
-			"HU",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Iceland
-			"IS",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// India
-			"IN",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149, 	4,  24, IDOR, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Indonesia
-			"ID",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149, 	4,  27, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Ireland
-			"IE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, ODOR, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Israel
-			"IL",
-			CE,
-			{
-				{ 1,    3,  20, IDOR, FALSE},	// 2.4 G, ch 1~3
-				{ 4, 	6,  20, BOTH, FALSE},	// 2.4 G, ch 4~9
-				{ 10, 	4,  20, IDOR, FALSE},	// 2.4 G, ch 10~13
-				{ 0},							// end
-			}
-		},
-
-		{	// Italy
-			"IT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, ODOR, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Japan
-			"JP",
-			JAP,
-			{
-				{ 1,   14,  20, BOTH, FALSE},	// 2.4 G, ch 1~14
-				{ 34, 	4,  23, IDOR, FALSE},	// 5G, ch 34~46
-				{ 0},							// end
-			}
-		},
-
-		{	// Jordan
-			"JO",
-			CE,
-			{
-				{ 1,   13,  20, IDOR, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 149, 	4,  23, IDOR, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Latvia
-			"LV",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Liechtenstein
-			"LI",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Lithuania
-			"LT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Luxemburg
-			"LU",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Malaysia
-			"MY",
-			CE,
-			{
-				{ 36, 	4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  5,  20, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Malta
-			"MT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Marocco
-			"MA",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  24, IDOR, FALSE},	// 5G, ch 36~48
-				{ 0},							// end
-			}
-		},
-
-		{	// Mexico
-			"MX",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  5,  30, IDOR, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Netherlands
-			"NL",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  24, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// New Zealand
-			"NZ",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  24, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  24, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Norway
-			"NO",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36, 	4,  24, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52, 	4,  24, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Peru
-			"PE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149,  4,  27, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Portugal
-			"PT",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Poland
-			"PL",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Romania
-			"RO",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Russia
-			"RU",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 149,  4,  20, IDOR, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Saudi Arabia
-			"SA",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  23, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Serbia_and_Montenegro
-			"CS",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 0},							// end
-			}
-		},
-
-		{	// Singapore
-			"SG",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 149,  4,  20, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Slovakia
-			"SK",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Slovenia
-			"SI",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// South Africa
-			"ZA",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, FALSE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 149,  4,  30, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// South Korea
-			"KR",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  20, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  20, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100,  8,  20, BOTH, FALSE},	// 5G, ch 100~128
-				{ 149,  4,  20, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Spain
-			"ES",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  17, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Sweden
-			"SE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Switzerland
-			"CH",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~13
-				{ 36,   4,  23, IDOR, TRUE},	// 5G, ch 36~48
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Taiwan
-			"TW",
-			CE,
-			{
-				{ 1,   11,  30, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 52,   4,  23, IDOR, FALSE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// Turkey
-			"TR",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 36,   4,  23, BOTH, FALSE},	// 5G, ch 36~48
-				{ 52,   4,  23, BOTH, FALSE},	// 5G, ch 52~64
-				{ 0},							// end
-			}
-		},
-
-		{	// UK
-			"GB",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 36,   4,  23, IDOR, FALSE},	// 5G, ch 52~64
-				{ 52,   4,  23, IDOR, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 0},							// end
-			}
-		},
-
-		{	// Ukraine
-			"UA",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 0},							// end
-			}
-		},
-
-		{	// United_Arab_Emirates
-			"AE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 0},							// end
-			}
-		},
-
-		{	// United_States
-			"US",
-			CE,
-			{
-				{ 1,   11,  30, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 36,   4,  17, IDOR, FALSE},	// 5G, ch 52~64
-				{ 52,   4,  24, BOTH, TRUE},	// 5G, ch 52~64
-				{ 100, 11,  30, BOTH, TRUE},	// 5G, ch 100~140
-				{ 149,  5,  30, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-
-		{	// Venezuela
-			"VE",
-			CE,
-			{
-				{ 1,   13,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 149,  4,  27, BOTH, FALSE},	// 5G, ch 149~161
-				{ 0},							// end
-			}
-		},
-
-		{	// Default
-			"",
-			CE,
-			{
-				{ 1,   11,  20, BOTH, FALSE},	// 2.4 G, ch 1~11
-				{ 36,   4,  20, BOTH, FALSE},	// 5G, ch 52~64
-				{ 52,   4,  20, BOTH, FALSE},	// 5G, ch 52~64
-				{ 100, 11,  20, BOTH, FALSE},	// 5G, ch 100~140
-				{ 149,  5,  20, BOTH, FALSE},	// 5G, ch 149~165
-				{ 0},							// end
-			}
-		},
-};
-
-static inline PCH_REGION GetChRegion(
-	IN PUCHAR CntryCode)
-{
-	INT loop = 0;
-	PCH_REGION pChRegion = NULL;
-
-	while (strcmp(ChRegion[loop].CountReg, "") != 0)
-	{
-		if (strncmp(ChRegion[loop].CountReg, CntryCode, 2) == 0)
-		{
-			pChRegion = &ChRegion[loop];
-			break;
-		}
-		loop++;
-	}
-
-	if (pChRegion == NULL)
-		pChRegion = &ChRegion[loop];
-	return pChRegion;
-}
-
-static inline VOID ChBandCheck(
-	IN UCHAR PhyMode,
-	OUT PUCHAR pChType)
-{
-	switch(PhyMode)
-	{
-		case PHY_11A:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11AN_MIXED:
-#endif // DOT11_N_SUPPORT //
-			*pChType = BAND_5G;
-			break;
-		case PHY_11ABG_MIXED:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11AGN_MIXED:
-		case PHY_11ABGN_MIXED:
-#endif // DOT11_N_SUPPORT //
-			*pChType = BAND_BOTH;
-			break;
-
-		default:
-			*pChType = BAND_24G;
-			break;
-	}
-}
-
-static inline UCHAR FillChList(
-	IN PRTMP_ADAPTER pAd,
-	IN PCH_DESP pChDesp,
-	IN UCHAR Offset,
-	IN UCHAR increment)
-{
-	INT i, j, l;
-	UCHAR channel;
-
-	j = Offset;
-	for (i = 0; i < pChDesp->NumOfCh; i++)
-	{
-		channel = pChDesp->FirstChannel + i * increment;
-		for (l=0; l<MAX_NUM_OF_CHANNELS; l++)
-		{
-			if (channel == pAd->TxPower[l].Channel)
-			{
-				pAd->ChannelList[j].Power = pAd->TxPower[l].Power;
-				pAd->ChannelList[j].Power2 = pAd->TxPower[l].Power2;
-				break;
-			}
-		}
-		if (l == MAX_NUM_OF_CHANNELS)
-			continue;
-
-		pAd->ChannelList[j].Channel = pChDesp->FirstChannel + i * increment;
-		pAd->ChannelList[j].MaxTxPwr = pChDesp->MaxTxPwr;
-		pAd->ChannelList[j].DfsReq = pChDesp->DfsReq;
-		j++;
-	}
-	pAd->ChannelListNum = j;
-
-	return j;
-}
-
-static inline VOID CreateChList(
-	IN PRTMP_ADAPTER pAd,
-	IN PCH_REGION pChRegion,
-	IN UCHAR Geography)
-{
-	INT i;
-	UCHAR offset = 0;
-	PCH_DESP pChDesp;
-	UCHAR ChType;
-	UCHAR increment;
-
-	if (pChRegion == NULL)
-		return;
-
-	ChBandCheck(pAd->CommonCfg.PhyMode, &ChType);
-
-	for (i=0; i<10; i++)
-	{
-		pChDesp = &pChRegion->ChDesp[i];
-		if (pChDesp->FirstChannel == 0)
-			break;
-
-		if (ChType == BAND_5G)
-		{
-			if (pChDesp->FirstChannel <= 14)
-				continue;
-		}
-		else if (ChType == BAND_24G)
-		{
-			if (pChDesp->FirstChannel > 14)
-				continue;
-		}
-
-		if ((pChDesp->Geography == BOTH)
-			|| (pChDesp->Geography == Geography))
-        {
-			if (pChDesp->FirstChannel > 14)
-                increment = 4;
-            else
-                increment = 1;
-			offset = FillChList(pAd, pChDesp, offset, increment);
-        }
-	}
-}
-
-static inline VOID BuildChannelListEx(
-	IN PRTMP_ADAPTER pAd)
-{
-	PCH_REGION pChReg;
-
-	pChReg = GetChRegion(pAd->CommonCfg.CountryCode);
-	CreateChList(pAd, pChReg, pAd->CommonCfg.Geography);
-}
-
-static inline VOID BuildBeaconChList(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pBuf,
-	OUT	PULONG pBufLen)
-{
-	INT i;
-	ULONG TmpLen;
-	PCH_REGION pChRegion;
-	PCH_DESP pChDesp;
-	UCHAR ChType;
-
-	pChRegion = GetChRegion(pAd->CommonCfg.CountryCode);
-
-	if (pChRegion == NULL)
-		return;
-
-	ChBandCheck(pAd->CommonCfg.PhyMode, &ChType);
-	*pBufLen = 0;
-
-	for (i=0; i<10; i++)
-	{
-		pChDesp = &pChRegion->ChDesp[i];
-		if (pChDesp->FirstChannel == 0)
-			break;
-
-		if (ChType == BAND_5G)
-		{
-			if (pChDesp->FirstChannel <= 14)
-				continue;
-		}
-		else if (ChType == BAND_24G)
-		{
-			if (pChDesp->FirstChannel > 14)
-				continue;
-		}
-
-		if ((pChDesp->Geography == BOTH)
-			|| (pChDesp->Geography == pAd->CommonCfg.Geography))
-		{
-			MakeOutgoingFrame(pBuf + *pBufLen,		&TmpLen,
-								1,                 	&pChDesp->FirstChannel,
-								1,                 	&pChDesp->NumOfCh,
-								1,                 	&pChDesp->MaxTxPwr,
-								END_OF_ARGS);
-			*pBufLen += TmpLen;
-		}
-	}
-}
-
-
-#ifdef DOT11_N_SUPPORT
-static inline BOOLEAN IsValidChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR channel)
-
-{
-	INT i;
-
-	for (i = 0; i < pAd->ChannelListNum; i++)
-	{
-		if (pAd->ChannelList[i].Channel == channel)
-			break;
-	}
-
-	if (i == pAd->ChannelListNum)
-		return FALSE;
-	else
-		return TRUE;
-}
-
-
-static inline UCHAR GetExtCh(
-	IN UCHAR Channel,
-	IN UCHAR Direction)
-{
-	CHAR ExtCh;
-
-	if (Direction == EXTCHA_ABOVE)
-		ExtCh = Channel + 4;
-	else
-		ExtCh = (Channel - 4) > 0 ? (Channel - 4) : 0;
-
-	return ExtCh;
-}
-
-
-static inline VOID N_ChannelCheck(
-	IN PRTMP_ADAPTER pAd)
-{
-	//UCHAR ChannelNum = pAd->ChannelListNum;
-	UCHAR Channel = pAd->CommonCfg.Channel;
-
-	if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED) && (pAd->CommonCfg.RegTransmitSetting.field.BW  == BW_40))
-	{
-		if (Channel > 14)
-		{
-			if ((Channel == 36) || (Channel == 44) || (Channel == 52) || (Channel == 60) || (Channel == 100) || (Channel == 108) ||
-			    (Channel == 116) || (Channel == 124) || (Channel == 132) || (Channel == 149) || (Channel == 157))
-			{
-				pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-			}
-			else if ((Channel == 40) || (Channel == 48) || (Channel == 56) || (Channel == 64) || (Channel == 104) || (Channel == 112) ||
-					(Channel == 120) || (Channel == 128) || (Channel == 136) || (Channel == 153) || (Channel == 161))
-			{
-				pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_BELOW;
-			}
-			else
-			{
-				pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-			}
-		}
-		else
-		{
-			do
-			{
-				UCHAR ExtCh;
-				UCHAR Dir = pAd->CommonCfg.RegTransmitSetting.field.EXTCHA;
-				ExtCh = GetExtCh(Channel, Dir);
-				if (IsValidChannel(pAd, ExtCh))
-					break;
-
-				Dir = (Dir == EXTCHA_ABOVE) ? EXTCHA_BELOW : EXTCHA_ABOVE;
-				ExtCh = GetExtCh(Channel, Dir);
-				if (IsValidChannel(pAd, ExtCh))
-				{
-					pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = Dir;
-					break;
-				}
-				pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-			} while(FALSE);
-
-			if (Channel == 14)
-			{
-				pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-				//pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_NONE;	// We didn't set the ExtCh as NONE due to it'll set in RTMPSetHT()
-			}
-		}
-	}
-
-
-}
-
-
-static inline VOID N_SetCenCh(
-	IN PRTMP_ADAPTER pAd)
-{
-	if (pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40)
-	{
-		if (pAd->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_ABOVE)
-		{
-			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel + 2;
-		}
-		else
-		{
-			if (pAd->CommonCfg.Channel == 14)
-				pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel - 1;
-			else
-				pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel - 2;
-		}
-	}
-	else
-	{
-		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
-	}
-}
-#endif // DOT11_N_SUPPORT //
-
-
-static inline UINT8 GetCuntryMaxTxPwr(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT8 channel)
-{
-	int i;
-	for (i = 0; i < pAd->ChannelListNum; i++)
-	{
-		if (pAd->ChannelList[i].Channel == channel)
-			break;
-	}
-
-	if (i == pAd->ChannelListNum)
-		return 0xff;
-	else
-		return pAd->ChannelList[i].MaxTxPwr;
-}
-#endif // __CHLIST_H__
-
+#include "../rt2870/chlist.h"
diff --git a/drivers/staging/rt3070/common/2870_rtmp_init.c b/drivers/staging/rt3070/common/2870_rtmp_init.c
index fdf8dc1..5456454 100644
--- a/drivers/staging/rt3070/common/2870_rtmp_init.c
+++ b/drivers/staging/rt3070/common/2870_rtmp_init.c
@@ -1,1762 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	2870_rtmp_init.c
-
-	Abstract:
-	Miniport generic portion header file
-
-	Revision History:
-	Who         When          What
-	--------    ----------    ----------------------------------------------
-	Paul Lin    2002-08-01    created
-    John Chang  2004-08-20    RT2561/2661 use scatter-gather scheme
-    Jan Lee  	2006-09-15    RT2860. Change for 802.11n , EEPROM, Led, BA, HT.
-	Sample Lin	2007-05-31    Merge RT2860 and RT2870 drivers.
-*/
-
-#include	"../rt_config.h"
-
-
-static void rx_done_tasklet(unsigned long data);
-static void rt2870_hcca_dma_done_tasklet(unsigned long data);
-static void rt2870_ac3_dma_done_tasklet(unsigned long data);
-static void rt2870_ac2_dma_done_tasklet(unsigned long data);
-static void rt2870_ac1_dma_done_tasklet(unsigned long data);
-static void rt2870_ac0_dma_done_tasklet(unsigned long data);
-static void rt2870_mgmt_dma_done_tasklet(unsigned long data);
-static void rt2870_null_frame_complete_tasklet(unsigned long data);
-static void rt2870_rts_frame_complete_tasklet(unsigned long data);
-static void rt2870_pspoll_frame_complete_tasklet(unsigned long data);
-static void rt2870_dataout_complete_tasklet(unsigned long data);
-
-
-/*
-========================================================================
-Routine Description:
-    Initialize receive data structures.
-
-Arguments:
-    pAd					Pointer to our adapter
-
-Return Value:
-	NDIS_STATUS_SUCCESS
-	NDIS_STATUS_RESOURCES
-
-Note:
-	Initialize all receive releated private buffer, include those define
-	in RTMP_ADAPTER structure and all private data structures. The mahor
-	work is to allocate buffer for each packet and chain buffer to
-	NDIS packet descriptor.
-========================================================================
-*/
-NDIS_STATUS	NICInitRecv(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UCHAR				i;
-	NDIS_STATUS			Status = NDIS_STATUS_SUCCESS;
-	POS_COOKIE			pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICInitRecv\n"));
-	pObj = pObj;
-
-	//InterlockedExchange(&pAd->PendingRx, 0);
-	pAd->PendingRx = 0;
-	pAd->NextRxBulkInReadIndex 	= 0;	// Next Rx Read index
-	pAd->NextRxBulkInIndex		= 0 ; //RX_RING_SIZE -1; // Rx Bulk pointer
-	pAd->NextRxBulkInPosition 	= 0;
-
-	for (i = 0; i < (RX_RING_SIZE); i++)
-	{
-		PRX_CONTEXT  pRxContext = &(pAd->RxContext[i]);
-
-		//Allocate URB
-		pRxContext->pUrb = RTUSB_ALLOC_URB(0);
-		if (pRxContext->pUrb == NULL)
-		{
-			Status = NDIS_STATUS_RESOURCES;
-			goto out1;
-		}
-
-		// Allocate transfer buffer
-		pRxContext->TransferBuffer = RTUSB_URB_ALLOC_BUFFER(pObj->pUsb_Dev, MAX_RXBULK_SIZE, &pRxContext->data_dma);
-		if (pRxContext->TransferBuffer == NULL)
-		{
-			Status = NDIS_STATUS_RESOURCES;
-			goto out1;
-		}
-
-		NdisZeroMemory(pRxContext->TransferBuffer, MAX_RXBULK_SIZE);
-
-		pRxContext->pAd	= pAd;
-		pRxContext->pIrp = NULL;
-		pRxContext->InUse		= FALSE;
-		pRxContext->IRPPending	= FALSE;
-		pRxContext->Readable	= FALSE;
-		//pRxContext->ReorderInUse = FALSE;
-		pRxContext->bRxHandling = FALSE;
-		pRxContext->BulkInOffset = 0;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICInitRecv\n"));
-	return Status;
-
-out1:
-	for (i = 0; i < (RX_RING_SIZE); i++)
-	{
-		PRX_CONTEXT  pRxContext = &(pAd->RxContext[i]);
-
-		if (NULL != pRxContext->TransferBuffer)
-		{
-			RTUSB_URB_FREE_BUFFER(pObj->pUsb_Dev, MAX_RXBULK_SIZE,
-								pRxContext->TransferBuffer, pRxContext->data_dma);
-			pRxContext->TransferBuffer = NULL;
-		}
-
-		if (NULL != pRxContext->pUrb)
-		{
-			RTUSB_UNLINK_URB(pRxContext->pUrb);
-			RTUSB_FREE_URB(pRxContext->pUrb);
-			pRxContext->pUrb = NULL;
-		}
-	}
-
-	return Status;
-}
-
-
-/*
-========================================================================
-Routine Description:
-    Initialize transmit data structures.
-
-Arguments:
-    pAd					Pointer to our adapter
-
-Return Value:
-	NDIS_STATUS_SUCCESS
-	NDIS_STATUS_RESOURCES
-
-Note:
-========================================================================
-*/
-NDIS_STATUS	NICInitTransmit(
-	IN	PRTMP_ADAPTER	pAd)
-{
-#define LM_USB_ALLOC(pObj, Context, TB_Type, BufferSize, Status, msg1, err1, msg2, err2)	\
-	Context->pUrb = RTUSB_ALLOC_URB(0);		\
-	if (Context->pUrb == NULL) {			\
-		DBGPRINT(RT_DEBUG_ERROR, msg1);		\
-		Status = NDIS_STATUS_RESOURCES;		\
-		goto err1; }						\
-											\
-	Context->TransferBuffer = 				\
-		(TB_Type)RTUSB_URB_ALLOC_BUFFER(pObj->pUsb_Dev, BufferSize, &Context->data_dma);	\
-	if (Context->TransferBuffer == NULL) {	\
-		DBGPRINT(RT_DEBUG_ERROR, msg2);		\
-		Status = NDIS_STATUS_RESOURCES;		\
-		goto err2; }
-
-#define LM_URB_FREE(pObj, Context, BufferSize)				\
-	if (NULL != Context->pUrb) {							\
-		RTUSB_UNLINK_URB(Context->pUrb);					\
-		RTUSB_FREE_URB(Context->pUrb);						\
-		Context->pUrb = NULL; }								\
-	if (NULL != Context->TransferBuffer) {				\
-		RTUSB_URB_FREE_BUFFER(pObj->pUsb_Dev, BufferSize,	\
-								Context->TransferBuffer,	\
-								Context->data_dma);			\
-		Context->TransferBuffer = NULL; }
-
-	UCHAR			i, acidx;
-	NDIS_STATUS     Status = NDIS_STATUS_SUCCESS;
-	PTX_CONTEXT		pNullContext   = &(pAd->NullContext);
-	PTX_CONTEXT		pPsPollContext = &(pAd->PsPollContext);
-	PTX_CONTEXT		pRTSContext    = &(pAd->RTSContext);
-	PTX_CONTEXT		pMLMEContext = NULL;
-//	PHT_TX_CONTEXT	pHTTXContext = NULL;
-	POS_COOKIE		pObj = (POS_COOKIE) pAd->OS_Cookie;
-	PVOID			RingBaseVa;
-//	RTMP_TX_RING	*pTxRing;
-	RTMP_MGMT_RING  *pMgmtRing;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICInitTransmit\n"));
-	pObj = pObj;
-
-	// Init 4 set of Tx parameters
-	for(acidx = 0; acidx < NUM_OF_TX_RING; acidx++)
-	{
-		// Initialize all Transmit releated queues
-		InitializeQueueHeader(&pAd->TxSwQueue[acidx]);
-
-		// Next Local tx ring pointer waiting for buck out
-		pAd->NextBulkOutIndex[acidx] = acidx;
-		pAd->BulkOutPending[acidx] = FALSE; // Buck Out control flag
-		//pAd->DataBulkDoneIdx[acidx] = 0;
-	}
-
-	//pAd->NextMLMEIndex	= 0;
-	//pAd->PushMgmtIndex	= 0;
-	//pAd->PopMgmtIndex	= 0;
-	//InterlockedExchange(&pAd->MgmtQueueSize, 0);
-	//InterlockedExchange(&pAd->TxCount, 0);
-
-	//pAd->PrioRingFirstIndex	= 0;
-	//pAd->PrioRingTxCnt		= 0;
-
-	do
-	{
-		//
-		// TX_RING_SIZE, 4 ACs
-		//
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		for(acidx=0; acidx<4; acidx++)
-#endif // CONFIG_STA_SUPPORT //
-		{
-#if 1 //def DOT11_N_SUPPORT
-			PHT_TX_CONTEXT	pHTTXContext = &(pAd->TxContext[acidx]);
-
-			NdisZeroMemory(pHTTXContext, sizeof(HT_TX_CONTEXT));
-			//Allocate URB
-			LM_USB_ALLOC(pObj, pHTTXContext, PHTTX_BUFFER, sizeof(HTTX_BUFFER), Status,
-							("<-- ERROR in Alloc TX TxContext[%d] urb!! \n", acidx),
-							done,
-							("<-- ERROR in Alloc TX TxContext[%d] HTTX_BUFFER !! \n", acidx),
-							out1);
-
-			NdisZeroMemory(pHTTXContext->TransferBuffer->Aggregation, 4);
-			pHTTXContext->pAd = pAd;
-			pHTTXContext->pIrp = NULL;
-			pHTTXContext->IRPPending = FALSE;
-			pHTTXContext->NextBulkOutPosition = 0;
-			pHTTXContext->ENextBulkOutPosition = 0;
-			pHTTXContext->CurWritePosition = 0;
-			pHTTXContext->CurWriteRealPos = 0;
-			pHTTXContext->BulkOutSize = 0;
-			pHTTXContext->BulkOutPipeId = acidx;
-			pHTTXContext->bRingEmpty = TRUE;
-			pHTTXContext->bCopySavePad = FALSE;
-#endif // DOT11_N_SUPPORT //
-			pAd->BulkOutPending[acidx] = FALSE;
-		}
-
-
-		//
-		// MGMT_RING_SIZE
-		//
-		// Allocate MGMT ring descriptor's memory
-		pAd->MgmtDescRing.AllocSize = MGMT_RING_SIZE * sizeof(TX_CONTEXT);
-		RTMPAllocateMemory(&pAd->MgmtDescRing.AllocVa, pAd->MgmtDescRing.AllocSize);
-		if (pAd->MgmtDescRing.AllocVa == NULL)
-		{
-			DBGPRINT_ERR(("Failed to allocate a big buffer for MgmtDescRing!\n"));
-			Status = NDIS_STATUS_RESOURCES;
-			goto out1;
-		}
-		NdisZeroMemory(pAd->MgmtDescRing.AllocVa, pAd->MgmtDescRing.AllocSize);
-		RingBaseVa     = pAd->MgmtDescRing.AllocVa;
-
-		// Initialize MGMT Ring and associated buffer memory
-		pMgmtRing = &pAd->MgmtRing;
-		for (i = 0; i < MGMT_RING_SIZE; i++)
-		{
-			// link the pre-allocated Mgmt buffer to MgmtRing.Cell
-			pMgmtRing->Cell[i].AllocSize = sizeof(TX_CONTEXT);
-			pMgmtRing->Cell[i].AllocVa = RingBaseVa;
-			pMgmtRing->Cell[i].pNdisPacket = NULL;
-			pMgmtRing->Cell[i].pNextNdisPacket = NULL;
-
-			//Allocate URB for MLMEContext
-			pMLMEContext = (PTX_CONTEXT) pAd->MgmtRing.Cell[i].AllocVa;
-			pMLMEContext->pUrb = RTUSB_ALLOC_URB(0);
-			if (pMLMEContext->pUrb == NULL)
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("<-- ERROR in Alloc TX MLMEContext[%d] urb!! \n", i));
-				Status = NDIS_STATUS_RESOURCES;
-				goto out2;
-			}
-			pMLMEContext->pAd = pAd;
-			pMLMEContext->pIrp = NULL;
-			pMLMEContext->TransferBuffer = NULL;
-			pMLMEContext->InUse = FALSE;
-			pMLMEContext->IRPPending = FALSE;
-			pMLMEContext->bWaitingBulkOut = FALSE;
-			pMLMEContext->BulkOutSize = 0;
-			pMLMEContext->SelfIdx = i;
-
-			// Offset to next ring descriptor address
-			RingBaseVa = (PUCHAR) RingBaseVa + sizeof(TX_CONTEXT);
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("MGMT Ring: total %d entry allocated\n", i));
-
-		//pAd->MgmtRing.TxSwFreeIdx = (MGMT_RING_SIZE - 1);
-		pAd->MgmtRing.TxSwFreeIdx = MGMT_RING_SIZE;
-		pAd->MgmtRing.TxCpuIdx = 0;
-		pAd->MgmtRing.TxDmaIdx = 0;
-
-		//
-		// BEACON_RING_SIZE
-		//
-		for(i=0; i<BEACON_RING_SIZE; i++) // 2
-		{
-			PTX_CONTEXT	pBeaconContext = &(pAd->BeaconContext[i]);
-
-
-			NdisZeroMemory(pBeaconContext, sizeof(TX_CONTEXT));
-
-			//Allocate URB
-			LM_USB_ALLOC(pObj, pBeaconContext, PTX_BUFFER, sizeof(TX_BUFFER), Status,
-							("<-- ERROR in Alloc TX BeaconContext[%d] urb!! \n", i),
-							out2,
-							("<-- ERROR in Alloc TX BeaconContext[%d] TX_BUFFER !! \n", i),
-							out3);
-
-			pBeaconContext->pAd = pAd;
-			pBeaconContext->pIrp = NULL;
-			pBeaconContext->InUse = FALSE;
-			pBeaconContext->IRPPending = FALSE;
-		}
-
-		//
-		// NullContext
-		//
-		NdisZeroMemory(pNullContext, sizeof(TX_CONTEXT));
-
-		//Allocate URB
-		LM_USB_ALLOC(pObj, pNullContext, PTX_BUFFER, sizeof(TX_BUFFER), Status,
-						("<-- ERROR in Alloc TX NullContext urb!! \n"),
-						out3,
-						("<-- ERROR in Alloc TX NullContext TX_BUFFER !! \n"),
-						out4);
-
-		pNullContext->pAd = pAd;
-		pNullContext->pIrp = NULL;
-		pNullContext->InUse = FALSE;
-		pNullContext->IRPPending = FALSE;
-
-		//
-		// RTSContext
-		//
-		NdisZeroMemory(pRTSContext, sizeof(TX_CONTEXT));
-
-		//Allocate URB
-		LM_USB_ALLOC(pObj, pRTSContext, PTX_BUFFER, sizeof(TX_BUFFER), Status,
-						("<-- ERROR in Alloc TX RTSContext urb!! \n"),
-						out4,
-						("<-- ERROR in Alloc TX RTSContext TX_BUFFER !! \n"),
-						out5);
-
-		pRTSContext->pAd = pAd;
-		pRTSContext->pIrp = NULL;
-		pRTSContext->InUse = FALSE;
-		pRTSContext->IRPPending = FALSE;
-
-		//
-		// PsPollContext
-		//
-		//NdisZeroMemory(pPsPollContext, sizeof(TX_CONTEXT));
-		//Allocate URB
-		LM_USB_ALLOC(pObj, pPsPollContext, PTX_BUFFER, sizeof(TX_BUFFER), Status,
-						("<-- ERROR in Alloc TX PsPollContext urb!! \n"),
-						out5,
-						("<-- ERROR in Alloc TX PsPollContext TX_BUFFER !! \n"),
-						out6);
-
-		pPsPollContext->pAd = pAd;
-		pPsPollContext->pIrp = NULL;
-		pPsPollContext->InUse = FALSE;
-		pPsPollContext->IRPPending = FALSE;
-		pPsPollContext->bAggregatible = FALSE;
-		pPsPollContext->LastOne = TRUE;
-
-	}   while (FALSE);
-
-
-done:
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICInitTransmit\n"));
-
-	return Status;
-
-	/* --------------------------- ERROR HANDLE --------------------------- */
-out6:
-	LM_URB_FREE(pObj, pPsPollContext, sizeof(TX_BUFFER));
-
-out5:
-	LM_URB_FREE(pObj, pRTSContext, sizeof(TX_BUFFER));
-
-out4:
-	LM_URB_FREE(pObj, pNullContext, sizeof(TX_BUFFER));
-
-out3:
-	for(i=0; i<BEACON_RING_SIZE; i++)
-	{
-		PTX_CONTEXT	pBeaconContext = &(pAd->BeaconContext[i]);
-		if (pBeaconContext)
-			LM_URB_FREE(pObj, pBeaconContext, sizeof(TX_BUFFER));
-	}
-
-out2:
-	if (pAd->MgmtDescRing.AllocVa)
-	{
-		pMgmtRing = &pAd->MgmtRing;
-	for(i=0; i<MGMT_RING_SIZE; i++)
-	{
-		pMLMEContext = (PTX_CONTEXT) pAd->MgmtRing.Cell[i].AllocVa;
-		if (pMLMEContext)
-			LM_URB_FREE(pObj, pMLMEContext, sizeof(TX_BUFFER));
-	}
-		NdisFreeMemory(pAd->MgmtDescRing.AllocVa, pAd->MgmtDescRing.AllocSize, 0);
-		pAd->MgmtDescRing.AllocVa = NULL;
-	}
-
-out1:
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	for(acidx=0; acidx<4; acidx++)
-#endif // CONFIG_STA_SUPPORT //
-	{
-		PHT_TX_CONTEXT pTxContext = &(pAd->TxContext[acidx]);
-		if (pTxContext)
-			LM_URB_FREE(pObj, pTxContext, sizeof(HTTX_BUFFER));
-	}
-
-	// Here we didn't have any pre-allocated memory need to free.
-
-	return Status;
-}
-
-
-/*
-========================================================================
-Routine Description:
-    Allocate DMA memory blocks for send, receive.
-
-Arguments:
-    pAd					Pointer to our adapter
-
-Return Value:
-	NDIS_STATUS_SUCCESS
-	NDIS_STATUS_FAILURE
-	NDIS_STATUS_RESOURCES
-
-Note:
-========================================================================
-*/
-NDIS_STATUS	RTMPAllocTxRxRingMemory(
-	IN	PRTMP_ADAPTER	pAd)
-{
-//	COUNTER_802_11	pCounter = &pAd->WlanCounters;
-	NDIS_STATUS		Status;
-	INT				num;
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> RTMPAllocTxRxRingMemory\n"));
-
-
-	do
-	{
-		// Init the CmdQ and CmdQLock
-		NdisAllocateSpinLock(&pAd->CmdQLock);
-		NdisAcquireSpinLock(&pAd->CmdQLock);
-		RTUSBInitializeCmdQ(&pAd->CmdQ);
-		NdisReleaseSpinLock(&pAd->CmdQLock);
-
-
-		NdisAllocateSpinLock(&pAd->MLMEBulkOutLock);
-		//NdisAllocateSpinLock(&pAd->MLMEWaitQueueLock);
-		NdisAllocateSpinLock(&pAd->BulkOutLock[0]);
-		NdisAllocateSpinLock(&pAd->BulkOutLock[1]);
-		NdisAllocateSpinLock(&pAd->BulkOutLock[2]);
-		NdisAllocateSpinLock(&pAd->BulkOutLock[3]);
-		NdisAllocateSpinLock(&pAd->BulkOutLock[4]);
-		NdisAllocateSpinLock(&pAd->BulkOutLock[5]);
-		NdisAllocateSpinLock(&pAd->BulkInLock);
-
-		for (num = 0; num < NUM_OF_TX_RING; num++)
-		{
-			NdisAllocateSpinLock(&pAd->TxContextQueueLock[num]);
-		}
-
-#ifdef RALINK_ATE
-		NdisAllocateSpinLock(&pAd->GenericLock);
-#endif // RALINK_ATE //
-
-//		NdisAllocateSpinLock(&pAd->MemLock);	// Not used in RT28XX
-
-//		NdisAllocateSpinLock(&pAd->MacTabLock); // init it in UserCfgInit()
-//		NdisAllocateSpinLock(&pAd->BATabLock); // init it in BATableInit()
-
-//		for(num=0; num<MAX_LEN_OF_BA_REC_TABLE; num++)
-//		{
-//			NdisAllocateSpinLock(&pAd->BATable.BARecEntry[num].RxReRingLock);
-//		}
-
-		//
-		// Init Mac Table
-		//
-//		MacTableInitialize(pAd);
-
-		//
-		// Init send data structures and related parameters
-		//
-		Status = NICInitTransmit(pAd);
-		if (Status != NDIS_STATUS_SUCCESS)
-			break;
-
-		//
-		// Init receive data structures and related parameters
-		//
-		Status = NICInitRecv(pAd);
-		if (Status != NDIS_STATUS_SUCCESS)
-			break;
-
-		pAd->PendingIoCount = 1;
-
-	} while (FALSE);
-
-	NdisZeroMemory(&pAd->FragFrame, sizeof(FRAGMENT_FRAME));
-	pAd->FragFrame.pFragPacket =  RTMP_AllocateFragPacketBuffer(pAd, RX_BUFFER_NORMSIZE);
-
-	if (pAd->FragFrame.pFragPacket == NULL)
-	{
-		Status = NDIS_STATUS_RESOURCES;
-	}
-
-	DBGPRINT_S(Status, ("<-- RTMPAllocTxRxRingMemory, Status=%x\n", Status));
-	return Status;
-}
-
-
-/*
-========================================================================
-Routine Description:
-	Calls USB_InterfaceStop and frees memory allocated for the URBs
-    calls NdisMDeregisterDevice and frees the memory
-    allocated in VNetInitialize for the Adapter Object
-
-Arguments:
-	*pAd				the raxx interface data pointer
-
-Return Value:
-	None
-
-Note:
-========================================================================
-*/
-VOID	RTMPFreeTxRxRingMemory(
-	IN	PRTMP_ADAPTER	pAd)
-{
-#define LM_URB_FREE(pObj, Context, BufferSize)				\
-	if (NULL != Context->pUrb) {							\
-		RTUSB_UNLINK_URB(Context->pUrb);					\
-		RTUSB_FREE_URB(Context->pUrb);						\
-		Context->pUrb = NULL; }								\
-	if (NULL != Context->TransferBuffer) {					\
-		RTUSB_URB_FREE_BUFFER(pObj->pUsb_Dev, BufferSize,	\
-								Context->TransferBuffer,	\
-								Context->data_dma);			\
-		Context->TransferBuffer = NULL; }
-
-
-	UINT                i, acidx;
-	PTX_CONTEXT			pNullContext   = &pAd->NullContext;
-	PTX_CONTEXT			pPsPollContext = &pAd->PsPollContext;
-	PTX_CONTEXT			pRTSContext    = &pAd->RTSContext;
-//	PHT_TX_CONTEXT 		pHTTXContext;
-	//PRTMP_REORDERBUF	pReorderBuf;
-	POS_COOKIE			pObj = (POS_COOKIE) pAd->OS_Cookie;
-//	RTMP_TX_RING		*pTxRing;
-
-	DBGPRINT(RT_DEBUG_ERROR, ("---> RTMPFreeTxRxRingMemory\n"));
-	pObj = pObj;
-
-	// Free all resources for the RECEIVE buffer queue.
-	for(i=0; i<(RX_RING_SIZE); i++)
-	{
-		PRX_CONTEXT  pRxContext = &(pAd->RxContext[i]);
-		if (pRxContext)
-			LM_URB_FREE(pObj, pRxContext, MAX_RXBULK_SIZE);
-	}
-
-	// Free PsPoll frame resource
-	LM_URB_FREE(pObj, pPsPollContext, sizeof(TX_BUFFER));
-
-	// Free NULL frame resource
-	LM_URB_FREE(pObj, pNullContext, sizeof(TX_BUFFER));
-
-	// Free RTS frame resource
-	LM_URB_FREE(pObj, pRTSContext, sizeof(TX_BUFFER));
-
-
-	// Free beacon frame resource
-	for(i=0; i<BEACON_RING_SIZE; i++)
-	{
-		PTX_CONTEXT	pBeaconContext = &(pAd->BeaconContext[i]);
-		if (pBeaconContext)
-			LM_URB_FREE(pObj, pBeaconContext, sizeof(TX_BUFFER));
-	}
-
-
-	// Free mgmt frame resource
-	for(i = 0; i < MGMT_RING_SIZE; i++)
-	{
-		PTX_CONTEXT pMLMEContext = (PTX_CONTEXT)pAd->MgmtRing.Cell[i].AllocVa;
-		//LM_URB_FREE(pObj, pMLMEContext, sizeof(TX_BUFFER));
-		if (NULL != pAd->MgmtRing.Cell[i].pNdisPacket)
-		{
-			RTMPFreeNdisPacket(pAd, pAd->MgmtRing.Cell[i].pNdisPacket);
-			pAd->MgmtRing.Cell[i].pNdisPacket = NULL;
-			pMLMEContext->TransferBuffer = NULL;
-		}
-
-		if (pMLMEContext)
-		{
-			if (NULL != pMLMEContext->pUrb)
-			{
-				RTUSB_UNLINK_URB(pMLMEContext->pUrb);
-				RTUSB_FREE_URB(pMLMEContext->pUrb);
-				pMLMEContext->pUrb = NULL;
-			}
-		}
-	}
-	if (pAd->MgmtDescRing.AllocVa)
-		NdisFreeMemory(pAd->MgmtDescRing.AllocVa, pAd->MgmtDescRing.AllocSize, 0);
-
-
-	// Free Tx frame resource
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		for(acidx=0; acidx<4; acidx++)
-#endif // CONFIG_STA_SUPPORT //
-		{
-		PHT_TX_CONTEXT pHTTXContext = &(pAd->TxContext[acidx]);
-			if (pHTTXContext)
-				LM_URB_FREE(pObj, pHTTXContext, sizeof(HTTX_BUFFER));
-		}
-
-	if (pAd->FragFrame.pFragPacket)
-		RELEASE_NDIS_PACKET(pAd, pAd->FragFrame.pFragPacket, NDIS_STATUS_SUCCESS);
-
-	for(i=0; i<6; i++)
-	{
-		NdisFreeSpinLock(&pAd->BulkOutLock[i]);
-	}
-
-	NdisFreeSpinLock(&pAd->BulkInLock);
-	NdisFreeSpinLock(&pAd->MLMEBulkOutLock);
-
-	NdisFreeSpinLock(&pAd->CmdQLock);
-#ifdef RALINK_ATE
-	NdisFreeSpinLock(&pAd->GenericLock);
-#endif // RALINK_ATE //
-	// Clear all pending bulk-out request flags.
-	RTUSB_CLEAR_BULK_FLAG(pAd, 0xffffffff);
-
-//	NdisFreeSpinLock(&pAd->MacTabLock);
-
-//	for(i=0; i<MAX_LEN_OF_BA_REC_TABLE; i++)
-//	{
-//		NdisFreeSpinLock(&pAd->BATable.BARecEntry[i].RxReRingLock);
-//	}
-
-	DBGPRINT(RT_DEBUG_ERROR, ("<--- ReleaseAdapter\n"));
-}
-
-
-/*
-========================================================================
-Routine Description:
-    Allocate memory for adapter control block.
-
-Arguments:
-    pAd					Pointer to our adapter
-
-Return Value:
-	NDIS_STATUS_SUCCESS
-	NDIS_STATUS_FAILURE
-	NDIS_STATUS_RESOURCES
-
-Note:
-========================================================================
-*/
-NDIS_STATUS AdapterBlockAllocateMemory(
-	IN PVOID	handle,
-	OUT	PVOID	*ppAd)
-{
-	PUSB_DEV	usb_dev;
-	POS_COOKIE	pObj = (POS_COOKIE) handle;
-
-
-	usb_dev = pObj->pUsb_Dev;
-
-	pObj->MLMEThr_pid	= NULL;
-	pObj->RTUSBCmdThr_pid	= NULL;
-
-	*ppAd = (PVOID)vmalloc(sizeof(RTMP_ADAPTER));
-
-	if (*ppAd)
-	{
-		NdisZeroMemory(*ppAd, sizeof(RTMP_ADAPTER));
-		((PRTMP_ADAPTER)*ppAd)->OS_Cookie = handle;
-		return (NDIS_STATUS_SUCCESS);
-	}
-	else
-	{
-		return (NDIS_STATUS_FAILURE);
-	}
-}
-
-
-/*
-========================================================================
-Routine Description:
-    Create kernel threads & tasklets.
-
-Arguments:
-    *net_dev			Pointer to wireless net device interface
-
-Return Value:
-	NDIS_STATUS_SUCCESS
-	NDIS_STATUS_FAILURE
-
-Note:
-========================================================================
-*/
-NDIS_STATUS	 CreateThreads(
-	IN	struct net_device *net_dev)
-{
-	PRTMP_ADAPTER pAd = net_dev->ml_priv;
-	POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;
-	pid_t pid_number;
-
-	//init_MUTEX(&(pAd->usbdev_semaphore));
-
-	init_MUTEX_LOCKED(&(pAd->mlme_semaphore));
-	init_completion (&pAd->mlmeComplete);
-
-	init_MUTEX_LOCKED(&(pAd->RTUSBCmd_semaphore));
-	init_completion (&pAd->CmdQComplete);
-
-	init_MUTEX_LOCKED(&(pAd->RTUSBTimer_semaphore));
-	init_completion (&pAd->TimerQComplete);
-
-	// Creat MLME Thread
-	pObj->MLMEThr_pid = NULL;
-	pid_number = kernel_thread(MlmeThread, pAd, CLONE_VM);
-	if (pid_number < 0)
-	{
-		printk (KERN_WARNING "%s: unable to start Mlme thread\n",pAd->net_dev->name);
-		return NDIS_STATUS_FAILURE;
-	}
-	pObj->MLMEThr_pid = find_get_pid(pid_number);
-	// Wait for the thread to start
-	wait_for_completion(&(pAd->mlmeComplete));
-
-	// Creat Command Thread
-	pObj->RTUSBCmdThr_pid = NULL;
-	pid_number = kernel_thread(RTUSBCmdThread, pAd, CLONE_VM);
-	if (pid_number < 0)
-	{
-		printk (KERN_WARNING "%s: unable to start RTUSBCmd thread\n",pAd->net_dev->name);
-		return NDIS_STATUS_FAILURE;
-	}
-	pObj->RTUSBCmdThr_pid = find_get_pid(pid_number);
-	wait_for_completion(&(pAd->CmdQComplete));
-
-	pObj->TimerQThr_pid = NULL;
-	pid_number = kernel_thread(TimerQThread, pAd, CLONE_VM);
-	if (pid_number < 0)
-	{
-		printk (KERN_WARNING "%s: unable to start TimerQThread\n",pAd->net_dev->name);
-		return NDIS_STATUS_FAILURE;
-	}
-	pObj->TimerQThr_pid = find_get_pid(pid_number);
-	// Wait for the thread to start
-	wait_for_completion(&(pAd->TimerQComplete));
-
-	// Create receive tasklet
-	tasklet_init(&pObj->rx_done_task, rx_done_tasklet, (ULONG)pAd);
-	tasklet_init(&pObj->mgmt_dma_done_task, rt2870_mgmt_dma_done_tasklet, (unsigned long)pAd);
-	tasklet_init(&pObj->ac0_dma_done_task, rt2870_ac0_dma_done_tasklet, (unsigned long)pAd);
-	tasklet_init(&pObj->ac1_dma_done_task, rt2870_ac1_dma_done_tasklet, (unsigned long)pAd);
-	tasklet_init(&pObj->ac2_dma_done_task, rt2870_ac2_dma_done_tasklet, (unsigned long)pAd);
-	tasklet_init(&pObj->ac3_dma_done_task, rt2870_ac3_dma_done_tasklet, (unsigned long)pAd);
-	tasklet_init(&pObj->hcca_dma_done_task, rt2870_hcca_dma_done_tasklet, (unsigned long)pAd);
-	tasklet_init(&pObj->tbtt_task, tbtt_tasklet, (unsigned long)pAd);
-	tasklet_init(&pObj->null_frame_complete_task, rt2870_null_frame_complete_tasklet, (unsigned long)pAd);
-	tasklet_init(&pObj->rts_frame_complete_task, rt2870_rts_frame_complete_tasklet, (unsigned long)pAd);
-	tasklet_init(&pObj->pspoll_frame_complete_task, rt2870_pspoll_frame_complete_tasklet, (unsigned long)pAd);
-
-	return NDIS_STATUS_SUCCESS;
-}
-
-
-#ifdef CONFIG_STA_SUPPORT
-/*
-========================================================================
-Routine Description:
- 	As STA's BSSID is a WC too, it uses shared key table.
- 	This function write correct unicast TX key to ASIC WCID.
- 	And we still make a copy in our MacTab.Content[BSSID_WCID].PairwiseKey.
-	Caller guarantee TKIP/AES always has keyidx = 0. (pairwise key)
-	Caller guarantee WEP calls this function when set Txkey,  default key index=0~3.
-
-Arguments:
-	pAd 					Pointer to our adapter
-	pKey					Pointer to the where the key stored
-
-Return Value:
-	NDIS_SUCCESS			Add key successfully
-
-Note:
-========================================================================
-*/
-VOID	RTMPAddBSSIDCipher(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	UCHAR				Aid,
-	IN	PNDIS_802_11_KEY	pKey,
-	IN  UCHAR   			CipherAlg)
-{
-	PUCHAR		pTxMic, pRxMic;
-	BOOLEAN 	bKeyRSC, bAuthenticator; // indicate the receive SC set by KeyRSC value
-//	UCHAR		CipherAlg;
-	UCHAR		i;
-	ULONG		WCIDAttri;
-	USHORT	 	offset;
-	UCHAR		KeyIdx, IVEIV[8];
-	UINT32		Value;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPAddBSSIDCipher==> Aid = %d\n",Aid));
-
-	// Bit 29 of Add-key KeyRSC
-	bKeyRSC 	   = (pKey->KeyIndex & 0x20000000) ? TRUE : FALSE;
-
-	// Bit 28 of Add-key Authenticator
-	bAuthenticator = (pKey->KeyIndex & 0x10000000) ? TRUE : FALSE;
-	KeyIdx = (UCHAR)pKey->KeyIndex&0xff;
-
-	if (KeyIdx > 4)
-		return;
-
-
-	if (pAd->MacTab.Content[Aid].PairwiseKey.CipherAlg == CIPHER_TKIP)
-	{	if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-		{
-			// for WPA-None Tx, Rx MIC is the same
-			pTxMic = (PUCHAR) (&pKey->KeyMaterial) + 16;
-			pRxMic = pTxMic;
-		}
-		else if (bAuthenticator == TRUE)
-		{
-			pTxMic = (PUCHAR) (&pKey->KeyMaterial) + 16;
-			pRxMic = (PUCHAR) (&pKey->KeyMaterial) + 24;
-		}
-		else
-		{
-			pRxMic = (PUCHAR) (&pKey->KeyMaterial) + 16;
-			pTxMic = (PUCHAR) (&pKey->KeyMaterial) + 24;
-		}
-
-		offset = PAIRWISE_KEY_TABLE_BASE + (Aid * HW_KEY_ENTRY_SIZE) + 0x10;
-		for (i=0; i<8; )
-		{
-			Value = *(pTxMic+i);
-			Value += (*(pTxMic+i+1)<<8);
-			Value += (*(pTxMic+i+2)<<16);
-			Value += (*(pTxMic+i+3)<<24);
-			RTUSBWriteMACRegister(pAd, offset+i, Value);
-			i+=4;
-		}
-
-		offset = PAIRWISE_KEY_TABLE_BASE + (Aid * HW_KEY_ENTRY_SIZE) + 0x18;
-		for (i=0; i<8; )
-		{
-			Value = *(pRxMic+i);
-			Value += (*(pRxMic+i+1)<<8);
-			Value += (*(pRxMic+i+2)<<16);
-			Value += (*(pRxMic+i+3)<<24);
-			RTUSBWriteMACRegister(pAd, offset+i, Value);
-			i+=4;
-		}
-
-		// Only Key lenth equal to TKIP key have these
-		NdisMoveMemory(pAd->MacTab.Content[Aid].PairwiseKey.RxMic, pRxMic, 8);
-		NdisMoveMemory(pAd->MacTab.Content[Aid].PairwiseKey.TxMic, pTxMic, 8);
-
-		DBGPRINT(RT_DEBUG_TRACE,
-				("	TxMIC  = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x \n",
-				pTxMic[0],pTxMic[1],pTxMic[2],pTxMic[3],
-				pTxMic[4],pTxMic[5],pTxMic[6],pTxMic[7]));
-		DBGPRINT(RT_DEBUG_TRACE,
-				("	RxMIC  = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x \n",
-				pRxMic[0],pRxMic[1],pRxMic[2],pRxMic[3],
-				pRxMic[4],pRxMic[5],pRxMic[6],pRxMic[7]));
-	}
-
-	// 2. Record Security Key.
-	pAd->MacTab.Content[BSSID_WCID].PairwiseKey.KeyLen= (UCHAR)pKey->KeyLength;
-	NdisMoveMemory(pAd->MacTab.Content[Aid].PairwiseKey.Key, &pKey->KeyMaterial, pKey->KeyLength);
-
-	// 3. Check RxTsc. And used to init to ASIC IV.
-	if (bKeyRSC == TRUE)
-		NdisMoveMemory(pAd->MacTab.Content[Aid].PairwiseKey.RxTsc, &pKey->KeyRSC, 6);
-	else
-		NdisZeroMemory(pAd->MacTab.Content[Aid].PairwiseKey.RxTsc, 6);
-
-	// 4. Init TxTsc to one based on WiFi WPA specs
-	pAd->MacTab.Content[Aid].PairwiseKey.TxTsc[0] = 1;
-	pAd->MacTab.Content[Aid].PairwiseKey.TxTsc[1] = 0;
-	pAd->MacTab.Content[Aid].PairwiseKey.TxTsc[2] = 0;
-	pAd->MacTab.Content[Aid].PairwiseKey.TxTsc[3] = 0;
-	pAd->MacTab.Content[Aid].PairwiseKey.TxTsc[4] = 0;
-	pAd->MacTab.Content[Aid].PairwiseKey.TxTsc[5] = 0;
-
-	CipherAlg = pAd->MacTab.Content[Aid].PairwiseKey.CipherAlg;
-
-	offset = PAIRWISE_KEY_TABLE_BASE + (Aid * HW_KEY_ENTRY_SIZE);
-	RTUSBMultiWrite(pAd, (USHORT) offset, pKey->KeyMaterial,
-				((pKey->KeyLength == LEN_TKIP_KEY) ? 16 : (USHORT)pKey->KeyLength));
-
-	offset = SHARED_KEY_TABLE_BASE + (KeyIdx * HW_KEY_ENTRY_SIZE);
-	RTUSBMultiWrite(pAd, (USHORT) offset, pKey->KeyMaterial, (USHORT)pKey->KeyLength);
-
-	offset = PAIRWISE_IVEIV_TABLE_BASE + (Aid * HW_IVEIV_ENTRY_SIZE);
-	NdisZeroMemory(IVEIV, 8);
-
-	// IV/EIV
-	if ((CipherAlg == CIPHER_TKIP) ||
-		(CipherAlg == CIPHER_TKIP_NO_MIC) ||
-		(CipherAlg == CIPHER_AES))
-	{
-		IVEIV[3] = 0x20; // Eiv bit on. keyid always 0 for pairwise key
-	}
-	// default key idx needs to set.
-	// in TKIP/AES KeyIdx = 0 , WEP KeyIdx is default tx key.
-	else
-	{
-		IVEIV[3] |= (KeyIdx<< 6);
-	}
-	RTUSBMultiWrite(pAd, (USHORT) offset, IVEIV, 8);
-
-	// WCID Attribute UDF:3, BSSIdx:3, Alg:3, Keytable:1=PAIRWISE KEY, BSSIdx is 0
-	if ((CipherAlg == CIPHER_TKIP) ||
-		(CipherAlg == CIPHER_TKIP_NO_MIC) ||
-		(CipherAlg == CIPHER_AES))
-	{
-		WCIDAttri = (CipherAlg<<1)|SHAREDKEYTABLE;
-	}
-	else
-		WCIDAttri = (CipherAlg<<1)|SHAREDKEYTABLE;
-
-	offset = MAC_WCID_ATTRIBUTE_BASE + (Aid* HW_WCID_ATTRI_SIZE);
-	RTUSBWriteMACRegister(pAd, offset, WCIDAttri);
-	RTUSBReadMACRegister(pAd, offset, &Value);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("BSSID_WCID : offset = %x, WCIDAttri = %lx\n",
-			offset, WCIDAttri));
-
-	// pAddr
-	// Add Bssid mac address at linkup. not here.  check!
-	/*offset = MAC_WCID_BASE + (BSSID_WCID * HW_WCID_ENTRY_SIZE);
-	*for (i=0; i<MAC_ADDR_LEN; i++)
-	{
-		RTMP_IO_WRITE8(pAd, offset+i, pKey->BSSID[i]);
-	}
-	*/
-
-	DBGPRINT(RT_DEBUG_ERROR, ("AddBSSIDasWCIDEntry: Alg=%s, KeyLength = %d\n",
-			CipherName[CipherAlg], pKey->KeyLength));
-	DBGPRINT(RT_DEBUG_TRACE, ("Key [idx=%x] [KeyLen = %d]\n",
-			pKey->KeyIndex, pKey->KeyLength));
-	for(i=0; i<pKey->KeyLength; i++)
-		DBGPRINT_RAW(RT_DEBUG_TRACE,(" %x:", pKey->KeyMaterial[i]));
-	DBGPRINT(RT_DEBUG_TRACE,("	 \n"));
-}
-#endif // CONFIG_STA_SUPPORT //
-
-/*
-========================================================================
-Routine Description:
-    Get a received packet.
-
-Arguments:
-	pAd					device control block
-	pSaveRxD			receive descriptor information
-	*pbReschedule		need reschedule flag
-	*pRxPending			pending received packet flag
-
-Return Value:
-    the recieved packet
-
-Note:
-========================================================================
-*/
-#define RT2870_RXDMALEN_FIELD_SIZE			4
-PNDIS_PACKET GetPacketFromRxRing(
-	IN		PRTMP_ADAPTER		pAd,
-	OUT		PRT28XX_RXD_STRUC	pSaveRxD,
-	OUT		BOOLEAN				*pbReschedule,
-	IN OUT	UINT32				*pRxPending)
-{
-	PRX_CONTEXT		pRxContext;
-	PNDIS_PACKET	pSkb;
-	PUCHAR			pData;
-	ULONG			ThisFrameLen;
-	ULONG			RxBufferLength;
-	PRXWI_STRUC		pRxWI;
-
-	pRxContext = &pAd->RxContext[pAd->NextRxBulkInReadIndex];
-	if ((pRxContext->Readable == FALSE) || (pRxContext->InUse == TRUE))
-		return NULL;
-
-	RxBufferLength = pRxContext->BulkInOffset - pAd->ReadPosition;
-	if (RxBufferLength < (RT2870_RXDMALEN_FIELD_SIZE + sizeof(RXWI_STRUC) + sizeof(RXINFO_STRUC)))
-	{
-		goto label_null;
-	}
-
-	pData = &pRxContext->TransferBuffer[pAd->ReadPosition]; /* 4KB */
-	// The RXDMA field is 4 bytes, now just use the first 2 bytes. The Length including the (RXWI + MSDU + Padding)
-	ThisFrameLen = *pData + (*(pData+1)<<8);
-    if (ThisFrameLen == 0)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("BIRIdx(%d): RXDMALen is zero.[%ld], BulkInBufLen = %ld)\n",
-								pAd->NextRxBulkInReadIndex, ThisFrameLen, pRxContext->BulkInOffset));
-		goto label_null;
-	}
-	if ((ThisFrameLen&0x3) != 0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("BIRIdx(%d): RXDMALen not multiple of 4.[%ld], BulkInBufLen = %ld)\n",
-								pAd->NextRxBulkInReadIndex, ThisFrameLen, pRxContext->BulkInOffset));
-		goto label_null;
-	}
-
-	if ((ThisFrameLen + 8)> RxBufferLength)	// 8 for (RT2870_RXDMALEN_FIELD_SIZE + sizeof(RXINFO_STRUC))
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("BIRIdx(%d):FrameLen(0x%lx) outranges. BulkInLen=0x%lx, remaining RxBufLen=0x%lx, ReadPos=0x%lx\n",
-						pAd->NextRxBulkInReadIndex, ThisFrameLen, pRxContext->BulkInOffset, RxBufferLength, pAd->ReadPosition));
-
-		// error frame. finish this loop
-		goto label_null;
-	}
-
-	// skip USB frame length field
-	pData += RT2870_RXDMALEN_FIELD_SIZE;
-	pRxWI = (PRXWI_STRUC)pData;
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange(pData, TYPE_RXWI);
-#endif // RT_BIG_ENDIAN //
-	if (pRxWI->MPDUtotalByteCount > ThisFrameLen)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s():pRxWIMPDUtotalByteCount(%d) large than RxDMALen(%ld)\n",
-									__FUNCTION__, pRxWI->MPDUtotalByteCount, ThisFrameLen));
-		goto label_null;
-	}
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange(pData, TYPE_RXWI);
-#endif // RT_BIG_ENDIAN //
-
-	// allocate a rx packet
-	pSkb = dev_alloc_skb(ThisFrameLen);
-	if (pSkb == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("%s():Cannot Allocate sk buffer for this Bulk-In buffer!\n", __FUNCTION__));
-		goto label_null;
-	}
-
-	// copy the rx packet
-	memcpy(skb_put(pSkb, ThisFrameLen), pData, ThisFrameLen);
-	RTPKT_TO_OSPKT(pSkb)->dev = get_netdev_from_bssid(pAd, BSS0);
-	RTMP_SET_PACKET_SOURCE(OSPKT_TO_RTPKT(pSkb), PKTSRC_NDIS);
-
-	// copy RxD
-	*pSaveRxD = *(PRXINFO_STRUC)(pData + ThisFrameLen);
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pSaveRxD, TYPE_RXINFO);
-#endif // RT_BIG_ENDIAN //
-
-	// update next packet read position.
-	pAd->ReadPosition += (ThisFrameLen + RT2870_RXDMALEN_FIELD_SIZE + RXINFO_SIZE);	// 8 for (RT2870_RXDMALEN_FIELD_SIZE + sizeof(RXINFO_STRUC))
-
-	return pSkb;
-
-label_null:
-
-	return NULL;
-}
-
-
-/*
-========================================================================
-Routine Description:
-    Handle received packets.
-
-Arguments:
-	data				- URB information pointer
-
-Return Value:
-    None
-
-Note:
-========================================================================
-*/
-static void rx_done_tasklet(unsigned long data)
-{
-	purbb_t 			pUrb;
-	PRX_CONTEXT			pRxContext;
-	PRTMP_ADAPTER		pAd;
-	NTSTATUS			Status;
-	unsigned int		IrqFlags;
-
-	pUrb		= (purbb_t)data;
-	pRxContext	= (PRX_CONTEXT)pUrb->context;
-	pAd 		= pRxContext->pAd;
-	Status = pUrb->status;
-
-
-	RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-	pRxContext->InUse = FALSE;
-	pRxContext->IRPPending = FALSE;
-	pRxContext->BulkInOffset += pUrb->actual_length;
-	//NdisInterlockedDecrement(&pAd->PendingRx);
-	pAd->PendingRx--;
-
-	if (Status == USB_ST_NOERROR)
-	{
-		pAd->BulkInComplete++;
-		pAd->NextRxBulkInPosition = 0;
-		if (pRxContext->BulkInOffset)	// As jan's comment, it may bulk-in success but size is zero.
-		{
-			pRxContext->Readable = TRUE;
-			INC_RING_INDEX(pAd->NextRxBulkInIndex, RX_RING_SIZE);
-		}
-		RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-	}
-	else	 // STATUS_OTHER
-	{
-		pAd->BulkInCompleteFail++;
-		// Still read this packet although it may comtain wrong bytes.
-		pRxContext->Readable = FALSE;
-		RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-
-		// Parsing all packets. because after reset, the index will reset to all zero.
-		if ((!RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
-									fRTMP_ADAPTER_BULKIN_RESET |
-									fRTMP_ADAPTER_HALT_IN_PROGRESS |
-									fRTMP_ADAPTER_NIC_NOT_EXIST))))
-		{
-
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("Bulk In Failed. Status=%d, BIIdx=0x%x, BIRIdx=0x%x, actual_length= 0x%x\n",
-							Status, pAd->NextRxBulkInIndex, pAd->NextRxBulkInReadIndex, pRxContext->pUrb->actual_length));
-
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKIN_RESET);
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_IN, NULL, 0);
-		}
-	}
-
-	ASSERT((pRxContext->InUse == pRxContext->IRPPending));
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-    {
-		// If the driver is in ATE mode and Rx frame is set into here.
-		if (pAd->ContinBulkIn == TRUE)
-		{
-			RTUSBBulkReceive(pAd);
-		}
-	}
-	else
-#endif // RALINK_ATE //
-	RTUSBBulkReceive(pAd);
-
-	return;
-
-}
-
-
-static void rt2870_mgmt_dma_done_tasklet(unsigned long data)
-{
-	PRTMP_ADAPTER 	pAd;
-	PTX_CONTEXT		pMLMEContext;
-	int				index;
-	PNDIS_PACKET	pPacket;
-	purbb_t			pUrb;
-	NTSTATUS		Status;
-	unsigned long	IrqFlags;
-
-
-	pUrb			= (purbb_t)data;
-	pMLMEContext	= (PTX_CONTEXT)pUrb->context;
-	pAd 			= pMLMEContext->pAd;
-	Status			= pUrb->status;
-	index 			= pMLMEContext->SelfIdx;
-
-	ASSERT((pAd->MgmtRing.TxDmaIdx == index));
-
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[MGMTPIPEIDX], IrqFlags);
-
-
-	if (Status != USB_ST_NOERROR)
-	{
-		//Bulk-Out fail status handle
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("Bulk Out MLME Failed, Status=%d!\n", Status));
-			// TODO: How to handle about the MLMEBulkOut failed issue. Need to resend the mgmt pkt?
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			pAd->bulkResetPipeid = (MGMTPIPEIDX | BULKOUT_MGMT_RESET_FLAG);
-		}
-	}
-
-	pAd->BulkOutPending[MGMTPIPEIDX] = FALSE;
-	RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[MGMTPIPEIDX], IrqFlags);
-
-	RTMP_IRQ_LOCK(&pAd->MLMEBulkOutLock, IrqFlags);
-	// Reset MLME context flags
-	pMLMEContext->IRPPending = FALSE;
-	pMLMEContext->InUse = FALSE;
-	pMLMEContext->bWaitingBulkOut = FALSE;
-	pMLMEContext->BulkOutSize = 0;
-
-	pPacket = pAd->MgmtRing.Cell[index].pNdisPacket;
-	pAd->MgmtRing.Cell[index].pNdisPacket = NULL;
-
-	// Increase MgmtRing Index
-	INC_RING_INDEX(pAd->MgmtRing.TxDmaIdx, MGMT_RING_SIZE);
-	pAd->MgmtRing.TxSwFreeIdx++;
-	RTMP_IRQ_UNLOCK(&pAd->MLMEBulkOutLock, IrqFlags);
-
-	// No-matter success or fail, we free the mgmt packet.
-	if (pPacket)
-		RTMPFreeNdisPacket(pAd, pPacket);
-
-	if ((RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
-								fRTMP_ADAPTER_HALT_IN_PROGRESS |
-								fRTMP_ADAPTER_NIC_NOT_EXIST))))
-	{
-		// do nothing and return directly.
-	}
-	else
-	{
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET) &&
-			((pAd->bulkResetPipeid & BULKOUT_MGMT_RESET_FLAG) == BULKOUT_MGMT_RESET_FLAG))
-		{	// For Mgmt Bulk-Out failed, ignore it now.
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-		else
-		{
-
-			// Always call Bulk routine, even reset bulk.
-			// The protectioon of rest bulk should be in BulkOut routine
-			if (pAd->MgmtRing.TxSwFreeIdx < MGMT_RING_SIZE /* pMLMEContext->bWaitingBulkOut == TRUE */)
-			{
-				RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_MLME);
-			}
-				RTUSBKickBulkOut(pAd);
-			}
-		}
-
-}
-
-
-static void rt2870_hcca_dma_done_tasklet(unsigned long data)
-{
-	PRTMP_ADAPTER		pAd;
-	PHT_TX_CONTEXT		pHTTXContext;
-	UCHAR				BulkOutPipeId = 4;
-	purbb_t				pUrb;
-
-
-	pUrb			= (purbb_t)data;
-	pHTTXContext	= (PHT_TX_CONTEXT)pUrb->context;
-	pAd				= pHTTXContext->pAd;
-
-	rt2870_dataout_complete_tasklet((unsigned long)pUrb);
-
-	if ((RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
-								fRTMP_ADAPTER_HALT_IN_PROGRESS |
-								fRTMP_ADAPTER_NIC_NOT_EXIST))))
-	{
-		// do nothing and return directly.
-	}
-	else
-	{
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET))
-		{
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-		else
-		{	pHTTXContext = &pAd->TxContext[BulkOutPipeId];
-			if ((pAd->TxSwQueue[BulkOutPipeId].Number > 0) &&
-				/*((pHTTXContext->CurWritePosition > (pHTTXContext->NextBulkOutPosition + 0x6000)) || (pHTTXContext->NextBulkOutPosition > pHTTXContext->CurWritePosition + 0x6000)) && */
-				(pAd->DeQueueRunning[BulkOutPipeId] == FALSE) &&
-				(pHTTXContext->bCurWriting == FALSE))
-			{
-				RTMPDeQueuePacket(pAd, FALSE, BulkOutPipeId, MAX_TX_PROCESS);
-			}
-
-			RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL<<4);
-			RTUSBKickBulkOut(pAd);
-		}
-	}
-
-
-		return;
-}
-
-
-static void rt2870_ac3_dma_done_tasklet(unsigned long data)
-{
-	PRTMP_ADAPTER		pAd;
-	PHT_TX_CONTEXT		pHTTXContext;
-	UCHAR				BulkOutPipeId = 3;
-	purbb_t				pUrb;
-
-
-	pUrb			= (purbb_t)data;
-	pHTTXContext	= (PHT_TX_CONTEXT)pUrb->context;
-	pAd				= pHTTXContext->pAd;
-
-	rt2870_dataout_complete_tasklet((unsigned long)pUrb);
-
-	if ((RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
-								fRTMP_ADAPTER_HALT_IN_PROGRESS |
-								fRTMP_ADAPTER_NIC_NOT_EXIST))))
-	{
-		// do nothing and return directly.
-	}
-	else
-	{
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET))
-		{
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-		else
-		{	pHTTXContext = &pAd->TxContext[BulkOutPipeId];
-			if ((pAd->TxSwQueue[BulkOutPipeId].Number > 0) &&
-				/*((pHTTXContext->CurWritePosition > (pHTTXContext->NextBulkOutPosition + 0x6000)) || (pHTTXContext->NextBulkOutPosition > pHTTXContext->CurWritePosition + 0x6000)) && */
-				(pAd->DeQueueRunning[BulkOutPipeId] == FALSE) &&
-				(pHTTXContext->bCurWriting == FALSE))
-			{
-				RTMPDeQueuePacket(pAd, FALSE, BulkOutPipeId, MAX_TX_PROCESS);
-			}
-
-			RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL<<3);
-			RTUSBKickBulkOut(pAd);
-		}
-	}
-
-
-		return;
-}
-
-
-static void rt2870_ac2_dma_done_tasklet(unsigned long data)
-{
-	PRTMP_ADAPTER		pAd;
-	PHT_TX_CONTEXT		pHTTXContext;
-	UCHAR				BulkOutPipeId = 2;
-	purbb_t				pUrb;
-
-
-	pUrb			= (purbb_t)data;
-	pHTTXContext	= (PHT_TX_CONTEXT)pUrb->context;
-	pAd				= pHTTXContext->pAd;
-
-	rt2870_dataout_complete_tasklet((unsigned long)pUrb);
-
-	if ((RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
-								fRTMP_ADAPTER_HALT_IN_PROGRESS |
-								fRTMP_ADAPTER_NIC_NOT_EXIST))))
-	{
-		// do nothing and return directly.
-	}
-	else
-	{
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET))
-		{
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-		else
-		{	pHTTXContext = &pAd->TxContext[BulkOutPipeId];
-			if ((pAd->TxSwQueue[BulkOutPipeId].Number > 0) &&
-				/*((pHTTXContext->CurWritePosition > (pHTTXContext->NextBulkOutPosition + 0x6000)) || (pHTTXContext->NextBulkOutPosition > pHTTXContext->CurWritePosition + 0x6000)) && */
-				(pAd->DeQueueRunning[BulkOutPipeId] == FALSE) &&
-				(pHTTXContext->bCurWriting == FALSE))
-			{
-				RTMPDeQueuePacket(pAd, FALSE, BulkOutPipeId, MAX_TX_PROCESS);
-			}
-
-			RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL<<2);
-			RTUSBKickBulkOut(pAd);
-		}
-	}
-
-		return;
-}
-
-
-static void rt2870_ac1_dma_done_tasklet(unsigned long data)
-{
-	PRTMP_ADAPTER		pAd;
-	PHT_TX_CONTEXT		pHTTXContext;
-	UCHAR				BulkOutPipeId = 1;
-	purbb_t				pUrb;
-
-
-	pUrb			= (purbb_t)data;
-	pHTTXContext	= (PHT_TX_CONTEXT)pUrb->context;
-	pAd				= pHTTXContext->pAd;
-
-	rt2870_dataout_complete_tasklet((unsigned long)pUrb);
-
-	if ((RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
-								fRTMP_ADAPTER_HALT_IN_PROGRESS |
-								fRTMP_ADAPTER_NIC_NOT_EXIST))))
-	{
-		// do nothing and return directly.
-	}
-	else
-	{
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET))
-		{
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-		else
-		{	pHTTXContext = &pAd->TxContext[BulkOutPipeId];
-			if ((pAd->TxSwQueue[BulkOutPipeId].Number > 0) &&
-				/*((pHTTXContext->CurWritePosition > (pHTTXContext->NextBulkOutPosition + 0x6000)) || (pHTTXContext->NextBulkOutPosition > pHTTXContext->CurWritePosition + 0x6000)) && */
-				(pAd->DeQueueRunning[BulkOutPipeId] == FALSE) &&
-				(pHTTXContext->bCurWriting == FALSE))
-			{
-				RTMPDeQueuePacket(pAd, FALSE, BulkOutPipeId, MAX_TX_PROCESS);
-			}
-
-			RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL<<1);
-			RTUSBKickBulkOut(pAd);
-		}
-	}
-
-
-	return;
-}
-
-
-static void rt2870_ac0_dma_done_tasklet(unsigned long data)
-{
-	PRTMP_ADAPTER		pAd;
-	PHT_TX_CONTEXT		pHTTXContext;
-	UCHAR				BulkOutPipeId = 0;
-	purbb_t				pUrb;
-
-
-	pUrb			= (purbb_t)data;
-	pHTTXContext	= (PHT_TX_CONTEXT)pUrb->context;
-	pAd				= pHTTXContext->pAd;
-
-	rt2870_dataout_complete_tasklet((unsigned long)pUrb);
-
-	if ((RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
-								fRTMP_ADAPTER_HALT_IN_PROGRESS |
-								fRTMP_ADAPTER_NIC_NOT_EXIST))))
-	{
-		// do nothing and return directly.
-	}
-	else
-	{
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET))
-		{
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-		else
-		{	pHTTXContext = &pAd->TxContext[BulkOutPipeId];
-			if ((pAd->TxSwQueue[BulkOutPipeId].Number > 0) &&
-				/*  ((pHTTXContext->CurWritePosition > (pHTTXContext->NextBulkOutPosition + 0x6000)) || (pHTTXContext->NextBulkOutPosition > pHTTXContext->CurWritePosition + 0x6000)) && */
-				(pAd->DeQueueRunning[BulkOutPipeId] == FALSE) &&
-				(pHTTXContext->bCurWriting == FALSE))
-			{
-				RTMPDeQueuePacket(pAd, FALSE, BulkOutPipeId, MAX_TX_PROCESS);
-			}
-
-			RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL);
-			RTUSBKickBulkOut(pAd);
-		}
-	}
-
-
-	return;
-
-}
-
-
-static void rt2870_null_frame_complete_tasklet(unsigned long data)
-{
-	PRTMP_ADAPTER	pAd;
-	PTX_CONTEXT		pNullContext;
-	purbb_t			pUrb;
-	NTSTATUS		Status;
-	unsigned long	irqFlag;
-
-
-	pUrb			= (purbb_t)data;
-	pNullContext	= (PTX_CONTEXT)pUrb->context;
-	pAd 			= pNullContext->pAd;
-	Status 			= pUrb->status;
-
-	// Reset Null frame context flags
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[0], irqFlag);
-	pNullContext->IRPPending 	= FALSE;
-	pNullContext->InUse 		= FALSE;
-	pAd->BulkOutPending[0] = FALSE;
-	pAd->watchDogTxPendingCnt[0] = 0;
-
-	if (Status == USB_ST_NOERROR)
-	{
-		RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], irqFlag);
-
-		RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-	else	// STATUS_OTHER
-	{
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("Bulk Out Null Frame Failed, ReasonCode=%d!\n", Status));
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			pAd->bulkResetPipeid = (MGMTPIPEIDX | BULKOUT_MGMT_RESET_FLAG);
-			RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], irqFlag);
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-		else
-		{
-			RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], irqFlag);
-		}
-	}
-
-	// Always call Bulk routine, even reset bulk.
-	// The protectioon of rest bulk should be in BulkOut routine
-	RTUSBKickBulkOut(pAd);
-
-}
-
-
-static void rt2870_rts_frame_complete_tasklet(unsigned long data)
-{
-	PRTMP_ADAPTER	pAd;
-	PTX_CONTEXT		pRTSContext;
-	purbb_t			pUrb;
-	NTSTATUS		Status;
-	unsigned long	irqFlag;
-
-
-	pUrb		= (purbb_t)data;
-	pRTSContext	= (PTX_CONTEXT)pUrb->context;
-	pAd			= pRTSContext->pAd;
-	Status		= pUrb->status;
-
-	// Reset RTS frame context flags
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[0], irqFlag);
-	pRTSContext->IRPPending = FALSE;
-	pRTSContext->InUse		= FALSE;
-
-	if (Status == USB_ST_NOERROR)
-	{
-		RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], irqFlag);
-		RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-	else	// STATUS_OTHER
-	{
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("Bulk Out RTS Frame Failed\n"));
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			pAd->bulkResetPipeid = (MGMTPIPEIDX | BULKOUT_MGMT_RESET_FLAG);
-			RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], irqFlag);
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-		else
-		{
-			RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], irqFlag);
-		}
-	}
-
-	RTMP_SEM_LOCK(&pAd->BulkOutLock[pRTSContext->BulkOutPipeId]);
-	pAd->BulkOutPending[pRTSContext->BulkOutPipeId] = FALSE;
-	RTMP_SEM_UNLOCK(&pAd->BulkOutLock[pRTSContext->BulkOutPipeId]);
-
-	// Always call Bulk routine, even reset bulk.
-	// The protectioon of rest bulk should be in BulkOut routine
-	RTUSBKickBulkOut(pAd);
-
-}
-
-
-static void rt2870_pspoll_frame_complete_tasklet(unsigned long data)
-{
-	PRTMP_ADAPTER	pAd;
-	PTX_CONTEXT		pPsPollContext;
-	purbb_t			pUrb;
-	NTSTATUS		Status;
-
-
-	pUrb			= (purbb_t)data;
-	pPsPollContext	= (PTX_CONTEXT)pUrb->context;
-	pAd				= pPsPollContext->pAd;
-	Status			= pUrb->status;
-
-	// Reset PsPoll context flags
-	pPsPollContext->IRPPending	= FALSE;
-	pPsPollContext->InUse		= FALSE;
-	pAd->watchDogTxPendingCnt[0] = 0;
-
-	if (Status == USB_ST_NOERROR)
-	{
-		RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-	else // STATUS_OTHER
-	{
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			DBGPRINT_RAW(RT_DEBUG_ERROR, ("Bulk Out PSPoll Failed\n"));
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			pAd->bulkResetPipeid = (MGMTPIPEIDX | BULKOUT_MGMT_RESET_FLAG);
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-		}
-	}
-
-	RTMP_SEM_LOCK(&pAd->BulkOutLock[0]);
-	pAd->BulkOutPending[0] = FALSE;
-	RTMP_SEM_UNLOCK(&pAd->BulkOutLock[0]);
-
-	// Always call Bulk routine, even reset bulk.
-	// The protectioon of rest bulk should be in BulkOut routine
-	RTUSBKickBulkOut(pAd);
-
-}
-
-
-static void rt2870_dataout_complete_tasklet(unsigned long data)
-{
-	PRTMP_ADAPTER		pAd;
-	purbb_t				pUrb;
-	POS_COOKIE			pObj;
-	PHT_TX_CONTEXT		pHTTXContext;
-	UCHAR				BulkOutPipeId;
-	NTSTATUS			Status;
-	unsigned long		IrqFlags;
-
-
-	pUrb			= (purbb_t)data;
-	pHTTXContext	= (PHT_TX_CONTEXT)pUrb->context;
-	pAd				= pHTTXContext->pAd;
-	pObj 			= (POS_COOKIE) pAd->OS_Cookie;
-	Status			= pUrb->status;
-
-	// Store BulkOut PipeId
-	BulkOutPipeId = pHTTXContext->BulkOutPipeId;
-	pAd->BulkOutDataOneSecCount++;
-
-	//DBGPRINT(RT_DEBUG_LOUD, ("Done-B(%d):I=0x%lx, CWPos=%ld, NBPos=%ld, ENBPos=%ld, bCopy=%d!\n", BulkOutPipeId, in_interrupt(), pHTTXContext->CurWritePosition,
-	//		pHTTXContext->NextBulkOutPosition, pHTTXContext->ENextBulkOutPosition, pHTTXContext->bCopySavePad));
-
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-	pAd->BulkOutPending[BulkOutPipeId] = FALSE;
-	pHTTXContext->IRPPending = FALSE;
-	pAd->watchDogTxPendingCnt[BulkOutPipeId] = 0;
-
-	if (Status == USB_ST_NOERROR)
-	{
-		pAd->BulkOutComplete++;
-
-		RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-
-		pAd->Counters8023.GoodTransmits++;
-		//RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-		FREE_HTTX_RING(pAd, BulkOutPipeId, pHTTXContext);
-		//RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-
-
-	}
-	else	// STATUS_OTHER
-	{
-		PUCHAR	pBuf;
-
-		pAd->BulkOutCompleteOther++;
-
-		pBuf = &pHTTXContext->TransferBuffer->field.WirelessPacket[pHTTXContext->NextBulkOutPosition];
-
-		if (!RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
-									fRTMP_ADAPTER_HALT_IN_PROGRESS |
-									fRTMP_ADAPTER_NIC_NOT_EXIST |
-									fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			pAd->bulkResetPipeid = BulkOutPipeId;
-			pAd->bulkResetReq[BulkOutPipeId] = pAd->BulkOutReq;
-		}
-		RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("BulkOutDataPacket failed: ReasonCode=%d!\n", Status));
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("\t>>BulkOut Req=0x%lx, Complete=0x%lx, Other=0x%lx\n", pAd->BulkOutReq, pAd->BulkOutComplete, pAd->BulkOutCompleteOther));
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("\t>>BulkOut Header:%x %x %x %x %x %x %x %x\n", pBuf[0], pBuf[1], pBuf[2], pBuf[3], pBuf[4], pBuf[5], pBuf[6], pBuf[7]));
-		//DBGPRINT_RAW(RT_DEBUG_ERROR, (">>BulkOutCompleteCancel=0x%x, BulkOutCompleteOther=0x%x\n", pAd->BulkOutCompleteCancel, pAd->BulkOutCompleteOther));
-
-	}
-
-	//
-	// bInUse = TRUE, means some process are filling TX data, after that must turn on bWaitingBulkOut
-	// bWaitingBulkOut = TRUE, means the TX data are waiting for bulk out.
-	//
-	//RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-	if ((pHTTXContext->ENextBulkOutPosition != pHTTXContext->CurWritePosition) &&
-		(pHTTXContext->ENextBulkOutPosition != (pHTTXContext->CurWritePosition+8)) &&
-		!RTUSB_TEST_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_FRAG << BulkOutPipeId)))
-	{
-		// Indicate There is data avaliable
-		RTUSB_SET_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << BulkOutPipeId));
-	}
-	//RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-
-	// Always call Bulk routine, even reset bulk.
-	// The protection of rest bulk should be in BulkOut routine
-	RTUSBKickBulkOut(pAd);
-}
-
-/* End of 2870_rtmp_init.c */
+#include "../../rt2870/common/2870_rtmp_init.c"
diff --git a/drivers/staging/rt3070/common/action.c b/drivers/staging/rt3070/common/action.c
index b8ae536..035fd80 100644
--- a/drivers/staging/rt3070/common/action.c
+++ b/drivers/staging/rt3070/common/action.c
@@ -1,1038 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-	action.c
-
-    Abstract:
-    Handle association related requests either from WSTA or from local MLME
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-	Jan Lee		2006	  	created for rt2860
- */
-
-#include "../rt_config.h"
-#include "../action.h"
-
-
-static VOID ReservedAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-/*
-    ==========================================================================
-    Description:
-        association state machine init, including state transition and timer init
-    Parameters:
-        S - pointer to the association state machine
-    Note:
-        The state machine looks like the following
-
-                                    ASSOC_IDLE
-        MT2_MLME_DISASSOC_REQ    mlme_disassoc_req_action
-        MT2_PEER_DISASSOC_REQ    peer_disassoc_action
-        MT2_PEER_ASSOC_REQ       drop
-        MT2_PEER_REASSOC_REQ     drop
-        MT2_CLS3ERR              cls3err_action
-    ==========================================================================
- */
-VOID ActionStateMachineInit(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  STATE_MACHINE *S,
-    OUT STATE_MACHINE_FUNC Trans[])
-{
-	StateMachineInit(S, (STATE_MACHINE_FUNC *)Trans, MAX_ACT_STATE, MAX_ACT_MSG, (STATE_MACHINE_FUNC)Drop, ACT_IDLE, ACT_MACHINE_BASE);
-
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_SPECTRUM_CATE, (STATE_MACHINE_FUNC)PeerSpectrumAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_QOS_CATE, (STATE_MACHINE_FUNC)PeerQOSAction);
-
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_DLS_CATE, (STATE_MACHINE_FUNC)ReservedAction);
-#ifdef QOS_DLS_SUPPORT
-		StateMachineSetAction(S, ACT_IDLE, MT2_PEER_DLS_CATE, (STATE_MACHINE_FUNC)PeerDLSAction);
-#endif // QOS_DLS_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_BA_CATE, (STATE_MACHINE_FUNC)PeerBAAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_HT_CATE, (STATE_MACHINE_FUNC)PeerHTAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_ADD_BA_CATE, (STATE_MACHINE_FUNC)MlmeADDBAAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_ORI_DELBA_CATE, (STATE_MACHINE_FUNC)MlmeDELBAAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_REC_DELBA_CATE, (STATE_MACHINE_FUNC)MlmeDELBAAction);
-#endif // DOT11_N_SUPPORT //
-
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_PUBLIC_CATE, (STATE_MACHINE_FUNC)PeerPublicAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_PEER_RM_CATE, (STATE_MACHINE_FUNC)PeerRMAction);
-
-	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_QOS_CATE, (STATE_MACHINE_FUNC)MlmeQOSAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_MLME_DLS_CATE, (STATE_MACHINE_FUNC)MlmeDLSAction);
-	StateMachineSetAction(S, ACT_IDLE, MT2_ACT_INVALID, (STATE_MACHINE_FUNC)MlmeInvalidAction);
-}
-
-#ifdef DOT11_N_SUPPORT
-VOID MlmeADDBAAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-
-{
-	MLME_ADDBA_REQ_STRUCT *pInfo;
-	UCHAR           Addr[6];
-	PUCHAR         pOutBuffer = NULL;
-	NDIS_STATUS     NStatus;
-	ULONG		Idx;
-	FRAME_ADDBA_REQ  Frame;
-	ULONG		FrameLen;
-	BA_ORI_ENTRY			*pBAEntry = NULL;
-
-	pInfo = (MLME_ADDBA_REQ_STRUCT *)Elem->Msg;
-	NdisZeroMemory(&Frame, sizeof(FRAME_ADDBA_REQ));
-
-	if(MlmeAddBAReqSanity(pAd, Elem->Msg, Elem->MsgLen, Addr))
-	{
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-		if(NStatus != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("BA - MlmeADDBAAction() allocate memory failed \n"));
-			return;
-		}
-		// 1. find entry
-		Idx = pAd->MacTab.Content[pInfo->Wcid].BAOriWcidArray[pInfo->TID];
-		if (Idx == 0)
-		{
-			MlmeFreeMemory(pAd, pOutBuffer);
-			DBGPRINT(RT_DEBUG_ERROR,("BA - MlmeADDBAAction() can't find BAOriEntry \n"));
-			return;
-		}
-		else
-		{
-			pBAEntry =&pAd->BATable.BAOriEntry[Idx];
-		}
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			if (ADHOC_ON(pAd))
-				ActHeaderInit(pAd, &Frame.Hdr, pInfo->pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-			else
-				ActHeaderInit(pAd, &Frame.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pInfo->pAddr);
-
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		Frame.Category = CATEGORY_BA;
-		Frame.Action = ADDBA_REQ;
-		Frame.BaParm.AMSDUSupported = 0;
-		Frame.BaParm.BAPolicy = IMMED_BA;
-		Frame.BaParm.TID = pInfo->TID;
-		Frame.BaParm.BufSize = pInfo->BaBufSize;
-		Frame.Token = pInfo->Token;
-		Frame.TimeOutValue = pInfo->TimeOutValue;
-		Frame.BaStartSeq.field.FragNum = 0;
-		Frame.BaStartSeq.field.StartSeq = pAd->MacTab.Content[pInfo->Wcid].TxSeq[pInfo->TID];
-
-		*(USHORT *)(&Frame.BaParm) = cpu2le16(*(USHORT *)(&Frame.BaParm));
-		Frame.TimeOutValue = cpu2le16(Frame.TimeOutValue);
-		Frame.BaStartSeq.word = cpu2le16(Frame.BaStartSeq.word);
-
-		MakeOutgoingFrame(pOutBuffer,		   &FrameLen,
-		              sizeof(FRAME_ADDBA_REQ), &Frame,
-		              END_OF_ARGS);
-		MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-		//MiniportDataMMRequest(pAd, MapUserPriorityToAccessCategory[pInfo->TID], pOutBuffer, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("BA - Send ADDBA request. StartSeq = %x,  FrameLen = %ld. BufSize = %d\n", Frame.BaStartSeq.field.StartSeq, FrameLen, Frame.BaParm.BufSize));
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-        send DELBA and delete BaEntry if any
-    Parametrs:
-        Elem - MLME message MLME_DELBA_REQ_STRUCT
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeDELBAAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	MLME_DELBA_REQ_STRUCT *pInfo;
-	PUCHAR         pOutBuffer = NULL;
-	PUCHAR		   pOutBuffer2 = NULL;
-	NDIS_STATUS     NStatus;
-	ULONG		Idx;
-	FRAME_DELBA_REQ  Frame;
-	ULONG		FrameLen;
-	FRAME_BAR	FrameBar;
-
-	pInfo = (MLME_DELBA_REQ_STRUCT *)Elem->Msg;
-	// must send back DELBA
-	NdisZeroMemory(&Frame, sizeof(FRAME_DELBA_REQ));
-	DBGPRINT(RT_DEBUG_TRACE, ("==> MlmeDELBAAction(), Initiator(%d) \n", pInfo->Initiator));
-
-	if(MlmeDelBAReqSanity(pAd, Elem->Msg, Elem->MsgLen))
-	{
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-		if(NStatus != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_ERROR,("BA - MlmeDELBAAction() allocate memory failed 1. \n"));
-			return;
-		}
-
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer2);  //Get an unused nonpaged memory
-		if(NStatus != NDIS_STATUS_SUCCESS)
-		{
-			MlmeFreeMemory(pAd, pOutBuffer);
-			DBGPRINT(RT_DEBUG_ERROR, ("BA - MlmeDELBAAction() allocate memory failed 2. \n"));
-			return;
-		}
-
-		// SEND BAR (Send BAR to refresh peer reordering buffer.)
-		Idx = pAd->MacTab.Content[pInfo->Wcid].BAOriWcidArray[pInfo->TID];
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			BarHeaderInit(pAd, &FrameBar, pAd->MacTab.Content[pInfo->Wcid].Addr, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
-
-		FrameBar.StartingSeq.field.FragNum = 0; // make sure sequence not clear in DEL funciton.
-		FrameBar.StartingSeq.field.StartSeq = pAd->MacTab.Content[pInfo->Wcid].TxSeq[pInfo->TID]; // make sure sequence not clear in DEL funciton.
-		FrameBar.BarControl.TID = pInfo->TID; // make sure sequence not clear in DEL funciton.
-		FrameBar.BarControl.ACKPolicy = IMMED_BA; // make sure sequence not clear in DEL funciton.
-		FrameBar.BarControl.Compressed = 1; // make sure sequence not clear in DEL funciton.
-		FrameBar.BarControl.MTID = 0; // make sure sequence not clear in DEL funciton.
-
-		MakeOutgoingFrame(pOutBuffer2,				&FrameLen,
-					  sizeof(FRAME_BAR),	  &FrameBar,
-					  END_OF_ARGS);
-		MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer2, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer2);
-		DBGPRINT(RT_DEBUG_TRACE,("BA - MlmeDELBAAction() . Send BAR to refresh peer reordering buffer \n"));
-
-		// SEND DELBA FRAME
-		FrameLen = 0;
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			if (ADHOC_ON(pAd))
-				ActHeaderInit(pAd, &Frame.Hdr, pAd->MacTab.Content[pInfo->Wcid].Addr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-			else
-				ActHeaderInit(pAd, &Frame.Hdr,  pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->MacTab.Content[pInfo->Wcid].Addr);
-		}
-#endif // CONFIG_STA_SUPPORT //
-		Frame.Category = CATEGORY_BA;
-		Frame.Action = DELBA;
-		Frame.DelbaParm.Initiator = pInfo->Initiator;
-		Frame.DelbaParm.TID = pInfo->TID;
-		Frame.ReasonCode = 39; // Time Out
-		*(USHORT *)(&Frame.DelbaParm) = cpu2le16(*(USHORT *)(&Frame.DelbaParm));
-		Frame.ReasonCode = cpu2le16(Frame.ReasonCode);
-
-		MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-		              sizeof(FRAME_DELBA_REQ),    &Frame,
-		              END_OF_ARGS);
-		MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer);
-		DBGPRINT(RT_DEBUG_TRACE, ("BA - MlmeDELBAAction() . 3 DELBA sent. Initiator(%d)\n", pInfo->Initiator));
-    	}
-}
-#endif // DOT11_N_SUPPORT //
-
-VOID MlmeQOSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-}
-
-VOID MlmeDLSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-}
-
-VOID MlmeInvalidAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	//PUCHAR		   pOutBuffer = NULL;
-	//Return the receiving frame except the MSB of category filed set to 1.  7.3.1.11
-}
-
-VOID PeerQOSAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-}
-
-#ifdef QOS_DLS_SUPPORT
-VOID PeerDLSAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-
-	switch(Action)
-	{
-		case ACTION_DLS_REQUEST:
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			PeerDlsReqAction(pAd, Elem);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-
-		case ACTION_DLS_RESPONSE:
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			PeerDlsRspAction(pAd, Elem);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-
-		case ACTION_DLS_TEARDOWN:
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			PeerDlsTearDownAction(pAd, Elem);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-	}
-}
-#endif // QOS_DLS_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-VOID PeerBAAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-
-	switch(Action)
-	{
-		case ADDBA_REQ:
-			PeerAddBAReqAction(pAd,Elem);
-			break;
-		case ADDBA_RESP:
-			PeerAddBARspAction(pAd,Elem);
-			break;
-		case DELBA:
-			PeerDelBAAction(pAd,Elem);
-			break;
-	}
-}
-
-
-#ifdef DOT11N_DRAFT3
-
-#ifdef CONFIG_STA_SUPPORT
-VOID StaPublicAction(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR Bss2040Coexist)
-{
-	BSS_2040_COEXIST_IE		BssCoexist;
-	MLME_SCAN_REQ_STRUCT			ScanReq;
-
-	BssCoexist.word = Bss2040Coexist;
-	// AP asks Station to return a 20/40 BSS Coexistence mgmt frame.  So we first starts a scan, then send back 20/40 BSS Coexistence mgmt frame
-	if ((BssCoexist.field.InfoReq == 1) && (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SCAN_2040)))
-	{
-		// Clear record first.  After scan , will update those bit and send back to transmiter.
-		pAd->CommonCfg.BSSCoexist2040.field.InfoReq = 1;
-		pAd->CommonCfg.BSSCoexist2040.field.Intolerant40 = 0;
-		pAd->CommonCfg.BSSCoexist2040.field.BSS20WidthReq = 0;
-		// Fill out stuff for scan request
-		ScanParmFill(pAd, &ScanReq, ZeroSsid, 0, BSS_ANY, SCAN_2040_BSS_COEXIST);
-		MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-	}
-}
-
-
-/*
-Description : Build Intolerant Channel Rerpot from Trigger event table.
-return : how many bytes copied.
-*/
-ULONG BuildIntolerantChannelRep(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    PUCHAR  pDest)
-{
-	ULONG			FrameLen = 0;
-	ULONG			ReadOffset = 0;
-	UCHAR			i;
-	UCHAR			LastRegClass = 0xff;
-	PUCHAR			pLen;
-
-	for ( i = 0;i < MAX_TRIGGER_EVENT;i++)
-	{
-		if (pAd->CommonCfg.TriggerEventTab.EventA[i].bValid == TRUE)
-		{
-			if (pAd->CommonCfg.TriggerEventTab.EventA[i].RegClass == LastRegClass)
-			{
-				*(pDest + ReadOffset) = (UCHAR)pAd->CommonCfg.TriggerEventTab.EventA[i].Channel;
-				*pLen++;
-				ReadOffset++;
-				FrameLen++;
-			}
-			else
-			{
-				*(pDest + ReadOffset) = IE_2040_BSS_INTOLERANT_REPORT;  // IE
-				*(pDest + ReadOffset + 1) = 2;	// Len = RegClass byte + channel byte.
-				pLen = pDest + ReadOffset + 1;
-				LastRegClass = pAd->CommonCfg.TriggerEventTab.EventA[i].RegClass;
-				*(pDest + ReadOffset + 2) = LastRegClass;	// Len = RegClass byte + channel byte.
-				*(pDest + ReadOffset + 3) = (UCHAR)pAd->CommonCfg.TriggerEventTab.EventA[i].Channel;
-				FrameLen += 4;
-				ReadOffset += 4;
-			}
-
-		}
-	}
-	return FrameLen;
-}
-
-
-/*
-Description : Send 20/40 BSS Coexistence Action frame If one trigger event is triggered.
-*/
-VOID Send2040CoexistAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS 	NStatus;
-	FRAME_ACTION_HDR	Frame;
-	ULONG			FrameLen;
-	ULONG			IntolerantChaRepLen;
-
-	IntolerantChaRepLen = 0;
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("ACT - Send2040CoexistAction() allocate memory failed \n"));
-		return;
-	}
-	ActHeaderInit(pAd, &Frame.Hdr, pAd->MacTab.Content[Wcid].Addr, pAd->CommonCfg.Bssid);
-	Frame.Category = CATEGORY_PUBLIC;
-	Frame.Action = ACTION_BSS_2040_COEXIST;
-
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-				  sizeof(FRAME_ACTION_HDR),	  &Frame,
-				  END_OF_ARGS);
-
-	*(pOutBuffer + FrameLen) = pAd->CommonCfg.BSSCoexist2040.word;
-	FrameLen++;
-
-	if (bAddIntolerantCha == TRUE)
-		IntolerantChaRepLen = BuildIntolerantChannelRep(pAd, pOutBuffer + FrameLen);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen + IntolerantChaRepLen);
-	DBGPRINT(RT_DEBUG_ERROR,("ACT - Send2040CoexistAction( BSSCoexist2040 = 0x%x )  \n", pAd->CommonCfg.BSSCoexist2040.word));
-
-}
-
-
-/*
-	==========================================================================
-	Description:
-	After scan, Update 20/40 BSS Coexistence IE and send out.
-	According to 802.11n D3.03 11.14.10
-
-	Parameters:
-	==========================================================================
- */
-VOID Update2040CoexistFrameAndNotify(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha)
-{
-	BSS_2040_COEXIST_IE	OldValue;
-
-	OldValue.word = pAd->CommonCfg.BSSCoexist2040.word;
-	if ((pAd->CommonCfg.TriggerEventTab.EventANo > 0) || (pAd->CommonCfg.TriggerEventTab.EventBCountDown > 0))
-		pAd->CommonCfg.BSSCoexist2040.field.BSS20WidthReq = 1;
-
-	// Need to check !!!!
-	// How STA will set Intolerant40 if implementation dependent. Now we don't set this bit first.!!!!!
-	// So Only check BSS20WidthReq change.
-	if (OldValue.field.BSS20WidthReq != pAd->CommonCfg.BSSCoexist2040.field.BSS20WidthReq)
-	{
-		Send2040CoexistAction(pAd, Wcid, bAddIntolerantCha);
-	}
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-BOOLEAN ChannelSwitchSanityCheck(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  NewChannel,
-	IN    UCHAR  Secondary)
-{
-	UCHAR		i;
-
-	if (Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return FALSE;
-
-	if ((NewChannel > 7) && (Secondary == 1))
-		return FALSE;
-
-	if ((NewChannel < 5) && (Secondary == 3))
-		return FALSE;
-
-	// 0. Check if new channel is in the channellist.
-	for (i = 0;i < pAd->ChannelListNum;i++)
-	{
-		if (pAd->ChannelList[i].Channel == NewChannel)
-		{
-			break;
-		}
-	}
-
-	if (i == pAd->ChannelListNum)
-		return FALSE;
-
-	return TRUE;
-}
-
-
-VOID ChannelSwitchAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  NewChannel,
-	IN    UCHAR  Secondary)
-{
-	UCHAR		BBPValue = 0;
-	ULONG		MACValue;
-
-	DBGPRINT(RT_DEBUG_TRACE,("SPECTRUM - ChannelSwitchAction(NewChannel = %d , Secondary = %d)  \n", NewChannel, Secondary));
-
-	if (ChannelSwitchSanityCheck(pAd, Wcid, NewChannel, Secondary) == FALSE)
-		return;
-
-	// 1.  Switches to BW = 20.
-	if (Secondary == 0)
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-		BBPValue&= (~0x18);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-		if (pAd->MACVersion == 0x28600100)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x16);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x08);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x11);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
-		}
-		pAd->CommonCfg.BBPCurrentBW = BW_20;
-		pAd->CommonCfg.Channel = NewChannel;
-		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.Channel,FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-		pAd->MacTab.Content[Wcid].HTPhyMode.field.BW = 0;
-		DBGPRINT(RT_DEBUG_TRACE, ("!!!20MHz   !!! \n" ));
-	}
-	// 1.  Switches to BW = 40 And Station supports BW = 40.
-	else if (((Secondary == 1) || (Secondary == 3)) && (pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth == 1))
-	{
-		pAd->CommonCfg.Channel = NewChannel;
-
-		if (Secondary == 1)
-		{
-			// Secondary above.
-			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel + 2;
-			RTMP_IO_READ32(pAd, TX_BAND_CFG, &MACValue);
-			MACValue &= 0xfe;
-			RTMP_IO_WRITE32(pAd, TX_BAND_CFG, MACValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue&= (~0x18);
-			BBPValue|= (0x10);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPValue);
-			BBPValue&= (~0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPValue);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!!40MHz Lower LINK UP !!! Control Channel at Below. Central = %d \n", pAd->CommonCfg.CentralChannel ));
-		}
-		else
-		{
-			// Secondary below.
-			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel - 2;
-			RTMP_IO_READ32(pAd, TX_BAND_CFG, &MACValue);
-			MACValue &= 0xfe;
-			MACValue |= 0x1;
-			RTMP_IO_WRITE32(pAd, TX_BAND_CFG, MACValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue&= (~0x18);
-			BBPValue|= (0x10);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPValue);
-			BBPValue&= (~0x20);
-			BBPValue|= (0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPValue);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!!40MHz Upper LINK UP !!! Control Channel at UpperCentral = %d \n", pAd->CommonCfg.CentralChannel ));
-		}
-		pAd->CommonCfg.BBPCurrentBW = BW_40;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-		pAd->MacTab.Content[Wcid].HTPhyMode.field.BW = 1;
-	}
-}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-VOID PeerPublicAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-#ifdef DOT11N_DRAFT3
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-#endif // DOT11N_DRAFT3 //
-
-	if (Elem->Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return;
-
-#ifdef DOT11N_DRAFT3
-	switch(Action)
-	{
-		case ACTION_BSS_2040_COEXIST:	// Format defined in IEEE 7.4.7a.1 in 11n Draf3.03
-			{
-				//UCHAR	BssCoexist;
-				BSS_2040_COEXIST_ELEMENT		*pCoexistInfo;
-				BSS_2040_COEXIST_IE 			*pBssCoexistIe;
-				BSS_2040_INTOLERANT_CH_REPORT	*pIntolerantReport = NULL;
-
-				if (Elem->MsgLen <= (LENGTH_802_11 + sizeof(BSS_2040_COEXIST_ELEMENT)) )
-				{
-					DBGPRINT(RT_DEBUG_ERROR, ("ACTION - 20/40 BSS Coexistence Management Frame length too short! len = %ld!\n", Elem->MsgLen));
-					break;
-				}
-				DBGPRINT(RT_DEBUG_TRACE, ("ACTION - 20/40 BSS Coexistence Management action----> \n"));
-				hex_dump("CoexistenceMgmtFrame", Elem->Msg, Elem->MsgLen);
-
-
-				pCoexistInfo = (BSS_2040_COEXIST_ELEMENT *) &Elem->Msg[LENGTH_802_11+2];
-				//hex_dump("CoexistInfo", (PUCHAR)pCoexistInfo, sizeof(BSS_2040_COEXIST_ELEMENT));
-				if (Elem->MsgLen >= (LENGTH_802_11 + sizeof(BSS_2040_COEXIST_ELEMENT) + sizeof(BSS_2040_INTOLERANT_CH_REPORT)))
-				{
-					pIntolerantReport = (BSS_2040_INTOLERANT_CH_REPORT *)((PUCHAR)pCoexistInfo + sizeof(BSS_2040_COEXIST_ELEMENT));
-				}
-				//hex_dump("IntolerantReport ", (PUCHAR)pIntolerantReport, sizeof(BSS_2040_INTOLERANT_CH_REPORT));
-
-				pBssCoexistIe = (BSS_2040_COEXIST_IE *)(&pCoexistInfo->BssCoexistIe);
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-					if (INFRA_ON(pAd))
-					{
-						StaPublicAction(pAd, pCoexistInfo);
-					}
-				}
-#endif // CONFIG_STA_SUPPORT //
-
-			}
-			break;
-	}
-
-#endif // DOT11N_DRAFT3 //
-
-}
-
-
-static VOID ReservedAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR Category;
-
-	if (Elem->MsgLen <= LENGTH_802_11)
-	{
-		return;
-	}
-
-	Category = Elem->Msg[LENGTH_802_11];
-	DBGPRINT(RT_DEBUG_TRACE,("Rcv reserved category(%d) Action Frame\n", Category));
-	hex_dump("Reserved Action Frame", &Elem->Msg[0], Elem->MsgLen);
-}
-
-VOID PeerRMAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-
-{
-	return;
-}
-
-#ifdef DOT11_N_SUPPORT
-static VOID respond_ht_information_exchange_action(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen;
-	FRAME_HT_INFO	HTINFOframe, *pFrame;
-	UCHAR   		*pAddr;
-
-
-	// 2. Always send back ADDBA Response
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);	 //Get an unused nonpaged memory
-
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("ACTION - respond_ht_information_exchange_action() allocate memory failed \n"));
-		return;
-	}
-
-	// get RA
-	pFrame = (FRAME_HT_INFO *) &Elem->Msg[0];
-	pAddr = pFrame->Hdr.Addr2;
-
-	NdisZeroMemory(&HTINFOframe, sizeof(FRAME_HT_INFO));
-	// 2-1. Prepare ADDBA Response frame.
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (ADHOC_ON(pAd))
-			ActHeaderInit(pAd, &HTINFOframe.Hdr, pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-		else
-			ActHeaderInit(pAd, &HTINFOframe.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAddr);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	HTINFOframe.Category = CATEGORY_HT;
-	HTINFOframe.Action = HT_INFO_EXCHANGE;
-	HTINFOframe.HT_Info.Request = 0;
-	HTINFOframe.HT_Info.Forty_MHz_Intolerant = pAd->CommonCfg.HtCapability.HtCapInfo.Forty_Mhz_Intolerant;
-	HTINFOframe.HT_Info.STA_Channel_Width	 = pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth;
-
-	MakeOutgoingFrame(pOutBuffer,					&FrameLen,
-					  sizeof(FRAME_HT_INFO),	&HTINFOframe,
-					  END_OF_ARGS);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-}
-
-
-#ifdef DOT11N_DRAFT3
-VOID SendNotifyBWActionFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR  Wcid,
-	IN UCHAR apidx)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS 	NStatus;
-	FRAME_ACTION_HDR	Frame;
-	ULONG			FrameLen;
-	PUCHAR			pAddr1;
-
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("ACT - SendNotifyBWAction() allocate memory failed \n"));
-		return;
-	}
-
-	if (Wcid == MCAST_WCID)
-		pAddr1 = &BROADCAST_ADDR[0];
-	else
-		pAddr1 = pAd->MacTab.Content[Wcid].Addr;
-	ActHeaderInit(pAd, &Frame.Hdr, pAddr1, pAd->ApCfg.MBSSID[apidx].Bssid, pAd->ApCfg.MBSSID[apidx].Bssid);
-
-	Frame.Category = CATEGORY_HT;
-	Frame.Action = NOTIFY_BW_ACTION;
-
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-				  sizeof(FRAME_ACTION_HDR),	  &Frame,
-				  END_OF_ARGS);
-
-	*(pOutBuffer + FrameLen) = pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth;
-	FrameLen++;
-
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	DBGPRINT(RT_DEBUG_TRACE,("ACT - SendNotifyBWAction(NotifyBW= %d)!\n", pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth));
-
-}
-#endif // DOT11N_DRAFT3 //
-
-
-VOID PeerHTAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-
-	if (Elem->Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return;
-
-	switch(Action)
-	{
-		case NOTIFY_BW_ACTION:
-			DBGPRINT(RT_DEBUG_TRACE,("ACTION - HT Notify Channel bandwidth action----> \n"));
-#ifdef CONFIG_STA_SUPPORT
-			if(pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE)
-			{
-				// Note, this is to patch DIR-1353 AP. When the AP set to Wep, it will use legacy mode. But AP still keeps
-				// sending BW_Notify Action frame, and cause us to linkup and linkdown.
-				// In legacy mode, don't need to parse HT action frame.
-				DBGPRINT(RT_DEBUG_TRACE,("ACTION -Ignore HT Notify Channel BW when link as legacy mode. BW = %d---> \n",
-								Elem->Msg[LENGTH_802_11+2] ));
-				break;
-			}
-#endif // CONFIG_STA_SUPPORT //
-
-			if (Elem->Msg[LENGTH_802_11+2] == 0)	// 7.4.8.2. if value is 1, keep the same as supported channel bandwidth.
-				pAd->MacTab.Content[Elem->Wcid].HTPhyMode.field.BW = 0;
-
-			break;
-
-		case SMPS_ACTION:
-			// 7.3.1.25
- 			DBGPRINT(RT_DEBUG_TRACE,("ACTION - SMPS action----> \n"));
-			if (((Elem->Msg[LENGTH_802_11+2]&0x1) == 0))
-			{
-				pAd->MacTab.Content[Elem->Wcid].MmpsMode = MMPS_ENABLE;
-			}
-			else if (((Elem->Msg[LENGTH_802_11+2]&0x2) == 0))
-			{
-				pAd->MacTab.Content[Elem->Wcid].MmpsMode = MMPS_STATIC;
-			}
-			else
-			{
-				pAd->MacTab.Content[Elem->Wcid].MmpsMode = MMPS_DYNAMIC;
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE,("Aid(%d) MIMO PS = %d\n", Elem->Wcid, pAd->MacTab.Content[Elem->Wcid].MmpsMode));
-			// rt2860c : add something for smps change.
-			break;
-
-		case SETPCO_ACTION:
-			break;
-
-		case MIMO_CHA_MEASURE_ACTION:
-			break;
-
-		case HT_INFO_EXCHANGE:
-			{
-				HT_INFORMATION_OCTET	*pHT_info;
-
-				pHT_info = (HT_INFORMATION_OCTET *) &Elem->Msg[LENGTH_802_11+2];
-    				// 7.4.8.10
-    				DBGPRINT(RT_DEBUG_TRACE,("ACTION - HT Information Exchange action----> \n"));
-    				if (pHT_info->Request)
-    				{
-    					respond_ht_information_exchange_action(pAd, Elem);
-    				}
-			}
-    			break;
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Retry sending ADDBA Reqest.
-
-	IRQL = DISPATCH_LEVEL
-
-	Parametrs:
-	p8023Header: if this is already 802.3 format, p8023Header is NULL
-
-	Return	: TRUE if put into rx reordering buffer, shouldn't indicaterxhere.
-				FALSE , then continue indicaterx at this moment.
-	==========================================================================
- */
-VOID ORIBATimerTimeout(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	MAC_TABLE_ENTRY	*pEntry;
-	INT			i, total;
-//	FRAME_BAR			FrameBar;
-//	ULONG			FrameLen;
-//	NDIS_STATUS 	NStatus;
-//	PUCHAR			pOutBuffer = NULL;
-//	USHORT			Sequence;
-	UCHAR			TID;
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	total = pAd->MacTab.Size * NUM_OF_TID;
-
-	for (i = 1; ((i <MAX_LEN_OF_BA_ORI_TABLE) && (total > 0)) ; i++)
-	{
-		if  (pAd->BATable.BAOriEntry[i].ORI_BA_Status == Originator_Done)
-		{
-			pEntry = &pAd->MacTab.Content[pAd->BATable.BAOriEntry[i].Wcid];
-			TID = pAd->BATable.BAOriEntry[i].TID;
-
-			ASSERT(pAd->BATable.BAOriEntry[i].Wcid < MAX_LEN_OF_MAC_TABLE);
-		}
-		total --;
-	}
-}
-
-
-VOID SendRefreshBAR(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry)
-{
-	FRAME_BAR		FrameBar;
-	ULONG			FrameLen;
-	NDIS_STATUS 	NStatus;
-	PUCHAR			pOutBuffer = NULL;
-	USHORT			Sequence;
-	UCHAR			i, TID;
-	USHORT			idx;
-	BA_ORI_ENTRY	*pBAEntry;
-
-	for (i = 0; i <NUM_OF_TID; i++)
-	{
-		idx = pEntry->BAOriWcidArray[i];
-		if (idx == 0)
-		{
-			continue;
-		}
-		pBAEntry = &pAd->BATable.BAOriEntry[idx];
-
-		if  (pBAEntry->ORI_BA_Status == Originator_Done)
-		{
-			TID = pBAEntry->TID;
-
-			ASSERT(pBAEntry->Wcid < MAX_LEN_OF_MAC_TABLE);
-
-			NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-			if(NStatus != NDIS_STATUS_SUCCESS)
-			{
-				DBGPRINT(RT_DEBUG_ERROR,("BA - MlmeADDBAAction() allocate memory failed \n"));
-				return;
-			}
-
-			Sequence = pEntry->TxSeq[TID];
-
-
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				BarHeaderInit(pAd, &FrameBar, pEntry->Addr, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
-
-			FrameBar.StartingSeq.field.FragNum = 0; // make sure sequence not clear in DEL function.
-			FrameBar.StartingSeq.field.StartSeq = Sequence; // make sure sequence not clear in DEL funciton.
-			FrameBar.BarControl.TID = TID; // make sure sequence not clear in DEL funciton.
-
-			MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-							  sizeof(FRAME_BAR),	  &FrameBar,
-							  END_OF_ARGS);
-			//if (!(CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_RALINK_CHIPSET)))
-			if (1)	// Now we always send BAR.
-			{
-				//MiniportMMRequestUnlock(pAd, 0, pOutBuffer, FrameLen);
-				MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-				//MiniportDataMMRequest(pAd, MapUserPriorityToAccessCategory[TID], pOutBuffer, FrameLen);
-			}
-			MlmeFreeMemory(pAd, pOutBuffer);
-		}
-	}
-}
-#endif // DOT11_N_SUPPORT //
-
-VOID ActHeaderInit(
-    IN	PRTMP_ADAPTER	pAd,
-    IN OUT PHEADER_802_11 pHdr80211,
-    IN PUCHAR Addr1,
-    IN PUCHAR Addr2,
-    IN PUCHAR Addr3)
-{
-    NdisZeroMemory(pHdr80211, sizeof(HEADER_802_11));
-    pHdr80211->FC.Type = BTYPE_MGMT;
-    pHdr80211->FC.SubType = SUBTYPE_ACTION;
-
-    COPY_MAC_ADDR(pHdr80211->Addr1, Addr1);
-	COPY_MAC_ADDR(pHdr80211->Addr2, Addr2);
-    COPY_MAC_ADDR(pHdr80211->Addr3, Addr3);
-}
-
-VOID BarHeaderInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN OUT PFRAME_BAR pCntlBar,
-	IN PUCHAR pDA,
-	IN PUCHAR pSA)
-{
-//	USHORT	Duration;
-
-	NdisZeroMemory(pCntlBar, sizeof(FRAME_BAR));
-	pCntlBar->FC.Type = BTYPE_CNTL;
-	pCntlBar->FC.SubType = SUBTYPE_BLOCK_ACK_REQ;
-   	pCntlBar->BarControl.MTID = 0;
-	pCntlBar->BarControl.Compressed = 1;
-	pCntlBar->BarControl.ACKPolicy = 0;
-
-
-	pCntlBar->Duration = 16 + RTMPCalcDuration(pAd, RATE_1, sizeof(FRAME_BA));
-
-	COPY_MAC_ADDR(pCntlBar->Addr1, pDA);
-	COPY_MAC_ADDR(pCntlBar->Addr2, pSA);
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Insert Category and action code into the action frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. category code of the frame.
-		4. action code of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID InsertActField(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN UINT8 Category,
-	IN UINT8 ActCode)
-{
-	ULONG TempLen;
-
-	MakeOutgoingFrame(	pFrameBuf,		&TempLen,
-						1,				&Category,
-						1,				&ActCode,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-	return;
-}
+#include "../../rt2870/common/action.c"
diff --git a/drivers/staging/rt3070/common/ba_action.c b/drivers/staging/rt3070/common/ba_action.c
index 17e1f87..2d638ea 100644
--- a/drivers/staging/rt3070/common/ba_action.c
+++ b/drivers/staging/rt3070/common/ba_action.c
@@ -1,1810 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-
-#ifdef DOT11_N_SUPPORT
-
-#include "../rt_config.h"
-
-
-
-#define BA_ORI_INIT_SEQ		(pEntry->TxSeq[TID]) //1			// inital sequence number of BA session
-
-#define ORI_SESSION_MAX_RETRY	8
-#define ORI_BA_SESSION_TIMEOUT	(2000)	// ms
-#define REC_BA_SESSION_IDLE_TIMEOUT	(1000)	// ms
-
-#define REORDERING_PACKET_TIMEOUT		((100 * HZ)/1000)	// system ticks -- 100 ms
-#define MAX_REORDERING_PACKET_TIMEOUT	((3000 * HZ)/1000)	// system ticks -- 100 ms
-
-#define RESET_RCV_SEQ		(0xFFFF)
-
-static void ba_mpdu_blk_free(PRTMP_ADAPTER pAd, struct reordering_mpdu *mpdu_blk);
-
-
-BA_ORI_ENTRY *BATableAllocOriEntry(
-								  IN  PRTMP_ADAPTER   pAd,
-								  OUT USHORT          *Idx);
-
-BA_REC_ENTRY *BATableAllocRecEntry(
-								  IN  PRTMP_ADAPTER   pAd,
-								  OUT USHORT          *Idx);
-
-VOID BAOriSessionSetupTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-VOID BARecSessionIdleTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-
-BUILD_TIMER_FUNCTION(BAOriSessionSetupTimeout);
-BUILD_TIMER_FUNCTION(BARecSessionIdleTimeout);
-
-#define ANNOUNCE_REORDERING_PACKET(_pAd, _mpdu_blk)	\
-			Announce_Reordering_Packet(_pAd, _mpdu_blk);
-
-VOID BA_MaxWinSizeReasign(
-	IN PRTMP_ADAPTER	pAd,
-	IN MAC_TABLE_ENTRY  *pEntryPeer,
-	OUT UCHAR			*pWinSize)
-{
-	UCHAR MaxSize;
-
-
-	if (pAd->MACVersion >= RALINK_2883_VERSION) // 3*3
-	{
-		if (pAd->MACVersion >= RALINK_3070_VERSION)
-		{
-			if (pEntryPeer->WepStatus != Ndis802_11EncryptionDisabled)
-				MaxSize = 7; // for non-open mode
-			else
-				MaxSize = 13;
-		}
-		else
-			MaxSize = 31;
-	}
-	else if (pAd->MACVersion >= RALINK_2880E_VERSION) // 2880 e
-	{
-		if (pEntryPeer->WepStatus != Ndis802_11EncryptionDisabled)
-			MaxSize = 7; // for non-open mode
-		else
-			MaxSize = 13;
-	}
-	else
-		MaxSize = 7;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ba> Win Size = %d, Max Size = %d\n",
-			*pWinSize, MaxSize));
-
-	if ((*pWinSize) > MaxSize)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ba> reassign max win size from %d to %d\n",
-				*pWinSize, MaxSize));
-
-		*pWinSize = MaxSize;
-	}
-}
-
-void Announce_Reordering_Packet(IN PRTMP_ADAPTER			pAd,
-								IN struct reordering_mpdu	*mpdu)
-{
-	PNDIS_PACKET    pPacket;
-
-	pPacket = mpdu->pPacket;
-
-	if (mpdu->bAMSDU)
-	{
-		ASSERT(0);
-		BA_Reorder_AMSDU_Annnounce(pAd, pPacket);
-	}
-	else
-	{
-		//
-		// pass this 802.3 packet to upper layer or forward this packet to WM directly
-		//
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pPacket, RTMP_GET_PACKET_IF(pPacket));
-#endif // CONFIG_STA_SUPPORT //
-	}
-}
-
-/*
- * Insert a reordering mpdu into sorted linked list by sequence no.
- */
-BOOLEAN ba_reordering_mpdu_insertsorted(struct reordering_list *list, struct reordering_mpdu *mpdu)
-{
-
-	struct reordering_mpdu **ppScan = &list->next;
-
-	while (*ppScan != NULL)
-	{
-		if (SEQ_SMALLER((*ppScan)->Sequence, mpdu->Sequence, MAXSEQ))
-		{
-			ppScan = &(*ppScan)->next;
-		}
-		else if ((*ppScan)->Sequence == mpdu->Sequence)
-		{
-			/* give up this duplicated frame */
-			return(FALSE);
-		}
-		else
-		{
-			/* find position */
-			break;
-		}
-	}
-
-	mpdu->next = *ppScan;
-	*ppScan = mpdu;
-	list->qlen++;
-	return TRUE;
-}
-
-
-/*
- * caller lock critical section if necessary
- */
-static inline void ba_enqueue(struct reordering_list *list, struct reordering_mpdu *mpdu_blk)
-{
-	list->qlen++;
-	mpdu_blk->next = list->next;
-	list->next = mpdu_blk;
-}
-
-/*
- * caller lock critical section if necessary
- */
-static inline struct reordering_mpdu * ba_dequeue(struct reordering_list *list)
-{
-	struct reordering_mpdu *mpdu_blk = NULL;
-
-	ASSERT(list);
-
-		if (list->qlen)
-		{
-			list->qlen--;
-			mpdu_blk = list->next;
-			if (mpdu_blk)
-			{
-				list->next = mpdu_blk->next;
-				mpdu_blk->next = NULL;
-			}
-		}
-	return mpdu_blk;
-}
-
-
-static inline struct reordering_mpdu  *ba_reordering_mpdu_dequeue(struct reordering_list *list)
-{
-	return(ba_dequeue(list));
-}
-
-
-static inline struct reordering_mpdu  *ba_reordering_mpdu_probe(struct reordering_list *list)
-	{
-	ASSERT(list);
-
-		return(list->next);
-	}
-
-
-/*
- * free all resource for reordering mechanism
- */
-void ba_reordering_resource_release(PRTMP_ADAPTER pAd)
-{
-	BA_TABLE        *Tab;
-	PBA_REC_ENTRY   pBAEntry;
-	struct reordering_mpdu *mpdu_blk;
-	int i;
-
-	Tab = &pAd->BATable;
-
-	/* I.  release all pending reordering packet */
-	NdisAcquireSpinLock(&pAd->BATabLock);
-	for (i = 0; i < MAX_LEN_OF_BA_REC_TABLE; i++)
-	{
-		pBAEntry = &Tab->BARecEntry[i];
-		if (pBAEntry->REC_BA_Status != Recipient_NONE)
-		{
-			while ((mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list)))
-			{
-				ASSERT(mpdu_blk->pPacket);
-				RELEASE_NDIS_PACKET(pAd, mpdu_blk->pPacket, NDIS_STATUS_FAILURE);
-				ba_mpdu_blk_free(pAd, mpdu_blk);
-			}
-		}
-	}
-	NdisReleaseSpinLock(&pAd->BATabLock);
-
-	ASSERT(pBAEntry->list.qlen == 0);
-	/* II. free memory of reordering mpdu table */
-	NdisAcquireSpinLock(&pAd->mpdu_blk_pool.lock);
-	os_free_mem(pAd, pAd->mpdu_blk_pool.mem);
-	NdisReleaseSpinLock(&pAd->mpdu_blk_pool.lock);
-}
-
-
-
-/*
- * Allocate all resource for reordering mechanism
- */
-BOOLEAN ba_reordering_resource_init(PRTMP_ADAPTER pAd, int num)
-{
-	int     i;
-	PUCHAR  mem;
-	struct reordering_mpdu *mpdu_blk;
-	struct reordering_list *freelist;
-
-	/* allocate spinlock */
-	NdisAllocateSpinLock(&pAd->mpdu_blk_pool.lock);
-
-	/* initialize freelist */
-	freelist = &pAd->mpdu_blk_pool.freelist;
-	freelist->next = NULL;
-	freelist->qlen = 0;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Allocate %d memory for BA reordering\n", (UINT32)(num*sizeof(struct reordering_mpdu))));
-
-	/* allocate number of mpdu_blk memory */
-	os_alloc_mem(pAd, (PUCHAR *)&mem, (num*sizeof(struct reordering_mpdu)));
-
-	pAd->mpdu_blk_pool.mem = mem;
-
-	if (mem == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Can't Allocate Memory for BA Reordering\n"));
-		return(FALSE);
-	}
-
-	/* build mpdu_blk free list */
-	for (i=0; i<num; i++)
-	{
-		/* get mpdu_blk */
-		mpdu_blk = (struct reordering_mpdu *) mem;
-		/* initial mpdu_blk */
-		NdisZeroMemory(mpdu_blk, sizeof(struct reordering_mpdu));
-		/* next mpdu_blk */
-		mem += sizeof(struct reordering_mpdu);
-		/* insert mpdu_blk into freelist */
-		ba_enqueue(freelist, mpdu_blk);
-	}
-
-	return(TRUE);
-}
-
-//static int blk_count=0; // sample take off, no use
-
-static struct reordering_mpdu *ba_mpdu_blk_alloc(PRTMP_ADAPTER pAd)
-{
-	struct reordering_mpdu *mpdu_blk;
-
-	NdisAcquireSpinLock(&pAd->mpdu_blk_pool.lock);
-	mpdu_blk = ba_dequeue(&pAd->mpdu_blk_pool.freelist);
-	if (mpdu_blk)
-	{
-//		blk_count++;
-		/* reset mpdu_blk */
-		NdisZeroMemory(mpdu_blk, sizeof(struct reordering_mpdu));
-	}
-	NdisReleaseSpinLock(&pAd->mpdu_blk_pool.lock);
-	return mpdu_blk;
-}
-
-static void ba_mpdu_blk_free(PRTMP_ADAPTER pAd, struct reordering_mpdu *mpdu_blk)
-{
-	ASSERT(mpdu_blk);
-
-	NdisAcquireSpinLock(&pAd->mpdu_blk_pool.lock);
-//	blk_count--;
-	ba_enqueue(&pAd->mpdu_blk_pool.freelist, mpdu_blk);
-	NdisReleaseSpinLock(&pAd->mpdu_blk_pool.lock);
-}
-
-
-static USHORT ba_indicate_reordering_mpdus_in_order(
-												   IN PRTMP_ADAPTER    pAd,
-												   IN PBA_REC_ENTRY    pBAEntry,
-												   IN USHORT           StartSeq)
-{
-	struct reordering_mpdu *mpdu_blk;
-	USHORT  LastIndSeq = RESET_RCV_SEQ;
-
-	NdisAcquireSpinLock(&pBAEntry->RxReRingLock);
-
-	while ((mpdu_blk = ba_reordering_mpdu_probe(&pBAEntry->list)))
-		{
-			/* find in-order frame */
-		if (!SEQ_STEPONE(mpdu_blk->Sequence, StartSeq, MAXSEQ))
-			{
-				break;
-			}
-			/* dequeue in-order frame from reodering list */
-			mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list);
-			/* pass this frame up */
-		ANNOUNCE_REORDERING_PACKET(pAd, mpdu_blk);
-		/* move to next sequence */
-			StartSeq = mpdu_blk->Sequence;
-		LastIndSeq = StartSeq;
-		/* free mpdu_blk */
-			ba_mpdu_blk_free(pAd, mpdu_blk);
-	}
-
-	NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
-
-	/* update last indicated sequence */
-	return LastIndSeq;
-}
-
-static void ba_indicate_reordering_mpdus_le_seq(
-											   IN PRTMP_ADAPTER    pAd,
-											   IN PBA_REC_ENTRY    pBAEntry,
-											   IN USHORT           Sequence)
-{
-	struct reordering_mpdu *mpdu_blk;
-
-	NdisAcquireSpinLock(&pBAEntry->RxReRingLock);
-	while ((mpdu_blk = ba_reordering_mpdu_probe(&pBAEntry->list)))
-		{
-			/* find in-order frame */
-		if ((mpdu_blk->Sequence == Sequence) || SEQ_SMALLER(mpdu_blk->Sequence, Sequence, MAXSEQ))
-		{
-			/* dequeue in-order frame from reodering list */
-			mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list);
-			/* pass this frame up */
-			ANNOUNCE_REORDERING_PACKET(pAd, mpdu_blk);
-			/* free mpdu_blk */
-			ba_mpdu_blk_free(pAd, mpdu_blk);
-		}
-		else
-			{
-				break;
-			}
-	}
-	NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
-}
-
-
-static void ba_refresh_reordering_mpdus(
-									   IN PRTMP_ADAPTER    pAd,
-									   PBA_REC_ENTRY       pBAEntry)
-{
-	struct reordering_mpdu *mpdu_blk;
-
-	NdisAcquireSpinLock(&pBAEntry->RxReRingLock);
-
-			/* dequeue in-order frame from reodering list */
-	while ((mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list)))
-	{
-			/* pass this frame up */
-		ANNOUNCE_REORDERING_PACKET(pAd, mpdu_blk);
-
-		pBAEntry->LastIndSeq = mpdu_blk->Sequence;
-			ba_mpdu_blk_free(pAd, mpdu_blk);
-
-		/* update last indicated sequence */
-	}
-	ASSERT(pBAEntry->list.qlen == 0);
-	pBAEntry->LastIndSeq = RESET_RCV_SEQ;
-	NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
-}
-
-
-//static
-void ba_flush_reordering_timeout_mpdus(
-									IN PRTMP_ADAPTER    pAd,
-									IN PBA_REC_ENTRY    pBAEntry,
-									IN ULONG            Now32)
-
-{
-	USHORT Sequence;
-
-//	if ((RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+REORDERING_PACKET_TIMEOUT)) &&
-//		 (pBAEntry->list.qlen > ((pBAEntry->BAWinSize*7)/8))) //||
-//		(RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(10*REORDERING_PACKET_TIMEOUT))) &&
-//		 (pBAEntry->list.qlen > (pBAEntry->BAWinSize/8)))
-	if (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(MAX_REORDERING_PACKET_TIMEOUT/6)))
-		 &&(pBAEntry->list.qlen > 1)
-		)
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("timeout[%d] (%08lx-%08lx = %d > %d): %x, flush all!\n ", pBAEntry->list.qlen, Now32, (pBAEntry->LastIndSeqAtTimer),
-			   (int)((long) Now32 - (long)(pBAEntry->LastIndSeqAtTimer)), MAX_REORDERING_PACKET_TIMEOUT,
-			   pBAEntry->LastIndSeq));
-		ba_refresh_reordering_mpdus(pAd, pBAEntry);
-		pBAEntry->LastIndSeqAtTimer = Now32;
-	}
-	else
-	if (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(REORDERING_PACKET_TIMEOUT)))
-		&& (pBAEntry->list.qlen > 0)
-	   )
-		{
-//		printk("timeout[%d] (%lx-%lx = %d > %d): %x, ", pBAEntry->list.qlen, Now32, (pBAEntry->LastIndSeqAtTimer),
-//			   (int)((long) Now32 - (long)(pBAEntry->LastIndSeqAtTimer)), REORDERING_PACKET_TIMEOUT,
-//			   pBAEntry->LastIndSeq);
-    		//
-		// force LastIndSeq to shift to LastIndSeq+1
-    		//
-    		Sequence = (pBAEntry->LastIndSeq+1) & MAXSEQ;
-    		ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, Sequence);
-    		pBAEntry->LastIndSeqAtTimer = Now32;
-			pBAEntry->LastIndSeq = Sequence;
-    		//
-    		// indicate in-order mpdus
-    		//
-    		Sequence = ba_indicate_reordering_mpdus_in_order(pAd, pBAEntry, Sequence);
-    		if (Sequence != RESET_RCV_SEQ)
-    		{
-    			pBAEntry->LastIndSeq = Sequence;
-    		}
-
-		//printk("%x, flush one!\n", pBAEntry->LastIndSeq);
-
-	}
-}
-
-
-/*
- * generate ADDBA request to
- * set up BA agreement
- */
-VOID BAOriSessionSetUp(
-					  IN PRTMP_ADAPTER    pAd,
-					  IN MAC_TABLE_ENTRY  *pEntry,
-					  IN UCHAR            TID,
-					  IN USHORT           TimeOut,
-					  IN ULONG            DelayTime,
-					  IN BOOLEAN          isForced)
-
-{
-	//MLME_ADDBA_REQ_STRUCT	AddbaReq;
-	BA_ORI_ENTRY            *pBAEntry = NULL;
-	USHORT                  Idx;
-	BOOLEAN                 Cancelled;
-
-	if ((pAd->CommonCfg.BACapability.field.AutoBA != TRUE)  &&  (isForced == FALSE))
-		return;
-
-	// if this entry is limited to use legacy tx mode, it doesn't generate BA.
-	if (RTMPStaFixedTxMode(pAd, pEntry) != FIXED_TXMODE_HT)
-		return;
-
-	if ((pEntry->BADeclineBitmap & (1<<TID)) && (isForced == FALSE))
-	{
-		// try again after 3 secs
-		DelayTime = 3000;
-//		printk("DeCline BA from Peer\n");
-//		return;
-	}
-
-
-	Idx = pEntry->BAOriWcidArray[TID];
-	if (Idx == 0)
-	{
-		// allocate a BA session
-		pBAEntry = BATableAllocOriEntry(pAd, &Idx);
-		if (pBAEntry == NULL)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("ADDBA - MlmeADDBAAction() allocate BA session failed \n"));
-			return;
-		}
-	}
-	else
-	{
-		pBAEntry =&pAd->BATable.BAOriEntry[Idx];
-	}
-
-	if (pBAEntry->ORI_BA_Status >= Originator_WaitRes)
-	{
-		return;
-	}
-
-	pEntry->BAOriWcidArray[TID] = Idx;
-
-	// Initialize BA session
-	pBAEntry->ORI_BA_Status = Originator_WaitRes;
-	pBAEntry->Wcid = pEntry->Aid;
-	pBAEntry->BAWinSize = pAd->CommonCfg.BACapability.field.RxBAWinLimit;
-	pBAEntry->Sequence = BA_ORI_INIT_SEQ;
-	pBAEntry->Token = 1;	// (2008-01-21) Jan Lee recommends it - this token can't be 0
-	pBAEntry->TID = TID;
-	pBAEntry->TimeOutValue = TimeOut;
-	pBAEntry->pAdapter = pAd;
-
-	DBGPRINT(RT_DEBUG_TRACE,("Send AddBA to %02x:%02x:%02x:%02x:%02x:%02x Tid:%d isForced:%d Wcid:%d\n"
-		,pEntry->Addr[0],pEntry->Addr[1],pEntry->Addr[2]
-		,pEntry->Addr[3],pEntry->Addr[4],pEntry->Addr[5]
-		,TID,isForced,pEntry->Aid));
-
-	if (!(pEntry->TXBAbitmap & (1<<TID)))
-	{
-		RTMPInitTimer(pAd, &pBAEntry->ORIBATimer, GET_TIMER_FUNCTION(BAOriSessionSetupTimeout), pBAEntry, FALSE);
-	}
-	else
-		RTMPCancelTimer(&pBAEntry->ORIBATimer, &Cancelled);
-
-	// set timer to send ADDBA request
-	RTMPSetTimer(&pBAEntry->ORIBATimer, DelayTime);
-}
-
-VOID BAOriSessionAdd(
-			IN PRTMP_ADAPTER    pAd,
-					IN MAC_TABLE_ENTRY  *pEntry,
-			IN PFRAME_ADDBA_RSP pFrame)
-{
-	BA_ORI_ENTRY  *pBAEntry = NULL;
-	BOOLEAN       Cancelled;
-	UCHAR         TID;
-	USHORT        Idx;
-	PUCHAR          pOutBuffer2 = NULL;
-	NDIS_STATUS     NStatus;
-	ULONG           FrameLen;
-	FRAME_BAR       FrameBar;
-
-	TID = pFrame->BaParm.TID;
-	Idx = pEntry->BAOriWcidArray[TID];
-	pBAEntry =&pAd->BATable.BAOriEntry[Idx];
-
-	// Start fill in parameters.
-	if ((Idx !=0) && (pBAEntry->TID == TID) && (pBAEntry->ORI_BA_Status == Originator_WaitRes))
-	{
-		pBAEntry->BAWinSize = min(pBAEntry->BAWinSize, ((UCHAR)pFrame->BaParm.BufSize));
-		BA_MaxWinSizeReasign(pAd, pEntry, &pBAEntry->BAWinSize);
-
-		pBAEntry->TimeOutValue = pFrame->TimeOutValue;
-		pBAEntry->ORI_BA_Status = Originator_Done;
-		// reset sequence number
-		pBAEntry->Sequence = BA_ORI_INIT_SEQ;
-		// Set Bitmap flag.
-		pEntry->TXBAbitmap |= (1<<TID);
-				RTMPCancelTimer(&pBAEntry->ORIBATimer, &Cancelled);
-
-		pBAEntry->ORIBATimer.TimerValue = 0;	//pFrame->TimeOutValue;
-
-		DBGPRINT(RT_DEBUG_TRACE,("%s : TXBAbitmap = %x, BAWinSize = %d, TimeOut = %ld\n", __FUNCTION__, pEntry->TXBAbitmap,
-								 pBAEntry->BAWinSize, pBAEntry->ORIBATimer.TimerValue));
-
-		// SEND BAR ;
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer2);  //Get an unused nonpaged memory
-		if (NStatus != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("BA - BAOriSessionAdd() allocate memory failed \n"));
-			return;
-		}
-
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			BarHeaderInit(pAd, &FrameBar, pAd->MacTab.Content[pBAEntry->Wcid].Addr, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
-
-		FrameBar.StartingSeq.field.FragNum = 0;	// make sure sequence not clear in DEL function.
-		FrameBar.StartingSeq.field.StartSeq = pBAEntry->Sequence; // make sure sequence not clear in DEL funciton.
-		FrameBar.BarControl.TID = pBAEntry->TID; // make sure sequence not clear in DEL funciton.
-		MakeOutgoingFrame(pOutBuffer2,              &FrameLen,
-						  sizeof(FRAME_BAR),      &FrameBar,
-					  END_OF_ARGS);
-		MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer2, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer2);
-
-
-		if (pBAEntry->ORIBATimer.TimerValue)
-			RTMPSetTimer(&pBAEntry->ORIBATimer, pBAEntry->ORIBATimer.TimerValue); // in mSec
-	}
-}
-
-BOOLEAN BARecSessionAdd(
-					   IN PRTMP_ADAPTER    pAd,
-					   IN MAC_TABLE_ENTRY  *pEntry,
-					   IN PFRAME_ADDBA_REQ pFrame)
-{
-	BA_REC_ENTRY            *pBAEntry = NULL;
-	BOOLEAN                 Status = TRUE;
-	BOOLEAN                 Cancelled;
-	USHORT                  Idx;
-	UCHAR                   TID;
-	UCHAR                   BAWinSize;
-	//UINT32                  Value;
-	//UINT                    offset;
-
-
-	ASSERT(pEntry);
-
-	// find TID
-	TID = pFrame->BaParm.TID;
-
-	BAWinSize = min(((UCHAR)pFrame->BaParm.BufSize), (UCHAR)pAd->CommonCfg.BACapability.field.RxBAWinLimit);
-
-	// Intel patch
-	if (BAWinSize == 0)
-	{
-		BAWinSize = 64;
-	}
-
-	Idx = pEntry->BARecWcidArray[TID];
-
-
-	if (Idx == 0)
-	{
-		pBAEntry = BATableAllocRecEntry(pAd, &Idx);
-	}
-	else
-	{
-		pBAEntry = &pAd->BATable.BARecEntry[Idx];
-		// flush all pending reordering mpdus
-		ba_refresh_reordering_mpdus(pAd, pBAEntry);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("%s(%ld): Idx = %d, BAWinSize(req %d) = %d\n", __FUNCTION__, pAd->BATable.numAsRecipient, Idx,
-							 pFrame->BaParm.BufSize, BAWinSize));
-
-	// Start fill in parameters.
-	if (pBAEntry != NULL)
-	{
-		ASSERT(pBAEntry->list.qlen == 0);
-
-		pBAEntry->REC_BA_Status = Recipient_HandleRes;
-		pBAEntry->BAWinSize = BAWinSize;
-		pBAEntry->Wcid = pEntry->Aid;
-		pBAEntry->TID = TID;
-		pBAEntry->TimeOutValue = pFrame->TimeOutValue;
-		pBAEntry->REC_BA_Status = Recipient_Accept;
-		// initial sequence number
-		pBAEntry->LastIndSeq = RESET_RCV_SEQ; //pFrame->BaStartSeq.field.StartSeq;
-
-		printk("Start Seq = %08x\n",  pFrame->BaStartSeq.field.StartSeq);
-
-		if (pEntry->RXBAbitmap & (1<<TID))
-		{
-			RTMPCancelTimer(&pBAEntry->RECBATimer, &Cancelled);
-		}
-		else
-		{
-			RTMPInitTimer(pAd, &pBAEntry->RECBATimer, GET_TIMER_FUNCTION(BARecSessionIdleTimeout), pBAEntry, TRUE);
-		}
-
-		// Set Bitmap flag.
-		pEntry->RXBAbitmap |= (1<<TID);
-		pEntry->BARecWcidArray[TID] = Idx;
-
-		pEntry->BADeclineBitmap &= ~(1<<TID);
-
-		// Set BA session mask in WCID table.
-		RT28XX_ADD_BA_SESSION_TO_ASIC(pAd, pEntry->Aid, TID);
-
-		DBGPRINT(RT_DEBUG_TRACE,("MACEntry[%d]RXBAbitmap = 0x%x. BARecWcidArray=%d\n",
-				pEntry->Aid, pEntry->RXBAbitmap, pEntry->BARecWcidArray[TID]));
-	}
-	else
-	{
-		Status = FALSE;
-		DBGPRINT(RT_DEBUG_TRACE,("Can't Accept ADDBA for %02x:%02x:%02x:%02x:%02x:%02x TID = %d\n",
-				PRINT_MAC(pEntry->Addr), TID));
-	}
-	return(Status);
-}
-
-
-BA_REC_ENTRY *BATableAllocRecEntry(
-								  IN  PRTMP_ADAPTER   pAd,
-								  OUT USHORT          *Idx)
-{
-	int             i;
-	BA_REC_ENTRY    *pBAEntry = NULL;
-
-
-	NdisAcquireSpinLock(&pAd->BATabLock);
-
-	if (pAd->BATable.numAsRecipient >= MAX_BARECI_SESSION)
-	{
-		printk("BA Recipeint Session (%ld) > %d\n", pAd->BATable.numAsRecipient,
-			MAX_BARECI_SESSION);
-		goto done;
-	}
-
-	// reserve idx 0 to identify BAWcidArray[TID] as empty
-	for (i=1; i < MAX_LEN_OF_BA_REC_TABLE; i++)
-	{
-		pBAEntry =&pAd->BATable.BARecEntry[i];
-		if ((pBAEntry->REC_BA_Status == Recipient_NONE))
-		{
-			// get one
-			pAd->BATable.numAsRecipient++;
-			pBAEntry->REC_BA_Status = Recipient_USED;
-			*Idx = i;
-			break;
-		}
-	}
-
-done:
-	NdisReleaseSpinLock(&pAd->BATabLock);
-	return pBAEntry;
-}
-
-BA_ORI_ENTRY *BATableAllocOriEntry(
-								  IN  PRTMP_ADAPTER   pAd,
-								  OUT USHORT          *Idx)
-{
-	int             i;
-	BA_ORI_ENTRY    *pBAEntry = NULL;
-
-	NdisAcquireSpinLock(&pAd->BATabLock);
-
-	if (pAd->BATable.numAsOriginator >= (MAX_LEN_OF_BA_ORI_TABLE))
-	{
-		goto done;
-	}
-
-	// reserve idx 0 to identify BAWcidArray[TID] as empty
-	for (i=1; i<MAX_LEN_OF_BA_ORI_TABLE; i++)
-	{
-		pBAEntry =&pAd->BATable.BAOriEntry[i];
-		if ((pBAEntry->ORI_BA_Status == Originator_NONE))
-		{
-			// get one
-			pAd->BATable.numAsOriginator++;
-			pBAEntry->ORI_BA_Status = Originator_USED;
-			pBAEntry->pAdapter = pAd;
-			*Idx = i;
-			break;
-		}
-	}
-
-done:
-	NdisReleaseSpinLock(&pAd->BATabLock);
-	return pBAEntry;
-}
-
-
-VOID BATableFreeOriEntry(
-						IN  PRTMP_ADAPTER   pAd,
-						IN  ULONG           Idx)
-{
-	BA_ORI_ENTRY    *pBAEntry = NULL;
-	MAC_TABLE_ENTRY *pEntry;
-
-
-	if ((Idx == 0) || (Idx >= MAX_LEN_OF_BA_ORI_TABLE))
-		return;
-
-	pBAEntry =&pAd->BATable.BAOriEntry[Idx];
-
-	if (pBAEntry->ORI_BA_Status != Originator_NONE)
-	{
-		pEntry = &pAd->MacTab.Content[pBAEntry->Wcid];
-		pEntry->BAOriWcidArray[pBAEntry->TID] = 0;
-
-
-		NdisAcquireSpinLock(&pAd->BATabLock);
-		if (pBAEntry->ORI_BA_Status == Originator_Done)
-		{
-		 	pEntry->TXBAbitmap &= (~(1<<(pBAEntry->TID) ));
-			DBGPRINT(RT_DEBUG_TRACE, ("BATableFreeOriEntry numAsOriginator= %ld\n", pAd->BATable.numAsRecipient));
-			// Erase Bitmap flag.
-		}
-
-		ASSERT(pAd->BATable.numAsOriginator != 0);
-
-		pAd->BATable.numAsOriginator -= 1;
-
-		pBAEntry->ORI_BA_Status = Originator_NONE;
-		pBAEntry->Token = 0;
-		NdisReleaseSpinLock(&pAd->BATabLock);
-	}
-}
-
-
-VOID BATableFreeRecEntry(
-						IN  PRTMP_ADAPTER   pAd,
-						IN  ULONG           Idx)
-{
-	BA_REC_ENTRY    *pBAEntry = NULL;
-	MAC_TABLE_ENTRY *pEntry;
-
-
-	if ((Idx == 0) || (Idx >= MAX_LEN_OF_BA_REC_TABLE))
-		return;
-
-	pBAEntry =&pAd->BATable.BARecEntry[Idx];
-
-	if (pBAEntry->REC_BA_Status != Recipient_NONE)
-	{
-		pEntry = &pAd->MacTab.Content[pBAEntry->Wcid];
-		pEntry->BARecWcidArray[pBAEntry->TID] = 0;
-
-		NdisAcquireSpinLock(&pAd->BATabLock);
-
-		ASSERT(pAd->BATable.numAsRecipient != 0);
-
-		pAd->BATable.numAsRecipient -= 1;
-
-		pBAEntry->REC_BA_Status = Recipient_NONE;
-		NdisReleaseSpinLock(&pAd->BATabLock);
-	}
-}
-
-
-VOID BAOriSessionTearDown(
-						 IN OUT  PRTMP_ADAPTER   pAd,
-						 IN      UCHAR           Wcid,
-						 IN      UCHAR           TID,
-						 IN      BOOLEAN         bPassive,
-						 IN      BOOLEAN         bForceSend)
-{
-	ULONG           Idx = 0;
-	BA_ORI_ENTRY    *pBAEntry;
-	BOOLEAN         Cancelled;
-
-	if (Wcid >= MAX_LEN_OF_MAC_TABLE)
-	{
-		return;
-	}
-
-	//
-	// Locate corresponding BA Originator Entry in BA Table with the (pAddr,TID).
-	//
-	Idx = pAd->MacTab.Content[Wcid].BAOriWcidArray[TID];
-	if ((Idx == 0) || (Idx >= MAX_LEN_OF_BA_ORI_TABLE))
-	{
-		if (bForceSend == TRUE)
-		{
-			// force send specified TID DelBA
-			MLME_DELBA_REQ_STRUCT   DelbaReq;
-			MLME_QUEUE_ELEM *Elem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-
-			NdisZeroMemory(&DelbaReq, sizeof(DelbaReq));
-			NdisZeroMemory(Elem, sizeof(MLME_QUEUE_ELEM));
-
-			COPY_MAC_ADDR(DelbaReq.Addr, pAd->MacTab.Content[Wcid].Addr);
-			DelbaReq.Wcid = Wcid;
-			DelbaReq.TID = TID;
-			DelbaReq.Initiator = ORIGINATOR;
-#if 1
-			Elem->MsgLen  = sizeof(DelbaReq);
-			NdisMoveMemory(Elem->Msg, &DelbaReq, sizeof(DelbaReq));
-			MlmeDELBAAction(pAd, Elem);
-			kfree(Elem);
-#else
-			MlmeEnqueue(pAd, ACTION_STATE_MACHINE, MT2_MLME_ORI_DELBA_CATE, sizeof(MLME_DELBA_REQ_STRUCT), (PVOID)&DelbaReq);
-			RT28XX_MLME_HANDLER(pAd);
-#endif
-		}
-
-		return;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("%s===>Wcid=%d.TID=%d \n", __FUNCTION__, Wcid, TID));
-
-	pBAEntry = &pAd->BATable.BAOriEntry[Idx];
-	DBGPRINT(RT_DEBUG_TRACE,("\t===>Idx = %ld, Wcid=%d.TID=%d, ORI_BA_Status = %d \n", Idx, Wcid, TID, pBAEntry->ORI_BA_Status));
-	//
-	// Prepare DelBA action frame and send to the peer.
-	//
-	if ((bPassive == FALSE) && (TID == pBAEntry->TID) && (pBAEntry->ORI_BA_Status == Originator_Done))
-	{
-		MLME_DELBA_REQ_STRUCT   DelbaReq;
-		MLME_QUEUE_ELEM *Elem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-
-		NdisZeroMemory(&DelbaReq, sizeof(DelbaReq));
-		NdisZeroMemory(Elem, sizeof(MLME_QUEUE_ELEM));
-
-		COPY_MAC_ADDR(DelbaReq.Addr, pAd->MacTab.Content[Wcid].Addr);
-		DelbaReq.Wcid = Wcid;
-		DelbaReq.TID = pBAEntry->TID;
-		DelbaReq.Initiator = ORIGINATOR;
-#if 1
-		Elem->MsgLen  = sizeof(DelbaReq);
-		NdisMoveMemory(Elem->Msg, &DelbaReq, sizeof(DelbaReq));
-		MlmeDELBAAction(pAd, Elem);
-		kfree(Elem);
-#else
-		MlmeEnqueue(pAd, ACTION_STATE_MACHINE, MT2_MLME_ORI_DELBA_CATE, sizeof(MLME_DELBA_REQ_STRUCT), (PVOID)&DelbaReq);
-		RT28XX_MLME_HANDLER(pAd);
-#endif
-	}
-	RTMPCancelTimer(&pBAEntry->ORIBATimer, &Cancelled);
-	BATableFreeOriEntry(pAd, Idx);
-
-	if (bPassive)
-	{
-		//BAOriSessionSetUp(pAd, &pAd->MacTab.Content[Wcid], TID, 0, 10000, TRUE);
-	}
-}
-
-VOID BARecSessionTearDown(
-						 IN OUT  PRTMP_ADAPTER   pAd,
-						 IN      UCHAR           Wcid,
-						 IN      UCHAR           TID,
-						 IN      BOOLEAN         bPassive)
-{
-	ULONG           Idx = 0;
-	BA_REC_ENTRY    *pBAEntry;
-
-	if (Wcid >= MAX_LEN_OF_MAC_TABLE)
-	{
-		return;
-	}
-
-	//
-	//  Locate corresponding BA Originator Entry in BA Table with the (pAddr,TID).
-	//
-	Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID];
-	if (Idx == 0)
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE,("%s===>Wcid=%d.TID=%d \n", __FUNCTION__, Wcid, TID));
-
-
-	pBAEntry = &pAd->BATable.BARecEntry[Idx];
-	DBGPRINT(RT_DEBUG_TRACE,("\t===>Idx = %ld, Wcid=%d.TID=%d, REC_BA_Status = %d \n", Idx, Wcid, TID, pBAEntry->REC_BA_Status));
-	//
-	// Prepare DelBA action frame and send to the peer.
-	//
-	if ((TID == pBAEntry->TID) && (pBAEntry->REC_BA_Status == Recipient_Accept))
-	{
-		MLME_DELBA_REQ_STRUCT   DelbaReq;
-		BOOLEAN 				Cancelled;
-		MLME_QUEUE_ELEM *Elem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-		//ULONG   offset;
-		//UINT32  VALUE;
-
-		RTMPCancelTimer(&pBAEntry->RECBATimer, &Cancelled);
-
-		//
-		// 1. Send DELBA Action Frame
-		//
-		if (bPassive == FALSE)
-		{
-			NdisZeroMemory(&DelbaReq, sizeof(DelbaReq));
-			NdisZeroMemory(Elem, sizeof(MLME_QUEUE_ELEM));
-
-			COPY_MAC_ADDR(DelbaReq.Addr, pAd->MacTab.Content[Wcid].Addr);
-			DelbaReq.Wcid = Wcid;
-			DelbaReq.TID = TID;
-			DelbaReq.Initiator = RECIPIENT;
-#if 1
-			Elem->MsgLen  = sizeof(DelbaReq);
-			NdisMoveMemory(Elem->Msg, &DelbaReq, sizeof(DelbaReq));
-			MlmeDELBAAction(pAd, Elem);
-			kfree(Elem);
-#else
-			MlmeEnqueue(pAd, ACTION_STATE_MACHINE, MT2_MLME_ORI_DELBA_CATE, sizeof(MLME_DELBA_REQ_STRUCT), (PVOID)&DelbaReq);
-			RT28XX_MLME_HANDLER(pAd);
-#endif
-		}
-
-
-		//
-		// 2. Free resource of BA session
-		//
-		// flush all pending reordering mpdus
-		ba_refresh_reordering_mpdus(pAd, pBAEntry);
-
-		NdisAcquireSpinLock(&pAd->BATabLock);
-
-		// Erase Bitmap flag.
-		pBAEntry->LastIndSeq = RESET_RCV_SEQ;
-		pBAEntry->BAWinSize = 0;
-		// Erase Bitmap flag at software mactable
-		pAd->MacTab.Content[Wcid].RXBAbitmap &= (~(1<<(pBAEntry->TID)));
-		pAd->MacTab.Content[Wcid].BARecWcidArray[TID] = 0;
-
-		RT28XX_DEL_BA_SESSION_FROM_ASIC(pAd, Wcid, TID);
-
-		NdisReleaseSpinLock(&pAd->BATabLock);
-
-	}
-
-	BATableFreeRecEntry(pAd, Idx);
-}
-
-VOID BASessionTearDownALL(
-						 IN OUT  PRTMP_ADAPTER pAd,
-						 IN      UCHAR Wcid)
-{
-	int i;
-
-	for (i=0; i<NUM_OF_TID; i++)
-	{
-		BAOriSessionTearDown(pAd, Wcid, i, FALSE, FALSE);
-		BARecSessionTearDown(pAd, Wcid, i, FALSE);
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Retry sending ADDBA Reqest.
-
-	IRQL = DISPATCH_LEVEL
-
-	Parametrs:
-	p8023Header: if this is already 802.3 format, p8023Header is NULL
-
-	Return	: TRUE if put into rx reordering buffer, shouldn't indicaterxhere.
-				FALSE , then continue indicaterx at this moment.
-	==========================================================================
- */
-VOID BAOriSessionSetupTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3)
-{
-	BA_ORI_ENTRY    *pBAEntry = (BA_ORI_ENTRY *)FunctionContext;
-	MAC_TABLE_ENTRY *pEntry;
-	PRTMP_ADAPTER   pAd;
-
-	if (pBAEntry == NULL)
-		return;
-
-	pAd = pBAEntry->pAdapter;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Do nothing if monitor mode is on
-		if (MONITOR_ON(pAd))
-			return;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef RALINK_ATE
-	// Nothing to do in ATE mode.
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	pEntry = &pAd->MacTab.Content[pBAEntry->Wcid];
-
-	if ((pBAEntry->ORI_BA_Status == Originator_WaitRes) && (pBAEntry->Token < ORI_SESSION_MAX_RETRY))
-	{
-		MLME_ADDBA_REQ_STRUCT    AddbaReq;
-
-		NdisZeroMemory(&AddbaReq, sizeof(AddbaReq));
-		COPY_MAC_ADDR(AddbaReq.pAddr, pEntry->Addr);
-		AddbaReq.Wcid = (UCHAR)(pEntry->Aid);
-		AddbaReq.TID = pBAEntry->TID;
-		AddbaReq.BaBufSize = pAd->CommonCfg.BACapability.field.RxBAWinLimit;
-		AddbaReq.TimeOutValue = 0;
-		AddbaReq.Token = pBAEntry->Token;
-		MlmeEnqueue(pAd, ACTION_STATE_MACHINE, MT2_MLME_ADD_BA_CATE, sizeof(MLME_ADDBA_REQ_STRUCT), (PVOID)&AddbaReq);
-		RT28XX_MLME_HANDLER(pAd);
-		//DBGPRINT(RT_DEBUG_TRACE,("BA Ori Session Timeout(%d) : Send ADD BA again\n", pBAEntry->Token));
-
-		DBGPRINT(RT_DEBUG_TRACE,("BA Ori Session Timeout(%d) to %02x:%02x:%02x:%02x:%02x:%02x Tid:%d Wcid:%d\n"
-		,pBAEntry->Token
-		,pEntry->Addr[0],pEntry->Addr[1],pEntry->Addr[2]
-		,pEntry->Addr[3],pEntry->Addr[4],pEntry->Addr[5]
-		,pBAEntry->TID,pEntry->Aid));
-
-		pBAEntry->Token++;
-		RTMPSetTimer(&pBAEntry->ORIBATimer, ORI_BA_SESSION_TIMEOUT);
-	}
-	else
-	{
-		BATableFreeOriEntry(pAd, pEntry->BAOriWcidArray[pBAEntry->TID]);
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		Retry sending ADDBA Reqest.
-
-	IRQL = DISPATCH_LEVEL
-
-	Parametrs:
-	p8023Header: if this is already 802.3 format, p8023Header is NULL
-
-	Return	: TRUE if put into rx reordering buffer, shouldn't indicaterxhere.
-				FALSE , then continue indicaterx at this moment.
-	==========================================================================
- */
-VOID BARecSessionIdleTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3)
-{
-
-	BA_REC_ENTRY    *pBAEntry = (BA_REC_ENTRY *)FunctionContext;
-	PRTMP_ADAPTER   pAd;
-	ULONG           Now32;
-
-	if (pBAEntry == NULL)
-		return;
-
-	if ((pBAEntry->REC_BA_Status == Recipient_Accept))
-	{
-		NdisGetSystemUpTime(&Now32);
-
-		if (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer + REC_BA_SESSION_IDLE_TIMEOUT)))
-		{
-			pAd = pBAEntry->pAdapter;
-			// flush all pending reordering mpdus
-			ba_refresh_reordering_mpdus(pAd, pBAEntry);
-			printk("%ld: REC BA session Timeout\n", Now32);
-		}
-	}
-}
-
-
-VOID PeerAddBAReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-
-{
-	//	7.4.4.1
-	//ULONG	Idx;
-	UCHAR   Status = 1;
-	UCHAR   pAddr[6];
-	FRAME_ADDBA_RSP ADDframe;
-	PUCHAR         pOutBuffer = NULL;
-	NDIS_STATUS     NStatus;
-	PFRAME_ADDBA_REQ  pAddreqFrame = NULL;
-	//UCHAR		BufSize;
-	ULONG       FrameLen;
-	PULONG      ptemp;
-	PMAC_TABLE_ENTRY	pMacEntry;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s ==> (Wcid = %d)\n", __FUNCTION__, Elem->Wcid));
-
-	//hex_dump("AddBAReq", Elem->Msg, Elem->MsgLen);
-
-	//ADDBA Request from unknown peer, ignore this.
-	if (Elem->Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return;
-
-	pMacEntry = &pAd->MacTab.Content[Elem->Wcid];
-	DBGPRINT(RT_DEBUG_TRACE,("BA - PeerAddBAReqAction----> \n"));
-	ptemp = (PULONG)Elem->Msg;
-	//DBGPRINT_RAW(RT_DEBUG_EMU, ("%08x:: %08x:: %08x:: %08x:: %08x:: %08x:: %08x:: %08x:: %08x\n", *(ptemp), *(ptemp+1), *(ptemp+2), *(ptemp+3), *(ptemp+4), *(ptemp+5), *(ptemp+6), *(ptemp+7), *(ptemp+8)));
-
-	if (PeerAddBAReqActionSanity(pAd, Elem->Msg, Elem->MsgLen, pAddr))
-	{
-
-		if ((pAd->CommonCfg.bBADecline == FALSE) && IS_HT_STA(pMacEntry))
-		{
-			pAddreqFrame = (PFRAME_ADDBA_REQ)(&Elem->Msg[0]);
-			printk("Rcv Wcid(%d) AddBAReq\n", Elem->Wcid);
-			if (BARecSessionAdd(pAd, &pAd->MacTab.Content[Elem->Wcid], pAddreqFrame))
-				Status = 0;
-			else
-				Status = 38; // more parameters have invalid values
-		}
-		else
-		{
-			Status = 37; // the request has been declined.
-		}
-	}
-
-	if (pAd->MacTab.Content[Elem->Wcid].ValidAsCLI)
-		ASSERT(pAd->MacTab.Content[Elem->Wcid].Sst == SST_ASSOC);
-
-	pAddreqFrame = (PFRAME_ADDBA_REQ)(&Elem->Msg[0]);
-	// 2. Always send back ADDBA Response
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);	 //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("ACTION - PeerBAAction() allocate memory failed \n"));
-		return;
-	}
-
-	NdisZeroMemory(&ADDframe, sizeof(FRAME_ADDBA_RSP));
-	// 2-1. Prepare ADDBA Response frame.
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (ADHOC_ON(pAd))
-			ActHeaderInit(pAd, &ADDframe.Hdr, pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-		else
-			ActHeaderInit(pAd, &ADDframe.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAddr);
-	}
-#endif // CONFIG_STA_SUPPORT //
-	ADDframe.Category = CATEGORY_BA;
-	ADDframe.Action = ADDBA_RESP;
-	ADDframe.Token = pAddreqFrame->Token;
-	// What is the Status code??  need to check.
-	ADDframe.StatusCode = Status;
-	ADDframe.BaParm.BAPolicy = IMMED_BA;
-	ADDframe.BaParm.AMSDUSupported = 0;
-	ADDframe.BaParm.TID = pAddreqFrame->BaParm.TID;
-	ADDframe.BaParm.BufSize = min(((UCHAR)pAddreqFrame->BaParm.BufSize), (UCHAR)pAd->CommonCfg.BACapability.field.RxBAWinLimit);
-	if (ADDframe.BaParm.BufSize == 0)
-	{
-		ADDframe.BaParm.BufSize = 64;
-	}
-	ADDframe.TimeOutValue = 0; //pAddreqFrame->TimeOutValue;
-
-	*(USHORT *)(&ADDframe.BaParm) = cpu2le16(*(USHORT *)(&ADDframe.BaParm));
-	ADDframe.StatusCode = cpu2le16(ADDframe.StatusCode);
-	ADDframe.TimeOutValue = cpu2le16(ADDframe.TimeOutValue);
-
-	MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-					  sizeof(FRAME_ADDBA_RSP),  &ADDframe,
-			  END_OF_ARGS);
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s(%d): TID(%d), BufSize(%d) <== \n", __FUNCTION__, Elem->Wcid, ADDframe.BaParm.TID,
-							  ADDframe.BaParm.BufSize));
-}
-
-
-VOID PeerAddBARspAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-
-{
-	//UCHAR		Idx, i;
-	//PUCHAR		   pOutBuffer = NULL;
-	PFRAME_ADDBA_RSP    pFrame = NULL;
-	//PBA_ORI_ENTRY		pBAEntry;
-
-	//ADDBA Response from unknown peer, ignore this.
-	if (Elem->Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s ==> Wcid(%d)\n", __FUNCTION__, Elem->Wcid));
-
-	//hex_dump("PeerAddBARspAction()", Elem->Msg, Elem->MsgLen);
-
-	if (PeerAddBARspActionSanity(pAd, Elem->Msg, Elem->MsgLen))
-	{
-		pFrame = (PFRAME_ADDBA_RSP)(&Elem->Msg[0]);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("\t\t StatusCode = %d\n", pFrame->StatusCode));
-		switch (pFrame->StatusCode)
-		{
-			case 0:
-				// I want a BAsession with this peer as an originator.
-				BAOriSessionAdd(pAd, &pAd->MacTab.Content[Elem->Wcid], pFrame);
-				break;
-			default:
-				// check status == USED ???
-				BAOriSessionTearDown(pAd, Elem->Wcid, pFrame->BaParm.TID, TRUE, FALSE);
-				break;
-		}
-		// Rcv Decline StatusCode
-		if ((pFrame->StatusCode == 37)
-#ifdef CONFIG_STA_SUPPORT
-            || ((pAd->OpMode == OPMODE_STA) && STA_TGN_WIFI_ON(pAd) && (pFrame->StatusCode != 0))
-#endif // CONFIG_STA_SUPPORT //
-            )
-		{
-			pAd->MacTab.Content[Elem->Wcid].BADeclineBitmap |= 1<<pFrame->BaParm.TID;
-		}
-	}
-}
-
-VOID PeerDelBAAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-
-{
-	//UCHAR				Idx;
-	//PUCHAR				pOutBuffer = NULL;
-	PFRAME_DELBA_REQ    pDelFrame = NULL;
-
-	DBGPRINT(RT_DEBUG_TRACE,("%s ==>\n", __FUNCTION__));
-	//DELBA Request from unknown peer, ignore this.
-	if (PeerDelBAActionSanity(pAd, Elem->Wcid, Elem->Msg, Elem->MsgLen))
-	{
-		pDelFrame = (PFRAME_DELBA_REQ)(&Elem->Msg[0]);
-		if (pDelFrame->DelbaParm.Initiator == ORIGINATOR)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("BA - PeerDelBAAction----> ORIGINATOR\n"));
-			BARecSessionTearDown(pAd, Elem->Wcid, pDelFrame->DelbaParm.TID, TRUE);
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("BA - PeerDelBAAction----> RECIPIENT, Reason = %d\n",  pDelFrame->ReasonCode));
-			//hex_dump("DelBA Frame", pDelFrame, Elem->MsgLen);
-			BAOriSessionTearDown(pAd, Elem->Wcid, pDelFrame->DelbaParm.TID, TRUE, FALSE);
-		}
-	}
-}
-
-
-BOOLEAN CntlEnqueueForRecv(
-						  IN PRTMP_ADAPTER		pAd,
-						  IN ULONG				Wcid,
-						  IN ULONG				MsgLen,
-						  IN PFRAME_BA_REQ		pMsg)
-{
-	PFRAME_BA_REQ   pFrame = pMsg;
-	//PRTMP_REORDERBUF	pBuffer;
-	//PRTMP_REORDERBUF	pDmaBuf;
-	PBA_REC_ENTRY pBAEntry;
-	//BOOLEAN 	Result;
-	ULONG   Idx;
-	//UCHAR	NumRxPkt;
-	UCHAR	TID;//, i;
-
-	TID = (UCHAR)pFrame->BARControl.TID;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s(): BAR-Wcid(%ld), Tid (%d)\n", __FUNCTION__, Wcid, TID));
-	//hex_dump("BAR", (PCHAR) pFrame, MsgLen);
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return FALSE;
-
-	// First check the size, it MUST not exceed the mlme queue size
-	if (MsgLen > MGMT_DMA_BUFFER_SIZE)
-	{
-		DBGPRINT_ERR(("CntlEnqueueForRecv: frame too large, size = %ld \n", MsgLen));
-		return FALSE;
-	}
-	else if (MsgLen != sizeof(FRAME_BA_REQ))
-	{
-		DBGPRINT_ERR(("CntlEnqueueForRecv: BlockAck Request frame length size = %ld incorrect\n", MsgLen));
-		return FALSE;
-	}
-	else if (MsgLen != sizeof(FRAME_BA_REQ))
-	{
-		DBGPRINT_ERR(("CntlEnqueueForRecv: BlockAck Request frame length size = %ld incorrect\n", MsgLen));
-		return FALSE;
-	}
-
-	if ((Wcid < MAX_LEN_OF_MAC_TABLE) && (TID < 8))
-		{
-		// if this receiving packet is from SA that is in our OriEntry. Since WCID <9 has direct mapping. no need search.
-		Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID];
-		pBAEntry = &pAd->BATable.BARecEntry[Idx];
-		}
-		else
-		{
-		return FALSE;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("BAR(%ld) : Tid (%d) - %04x:%04x\n", Wcid, TID, pFrame->BAStartingSeq.field.StartSeq, pBAEntry->LastIndSeq ));
-
-	if (SEQ_SMALLER(pBAEntry->LastIndSeq, pFrame->BAStartingSeq.field.StartSeq, MAXSEQ))
-	{
-		//printk("BAR Seq = %x, LastIndSeq = %x\n", pFrame->BAStartingSeq.field.StartSeq, pBAEntry->LastIndSeq);
-		ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, pFrame->BAStartingSeq.field.StartSeq);
-		pBAEntry->LastIndSeq = (pFrame->BAStartingSeq.field.StartSeq == 0) ? MAXSEQ :(pFrame->BAStartingSeq.field.StartSeq -1);
-	}
-	//ba_refresh_reordering_mpdus(pAd, pBAEntry);
-	return TRUE;
-}
-
-/*
-Description : Send PSMP Action frame If PSMP mode switches.
-*/
-VOID SendPSMPAction(
-				   IN PRTMP_ADAPTER		pAd,
-				   IN UCHAR				Wcid,
-				   IN UCHAR				Psmp)
-{
-	PUCHAR          pOutBuffer = NULL;
-	NDIS_STATUS     NStatus;
-	//ULONG           Idx;
-	FRAME_PSMP_ACTION   Frame;
-	ULONG           FrameLen;
-#ifdef RT30xx
-	UCHAR			bbpdata=0;
-	UINT32			macdata;
-#endif // RT30xx //
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);	 //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("BA - MlmeADDBAAction() allocate memory failed \n"));
-		return;
-	}
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		ActHeaderInit(pAd, &Frame.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->MacTab.Content[Wcid].Addr);
-#endif // CONFIG_STA_SUPPORT //
-
-	Frame.Category = CATEGORY_HT;
-	Frame.Action = SMPS_ACTION;
-	switch (Psmp)
-	{
-		case MMPS_ENABLE:
-#ifdef RT30xx
-			if (IS_RT3090(pAd))
-			{
-				// disable MMPS BBP control register
-				RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &bbpdata);
-				bbpdata &= ~(0x04);	//bit 2
-				RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, bbpdata);
-
-				// disable MMPS MAC control register
-				RTMP_IO_READ32(pAd, 0x1210, &macdata);
-				macdata &= ~(0x09);	//bit 0, 3
-				RTMP_IO_WRITE32(pAd, 0x1210, macdata);
-			}
-#endif // RT30xx //
-			Frame.Psmp = 0;
-			break;
-		case MMPS_DYNAMIC:
-#ifdef RT30xx
-			if (IS_RT3090(pAd))
-			{
-				// enable MMPS BBP control register
-				RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &bbpdata);
-				bbpdata |= 0x04;	//bit 2
-				RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, bbpdata);
-
-				// enable MMPS MAC control register
-				RTMP_IO_READ32(pAd, 0x1210, &macdata);
-				macdata |= 0x09;	//bit 0, 3
-				RTMP_IO_WRITE32(pAd, 0x1210, macdata);
-			}
-#endif // RT30xx //
-			Frame.Psmp = 3;
-			break;
-		case MMPS_STATIC:
-#ifdef RT30xx
-			if (IS_RT3090(pAd))
-			{
-				// enable MMPS BBP control register
-				RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &bbpdata);
-				bbpdata |= 0x04;	//bit 2
-				RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, bbpdata);
-
-				// enable MMPS MAC control register
-				RTMP_IO_READ32(pAd, 0x1210, &macdata);
-				macdata |= 0x09;	//bit 0, 3
-				RTMP_IO_WRITE32(pAd, 0x1210, macdata);
-			}
-#endif // RT30xx //
-			Frame.Psmp = 1;
-			break;
-	}
-	MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-					  sizeof(FRAME_PSMP_ACTION),      &Frame,
-					  END_OF_ARGS);
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-	DBGPRINT(RT_DEBUG_ERROR,("HT - SendPSMPAction( %d )  \n", Frame.Psmp));
-}
-
-
-#define RADIO_MEASUREMENT_REQUEST_ACTION	0
-
-typedef struct PACKED
-{
-	UCHAR	RegulatoryClass;
-	UCHAR	ChannelNumber;
-	USHORT	RandomInterval;
-	USHORT	MeasurementDuration;
-	UCHAR	MeasurementMode;
-	UCHAR   BSSID[MAC_ADDR_LEN];
-	UCHAR	ReportingCondition;
-	UCHAR	Threshold;
-	UCHAR   SSIDIE[2];			// 2 byte
-} BEACON_REQUEST;
-
-typedef struct PACKED
-{
-	UCHAR	ID;
-	UCHAR	Length;
-	UCHAR	Token;
-	UCHAR	RequestMode;
-	UCHAR	Type;
-} MEASUREMENT_REQ;
-
-
-
-
-void convert_reordering_packet_to_preAMSDU_or_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN  UCHAR			FromWhichBSSID)
-{
-	PNDIS_PACKET	pRxPkt;
-	UCHAR			Header802_3[LENGTH_802_3];
-
-	// 1. get 802.3 Header
-	// 2. remove LLC
-	// 		a. pointer pRxBlk->pData to payload
-	//      b. modify pRxBlk->DataSize
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
-#endif // CONFIG_STA_SUPPORT //
-
-	ASSERT(pRxBlk->pRxPacket);
-	pRxPkt = RTPKT_TO_OSPKT(pRxBlk->pRxPacket);
-
-	RTPKT_TO_OSPKT(pRxPkt)->dev = get_netdev_from_bssid(pAd, FromWhichBSSID);
-	RTPKT_TO_OSPKT(pRxPkt)->data = pRxBlk->pData;
-	RTPKT_TO_OSPKT(pRxPkt)->len = pRxBlk->DataSize;
-	RTPKT_TO_OSPKT(pRxPkt)->tail = RTPKT_TO_OSPKT(pRxPkt)->data + RTPKT_TO_OSPKT(pRxPkt)->len;
-
-	//
-	// copy 802.3 header, if necessary
-	//
-	if (!RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU))
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-#ifdef LINUX
-			NdisMoveMemory(skb_push(pRxPkt, LENGTH_802_3), Header802_3, LENGTH_802_3);
-#endif
-#ifdef UCOS
-			NdisMoveMemory(net_pkt_push(pRxPkt, LENGTH_802_3), Header802_3, LENGTH_802_3);
-#endif
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-}
-
-
-#define INDICATE_LEGACY_OR_AMSDU(_pAd, _pRxBlk, _fromWhichBSSID)		\
-	do																	\
-	{																	\
-    	if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_AMSDU))						\
-    	{																\
-    		Indicate_AMSDU_Packet(_pAd, _pRxBlk, _fromWhichBSSID);		\
-    	}																\
-		else if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_EAP))					\
-		{																\
-			Indicate_EAPOL_Packet(_pAd, _pRxBlk, _fromWhichBSSID);		\
-		}																\
-    	else															\
-    	{																\
-    		Indicate_Legacy_Packet(_pAd, _pRxBlk, _fromWhichBSSID);		\
-    	}																\
-	} while (0);
-
-
-
-static VOID ba_enqueue_reordering_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PBA_REC_ENTRY	pBAEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	struct reordering_mpdu *mpdu_blk;
-	UINT16	Sequence = (UINT16) pRxBlk->pHeader->Sequence;
-
-	mpdu_blk = ba_mpdu_blk_alloc(pAd);
-	if (mpdu_blk != NULL)
-	{
-		// Write RxD buffer address & allocated buffer length
-		NdisAcquireSpinLock(&pBAEntry->RxReRingLock);
-
-		mpdu_blk->Sequence = Sequence;
-
-		mpdu_blk->bAMSDU = RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU);
-
-		convert_reordering_packet_to_preAMSDU_or_802_3_packet(pAd, pRxBlk, FromWhichBSSID);
-
-		STATS_INC_RX_PACKETS(pAd, FromWhichBSSID);
-
-        //
-		// it is necessary for reordering packet to record
-		// which BSS it come from
-		//
-		RTMP_SET_PACKET_IF(pRxBlk->pRxPacket, FromWhichBSSID);
-
-		mpdu_blk->pPacket = pRxBlk->pRxPacket;
-
-		if (ba_reordering_mpdu_insertsorted(&pBAEntry->list, mpdu_blk) == FALSE)
-		{
-			// had been already within reordering list
-			// don't indicate
-			RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_SUCCESS);
-			ba_mpdu_blk_free(pAd, mpdu_blk);
-		}
-
-		ASSERT((0<= pBAEntry->list.qlen)  && (pBAEntry->list.qlen <= pBAEntry->BAWinSize));
-		NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR,  ("!!! (%d) Can't allocate reordering mpdu blk\n",
-								   pBAEntry->list.qlen));
-		/*
-		 * flush all pending reordering mpdus
-		 * and receving mpdu to upper layer
-		 * make tcp/ip to take care reordering mechanism
-		 */
-		//ba_refresh_reordering_mpdus(pAd, pBAEntry);
-		ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, Sequence);
-
-		pBAEntry->LastIndSeq = Sequence;
-		INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Indicate this packet to upper layer or put it into reordering buffer
-
-	Parametrs:
-		pRxBlk         : carry necessary packet info 802.11 format
-		FromWhichBSSID : the packet received from which BSS
-
-	Return	:
-			  none
-
-	Note    :
-	          the packet queued into reordering buffer need to cover to 802.3 format
-			  or pre_AMSDU format
-	==========================================================================
- */
-
-VOID Indicate_AMPDU_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	USHORT				Idx;
-	PBA_REC_ENTRY		pBAEntry = NULL;
-	UINT16				Sequence = pRxBlk->pHeader->Sequence;
-	ULONG				Now32;
-	UCHAR				Wcid = pRxBlk->pRxWI->WirelessCliID;
-	UCHAR				TID = pRxBlk->pRxWI->TID;
-
-
-	if (!RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU) &&  (pRxBlk->DataSize > MAX_RX_PKT_LEN))
-	{
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-	if (Wcid < MAX_LEN_OF_MAC_TABLE)
-	{
-		Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID];
-		if (Idx == 0)
-		{
-			/* Rec BA Session had been torn down */
-			INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
-			return;
-		}
-		pBAEntry = &pAd->BATable.BARecEntry[Idx];
-	}
-	else
-	{
-		// impossible !!!
-		ASSERT(0);
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-	ASSERT(pBAEntry);
-
-	// update last rx time
-	NdisGetSystemUpTime(&Now32);
-
-	pBAEntry->rcvSeq = Sequence;
-
-
-	ba_flush_reordering_timeout_mpdus(pAd, pBAEntry, Now32);
-	pBAEntry->LastIndSeqAtTimer = Now32;
-
-	//
-	// Reset Last Indicate Sequence
-	//
-	if (pBAEntry->LastIndSeq == RESET_RCV_SEQ)
-	{
-		ASSERT((pBAEntry->list.qlen == 0) && (pBAEntry->list.next == NULL));
-
-		// reset rcv sequence of BA session
-		pBAEntry->LastIndSeq = Sequence;
-		pBAEntry->LastIndSeqAtTimer = Now32;
-		INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
-		return;
-	}
-
-
-	//
-	// I. Check if in order.
-	//
-	if (SEQ_STEPONE(Sequence, pBAEntry->LastIndSeq, MAXSEQ))
-	{
-		USHORT  LastIndSeq;
-
-		pBAEntry->LastIndSeq = Sequence;
-		INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID);
- 		LastIndSeq = ba_indicate_reordering_mpdus_in_order(pAd, pBAEntry, pBAEntry->LastIndSeq);
-		if (LastIndSeq != RESET_RCV_SEQ)
-		{
-			pBAEntry->LastIndSeq = LastIndSeq;
-		}
-		pBAEntry->LastIndSeqAtTimer = Now32;
-	}
-	//
-	// II. Drop Duplicated Packet
-	//
-	else if (Sequence == pBAEntry->LastIndSeq)
-	{
-
-		// drop and release packet
-		pBAEntry->nDropPacket++;
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-	}
-	//
-	// III. Drop Old Received Packet
-	//
-	else if (SEQ_SMALLER(Sequence, pBAEntry->LastIndSeq, MAXSEQ))
-	{
-
-		// drop and release packet
-		pBAEntry->nDropPacket++;
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-	}
-	//
-	// IV. Receive Sequence within Window Size
-	//
-	else if (SEQ_SMALLER(Sequence, (((pBAEntry->LastIndSeq+pBAEntry->BAWinSize+1)) & MAXSEQ), MAXSEQ))
-	{
-		ba_enqueue_reordering_packet(pAd, pBAEntry, pRxBlk, FromWhichBSSID);
-	}
-	//
-	// V. Receive seq surpasses Win(lastseq + nMSDU). So refresh all reorder buffer
-	//
-	else
-	{
-		LONG WinStartSeq, TmpSeq;
-
-
-		TmpSeq = Sequence - (pBAEntry->BAWinSize) -1;
-		if (TmpSeq < 0)
-		{
-			TmpSeq = (MAXSEQ+1) + TmpSeq;
-		}
-		WinStartSeq = (TmpSeq+1) & MAXSEQ;
-		ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, WinStartSeq);
-		pBAEntry->LastIndSeq = WinStartSeq; //TmpSeq;
-
-		pBAEntry->LastIndSeqAtTimer = Now32;
-
-		ba_enqueue_reordering_packet(pAd, pBAEntry, pRxBlk, FromWhichBSSID);
-
-		TmpSeq = ba_indicate_reordering_mpdus_in_order(pAd, pBAEntry, pBAEntry->LastIndSeq);
-		if (TmpSeq != RESET_RCV_SEQ)
-		{
-			pBAEntry->LastIndSeq = TmpSeq;
-		}
-	}
-}
-
-#endif // DOT11_N_SUPPORT //
-
+#include "../../rt2870/common/ba_action.c"
diff --git a/drivers/staging/rt3070/common/cmm_data.c b/drivers/staging/rt3070/common/cmm_data.c
index 85f92b9..02e202d 100644
--- a/drivers/staging/rt3070/common/cmm_data.c
+++ b/drivers/staging/rt3070/common/cmm_data.c
@@ -1,2827 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-*/
-
-#include "../rt_config.h"
-
-#define MAX_TX_IN_TBTT		(16)
-
-
-UCHAR	SNAP_802_1H[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00};
-UCHAR	SNAP_BRIDGE_TUNNEL[] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0xf8};
-// Add Cisco Aironet SNAP heade for CCX2 support
-UCHAR	SNAP_AIRONET[] = {0xaa, 0xaa, 0x03, 0x00, 0x40, 0x96, 0x00, 0x00};
-UCHAR	CKIP_LLC_SNAP[] = {0xaa, 0xaa, 0x03, 0x00, 0x40, 0x96, 0x00, 0x02};
-UCHAR	EAPOL_LLC_SNAP[]= {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00, 0x88, 0x8e};
-UCHAR	EAPOL[] = {0x88, 0x8e};
-UCHAR   TPID[] = {0x81, 0x00}; /* VLAN related */
-
-UCHAR	IPX[] = {0x81, 0x37};
-UCHAR	APPLE_TALK[] = {0x80, 0xf3};
-UCHAR	RateIdToPlcpSignal[12] = {
-	 0, /* RATE_1 */	1, /* RATE_2 */ 	2, /* RATE_5_5 */	3, /* RATE_11 */	// see BBP spec
-	11, /* RATE_6 */   15, /* RATE_9 */    10, /* RATE_12 */   14, /* RATE_18 */	// see IEEE802.11a-1999 p.14
-	 9, /* RATE_24 */  13, /* RATE_36 */	8, /* RATE_48 */   12  /* RATE_54 */ }; // see IEEE802.11a-1999 p.14
-
-UCHAR	 OfdmSignalToRateId[16] = {
-	RATE_54,  RATE_54,	RATE_54,  RATE_54,	// OFDM PLCP Signal = 0,  1,  2,  3 respectively
-	RATE_54,  RATE_54,	RATE_54,  RATE_54,	// OFDM PLCP Signal = 4,  5,  6,  7 respectively
-	RATE_48,  RATE_24,	RATE_12,  RATE_6,	// OFDM PLCP Signal = 8,  9,  10, 11 respectively
-	RATE_54,  RATE_36,	RATE_18,  RATE_9,	// OFDM PLCP Signal = 12, 13, 14, 15 respectively
-};
-
-UCHAR	 OfdmRateToRxwiMCS[12] = {
-	0,  0,	0,  0,
-	0,  1,	2,  3,	// OFDM rate 6,9,12,18 = rxwi mcs 0,1,2,3
-	4,  5,	6,  7,	// OFDM rate 24,36,48,54 = rxwi mcs 4,5,6,7
-};
-UCHAR	 RxwiMCSToOfdmRate[12] = {
-	RATE_6,  RATE_9,	RATE_12,  RATE_18,
-	RATE_24,  RATE_36,	RATE_48,  RATE_54,	// OFDM rate 6,9,12,18 = rxwi mcs 0,1,2,3
-	4,  5,	6,  7,	// OFDM rate 24,36,48,54 = rxwi mcs 4,5,6,7
-};
-
-char*   MCSToMbps[] = {"1Mbps","2Mbps","5.5Mbps","11Mbps","06Mbps","09Mbps","12Mbps","18Mbps","24Mbps","36Mbps","48Mbps","54Mbps","MM-0","MM-1","MM-2","MM-3","MM-4","MM-5","MM-6","MM-7","MM-8","MM-9","MM-10","MM-11","MM-12","MM-13","MM-14","MM-15","MM-32","ee1","ee2","ee3"};
-
-UCHAR default_cwmin[]={CW_MIN_IN_BITS, CW_MIN_IN_BITS, CW_MIN_IN_BITS-1, CW_MIN_IN_BITS-2};
-//UCHAR default_cwmax[]={CW_MAX_IN_BITS, CW_MAX_IN_BITS, CW_MIN_IN_BITS, CW_MIN_IN_BITS-1};
-UCHAR default_sta_aifsn[]={3,7,2,2};
-
-UCHAR MapUserPriorityToAccessCategory[8] = {QID_AC_BE, QID_AC_BK, QID_AC_BK, QID_AC_BE, QID_AC_VI, QID_AC_VI, QID_AC_VO, QID_AC_VO};
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		API for MLME to transmit management frame to AP (BSS Mode)
-	or station (IBSS Mode)
-
-	Arguments:
-		pAd Pointer to our adapter
-		pData		Pointer to the outgoing 802.11 frame
-		Length		Size of outgoing management frame
-
-	Return Value:
-		NDIS_STATUS_FAILURE
-		NDIS_STATUS_PENDING
-		NDIS_STATUS_SUCCESS
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS MiniportMMRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			QueIdx,
-	IN	PUCHAR			pData,
-	IN	UINT			Length)
-{
-	PNDIS_PACKET	pPacket;
-	NDIS_STATUS  	Status = NDIS_STATUS_SUCCESS;
-	ULONG	 		FreeNum;
-	UCHAR			IrqState;
-	UCHAR			rtmpHwHdr[TXINFO_SIZE + TXWI_SIZE]; //RTMP_HW_HDR_LEN];
-
-	ASSERT(Length <= MGMT_DMA_BUFFER_SIZE);
-
-	QueIdx=3;
-
-	// 2860C use Tx Ring
-
-	IrqState = pAd->irq_disabled;
-
-	do
-	{
-		// Reset is in progress, stop immediately
-		if ( RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS) ||
-			 RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST)||
-			 !RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP))
-		{
-			Status = NDIS_STATUS_FAILURE;
-			break;
-		}
-
-		// Check Free priority queue
-		// Since we use PBF Queue2 for management frame.  Its corresponding DMA ring should be using TxRing.
-
-		// 2860C use Tx Ring
-		if (pAd->MACVersion == 0x28600100)
-		{
-			FreeNum = GET_TXRING_FREENO(pAd, QueIdx);
-		}
-		else
-		{
-			FreeNum = GET_MGMTRING_FREENO(pAd);
-		}
-
-		if ((FreeNum > 0))
-		{
-			// We need to reserve space for rtmp hardware header. i.e., TxWI for RT2860 and TxInfo+TxWI for RT2870
-			NdisZeroMemory(&rtmpHwHdr, (TXINFO_SIZE + TXWI_SIZE));
-			Status = RTMPAllocateNdisPacket(pAd, &pPacket, (PUCHAR)&rtmpHwHdr, (TXINFO_SIZE + TXWI_SIZE), pData, Length);
-			if (Status != NDIS_STATUS_SUCCESS)
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("MiniportMMRequest (error:: can't allocate NDIS PACKET)\n"));
-				break;
-			}
-
-			//pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_CCK;
-			//pAd->CommonCfg.MlmeRate = RATE_2;
-
-
-			Status = MlmeHardTransmit(pAd, QueIdx, pPacket);
-			if (Status != NDIS_STATUS_SUCCESS)
-				RTMPFreeNdisPacket(pAd, pPacket);
-		}
-		else
-		{
-			pAd->RalinkCounters.MgmtRingFullCount++;
-			DBGPRINT(RT_DEBUG_ERROR, ("Qidx(%d), not enough space in MgmtRing, MgmtRingFullCount=%ld!\n",
-										QueIdx, pAd->RalinkCounters.MgmtRingFullCount));
-		}
-
-	} while (FALSE);
-
-
-	return Status;
-}
-
-
-
-NDIS_STATUS MlmeDataHardTransmit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR	QueIdx,
-	IN	PNDIS_PACKET	pPacket);
-
-#define MAX_DATAMM_RETRY	3
-/*
-	========================================================================
-
-	Routine Description:
-		API for MLME to transmit management frame to AP (BSS Mode)
-	or station (IBSS Mode)
-
-	Arguments:
-		pAd Pointer to our adapter
-		pData		Pointer to the outgoing 802.11 frame
-		Length		Size of outgoing management frame
-
-	Return Value:
-		NDIS_STATUS_FAILURE
-		NDIS_STATUS_PENDING
-		NDIS_STATUS_SUCCESS
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS MiniportDataMMRequest(
-							 IN  PRTMP_ADAPTER   pAd,
-							 IN  UCHAR           QueIdx,
-							 IN  PUCHAR          pData,
-							 IN  UINT            Length)
-{
-	PNDIS_PACKET    pPacket;
-	NDIS_STATUS  Status = NDIS_STATUS_SUCCESS;
-	ULONG    FreeNum;
-	int 	retry = 0;
-	UCHAR           IrqState;
-	UCHAR			rtmpHwHdr[TXINFO_SIZE + TXWI_SIZE]; //RTMP_HW_HDR_LEN];
-
-	ASSERT(Length <= MGMT_DMA_BUFFER_SIZE);
-
-	// 2860C use Tx Ring
-	IrqState = pAd->irq_disabled;
-
-	do
-	{
-		// Reset is in progress, stop immediately
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS) ||
-			 RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST)||
-			!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP))
-		{
-			Status = NDIS_STATUS_FAILURE;
-			break;
-		}
-
-		// Check Free priority queue
-		// Since we use PBF Queue2 for management frame.  Its corresponding DMA ring should be using TxRing.
-
-		// 2860C use Tx Ring
-
-		// free Tx(QueIdx) resources
-		FreeNum = GET_TXRING_FREENO(pAd, QueIdx);
-
-		if ((FreeNum > 0))
-		{
-			// We need to reserve space for rtmp hardware header. i.e., TxWI for RT2860 and TxInfo+TxWI for RT2870
-			NdisZeroMemory(&rtmpHwHdr, (TXINFO_SIZE + TXWI_SIZE));
-			Status = RTMPAllocateNdisPacket(pAd, &pPacket, (PUCHAR)&rtmpHwHdr, (TXINFO_SIZE + TXWI_SIZE), pData, Length);
-			if (Status != NDIS_STATUS_SUCCESS)
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("MiniportMMRequest (error:: can't allocate NDIS PACKET)\n"));
-				break;
-			}
-
-			//pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_CCK;
-			//pAd->CommonCfg.MlmeRate = RATE_2;
-
-
-			Status = MlmeDataHardTransmit(pAd, QueIdx, pPacket);
-			if (Status != NDIS_STATUS_SUCCESS)
-				RTMPFreeNdisPacket(pAd, pPacket);
-			retry = MAX_DATAMM_RETRY;
-		}
-		else
-		{
-			retry ++;
-
-			printk("retry %d\n", retry);
-			pAd->RalinkCounters.MgmtRingFullCount++;
-
-			if (retry >= MAX_DATAMM_RETRY)
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("Qidx(%d), not enough space in DataRing, MgmtRingFullCount=%ld!\n",
-											QueIdx, pAd->RalinkCounters.MgmtRingFullCount));
-			}
-		}
-
-	} while (retry < MAX_DATAMM_RETRY);
-
-
-	return Status;
-}
-
-
-
-
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Copy frame from waiting queue into relative ring buffer and set
-	appropriate ASIC register to kick hardware transmit function
-
-	Arguments:
-		pAd Pointer to our adapter
-		pBuffer 	Pointer to	memory of outgoing frame
-		Length		Size of outgoing management frame
-
-	Return Value:
-		NDIS_STATUS_FAILURE
-		NDIS_STATUS_PENDING
-		NDIS_STATUS_SUCCESS
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS MlmeHardTransmit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			QueIdx,
-	IN	PNDIS_PACKET	pPacket)
-{
-	if ((pAd->CommonCfg.RadarDetect.RDMode != RD_NORMAL_MODE)
-#ifdef CARRIER_DETECTION_SUPPORT
-#endif // CARRIER_DETECTION_SUPPORT //
-		)
-	{
-		return NDIS_STATUS_FAILURE;
-	}
-
-		return MlmeHardTransmitMgmtRing(pAd,QueIdx,pPacket);
-
-}
-
-NDIS_STATUS MlmeDataHardTransmit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR	QueIdx,
-	IN	PNDIS_PACKET	pPacket)
-{
-	if ((pAd->CommonCfg.RadarDetect.RDMode != RD_NORMAL_MODE)
-#ifdef CARRIER_DETECTION_SUPPORT
-#endif // CARRIER_DETECTION_SUPPORT //
-		)
-	{
-		return NDIS_STATUS_FAILURE;
-	}
-
-#ifdef RT2870
-	return MlmeHardTransmitMgmtRing(pAd,QueIdx,pPacket);
-#endif // RT2870 //
-}
-
-
-
-
-
-NDIS_STATUS MlmeHardTransmitMgmtRing(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR	QueIdx,
-	IN	PNDIS_PACKET	pPacket)
-{
-	PACKET_INFO 	PacketInfo;
-	PUCHAR			pSrcBufVA;
-	UINT			SrcBufLen;
-	PHEADER_802_11	pHeader_802_11;
-	BOOLEAN 		bAckRequired, bInsertTimestamp;
-	UCHAR			MlmeRate;
-	PTXWI_STRUC 	pFirstTxWI;
-	MAC_TABLE_ENTRY	*pMacEntry = NULL;
-
-	RTMP_QueryPacketInfo(pPacket, &PacketInfo, &pSrcBufVA, &SrcBufLen);
-
-	// Make sure MGMT ring resource won't be used by other threads
-// sample, for IRQ LOCK -> SEM LOCK
-//	IrqState = pAd->irq_disabled;
-//	if (!IrqState)
-		RTMP_SEM_LOCK(&pAd->MgmtRingLock);
-
-
-	if (pSrcBufVA == NULL)
-	{
-		// The buffer shouldn't be NULL
-//		if (!IrqState)
-			RTMP_SEM_UNLOCK(&pAd->MgmtRingLock);
-		return NDIS_STATUS_FAILURE;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// outgoing frame always wakeup PHY to prevent frame lost
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-			AsicForceWakeup(pAd, TRUE);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	pFirstTxWI = (PTXWI_STRUC)(pSrcBufVA +  TXINFO_SIZE);
-	pHeader_802_11 = (PHEADER_802_11) (pSrcBufVA + TXINFO_SIZE + TXWI_SIZE); //TXWI_SIZE);
-
-	if (pHeader_802_11->Addr1[0] & 0x01)
-	{
-		MlmeRate = pAd->CommonCfg.BasicMlmeRate;
-	}
-	else
-	{
-		MlmeRate = pAd->CommonCfg.MlmeRate;
-	}
-
-	// Verify Mlme rate for a / g bands.
-	if ((pAd->LatchRfRegs.Channel > 14) && (MlmeRate < RATE_6)) // 11A band
-		MlmeRate = RATE_6;
-
-	if ((pHeader_802_11->FC.Type == BTYPE_DATA) &&
-		(pHeader_802_11->FC.SubType == SUBTYPE_QOS_NULL))
-	{
-		pMacEntry = MacTableLookup(pAd, pHeader_802_11->Addr1);
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Fixed W52 with Activity scan issue in ABG_MIXED and ABGN_MIXED mode.
-		if (pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED
-#ifdef DOT11_N_SUPPORT
-			|| pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED
-#endif // DOT11_N_SUPPORT //
-		)
-		{
-			if (pAd->LatchRfRegs.Channel > 14)
-				pAd->CommonCfg.MlmeTransmit.field.MODE = 1;
-			else
-				pAd->CommonCfg.MlmeTransmit.field.MODE = 0;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	//
-	// Should not be hard code to set PwrMgmt to 0 (PWR_ACTIVE)
-	// Snice it's been set to 0 while on MgtMacHeaderInit
-	// By the way this will cause frame to be send on PWR_SAVE failed.
-	//
-	// pHeader_802_11->FC.PwrMgmt = 0; // (pAd->StaCfg.Psm == PWR_SAVE);
-	//
-	// In WMM-UAPSD, mlme frame should be set psm as power saving but probe request frame
-#ifdef CONFIG_STA_SUPPORT
-    // Data-Null packets alse pass through MMRequest in RT2860, however, we hope control the psm bit to pass APSD
-	if ((pHeader_802_11->FC.Type != BTYPE_DATA) && (pHeader_802_11->FC.Type != BTYPE_CNTL))
-	{
-		if ((pAd->StaCfg.Psm == PWR_SAVE) &&
-			(pHeader_802_11->FC.SubType == SUBTYPE_ACTION))
-			pHeader_802_11->FC.PwrMgmt = PWR_SAVE;
-		else
-			pHeader_802_11->FC.PwrMgmt = PWR_ACTIVE;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	bInsertTimestamp = FALSE;
-	if (pHeader_802_11->FC.Type == BTYPE_CNTL) // must be PS-POLL
-	{
-#ifdef CONFIG_STA_SUPPORT
-		//Set PM bit in ps-poll, to fix WLK 1.2  PowerSaveMode_ext failure issue.
-		if ((pAd->OpMode == OPMODE_STA) && (pHeader_802_11->FC.SubType == SUBTYPE_PS_POLL))
-		{
-			pHeader_802_11->FC.PwrMgmt = PWR_SAVE;
-		}
-#endif // CONFIG_STA_SUPPORT //
-		bAckRequired = FALSE;
-	}
-	else // BTYPE_MGMT or BTYPE_DATA(must be NULL frame)
-	{
-		//pAd->Sequence++;
-		//pHeader_802_11->Sequence = pAd->Sequence;
-
-		if (pHeader_802_11->Addr1[0] & 0x01) // MULTICAST, BROADCAST
-		{
-			bAckRequired = FALSE;
-			pHeader_802_11->Duration = 0;
-		}
-		else
-		{
-			bAckRequired = TRUE;
-			pHeader_802_11->Duration = RTMPCalcDuration(pAd, MlmeRate, 14);
-			if (pHeader_802_11->FC.SubType == SUBTYPE_PROBE_RSP)
-			{
-				bInsertTimestamp = TRUE;
-			}
-		}
-	}
-
-	pHeader_802_11->Sequence = pAd->Sequence++;
-	if (pAd->Sequence >0xfff)
-		pAd->Sequence = 0;
-
-	// Before radar detection done, mgmt frame can not be sent but probe req
-	// Because we need to use probe req to trigger driver to send probe req in passive scan
-	if ((pHeader_802_11->FC.SubType != SUBTYPE_PROBE_REQ)
-		&& (pAd->CommonCfg.bIEEE80211H == 1)
-		&& (pAd->CommonCfg.RadarDetect.RDMode != RD_NORMAL_MODE))
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("MlmeHardTransmit --> radar detect not in normal mode !!!\n"));
-//		if (!IrqState)
-			RTMP_SEM_UNLOCK(&pAd->MgmtRingLock);
-		return (NDIS_STATUS_FAILURE);
-	}
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pHeader_802_11, DIR_WRITE, FALSE);
-#endif
-
-	//
-	// fill scatter-and-gather buffer list into TXD. Internally created NDIS PACKET
-	// should always has only one ohysical buffer, and the whole frame size equals
-	// to the first scatter buffer size
-	//
-
-	// Initialize TX Descriptor
-	// For inter-frame gap, the number is for this frame and next frame
-	// For MLME rate, we will fix as 2Mb to match other vendor's implement
-//	pAd->CommonCfg.MlmeTransmit.field.MODE = 1;
-
-// management frame doesn't need encryption. so use RESERVED_WCID no matter u are sending to specific wcid or not.
-	if (pMacEntry == NULL)
-	{
-		RTMPWriteTxWI(pAd, pFirstTxWI, FALSE, FALSE, bInsertTimestamp, FALSE, bAckRequired, FALSE,
-		0, RESERVED_WCID, (SrcBufLen - TXINFO_SIZE - TXWI_SIZE), PID_MGMT, 0,  (UCHAR)pAd->CommonCfg.MlmeTransmit.field.MCS, IFS_BACKOFF, FALSE, &pAd->CommonCfg.MlmeTransmit);
-	}
-	else
-	{
-		RTMPWriteTxWI(pAd, pFirstTxWI, FALSE, FALSE,
-					bInsertTimestamp, FALSE, bAckRequired, FALSE,
-					0, pMacEntry->Aid, (SrcBufLen - TXINFO_SIZE - TXWI_SIZE),
-					pMacEntry->MaxHTPhyMode.field.MCS, 0,
-					(UCHAR)pMacEntry->MaxHTPhyMode.field.MCS,
-					IFS_BACKOFF, FALSE, &pMacEntry->MaxHTPhyMode);
-	}
-
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange((PUCHAR)pFirstTxWI, TYPE_TXWI);
-#endif
-
-	// Now do hardware-depened kick out.
-	HAL_KickOutMgmtTx(pAd, QueIdx, pPacket, pSrcBufVA, SrcBufLen);
-
-	// Make sure to release MGMT ring resource
-//	if (!IrqState)
-		RTMP_SEM_UNLOCK(&pAd->MgmtRingLock);
-	return NDIS_STATUS_SUCCESS;
-}
-
-
-/********************************************************************************
-
-	New DeQueue Procedures.
-
- ********************************************************************************/
-
-#define DEQUEUE_LOCK(lock, bIntContext, IrqFlags) 				\
-			do{													\
-				if (bIntContext == FALSE)						\
-				RTMP_IRQ_LOCK((lock), IrqFlags);		\
-			}while(0)
-
-#define DEQUEUE_UNLOCK(lock, bIntContext, IrqFlags)				\
-			do{													\
-				if (bIntContext == FALSE)						\
-					RTMP_IRQ_UNLOCK((lock), IrqFlags);	\
-			}while(0)
-
-
-/*
-	========================================================================
-	Tx Path design algorithm:
-		Basically, we divide the packets into four types, Broadcast/Multicast, 11N Rate(AMPDU, AMSDU, Normal), B/G Rate(ARALINK, Normal),
-		Specific Packet Type. Following show the classification rule and policy for each kinds of packets.
-				Classification Rule=>
-					Multicast: (*addr1 & 0x01) == 0x01
-					Specific : bDHCPFrame, bARPFrame, bEAPOLFrame, etc.
-					11N Rate : If peer support HT
-								(1).AMPDU  -- If TXBA is negotiated.
-								(2).AMSDU  -- If AMSDU is capable for both peer and ourself.
-											*). AMSDU can embedded in a AMPDU, but now we didn't support it.
-								(3).Normal -- Other packets which send as 11n rate.
-
-					B/G Rate : If peer is b/g only.
-								(1).ARALINK-- If both of peer/us supprot Ralink proprietary Aggregation and the TxRate is large than RATE_6
-								(2).Normal -- Other packets which send as b/g rate.
-					Fragment:
-								The packet must be unicast, NOT A-RALINK, NOT A-MSDU, NOT 11n, then can consider about fragment.
-
-				Classified Packet Handle Rule=>
-					Multicast:
-								No ACK, 		//pTxBlk->bAckRequired = FALSE;
-								No WMM, 		//pTxBlk->bWMM = FALSE;
-								No piggyback,   //pTxBlk->bPiggyBack = FALSE;
-								Force LowRate,  //pTxBlk->bForceLowRate = TRUE;
-					Specific :	Basically, for specific packet, we should handle it specifically, but now all specific packets are use
-									the same policy to handle it.
-								Force LowRate,  //pTxBlk->bForceLowRate = TRUE;
-
-					11N Rate :
-								No piggyback,	//pTxBlk->bPiggyBack = FALSE;
-
-								(1).AMSDU
-									pTxBlk->bWMM = TRUE;
-								(2).AMPDU
-									pTxBlk->bWMM = TRUE;
-								(3).Normal
-
-					B/G Rate :
-								(1).ARALINK
-
-								(2).Normal
-	========================================================================
-*/
-static UCHAR TxPktClassification(
-	IN RTMP_ADAPTER *pAd,
-	IN PNDIS_PACKET  pPacket)
-{
-	UCHAR			TxFrameType = TX_UNKOWN_FRAME;
-	UCHAR			Wcid;
-	MAC_TABLE_ENTRY	*pMacEntry = NULL;
-#ifdef DOT11_N_SUPPORT
-	BOOLEAN			bHTRate = FALSE;
-#endif // DOT11_N_SUPPORT //
-
-	Wcid = RTMP_GET_PACKET_WCID(pPacket);
-	if (Wcid == MCAST_WCID)
-	{	// Handle for RA is Broadcast/Multicast Address.
-		return TX_MCAST_FRAME;
-	}
-
-	// Handle for unicast packets
-	pMacEntry = &pAd->MacTab.Content[Wcid];
-	if (RTMP_GET_PACKET_LOWRATE(pPacket))
-	{	// It's a specific packet need to force low rate, i.e., bDHCPFrame, bEAPOLFrame, bWAIFrame
-		TxFrameType = TX_LEGACY_FRAME;
-	}
-#ifdef DOT11_N_SUPPORT
-	else if (IS_HT_RATE(pMacEntry))
-	{	// it's a 11n capable packet
-
-		// Depends on HTPhyMode to check if the peer support the HTRate transmission.
-		// 	Currently didn't support A-MSDU embedded in A-MPDU
-		bHTRate = TRUE;
-		if (RTMP_GET_PACKET_MOREDATA(pPacket) || (pMacEntry->PsMode == PWR_SAVE))
-			TxFrameType = TX_LEGACY_FRAME;
-#ifdef UAPSD_AP_SUPPORT
-		else if (RTMP_GET_PACKET_EOSP(pPacket))
-			TxFrameType = TX_LEGACY_FRAME;
-#endif // UAPSD_AP_SUPPORT //
-		else if((pMacEntry->TXBAbitmap & (1<<(RTMP_GET_PACKET_UP(pPacket)))) != 0)
-			return TX_AMPDU_FRAME;
-		else if(CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_AMSDU_INUSED))
-			return TX_AMSDU_FRAME;
-		else
-			TxFrameType = TX_LEGACY_FRAME;
-	}
-#endif // DOT11_N_SUPPORT //
-	else
-	{	// it's a legacy b/g packet.
-		if ((CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_AGGREGATION_CAPABLE) && pAd->CommonCfg.bAggregationCapable) &&
-			(RTMP_GET_PACKET_TXRATE(pPacket) >= RATE_6) &&
-			(!(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) && CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_WMM_CAPABLE))))
-		{	// if peer support Ralink Aggregation, we use it.
-			TxFrameType = TX_RALINK_FRAME;
-		}
-		else
-		{
-			TxFrameType = TX_LEGACY_FRAME;
-		}
-	}
-
-	// Currently, our fragment only support when a unicast packet send as NOT-ARALINK, NOT-AMSDU and NOT-AMPDU.
-	if ((RTMP_GET_PACKET_FRAGMENTS(pPacket) > 1) && (TxFrameType == TX_LEGACY_FRAME))
-		TxFrameType = TX_FRAG_FRAME;
-
-	return TxFrameType;
-}
-
-
-BOOLEAN RTMP_FillTxBlkInfo(
-	IN RTMP_ADAPTER *pAd,
-	IN TX_BLK *pTxBlk)
-{
-	PACKET_INFO			PacketInfo;
-	PNDIS_PACKET		pPacket;
-	PMAC_TABLE_ENTRY	pMacEntry = NULL;
-
-	pPacket = pTxBlk->pPacket;
-	RTMP_QueryPacketInfo(pPacket, &PacketInfo, &pTxBlk->pSrcBufHeader, &pTxBlk->SrcBufLen);
-
-	pTxBlk->Wcid	 	 		= RTMP_GET_PACKET_WCID(pPacket);
-	pTxBlk->apidx		 		= RTMP_GET_PACKET_IF(pPacket);
-	pTxBlk->UserPriority 		= RTMP_GET_PACKET_UP(pPacket);
-	pTxBlk->FrameGap = IFS_HTTXOP;		// ASIC determine Frame Gap
-
-	if (RTMP_GET_PACKET_CLEAR_EAP_FRAME(pTxBlk->pPacket))
-		TX_BLK_SET_FLAG(pTxBlk, fTX_bClearEAPFrame);
-	else
-		TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bClearEAPFrame);
-
-	// Default to clear this flag
-	TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bForceNonQoS);
-
-
-	if (pTxBlk->Wcid == MCAST_WCID)
-	{
-		pTxBlk->pMacEntry = NULL;
-		{
-#ifdef MCAST_RATE_SPECIFIC
-			PUCHAR pDA = GET_OS_PKT_DATAPTR(pPacket);
-			if (((*pDA & 0x01) == 0x01) && (*pDA != 0xff))
-				pTxBlk->pTransmit = &pAd->CommonCfg.MCastPhyMode;
-			else
-#endif // MCAST_RATE_SPECIFIC //
-				pTxBlk->pTransmit = &pAd->MacTab.Content[MCAST_WCID].HTPhyMode;
-		}
-
-		TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bAckRequired);	// AckRequired = FALSE, when broadcast packet in Adhoc mode.
-		//TX_BLK_SET_FLAG(pTxBlk, fTX_bForceLowRate);
-		TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bAllowFrag);
-		TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bWMM);
-		if (RTMP_GET_PACKET_MOREDATA(pPacket))
-		{
-			TX_BLK_SET_FLAG(pTxBlk, fTX_bMoreData);
-		}
-
-	}
-	else
-	{
-		pTxBlk->pMacEntry = &pAd->MacTab.Content[pTxBlk->Wcid];
-		pTxBlk->pTransmit = &pTxBlk->pMacEntry->HTPhyMode;
-
-		pMacEntry = pTxBlk->pMacEntry;
-
-
-		// For all unicast packets, need Ack unless the Ack Policy is not set as NORMAL_ACK.
-		if (pAd->CommonCfg.AckPolicy[pTxBlk->QueIdx] != NORMAL_ACK)
-			TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bAckRequired);
-		else
-			TX_BLK_SET_FLAG(pTxBlk, fTX_bAckRequired);
-
-		{
-
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			{
-
-				// If support WMM, enable it.
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) &&
-					CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_WMM_CAPABLE))
-					TX_BLK_SET_FLAG(pTxBlk, fTX_bWMM);
-
-//				if (pAd->StaCfg.bAutoTxRateSwitch)
-//					TX_BLK_SET_FLAG(pTxBlk, fTX_AutoRateSwitch);
-			}
-#endif // CONFIG_STA_SUPPORT //
-		}
-
-		if (pTxBlk->TxFrameType == TX_LEGACY_FRAME)
-		{
-			if ( (RTMP_GET_PACKET_LOWRATE(pPacket)) ||
-                ((pAd->OpMode == OPMODE_AP) && (pMacEntry->MaxHTPhyMode.field.MODE == MODE_CCK) && (pMacEntry->MaxHTPhyMode.field.MCS == RATE_1)))
-			{	// Specific packet, i.e., bDHCPFrame, bEAPOLFrame, bWAIFrame, need force low rate.
-				pTxBlk->pTransmit = &pAd->MacTab.Content[MCAST_WCID].HTPhyMode;
-#ifdef DOT11_N_SUPPORT
-				// Modify the WMM bit for ICV issue. If we have a packet with EOSP field need to set as 1, how to handle it???
-				if (IS_HT_STA(pTxBlk->pMacEntry) &&
-					(CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_RALINK_CHIPSET)) &&
-					((pAd->CommonCfg.bRdg == TRUE) && CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_RDG_CAPABLE)))
-				{
-					TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bWMM);
-					TX_BLK_SET_FLAG(pTxBlk, fTX_bForceNonQoS);
-				}
-#endif // DOT11_N_SUPPORT //
-			}
-
-#ifdef DOT11_N_SUPPORT
-			if ( (IS_HT_RATE(pMacEntry) == FALSE) &&
-				(CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_PIGGYBACK_CAPABLE)))
-			{	// Currently piggy-back only support when peer is operate in b/g mode.
-				TX_BLK_SET_FLAG(pTxBlk, fTX_bPiggyBack);
-			}
-#endif // DOT11_N_SUPPORT //
-
-			if (RTMP_GET_PACKET_MOREDATA(pPacket))
-			{
-				TX_BLK_SET_FLAG(pTxBlk, fTX_bMoreData);
-			}
-#ifdef UAPSD_AP_SUPPORT
-			if (RTMP_GET_PACKET_EOSP(pPacket))
-			{
-				TX_BLK_SET_FLAG(pTxBlk, fTX_bWMM_UAPSD_EOSP);
-			}
-#endif // UAPSD_AP_SUPPORT //
-		}
-		else if (pTxBlk->TxFrameType == TX_FRAG_FRAME)
-		{
-			TX_BLK_SET_FLAG(pTxBlk, fTX_bAllowFrag);
-		}
-
-		pMacEntry->DebugTxCount++;
-	}
-
-	return TRUE;
-
-FillTxBlkErr:
-	return FALSE;
-}
-
-
-BOOLEAN CanDoAggregateTransmit(
-	IN RTMP_ADAPTER *pAd,
-	IN NDIS_PACKET *pPacket,
-	IN TX_BLK		*pTxBlk)
-{
-
-	//printk("Check if can do aggregation! TxFrameType=%d!\n", pTxBlk->TxFrameType);
-
-	if (RTMP_GET_PACKET_WCID(pPacket) == MCAST_WCID)
-		return FALSE;
-
-	if (RTMP_GET_PACKET_DHCP(pPacket) ||
-		RTMP_GET_PACKET_EAPOL(pPacket) ||
-		RTMP_GET_PACKET_WAI(pPacket))
-		return FALSE;
-
-	if ((pTxBlk->TxFrameType == TX_AMSDU_FRAME) &&
-		((pTxBlk->TotalFrameLen + GET_OS_PKT_LEN(pPacket))> (RX_BUFFER_AGGRESIZE - 100)))
-	{	// For AMSDU, allow the packets with total length < max-amsdu size
-		return FALSE;
-	}
-
-	if ((pTxBlk->TxFrameType == TX_RALINK_FRAME) &&
-		(pTxBlk->TxPacketList.Number == 2))
-	{	// For RALINK-Aggregation, allow two frames in one batch.
-		return FALSE;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	if ((INFRA_ON(pAd)) && (pAd->OpMode == OPMODE_STA)) // must be unicast to AP
-		return TRUE;
-	else
-#endif // CONFIG_STA_SUPPORT //
-		return FALSE;
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		To do the enqueue operation and extract the first item of waiting
-		list. If a number of available shared memory segments could meet
-		the request of extracted item, the extracted item will be fragmented
-		into shared memory segments.
-
-	Arguments:
-		pAd Pointer to our adapter
-		pQueue		Pointer to Waiting Queue
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID RTMPDeQueuePacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  BOOLEAN         bIntContext,
-	IN  UCHAR			QIdx, /* BulkOutPipeId */
-	IN  UCHAR           Max_Tx_Packets)
-{
-	PQUEUE_ENTRY    pEntry = NULL;
-	PNDIS_PACKET 	pPacket;
-	NDIS_STATUS     Status = NDIS_STATUS_SUCCESS;
-	UCHAR           Count=0;
-	PQUEUE_HEADER   pQueue;
-	ULONG           FreeNumber[NUM_OF_TX_RING];
-	UCHAR			QueIdx, sQIdx, eQIdx;
-	unsigned long	IrqFlags = 0;
-	BOOLEAN			hasTxDesc = FALSE;
-	TX_BLK			TxBlk;
-	TX_BLK			*pTxBlk;
-
-#ifdef DBG_DIAGNOSE
-	BOOLEAN			firstRound;
-	RtmpDiagStruct	*pDiagStruct = &pAd->DiagStruct;
-#endif
-
-
-	if (QIdx == NUM_OF_TX_RING)
-	{
-		sQIdx = 0;
-//PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		eQIdx = 3;	// 4 ACs, start from 0.
-#endif // CONFIG_STA_SUPPORT //
-	}
-	else
-	{
-		sQIdx = eQIdx = QIdx;
-	}
-
-	for (QueIdx=sQIdx; QueIdx <= eQIdx; QueIdx++)
-	{
-		Count=0;
-
-		RT28XX_START_DEQUEUE(pAd, QueIdx, IrqFlags);
-
-#ifdef DBG_DIAGNOSE
-		firstRound = ((QueIdx == 0) ? TRUE : FALSE);
-#endif // DBG_DIAGNOSE //
-
-		while (1)
-		{
-			if ((RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS |
-										fRTMP_ADAPTER_RADIO_OFF |
-										fRTMP_ADAPTER_RESET_IN_PROGRESS |
-										fRTMP_ADAPTER_HALT_IN_PROGRESS |
-										fRTMP_ADAPTER_NIC_NOT_EXIST))))
-			{
-				RT28XX_STOP_DEQUEUE(pAd, QueIdx, IrqFlags);
-				return;
-			}
-
-			if (Count >= Max_Tx_Packets)
-				break;
-
-			DEQUEUE_LOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-			if (&pAd->TxSwQueue[QueIdx] == NULL)
-			{
-#ifdef DBG_DIAGNOSE
-				if (firstRound == TRUE)
-					pDiagStruct->TxSWQueCnt[pDiagStruct->ArrayCurIdx][0]++;
-#endif // DBG_DIAGNOSE //
-				DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-				break;
-			}
-
-
-			// probe the Queue Head
-			pQueue = &pAd->TxSwQueue[QueIdx];
-			if ((pEntry = pQueue->Head) == NULL)
-			{
-				DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-				break;
-			}
-
-			pTxBlk = &TxBlk;
-			NdisZeroMemory((PUCHAR)pTxBlk, sizeof(TX_BLK));
-			//InitializeQueueHeader(&pTxBlk->TxPacketList);		// Didn't need it because we already memzero it.
-			pTxBlk->QueIdx = QueIdx;
-
-			pPacket = QUEUE_ENTRY_TO_PKT(pEntry);
-
-			// Early check to make sure we have enoguh Tx Resource.
-			hasTxDesc = RT28XX_HAS_ENOUGH_FREE_DESC(pAd, pTxBlk, FreeNumber[QueIdx], pPacket);
-			if (!hasTxDesc)
-			{
-				pAd->PrivateInfo.TxRingFullCnt++;
-
-				DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-
-				break;
-			}
-
-			pTxBlk->TxFrameType = TxPktClassification(pAd, pPacket);
-			pEntry = RemoveHeadQueue(pQueue);
-			pTxBlk->TotalFrameNum++;
-			pTxBlk->TotalFragNum += RTMP_GET_PACKET_FRAGMENTS(pPacket);	// The real fragment number maybe vary
-			pTxBlk->TotalFrameLen += GET_OS_PKT_LEN(pPacket);
-			pTxBlk->pPacket = pPacket;
-			InsertTailQueue(&pTxBlk->TxPacketList, PACKET_TO_QUEUE_ENTRY(pPacket));
-
-			if (pTxBlk->TxFrameType == TX_RALINK_FRAME || pTxBlk->TxFrameType == TX_AMSDU_FRAME)
-			{
-				// Enhance SW Aggregation Mechanism
-				if (NEED_QUEUE_BACK_FOR_AGG(pAd, QueIdx, FreeNumber[QueIdx], pTxBlk->TxFrameType))
-				{
-					InsertHeadQueue(pQueue, PACKET_TO_QUEUE_ENTRY(pPacket));
-					DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-					break;
-				}
-
-				do{
-					if((pEntry = pQueue->Head) == NULL)
-						break;
-
-					// For TX_AMSDU_FRAME/TX_RALINK_FRAME, Need to check if next pakcet can do aggregation.
-					pPacket = QUEUE_ENTRY_TO_PKT(pEntry);
-					FreeNumber[QueIdx] = GET_TXRING_FREENO(pAd, QueIdx);
-					hasTxDesc = RT28XX_HAS_ENOUGH_FREE_DESC(pAd, pTxBlk, FreeNumber[QueIdx], pPacket);
-					if ((hasTxDesc == FALSE) || (CanDoAggregateTransmit(pAd, pPacket, pTxBlk) == FALSE))
-						break;
-
-					//Remove the packet from the TxSwQueue and insert into pTxBlk
-					pEntry = RemoveHeadQueue(pQueue);
-					ASSERT(pEntry);
-					pPacket = QUEUE_ENTRY_TO_PKT(pEntry);
-					pTxBlk->TotalFrameNum++;
-					pTxBlk->TotalFragNum += RTMP_GET_PACKET_FRAGMENTS(pPacket);	// The real fragment number maybe vary
-					pTxBlk->TotalFrameLen += GET_OS_PKT_LEN(pPacket);
-					InsertTailQueue(&pTxBlk->TxPacketList, PACKET_TO_QUEUE_ENTRY(pPacket));
-				}while(1);
-
-				if (pTxBlk->TxPacketList.Number == 1)
-					pTxBlk->TxFrameType = TX_LEGACY_FRAME;
-			}
-
-#ifdef RT2870
-			DEQUEUE_UNLOCK(&pAd->irq_lock, bIntContext, IrqFlags);
-#endif // RT2870 //
-
-			Count += pTxBlk->TxPacketList.Number;
-
-				// Do HardTransmit now.
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				Status = STAHardTransmit(pAd, pTxBlk, QueIdx);
-#endif // CONFIG_STA_SUPPORT //
-		}
-
-		RT28XX_STOP_DEQUEUE(pAd, QueIdx, IrqFlags);
-
-#ifdef RT2870
-		if (!hasTxDesc)
-			RTUSBKickBulkOut(pAd);
-#endif // RT2870 //
-
-#ifdef BLOCK_NET_IF
-		if ((pAd->blockQueueTab[QueIdx].SwTxQueueBlockFlag == TRUE)
-			&& (pAd->TxSwQueue[QueIdx].Number < 1))
-		{
-			releaseNetIf(&pAd->blockQueueTab[QueIdx]);
-		}
-#endif // BLOCK_NET_IF //
-
-	}
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Calculates the duration which is required to transmit out frames
-	with given size and specified rate.
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		Rate			Transmit rate
-		Size			Frame size in units of byte
-
-	Return Value:
-		Duration number in units of usec
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-USHORT	RTMPCalcDuration(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Rate,
-	IN	ULONG			Size)
-{
-	ULONG	Duration = 0;
-
-	if (Rate < RATE_FIRST_OFDM_RATE) // CCK
-	{
-		if ((Rate > RATE_1) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED))
-			Duration = 96;	// 72+24 preamble+plcp
-		else
-			Duration = 192; // 144+48 preamble+plcp
-
-		Duration += (USHORT)((Size << 4) / RateIdTo500Kbps[Rate]);
-		if ((Size << 4) % RateIdTo500Kbps[Rate])
-			Duration ++;
-	}
-	else if (Rate <= RATE_LAST_OFDM_RATE)// OFDM rates
-	{
-		Duration = 20 + 6;		// 16+4 preamble+plcp + Signal Extension
-		Duration += 4 * (USHORT)((11 + Size * 4) / RateIdTo500Kbps[Rate]);
-		if ((11 + Size * 4) % RateIdTo500Kbps[Rate])
-			Duration += 4;
-	}
-	else	//mimo rate
-	{
-		Duration = 20 + 6;		// 16+4 preamble+plcp + Signal Extension
-	}
-
-	return (USHORT)Duration;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Calculates the duration which is required to transmit out frames
-	with given size and specified rate.
-
-	Arguments:
-		pTxWI		Pointer to head of each MPDU to HW.
-		Ack 		Setting for Ack requirement bit
-		Fragment	Setting for Fragment bit
-		RetryMode	Setting for retry mode
-		Ifs 		Setting for IFS gap
-		Rate		Setting for transmit rate
-		Service 	Setting for service
-		Length		Frame length
-		TxPreamble	Short or Long preamble when using CCK rates
-		QueIdx - 0-3, according to 802.11e/d4.4 June/2003
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-    See also : BASmartHardTransmit()    !!!
-
-	========================================================================
-*/
-VOID RTMPWriteTxWI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXWI_STRUC 	pOutTxWI,
-	IN	BOOLEAN			FRAG,
-	IN	BOOLEAN			CFACK,
-	IN	BOOLEAN			InsTimestamp,
-	IN	BOOLEAN 		AMPDU,
-	IN	BOOLEAN 		Ack,
-	IN	BOOLEAN 		NSeq,		// HW new a sequence.
-	IN	UCHAR			BASize,
-	IN	UCHAR			WCID,
-	IN	ULONG			Length,
-	IN	UCHAR 			PID,
-	IN	UCHAR			TID,
-	IN	UCHAR			TxRate,
-	IN	UCHAR			Txopmode,
-	IN	BOOLEAN			CfAck,
-	IN	HTTRANSMIT_SETTING	*pTransmit)
-{
-	PMAC_TABLE_ENTRY	pMac = NULL;
-	TXWI_STRUC 		TxWI;
-	PTXWI_STRUC 	pTxWI;
-
-	if (WCID < MAX_LEN_OF_MAC_TABLE)
-		pMac = &pAd->MacTab.Content[WCID];
-
-	//
-	// Always use Long preamble before verifiation short preamble functionality works well.
-	// Todo: remove the following line if short preamble functionality works
-	//
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-	NdisZeroMemory(&TxWI, TXWI_SIZE);
-	pTxWI = &TxWI;
-
-	pTxWI->FRAG= FRAG;
-
-	pTxWI->CFACK = CFACK;
-	pTxWI->TS= InsTimestamp;
-	pTxWI->AMPDU = AMPDU;
-	pTxWI->ACK = Ack;
-	pTxWI->txop= Txopmode;
-
-	pTxWI->NSEQ = NSeq;
-	// John tune the performace with Intel Client in 20 MHz performance
-#ifdef DOT11_N_SUPPORT
-	BASize = pAd->CommonCfg.TxBASize;
-
-	if( BASize >7 )
-		BASize =7;
-	pTxWI->BAWinSize = BASize;
-	pTxWI->ShortGI = pTransmit->field.ShortGI;
-	pTxWI->STBC = pTransmit->field.STBC;
-#endif // DOT11_N_SUPPORT //
-
-	pTxWI->WirelessCliID = WCID;
-	pTxWI->MPDUtotalByteCount = Length;
-	pTxWI->PacketId = PID;
-
-	// If CCK or OFDM, BW must be 20
-	pTxWI->BW = (pTransmit->field.MODE <= MODE_OFDM) ? (BW_20) : (pTransmit->field.BW);
-#ifdef DOT11N_DRAFT3
-	if (pTxWI->BW)
-		pTxWI->BW = (pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth == 0) ? (BW_20) : (pTransmit->field.BW);
-#endif // DOT11N_DRAFT3 //
-
-	pTxWI->MCS = pTransmit->field.MCS;
-	pTxWI->PHYMODE = pTransmit->field.MODE;
-	pTxWI->CFACK = CfAck;
-
-#ifdef DOT11_N_SUPPORT
-	if (pMac)
-	{
-		if (pAd->CommonCfg.bMIMOPSEnable)
-		{
-			if ((pMac->MmpsMode == MMPS_DYNAMIC) && (pTransmit->field.MCS > 7))
-			{
-				// Dynamic MIMO Power Save Mode
-				pTxWI->MIMOps = 1;
-			}
-			else if (pMac->MmpsMode == MMPS_STATIC)
-			{
-				// Static MIMO Power Save Mode
-				if (pTransmit->field.MODE >= MODE_HTMIX && pTransmit->field.MCS > 7)
-				{
-					pTxWI->MCS = 7;
-					pTxWI->MIMOps = 0;
-				}
-			}
-		}
-		//pTxWI->MIMOps = (pMac->PsMode == PWR_MMPS)? 1:0;
-		if (pMac->bIAmBadAtheros && (pMac->WepStatus != Ndis802_11WEPDisabled))
-		{
-			pTxWI->MpduDensity = 7;
-		}
-		else
-		{
-			pTxWI->MpduDensity = pMac->MpduDensity;
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-	pTxWI->PacketId = pTxWI->MCS;
-	NdisMoveMemory(pOutTxWI, &TxWI, sizeof(TXWI_STRUC));
-}
-
-
-VOID RTMPWriteTxWI_Data(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	OUT PTXWI_STRUC		pTxWI,
-	IN	TX_BLK				*pTxBlk)
-{
-	HTTRANSMIT_SETTING	*pTransmit;
-	PMAC_TABLE_ENTRY	pMacEntry;
-#ifdef DOT11_N_SUPPORT
-	UCHAR				BASize;
-#endif // DOT11_N_SUPPORT //
-
-
-	ASSERT(pTxWI);
-
-	pTransmit = pTxBlk->pTransmit;
-	pMacEntry = pTxBlk->pMacEntry;
-
-
-	//
-	// Always use Long preamble before verifiation short preamble functionality works well.
-	// Todo: remove the following line if short preamble functionality works
-	//
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-	NdisZeroMemory(pTxWI, TXWI_SIZE);
-
-	pTxWI->FRAG		= TX_BLK_TEST_FLAG(pTxBlk, fTX_bAllowFrag);
-	pTxWI->ACK		= TX_BLK_TEST_FLAG(pTxBlk, fTX_bAckRequired);
-	pTxWI->txop		= pTxBlk->FrameGap;
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-	if (pMacEntry &&
-		(pAd->StaCfg.BssType == BSS_INFRA) &&
-		(pMacEntry->ValidAsDls == TRUE))
-		pTxWI->WirelessCliID = BSSID_WCID;
-	else
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-		pTxWI->WirelessCliID		= pTxBlk->Wcid;
-
-	pTxWI->MPDUtotalByteCount	= pTxBlk->MpduHeaderLen + pTxBlk->SrcBufLen;
-	pTxWI->CFACK				= TX_BLK_TEST_FLAG(pTxBlk, fTX_bPiggyBack);
-
-	// If CCK or OFDM, BW must be 20
-	pTxWI->BW = (pTransmit->field.MODE <= MODE_OFDM) ? (BW_20) : (pTransmit->field.BW);
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	if (pTxWI->BW)
-		pTxWI->BW = (pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth == 0) ? (BW_20) : (pTransmit->field.BW);
-#endif // DOT11N_DRAFT3 //
-	pTxWI->AMPDU	= ((pTxBlk->TxFrameType == TX_AMPDU_FRAME) ? TRUE : FALSE);
-
-	// John tune the performace with Intel Client in 20 MHz performance
-	BASize = pAd->CommonCfg.TxBASize;
-	if((pTxBlk->TxFrameType == TX_AMPDU_FRAME) && (pMacEntry))
-	{
-		UCHAR		RABAOriIdx = 0;	//The RA's BA Originator table index.
-
-		RABAOriIdx = pTxBlk->pMacEntry->BAOriWcidArray[pTxBlk->UserPriority];
-		BASize = pAd->BATable.BAOriEntry[RABAOriIdx].BAWinSize;
-	}
-
-	pTxWI->TxBF = pTransmit->field.TxBF;
-	pTxWI->BAWinSize = BASize;
-	pTxWI->ShortGI = pTransmit->field.ShortGI;
-	pTxWI->STBC = pTransmit->field.STBC;
-#endif // DOT11_N_SUPPORT //
-
-	pTxWI->MCS = pTransmit->field.MCS;
-	pTxWI->PHYMODE = pTransmit->field.MODE;
-
-#ifdef DOT11_N_SUPPORT
-	if (pMacEntry)
-	{
-		if ((pMacEntry->MmpsMode == MMPS_DYNAMIC) && (pTransmit->field.MCS > 7))
-		{
-			// Dynamic MIMO Power Save Mode
-			pTxWI->MIMOps = 1;
-		}
-		else if (pMacEntry->MmpsMode == MMPS_STATIC)
-		{
-			// Static MIMO Power Save Mode
-			if (pTransmit->field.MODE >= MODE_HTMIX && pTransmit->field.MCS > 7)
-			{
-				pTxWI->MCS = 7;
-				pTxWI->MIMOps = 0;
-			}
-		}
-
-		if (pMacEntry->bIAmBadAtheros && (pMacEntry->WepStatus != Ndis802_11WEPDisabled))
-		{
-			pTxWI->MpduDensity = 7;
-		}
-		else
-		{
-			pTxWI->MpduDensity = pMacEntry->MpduDensity;
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-#ifdef DBG_DIAGNOSE
-		if (pTxBlk->QueIdx== 0)
-		{
-			pAd->DiagStruct.TxDataCnt[pAd->DiagStruct.ArrayCurIdx]++;
-			pAd->DiagStruct.TxMcsCnt[pAd->DiagStruct.ArrayCurIdx][pTxWI->MCS]++;
-		}
-#endif // DBG_DIAGNOSE //
-
-	// for rate adapation
-	pTxWI->PacketId = pTxWI->MCS;
-#ifdef INF_AMAZON_SE
-/*Iverson patch for WMM A5-T07 ,WirelessStaToWirelessSta do not bulk out aggregate */
-	if( RTMP_GET_PACKET_NOBULKOUT(pTxBlk->pPacket))
-	{
-		if(pTxWI->PHYMODE == MODE_CCK)
-		{
-			pTxWI->PacketId = 6;
-		}
-	}
-#endif // INF_AMAZON_SE //
-}
-
-
-VOID RTMPWriteTxWI_Cache(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	OUT PTXWI_STRUC		pTxWI,
-	IN	TX_BLK				*pTxBlk)
-{
-	PHTTRANSMIT_SETTING	/*pTxHTPhyMode,*/ pTransmit;
-	PMAC_TABLE_ENTRY	pMacEntry;
-
-	//
-	// update TXWI
-	//
-	pMacEntry = pTxBlk->pMacEntry;
-	pTransmit = pTxBlk->pTransmit;
-
-	//if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED))
-	//if (RTMPCheckEntryEnableAutoRateSwitch(pAd, pMacEntry))
-	//if (TX_BLK_TEST_FLAG(pTxBlk, fTX_AutoRateSwitch))
-	if (pMacEntry->bAutoTxRateSwitch)
-	{
-		pTxWI->txop = IFS_HTTXOP;
-
-		// If CCK or OFDM, BW must be 20
-		pTxWI->BW = (pTransmit->field.MODE <= MODE_OFDM) ? (BW_20) : (pTransmit->field.BW);
-		pTxWI->ShortGI = pTransmit->field.ShortGI;
-		pTxWI->STBC = pTransmit->field.STBC;
-
-		pTxWI->MCS = pTransmit->field.MCS;
-		pTxWI->PHYMODE = pTransmit->field.MODE;
-
-		// set PID for TxRateSwitching
-		pTxWI->PacketId = pTransmit->field.MCS;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	pTxWI->AMPDU = ((pMacEntry->NoBADataCountDown == 0) ? TRUE: FALSE);
-	pTxWI->MIMOps = 0;
-
-#ifdef DOT11N_DRAFT3
-	if (pTxWI->BW)
-		pTxWI->BW = (pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth == 0) ? (BW_20) : (pTransmit->field.BW);
-#endif // DOT11N_DRAFT3 //
-
-	if (pAd->CommonCfg.bMIMOPSEnable)
-	{
-		// MIMO Power Save Mode
-		if ((pMacEntry->MmpsMode == MMPS_DYNAMIC) && (pTransmit->field.MCS > 7))
-		{
-			// Dynamic MIMO Power Save Mode
-			pTxWI->MIMOps = 1;
-		}
-		else if (pMacEntry->MmpsMode == MMPS_STATIC)
-		{
-			// Static MIMO Power Save Mode
-			if ((pTransmit->field.MODE >= MODE_HTMIX) && (pTransmit->field.MCS > 7))
-			{
-				pTxWI->MCS = 7;
-				pTxWI->MIMOps = 0;
-			}
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-#ifdef DBG_DIAGNOSE
-	if (pTxBlk->QueIdx== 0)
-	{
-		pAd->DiagStruct.TxDataCnt[pAd->DiagStruct.ArrayCurIdx]++;
-		pAd->DiagStruct.TxMcsCnt[pAd->DiagStruct.ArrayCurIdx][pTxWI->MCS]++;
-	}
-#endif // DBG_DIAGNOSE //
-
-	pTxWI->MPDUtotalByteCount = pTxBlk->MpduHeaderLen + pTxBlk->SrcBufLen;
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Calculates the duration which is required to transmit out frames
-	with given size and specified rate.
-
-	Arguments:
-		pTxD		Pointer to transmit descriptor
-		Ack 		Setting for Ack requirement bit
-		Fragment	Setting for Fragment bit
-		RetryMode	Setting for retry mode
-		Ifs 		Setting for IFS gap
-		Rate		Setting for transmit rate
-		Service 	Setting for service
-		Length		Frame length
-		TxPreamble	Short or Long preamble when using CCK rates
-		QueIdx - 0-3, according to 802.11e/d4.4 June/2003
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-VOID RTMPWriteTxDescriptor(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXD_STRUC		pTxD,
-	IN	BOOLEAN 		bWIV,
-	IN	UCHAR			QueueSEL)
-{
-	//
-	// Always use Long preamble before verifiation short preamble functionality works well.
-	// Todo: remove the following line if short preamble functionality works
-	//
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-
-	pTxD->WIV	= (bWIV) ? 1: 0;
-	pTxD->QSEL= (QueueSEL);
-	if (pAd->bGenOneHCCA == TRUE)
-		pTxD->QSEL= FIFO_HCCA;
-	pTxD->DMADONE = 0;
-}
-
-
-// should be called only when -
-// 1. MEADIA_CONNECTED
-// 2. AGGREGATION_IN_USED
-// 3. Fragmentation not in used
-// 4. either no previous frame (pPrevAddr1=NULL) .OR. previoud frame is aggregatible
-BOOLEAN TxFrameIsAggregatible(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pPrevAddr1,
-	IN	PUCHAR			p8023hdr)
-{
-
-	// can't aggregate EAPOL (802.1x) frame
-	if ((p8023hdr[12] == 0x88) && (p8023hdr[13] == 0x8e))
-		return FALSE;
-
-	// can't aggregate multicast/broadcast frame
-	if (p8023hdr[0] & 0x01)
-		return FALSE;
-
-	if (INFRA_ON(pAd)) // must be unicast to AP
-		return TRUE;
-	else if ((pPrevAddr1 == NULL) || MAC_ADDR_EQUAL(pPrevAddr1, p8023hdr)) // unicast to same STA
-		return TRUE;
-	else
-		return FALSE;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-	   Check the MSDU Aggregation policy
-	1.HT aggregation is A-MSDU
-	2.legaacy rate aggregation is software aggregation by Ralink.
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-BOOLEAN PeerIsAggreOn(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	ULONG		   TxRate,
-	IN	PMAC_TABLE_ENTRY pMacEntry)
-{
-	ULONG	AFlags = (fCLIENT_STATUS_AMSDU_INUSED | fCLIENT_STATUS_AGGREGATION_CAPABLE);
-
-	if (pMacEntry != NULL && CLIENT_STATUS_TEST_FLAG(pMacEntry, AFlags))
-	{
-#ifdef DOT11_N_SUPPORT
-		if (pMacEntry->HTPhyMode.field.MODE >= MODE_HTMIX)
-		{
-			return TRUE;
-		}
-#endif // DOT11_N_SUPPORT //
-
-#ifdef AGGREGATION_SUPPORT
-		if (TxRate >= RATE_6 && pAd->CommonCfg.bAggregationCapable && (!(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) && CLIENT_STATUS_TEST_FLAG(pMacEntry, fCLIENT_STATUS_WMM_CAPABLE))))
-		{	// legacy  Ralink Aggregation support
-			return TRUE;
-		}
-#endif // AGGREGATION_SUPPORT //
-	}
-
-	return FALSE;
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Check and fine the packet waiting in SW queue with highest priority
-
-	Arguments:
-		pAd Pointer to our adapter
-
-	Return Value:
-		pQueue		Pointer to Waiting Queue
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-PQUEUE_HEADER	RTMPCheckTxSwQueue(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT PUCHAR			pQueIdx)
-{
-
-	ULONG	Number;
-	// 2004-11-15 to be removed. test aggregation only
-//	if ((OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED)) && (*pNumber < 2))
-//		 return NULL;
-
-	Number = pAd->TxSwQueue[QID_AC_BK].Number
-			 + pAd->TxSwQueue[QID_AC_BE].Number
-			 + pAd->TxSwQueue[QID_AC_VI].Number
-			 + pAd->TxSwQueue[QID_AC_VO].Number
-			 + pAd->TxSwQueue[QID_HCCA].Number;
-
-	if (pAd->TxSwQueue[QID_AC_VO].Head != NULL)
-	{
-		*pQueIdx = QID_AC_VO;
-		return (&pAd->TxSwQueue[QID_AC_VO]);
-	}
-	else if (pAd->TxSwQueue[QID_AC_VI].Head != NULL)
-	{
-		*pQueIdx = QID_AC_VI;
-		return (&pAd->TxSwQueue[QID_AC_VI]);
-	}
-	else if (pAd->TxSwQueue[QID_AC_BE].Head != NULL)
-	{
-		*pQueIdx = QID_AC_BE;
-		return (&pAd->TxSwQueue[QID_AC_BE]);
-	}
-	else if (pAd->TxSwQueue[QID_AC_BK].Head != NULL)
-	{
-		*pQueIdx = QID_AC_BK;
-		return (&pAd->TxSwQueue[QID_AC_BK]);
-	}
-	else if (pAd->TxSwQueue[QID_HCCA].Head != NULL)
-	{
-		*pQueIdx = QID_HCCA;
-		return (&pAd->TxSwQueue[QID_HCCA]);
-	}
-
-	// No packet pending in Tx Sw queue
-	*pQueIdx = QID_AC_BK;
-
-	return (NULL);
-}
-
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Suspend MSDU transmission
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPSuspendMsduTransmission(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	DBGPRINT(RT_DEBUG_TRACE,("SCANNING, suspend MSDU transmission ...\n"));
-
-
-	//
-	// Before BSS_SCAN_IN_PROGRESS, we need to keep Current R66 value and
-	// use Lowbound as R66 value on ScanNextChannel(...)
-	//
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &pAd->BbpTuning.R66CurrentValue);
-
-	// set BBP_R66 to 0x30/0x40 when scanning (AsicSwitchChannel will set R66 according to channel when scanning)
-	//RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, (0x26 + GET_LNA_GAIN(pAd)));
-	RTMPSetAGCInitValue(pAd, BW_20);
-
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-	//RTMP_IO_WRITE32(pAd, TX_CNTL_CSR, 0x000f0000);		// abort all TX rings
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Resume MSDU transmission
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID RTMPResumeMsduTransmission(
-	IN	PRTMP_ADAPTER	pAd)
-{
-//    UCHAR			IrqState;
-
-	DBGPRINT(RT_DEBUG_TRACE,("SCAN done, resume MSDU transmission ...\n"));
-
-
-	// After finish BSS_SCAN_IN_PROGRESS, we need to restore Current R66 value
-	// R66 should not be 0
-	if (pAd->BbpTuning.R66CurrentValue == 0)
-	{
-		pAd->BbpTuning.R66CurrentValue = 0x38;
-		DBGPRINT_ERR(("RTMPResumeMsduTransmission, R66CurrentValue=0...\n"));
-	}
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, pAd->BbpTuning.R66CurrentValue);
-
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-// sample, for IRQ LOCK to SEM LOCK
-//    IrqState = pAd->irq_disabled;
-//	if (IrqState)
-//		RTMPDeQueuePacket(pAd, TRUE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-//    else
-	RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-}
-
-
-UINT deaggregate_AMSDU_announce(
-	IN	PRTMP_ADAPTER	pAd,
-	PNDIS_PACKET		pPacket,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize)
-{
-	USHORT 			PayloadSize;
-	USHORT 			SubFrameSize;
-	PHEADER_802_3 	pAMSDUsubheader;
-	UINT			nMSDU;
-    UCHAR			Header802_3[14];
-
-	PUCHAR			pPayload, pDA, pSA, pRemovedLLCSNAP;
-	PNDIS_PACKET	pClonePacket;
-
-
-
-	nMSDU = 0;
-
-	while (DataSize > LENGTH_802_3)
-	{
-
-		nMSDU++;
-
-		//hex_dump("subheader", pData, 64);
-		pAMSDUsubheader = (PHEADER_802_3)pData;
-		//pData += LENGTH_802_3;
-		PayloadSize = pAMSDUsubheader->Octet[1] + (pAMSDUsubheader->Octet[0]<<8);
-		SubFrameSize = PayloadSize + LENGTH_802_3;
-
-
-		if ((DataSize < SubFrameSize) || (PayloadSize > 1518 ))
-		{
-			break;
-		}
-
-		//printk("%d subframe: Size = %d\n",  nMSDU, PayloadSize);
-
-		pPayload = pData + LENGTH_802_3;
-		pDA = pData;
-		pSA = pData + MAC_ADDR_LEN;
-
-		// convert to 802.3 header
-        CONVERT_TO_802_3(Header802_3, pDA, pSA, pPayload, PayloadSize, pRemovedLLCSNAP);
-
-#ifdef CONFIG_STA_SUPPORT
-		if ((Header802_3[12] == 0x88) && (Header802_3[13] == 0x8E) )
-		{
-		    // avoid local heap overflow, use dyanamic allocation
-		   MLME_QUEUE_ELEM *Elem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-		   memmove(Elem->Msg+(LENGTH_802_11 + LENGTH_802_1_H), pPayload, PayloadSize);
-		   Elem->MsgLen = LENGTH_802_11 + LENGTH_802_1_H + PayloadSize;
-		   WpaEAPOLKeyAction(pAd, Elem);
-		   kfree(Elem);
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-	        	if (pRemovedLLCSNAP)
-	        	{
-	    			pPayload -= LENGTH_802_3;
-	    			PayloadSize += LENGTH_802_3;
-	    			NdisMoveMemory(pPayload, &Header802_3[0], LENGTH_802_3);
-	        	}
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		pClonePacket = ClonePacket(pAd, pPacket, pPayload, PayloadSize);
-		if (pClonePacket)
-		{
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pClonePacket, RTMP_GET_PACKET_IF(pPacket));
-#endif // CONFIG_STA_SUPPORT //
-		}
-
-
-		// A-MSDU has padding to multiple of 4 including subframe header.
-		// align SubFrameSize up to multiple of 4
-		SubFrameSize = (SubFrameSize+3)&(~0x3);
-
-
-		if (SubFrameSize > 1528 || SubFrameSize < 32)
-		{
-			break;
-		}
-
-		if (DataSize > SubFrameSize)
-		{
-			pData += SubFrameSize;
-			DataSize -= SubFrameSize;
-		}
-		else
-		{
-			// end of A-MSDU
-			DataSize = 0;
-		}
-	}
-
-	// finally release original rx packet
-	RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_SUCCESS);
-
-	return nMSDU;
-}
-
-
-UINT BA_Reorder_AMSDU_Annnounce(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-	PUCHAR			pData;
-	USHORT			DataSize;
-	UINT			nMSDU = 0;
-
-	pData = (PUCHAR) GET_OS_PKT_DATAPTR(pPacket);
-	DataSize = (USHORT) GET_OS_PKT_LEN(pPacket);
-
-	nMSDU = deaggregate_AMSDU_announce(pAd, pPacket, pData, DataSize);
-
-	return nMSDU;
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Look up the MAC address in the MAC table. Return NULL if not found.
-	Return:
-		pEntry - pointer to the MAC entry; NULL is not found
-	==========================================================================
-*/
-MAC_TABLE_ENTRY *MacTableLookup(
-	IN PRTMP_ADAPTER pAd,
-	PUCHAR pAddr)
-{
-	ULONG HashIdx;
-	MAC_TABLE_ENTRY *pEntry = NULL;
-
-	HashIdx = MAC_ADDR_HASH_INDEX(pAddr);
-	pEntry = pAd->MacTab.Hash[HashIdx];
-
-	while (pEntry && (pEntry->ValidAsCLI || pEntry->ValidAsWDS || pEntry->ValidAsApCli || pEntry->ValidAsMesh))
-	{
-		if (MAC_ADDR_EQUAL(pEntry->Addr, pAddr))
-		{
-			break;
-		}
-		else
-			pEntry = pEntry->pNext;
-	}
-
-	return pEntry;
-}
-
-MAC_TABLE_ENTRY *MacTableInsertEntry(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR			pAddr,
-	IN	UCHAR			apidx,
-	IN BOOLEAN	CleanAll)
-{
-	UCHAR HashIdx;
-	int i, FirstWcid;
-	MAC_TABLE_ENTRY *pEntry = NULL, *pCurrEntry;
-//	USHORT	offset;
-//	ULONG	addr;
-
-	// if FULL, return
-	if (pAd->MacTab.Size >= MAX_LEN_OF_MAC_TABLE)
-		return NULL;
-
-	FirstWcid = 1;
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	if (pAd->StaCfg.BssType == BSS_INFRA)
-		FirstWcid = 2;
-#endif // CONFIG_STA_SUPPORT //
-
-	// allocate one MAC entry
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-	for (i = FirstWcid; i< MAX_LEN_OF_MAC_TABLE; i++)   // skip entry#0 so that "entry index == AID" for fast lookup
-	{
-		// pick up the first available vacancy
-		if ((pAd->MacTab.Content[i].ValidAsCLI == FALSE) &&
-			(pAd->MacTab.Content[i].ValidAsWDS == FALSE) &&
-			(pAd->MacTab.Content[i].ValidAsApCli== FALSE) &&
-			(pAd->MacTab.Content[i].ValidAsMesh == FALSE)
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-			&& (pAd->MacTab.Content[i].ValidAsDls == FALSE)
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-			)
-		{
-			pEntry = &pAd->MacTab.Content[i];
-			if (CleanAll == TRUE)
-			{
-				pEntry->MaxSupportedRate = RATE_11;
-				pEntry->CurrTxRate = RATE_11;
-				NdisZeroMemory(pEntry, sizeof(MAC_TABLE_ENTRY));
-				pEntry->PairwiseKey.KeyLen = 0;
-				pEntry->PairwiseKey.CipherAlg = CIPHER_NONE;
-			}
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-			if (apidx >= MIN_NET_DEVICE_FOR_DLS)
-			{
-				pEntry->ValidAsCLI = FALSE;
-				pEntry->ValidAsWDS = FALSE;
-				pEntry->ValidAsApCli = FALSE;
-				pEntry->ValidAsMesh = FALSE;
-				pEntry->ValidAsDls = TRUE;
-				pEntry->isCached = FALSE;
-			}
-			else
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-			{
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-					pEntry->ValidAsCLI = TRUE;
-					pEntry->ValidAsWDS = FALSE;
-					pEntry->ValidAsApCli = FALSE;
-					pEntry->ValidAsMesh = FALSE;
-					pEntry->ValidAsDls = FALSE;
-				}
-#endif // CONFIG_STA_SUPPORT //
-			}
-
-			pEntry->bIAmBadAtheros = FALSE;
-			pEntry->pAd = pAd;
-			pEntry->CMTimerRunning = FALSE;
-			pEntry->EnqueueEapolStartTimerRunning = EAPOL_START_DISABLE;
-			pEntry->RSNIE_Len = 0;
-			NdisZeroMemory(pEntry->R_Counter, sizeof(pEntry->R_Counter));
-			pEntry->ReTryCounter = PEER_MSG1_RETRY_TIMER_CTR;
-
-			if (pEntry->ValidAsMesh)
-				pEntry->apidx = (apidx - MIN_NET_DEVICE_FOR_MESH);
-			else if (pEntry->ValidAsApCli)
-				pEntry->apidx = (apidx - MIN_NET_DEVICE_FOR_APCLI);
-			else if (pEntry->ValidAsWDS)
-				pEntry->apidx = (apidx - MIN_NET_DEVICE_FOR_WDS);
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-			else if (pEntry->ValidAsDls)
-				pEntry->apidx = (apidx - MIN_NET_DEVICE_FOR_DLS);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-			else
-				pEntry->apidx = apidx;
-
-			{
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-					pEntry->AuthMode = pAd->StaCfg.AuthMode;
-					pEntry->WepStatus = pAd->StaCfg.WepStatus;
-					pEntry->PrivacyFilter = Ndis802_11PrivFilterAcceptAll;
-				}
-#endif // CONFIG_STA_SUPPORT //
-			}
-
-			pEntry->GTKState = REKEY_NEGOTIATING;
-			pEntry->PairwiseKey.KeyLen = 0;
-			pEntry->PairwiseKey.CipherAlg = CIPHER_NONE;
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-			if (pEntry->ValidAsDls == TRUE)
-				pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
-			else
-#endif //QOS_DLS_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-			pEntry->PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			pEntry->PMKID_CacheIdx = ENTRY_NOT_FOUND;
-			COPY_MAC_ADDR(pEntry->Addr, pAddr);
-			pEntry->Sst = SST_NOT_AUTH;
-			pEntry->AuthState = AS_NOT_AUTH;
-			pEntry->Aid = (USHORT)i;  //0;
-			pEntry->CapabilityInfo = 0;
-			pEntry->PsMode = PWR_ACTIVE;
-			pEntry->PsQIdleCount = 0;
-			pEntry->NoDataIdleCount = 0;
-			pEntry->ContinueTxFailCnt = 0;
-			InitializeQueueHeader(&pEntry->PsQueue);
-
-
-			pAd->MacTab.Size ++;
-
-			// Add this entry into ASIC RX WCID search table
-			RT28XX_STA_ENTRY_ADD(pAd, pEntry);
-
-
-
-			DBGPRINT(RT_DEBUG_TRACE, ("MacTableInsertEntry - allocate entry #%d, Total= %d\n",i, pAd->MacTab.Size));
-			break;
-		}
-	}
-
-	// add this MAC entry into HASH table
-	if (pEntry)
-	{
-		HashIdx = MAC_ADDR_HASH_INDEX(pAddr);
-		if (pAd->MacTab.Hash[HashIdx] == NULL)
-		{
-			pAd->MacTab.Hash[HashIdx] = pEntry;
-		}
-		else
-		{
-			pCurrEntry = pAd->MacTab.Hash[HashIdx];
-			while (pCurrEntry->pNext != NULL)
-				pCurrEntry = pCurrEntry->pNext;
-			pCurrEntry->pNext = pEntry;
-		}
-	}
-
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-	return pEntry;
-}
-
-/*
-	==========================================================================
-	Description:
-		Delete a specified client from MAC table
-	==========================================================================
- */
-BOOLEAN MacTableDeleteEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT wcid,
-	IN PUCHAR pAddr)
-{
-	USHORT HashIdx;
-	MAC_TABLE_ENTRY *pEntry, *pPrevEntry, *pProbeEntry;
-	BOOLEAN Cancelled;
-	//USHORT	offset;	// unused variable
-	//UCHAR	j;			// unused variable
-
-	if (wcid >= MAX_LEN_OF_MAC_TABLE)
-		return FALSE;
-
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-
-	HashIdx = MAC_ADDR_HASH_INDEX(pAddr);
-	//pEntry = pAd->MacTab.Hash[HashIdx];
-	pEntry = &pAd->MacTab.Content[wcid];
-
-	if (pEntry && (pEntry->ValidAsCLI || pEntry->ValidAsApCli || pEntry->ValidAsWDS || pEntry->ValidAsMesh
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
- 		|| pEntry->ValidAsDls
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-		))
-	{
-		if (MAC_ADDR_EQUAL(pEntry->Addr, pAddr))
-		{
-
-			// Delete this entry from ASIC on-chip WCID Table
-			RT28XX_STA_ENTRY_MAC_RESET(pAd, wcid);
-
-#ifdef DOT11_N_SUPPORT
-			// free resources of BA
-			BASessionTearDownALL(pAd, pEntry->Aid);
-#endif // DOT11_N_SUPPORT //
-
-
-			pPrevEntry = NULL;
-			pProbeEntry = pAd->MacTab.Hash[HashIdx];
-			ASSERT(pProbeEntry);
-
-			// update Hash list
-			do
-			{
-				if (pProbeEntry == pEntry)
-				{
-					if (pPrevEntry == NULL)
-					{
-						pAd->MacTab.Hash[HashIdx] = pEntry->pNext;
-					}
-					else
-					{
-						pPrevEntry->pNext = pEntry->pNext;
-					}
-					break;
-				}
-
-				pPrevEntry = pProbeEntry;
-				pProbeEntry = pProbeEntry->pNext;
-			} while (pProbeEntry);
-
-			// not found !!!
-			ASSERT(pProbeEntry != NULL);
-
-			RT28XX_STA_ENTRY_KEY_DEL(pAd, BSS0, wcid);
-
-
-		if (pEntry->EnqueueEapolStartTimerRunning != EAPOL_START_DISABLE)
-		{
-			RTMPCancelTimer(&pEntry->EnqueueStartForPSKTimer, &Cancelled);
-			pEntry->EnqueueEapolStartTimerRunning = EAPOL_START_DISABLE;
-		}
-
-
-   			NdisZeroMemory(pEntry, sizeof(MAC_TABLE_ENTRY));
-			pAd->MacTab.Size --;
-			DBGPRINT(RT_DEBUG_TRACE, ("MacTableDeleteEntry1 - Total= %d\n", pAd->MacTab.Size));
-		}
-		else
-		{
-			printk("\n%s: Impossible Wcid = %d !!!!!\n", __FUNCTION__, wcid);
-		}
-	}
-
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-
-	//Reset operating mode when no Sta.
-	if (pAd->MacTab.Size == 0)
-	{
-#ifdef DOT11_N_SUPPORT
-		pAd->CommonCfg.AddHTInfo.AddHtInfo2.OperaionMode = 0;
-#endif // DOT11_N_SUPPORT //
-		//AsicUpdateProtect(pAd, 0 /*pAd->CommonCfg.AddHTInfo.AddHtInfo2.OperaionMode*/, (ALLN_SETPROTECT), TRUE, 0 /*pAd->MacTab.fAnyStationNonGF*/);
-		RT28XX_UPDATE_PROTECT(pAd);  // edit by johnli, fix "in_interrupt" error when call "MacTableDeleteEntry" in Rx tasklet
-	}
-
-	return TRUE;
-}
-
-
-/*
-	==========================================================================
-	Description:
-		This routine reset the entire MAC table. All packets pending in
-		the power-saving queues are freed here.
-	==========================================================================
- */
-VOID MacTableReset(
-	IN  PRTMP_ADAPTER  pAd)
-{
-	int         i;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("MacTableReset\n"));
-	//NdisAcquireSpinLock(&pAd->MacTabLock);
-
-	for (i=1; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		if (pAd->MacTab.Content[i].ValidAsCLI == TRUE)
-	   {
-
-#ifdef DOT11_N_SUPPORT
-			// free resources of BA
-			BASessionTearDownALL(pAd, i);
-#endif // DOT11_N_SUPPORT //
-
-			pAd->MacTab.Content[i].ValidAsCLI = FALSE;
-
-
-
-#ifdef RT2870
-			NdisZeroMemory(pAd->MacTab.Content[i].Addr, 6);
-			RT28XX_STA_ENTRY_MAC_RESET(pAd, i);
-#endif // RT2870 //
-
-			//AsicDelWcidTab(pAd, i);
-		}
-	}
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID AssocParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_ASSOC_REQ_STRUCT *AssocReq,
-	IN PUCHAR                     pAddr,
-	IN USHORT                     CapabilityInfo,
-	IN ULONG                      Timeout,
-	IN USHORT                     ListenIntv)
-{
-	COPY_MAC_ADDR(AssocReq->Addr, pAddr);
-	// Add mask to support 802.11b mode only
-	AssocReq->CapabilityInfo = CapabilityInfo & SUPPORTED_CAPABILITY_INFO; // not cf-pollable, not cf-poll-request
-	AssocReq->Timeout = Timeout;
-	AssocReq->ListenIntv = ListenIntv;
-}
-
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID DisassocParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_DISASSOC_REQ_STRUCT *DisassocReq,
-	IN PUCHAR pAddr,
-	IN USHORT Reason)
-{
-	COPY_MAC_ADDR(DisassocReq->Addr, pAddr);
-	DisassocReq->Reason = Reason;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Check the out going frame, if this is an DHCP or ARP datagram
-	will be duplicate another frame at low data rate transmit.
-
-	Arguments:
-		pAd 		Pointer to our adapter
-		pPacket 	Pointer to outgoing Ndis frame
-
-	Return Value:
-		TRUE		To be duplicate at Low data rate transmit. (1mb)
-		FALSE		Do nothing.
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-		MAC header + IP Header + UDP Header
-		  14 Bytes	  20 Bytes
-
-		UDP Header
-		00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|
-						Source Port
-		16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|
-					Destination Port
-
-		port 0x43 means Bootstrap Protocol, server.
-		Port 0x44 means Bootstrap Protocol, client.
-
-	========================================================================
-*/
-
-BOOLEAN RTMPCheckDHCPFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-	PACKET_INFO 	PacketInfo;
-	ULONG			NumberOfBytesRead = 0;
-	ULONG			CurrentOffset = 0;
-	PVOID			pVirtualAddress = NULL;
-	UINT			NdisBufferLength;
-	PUCHAR			pSrc;
-	USHORT			Protocol;
-	UCHAR			ByteOffset36 = 0;
-	UCHAR			ByteOffset38 = 0;
-	BOOLEAN 		ReadFirstParm = TRUE;
-
-	RTMP_QueryPacketInfo(pPacket, &PacketInfo, (PUCHAR *)&pVirtualAddress, &NdisBufferLength);
-
-	NumberOfBytesRead += NdisBufferLength;
-	pSrc = (PUCHAR) pVirtualAddress;
-	Protocol = *(pSrc + 12) * 256 + *(pSrc + 13);
-
-	//
-	// Check DHCP & BOOTP protocol
-	//
-	while (NumberOfBytesRead <= PacketInfo.TotalPacketLength)
-	{
-		if ((NumberOfBytesRead >= 35) && (ReadFirstParm == TRUE))
-		{
-			CurrentOffset = 35 - (NumberOfBytesRead - NdisBufferLength);
-			ByteOffset36 = *(pSrc + CurrentOffset);
-			ReadFirstParm = FALSE;
-		}
-
-		if (NumberOfBytesRead >= 37)
-		{
-			CurrentOffset = 37 - (NumberOfBytesRead - NdisBufferLength);
-			ByteOffset38 = *(pSrc + CurrentOffset);
-			//End of Read
-			break;
-		}
-		return FALSE;
-	}
-
-	// Check for DHCP & BOOTP protocol
-	if ((ByteOffset36 != 0x44) || (ByteOffset38 != 0x43))
-		{
-		//
-		// 2054 (hex 0806) for ARP datagrams
-		// if this packet is not ARP datagrams, then do nothing
-		// ARP datagrams will also be duplicate at 1mb broadcast frames
-		//
-		if (Protocol != 0x0806 )
-			return FALSE;
-		}
-
-	return TRUE;
-}
-
-
-BOOLEAN RTMPCheckEtherType(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-	USHORT	TypeLen;
-	UCHAR	Byte0, Byte1;
-	PUCHAR	pSrcBuf;
-	UINT32	pktLen;
-	UINT16 	srcPort, dstPort;
-	BOOLEAN	status = TRUE;
-
-
-	pSrcBuf = GET_OS_PKT_DATAPTR(pPacket);
-	pktLen = GET_OS_PKT_LEN(pPacket);
-
-	ASSERT(pSrcBuf);
-
-	RTMP_SET_PACKET_SPECIFIC(pPacket, 0);
-
-	// get Ethernet protocol field
-	TypeLen = (pSrcBuf[12] << 8) + pSrcBuf[13];
-
-	pSrcBuf += LENGTH_802_3;	// Skip the Ethernet Header.
-
-	if (TypeLen <= 1500)
-	{	// 802.3, 802.3 LLC
-		/*
-			DestMAC(6) + SrcMAC(6) + Lenght(2) +
-			DSAP(1) + SSAP(1) + Control(1) +
-			if the DSAP = 0xAA, SSAP=0xAA, Contorl = 0x03, it has a 5-bytes SNAP header.
-				=> + SNAP (5, OriginationID(3) + etherType(2))
-		*/
-		if (pSrcBuf[0] == 0xAA && pSrcBuf[1] == 0xAA && pSrcBuf[2] == 0x03)
-		{
-			Sniff2BytesFromNdisBuffer(pSrcBuf, 6, &Byte0, &Byte1);
-			RTMP_SET_PACKET_LLCSNAP(pPacket, 1);
-			TypeLen = (USHORT)((Byte0 << 8) + Byte1);
-			pSrcBuf += 8; // Skip this LLC/SNAP header
-		}
-		else
-		{
-			//It just has 3-byte LLC header, maybe a legacy ether type frame. we didn't handle it.
-		}
-	}
-
-	// If it's a VLAN packet, get the real Type/Length field.
-	if (TypeLen == 0x8100)
-	{
-		/* 0x8100 means VLAN packets */
-
-		/* Dest. MAC Address (6-bytes) +
-		   Source MAC Address (6-bytes) +
-		   Length/Type = 802.1Q Tag Type (2-byte) +
-		   Tag Control Information (2-bytes) +
-		   Length / Type (2-bytes) +
-		   data payload (0-n bytes) +
-		   Pad (0-p bytes) +
-		   Frame Check Sequence (4-bytes) */
-
-		RTMP_SET_PACKET_VLAN(pPacket, 1);
-		Sniff2BytesFromNdisBuffer(pSrcBuf, 2, &Byte0, &Byte1);
-		TypeLen = (USHORT)((Byte0 << 8) + Byte1);
-
-		pSrcBuf += 4; // Skip the VLAN Header.
-	}
-
-	switch (TypeLen)
-	{
-		case 0x0800:
-			{
-				ASSERT((pktLen > 34));
-				if (*(pSrcBuf + 9) == 0x11)
-				{	// udp packet
-					ASSERT((pktLen > 34));	// 14 for ethernet header, 20 for IP header
-
-					pSrcBuf += 20;	// Skip the IP header
-					srcPort = OS_NTOHS(*((UINT16 *)pSrcBuf));
-					dstPort = OS_NTOHS(*((UINT16 *)(pSrcBuf +2)));
-
-					if ((srcPort==0x44 && dstPort==0x43) || (srcPort==0x43 && dstPort==0x44))
-					{	//It's a BOOTP/DHCP packet
-						RTMP_SET_PACKET_DHCP(pPacket, 1);
-					}
-				}
-			}
-			break;
-		case 0x0806:
-			{
-				//ARP Packet.
-				RTMP_SET_PACKET_DHCP(pPacket, 1);
-			}
-			break;
-		case 0x888e:
-			{
-				// EAPOL Packet.
-				RTMP_SET_PACKET_EAPOL(pPacket, 1);
-			}
-			break;
-		default:
-			status = FALSE;
-			break;
-	}
-
-	return status;
-
-}
-
-
-
-VOID Update_Rssi_Sample(
-	IN PRTMP_ADAPTER	pAd,
-	IN RSSI_SAMPLE		*pRssi,
-	IN PRXWI_STRUC		pRxWI)
-		{
-	CHAR	rssi0 = pRxWI->RSSI0;
-	CHAR	rssi1 = pRxWI->RSSI1;
-	CHAR	rssi2 = pRxWI->RSSI2;
-
-	if (rssi0 != 0)
-	{
-		pRssi->LastRssi0	= ConvertToRssi(pAd, (CHAR)rssi0, RSSI_0);
-		pRssi->AvgRssi0X8	= (pRssi->AvgRssi0X8 - pRssi->AvgRssi0) + pRssi->LastRssi0;
-		pRssi->AvgRssi0	= pRssi->AvgRssi0X8 >> 3;
-	}
-
-	if (rssi1 != 0)
-	{
-		pRssi->LastRssi1	= ConvertToRssi(pAd, (CHAR)rssi1, RSSI_1);
-		pRssi->AvgRssi1X8	= (pRssi->AvgRssi1X8 - pRssi->AvgRssi1) + pRssi->LastRssi1;
-		pRssi->AvgRssi1	= pRssi->AvgRssi1X8 >> 3;
-	}
-
-	if (rssi2 != 0)
-	{
-		pRssi->LastRssi2	= ConvertToRssi(pAd, (CHAR)rssi2, RSSI_2);
-		pRssi->AvgRssi2X8  = (pRssi->AvgRssi2X8 - pRssi->AvgRssi2) + pRssi->LastRssi2;
-		pRssi->AvgRssi2 = pRssi->AvgRssi2X8 >> 3;
-	}
-}
-
-
-
-// Normal legacy Rx packet indication
-VOID Indicate_Legacy_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	PNDIS_PACKET	pRxPacket = pRxBlk->pRxPacket;
-	UCHAR			Header802_3[LENGTH_802_3];
-
-	// 1. get 802.3 Header
-	// 2. remove LLC
-	// 		a. pointer pRxBlk->pData to payload
-	//      b. modify pRxBlk->DataSize
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
-#endif // CONFIG_STA_SUPPORT //
-
-	if (pRxBlk->DataSize > MAX_RX_PKT_LEN)
-	{
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-
-	STATS_INC_RX_PACKETS(pAd, FromWhichBSSID);
-
-#ifdef RT2870
-#ifdef DOT11_N_SUPPORT
-	if (pAd->CommonCfg.bDisableReordering == 0)
-	{
-		PBA_REC_ENTRY		pBAEntry;
-		ULONG				Now32;
-		UCHAR				Wcid = pRxBlk->pRxWI->WirelessCliID;
-		UCHAR				TID = pRxBlk->pRxWI->TID;
-		USHORT				Idx;
-
-#define REORDERING_PACKET_TIMEOUT		((100 * HZ)/1000)	// system ticks -- 100 ms
-
-		if (Wcid < MAX_LEN_OF_MAC_TABLE)
-		{
-			Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID];
-			if (Idx != 0)
-			{
-				pBAEntry = &pAd->BATable.BARecEntry[Idx];
-				// update last rx time
-				NdisGetSystemUpTime(&Now32);
-				if ((pBAEntry->list.qlen > 0) &&
-					 RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(REORDERING_PACKET_TIMEOUT)))
-	   				)
-				{
-					printk("Indicate_Legacy_Packet():flush reordering_timeout_mpdus! RxWI->Flags=%d, pRxWI.TID=%d, RxD->AMPDU=%d!\n", pRxBlk->Flags, pRxBlk->pRxWI->TID, pRxBlk->RxD.AMPDU);
-					hex_dump("Dump the legacy Packet:", GET_OS_PKT_DATAPTR(pRxBlk->pRxPacket), 64);
-					ba_flush_reordering_timeout_mpdus(pAd, pBAEntry, Now32);
-				}
-			}
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-#endif // RT2870 //
-
-	wlan_802_11_to_802_3_packet(pAd, pRxBlk, Header802_3, FromWhichBSSID);
-
-	//
-	// pass this 802.3 packet to upper layer or forward this packet to WM directly
-	//
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pRxPacket, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
-
-}
-
-
-// Normal, AMPDU or AMSDU
-VOID CmmRxnonRalinkFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-#ifdef DOT11_N_SUPPORT
-	if (RX_BLK_TEST_FLAG(pRxBlk, fRX_AMPDU) && (pAd->CommonCfg.bDisableReordering == 0))
-	{
-		Indicate_AMPDU_Packet(pAd, pRxBlk, FromWhichBSSID);
-	}
-	else
-#endif // DOT11_N_SUPPORT //
-	{
-#ifdef DOT11_N_SUPPORT
-		if (RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU))
-		{
-			// handle A-MSDU
-			Indicate_AMSDU_Packet(pAd, pRxBlk, FromWhichBSSID);
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			Indicate_Legacy_Packet(pAd, pRxBlk, FromWhichBSSID);
-		}
-	}
-}
-
-
-VOID CmmRxRalinkFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	UCHAR			Header802_3[LENGTH_802_3];
-	UINT16			Msdu2Size;
-	UINT16 			Payload1Size, Payload2Size;
-	PUCHAR 			pData2;
-	PNDIS_PACKET	pPacket2 = NULL;
-
-
-
-	Msdu2Size = *(pRxBlk->pData) + (*(pRxBlk->pData+1) << 8);
-
-	if ((Msdu2Size <= 1536) && (Msdu2Size < pRxBlk->DataSize))
-	{
-		/* skip two byte MSDU2 len */
-		pRxBlk->pData += 2;
-		pRxBlk->DataSize -= 2;
-	}
-	else
-	{
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-	// get 802.3 Header and  remove LLC
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3);
-#endif // CONFIG_STA_SUPPORT //
-
-
-	ASSERT(pRxBlk->pRxPacket);
-
-	// Ralink Aggregation frame
-	pAd->RalinkCounters.OneSecRxAggregationCount ++;
-	Payload1Size = pRxBlk->DataSize - Msdu2Size;
-	Payload2Size = Msdu2Size - LENGTH_802_3;
-
-	pData2 = pRxBlk->pData + Payload1Size + LENGTH_802_3;
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		pPacket2 = duplicate_pkt(pAd, (pData2-LENGTH_802_3), LENGTH_802_3, pData2, Payload2Size, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
-
-	if (!pPacket2)
-	{
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-	// update payload size of 1st packet
-	pRxBlk->DataSize = Payload1Size;
-	wlan_802_11_to_802_3_packet(pAd, pRxBlk, Header802_3, FromWhichBSSID);
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pRxBlk->pRxPacket, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
-
-	if (pPacket2)
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pPacket2, FromWhichBSSID);
-#endif // CONFIG_STA_SUPPORT //
-	}
-}
-
-
-#define RESET_FRAGFRAME(_fragFrame) \
-	{								\
-		_fragFrame.RxSize = 0;		\
-		_fragFrame.Sequence = 0;	\
-		_fragFrame.LastFrag = 0;	\
-		_fragFrame.Flags = 0;		\
-	}
-
-
-PNDIS_PACKET RTMPDeFragmentDataFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk)
-{
-	PHEADER_802_11	pHeader = pRxBlk->pHeader;
-	PNDIS_PACKET	pRxPacket = pRxBlk->pRxPacket;
-	UCHAR			*pData = pRxBlk->pData;
-	USHORT			DataSize = pRxBlk->DataSize;
-	PNDIS_PACKET	pRetPacket = NULL;
-	UCHAR			*pFragBuffer = NULL;
-	BOOLEAN 		bReassDone = FALSE;
-	UCHAR			HeaderRoom = 0;
-
-
-	ASSERT(pHeader);
-
-	HeaderRoom = pData - (UCHAR *)pHeader;
-
-	// Re-assemble the fragmented packets
-	if (pHeader->Frag == 0)		// Frag. Number is 0 : First frag or only one pkt
-	{
-		// the first pkt of fragment, record it.
-		if (pHeader->FC.MoreFrag)
-		{
-			ASSERT(pAd->FragFrame.pFragPacket);
-			pFragBuffer = GET_OS_PKT_DATAPTR(pAd->FragFrame.pFragPacket);
-			pAd->FragFrame.RxSize   = DataSize + HeaderRoom;
-			NdisMoveMemory(pFragBuffer,	 pHeader, pAd->FragFrame.RxSize);
-			pAd->FragFrame.Sequence = pHeader->Sequence;
-			pAd->FragFrame.LastFrag = pHeader->Frag;	   // Should be 0
-			ASSERT(pAd->FragFrame.LastFrag == 0);
-			goto done;	// end of processing this frame
-		}
-	}
-	else	//Middle & End of fragment
-	{
-		if ((pHeader->Sequence != pAd->FragFrame.Sequence) ||
-			(pHeader->Frag != (pAd->FragFrame.LastFrag + 1)))
-		{
-			// Fragment is not the same sequence or out of fragment number order
-			// Reset Fragment control blk
-			RESET_FRAGFRAME(pAd->FragFrame);
-			DBGPRINT(RT_DEBUG_ERROR, ("Fragment is not the same sequence or out of fragment number order.\n"));
-			goto done; // give up this frame
-		}
-		else if ((pAd->FragFrame.RxSize + DataSize) > MAX_FRAME_SIZE)
-		{
-			// Fragment frame is too large, it exeeds the maximum frame size.
-			// Reset Fragment control blk
-			RESET_FRAGFRAME(pAd->FragFrame);
-			DBGPRINT(RT_DEBUG_ERROR, ("Fragment frame is too large, it exeeds the maximum frame size.\n"));
-			goto done; // give up this frame
-		}
-
-        //
-		// Broadcom AP(BCM94704AGR) will send out LLC in fragment's packet, LLC only can accpet at first fragment.
-		// In this case, we will dropt it.
-		//
-		if (NdisEqualMemory(pData, SNAP_802_1H, sizeof(SNAP_802_1H)))
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("Find another LLC at Middle or End fragment(SN=%d, Frag=%d)\n", pHeader->Sequence, pHeader->Frag));
-			goto done; // give up this frame
-		}
-
-		pFragBuffer = GET_OS_PKT_DATAPTR(pAd->FragFrame.pFragPacket);
-
-		// concatenate this fragment into the re-assembly buffer
-		NdisMoveMemory((pFragBuffer + pAd->FragFrame.RxSize), pData, DataSize);
-		pAd->FragFrame.RxSize  += DataSize;
-		pAd->FragFrame.LastFrag = pHeader->Frag;	   // Update fragment number
-
-		// Last fragment
-		if (pHeader->FC.MoreFrag == FALSE)
-		{
-			bReassDone = TRUE;
-		}
-	}
-
-done:
-	// always release rx fragmented packet
-	RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-
-	// return defragmented packet if packet is reassembled completely
-	// otherwise return NULL
-	if (bReassDone)
-	{
-		PNDIS_PACKET pNewFragPacket;
-
-		// allocate a new packet buffer for fragment
-		pNewFragPacket = RTMP_AllocateFragPacketBuffer(pAd, RX_BUFFER_NORMSIZE);
-		if (pNewFragPacket)
-		{
-			// update RxBlk
-			pRetPacket = pAd->FragFrame.pFragPacket;
-			pAd->FragFrame.pFragPacket = pNewFragPacket;
-			pRxBlk->pHeader = (PHEADER_802_11) GET_OS_PKT_DATAPTR(pRetPacket);
-			pRxBlk->pData = (UCHAR *)pRxBlk->pHeader + HeaderRoom;
-			pRxBlk->DataSize = pAd->FragFrame.RxSize - HeaderRoom;
-			pRxBlk->pRxPacket = pRetPacket;
-		}
-		else
-		{
-			RESET_FRAGFRAME(pAd->FragFrame);
-		}
-	}
-
-	return pRetPacket;
-}
-
-
-VOID Indicate_AMSDU_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	UINT			nMSDU;
-
-	update_os_packet_info(pAd, pRxBlk, FromWhichBSSID);
-	RTMP_SET_PACKET_IF(pRxBlk->pRxPacket, FromWhichBSSID);
-	nMSDU = deaggregate_AMSDU_announce(pAd, pRxBlk->pRxPacket, pRxBlk->pData, pRxBlk->DataSize);
-}
-
-VOID Indicate_EAPOL_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	MAC_TABLE_ENTRY *pEntry = NULL;
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		pEntry = &pAd->MacTab.Content[BSSID_WCID];
-		STARxEAPOLFrameIndicate(pAd, pEntry, pRxBlk, FromWhichBSSID);
-		return;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	if (pEntry == NULL)
-	{
-		DBGPRINT(RT_DEBUG_WARN, ("Indicate_EAPOL_Packet: drop and release the invalid packet.\n"));
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-}
-
-#define BCN_TBTT_OFFSET		64	//defer 64 us
-VOID ReSyncBeaconTime(
-	IN  PRTMP_ADAPTER   pAd)
-{
-
-	UINT32  Offset;
-
-
-	Offset = (pAd->TbttTickCount) % (BCN_TBTT_OFFSET);
-
-	pAd->TbttTickCount++;
-
-	//
-	// The updated BeaconInterval Value will affect Beacon Interval after two TBTT
-	// beacasue the original BeaconInterval had been loaded into next TBTT_TIMER
-	//
-	if (Offset == (BCN_TBTT_OFFSET-2))
-	{
-		BCN_TIME_CFG_STRUC csr;
-		RTMP_IO_READ32(pAd, BCN_TIME_CFG, &csr.word);
-		csr.field.BeaconInterval = (pAd->CommonCfg.BeaconPeriod << 4) - 1 ;	// ASIC register in units of 1/16 TU = 64us
-		RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr.word);
-	}
-	else
-	{
-		if (Offset == (BCN_TBTT_OFFSET-1))
-		{
-			BCN_TIME_CFG_STRUC csr;
-
-			RTMP_IO_READ32(pAd, BCN_TIME_CFG, &csr.word);
-			csr.field.BeaconInterval = (pAd->CommonCfg.BeaconPeriod) << 4; // ASIC register in units of 1/16 TU
-			RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr.word);
-		}
-	}
-}
-
+#include "../../rt2870/common/cmm_data.c"
diff --git a/drivers/staging/rt3070/common/cmm_data_2870.c b/drivers/staging/rt3070/common/cmm_data_2870.c
index b1066aa..0e51ee4 100644
--- a/drivers/staging/rt3070/common/cmm_data_2870.c
+++ b/drivers/staging/rt3070/common/cmm_data_2870.c
@@ -1,980 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-*/
-/*
-   All functions in this file must be USB-depended, or you should out your function
-	in other files.
-
-*/
-#include	"../rt_config.h"
-
-
-/*
-	We can do copy the frame into pTxContext when match following conditions.
-		=>
-		=>
-		=>
-*/
-static inline NDIS_STATUS RtmpUSBCanDoWrite(
-	IN RTMP_ADAPTER		*pAd,
-	IN UCHAR			QueIdx,
-	IN HT_TX_CONTEXT 	*pHTTXContext)
-{
-	NDIS_STATUS	canWrite = NDIS_STATUS_RESOURCES;
-
-	if (((pHTTXContext->CurWritePosition) < pHTTXContext->NextBulkOutPosition) && (pHTTXContext->CurWritePosition + LOCAL_TXBUF_SIZE) > pHTTXContext->NextBulkOutPosition)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("RtmpUSBCanDoWrite c1!\n"));
-		RTUSB_SET_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << QueIdx));
-	}
-	else if ((pHTTXContext->CurWritePosition == 8) && (pHTTXContext->NextBulkOutPosition < LOCAL_TXBUF_SIZE))
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("RtmpUSBCanDoWrite c2!\n"));
-		RTUSB_SET_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << QueIdx));
-	}
-	else if (pHTTXContext->bCurWriting == TRUE)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("RtmpUSBCanDoWrite c3!\n"));
-	}
-	else
-	{
-		canWrite = NDIS_STATUS_SUCCESS;
-	}
-
-
-	return canWrite;
-}
-
-
-USHORT RtmpUSB_WriteSubTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	BOOLEAN			bIsLast,
-	OUT	USHORT			*FreeNumber)
-{
-
-	// Dummy function. Should be removed in the future.
-	return 0;
-
-}
-
-USHORT	RtmpUSB_WriteFragTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	UCHAR			fragNum,
-	OUT	USHORT			*FreeNumber)
-{
-	HT_TX_CONTEXT	*pHTTXContext;
-	USHORT			hwHdrLen;	// The hwHdrLen consist of 802.11 header length plus the header padding length.
-	UINT32			fillOffset;
-	TXINFO_STRUC	*pTxInfo;
-	TXWI_STRUC		*pTxWI;
-	PUCHAR			pWirelessPacket = NULL;
-	UCHAR			QueIdx;
-	NDIS_STATUS		Status;
-	unsigned long	IrqFlags;
-	UINT32			USBDMApktLen = 0, DMAHdrLen, padding;
-	BOOLEAN			TxQLastRound = FALSE;
-
-	//
-	// get Tx Ring Resource & Dma Buffer address
-	//
-	QueIdx = pTxBlk->QueIdx;
-	pHTTXContext  = &pAd->TxContext[QueIdx];
-
-	RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-	pHTTXContext  = &pAd->TxContext[QueIdx];
-	fillOffset = pHTTXContext->CurWritePosition;
-
-	if(fragNum == 0)
-	{
-		// Check if we have enough space for this bulk-out batch.
-		Status = RtmpUSBCanDoWrite(pAd, QueIdx, pHTTXContext);
-		if (Status == NDIS_STATUS_SUCCESS)
-		{
-			pHTTXContext->bCurWriting = TRUE;
-
-			// Reserve space for 8 bytes padding.
-			if ((pHTTXContext->ENextBulkOutPosition == pHTTXContext->CurWritePosition))
-			{
-				pHTTXContext->ENextBulkOutPosition += 8;
-				pHTTXContext->CurWritePosition += 8;
-				fillOffset += 8;
-			}
-			pTxBlk->Priv = 0;
-			pHTTXContext->CurWriteRealPos = pHTTXContext->CurWritePosition;
-		}
-		else
-		{
-			RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-			RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-			return(Status);
-		}
-	}
-	else
-	{
-		// For sub-sequent frames of this bulk-out batch. Just copy it to our bulk-out buffer.
-		Status = ((pHTTXContext->bCurWriting == TRUE) ? NDIS_STATUS_SUCCESS : NDIS_STATUS_FAILURE);
-		if (Status == NDIS_STATUS_SUCCESS)
-		{
-			fillOffset += pTxBlk->Priv;
-		}
-		else
-		{
-			RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-			RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-			return(Status);
-		}
-	}
-
-	NdisZeroMemory((PUCHAR)(&pTxBlk->HeaderBuf[0]), TXINFO_SIZE);
-	pTxInfo = (PTXINFO_STRUC)(&pTxBlk->HeaderBuf[0]);
-	pTxWI= (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]);
-
-	pWirelessPacket = &pHTTXContext->TransferBuffer->field.WirelessPacket[fillOffset];
-
-	// copy TXWI + WLAN Header + LLC into DMA Header Buffer
-	//hwHdrLen = ROUND_UP(pTxBlk->MpduHeaderLen, 4);
-	hwHdrLen = pTxBlk->MpduHeaderLen + pTxBlk->HdrPadLen;
-
-	// Build our URB for USBD
-	DMAHdrLen = TXWI_SIZE + hwHdrLen;
-	USBDMApktLen = DMAHdrLen + pTxBlk->SrcBufLen;
-	padding = (4 - (USBDMApktLen % 4)) & 0x03;	// round up to 4 byte alignment
-	USBDMApktLen += padding;
-
-	pTxBlk->Priv += (TXINFO_SIZE + USBDMApktLen);
-
-	// For TxInfo, the length of USBDMApktLen = TXWI_SIZE + 802.11 header + payload
-	RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(USBDMApktLen), FALSE, FIFO_EDCA, FALSE /*NextValid*/,  FALSE);
-
-	if (fragNum == pTxBlk->TotalFragNum)
-	{
-		pTxInfo->USBDMATxburst = 0;
-		if ((pHTTXContext->CurWritePosition + pTxBlk->Priv + 3906)> MAX_TXBULK_LIMIT)
-		{
-			pTxInfo->SwUseLastRound = 1;
-			TxQLastRound = TRUE;
-		}
-	}
-	else
-	{
-		pTxInfo->USBDMATxburst = 1;
-	}
-
-	NdisMoveMemory(pWirelessPacket, pTxBlk->HeaderBuf, TXINFO_SIZE + TXWI_SIZE + hwHdrLen);
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)(pWirelessPacket + TXINFO_SIZE + TXWI_SIZE), DIR_WRITE, FALSE);
-#endif // RT_BIG_ENDIAN //
-	pWirelessPacket += (TXINFO_SIZE + TXWI_SIZE + hwHdrLen);
-	pHTTXContext->CurWriteRealPos += (TXINFO_SIZE + TXWI_SIZE + hwHdrLen);
-
-	RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-	NdisMoveMemory(pWirelessPacket, pTxBlk->pSrcBufData, pTxBlk->SrcBufLen);
-
-	//	Zero the last padding.
-	pWirelessPacket += pTxBlk->SrcBufLen;
-	NdisZeroMemory(pWirelessPacket, padding + 8);
-
-	if (fragNum == pTxBlk->TotalFragNum)
-	{
-		RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-		// Update the pHTTXContext->CurWritePosition. 3906 used to prevent the NextBulkOut is a A-RALINK/A-MSDU Frame.
-		pHTTXContext->CurWritePosition += pTxBlk->Priv;
-		if (TxQLastRound == TRUE)
-			pHTTXContext->CurWritePosition = 8;
-		pHTTXContext->CurWriteRealPos = pHTTXContext->CurWritePosition;
-
-
-		// Finally, set bCurWriting as FALSE
-	pHTTXContext->bCurWriting = FALSE;
-
-		RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-		// succeed and release the skb buffer
-		RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_SUCCESS);
-	}
-
-
-	return(Status);
-
-}
-
-
-USHORT RtmpUSB_WriteSingleTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	BOOLEAN			bIsLast,
-	OUT	USHORT			*FreeNumber)
-{
-	HT_TX_CONTEXT	*pHTTXContext;
-	USHORT			hwHdrLen;
-	UINT32			fillOffset;
-	TXINFO_STRUC	*pTxInfo;
-	TXWI_STRUC		*pTxWI;
-	PUCHAR			pWirelessPacket;
-	UCHAR			QueIdx;
-	unsigned long	IrqFlags;
-	NDIS_STATUS		Status;
-	UINT32			USBDMApktLen = 0, DMAHdrLen, padding;
-	BOOLEAN			bTxQLastRound = FALSE;
-
-	// For USB, didn't need PCI_MAP_SINGLE()
-	//SrcBufPA = PCI_MAP_SINGLE(pAd, (char *) pTxBlk->pSrcBufData, pTxBlk->SrcBufLen, PCI_DMA_TODEVICE);
-
-
-	//
-	// get Tx Ring Resource & Dma Buffer address
-	//
-	QueIdx = pTxBlk->QueIdx;
-
-	RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-	pHTTXContext  = &pAd->TxContext[QueIdx];
-	fillOffset = pHTTXContext->CurWritePosition;
-
-
-
-	// Check ring full.
-	Status = RtmpUSBCanDoWrite(pAd, QueIdx, pHTTXContext);
-	if(Status == NDIS_STATUS_SUCCESS)
-	{
-		pHTTXContext->bCurWriting = TRUE;
-
-		pTxInfo = (PTXINFO_STRUC)(&pTxBlk->HeaderBuf[0]);
-		pTxWI= (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]);
-
-		// Reserve space for 8 bytes padding.
-		if ((pHTTXContext->ENextBulkOutPosition == pHTTXContext->CurWritePosition))
-		{
-			pHTTXContext->ENextBulkOutPosition += 8;
-			pHTTXContext->CurWritePosition += 8;
-			fillOffset += 8;
-		}
-		pHTTXContext->CurWriteRealPos = pHTTXContext->CurWritePosition;
-
-		pWirelessPacket = &pHTTXContext->TransferBuffer->field.WirelessPacket[fillOffset];
-
-		// copy TXWI + WLAN Header + LLC into DMA Header Buffer
-		//hwHdrLen = ROUND_UP(pTxBlk->MpduHeaderLen, 4);
-		hwHdrLen = pTxBlk->MpduHeaderLen + pTxBlk->HdrPadLen;
-
-		// Build our URB for USBD
-		DMAHdrLen = TXWI_SIZE + hwHdrLen;
-		USBDMApktLen = DMAHdrLen + pTxBlk->SrcBufLen;
-		padding = (4 - (USBDMApktLen % 4)) & 0x03;	// round up to 4 byte alignment
-		USBDMApktLen += padding;
-
-		pTxBlk->Priv = (TXINFO_SIZE + USBDMApktLen);
-
-		// For TxInfo, the length of USBDMApktLen = TXWI_SIZE + 802.11 header + payload
-		//PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(USBDMApktLen), FALSE, FIFO_EDCA, FALSE /*NextValid*/,  FALSE);
-#endif // CONFIG_STA_SUPPORT //
-
-		if ((pHTTXContext->CurWritePosition + 3906 + pTxBlk->Priv) > MAX_TXBULK_LIMIT)
-		{
-			pTxInfo->SwUseLastRound = 1;
-			bTxQLastRound = TRUE;
-		}
-		NdisMoveMemory(pWirelessPacket, pTxBlk->HeaderBuf, TXINFO_SIZE + TXWI_SIZE + hwHdrLen);
-#ifdef RT_BIG_ENDIAN
-		RTMPFrameEndianChange(pAd, (PUCHAR)(pWirelessPacket + TXINFO_SIZE + TXWI_SIZE), DIR_WRITE, FALSE);
-#endif // RT_BIG_ENDIAN //
-		pWirelessPacket += (TXINFO_SIZE + TXWI_SIZE + hwHdrLen);
-
-		// We unlock it here to prevent the first 8 bytes maybe over-writed issue.
-		//	1. First we got CurWritePosition but the first 8 bytes still not write to the pTxcontext.
-		//	2. An interrupt break our routine and handle bulk-out complete.
-		//	3. In the bulk-out compllete, it need to do another bulk-out,
-		//			if the ENextBulkOutPosition is just the same as CurWritePosition, it will save the first 8 bytes from CurWritePosition,
-		//			but the payload still not copyed. the pTxContext->SavedPad[] will save as allzero. and set the bCopyPad = TRUE.
-		//	4. Interrupt complete.
-		//  5. Our interrupted routine go back and fill the first 8 bytes to pTxContext.
-		//	6. Next time when do bulk-out, it found the bCopyPad==TRUE and will copy the SavedPad[] to pTxContext->NextBulkOutPosition.
-		//		and the packet will wrong.
-		pHTTXContext->CurWriteRealPos += (TXINFO_SIZE + TXWI_SIZE + hwHdrLen);
-		RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-		NdisMoveMemory(pWirelessPacket, pTxBlk->pSrcBufData, pTxBlk->SrcBufLen);
-		pWirelessPacket += pTxBlk->SrcBufLen;
-		NdisZeroMemory(pWirelessPacket, padding + 8);
-
-		RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-		pHTTXContext->CurWritePosition += pTxBlk->Priv;
-		if (bTxQLastRound)
-			pHTTXContext->CurWritePosition = 8;
-		pHTTXContext->CurWriteRealPos = pHTTXContext->CurWritePosition;
-
-	pHTTXContext->bCurWriting = FALSE;
-	}
-
-
-	RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-
-	// succeed and release the skb buffer
-	RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_SUCCESS);
-
-	return(Status);
-
-}
-
-
-USHORT RtmpUSB_WriteMultiTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	UCHAR			frameNum,
-	OUT	USHORT			*FreeNumber)
-{
-	HT_TX_CONTEXT	*pHTTXContext;
-	USHORT			hwHdrLen;	// The hwHdrLen consist of 802.11 header length plus the header padding length.
-	UINT32			fillOffset;
-	TXINFO_STRUC	*pTxInfo;
-	TXWI_STRUC		*pTxWI;
-	PUCHAR			pWirelessPacket = NULL;
-	UCHAR			QueIdx;
-	NDIS_STATUS		Status;
-	unsigned long	IrqFlags;
-	//UINT32			USBDMApktLen = 0, DMAHdrLen, padding;
-
-	//
-	// get Tx Ring Resource & Dma Buffer address
-	//
-	QueIdx = pTxBlk->QueIdx;
-	pHTTXContext  = &pAd->TxContext[QueIdx];
-
-	RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-	if(frameNum == 0)
-	{
-		// Check if we have enough space for this bulk-out batch.
-		Status = RtmpUSBCanDoWrite(pAd, QueIdx, pHTTXContext);
-		if (Status == NDIS_STATUS_SUCCESS)
-		{
-			pHTTXContext->bCurWriting = TRUE;
-
-			pTxInfo = (PTXINFO_STRUC)(&pTxBlk->HeaderBuf[0]);
-			pTxWI= (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]);
-
-
-			// Reserve space for 8 bytes padding.
-			if ((pHTTXContext->ENextBulkOutPosition == pHTTXContext->CurWritePosition))
-			{
-
-				pHTTXContext->CurWritePosition += 8;
-				pHTTXContext->ENextBulkOutPosition += 8;
-			}
-			fillOffset = pHTTXContext->CurWritePosition;
-			pHTTXContext->CurWriteRealPos = pHTTXContext->CurWritePosition;
-
-			pWirelessPacket = &pHTTXContext->TransferBuffer->field.WirelessPacket[fillOffset];
-
-			//
-			// Copy TXINFO + TXWI + WLAN Header + LLC into DMA Header Buffer
-			//
-			if (pTxBlk->TxFrameType == TX_AMSDU_FRAME)
-				//hwHdrLen = ROUND_UP(pTxBlk->MpduHeaderLen-LENGTH_AMSDU_SUBFRAMEHEAD, 4)+LENGTH_AMSDU_SUBFRAMEHEAD;
-				hwHdrLen = pTxBlk->MpduHeaderLen-LENGTH_AMSDU_SUBFRAMEHEAD + pTxBlk->HdrPadLen + LENGTH_AMSDU_SUBFRAMEHEAD;
-			else if (pTxBlk->TxFrameType == TX_RALINK_FRAME)
-				//hwHdrLen = ROUND_UP(pTxBlk->MpduHeaderLen-LENGTH_ARALINK_HEADER_FIELD, 4)+LENGTH_ARALINK_HEADER_FIELD;
-				hwHdrLen = pTxBlk->MpduHeaderLen-LENGTH_ARALINK_HEADER_FIELD + pTxBlk->HdrPadLen + LENGTH_ARALINK_HEADER_FIELD;
-			else
-				//hwHdrLen = ROUND_UP(pTxBlk->MpduHeaderLen, 4);
-				hwHdrLen = pTxBlk->MpduHeaderLen + pTxBlk->HdrPadLen;
-
-			// Update the pTxBlk->Priv.
-			pTxBlk->Priv = TXINFO_SIZE + TXWI_SIZE + hwHdrLen;
-
-			//	pTxInfo->USBDMApktLen now just a temp value and will to correct latter.
-			RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(pTxBlk->Priv), FALSE, FIFO_EDCA, FALSE /*NextValid*/,  FALSE);
-
-			// Copy it.
-			NdisMoveMemory(pWirelessPacket, pTxBlk->HeaderBuf, pTxBlk->Priv);
-#ifdef RT_BIG_ENDIAN
-			RTMPFrameEndianChange(pAd, (PUCHAR)(pWirelessPacket+ TXINFO_SIZE + TXWI_SIZE), DIR_WRITE, FALSE);
-#endif // RT_BIG_ENDIAN //
-			pHTTXContext->CurWriteRealPos += pTxBlk->Priv;
-			pWirelessPacket += pTxBlk->Priv;
-		}
-	}
-	else
-	{	// For sub-sequent frames of this bulk-out batch. Just copy it to our bulk-out buffer.
-
-		Status = ((pHTTXContext->bCurWriting == TRUE) ? NDIS_STATUS_SUCCESS : NDIS_STATUS_FAILURE);
-		if (Status == NDIS_STATUS_SUCCESS)
-		{
-			fillOffset =  (pHTTXContext->CurWritePosition + pTxBlk->Priv);
-			pWirelessPacket = &pHTTXContext->TransferBuffer->field.WirelessPacket[fillOffset];
-
-			//hwHdrLen = pTxBlk->MpduHeaderLen;
-			NdisMoveMemory(pWirelessPacket, pTxBlk->HeaderBuf, pTxBlk->MpduHeaderLen);
-			pWirelessPacket += (pTxBlk->MpduHeaderLen);
-			pTxBlk->Priv += pTxBlk->MpduHeaderLen;
-		}
-		else
-		{	// It should not happened now unless we are going to shutdown.
-			DBGPRINT(RT_DEBUG_ERROR, ("WriteMultiTxResource():bCurWriting is FALSE when handle sub-sequent frames.\n"));
-			Status = NDIS_STATUS_FAILURE;
-		}
-	}
-
-
-	// We unlock it here to prevent the first 8 bytes maybe over-write issue.
-	//	1. First we got CurWritePosition but the first 8 bytes still not write to the pTxContext.
-	//	2. An interrupt break our routine and handle bulk-out complete.
-	//	3. In the bulk-out compllete, it need to do another bulk-out,
-	//			if the ENextBulkOutPosition is just the same as CurWritePosition, it will save the first 8 bytes from CurWritePosition,
-	//			but the payload still not copyed. the pTxContext->SavedPad[] will save as allzero. and set the bCopyPad = TRUE.
-	//	4. Interrupt complete.
-	//  5. Our interrupted routine go back and fill the first 8 bytes to pTxContext.
-	//	6. Next time when do bulk-out, it found the bCopyPad==TRUE and will copy the SavedPad[] to pTxContext->NextBulkOutPosition.
-	//		and the packet will wrong.
-	RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("WriteMultiTxResource: CWPos = %ld, NBOutPos = %ld.\n", pHTTXContext->CurWritePosition, pHTTXContext->NextBulkOutPosition));
-		goto done;
-	}
-
-	// Copy the frame content into DMA buffer and update the pTxBlk->Priv
-	NdisMoveMemory(pWirelessPacket, pTxBlk->pSrcBufData, pTxBlk->SrcBufLen);
-	pWirelessPacket += pTxBlk->SrcBufLen;
-	pTxBlk->Priv += pTxBlk->SrcBufLen;
-
-done:
-	// Release the skb buffer here
-	RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_SUCCESS);
-
-	return(Status);
-
-}
-
-
-VOID RtmpUSB_FinalWriteTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	USHORT			totalMPDUSize,
-	IN	USHORT			TxIdx)
-{
-	UCHAR			QueIdx;
-	HT_TX_CONTEXT	*pHTTXContext;
-	UINT32			fillOffset;
-	TXINFO_STRUC	*pTxInfo;
-	TXWI_STRUC		*pTxWI;
-	UINT32			USBDMApktLen, padding;
-	unsigned long	IrqFlags;
-	PUCHAR			pWirelessPacket;
-
-	QueIdx = pTxBlk->QueIdx;
-	pHTTXContext  = &pAd->TxContext[QueIdx];
-
-	RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-	if (pHTTXContext->bCurWriting == TRUE)
-	{
-		fillOffset = pHTTXContext->CurWritePosition;
-		if (((pHTTXContext->ENextBulkOutPosition == pHTTXContext->CurWritePosition) || ((pHTTXContext->ENextBulkOutPosition-8) == pHTTXContext->CurWritePosition))
-			&& (pHTTXContext->bCopySavePad == TRUE))
-			pWirelessPacket = (PUCHAR)(&pHTTXContext->SavedPad[0]);
-		else
-			pWirelessPacket = (PUCHAR)(&pHTTXContext->TransferBuffer->field.WirelessPacket[fillOffset]);
-
-		//
-		// Update TxInfo->USBDMApktLen ,
-		//		the length = TXWI_SIZE + 802.11_hdr + 802.11_hdr_pad + payload_of_all_batch_frames + Bulk-Out-padding
-		//
-		pTxInfo = (PTXINFO_STRUC)(pWirelessPacket);
-
-		// Calculate the bulk-out padding
-		USBDMApktLen = pTxBlk->Priv - TXINFO_SIZE;
-		padding = (4 - (USBDMApktLen % 4)) & 0x03;	// round up to 4 byte alignment
-		USBDMApktLen += padding;
-
-		pTxInfo->USBDMATxPktLen = USBDMApktLen;
-
-		//
-		// Update TXWI->MPDUtotalByteCount ,
-		//		the length = 802.11 header + payload_of_all_batch_frames
-		pTxWI= (PTXWI_STRUC)(pWirelessPacket + TXINFO_SIZE);
-		pTxWI->MPDUtotalByteCount = totalMPDUSize;
-
-		//
-		// Update the pHTTXContext->CurWritePosition
-		//
-		pHTTXContext->CurWritePosition += (TXINFO_SIZE + USBDMApktLen);
-		if ((pHTTXContext->CurWritePosition + 3906)> MAX_TXBULK_LIMIT)
-		{	// Add 3906 for prevent the NextBulkOut packet size is a A-RALINK/A-MSDU Frame.
-			pHTTXContext->CurWritePosition = 8;
-			pTxInfo->SwUseLastRound = 1;
-		}
-		pHTTXContext->CurWriteRealPos = pHTTXContext->CurWritePosition;
-
-
-		//
-		//	Zero the last padding.
-		//
-		pWirelessPacket = (&pHTTXContext->TransferBuffer->field.WirelessPacket[fillOffset + pTxBlk->Priv]);
-		NdisZeroMemory(pWirelessPacket, padding + 8);
-
-		// Finally, set bCurWriting as FALSE
-		pHTTXContext->bCurWriting = FALSE;
-
-	}
-	else
-	{	// It should not happened now unless we are going to shutdown.
-		DBGPRINT(RT_DEBUG_ERROR, ("FinalWriteTxResource():bCurWriting is FALSE when handle last frames.\n"));
-	}
-
-	RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-
-}
-
-
-VOID RtmpUSBDataLastTxIdx(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			QueIdx,
-	IN	USHORT			TxIdx)
-{
-	// DO nothing for USB.
-}
-
-
-/*
-	When can do bulk-out:
-		1. TxSwFreeIdx < TX_RING_SIZE;
-			It means has at least one Ring entity is ready for bulk-out, kick it out.
-		2. If TxSwFreeIdx == TX_RING_SIZE
-			Check if the CurWriting flag is FALSE, if it's FALSE, we can do kick out.
-
-*/
-VOID RtmpUSBDataKickOut(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	UCHAR			QueIdx)
-{
-	RTUSB_SET_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << QueIdx));
-	RTUSBKickBulkOut(pAd);
-
-}
-
-
-/*
-	Must be run in Interrupt context
-	This function handle RT2870 specific TxDesc and cpu index update and kick the packet out.
- */
-int RtmpUSBMgmtKickOut(
-	IN RTMP_ADAPTER 	*pAd,
-	IN UCHAR 			QueIdx,
-	IN PNDIS_PACKET		pPacket,
-	IN PUCHAR			pSrcBufVA,
-	IN UINT 			SrcBufLen)
-{
-	PTXINFO_STRUC	pTxInfo;
-	ULONG			BulkOutSize;
-	UCHAR			padLen;
-	PUCHAR			pDest;
-	ULONG			SwIdx = pAd->MgmtRing.TxCpuIdx;
-	PTX_CONTEXT		pMLMEContext = (PTX_CONTEXT)pAd->MgmtRing.Cell[SwIdx].AllocVa;
-	unsigned long	IrqFlags;
-
-
-	pTxInfo = (PTXINFO_STRUC)(pSrcBufVA);
-
-	// Build our URB for USBD
-	BulkOutSize = SrcBufLen;
-	BulkOutSize = (BulkOutSize + 3) & (~3);
-	RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(BulkOutSize - TXINFO_SIZE), TRUE, EpToQueue[MGMTPIPEIDX], FALSE,  FALSE);
-
-	BulkOutSize += 4; // Always add 4 extra bytes at every packet.
-
-	// If BulkOutSize is multiple of BulkOutMaxPacketSize, add extra 4 bytes again.
-	if ((BulkOutSize % pAd->BulkOutMaxPacketSize) == 0)
-		BulkOutSize += 4;
-
-	padLen = BulkOutSize - SrcBufLen;
-	ASSERT((padLen <= RTMP_PKT_TAIL_PADDING));
-
-	// Now memzero all extra padding bytes.
-	pDest = (PUCHAR)(pSrcBufVA + SrcBufLen);
-	skb_put(GET_OS_PKT_TYPE(pPacket), padLen);
-	NdisZeroMemory(pDest, padLen);
-
-	RTMP_IRQ_LOCK(&pAd->MLMEBulkOutLock, IrqFlags);
-
-	pAd->MgmtRing.Cell[pAd->MgmtRing.TxCpuIdx].pNdisPacket = pPacket;
-	pMLMEContext->TransferBuffer = (PTX_BUFFER)(GET_OS_PKT_DATAPTR(pPacket));
-
-	// Length in TxInfo should be 8 less than bulkout size.
-	pMLMEContext->BulkOutSize = BulkOutSize;
-	pMLMEContext->InUse = TRUE;
-	pMLMEContext->bWaitingBulkOut = TRUE;
-
-
-	//for debug
-	//hex_dump("RtmpUSBMgmtKickOut", &pMLMEContext->TransferBuffer->field.WirelessPacket[0], (pMLMEContext->BulkOutSize > 16 ? 16 : pMLMEContext->BulkOutSize));
-
-	//pAd->RalinkCounters.KickTxCount++;
-	//pAd->RalinkCounters.OneSecTxDoneCount++;
-
-	//if (pAd->MgmtRing.TxSwFreeIdx == MGMT_RING_SIZE)
-	//	needKickOut = TRUE;
-
-	// Decrease the TxSwFreeIdx and Increase the TX_CTX_IDX
-	pAd->MgmtRing.TxSwFreeIdx--;
-	INC_RING_INDEX(pAd->MgmtRing.TxCpuIdx, MGMT_RING_SIZE);
-
-	RTMP_IRQ_UNLOCK(&pAd->MLMEBulkOutLock, IrqFlags);
-
-	RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_MLME);
-	//if (needKickOut)
-	RTUSBKickBulkOut(pAd);
-
-	return 0;
-}
-
-
-VOID RtmpUSBNullFrameKickOut(
-	IN RTMP_ADAPTER *pAd,
-	IN UCHAR		QueIdx,
-	IN UCHAR		*pNullFrame,
-	IN UINT32		frameLen)
-{
-	if (pAd->NullContext.InUse == FALSE)
-	{
-		PTX_CONTEXT		pNullContext;
-		PTXINFO_STRUC	pTxInfo;
-		PTXWI_STRUC		pTxWI;
-		PUCHAR			pWirelessPkt;
-
-		pNullContext = &(pAd->NullContext);
-
-		// Set the in use bit
-		pNullContext->InUse = TRUE;
-		pWirelessPkt = (PUCHAR)&pNullContext->TransferBuffer->field.WirelessPacket[0];
-
-		RTMPZeroMemory(&pWirelessPkt[0], 100);
-		pTxInfo = (PTXINFO_STRUC)&pWirelessPkt[0];
-		RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(sizeof(HEADER_802_11)+TXWI_SIZE), TRUE, EpToQueue[MGMTPIPEIDX], FALSE,  FALSE);
-		pTxInfo->QSEL = FIFO_EDCA;
-		pTxWI = (PTXWI_STRUC)&pWirelessPkt[TXINFO_SIZE];
-		RTMPWriteTxWI(pAd, pTxWI,  FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, 0, BSSID_WCID, (sizeof(HEADER_802_11)),
-			0, 0, (UCHAR)pAd->CommonCfg.MlmeTransmit.field.MCS, IFS_HTTXOP, FALSE, &pAd->CommonCfg.MlmeTransmit);
-#ifdef RT_BIG_ENDIAN
-		RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-#endif // RT_BIG_ENDIAN //
-
-		RTMPMoveMemory(&pWirelessPkt[TXWI_SIZE+TXINFO_SIZE], &pAd->NullFrame, sizeof(HEADER_802_11));
-#ifdef RT_BIG_ENDIAN
-		RTMPFrameEndianChange(pAd, (PUCHAR)&pWirelessPkt[TXINFO_SIZE + TXWI_SIZE], DIR_WRITE, FALSE);
-#endif // RT_BIG_ENDIAN //
-		pAd->NullContext.BulkOutSize =  TXINFO_SIZE + TXWI_SIZE + sizeof(pAd->NullFrame) + 4;
-
-		// Fill out frame length information for global Bulk out arbitor
-		//pNullContext->BulkOutSize = TransferBufferLength;
-		DBGPRINT(RT_DEBUG_TRACE, ("SYNC - send NULL Frame @%d Mbps...\n", RateIdToMbps[pAd->CommonCfg.TxRate]));
-		RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NULL);
-
-		// Kick bulk out
-		RTUSBKickBulkOut(pAd);
-	}
-
-}
-
-#ifdef CONFIG_STA_SUPPORT
-/*
-	========================================================================
-
-	Routine	Description:
-		Check Rx descriptor, return NDIS_STATUS_FAILURE if any error dound
-
-	Arguments:
-		pRxD		Pointer	to the Rx descriptor
-
-	Return Value:
-		NDIS_STATUS_SUCCESS		No err
-		NDIS_STATUS_FAILURE		Error
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS	RTMPCheckRxError(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PHEADER_802_11	pHeader,
-	IN	PRXWI_STRUC	pRxWI,
-	IN	PRT28XX_RXD_STRUC	pRxINFO)
-{
-	PCIPHER_KEY pWpaKey;
-	INT	dBm;
-
-	if (pAd->bPromiscuous == TRUE)
-		return(NDIS_STATUS_SUCCESS);
-	if(pRxINFO == NULL)
-		return(NDIS_STATUS_FAILURE);
-
-	// Phy errors & CRC errors
-	if (pRxINFO->Crc)
-	{
-		// Check RSSI for Noise Hist statistic collection.
-		dBm = (INT) (pRxWI->RSSI0) - pAd->BbpRssiToDbmDelta;
-		if (dBm <= -87)
-			pAd->StaCfg.RPIDensity[0] += 1;
-		else if (dBm <= -82)
-			pAd->StaCfg.RPIDensity[1] += 1;
-		else if (dBm <= -77)
-			pAd->StaCfg.RPIDensity[2] += 1;
-		else if (dBm <= -72)
-			pAd->StaCfg.RPIDensity[3] += 1;
-		else if (dBm <= -67)
-			pAd->StaCfg.RPIDensity[4] += 1;
-		else if (dBm <= -62)
-			pAd->StaCfg.RPIDensity[5] += 1;
-		else if (dBm <= -57)
-			pAd->StaCfg.RPIDensity[6] += 1;
-		else if (dBm > -57)
-			pAd->StaCfg.RPIDensity[7] += 1;
-
-		return(NDIS_STATUS_FAILURE);
-	}
-
-	// Add Rx size to channel load counter, we should ignore error counts
-	pAd->StaCfg.CLBusyBytes += (pRxWI->MPDUtotalByteCount+ 14);
-
-	// Drop ToDs promiscous frame, it is opened due to CCX 2 channel load statistics
-	if (pHeader->FC.ToDs)
-	{
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("Err;FC.ToDs\n"));
-		return NDIS_STATUS_FAILURE;
-	}
-
-	// Paul 04-03 for OFDM Rx length issue
-	if (pRxWI->MPDUtotalByteCount > MAX_AGGREGATION_SIZE)
-	{
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("received packet too long\n"));
-		return NDIS_STATUS_FAILURE;
-	}
-
-	// Drop not U2M frames, cant's drop here because we will drop beacon in this case
-	// I am kind of doubting the U2M bit operation
-	// if (pRxD->U2M == 0)
-	//	return(NDIS_STATUS_FAILURE);
-
-	// drop decyption fail frame
-	if (pRxINFO->Decrypted && pRxINFO->CipherErr)
-	{
-
-		//
-		// MIC Error
-		//
-		if ((pRxINFO->CipherErr == 2) && pRxINFO->MyBss)
-		{
-			pWpaKey = &pAd->SharedKey[BSS0][pRxWI->KeyIndex];
-			RTMPReportMicError(pAd, pWpaKey);
-			DBGPRINT_RAW(RT_DEBUG_ERROR,("Rx MIC Value error\n"));
-		}
-
-		if (pRxINFO->Decrypted &&
-			(pAd->SharedKey[BSS0][pRxWI->KeyIndex].CipherAlg == CIPHER_AES) &&
-			(pHeader->Sequence == pAd->FragFrame.Sequence))
-		{
-			//
-			// Acceptable since the First FragFrame no CipherErr problem.
-			//
-			return(NDIS_STATUS_SUCCESS);
-		}
-
-		return(NDIS_STATUS_FAILURE);
-	}
-
-	return(NDIS_STATUS_SUCCESS);
-}
-
-VOID RT28xxUsbStaAsicForceWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN       bFromTx)
-{
-    AUTO_WAKEUP_STRUC	AutoWakeupCfg;
-
-	AutoWakeupCfg.word = 0;
-	RTMP_IO_WRITE32(pAd, AUTO_WAKEUP_CFG, AutoWakeupCfg.word);
-
-	AsicSendCommandToMcu(pAd, 0x31, 0xff, 0x00, 0x02);
-
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_DOZE);
-}
-
-VOID RT28xxUsbStaAsicSleepThenAutoWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT TbttNumToNextWakeUp)
-{
-	AUTO_WAKEUP_STRUC	AutoWakeupCfg;
-
-	// we have decided to SLEEP, so at least do it for a BEACON period.
-	if (TbttNumToNextWakeUp == 0)
-		TbttNumToNextWakeUp = 1;
-
-	AutoWakeupCfg.word = 0;
-	RTMP_IO_WRITE32(pAd, AUTO_WAKEUP_CFG, AutoWakeupCfg.word);
-
-	AutoWakeupCfg.field.NumofSleepingTbtt = TbttNumToNextWakeUp - 1;
-	AutoWakeupCfg.field.EnableAutoWakeup = 1;
-	AutoWakeupCfg.field.AutoLeadTime = 5;
-	RTMP_IO_WRITE32(pAd, AUTO_WAKEUP_CFG, AutoWakeupCfg.word);
-
-	AsicSendCommandToMcu(pAd, 0x30, 0xff, 0xff, 0x02);   // send POWER-SAVE command to MCU. Timeout 40us.
-
-	OPSTATUS_SET_FLAG(pAd, fOP_STATUS_DOZE);
-
-}
-#endif // CONFIG_STA_SUPPORT //
-
-VOID RT28xxUsbMlmeRadioOn(
-	IN PRTMP_ADAPTER pAd)
-{
-    DBGPRINT(RT_DEBUG_TRACE,("RT28xxUsbMlmeRadioOn()\n"));
-
-	if (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))
-		return;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-    	AsicSendCommandToMcu(pAd, 0x31, 0xff, 0x00, 0x02);
-		RTMPusecDelay(10000);
-	}
-#endif // CONFIG_STA_SUPPORT //
-	NICResetFromError(pAd);
-
-	// Enable Tx/Rx
-	RTMPEnableRxTx(pAd);
-
-#ifdef RT3070
-	if (IS_RT3071(pAd))
-	{
-		RT30xxReverseRFSleepModeSetup(pAd);
-	}
-#endif // RT3070 //
-
-	// Clear Radio off flag
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		RTUSBBulkReceive(pAd);
-#endif // CONFIG_STA_SUPPORT //
-
-	// Set LED
-	RTMPSetLED(pAd, LED_RADIO_ON);
-}
-
-VOID RT28xxUsbMlmeRadioOFF(
-	IN PRTMP_ADAPTER pAd)
-{
-	WPDMA_GLO_CFG_STRUC	GloCfg;
-	UINT32	Value, i;
-
-	DBGPRINT(RT_DEBUG_TRACE,("RT28xxUsbMlmeRadioOFF()\n"));
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))
-		return;
-
-	// Set LED
-	RTMPSetLED(pAd, LED_RADIO_OFF);
-	// Set Radio off flag
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Link down first if any association exists
-		if (INFRA_ON(pAd) || ADHOC_ON(pAd))
-			LinkDown(pAd, FALSE);
-		RTMPusecDelay(10000);
-
-		//==========================================
-		// Clean up old bss table
-		BssTableInit(&pAd->ScanTab);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-
-	if (pAd->CommonCfg.BBPCurrentBW == BW_40)
-	{
-		// Must using 40MHz.
-		AsicTurnOffRFClk(pAd, pAd->CommonCfg.CentralChannel);
-	}
-	else
-	{
-		// Must using 20MHz.
-		AsicTurnOffRFClk(pAd, pAd->CommonCfg.Channel);
-	}
-
-	// Disable Tx/Rx DMA
-	RTUSBReadMACRegister(pAd, WPDMA_GLO_CFG, &GloCfg.word);	   // disable DMA
-	GloCfg.field.EnableTxDMA = 0;
-	GloCfg.field.EnableRxDMA = 0;
-	RTUSBWriteMACRegister(pAd, WPDMA_GLO_CFG, GloCfg.word);	   // abort all TX rings
-
-	// Waiting for DMA idle
-	i = 0;
-	do
-	{
-		RTMP_IO_READ32(pAd, WPDMA_GLO_CFG, &GloCfg.word);
-		if ((GloCfg.field.TxDMABusy == 0) && (GloCfg.field.RxDMABusy == 0))
-			break;
-
-		RTMPusecDelay(1000);
-	}while (i++ < 100);
-
-	// Disable MAC Tx/Rx
-	RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-	Value &= (0xfffffff3);
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-	// MAC_SYS_CTRL => value = 0x0 => 40mA
-	//RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0);
-
-	// PWR_PIN_CFG => value = 0x0 => 40mA
-	//RTMP_IO_WRITE32(pAd, PWR_PIN_CFG, 0);
-
-	// TX_PIN_CFG => value = 0x0 => 20mA
-	//RTMP_IO_WRITE32(pAd, TX_PIN_CFG, 0);
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		AsicSendCommandToMcu(pAd, 0x30, 0xff, 0xff, 0x02);
-#endif // CONFIG_STA_SUPPORT //
-}
-
+#include "../../rt2870/common/cmm_data_2870.c"
diff --git a/drivers/staging/rt3070/common/cmm_info.c b/drivers/staging/rt3070/common/cmm_info.c
index 54cb1a3..6e981e5 100644
--- a/drivers/staging/rt3070/common/cmm_info.c
+++ b/drivers/staging/rt3070/common/cmm_info.c
@@ -1,3395 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-*/
-
-#include	"../rt_config.h"
-
-INT	Show_SSID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_WirelessMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_TxBurst_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_TxPreamble_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_TxPower_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_Channel_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_BGProtection_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_RTSThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_FragThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-#ifdef DOT11_N_SUPPORT
-INT	Show_HtBw_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtMcs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtGi_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtOpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtExtcha_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtMpduDensity_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtBaWinSize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtRdg_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtAmsdu_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_HtAutoBa_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-#endif // DOT11_N_SUPPORT //
-
-INT	Show_CountryRegion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_CountryRegionABand_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_CountryCode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-#ifdef AGGREGATION_SUPPORT
-INT	Show_PktAggregate_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-#endif // AGGREGATION_SUPPORT //
-
-#ifdef WMM_SUPPORT
-INT	Show_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-#endif // WMM_SUPPORT //
-
-INT	Show_IEEE80211H_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-#ifdef CONFIG_STA_SUPPORT
-INT	Show_NetworkType_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-#endif // CONFIG_STA_SUPPORT //
-
-INT	Show_AuthMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_EncrypType_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_DefaultKeyID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_Key1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_Key2_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_Key3_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_Key4_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-INT	Show_WPAPSK_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf);
-
-static struct {
-	CHAR *name;
-	INT (*show_proc)(PRTMP_ADAPTER pAdapter, PUCHAR arg);
-} *PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC, RTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC[] = {
-	{"SSID",					Show_SSID_Proc},
-	{"WirelessMode",			Show_WirelessMode_Proc},
-	{"TxBurst",					Show_TxBurst_Proc},
-	{"TxPreamble",				Show_TxPreamble_Proc},
-	{"TxPower",					Show_TxPower_Proc},
-	{"Channel",					Show_Channel_Proc},
-	{"BGProtection",			Show_BGProtection_Proc},
-	{"RTSThreshold",			Show_RTSThreshold_Proc},
-	{"FragThreshold",			Show_FragThreshold_Proc},
-#ifdef DOT11_N_SUPPORT
-	{"HtBw",					Show_HtBw_Proc},
-	{"HtMcs",					Show_HtMcs_Proc},
-	{"HtGi",					Show_HtGi_Proc},
-	{"HtOpMode",				Show_HtOpMode_Proc},
-	{"HtExtcha",				Show_HtExtcha_Proc},
-	{"HtMpduDensity",			Show_HtMpduDensity_Proc},
-	{"HtBaWinSize",		        Show_HtBaWinSize_Proc},
-	{"HtRdg",		        	Show_HtRdg_Proc},
-	{"HtAmsdu",		        	Show_HtAmsdu_Proc},
-	{"HtAutoBa",		        Show_HtAutoBa_Proc},
-#endif // DOT11_N_SUPPORT //
-	{"CountryRegion",			Show_CountryRegion_Proc},
-	{"CountryRegionABand",		Show_CountryRegionABand_Proc},
-	{"CountryCode",				Show_CountryCode_Proc},
-#ifdef AGGREGATION_SUPPORT
-	{"PktAggregate",			Show_PktAggregate_Proc},
-#endif
-
-#ifdef WMM_SUPPORT
-	{"WmmCapable",				Show_WmmCapable_Proc},
-#endif
-	{"IEEE80211H",				Show_IEEE80211H_Proc},
-#ifdef CONFIG_STA_SUPPORT
-    {"NetworkType",				Show_NetworkType_Proc},
-#endif // CONFIG_STA_SUPPORT //
-	{"AuthMode",				Show_AuthMode_Proc},
-	{"EncrypType",				Show_EncrypType_Proc},
-	{"DefaultKeyID",			Show_DefaultKeyID_Proc},
-	{"Key1",					Show_Key1_Proc},
-	{"Key2",					Show_Key2_Proc},
-	{"Key3",					Show_Key3_Proc},
-	{"Key4",					Show_Key4_Proc},
-	{"WPAPSK",					Show_WPAPSK_Proc},
-	{NULL, NULL}
-};
-
-/*
-    ==========================================================================
-    Description:
-        Get Driver version.
-
-    Return:
-    ==========================================================================
-*/
-INT Set_DriverVersion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		DBGPRINT(RT_DEBUG_TRACE, ("Driver version-%s\n", STA_DRIVER_VERSION));
-#endif // CONFIG_STA_SUPPORT //
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Country Region.
-        This command will not work, if the field of CountryRegion in eeprom is programmed.
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_CountryRegion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG region;
-
-	region = simple_strtol(arg, 0, 10);
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-	return -EOPNOTSUPP;
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-	// Country can be set only when EEPROM not programmed
-	if (pAd->CommonCfg.CountryRegion & 0x80)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Set_CountryRegion_Proc::parameter of CountryRegion in eeprom is programmed \n"));
-		return FALSE;
-	}
-
-	if((region >= 0) && (region <= REGION_MAXIMUM_BG_BAND))
-	{
-		pAd->CommonCfg.CountryRegion = (UCHAR) region;
-	}
-	else if (region == REGION_31_BG_BAND)
-	{
-		pAd->CommonCfg.CountryRegion = (UCHAR) region;
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Set_CountryRegion_Proc::parameters out of range\n"));
-		return FALSE;
-	}
-
-	// if set country region, driver needs to be reset
-	BuildChannelList(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_CountryRegion_Proc::(CountryRegion=%d)\n", pAd->CommonCfg.CountryRegion));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Country Region for A band.
-        This command will not work, if the field of CountryRegion in eeprom is programmed.
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_CountryRegionABand_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG region;
-
-	region = simple_strtol(arg, 0, 10);
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-	return -EOPNOTSUPP;
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-	// Country can be set only when EEPROM not programmed
-	if (pAd->CommonCfg.CountryRegionForABand & 0x80)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Set_CountryRegionABand_Proc::parameter of CountryRegion in eeprom is programmed \n"));
-		return FALSE;
-	}
-
-	if((region >= 0) && (region <= REGION_MAXIMUM_A_BAND))
-	{
-		pAd->CommonCfg.CountryRegionForABand = (UCHAR) region;
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Set_CountryRegionABand_Proc::parameters out of range\n"));
-		return FALSE;
-	}
-
-	// if set country region, driver needs to be reset
-	BuildChannelList(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_CountryRegionABand_Proc::(CountryRegion=%d)\n", pAd->CommonCfg.CountryRegionForABand));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Wireless Mode
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_WirelessMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG	WirelessMode;
-	INT		success = TRUE;
-
-	WirelessMode = simple_strtol(arg, 0, 10);
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		INT MaxPhyMode = PHY_11G;
-
-#ifdef DOT11_N_SUPPORT
-		MaxPhyMode = PHY_11N_5G;
-#endif // DOT11_N_SUPPORT //
-
-		if (WirelessMode <= MaxPhyMode)
-		{
-			RTMPSetPhyMode(pAd, WirelessMode);
-#ifdef DOT11_N_SUPPORT
-			if (WirelessMode >= PHY_11ABGN_MIXED)
-			{
-				pAd->CommonCfg.BACapability.field.AutoBA = TRUE;
-				pAd->CommonCfg.REGBACapability.field.AutoBA = TRUE;
-			}
-			else
-			{
-				pAd->CommonCfg.BACapability.field.AutoBA = FALSE;
-				pAd->CommonCfg.REGBACapability.field.AutoBA = FALSE;
-			}
-#endif // DOT11_N_SUPPORT //
-			// Set AdhocMode rates
-			if (pAd->StaCfg.BssType == BSS_ADHOC)
-			{
-				MlmeUpdateTxRates(pAd, FALSE, 0);
-				MakeIbssBeacon(pAd);           // re-build BEACON frame
-				AsicEnableIbssSync(pAd);       // copy to on-chip memory
-			}
-		}
-		else
-		{
-			success = FALSE;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// it is needed to set SSID to take effect
-	if (success == TRUE)
-	{
-#ifdef DOT11_N_SUPPORT
-		SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-		DBGPRINT(RT_DEBUG_TRACE, ("Set_WirelessMode_Proc::(=%ld)\n", WirelessMode));
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Set_WirelessMode_Proc::parameters out of range\n"));
-	}
-
-	return success;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Channel
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_Channel_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
- 	INT		success = TRUE;
-	UCHAR	Channel;
-
-	Channel = (UCHAR) simple_strtol(arg, 0, 10);
-
-	// check if this channel is valid
-	if (ChannelSanity(pAd, Channel) == TRUE)
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			pAd->CommonCfg.Channel = Channel;
-
-			if (MONITOR_ON(pAd))
-			{
-#ifdef DOT11_N_SUPPORT
-				N_ChannelCheck(pAd);
-				if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-					pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40)
-				{
-					N_SetCenCh(pAd);
-					AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-					AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-					DBGPRINT(RT_DEBUG_TRACE, ("BW_40, control_channel(%d), CentralChannel(%d) \n",
-								pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel));
-				}
-				else
-#endif // DOT11_N_SUPPORT //
-				{
-					AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-					AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-					DBGPRINT(RT_DEBUG_TRACE, ("BW_20, Channel(%d)\n", pAd->CommonCfg.Channel));
-				}
-			}
-		}
-#endif // CONFIG_STA_SUPPORT //
-		success = TRUE;
-	}
-	else
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			success = FALSE;
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-
-	if (success == TRUE)
-		DBGPRINT(RT_DEBUG_TRACE, ("Set_Channel_Proc::(Channel=%d)\n", pAd->CommonCfg.Channel));
-
-	return success;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Short Slot Time Enable or Disable
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ShortSlot_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG ShortSlot;
-
-	ShortSlot = simple_strtol(arg, 0, 10);
-
-	if (ShortSlot == 1)
-		pAd->CommonCfg.bUseShortSlotTime = TRUE;
-	else if (ShortSlot == 0)
-		pAd->CommonCfg.bUseShortSlotTime = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_ShortSlot_Proc::(ShortSlot=%d)\n", pAd->CommonCfg.bUseShortSlotTime));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Tx power
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_TxPower_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG TxPower;
-	INT   success = FALSE;
-
-	TxPower = (ULONG) simple_strtol(arg, 0, 10);
-	if (TxPower <= 100)
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			pAd->CommonCfg.TxPowerDefault = TxPower;
-			pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault;
-		}
-#endif // CONFIG_STA_SUPPORT //
-		success = TRUE;
-	}
-	else
-		success = FALSE;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_TxPower_Proc::(TxPowerPercentage=%ld)\n", pAd->CommonCfg.TxPowerPercentage));
-
-	return success;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set 11B/11G Protection
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_BGProtection_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	switch (simple_strtol(arg, 0, 10))
-	{
-		case 0: //AUTO
-			pAd->CommonCfg.UseBGProtection = 0;
-			break;
-		case 1: //Always On
-			pAd->CommonCfg.UseBGProtection = 1;
-			break;
-		case 2: //Always OFF
-			pAd->CommonCfg.UseBGProtection = 2;
-			break;
-		default:  //Invalid argument
-			return FALSE;
-	}
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_BGProtection_Proc::(BGProtection=%ld)\n", pAd->CommonCfg.UseBGProtection));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set TxPreamble
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_TxPreamble_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	RT_802_11_PREAMBLE	Preamble;
-
-	Preamble = simple_strtol(arg, 0, 10);
-
-
-	switch (Preamble)
-	{
-		case Rt802_11PreambleShort:
-			pAd->CommonCfg.TxPreamble = Preamble;
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				MlmeSetTxPreamble(pAd, Rt802_11PreambleShort);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-		case Rt802_11PreambleLong:
-#ifdef CONFIG_STA_SUPPORT
-		case Rt802_11PreambleAuto:
-			// if user wants AUTO, initialize to LONG here, then change according to AP's
-			// capability upon association.
-#endif // CONFIG_STA_SUPPORT //
-			pAd->CommonCfg.TxPreamble = Preamble;
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				MlmeSetTxPreamble(pAd, Rt802_11PreambleLong);
-#endif // CONFIG_STA_SUPPORT //
-			break;
-		default: //Invalid argument
-			return FALSE;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_TxPreamble_Proc::(TxPreamble=%ld)\n", pAd->CommonCfg.TxPreamble));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set RTS Threshold
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_RTSThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	 NDIS_802_11_RTS_THRESHOLD           RtsThresh;
-
-	RtsThresh = simple_strtol(arg, 0, 10);
-
-	if((RtsThresh > 0) && (RtsThresh <= MAX_RTS_THRESHOLD))
-		pAd->CommonCfg.RtsThreshold  = (USHORT)RtsThresh;
-#ifdef CONFIG_STA_SUPPORT
-	else if (RtsThresh == 0)
-		pAd->CommonCfg.RtsThreshold = MAX_RTS_THRESHOLD;
-#endif // CONFIG_STA_SUPPORT //
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_RTSThreshold_Proc::(RTSThreshold=%d)\n", pAd->CommonCfg.RtsThreshold));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Fragment Threshold
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_FragThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	 NDIS_802_11_FRAGMENTATION_THRESHOLD     FragThresh;
-
-	FragThresh = simple_strtol(arg, 0, 10);
-
-	if (FragThresh > MAX_FRAG_THRESHOLD || FragThresh < MIN_FRAG_THRESHOLD)
-	{
-		//Illegal FragThresh so we set it to default
-		pAd->CommonCfg.FragmentThreshold = MAX_FRAG_THRESHOLD;
-	}
-	else if (FragThresh % 2 == 1)
-	{
-		// The length of each fragment shall always be an even number of octets, except for the last fragment
-		// of an MSDU or MMPDU, which may be either an even or an odd number of octets.
-		pAd->CommonCfg.FragmentThreshold = (USHORT)(FragThresh - 1);
-	}
-	else
-	{
-		pAd->CommonCfg.FragmentThreshold = (USHORT)FragThresh;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pAd->CommonCfg.FragmentThreshold == MAX_FRAG_THRESHOLD)
-			pAd->CommonCfg.bUseZeroToDisableFragment = TRUE;
-		else
-			pAd->CommonCfg.bUseZeroToDisableFragment = FALSE;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_FragThreshold_Proc::(FragThreshold=%d)\n", pAd->CommonCfg.FragmentThreshold));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set TxBurst
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_TxBurst_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG TxBurst;
-
-	TxBurst = simple_strtol(arg, 0, 10);
-	if (TxBurst == 1)
-		pAd->CommonCfg.bEnableTxBurst = TRUE;
-	else if (TxBurst == 0)
-		pAd->CommonCfg.bEnableTxBurst = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_TxBurst_Proc::(TxBurst=%d)\n", pAd->CommonCfg.bEnableTxBurst));
-
-	return TRUE;
-}
-
-#ifdef AGGREGATION_SUPPORT
-/*
-    ==========================================================================
-    Description:
-        Set TxBurst
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_PktAggregate_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG aggre;
-
-	aggre = simple_strtol(arg, 0, 10);
-
-	if (aggre == 1)
-		pAd->CommonCfg.bAggregationCapable = TRUE;
-	else if (aggre == 0)
-		pAd->CommonCfg.bAggregationCapable = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_PktAggregate_Proc::(AGGRE=%d)\n", pAd->CommonCfg.bAggregationCapable));
-
-	return TRUE;
-}
-#endif
-
-/*
-    ==========================================================================
-    Description:
-        Set IEEE80211H.
-        This parameter is 1 when needs radar detection, otherwise 0
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_IEEE80211H_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    ULONG ieee80211h;
-
-	ieee80211h = simple_strtol(arg, 0, 10);
-
-	if (ieee80211h == 1)
-		pAd->CommonCfg.bIEEE80211H = TRUE;
-	else if (ieee80211h == 0)
-		pAd->CommonCfg.bIEEE80211H = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_IEEE80211H_Proc::(IEEE80211H=%d)\n", pAd->CommonCfg.bIEEE80211H));
-
-	return TRUE;
-}
-
-
-#ifdef DBG
-/*
-    ==========================================================================
-    Description:
-        For Debug information
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_Debug_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	DBGPRINT(RT_DEBUG_TRACE, ("==> Set_Debug_Proc *******************\n"));
-
-    if(simple_strtol(arg, 0, 10) <= RT_DEBUG_LOUD)
-        RTDebugLevel = simple_strtol(arg, 0, 10);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<== Set_Debug_Proc(RTDebugLevel = %ld)\n", RTDebugLevel));
-
-	return TRUE;
-}
-#endif
-
-INT	Show_DescInfo_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Reset statistics counter
-
-    Arguments:
-        pAdapter            Pointer to our adapter
-        arg
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ResetStatCounter_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	//UCHAR           i;
-	//MAC_TABLE_ENTRY *pEntry;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==>Set_ResetStatCounter_Proc\n"));
-
-	// add the most up-to-date h/w raw counters into software counters
-	NICUpdateRawCounters(pAd);
-
-	NdisZeroMemory(&pAd->WlanCounters, sizeof(COUNTER_802_11));
-	NdisZeroMemory(&pAd->Counters8023, sizeof(COUNTER_802_3));
-	NdisZeroMemory(&pAd->RalinkCounters, sizeof(COUNTER_RALINK));
-
-	return TRUE;
-}
-
-BOOLEAN RTMPCheckStrPrintAble(
-    IN  CHAR *pInPutStr,
-    IN  UCHAR strLen)
-{
-    UCHAR i=0;
-
-    for (i=0; i<strLen; i++)
-    {
-        if ((pInPutStr[i] < 0x21) ||
-            (pInPutStr[i] > 0x7E))
-            return FALSE;
-    }
-
-    return TRUE;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Remove WPA Key process
-
-	Arguments:
-		pAd 					Pointer to our adapter
-		pBuf							Pointer to the where the key stored
-
-	Return Value:
-		NDIS_SUCCESS					Add key successfully
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-#ifdef CONFIG_STA_SUPPORT
-VOID    RTMPSetDesiredRates(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  LONG            Rates)
-{
-    NDIS_802_11_RATES aryRates;
-
-    memset(&aryRates, 0x00, sizeof(NDIS_802_11_RATES));
-    switch (pAdapter->CommonCfg.PhyMode)
-    {
-        case PHY_11A: // A only
-            switch (Rates)
-            {
-                case 6000000: //6M
-                    aryRates[0] = 0x0c; // 6M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_0;
-                    break;
-                case 9000000: //9M
-                    aryRates[0] = 0x12; // 9M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_1;
-                    break;
-                case 12000000: //12M
-                    aryRates[0] = 0x18; // 12M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_2;
-                    break;
-                case 18000000: //18M
-                    aryRates[0] = 0x24; // 18M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_3;
-                    break;
-                case 24000000: //24M
-                    aryRates[0] = 0x30; // 24M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_4;
-                    break;
-                case 36000000: //36M
-                    aryRates[0] = 0x48; // 36M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_5;
-                    break;
-                case 48000000: //48M
-                    aryRates[0] = 0x60; // 48M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_6;
-                    break;
-                case 54000000: //54M
-                    aryRates[0] = 0x6c; // 54M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_7;
-                    break;
-                case -1: //Auto
-                default:
-                    aryRates[0] = 0x6c; // 54Mbps
-                    aryRates[1] = 0x60; // 48Mbps
-                    aryRates[2] = 0x48; // 36Mbps
-                    aryRates[3] = 0x30; // 24Mbps
-                    aryRates[4] = 0x24; // 18M
-                    aryRates[5] = 0x18; // 12M
-                    aryRates[6] = 0x12; // 9M
-                    aryRates[7] = 0x0c; // 6M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-                    break;
-            }
-            break;
-        case PHY_11BG_MIXED: // B/G Mixed
-        case PHY_11B: // B only
-        case PHY_11ABG_MIXED: // A/B/G Mixed
-        default:
-            switch (Rates)
-            {
-                case 1000000: //1M
-                    aryRates[0] = 0x02;
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_0;
-                    break;
-                case 2000000: //2M
-                    aryRates[0] = 0x04;
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_1;
-                    break;
-                case 5000000: //5.5M
-                    aryRates[0] = 0x0b; // 5.5M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_2;
-                    break;
-                case 11000000: //11M
-                    aryRates[0] = 0x16; // 11M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_3;
-                    break;
-                case 6000000: //6M
-                    aryRates[0] = 0x0c; // 6M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_0;
-                    break;
-                case 9000000: //9M
-                    aryRates[0] = 0x12; // 9M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_1;
-                    break;
-                case 12000000: //12M
-                    aryRates[0] = 0x18; // 12M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_2;
-                    break;
-                case 18000000: //18M
-                    aryRates[0] = 0x24; // 18M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_3;
-                    break;
-                case 24000000: //24M
-                    aryRates[0] = 0x30; // 24M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_4;
-                    break;
-                case 36000000: //36M
-                    aryRates[0] = 0x48; // 36M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_5;
-                    break;
-                case 48000000: //48M
-                    aryRates[0] = 0x60; // 48M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_6;
-                    break;
-                case 54000000: //54M
-                    aryRates[0] = 0x6c; // 54M
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_7;
-                    break;
-                case -1: //Auto
-                default:
-                    if (pAdapter->CommonCfg.PhyMode == PHY_11B)
-                    { //B Only
-                        aryRates[0] = 0x16; // 11Mbps
-                        aryRates[1] = 0x0b; // 5.5Mbps
-                        aryRates[2] = 0x04; // 2Mbps
-                        aryRates[3] = 0x02; // 1Mbps
-                    }
-                    else
-                    { //(B/G) Mixed or (A/B/G) Mixed
-                        aryRates[0] = 0x6c; // 54Mbps
-                        aryRates[1] = 0x60; // 48Mbps
-                        aryRates[2] = 0x48; // 36Mbps
-                        aryRates[3] = 0x30; // 24Mbps
-                        aryRates[4] = 0x16; // 11Mbps
-                        aryRates[5] = 0x0b; // 5.5Mbps
-                        aryRates[6] = 0x04; // 2Mbps
-                        aryRates[7] = 0x02; // 1Mbps
-                    }
-                    pAdapter->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-                    break;
-            }
-            break;
-    }
-
-    NdisZeroMemory(pAdapter->CommonCfg.DesireRate, MAX_LEN_OF_SUPPORTED_RATES);
-    NdisMoveMemory(pAdapter->CommonCfg.DesireRate, &aryRates, sizeof(NDIS_802_11_RATES));
-    DBGPRINT(RT_DEBUG_TRACE, (" RTMPSetDesiredRates (%02x,%02x,%02x,%02x,%02x,%02x,%02x,%02x)\n",
-        pAdapter->CommonCfg.DesireRate[0],pAdapter->CommonCfg.DesireRate[1],
-        pAdapter->CommonCfg.DesireRate[2],pAdapter->CommonCfg.DesireRate[3],
-        pAdapter->CommonCfg.DesireRate[4],pAdapter->CommonCfg.DesireRate[5],
-        pAdapter->CommonCfg.DesireRate[6],pAdapter->CommonCfg.DesireRate[7] ));
-    // Changing DesiredRate may affect the MAX TX rate we used to TX frames out
-    MlmeUpdateTxRates(pAdapter, FALSE, 0);
-}
-
-NDIS_STATUS RTMPWPARemoveKeyProc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PVOID			pBuf)
-{
-	PNDIS_802_11_REMOVE_KEY pKey;
-	ULONG					KeyIdx;
-	NDIS_STATUS 			Status = NDIS_STATUS_FAILURE;
-	BOOLEAN 	bTxKey; 		// Set the key as transmit key
-	BOOLEAN 	bPairwise;		// Indicate the key is pairwise key
-	BOOLEAN 	bKeyRSC;		// indicate the receive  SC set by KeyRSC value.
-								// Otherwise, it will set by the NIC.
-	BOOLEAN 	bAuthenticator; // indicate key is set by authenticator.
-	INT 		i;
-
-	DBGPRINT(RT_DEBUG_TRACE,("---> RTMPWPARemoveKeyProc\n"));
-
-	pKey = (PNDIS_802_11_REMOVE_KEY) pBuf;
-	KeyIdx = pKey->KeyIndex & 0xff;
-	// Bit 31 of Add-key, Tx Key
-	bTxKey		   = (pKey->KeyIndex & 0x80000000) ? TRUE : FALSE;
-	// Bit 30 of Add-key PairwiseKey
-	bPairwise	   = (pKey->KeyIndex & 0x40000000) ? TRUE : FALSE;
-	// Bit 29 of Add-key KeyRSC
-	bKeyRSC 	   = (pKey->KeyIndex & 0x20000000) ? TRUE : FALSE;
-	// Bit 28 of Add-key Authenticator
-	bAuthenticator = (pKey->KeyIndex & 0x10000000) ? TRUE : FALSE;
-
-	// 1. If bTx is TRUE, return failure information
-	if (bTxKey == TRUE)
-		return(NDIS_STATUS_INVALID_DATA);
-
-	// 2. Check Pairwise Key
-	if (bPairwise)
-	{
-		// a. If BSSID is broadcast, remove all pairwise keys.
-		// b. If not broadcast, remove the pairwise specified by BSSID
-		for (i = 0; i < SHARE_KEY_NUM; i++)
-		{
-			if (MAC_ADDR_EQUAL(pAd->SharedKey[BSS0][i].BssId, pKey->BSSID))
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("RTMPWPARemoveKeyProc(KeyIdx=%d)\n", i));
-				pAd->SharedKey[BSS0][i].KeyLen = 0;
-				pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_NONE;
-				AsicRemoveSharedKeyEntry(pAd, BSS0, (UCHAR)i);
-				Status = NDIS_STATUS_SUCCESS;
-				break;
-			}
-		}
-	}
-	// 3. Group Key
-	else
-	{
-		// a. If BSSID is broadcast, remove all group keys indexed
-		// b. If BSSID matched, delete the group key indexed.
-		DBGPRINT(RT_DEBUG_TRACE,("RTMPWPARemoveKeyProc(KeyIdx=%ld)\n", KeyIdx));
-		pAd->SharedKey[BSS0][KeyIdx].KeyLen = 0;
-		pAd->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_NONE;
-		AsicRemoveSharedKeyEntry(pAd, BSS0, (UCHAR)KeyIdx);
-		Status = NDIS_STATUS_SUCCESS;
-	}
-
-	return (Status);
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-#ifdef CONFIG_STA_SUPPORT
-/*
-	========================================================================
-
-	Routine Description:
-		Remove All WPA Keys
-
-	Arguments:
-		pAd 					Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPWPARemoveAllKeys(
-	IN	PRTMP_ADAPTER	pAd)
-{
-
-	UCHAR 	i;
-
-	DBGPRINT(RT_DEBUG_TRACE,("RTMPWPARemoveAllKeys(AuthMode=%d, WepStatus=%d)\n", pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus));
-
-	// For WEP/CKIP, there is no need to remove it, since WinXP won't set it again after
-	// Link up. And it will be replaced if user changed it.
-	if (pAd->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-		return;
-
-	// For WPA-None, there is no need to remove it, since WinXP won't set it again after
-	// Link up. And it will be replaced if user changed it.
-	if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-		return;
-
-	// set BSSID wcid entry of the Pair-wise Key table as no-security mode
-	AsicRemovePairwiseKeyEntry(pAd, BSS0, BSSID_WCID);
-
-	// set all shared key mode as no-security.
-	for (i = 0; i < SHARE_KEY_NUM; i++)
-    {
-		DBGPRINT(RT_DEBUG_TRACE,("remove %s key #%d\n", CipherName[pAd->SharedKey[BSS0][i].CipherAlg], i));
-		NdisZeroMemory(&pAd->SharedKey[BSS0][i], sizeof(CIPHER_KEY));
-
-		AsicRemoveSharedKeyEntry(pAd, BSS0, i);
-	}
-
-}
-#endif // CONFIG_STA_SUPPORT //
-
-/*
-	========================================================================
-	Routine Description:
-		Change NIC PHY mode. Re-association may be necessary. possible settings
-		include - PHY_11B, PHY_11BG_MIXED, PHY_11A, and PHY_11ABG_MIXED
-
-	Arguments:
-		pAd - Pointer to our adapter
-		phymode  -
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-VOID	RTMPSetPhyMode(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	ULONG phymode)
-{
-	INT i;
-	// the selected phymode must be supported by the RF IC encoded in E2PROM
-
-	pAd->CommonCfg.PhyMode = (UCHAR)phymode;
-
-	DBGPRINT(RT_DEBUG_TRACE,("RTMPSetPhyMode : PhyMode=%d, channel=%d \n", pAd->CommonCfg.PhyMode, pAd->CommonCfg.Channel));
-#ifdef EXT_BUILD_CHANNEL_LIST
-	BuildChannelListEx(pAd);
-#else
-	BuildChannelList(pAd);
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-	// sanity check user setting
-	for (i = 0; i < pAd->ChannelListNum; i++)
-	{
-		if (pAd->CommonCfg.Channel == pAd->ChannelList[i].Channel)
-			break;
-	}
-
-	if (i == pAd->ChannelListNum)
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			pAd->CommonCfg.Channel = FirstChannel(pAd);
-#endif // CONFIG_STA_SUPPORT //
-		DBGPRINT(RT_DEBUG_ERROR, ("RTMPSetPhyMode: channel is out of range, use first channel=%d \n", pAd->CommonCfg.Channel));
-	}
-
-	NdisZeroMemory(pAd->CommonCfg.SupRate, MAX_LEN_OF_SUPPORTED_RATES);
-	NdisZeroMemory(pAd->CommonCfg.ExtRate, MAX_LEN_OF_SUPPORTED_RATES);
-	NdisZeroMemory(pAd->CommonCfg.DesireRate, MAX_LEN_OF_SUPPORTED_RATES);
-	switch (phymode) {
-		case PHY_11B:
-			pAd->CommonCfg.SupRate[0]  = 0x82;	  // 1 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[1]  = 0x84;	  // 2 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[2]  = 0x8B;	  // 5.5 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[3]  = 0x96;	  // 11 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRateLen  = 4;
-			pAd->CommonCfg.ExtRateLen  = 0;
-			pAd->CommonCfg.DesireRate[0]  = 2;	   // 1 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[1]  = 4;	   // 2 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[2]  = 11;    // 5.5 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[3]  = 22;    // 11 mbps, in units of 0.5 Mbps
-			//pAd->CommonCfg.HTPhyMode.field.MODE = MODE_CCK; // This MODE is only FYI. not use
-			break;
-
-		case PHY_11G:
-		case PHY_11BG_MIXED:
-		case PHY_11ABG_MIXED:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11N_2_4G:
-		case PHY_11ABGN_MIXED:
-		case PHY_11BGN_MIXED:
-		case PHY_11GN_MIXED:
-#endif // DOT11_N_SUPPORT //
-			pAd->CommonCfg.SupRate[0]  = 0x82;	  // 1 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[1]  = 0x84;	  // 2 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[2]  = 0x8B;	  // 5.5 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[3]  = 0x96;	  // 11 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[4]  = 0x12;	  // 9 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[5]  = 0x24;	  // 18 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[6]  = 0x48;	  // 36 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[7]  = 0x6c;	  // 54 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRateLen  = 8;
-			pAd->CommonCfg.ExtRate[0]  = 0x0C;	  // 6 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.ExtRate[1]  = 0x18;	  // 12 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.ExtRate[2]  = 0x30;	  // 24 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.ExtRate[3]  = 0x60;	  // 48 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.ExtRateLen  = 4;
-			pAd->CommonCfg.DesireRate[0]  = 2;	   // 1 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[1]  = 4;	   // 2 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[2]  = 11;    // 5.5 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[3]  = 22;    // 11 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[4]  = 12;    // 6 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[5]  = 18;    // 9 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[6]  = 24;    // 12 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[7]  = 36;    // 18 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[8]  = 48;    // 24 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[9]  = 72;    // 36 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[10] = 96;    // 48 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[11] = 108;   // 54 mbps, in units of 0.5 Mbps
-			break;
-
-		case PHY_11A:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11AN_MIXED:
-		case PHY_11AGN_MIXED:
-		case PHY_11N_5G:
-#endif // DOT11_N_SUPPORT //
-			pAd->CommonCfg.SupRate[0]  = 0x8C;	  // 6 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[1]  = 0x12;	  // 9 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[2]  = 0x98;	  // 12 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[3]  = 0x24;	  // 18 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[4]  = 0xb0;	  // 24 mbps, in units of 0.5 Mbps, basic rate
-			pAd->CommonCfg.SupRate[5]  = 0x48;	  // 36 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[6]  = 0x60;	  // 48 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRate[7]  = 0x6c;	  // 54 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.SupRateLen  = 8;
-			pAd->CommonCfg.ExtRateLen  = 0;
-			pAd->CommonCfg.DesireRate[0]  = 12;    // 6 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[1]  = 18;    // 9 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[2]  = 24;    // 12 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[3]  = 36;    // 18 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[4]  = 48;    // 24 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[5]  = 72;    // 36 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[6]  = 96;    // 48 mbps, in units of 0.5 Mbps
-			pAd->CommonCfg.DesireRate[7]  = 108;   // 54 mbps, in units of 0.5 Mbps
-			//pAd->CommonCfg.HTPhyMode.field.MODE = MODE_OFDM; // This MODE is only FYI. not use
-			break;
-
-		default:
-			break;
-	}
-
-
-	pAd->CommonCfg.BandState = UNKNOWN_BAND;
-}
-
-
-#ifdef DOT11_N_SUPPORT
-/*
-	========================================================================
-	Routine Description:
-		Caller ensures we has 802.11n support.
-		Calls at setting HT from AP/STASetinformation
-
-	Arguments:
-		pAd - Pointer to our adapter
-		phymode  -
-
-	========================================================================
-*/
-VOID	RTMPSetHT(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	OID_SET_HT_PHYMODE *pHTPhyMode)
-{
-	//ULONG	*pmcs;
-	UINT32	Value = 0;
-	UCHAR	BBPValue = 0;
-	UCHAR	BBP3Value = 0;
-	UCHAR	RxStream = pAd->CommonCfg.RxStream;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSetHT : HT_mode(%d), ExtOffset(%d), MCS(%d), BW(%d), STBC(%d), SHORTGI(%d)\n",
-										pHTPhyMode->HtMode, pHTPhyMode->ExtOffset,
-										pHTPhyMode->MCS, pHTPhyMode->BW,
-										pHTPhyMode->STBC, pHTPhyMode->SHORTGI));
-
-	// Don't zero supportedHyPhy structure.
-	RTMPZeroMemory(&pAd->CommonCfg.HtCapability, sizeof(pAd->CommonCfg.HtCapability));
-	RTMPZeroMemory(&pAd->CommonCfg.AddHTInfo, sizeof(pAd->CommonCfg.AddHTInfo));
-	RTMPZeroMemory(&pAd->CommonCfg.NewExtChanOffset, sizeof(pAd->CommonCfg.NewExtChanOffset));
-	RTMPZeroMemory(&pAd->CommonCfg.DesiredHtPhy, sizeof(pAd->CommonCfg.DesiredHtPhy));
-
-   	if (pAd->CommonCfg.bRdg)
-	{
-		pAd->CommonCfg.HtCapability.ExtHtCapInfo.PlusHTC = 1;
-		pAd->CommonCfg.HtCapability.ExtHtCapInfo.RDGSupport = 1;
-	}
-	else
-	{
-		pAd->CommonCfg.HtCapability.ExtHtCapInfo.PlusHTC = 0;
-		pAd->CommonCfg.HtCapability.ExtHtCapInfo.RDGSupport = 0;
-	}
-
-	pAd->CommonCfg.HtCapability.HtCapParm.MaxRAmpduFactor = 3;
-	pAd->CommonCfg.DesiredHtPhy.MaxRAmpduFactor = 3;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSetHT : RxBAWinLimit = %d\n", pAd->CommonCfg.BACapability.field.RxBAWinLimit));
-
-	// Mimo power save, A-MSDU size,
-	pAd->CommonCfg.DesiredHtPhy.AmsduEnable = (USHORT)pAd->CommonCfg.BACapability.field.AmsduEnable;
-	pAd->CommonCfg.DesiredHtPhy.AmsduSize = (UCHAR)pAd->CommonCfg.BACapability.field.AmsduSize;
-	pAd->CommonCfg.DesiredHtPhy.MimoPs = (UCHAR)pAd->CommonCfg.BACapability.field.MMPSmode;
-	pAd->CommonCfg.DesiredHtPhy.MpduDensity = (UCHAR)pAd->CommonCfg.BACapability.field.MpduDensity;
-
-	pAd->CommonCfg.HtCapability.HtCapInfo.AMsduSize = (USHORT)pAd->CommonCfg.BACapability.field.AmsduSize;
-	pAd->CommonCfg.HtCapability.HtCapInfo.MimoPs = (USHORT)pAd->CommonCfg.BACapability.field.MMPSmode;
-	pAd->CommonCfg.HtCapability.HtCapParm.MpduDensity = (UCHAR)pAd->CommonCfg.BACapability.field.MpduDensity;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSetHT : AMsduSize = %d, MimoPs = %d, MpduDensity = %d, MaxRAmpduFactor = %d\n",
-													pAd->CommonCfg.DesiredHtPhy.AmsduSize,
-													pAd->CommonCfg.DesiredHtPhy.MimoPs,
-													pAd->CommonCfg.DesiredHtPhy.MpduDensity,
-													pAd->CommonCfg.DesiredHtPhy.MaxRAmpduFactor));
-
-	if(pHTPhyMode->HtMode == HTMODE_GF)
-	{
-		pAd->CommonCfg.HtCapability.HtCapInfo.GF = 1;
-		pAd->CommonCfg.DesiredHtPhy.GF = 1;
-	}
-	else
-		pAd->CommonCfg.DesiredHtPhy.GF = 0;
-
-	// Decide Rx MCSSet
-	switch (RxStream)
-	{
-		case 1:
-			pAd->CommonCfg.HtCapability.MCSSet[0] =  0xff;
-			pAd->CommonCfg.HtCapability.MCSSet[1] =  0x00;
-			break;
-
-		case 2:
-			pAd->CommonCfg.HtCapability.MCSSet[0] =  0xff;
-			pAd->CommonCfg.HtCapability.MCSSet[1] =  0xff;
-			break;
-
-		case 3: // 3*3
-			pAd->CommonCfg.HtCapability.MCSSet[0] =  0xff;
-			pAd->CommonCfg.HtCapability.MCSSet[1] =  0xff;
-			pAd->CommonCfg.HtCapability.MCSSet[2] =  0xff;
-			break;
-	}
-
-	if (pAd->CommonCfg.bForty_Mhz_Intolerant && (pAd->CommonCfg.Channel <= 14) && (pHTPhyMode->BW == BW_40) )
-	{
-		pHTPhyMode->BW = BW_20;
-		pAd->CommonCfg.HtCapability.HtCapInfo.Forty_Mhz_Intolerant = 1;
-	}
-
-	if(pHTPhyMode->BW == BW_40)
-	{
-		pAd->CommonCfg.HtCapability.MCSSet[4] = 0x1; // MCS 32
-		pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth = 1;
-		if (pAd->CommonCfg.Channel <= 14)
-			pAd->CommonCfg.HtCapability.HtCapInfo.CCKmodein40 = 1;
-
-		pAd->CommonCfg.DesiredHtPhy.ChannelWidth = 1;
-		pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth = 1;
-		pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset = (pHTPhyMode->ExtOffset == EXTCHA_BELOW)? (EXTCHA_BELOW): EXTCHA_ABOVE;
-		// Set Regsiter for extension channel position.
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBP3Value);
-		if ((pHTPhyMode->ExtOffset == EXTCHA_BELOW))
-		{
-			Value |= 0x1;
-			BBP3Value |= (0x20);
-			RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-		}
-		else if ((pHTPhyMode->ExtOffset == EXTCHA_ABOVE))
-		{
-			Value &= 0xfe;
-			BBP3Value &= (~0x20);
-			RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-		}
-
-		// Turn on BBP 40MHz mode now only as AP .
-		// Sta can turn on BBP 40MHz after connection with 40MHz AP. Sta only broadcast 40MHz capability before connection.
-		if ((pAd->OpMode == OPMODE_AP) || INFRA_ON(pAd) || ADHOC_ON(pAd)
-			)
-		{
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue &= (~0x18);
-			BBPValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBP3Value);
-			pAd->CommonCfg.BBPCurrentBW = BW_40;
-		}
-	}
-	else
-	{
-		pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth = 0;
-		pAd->CommonCfg.DesiredHtPhy.ChannelWidth = 0;
-		pAd->CommonCfg.AddHTInfo.AddHtInfo.RecomWidth = 0;
-		pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset = EXTCHA_NONE;
-		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
-		// Turn on BBP 20MHz mode by request here.
-		{
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue &= (~0x18);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-			pAd->CommonCfg.BBPCurrentBW = BW_20;
-		}
-	}
-
-	if(pHTPhyMode->STBC == STBC_USE)
-	{
-		pAd->CommonCfg.HtCapability.HtCapInfo.TxSTBC = 1;
-		pAd->CommonCfg.DesiredHtPhy.TxSTBC = 1;
-		pAd->CommonCfg.HtCapability.HtCapInfo.RxSTBC = 1;
-		pAd->CommonCfg.DesiredHtPhy.RxSTBC = 1;
-	}
-	else
-	{
-		pAd->CommonCfg.DesiredHtPhy.TxSTBC = 0;
-		pAd->CommonCfg.DesiredHtPhy.RxSTBC = 0;
-	}
-
-	if(pHTPhyMode->SHORTGI == GI_400)
-	{
-		pAd->CommonCfg.HtCapability.HtCapInfo.ShortGIfor20 = 1;
-		pAd->CommonCfg.HtCapability.HtCapInfo.ShortGIfor40 = 1;
-		pAd->CommonCfg.DesiredHtPhy.ShortGIfor20 = 1;
-		pAd->CommonCfg.DesiredHtPhy.ShortGIfor40 = 1;
-	}
-	else
-	{
-		pAd->CommonCfg.HtCapability.HtCapInfo.ShortGIfor20 = 0;
-		pAd->CommonCfg.HtCapability.HtCapInfo.ShortGIfor40 = 0;
-		pAd->CommonCfg.DesiredHtPhy.ShortGIfor20 = 0;
-		pAd->CommonCfg.DesiredHtPhy.ShortGIfor40 = 0;
-	}
-
-	// We support link adaptation for unsolicit MCS feedback, set to 2.
-	pAd->CommonCfg.HtCapability.ExtHtCapInfo.MCSFeedback = MCSFBK_NONE; //MCSFBK_UNSOLICIT;
-	pAd->CommonCfg.AddHTInfo.ControlChan = pAd->CommonCfg.Channel;
-	// 1, the extension channel above the control channel.
-
-	// EDCA parameters used for AP's own transmission
-	if (pAd->CommonCfg.APEdcaParm.bValid == FALSE)
-	{
-		pAd->CommonCfg.APEdcaParm.bValid = TRUE;
-		pAd->CommonCfg.APEdcaParm.Aifsn[0] = 3;
-		pAd->CommonCfg.APEdcaParm.Aifsn[1] = 7;
-		pAd->CommonCfg.APEdcaParm.Aifsn[2] = 1;
-		pAd->CommonCfg.APEdcaParm.Aifsn[3] = 1;
-
-		pAd->CommonCfg.APEdcaParm.Cwmin[0] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmin[1] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmin[2] = 3;
-		pAd->CommonCfg.APEdcaParm.Cwmin[3] = 2;
-
-		pAd->CommonCfg.APEdcaParm.Cwmax[0] = 6;
-		pAd->CommonCfg.APEdcaParm.Cwmax[1] = 10;
-		pAd->CommonCfg.APEdcaParm.Cwmax[2] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmax[3] = 3;
-
-		pAd->CommonCfg.APEdcaParm.Txop[0]  = 0;
-		pAd->CommonCfg.APEdcaParm.Txop[1]  = 0;
-		pAd->CommonCfg.APEdcaParm.Txop[2]  = 94;
-		pAd->CommonCfg.APEdcaParm.Txop[3]  = 47;
-	}
-	AsicSetEdcaParm(pAd, &pAd->CommonCfg.APEdcaParm);
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		RTMPSetIndividualHT(pAd, 0);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Caller ensures we has 802.11n support.
-		Calls at setting HT from AP/STASetinformation
-
-	Arguments:
-		pAd - Pointer to our adapter
-		phymode  -
-
-	========================================================================
-*/
-VOID	RTMPSetIndividualHT(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	UCHAR				apidx)
-{
-	PRT_HT_PHY_INFO		pDesired_ht_phy = NULL;
-	UCHAR	TxStream = pAd->CommonCfg.TxStream;
-	UCHAR	DesiredMcs	= MCS_AUTO;
-
-	do
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			pDesired_ht_phy = &pAd->StaCfg.DesiredHtPhyInfo;
-			DesiredMcs = pAd->StaCfg.DesiredTransmitSetting.field.MCS;
-			//pAd->StaCfg.bAutoTxRateSwitch = (DesiredMcs == MCS_AUTO) ? TRUE : FALSE;
-				break;
-		}
-#endif // CONFIG_STA_SUPPORT //
-	} while (FALSE);
-
-	if (pDesired_ht_phy == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RTMPSetIndividualHT: invalid apidx(%d)\n", apidx));
-		return;
-	}
-	RTMPZeroMemory(pDesired_ht_phy, sizeof(RT_HT_PHY_INFO));
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSetIndividualHT : Desired MCS = %d\n", DesiredMcs));
-	// Check the validity of MCS
-	if ((TxStream == 1) && ((DesiredMcs >= MCS_8) && (DesiredMcs <= MCS_15)))
-	{
-		DBGPRINT(RT_DEBUG_WARN, ("RTMPSetIndividualHT: MCS(%d) is invalid in 1S, reset it as MCS_7\n", DesiredMcs));
-		DesiredMcs = MCS_7;
-	}
-
-	if ((pAd->CommonCfg.DesiredHtPhy.ChannelWidth == BW_20) && (DesiredMcs == MCS_32))
-	{
-		DBGPRINT(RT_DEBUG_WARN, ("RTMPSetIndividualHT: MCS_32 is only supported in 40-MHz, reset it as MCS_0\n"));
-		DesiredMcs = MCS_0;
-	}
-
-	pDesired_ht_phy->bHtEnable = TRUE;
-
-	// Decide desired Tx MCS
-	switch (TxStream)
-	{
-		case 1:
-			if (DesiredMcs == MCS_AUTO)
-			{
-				pDesired_ht_phy->MCSSet[0]= 0xff;
-				pDesired_ht_phy->MCSSet[1]= 0x00;
-			}
-			else if (DesiredMcs <= MCS_7)
-			{
-				pDesired_ht_phy->MCSSet[0]= 1<<DesiredMcs;
-				pDesired_ht_phy->MCSSet[1]= 0x00;
-			}
-			break;
-
-		case 2:
-			if (DesiredMcs == MCS_AUTO)
-			{
-				pDesired_ht_phy->MCSSet[0]= 0xff;
-				pDesired_ht_phy->MCSSet[1]= 0xff;
-			}
-			else if (DesiredMcs <= MCS_15)
-			{
-				ULONG mode;
-
-				mode = DesiredMcs / 8;
-				if (mode < 2)
-					pDesired_ht_phy->MCSSet[mode] = (1 << (DesiredMcs - mode * 8));
-			}
-			break;
-
-		case 3: // 3*3
-			if (DesiredMcs == MCS_AUTO)
-			{
-				/* MCS0 ~ MCS23, 3 bytes */
-				pDesired_ht_phy->MCSSet[0]= 0xff;
-				pDesired_ht_phy->MCSSet[1]= 0xff;
-				pDesired_ht_phy->MCSSet[2]= 0xff;
-			}
-			else if (DesiredMcs <= MCS_23)
-			{
-				ULONG mode;
-
-				mode = DesiredMcs / 8;
-				if (mode < 3)
-					pDesired_ht_phy->MCSSet[mode] = (1 << (DesiredMcs - mode * 8));
-			}
-			break;
-	}
-
-	if(pAd->CommonCfg.DesiredHtPhy.ChannelWidth == BW_40)
-	{
-		if (DesiredMcs == MCS_AUTO || DesiredMcs == MCS_32)
-			pDesired_ht_phy->MCSSet[4] = 0x1;
-	}
-
-	// update HT Rate setting
-    if (pAd->OpMode == OPMODE_STA)
-        MlmeUpdateHtTxRates(pAd, BSS0);
-    else
-	    MlmeUpdateHtTxRates(pAd, apidx);
-}
-
-
-/*
-	========================================================================
-	Routine Description:
-		Update HT IE from our capability.
-
-	Arguments:
-		Send all HT IE in beacon/probe rsp/assoc rsp/action frame.
-
-
-	========================================================================
-*/
-VOID	RTMPUpdateHTIE(
-	IN	RT_HT_CAPABILITY	*pRtHt,
-	IN		UCHAR				*pMcsSet,
-	OUT		HT_CAPABILITY_IE *pHtCapability,
-	OUT		ADD_HT_INFO_IE		*pAddHtInfo)
-{
-	RTMPZeroMemory(pHtCapability, sizeof(HT_CAPABILITY_IE));
-	RTMPZeroMemory(pAddHtInfo, sizeof(ADD_HT_INFO_IE));
-
-		pHtCapability->HtCapInfo.ChannelWidth = pRtHt->ChannelWidth;
-		pHtCapability->HtCapInfo.MimoPs = pRtHt->MimoPs;
-		pHtCapability->HtCapInfo.GF = pRtHt->GF;
-		pHtCapability->HtCapInfo.ShortGIfor20 = pRtHt->ShortGIfor20;
-		pHtCapability->HtCapInfo.ShortGIfor40 = pRtHt->ShortGIfor40;
-		pHtCapability->HtCapInfo.TxSTBC = pRtHt->TxSTBC;
-		pHtCapability->HtCapInfo.RxSTBC = pRtHt->RxSTBC;
-		pHtCapability->HtCapInfo.AMsduSize = pRtHt->AmsduSize;
-		pHtCapability->HtCapParm.MaxRAmpduFactor = pRtHt->MaxRAmpduFactor;
-		pHtCapability->HtCapParm.MpduDensity = pRtHt->MpduDensity;
-
-		pAddHtInfo->AddHtInfo.ExtChanOffset = pRtHt->ExtChanOffset ;
-		pAddHtInfo->AddHtInfo.RecomWidth = pRtHt->RecomWidth;
-		pAddHtInfo->AddHtInfo2.OperaionMode = pRtHt->OperaionMode;
-		pAddHtInfo->AddHtInfo2.NonGfPresent = pRtHt->NonGfPresent;
-		RTMPMoveMemory(pAddHtInfo->MCSSet, /*pRtHt->MCSSet*/pMcsSet, 4); // rt2860 only support MCS max=32, no need to copy all 16 uchar.
-
-        DBGPRINT(RT_DEBUG_TRACE,("RTMPUpdateHTIE <== \n"));
-}
-#endif // DOT11_N_SUPPORT //
-
-/*
-	========================================================================
-	Description:
-		Add Client security information into ASIC WCID table and IVEIV table.
-    Return:
-	========================================================================
-*/
-VOID	RTMPAddWcidAttributeEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BssIdx,
-	IN 	UCHAR		 	KeyIdx,
-	IN 	UCHAR		 	CipherAlg,
-	IN 	MAC_TABLE_ENTRY *pEntry)
-{
-	UINT32		WCIDAttri = 0;
-	USHORT		offset;
-	UCHAR		IVEIV = 0;
-	USHORT		Wcid = 0;
-
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			if (BssIdx > BSS0)
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("RTMPAddWcidAttributeEntry: The BSS-index(%d) is out of range for Infra link. \n", BssIdx));
-				return;
-			}
-
-			// 1.	In ADHOC mode, the AID is wcid number. And NO mesh link exists.
-			// 2.	In Infra mode, the AID:1 MUST be wcid of infra STA.
-			//					   the AID:2~ assign to mesh link entry.
-			if (pEntry && ADHOC_ON(pAd))
-				Wcid = pEntry->Aid;
-			else if (pEntry && INFRA_ON(pAd))
-			{
-#ifdef QOS_DLS_SUPPORT
-				if (pEntry->ValidAsDls == TRUE)
-					Wcid = pEntry->Aid;
-				else
-#endif // QOS_DLS_SUPPORT //
-				Wcid = BSSID_WCID;
-			}
-			else
-				Wcid = MCAST_WCID;
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	// Update WCID attribute table
-	offset = MAC_WCID_ATTRIBUTE_BASE + (Wcid * HW_WCID_ATTRI_SIZE);
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pEntry && pEntry->ValidAsMesh)
-			WCIDAttri = (CipherAlg<<1) | PAIRWISEKEYTABLE;
-#ifdef QOS_DLS_SUPPORT
-		else if ((pEntry) && (pEntry->ValidAsDls) &&
-					((CipherAlg == CIPHER_TKIP) ||
-				 	(CipherAlg == CIPHER_TKIP_NO_MIC) ||
-					(CipherAlg == CIPHER_AES) ||
-				 	(CipherAlg == CIPHER_NONE)))
-			WCIDAttri = (CipherAlg<<1) | PAIRWISEKEYTABLE;
-#endif // QOS_DLS_SUPPORT //
-		else
-			WCIDAttri = (CipherAlg<<1) | SHAREDKEYTABLE;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	RTMP_IO_WRITE32(pAd, offset, WCIDAttri);
-
-
-	// Update IV/EIV table
-	offset = MAC_IVEIV_TABLE_BASE + (Wcid * HW_IVEIV_ENTRY_SIZE);
-
-	// WPA mode
-	if ((CipherAlg == CIPHER_TKIP) || (CipherAlg == CIPHER_TKIP_NO_MIC) || (CipherAlg == CIPHER_AES))
-	{
-		// Eiv bit on. keyid always is 0 for pairwise key
-		IVEIV = (KeyIdx <<6) | 0x20;
-	}
-	else
-	{
-		// WEP KeyIdx is default tx key.
-		IVEIV = (KeyIdx << 6);
-	}
-
-	// For key index and ext IV bit, so only need to update the position(offset+3).
-#ifdef RT2870
-	RTUSBMultiWrite_OneByte(pAd, offset+3, &IVEIV);
-#endif // RT2870 //
-
-	DBGPRINT(RT_DEBUG_TRACE,("RTMPAddWcidAttributeEntry: WCID #%d, KeyIndex #%d, Alg=%s\n",Wcid, KeyIdx, CipherName[CipherAlg]));
-	DBGPRINT(RT_DEBUG_TRACE,("	WCIDAttri = 0x%x \n",  WCIDAttri));
-
-}
-
-/*
-    ==========================================================================
-    Description:
-        Parse encryption type
-Arguments:
-    pAdapter                    Pointer to our adapter
-    wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-    ==========================================================================
-*/
-CHAR *GetEncryptType(CHAR enc)
-{
-    if(enc == Ndis802_11WEPDisabled)
-        return "NONE";
-    if(enc == Ndis802_11WEPEnabled)
-    	return "WEP";
-    if(enc == Ndis802_11Encryption2Enabled)
-    	return "TKIP";
-    if(enc == Ndis802_11Encryption3Enabled)
-    	return "AES";
-	if(enc == Ndis802_11Encryption4Enabled)
-    	return "TKIPAES";
-    else
-    	return "UNKNOW";
-}
-
-CHAR *GetAuthMode(CHAR auth)
-{
-    if(auth == Ndis802_11AuthModeOpen)
-    	return "OPEN";
-    if(auth == Ndis802_11AuthModeShared)
-    	return "SHARED";
-	if(auth == Ndis802_11AuthModeAutoSwitch)
-    	return "AUTOWEP";
-    if(auth == Ndis802_11AuthModeWPA)
-    	return "WPA";
-    if(auth == Ndis802_11AuthModeWPAPSK)
-    	return "WPAPSK";
-    if(auth == Ndis802_11AuthModeWPANone)
-    	return "WPANONE";
-    if(auth == Ndis802_11AuthModeWPA2)
-    	return "WPA2";
-    if(auth == Ndis802_11AuthModeWPA2PSK)
-    	return "WPA2PSK";
-	if(auth == Ndis802_11AuthModeWPA1WPA2)
-    	return "WPA1WPA2";
-	if(auth == Ndis802_11AuthModeWPA1PSKWPA2PSK)
-    	return "WPA1PSKWPA2PSK";
-
-    	return "UNKNOW";
-}
-
-#if 1 //#ifndef UCOS
-/*
-    ==========================================================================
-    Description:
-        Get site survey results
-	Arguments:
-	    pAdapter                    Pointer to our adapter
-	    wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-        		1.) UI needs to wait 4 seconds after issue a site survey command
-        		2.) iwpriv ra0 get_site_survey
-        		3.) UI needs to prepare at least 4096bytes to get the results
-    ==========================================================================
-*/
-#define	LINE_LEN	(4+33+20+8+10+9+7+3)	// Channel+SSID+Bssid+WepStatus+AuthMode+Signal+WiressMode+NetworkType
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-VOID RTMPIoctlGetSiteSurvey(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	CHAR		*msg;
-	INT 		i=0;
-	INT			WaitCnt;
-	INT 		Status=0;
-	CHAR		Ssid[MAX_LEN_OF_SSID +1];
-    INT         Rssi = 0, max_len = LINE_LEN;
-	UINT        Rssi_Quality = 0;
-	NDIS_802_11_NETWORK_TYPE    wireless_mode;
-
-	os_alloc_mem(NULL, (PUCHAR *)&msg, sizeof(CHAR)*((MAX_LEN_OF_BSS_TABLE)*max_len));
-
-	if (msg == NULL)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("RTMPIoctlGetSiteSurvey - msg memory alloc fail.\n"));
-		return;
-	}
-
-	memset(msg, 0 ,(MAX_LEN_OF_BSS_TABLE)*max_len );
-	memset(Ssid, 0 ,(MAX_LEN_OF_SSID +1));
-	sprintf(msg,"%s","\n");
-	sprintf(msg+strlen(msg),"%-4s%-33s%-20s%-8s%-10s%-9s%-7s%-3s\n",
-	    "Ch", "SSID", "BSSID", "Enc", "Auth", "Siganl(%)", "W-Mode", " NT");
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-	WaitCnt = 0;
-#ifdef CONFIG_STA_SUPPORT
-	pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-	while ((ScanRunning(pAdapter) == TRUE) && (WaitCnt++ < 200))
-		OS_WAIT(500);
-#endif // CONFIG_STA_SUPPORT //
-
-	for(i=0; i<pAdapter->ScanTab.BssNr ;i++)
-	{
-		if( pAdapter->ScanTab.BssEntry[i].Channel==0)
-			break;
-
-		if((strlen(msg)+max_len ) >= IW_SCAN_MAX_DATA)
-			break;
-
-		//Channel
-		sprintf(msg+strlen(msg),"%-4d", pAdapter->ScanTab.BssEntry[i].Channel);
-		//SSID
-		memcpy(Ssid, pAdapter->ScanTab.BssEntry[i].Ssid, pAdapter->ScanTab.BssEntry[i].SsidLen);
-		Ssid[pAdapter->ScanTab.BssEntry[i].SsidLen] = '\0';
-		sprintf(msg+strlen(msg),"%-33s", Ssid);
-		//BSSID
-		sprintf(msg+strlen(msg),"%02x:%02x:%02x:%02x:%02x:%02x   ",
-			pAdapter->ScanTab.BssEntry[i].Bssid[0],
-			pAdapter->ScanTab.BssEntry[i].Bssid[1],
-			pAdapter->ScanTab.BssEntry[i].Bssid[2],
-			pAdapter->ScanTab.BssEntry[i].Bssid[3],
-			pAdapter->ScanTab.BssEntry[i].Bssid[4],
-			pAdapter->ScanTab.BssEntry[i].Bssid[5]);
-		//Encryption Type
-		sprintf(msg+strlen(msg),"%-8s",GetEncryptType(pAdapter->ScanTab.BssEntry[i].WepStatus));
-		//Authentication Mode
-		if (pAdapter->ScanTab.BssEntry[i].WepStatus == Ndis802_11WEPEnabled)
-			sprintf(msg+strlen(msg),"%-10s", "UNKNOW");
-		else
-			sprintf(msg+strlen(msg),"%-10s",GetAuthMode(pAdapter->ScanTab.BssEntry[i].AuthMode));
-		// Rssi
-		Rssi = (INT)pAdapter->ScanTab.BssEntry[i].Rssi;
-		if (Rssi >= -50)
-			Rssi_Quality = 100;
-		else if (Rssi >= -80)    // between -50 ~ -80dbm
-			Rssi_Quality = (UINT)(24 + ((Rssi + 80) * 26)/10);
-		else if (Rssi >= -90)   // between -80 ~ -90dbm
-			Rssi_Quality = (UINT)(((Rssi + 90) * 26)/10);
-		else    // < -84 dbm
-			Rssi_Quality = 0;
-		sprintf(msg+strlen(msg),"%-9d", Rssi_Quality);
-		// Wireless Mode
-		wireless_mode = NetworkTypeInUseSanity(&pAdapter->ScanTab.BssEntry[i]);
-		if (wireless_mode == Ndis802_11FH ||
-			wireless_mode == Ndis802_11DS)
-			sprintf(msg+strlen(msg),"%-7s", "11b");
-		else if (wireless_mode == Ndis802_11OFDM5)
-			sprintf(msg+strlen(msg),"%-7s", "11a");
-		else if (wireless_mode == Ndis802_11OFDM5_N)
-			sprintf(msg+strlen(msg),"%-7s", "11a/n");
-		else if (wireless_mode == Ndis802_11OFDM24)
-			sprintf(msg+strlen(msg),"%-7s", "11b/g");
-		else if (wireless_mode == Ndis802_11OFDM24_N)
-			sprintf(msg+strlen(msg),"%-7s", "11b/g/n");
-		else
-			sprintf(msg+strlen(msg),"%-7s", "unknow");
-		//Network Type
-		if (pAdapter->ScanTab.BssEntry[i].BssType == BSS_ADHOC)
-			sprintf(msg+strlen(msg),"%-3s", " Ad");
-		else
-			sprintf(msg+strlen(msg),"%-3s", " In");
-
-        sprintf(msg+strlen(msg),"\n");
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-#endif // CONFIG_STA_SUPPORT //
-	wrq->u.data.length = strlen(msg);
-	Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPIoctlGetSiteSurvey - wrq->u.data.length = %d\n", wrq->u.data.length));
-	os_free_mem(NULL, (PUCHAR)msg);
-}
-
-
-#define	MAC_LINE_LEN	(14+4+4+10+10+10+6+6)	// Addr+aid+psm+datatime+rxbyte+txbyte+current tx rate+last tx rate
-VOID RTMPIoctlGetMacTable(
-	IN PRTMP_ADAPTER pAd,
-	IN struct iwreq *wrq)
-{
-	INT i;
-	RT_802_11_MAC_TABLE MacTab;
-	char *msg;
-
-	MacTab.Num = 0;
-	for (i=0; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		if (pAd->MacTab.Content[i].ValidAsCLI && (pAd->MacTab.Content[i].Sst == SST_ASSOC))
-		{
-			COPY_MAC_ADDR(MacTab.Entry[MacTab.Num].Addr, &pAd->MacTab.Content[i].Addr);
-			MacTab.Entry[MacTab.Num].Aid = (UCHAR)pAd->MacTab.Content[i].Aid;
-			MacTab.Entry[MacTab.Num].Psm = pAd->MacTab.Content[i].PsMode;
-#ifdef DOT11_N_SUPPORT
-			MacTab.Entry[MacTab.Num].MimoPs = pAd->MacTab.Content[i].MmpsMode;
-#endif // DOT11_N_SUPPORT //
-
-			// Fill in RSSI per entry
-			MacTab.Entry[MacTab.Num].AvgRssi0 = pAd->MacTab.Content[i].RssiSample.AvgRssi0;
-			MacTab.Entry[MacTab.Num].AvgRssi1 = pAd->MacTab.Content[i].RssiSample.AvgRssi1;
-			MacTab.Entry[MacTab.Num].AvgRssi2 = pAd->MacTab.Content[i].RssiSample.AvgRssi2;
-
-			// the connected time per entry
-			MacTab.Entry[MacTab.Num].ConnectedTime = pAd->MacTab.Content[i].StaConnectTime;
-			MacTab.Entry[MacTab.Num].TxRate.field.MCS = pAd->MacTab.Content[i].HTPhyMode.field.MCS;
-			MacTab.Entry[MacTab.Num].TxRate.field.BW = pAd->MacTab.Content[i].HTPhyMode.field.BW;
-			MacTab.Entry[MacTab.Num].TxRate.field.ShortGI = pAd->MacTab.Content[i].HTPhyMode.field.ShortGI;
-			MacTab.Entry[MacTab.Num].TxRate.field.STBC = pAd->MacTab.Content[i].HTPhyMode.field.STBC;
-			MacTab.Entry[MacTab.Num].TxRate.field.rsv = pAd->MacTab.Content[i].HTPhyMode.field.rsv;
-			MacTab.Entry[MacTab.Num].TxRate.field.MODE = pAd->MacTab.Content[i].HTPhyMode.field.MODE;
-			MacTab.Entry[MacTab.Num].TxRate.word = pAd->MacTab.Content[i].HTPhyMode.word;
-
-			MacTab.Num += 1;
-		}
-	}
-	wrq->u.data.length = sizeof(RT_802_11_MAC_TABLE);
-	if (copy_to_user(wrq->u.data.pointer, &MacTab, wrq->u.data.length))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s: copy_to_user() fail\n", __FUNCTION__));
-	}
-
-	msg = (CHAR *) kmalloc(sizeof(CHAR)*(MAX_LEN_OF_MAC_TABLE*MAC_LINE_LEN), MEM_ALLOC_FLAG);
-	memset(msg, 0 ,MAX_LEN_OF_MAC_TABLE*MAC_LINE_LEN );
-	sprintf(msg,"%s","\n");
-	sprintf(msg+strlen(msg),"%-14s%-4s%-4s%-10s%-10s%-10s%-6s%-6s\n",
-		"MAC", "AID", "PSM", "LDT", "RxB", "TxB","CTxR", "LTxR");
-
-	for (i=0; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[i];
-		if (pEntry->ValidAsCLI && (pEntry->Sst == SST_ASSOC))
-		{
-			if((strlen(msg)+MAC_LINE_LEN ) >= (MAX_LEN_OF_MAC_TABLE*MAC_LINE_LEN) )
-				break;
-			sprintf(msg+strlen(msg),"%02x%02x%02x%02x%02x%02x  ",
-				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
-				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5]);
-			sprintf(msg+strlen(msg),"%-4d", (int)pEntry->Aid);
-			sprintf(msg+strlen(msg),"%-4d", (int)pEntry->PsMode);
-			sprintf(msg+strlen(msg),"%-10d",0/*pAd->MacTab.Content[i].HSCounter.LastDataPacketTime*/); // ToDo
-			sprintf(msg+strlen(msg),"%-10d",0/*pAd->MacTab.Content[i].HSCounter.TotalRxByteCount*/); // ToDo
-			sprintf(msg+strlen(msg),"%-10d",0/*pAd->MacTab.Content[i].HSCounter.TotalTxByteCount*/); // ToDo
-			sprintf(msg+strlen(msg),"%-6d",RateIdToMbps[pAd->MacTab.Content[i].CurrTxRate]);
-			sprintf(msg+strlen(msg),"%-6d\n",0/*RateIdToMbps[pAd->MacTab.Content[i].LastTxRate]*/); // ToDo
-		}
-	}
-	// for compatible with old API just do the printk to console
-	//wrq->u.data.length = strlen(msg);
-	//if (copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s", msg));
-	}
-
-	kfree(msg);
-}
-#endif // UCOS //
-
-#ifdef DOT11_N_SUPPORT
-INT	Set_BASetup_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    UCHAR mac[6], tid;
-	char *token, sepValue[] = ":", DASH = '-';
-	INT i;
-    MAC_TABLE_ENTRY *pEntry;
-
-/*
-	The BASetup inupt string format should be xx:xx:xx:xx:xx:xx-d,
-		=>The six 2 digit hex-decimal number previous are the Mac address,
-		=>The seventh decimal number is the tid value.
-*/
-	//printk("\n%s\n", arg);
-
-	if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and tid value in decimal format.
-		return FALSE;
-
-	token = strchr(arg, DASH);
-	if ((token != NULL) && (strlen(token)>1))
-	{
-		tid = simple_strtol((token+1), 0, 10);
-		if (tid > 15)
-			return FALSE;
-
-		*token = '\0';
-		for (i = 0, token = rstrtok(arg, &sepValue[0]); token; token = rstrtok(NULL, &sepValue[0]), i++)
-		{
-			if((strlen(token) != 2) || (!isxdigit(*token)) || (!isxdigit(*(token+1))))
-				return FALSE;
-			AtoH(token, (PUCHAR)(&mac[i]), 1);
-		}
-		if(i != 6)
-			return FALSE;
-
-		printk("\n%02x:%02x:%02x:%02x:%02x:%02x-%02x\n", mac[0], mac[1],
-				mac[2], mac[3], mac[4], mac[5], tid);
-
-	    pEntry = MacTableLookup(pAd, mac);
-
-    	if (pEntry) {
-        	printk("\nSetup BA Session: Tid = %d\n", tid);
-	        BAOriSessionSetUp(pAd, pEntry, tid, 0, 100, TRUE);
-    	}
-
-		return TRUE;
-	}
-
-	return FALSE;
-
-}
-
-INT	Set_BADecline_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG bBADecline;
-
-	bBADecline = simple_strtol(arg, 0, 10);
-
-	if (bBADecline == 0)
-	{
-		pAd->CommonCfg.bBADecline = FALSE;
-	}
-	else if (bBADecline == 1)
-	{
-		pAd->CommonCfg.bBADecline = TRUE;
-	}
-	else
-	{
-		return FALSE; //Invalid argument
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_BADecline_Proc::(BADecline=%d)\n", pAd->CommonCfg.bBADecline));
-
-	return TRUE;
-}
-
-INT	Set_BAOriTearDown_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    UCHAR mac[6], tid;
-	char *token, sepValue[] = ":", DASH = '-';
-	INT i;
-    MAC_TABLE_ENTRY *pEntry;
-
-    //printk("\n%s\n", arg);
-/*
-	The BAOriTearDown inupt string format should be xx:xx:xx:xx:xx:xx-d,
-		=>The six 2 digit hex-decimal number previous are the Mac address,
-		=>The seventh decimal number is the tid value.
-*/
-    if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and tid value in decimal format.
-		return FALSE;
-
-	token = strchr(arg, DASH);
-	if ((token != NULL) && (strlen(token)>1))
-	{
-		tid = simple_strtol((token+1), 0, 10);
-		if (tid > NUM_OF_TID)
-			return FALSE;
-
-		*token = '\0';
-		for (i = 0, token = rstrtok(arg, &sepValue[0]); token; token = rstrtok(NULL, &sepValue[0]), i++)
-		{
-			if((strlen(token) != 2) || (!isxdigit(*token)) || (!isxdigit(*(token+1))))
-				return FALSE;
-			AtoH(token, (PUCHAR)(&mac[i]), 1);
-		}
-		if(i != 6)
-			return FALSE;
-
-	    printk("\n%02x:%02x:%02x:%02x:%02x:%02x-%02x", mac[0], mac[1],
-	           mac[2], mac[3], mac[4], mac[5], tid);
-
-	    pEntry = MacTableLookup(pAd, mac);
-
-	    if (pEntry) {
-	        printk("\nTear down Ori BA Session: Tid = %d\n", tid);
-        BAOriSessionTearDown(pAd, pEntry->Aid, tid, FALSE, TRUE);
-	    }
-
-		return TRUE;
-	}
-
-	return FALSE;
-
-}
-
-INT	Set_BARecTearDown_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    UCHAR mac[6], tid;
-	char *token, sepValue[] = ":", DASH = '-';
-	INT i;
-    MAC_TABLE_ENTRY *pEntry;
-
-    //printk("\n%s\n", arg);
-/*
-	The BARecTearDown inupt string format should be xx:xx:xx:xx:xx:xx-d,
-		=>The six 2 digit hex-decimal number previous are the Mac address,
-		=>The seventh decimal number is the tid value.
-*/
-    if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and tid value in decimal format.
-		return FALSE;
-
-	token = strchr(arg, DASH);
-	if ((token != NULL) && (strlen(token)>1))
-	{
-		tid = simple_strtol((token+1), 0, 10);
-		if (tid > NUM_OF_TID)
-			return FALSE;
-
-		*token = '\0';
-		for (i = 0, token = rstrtok(arg, &sepValue[0]); token; token = rstrtok(NULL, &sepValue[0]), i++)
-		{
-			if((strlen(token) != 2) || (!isxdigit(*token)) || (!isxdigit(*(token+1))))
-				return FALSE;
-			AtoH(token, (PUCHAR)(&mac[i]), 1);
-		}
-		if(i != 6)
-			return FALSE;
-
-		printk("\n%02x:%02x:%02x:%02x:%02x:%02x-%02x", mac[0], mac[1],
-		       mac[2], mac[3], mac[4], mac[5], tid);
-
-		pEntry = MacTableLookup(pAd, mac);
-
-		if (pEntry) {
-		    printk("\nTear down Rec BA Session: Tid = %d\n", tid);
-		    BARecSessionTearDown(pAd, pEntry->Aid, tid, FALSE);
-		}
-
-		return TRUE;
-	}
-
-	return FALSE;
-
-}
-
-INT	Set_HtBw_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG HtBw;
-
-	HtBw = simple_strtol(arg, 0, 10);
-	if (HtBw == BW_40)
-		pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_40;
-	else if (HtBw == BW_20)
-		pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-	else
-		return FALSE;  //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtBw_Proc::(HtBw=%d)\n", pAd->CommonCfg.RegTransmitSetting.field.BW));
-
-	return TRUE;
-}
-
-INT	Set_HtMcs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG HtMcs, Mcs_tmp;
-#ifdef CONFIG_STA_SUPPORT
-    BOOLEAN bAutoRate = FALSE;
-#endif // CONFIG_STA_SUPPORT //
-
-	Mcs_tmp = simple_strtol(arg, 0, 10);
-
-	if (Mcs_tmp <= 15 || Mcs_tmp == 32)
-		HtMcs = Mcs_tmp;
-	else
-		HtMcs = MCS_AUTO;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		pAd->StaCfg.DesiredTransmitSetting.field.MCS = HtMcs;
-		pAd->StaCfg.bAutoTxRateSwitch = (HtMcs == MCS_AUTO) ? TRUE:FALSE;
-		DBGPRINT(RT_DEBUG_TRACE, ("Set_HtMcs_Proc::(HtMcs=%d, bAutoTxRateSwitch = %d)\n",
-						pAd->StaCfg.DesiredTransmitSetting.field.MCS, pAd->StaCfg.bAutoTxRateSwitch));
-
-		if ((pAd->CommonCfg.PhyMode < PHY_11ABGN_MIXED) ||
-			(pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE < MODE_HTMIX))
-		{
-	        if ((pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO) &&
-				(HtMcs >= 0 && HtMcs <= 3) &&
-	            (pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode == FIXED_TXMODE_CCK))
-			{
-				RTMPSetDesiredRates(pAd, (LONG) (RateIdToMbps[HtMcs] * 1000000));
-			}
-	        else if ((pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO) &&
-					(HtMcs >= 0 && HtMcs <= 7) &&
-	            	(pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode == FIXED_TXMODE_OFDM))
-			{
-				RTMPSetDesiredRates(pAd, (LONG) (RateIdToMbps[HtMcs+4] * 1000000));
-			}
-			else
-				bAutoRate = TRUE;
-
-			if (bAutoRate)
-			{
-	            pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-				RTMPSetDesiredRates(pAd, -1);
-			}
-	        DBGPRINT(RT_DEBUG_TRACE, ("Set_HtMcs_Proc::(FixedTxMode=%d)\n",pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode));
-		}
-        if (ADHOC_ON(pAd))
-            return TRUE;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	SetCommonHT(pAd);
-
-	return TRUE;
-}
-
-INT	Set_HtGi_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG HtGi;
-
-	HtGi = simple_strtol(arg, 0, 10);
-
-	if ( HtGi == GI_400)
-		pAd->CommonCfg.RegTransmitSetting.field.ShortGI = GI_400;
-	else if ( HtGi == GI_800 )
-		pAd->CommonCfg.RegTransmitSetting.field.ShortGI = GI_800;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtGi_Proc::(ShortGI=%d)\n",pAd->CommonCfg.RegTransmitSetting.field.ShortGI));
-
-	return TRUE;
-}
-
-
-INT	Set_HtTxBASize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR Size;
-
-	Size = simple_strtol(arg, 0, 10);
-
-	if (Size <=0 || Size >=64)
-	{
-		Size = 8;
-	}
-	pAd->CommonCfg.TxBASize = Size-1;
-	DBGPRINT(RT_DEBUG_ERROR, ("Set_HtTxBASize ::(TxBASize= %d)\n", Size));
-
-	return TRUE;
-}
-
-
-INT	Set_HtOpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value == HTMODE_GF)
-		pAd->CommonCfg.RegTransmitSetting.field.HTMODE  = HTMODE_GF;
-	else if ( Value == HTMODE_MM )
-		pAd->CommonCfg.RegTransmitSetting.field.HTMODE  = HTMODE_MM;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtOpMode_Proc::(HtOpMode=%d)\n",pAd->CommonCfg.RegTransmitSetting.field.HTMODE));
-
-	return TRUE;
-
-}
-
-INT	Set_HtStbc_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value == STBC_USE)
-		pAd->CommonCfg.RegTransmitSetting.field.STBC = STBC_USE;
-	else if ( Value == STBC_NONE )
-		pAd->CommonCfg.RegTransmitSetting.field.STBC = STBC_NONE;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_Stbc_Proc::(HtStbc=%d)\n",pAd->CommonCfg.RegTransmitSetting.field.STBC));
-
-	return TRUE;
-}
-
-INT	Set_HtHtc_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->HTCEnable = FALSE;
-	else if ( Value ==1 )
-        	pAd->HTCEnable = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtHtc_Proc::(HtHtc=%d)\n",pAd->HTCEnable));
-
-	return TRUE;
-}
-
-INT	Set_HtExtcha_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value == 0)
-		pAd->CommonCfg.RegTransmitSetting.field.EXTCHA  = EXTCHA_BELOW;
-	else if ( Value ==1 )
-        pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtExtcha_Proc::(HtExtcha=%d)\n",pAd->CommonCfg.RegTransmitSetting.field.EXTCHA));
-
-	return TRUE;
-}
-
-INT	Set_HtMpduDensity_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value <=7 && Value >= 0)
-		pAd->CommonCfg.BACapability.field.MpduDensity = Value;
-	else
-		pAd->CommonCfg.BACapability.field.MpduDensity = 4;
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtMpduDensity_Proc::(HtMpduDensity=%d)\n",pAd->CommonCfg.BACapability.field.MpduDensity));
-
-	return TRUE;
-}
-
-INT	Set_HtBaWinSize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-
-	if (Value >=1 && Value <= 64)
-	{
-		pAd->CommonCfg.REGBACapability.field.RxBAWinLimit = Value;
-		pAd->CommonCfg.BACapability.field.RxBAWinLimit = Value;
-	}
-	else
-	{
-        pAd->CommonCfg.REGBACapability.field.RxBAWinLimit = 64;
-		pAd->CommonCfg.BACapability.field.RxBAWinLimit = 64;
-	}
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtBaWinSize_Proc::(HtBaWinSize=%d)\n",pAd->CommonCfg.BACapability.field.RxBAWinLimit));
-
-	return TRUE;
-}
-
-INT	Set_HtRdg_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value == 0)
-		pAd->CommonCfg.bRdg = FALSE;
-	else if ( Value ==1 )
-	{
-		pAd->HTCEnable = TRUE;
-        	pAd->CommonCfg.bRdg = TRUE;
-	}
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtRdg_Proc::(HtRdg=%d)\n",pAd->CommonCfg.bRdg));
-
-	return TRUE;
-}
-
-INT	Set_HtLinkAdapt_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->bLinkAdapt = FALSE;
-	else if ( Value ==1 )
-	{
-			pAd->HTCEnable = TRUE;
-			pAd->bLinkAdapt = TRUE;
-	}
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtLinkAdapt_Proc::(HtLinkAdapt=%d)\n",pAd->bLinkAdapt));
-
-	return TRUE;
-}
-
-INT	Set_HtAmsdu_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->CommonCfg.BACapability.field.AmsduEnable = FALSE;
-	else if ( Value == 1 )
-        pAd->CommonCfg.BACapability.field.AmsduEnable = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtAmsdu_Proc::(HtAmsdu=%d)\n",pAd->CommonCfg.BACapability.field.AmsduEnable));
-
-	return TRUE;
-}
-
-INT	Set_HtAutoBa_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-	{
-		pAd->CommonCfg.BACapability.field.AutoBA = FALSE;
-		pAd->CommonCfg.BACapability.field.Policy = BA_NOTUSE;
-	}
-        else if (Value == 1)
-	{
-		pAd->CommonCfg.BACapability.field.AutoBA = TRUE;
-		pAd->CommonCfg.BACapability.field.Policy = IMMED_BA;
-	}
-	else
-		return FALSE; //Invalid argument
-
-    pAd->CommonCfg.REGBACapability.field.AutoBA = pAd->CommonCfg.BACapability.field.AutoBA;
-    pAd->CommonCfg.REGBACapability.field.Policy = pAd->CommonCfg.BACapability.field.Policy;
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtAutoBa_Proc::(HtAutoBa=%d)\n",pAd->CommonCfg.BACapability.field.AutoBA));
-
-	return TRUE;
-
-}
-
-INT	Set_HtProtect_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->CommonCfg.bHTProtect = FALSE;
-    else if (Value == 1)
-		pAd->CommonCfg.bHTProtect = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtProtect_Proc::(HtProtect=%d)\n",pAd->CommonCfg.bHTProtect));
-
-	return TRUE;
-}
-
-INT	Set_SendPSMPAction_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    UCHAR mac[6], mode;
-	char *token, sepValue[] = ":", DASH = '-';
-	INT i;
-    MAC_TABLE_ENTRY *pEntry;
-
-    //printk("\n%s\n", arg);
-/*
-	The BARecTearDown inupt string format should be xx:xx:xx:xx:xx:xx-d,
-		=>The six 2 digit hex-decimal number previous are the Mac address,
-		=>The seventh decimal number is the mode value.
-*/
-    if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and mode value in decimal format.
-		return FALSE;
-
-   	token = strchr(arg, DASH);
-	if ((token != NULL) && (strlen(token)>1))
-	{
-		mode = simple_strtol((token+1), 0, 10);
-		if (mode > MMPS_ENABLE)
-			return FALSE;
-
-		*token = '\0';
-		for (i = 0, token = rstrtok(arg, &sepValue[0]); token; token = rstrtok(NULL, &sepValue[0]), i++)
-		{
-			if((strlen(token) != 2) || (!isxdigit(*token)) || (!isxdigit(*(token+1))))
-				return FALSE;
-			AtoH(token, (PUCHAR)(&mac[i]), 1);
-		}
-		if(i != 6)
-			return FALSE;
-
-		printk("\n%02x:%02x:%02x:%02x:%02x:%02x-%02x", mac[0], mac[1],
-		       mac[2], mac[3], mac[4], mac[5], mode);
-
-		pEntry = MacTableLookup(pAd, mac);
-
-		if (pEntry) {
-		    printk("\nSendPSMPAction MIPS mode = %d\n", mode);
-		    SendPSMPAction(pAd, pEntry->Aid, mode);
-		}
-
-		return TRUE;
-	}
-
-	return FALSE;
-
-
-}
-
-INT	Set_HtMIMOPSmode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	if (Value <=3 && Value >= 0)
-		pAd->CommonCfg.BACapability.field.MMPSmode = Value;
-	else
-		pAd->CommonCfg.BACapability.field.MMPSmode = 3;
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtMIMOPSmode_Proc::(MIMOPS mode=%d)\n",pAd->CommonCfg.BACapability.field.MMPSmode));
-
-	return TRUE;
-}
-
-
-INT	Set_ForceShortGI_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->WIFItestbed.bShortGI = FALSE;
-	else if (Value == 1)
-		pAd->WIFItestbed.bShortGI = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_ForceShortGI_Proc::(ForceShortGI=%d)\n", pAd->WIFItestbed.bShortGI));
-
-	return TRUE;
-}
-
-
-
-INT	Set_ForceGF_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->WIFItestbed.bGreenField = FALSE;
-	else if (Value == 1)
-		pAd->WIFItestbed.bGreenField = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	SetCommonHT(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_ForceGF_Proc::(ForceGF=%d)\n", pAd->WIFItestbed.bGreenField));
-
-	return TRUE;
-}
-
-INT	Set_HtMimoPs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-	if (Value == 0)
-		pAd->CommonCfg.bMIMOPSEnable = FALSE;
-	else if (Value == 1)
-		pAd->CommonCfg.bMIMOPSEnable = TRUE;
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_HtMimoPs_Proc::(HtMimoPs=%d)\n",pAd->CommonCfg.bMIMOPSEnable));
-
-	return TRUE;
-}
-#endif // DOT11_N_SUPPORT //
-
-
-#ifdef DOT11_N_SUPPORT
-INT	SetCommonHT(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	OID_SET_HT_PHYMODE		SetHT;
-
-	if (pAd->CommonCfg.PhyMode < PHY_11ABGN_MIXED)
-		return FALSE;
-
-	SetHT.PhyMode = pAd->CommonCfg.PhyMode;
-	SetHT.TransmitNo = ((UCHAR)pAd->Antenna.field.TxPath);
-	SetHT.HtMode = (UCHAR)pAd->CommonCfg.RegTransmitSetting.field.HTMODE;
-	SetHT.ExtOffset = (UCHAR)pAd->CommonCfg.RegTransmitSetting.field.EXTCHA;
-	SetHT.MCS = MCS_AUTO;
-	SetHT.BW = (UCHAR)pAd->CommonCfg.RegTransmitSetting.field.BW;
-	SetHT.STBC = (UCHAR)pAd->CommonCfg.RegTransmitSetting.field.STBC;
-	SetHT.SHORTGI = (UCHAR)pAd->CommonCfg.RegTransmitSetting.field.ShortGI;
-
-	RTMPSetHT(pAd, &SetHT);
-
-	return TRUE;
-}
-#endif // DOT11_N_SUPPORT //
-
-INT	Set_FixedTxMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR	fix_tx_mode = FIXED_TXMODE_HT;
-
-	if (strcmp(arg, "OFDM") == 0 || strcmp(arg, "ofdm") == 0)
-	{
-		fix_tx_mode = FIXED_TXMODE_OFDM;
-	}
-	else if (strcmp(arg, "CCK") == 0 || strcmp(arg, "cck") == 0)
-	{
-        fix_tx_mode = FIXED_TXMODE_CCK;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode = fix_tx_mode;
-#endif // CONFIG_STA_SUPPORT //
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_FixedTxMode_Proc::(FixedTxMode=%d)\n", fix_tx_mode));
-
-	return TRUE;
-}
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-INT	Set_OpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ULONG Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-#ifdef RT2870
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP))
-#endif // RT2870 //
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Can not switch operate mode on interface up !! \n"));
-		return FALSE;
-	}
-
-	if (Value == 0)
-		pAd->OpMode = OPMODE_STA;
-	else if (Value == 1)
-		pAd->OpMode = OPMODE_AP;
-	else
-		return FALSE; //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_OpMode_Proc::(OpMode=%s)\n", pAd->OpMode == 1 ? "AP Mode" : "STA Mode"));
-
-	return TRUE;
-}
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-
-/////////////////////////////////////////////////////////////////////////
-PCHAR   RTMPGetRalinkAuthModeStr(
-    IN  NDIS_802_11_AUTHENTICATION_MODE authMode)
-{
-	switch(authMode)
-	{
-		case Ndis802_11AuthModeOpen:
-			return "OPEN";
-        default:
-		case Ndis802_11AuthModeWPAPSK:
-			return "WPAPSK";
-		case Ndis802_11AuthModeShared:
-			return "SHARED";
-		case Ndis802_11AuthModeWPA:
-			return "WPA";
-		case Ndis802_11AuthModeWPA2:
-			return "WPA2";
-		case Ndis802_11AuthModeWPA2PSK:
-			return "WPA2PSK";
-        case Ndis802_11AuthModeWPA1PSKWPA2PSK:
-			return "WPAPSKWPA2PSK";
-        case Ndis802_11AuthModeWPA1WPA2:
-			return "WPA1WPA2";
-	}
-}
-
-PCHAR   RTMPGetRalinkEncryModeStr(
-    IN  USHORT encryMode)
-{
-	switch(encryMode)
-	{
-	    default:
-		case Ndis802_11WEPDisabled:
-			return "NONE";
-		case Ndis802_11WEPEnabled:
-			return "WEP";
-		case Ndis802_11Encryption2Enabled:
-			return "TKIP";
-		case Ndis802_11Encryption3Enabled:
-			return "AES";
-        case Ndis802_11Encryption4Enabled:
-			return "TKIPAES";
-	}
-}
-
-INT RTMPShowCfgValue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pName,
-	IN	PUCHAR			pBuf)
-{
-	INT	Status = 0;
-
-	for (PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC = RTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC; PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name; PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC++)
-	{
-		if (!strcmp(pName, PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name))
-		{
-			if(PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->show_proc(pAd, pBuf))
-				Status = -EINVAL;
-			break;  //Exit for loop.
-		}
-	}
-
-	if(PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name == NULL)
-	{
-		sprintf(pBuf, "\n");
-		for (PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC = RTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC; PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name; PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC++)
-			sprintf(pBuf, "%s%s\n", pBuf, PRTMP_PRIVATE_STA_SHOW_CFG_VALUE_PROC->name);
-	}
-
-	return Status;
-}
-
-INT	Show_SSID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		sprintf(pBuf, "\t%s", pAd->CommonCfg.Ssid);
-#endif // CONFIG_STA_SUPPORT //
-	return 0;
-}
-
-INT	Show_WirelessMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.PhyMode)
-	{
-		case PHY_11BG_MIXED:
-			sprintf(pBuf, "\t11B/G");
-			break;
-		case PHY_11B:
-			sprintf(pBuf, "\t11B");
-			break;
-		case PHY_11A:
-			sprintf(pBuf, "\t11A");
-			break;
-		case PHY_11ABG_MIXED:
-			sprintf(pBuf, "\t11A/B/G");
-			break;
-		case PHY_11G:
-			sprintf(pBuf, "\t11G");
-			break;
-#ifdef DOT11_N_SUPPORT
-		case PHY_11ABGN_MIXED:
-			sprintf(pBuf, "\t11A/B/G/N");
-			break;
-		case PHY_11N_2_4G:
-			sprintf(pBuf, "\t11N only with 2.4G");
-			break;
-		case PHY_11GN_MIXED:
-			sprintf(pBuf, "\t11G/N");
-			break;
-		case PHY_11AN_MIXED:
-			sprintf(pBuf, "\t11A/N");
-			break;
-		case PHY_11BGN_MIXED:
-			sprintf(pBuf, "\t11B/G/N");
-			break;
-		case PHY_11AGN_MIXED:
-			sprintf(pBuf, "\t11A/G/N");
-			break;
-		case PHY_11N_5G:
-			sprintf(pBuf, "\t11N only with 5G");
-			break;
-#endif // DOT11_N_SUPPORT //
-		default:
-			sprintf(pBuf, "\tUnknow Value(%d)", pAd->CommonCfg.PhyMode);
-			break;
-	}
-	return 0;
-}
-
-
-INT	Show_TxBurst_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.bEnableTxBurst ? "TRUE":"FALSE");
-	return 0;
-}
-
-INT	Show_TxPreamble_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.TxPreamble)
-	{
-		case Rt802_11PreambleShort:
-			sprintf(pBuf, "\tShort");
-			break;
-		case Rt802_11PreambleLong:
-			sprintf(pBuf, "\tLong");
-			break;
-		case Rt802_11PreambleAuto:
-			sprintf(pBuf, "\tAuto");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%lu)", pAd->CommonCfg.TxPreamble);
-			break;
-	}
-
-	return 0;
-}
-
-INT	Show_TxPower_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%lu", pAd->CommonCfg.TxPowerPercentage);
-	return 0;
-}
-
-INT	Show_Channel_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%d", pAd->CommonCfg.Channel);
-	return 0;
-}
-
-INT	Show_BGProtection_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.UseBGProtection)
-	{
-		case 1: //Always On
-			sprintf(pBuf, "\tON");
-			break;
-		case 2: //Always OFF
-			sprintf(pBuf, "\tOFF");
-			break;
-		case 0: //AUTO
-			sprintf(pBuf, "\tAuto");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%lu)", pAd->CommonCfg.UseBGProtection);
-			break;
-	}
-	return 0;
-}
-
-INT	Show_RTSThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%u", pAd->CommonCfg.RtsThreshold);
-	return 0;
-}
-
-INT	Show_FragThreshold_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%u", pAd->CommonCfg.FragmentThreshold);
-	return 0;
-}
-
-#ifdef DOT11_N_SUPPORT
-INT	Show_HtBw_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	if (pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40)
-	{
-		sprintf(pBuf, "\t40 MHz");
-	}
-	else
-	{
-        sprintf(pBuf, "\t20 MHz");
-	}
-	return 0;
-}
-
-INT	Show_HtMcs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		sprintf(pBuf, "\t%u", pAd->StaCfg.DesiredTransmitSetting.field.MCS);
-#endif // CONFIG_STA_SUPPORT //
-	return 0;
-}
-
-INT	Show_HtGi_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.RegTransmitSetting.field.ShortGI)
-	{
-		case GI_400:
-			sprintf(pBuf, "\tGI_400");
-			break;
-		case GI_800:
-			sprintf(pBuf, "\tGI_800");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%u)", pAd->CommonCfg.RegTransmitSetting.field.ShortGI);
-			break;
-	}
-	return 0;
-}
-
-INT	Show_HtOpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.RegTransmitSetting.field.HTMODE)
-	{
-		case HTMODE_GF:
-			sprintf(pBuf, "\tGF");
-			break;
-		case HTMODE_MM:
-			sprintf(pBuf, "\tMM");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%u)", pAd->CommonCfg.RegTransmitSetting.field.HTMODE);
-			break;
-	}
-	return 0;
-}
-
-INT	Show_HtExtcha_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->CommonCfg.RegTransmitSetting.field.EXTCHA)
-	{
-		case EXTCHA_BELOW:
-			sprintf(pBuf, "\tBelow");
-			break;
-		case EXTCHA_ABOVE:
-			sprintf(pBuf, "\tAbove");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%u)", pAd->CommonCfg.RegTransmitSetting.field.EXTCHA);
-			break;
-	}
-	return 0;
-}
-
-
-INT	Show_HtMpduDensity_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%u", pAd->CommonCfg.BACapability.field.MpduDensity);
-	return 0;
-}
-
-INT	Show_HtBaWinSize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%u", pAd->CommonCfg.BACapability.field.RxBAWinLimit);
-	return 0;
-}
-
-INT	Show_HtRdg_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.bRdg ? "TRUE":"FALSE");
-	return 0;
-}
-
-INT	Show_HtAmsdu_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.BACapability.field.AmsduEnable ? "TRUE":"FALSE");
-	return 0;
-}
-
-INT	Show_HtAutoBa_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.BACapability.field.AutoBA ? "TRUE":"FALSE");
-	return 0;
-}
-#endif // DOT11_N_SUPPORT //
-
-INT	Show_CountryRegion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%d", pAd->CommonCfg.CountryRegion);
-	return 0;
-}
-
-INT	Show_CountryRegionABand_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%d", pAd->CommonCfg.CountryRegionForABand);
-	return 0;
-}
-
-INT	Show_CountryCode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.CountryCode);
-	return 0;
-}
-
-#ifdef AGGREGATION_SUPPORT
-INT	Show_PktAggregate_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.bAggregationCapable ? "TRUE":"FALSE");
-	return 0;
-}
-#endif // AGGREGATION_SUPPORT //
-
-#ifdef WMM_SUPPORT
-INT	Show_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		sprintf(pBuf, "\t%s", pAd->CommonCfg.bWmmCapable ? "TRUE":"FALSE");
-#endif // CONFIG_STA_SUPPORT //
-
-	return 0;
-}
-#endif // WMM_SUPPORT //
-
-INT	Show_IEEE80211H_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	sprintf(pBuf, "\t%s", pAd->CommonCfg.bIEEE80211H ? "TRUE":"FALSE");
-	return 0;
-}
-
-#ifdef CONFIG_STA_SUPPORT
-INT	Show_NetworkType_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	switch(pAd->StaCfg.BssType)
-	{
-		case BSS_ADHOC:
-			sprintf(pBuf, "\tAdhoc");
-			break;
-		case BSS_INFRA:
-			sprintf(pBuf, "\tInfra");
-			break;
-		case BSS_ANY:
-			sprintf(pBuf, "\tAny");
-			break;
-		case BSS_MONITOR:
-			sprintf(pBuf, "\tMonitor");
-			break;
-		default:
-			sprintf(pBuf, "\tUnknow Value(%d)", pAd->StaCfg.BssType);
-			break;
-	}
-	return 0;
-}
-#endif // CONFIG_STA_SUPPORT //
-
-INT	Show_AuthMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	NDIS_802_11_AUTHENTICATION_MODE	AuthMode = Ndis802_11AuthModeOpen;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		AuthMode = pAd->StaCfg.AuthMode;
-#endif // CONFIG_STA_SUPPORT //
-
-	if ((AuthMode >= Ndis802_11AuthModeOpen) &&
-		(AuthMode <= Ndis802_11AuthModeWPA1PSKWPA2PSK))
-		sprintf(pBuf, "\t%s", RTMPGetRalinkAuthModeStr(AuthMode));
-	else
-		sprintf(pBuf, "\tUnknow Value(%d)", AuthMode);
-
-	return 0;
-}
-
-INT	Show_EncrypType_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	NDIS_802_11_WEP_STATUS	WepStatus = Ndis802_11WEPDisabled;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		WepStatus = pAd->StaCfg.WepStatus;
-#endif // CONFIG_STA_SUPPORT //
-
-	if ((WepStatus >= Ndis802_11WEPEnabled) &&
-		(WepStatus <= Ndis802_11Encryption4KeyAbsent))
-		sprintf(pBuf, "\t%s", RTMPGetRalinkEncryModeStr(WepStatus));
-	else
-		sprintf(pBuf, "\tUnknow Value(%d)", WepStatus);
-
-	return 0;
-}
-
-INT	Show_DefaultKeyID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	UCHAR DefaultKeyId = 0;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		DefaultKeyId = pAd->StaCfg.DefaultKeyId;
-#endif // CONFIG_STA_SUPPORT //
-
-	sprintf(pBuf, "\t%d", DefaultKeyId);
-
-	return 0;
-}
-
-INT	Show_WepKey_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  INT				KeyIdx,
-	OUT	PUCHAR			pBuf)
-{
-	UCHAR   Key[16] = {0}, KeyLength = 0;
-	INT		index = BSS0;
-
-	KeyLength = pAd->SharedKey[index][KeyIdx].KeyLen;
-	NdisMoveMemory(Key, pAd->SharedKey[index][KeyIdx].Key, KeyLength);
-
-	//check key string is ASCII or not
-    if (RTMPCheckStrPrintAble(Key, KeyLength))
-        sprintf(pBuf, "\t%s", Key);
-    else
-    {
-        int idx;
-        sprintf(pBuf, "\t");
-        for (idx = 0; idx < KeyLength; idx++)
-            sprintf(pBuf+strlen(pBuf), "%02X", Key[idx]);
-    }
-	return 0;
-}
-
-INT	Show_Key1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	Show_WepKey_Proc(pAd, 0, pBuf);
-	return 0;
-}
-
-INT	Show_Key2_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	Show_WepKey_Proc(pAd, 1, pBuf);
-	return 0;
-}
-
-INT	Show_Key3_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	Show_WepKey_Proc(pAd, 2, pBuf);
-	return 0;
-}
-
-INT	Show_Key4_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	Show_WepKey_Proc(pAd, 3, pBuf);
-	return 0;
-}
-
-INT	Show_WPAPSK_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUCHAR			pBuf)
-{
-	INT 	idx;
-	UCHAR	PMK[32] = {0};
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		NdisMoveMemory(PMK, pAd->StaCfg.PMK, 32);
-#endif // CONFIG_STA_SUPPORT //
-
-    sprintf(pBuf, "\tPMK = ");
-    for (idx = 0; idx < 32; idx++)
-        sprintf(pBuf+strlen(pBuf), "%02X", PMK[idx]);
-
-	return 0;
-}
-
+#include "../../rt2870/common/cmm_info.c"
diff --git a/drivers/staging/rt3070/common/cmm_sanity.c b/drivers/staging/rt3070/common/cmm_sanity.c
index 6118df8..82ccf9e 100644
--- a/drivers/staging/rt3070/common/cmm_sanity.c
+++ b/drivers/staging/rt3070/common/cmm_sanity.c
@@ -1,1669 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	sanity.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang  2004-09-01      add WMM support
-*/
-#include "../rt_config.h"
-
-
-extern UCHAR	CISCO_OUI[];
-
-extern UCHAR	WPA_OUI[];
-extern UCHAR	RSN_OUI[];
-extern UCHAR	WME_INFO_ELEM[];
-extern UCHAR	WME_PARM_ELEM[];
-extern UCHAR	Ccx2QosInfo[];
-extern UCHAR	RALINK_OUI[];
-extern UCHAR	BROADCOM_OUI[];
-extern UCHAR    WPS_OUI[];
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN MlmeAddBAReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2)
-{
-    PMLME_ADDBA_REQ_STRUCT   pInfo;
-
-    pInfo = (MLME_ADDBA_REQ_STRUCT *)Msg;
-
-    if ((MsgLen != sizeof(MLME_ADDBA_REQ_STRUCT)))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeAddBAReqSanity fail - message lenght not correct.\n"));
-        return FALSE;
-    }
-
-    if ((pInfo->Wcid >= MAX_LEN_OF_MAC_TABLE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeAddBAReqSanity fail - The peer Mac is not associated yet.\n"));
-        return FALSE;
-    }
-
-	/*
-    if ((pInfo->BaBufSize > MAX_RX_REORDERBUF) || (pInfo->BaBufSize < 2))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeAddBAReqSanity fail - Rx Reordering buffer too big or too small\n"));
-        return FALSE;
-    }
-	*/
-
-    if ((pInfo->pAddr[0]&0x01) == 0x01)
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeAddBAReqSanity fail - broadcast address not support BA\n"));
-        return FALSE;
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN MlmeDelBAReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen)
-{
-	MLME_DELBA_REQ_STRUCT *pInfo;
-	pInfo = (MLME_DELBA_REQ_STRUCT *)Msg;
-
-    if ((MsgLen != sizeof(MLME_DELBA_REQ_STRUCT)))
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("MlmeDelBAReqSanity fail - message lenght not correct.\n"));
-        return FALSE;
-    }
-
-    if ((pInfo->Wcid >= MAX_LEN_OF_MAC_TABLE))
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("MlmeDelBAReqSanity fail - The peer Mac is not associated yet.\n"));
-        return FALSE;
-    }
-
-    if ((pInfo->TID & 0xf0))
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("MlmeDelBAReqSanity fail - The peer TID is incorrect.\n"));
-        return FALSE;
-    }
-
-	if (NdisEqualMemory(pAd->MacTab.Content[pInfo->Wcid].Addr, pInfo->Addr, MAC_ADDR_LEN) == 0)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("MlmeDelBAReqSanity fail - the peer addr dosen't exist.\n"));
-        return FALSE;
-    }
-
-    return TRUE;
-}
-
-BOOLEAN PeerAddBAReqActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *pMsg,
-    IN ULONG MsgLen,
-	OUT PUCHAR pAddr2)
-{
-	PFRAME_802_11 pFrame = (PFRAME_802_11)pMsg;
-	PFRAME_ADDBA_REQ pAddFrame;
-	pAddFrame = (PFRAME_ADDBA_REQ)(pMsg);
-	if (MsgLen < (sizeof(FRAME_ADDBA_REQ)))
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBAReqActionSanity: ADDBA Request frame length size = %ld incorrect\n", MsgLen));
-		return FALSE;
-	}
-	// we support immediate BA.
-	*(USHORT *)(&pAddFrame->BaParm) = cpu2le16(*(USHORT *)(&pAddFrame->BaParm));
-	pAddFrame->TimeOutValue = cpu2le16(pAddFrame->TimeOutValue);
-	pAddFrame->BaStartSeq.word = cpu2le16(pAddFrame->BaStartSeq.word);
-
-	if (pAddFrame->BaParm.BAPolicy != IMMED_BA)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBAReqActionSanity: ADDBA Request Ba Policy[%d] not support\n", pAddFrame->BaParm.BAPolicy));
-		DBGPRINT(RT_DEBUG_ERROR,("ADDBA Request. tid=%x, Bufsize=%x, AMSDUSupported=%x \n", pAddFrame->BaParm.TID, pAddFrame->BaParm.BufSize, pAddFrame->BaParm.AMSDUSupported));
-		return FALSE;
-	}
-
-	// we support immediate BA.
-	if (pAddFrame->BaParm.TID &0xfff0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBAReqActionSanity: ADDBA Request incorrect TID = %d\n", pAddFrame->BaParm.TID));
-		return FALSE;
-	}
-	COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-	return TRUE;
-}
-
-BOOLEAN PeerAddBARspActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *pMsg,
-    IN ULONG MsgLen)
-{
-	//PFRAME_802_11 pFrame = (PFRAME_802_11)pMsg;
-	PFRAME_ADDBA_RSP pAddFrame;
-
-	pAddFrame = (PFRAME_ADDBA_RSP)(pMsg);
-	if (MsgLen < (sizeof(FRAME_ADDBA_RSP)))
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBARspActionSanity: ADDBA Response frame length size = %ld incorrect\n", MsgLen));
-		return FALSE;
-	}
-	// we support immediate BA.
-	*(USHORT *)(&pAddFrame->BaParm) = cpu2le16(*(USHORT *)(&pAddFrame->BaParm));
-	pAddFrame->StatusCode = cpu2le16(pAddFrame->StatusCode);
-	pAddFrame->TimeOutValue = cpu2le16(pAddFrame->TimeOutValue);
-
-	if (pAddFrame->BaParm.BAPolicy != IMMED_BA)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBAReqActionSanity: ADDBA Response Ba Policy[%d] not support\n", pAddFrame->BaParm.BAPolicy));
-		return FALSE;
-	}
-
-	// we support immediate BA.
-	if (pAddFrame->BaParm.TID &0xfff0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("PeerAddBARspActionSanity: ADDBA Response incorrect TID = %d\n", pAddFrame->BaParm.TID));
-		return FALSE;
-	}
-	return TRUE;
-
-}
-
-BOOLEAN PeerDelBAActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN UCHAR Wcid,
-    IN VOID *pMsg,
-    IN ULONG MsgLen )
-{
-	//PFRAME_802_11 pFrame = (PFRAME_802_11)pMsg;
-	PFRAME_DELBA_REQ  pDelFrame;
-	if (MsgLen != (sizeof(FRAME_DELBA_REQ)))
-		return FALSE;
-
-	if (Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return FALSE;
-
-	pDelFrame = (PFRAME_DELBA_REQ)(pMsg);
-
-	*(USHORT *)(&pDelFrame->DelbaParm) = cpu2le16(*(USHORT *)(&pDelFrame->DelbaParm));
-	pDelFrame->ReasonCode = cpu2le16(pDelFrame->ReasonCode);
-
-	if (pDelFrame->DelbaParm.TID &0xfff0)
-		return FALSE;
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerBeaconAndProbeRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    IN UCHAR  MsgChannel,
-    OUT PUCHAR pAddr2,
-    OUT PUCHAR pBssid,
-    OUT CHAR Ssid[],
-    OUT UCHAR *pSsidLen,
-    OUT UCHAR *pBssType,
-    OUT USHORT *pBeaconPeriod,
-    OUT UCHAR *pChannel,
-    OUT UCHAR *pNewChannel,
-    OUT LARGE_INTEGER *pTimestamp,
-    OUT CF_PARM *pCfParm,
-    OUT USHORT *pAtimWin,
-    OUT USHORT *pCapabilityInfo,
-    OUT UCHAR *pErp,
-    OUT UCHAR *pDtimCount,
-    OUT UCHAR *pDtimPeriod,
-    OUT UCHAR *pBcastFlag,
-    OUT UCHAR *pMessageToMe,
-    OUT UCHAR SupRate[],
-    OUT UCHAR *pSupRateLen,
-    OUT UCHAR ExtRate[],
-    OUT UCHAR *pExtRateLen,
-    OUT	UCHAR *pCkipFlag,
-    OUT	UCHAR *pAironetCellPowerLimit,
-    OUT PEDCA_PARM       pEdcaParm,
-    OUT PQBSS_LOAD_PARM  pQbssLoad,
-    OUT PQOS_CAPABILITY_PARM pQosCapability,
-    OUT ULONG *pRalinkIe,
-    OUT UCHAR		 *pHtCapabilityLen,
-#ifdef CONFIG_STA_SUPPORT
-    OUT UCHAR		 *pPreNHtCapabilityLen,
-#endif // CONFIG_STA_SUPPORT //
-    OUT HT_CAPABILITY_IE *pHtCapability,
-	OUT UCHAR		 *AddHtInfoLen,
-	OUT ADD_HT_INFO_IE *AddHtInfo,
-	OUT UCHAR *NewExtChannelOffset,		// Ht extension channel offset(above or below)
-    OUT USHORT *LengthVIE,
-    OUT	PNDIS_802_11_VARIABLE_IEs pVIE)
-{
-    CHAR				*Ptr;
-#ifdef CONFIG_STA_SUPPORT
-	CHAR 				TimLen;
-#endif // CONFIG_STA_SUPPORT //
-    PFRAME_802_11		pFrame;
-    PEID_STRUCT         pEid;
-    UCHAR				SubType;
-    UCHAR				Sanity;
-    //UCHAR				ECWMin, ECWMax;
-    //MAC_CSR9_STRUC		Csr9;
-    ULONG				Length = 0;
-
-	// For some 11a AP which didn't have DS_IE, we use two conditions to decide the channel
-	//	1. If the AP is 11n enabled, then check the control channel.
-	//	2. If the AP didn't have any info about channel, use the channel we received this frame as the channel. (May inaccuracy!!)
-	UCHAR			CtrlChannel = 0;
-
-    // Add for 3 necessary EID field check
-    Sanity = 0;
-
-    *pAtimWin = 0;
-    *pErp = 0;
-    *pDtimCount = 0;
-    *pDtimPeriod = 0;
-    *pBcastFlag = 0;
-    *pMessageToMe = 0;
-    *pExtRateLen = 0;
-    *pCkipFlag = 0;			        // Default of CkipFlag is 0
-    *pAironetCellPowerLimit = 0xFF;  // Default of AironetCellPowerLimit is 0xFF
-    *LengthVIE = 0;					// Set the length of VIE to init value 0
-    *pHtCapabilityLen = 0;					// Set the length of VIE to init value 0
-#ifdef CONFIG_STA_SUPPORT
-	if (pAd->OpMode == OPMODE_STA)
-		*pPreNHtCapabilityLen = 0;					// Set the length of VIE to init value 0
-#endif // CONFIG_STA_SUPPORT //
-    *AddHtInfoLen = 0;					// Set the length of VIE to init value 0
-    *pRalinkIe = 0;
-    *pNewChannel = 0;
-    *NewExtChannelOffset = 0xff;	//Default 0xff means no such IE
-    pCfParm->bValid = FALSE;        // default: no IE_CF found
-    pQbssLoad->bValid = FALSE;      // default: no IE_QBSS_LOAD found
-    pEdcaParm->bValid = FALSE;      // default: no IE_EDCA_PARAMETER found
-    pQosCapability->bValid = FALSE; // default: no IE_QOS_CAPABILITY found
-
-    pFrame = (PFRAME_802_11)Msg;
-
-    // get subtype from header
-    SubType = (UCHAR)pFrame->Hdr.FC.SubType;
-
-    // get Addr2 and BSSID from header
-    COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-    COPY_MAC_ADDR(pBssid, pFrame->Hdr.Addr3);
-
-//	hex_dump("Beacon", Msg, MsgLen);
-
-    Ptr = pFrame->Octet;
-    Length += LENGTH_802_11;
-
-    // get timestamp from payload and advance the pointer
-    NdisMoveMemory(pTimestamp, Ptr, TIMESTAMP_LEN);
-
-	pTimestamp->u.LowPart = cpu2le32(pTimestamp->u.LowPart);
-	pTimestamp->u.HighPart = cpu2le32(pTimestamp->u.HighPart);
-
-    Ptr += TIMESTAMP_LEN;
-    Length += TIMESTAMP_LEN;
-
-    // get beacon interval from payload and advance the pointer
-    NdisMoveMemory(pBeaconPeriod, Ptr, 2);
-    Ptr += 2;
-    Length += 2;
-
-    // get capability info from payload and advance the pointer
-    NdisMoveMemory(pCapabilityInfo, Ptr, 2);
-    Ptr += 2;
-    Length += 2;
-
-    if (CAP_IS_ESS_ON(*pCapabilityInfo))
-        *pBssType = BSS_INFRA;
-    else
-        *pBssType = BSS_ADHOC;
-
-    pEid = (PEID_STRUCT) Ptr;
-
-    // get variable fields from payload and advance the pointer
-    while ((Length + 2 + pEid->Len) <= MsgLen)
-    {
-        //
-        // Secure copy VIE to VarIE[MAX_VIE_LEN] didn't overflow.
-        //
-        if ((*LengthVIE + pEid->Len + 2) >= MAX_VIE_LEN)
-        {
-            DBGPRINT(RT_DEBUG_WARN, ("PeerBeaconAndProbeRspSanity - Variable IEs out of resource [len(=%d) > MAX_VIE_LEN(=%d)]\n",
-                    (*LengthVIE + pEid->Len + 2), MAX_VIE_LEN));
-            break;
-        }
-
-        switch(pEid->Eid)
-        {
-            case IE_SSID:
-                // Already has one SSID EID in this beacon, ignore the second one
-                if (Sanity & 0x1)
-                    break;
-                if(pEid->Len <= MAX_LEN_OF_SSID)
-                {
-                    NdisMoveMemory(Ssid, pEid->Octet, pEid->Len);
-                    *pSsidLen = pEid->Len;
-                    Sanity |= 0x1;
-                }
-                else
-                {
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_SSID (len=%d)\n",pEid->Len));
-                    return FALSE;
-                }
-                break;
-
-            case IE_SUPP_RATES:
-                if(pEid->Len <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    Sanity |= 0x2;
-                    NdisMoveMemory(SupRate, pEid->Octet, pEid->Len);
-                    *pSupRateLen = pEid->Len;
-
-                    // TODO: 2004-09-14 not a good design here, cause it exclude extra rates
-                    // from ScanTab. We should report as is. And filter out unsupported
-                    // rates in MlmeAux.
-                    // Check against the supported rates
-                    // RTMPCheckRates(pAd, SupRate, pSupRateLen);
-                }
-                else
-                {
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_SUPP_RATES (len=%d)\n",pEid->Len));
-                    return FALSE;
-                }
-                break;
-
-            case IE_HT_CAP:
-			if (pEid->Len >= SIZE_HT_CAP_IE)  //Note: allow extension.!!
-			{
-				NdisMoveMemory(pHtCapability, pEid->Octet, sizeof(HT_CAPABILITY_IE));
-				*pHtCapabilityLen = SIZE_HT_CAP_IE;	// Nnow we only support 26 bytes.
-
-				*(USHORT *)(&pHtCapability->HtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->HtCapInfo));
-				*(USHORT *)(&pHtCapability->ExtHtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->ExtHtCapInfo));
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-					*pPreNHtCapabilityLen = 0;	// Nnow we only support 26 bytes.
-
-					Ptr = (PUCHAR) pVIE;
-					NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
-					*LengthVIE += (pEid->Len + 2);
-				}
-#endif // CONFIG_STA_SUPPORT //
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerBeaconAndProbeRspSanity - wrong IE_HT_CAP. pEid->Len = %d\n", pEid->Len));
-			}
-
-		break;
-            case IE_ADD_HT:
-			if (pEid->Len >= sizeof(ADD_HT_INFO_IE))
-			{
-				// This IE allows extension, but we can ignore extra bytes beyond our knowledge , so only
-				// copy first sizeof(ADD_HT_INFO_IE)
-				NdisMoveMemory(AddHtInfo, pEid->Octet, sizeof(ADD_HT_INFO_IE));
-				*AddHtInfoLen = SIZE_ADD_HT_INFO_IE;
-
-				CtrlChannel = AddHtInfo->ControlChan;
-
-				*(USHORT *)(&AddHtInfo->AddHtInfo2) = cpu2le16(*(USHORT *)(&AddHtInfo->AddHtInfo2));
-				*(USHORT *)(&AddHtInfo->AddHtInfo3) = cpu2le16(*(USHORT *)(&AddHtInfo->AddHtInfo3));
-
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-			                Ptr = (PUCHAR) pVIE;
-			                NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
-			                *LengthVIE += (pEid->Len + 2);
-				}
-#endif // CONFIG_STA_SUPPORT //
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerBeaconAndProbeRspSanity - wrong IE_ADD_HT. \n"));
-			}
-
-		break;
-            case IE_SECONDARY_CH_OFFSET:
-			if (pEid->Len == 1)
-			{
-				*NewExtChannelOffset = pEid->Octet[0];
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerBeaconAndProbeRspSanity - wrong IE_SECONDARY_CH_OFFSET. \n"));
-			}
-
-		break;
-            case IE_FH_PARM:
-                DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity(IE_FH_PARM) \n"));
-                break;
-
-            case IE_DS_PARM:
-                if(pEid->Len == 1)
-                {
-                    *pChannel = *pEid->Octet;
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-					{
-						if (ChannelSanity(pAd, *pChannel) == 0)
-						{
-
-							return FALSE;
-						}
-					}
-#endif // CONFIG_STA_SUPPORT //
-                    Sanity |= 0x4;
-                }
-                else
-                {
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_DS_PARM (len=%d)\n",pEid->Len));
-                    return FALSE;
-                }
-                break;
-
-            case IE_CF_PARM:
-                if(pEid->Len == 6)
-                {
-                    pCfParm->bValid = TRUE;
-                    pCfParm->CfpCount = pEid->Octet[0];
-                    pCfParm->CfpPeriod = pEid->Octet[1];
-                    pCfParm->CfpMaxDuration = pEid->Octet[2] + 256 * pEid->Octet[3];
-                    pCfParm->CfpDurRemaining = pEid->Octet[4] + 256 * pEid->Octet[5];
-                }
-                else
-                {
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_CF_PARM\n"));
-                    return FALSE;
-                }
-                break;
-
-            case IE_IBSS_PARM:
-                if(pEid->Len == 2)
-                {
-                    NdisMoveMemory(pAtimWin, pEid->Octet, pEid->Len);
-                }
-                else
-                {
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_IBSS_PARM\n"));
-                    return FALSE;
-                }
-                break;
-
-#ifdef CONFIG_STA_SUPPORT
-            case IE_TIM:
-                if(INFRA_ON(pAd) && SubType == SUBTYPE_BEACON)
-                {
-                    GetTimBit((PUCHAR)pEid, pAd->StaActive.Aid, &TimLen, pBcastFlag, pDtimCount, pDtimPeriod, pMessageToMe);
-                }
-                break;
-#endif // CONFIG_STA_SUPPORT //
-            case IE_CHANNEL_SWITCH_ANNOUNCEMENT:
-                if(pEid->Len == 3)
-                {
-                	*pNewChannel = pEid->Octet[1];	//extract new channel number
-                }
-                break;
-
-            // New for WPA
-            // CCX v2 has the same IE, we need to parse that too
-            // Wifi WMM use the same IE vale, need to parse that too
-            // case IE_WPA:
-            case IE_VENDOR_SPECIFIC:
-                // Check Broadcom/Atheros 802.11n OUI version, for HT Capability IE.
-                // This HT IE is before IEEE draft set HT IE value.2006-09-28 by Jan.
-                /*if (NdisEqualMemory(pEid->Octet, BROADCOM_OUI, 3) && (pEid->Len >= 4))
-                {
-                	if ((pEid->Octet[3] == OUI_BROADCOM_HT) && (pEid->Len >= 30))
-            		{
-				{
-					NdisMoveMemory(pHtCapability, &pEid->Octet[4], sizeof(HT_CAPABILITY_IE));
-					*pHtCapabilityLen = SIZE_HT_CAP_IE;	// Nnow we only support 26 bytes.
-				}
-         		}
-                	if ((pEid->Octet[3] == OUI_BROADCOM_HT) && (pEid->Len >= 26))
-            		{
-				{
-					NdisMoveMemory(AddHtInfo, &pEid->Octet[4], sizeof(ADD_HT_INFO_IE));
-					*AddHtInfoLen = SIZE_ADD_HT_INFO_IE;	// Nnow we only support 26 bytes.
-				}
-         		}
-                }
-				*/
-                // Check the OUI version, filter out non-standard usage
-                if (NdisEqualMemory(pEid->Octet, RALINK_OUI, 3) && (pEid->Len == 7))
-                {
-                    //*pRalinkIe = pEid->Octet[3];
-                    if (pEid->Octet[3] != 0)
-        				*pRalinkIe = pEid->Octet[3];
-        			else
-        				*pRalinkIe = 0xf0000000; // Set to non-zero value (can't set bit0-2) to represent this is Ralink Chip. So at linkup, we will set ralinkchip flag.
-                }
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
-		// This HT IE is before IEEE draft set HT IE value.2006-09-28 by Jan.
-
-                // Other vendors had production before IE_HT_CAP value is assigned. To backward support those old-firmware AP,
-                // Check broadcom-defiend pre-802.11nD1.0 OUI for HT related IE, including HT Capatilities IE and HT Information IE
-                else if ((*pHtCapabilityLen == 0) && NdisEqualMemory(pEid->Octet, PRE_N_HT_OUI, 3) && (pEid->Len >= 4) && (pAd->OpMode == OPMODE_STA))
-                {
-                    if ((pEid->Octet[3] == OUI_PREN_HT_CAP) && (pEid->Len >= 30) && (*pHtCapabilityLen == 0))
-                    {
-                        NdisMoveMemory(pHtCapability, &pEid->Octet[4], sizeof(HT_CAPABILITY_IE));
-                        *pPreNHtCapabilityLen = SIZE_HT_CAP_IE;
-                    }
-
-                    if ((pEid->Octet[3] == OUI_PREN_ADD_HT) && (pEid->Len >= 26))
-                    {
-                        NdisMoveMemory(AddHtInfo, &pEid->Octet[4], sizeof(ADD_HT_INFO_IE));
-                        *AddHtInfoLen = SIZE_ADD_HT_INFO_IE;
-                    }
-                }
-#endif // DOT11_N_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-                else if (NdisEqualMemory(pEid->Octet, WPA_OUI, 4))
-                {
-                    // Copy to pVIE which will report to microsoft bssid list.
-                    Ptr = (PUCHAR) pVIE;
-                    NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
-                    *LengthVIE += (pEid->Len + 2);
-                }
-                else if (NdisEqualMemory(pEid->Octet, WME_PARM_ELEM, 6) && (pEid->Len == 24))
-                {
-                    PUCHAR ptr;
-                    int i;
-
-                    // parsing EDCA parameters
-                    pEdcaParm->bValid          = TRUE;
-                    pEdcaParm->bQAck           = FALSE; // pEid->Octet[0] & 0x10;
-                    pEdcaParm->bQueueRequest   = FALSE; // pEid->Octet[0] & 0x20;
-                    pEdcaParm->bTxopRequest    = FALSE; // pEid->Octet[0] & 0x40;
-                    pEdcaParm->EdcaUpdateCount = pEid->Octet[6] & 0x0f;
-                    pEdcaParm->bAPSDCapable    = (pEid->Octet[6] & 0x80) ? 1 : 0;
-                    ptr = &pEid->Octet[8];
-                    for (i=0; i<4; i++)
-                    {
-                        UCHAR aci = (*ptr & 0x60) >> 5; // b5~6 is AC INDEX
-                        pEdcaParm->bACM[aci]  = (((*ptr) & 0x10) == 0x10);   // b5 is ACM
-                        pEdcaParm->Aifsn[aci] = (*ptr) & 0x0f;               // b0~3 is AIFSN
-                        pEdcaParm->Cwmin[aci] = *(ptr+1) & 0x0f;             // b0~4 is Cwmin
-                        pEdcaParm->Cwmax[aci] = *(ptr+1) >> 4;               // b5~8 is Cwmax
-                        pEdcaParm->Txop[aci]  = *(ptr+2) + 256 * (*(ptr+3)); // in unit of 32-us
-                        ptr += 4; // point to next AC
-                    }
-                }
-                else if (NdisEqualMemory(pEid->Octet, WME_INFO_ELEM, 6) && (pEid->Len == 7))
-                {
-                    // parsing EDCA parameters
-                    pEdcaParm->bValid          = TRUE;
-                    pEdcaParm->bQAck           = FALSE; // pEid->Octet[0] & 0x10;
-                    pEdcaParm->bQueueRequest   = FALSE; // pEid->Octet[0] & 0x20;
-                    pEdcaParm->bTxopRequest    = FALSE; // pEid->Octet[0] & 0x40;
-                    pEdcaParm->EdcaUpdateCount = pEid->Octet[6] & 0x0f;
-                    pEdcaParm->bAPSDCapable    = (pEid->Octet[6] & 0x80) ? 1 : 0;
-
-                    // use default EDCA parameter
-                    pEdcaParm->bACM[QID_AC_BE]  = 0;
-                    pEdcaParm->Aifsn[QID_AC_BE] = 3;
-                    pEdcaParm->Cwmin[QID_AC_BE] = CW_MIN_IN_BITS;
-                    pEdcaParm->Cwmax[QID_AC_BE] = CW_MAX_IN_BITS;
-                    pEdcaParm->Txop[QID_AC_BE]  = 0;
-
-                    pEdcaParm->bACM[QID_AC_BK]  = 0;
-                    pEdcaParm->Aifsn[QID_AC_BK] = 7;
-                    pEdcaParm->Cwmin[QID_AC_BK] = CW_MIN_IN_BITS;
-                    pEdcaParm->Cwmax[QID_AC_BK] = CW_MAX_IN_BITS;
-                    pEdcaParm->Txop[QID_AC_BK]  = 0;
-
-                    pEdcaParm->bACM[QID_AC_VI]  = 0;
-                    pEdcaParm->Aifsn[QID_AC_VI] = 2;
-                    pEdcaParm->Cwmin[QID_AC_VI] = CW_MIN_IN_BITS-1;
-                    pEdcaParm->Cwmax[QID_AC_VI] = CW_MAX_IN_BITS;
-                    pEdcaParm->Txop[QID_AC_VI]  = 96;   // AC_VI: 96*32us ~= 3ms
-
-                    pEdcaParm->bACM[QID_AC_VO]  = 0;
-                    pEdcaParm->Aifsn[QID_AC_VO] = 2;
-                    pEdcaParm->Cwmin[QID_AC_VO] = CW_MIN_IN_BITS-2;
-                    pEdcaParm->Cwmax[QID_AC_VO] = CW_MAX_IN_BITS-1;
-                    pEdcaParm->Txop[QID_AC_VO]  = 48;   // AC_VO: 48*32us ~= 1.5ms
-                }
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-                else
-                {
-                }
-
-                break;
-
-            case IE_EXT_SUPP_RATES:
-                if (pEid->Len <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    NdisMoveMemory(ExtRate, pEid->Octet, pEid->Len);
-                    *pExtRateLen = pEid->Len;
-
-                    // TODO: 2004-09-14 not a good design here, cause it exclude extra rates
-                    // from ScanTab. We should report as is. And filter out unsupported
-                    // rates in MlmeAux.
-                    // Check against the supported rates
-                    // RTMPCheckRates(pAd, ExtRate, pExtRateLen);
-                }
-                break;
-
-            case IE_ERP:
-                if (pEid->Len == 1)
-                {
-                    *pErp = (UCHAR)pEid->Octet[0];
-                }
-                break;
-
-            case IE_AIRONET_CKIP:
-                // 0. Check Aironet IE length, it must be larger or equal to 28
-                // Cisco AP350 used length as 28
-                // Cisco AP12XX used length as 30
-                if (pEid->Len < (CKIP_NEGOTIATION_LENGTH - 2))
-                    break;
-
-                // 1. Copy CKIP flag byte to buffer for process
-                *pCkipFlag = *(pEid->Octet + 8);
-                break;
-
-            case IE_AP_TX_POWER:
-                // AP Control of Client Transmit Power
-                //0. Check Aironet IE length, it must be 6
-                if (pEid->Len != 0x06)
-                    break;
-
-                // Get cell power limit in dBm
-                if (NdisEqualMemory(pEid->Octet, CISCO_OUI, 3) == 1)
-                    *pAironetCellPowerLimit = *(pEid->Octet + 4);
-                break;
-
-            // WPA2 & 802.11i RSN
-            case IE_RSN:
-                // There is no OUI for version anymore, check the group cipher OUI before copying
-                if (RTMPEqualMemory(pEid->Octet + 2, RSN_OUI, 3))
-                {
-                    // Copy to pVIE which will report to microsoft bssid list.
-                    Ptr = (PUCHAR) pVIE;
-                    NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
-                    *LengthVIE += (pEid->Len + 2);
-                }
-                break;
-#ifdef CONFIG_STA_SUPPORT
-#ifdef EXT_BUILD_CHANNEL_LIST
-			case IE_COUNTRY:
-				Ptr = (PUCHAR) pVIE;
-                NdisMoveMemory(Ptr + *LengthVIE, &pEid->Eid, pEid->Len + 2);
-                *LengthVIE += (pEid->Len + 2);
-				break;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
-            default:
-                break;
-        }
-
-        Length = Length + 2 + pEid->Len;  // Eid[1] + Len[1]+ content[Len]
-        pEid = (PEID_STRUCT)((UCHAR*)pEid + 2 + pEid->Len);
-    }
-
-    // For some 11a AP. it did not have the channel EID, patch here
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		UCHAR LatchRfChannel = MsgChannel;
-		if ((pAd->LatchRfRegs.Channel > 14) && ((Sanity & 0x4) == 0))
-		{
-			if (CtrlChannel != 0)
-				*pChannel = CtrlChannel;
-			else
-				*pChannel = LatchRfChannel;
-			Sanity |= 0x4;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	if (Sanity != 0x7)
-	{
-		DBGPRINT(RT_DEBUG_WARN, ("PeerBeaconAndProbeRspSanity - missing field, Sanity=0x%02x\n", Sanity));
-		return FALSE;
-	}
-	else
-	{
-		return TRUE;
-	}
-
-}
-
-#ifdef DOT11N_DRAFT3
-/*
-	==========================================================================
-	Description:
-		MLME message sanity check for some IE addressed  in 802.11n d3.03.
-	Return:
-		TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-BOOLEAN PeerBeaconAndProbeRspSanity2(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *Msg,
-	IN ULONG MsgLen,
-	OUT UCHAR 	*RegClass)
-{
-	CHAR				*Ptr;
-	PFRAME_802_11		pFrame;
-	PEID_STRUCT			pEid;
-	ULONG				Length = 0;
-
-	pFrame = (PFRAME_802_11)Msg;
-
-	*RegClass = 0;
-	Ptr = pFrame->Octet;
-	Length += LENGTH_802_11;
-
-	// get timestamp from payload and advance the pointer
-	Ptr += TIMESTAMP_LEN;
-	Length += TIMESTAMP_LEN;
-
-	// get beacon interval from payload and advance the pointer
-	Ptr += 2;
-	Length += 2;
-
-	// get capability info from payload and advance the pointer
-	Ptr += 2;
-	Length += 2;
-
-	pEid = (PEID_STRUCT) Ptr;
-
-	// get variable fields from payload and advance the pointer
-	while ((Length + 2 + pEid->Len) <= MsgLen)
-	{
-		switch(pEid->Eid)
-		{
-			case IE_SUPP_REG_CLASS:
-				if(pEid->Len > 0)
-				{
-					*RegClass = *pEid->Octet;
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAndProbeRspSanity - wrong IE_SSID (len=%d)\n",pEid->Len));
-					return FALSE;
-				}
-				break;
-		}
-
-		Length = Length + 2 + pEid->Len;  // Eid[1] + Len[1]+ content[Len]
-		pEid = (PEID_STRUCT)((UCHAR*)pEid + 2 + pEid->Len);
-	}
-
-	return TRUE;
-
-}
-#endif // DOT11N_DRAFT3 //
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
- */
-BOOLEAN MlmeScanReqSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *Msg,
-	IN ULONG MsgLen,
-	OUT UCHAR *pBssType,
-	OUT CHAR Ssid[],
-	OUT UCHAR *pSsidLen,
-	OUT UCHAR *pScanType)
-{
-	MLME_SCAN_REQ_STRUCT *Info;
-
-	Info = (MLME_SCAN_REQ_STRUCT *)(Msg);
-	*pBssType = Info->BssType;
-	*pSsidLen = Info->SsidLen;
-	NdisMoveMemory(Ssid, Info->Ssid, *pSsidLen);
-	*pScanType = Info->ScanType;
-
-	if ((*pBssType == BSS_INFRA || *pBssType == BSS_ADHOC || *pBssType == BSS_ANY)
-		&& (*pScanType == SCAN_ACTIVE || *pScanType == SCAN_PASSIVE
-#ifdef CONFIG_STA_SUPPORT
-		|| *pScanType == SCAN_CISCO_PASSIVE || *pScanType == SCAN_CISCO_ACTIVE
-		|| *pScanType == SCAN_CISCO_CHANNEL_LOAD || *pScanType == SCAN_CISCO_NOISE
-#endif // CONFIG_STA_SUPPORT //
-		))
-	{
-		return TRUE;
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("MlmeScanReqSanity fail - wrong BssType or ScanType\n"));
-		return FALSE;
-	}
-}
-
-// IRQL = DISPATCH_LEVEL
-UCHAR ChannelSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN UCHAR channel)
-{
-    int i;
-
-    for (i = 0; i < pAd->ChannelListNum; i ++)
-    {
-        if (channel == pAd->ChannelList[i].Channel)
-            return 1;
-    }
-    return 0;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerDeauthSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *pReason)
-{
-    PFRAME_802_11 pFrame = (PFRAME_802_11)Msg;
-
-    COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-    NdisMoveMemory(pReason, &pFrame->Octet[0], 2);
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerAuthSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr,
-    OUT USHORT *pAlg,
-    OUT USHORT *pSeq,
-    OUT USHORT *pStatus,
-    CHAR *pChlgText)
-{
-    PFRAME_802_11 pFrame = (PFRAME_802_11)Msg;
-
-    COPY_MAC_ADDR(pAddr,   pFrame->Hdr.Addr2);
-    NdisMoveMemory(pAlg,    &pFrame->Octet[0], 2);
-    NdisMoveMemory(pSeq,    &pFrame->Octet[2], 2);
-    NdisMoveMemory(pStatus, &pFrame->Octet[4], 2);
-
-    if ((*pAlg == Ndis802_11AuthModeOpen)
-#ifdef LEAP_SUPPORT
-      || (*pAlg == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
-      )
-    {
-        if (*pSeq == 1 || *pSeq == 2)
-        {
-            return TRUE;
-        }
-        else
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("PeerAuthSanity fail - wrong Seg#\n"));
-            return FALSE;
-        }
-    }
-    else if (*pAlg == Ndis802_11AuthModeShared)
-    {
-        if (*pSeq == 1 || *pSeq == 4)
-        {
-            return TRUE;
-        }
-        else if (*pSeq == 2 || *pSeq == 3)
-        {
-            NdisMoveMemory(pChlgText, &pFrame->Octet[8], CIPHER_TEXT_LEN);
-            return TRUE;
-        }
-        else
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("PeerAuthSanity fail - wrong Seg#\n"));
-            return FALSE;
-        }
-    }
-    else
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("PeerAuthSanity fail - wrong algorithm\n"));
-        return FALSE;
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
- */
-BOOLEAN MlmeAuthReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr,
-    OUT ULONG *pTimeout,
-    OUT USHORT *pAlg)
-{
-    MLME_AUTH_REQ_STRUCT *pInfo;
-
-    pInfo  = (MLME_AUTH_REQ_STRUCT *)Msg;
-    COPY_MAC_ADDR(pAddr, pInfo->Addr);
-    *pTimeout = pInfo->Timeout;
-    *pAlg = pInfo->Alg;
-
-    if (((*pAlg == Ndis802_11AuthModeShared) ||(*pAlg == Ndis802_11AuthModeOpen)
-#ifdef LEAP_SUPPORT
-     || (*pAlg == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
-     	) &&
-        ((*pAddr & 0x01) == 0))
-    {
-        return TRUE;
-    }
-    else
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeAuthReqSanity fail - wrong algorithm\n"));
-        return FALSE;
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN MlmeAssocReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pApAddr,
-    OUT USHORT *pCapabilityInfo,
-    OUT ULONG *pTimeout,
-    OUT USHORT *pListenIntv)
-{
-    MLME_ASSOC_REQ_STRUCT *pInfo;
-
-    pInfo = (MLME_ASSOC_REQ_STRUCT *)Msg;
-    *pTimeout = pInfo->Timeout;                             // timeout
-    COPY_MAC_ADDR(pApAddr, pInfo->Addr);                   // AP address
-    *pCapabilityInfo = pInfo->CapabilityInfo;               // capability info
-    *pListenIntv = pInfo->ListenIntv;
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerDisassocSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *pReason)
-{
-    PFRAME_802_11 pFrame = (PFRAME_802_11)Msg;
-
-    COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-    NdisMoveMemory(pReason, &pFrame->Octet[0], 2);
-
-    return TRUE;
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Sanity check NetworkType (11b, 11g or 11a)
-
-	Arguments:
-		pBss - Pointer to BSS table.
-
-	Return Value:
-        Ndis802_11DS .......(11b)
-        Ndis802_11OFDM24....(11g)
-        Ndis802_11OFDM5.....(11a)
-
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-NDIS_802_11_NETWORK_TYPE NetworkTypeInUseSanity(
-    IN PBSS_ENTRY pBss)
-{
-	NDIS_802_11_NETWORK_TYPE	NetWorkType;
-	UCHAR						rate, i;
-
-	NetWorkType = Ndis802_11DS;
-
-	if (pBss->Channel <= 14)
-	{
-		//
-		// First check support Rate.
-		//
-		for (i = 0; i < pBss->SupRateLen; i++)
-		{
-			rate = pBss->SupRate[i] & 0x7f; // Mask out basic rate set bit
-			if ((rate == 2) || (rate == 4) || (rate == 11) || (rate == 22))
-			{
-				continue;
-			}
-			else
-			{
-				//
-				// Otherwise (even rate > 108) means Ndis802_11OFDM24
-				//
-				NetWorkType = Ndis802_11OFDM24;
-				break;
-			}
-		}
-
-		//
-		// Second check Extend Rate.
-		//
-		if (NetWorkType != Ndis802_11OFDM24)
-		{
-			for (i = 0; i < pBss->ExtRateLen; i++)
-			{
-				rate = pBss->SupRate[i] & 0x7f; // Mask out basic rate set bit
-				if ((rate == 2) || (rate == 4) || (rate == 11) || (rate == 22))
-				{
-					continue;
-				}
-				else
-				{
-					//
-					// Otherwise (even rate > 108) means Ndis802_11OFDM24
-					//
-					NetWorkType = Ndis802_11OFDM24;
-					break;
-				}
-			}
-		}
-	}
-	else
-	{
-		NetWorkType = Ndis802_11OFDM5;
-	}
-
-    if (pBss->HtCapabilityLen != 0)
-    {
-        if (NetWorkType == Ndis802_11OFDM5)
-            NetWorkType = Ndis802_11OFDM5_N;
-        else
-            NetWorkType = Ndis802_11OFDM24_N;
-    }
-
-	return NetWorkType;
-}
-
-/*
-    ==========================================================================
-    Description:
-        WPA message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
- */
-BOOLEAN PeerWpaMessageSanity(
-    IN 	PRTMP_ADAPTER 		pAd,
-    IN 	PEAPOL_PACKET 		pMsg,
-    IN 	ULONG 				MsgLen,
-    IN 	UCHAR				MsgType,
-    IN 	MAC_TABLE_ENTRY  	*pEntry)
-{
-	UCHAR			mic[LEN_KEY_DESC_MIC], digest[80], KEYDATA[MAX_LEN_OF_RSNIE];
-	BOOLEAN			bReplayDiff = FALSE;
-	BOOLEAN			bWPA2 = FALSE;
-	KEY_INFO		EapolKeyInfo;
-	UCHAR			GroupKeyIndex = 0;
-
-
-	NdisZeroMemory(mic, sizeof(mic));
-	NdisZeroMemory(digest, sizeof(digest));
-	NdisZeroMemory(KEYDATA, sizeof(KEYDATA));
-	NdisZeroMemory((PUCHAR)&EapolKeyInfo, sizeof(EapolKeyInfo));
-
-	NdisMoveMemory((PUCHAR)&EapolKeyInfo, (PUCHAR)&pMsg->KeyDesc.KeyInfo, sizeof(KEY_INFO));
-
-	*((USHORT *)&EapolKeyInfo) = cpu2le16(*((USHORT *)&EapolKeyInfo));
-
-	// Choose WPA2 or not
-	if ((pEntry->AuthMode == Ndis802_11AuthModeWPA2) || (pEntry->AuthMode == Ndis802_11AuthModeWPA2PSK))
-		bWPA2 = TRUE;
-
-	// 0. Check MsgType
-	if ((MsgType > EAPOL_GROUP_MSG_2) || (MsgType < EAPOL_PAIR_MSG_1))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("The message type is invalid(%d)! \n", MsgType));
-		return FALSE;
-	}
-
-	// 1. Replay counter check
- 	if (MsgType == EAPOL_PAIR_MSG_1 || MsgType == EAPOL_PAIR_MSG_3 || MsgType == EAPOL_GROUP_MSG_1)	// For supplicant
-    {
-    	// First validate replay counter, only accept message with larger replay counter.
-		// Let equal pass, some AP start with all zero replay counter
-		UCHAR	ZeroReplay[LEN_KEY_DESC_REPLAY];
-
-        NdisZeroMemory(ZeroReplay, LEN_KEY_DESC_REPLAY);
-		if ((RTMPCompareMemory(pMsg->KeyDesc.ReplayCounter, pEntry->R_Counter, LEN_KEY_DESC_REPLAY) != 1) &&
-			(RTMPCompareMemory(pMsg->KeyDesc.ReplayCounter, ZeroReplay, LEN_KEY_DESC_REPLAY) != 0))
-    	{
-			bReplayDiff = TRUE;
-    	}
- 	}
-	else if (MsgType == EAPOL_PAIR_MSG_2 || MsgType == EAPOL_PAIR_MSG_4 || MsgType == EAPOL_GROUP_MSG_2)	// For authenticator
-	{
-		// check Replay Counter coresponds to MSG from authenticator, otherwise discard
-    	if (!NdisEqualMemory(pMsg->KeyDesc.ReplayCounter, pEntry->R_Counter, LEN_KEY_DESC_REPLAY))
-    	{
-			bReplayDiff = TRUE;
-    	}
-	}
-
-	// Replay Counter different condition
-	if (bReplayDiff)
-	{
-		// send wireless event - for replay counter different
-		if (pAd->CommonCfg.bWirelessEvent)
-			RTMPSendWirelessEvent(pAd, IW_REPLAY_COUNTER_DIFF_EVENT_FLAG, pEntry->Addr, pEntry->apidx, 0);
-
-		if (MsgType < EAPOL_GROUP_MSG_1)
-		{
-           	DBGPRINT(RT_DEBUG_ERROR, ("Replay Counter Different in pairwise msg %d of 4-way handshake!\n", MsgType));
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("Replay Counter Different in group msg %d of 2-way handshake!\n", (MsgType - EAPOL_PAIR_MSG_4)));
-		}
-
-		hex_dump("Receive replay counter ", pMsg->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-		hex_dump("Current replay counter ", pEntry->R_Counter, LEN_KEY_DESC_REPLAY);
-        return FALSE;
-	}
-
-	// 2. Verify MIC except Pairwise Msg1
-	if (MsgType != EAPOL_PAIR_MSG_1)
-	{
-		UCHAR			rcvd_mic[LEN_KEY_DESC_MIC];
-
-		// Record the received MIC for check later
-		NdisMoveMemory(rcvd_mic, pMsg->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-		NdisZeroMemory(pMsg->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-
-        if (pEntry->WepStatus == Ndis802_11Encryption2Enabled)	// TKIP
-        {
-            hmac_md5(pEntry->PTK, LEN_EAP_MICK, (PUCHAR)pMsg, MsgLen, mic);
-        }
-        else if (pEntry->WepStatus == Ndis802_11Encryption3Enabled)	// AES
-        {
-            HMAC_SHA1((PUCHAR)pMsg, MsgLen, pEntry->PTK, LEN_EAP_MICK, digest);
-            NdisMoveMemory(mic, digest, LEN_KEY_DESC_MIC);
-        }
-
-        if (!NdisEqualMemory(rcvd_mic, mic, LEN_KEY_DESC_MIC))
-        {
-			// send wireless event - for MIC different
-			if (pAd->CommonCfg.bWirelessEvent)
-				RTMPSendWirelessEvent(pAd, IW_MIC_DIFF_EVENT_FLAG, pEntry->Addr, pEntry->apidx, 0);
-
-			if (MsgType < EAPOL_GROUP_MSG_1)
-			{
-            	DBGPRINT(RT_DEBUG_ERROR, ("MIC Different in pairwise msg %d of 4-way handshake!\n", MsgType));
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("MIC Different in group msg %d of 2-way handshake!\n", (MsgType - EAPOL_PAIR_MSG_4)));
-			}
-
-			hex_dump("Received MIC", rcvd_mic, LEN_KEY_DESC_MIC);
-			hex_dump("Desired  MIC", mic, LEN_KEY_DESC_MIC);
-
-			return FALSE;
-        }
-	}
-
-	// Extract the context of the Key Data field if it exist
-	// The field in pairwise_msg_2_WPA1(WPA2) & pairwise_msg_3_WPA1 is un-encrypted.
-	// The field in group_msg_1_WPA1(WPA2) & pairwise_msg_3_WPA2 is encrypted.
-	if (pMsg->KeyDesc.KeyDataLen[1] > 0)
-	{
-		// Decrypt this field
-		if ((MsgType == EAPOL_PAIR_MSG_3 && bWPA2) || (MsgType == EAPOL_GROUP_MSG_1))
-		{
-			if(pEntry->WepStatus == Ndis802_11Encryption3Enabled)
-			{
-				// AES
-				AES_GTK_KEY_UNWRAP(&pEntry->PTK[16], KEYDATA, pMsg->KeyDesc.KeyDataLen[1],pMsg->KeyDesc.KeyData);
-			}
-			else
-			{
-				INT 	i;
-				UCHAR   Key[32];
-				// Decrypt TKIP GTK
-				// Construct 32 bytes RC4 Key
-				NdisMoveMemory(Key, pMsg->KeyDesc.KeyIv, 16);
-				NdisMoveMemory(&Key[16], &pEntry->PTK[16], 16);
-				ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, Key, 32);
-				//discard first 256 bytes
-				for(i = 0; i < 256; i++)
-					ARCFOUR_BYTE(&pAd->PrivateInfo.WEPCONTEXT);
-				// Decrypt GTK. Becareful, there is no ICV to check the result is correct or not
-				ARCFOUR_DECRYPT(&pAd->PrivateInfo.WEPCONTEXT, KEYDATA, pMsg->KeyDesc.KeyData, pMsg->KeyDesc.KeyDataLen[1]);
-			}
-
-			if (!bWPA2 && (MsgType == EAPOL_GROUP_MSG_1))
-				GroupKeyIndex = EapolKeyInfo.KeyIndex;
-
-		}
-		else if ((MsgType == EAPOL_PAIR_MSG_2) || (MsgType == EAPOL_PAIR_MSG_3 && !bWPA2))
-		{
-			NdisMoveMemory(KEYDATA, pMsg->KeyDesc.KeyData, pMsg->KeyDesc.KeyDataLen[1]);
-		}
-		else
-		{
-
-			return TRUE;
-		}
-
-		// Parse Key Data field to
-		// 1. verify RSN IE for pairwise_msg_2_WPA1(WPA2) ,pairwise_msg_3_WPA1(WPA2)
-		// 2. verify KDE format for pairwise_msg_3_WPA2, group_msg_1_WPA2
-		// 3. update shared key for pairwise_msg_3_WPA2, group_msg_1_WPA1(WPA2)
-		if (!RTMPParseEapolKeyData(pAd, KEYDATA, pMsg->KeyDesc.KeyDataLen[1], GroupKeyIndex, MsgType, bWPA2, pEntry))
-		{
-			return FALSE;
-		}
-	}
-
-	return TRUE;
-
-}
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-BOOLEAN MlmeDlsReqSanity(
-	IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PRT_802_11_DLS *pDLS,
-    OUT PUSHORT pReason)
-{
-	MLME_DLS_REQ_STRUCT *pInfo;
-
-    pInfo = (MLME_DLS_REQ_STRUCT *)Msg;
-
-	*pDLS = pInfo->pDLS;
-	*pReason = pInfo->Reason;
-
-	return TRUE;
-}
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef QOS_DLS_SUPPORT
-BOOLEAN PeerDlsReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pDlsTimeout,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-	OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability)
-{
-	CHAR            *Ptr;
-    PFRAME_802_11	Fr = (PFRAME_802_11)Msg;
-	PEID_STRUCT  eid_ptr;
-
-    // to prevent caller from using garbage output value
-    *pCapabilityInfo	= 0;
-    *pDlsTimeout	= 0;
-	*pHtCapabilityLen = 0;
-
-    Ptr = Fr->Octet;
-
-	// offset to destination MAC address (Category and Action field)
-    Ptr += 2;
-
-    // get DA from payload and advance the pointer
-    NdisMoveMemory(pDA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get SA from payload and advance the pointer
-    NdisMoveMemory(pSA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get capability info from payload and advance the pointer
-    NdisMoveMemory(pCapabilityInfo, Ptr, 2);
-    Ptr += 2;
-
-    // get capability info from payload and advance the pointer
-    NdisMoveMemory(pDlsTimeout, Ptr, 2);
-    Ptr += 2;
-
-	// Category and Action field + DA + SA + capability + Timeout
-	eid_ptr = (PEID_STRUCT) &Fr->Octet[18];
-
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((UCHAR*)Fr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_SUPP_RATES:
-                if ((eid_ptr->Len <= MAX_LEN_OF_SUPPORTED_RATES) && (eid_ptr->Len > 0))
-                {
-                    NdisMoveMemory(Rates, eid_ptr->Octet, eid_ptr->Len);
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - IE_SUPP_RATES., Len=%d. Rates[0]=%x\n",eid_ptr->Len, Rates[0]));
-                    DBGPRINT(RT_DEBUG_TRACE, ("Rates[1]=%x %x %x %x %x %x %x\n", Rates[1], Rates[2], Rates[3], Rates[4], Rates[5], Rates[6], Rates[7]));
-                    *pRatesLen = eid_ptr->Len;
-                }
-                else
-                {
-                    *pRatesLen = 8;
-					Rates[0] = 0x82;
-					Rates[1] = 0x84;
-					Rates[2] = 0x8b;
-					Rates[3] = 0x96;
-					Rates[4] = 0x12;
-					Rates[5] = 0x24;
-					Rates[6] = 0x48;
-					Rates[7] = 0x6c;
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - wrong IE_SUPP_RATES., Len=%d\n",eid_ptr->Len));
-                }
-				break;
-
-			case IE_EXT_SUPP_RATES:
-                if (eid_ptr->Len + *pRatesLen <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, eid_ptr->Len);
-                    *pRatesLen = (*pRatesLen) + eid_ptr->Len;
-                }
-                else
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, MAX_LEN_OF_SUPPORTED_RATES - (*pRatesLen));
-                    *pRatesLen = MAX_LEN_OF_SUPPORTED_RATES;
-                }
-				break;
-
-			case IE_HT_CAP:
-				if (eid_ptr->Len >= sizeof(HT_CAPABILITY_IE))
-				{
-					NdisMoveMemory(pHtCapability, eid_ptr->Octet, sizeof(HT_CAPABILITY_IE));
-
-					*(USHORT *)(&pHtCapability->HtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->HtCapInfo));
-					*(USHORT *)(&pHtCapability->ExtHtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->ExtHtCapInfo));
-					*pHtCapabilityLen = sizeof(HT_CAPABILITY_IE);
-
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - IE_HT_CAP\n"));
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsReqSanity - wrong IE_HT_CAP.eid_ptr->Len = %d\n", eid_ptr->Len));
-				}
-				break;
-
-			default:
-				break;
-		}
-
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-    return TRUE;
-}
-
-BOOLEAN PeerDlsRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pStatus,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-    OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability)
-{
-    CHAR            *Ptr;
-    PFRAME_802_11	Fr = (PFRAME_802_11)Msg;
-	PEID_STRUCT  eid_ptr;
-
-    // to prevent caller from using garbage output value
-    *pStatus		= 0;
-    *pCapabilityInfo	= 0;
-	*pHtCapabilityLen = 0;
-
-    Ptr = Fr->Octet;
-
-	// offset to destination MAC address (Category and Action field)
-    Ptr += 2;
-
-	// get status code from payload and advance the pointer
-    NdisMoveMemory(pStatus, Ptr, 2);
-    Ptr += 2;
-
-    // get DA from payload and advance the pointer
-    NdisMoveMemory(pDA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get SA from payload and advance the pointer
-    NdisMoveMemory(pSA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-	if (pStatus == 0)
-	{
-	    // get capability info from payload and advance the pointer
-	    NdisMoveMemory(pCapabilityInfo, Ptr, 2);
-	    Ptr += 2;
-	}
-
-	// Category and Action field + status code + DA + SA + capability
-	eid_ptr = (PEID_STRUCT) &Fr->Octet[18];
-
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((UCHAR*)Fr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_SUPP_RATES:
-                if ((eid_ptr->Len <= MAX_LEN_OF_SUPPORTED_RATES) && (eid_ptr->Len > 0))
-                {
-                    NdisMoveMemory(Rates, eid_ptr->Octet, eid_ptr->Len);
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - IE_SUPP_RATES., Len=%d. Rates[0]=%x\n",eid_ptr->Len, Rates[0]));
-                    DBGPRINT(RT_DEBUG_TRACE, ("Rates[1]=%x %x %x %x %x %x %x\n", Rates[1], Rates[2], Rates[3], Rates[4], Rates[5], Rates[6], Rates[7]));
-                    *pRatesLen = eid_ptr->Len;
-                }
-                else
-                {
-                    *pRatesLen = 8;
-					Rates[0] = 0x82;
-					Rates[1] = 0x84;
-					Rates[2] = 0x8b;
-					Rates[3] = 0x96;
-					Rates[4] = 0x12;
-					Rates[5] = 0x24;
-					Rates[6] = 0x48;
-					Rates[7] = 0x6c;
-                    DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - wrong IE_SUPP_RATES., Len=%d\n",eid_ptr->Len));
-                }
-				break;
-
-			case IE_EXT_SUPP_RATES:
-                if (eid_ptr->Len + *pRatesLen <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, eid_ptr->Len);
-                    *pRatesLen = (*pRatesLen) + eid_ptr->Len;
-                }
-                else
-                {
-                    NdisMoveMemory(&Rates[*pRatesLen], eid_ptr->Octet, MAX_LEN_OF_SUPPORTED_RATES - (*pRatesLen));
-                    *pRatesLen = MAX_LEN_OF_SUPPORTED_RATES;
-                }
-				break;
-
-			case IE_HT_CAP:
-				if (eid_ptr->Len >= sizeof(HT_CAPABILITY_IE))
-				{
-					NdisMoveMemory(pHtCapability, eid_ptr->Octet, sizeof(HT_CAPABILITY_IE));
-
-					*(USHORT *)(&pHtCapability->HtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->HtCapInfo));
-					*(USHORT *)(&pHtCapability->ExtHtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->ExtHtCapInfo));
-					*pHtCapabilityLen = sizeof(HT_CAPABILITY_IE);
-
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - IE_HT_CAP\n"));
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerDlsRspSanity - wrong IE_HT_CAP.eid_ptr->Len = %d\n", eid_ptr->Len));
-				}
-				break;
-
-			default:
-				break;
-		}
-
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-    return TRUE;
-}
-
-BOOLEAN PeerDlsTearDownSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pReason)
-{
-    CHAR            *Ptr;
-    PFRAME_802_11	Fr = (PFRAME_802_11)Msg;
-
-    // to prevent caller from using garbage output value
-    *pReason	= 0;
-
-    Ptr = Fr->Octet;
-
-	// offset to destination MAC address (Category and Action field)
-    Ptr += 2;
-
-    // get DA from payload and advance the pointer
-    NdisMoveMemory(pDA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-    // get SA from payload and advance the pointer
-    NdisMoveMemory(pSA, Ptr, MAC_ADDR_LEN);
-    Ptr += MAC_ADDR_LEN;
-
-	// get reason code from payload and advance the pointer
-    NdisMoveMemory(pReason, Ptr, 2);
-    Ptr += 2;
-
-    return TRUE;
-}
-#endif // QOS_DLS_SUPPORT //
-
+#include "../../rt2870/common/cmm_sanity.c"
diff --git a/drivers/staging/rt3070/common/cmm_sync.c b/drivers/staging/rt3070/common/cmm_sync.c
index 2be7c77..3b51742 100644
--- a/drivers/staging/rt3070/common/cmm_sync.c
+++ b/drivers/staging/rt3070/common/cmm_sync.c
@@ -1,711 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	sync.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang	2004-09-01      modified for rt2561/2661
-*/
-#include "../rt_config.h"
-
-// 2.4 Ghz channel plan index in the TxPower arrays.
-#define	BG_BAND_REGION_0_START	0			// 1,2,3,4,5,6,7,8,9,10,11
-#define	BG_BAND_REGION_0_SIZE	11
-#define	BG_BAND_REGION_1_START	0			// 1,2,3,4,5,6,7,8,9,10,11,12,13
-#define	BG_BAND_REGION_1_SIZE	13
-#define	BG_BAND_REGION_2_START	9			// 10,11
-#define	BG_BAND_REGION_2_SIZE	2
-#define	BG_BAND_REGION_3_START	9			// 10,11,12,13
-#define	BG_BAND_REGION_3_SIZE	4
-#define	BG_BAND_REGION_4_START	13			// 14
-#define	BG_BAND_REGION_4_SIZE	1
-#define	BG_BAND_REGION_5_START	0			// 1,2,3,4,5,6,7,8,9,10,11,12,13,14
-#define	BG_BAND_REGION_5_SIZE	14
-#define	BG_BAND_REGION_6_START	2			// 3,4,5,6,7,8,9
-#define	BG_BAND_REGION_6_SIZE	7
-#define	BG_BAND_REGION_7_START	4			// 5,6,7,8,9,10,11,12,13
-#define	BG_BAND_REGION_7_SIZE	9
-#define	BG_BAND_REGION_31_START	0			// 1,2,3,4,5,6,7,8,9,10,11,12,13,14
-#define	BG_BAND_REGION_31_SIZE	14
-
-// 5 Ghz channel plan index in the TxPower arrays.
-UCHAR A_BAND_REGION_0_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64, 149, 153, 157, 161, 165};
-UCHAR A_BAND_REGION_1_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140};
-UCHAR A_BAND_REGION_2_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64};
-UCHAR A_BAND_REGION_3_CHANNEL_LIST[]={52, 56, 60, 64, 149, 153, 157, 161};
-UCHAR A_BAND_REGION_4_CHANNEL_LIST[]={149, 153, 157, 161, 165};
-UCHAR A_BAND_REGION_5_CHANNEL_LIST[]={149, 153, 157, 161};
-UCHAR A_BAND_REGION_6_CHANNEL_LIST[]={36, 40, 44, 48};
-UCHAR A_BAND_REGION_7_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 149, 153, 157, 161, 165};
-UCHAR A_BAND_REGION_8_CHANNEL_LIST[]={52, 56, 60, 64};
-UCHAR A_BAND_REGION_9_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 132, 136, 140, 149, 153, 157, 161, 165};
-UCHAR A_BAND_REGION_10_CHANNEL_LIST[]={36, 40, 44, 48, 149, 153, 157, 161, 165};
-UCHAR A_BAND_REGION_11_CHANNEL_LIST[]={36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 149, 153, 157, 161};
-
-//BaSizeArray follows the 802.11n definition as MaxRxFactor.  2^(13+factor) bytes. When factor =0, it's about Ba buffer size =8.
-UCHAR BaSizeArray[4] = {8,16,32,64};
-
-/*
-	==========================================================================
-	Description:
-		Update StaCfg->ChannelList[] according to 1) Country Region 2) RF IC type,
-		and 3) PHY-mode user selected.
-		The outcome is used by driver when doing site survey.
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID BuildChannelList(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR i, j, index=0, num=0;
-	PUCHAR	pChannelList = NULL;
-
-	NdisZeroMemory(pAd->ChannelList, MAX_NUM_OF_CHANNELS * sizeof(CHANNEL_TX_POWER));
-
-	// if not 11a-only mode, channel list starts from 2.4Ghz band
-	if ((pAd->CommonCfg.PhyMode != PHY_11A)
-#ifdef DOT11_N_SUPPORT
-		&& (pAd->CommonCfg.PhyMode != PHY_11AN_MIXED) && (pAd->CommonCfg.PhyMode != PHY_11N_5G)
-#endif // DOT11_N_SUPPORT //
-	)
-	{
-		switch (pAd->CommonCfg.CountryRegion  & 0x7f)
-		{
-			case REGION_0_BG_BAND:	// 1 -11
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_0_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_0_SIZE);
-				index += BG_BAND_REGION_0_SIZE;
-				break;
-			case REGION_1_BG_BAND:	// 1 - 13
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_1_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_1_SIZE);
-				index += BG_BAND_REGION_1_SIZE;
-				break;
-			case REGION_2_BG_BAND:	// 10 - 11
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_2_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_2_SIZE);
-				index += BG_BAND_REGION_2_SIZE;
-				break;
-			case REGION_3_BG_BAND:	// 10 - 13
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_3_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_3_SIZE);
-				index += BG_BAND_REGION_3_SIZE;
-				break;
-			case REGION_4_BG_BAND:	// 14
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_4_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_4_SIZE);
-				index += BG_BAND_REGION_4_SIZE;
-				break;
-			case REGION_5_BG_BAND:	// 1 - 14
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_5_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_5_SIZE);
-				index += BG_BAND_REGION_5_SIZE;
-				break;
-			case REGION_6_BG_BAND:	// 3 - 9
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_6_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_6_SIZE);
-				index += BG_BAND_REGION_6_SIZE;
-				break;
-			case REGION_7_BG_BAND:  // 5 - 13
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_7_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_7_SIZE);
-				index += BG_BAND_REGION_7_SIZE;
-				break;
-			case REGION_31_BG_BAND:	// 1 - 14
-				NdisMoveMemory(&pAd->ChannelList[index], &pAd->TxPower[BG_BAND_REGION_31_START], sizeof(CHANNEL_TX_POWER) * BG_BAND_REGION_31_SIZE);
-				index += BG_BAND_REGION_31_SIZE;
-				break;
-			default:            // Error. should never happen
-				break;
-		}
-		for (i=0; i<index; i++)
-			pAd->ChannelList[i].MaxTxPwr = 20;
-	}
-
-	if ((pAd->CommonCfg.PhyMode == PHY_11A) || (pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED)
-#ifdef DOT11_N_SUPPORT
-		|| (pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED) || (pAd->CommonCfg.PhyMode == PHY_11AN_MIXED)
-		|| (pAd->CommonCfg.PhyMode == PHY_11AGN_MIXED) || (pAd->CommonCfg.PhyMode == PHY_11N_5G)
-#endif // DOT11_N_SUPPORT //
-	)
-	{
-		switch (pAd->CommonCfg.CountryRegionForABand & 0x7f)
-		{
-			case REGION_0_A_BAND:
-				num = sizeof(A_BAND_REGION_0_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_0_CHANNEL_LIST;
-				break;
-			case REGION_1_A_BAND:
-				num = sizeof(A_BAND_REGION_1_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_1_CHANNEL_LIST;
-				break;
-			case REGION_2_A_BAND:
-				num = sizeof(A_BAND_REGION_2_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_2_CHANNEL_LIST;
-				break;
-			case REGION_3_A_BAND:
-				num = sizeof(A_BAND_REGION_3_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_3_CHANNEL_LIST;
-				break;
-			case REGION_4_A_BAND:
-				num = sizeof(A_BAND_REGION_4_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_4_CHANNEL_LIST;
-				break;
-			case REGION_5_A_BAND:
-				num = sizeof(A_BAND_REGION_5_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_5_CHANNEL_LIST;
-				break;
-			case REGION_6_A_BAND:
-				num = sizeof(A_BAND_REGION_6_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_6_CHANNEL_LIST;
-				break;
-			case REGION_7_A_BAND:
-				num = sizeof(A_BAND_REGION_7_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_7_CHANNEL_LIST;
-				break;
-			case REGION_8_A_BAND:
-				num = sizeof(A_BAND_REGION_8_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_8_CHANNEL_LIST;
-				break;
-			case REGION_9_A_BAND:
-				num = sizeof(A_BAND_REGION_9_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_9_CHANNEL_LIST;
-				break;
-
-			case REGION_10_A_BAND:
-				num = sizeof(A_BAND_REGION_10_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_10_CHANNEL_LIST;
-				break;
-
-			case REGION_11_A_BAND:
-				num = sizeof(A_BAND_REGION_11_CHANNEL_LIST)/sizeof(UCHAR);
-				pChannelList = A_BAND_REGION_11_CHANNEL_LIST;
-				break;
-
-			default:            // Error. should never happen
-				DBGPRINT(RT_DEBUG_WARN,("countryregion=%d not support", pAd->CommonCfg.CountryRegionForABand));
-				break;
-		}
-
-		if (num != 0)
-		{
-			UCHAR RadarCh[15]={52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140};
-			for (i=0; i<num; i++)
-			{
-				for (j=0; j<MAX_NUM_OF_CHANNELS; j++)
-				{
-					if (pChannelList[i] == pAd->TxPower[j].Channel)
-						NdisMoveMemory(&pAd->ChannelList[index+i], &pAd->TxPower[j], sizeof(CHANNEL_TX_POWER));
-					}
-				for (j=0; j<15; j++)
-				{
-					if (pChannelList[i] == RadarCh[j])
-						pAd->ChannelList[index+i].DfsReq = TRUE;
-				}
-				pAd->ChannelList[index+i].MaxTxPwr = 20;
-			}
-			index += num;
-		}
-	}
-
-	pAd->ChannelListNum = index;
-	DBGPRINT(RT_DEBUG_TRACE,("country code=%d/%d, RFIC=%d, PHY mode=%d, support %d channels\n",
-		pAd->CommonCfg.CountryRegion, pAd->CommonCfg.CountryRegionForABand, pAd->RfIcType, pAd->CommonCfg.PhyMode, pAd->ChannelListNum));
-#ifdef DBG
-	for (i=0;i<pAd->ChannelListNum;i++)
-	{
-		DBGPRINT_RAW(RT_DEBUG_TRACE,("BuildChannel # %d :: Pwr0 = %d, Pwr1 =%d, \n ", pAd->ChannelList[i].Channel, pAd->ChannelList[i].Power, pAd->ChannelList[i].Power2));
-	}
-#endif
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine return the first channel number according to the country
-		code selection and RF IC selection (signal band or dual band). It is called
-		whenever driver need to start a site survey of all supported channels.
-	Return:
-		ch - the first channel number of current country code setting
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
- */
-UCHAR FirstChannel(
-	IN PRTMP_ADAPTER pAd)
-{
-	return pAd->ChannelList[0].Channel;
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine returns the next channel number. This routine is called
-		during driver need to start a site survey of all supported channels.
-	Return:
-		next_channel - the next channel number valid in current country code setting.
-	Note:
-		return 0 if no more next channel
-	==========================================================================
- */
-UCHAR NextChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR channel)
-{
-	int i;
-	UCHAR next_channel = 0;
-
-	for (i = 0; i < (pAd->ChannelListNum - 1); i++)
-		if (channel == pAd->ChannelList[i].Channel)
-		{
-			next_channel = pAd->ChannelList[i+1].Channel;
-			break;
-	}
-	return next_channel;
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine is for Cisco Compatible Extensions 2.X
-		Spec31. AP Control of Client Transmit Power
-	Return:
-		None
-	Note:
-	   Required by Aironet dBm(mW)
-		   0dBm(1mW),   1dBm(5mW), 13dBm(20mW), 15dBm(30mW),
-		  17dBm(50mw), 20dBm(100mW)
-
-	   We supported
-		   3dBm(Lowest), 6dBm(10%), 9dBm(25%), 12dBm(50%),
-		  14dBm(75%),   15dBm(100%)
-
-		The client station's actual transmit power shall be within +/- 5dB of
-		the minimum value or next lower value.
-	==========================================================================
- */
-VOID ChangeToCellPowerLimit(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR         AironetCellPowerLimit)
-{
-	//valud 0xFF means that hasn't found power limit information
-	//from the AP's Beacon/Probe response.
-	if (AironetCellPowerLimit == 0xFF)
-		return;
-
-	if (AironetCellPowerLimit < 6) //Used Lowest Power Percentage.
-		pAd->CommonCfg.TxPowerPercentage = 6;
-	else if (AironetCellPowerLimit < 9)
-		pAd->CommonCfg.TxPowerPercentage = 10;
-	else if (AironetCellPowerLimit < 12)
-		pAd->CommonCfg.TxPowerPercentage = 25;
-	else if (AironetCellPowerLimit < 14)
-		pAd->CommonCfg.TxPowerPercentage = 50;
-	else if (AironetCellPowerLimit < 15)
-		pAd->CommonCfg.TxPowerPercentage = 75;
-	else
-		pAd->CommonCfg.TxPowerPercentage = 100; //else used maximum
-
-	if (pAd->CommonCfg.TxPowerPercentage > pAd->CommonCfg.TxPowerDefault)
-		pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault;
-
-}
-
-CHAR	ConvertToRssi(
-	IN PRTMP_ADAPTER pAd,
-	IN	CHAR			Rssi,
-	IN  UCHAR   RssiNumber)
-{
-	UCHAR	RssiOffset, LNAGain;
-
-	// Rssi equals to zero should be an invalid value
-	if (Rssi == 0)
-		return -99;
-
-	LNAGain = GET_LNA_GAIN(pAd);
-    if (pAd->LatchRfRegs.Channel > 14)
-    {
-        if (RssiNumber == 0)
-			RssiOffset = pAd->ARssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->ARssiOffset1;
-		else
-			RssiOffset = pAd->ARssiOffset2;
-    }
-    else
-    {
-        if (RssiNumber == 0)
-			RssiOffset = pAd->BGRssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->BGRssiOffset1;
-		else
-			RssiOffset = pAd->BGRssiOffset2;
-    }
-
-    return (-12 - RssiOffset - LNAGain - Rssi);
-}
-
-/*
-	==========================================================================
-	Description:
-		Scan next channel
-	==========================================================================
- */
-VOID ScanNextChannel(
-	IN PRTMP_ADAPTER pAd)
-{
-	HEADER_802_11   Hdr80211;
-	PUCHAR          pOutBuffer = NULL;
-	NDIS_STATUS     NStatus;
-	ULONG           FrameLen = 0;
-	UCHAR           SsidLen = 0, ScanType = pAd->MlmeAux.ScanType, BBPValue = 0;
-#ifdef CONFIG_STA_SUPPORT
-	USHORT          Status;
-	PHEADER_802_11  pHdr80211;
-#endif // CONFIG_STA_SUPPORT //
-	UINT			ScanTimeIn5gChannel = SHORT_CHANNEL_TIME;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (MONITOR_ON(pAd))
-			return;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef RALINK_ATE
-	// Nothing to do in ATE mode.
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	if (pAd->MlmeAux.Channel == 0)
-	{
-		if ((pAd->CommonCfg.BBPCurrentBW == BW_40)
-#ifdef CONFIG_STA_SUPPORT
-			&& (INFRA_ON(pAd)
-				|| (pAd->OpMode == OPMODE_AP))
-#endif // CONFIG_STA_SUPPORT //
-			)
-		{
-			AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-			AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue &= (~0x18);
-			BBPValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-			DBGPRINT(RT_DEBUG_TRACE, ("SYNC - End of SCAN, restore to 40MHz channel %d, Total BSS[%02d]\n",pAd->CommonCfg.CentralChannel, pAd->ScanTab.BssNr));
-		}
-		else
-		{
-			AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-			AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-			DBGPRINT(RT_DEBUG_TRACE, ("SYNC - End of SCAN, restore to channel %d, Total BSS[%02d]\n",pAd->CommonCfg.Channel, pAd->ScanTab.BssNr));
-		}
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			//
-			// To prevent data lost.
-			// Send an NULL data with turned PSM bit on to current associated AP before SCAN progress.
-			// Now, we need to send an NULL data with turned PSM bit off to AP, when scan progress done
-			//
-			if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) && (INFRA_ON(pAd)))
-			{
-				NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);
-				if (NStatus	== NDIS_STATUS_SUCCESS)
-				{
-					pHdr80211 = (PHEADER_802_11) pOutBuffer;
-					MgtMacHeaderInit(pAd, pHdr80211, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-					pHdr80211->Duration = 0;
-					pHdr80211->FC.Type = BTYPE_DATA;
-					pHdr80211->FC.PwrMgmt = (pAd->StaCfg.Psm == PWR_SAVE);
-
-					// Send using priority queue
-					MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-					DBGPRINT(RT_DEBUG_TRACE, ("MlmeScanReqAction -- Send PSM Data frame\n"));
-					MlmeFreeMemory(pAd, pOutBuffer);
-					RTMPusecDelay(5000);
-				}
-			}
-
-			pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-			Status = MLME_SUCCESS;
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status);
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-
-		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-	}
-#ifdef RT2870
-#ifdef CONFIG_STA_SUPPORT
-	else if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST) && (pAd->OpMode == OPMODE_STA))
-	{
-		pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-		MlmeCntlConfirm(pAd, MT2_SCAN_CONF, MLME_FAIL_NO_RESOURCE);
-	}
-#endif // CONFIG_STA_SUPPORT //
-#endif // RT2870 //
-	else
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-		// BBP and RF are not accessible in PS mode, we has to wake them up first
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-			AsicForceWakeup(pAd, TRUE);
-
-			// leave PSM during scanning. otherwise we may lost ProbeRsp & BEACON
-			if (pAd->StaCfg.Psm == PWR_SAVE)
-				MlmeSetPsmBit(pAd, PWR_ACTIVE);
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		AsicSwitchChannel(pAd, pAd->MlmeAux.Channel, TRUE);
-		AsicLockChannel(pAd, pAd->MlmeAux.Channel);
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			if (pAd->MlmeAux.Channel > 14)
-			{
-				if ((pAd->CommonCfg.bIEEE80211H == 1) && RadarChannelCheck(pAd, pAd->MlmeAux.Channel))
-				{
-					ScanType = SCAN_PASSIVE;
-					ScanTimeIn5gChannel = MIN_CHANNEL_TIME;
-				}
-			}
-
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-			// carrier detection
-			if (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-			{
-				ScanType = SCAN_PASSIVE;
-				ScanTimeIn5gChannel = MIN_CHANNEL_TIME;
-			}
-#endif // CARRIER_DETECTION_SUPPORT //
-		}
-
-#endif // CONFIG_STA_SUPPORT //
-
-		//Global country domain(ch1-11:active scan, ch12-14 passive scan)
-		if ((pAd->MlmeAux.Channel <= 14) && (pAd->MlmeAux.Channel >= 12) && ((pAd->CommonCfg.CountryRegion & 0x7f) == REGION_31_BG_BAND))
-		{
-			ScanType = SCAN_PASSIVE;
-		}
-
-		// We need to shorten active scan time in order for WZC connect issue
-		// Chnage the channel scan time for CISCO stuff based on its IAPP announcement
-		if (ScanType == FAST_SCAN_ACTIVE)
-			RTMPSetTimer(&pAd->MlmeAux.ScanTimer, FAST_ACTIVE_SCAN_TIME);
-#ifdef CONFIG_STA_SUPPORT
-		else if (((ScanType == SCAN_CISCO_ACTIVE) ||
-				(ScanType == SCAN_CISCO_PASSIVE) ||
-				(ScanType == SCAN_CISCO_CHANNEL_LOAD) ||
-				(ScanType == SCAN_CISCO_NOISE)) && (pAd->OpMode == OPMODE_STA))
-		{
-			if (pAd->StaCfg.CCXScanTime < 25)
-				RTMPSetTimer(&pAd->MlmeAux.ScanTimer, pAd->StaCfg.CCXScanTime * 2);
-			else
-				RTMPSetTimer(&pAd->MlmeAux.ScanTimer, pAd->StaCfg.CCXScanTime);
-		}
-#endif // CONFIG_STA_SUPPORT //
-		else // must be SCAN_PASSIVE or SCAN_ACTIVE
-		{
-			if ((pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED)
-#ifdef DOT11_N_SUPPORT
-				|| (pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED) || (pAd->CommonCfg.PhyMode == PHY_11AGN_MIXED)
-#endif // DOT11_N_SUPPORT //
-			)
-			{
-				if (pAd->MlmeAux.Channel > 14)
-					RTMPSetTimer(&pAd->MlmeAux.ScanTimer, ScanTimeIn5gChannel);
-				else
-				RTMPSetTimer(&pAd->MlmeAux.ScanTimer, MIN_CHANNEL_TIME);
-			}
-			else
-				RTMPSetTimer(&pAd->MlmeAux.ScanTimer, MAX_CHANNEL_TIME);
-		}
-
-		if ((ScanType == SCAN_ACTIVE) || (ScanType == FAST_SCAN_ACTIVE) ||
-			(ScanType == SCAN_CISCO_ACTIVE))
-		{
-			NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-			if (NStatus != NDIS_STATUS_SUCCESS)
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("SYNC - ScanNextChannel() allocate memory fail\n"));
-#ifdef CONFIG_STA_SUPPORT
-				IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				{
-					pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-					Status = MLME_FAIL_NO_RESOURCE;
-					MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status);
-				}
-#endif // CONFIG_STA_SUPPORT //
-
-				return;
-			}
-
-			// There is no need to send broadcast probe request if active scan is in effect.
-			if ((ScanType == SCAN_ACTIVE) || (ScanType == FAST_SCAN_ACTIVE)
-				)
-				SsidLen = pAd->MlmeAux.SsidLen;
-			else
-				SsidLen = 0;
-
-			MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, BROADCAST_ADDR, BROADCAST_ADDR);
-			MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-							  sizeof(HEADER_802_11),    &Hdr80211,
-							  1,                        &SsidIe,
-							  1,                        &SsidLen,
-							  SsidLen,			        pAd->MlmeAux.Ssid,
-							  1,                        &SupRateIe,
-							  1,                        &pAd->CommonCfg.SupRateLen,
-							  pAd->CommonCfg.SupRateLen,  pAd->CommonCfg.SupRate,
-							  END_OF_ARGS);
-
-			if (pAd->CommonCfg.ExtRateLen)
-			{
-				ULONG Tmp;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &Tmp,
-								  1,                                &ExtRateIe,
-								  1,                                &pAd->CommonCfg.ExtRateLen,
-								  pAd->CommonCfg.ExtRateLen,          pAd->CommonCfg.ExtRate,
-								  END_OF_ARGS);
-				FrameLen += Tmp;
-			}
-
-#ifdef DOT11_N_SUPPORT
-			if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-			{
-				ULONG	Tmp;
-				UCHAR	HtLen;
-				UCHAR	BROADCOM[4] = {0x0, 0x90, 0x4c, 0x33};
-#ifdef RT_BIG_ENDIAN
-				HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
-				if (pAd->bBroadComHT == TRUE)
-				{
-					HtLen = pAd->MlmeAux.HtCapabilityLen + 4;
-#ifdef RT_BIG_ENDIAN
-					NdisMoveMemory(&HtCapabilityTmp, &pAd->MlmeAux.HtCapability, SIZE_HT_CAP_IE);
-					*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-					*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
-									1,                                &WpaIe,
-									1,                                &HtLen,
-									4,                                &BROADCOM[0],
-									pAd->MlmeAux.HtCapabilityLen,     &HtCapabilityTmp,
-									END_OF_ARGS);
-#else
-					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
-									1,                                &WpaIe,
-									1,                                &HtLen,
-									4,                                &BROADCOM[0],
-									pAd->MlmeAux.HtCapabilityLen,     &pAd->MlmeAux.HtCapability,
-									END_OF_ARGS);
-#endif // RT_BIG_ENDIAN //
-				}
-				else
-				{
-					HtLen = pAd->MlmeAux.HtCapabilityLen;
-#ifdef RT_BIG_ENDIAN
-					NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, SIZE_HT_CAP_IE);
-					*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-					*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
-									1,                                &HtCapIe,
-									1,                                &HtLen,
-									HtLen,                            &HtCapabilityTmp,
-									END_OF_ARGS);
-#else
-					MakeOutgoingFrame(pOutBuffer + FrameLen,          &Tmp,
-									1,                                &HtCapIe,
-									1,                                &HtLen,
-									HtLen,                            &pAd->CommonCfg.HtCapability,
-									END_OF_ARGS);
-#endif // RT_BIG_ENDIAN //
-				}
-				FrameLen += Tmp;
-
-#ifdef DOT11N_DRAFT3
-				if (pAd->CommonCfg.BACapability.field.b2040CoexistScanSup == 1)
-				{
-					ULONG		Tmp;
-					HtLen = 1;
-					MakeOutgoingFrame(pOutBuffer + FrameLen,            &Tmp,
-									  1,					&ExtHtCapIe,
-									  1,					&HtLen,
-									  1,          			&pAd->CommonCfg.BSSCoexist2040.word,
-									  END_OF_ARGS);
-
-					FrameLen += Tmp;
-				}
-#endif // DOT11N_DRAFT3 //
-			}
-#endif // DOT11_N_SUPPORT //
-
-
-			MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-			MlmeFreeMemory(pAd, pOutBuffer);
-		}
-
-		// For SCAN_CISCO_PASSIVE, do nothing and silently wait for beacon or other probe reponse
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			pAd->Mlme.SyncMachine.CurrState = SCAN_LISTEN;
-#endif // CONFIG_STA_SUPPORT //
-
-	}
-}
-
-VOID MgtProbReqMacHeaderInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN OUT PHEADER_802_11 pHdr80211,
-	IN UCHAR SubType,
-	IN UCHAR ToDs,
-	IN PUCHAR pDA,
-	IN PUCHAR pBssid)
-{
-	NdisZeroMemory(pHdr80211, sizeof(HEADER_802_11));
-
-	pHdr80211->FC.Type = BTYPE_MGMT;
-	pHdr80211->FC.SubType = SubType;
-	if (SubType == SUBTYPE_ACK)
-		pHdr80211->FC.Type = BTYPE_CNTL;
-	pHdr80211->FC.ToDs = ToDs;
-	COPY_MAC_ADDR(pHdr80211->Addr1, pDA);
-	COPY_MAC_ADDR(pHdr80211->Addr2, pAd->CurrentAddress);
-	COPY_MAC_ADDR(pHdr80211->Addr3, pBssid);
-}
-
-
+#include "../../rt2870/common/cmm_sync.c"
diff --git a/drivers/staging/rt3070/common/cmm_wpa.c b/drivers/staging/rt3070/common/cmm_wpa.c
index 81c332a..6483d32 100644
--- a/drivers/staging/rt3070/common/cmm_wpa.c
+++ b/drivers/staging/rt3070/common/cmm_wpa.c
@@ -1,1606 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	wpa.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Jan	Lee		03-07-22		Initial
-	Paul Lin	03-11-28		Modify for supplicant
-*/
-#include "../rt_config.h"
-// WPA OUI
-UCHAR		OUI_WPA_NONE_AKM[4]		= {0x00, 0x50, 0xF2, 0x00};
-UCHAR       OUI_WPA_VERSION[4]      = {0x00, 0x50, 0xF2, 0x01};
-UCHAR       OUI_WPA_TKIP[4]     = {0x00, 0x50, 0xF2, 0x02};
-UCHAR       OUI_WPA_CCMP[4]     = {0x00, 0x50, 0xF2, 0x04};
-UCHAR       OUI_WPA_8021X_AKM[4]	= {0x00, 0x50, 0xF2, 0x01};
-UCHAR       OUI_WPA_PSK_AKM[4]      = {0x00, 0x50, 0xF2, 0x02};
-// WPA2 OUI
-UCHAR       OUI_WPA2_WEP40[4]   = {0x00, 0x0F, 0xAC, 0x01};
-UCHAR       OUI_WPA2_TKIP[4]        = {0x00, 0x0F, 0xAC, 0x02};
-UCHAR       OUI_WPA2_CCMP[4]        = {0x00, 0x0F, 0xAC, 0x04};
-UCHAR       OUI_WPA2_8021X_AKM[4]   = {0x00, 0x0F, 0xAC, 0x01};
-UCHAR       OUI_WPA2_PSK_AKM[4]   	= {0x00, 0x0F, 0xAC, 0x02};
-// MSA OUI
-UCHAR   	OUI_MSA_8021X_AKM[4]    = {0x00, 0x0F, 0xAC, 0x05};		// Not yet final - IEEE 802.11s-D1.06
-UCHAR   	OUI_MSA_PSK_AKM[4]   	= {0x00, 0x0F, 0xAC, 0x06};		// Not yet final - IEEE 802.11s-D1.06
-
-/*
-	========================================================================
-
-	Routine Description:
-		The pseudo-random function(PRF) that hashes various inputs to
-		derive a pseudo-random value. To add liveness to the pseudo-random
-		value, a nonce should be one of the inputs.
-
-		It is used to generate PTK, GTK or some specific random value.
-
-	Arguments:
-		UCHAR	*key,		-	the key material for HMAC_SHA1 use
-		INT		key_len		-	the length of key
-		UCHAR	*prefix		-	a prefix label
-		INT		prefix_len	-	the length of the label
-		UCHAR	*data		-	a specific data with variable length
-		INT		data_len	-	the length of a specific data
-		INT		len			-	the output lenght
-
-	Return Value:
-		UCHAR	*output		-	the calculated result
-
-	Note:
-		802.11i-2004	Annex H.3
-
-	========================================================================
-*/
-VOID	PRF(
-	IN	UCHAR	*key,
-	IN	INT		key_len,
-	IN	UCHAR	*prefix,
-	IN	INT		prefix_len,
-	IN	UCHAR	*data,
-	IN	INT		data_len,
-	OUT	UCHAR	*output,
-	IN	INT		len)
-{
-	INT		i;
-    UCHAR   *input;
-	INT		currentindex = 0;
-	INT		total_len;
-
-	// Allocate memory for input
-	os_alloc_mem(NULL, (PUCHAR *)&input, 1024);
-
-    if (input == NULL)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("!!!PRF: no memory!!!\n"));
-        return;
-    }
-
-	// Generate concatenation input
-	NdisMoveMemory(input, prefix, prefix_len);
-
-	// Concatenate a single octet containing 0
-	input[prefix_len] =	0;
-
-	// Concatenate specific data
-	NdisMoveMemory(&input[prefix_len + 1], data, data_len);
-	total_len =	prefix_len + 1 + data_len;
-
-	// Concatenate a single octet containing 0
-	// This octet shall be update later
-	input[total_len] = 0;
-	total_len++;
-
-	// Iterate to calculate the result by hmac-sha-1
-	// Then concatenate to last result
-	for	(i = 0;	i <	(len + 19) / 20; i++)
-	{
-		HMAC_SHA1(input, total_len,	key, key_len, &output[currentindex]);
-		currentindex +=	20;
-
-		// update the last octet
-		input[total_len - 1]++;
-	}
-    os_free_mem(NULL, input);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		It utilizes PRF-384 or PRF-512 to derive session-specific keys from a PMK.
-		It shall be called by 4-way handshake processing.
-
-	Arguments:
-		pAd 	-	pointer to our pAdapter context
-		PMK		-	pointer to PMK
-		ANonce	-	pointer to ANonce
-		AA		-	pointer to Authenticator Address
-		SNonce	-	pointer to SNonce
-		SA		-	pointer to Supplicant Address
-		len		-	indicate the length of PTK (octet)
-
-	Return Value:
-		Output		pointer to the PTK
-
-	Note:
-		Refer to IEEE 802.11i-2004 8.5.1.2
-
-	========================================================================
-*/
-VOID WpaCountPTK(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR	*PMK,
-	IN	UCHAR	*ANonce,
-	IN	UCHAR	*AA,
-	IN	UCHAR	*SNonce,
-	IN	UCHAR	*SA,
-	OUT	UCHAR	*output,
-	IN	UINT	len)
-{
-	UCHAR	concatenation[76];
-	UINT	CurrPos = 0;
-	UCHAR	temp[32];
-	UCHAR	Prefix[] = {'P', 'a', 'i', 'r', 'w', 'i', 's', 'e', ' ', 'k', 'e', 'y', ' ',
-						'e', 'x', 'p', 'a', 'n', 's', 'i', 'o', 'n'};
-
-	// initiate the concatenation input
-	NdisZeroMemory(temp, sizeof(temp));
-	NdisZeroMemory(concatenation, 76);
-
-	// Get smaller address
-	if (RTMPCompareMemory(SA, AA, 6) == 1)
-		NdisMoveMemory(concatenation, AA, 6);
-	else
-		NdisMoveMemory(concatenation, SA, 6);
-	CurrPos += 6;
-
-	// Get larger address
-	if (RTMPCompareMemory(SA, AA, 6) == 1)
-		NdisMoveMemory(&concatenation[CurrPos], SA, 6);
-	else
-		NdisMoveMemory(&concatenation[CurrPos], AA, 6);
-
-	// store the larger mac address for backward compatible of
-	// ralink proprietary STA-key issue
-	NdisMoveMemory(temp, &concatenation[CurrPos], MAC_ADDR_LEN);
-	CurrPos += 6;
-
-	// Get smaller Nonce
-	if (RTMPCompareMemory(ANonce, SNonce, 32) == 0)
-		NdisMoveMemory(&concatenation[CurrPos], temp, 32);	// patch for ralink proprietary STA-key issue
-	else if (RTMPCompareMemory(ANonce, SNonce, 32) == 1)
-		NdisMoveMemory(&concatenation[CurrPos], SNonce, 32);
-	else
-		NdisMoveMemory(&concatenation[CurrPos], ANonce, 32);
-	CurrPos += 32;
-
-	// Get larger Nonce
-	if (RTMPCompareMemory(ANonce, SNonce, 32) == 0)
-		NdisMoveMemory(&concatenation[CurrPos], temp, 32);	// patch for ralink proprietary STA-key issue
-	else if (RTMPCompareMemory(ANonce, SNonce, 32) == 1)
-		NdisMoveMemory(&concatenation[CurrPos], ANonce, 32);
-	else
-		NdisMoveMemory(&concatenation[CurrPos], SNonce, 32);
-	CurrPos += 32;
-
-	hex_dump("concatenation=", concatenation, 76);
-
-	// Use PRF to generate PTK
-	PRF(PMK, LEN_MASTER_KEY, Prefix, 22, concatenation, 76, output, len);
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Generate random number by software.
-
-	Arguments:
-		pAd		-	pointer to our pAdapter context
-		macAddr	-	pointer to local MAC address
-
-	Return Value:
-
-	Note:
-		802.1ii-2004  Annex H.5
-
-	========================================================================
-*/
-VOID	GenRandom(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			*macAddr,
-	OUT	UCHAR			*random)
-{
-	INT		i, curr;
-	UCHAR	local[80], KeyCounter[32];
-	UCHAR	result[80];
-	ULONG	CurrentTime;
-	UCHAR	prefix[] = {'I', 'n', 'i', 't', ' ', 'C', 'o', 'u', 'n', 't', 'e', 'r'};
-
-	// Zero the related information
-	NdisZeroMemory(result, 80);
-	NdisZeroMemory(local, 80);
-	NdisZeroMemory(KeyCounter, 32);
-
-	for	(i = 0;	i <	32;	i++)
-	{
-		// copy the local MAC address
-		COPY_MAC_ADDR(local, macAddr);
-		curr =	MAC_ADDR_LEN;
-
-		// concatenate the current time
-		NdisGetSystemUpTime(&CurrentTime);
-		NdisMoveMemory(&local[curr],  &CurrentTime,	sizeof(CurrentTime));
-		curr +=	sizeof(CurrentTime);
-
-		// concatenate the last result
-		NdisMoveMemory(&local[curr],  result, 32);
-		curr +=	32;
-
-		// concatenate a variable
-		NdisMoveMemory(&local[curr],  &i,  2);
-		curr +=	2;
-
-		// calculate the result
-		PRF(KeyCounter, 32, prefix,12, local, curr, result, 32);
-	}
-
-	NdisMoveMemory(random, result,	32);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Build cipher suite in RSN-IE.
-		It only shall be called by RTMPMakeRSNIE.
-
-	Arguments:
-		pAd			-	pointer to our pAdapter context
-    	ElementID	-	indicate the WPA1 or WPA2
-    	WepStatus	-	indicate the encryption type
-		bMixCipher	-	a boolean to indicate the pairwise cipher and group
-						cipher are the same or not
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-static VOID RTMPInsertRsnIeCipher(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			ElementID,
-	IN	UINT			WepStatus,
-	IN	BOOLEAN			bMixCipher,
-	IN	UCHAR			FlexibleCipher,
-	OUT	PUCHAR			pRsnIe,
-	OUT	UCHAR			*rsn_len)
-{
-	UCHAR	PairwiseCnt;
-
-	*rsn_len = 0;
-
-	// decide WPA2 or WPA1
-	if (ElementID == Wpa2Ie)
-	{
-		RSNIE2	*pRsnie_cipher = (RSNIE2*)pRsnIe;
-
-		// Assign the verson as 1
-		pRsnie_cipher->version = 1;
-
-        switch (WepStatus)
-        {
-        	// TKIP mode
-            case Ndis802_11Encryption2Enabled:
-                NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_TKIP, 4);
-                pRsnie_cipher->ucount = 1;
-                NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_TKIP, 4);
-                *rsn_len = sizeof(RSNIE2);
-                break;
-
-			// AES mode
-            case Ndis802_11Encryption3Enabled:
-				if (bMixCipher)
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_TKIP, 4);
-				else
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_CCMP, 4);
-                pRsnie_cipher->ucount = 1;
-                NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_CCMP, 4);
-                *rsn_len = sizeof(RSNIE2);
-                break;
-
-			// TKIP-AES mix mode
-            case Ndis802_11Encryption4Enabled:
-                NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA2_TKIP, 4);
-
-				PairwiseCnt = 1;
-				// Insert WPA2 TKIP as the first pairwise cipher
-				if (MIX_CIPHER_WPA2_TKIP_ON(FlexibleCipher))
-				{
-                	NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_TKIP, 4);
-					// Insert WPA2 AES as the secondary pairwise cipher
-					if (MIX_CIPHER_WPA2_AES_ON(FlexibleCipher))
-					{
-                		NdisMoveMemory(pRsnie_cipher->ucast[0].oui + 4, OUI_WPA2_CCMP, 4);
-						PairwiseCnt = 2;
-					}
-				}
-				else
-				{
-					// Insert WPA2 AES as the first pairwise cipher
-					NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA2_CCMP, 4);
-				}
-
-                pRsnie_cipher->ucount = PairwiseCnt;
-                *rsn_len = sizeof(RSNIE2) + (4 * (PairwiseCnt - 1));
-                break;
-        }
-
-		// swap for big-endian platform
-		pRsnie_cipher->version = cpu2le16(pRsnie_cipher->version);
-	    pRsnie_cipher->ucount = cpu2le16(pRsnie_cipher->ucount);
-	}
-	else
-	{
-		RSNIE	*pRsnie_cipher = (RSNIE*)pRsnIe;
-
-		// Assign OUI and version
-		NdisMoveMemory(pRsnie_cipher->oui, OUI_WPA_VERSION, 4);
-        pRsnie_cipher->version = 1;
-
-		switch (WepStatus)
-		{
-			// TKIP mode
-            case Ndis802_11Encryption2Enabled:
-                NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_TKIP, 4);
-                pRsnie_cipher->ucount = 1;
-                NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_TKIP, 4);
-                *rsn_len = sizeof(RSNIE);
-                break;
-
-			// AES mode
-            case Ndis802_11Encryption3Enabled:
-				if (bMixCipher)
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_TKIP, 4);
-				else
-					NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_CCMP, 4);
-                pRsnie_cipher->ucount = 1;
-                NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_CCMP, 4);
-                *rsn_len = sizeof(RSNIE);
-                break;
-
-			// TKIP-AES mix mode
-            case Ndis802_11Encryption4Enabled:
-                NdisMoveMemory(pRsnie_cipher->mcast, OUI_WPA_TKIP, 4);
-
-				PairwiseCnt = 1;
-				// Insert WPA TKIP as the first pairwise cipher
-				if (MIX_CIPHER_WPA_TKIP_ON(FlexibleCipher))
-				{
-                	NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_TKIP, 4);
-					// Insert WPA AES as the secondary pairwise cipher
-					if (MIX_CIPHER_WPA_AES_ON(FlexibleCipher))
-					{
-                		NdisMoveMemory(pRsnie_cipher->ucast[0].oui + 4, OUI_WPA_CCMP, 4);
-						PairwiseCnt = 2;
-					}
-				}
-				else
-				{
-					// Insert WPA AES as the first pairwise cipher
-					NdisMoveMemory(pRsnie_cipher->ucast[0].oui, OUI_WPA_CCMP, 4);
-				}
-
-                pRsnie_cipher->ucount = PairwiseCnt;
-                *rsn_len = sizeof(RSNIE) + (4 * (PairwiseCnt - 1));
-                break;
-        }
-
-		// swap for big-endian platform
-		pRsnie_cipher->version = cpu2le16(pRsnie_cipher->version);
-	    pRsnie_cipher->ucount = cpu2le16(pRsnie_cipher->ucount);
-	}
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Build AKM suite in RSN-IE.
-		It only shall be called by RTMPMakeRSNIE.
-
-	Arguments:
-		pAd			-	pointer to our pAdapter context
-    	ElementID	-	indicate the WPA1 or WPA2
-    	AuthMode	-	indicate the authentication mode
-		apidx		-	indicate the interface index
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-static VOID RTMPInsertRsnIeAKM(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			ElementID,
-	IN	UINT			AuthMode,
-	IN	UCHAR			apidx,
-	OUT	PUCHAR			pRsnIe,
-	OUT	UCHAR			*rsn_len)
-{
-	RSNIE_AUTH		*pRsnie_auth;
-
-	pRsnie_auth = (RSNIE_AUTH*)(pRsnIe + (*rsn_len));
-
-	// decide WPA2 or WPA1
-	if (ElementID == Wpa2Ie)
-	{
-		switch (AuthMode)
-        {
-            case Ndis802_11AuthModeWPA2:
-            case Ndis802_11AuthModeWPA1WPA2:
-                pRsnie_auth->acount = 1;
-                	NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA2_8021X_AKM, 4);
-                break;
-
-            case Ndis802_11AuthModeWPA2PSK:
-            case Ndis802_11AuthModeWPA1PSKWPA2PSK:
-                pRsnie_auth->acount = 1;
-                	NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA2_PSK_AKM, 4);
-                break;
-        }
-	}
-	else
-	{
-		switch (AuthMode)
-        {
-            case Ndis802_11AuthModeWPA:
-            case Ndis802_11AuthModeWPA1WPA2:
-                pRsnie_auth->acount = 1;
-                NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA_8021X_AKM, 4);
-                break;
-
-            case Ndis802_11AuthModeWPAPSK:
-            case Ndis802_11AuthModeWPA1PSKWPA2PSK:
-                pRsnie_auth->acount = 1;
-                NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA_PSK_AKM, 4);
-                break;
-
-			case Ndis802_11AuthModeWPANone:
-                pRsnie_auth->acount = 1;
-                NdisMoveMemory(pRsnie_auth->auth[0].oui, OUI_WPA_NONE_AKM, 4);
-                break;
-        }
-	}
-
-	pRsnie_auth->acount = cpu2le16(pRsnie_auth->acount);
-
-	(*rsn_len) += sizeof(RSNIE_AUTH);	// update current RSNIE length
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Build capability in RSN-IE.
-		It only shall be called by RTMPMakeRSNIE.
-
-	Arguments:
-		pAd			-	pointer to our pAdapter context
-    	ElementID	-	indicate the WPA1 or WPA2
-		apidx		-	indicate the interface index
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-static VOID RTMPInsertRsnIeCap(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			ElementID,
-	IN	UCHAR			apidx,
-	OUT	PUCHAR			pRsnIe,
-	OUT	UCHAR			*rsn_len)
-{
-	RSN_CAPABILITIES    *pRSN_Cap;
-
-	// it could be ignored in WPA1 mode
-	if (ElementID == WpaIe)
-		return;
-
-	pRSN_Cap = (RSN_CAPABILITIES*)(pRsnIe + (*rsn_len));
-
-
-	pRSN_Cap->word = cpu2le16(pRSN_Cap->word);
-
-	(*rsn_len) += sizeof(RSN_CAPABILITIES);	// update current RSNIE length
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Build RSN IE context. It is not included element-ID and length.
-
-	Arguments:
-		pAd			-	pointer to our pAdapter context
-    	AuthMode	-	indicate the authentication mode
-    	WepStatus	-	indicate the encryption type
-		apidx		-	indicate the interface index
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID RTMPMakeRSNIE(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  UINT            AuthMode,
-    IN  UINT            WepStatus,
-	IN	UCHAR			apidx)
-{
-	PUCHAR		pRsnIe = NULL;			// primary RSNIE
-	UCHAR 		*rsnielen_cur_p = 0;	// the length of the primary RSNIE
-	UCHAR		*rsnielen_ex_cur_p = 0;	// the length of the secondary RSNIE
-	UCHAR		PrimaryRsnie;
-	BOOLEAN		bMixCipher = FALSE;	// indicate the pairwise and group cipher are different
-	UCHAR		p_offset;
-	WPA_MIX_PAIR_CIPHER		FlexibleCipher = MIX_CIPHER_NOTUSE;	// it provide the more flexible cipher combination in WPA-WPA2 and TKIPAES mode
-
-	rsnielen_cur_p = NULL;
-	rsnielen_ex_cur_p = NULL;
-
-	{
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-#ifdef WPA_SUPPLICANT_SUPPORT
-			if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-			{
-				if (AuthMode < Ndis802_11AuthModeWPA)
-					return;
-			}
-			else
-#endif // WPA_SUPPLICANT_SUPPORT //
-			{
-				// Support WPAPSK or WPA2PSK in STA-Infra mode
-				// Support WPANone in STA-Adhoc mode
-				if ((AuthMode != Ndis802_11AuthModeWPAPSK) &&
-					(AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-					(AuthMode != Ndis802_11AuthModeWPANone)
-					)
-					return;
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE,("==> RTMPMakeRSNIE(STA)\n"));
-
-			// Zero RSNIE context
-			pAd->StaCfg.RSNIE_Len = 0;
-			NdisZeroMemory(pAd->StaCfg.RSN_IE, MAX_LEN_OF_RSNIE);
-
-			// Pointer to RSNIE
-			rsnielen_cur_p = &pAd->StaCfg.RSNIE_Len;
-			pRsnIe = pAd->StaCfg.RSN_IE;
-
-			bMixCipher = pAd->StaCfg.bMixCipher;
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	// indicate primary RSNIE as WPA or WPA2
-	if ((AuthMode == Ndis802_11AuthModeWPA) ||
-		(AuthMode == Ndis802_11AuthModeWPAPSK) ||
-		(AuthMode == Ndis802_11AuthModeWPANone) ||
-		(AuthMode == Ndis802_11AuthModeWPA1WPA2) ||
-		(AuthMode == Ndis802_11AuthModeWPA1PSKWPA2PSK))
-		PrimaryRsnie = WpaIe;
-	else
-		PrimaryRsnie = Wpa2Ie;
-
-	{
-		// Build the primary RSNIE
-		// 1. insert cipher suite
-		RTMPInsertRsnIeCipher(pAd, PrimaryRsnie, WepStatus, bMixCipher, FlexibleCipher, pRsnIe, &p_offset);
-
-		// 2. insert AKM
-		RTMPInsertRsnIeAKM(pAd, PrimaryRsnie, AuthMode, apidx, pRsnIe, &p_offset);
-
-		// 3. insert capability
-		RTMPInsertRsnIeCap(pAd, PrimaryRsnie, apidx, pRsnIe, &p_offset);
-	}
-
-	// 4. update the RSNIE length
-	*rsnielen_cur_p = p_offset;
-
-	hex_dump("The primary RSNIE", pRsnIe, (*rsnielen_cur_p));
-
-
-}
-
-/*
-    ==========================================================================
-    Description:
-		Check whether the received frame is EAP frame.
-
-	Arguments:
-		pAd				-	pointer to our pAdapter context
-		pEntry			-	pointer to active entry
-		pData			-	the received frame
-		DataByteCount 	-	the received frame's length
-		FromWhichBSSID	-	indicate the interface index
-
-    Return:
-         TRUE 			-	This frame is EAP frame
-         FALSE 			-	otherwise
-    ==========================================================================
-*/
-BOOLEAN RTMPCheckWPAframe(
-    IN PRTMP_ADAPTER    pAd,
-    IN PMAC_TABLE_ENTRY	pEntry,
-    IN PUCHAR           pData,
-    IN ULONG            DataByteCount,
-	IN UCHAR			FromWhichBSSID)
-{
-	ULONG	Body_len;
-	BOOLEAN Cancelled;
-
-
-    if(DataByteCount < (LENGTH_802_1_H + LENGTH_EAPOL_H))
-        return FALSE;
-
-
-	// Skip LLC header
-    if (NdisEqualMemory(SNAP_802_1H, pData, 6) ||
-        // Cisco 1200 AP may send packet with SNAP_BRIDGE_TUNNEL
-        NdisEqualMemory(SNAP_BRIDGE_TUNNEL, pData, 6))
-    {
-        pData += 6;
-    }
-	// Skip 2-bytes EAPoL type
-    if (NdisEqualMemory(EAPOL, pData, 2))
-    {
-        pData += 2;
-    }
-    else
-        return FALSE;
-
-    switch (*(pData+1))
-    {
-        case EAPPacket:
-			Body_len = (*(pData+2)<<8) | (*(pData+3));
-            DBGPRINT(RT_DEBUG_TRACE, ("Receive EAP-Packet frame, TYPE = 0, Length = %ld\n", Body_len));
-            break;
-        case EAPOLStart:
-            DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL-Start frame, TYPE = 1 \n"));
-			if (pEntry->EnqueueEapolStartTimerRunning != EAPOL_START_DISABLE)
-            {
-            	DBGPRINT(RT_DEBUG_TRACE, ("Cancel the EnqueueEapolStartTimerRunning \n"));
-                RTMPCancelTimer(&pEntry->EnqueueStartForPSKTimer, &Cancelled);
-                pEntry->EnqueueEapolStartTimerRunning = EAPOL_START_DISABLE;
-            }
-            break;
-        case EAPOLLogoff:
-            DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOLLogoff frame, TYPE = 2 \n"));
-            break;
-        case EAPOLKey:
-			Body_len = (*(pData+2)<<8) | (*(pData+3));
-            DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL-Key frame, TYPE = 3, Length = %ld\n", Body_len));
-            break;
-        case EAPOLASFAlert:
-            DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOLASFAlert frame, TYPE = 4 \n"));
-            break;
-        default:
-            return FALSE;
-
-    }
-    return TRUE;
-}
-
-
-/*
-    ==========================================================================
-    Description:
-        ENCRYPT AES GTK before sending in EAPOL frame.
-        AES GTK length = 128 bit,  so fix blocks for aes-key-wrap as 2 in this function.
-        This function references to RFC 3394 for aes key wrap algorithm.
-    Return:
-    ==========================================================================
-*/
-VOID AES_GTK_KEY_WRAP(
-    IN UCHAR    *key,
-    IN UCHAR    *plaintext,
-    IN UCHAR    p_len,
-    OUT UCHAR   *ciphertext)
-{
-    UCHAR       A[8], BIN[16], BOUT[16];
-    UCHAR       R[512];
-    INT         num_blocks = p_len/8;   // unit:64bits
-    INT         i, j;
-    aes_context aesctx;
-    UCHAR       xor;
-
-    rtmp_aes_set_key(&aesctx, key, 128);
-
-    // Init IA
-    for (i = 0; i < 8; i++)
-        A[i] = 0xa6;
-
-    //Input plaintext
-    for (i = 0; i < num_blocks; i++)
-    {
-        for (j = 0 ; j < 8; j++)
-            R[8 * (i + 1) + j] = plaintext[8 * i + j];
-    }
-
-    // Key Mix
-    for (j = 0; j < 6; j++)
-    {
-        for(i = 1; i <= num_blocks; i++)
-        {
-            //phase 1
-            NdisMoveMemory(BIN, A, 8);
-            NdisMoveMemory(&BIN[8], &R[8 * i], 8);
-            rtmp_aes_encrypt(&aesctx, BIN, BOUT);
-
-            NdisMoveMemory(A, &BOUT[0], 8);
-            xor = num_blocks * j + i;
-            A[7] = BOUT[7] ^ xor;
-            NdisMoveMemory(&R[8 * i], &BOUT[8], 8);
-        }
-    }
-
-    // Output ciphertext
-    NdisMoveMemory(ciphertext, A, 8);
-
-    for (i = 1; i <= num_blocks; i++)
-    {
-        for (j = 0 ; j < 8; j++)
-            ciphertext[8 * i + j] = R[8 * i + j];
-    }
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Misc function to decrypt AES body
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-		This function references to	RFC	3394 for aes key unwrap algorithm.
-
-	========================================================================
-*/
-VOID	AES_GTK_KEY_UNWRAP(
-	IN	UCHAR	*key,
-	OUT	UCHAR	*plaintext,
-	IN	UCHAR    c_len,
-	IN	UCHAR	*ciphertext)
-
-{
-	UCHAR       A[8], BIN[16], BOUT[16];
-	UCHAR       xor;
-	INT         i, j;
-	aes_context aesctx;
-	UCHAR       *R;
-	INT         num_blocks = c_len/8;	// unit:64bits
-
-
-	os_alloc_mem(NULL, (PUCHAR *)&R, 512);
-
-	if (R == NULL)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("!!!AES_GTK_KEY_UNWRAP: no memory!!!\n"));
-        return;
-    } /* End of if */
-
-	// Initialize
-	NdisMoveMemory(A, ciphertext, 8);
-	//Input plaintext
-	for(i = 0; i < (c_len-8); i++)
-	{
-		R[ i] = ciphertext[i + 8];
-	}
-
-	rtmp_aes_set_key(&aesctx, key, 128);
-
-	for(j = 5; j >= 0; j--)
-	{
-		for(i = (num_blocks-1); i > 0; i--)
-		{
-			xor = (num_blocks -1 )* j + i;
-			NdisMoveMemory(BIN, A, 8);
-			BIN[7] = A[7] ^ xor;
-			NdisMoveMemory(&BIN[8], &R[(i-1)*8], 8);
-			rtmp_aes_decrypt(&aesctx, BIN, BOUT);
-			NdisMoveMemory(A, &BOUT[0], 8);
-			NdisMoveMemory(&R[(i-1)*8], &BOUT[8], 8);
-		}
-	}
-
-	// OUTPUT
-	for(i = 0; i < c_len; i++)
-	{
-		plaintext[i] = R[i];
-	}
-
-
-	os_free_mem(NULL, R);
-}
-
-/*
-    ==========================================================================
-    Description:
-		Report the EAP message type
-
-	Arguments:
-		msg		-	EAPOL_PAIR_MSG_1
-					EAPOL_PAIR_MSG_2
-					EAPOL_PAIR_MSG_3
-					EAPOL_PAIR_MSG_4
-					EAPOL_GROUP_MSG_1
-					EAPOL_GROUP_MSG_2
-
-    Return:
-         message type string
-
-    ==========================================================================
-*/
-CHAR *GetEapolMsgType(CHAR msg)
-{
-    if(msg == EAPOL_PAIR_MSG_1)
-        return "Pairwise Message 1";
-    else if(msg == EAPOL_PAIR_MSG_2)
-        return "Pairwise Message 2";
-	else if(msg == EAPOL_PAIR_MSG_3)
-        return "Pairwise Message 3";
-	else if(msg == EAPOL_PAIR_MSG_4)
-        return "Pairwise Message 4";
-	else if(msg == EAPOL_GROUP_MSG_1)
-        return "Group Message 1";
-	else if(msg == EAPOL_GROUP_MSG_2)
-        return "Group Message 2";
-    else
-    	return "Invalid Message";
-}
-
-
-/*
-    ========================================================================
-
-    Routine Description:
-    Check Sanity RSN IE of EAPoL message
-
-    Arguments:
-
-    Return Value:
-
-
-    ========================================================================
-*/
-BOOLEAN RTMPCheckRSNIE(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pData,
-	IN  UCHAR           DataLen,
-	IN  MAC_TABLE_ENTRY *pEntry,
-	OUT	UCHAR			*Offset)
-{
-	PUCHAR              pVIE;
-	UCHAR               len;
-	PEID_STRUCT         pEid;
-	BOOLEAN				result = FALSE;
-
-	pVIE = pData;
-	len	 = DataLen;
-	*Offset = 0;
-
-	while (len > sizeof(RSNIE2))
-	{
-		pEid = (PEID_STRUCT) pVIE;
-		// WPA RSN IE
-		if ((pEid->Eid == IE_WPA) && (NdisEqualMemory(pEid->Octet, WPA_OUI, 4)))
-		{
-			if ((pEntry->AuthMode == Ndis802_11AuthModeWPA || pEntry->AuthMode == Ndis802_11AuthModeWPAPSK) &&
-				(NdisEqualMemory(pVIE, pEntry->RSN_IE, pEntry->RSNIE_Len)) &&
-				(pEntry->RSNIE_Len == (pEid->Len + 2)))
-			{
-					result = TRUE;
-			}
-
-			*Offset += (pEid->Len + 2);
-		}
-		// WPA2 RSN IE
-		else if ((pEid->Eid == IE_RSN) && (NdisEqualMemory(pEid->Octet + 2, RSN_OUI, 3)))
-		{
-			if ((pEntry->AuthMode == Ndis802_11AuthModeWPA2 || pEntry->AuthMode == Ndis802_11AuthModeWPA2PSK) &&
-				(NdisEqualMemory(pVIE, pEntry->RSN_IE, pEntry->RSNIE_Len)) &&
-				(pEntry->RSNIE_Len == (pEid->Len + 2))/* ToDo-AlbertY for mesh*/)
-			{
-					result = TRUE;
-			}
-
-			*Offset += (pEid->Len + 2);
-		}
-		else
-		{
-			break;
-		}
-
-		pVIE += (pEid->Len + 2);
-		len  -= (pEid->Len + 2);
-	}
-
-
-	return result;
-
-}
-
-
-/*
-    ========================================================================
-
-    Routine Description:
-    Parse KEYDATA field.  KEYDATA[] May contain 2 RSN IE and optionally GTK.
-    GTK  is encaptulated in KDE format at  p.83 802.11i D10
-
-    Arguments:
-
-    Return Value:
-
-    Note:
-        802.11i D10
-
-    ========================================================================
-*/
-BOOLEAN RTMPParseEapolKeyData(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pKeyData,
-	IN  UCHAR           KeyDataLen,
-	IN	UCHAR			GroupKeyIndex,
-	IN	UCHAR			MsgType,
-	IN	BOOLEAN			bWPA2,
-	IN  MAC_TABLE_ENTRY *pEntry)
-{
-    PKDE_ENCAP          pKDE = NULL;
-    PUCHAR              pMyKeyData = pKeyData;
-    UCHAR               KeyDataLength = KeyDataLen;
-    UCHAR               GTKLEN = 0;
-	UCHAR				DefaultIdx = 0;
-	UCHAR				skip_offset;
-
-	// Verify The RSN IE contained in pairewise_msg_2 && pairewise_msg_3 and skip it
-	if (MsgType == EAPOL_PAIR_MSG_2 || MsgType == EAPOL_PAIR_MSG_3)
-    {
-		// Check RSN IE whether it is WPA2/WPA2PSK
-		if (!RTMPCheckRSNIE(pAd, pKeyData, KeyDataLen, pEntry, &skip_offset))
-		{
-			// send wireless event - for RSN IE different
-			if (pAd->CommonCfg.bWirelessEvent)
-				RTMPSendWirelessEvent(pAd, IW_RSNIE_DIFF_EVENT_FLAG, pEntry->Addr, pEntry->apidx, 0);
-
-        	DBGPRINT(RT_DEBUG_ERROR, ("RSN_IE Different in msg %d of 4-way handshake!\n", MsgType));
-			hex_dump("Receive RSN_IE ", pKeyData, KeyDataLen);
-			hex_dump("Desired RSN_IE ", pEntry->RSN_IE, pEntry->RSNIE_Len);
-
-			return FALSE;
-    	}
-    	else
-		{
-			if (bWPA2 && MsgType == EAPOL_PAIR_MSG_3)
-			{
-				// skip RSN IE
-				pMyKeyData += skip_offset;
-				KeyDataLength -= skip_offset;
-				DBGPRINT(RT_DEBUG_TRACE, ("RTMPParseEapolKeyData ==> WPA2/WPA2PSK RSN IE matched in Msg 3, Length(%d) \n", skip_offset));
-			}
-			else
-				return TRUE;
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("RTMPParseEapolKeyData ==> KeyDataLength %d without RSN_IE \n", KeyDataLength));
-
-	// Parse EKD format in pairwise_msg_3_WPA2 && group_msg_1_WPA2
-	if (bWPA2 && (MsgType == EAPOL_PAIR_MSG_3 || MsgType == EAPOL_GROUP_MSG_1))
-	{
-		if (KeyDataLength >= 8)	// KDE format exclude GTK length
-    	{
-        	pKDE = (PKDE_ENCAP) pMyKeyData;
-
-
-			DefaultIdx = pKDE->GTKEncap.Kid;
-
-			// Sanity check - KED length
-			if (KeyDataLength < (pKDE->Len + 2))
-    		{
-        		DBGPRINT(RT_DEBUG_ERROR, ("ERROR: The len from KDE is too short \n"));
-        		return FALSE;
-    		}
-
-			// Get GTK length - refer to IEEE 802.11i-2004 p.82
-			GTKLEN = pKDE->Len -6;
-			if (GTKLEN < LEN_AES_KEY)
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("ERROR: GTK Key length is too short (%d) \n", GTKLEN));
-        		return FALSE;
-			}
-
-    	}
-		else
-    	{
-			DBGPRINT(RT_DEBUG_ERROR, ("ERROR: KDE format length is too short \n"));
-	        return FALSE;
-    	}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("GTK in KDE format ,DefaultKeyID=%d, KeyLen=%d \n", DefaultIdx, GTKLEN));
-		// skip it
-		pMyKeyData += 8;
-		KeyDataLength -= 8;
-
-	}
-	else if (!bWPA2 && MsgType == EAPOL_GROUP_MSG_1)
-	{
-		DefaultIdx = GroupKeyIndex;
-		DBGPRINT(RT_DEBUG_TRACE, ("GTK DefaultKeyID=%d \n", DefaultIdx));
-	}
-
-	// Sanity check - shared key index must be 1 ~ 3
-	if (DefaultIdx < 1 || DefaultIdx > 3)
-    {
-     	DBGPRINT(RT_DEBUG_ERROR, ("ERROR: GTK Key index(%d) is invalid in %s %s \n", DefaultIdx, ((bWPA2) ? "WPA2" : "WPA"), GetEapolMsgType(MsgType)));
-        return FALSE;
-    }
-
-
-#ifdef CONFIG_STA_SUPPORT
-	// Todo
-#endif // CONFIG_STA_SUPPORT //
-
-	return TRUE;
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Construct EAPoL message for WPA handshaking
-		Its format is below,
-
-		+--------------------+
-		| Protocol Version	 |  1 octet
-		+--------------------+
-		| Protocol Type		 |	1 octet
-		+--------------------+
-		| Body Length		 |  2 octets
-		+--------------------+
-		| Descriptor Type	 |	1 octet
-		+--------------------+
-		| Key Information    |	2 octets
-		+--------------------+
-		| Key Length	     |  1 octet
-		+--------------------+
-		| Key Repaly Counter |	8 octets
-		+--------------------+
-		| Key Nonce		     |  32 octets
-		+--------------------+
-		| Key IV			 |  16 octets
-		+--------------------+
-		| Key RSC			 |  8 octets
-		+--------------------+
-		| Key ID or Reserved |	8 octets
-		+--------------------+
-		| Key MIC			 |	16 octets
-		+--------------------+
-		| Key Data Length	 |	2 octets
-		+--------------------+
-		| Key Data			 |	n octets
-		+--------------------+
-
-
-	Arguments:
-		pAd			Pointer	to our adapter
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	ConstructEapolMsg(
-	IN 	PRTMP_ADAPTER    	pAd,
-    IN 	UCHAR				AuthMode,
-    IN 	UCHAR				WepStatus,
-    IN 	UCHAR				GroupKeyWepStatus,
-    IN 	UCHAR				MsgType,
-    IN	UCHAR				DefaultKeyIdx,
-    IN 	UCHAR				*ReplayCounter,
-	IN 	UCHAR				*KeyNonce,
-	IN	UCHAR				*TxRSC,
-	IN	UCHAR				*PTK,
-	IN	UCHAR				*GTK,
-	IN	UCHAR				*RSNIE,
-	IN	UCHAR				RSNIE_Len,
-    OUT PEAPOL_PACKET       pMsg)
-{
-	BOOLEAN	bWPA2 = FALSE;
-
-	// Choose WPA2 or not
-	if ((AuthMode == Ndis802_11AuthModeWPA2) || (AuthMode == Ndis802_11AuthModeWPA2PSK))
-		bWPA2 = TRUE;
-
-    // Init Packet and Fill header
-    pMsg->ProVer = EAPOL_VER;
-    pMsg->ProType = EAPOLKey;
-
-	// Default 95 bytes, the EAPoL-Key descriptor exclude Key-data field
-	pMsg->Body_Len[1] = LEN_EAPOL_KEY_MSG;
-
-	// Fill in EAPoL descriptor
-	if (bWPA2)
-		pMsg->KeyDesc.Type = WPA2_KEY_DESC;
-	else
-		pMsg->KeyDesc.Type = WPA1_KEY_DESC;
-
-	// Fill in Key information, refer to IEEE Std 802.11i-2004 page 78
-	// When either the pairwise or the group cipher is AES, the DESC_TYPE_AES(2) shall be used.
-	pMsg->KeyDesc.KeyInfo.KeyDescVer =
-        	(((WepStatus == Ndis802_11Encryption3Enabled) || (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)) ? (DESC_TYPE_AES) : (DESC_TYPE_TKIP));
-
-	// Specify Key Type as Group(0) or Pairwise(1)
-	if (MsgType >= EAPOL_GROUP_MSG_1)
-		pMsg->KeyDesc.KeyInfo.KeyType = GROUPKEY;
-	else
-		pMsg->KeyDesc.KeyInfo.KeyType = PAIRWISEKEY;
-
-	// Specify Key Index, only group_msg1_WPA1
-	if (!bWPA2 && (MsgType >= EAPOL_GROUP_MSG_1))
-		pMsg->KeyDesc.KeyInfo.KeyIndex = DefaultKeyIdx;
-
-	if (MsgType == EAPOL_PAIR_MSG_3)
-		pMsg->KeyDesc.KeyInfo.Install = 1;
-
-	if ((MsgType == EAPOL_PAIR_MSG_1) || (MsgType == EAPOL_PAIR_MSG_3) || (MsgType == EAPOL_GROUP_MSG_1))
-		pMsg->KeyDesc.KeyInfo.KeyAck = 1;
-
-	if (MsgType != EAPOL_PAIR_MSG_1)
-		pMsg->KeyDesc.KeyInfo.KeyMic = 1;
-
-	if ((bWPA2 && (MsgType >= EAPOL_PAIR_MSG_3)) || (!bWPA2 && (MsgType >= EAPOL_GROUP_MSG_1)))
-    {
-       	pMsg->KeyDesc.KeyInfo.Secure = 1;
-    }
-
-	if (bWPA2 && ((MsgType == EAPOL_PAIR_MSG_3) || (MsgType == EAPOL_GROUP_MSG_1)))
-    {
-        pMsg->KeyDesc.KeyInfo.EKD_DL = 1;
-    }
-
-	// key Information element has done.
-	*(USHORT *)(&pMsg->KeyDesc.KeyInfo) = cpu2le16(*(USHORT *)(&pMsg->KeyDesc.KeyInfo));
-
-	// Fill in Key Length
-	{
-		if (MsgType >= EAPOL_GROUP_MSG_1)
-		{
-			// the length of group key cipher
-			pMsg->KeyDesc.KeyLength[1] = ((GroupKeyWepStatus == Ndis802_11Encryption2Enabled) ? TKIP_GTK_LENGTH : LEN_AES_KEY);
-		}
-		else
-		{
-			// the length of pairwise key cipher
-			pMsg->KeyDesc.KeyLength[1] = ((WepStatus == Ndis802_11Encryption2Enabled) ? LEN_TKIP_KEY : LEN_AES_KEY);
-		}
-	}
-
- 	// Fill in replay counter
-    NdisMoveMemory(pMsg->KeyDesc.ReplayCounter, ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Fill Key Nonce field
-	// ANonce : pairwise_msg1 & pairwise_msg3
-	// SNonce : pairwise_msg2
-	// GNonce : group_msg1_wpa1
-	if ((MsgType <= EAPOL_PAIR_MSG_3) || ((!bWPA2 && (MsgType == EAPOL_GROUP_MSG_1))))
-    	NdisMoveMemory(pMsg->KeyDesc.KeyNonce, KeyNonce, LEN_KEY_DESC_NONCE);
-
-	// Fill key IV - WPA2 as 0, WPA1 as random
-	if (!bWPA2 && (MsgType == EAPOL_GROUP_MSG_1))
-	{
-		// Suggest IV be random number plus some number,
-		NdisMoveMemory(pMsg->KeyDesc.KeyIv, &KeyNonce[16], LEN_KEY_DESC_IV);
-        pMsg->KeyDesc.KeyIv[15] += 2;
-	}
-
-    // Fill Key RSC field
-    // It contains the RSC for the GTK being installed.
-	if ((MsgType == EAPOL_PAIR_MSG_3 && bWPA2) || (MsgType == EAPOL_GROUP_MSG_1))
-	{
-        NdisMoveMemory(pMsg->KeyDesc.KeyRsc, TxRSC, 6);
-	}
-
-	// Clear Key MIC field for MIC calculation later
-    NdisZeroMemory(pMsg->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-
-	ConstructEapolKeyData(pAd,
-						  AuthMode,
-						  WepStatus,
-						  GroupKeyWepStatus,
-						  MsgType,
-						  DefaultKeyIdx,
-						  bWPA2,
-						  PTK,
-						  GTK,
-						  RSNIE,
-						  RSNIE_Len,
-						  pMsg);
-
-	// Calculate MIC and fill in KeyMic Field except Pairwise Msg 1.
-	if (MsgType != EAPOL_PAIR_MSG_1)
-	{
-		CalculateMIC(pAd, WepStatus, PTK, pMsg);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("===> ConstructEapolMsg for %s %s\n", ((bWPA2) ? "WPA2" : "WPA"), GetEapolMsgType(MsgType)));
-	DBGPRINT(RT_DEBUG_TRACE, ("	     Body length = %d \n", pMsg->Body_Len[1]));
-	DBGPRINT(RT_DEBUG_TRACE, ("	     Key length  = %d \n", pMsg->KeyDesc.KeyLength[1]));
-
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Construct the Key Data field of EAPoL message
-
-	Arguments:
-		pAd			Pointer	to our adapter
-		Elem		Message body
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	ConstructEapolKeyData(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			AuthMode,
-	IN	UCHAR			WepStatus,
-	IN	UCHAR			GroupKeyWepStatus,
-	IN 	UCHAR			MsgType,
-	IN	UCHAR			DefaultKeyIdx,
-	IN	BOOLEAN			bWPA2Capable,
-	IN	UCHAR			*PTK,
-	IN	UCHAR			*GTK,
-	IN	UCHAR			*RSNIE,
-	IN	UCHAR			RSNIE_LEN,
-	OUT PEAPOL_PACKET   pMsg)
-{
-	UCHAR		*mpool, *Key_Data, *Rc4GTK;
-	UCHAR       ekey[(LEN_KEY_DESC_IV+LEN_EAP_EK)];
-	UCHAR		data_offset;
-
-
-	if (MsgType == EAPOL_PAIR_MSG_1 || MsgType == EAPOL_PAIR_MSG_4 || MsgType == EAPOL_GROUP_MSG_2)
-		return;
-
-	// allocate memory pool
-	os_alloc_mem(pAd, (PUCHAR *)&mpool, 1500);
-
-    if (mpool == NULL)
-		return;
-
-	/* Rc4GTK Len = 512 */
-	Rc4GTK = (UCHAR *) ROUND_UP(mpool, 4);
-	/* Key_Data Len = 512 */
-	Key_Data = (UCHAR *) ROUND_UP(Rc4GTK + 512, 4);
-
-	NdisZeroMemory(Key_Data, 512);
-	pMsg->KeyDesc.KeyDataLen[1] = 0;
-	data_offset = 0;
-
-	// Encapsulate RSNIE in pairwise_msg2 & pairwise_msg3
-	if (RSNIE_LEN && ((MsgType == EAPOL_PAIR_MSG_2) || (MsgType == EAPOL_PAIR_MSG_3)))
-	{
-		if (bWPA2Capable)
-			Key_Data[data_offset + 0] = IE_WPA2;
-		else
-			Key_Data[data_offset + 0] = IE_WPA;
-
-        Key_Data[data_offset + 1] = RSNIE_LEN;
-		NdisMoveMemory(&Key_Data[data_offset + 2], RSNIE, RSNIE_LEN);
-		data_offset += (2 + RSNIE_LEN);
-	}
-
-	// Encapsulate KDE format in pairwise_msg3_WPA2 & group_msg1_WPA2
-	if (bWPA2Capable && ((MsgType == EAPOL_PAIR_MSG_3) || (MsgType == EAPOL_GROUP_MSG_1)))
-	{
-		// Key Data Encapsulation (KDE) format - 802.11i-2004  Figure-43w and Table-20h
-        Key_Data[data_offset + 0] = 0xDD;
-
-		if (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)
-		{
-			Key_Data[data_offset + 1] = 0x16;// 4+2+16(OUI+DataType+DataField)
-		}
-		else
-		{
-			Key_Data[data_offset + 1] = 0x26;// 4+2+32(OUI+DataType+DataField)
-		}
-
-        Key_Data[data_offset + 2] = 0x00;
-        Key_Data[data_offset + 3] = 0x0F;
-        Key_Data[data_offset + 4] = 0xAC;
-        Key_Data[data_offset + 5] = 0x01;
-
-		// GTK KDE format - 802.11i-2004  Figure-43x
-        Key_Data[data_offset + 6] = (DefaultKeyIdx & 0x03);
-        Key_Data[data_offset + 7] = 0x00;	// Reserved Byte
-
-		data_offset += 8;
-	}
-
-
-	// Encapsulate GTK and encrypt the key-data field with KEK.
-	// Only for pairwise_msg3_WPA2 and group_msg1
-	if ((MsgType == EAPOL_PAIR_MSG_3 && bWPA2Capable) || (MsgType == EAPOL_GROUP_MSG_1))
-	{
-		// Fill in GTK
-		if (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)
-		{
-			NdisMoveMemory(&Key_Data[data_offset], GTK, LEN_AES_KEY);
-			data_offset += LEN_AES_KEY;
-		}
-		else
-		{
-			NdisMoveMemory(&Key_Data[data_offset], GTK, TKIP_GTK_LENGTH);
-			data_offset += TKIP_GTK_LENGTH;
-		}
-
-		// Still dont know why, but if not append will occur "GTK not include in MSG3"
-		// Patch for compatibility between zero config and funk
-		if (MsgType == EAPOL_PAIR_MSG_3 && bWPA2Capable)
-		{
-			if (GroupKeyWepStatus == Ndis802_11Encryption3Enabled)
-			{
-				Key_Data[data_offset + 0] = 0xDD;
-				Key_Data[data_offset + 1] = 0;
-				data_offset += 2;
-			}
-			else
-			{
-				Key_Data[data_offset + 0] = 0xDD;
-				Key_Data[data_offset + 1] = 0;
-				Key_Data[data_offset + 2] = 0;
-				Key_Data[data_offset + 3] = 0;
-				Key_Data[data_offset + 4] = 0;
-				Key_Data[data_offset + 5] = 0;
-				data_offset += 6;
-			}
-		}
-
-		// Encrypt the data material in key data field
-		if (WepStatus == Ndis802_11Encryption3Enabled)
-		{
-			AES_GTK_KEY_WRAP(&PTK[16], Key_Data, data_offset, Rc4GTK);
-            // AES wrap function will grow 8 bytes in length
-            data_offset += 8;
-		}
-		else
-		{
-			// PREPARE Encrypted  "Key DATA" field.  (Encrypt GTK with RC4, usinf PTK[16]->[31] as Key, IV-field as IV)
-			// put TxTsc in Key RSC field
-			pAd->PrivateInfo.FCSCRC32 = PPPINITFCS32;   //Init crc32.
-
-			// ekey is the contanetion of IV-field, and PTK[16]->PTK[31]
-			NdisMoveMemory(ekey, pMsg->KeyDesc.KeyIv, LEN_KEY_DESC_IV);
-			NdisMoveMemory(&ekey[LEN_KEY_DESC_IV], &PTK[16], LEN_EAP_EK);
-			ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, ekey, sizeof(ekey));  //INIT SBOX, KEYLEN+3(IV)
-			pAd->PrivateInfo.FCSCRC32 = RTMP_CALC_FCS32(pAd->PrivateInfo.FCSCRC32, Key_Data, data_offset);
-			WPAARCFOUR_ENCRYPT(&pAd->PrivateInfo.WEPCONTEXT, Rc4GTK, Key_Data, data_offset);
-		}
-
-		NdisMoveMemory(pMsg->KeyDesc.KeyData, Rc4GTK, data_offset);
-	}
-	else
-	{
-		NdisMoveMemory(pMsg->KeyDesc.KeyData, Key_Data, data_offset);
-	}
-
-	// set key data length field and total length
-	pMsg->KeyDesc.KeyDataLen[1] = data_offset;
-    pMsg->Body_Len[1] += data_offset;
-
-	os_free_mem(pAd, mpool);
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Calcaulate MIC. It is used during 4-ways handsharking.
-
-	Arguments:
-		pAd				-	pointer to our pAdapter context
-    	PeerWepStatus	-	indicate the encryption type
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	CalculateMIC(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			PeerWepStatus,
-	IN	UCHAR			*PTK,
-	OUT PEAPOL_PACKET   pMsg)
-{
-    UCHAR   *OutBuffer;
-	ULONG	FrameLen = 0;
-	UCHAR	mic[LEN_KEY_DESC_MIC];
-	UCHAR	digest[80];
-
-	// allocate memory for MIC calculation
-	os_alloc_mem(pAd, (PUCHAR *)&OutBuffer, 512);
-
-    if (OutBuffer == NULL)
-    {
-		DBGPRINT(RT_DEBUG_ERROR, ("!!!CalculateMIC: no memory!!!\n"));
-		return;
-    }
-
-	// make a frame for calculating MIC.
-    MakeOutgoingFrame(OutBuffer,            	&FrameLen,
-                      pMsg->Body_Len[1] + 4,  	pMsg,
-                      END_OF_ARGS);
-
-	NdisZeroMemory(mic, sizeof(mic));
-
-	// Calculate MIC
-    if (PeerWepStatus == Ndis802_11Encryption3Enabled)
- 	{
-		HMAC_SHA1(OutBuffer,  FrameLen, PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(PTK,  LEN_EAP_MICK, OutBuffer, FrameLen, mic);
-	}
-
-	// store the calculated MIC
-	NdisMoveMemory(pMsg->KeyDesc.KeyMic, mic, LEN_KEY_DESC_MIC);
-
-	os_free_mem(pAd, OutBuffer);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Some received frames can't decrypt by Asic, so decrypt them by software.
-
-	Arguments:
-		pAd				-	pointer to our pAdapter context
-    	PeerWepStatus	-	indicate the encryption type
-
-	Return Value:
-		NDIS_STATUS_SUCCESS		-	decryption successful
-		NDIS_STATUS_FAILURE		-	decryption failure
-
-	========================================================================
-*/
-NDIS_STATUS	RTMPSoftDecryptBroadCastData(
-	IN	PRTMP_ADAPTER					pAd,
-	IN	RX_BLK							*pRxBlk,
-	IN  NDIS_802_11_ENCRYPTION_STATUS 	GroupCipher,
-	IN  PCIPHER_KEY						pShard_key)
-{
-	PRXWI_STRUC			pRxWI = pRxBlk->pRxWI;
-
-
-
-	// handle WEP decryption
-	if (GroupCipher == Ndis802_11Encryption1Enabled)
-    {
-		if (RTMPSoftDecryptWEP(pAd, pRxBlk->pData, pRxWI->MPDUtotalByteCount, pShard_key))
-		{
-
-			//Minus IV[4] & ICV[4]
-			pRxWI->MPDUtotalByteCount -= 8;
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("ERROR : Software decrypt WEP data fails.\n"));
-			// give up this frame
-			return NDIS_STATUS_FAILURE;
-		}
-	}
-	// handle TKIP decryption
-	else if (GroupCipher == Ndis802_11Encryption2Enabled)
-	{
-		if (RTMPSoftDecryptTKIP(pAd, pRxBlk->pData, pRxWI->MPDUtotalByteCount, 0, pShard_key))
-		{
-
-			//Minus 8 bytes MIC, 8 bytes IV/EIV, 4 bytes ICV
-			pRxWI->MPDUtotalByteCount -= 20;
-		}
-        else
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("ERROR : RTMPSoftDecryptTKIP Failed\n"));
-			// give up this frame
-			return NDIS_STATUS_FAILURE;
-        }
-	}
-	// handle AES decryption
-	else if (GroupCipher == Ndis802_11Encryption3Enabled)
-	{
-		if (RTMPSoftDecryptAES(pAd, pRxBlk->pData, pRxWI->MPDUtotalByteCount , pShard_key))
-		{
-
-			//8 bytes MIC, 8 bytes IV/EIV (CCMP Header)
-			pRxWI->MPDUtotalByteCount -= 16;
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("ERROR : RTMPSoftDecryptAES Failed\n"));
-			// give up this frame
-			return NDIS_STATUS_FAILURE;
-		}
-	}
-	else
-	{
-		// give up this frame
-		return NDIS_STATUS_FAILURE;
-	}
-
-	return NDIS_STATUS_SUCCESS;
-
-}
-
+#include "../../rt2870/common/cmm_wpa.c"
diff --git a/drivers/staging/rt3070/common/dfs.c b/drivers/staging/rt3070/common/dfs.c
index 28d6014..c584a69 100644
--- a/drivers/staging/rt3070/common/dfs.c
+++ b/drivers/staging/rt3070/common/dfs.c
@@ -1,441 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    ap_dfs.c
-
-    Abstract:
-    Support DFS function.
-
-    Revision History:
-    Who       When            What
-    --------  ----------      ----------------------------------------------
-    Fonchi    03-12-2007      created
-*/
-
-#include "../rt_config.h"
-
-typedef struct _RADAR_DURATION_TABLE
-{
-	ULONG RDDurRegion;
-	ULONG RadarSignalDuration;
-	ULONG Tolerance;
-} RADAR_DURATION_TABLE, *PRADAR_DURATION_TABLE;
-
-
-static UCHAR RdIdleTimeTable[MAX_RD_REGION][4] =
-{
-	{9, 250, 250, 250},		// CE
-	{4, 250, 250, 250},		// FCC
-	{4, 250, 250, 250},		// JAP
-	{15, 250, 250, 250},	// JAP_W53
-	{4, 250, 250, 250}		// JAP_W56
-};
-
-/*
-	========================================================================
-
-	Routine Description:
-		Bbp Radar detection routine
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-
-	========================================================================
-*/
-VOID BbpRadarDetectionStart(
-	IN PRTMP_ADAPTER pAd)
-{
-	UINT8 RadarPeriod;
-
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 114, 0x02);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 121, 0x20);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 122, 0x00);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 123, 0x08/*0x80*/);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 124, 0x28);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, 125, 0xff);
-
-	RadarPeriod = ((UINT)RdIdleTimeTable[pAd->CommonCfg.RadarDetect.RDDurRegion][0] + (UINT)pAd->CommonCfg.RadarDetect.DfsSessionTime) < 250 ?
-			(RdIdleTimeTable[pAd->CommonCfg.RadarDetect.RDDurRegion][0] + pAd->CommonCfg.RadarDetect.DfsSessionTime) : 250;
-
-	RTMP_IO_WRITE8(pAd, 0x7020, 0x1d);
-	RTMP_IO_WRITE8(pAd, 0x7021, 0x40);
-
-	RadarDetectionStart(pAd, 0, RadarPeriod);
-	return;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Bbp Radar detection routine
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-
-	========================================================================
-*/
-VOID BbpRadarDetectionStop(
-	IN PRTMP_ADAPTER pAd)
-{
-	RTMP_IO_WRITE8(pAd, 0x7020, 0x1d);
-	RTMP_IO_WRITE8(pAd, 0x7021, 0x60);
-
-	RadarDetectionStop(pAd);
-	return;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Radar detection routine
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-
-	========================================================================
-*/
-VOID RadarDetectionStart(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN CTSProtect,
-	IN UINT8 CTSPeriod)
-{
-	UINT8 DfsActiveTime = (pAd->CommonCfg.RadarDetect.DfsSessionTime & 0x1f);
-	UINT8 CtsProtect = (CTSProtect == 1) ? 0x02 : 0x01; // CTS protect.
-
-	if (CTSProtect != 0)
-	{
-		switch(pAd->CommonCfg.RadarDetect.RDDurRegion)
-		{
-		case FCC:
-		case JAP_W56:
-			CtsProtect = 0x03;
-			break;
-
-		case CE:
-		case JAP_W53:
-		default:
-			CtsProtect = 0x02;
-			break;
-		}
-	}
-	else
-		CtsProtect = 0x01;
-
-
-	// send start-RD with CTS protection command to MCU
-	// highbyte [7]		reserve
-	// highbyte [6:5]	0x: stop Carrier/Radar detection
-	// highbyte [10]:	Start Carrier/Radar detection without CTS protection, 11: Start Carrier/Radar detection with CTS protection
-	// highbyte [4:0]	Radar/carrier detection duration. In 1ms.
-
-	// lowbyte [7:0]	Radar/carrier detection period, in 1ms.
-	AsicSendCommandToMcu(pAd, 0x60, 0xff, CTSPeriod, DfsActiveTime | (CtsProtect << 5));
-	//AsicSendCommandToMcu(pAd, 0x63, 0xff, 10, 0);
-
-	return;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Radar detection routine
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-		TRUE	Found radar signal
-		FALSE	Not found radar signal
-
-	========================================================================
-*/
-VOID RadarDetectionStop(
-	IN PRTMP_ADAPTER	pAd)
-{
-	DBGPRINT(RT_DEBUG_TRACE,("RadarDetectionStop.\n"));
-	AsicSendCommandToMcu(pAd, 0x60, 0xff, 0x00, 0x00);	// send start-RD with CTS protection command to MCU
-
-	return;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Radar channel check routine
-
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	Return Value:
-		TRUE	need to do radar detect
-		FALSE	need not to do radar detect
-
-	========================================================================
-*/
-BOOLEAN RadarChannelCheck(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			Ch)
-{
-#if 1
-	INT		i;
-	BOOLEAN result = FALSE;
-
-	for (i=0; i<pAd->ChannelListNum; i++)
-	{
-		if (Ch == pAd->ChannelList[i].Channel)
-		{
-			result = pAd->ChannelList[i].DfsReq;
-			break;
-		}
-	}
-
-	return result;
-#else
-	INT		i;
-	UCHAR	Channel[15]={52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140};
-
-	for (i=0; i<15; i++)
-	{
-		if (Ch == Channel[i])
-		{
-			break;
-		}
-	}
-
-	if (i != 15)
-		return TRUE;
-	else
-		return FALSE;
-#endif
-}
-
-ULONG JapRadarType(
-	IN PRTMP_ADAPTER pAd)
-{
-	ULONG		i;
-	const UCHAR	Channel[15]={52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140};
-
-	if (pAd->CommonCfg.RadarDetect.RDDurRegion != JAP)
-	{
-		return pAd->CommonCfg.RadarDetect.RDDurRegion;
-	}
-
-	for (i=0; i<15; i++)
-	{
-		if (pAd->CommonCfg.Channel == Channel[i])
-		{
-			break;
-		}
-	}
-
-	if (i < 4)
-		return JAP_W53;
-	else if (i < 15)
-		return JAP_W56;
-	else
-		return JAP; // W52
-
-}
-
-ULONG RTMPBbpReadRadarDuration(
-	IN PRTMP_ADAPTER	pAd)
-{
-	UINT8 byteValue = 0;
-	ULONG result;
-
-	BBP_IO_READ8_BY_REG_ID(pAd, BBP_R115, &byteValue);
-
-	result = 0;
-	switch (byteValue)
-	{
-	case 1: // radar signal detected by pulse mode.
-	case 2: // radar signal detected by width mode.
-		result = RTMPReadRadarDuration(pAd);
-		break;
-
-	case 0: // No radar signal.
-	default:
-
-		result = 0;
-		break;
-	}
-
-	return result;
-}
-
-ULONG RTMPReadRadarDuration(
-	IN PRTMP_ADAPTER	pAd)
-{
-	ULONG result = 0;
-
-#ifdef DFS_SUPPORT
-	UINT8 duration1 = 0, duration2 = 0, duration3 = 0;
-
-	BBP_IO_READ8_BY_REG_ID(pAd, BBP_R116, &duration1);
-	BBP_IO_READ8_BY_REG_ID(pAd, BBP_R117, &duration2);
-	BBP_IO_READ8_BY_REG_ID(pAd, BBP_R118, &duration3);
-	result = (duration1 << 16) + (duration2 << 8) + duration3;
-#endif // DFS_SUPPORT //
-
-	return result;
-
-}
-
-VOID RTMPCleanRadarDuration(
-	IN PRTMP_ADAPTER	pAd)
-{
-	return;
-}
-
-/*
-    ========================================================================
-    Routine Description:
-        Radar wave detection. The API should be invoke each second.
-
-    Arguments:
-        pAd         - Adapter pointer
-
-    Return Value:
-        None
-
-    ========================================================================
-*/
-VOID ApRadarDetectPeriodic(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT	i;
-
-	pAd->CommonCfg.RadarDetect.InServiceMonitorCount++;
-
-	for (i=0; i<pAd->ChannelListNum; i++)
-	{
-		if (pAd->ChannelList[i].RemainingTimeForUse > 0)
-		{
-			pAd->ChannelList[i].RemainingTimeForUse --;
-			if ((pAd->Mlme.PeriodicRound%5) == 0)
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("RadarDetectPeriodic - ch=%d, RemainingTimeForUse=%d\n", pAd->ChannelList[i].Channel, pAd->ChannelList[i].RemainingTimeForUse));
-			}
-		}
-	}
-
-	//radar detect
-	if ((pAd->CommonCfg.Channel > 14)
-		&& (pAd->CommonCfg.bIEEE80211H == 1)
-		&& RadarChannelCheck(pAd, pAd->CommonCfg.Channel))
-	{
-		RadarDetectPeriodic(pAd);
-	}
-
-	return;
-}
-
-// Periodic Radar detection, switch channel will occur in RTMPHandleTBTTInterrupt()
-// Before switch channel, driver needs doing channel switch announcement.
-VOID RadarDetectPeriodic(
-	IN PRTMP_ADAPTER	pAd)
-{
-	// need to check channel availability, after switch channel
-	if (pAd->CommonCfg.RadarDetect.RDMode != RD_SILENCE_MODE)
-			return;
-
-	// channel availability check time is 60sec, use 65 for assurance
-	if (pAd->CommonCfg.RadarDetect.RDCount++ > pAd->CommonCfg.RadarDetect.ChMovingTime)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("Not found radar signal, start send beacon and radar detection in service monitor\n\n"));
-			BbpRadarDetectionStop(pAd);
-		AsicEnableBssSync(pAd);
-		pAd->CommonCfg.RadarDetect.RDMode = RD_NORMAL_MODE;
-
-
-		return;
-	}
-
-	return;
-}
-
-
-/*
-    ==========================================================================
-    Description:
-		change channel moving time for DFS testing.
-
-	Arguments:
-	    pAdapter                    Pointer to our adapter
-	    wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-               1.) iwpriv ra0 set ChMovTime=[value]
-    ==========================================================================
-*/
-INT Set_ChMovingTime_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg)
-{
-	UINT8 Value;
-
-	Value = simple_strtol(arg, 0, 10);
-
-	pAd->CommonCfg.RadarDetect.ChMovingTime = Value;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s:: %d\n", __FUNCTION__,
-		pAd->CommonCfg.RadarDetect.ChMovingTime));
-
-	return TRUE;
-}
-
-INT Set_LongPulseRadarTh_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg)
-{
-	UINT8 Value;
-
-	Value = simple_strtol(arg, 0, 10) > 10 ? 10 : simple_strtol(arg, 0, 10);
-
-	pAd->CommonCfg.RadarDetect.LongPulseRadarTh = Value;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s:: %d\n", __FUNCTION__,
-		pAd->CommonCfg.RadarDetect.LongPulseRadarTh));
-
-	return TRUE;
-}
-
-
+#include "../../rt2870/common/dfs.c"
diff --git a/drivers/staging/rt3070/common/eeprom.c b/drivers/staging/rt3070/common/eeprom.c
index 63e1dc1..0c567d3 100644
--- a/drivers/staging/rt3070/common/eeprom.c
+++ b/drivers/staging/rt3070/common/eeprom.c
@@ -1,1498 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	eeprom.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-*/
-#include	"../rt_config.h"
-
-// IRQL = PASSIVE_LEVEL
-VOID RaiseClock(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  UINT32 *x)
-{
-    *x = *x | EESK;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, *x);
-    RTMPusecDelay(1);				// Max frequency = 1MHz in Spec. definition
-}
-
-// IRQL = PASSIVE_LEVEL
-VOID LowerClock(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  UINT32 *x)
-{
-    *x = *x & ~EESK;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, *x);
-    RTMPusecDelay(1);
-}
-
-// IRQL = PASSIVE_LEVEL
-USHORT ShiftInBits(
-    IN	PRTMP_ADAPTER	pAd)
-{
-    UINT32		x,i;
-	USHORT      data=0;
-
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-
-    x &= ~( EEDO | EEDI);
-
-    for(i=0; i<16; i++)
-    {
-        data = data << 1;
-        RaiseClock(pAd, &x);
-
-        RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-		LowerClock(pAd, &x); //prevent read failed
-
-        x &= ~(EEDI);
-        if(x & EEDO)
-            data |= 1;
-    }
-
-    return data;
-}
-
-// IRQL = PASSIVE_LEVEL
-VOID ShiftOutBits(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  USHORT data,
-    IN  USHORT count)
-{
-    UINT32       x,mask;
-
-    mask = 0x01 << (count - 1);
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-
-    x &= ~(EEDO | EEDI);
-
-    do
-    {
-        x &= ~EEDI;
-        if(data & mask)		x |= EEDI;
-
-        RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-        RaiseClock(pAd, &x);
-        LowerClock(pAd, &x);
-
-        mask = mask >> 1;
-    } while(mask);
-
-    x &= ~EEDI;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-}
-
-// IRQL = PASSIVE_LEVEL
-VOID EEpromCleanup(
-    IN	PRTMP_ADAPTER	pAd)
-{
-    UINT32 x;
-
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-
-    x &= ~(EECS | EEDI);
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-    RaiseClock(pAd, &x);
-    LowerClock(pAd, &x);
-}
-
-VOID EWEN(
-	IN	PRTMP_ADAPTER	pAd)
-{
-    UINT32	x;
-
-    // reset bits and set EECS
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-    x &= ~(EEDI | EEDO | EESK);
-    x |= EECS;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-	// kick a pulse
-	RaiseClock(pAd, &x);
-	LowerClock(pAd, &x);
-
-    // output the read_opcode and six pulse in that order
-    ShiftOutBits(pAd, EEPROM_EWEN_OPCODE, 5);
-    ShiftOutBits(pAd, 0, 6);
-
-    EEpromCleanup(pAd);
-}
-
-VOID EWDS(
-	IN	PRTMP_ADAPTER	pAd)
-{
-    UINT32	x;
-
-    // reset bits and set EECS
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-    x &= ~(EEDI | EEDO | EESK);
-    x |= EECS;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-	// kick a pulse
-	RaiseClock(pAd, &x);
-	LowerClock(pAd, &x);
-
-    // output the read_opcode and six pulse in that order
-    ShiftOutBits(pAd, EEPROM_EWDS_OPCODE, 5);
-    ShiftOutBits(pAd, 0, 6);
-
-    EEpromCleanup(pAd);
-}
-
-// IRQL = PASSIVE_LEVEL
-USHORT RTMP_EEPROM_READ16(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  USHORT Offset)
-{
-    UINT32		x;
-    USHORT		data;
-
-	if (pAd->NicConfig2.field.AntDiversity)
-    {
-    	pAd->EepromAccess = TRUE;
-    }
-//2008/09/11:KH add to support efuse<--
-//2008/09/11:KH add to support efuse-->
-{
-    Offset /= 2;
-    // reset bits and set EECS
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-    x &= ~(EEDI | EEDO | EESK);
-    x |= EECS;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-	// patch can not access e-Fuse issue
-    if (!IS_RT3090(pAd))
-    {
-	// kick a pulse
-	RaiseClock(pAd, &x);
-	LowerClock(pAd, &x);
-    }
-
-    // output the read_opcode and register number in that order
-    ShiftOutBits(pAd, EEPROM_READ_OPCODE, 3);
-    ShiftOutBits(pAd, Offset, pAd->EEPROMAddressNum);
-
-    // Now read the data (16 bits) in from the selected EEPROM word
-    data = ShiftInBits(pAd);
-
-    EEpromCleanup(pAd);
-
-	// Antenna and EEPROM access are both using EESK pin,
-    // Therefor we should avoid accessing EESK at the same time
-    // Then restore antenna after EEPROM access
-	if ((pAd->NicConfig2.field.AntDiversity) || (pAd->RfIcType == RFIC_3020))
-    {
-	    pAd->EepromAccess = FALSE;
-	    AsicSetRxAnt(pAd, pAd->RxAnt.Pair1PrimaryRxAnt);
-    }
-}
-    return data;
-}	//ReadEEprom
-
-VOID RTMP_EEPROM_WRITE16(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  USHORT Offset,
-    IN  USHORT Data)
-{
-    UINT32 x;
-
-	if (pAd->NicConfig2.field.AntDiversity)
-    {
-    	pAd->EepromAccess = TRUE;
-    }
-	//2008/09/11:KH add to support efuse<--
-//2008/09/11:KH add to support efuse-->
-	{
-	Offset /= 2;
-
-	EWEN(pAd);
-
-    // reset bits and set EECS
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-    x &= ~(EEDI | EEDO | EESK);
-    x |= EECS;
-    RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-	// patch can not access e-Fuse issue
-    if (!IS_RT3090(pAd))
-    {
-	// kick a pulse
-	RaiseClock(pAd, &x);
-	LowerClock(pAd, &x);
-    }
-
-    // output the read_opcode ,register number and data in that order
-    ShiftOutBits(pAd, EEPROM_WRITE_OPCODE, 3);
-    ShiftOutBits(pAd, Offset, pAd->EEPROMAddressNum);
-	ShiftOutBits(pAd, Data, 16);		// 16-bit access
-
-    // read DO status
-    RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-
-	EEpromCleanup(pAd);
-
-	RTMPusecDelay(10000);	//delay for twp(MAX)=10ms
-
-	EWDS(pAd);
-
-    EEpromCleanup(pAd);
-
-	// Antenna and EEPROM access are both using EESK pin,
-    // Therefor we should avoid accessing EESK at the same time
-    // Then restore antenna after EEPROM access
-	if ((pAd->NicConfig2.field.AntDiversity) || (pAd->RfIcType == RFIC_3020))
-    {
-	    pAd->EepromAccess = FALSE;
-	    AsicSetRxAnt(pAd, pAd->RxAnt.Pair1PrimaryRxAnt);
-    }
-}
-}
-
-//2008/09/11:KH add to support efuse<--
-#ifdef RT30xx
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-UCHAR eFuseReadRegisters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT Offset,
-	IN	USHORT Length,
-	OUT	USHORT* pData)
-{
-	EFUSE_CTRL_STRUC		eFuseCtrlStruc;
-	int	i;
-	USHORT	efuseDataOffset;
-	UINT32	data;
-
-	RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
-
-	//Step0. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
-	//Use the eeprom logical address and covert to address to block number
-	eFuseCtrlStruc.field.EFSROM_AIN = Offset & 0xfff0;
-
-	//Step1. Write EFSROM_MODE (0x580, bit7:bit6) to 0.
-	eFuseCtrlStruc.field.EFSROM_MODE = 0;
-
-	//Step2. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical read procedure.
-	eFuseCtrlStruc.field.EFSROM_KICK = 1;
-
-	NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
-	RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
-
-	//Step3. Polling EFSROM_KICK(0x580, bit30) until it become 0 again.
-	i = 0;
-	while(i < 100)
-	{
-		//rtmp.HwMemoryReadDword(EFUSE_CTRL, (DWORD *) &eFuseCtrlStruc, 4);
-		RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
-		if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
-		{
-			break;
-		}
-		RTMPusecDelay(2);
-		i++;
-	}
-
-	//if EFSROM_AOUT is not found in physical address, write 0xffff
-	if (eFuseCtrlStruc.field.EFSROM_AOUT == 0x3f)
-	{
-		for(i=0; i<Length/2; i++)
-			*(pData+2*i) = 0xffff;
-	}
-	else
-	{
-		//Step4. Read 16-byte of data from EFUSE_DATA0-3 (0x590-0x59C)
-		efuseDataOffset =  EFUSE_DATA3 - (Offset & 0xC)  ;
-		//data hold 4 bytes data.
-		//In RTMP_IO_READ32 will automatically execute 32-bytes swapping
-		RTMP_IO_READ32(pAd, efuseDataOffset, &data);
-		//Decide the upper 2 bytes or the bottom 2 bytes.
-		// Little-endian		S	|	S	Big-endian
-		// addr	3	2	1	0	|	0	1	2	3
-		// Ori-V	D	C	B	A	|	A	B	C	D
-		//After swapping
-		//		D	C	B	A	|	D	C	B	A
-		//Return 2-bytes
-		//The return byte statrs from S. Therefore, the little-endian will return BA, the Big-endian will return DC.
-		//For returning the bottom 2 bytes, the Big-endian should shift right 2-bytes.
-#ifdef RT_BIG_ENDIAN
-		data = data << (8*((Offset & 0x3)^0x2));
-#else
-		data = data >> (8*(Offset & 0x3));
-#endif
-
-		NdisMoveMemory(pData, &data, Length);
-	}
-
-	return (UCHAR) eFuseCtrlStruc.field.EFSROM_AOUT;
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-VOID eFusePhysicalReadRegisters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT Offset,
-	IN	USHORT Length,
-	OUT	USHORT* pData)
-{
-	EFUSE_CTRL_STRUC		eFuseCtrlStruc;
-	int	i;
-	USHORT	efuseDataOffset;
-	UINT32	data;
-
-	RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
-
-	//Step0. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
-	eFuseCtrlStruc.field.EFSROM_AIN = Offset & 0xfff0;
-
-	//Step1. Write EFSROM_MODE (0x580, bit7:bit6) to 1.
-	//Read in physical view
-	eFuseCtrlStruc.field.EFSROM_MODE = 1;
-
-	//Step2. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical read procedure.
-	eFuseCtrlStruc.field.EFSROM_KICK = 1;
-
-	NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
-	RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
-
-	//Step3. Polling EFSROM_KICK(0x580, bit30) until it become 0 again.
-	i = 0;
-	while(i < 100)
-	{
-		RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
-		if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
-			break;
-		RTMPusecDelay(2);
-		i++;
-	}
-
-	//Step4. Read 16-byte of data from EFUSE_DATA0-3 (0x59C-0x590)
-	//Because the size of each EFUSE_DATA is 4 Bytes, the size of address of each is 2 bits.
-	//The previous 2 bits is the EFUSE_DATA number, the last 2 bits is used to decide which bytes
-	//Decide which EFUSE_DATA to read
-	//590:F E D C
-	//594:B A 9 8
-	//598:7 6 5 4
-	//59C:3 2 1 0
-	efuseDataOffset =  EFUSE_DATA3 - (Offset & 0xC)  ;
-
-	RTMP_IO_READ32(pAd, efuseDataOffset, &data);
-
-#ifdef RT_BIG_ENDIAN
-		data = data << (8*((Offset & 0x3)^0x2));
-#else
-	data = data >> (8*(Offset & 0x3));
-#endif
-
-	NdisMoveMemory(pData, &data, Length);
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-VOID eFuseReadPhysical(
-	IN	PRTMP_ADAPTER	pAd,
-  	IN	PUSHORT lpInBuffer,
-  	IN	ULONG nInBufferSize,
-  	OUT	PUSHORT lpOutBuffer,
-  	IN	ULONG nOutBufferSize
-)
-{
-	USHORT* pInBuf = (USHORT*)lpInBuffer;
-	USHORT* pOutBuf = (USHORT*)lpOutBuffer;
-
-	USHORT Offset = pInBuf[0];					//addr
-	USHORT Length = pInBuf[1];					//length
-	int 		i;
-
-	for(i=0; i<Length; i+=2)
-	{
-		eFusePhysicalReadRegisters(pAd,Offset+i, 2, &pOutBuf[i/2]);
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS eFuseRead(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	OUT	PUCHAR			pData,
-	IN	USHORT			Length)
-{
-	USHORT* pOutBuf = (USHORT*)pData;
-	NTSTATUS	Status = STATUS_SUCCESS;
-	UCHAR	EFSROM_AOUT;
-	int	i;
-
-	for(i=0; i<Length; i+=2)
-	{
-		EFSROM_AOUT = eFuseReadRegisters(pAd, Offset+i, 2, &pOutBuf[i/2]);
-	}
-	return Status;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-VOID eFusePhysicalWriteRegisters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT Offset,
-	IN	USHORT Length,
-	OUT	USHORT* pData)
-{
-	EFUSE_CTRL_STRUC		eFuseCtrlStruc;
-	int	i;
-	USHORT	efuseDataOffset;
-	UINT32	data, eFuseDataBuffer[4];
-
-	//Step0. Write 16-byte of data to EFUSE_DATA0-3 (0x590-0x59C), where EFUSE_DATA0 is the LSB DW, EFUSE_DATA3 is the MSB DW.
-
-	/////////////////////////////////////////////////////////////////
-	//read current values of 16-byte block
-	RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
-
-	//Step0. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
-	eFuseCtrlStruc.field.EFSROM_AIN = Offset & 0xfff0;
-
-	//Step1. Write EFSROM_MODE (0x580, bit7:bit6) to 1.
-	eFuseCtrlStruc.field.EFSROM_MODE = 1;
-
-	//Step2. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical read procedure.
-	eFuseCtrlStruc.field.EFSROM_KICK = 1;
-
-	NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
-	RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
-
-	//Step3. Polling EFSROM_KICK(0x580, bit30) until it become 0 again.
-	i = 0;
-	while(i < 100)
-	{
-		RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
-
-		if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
-			break;
-		RTMPusecDelay(2);
-		i++;
-	}
-
-	//Step4. Read 16-byte of data from EFUSE_DATA0-3 (0x59C-0x590)
-	efuseDataOffset =  EFUSE_DATA3;
-	for(i=0; i< 4; i++)
-	{
-		RTMP_IO_READ32(pAd, efuseDataOffset, (PUINT32) &eFuseDataBuffer[i]);
-		efuseDataOffset -=  4;
-	}
-
-	//Update the value, the offset is multiple of 2, length is 2
-	efuseDataOffset = (Offset & 0xc) >> 2;
-	data = pData[0] & 0xffff;
-	//The offset should be 0x***10 or 0x***00
-	if((Offset % 4) != 0)
-	{
-		eFuseDataBuffer[efuseDataOffset] = (eFuseDataBuffer[efuseDataOffset] & 0xffff) | (data << 16);
-	}
-	else
-	{
-		eFuseDataBuffer[efuseDataOffset] = (eFuseDataBuffer[efuseDataOffset] & 0xffff0000) | data;
-	}
-
-	efuseDataOffset =  EFUSE_DATA3;
-	for(i=0; i< 4; i++)
-	{
-		RTMP_IO_WRITE32(pAd, efuseDataOffset, eFuseDataBuffer[i]);
-		efuseDataOffset -= 4;
-	}
-	/////////////////////////////////////////////////////////////////
-
-	//Step1. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
-	eFuseCtrlStruc.field.EFSROM_AIN = Offset & 0xfff0;
-
-	//Step2. Write EFSROM_MODE (0x580, bit7:bit6) to 3.
-	eFuseCtrlStruc.field.EFSROM_MODE = 3;
-
-	//Step3. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical write procedure.
-	eFuseCtrlStruc.field.EFSROM_KICK = 1;
-
-	NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
-	RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
-
-	//Step4. Polling EFSROM_KICK(0x580, bit30) until it become 0 again. It¡¦s done.
-	i = 0;
-	while(i < 100)
-	{
-		RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
-
-		if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
-			break;
-
-		RTMPusecDelay(2);
-		i++;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS eFuseWriteRegisters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT Offset,
-	IN	USHORT Length,
-	IN	USHORT* pData)
-{
-	USHORT	i;
-	USHORT	eFuseData;
-	USHORT	LogicalAddress, BlkNum = 0xffff;
-	UCHAR	EFSROM_AOUT;
-
-	USHORT addr,tmpaddr, InBuf[3], tmpOffset;
-	USHORT buffer[8];
-	BOOLEAN		bWriteSuccess = TRUE;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters Offset=%x, pData=%x\n", Offset, *pData));
-
-	//Step 0. find the entry in the mapping table
-	//The address of EEPROM is 2-bytes alignment.
-	//The last bit is used for alignment, so it must be 0.
-	tmpOffset = Offset & 0xfffe;
-	EFSROM_AOUT = eFuseReadRegisters(pAd, tmpOffset, 2, &eFuseData);
-
-	if( EFSROM_AOUT == 0x3f)
-	{	//find available logical address pointer
-		//the logical address does not exist, find an empty one
-		//from the first address of block 45=16*45=0x2d0 to the last address of block 47
-		//==>48*16-3(reserved)=2FC
-		for (i=EFUSE_USAGE_MAP_START; i<=EFUSE_USAGE_MAP_END; i+=2)
-		{
-			//Retrive the logical block nubmer form each logical address pointer
-			//It will access two logical address pointer each time.
-			eFusePhysicalReadRegisters(pAd, i, 2, &LogicalAddress);
-			if( (LogicalAddress & 0xff) == 0)
-			{//Not used logical address pointer
-				BlkNum = i-EFUSE_USAGE_MAP_START;
-				break;
-			}
-			else if(( (LogicalAddress >> 8) & 0xff) == 0)
-			{//Not used logical address pointer
-				if (i != EFUSE_USAGE_MAP_END)
-				{
-					BlkNum = i-EFUSE_USAGE_MAP_START+1;
-				}
-				break;
-			}
-		}
-	}
-	else
-	{
-		BlkNum = EFSROM_AOUT;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters BlkNum = %d \n", BlkNum));
-
-	if(BlkNum == 0xffff)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters: out of free E-fuse space!!!\n"));
-		return FALSE;
-	}
-
-	//Step 1. Save data of this block	which is pointed by the avaible logical address pointer
-	// read and save the original block data
-	for(i =0; i<8; i++)
-	{
-		addr = BlkNum * 0x10 ;
-
-		InBuf[0] = addr+2*i;
-		InBuf[1] = 2;
-		InBuf[2] = 0x0;
-
-		eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
-
-		buffer[i] = InBuf[2];
-	}
-
-	//Step 2. Update the data in buffer, and write the data to Efuse
-	buffer[ (Offset >> 1) % 8] = pData[0];
-
-	do
-	{
-		//Step 3. Write the data to Efuse
-		if(!bWriteSuccess)
-		{
-			for(i =0; i<8; i++)
-			{
-				addr = BlkNum * 0x10 ;
-
-				InBuf[0] = addr+2*i;
-				InBuf[1] = 2;
-				InBuf[2] = buffer[i];
-
-				eFuseWritePhysical(pAd, &InBuf[0], 6, NULL, 2);
-			}
-		}
-		else
-		{
-				addr = BlkNum * 0x10 ;
-
-				InBuf[0] = addr+(Offset % 16);
-				InBuf[1] = 2;
-				InBuf[2] = pData[0];
-
-				eFuseWritePhysical(pAd, &InBuf[0], 6, NULL, 2);
-		}
-
-		//Step 4. Write mapping table
-		addr = EFUSE_USAGE_MAP_START+BlkNum;
-
-		tmpaddr = addr;
-
-		if(addr % 2 != 0)
-			addr = addr -1;
-		InBuf[0] = addr;
-		InBuf[1] = 2;
-
-		//convert the address from 10 to 8 bit ( bit7, 6 = parity and bit5 ~ 0 = bit9~4), and write to logical map entry
-		tmpOffset = Offset;
-		tmpOffset >>= 4;
-		tmpOffset |= ((~((tmpOffset & 0x01) ^ ( tmpOffset >> 1 & 0x01) ^  (tmpOffset >> 2 & 0x01) ^  (tmpOffset >> 3 & 0x01))) << 6) & 0x40;
-		tmpOffset |= ((~( (tmpOffset >> 2 & 0x01) ^ (tmpOffset >> 3 & 0x01) ^ (tmpOffset >> 4 & 0x01) ^ ( tmpOffset >> 5 & 0x01))) << 7) & 0x80;
-
-		// write the logical address
-		if(tmpaddr%2 != 0)
-			InBuf[2] = tmpOffset<<8;
-		else
-			InBuf[2] = tmpOffset;
-
-		eFuseWritePhysical(pAd,&InBuf[0], 6, NULL, 0);
-
-		//Step 5. Compare data if not the same, invalidate the mapping entry, then re-write the data until E-fuse is exhausted
-		bWriteSuccess = TRUE;
-		for(i =0; i<8; i++)
-		{
-			addr = BlkNum * 0x10 ;
-
-			InBuf[0] = addr+2*i;
-			InBuf[1] = 2;
-			InBuf[2] = 0x0;
-
-			eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
-
-			if(buffer[i] != InBuf[2])
-			{
-				bWriteSuccess = FALSE;
-				break;
-			}
-		}
-
-		//Step 6. invlidate mapping entry and find a free mapping entry if not succeed
-		if (!bWriteSuccess)
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("Not bWriteSuccess BlkNum = %d\n", BlkNum));
-
-			// the offset of current mapping entry
-			addr = EFUSE_USAGE_MAP_START+BlkNum;
-
-			//find a new mapping entry
-			BlkNum = 0xffff;
-			for (i=EFUSE_USAGE_MAP_START; i<=EFUSE_USAGE_MAP_END; i+=2)
-			{
-				eFusePhysicalReadRegisters(pAd, i, 2, &LogicalAddress);
-				if( (LogicalAddress & 0xff) == 0)
-				{
-					BlkNum = i-EFUSE_USAGE_MAP_START;
-					break;
-				}
-				else if(( (LogicalAddress >> 8) & 0xff) == 0)
-				{
-					if (i != EFUSE_USAGE_MAP_END)
-					{
-						BlkNum = i+1-EFUSE_USAGE_MAP_START;
-					}
-					break;
-				}
-			}
-			DBGPRINT(RT_DEBUG_TRACE, ("Not bWriteSuccess new BlkNum = %d\n", BlkNum));
-			if(BlkNum == 0xffff)
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters: out of free E-fuse space!!!\n"));
-				return FALSE;
-			}
-
-			//invalidate the original mapping entry if new entry is not found
-			tmpaddr = addr;
-
-			if(addr % 2 != 0)
-				addr = addr -1;
-			InBuf[0] = addr;
-			InBuf[1] = 2;
-
-			eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
-
-			// write the logical address
-			if(tmpaddr%2 != 0)
-			{
-				// Invalidate the high byte
-				for (i=8; i<15; i++)
-				{
-					if( ( (InBuf[2] >> i) & 0x01) == 0)
-					{
-						InBuf[2] |= (0x1 <<i);
-						break;
-					}
-				}
-			}
-			else
-			{
-				// invalidate the low byte
-				for (i=0; i<8; i++)
-				{
-					if( ( (InBuf[2] >> i) & 0x01) == 0)
-					{
-						InBuf[2] |= (0x1 <<i);
-						break;
-					}
-				}
-			}
-			eFuseWritePhysical(pAd, &InBuf[0], 6, NULL, 0);
-		}
-	}
-	while(!bWriteSuccess);
-
-	return TRUE;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-VOID eFuseWritePhysical(
-	IN	PRTMP_ADAPTER	pAd,
-  	PUSHORT lpInBuffer,
-	ULONG nInBufferSize,
-  	PUCHAR lpOutBuffer,
-  	ULONG nOutBufferSize
-)
-{
-	USHORT* pInBuf = (USHORT*)lpInBuffer;
-	int 		i;
-	//USHORT* pOutBuf = (USHORT*)ioBuffer;
-
-	USHORT Offset = pInBuf[0];					//addr
-	USHORT Length = pInBuf[1];					//length
-	USHORT* pValueX = &pInBuf[2];				//value ...
-		// Little-endian		S	|	S	Big-endian
-		// addr	3	2	1	0	|	0	1	2	3
-		// Ori-V	D	C	B	A	|	A	B	C	D
-		//After swapping
-		//		D	C	B	A	|	D	C	B	A
-		//Both the little and big-endian use the same sequence to write  data.
-		//Therefore, we only need swap data when read the data.
-	for(i=0; i<Length; i+=2)
-	{
-		eFusePhysicalWriteRegisters(pAd, Offset+i, 2, &pValueX[i/2]);
-	}
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS eFuseWrite(
-   	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	PUCHAR			pData,
-	IN	USHORT			length)
-{
-	int i;
-
-	USHORT* pValueX = (PUSHORT) pData;				//value ...
-		//The input value=3070 will be stored as following
- 		// Little-endian		S	|	S	Big-endian
-		// addr			1	0	|	0	1
-		// Ori-V			30	70	|	30	70
-		//After swapping
-		//				30	70	|	70	30
-		//Casting
-		//				3070	|	7030 (x)
-		//The swapping should be removed for big-endian
-	for(i=0; i<length; i+=2)
-	{
-		eFuseWriteRegisters(pAd, Offset+i, 2, &pValueX[i/2]);
-	}
-
-	return TRUE;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-INT set_eFuseGetFreeBlockCount_Proc(
-   	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	USHORT i;
-	USHORT	LogicalAddress;
-	USHORT efusefreenum=0;
-	if(!pAd->bUseEfuse)
-		return FALSE;
-	for (i = EFUSE_USAGE_MAP_START; i <= EFUSE_USAGE_MAP_END; i+=2)
-	{
-		eFusePhysicalReadRegisters(pAd, i, 2, &LogicalAddress);
-		if( (LogicalAddress & 0xff) == 0)
-		{
-			efusefreenum= (UCHAR) (EFUSE_USAGE_MAP_END-i+1);
-			break;
-		}
-		else if(( (LogicalAddress >> 8) & 0xff) == 0)
-		{
-			efusefreenum = (UCHAR) (EFUSE_USAGE_MAP_END-i);
-			break;
-		}
-
-		if(i == EFUSE_USAGE_MAP_END)
-			efusefreenum = 0;
-	}
-	printk("efuseFreeNumber is %d\n",efusefreenum);
-	return TRUE;
-}
-INT set_eFusedump_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-USHORT InBuf[3];
-	INT i=0;
-	if(!pAd->bUseEfuse)
-		return FALSE;
-	for(i =0; i<EFUSE_USAGE_MAP_END/2; i++)
-	{
-		InBuf[0] = 2*i;
-		InBuf[1] = 2;
-		InBuf[2] = 0x0;
-
-		eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
-		if(i%4==0)
-		printk("\nBlock %x:",i/8);
-		printk("%04x ",InBuf[2]);
-	}
-	return TRUE;
-}
-INT	set_eFuseLoadFromBin_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR					*src;
-	struct file				*srcf;
-	INT 					retval, orgfsuid, orgfsgid;
-   	mm_segment_t			orgfs;
-	UCHAR					*buffer;
-	UCHAR					BinFileSize=0;
-	INT						i = 0,j=0,k=1;
-	USHORT					*PDATA;
-	USHORT					DATA;
-	BinFileSize=strlen("RT30xxEEPROM.bin");
-	src = kmalloc(128, MEM_ALLOC_FLAG);
-	NdisZeroMemory(src, 128);
-
- 	if(strlen(arg)>0)
-	{
-
-		NdisMoveMemory(src, arg, strlen(arg));
- 	}
-
-	else
-	{
-
-		NdisMoveMemory(src, "RT30xxEEPROM.bin", BinFileSize);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("FileName=%s\n",src));
-	buffer = kmalloc(MAX_EEPROM_BIN_FILE_SIZE, MEM_ALLOC_FLAG);
-
-	if(buffer == NULL)
-	{
-		kfree(src);
-		 return FALSE;
-}
-	PDATA=kmalloc(sizeof(USHORT)*8,MEM_ALLOC_FLAG);
-
-	if(PDATA==NULL)
-	{
-		kfree(src);
-
-		kfree(buffer);
-		return FALSE;
-	}
-	/* Don't change to uid 0, let the file be opened as the "normal" user */
-#if 0
-	orgfsuid = current->fsuid;
-	orgfsgid = current->fsgid;
-	current->fsuid=current->fsgid = 0;
-#endif
-    	orgfs = get_fs();
-   	 set_fs(KERNEL_DS);
-
-	if (src && *src)
-	{
-		srcf = filp_open(src, O_RDONLY, 0);
-		if (IS_ERR(srcf))
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("--> Error %ld opening %s\n", -PTR_ERR(srcf),src));
-			return FALSE;
-		}
-		else
-		{
-			// The object must have a read method
-			if (srcf->f_op && srcf->f_op->read)
-			{
-				memset(buffer, 0x00, MAX_EEPROM_BIN_FILE_SIZE);
-				while(srcf->f_op->read(srcf, &buffer[i], 1, &srcf->f_pos)==1)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("%02X ",buffer[i]));
-					if((i+1)%8==0)
-						DBGPRINT(RT_DEBUG_TRACE, ("\n"));
-              			i++;
-						if(i>=MAX_EEPROM_BIN_FILE_SIZE)
-							{
-								DBGPRINT(RT_DEBUG_ERROR, ("--> Error %ld reading %s, The file is too large[1024]\n", -PTR_ERR(srcf),src));
-								kfree(PDATA);
-								kfree(buffer);
-								kfree(src);
-								return FALSE;
-							}
-			       }
-			}
-			else
-			{
-						DBGPRINT(RT_DEBUG_ERROR, ("--> Error!! System doest not support read function\n"));
-						kfree(PDATA);
-						kfree(buffer);
-						kfree(src);
-						return FALSE;
-			}
-      		}
-
-
-	}
-	else
-		{
-					DBGPRINT(RT_DEBUG_ERROR, ("--> Error src  or srcf is null\n"));
-					kfree(PDATA);
-					kfree(buffer);
-					return FALSE;
-
-		}
-
-
-	retval=filp_close(srcf,NULL);
-
-	if (retval)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("--> Error %d closing %s\n", -retval, src));
-	}
-	set_fs(orgfs);
-#if 0
-	current->fsuid = orgfsuid;
-	current->fsgid = orgfsgid;
-#endif
-	for(j=0;j<i;j++)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%02X ",buffer[j]));
-		if((j+1)%2==0)
-			PDATA[j/2%8]=((buffer[j]<<8)&0xff00)|(buffer[j-1]&0xff);
-		if(j%16==0)
-		{
-			k=buffer[j];
-		}
-		else
-		{
-			k&=buffer[j];
-			if((j+1)%16==0)
-			{
-
-				DBGPRINT(RT_DEBUG_TRACE, (" result=%02X,blk=%02x\n",k,j/16));
-
-				if(k!=0xff)
-					eFuseWriteRegistersFromBin(pAd,(USHORT)j-15, 16, PDATA);
-				else
-					{
-						if(eFuseReadRegisters(pAd,j, 2,(PUSHORT)&DATA)!=0x3f)
-							eFuseWriteRegistersFromBin(pAd,(USHORT)j-15, 16, PDATA);
-					}
-				/*
-				for(l=0;l<8;l++)
-					printk("%04x ",PDATA[l]);
-				printk("\n");
-				*/
-				NdisZeroMemory(PDATA,16);
-
-
-			}
-		}
-
-
-	}
-
-
-	kfree(PDATA);
-	kfree(buffer);
-	kfree(src);
-	return TRUE;
-}
-NTSTATUS eFuseWriteRegistersFromBin(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT Offset,
-	IN	USHORT Length,
-	IN	USHORT* pData)
-{
-	USHORT	i;
-	USHORT	eFuseData;
-	USHORT	LogicalAddress, BlkNum = 0xffff;
-	UCHAR	EFSROM_AOUT,Loop=0;
-	EFUSE_CTRL_STRUC		eFuseCtrlStruc;
-	USHORT	efuseDataOffset;
-	UINT32	data,tempbuffer;
-	USHORT addr,tmpaddr, InBuf[3], tmpOffset;
-	UINT32 buffer[4];
-	BOOLEAN		bWriteSuccess = TRUE;
-	BOOLEAN		bNotWrite=TRUE;
-	BOOLEAN		bAllocateNewBlk=TRUE;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegistersFromBin Offset=%x, pData=%04x:%04x:%04x:%04x\n", Offset, *pData,*(pData+1),*(pData+2),*(pData+3)));
-
-	do
-	{
-	//Step 0. find the entry in the mapping table
-	//The address of EEPROM is 2-bytes alignment.
-	//The last bit is used for alignment, so it must be 0.
-	Loop++;
-	tmpOffset = Offset & 0xfffe;
-	EFSROM_AOUT = eFuseReadRegisters(pAd, tmpOffset, 2, &eFuseData);
-
-	if( EFSROM_AOUT == 0x3f)
-	{	//find available logical address pointer
-		//the logical address does not exist, find an empty one
-		//from the first address of block 45=16*45=0x2d0 to the last address of block 47
-		//==>48*16-3(reserved)=2FC
-		bAllocateNewBlk=TRUE;
-		for (i=EFUSE_USAGE_MAP_START; i<=EFUSE_USAGE_MAP_END; i+=2)
-		{
-			//Retrive the logical block nubmer form each logical address pointer
-			//It will access two logical address pointer each time.
-			eFusePhysicalReadRegisters(pAd, i, 2, &LogicalAddress);
-			if( (LogicalAddress & 0xff) == 0)
-			{//Not used logical address pointer
-				BlkNum = i-EFUSE_USAGE_MAP_START;
-				break;
-			}
-			else if(( (LogicalAddress >> 8) & 0xff) == 0)
-			{//Not used logical address pointer
-				if (i != EFUSE_USAGE_MAP_END)
-				{
-					BlkNum = i-EFUSE_USAGE_MAP_START+1;
-				}
-				break;
-			}
-		}
-	}
-	else
-	{
-		bAllocateNewBlk=FALSE;
-		BlkNum = EFSROM_AOUT;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters BlkNum = %d \n", BlkNum));
-
-	if(BlkNum == 0xffff)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegisters: out of free E-fuse space!!!\n"));
-		return FALSE;
-	}
-	//Step 1.1.0
-	//If the block is not existing in mapping table, create one
-	//and write down the 16-bytes data to the new block
-	if(bAllocateNewBlk)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("Allocate New Blk\n"));
-		efuseDataOffset =  EFUSE_DATA3;
-		for(i=0; i< 4; i++)
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("Allocate New Blk, Data%d=%04x%04x\n",3-i,pData[2*i+1],pData[2*i]));
-			tempbuffer=((pData[2*i+1]<<16)&0xffff0000)|pData[2*i];
-
-
-			RTMP_IO_WRITE32(pAd, efuseDataOffset,tempbuffer);
-			efuseDataOffset -= 4;
-
-		}
-		/////////////////////////////////////////////////////////////////
-
-		//Step1.1.1. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
-		eFuseCtrlStruc.field.EFSROM_AIN = BlkNum* 0x10 ;
-
-		//Step1.1.2. Write EFSROM_MODE (0x580, bit7:bit6) to 3.
-		eFuseCtrlStruc.field.EFSROM_MODE = 3;
-
-		//Step1.1.3. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical write procedure.
-		eFuseCtrlStruc.field.EFSROM_KICK = 1;
-
-		NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
-
-		RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
-
-		//Step1.1.4. Polling EFSROM_KICK(0x580, bit30) until it become 0 again. It¡¦s done.
-		i = 0;
-		while(i < 100)
-		{
-			RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
-
-			if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
-				break;
-
-			RTMPusecDelay(2);
-			i++;
-		}
-
-	}
-	else
-	{	//Step1.2.
-		//If the same logical number is existing, check if the writting data and the data
-		//saving in this block are the same.
-		/////////////////////////////////////////////////////////////////
-		//read current values of 16-byte block
-		RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
-
-		//Step1.2.0. Write 10-bit of address to EFSROM_AIN (0x580, bit25:bit16). The address must be 16-byte alignment.
-		eFuseCtrlStruc.field.EFSROM_AIN = Offset & 0xfff0;
-
-		//Step1.2.1. Write EFSROM_MODE (0x580, bit7:bit6) to 1.
-		eFuseCtrlStruc.field.EFSROM_MODE = 0;
-
-		//Step1.2.2. Write EFSROM_KICK (0x580, bit30) to 1 to kick-off physical read procedure.
-		eFuseCtrlStruc.field.EFSROM_KICK = 1;
-
-		NdisMoveMemory(&data, &eFuseCtrlStruc, 4);
-		RTMP_IO_WRITE32(pAd, EFUSE_CTRL, data);
-
-		//Step1.2.3. Polling EFSROM_KICK(0x580, bit30) until it become 0 again.
-		i = 0;
-		while(i < 100)
-		{
-			RTMP_IO_READ32(pAd, EFUSE_CTRL, (PUINT32) &eFuseCtrlStruc);
-
-			if(eFuseCtrlStruc.field.EFSROM_KICK == 0)
-				break;
-			RTMPusecDelay(2);
-			i++;
-		}
-
-		//Step1.2.4. Read 16-byte of data from EFUSE_DATA0-3 (0x59C-0x590)
-		efuseDataOffset =  EFUSE_DATA3;
-		for(i=0; i< 4; i++)
-		{
-			RTMP_IO_READ32(pAd, efuseDataOffset, (PUINT32) &buffer[i]);
-			efuseDataOffset -=  4;
-		}
-		//Step1.2.5. Check if the data of efuse and the writing data are the same.
-		for(i =0; i<4; i++)
-		{
-			tempbuffer=((pData[2*i+1]<<16)&0xffff0000)|pData[2*i];
-			DBGPRINT(RT_DEBUG_TRACE, ("buffer[%d]=%x,pData[%d]=%x,pData[%d]=%x,tempbuffer=%x\n",i,buffer[i],2*i,pData[2*i],2*i+1,pData[2*i+1],tempbuffer));
-
-			if(((buffer[i]&0xffff0000)==(pData[2*i+1]<<16))&&((buffer[i]&0xffff)==pData[2*i]))
-				bNotWrite&=TRUE;
-			else
-			{
-				bNotWrite&=FALSE;
-				break;
-			}
-		}
-		if(!bNotWrite)
-		{
-		printk("The data is not the same\n");
-
-			for(i =0; i<8; i++)
-			{
-				addr = BlkNum * 0x10 ;
-
-				InBuf[0] = addr+2*i;
-				InBuf[1] = 2;
-				InBuf[2] = pData[i];
-
-				eFuseWritePhysical(pAd, &InBuf[0], 6, NULL, 2);
-			}
-
-		}
-		else
-			return TRUE;
-	     }
-
-
-
-		//Step 2. Write mapping table
-		addr = EFUSE_USAGE_MAP_START+BlkNum;
-
-		tmpaddr = addr;
-
-		if(addr % 2 != 0)
-			addr = addr -1;
-		InBuf[0] = addr;
-		InBuf[1] = 2;
-
-		//convert the address from 10 to 8 bit ( bit7, 6 = parity and bit5 ~ 0 = bit9~4), and write to logical map entry
-		tmpOffset = Offset;
-		tmpOffset >>= 4;
-		tmpOffset |= ((~((tmpOffset & 0x01) ^ ( tmpOffset >> 1 & 0x01) ^  (tmpOffset >> 2 & 0x01) ^  (tmpOffset >> 3 & 0x01))) << 6) & 0x40;
-		tmpOffset |= ((~( (tmpOffset >> 2 & 0x01) ^ (tmpOffset >> 3 & 0x01) ^ (tmpOffset >> 4 & 0x01) ^ ( tmpOffset >> 5 & 0x01))) << 7) & 0x80;
-
-		// write the logical address
-		if(tmpaddr%2 != 0)
-			InBuf[2] = tmpOffset<<8;
-		else
-			InBuf[2] = tmpOffset;
-
-		eFuseWritePhysical(pAd,&InBuf[0], 6, NULL, 0);
-
-		//Step 3. Compare data if not the same, invalidate the mapping entry, then re-write the data until E-fuse is exhausted
-		bWriteSuccess = TRUE;
-		for(i =0; i<8; i++)
-		{
-			addr = BlkNum * 0x10 ;
-
-			InBuf[0] = addr+2*i;
-			InBuf[1] = 2;
-			InBuf[2] = 0x0;
-
-			eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
-			DBGPRINT(RT_DEBUG_TRACE, ("addr=%x, buffer[i]=%x,InBuf[2]=%x\n",InBuf[0],pData[i],InBuf[2]));
-			if(pData[i] != InBuf[2])
-			{
-				bWriteSuccess = FALSE;
-				break;
-			}
-		}
-
-		//Step 4. invlidate mapping entry and find a free mapping entry if not succeed
-
-		if (!bWriteSuccess&&Loop<2)
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegistersFromBin::Not bWriteSuccess BlkNum = %d\n", BlkNum));
-
-			// the offset of current mapping entry
-			addr = EFUSE_USAGE_MAP_START+BlkNum;
-
-			//find a new mapping entry
-			BlkNum = 0xffff;
-			for (i=EFUSE_USAGE_MAP_START; i<=EFUSE_USAGE_MAP_END; i+=2)
-			{
-				eFusePhysicalReadRegisters(pAd, i, 2, &LogicalAddress);
-				if( (LogicalAddress & 0xff) == 0)
-				{
-					BlkNum = i-EFUSE_USAGE_MAP_START;
-					break;
-				}
-				else if(( (LogicalAddress >> 8) & 0xff) == 0)
-				{
-					if (i != EFUSE_USAGE_MAP_END)
-					{
-						BlkNum = i+1-EFUSE_USAGE_MAP_START;
-					}
-					break;
-				}
-			}
-			DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegistersFromBin::Not bWriteSuccess new BlkNum = %d\n", BlkNum));
-			if(BlkNum == 0xffff)
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("eFuseWriteRegistersFromBin: out of free E-fuse space!!!\n"));
-				return FALSE;
-			}
-
-			//invalidate the original mapping entry if new entry is not found
-			tmpaddr = addr;
-
-			if(addr % 2 != 0)
-				addr = addr -1;
-			InBuf[0] = addr;
-			InBuf[1] = 2;
-
-			eFuseReadPhysical(pAd, &InBuf[0], 4, &InBuf[2], 2);
-
-			// write the logical address
-			if(tmpaddr%2 != 0)
-			{
-				// Invalidate the high byte
-				for (i=8; i<15; i++)
-				{
-					if( ( (InBuf[2] >> i) & 0x01) == 0)
-					{
-						InBuf[2] |= (0x1 <<i);
-						break;
-					}
-				}
-			}
-			else
-			{
-				// invalidate the low byte
-				for (i=0; i<8; i++)
-				{
-					if( ( (InBuf[2] >> i) & 0x01) == 0)
-					{
-						InBuf[2] |= (0x1 <<i);
-						break;
-					}
-				}
-			}
-			eFuseWritePhysical(pAd, &InBuf[0], 6, NULL, 0);
-		}
-
-	}
-	while(!bWriteSuccess&&Loop<2);
-
-	return TRUE;
-}
-
-#endif // RT30xx //
-//2008/09/11:KH add to support efuse-->
-
+#include "../../rt2870/common/eeprom.c"
diff --git a/drivers/staging/rt3070/common/md5.c b/drivers/staging/rt3070/common/md5.c
index 774776b..0752884 100644
--- a/drivers/staging/rt3070/common/md5.c
+++ b/drivers/staging/rt3070/common/md5.c
@@ -1,1427 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    md5.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-	jan			10-28-03		Initial
-	Rita    	11-23-04		Modify MD5 and SHA-1
-	Rita		10-14-05		Modify SHA-1 in big-endian platform
- */
-#include "../rt_config.h"
-
-/**
- * md5_mac:
- * @key: pointer to	the	key	used for MAC generation
- * @key_len: length	of the key in bytes
- * @data: pointer to the data area for which the MAC is	generated
- * @data_len: length of	the	data in	bytes
- * @mac: pointer to	the	buffer holding space for the MAC; the buffer should
- * have	space for 128-bit (16 bytes) MD5 hash value
- *
- * md5_mac() determines	the	message	authentication code	by using secure	hash
- * MD5(key | data |	key).
- */
-void md5_mac(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac)
-{
-	MD5_CTX	context;
-
-	MD5Init(&context);
-	MD5Update(&context,	key, key_len);
-	MD5Update(&context,	data, data_len);
-	MD5Update(&context,	key, key_len);
-	MD5Final(mac, &context);
-}
-
-/**
- * hmac_md5:
- * @key: pointer to	the	key	used for MAC generation
- * @key_len: length	of the key in bytes
- * @data: pointer to the data area for which the MAC is	generated
- * @data_len: length of	the	data in	bytes
- * @mac: pointer to	the	buffer holding space for the MAC; the buffer should
- * have	space for 128-bit (16 bytes) MD5 hash value
- *
- * hmac_md5() determines the message authentication	code using HMAC-MD5.
- * This	implementation is based	on the sample code presented in	RFC	2104.
- */
-void hmac_md5(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac)
-{
-	MD5_CTX	context;
-    u8 k_ipad[65]; /* inner padding - key XORd with ipad */
-    u8 k_opad[65]; /* outer padding - key XORd with opad */
-    u8 tk[16];
-	int	i;
-
-	//assert(key != NULL && data != NULL && mac != NULL);
-
-	/* if key is longer	than 64	bytes reset	it to key =	MD5(key) */
-	if (key_len	> 64) {
-		MD5_CTX	ttcontext;
-
-		MD5Init(&ttcontext);
-		MD5Update(&ttcontext, key, key_len);
-		MD5Final(tk, &ttcontext);
-		//key=(PUCHAR)ttcontext.buf;
-		key	= tk;
-		key_len	= 16;
-	}
-
-	/* the HMAC_MD5	transform looks	like:
-	 *
-	 * MD5(K XOR opad, MD5(K XOR ipad, text))
-	 *
-	 * where K is an n byte	key
-	 * ipad	is the byte	0x36 repeated 64 times
-	 * opad	is the byte	0x5c repeated 64 times
-	 * and text	is the data	being protected	*/
-
-	/* start out by	storing	key	in pads	*/
-	NdisZeroMemory(k_ipad, sizeof(k_ipad));
-	NdisZeroMemory(k_opad,	sizeof(k_opad));
-	//assert(key_len < sizeof(k_ipad));
-	NdisMoveMemory(k_ipad, key,	key_len);
-	NdisMoveMemory(k_opad, key,	key_len);
-
-	/* XOR key with	ipad and opad values */
-	for	(i = 0;	i <	64;	i++) {
-		k_ipad[i] ^= 0x36;
-		k_opad[i] ^= 0x5c;
-	}
-
-	/* perform inner MD5 */
-	MD5Init(&context);					 /*	init context for 1st pass */
-	MD5Update(&context,	k_ipad,	64);	 /*	start with inner pad */
-	MD5Update(&context,	data, data_len); /*	then text of datagram */
-	MD5Final(mac, &context);			 /*	finish up 1st pass */
-
-	/* perform outer MD5 */
-	MD5Init(&context);					 /*	init context for 2nd pass */
-	MD5Update(&context,	k_opad,	64);	 /*	start with outer pad */
-	MD5Update(&context,	mac, 16);		 /*	then results of	1st	hash */
-	MD5Final(mac, &context);			 /*	finish up 2nd pass */
-}
-
-#ifndef RT_BIG_ENDIAN
-#define byteReverse(buf, len)   /* Nothing */
-#else
-void byteReverse(unsigned char *buf, unsigned longs);
-void byteReverse(unsigned char *buf, unsigned longs)
-{
-    do {
-        *(UINT32 *)buf = SWAP32(*(UINT32 *)buf);
-        buf += 4;
-    } while (--longs);
-}
-#endif
-
-
-/* ==========================  MD5 implementation =========================== */
-// four base functions for MD5
-#define MD5_F1(x, y, z) (((x) & (y)) | ((~x) & (z)))
-#define MD5_F2(x, y, z) (((x) & (z)) | ((y) & (~z)))
-#define MD5_F3(x, y, z) ((x) ^ (y) ^ (z))
-#define MD5_F4(x, y, z) ((y) ^ ((x) | (~z)))
-#define CYCLIC_LEFT_SHIFT(w, s) (((w) << (s)) | ((w) >> (32-(s))))
-
-#define	MD5Step(f, w, x, y,	z, data, t, s)	\
-	( w	+= f(x,	y, z) +	data + t,  w = (CYCLIC_LEFT_SHIFT(w, s)) & 0xffffffff, w +=	x )
-
-
-/*
- *  Function Description:
- *      Initiate MD5 Context satisfied in RFC 1321
- *
- *  Arguments:
- *      pCtx        Pointer	to MD5 context
- *
- *  Return Value:
- *      None
- */
-VOID MD5Init(MD5_CTX *pCtx)
-{
-    pCtx->Buf[0]=0x67452301;
-    pCtx->Buf[1]=0xefcdab89;
-    pCtx->Buf[2]=0x98badcfe;
-    pCtx->Buf[3]=0x10325476;
-
-    pCtx->LenInBitCount[0]=0;
-    pCtx->LenInBitCount[1]=0;
-}
-
-
-/*
- *  Function Description:
- *      Update MD5 Context, allow of an arrary of octets as the next portion
- *      of the message
- *
- *  Arguments:
- *      pCtx		Pointer	to MD5 context
- * 	    pData       Pointer to input data
- *      LenInBytes  The length of input data (unit: byte)
- *
- *  Return Value:
- *      None
- *
- *  Note:
- *      Called after MD5Init or MD5Update(itself)
- */
-VOID MD5Update(MD5_CTX *pCtx, UCHAR *pData, UINT32 LenInBytes)
-{
-
-    UINT32 TfTimes;
-    UINT32 temp;
-	unsigned int i;
-
-    temp = pCtx->LenInBitCount[0];
-
-    pCtx->LenInBitCount[0] = (UINT32) (pCtx->LenInBitCount[0] + (LenInBytes << 3));
-
-    if (pCtx->LenInBitCount[0] < temp)
-        pCtx->LenInBitCount[1]++;   //carry in
-
-    pCtx->LenInBitCount[1] += LenInBytes >> 29;
-
-    // mod 64 bytes
-    temp = (temp >> 3) & 0x3f;
-
-    // process lacks of 64-byte data
-    if (temp)
-    {
-        UCHAR *pAds = (UCHAR *) pCtx->Input + temp;
-
-        if ((temp+LenInBytes) < 64)
-        {
-            NdisMoveMemory(pAds, (UCHAR *)pData, LenInBytes);
-            return;
-        }
-
-        NdisMoveMemory(pAds, (UCHAR *)pData, 64-temp);
-        byteReverse(pCtx->Input, 16);
-        MD5Transform(pCtx->Buf, (UINT32 *)pCtx->Input);
-
-        pData += 64-temp;
-        LenInBytes -= 64-temp;
-    } // end of if (temp)
-
-
-    TfTimes = (LenInBytes >> 6);
-
-    for (i=TfTimes; i>0; i--)
-    {
-        NdisMoveMemory(pCtx->Input, (UCHAR *)pData, 64);
-        byteReverse(pCtx->Input, 16);
-        MD5Transform(pCtx->Buf, (UINT32 *)pCtx->Input);
-        pData += 64;
-        LenInBytes -= 64;
-    } // end of for
-
-    // buffering lacks of 64-byte data
-    if(LenInBytes)
-        NdisMoveMemory(pCtx->Input, (UCHAR *)pData, LenInBytes);
-
-}
-
-
-/*
- *  Function Description:
- *      Append padding bits and length of original message in the tail
- *      The message digest has to be completed in the end
- *
- *  Arguments:
- *      Digest		Output of Digest-Message for MD5
- *  	pCtx        Pointer	to MD5 context
- *
- *  Return Value:
- *      None
- *
- *  Note:
- *      Called after MD5Update
- */
-VOID MD5Final(UCHAR Digest[16], MD5_CTX *pCtx)
-{
-    UCHAR Remainder;
-    UCHAR PadLenInBytes;
-    UCHAR *pAppend=0;
-    unsigned int i;
-
-    Remainder = (UCHAR)((pCtx->LenInBitCount[0] >> 3) & 0x3f);
-
-    PadLenInBytes = (Remainder < 56) ? (56-Remainder) : (120-Remainder);
-
-    pAppend = (UCHAR *)pCtx->Input + Remainder;
-
-    // padding bits without crossing block(64-byte based) boundary
-    if (Remainder < 56)
-    {
-        *pAppend = 0x80;
-        PadLenInBytes --;
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, PadLenInBytes);
-
-		// add data-length field, from low to high
-       	for (i=0; i<4; i++)
-        {
-        	pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[0] >> (i << 3)) & 0xff);
-        	pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[1] >> (i << 3)) & 0xff);
-      	}
-
-        byteReverse(pCtx->Input, 16);
-        MD5Transform(pCtx->Buf, (UINT32 *)pCtx->Input);
-    } // end of if
-
-    // padding bits with crossing block(64-byte based) boundary
-    else
-    {
-        // the first block ===
-        *pAppend = 0x80;
-        PadLenInBytes --;
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, (64-Remainder-1));
-        PadLenInBytes -= (64 - Remainder - 1);
-
-        byteReverse(pCtx->Input, 16);
-        MD5Transform(pCtx->Buf, (UINT32 *)pCtx->Input);
-
-
-        // the second block ===
-        NdisZeroMemory((UCHAR *)pCtx->Input, PadLenInBytes);
-
-        // add data-length field
-        for (i=0; i<4; i++)
-        {
-        	pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[0] >> (i << 3)) & 0xff);
-        	pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[1] >> (i << 3)) & 0xff);
-      	}
-
-        byteReverse(pCtx->Input, 16);
-        MD5Transform(pCtx->Buf, (UINT32 *)pCtx->Input);
-    } // end of else
-
-
-    NdisMoveMemory((UCHAR *)Digest, (UINT32 *)pCtx->Buf, 16); // output
-    byteReverse((UCHAR *)Digest, 4);
-    NdisZeroMemory(pCtx, sizeof(pCtx)); // memory free
-}
-
-
-/*
- *  Function Description:
- *      The central algorithm of MD5, consists of four rounds and sixteen
- *  	steps per round
- *
- *  Arguments:
- *      Buf     Buffers of four states (output: 16 bytes)
- * 	    Mes     Input data (input: 64 bytes)
- *
- *  Return Value:
- *      None
- *
- *  Note:
- *      Called by MD5Update or MD5Final
- */
-VOID MD5Transform(UINT32 Buf[4], UINT32 Mes[16])
-{
-    UINT32 Reg[4], Temp;
-	unsigned int i;
-
-    static UCHAR LShiftVal[16] =
-    {
-        7, 12, 17, 22,
-		5, 9 , 14, 20,
-		4, 11, 16, 23,
- 		6, 10, 15, 21,
- 	};
-
-
-	// [equal to 4294967296*abs(sin(index))]
-    static UINT32 MD5Table[64] =
-	{
-		0xd76aa478,	0xe8c7b756,	0x242070db,	0xc1bdceee,
-		0xf57c0faf,	0x4787c62a,	0xa8304613, 0xfd469501,
-		0x698098d8,	0x8b44f7af,	0xffff5bb1,	0x895cd7be,
-    	0x6b901122,	0xfd987193,	0xa679438e,	0x49b40821,
-
-    	0xf61e2562,	0xc040b340,	0x265e5a51,	0xe9b6c7aa,
-    	0xd62f105d,	0x02441453,	0xd8a1e681,	0xe7d3fbc8,
-    	0x21e1cde6,	0xc33707d6,	0xf4d50d87,	0x455a14ed,
-    	0xa9e3e905,	0xfcefa3f8,	0x676f02d9,	0x8d2a4c8a,
-
-    	0xfffa3942,	0x8771f681,	0x6d9d6122,	0xfde5380c,
-    	0xa4beea44,	0x4bdecfa9,	0xf6bb4b60,	0xbebfbc70,
-    	0x289b7ec6,	0xeaa127fa,	0xd4ef3085,	0x04881d05,
-    	0xd9d4d039,	0xe6db99e5,	0x1fa27cf8,	0xc4ac5665,
-
-    	0xf4292244,	0x432aff97,	0xab9423a7,	0xfc93a039,
-   		0x655b59c3,	0x8f0ccc92,	0xffeff47d,	0x85845dd1,
-    	0x6fa87e4f,	0xfe2ce6e0,	0xa3014314,	0x4e0811a1,
-    	0xf7537e82,	0xbd3af235,	0x2ad7d2bb,	0xeb86d391
-	};
-
-
-    for (i=0; i<4; i++)
-        Reg[i]=Buf[i];
-
-
-    // 64 steps in MD5 algorithm
-    for (i=0; i<16; i++)
-    {
-        MD5Step(MD5_F1, Reg[0], Reg[1], Reg[2], Reg[3], Mes[i],
-                MD5Table[i], LShiftVal[i & 0x3]);
-
-        // one-word right shift
-        Temp   = Reg[3];
-        Reg[3] = Reg[2];
-        Reg[2] = Reg[1];
-        Reg[1] = Reg[0];
-        Reg[0] = Temp;
-    }
-    for (i=16; i<32; i++)
-    {
-        MD5Step(MD5_F2, Reg[0], Reg[1], Reg[2], Reg[3], Mes[(5*(i & 0xf)+1) & 0xf],
-                MD5Table[i], LShiftVal[(0x1 << 2)+(i & 0x3)]);
-
-        // one-word right shift
-        Temp   = Reg[3];
-        Reg[3] = Reg[2];
-        Reg[2] = Reg[1];
-        Reg[1] = Reg[0];
-        Reg[0] = Temp;
-    }
-    for (i=32; i<48; i++)
-    {
-        MD5Step(MD5_F3, Reg[0], Reg[1], Reg[2], Reg[3], Mes[(3*(i & 0xf)+5) & 0xf],
-                MD5Table[i], LShiftVal[(0x1 << 3)+(i & 0x3)]);
-
-        // one-word right shift
-        Temp   = Reg[3];
-        Reg[3] = Reg[2];
-        Reg[2] = Reg[1];
-        Reg[1] = Reg[0];
-        Reg[0] = Temp;
-    }
-    for (i=48; i<64; i++)
-    {
-        MD5Step(MD5_F4, Reg[0], Reg[1], Reg[2], Reg[3], Mes[(7*(i & 0xf)) & 0xf],
-                MD5Table[i], LShiftVal[(0x3 << 2)+(i & 0x3)]);
-
-        // one-word right shift
-        Temp   = Reg[3];
-        Reg[3] = Reg[2];
-        Reg[2] = Reg[1];
-        Reg[1] = Reg[0];
-        Reg[0] = Temp;
-    }
-
-
-    // (temporary)output
-    for (i=0; i<4; i++)
-        Buf[i] += Reg[i];
-
-}
-
-
-
-/* =========================  SHA-1 implementation ========================== */
-// four base functions for SHA-1
-#define SHA1_F1(b, c, d)    (((b) & (c)) | ((~b) & (d)))
-#define SHA1_F2(b, c, d)    ((b) ^ (c) ^ (d))
-#define SHA1_F3(b, c, d)    (((b) & (c)) | ((b) & (d)) | ((c) & (d)))
-
-
-#define SHA1Step(f, a, b, c, d, e, w, k)    \
-    ( e	+= ( f(b, c, d) + w + k + CYCLIC_LEFT_SHIFT(a, 5)) & 0xffffffff, \
-      b = CYCLIC_LEFT_SHIFT(b, 30) )
-
-//Initiate SHA-1 Context satisfied in RFC 3174
-VOID SHAInit(SHA_CTX *pCtx)
-{
-    pCtx->Buf[0]=0x67452301;
-    pCtx->Buf[1]=0xefcdab89;
-    pCtx->Buf[2]=0x98badcfe;
-    pCtx->Buf[3]=0x10325476;
-    pCtx->Buf[4]=0xc3d2e1f0;
-
-    pCtx->LenInBitCount[0]=0;
-    pCtx->LenInBitCount[1]=0;
-}
-
-/*
- *  Function Description:
- *      Update SHA-1 Context, allow of an arrary of octets as the next
- *      portion of the message
- *
- *  Arguments:
- *      pCtx		Pointer	to SHA-1 context
- * 	    pData       Pointer to input data
- *      LenInBytes  The length of input data (unit: byte)
- *
- *  Return Value:
- *      error       indicate more than pow(2,64) bits of data
- *
- *  Note:
- *      Called after SHAInit or SHAUpdate(itself)
- */
-UCHAR SHAUpdate(SHA_CTX *pCtx, UCHAR *pData, UINT32 LenInBytes)
-{
-    UINT32 TfTimes;
-    UINT32 temp1,temp2;
-	unsigned int i;
-	UCHAR err=1;
-
-    temp1 = pCtx->LenInBitCount[0];
-    temp2 = pCtx->LenInBitCount[1];
-
-    pCtx->LenInBitCount[0] = (UINT32) (pCtx->LenInBitCount[0] + (LenInBytes << 3));
-    if (pCtx->LenInBitCount[0] < temp1)
-        pCtx->LenInBitCount[1]++;   //carry in
-
-
-    pCtx->LenInBitCount[1] = (UINT32) (pCtx->LenInBitCount[1] +(LenInBytes >> 29));
-    if (pCtx->LenInBitCount[1] < temp2)
-        return (err);   //check total length of original data
-
-
-    // mod 64 bytes
-    temp1 = (temp1 >> 3) & 0x3f;
-
-    // process lacks of 64-byte data
-    if (temp1)
-    {
-        UCHAR *pAds = (UCHAR *) pCtx->Input + temp1;
-
-        if ((temp1+LenInBytes) < 64)
-        {
-            NdisMoveMemory(pAds, (UCHAR *)pData, LenInBytes);
-            return (0);
-        }
-
-        NdisMoveMemory(pAds, (UCHAR *)pData, 64-temp1);
-        byteReverse((UCHAR *)pCtx->Input, 16);
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
-        SHATransform(pCtx->Buf, (UINT32 *)pCtx->Input);
-
-        pData += 64-temp1;
-        LenInBytes -= 64-temp1;
-    } // end of if (temp1)
-
-
-    TfTimes = (LenInBytes >> 6);
-
-    for (i=TfTimes; i>0; i--)
-    {
-        NdisMoveMemory(pCtx->Input, (UCHAR *)pData, 64);
-        byteReverse((UCHAR *)pCtx->Input, 16);
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
-        SHATransform(pCtx->Buf, (UINT32 *)pCtx->Input);
-        pData += 64;
-        LenInBytes -= 64;
-    } // end of for
-
-    // buffering lacks of 64-byte data
-    if(LenInBytes)
-        NdisMoveMemory(pCtx->Input, (UCHAR *)pData, LenInBytes);
-
-	return (0);
-
-}
-
-// Append padding bits and length of original message in the tail
-// The message digest has to be completed in the end
-VOID SHAFinal(SHA_CTX *pCtx, UCHAR Digest[20])
-{
-    UCHAR Remainder;
-    UCHAR PadLenInBytes;
-    UCHAR *pAppend=0;
-    unsigned int i;
-
-    Remainder = (UCHAR)((pCtx->LenInBitCount[0] >> 3) & 0x3f);
-
-    pAppend = (UCHAR *)pCtx->Input + Remainder;
-
-    PadLenInBytes = (Remainder < 56) ? (56-Remainder) : (120-Remainder);
-
-    // padding bits without crossing block(64-byte based) boundary
-    if (Remainder < 56)
-    {
-        *pAppend = 0x80;
-        PadLenInBytes --;
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, PadLenInBytes);
-
-		// add data-length field, from high to low
-        for (i=0; i<4; i++)
-        {
-        	pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[1] >> ((3-i) << 3)) & 0xff);
-        	pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[0] >> ((3-i) << 3)) & 0xff);
-      	}
-
-        byteReverse((UCHAR *)pCtx->Input, 16);
-        NdisZeroMemory((UCHAR *)pCtx->Input + 64, 14);
-        SHATransform(pCtx->Buf, (UINT32 *)pCtx->Input);
-    } // end of if
-
-    // padding bits with crossing block(64-byte based) boundary
-    else
-    {
-        // the first block ===
-        *pAppend = 0x80;
-        PadLenInBytes --;
-
-        NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, (64-Remainder-1));
-        PadLenInBytes -= (64 - Remainder - 1);
-
-        byteReverse((UCHAR *)pCtx->Input, 16);
-        NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
-        SHATransform(pCtx->Buf, (UINT32 *)pCtx->Input);
-
-
-        // the second block ===
-        NdisZeroMemory((UCHAR *)pCtx->Input, PadLenInBytes);
-
-		// add data-length field
-		for (i=0; i<4; i++)
-        {
-        	pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[1] >> ((3-i) << 3)) & 0xff);
-        	pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[0] >> ((3-i) << 3)) & 0xff);
-      	}
-
-        byteReverse((UCHAR *)pCtx->Input, 16);
-        NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
-        SHATransform(pCtx->Buf, (UINT32 *)pCtx->Input);
-    } // end of else
-
-
-    //Output, bytereverse
-    for (i=0; i<20; i++)
-    {
-        Digest [i] = (UCHAR)(pCtx->Buf[i>>2] >> 8*(3-(i & 0x3)));
-    }
-
-    NdisZeroMemory(pCtx, sizeof(pCtx)); // memory free
-}
-
-
-// The central algorithm of SHA-1, consists of four rounds and
-// twenty steps per round
-VOID SHATransform(UINT32 Buf[5], UINT32 Mes[20])
-{
-    UINT32 Reg[5],Temp;
-	unsigned int i;
-    UINT32 W[80];
-
-    static UINT32 SHA1Table[4] = { 0x5a827999, 0x6ed9eba1,
-                                  0x8f1bbcdc, 0xca62c1d6 };
-
-    Reg[0]=Buf[0];
-	Reg[1]=Buf[1];
-	Reg[2]=Buf[2];
-	Reg[3]=Buf[3];
-	Reg[4]=Buf[4];
-
-    //the first octet of a word is stored in the 0th element, bytereverse
-	for(i = 0; i < 16; i++)
-    {
-    	W[i]  = (Mes[i] >> 24) & 0xff;
-        W[i] |= (Mes[i] >> 8 ) & 0xff00;
-        W[i] |= (Mes[i] << 8 ) & 0xff0000;
-        W[i] |= (Mes[i] << 24) & 0xff000000;
-    }
-
-
-    for	(i = 0; i < 64; i++)
-	    W[16+i] = CYCLIC_LEFT_SHIFT(W[i] ^ W[2+i] ^ W[8+i] ^ W[13+i], 1);
-
-
-    // 80 steps in SHA-1 algorithm
-    for (i=0; i<80; i++)
-    {
-        if (i<20)
-            SHA1Step(SHA1_F1, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
-                     W[i], SHA1Table[0]);
-
-        else if (i>=20 && i<40)
-            SHA1Step(SHA1_F2, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
-                     W[i], SHA1Table[1]);
-
-		else if (i>=40 && i<60)
-            SHA1Step(SHA1_F3, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
-                      W[i], SHA1Table[2]);
-
-        else
-            SHA1Step(SHA1_F2, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
-                     W[i], SHA1Table[3]);
-
-
-       // one-word right shift
-		Temp   = Reg[4];
-        Reg[4] = Reg[3];
-        Reg[3] = Reg[2];
-        Reg[2] = Reg[1];
-        Reg[1] = Reg[0];
-        Reg[0] = Temp;
-
-    } // end of for-loop
-
-
-    // (temporary)output
-    for (i=0; i<5; i++)
-        Buf[i] += Reg[i];
-
-}
-
-
-/* =========================  AES En/Decryption ========================== */
-
-/* forward S-box */
-static uint32 FSb[256] =
-{
-	0x63, 0x7C,	0x77, 0x7B,	0xF2, 0x6B,	0x6F, 0xC5,
-	0x30, 0x01,	0x67, 0x2B,	0xFE, 0xD7,	0xAB, 0x76,
-	0xCA, 0x82,	0xC9, 0x7D,	0xFA, 0x59,	0x47, 0xF0,
-	0xAD, 0xD4,	0xA2, 0xAF,	0x9C, 0xA4,	0x72, 0xC0,
-	0xB7, 0xFD,	0x93, 0x26,	0x36, 0x3F,	0xF7, 0xCC,
-	0x34, 0xA5,	0xE5, 0xF1,	0x71, 0xD8,	0x31, 0x15,
-	0x04, 0xC7,	0x23, 0xC3,	0x18, 0x96,	0x05, 0x9A,
-	0x07, 0x12,	0x80, 0xE2,	0xEB, 0x27,	0xB2, 0x75,
-	0x09, 0x83,	0x2C, 0x1A,	0x1B, 0x6E,	0x5A, 0xA0,
-	0x52, 0x3B,	0xD6, 0xB3,	0x29, 0xE3,	0x2F, 0x84,
-	0x53, 0xD1,	0x00, 0xED,	0x20, 0xFC,	0xB1, 0x5B,
-	0x6A, 0xCB,	0xBE, 0x39,	0x4A, 0x4C,	0x58, 0xCF,
-	0xD0, 0xEF,	0xAA, 0xFB,	0x43, 0x4D,	0x33, 0x85,
-	0x45, 0xF9,	0x02, 0x7F,	0x50, 0x3C,	0x9F, 0xA8,
-	0x51, 0xA3,	0x40, 0x8F,	0x92, 0x9D,	0x38, 0xF5,
-	0xBC, 0xB6,	0xDA, 0x21,	0x10, 0xFF,	0xF3, 0xD2,
-	0xCD, 0x0C,	0x13, 0xEC,	0x5F, 0x97,	0x44, 0x17,
-	0xC4, 0xA7,	0x7E, 0x3D,	0x64, 0x5D,	0x19, 0x73,
-	0x60, 0x81,	0x4F, 0xDC,	0x22, 0x2A,	0x90, 0x88,
-	0x46, 0xEE,	0xB8, 0x14,	0xDE, 0x5E,	0x0B, 0xDB,
-	0xE0, 0x32,	0x3A, 0x0A,	0x49, 0x06,	0x24, 0x5C,
-	0xC2, 0xD3,	0xAC, 0x62,	0x91, 0x95,	0xE4, 0x79,
-	0xE7, 0xC8,	0x37, 0x6D,	0x8D, 0xD5,	0x4E, 0xA9,
-	0x6C, 0x56,	0xF4, 0xEA,	0x65, 0x7A,	0xAE, 0x08,
-	0xBA, 0x78,	0x25, 0x2E,	0x1C, 0xA6,	0xB4, 0xC6,
-	0xE8, 0xDD,	0x74, 0x1F,	0x4B, 0xBD,	0x8B, 0x8A,
-	0x70, 0x3E,	0xB5, 0x66,	0x48, 0x03,	0xF6, 0x0E,
-	0x61, 0x35,	0x57, 0xB9,	0x86, 0xC1,	0x1D, 0x9E,
-	0xE1, 0xF8,	0x98, 0x11,	0x69, 0xD9,	0x8E, 0x94,
-	0x9B, 0x1E,	0x87, 0xE9,	0xCE, 0x55,	0x28, 0xDF,
-	0x8C, 0xA1,	0x89, 0x0D,	0xBF, 0xE6,	0x42, 0x68,
-	0x41, 0x99,	0x2D, 0x0F,	0xB0, 0x54,	0xBB, 0x16
-};
-
-/* forward table */
-#define	FT \
-\
-	V(C6,63,63,A5),	V(F8,7C,7C,84),	V(EE,77,77,99),	V(F6,7B,7B,8D),	\
-	V(FF,F2,F2,0D),	V(D6,6B,6B,BD),	V(DE,6F,6F,B1),	V(91,C5,C5,54),	\
-	V(60,30,30,50),	V(02,01,01,03),	V(CE,67,67,A9),	V(56,2B,2B,7D),	\
-	V(E7,FE,FE,19),	V(B5,D7,D7,62),	V(4D,AB,AB,E6),	V(EC,76,76,9A),	\
-	V(8F,CA,CA,45),	V(1F,82,82,9D),	V(89,C9,C9,40),	V(FA,7D,7D,87),	\
-	V(EF,FA,FA,15),	V(B2,59,59,EB),	V(8E,47,47,C9),	V(FB,F0,F0,0B),	\
-	V(41,AD,AD,EC),	V(B3,D4,D4,67),	V(5F,A2,A2,FD),	V(45,AF,AF,EA),	\
-	V(23,9C,9C,BF),	V(53,A4,A4,F7),	V(E4,72,72,96),	V(9B,C0,C0,5B),	\
-	V(75,B7,B7,C2),	V(E1,FD,FD,1C),	V(3D,93,93,AE),	V(4C,26,26,6A),	\
-	V(6C,36,36,5A),	V(7E,3F,3F,41),	V(F5,F7,F7,02),	V(83,CC,CC,4F),	\
-	V(68,34,34,5C),	V(51,A5,A5,F4),	V(D1,E5,E5,34),	V(F9,F1,F1,08),	\
-	V(E2,71,71,93),	V(AB,D8,D8,73),	V(62,31,31,53),	V(2A,15,15,3F),	\
-	V(08,04,04,0C),	V(95,C7,C7,52),	V(46,23,23,65),	V(9D,C3,C3,5E),	\
-	V(30,18,18,28),	V(37,96,96,A1),	V(0A,05,05,0F),	V(2F,9A,9A,B5),	\
-	V(0E,07,07,09),	V(24,12,12,36),	V(1B,80,80,9B),	V(DF,E2,E2,3D),	\
-	V(CD,EB,EB,26),	V(4E,27,27,69),	V(7F,B2,B2,CD),	V(EA,75,75,9F),	\
-	V(12,09,09,1B),	V(1D,83,83,9E),	V(58,2C,2C,74),	V(34,1A,1A,2E),	\
-	V(36,1B,1B,2D),	V(DC,6E,6E,B2),	V(B4,5A,5A,EE),	V(5B,A0,A0,FB),	\
-	V(A4,52,52,F6),	V(76,3B,3B,4D),	V(B7,D6,D6,61),	V(7D,B3,B3,CE),	\
-	V(52,29,29,7B),	V(DD,E3,E3,3E),	V(5E,2F,2F,71),	V(13,84,84,97),	\
-	V(A6,53,53,F5),	V(B9,D1,D1,68),	V(00,00,00,00),	V(C1,ED,ED,2C),	\
-	V(40,20,20,60),	V(E3,FC,FC,1F),	V(79,B1,B1,C8),	V(B6,5B,5B,ED),	\
-	V(D4,6A,6A,BE),	V(8D,CB,CB,46),	V(67,BE,BE,D9),	V(72,39,39,4B),	\
-	V(94,4A,4A,DE),	V(98,4C,4C,D4),	V(B0,58,58,E8),	V(85,CF,CF,4A),	\
-	V(BB,D0,D0,6B),	V(C5,EF,EF,2A),	V(4F,AA,AA,E5),	V(ED,FB,FB,16),	\
-	V(86,43,43,C5),	V(9A,4D,4D,D7),	V(66,33,33,55),	V(11,85,85,94),	\
-	V(8A,45,45,CF),	V(E9,F9,F9,10),	V(04,02,02,06),	V(FE,7F,7F,81),	\
-	V(A0,50,50,F0),	V(78,3C,3C,44),	V(25,9F,9F,BA),	V(4B,A8,A8,E3),	\
-	V(A2,51,51,F3),	V(5D,A3,A3,FE),	V(80,40,40,C0),	V(05,8F,8F,8A),	\
-	V(3F,92,92,AD),	V(21,9D,9D,BC),	V(70,38,38,48),	V(F1,F5,F5,04),	\
-	V(63,BC,BC,DF),	V(77,B6,B6,C1),	V(AF,DA,DA,75),	V(42,21,21,63),	\
-	V(20,10,10,30),	V(E5,FF,FF,1A),	V(FD,F3,F3,0E),	V(BF,D2,D2,6D),	\
-	V(81,CD,CD,4C),	V(18,0C,0C,14),	V(26,13,13,35),	V(C3,EC,EC,2F),	\
-	V(BE,5F,5F,E1),	V(35,97,97,A2),	V(88,44,44,CC),	V(2E,17,17,39),	\
-	V(93,C4,C4,57),	V(55,A7,A7,F2),	V(FC,7E,7E,82),	V(7A,3D,3D,47),	\
-	V(C8,64,64,AC),	V(BA,5D,5D,E7),	V(32,19,19,2B),	V(E6,73,73,95),	\
-	V(C0,60,60,A0),	V(19,81,81,98),	V(9E,4F,4F,D1),	V(A3,DC,DC,7F),	\
-	V(44,22,22,66),	V(54,2A,2A,7E),	V(3B,90,90,AB),	V(0B,88,88,83),	\
-	V(8C,46,46,CA),	V(C7,EE,EE,29),	V(6B,B8,B8,D3),	V(28,14,14,3C),	\
-	V(A7,DE,DE,79),	V(BC,5E,5E,E2),	V(16,0B,0B,1D),	V(AD,DB,DB,76),	\
-	V(DB,E0,E0,3B),	V(64,32,32,56),	V(74,3A,3A,4E),	V(14,0A,0A,1E),	\
-	V(92,49,49,DB),	V(0C,06,06,0A),	V(48,24,24,6C),	V(B8,5C,5C,E4),	\
-	V(9F,C2,C2,5D),	V(BD,D3,D3,6E),	V(43,AC,AC,EF),	V(C4,62,62,A6),	\
-	V(39,91,91,A8),	V(31,95,95,A4),	V(D3,E4,E4,37),	V(F2,79,79,8B),	\
-	V(D5,E7,E7,32),	V(8B,C8,C8,43),	V(6E,37,37,59),	V(DA,6D,6D,B7),	\
-	V(01,8D,8D,8C),	V(B1,D5,D5,64),	V(9C,4E,4E,D2),	V(49,A9,A9,E0),	\
-	V(D8,6C,6C,B4),	V(AC,56,56,FA),	V(F3,F4,F4,07),	V(CF,EA,EA,25),	\
-	V(CA,65,65,AF),	V(F4,7A,7A,8E),	V(47,AE,AE,E9),	V(10,08,08,18),	\
-	V(6F,BA,BA,D5),	V(F0,78,78,88),	V(4A,25,25,6F),	V(5C,2E,2E,72),	\
-	V(38,1C,1C,24),	V(57,A6,A6,F1),	V(73,B4,B4,C7),	V(97,C6,C6,51),	\
-	V(CB,E8,E8,23),	V(A1,DD,DD,7C),	V(E8,74,74,9C),	V(3E,1F,1F,21),	\
-	V(96,4B,4B,DD),	V(61,BD,BD,DC),	V(0D,8B,8B,86),	V(0F,8A,8A,85),	\
-	V(E0,70,70,90),	V(7C,3E,3E,42),	V(71,B5,B5,C4),	V(CC,66,66,AA),	\
-	V(90,48,48,D8),	V(06,03,03,05),	V(F7,F6,F6,01),	V(1C,0E,0E,12),	\
-	V(C2,61,61,A3),	V(6A,35,35,5F),	V(AE,57,57,F9),	V(69,B9,B9,D0),	\
-	V(17,86,86,91),	V(99,C1,C1,58),	V(3A,1D,1D,27),	V(27,9E,9E,B9),	\
-	V(D9,E1,E1,38),	V(EB,F8,F8,13),	V(2B,98,98,B3),	V(22,11,11,33),	\
-	V(D2,69,69,BB),	V(A9,D9,D9,70),	V(07,8E,8E,89),	V(33,94,94,A7),	\
-	V(2D,9B,9B,B6),	V(3C,1E,1E,22),	V(15,87,87,92),	V(C9,E9,E9,20),	\
-	V(87,CE,CE,49),	V(AA,55,55,FF),	V(50,28,28,78),	V(A5,DF,DF,7A),	\
-	V(03,8C,8C,8F),	V(59,A1,A1,F8),	V(09,89,89,80),	V(1A,0D,0D,17),	\
-	V(65,BF,BF,DA),	V(D7,E6,E6,31),	V(84,42,42,C6),	V(D0,68,68,B8),	\
-	V(82,41,41,C3),	V(29,99,99,B0),	V(5A,2D,2D,77),	V(1E,0F,0F,11),	\
-	V(7B,B0,B0,CB),	V(A8,54,54,FC),	V(6D,BB,BB,D6),	V(2C,16,16,3A)
-
-#define	V(a,b,c,d) 0x##a##b##c##d
-static uint32 FT0[256] = { FT };
-#undef V
-
-#define	V(a,b,c,d) 0x##d##a##b##c
-static uint32 FT1[256] = { FT };
-#undef V
-
-#define	V(a,b,c,d) 0x##c##d##a##b
-static uint32 FT2[256] = { FT };
-#undef V
-
-#define	V(a,b,c,d) 0x##b##c##d##a
-static uint32 FT3[256] = { FT };
-#undef V
-
-#undef FT
-
-/* reverse S-box */
-
-static uint32 RSb[256] =
-{
-	0x52, 0x09,	0x6A, 0xD5,	0x30, 0x36,	0xA5, 0x38,
-	0xBF, 0x40,	0xA3, 0x9E,	0x81, 0xF3,	0xD7, 0xFB,
-	0x7C, 0xE3,	0x39, 0x82,	0x9B, 0x2F,	0xFF, 0x87,
-	0x34, 0x8E,	0x43, 0x44,	0xC4, 0xDE,	0xE9, 0xCB,
-	0x54, 0x7B,	0x94, 0x32,	0xA6, 0xC2,	0x23, 0x3D,
-	0xEE, 0x4C,	0x95, 0x0B,	0x42, 0xFA,	0xC3, 0x4E,
-	0x08, 0x2E,	0xA1, 0x66,	0x28, 0xD9,	0x24, 0xB2,
-	0x76, 0x5B,	0xA2, 0x49,	0x6D, 0x8B,	0xD1, 0x25,
-	0x72, 0xF8,	0xF6, 0x64,	0x86, 0x68,	0x98, 0x16,
-	0xD4, 0xA4,	0x5C, 0xCC,	0x5D, 0x65,	0xB6, 0x92,
-	0x6C, 0x70,	0x48, 0x50,	0xFD, 0xED,	0xB9, 0xDA,
-	0x5E, 0x15,	0x46, 0x57,	0xA7, 0x8D,	0x9D, 0x84,
-	0x90, 0xD8,	0xAB, 0x00,	0x8C, 0xBC,	0xD3, 0x0A,
-	0xF7, 0xE4,	0x58, 0x05,	0xB8, 0xB3,	0x45, 0x06,
-	0xD0, 0x2C,	0x1E, 0x8F,	0xCA, 0x3F,	0x0F, 0x02,
-	0xC1, 0xAF,	0xBD, 0x03,	0x01, 0x13,	0x8A, 0x6B,
-	0x3A, 0x91,	0x11, 0x41,	0x4F, 0x67,	0xDC, 0xEA,
-	0x97, 0xF2,	0xCF, 0xCE,	0xF0, 0xB4,	0xE6, 0x73,
-	0x96, 0xAC,	0x74, 0x22,	0xE7, 0xAD,	0x35, 0x85,
-	0xE2, 0xF9,	0x37, 0xE8,	0x1C, 0x75,	0xDF, 0x6E,
-	0x47, 0xF1,	0x1A, 0x71,	0x1D, 0x29,	0xC5, 0x89,
-	0x6F, 0xB7,	0x62, 0x0E,	0xAA, 0x18,	0xBE, 0x1B,
-	0xFC, 0x56,	0x3E, 0x4B,	0xC6, 0xD2,	0x79, 0x20,
-	0x9A, 0xDB,	0xC0, 0xFE,	0x78, 0xCD,	0x5A, 0xF4,
-	0x1F, 0xDD,	0xA8, 0x33,	0x88, 0x07,	0xC7, 0x31,
-	0xB1, 0x12,	0x10, 0x59,	0x27, 0x80,	0xEC, 0x5F,
-	0x60, 0x51,	0x7F, 0xA9,	0x19, 0xB5,	0x4A, 0x0D,
-	0x2D, 0xE5,	0x7A, 0x9F,	0x93, 0xC9,	0x9C, 0xEF,
-	0xA0, 0xE0,	0x3B, 0x4D,	0xAE, 0x2A,	0xF5, 0xB0,
-	0xC8, 0xEB,	0xBB, 0x3C,	0x83, 0x53,	0x99, 0x61,
-	0x17, 0x2B,	0x04, 0x7E,	0xBA, 0x77,	0xD6, 0x26,
-	0xE1, 0x69,	0x14, 0x63,	0x55, 0x21,	0x0C, 0x7D
-};
-
-/* reverse table */
-
-#define	RT \
-\
-	V(51,F4,A7,50),	V(7E,41,65,53),	V(1A,17,A4,C3),	V(3A,27,5E,96),	\
-	V(3B,AB,6B,CB),	V(1F,9D,45,F1),	V(AC,FA,58,AB),	V(4B,E3,03,93),	\
-	V(20,30,FA,55),	V(AD,76,6D,F6),	V(88,CC,76,91),	V(F5,02,4C,25),	\
-	V(4F,E5,D7,FC),	V(C5,2A,CB,D7),	V(26,35,44,80),	V(B5,62,A3,8F),	\
-	V(DE,B1,5A,49),	V(25,BA,1B,67),	V(45,EA,0E,98),	V(5D,FE,C0,E1),	\
-	V(C3,2F,75,02),	V(81,4C,F0,12),	V(8D,46,97,A3),	V(6B,D3,F9,C6),	\
-	V(03,8F,5F,E7),	V(15,92,9C,95),	V(BF,6D,7A,EB),	V(95,52,59,DA),	\
-	V(D4,BE,83,2D),	V(58,74,21,D3),	V(49,E0,69,29),	V(8E,C9,C8,44),	\
-	V(75,C2,89,6A),	V(F4,8E,79,78),	V(99,58,3E,6B),	V(27,B9,71,DD),	\
-	V(BE,E1,4F,B6),	V(F0,88,AD,17),	V(C9,20,AC,66),	V(7D,CE,3A,B4),	\
-	V(63,DF,4A,18),	V(E5,1A,31,82),	V(97,51,33,60),	V(62,53,7F,45),	\
-	V(B1,64,77,E0),	V(BB,6B,AE,84),	V(FE,81,A0,1C),	V(F9,08,2B,94),	\
-	V(70,48,68,58),	V(8F,45,FD,19),	V(94,DE,6C,87),	V(52,7B,F8,B7),	\
-	V(AB,73,D3,23),	V(72,4B,02,E2),	V(E3,1F,8F,57),	V(66,55,AB,2A),	\
-	V(B2,EB,28,07),	V(2F,B5,C2,03),	V(86,C5,7B,9A),	V(D3,37,08,A5),	\
-	V(30,28,87,F2),	V(23,BF,A5,B2),	V(02,03,6A,BA),	V(ED,16,82,5C),	\
-	V(8A,CF,1C,2B),	V(A7,79,B4,92),	V(F3,07,F2,F0),	V(4E,69,E2,A1),	\
-	V(65,DA,F4,CD),	V(06,05,BE,D5),	V(D1,34,62,1F),	V(C4,A6,FE,8A),	\
-	V(34,2E,53,9D),	V(A2,F3,55,A0),	V(05,8A,E1,32),	V(A4,F6,EB,75),	\
-	V(0B,83,EC,39),	V(40,60,EF,AA),	V(5E,71,9F,06),	V(BD,6E,10,51),	\
-	V(3E,21,8A,F9),	V(96,DD,06,3D),	V(DD,3E,05,AE),	V(4D,E6,BD,46),	\
-	V(91,54,8D,B5),	V(71,C4,5D,05),	V(04,06,D4,6F),	V(60,50,15,FF),	\
-	V(19,98,FB,24),	V(D6,BD,E9,97),	V(89,40,43,CC),	V(67,D9,9E,77),	\
-	V(B0,E8,42,BD),	V(07,89,8B,88),	V(E7,19,5B,38),	V(79,C8,EE,DB),	\
-	V(A1,7C,0A,47),	V(7C,42,0F,E9),	V(F8,84,1E,C9),	V(00,00,00,00),	\
-	V(09,80,86,83),	V(32,2B,ED,48),	V(1E,11,70,AC),	V(6C,5A,72,4E),	\
-	V(FD,0E,FF,FB),	V(0F,85,38,56),	V(3D,AE,D5,1E),	V(36,2D,39,27),	\
-	V(0A,0F,D9,64),	V(68,5C,A6,21),	V(9B,5B,54,D1),	V(24,36,2E,3A),	\
-	V(0C,0A,67,B1),	V(93,57,E7,0F),	V(B4,EE,96,D2),	V(1B,9B,91,9E),	\
-	V(80,C0,C5,4F),	V(61,DC,20,A2),	V(5A,77,4B,69),	V(1C,12,1A,16),	\
-	V(E2,93,BA,0A),	V(C0,A0,2A,E5),	V(3C,22,E0,43),	V(12,1B,17,1D),	\
-	V(0E,09,0D,0B),	V(F2,8B,C7,AD),	V(2D,B6,A8,B9),	V(14,1E,A9,C8),	\
-	V(57,F1,19,85),	V(AF,75,07,4C),	V(EE,99,DD,BB),	V(A3,7F,60,FD),	\
-	V(F7,01,26,9F),	V(5C,72,F5,BC),	V(44,66,3B,C5),	V(5B,FB,7E,34),	\
-	V(8B,43,29,76),	V(CB,23,C6,DC),	V(B6,ED,FC,68),	V(B8,E4,F1,63),	\
-	V(D7,31,DC,CA),	V(42,63,85,10),	V(13,97,22,40),	V(84,C6,11,20),	\
-	V(85,4A,24,7D),	V(D2,BB,3D,F8),	V(AE,F9,32,11),	V(C7,29,A1,6D),	\
-	V(1D,9E,2F,4B),	V(DC,B2,30,F3),	V(0D,86,52,EC),	V(77,C1,E3,D0),	\
-	V(2B,B3,16,6C),	V(A9,70,B9,99),	V(11,94,48,FA),	V(47,E9,64,22),	\
-	V(A8,FC,8C,C4),	V(A0,F0,3F,1A),	V(56,7D,2C,D8),	V(22,33,90,EF),	\
-	V(87,49,4E,C7),	V(D9,38,D1,C1),	V(8C,CA,A2,FE),	V(98,D4,0B,36),	\
-	V(A6,F5,81,CF),	V(A5,7A,DE,28),	V(DA,B7,8E,26),	V(3F,AD,BF,A4),	\
-	V(2C,3A,9D,E4),	V(50,78,92,0D),	V(6A,5F,CC,9B),	V(54,7E,46,62),	\
-	V(F6,8D,13,C2),	V(90,D8,B8,E8),	V(2E,39,F7,5E),	V(82,C3,AF,F5),	\
-	V(9F,5D,80,BE),	V(69,D0,93,7C),	V(6F,D5,2D,A9),	V(CF,25,12,B3),	\
-	V(C8,AC,99,3B),	V(10,18,7D,A7),	V(E8,9C,63,6E),	V(DB,3B,BB,7B),	\
-	V(CD,26,78,09),	V(6E,59,18,F4),	V(EC,9A,B7,01),	V(83,4F,9A,A8),	\
-	V(E6,95,6E,65),	V(AA,FF,E6,7E),	V(21,BC,CF,08),	V(EF,15,E8,E6),	\
-	V(BA,E7,9B,D9),	V(4A,6F,36,CE),	V(EA,9F,09,D4),	V(29,B0,7C,D6),	\
-	V(31,A4,B2,AF),	V(2A,3F,23,31),	V(C6,A5,94,30),	V(35,A2,66,C0),	\
-	V(74,4E,BC,37),	V(FC,82,CA,A6),	V(E0,90,D0,B0),	V(33,A7,D8,15),	\
-	V(F1,04,98,4A),	V(41,EC,DA,F7),	V(7F,CD,50,0E),	V(17,91,F6,2F),	\
-	V(76,4D,D6,8D),	V(43,EF,B0,4D),	V(CC,AA,4D,54),	V(E4,96,04,DF),	\
-	V(9E,D1,B5,E3),	V(4C,6A,88,1B),	V(C1,2C,1F,B8),	V(46,65,51,7F),	\
-	V(9D,5E,EA,04),	V(01,8C,35,5D),	V(FA,87,74,73),	V(FB,0B,41,2E),	\
-	V(B3,67,1D,5A),	V(92,DB,D2,52),	V(E9,10,56,33),	V(6D,D6,47,13),	\
-	V(9A,D7,61,8C),	V(37,A1,0C,7A),	V(59,F8,14,8E),	V(EB,13,3C,89),	\
-	V(CE,A9,27,EE),	V(B7,61,C9,35),	V(E1,1C,E5,ED),	V(7A,47,B1,3C),	\
-	V(9C,D2,DF,59),	V(55,F2,73,3F),	V(18,14,CE,79),	V(73,C7,37,BF),	\
-	V(53,F7,CD,EA),	V(5F,FD,AA,5B),	V(DF,3D,6F,14),	V(78,44,DB,86),	\
-	V(CA,AF,F3,81),	V(B9,68,C4,3E),	V(38,24,34,2C),	V(C2,A3,40,5F),	\
-	V(16,1D,C3,72),	V(BC,E2,25,0C),	V(28,3C,49,8B),	V(FF,0D,95,41),	\
-	V(39,A8,01,71),	V(08,0C,B3,DE),	V(D8,B4,E4,9C),	V(64,56,C1,90),	\
-	V(7B,CB,84,61),	V(D5,32,B6,70),	V(48,6C,5C,74),	V(D0,B8,57,42)
-
-#define	V(a,b,c,d) 0x##a##b##c##d
-static uint32 RT0[256] = { RT };
-#undef V
-
-#define	V(a,b,c,d) 0x##d##a##b##c
-static uint32 RT1[256] = { RT };
-#undef V
-
-#define	V(a,b,c,d) 0x##c##d##a##b
-static uint32 RT2[256] = { RT };
-#undef V
-
-#define	V(a,b,c,d) 0x##b##c##d##a
-static uint32 RT3[256] = { RT };
-#undef V
-
-#undef RT
-
-/* round constants */
-
-static uint32 RCON[10] =
-{
-	0x01000000,	0x02000000,	0x04000000,	0x08000000,
-	0x10000000,	0x20000000,	0x40000000,	0x80000000,
-	0x1B000000,	0x36000000
-};
-
-/* key schedule	tables */
-
-static int KT_init = 1;
-
-static uint32 KT0[256];
-static uint32 KT1[256];
-static uint32 KT2[256];
-static uint32 KT3[256];
-
-/* platform-independant	32-bit integer manipulation	macros */
-
-#define	GET_UINT32(n,b,i)						\
-{												\
-	(n)	= (	(uint32) (b)[(i)	] << 24	)		\
-		| (	(uint32) (b)[(i) + 1] << 16	)		\
-		| (	(uint32) (b)[(i) + 2] <<  8	)		\
-		| (	(uint32) (b)[(i) + 3]		);		\
-}
-
-#define	PUT_UINT32(n,b,i)						\
-{												\
-	(b)[(i)	   ] = (uint8) ( (n) >>	24 );		\
-	(b)[(i)	+ 1] = (uint8) ( (n) >>	16 );		\
-	(b)[(i)	+ 2] = (uint8) ( (n) >>	 8 );		\
-	(b)[(i)	+ 3] = (uint8) ( (n)	   );		\
-}
-
-/* AES key scheduling routine */
-
-int	rtmp_aes_set_key( aes_context *ctx, uint8 *key, int nbits )
-{
-	int	i;
-	uint32 *RK,	*SK;
-
-	switch(	nbits )
-	{
-		case 128: ctx->nr =	10;	break;
-		case 192: ctx->nr =	12;	break;
-		case 256: ctx->nr =	14;	break;
-		default	: return( 1	);
-	}
-
-	RK = ctx->erk;
-
-	for( i = 0;	i <	(nbits >> 5); i++ )
-	{
-		GET_UINT32(	RK[i], key,	i *	4 );
-	}
-
-	/* setup encryption	round keys */
-
-	switch(	nbits )
-	{
-	case 128:
-
-		for( i = 0;	i <	10;	i++, RK	+= 4 )
-		{
-			RK[4]  = RK[0] ^ RCON[i] ^
-						( FSb[ (uint8) ( RK[3] >> 16 ) ] <<	24 ) ^
-						( FSb[ (uint8) ( RK[3] >>  8 ) ] <<	16 ) ^
-						( FSb[ (uint8) ( RK[3]		 ) ] <<	 8 ) ^
-						( FSb[ (uint8) ( RK[3] >> 24 ) ]	   );
-
-			RK[5]  = RK[1] ^ RK[4];
-			RK[6]  = RK[2] ^ RK[5];
-			RK[7]  = RK[3] ^ RK[6];
-		}
-		break;
-
-	case 192:
-
-		for( i = 0;	i <	8; i++,	RK += 6	)
-		{
-			RK[6]  = RK[0] ^ RCON[i] ^
-						( FSb[ (uint8) ( RK[5] >> 16 ) ] <<	24 ) ^
-						( FSb[ (uint8) ( RK[5] >>  8 ) ] <<	16 ) ^
-						( FSb[ (uint8) ( RK[5]		 ) ] <<	 8 ) ^
-						( FSb[ (uint8) ( RK[5] >> 24 ) ]	   );
-
-			RK[7]  = RK[1] ^ RK[6];
-			RK[8]  = RK[2] ^ RK[7];
-			RK[9]  = RK[3] ^ RK[8];
-			RK[10] = RK[4] ^ RK[9];
-			RK[11] = RK[5] ^ RK[10];
-		}
-		break;
-
-	case 256:
-
-		for( i = 0;	i <	7; i++,	RK += 8	)
-		{
-			RK[8]  = RK[0] ^ RCON[i] ^
-						( FSb[ (uint8) ( RK[7] >> 16 ) ] <<	24 ) ^
-						( FSb[ (uint8) ( RK[7] >>  8 ) ] <<	16 ) ^
-						( FSb[ (uint8) ( RK[7]		 ) ] <<	 8 ) ^
-						( FSb[ (uint8) ( RK[7] >> 24 ) ]	   );
-
-			RK[9]  = RK[1] ^ RK[8];
-			RK[10] = RK[2] ^ RK[9];
-			RK[11] = RK[3] ^ RK[10];
-
-			RK[12] = RK[4] ^
-						( FSb[ (uint8) ( RK[11]	>> 24 )	] << 24	) ^
-						( FSb[ (uint8) ( RK[11]	>> 16 )	] << 16	) ^
-						( FSb[ (uint8) ( RK[11]	>>	8 )	] <<  8	) ^
-						( FSb[ (uint8) ( RK[11]		  )	]		);
-
-			RK[13] = RK[5] ^ RK[12];
-			RK[14] = RK[6] ^ RK[13];
-			RK[15] = RK[7] ^ RK[14];
-		}
-		break;
-	}
-
-	/* setup decryption	round keys */
-
-	if(	KT_init	)
-	{
-		for( i = 0;	i <	256; i++ )
-		{
-			KT0[i] = RT0[ FSb[i] ];
-			KT1[i] = RT1[ FSb[i] ];
-			KT2[i] = RT2[ FSb[i] ];
-			KT3[i] = RT3[ FSb[i] ];
-		}
-
-		KT_init	= 0;
-	}
-
-	SK = ctx->drk;
-
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-
-	for( i = 1;	i <	ctx->nr; i++ )
-	{
-		RK -= 8;
-
-		*SK++ =	KT0[ (uint8) ( *RK >> 24 ) ] ^
-				KT1[ (uint8) ( *RK >> 16 ) ] ^
-				KT2[ (uint8) ( *RK >>  8 ) ] ^
-				KT3[ (uint8) ( *RK		 ) ]; RK++;
-
-		*SK++ =	KT0[ (uint8) ( *RK >> 24 ) ] ^
-				KT1[ (uint8) ( *RK >> 16 ) ] ^
-				KT2[ (uint8) ( *RK >>  8 ) ] ^
-				KT3[ (uint8) ( *RK		 ) ]; RK++;
-
-		*SK++ =	KT0[ (uint8) ( *RK >> 24 ) ] ^
-				KT1[ (uint8) ( *RK >> 16 ) ] ^
-				KT2[ (uint8) ( *RK >>  8 ) ] ^
-				KT3[ (uint8) ( *RK		 ) ]; RK++;
-
-		*SK++ =	KT0[ (uint8) ( *RK >> 24 ) ] ^
-				KT1[ (uint8) ( *RK >> 16 ) ] ^
-				KT2[ (uint8) ( *RK >>  8 ) ] ^
-				KT3[ (uint8) ( *RK		 ) ]; RK++;
-	}
-
-	RK -= 8;
-
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-	*SK++ =	*RK++;
-
-	return(	0 );
-}
-
-/* AES 128-bit block encryption	routine	*/
-
-void rtmp_aes_encrypt(aes_context *ctx, uint8 input[16],	uint8 output[16] )
-{
-	uint32 *RK,	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3;
-
-	RK = ctx->erk;
-	GET_UINT32(	X0,	input,	0 ); X0	^= RK[0];
-	GET_UINT32(	X1,	input,	4 ); X1	^= RK[1];
-	GET_UINT32(	X2,	input,	8 ); X2	^= RK[2];
-	GET_UINT32(	X3,	input, 12 ); X3	^= RK[3];
-
-#define	AES_FROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3)		\
-{												\
-	RK += 4;									\
-												\
-	X0 = RK[0] ^ FT0[ (uint8) (	Y0 >> 24 ) ] ^	\
-				 FT1[ (uint8) (	Y1 >> 16 ) ] ^	\
-				 FT2[ (uint8) (	Y2 >>  8 ) ] ^	\
-				 FT3[ (uint8) (	Y3		 ) ];	\
-												\
-	X1 = RK[1] ^ FT0[ (uint8) (	Y1 >> 24 ) ] ^	\
-				 FT1[ (uint8) (	Y2 >> 16 ) ] ^	\
-				 FT2[ (uint8) (	Y3 >>  8 ) ] ^	\
-				 FT3[ (uint8) (	Y0		 ) ];	\
-												\
-	X2 = RK[2] ^ FT0[ (uint8) (	Y2 >> 24 ) ] ^	\
-				 FT1[ (uint8) (	Y3 >> 16 ) ] ^	\
-				 FT2[ (uint8) (	Y0 >>  8 ) ] ^	\
-				 FT3[ (uint8) (	Y1		 ) ];	\
-												\
-	X3 = RK[3] ^ FT0[ (uint8) (	Y3 >> 24 ) ] ^	\
-				 FT1[ (uint8) (	Y0 >> 16 ) ] ^	\
-				 FT2[ (uint8) (	Y1 >>  8 ) ] ^	\
-				 FT3[ (uint8) (	Y2		 ) ];	\
-}
-
-	AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 1 */
-	AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 2 */
-	AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 3 */
-	AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 4 */
-	AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 5 */
-	AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 6 */
-	AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 7 */
-	AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 8 */
-	AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 9 */
-
-	if(	ctx->nr	> 10 )
-	{
-		AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );	/* round 10	*/
-		AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );	/* round 11	*/
-	}
-
-	if(	ctx->nr	> 12 )
-	{
-		AES_FROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );	/* round 12	*/
-		AES_FROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );	/* round 13	*/
-	}
-
-	/* last	round */
-
-	RK += 4;
-
-	X0 = RK[0] ^ ( FSb[	(uint8)	( Y0 >>	24 ) ] << 24 ) ^
-				 ( FSb[	(uint8)	( Y1 >>	16 ) ] << 16 ) ^
-				 ( FSb[	(uint8)	( Y2 >>	 8 ) ] <<  8 ) ^
-				 ( FSb[	(uint8)	( Y3	   ) ]		 );
-
-	X1 = RK[1] ^ ( FSb[	(uint8)	( Y1 >>	24 ) ] << 24 ) ^
-				 ( FSb[	(uint8)	( Y2 >>	16 ) ] << 16 ) ^
-				 ( FSb[	(uint8)	( Y3 >>	 8 ) ] <<  8 ) ^
-				 ( FSb[	(uint8)	( Y0	   ) ]		 );
-
-	X2 = RK[2] ^ ( FSb[	(uint8)	( Y2 >>	24 ) ] << 24 ) ^
-				 ( FSb[	(uint8)	( Y3 >>	16 ) ] << 16 ) ^
-				 ( FSb[	(uint8)	( Y0 >>	 8 ) ] <<  8 ) ^
-				 ( FSb[	(uint8)	( Y1	   ) ]		 );
-
-	X3 = RK[3] ^ ( FSb[	(uint8)	( Y3 >>	24 ) ] << 24 ) ^
-				 ( FSb[	(uint8)	( Y0 >>	16 ) ] << 16 ) ^
-				 ( FSb[	(uint8)	( Y1 >>	 8 ) ] <<  8 ) ^
-				 ( FSb[	(uint8)	( Y2	   ) ]		 );
-
-	PUT_UINT32(	X0,	output,	 0 );
-	PUT_UINT32(	X1,	output,	 4 );
-	PUT_UINT32(	X2,	output,	 8 );
-	PUT_UINT32(	X3,	output,	12 );
-}
-
-/* AES 128-bit block decryption	routine	*/
-
-void rtmp_aes_decrypt( aes_context *ctx,	uint8 input[16], uint8 output[16] )
-{
-	uint32 *RK,	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3;
-
-	RK = ctx->drk;
-
-	GET_UINT32(	X0,	input,	0 ); X0	^= RK[0];
-	GET_UINT32(	X1,	input,	4 ); X1	^= RK[1];
-	GET_UINT32(	X2,	input,	8 ); X2	^= RK[2];
-	GET_UINT32(	X3,	input, 12 ); X3	^= RK[3];
-
-#define	AES_RROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3)		\
-{												\
-	RK += 4;									\
-												\
-	X0 = RK[0] ^ RT0[ (uint8) (	Y0 >> 24 ) ] ^	\
-				 RT1[ (uint8) (	Y3 >> 16 ) ] ^	\
-				 RT2[ (uint8) (	Y2 >>  8 ) ] ^	\
-				 RT3[ (uint8) (	Y1		 ) ];	\
-												\
-	X1 = RK[1] ^ RT0[ (uint8) (	Y1 >> 24 ) ] ^	\
-				 RT1[ (uint8) (	Y0 >> 16 ) ] ^	\
-				 RT2[ (uint8) (	Y3 >>  8 ) ] ^	\
-				 RT3[ (uint8) (	Y2		 ) ];	\
-												\
-	X2 = RK[2] ^ RT0[ (uint8) (	Y2 >> 24 ) ] ^	\
-				 RT1[ (uint8) (	Y1 >> 16 ) ] ^	\
-				 RT2[ (uint8) (	Y0 >>  8 ) ] ^	\
-				 RT3[ (uint8) (	Y3		 ) ];	\
-												\
-	X3 = RK[3] ^ RT0[ (uint8) (	Y3 >> 24 ) ] ^	\
-				 RT1[ (uint8) (	Y2 >> 16 ) ] ^	\
-				 RT2[ (uint8) (	Y1 >>  8 ) ] ^	\
-				 RT3[ (uint8) (	Y0		 ) ];	\
-}
-
-	AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 1 */
-	AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 2 */
-	AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 3 */
-	AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 4 */
-	AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 5 */
-	AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 6 */
-	AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 7 */
-	AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );		/* round 8 */
-	AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );		/* round 9 */
-
-	if(	ctx->nr	> 10 )
-	{
-		AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );	/* round 10	*/
-		AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );	/* round 11	*/
-	}
-
-	if(	ctx->nr	> 12 )
-	{
-		AES_RROUND(	X0,	X1,	X2,	X3,	Y0,	Y1,	Y2,	Y3 );	/* round 12	*/
-		AES_RROUND(	Y0,	Y1,	Y2,	Y3,	X0,	X1,	X2,	X3 );	/* round 13	*/
-	}
-
-	/* last	round */
-
-	RK += 4;
-
-	X0 = RK[0] ^ ( RSb[	(uint8)	( Y0 >>	24 ) ] << 24 ) ^
-				 ( RSb[	(uint8)	( Y3 >>	16 ) ] << 16 ) ^
-				 ( RSb[	(uint8)	( Y2 >>	 8 ) ] <<  8 ) ^
-				 ( RSb[	(uint8)	( Y1	   ) ]		 );
-
-	X1 = RK[1] ^ ( RSb[	(uint8)	( Y1 >>	24 ) ] << 24 ) ^
-				 ( RSb[	(uint8)	( Y0 >>	16 ) ] << 16 ) ^
-				 ( RSb[	(uint8)	( Y3 >>	 8 ) ] <<  8 ) ^
-				 ( RSb[	(uint8)	( Y2	   ) ]		 );
-
-	X2 = RK[2] ^ ( RSb[	(uint8)	( Y2 >>	24 ) ] << 24 ) ^
-				 ( RSb[	(uint8)	( Y1 >>	16 ) ] << 16 ) ^
-				 ( RSb[	(uint8)	( Y0 >>	 8 ) ] <<  8 ) ^
-				 ( RSb[	(uint8)	( Y3	   ) ]		 );
-
-	X3 = RK[3] ^ ( RSb[	(uint8)	( Y3 >>	24 ) ] << 24 ) ^
-				 ( RSb[	(uint8)	( Y2 >>	16 ) ] << 16 ) ^
-				 ( RSb[	(uint8)	( Y1 >>	 8 ) ] <<  8 ) ^
-				 ( RSb[	(uint8)	( Y0	   ) ]		 );
-
-	PUT_UINT32(	X0,	output,	 0 );
-	PUT_UINT32(	X1,	output,	 4 );
-	PUT_UINT32(	X2,	output,	 8 );
-	PUT_UINT32(	X3,	output,	12 );
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		SHA1 function
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	HMAC_SHA1(
-	IN	UCHAR	*text,
-	IN	UINT	text_len,
-	IN	UCHAR	*key,
-	IN	UINT	key_len,
-	IN	UCHAR	*digest)
-{
-	SHA_CTX	context;
-	UCHAR	k_ipad[65]; /* inner padding - key XORd with ipad	*/
-	UCHAR	k_opad[65]; /* outer padding - key XORd with opad	*/
-	INT		i;
-
-	// if key is longer	than 64	bytes reset	it to key=SHA1(key)
-	if (key_len	> 64)
-	{
-		SHA_CTX		 tctx;
-		SHAInit(&tctx);
-		SHAUpdate(&tctx, key, key_len);
-		SHAFinal(&tctx,	key);
-		key_len	= 20;
-	}
-	NdisZeroMemory(k_ipad, sizeof(k_ipad));
-	NdisZeroMemory(k_opad, sizeof(k_opad));
-	NdisMoveMemory(k_ipad, key,	key_len);
-	NdisMoveMemory(k_opad, key,	key_len);
-
-	// XOR key with	ipad and opad values
-	for	(i = 0;	i <	64;	i++)
-	{
-		k_ipad[i] ^= 0x36;
-		k_opad[i] ^= 0x5c;
-	}
-
-	// perform inner SHA1
-	SHAInit(&context); 						/* init context for 1st pass */
-	SHAUpdate(&context,	k_ipad,	64);		/*	start with inner pad */
-	SHAUpdate(&context,	text, text_len);	/*	then text of datagram */
-	SHAFinal(&context, digest);				/* finish up 1st pass */
-
-	//perform outer	SHA1
-	SHAInit(&context);					/* init context for 2nd pass */
-	SHAUpdate(&context,	k_opad,	64);	/*	start with outer pad */
-	SHAUpdate(&context,	digest,	20);	/*	then results of	1st	hash */
-	SHAFinal(&context, digest);			/* finish up 2nd pass */
-
-}
-
-/*
-* F(P, S, c, i) = U1 xor U2 xor ... Uc
-* U1 = PRF(P, S || Int(i))
-* U2 = PRF(P, U1)
-* Uc = PRF(P, Uc-1)
-*/
-
-void F(char *password, unsigned char *ssid, int ssidlength, int iterations, int count, unsigned char *output)
-{
-    unsigned char digest[36], digest1[SHA_DIGEST_LEN];
-    int i, j;
-
-    /* U1 = PRF(P, S || int(i)) */
-    memcpy(digest, ssid, ssidlength);
-    digest[ssidlength] = (unsigned char)((count>>24) & 0xff);
-    digest[ssidlength+1] = (unsigned char)((count>>16) & 0xff);
-    digest[ssidlength+2] = (unsigned char)((count>>8) & 0xff);
-    digest[ssidlength+3] = (unsigned char)(count & 0xff);
-    HMAC_SHA1(digest, ssidlength+4, (unsigned char*) password, (int) strlen(password), digest1); // for WPA update
-
-    /* output = U1 */
-    memcpy(output, digest1, SHA_DIGEST_LEN);
-
-    for (i = 1; i < iterations; i++)
-    {
-        /* Un = PRF(P, Un-1) */
-        HMAC_SHA1(digest1, SHA_DIGEST_LEN, (unsigned char*) password, (int) strlen(password), digest); // for WPA update
-        memcpy(digest1, digest, SHA_DIGEST_LEN);
-
-        /* output = output xor Un */
-        for (j = 0; j < SHA_DIGEST_LEN; j++)
-        {
-            output[j] ^= digest[j];
-        }
-    }
-}
-/*
-* password - ascii string up to 63 characters in length
-* ssid - octet string up to 32 octets
-* ssidlength - length of ssid in octets
-* output must be 40 octets in length and outputs 256 bits of key
-*/
-int PasswordHash(char *password, unsigned char *ssid, int ssidlength, unsigned char *output)
-{
-    if ((strlen(password) > 63) || (ssidlength > 32))
-        return 0;
-
-    F(password, ssid, ssidlength, 4096, 1, output);
-    F(password, ssid, ssidlength, 4096, 2, &output[SHA_DIGEST_LEN]);
-    return 1;
-}
-
-
+#include "../../rt2870/common/md5.c"
diff --git a/drivers/staging/rt3070/common/mlme.c b/drivers/staging/rt3070/common/mlme.c
index 0189bab..c2d0d4e 100644
--- a/drivers/staging/rt3070/common/mlme.c
+++ b/drivers/staging/rt3070/common/mlme.c
@@ -1,9136 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	mlme.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang	2004-08-25		Modify from RT2500 code base
-	John Chang	2004-09-06		modified for RT2600
-*/
-
-#include "../rt_config.h"
-#include <stdarg.h>
-
-UCHAR	CISCO_OUI[] = {0x00, 0x40, 0x96};
-
-UCHAR	WPA_OUI[] = {0x00, 0x50, 0xf2, 0x01};
-UCHAR	RSN_OUI[] = {0x00, 0x0f, 0xac};
-UCHAR	WAPI_OUI[] = {0x00, 0x14, 0x72};
-UCHAR   WME_INFO_ELEM[]  = {0x00, 0x50, 0xf2, 0x02, 0x00, 0x01};
-UCHAR   WME_PARM_ELEM[] = {0x00, 0x50, 0xf2, 0x02, 0x01, 0x01};
-UCHAR	Ccx2QosInfo[] = {0x00, 0x40, 0x96, 0x04};
-UCHAR   RALINK_OUI[]  = {0x00, 0x0c, 0x43};
-UCHAR   BROADCOM_OUI[]  = {0x00, 0x90, 0x4c};
-UCHAR   WPS_OUI[] = {0x00, 0x50, 0xf2, 0x04};
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
-UCHAR	PRE_N_HT_OUI[]	= {0x00, 0x90, 0x4c};
-#endif // DOT11_N_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-UCHAR RateSwitchTable[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x11, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x00,  0, 40, 101,
-    0x01, 0x00,  1, 40, 50,
-    0x02, 0x00,  2, 35, 45,
-    0x03, 0x00,  3, 20, 45,
-    0x04, 0x21,  0, 30, 50,
-    0x05, 0x21,  1, 20, 50,
-    0x06, 0x21,  2, 20, 50,
-    0x07, 0x21,  3, 15, 50,
-    0x08, 0x21,  4, 15, 30,
-    0x09, 0x21,  5, 10, 25,
-    0x0a, 0x21,  6,  8, 25,
-    0x0b, 0x21,  7,  8, 25,
-    0x0c, 0x20, 12,  15, 30,
-    0x0d, 0x20, 13,  8, 20,
-    0x0e, 0x20, 14,  8, 20,
-    0x0f, 0x20, 15,  8, 25,
-    0x10, 0x22, 15,  8, 25,
-    0x11, 0x00,  0,  0,  0,
-    0x12, 0x00,  0,  0,  0,
-    0x13, 0x00,  0,  0,  0,
-    0x14, 0x00,  0,  0,  0,
-    0x15, 0x00,  0,  0,  0,
-    0x16, 0x00,  0,  0,  0,
-    0x17, 0x00,  0,  0,  0,
-    0x18, 0x00,  0,  0,  0,
-    0x19, 0x00,  0,  0,  0,
-    0x1a, 0x00,  0,  0,  0,
-    0x1b, 0x00,  0,  0,  0,
-    0x1c, 0x00,  0,  0,  0,
-    0x1d, 0x00,  0,  0,  0,
-    0x1e, 0x00,  0,  0,  0,
-    0x1f, 0x00,  0,  0,  0,
-};
-
-UCHAR RateSwitchTable11B[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x04, 0x03,  0,  0,  0,						// Initial used item after association
-    0x00, 0x00,  0, 40, 101,
-    0x01, 0x00,  1, 40, 50,
-    0x02, 0x00,  2, 35, 45,
-    0x03, 0x00,  3, 20, 45,
-};
-
-UCHAR RateSwitchTable11BG[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0a, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x00,  0, 40, 101,
-    0x01, 0x00,  1, 40, 50,
-    0x02, 0x00,  2, 35, 45,
-    0x03, 0x00,  3, 20, 45,
-    0x04, 0x10,  2, 20, 35,
-    0x05, 0x10,  3, 16, 35,
-    0x06, 0x10,  4, 10, 25,
-    0x07, 0x10,  5, 16, 25,
-    0x08, 0x10,  6, 10, 25,
-    0x09, 0x10,  7, 10, 13,
-};
-
-UCHAR RateSwitchTable11G[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x08, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x10,  0, 20, 101,
-    0x01, 0x10,  1, 20, 35,
-    0x02, 0x10,  2, 20, 35,
-    0x03, 0x10,  3, 16, 35,
-    0x04, 0x10,  4, 10, 25,
-    0x05, 0x10,  5, 16, 25,
-    0x06, 0x10,  6, 10, 25,
-    0x07, 0x10,  7, 10, 13,
-};
-
-#ifdef DOT11_N_SUPPORT
-UCHAR RateSwitchTable11N1S[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x09, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30, 101,
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x21,  5, 10, 25,
-    0x06, 0x21,  6,  8, 14,
-    0x07, 0x21,  7,  8, 14,
-    0x08, 0x23,  7,  8, 14,
-};
-
-UCHAR RateSwitchTable11N2S[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0a, 0x00,  0,  0,  0,      // Initial used item after association
-    0x00, 0x21,  0, 30, 101,
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x20, 12,  15, 30,
-    0x06, 0x20, 13,  8, 20,
-    0x07, 0x20, 14,  8, 20,
-    0x08, 0x20, 15,  8, 25,
-    0x09, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11N3S[] = {
-// Item No.	Mode	Curr-MCS	TrainUp	TrainDown	// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0a, 0x00,  0,  0,  0,      // Initial used item after association
-    0x00, 0x21,  0, 30, 101,
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x20, 12,  15, 30,
-    0x06, 0x20, 13,  8, 20,
-    0x07, 0x20, 14,  8, 20,
-    0x08, 0x20, 15,  8, 25,
-    0x09, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11N2SForABand[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0b, 0x09,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30, 101,
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x21,  5, 15, 30,
-    0x06, 0x20, 12,  15, 30,
-    0x07, 0x20, 13,  8, 20,
-    0x08, 0x20, 14,  8, 20,
-    0x09, 0x20, 15,  8, 25,
-    0x0a, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11N3SForABand[] = { // 3*3
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0b, 0x09,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30, 101,
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x21,  5, 15, 30,
-    0x06, 0x20, 12,  15, 30,
-    0x07, 0x20, 13,  8, 20,
-    0x08, 0x20, 14,  8, 20,
-    0x09, 0x20, 15,  8, 25,
-    0x0a, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11BGN1S[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0d, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x00,  0, 40, 101,
-    0x01, 0x00,  1, 40, 50,
-    0x02, 0x00,  2, 35, 45,
-    0x03, 0x00,  3, 20, 45,
-    0x04, 0x21,  0, 30,101,	//50
-    0x05, 0x21,  1, 20, 50,
-    0x06, 0x21,  2, 20, 50,
-    0x07, 0x21,  3, 15, 50,
-    0x08, 0x21,  4, 15, 30,
-    0x09, 0x21,  5, 10, 25,
-    0x0a, 0x21,  6,  8, 14,
-    0x0b, 0x21,  7,  8, 14,
-	0x0c, 0x23,  7,  8, 14,
-};
-
-UCHAR RateSwitchTable11BGN2S[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0a, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30,101,	//50
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x20, 12, 15, 30,
-    0x06, 0x20, 13,  8, 20,
-    0x07, 0x20, 14,  8, 20,
-    0x08, 0x20, 15,  8, 25,
-    0x09, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11BGN3S[] = { // 3*3
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0a, 0x00,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30,101,	//50
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 20, 50,
-    0x04, 0x21,  4, 15, 50,
-#if 1
-    0x05, 0x20, 20, 15, 30,
-    0x06, 0x20, 21,  8, 20,
-    0x07, 0x20, 22,  8, 20,
-    0x08, 0x20, 23,  8, 25,
-    0x09, 0x22, 23,  8, 25,
-#else // for RT2860 2*3 test
-    0x05, 0x20, 12, 15, 30,
-    0x06, 0x20, 13,  8, 20,
-    0x07, 0x20, 14,  8, 20,
-    0x08, 0x20, 15,  8, 25,
-    0x09, 0x22, 15,  8, 25,
-#endif
-};
-
-UCHAR RateSwitchTable11BGN2SForABand[] = {
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0b, 0x09,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30,101,	//50
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x21,  5, 15, 30,
-    0x06, 0x20, 12, 15, 30,
-    0x07, 0x20, 13,  8, 20,
-    0x08, 0x20, 14,  8, 20,
-    0x09, 0x20, 15,  8, 25,
-    0x0a, 0x22, 15,  8, 25,
-};
-
-UCHAR RateSwitchTable11BGN3SForABand[] = { // 3*3
-// Item No.   Mode   Curr-MCS   TrainUp   TrainDown		// Mode- Bit0: STBC, Bit1: Short GI, Bit4,5: Mode(0:CCK, 1:OFDM, 2:HT Mix, 3:HT GF)
-    0x0c, 0x09,  0,  0,  0,						// Initial used item after association
-    0x00, 0x21,  0, 30,101,	//50
-    0x01, 0x21,  1, 20, 50,
-    0x02, 0x21,  2, 20, 50,
-    0x03, 0x21,  3, 15, 50,
-    0x04, 0x21,  4, 15, 30,
-    0x05, 0x21,  5, 15, 30,
-    0x06, 0x21, 12, 15, 30,
-    0x07, 0x20, 20, 15, 30,
-    0x08, 0x20, 21,  8, 20,
-    0x09, 0x20, 22,  8, 20,
-    0x0a, 0x20, 23,  8, 25,
-    0x0b, 0x22, 23,  8, 25,
-};
-#endif // DOT11_N_SUPPORT //
-
-PUCHAR ReasonString[] = {
-	/* 0  */	 "Reserved",
-	/* 1  */	 "Unspecified Reason",
-	/* 2  */	 "Previous Auth no longer valid",
-	/* 3  */	 "STA is leaving / has left",
-	/* 4  */	 "DIS-ASSOC due to inactivity",
-	/* 5  */	 "AP unable to hanle all associations",
-	/* 6  */	 "class 2 error",
-	/* 7  */	 "class 3 error",
-	/* 8  */	 "STA is leaving / has left",
-	/* 9  */	 "require auth before assoc/re-assoc",
-	/* 10 */	 "Reserved",
-	/* 11 */	 "Reserved",
-	/* 12 */	 "Reserved",
-	/* 13 */	 "invalid IE",
-	/* 14 */	 "MIC error",
-	/* 15 */	 "4-way handshake timeout",
-	/* 16 */	 "2-way (group key) handshake timeout",
-	/* 17 */	 "4-way handshake IE diff among AssosReq/Rsp/Beacon",
-	/* 18 */
-};
-
-extern UCHAR	 OfdmRateToRxwiMCS[];
-// since RT61 has better RX sensibility, we have to limit TX ACK rate not to exceed our normal data TX rate.
-// otherwise the WLAN peer may not be able to receive the ACK thus downgrade its data TX rate
-ULONG BasicRateMask[12]				= {0xfffff001 /* 1-Mbps */, 0xfffff003 /* 2 Mbps */, 0xfffff007 /* 5.5 */, 0xfffff00f /* 11 */,
-									  0xfffff01f /* 6 */	 , 0xfffff03f /* 9 */	  , 0xfffff07f /* 12 */ , 0xfffff0ff /* 18 */,
-									  0xfffff1ff /* 24 */	 , 0xfffff3ff /* 36 */	  , 0xfffff7ff /* 48 */ , 0xffffffff /* 54 */};
-
-UCHAR MULTICAST_ADDR[MAC_ADDR_LEN] = {0x1,  0x00, 0x00, 0x00, 0x00, 0x00};
-UCHAR BROADCAST_ADDR[MAC_ADDR_LEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
-UCHAR ZERO_MAC_ADDR[MAC_ADDR_LEN]  = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-
-// e.g. RssiSafeLevelForTxRate[RATE_36]" means if the current RSSI is greater than
-//		this value, then it's quaranteed capable of operating in 36 mbps TX rate in
-//		clean environment.
-//								  TxRate: 1   2   5.5	11	 6	  9    12	18	 24   36   48	54	 72  100
-CHAR RssiSafeLevelForTxRate[] ={  -92, -91, -90, -87, -88, -86, -85, -83, -81, -78, -72, -71, -40, -40 };
-
-UCHAR  RateIdToMbps[]	 = { 1, 2, 5, 11, 6, 9, 12, 18, 24, 36, 48, 54, 72, 100};
-USHORT RateIdTo500Kbps[] = { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108, 144, 200};
-
-UCHAR  SsidIe	 = IE_SSID;
-UCHAR  SupRateIe = IE_SUPP_RATES;
-UCHAR  ExtRateIe = IE_EXT_SUPP_RATES;
-#ifdef DOT11_N_SUPPORT
-UCHAR  HtCapIe = IE_HT_CAP;
-UCHAR  AddHtInfoIe = IE_ADD_HT;
-UCHAR  NewExtChanIe = IE_SECONDARY_CH_OFFSET;
-#ifdef DOT11N_DRAFT3
-UCHAR  ExtHtCapIe = IE_EXT_CAPABILITY;
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-UCHAR  ErpIe	 = IE_ERP;
-UCHAR  DsIe 	 = IE_DS_PARM;
-UCHAR  TimIe	 = IE_TIM;
-UCHAR  WpaIe	 = IE_WPA;
-UCHAR  Wpa2Ie	 = IE_WPA2;
-UCHAR  IbssIe	 = IE_IBSS_PARM;
-UCHAR  Ccx2Ie	 = IE_CCX_V2;
-UCHAR  WapiIe	 = IE_WAPI;
-
-extern UCHAR	WPA_OUI[];
-
-UCHAR	SES_OUI[] = {0x00, 0x90, 0x4c};
-
-UCHAR	ZeroSsid[32] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
-	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
-
-// Reset the RFIC setting to new series
-RTMP_RF_REGS RF2850RegTable[] = {
-//		ch	 R1 		 R2 		 R3(TX0~4=0) R4
-		{1,  0x98402ecc, 0x984c0786, 0x9816b455, 0x9800510b},
-		{2,  0x98402ecc, 0x984c0786, 0x98168a55, 0x9800519f},
-		{3,  0x98402ecc, 0x984c078a, 0x98168a55, 0x9800518b},
-		{4,  0x98402ecc, 0x984c078a, 0x98168a55, 0x9800519f},
-		{5,  0x98402ecc, 0x984c078e, 0x98168a55, 0x9800518b},
-		{6,  0x98402ecc, 0x984c078e, 0x98168a55, 0x9800519f},
-		{7,  0x98402ecc, 0x984c0792, 0x98168a55, 0x9800518b},
-		{8,  0x98402ecc, 0x984c0792, 0x98168a55, 0x9800519f},
-		{9,  0x98402ecc, 0x984c0796, 0x98168a55, 0x9800518b},
-		{10, 0x98402ecc, 0x984c0796, 0x98168a55, 0x9800519f},
-		{11, 0x98402ecc, 0x984c079a, 0x98168a55, 0x9800518b},
-		{12, 0x98402ecc, 0x984c079a, 0x98168a55, 0x9800519f},
-		{13, 0x98402ecc, 0x984c079e, 0x98168a55, 0x9800518b},
-		{14, 0x98402ecc, 0x984c07a2, 0x98168a55, 0x98005193},
-
-		// 802.11 UNI / HyperLan 2
-		{36, 0x98402ecc, 0x984c099a, 0x98158a55, 0x980ed1a3},
-		{38, 0x98402ecc, 0x984c099e, 0x98158a55, 0x980ed193},
-		{40, 0x98402ec8, 0x984c0682, 0x98158a55, 0x980ed183},
-		{44, 0x98402ec8, 0x984c0682, 0x98158a55, 0x980ed1a3},
-		{46, 0x98402ec8, 0x984c0686, 0x98158a55, 0x980ed18b},
-		{48, 0x98402ec8, 0x984c0686, 0x98158a55, 0x980ed19b},
-		{52, 0x98402ec8, 0x984c068a, 0x98158a55, 0x980ed193},
-		{54, 0x98402ec8, 0x984c068a, 0x98158a55, 0x980ed1a3},
-		{56, 0x98402ec8, 0x984c068e, 0x98158a55, 0x980ed18b},
-		{60, 0x98402ec8, 0x984c0692, 0x98158a55, 0x980ed183},
-		{62, 0x98402ec8, 0x984c0692, 0x98158a55, 0x980ed193},
-		{64, 0x98402ec8, 0x984c0692, 0x98158a55, 0x980ed1a3}, // Plugfest#4, Day4, change RFR3 left4th 9->5.
-
-		// 802.11 HyperLan 2
-		{100, 0x98402ec8, 0x984c06b2, 0x98178a55, 0x980ed783},
-
-		// 2008.04.30 modified
-		// The system team has AN to improve the EVM value
-		// for channel 102 to 108 for the RT2850/RT2750 dual band solution.
-		{102, 0x98402ec8, 0x985c06b2, 0x98578a55, 0x980ed793},
-		{104, 0x98402ec8, 0x985c06b2, 0x98578a55, 0x980ed1a3},
-		{108, 0x98402ecc, 0x985c0a32, 0x98578a55, 0x980ed193},
-
-		{110, 0x98402ecc, 0x984c0a36, 0x98178a55, 0x980ed183},
-		{112, 0x98402ecc, 0x984c0a36, 0x98178a55, 0x980ed19b},
-		{116, 0x98402ecc, 0x984c0a3a, 0x98178a55, 0x980ed1a3},
-		{118, 0x98402ecc, 0x984c0a3e, 0x98178a55, 0x980ed193},
-		{120, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed183},
-		{124, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed193},
-		{126, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed15b}, // 0x980ed1bb->0x980ed15b required by Rory 20070927
-		{128, 0x98402ec4, 0x984c0382, 0x98178a55, 0x980ed1a3},
-		{132, 0x98402ec4, 0x984c0386, 0x98178a55, 0x980ed18b},
-		{134, 0x98402ec4, 0x984c0386, 0x98178a55, 0x980ed193},
-		{136, 0x98402ec4, 0x984c0386, 0x98178a55, 0x980ed19b},
-		{140, 0x98402ec4, 0x984c038a, 0x98178a55, 0x980ed183},
-
-		// 802.11 UNII
-		{149, 0x98402ec4, 0x984c038a, 0x98178a55, 0x980ed1a7},
-		{151, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed187},
-		{153, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed18f},
-		{157, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed19f},
-		{159, 0x98402ec4, 0x984c038e, 0x98178a55, 0x980ed1a7},
-		{161, 0x98402ec4, 0x984c0392, 0x98178a55, 0x980ed187},
-		{165, 0x98402ec4, 0x984c0392, 0x98178a55, 0x980ed197},
-
-		// Japan
-		{184, 0x95002ccc, 0x9500491e, 0x9509be55, 0x950c0a0b},
-		{188, 0x95002ccc, 0x95004922, 0x9509be55, 0x950c0a13},
-		{192, 0x95002ccc, 0x95004926, 0x9509be55, 0x950c0a1b},
-		{196, 0x95002ccc, 0x9500492a, 0x9509be55, 0x950c0a23},
-		{208, 0x95002ccc, 0x9500493a, 0x9509be55, 0x950c0a13},
-		{212, 0x95002ccc, 0x9500493e, 0x9509be55, 0x950c0a1b},
-		{216, 0x95002ccc, 0x95004982, 0x9509be55, 0x950c0a23},
-
-		// still lack of MMAC(Japan) ch 34,38,42,46
-};
-UCHAR	NUM_OF_2850_CHNL = (sizeof(RF2850RegTable) / sizeof(RTMP_RF_REGS));
-
-FREQUENCY_ITEM FreqItems3020[] =
-{
-	/**************************************************/
-	// ISM : 2.4 to 2.483 GHz                         //
-	/**************************************************/
-	// 11g
-	/**************************************************/
-	//-CH---N-------R---K-----------
-	{1,    241,  2,  2},
-	{2,    241,	 2,  7},
-	{3,    242,	 2,  2},
-	{4,    242,	 2,  7},
-	{5,    243,	 2,  2},
-	{6,    243,	 2,  7},
-	{7,    244,	 2,  2},
-	{8,    244,	 2,  7},
-	{9,    245,	 2,  2},
-	{10,   245,	 2,  7},
-	{11,   246,	 2,  2},
-	{12,   246,	 2,  7},
-	{13,   247,	 2,  2},
-	{14,   248,	 2,  4},
-};
-//2008/07/10:KH Modified to share this variable
-UCHAR	NUM_OF_3020_CHNL=(sizeof(FreqItems3020) / sizeof(FREQUENCY_ITEM));
-
-/*
-	==========================================================================
-	Description:
-		initialize the MLME task and its data structure (queue, spinlock,
-		timer, state machines).
-
-	IRQL = PASSIVE_LEVEL
-
-	Return:
-		always return NDIS_STATUS_SUCCESS
-
-	==========================================================================
-*/
-NDIS_STATUS MlmeInit(
-	IN PRTMP_ADAPTER pAd)
-{
-	NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> MLME Initialize\n"));
-
-	do
-	{
-		Status = MlmeQueueInit(&pAd->Mlme.Queue);
-		if(Status != NDIS_STATUS_SUCCESS)
-			break;
-
-		pAd->Mlme.bRunning = FALSE;
-		NdisAllocateSpinLock(&pAd->Mlme.TaskLock);
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			BssTableInit(&pAd->ScanTab);
-
-			// init STA state machines
-			AssocStateMachineInit(pAd, &pAd->Mlme.AssocMachine, pAd->Mlme.AssocFunc);
-			AuthStateMachineInit(pAd, &pAd->Mlme.AuthMachine, pAd->Mlme.AuthFunc);
-			AuthRspStateMachineInit(pAd, &pAd->Mlme.AuthRspMachine, pAd->Mlme.AuthRspFunc);
-			SyncStateMachineInit(pAd, &pAd->Mlme.SyncMachine, pAd->Mlme.SyncFunc);
-			WpaPskStateMachineInit(pAd, &pAd->Mlme.WpaPskMachine, pAd->Mlme.WpaPskFunc);
-			AironetStateMachineInit(pAd, &pAd->Mlme.AironetMachine, pAd->Mlme.AironetFunc);
-
-#ifdef QOS_DLS_SUPPORT
-			DlsStateMachineInit(pAd, &pAd->Mlme.DlsMachine, pAd->Mlme.DlsFunc);
-#endif // QOS_DLS_SUPPORT //
-
-
-			// Since we are using switch/case to implement it, the init is different from the above
-			// state machine init
-			MlmeCntlInit(pAd, &pAd->Mlme.CntlMachine, NULL);
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-		ActionStateMachineInit(pAd, &pAd->Mlme.ActMachine, pAd->Mlme.ActFunc);
-
-		// Init mlme periodic timer
-		RTMPInitTimer(pAd, &pAd->Mlme.PeriodicTimer, GET_TIMER_FUNCTION(MlmePeriodicExec), pAd, TRUE);
-
-		// Set mlme periodic timer
-		RTMPSetTimer(&pAd->Mlme.PeriodicTimer, MLME_TASK_EXEC_INTV);
-
-		// software-based RX Antenna diversity
-		RTMPInitTimer(pAd, &pAd->Mlme.RxAntEvalTimer, GET_TIMER_FUNCTION(AsicRxAntEvalTimeout), pAd, FALSE);
-
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-	} while (FALSE);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- MLME Initialize\n"));
-
-	return Status;
-}
-
-/*
-	==========================================================================
-	Description:
-		main loop of the MLME
-	Pre:
-		Mlme has to be initialized, and there are something inside the queue
-	Note:
-		This function is invoked from MPSetInformation and MPReceive;
-		This task guarantee only one MlmeHandler will run.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID MlmeHandler(
-	IN PRTMP_ADAPTER pAd)
-{
-	MLME_QUEUE_ELEM 	   *Elem = NULL;
-
-	// Only accept MLME and Frame from peer side, no other (control/data) frame should
-	// get into this state machine
-
-	NdisAcquireSpinLock(&pAd->Mlme.TaskLock);
-	if(pAd->Mlme.bRunning)
-	{
-		NdisReleaseSpinLock(&pAd->Mlme.TaskLock);
-		return;
-	}
-	else
-	{
-		pAd->Mlme.bRunning = TRUE;
-	}
-	NdisReleaseSpinLock(&pAd->Mlme.TaskLock);
-
-	while (!MlmeQueueEmpty(&pAd->Mlme.Queue))
-	{
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_MLME_RESET_IN_PROGRESS) ||
-			RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS) ||
-			RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("Device Halted or Removed or MlmeRest, exit MlmeHandler! (queue num = %ld)\n", pAd->Mlme.Queue.Num));
-			break;
-		}
-
-#ifdef RALINK_ATE
-		if(ATE_ON(pAd))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now in MlmeHandler\n"));
-			break;
-		}
-#endif // RALINK_ATE //
-
-		//From message type, determine which state machine I should drive
-		if (MlmeDequeue(&pAd->Mlme.Queue, &Elem))
-		{
-#ifdef RT2870
-			if (Elem->MsgType == MT2_RESET_CONF)
-			{
-				DBGPRINT_RAW(RT_DEBUG_TRACE, ("!!! reset MLME state machine !!!\n"));
-				MlmeRestartStateMachine(pAd);
-				Elem->Occupied = FALSE;
-				Elem->MsgLen = 0;
-				continue;
-			}
-#endif // RT2870 //
-
-			// if dequeue success
-			switch (Elem->Machine)
-			{
-				// STA state machines
-#ifdef	CONFIG_STA_SUPPORT
-				case ASSOC_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.AssocMachine, Elem);
-					break;
-				case AUTH_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.AuthMachine, Elem);
-					break;
-				case AUTH_RSP_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.AuthRspMachine, Elem);
-					break;
-				case SYNC_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.SyncMachine, Elem);
-					break;
-				case MLME_CNTL_STATE_MACHINE:
-					MlmeCntlMachinePerformAction(pAd, &pAd->Mlme.CntlMachine, Elem);
-					break;
-				case WPA_PSK_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.WpaPskMachine, Elem);
-					break;
-#ifdef LEAP_SUPPORT
-				case LEAP_STATE_MACHINE:
-					LeapMachinePerformAction(pAd, &pAd->Mlme.LeapMachine, Elem);
-					break;
-#endif
-				case AIRONET_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.AironetMachine, Elem);
-					break;
-
-#ifdef QOS_DLS_SUPPORT
-				case DLS_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.DlsMachine, Elem);
-					break;
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-				case ACTION_STATE_MACHINE:
-					StateMachinePerformAction(pAd, &pAd->Mlme.ActMachine, Elem);
-					break;
-
-
-
-
-				default:
-					DBGPRINT(RT_DEBUG_TRACE, ("ERROR: Illegal machine %ld in MlmeHandler()\n", Elem->Machine));
-					break;
-			} // end of switch
-
-			// free MLME element
-			Elem->Occupied = FALSE;
-			Elem->MsgLen = 0;
-
-		}
-		else {
-			DBGPRINT_ERR(("MlmeHandler: MlmeQueue empty\n"));
-		}
-	}
-
-	NdisAcquireSpinLock(&pAd->Mlme.TaskLock);
-	pAd->Mlme.bRunning = FALSE;
-	NdisReleaseSpinLock(&pAd->Mlme.TaskLock);
-}
-
-/*
-	==========================================================================
-	Description:
-		Destructor of MLME (Destroy queue, state machine, spin lock and timer)
-	Parameters:
-		Adapter - NIC Adapter pointer
-	Post:
-		The MLME task will no longer work properly
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
- */
-VOID MlmeHalt(
-	IN PRTMP_ADAPTER pAd)
-{
-	BOOLEAN		Cancelled;
-#ifdef RT3070
-	UINT32		TxPinCfg = 0x00050F0F;
-#endif // RT3070 //
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==> MlmeHalt\n"));
-
-	if (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
-	{
-		// disable BEACON generation and other BEACON related hardware timers
-		AsicDisableSync(pAd);
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-#ifdef QOS_DLS_SUPPORT
-		UCHAR		i;
-#endif // QOS_DLS_SUPPORT //
-		// Cancel pending timers
-		RTMPCancelTimer(&pAd->MlmeAux.AssocTimer,		&Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer,		&Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer,	&Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.AuthTimer,		&Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer,		&Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer,		&Cancelled);
-
-#ifdef QOS_DLS_SUPPORT
-		for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &Cancelled);
-		}
-#endif // QOS_DLS_SUPPORT //
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	RTMPCancelTimer(&pAd->Mlme.PeriodicTimer,		&Cancelled);
-	RTMPCancelTimer(&pAd->Mlme.RxAntEvalTimer,		&Cancelled);
-
-
-
-	if (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
-	{
-		// Set LED
-		RTMPSetLED(pAd, LED_HALT);
-        RTMPSetSignalLED(pAd, -100);	// Force signal strength Led to be turned off, firmware is not done it.
-#ifdef RT2870
-        {
-            LED_CFG_STRUC LedCfg;
-            RTMP_IO_READ32(pAd, LED_CFG, &LedCfg.word);
-            LedCfg.field.LedPolar = 0;
-            LedCfg.field.RLedMode = 0;
-            LedCfg.field.GLedMode = 0;
-            LedCfg.field.YLedMode = 0;
-            RTMP_IO_WRITE32(pAd, LED_CFG, LedCfg.word);
-        }
-#endif // RT2870 //
-#ifdef RT3070
-		//
-		// Turn off LNA_PE
-		//
-		if (IS_RT3070(pAd) || IS_RT3071(pAd))
-		{
-			TxPinCfg &= 0xFFFFF0F0;
-			RTUSBWriteMACRegister(pAd, TX_PIN_CFG, TxPinCfg);
-		}
-#endif // RT3070 //
-	}
-
-	RTMPusecDelay(5000);    //  5 msec to gurantee Ant Diversity timer canceled
-
-	MlmeQueueDestroy(&pAd->Mlme.Queue);
-	NdisFreeSpinLock(&pAd->Mlme.TaskLock);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<== MlmeHalt\n"));
-}
-
-VOID MlmeResetRalinkCounters(
-	IN  PRTMP_ADAPTER   pAd)
-{
-	pAd->RalinkCounters.LastOneSecRxOkDataCnt = pAd->RalinkCounters.OneSecRxOkDataCnt;
-	// clear all OneSecxxx counters.
-	pAd->RalinkCounters.OneSecBeaconSentCnt = 0;
-	pAd->RalinkCounters.OneSecFalseCCACnt = 0;
-	pAd->RalinkCounters.OneSecRxFcsErrCnt = 0;
-	pAd->RalinkCounters.OneSecRxOkCnt = 0;
-	pAd->RalinkCounters.OneSecTxFailCount = 0;
-	pAd->RalinkCounters.OneSecTxNoRetryOkCount = 0;
-	pAd->RalinkCounters.OneSecTxRetryOkCount = 0;
-	pAd->RalinkCounters.OneSecRxOkDataCnt = 0;
-
-	// TODO: for debug only. to be removed
-	pAd->RalinkCounters.OneSecOsTxCount[QID_AC_BE] = 0;
-	pAd->RalinkCounters.OneSecOsTxCount[QID_AC_BK] = 0;
-	pAd->RalinkCounters.OneSecOsTxCount[QID_AC_VI] = 0;
-	pAd->RalinkCounters.OneSecOsTxCount[QID_AC_VO] = 0;
-	pAd->RalinkCounters.OneSecDmaDoneCount[QID_AC_BE] = 0;
-	pAd->RalinkCounters.OneSecDmaDoneCount[QID_AC_BK] = 0;
-	pAd->RalinkCounters.OneSecDmaDoneCount[QID_AC_VI] = 0;
-	pAd->RalinkCounters.OneSecDmaDoneCount[QID_AC_VO] = 0;
-	pAd->RalinkCounters.OneSecTxDoneCount = 0;
-	pAd->RalinkCounters.OneSecRxCount = 0;
-	pAd->RalinkCounters.OneSecTxAggregationCount = 0;
-	pAd->RalinkCounters.OneSecRxAggregationCount = 0;
-
-	return;
-}
-
-unsigned long rx_AMSDU;
-unsigned long rx_Total;
-
-/*
-	==========================================================================
-	Description:
-		This routine is executed periodically to -
-		1. Decide if it's a right time to turn on PwrMgmt bit of all
-		   outgoiing frames
-		2. Calculate ChannelQuality based on statistics of the last
-		   period, so that TX rate won't toggling very frequently between a
-		   successful TX and a failed TX.
-		3. If the calculated ChannelQuality indicated current connection not
-		   healthy, then a ROAMing attempt is tried here.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-#define ADHOC_BEACON_LOST_TIME		(8*OS_HZ)  // 8 sec
-VOID MlmePeriodicExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	ULONG			TxTotalCnt;
-	PRTMP_ADAPTER	pAd = (RTMP_ADAPTER *)FunctionContext;
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if ((RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_HALT_IN_PROGRESS |
-								fRTMP_ADAPTER_RADIO_OFF |
-								fRTMP_ADAPTER_RADIO_MEASUREMENT |
-								fRTMP_ADAPTER_RESET_IN_PROGRESS))))
-		return;
-
-	RT28XX_MLME_PRE_SANITY_CHECK(pAd);
-
-#ifdef RALINK_ATE
-	/* Do not show RSSI until "Normal 1 second Mlme PeriodicExec". */
-	if (ATE_ON(pAd))
-	{
-		if (pAd->Mlme.PeriodicRound % MLME_TASK_EXEC_MULTIPLE != (MLME_TASK_EXEC_MULTIPLE - 1))
-	{
-			pAd->Mlme.PeriodicRound ++;
-			return;
-		}
-	}
-#endif // RALINK_ATE //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Do nothing if monitor mode is on
-		if (MONITOR_ON(pAd))
-			return;
-
-		if (pAd->Mlme.PeriodicRound & 0x1)
-		{
-			// This is the fix for wifi 11n extension channel overlapping test case.  for 2860D
-			if (((pAd->MACVersion & 0xffff) == 0x0101) &&
-				(STA_TGN_WIFI_ON(pAd)) &&
-				(pAd->CommonCfg.IOTestParm.bToggle == FALSE))
-
-				{
-					RTMP_IO_WRITE32(pAd, TXOP_CTRL_CFG, 0x24Bf);
-					pAd->CommonCfg.IOTestParm.bToggle = TRUE;
-				}
-				else if ((STA_TGN_WIFI_ON(pAd)) &&
-						((pAd->MACVersion & 0xffff) == 0x0101))
-				{
-					RTMP_IO_WRITE32(pAd, TXOP_CTRL_CFG, 0x243f);
-					pAd->CommonCfg.IOTestParm.bToggle = FALSE;
-				}
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	pAd->bUpdateBcnCntDone = FALSE;
-
-//	RECBATimerTimeout(SystemSpecific1,FunctionContext,SystemSpecific2,SystemSpecific3);
-	pAd->Mlme.PeriodicRound ++;
-
-#ifdef RT2870
-	// execute every 100ms, update the Tx FIFO Cnt for update Tx Rate.
-	NICUpdateFifoStaCounters(pAd);
-#endif // RT2870 //
-	// execute every 500ms
-	if ((pAd->Mlme.PeriodicRound % 5 == 0) && RTMPAutoRateSwitchCheck(pAd)/*(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED))*/)
-	{
-#ifdef CONFIG_STA_SUPPORT
-		// perform dynamic tx rate switching based on past TX history
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			if ((OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)
-					)
-				&& (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE)))
-				MlmeDynamicTxRateSwitching(pAd);
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	// Normal 1 second Mlme PeriodicExec.
-	if (pAd->Mlme.PeriodicRound %MLME_TASK_EXEC_MULTIPLE == 0)
-	{
-                pAd->Mlme.OneSecPeriodicRound ++;
-
-#ifdef RALINK_ATE
-    	if (ATE_ON(pAd))
-    	{
-			/* request from Baron : move this routine from later to here */
-			/* for showing Rx error count in ATE RXFRAME */
-            NICUpdateRawCounters(pAd);
-			if (pAd->ate.bRxFer == 1)
-			{
-				pAd->ate.RxTotalCnt += pAd->ate.RxCntPerSec;
-			    ate_print(KERN_EMERG "MlmePeriodicExec: Rx packet cnt = %d/%d\n", pAd->ate.RxCntPerSec, pAd->ate.RxTotalCnt);
-				pAd->ate.RxCntPerSec = 0;
-
-				if (pAd->ate.RxAntennaSel == 0)
-					ate_print(KERN_EMERG "MlmePeriodicExec: Rx AvgRssi0=%d, AvgRssi1=%d, AvgRssi2=%d\n\n",
-						pAd->ate.AvgRssi0, pAd->ate.AvgRssi1, pAd->ate.AvgRssi2);
-				else
-					ate_print(KERN_EMERG "MlmePeriodicExec: Rx AvgRssi=%d\n\n", pAd->ate.AvgRssi0);
-			}
-			MlmeResetRalinkCounters(pAd);
-			return;
-    	}
-#endif // RALINK_ATE //
-
-
-		if (rx_Total)
-		{
-
-			// reset counters
-			rx_AMSDU = 0;
-			rx_Total = 0;
-		}
-
-		//ORIBATimerTimeout(pAd);
-
-		// Media status changed, report to NDIS
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_MEDIA_STATE_CHANGE))
-		{
-			RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_MEDIA_STATE_CHANGE);
-			if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-			{
-				pAd->IndicateMediaState = NdisMediaStateConnected;
-				RTMP_IndicateMediaState(pAd);
-
-			}
-			else
-			{
-				pAd->IndicateMediaState = NdisMediaStateDisconnected;
-				RTMP_IndicateMediaState(pAd);
-			}
-		}
-
-		NdisGetSystemUpTime(&pAd->Mlme.Now32);
-
-		// add the most up-to-date h/w raw counters into software variable, so that
-		// the dynamic tuning mechanism below are based on most up-to-date information
-		NICUpdateRawCounters(pAd);
-
-#ifdef RT2870
-		RT2870_WatchDog(pAd);
-#endif // RT2870 //
-
-#ifdef DOT11_N_SUPPORT
-   		// Need statistics after read counter. So put after NICUpdateRawCounters
-		ORIBATimerTimeout(pAd);
-#endif // DOT11_N_SUPPORT //
-
-		// The time period for checking antenna is according to traffic
-		{
-			if (pAd->Mlme.bEnableAutoAntennaCheck)
-			{
-				TxTotalCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount +
-								 pAd->RalinkCounters.OneSecTxRetryOkCount +
-								 pAd->RalinkCounters.OneSecTxFailCount;
-
-					// dynamic adjust antenna evaluation period according to the traffic
-				if (TxTotalCnt > 50)
-				{
-					if (pAd->Mlme.OneSecPeriodicRound % 10 == 0)
-					{
-						AsicEvaluateRxAnt(pAd);
-					}
-				}
-				else
-				{
-					if (pAd->Mlme.OneSecPeriodicRound % 3 == 0)
-					{
-						AsicEvaluateRxAnt(pAd);
-					}
-				}
-			}
-		}
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			STAMlmePeriodicExec(pAd);
-#endif // CONFIG_STA_SUPPORT //
-
-		MlmeResetRalinkCounters(pAd);
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			{
-				// When Adhoc beacon is enabled and RTS/CTS is enabled, there is a chance that hardware MAC FSM will run into a deadlock
-				// and sending CTS-to-self over and over.
-				// Software Patch Solution:
-				// 1. Polling debug state register 0x10F4 every one second.
-				// 2. If in 0x10F4 the ((bit29==1) && (bit7==1)) OR ((bit29==1) && (bit5==1)), it means the deadlock has occurred.
-				// 3. If the deadlock occurred, reset MAC/BBP by setting 0x1004 to 0x0001 for a while then setting it back to 0x000C again.
-
-				UINT32	MacReg = 0;
-
-				RTMP_IO_READ32(pAd, 0x10F4, &MacReg);
-				if (((MacReg & 0x20000000) && (MacReg & 0x80)) || ((MacReg & 0x20000000) && (MacReg & 0x20)))
-				{
-					RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x1);
-					RTMPusecDelay(1);
-					RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0xC);
-
-					DBGPRINT(RT_DEBUG_WARN,("Warning, MAC specific condition occurs \n"));
-				}
-			}
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		RT28XX_MLME_HANDLER(pAd);
-	}
-
-
-	pAd->bUpdateBcnCntDone = FALSE;
-}
-
-#ifdef CONFIG_STA_SUPPORT
-VOID STAMlmePeriodicExec(
-	PRTMP_ADAPTER pAd)
-{
-	ULONG			    TxTotalCnt;
-	int 	i;
-
-//
-// We return here in ATE mode, because the statistics
-// that ATE needs are not collected via this routine.
-//
-#ifdef RALINK_ATE
-	// It is supposed that we will never reach here in ATE mode.
-	ASSERT(!(ATE_ON(pAd)));
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-    if (pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_DISABLE)
-#endif // WPA_SUPPLICANT_SUPPORT //
-    {
-    	// WPA MIC error should block association attempt for 60 seconds
-    	if (pAd->StaCfg.bBlockAssoc && (pAd->StaCfg.LastMicErrorTime + (60 * OS_HZ) < pAd->Mlme.Now32))
-    		pAd->StaCfg.bBlockAssoc = FALSE;
-    }
-
-    if ((pAd->PreMediaState != pAd->IndicateMediaState) && (pAd->CommonCfg.bWirelessEvent))
-	{
-		if (pAd->IndicateMediaState == NdisMediaStateConnected)
-		{
-			RTMPSendWirelessEvent(pAd, IW_STA_LINKUP_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-		}
-		pAd->PreMediaState = pAd->IndicateMediaState;
-	}
-
-
-
-
-   	AsicStaBbpTuning(pAd);
-
-	TxTotalCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount +
-					 pAd->RalinkCounters.OneSecTxRetryOkCount +
-					 pAd->RalinkCounters.OneSecTxFailCount;
-
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-	{
-		// update channel quality for Roaming and UI LinkQuality display
-		MlmeCalculateChannelQuality(pAd, pAd->Mlme.Now32);
-	}
-
-	// must be AFTER MlmeDynamicTxRateSwitching() because it needs to know if
-	// Radio is currently in noisy environment
-	if (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-		AsicAdjustTxPower(pAd);
-
-	if (INFRA_ON(pAd))
-	{
-#ifdef QOS_DLS_SUPPORT
-		// Check DLS time out, then tear down those session
-		RTMPCheckDLSTimeOut(pAd);
-#endif // QOS_DLS_SUPPORT //
-
-		// Is PSM bit consistent with user power management policy?
-		// This is the only place that will set PSM bit ON.
-		if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-		MlmeCheckPsmChange(pAd, pAd->Mlme.Now32);
-
-		pAd->RalinkCounters.LastOneSecTotalTxCount = TxTotalCnt;
-
-		if ((pAd->StaCfg.LastBeaconRxTime + 1*OS_HZ < pAd->Mlme.Now32) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) &&
-			((TxTotalCnt + pAd->RalinkCounters.OneSecRxOkCnt < 600)))
-		{
-			RTMPSetAGCInitValue(pAd, BW_20);
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - No BEACON. restore R66 to the low bound(%d) \n", (0x2E + GET_LNA_GAIN(pAd))));
-		}
-
-        //if ((pAd->RalinkCounters.OneSecTxNoRetryOkCount == 0) &&
-        //    (pAd->RalinkCounters.OneSecTxRetryOkCount == 0))
-        {
-    		if (pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable)
-    		{
-    		    // When APSD is enabled, the period changes as 20 sec
-    			if ((pAd->Mlme.OneSecPeriodicRound % 20) == 8)
-    				RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, TRUE);
-    		}
-    		else
-    		{
-    		    // Send out a NULL frame every 10 sec to inform AP that STA is still alive (Avoid being age out)
-    			if ((pAd->Mlme.OneSecPeriodicRound % 10) == 8)
-                {
-                    if (pAd->CommonCfg.bWmmCapable)
-    					RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, TRUE);
-                    else
-						RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, FALSE);
-                }
-    		}
-        }
-
-		if (CQI_IS_DEAD(pAd->Mlme.ChannelQuality))
-			{
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - No BEACON. Dead CQI. Auto Recovery attempt #%ld\n", pAd->RalinkCounters.BadCQIAutoRecoveryCount));
-			pAd->StaCfg.CCXAdjacentAPReportFlag = TRUE;
-			pAd->StaCfg.CCXAdjacentAPLinkDownTime = pAd->StaCfg.LastBeaconRxTime;
-
-			// Lost AP, send disconnect & link down event
-			LinkDown(pAd, FALSE);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.WpaSupplicantUP)
-			{
-                union iwreq_data    wrqu;
-                //send disassociate event to wpa_supplicant
-                memset(&wrqu, 0, sizeof(wrqu));
-                wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-                wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-            {
-                union iwreq_data    wrqu;
-                memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-			// RTMPPatchMacBbpBug(pAd);
-			MlmeAutoReconnectLastSSID(pAd);
-		}
-		else if (CQI_IS_BAD(pAd->Mlme.ChannelQuality))
-		{
-			pAd->RalinkCounters.BadCQIAutoRecoveryCount ++;
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - Bad CQI. Auto Recovery attempt #%ld\n", pAd->RalinkCounters.BadCQIAutoRecoveryCount));
-			MlmeAutoReconnectLastSSID(pAd);
-		}
-
-		// Add auto seamless roaming
-		if (pAd->StaCfg.bFastRoaming)
-		{
-			SHORT	dBmToRoam = (SHORT)pAd->StaCfg.dBmToRoam;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("Rssi=%d, dBmToRoam=%d\n", RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2), (CHAR)dBmToRoam));
-
-			if (RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2) <= (CHAR)dBmToRoam)
-			{
-				MlmeCheckForFastRoaming(pAd, pAd->Mlme.Now32);
-			}
-		}
-	}
-	else if (ADHOC_ON(pAd))
-	{
-		//radar detect
-		if ((pAd->CommonCfg.Channel > 14)
-			&& (pAd->CommonCfg.bIEEE80211H == 1)
-			&& RadarChannelCheck(pAd, pAd->CommonCfg.Channel))
-		{
-			RadarDetectPeriodic(pAd);
-		}
-
-		// If all peers leave, and this STA becomes the last one in this IBSS, then change MediaState
-		// to DISCONNECTED. But still holding this IBSS (i.e. sending BEACON) so that other STAs can
-		// join later.
-		if ((pAd->StaCfg.LastBeaconRxTime + ADHOC_BEACON_LOST_TIME < pAd->Mlme.Now32) &&
-			OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-		{
-			MLME_START_REQ_STRUCT     StartReq;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - excessive BEACON lost, last STA in this IBSS, MediaState=Disconnected\n"));
-			LinkDown(pAd, FALSE);
-
-			StartParmFill(pAd, &StartReq, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-			MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_START_REQ, sizeof(MLME_START_REQ_STRUCT), &StartReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_START;
-		}
-
-		for (i = 1; i < MAX_LEN_OF_MAC_TABLE; i++)
-		{
-			MAC_TABLE_ENTRY *pEntry = &pAd->MacTab.Content[i];
-
-			if (pEntry->ValidAsCLI == FALSE)
-				continue;
-
-			if (pEntry->LastBeaconRxTime + ADHOC_BEACON_LOST_TIME < pAd->Mlme.Now32)
-				MacTableDeleteEntry(pAd, pEntry->Aid, pEntry->Addr);
-		}
-	}
-	else // no INFRA nor ADHOC connection
-	{
-
-		if (pAd->StaCfg.bScanReqIsFromWebUI &&
-            ((pAd->StaCfg.LastScanTime + 30 * OS_HZ) > pAd->Mlme.Now32))
-			goto SKIP_AUTO_SCAN_CONN;
-        else
-            pAd->StaCfg.bScanReqIsFromWebUI = FALSE;
-
-		if ((pAd->StaCfg.bAutoReconnect == TRUE)
-			&& RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP)
-			&& (MlmeValidateSSID(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen) == TRUE))
-		{
-			if ((pAd->ScanTab.BssNr==0) && (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE))
-			{
-				MLME_SCAN_REQ_STRUCT	   ScanReq;
-
-				if ((pAd->StaCfg.LastScanTime + 10 * OS_HZ) < pAd->Mlme.Now32)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("STAMlmePeriodicExec():CNTL - ScanTab.BssNr==0, start a new ACTIVE scan SSID[%s]\n", pAd->MlmeAux.AutoReconnectSsid));
-					ScanParmFill(pAd, &ScanReq, pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen, BSS_ANY, SCAN_ACTIVE);
-					MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-					pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-					// Reset Missed scan number
-					pAd->StaCfg.LastScanTime = pAd->Mlme.Now32;
-				}
-				else if (pAd->StaCfg.BssType == BSS_ADHOC)	// Quit the forever scan when in a very clean room
-					MlmeAutoReconnectLastSSID(pAd);
-			}
-			else if (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE)
-			{
-				if ((pAd->Mlme.OneSecPeriodicRound % 7) == 0)
-				{
-					MlmeAutoScan(pAd);
-					pAd->StaCfg.LastScanTime = pAd->Mlme.Now32;
-				}
-				else
-				{
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-					if (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-					{
-						if ((pAd->Mlme.OneSecPeriodicRound % 5) == 1)
-							MlmeAutoReconnectLastSSID(pAd);
-					}
-					else
-#endif // CARRIER_DETECTION_SUPPORT //
-						MlmeAutoReconnectLastSSID(pAd);
-				}
-			}
-		}
-	}
-
-SKIP_AUTO_SCAN_CONN:
-
-#ifdef DOT11_N_SUPPORT
-    if ((pAd->MacTab.Content[BSSID_WCID].TXBAbitmap !=0) && (pAd->MacTab.fAnyBASession == FALSE))
-	{
-		pAd->MacTab.fAnyBASession = TRUE;
-		AsicUpdateProtect(pAd, HT_FORCERTSCTS,  ALLN_SETPROTECT, FALSE, FALSE);
-	}
-	else if ((pAd->MacTab.Content[BSSID_WCID].TXBAbitmap ==0) && (pAd->MacTab.fAnyBASession == TRUE))
-	{
-		pAd->MacTab.fAnyBASession = FALSE;
-		AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode,  ALLN_SETPROTECT, FALSE, FALSE);
-	}
-#endif // DOT11_N_SUPPORT //
-
-
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SCAN_2040))
-		TriEventCounterMaintenance(pAd);
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-	return;
-}
-
-// Link down report
-VOID LinkDownExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	pAd->IndicateMediaState = NdisMediaStateDisconnected;
-	RTMP_IndicateMediaState(pAd);
-    pAd->ExtraInfo = GENERAL_LINK_DOWN;
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID MlmeAutoScan(
-	IN PRTMP_ADAPTER pAd)
-{
-	// check CntlMachine.CurrState to avoid collision with NDIS SetOID request
-	if (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - Driver auto scan\n"));
-		MlmeEnqueue(pAd,
-					MLME_CNTL_STATE_MACHINE,
-					OID_802_11_BSSID_LIST_SCAN,
-					0,
-					NULL);
-		RT28XX_MLME_HANDLER(pAd);
-	}
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID MlmeAutoReconnectLastSSID(
-	IN PRTMP_ADAPTER pAd)
-{
-
-
-	// check CntlMachine.CurrState to avoid collision with NDIS SetOID request
-	if ((pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE) &&
-		(MlmeValidateSSID(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen) == TRUE))
-	{
-		NDIS_802_11_SSID OidSsid;
-		OidSsid.SsidLength = pAd->MlmeAux.AutoReconnectSsidLen;
-		NdisMoveMemory(OidSsid.Ssid, pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Driver auto reconnect to last OID_802_11_SSID setting - %s, len - %d\n", pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen));
-		MlmeEnqueue(pAd,
-					MLME_CNTL_STATE_MACHINE,
-					OID_802_11_SSID,
-					sizeof(NDIS_802_11_SSID),
-					&OidSsid);
-		RT28XX_MLME_HANDLER(pAd);
-	}
-}
-#endif // CONFIG_STA_SUPPORT //
-
-/*
-	==========================================================================
-	Validate SSID for connection try and rescan purpose
-	Valid SSID will have visible chars only.
-	The valid length is from 0 to 32.
-	IRQL = DISPATCH_LEVEL
-	==========================================================================
- */
-BOOLEAN MlmeValidateSSID(
-	IN PUCHAR	pSsid,
-	IN UCHAR	SsidLen)
-{
-	int	index;
-
-	if (SsidLen > MAX_LEN_OF_SSID)
-		return (FALSE);
-
-	// Check each character value
-	for (index = 0; index < SsidLen; index++)
-	{
-		if (pSsid[index] < 0x20)
-			return (FALSE);
-	}
-
-	// All checked
-	return (TRUE);
-}
-
-VOID MlmeSelectTxRateTable(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PUCHAR				*ppTable,
-	IN PUCHAR				pTableSize,
-	IN PUCHAR				pInitTxRateIdx)
-{
-	do
-	{
-		// decide the rate table for tuning
-		if (pAd->CommonCfg.TxRateTableSize > 0)
-		{
-			*ppTable = RateSwitchTable;
-			*pTableSize = RateSwitchTable[0];
-			*pInitTxRateIdx = RateSwitchTable[1];
-
-			break;
-		}
-
-#ifdef CONFIG_STA_SUPPORT
-		if ((pAd->OpMode == OPMODE_STA) && ADHOC_ON(pAd))
-		{
-#ifdef DOT11_N_SUPPORT
-			if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED) &&
-				(pEntry->HTCapability.MCSSet[0] == 0xff) &&
-				((pEntry->HTCapability.MCSSet[1] == 0x00) || (pAd->Antenna.field.TxPath == 1)))
-			{// 11N 1S Adhoc
-				*ppTable = RateSwitchTable11N1S;
-				*pTableSize = RateSwitchTable11N1S[0];
-				*pInitTxRateIdx = RateSwitchTable11N1S[1];
-
-			}
-			else if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED) &&
-					(pEntry->HTCapability.MCSSet[0] == 0xff) &&
-					(pEntry->HTCapability.MCSSet[1] == 0xff) &&
-					(pAd->Antenna.field.TxPath == 2))
-			{// 11N 2S Adhoc
-				if (pAd->LatchRfRegs.Channel <= 14)
-				{
-					*ppTable = RateSwitchTable11N2S;
-					*pTableSize = RateSwitchTable11N2S[0];
-					*pInitTxRateIdx = RateSwitchTable11N2S[1];
-				}
-				else
-				{
-					*ppTable = RateSwitchTable11N2SForABand;
-					*pTableSize = RateSwitchTable11N2SForABand[0];
-					*pInitTxRateIdx = RateSwitchTable11N2SForABand[1];
-				}
-
-			}
-			else
-#endif // DOT11_N_SUPPORT //
-				if ((pEntry->RateLen == 4)
-#ifdef DOT11_N_SUPPORT
-					&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
-#endif // DOT11_N_SUPPORT //
-					)
-			{
-				*ppTable = RateSwitchTable11B;
-				*pTableSize = RateSwitchTable11B[0];
-				*pInitTxRateIdx = RateSwitchTable11B[1];
-
-			}
-			else if (pAd->LatchRfRegs.Channel <= 14)
-			{
-				*ppTable = RateSwitchTable11BG;
-				*pTableSize = RateSwitchTable11BG[0];
-				*pInitTxRateIdx = RateSwitchTable11BG[1];
-
-			}
-			else
-			{
-				*ppTable = RateSwitchTable11G;
-				*pTableSize = RateSwitchTable11G[0];
-				*pInitTxRateIdx = RateSwitchTable11G[1];
-
-			}
-			break;
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-		//if ((pAd->StaActive.SupRateLen + pAd->StaActive.ExtRateLen == 12) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0xff) &&
-		//	((pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0x00) || (pAd->Antenna.field.TxPath == 1)))
-		if ((pEntry->RateLen == 12) && (pEntry->HTCapability.MCSSet[0] == 0xff) &&
-			((pEntry->HTCapability.MCSSet[1] == 0x00) || (pAd->CommonCfg.TxStream == 1)))
-		{// 11BGN 1S AP
-			*ppTable = RateSwitchTable11BGN1S;
-			*pTableSize = RateSwitchTable11BGN1S[0];
-			*pInitTxRateIdx = RateSwitchTable11BGN1S[1];
-
-			break;
-		}
-
-		//else if ((pAd->StaActive.SupRateLen + pAd->StaActive.ExtRateLen == 12) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0xff) &&
-		//	(pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0xff) && (pAd->Antenna.field.TxPath == 2))
-		if ((pEntry->RateLen == 12) && (pEntry->HTCapability.MCSSet[0] == 0xff) &&
-			(pEntry->HTCapability.MCSSet[1] == 0xff) && (pAd->CommonCfg.TxStream == 2))
-		{// 11BGN 2S AP
-			if (pAd->LatchRfRegs.Channel <= 14)
-			{
-				*ppTable = RateSwitchTable11BGN2S;
-				*pTableSize = RateSwitchTable11BGN2S[0];
-				*pInitTxRateIdx = RateSwitchTable11BGN2S[1];
-
-			}
-			else
-			{
-				*ppTable = RateSwitchTable11BGN2SForABand;
-				*pTableSize = RateSwitchTable11BGN2SForABand[0];
-				*pInitTxRateIdx = RateSwitchTable11BGN2SForABand[1];
-
-			}
-			break;
-		}
-
-		//else if ((pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0xff) && ((pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0x00) || (pAd->Antenna.field.TxPath == 1)))
-		if ((pEntry->HTCapability.MCSSet[0] == 0xff) && ((pEntry->HTCapability.MCSSet[1] == 0x00) || (pAd->CommonCfg.TxStream == 1)))
-		{// 11N 1S AP
-			*ppTable = RateSwitchTable11N1S;
-			*pTableSize = RateSwitchTable11N1S[0];
-			*pInitTxRateIdx = RateSwitchTable11N1S[1];
-
-			break;
-		}
-
-		//else if ((pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0xff) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0xff) && (pAd->Antenna.field.TxPath == 2))
-		if ((pEntry->HTCapability.MCSSet[0] == 0xff) && (pEntry->HTCapability.MCSSet[1] == 0xff) && (pAd->CommonCfg.TxStream == 2))
-		{// 11N 2S AP
-			if (pAd->LatchRfRegs.Channel <= 14)
-			{
-			*ppTable = RateSwitchTable11N2S;
-			*pTableSize = RateSwitchTable11N2S[0];
-			*pInitTxRateIdx = RateSwitchTable11N2S[1];
-            }
-			else
-			{
-				*ppTable = RateSwitchTable11N2SForABand;
-				*pTableSize = RateSwitchTable11N2SForABand[0];
-				*pInitTxRateIdx = RateSwitchTable11N2SForABand[1];
-			}
-
-			break;
-		}
-#endif // DOT11_N_SUPPORT //
-		//else if ((pAd->StaActive.SupRateLen == 4) && (pAd->StaActive.ExtRateLen == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
-		if ((pEntry->RateLen == 4)
-#ifdef DOT11_N_SUPPORT
-//Iverson mark for Adhoc b mode,sta will use rate 54  Mbps when connect with sta b/g/n mode
-//			&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
-#endif // DOT11_N_SUPPORT //
-			)
-		{// B only AP
-			*ppTable = RateSwitchTable11B;
-			*pTableSize = RateSwitchTable11B[0];
-			*pInitTxRateIdx = RateSwitchTable11B[1];
-
-			break;
-		}
-
-		//else if ((pAd->StaActive.SupRateLen + pAd->StaActive.ExtRateLen > 8) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
-		if ((pEntry->RateLen > 8)
-#ifdef DOT11_N_SUPPORT
-			&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
-#endif // DOT11_N_SUPPORT //
-			)
-		{// B/G  mixed AP
-			*ppTable = RateSwitchTable11BG;
-			*pTableSize = RateSwitchTable11BG[0];
-			*pInitTxRateIdx = RateSwitchTable11BG[1];
-
-			break;
-		}
-
-		//else if ((pAd->StaActive.SupRateLen + pAd->StaActive.ExtRateLen == 8) && (pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
-		if ((pEntry->RateLen == 8)
-#ifdef DOT11_N_SUPPORT
-			&& (pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0)
-#endif // DOT11_N_SUPPORT //
-			)
-		{// G only AP
-			*ppTable = RateSwitchTable11G;
-			*pTableSize = RateSwitchTable11G[0];
-			*pInitTxRateIdx = RateSwitchTable11G[1];
-
-			break;
-		}
-#ifdef DOT11_N_SUPPORT
-#endif // DOT11_N_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-#ifdef DOT11_N_SUPPORT
-			//else if ((pAd->StaActive.SupportedPhyInfo.MCSSet[0] == 0) && (pAd->StaActive.SupportedPhyInfo.MCSSet[1] == 0))
-			if ((pEntry->HTCapability.MCSSet[0] == 0) && (pEntry->HTCapability.MCSSet[1] == 0))
-#endif // DOT11_N_SUPPORT //
-			{	// Legacy mode
-				if (pAd->CommonCfg.MaxTxRate <= RATE_11)
-				{
-					*ppTable = RateSwitchTable11B;
-					*pTableSize = RateSwitchTable11B[0];
-					*pInitTxRateIdx = RateSwitchTable11B[1];
-				}
-				else if ((pAd->CommonCfg.MaxTxRate > RATE_11) && (pAd->CommonCfg.MinTxRate > RATE_11))
-				{
-					*ppTable = RateSwitchTable11G;
-					*pTableSize = RateSwitchTable11G[0];
-					*pInitTxRateIdx = RateSwitchTable11G[1];
-
-				}
-				else
-				{
-					*ppTable = RateSwitchTable11BG;
-					*pTableSize = RateSwitchTable11BG[0];
-					*pInitTxRateIdx = RateSwitchTable11BG[1];
-				}
-				break;
-			}
-#ifdef DOT11_N_SUPPORT
-			if (pAd->LatchRfRegs.Channel <= 14)
-			{
-				if (pAd->CommonCfg.TxStream == 1)
-				{
-					*ppTable = RateSwitchTable11N1S;
-					*pTableSize = RateSwitchTable11N1S[0];
-					*pInitTxRateIdx = RateSwitchTable11N1S[1];
-					DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode,default use 11N 1S AP \n"));
-				}
-				else
-				{
-					*ppTable = RateSwitchTable11N2S;
-					*pTableSize = RateSwitchTable11N2S[0];
-					*pInitTxRateIdx = RateSwitchTable11N2S[1];
-					DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode,default use 11N 2S AP \n"));
-				}
-			}
-			else
-			{
-				if (pAd->CommonCfg.TxStream == 1)
-				{
-					*ppTable = RateSwitchTable11N1S;
-					*pTableSize = RateSwitchTable11N1S[0];
-					*pInitTxRateIdx = RateSwitchTable11N1S[1];
-					DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode,default use 11N 1S AP \n"));
-				}
-				else
-				{
-					*ppTable = RateSwitchTable11N2SForABand;
-					*pTableSize = RateSwitchTable11N2SForABand[0];
-					*pInitTxRateIdx = RateSwitchTable11N2SForABand[1];
-					DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode,default use 11N 2S AP \n"));
-				}
-			}
-#endif // DOT11_N_SUPPORT //
-			DBGPRINT_RAW(RT_DEBUG_ERROR,("DRS: unkown mode (SupRateLen=%d, ExtRateLen=%d, MCSSet[0]=0x%x, MCSSet[1]=0x%x)\n",
-				pAd->StaActive.SupRateLen, pAd->StaActive.ExtRateLen, pAd->StaActive.SupportedPhyInfo.MCSSet[0], pAd->StaActive.SupportedPhyInfo.MCSSet[1]));
-		}
-#endif // CONFIG_STA_SUPPORT //
-	} while(FALSE);
-}
-
-#ifdef CONFIG_STA_SUPPORT
-/*
-	==========================================================================
-	Description:
-		This routine checks if there're other APs out there capable for
-		roaming. Caller should call this routine only when Link up in INFRA mode
-		and channel quality is below CQI_GOOD_THRESHOLD.
-
-	IRQL = DISPATCH_LEVEL
-
-	Output:
-	==========================================================================
- */
-VOID MlmeCheckForRoaming(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG	Now32)
-{
-	USHORT	   i;
-	BSS_TABLE  *pRoamTab = &pAd->MlmeAux.RoamTab;
-	BSS_ENTRY  *pBss;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==> MlmeCheckForRoaming\n"));
-	// put all roaming candidates into RoamTab, and sort in RSSI order
-	BssTableInit(pRoamTab);
-	for (i = 0; i < pAd->ScanTab.BssNr; i++)
-	{
-		pBss = &pAd->ScanTab.BssEntry[i];
-
-		if ((pBss->LastBeaconRxTime + BEACON_LOST_TIME) < Now32)
-			continue;	 // AP disappear
-		if (pBss->Rssi <= RSSI_THRESHOLD_FOR_ROAMING)
-			continue;	 // RSSI too weak. forget it.
-		if (MAC_ADDR_EQUAL(pBss->Bssid, pAd->CommonCfg.Bssid))
-			continue;	 // skip current AP
-		if (pBss->Rssi < (pAd->StaCfg.RssiSample.LastRssi0 + RSSI_DELTA))
-			continue;	 // only AP with stronger RSSI is eligible for roaming
-
-		// AP passing all above rules is put into roaming candidate table
-		NdisMoveMemory(&pRoamTab->BssEntry[pRoamTab->BssNr], pBss, sizeof(BSS_ENTRY));
-		pRoamTab->BssNr += 1;
-	}
-
-	if (pRoamTab->BssNr > 0)
-	{
-		// check CntlMachine.CurrState to avoid collision with NDIS SetOID request
-		if (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE)
-		{
-			pAd->RalinkCounters.PoorCQIRoamingCount ++;
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - Roaming attempt #%ld\n", pAd->RalinkCounters.PoorCQIRoamingCount));
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_MLME_ROAMING_REQ, 0, NULL);
-			RT28XX_MLME_HANDLER(pAd);
-		}
-	}
-	DBGPRINT(RT_DEBUG_TRACE, ("<== MlmeCheckForRoaming(# of candidate= %d)\n",pRoamTab->BssNr));
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine checks if there're other APs out there capable for
-		roaming. Caller should call this routine only when link up in INFRA mode
-		and channel quality is below CQI_GOOD_THRESHOLD.
-
-	IRQL = DISPATCH_LEVEL
-
-	Output:
-	==========================================================================
- */
-VOID MlmeCheckForFastRoaming(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	ULONG			Now)
-{
-	USHORT		i;
-	BSS_TABLE	*pRoamTab = &pAd->MlmeAux.RoamTab;
-	BSS_ENTRY	*pBss;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==> MlmeCheckForFastRoaming\n"));
-	// put all roaming candidates into RoamTab, and sort in RSSI order
-	BssTableInit(pRoamTab);
-	for (i = 0; i < pAd->ScanTab.BssNr; i++)
-	{
-		pBss = &pAd->ScanTab.BssEntry[i];
-
-        if ((pBss->Rssi <= -50) && (pBss->Channel == pAd->CommonCfg.Channel))
-			continue;	 // RSSI too weak. forget it.
-		if (MAC_ADDR_EQUAL(pBss->Bssid, pAd->CommonCfg.Bssid))
-			continue;	 // skip current AP
-		if (!SSID_EQUAL(pBss->Ssid, pBss->SsidLen, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen))
-			continue;	 // skip different SSID
-        if (pBss->Rssi < (RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2) + RSSI_DELTA))
-			continue;	 // skip AP without better RSSI
-
-        DBGPRINT(RT_DEBUG_TRACE, ("LastRssi0 = %d, pBss->Rssi = %d\n", RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2), pBss->Rssi));
-		// AP passing all above rules is put into roaming candidate table
-		NdisMoveMemory(&pRoamTab->BssEntry[pRoamTab->BssNr], pBss, sizeof(BSS_ENTRY));
-		pRoamTab->BssNr += 1;
-	}
-
-	if (pRoamTab->BssNr > 0)
-	{
-		// check CntlMachine.CurrState to avoid collision with NDIS SetOID request
-		if (pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE)
-		{
-			pAd->RalinkCounters.PoorCQIRoamingCount ++;
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - Roaming attempt #%ld\n", pAd->RalinkCounters.PoorCQIRoamingCount));
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_MLME_ROAMING_REQ, 0, NULL);
-			RT28XX_MLME_HANDLER(pAd);
-		}
-	}
-	// Maybe site survey required
-	else
-	{
-		if ((pAd->StaCfg.LastScanTime + 10 * 1000) < Now)
-		{
-			// check CntlMachine.CurrState to avoid collision with NDIS SetOID request
-			DBGPRINT(RT_DEBUG_TRACE, ("MMCHK - Roaming, No eligable entry, try new scan!\n"));
-			pAd->StaCfg.ScanCnt = 2;
-			pAd->StaCfg.LastScanTime = Now;
-			MlmeAutoScan(pAd);
-		}
-	}
-
-    DBGPRINT(RT_DEBUG_TRACE, ("<== MlmeCheckForFastRoaming (BssNr=%d)\n", pRoamTab->BssNr));
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine calculates TxPER, RxPER of the past N-sec period. And
-		according to the calculation result, ChannelQuality is calculated here
-		to decide if current AP is still doing the job.
-
-		If ChannelQuality is not good, a ROAMing attempt may be tried later.
-	Output:
-		StaCfg.ChannelQuality - 0..100
-
-	IRQL = DISPATCH_LEVEL
-
-	NOTE: This routine decide channle quality based on RX CRC error ratio.
-		Caller should make sure a function call to NICUpdateRawCounters(pAd)
-		is performed right before this routine, so that this routine can decide
-		channel quality based on the most up-to-date information
-	==========================================================================
- */
-VOID MlmeCalculateChannelQuality(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG Now32)
-{
-	ULONG TxOkCnt, TxCnt, TxPER, TxPRR;
-	ULONG RxCnt, RxPER;
-	UCHAR NorRssi;
-	CHAR  MaxRssi;
-	ULONG BeaconLostTime = BEACON_LOST_TIME;
-
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-	// longer beacon lost time when carrier detection enabled
-	if (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-	{
-		BeaconLostTime = BEACON_LOST_TIME + BEACON_LOST_TIME/2;
-	}
-#endif // CARRIER_DETECTION_SUPPORT //
-
-	MaxRssi = RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2);
-
-	//
-	// calculate TX packet error ratio and TX retry ratio - if too few TX samples, skip TX related statistics
-	//
-	TxOkCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount + pAd->RalinkCounters.OneSecTxRetryOkCount;
-	TxCnt = TxOkCnt + pAd->RalinkCounters.OneSecTxFailCount;
-	if (TxCnt < 5)
-	{
-		TxPER = 0;
-		TxPRR = 0;
-	}
-	else
-	{
-		TxPER = (pAd->RalinkCounters.OneSecTxFailCount * 100) / TxCnt;
-		TxPRR = ((TxCnt - pAd->RalinkCounters.OneSecTxNoRetryOkCount) * 100) / TxCnt;
-	}
-
-	//
-	// calculate RX PER - don't take RxPER into consideration if too few sample
-	//
-	RxCnt = pAd->RalinkCounters.OneSecRxOkCnt + pAd->RalinkCounters.OneSecRxFcsErrCnt;
-	if (RxCnt < 5)
-		RxPER = 0;
-	else
-		RxPER = (pAd->RalinkCounters.OneSecRxFcsErrCnt * 100) / RxCnt;
-
-	//
-	// decide ChannelQuality based on: 1)last BEACON received time, 2)last RSSI, 3)TxPER, and 4)RxPER
-	//
-	if (INFRA_ON(pAd) &&
-		(pAd->RalinkCounters.OneSecTxNoRetryOkCount < 2) && // no heavy traffic
-		(pAd->StaCfg.LastBeaconRxTime + BeaconLostTime < Now32))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("BEACON lost > %ld msec with TxOkCnt=%ld -> CQI=0\n", BeaconLostTime, TxOkCnt));
-		pAd->Mlme.ChannelQuality = 0;
-	}
-	else
-	{
-		// Normalize Rssi
-		if (MaxRssi > -40)
-			NorRssi = 100;
-		else if (MaxRssi < -90)
-			NorRssi = 0;
-		else
-			NorRssi = (MaxRssi + 90) * 2;
-
-		// ChannelQuality = W1*RSSI + W2*TxPRR + W3*RxPER	 (RSSI 0..100), (TxPER 100..0), (RxPER 100..0)
-		pAd->Mlme.ChannelQuality = (RSSI_WEIGHTING * NorRssi +
-								   TX_WEIGHTING * (100 - TxPRR) +
-								   RX_WEIGHTING* (100 - RxPER)) / 100;
-		if (pAd->Mlme.ChannelQuality >= 100)
-			pAd->Mlme.ChannelQuality = 100;
-	}
-
-}
-
-VOID MlmeSetTxRate(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PRTMP_TX_RATE_SWITCH	pTxRate)
-{
-	UCHAR	MaxMode = MODE_OFDM;
-
-#ifdef DOT11_N_SUPPORT
-	MaxMode = MODE_HTGREENFIELD;
-
-	if (pTxRate->STBC && (pAd->StaCfg.MaxHTPhyMode.field.STBC) && (pAd->Antenna.field.TxPath == 2))
-		pAd->StaCfg.HTPhyMode.field.STBC = STBC_USE;
-	else
-#endif // DOT11_N_SUPPORT //
-		pAd->StaCfg.HTPhyMode.field.STBC = STBC_NONE;
-
-	if (pTxRate->CurrMCS < MCS_AUTO)
-		pAd->StaCfg.HTPhyMode.field.MCS = pTxRate->CurrMCS;
-
-	if (pAd->StaCfg.HTPhyMode.field.MCS > 7)
-		pAd->StaCfg.HTPhyMode.field.STBC = STBC_NONE;
-
-   	if (ADHOC_ON(pAd))
-	{
-		// If peer adhoc is b-only mode, we can't send 11g rate.
-		pAd->StaCfg.HTPhyMode.field.ShortGI = GI_800;
-		pEntry->HTPhyMode.field.STBC	= STBC_NONE;
-
-		//
-		// For Adhoc MODE_CCK, driver will use AdhocBOnlyJoined flag to roll back to B only if necessary
-		//
-		pEntry->HTPhyMode.field.MODE	= pTxRate->Mode;
-		pEntry->HTPhyMode.field.ShortGI	= pAd->StaCfg.HTPhyMode.field.ShortGI;
-		pEntry->HTPhyMode.field.MCS		= pAd->StaCfg.HTPhyMode.field.MCS;
-
-		// Patch speed error in status page
-		pAd->StaCfg.HTPhyMode.field.MODE = pEntry->HTPhyMode.field.MODE;
-	}
-	else
-	{
-		if (pTxRate->Mode <= MaxMode)
-			pAd->StaCfg.HTPhyMode.field.MODE = pTxRate->Mode;
-
-#ifdef DOT11_N_SUPPORT
-		if (pTxRate->ShortGI && (pAd->StaCfg.MaxHTPhyMode.field.ShortGI))
-			pAd->StaCfg.HTPhyMode.field.ShortGI = GI_400;
-		else
-#endif // DOT11_N_SUPPORT //
-			pAd->StaCfg.HTPhyMode.field.ShortGI = GI_800;
-
-#ifdef DOT11_N_SUPPORT
-		// Reexam each bandwidth's SGI support.
-		if (pAd->StaCfg.HTPhyMode.field.ShortGI == GI_400)
-		{
-			if ((pEntry->HTPhyMode.field.BW == BW_20) && (!CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE)))
-				pAd->StaCfg.HTPhyMode.field.ShortGI = GI_800;
-			if ((pEntry->HTPhyMode.field.BW == BW_40) && (!CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE)))
-				pAd->StaCfg.HTPhyMode.field.ShortGI = GI_800;
-		}
-
-		// Turn RTS/CTS rate to 6Mbps.
-		if ((pEntry->HTPhyMode.field.MCS == 0) && (pAd->StaCfg.HTPhyMode.field.MCS != 0))
-		{
-			pEntry->HTPhyMode.field.MCS		= pAd->StaCfg.HTPhyMode.field.MCS;
-			if (pAd->MacTab.fAnyBASession)
-			{
-				AsicUpdateProtect(pAd, HT_FORCERTSCTS, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-			}
-			else
-			{
-				AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-			}
-		}
-		else if ((pEntry->HTPhyMode.field.MCS == 8) && (pAd->StaCfg.HTPhyMode.field.MCS != 8))
-		{
-			pEntry->HTPhyMode.field.MCS		= pAd->StaCfg.HTPhyMode.field.MCS;
-			if (pAd->MacTab.fAnyBASession)
-			{
-				AsicUpdateProtect(pAd, HT_FORCERTSCTS, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-			}
-			else
-			{
-				AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-			}
-		}
-		else if ((pEntry->HTPhyMode.field.MCS != 0) && (pAd->StaCfg.HTPhyMode.field.MCS == 0))
-		{
-			AsicUpdateProtect(pAd, HT_RTSCTS_6M, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-
-		}
-		else if ((pEntry->HTPhyMode.field.MCS != 8) && (pAd->StaCfg.HTPhyMode.field.MCS == 8))
-		{
-			AsicUpdateProtect(pAd, HT_RTSCTS_6M, ALLN_SETPROTECT, TRUE, (BOOLEAN)pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent);
-		}
-#endif // DOT11_N_SUPPORT //
-
-		pEntry->HTPhyMode.field.STBC	= pAd->StaCfg.HTPhyMode.field.STBC;
-		pEntry->HTPhyMode.field.ShortGI	= pAd->StaCfg.HTPhyMode.field.ShortGI;
-		pEntry->HTPhyMode.field.MCS		= pAd->StaCfg.HTPhyMode.field.MCS;
-		pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-#ifdef DOT11_N_SUPPORT
-		if ((pAd->StaCfg.MaxHTPhyMode.field.MODE == MODE_HTGREENFIELD) &&
-		    pAd->WIFItestbed.bGreenField)
-		    pEntry->HTPhyMode.field.MODE = MODE_HTGREENFIELD;
-#endif // DOT11_N_SUPPORT //
-	}
-
-	pAd->LastTxRate = (USHORT)(pEntry->HTPhyMode.word);
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine calculates the acumulated TxPER of eaxh TxRate. And
-		according to the calculation result, change CommonCfg.TxRate which
-		is the stable TX Rate we expect the Radio situation could sustained.
-
-		CommonCfg.TxRate will change dynamically within {RATE_1/RATE_6, MaxTxRate}
-	Output:
-		CommonCfg.TxRate -
-
-	IRQL = DISPATCH_LEVEL
-
-	NOTE:
-		call this routine every second
-	==========================================================================
- */
-VOID MlmeDynamicTxRateSwitching(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR					UpRateIdx = 0, DownRateIdx = 0, CurrRateIdx;
-	ULONG					i, AccuTxTotalCnt = 0, TxTotalCnt;
-	ULONG					TxErrorRatio = 0;
-	BOOLEAN					bTxRateChanged, bUpgradeQuality = FALSE;
-	PRTMP_TX_RATE_SWITCH	pCurrTxRate, pNextTxRate = NULL;
-	PUCHAR					pTable;
-	UCHAR					TableSize = 0;
-	UCHAR					InitTxRateIdx = 0, TrainUp, TrainDown;
-	CHAR					Rssi, RssiOffset = 0;
-	TX_STA_CNT1_STRUC		StaTx1;
-	TX_STA_CNT0_STRUC		TxStaCnt0;
-	ULONG					TxRetransmit = 0, TxSuccess = 0, TxFailCount = 0;
-	MAC_TABLE_ENTRY			*pEntry;
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-		return;
-	}
-#endif // RALINK_ATE //
-
-	//
-	// walk through MAC table, see if need to change AP's TX rate toward each entry
-	//
-   	for (i = 1; i < MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		pEntry = &pAd->MacTab.Content[i];
-
-		// check if this entry need to switch rate automatically
-		if (RTMPCheckEntryEnableAutoRateSwitch(pAd, pEntry) == FALSE)
-			continue;
-
-		if ((pAd->MacTab.Size == 1) || (pEntry->ValidAsDls))
-		{
-			Rssi = RTMPMaxRssi(pAd,
-							   pAd->StaCfg.RssiSample.AvgRssi0,
-							   pAd->StaCfg.RssiSample.AvgRssi1,
-							   pAd->StaCfg.RssiSample.AvgRssi2);
-
-			// Update statistic counter
-			RTMP_IO_READ32(pAd, TX_STA_CNT0, &TxStaCnt0.word);
-			RTMP_IO_READ32(pAd, TX_STA_CNT1, &StaTx1.word);
-			pAd->bUpdateBcnCntDone = TRUE;
-			TxRetransmit = StaTx1.field.TxRetransmit;
-			TxSuccess = StaTx1.field.TxSuccess;
-			TxFailCount = TxStaCnt0.field.TxFailCount;
-			TxTotalCnt = TxRetransmit + TxSuccess + TxFailCount;
-
-			pAd->RalinkCounters.OneSecTxRetryOkCount += StaTx1.field.TxRetransmit;
-			pAd->RalinkCounters.OneSecTxNoRetryOkCount += StaTx1.field.TxSuccess;
-			pAd->RalinkCounters.OneSecTxFailCount += TxStaCnt0.field.TxFailCount;
-			pAd->WlanCounters.TransmittedFragmentCount.u.LowPart += StaTx1.field.TxSuccess;
-			pAd->WlanCounters.RetryCount.u.LowPart += StaTx1.field.TxRetransmit;
-			pAd->WlanCounters.FailedCount.u.LowPart += TxStaCnt0.field.TxFailCount;
-
-			// if no traffic in the past 1-sec period, don't change TX rate,
-			// but clear all bad history. because the bad history may affect the next
-			// Chariot throughput test
-			AccuTxTotalCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount +
-						 pAd->RalinkCounters.OneSecTxRetryOkCount +
-						 pAd->RalinkCounters.OneSecTxFailCount;
-
-			if (TxTotalCnt)
-				TxErrorRatio = ((TxRetransmit + TxFailCount) * 100) / TxTotalCnt;
-		}
-		else
-		{
-			if (INFRA_ON(pAd) && (i == 1))
-				Rssi = RTMPMaxRssi(pAd,
-								   pAd->StaCfg.RssiSample.AvgRssi0,
-								   pAd->StaCfg.RssiSample.AvgRssi1,
-								   pAd->StaCfg.RssiSample.AvgRssi2);
-			else
-				Rssi = RTMPMaxRssi(pAd,
-								   pEntry->RssiSample.AvgRssi0,
-								   pEntry->RssiSample.AvgRssi1,
-								   pEntry->RssiSample.AvgRssi2);
-
-			TxTotalCnt = pEntry->OneSecTxNoRetryOkCount +
-				 pEntry->OneSecTxRetryOkCount +
-				 pEntry->OneSecTxFailCount;
-
-			if (TxTotalCnt)
-				TxErrorRatio = ((pEntry->OneSecTxRetryOkCount + pEntry->OneSecTxFailCount) * 100) / TxTotalCnt;
-		}
-
-		CurrRateIdx = pEntry->CurrTxRateIndex;
-
-		MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &InitTxRateIdx);
-
-		if (CurrRateIdx >= TableSize)
-		{
-			CurrRateIdx = TableSize - 1;
-		}
-
-		// When switch from Fixed rate -> auto rate, the REAL TX rate might be different from pAd->CommonCfg.TxRateIndex.
-		// So need to sync here.
-		pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(CurrRateIdx+1)*5];
-		if ((pEntry->HTPhyMode.field.MCS != pCurrTxRate->CurrMCS)
-			//&& (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-			)
-		{
-
-			// Need to sync Real Tx rate and our record.
-			// Then return for next DRS.
-			pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(InitTxRateIdx+1)*5];
-			pEntry->CurrTxRateIndex = InitTxRateIdx;
-			MlmeSetTxRate(pAd, pEntry, pCurrTxRate);
-
-			// reset all OneSecTx counters
-			RESET_ONE_SEC_TX_CNT(pEntry);
-			continue;
-		}
-
-		// decide the next upgrade rate and downgrade rate, if any
-		if ((CurrRateIdx > 0) && (CurrRateIdx < (TableSize - 1)))
-		{
-			UpRateIdx = CurrRateIdx + 1;
-			DownRateIdx = CurrRateIdx -1;
-		}
-		else if (CurrRateIdx == 0)
-		{
-			UpRateIdx = CurrRateIdx + 1;
-			DownRateIdx = CurrRateIdx;
-		}
-		else if (CurrRateIdx == (TableSize - 1))
-		{
-			UpRateIdx = CurrRateIdx;
-			DownRateIdx = CurrRateIdx - 1;
-		}
-
-		pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(CurrRateIdx+1)*5];
-
-#ifdef DOT11_N_SUPPORT
-		if ((Rssi > -65) && (pCurrTxRate->Mode >= MODE_HTMIX))
-		{
-			TrainUp		= (pCurrTxRate->TrainUp + (pCurrTxRate->TrainUp >> 1));
-			TrainDown	= (pCurrTxRate->TrainDown + (pCurrTxRate->TrainDown >> 1));
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			TrainUp		= pCurrTxRate->TrainUp;
-			TrainDown	= pCurrTxRate->TrainDown;
-		}
-
-		//pAd->DrsCounters.LastTimeTxRateChangeAction = pAd->DrsCounters.LastSecTxRateChangeAction;
-
-		//
-		// Keep the last time TxRateChangeAction status.
-		//
-		pEntry->LastTimeTxRateChangeAction = pEntry->LastSecTxRateChangeAction;
-
-
-
-		//
-		// CASE 1. when TX samples are fewer than 15, then decide TX rate solely on RSSI
-		//         (criteria copied from RT2500 for Netopia case)
-		//
-		if (TxTotalCnt <= 15)
-		{
-			CHAR	idx = 0;
-			UCHAR	TxRateIdx;
-			//UCHAR	MCS0 = 0, MCS1 = 0, MCS2 = 0, MCS3 = 0, MCS4 = 0, MCS7 = 0, MCS12 = 0, MCS13 = 0, MCS14 = 0, MCS15 = 0;
-			UCHAR	MCS0 = 0, MCS1 = 0, MCS2 = 0, MCS3 = 0, MCS4 = 0,  MCS5 =0, MCS6 = 0, MCS7 = 0;
-	        UCHAR	MCS12 = 0, MCS13 = 0, MCS14 = 0, MCS15 = 0;
-			UCHAR	MCS20 = 0, MCS21 = 0, MCS22 = 0, MCS23 = 0; // 3*3
-
-			// check the existence and index of each needed MCS
-			while (idx < pTable[0])
-			{
-				pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(idx+1)*5];
-
-				if (pCurrTxRate->CurrMCS == MCS_0)
-				{
-					MCS0 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_1)
-				{
-					MCS1 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_2)
-				{
-					MCS2 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_3)
-				{
-					MCS3 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_4)
-				{
-					MCS4 = idx;
-				}
-	            else if (pCurrTxRate->CurrMCS == MCS_5)
-	            {
-	                MCS5 = idx;
-	            }
-	            else if (pCurrTxRate->CurrMCS == MCS_6)
-	            {
-	                MCS6 = idx;
-	            }
-				//else if (pCurrTxRate->CurrMCS == MCS_7)
-				else if ((pCurrTxRate->CurrMCS == MCS_7) && (pCurrTxRate->ShortGI == GI_800))	// prevent the highest MCS using short GI when 1T and low throughput
-				{
-					MCS7 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_12)
-				{
-					MCS12 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_13)
-				{
-					MCS13 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_14)
-				{
-					MCS14 = idx;
-				}
-				else if ((pCurrTxRate->CurrMCS == MCS_15) && (pCurrTxRate->ShortGI == GI_800))
-				{
-					MCS15 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_20) // 3*3
-				{
-					MCS20 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_21)
-				{
-					MCS21 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_22)
-				{
-					MCS22 = idx;
-				}
-				else if (pCurrTxRate->CurrMCS == MCS_23)
-				{
-					MCS23 = idx;
-				}
-				idx ++;
-			}
-
-			if (pAd->LatchRfRegs.Channel <= 14)
-			{
-				if (pAd->NicConfig2.field.ExternalLNAForG)
-				{
-					RssiOffset = 2;
-				}
-				else
-				{
-					RssiOffset = 5;
-				}
-			}
-			else
-			{
-				if (pAd->NicConfig2.field.ExternalLNAForA)
-				{
-					RssiOffset = 5;
-				}
-				else
-				{
-					RssiOffset = 8;
-				}
-			}
-#ifdef DOT11_N_SUPPORT
-			/*if (MCS15)*/
-			if ((pTable == RateSwitchTable11BGN3S) ||
-				(pTable == RateSwitchTable11N3S) ||
-				(pTable == RateSwitchTable))
-			{// N mode with 3 stream // 3*3
-				if (MCS23 && (Rssi >= -70))
-					TxRateIdx = MCS15;
-				else if (MCS22 && (Rssi >= -72))
-					TxRateIdx = MCS14;
-        	    else if (MCS21 && (Rssi >= -76))
-					TxRateIdx = MCS13;
-				else if (MCS20 && (Rssi >= -78))
-					TxRateIdx = MCS12;
-			else if (MCS4 && (Rssi >= -82))
-				TxRateIdx = MCS4;
-			else if (MCS3 && (Rssi >= -84))
-				TxRateIdx = MCS3;
-			else if (MCS2 && (Rssi >= -86))
-				TxRateIdx = MCS2;
-			else if (MCS1 && (Rssi >= -88))
-				TxRateIdx = MCS1;
-			else
-				TxRateIdx = MCS0;
-		}
-//		else if ((pTable == RateSwitchTable11BGN2S) || (pTable == RateSwitchTable11BGN2SForABand) ||(pTable == RateSwitchTable11N2S) ||(pTable == RateSwitchTable11N2SForABand) || (pTable == RateSwitchTable))
-		else if ((pTable == RateSwitchTable11BGN2S) || (pTable == RateSwitchTable11BGN2SForABand) ||(pTable == RateSwitchTable11N2S) ||(pTable == RateSwitchTable11N2SForABand)) // 3*3
-			{// N mode with 2 stream
-				if (MCS15 && (Rssi >= (-70+RssiOffset)))
-					TxRateIdx = MCS15;
-				else if (MCS14 && (Rssi >= (-72+RssiOffset)))
-					TxRateIdx = MCS14;
-				else if (MCS13 && (Rssi >= (-76+RssiOffset)))
-					TxRateIdx = MCS13;
-				else if (MCS12 && (Rssi >= (-78+RssiOffset)))
-					TxRateIdx = MCS12;
-				else if (MCS4 && (Rssi >= (-82+RssiOffset)))
-					TxRateIdx = MCS4;
-				else if (MCS3 && (Rssi >= (-84+RssiOffset)))
-					TxRateIdx = MCS3;
-				else if (MCS2 && (Rssi >= (-86+RssiOffset)))
-					TxRateIdx = MCS2;
-				else if (MCS1 && (Rssi >= (-88+RssiOffset)))
-					TxRateIdx = MCS1;
-				else
-					TxRateIdx = MCS0;
-			}
-			else if ((pTable == RateSwitchTable11BGN1S) || (pTable == RateSwitchTable11N1S))
-			{// N mode with 1 stream
-				if (MCS7 && (Rssi > (-72+RssiOffset)))
-					TxRateIdx = MCS7;
-				else if (MCS6 && (Rssi > (-74+RssiOffset)))
-					TxRateIdx = MCS6;
-				else if (MCS5 && (Rssi > (-77+RssiOffset)))
-					TxRateIdx = MCS5;
-				else if (MCS4 && (Rssi > (-79+RssiOffset)))
-					TxRateIdx = MCS4;
-				else if (MCS3 && (Rssi > (-81+RssiOffset)))
-					TxRateIdx = MCS3;
-				else if (MCS2 && (Rssi > (-83+RssiOffset)))
-					TxRateIdx = MCS2;
-				else if (MCS1 && (Rssi > (-86+RssiOffset)))
-					TxRateIdx = MCS1;
-				else
-					TxRateIdx = MCS0;
-			}
-			else
-#endif // DOT11_N_SUPPORT //
-			{// Legacy mode
-				if (MCS7 && (Rssi > -70))
-					TxRateIdx = MCS7;
-				else if (MCS6 && (Rssi > -74))
-					TxRateIdx = MCS6;
-				else if (MCS5 && (Rssi > -78))
-					TxRateIdx = MCS5;
-				else if (MCS4 && (Rssi > -82))
-					TxRateIdx = MCS4;
-				else if (MCS4 == 0)	// for B-only mode
-					TxRateIdx = MCS3;
-				else if (MCS3 && (Rssi > -85))
-					TxRateIdx = MCS3;
-				else if (MCS2 && (Rssi > -87))
-					TxRateIdx = MCS2;
-				else if (MCS1 && (Rssi > -90))
-					TxRateIdx = MCS1;
-				else
-					TxRateIdx = MCS0;
-			}
-
-	//		if (TxRateIdx != pAd->CommonCfg.TxRateIndex)
-			{
-				pEntry->CurrTxRateIndex = TxRateIdx;
-				pNextTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(pEntry->CurrTxRateIndex+1)*5];
-				MlmeSetTxRate(pAd, pEntry, pNextTxRate);
-			}
-
-			NdisZeroMemory(pEntry->TxQuality, sizeof(USHORT) * MAX_STEP_OF_TX_RATE_SWITCH);
-			NdisZeroMemory(pEntry->PER, sizeof(UCHAR) * MAX_STEP_OF_TX_RATE_SWITCH);
-			pEntry->fLastSecAccordingRSSI = TRUE;
-			// reset all OneSecTx counters
-			RESET_ONE_SEC_TX_CNT(pEntry);
-
-			continue;
-		}
-
-		if (pEntry->fLastSecAccordingRSSI == TRUE)
-		{
-			pEntry->fLastSecAccordingRSSI = FALSE;
-			pEntry->LastSecTxRateChangeAction = 0;
-			// reset all OneSecTx counters
-			RESET_ONE_SEC_TX_CNT(pEntry);
-
-			continue;
-		}
-
-		do
-		{
-			BOOLEAN	bTrainUpDown = FALSE;
-
-			pEntry->CurrTxRateStableTime ++;
-
-			// downgrade TX quality if PER >= Rate-Down threshold
-			if (TxErrorRatio >= TrainDown)
-			{
-				bTrainUpDown = TRUE;
-				pEntry->TxQuality[CurrRateIdx] = DRS_TX_QUALITY_WORST_BOUND;
-			}
-			// upgrade TX quality if PER <= Rate-Up threshold
-			else if (TxErrorRatio <= TrainUp)
-			{
-				bTrainUpDown = TRUE;
-				bUpgradeQuality = TRUE;
-				if (pEntry->TxQuality[CurrRateIdx])
-					pEntry->TxQuality[CurrRateIdx] --;  // quality very good in CurrRate
-
-				if (pEntry->TxRateUpPenalty)
-					pEntry->TxRateUpPenalty --;
-				else if (pEntry->TxQuality[UpRateIdx])
-					pEntry->TxQuality[UpRateIdx] --;    // may improve next UP rate's quality
-			}
-
-			pEntry->PER[CurrRateIdx] = (UCHAR)TxErrorRatio;
-
-			if (bTrainUpDown)
-			{
-				// perform DRS - consider TxRate Down first, then rate up.
-				if ((CurrRateIdx != DownRateIdx) && (pEntry->TxQuality[CurrRateIdx] >= DRS_TX_QUALITY_WORST_BOUND))
-				{
-					pEntry->CurrTxRateIndex = DownRateIdx;
-				}
-				else if ((CurrRateIdx != UpRateIdx) && (pEntry->TxQuality[UpRateIdx] <= 0))
-				{
-					pEntry->CurrTxRateIndex = UpRateIdx;
-				}
-			}
-		} while (FALSE);
-
-		// if rate-up happen, clear all bad history of all TX rates
-		if (pEntry->CurrTxRateIndex > CurrRateIdx)
-		{
-			pEntry->CurrTxRateStableTime = 0;
-			pEntry->TxRateUpPenalty = 0;
-			pEntry->LastSecTxRateChangeAction = 1; // rate UP
-			NdisZeroMemory(pEntry->TxQuality, sizeof(USHORT) * MAX_STEP_OF_TX_RATE_SWITCH);
-			NdisZeroMemory(pEntry->PER, sizeof(UCHAR) * MAX_STEP_OF_TX_RATE_SWITCH);
-
-			//
-			// For TxRate fast train up
-			//
-			if (!pAd->StaCfg.StaQuickResponeForRateUpTimerRunning)
-			{
-				RTMPSetTimer(&pAd->StaCfg.StaQuickResponeForRateUpTimer, 100);
-
-				pAd->StaCfg.StaQuickResponeForRateUpTimerRunning = TRUE;
-			}
-			bTxRateChanged = TRUE;
-		}
-		// if rate-down happen, only clear DownRate's bad history
-		else if (pEntry->CurrTxRateIndex < CurrRateIdx)
-		{
-			pEntry->CurrTxRateStableTime = 0;
-			pEntry->TxRateUpPenalty = 0;           // no penalty
-			pEntry->LastSecTxRateChangeAction = 2; // rate DOWN
-			pEntry->TxQuality[pEntry->CurrTxRateIndex] = 0;
-			pEntry->PER[pEntry->CurrTxRateIndex] = 0;
-
-			//
-			// For TxRate fast train down
-			//
-			if (!pAd->StaCfg.StaQuickResponeForRateUpTimerRunning)
-			{
-				RTMPSetTimer(&pAd->StaCfg.StaQuickResponeForRateUpTimer, 100);
-
-				pAd->StaCfg.StaQuickResponeForRateUpTimerRunning = TRUE;
-			}
-			bTxRateChanged = TRUE;
-		}
-		else
-		{
-			pEntry->LastSecTxRateChangeAction = 0; // rate no change
-			bTxRateChanged = FALSE;
-		}
-
-		pEntry->LastTxOkCount = TxSuccess;
-
-		// reset all OneSecTx counters
-		RESET_ONE_SEC_TX_CNT(pEntry);
-
-		pNextTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(pEntry->CurrTxRateIndex+1)*5];
-		if (bTxRateChanged && pNextTxRate)
-		{
-			MlmeSetTxRate(pAd, pEntry, pNextTxRate);
-		}
-	}
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Station side, Auto TxRate faster train up timer call back function.
-
-	Arguments:
-		SystemSpecific1			- Not used.
-		FunctionContext			- Pointer to our Adapter context.
-		SystemSpecific2			- Not used.
-		SystemSpecific3			- Not used.
-
-	Return Value:
-		None
-
-	========================================================================
-*/
-VOID StaQuickResponeForRateUpExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	PRTMP_ADAPTER			pAd = (PRTMP_ADAPTER)FunctionContext;
-	UCHAR					UpRateIdx = 0, DownRateIdx = 0, CurrRateIdx = 0;
-	ULONG					TxTotalCnt;
-	ULONG					TxErrorRatio = 0;
-	BOOLEAN					bTxRateChanged; //, bUpgradeQuality = FALSE;
-	PRTMP_TX_RATE_SWITCH	pCurrTxRate, pNextTxRate = NULL;
-	PUCHAR					pTable;
-	UCHAR					TableSize = 0;
-	UCHAR					InitTxRateIdx = 0, TrainUp, TrainDown;
-	TX_STA_CNT1_STRUC		StaTx1;
-	TX_STA_CNT0_STRUC		TxStaCnt0;
-	CHAR					Rssi, ratio;
-	ULONG					TxRetransmit = 0, TxSuccess = 0, TxFailCount = 0;
-	MAC_TABLE_ENTRY			*pEntry;
-	ULONG					i;
-
-	pAd->StaCfg.StaQuickResponeForRateUpTimerRunning = FALSE;
-
-    //
-    // walk through MAC table, see if need to change AP's TX rate toward each entry
-    //
-	for (i = 1; i < MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		pEntry = &pAd->MacTab.Content[i];
-
-		// check if this entry need to switch rate automatically
-		if (RTMPCheckEntryEnableAutoRateSwitch(pAd, pEntry) == FALSE)
-			continue;
-
-		if (INFRA_ON(pAd) && (i == 1))
-			Rssi = RTMPMaxRssi(pAd,
-							   pAd->StaCfg.RssiSample.AvgRssi0,
-							   pAd->StaCfg.RssiSample.AvgRssi1,
-							   pAd->StaCfg.RssiSample.AvgRssi2);
-		else
-			Rssi = RTMPMaxRssi(pAd,
-							   pEntry->RssiSample.AvgRssi0,
-							   pEntry->RssiSample.AvgRssi1,
-							   pEntry->RssiSample.AvgRssi2);
-
-		CurrRateIdx = pAd->CommonCfg.TxRateIndex;
-
-			MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &InitTxRateIdx);
-
-		// decide the next upgrade rate and downgrade rate, if any
-		if ((CurrRateIdx > 0) && (CurrRateIdx < (TableSize - 1)))
-		{
-			UpRateIdx = CurrRateIdx + 1;
-			DownRateIdx = CurrRateIdx -1;
-		}
-		else if (CurrRateIdx == 0)
-		{
-			UpRateIdx = CurrRateIdx + 1;
-			DownRateIdx = CurrRateIdx;
-		}
-		else if (CurrRateIdx == (TableSize - 1))
-		{
-			UpRateIdx = CurrRateIdx;
-			DownRateIdx = CurrRateIdx - 1;
-		}
-
-		pCurrTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(CurrRateIdx+1)*5];
-
-#ifdef DOT11_N_SUPPORT
-		if ((Rssi > -65) && (pCurrTxRate->Mode >= MODE_HTMIX))
-		{
-			TrainUp		= (pCurrTxRate->TrainUp + (pCurrTxRate->TrainUp >> 1));
-			TrainDown	= (pCurrTxRate->TrainDown + (pCurrTxRate->TrainDown >> 1));
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			TrainUp		= pCurrTxRate->TrainUp;
-			TrainDown	= pCurrTxRate->TrainDown;
-		}
-
-		if (pAd->MacTab.Size == 1)
-		{
-			// Update statistic counter
-			RTMP_IO_READ32(pAd, TX_STA_CNT0, &TxStaCnt0.word);
-			RTMP_IO_READ32(pAd, TX_STA_CNT1, &StaTx1.word);
-
-			TxRetransmit = StaTx1.field.TxRetransmit;
-			TxSuccess = StaTx1.field.TxSuccess;
-			TxFailCount = TxStaCnt0.field.TxFailCount;
-			TxTotalCnt = TxRetransmit + TxSuccess + TxFailCount;
-
-			pAd->RalinkCounters.OneSecTxRetryOkCount += StaTx1.field.TxRetransmit;
-			pAd->RalinkCounters.OneSecTxNoRetryOkCount += StaTx1.field.TxSuccess;
-			pAd->RalinkCounters.OneSecTxFailCount += TxStaCnt0.field.TxFailCount;
-			pAd->WlanCounters.TransmittedFragmentCount.u.LowPart += StaTx1.field.TxSuccess;
-			pAd->WlanCounters.RetryCount.u.LowPart += StaTx1.field.TxRetransmit;
-			pAd->WlanCounters.FailedCount.u.LowPart += TxStaCnt0.field.TxFailCount;
-
-			if (TxTotalCnt)
-				TxErrorRatio = ((TxRetransmit + TxFailCount) * 100) / TxTotalCnt;
-		}
-		else
-		{
-			TxTotalCnt = pEntry->OneSecTxNoRetryOkCount +
-				 pEntry->OneSecTxRetryOkCount +
-				 pEntry->OneSecTxFailCount;
-
-			if (TxTotalCnt)
-				TxErrorRatio = ((pEntry->OneSecTxRetryOkCount + pEntry->OneSecTxFailCount) * 100) / TxTotalCnt;
-		}
-
-
-		//
-		// CASE 1. when TX samples are fewer than 15, then decide TX rate solely on RSSI
-		//         (criteria copied from RT2500 for Netopia case)
-		//
-		if (TxTotalCnt <= 12)
-		{
-			NdisZeroMemory(pAd->DrsCounters.TxQuality, sizeof(USHORT) * MAX_STEP_OF_TX_RATE_SWITCH);
-			NdisZeroMemory(pAd->DrsCounters.PER, sizeof(UCHAR) * MAX_STEP_OF_TX_RATE_SWITCH);
-
-			if ((pAd->DrsCounters.LastSecTxRateChangeAction == 1) && (CurrRateIdx != DownRateIdx))
-			{
-				pAd->CommonCfg.TxRateIndex = DownRateIdx;
-				pAd->DrsCounters.TxQuality[CurrRateIdx] = DRS_TX_QUALITY_WORST_BOUND;
-			}
-			else if ((pAd->DrsCounters.LastSecTxRateChangeAction == 2) && (CurrRateIdx != UpRateIdx))
-			{
-				pAd->CommonCfg.TxRateIndex = UpRateIdx;
-			}
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE,("QuickDRS: TxTotalCnt <= 15, train back to original rate \n"));
-			return;
-		}
-
-		do
-		{
-			ULONG OneSecTxNoRetryOKRationCount;
-
-			if (pAd->DrsCounters.LastTimeTxRateChangeAction == 0)
-				ratio = 5;
-			else
-				ratio = 4;
-
-			// downgrade TX quality if PER >= Rate-Down threshold
-			if (TxErrorRatio >= TrainDown)
-			{
-				pAd->DrsCounters.TxQuality[CurrRateIdx] = DRS_TX_QUALITY_WORST_BOUND;
-			}
-
-			pAd->DrsCounters.PER[CurrRateIdx] = (UCHAR)TxErrorRatio;
-
-			OneSecTxNoRetryOKRationCount = (TxSuccess * ratio);
-
-			// perform DRS - consider TxRate Down first, then rate up.
-			if ((pAd->DrsCounters.LastSecTxRateChangeAction == 1) && (CurrRateIdx != DownRateIdx))
-			{
-				if ((pAd->DrsCounters.LastTxOkCount + 2) >= OneSecTxNoRetryOKRationCount)
-				{
-					pAd->CommonCfg.TxRateIndex = DownRateIdx;
-					pAd->DrsCounters.TxQuality[CurrRateIdx] = DRS_TX_QUALITY_WORST_BOUND;
-
-				}
-
-			}
-			else if ((pAd->DrsCounters.LastSecTxRateChangeAction == 2) && (CurrRateIdx != UpRateIdx))
-			{
-				if ((TxErrorRatio >= 50) || (TxErrorRatio >= TrainDown))
-				{
-
-				}
-				else if ((pAd->DrsCounters.LastTxOkCount + 2) >= OneSecTxNoRetryOKRationCount)
-				{
-					pAd->CommonCfg.TxRateIndex = UpRateIdx;
-				}
-			}
-		}while (FALSE);
-
-		// if rate-up happen, clear all bad history of all TX rates
-		if (pAd->CommonCfg.TxRateIndex > CurrRateIdx)
-		{
-			pAd->DrsCounters.TxRateUpPenalty = 0;
-			NdisZeroMemory(pAd->DrsCounters.TxQuality, sizeof(USHORT) * MAX_STEP_OF_TX_RATE_SWITCH);
-			NdisZeroMemory(pAd->DrsCounters.PER, sizeof(UCHAR) * MAX_STEP_OF_TX_RATE_SWITCH);
-			bTxRateChanged = TRUE;
-		}
-		// if rate-down happen, only clear DownRate's bad history
-		else if (pAd->CommonCfg.TxRateIndex < CurrRateIdx)
-		{
-			DBGPRINT_RAW(RT_DEBUG_TRACE,("QuickDRS: --TX rate from %d to %d \n", CurrRateIdx, pAd->CommonCfg.TxRateIndex));
-
-			pAd->DrsCounters.TxRateUpPenalty = 0;           // no penalty
-			pAd->DrsCounters.TxQuality[pAd->CommonCfg.TxRateIndex] = 0;
-			pAd->DrsCounters.PER[pAd->CommonCfg.TxRateIndex] = 0;
-			bTxRateChanged = TRUE;
-		}
-		else
-		{
-			bTxRateChanged = FALSE;
-		}
-
-		pNextTxRate = (PRTMP_TX_RATE_SWITCH) &pTable[(pAd->CommonCfg.TxRateIndex+1)*5];
-		if (bTxRateChanged && pNextTxRate)
-		{
-			MlmeSetTxRate(pAd, pEntry, pNextTxRate);
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		This routine is executed periodically inside MlmePeriodicExec() after
-		association with an AP.
-		It checks if StaCfg.Psm is consistent with user policy (recorded in
-		StaCfg.WindowsPowerMode). If not, enforce user policy. However,
-		there're some conditions to consider:
-		1. we don't support power-saving in ADHOC mode, so Psm=PWR_ACTIVE all
-		   the time when Mibss==TRUE
-		2. When link up in INFRA mode, Psm should not be switch to PWR_SAVE
-		   if outgoing traffic available in TxRing or MgmtRing.
-	Output:
-		1. change pAd->StaCfg.Psm to PWR_SAVE or leave it untouched
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID MlmeCheckPsmChange(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG	Now32)
-{
-	ULONG	PowerMode;
-
-	// condition -
-	// 1. Psm maybe ON only happen in INFRASTRUCTURE mode
-	// 2. user wants either MAX_PSP or FAST_PSP
-	// 3. but current psm is not in PWR_SAVE
-	// 4. CNTL state machine is not doing SCANning
-	// 5. no TX SUCCESS event for the past 1-sec period
-#ifdef NDIS51_MINIPORT
-	if (pAd->StaCfg.WindowsPowerProfile == NdisPowerProfileBattery)
-		PowerMode = pAd->StaCfg.WindowsBatteryPowerMode;
-	else
-#endif
-		PowerMode = pAd->StaCfg.WindowsPowerMode;
-
-	if (INFRA_ON(pAd) &&
-		(PowerMode != Ndis802_11PowerModeCAM) &&
-		(pAd->StaCfg.Psm == PWR_ACTIVE) &&
-//		(! RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-		(pAd->Mlme.CntlMachine.CurrState == CNTL_IDLE) /*&&
-		(pAd->RalinkCounters.OneSecTxNoRetryOkCount == 0) &&
-		(pAd->RalinkCounters.OneSecTxRetryOkCount == 0)*/)
-	{
-		// add by johnli, use Rx OK data count per second to calculate throughput
-		// If Ttraffic is too high ( > 400 Rx per second), don't go to sleep mode. If tx rate is low, use low criteria
-		// Mode=CCK/MCS=3 => 11 Mbps, Mode=OFDM/MCS=3 => 18 Mbps
-		if (((pAd->StaCfg.HTPhyMode.field.MCS <= 3) &&
-/* Iverson mark
-				(pAd->StaCfg.HTPhyMode.field.MODE <= MODE_OFDM) &&
-*/
-				(pAd->RalinkCounters.OneSecRxOkDataCnt < (ULONG)100)) ||
-			((pAd->StaCfg.HTPhyMode.field.MCS > 3) &&
-/* Iverson mark
-			(pAd->StaCfg.HTPhyMode.field.MODE > MODE_OFDM) &&
-*/
-			(pAd->RalinkCounters.OneSecRxOkDataCnt < (ULONG)400)))
-		{
-				// Get this time
-			NdisGetSystemUpTime(&pAd->Mlme.LastSendNULLpsmTime);
-			pAd->RalinkCounters.RxCountSinceLastNULL = 0;
-			MlmeSetPsmBit(pAd, PWR_SAVE);
-			if (!(pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable))
-			{
-				RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, FALSE);
-			}
-			else
-			{
-				RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, TRUE);
-			}
-		}
-	}
-}
-
-// IRQL = PASSIVE_LEVEL
-// IRQL = DISPATCH_LEVEL
-VOID MlmeSetPsmBit(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT psm)
-{
-	AUTO_RSP_CFG_STRUC csr4;
-
-	pAd->StaCfg.Psm = psm;
-	RTMP_IO_READ32(pAd, AUTO_RSP_CFG, &csr4.word);
-	csr4.field.AckCtsPsmBit = (psm == PWR_SAVE)? 1:0;
-	RTMP_IO_WRITE32(pAd, AUTO_RSP_CFG, csr4.word);
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-// IRQL = DISPATCH_LEVEL
-VOID MlmeSetTxPreamble(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT TxPreamble)
-{
-	AUTO_RSP_CFG_STRUC csr4;
-
-	//
-	// Always use Long preamble before verifiation short preamble functionality works well.
-	// Todo: remove the following line if short preamble functionality works
-	//
-	//TxPreamble = Rt802_11PreambleLong;
-
-	RTMP_IO_READ32(pAd, AUTO_RSP_CFG, &csr4.word);
-	if (TxPreamble == Rt802_11PreambleLong)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("MlmeSetTxPreamble (= LONG PREAMBLE)\n"));
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-		csr4.field.AutoResponderPreamble = 0;
-	}
-	else
-	{
-		// NOTE: 1Mbps should always use long preamble
-		DBGPRINT(RT_DEBUG_TRACE, ("MlmeSetTxPreamble (= SHORT PREAMBLE)\n"));
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-		csr4.field.AutoResponderPreamble = 1;
-	}
-
-	RTMP_IO_WRITE32(pAd, AUTO_RSP_CFG, csr4.word);
-}
-
-/*
-    ==========================================================================
-    Description:
-        Update basic rate bitmap
-    ==========================================================================
- */
-
-VOID UpdateBasicRateBitmap(
-    IN  PRTMP_ADAPTER   pAdapter)
-{
-    INT  i, j;
-                  /* 1  2  5.5, 11,  6,  9, 12, 18, 24, 36, 48,  54 */
-    UCHAR rate[] = { 2, 4,  11, 22, 12, 18, 24, 36, 48, 72, 96, 108 };
-    UCHAR *sup_p = pAdapter->CommonCfg.SupRate;
-    UCHAR *ext_p = pAdapter->CommonCfg.ExtRate;
-    ULONG bitmap = pAdapter->CommonCfg.BasicRateBitmap;
-
-
-    /* if A mode, always use fix BasicRateBitMap */
-    //if (pAdapter->CommonCfg.Channel == PHY_11A)
-	if (pAdapter->CommonCfg.Channel > 14)
-        pAdapter->CommonCfg.BasicRateBitmap = 0x150; /* 6, 12, 24M */
-    /* End of if */
-
-    if (pAdapter->CommonCfg.BasicRateBitmap > 4095)
-    {
-        /* (2 ^ MAX_LEN_OF_SUPPORTED_RATES) -1 */
-        return;
-    } /* End of if */
-
-    for(i=0; i<MAX_LEN_OF_SUPPORTED_RATES; i++)
-    {
-        sup_p[i] &= 0x7f;
-        ext_p[i] &= 0x7f;
-    } /* End of for */
-
-    for(i=0; i<MAX_LEN_OF_SUPPORTED_RATES; i++)
-    {
-        if (bitmap & (1 << i))
-        {
-            for(j=0; j<MAX_LEN_OF_SUPPORTED_RATES; j++)
-            {
-                if (sup_p[j] == rate[i])
-                    sup_p[j] |= 0x80;
-                /* End of if */
-            } /* End of for */
-
-            for(j=0; j<MAX_LEN_OF_SUPPORTED_RATES; j++)
-            {
-                if (ext_p[j] == rate[i])
-                    ext_p[j] |= 0x80;
-                /* End of if */
-            } /* End of for */
-        } /* End of if */
-    } /* End of for */
-} /* End of UpdateBasicRateBitmap */
-
-// IRQL = PASSIVE_LEVEL
-// IRQL = DISPATCH_LEVEL
-// bLinkUp is to identify the inital link speed.
-// TRUE indicates the rate update at linkup, we should not try to set the rate at 54Mbps.
-VOID MlmeUpdateTxRates(
-	IN PRTMP_ADAPTER 		pAd,
-	IN 	BOOLEAN		 		bLinkUp,
-	IN	UCHAR				apidx)
-{
-	int i, num;
-	UCHAR Rate = RATE_6, MaxDesire = RATE_1, MaxSupport = RATE_1;
-	UCHAR MinSupport = RATE_54;
-	ULONG BasicRateBitmap = 0;
-	UCHAR CurrBasicRate = RATE_1;
-	UCHAR *pSupRate, SupRateLen, *pExtRate, ExtRateLen;
-	PHTTRANSMIT_SETTING		pHtPhy = NULL;
-	PHTTRANSMIT_SETTING		pMaxHtPhy = NULL;
-	PHTTRANSMIT_SETTING		pMinHtPhy = NULL;
-	BOOLEAN 				*auto_rate_cur_p;
-	UCHAR					HtMcs = MCS_AUTO;
-
-	// find max desired rate
-	UpdateBasicRateBitmap(pAd);
-
-	num = 0;
-	auto_rate_cur_p = NULL;
-	for (i=0; i<MAX_LEN_OF_SUPPORTED_RATES; i++)
-	{
-		switch (pAd->CommonCfg.DesireRate[i] & 0x7f)
-		{
-			case 2:  Rate = RATE_1;   num++;   break;
-			case 4:  Rate = RATE_2;   num++;   break;
-			case 11: Rate = RATE_5_5; num++;   break;
-			case 22: Rate = RATE_11;  num++;   break;
-			case 12: Rate = RATE_6;   num++;   break;
-			case 18: Rate = RATE_9;   num++;   break;
-			case 24: Rate = RATE_12;  num++;   break;
-			case 36: Rate = RATE_18;  num++;   break;
-			case 48: Rate = RATE_24;  num++;   break;
-			case 72: Rate = RATE_36;  num++;   break;
-			case 96: Rate = RATE_48;  num++;   break;
-			case 108: Rate = RATE_54; num++;   break;
-			//default: Rate = RATE_1;   break;
-		}
-		if (MaxDesire < Rate)  MaxDesire = Rate;
-	}
-
-//===========================================================================
-//===========================================================================
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		pHtPhy 		= &pAd->StaCfg.HTPhyMode;
-		pMaxHtPhy	= &pAd->StaCfg.MaxHTPhyMode;
-		pMinHtPhy	= &pAd->StaCfg.MinHTPhyMode;
-
-		auto_rate_cur_p = &pAd->StaCfg.bAutoTxRateSwitch;
-		HtMcs 		= pAd->StaCfg.DesiredTransmitSetting.field.MCS;
-
-		if ((pAd->StaCfg.BssType == BSS_ADHOC) &&
-			(pAd->CommonCfg.PhyMode == PHY_11B) &&
-			(MaxDesire > RATE_11))
-		{
-			MaxDesire = RATE_11;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	pAd->CommonCfg.MaxDesiredRate = MaxDesire;
-	pMinHtPhy->word = 0;
-	pMaxHtPhy->word = 0;
-	pHtPhy->word = 0;
-
-	// Auto rate switching is enabled only if more than one DESIRED RATES are
-	// specified; otherwise disabled
-	if (num <= 1)
-	{
-		//OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED);
-		//pAd->CommonCfg.bAutoTxRateSwitch	= FALSE;
-		*auto_rate_cur_p = FALSE;
-	}
-	else
-	{
-		//OPSTATUS_SET_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED);
-		//pAd->CommonCfg.bAutoTxRateSwitch	= TRUE;
-		*auto_rate_cur_p = TRUE;
-	}
-
-#if 1
-	if (HtMcs != MCS_AUTO)
-	{
-		//OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED);
-		//pAd->CommonCfg.bAutoTxRateSwitch	= FALSE;
-		*auto_rate_cur_p = FALSE;
-	}
-	else
-	{
-		//OPSTATUS_SET_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED);
-		//pAd->CommonCfg.bAutoTxRateSwitch	= TRUE;
-		*auto_rate_cur_p = TRUE;
-	}
-#endif
-
-#ifdef CONFIG_STA_SUPPORT
-	if ((ADHOC_ON(pAd) || INFRA_ON(pAd)) && (pAd->OpMode == OPMODE_STA))
-	{
-		pSupRate = &pAd->StaActive.SupRate[0];
-		pExtRate = &pAd->StaActive.ExtRate[0];
-		SupRateLen = pAd->StaActive.SupRateLen;
-		ExtRateLen = pAd->StaActive.ExtRateLen;
-	}
-	else
-#endif // CONFIG_STA_SUPPORT //
-	{
-		pSupRate = &pAd->CommonCfg.SupRate[0];
-		pExtRate = &pAd->CommonCfg.ExtRate[0];
-		SupRateLen = pAd->CommonCfg.SupRateLen;
-		ExtRateLen = pAd->CommonCfg.ExtRateLen;
-	}
-
-	// find max supported rate
-	for (i=0; i<SupRateLen; i++)
-	{
-		switch (pSupRate[i] & 0x7f)
-		{
-			case 2:   Rate = RATE_1;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0001;	 break;
-			case 4:   Rate = RATE_2;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0002;	 break;
-			case 11:  Rate = RATE_5_5;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0004;	 break;
-			case 22:  Rate = RATE_11;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0008;	 break;
-			case 12:  Rate = RATE_6;	/*if (pSupRate[i] & 0x80)*/  BasicRateBitmap |= 0x0010;  break;
-			case 18:  Rate = RATE_9;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0020;	 break;
-			case 24:  Rate = RATE_12;	/*if (pSupRate[i] & 0x80)*/  BasicRateBitmap |= 0x0040;  break;
-			case 36:  Rate = RATE_18;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0080;	 break;
-			case 48:  Rate = RATE_24;	/*if (pSupRate[i] & 0x80)*/  BasicRateBitmap |= 0x0100;  break;
-			case 72:  Rate = RATE_36;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0200;	 break;
-			case 96:  Rate = RATE_48;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0400;	 break;
-			case 108: Rate = RATE_54;	if (pSupRate[i] & 0x80) BasicRateBitmap |= 0x0800;	 break;
-			default:  Rate = RATE_1;	break;
-		}
-		if (MaxSupport < Rate)	MaxSupport = Rate;
-
-		if (MinSupport > Rate) MinSupport = Rate;
-	}
-
-	for (i=0; i<ExtRateLen; i++)
-	{
-		switch (pExtRate[i] & 0x7f)
-		{
-			case 2:   Rate = RATE_1;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0001;	 break;
-			case 4:   Rate = RATE_2;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0002;	 break;
-			case 11:  Rate = RATE_5_5;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0004;	 break;
-			case 22:  Rate = RATE_11;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0008;	 break;
-			case 12:  Rate = RATE_6;	/*if (pExtRate[i] & 0x80)*/  BasicRateBitmap |= 0x0010;  break;
-			case 18:  Rate = RATE_9;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0020;	 break;
-			case 24:  Rate = RATE_12;	/*if (pExtRate[i] & 0x80)*/  BasicRateBitmap |= 0x0040;  break;
-			case 36:  Rate = RATE_18;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0080;	 break;
-			case 48:  Rate = RATE_24;	/*if (pExtRate[i] & 0x80)*/  BasicRateBitmap |= 0x0100;  break;
-			case 72:  Rate = RATE_36;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0200;	 break;
-			case 96:  Rate = RATE_48;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0400;	 break;
-			case 108: Rate = RATE_54;	if (pExtRate[i] & 0x80) BasicRateBitmap |= 0x0800;	 break;
-			default:  Rate = RATE_1;	break;
-		}
-		if (MaxSupport < Rate)	MaxSupport = Rate;
-
-		if (MinSupport > Rate) MinSupport = Rate;
-	}
-
-	RTMP_IO_WRITE32(pAd, LEGACY_BASIC_RATE, BasicRateBitmap);
-
-	// calculate the exptected ACK rate for each TX rate. This info is used to caculate
-	// the DURATION field of outgoing uniicast DATA/MGMT frame
-	for (i=0; i<MAX_LEN_OF_SUPPORTED_RATES; i++)
-	{
-		if (BasicRateBitmap & (0x01 << i))
-			CurrBasicRate = (UCHAR)i;
-		pAd->CommonCfg.ExpectedACKRate[i] = CurrBasicRate;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("MlmeUpdateTxRates[MaxSupport = %d] = MaxDesire %d Mbps\n", RateIdToMbps[MaxSupport], RateIdToMbps[MaxDesire]));
-	// max tx rate = min {max desire rate, max supported rate}
-	if (MaxSupport < MaxDesire)
-		pAd->CommonCfg.MaxTxRate = MaxSupport;
-	else
-		pAd->CommonCfg.MaxTxRate = MaxDesire;
-
-	pAd->CommonCfg.MinTxRate = MinSupport;
-	// 2003-07-31 john - 2500 doesn't have good sensitivity at high OFDM rates. to increase the success
-	// ratio of initial DHCP packet exchange, TX rate starts from a lower rate depending
-	// on average RSSI
-	//	 1. RSSI >= -70db, start at 54 Mbps (short distance)
-	//	 2. -70 > RSSI >= -75, start at 24 Mbps (mid distance)
-	//	 3. -75 > RSSI, start at 11 Mbps (long distance)
-	//if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED)/* &&
-	//	OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)*/)
-	if (*auto_rate_cur_p)
-	{
-		short dbm = 0;
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			dbm = pAd->StaCfg.RssiSample.AvgRssi0 - pAd->BbpRssiToDbmDelta;
-#endif // CONFIG_STA_SUPPORT //
-		if (bLinkUp == TRUE)
-			pAd->CommonCfg.TxRate = RATE_24;
-		else
-			pAd->CommonCfg.TxRate = pAd->CommonCfg.MaxTxRate;
-
-		if (dbm < -75)
-			pAd->CommonCfg.TxRate = RATE_11;
-		else if (dbm < -70)
-			pAd->CommonCfg.TxRate = RATE_24;
-
-		// should never exceed MaxTxRate (consider 11B-only mode)
-		if (pAd->CommonCfg.TxRate > pAd->CommonCfg.MaxTxRate)
-			pAd->CommonCfg.TxRate = pAd->CommonCfg.MaxTxRate;
-
-		pAd->CommonCfg.TxRateIndex = 0;
-	}
-	else
-	{
-		pAd->CommonCfg.TxRate = pAd->CommonCfg.MaxTxRate;
-		pHtPhy->field.MCS	= (pAd->CommonCfg.MaxTxRate > 3) ? (pAd->CommonCfg.MaxTxRate - 4) : pAd->CommonCfg.MaxTxRate;
-		pHtPhy->field.MODE	= (pAd->CommonCfg.MaxTxRate > 3) ? MODE_OFDM : MODE_CCK;
-
-		pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.STBC	= pHtPhy->field.STBC;
-		pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.ShortGI	= pHtPhy->field.ShortGI;
-		pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MCS		= pHtPhy->field.MCS;
-		pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE	= pHtPhy->field.MODE;
-	}
-
-	if (pAd->CommonCfg.TxRate <= RATE_11)
-	{
-		pMaxHtPhy->field.MODE = MODE_CCK;
-		pMaxHtPhy->field.MCS = pAd->CommonCfg.TxRate;
-		pMinHtPhy->field.MCS = pAd->CommonCfg.MinTxRate;
-	}
-	else
-	{
-		pMaxHtPhy->field.MODE = MODE_OFDM;
-		pMaxHtPhy->field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.TxRate];
-		if (pAd->CommonCfg.MinTxRate >= RATE_6 && (pAd->CommonCfg.MinTxRate <= RATE_54))
-			{pMinHtPhy->field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MinTxRate];}
-		else
-			{pMinHtPhy->field.MCS = pAd->CommonCfg.MinTxRate;}
-	}
-
-	pHtPhy->word = (pMaxHtPhy->word);
-	if (bLinkUp && (pAd->OpMode == OPMODE_STA))
-	{
-			pAd->MacTab.Content[BSSID_WCID].HTPhyMode.word = pHtPhy->word;
-			pAd->MacTab.Content[BSSID_WCID].MaxHTPhyMode.word = pMaxHtPhy->word;
-			pAd->MacTab.Content[BSSID_WCID].MinHTPhyMode.word = pMinHtPhy->word;
-	}
-	else
-	{
-		switch (pAd->CommonCfg.PhyMode)
-		{
-			case PHY_11BG_MIXED:
-			case PHY_11B:
-#ifdef DOT11_N_SUPPORT
-			case PHY_11BGN_MIXED:
-#endif // DOT11_N_SUPPORT //
-				pAd->CommonCfg.MlmeRate = RATE_1;
-				pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_CCK;
-				pAd->CommonCfg.MlmeTransmit.field.MCS = RATE_1;
-
-//#ifdef	WIFI_TEST
-				pAd->CommonCfg.RtsRate = RATE_11;
-//#else
-//				pAd->CommonCfg.RtsRate = RATE_1;
-//#endif
-				break;
-			case PHY_11G:
-			case PHY_11A:
-#ifdef DOT11_N_SUPPORT
-			case PHY_11AGN_MIXED:
-			case PHY_11GN_MIXED:
-			case PHY_11N_2_4G:
-			case PHY_11AN_MIXED:
-			case PHY_11N_5G:
-#endif // DOT11_N_SUPPORT //
-				pAd->CommonCfg.MlmeRate = RATE_6;
-				pAd->CommonCfg.RtsRate = RATE_6;
-				pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-				pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-				break;
-			case PHY_11ABG_MIXED:
-#ifdef DOT11_N_SUPPORT
-			case PHY_11ABGN_MIXED:
-#endif // DOT11_N_SUPPORT //
-				if (pAd->CommonCfg.Channel <= 14)
-				{
-					pAd->CommonCfg.MlmeRate = RATE_1;
-					pAd->CommonCfg.RtsRate = RATE_1;
-					pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_CCK;
-					pAd->CommonCfg.MlmeTransmit.field.MCS = RATE_1;
-				}
-				else
-				{
-					pAd->CommonCfg.MlmeRate = RATE_6;
-					pAd->CommonCfg.RtsRate = RATE_6;
-					pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-					pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-				}
-				break;
-			default: // error
-				pAd->CommonCfg.MlmeRate = RATE_6;
-                        	pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-				pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-				pAd->CommonCfg.RtsRate = RATE_1;
-				break;
-		}
-		//
-		// Keep Basic Mlme Rate.
-		//
-		pAd->MacTab.Content[MCAST_WCID].HTPhyMode.word = pAd->CommonCfg.MlmeTransmit.word;
-		if (pAd->CommonCfg.MlmeTransmit.field.MODE == MODE_OFDM)
-			pAd->MacTab.Content[MCAST_WCID].HTPhyMode.field.MCS = OfdmRateToRxwiMCS[RATE_24];
-		else
-			pAd->MacTab.Content[MCAST_WCID].HTPhyMode.field.MCS = RATE_1;
-		pAd->CommonCfg.BasicMlmeRate = pAd->CommonCfg.MlmeRate;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (MaxDesire=%d, MaxSupport=%d, MaxTxRate=%d, MinRate=%d, Rate Switching =%d)\n",
-			 RateIdToMbps[MaxDesire], RateIdToMbps[MaxSupport], RateIdToMbps[pAd->CommonCfg.MaxTxRate], RateIdToMbps[pAd->CommonCfg.MinTxRate],
-			 /*OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED)*/*auto_rate_cur_p));
-	DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (TxRate=%d, RtsRate=%d, BasicRateBitmap=0x%04lx)\n",
-			 RateIdToMbps[pAd->CommonCfg.TxRate], RateIdToMbps[pAd->CommonCfg.RtsRate], BasicRateBitmap));
-	DBGPRINT(RT_DEBUG_TRACE, ("MlmeUpdateTxRates (MlmeTransmit=0x%x, MinHTPhyMode=%x, MaxHTPhyMode=0x%x, HTPhyMode=0x%x)\n",
-			 pAd->CommonCfg.MlmeTransmit.word, pAd->MacTab.Content[BSSID_WCID].MinHTPhyMode.word ,pAd->MacTab.Content[BSSID_WCID].MaxHTPhyMode.word ,pAd->MacTab.Content[BSSID_WCID].HTPhyMode.word ));
-}
-
-#ifdef DOT11_N_SUPPORT
-/*
-	==========================================================================
-	Description:
-		This function update HT Rate setting.
-		Input Wcid value is valid for 2 case :
-		1. it's used for Station in infra mode that copy AP rate to Mactable.
-		2. OR Station 	in adhoc mode to copy peer's HT rate to Mactable.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID MlmeUpdateHtTxRates(
-	IN PRTMP_ADAPTER 		pAd,
-	IN	UCHAR				apidx)
-{
-	UCHAR	StbcMcs; //j, StbcMcs, bitmask;
-	CHAR 	i; // 3*3
-	RT_HT_CAPABILITY 	*pRtHtCap = NULL;
-	RT_HT_PHY_INFO		*pActiveHtPhy = NULL;
-	ULONG		BasicMCS;
-	UCHAR j, bitmask;
-	PRT_HT_PHY_INFO			pDesireHtPhy = NULL;
-	PHTTRANSMIT_SETTING		pHtPhy = NULL;
-	PHTTRANSMIT_SETTING		pMaxHtPhy = NULL;
-	PHTTRANSMIT_SETTING		pMinHtPhy = NULL;
-	BOOLEAN 				*auto_rate_cur_p;
-
-	DBGPRINT(RT_DEBUG_TRACE,("MlmeUpdateHtTxRates===> \n"));
-
-	auto_rate_cur_p = NULL;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		pDesireHtPhy	= &pAd->StaCfg.DesiredHtPhyInfo;
-		pActiveHtPhy	= &pAd->StaCfg.DesiredHtPhyInfo;
-		pHtPhy 		= &pAd->StaCfg.HTPhyMode;
-		pMaxHtPhy	= &pAd->StaCfg.MaxHTPhyMode;
-		pMinHtPhy	= &pAd->StaCfg.MinHTPhyMode;
-
-		auto_rate_cur_p = &pAd->StaCfg.bAutoTxRateSwitch;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-	if ((ADHOC_ON(pAd) || INFRA_ON(pAd)) && (pAd->OpMode == OPMODE_STA))
-	{
-		if (pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE)
-			return;
-
-		pRtHtCap = &pAd->StaActive.SupportedHtPhy;
-		pActiveHtPhy = &pAd->StaActive.SupportedPhyInfo;
-		StbcMcs = (UCHAR)pAd->MlmeAux.AddHtInfo.AddHtInfo3.StbcMcs;
-		BasicMCS =pAd->MlmeAux.AddHtInfo.MCSSet[0]+(pAd->MlmeAux.AddHtInfo.MCSSet[1]<<8)+(StbcMcs<<16);
-		if ((pAd->CommonCfg.DesiredHtPhy.TxSTBC) && (pRtHtCap->RxSTBC) && (pAd->Antenna.field.TxPath == 2))
-			pMaxHtPhy->field.STBC = STBC_USE;
-		else
-			pMaxHtPhy->field.STBC = STBC_NONE;
-	}
-	else
-#endif // CONFIG_STA_SUPPORT //
-	{
-		if (pDesireHtPhy->bHtEnable == FALSE)
-			return;
-
-		pRtHtCap = &pAd->CommonCfg.DesiredHtPhy;
-		StbcMcs = (UCHAR)pAd->CommonCfg.AddHTInfo.AddHtInfo3.StbcMcs;
-		BasicMCS = pAd->CommonCfg.AddHTInfo.MCSSet[0]+(pAd->CommonCfg.AddHTInfo.MCSSet[1]<<8)+(StbcMcs<<16);
-		if ((pAd->CommonCfg.DesiredHtPhy.TxSTBC) && (pRtHtCap->RxSTBC) && (pAd->Antenna.field.TxPath == 2))
-			pMaxHtPhy->field.STBC = STBC_USE;
-		else
-			pMaxHtPhy->field.STBC = STBC_NONE;
-	}
-
-	// Decide MAX ht rate.
-	if ((pRtHtCap->GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-		pMaxHtPhy->field.MODE = MODE_HTGREENFIELD;
-	else
-		pMaxHtPhy->field.MODE = MODE_HTMIX;
-
-    if ((pAd->CommonCfg.DesiredHtPhy.ChannelWidth) && (pRtHtCap->ChannelWidth))
-		pMaxHtPhy->field.BW = BW_40;
-	else
-		pMaxHtPhy->field.BW = BW_20;
-
-    if (pMaxHtPhy->field.BW == BW_20)
-		pMaxHtPhy->field.ShortGI = (pAd->CommonCfg.DesiredHtPhy.ShortGIfor20 & pRtHtCap->ShortGIfor20);
-	else
-		pMaxHtPhy->field.ShortGI = (pAd->CommonCfg.DesiredHtPhy.ShortGIfor40 & pRtHtCap->ShortGIfor40);
-
-	for (i=23; i>=0; i--) // 3*3
-	{
-		j = i/8;
-		bitmask = (1<<(i-(j*8)));
-
-		if ((pActiveHtPhy->MCSSet[j] & bitmask) && (pDesireHtPhy->MCSSet[j] & bitmask))
-		{
-			pMaxHtPhy->field.MCS = i;
-			break;
-		}
-
-		if (i==0)
-			break;
-	}
-
-	// Copy MIN ht rate.  rt2860???
-	pMinHtPhy->field.BW = BW_20;
-	pMinHtPhy->field.MCS = 0;
-	pMinHtPhy->field.STBC = 0;
-	pMinHtPhy->field.ShortGI = 0;
-	//If STA assigns fixed rate. update to fixed here.
-#ifdef CONFIG_STA_SUPPORT
-	if ( (pAd->OpMode == OPMODE_STA) && (pDesireHtPhy->MCSSet[0] != 0xff))
-	{
-		if (pDesireHtPhy->MCSSet[4] != 0)
-		{
-			pMaxHtPhy->field.MCS = 32;
-			pMinHtPhy->field.MCS = 32;
-			DBGPRINT(RT_DEBUG_TRACE,("MlmeUpdateHtTxRates<=== Use Fixed MCS = %d\n",pMinHtPhy->field.MCS));
-		}
-
-		for (i=23; (CHAR)i >= 0; i--) // 3*3
-		{
-			j = i/8;
-			bitmask = (1<<(i-(j*8)));
-			if ( (pDesireHtPhy->MCSSet[j] & bitmask) && (pActiveHtPhy->MCSSet[j] & bitmask))
-			{
-				pMaxHtPhy->field.MCS = i;
-				pMinHtPhy->field.MCS = i;
-				break;
-			}
-			if (i==0)
-				break;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-
-	// Decide ht rate
-	pHtPhy->field.STBC = pMaxHtPhy->field.STBC;
-	pHtPhy->field.BW = pMaxHtPhy->field.BW;
-	pHtPhy->field.MODE = pMaxHtPhy->field.MODE;
-	pHtPhy->field.MCS = pMaxHtPhy->field.MCS;
-	pHtPhy->field.ShortGI = pMaxHtPhy->field.ShortGI;
-
-	// use default now. rt2860
-	if (pDesireHtPhy->MCSSet[0] != 0xff)
-		*auto_rate_cur_p = FALSE;
-	else
-		*auto_rate_cur_p = TRUE;
-
-	DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateHtTxRates<---.AMsduSize = %d  \n", pAd->CommonCfg.DesiredHtPhy.AmsduSize ));
-	DBGPRINT(RT_DEBUG_TRACE,("TX: MCS[0] = %x (choose %d), BW = %d, ShortGI = %d, MODE = %d,  \n", pActiveHtPhy->MCSSet[0],pHtPhy->field.MCS,
-		pHtPhy->field.BW, pHtPhy->field.ShortGI, pHtPhy->field.MODE));
-	DBGPRINT(RT_DEBUG_TRACE,("MlmeUpdateHtTxRates<=== \n"));
-}
-#endif // DOT11_N_SUPPORT //
-
-// IRQL = DISPATCH_LEVEL
-VOID MlmeRadioOff(
-	IN PRTMP_ADAPTER pAd)
-{
-	RT28XX_MLME_RADIO_OFF(pAd);
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID MlmeRadioOn(
-	IN PRTMP_ADAPTER pAd)
-{
-	RT28XX_MLME_RADIO_ON(pAd);
-}
-
-// ===========================================================================================
-// bss_table.c
-// ===========================================================================================
-
-
-/*! \brief initialize BSS table
- *	\param p_tab pointer to the table
- *	\return none
- *	\pre
- *	\post
-
- IRQL = PASSIVE_LEVEL
- IRQL = DISPATCH_LEVEL
-
- */
-VOID BssTableInit(
-	IN BSS_TABLE *Tab)
-{
-	int i;
-
-	Tab->BssNr = 0;
-    Tab->BssOverlapNr = 0;
-	for (i = 0; i < MAX_LEN_OF_BSS_TABLE; i++)
-	{
-		NdisZeroMemory(&Tab->BssEntry[i], sizeof(BSS_ENTRY));
-		Tab->BssEntry[i].Rssi = -127;	// initial the rssi as a minimum value
-	}
-}
-
-#ifdef DOT11_N_SUPPORT
-VOID BATableInit(
-	IN PRTMP_ADAPTER pAd,
-    IN BA_TABLE *Tab)
-{
-	int i;
-
-	Tab->numAsOriginator = 0;
-	Tab->numAsRecipient = 0;
-	NdisAllocateSpinLock(&pAd->BATabLock);
-	for (i = 0; i < MAX_LEN_OF_BA_REC_TABLE; i++)
-	{
-		Tab->BARecEntry[i].REC_BA_Status = Recipient_NONE;
-		NdisAllocateSpinLock(&(Tab->BARecEntry[i].RxReRingLock));
-	}
-	for (i = 0; i < MAX_LEN_OF_BA_ORI_TABLE; i++)
-	{
-		Tab->BAOriEntry[i].ORI_BA_Status = Originator_NONE;
-	}
-}
-#endif // DOT11_N_SUPPORT //
-
-/*! \brief search the BSS table by SSID
- *	\param p_tab pointer to the bss table
- *	\param ssid SSID string
- *	\return index of the table, BSS_NOT_FOUND if not in the table
- *	\pre
- *	\post
- *	\note search by sequential search
-
- IRQL = DISPATCH_LEVEL
-
- */
-ULONG BssTableSearch(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR	 pBssid,
-	IN UCHAR	 Channel)
-{
-	UCHAR i;
-
-	for (i = 0; i < Tab->BssNr; i++)
-	{
-		//
-		// Some AP that support A/B/G mode that may used the same BSSID on 11A and 11B/G.
-		// We should distinguish this case.
-		//
-		if ((((Tab->BssEntry[i].Channel <= 14) && (Channel <= 14)) ||
-			 ((Tab->BssEntry[i].Channel > 14) && (Channel > 14))) &&
-			MAC_ADDR_EQUAL(Tab->BssEntry[i].Bssid, pBssid))
-		{
-			return i;
-		}
-	}
-	return (ULONG)BSS_NOT_FOUND;
-}
-
-ULONG BssSsidTableSearch(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR	 pBssid,
-	IN PUCHAR	 pSsid,
-	IN UCHAR	 SsidLen,
-	IN UCHAR	 Channel)
-{
-	UCHAR i;
-
-	for (i = 0; i < Tab->BssNr; i++)
-	{
-		//
-		// Some AP that support A/B/G mode that may used the same BSSID on 11A and 11B/G.
-		// We should distinguish this case.
-		//
-		if ((((Tab->BssEntry[i].Channel <= 14) && (Channel <= 14)) ||
-			 ((Tab->BssEntry[i].Channel > 14) && (Channel > 14))) &&
-			MAC_ADDR_EQUAL(Tab->BssEntry[i].Bssid, pBssid) &&
-			SSID_EQUAL(pSsid, SsidLen, Tab->BssEntry[i].Ssid, Tab->BssEntry[i].SsidLen))
-		{
-			return i;
-		}
-	}
-	return (ULONG)BSS_NOT_FOUND;
-}
-
-ULONG BssTableSearchWithSSID(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR	 Bssid,
-	IN PUCHAR	 pSsid,
-	IN UCHAR	 SsidLen,
-	IN UCHAR	 Channel)
-{
-	UCHAR i;
-
-	for (i = 0; i < Tab->BssNr; i++)
-	{
-		if ((((Tab->BssEntry[i].Channel <= 14) && (Channel <= 14)) ||
-			((Tab->BssEntry[i].Channel > 14) && (Channel > 14))) &&
-			MAC_ADDR_EQUAL(&(Tab->BssEntry[i].Bssid), Bssid) &&
-			(SSID_EQUAL(pSsid, SsidLen, Tab->BssEntry[i].Ssid, Tab->BssEntry[i].SsidLen) ||
-			(NdisEqualMemory(pSsid, ZeroSsid, SsidLen)) ||
-			(NdisEqualMemory(Tab->BssEntry[i].Ssid, ZeroSsid, Tab->BssEntry[i].SsidLen))))
-		{
-			return i;
-		}
-	}
-	return (ULONG)BSS_NOT_FOUND;
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID BssTableDeleteEntry(
-	IN OUT	BSS_TABLE *Tab,
-	IN		PUCHAR	  pBssid,
-	IN		UCHAR	  Channel)
-{
-	UCHAR i, j;
-
-	for (i = 0; i < Tab->BssNr; i++)
-	{
-		if ((Tab->BssEntry[i].Channel == Channel) &&
-			(MAC_ADDR_EQUAL(Tab->BssEntry[i].Bssid, pBssid)))
-		{
-			for (j = i; j < Tab->BssNr - 1; j++)
-			{
-				NdisMoveMemory(&(Tab->BssEntry[j]), &(Tab->BssEntry[j + 1]), sizeof(BSS_ENTRY));
-			}
-			NdisZeroMemory(&(Tab->BssEntry[Tab->BssNr - 1]), sizeof(BSS_ENTRY));
-			Tab->BssNr -= 1;
-			return;
-		}
-	}
-}
-
-#ifdef DOT11_N_SUPPORT
-/*
-	========================================================================
-	Routine Description:
-		Delete the Originator Entry in BAtable. Or decrease numAs Originator by 1 if needed.
-
-	Arguments:
-	// IRQL = DISPATCH_LEVEL
-	========================================================================
-*/
-VOID BATableDeleteORIEntry(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		BA_ORI_ENTRY	*pBAORIEntry)
-{
-
-	if (pBAORIEntry->ORI_BA_Status != Originator_NONE)
-	{
-		NdisAcquireSpinLock(&pAd->BATabLock);
-		if (pBAORIEntry->ORI_BA_Status == Originator_Done)
-		{
-			pAd->BATable.numAsOriginator -= 1;
-			DBGPRINT(RT_DEBUG_TRACE, ("BATableDeleteORIEntry numAsOriginator= %ld\n", pAd->BATable.numAsRecipient));
-			// Erase Bitmap flag.
-		}
-		pAd->MacTab.Content[pBAORIEntry->Wcid].TXBAbitmap &= (~(1<<(pBAORIEntry->TID) ));	// If STA mode,  erase flag here
-		pAd->MacTab.Content[pBAORIEntry->Wcid].BAOriWcidArray[pBAORIEntry->TID] = 0;	// If STA mode,  erase flag here
-		pBAORIEntry->ORI_BA_Status = Originator_NONE;
-		pBAORIEntry->Token = 1;
-		// Not clear Sequence here.
-		NdisReleaseSpinLock(&pAd->BATabLock);
-	}
-}
-#endif // DOT11_N_SUPPORT //
-
-/*! \brief
- *	\param
- *	\return
- *	\pre
- *	\post
-
- IRQL = DISPATCH_LEVEL
-
- */
-VOID BssEntrySet(
-	IN PRTMP_ADAPTER	pAd,
-	OUT BSS_ENTRY *pBss,
-	IN PUCHAR pBssid,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR BssType,
-	IN USHORT BeaconPeriod,
-	IN PCF_PARM pCfParm,
-	IN USHORT AtimWin,
-	IN USHORT CapabilityInfo,
-	IN UCHAR SupRate[],
-	IN UCHAR SupRateLen,
-	IN UCHAR ExtRate[],
-	IN UCHAR ExtRateLen,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN ADD_HT_INFO_IE *pAddHtInfo,	// AP might use this additional ht info IE
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			AddHtInfoLen,
-	IN UCHAR			NewExtChanOffset,
-	IN UCHAR Channel,
-	IN CHAR Rssi,
-	IN LARGE_INTEGER TimeStamp,
-	IN UCHAR CkipFlag,
-	IN PEDCA_PARM pEdcaParm,
-	IN PQOS_CAPABILITY_PARM pQosCapability,
-	IN PQBSS_LOAD_PARM pQbssLoad,
-	IN USHORT LengthVIE,
-	IN PNDIS_802_11_VARIABLE_IEs pVIE)
-{
-	COPY_MAC_ADDR(pBss->Bssid, pBssid);
-	// Default Hidden SSID to be TRUE, it will be turned to FALSE after coping SSID
-	pBss->Hidden = 1;
-	if (SsidLen > 0)
-	{
-		// For hidden SSID AP, it might send beacon with SSID len equal to 0
-		// Or send beacon /probe response with SSID len matching real SSID length,
-		// but SSID is all zero. such as "00-00-00-00" with length 4.
-		// We have to prevent this case overwrite correct table
-		if (NdisEqualMemory(Ssid, ZeroSsid, SsidLen) == 0)
-		{
-		    NdisZeroMemory(pBss->Ssid, MAX_LEN_OF_SSID);
-			NdisMoveMemory(pBss->Ssid, Ssid, SsidLen);
-			pBss->SsidLen = SsidLen;
-			pBss->Hidden = 0;
-		}
-	}
-	else
-		pBss->SsidLen = 0;
-	pBss->BssType = BssType;
-	pBss->BeaconPeriod = BeaconPeriod;
-	if (BssType == BSS_INFRA)
-	{
-		if (pCfParm->bValid)
-		{
-			pBss->CfpCount = pCfParm->CfpCount;
-			pBss->CfpPeriod = pCfParm->CfpPeriod;
-			pBss->CfpMaxDuration = pCfParm->CfpMaxDuration;
-			pBss->CfpDurRemaining = pCfParm->CfpDurRemaining;
-		}
-	}
-	else
-	{
-		pBss->AtimWin = AtimWin;
-	}
-
-	pBss->CapabilityInfo = CapabilityInfo;
-	// The privacy bit indicate security is ON, it maight be WEP, TKIP or AES
-	// Combine with AuthMode, they will decide the connection methods.
-	pBss->Privacy = CAP_IS_PRIVACY_ON(pBss->CapabilityInfo);
-	ASSERT(SupRateLen <= MAX_LEN_OF_SUPPORTED_RATES);
-	if (SupRateLen <= MAX_LEN_OF_SUPPORTED_RATES)
-		NdisMoveMemory(pBss->SupRate, SupRate, SupRateLen);
-	else
-		NdisMoveMemory(pBss->SupRate, SupRate, MAX_LEN_OF_SUPPORTED_RATES);
-	pBss->SupRateLen = SupRateLen;
-	ASSERT(ExtRateLen <= MAX_LEN_OF_SUPPORTED_RATES);
-	NdisMoveMemory(pBss->ExtRate, ExtRate, ExtRateLen);
-	NdisMoveMemory(&pBss->HtCapability, pHtCapability, HtCapabilityLen);
-	NdisMoveMemory(&pBss->AddHtInfo, pAddHtInfo, AddHtInfoLen);
-	pBss->NewExtChanOffset = NewExtChanOffset;
-	pBss->ExtRateLen = ExtRateLen;
-	pBss->Channel = Channel;
-	pBss->CentralChannel = Channel;
-	pBss->Rssi = Rssi;
-	// Update CkipFlag. if not exists, the value is 0x0
-	pBss->CkipFlag = CkipFlag;
-
-	// New for microsoft Fixed IEs
-	NdisMoveMemory(pBss->FixIEs.Timestamp, &TimeStamp, 8);
-	pBss->FixIEs.BeaconInterval = BeaconPeriod;
-	pBss->FixIEs.Capabilities = CapabilityInfo;
-
-	// New for microsoft Variable IEs
-	if (LengthVIE != 0)
-	{
-		pBss->VarIELen = LengthVIE;
-		NdisMoveMemory(pBss->VarIEs, pVIE, pBss->VarIELen);
-	}
-	else
-	{
-		pBss->VarIELen = 0;
-	}
-
-	pBss->AddHtInfoLen = 0;
-	pBss->HtCapabilityLen = 0;
-#ifdef DOT11_N_SUPPORT
-	if (HtCapabilityLen> 0)
-	{
-		pBss->HtCapabilityLen = HtCapabilityLen;
-		NdisMoveMemory(&pBss->HtCapability, pHtCapability, HtCapabilityLen);
-		if (AddHtInfoLen > 0)
-		{
-			pBss->AddHtInfoLen = AddHtInfoLen;
-			NdisMoveMemory(&pBss->AddHtInfo, pAddHtInfo, AddHtInfoLen);
-
-	 			if ((pAddHtInfo->ControlChan > 2)&& (pAddHtInfo->AddHtInfo.ExtChanOffset == EXTCHA_BELOW) && (pHtCapability->HtCapInfo.ChannelWidth == BW_40))
-	 			{
-	 				pBss->CentralChannel = pAddHtInfo->ControlChan - 2;
-	 			}
-	 			else if ((pAddHtInfo->AddHtInfo.ExtChanOffset == EXTCHA_ABOVE) && (pHtCapability->HtCapInfo.ChannelWidth == BW_40))
-				{
-		 				pBss->CentralChannel = pAddHtInfo->ControlChan + 2;
-				}
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-	BssCipherParse(pBss);
-
-	// new for QOS
-	if (pEdcaParm)
-		NdisMoveMemory(&pBss->EdcaParm, pEdcaParm, sizeof(EDCA_PARM));
-	else
-		pBss->EdcaParm.bValid = FALSE;
-	if (pQosCapability)
-		NdisMoveMemory(&pBss->QosCapability, pQosCapability, sizeof(QOS_CAPABILITY_PARM));
-	else
-		pBss->QosCapability.bValid = FALSE;
-	if (pQbssLoad)
-		NdisMoveMemory(&pBss->QbssLoad, pQbssLoad, sizeof(QBSS_LOAD_PARM));
-	else
-		pBss->QbssLoad.bValid = FALSE;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		PEID_STRUCT     pEid;
-		USHORT          Length = 0;
-
-
-		NdisZeroMemory(&pBss->WpaIE.IE[0], MAX_CUSTOM_LEN);
-		NdisZeroMemory(&pBss->RsnIE.IE[0], MAX_CUSTOM_LEN);
-#ifdef EXT_BUILD_CHANNEL_LIST
-		NdisZeroMemory(&pBss->CountryString[0], 3);
-		pBss->bHasCountryIE = FALSE;
-#endif // EXT_BUILD_CHANNEL_LIST //
-		pEid = (PEID_STRUCT) pVIE;
-		while ((Length + 2 + (USHORT)pEid->Len) <= LengthVIE)
-		{
-			switch(pEid->Eid)
-			{
-				case IE_WPA:
-					if (NdisEqualMemory(pEid->Octet, WPA_OUI, 4))
-					{
-						if ((pEid->Len + 2) > MAX_CUSTOM_LEN)
-						{
-							pBss->WpaIE.IELen = 0;
-							break;
-						}
-						pBss->WpaIE.IELen = pEid->Len + 2;
-						NdisMoveMemory(pBss->WpaIE.IE, pEid, pBss->WpaIE.IELen);
-					}
-					break;
-                case IE_RSN:
-                    if (NdisEqualMemory(pEid->Octet + 2, RSN_OUI, 3))
-					{
-						if ((pEid->Len + 2) > MAX_CUSTOM_LEN)
-						{
-							pBss->RsnIE.IELen = 0;
-							break;
-						}
-						pBss->RsnIE.IELen = pEid->Len + 2;
-						NdisMoveMemory(pBss->RsnIE.IE, pEid, pBss->RsnIE.IELen);
-			}
-				break;
-#ifdef EXT_BUILD_CHANNEL_LIST
-				case IE_COUNTRY:
-					NdisMoveMemory(&pBss->CountryString[0], pEid->Octet, 3);
-					pBss->bHasCountryIE = TRUE;
-					break;
-#endif // EXT_BUILD_CHANNEL_LIST //
-            }
-			Length = Length + 2 + (USHORT)pEid->Len;  // Eid[1] + Len[1]+ content[Len]
-			pEid = (PEID_STRUCT)((UCHAR*)pEid + 2 + pEid->Len);
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-}
-
-/*!
- *	\brief insert an entry into the bss table
- *	\param p_tab The BSS table
- *	\param Bssid BSSID
- *	\param ssid SSID
- *	\param ssid_len Length of SSID
- *	\param bss_type
- *	\param beacon_period
- *	\param timestamp
- *	\param p_cf
- *	\param atim_win
- *	\param cap
- *	\param rates
- *	\param rates_len
- *	\param channel_idx
- *	\return none
- *	\pre
- *	\post
- *	\note If SSID is identical, the old entry will be replaced by the new one
-
- IRQL = DISPATCH_LEVEL
-
- */
-ULONG BssTableSetEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT BSS_TABLE *Tab,
-	IN PUCHAR pBssid,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR BssType,
-	IN USHORT BeaconPeriod,
-	IN CF_PARM *CfParm,
-	IN USHORT AtimWin,
-	IN USHORT CapabilityInfo,
-	IN UCHAR SupRate[],
-	IN UCHAR SupRateLen,
-	IN UCHAR ExtRate[],
-	IN UCHAR ExtRateLen,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN ADD_HT_INFO_IE *pAddHtInfo,	// AP might use this additional ht info IE
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			AddHtInfoLen,
-	IN UCHAR			NewExtChanOffset,
-	IN UCHAR ChannelNo,
-	IN CHAR Rssi,
-	IN LARGE_INTEGER TimeStamp,
-	IN UCHAR CkipFlag,
-	IN PEDCA_PARM pEdcaParm,
-	IN PQOS_CAPABILITY_PARM pQosCapability,
-	IN PQBSS_LOAD_PARM pQbssLoad,
-	IN USHORT LengthVIE,
-	IN PNDIS_802_11_VARIABLE_IEs pVIE)
-{
-	ULONG	Idx;
-
-	Idx = BssTableSearchWithSSID(Tab, pBssid,  Ssid, SsidLen, ChannelNo);
-	if (Idx == BSS_NOT_FOUND)
-	{
-		if (Tab->BssNr >= MAX_LEN_OF_BSS_TABLE)
-	    {
-			//
-			// It may happen when BSS Table was full.
-			// The desired AP will not be added into BSS Table
-			// In this case, if we found the desired AP then overwrite BSS Table.
-			//
-			if(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-			{
-				if (MAC_ADDR_EQUAL(pAd->MlmeAux.Bssid, pBssid) ||
-					SSID_EQUAL(pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen, Ssid, SsidLen))
-				{
-					Idx = Tab->BssOverlapNr;
-					BssEntrySet(pAd, &Tab->BssEntry[Idx], pBssid, Ssid, SsidLen, BssType, BeaconPeriod, CfParm, AtimWin,
-						CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,pHtCapability, pAddHtInfo,HtCapabilityLen, AddHtInfoLen,
-						NewExtChanOffset, ChannelNo, Rssi, TimeStamp, CkipFlag, pEdcaParm, pQosCapability, pQbssLoad, LengthVIE, pVIE);
-                    Tab->BssOverlapNr = (Tab->BssOverlapNr++) % MAX_LEN_OF_BSS_TABLE;
-				}
-				return Idx;
-			}
-			else
-			{
-			return BSS_NOT_FOUND;
-			}
-		}
-		Idx = Tab->BssNr;
-		BssEntrySet(pAd, &Tab->BssEntry[Idx], pBssid, Ssid, SsidLen, BssType, BeaconPeriod, CfParm, AtimWin,
-					CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,pHtCapability, pAddHtInfo,HtCapabilityLen, AddHtInfoLen,
-					NewExtChanOffset, ChannelNo, Rssi, TimeStamp, CkipFlag, pEdcaParm, pQosCapability, pQbssLoad, LengthVIE, pVIE);
-		Tab->BssNr++;
-	}
-	else
-	{
-		/* avoid  Hidden SSID form beacon to overwirite correct SSID from probe response */
-		if ((SSID_EQUAL(Ssid, SsidLen, Tab->BssEntry[Idx].Ssid, Tab->BssEntry[Idx].SsidLen)) ||
-			(NdisEqualMemory(Tab->BssEntry[Idx].Ssid, ZeroSsid, Tab->BssEntry[Idx].SsidLen)))
-		{
-			BssEntrySet(pAd, &Tab->BssEntry[Idx], pBssid, Ssid, SsidLen, BssType, BeaconPeriod,CfParm, AtimWin,
-						CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,pHtCapability, pAddHtInfo,HtCapabilityLen, AddHtInfoLen,
-						NewExtChanOffset, ChannelNo, Rssi, TimeStamp, CkipFlag, pEdcaParm, pQosCapability, pQbssLoad, LengthVIE, pVIE);
-		}
-	}
-
-	return Idx;
-}
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-VOID  TriEventInit(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UCHAR		i;
-
-	for (i = 0;i < MAX_TRIGGER_EVENT;i++)
-		pAd->CommonCfg.TriggerEventTab.EventA[i].bValid = FALSE;
-
-	pAd->CommonCfg.TriggerEventTab.EventANo = 0;
-	pAd->CommonCfg.TriggerEventTab.EventBCountDown = 0;
-}
-
-ULONG TriEventTableSetEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT TRIGGER_EVENT_TAB *Tab,
-	IN PUCHAR pBssid,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			RegClass,
-	IN UCHAR ChannelNo)
-{
-	// Event A
-	if (HtCapabilityLen == 0)
-	{
-		if (Tab->EventANo < MAX_TRIGGER_EVENT)
-		{
-			RTMPMoveMemory(Tab->EventA[Tab->EventANo].BSSID, pBssid, 6);
-			Tab->EventA[Tab->EventANo].bValid = TRUE;
-			Tab->EventA[Tab->EventANo].Channel = ChannelNo;
-			Tab->EventA[Tab->EventANo].CDCounter = pAd->CommonCfg.Dot11BssWidthChanTranDelay;
-			if (RegClass != 0)
-			{
-				// Beacon has Regulatory class IE. So use beacon's
-				Tab->EventA[Tab->EventANo].RegClass = RegClass;
-			}
-			else
-			{
-				// Use Station's Regulatory class instead.
-				if (pAd->StaActive.SupportedHtPhy.bHtEnable == TRUE)
-				{
-					if (pAd->CommonCfg.CentralChannel > pAd->CommonCfg.Channel)
-					{
-						Tab->EventA[Tab->EventANo].RegClass = 32;
-					}
-					else if (pAd->CommonCfg.CentralChannel < pAd->CommonCfg.Channel)
-						Tab->EventA[Tab->EventANo].RegClass = 33;
-				}
-				else
-					Tab->EventA[Tab->EventANo].RegClass = ??;
-
-			}
-
-			Tab->EventANo ++;
-		}
-	}
-	else if (pHtCapability->HtCapInfo.Intolerant40)
-	{
-		Tab->EventBCountDown = pAd->CommonCfg.Dot11BssWidthChanTranDelay;
-	}
-
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Trigger Event table Maintainence called once every second.
-
-	Arguments:
-	// IRQL = DISPATCH_LEVEL
-	========================================================================
-*/
-VOID TriEventCounterMaintenance(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UCHAR		i;
-	BOOLEAN			bNotify = FALSE;
-	for (i = 0;i < MAX_TRIGGER_EVENT;i++)
-	{
-		if (pAd->CommonCfg.TriggerEventTab.EventA[i].bValid && (pAd->CommonCfg.TriggerEventTab.EventA[i].CDCounter > 0))
-		{
-			pAd->CommonCfg.TriggerEventTab.EventA[i].CDCounter--;
-			if (pAd->CommonCfg.TriggerEventTab.EventA[i].CDCounter == 0)
-			{
-				pAd->CommonCfg.TriggerEventTab.EventA[i].bValid = FALSE;
-				pAd->CommonCfg.TriggerEventTab.EventANo --;
-				// Need to send 20/40 Coexistence Notify frame if has status change.
-				bNotify = TRUE;
-			}
-		}
-	}
-	if (pAd->CommonCfg.TriggerEventTab.EventBCountDown > 0)
-	{
-		pAd->CommonCfg.TriggerEventTab.EventBCountDown--;
-		if (pAd->CommonCfg.TriggerEventTab.EventBCountDown == 0)
-			bNotify = TRUE;
-	}
-
-	if (bNotify == TRUE)
-		Update2040CoexistFrameAndNotify(pAd, BSSID_WCID, TRUE);
-}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-// IRQL = DISPATCH_LEVEL
-VOID BssTableSsidSort(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT BSS_TABLE *OutTab,
-	IN	CHAR Ssid[],
-	IN	UCHAR SsidLen)
-{
-	INT i;
-	BssTableInit(OutTab);
-
-	for (i = 0; i < pAd->ScanTab.BssNr; i++)
-	{
-		BSS_ENTRY *pInBss = &pAd->ScanTab.BssEntry[i];
-		BOOLEAN	bIsHiddenApIncluded = FALSE;
-
-		if (((pAd->CommonCfg.bIEEE80211H == 1) &&
-            (pAd->MlmeAux.Channel > 14) &&
-             RadarChannelCheck(pAd, pInBss->Channel))
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-             || (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-#endif // CARRIER_DETECTION_SUPPORT //
-            )
-		{
-			if (pInBss->Hidden)
-				bIsHiddenApIncluded = TRUE;
-		}
-
-		if ((pInBss->BssType == pAd->StaCfg.BssType) &&
-			(SSID_EQUAL(Ssid, SsidLen, pInBss->Ssid, pInBss->SsidLen) || bIsHiddenApIncluded))
-		{
-			BSS_ENTRY *pOutBss = &OutTab->BssEntry[OutTab->BssNr];
-
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-			// If no Country IE exists no Connection will be established when IEEE80211dClientMode is strict.
-			if ((pAd->StaCfg.IEEE80211dClientMode == Rt802_11_D_Strict) &&
-				(pInBss->bHasCountryIE == FALSE))
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("StaCfg.IEEE80211dClientMode == Rt802_11_D_Strict, but this AP doesn't have country IE.\n"));
-				continue;
-			}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef DOT11_N_SUPPORT
-			// 2.4G/5G N only mode
-			if ((pInBss->HtCapabilityLen == 0) &&
-				((pAd->CommonCfg.PhyMode == PHY_11N_2_4G) || (pAd->CommonCfg.PhyMode == PHY_11N_5G)))
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("STA is in N-only Mode, this AP don't have Ht capability in Beacon.\n"));
-				continue;
-			}
-#endif // DOT11_N_SUPPORT //
-
-			// New for WPA2
-			// Check the Authmode first
-			if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-			{
-				// Check AuthMode and AuthModeAux for matching, in case AP support dual-mode
-				if ((pAd->StaCfg.AuthMode != pInBss->AuthMode) && (pAd->StaCfg.AuthMode != pInBss->AuthModeAux))
-					// None matched
-					continue;
-
-				// Check cipher suite, AP must have more secured cipher than station setting
-				if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-				{
-					// If it's not mixed mode, we should only let BSS pass with the same encryption
-					if (pInBss->WPA.bMixMode == FALSE)
-						if (pAd->StaCfg.WepStatus != pInBss->WPA.GroupCipher)
-							continue;
-
-					// check group cipher
-					if (pAd->StaCfg.WepStatus < pInBss->WPA.GroupCipher)
-						continue;
-
-					// check pairwise cipher, skip if none matched
-					// If profile set to AES, let it pass without question.
-					// If profile set to TKIP, we must find one mateched
-					if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA.PairCipher) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA.PairCipherAux))
-						continue;
-				}
-				else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-				{
-					// If it's not mixed mode, we should only let BSS pass with the same encryption
-					if (pInBss->WPA2.bMixMode == FALSE)
-						if (pAd->StaCfg.WepStatus != pInBss->WPA2.GroupCipher)
-							continue;
-
-					// check group cipher
-					if (pAd->StaCfg.WepStatus < pInBss->WPA2.GroupCipher)
-						continue;
-
-					// check pairwise cipher, skip if none matched
-					// If profile set to AES, let it pass without question.
-					// If profile set to TKIP, we must find one mateched
-					if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA2.PairCipher) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA2.PairCipherAux))
-						continue;
-				}
-			}
-			// Bss Type matched, SSID matched.
-			// We will check wepstatus for qualification Bss
-			else if (pAd->StaCfg.WepStatus != pInBss->WepStatus)
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("StaCfg.WepStatus=%d, while pInBss->WepStatus=%d\n", pAd->StaCfg.WepStatus, pInBss->WepStatus));
-				//
-				// For the SESv2 case, we will not qualify WepStatus.
-				//
-				if (!pInBss->bSES)
-					continue;
-			}
-
-			// Since the AP is using hidden SSID, and we are trying to connect to ANY
-			// It definitely will fail. So, skip it.
-			// CCX also require not even try to connect it!!
-			if (SsidLen == 0)
-				continue;
-
-#ifdef DOT11_N_SUPPORT
-			// If both station and AP use 40MHz, still need to check if the 40MHZ band's legality in my country region
-			// If this 40MHz wideband is not allowed in my country list, use bandwidth 20MHZ instead,
-			if ((pInBss->CentralChannel != pInBss->Channel) &&
-				(pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40))
-			{
-				if (RTMPCheckChannel(pAd, pInBss->CentralChannel, pInBss->Channel) == FALSE)
-				{
-					pAd->CommonCfg.RegTransmitSetting.field.BW = BW_20;
-					SetCommonHT(pAd);
-					pAd->CommonCfg.RegTransmitSetting.field.BW = BW_40;
-				}
-				else
-				{
-					if (pAd->CommonCfg.DesiredHtPhy.ChannelWidth == BAND_WIDTH_20)
-					{
-						SetCommonHT(pAd);
-					}
-				}
-			}
-#endif // DOT11_N_SUPPORT //
-
-			// copy matching BSS from InTab to OutTab
-			NdisMoveMemory(pOutBss, pInBss, sizeof(BSS_ENTRY));
-
-			OutTab->BssNr++;
-		}
-		else if ((pInBss->BssType == pAd->StaCfg.BssType) && (SsidLen == 0))
-		{
-			BSS_ENTRY *pOutBss = &OutTab->BssEntry[OutTab->BssNr];
-
-
-#ifdef DOT11_N_SUPPORT
-			// 2.4G/5G N only mode
-			if ((pInBss->HtCapabilityLen == 0) &&
-				((pAd->CommonCfg.PhyMode == PHY_11N_2_4G) || (pAd->CommonCfg.PhyMode == PHY_11N_5G)))
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("STA is in N-only Mode, this AP don't have Ht capability in Beacon.\n"));
-				continue;
-			}
-#endif // DOT11_N_SUPPORT //
-
-			// New for WPA2
-			// Check the Authmode first
-			if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-			{
-				// Check AuthMode and AuthModeAux for matching, in case AP support dual-mode
-				if ((pAd->StaCfg.AuthMode != pInBss->AuthMode) && (pAd->StaCfg.AuthMode != pInBss->AuthModeAux))
-					// None matched
-					continue;
-
-				// Check cipher suite, AP must have more secured cipher than station setting
-				if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-				{
-					// If it's not mixed mode, we should only let BSS pass with the same encryption
-					if (pInBss->WPA.bMixMode == FALSE)
-						if (pAd->StaCfg.WepStatus != pInBss->WPA.GroupCipher)
-							continue;
-
-					// check group cipher
-					if (pAd->StaCfg.WepStatus < pInBss->WPA.GroupCipher)
-						continue;
-
-					// check pairwise cipher, skip if none matched
-					// If profile set to AES, let it pass without question.
-					// If profile set to TKIP, we must find one mateched
-					if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA.PairCipher) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA.PairCipherAux))
-						continue;
-				}
-				else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-				{
-					// If it's not mixed mode, we should only let BSS pass with the same encryption
-					if (pInBss->WPA2.bMixMode == FALSE)
-						if (pAd->StaCfg.WepStatus != pInBss->WPA2.GroupCipher)
-							continue;
-
-					// check group cipher
-					if (pAd->StaCfg.WepStatus < pInBss->WPA2.GroupCipher)
-						continue;
-
-					// check pairwise cipher, skip if none matched
-					// If profile set to AES, let it pass without question.
-					// If profile set to TKIP, we must find one mateched
-					if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA2.PairCipher) &&
-						(pAd->StaCfg.WepStatus != pInBss->WPA2.PairCipherAux))
-						continue;
-				}
-			}
-			// Bss Type matched, SSID matched.
-			// We will check wepstatus for qualification Bss
-			else if (pAd->StaCfg.WepStatus != pInBss->WepStatus)
-					continue;
-
-#ifdef DOT11_N_SUPPORT
-			// If both station and AP use 40MHz, still need to check if the 40MHZ band's legality in my country region
-			// If this 40MHz wideband is not allowed in my country list, use bandwidth 20MHZ instead,
-			if ((pInBss->CentralChannel != pInBss->Channel) &&
-				(pAd->CommonCfg.RegTransmitSetting.field.BW == BW_40))
-			{
-				if (RTMPCheckChannel(pAd, pInBss->CentralChannel, pInBss->Channel) == FALSE)
-				{
-					pAd->CommonCfg.RegTransmitSetting.field.BW = BW_20;
-					SetCommonHT(pAd);
-					pAd->CommonCfg.RegTransmitSetting.field.BW = BW_40;
-				}
-			}
-#endif // DOT11_N_SUPPORT //
-
-			// copy matching BSS from InTab to OutTab
-			NdisMoveMemory(pOutBss, pInBss, sizeof(BSS_ENTRY));
-
-			OutTab->BssNr++;
-		}
-
-		if (OutTab->BssNr >= MAX_LEN_OF_BSS_TABLE)
-			break;
-	}
-
-	BssTableSortByRssi(OutTab);
-}
-
-
-// IRQL = DISPATCH_LEVEL
-VOID BssTableSortByRssi(
-	IN OUT BSS_TABLE *OutTab)
-{
-	INT 	  i, j;
-	BSS_ENTRY TmpBss;
-
-	for (i = 0; i < OutTab->BssNr - 1; i++)
-	{
-		for (j = i+1; j < OutTab->BssNr; j++)
-		{
-			if (OutTab->BssEntry[j].Rssi > OutTab->BssEntry[i].Rssi)
-			{
-				NdisMoveMemory(&TmpBss, &OutTab->BssEntry[j], sizeof(BSS_ENTRY));
-				NdisMoveMemory(&OutTab->BssEntry[j], &OutTab->BssEntry[i], sizeof(BSS_ENTRY));
-				NdisMoveMemory(&OutTab->BssEntry[i], &TmpBss, sizeof(BSS_ENTRY));
-			}
-		}
-	}
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-VOID BssCipherParse(
-	IN OUT	PBSS_ENTRY	pBss)
-{
-	PEID_STRUCT 		 pEid;
-	PUCHAR				pTmp;
-	PRSN_IE_HEADER_STRUCT			pRsnHeader;
-	PCIPHER_SUITE_STRUCT			pCipher;
-	PAKM_SUITE_STRUCT				pAKM;
-	USHORT							Count;
-	INT								Length;
-	NDIS_802_11_ENCRYPTION_STATUS	TmpCipher;
-
-	//
-	// WepStatus will be reset later, if AP announce TKIP or AES on the beacon frame.
-	//
-	if (pBss->Privacy)
-	{
-		pBss->WepStatus 	= Ndis802_11WEPEnabled;
-	}
-	else
-	{
-		pBss->WepStatus 	= Ndis802_11WEPDisabled;
-	}
-	// Set default to disable & open authentication before parsing variable IE
-	pBss->AuthMode		= Ndis802_11AuthModeOpen;
-	pBss->AuthModeAux	= Ndis802_11AuthModeOpen;
-
-	// Init WPA setting
-	pBss->WPA.PairCipher	= Ndis802_11WEPDisabled;
-	pBss->WPA.PairCipherAux = Ndis802_11WEPDisabled;
-	pBss->WPA.GroupCipher	= Ndis802_11WEPDisabled;
-	pBss->WPA.RsnCapability = 0;
-	pBss->WPA.bMixMode		= FALSE;
-
-	// Init WPA2 setting
-	pBss->WPA2.PairCipher	 = Ndis802_11WEPDisabled;
-	pBss->WPA2.PairCipherAux = Ndis802_11WEPDisabled;
-	pBss->WPA2.GroupCipher	 = Ndis802_11WEPDisabled;
-	pBss->WPA2.RsnCapability = 0;
-	pBss->WPA2.bMixMode 	 = FALSE;
-
-
-	Length = (INT) pBss->VarIELen;
-
-	while (Length > 0)
-	{
-		// Parse cipher suite base on WPA1 & WPA2, they should be parsed differently
-		pTmp = ((PUCHAR) pBss->VarIEs) + pBss->VarIELen - Length;
-		pEid = (PEID_STRUCT) pTmp;
-		switch (pEid->Eid)
-		{
-			case IE_WPA:
-				//Parse Cisco IE_WPA (LEAP, CCKM, etc.)
-				if ( NdisEqualMemory((pTmp+8), CISCO_OUI, 3))
-				{
-					pTmp   += 11;
-					switch (*pTmp)
-					{
-						case 1:
-						case 5:	// Although WEP is not allowed in WPA related auth mode, we parse it anyway
-							pBss->WepStatus = Ndis802_11Encryption1Enabled;
-							pBss->WPA.PairCipher = Ndis802_11Encryption1Enabled;
-							pBss->WPA.GroupCipher = Ndis802_11Encryption1Enabled;
-							break;
-						case 2:
-							pBss->WepStatus = Ndis802_11Encryption2Enabled;
-							pBss->WPA.PairCipher = Ndis802_11Encryption1Enabled;
-							pBss->WPA.GroupCipher = Ndis802_11Encryption1Enabled;
-							break;
-						case 4:
-							pBss->WepStatus = Ndis802_11Encryption3Enabled;
-							pBss->WPA.PairCipher = Ndis802_11Encryption1Enabled;
-							pBss->WPA.GroupCipher = Ndis802_11Encryption1Enabled;
-							break;
-						default:
-							break;
-					}
-
-					// if Cisco IE_WPA, break
-					break;
-				}
-				else if (NdisEqualMemory(pEid->Octet, SES_OUI, 3) && (pEid->Len == 7))
-				{
-					pBss->bSES = TRUE;
-					break;
-				}
-				else if (NdisEqualMemory(pEid->Octet, WPA_OUI, 4) != 1)
-				{
-					// if unsupported vendor specific IE
-					break;
-				}
-				// Skip OUI, version, and multicast suite
-				// This part should be improved in the future when AP supported multiple cipher suite.
-				// For now, it's OK since almost all APs have fixed cipher suite supported.
-				// pTmp = (PUCHAR) pEid->Octet;
-				pTmp   += 11;
-
-				// Cipher Suite Selectors from Spec P802.11i/D3.2 P26.
-				//	Value	   Meaning
-				//	0			None
-				//	1			WEP-40
-				//	2			Tkip
-				//	3			WRAP
-				//	4			AES
-				//	5			WEP-104
-				// Parse group cipher
-				switch (*pTmp)
-				{
-					case 1:
-					case 5:	// Although WEP is not allowed in WPA related auth mode, we parse it anyway
-						pBss->WPA.GroupCipher = Ndis802_11Encryption1Enabled;
-						break;
-					case 2:
-						pBss->WPA.GroupCipher = Ndis802_11Encryption2Enabled;
-						break;
-					case 4:
-						pBss->WPA.GroupCipher = Ndis802_11Encryption3Enabled;
-						break;
-					default:
-						break;
-				}
-				// number of unicast suite
-				pTmp   += 1;
-
-				// skip all unicast cipher suites
-				//Count = *(PUSHORT) pTmp;
-				Count = (pTmp[1]<<8) + pTmp[0];
-				pTmp   += sizeof(USHORT);
-
-				// Parsing all unicast cipher suite
-				while (Count > 0)
-				{
-					// Skip OUI
-					pTmp += 3;
-					TmpCipher = Ndis802_11WEPDisabled;
-					switch (*pTmp)
-					{
-						case 1:
-						case 5: // Although WEP is not allowed in WPA related auth mode, we parse it anyway
-							TmpCipher = Ndis802_11Encryption1Enabled;
-							break;
-						case 2:
-							TmpCipher = Ndis802_11Encryption2Enabled;
-							break;
-						case 4:
-							TmpCipher = Ndis802_11Encryption3Enabled;
-							break;
-						default:
-							break;
-					}
-					if (TmpCipher > pBss->WPA.PairCipher)
-					{
-						// Move the lower cipher suite to PairCipherAux
-						pBss->WPA.PairCipherAux = pBss->WPA.PairCipher;
-						pBss->WPA.PairCipher	= TmpCipher;
-					}
-					else
-					{
-						pBss->WPA.PairCipherAux = TmpCipher;
-					}
-					pTmp++;
-					Count--;
-				}
-
-				// 4. get AKM suite counts
-				//Count	= *(PUSHORT) pTmp;
-				Count = (pTmp[1]<<8) + pTmp[0];
-				pTmp   += sizeof(USHORT);
-				pTmp   += 3;
-
-				switch (*pTmp)
-				{
-					case 1:
-						// Set AP support WPA mode
-						if (pBss->AuthMode == Ndis802_11AuthModeOpen)
-							pBss->AuthMode = Ndis802_11AuthModeWPA;
-						else
-							pBss->AuthModeAux = Ndis802_11AuthModeWPA;
-						break;
-					case 2:
-						// Set AP support WPA mode
-						if (pBss->AuthMode == Ndis802_11AuthModeOpen)
-							pBss->AuthMode = Ndis802_11AuthModeWPAPSK;
-						else
-							pBss->AuthModeAux = Ndis802_11AuthModeWPAPSK;
-						break;
-					default:
-						break;
-				}
-				pTmp   += 1;
-
-				// Fixed for WPA-None
-				if (pBss->BssType == BSS_ADHOC)
-				{
-					pBss->AuthMode	  = Ndis802_11AuthModeWPANone;
-					pBss->AuthModeAux = Ndis802_11AuthModeWPANone;
-					pBss->WepStatus   = pBss->WPA.GroupCipher;
-					if (pBss->WPA.PairCipherAux == Ndis802_11WEPDisabled)
-						pBss->WPA.PairCipherAux = pBss->WPA.GroupCipher;
-				}
-				else
-					pBss->WepStatus   = pBss->WPA.PairCipher;
-
-				// Check the Pair & Group, if different, turn on mixed mode flag
-				if (pBss->WPA.GroupCipher != pBss->WPA.PairCipher)
-					pBss->WPA.bMixMode = TRUE;
-
-				break;
-
-			case IE_RSN:
-				pRsnHeader = (PRSN_IE_HEADER_STRUCT) pTmp;
-
-				// 0. Version must be 1
-				if (le2cpu16(pRsnHeader->Version) != 1)
-					break;
-				pTmp   += sizeof(RSN_IE_HEADER_STRUCT);
-
-				// 1. Check group cipher
-				pCipher = (PCIPHER_SUITE_STRUCT) pTmp;
-				if (!RTMPEqualMemory(pTmp, RSN_OUI, 3))
-					break;
-
-				// Parse group cipher
-				switch (pCipher->Type)
-				{
-					case 1:
-					case 5:	// Although WEP is not allowed in WPA related auth mode, we parse it anyway
-						pBss->WPA2.GroupCipher = Ndis802_11Encryption1Enabled;
-						break;
-					case 2:
-						pBss->WPA2.GroupCipher = Ndis802_11Encryption2Enabled;
-						break;
-					case 4:
-						pBss->WPA2.GroupCipher = Ndis802_11Encryption3Enabled;
-						break;
-					default:
-						break;
-				}
-				// set to correct offset for next parsing
-				pTmp   += sizeof(CIPHER_SUITE_STRUCT);
-
-				// 2. Get pairwise cipher counts
-				//Count = *(PUSHORT) pTmp;
-				Count = (pTmp[1]<<8) + pTmp[0];
-				pTmp   += sizeof(USHORT);
-
-				// 3. Get pairwise cipher
-				// Parsing all unicast cipher suite
-				while (Count > 0)
-				{
-					// Skip OUI
-					pCipher = (PCIPHER_SUITE_STRUCT) pTmp;
-					TmpCipher = Ndis802_11WEPDisabled;
-					switch (pCipher->Type)
-					{
-						case 1:
-						case 5: // Although WEP is not allowed in WPA related auth mode, we parse it anyway
-							TmpCipher = Ndis802_11Encryption1Enabled;
-							break;
-						case 2:
-							TmpCipher = Ndis802_11Encryption2Enabled;
-							break;
-						case 4:
-							TmpCipher = Ndis802_11Encryption3Enabled;
-							break;
-						default:
-							break;
-					}
-					if (TmpCipher > pBss->WPA2.PairCipher)
-					{
-						// Move the lower cipher suite to PairCipherAux
-						pBss->WPA2.PairCipherAux = pBss->WPA2.PairCipher;
-						pBss->WPA2.PairCipher	 = TmpCipher;
-					}
-					else
-					{
-						pBss->WPA2.PairCipherAux = TmpCipher;
-					}
-					pTmp += sizeof(CIPHER_SUITE_STRUCT);
-					Count--;
-				}
-
-				// 4. get AKM suite counts
-				//Count	= *(PUSHORT) pTmp;
-				Count = (pTmp[1]<<8) + pTmp[0];
-				pTmp   += sizeof(USHORT);
-
-				// 5. Get AKM ciphers
-				pAKM = (PAKM_SUITE_STRUCT) pTmp;
-				if (!RTMPEqualMemory(pTmp, RSN_OUI, 3))
-					break;
-
-				switch (pAKM->Type)
-				{
-					case 1:
-						// Set AP support WPA mode
-						if (pBss->AuthMode == Ndis802_11AuthModeOpen)
-							pBss->AuthMode = Ndis802_11AuthModeWPA2;
-						else
-							pBss->AuthModeAux = Ndis802_11AuthModeWPA2;
-						break;
-					case 2:
-						// Set AP support WPA mode
-						if (pBss->AuthMode == Ndis802_11AuthModeOpen)
-							pBss->AuthMode = Ndis802_11AuthModeWPA2PSK;
-						else
-							pBss->AuthModeAux = Ndis802_11AuthModeWPA2PSK;
-						break;
-					default:
-						break;
-				}
-				pTmp   += (Count * sizeof(AKM_SUITE_STRUCT));
-
-				// Fixed for WPA-None
-				if (pBss->BssType == BSS_ADHOC)
-				{
-					pBss->AuthMode = Ndis802_11AuthModeWPANone;
-					pBss->AuthModeAux = Ndis802_11AuthModeWPANone;
-					pBss->WPA.PairCipherAux = pBss->WPA2.PairCipherAux;
-					pBss->WPA.GroupCipher	= pBss->WPA2.GroupCipher;
-					pBss->WepStatus 		= pBss->WPA.GroupCipher;
-					if (pBss->WPA.PairCipherAux == Ndis802_11WEPDisabled)
-						pBss->WPA.PairCipherAux = pBss->WPA.GroupCipher;
-				}
-				pBss->WepStatus   = pBss->WPA2.PairCipher;
-
-				// 6. Get RSN capability
-				//pBss->WPA2.RsnCapability = *(PUSHORT) pTmp;
-				pBss->WPA2.RsnCapability = (pTmp[1]<<8) + pTmp[0];
-				pTmp += sizeof(USHORT);
-
-				// Check the Pair & Group, if different, turn on mixed mode flag
-				if (pBss->WPA2.GroupCipher != pBss->WPA2.PairCipher)
-					pBss->WPA2.bMixMode = TRUE;
-
-				break;
-			default:
-				break;
-		}
-		Length -= (pEid->Len + 2);
-	}
-}
-
-// ===========================================================================================
-// mac_table.c
-// ===========================================================================================
-
-/*! \brief generates a random mac address value for IBSS BSSID
- *	\param Addr the bssid location
- *	\return none
- *	\pre
- *	\post
- */
-VOID MacAddrRandomBssid(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pAddr)
-{
-	INT i;
-
-	for (i = 0; i < MAC_ADDR_LEN; i++)
-	{
-		pAddr[i] = RandomByte(pAd);
-	}
-
-	pAddr[0] = (pAddr[0] & 0xfe) | 0x02;  // the first 2 bits must be 01xxxxxxxx
-}
-
-/*! \brief init the management mac frame header
- *	\param p_hdr mac header
- *	\param subtype subtype of the frame
- *	\param p_ds destination address, don't care if it is a broadcast address
- *	\return none
- *	\pre the station has the following information in the pAd->StaCfg
- *	 - bssid
- *	 - station address
- *	\post
- *	\note this function initializes the following field
-
- IRQL = PASSIVE_LEVEL
- IRQL = DISPATCH_LEVEL
-
- */
-VOID MgtMacHeaderInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN OUT PHEADER_802_11 pHdr80211,
-	IN UCHAR SubType,
-	IN UCHAR ToDs,
-	IN PUCHAR pDA,
-	IN PUCHAR pBssid)
-{
-	NdisZeroMemory(pHdr80211, sizeof(HEADER_802_11));
-
-	pHdr80211->FC.Type = BTYPE_MGMT;
-	pHdr80211->FC.SubType = SubType;
-//	if (SubType == SUBTYPE_ACK)	// sample, no use, it will conflict with ACTION frame sub type
-//		pHdr80211->FC.Type = BTYPE_CNTL;
-	pHdr80211->FC.ToDs = ToDs;
-	COPY_MAC_ADDR(pHdr80211->Addr1, pDA);
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		COPY_MAC_ADDR(pHdr80211->Addr2, pAd->CurrentAddress);
-#endif // CONFIG_STA_SUPPORT //
-	COPY_MAC_ADDR(pHdr80211->Addr3, pBssid);
-}
-
-// ===========================================================================================
-// mem_mgmt.c
-// ===========================================================================================
-
-/*!***************************************************************************
- * This routine build an outgoing frame, and fill all information specified
- * in argument list to the frame body. The actual frame size is the summation
- * of all arguments.
- * input params:
- *		Buffer - pointer to a pre-allocated memory segment
- *		args - a list of <int arg_size, arg> pairs.
- *		NOTE NOTE NOTE!!!! the last argument must be NULL, otherwise this
- *						   function will FAIL!!!
- * return:
- *		Size of the buffer
- * usage:
- *		MakeOutgoingFrame(Buffer, output_length, 2, &fc, 2, &dur, 6, p_addr1, 6,p_addr2, END_OF_ARGS);
-
- IRQL = PASSIVE_LEVEL
- IRQL = DISPATCH_LEVEL
-
- ****************************************************************************/
-ULONG MakeOutgoingFrame(
-	OUT CHAR *Buffer,
-	OUT ULONG *FrameLen, ...)
-{
-	CHAR   *p;
-	int 	leng;
-	ULONG	TotLeng;
-	va_list Args;
-
-	// calculates the total length
-	TotLeng = 0;
-	va_start(Args, FrameLen);
-	do
-	{
-		leng = va_arg(Args, int);
-		if (leng == END_OF_ARGS)
-		{
-			break;
-		}
-		p = va_arg(Args, PVOID);
-		NdisMoveMemory(&Buffer[TotLeng], p, leng);
-		TotLeng = TotLeng + leng;
-	} while(TRUE);
-
-	va_end(Args); /* clean up */
-	*FrameLen = TotLeng;
-	return TotLeng;
-}
-
-// ===========================================================================================
-// mlme_queue.c
-// ===========================================================================================
-
-/*! \brief	Initialize The MLME Queue, used by MLME Functions
- *	\param	*Queue	   The MLME Queue
- *	\return Always	   Return NDIS_STATE_SUCCESS in this implementation
- *	\pre
- *	\post
- *	\note	Because this is done only once (at the init stage), no need to be locked
-
- IRQL = PASSIVE_LEVEL
-
- */
-NDIS_STATUS MlmeQueueInit(
-	IN MLME_QUEUE *Queue)
-{
-	INT i;
-
-	NdisAllocateSpinLock(&Queue->Lock);
-
-	Queue->Num	= 0;
-	Queue->Head = 0;
-	Queue->Tail = 0;
-
-	for (i = 0; i < MAX_LEN_OF_MLME_QUEUE; i++)
-	{
-		Queue->Entry[i].Occupied = FALSE;
-		Queue->Entry[i].MsgLen = 0;
-		NdisZeroMemory(Queue->Entry[i].Msg, MGMT_DMA_BUFFER_SIZE);
-	}
-
-	return NDIS_STATUS_SUCCESS;
-}
-
-/*! \brief	 Enqueue a message for other threads, if they want to send messages to MLME thread
- *	\param	*Queue	  The MLME Queue
- *	\param	 Machine  The State Machine Id
- *	\param	 MsgType  The Message Type
- *	\param	 MsgLen   The Message length
- *	\param	*Msg	  The message pointer
- *	\return  TRUE if enqueue is successful, FALSE if the queue is full
- *	\pre
- *	\post
- *	\note	 The message has to be initialized
-
- IRQL = PASSIVE_LEVEL
- IRQL = DISPATCH_LEVEL
-
- */
-BOOLEAN MlmeEnqueue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN ULONG Machine,
-	IN ULONG MsgType,
-	IN ULONG MsgLen,
-	IN VOID *Msg)
-{
-	INT Tail;
-	MLME_QUEUE	*Queue = (MLME_QUEUE *)&pAd->Mlme.Queue;
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return FALSE;
-
-	// First check the size, it MUST not exceed the mlme queue size
-	if (MsgLen > MGMT_DMA_BUFFER_SIZE)
-	{
-		DBGPRINT_ERR(("MlmeEnqueue: msg too large, size = %ld \n", MsgLen));
-		return FALSE;
-	}
-
-	if (MlmeQueueFull(Queue))
-	{
-		return FALSE;
-	}
-
-	NdisAcquireSpinLock(&(Queue->Lock));
-	Tail = Queue->Tail;
-	Queue->Tail++;
-	Queue->Num++;
-	if (Queue->Tail == MAX_LEN_OF_MLME_QUEUE)
-	{
-		Queue->Tail = 0;
-	}
-
-	Queue->Entry[Tail].Wcid = RESERVED_WCID;
-	Queue->Entry[Tail].Occupied = TRUE;
-	Queue->Entry[Tail].Machine = Machine;
-	Queue->Entry[Tail].MsgType = MsgType;
-	Queue->Entry[Tail].MsgLen  = MsgLen;
-
-	if (Msg != NULL)
-	{
-		NdisMoveMemory(Queue->Entry[Tail].Msg, Msg, MsgLen);
-	}
-
-	NdisReleaseSpinLock(&(Queue->Lock));
-	return TRUE;
-}
-
-/*! \brief	 This function is used when Recv gets a MLME message
- *	\param	*Queue			 The MLME Queue
- *	\param	 TimeStampHigh	 The upper 32 bit of timestamp
- *	\param	 TimeStampLow	 The lower 32 bit of timestamp
- *	\param	 Rssi			 The receiving RSSI strength
- *	\param	 MsgLen 		 The length of the message
- *	\param	*Msg			 The message pointer
- *	\return  TRUE if everything ok, FALSE otherwise (like Queue Full)
- *	\pre
- *	\post
-
- IRQL = DISPATCH_LEVEL
-
- */
-BOOLEAN MlmeEnqueueForRecv(
-	IN	PRTMP_ADAPTER	pAd,
-	IN ULONG Wcid,
-	IN ULONG TimeStampHigh,
-	IN ULONG TimeStampLow,
-	IN UCHAR Rssi0,
-	IN UCHAR Rssi1,
-	IN UCHAR Rssi2,
-	IN ULONG MsgLen,
-	IN VOID *Msg,
-	IN UCHAR Signal)
-{
-	INT 		 Tail, Machine;
-	PFRAME_802_11 pFrame = (PFRAME_802_11)Msg;
-	INT		 MsgType;
-	MLME_QUEUE	*Queue = (MLME_QUEUE *)&pAd->Mlme.Queue;
-
-#ifdef RALINK_ATE
-	/* Nothing to do in ATE mode */
-	if(ATE_ON(pAd))
-		return FALSE;
-#endif // RALINK_ATE //
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-	{
-		DBGPRINT_ERR(("MlmeEnqueueForRecv: fRTMP_ADAPTER_HALT_IN_PROGRESS\n"));
-		return FALSE;
-	}
-
-	// First check the size, it MUST not exceed the mlme queue size
-	if (MsgLen > MGMT_DMA_BUFFER_SIZE)
-	{
-		DBGPRINT_ERR(("MlmeEnqueueForRecv: frame too large, size = %ld \n", MsgLen));
-		return FALSE;
-	}
-
-	if (MlmeQueueFull(Queue))
-	{
-		return FALSE;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (!MsgTypeSubst(pAd, pFrame, &Machine, &MsgType))
-		{
-			DBGPRINT_ERR(("MlmeEnqueueForRecv: un-recongnized mgmt->subtype=%d\n",pFrame->Hdr.FC.SubType));
-			return FALSE;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// OK, we got all the informations, it is time to put things into queue
-	NdisAcquireSpinLock(&(Queue->Lock));
-	Tail = Queue->Tail;
-	Queue->Tail++;
-	Queue->Num++;
-	if (Queue->Tail == MAX_LEN_OF_MLME_QUEUE)
-	{
-		Queue->Tail = 0;
-	}
-	Queue->Entry[Tail].Occupied = TRUE;
-	Queue->Entry[Tail].Machine = Machine;
-	Queue->Entry[Tail].MsgType = MsgType;
-	Queue->Entry[Tail].MsgLen  = MsgLen;
-	Queue->Entry[Tail].TimeStamp.u.LowPart = TimeStampLow;
-	Queue->Entry[Tail].TimeStamp.u.HighPart = TimeStampHigh;
-	Queue->Entry[Tail].Rssi0 = Rssi0;
-	Queue->Entry[Tail].Rssi1 = Rssi1;
-	Queue->Entry[Tail].Rssi2 = Rssi2;
-	Queue->Entry[Tail].Signal = Signal;
-	Queue->Entry[Tail].Wcid = (UCHAR)Wcid;
-
-	Queue->Entry[Tail].Channel = pAd->LatchRfRegs.Channel;
-
-	if (Msg != NULL)
-	{
-		NdisMoveMemory(Queue->Entry[Tail].Msg, Msg, MsgLen);
-	}
-
-	NdisReleaseSpinLock(&(Queue->Lock));
-
-	RT28XX_MLME_HANDLER(pAd);
-
-	return TRUE;
-}
-
-
-/*! \brief	 Dequeue a message from the MLME Queue
- *	\param	*Queue	  The MLME Queue
- *	\param	*Elem	  The message dequeued from MLME Queue
- *	\return  TRUE if the Elem contains something, FALSE otherwise
- *	\pre
- *	\post
-
- IRQL = DISPATCH_LEVEL
-
- */
-BOOLEAN MlmeDequeue(
-	IN MLME_QUEUE *Queue,
-	OUT MLME_QUEUE_ELEM **Elem)
-{
-	NdisAcquireSpinLock(&(Queue->Lock));
-	*Elem = &(Queue->Entry[Queue->Head]);
-	Queue->Num--;
-	Queue->Head++;
-	if (Queue->Head == MAX_LEN_OF_MLME_QUEUE)
-	{
-		Queue->Head = 0;
-	}
-	NdisReleaseSpinLock(&(Queue->Lock));
-	return TRUE;
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID	MlmeRestartStateMachine(
-	IN	PRTMP_ADAPTER	pAd)
-{
-#ifdef CONFIG_STA_SUPPORT
-	BOOLEAN				Cancelled;
-#endif // CONFIG_STA_SUPPORT //
-
-	DBGPRINT(RT_DEBUG_TRACE, ("MlmeRestartStateMachine \n"));
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-#ifdef QOS_DLS_SUPPORT
-		UCHAR i;
-#endif // QOS_DLS_SUPPORT //
-		// Cancel all timer events
-		// Be careful to cancel new added timer
-		RTMPCancelTimer(&pAd->MlmeAux.AssocTimer,	  &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer,   &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer,  &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.AuthTimer,	   &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer,	   &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer,	   &Cancelled);
-
-#ifdef QOS_DLS_SUPPORT
-		for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &Cancelled);
-		}
-#endif // QOS_DLS_SUPPORT //
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Change back to original channel in case of doing scan
-	AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-	AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-
-	// Resume MSDU which is turned off durning scan
-	RTMPResumeMsduTransmission(pAd);
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Set all state machines back IDLE
-		pAd->Mlme.CntlMachine.CurrState    = CNTL_IDLE;
-		pAd->Mlme.AssocMachine.CurrState   = ASSOC_IDLE;
-		pAd->Mlme.AuthMachine.CurrState    = AUTH_REQ_IDLE;
-		pAd->Mlme.AuthRspMachine.CurrState = AUTH_RSP_IDLE;
-		pAd->Mlme.SyncMachine.CurrState    = SYNC_IDLE;
-		pAd->Mlme.ActMachine.CurrState    = ACT_IDLE;
-#ifdef QOS_DLS_SUPPORT
-		pAd->Mlme.DlsMachine.CurrState    = DLS_IDLE;
-#endif // QOS_DLS_SUPPORT //
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-}
-
-/*! \brief	test if the MLME Queue is empty
- *	\param	*Queue	  The MLME Queue
- *	\return TRUE if the Queue is empty, FALSE otherwise
- *	\pre
- *	\post
-
- IRQL = DISPATCH_LEVEL
-
- */
-BOOLEAN MlmeQueueEmpty(
-	IN MLME_QUEUE *Queue)
-{
-	BOOLEAN Ans;
-
-	NdisAcquireSpinLock(&(Queue->Lock));
-	Ans = (Queue->Num == 0);
-	NdisReleaseSpinLock(&(Queue->Lock));
-
-	return Ans;
-}
-
-/*! \brief	 test if the MLME Queue is full
- *	\param	 *Queue 	 The MLME Queue
- *	\return  TRUE if the Queue is empty, FALSE otherwise
- *	\pre
- *	\post
-
- IRQL = PASSIVE_LEVEL
- IRQL = DISPATCH_LEVEL
-
- */
-BOOLEAN MlmeQueueFull(
-	IN MLME_QUEUE *Queue)
-{
-	BOOLEAN Ans;
-
-	NdisAcquireSpinLock(&(Queue->Lock));
-	Ans = (Queue->Num == MAX_LEN_OF_MLME_QUEUE || Queue->Entry[Queue->Tail].Occupied);
-	NdisReleaseSpinLock(&(Queue->Lock));
-
-	return Ans;
-}
-
-/*! \brief	 The destructor of MLME Queue
- *	\param
- *	\return
- *	\pre
- *	\post
- *	\note	Clear Mlme Queue, Set Queue->Num to Zero.
-
- IRQL = PASSIVE_LEVEL
-
- */
-VOID MlmeQueueDestroy(
-	IN MLME_QUEUE *pQueue)
-{
-	NdisAcquireSpinLock(&(pQueue->Lock));
-	pQueue->Num  = 0;
-	pQueue->Head = 0;
-	pQueue->Tail = 0;
-	NdisReleaseSpinLock(&(pQueue->Lock));
-	NdisFreeSpinLock(&(pQueue->Lock));
-}
-
-/*! \brief	 To substitute the message type if the message is coming from external
- *	\param	pFrame		   The frame received
- *	\param	*Machine	   The state machine
- *	\param	*MsgType	   the message type for the state machine
- *	\return TRUE if the substitution is successful, FALSE otherwise
- *	\pre
- *	\post
-
- IRQL = DISPATCH_LEVEL
-
- */
-#ifdef CONFIG_STA_SUPPORT
-BOOLEAN MsgTypeSubst(
-	IN PRTMP_ADAPTER  pAd,
-	IN PFRAME_802_11 pFrame,
-	OUT INT *Machine,
-	OUT INT *MsgType)
-{
-	USHORT	Seq;
-	UCHAR	EAPType;
-	PUCHAR	pData;
-
-	// Pointer to start of data frames including SNAP header
-	pData = (PUCHAR) pFrame + LENGTH_802_11;
-
-	// The only data type will pass to this function is EAPOL frame
-	if (pFrame->Hdr.FC.Type == BTYPE_DATA)
-	{
-		if (NdisEqualMemory(SNAP_AIRONET, pData, LENGTH_802_1_H))
-		{
-			// Cisco Aironet SNAP header
-			*Machine = AIRONET_STATE_MACHINE;
-			*MsgType = MT2_AIRONET_MSG;
-			return (TRUE);
-		}
-#ifdef LEAP_SUPPORT
-		if ( pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP ) //LEAP
-		{
-			// LEAP frames
-			*Machine = LEAP_STATE_MACHINE;
-			EAPType = *((UCHAR*)pFrame + LENGTH_802_11 + LENGTH_802_1_H + 1);
-			return (LeapMsgTypeSubst(EAPType, MsgType));
-		}
-		else
-#endif // LEAP_SUPPORT //
-		{
-			*Machine = WPA_PSK_STATE_MACHINE;
-			EAPType = *((UCHAR*)pFrame + LENGTH_802_11 + LENGTH_802_1_H + 1);
-			return(WpaMsgTypeSubst(EAPType, MsgType));
-		}
-	}
-
-	switch (pFrame->Hdr.FC.SubType)
-	{
-		case SUBTYPE_ASSOC_REQ:
-			*Machine = ASSOC_STATE_MACHINE;
-			*MsgType = MT2_PEER_ASSOC_REQ;
-			break;
-		case SUBTYPE_ASSOC_RSP:
-			*Machine = ASSOC_STATE_MACHINE;
-			*MsgType = MT2_PEER_ASSOC_RSP;
-			break;
-		case SUBTYPE_REASSOC_REQ:
-			*Machine = ASSOC_STATE_MACHINE;
-			*MsgType = MT2_PEER_REASSOC_REQ;
-			break;
-		case SUBTYPE_REASSOC_RSP:
-			*Machine = ASSOC_STATE_MACHINE;
-			*MsgType = MT2_PEER_REASSOC_RSP;
-			break;
-		case SUBTYPE_PROBE_REQ:
-			*Machine = SYNC_STATE_MACHINE;
-			*MsgType = MT2_PEER_PROBE_REQ;
-			break;
-		case SUBTYPE_PROBE_RSP:
-			*Machine = SYNC_STATE_MACHINE;
-			*MsgType = MT2_PEER_PROBE_RSP;
-			break;
-		case SUBTYPE_BEACON:
-			*Machine = SYNC_STATE_MACHINE;
-			*MsgType = MT2_PEER_BEACON;
-			break;
-		case SUBTYPE_ATIM:
-			*Machine = SYNC_STATE_MACHINE;
-			*MsgType = MT2_PEER_ATIM;
-			break;
-		case SUBTYPE_DISASSOC:
-			*Machine = ASSOC_STATE_MACHINE;
-			*MsgType = MT2_PEER_DISASSOC_REQ;
-			break;
-		case SUBTYPE_AUTH:
-			// get the sequence number from payload 24 Mac Header + 2 bytes algorithm
-			NdisMoveMemory(&Seq, &pFrame->Octet[2], sizeof(USHORT));
-			if (Seq == 1 || Seq == 3)
-			{
-				*Machine = AUTH_RSP_STATE_MACHINE;
-				*MsgType = MT2_PEER_AUTH_ODD;
-			}
-			else if (Seq == 2 || Seq == 4)
-			{
-				*Machine = AUTH_STATE_MACHINE;
-				*MsgType = MT2_PEER_AUTH_EVEN;
-			}
-			else
-			{
-				return FALSE;
-			}
-			break;
-		case SUBTYPE_DEAUTH:
-			*Machine = AUTH_RSP_STATE_MACHINE;
-			*MsgType = MT2_PEER_DEAUTH;
-			break;
-		case SUBTYPE_ACTION:
-			*Machine = ACTION_STATE_MACHINE;
-			//  Sometimes Sta will return with category bytes with MSB = 1, if they receive catogory out of their support
-			if ((pFrame->Octet[0]&0x7F) > MAX_PEER_CATE_MSG)
-			{
-				*MsgType = MT2_ACT_INVALID;
-			}
-			else
-			{
-				*MsgType = (pFrame->Octet[0]&0x7F);
-			}
-			break;
-		default:
-			return FALSE;
-			break;
-	}
-
-	return TRUE;
-}
-#endif // CONFIG_STA_SUPPORT //
-
-// ===========================================================================================
-// state_machine.c
-// ===========================================================================================
-
-/*! \brief Initialize the state machine.
- *	\param *S			pointer to the state machine
- *	\param	Trans		State machine transition function
- *	\param	StNr		number of states
- *	\param	MsgNr		number of messages
- *	\param	DefFunc 	default function, when there is invalid state/message combination
- *	\param	InitState	initial state of the state machine
- *	\param	Base		StateMachine base, internal use only
- *	\pre p_sm should be a legal pointer
- *	\post
-
- IRQL = PASSIVE_LEVEL
-
- */
-VOID StateMachineInit(
-	IN STATE_MACHINE *S,
-	IN STATE_MACHINE_FUNC Trans[],
-	IN ULONG StNr,
-	IN ULONG MsgNr,
-	IN STATE_MACHINE_FUNC DefFunc,
-	IN ULONG InitState,
-	IN ULONG Base)
-{
-	ULONG i, j;
-
-	// set number of states and messages
-	S->NrState = StNr;
-	S->NrMsg   = MsgNr;
-	S->Base    = Base;
-
-	S->TransFunc  = Trans;
-
-	// init all state transition to default function
-	for (i = 0; i < StNr; i++)
-	{
-		for (j = 0; j < MsgNr; j++)
-		{
-			S->TransFunc[i * MsgNr + j] = DefFunc;
-		}
-	}
-
-	// set the starting state
-	S->CurrState = InitState;
-}
-
-/*! \brief This function fills in the function pointer into the cell in the state machine
- *	\param *S	pointer to the state machine
- *	\param St	state
- *	\param Msg	incoming message
- *	\param f	the function to be executed when (state, message) combination occurs at the state machine
- *	\pre *S should be a legal pointer to the state machine, st, msg, should be all within the range, Base should be set in the initial state
- *	\post
-
- IRQL = PASSIVE_LEVEL
-
- */
-VOID StateMachineSetAction(
-	IN STATE_MACHINE *S,
-	IN ULONG St,
-	IN ULONG Msg,
-	IN STATE_MACHINE_FUNC Func)
-{
-	ULONG MsgIdx;
-
-	MsgIdx = Msg - S->Base;
-
-	if (St < S->NrState && MsgIdx < S->NrMsg)
-	{
-		// boundary checking before setting the action
-		S->TransFunc[St * S->NrMsg + MsgIdx] = Func;
-	}
-}
-
-/*! \brief	 This function does the state transition
- *	\param	 *Adapter the NIC adapter pointer
- *	\param	 *S 	  the state machine
- *	\param	 *Elem	  the message to be executed
- *	\return   None
-
- IRQL = DISPATCH_LEVEL
-
- */
-VOID StateMachinePerformAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN STATE_MACHINE *S,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	(*(S->TransFunc[S->CurrState * S->NrMsg + Elem->MsgType - S->Base]))(pAd, Elem);
-}
-
-/*
-	==========================================================================
-	Description:
-		The drop function, when machine executes this, the message is simply
-		ignored. This function does nothing, the message is freed in
-		StateMachinePerformAction()
-	==========================================================================
- */
-VOID Drop(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-}
-
-// ===========================================================================================
-// lfsr.c
-// ===========================================================================================
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
- */
-VOID LfsrInit(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG Seed)
-{
-	if (Seed == 0)
-		pAd->Mlme.ShiftReg = 1;
-	else
-		pAd->Mlme.ShiftReg = Seed;
-}
-
-/*
-	==========================================================================
-	Description:
-	==========================================================================
- */
-UCHAR RandomByte(
-	IN PRTMP_ADAPTER pAd)
-{
-	ULONG i;
-	UCHAR R, Result;
-
-	R = 0;
-
-	if (pAd->Mlme.ShiftReg == 0)
-	NdisGetSystemUpTime((ULONG *)&pAd->Mlme.ShiftReg);
-
-	for (i = 0; i < 8; i++)
-	{
-		if (pAd->Mlme.ShiftReg & 0x00000001)
-		{
-			pAd->Mlme.ShiftReg = ((pAd->Mlme.ShiftReg ^ LFSR_MASK) >> 1) | 0x80000000;
-			Result = 1;
-		}
-		else
-		{
-			pAd->Mlme.ShiftReg = pAd->Mlme.ShiftReg >> 1;
-			Result = 0;
-		}
-		R = (R << 1) | Result;
-	}
-
-	return R;
-}
-
-VOID AsicUpdateAutoFallBackTable(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pRateTable)
-{
-	UCHAR					i;
-	HT_FBK_CFG0_STRUC		HtCfg0;
-	HT_FBK_CFG1_STRUC		HtCfg1;
-	LG_FBK_CFG0_STRUC		LgCfg0;
-	LG_FBK_CFG1_STRUC		LgCfg1;
-	PRTMP_TX_RATE_SWITCH	pCurrTxRate, pNextTxRate;
-
-	// set to initial value
-	HtCfg0.word = 0x65432100;
-	HtCfg1.word = 0xedcba988;
-	LgCfg0.word = 0xedcba988;
-	LgCfg1.word = 0x00002100;
-
-	pNextTxRate = (PRTMP_TX_RATE_SWITCH)pRateTable+1;
-	for (i = 1; i < *((PUCHAR) pRateTable); i++)
-	{
-		pCurrTxRate = (PRTMP_TX_RATE_SWITCH)pRateTable+1+i;
-		switch (pCurrTxRate->Mode)
-		{
-			case 0:		//CCK
-				break;
-			case 1:		//OFDM
-				{
-					switch(pCurrTxRate->CurrMCS)
-					{
-						case 0:
-							LgCfg0.field.OFDMMCS0FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 1:
-							LgCfg0.field.OFDMMCS1FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 2:
-							LgCfg0.field.OFDMMCS2FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 3:
-							LgCfg0.field.OFDMMCS3FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 4:
-							LgCfg0.field.OFDMMCS4FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 5:
-							LgCfg0.field.OFDMMCS5FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 6:
-							LgCfg0.field.OFDMMCS6FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-						case 7:
-							LgCfg0.field.OFDMMCS7FBK = (pNextTxRate->Mode == MODE_OFDM) ? (pNextTxRate->CurrMCS+8): pNextTxRate->CurrMCS;
-							break;
-					}
-				}
-				break;
-#ifdef DOT11_N_SUPPORT
-			case 2:		//HT-MIX
-			case 3:		//HT-GF
-				{
-					if ((pNextTxRate->Mode >= MODE_HTMIX) && (pCurrTxRate->CurrMCS != pNextTxRate->CurrMCS))
-					{
-						switch(pCurrTxRate->CurrMCS)
-						{
-							case 0:
-								HtCfg0.field.HTMCS0FBK = pNextTxRate->CurrMCS;
-								break;
-							case 1:
-								HtCfg0.field.HTMCS1FBK = pNextTxRate->CurrMCS;
-								break;
-							case 2:
-								HtCfg0.field.HTMCS2FBK = pNextTxRate->CurrMCS;
-								break;
-							case 3:
-								HtCfg0.field.HTMCS3FBK = pNextTxRate->CurrMCS;
-								break;
-							case 4:
-								HtCfg0.field.HTMCS4FBK = pNextTxRate->CurrMCS;
-								break;
-							case 5:
-								HtCfg0.field.HTMCS5FBK = pNextTxRate->CurrMCS;
-								break;
-							case 6:
-								HtCfg0.field.HTMCS6FBK = pNextTxRate->CurrMCS;
-								break;
-							case 7:
-								HtCfg0.field.HTMCS7FBK = pNextTxRate->CurrMCS;
-								break;
-							case 8:
-								HtCfg1.field.HTMCS8FBK = pNextTxRate->CurrMCS;
-								break;
-							case 9:
-								HtCfg1.field.HTMCS9FBK = pNextTxRate->CurrMCS;
-								break;
-							case 10:
-								HtCfg1.field.HTMCS10FBK = pNextTxRate->CurrMCS;
-								break;
-							case 11:
-								HtCfg1.field.HTMCS11FBK = pNextTxRate->CurrMCS;
-								break;
-							case 12:
-								HtCfg1.field.HTMCS12FBK = pNextTxRate->CurrMCS;
-								break;
-							case 13:
-								HtCfg1.field.HTMCS13FBK = pNextTxRate->CurrMCS;
-								break;
-							case 14:
-								HtCfg1.field.HTMCS14FBK = pNextTxRate->CurrMCS;
-								break;
-							case 15:
-								HtCfg1.field.HTMCS15FBK = pNextTxRate->CurrMCS;
-								break;
-							default:
-								DBGPRINT(RT_DEBUG_ERROR, ("AsicUpdateAutoFallBackTable: not support CurrMCS=%d\n", pCurrTxRate->CurrMCS));
-						}
-					}
-				}
-				break;
-#endif // DOT11_N_SUPPORT //
-		}
-
-		pNextTxRate = pCurrTxRate;
-	}
-
-	RTMP_IO_WRITE32(pAd, HT_FBK_CFG0, HtCfg0.word);
-	RTMP_IO_WRITE32(pAd, HT_FBK_CFG1, HtCfg1.word);
-	RTMP_IO_WRITE32(pAd, LG_FBK_CFG0, LgCfg0.word);
-	RTMP_IO_WRITE32(pAd, LG_FBK_CFG1, LgCfg1.word);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Set MAC register value according operation mode.
-		OperationMode AND bNonGFExist are for MM and GF Proteciton.
-		If MM or GF mask is not set, those passing argument doesn't not take effect.
-
-		Operation mode meaning:
-		= 0 : Pure HT, no preotection.
-		= 0x01; there may be non-HT devices in both the control and extension channel, protection is optional in BSS.
-		= 0x10: No Transmission in 40M is protected.
-		= 0x11: Transmission in both 40M and 20M shall be protected
-		if (bNonGFExist)
-			we should choose not to use GF. But still set correct ASIC registers.
-	========================================================================
-*/
-VOID 	AsicUpdateProtect(
-	IN		PRTMP_ADAPTER	pAd,
-	IN 		USHORT			OperationMode,
-	IN 		UCHAR			SetMask,
-	IN		BOOLEAN			bDisableBGProtect,
-	IN		BOOLEAN			bNonGFExist)
-{
-	PROT_CFG_STRUC	ProtCfg, ProtCfg4;
-	UINT32 Protect[6];
-	USHORT			offset;
-	UCHAR			i;
-	UINT32 MacReg = 0;
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-#ifdef DOT11_N_SUPPORT
-	if (!(pAd->CommonCfg.bHTProtect) && (OperationMode != 8))
-	{
-		return;
-	}
-
-	if (pAd->BATable.numAsOriginator)
-	{
-		//
-		// enable the RTS/CTS to avoid channel collision
-		//
-		SetMask = ALLN_SETPROTECT;
-		OperationMode = 8;
-	}
-#endif // DOT11_N_SUPPORT //
-
-	// Config ASIC RTS threshold register
-	RTMP_IO_READ32(pAd, TX_RTS_CFG, &MacReg);
-	MacReg &= 0xFF0000FF;
-
-	// If the user want disable RtsThreshold and enable Amsdu/Ralink-Aggregation, set the RtsThreshold as 4096
-    if ((
-#ifdef DOT11_N_SUPPORT
-		(pAd->CommonCfg.BACapability.field.AmsduEnable) ||
-#endif // DOT11_N_SUPPORT //
-		(pAd->CommonCfg.bAggregationCapable == TRUE))
-        && pAd->CommonCfg.RtsThreshold == MAX_RTS_THRESHOLD)
-    {
-		MacReg |= (0x1000 << 8);
-    }
-    else
-    {
-		MacReg |= (pAd->CommonCfg.RtsThreshold << 8);
-    }
-
-	RTMP_IO_WRITE32(pAd, TX_RTS_CFG, MacReg);
-
-	// Initial common protection settings
-	RTMPZeroMemory(Protect, sizeof(Protect));
-	ProtCfg4.word = 0;
-	ProtCfg.word = 0;
-	ProtCfg.field.TxopAllowGF40 = 1;
-	ProtCfg.field.TxopAllowGF20 = 1;
-	ProtCfg.field.TxopAllowMM40 = 1;
-	ProtCfg.field.TxopAllowMM20 = 1;
-	ProtCfg.field.TxopAllowOfdm = 1;
-	ProtCfg.field.TxopAllowCck = 1;
-	ProtCfg.field.RTSThEn = 1;
-	ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
-
-	// update PHY mode and rate
-	if (pAd->CommonCfg.Channel > 14)
-		ProtCfg.field.ProtectRate = 0x4000;
-	ProtCfg.field.ProtectRate |= pAd->CommonCfg.RtsRate;
-
-	// Handle legacy(B/G) protection
-	if (bDisableBGProtect)
-	{
-		//ProtCfg.field.ProtectRate = pAd->CommonCfg.RtsRate;
-		ProtCfg.field.ProtectCtrl = 0;
-		Protect[0] = ProtCfg.word;
-		Protect[1] = ProtCfg.word;
-	}
-	else
-	{
-		//ProtCfg.field.ProtectRate = pAd->CommonCfg.RtsRate;
-		ProtCfg.field.ProtectCtrl = 0;			// CCK do not need to be protected
-		Protect[0] = ProtCfg.word;
-		ProtCfg.field.ProtectCtrl = ASIC_CTS;	// OFDM needs using CCK to protect
-		Protect[1] = ProtCfg.word;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	// Decide HT frame protection.
-	if ((SetMask & ALLN_SETPROTECT) != 0)
-	{
-		switch(OperationMode)
-		{
-			case 0x0:
-				// NO PROTECT
-				// 1.All STAs in the BSS are 20/40 MHz HT
-				// 2. in ai 20/40MHz BSS
-				// 3. all STAs are 20MHz in a 20MHz BSS
-				// Pure HT. no protection.
-
-				// MM20_PROT_CFG
-				//	Reserved (31:27)
-				// 	PROT_TXOP(25:20) -- 010111
-				//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-				//  PROT_CTRL(17:16) -- 00 (None)
-				// 	PROT_RATE(15:0)  -- 0x4004 (OFDM 24M)
-				Protect[2] = 0x01744004;
-
-				// MM40_PROT_CFG
-				//	Reserved (31:27)
-				// 	PROT_TXOP(25:20) -- 111111
-				//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-				//  PROT_CTRL(17:16) -- 00 (None)
-				// 	PROT_RATE(15:0)  -- 0x4084 (duplicate OFDM 24M)
-				Protect[3] = 0x03f44084;
-
-				// CF20_PROT_CFG
-				//	Reserved (31:27)
-				// 	PROT_TXOP(25:20) -- 010111
-				//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-				//  PROT_CTRL(17:16) -- 00 (None)
-				// 	PROT_RATE(15:0)  -- 0x4004 (OFDM 24M)
-				Protect[4] = 0x01744004;
-
-				// CF40_PROT_CFG
-				//	Reserved (31:27)
-				// 	PROT_TXOP(25:20) -- 111111
-				//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-				//  PROT_CTRL(17:16) -- 00 (None)
-				// 	PROT_RATE(15:0)  -- 0x4084 (duplicate OFDM 24M)
-				Protect[5] = 0x03f44084;
-
-				if (bNonGFExist)
-				{
-					// PROT_NAV(19:18)  -- 01 (Short NAV protectiion)
-					// PROT_CTRL(17:16) -- 01 (RTS/CTS)
-					Protect[4] = 0x01754004;
-					Protect[5] = 0x03f54084;
-				}
-				pAd->CommonCfg.IOTestParm.bRTSLongProtOn = FALSE;
-				break;
-
- 			case 1:
-				// This is "HT non-member protection mode."
-				// If there may be non-HT STAs my BSS
-				ProtCfg.word = 0x01744004;	// PROT_CTRL(17:16) : 0 (None)
-				ProtCfg4.word = 0x03f44084; // duplicaet legacy 24M. BW set 1.
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED))
-				{
-					ProtCfg.word = 0x01740003;	//ERP use Protection bit is set, use protection rate at Clause 18..
-					ProtCfg4.word = 0x03f40003; // Don't duplicate RTS/CTS in CCK mode. 0x03f40083;
-				}
-				//Assign Protection method for 20&40 MHz packets
-				ProtCfg.field.ProtectCtrl = ASIC_RTS;
-				ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
-				ProtCfg4.field.ProtectCtrl = ASIC_RTS;
-				ProtCfg4.field.ProtectNav = ASIC_SHORTNAV;
-				Protect[2] = ProtCfg.word;
-				Protect[3] = ProtCfg4.word;
-				Protect[4] = ProtCfg.word;
-				Protect[5] = ProtCfg4.word;
-				pAd->CommonCfg.IOTestParm.bRTSLongProtOn = TRUE;
-				break;
-
-			case 2:
-				// If only HT STAs are in BSS. at least one is 20MHz. Only protect 40MHz packets
-				ProtCfg.word = 0x01744004;  // PROT_CTRL(17:16) : 0 (None)
-				ProtCfg4.word = 0x03f44084; // duplicaet legacy 24M. BW set 1.
-
-				//Assign Protection method for 40MHz packets
-				ProtCfg4.field.ProtectCtrl = ASIC_RTS;
-				ProtCfg4.field.ProtectNav = ASIC_SHORTNAV;
-				Protect[2] = ProtCfg.word;
-				Protect[3] = ProtCfg4.word;
-				if (bNonGFExist)
-				{
-					ProtCfg.field.ProtectCtrl = ASIC_RTS;
-					ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
-				}
-				Protect[4] = ProtCfg.word;
-				Protect[5] = ProtCfg4.word;
-
-				pAd->CommonCfg.IOTestParm.bRTSLongProtOn = FALSE;
-				break;
-
-			case 3:
-				// HT mixed mode.	 PROTECT ALL!
-				// Assign Rate
-				ProtCfg.word = 0x01744004;	//duplicaet legacy 24M. BW set 1.
-				ProtCfg4.word = 0x03f44084;
-				// both 20MHz and 40MHz are protected. Whether use RTS or CTS-to-self depends on the
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED))
-				{
-					ProtCfg.word = 0x01740003;	//ERP use Protection bit is set, use protection rate at Clause 18..
-					ProtCfg4.word = 0x03f40003; // Don't duplicate RTS/CTS in CCK mode. 0x03f40083
-				}
-				//Assign Protection method for 20&40 MHz packets
-				ProtCfg.field.ProtectCtrl = ASIC_RTS;
-				ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
-				ProtCfg4.field.ProtectCtrl = ASIC_RTS;
-				ProtCfg4.field.ProtectNav = ASIC_SHORTNAV;
-				Protect[2] = ProtCfg.word;
-				Protect[3] = ProtCfg4.word;
-				Protect[4] = ProtCfg.word;
-				Protect[5] = ProtCfg4.word;
-				pAd->CommonCfg.IOTestParm.bRTSLongProtOn = TRUE;
-				break;
-
-			case 8:
-				Protect[2] = 0x01754004;
-				Protect[3] = 0x03f54084;
-				Protect[4] = 0x01754004;
-				Protect[5] = 0x03f54084;
-				pAd->CommonCfg.IOTestParm.bRTSLongProtOn = TRUE;
-				break;
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-	offset = CCK_PROT_CFG;
-	for (i = 0;i < 6;i++)
-	{
-		if ((SetMask & (1<< i)))
-		{
-			RTMP_IO_WRITE32(pAd, offset + i*4, Protect[i]);
-		}
-	}
-}
-
-
-#ifdef RT30xx
-/*
-	========================================================================
-
-	Routine Description: Write RT30xx RF register through MAC
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS RT30xxWriteRFRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			RegID,
-	IN	UCHAR			Value)
-{
-	RF_CSR_CFG_STRUC	rfcsr;
-	UINT				i = 0;
-
-	do
-	{
-		RTMP_IO_READ32(pAd, RF_CSR_CFG, &rfcsr.word);
-
-		if (!rfcsr.field.RF_CSR_KICK)
-			break;
-		i++;
-	}
-	while ((i < RETRY_LIMIT) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));
-
-	if ((i == RETRY_LIMIT) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-	{
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("Retry count exhausted or device removed!!!\n"));
-		return STATUS_UNSUCCESSFUL;
-	}
-
-	rfcsr.field.RF_CSR_WR = 1;
-	rfcsr.field.RF_CSR_KICK = 1;
-	rfcsr.field.TESTCSR_RFACC_REGNUM = RegID;
-	rfcsr.field.RF_CSR_DATA = Value;
-
-	RTMP_IO_WRITE32(pAd, RF_CSR_CFG, rfcsr.word);
-
-	return STATUS_SUCCESS;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description: Read RT30xx RF register through MAC
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS RT30xxReadRFRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			RegID,
-	IN	PUCHAR			pValue)
-{
-	RF_CSR_CFG_STRUC	rfcsr;
-	UINT				i=0, k=0;
-
-	for (i=0; i<MAX_BUSY_COUNT; i++)
-	{
-		RTMP_IO_READ32(pAd, RF_CSR_CFG, &rfcsr.word);
-
-		if (rfcsr.field.RF_CSR_KICK == BUSY)
-		{
-			continue;
-		}
-		rfcsr.word = 0;
-		rfcsr.field.RF_CSR_WR = 0;
-		rfcsr.field.RF_CSR_KICK = 1;
-		rfcsr.field.TESTCSR_RFACC_REGNUM = RegID;
-		RTMP_IO_WRITE32(pAd, RF_CSR_CFG, rfcsr.word);
-		for (k=0; k<MAX_BUSY_COUNT; k++)
-		{
-			RTMP_IO_READ32(pAd, RF_CSR_CFG, &rfcsr.word);
-
-			if (rfcsr.field.RF_CSR_KICK == IDLE)
-				break;
-		}
-		if ((rfcsr.field.RF_CSR_KICK == IDLE) &&
-			(rfcsr.field.TESTCSR_RFACC_REGNUM == RegID))
-		{
-			*pValue = (UCHAR)rfcsr.field.RF_CSR_DATA;
-			break;
-		}
-	}
-	if (rfcsr.field.RF_CSR_KICK == BUSY)
-	{
-		DBGPRINT_ERR(("RF read R%d=0x%x fail, i[%d], k[%d]\n", RegID, rfcsr.word,i,k));
-		return STATUS_UNSUCCESSFUL;
-	}
-
-	return STATUS_SUCCESS;
-}
-#endif // RT30xx //
-
-#ifdef RT30xx
-// add by johnli, RF power sequence setup
-/*
-	==========================================================================
-	Description:
-
-	Load RF normal operation-mode setup
-
-	==========================================================================
- */
-VOID RT30xxLoadRFNormalModeSetup(
-	IN PRTMP_ADAPTER 	pAd)
-{
-	UCHAR RFValue;
-
-	// RX0_PD & TX0_PD, RF R1 register Bit 2 & Bit 3 to 0 and RF_BLOCK_en,RX1_PD & TX1_PD, Bit0, Bit 4 & Bit5 to 1
-	RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
-	RFValue = (RFValue & (~0x0C)) | 0x31;
-	RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
-
-	// TX_LO2_en, RF R15 register Bit 3 to 0
-	RT30xxReadRFRegister(pAd, RF_R15, &RFValue);
-	RFValue &= (~0x08);
-	RT30xxWriteRFRegister(pAd, RF_R15, RFValue);
-
-	// TX_LO1_en, RF R17 register Bit 3 to 0
-	RT30xxReadRFRegister(pAd, RF_R17, &RFValue);
-	RFValue &= (~0x08);
-	// to fix rx long range issue
-	if (((pAd->MACVersion & 0xffff) >= 0x0211) && (pAd->NicConfig2.field.ExternalLNAForG == 0))
-	{
-		RFValue |= 0x20;
-	}
-	RT30xxWriteRFRegister(pAd, RF_R17, RFValue);
-
-	// RX_LO1_en, RF R20 register Bit 3 to 0
-	RT30xxReadRFRegister(pAd, RF_R20, &RFValue);
-	RFValue &= (~0x08);
-	RT30xxWriteRFRegister(pAd, RF_R20, RFValue);
-
-	// RX_LO2_en, RF R21 register Bit 3 to 0
-	RT30xxReadRFRegister(pAd, RF_R21, &RFValue);
-	RFValue &= (~0x08);
-	RT30xxWriteRFRegister(pAd, RF_R21, RFValue);
-
-	// LDORF_VC, RF R27 register Bit 2 to 0
-	RT30xxReadRFRegister(pAd, RF_R27, &RFValue);
-	if ((pAd->MACVersion & 0xffff) < 0x0211)
-		RFValue = (RFValue & (~0x77)) | 0x3;
-	else
-		RFValue = (RFValue & (~0x77));
-	RT30xxWriteRFRegister(pAd, RF_R27, RFValue);
-	/* end johnli */
-}
-
-/*
-	==========================================================================
-	Description:
-
-	Load RF sleep-mode setup
-
-	==========================================================================
- */
-VOID RT30xxLoadRFSleepModeSetup(
-	IN PRTMP_ADAPTER 	pAd)
-{
-	UCHAR RFValue;
-	UINT32 MACValue;
-
-	// RF_BLOCK_en. RF R1 register Bit 0 to 0
-	RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
-	RFValue &= (~0x01);
-	RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
-
-	// VCO_IC, RF R7 register Bit 4 & Bit 5 to 0
-	RT30xxReadRFRegister(pAd, RF_R07, &RFValue);
-	RFValue &= (~0x30);
-	RT30xxWriteRFRegister(pAd, RF_R07, RFValue);
-
-	// Idoh, RF R9 register Bit 1, Bit 2 & Bit 3 to 0
-	RT30xxReadRFRegister(pAd, RF_R09, &RFValue);
-	RFValue &= (~0x0E);
-	RT30xxWriteRFRegister(pAd, RF_R09, RFValue);
-
-	// RX_CTB_en, RF R21 register Bit 7 to 0
-	RT30xxReadRFRegister(pAd, RF_R21, &RFValue);
-	RFValue &= (~0x80);
-	RT30xxWriteRFRegister(pAd, RF_R21, RFValue);
-
-	// LDORF_VC, RF R27 register Bit 0, Bit 1 & Bit 2 to 1
-	RT30xxReadRFRegister(pAd, RF_R27, &RFValue);
-	RFValue |= 0x77;
-	RT30xxWriteRFRegister(pAd, RF_R27, RFValue);
-
-	RTMP_IO_READ32(pAd, LDO_CFG0, &MACValue);
-	MACValue |= 0x1D000000;
-	RTMP_IO_WRITE32(pAd, LDO_CFG0, MACValue);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	Reverse RF sleep-mode setup
-
-	==========================================================================
- */
-VOID RT30xxReverseRFSleepModeSetup(
-	IN PRTMP_ADAPTER 	pAd)
-{
-	UCHAR RFValue;
-	UINT32 MACValue;
-
-	// RF_BLOCK_en, RF R1 register Bit 0 to 1
-	RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
-	RFValue |= 0x01;
-	RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
-
-	// VCO_IC, RF R7 register Bit 4 & Bit 5 to 1
-	RT30xxReadRFRegister(pAd, RF_R07, &RFValue);
-	RFValue |= 0x30;
-	RT30xxWriteRFRegister(pAd, RF_R07, RFValue);
-
-	// Idoh, RF R9 register Bit 1, Bit 2 & Bit 3 to 1
-	RT30xxReadRFRegister(pAd, RF_R09, &RFValue);
-	RFValue |= 0x0E;
-	RT30xxWriteRFRegister(pAd, RF_R09, RFValue);
-
-	// RX_CTB_en, RF R21 register Bit 7 to 1
-	RT30xxReadRFRegister(pAd, RF_R21, &RFValue);
-	RFValue |= 0x80;
-	RT30xxWriteRFRegister(pAd, RF_R21, RFValue);
-
-	// LDORF_VC, RF R27 register Bit 2 to 0
-	RT30xxReadRFRegister(pAd, RF_R27, &RFValue);
-	if ((pAd->MACVersion & 0xffff) < 0x0211)
-		RFValue = (RFValue & (~0x77)) | 0x3;
-	else
-		RFValue = (RFValue & (~0x77));
-	RT30xxWriteRFRegister(pAd, RF_R27, RFValue);
-
-	// RT3071 version E has fixed this issue
-	if ((pAd->NicConfig2.field.DACTestBit == 1) && ((pAd->MACVersion & 0xffff) < 0x0211))
-	{
-		// patch tx EVM issue temporarily
-		RTMP_IO_READ32(pAd, LDO_CFG0, &MACValue);
-		MACValue = ((MACValue & 0xE0FFFFFF) | 0x0D000000);
-		RTMP_IO_WRITE32(pAd, LDO_CFG0, MACValue);
-	}
-	else
-	{
-		RTMP_IO_READ32(pAd, LDO_CFG0, &MACValue);
-		MACValue = ((MACValue & 0xE0FFFFFF) | 0x01000000);
-		RTMP_IO_WRITE32(pAd, LDO_CFG0, MACValue);
-	}
-}
-// end johnli
-#endif // RT30xx //
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicSwitchChannel(
-					  IN PRTMP_ADAPTER pAd,
-	IN	UCHAR			Channel,
-	IN	BOOLEAN			bScan)
-{
-	ULONG			R2 = 0, R3 = DEFAULT_RF_TX_POWER, R4 = 0;
-	CHAR    TxPwer = 0, TxPwer2 = DEFAULT_RF_TX_POWER; //Bbp94 = BBPR94_DEFAULT, TxPwer2 = DEFAULT_RF_TX_POWER;
-	UCHAR	index;
-	UINT32 	Value = 0; //BbpReg, Value;
-	RTMP_RF_REGS *RFRegTable;
-
-	// Search Tx power value
-#if 1
-	// We can't use ChannelList to search channel, since some central channl's txpowr doesn't list
-	// in ChannelList, so use TxPower array instead.
-	//
-	for (index = 0; index < MAX_NUM_OF_CHANNELS; index++)
-	{
-		if (Channel == pAd->TxPower[index].Channel)
-		{
-			TxPwer = pAd->TxPower[index].Power;
-			TxPwer2 = pAd->TxPower[index].Power2;
-			break;
-		}
-	}
-#else
-	for (index = 0; index < pAd->ChannelListNum; index++)
-	{
-		if (Channel == pAd->ChannelList[index].Channel)
-		{
-			TxPwer = pAd->ChannelList[index].Power;
-			TxPwer2 = pAd->ChannelList[index].Power2;
-			break;
-		}
-	}
-#endif
-
-	if (index == MAX_NUM_OF_CHANNELS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("AsicSwitchChannel: Can't find the Channel#%d \n", Channel));
-	}
-
-#ifdef RT30xx
-	// The RF programming sequence is difference between 3xxx and 2xxx
-	if ((IS_RT3070(pAd) || IS_RT3090(pAd)) && ((pAd->RfIcType == RFIC_3020) || (pAd->RfIcType == RFIC_2020) ||
-		(pAd->RfIcType == RFIC_3021) || (pAd->RfIcType == RFIC_3022)))
-	{
-		/* modify by WY for Read RF Reg. error */
-		UCHAR RFValue;
-
-		for (index = 0; index < NUM_OF_3020_CHNL; index++)
-		{
-			if (Channel == FreqItems3020[index].Channel)
-			{
-				// Programming channel parameters
-				RT30xxWriteRFRegister(pAd, RF_R02, FreqItems3020[index].N);
-				RT30xxWriteRFRegister(pAd, RF_R03, FreqItems3020[index].K);
-				RT30xxReadRFRegister(pAd, RF_R06, &RFValue);
-				RFValue = (RFValue & 0xFC) | FreqItems3020[index].R;
-				RT30xxWriteRFRegister(pAd, RF_R06, RFValue);
-
-				// Set Tx0 Power
-				RT30xxReadRFRegister(pAd, RF_R12, &RFValue);
-				RFValue = (RFValue & 0xE0) | TxPwer;
-				RT30xxWriteRFRegister(pAd, RF_R12, RFValue);
-
-				// Set Tx1 Power
-				RT30xxReadRFRegister(pAd, RF_R13, &RFValue);
-				RFValue = (RFValue & 0xE0) | TxPwer2;
-				RT30xxWriteRFRegister(pAd, RF_R13, RFValue);
-
-				// Tx/Rx Stream setting
-				RT30xxReadRFRegister(pAd, RF_R01, &RFValue);
-				//if (IS_RT3090(pAd))
-				//	RFValue |= 0x01; // Enable RF block.
-				RFValue &= 0x03;	//clear bit[7~2]
-				if (pAd->Antenna.field.TxPath == 1)
-					RFValue |= 0xA0;
-				else if (pAd->Antenna.field.TxPath == 2)
-					RFValue |= 0x80;
-				if (pAd->Antenna.field.RxPath == 1)
-					RFValue |= 0x50;
-				else if (pAd->Antenna.field.RxPath == 2)
-					RFValue |= 0x40;
-				RT30xxWriteRFRegister(pAd, RF_R01, RFValue);
-
-				// Set RF offset
-				RT30xxReadRFRegister(pAd, RF_R23, &RFValue);
-				RFValue = (RFValue & 0x80) | pAd->RfFreqOffset;
-				RT30xxWriteRFRegister(pAd, RF_R23, RFValue);
-
-				// Set BW
-				if (!bScan && (pAd->CommonCfg.BBPCurrentBW == BW_40))
-				{
-					RFValue = pAd->Mlme.CaliBW40RfR24;
-					//DISABLE_11N_CHECK(pAd);
-				}
-				else
-				{
-					RFValue = pAd->Mlme.CaliBW20RfR24;
-				}
-				RT30xxWriteRFRegister(pAd, RF_R24, RFValue);
-				RT30xxWriteRFRegister(pAd, RF_R31, RFValue);
-
-				// Enable RF tuning
-				RT30xxReadRFRegister(pAd, RF_R07, &RFValue);
-				RFValue = RFValue | 0x1;
-				RT30xxWriteRFRegister(pAd, RF_R07, RFValue);
-
-				// latch channel for future usage.
-				pAd->LatchRfRegs.Channel = Channel;
-
-				DBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%d, Pwr1=%d, %dT), N=0x%02X, K=0x%02X, R=0x%02X\n",
-					Channel,
-					pAd->RfIcType,
-					TxPwer,
-					TxPwer2,
-					pAd->Antenna.field.TxPath,
-					FreqItems3020[index].N,
-					FreqItems3020[index].K,
-					FreqItems3020[index].R));
-
-				break;
-			}
-		}
-	}
-	else
-#endif // RT30xx //
-
-	{
-		RFRegTable = RF2850RegTable;
-
-		switch (pAd->RfIcType)
-		{
-			case RFIC_2820:
-			case RFIC_2850:
-			case RFIC_2720:
-			case RFIC_2750:
-
-			for (index = 0; index < NUM_OF_2850_CHNL; index++)
-			{
-				if (Channel == RFRegTable[index].Channel)
-				{
-					R2 = RFRegTable[index].R2;
-					if (pAd->Antenna.field.TxPath == 1)
-					{
-						R2 |= 0x4000;	// If TXpath is 1, bit 14 = 1;
-					}
-
-					if (pAd->Antenna.field.RxPath == 2)
-					{
-						R2 |= 0x40;	// write 1 to off Rxpath.
-					}
-					else if (pAd->Antenna.field.RxPath == 1)
-					{
-						R2 |= 0x20040;	// write 1 to off RxPath
-					}
-
-					if (Channel > 14)
-					{
-						// initialize R3, R4
-						R3 = (RFRegTable[index].R3 & 0xffffc1ff);
-						R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->RfFreqOffset << 15);
-
-						// 5G band power range: 0xF9~0X0F, TX0 Reg3 bit9/TX1 Reg4 bit6="0" means the TX power reduce 7dB
-						// R3
-						if ((TxPwer >= -7) && (TxPwer < 0))
-						{
-							TxPwer = (7+TxPwer);
-							TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
-							R3 |= (TxPwer << 10);
-							DBGPRINT(RT_DEBUG_ERROR, ("AsicSwitchChannel: TxPwer=%d \n", TxPwer));
-						}
-						else
-						{
-							TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
-							R3 |= (TxPwer << 10) | (1 << 9);
-						}
-
-						// R4
-						if ((TxPwer2 >= -7) && (TxPwer2 < 0))
-						{
-							TxPwer2 = (7+TxPwer2);
-							TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
-							R4 |= (TxPwer2 << 7);
-							DBGPRINT(RT_DEBUG_ERROR, ("AsicSwitchChannel: TxPwer2=%d \n", TxPwer2));
-						}
-						else
-						{
-							TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
-							R4 |= (TxPwer2 << 7) | (1 << 6);
-						}
-					}
-					else
-					{
-						R3 = (RFRegTable[index].R3 & 0xffffc1ff) | (TxPwer << 9); // set TX power0
-					R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->RfFreqOffset << 15) | (TxPwer2 <<6);// Set freq Offset & TxPwr1
-					}
-
-					// Based on BBP current mode before changing RF channel.
-					if (!bScan && (pAd->CommonCfg.BBPCurrentBW == BW_40))
-					{
-						R4 |=0x200000;
-					}
-
-					// Update variables
-					pAd->LatchRfRegs.Channel = Channel;
-					pAd->LatchRfRegs.R1 = RFRegTable[index].R1;
-					pAd->LatchRfRegs.R2 = R2;
-					pAd->LatchRfRegs.R3 = R3;
-					pAd->LatchRfRegs.R4 = R4;
-
-					// Set RF value 1's set R3[bit2] = [0]
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-					RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-					RTMPusecDelay(200);
-
-					// Set RF value 2's set R3[bit2] = [1]
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-					RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 | 0x04));
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-					RTMPusecDelay(200);
-
-					// Set RF value 3's set R3[bit2] = [0]
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-					RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
-					RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-					break;
-				}
-			}
-			break;
-
-			default:
-			break;
-		}
-	}
-
-	// Change BBP setting during siwtch from a->g, g->a
-	if (Channel <= 14)
-	{
-	    ULONG	TxPinCfg = 0x00050F0A;//Gary 2007/08/09 0x050A0A
-
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0);//(0x44 - GET_LNA_GAIN(pAd)));	// According the Rory's suggestion to solve the middle range issue.
-		//RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x62);
-
-		// Rx High power VGA offset for LNA select
-	    if (pAd->NicConfig2.field.ExternalLNAForG)
-	    {
-	        RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x62);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x46);
-	    }
-	    else
-	    {
-	        RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x84);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x50);
-	    }
-
-		// 5G band selection PIN, bit1 and bit2 are complement
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		Value &= (~0x6);
-		Value |= (0x04);
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-
-        // Turn off unused PA or LNA when only 1T or 1R
-		if (pAd->Antenna.field.TxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFFFF3;
-		}
-		if (pAd->Antenna.field.RxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFF3FF;
-		}
-
-		RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
-	}
-	else
-	{
-	    ULONG	TxPinCfg = 0x00050F05;//Gary 2007/8/9 0x050505
-
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0);//(0x44 - GET_LNA_GAIN(pAd)));   // According the Rory's suggestion to solve the middle range issue.
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0xF2);
-
-		// Rx High power VGA offset for LNA select
-		if (pAd->NicConfig2.field.ExternalLNAForA)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x46);
-		}
-		else
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R75, 0x50);
-		}
-
-		// 5G band selection PIN, bit1 and bit2 are complement
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		Value &= (~0x6);
-		Value |= (0x02);
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-
-        // Turn off unused PA or LNA when only 1T or 1R
-		if (pAd->Antenna.field.TxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFFFF3;
-	}
-		if (pAd->Antenna.field.RxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFF3FF;
-	}
-
-		RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
-	}
-
-    // R66 should be set according to Channel and use 20MHz when scanning
-	//RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, (0x2E + GET_LNA_GAIN(pAd)));
-	if (bScan)
-		RTMPSetAGCInitValue(pAd, BW_20);
-	else
-		RTMPSetAGCInitValue(pAd, pAd->CommonCfg.BBPCurrentBW);
-
-	//
-	// On 11A, We should delay and wait RF/BBP to be stable
-	// and the appropriate time should be 1000 micro seconds
-	// 2005/06/05 - On 11G, We also need this delay time. Otherwise it's difficult to pass the WHQL.
-	//
-	RTMPusecDelay(1000);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%lu, Pwr1=%lu, %dT) to , R1=0x%08lx, R2=0x%08lx, R3=0x%08lx, R4=0x%08lx\n",
-							  Channel,
-							  pAd->RfIcType,
-							  (R3 & 0x00003e00) >> 9,
-							  (R4 & 0x000007c0) >> 6,
-							  pAd->Antenna.field.TxPath,
-							  pAd->LatchRfRegs.R1,
-							  pAd->LatchRfRegs.R2,
-							  pAd->LatchRfRegs.R3,
-							  pAd->LatchRfRegs.R4));
-}
-
-/*
-	==========================================================================
-	Description:
-		This function is required for 2421 only, and should not be used during
-		site survey. It's only required after NIC decided to stay at a channel
-		for a longer period.
-		When this function is called, it's always after AsicSwitchChannel().
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicLockChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR Channel)
-{
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID	AsicAntennaSelect(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Channel)
-{
-			if (pAd->Mlme.OneSecPeriodicRound % 2 == 1)
-			{
-				// patch for AsicSetRxAnt failed
-				pAd->RxAnt.EvaluatePeriod = 0;
-
-				// check every 2 second. If rcv-beacon less than 5 in the past 2 second, then AvgRSSI is no longer a
-				// valid indication of the distance between this AP and its clients.
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				{
-					SHORT	realavgrssi1;
-
-					// if no traffic then reset average rssi to trigger evaluation
-#ifdef CONFIG_STA_SUPPORT
-					if (pAd->StaCfg.NumOfAvgRssiSample < 5)
-					{
-						pAd->RxAnt.Pair1LastAvgRssi = (-99);
-						pAd->RxAnt.Pair2LastAvgRssi = (-99);
-						DBGPRINT(RT_DEBUG_TRACE, ("MlmePeriodicExec: no traffic/beacon, reset RSSI\n"));
-					}
-
-					pAd->StaCfg.NumOfAvgRssiSample = 0;
-#endif // CONFIG_STA_SUPPORT //
-					realavgrssi1 = (pAd->RxAnt.Pair1AvgRssi[pAd->RxAnt.Pair1PrimaryRxAnt] >> 3);
-
-					DBGPRINT(RT_DEBUG_TRACE,("Ant-realrssi0(%d), Lastrssi0(%d), EvaluateStableCnt=%d\n", realavgrssi1, pAd->RxAnt.Pair1LastAvgRssi, pAd->RxAnt.EvaluateStableCnt));
-
-					// if the difference between two rssi is larger or less than 5, then evaluate the other antenna
-					if ((pAd->RxAnt.EvaluateStableCnt < 2) || (realavgrssi1 > (pAd->RxAnt.Pair1LastAvgRssi + 5)) || (realavgrssi1 < (pAd->RxAnt.Pair1LastAvgRssi - 5)))
-					{
-						pAd->RxAnt.Pair1LastAvgRssi = realavgrssi1;
-						AsicEvaluateRxAnt(pAd);
-					}
-				}
-				else
-				{
-					// if not connected, always switch antenna to try to connect
-					UCHAR	temp;
-
-					temp = pAd->RxAnt.Pair1PrimaryRxAnt;
-					pAd->RxAnt.Pair1PrimaryRxAnt = pAd->RxAnt.Pair1SecondaryRxAnt;
-					pAd->RxAnt.Pair1SecondaryRxAnt = temp;
-
-					DBGPRINT(RT_DEBUG_TRACE, ("MlmePeriodicExec: no connect, switch to another one to try connection\n"));
-
-					AsicSetRxAnt(pAd, pAd->RxAnt.Pair1PrimaryRxAnt);
-				}
-			}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Antenna miscellaneous setting.
-
-	Arguments:
-		pAd						Pointer to our adapter
-		BandState				Indicate current Band State.
-
-	Return Value:
-		None
-
-	IRQL <= DISPATCH_LEVEL
-
-	Note:
-		1.) Frame End type control
-			only valid for G only (RF_2527 & RF_2529)
-			0: means DPDT, set BBP R4 bit 5 to 1
-			1: means SPDT, set BBP R4 bit 5 to 0
-
-
-	========================================================================
-*/
-VOID	AsicAntennaSetting(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	ABGBAND_STATE	BandState)
-{
-}
-
-VOID AsicRfTuningExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-}
-
-/*
-	==========================================================================
-	Description:
-		Gives CCK TX rate 2 more dB TX power.
-		This routine works only in LINK UP in INFRASTRUCTURE mode.
-
-		calculate desired Tx power in RF R3.Tx0~5,	should consider -
-		0. if current radio is a noisy environment (pAd->DrsCounters.fNoisyEnvironment)
-		1. TxPowerPercentage
-		2. auto calibration based on TSSI feedback
-		3. extra 2 db for CCK
-		4. -10 db upon very-short distance (AvgRSSI >= -40db) to AP
-
-	NOTE: Since this routine requires the value of (pAd->DrsCounters.fNoisyEnvironment),
-		it should be called AFTER MlmeDynamicTxRatSwitching()
-	==========================================================================
- */
-VOID AsicAdjustTxPower(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT			i, j;
-	CHAR		DeltaPwr = 0;
-	BOOLEAN		bAutoTxAgc = FALSE;
-	UCHAR		TssiRef, *pTssiMinusBoundary, *pTssiPlusBoundary, TxAgcStep;
-	UCHAR		BbpR1 = 0, BbpR49 = 0, idx;
-	PCHAR		pTxAgcCompensate;
-	ULONG		TxPwr[5];
-	CHAR		Value;
-
-
-
-	if (pAd->CommonCfg.BBPCurrentBW == BW_40)
-	{
-		if (pAd->CommonCfg.CentralChannel > 14)
-		{
-			TxPwr[0] = pAd->Tx40MPwrCfgABand[0];
-			TxPwr[1] = pAd->Tx40MPwrCfgABand[1];
-			TxPwr[2] = pAd->Tx40MPwrCfgABand[2];
-			TxPwr[3] = pAd->Tx40MPwrCfgABand[3];
-			TxPwr[4] = pAd->Tx40MPwrCfgABand[4];
-		}
-		else
-		{
-			TxPwr[0] = pAd->Tx40MPwrCfgGBand[0];
-			TxPwr[1] = pAd->Tx40MPwrCfgGBand[1];
-			TxPwr[2] = pAd->Tx40MPwrCfgGBand[2];
-			TxPwr[3] = pAd->Tx40MPwrCfgGBand[3];
-			TxPwr[4] = pAd->Tx40MPwrCfgGBand[4];
-		}
-	}
-	else
-	{
-		if (pAd->CommonCfg.Channel > 14)
-		{
-			TxPwr[0] = pAd->Tx20MPwrCfgABand[0];
-			TxPwr[1] = pAd->Tx20MPwrCfgABand[1];
-			TxPwr[2] = pAd->Tx20MPwrCfgABand[2];
-			TxPwr[3] = pAd->Tx20MPwrCfgABand[3];
-			TxPwr[4] = pAd->Tx20MPwrCfgABand[4];
-		}
-		else
-		{
-			TxPwr[0] = pAd->Tx20MPwrCfgGBand[0];
-			TxPwr[1] = pAd->Tx20MPwrCfgGBand[1];
-			TxPwr[2] = pAd->Tx20MPwrCfgGBand[2];
-			TxPwr[3] = pAd->Tx20MPwrCfgGBand[3];
-			TxPwr[4] = pAd->Tx20MPwrCfgGBand[4];
-		}
-	}
-
-	// TX power compensation for temperature variation based on TSSI. try every 4 second
-	if (pAd->Mlme.OneSecPeriodicRound % 4 == 0)
-	{
-		if (pAd->CommonCfg.Channel <= 14)
-		{
-			/* bg channel */
-			bAutoTxAgc         = pAd->bAutoTxAgcG;
-			TssiRef            = pAd->TssiRefG;
-			pTssiMinusBoundary = &pAd->TssiMinusBoundaryG[0];
-			pTssiPlusBoundary  = &pAd->TssiPlusBoundaryG[0];
-			TxAgcStep          = pAd->TxAgcStepG;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateG;
-		}
-		else
-		{
-			/* a channel */
-			bAutoTxAgc         = pAd->bAutoTxAgcA;
-			TssiRef            = pAd->TssiRefA;
-			pTssiMinusBoundary = &pAd->TssiMinusBoundaryA[0];
-			pTssiPlusBoundary  = &pAd->TssiPlusBoundaryA[0];
-			TxAgcStep          = pAd->TxAgcStepA;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateA;
-		}
-
-		if (bAutoTxAgc)
-		{
-			/* BbpR1 is unsigned char */
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R49, &BbpR49);
-
-			/* (p) TssiPlusBoundaryG[0] = 0 = (m) TssiMinusBoundaryG[0] */
-			/* compensate: +4     +3   +2   +1    0   -1   -2   -3   -4 * steps */
-			/* step value is defined in pAd->TxAgcStepG for tx power value */
-
-			/* [4]+1+[4]   p4     p3   p2   p1   o1   m1   m2   m3   m4 */
-			/* ex:         0x00 0x15 0x25 0x45 0x88 0xA0 0xB5 0xD0 0xF0
-			   above value are examined in mass factory production */
-			/*             [4]    [3]  [2]  [1]  [0]  [1]  [2]  [3]  [4] */
-
-			/* plus (+) is 0x00 ~ 0x45, minus (-) is 0xa0 ~ 0xf0 */
-			/* if value is between p1 ~ o1 or o1 ~ s1, no need to adjust tx power */
-			/* if value is 0xa5, tx power will be -= TxAgcStep*(2-1) */
-
-			if (BbpR49 > pTssiMinusBoundary[1])
-			{
-				// Reading is larger than the reference value
-				// check for how large we need to decrease the Tx power
-				for (idx = 1; idx < 5; idx++)
-				{
-					if (BbpR49 <= pTssiMinusBoundary[idx])  // Found the range
-						break;
-				}
-				// The index is the step we should decrease, idx = 0 means there is nothing to compensate
-//				if (R3 > (ULONG) (TxAgcStep * (idx-1)))
-					*pTxAgcCompensate = -(TxAgcStep * (idx-1));
-//				else
-//					*pTxAgcCompensate = -((UCHAR)R3);
-
-				DeltaPwr += (*pTxAgcCompensate);
-				DBGPRINT(RT_DEBUG_TRACE, ("-- Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = -%d\n",
-					BbpR49, TssiRef, TxAgcStep, idx-1));
-			}
-			else if (BbpR49 < pTssiPlusBoundary[1])
-			{
-				// Reading is smaller than the reference value
-				// check for how large we need to increase the Tx power
-				for (idx = 1; idx < 5; idx++)
-				{
-					if (BbpR49 >= pTssiPlusBoundary[idx])   // Found the range
-						break;
-				}
-				// The index is the step we should increase, idx = 0 means there is nothing to compensate
-				*pTxAgcCompensate = TxAgcStep * (idx-1);
-				DeltaPwr += (*pTxAgcCompensate);
-				DBGPRINT(RT_DEBUG_TRACE, ("++ Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
-					BbpR49, TssiRef, TxAgcStep, idx-1));
-			}
-			else
-			{
-				*pTxAgcCompensate = 0;
-				DBGPRINT(RT_DEBUG_TRACE, ("   Tx Power, BBP R49=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
-					BbpR49, TssiRef, TxAgcStep, 0));
-			}
-		}
-	}
-	else
-	{
-		if (pAd->CommonCfg.Channel <= 14)
-		{
-			bAutoTxAgc         = pAd->bAutoTxAgcG;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateG;
-		}
-		else
-		{
-			bAutoTxAgc         = pAd->bAutoTxAgcA;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateA;
-		}
-
-		if (bAutoTxAgc)
-			DeltaPwr += (*pTxAgcCompensate);
-	}
-
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpR1);
-	BbpR1 &= 0xFC;
-
-#ifdef SINGLE_SKU
-	// Handle regulatory max tx power constrain
-	do
-	{
-		UCHAR    TxPwrInEEPROM = 0xFF, CountryTxPwr = 0xFF, criterion;
-		UCHAR    AdjustMaxTxPwr[40];
-
-		if (pAd->CommonCfg.Channel > 14) // 5G band
-			TxPwrInEEPROM = ((pAd->CommonCfg.DefineMaxTxPwr & 0xFF00) >> 8);
-		else // 2.4G band
-			TxPwrInEEPROM = (pAd->CommonCfg.DefineMaxTxPwr & 0x00FF);
-		CountryTxPwr = GetCuntryMaxTxPwr(pAd, pAd->CommonCfg.Channel);
-
-		// error handling, range check
-		if ((TxPwrInEEPROM > 0x50) || (CountryTxPwr > 0x50))
-		{
-			DBGPRINT(RT_DEBUG_ERROR,("AsicAdjustTxPower - Invalid max tx power (=0x%02x), CountryTxPwr=%d\n", TxPwrInEEPROM, CountryTxPwr));
-			break;
-		}
-
-		criterion = *((PUCHAR)TxPwr + 2) & 0xF;        // FAE use OFDM 6M as criterion
-
-		DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (criterion=%d, TxPwrInEEPROM=%d, CountryTxPwr=%d)\n", criterion, TxPwrInEEPROM, CountryTxPwr));
-
-		// Adjust max tx power according to the relationship of tx power in E2PROM
-		for (i=0; i<5; i++)
-		{
-			// CCK will have 4dBm larger than OFDM
-			// Therefore, we should separate to parse the tx power field
-			if (i == 0)
-			{
-				for (j=0; j<8; j++)
-				{
-					Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F);
-
-					if (j < 4)
-					{
-						// CCK will have 4dBm larger than OFDM
-						AdjustMaxTxPwr[i*8+j] = TxPwrInEEPROM + (Value - criterion) + 4;
-					}
-					else
-					{
-						AdjustMaxTxPwr[i*8+j] = TxPwrInEEPROM + (Value - criterion);
-					}
-					DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-				}
-			}
-			else
-			{
-				for (j=0; j<8; j++)
-				{
-					Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F);
-
-					AdjustMaxTxPwr[i*8+j] = TxPwrInEEPROM + (Value - criterion);
-					DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-				}
-			}
-		}
-
-		// Adjust tx power according to the relationship
-		for (i=0; i<5; i++)
-		{
-			if (TxPwr[i] != 0xffffffff)
-			{
-				for (j=0; j<8; j++)
-				{
-					Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F);
-
-					// The system tx power is larger than the regulatory, the power should be restrain
-					if (AdjustMaxTxPwr[i*8+j] > CountryTxPwr)
-					{
-						// decrease to zero and don't need to take care BBPR1
-						if ((Value - (AdjustMaxTxPwr[i*8+j] - CountryTxPwr)) > 0)
-							Value -= (AdjustMaxTxPwr[i*8+j] - CountryTxPwr);
-						else
-							Value = 0;
-
-						DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-					}
-					else
-						DBGPRINT_RAW(RT_DEBUG_TRACE,("AsicAdjustTxPower (i/j=%d/%d, Value=%d, %d, no change)\n", i, j, Value, AdjustMaxTxPwr[i*8+j]));
-
-						TxPwr[i] = (TxPwr[i] & ~(0x0000000F << j*4)) | (Value << j*4);
-				}
-			}
-		}
-	} while (FALSE);
-#endif // SINGLE_SKU //
-
-	/* calculate delta power based on the percentage specified from UI */
-	// E2PROM setting is calibrated for maximum TX power (i.e. 100%)
-	// We lower TX power here according to the percentage specified from UI
-	if (pAd->CommonCfg.TxPowerPercentage == 0xffffffff)       // AUTO TX POWER control
-		;
-	else if (pAd->CommonCfg.TxPowerPercentage > 90)  // 91 ~ 100% & AUTO, treat as 100% in terms of mW
-		;
-	else if (pAd->CommonCfg.TxPowerPercentage > 60)  // 61 ~ 90%, treat as 75% in terms of mW		// DeltaPwr -= 1;
-	{
-		DeltaPwr -= 1;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 30)  // 31 ~ 60%, treat as 50% in terms of mW		// DeltaPwr -= 3;
-	{
-		DeltaPwr -= 3;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 15)  // 16 ~ 30%, treat as 25% in terms of mW		// DeltaPwr -= 6;
-	{
-		BbpR1 |= 0x01;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 9)   // 10 ~ 15%, treat as 12.5% in terms of mW		// DeltaPwr -= 9;
-	{
-		BbpR1 |= 0x01;
-		DeltaPwr -= 3;
-	}
-	else                                           // 0 ~ 9 %, treat as MIN(~3%) in terms of mW		// DeltaPwr -= 12;
-	{
-		BbpR1 |= 0x02;
-	}
-
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpR1);
-
-	/* reset different new tx power for different TX rate */
-	for(i=0; i<5; i++)
-	{
-		if (TxPwr[i] != 0xffffffff)
-		{
-			for (j=0; j<8; j++)
-			{
-				Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F); /* 0 ~ 15 */
-
-				if ((Value + DeltaPwr) < 0)
-				{
-					Value = 0; /* min */
-				}
-				else if ((Value + DeltaPwr) > 0xF)
-				{
-					Value = 0xF; /* max */
-				}
-				else
-				{
-					Value += DeltaPwr; /* temperature compensation */
-				}
-
-				/* fill new value to CSR offset */
-				TxPwr[i] = (TxPwr[i] & ~(0x0000000F << j*4)) | (Value << j*4);
-			}
-
-			/* write tx power value to CSR */
-			/* TX_PWR_CFG_0 (8 tx rate) for	TX power for OFDM 12M/18M
-											TX power for OFDM 6M/9M
-											TX power for CCK5.5M/11M
-											TX power for CCK1M/2M */
-			/* TX_PWR_CFG_1 ~ TX_PWR_CFG_4 */
-			RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, TxPwr[i]);
-		}
-	}
-
-
-}
-
-#ifdef CONFIG_STA_SUPPORT
-/*
-	==========================================================================
-	Description:
-		put PHY to sleep here, and set next wakeup timer. PHY doesn't not wakeup
-		automatically. Instead, MCU will issue a TwakeUpInterrupt to host after
-		the wakeup timer timeout. Driver has to issue a separate command to wake
-		PHY up.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicSleepThenAutoWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT TbttNumToNextWakeUp)
-{
-    RT28XX_STA_SLEEP_THEN_AUTO_WAKEUP(pAd, TbttNumToNextWakeUp);
-}
-
-/*
-	==========================================================================
-	Description:
-		AsicForceWakeup() is used whenever manual wakeup is required
-		AsicForceSleep() should only be used when not in INFRA BSS. When
-		in INFRA BSS, we should use AsicSleepThenAutoWakeup() instead.
-	==========================================================================
- */
-VOID AsicForceSleep(
-	IN PRTMP_ADAPTER pAd)
-{
-
-}
-
-/*
-	==========================================================================
-	Description:
-		AsicForceWakeup() is used whenever Twakeup timer (set via AsicSleepThenAutoWakeup)
-		expired.
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-	==========================================================================
- */
-VOID AsicForceWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN    bFromTx)
-{
-    DBGPRINT(RT_DEBUG_TRACE, ("--> AsicForceWakeup \n"));
-    RT28XX_STA_FORCE_WAKEUP(pAd, bFromTx);
-}
-#endif // CONFIG_STA_SUPPORT //
-/*
-	==========================================================================
-	Description:
-		Set My BSSID
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicSetBssid(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pBssid)
-{
-	ULONG		  Addr4;
-	DBGPRINT(RT_DEBUG_TRACE, ("==============> AsicSetBssid %x:%x:%x:%x:%x:%x\n",
-		pBssid[0],pBssid[1],pBssid[2],pBssid[3], pBssid[4],pBssid[5]));
-
-	Addr4 = (ULONG)(pBssid[0])		 |
-			(ULONG)(pBssid[1] << 8)  |
-			(ULONG)(pBssid[2] << 16) |
-			(ULONG)(pBssid[3] << 24);
-	RTMP_IO_WRITE32(pAd, MAC_BSSID_DW0, Addr4);
-
-	Addr4 = 0;
-	// always one BSSID in STA mode
-	Addr4 = (ULONG)(pBssid[4]) | (ULONG)(pBssid[5] << 8);
-
-	RTMP_IO_WRITE32(pAd, MAC_BSSID_DW1, Addr4);
-}
-
-VOID AsicSetMcastWC(
-	IN PRTMP_ADAPTER pAd)
-{
-	MAC_TABLE_ENTRY *pEntry = &pAd->MacTab.Content[MCAST_WCID];
-	USHORT		offset;
-
-	pEntry->Sst        = SST_ASSOC;
-	pEntry->Aid        = MCAST_WCID;	// Softap supports 1 BSSID and use WCID=0 as multicast Wcid index
-	pEntry->PsMode     = PWR_ACTIVE;
-	pEntry->CurrTxRate = pAd->CommonCfg.MlmeRate;
-	offset = MAC_WCID_BASE + BSS0Mcast_WCID * HW_WCID_ENTRY_SIZE;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicDelWcidTab(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR	Wcid)
-{
-	ULONG		  Addr0 = 0x0, Addr1 = 0x0;
-	ULONG 		offset;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AsicDelWcidTab==>Wcid = 0x%x\n",Wcid));
-	offset = MAC_WCID_BASE + Wcid * HW_WCID_ENTRY_SIZE;
-	RTMP_IO_WRITE32(pAd, offset, Addr0);
-	offset += 4;
-	RTMP_IO_WRITE32(pAd, offset, Addr1);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicEnableRDG(
-	IN PRTMP_ADAPTER pAd)
-{
-	TX_LINK_CFG_STRUC	TxLinkCfg;
-	UINT32				Data = 0;
-
-	RTMP_IO_READ32(pAd, TX_LINK_CFG, &TxLinkCfg.word);
-	TxLinkCfg.field.TxRDGEn = 1;
-	RTMP_IO_WRITE32(pAd, TX_LINK_CFG, TxLinkCfg.word);
-
-	RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
-	Data  &= 0xFFFFFF00;
-	Data  |= 0x80;
-	RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
-
-	//OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicDisableRDG(
-	IN PRTMP_ADAPTER pAd)
-{
-	TX_LINK_CFG_STRUC	TxLinkCfg;
-	UINT32				Data = 0;
-
-
-	RTMP_IO_READ32(pAd, TX_LINK_CFG, &TxLinkCfg.word);
-	TxLinkCfg.field.TxRDGEn = 0;
-	RTMP_IO_WRITE32(pAd, TX_LINK_CFG, TxLinkCfg.word);
-
-	RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
-
-	Data  &= 0xFFFFFF00;
-	//Data  |= 0x20;
-#ifndef WIFI_TEST
-	//if ( pAd->CommonCfg.bEnableTxBurst )
-	//	Data |= 0x60; // for performance issue not set the TXOP to 0
-#endif
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_DYNAMIC_BE_TXOP_ACTIVE)
-#ifdef DOT11_N_SUPPORT
-		&& (pAd->MacTab.fAnyStationMIMOPSDynamic == FALSE)
-#endif // DOT11_N_SUPPORT //
-	)
-	{
-		// For CWC test, change txop from 0x30 to 0x20 in TxBurst mode
-		if (pAd->CommonCfg.bEnableTxBurst)
-			Data |= 0x20;
-	}
-	RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicDisableSync(
-	IN PRTMP_ADAPTER pAd)
-{
-	BCN_TIME_CFG_STRUC csr;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--->Disable TSF synchronization\n"));
-
-	// 2003-12-20 disable TSF and TBTT while NIC in power-saving have side effect
-	//			  that NIC will never wakes up because TSF stops and no more
-	//			  TBTT interrupts
-	pAd->TbttTickCount = 0;
-	RTMP_IO_READ32(pAd, BCN_TIME_CFG, &csr.word);
-	csr.field.bBeaconGen = 0;
-	csr.field.bTBTTEnable = 0;
-	csr.field.TsfSyncMode = 0;
-	csr.field.bTsfTicking = 0;
-	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr.word);
-
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicEnableBssSync(
-	IN PRTMP_ADAPTER pAd)
-{
-	BCN_TIME_CFG_STRUC csr;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--->AsicEnableBssSync(INFRA mode)\n"));
-
-	RTMP_IO_READ32(pAd, BCN_TIME_CFG, &csr.word);
-//	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, 0x00000000);
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		csr.field.BeaconInterval = pAd->CommonCfg.BeaconPeriod << 4; // ASIC register in units of 1/16 TU
-		csr.field.bTsfTicking = 1;
-		csr.field.TsfSyncMode = 1; // sync TSF in INFRASTRUCTURE mode
-		csr.field.bBeaconGen  = 0; // do NOT generate BEACON
-		csr.field.bTBTTEnable = 1;
-	}
-#endif // CONFIG_STA_SUPPORT //
-	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr.word);
-}
-
-/*
-	==========================================================================
-	Description:
-	Note:
-		BEACON frame in shared memory should be built ok before this routine
-		can be called. Otherwise, a garbage frame maybe transmitted out every
-		Beacon period.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicEnableIbssSync(
-	IN PRTMP_ADAPTER pAd)
-{
-	BCN_TIME_CFG_STRUC csr9;
-	PUCHAR			ptr;
-	UINT i;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--->AsicEnableIbssSync(ADHOC mode. MPDUtotalByteCount = %d)\n", pAd->BeaconTxWI.MPDUtotalByteCount));
-
-	RTMP_IO_READ32(pAd, BCN_TIME_CFG, &csr9.word);
-	csr9.field.bBeaconGen = 0;
-	csr9.field.bTBTTEnable = 0;
-	csr9.field.bTsfTicking = 0;
-	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr9.word);
-
-
-#ifdef RT2870
-	// move BEACON TXD and frame content to on-chip memory
-	ptr = (PUCHAR)&pAd->BeaconTxWI;
-	for (i=0; i<TXWI_SIZE; i+=2)  // 16-byte TXWI field
-	{
-		//UINT32 longptr =  *ptr + (*(ptr+1)<<8) + (*(ptr+2)<<16) + (*(ptr+3)<<24);
-		//RTMP_IO_WRITE32(pAd, HW_BEACON_BASE0 + i, longptr);
-		RTUSBMultiWrite(pAd, HW_BEACON_BASE0 + i, ptr, 2);
-		ptr += 2;
-	}
-
-	// start right after the 16-byte TXWI field
-	ptr = pAd->BeaconBuf;
-	for (i=0; i< pAd->BeaconTxWI.MPDUtotalByteCount; i+=2)
-	{
-		//UINT32 longptr =  *ptr + (*(ptr+1)<<8) + (*(ptr+2)<<16) + (*(ptr+3)<<24);
-		//RTMP_IO_WRITE32(pAd, HW_BEACON_BASE0 + TXWI_SIZE + i, longptr);
-		RTUSBMultiWrite(pAd, HW_BEACON_BASE0 + TXWI_SIZE + i, ptr, 2);
-		ptr +=2;
-	}
-#endif // RT2870 //
-
-	//
-	// For Wi-Fi faily generated beacons between participating stations.
-	// Set TBTT phase adaptive adjustment step to 8us (default 16us)
-	// don't change settings 2006-5- by Jerry
-	//RTMP_IO_WRITE32(pAd, TBTT_SYNC_CFG, 0x00001010);
-
-	// start sending BEACON
-	csr9.field.BeaconInterval = pAd->CommonCfg.BeaconPeriod << 4; // ASIC register in units of 1/16 TU
-	csr9.field.bTsfTicking = 1;
-	csr9.field.TsfSyncMode = 2; // sync TSF in IBSS mode
-	csr9.field.bTBTTEnable = 1;
-	csr9.field.bBeaconGen = 1;
-	RTMP_IO_WRITE32(pAd, BCN_TIME_CFG, csr9.word);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicSetEdcaParm(
-	IN PRTMP_ADAPTER pAd,
-	IN PEDCA_PARM	 pEdcaParm)
-{
-	EDCA_AC_CFG_STRUC   Ac0Cfg, Ac1Cfg, Ac2Cfg, Ac3Cfg;
-	AC_TXOP_CSR0_STRUC csr0;
-	AC_TXOP_CSR1_STRUC csr1;
-	AIFSN_CSR_STRUC    AifsnCsr;
-	CWMIN_CSR_STRUC    CwminCsr;
-	CWMAX_CSR_STRUC    CwmaxCsr;
-	int i;
-
-	Ac0Cfg.word = 0;
-	Ac1Cfg.word = 0;
-	Ac2Cfg.word = 0;
-	Ac3Cfg.word = 0;
-	if ((pEdcaParm == NULL) || (pEdcaParm->bValid == FALSE))
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("AsicSetEdcaParm\n"));
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_WMM_INUSED);
-		for (i=0; i<MAX_LEN_OF_MAC_TABLE; i++)
-		{
-			if (pAd->MacTab.Content[i].ValidAsCLI || pAd->MacTab.Content[i].ValidAsApCli)
-				CLIENT_STATUS_CLEAR_FLAG(&pAd->MacTab.Content[i], fCLIENT_STATUS_WMM_CAPABLE);
-		}
-
-		//========================================================
-		//      MAC Register has a copy .
-		//========================================================
-//#ifndef WIFI_TEST
-		if( pAd->CommonCfg.bEnableTxBurst )
-		{
-			// For CWC test, change txop from 0x30 to 0x20 in TxBurst mode
-			Ac0Cfg.field.AcTxop = 0x20; // Suggest by John for TxBurst in HT Mode
-		}
-		else
-			Ac0Cfg.field.AcTxop = 0;	// QID_AC_BE
-//#else
-//		Ac0Cfg.field.AcTxop = 0;	// QID_AC_BE
-//#endif
-		Ac0Cfg.field.Cwmin = CW_MIN_IN_BITS;
-		Ac0Cfg.field.Cwmax = CW_MAX_IN_BITS;
-		Ac0Cfg.field.Aifsn = 2;
-		RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Ac0Cfg.word);
-
-		Ac1Cfg.field.AcTxop = 0;	// QID_AC_BK
-		Ac1Cfg.field.Cwmin = CW_MIN_IN_BITS;
-		Ac1Cfg.field.Cwmax = CW_MAX_IN_BITS;
-		Ac1Cfg.field.Aifsn = 2;
-		RTMP_IO_WRITE32(pAd, EDCA_AC1_CFG, Ac1Cfg.word);
-
-		if (pAd->CommonCfg.PhyMode == PHY_11B)
-		{
-			Ac2Cfg.field.AcTxop = 192;	// AC_VI: 192*32us ~= 6ms
-			Ac3Cfg.field.AcTxop = 96;	// AC_VO: 96*32us  ~= 3ms
-		}
-		else
-		{
-			Ac2Cfg.field.AcTxop = 96;	// AC_VI: 96*32us ~= 3ms
-			Ac3Cfg.field.AcTxop = 48;	// AC_VO: 48*32us ~= 1.5ms
-		}
-		Ac2Cfg.field.Cwmin = CW_MIN_IN_BITS;
-		Ac2Cfg.field.Cwmax = CW_MAX_IN_BITS;
-		Ac2Cfg.field.Aifsn = 2;
-		RTMP_IO_WRITE32(pAd, EDCA_AC2_CFG, Ac2Cfg.word);
-		Ac3Cfg.field.Cwmin = CW_MIN_IN_BITS;
-		Ac3Cfg.field.Cwmax = CW_MAX_IN_BITS;
-		Ac3Cfg.field.Aifsn = 2;
-		RTMP_IO_WRITE32(pAd, EDCA_AC3_CFG, Ac3Cfg.word);
-
-		//========================================================
-		//      DMA Register has a copy too.
-		//========================================================
-		csr0.field.Ac0Txop = 0;		// QID_AC_BE
-		csr0.field.Ac1Txop = 0;		// QID_AC_BK
-		RTMP_IO_WRITE32(pAd, WMM_TXOP0_CFG, csr0.word);
-		if (pAd->CommonCfg.PhyMode == PHY_11B)
-		{
-			csr1.field.Ac2Txop = 192;		// AC_VI: 192*32us ~= 6ms
-			csr1.field.Ac3Txop = 96;		// AC_VO: 96*32us  ~= 3ms
-		}
-		else
-		{
-			csr1.field.Ac2Txop = 96;		// AC_VI: 96*32us ~= 3ms
-			csr1.field.Ac3Txop = 48;		// AC_VO: 48*32us ~= 1.5ms
-		}
-		RTMP_IO_WRITE32(pAd, WMM_TXOP1_CFG, csr1.word);
-
-		CwminCsr.word = 0;
-		CwminCsr.field.Cwmin0 = CW_MIN_IN_BITS;
-		CwminCsr.field.Cwmin1 = CW_MIN_IN_BITS;
-		CwminCsr.field.Cwmin2 = CW_MIN_IN_BITS;
-		CwminCsr.field.Cwmin3 = CW_MIN_IN_BITS;
-		RTMP_IO_WRITE32(pAd, WMM_CWMIN_CFG, CwminCsr.word);
-
-		CwmaxCsr.word = 0;
-		CwmaxCsr.field.Cwmax0 = CW_MAX_IN_BITS;
-		CwmaxCsr.field.Cwmax1 = CW_MAX_IN_BITS;
-		CwmaxCsr.field.Cwmax2 = CW_MAX_IN_BITS;
-		CwmaxCsr.field.Cwmax3 = CW_MAX_IN_BITS;
-		RTMP_IO_WRITE32(pAd, WMM_CWMAX_CFG, CwmaxCsr.word);
-
-		RTMP_IO_WRITE32(pAd, WMM_AIFSN_CFG, 0x00002222);
-
-		NdisZeroMemory(&pAd->CommonCfg.APEdcaParm, sizeof(EDCA_PARM));
-	}
-	else
-	{
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_WMM_INUSED);
-		//========================================================
-		//      MAC Register has a copy.
-		//========================================================
-		//
-		// Modify Cwmin/Cwmax/Txop on queue[QID_AC_VI], Recommend by Jerry 2005/07/27
-		// To degrade our VIDO Queue's throughput for WiFi WMM S3T07 Issue.
-		//
-		//pEdcaParm->Txop[QID_AC_VI] = pEdcaParm->Txop[QID_AC_VI] * 7 / 10; // rt2860c need this
-
-		Ac0Cfg.field.AcTxop =  pEdcaParm->Txop[QID_AC_BE];
-		Ac0Cfg.field.Cwmin= pEdcaParm->Cwmin[QID_AC_BE];
-		Ac0Cfg.field.Cwmax = pEdcaParm->Cwmax[QID_AC_BE];
-		Ac0Cfg.field.Aifsn = pEdcaParm->Aifsn[QID_AC_BE]; //+1;
-
-		Ac1Cfg.field.AcTxop =  pEdcaParm->Txop[QID_AC_BK];
-		Ac1Cfg.field.Cwmin = pEdcaParm->Cwmin[QID_AC_BK]; //+2;
-		Ac1Cfg.field.Cwmax = pEdcaParm->Cwmax[QID_AC_BK];
-		Ac1Cfg.field.Aifsn = pEdcaParm->Aifsn[QID_AC_BK]; //+1;
-
-		Ac2Cfg.field.AcTxop = (pEdcaParm->Txop[QID_AC_VI] * 6) / 10;
-		Ac2Cfg.field.Cwmin = pEdcaParm->Cwmin[QID_AC_VI];
-		Ac2Cfg.field.Cwmax = pEdcaParm->Cwmax[QID_AC_VI];
-		Ac2Cfg.field.Aifsn = pEdcaParm->Aifsn[QID_AC_VI];
-#ifdef INF_AMAZON_SE
-#endif // INF_AMAZON_SE //
-
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			// Tuning for Wi-Fi WMM S06
-			if (pAd->CommonCfg.bWiFiTest &&
-				pEdcaParm->Aifsn[QID_AC_VI] == 10)
-				Ac2Cfg.field.Aifsn -= 1;
-
-			// Tuning for TGn Wi-Fi 5.2.32
-			// STA TestBed changes in this item: conexant legacy sta ==> broadcom 11n sta
-			if (STA_TGN_WIFI_ON(pAd) &&
-				pEdcaParm->Aifsn[QID_AC_VI] == 10)
-			{
-				Ac0Cfg.field.Aifsn = 3;
-				Ac2Cfg.field.AcTxop = 5;
-			}
-
-#ifdef RT30xx
-			if (pAd->RfIcType == RFIC_3020 || pAd->RfIcType == RFIC_2020)
-			{
-				// Tuning for WiFi WMM S3-T07: connexant legacy sta ==> broadcom 11n sta.
-				Ac2Cfg.field.Aifsn = 5;
-			}
-#endif // RT30xx //
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		Ac3Cfg.field.AcTxop = pEdcaParm->Txop[QID_AC_VO];
-		Ac3Cfg.field.Cwmin = pEdcaParm->Cwmin[QID_AC_VO];
-		Ac3Cfg.field.Cwmax = pEdcaParm->Cwmax[QID_AC_VO];
-		Ac3Cfg.field.Aifsn = pEdcaParm->Aifsn[QID_AC_VO];
-
-//#ifdef WIFI_TEST
-		if (pAd->CommonCfg.bWiFiTest)
-		{
-			if (Ac3Cfg.field.AcTxop == 102)
-			{
-			Ac0Cfg.field.AcTxop = pEdcaParm->Txop[QID_AC_BE] ? pEdcaParm->Txop[QID_AC_BE] : 10;
-				Ac0Cfg.field.Aifsn  = pEdcaParm->Aifsn[QID_AC_BE]-1; /* AIFSN must >= 1 */
-			Ac1Cfg.field.AcTxop = pEdcaParm->Txop[QID_AC_BK];
-				Ac1Cfg.field.Aifsn  = pEdcaParm->Aifsn[QID_AC_BK];
-			Ac2Cfg.field.AcTxop = pEdcaParm->Txop[QID_AC_VI];
-			} /* End of if */
-		}
-//#endif // WIFI_TEST //
-
-		RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Ac0Cfg.word);
-		RTMP_IO_WRITE32(pAd, EDCA_AC1_CFG, Ac1Cfg.word);
-		RTMP_IO_WRITE32(pAd, EDCA_AC2_CFG, Ac2Cfg.word);
-		RTMP_IO_WRITE32(pAd, EDCA_AC3_CFG, Ac3Cfg.word);
-
-
-		//========================================================
-		//      DMA Register has a copy too.
-		//========================================================
-		csr0.field.Ac0Txop = Ac0Cfg.field.AcTxop;
-		csr0.field.Ac1Txop = Ac1Cfg.field.AcTxop;
-		RTMP_IO_WRITE32(pAd, WMM_TXOP0_CFG, csr0.word);
-
-		csr1.field.Ac2Txop = Ac2Cfg.field.AcTxop;
-		csr1.field.Ac3Txop = Ac3Cfg.field.AcTxop;
-		RTMP_IO_WRITE32(pAd, WMM_TXOP1_CFG, csr1.word);
-
-		CwminCsr.word = 0;
-		CwminCsr.field.Cwmin0 = pEdcaParm->Cwmin[QID_AC_BE];
-		CwminCsr.field.Cwmin1 = pEdcaParm->Cwmin[QID_AC_BK];
-		CwminCsr.field.Cwmin2 = pEdcaParm->Cwmin[QID_AC_VI];
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			CwminCsr.field.Cwmin3 = pEdcaParm->Cwmin[QID_AC_VO] - 1; //for TGn wifi test
-#endif // CONFIG_STA_SUPPORT //
-		RTMP_IO_WRITE32(pAd, WMM_CWMIN_CFG, CwminCsr.word);
-
-		CwmaxCsr.word = 0;
-		CwmaxCsr.field.Cwmax0 = pEdcaParm->Cwmax[QID_AC_BE];
-		CwmaxCsr.field.Cwmax1 = pEdcaParm->Cwmax[QID_AC_BK];
-		CwmaxCsr.field.Cwmax2 = pEdcaParm->Cwmax[QID_AC_VI];
-		CwmaxCsr.field.Cwmax3 = pEdcaParm->Cwmax[QID_AC_VO];
-		RTMP_IO_WRITE32(pAd, WMM_CWMAX_CFG, CwmaxCsr.word);
-
-		AifsnCsr.word = 0;
-		AifsnCsr.field.Aifsn0 = Ac0Cfg.field.Aifsn; //pEdcaParm->Aifsn[QID_AC_BE];
-		AifsnCsr.field.Aifsn1 = Ac1Cfg.field.Aifsn; //pEdcaParm->Aifsn[QID_AC_BK];
-		AifsnCsr.field.Aifsn2 = Ac2Cfg.field.Aifsn; //pEdcaParm->Aifsn[QID_AC_VI];
-#ifdef INF_AMAZON_SE
-#endif // INF_AMAZON_SE //
-
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			// Tuning for Wi-Fi WMM S06
-			if (pAd->CommonCfg.bWiFiTest &&
-				pEdcaParm->Aifsn[QID_AC_VI] == 10)
-				AifsnCsr.field.Aifsn2 = Ac2Cfg.field.Aifsn - 4;
-
-			// Tuning for TGn Wi-Fi 5.2.32
-			// STA TestBed changes in this item: connexant legacy sta ==> broadcom 11n sta
-			if (STA_TGN_WIFI_ON(pAd) &&
-				pEdcaParm->Aifsn[QID_AC_VI] == 10)
-			{
-				AifsnCsr.field.Aifsn0 = 3;
-				AifsnCsr.field.Aifsn2 = 7;
-			}
-
-			if (INFRA_ON(pAd))
-				CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_WMM_CAPABLE);
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			AifsnCsr.field.Aifsn3 = Ac3Cfg.field.Aifsn - 1; //pEdcaParm->Aifsn[QID_AC_VO]; //for TGn wifi test
-#ifdef RT30xx
-		if (pAd->RfIcType == RFIC_3020 || pAd->RfIcType == RFIC_2020)
-		{
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			AifsnCsr.field.Aifsn2 = 0x2; //pEdcaParm->Aifsn[QID_AC_VI]; //for WiFi WMM S4-T04.
-		}
-#endif // RT30xx //
-#endif // CONFIG_STA_SUPPORT //
-		RTMP_IO_WRITE32(pAd, WMM_AIFSN_CFG, AifsnCsr.word);
-
-		NdisMoveMemory(&pAd->CommonCfg.APEdcaParm, pEdcaParm, sizeof(EDCA_PARM));
-		if (!ADHOC_ON(pAd))
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("EDCA [#%d]: AIFSN CWmin CWmax  TXOP(us)  ACM\n", pEdcaParm->EdcaUpdateCount));
-			DBGPRINT(RT_DEBUG_TRACE,("     AC_BE      %2d     %2d     %2d      %4d     %d\n",
-									 pEdcaParm->Aifsn[0],
-									 pEdcaParm->Cwmin[0],
-									 pEdcaParm->Cwmax[0],
-									 pEdcaParm->Txop[0]<<5,
-									 pEdcaParm->bACM[0]));
-			DBGPRINT(RT_DEBUG_TRACE,("     AC_BK      %2d     %2d     %2d      %4d     %d\n",
-									 pEdcaParm->Aifsn[1],
-									 pEdcaParm->Cwmin[1],
-									 pEdcaParm->Cwmax[1],
-									 pEdcaParm->Txop[1]<<5,
-									 pEdcaParm->bACM[1]));
-			DBGPRINT(RT_DEBUG_TRACE,("     AC_VI      %2d     %2d     %2d      %4d     %d\n",
-									 pEdcaParm->Aifsn[2],
-									 pEdcaParm->Cwmin[2],
-									 pEdcaParm->Cwmax[2],
-									 pEdcaParm->Txop[2]<<5,
-									 pEdcaParm->bACM[2]));
-			DBGPRINT(RT_DEBUG_TRACE,("     AC_VO      %2d     %2d     %2d      %4d     %d\n",
-									 pEdcaParm->Aifsn[3],
-									 pEdcaParm->Cwmin[3],
-									 pEdcaParm->Cwmax[3],
-									 pEdcaParm->Txop[3]<<5,
-									 pEdcaParm->bACM[3]));
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID 	AsicSetSlotTime(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN bUseShortSlotTime)
-{
-	ULONG	SlotTime;
-	UINT32	RegValue = 0;
-
-#ifdef CONFIG_STA_SUPPORT
-	if (pAd->CommonCfg.Channel > 14)
-		bUseShortSlotTime = TRUE;
-#endif // CONFIG_STA_SUPPORT //
-
-	if (bUseShortSlotTime)
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_SHORT_SLOT_INUSED);
-	else
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_SLOT_INUSED);
-
-	SlotTime = (bUseShortSlotTime)? 9 : 20;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// force using short SLOT time for FAE to demo performance when TxBurst is ON
-		if (pAd->CommonCfg.bEnableTxBurst)
-			SlotTime = 9;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	//
-	// For some reasons, always set it to short slot time.
-	//
-	// ToDo: Should consider capability with 11B
-	//
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pAd->StaCfg.BssType == BSS_ADHOC)
-			SlotTime = 20;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	RTMP_IO_READ32(pAd, BKOFF_SLOT_CFG, &RegValue);
-	RegValue = RegValue & 0xFFFFFF00;
-
-	RegValue |= SlotTime;
-
-	RTMP_IO_WRITE32(pAd, BKOFF_SLOT_CFG, RegValue);
-}
-
-/*
-	========================================================================
-	Description:
-		Add Shared key information into ASIC.
-		Update shared key, TxMic and RxMic to Asic Shared key table
-		Update its cipherAlg to Asic Shared key Mode.
-
-    Return:
-	========================================================================
-*/
-VOID AsicAddSharedKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		 BssIndex,
-	IN UCHAR		 KeyIdx,
-	IN UCHAR		 CipherAlg,
-	IN PUCHAR		 pKey,
-	IN PUCHAR		 pTxMic,
-	IN PUCHAR		 pRxMic)
-{
-	ULONG offset; //, csr0;
-	SHAREDKEY_MODE_STRUC csr1;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AsicAddSharedKeyEntry BssIndex=%d, KeyIdx=%d\n", BssIndex,KeyIdx));
-//============================================================================================
-
-	DBGPRINT(RT_DEBUG_TRACE,("AsicAddSharedKeyEntry: %s key #%d\n", CipherName[CipherAlg], BssIndex*4 + KeyIdx));
-	DBGPRINT_RAW(RT_DEBUG_TRACE, (" 	Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pKey[0],pKey[1],pKey[2],pKey[3],pKey[4],pKey[5],pKey[6],pKey[7],pKey[8],pKey[9],pKey[10],pKey[11],pKey[12],pKey[13],pKey[14],pKey[15]));
-	if (pRxMic)
-	{
-		DBGPRINT_RAW(RT_DEBUG_TRACE, (" 	Rx MIC Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-			pRxMic[0],pRxMic[1],pRxMic[2],pRxMic[3],pRxMic[4],pRxMic[5],pRxMic[6],pRxMic[7]));
-	}
-	if (pTxMic)
-	{
-		DBGPRINT_RAW(RT_DEBUG_TRACE, (" 	Tx MIC Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-			pTxMic[0],pTxMic[1],pTxMic[2],pTxMic[3],pTxMic[4],pTxMic[5],pTxMic[6],pTxMic[7]));
-	}
-//============================================================================================
-	//
-	// fill key material - key + TX MIC + RX MIC
-	//
-
-#ifdef RT2870
-{
-	offset = SHARED_KEY_TABLE_BASE + (4*BssIndex + KeyIdx)*HW_KEY_ENTRY_SIZE;
-	RTUSBMultiWrite(pAd, offset, pKey, MAX_LEN_OF_SHARE_KEY);
-
-	offset += MAX_LEN_OF_SHARE_KEY;
-	if (pTxMic)
-	{
-		RTUSBMultiWrite(pAd, offset, pTxMic, 8);
-	}
-
-	offset += 8;
-	if (pRxMic)
-	{
-		RTUSBMultiWrite(pAd, offset, pRxMic, 8);
-	}
-}
-#endif // RT2870 //
-
-	//
-	// Update cipher algorithm. WSTA always use BSS0
-	//
-	RTMP_IO_READ32(pAd, SHARED_KEY_MODE_BASE+4*(BssIndex/2), &csr1.word);
-	DBGPRINT(RT_DEBUG_TRACE,("Read: SHARED_KEY_MODE_BASE at this Bss[%d] KeyIdx[%d]= 0x%x \n", BssIndex,KeyIdx, csr1.word));
-	if ((BssIndex%2) == 0)
-	{
-		if (KeyIdx == 0)
-			csr1.field.Bss0Key0CipherAlg = CipherAlg;
-		else if (KeyIdx == 1)
-			csr1.field.Bss0Key1CipherAlg = CipherAlg;
-		else if (KeyIdx == 2)
-			csr1.field.Bss0Key2CipherAlg = CipherAlg;
-		else
-			csr1.field.Bss0Key3CipherAlg = CipherAlg;
-	}
-	else
-	{
-		if (KeyIdx == 0)
-			csr1.field.Bss1Key0CipherAlg = CipherAlg;
-		else if (KeyIdx == 1)
-			csr1.field.Bss1Key1CipherAlg = CipherAlg;
-		else if (KeyIdx == 2)
-			csr1.field.Bss1Key2CipherAlg = CipherAlg;
-		else
-			csr1.field.Bss1Key3CipherAlg = CipherAlg;
-	}
-	DBGPRINT(RT_DEBUG_TRACE,("Write: SHARED_KEY_MODE_BASE at this Bss[%d] = 0x%x \n", BssIndex, csr1.word));
-	RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE+4*(BssIndex/2), csr1.word);
-
-}
-
-//	IRQL = DISPATCH_LEVEL
-VOID AsicRemoveSharedKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		 BssIndex,
-	IN UCHAR		 KeyIdx)
-{
-	//ULONG SecCsr0;
-	SHAREDKEY_MODE_STRUC csr1;
-
-	DBGPRINT(RT_DEBUG_TRACE,("AsicRemoveSharedKeyEntry: #%d \n", BssIndex*4 + KeyIdx));
-
-	RTMP_IO_READ32(pAd, SHARED_KEY_MODE_BASE+4*(BssIndex/2), &csr1.word);
-	if ((BssIndex%2) == 0)
-	{
-		if (KeyIdx == 0)
-			csr1.field.Bss0Key0CipherAlg = 0;
-		else if (KeyIdx == 1)
-			csr1.field.Bss0Key1CipherAlg = 0;
-		else if (KeyIdx == 2)
-			csr1.field.Bss0Key2CipherAlg = 0;
-		else
-			csr1.field.Bss0Key3CipherAlg = 0;
-	}
-	else
-	{
-		if (KeyIdx == 0)
-			csr1.field.Bss1Key0CipherAlg = 0;
-		else if (KeyIdx == 1)
-			csr1.field.Bss1Key1CipherAlg = 0;
-		else if (KeyIdx == 2)
-			csr1.field.Bss1Key2CipherAlg = 0;
-		else
-			csr1.field.Bss1Key3CipherAlg = 0;
-	}
-	DBGPRINT(RT_DEBUG_TRACE,("Write: SHARED_KEY_MODE_BASE at this Bss[%d] = 0x%x \n", BssIndex, csr1.word));
-	RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE+4*(BssIndex/2), csr1.word);
-	ASSERT(BssIndex < 4);
-	ASSERT(KeyIdx < 4);
-
-}
-
-
-VOID AsicUpdateWCIDAttribute(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN UCHAR		BssIndex,
-	IN UCHAR        CipherAlg,
-	IN BOOLEAN		bUsePairewiseKeyTable)
-{
-	ULONG   WCIDAttri = 0, offset;
-
-	//
-	// Update WCID attribute.
-	// Only TxKey could update WCID attribute.
-	//
-	offset = MAC_WCID_ATTRIBUTE_BASE + (WCID * HW_WCID_ATTRI_SIZE);
-	WCIDAttri = (BssIndex << 4) | (CipherAlg << 1) | (bUsePairewiseKeyTable);
-	RTMP_IO_WRITE32(pAd, offset, WCIDAttri);
-}
-
-VOID AsicUpdateWCIDIVEIV(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN ULONG        uIV,
-	IN ULONG        uEIV)
-{
-	ULONG	offset;
-
-	offset = MAC_IVEIV_TABLE_BASE + (WCID * HW_IVEIV_ENTRY_SIZE);
-
-	RTMP_IO_WRITE32(pAd, offset, uIV);
-	RTMP_IO_WRITE32(pAd, offset + 4, uEIV);
-}
-
-VOID AsicUpdateRxWCIDTable(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN PUCHAR        pAddr)
-{
-	ULONG offset;
-	ULONG Addr;
-
-	offset = MAC_WCID_BASE + (WCID * HW_WCID_ENTRY_SIZE);
-	Addr = pAddr[0] + (pAddr[1] << 8) +(pAddr[2] << 16) +(pAddr[3] << 24);
-	RTMP_IO_WRITE32(pAd, offset, Addr);
-	Addr = pAddr[4] + (pAddr[5] << 8);
-	RTMP_IO_WRITE32(pAd, offset + 4, Addr);
-}
-
-
-/*
-    ========================================================================
-
-    Routine Description:
-        Set Cipher Key, Cipher algorithm, IV/EIV to Asic
-
-    Arguments:
-        pAd                     Pointer to our adapter
-        WCID                    WCID Entry number.
-        BssIndex                BSSID index, station or none multiple BSSID support
-                                this value should be 0.
-        KeyIdx                  This KeyIdx will set to IV's KeyID if bTxKey enabled
-        pCipherKey              Pointer to Cipher Key.
-        bUsePairewiseKeyTable   TRUE means saved the key in SharedKey table,
-                                otherwise PairewiseKey table
-        bTxKey                  This is the transmit key if enabled.
-
-    Return Value:
-        None
-
-    Note:
-        This routine will set the relative key stuff to Asic including WCID attribute,
-        Cipher Key, Cipher algorithm and IV/EIV.
-
-        IV/EIV will be update if this CipherKey is the transmission key because
-        ASIC will base on IV's KeyID value to select Cipher Key.
-
-        If bTxKey sets to FALSE, this is not the TX key, but it could be
-        RX key
-
-    	For AP mode bTxKey must be always set to TRUE.
-    ========================================================================
-*/
-VOID AsicAddKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN UCHAR		BssIndex,
-	IN UCHAR		KeyIdx,
-	IN PCIPHER_KEY	pCipherKey,
-	IN BOOLEAN		bUsePairewiseKeyTable,
-	IN BOOLEAN		bTxKey)
-{
-	ULONG	offset;
-//	ULONG   WCIDAttri = 0;
-	UCHAR	IV4 = 0;
-	PUCHAR		pKey = pCipherKey->Key;
-//	ULONG		KeyLen = pCipherKey->KeyLen;
-	PUCHAR		pTxMic = pCipherKey->TxMic;
-	PUCHAR		pRxMic = pCipherKey->RxMic;
-	PUCHAR		pTxtsc = pCipherKey->TxTsc;
-	UCHAR		CipherAlg = pCipherKey->CipherAlg;
-	SHAREDKEY_MODE_STRUC csr1;
-
-//	ASSERT(KeyLen <= MAX_LEN_OF_PEER_KEY);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==> AsicAddKeyEntry\n"));
-	//
-	// 1.) decide key table offset
-	//
-	if (bUsePairewiseKeyTable)
-		offset = PAIRWISE_KEY_TABLE_BASE + (WCID * HW_KEY_ENTRY_SIZE);
-	else
-		offset = SHARED_KEY_TABLE_BASE + (4 * BssIndex + KeyIdx) * HW_KEY_ENTRY_SIZE;
-
-	//
-	// 2.) Set Key to Asic
-	//
-	//for (i = 0; i < KeyLen; i++)
-
-#ifdef RT2870
-	RTUSBMultiWrite(pAd, offset, pKey, MAX_LEN_OF_PEER_KEY);
-	offset += MAX_LEN_OF_PEER_KEY;
-
-	//
-	// 3.) Set MIC key if available
-	//
-	if (pTxMic)
-	{
-		RTUSBMultiWrite(pAd, offset, pTxMic, 8);
-	}
-	offset += LEN_TKIP_TXMICK;
-
-	if (pRxMic)
-	{
-		RTUSBMultiWrite(pAd, offset, pRxMic, 8);
-	}
-#endif // RT2870 //
-
-	//
-	// 4.) Modify IV/EIV if needs
-	//     This will force Asic to use this key ID by setting IV.
-	//
-	if (bTxKey)
-	{
-
-#ifdef RT2870
-		UINT32 tmpVal;
-
-		//
-		// Write IV
-		//
-		IV4 = (KeyIdx << 6);
-		if ((CipherAlg == CIPHER_TKIP) || (CipherAlg == CIPHER_TKIP_NO_MIC) ||(CipherAlg == CIPHER_AES))
-			IV4 |= 0x20;  // turn on extension bit means EIV existence
-
-		tmpVal = pTxtsc[1] + (((pTxtsc[1] | 0x20) & 0x7f) << 8) + (pTxtsc[0] << 16) + (IV4 << 24);
-		RTMP_IO_WRITE32(pAd, offset, tmpVal);
-
-		//
-		// Write EIV
-		//
-		offset += 4;
-		RTMP_IO_WRITE32(pAd, offset, *(PUINT32)&pCipherKey->TxTsc[2]);
-#endif // RT2870 //
-		AsicUpdateWCIDAttribute(pAd, WCID, BssIndex, CipherAlg, bUsePairewiseKeyTable);
-	}
-
-	if (!bUsePairewiseKeyTable)
-	{
-		//
-		// Only update the shared key security mode
-		//
-		RTMP_IO_READ32(pAd, SHARED_KEY_MODE_BASE + 4 * (BssIndex / 2), &csr1.word);
-		if ((BssIndex % 2) == 0)
-		{
-			if (KeyIdx == 0)
-				csr1.field.Bss0Key0CipherAlg = CipherAlg;
-			else if (KeyIdx == 1)
-				csr1.field.Bss0Key1CipherAlg = CipherAlg;
-			else if (KeyIdx == 2)
-				csr1.field.Bss0Key2CipherAlg = CipherAlg;
-			else
-				csr1.field.Bss0Key3CipherAlg = CipherAlg;
-		}
-		else
-		{
-			if (KeyIdx == 0)
-				csr1.field.Bss1Key0CipherAlg = CipherAlg;
-			else if (KeyIdx == 1)
-				csr1.field.Bss1Key1CipherAlg = CipherAlg;
-			else if (KeyIdx == 2)
-				csr1.field.Bss1Key2CipherAlg = CipherAlg;
-			else
-				csr1.field.Bss1Key3CipherAlg = CipherAlg;
-		}
-		RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE + 4 * (BssIndex / 2), csr1.word);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<== AsicAddKeyEntry\n"));
-}
-
-
-/*
-	========================================================================
-	Description:
-		Add Pair-wise key material into ASIC.
-		Update pairwise key, TxMic and RxMic to Asic Pair-wise key table
-
-    Return:
-	========================================================================
-*/
-VOID AsicAddPairwiseKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR        pAddr,
-	IN UCHAR		WCID,
-	IN CIPHER_KEY		 *pCipherKey)
-{
-	INT i;
-	ULONG 		offset;
-	PUCHAR		 pKey = pCipherKey->Key;
-	PUCHAR		 pTxMic = pCipherKey->TxMic;
-	PUCHAR		 pRxMic = pCipherKey->RxMic;
-#ifdef DBG
-	UCHAR		CipherAlg = pCipherKey->CipherAlg;
-#endif // DBG //
-
-	// EKEY
-	offset = PAIRWISE_KEY_TABLE_BASE + (WCID * HW_KEY_ENTRY_SIZE);
-#ifdef RT2870
-	RTUSBMultiWrite(pAd, offset, &pCipherKey->Key[0], MAX_LEN_OF_PEER_KEY);
-#endif // RT2870 //
-	for (i=0; i<MAX_LEN_OF_PEER_KEY; i+=4)
-	{
-		UINT32 Value;
-		RTMP_IO_READ32(pAd, offset + i, &Value);
-	}
-
-	offset += MAX_LEN_OF_PEER_KEY;
-
-	//  MIC KEY
-	if (pTxMic)
-	{
-#ifdef RT2870
-		RTUSBMultiWrite(pAd, offset, &pCipherKey->TxMic[0], 8);
-#endif // RT2870 //
-	}
-	offset += 8;
-	if (pRxMic)
-	{
-#ifdef RT2870
-		RTUSBMultiWrite(pAd, offset, &pCipherKey->RxMic[0], 8);
-#endif // RT2870 //
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("AsicAddPairwiseKeyEntry: WCID #%d Alg=%s\n",WCID, CipherName[CipherAlg]));
-	DBGPRINT(RT_DEBUG_TRACE,("	Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pKey[0],pKey[1],pKey[2],pKey[3],pKey[4],pKey[5],pKey[6],pKey[7],pKey[8],pKey[9],pKey[10],pKey[11],pKey[12],pKey[13],pKey[14],pKey[15]));
-	if (pRxMic)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("	Rx MIC Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-			pRxMic[0],pRxMic[1],pRxMic[2],pRxMic[3],pRxMic[4],pRxMic[5],pRxMic[6],pRxMic[7]));
-	}
-	if (pTxMic)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("	Tx MIC Key = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
-			pTxMic[0],pTxMic[1],pTxMic[2],pTxMic[3],pTxMic[4],pTxMic[5],pTxMic[6],pTxMic[7]));
-	}
-}
-/*
-	========================================================================
-	Description:
-		Remove Pair-wise key material from ASIC.
-
-    Return:
-	========================================================================
-*/
-VOID AsicRemovePairwiseKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		 BssIdx,
-	IN UCHAR		 Wcid)
-{
-	ULONG		WCIDAttri;
-	USHORT		offset;
-
-	// re-set the entry's WCID attribute as OPEN-NONE.
-	offset = MAC_WCID_ATTRIBUTE_BASE + (Wcid * HW_WCID_ATTRI_SIZE);
-	WCIDAttri = (BssIdx<<4) | PAIRWISEKEYTABLE;
-	RTMP_IO_WRITE32(pAd, offset, WCIDAttri);
-}
-
-BOOLEAN AsicSendCommandToMcu(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		 Command,
-	IN UCHAR		 Token,
-	IN UCHAR		 Arg0,
-	IN UCHAR		 Arg1)
-{
-	HOST_CMD_CSR_STRUC	H2MCmd;
-	H2M_MAILBOX_STRUC	H2MMailbox;
-	ULONG				i = 0;
-	do
-	{
-		RTMP_IO_READ32(pAd, H2M_MAILBOX_CSR, &H2MMailbox.word);
-		if (H2MMailbox.field.Owner == 0)
-			break;
-
-		RTMPusecDelay(2);
-	} while(i++ < 100);
-
-	if (i >= 100)
-	{
-		{
-		DBGPRINT_ERR(("H2M_MAILBOX still hold by MCU. command fail\n"));
-		}
-		return FALSE;
-	}
-
-
-	H2MMailbox.field.Owner	  = 1;	   // pass ownership to MCU
-	H2MMailbox.field.CmdToken = Token;
-	H2MMailbox.field.HighByte = Arg1;
-	H2MMailbox.field.LowByte  = Arg0;
-	RTMP_IO_WRITE32(pAd, H2M_MAILBOX_CSR, H2MMailbox.word);
-
-	H2MCmd.word 			  = 0;
-	H2MCmd.field.HostCommand  = Command;
-	RTMP_IO_WRITE32(pAd, HOST_CMD_CSR, H2MCmd.word);
-
-	if (Command != 0x80)
-	{
-	}
-
-	return TRUE;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Verify the support rate for different PHY type
-
-	Arguments:
-		pAd 				Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-VOID	RTMPCheckRates(
-	IN		PRTMP_ADAPTER	pAd,
-	IN OUT	UCHAR			SupRate[],
-	IN OUT	UCHAR			*SupRateLen)
-{
-	UCHAR	RateIdx, i, j;
-	UCHAR	NewRate[12], NewRateLen;
-
-	NewRateLen = 0;
-
-	if (pAd->CommonCfg.PhyMode == PHY_11B)
-		RateIdx = 4;
-	else
-		RateIdx = 12;
-
-	// Check for support rates exclude basic rate bit
-	for (i = 0; i < *SupRateLen; i++)
-		for (j = 0; j < RateIdx; j++)
-			if ((SupRate[i] & 0x7f) == RateIdTo500Kbps[j])
-				NewRate[NewRateLen++] = SupRate[i];
-
-	*SupRateLen = NewRateLen;
-	NdisMoveMemory(SupRate, NewRate, NewRateLen);
-}
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef DOT11_N_SUPPORT
-BOOLEAN RTMPCheckChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		CentralChannel,
-	IN UCHAR		Channel)
-{
-	UCHAR		k;
-	UCHAR		UpperChannel = 0, LowerChannel = 0;
-	UCHAR		NoEffectChannelinList = 0;
-
-	// Find upper and lower channel according to 40MHz current operation.
-	if (CentralChannel < Channel)
-	{
-		UpperChannel = Channel;
-		if (CentralChannel > 2)
-			LowerChannel = CentralChannel - 2;
-		else
-			return FALSE;
-	}
-	else if (CentralChannel > Channel)
-	{
-		UpperChannel = CentralChannel + 2;
-		LowerChannel = Channel;
-	}
-
-	for (k = 0;k < pAd->ChannelListNum;k++)
-	{
-		if (pAd->ChannelList[k].Channel == UpperChannel)
-		{
-			NoEffectChannelinList ++;
-		}
-		if (pAd->ChannelList[k].Channel == LowerChannel)
-		{
-			NoEffectChannelinList ++;
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("Total Channel in Channel List = [%d]\n", NoEffectChannelinList));
-	if (NoEffectChannelinList == 2)
-		return TRUE;
-	else
-		return FALSE;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Verify the support rate for HT phy type
-
-	Arguments:
-		pAd 				Pointer to our adapter
-
-	Return Value:
-		FALSE if pAd->CommonCfg.SupportedHtPhy doesn't accept the pHtCapability.  (AP Mode)
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-BOOLEAN 	RTMPCheckHt(
-	IN	PRTMP_ADAPTER			pAd,
-	IN	UCHAR					Wcid,
-	IN 	HT_CAPABILITY_IE		*pHtCapability,
-	IN 	ADD_HT_INFO_IE			*pAddHtInfo)
-{
-	if (Wcid >= MAX_LEN_OF_MAC_TABLE)
-		return FALSE;
-
-	// If use AMSDU, set flag.
-	if (pAd->CommonCfg.DesiredHtPhy.AmsduEnable)
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_AMSDU_INUSED);
-	// Save Peer Capability
-	if (pHtCapability->HtCapInfo.ShortGIfor20)
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_SGI20_CAPABLE);
-	if (pHtCapability->HtCapInfo.ShortGIfor40)
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_SGI40_CAPABLE);
-	if (pHtCapability->HtCapInfo.TxSTBC)
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_TxSTBC_CAPABLE);
-	if (pHtCapability->HtCapInfo.RxSTBC)
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_RxSTBC_CAPABLE);
-	if (pAd->CommonCfg.bRdg && pHtCapability->ExtHtCapInfo.RDGSupport)
-	{
-		CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[Wcid], fCLIENT_STATUS_RDG_CAPABLE);
-	}
-
-	if (Wcid < MAX_LEN_OF_MAC_TABLE)
-	{
-		pAd->MacTab.Content[Wcid].MpduDensity = pHtCapability->HtCapParm.MpduDensity;
-	}
-
-	// Will check ChannelWidth for MCSSet[4] below
-	pAd->MlmeAux.HtCapability.MCSSet[4] = 0x1;
-    switch (pAd->CommonCfg.RxStream)
-	{
-		case 1:
-			pAd->MlmeAux.HtCapability.MCSSet[0] = 0xff;
-			pAd->MlmeAux.HtCapability.MCSSet[1] = 0x00;
-            pAd->MlmeAux.HtCapability.MCSSet[2] = 0x00;
-            pAd->MlmeAux.HtCapability.MCSSet[3] = 0x00;
-			break;
-		case 2:
-			pAd->MlmeAux.HtCapability.MCSSet[0] = 0xff;
-			pAd->MlmeAux.HtCapability.MCSSet[1] = 0xff;
-            pAd->MlmeAux.HtCapability.MCSSet[2] = 0x00;
-            pAd->MlmeAux.HtCapability.MCSSet[3] = 0x00;
-			break;
-		case 3:
-			pAd->MlmeAux.HtCapability.MCSSet[0] = 0xff;
-			pAd->MlmeAux.HtCapability.MCSSet[1] = 0xff;
-            pAd->MlmeAux.HtCapability.MCSSet[2] = 0xff;
-            pAd->MlmeAux.HtCapability.MCSSet[3] = 0x00;
-			break;
-	}
-
-	pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth = pAddHtInfo->AddHtInfo.RecomWidth & pAd->CommonCfg.DesiredHtPhy.ChannelWidth;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("RTMPCheckHt:: HtCapInfo.ChannelWidth=%d, RecomWidth=%d, DesiredHtPhy.ChannelWidth=%d, BW40MAvailForA/G=%d/%d, PhyMode=%d \n",
-		pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth, pAddHtInfo->AddHtInfo.RecomWidth, pAd->CommonCfg.DesiredHtPhy.ChannelWidth,
-		pAd->NicConfig2.field.BW40MAvailForA, pAd->NicConfig2.field.BW40MAvailForG, pAd->CommonCfg.PhyMode));
-
-	pAd->MlmeAux.HtCapability.HtCapInfo.GF =  pHtCapability->HtCapInfo.GF &pAd->CommonCfg.DesiredHtPhy.GF;
-
-	// Send Assoc Req with my HT capability.
-	pAd->MlmeAux.HtCapability.HtCapInfo.AMsduSize =  pAd->CommonCfg.DesiredHtPhy.AmsduSize;
-	pAd->MlmeAux.HtCapability.HtCapInfo.MimoPs =  pAd->CommonCfg.DesiredHtPhy.MimoPs;
-	pAd->MlmeAux.HtCapability.HtCapInfo.ShortGIfor20 =  (pAd->CommonCfg.DesiredHtPhy.ShortGIfor20) & (pHtCapability->HtCapInfo.ShortGIfor20);
-	pAd->MlmeAux.HtCapability.HtCapInfo.ShortGIfor40 =  (pAd->CommonCfg.DesiredHtPhy.ShortGIfor40) & (pHtCapability->HtCapInfo.ShortGIfor40);
-	pAd->MlmeAux.HtCapability.HtCapInfo.TxSTBC =  (pAd->CommonCfg.DesiredHtPhy.TxSTBC)&(pHtCapability->HtCapInfo.RxSTBC);
-	pAd->MlmeAux.HtCapability.HtCapInfo.RxSTBC =  (pAd->CommonCfg.DesiredHtPhy.RxSTBC)&(pHtCapability->HtCapInfo.TxSTBC);
-	pAd->MlmeAux.HtCapability.HtCapParm.MaxRAmpduFactor = pAd->CommonCfg.DesiredHtPhy.MaxRAmpduFactor;
-    pAd->MlmeAux.HtCapability.HtCapParm.MpduDensity = pAd->CommonCfg.HtCapability.HtCapParm.MpduDensity;
-	pAd->MlmeAux.HtCapability.ExtHtCapInfo.PlusHTC = pHtCapability->ExtHtCapInfo.PlusHTC;
-	pAd->MacTab.Content[Wcid].HTCapability.ExtHtCapInfo.PlusHTC = pHtCapability->ExtHtCapInfo.PlusHTC;
-	if (pAd->CommonCfg.bRdg)
-	{
-		pAd->MlmeAux.HtCapability.ExtHtCapInfo.RDGSupport = pHtCapability->ExtHtCapInfo.RDGSupport;
-        pAd->MlmeAux.HtCapability.ExtHtCapInfo.PlusHTC = 1;
-	}
-
-    if (pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth == BW_20)
-        pAd->MlmeAux.HtCapability.MCSSet[4] = 0x0;  // BW20 can't transmit MCS32
-
-	COPY_AP_HTSETTINGS_FROM_BEACON(pAd, pHtCapability);
-	return TRUE;
-}
-#endif // DOT11_N_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-/*
-	========================================================================
-
-	Routine Description:
-		Verify the support rate for different PHY type
-
-	Arguments:
-		pAd 				Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-VOID RTMPUpdateMlmeRate(
-	IN PRTMP_ADAPTER	pAd)
-{
-	UCHAR	MinimumRate;
-	UCHAR	ProperMlmeRate; //= RATE_54;
-	UCHAR	i, j, RateIdx = 12; //1, 2, 5.5, 11, 6, 9, 12, 18, 24, 36, 48, 54
-	BOOLEAN	bMatch = FALSE;
-
-	switch (pAd->CommonCfg.PhyMode)
-	{
-		case PHY_11B:
-			ProperMlmeRate = RATE_11;
-			MinimumRate = RATE_1;
-			break;
-		case PHY_11BG_MIXED:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11ABGN_MIXED:
-		case PHY_11BGN_MIXED:
-#endif // DOT11_N_SUPPORT //
-			if ((pAd->MlmeAux.SupRateLen == 4) &&
-				(pAd->MlmeAux.ExtRateLen == 0))
-				// B only AP
-				ProperMlmeRate = RATE_11;
-			else
-				ProperMlmeRate = RATE_24;
-
-			if (pAd->MlmeAux.Channel <= 14)
-				MinimumRate = RATE_1;
-			else
-				MinimumRate = RATE_6;
-			break;
-		case PHY_11A:
-#ifdef DOT11_N_SUPPORT
-		case PHY_11N_2_4G:	// rt2860 need to check mlmerate for 802.11n
-		case PHY_11GN_MIXED:
-		case PHY_11AGN_MIXED:
-		case PHY_11AN_MIXED:
-		case PHY_11N_5G:
-#endif // DOT11_N_SUPPORT //
-			ProperMlmeRate = RATE_24;
-			MinimumRate = RATE_6;
-			break;
-		case PHY_11ABG_MIXED:
-			ProperMlmeRate = RATE_24;
-			if (pAd->MlmeAux.Channel <= 14)
-			   MinimumRate = RATE_1;
-			else
-				MinimumRate = RATE_6;
-			break;
-		default: // error
-			ProperMlmeRate = RATE_1;
-			MinimumRate = RATE_1;
-			break;
-	}
-
-	for (i = 0; i < pAd->MlmeAux.SupRateLen; i++)
-	{
-		for (j = 0; j < RateIdx; j++)
-		{
-			if ((pAd->MlmeAux.SupRate[i] & 0x7f) == RateIdTo500Kbps[j])
-			{
-				if (j == ProperMlmeRate)
-				{
-					bMatch = TRUE;
-					break;
-				}
-			}
-		}
-
-		if (bMatch)
-			break;
-	}
-
-	if (bMatch == FALSE)
-	{
-		for (i = 0; i < pAd->MlmeAux.ExtRateLen; i++)
-		{
-			for (j = 0; j < RateIdx; j++)
-			{
-				if ((pAd->MlmeAux.ExtRate[i] & 0x7f) == RateIdTo500Kbps[j])
-				{
-					if (j == ProperMlmeRate)
-					{
-						bMatch = TRUE;
-						break;
-					}
-				}
-			}
-
-			if (bMatch)
-				break;
-		}
-	}
-
-	if (bMatch == FALSE)
-	{
-		ProperMlmeRate = MinimumRate;
-	}
-
-	pAd->CommonCfg.MlmeRate = MinimumRate;
-	pAd->CommonCfg.RtsRate = ProperMlmeRate;
-	if (pAd->CommonCfg.MlmeRate >= RATE_6)
-	{
-		pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-		pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MODE = MODE_OFDM;
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-	}
-	else
-	{
-		pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_CCK;
-		pAd->CommonCfg.MlmeTransmit.field.MCS = pAd->CommonCfg.MlmeRate;
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MODE = MODE_CCK;
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MCS = pAd->CommonCfg.MlmeRate;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPUpdateMlmeRate ==>   MlmeTransmit = 0x%x  \n" , pAd->CommonCfg.MlmeTransmit.word));
-}
-
-CHAR RTMPMaxRssi(
-	IN PRTMP_ADAPTER	pAd,
-	IN CHAR				Rssi0,
-	IN CHAR				Rssi1,
-	IN CHAR				Rssi2)
-{
-	CHAR	larger = -127;
-
-	if ((pAd->Antenna.field.RxPath == 1) && (Rssi0 != 0))
-	{
-		larger = Rssi0;
-	}
-
-	if ((pAd->Antenna.field.RxPath >= 2) && (Rssi1 != 0))
-	{
-		larger = max(Rssi0, Rssi1);
-	}
-
-	if ((pAd->Antenna.field.RxPath == 3) && (Rssi2 != 0))
-	{
-		larger = max(larger, Rssi2);
-	}
-
-	if (larger == -127)
-		larger = 0;
-
-	return larger;
-}
-
-
-// Antenna divesity use GPIO3 and EESK pin for control
-// Antenna and EEPROM access are both using EESK pin,
-// Therefor we should avoid accessing EESK at the same time
-// Then restore antenna after EEPROM access
-VOID AsicSetRxAnt(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			Ant)
-{
-#ifdef RT30xx
-	UINT32	Value;
-	UINT32	x;
-
-	if ((pAd->EepromAccess)										||
-		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS))	||
-		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS))	||
-		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))			||
-		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-	{
-		return;
-	}
-
-	// the antenna selection is through firmware and MAC register(GPIO3)
-	if (Ant == 0)
-	{
-		// Main antenna
-		RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-		x |= (EESK);
-		RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-		RTMP_IO_READ32(pAd, GPIO_CTRL_CFG, &Value);
-		Value &= ~(0x0808);
-		RTMP_IO_WRITE32(pAd, GPIO_CTRL_CFG, Value);
-		DBGPRINT_RAW(RT_DEBUG_TRACE, ("AsicSetRxAnt, switch to main antenna\n"));
-	}
-	else
-	{
-		// Aux antenna
-		RTMP_IO_READ32(pAd, E2PROM_CSR, &x);
-		x &= ~(EESK);
-		RTMP_IO_WRITE32(pAd, E2PROM_CSR, x);
-
-		RTMP_IO_READ32(pAd, GPIO_CTRL_CFG, &Value);
-		Value &= ~(0x0808);
-		Value |= 0x08;
-		RTMP_IO_WRITE32(pAd, GPIO_CTRL_CFG, Value);
-		DBGPRINT_RAW(RT_DEBUG_TRACE, ("AsicSetRxAnt, switch to aux antenna\n"));
-	}
-#endif // RT30xx //
-}
-
-
-/*
-    ========================================================================
-    Routine Description:
-        Periodic evaluate antenna link status
-
-    Arguments:
-        pAd         - Adapter pointer
-
-    Return Value:
-        None
-
-    ========================================================================
-*/
-VOID AsicEvaluateRxAnt(
-	IN PRTMP_ADAPTER	pAd)
-{
-	UCHAR	BBPR3 = 0;
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS	|
-							fRTMP_ADAPTER_HALT_IN_PROGRESS	|
-							fRTMP_ADAPTER_RADIO_OFF			|
-							fRTMP_ADAPTER_NIC_NOT_EXIST		|
-							fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS) ||
-							OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE)
-#ifdef RT30xx
-							|| (pAd->EepromAccess)
-#endif // RT30xx //
-							)
-		return;
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		//if (pAd->StaCfg.Psm == PWR_SAVE)
-		//	return;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// two antenna selection mechanism- one is antenna diversity, the other is failed antenna remove
-	// one is antenna diversity:there is only one antenna can rx and tx
-	// the other is failed antenna remove:two physical antenna can rx and tx
-	if (pAd->NicConfig2.field.AntDiversity)
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("AntDiv - before evaluate Pair1-Ant (%d,%d)\n",
-			pAd->RxAnt.Pair1PrimaryRxAnt, pAd->RxAnt.Pair1SecondaryRxAnt));
-
-		AsicSetRxAnt(pAd, pAd->RxAnt.Pair1SecondaryRxAnt);
-
-		pAd->RxAnt.EvaluatePeriod = 1; // 1:Means switch to SecondaryRxAnt, 0:Means switch to Pair1PrimaryRxAnt
-		pAd->RxAnt.FirstPktArrivedWhenEvaluate = FALSE;
-		pAd->RxAnt.RcvPktNumWhenEvaluate = 0;
-
-		// a one-shot timer to end the evalution
-		// dynamic adjust antenna evaluation period according to the traffic
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-			RTMPSetTimer(&pAd->Mlme.RxAntEvalTimer, 100);
-		else
-			RTMPSetTimer(&pAd->Mlme.RxAntEvalTimer, 300);
-	}
-	else
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		if (pAd->StaCfg.Psm == PWR_SAVE)
-			return;
-#endif // CONFIG_STA_SUPPORT //
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPR3);
-		BBPR3 &= (~0x18);
-		if(pAd->Antenna.field.RxPath == 3)
-		{
-			BBPR3 |= (0x10);
-		}
-		else if(pAd->Antenna.field.RxPath == 2)
-		{
-			BBPR3 |= (0x8);
-		}
-		else if(pAd->Antenna.field.RxPath == 1)
-		{
-			BBPR3 |= (0x0);
-		}
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPR3);
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)
-			)
-		{
-			ULONG	TxTotalCnt = pAd->RalinkCounters.OneSecTxNoRetryOkCount +
-									pAd->RalinkCounters.OneSecTxRetryOkCount +
-									pAd->RalinkCounters.OneSecTxFailCount;
-
-			// dynamic adjust antenna evaluation period according to the traffic
-			if (TxTotalCnt > 50)
-			{
-				RTMPSetTimer(&pAd->Mlme.RxAntEvalTimer, 20);
-				pAd->Mlme.bLowThroughput = FALSE;
-			}
-			else
-			{
-				RTMPSetTimer(&pAd->Mlme.RxAntEvalTimer, 300);
-				pAd->Mlme.bLowThroughput = TRUE;
-			}
-		}
-	}
-}
-
-/*
-    ========================================================================
-    Routine Description:
-        After evaluation, check antenna link status
-
-    Arguments:
-        pAd         - Adapter pointer
-
-    Return Value:
-        None
-
-    ========================================================================
-*/
-VOID AsicRxAntEvalTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER	*pAd = (RTMP_ADAPTER *)FunctionContext;
-#ifdef CONFIG_STA_SUPPORT
-	UCHAR			BBPR3 = 0;
-	CHAR			larger = -127, rssi0, rssi1, rssi2;
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS	|
-							fRTMP_ADAPTER_HALT_IN_PROGRESS	|
-							fRTMP_ADAPTER_RADIO_OFF			|
-							fRTMP_ADAPTER_NIC_NOT_EXIST) ||
-							OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE)
-#ifdef RT30xx
-							|| (pAd->EepromAccess)
-#endif // RT30xx //
-							)
-		return;
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		//if (pAd->StaCfg.Psm == PWR_SAVE)
-		//	return;
-
-		if (pAd->NicConfig2.field.AntDiversity)
-		{
-			if ((pAd->RxAnt.RcvPktNumWhenEvaluate != 0) && (pAd->RxAnt.Pair1AvgRssi[pAd->RxAnt.Pair1SecondaryRxAnt] >= pAd->RxAnt.Pair1AvgRssi[pAd->RxAnt.Pair1PrimaryRxAnt]))
-			{
-				UCHAR			temp;
-
-				//
-				// select PrimaryRxAntPair
-				//    Role change, Used Pair1SecondaryRxAnt as PrimaryRxAntPair.
-				//    Since Pair1SecondaryRxAnt Quality good than Pair1PrimaryRxAnt
-				//
-				temp = pAd->RxAnt.Pair1PrimaryRxAnt;
-				pAd->RxAnt.Pair1PrimaryRxAnt = pAd->RxAnt.Pair1SecondaryRxAnt;
-				pAd->RxAnt.Pair1SecondaryRxAnt = temp;
-
-				pAd->RxAnt.Pair1LastAvgRssi = (pAd->RxAnt.Pair1AvgRssi[pAd->RxAnt.Pair1SecondaryRxAnt] >> 3);
-				pAd->RxAnt.EvaluateStableCnt = 0;
-			}
-			else
-			{
-				// if the evaluated antenna is not better than original, switch back to original antenna
-				AsicSetRxAnt(pAd, pAd->RxAnt.Pair1PrimaryRxAnt);
-				pAd->RxAnt.EvaluateStableCnt ++;
-			}
-
-			pAd->RxAnt.EvaluatePeriod = 0; // 1:Means switch to SecondaryRxAnt, 0:Means switch to Pair1PrimaryRxAnt
-
-			DBGPRINT(RT_DEBUG_TRACE,("AsicRxAntEvalAction::After Eval(fix in #%d), <%d, %d>, RcvPktNumWhenEvaluate=%ld\n",
-					pAd->RxAnt.Pair1PrimaryRxAnt, (pAd->RxAnt.Pair1AvgRssi[0] >> 3), (pAd->RxAnt.Pair1AvgRssi[1] >> 3), pAd->RxAnt.RcvPktNumWhenEvaluate));
-		}
-		else
-		{
-			if (pAd->StaCfg.Psm == PWR_SAVE)
-				return;
-
-			// if the traffic is low, use average rssi as the criteria
-			if (pAd->Mlme.bLowThroughput == TRUE)
-			{
-				rssi0 = pAd->StaCfg.RssiSample.LastRssi0;
-				rssi1 = pAd->StaCfg.RssiSample.LastRssi1;
-				rssi2 = pAd->StaCfg.RssiSample.LastRssi2;
-			}
-			else
-			{
-				rssi0 = pAd->StaCfg.RssiSample.AvgRssi0;
-				rssi1 = pAd->StaCfg.RssiSample.AvgRssi1;
-				rssi2 = pAd->StaCfg.RssiSample.AvgRssi2;
-			}
-
-			if(pAd->Antenna.field.RxPath == 3)
-			{
-				larger = max(rssi0, rssi1);
-
-				if (larger > (rssi2 + 20))
-					pAd->Mlme.RealRxPath = 2;
-				else
-					pAd->Mlme.RealRxPath = 3;
-			}
-			else if(pAd->Antenna.field.RxPath == 2)
-			{
-				if (rssi0 > (rssi1 + 20))
-					pAd->Mlme.RealRxPath = 1;
-				else
-					pAd->Mlme.RealRxPath = 2;
-			}
-
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPR3);
-			BBPR3 &= (~0x18);
-			if(pAd->Mlme.RealRxPath == 3)
-			{
-				BBPR3 |= (0x10);
-			}
-			else if(pAd->Mlme.RealRxPath == 2)
-			{
-				BBPR3 |= (0x8);
-			}
-			else if(pAd->Mlme.RealRxPath == 1)
-			{
-				BBPR3 |= (0x0);
-			}
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPR3);
-		}
-	}
-
-#endif // CONFIG_STA_SUPPORT //
-
-}
-
-
-
-VOID APSDPeriodicExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-		return;
-
-	pAd->CommonCfg.TriggerTimerCount++;
-
-// Driver should not send trigger frame, it should be send by application layer
-/*
-	if (pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable
-		&& (pAd->CommonCfg.bNeedSendTriggerFrame ||
-		(((pAd->CommonCfg.TriggerTimerCount%20) == 19) && (!pAd->CommonCfg.bAPSDAC_BE || !pAd->CommonCfg.bAPSDAC_BK || !pAd->CommonCfg.bAPSDAC_VI || !pAd->CommonCfg.bAPSDAC_VO))))
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("Sending trigger frame and enter service period when support APSD\n"));
-		RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, TRUE);
-		pAd->CommonCfg.bNeedSendTriggerFrame = FALSE;
-		pAd->CommonCfg.TriggerTimerCount = 0;
-		pAd->CommonCfg.bInServicePeriod = TRUE;
-	}*/
-}
-
-/*
-    ========================================================================
-    Routine Description:
-        Set/reset MAC registers according to bPiggyBack parameter
-
-    Arguments:
-        pAd         - Adapter pointer
-        bPiggyBack  - Enable / Disable Piggy-Back
-
-    Return Value:
-        None
-
-    ========================================================================
-*/
-VOID RTMPSetPiggyBack(
-    IN PRTMP_ADAPTER    pAd,
-    IN BOOLEAN          bPiggyBack)
-{
-	TX_LINK_CFG_STRUC  TxLinkCfg;
-
-	RTMP_IO_READ32(pAd, TX_LINK_CFG, &TxLinkCfg.word);
-
-	TxLinkCfg.field.TxCFAckEn = bPiggyBack;
-	RTMP_IO_WRITE32(pAd, TX_LINK_CFG, TxLinkCfg.word);
-}
-
-/*
-    ========================================================================
-    Routine Description:
-        check if this entry need to switch rate automatically
-
-    Arguments:
-        pAd
-        pEntry
-
-    Return Value:
-        TURE
-        FALSE
-
-    ========================================================================
-*/
-BOOLEAN RTMPCheckEntryEnableAutoRateSwitch(
-	IN PRTMP_ADAPTER    pAd,
-	IN PMAC_TABLE_ENTRY	pEntry)
-{
-	BOOLEAN		result = TRUE;
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// only associated STA counts
-		if (pEntry && (pEntry->ValidAsCLI) && (pEntry->Sst == SST_ASSOC))
-		{
-			result = pAd->StaCfg.bAutoTxRateSwitch;
-		}
-		else
-			result = FALSE;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-	return result;
-}
-
-
-BOOLEAN RTMPAutoRateSwitchCheck(
-	IN PRTMP_ADAPTER    pAd)
-{
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pAd->StaCfg.bAutoTxRateSwitch)
-			return TRUE;
-	}
-#endif // CONFIG_STA_SUPPORT //
-	return FALSE;
-}
-
-
-/*
-    ========================================================================
-    Routine Description:
-        check if this entry need to fix tx legacy rate
-
-    Arguments:
-        pAd
-        pEntry
-
-    Return Value:
-        TURE
-        FALSE
-
-    ========================================================================
-*/
-UCHAR RTMPStaFixedTxMode(
-	IN PRTMP_ADAPTER    pAd,
-	IN PMAC_TABLE_ENTRY	pEntry)
-{
-	UCHAR	tx_mode = FIXED_TXMODE_HT;
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		tx_mode = (UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	return tx_mode;
-}
-
-/*
-    ========================================================================
-    Routine Description:
-        Overwrite HT Tx Mode by Fixed Legency Tx Mode, if specified.
-
-    Arguments:
-        pAd
-        pEntry
-
-    Return Value:
-        TURE
-        FALSE
-
-    ========================================================================
-*/
-VOID RTMPUpdateLegacyTxSetting(
-		UCHAR				fixed_tx_mode,
-		PMAC_TABLE_ENTRY	pEntry)
-{
-	HTTRANSMIT_SETTING TransmitSetting;
-
-	if (fixed_tx_mode == FIXED_TXMODE_HT)
-		return;
-
-	TransmitSetting.word = 0;
-
-	TransmitSetting.field.MODE = pEntry->HTPhyMode.field.MODE;
-	TransmitSetting.field.MCS = pEntry->HTPhyMode.field.MCS;
-
-	if (fixed_tx_mode == FIXED_TXMODE_CCK)
-	{
-		TransmitSetting.field.MODE = MODE_CCK;
-		// CCK mode allow MCS 0~3
-		if (TransmitSetting.field.MCS > MCS_3)
-			TransmitSetting.field.MCS = MCS_3;
-	}
-	else
-	{
-		TransmitSetting.field.MODE = MODE_OFDM;
-		// OFDM mode allow MCS 0~7
-		if (TransmitSetting.field.MCS > MCS_7)
-			TransmitSetting.field.MCS = MCS_7;
-	}
-
-	if (pEntry->HTPhyMode.field.MODE >= TransmitSetting.field.MODE)
-	{
-		pEntry->HTPhyMode.word = TransmitSetting.word;
-		DBGPRINT(RT_DEBUG_TRACE, ("RTMPUpdateLegacyTxSetting : wcid-%d, MODE=%s, MCS=%d \n",
-				pEntry->Aid, GetPhyMode(pEntry->HTPhyMode.field.MODE), pEntry->HTPhyMode.field.MCS));
-	}
-}
-
-#ifdef CONFIG_STA_SUPPORT
-/*
-	==========================================================================
-	Description:
-		dynamic tune BBP R66 to find a balance between sensibility and
-		noise isolation
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AsicStaBbpTuning(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR	OrigR66Value = 0, R66;//, R66UpperBound = 0x30, R66LowerBound = 0x30;
-	CHAR	Rssi;
-
-	// 2860C did not support Fase CCA, therefore can't tune
-	if (pAd->MACVersion == 0x28600100)
-		return;
-
-	//
-	// work as a STA
-	//
-	if (pAd->Mlme.CntlMachine.CurrState != CNTL_IDLE)  // no R66 tuning when SCANNING
-		return;
-
-	if ((pAd->OpMode == OPMODE_STA)
-		&& (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)
-			)
-		&& !(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-		)
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &OrigR66Value);
-		R66 = OrigR66Value;
-
-		if (pAd->Antenna.field.RxPath > 1)
-			Rssi = (pAd->StaCfg.RssiSample.AvgRssi0 + pAd->StaCfg.RssiSample.AvgRssi1) >> 1;
-		else
-			Rssi = pAd->StaCfg.RssiSample.AvgRssi0;
-
-		if (pAd->LatchRfRegs.Channel <= 14)
-		{	//BG band
-#ifdef RT30xx
-			// RT3070 is a no LNA solution, it should have different control regarding to AGC gain control
-			// Otherwise, it will have some throughput side effect when low RSSI
-			if (IS_RT30xx(pAd))
-			{
-				if (Rssi > RSSI_FOR_MID_LOW_SENSIBILITY)
-				{
-					R66 = 0x1C + 2*GET_LNA_GAIN(pAd) + 0x20;
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-				else
-				{
-					R66 = 0x1C + 2*GET_LNA_GAIN(pAd);
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-			}
-			else
-#endif // RT30xx //
-			{
-				if (Rssi > RSSI_FOR_MID_LOW_SENSIBILITY)
-				{
-					R66 = (0x2E + GET_LNA_GAIN(pAd)) + 0x10;
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-				else
-				{
-					R66 = 0x2E + GET_LNA_GAIN(pAd);
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-			}
-
-		}
-		else
-		{	//A band
-			if (pAd->CommonCfg.BBPCurrentBW == BW_20)
-			{
-				if (Rssi > RSSI_FOR_MID_LOW_SENSIBILITY)
-				{
-					R66 = 0x32 + (GET_LNA_GAIN(pAd)*5)/3 + 0x10;
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-				else
-				{
-					R66 = 0x32 + (GET_LNA_GAIN(pAd)*5)/3;
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-			}
-			else
-			{
-				if (Rssi > RSSI_FOR_MID_LOW_SENSIBILITY)
-				{
-					R66 = 0x3A + (GET_LNA_GAIN(pAd)*5)/3 + 0x10;
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-				else
-				{
-					R66 = 0x3A + (GET_LNA_GAIN(pAd)*5)/3;
-					if (OrigR66Value != R66)
-					{
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-					}
-				}
-			}
-		}
-
-
-	}
-}
-#endif // CONFIG_STA_SUPPORT //
-
-VOID RTMPSetAGCInitValue(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			BandWidth)
-{
-	UCHAR	R66 = 0x30;
-
-	if (pAd->LatchRfRegs.Channel <= 14)
-	{	// BG band
-		R66 = 0x2E + GET_LNA_GAIN(pAd);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-	}
-	else
-	{	//A band
-		if (BandWidth == BW_20)
-		{
-			R66 = (UCHAR)(0x32 + (GET_LNA_GAIN(pAd)*5)/3);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-		}
-#ifdef DOT11_N_SUPPORT
-		else
-		{
-			R66 = (UCHAR)(0x3A + (GET_LNA_GAIN(pAd)*5)/3);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-		}
-#endif // DOT11_N_SUPPORT //
-	}
-
-}
-
-VOID AsicTurnOffRFClk(
-	IN PRTMP_ADAPTER pAd,
-	IN	UCHAR		Channel)
-{
-	// RF R2 bit 18 = 0
-	UINT32			R1 = 0, R2 = 0, R3 = 0;
-	UCHAR			index;
-	RTMP_RF_REGS	*RFRegTable;
-
-#ifdef RT30xx
-	// The RF programming sequence is difference between 3xxx and 2xxx
-	if (IS_RT3090(pAd))
-	{
-		RT30xxLoadRFSleepModeSetup(pAd);  // add by johnli,  RF power sequence setup, load RF sleep-mode setup
-	}
-	else
-	{
-#endif // RT30xx //
-	RFRegTable = RF2850RegTable;
-
-	switch (pAd->RfIcType)
-	{
-		case RFIC_2820:
-		case RFIC_2850:
-		case RFIC_2720:
-		case RFIC_2750:
-
-			for (index = 0; index < NUM_OF_2850_CHNL; index++)
-			{
-				if (Channel == RFRegTable[index].Channel)
-				{
-					R1 = RFRegTable[index].R1 & 0xffffdfff;
-					R2 = RFRegTable[index].R2 & 0xfffbffff;
-					R3 = RFRegTable[index].R3 & 0xfff3ffff;
-
-					RTMP_RF_IO_WRITE32(pAd, R1);
-					RTMP_RF_IO_WRITE32(pAd, R2);
-
-					// Program R1b13 to 1, R3/b18,19 to 0, R2b18 to 0.
-					// Set RF R2 bit18=0, R3 bit[18:19]=0
-					//if (pAd->StaCfg.bRadio == FALSE)
-					if (1)
-					{
-						RTMP_RF_IO_WRITE32(pAd, R3);
-
-						DBGPRINT(RT_DEBUG_TRACE, ("AsicTurnOffRFClk#%d(RF=%d, ) , R2=0x%08x,  R3 = 0x%08x \n",
-							Channel, pAd->RfIcType, R2, R3));
-					}
-					else
-						DBGPRINT(RT_DEBUG_TRACE, ("AsicTurnOffRFClk#%d(RF=%d, ) , R2=0x%08x \n",
-							Channel, pAd->RfIcType, R2));
-					break;
-				}
-			}
-			break;
-
-		default:
-			break;
-	}
-#ifdef RT30xx
-	}
-#endif // RT30xx //
-
-}
-
-
-VOID AsicTurnOnRFClk(
-	IN PRTMP_ADAPTER pAd,
-	IN	UCHAR			Channel)
-{
-	// RF R2 bit 18 = 0
-	UINT32			R1 = 0, R2 = 0, R3 = 0;
-	UCHAR			index;
-	RTMP_RF_REGS	*RFRegTable;
-
-#ifdef RT30xx
-	// The RF programming sequence is difference between 3xxx and 2xxx
-	if (IS_RT3090(pAd))
-	{
-	}
-	else
-	{
-#endif // RT30xx //
-	RFRegTable = RF2850RegTable;
-
-	switch (pAd->RfIcType)
-	{
-		case RFIC_2820:
-		case RFIC_2850:
-		case RFIC_2720:
-		case RFIC_2750:
-
-			for (index = 0; index < NUM_OF_2850_CHNL; index++)
-			{
-				if (Channel == RFRegTable[index].Channel)
-				{
-					R3 = pAd->LatchRfRegs.R3;
-					R3 &= 0xfff3ffff;
-					R3 |= 0x00080000;
-					RTMP_RF_IO_WRITE32(pAd, R3);
-
-					R1 = RFRegTable[index].R1;
-					RTMP_RF_IO_WRITE32(pAd, R1);
-
-					R2 = RFRegTable[index].R2;
-					if (pAd->Antenna.field.TxPath == 1)
-					{
-						R2 |= 0x4000;	// If TXpath is 1, bit 14 = 1;
-					}
-
-					if (pAd->Antenna.field.RxPath == 2)
-					{
-						R2 |= 0x40;	// write 1 to off Rxpath.
-					}
-					else if (pAd->Antenna.field.RxPath == 1)
-					{
-						R2 |= 0x20040;	// write 1 to off RxPath
-					}
-					RTMP_RF_IO_WRITE32(pAd, R2);
-
-					break;
-				}
-			}
-			break;
-
-		default:
-			break;
-	}
-
-#ifdef RT30xx
-	}
-#endif // RT30xx //
-
-}
-
+#include "../../rt2870/common/mlme.c"
diff --git a/drivers/staging/rt3070/common/netif_block.c b/drivers/staging/rt3070/common/netif_block.c
deleted file mode 100644
index 4773c11..0000000
--- a/drivers/staging/rt3070/common/netif_block.c
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#include "../rt_config.h"
-#include "netif_block.h"
-
-static NETIF_ENTRY freeNetIfEntryPool[FREE_NETIF_POOL_SIZE];
-static LIST_HEADER freeNetIfEntryList;
-
-void initblockQueueTab(
-	IN PRTMP_ADAPTER pAd)
-{
-	int i;
-
-	initList(&freeNetIfEntryList);
-	for (i = 0; i < FREE_NETIF_POOL_SIZE; i++)
-		insertTailList(&freeNetIfEntryList, (PLIST_ENTRY)&freeNetIfEntryPool[i]);
-
-	for (i=0; i < NUM_OF_TX_RING; i++)
-		initList(&pAd->blockQueueTab[i].NetIfList);
-
-	return;
-}
-
-BOOLEAN blockNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry,
-	IN PNET_DEV pNetDev)
-{
-	PNETIF_ENTRY pNetIfEntry = NULL;
-
-	if ((pNetIfEntry = (PNETIF_ENTRY)removeHeadList(&freeNetIfEntryList)) != NULL)
-	{
-		netif_stop_queue(pNetDev);
-		pNetIfEntry->pNetDev = pNetDev;
-		insertTailList(&pBlockQueueEntry->NetIfList, (PLIST_ENTRY)pNetIfEntry);
-
-		pBlockQueueEntry->SwTxQueueBlockFlag = TRUE;
-		DBGPRINT(RT_DEBUG_TRACE, ("netif_stop_queue(%s)\n", pNetDev->name));
-	}
-	else
-		return FALSE;
-
-	return TRUE;
-}
-
-VOID releaseNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry)
-{
-	PNETIF_ENTRY pNetIfEntry = NULL;
-	PLIST_HEADER pNetIfList = &pBlockQueueEntry->NetIfList;
-
-	while((pNetIfEntry = (PNETIF_ENTRY)removeHeadList(pNetIfList)) !=  NULL)
-	{
-		PNET_DEV pNetDev = pNetIfEntry->pNetDev;
-		netif_wake_queue(pNetDev);
-		insertTailList(&freeNetIfEntryList, (PLIST_ENTRY)pNetIfEntry);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("netif_wake_queue(%s)\n", pNetDev->name));
-	}
-	pBlockQueueEntry->SwTxQueueBlockFlag = FALSE;
-	return;
-}
-
-
-VOID StopNetIfQueue(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR QueIdx,
-	IN PNDIS_PACKET pPacket)
-{
-	PNET_DEV NetDev = NULL;
-	UCHAR IfIdx = 0;
-	BOOLEAN valid = FALSE;
-
-#ifdef WDS_SUPPORT
-	if (RTMP_GET_PACKET_NET_DEVICE(pPacket) >= MIN_NET_DEVICE_FOR_WDS)
-	{
-		IfIdx = (RTMP_GET_PACKET_NET_DEVICE(pPacket) - MIN_NET_DEVICE_FOR_WDS) % MAX_WDS_ENTRY;
-		NetDev = pAd->WdsTab.WdsEntry[IfIdx].dev;
-	}
-	else
-#endif // WDS_SUPPORT //
-	{
-#ifdef MBSS_SUPPORT
-		if (pAd->OpMode == OPMODE_AP)
-		{
-			IfIdx = (RTMP_GET_PACKET_NET_DEVICE(pPacket) - MIN_NET_DEVICE_FOR_MBSSID) % MAX_MBSSID_NUM;
-			NetDev = pAd->ApCfg.MBSSID[IfIdx].MSSIDDev;
-		}
-		else
-		{
-			IfIdx = MAIN_MBSSID;
-			NetDev = pAd->net_dev;
-		}
-#else
-		IfIdx = MAIN_MBSSID;
-		NetDev = pAd->net_dev;
-#endif
-	}
-
-	// WMM support 4 software queues.
-	// One software queue full doesn't mean device have no capbility to transmit packet.
-	// So disable block Net-If queue function while WMM enable.
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		valid = (pAd->CommonCfg.bWmmCapable == TRUE) ? FALSE : TRUE;
-#endif // CONFIG_STA_SUPPORT //
-
-	if (valid)
-		blockNetIf(&pAd->blockQueueTab[QueIdx], NetDev);
-	return;
-}
-
diff --git a/drivers/staging/rt3070/common/rtmp_init.c b/drivers/staging/rt3070/common/rtmp_init.c
index 4503f6c..4709e5f 100644
--- a/drivers/staging/rt3070/common/rtmp_init.c
+++ b/drivers/staging/rt3070/common/rtmp_init.c
@@ -1,4197 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtmp_init.c
-
-	Abstract:
-	Miniport generic portion header file
-
-	Revision History:
-	Who         When          What
-	--------    ----------    ----------------------------------------------
-	Paul Lin    2002-08-01    created
-    John Chang  2004-08-20    RT2561/2661 use scatter-gather scheme
-    Jan Lee  2006-09-15    RT2860. Change for 802.11n , EEPROM, Led, BA, HT.
-*/
-#include	"../rt_config.h"
-#include 	"../firmware.h"
-
-//#define BIN_IN_FILE /* use *.bin firmware */
-
-UCHAR    BIT8[] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
-ULONG    BIT32[] = {0x00000001, 0x00000002, 0x00000004, 0x00000008,
-					0x00000010, 0x00000020, 0x00000040, 0x00000080,
-					0x00000100, 0x00000200, 0x00000400, 0x00000800,
-					0x00001000, 0x00002000, 0x00004000, 0x00008000,
-					0x00010000, 0x00020000, 0x00040000, 0x00080000,
-					0x00100000, 0x00200000, 0x00400000, 0x00800000,
-					0x01000000, 0x02000000, 0x04000000, 0x08000000,
-					0x10000000, 0x20000000, 0x40000000, 0x80000000};
-
-char*   CipherName[] = {"none","wep64","wep128","TKIP","AES","CKIP64","CKIP128"};
-
-const unsigned short ccitt_16Table[] = {
-	0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
-	0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
-	0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
-	0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
-	0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
-	0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
-	0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
-	0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
-	0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
-	0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
-	0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
-	0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
-	0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
-	0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
-	0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
-	0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
-	0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
-	0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
-	0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
-	0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
-	0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
-	0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
-	0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
-	0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
-	0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
-	0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
-	0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
-	0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
-	0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
-	0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
-	0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
-	0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
-};
-#define ByteCRC16(v, crc) \
-	(unsigned short)((crc << 8) ^  ccitt_16Table[((crc >> 8) ^ (v)) & 255])
-
-unsigned char BitReverse(unsigned char x)
-{
-	int i;
-	unsigned char Temp=0;
-	for(i=0; ; i++)
-	{
-		if(x & 0x80)	Temp |= 0x80;
-		if(i==7)		break;
-		x	<<= 1;
-		Temp >>= 1;
-	}
-	return Temp;
-}
-
-//
-// BBP register initialization set
-//
-REG_PAIR   BBPRegTable[] = {
-	{BBP_R65,		0x2C},		// fix rssi issue
-	{BBP_R66,		0x38},	// Also set this default value to pAd->BbpTuning.R66CurrentValue at initial
-	{BBP_R69,		0x12},
-	{BBP_R70,		0xa},	// BBP_R70 will change to 0x8 in ApStartUp and LinkUp for rt2860C, otherwise value is 0xa
-	{BBP_R73,		0x10},
-	{BBP_R81,		0x37},
-	{BBP_R82,		0x62},
-	{BBP_R83,		0x6A},
-	{BBP_R84,		0x99},	// 0x19 is for rt2860E and after. This is for extension channel overlapping IOT. 0x99 is for rt2860D and before
-	{BBP_R86,		0x00},	// middle range issue, Rory @2008-01-28
-	{BBP_R91,		0x04},	// middle range issue, Rory @2008-01-28
-	{BBP_R92,		0x00},	// middle range issue, Rory @2008-01-28
-	{BBP_R103,  	0x00}, 	// near range high-power issue, requested from Gary @2008-0528
-	{BBP_R105,		0x05},	// 0x05 is for rt2860E to turn on FEQ control. It is safe for rt2860D and before, because Bit 7:2 are reserved in rt2860D and before.
-};
-#define	NUM_BBP_REG_PARMS	(sizeof(BBPRegTable) / sizeof(REG_PAIR))
-
-//
-// RF register initialization set
-//
-#ifdef RT30xx
-REG_PAIR   RT30xx_RFRegTable[] = {
-        {RF_R04,          0x40},
-        {RF_R05,          0x03},
-        {RF_R06,          0x02},
-        {RF_R07,          0x70},
-        {RF_R09,          0x0F},
-        {RF_R10,          0x41},
-        {RF_R11,          0x21},
-        {RF_R12,          0x7B},
-        {RF_R14,          0x90},
-        {RF_R15,          0x58},
-        {RF_R16,          0xB3},
-        {RF_R17,          0x92},
-        {RF_R18,          0x2C},
-        {RF_R19,          0x02},
-        {RF_R20,          0xBA},
-        {RF_R21,          0xDB},
-        {RF_R24,          0x16},
-        {RF_R25,          0x01},
-        {RF_R29,          0x1F},
-};
-#define	NUM_RF_REG_PARMS	(sizeof(RT30xx_RFRegTable) / sizeof(REG_PAIR))
-#endif // RT30xx //
-
-//
-// ASIC register initialization sets
-//
-
-RTMP_REG_PAIR	MACRegTable[] =	{
-#if defined(HW_BEACON_OFFSET) && (HW_BEACON_OFFSET == 0x200)
-	{BCN_OFFSET0,			0xf8f0e8e0}, /* 0x3800(e0), 0x3A00(e8), 0x3C00(f0), 0x3E00(f8), 512B for each beacon */
-	{BCN_OFFSET1,			0x6f77d0c8}, /* 0x3200(c8), 0x3400(d0), 0x1DC0(77), 0x1BC0(6f), 512B for each beacon */
-#elif defined(HW_BEACON_OFFSET) && (HW_BEACON_OFFSET == 0x100)
-	{BCN_OFFSET0,			0xece8e4e0}, /* 0x3800, 0x3A00, 0x3C00, 0x3E00, 512B for each beacon */
-	{BCN_OFFSET1,			0xfcf8f4f0}, /* 0x3800, 0x3A00, 0x3C00, 0x3E00, 512B for each beacon */
-#else
-    #error You must re-calculate new value for BCN_OFFSET0 & BCN_OFFSET1 in MACRegTable[]!!!
-#endif // HW_BEACON_OFFSET //
-
-	{LEGACY_BASIC_RATE,		0x0000013f}, //  Basic rate set bitmap
-	{HT_BASIC_RATE,		0x00008003}, // Basic HT rate set , 20M, MCS=3, MM. Format is the same as in TXWI.
-	{MAC_SYS_CTRL,		0x00}, // 0x1004, , default Disable RX
-	{RX_FILTR_CFG,		0x17f97}, //0x1400  , RX filter control,
-	{BKOFF_SLOT_CFG,	0x209}, // default set short slot time, CC_DELAY_TIME should be 2
-	//{TX_SW_CFG0,		0x40a06}, // Gary,2006-08-23
-	{TX_SW_CFG0,		0x0}, 		// Gary,2008-05-21 for CWC test
-	{TX_SW_CFG1,		0x80606}, // Gary,2006-08-23
-	{TX_LINK_CFG,		0x1020},		// Gary,2006-08-23
-	{TX_TIMEOUT_CFG,	0x000a2090},
-	{MAX_LEN_CFG,		MAX_AGGREGATION_SIZE | 0x00001000},	// 0x3018, MAX frame length. Max PSDU = 16kbytes.
-	{LED_CFG,		0x7f031e46}, // Gary, 2006-08-23
-
-//#ifdef CONFIG_STA_SUPPORT
-//	{WMM_AIFSN_CFG,		0x00002273},
-//	{WMM_CWMIN_CFG,		0x00002344},
-//	{WMM_CWMAX_CFG,		0x000034aa},
-//#endif // CONFIG_STA_SUPPORT //
-#ifdef INF_AMAZON_SE
-	{PBF_MAX_PCNT,			0x1F3F6F6F}, 	//iverson modify for usb issue, 2008/09/19
-											// 6F + 6F < total page count FE
-											// so that RX doesn't occupy TX's buffer space when WMM congestion.
-#else
-	{PBF_MAX_PCNT,			0x1F3FBF9F}, 	//0x1F3f7f9f},		//Jan, 2006/04/20
-#endif // INF_AMAZON_SE //
-	//{TX_RTY_CFG,			0x6bb80408},	// Jan, 2006/11/16
-	{TX_RTY_CFG,			0x47d01f0f},	// Jan, 2006/11/16, Set TxWI->ACK =0 in Probe Rsp Modify for 2860E ,2007-08-03
-	{AUTO_RSP_CFG,			0x00000013},	// Initial Auto_Responder, because QA will turn off Auto-Responder
-	{CCK_PROT_CFG,			0x05740003 /*0x01740003*/},	// Initial Auto_Responder, because QA will turn off Auto-Responder. And RTS threshold is enabled.
-	{OFDM_PROT_CFG,			0x05740003 /*0x01740003*/},	// Initial Auto_Responder, because QA will turn off Auto-Responder. And RTS threshold is enabled.
-//PS packets use Tx1Q (for HCCA) when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
-#ifdef RT2870
-#ifdef CONFIG_STA_SUPPORT
-	{PBF_CFG, 				0xf40006}, 		// Only enable Queue 2
-#endif // CONFIG_STA_SUPPORT //
-	{MM40_PROT_CFG,			0x3F44084},		// Initial Auto_Responder, because QA will turn off Auto-Responder
-	{WPDMA_GLO_CFG,			0x00000030},
-#endif // RT2870 //
-	{GF20_PROT_CFG,			0x01744004},    // set 19:18 --> Short NAV for MIMO PS
-	{GF40_PROT_CFG,			0x03F44084},
-	{MM20_PROT_CFG,			0x01744004},
-	{TXOP_CTRL_CFG,			0x0000583f, /*0x0000243f*/ /*0x000024bf*/},	//Extension channel backoff.
-	{TX_RTS_CFG,			0x00092b20},
-//#ifdef WIFI_TEST
-	{EXP_ACK_TIME,			0x002400ca},	// default value
-//#else
-//	{EXP_ACK_TIME,			0x005400ca},	// suggested by Gray @ 20070323 for 11n intel-sta throughput
-//#endif // end - WIFI_TEST //
-	{TXOP_HLDR_ET, 			0x00000002},
-
-	/* Jerry comments 2008/01/16: we use SIFS = 10us in CCK defaultly, but it seems that 10us
-		is too small for INTEL 2200bg card, so in MBSS mode, the delta time between beacon0
-		and beacon1 is SIFS (10us), so if INTEL 2200bg card connects to BSS0, the ping
-		will always lost. So we change the SIFS of CCK from 10us to 16us. */
-	{XIFS_TIME_CFG,			0x33a41010},
-	{PWR_PIN_CFG,			0x00000003},	// patch for 2880-E
-};
-
-
-#ifdef CONFIG_STA_SUPPORT
-RTMP_REG_PAIR	STAMACRegTable[] =	{
-	{WMM_AIFSN_CFG,		0x00002273},
-	{WMM_CWMIN_CFG,	0x00002344},
-	{WMM_CWMAX_CFG,	0x000034aa},
-};
-#endif // CONFIG_STA_SUPPORT //
-
-#define	NUM_MAC_REG_PARMS		(sizeof(MACRegTable) / sizeof(RTMP_REG_PAIR))
-#ifdef CONFIG_STA_SUPPORT
-#define	NUM_STA_MAC_REG_PARMS	(sizeof(STAMACRegTable) / sizeof(RTMP_REG_PAIR))
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef RT2870
-//
-// RT2870 Firmware Spec only used 1 oct for version expression
-//
-#define FIRMWARE_MINOR_VERSION	7
-
-#endif // RT2870 //
-
-// New 8k byte firmware size for RT3071/RT3072
-#define FIRMWAREIMAGE_MAX_LENGTH	0x2000
-#define FIRMWAREIMAGE_LENGTH		(sizeof (FirmwareImage) / sizeof(UCHAR))
-#define FIRMWARE_MAJOR_VERSION	0
-
-#define FIRMWAREIMAGEV1_LENGTH	0x1000
-#define FIRMWAREIMAGEV2_LENGTH	0x1000
-
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Allocate RTMP_ADAPTER data block and do some initialization
-
-	Arguments:
-		Adapter		Pointer to our adapter
-
-	Return Value:
-		NDIS_STATUS_SUCCESS
-		NDIS_STATUS_FAILURE
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS	RTMPAllocAdapterBlock(
-	IN  PVOID	handle,
-	OUT	PRTMP_ADAPTER	*ppAdapter)
-{
-	PRTMP_ADAPTER	pAd;
-	NDIS_STATUS		Status;
-	INT 			index;
-	UCHAR			*pBeaconBuf = NULL;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> RTMPAllocAdapterBlock\n"));
-
-	*ppAdapter = NULL;
-
-	do
-	{
-		// Allocate RTMP_ADAPTER memory block
-		pBeaconBuf = kmalloc(MAX_BEACON_SIZE, MEM_ALLOC_FLAG);
-		if (pBeaconBuf == NULL)
-		{
-			Status = NDIS_STATUS_FAILURE;
-			DBGPRINT_ERR(("Failed to allocate memory - BeaconBuf!\n"));
-			break;
-		}
-
-		Status = AdapterBlockAllocateMemory(handle, (PVOID *)&pAd);
-		if (Status != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT_ERR(("Failed to allocate memory - ADAPTER\n"));
-			break;
-		}
-		pAd->BeaconBuf = pBeaconBuf;
-		printk("\n\n=== pAd = %p, size = %d ===\n\n", pAd, (UINT32)sizeof(RTMP_ADAPTER));
-
-
-		// Init spin locks
-		NdisAllocateSpinLock(&pAd->MgmtRingLock);
-
-		for (index =0 ; index < NUM_OF_TX_RING; index++)
-		{
-			NdisAllocateSpinLock(&pAd->TxSwQueueLock[index]);
-			NdisAllocateSpinLock(&pAd->DeQueueLock[index]);
-			pAd->DeQueueRunning[index] = FALSE;
-		}
-
-		NdisAllocateSpinLock(&pAd->irq_lock);
-
-	} while (FALSE);
-
-	if ((Status != NDIS_STATUS_SUCCESS) && (pBeaconBuf))
-		kfree(pBeaconBuf);
-
-	*ppAdapter = pAd;
-
-	DBGPRINT_S(Status, ("<-- RTMPAllocAdapterBlock, Status=%x\n", Status));
-	return Status;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Read initial Tx power per MCS and BW from EEPROM
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPReadTxPwrPerRate(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	ULONG		data, Adata, Gdata;
-	USHORT		i, value, value2;
-	INT			Apwrdelta, Gpwrdelta;
-	UCHAR		t1,t2,t3,t4;
-	BOOLEAN		bValid, bApwrdeltaMinus = TRUE, bGpwrdeltaMinus = TRUE;
-
-	//
-	// Get power delta for 20MHz and 40MHz.
-	//
-	DBGPRINT(RT_DEBUG_TRACE, ("Txpower per Rate\n"));
-	RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_DELTA, value2);
-	Apwrdelta = 0;
-	Gpwrdelta = 0;
-
-	if ((value2 & 0xff) != 0xff)
-	{
-		if ((value2 & 0x80))
-			Gpwrdelta = (value2&0xf);
-
-		if ((value2 & 0x40))
-			bGpwrdeltaMinus = FALSE;
-		else
-			bGpwrdeltaMinus = TRUE;
-	}
-	if ((value2 & 0xff00) != 0xff00)
-	{
-		if ((value2 & 0x8000))
-			Apwrdelta = ((value2&0xf00)>>8);
-
-		if ((value2 & 0x4000))
-			bApwrdeltaMinus = FALSE;
-		else
-			bApwrdeltaMinus = TRUE;
-	}
-	DBGPRINT(RT_DEBUG_TRACE, ("Gpwrdelta = %x, Apwrdelta = %x .\n", Gpwrdelta, Apwrdelta));
-
-	//
-	// Get Txpower per MCS for 20MHz in 2.4G.
-	//
-	for (i=0; i<5; i++)
-	{
-		RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_20MHZ_2_4G + i*4, value);
-		data = value;
-		if (bApwrdeltaMinus == FALSE)
-		{
-			t1 = (value&0xf)+(Apwrdelta);
-			if (t1 > 0xf)
-				t1 = 0xf;
-			t2 = ((value&0xf0)>>4)+(Apwrdelta);
-			if (t2 > 0xf)
-				t2 = 0xf;
-			t3 = ((value&0xf00)>>8)+(Apwrdelta);
-			if (t3 > 0xf)
-				t3 = 0xf;
-			t4 = ((value&0xf000)>>12)+(Apwrdelta);
-			if (t4 > 0xf)
-				t4 = 0xf;
-		}
-		else
-		{
-			if ((value&0xf) > Apwrdelta)
-				t1 = (value&0xf)-(Apwrdelta);
-			else
-				t1 = 0;
-			if (((value&0xf0)>>4) > Apwrdelta)
-				t2 = ((value&0xf0)>>4)-(Apwrdelta);
-			else
-				t2 = 0;
-			if (((value&0xf00)>>8) > Apwrdelta)
-				t3 = ((value&0xf00)>>8)-(Apwrdelta);
-			else
-				t3 = 0;
-			if (((value&0xf000)>>12) > Apwrdelta)
-				t4 = ((value&0xf000)>>12)-(Apwrdelta);
-			else
-				t4 = 0;
-		}
-		Adata = t1 + (t2<<4) + (t3<<8) + (t4<<12);
-		if (bGpwrdeltaMinus == FALSE)
-		{
-			t1 = (value&0xf)+(Gpwrdelta);
-			if (t1 > 0xf)
-				t1 = 0xf;
-			t2 = ((value&0xf0)>>4)+(Gpwrdelta);
-			if (t2 > 0xf)
-				t2 = 0xf;
-			t3 = ((value&0xf00)>>8)+(Gpwrdelta);
-			if (t3 > 0xf)
-				t3 = 0xf;
-			t4 = ((value&0xf000)>>12)+(Gpwrdelta);
-			if (t4 > 0xf)
-				t4 = 0xf;
-		}
-		else
-		{
-			if ((value&0xf) > Gpwrdelta)
-				t1 = (value&0xf)-(Gpwrdelta);
-			else
-				t1 = 0;
-			if (((value&0xf0)>>4) > Gpwrdelta)
-				t2 = ((value&0xf0)>>4)-(Gpwrdelta);
-			else
-				t2 = 0;
-			if (((value&0xf00)>>8) > Gpwrdelta)
-				t3 = ((value&0xf00)>>8)-(Gpwrdelta);
-			else
-				t3 = 0;
-			if (((value&0xf000)>>12) > Gpwrdelta)
-				t4 = ((value&0xf000)>>12)-(Gpwrdelta);
-			else
-				t4 = 0;
-		}
-		Gdata = t1 + (t2<<4) + (t3<<8) + (t4<<12);
-
-		RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_20MHZ_2_4G + i*4 + 2, value);
-		if (bApwrdeltaMinus == FALSE)
-		{
-			t1 = (value&0xf)+(Apwrdelta);
-			if (t1 > 0xf)
-				t1 = 0xf;
-			t2 = ((value&0xf0)>>4)+(Apwrdelta);
-			if (t2 > 0xf)
-				t2 = 0xf;
-			t3 = ((value&0xf00)>>8)+(Apwrdelta);
-			if (t3 > 0xf)
-				t3 = 0xf;
-			t4 = ((value&0xf000)>>12)+(Apwrdelta);
-			if (t4 > 0xf)
-				t4 = 0xf;
-		}
-		else
-		{
-			if ((value&0xf) > Apwrdelta)
-				t1 = (value&0xf)-(Apwrdelta);
-			else
-				t1 = 0;
-			if (((value&0xf0)>>4) > Apwrdelta)
-				t2 = ((value&0xf0)>>4)-(Apwrdelta);
-			else
-				t2 = 0;
-			if (((value&0xf00)>>8) > Apwrdelta)
-				t3 = ((value&0xf00)>>8)-(Apwrdelta);
-			else
-				t3 = 0;
-			if (((value&0xf000)>>12) > Apwrdelta)
-				t4 = ((value&0xf000)>>12)-(Apwrdelta);
-			else
-				t4 = 0;
-		}
-		Adata |= ((t1<<16) + (t2<<20) + (t3<<24) + (t4<<28));
-		if (bGpwrdeltaMinus == FALSE)
-		{
-			t1 = (value&0xf)+(Gpwrdelta);
-			if (t1 > 0xf)
-				t1 = 0xf;
-			t2 = ((value&0xf0)>>4)+(Gpwrdelta);
-			if (t2 > 0xf)
-				t2 = 0xf;
-			t3 = ((value&0xf00)>>8)+(Gpwrdelta);
-			if (t3 > 0xf)
-				t3 = 0xf;
-			t4 = ((value&0xf000)>>12)+(Gpwrdelta);
-			if (t4 > 0xf)
-				t4 = 0xf;
-		}
-		else
-		{
-			if ((value&0xf) > Gpwrdelta)
-				t1 = (value&0xf)-(Gpwrdelta);
-			else
-				t1 = 0;
-			if (((value&0xf0)>>4) > Gpwrdelta)
-				t2 = ((value&0xf0)>>4)-(Gpwrdelta);
-			else
-				t2 = 0;
-			if (((value&0xf00)>>8) > Gpwrdelta)
-				t3 = ((value&0xf00)>>8)-(Gpwrdelta);
-			else
-				t3 = 0;
-			if (((value&0xf000)>>12) > Gpwrdelta)
-				t4 = ((value&0xf000)>>12)-(Gpwrdelta);
-			else
-				t4 = 0;
-		}
-		Gdata |= ((t1<<16) + (t2<<20) + (t3<<24) + (t4<<28));
-		data |= (value<<16);
-
-		pAd->Tx20MPwrCfgABand[i] = pAd->Tx40MPwrCfgABand[i] = Adata;
-		pAd->Tx20MPwrCfgGBand[i] = pAd->Tx40MPwrCfgGBand[i] = Gdata;
-
-		if (data != 0xffffffff)
-			RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, data);
-		DBGPRINT_RAW(RT_DEBUG_TRACE, ("20MHz BW, 2.4G band-%lx,  Adata = %lx,  Gdata = %lx \n", data, Adata, Gdata));
-	}
-
-	//
-	// Check this block is valid for 40MHz in 2.4G. If invalid, use parameter for 20MHz in 2.4G
-	//
-	bValid = TRUE;
-	for (i=0; i<6; i++)
-	{
-		RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_2_4G + 2 + i*2, value);
-		if (((value & 0x00FF) == 0x00FF) || ((value & 0xFF00) == 0xFF00))
-		{
-			bValid = FALSE;
-			break;
-		}
-	}
-
-	//
-	// Get Txpower per MCS for 40MHz in 2.4G.
-	//
-	if (bValid)
-	{
-		for (i=0; i<4; i++)
-		{
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_2_4G + i*4, value);
-			if (bGpwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Gpwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Gpwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Gpwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Gpwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Gpwrdelta)
-					t1 = (value&0xf)-(Gpwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Gpwrdelta)
-					t2 = ((value&0xf0)>>4)-(Gpwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Gpwrdelta)
-					t3 = ((value&0xf00)>>8)-(Gpwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Gpwrdelta)
-					t4 = ((value&0xf000)>>12)-(Gpwrdelta);
-				else
-					t4 = 0;
-			}
-			Gdata = t1 + (t2<<4) + (t3<<8) + (t4<<12);
-
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_2_4G + i*4 + 2, value);
-			if (bGpwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Gpwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Gpwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Gpwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Gpwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Gpwrdelta)
-					t1 = (value&0xf)-(Gpwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Gpwrdelta)
-					t2 = ((value&0xf0)>>4)-(Gpwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Gpwrdelta)
-					t3 = ((value&0xf00)>>8)-(Gpwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Gpwrdelta)
-					t4 = ((value&0xf000)>>12)-(Gpwrdelta);
-				else
-					t4 = 0;
-			}
-			Gdata |= ((t1<<16) + (t2<<20) + (t3<<24) + (t4<<28));
-
-			if (i == 0)
-				pAd->Tx40MPwrCfgGBand[i+1] = (pAd->Tx40MPwrCfgGBand[i+1] & 0x0000FFFF) | (Gdata & 0xFFFF0000);
-			else
-				pAd->Tx40MPwrCfgGBand[i+1] = Gdata;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE, ("40MHz BW, 2.4G band, Gdata = %lx \n", Gdata));
-		}
-	}
-
-	//
-	// Check this block is valid for 20MHz in 5G. If invalid, use parameter for 20MHz in 2.4G
-	//
-	bValid = TRUE;
-	for (i=0; i<8; i++)
-	{
-		RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_20MHZ_5G + 2 + i*2, value);
-		if (((value & 0x00FF) == 0x00FF) || ((value & 0xFF00) == 0xFF00))
-		{
-			bValid = FALSE;
-			break;
-		}
-	}
-
-	//
-	// Get Txpower per MCS for 20MHz in 5G.
-	//
-	if (bValid)
-	{
-		for (i=0; i<5; i++)
-		{
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_20MHZ_5G + i*4, value);
-			if (bApwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Apwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Apwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Apwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Apwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Apwrdelta)
-					t1 = (value&0xf)-(Apwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Apwrdelta)
-					t2 = ((value&0xf0)>>4)-(Apwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Apwrdelta)
-					t3 = ((value&0xf00)>>8)-(Apwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Apwrdelta)
-					t4 = ((value&0xf000)>>12)-(Apwrdelta);
-				else
-					t4 = 0;
-			}
-			Adata = t1 + (t2<<4) + (t3<<8) + (t4<<12);
-
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_20MHZ_5G + i*4 + 2, value);
-			if (bApwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Apwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Apwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Apwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Apwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Apwrdelta)
-					t1 = (value&0xf)-(Apwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Apwrdelta)
-					t2 = ((value&0xf0)>>4)-(Apwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Apwrdelta)
-					t3 = ((value&0xf00)>>8)-(Apwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Apwrdelta)
-					t4 = ((value&0xf000)>>12)-(Apwrdelta);
-				else
-					t4 = 0;
-			}
-			Adata |= ((t1<<16) + (t2<<20) + (t3<<24) + (t4<<28));
-
-			if (i == 0)
-				pAd->Tx20MPwrCfgABand[i] = (pAd->Tx20MPwrCfgABand[i] & 0x0000FFFF) | (Adata & 0xFFFF0000);
-			else
-				pAd->Tx20MPwrCfgABand[i] = Adata;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE, ("20MHz BW, 5GHz band, Adata = %lx \n", Adata));
-		}
-	}
-
-	//
-	// Check this block is valid for 40MHz in 5G. If invalid, use parameter for 20MHz in 2.4G
-	//
-	bValid = TRUE;
-	for (i=0; i<6; i++)
-	{
-		RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_5G + 2 + i*2, value);
-		if (((value & 0x00FF) == 0x00FF) || ((value & 0xFF00) == 0xFF00))
-		{
-			bValid = FALSE;
-			break;
-		}
-	}
-
-	//
-	// Get Txpower per MCS for 40MHz in 5G.
-	//
-	if (bValid)
-	{
-		for (i=0; i<4; i++)
-		{
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_5G + i*4, value);
-			if (bApwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Apwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Apwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Apwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Apwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Apwrdelta)
-					t1 = (value&0xf)-(Apwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Apwrdelta)
-					t2 = ((value&0xf0)>>4)-(Apwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Apwrdelta)
-					t3 = ((value&0xf00)>>8)-(Apwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Apwrdelta)
-					t4 = ((value&0xf000)>>12)-(Apwrdelta);
-				else
-					t4 = 0;
-			}
-			Adata = t1 + (t2<<4) + (t3<<8) + (t4<<12);
-
-			RT28xx_EEPROM_READ16(pAd, EEPROM_TXPOWER_BYRATE_40MHZ_5G + i*4 + 2, value);
-			if (bApwrdeltaMinus == FALSE)
-			{
-				t1 = (value&0xf)+(Apwrdelta);
-				if (t1 > 0xf)
-					t1 = 0xf;
-				t2 = ((value&0xf0)>>4)+(Apwrdelta);
-				if (t2 > 0xf)
-					t2 = 0xf;
-				t3 = ((value&0xf00)>>8)+(Apwrdelta);
-				if (t3 > 0xf)
-					t3 = 0xf;
-				t4 = ((value&0xf000)>>12)+(Apwrdelta);
-				if (t4 > 0xf)
-					t4 = 0xf;
-			}
-			else
-			{
-				if ((value&0xf) > Apwrdelta)
-					t1 = (value&0xf)-(Apwrdelta);
-				else
-					t1 = 0;
-				if (((value&0xf0)>>4) > Apwrdelta)
-					t2 = ((value&0xf0)>>4)-(Apwrdelta);
-				else
-					t2 = 0;
-				if (((value&0xf00)>>8) > Apwrdelta)
-					t3 = ((value&0xf00)>>8)-(Apwrdelta);
-				else
-					t3 = 0;
-				if (((value&0xf000)>>12) > Apwrdelta)
-					t4 = ((value&0xf000)>>12)-(Apwrdelta);
-				else
-					t4 = 0;
-			}
-			Adata |= ((t1<<16) + (t2<<20) + (t3<<24) + (t4<<28));
-
-			if (i == 0)
-				pAd->Tx40MPwrCfgABand[i+1] = (pAd->Tx40MPwrCfgABand[i+1] & 0x0000FFFF) | (Adata & 0xFFFF0000);
-			else
-				pAd->Tx40MPwrCfgABand[i+1] = Adata;
-
-			DBGPRINT_RAW(RT_DEBUG_TRACE, ("40MHz BW, 5GHz band, Adata = %lx \n", Adata));
-		}
-	}
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Read initial channel power parameters from EEPROM
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPReadChannelPwr(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UCHAR				i, choffset;
-	EEPROM_TX_PWR_STRUC	    Power;
-	EEPROM_TX_PWR_STRUC	    Power2;
-
-	// Read Tx power value for all channels
-	// Value from 1 - 0x7f. Default value is 24.
-	// Power value : 2.4G 0x00 (0) ~ 0x1F (31)
-	//             : 5.5G 0xF9 (-7) ~ 0x0F (15)
-
-	// 0. 11b/g, ch1 - ch 14
-	for (i = 0; i < 7; i++)
-	{
-//		Power.word = RTMP_EEPROM_READ16(pAd, EEPROM_G_TX_PWR_OFFSET + i * 2);
-//		Power2.word = RTMP_EEPROM_READ16(pAd, EEPROM_G_TX2_PWR_OFFSET + i * 2);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_G_TX_PWR_OFFSET + i * 2, Power.word);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_G_TX2_PWR_OFFSET + i * 2, Power2.word);
-		pAd->TxPower[i * 2].Channel = i * 2 + 1;
-		pAd->TxPower[i * 2 + 1].Channel = i * 2 + 2;
-
-		if ((Power.field.Byte0 > 31) || (Power.field.Byte0 < 0))
-			pAd->TxPower[i * 2].Power = DEFAULT_RF_TX_POWER;
-		else
-			pAd->TxPower[i * 2].Power = Power.field.Byte0;
-
-		if ((Power.field.Byte1 > 31) || (Power.field.Byte1 < 0))
-			pAd->TxPower[i * 2 + 1].Power = DEFAULT_RF_TX_POWER;
-		else
-			pAd->TxPower[i * 2 + 1].Power = Power.field.Byte1;
-
-		if ((Power2.field.Byte0 > 31) || (Power2.field.Byte0 < 0))
-			pAd->TxPower[i * 2].Power2 = DEFAULT_RF_TX_POWER;
-		else
-			pAd->TxPower[i * 2].Power2 = Power2.field.Byte0;
-
-		if ((Power2.field.Byte1 > 31) || (Power2.field.Byte1 < 0))
-			pAd->TxPower[i * 2 + 1].Power2 = DEFAULT_RF_TX_POWER;
-		else
-			pAd->TxPower[i * 2 + 1].Power2 = Power2.field.Byte1;
-	}
-
-	// 1. U-NII lower/middle band: 36, 38, 40; 44, 46, 48; 52, 54, 56; 60, 62, 64 (including central frequency in BW 40MHz)
-	// 1.1 Fill up channel
-	choffset = 14;
-	for (i = 0; i < 4; i++)
-	{
-		pAd->TxPower[3 * i + choffset + 0].Channel	= 36 + i * 8 + 0;
-		pAd->TxPower[3 * i + choffset + 0].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 0].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 1].Channel	= 36 + i * 8 + 2;
-		pAd->TxPower[3 * i + choffset + 1].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 1].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 2].Channel	= 36 + i * 8 + 4;
-		pAd->TxPower[3 * i + choffset + 2].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 2].Power2	= DEFAULT_RF_TX_POWER;
-	}
-
-	// 1.2 Fill up power
-	for (i = 0; i < 6; i++)
-	{
-//		Power.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + i * 2);
-//		Power2.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + i * 2);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + i * 2, Power.word);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + i * 2, Power2.word);
-
-		if ((Power.field.Byte0 < 16) && (Power.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power = Power.field.Byte0;
-
-		if ((Power.field.Byte1 < 16) && (Power.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power = Power.field.Byte1;
-
-		if ((Power2.field.Byte0 < 16) && (Power2.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power2 = Power2.field.Byte0;
-
-		if ((Power2.field.Byte1 < 16) && (Power2.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power2 = Power2.field.Byte1;
-	}
-
-	// 2. HipperLAN 2 100, 102 ,104; 108, 110, 112; 116, 118, 120; 124, 126, 128; 132, 134, 136; 140 (including central frequency in BW 40MHz)
-	// 2.1 Fill up channel
-	choffset = 14 + 12;
-	for (i = 0; i < 5; i++)
-	{
-		pAd->TxPower[3 * i + choffset + 0].Channel	= 100 + i * 8 + 0;
-		pAd->TxPower[3 * i + choffset + 0].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 0].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 1].Channel	= 100 + i * 8 + 2;
-		pAd->TxPower[3 * i + choffset + 1].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 1].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 2].Channel	= 100 + i * 8 + 4;
-		pAd->TxPower[3 * i + choffset + 2].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 2].Power2	= DEFAULT_RF_TX_POWER;
-	}
-	pAd->TxPower[3 * 5 + choffset + 0].Channel		= 140;
-	pAd->TxPower[3 * 5 + choffset + 0].Power		= DEFAULT_RF_TX_POWER;
-	pAd->TxPower[3 * 5 + choffset + 0].Power2		= DEFAULT_RF_TX_POWER;
-
-	// 2.2 Fill up power
-	for (i = 0; i < 8; i++)
-	{
-//		Power.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + (choffset - 14) + i * 2);
-//		Power2.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + (choffset - 14) + i * 2);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + (choffset - 14) + i * 2, Power.word);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + (choffset - 14) + i * 2, Power2.word);
-
-		if ((Power.field.Byte0 < 16) && (Power.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power = Power.field.Byte0;
-
-		if ((Power.field.Byte1 < 16) && (Power.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power = Power.field.Byte1;
-
-		if ((Power2.field.Byte0 < 16) && (Power2.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power2 = Power2.field.Byte0;
-
-		if ((Power2.field.Byte1 < 16) && (Power2.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power2 = Power2.field.Byte1;
-	}
-
-	// 3. U-NII upper band: 149, 151, 153; 157, 159, 161; 165 (including central frequency in BW 40MHz)
-	// 3.1 Fill up channel
-	choffset = 14 + 12 + 16;
-	for (i = 0; i < 2; i++)
-	{
-		pAd->TxPower[3 * i + choffset + 0].Channel	= 149 + i * 8 + 0;
-		pAd->TxPower[3 * i + choffset + 0].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 0].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 1].Channel	= 149 + i * 8 + 2;
-		pAd->TxPower[3 * i + choffset + 1].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 1].Power2	= DEFAULT_RF_TX_POWER;
-
-		pAd->TxPower[3 * i + choffset + 2].Channel	= 149 + i * 8 + 4;
-		pAd->TxPower[3 * i + choffset + 2].Power	= DEFAULT_RF_TX_POWER;
-		pAd->TxPower[3 * i + choffset + 2].Power2	= DEFAULT_RF_TX_POWER;
-	}
-	pAd->TxPower[3 * 2 + choffset + 0].Channel		= 165;
-	pAd->TxPower[3 * 2 + choffset + 0].Power		= DEFAULT_RF_TX_POWER;
-	pAd->TxPower[3 * 2 + choffset + 0].Power2		= DEFAULT_RF_TX_POWER;
-
-	// 3.2 Fill up power
-	for (i = 0; i < 4; i++)
-	{
-//		Power.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + (choffset - 14) + i * 2);
-//		Power2.word = RTMP_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + (choffset - 14) + i * 2);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX_PWR_OFFSET + (choffset - 14) + i * 2, Power.word);
-		RT28xx_EEPROM_READ16(pAd, EEPROM_A_TX2_PWR_OFFSET + (choffset - 14) + i * 2, Power2.word);
-
-		if ((Power.field.Byte0 < 16) && (Power.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power = Power.field.Byte0;
-
-		if ((Power.field.Byte1 < 16) && (Power.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power = Power.field.Byte1;
-
-		if ((Power2.field.Byte0 < 16) && (Power2.field.Byte0 >= -7))
-			pAd->TxPower[i * 2 + choffset + 0].Power2 = Power2.field.Byte0;
-
-		if ((Power2.field.Byte1 < 16) && (Power2.field.Byte1 >= -7))
-			pAd->TxPower[i * 2 + choffset + 1].Power2 = Power2.field.Byte1;
-	}
-
-	// 4. Print and Debug
-	choffset = 14 + 12 + 16 + 7;
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Read the following from the registry
-		1. All the parameters
-		2. NetworkAddres
-
-	Arguments:
-		Adapter						Pointer to our adapter
-		WrapperConfigurationContext	For use by NdisOpenConfiguration
-
-	Return Value:
-		NDIS_STATUS_SUCCESS
-		NDIS_STATUS_FAILURE
-		NDIS_STATUS_RESOURCES
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS	NICReadRegParameters(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	NDIS_HANDLE			WrapperConfigurationContext
-	)
-{
-	NDIS_STATUS						Status = NDIS_STATUS_SUCCESS;
-	DBGPRINT_S(Status, ("<-- NICReadRegParameters, Status=%x\n", Status));
-	return Status;
-}
-
-
-#ifdef RT30xx
-/*
-	========================================================================
-
-	Routine Description:
-		For RF filter calibration purpose
-
-	Arguments:
-		pAd                          Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-VOID RTMPFilterCalibration(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR	R55x = 0, value, FilterTarget = 0x1E, BBPValue=0;
-	UINT	loop = 0, count = 0, loopcnt = 0, ReTry = 0;
-	UCHAR	RF_R24_Value = 0;
-
-	// Give bbp filter initial value
-	pAd->Mlme.CaliBW20RfR24 = 0x1F;
-	pAd->Mlme.CaliBW40RfR24 = 0x2F; //Bit[5] must be 1 for BW 40
-
-	do
-	{
-		if (loop == 1)	//BandWidth = 40 MHz
-		{
-			// Write 0x27 to RF_R24 to program filter
-			RF_R24_Value = 0x27;
-			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
-			if (IS_RT3090(pAd))
-				FilterTarget = 0x15;
-			else
-				FilterTarget = 0x19;
-
-			// when calibrate BW40, BBP mask must set to BW40.
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-			BBPValue&= (~0x18);
-			BBPValue|= (0x10);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-
-			// set to BW40
-			RT30xxReadRFRegister(pAd, RF_R31, &value);
-			value |= 0x20;
-			RT30xxWriteRFRegister(pAd, RF_R31, value);
-		}
-		else			//BandWidth = 20 MHz
-		{
-			// Write 0x07 to RF_R24 to program filter
-			RF_R24_Value = 0x07;
-			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
-			if (IS_RT3090(pAd))
-				FilterTarget = 0x13;
-			else
-				FilterTarget = 0x16;
-
-			// set to BW20
-			RT30xxReadRFRegister(pAd, RF_R31, &value);
-			value &= (~0x20);
-			RT30xxWriteRFRegister(pAd, RF_R31, value);
-		}
-
-		// Write 0x01 to RF_R22 to enable baseband loopback mode
-		RT30xxReadRFRegister(pAd, RF_R22, &value);
-		value |= 0x01;
-		RT30xxWriteRFRegister(pAd, RF_R22, value);
-
-		// Write 0x00 to BBP_R24 to set power & frequency of passband test tone
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, 0);
-
-		do
-		{
-			// Write 0x90 to BBP_R25 to transmit test tone
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R25, 0x90);
-
-			RTMPusecDelay(1000);
-			// Read BBP_R55[6:0] for received power, set R55x = BBP_R55[6:0]
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R55, &value);
-			R55x = value & 0xFF;
-
-		} while ((ReTry++ < 100) && (R55x == 0));
-
-		// Write 0x06 to BBP_R24 to set power & frequency of stopband test tone
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, 0x06);
-
-		while(TRUE)
-		{
-			// Write 0x90 to BBP_R25 to transmit test tone
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R25, 0x90);
-
-			//We need to wait for calibration
-			RTMPusecDelay(1000);
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R55, &value);
-			value &= 0xFF;
-			if ((R55x - value) < FilterTarget)
-			{
-				RF_R24_Value ++;
-			}
-			else if ((R55x - value) == FilterTarget)
-			{
-				RF_R24_Value ++;
-				count ++;
-			}
-			else
-			{
-				break;
-			}
-
-			// prevent infinite loop cause driver hang.
-			if (loopcnt++ > 100)
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("RTMPFilterCalibration - can't find a valid value, loopcnt=%d stop calibrating", loopcnt));
-				break;
-			}
-
-			// Write RF_R24 to program filter
-			RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
-		}
-
-		if (count > 0)
-		{
-			RF_R24_Value = RF_R24_Value - ((count) ? (1) : (0));
-		}
-
-		// Store for future usage
-		if (loopcnt < 100)
-		{
-			if (loop++ == 0)
-			{
-				//BandWidth = 20 MHz
-				pAd->Mlme.CaliBW20RfR24 = (UCHAR)RF_R24_Value;
-			}
-			else
-			{
-				//BandWidth = 40 MHz
-				pAd->Mlme.CaliBW40RfR24 = (UCHAR)RF_R24_Value;
-				break;
-			}
-		}
-		else
-			break;
-
-		RT30xxWriteRFRegister(pAd, RF_R24, RF_R24_Value);
-
-		// reset count
-		count = 0;
-	} while(TRUE);
-
-	//
-	// Set back to initial state
-	//
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, 0);
-
-	RT30xxReadRFRegister(pAd, RF_R22, &value);
-	value &= ~(0x01);
-	RT30xxWriteRFRegister(pAd, RF_R22, value);
-
-	// set BBP back to BW20
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-	BBPValue&= (~0x18);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPFilterCalibration - CaliBW20RfR24=0x%x, CaliBW40RfR24=0x%x\n", pAd->Mlme.CaliBW20RfR24, pAd->Mlme.CaliBW40RfR24));
-}
-#endif // RT30xx //
-
-
-#ifdef RT3070
-VOID NICInitRT30xxRFRegisters(IN PRTMP_ADAPTER pAd)
-{
-	INT i;
-	// Driver must read EEPROM to get RfIcType before initial RF registers
-	// Initialize RF register to default value
-	if (IS_RT3070(pAd) || IS_RT3071(pAd))
-	{
-		// Init RF calibration
-		// Driver should toggle RF R30 bit7 before init RF registers
-		UINT32 RfReg = 0;
-		UINT32 data;
-
-		RT30xxReadRFRegister(pAd, RF_R30, (PUCHAR)&RfReg);
-		RfReg |= 0x80;
-		RT30xxWriteRFRegister(pAd, RF_R30, (UCHAR)RfReg);
-		RTMPusecDelay(1000);
-		RfReg &= 0x7F;
-		RT30xxWriteRFRegister(pAd, RF_R30, (UCHAR)RfReg);
-
-		// Initialize RF register to default value
-		for (i = 0; i < NUM_RF_REG_PARMS; i++)
-		{
-			RT30xxWriteRFRegister(pAd, RT30xx_RFRegTable[i].Register, RT30xx_RFRegTable[i].Value);
-		}
-
-		// add by johnli
-		if (IS_RT3070(pAd))
-		{
-			//  Update MAC 0x05D4 from 01xxxxxx to 0Dxxxxxx (voltage 1.2V to 1.35V) for RT3070 to improve yield rate
-			RTUSBReadMACRegister(pAd, LDO_CFG0, &data);
-			data = ((data & 0xF0FFFFFF) | 0x0D000000);
-			RTUSBWriteMACRegister(pAd, LDO_CFG0, data);
-		}
-		else if (IS_RT3071(pAd))
-		{
-			// Driver should set RF R6 bit6 on before init RF registers
-			RT30xxReadRFRegister(pAd, RF_R06, (PUCHAR)&RfReg);
-			RfReg |= 0x40;
-			RT30xxWriteRFRegister(pAd, RF_R06, (UCHAR)RfReg);
-
-			// init R31
-			RT30xxWriteRFRegister(pAd, RF_R31, 0x14);
-
-			// RT3071 version E has fixed this issue
-			if ((pAd->NicConfig2.field.DACTestBit == 1) && ((pAd->MACVersion & 0xffff) < 0x0211))
-			{
-				// patch tx EVM issue temporarily
-				RTUSBReadMACRegister(pAd, LDO_CFG0, &data);
-				data = ((data & 0xE0FFFFFF) | 0x0D000000);
-				RTUSBWriteMACRegister(pAd, LDO_CFG0, data);
-			}
-			else
-			{
-				RTMP_IO_READ32(pAd, LDO_CFG0, &data);
-				data = ((data & 0xE0FFFFFF) | 0x01000000);
-				RTMP_IO_WRITE32(pAd, LDO_CFG0, data);
-			}
-
-			// patch LNA_PE_G1 failed issue
-			RTUSBReadMACRegister(pAd, GPIO_SWITCH, &data);
-			data &= ~(0x20);
-			RTUSBWriteMACRegister(pAd, GPIO_SWITCH, data);
-		}
-
-		//For RF filter Calibration
-		RTMPFilterCalibration(pAd);
-
-		// Initialize RF R27 register, set RF R27 must be behind RTMPFilterCalibration()
-		if ((pAd->MACVersion & 0xffff) < 0x0211)
-			RT30xxWriteRFRegister(pAd, RF_R27, 0x3);
-
-		// set led open drain enable
-		RTUSBReadMACRegister(pAd, OPT_14, &data);
-		data |= 0x01;
-		RTUSBWriteMACRegister(pAd, OPT_14, data);
-
-		if (IS_RT3071(pAd))
-		{
-			// add by johnli, RF power sequence setup, load RF normal operation-mode setup
-			RT30xxLoadRFNormalModeSetup(pAd);
-		}
-	}
-
-}
-#endif // RT3070 //
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Read initial parameters from EEPROM
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	NICReadEEPROMParameters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			mac_addr)
-{
-	UINT32			data = 0;
-	USHORT			i, value, value2;
-	UCHAR			TmpPhy;
-	EEPROM_TX_PWR_STRUC	    Power;
-	EEPROM_VERSION_STRUC    Version;
-	EEPROM_ANTENNA_STRUC	Antenna;
-	EEPROM_NIC_CONFIG2_STRUC    NicConfig2;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICReadEEPROMParameters\n"));
-
-	// Init EEPROM Address Number, before access EEPROM; if 93c46, EEPROMAddressNum=6, else if 93c66, EEPROMAddressNum=8
-	RTMP_IO_READ32(pAd, E2PROM_CSR, &data);
-	DBGPRINT(RT_DEBUG_TRACE, ("--> E2PROM_CSR = 0x%x\n", data));
-
-	if((data & 0x30) == 0)
-		pAd->EEPROMAddressNum = 6;		// 93C46
-	else if((data & 0x30) == 0x10)
-		pAd->EEPROMAddressNum = 8;     // 93C66
-	else
-		pAd->EEPROMAddressNum = 8;     // 93C86
-	DBGPRINT(RT_DEBUG_TRACE, ("--> EEPROMAddressNum = %d\n", pAd->EEPROMAddressNum ));
-
-	// RT2860 MAC no longer auto load MAC address from E2PROM. Driver has to intialize
-	// MAC address registers according to E2PROM setting
-	if (mac_addr == NULL ||
-		strlen(mac_addr) != 17 ||
-		mac_addr[2] != ':'  || mac_addr[5] != ':'  || mac_addr[8] != ':' ||
-		mac_addr[11] != ':' || mac_addr[14] != ':')
-	{
-		USHORT  Addr01,Addr23,Addr45 ;
-
-		RT28xx_EEPROM_READ16(pAd, 0x04, Addr01);
-		RT28xx_EEPROM_READ16(pAd, 0x06, Addr23);
-		RT28xx_EEPROM_READ16(pAd, 0x08, Addr45);
-
-		pAd->PermanentAddress[0] = (UCHAR)(Addr01 & 0xff);
-		pAd->PermanentAddress[1] = (UCHAR)(Addr01 >> 8);
-		pAd->PermanentAddress[2] = (UCHAR)(Addr23 & 0xff);
-		pAd->PermanentAddress[3] = (UCHAR)(Addr23 >> 8);
-		pAd->PermanentAddress[4] = (UCHAR)(Addr45 & 0xff);
-		pAd->PermanentAddress[5] = (UCHAR)(Addr45 >> 8);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Initialize MAC Address from E2PROM \n"));
-	}
-	else
-	{
-		INT		j;
-		PUCHAR	macptr;
-
-		macptr = mac_addr;
-
-		for (j=0; j<MAC_ADDR_LEN; j++)
-		{
-			AtoH(macptr, &pAd->PermanentAddress[j], 1);
-			macptr=macptr+3;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Initialize MAC Address from module parameter \n"));
-	}
-
-
-	{
-		//more conveninet to test mbssid, so ap's bssid &0xf1
-		if (pAd->PermanentAddress[0] == 0xff)
-			pAd->PermanentAddress[0] = RandomByte(pAd)&0xf8;
-
-		//if (pAd->PermanentAddress[5] == 0xff)
-		//	pAd->PermanentAddress[5] = RandomByte(pAd)&0xf8;
-
-		DBGPRINT_RAW(RT_DEBUG_TRACE,("E2PROM MAC: =%02x:%02x:%02x:%02x:%02x:%02x\n",
-			pAd->PermanentAddress[0], pAd->PermanentAddress[1],
-			pAd->PermanentAddress[2], pAd->PermanentAddress[3],
-			pAd->PermanentAddress[4], pAd->PermanentAddress[5]));
-		if (pAd->bLocalAdminMAC == FALSE)
-		{
-			MAC_DW0_STRUC csr2;
-			MAC_DW1_STRUC csr3;
-			COPY_MAC_ADDR(pAd->CurrentAddress, pAd->PermanentAddress);
-			csr2.field.Byte0 = pAd->CurrentAddress[0];
-			csr2.field.Byte1 = pAd->CurrentAddress[1];
-			csr2.field.Byte2 = pAd->CurrentAddress[2];
-			csr2.field.Byte3 = pAd->CurrentAddress[3];
-			RTMP_IO_WRITE32(pAd, MAC_ADDR_DW0, csr2.word);
-			csr3.word = 0;
-			csr3.field.Byte4 = pAd->CurrentAddress[4];
-			csr3.field.Byte5 = pAd->CurrentAddress[5];
-			csr3.field.U2MeMask = 0xff;
-			RTMP_IO_WRITE32(pAd, MAC_ADDR_DW1, csr3.word);
-			DBGPRINT_RAW(RT_DEBUG_TRACE,("E2PROM MAC: =%02x:%02x:%02x:%02x:%02x:%02x\n",
-				pAd->PermanentAddress[0], pAd->PermanentAddress[1],
-				pAd->PermanentAddress[2], pAd->PermanentAddress[3],
-				pAd->PermanentAddress[4], pAd->PermanentAddress[5]));
-		}
-	}
-
-	// if not return early. cause fail at emulation.
-	// Init the channel number for TX channel power
-	RTMPReadChannelPwr(pAd);
-
-	// if E2PROM version mismatch with driver's expectation, then skip
-	// all subsequent E2RPOM retieval and set a system error bit to notify GUI
-	RT28xx_EEPROM_READ16(pAd, EEPROM_VERSION_OFFSET, Version.word);
-	pAd->EepromVersion = Version.field.Version + Version.field.FaeReleaseNumber * 256;
-	DBGPRINT(RT_DEBUG_TRACE, ("E2PROM: Version = %d, FAE release #%d\n", Version.field.Version, Version.field.FaeReleaseNumber));
-
-	if (Version.field.Version > VALID_EEPROM_VERSION)
-	{
-		DBGPRINT_ERR(("E2PROM: WRONG VERSION 0x%x, should be %d\n",Version.field.Version, VALID_EEPROM_VERSION));
-		/*pAd->SystemErrorBitmap |= 0x00000001;
-
-		// hard-code default value when no proper E2PROM installed
-		pAd->bAutoTxAgcA = FALSE;
-		pAd->bAutoTxAgcG = FALSE;
-
-		// Default the channel power
-		for (i = 0; i < MAX_NUM_OF_CHANNELS; i++)
-			pAd->TxPower[i].Power = DEFAULT_RF_TX_POWER;
-
-		// Default the channel power
-		for (i = 0; i < MAX_NUM_OF_11JCHANNELS; i++)
-			pAd->TxPower11J[i].Power = DEFAULT_RF_TX_POWER;
-
-		for(i = 0; i < NUM_EEPROM_BBP_PARMS; i++)
-			pAd->EEPROMDefaultValue[i] = 0xffff;
-		return;  */
-	}
-
-	// Read BBP default value from EEPROM and store to array(EEPROMDefaultValue) in pAd
-	RT28xx_EEPROM_READ16(pAd, EEPROM_NIC1_OFFSET, value);
-	pAd->EEPROMDefaultValue[0] = value;
-
-	RT28xx_EEPROM_READ16(pAd, EEPROM_NIC2_OFFSET, value);
-	pAd->EEPROMDefaultValue[1] = value;
-
-	RT28xx_EEPROM_READ16(pAd, 0x38, value);	// Country Region
-	pAd->EEPROMDefaultValue[2] = value;
-
-	for(i = 0; i < 8; i++)
-	{
-		RT28xx_EEPROM_READ16(pAd, EEPROM_BBP_BASE_OFFSET + i*2, value);
-		pAd->EEPROMDefaultValue[i+3] = value;
-	}
-
-	// We have to parse NIC configuration 0 at here.
-	// If TSSI did not have preloaded value, it should reset the TxAutoAgc to false
-	// Therefore, we have to read TxAutoAgc control beforehand.
-	// Read Tx AGC control bit
-	Antenna.word = pAd->EEPROMDefaultValue[0];
-	if (Antenna.word == 0xFFFF)
-	{
-#ifdef RT30xx
-		if(IS_RT3090(pAd))
-		{
-			Antenna.word = 0;
-			Antenna.field.RfIcType = RFIC_3020;
-			Antenna.field.TxPath = 1;
-			Antenna.field.RxPath = 1;
-		}
-		else
-		{
-#endif // RT30xx //
-			Antenna.word = 0;
-			Antenna.field.RfIcType = RFIC_2820;
-			Antenna.field.TxPath = 1;
-			Antenna.field.RxPath = 2;
-			DBGPRINT(RT_DEBUG_WARN, ("E2PROM error, hard code as 0x%04x\n", Antenna.word));
-#ifdef RT30xx
-		}
-#endif // RT30xx //
-	}
-
-	// Choose the desired Tx&Rx stream.
-	if ((pAd->CommonCfg.TxStream == 0) || (pAd->CommonCfg.TxStream > Antenna.field.TxPath))
-		pAd->CommonCfg.TxStream = Antenna.field.TxPath;
-
-	if ((pAd->CommonCfg.RxStream == 0) || (pAd->CommonCfg.RxStream > Antenna.field.RxPath))
-	{
-		pAd->CommonCfg.RxStream = Antenna.field.RxPath;
-
-		if ((pAd->MACVersion < RALINK_2883_VERSION) &&
-			(pAd->CommonCfg.RxStream > 2))
-		{
-			// only 2 Rx streams for RT2860 series
-			pAd->CommonCfg.RxStream = 2;
-		}
-	}
-
-	// 3*3
-	// read value from EEPROM and set them to CSR174 ~ 177 in chain0 ~ chain2
-	// yet implement
-	for(i=0; i<3; i++)
-	{
-	}
-
-	NicConfig2.word = pAd->EEPROMDefaultValue[1];
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if ((NicConfig2.word & 0x00ff) == 0xff)
-		{
-			NicConfig2.word &= 0xff00;
-		}
-
-		if ((NicConfig2.word >> 8) == 0xff)
-		{
-			NicConfig2.word &= 0x00ff;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	if (NicConfig2.field.DynamicTxAgcControl == 1)
-		pAd->bAutoTxAgcA = pAd->bAutoTxAgcG = TRUE;
-	else
-		pAd->bAutoTxAgcA = pAd->bAutoTxAgcG = FALSE;
-
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("NICReadEEPROMParameters: RxPath = %d, TxPath = %d\n", Antenna.field.RxPath, Antenna.field.TxPath));
-
-	// Save the antenna for future use
-	pAd->Antenna.word = Antenna.word;
-
-	//
-	// Reset PhyMode if we don't support 802.11a
-	// Only RFIC_2850 & RFIC_2750 support 802.11a
-	//
-	if ((Antenna.field.RfIcType != RFIC_2850) && (Antenna.field.RfIcType != RFIC_2750))
-	{
-		if ((pAd->CommonCfg.PhyMode == PHY_11ABG_MIXED) ||
-			(pAd->CommonCfg.PhyMode == PHY_11A))
-			pAd->CommonCfg.PhyMode = PHY_11BG_MIXED;
-#ifdef DOT11_N_SUPPORT
-		else if ((pAd->CommonCfg.PhyMode == PHY_11ABGN_MIXED)	||
-				 (pAd->CommonCfg.PhyMode == PHY_11AN_MIXED) 	||
-				 (pAd->CommonCfg.PhyMode == PHY_11AGN_MIXED) 	||
-				 (pAd->CommonCfg.PhyMode == PHY_11N_5G))
-			pAd->CommonCfg.PhyMode = PHY_11BGN_MIXED;
-#endif // DOT11_N_SUPPORT //
-	}
-
-	// Read TSSI reference and TSSI boundary for temperature compensation. This is ugly
-	// 0. 11b/g
-	{
-		/* these are tempature reference value (0x00 ~ 0xFE)
-		   ex: 0x00 0x15 0x25 0x45 0x88 0xA0 0xB5 0xD0 0xF0
-		   TssiPlusBoundaryG [4] [3] [2] [1] [0] (smaller) +
-		   TssiMinusBoundaryG[0] [1] [2] [3] [4] (larger) */
-		RT28xx_EEPROM_READ16(pAd, 0x6E, Power.word);
-		pAd->TssiMinusBoundaryG[4] = Power.field.Byte0;
-		pAd->TssiMinusBoundaryG[3] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0x70, Power.word);
-		pAd->TssiMinusBoundaryG[2] = Power.field.Byte0;
-		pAd->TssiMinusBoundaryG[1] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0x72, Power.word);
-		pAd->TssiRefG   = Power.field.Byte0; /* reference value [0] */
-		pAd->TssiPlusBoundaryG[1] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0x74, Power.word);
-		pAd->TssiPlusBoundaryG[2] = Power.field.Byte0;
-		pAd->TssiPlusBoundaryG[3] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0x76, Power.word);
-		pAd->TssiPlusBoundaryG[4] = Power.field.Byte0;
-		pAd->TxAgcStepG = Power.field.Byte1;
-		pAd->TxAgcCompensateG = 0;
-		pAd->TssiMinusBoundaryG[0] = pAd->TssiRefG;
-		pAd->TssiPlusBoundaryG[0]  = pAd->TssiRefG;
-
-		// Disable TxAgc if the based value is not right
-		if (pAd->TssiRefG == 0xff)
-			pAd->bAutoTxAgcG = FALSE;
-
-		DBGPRINT(RT_DEBUG_TRACE,("E2PROM: G Tssi[-4 .. +4] = %d %d %d %d - %d -%d %d %d %d, step=%d, tuning=%d\n",
-			pAd->TssiMinusBoundaryG[4], pAd->TssiMinusBoundaryG[3], pAd->TssiMinusBoundaryG[2], pAd->TssiMinusBoundaryG[1],
-			pAd->TssiRefG,
-			pAd->TssiPlusBoundaryG[1], pAd->TssiPlusBoundaryG[2], pAd->TssiPlusBoundaryG[3], pAd->TssiPlusBoundaryG[4],
-			pAd->TxAgcStepG, pAd->bAutoTxAgcG));
-	}
-	// 1. 11a
-	{
-		RT28xx_EEPROM_READ16(pAd, 0xD4, Power.word);
-		pAd->TssiMinusBoundaryA[4] = Power.field.Byte0;
-		pAd->TssiMinusBoundaryA[3] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0xD6, Power.word);
-		pAd->TssiMinusBoundaryA[2] = Power.field.Byte0;
-		pAd->TssiMinusBoundaryA[1] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0xD8, Power.word);
-		pAd->TssiRefA   = Power.field.Byte0;
-		pAd->TssiPlusBoundaryA[1] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0xDA, Power.word);
-		pAd->TssiPlusBoundaryA[2] = Power.field.Byte0;
-		pAd->TssiPlusBoundaryA[3] = Power.field.Byte1;
-		RT28xx_EEPROM_READ16(pAd, 0xDC, Power.word);
-		pAd->TssiPlusBoundaryA[4] = Power.field.Byte0;
-		pAd->TxAgcStepA = Power.field.Byte1;
-		pAd->TxAgcCompensateA = 0;
-		pAd->TssiMinusBoundaryA[0] = pAd->TssiRefA;
-		pAd->TssiPlusBoundaryA[0]  = pAd->TssiRefA;
-
-		// Disable TxAgc if the based value is not right
-		if (pAd->TssiRefA == 0xff)
-			pAd->bAutoTxAgcA = FALSE;
-
-		DBGPRINT(RT_DEBUG_TRACE,("E2PROM: A Tssi[-4 .. +4] = %d %d %d %d - %d -%d %d %d %d, step=%d, tuning=%d\n",
-			pAd->TssiMinusBoundaryA[4], pAd->TssiMinusBoundaryA[3], pAd->TssiMinusBoundaryA[2], pAd->TssiMinusBoundaryA[1],
-			pAd->TssiRefA,
-			pAd->TssiPlusBoundaryA[1], pAd->TssiPlusBoundaryA[2], pAd->TssiPlusBoundaryA[3], pAd->TssiPlusBoundaryA[4],
-			pAd->TxAgcStepA, pAd->bAutoTxAgcA));
-	}
-	pAd->BbpRssiToDbmDelta = 0x0;
-
-	// Read frequency offset setting for RF
-	RT28xx_EEPROM_READ16(pAd, EEPROM_FREQ_OFFSET, value);
-	if ((value & 0x00FF) != 0x00FF)
-		pAd->RfFreqOffset = (ULONG) (value & 0x00FF);
-	else
-		pAd->RfFreqOffset = 0;
-	DBGPRINT(RT_DEBUG_TRACE, ("E2PROM: RF FreqOffset=0x%lx \n", pAd->RfFreqOffset));
-
-	//CountryRegion byte offset (38h)
-	value = pAd->EEPROMDefaultValue[2] >> 8;		// 2.4G band
-	value2 = pAd->EEPROMDefaultValue[2] & 0x00FF;	// 5G band
-
-	if ((value <= REGION_MAXIMUM_BG_BAND) && (value2 <= REGION_MAXIMUM_A_BAND))
-	{
-		pAd->CommonCfg.CountryRegion = ((UCHAR) value) | 0x80;
-		pAd->CommonCfg.CountryRegionForABand = ((UCHAR) value2) | 0x80;
-		TmpPhy = pAd->CommonCfg.PhyMode;
-		pAd->CommonCfg.PhyMode = 0xff;
-		RTMPSetPhyMode(pAd, TmpPhy);
-#ifdef DOT11_N_SUPPORT
-		SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-	}
-
-	//
-	// Get RSSI Offset on EEPROM 0x9Ah & 0x9Ch.
-	// The valid value are (-10 ~ 10)
-	//
-	RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_BG_OFFSET, value);
-	pAd->BGRssiOffset0 = value & 0x00ff;
-	pAd->BGRssiOffset1 = (value >> 8);
-	RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_BG_OFFSET+2, value);
-	pAd->BGRssiOffset2 = value & 0x00ff;
-	pAd->ALNAGain1 = (value >> 8);
-	RT28xx_EEPROM_READ16(pAd, EEPROM_LNA_OFFSET, value);
-	pAd->BLNAGain = value & 0x00ff;
-	pAd->ALNAGain0 = (value >> 8);
-
-	// Validate 11b/g RSSI_0 offset.
-	if ((pAd->BGRssiOffset0 < -10) || (pAd->BGRssiOffset0 > 10))
-		pAd->BGRssiOffset0 = 0;
-
-	// Validate 11b/g RSSI_1 offset.
-	if ((pAd->BGRssiOffset1 < -10) || (pAd->BGRssiOffset1 > 10))
-		pAd->BGRssiOffset1 = 0;
-
-	// Validate 11b/g RSSI_2 offset.
-	if ((pAd->BGRssiOffset2 < -10) || (pAd->BGRssiOffset2 > 10))
-		pAd->BGRssiOffset2 = 0;
-
-	RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_A_OFFSET, value);
-	pAd->ARssiOffset0 = value & 0x00ff;
-	pAd->ARssiOffset1 = (value >> 8);
-	RT28xx_EEPROM_READ16(pAd, (EEPROM_RSSI_A_OFFSET+2), value);
-	pAd->ARssiOffset2 = value & 0x00ff;
-	pAd->ALNAGain2 = (value >> 8);
-
-	if (((UCHAR)pAd->ALNAGain1 == 0xFF) || (pAd->ALNAGain1 == 0x00))
-		pAd->ALNAGain1 = pAd->ALNAGain0;
-	if (((UCHAR)pAd->ALNAGain2 == 0xFF) || (pAd->ALNAGain2 == 0x00))
-		pAd->ALNAGain2 = pAd->ALNAGain0;
-
-	// Validate 11a RSSI_0 offset.
-	if ((pAd->ARssiOffset0 < -10) || (pAd->ARssiOffset0 > 10))
-		pAd->ARssiOffset0 = 0;
-
-	// Validate 11a RSSI_1 offset.
-	if ((pAd->ARssiOffset1 < -10) || (pAd->ARssiOffset1 > 10))
-		pAd->ARssiOffset1 = 0;
-
-	//Validate 11a RSSI_2 offset.
-	if ((pAd->ARssiOffset2 < -10) || (pAd->ARssiOffset2 > 10))
-		pAd->ARssiOffset2 = 0;
-
-	//
-	// Get LED Setting.
-	//
-	RT28xx_EEPROM_READ16(pAd, 0x3a, value);
-	pAd->LedCntl.word = (value&0xff00) >> 8;
-	RT28xx_EEPROM_READ16(pAd, EEPROM_LED1_OFFSET, value);
-	pAd->Led1 = value;
-	RT28xx_EEPROM_READ16(pAd, EEPROM_LED2_OFFSET, value);
-	pAd->Led2 = value;
-	RT28xx_EEPROM_READ16(pAd, EEPROM_LED3_OFFSET, value);
-	pAd->Led3 = value;
-
-	RTMPReadTxPwrPerRate(pAd);
-
-#ifdef SINGLE_SKU
-	//pAd->CommonCfg.DefineMaxTxPwr = RTMP_EEPROM_READ16(pAd, EEPROM_DEFINE_MAX_TXPWR);
-	RT28xx_EEPROM_READ16(pAd, EEPROM_DEFINE_MAX_TXPWR, pAd->CommonCfg.DefineMaxTxPwr);
-#endif // SINGLE_SKU //
-#ifdef RT30xx
-	if (IS_RT30xx(pAd))
-	{
-		eFusePhysicalReadRegisters(pAd, EFUSE_TAG, 2, &value);
-		pAd->EFuseTag = (value & 0xff);
-	}
-#endif // RT30xx //
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICReadEEPROMParameters\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Set default value from EEPROM
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	NICInitAsicFromEEPROM(
-	IN	PRTMP_ADAPTER	pAd)
-{
-#ifdef CONFIG_STA_SUPPORT
-	UINT32					data = 0;
-	UCHAR	BBPR1 = 0;
-#endif // CONFIG_STA_SUPPORT //
-	USHORT					i;
-	EEPROM_ANTENNA_STRUC	Antenna;
-	EEPROM_NIC_CONFIG2_STRUC    NicConfig2;
-	UCHAR	BBPR3 = 0;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICInitAsicFromEEPROM\n"));
-	for(i = 3; i < NUM_EEPROM_BBP_PARMS; i++)
-	{
-		UCHAR BbpRegIdx, BbpValue;
-
-		if ((pAd->EEPROMDefaultValue[i] != 0xFFFF) && (pAd->EEPROMDefaultValue[i] != 0))
-		{
-			BbpRegIdx = (UCHAR)(pAd->EEPROMDefaultValue[i] >> 8);
-			BbpValue  = (UCHAR)(pAd->EEPROMDefaultValue[i] & 0xff);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BbpRegIdx, BbpValue);
-		}
-	}
-
-	Antenna.word = pAd->EEPROMDefaultValue[0];
-	if (Antenna.word == 0xFFFF)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("E2PROM error, hard code as 0x%04x\n", Antenna.word));
-		BUG_ON(Antenna.word == 0xFFFF);
-	}
-	pAd->Mlme.RealRxPath = (UCHAR) Antenna.field.RxPath;
-	pAd->RfIcType = (UCHAR) Antenna.field.RfIcType;
-
-	DBGPRINT(RT_DEBUG_WARN, ("pAd->RfIcType = %d, RealRxPath=%d, TxPath = %d\n", pAd->RfIcType, pAd->Mlme.RealRxPath,Antenna.field.TxPath));
-
-	// Save the antenna for future use
-	pAd->Antenna.word = Antenna.word;
-
-	NicConfig2.word = pAd->EEPROMDefaultValue[1];
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if ((NicConfig2.word & 0x00ff) == 0xff)
-		{
-			NicConfig2.word &= 0xff00;
-		}
-
-		if ((NicConfig2.word >> 8) == 0xff)
-		{
-			NicConfig2.word &= 0x00ff;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Save the antenna for future use
-	pAd->NicConfig2.word = NicConfig2.word;
-
-	// set default antenna as main
-	if (pAd->RfIcType == RFIC_3020)
-		AsicSetRxAnt(pAd, pAd->RxAnt.Pair1PrimaryRxAnt);
-
-	//
-	// Send LED Setting to MCU.
-	//
-	if (pAd->LedCntl.word == 0xFF)
-	{
-		pAd->LedCntl.word = 0x01;
-		pAd->Led1 = 0x5555;
-		pAd->Led2 = 0x2221;
-
-#ifdef RT2870
-		pAd->Led3 = 0x5627;
-#endif // RT2870 //
-	}
-
-	AsicSendCommandToMcu(pAd, 0x52, 0xff, (UCHAR)pAd->Led1, (UCHAR)(pAd->Led1 >> 8));
-	AsicSendCommandToMcu(pAd, 0x53, 0xff, (UCHAR)pAd->Led2, (UCHAR)(pAd->Led2 >> 8));
-	AsicSendCommandToMcu(pAd, 0x54, 0xff, (UCHAR)pAd->Led3, (UCHAR)(pAd->Led3 >> 8));
-    pAd->LedIndicatorStregth = 0xFF;
-    RTMPSetSignalLED(pAd, -100);	// Force signal strength Led to be turned off, before link up
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Read Hardware controlled Radio state enable bit
-		if (NicConfig2.field.HardwareRadioControl == 1)
-		{
-			pAd->StaCfg.bHardwareRadio = TRUE;
-
-			// Read GPIO pin2 as Hardware controlled radio state
-			RTMP_IO_READ32(pAd, GPIO_CTRL_CFG, &data);
-			if ((data & 0x04) == 0)
-			{
-				pAd->StaCfg.bHwRadio = FALSE;
-				pAd->StaCfg.bRadio = FALSE;
-//				RTMP_IO_WRITE32(pAd, PWR_PIN_CFG, 0x00001818);
-				RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
-			}
-		}
-		else
-			pAd->StaCfg.bHardwareRadio = FALSE;
-
-		if (pAd->StaCfg.bRadio == FALSE)
-		{
-			RTMPSetLED(pAd, LED_RADIO_OFF);
-		}
-		else
-		{
-			RTMPSetLED(pAd, LED_RADIO_ON);
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Turn off patching for cardbus controller
-	if (NicConfig2.field.CardbusAcceleration == 1)
-	{
-//		pAd->bTest1 = TRUE;
-	}
-
-	if (NicConfig2.field.DynamicTxAgcControl == 1)
-		pAd->bAutoTxAgcA = pAd->bAutoTxAgcG = TRUE;
-	else
-		pAd->bAutoTxAgcA = pAd->bAutoTxAgcG = FALSE;
-	//
-	// Since BBP has been progamed, to make sure BBP setting will be
-	// upate inside of AsicAntennaSelect, so reset to UNKNOWN_BAND!!
-	//
-	pAd->CommonCfg.BandState = UNKNOWN_BAND;
-
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BBPR3);
-	BBPR3 &= (~0x18);
-	if(pAd->Antenna.field.RxPath == 3)
-	{
-		BBPR3 |= (0x10);
-	}
-	else if(pAd->Antenna.field.RxPath == 2)
-	{
-		BBPR3 |= (0x8);
-	}
-	else if(pAd->Antenna.field.RxPath == 1)
-	{
-		BBPR3 |= (0x0);
-	}
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BBPR3);
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Handle the difference when 1T
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BBPR1);
-		if(pAd->Antenna.field.TxPath == 1)
-		{
-		BBPR1 &= (~0x18);
-		}
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BBPR1);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Use Hw Radio Control Pin=%d; if used Pin=%d;\n", pAd->CommonCfg.bHardwareRadio, pAd->CommonCfg.bHardwareRadio));
-	}
-#endif // CONFIG_STA_SUPPORT //
-	DBGPRINT(RT_DEBUG_TRACE, ("TxPath = %d, RxPath = %d, RFIC=%d, Polar+LED mode=%x\n", pAd->Antenna.field.TxPath, pAd->Antenna.field.RxPath, pAd->RfIcType, pAd->LedCntl.word));
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICInitAsicFromEEPROM\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Initialize NIC hardware
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS	NICInitializeAdapter(
-	IN	PRTMP_ADAPTER	pAd,
-	IN   BOOLEAN    bHardReset)
-{
-	NDIS_STATUS     Status = NDIS_STATUS_SUCCESS;
-	WPDMA_GLO_CFG_STRUC	GloCfg;
-//	INT_MASK_CSR_STRUC		IntMask;
-	ULONG	i =0, j=0;
-	AC_TXOP_CSR0_STRUC	csr0;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICInitializeAdapter\n"));
-
-	// 3. Set DMA global configuration except TX_DMA_EN and RX_DMA_EN bits:
-retry:
-	i = 0;
-	do
-	{
-		RTMP_IO_READ32(pAd, WPDMA_GLO_CFG, &GloCfg.word);
-		if ((GloCfg.field.TxDMABusy == 0)  && (GloCfg.field.RxDMABusy == 0))
-			break;
-
-		RTMPusecDelay(1000);
-		i++;
-	}while ( i<100);
-	DBGPRINT(RT_DEBUG_TRACE, ("<== DMA offset 0x208 = 0x%x\n", GloCfg.word));
-	GloCfg.word &= 0xff0;
-	GloCfg.field.EnTXWriteBackDDONE =1;
-	RTMP_IO_WRITE32(pAd, WPDMA_GLO_CFG, GloCfg.word);
-
-	// Record HW Beacon offset
-	pAd->BeaconOffset[0] = HW_BEACON_BASE0;
-	pAd->BeaconOffset[1] = HW_BEACON_BASE1;
-	pAd->BeaconOffset[2] = HW_BEACON_BASE2;
-	pAd->BeaconOffset[3] = HW_BEACON_BASE3;
-	pAd->BeaconOffset[4] = HW_BEACON_BASE4;
-	pAd->BeaconOffset[5] = HW_BEACON_BASE5;
-	pAd->BeaconOffset[6] = HW_BEACON_BASE6;
-	pAd->BeaconOffset[7] = HW_BEACON_BASE7;
-
-	//
-	// write all shared Ring's base address into ASIC
-	//
-
-	// asic simulation sequence put this ahead before loading firmware.
-	// pbf hardware reset
-
-	// Initialze ASIC for TX & Rx operation
-	if (NICInitializeAsic(pAd , bHardReset) != NDIS_STATUS_SUCCESS)
-	{
-		if (j++ == 0)
-		{
-			NICLoadFirmware(pAd);
-			goto retry;
-		}
-		return NDIS_STATUS_FAILURE;
-	}
-
-
-
-
-	// WMM parameter
-	csr0.word = 0;
-	RTMP_IO_WRITE32(pAd, WMM_TXOP0_CFG, csr0.word);
-	if (pAd->CommonCfg.PhyMode == PHY_11B)
-	{
-		csr0.field.Ac0Txop = 192;	// AC_VI: 192*32us ~= 6ms
-		csr0.field.Ac1Txop = 96;	// AC_VO: 96*32us  ~= 3ms
-	}
-	else
-	{
-		csr0.field.Ac0Txop = 96;	// AC_VI: 96*32us ~= 3ms
-		csr0.field.Ac1Txop = 48;	// AC_VO: 48*32us ~= 1.5ms
-	}
-	RTMP_IO_WRITE32(pAd, WMM_TXOP1_CFG, csr0.word);
-
-
-
-
-	// reset action
-	// Load firmware
-	//  Status = NICLoadFirmware(pAd);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICInitializeAdapter\n"));
-	return Status;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Initialize ASIC
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS	NICInitializeAsic(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  BOOLEAN		bHardReset)
-{
-	ULONG			Index = 0;
-	UCHAR			R0 = 0xff;
-	UINT32			MacCsr12 = 0, Counter = 0;
-#ifdef RT2870
-	UINT32			MacCsr0 = 0;
-	NTSTATUS		Status;
-	UCHAR			Value = 0xff;
-#endif // RT2870 //
-#ifdef RT30xx
-	UINT32			eFuseCtrl;
-#endif // RT30xx //
-	USHORT			KeyIdx;
-	INT				i,apidx;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICInitializeAsic\n"));
-
-
-#ifdef RT2870
-	//
-	// Make sure MAC gets ready after NICLoadFirmware().
-	//
-	Index = 0;
-
-	//To avoid hang-on issue when interface up in kernel 2.4,
-	//we use a local variable "MacCsr0" instead of using "pAd->MACVersion" directly.
-	do
-	{
-		RTMP_IO_READ32(pAd, MAC_CSR0, &MacCsr0);
-
-		if ((MacCsr0 != 0x00) && (MacCsr0 != 0xFFFFFFFF))
-			break;
-
-		RTMPusecDelay(10);
-	} while (Index++ < 100);
-
-	pAd->MACVersion = MacCsr0;
-	DBGPRINT(RT_DEBUG_TRACE, ("MAC_CSR0  [ Ver:Rev=0x%08x]\n", pAd->MACVersion));
-	// turn on bit13 (set to zero) after rt2860D. This is to solve high-current issue.
-	RTMP_IO_READ32(pAd, PBF_SYS_CTRL, &MacCsr12);
-	MacCsr12 &= (~0x2000);
-	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, MacCsr12);
-
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x3);
-	RTMP_IO_WRITE32(pAd, USB_DMA_CFG, 0x0);
-	Status = RTUSBVenderReset(pAd);
-
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x0);
-
-	// Initialize MAC register to default value
-	for(Index=0; Index<NUM_MAC_REG_PARMS; Index++)
-	{
-#ifdef RT3070
-		if ((MACRegTable[Index].Register == TX_SW_CFG0) && (IS_RT3070(pAd) || IS_RT3071(pAd)))
-		{
-			MACRegTable[Index].Value = 0x00000400;
-		}
-#endif // RT3070 //
-		RTMP_IO_WRITE32(pAd, (USHORT)MACRegTable[Index].Register, MACRegTable[Index].Value);
-	}
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		for (Index = 0; Index < NUM_STA_MAC_REG_PARMS; Index++)
-		{
-			RTMP_IO_WRITE32(pAd, (USHORT)STAMACRegTable[Index].Register, STAMACRegTable[Index].Value);
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-#endif // RT2870 //
-
-#ifdef RT30xx
-	// Initialize RT3070 serial MAc registers which is different from RT2870 serial
-	if (IS_RT3090(pAd))
-	{
-		RTMP_IO_WRITE32(pAd, TX_SW_CFG1, 0);
-
-		// RT3071 version E has fixed this issue
-		if ((pAd->MACVersion & 0xffff) < 0x0211)
-		{
-			if (pAd->NicConfig2.field.DACTestBit == 1)
-			{
-				RTMP_IO_WRITE32(pAd, TX_SW_CFG2, 0x1F);	// To fix throughput drop drastically
-			}
-			else
-			{
-				RTMP_IO_WRITE32(pAd, TX_SW_CFG2, 0x0F);	// To fix throughput drop drastically
-			}
-		}
-		else
-		{
-			RTMP_IO_WRITE32(pAd, TX_SW_CFG2, 0x0);
-		}
-	}
-	else if (IS_RT3070(pAd))
-	{
-		RTMP_IO_WRITE32(pAd, TX_SW_CFG1, 0);
-		RTMP_IO_WRITE32(pAd, TX_SW_CFG2, 0x1F);	// To fix throughput drop drastically
-	}
-#endif // RT30xx //
-
-	//
-	// Before program BBP, we need to wait BBP/RF get wake up.
-	//
-	Index = 0;
-	do
-	{
-		RTMP_IO_READ32(pAd, MAC_STATUS_CFG, &MacCsr12);
-
-		if ((MacCsr12 & 0x03) == 0)	// if BB.RF is stable
-			break;
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Check MAC_STATUS_CFG  = Busy = %x\n", MacCsr12));
-		RTMPusecDelay(1000);
-	} while (Index++ < 100);
-
-    // The commands to firmware should be after these commands, these commands will init firmware
-	// PCI and USB are not the same because PCI driver needs to wait for PCI bus ready
-	RTMP_IO_WRITE32(pAd, H2M_BBP_AGENT, 0);	// initialize BBP R/W access agent
-	RTMP_IO_WRITE32(pAd, H2M_MAILBOX_CSR, 0);
-	RTMPusecDelay(1000);
-
-	// Read BBP register, make sure BBP is up and running before write new data
-	Index = 0;
-	do
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R0, &R0);
-		DBGPRINT(RT_DEBUG_TRACE, ("BBP version = %x\n", R0));
-	} while ((++Index < 20) && ((R0 == 0xff) || (R0 == 0x00)));
-	//ASSERT(Index < 20); //this will cause BSOD on Check-build driver
-
-	if ((R0 == 0xff) || (R0 == 0x00))
-		return NDIS_STATUS_FAILURE;
-
-	// Initialize BBP register to default value
-	for (Index = 0; Index < NUM_BBP_REG_PARMS; Index++)
-	{
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBPRegTable[Index].Register, BBPRegTable[Index].Value);
-	}
-
-	// for rt2860E and after, init BBP_R84 with 0x19. This is for extension channel overlapping IOT.
-	// RT3090 should not program BBP R84 to 0x19, otherwise TX will block.
-	if (((pAd->MACVersion&0xffff) != 0x0101) && (!IS_RT30xx(pAd)))
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R84, 0x19);
-
-// add by johnli, RF power sequence setup
-#ifdef RT30xx
-	if (IS_RT30xx(pAd))
-	{	//update for RT3070/71/72/90/91/92.
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R79, 0x13);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R80, 0x05);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R81, 0x33);
-	}
-
-	if (IS_RT3090(pAd))
-	{
-		UCHAR		bbpreg=0;
-
-		// enable DC filter
-		if ((pAd->MACVersion & 0xffff) >= 0x0211)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R103, 0xc0);
-		}
-
-		// improve power consumption
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R138, &bbpreg);
-		if (pAd->Antenna.field.TxPath == 1)
-		{
-			// turn off tx DAC_1
-			bbpreg = (bbpreg | 0x20);
-		}
-
-		if (pAd->Antenna.field.RxPath == 1)
-		{
-			// turn off tx ADC_1
-			bbpreg &= (~0x2);
-		}
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R138, bbpreg);
-
-		// improve power consumption in RT3071 Ver.E
-		if ((pAd->MACVersion & 0xffff) >= 0x0211)
-		{
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R31, &bbpreg);
-			bbpreg &= (~0x3);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R31, bbpreg);
-		}
-	}
-#endif // RT30xx //
-// end johnli
-
-	if (pAd->MACVersion == 0x28600100)
-	{
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x16);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x12);
-    }
-
-	if (pAd->MACVersion >= RALINK_2880E_VERSION && pAd->MACVersion < RALINK_3070_VERSION) // 3*3
-	{
-		// enlarge MAX_LEN_CFG
-		UINT32 csr;
-		RTMP_IO_READ32(pAd, MAX_LEN_CFG, &csr);
-		csr &= 0xFFF;
-		csr |= 0x2000;
-		RTMP_IO_WRITE32(pAd, MAX_LEN_CFG, csr);
-	}
-
-#ifdef RT2870
-{
-	UCHAR	MAC_Value[]={0xff,0xff,0xff,0xff,0xff,0xff,0xff,0,0};
-
-	//Initialize WCID table
-	Value = 0xff;
-	for(Index =0 ;Index < 254;Index++)
-	{
-		RTUSBMultiWrite(pAd, (USHORT)(MAC_WCID_BASE + Index * 8), MAC_Value, 8);
-	}
-}
-#endif // RT2870 //
-
-	// Add radio off control
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		if (pAd->StaCfg.bRadio == FALSE)
-		{
-//			RTMP_IO_WRITE32(pAd, PWR_PIN_CFG, 0x00001818);
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF);
-			DBGPRINT(RT_DEBUG_TRACE, ("Set Radio Off\n"));
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Clear raw counters
-	RTMP_IO_READ32(pAd, RX_STA_CNT0, &Counter);
-	RTMP_IO_READ32(pAd, RX_STA_CNT1, &Counter);
-	RTMP_IO_READ32(pAd, RX_STA_CNT2, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT0, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT1, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT2, &Counter);
-
-	// ASIC will keep garbage value after boot
-	// Clear all seared key table when initial
-	// This routine can be ignored in radio-ON/OFF operation.
-	if (bHardReset)
-	{
-		for (KeyIdx = 0; KeyIdx < 4; KeyIdx++)
-		{
-			RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE + 4*KeyIdx, 0);
-		}
-
-	// Clear all pairwise key table when initial
-	for (KeyIdx = 0; KeyIdx < 256; KeyIdx++)
-	{
-		RTMP_IO_WRITE32(pAd, MAC_WCID_ATTRIBUTE_BASE + (KeyIdx * HW_WCID_ATTRI_SIZE), 1);
-	}
-	}
-
-	// assert HOST ready bit
-//  RTMP_IO_WRITE32(pAd, MAC_CSR1, 0x0); // 2004-09-14 asked by Mark
-//  RTMP_IO_WRITE32(pAd, MAC_CSR1, 0x4);
-
-	// It isn't necessary to clear this space when not hard reset.
-	if (bHardReset == TRUE)
-	{
-		// clear all on-chip BEACON frame space
-		for (apidx = 0; apidx < HW_BEACON_MAX_COUNT; apidx++)
-		{
-			for (i = 0; i < HW_BEACON_OFFSET>>2; i+=4)
-				RTMP_IO_WRITE32(pAd, pAd->BeaconOffset[apidx] + i, 0x00);
-		}
-	}
-#ifdef RT2870
-	AsicDisableSync(pAd);
-	// Clear raw counters
-	RTMP_IO_READ32(pAd, RX_STA_CNT0, &Counter);
-	RTMP_IO_READ32(pAd, RX_STA_CNT1, &Counter);
-	RTMP_IO_READ32(pAd, RX_STA_CNT2, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT0, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT1, &Counter);
-	RTMP_IO_READ32(pAd, TX_STA_CNT2, &Counter);
-	// Default PCI clock cycle per ms is different as default setting, which is based on PCI.
-	RTMP_IO_READ32(pAd, USB_CYC_CFG, &Counter);
-	Counter&=0xffffff00;
-	Counter|=0x000001e;
-	RTMP_IO_WRITE32(pAd, USB_CYC_CFG, Counter);
-#endif // RT2870 //
-#ifdef RT30xx
-	pAd->bUseEfuse=FALSE;
-	RTMP_IO_READ32(pAd, EFUSE_CTRL, &eFuseCtrl);
-	pAd->bUseEfuse = ( (eFuseCtrl & 0x80000000) == 0x80000000) ? 1 : 0;
-	if(pAd->bUseEfuse)
-	{
-			DBGPRINT(RT_DEBUG_TRACE, ("NVM is Efuse\n"));
-	}
-	else
-	{
-			DBGPRINT(RT_DEBUG_TRACE, ("NVM is EEPROM\n"));
-
-	}
-#endif // RT30xx //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// for rt2860E and after, init TXOP_CTRL_CFG with 0x583f. This is for extension channel overlapping IOT.
-		if ((pAd->MACVersion&0xffff) != 0x0101)
-			RTMP_IO_WRITE32(pAd, TXOP_CTRL_CFG, 0x583f);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICInitializeAsic\n"));
-	return NDIS_STATUS_SUCCESS;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Reset NIC Asics
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-		Reset NIC to initial state AS IS system boot up time.
-
-	========================================================================
-*/
-VOID	NICIssueReset(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UINT32	Value = 0;
-	DBGPRINT(RT_DEBUG_TRACE, ("--> NICIssueReset\n"));
-
-	// Abort Tx, prevent ASIC from writing to Host memory
-	//RTMP_IO_WRITE32(pAd, TX_CNTL_CSR, 0x001f0000);
-
-	// Disable Rx, register value supposed will remain after reset
-	RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-	Value &= (0xfffffff3);
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-	// Issue reset and clear from reset state
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x03); // 2004-09-17 change from 0x01
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x00);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- NICIssueReset\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Check ASIC registers and find any reason the system might hang
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-BOOLEAN	NICCheckForHang(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	return (FALSE);
-}
-
-VOID NICUpdateFifoStaCounters(
-	IN PRTMP_ADAPTER pAd)
-{
-	TX_STA_FIFO_STRUC	StaFifo;
-	MAC_TABLE_ENTRY		*pEntry;
-	UCHAR				i = 0;
-	UCHAR			pid = 0, wcid = 0;
-	CHAR				reTry;
-	UCHAR				succMCS;
-
-#ifdef RALINK_ATE
-	/* Nothing to do in ATE mode */
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-		do
-		{
-			RTMP_IO_READ32(pAd, TX_STA_FIFO, &StaFifo.word);
-
-			if (StaFifo.field.bValid == 0)
-				break;
-
-			wcid = (UCHAR)StaFifo.field.wcid;
-
-
-		/* ignore NoACK and MGMT frame use 0xFF as WCID */
-			if ((StaFifo.field.TxAckRequired == 0) || (wcid >= MAX_LEN_OF_MAC_TABLE))
-			{
-				i++;
-				continue;
-			}
-
-			/* PID store Tx MCS Rate */
-			pid = (UCHAR)StaFifo.field.PidType;
-
-			pEntry = &pAd->MacTab.Content[wcid];
-
-			pEntry->DebugFIFOCount++;
-
-#ifdef DOT11_N_SUPPORT
-			if (StaFifo.field.TxBF) // 3*3
-				pEntry->TxBFCount++;
-#endif // DOT11_N_SUPPORT //
-
-#ifdef UAPSD_AP_SUPPORT
-			UAPSD_SP_AUE_Handle(pAd, pEntry, StaFifo.field.TxSuccess);
-#endif // UAPSD_AP_SUPPORT //
-
-			if (!StaFifo.field.TxSuccess)
-			{
-				pEntry->FIFOCount++;
-				pEntry->OneSecTxFailCount++;
-
-				if (pEntry->FIFOCount >= 1)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("#"));
-#ifdef DOT11_N_SUPPORT
-					pEntry->NoBADataCountDown = 64;
-#endif // DOT11_N_SUPPORT //
-
-					if(pEntry->PsMode == PWR_ACTIVE)
-					{
-#ifdef DOT11_N_SUPPORT
-						int tid;
-						for (tid=0; tid<NUM_OF_TID; tid++)
-						{
-							BAOriSessionTearDown(pAd, pEntry->Aid,  tid, FALSE, FALSE);
-						}
-#endif // DOT11_N_SUPPORT //
-
-						// Update the continuous transmission counter except PS mode
-						pEntry->ContinueTxFailCnt++;
-					}
-					else
-					{
-						// Clear the FIFOCount when sta in Power Save mode. Basically we assume
-						//     this tx error happened due to sta just go to sleep.
-						pEntry->FIFOCount = 0;
-						pEntry->ContinueTxFailCnt = 0;
-					}
-					//pEntry->FIFOCount = 0;
-				}
-				//pEntry->bSendBAR = TRUE;
-			}
-			else
-			{
-#ifdef DOT11_N_SUPPORT
-				if ((pEntry->PsMode != PWR_SAVE) && (pEntry->NoBADataCountDown > 0))
-				{
-					pEntry->NoBADataCountDown--;
-					if (pEntry->NoBADataCountDown==0)
-					{
-						DBGPRINT(RT_DEBUG_TRACE, ("@\n"));
-					}
-				}
-#endif // DOT11_N_SUPPORT //
-				pEntry->FIFOCount = 0;
-				pEntry->OneSecTxNoRetryOkCount++;
-				// update NoDataIdleCount when sucessful send packet to STA.
-				pEntry->NoDataIdleCount = 0;
-				pEntry->ContinueTxFailCnt = 0;
-			}
-
-			succMCS = StaFifo.field.SuccessRate & 0x7F;
-
-			reTry = pid - succMCS;
-
-			if (StaFifo.field.TxSuccess)
-			{
-				pEntry->TXMCSExpected[pid]++;
-				if (pid == succMCS)
-				{
-					pEntry->TXMCSSuccessful[pid]++;
-				}
-				else
-				{
-					pEntry->TXMCSAutoFallBack[pid][succMCS]++;
-				}
-			}
-			else
-			{
-				pEntry->TXMCSFailed[pid]++;
-			}
-
-			if (reTry > 0)
-			{
-				if ((pid >= 12) && succMCS <=7)
-				{
-					reTry -= 4;
-				}
-				pEntry->OneSecTxRetryOkCount += reTry;
-			}
-
-			i++;
-			// ASIC store 16 stack
-		} while ( i < (2*TX_RING_SIZE) );
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Read statistical counters from hardware registers and record them
-		in software variables for later on query
-
-	Arguments:
-		pAd					Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-VOID NICUpdateRawCounters(
-	IN PRTMP_ADAPTER pAd)
-{
-	UINT32	OldValue;//, Value2;
-	//ULONG	PageSum, OneSecTransmitCount;
-	//ULONG	TxErrorRatio, Retry, Fail;
-	RX_STA_CNT0_STRUC	 RxStaCnt0;
-	RX_STA_CNT1_STRUC   RxStaCnt1;
-	RX_STA_CNT2_STRUC   RxStaCnt2;
-	TX_STA_CNT0_STRUC 	 TxStaCnt0;
-	TX_STA_CNT1_STRUC	 StaTx1;
-	TX_STA_CNT2_STRUC	 StaTx2;
-	TX_AGG_CNT_STRUC	TxAggCnt;
-	TX_AGG_CNT0_STRUC	TxAggCnt0;
-	TX_AGG_CNT1_STRUC	TxAggCnt1;
-	TX_AGG_CNT2_STRUC	TxAggCnt2;
-	TX_AGG_CNT3_STRUC	TxAggCnt3;
-	TX_AGG_CNT4_STRUC	TxAggCnt4;
-	TX_AGG_CNT5_STRUC	TxAggCnt5;
-	TX_AGG_CNT6_STRUC	TxAggCnt6;
-	TX_AGG_CNT7_STRUC	TxAggCnt7;
-
-	RTMP_IO_READ32(pAd, RX_STA_CNT0, &RxStaCnt0.word);
-	RTMP_IO_READ32(pAd, RX_STA_CNT2, &RxStaCnt2.word);
-
-	{
-		RTMP_IO_READ32(pAd, RX_STA_CNT1, &RxStaCnt1.word);
-	    // Update RX PLCP error counter
-	    pAd->PrivateInfo.PhyRxErrCnt += RxStaCnt1.field.PlcpErr;
-		// Update False CCA counter
-		pAd->RalinkCounters.OneSecFalseCCACnt += RxStaCnt1.field.FalseCca;
-	}
-
-	// Update FCS counters
-	OldValue= pAd->WlanCounters.FCSErrorCount.u.LowPart;
-	pAd->WlanCounters.FCSErrorCount.u.LowPart += (RxStaCnt0.field.CrcErr); // >> 7);
-	if (pAd->WlanCounters.FCSErrorCount.u.LowPart < OldValue)
-		pAd->WlanCounters.FCSErrorCount.u.HighPart++;
-
-	// Add FCS error count to private counters
-	pAd->RalinkCounters.OneSecRxFcsErrCnt += RxStaCnt0.field.CrcErr;
-	OldValue = pAd->RalinkCounters.RealFcsErrCount.u.LowPart;
-	pAd->RalinkCounters.RealFcsErrCount.u.LowPart += RxStaCnt0.field.CrcErr;
-	if (pAd->RalinkCounters.RealFcsErrCount.u.LowPart < OldValue)
-		pAd->RalinkCounters.RealFcsErrCount.u.HighPart++;
-
-	// Update Duplicate Rcv check
-	pAd->RalinkCounters.DuplicateRcv += RxStaCnt2.field.RxDupliCount;
-	pAd->WlanCounters.FrameDuplicateCount.u.LowPart += RxStaCnt2.field.RxDupliCount;
-	// Update RX Overflow counter
-	pAd->Counters8023.RxNoBuffer += (RxStaCnt2.field.RxFifoOverflowCount);
-
-	//pAd->RalinkCounters.RxCount = 0;
-#ifdef RT2870
-	if (pAd->RalinkCounters.RxCount != pAd->watchDogRxCnt)
-	{
-		pAd->watchDogRxCnt = pAd->RalinkCounters.RxCount;
-		pAd->watchDogRxOverFlowCnt = 0;
-	}
-	else
-	{
-		if (RxStaCnt2.field.RxFifoOverflowCount)
-			pAd->watchDogRxOverFlowCnt++;
-		else
-			pAd->watchDogRxOverFlowCnt = 0;
-	}
-#endif // RT2870 //
-
-
-	//if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED) ||
-	//	(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_TX_RATE_SWITCH_ENABLED) && (pAd->MacTab.Size != 1)))
-	if (!pAd->bUpdateBcnCntDone)
-	{
-	// Update BEACON sent count
-	RTMP_IO_READ32(pAd, TX_STA_CNT0, &TxStaCnt0.word);
-	RTMP_IO_READ32(pAd, TX_STA_CNT1, &StaTx1.word);
-	RTMP_IO_READ32(pAd, TX_STA_CNT2, &StaTx2.word);
-	pAd->RalinkCounters.OneSecBeaconSentCnt += TxStaCnt0.field.TxBeaconCount;
-	pAd->RalinkCounters.OneSecTxRetryOkCount += StaTx1.field.TxRetransmit;
-	pAd->RalinkCounters.OneSecTxNoRetryOkCount += StaTx1.field.TxSuccess;
-	pAd->RalinkCounters.OneSecTxFailCount += TxStaCnt0.field.TxFailCount;
-	pAd->WlanCounters.TransmittedFragmentCount.u.LowPart += StaTx1.field.TxSuccess;
-	pAd->WlanCounters.RetryCount.u.LowPart += StaTx1.field.TxRetransmit;
-	pAd->WlanCounters.FailedCount.u.LowPart += TxStaCnt0.field.TxFailCount;
-	}
-
-	//if (pAd->bStaFifoTest == TRUE)
-	{
-		RTMP_IO_READ32(pAd, TX_AGG_CNT, &TxAggCnt.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT0, &TxAggCnt0.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT1, &TxAggCnt1.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT2, &TxAggCnt2.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT3, &TxAggCnt3.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT4, &TxAggCnt4.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT5, &TxAggCnt5.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT6, &TxAggCnt6.word);
-		RTMP_IO_READ32(pAd, TX_AGG_CNT7, &TxAggCnt7.word);
-		pAd->RalinkCounters.TxAggCount += TxAggCnt.field.AggTxCount;
-		pAd->RalinkCounters.TxNonAggCount += TxAggCnt.field.NonAggTxCount;
-		pAd->RalinkCounters.TxAgg1MPDUCount += TxAggCnt0.field.AggSize1Count;
-		pAd->RalinkCounters.TxAgg2MPDUCount += TxAggCnt0.field.AggSize2Count;
-
-		pAd->RalinkCounters.TxAgg3MPDUCount += TxAggCnt1.field.AggSize3Count;
-		pAd->RalinkCounters.TxAgg4MPDUCount += TxAggCnt1.field.AggSize4Count;
-		pAd->RalinkCounters.TxAgg5MPDUCount += TxAggCnt2.field.AggSize5Count;
-		pAd->RalinkCounters.TxAgg6MPDUCount += TxAggCnt2.field.AggSize6Count;
-
-		pAd->RalinkCounters.TxAgg7MPDUCount += TxAggCnt3.field.AggSize7Count;
-		pAd->RalinkCounters.TxAgg8MPDUCount += TxAggCnt3.field.AggSize8Count;
-		pAd->RalinkCounters.TxAgg9MPDUCount += TxAggCnt4.field.AggSize9Count;
-		pAd->RalinkCounters.TxAgg10MPDUCount += TxAggCnt4.field.AggSize10Count;
-
-		pAd->RalinkCounters.TxAgg11MPDUCount += TxAggCnt5.field.AggSize11Count;
-		pAd->RalinkCounters.TxAgg12MPDUCount += TxAggCnt5.field.AggSize12Count;
-		pAd->RalinkCounters.TxAgg13MPDUCount += TxAggCnt6.field.AggSize13Count;
-		pAd->RalinkCounters.TxAgg14MPDUCount += TxAggCnt6.field.AggSize14Count;
-
-		pAd->RalinkCounters.TxAgg15MPDUCount += TxAggCnt7.field.AggSize15Count;
-		pAd->RalinkCounters.TxAgg16MPDUCount += TxAggCnt7.field.AggSize16Count;
-
-		// Calculate the transmitted A-MPDU count
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += TxAggCnt0.field.AggSize1Count;
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt0.field.AggSize2Count / 2);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt1.field.AggSize3Count / 3);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt1.field.AggSize4Count / 4);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt2.field.AggSize5Count / 5);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt2.field.AggSize6Count / 6);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt3.field.AggSize7Count / 7);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt3.field.AggSize8Count / 8);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt4.field.AggSize9Count / 9);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt4.field.AggSize10Count / 10);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt5.field.AggSize11Count / 11);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt5.field.AggSize12Count / 12);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt6.field.AggSize13Count / 13);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt6.field.AggSize14Count / 14);
-
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt7.field.AggSize15Count / 15);
-		pAd->RalinkCounters.TransmittedAMPDUCount.u.LowPart += (TxAggCnt7.field.AggSize16Count / 16);
-	}
-
-#ifdef DBG_DIAGNOSE
-	{
-		RtmpDiagStruct	*pDiag;
-		COUNTER_RALINK	*pRalinkCounters;
-		UCHAR			ArrayCurIdx, i;
-
-		pDiag = &pAd->DiagStruct;
-		pRalinkCounters = &pAd->RalinkCounters;
-		ArrayCurIdx = pDiag->ArrayCurIdx;
-
-		if (pDiag->inited == 0)
-		{
-			NdisZeroMemory(pDiag, sizeof(struct _RtmpDiagStrcut_));
-			pDiag->ArrayStartIdx = pDiag->ArrayCurIdx = 0;
-			pDiag->inited = 1;
-		}
-		else
-		{
-			// Tx
-			pDiag->TxFailCnt[ArrayCurIdx] = TxStaCnt0.field.TxFailCount;
-			pDiag->TxAggCnt[ArrayCurIdx] = TxAggCnt.field.AggTxCount;
-			pDiag->TxNonAggCnt[ArrayCurIdx] = TxAggCnt.field.NonAggTxCount;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][0] = TxAggCnt0.field.AggSize1Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][1] = TxAggCnt0.field.AggSize2Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][2] = TxAggCnt1.field.AggSize3Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][3] = TxAggCnt1.field.AggSize4Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][4] = TxAggCnt2.field.AggSize5Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][5] = TxAggCnt2.field.AggSize6Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][6] = TxAggCnt3.field.AggSize7Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][7] = TxAggCnt3.field.AggSize8Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][8] = TxAggCnt4.field.AggSize9Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][9] = TxAggCnt4.field.AggSize10Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][10] = TxAggCnt5.field.AggSize11Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][11] = TxAggCnt5.field.AggSize12Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][12] = TxAggCnt6.field.AggSize13Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][13] = TxAggCnt6.field.AggSize14Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][14] = TxAggCnt7.field.AggSize15Count;
-			pDiag->TxAMPDUCnt[ArrayCurIdx][15] = TxAggCnt7.field.AggSize16Count;
-
-			pDiag->RxCrcErrCnt[ArrayCurIdx] = RxStaCnt0.field.CrcErr;
-
-			INC_RING_INDEX(pDiag->ArrayCurIdx,  DIAGNOSE_TIME);
-			ArrayCurIdx = pDiag->ArrayCurIdx;
-			for (i =0; i < 9; i++)
-			{
-				pDiag->TxDescCnt[ArrayCurIdx][i]= 0;
-				pDiag->TxSWQueCnt[ArrayCurIdx][i] =0;
-				pDiag->TxMcsCnt[ArrayCurIdx][i] = 0;
-				pDiag->RxMcsCnt[ArrayCurIdx][i] = 0;
-			}
-			pDiag->TxDataCnt[ArrayCurIdx] = 0;
-			pDiag->TxFailCnt[ArrayCurIdx] = 0;
-			pDiag->RxDataCnt[ArrayCurIdx] = 0;
-			pDiag->RxCrcErrCnt[ArrayCurIdx]  = 0;
-//			for (i = 9; i < 16; i++)
-			for (i = 9; i < 24; i++) // 3*3
-			{
-				pDiag->TxDescCnt[ArrayCurIdx][i] = 0;
-				pDiag->TxMcsCnt[ArrayCurIdx][i] = 0;
-				pDiag->RxMcsCnt[ArrayCurIdx][i] = 0;
-}
-
-			if (pDiag->ArrayCurIdx == pDiag->ArrayStartIdx)
-				INC_RING_INDEX(pDiag->ArrayStartIdx,  DIAGNOSE_TIME);
-		}
-
-	}
-#endif // DBG_DIAGNOSE //
-
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Reset NIC from error
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-		Reset NIC from error state
-
-	========================================================================
-*/
-VOID	NICResetFromError(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	// Reset BBP (according to alex, reset ASIC will force reset BBP
-	// Therefore, skip the reset BBP
-	// RTMP_IO_WRITE32(pAd, MAC_CSR1, 0x2);
-
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x1);
-	// Remove ASIC from reset state
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0x0);
-
-	NICInitializeAdapter(pAd, FALSE);
-	NICInitAsicFromEEPROM(pAd);
-
-	// Switch to current channel, since during reset process, the connection should remains on.
-	AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-	AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		erase 8051 firmware image in MAC ASIC
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-VOID NICEraseFirmware(
-	IN PRTMP_ADAPTER pAd)
-{
-	ULONG i;
-
-	for(i=0; i<MAX_FIRMWARE_IMAGE_SIZE; i+=4)
-		RTMP_IO_WRITE32(pAd, FIRMWARE_IMAGE_BASE + i, 0);
-
-}/* End of NICEraseFirmware */
-
-/*
-	========================================================================
-
-	Routine Description:
-		Load 8051 firmware RT2561.BIN file into MAC ASIC
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		NDIS_STATUS_SUCCESS         firmware image load ok
-		NDIS_STATUS_FAILURE         image not found
-
-	IRQL = PASSIVE_LEVEL
-
-	========================================================================
-*/
-NDIS_STATUS NICLoadFirmware(
-	IN PRTMP_ADAPTER pAd)
-{
-#ifdef BIN_IN_FILE
-#define NICLF_DEFAULT_USE()	\
-	flg_default_firm_use = TRUE; \
-	printk("%s - Use default firmware!\n", __FUNCTION__);
-
-	NDIS_STATUS		Status = NDIS_STATUS_SUCCESS;
-	PUCHAR			src;
-	struct file		*srcf;
-	INT 			retval, orgfsuid, orgfsgid, i;
-   	mm_segment_t	orgfs;
-	PUCHAR			pFirmwareImage;
-	UINT			FileLength = 0;
-	UINT32			MacReg;
-	ULONG			Index;
-	ULONG			firm;
-	BOOLEAN			flg_default_firm_use = FALSE;
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("===> %s\n", __FUNCTION__));
-
-	/* init */
-	pFirmwareImage = NULL;
-	src = RTMP_FIRMWARE_FILE_NAME;
-
-	/* save uid and gid used for filesystem access.
-	   set user and group to 0 (root) */
-	orgfsuid = current->fsuid;
-	orgfsgid = current->fsgid;
-	current->fsuid = current->fsgid = 0;
-    orgfs = get_fs();
-    set_fs(KERNEL_DS);
-
-	pAd->FirmwareVersion = (FIRMWARE_MAJOR_VERSION << 8) + \
-						   FIRMWARE_MINOR_VERSION;
-
-
-	/* allocate firmware buffer */
-    pFirmwareImage = kmalloc(MAX_FIRMWARE_IMAGE_SIZE, MEM_ALLOC_FLAG);
-    if (pFirmwareImage == NULL)
-	{
-		/* allocate fail, use default firmware array in firmware.h */
-		printk("%s - Allocate memory fail!\n", __FUNCTION__);
-		NICLF_DEFAULT_USE();
-    }
-	else
-	{
-		/* allocate ok! zero the firmware buffer */
-		memset(pFirmwareImage, 0x00, MAX_FIRMWARE_IMAGE_SIZE);
-	} /* End of if */
-
-
-	/* if ok, read firmware file from *.bin file */
-	if (flg_default_firm_use == FALSE)
-	{
-		do
-		{
-			/* open the bin file */
-			srcf = filp_open(src, O_RDONLY, 0);
-
-			if (IS_ERR(srcf))
-			{
-				printk("%s - Error %ld opening %s\n",
-					   __FUNCTION__, -PTR_ERR(srcf), src);
-				NICLF_DEFAULT_USE();
-				break;
-			} /* End of if */
-
-			/* the object must have a read method */
-			if ((srcf->f_op == NULL) || (srcf->f_op->read == NULL))
-			{
-				printk("%s - %s does not have a write method\n", __FUNCTION__, src);
-				NICLF_DEFAULT_USE();
-				break;
-			} /* End of if */
-
-			/* read the firmware from the file *.bin */
-			FileLength = srcf->f_op->read(srcf,
-										  pFirmwareImage,
-										  MAX_FIRMWARE_IMAGE_SIZE,
-										  &srcf->f_pos);
-
-			if (FileLength != MAX_FIRMWARE_IMAGE_SIZE)
-			{
-				printk("%s: error file length (=%d) in RT2860AP.BIN\n",
-					   __FUNCTION__, FileLength);
-				NICLF_DEFAULT_USE();
-				break;
-			}
-			else
-			{
-				PUCHAR ptr = pFirmwareImage;
-				USHORT crc = 0xffff;
-
-
-				/* calculate firmware CRC */
-				for(i=0; i<(MAX_FIRMWARE_IMAGE_SIZE-2); i++, ptr++)
-					crc = ByteCRC16(BitReverse(*ptr), crc);
-				/* End of for */
-
-				if ((pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-2] != \
-								(UCHAR)BitReverse((UCHAR)(crc>>8))) ||
-					(pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-1] != \
-								(UCHAR)BitReverse((UCHAR)crc)))
-				{
-					/* CRC fail */
-					printk("%s: CRC = 0x%02x 0x%02x "
-						   "error, should be 0x%02x 0x%02x\n",
-						   __FUNCTION__,
-						   pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-2],
-						   pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-1],
-						   (UCHAR)(crc>>8), (UCHAR)(crc));
-					NICLF_DEFAULT_USE();
-					break;
-				}
-				else
-				{
-					/* firmware is ok */
-					pAd->FirmwareVersion = \
-						(pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-4] << 8) +
-						pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-3];
-
-					/* check if firmware version of the file is too old */
-					if ((pAd->FirmwareVersion) < \
-											((FIRMWARE_MAJOR_VERSION << 8) +
-									  	 	 FIRMWARE_MINOR_VERSION))
-					{
-						printk("%s: firmware version too old!\n", __FUNCTION__);
-						NICLF_DEFAULT_USE();
-						break;
-					} /* End of if */
-				} /* End of if */
-
-				DBGPRINT(RT_DEBUG_TRACE,
-						 ("NICLoadFirmware: CRC ok, ver=%d.%d\n",
-						  pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-4],
-						  pFirmwareImage[MAX_FIRMWARE_IMAGE_SIZE-3]));
-			} /* End of if (FileLength == MAX_FIRMWARE_IMAGE_SIZE) */
-			break;
-		} while(TRUE);
-
-		/* close firmware file */
-		if (IS_ERR(srcf))
-			;
-		else
-		{
-			retval = filp_close(srcf, NULL);
-			if (retval)
-			{
-				DBGPRINT(RT_DEBUG_ERROR,
-						 ("--> Error %d closing %s\n", -retval, src));
-			} /* End of if */
-		} /* End of if */
-	} /* End of if */
-
-
-	/* write firmware to ASIC */
-	if (flg_default_firm_use == TRUE)
-	{
-		/* use default fimeware, free allocated buffer */
-		if (pFirmwareImage != NULL)
-			kfree(pFirmwareImage);
-		/* End of if */
-
-		/* use default *.bin array */
-		pFirmwareImage = FirmwareImage;
-		FileLength = sizeof(FirmwareImage);
-	} /* End of if */
-
-	/* enable Host program ram write selection */
-	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, 0x10000);
-
-	for(i=0; i<FileLength; i+=4)
-	{
-		firm = pFirmwareImage[i] +
-			   (pFirmwareImage[i+3] << 24) +
-			   (pFirmwareImage[i+2] << 16) +
-			   (pFirmwareImage[i+1] << 8);
-
-		RTMP_IO_WRITE32(pAd, FIRMWARE_IMAGE_BASE + i, firm);
-	} /* End of for */
-
-	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, 0x00000);
-	RTMP_IO_WRITE32(pAd, PBF_SYS_CTRL, 0x00001);
-
-	/* initialize BBP R/W access agent */
-	RTMP_IO_WRITE32(pAd, H2M_BBP_AGENT, 0);
-	RTMP_IO_WRITE32(pAd, H2M_MAILBOX_CSR, 0);
-
-	if (flg_default_firm_use == FALSE)
-	{
-		/* use file firmware, free allocated buffer */
-		if (pFirmwareImage != NULL)
-			kfree(pFirmwareImage);
-		/* End of if */
-	} /* End of if */
-
-	set_fs(orgfs);
-	current->fsuid = orgfsuid;
-	current->fsgid = orgfsgid;
-#else
-
-	NDIS_STATUS		Status = NDIS_STATUS_SUCCESS;
-	PUCHAR			pFirmwareImage;
-	ULONG			FileLength, Index;
-	//ULONG			firm;
-	UINT32			MacReg = 0;
-	UINT32			Version = (pAd->MACVersion >> 16);
-
-	pFirmwareImage = FirmwareImage;
-	FileLength = sizeof(FirmwareImage);
-
-	// New 8k byte firmware size for RT3071/RT3072
-	//printk("Usb Chip\n");
-	if (FIRMWAREIMAGE_LENGTH == FIRMWAREIMAGE_MAX_LENGTH)
-	//The firmware image consists of two parts. One is the origianl and the other is the new.
-	//Use Second Part
-	{
-#ifdef RT2870
-		if ((Version != 0x2860) && (Version != 0x2872) && (Version != 0x3070))
-		{	// Use Firmware V2.
-			//printk("KH:Use New Version,part2\n");
-			pFirmwareImage = (PUCHAR)&FirmwareImage[FIRMWAREIMAGEV1_LENGTH];
-			FileLength = FIRMWAREIMAGEV2_LENGTH;
-		}
-		else
-		{
-			//printk("KH:Use New Version,part1\n");
-			pFirmwareImage = FirmwareImage;
-			FileLength = FIRMWAREIMAGEV1_LENGTH;
-		}
-#endif // RT2870 //
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("KH: bin file should be 8KB.\n"));
-		Status = NDIS_STATUS_FAILURE;
-	}
-
-	RT28XX_WRITE_FIRMWARE(pAd, pFirmwareImage, FileLength);
-
-#endif
-
-	/* check if MCU is ready */
-	Index = 0;
-	do
-	{
-		RTMP_IO_READ32(pAd, PBF_SYS_CTRL, &MacReg);
-
-		if (MacReg & 0x80)
-			break;
-
-		RTMPusecDelay(1000);
-	} while (Index++ < 1000);
-
-    if (Index >= 1000)
-	{
-		Status = NDIS_STATUS_FAILURE;
-		DBGPRINT(RT_DEBUG_ERROR, ("NICLoadFirmware: MCU is not ready\n\n\n"));
-	} /* End of if */
-
-    DBGPRINT(RT_DEBUG_TRACE,
-			 ("<=== %s (status=%d)\n", __FUNCTION__, Status));
-    return Status;
-} /* End of NICLoadFirmware */
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Load Tx rate switching parameters
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		NDIS_STATUS_SUCCESS         firmware image load ok
-		NDIS_STATUS_FAILURE         image not found
-
-	IRQL = PASSIVE_LEVEL
-
-	Rate Table Format:
-		1. (B0: Valid Item number) (B1:Initial item from zero)
-		2. Item Number(Dec)      Mode(Hex)     Current MCS(Dec)    TrainUp(Dec)    TrainDown(Dec)
-
-	========================================================================
-*/
-NDIS_STATUS NICLoadRateSwitchingParams(
-	IN PRTMP_ADAPTER pAd)
-{
-	return NDIS_STATUS_SUCCESS;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		if  pSrc1 all zero with length Length, return 0.
-		If not all zero, return 1
-
-	Arguments:
-		pSrc1
-
-	Return Value:
-		1:			not all zero
-		0:			all zero
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-ULONG	RTMPNotAllZero(
-	IN	PVOID	pSrc1,
-	IN	ULONG	Length)
-{
-	PUCHAR	pMem1;
-	ULONG	Index = 0;
-
-	pMem1 = (PUCHAR) pSrc1;
-
-	for (Index = 0; Index < Length; Index++)
-	{
-		if (pMem1[Index] != 0x0)
-		{
-			break;
-		}
-	}
-
-	if (Index == Length)
-	{
-		return (0);
-	}
-	else
-	{
-		return (1);
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Compare two memory block
-
-	Arguments:
-		pSrc1		Pointer to first memory address
-		pSrc2		Pointer to second memory address
-
-	Return Value:
-		0:			memory is equal
-		1:			pSrc1 memory is larger
-		2:			pSrc2 memory is larger
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-ULONG	RTMPCompareMemory(
-	IN	PVOID	pSrc1,
-	IN	PVOID	pSrc2,
-	IN	ULONG	Length)
-{
-	PUCHAR	pMem1;
-	PUCHAR	pMem2;
-	ULONG	Index = 0;
-
-	pMem1 = (PUCHAR) pSrc1;
-	pMem2 = (PUCHAR) pSrc2;
-
-	for (Index = 0; Index < Length; Index++)
-	{
-		if (pMem1[Index] > pMem2[Index])
-			return (1);
-		else if (pMem1[Index] < pMem2[Index])
-			return (2);
-	}
-
-	// Equal
-	return (0);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Zero out memory block
-
-	Arguments:
-		pSrc1		Pointer to memory address
-		Length		Size
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPZeroMemory(
-	IN	PVOID	pSrc,
-	IN	ULONG	Length)
-{
-	PUCHAR	pMem;
-	ULONG	Index = 0;
-
-	pMem = (PUCHAR) pSrc;
-
-	for (Index = 0; Index < Length; Index++)
-	{
-		pMem[Index] = 0x00;
-	}
-}
-
-VOID	RTMPFillMemory(
-	IN	PVOID	pSrc,
-	IN	ULONG	Length,
-	IN	UCHAR	Fill)
-{
-	PUCHAR	pMem;
-	ULONG	Index = 0;
-
-	pMem = (PUCHAR) pSrc;
-
-	for (Index = 0; Index < Length; Index++)
-	{
-		pMem[Index] = Fill;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Copy data from memory block 1 to memory block 2
-
-	Arguments:
-		pDest		Pointer to destination memory address
-		pSrc		Pointer to source memory address
-		Length		Copy size
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPMoveMemory(
-	OUT	PVOID	pDest,
-	IN	PVOID	pSrc,
-	IN	ULONG	Length)
-{
-	PUCHAR	pMem1;
-	PUCHAR	pMem2;
-	UINT	Index;
-
-	ASSERT((Length==0) || (pDest && pSrc));
-
-	pMem1 = (PUCHAR) pDest;
-	pMem2 = (PUCHAR) pSrc;
-
-	for (Index = 0; Index < Length; Index++)
-	{
-		pMem1[Index] = pMem2[Index];
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Initialize port configuration structure
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	UserCfgInit(
-	IN	PRTMP_ADAPTER pAd)
-{
-//	EDCA_PARM DefaultEdcaParm;
-    UINT key_index, bss_index;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--> UserCfgInit\n"));
-
-	//
-	//  part I. intialize common configuration
-	//
-#ifdef RT2870
-	pAd->BulkOutReq = 0;
-
-	pAd->BulkOutComplete = 0;
-	pAd->BulkOutCompleteOther = 0;
-	pAd->BulkOutCompleteCancel = 0;
-	pAd->BulkInReq = 0;
-	pAd->BulkInComplete = 0;
-	pAd->BulkInCompleteFail = 0;
-
-	//pAd->QuickTimerP = 100;
-	//pAd->TurnAggrBulkInCount = 0;
-	pAd->bUsbTxBulkAggre = 0;
-
-	// init as unsed value to ensure driver will set to MCU once.
-	pAd->LedIndicatorStregth = 0xFF;
-
-	pAd->CommonCfg.MaxPktOneTxBulk = 2;
-	pAd->CommonCfg.TxBulkFactor = 1;
-	pAd->CommonCfg.RxBulkFactor =1;
-
-	pAd->CommonCfg.TxPower = 100; //mW
-
-	NdisZeroMemory(&pAd->CommonCfg.IOTestParm, sizeof(pAd->CommonCfg.IOTestParm));
-#endif // RT2870 //
-
-	for(key_index=0; key_index<SHARE_KEY_NUM; key_index++)
-	{
-		for(bss_index = 0; bss_index < MAX_MBSSID_NUM; bss_index++)
-		{
-			pAd->SharedKey[bss_index][key_index].KeyLen = 0;
-			pAd->SharedKey[bss_index][key_index].CipherAlg = CIPHER_NONE;
-        } /* End of for */
-    } /* End of for */
-
-	pAd->EepromAccess = FALSE;
-
-	pAd->Antenna.word = 0;
-	pAd->CommonCfg.BBPCurrentBW = BW_20;
-
-	pAd->LedCntl.word = 0;
-
-	pAd->bAutoTxAgcA = FALSE;			// Default is OFF
-	pAd->bAutoTxAgcG = FALSE;			// Default is OFF
-	pAd->RfIcType = RFIC_2820;
-
-	// Init timer for reset complete event
-	pAd->CommonCfg.CentralChannel = 1;
-	pAd->bForcePrintTX = FALSE;
-	pAd->bForcePrintRX = FALSE;
-	pAd->bStaFifoTest = FALSE;
-	pAd->bProtectionTest = FALSE;
-	pAd->bHCCATest = FALSE;
-	pAd->bGenOneHCCA = FALSE;
-	pAd->CommonCfg.Dsifs = 10;      // in units of usec
-	pAd->CommonCfg.TxPower = 100; //mW
-	pAd->CommonCfg.TxPowerPercentage = 0xffffffff; // AUTO
-	pAd->CommonCfg.TxPowerDefault = 0xffffffff; // AUTO
-	pAd->CommonCfg.TxPreamble = Rt802_11PreambleAuto; // use Long preamble on TX by defaut
-	pAd->CommonCfg.bUseZeroToDisableFragment = FALSE;
-	pAd->CommonCfg.RtsThreshold = 2347;
-	pAd->CommonCfg.FragmentThreshold = 2346;
-	pAd->CommonCfg.UseBGProtection = 0;    // 0: AUTO
-	pAd->CommonCfg.bEnableTxBurst = TRUE; //0;
-	pAd->CommonCfg.PhyMode = 0xff;     // unknown
-	pAd->CommonCfg.BandState = UNKNOWN_BAND;
-	pAd->CommonCfg.RadarDetect.CSPeriod = 10;
-	pAd->CommonCfg.RadarDetect.CSCount = 0;
-	pAd->CommonCfg.RadarDetect.RDMode = RD_NORMAL_MODE;
-	pAd->CommonCfg.RadarDetect.ChMovingTime = 65;
-	pAd->CommonCfg.RadarDetect.LongPulseRadarTh = 3;
-	pAd->CommonCfg.bAPSDCapable = FALSE;
-	pAd->CommonCfg.bNeedSendTriggerFrame = FALSE;
-	pAd->CommonCfg.TriggerTimerCount = 0;
-	pAd->CommonCfg.bAPSDForcePowerSave = FALSE;
-	pAd->CommonCfg.bCountryFlag = FALSE;
-	pAd->CommonCfg.TxStream = 0;
-	pAd->CommonCfg.RxStream = 0;
-
-	NdisZeroMemory(&pAd->BeaconTxWI, sizeof(pAd->BeaconTxWI));
-
-#ifdef DOT11_N_SUPPORT
-	NdisZeroMemory(&pAd->CommonCfg.HtCapability, sizeof(pAd->CommonCfg.HtCapability));
-	pAd->HTCEnable = FALSE;
-	pAd->bBroadComHT = FALSE;
-	pAd->CommonCfg.bRdg = FALSE;
-
-#ifdef DOT11N_DRAFT3
-	pAd->CommonCfg.Dot11OBssScanPassiveDwell = dot11OBSSScanPassiveDwell;	// Unit : TU. 5~1000
-	pAd->CommonCfg.Dot11OBssScanActiveDwell = dot11OBSSScanActiveDwell;	// Unit : TU. 10~1000
-	pAd->CommonCfg.Dot11BssWidthTriggerScanInt = dot11BSSWidthTriggerScanInterval;	// Unit : Second
-	pAd->CommonCfg.Dot11OBssScanPassiveTotalPerChannel = dot11OBSSScanPassiveTotalPerChannel;	// Unit : TU. 200~10000
-	pAd->CommonCfg.Dot11OBssScanActiveTotalPerChannel = dot11OBSSScanActiveTotalPerChannel;	// Unit : TU. 20~10000
-	pAd->CommonCfg.Dot11BssWidthChanTranDelayFactor = dot11BSSWidthChannelTransactionDelayFactor;
-	pAd->CommonCfg.Dot11OBssScanActivityThre = dot11BSSScanActivityThreshold;	// Unit : percentage
-	pAd->CommonCfg.Dot11BssWidthChanTranDelay = (pAd->CommonCfg.Dot11BssWidthTriggerScanInt * pAd->CommonCfg.Dot11BssWidthChanTranDelayFactor);
-#endif  // DOT11N_DRAFT3 //
-
-	NdisZeroMemory(&pAd->CommonCfg.AddHTInfo, sizeof(pAd->CommonCfg.AddHTInfo));
-	pAd->CommonCfg.BACapability.field.MMPSmode = MMPS_ENABLE;
-	pAd->CommonCfg.BACapability.field.MpduDensity = 0;
-	pAd->CommonCfg.BACapability.field.Policy = IMMED_BA;
-	pAd->CommonCfg.BACapability.field.RxBAWinLimit = 64; //32;
-	pAd->CommonCfg.BACapability.field.TxBAWinLimit = 64; //32;
-	DBGPRINT(RT_DEBUG_TRACE, ("--> UserCfgInit. BACapability = 0x%x\n", pAd->CommonCfg.BACapability.word));
-
-	pAd->CommonCfg.BACapability.field.AutoBA = FALSE;
-	BATableInit(pAd, &pAd->BATable);
-
-	pAd->CommonCfg.bExtChannelSwitchAnnouncement = 1;
-	pAd->CommonCfg.bHTProtect = 1;
-	pAd->CommonCfg.bMIMOPSEnable = TRUE;
-	pAd->CommonCfg.bBADecline = FALSE;
-	pAd->CommonCfg.bDisableReordering = FALSE;
-
-	pAd->CommonCfg.TxBASize = 7;
-
-	pAd->CommonCfg.REGBACapability.word = pAd->CommonCfg.BACapability.word;
-#endif // DOT11_N_SUPPORT //
-
-	//pAd->CommonCfg.HTPhyMode.field.BW = BW_20;
-	//pAd->CommonCfg.HTPhyMode.field.MCS = MCS_AUTO;
-	//pAd->CommonCfg.HTPhyMode.field.ShortGI = GI_800;
-	//pAd->CommonCfg.HTPhyMode.field.STBC = STBC_NONE;
-	pAd->CommonCfg.TxRate = RATE_6;
-
-	pAd->CommonCfg.MlmeTransmit.field.MCS = MCS_RATE_6;
-	pAd->CommonCfg.MlmeTransmit.field.BW = BW_20;
-	pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-
-	pAd->CommonCfg.BeaconPeriod = 100;     // in mSec
-
-	//
-	// part II. intialize STA specific configuration
-	//
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		RX_FILTER_SET_FLAG(pAd, fRX_FILTER_ACCEPT_DIRECT);
-		RX_FILTER_CLEAR_FLAG(pAd, fRX_FILTER_ACCEPT_MULTICAST);
-		RX_FILTER_SET_FLAG(pAd, fRX_FILTER_ACCEPT_BROADCAST);
-		RX_FILTER_SET_FLAG(pAd, fRX_FILTER_ACCEPT_ALL_MULTICAST);
-
-		pAd->StaCfg.Psm = PWR_ACTIVE;
-
-		pAd->StaCfg.OrigWepStatus = Ndis802_11EncryptionDisabled;
-		pAd->StaCfg.PairCipher = Ndis802_11EncryptionDisabled;
-		pAd->StaCfg.GroupCipher = Ndis802_11EncryptionDisabled;
-		pAd->StaCfg.bMixCipher = FALSE;
-		pAd->StaCfg.DefaultKeyId = 0;
-
-		// 802.1x port control
-		pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilter8021xWEP;
-		pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-		pAd->StaCfg.LastMicErrorTime = 0;
-		pAd->StaCfg.MicErrCnt        = 0;
-		pAd->StaCfg.bBlockAssoc      = FALSE;
-		pAd->StaCfg.WpaState         = SS_NOTUSE;
-
-		pAd->CommonCfg.NdisRadioStateOff = FALSE;		// New to support microsoft disable radio with OID command
-
-		pAd->StaCfg.RssiTrigger = 0;
-		NdisZeroMemory(&pAd->StaCfg.RssiSample, sizeof(RSSI_SAMPLE));
-		pAd->StaCfg.RssiTriggerMode = RSSI_TRIGGERED_UPON_BELOW_THRESHOLD;
-		pAd->StaCfg.AtimWin = 0;
-		pAd->StaCfg.DefaultListenCount = 3;//default listen count;
-		pAd->StaCfg.BssType = BSS_INFRA;  // BSS_INFRA or BSS_ADHOC or BSS_MONITOR
-		pAd->StaCfg.bScanReqIsFromWebUI = FALSE;
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_DOZE);
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_WAKEUP_NOW);
-
-		pAd->StaCfg.bAutoTxRateSwitch = TRUE;
-		pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-	}
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-	pAd->StaCfg.IEEE80211dClientMode = Rt802_11_D_None;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
-
-	// global variables mXXXX used in MAC protocol state machines
-	OPSTATUS_SET_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM);
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_ADHOC_ON);
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_INFRA_ON);
-
-	// PHY specification
-	pAd->CommonCfg.PhyMode = PHY_11BG_MIXED;		// default PHY mode
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);  // CCK use LONG preamble
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// user desired power mode
-		pAd->StaCfg.WindowsPowerMode = Ndis802_11PowerModeCAM;
-		pAd->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeCAM;
-		pAd->StaCfg.bWindowsACCAMEnable = FALSE;
-
-#ifdef LEAP_SUPPORT
-		// CCX v1.0 releated init value
-		RTMPInitTimer(pAd, &pAd->StaCfg.LeapAuthTimer, GET_TIMER_FUNCTION(LeapAuthTimeout), pAd, FALSE);
-		pAd->StaCfg.LeapAuthMode = CISCO_AuthModeLEAPNone;
-		pAd->StaCfg.bCkipOn = FALSE;
-#endif // LEAP_SUPPORT //
-
-		RTMPInitTimer(pAd, &pAd->StaCfg.StaQuickResponeForRateUpTimer, GET_TIMER_FUNCTION(StaQuickResponeForRateUpExec), pAd, FALSE);
-		pAd->StaCfg.StaQuickResponeForRateUpTimerRunning = FALSE;
-
-		// Patch for Ndtest
-		pAd->StaCfg.ScanCnt = 0;
-
-		// CCX 2.0 control flag init
-		pAd->StaCfg.CCXEnable = FALSE;
-		pAd->StaCfg.CCXReqType = MSRN_TYPE_UNUSED;
-		pAd->StaCfg.CCXQosECWMin	= 4;
-		pAd->StaCfg.CCXQosECWMax	= 10;
-
-		pAd->StaCfg.bHwRadio  = TRUE; // Default Hardware Radio status is On
-		pAd->StaCfg.bSwRadio  = TRUE; // Default Software Radio status is On
-		pAd->StaCfg.bRadio    = TRUE; // bHwRadio && bSwRadio
-		pAd->StaCfg.bHardwareRadio = FALSE;		// Default is OFF
-		pAd->StaCfg.bShowHiddenSSID = FALSE;		// Default no show
-
-		// Nitro mode control
-		pAd->StaCfg.bAutoReconnect = TRUE;
-
-		// Save the init time as last scan time, the system should do scan after 2 seconds.
-		// This patch is for driver wake up from standby mode, system will do scan right away.
-		pAd->StaCfg.LastScanTime = 0;
-		NdisZeroMemory(pAd->nickname, IW_ESSID_MAX_SIZE+1);
-		sprintf(pAd->nickname, "%s", STA_NIC_DEVICE_NAME);
-		RTMPInitTimer(pAd, &pAd->StaCfg.WpaDisassocAndBlockAssocTimer, GET_TIMER_FUNCTION(WpaDisassocApAndBlockAssoc), pAd, FALSE);
-#ifdef WPA_SUPPLICANT_SUPPORT
-		pAd->StaCfg.IEEE8021X = FALSE;
-		pAd->StaCfg.IEEE8021x_required_keys = FALSE;
-		pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_DISABLE;
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-		pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_ENABLE;
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Default for extra information is not valid
-	pAd->ExtraInfo = EXTRA_INFO_CLEAR;
-
-	// Default Config change flag
-	pAd->bConfigChanged = FALSE;
-
-	//
-	// part III. AP configurations
-	//
-
-
-	//
-	// part IV. others
-	//
-	// dynamic BBP R66:sensibity tuning to overcome background noise
-	pAd->BbpTuning.bEnable                = TRUE;
-	pAd->BbpTuning.FalseCcaLowerThreshold = 100;
-	pAd->BbpTuning.FalseCcaUpperThreshold = 512;
-	pAd->BbpTuning.R66Delta               = 4;
-	pAd->Mlme.bEnableAutoAntennaCheck = TRUE;
-
-	//
-	// Also initial R66CurrentValue, RTUSBResumeMsduTransmission might use this value.
-	// if not initial this value, the default value will be 0.
-	//
-	pAd->BbpTuning.R66CurrentValue = 0x38;
-
-	pAd->Bbp94 = BBPR94_DEFAULT;
-	pAd->BbpForCCK = FALSE;
-
-	// Default is FALSE for test bit 1
-	//pAd->bTest1 = FALSE;
-
-	// initialize MAC table and allocate spin lock
-	NdisZeroMemory(&pAd->MacTab, sizeof(MAC_TABLE));
-	InitializeQueueHeader(&pAd->MacTab.McastPsQueue);
-	NdisAllocateSpinLock(&pAd->MacTabLock);
-
-	//RTMPInitTimer(pAd, &pAd->RECBATimer, RECBATimerTimeout, pAd, TRUE);
-	//RTMPSetTimer(&pAd->RECBATimer, REORDER_EXEC_INTV);
-
-#ifdef RALINK_ATE
-	NdisZeroMemory(&pAd->ate, sizeof(ATE_INFO));
-	pAd->ate.Mode = ATE_STOP;
-	pAd->ate.TxCount = 200;/* to exceed TX_RING_SIZE ... */
-	pAd->ate.TxLength = 1024;
-	pAd->ate.TxWI.ShortGI = 0;// LONG GI : 800 ns
-	pAd->ate.TxWI.PHYMODE = MODE_CCK;
-	pAd->ate.TxWI.MCS = 3;
-	pAd->ate.TxWI.BW = BW_20;
-	pAd->ate.Channel = 1;
-	pAd->ate.QID = QID_AC_BE;
-	pAd->ate.Addr1[0] = 0x00;
-	pAd->ate.Addr1[1] = 0x11;
-	pAd->ate.Addr1[2] = 0x22;
-	pAd->ate.Addr1[3] = 0xAA;
-	pAd->ate.Addr1[4] = 0xBB;
-	pAd->ate.Addr1[5] = 0xCC;
-	NdisMoveMemory(pAd->ate.Addr2, pAd->ate.Addr1, ETH_LENGTH_OF_ADDRESS);
-	NdisMoveMemory(pAd->ate.Addr3, pAd->ate.Addr1, ETH_LENGTH_OF_ADDRESS);
-	pAd->ate.bRxFer = 0;
-	pAd->ate.bQATxStart = FALSE;
-	pAd->ate.bQARxStart = FALSE;
-#ifdef RALINK_28xx_QA
-	//pAd->ate.Repeat = 0;
-	pAd->ate.TxStatus = 0;
-	pAd->ate.AtePid = 0;
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-
-	pAd->CommonCfg.bWiFiTest = FALSE;
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<-- UserCfgInit\n"));
-}
-
-// IRQL = PASSIVE_LEVEL
-UCHAR BtoH(char ch)
-{
-	if (ch >= '0' && ch <= '9') return (ch - '0');        // Handle numerals
-	if (ch >= 'A' && ch <= 'F') return (ch - 'A' + 0xA);  // Handle capitol hex digits
-	if (ch >= 'a' && ch <= 'f') return (ch - 'a' + 0xA);  // Handle small hex digits
-	return(255);
-}
-
-//
-//  FUNCTION: AtoH(char *, UCHAR *, int)
-//
-//  PURPOSE:  Converts ascii string to network order hex
-//
-//  PARAMETERS:
-//    src    - pointer to input ascii string
-//    dest   - pointer to output hex
-//    destlen - size of dest
-//
-//  COMMENTS:
-//
-//    2 ascii bytes make a hex byte so must put 1st ascii byte of pair
-//    into upper nibble and 2nd ascii byte of pair into lower nibble.
-//
-// IRQL = PASSIVE_LEVEL
-
-void AtoH(char * src, UCHAR * dest, int destlen)
-{
-	char * srcptr;
-	PUCHAR destTemp;
-
-	srcptr = src;
-	destTemp = (PUCHAR) dest;
-
-	while(destlen--)
-	{
-		*destTemp = BtoH(*srcptr++) << 4;    // Put 1st ascii byte in upper nibble.
-		*destTemp += BtoH(*srcptr++);      // Add 2nd ascii byte to above.
-		destTemp++;
-	}
-}
-
-VOID	RTMPPatchMacBbpBug(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	ULONG	Index;
-
-	// Initialize BBP register to default value
-	for (Index = 0; Index < NUM_BBP_REG_PARMS; Index++)
-	{
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBPRegTable[Index].Register, (UCHAR)BBPRegTable[Index].Value);
-	}
-
-	// Initialize RF register to default value
-	AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-	AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-
-	// Re-init BBP register from EEPROM value
-	NICInitAsicFromEEPROM(pAd);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Init timer objects
-
-	Arguments:
-		pAd			Pointer to our adapter
-		pTimer				Timer structure
-		pTimerFunc			Function to execute when timer expired
-		Repeat				Ture for period timer
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPInitTimer(
-	IN	PRTMP_ADAPTER			pAd,
-	IN	PRALINK_TIMER_STRUCT	pTimer,
-	IN	PVOID					pTimerFunc,
-	IN	PVOID					pData,
-	IN	BOOLEAN					Repeat)
-{
-	//
-	// Set Valid to TRUE for later used.
-	// It will crash if we cancel a timer or set a timer
-	// that we haven't initialize before.
-	//
-	pTimer->Valid      = TRUE;
-
-	pTimer->PeriodicType = Repeat;
-	pTimer->State      = FALSE;
-	pTimer->cookie = (ULONG) pData;
-
-#ifdef RT2870
-	pTimer->pAd = pAd;
-#endif // RT2870 //
-
-	RTMP_OS_Init_Timer(pAd,	&pTimer->TimerObj,	pTimerFunc, (PVOID) pTimer);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Init timer objects
-
-	Arguments:
-		pTimer				Timer structure
-		Value				Timer value in milliseconds
-
-	Return Value:
-		None
-
-	Note:
-		To use this routine, must call RTMPInitTimer before.
-
-	========================================================================
-*/
-VOID	RTMPSetTimer(
-	IN	PRALINK_TIMER_STRUCT	pTimer,
-	IN	ULONG					Value)
-{
-	if (pTimer->Valid)
-	{
-		pTimer->TimerValue = Value;
-		pTimer->State      = FALSE;
-		if (pTimer->PeriodicType == TRUE)
-		{
-			pTimer->Repeat = TRUE;
-			RTMP_SetPeriodicTimer(&pTimer->TimerObj, Value);
-		}
-		else
-		{
-			pTimer->Repeat = FALSE;
-			RTMP_OS_Add_Timer(&pTimer->TimerObj, Value);
-		}
-	}
-	else
-	{
-		DBGPRINT_ERR(("RTMPSetTimer failed, Timer hasn't been initialize!\n"));
-	}
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Init timer objects
-
-	Arguments:
-		pTimer				Timer structure
-		Value				Timer value in milliseconds
-
-	Return Value:
-		None
-
-	Note:
-		To use this routine, must call RTMPInitTimer before.
-
-	========================================================================
-*/
-VOID	RTMPModTimer(
-	IN	PRALINK_TIMER_STRUCT	pTimer,
-	IN	ULONG					Value)
-{
-	BOOLEAN	Cancel;
-
-	if (pTimer->Valid)
-	{
-		pTimer->TimerValue = Value;
-		pTimer->State      = FALSE;
-		if (pTimer->PeriodicType == TRUE)
-		{
-			RTMPCancelTimer(pTimer, &Cancel);
-			RTMPSetTimer(pTimer, Value);
-		}
-		else
-		{
-			RTMP_OS_Mod_Timer(&pTimer->TimerObj, Value);
-		}
-	}
-	else
-	{
-		DBGPRINT_ERR(("RTMPModTimer failed, Timer hasn't been initialize!\n"));
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Cancel timer objects
-
-	Arguments:
-		Adapter						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-		1.) To use this routine, must call RTMPInitTimer before.
-		2.) Reset NIC to initial state AS IS system boot up time.
-
-	========================================================================
-*/
-VOID	RTMPCancelTimer(
-	IN	PRALINK_TIMER_STRUCT	pTimer,
-	OUT	BOOLEAN					*pCancelled)
-{
-	if (pTimer->Valid)
-	{
-		if (pTimer->State == FALSE)
-			pTimer->Repeat = FALSE;
-			RTMP_OS_Del_Timer(&pTimer->TimerObj, pCancelled);
-
-		if (*pCancelled == TRUE)
-			pTimer->State = TRUE;
-
-#ifdef RT2870
-		// We need to go-through the TimerQ to findout this timer handler and remove it if
-		//		it's still waiting for execution.
-
-		RT2870_TimerQ_Remove(pTimer->pAd, pTimer);
-#endif // RT2870 //
-	}
-	else
-	{
-		//
-		// NdisMCancelTimer just canced the timer and not mean release the timer.
-		// And don't set the "Valid" to False. So that we can use this timer again.
-		//
-		DBGPRINT_ERR(("RTMPCancelTimer failed, Timer hasn't been initialize!\n"));
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Set LED Status
-
-	Arguments:
-		pAd						Pointer to our adapter
-		Status					LED Status
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID RTMPSetLED(
-	IN PRTMP_ADAPTER 	pAd,
-	IN UCHAR			Status)
-{
-	//ULONG			data;
-	UCHAR			HighByte = 0;
-	UCHAR			LowByte;
-
-// In ATE mode of RT2860 AP/STA, we have erased 8051 firmware.
-// So LED mode is not supported when ATE is running.
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	LowByte = pAd->LedCntl.field.LedMode&0x7f;
-	switch (Status)
-	{
-		case LED_LINK_DOWN:
-			HighByte = 0x20;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			pAd->LedIndicatorStregth = 0;
-			break;
-		case LED_LINK_UP:
-			if (pAd->CommonCfg.Channel > 14)
-				HighByte = 0xa0;
-			else
-				HighByte = 0x60;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-		case LED_RADIO_ON:
-			HighByte = 0x20;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-		case LED_HALT:
-			LowByte = 0; // Driver sets MAC register and MAC controls LED
-		case LED_RADIO_OFF:
-			HighByte = 0;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-        case LED_WPS:
-			HighByte = 0x10;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-		case LED_ON_SITE_SURVEY:
-			HighByte = 0x08;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-		case LED_POWER_UP:
-			HighByte = 0x04;
-			AsicSendCommandToMcu(pAd, 0x50, 0xff, LowByte, HighByte);
-			break;
-		default:
-			DBGPRINT(RT_DEBUG_WARN, ("RTMPSetLED::Unknown Status %d\n", Status));
-			break;
-	}
-
-    //
-	// Keep LED status for LED SiteSurvey mode.
-	// After SiteSurvey, we will set the LED mode to previous status.
-	//
-	if ((Status != LED_ON_SITE_SURVEY) && (Status != LED_POWER_UP))
-		pAd->LedStatus = Status;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSetLED::Mode=%d,HighByte=0x%02x,LowByte=0x%02x\n", pAd->LedCntl.field.LedMode, HighByte, LowByte));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Set LED Signal Stregth
-
-	Arguments:
-		pAd						Pointer to our adapter
-		Dbm						Signal Stregth
-
-	Return Value:
-		None
-
-	IRQL = PASSIVE_LEVEL
-
-	Note:
-		Can be run on any IRQL level.
-
-		According to Microsoft Zero Config Wireless Signal Stregth definition as belows.
-		<= -90  No Signal
-		<= -81  Very Low
-		<= -71  Low
-		<= -67  Good
-		<= -57  Very Good
-		 > -57  Excellent
-	========================================================================
-*/
-VOID RTMPSetSignalLED(
-	IN PRTMP_ADAPTER 	pAd,
-	IN NDIS_802_11_RSSI Dbm)
-{
-	UCHAR		nLed = 0;
-
-	//
-	// if not Signal Stregth, then do nothing.
-	//
-	if (pAd->LedCntl.field.LedMode != LED_MODE_SIGNAL_STREGTH)
-	{
-		return;
-	}
-
-	if (Dbm <= -90)
-		nLed = 0;
-	else if (Dbm <= -81)
-		nLed = 1;
-	else if (Dbm <= -71)
-		nLed = 3;
-	else if (Dbm <= -67)
-		nLed = 7;
-	else if (Dbm <= -57)
-		nLed = 15;
-	else
-		nLed = 31;
-
-	//
-	// Update Signal Stregth to firmware if changed.
-	//
-	if (pAd->LedIndicatorStregth != nLed)
-	{
-		AsicSendCommandToMcu(pAd, 0x51, 0xff, nLed, pAd->LedCntl.field.Polarity);
-		pAd->LedIndicatorStregth = nLed;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Enable RX
-
-	Arguments:
-		pAd						Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL <= DISPATCH_LEVEL
-
-	Note:
-		Before Enable RX, make sure you have enabled Interrupt.
-	========================================================================
-*/
-VOID RTMPEnableRxTx(
-	IN PRTMP_ADAPTER	pAd)
-{
-//	WPDMA_GLO_CFG_STRUC	GloCfg;
-//	ULONG	i = 0;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==> RTMPEnableRxTx\n"));
-
-	// Enable Rx DMA.
-	RT28XXDMAEnable(pAd);
-
-	// enable RX of MAC block
-	if (pAd->OpMode == OPMODE_AP)
-	{
-		UINT32 rx_filter_flag = APNORMAL;
-
-
-		RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, rx_filter_flag);     // enable RX of DMA block
-	}
-	else
-	{
-		RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, STANORMAL);     // Staion not drop control frame will fail WiFi Certification.
-	}
-
-	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, 0xc);
-	DBGPRINT(RT_DEBUG_TRACE, ("<== RTMPEnableRxTx\n"));
-}
-
-
+#include "../../rt2870/common/rtmp_init.c"
diff --git a/drivers/staging/rt3070/common/rtmp_tkip.c b/drivers/staging/rt3070/common/rtmp_tkip.c
index bf8986e..57a5ee9 100644
--- a/drivers/staging/rt3070/common/rtmp_tkip.c
+++ b/drivers/staging/rt3070/common/rtmp_tkip.c
@@ -1,1613 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtmp_tkip.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Paul Wu		02-25-02		Initial
-*/
-
-#include	"../rt_config.h"
-
-// Rotation functions on 32 bit values
-#define ROL32( A, n ) \
-	( ((A) << (n)) | ( ((A)>>(32-(n))) & ( (1UL << (n)) - 1 ) ) )
-#define ROR32( A, n ) ROL32( (A), 32-(n) )
-
-UINT Tkip_Sbox_Lower[256] =
-{
-	0xA5,0x84,0x99,0x8D,0x0D,0xBD,0xB1,0x54,
-	0x50,0x03,0xA9,0x7D,0x19,0x62,0xE6,0x9A,
-	0x45,0x9D,0x40,0x87,0x15,0xEB,0xC9,0x0B,
-	0xEC,0x67,0xFD,0xEA,0xBF,0xF7,0x96,0x5B,
-	0xC2,0x1C,0xAE,0x6A,0x5A,0x41,0x02,0x4F,
-	0x5C,0xF4,0x34,0x08,0x93,0x73,0x53,0x3F,
-	0x0C,0x52,0x65,0x5E,0x28,0xA1,0x0F,0xB5,
-	0x09,0x36,0x9B,0x3D,0x26,0x69,0xCD,0x9F,
-	0x1B,0x9E,0x74,0x2E,0x2D,0xB2,0xEE,0xFB,
-	0xF6,0x4D,0x61,0xCE,0x7B,0x3E,0x71,0x97,
-	0xF5,0x68,0x00,0x2C,0x60,0x1F,0xC8,0xED,
-	0xBE,0x46,0xD9,0x4B,0xDE,0xD4,0xE8,0x4A,
-	0x6B,0x2A,0xE5,0x16,0xC5,0xD7,0x55,0x94,
-	0xCF,0x10,0x06,0x81,0xF0,0x44,0xBA,0xE3,
-	0xF3,0xFE,0xC0,0x8A,0xAD,0xBC,0x48,0x04,
-	0xDF,0xC1,0x75,0x63,0x30,0x1A,0x0E,0x6D,
-	0x4C,0x14,0x35,0x2F,0xE1,0xA2,0xCC,0x39,
-	0x57,0xF2,0x82,0x47,0xAC,0xE7,0x2B,0x95,
-	0xA0,0x98,0xD1,0x7F,0x66,0x7E,0xAB,0x83,
-	0xCA,0x29,0xD3,0x3C,0x79,0xE2,0x1D,0x76,
-	0x3B,0x56,0x4E,0x1E,0xDB,0x0A,0x6C,0xE4,
-	0x5D,0x6E,0xEF,0xA6,0xA8,0xA4,0x37,0x8B,
-	0x32,0x43,0x59,0xB7,0x8C,0x64,0xD2,0xE0,
-	0xB4,0xFA,0x07,0x25,0xAF,0x8E,0xE9,0x18,
-	0xD5,0x88,0x6F,0x72,0x24,0xF1,0xC7,0x51,
-	0x23,0x7C,0x9C,0x21,0xDD,0xDC,0x86,0x85,
-	0x90,0x42,0xC4,0xAA,0xD8,0x05,0x01,0x12,
-	0xA3,0x5F,0xF9,0xD0,0x91,0x58,0x27,0xB9,
-	0x38,0x13,0xB3,0x33,0xBB,0x70,0x89,0xA7,
-	0xB6,0x22,0x92,0x20,0x49,0xFF,0x78,0x7A,
-	0x8F,0xF8,0x80,0x17,0xDA,0x31,0xC6,0xB8,
-	0xC3,0xB0,0x77,0x11,0xCB,0xFC,0xD6,0x3A
-};
-
-UINT Tkip_Sbox_Upper[256] =
-{
-	0xC6,0xF8,0xEE,0xF6,0xFF,0xD6,0xDE,0x91,
-	0x60,0x02,0xCE,0x56,0xE7,0xB5,0x4D,0xEC,
-	0x8F,0x1F,0x89,0xFA,0xEF,0xB2,0x8E,0xFB,
-	0x41,0xB3,0x5F,0x45,0x23,0x53,0xE4,0x9B,
-	0x75,0xE1,0x3D,0x4C,0x6C,0x7E,0xF5,0x83,
-	0x68,0x51,0xD1,0xF9,0xE2,0xAB,0x62,0x2A,
-	0x08,0x95,0x46,0x9D,0x30,0x37,0x0A,0x2F,
-	0x0E,0x24,0x1B,0xDF,0xCD,0x4E,0x7F,0xEA,
-	0x12,0x1D,0x58,0x34,0x36,0xDC,0xB4,0x5B,
-	0xA4,0x76,0xB7,0x7D,0x52,0xDD,0x5E,0x13,
-	0xA6,0xB9,0x00,0xC1,0x40,0xE3,0x79,0xB6,
-	0xD4,0x8D,0x67,0x72,0x94,0x98,0xB0,0x85,
-	0xBB,0xC5,0x4F,0xED,0x86,0x9A,0x66,0x11,
-	0x8A,0xE9,0x04,0xFE,0xA0,0x78,0x25,0x4B,
-	0xA2,0x5D,0x80,0x05,0x3F,0x21,0x70,0xF1,
-	0x63,0x77,0xAF,0x42,0x20,0xE5,0xFD,0xBF,
-	0x81,0x18,0x26,0xC3,0xBE,0x35,0x88,0x2E,
-	0x93,0x55,0xFC,0x7A,0xC8,0xBA,0x32,0xE6,
-	0xC0,0x19,0x9E,0xA3,0x44,0x54,0x3B,0x0B,
-	0x8C,0xC7,0x6B,0x28,0xA7,0xBC,0x16,0xAD,
-	0xDB,0x64,0x74,0x14,0x92,0x0C,0x48,0xB8,
-	0x9F,0xBD,0x43,0xC4,0x39,0x31,0xD3,0xF2,
-	0xD5,0x8B,0x6E,0xDA,0x01,0xB1,0x9C,0x49,
-	0xD8,0xAC,0xF3,0xCF,0xCA,0xF4,0x47,0x10,
-	0x6F,0xF0,0x4A,0x5C,0x38,0x57,0x73,0x97,
-	0xCB,0xA1,0xE8,0x3E,0x96,0x61,0x0D,0x0F,
-	0xE0,0x7C,0x71,0xCC,0x90,0x06,0xF7,0x1C,
-	0xC2,0x6A,0xAE,0x69,0x17,0x99,0x3A,0x27,
-	0xD9,0xEB,0x2B,0x22,0xD2,0xA9,0x07,0x33,
-	0x2D,0x3C,0x15,0xC9,0x87,0xAA,0x50,0xA5,
-	0x03,0x59,0x09,0x1A,0x65,0xD7,0x84,0xD0,
-	0x82,0x29,0x5A,0x1E,0x7B,0xA8,0x6D,0x2C
-};
-
-/*****************************/
-/******** SBOX Table *********/
-/*****************************/
-
-UCHAR SboxTable[256] =
-{
-	0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
-	0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
-	0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
-	0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
-	0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
-	0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
-	0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
-	0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
-	0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
-	0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
-	0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
-	0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
-	0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
-	0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
-	0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
-	0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
-	0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
-	0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
-	0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
-	0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
-	0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
-	0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
-	0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
-	0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
-	0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
-	0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
-	0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
-	0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
-	0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
-	0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
-	0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
-	0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
-};
-
-VOID xor_32(
-	IN  PUCHAR              a,
-	IN  PUCHAR              b,
-	OUT PUCHAR              out);
-
-VOID xor_128(
-	IN  PUCHAR              a,
-	IN  PUCHAR              b,
-	OUT PUCHAR              out);
-
-VOID next_key(
-	IN  PUCHAR              key,
-	IN  INT                 round);
-
-VOID byte_sub(
-	IN  PUCHAR              in,
-	OUT PUCHAR              out);
-
-VOID shift_row(
-	IN  PUCHAR              in,
-	OUT PUCHAR              out);
-
-VOID mix_column(
-	IN  PUCHAR              in,
-	OUT PUCHAR              out);
-
-UCHAR RTMPCkipSbox(
-	IN  UCHAR               a);
-//
-// Expanded IV for TKIP function.
-//
-typedef	struct	PACKED _IV_CONTROL_
-{
-	union PACKED
-	{
-		struct PACKED
-		{
-			UCHAR		rc0;
-			UCHAR		rc1;
-			UCHAR		rc2;
-
-			union PACKED
-			{
-				struct PACKED
-				{
-#ifdef RT_BIG_ENDIAN
-					UCHAR	KeyID:2;
-					UCHAR	ExtIV:1;
-					UCHAR	Rsvd:5;
-#else
-					UCHAR	Rsvd:5;
-					UCHAR	ExtIV:1;
-					UCHAR	KeyID:2;
-#endif
-				}	field;
-				UCHAR		Byte;
-			}	CONTROL;
-		}	field;
-
-		ULONG	word;
-	}	IV16;
-
-	ULONG	IV32;
-}	TKIP_IV, *PTKIP_IV;
-
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Convert from UCHAR[] to ULONG in a portable way
-
-	Arguments:
-      pMICKey		pointer to MIC Key
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-ULONG	RTMPTkipGetUInt32(
-	IN	PUCHAR	pMICKey)
-{
-	ULONG	res = 0;
-	INT		i;
-
-	for (i = 0; i < 4; i++)
-	{
-		res |= (*pMICKey++) << (8 * i);
-	}
-
-	return res;
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Convert from ULONG to UCHAR[] in a portable way
-
-	Arguments:
-      pDst			pointer to destination for convert ULONG to UCHAR[]
-      val			the value for convert
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPTkipPutUInt32(
-	IN OUT	PUCHAR		pDst,
-	IN		ULONG		val)
-{
-	INT i;
-
-	for(i = 0; i < 4; i++)
-	{
-		*pDst++ = (UCHAR) (val & 0xff);
-		val >>= 8;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Set the MIC Key.
-
-	Arguments:
-      pAd		Pointer to our adapter
-      pMICKey		pointer to MIC Key
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID RTMPTkipSetMICKey(
-	IN	PTKIP_KEY_INFO	pTkip,
-	IN	PUCHAR			pMICKey)
-{
-	// Set the key
-	pTkip->K0 = RTMPTkipGetUInt32(pMICKey);
-	pTkip->K1 = RTMPTkipGetUInt32(pMICKey + 4);
-	// and reset the message
-	pTkip->L = pTkip->K0;
-	pTkip->R = pTkip->K1;
-	pTkip->nBytesInM = 0;
-	pTkip->M = 0;
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Calculate the MIC Value.
-
-	Arguments:
-      pAd		Pointer to our adapter
-      uChar			Append this uChar
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPTkipAppendByte(
-	IN	PTKIP_KEY_INFO	pTkip,
-	IN	UCHAR 			uChar)
-{
-	// Append the byte to our word-sized buffer
-	pTkip->M |= (uChar << (8* pTkip->nBytesInM));
-	pTkip->nBytesInM++;
-	// Process the word if it is full.
-	if( pTkip->nBytesInM >= 4 )
-	{
-		pTkip->L ^= pTkip->M;
-		pTkip->R ^= ROL32( pTkip->L, 17 );
-		pTkip->L += pTkip->R;
-		pTkip->R ^= ((pTkip->L & 0xff00ff00) >> 8) | ((pTkip->L & 0x00ff00ff) << 8);
-		pTkip->L += pTkip->R;
-		pTkip->R ^= ROL32( pTkip->L, 3 );
-		pTkip->L += pTkip->R;
-		pTkip->R ^= ROR32( pTkip->L, 2 );
-		pTkip->L += pTkip->R;
-		// Clear the buffer
-		pTkip->M = 0;
-		pTkip->nBytesInM = 0;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Calculate the MIC Value.
-
-	Arguments:
-      pAd		Pointer to our adapter
-      pSrc			Pointer to source data for Calculate MIC Value
-      Len			Indicate the length of the source data
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPTkipAppend(
-	IN	PTKIP_KEY_INFO	pTkip,
-	IN	PUCHAR			pSrc,
-	IN	UINT			nBytes)
-{
-	// This is simple
-	while(nBytes > 0)
-	{
-		RTMPTkipAppendByte(pTkip, *pSrc++);
-		nBytes--;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Get the MIC Value.
-
-	Arguments:
-      pAd		Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-		the MIC Value is store in pAd->PrivateInfo.MIC
-	========================================================================
-*/
-VOID	RTMPTkipGetMIC(
-	IN	PTKIP_KEY_INFO	pTkip)
-{
-	// Append the minimum padding
-	RTMPTkipAppendByte(pTkip, 0x5a );
-	RTMPTkipAppendByte(pTkip, 0 );
-	RTMPTkipAppendByte(pTkip, 0 );
-	RTMPTkipAppendByte(pTkip, 0 );
-	RTMPTkipAppendByte(pTkip, 0 );
-	// and then zeroes until the length is a multiple of 4
-	while( pTkip->nBytesInM != 0 )
-	{
-		RTMPTkipAppendByte(pTkip, 0 );
-	}
-	// The appendByte function has already computed the result.
-	RTMPTkipPutUInt32(pTkip->MIC, pTkip->L);
-	RTMPTkipPutUInt32(pTkip->MIC + 4, pTkip->R);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Init Tkip function.
-
-	Arguments:
-      pAd		Pointer to our adapter
-		pTKey       Pointer to the Temporal Key (TK), TK shall be 128bits.
-		KeyId		TK Key ID
-		pTA			Pointer to transmitter address
-		pMICKey		pointer to MIC Key
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPInitTkipEngine(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pKey,
-	IN	UCHAR			KeyId,
-	IN	PUCHAR			pTA,
-	IN	PUCHAR			pMICKey,
-	IN	PUCHAR			pTSC,
-	OUT	PULONG			pIV16,
-	OUT	PULONG			pIV32)
-{
-	TKIP_IV	tkipIv;
-
-	// Prepare 8 bytes TKIP encapsulation for MPDU
-	NdisZeroMemory(&tkipIv, sizeof(TKIP_IV));
-	tkipIv.IV16.field.rc0 = *(pTSC + 1);
-	tkipIv.IV16.field.rc1 = (tkipIv.IV16.field.rc0 | 0x20) & 0x7f;
-	tkipIv.IV16.field.rc2 = *pTSC;
-	tkipIv.IV16.field.CONTROL.field.ExtIV = 1;  // 0: non-extended IV, 1: an extended IV
-	tkipIv.IV16.field.CONTROL.field.KeyID = KeyId;
-//	tkipIv.IV32 = *(PULONG)(pTSC + 2);
-	NdisMoveMemory(&tkipIv.IV32, (pTSC + 2), 4);   // Copy IV
-
-	*pIV16 = tkipIv.IV16.word;
-	*pIV32 = tkipIv.IV32;
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Init MIC Value calculation function which include set MIC key &
-		calculate first 16 bytes (DA + SA + priority +  0)
-
-	Arguments:
-      pAd		Pointer to our adapter
-		pTKey       Pointer to the Temporal Key (TK), TK shall be 128bits.
-		pDA			Pointer to DA address
-		pSA			Pointer to SA address
-		pMICKey		pointer to MIC Key
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPInitMICEngine(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pKey,
-	IN	PUCHAR			pDA,
-	IN	PUCHAR			pSA,
-	IN  UCHAR           UserPriority,
-	IN	PUCHAR			pMICKey)
-{
-	ULONG Priority = UserPriority;
-
-	// Init MIC value calculation
-	RTMPTkipSetMICKey(&pAd->PrivateInfo.Tx, pMICKey);
-	// DA
-	RTMPTkipAppend(&pAd->PrivateInfo.Tx, pDA, MAC_ADDR_LEN);
-	// SA
-	RTMPTkipAppend(&pAd->PrivateInfo.Tx, pSA, MAC_ADDR_LEN);
-	// Priority + 3 bytes of 0
-	RTMPTkipAppend(&pAd->PrivateInfo.Tx, (PUCHAR)&Priority, 4);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Compare MIC value of received MSDU
-
-	Arguments:
-		pAd	Pointer to our adapter
-		pSrc        Pointer to the received Plain text data
-		pDA			Pointer to DA address
-		pSA			Pointer to SA address
-		pMICKey		pointer to MIC Key
-		Len         the length of the received plain text data exclude MIC value
-
-	Return Value:
-		TRUE        MIC value matched
-		FALSE       MIC value mismatched
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-BOOLEAN	RTMPTkipCompareMICValue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pSrc,
-	IN	PUCHAR			pDA,
-	IN	PUCHAR			pSA,
-	IN	PUCHAR			pMICKey,
-	IN	UCHAR			UserPriority,
-	IN	UINT			Len)
-{
-	UCHAR	OldMic[8];
-	ULONG	Priority = UserPriority;
-
-	// Init MIC value calculation
-	RTMPTkipSetMICKey(&pAd->PrivateInfo.Rx, pMICKey);
-	// DA
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pDA, MAC_ADDR_LEN);
-	// SA
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pSA, MAC_ADDR_LEN);
-	// Priority + 3 bytes of 0
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, (PUCHAR)&Priority, 4);
-
-	// Calculate MIC value from plain text data
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pSrc, Len);
-
-	// Get MIC valude from received frame
-	NdisMoveMemory(OldMic, pSrc + Len, 8);
-
-	// Get MIC value from decrypted plain data
-	RTMPTkipGetMIC(&pAd->PrivateInfo.Rx);
-
-	// Move MIC value from MSDU, this steps should move to data path.
-	// Since the MIC value might cross MPDUs.
-	if(!NdisEqualMemory(pAd->PrivateInfo.Rx.MIC, OldMic, 8))
-	{
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("RTMPTkipCompareMICValue(): TKIP MIC Error !\n"));  //MIC error.
-
-
-		return (FALSE);
-	}
-	return (TRUE);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Compare MIC value of received MSDU
-
-	Arguments:
-		pAd	Pointer to our adapter
-		pLLC		LLC header
-		pSrc        Pointer to the received Plain text data
-		pDA			Pointer to DA address
-		pSA			Pointer to SA address
-		pMICKey		pointer to MIC Key
-		Len         the length of the received plain text data exclude MIC value
-
-	Return Value:
-		TRUE        MIC value matched
-		FALSE       MIC value mismatched
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-BOOLEAN	RTMPTkipCompareMICValueWithLLC(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pLLC,
-	IN	PUCHAR			pSrc,
-	IN	PUCHAR			pDA,
-	IN	PUCHAR			pSA,
-	IN	PUCHAR			pMICKey,
-	IN	UINT			Len)
-{
-	UCHAR	OldMic[8];
-	ULONG	Priority = 0;
-
-	// Init MIC value calculation
-	RTMPTkipSetMICKey(&pAd->PrivateInfo.Rx, pMICKey);
-	// DA
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pDA, MAC_ADDR_LEN);
-	// SA
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pSA, MAC_ADDR_LEN);
-	// Priority + 3 bytes of 0
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, (PUCHAR)&Priority, 4);
-
-	// Start with LLC header
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pLLC, 8);
-
-	// Calculate MIC value from plain text data
-	RTMPTkipAppend(&pAd->PrivateInfo.Rx, pSrc, Len);
-
-	// Get MIC valude from received frame
-	NdisMoveMemory(OldMic, pSrc + Len, 8);
-
-	// Get MIC value from decrypted plain data
-	RTMPTkipGetMIC(&pAd->PrivateInfo.Rx);
-
-	// Move MIC value from MSDU, this steps should move to data path.
-	// Since the MIC value might cross MPDUs.
-	if(!NdisEqualMemory(pAd->PrivateInfo.Rx.MIC, OldMic, 8))
-	{
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("RTMPTkipCompareMICValueWithLLC(): TKIP MIC Error !\n"));  //MIC error.
-
-
-		return (FALSE);
-	}
-	return (TRUE);
-}
-/*
-	========================================================================
-
-	Routine	Description:
-		Copy frame from waiting queue into relative ring buffer and set
-	appropriate ASIC register to kick hardware transmit function
-
-	Arguments:
-		pAd		Pointer	to our adapter
-		PNDIS_PACKET	Pointer to Ndis Packet for MIC calculation
-		pEncap			Pointer to LLC encap data
-		LenEncap		Total encap length, might be 0 which indicates no encap
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPCalculateMICValue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR			pEncap,
-	IN	PCIPHER_KEY		pKey,
-	IN	UCHAR			apidx)
-{
-	PACKET_INFO		PacketInfo;
-	PUCHAR			pSrcBufVA;
-	UINT			SrcBufLen;
-	PUCHAR			pSrc;
-    UCHAR           UserPriority;
-	UCHAR			vlan_offset = 0;
-
-	RTMP_QueryPacketInfo(pPacket, &PacketInfo, &pSrcBufVA, &SrcBufLen);
-
-	UserPriority = RTMP_GET_PACKET_UP(pPacket);
-	pSrc = pSrcBufVA;
-
-	// determine if this is a vlan packet
-	if (((*(pSrc + 12) << 8) + *(pSrc + 13)) == 0x8100)
-		vlan_offset = 4;
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-	{
-		RTMPInitMICEngine(
-			pAd,
-			pKey->Key,
-			pSrc,
-			pSrc + 6,
-			UserPriority,
-			pKey->TxMic);
-	}
-
-
-	if (pEncap != NULL)
-	{
-		// LLC encapsulation
-		RTMPTkipAppend(&pAd->PrivateInfo.Tx, pEncap, 6);
-		// Protocol Type
-		RTMPTkipAppend(&pAd->PrivateInfo.Tx, pSrc + 12 + vlan_offset, 2);
-	}
-	SrcBufLen -= (14 + vlan_offset);
-	pSrc += (14 + vlan_offset);
-	do
-	{
-		if (SrcBufLen > 0)
-		{
-			RTMPTkipAppend(&pAd->PrivateInfo.Tx, pSrc, SrcBufLen);
-		}
-
-		break;	// No need handle next packet
-
-	}	while (TRUE);		// End of copying payload
-
-	// Compute the final MIC Value
-	RTMPTkipGetMIC(&pAd->PrivateInfo.Tx);
-}
-
-
-/************************************************************/
-/* tkip_sbox()																*/
-/* Returns a 16 bit value from a 64K entry table. The Table */
-/* is synthesized from two 256 entry byte wide tables.		*/
-/************************************************************/
-
-UINT tkip_sbox(UINT index)
-{
-	UINT index_low;
-	UINT index_high;
-	UINT left, right;
-
-	index_low = (index % 256);
-	index_high = ((index >> 8) % 256);
-
-	left = Tkip_Sbox_Lower[index_low] + (Tkip_Sbox_Upper[index_low] * 256);
-	right = Tkip_Sbox_Upper[index_high] + (Tkip_Sbox_Lower[index_high] * 256);
-
-	return (left ^ right);
-}
-
-UINT rotr1(UINT a)
-{
-	unsigned int b;
-
-	if ((a & 0x01) == 0x01)
-	{
-		b = (a >> 1) | 0x8000;
-	}
-	else
-	{
-		b = (a >> 1) & 0x7fff;
-	}
-	b = b % 65536;
-	return b;
-}
-
-VOID RTMPTkipMixKey(
-	UCHAR *key,
-	UCHAR *ta,
-	ULONG pnl, /* Least significant 16 bits of PN */
-	ULONG pnh, /* Most significant 32 bits of PN */
-	UCHAR *rc4key,
-	UINT *p1k)
-{
-
-	UINT tsc0;
-	UINT tsc1;
-	UINT tsc2;
-
-	UINT ppk0;
-	UINT ppk1;
-	UINT ppk2;
-	UINT ppk3;
-	UINT ppk4;
-	UINT ppk5;
-
-	INT i;
-	INT j;
-
-	tsc0 = (unsigned int)((pnh >> 16) % 65536); /* msb */
-	tsc1 = (unsigned int)(pnh % 65536);
-	tsc2 = (unsigned int)(pnl % 65536); /* lsb */
-
-	/* Phase 1, step 1 */
-	p1k[0] = tsc1;
-	p1k[1] = tsc0;
-	p1k[2] = (UINT)(ta[0] + (ta[1]*256));
-	p1k[3] = (UINT)(ta[2] + (ta[3]*256));
-	p1k[4] = (UINT)(ta[4] + (ta[5]*256));
-
-	/* Phase 1, step 2 */
-	for (i=0; i<8; i++)
-	{
-		j = 2*(i & 1);
-		p1k[0] = (p1k[0] + tkip_sbox( (p1k[4] ^ ((256*key[1+j]) + key[j])) % 65536 )) % 65536;
-		p1k[1] = (p1k[1] + tkip_sbox( (p1k[0] ^ ((256*key[5+j]) + key[4+j])) % 65536 )) % 65536;
-		p1k[2] = (p1k[2] + tkip_sbox( (p1k[1] ^ ((256*key[9+j]) + key[8+j])) % 65536 )) % 65536;
-		p1k[3] = (p1k[3] + tkip_sbox( (p1k[2] ^ ((256*key[13+j]) + key[12+j])) % 65536 )) % 65536;
-		p1k[4] = (p1k[4] + tkip_sbox( (p1k[3] ^ (((256*key[1+j]) + key[j]))) % 65536 )) % 65536;
-		p1k[4] = (p1k[4] + i) % 65536;
-	}
-
-	/* Phase 2, Step 1 */
-	ppk0 = p1k[0];
-	ppk1 = p1k[1];
-	ppk2 = p1k[2];
-	ppk3 = p1k[3];
-	ppk4 = p1k[4];
-	ppk5 = (p1k[4] + tsc2) % 65536;
-
-	/* Phase2, Step 2 */
-	ppk0 = ppk0 + tkip_sbox( (ppk5 ^ ((256*key[1]) + key[0])) % 65536);
-	ppk1 = ppk1 + tkip_sbox( (ppk0 ^ ((256*key[3]) + key[2])) % 65536);
-	ppk2 = ppk2 + tkip_sbox( (ppk1 ^ ((256*key[5]) + key[4])) % 65536);
-	ppk3 = ppk3 + tkip_sbox( (ppk2 ^ ((256*key[7]) + key[6])) % 65536);
-	ppk4 = ppk4 + tkip_sbox( (ppk3 ^ ((256*key[9]) + key[8])) % 65536);
-	ppk5 = ppk5 + tkip_sbox( (ppk4 ^ ((256*key[11]) + key[10])) % 65536);
-
-	ppk0 = ppk0 + rotr1(ppk5 ^ ((256*key[13]) + key[12]));
-	ppk1 = ppk1 + rotr1(ppk0 ^ ((256*key[15]) + key[14]));
-	ppk2 = ppk2 + rotr1(ppk1);
-	ppk3 = ppk3 + rotr1(ppk2);
-	ppk4 = ppk4 + rotr1(ppk3);
-	ppk5 = ppk5 + rotr1(ppk4);
-
-	/* Phase 2, Step 3 */
-    /* Phase 2, Step 3 */
-
-	tsc0 = (unsigned int)((pnh >> 16) % 65536); /* msb */
-	tsc1 = (unsigned int)(pnh % 65536);
-	tsc2 = (unsigned int)(pnl % 65536); /* lsb */
-
-	rc4key[0] = (tsc2 >> 8) % 256;
-	rc4key[1] = (((tsc2 >> 8) % 256) | 0x20) & 0x7f;
-	rc4key[2] = tsc2 % 256;
-	rc4key[3] = ((ppk5 ^ ((256*key[1]) + key[0])) >> 1) % 256;
-
-	rc4key[4] = ppk0 % 256;
-	rc4key[5] = (ppk0 >> 8) % 256;
-
-	rc4key[6] = ppk1 % 256;
-	rc4key[7] = (ppk1 >> 8) % 256;
-
-	rc4key[8] = ppk2 % 256;
-	rc4key[9] = (ppk2 >> 8) % 256;
-
-	rc4key[10] = ppk3 % 256;
-	rc4key[11] = (ppk3 >> 8) % 256;
-
-	rc4key[12] = ppk4 % 256;
-	rc4key[13] = (ppk4 >> 8) % 256;
-
-	rc4key[14] = ppk5 % 256;
-	rc4key[15] = (ppk5 >> 8) % 256;
-}
-
-
-/************************************************/
-/* construct_mic_header1()                      */
-/* Builds the first MIC header block from       */
-/* header fields.                               */
-/************************************************/
-
-void construct_mic_header1(
-	unsigned char *mic_header1,
-	int header_length,
-	unsigned char *mpdu)
-{
-	mic_header1[0] = (unsigned char)((header_length - 2) / 256);
-	mic_header1[1] = (unsigned char)((header_length - 2) % 256);
-	mic_header1[2] = mpdu[0] & 0xcf;    /* Mute CF poll & CF ack bits */
-	mic_header1[3] = mpdu[1] & 0xc7;    /* Mute retry, more data and pwr mgt bits */
-	mic_header1[4] = mpdu[4];       /* A1 */
-	mic_header1[5] = mpdu[5];
-	mic_header1[6] = mpdu[6];
-	mic_header1[7] = mpdu[7];
-	mic_header1[8] = mpdu[8];
-	mic_header1[9] = mpdu[9];
-	mic_header1[10] = mpdu[10];     /* A2 */
-	mic_header1[11] = mpdu[11];
-	mic_header1[12] = mpdu[12];
-	mic_header1[13] = mpdu[13];
-	mic_header1[14] = mpdu[14];
-	mic_header1[15] = mpdu[15];
-}
-
-/************************************************/
-/* construct_mic_header2()                      */
-/* Builds the last MIC header block from        */
-/* header fields.                               */
-/************************************************/
-
-void construct_mic_header2(
-	unsigned char *mic_header2,
-	unsigned char *mpdu,
-	int a4_exists,
-	int qc_exists)
-{
-	int i;
-
-	for (i = 0; i<16; i++) mic_header2[i]=0x00;
-
-	mic_header2[0] = mpdu[16];    /* A3 */
-	mic_header2[1] = mpdu[17];
-	mic_header2[2] = mpdu[18];
-	mic_header2[3] = mpdu[19];
-	mic_header2[4] = mpdu[20];
-	mic_header2[5] = mpdu[21];
-
-	// In Sequence Control field, mute sequence numer bits (12-bit)
-	mic_header2[6] = mpdu[22] & 0x0f;   /* SC */
-	mic_header2[7] = 0x00; /* mpdu[23]; */
-
-	if ((!qc_exists) & a4_exists)
-	{
-		for (i=0;i<6;i++) mic_header2[8+i] = mpdu[24+i];   /* A4 */
-
-	}
-
-	if (qc_exists && (!a4_exists))
-	{
-		mic_header2[8] = mpdu[24] & 0x0f; /* mute bits 15 - 4 */
-		mic_header2[9] = mpdu[25] & 0x00;
-	}
-
-	if (qc_exists && a4_exists)
-	{
-		for (i=0;i<6;i++) mic_header2[8+i] = mpdu[24+i];   /* A4 */
-
-		mic_header2[14] = mpdu[30] & 0x0f;
-		mic_header2[15] = mpdu[31] & 0x00;
-	}
-}
-
-
-/************************************************/
-/* construct_mic_iv()                           */
-/* Builds the MIC IV from header fields and PN  */
-/************************************************/
-
-void construct_mic_iv(
-	unsigned char *mic_iv,
-	int qc_exists,
-	int a4_exists,
-	unsigned char *mpdu,
-	unsigned int payload_length,
-	unsigned char *pn_vector)
-{
-	int i;
-
-	mic_iv[0] = 0x59;
-	if (qc_exists && a4_exists)
-		mic_iv[1] = mpdu[30] & 0x0f;    /* QoS_TC           */
-	if (qc_exists && !a4_exists)
-		mic_iv[1] = mpdu[24] & 0x0f;   /* mute bits 7-4    */
-	if (!qc_exists)
-		mic_iv[1] = 0x00;
-	for (i = 2; i < 8; i++)
-		mic_iv[i] = mpdu[i + 8];                    /* mic_iv[2:7] = A2[0:5] = mpdu[10:15] */
-#ifdef CONSISTENT_PN_ORDER
-		for (i = 8; i < 14; i++)
-			mic_iv[i] = pn_vector[i - 8];           /* mic_iv[8:13] = PN[0:5] */
-#else
-		for (i = 8; i < 14; i++)
-			mic_iv[i] = pn_vector[13 - i];          /* mic_iv[8:13] = PN[5:0] */
-#endif
-	i = (payload_length / 256);
-	i = (payload_length % 256);
-	mic_iv[14] = (unsigned char) (payload_length / 256);
-	mic_iv[15] = (unsigned char) (payload_length % 256);
-
-}
-
-
-
-/************************************/
-/* bitwise_xor()                    */
-/* A 128 bit, bitwise exclusive or  */
-/************************************/
-
-void bitwise_xor(unsigned char *ina, unsigned char *inb, unsigned char *out)
-{
-	int i;
-	for (i=0; i<16; i++)
-	{
-		out[i] = ina[i] ^ inb[i];
-	}
-}
-
-
-void aes128k128d(unsigned char *key, unsigned char *data, unsigned char *ciphertext)
-{
-	int round;
-	int i;
-	unsigned char intermediatea[16];
-	unsigned char intermediateb[16];
-	unsigned char round_key[16];
-
-	for(i=0; i<16; i++) round_key[i] = key[i];
-
-	for (round = 0; round < 11; round++)
-	{
-		if (round == 0)
-		{
-			xor_128(round_key, data, ciphertext);
-			next_key(round_key, round);
-		}
-		else if (round == 10)
-		{
-			byte_sub(ciphertext, intermediatea);
-			shift_row(intermediatea, intermediateb);
-			xor_128(intermediateb, round_key, ciphertext);
-		}
-		else    /* 1 - 9 */
-		{
-			byte_sub(ciphertext, intermediatea);
-			shift_row(intermediatea, intermediateb);
-			mix_column(&intermediateb[0], &intermediatea[0]);
-			mix_column(&intermediateb[4], &intermediatea[4]);
-			mix_column(&intermediateb[8], &intermediatea[8]);
-			mix_column(&intermediateb[12], &intermediatea[12]);
-			xor_128(intermediatea, round_key, ciphertext);
-			next_key(round_key, round);
-		}
-	}
-
-}
-
-void construct_ctr_preload(
-	unsigned char *ctr_preload,
-	int a4_exists,
-	int qc_exists,
-	unsigned char *mpdu,
-	unsigned char *pn_vector,
-	int c)
-{
-
-	int i = 0;
-	for (i=0; i<16; i++) ctr_preload[i] = 0x00;
-	i = 0;
-
-	ctr_preload[0] = 0x01;                                  /* flag */
-	if (qc_exists && a4_exists) ctr_preload[1] = mpdu[30] & 0x0f;   /* QoC_Control  */
-	if (qc_exists && !a4_exists) ctr_preload[1] = mpdu[24] & 0x0f;
-
-	for (i = 2; i < 8; i++)
-		ctr_preload[i] = mpdu[i + 8];                       /* ctr_preload[2:7] = A2[0:5] = mpdu[10:15] */
-#ifdef CONSISTENT_PN_ORDER
-	  for (i = 8; i < 14; i++)
-			ctr_preload[i] =    pn_vector[i - 8];           /* ctr_preload[8:13] = PN[0:5] */
-#else
-	  for (i = 8; i < 14; i++)
-			ctr_preload[i] =    pn_vector[13 - i];          /* ctr_preload[8:13] = PN[5:0] */
-#endif
-	ctr_preload[14] =  (unsigned char) (c / 256); // Ctr
-	ctr_preload[15] =  (unsigned char) (c % 256);
-
-}
-
-
-//
-// TRUE: Success!
-// FALSE: Decrypt Error!
-//
-BOOLEAN RTMPSoftDecryptTKIP(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pData,
-	IN ULONG	DataByteCnt,
-	IN UCHAR    UserPriority,
-	IN PCIPHER_KEY	pWpaKey)
-{
-	UCHAR			KeyID;
-	UINT			HeaderLen;
-    UCHAR			fc0;
-	UCHAR			fc1;
-	USHORT			fc;
-	UINT			frame_type;
-	UINT			frame_subtype;
-    UINT			from_ds;
-    UINT			to_ds;
-	INT				a4_exists;
-	INT				qc_exists;
-	USHORT			duration;
-	USHORT			seq_control;
-	USHORT			qos_control;
-	UCHAR			TA[MAC_ADDR_LEN];
-	UCHAR			DA[MAC_ADDR_LEN];
-	UCHAR			SA[MAC_ADDR_LEN];
-	UCHAR			RC4Key[16];
-	UINT			p1k[5]; //for mix_key;
-	ULONG			pnl;/* Least significant 16 bits of PN */
-	ULONG			pnh;/* Most significant 32 bits of PN */
-	UINT			num_blocks;
-	UINT			payload_remainder;
-	ARCFOURCONTEXT 	ArcFourContext;
-	UINT			crc32 = 0;
-	UINT			trailfcs = 0;
-	UCHAR			MIC[8];
-	UCHAR			TrailMIC[8];
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
-
-	fc0 = *pData;
-	fc1 = *(pData + 1);
-
-	fc = *((PUSHORT)pData);
-
-	frame_type = ((fc0 >> 2) & 0x03);
-	frame_subtype = ((fc0 >> 4) & 0x0f);
-
-    from_ds = (fc1 & 0x2) >> 1;
-    to_ds = (fc1 & 0x1);
-
-    a4_exists = (from_ds & to_ds);
-    qc_exists = ((frame_subtype == 0x08) ||    /* Assumed QoS subtypes */
-                  (frame_subtype == 0x09) ||   /* Likely to change.    */
-                  (frame_subtype == 0x0a) ||
-                  (frame_subtype == 0x0b)
-                 );
-
-	HeaderLen = 24;
-	if (a4_exists)
-		HeaderLen += 6;
-
-	KeyID = *((PUCHAR)(pData+ HeaderLen + 3));
-	KeyID = KeyID >> 6;
-
-	if (pWpaKey[KeyID].KeyLen == 0)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("RTMPSoftDecryptTKIP failed!(KeyID[%d] Length can not be 0)\n", KeyID));
-		return FALSE;
-	}
-
-	duration = *((PUSHORT)(pData+2));
-
-	seq_control = *((PUSHORT)(pData+22));
-
-	if (qc_exists)
-	{
-		if (a4_exists)
-		{
-			qos_control = *((PUSHORT)(pData+30));
-		}
-		else
-		{
-			qos_control = *((PUSHORT)(pData+24));
-		}
-	}
-
-	if (to_ds == 0 && from_ds == 1)
-	{
-		NdisMoveMemory(DA, pData+4, MAC_ADDR_LEN);
-		NdisMoveMemory(SA, pData+16, MAC_ADDR_LEN);
-		NdisMoveMemory(TA, pData+10, MAC_ADDR_LEN);  //BSSID
-	}
-	else if (to_ds == 0 && from_ds == 0 )
-	{
-		NdisMoveMemory(TA, pData+10, MAC_ADDR_LEN);
-		NdisMoveMemory(DA, pData+4, MAC_ADDR_LEN);
-		NdisMoveMemory(SA, pData+10, MAC_ADDR_LEN);
-	}
-	else if (to_ds == 1 && from_ds == 0)
-	{
-		NdisMoveMemory(SA, pData+10, MAC_ADDR_LEN);
-		NdisMoveMemory(TA, pData+10, MAC_ADDR_LEN);
-		NdisMoveMemory(DA, pData+16, MAC_ADDR_LEN);
-	}
-	else if (to_ds == 1 && from_ds == 1)
-	{
-		NdisMoveMemory(TA, pData+10, MAC_ADDR_LEN);
-		NdisMoveMemory(DA, pData+16, MAC_ADDR_LEN);
-		NdisMoveMemory(SA, pData+22, MAC_ADDR_LEN);
-	}
-
-	num_blocks = (DataByteCnt - 16) / 16;
-	payload_remainder = (DataByteCnt - 16) % 16;
-
-	pnl = (*(pData + HeaderLen)) * 256 + *(pData + HeaderLen + 2);
-	pnh = *((PULONG)(pData + HeaderLen + 4));
-	pnh = cpu2le32(pnh);
-	RTMPTkipMixKey(pWpaKey[KeyID].Key, TA, pnl, pnh, RC4Key, p1k);
-
-	ARCFOUR_INIT(&ArcFourContext, RC4Key, 16);
-
-	ARCFOUR_DECRYPT(&ArcFourContext, pData + HeaderLen, pData + HeaderLen + 8, DataByteCnt - HeaderLen - 8);
-	NdisMoveMemory(&trailfcs, pData + DataByteCnt - 8 - 4, 4);
-	crc32 = RTMP_CALC_FCS32(PPPINITFCS32, pData + HeaderLen, DataByteCnt - HeaderLen - 8 - 4);  //Skip IV+EIV 8 bytes & Skip last 4 bytes(FCS).
-	crc32 ^= 0xffffffff;             /* complement */
-
-    if(crc32 != cpu2le32(trailfcs))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("RTMPSoftDecryptTKIP, WEP Data ICV Error !\n"));	 //ICV error.
-
-		return (FALSE);
-	}
-
-	NdisMoveMemory(TrailMIC, pData + DataByteCnt - 8 - 8 - 4, 8);
-	RTMPInitMICEngine(pAd, pWpaKey[KeyID].Key, DA, SA, UserPriority, pWpaKey[KeyID].RxMic);
-	RTMPTkipAppend(&pAd->PrivateInfo.Tx, pData + HeaderLen, DataByteCnt - HeaderLen - 8 - 12);
-	RTMPTkipGetMIC(&pAd->PrivateInfo.Tx);
-	NdisMoveMemory(MIC, pAd->PrivateInfo.Tx.MIC, 8);
-
-	if (!NdisEqualMemory(MIC, TrailMIC, 8))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RTMPSoftDecryptTKIP, WEP Data MIC Error !\n"));	 //MIC error.
-		//RTMPReportMicError(pAd, &pWpaKey[KeyID]);	// marked by AlbertY @ 20060630
-		return (FALSE);
-	}
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
-	//DBGPRINT(RT_DEBUG_TRACE, "RTMPSoftDecryptTKIP Decript done!!\n");
-	return TRUE;
-}
-
-
-
-
-BOOLEAN RTMPSoftDecryptAES(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pData,
-	IN ULONG	DataByteCnt,
-	IN PCIPHER_KEY	pWpaKey)
-{
-	UCHAR			KeyID;
-	UINT			HeaderLen;
-	UCHAR			PN[6];
-	UINT			payload_len;
-	UINT			num_blocks;
-	UINT			payload_remainder;
-	USHORT			fc;
-	UCHAR			fc0;
-	UCHAR			fc1;
-	UINT			frame_type;
-	UINT			frame_subtype;
-	UINT			from_ds;
-	UINT			to_ds;
-	INT				a4_exists;
-	INT				qc_exists;
-	UCHAR			aes_out[16];
-	int 			payload_index;
-	UINT 			i;
-	UCHAR 			ctr_preload[16];
-	UCHAR 			chain_buffer[16];
-	UCHAR 			padded_buffer[16];
-	UCHAR 			mic_iv[16];
-	UCHAR 			mic_header1[16];
-	UCHAR 			mic_header2[16];
-	UCHAR			MIC[8];
-	UCHAR			TrailMIC[8];
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
-
-	fc0 = *pData;
-	fc1 = *(pData + 1);
-
-	fc = *((PUSHORT)pData);
-
-	frame_type = ((fc0 >> 2) & 0x03);
-	frame_subtype = ((fc0 >> 4) & 0x0f);
-
-	from_ds = (fc1 & 0x2) >> 1;
-	to_ds = (fc1 & 0x1);
-
-	a4_exists = (from_ds & to_ds);
-	qc_exists = ((frame_subtype == 0x08) ||    /* Assumed QoS subtypes */
-				  (frame_subtype == 0x09) ||   /* Likely to change.    */
-				  (frame_subtype == 0x0a) ||
-				  (frame_subtype == 0x0b)
-				 );
-
-	HeaderLen = 24;
-	if (a4_exists)
-		HeaderLen += 6;
-
-	KeyID = *((PUCHAR)(pData+ HeaderLen + 3));
-	KeyID = KeyID >> 6;
-
-	if (pWpaKey[KeyID].KeyLen == 0)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("RTMPSoftDecryptAES failed!(KeyID[%d] Length can not be 0)\n", KeyID));
-		return FALSE;
-	}
-
-	PN[0] = *(pData+ HeaderLen);
-	PN[1] = *(pData+ HeaderLen + 1);
-	PN[2] = *(pData+ HeaderLen + 4);
-	PN[3] = *(pData+ HeaderLen + 5);
-	PN[4] = *(pData+ HeaderLen + 6);
-	PN[5] = *(pData+ HeaderLen + 7);
-
-	payload_len = DataByteCnt - HeaderLen - 8 - 8;	// 8 bytes for CCMP header , 8 bytes for MIC
-	payload_remainder = (payload_len) % 16;
-	num_blocks = (payload_len) / 16;
-
-
-
-	// Find start of payload
-	payload_index = HeaderLen + 8; //IV+EIV
-
-	for (i=0; i< num_blocks; i++)
-	{
-		construct_ctr_preload(ctr_preload,
-								a4_exists,
-								qc_exists,
-								pData,
-								PN,
-								i+1 );
-
-		aes128k128d(pWpaKey[KeyID].Key, ctr_preload, aes_out);
-
-		bitwise_xor(aes_out, pData + payload_index, chain_buffer);
-		NdisMoveMemory(pData + payload_index - 8, chain_buffer, 16);
-		payload_index += 16;
-	}
-
-	//
-	// If there is a short final block, then pad it
-	// encrypt it and copy the unpadded part back
-	//
-	if (payload_remainder > 0)
-	{
-		construct_ctr_preload(ctr_preload,
-								a4_exists,
-								qc_exists,
-								pData,
-								PN,
-								num_blocks + 1);
-
-		NdisZeroMemory(padded_buffer, 16);
-		NdisMoveMemory(padded_buffer, pData + payload_index, payload_remainder);
-
-		aes128k128d(pWpaKey[KeyID].Key, ctr_preload, aes_out);
-
-		bitwise_xor(aes_out, padded_buffer, chain_buffer);
-		NdisMoveMemory(pData + payload_index - 8, chain_buffer, payload_remainder);
-		payload_index += payload_remainder;
-	}
-
-	//
-	// Descrypt the MIC
-	//
-	construct_ctr_preload(ctr_preload,
-							a4_exists,
-							qc_exists,
-							pData,
-							PN,
-							0);
-	NdisZeroMemory(padded_buffer, 16);
-	NdisMoveMemory(padded_buffer, pData + payload_index, 8);
-
-	aes128k128d(pWpaKey[KeyID].Key, ctr_preload, aes_out);
-
-	bitwise_xor(aes_out, padded_buffer, chain_buffer);
-
-	NdisMoveMemory(TrailMIC, chain_buffer, 8);
-
-	//
-	// Calculate MIC
-	//
-
-	//Force the protected frame bit on
-	*(pData + 1) = *(pData + 1) | 0x40;
-
-	// Find start of payload
-	// Because the CCMP header has been removed
-	payload_index = HeaderLen;
-
-	construct_mic_iv(
-					mic_iv,
-					qc_exists,
-					a4_exists,
-					pData,
-					payload_len,
-					PN);
-
-	construct_mic_header1(
-						mic_header1,
-						HeaderLen,
-						pData);
-
-	construct_mic_header2(
-						mic_header2,
-						pData,
-						a4_exists,
-						qc_exists);
-
-	aes128k128d(pWpaKey[KeyID].Key, mic_iv, aes_out);
-	bitwise_xor(aes_out, mic_header1, chain_buffer);
-	aes128k128d(pWpaKey[KeyID].Key, chain_buffer, aes_out);
-	bitwise_xor(aes_out, mic_header2, chain_buffer);
-	aes128k128d(pWpaKey[KeyID].Key, chain_buffer, aes_out);
-
-	// iterate through each 16 byte payload block
-	for (i = 0; i < num_blocks; i++)
-	{
-		bitwise_xor(aes_out, pData + payload_index, chain_buffer);
-		payload_index += 16;
-		aes128k128d(pWpaKey[KeyID].Key, chain_buffer, aes_out);
-	}
-
-	// Add on the final payload block if it needs padding
-	if (payload_remainder > 0)
-	{
-		NdisZeroMemory(padded_buffer, 16);
-		NdisMoveMemory(padded_buffer, pData + payload_index, payload_remainder);
-
-		bitwise_xor(aes_out, padded_buffer, chain_buffer);
-		aes128k128d(pWpaKey[KeyID].Key, chain_buffer, aes_out);
-	}
-
-	// aes_out contains padded mic, discard most significant
-	// 8 bytes to generate 64 bit MIC
-	for (i = 0 ; i < 8; i++) MIC[i] = aes_out[i];
-
-	if (!NdisEqualMemory(MIC, TrailMIC, 8))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RTMPSoftDecryptAES, MIC Error !\n"));	 //MIC error.
-		return FALSE;
-	}
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, (PUCHAR)pData, DIR_READ, FALSE);
-#endif
-
-	return TRUE;
-}
-
-/****************************************/
-/* aes128k128d()                        */
-/* Performs a 128 bit AES encrypt with  */
-/* 128 bit data.                        */
-/****************************************/
-VOID xor_128(
-	IN  PUCHAR  a,
-	IN  PUCHAR  b,
-	OUT PUCHAR  out)
-{
-	INT i;
-
-	for (i=0;i<16; i++)
-	{
-		out[i] = a[i] ^ b[i];
-	}
-}
-
-VOID next_key(
-	IN  PUCHAR  key,
-	IN  INT     round)
-{
-	UCHAR       rcon;
-	UCHAR       sbox_key[4];
-	UCHAR       rcon_table[12] =
-	{
-		0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
-		0x1b, 0x36, 0x36, 0x36
-	};
-
-	sbox_key[0] = RTMPCkipSbox(key[13]);
-	sbox_key[1] = RTMPCkipSbox(key[14]);
-	sbox_key[2] = RTMPCkipSbox(key[15]);
-	sbox_key[3] = RTMPCkipSbox(key[12]);
-
-	rcon = rcon_table[round];
-
-	xor_32(&key[0], sbox_key, &key[0]);
-	key[0] = key[0] ^ rcon;
-
-	xor_32(&key[4], &key[0], &key[4]);
-	xor_32(&key[8], &key[4], &key[8]);
-	xor_32(&key[12], &key[8], &key[12]);
-}
-
-VOID xor_32(
-	IN  PUCHAR  a,
-	IN  PUCHAR  b,
-	OUT PUCHAR  out)
-{
-	INT i;
-
-	for (i=0;i<4; i++)
-	{
-		out[i] = a[i] ^ b[i];
-	}
-}
-
-VOID byte_sub(
-	IN  PUCHAR  in,
-	OUT PUCHAR  out)
-{
-	INT i;
-
-	for (i=0; i< 16; i++)
-	{
-		out[i] = RTMPCkipSbox(in[i]);
-	}
-}
-
-UCHAR RTMPCkipSbox(
-	IN  UCHAR   a)
-{
-	return SboxTable[(int)a];
-}
-
-VOID shift_row(
-	IN  PUCHAR  in,
-	OUT PUCHAR  out)
-{
-	out[0] =  in[0];
-	out[1] =  in[5];
-	out[2] =  in[10];
-	out[3] =  in[15];
-	out[4] =  in[4];
-	out[5] =  in[9];
-	out[6] =  in[14];
-	out[7] =  in[3];
-	out[8] =  in[8];
-	out[9] =  in[13];
-	out[10] = in[2];
-	out[11] = in[7];
-	out[12] = in[12];
-	out[13] = in[1];
-	out[14] = in[6];
-	out[15] = in[11];
-}
-
-VOID mix_column(
-	IN  PUCHAR  in,
-	OUT PUCHAR  out)
-{
-	INT         i;
-	UCHAR       add1b[4];
-	UCHAR       add1bf7[4];
-	UCHAR       rotl[4];
-	UCHAR       swap_halfs[4];
-	UCHAR       andf7[4];
-	UCHAR       rotr[4];
-	UCHAR       temp[4];
-	UCHAR       tempb[4];
-
-	for (i=0 ; i<4; i++)
-	{
-		if ((in[i] & 0x80)== 0x80)
-			add1b[i] = 0x1b;
-		else
-			add1b[i] = 0x00;
-	}
-
-	swap_halfs[0] = in[2];    /* Swap halfs */
-	swap_halfs[1] = in[3];
-	swap_halfs[2] = in[0];
-	swap_halfs[3] = in[1];
-
-	rotl[0] = in[3];        /* Rotate left 8 bits */
-	rotl[1] = in[0];
-	rotl[2] = in[1];
-	rotl[3] = in[2];
-
-	andf7[0] = in[0] & 0x7f;
-	andf7[1] = in[1] & 0x7f;
-	andf7[2] = in[2] & 0x7f;
-	andf7[3] = in[3] & 0x7f;
-
-	for (i = 3; i>0; i--)    /* logical shift left 1 bit */
-	{
-		andf7[i] = andf7[i] << 1;
-		if ((andf7[i-1] & 0x80) == 0x80)
-		{
-			andf7[i] = (andf7[i] | 0x01);
-		}
-	}
-	andf7[0] = andf7[0] << 1;
-	andf7[0] = andf7[0] & 0xfe;
-
-	xor_32(add1b, andf7, add1bf7);
-
-	xor_32(in, add1bf7, rotr);
-
-	temp[0] = rotr[0];         /* Rotate right 8 bits */
-	rotr[0] = rotr[1];
-	rotr[1] = rotr[2];
-	rotr[2] = rotr[3];
-	rotr[3] = temp[0];
-
-	xor_32(add1bf7, rotr, temp);
-	xor_32(swap_halfs, rotl,tempb);
-	xor_32(temp, tempb, out);
-}
-
+#include "../../rt2870/common/rtmp_tkip.c"
diff --git a/drivers/staging/rt3070/common/rtmp_wep.c b/drivers/staging/rt3070/common/rtmp_wep.c
index f5f0a3b..7197985 100644
--- a/drivers/staging/rt3070/common/rtmp_wep.c
+++ b/drivers/staging/rt3070/common/rtmp_wep.c
@@ -1,508 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtmp_wep.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Paul Wu		10-28-02		Initial
-*/
-
-#include	"../rt_config.h"
-
-UINT FCSTAB_32[256] =
-{
-	0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
-	0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
-	0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
-	0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
-	0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
-	0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
-	0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
-	0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
-	0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
-	0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
-	0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
-	0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
-	0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
-	0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
-	0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
-	0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
-	0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
-	0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
-	0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
-	0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
-	0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
-	0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
-	0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
-	0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
-	0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
-	0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
-	0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
-	0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
-	0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
-	0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
-	0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
-	0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
-	0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
-	0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
-	0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
-	0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
-	0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
-	0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
-	0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
-	0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
-	0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
-	0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
-	0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
-	0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
-	0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
-	0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
-	0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
-	0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
-	0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
-	0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
-	0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
-	0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
-	0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
-	0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
-	0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
-	0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
-	0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
-	0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
-	0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
-	0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
-	0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
-	0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
-	0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
-	0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
-};
-
-/*
-UCHAR   WEPKEY[] = {
-		//IV
-		0x00, 0x11, 0x22,
-		//WEP KEY
-		0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC
-	};
- */
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Init WEP function.
-
-	Arguments:
-      pAd		Pointer to our adapter
-		pKey        Pointer to the WEP KEY
-		KeyId		   WEP Key ID
-		KeyLen      the length of WEP KEY
-		pDest       Pointer to the destination which Encryption data will store in.
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPInitWepEngine(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pKey,
-	IN	UCHAR			KeyId,
-	IN	UCHAR			KeyLen,
-	IN OUT	PUCHAR		pDest)
-{
-	UINT i;
-	UCHAR   WEPKEY[] = {
-		//IV
-		0x00, 0x11, 0x22,
-		//WEP KEY
-		0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC
-	};
-
-	pAd->PrivateInfo.FCSCRC32 = PPPINITFCS32;   //Init crc32.
-
-#ifdef CONFIG_STA_SUPPORT
-    if (pAd->StaCfg.bCkipOn && (pAd->StaCfg.CkipFlag & 0x10) && (pAd->OpMode == OPMODE_STA))
-    {
-        ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, pKey, KeyLen);  //INIT SBOX, KEYLEN+3(IV)
-        NdisMoveMemory(pDest, pKey, 3);  //Append Init Vector
-    }
-    else
-#endif // CONFIG_STA_SUPPORT //
-    {
-		NdisMoveMemory(WEPKEY + 3, pKey, KeyLen);
-
-        for(i = 0; i < 3; i++)
-			WEPKEY[i] = RandomByte(pAd);   //Call mlme RandomByte() function.
-		ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, WEPKEY, KeyLen + 3);  //INIT SBOX, KEYLEN+3(IV)
-
-		NdisMoveMemory(pDest, WEPKEY, 3);  //Append Init Vector
-    }
-	*(pDest+3) = (KeyId << 6);       //Append KEYID
-
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Encrypt transimitted data
-
-	Arguments:
-      pAd		Pointer to our adapter
-      pSrc        Pointer to the transimitted source data that will be encrypt
-      pDest       Pointer to the destination where entryption data will be store in.
-      Len			Indicate the length of the source data
-
-	Return Value:
-      None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPEncryptData(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pSrc,
-	IN	PUCHAR			pDest,
-	IN	UINT			Len)
-{
-	pAd->PrivateInfo.FCSCRC32 = RTMP_CALC_FCS32(pAd->PrivateInfo.FCSCRC32, pSrc, Len);
-	ARCFOUR_ENCRYPT(&pAd->PrivateInfo.WEPCONTEXT, pDest, pSrc, Len);
-}
-
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Decrypt received WEP data
-
-	Arguments:
-		pAdapter		Pointer to our adapter
-		pSrc        Pointer to the received data
-		Len         the length of the received data
-
-	Return Value:
-		TRUE        Decrypt WEP data success
-		FALSE       Decrypt WEP data failed
-
-	Note:
-
-	========================================================================
-*/
-BOOLEAN	RTMPSoftDecryptWEP(
-	IN PRTMP_ADAPTER 	pAd,
-	IN PUCHAR			pData,
-	IN ULONG			DataByteCnt,
-	IN PCIPHER_KEY		pGroupKey)
-{
-	UINT	trailfcs;
-	UINT    crc32;
-	UCHAR	KeyIdx;
-	UCHAR   WEPKEY[] = {
-		//IV
-		0x00, 0x11, 0x22,
-		//WEP KEY
-		0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC
-	};
-	UCHAR 	*pPayload = (UCHAR *)pData + LENGTH_802_11;
-	ULONG	payload_len = DataByteCnt - LENGTH_802_11;
-
-	NdisMoveMemory(WEPKEY, pPayload, 3);    //Get WEP IV
-
-	KeyIdx = (*(pPayload + 3) & 0xc0) >> 6;
-	if (pGroupKey[KeyIdx].KeyLen == 0)
-		return (FALSE);
-
-	NdisMoveMemory(WEPKEY + 3, pGroupKey[KeyIdx].Key, pGroupKey[KeyIdx].KeyLen);
-	ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, WEPKEY, pGroupKey[KeyIdx].KeyLen + 3);
-	ARCFOUR_DECRYPT(&pAd->PrivateInfo.WEPCONTEXT, pPayload, pPayload + 4, payload_len - 4);
-	NdisMoveMemory(&trailfcs, pPayload + payload_len - 8, 4);
-	crc32 = RTMP_CALC_FCS32(PPPINITFCS32, pPayload, payload_len - 8);  //Skip last 4 bytes(FCS).
-	crc32 ^= 0xffffffff;             /* complement */
-
-    if(crc32 != cpu2le32(trailfcs))
-    {
-		DBGPRINT(RT_DEBUG_TRACE, ("! WEP Data CRC Error !\n"));	 //CRC error.
-		return (FALSE);
-	}
-	return (TRUE);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		The Stream Cipher Encryption Algorithm "ARCFOUR" initialize
-
-	Arguments:
-	   Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-		pKey        Pointer to the WEP KEY
-		KeyLen      Indicate the length fo the WEP KEY
-
-	Return Value:
-	   None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	ARCFOUR_INIT(
-	IN	PARCFOURCONTEXT	Ctx,
-	IN	PUCHAR			pKey,
-	IN	UINT			KeyLen)
-{
-	UCHAR	t, u;
-	UINT	keyindex;
-	UINT	stateindex;
-	PUCHAR	state;
-	UINT	counter;
-
-	state = Ctx->STATE;
-	Ctx->X = 0;
-	Ctx->Y = 0;
-	for (counter = 0; counter < 256; counter++)
-		state[counter] = (UCHAR)counter;
-	keyindex = 0;
-	stateindex = 0;
-	for (counter = 0; counter < 256; counter++)
-	{
-		t = state[counter];
-		stateindex = (stateindex + pKey[keyindex] + t) & 0xff;
-		u = state[stateindex];
-		state[stateindex] = t;
-		state[counter] = u;
-		if (++keyindex >= KeyLen)
-			keyindex = 0;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Get bytes from ARCFOUR CONTEXT (S-BOX)
-
-	Arguments:
-	   Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-
-	Return Value:
-	   UCHAR  - the value of the ARCFOUR CONTEXT (S-BOX)
-
-	Note:
-
-	========================================================================
-*/
-UCHAR	ARCFOUR_BYTE(
-	IN	PARCFOURCONTEXT		Ctx)
-{
-  UINT x;
-  UINT y;
-  UCHAR sx, sy;
-  PUCHAR state;
-
-  state = Ctx->STATE;
-  x = (Ctx->X + 1) & 0xff;
-  sx = state[x];
-  y = (sx + Ctx->Y) & 0xff;
-  sy = state[y];
-  Ctx->X = x;
-  Ctx->Y = y;
-  state[y] = sx;
-  state[x] = sy;
-
-  return(state[(sx + sy) & 0xff]);
-
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		The Stream Cipher Decryption Algorithm
-
-	Arguments:
-		Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-		pDest			Pointer to the Destination
-		pSrc        Pointer to the Source data
-		Len         Indicate the length of the Source data
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	ARCFOUR_DECRYPT(
-	IN	PARCFOURCONTEXT	Ctx,
-	IN	PUCHAR			pDest,
-	IN	PUCHAR			pSrc,
-	IN	UINT			Len)
-{
-	UINT i;
-
-	for (i = 0; i < Len; i++)
-		pDest[i] = pSrc[i] ^ ARCFOUR_BYTE(Ctx);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		The Stream Cipher Encryption Algorithm
-
-	Arguments:
-		Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-		pDest			Pointer to the Destination
-		pSrc        Pointer to the Source data
-		Len         Indicate the length of the Source dta
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	ARCFOUR_ENCRYPT(
-	IN	PARCFOURCONTEXT	Ctx,
-	IN	PUCHAR			pDest,
-	IN	PUCHAR			pSrc,
-	IN	UINT			Len)
-{
-	UINT i;
-
-	for (i = 0; i < Len; i++)
-		pDest[i] = pSrc[i] ^ ARCFOUR_BYTE(Ctx);
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		The Stream Cipher Encryption Algorithm which conform to the special requirement to encrypt  GTK.
-
-	Arguments:
-		Ctx         Pointer to ARCFOUR CONTEXT (SBOX)
-		pDest			Pointer to the Destination
-		pSrc        Pointer to the Source data
-		Len         Indicate the length of the Source dta
-
-
-	========================================================================
-*/
-
-VOID	WPAARCFOUR_ENCRYPT(
-	IN	PARCFOURCONTEXT	Ctx,
-	IN	PUCHAR			pDest,
-	IN	PUCHAR			pSrc,
-	IN	UINT			Len)
-{
-	UINT i;
-        //discard first 256 bytes
-	for (i = 0; i < 256; i++)
-            ARCFOUR_BYTE(Ctx);
-
-	for (i = 0; i < Len; i++)
-		pDest[i] = pSrc[i] ^ ARCFOUR_BYTE(Ctx);
-}
-
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Calculate a new FCS given the current FCS and the new data.
-
-	Arguments:
-		Fcs	      the original FCS value
-		Cp          pointer to the data which will be calculate the FCS
-		Len         the length of the data
-
-	Return Value:
-		UINT - FCS 32 bits
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-UINT	RTMP_CALC_FCS32(
-	IN	UINT	Fcs,
-	IN	PUCHAR	Cp,
-	IN	INT		Len)
-{
-	while (Len--)
-	   Fcs = (((Fcs) >> 8) ^ FCSTAB_32[((Fcs) ^ (*Cp++)) & 0xff]);
-
-	return (Fcs);
-}
-
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Get last FCS and encrypt it to the destination
-
-	Arguments:
-		pDest			Pointer to the Destination
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPSetICV(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR	pDest)
-{
-	pAd->PrivateInfo.FCSCRC32 ^= 0xffffffff;             /* complement */
-	pAd->PrivateInfo.FCSCRC32 = cpu2le32(pAd->PrivateInfo.FCSCRC32);
-
-	ARCFOUR_ENCRYPT(&pAd->PrivateInfo.WEPCONTEXT, pDest, (PUCHAR) &pAd->PrivateInfo.FCSCRC32, 4);
-}
-
+#include "../../rt2870/common/rtmp_wep.c"
diff --git a/drivers/staging/rt3070/common/rtusb_bulk.c b/drivers/staging/rt3070/common/rtusb_bulk.c
index 1a05703..762ecfe 100644
--- a/drivers/staging/rt3070/common/rtusb_bulk.c
+++ b/drivers/staging/rt3070/common/rtusb_bulk.c
@@ -1,1382 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtusb_bulk.c
-
-	Abstract:
-
-	Revision History:
-	Who			When		What
-	--------	----------	----------------------------------------------
-	Name		Date		Modification logs
-	Paul Lin	06-25-2004	created
-
-*/
-
-#include	"../rt_config.h"
-// Match total 6 bulkout endpoint to corresponding queue.
-UCHAR	EpToQueue[6]={FIFO_EDCA, FIFO_EDCA, FIFO_EDCA, FIFO_EDCA, FIFO_EDCA, FIFO_MGMT};
-
-//static BOOLEAN SingleBulkOut = FALSE;
-
-void RTUSB_FILL_BULK_URB (struct urb *pUrb,
-	struct usb_device *pUsb_Dev,
-	unsigned int bulkpipe,
-	void *pTransferBuf,
-	int BufSize,
-	usb_complete_t Complete,
-	void *pContext)
-{
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-	usb_fill_bulk_urb(pUrb, pUsb_Dev, bulkpipe, pTransferBuf, BufSize, (usb_complete_t)Complete, pContext);
-#else
-	FILL_BULK_URB(pUrb, pUsb_Dev, bulkpipe, pTransferBuf, BufSize, Complete, pContext);
-#endif
-
-}
-
-VOID	RTUSBInitTxDesc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTX_CONTEXT		pTxContext,
-	IN	UCHAR			BulkOutPipeId,
-	IN	usb_complete_t	Func)
-{
-	PURB				pUrb;
-	PUCHAR				pSrc = NULL;
-	POS_COOKIE			pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	pUrb = pTxContext->pUrb;
-	ASSERT(pUrb);
-
-	// Store BulkOut PipeId
-	pTxContext->BulkOutPipeId = BulkOutPipeId;
-
-	if (pTxContext->bAggregatible)
-	{
-		pSrc = &pTxContext->TransferBuffer->Aggregation[2];
-	}
-	else
-	{
-		pSrc = (PUCHAR) pTxContext->TransferBuffer->field.WirelessPacket;
-	}
-
-
-	//Initialize a tx bulk urb
-	RTUSB_FILL_BULK_URB(pUrb,
-						pObj->pUsb_Dev,
-						usb_sndbulkpipe(pObj->pUsb_Dev, pAd->BulkOutEpAddr[BulkOutPipeId]),
-						pSrc,
-						pTxContext->BulkOutSize,
-						Func,
-						pTxContext);
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-	if (pTxContext->bAggregatible)
-		pUrb->transfer_dma	= (pTxContext->data_dma + TX_BUFFER_NORMSIZE + 2);
-	else
-		pUrb->transfer_dma	= pTxContext->data_dma;
-
-	pUrb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
-#endif
-
-}
-
-VOID	RTUSBInitHTTxDesc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PHT_TX_CONTEXT	pTxContext,
-	IN	UCHAR			BulkOutPipeId,
-	IN	ULONG			BulkOutSize,
-	IN	usb_complete_t	Func)
-{
-	PURB				pUrb;
-	PUCHAR				pSrc = NULL;
-	POS_COOKIE			pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	pUrb = pTxContext->pUrb;
-	ASSERT(pUrb);
-
-	// Store BulkOut PipeId
-	pTxContext->BulkOutPipeId = BulkOutPipeId;
-
-	pSrc = &pTxContext->TransferBuffer->field.WirelessPacket[pTxContext->NextBulkOutPosition];
-
-
-	//Initialize a tx bulk urb
-	RTUSB_FILL_BULK_URB(pUrb,
-						pObj->pUsb_Dev,
-						usb_sndbulkpipe(pObj->pUsb_Dev, pAd->BulkOutEpAddr[BulkOutPipeId]),
-						pSrc,
-						BulkOutSize,
-						Func,
-						pTxContext);
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-	pUrb->transfer_dma	= (pTxContext->data_dma + pTxContext->NextBulkOutPosition);
-	pUrb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
-#endif
-
-}
-
-VOID	RTUSBInitRxDesc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PRX_CONTEXT		pRxContext)
-{
-	PURB				pUrb;
-	POS_COOKIE			pObj = (POS_COOKIE) pAd->OS_Cookie;
-	ULONG				RX_bulk_size;
-
-
-	pUrb = pRxContext->pUrb;
-	ASSERT(pUrb);
-
-	if ( pAd->BulkInMaxPacketSize == 64)
-		RX_bulk_size = 4096;
-	else
-		RX_bulk_size = MAX_RXBULK_SIZE;
-
-	//Initialize a rx bulk urb
-	RTUSB_FILL_BULK_URB(pUrb,
-						pObj->pUsb_Dev,
-						usb_rcvbulkpipe(pObj->pUsb_Dev, pAd->BulkInEpAddr),
-						&(pRxContext->TransferBuffer[pAd->NextRxBulkInPosition]),
-						RX_bulk_size - (pAd->NextRxBulkInPosition),
-						(usb_complete_t)RTUSBBulkRxComplete,
-						(void *)pRxContext);
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-	pUrb->transfer_dma	= pRxContext->data_dma + pAd->NextRxBulkInPosition;
-	pUrb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
-#endif
-
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-
-#define BULK_OUT_LOCK(pLock, IrqFlags)	\
-		if(1 /*!(in_interrupt() & 0xffff0000)*/)	\
-			RTMP_IRQ_LOCK((pLock), IrqFlags);
-
-#define BULK_OUT_UNLOCK(pLock, IrqFlags)	\
-		if(1 /*!(in_interrupt() & 0xffff0000)*/)	\
-			RTMP_IRQ_UNLOCK((pLock), IrqFlags);
-
-
-VOID	RTUSBBulkOutDataPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BulkOutPipeId,
-	IN	UCHAR			Index)
-{
-
-	PHT_TX_CONTEXT	pHTTXContext;
-	PURB			pUrb;
-	int				ret = 0;
-	PTXINFO_STRUC	pTxInfo, pLastTxInfo = NULL;
-	PTXWI_STRUC             pTxWI;
-	ULONG			TmpBulkEndPos, ThisBulkSize;
-	unsigned long	IrqFlags = 0, IrqFlags2 = 0;
-	PUCHAR			pWirelessPkt, pAppendant;
-	BOOLEAN			bTxQLastRound = FALSE;
-	UCHAR			allzero[4]= {0x0,0x0,0x0,0x0};
-
-	BULK_OUT_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-	if ((pAd->BulkOutPending[BulkOutPipeId] == TRUE) || RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NEED_STOP_TX))
-	{
-		BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-		return;
-	}
-	pAd->BulkOutPending[BulkOutPipeId] = TRUE;
-
-	if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)
-		)
-	{
-		pAd->BulkOutPending[BulkOutPipeId] = FALSE;
-		BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-		return;
-	}
-	BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-
-
-	pHTTXContext = &(pAd->TxContext[BulkOutPipeId]);
-
-	BULK_OUT_LOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags2);
-	if ((pHTTXContext->ENextBulkOutPosition == pHTTXContext->CurWritePosition)
-		|| ((pHTTXContext->ENextBulkOutPosition-8) == pHTTXContext->CurWritePosition))
-	{
-		BULK_OUT_UNLOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags2);
-
-		BULK_OUT_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-		pAd->BulkOutPending[BulkOutPipeId] = FALSE;
-
-		// Clear Data flag
-		RTUSB_CLEAR_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_FRAG << BulkOutPipeId));
-		RTUSB_CLEAR_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << BulkOutPipeId));
-
-		BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-		return;
-	}
-
-	// Clear Data flag
-	RTUSB_CLEAR_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_FRAG << BulkOutPipeId));
-	RTUSB_CLEAR_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << BulkOutPipeId));
-
-	//DBGPRINT(RT_DEBUG_TRACE,("BulkOut-B:I=0x%lx, CWPos=%ld, CWRPos=%ld, NBPos=%ld, ENBPos=%ld, bCopy=%d!\n", in_interrupt(),
-	//							pHTTXContext->CurWritePosition, pHTTXContext->CurWriteRealPos, pHTTXContext->NextBulkOutPosition,
-	//							pHTTXContext->ENextBulkOutPosition, pHTTXContext->bCopySavePad));
-	pHTTXContext->NextBulkOutPosition = pHTTXContext->ENextBulkOutPosition;
-	ThisBulkSize = 0;
-	TmpBulkEndPos = pHTTXContext->NextBulkOutPosition;
-	pWirelessPkt = &pHTTXContext->TransferBuffer->field.WirelessPacket[0];
-
-	if ((pHTTXContext->bCopySavePad == TRUE))
-	{
-		if (RTMPEqualMemory(pHTTXContext->SavedPad, allzero,4))
-		{
-			DBGPRINT_RAW(RT_DEBUG_ERROR,("e1, allzero : %x  %x  %x  %x  %x  %x  %x  %x \n",
-				pHTTXContext->SavedPad[0], pHTTXContext->SavedPad[1], pHTTXContext->SavedPad[2],pHTTXContext->SavedPad[3]
-				,pHTTXContext->SavedPad[4], pHTTXContext->SavedPad[5], pHTTXContext->SavedPad[6],pHTTXContext->SavedPad[7]));
-		}
-		NdisMoveMemory(&pWirelessPkt[TmpBulkEndPos], pHTTXContext->SavedPad, 8);
-		pHTTXContext->bCopySavePad = FALSE;
-		if (pAd->bForcePrintTX == TRUE)
-			DBGPRINT(RT_DEBUG_TRACE,("RTUSBBulkOutDataPacket --> COPY PAD. CurWrite = %ld, NextBulk = %ld.   ENextBulk = %ld.\n",   pHTTXContext->CurWritePosition, pHTTXContext->NextBulkOutPosition, pHTTXContext->ENextBulkOutPosition));
-	}
-
-	do
-	{
-		pTxInfo = (PTXINFO_STRUC)&pWirelessPkt[TmpBulkEndPos];
-		pTxWI = (PTXWI_STRUC)&pWirelessPkt[TmpBulkEndPos + TXINFO_SIZE];
-
-		if (pAd->bForcePrintTX == TRUE)
-			DBGPRINT(RT_DEBUG_TRACE, ("RTUSBBulkOutDataPacket AMPDU = %d.\n",   pTxWI->AMPDU));
-
-		// add by Iverson, limit BulkOut size to 4k to pass WMM b mode 2T1R test items
-		//if ((ThisBulkSize != 0)  && (pTxWI->AMPDU == 0))
-		if ((ThisBulkSize != 0) && (pTxWI->PHYMODE == MODE_CCK))
-		{
-#ifdef INF_AMAZON_SE
-			/*Iverson Add for AMAZON USB (RT2070 &&  RT3070) to pass WMM A2-T4 ~ A2-T10*/
-			if(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED))
-			{
-				/*Iverson patch for WMM A5-T07 ,WirelessStaToWirelessSta do not bulk out aggregate*/
-				if(pTxWI->PacketId == 6)
-                {
-                	pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-                	break;
-                }
-				else if (BulkOutPipeId == 1)
-				{
-					/*BK  No Limit BulkOut size .*/
-					pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-					break;
-				}
-				else if (((ThisBulkSize&0xffff8000) != 0) || (((ThisBulkSize&0x1000) == 0x1000) &&  (BulkOutPipeId == 0)  ))
-				{
-					/*BE  Limit BulkOut size to about 4k bytes.*/
-					pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-					break;
-				}
-				else if (((ThisBulkSize&0xffff8000) != 0) || (((ThisBulkSize&0x1c00) == 0x1c00) &&  (BulkOutPipeId == 2)  ))
-				{
-					/*VI Limit BulkOut size to about 7k bytes.*/
-					pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-					break;
-				}
-				else if (((ThisBulkSize&0xffff8000) != 0) || (((ThisBulkSize&0x2500) == 0x2500) &&  (BulkOutPipeId == 3)  ))
-				{
-					/*VO Limit BulkOut size to about 9k bytes.*/
-					pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-					break;
-				}
-			}
-			else if (((ThisBulkSize&0xffff8000) != 0) || ((ThisBulkSize&0x1000) == 0x1000))
-			{
-				/* Limit BulkOut size to about 4k bytes.*/
-				pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-				break;
-			}
-#else
-			if (((ThisBulkSize&0xffff8000) != 0) || ((ThisBulkSize&0x1000) == 0x1000))
-			{
-				// Limit BulkOut size to about 4k bytes.
-				pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-				break;
-			}
-#endif // INF_AMAZON_SE //
-
-			else if (((pAd->BulkOutMaxPacketSize < 512) && ((ThisBulkSize&0xfffff800) != 0) ) /*|| ( (ThisBulkSize != 0)  && (pTxWI->AMPDU == 0))*/)
-			{
-				// For USB 1.1 or peer which didn't support AMPDU, limit the BulkOut size.
-				// For performence in b/g mode, now just check for USB 1.1 and didn't care about the APMDU or not! 2008/06/04.
-				pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-				break;
-			}
-		}
-		// end Iverson
-		else
-		{
-#ifdef INF_AMAZON_SE
-//#ifdef DOT11_N_SUPPORT
-//			if(((ThisBulkSize&0xffff8000) != 0) || ((ThisBulkSize&0x6000) == 0x6000) || ( (ThisBulkSize != 0)  && (pTxWI->AMPDU == 0)))
-//			{
-//				/* AMAZON_SE: BG mode Disable BulkOut Aggregate, N mode BulkOut Aggregaet size 24K */
-//				pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-//               break;
-//			}
-//			else
-//#endif // DOT11_N_SUPPORT //
-//			{
-				if(OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) && (pTxWI->AMPDU == 0))
-				{
-					if (((pAd->BulkOutMaxPacketSize < 512) && ((ThisBulkSize&0xfffff800) != 0)) ||
-						(ThisBulkSize != 0))
-					{
-						/* AMAZON_SE: RT2070  Disable BulkOut Aggregate when WMM for USB issue */
-						pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-						break;
-					}
-				}
-/*
-				else if (((ThisBulkSize&0xffff8000) != 0) || ((ThisBulkSize&0x6000) == 0x6000))
-				{
-					// Limit BulkOut size to about 24k bytes.
-					pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-					break;
-				}
-			}
-*/
-#endif // INF_AMAZON_SE //
-
-			if (((ThisBulkSize&0xffff8000) != 0) || ((ThisBulkSize&0x6000) == 0x6000))
-			{	// Limit BulkOut size to about 24k bytes.
-				pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-				break;
-			}
-
-			else if (((pAd->BulkOutMaxPacketSize < 512) && ((ThisBulkSize&0xfffff800) != 0) ) /*|| ( (ThisBulkSize != 0)  && (pTxWI->AMPDU == 0))*/)
-			{	// For USB 1.1 or peer which didn't support AMPDU, limit the BulkOut size.
-				// For performence in b/g mode, now just check for USB 1.1 and didn't care about the APMDU or not! 2008/06/04.
-				pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-				break;
-			}
-		}
-
-		if (TmpBulkEndPos == pHTTXContext->CurWritePosition)
-		{
-			pHTTXContext->ENextBulkOutPosition = TmpBulkEndPos;
-			break;
-		}
-		//PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-		if (pTxInfo->QSEL != FIFO_EDCA)
-		{
-			printk("%s(): ====> pTxInfo->QueueSel(%d)!= FIFO_EDCA!!!!\n", __FUNCTION__, pTxInfo->QSEL);
-			printk("\tCWPos=%ld, NBPos=%ld, ENBPos=%ld, bCopy=%d!\n", pHTTXContext->CurWritePosition, pHTTXContext->NextBulkOutPosition, pHTTXContext->ENextBulkOutPosition, pHTTXContext->bCopySavePad);
-			hex_dump("Wrong QSel Pkt:", (PUCHAR)&pWirelessPkt[TmpBulkEndPos], (pHTTXContext->CurWritePosition - pHTTXContext->NextBulkOutPosition));
-		}
-		}
-#endif // CONFIG_STA_SUPPORT //
-
-		if (pTxInfo->USBDMATxPktLen <= 8)
-		{
-			BULK_OUT_UNLOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags2);
-			DBGPRINT(RT_DEBUG_ERROR /*RT_DEBUG_TRACE*/,("e2, USBDMATxPktLen==0, Size=%ld, bCSPad=%d, CWPos=%ld, NBPos=%ld, CWRPos=%ld!\n",
-					pHTTXContext->BulkOutSize, pHTTXContext->bCopySavePad, pHTTXContext->CurWritePosition, pHTTXContext->NextBulkOutPosition, pHTTXContext->CurWriteRealPos));
-			{
-				DBGPRINT_RAW(RT_DEBUG_ERROR /*RT_DEBUG_TRACE*/,("%x  %x  %x  %x  %x  %x  %x  %x \n",
-					pHTTXContext->SavedPad[0], pHTTXContext->SavedPad[1], pHTTXContext->SavedPad[2],pHTTXContext->SavedPad[3]
-					,pHTTXContext->SavedPad[4], pHTTXContext->SavedPad[5], pHTTXContext->SavedPad[6],pHTTXContext->SavedPad[7]));
-			}
-			pAd->bForcePrintTX = TRUE;
-			BULK_OUT_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-			pAd->BulkOutPending[BulkOutPipeId] = FALSE;
-			BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-			//DBGPRINT(RT_DEBUG_LOUD,("Out:pTxInfo->USBDMATxPktLen=%d!\n", pTxInfo->USBDMATxPktLen));
-			return;
-		}
-
-			// Increase Total transmit byte counter
-		pAd->RalinkCounters.OneSecTransmittedByteCount +=  pTxWI->MPDUtotalByteCount;
-		pAd->RalinkCounters.TransmittedByteCount +=  pTxWI->MPDUtotalByteCount;
-
-		pLastTxInfo = pTxInfo;
-
-		// Make sure we use EDCA QUEUE.
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		pTxInfo->QSEL = FIFO_EDCA; //PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
-#endif // CONFIG_STA_SUPPORT //
-		ThisBulkSize += (pTxInfo->USBDMATxPktLen+4);
-		TmpBulkEndPos += (pTxInfo->USBDMATxPktLen+4);
-
-		if (TmpBulkEndPos != pHTTXContext->CurWritePosition)
-			pTxInfo->USBDMANextVLD = 1;
-
-		if (pTxInfo->SwUseLastRound == 1)
-		{
-			if (pHTTXContext->CurWritePosition == 8)
-				pTxInfo->USBDMANextVLD = 0;
-			pTxInfo->SwUseLastRound = 0;
-
-			bTxQLastRound = TRUE;
-			pHTTXContext->ENextBulkOutPosition = 8;
-
-	#ifdef RT_BIG_ENDIAN
-			RTMPDescriptorEndianChange((PUCHAR)pTxInfo, TYPE_TXINFO);
-			RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-	#endif // RT_BIG_ENDIAN //
-
-			break;
-		}
-
-#ifdef RT_BIG_ENDIAN
-		RTMPDescriptorEndianChange((PUCHAR)pTxInfo, TYPE_TXINFO);
-		RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-#endif // RT_BIG_ENDIAN //
-
-	}while (TRUE);
-
-	// adjust the pTxInfo->USBDMANextVLD value of last pTxInfo.
-	if (pLastTxInfo)
-	{
-#ifdef RT_BIG_ENDIAN
-		RTMPDescriptorEndianChange((PUCHAR)pLastTxInfo, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-		pLastTxInfo->USBDMANextVLD = 0;
-#ifdef RT_BIG_ENDIAN
-		RTMPDescriptorEndianChange((PUCHAR)pLastTxInfo, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-	}
-
-	/*
-		We need to copy SavedPad when following condition matched!
-			1. Not the last round of the TxQueue and
-			2. any match of following cases:
-				(1). The End Position of this bulk out is reach to the Currenct Write position and
-						the TxInfo and related header already write to the CurWritePosition.
-			   		=>(ENextBulkOutPosition == CurWritePosition) && (CurWriteRealPos > CurWritePosition)
-
-				(2). The EndPosition of the bulk out is not reach to the Current Write Position.
-					=>(ENextBulkOutPosition != CurWritePosition)
-	*/
-	if ((bTxQLastRound == FALSE) &&
-		 (((pHTTXContext->ENextBulkOutPosition == pHTTXContext->CurWritePosition) && (pHTTXContext->CurWriteRealPos > pHTTXContext->CurWritePosition)) ||
-		  (pHTTXContext->ENextBulkOutPosition != pHTTXContext->CurWritePosition))
-		)
-	{
-		NdisMoveMemory(pHTTXContext->SavedPad, &pWirelessPkt[pHTTXContext->ENextBulkOutPosition], 8);
-		pHTTXContext->bCopySavePad = TRUE;
-		if (RTMPEqualMemory(pHTTXContext->SavedPad, allzero,4))
-		{
-			PUCHAR	pBuf = &pHTTXContext->SavedPad[0];
-			DBGPRINT_RAW(RT_DEBUG_ERROR,("WARNING-Zero-3:%02x%02x%02x%02x%02x%02x%02x%02x,CWPos=%ld, CWRPos=%ld, bCW=%d, NBPos=%ld, TBPos=%ld, TBSize=%ld\n",
-				pBuf[0], pBuf[1], pBuf[2],pBuf[3],pBuf[4], pBuf[5], pBuf[6],pBuf[7], pHTTXContext->CurWritePosition, pHTTXContext->CurWriteRealPos,
-				pHTTXContext->bCurWriting, pHTTXContext->NextBulkOutPosition, TmpBulkEndPos, ThisBulkSize));
-
-			pBuf = &pWirelessPkt[pHTTXContext->CurWritePosition];
-			DBGPRINT_RAW(RT_DEBUG_ERROR,("\tCWPos=%02x%02x%02x%02x%02x%02x%02x%02x\n", pBuf[0], pBuf[1], pBuf[2],pBuf[3],pBuf[4], pBuf[5], pBuf[6],pBuf[7]));
-		}
-		//DBGPRINT(RT_DEBUG_LOUD,("ENPos==CWPos=%ld, CWRPos=%ld, bCSPad=%d!\n", pHTTXContext->CurWritePosition, pHTTXContext->CurWriteRealPos, pHTTXContext->bCopySavePad));
-	}
-
-	if (pAd->bForcePrintTX == TRUE)
-		DBGPRINT(RT_DEBUG_TRACE,("BulkOut-A:Size=%ld, CWPos=%ld, NBPos=%ld, ENBPos=%ld, bCopy=%d!\n", ThisBulkSize, pHTTXContext->CurWritePosition, pHTTXContext->NextBulkOutPosition, pHTTXContext->ENextBulkOutPosition, pHTTXContext->bCopySavePad));
-	//DBGPRINT(RT_DEBUG_LOUD,("BulkOut-A:Size=%ld, CWPos=%ld, CWRPos=%ld, NBPos=%ld, ENBPos=%ld, bCopy=%d, bLRound=%d!\n", ThisBulkSize, pHTTXContext->CurWritePosition, pHTTXContext->CurWriteRealPos, pHTTXContext->NextBulkOutPosition, pHTTXContext->ENextBulkOutPosition, pHTTXContext->bCopySavePad, bTxQLastRound));
-
-		// USB DMA engine requires to pad extra 4 bytes. This pad doesn't count into real bulkoutsize.
-	pAppendant = &pWirelessPkt[TmpBulkEndPos];
-	NdisZeroMemory(pAppendant, 8);
-		ThisBulkSize += 4;
-		pHTTXContext->LastOne = TRUE;
-		if ((ThisBulkSize % pAd->BulkOutMaxPacketSize) == 0)
-			ThisBulkSize += 4;
-	pHTTXContext->BulkOutSize = ThisBulkSize;
-
-	pAd->watchDogTxPendingCnt[BulkOutPipeId] = 1;
-	BULK_OUT_UNLOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags2);
-
-	// Init Tx context descriptor
-	RTUSBInitHTTxDesc(pAd, pHTTXContext, BulkOutPipeId, ThisBulkSize, (usb_complete_t)RTUSBBulkOutDataPacketComplete);
-
-	pUrb = pHTTXContext->pUrb;
-	if((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RTUSBBulkOutDataPacket: Submit Tx URB failed %d\n", ret));
-
-		BULK_OUT_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-		pAd->BulkOutPending[BulkOutPipeId] = FALSE;
-		pAd->watchDogTxPendingCnt[BulkOutPipeId] = 0;
-		BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-
-		return;
-	}
-
-	BULK_OUT_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-	pHTTXContext->IRPPending = TRUE;
-	BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-	pAd->BulkOutReq++;
-
-}
-
-
-VOID RTUSBBulkOutDataPacketComplete(purbb_t pUrb, struct pt_regs *pt_regs)
-{
-	PHT_TX_CONTEXT	pHTTXContext;
-	PRTMP_ADAPTER	pAd;
-	POS_COOKIE 		pObj;
-	UCHAR			BulkOutPipeId;
-
-
-	pHTTXContext	= (PHT_TX_CONTEXT)pUrb->context;
-	pAd 			= pHTTXContext->pAd;
-	pObj 			= (POS_COOKIE) pAd->OS_Cookie;
-
-	// Store BulkOut PipeId
-	BulkOutPipeId	= pHTTXContext->BulkOutPipeId;
-	pAd->BulkOutDataOneSecCount++;
-
-	switch (BulkOutPipeId)
-	{
-		case 0:
-				pObj->ac0_dma_done_task.data = (unsigned long)pUrb;
-				tasklet_hi_schedule(&pObj->ac0_dma_done_task);
-				break;
-		case 1:
-				pObj->ac1_dma_done_task.data = (unsigned long)pUrb;
-				tasklet_hi_schedule(&pObj->ac1_dma_done_task);
-				break;
-		case 2:
-				pObj->ac2_dma_done_task.data = (unsigned long)pUrb;
-				tasklet_hi_schedule(&pObj->ac2_dma_done_task);
-				break;
-		case 3:
-				pObj->ac3_dma_done_task.data = (unsigned long)pUrb;
-				tasklet_hi_schedule(&pObj->ac3_dma_done_task);
-				break;
-		case 4:
-				pObj->hcca_dma_done_task.data = (unsigned long)pUrb;
-				tasklet_hi_schedule(&pObj->hcca_dma_done_task);
-				break;
-	}
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note: NULL frame use BulkOutPipeId = 0
-
-	========================================================================
-*/
-VOID	RTUSBBulkOutNullFrame(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	PTX_CONTEXT		pNullContext = &(pAd->NullContext);
-	PURB			pUrb;
-	int				ret = 0;
-	unsigned long	IrqFlags;
-
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[0], IrqFlags);
-	if ((pAd->BulkOutPending[0] == TRUE) || RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NEED_STOP_TX))
-	{
-		RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);
-		return;
-	}
-	pAd->BulkOutPending[0] = TRUE;
-	pAd->watchDogTxPendingCnt[0] = 1;
-	pNullContext->IRPPending = TRUE;
-	RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);
-
-	// Increase Total transmit byte counter
-	pAd->RalinkCounters.TransmittedByteCount +=  pNullContext->BulkOutSize;
-
-
-	// Clear Null frame bulk flag
-	RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NULL);
-
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pNullContext->TransferBuffer, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-
-	// Init Tx context descriptor
-	RTUSBInitTxDesc(pAd, pNullContext, 0, (usb_complete_t)RTUSBBulkOutNullFrameComplete);
-
-	pUrb = pNullContext->pUrb;
-	if((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
-	{
-		RTMP_IRQ_LOCK(&pAd->BulkOutLock[0], IrqFlags);
-		pAd->BulkOutPending[0] = FALSE;
-		pAd->watchDogTxPendingCnt[0] = 0;
-		pNullContext->IRPPending = FALSE;
-		RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);
-
-		DBGPRINT(RT_DEBUG_ERROR, ("RTUSBBulkOutNullFrame: Submit Tx URB failed %d\n", ret));
-		return;
-	}
-
-}
-
-// NULL frame use BulkOutPipeId = 0
-VOID RTUSBBulkOutNullFrameComplete(purbb_t pUrb, struct pt_regs *pt_regs)
-{
-	PRTMP_ADAPTER		pAd;
-	PTX_CONTEXT			pNullContext;
-	NTSTATUS			Status;
-	POS_COOKIE			pObj;
-
-
-	pNullContext	= (PTX_CONTEXT)pUrb->context;
-	pAd 			= pNullContext->pAd;
-	Status 			= pUrb->status;
-
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-	pObj->null_frame_complete_task.data = (unsigned long)pUrb;
-	tasklet_hi_schedule(&pObj->null_frame_complete_task);
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note: MLME use BulkOutPipeId = 0
-
-	========================================================================
-*/
-VOID	RTUSBBulkOutMLMEPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	PTX_CONTEXT		pMLMEContext;
-	PURB			pUrb;
-	int				ret = 0;
-	unsigned long	IrqFlags;
-
-	pMLMEContext = (PTX_CONTEXT)pAd->MgmtRing.Cell[pAd->MgmtRing.TxDmaIdx].AllocVa;
-	pUrb = pMLMEContext->pUrb;
-
-	if ((pAd->MgmtRing.TxSwFreeIdx >= MGMT_RING_SIZE) ||
-		(pMLMEContext->InUse == FALSE) ||
-		(pMLMEContext->bWaitingBulkOut == FALSE))
-	{
-
-
-		// Clear MLME bulk flag
-		RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_MLME);
-
-		return;
-	}
-
-
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[MGMTPIPEIDX], IrqFlags);
-	if ((pAd->BulkOutPending[MGMTPIPEIDX] == TRUE) || RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NEED_STOP_TX))
-	{
-		RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[MGMTPIPEIDX], IrqFlags);
-		return;
-	}
-
-	pAd->BulkOutPending[MGMTPIPEIDX] = TRUE;
-	pAd->watchDogTxPendingCnt[MGMTPIPEIDX] = 1;
-	pMLMEContext->IRPPending = TRUE;
-	pMLMEContext->bWaitingBulkOut = FALSE;
-	RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[MGMTPIPEIDX], IrqFlags);
-
-	// Increase Total transmit byte counter
-	pAd->RalinkCounters.TransmittedByteCount +=  pMLMEContext->BulkOutSize;
-
-	// Clear MLME bulk flag
-	RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_MLME);
-
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pMLMEContext->TransferBuffer, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-
-	// Init Tx context descriptor
-	RTUSBInitTxDesc(pAd, pMLMEContext, MGMTPIPEIDX, (usb_complete_t)RTUSBBulkOutMLMEPacketComplete);
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-	//For mgmt urb buffer, because we use sk_buff, so we need to notify the USB controller do dma mapping.
-	pUrb->transfer_dma	= 0;
-	pUrb->transfer_flags &= (~URB_NO_TRANSFER_DMA_MAP);
-#endif
-
-	pUrb = pMLMEContext->pUrb;
-	if((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RTUSBBulkOutMLMEPacket: Submit MLME URB failed %d\n", ret));
-		RTMP_IRQ_LOCK(&pAd->BulkOutLock[MGMTPIPEIDX], IrqFlags);
-		pAd->BulkOutPending[MGMTPIPEIDX] = FALSE;
-		pAd->watchDogTxPendingCnt[MGMTPIPEIDX] = 0;
-		pMLMEContext->IRPPending = FALSE;
-		pMLMEContext->bWaitingBulkOut = TRUE;
-		RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[MGMTPIPEIDX], IrqFlags);
-
-		return;
-	}
-
-	//DBGPRINT_RAW(RT_DEBUG_INFO, ("<---RTUSBBulkOutMLMEPacket \n"));
-//	printk("<---RTUSBBulkOutMLMEPacket,Cpu=%d!, Dma=%d, SwIdx=%d!\n", pAd->MgmtRing.TxCpuIdx, pAd->MgmtRing.TxDmaIdx, pAd->MgmtRing.TxSwFreeIdx);
-}
-
-
-VOID RTUSBBulkOutMLMEPacketComplete(purbb_t pUrb, struct pt_regs *pt_regs)
-{
-	PTX_CONTEXT			pMLMEContext;
-	PRTMP_ADAPTER		pAd;
-	NTSTATUS			Status;
-	POS_COOKIE 			pObj;
-	int					index;
-
-	//DBGPRINT_RAW(RT_DEBUG_INFO, ("--->RTUSBBulkOutMLMEPacketComplete\n"));
-	pMLMEContext	= (PTX_CONTEXT)pUrb->context;
-	pAd 			= pMLMEContext->pAd;
-	pObj 			= (POS_COOKIE)pAd->OS_Cookie;
-	Status			= pUrb->status;
-	index 			= pMLMEContext->SelfIdx;
-
-	pObj->mgmt_dma_done_task.data = (unsigned long)pUrb;
-	tasklet_hi_schedule(&pObj->mgmt_dma_done_task);
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note: PsPoll use BulkOutPipeId = 0
-
-	========================================================================
-*/
-VOID	RTUSBBulkOutPsPoll(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	PTX_CONTEXT		pPsPollContext = &(pAd->PsPollContext);
-	PURB			pUrb;
-	int				ret = 0;
-	unsigned long	IrqFlags;
-
-	RTMP_IRQ_LOCK(&pAd->BulkOutLock[0], IrqFlags);
-	if ((pAd->BulkOutPending[0] == TRUE) || RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NEED_STOP_TX))
-	{
-		RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);
-		return;
-	}
-	pAd->BulkOutPending[0] = TRUE;
-	pAd->watchDogTxPendingCnt[0] = 1;
-	pPsPollContext->IRPPending = TRUE;
-	RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);
-
-
-	// Clear PS-Poll bulk flag
-	RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_PSPOLL);
-
-#ifdef RT_BIG_ENDIAN
-	RTMPDescriptorEndianChange((PUCHAR)pPsPollContext->TransferBuffer, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-
-	// Init Tx context descriptor
-	RTUSBInitTxDesc(pAd, pPsPollContext, MGMTPIPEIDX, (usb_complete_t)RTUSBBulkOutPsPollComplete);
-
-	pUrb = pPsPollContext->pUrb;
-	if((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
-	{
-		RTMP_IRQ_LOCK(&pAd->BulkOutLock[0], IrqFlags);
-		pAd->BulkOutPending[0] = FALSE;
-		pAd->watchDogTxPendingCnt[0] = 0;
-		pPsPollContext->IRPPending = FALSE;
-		RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);
-
-		DBGPRINT(RT_DEBUG_ERROR, ("RTUSBBulkOutPsPoll: Submit Tx URB failed %d\n", ret));
-		return;
-	}
-
-}
-
-// PS-Poll frame use BulkOutPipeId = 0
-VOID RTUSBBulkOutPsPollComplete(purbb_t pUrb,struct pt_regs *pt_regs)
-{
-	PRTMP_ADAPTER		pAd;
-	PTX_CONTEXT			pPsPollContext;
-	NTSTATUS			Status;
-	POS_COOKIE			pObj;
-
-
-	pPsPollContext= (PTX_CONTEXT)pUrb->context;
-	pAd = pPsPollContext->pAd;
-	Status = pUrb->status;
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-	pObj->pspoll_frame_complete_task.data = (unsigned long)pUrb;
-	tasklet_hi_schedule(&pObj->pspoll_frame_complete_task);
-
-}
-
-VOID DoBulkIn(IN RTMP_ADAPTER *pAd)
-{
-	PRX_CONTEXT		pRxContext;
-	PURB			pUrb;
-	int				ret = 0;
-	unsigned long	IrqFlags;
-
-	RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-	pRxContext = &(pAd->RxContext[pAd->NextRxBulkInIndex]);
-	if ((pAd->PendingRx > 0) || (pRxContext->Readable == TRUE) || (pRxContext->InUse == TRUE))
-	{
-		RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-		return;
-	}
-	pRxContext->InUse = TRUE;
-	pRxContext->IRPPending = TRUE;
-	pAd->PendingRx++;
-	pAd->BulkInReq++;
-	RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-
-	// Init Rx context descriptor
-	NdisZeroMemory(pRxContext->TransferBuffer, pRxContext->BulkInOffset);
-	RTUSBInitRxDesc(pAd, pRxContext);
-
-	pUrb = pRxContext->pUrb;
-	if ((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
-	{	// fail
-
-		RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-		pRxContext->InUse = FALSE;
-		pRxContext->IRPPending = FALSE;
-		pAd->PendingRx--;
-		pAd->BulkInReq--;
-		RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-		DBGPRINT(RT_DEBUG_ERROR, ("RTUSBBulkReceive: Submit Rx URB failed %d\n", ret));
-	}
-	else
-	{	// success
-		ASSERT((pRxContext->InUse == pRxContext->IRPPending));
-		//printk("BIDone, Pend=%d,BIIdx=%d,BIRIdx=%d!\n", pAd->PendingRx, pAd->NextRxBulkInIndex, pAd->NextRxBulkInReadIndex);
-	}
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-	USB_RxPacket initializes a URB and uses the Rx IRP to submit it
-	to USB. It checks if an Rx Descriptor is available and passes the
-	the coresponding buffer to be filled. If no descriptor is available
-	fails the request. When setting the completion routine we pass our
-	Adapter Object as Context.
-
-	Arguments:
-
-	Return Value:
-		TRUE			found matched tuple cache
-		FALSE			no matched found
-
-	Note:
-
-	========================================================================
-*/
-#define fRTMP_ADAPTER_NEED_STOP_RX		\
-		(fRTMP_ADAPTER_NIC_NOT_EXIST | fRTMP_ADAPTER_HALT_IN_PROGRESS |	\
-		 fRTMP_ADAPTER_RADIO_OFF | fRTMP_ADAPTER_RESET_IN_PROGRESS | \
-		 fRTMP_ADAPTER_REMOVE_IN_PROGRESS | fRTMP_ADAPTER_BULKIN_RESET)
-
-#define fRTMP_ADAPTER_NEED_STOP_HANDLE_RX	\
-		(fRTMP_ADAPTER_NIC_NOT_EXIST | fRTMP_ADAPTER_HALT_IN_PROGRESS |	\
-		 fRTMP_ADAPTER_RADIO_OFF | fRTMP_ADAPTER_RESET_IN_PROGRESS | \
-		 fRTMP_ADAPTER_REMOVE_IN_PROGRESS)
-
-VOID	RTUSBBulkReceive(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	PRX_CONTEXT		pRxContext;
-	unsigned long	IrqFlags;
-
-
-	/* sanity check */
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NEED_STOP_HANDLE_RX))
-		return;
-
-	while(1)
-	{
-
-		RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-		pRxContext = &(pAd->RxContext[pAd->NextRxBulkInReadIndex]);
-		if (((pRxContext->InUse == FALSE) && (pRxContext->Readable == TRUE)) &&
-			(pRxContext->bRxHandling == FALSE))
-		{
-			pRxContext->bRxHandling = TRUE;
-			RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-
-			// read RxContext, Since not
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-				STARxDoneInterruptHandle(pAd, TRUE);
-#endif // CONFIG_STA_SUPPORT //
-
-			// Finish to handle this bulkIn buffer.
-			RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-			pRxContext->BulkInOffset = 0;
-			pRxContext->Readable = FALSE;
-			pRxContext->bRxHandling = FALSE;
-			pAd->ReadPosition = 0;
-			pAd->TransferBufferLength = 0;
-			INC_RING_INDEX(pAd->NextRxBulkInReadIndex, RX_RING_SIZE);
-			RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-
-		}
-		else
-		{
-			RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-			break;
-		}
-	}
-
-	if (!(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NEED_STOP_RX)))
-		DoBulkIn(pAd);
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		This routine process Rx Irp and call rx complete function.
-
-	Arguments:
-		DeviceObject	Pointer to the device object for next lower
-						device. DeviceObject passed in here belongs to
-						the next lower driver in the stack because we
-						were invoked via IoCallDriver in USB_RxPacket
-						AND it is not OUR device object
-	  Irp				Ptr to completed IRP
-	  Context			Ptr to our Adapter object (context specified
-						in IoSetCompletionRoutine
-
-	Return Value:
-		Always returns STATUS_MORE_PROCESSING_REQUIRED
-
-	Note:
-		Always returns STATUS_MORE_PROCESSING_REQUIRED
-	========================================================================
-*/
-VOID RTUSBBulkRxComplete(purbb_t pUrb, struct pt_regs *pt_regs)
-{
-	// use a receive tasklet to handle received packets;
-	// or sometimes hardware IRQ will be disabled here, so we can not
-	// use spin_lock_bh()/spin_unlock_bh() after IRQ is disabled. :<
-	PRX_CONTEXT		pRxContext;
-	PRTMP_ADAPTER	pAd;
-	POS_COOKIE 		pObj;
-
-
-	pRxContext	= (PRX_CONTEXT)pUrb->context;
-	pAd 		= pRxContext->pAd;
-	pObj 		= (POS_COOKIE) pAd->OS_Cookie;
-
-	pObj->rx_done_task.data = (unsigned long)pUrb;
-	tasklet_hi_schedule(&pObj->rx_done_task);
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTUSBKickBulkOut(
-	IN	PRTMP_ADAPTER pAd)
-{
-	// BulkIn Reset will reset whole USB PHY. So we need to make sure fRTMP_ADAPTER_BULKIN_RESET not flaged.
-	if (!RTMP_TEST_FLAG(pAd ,fRTMP_ADAPTER_NEED_STOP_TX)
-#ifdef RALINK_ATE
-		&& !(ATE_ON(pAd))
-#endif // RALINK_ATE //
-		)
-	{
-		// 2. PS-Poll frame is next
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_PSPOLL))
-		{
-			RTUSBBulkOutPsPoll(pAd);
-		}
-
-		// 5. Mlme frame is next
-		else if ((RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_MLME)) &&
-				 (pAd->MgmtRing.TxSwFreeIdx < MGMT_RING_SIZE))
-		{
-			RTUSBBulkOutMLMEPacket(pAd, pAd->MgmtRing.TxDmaIdx);
-		}
-
-		// 6. Data frame normal is next
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL))
-		{
-			if (((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) ||
-				(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				))
-			{
-				RTUSBBulkOutDataPacket(pAd, 0, pAd->NextBulkOutIndex[0]);
-			}
-		}
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL_2))
-		{
-			if (((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) ||
-				(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				))
-			{
-				RTUSBBulkOutDataPacket(pAd, 1, pAd->NextBulkOutIndex[1]);
-			}
-		}
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL_3))
-		{
-			if (((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) ||
-				(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				))
-			{
-				RTUSBBulkOutDataPacket(pAd, 2, pAd->NextBulkOutIndex[2]);
-			}
-		}
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL_4))
-		{
-			if (((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) ||
-				(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				))
-			{
-				RTUSBBulkOutDataPacket(pAd, 3, pAd->NextBulkOutIndex[3]);
-			}
-		}
-		//PS packets use HCCA queue when dequeue from PS unicast queue (WiFi WPA2 MA9_DT1 for Marvell B STA)
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NORMAL_5))
-		{
-			if (((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) ||
-				(!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				))
-			{
-			}
-		}
-
-		// 7. Null frame is the last
-		else if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_NULL))
-		{
-			if (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-			{
-				RTUSBBulkOutNullFrame(pAd);
-			}
-		}
-
-		// 8. No data avaliable
-		else
-		{
-
-		}
-	}
-#ifdef RALINK_ATE
-	/* If the mode is in ATE mode. */
-	else if((ATE_ON(pAd)) &&
-		!RTMP_TEST_FLAG(pAd ,fRTMP_ADAPTER_NEED_STOP_TX))// PETER : watch out !
-	{
-		if (RTUSB_TEST_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE))
-		{
-			ATE_RTUSBBulkOutDataPacket(pAd, 0);
-		}
-	}
-#endif // RALINK_ATE //
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-	Call from Reset action after BulkOut failed.
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTUSBCleanUpDataBulkOutQueue(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UCHAR			Idx;
-	PHT_TX_CONTEXT	pTxContext;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("--->CleanUpDataBulkOutQueue\n"));
-
-	for (Idx = 0; Idx < 4; Idx++)
-	{
-		pTxContext = &pAd->TxContext[Idx];
-
-		pTxContext->CurWritePosition = pTxContext->NextBulkOutPosition;
-		pTxContext->LastOne = FALSE;
-		NdisAcquireSpinLock(&pAd->BulkOutLock[Idx]);
-		pAd->BulkOutPending[Idx] = FALSE;
-		NdisReleaseSpinLock(&pAd->BulkOutLock[Idx]);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<---CleanUpDataBulkOutQueue\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTUSBCleanUpMLMEBulkOutQueue(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	DBGPRINT(RT_DEBUG_TRACE, ("--->CleanUpMLMEBulkOutQueue\n"));
-	DBGPRINT(RT_DEBUG_TRACE, ("<---CleanUpMLMEBulkOutQueue\n"));
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTUSBCancelPendingIRPs(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	RTUSBCancelPendingBulkInIRP(pAd);
-	RTUSBCancelPendingBulkOutIRP(pAd);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTUSBCancelPendingBulkInIRP(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	PRX_CONTEXT		pRxContext;
-	UINT			i;
-
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("--->RTUSBCancelPendingBulkInIRP\n"));
-	for ( i = 0; i < (RX_RING_SIZE); i++)
-	{
-		pRxContext = &(pAd->RxContext[i]);
-		if(pRxContext->IRPPending == TRUE)
-		{
-			RTUSB_UNLINK_URB(pRxContext->pUrb);
-			pRxContext->IRPPending = FALSE;
-			pRxContext->InUse = FALSE;
-			//NdisInterlockedDecrement(&pAd->PendingRx);
-			//pAd->PendingRx--;
-		}
-	}
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("<---RTUSBCancelPendingBulkInIRP\n"));
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTUSBCancelPendingBulkOutIRP(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	PHT_TX_CONTEXT		pHTTXContext;
-	PTX_CONTEXT			pMLMEContext;
-	PTX_CONTEXT			pBeaconContext;
-	PTX_CONTEXT			pNullContext;
-	PTX_CONTEXT			pPsPollContext;
-	PTX_CONTEXT			pRTSContext;
-	UINT				i, Idx;
-//	unsigned int 		IrqFlags;
-//	NDIS_SPIN_LOCK		*pLock;
-//	BOOLEAN				*pPending;
-
-
-//	pLock = &pAd->BulkOutLock[MGMTPIPEIDX];
-//	pPending = &pAd->BulkOutPending[MGMTPIPEIDX];
-
-	for (Idx = 0; Idx < 4; Idx++)
-	{
-		pHTTXContext = &(pAd->TxContext[Idx]);
-
-		if (pHTTXContext->IRPPending == TRUE)
-		{
-
-			// Get the USB_CONTEXT and cancel it's IRP; the completion routine will itself
-			// remove it from the HeadPendingSendList and NULL out HeadPendingSendList
-			//	when the last IRP on the list has been	cancelled; that's how we exit this loop
-			//
-
-			RTUSB_UNLINK_URB(pHTTXContext->pUrb);
-
-			// Sleep 200 microseconds to give cancellation time to work
-			RTMPusecDelay(200);
-		}
-
-#ifdef RALINK_ATE
-		pHTTXContext->bCopySavePad = 0;
-		pHTTXContext->CurWritePosition = 0;
-		pHTTXContext->CurWriteRealPos = 0;
-		pHTTXContext->bCurWriting = FALSE;
-		pHTTXContext->NextBulkOutPosition = 0;
-		pHTTXContext->ENextBulkOutPosition = 0;
-#endif // RALINK_ATE //
-		pAd->BulkOutPending[Idx] = FALSE;
-	}
-
-	//RTMP_IRQ_LOCK(pLock, IrqFlags);
-	for (i = 0; i < MGMT_RING_SIZE; i++)
-	{
-		pMLMEContext = (PTX_CONTEXT)pAd->MgmtRing.Cell[i].AllocVa;
-		if(pMLMEContext && (pMLMEContext->IRPPending == TRUE))
-		{
-
-			// Get the USB_CONTEXT and cancel it's IRP; the completion routine will itself
-			// remove it from the HeadPendingSendList and NULL out HeadPendingSendList
-			//	when the last IRP on the list has been	cancelled; that's how we exit this loop
-			//
-
-			RTUSB_UNLINK_URB(pMLMEContext->pUrb);
-			pMLMEContext->IRPPending = FALSE;
-
-			// Sleep 200 microsecs to give cancellation time to work
-			RTMPusecDelay(200);
-		}
-	}
-	pAd->BulkOutPending[MGMTPIPEIDX] = FALSE;
-	//RTMP_IRQ_UNLOCK(pLock, IrqFlags);
-
-
-	for (i = 0; i < BEACON_RING_SIZE; i++)
-	{
-		pBeaconContext = &(pAd->BeaconContext[i]);
-
-		if(pBeaconContext->IRPPending == TRUE)
-		{
-
-			// Get the USB_CONTEXT and cancel it's IRP; the completion routine will itself
-			// remove it from the HeadPendingSendList and NULL out HeadPendingSendList
-			//	when the last IRP on the list has been	cancelled; that's how we exit this loop
-			//
-
-			RTUSB_UNLINK_URB(pBeaconContext->pUrb);
-
-			// Sleep 200 microsecs to give cancellation time to work
-			RTMPusecDelay(200);
-		}
-	}
-
-	pNullContext = &(pAd->NullContext);
-	if (pNullContext->IRPPending == TRUE)
-		RTUSB_UNLINK_URB(pNullContext->pUrb);
-
-	pRTSContext = &(pAd->RTSContext);
-	if (pRTSContext->IRPPending == TRUE)
-		RTUSB_UNLINK_URB(pRTSContext->pUrb);
-
-	pPsPollContext = &(pAd->PsPollContext);
-	if (pPsPollContext->IRPPending == TRUE)
-		RTUSB_UNLINK_URB(pPsPollContext->pUrb);
-
-	for (Idx = 0; Idx < 4; Idx++)
-	{
-		NdisAcquireSpinLock(&pAd->BulkOutLock[Idx]);
-		pAd->BulkOutPending[Idx] = FALSE;
-		NdisReleaseSpinLock(&pAd->BulkOutLock[Idx]);
-	}
-}
-
+#include "../../rt2870/common/rtusb_bulk.c"
diff --git a/drivers/staging/rt3070/common/rtusb_data.c b/drivers/staging/rt3070/common/rtusb_data.c
index 521309a..d05deb8 100644
--- a/drivers/staging/rt3070/common/rtusb_data.c
+++ b/drivers/staging/rt3070/common/rtusb_data.c
@@ -1,218 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtusb_data.c
-
-	Abstract:
-	Ralink USB driver Tx/Rx functions.
-
-	Revision History:
-	Who         When          What
-	--------    ----------    ----------------------------------------------
-	Jan            03-25-2006    created
-
-*/
-#include	"../rt_config.h"
-
-extern  UCHAR Phy11BGNextRateUpward[]; // defined in mlme.c
-extern UCHAR	EpToQueue[];
-
-
-VOID REPORT_AMSDU_FRAMES_TO_LLC(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize)
-{
-	PNDIS_PACKET	pPacket;
-	UINT			nMSDU;
-	struct			sk_buff *pSkb;
-
-	nMSDU = 0;
-	/* allocate a rx packet */
-	pSkb = dev_alloc_skb(RX_BUFFER_AGGRESIZE);
-	pPacket = (PNDIS_PACKET)OSPKT_TO_RTPKT(pSkb);
-	if (pSkb)
-	{
-
-		/* convert 802.11 to 802.3 packet */
-		pSkb->dev = get_netdev_from_bssid(pAd, BSS0);
-		RTMP_SET_PACKET_SOURCE(pPacket, PKTSRC_NDIS);
-		deaggregate_AMSDU_announce(pAd, pPacket, pData, DataSize);
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("Can't allocate skb\n"));
-	}
-}
-
-NDIS_STATUS	RTUSBFreeDescriptorRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BulkOutPipeId,
-	IN	UINT32			NumberRequired)
-{
-//	UCHAR			FreeNumber = 0;
-//	UINT			Index;
-	NDIS_STATUS		Status = NDIS_STATUS_FAILURE;
-	unsigned long   IrqFlags;
-	HT_TX_CONTEXT	*pHTTXContext;
-
-
-	pHTTXContext = &pAd->TxContext[BulkOutPipeId];
-	RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-	if ((pHTTXContext->CurWritePosition < pHTTXContext->NextBulkOutPosition) && ((pHTTXContext->CurWritePosition + NumberRequired + LOCAL_TXBUF_SIZE) > pHTTXContext->NextBulkOutPosition))
-	{
-
-		RTUSB_SET_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << BulkOutPipeId));
-	}
-	else if ((pHTTXContext->CurWritePosition == 8) && (pHTTXContext->NextBulkOutPosition < (NumberRequired + LOCAL_TXBUF_SIZE)))
-	{
-		RTUSB_SET_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << BulkOutPipeId));
-	}
-	else if (pHTTXContext->bCurWriting == TRUE)
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("RTUSBFreeD c3 --> QueIdx=%d, CWPos=%ld, NBOutPos=%ld!\n", BulkOutPipeId, pHTTXContext->CurWritePosition, pHTTXContext->NextBulkOutPosition));
-		RTUSB_SET_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << BulkOutPipeId));
-	}
-	else
-	{
-		Status = NDIS_STATUS_SUCCESS;
-	}
-	RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-
-
-	return (Status);
-}
-
-
-NDIS_STATUS RTUSBFreeDescriptorRelease(
-	IN RTMP_ADAPTER *pAd,
-	IN UCHAR		BulkOutPipeId)
-{
-	unsigned long   IrqFlags;
-	HT_TX_CONTEXT	*pHTTXContext;
-
-	pHTTXContext = &pAd->TxContext[BulkOutPipeId];
-	RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-	pHTTXContext->bCurWriting = FALSE;
-	RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-
-	return (NDIS_STATUS_SUCCESS);
-}
-
-
-BOOLEAN	RTUSBNeedQueueBackForAgg(
-	IN RTMP_ADAPTER *pAd,
-	IN UCHAR		BulkOutPipeId)
-{
-	unsigned long   IrqFlags;
-	HT_TX_CONTEXT	*pHTTXContext;
-	BOOLEAN			needQueBack = FALSE;
-
-	pHTTXContext = &pAd->TxContext[BulkOutPipeId];
-
-	RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-	if ((pHTTXContext->IRPPending == TRUE)  /*&& (pAd->TxSwQueue[BulkOutPipeId].Number == 0) */)
-	{
-		if ((pHTTXContext->CurWritePosition < pHTTXContext->ENextBulkOutPosition) &&
-			(((pHTTXContext->ENextBulkOutPosition+MAX_AGGREGATION_SIZE) < MAX_TXBULK_LIMIT) || (pHTTXContext->CurWritePosition > MAX_AGGREGATION_SIZE)))
-		{
-			needQueBack = TRUE;
-		}
-		else if ((pHTTXContext->CurWritePosition > pHTTXContext->ENextBulkOutPosition) &&
-				 ((pHTTXContext->ENextBulkOutPosition + MAX_AGGREGATION_SIZE) < pHTTXContext->CurWritePosition))
-		{
-			needQueBack = TRUE;
-		}
-	}
-	RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[BulkOutPipeId], IrqFlags);
-
-	return needQueBack;
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTUSBRejectPendingPackets(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UCHAR			Index;
-	PQUEUE_ENTRY	pEntry;
-	PNDIS_PACKET	pPacket;
-	PQUEUE_HEADER	pQueue;
-
-
-	for (Index = 0; Index < 4; Index++)
-	{
-		NdisAcquireSpinLock(&pAd->TxSwQueueLock[Index]);
-		while (pAd->TxSwQueue[Index].Head != NULL)
-		{
-			pQueue = (PQUEUE_HEADER) &(pAd->TxSwQueue[Index]);
-			pEntry = RemoveHeadQueue(pQueue);
-			pPacket = QUEUE_ENTRY_TO_PACKET(pEntry);
-			RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-		}
-		NdisReleaseSpinLock(&pAd->TxSwQueueLock[Index]);
-
-	}
-
-}
-
-VOID RTMPWriteTxInfo(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXINFO_STRUC 	pTxInfo,
-	IN	  USHORT		USBDMApktLen,
-	IN	  BOOLEAN		bWiv,
-	IN	  UCHAR			QueueSel,
-	IN	  UCHAR			NextValid,
-	IN	  UCHAR			TxBurst)
-{
-	pTxInfo->USBDMATxPktLen = USBDMApktLen;
-	pTxInfo->QSEL = QueueSel;
-	if (QueueSel != FIFO_EDCA)
-		DBGPRINT(RT_DEBUG_TRACE, ("====> QueueSel != FIFO_EDCA<============\n"));
-	pTxInfo->USBDMANextVLD = FALSE; //NextValid;  // Need to check with Jan about this.
-	pTxInfo->USBDMATxburst = TxBurst;
-	pTxInfo->WIV = bWiv;
-	pTxInfo->SwUseLastRound = 0;
-	pTxInfo->rsv = 0;
-	pTxInfo->rsv2 = 0;
-}
-
+#include "../../rt2870/common/rtusb_data.c"
diff --git a/drivers/staging/rt3070/common/rtusb_io.c b/drivers/staging/rt3070/common/rtusb_io.c
index a6a52e3..20a0b56 100644
--- a/drivers/staging/rt3070/common/rtusb_io.c
+++ b/drivers/staging/rt3070/common/rtusb_io.c
@@ -1,1908 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
- 	Module Name:
-	rtusb_io.c
-
-	Abstract:
-
-	Revision History:
-	Who			When	    What
-	--------	----------  ----------------------------------------------
-	Name		Date	    Modification logs
-	Paul Lin    06-25-2004  created
-*/
-
-#include	"../rt_config.h"
-
-
-/*
-	========================================================================
-
-	Routine Description: NIC initialization complete
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-
-NTSTATUS	RTUSBFirmwareRun(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	NTSTATUS	Status;
-
-	Status = RTUSB_VendorRequest(
-		pAd,
-		USBD_TRANSFER_DIRECTION_OUT,
-		DEVICE_VENDOR_REQUEST_OUT,
-		0x01,
-		0x8,
-		0,
-		NULL,
-		0);
-
-	return Status;
-}
-
-
-
-/*
-	========================================================================
-
-	Routine Description: Write Firmware to NIC.
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS RTUSBFirmwareWrite(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR		pFwImage,
-	IN ULONG		FwLen)
-{
-	UINT32		MacReg;
-	NTSTATUS 	Status;
-//	ULONG 		i;
-	USHORT		writeLen;
-
-	Status = RTUSBReadMACRegister(pAd, MAC_CSR0, &MacReg);
-
-
-	writeLen = FwLen;
-	RTUSBMultiWrite(pAd, FIRMWARE_IMAGE_BASE, pFwImage, writeLen);
-
-	Status = RTUSBWriteMACRegister(pAd, 0x7014, 0xffffffff);
-	Status = RTUSBWriteMACRegister(pAd, 0x701c, 0xffffffff);
-	Status = RTUSBFirmwareRun(pAd);
-
-	RTMPusecDelay(10000);
-	RTUSBWriteMACRegister(pAd,H2M_MAILBOX_CSR,0);
-	AsicSendCommandToMcu(pAd, 0x72, 0x00, 0x00, 0x00);//reset rf by MCU supported by new firmware
-
-	return Status;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description: Get current firmware operation mode (Return Value)
-
-	Arguments:
-
-	Return Value:
-		0 or 1 = Downloaded by host driver
-		others = Driver doesn't download firmware
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSBFirmwareOpmode(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUINT32			pValue)
-{
-	NTSTATUS	Status;
-
-	Status = RTUSB_VendorRequest(
-		pAd,
-		(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
-		DEVICE_VENDOR_REQUEST_IN,
-		0x1,
-		0x11,
-		0,
-		pValue,
-		4);
-	return Status;
-}
-NTSTATUS	RTUSBVenderReset(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	NTSTATUS	Status;
-	DBGPRINT_RAW(RT_DEBUG_ERROR, ("-->RTUSBVenderReset\n"));
-	Status = RTUSB_VendorRequest(
-		pAd,
-		USBD_TRANSFER_DIRECTION_OUT,
-		DEVICE_VENDOR_REQUEST_OUT,
-		0x01,
-		0x1,
-		0,
-		NULL,
-		0);
-
-	DBGPRINT_RAW(RT_DEBUG_ERROR, ("<--RTUSBVenderReset\n"));
-	return Status;
-}
-/*
-	========================================================================
-
-	Routine Description: Read various length data from RT2573
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSBMultiRead(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	OUT	PUCHAR			pData,
-	IN	USHORT			length)
-{
-	NTSTATUS	Status;
-
-	Status = RTUSB_VendorRequest(
-		pAd,
-		(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
-		DEVICE_VENDOR_REQUEST_IN,
-		0x7,
-		0,
-		Offset,
-		pData,
-		length);
-
-	return Status;
-}
-
-/*
-	========================================================================
-
-	Routine Description: Write various length data to RT2573
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSBMultiWrite_OneByte(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	PUCHAR			pData)
-{
-	NTSTATUS	Status;
-
-	// TODO: In 2870, use this funciton carefully cause it's not stable.
-	Status = RTUSB_VendorRequest(
-		pAd,
-		USBD_TRANSFER_DIRECTION_OUT,
-		DEVICE_VENDOR_REQUEST_OUT,
-		0x6,
-		0,
-		Offset,
-		pData,
-		1);
-
-	return Status;
-}
-
-NTSTATUS	RTUSBMultiWrite(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	PUCHAR			pData,
-	IN	USHORT			length)
-{
-	NTSTATUS	Status;
-
-
-        USHORT          index = 0,Value;
-        PUCHAR          pSrc = pData;
-        USHORT          resude = 0;
-
-        resude = length % 2;
-		length  += resude;
-		do
-		{
-			Value =(USHORT)( *pSrc  | (*(pSrc + 1) << 8));
-		Status = RTUSBSingleWrite(pAd,Offset + index,Value);
-            index +=2;
-            length -= 2;
-            pSrc = pSrc + 2;
-        }while(length > 0);
-
-	return Status;
-}
-
-
-NTSTATUS RTUSBSingleWrite(
-	IN 	RTMP_ADAPTER 	*pAd,
-	IN	USHORT			Offset,
-	IN	USHORT			Value)
-{
-	NTSTATUS	Status;
-
-	Status = RTUSB_VendorRequest(
-		pAd,
-		USBD_TRANSFER_DIRECTION_OUT,
-		DEVICE_VENDOR_REQUEST_OUT,
-		0x2,
-		Value,
-		Offset,
-		NULL,
-		0);
-
-	return Status;
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description: Read 32-bit MAC register
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSBReadMACRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	OUT	PUINT32			pValue)
-{
-	NTSTATUS	Status;
-	UINT32		localVal;
-
-	Status = RTUSB_VendorRequest(
-		pAd,
-		(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
-		DEVICE_VENDOR_REQUEST_IN,
-		0x7,
-		0,
-		Offset,
-		&localVal,
-		4);
-
-	*pValue = le2cpu32(localVal);
-
-
-	if (Status < 0)
-		*pValue = 0xffffffff;
-
-	return Status;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description: Write 32-bit MAC register
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSBWriteMACRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	UINT32			Value)
-{
-	NTSTATUS	Status;
-	UINT32		localVal;
-
-	localVal = Value;
-
-	Status = RTUSBSingleWrite(pAd, Offset, (USHORT)(localVal & 0xffff));
-	Status = RTUSBSingleWrite(pAd, Offset + 2, (USHORT)((localVal & 0xffff0000) >> 16));
-
-	return Status;
-}
-
-
-
-#if 1
-/*
-	========================================================================
-
-	Routine Description: Read 8-bit BBP register
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSBReadBBPRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Id,
-	IN	PUCHAR			pValue)
-{
-	BBP_CSR_CFG_STRUC	BbpCsr;
-	UINT			i = 0;
-	NTSTATUS		status;
-
-	// Verify the busy condition
-	do
-	{
-		status = RTUSBReadMACRegister(pAd, BBP_CSR_CFG, &BbpCsr.word);
-		if(status >= 0)
-		{
-		if (!(BbpCsr.field.Busy == BUSY))
-			break;
-		}
-		printk("RTUSBReadBBPRegister(BBP_CSR_CFG_1):retry count=%d!\n", i);
-		i++;
-	}
-	while ((i < RETRY_LIMIT) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));
-
-	if ((i == RETRY_LIMIT) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-	{
-		//
-		// Read failed then Return Default value.
-		//
-		*pValue = pAd->BbpWriteLatch[Id];
-
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("Retry count exhausted or device removed!!!\n"));
-		return STATUS_UNSUCCESSFUL;
-	}
-
-	// Prepare for write material
-	BbpCsr.word 				= 0;
-	BbpCsr.field.fRead			= 1;
-	BbpCsr.field.Busy			= 1;
-	BbpCsr.field.RegNum 		= Id;
-	RTUSBWriteMACRegister(pAd, BBP_CSR_CFG, BbpCsr.word);
-
-	i = 0;
-	// Verify the busy condition
-	do
-	{
-		status = RTUSBReadMACRegister(pAd, BBP_CSR_CFG, &BbpCsr.word);
-		if (status >= 0)
-		{
-		if (!(BbpCsr.field.Busy == BUSY))
-		{
-			*pValue = (UCHAR)BbpCsr.field.Value;
-			break;
-		}
-		}
-		printk("RTUSBReadBBPRegister(BBP_CSR_CFG_2):retry count=%d!\n", i);
-		i++;
-	}
-	while ((i < RETRY_LIMIT) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));
-
-	if ((i == RETRY_LIMIT) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-	{
-		//
-		// Read failed then Return Default value.
-		//
-		*pValue = pAd->BbpWriteLatch[Id];
-
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("Retry count exhausted or device removed!!!\n"));
-		return STATUS_UNSUCCESSFUL;
-	}
-
-	return STATUS_SUCCESS;
-}
-#else
-/*
-	========================================================================
-
-	Routine Description: Read 8-bit BBP register via firmware
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSBReadBBPRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Id,
-	IN	PUCHAR			pValue)
-{
-	BBP_CSR_CFG_STRUC	BbpCsr;
-	int					i, k;
-	for (i=0; i<MAX_BUSY_COUNT; i++)
-	{
-		RTUSBReadMACRegister(pAd, H2M_BBP_AGENT, &BbpCsr.word);
-		if (BbpCsr.field.Busy == BUSY)
-		{
-			continue;
-		}
-		BbpCsr.word = 0;
-		BbpCsr.field.fRead = 1;
-		BbpCsr.field.BBP_RW_MODE = 1;
-		BbpCsr.field.Busy = 1;
-		BbpCsr.field.RegNum = Id;
-		RTUSBWriteMACRegister(pAd, H2M_BBP_AGENT, BbpCsr.word);
-		AsicSendCommandToMcu(pAd, 0x80, 0xff, 0x0, 0x0);
-		for (k=0; k<MAX_BUSY_COUNT; k++)
-		{
-			RTUSBReadMACRegister(pAd, H2M_BBP_AGENT, &BbpCsr.word);
-			if (BbpCsr.field.Busy == IDLE)
-				break;
-		}
-		if ((BbpCsr.field.Busy == IDLE) &&
-			(BbpCsr.field.RegNum == Id))
-		{
-			*pValue = (UCHAR)BbpCsr.field.Value;
-			break;
-		}
-	}
-	if (BbpCsr.field.Busy == BUSY)
-	{
-		DBGPRINT_ERR(("BBP read R%d=0x%x fail\n", Id, BbpCsr.word));
-		*pValue = pAd->BbpWriteLatch[Id];
-		return STATUS_UNSUCCESSFUL;
-	}
-	return STATUS_SUCCESS;
-}
-#endif
-
-#if 1
-/*
-	========================================================================
-
-	Routine Description: Write 8-bit BBP register
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSBWriteBBPRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Id,
-	IN	UCHAR			Value)
-{
-	BBP_CSR_CFG_STRUC	BbpCsr;
-	UINT			i = 0;
-	NTSTATUS		status;
-	// Verify the busy condition
-	do
-	{
-		status = RTUSBReadMACRegister(pAd, BBP_CSR_CFG, &BbpCsr.word);
-		if (status >= 0)
-		{
-		if (!(BbpCsr.field.Busy == BUSY))
-			break;
-		}
-		printk("RTUSBWriteBBPRegister(BBP_CSR_CFG):retry count=%d!\n", i);
-		i++;
-	}
-	while ((i < RETRY_LIMIT) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));
-
-	if ((i == RETRY_LIMIT) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-	{
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("Retry count exhausted or device removed!!!\n"));
-		return STATUS_UNSUCCESSFUL;
-	}
-
-	// Prepare for write material
-	BbpCsr.word 				= 0;
-	BbpCsr.field.fRead			= 0;
-	BbpCsr.field.Value			= Value;
-	BbpCsr.field.Busy			= 1;
-	BbpCsr.field.RegNum 		= Id;
-	RTUSBWriteMACRegister(pAd, BBP_CSR_CFG, BbpCsr.word);
-
-	pAd->BbpWriteLatch[Id] = Value;
-
-	return STATUS_SUCCESS;
-}
-#else
-/*
-	========================================================================
-
-	Routine Description: Write 8-bit BBP register via firmware
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-
-NTSTATUS	RTUSBWriteBBPRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Id,
-	IN	UCHAR			Value)
-
-{
-	BBP_CSR_CFG_STRUC	BbpCsr;
-	int					BusyCnt;
-	for (BusyCnt=0; BusyCnt<MAX_BUSY_COUNT; BusyCnt++)
-	{
-		RTMP_IO_READ32(pAd, H2M_BBP_AGENT, &BbpCsr.word);
-		if (BbpCsr.field.Busy == BUSY)
-			continue;
-		BbpCsr.word = 0;
-		BbpCsr.field.fRead = 0;
-		BbpCsr.field.BBP_RW_MODE = 1;
-		BbpCsr.field.Busy = 1;
-		BbpCsr.field.Value = Value;
-		BbpCsr.field.RegNum = Id;
-		RTMP_IO_WRITE32(pAd, H2M_BBP_AGENT, BbpCsr.word);
-		AsicSendCommandToMcu(pAd, 0x80, 0xff, 0x0, 0x0);
-		pAd->BbpWriteLatch[Id] = Value;
-		break;
-	}
-	if (BusyCnt == MAX_BUSY_COUNT)
-	{
-		DBGPRINT_ERR(("BBP write R%d=0x%x fail\n", Id, BbpCsr.word));
-		return STATUS_UNSUCCESSFUL;
-	}
-	return STATUS_SUCCESS;
-}
-#endif
-/*
-	========================================================================
-
-	Routine Description: Write RF register through MAC
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSBWriteRFRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UINT32			Value)
-{
-	PHY_CSR4_STRUC	PhyCsr4;
-	UINT			i = 0;
-	NTSTATUS		status;
-
-	NdisZeroMemory(&PhyCsr4, sizeof(PHY_CSR4_STRUC));
-	do
-	{
-		status = RTUSBReadMACRegister(pAd, RF_CSR_CFG0, &PhyCsr4.word);
-		if (status >= 0)
-		{
-		if (!(PhyCsr4.field.Busy))
-			break;
-		}
-		printk("RTUSBWriteRFRegister(RF_CSR_CFG0):retry count=%d!\n", i);
-		i++;
-	}
-	while ((i < RETRY_LIMIT) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));
-
-	if ((i == RETRY_LIMIT) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-	{
-		DBGPRINT_RAW(RT_DEBUG_ERROR, ("Retry count exhausted or device removed!!!\n"));
-		return STATUS_UNSUCCESSFUL;
-	}
-
-	RTUSBWriteMACRegister(pAd, RF_CSR_CFG0, Value);
-
-	return STATUS_SUCCESS;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSBReadEEPROM(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	OUT	PUCHAR			pData,
-	IN	USHORT			length)
-{
-	NTSTATUS	Status = STATUS_SUCCESS;
-
-#ifdef RT30xx
-	if(pAd->bUseEfuse)
-	{
-		Status =eFuseRead(pAd, Offset, pData, length);
-	}
-	else
-#endif // RT30xx //
-	{
-	Status = RTUSB_VendorRequest(
-		pAd,
-		(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
-		DEVICE_VENDOR_REQUEST_IN,
-		0x9,
-		0,
-		Offset,
-		pData,
-		length);
-	}
-
-	return Status;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSBWriteEEPROM(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	PUCHAR			pData,
-	IN	USHORT			length)
-{
-	NTSTATUS	Status = STATUS_SUCCESS;
-
-#ifdef RT30xx
-	if(pAd->bUseEfuse)
-	{
-		Status = eFuseWrite(pAd, Offset, pData, length);
-	}
-	else
-#endif // RT30xx //
-	{
-	Status = RTUSB_VendorRequest(
-		pAd,
-		USBD_TRANSFER_DIRECTION_OUT,
-		DEVICE_VENDOR_REQUEST_OUT,
-		0x8,
-		0,
-		Offset,
-		pData,
-		length);
-	}
-
-	return Status;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-VOID RTUSBPutToSleep(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	UINT32		value;
-
-	// Timeout 0x40 x 50us
-	value = (SLEEPCID<<16)+(OWNERMCU<<24)+ (0x40<<8)+1;
-	RTUSBWriteMACRegister(pAd, 0x7010, value);
-	RTUSBWriteMACRegister(pAd, 0x404, 0x30);
-	//RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS);
-	DBGPRINT_RAW(RT_DEBUG_ERROR, ("Sleep Mailbox testvalue %x\n", value));
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS RTUSBWakeUp(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	NTSTATUS	Status;
-
-	Status = RTUSB_VendorRequest(
-		pAd,
-		USBD_TRANSFER_DIRECTION_OUT,
-		DEVICE_VENDOR_REQUEST_OUT,
-		0x01,
-		0x09,
-		0,
-		NULL,
-		0);
-
-	return Status;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTUSBInitializeCmdQ(
-	IN	PCmdQ	cmdq)
-{
-	cmdq->head = NULL;
-	cmdq->tail = NULL;
-	cmdq->size = 0;
-	cmdq->CmdQState = RT2870_THREAD_INITED;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS	RTUSBEnqueueCmdFromNdis(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	NDIS_OID		Oid,
-	IN	BOOLEAN			SetInformation,
-	IN	PVOID			pInformationBuffer,
-	IN	UINT32			InformationBufferLength)
-{
-	NDIS_STATUS	status;
-	PCmdQElmt	cmdqelmt = NULL;
-	POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-
-	if (pObj->RTUSBCmdThr_pid < 0)
-		return (NDIS_STATUS_RESOURCES);
-
-	status = RTMPAllocateMemory((PVOID *)&cmdqelmt, sizeof(CmdQElmt));
-	if ((status != NDIS_STATUS_SUCCESS) || (cmdqelmt == NULL))
-		return (NDIS_STATUS_RESOURCES);
-
-		cmdqelmt->buffer = NULL;
-		if (pInformationBuffer != NULL)
-		{
-			status = RTMPAllocateMemory((PVOID *)&cmdqelmt->buffer, InformationBufferLength);
-			if ((status != NDIS_STATUS_SUCCESS) || (cmdqelmt->buffer == NULL))
-			{
-				kfree(cmdqelmt);
-				return (NDIS_STATUS_RESOURCES);
-			}
-			else
-			{
-				NdisMoveMemory(cmdqelmt->buffer, pInformationBuffer, InformationBufferLength);
-				cmdqelmt->bufferlength = InformationBufferLength;
-			}
-		}
-		else
-			cmdqelmt->bufferlength = 0;
-
-	cmdqelmt->command = Oid;
-	cmdqelmt->CmdFromNdis = TRUE;
-	if (SetInformation == TRUE)
-		cmdqelmt->SetOperation = TRUE;
-	else
-		cmdqelmt->SetOperation = FALSE;
-
-	NdisAcquireSpinLock(&pAd->CmdQLock);
-	if (pAd->CmdQ.CmdQState & RT2870_THREAD_CAN_DO_INSERT)
-	{
-		EnqueueCmd((&pAd->CmdQ), cmdqelmt);
-		status = NDIS_STATUS_SUCCESS;
-	}
-	else
-	{
-		status = NDIS_STATUS_FAILURE;
-	}
-	NdisReleaseSpinLock(&pAd->CmdQLock);
-
-	if (status == NDIS_STATUS_FAILURE)
-	{
-		if (cmdqelmt->buffer)
-			NdisFreeMemory(cmdqelmt->buffer, cmdqelmt->bufferlength, 0);
-		NdisFreeMemory(cmdqelmt, sizeof(CmdQElmt), 0);
-	}
-	else
-	RTUSBCMDUp(pAd);
-
-
-    return(NDIS_STATUS_SUCCESS);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS RTUSBEnqueueInternalCmd(
-	IN PRTMP_ADAPTER	pAd,
-	IN NDIS_OID			Oid,
-	IN PVOID			pInformationBuffer,
-	IN UINT32			InformationBufferLength)
-{
-	NDIS_STATUS	status;
-	PCmdQElmt	cmdqelmt = NULL;
-
-
-	status = RTMPAllocateMemory((PVOID *)&cmdqelmt, sizeof(CmdQElmt));
-	if ((status != NDIS_STATUS_SUCCESS) || (cmdqelmt == NULL))
-		return (NDIS_STATUS_RESOURCES);
-	NdisZeroMemory(cmdqelmt, sizeof(CmdQElmt));
-
-	if(InformationBufferLength > 0)
-	{
-		status = RTMPAllocateMemory((PVOID *)&cmdqelmt->buffer, InformationBufferLength);
-		if ((status != NDIS_STATUS_SUCCESS) || (cmdqelmt->buffer == NULL))
-		{
-			NdisFreeMemory(cmdqelmt, sizeof(CmdQElmt), 0);
-			return (NDIS_STATUS_RESOURCES);
-		}
-		else
-		{
-			NdisMoveMemory(cmdqelmt->buffer, pInformationBuffer, InformationBufferLength);
-			cmdqelmt->bufferlength = InformationBufferLength;
-		}
-	}
-	else
-	{
-		cmdqelmt->buffer = NULL;
-		cmdqelmt->bufferlength = 0;
-	}
-
-	cmdqelmt->command = Oid;
-	cmdqelmt->CmdFromNdis = FALSE;
-
-	if (cmdqelmt != NULL)
-	{
-		NdisAcquireSpinLock(&pAd->CmdQLock);
-		if (pAd->CmdQ.CmdQState & RT2870_THREAD_CAN_DO_INSERT)
-		{
-			EnqueueCmd((&pAd->CmdQ), cmdqelmt);
-			status = NDIS_STATUS_SUCCESS;
-		}
-		else
-		{
-			status = NDIS_STATUS_FAILURE;
-		}
-		NdisReleaseSpinLock(&pAd->CmdQLock);
-
-		if (status == NDIS_STATUS_FAILURE)
-		{
-			if (cmdqelmt->buffer)
-				NdisFreeMemory(cmdqelmt->buffer, cmdqelmt->bufferlength, 0);
-			NdisFreeMemory(cmdqelmt, sizeof(CmdQElmt), 0);
-		}
-		else
-		RTUSBCMDUp(pAd);
-	}
-	return(NDIS_STATUS_SUCCESS);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	IRQL =
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTUSBDequeueCmd(
-	IN	PCmdQ		cmdq,
-	OUT	PCmdQElmt	*pcmdqelmt)
-{
-	*pcmdqelmt = cmdq->head;
-
-	if (*pcmdqelmt != NULL)
-	{
-		cmdq->head = cmdq->head->next;
-		cmdq->size--;
-		if (cmdq->size == 0)
-			cmdq->tail = NULL;
-	}
-}
-
-/*
-    ========================================================================
-	  usb_control_msg - Builds a control urb, sends it off and waits for completion
-	  @dev: pointer to the usb device to send the message to
-	  @pipe: endpoint "pipe" to send the message to
-	  @request: USB message request value
-	  @requesttype: USB message request type value
-	  @value: USB message value
-	  @index: USB message index value
-	  @data: pointer to the data to send
-	  @size: length in bytes of the data to send
-	  @timeout: time in jiffies to wait for the message to complete before
-			  timing out (if 0 the wait is forever)
-	  Context: !in_interrupt ()
-
-	  This function sends a simple control message to a specified endpoint
-	  and waits for the message to complete, or timeout.
-	  If successful, it returns the number of bytes transferred, otherwise a negative error number.
-
-	 Don't use this function from within an interrupt context, like a
-	  bottom half handler.	If you need an asynchronous message, or need to send
-	  a message from within interrupt context, use usb_submit_urb()
-	  If a thread in your driver uses this call, make sure your disconnect()
-	  method can wait for it to complete.  Since you don't have a handle on
-	  the URB used, you can't cancel the request.
-
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS    RTUSB_VendorRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UINT32			TransferFlags,
-	IN	UCHAR			RequestType,
-	IN	UCHAR			Request,
-	IN	USHORT			Value,
-	IN	USHORT			Index,
-	IN	PVOID			TransferBuffer,
-	IN	UINT32			TransferBufferLength)
-{
-	int				ret;
-	POS_COOKIE		pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("device disconnected\n"));
-		return -1;
-	}
-	else if (in_interrupt())
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("in_interrupt, RTUSB_VendorRequest Request%02x Value%04x Offset%04x\n",Request,Value,Index));
-
-		return -1;
-	}
-	else
-	{
-#define MAX_RETRY_COUNT  10
-
-		int retryCount = 0;
-		void	*tmpBuf = TransferBuffer;
-
-		// Acquire Control token
-#ifdef INF_AMAZON_SE
-		ret = down_interruptible(&(pAd->UsbVendorReq_semaphore));
-		if (pAd->UsbVendorReqBuf)
-		{
-			ASSERT(TransferBufferLength <MAX_PARAM_BUFFER_SIZE);
-
-		   	tmpBuf = (void *)pAd->UsbVendorReqBuf;
-		   	NdisZeroMemory(pAd->UsbVendorReqBuf, TransferBufferLength);
-
-		   	if (RequestType == DEVICE_VENDOR_REQUEST_OUT)
-		   	 NdisMoveMemory(tmpBuf, TransferBuffer, TransferBufferLength);
-		}
-#endif // INF_AMAZON_SE //
-		do {
-		if( RequestType == DEVICE_VENDOR_REQUEST_OUT)
-			ret=usb_control_msg(pObj->pUsb_Dev, usb_sndctrlpipe( pObj->pUsb_Dev, 0 ), Request, RequestType, Value,Index, tmpBuf, TransferBufferLength, CONTROL_TIMEOUT_JIFFIES);
-		else if(RequestType == DEVICE_VENDOR_REQUEST_IN)
-			ret=usb_control_msg(pObj->pUsb_Dev, usb_rcvctrlpipe( pObj->pUsb_Dev, 0 ), Request, RequestType, Value,Index, tmpBuf, TransferBufferLength, CONTROL_TIMEOUT_JIFFIES);
-		else
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("vendor request direction is failed\n"));
-			ret = -1;
-		}
-
-			retryCount++;
-			if (ret < 0) {
-				printk("#\n");
-				RTMPusecDelay(5000);
-			}
-		} while((ret < 0) && (retryCount < MAX_RETRY_COUNT));
-
-#ifdef INF_AMAZON_SE
-	  	if ((pAd->UsbVendorReqBuf) && (RequestType == DEVICE_VENDOR_REQUEST_IN))
-			NdisMoveMemory(TransferBuffer, tmpBuf, TransferBufferLength);
-	  	up(&(pAd->UsbVendorReq_semaphore));
-#endif // INF_AMAZON_SE //
-
-        if (ret < 0) {
-//			DBGPRINT(RT_DEBUG_ERROR, ("USBVendorRequest failed ret=%d \n",ret));
-			DBGPRINT(RT_DEBUG_ERROR, ("RTUSB_VendorRequest failed(%d),TxFlags=0x%x, ReqType=%s, Req=0x%x, Index=0x%x\n",
-						ret, TransferFlags, (RequestType == DEVICE_VENDOR_REQUEST_OUT ? "OUT" : "IN"), Request, Index));
-			if (Request == 0x2)
-				DBGPRINT(RT_DEBUG_ERROR, ("\tRequest Value=0x%04x!\n", Value));
-
-			if ((TransferBuffer!= NULL) && (TransferBufferLength > 0))
-				hex_dump("Failed TransferBuffer value", TransferBuffer, TransferBufferLength);
-        }
-	}
-	return ret;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-	  Creates an IRP to submite an IOCTL_INTERNAL_USB_RESET_PORT
-	  synchronously. Callers of this function must be running at
-	  PASSIVE LEVEL.
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-NTSTATUS	RTUSB_ResetDevice(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	NTSTATUS		Status = TRUE;
-
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("--->USB_ResetDevice\n"));
-	//RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS);
-	return Status;
-}
-
-VOID CMDHandler(
-    IN PRTMP_ADAPTER pAd)
-{
-	PCmdQElmt		cmdqelmt;
-	PUCHAR			pData;
-	NDIS_STATUS		NdisStatus = NDIS_STATUS_SUCCESS;
-//	ULONG			Now = 0;
-	NTSTATUS		ntStatus;
-//	unsigned long	IrqFlags;
-
-	while (pAd->CmdQ.size > 0)
-	{
-		NdisStatus = NDIS_STATUS_SUCCESS;
-
-		NdisAcquireSpinLock(&pAd->CmdQLock);
-		RTUSBDequeueCmd(&pAd->CmdQ, &cmdqelmt);
-		NdisReleaseSpinLock(&pAd->CmdQLock);
-
-		if (cmdqelmt == NULL)
-			break;
-
-		pData = cmdqelmt->buffer;
-
-		if(!(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST) || RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)))
-		{
-			switch (cmdqelmt->command)
-			{
-				case CMDTHREAD_CHECK_GPIO:
-					{
-#ifdef CONFIG_STA_SUPPORT
-						UINT32 data;
-#endif // CONFIG_STA_SUPPORT //
-#ifdef RALINK_ATE
-       					if(ATE_ON(pAd))
-						{
-							DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-							break;
-						}
-#endif // RALINK_ATE //
-
-#ifdef CONFIG_STA_SUPPORT
-
-
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-						{
-							// Read GPIO pin2 as Hardware controlled radio state
-
-							RTUSBReadMACRegister( pAd, GPIO_CTRL_CFG, &data);
-
-							if (data & 0x04)
-							{
-								pAd->StaCfg.bHwRadio = TRUE;
-							}
-							else
-							{
-								pAd->StaCfg.bHwRadio = FALSE;
-							}
-
-							if(pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
-							{
-								pAd->StaCfg.bRadio = (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio);
-								if(pAd->StaCfg.bRadio == TRUE)
-								{
-									DBGPRINT_RAW(RT_DEBUG_ERROR, ("!!! Radio On !!!\n"));
-
-									MlmeRadioOn(pAd);
-									// Update extra information
-									pAd->ExtraInfo = EXTRA_INFO_CLEAR;
-								}
-								else
-								{
-									DBGPRINT_RAW(RT_DEBUG_ERROR, ("!!! Radio Off !!!\n"));
-
-									MlmeRadioOff(pAd);
-									// Update extra information
-									pAd->ExtraInfo = HW_RADIO_OFF;
-								}
-							}
-						}
-#endif // CONFIG_STA_SUPPORT //
-					}
-					break;
-
-#ifdef CONFIG_STA_SUPPORT
-				case CMDTHREAD_QKERIODIC_EXECUT:
-					{
-						StaQuickResponeForRateUpExec(NULL, pAd, NULL, NULL);
-					}
-					break;
-#endif // CONFIG_STA_SUPPORT //
-
-				case CMDTHREAD_RESET_BULK_OUT:
-					{
-						UINT32		MACValue;
-						UCHAR		Index;
-						int			ret=0;
-						PHT_TX_CONTEXT	pHTTXContext;
-//						RTMP_TX_RING *pTxRing;
-						unsigned long IrqFlags;
-#ifdef RALINK_ATE
-						PTX_CONTEXT		pNullContext = &(pAd->NullContext);
-#endif // RALINK_ATE //
-						DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_RESET_BULK_OUT(ResetPipeid=0x%0x)===>\n", pAd->bulkResetPipeid));
-						// All transfers must be aborted or cancelled before attempting to reset the pipe.
-						//RTUSBCancelPendingBulkOutIRP(pAd);
-						// Wait 10ms to let previous packet that are already in HW FIFO to clear. by MAXLEE 12-25-2007
-						Index = 0;
-						do
-						{
-							RTUSBReadMACRegister(pAd, TXRXQ_PCNT, &MACValue);
-							if ((MACValue & 0xf00000/*0x800000*/) == 0)
-								break;
-							Index++;
-							RTMPusecDelay(10000);
-						}while(Index < 100);
-						MACValue = 0;
-						RTUSBReadMACRegister(pAd, USB_DMA_CFG, &MACValue);
-						// To prevent Read Register error, we 2nd check the validity.
-						if ((MACValue & 0xc00000) == 0)
-							RTUSBReadMACRegister(pAd, USB_DMA_CFG, &MACValue);
-						// To prevent Read Register error, we 3rd check the validity.
-						if ((MACValue & 0xc00000) == 0)
-							RTUSBReadMACRegister(pAd, USB_DMA_CFG, &MACValue);
-						MACValue |= 0x80000;
-						RTUSBWriteMACRegister(pAd, USB_DMA_CFG, MACValue);
-
-						// Wait 1ms to prevent next URB to bulkout before HW reset. by MAXLEE 12-25-2007
-						RTMPusecDelay(1000);
-
-						MACValue &= (~0x80000);
-						RTUSBWriteMACRegister(pAd, USB_DMA_CFG, MACValue);
-						DBGPRINT_RAW(RT_DEBUG_TRACE, ("\tSet 0x2a0 bit19. Clear USB DMA TX path\n"));
-
-						// Wait 5ms to prevent next URB to bulkout before HW reset. by MAXLEE 12-25-2007
-						//RTMPusecDelay(5000);
-
-						if ((pAd->bulkResetPipeid & BULKOUT_MGMT_RESET_FLAG) == BULKOUT_MGMT_RESET_FLAG)
-						{
-							RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-							if (pAd->MgmtRing.TxSwFreeIdx < MGMT_RING_SIZE /* pMLMEContext->bWaitingBulkOut == TRUE */)
-							{
-								RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_MLME);
-							}
-							RTUSBKickBulkOut(pAd);
-
-							DBGPRINT_RAW(RT_DEBUG_TRACE, ("\tTX MGMT RECOVER Done!\n"));
-						}
-						else
-						{
-							pHTTXContext = &(pAd->TxContext[pAd->bulkResetPipeid]);
-							//NdisAcquireSpinLock(&pAd->BulkOutLock[pAd->bulkResetPipeid]);
-							RTMP_INT_LOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
-							if ( pAd->BulkOutPending[pAd->bulkResetPipeid] == FALSE)
-							{
-								pAd->BulkOutPending[pAd->bulkResetPipeid] = TRUE;
-								pHTTXContext->IRPPending = TRUE;
-								pAd->watchDogTxPendingCnt[pAd->bulkResetPipeid] = 1;
-
-								// no matter what, clean the flag
-								RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-
-								//NdisReleaseSpinLock(&pAd->BulkOutLock[pAd->bulkResetPipeid]);
-								RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
-/*-----------------------------------------------------------------------------------------------*/
-#ifdef RALINK_ATE
-								if(ATE_ON(pAd))
-							    {
-									pNullContext->IRPPending = TRUE;
-									//
-									// If driver is still in ATE TXFRAME mode,
-									// keep on transmitting ATE frames.
-									//
-									DBGPRINT_RAW(RT_DEBUG_TRACE, ("pAd->ate.Mode == %d\npAd->ContinBulkOut == %d\npAd->BulkOutRemained == %d\n", pAd->ate.Mode, pAd->ContinBulkOut, atomic_read(&pAd->BulkOutRemained)));
-									if((pAd->ate.Mode == ATE_TXFRAME) && ((pAd->ContinBulkOut == TRUE) || (atomic_read(&pAd->BulkOutRemained) > 0)))
-								    {
-										DBGPRINT_RAW(RT_DEBUG_TRACE, ("After CMDTHREAD_RESET_BULK_OUT, continue to bulk out frames !\n"));
-
-										// Init Tx context descriptor
-										RTUSBInitTxDesc(pAd, pNullContext, 0/* pAd->bulkResetPipeid */, (usb_complete_t)ATE_RTUSBBulkOutDataPacketComplete);
-
-										if((ret = RTUSB_SUBMIT_URB(pNullContext->pUrb))!=0)
-										{
-											DBGPRINT(RT_DEBUG_ERROR, ("ATE_RTUSBBulkOutDataPacket: Submit Tx URB failed %d\n", ret));
-										}
-
-										pAd->BulkOutReq++;
-									}
-								}
-								else
-#endif // RALINK_ATE //
-/*-----------------------------------------------------------------------------------------------*/
-								{
-								RTUSBInitHTTxDesc(pAd, pHTTXContext, pAd->bulkResetPipeid, pHTTXContext->BulkOutSize, (usb_complete_t)RTUSBBulkOutDataPacketComplete);
-
-								if((ret = RTUSB_SUBMIT_URB(pHTTXContext->pUrb))!=0)
-								{
-										RTMP_INT_LOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
-									pAd->BulkOutPending[pAd->bulkResetPipeid] = FALSE;
-									pHTTXContext->IRPPending = FALSE;
-										pAd->watchDogTxPendingCnt[pAd->bulkResetPipeid] = 0;
-										RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
-
-										DBGPRINT(RT_DEBUG_ERROR, ("CmdThread : CMDTHREAD_RESET_BULK_OUT: Submit Tx URB failed %d\n", ret));
-								}
-									else
-									{
-										RTMP_IRQ_LOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
-										DBGPRINT_RAW(RT_DEBUG_TRACE,("\tCMDTHREAD_RESET_BULK_OUT: TxContext[%d]:CWPos=%ld, NBPos=%ld, ENBPos=%ld, bCopy=%d, pending=%d!\n",
-												pAd->bulkResetPipeid, pHTTXContext->CurWritePosition, pHTTXContext->NextBulkOutPosition,
-															pHTTXContext->ENextBulkOutPosition, pHTTXContext->bCopySavePad, pAd->BulkOutPending[pAd->bulkResetPipeid]));
-										DBGPRINT_RAW(RT_DEBUG_TRACE,("\t\tBulkOut Req=0x%lx, Complete=0x%lx, Other=0x%lx\n",
-															pAd->BulkOutReq, pAd->BulkOutComplete, pAd->BulkOutCompleteOther));
-										RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
-										DBGPRINT_RAW(RT_DEBUG_TRACE, ("\tCMDTHREAD_RESET_BULK_OUT: Submit Tx DATA URB for failed BulkReq(0x%lx) Done, status=%d!\n", pAd->bulkResetReq[pAd->bulkResetPipeid], pHTTXContext->pUrb->status));
-
-									}
-								}
-							}
-							else
-							{
-								//NdisReleaseSpinLock(&pAd->BulkOutLock[pAd->bulkResetPipeid]);
-								//RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
-
-								DBGPRINT_RAW(RT_DEBUG_ERROR, ("CmdThread : TX DATA RECOVER FAIL for BulkReq(0x%lx) because BulkOutPending[%d] is TRUE!\n", pAd->bulkResetReq[pAd->bulkResetPipeid], pAd->bulkResetPipeid));
-								if (pAd->bulkResetPipeid == 0)
-								{
-									UCHAR	pendingContext = 0;
-									PHT_TX_CONTEXT pHTTXContext = (PHT_TX_CONTEXT)(&pAd->TxContext[pAd->bulkResetPipeid ]);
-									PTX_CONTEXT pMLMEContext = (PTX_CONTEXT)(pAd->MgmtRing.Cell[pAd->MgmtRing.TxDmaIdx].AllocVa);
-									PTX_CONTEXT pNULLContext = (PTX_CONTEXT)(&pAd->PsPollContext);
-									PTX_CONTEXT pPsPollContext = (PTX_CONTEXT)(&pAd->NullContext);
-
-									if (pHTTXContext->IRPPending)
-										pendingContext |= 1;
-									else if (pMLMEContext->IRPPending)
-										pendingContext |= 2;
-									else if (pNULLContext->IRPPending)
-										pendingContext |= 4;
-									else if (pPsPollContext->IRPPending)
-										pendingContext |= 8;
-									else
-										pendingContext = 0;
-
-									DBGPRINT_RAW(RT_DEBUG_ERROR, ("\tTX Occupied by %d!\n", pendingContext));
-								}
-
-							// no matter what, clean the flag
-							RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-
-								RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
-
-								RTUSB_SET_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << pAd->bulkResetPipeid));
-							}
-
-							RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-							//RTUSBKickBulkOut(pAd);
-						}
-
-					}
-					/*
-						// Don't cancel BULKIN.
-						while ((atomic_read(&pAd->PendingRx) > 0) &&
-								(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-						{
-							if (atomic_read(&pAd->PendingRx) > 0)
-							{
-								DBGPRINT_RAW(RT_DEBUG_ERROR, ("BulkIn IRP Pending!!cancel it!\n"));
-								RTUSBCancelPendingBulkInIRP(pAd);
-							}
-							RTMPusecDelay(100000);
-						}
-
-						if ((atomic_read(&pAd->PendingRx) == 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)))
-						{
-							UCHAR	i;
-							RTUSBRxPacket(pAd);
-							pAd->NextRxBulkInReadIndex = 0;	// Next Rx Read index
-							pAd->NextRxBulkInIndex		= 0;	// Rx Bulk pointer
-							for (i = 0; i < (RX_RING_SIZE); i++)
-							{
-								PRX_CONTEXT  pRxContext = &(pAd->RxContext[i]);
-
-								pRxContext->pAd	= pAd;
-								pRxContext->InUse		= FALSE;
-								pRxContext->IRPPending	= FALSE;
-								pRxContext->Readable	= FALSE;
-								pRxContext->ReorderInUse = FALSE;
-
-							}
-							RTUSBBulkReceive(pAd);
-							DBGPRINT_RAW(RT_DEBUG_ERROR, ("RTUSBBulkReceive\n"));
-						}*/
-					DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_RESET_BULK_OUT<===\n"));
-    	   			break;
-
-				case CMDTHREAD_RESET_BULK_IN:
-					DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_RESET_BULK_IN === >\n"));
-
-					// All transfers must be aborted or cancelled before attempting to reset the pipe.
-					{
-						UINT32		MACValue;
-/*-----------------------------------------------------------------------------------------------*/
-#ifdef RALINK_ATE
-						if (ATE_ON(pAd))
-						{
-							if((pAd->PendingRx > 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-							{
-								DBGPRINT_RAW(RT_DEBUG_ERROR, ("ATE : BulkIn IRP Pending!!!\n"));
-								ATE_RTUSBCancelPendingBulkInIRP(pAd);
-								RTMPusecDelay(100000);
-								pAd->PendingRx = 0;
-							}
-						}
-						else
-#endif // RALINK_ATE //
-/*-----------------------------------------------------------------------------------------------*/
-						{
-						//while ((atomic_read(&pAd->PendingRx) > 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-						if((pAd->PendingRx > 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-						{
-							DBGPRINT_RAW(RT_DEBUG_ERROR, ("BulkIn IRP Pending!!!\n"));
-							RTUSBCancelPendingBulkInIRP(pAd);
-							RTMPusecDelay(100000);
-							pAd->PendingRx = 0;
-						}
-						}
-
-						// Wait 10ms before reading register.
-						RTMPusecDelay(10000);
-						ntStatus = RTUSBReadMACRegister(pAd, MAC_CSR0, &MACValue);
-
-						if ((NT_SUCCESS(ntStatus) == TRUE) &&
-							(!(RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS | fRTMP_ADAPTER_RADIO_OFF |
-													fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST)))))
-						{
-							UCHAR	i;
-
-							if (RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS | fRTMP_ADAPTER_RADIO_OFF |
-														fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST)))
-								break;
-							pAd->NextRxBulkInPosition = pAd->RxContext[pAd->NextRxBulkInIndex].BulkInOffset;
-							DBGPRINT(RT_DEBUG_TRACE, ("BULK_IN_RESET: NBIIdx=0x%x,NBIRIdx=0x%x, BIRPos=0x%lx. BIReq=x%lx, BIComplete=0x%lx, BICFail0x%lx\n",
-									pAd->NextRxBulkInIndex,  pAd->NextRxBulkInReadIndex, pAd->NextRxBulkInPosition, pAd->BulkInReq, pAd->BulkInComplete, pAd->BulkInCompleteFail));
-							for (i = 0; i < RX_RING_SIZE; i++)
-							{
- 								DBGPRINT(RT_DEBUG_TRACE, ("\tRxContext[%d]: IRPPending=%d, InUse=%d, Readable=%d!\n"
-									, i, pAd->RxContext[i].IRPPending, pAd->RxContext[i].InUse, pAd->RxContext[i].Readable));
-							}
- 							/*
-
-							DBGPRINT_RAW(RT_DEBUG_ERROR, ("==========================================\n"));
-
-							pAd->NextRxBulkInReadIndex = 0;	// Next Rx Read index
-							pAd->NextRxBulkInIndex		= 0;	// Rx Bulk pointer
-							for (i = 0; i < (RX_RING_SIZE); i++)
-							{
-								PRX_CONTEXT  pRxContext = &(pAd->RxContext[i]);
-
-								pRxContext->pAd	= pAd;
-								pRxContext->InUse		= FALSE;
-								pRxContext->IRPPending	= FALSE;
-								pRxContext->Readable	= FALSE;
-								pRxContext->ReorderInUse = FALSE;
-
-							}*/
-							RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKIN_RESET);
-							for (i = 0; i < pAd->CommonCfg.NumOfBulkInIRP; i++)
-							{
-								//RTUSBBulkReceive(pAd);
-								PRX_CONTEXT		pRxContext;
-								PURB			pUrb;
-								int				ret = 0;
-								unsigned long	IrqFlags;
-
-
-								RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-								pRxContext = &(pAd->RxContext[pAd->NextRxBulkInIndex]);
-								if ((pAd->PendingRx > 0) || (pRxContext->Readable == TRUE) || (pRxContext->InUse == TRUE))
-								{
-									RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-									break;
-								}
-								pRxContext->InUse = TRUE;
-								pRxContext->IRPPending = TRUE;
-								pAd->PendingRx++;
-								pAd->BulkInReq++;
-								RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-
-								// Init Rx context descriptor
-								RTUSBInitRxDesc(pAd, pRxContext);
-								pUrb = pRxContext->pUrb;
-								if ((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
-								{	// fail
-
-									RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-									pRxContext->InUse = FALSE;
-									pRxContext->IRPPending = FALSE;
-									pAd->PendingRx--;
-									pAd->BulkInReq--;
-									RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-									DBGPRINT(RT_DEBUG_ERROR, ("CMDTHREAD_RESET_BULK_IN: Submit Rx URB failed(%d), status=%d\n", ret, pUrb->status));
-								}
-								else
-								{	// success
-									DBGPRINT_RAW(RT_DEBUG_TRACE, ("CMDTHREAD_RESET_BULK_IN: Submit Rx URB Done, status=%d!\n", pUrb->status));
-									ASSERT((pRxContext->InUse == pRxContext->IRPPending));
-								}
-							}
-
-						}
-						else
-						{
-							// Card must be removed
-							if (NT_SUCCESS(ntStatus) != TRUE)
-							{
-							RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);
-								DBGPRINT_RAW(RT_DEBUG_ERROR, ("CMDTHREAD_RESET_BULK_IN: Read Register Failed!Card must be removed!!\n\n"));
-							}
-							else
-							{
-								DBGPRINT_RAW(RT_DEBUG_ERROR, ("CMDTHREAD_RESET_BULK_IN: Cannot do bulk in because flags(0x%lx) on !\n", pAd->Flags));
-						}
-					}
-					}
-					DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_RESET_BULK_IN <===\n"));
-					break;
-
-				case CMDTHREAD_SET_ASIC_WCID:
-					{
-						RT_SET_ASIC_WCID	SetAsicWcid;
-						USHORT		offset;
-						UINT32		MACValue, MACRValue = 0;
-						SetAsicWcid = *((PRT_SET_ASIC_WCID)(pData));
-
-						if (SetAsicWcid.WCID >= MAX_LEN_OF_MAC_TABLE)
-							return;
-
-						offset = MAC_WCID_BASE + ((UCHAR)SetAsicWcid.WCID)*HW_WCID_ENTRY_SIZE;
-
-						DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_SET_ASIC_WCID : WCID = %ld, SetTid  = %lx, DeleteTid = %lx.\n", SetAsicWcid.WCID, SetAsicWcid.SetTid, SetAsicWcid.DeleteTid));
-						MACValue = (pAd->MacTab.Content[SetAsicWcid.WCID].Addr[3]<<24)+(pAd->MacTab.Content[SetAsicWcid.WCID].Addr[2]<<16)+(pAd->MacTab.Content[SetAsicWcid.WCID].Addr[1]<<8)+(pAd->MacTab.Content[SetAsicWcid.WCID].Addr[0]);
-						DBGPRINT_RAW(RT_DEBUG_TRACE, ("1-MACValue= %x,\n", MACValue));
-						RTUSBWriteMACRegister(pAd, offset, MACValue);
-						// Read bitmask
-						RTUSBReadMACRegister(pAd, offset+4, &MACRValue);
-						if ( SetAsicWcid.DeleteTid != 0xffffffff)
-							MACRValue &= (~SetAsicWcid.DeleteTid);
-						if (SetAsicWcid.SetTid != 0xffffffff)
-							MACRValue |= (SetAsicWcid.SetTid);
-						MACRValue &= 0xffff0000;
-
-						MACValue = (pAd->MacTab.Content[SetAsicWcid.WCID].Addr[5]<<8)+pAd->MacTab.Content[SetAsicWcid.WCID].Addr[4];
-						MACValue |= MACRValue;
-						RTUSBWriteMACRegister(pAd, offset+4, MACValue);
-
-						DBGPRINT_RAW(RT_DEBUG_TRACE, ("2-MACValue= %x,\n", MACValue));
-					}
-					break;
-
-				case CMDTHREAD_SET_ASIC_WCID_CIPHER:
-					{
-#ifdef CONFIG_STA_SUPPORT
-						RT_SET_ASIC_WCID_ATTRI	SetAsicWcidAttri;
-						USHORT		offset;
-						UINT32		MACRValue = 0;
-						SHAREDKEY_MODE_STRUC csr1;
-						SetAsicWcidAttri = *((PRT_SET_ASIC_WCID_ATTRI)(pData));
-
-						if (SetAsicWcidAttri.WCID >= MAX_LEN_OF_MAC_TABLE)
-							return;
-
-						offset = MAC_WCID_ATTRIBUTE_BASE + ((UCHAR)SetAsicWcidAttri.WCID)*HW_WCID_ATTRI_SIZE;
-
-						DBGPRINT_RAW(RT_DEBUG_TRACE, ("Cmd : CMDTHREAD_SET_ASIC_WCID_CIPHER : WCID = %ld, Cipher = %lx.\n", SetAsicWcidAttri.WCID, SetAsicWcidAttri.Cipher));
-						// Read bitmask
-						RTUSBReadMACRegister(pAd, offset, &MACRValue);
-						MACRValue = 0;
-						MACRValue |= (((UCHAR)SetAsicWcidAttri.Cipher) << 1);
-
-						RTUSBWriteMACRegister(pAd, offset, MACRValue);
-						DBGPRINT_RAW(RT_DEBUG_TRACE, ("2-offset = %x , MACValue= %x,\n", offset, MACRValue));
-
-						offset = PAIRWISE_IVEIV_TABLE_BASE + ((UCHAR)SetAsicWcidAttri.WCID)*HW_IVEIV_ENTRY_SIZE;
-						MACRValue = 0;
-						if ( (SetAsicWcidAttri.Cipher <= CIPHER_WEP128))
-							MACRValue |= ( pAd->StaCfg.DefaultKeyId << 30);
-						else
-							MACRValue |= (0x20000000);
-						RTUSBWriteMACRegister(pAd, offset, MACRValue);
-						DBGPRINT_RAW(RT_DEBUG_TRACE, ("2-offset = %x , MACValue= %x,\n", offset, MACRValue));
-
-						//
-						// Update cipher algorithm. WSTA always use BSS0
-						//
-						// for adhoc mode only ,because wep status slow than add key, when use zero config
-						if (pAd->StaCfg.BssType == BSS_ADHOC )
-						{
-							offset = MAC_WCID_ATTRIBUTE_BASE;
-
-							RTUSBReadMACRegister(pAd, offset, &MACRValue);
-							MACRValue &= (~0xe);
-							MACRValue |= (((UCHAR)SetAsicWcidAttri.Cipher) << 1);
-
-							RTUSBWriteMACRegister(pAd, offset, MACRValue);
-
-							//Update group key cipher,,because wep status slow than add key, when use zero config
-							RTUSBReadMACRegister(pAd, SHARED_KEY_MODE_BASE+4*(0/2), &csr1.word);
-
-							csr1.field.Bss0Key0CipherAlg = SetAsicWcidAttri.Cipher;
-							csr1.field.Bss0Key1CipherAlg = SetAsicWcidAttri.Cipher;
-
-							RTUSBWriteMACRegister(pAd, SHARED_KEY_MODE_BASE+4*(0/2), csr1.word);
-						}
-#endif // CONFIG_STA_SUPPORT //
-					}
-					break;
-
-//Benson modified for USB interface, avoid in interrupt when write key, 20080724 -->
-				case RT_CMD_SET_KEY_TABLE: //General call for AsicAddPairwiseKeyEntry()
-				{
-					RT_ADD_PAIRWISE_KEY_ENTRY KeyInfo;
-					KeyInfo = *((PRT_ADD_PAIRWISE_KEY_ENTRY)(pData));
-					AsicAddPairwiseKeyEntry(pAd,
-											KeyInfo.MacAddr,
-											(UCHAR)KeyInfo.MacTabMatchWCID,
-											&KeyInfo.CipherKey);
-				}
-					break;
-				case RT_CMD_SET_RX_WCID_TABLE: //General call for RTMPAddWcidAttributeEntry()
-				{
-					PMAC_TABLE_ENTRY pEntry;
-					UCHAR KeyIdx;
-					UCHAR CipherAlg;
-					UCHAR ApIdx;
-
-					pEntry = (PMAC_TABLE_ENTRY)(pData);
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-					KeyIdx = 0;
-					CipherAlg = pEntry->PairwiseKey.CipherAlg;
-					ApIdx = BSS0;
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-
-						RTMPAddWcidAttributeEntry(
-										  pAd,
-										  ApIdx,
-										  KeyIdx,
-										  CipherAlg,
-										  pEntry);
-					}
-						break;
-//Benson modified for USB interface, avoid in interrupt when write key, 20080724 <--
-
-				case CMDTHREAD_SET_CLIENT_MAC_ENTRY:
-					{
-						MAC_TABLE_ENTRY *pEntry;
-						pEntry = (MAC_TABLE_ENTRY *)pData;
-
-
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-						{
-							AsicRemovePairwiseKeyEntry(pAd, pEntry->apidx, (UCHAR)pEntry->Aid);
-							if ((pEntry->AuthMode <= Ndis802_11AuthModeAutoSwitch) && (pEntry->WepStatus == Ndis802_11Encryption1Enabled))
-							{
-								UINT32 uIV = 0;
-								PUCHAR  ptr;
-
-								ptr = (PUCHAR) &uIV;
-								*(ptr + 3) = (pAd->StaCfg.DefaultKeyId << 6);
-								AsicUpdateWCIDIVEIV(pAd, pEntry->Aid, uIV, 0);
-								AsicUpdateWCIDAttribute(pAd, pEntry->Aid, BSS0, pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg, FALSE);
-							}
-							else if (pEntry->AuthMode == Ndis802_11AuthModeWPANone)
-							{
-								UINT32 uIV = 0;
-								PUCHAR  ptr;
-
-								ptr = (PUCHAR) &uIV;
-								*(ptr + 3) = (pAd->StaCfg.DefaultKeyId << 6);
-								AsicUpdateWCIDIVEIV(pAd, pEntry->Aid, uIV, 0);
-								AsicUpdateWCIDAttribute(pAd, pEntry->Aid, BSS0, pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg, FALSE);
-							}
-							else
-							{
-								//
-								// Other case, disable engine.
-								// Don't worry WPA key, we will add WPA Key after 4-Way handshaking.
-								//
-								USHORT   offset;
-								offset = MAC_WCID_ATTRIBUTE_BASE + (pEntry->Aid * HW_WCID_ATTRI_SIZE);
-								// RX_PKEY_MODE:0 for no security; RX_KEY_TAB:0 for shared key table; BSS_IDX:0
-								RTUSBWriteMACRegister(pAd, offset, 0);
-							}
-						}
-#endif // CONFIG_STA_SUPPORT //
-
-						AsicUpdateRxWCIDTable(pAd, pEntry->Aid, pEntry->Addr);
-						printk("UpdateRxWCIDTable(): Aid=%d, Addr=%02x:%02x:%02x:%02x:%02x:%02x!\n", pEntry->Aid,
-								pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2], pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5]);
-					}
-					break;
-
-// add by johnli, fix "in_interrupt" error when call "MacTableDeleteEntry" in Rx tasklet
-				case CMDTHREAD_UPDATE_PROTECT:
-					{
-						AsicUpdateProtect(pAd, 0, (ALLN_SETPROTECT), TRUE, 0);
-					}
-					break;
-// end johnli
-
-				case OID_802_11_ADD_WEP:
-					{
-#ifdef CONFIG_STA_SUPPORT
-						UINT	i;
-						UINT32	KeyIdx;
-						PNDIS_802_11_WEP	pWepKey;
-
-						DBGPRINT(RT_DEBUG_TRACE, ("CmdThread::OID_802_11_ADD_WEP  \n"));
-
-						pWepKey = (PNDIS_802_11_WEP)pData;
-						KeyIdx = pWepKey->KeyIndex & 0x0fffffff;
-
-						// it is a shared key
-						if ((KeyIdx >= 4) || ((pWepKey->KeyLength != 5) && (pWepKey->KeyLength != 13)))
-						{
-							NdisStatus = NDIS_STATUS_INVALID_DATA;
-							DBGPRINT(RT_DEBUG_ERROR, ("CmdThread::OID_802_11_ADD_WEP, INVALID_DATA!!\n"));
-						}
-						else
-						{
-							UCHAR CipherAlg;
-							pAd->SharedKey[BSS0][KeyIdx].KeyLen = (UCHAR) pWepKey->KeyLength;
-							NdisMoveMemory(pAd->SharedKey[BSS0][KeyIdx].Key, &pWepKey->KeyMaterial, pWepKey->KeyLength);
-							CipherAlg = (pAd->SharedKey[BSS0][KeyIdx].KeyLen == 5)? CIPHER_WEP64 : CIPHER_WEP128;
-
-							//
-							// Change the WEP cipher to CKIP cipher if CKIP KP on.
-							// Funk UI or Meetinghouse UI will add ckip key from this path.
-							//
-
-							if (pAd->OpMode == OPMODE_STA)
-						 	{
-								pAd->MacTab.Content[BSSID_WCID].PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][KeyIdx].CipherAlg;
-								pAd->MacTab.Content[BSSID_WCID].PairwiseKey.KeyLen = pAd->SharedKey[BSS0][KeyIdx].KeyLen;
-						 	}
-							pAd->SharedKey[BSS0][KeyIdx].CipherAlg = CipherAlg;
-							if (pWepKey->KeyIndex & 0x80000000)
-							{
-								// Default key for tx (shared key)
-								UCHAR	IVEIV[8];
-								UINT32	WCIDAttri, Value;
-								USHORT	offset, offset2;
-								NdisZeroMemory(IVEIV, 8);
-								pAd->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-								// Add BSSID to WCTable. because this is Tx wep key.
-								// WCID Attribute UDF:3, BSSIdx:3, Alg:3, Keytable:1=PAIRWISE KEY, BSSIdx is 0
-								WCIDAttri = (CipherAlg<<1)|SHAREDKEYTABLE;
-
-								offset = MAC_WCID_ATTRIBUTE_BASE + (BSSID_WCID* HW_WCID_ATTRI_SIZE);
-								RTUSBWriteMACRegister(pAd, offset, WCIDAttri);
-								// 1. IV/EIV
-								// Specify key index to find shared key.
-								IVEIV[3] = (UCHAR)(KeyIdx<< 6);	//WEP Eiv bit off. groupkey index is not 0
-								offset = PAIRWISE_IVEIV_TABLE_BASE + (BSS0Mcast_WCID * HW_IVEIV_ENTRY_SIZE);
-								offset2 = PAIRWISE_IVEIV_TABLE_BASE + (BSSID_WCID* HW_IVEIV_ENTRY_SIZE);
-								for (i=0; i<8;)
-								{
-									Value = IVEIV[i];
-									Value += (IVEIV[i+1]<<8);
-									Value += (IVEIV[i+2]<<16);
-									Value += (IVEIV[i+3]<<24);
-									RTUSBWriteMACRegister(pAd, offset+i, Value);
-									RTUSBWriteMACRegister(pAd, offset2+i, Value);
-									i+=4;
-								}
-
-								// 2. WCID Attribute UDF:3, BSSIdx:3, Alg:3, Keytable:use share key, BSSIdx is 0
-								WCIDAttri = (pAd->SharedKey[BSS0][KeyIdx].CipherAlg<<1)|SHAREDKEYTABLE;
-								offset = MAC_WCID_ATTRIBUTE_BASE + (BSS0Mcast_WCID* HW_WCID_ATTRI_SIZE);
-							        DBGPRINT(RT_DEBUG_TRACE, ("BSS0Mcast_WCID : offset = %x, WCIDAttri = %x\n", offset, WCIDAttri));
-								RTUSBWriteMACRegister(pAd, offset, WCIDAttri);
-
-							}
-							AsicAddSharedKeyEntry(pAd, BSS0, (UCHAR)KeyIdx, CipherAlg, pWepKey->KeyMaterial, NULL, NULL);
-							DBGPRINT(RT_DEBUG_TRACE, ("CmdThread::OID_802_11_ADD_WEP (KeyIdx=%d, Len=%d-byte)\n", KeyIdx, pWepKey->KeyLength));
-						}
-#endif // CONFIG_STA_SUPPORT //
-					}
-					break;
-
-				case CMDTHREAD_802_11_COUNTER_MEASURE:
-					break;
-
-				default:
-					DBGPRINT(RT_DEBUG_ERROR, ("--> Control Thread !! ERROR !! Unknown(cmdqelmt->command=0x%x) !! \n", cmdqelmt->command));
-					break;
-			}
-		}
-
-		if (cmdqelmt->CmdFromNdis == TRUE)
-		{
-				if (cmdqelmt->buffer != NULL)
-					NdisFreeMemory(cmdqelmt->buffer, cmdqelmt->bufferlength, 0);
-
-			NdisFreeMemory(cmdqelmt, sizeof(CmdQElmt), 0);
-		}
-		else
-		{
-			if ((cmdqelmt->buffer != NULL) && (cmdqelmt->bufferlength != 0))
-				NdisFreeMemory(cmdqelmt->buffer, cmdqelmt->bufferlength, 0);
-            {
-				NdisFreeMemory(cmdqelmt, sizeof(CmdQElmt), 0);
-			}
-		}
-	}	/* end of while */
-}
-
+#include "../../rt2870/common/rtusb_io.c"
diff --git a/drivers/staging/rt3070/common/spectrum.c b/drivers/staging/rt3070/common/spectrum.c
index da57b12..de3b949 100644
--- a/drivers/staging/rt3070/common/spectrum.c
+++ b/drivers/staging/rt3070/common/spectrum.c
@@ -1,1876 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-	action.c
-
-    Abstract:
-    Handle association related requests either from WSTA or from local MLME
-
-    Revision History:
-    Who          When          What
-    ---------    ----------    ----------------------------------------------
-	Fonchi Wu    2008	  	   created for 802.11h
- */
-
-#include "../rt_config.h"
-#include "../action.h"
-
-VOID MeasureReqTabInit(
-	IN PRTMP_ADAPTER pAd)
-{
-	NdisAllocateSpinLock(&pAd->CommonCfg.MeasureReqTabLock);
-
-	pAd->CommonCfg.pMeasureReqTab = kmalloc(sizeof(MEASURE_REQ_TAB), GFP_ATOMIC);
-	if (pAd->CommonCfg.pMeasureReqTab)
-		NdisZeroMemory(pAd->CommonCfg.pMeasureReqTab, sizeof(MEASURE_REQ_TAB));
-	else
-		DBGPRINT(RT_DEBUG_ERROR, ("%s Fail to alloc memory for pAd->CommonCfg.pMeasureReqTab.\n", __FUNCTION__));
-
-	return;
-}
-
-VOID MeasureReqTabExit(
-	IN PRTMP_ADAPTER pAd)
-{
-	NdisFreeSpinLock(pAd->CommonCfg.MeasureReqTabLock);
-
-	if (pAd->CommonCfg.pMeasureReqTab)
-		kfree(pAd->CommonCfg.pMeasureReqTab);
-	pAd->CommonCfg.pMeasureReqTab = NULL;
-
-	return;
-}
-
-static PMEASURE_REQ_ENTRY MeasureReqLookUp(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	UINT HashIdx;
-	PMEASURE_REQ_TAB pTab = pAd->CommonCfg.pMeasureReqTab;
-	PMEASURE_REQ_ENTRY pEntry = NULL;
-	PMEASURE_REQ_ENTRY pPrevEntry = NULL;
-
-	if (pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab doesn't exist.\n", __FUNCTION__));
-		return NULL;
-	}
-
-	RTMP_SEM_LOCK(&pAd->CommonCfg.MeasureReqTabLock);
-
-	HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(DialogToken);
-	pEntry = pTab->Hash[HashIdx];
-
-	while (pEntry)
-	{
-		if (pEntry->DialogToken == DialogToken)
-			break;
-		else
-		{
-			pPrevEntry = pEntry;
-			pEntry = pEntry->pNext;
-		}
-	}
-
-	RTMP_SEM_UNLOCK(&pAd->CommonCfg.MeasureReqTabLock);
-
-	return pEntry;
-}
-
-static PMEASURE_REQ_ENTRY MeasureReqInsert(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	INT i;
-	ULONG HashIdx;
-	PMEASURE_REQ_TAB pTab = pAd->CommonCfg.pMeasureReqTab;
-	PMEASURE_REQ_ENTRY pEntry = NULL, pCurrEntry;
-	ULONG Now;
-
-	if(pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab doesn't exist.\n", __FUNCTION__));
-		return NULL;
-	}
-
-	pEntry = MeasureReqLookUp(pAd, DialogToken);
-	if (pEntry == NULL)
-	{
-		RTMP_SEM_LOCK(&pAd->CommonCfg.MeasureReqTabLock);
-		for (i = 0; i < MAX_MEASURE_REQ_TAB_SIZE; i++)
-		{
-			NdisGetSystemUpTime(&Now);
-			pEntry = &pTab->Content[i];
-
-			if ((pEntry->Valid == TRUE)
-				&& RTMP_TIME_AFTER((unsigned long)Now, (unsigned long)(pEntry->lastTime + MQ_REQ_AGE_OUT)))
-			{
-				PMEASURE_REQ_ENTRY pPrevEntry = NULL;
-				ULONG HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
-				PMEASURE_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
-
-				// update Hash list
-				do
-				{
-					if (pProbeEntry == pEntry)
-					{
-						if (pPrevEntry == NULL)
-						{
-							pTab->Hash[HashIdx] = pEntry->pNext;
-						}
-						else
-						{
-							pPrevEntry->pNext = pEntry->pNext;
-						}
-						break;
-					}
-
-					pPrevEntry = pProbeEntry;
-					pProbeEntry = pProbeEntry->pNext;
-				} while (pProbeEntry);
-
-				NdisZeroMemory(pEntry, sizeof(MEASURE_REQ_ENTRY));
-				pTab->Size--;
-
-				break;
-			}
-
-			if (pEntry->Valid == FALSE)
-				break;
-		}
-
-		if (i < MAX_MEASURE_REQ_TAB_SIZE)
-		{
-			NdisGetSystemUpTime(&Now);
-			pEntry->lastTime = Now;
-			pEntry->Valid = TRUE;
-			pEntry->DialogToken = DialogToken;
-			pTab->Size++;
-		}
-		else
-		{
-			pEntry = NULL;
-			DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab tab full.\n", __FUNCTION__));
-		}
-
-		// add this Neighbor entry into HASH table
-		if (pEntry)
-		{
-			HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(DialogToken);
-			if (pTab->Hash[HashIdx] == NULL)
-			{
-				pTab->Hash[HashIdx] = pEntry;
-			}
-			else
-			{
-				pCurrEntry = pTab->Hash[HashIdx];
-				while (pCurrEntry->pNext != NULL)
-					pCurrEntry = pCurrEntry->pNext;
-				pCurrEntry->pNext = pEntry;
-			}
-		}
-
-		RTMP_SEM_UNLOCK(&pAd->CommonCfg.MeasureReqTabLock);
-	}
-
-	return pEntry;
-}
-
-static VOID MeasureReqDelete(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	PMEASURE_REQ_TAB pTab = pAd->CommonCfg.pMeasureReqTab;
-	PMEASURE_REQ_ENTRY pEntry = NULL;
-
-	if(pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pMeasureReqTab doesn't exist.\n", __FUNCTION__));
-		return;
-	}
-
-	// if empty, return
-	if (pTab->Size == 0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("pMeasureReqTab empty.\n"));
-		return;
-	}
-
-	pEntry = MeasureReqLookUp(pAd, DialogToken);
-	if (pEntry != NULL)
-	{
-		PMEASURE_REQ_ENTRY pPrevEntry = NULL;
-		ULONG HashIdx = MQ_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
-		PMEASURE_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
-
-		RTMP_SEM_LOCK(&pAd->CommonCfg.MeasureReqTabLock);
-		// update Hash list
-		do
-		{
-			if (pProbeEntry == pEntry)
-			{
-				if (pPrevEntry == NULL)
-				{
-					pTab->Hash[HashIdx] = pEntry->pNext;
-				}
-				else
-				{
-					pPrevEntry->pNext = pEntry->pNext;
-				}
-				break;
-			}
-
-			pPrevEntry = pProbeEntry;
-			pProbeEntry = pProbeEntry->pNext;
-		} while (pProbeEntry);
-
-		NdisZeroMemory(pEntry, sizeof(MEASURE_REQ_ENTRY));
-		pTab->Size--;
-
-		RTMP_SEM_UNLOCK(&pAd->CommonCfg.MeasureReqTabLock);
-	}
-
-	return;
-}
-
-VOID TpcReqTabInit(
-	IN PRTMP_ADAPTER pAd)
-{
-	NdisAllocateSpinLock(&pAd->CommonCfg.TpcReqTabLock);
-
-	pAd->CommonCfg.pTpcReqTab = kmalloc(sizeof(TPC_REQ_TAB), GFP_ATOMIC);
-	if (pAd->CommonCfg.pTpcReqTab)
-		NdisZeroMemory(pAd->CommonCfg.pTpcReqTab, sizeof(TPC_REQ_TAB));
-	else
-		DBGPRINT(RT_DEBUG_ERROR, ("%s Fail to alloc memory for pAd->CommonCfg.pTpcReqTab.\n", __FUNCTION__));
-
-	return;
-}
-
-VOID TpcReqTabExit(
-	IN PRTMP_ADAPTER pAd)
-{
-	NdisFreeSpinLock(pAd->CommonCfg.TpcReqTabLock);
-
-	if (pAd->CommonCfg.pTpcReqTab)
-		kfree(pAd->CommonCfg.pTpcReqTab);
-	pAd->CommonCfg.pTpcReqTab = NULL;
-
-	return;
-}
-
-static PTPC_REQ_ENTRY TpcReqLookUp(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	UINT HashIdx;
-	PTPC_REQ_TAB pTab = pAd->CommonCfg.pTpcReqTab;
-	PTPC_REQ_ENTRY pEntry = NULL;
-	PTPC_REQ_ENTRY pPrevEntry = NULL;
-
-	if (pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab doesn't exist.\n", __FUNCTION__));
-		return NULL;
-	}
-
-	RTMP_SEM_LOCK(&pAd->CommonCfg.TpcReqTabLock);
-
-	HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(DialogToken);
-	pEntry = pTab->Hash[HashIdx];
-
-	while (pEntry)
-	{
-		if (pEntry->DialogToken == DialogToken)
-			break;
-		else
-		{
-			pPrevEntry = pEntry;
-			pEntry = pEntry->pNext;
-		}
-	}
-
-	RTMP_SEM_UNLOCK(&pAd->CommonCfg.TpcReqTabLock);
-
-	return pEntry;
-}
-
-
-static PTPC_REQ_ENTRY TpcReqInsert(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	INT i;
-	ULONG HashIdx;
-	PTPC_REQ_TAB pTab = pAd->CommonCfg.pTpcReqTab;
-	PTPC_REQ_ENTRY pEntry = NULL, pCurrEntry;
-	ULONG Now;
-
-	if(pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab doesn't exist.\n", __FUNCTION__));
-		return NULL;
-	}
-
-	pEntry = TpcReqLookUp(pAd, DialogToken);
-	if (pEntry == NULL)
-	{
-		RTMP_SEM_LOCK(&pAd->CommonCfg.TpcReqTabLock);
-		for (i = 0; i < MAX_TPC_REQ_TAB_SIZE; i++)
-		{
-			NdisGetSystemUpTime(&Now);
-			pEntry = &pTab->Content[i];
-
-			if ((pEntry->Valid == TRUE)
-				&& RTMP_TIME_AFTER((unsigned long)Now, (unsigned long)(pEntry->lastTime + TPC_REQ_AGE_OUT)))
-			{
-				PTPC_REQ_ENTRY pPrevEntry = NULL;
-				ULONG HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
-				PTPC_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
-
-				// update Hash list
-				do
-				{
-					if (pProbeEntry == pEntry)
-					{
-						if (pPrevEntry == NULL)
-						{
-							pTab->Hash[HashIdx] = pEntry->pNext;
-						}
-						else
-						{
-							pPrevEntry->pNext = pEntry->pNext;
-						}
-						break;
-					}
-
-					pPrevEntry = pProbeEntry;
-					pProbeEntry = pProbeEntry->pNext;
-				} while (pProbeEntry);
-
-				NdisZeroMemory(pEntry, sizeof(TPC_REQ_ENTRY));
-				pTab->Size--;
-
-				break;
-			}
-
-			if (pEntry->Valid == FALSE)
-				break;
-		}
-
-		if (i < MAX_TPC_REQ_TAB_SIZE)
-		{
-			NdisGetSystemUpTime(&Now);
-			pEntry->lastTime = Now;
-			pEntry->Valid = TRUE;
-			pEntry->DialogToken = DialogToken;
-			pTab->Size++;
-		}
-		else
-		{
-			pEntry = NULL;
-			DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab tab full.\n", __FUNCTION__));
-		}
-
-		// add this Neighbor entry into HASH table
-		if (pEntry)
-		{
-			HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(DialogToken);
-			if (pTab->Hash[HashIdx] == NULL)
-			{
-				pTab->Hash[HashIdx] = pEntry;
-			}
-			else
-			{
-				pCurrEntry = pTab->Hash[HashIdx];
-				while (pCurrEntry->pNext != NULL)
-					pCurrEntry = pCurrEntry->pNext;
-				pCurrEntry->pNext = pEntry;
-			}
-		}
-
-		RTMP_SEM_UNLOCK(&pAd->CommonCfg.TpcReqTabLock);
-	}
-
-	return pEntry;
-}
-
-static VOID TpcReqDelete(
-	IN PRTMP_ADAPTER	pAd,
-	IN UINT8			DialogToken)
-{
-	PTPC_REQ_TAB pTab = pAd->CommonCfg.pTpcReqTab;
-	PTPC_REQ_ENTRY pEntry = NULL;
-
-	if(pTab == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: pTpcReqTab doesn't exist.\n", __FUNCTION__));
-		return;
-	}
-
-	// if empty, return
-	if (pTab->Size == 0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("pTpcReqTab empty.\n"));
-		return;
-	}
-
-	pEntry = TpcReqLookUp(pAd, DialogToken);
-	if (pEntry != NULL)
-	{
-		PTPC_REQ_ENTRY pPrevEntry = NULL;
-		ULONG HashIdx = TPC_DIALOGTOKEN_HASH_INDEX(pEntry->DialogToken);
-		PTPC_REQ_ENTRY pProbeEntry = pTab->Hash[HashIdx];
-
-		RTMP_SEM_LOCK(&pAd->CommonCfg.TpcReqTabLock);
-		// update Hash list
-		do
-		{
-			if (pProbeEntry == pEntry)
-			{
-				if (pPrevEntry == NULL)
-				{
-					pTab->Hash[HashIdx] = pEntry->pNext;
-				}
-				else
-				{
-					pPrevEntry->pNext = pEntry->pNext;
-				}
-				break;
-			}
-
-			pPrevEntry = pProbeEntry;
-			pProbeEntry = pProbeEntry->pNext;
-		} while (pProbeEntry);
-
-		NdisZeroMemory(pEntry, sizeof(TPC_REQ_ENTRY));
-		pTab->Size--;
-
-		RTMP_SEM_UNLOCK(&pAd->CommonCfg.TpcReqTabLock);
-	}
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Get Current TimeS tamp.
-
-	Parametrs:
-
-	Return	: Current Time Stamp.
-	==========================================================================
- */
-static UINT64 GetCurrentTimeStamp(
-	IN PRTMP_ADAPTER pAd)
-{
-	// get current time stamp.
-	return 0;
-}
-
-/*
-	==========================================================================
-	Description:
-		Get Current Transmit Power.
-
-	Parametrs:
-
-	Return	: Current Time Stamp.
-	==========================================================================
- */
-static UINT8 GetCurTxPwr(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT8 Wcid)
-{
-	return 16; /* 16 dBm */
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert Dialog Token into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. Dialog token.
-
-	Return	: None.
-	==========================================================================
- */
-static VOID InsertDialogToken(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN UINT8 DialogToken)
-{
-	ULONG TempLen;
-	MakeOutgoingFrame(pFrameBuf,	&TempLen,
-					1,				&DialogToken,
-					END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert TPC Request IE into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-
-	Return	: None.
-	==========================================================================
- */
- static VOID InsertTpcReqIE(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen)
-{
-	ULONG TempLen;
-	ULONG Len = 0;
-	UINT8 ElementID = IE_TPC_REQUEST;
-
-	MakeOutgoingFrame(pFrameBuf,					&TempLen,
-						1,							&ElementID,
-						1,							&Len,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert TPC Report IE into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. Transmit Power.
-		4. Link Margin.
-
-	Return	: None.
-	==========================================================================
- */
- static VOID InsertTpcReportIE(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN UINT8 TxPwr,
-	IN UINT8 LinkMargin)
-{
-	ULONG TempLen;
-	ULONG Len = sizeof(TPC_REPORT_INFO);
-	UINT8 ElementID = IE_TPC_REPORT;
-	TPC_REPORT_INFO TpcReportIE;
-
-	TpcReportIE.TxPwr = TxPwr;
-	TpcReportIE.LinkMargin = LinkMargin;
-
-	MakeOutgoingFrame(pFrameBuf,					&TempLen,
-						1,							&ElementID,
-						1,							&Len,
-						Len,						&TpcReportIE,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert Channel Switch Announcement IE into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. channel switch announcement mode.
-		4. new selected channel.
-		5. channel switch announcement count.
-
-	Return	: None.
-	==========================================================================
- */
-static VOID InsertChSwAnnIE(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN UINT8 ChSwMode,
-	IN UINT8 NewChannel,
-	IN UINT8 ChSwCnt)
-{
-	ULONG TempLen;
-	ULONG Len = sizeof(CH_SW_ANN_INFO);
-	UINT8 ElementID = IE_CHANNEL_SWITCH_ANNOUNCEMENT;
-	CH_SW_ANN_INFO ChSwAnnIE;
-
-	ChSwAnnIE.ChSwMode = ChSwMode;
-	ChSwAnnIE.Channel = NewChannel;
-	ChSwAnnIE.ChSwCnt = ChSwCnt;
-
-	MakeOutgoingFrame(pFrameBuf,				&TempLen,
-						1,						&ElementID,
-						1,						&Len,
-						Len,					&ChSwAnnIE,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert Measure Request IE into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. Measure Token.
-		4. Measure Request Mode.
-		5. Measure Request Type.
-		6. Measure Channel.
-		7. Measure Start time.
-		8. Measure Duration.
-
-
-	Return	: None.
-	==========================================================================
- */
-static VOID InsertMeasureReqIE(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN PMEASURE_REQ_INFO pMeasureReqIE)
-{
-	ULONG TempLen;
-	UINT8 Len = sizeof(MEASURE_REQ_INFO);
-	UINT8 ElementID = IE_MEASUREMENT_REQUEST;
-
-	MakeOutgoingFrame(pFrameBuf,					&TempLen,
-						1,							&ElementID,
-						1,							&Len,
-						Len,						pMeasureReqIE,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Insert Measure Report IE into frame.
-
-	Parametrs:
-		1. frame buffer pointer.
-		2. frame length.
-		3. Measure Token.
-		4. Measure Request Mode.
-		5. Measure Request Type.
-		6. Length of Report Infomation
-		7. Pointer of Report Infomation Buffer.
-
-	Return	: None.
-	==========================================================================
- */
-static VOID InsertMeasureReportIE(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN PMEASURE_REPORT_INFO pMeasureReportIE,
-	IN UINT8 ReportLnfoLen,
-	IN PUINT8 pReportInfo)
-{
-	ULONG TempLen;
-	ULONG Len;
-	UINT8 ElementID = IE_MEASUREMENT_REPORT;
-
-	Len = sizeof(MEASURE_REPORT_INFO) + ReportLnfoLen;
-
-	MakeOutgoingFrame(pFrameBuf,					&TempLen,
-						1,							&ElementID,
-						1,							&Len,
-						Len,						pMeasureReportIE,
-						END_OF_ARGS);
-
-	*pFrameLen = *pFrameLen + TempLen;
-
-	if ((ReportLnfoLen > 0) && (pReportInfo != NULL))
-	{
-		MakeOutgoingFrame(pFrameBuf + *pFrameLen,		&TempLen,
-							ReportLnfoLen,				pReportInfo,
-							END_OF_ARGS);
-
-		*pFrameLen = *pFrameLen + TempLen;
-	}
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Prepare Measurement request action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueMeasurementReq(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 MeasureToken,
-	IN UINT8 MeasureReqMode,
-	IN UINT8 MeasureReqType,
-	IN UINT8 MeasureCh,
-	IN UINT16 MeasureDuration)
-{
-	PUCHAR pOutBuffer = NULL;
-	NDIS_STATUS NStatus;
-	ULONG FrameLen;
-	HEADER_802_11 ActHdr;
-	MEASURE_REQ_INFO MeasureReqIE;
-	UINT8 RmReqDailogToken = RandomByte(pAd);
-	UINT64 MeasureStartTime = GetCurrentTimeStamp(pAd);
-
-	// build action frame header.
-	MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
-						pAd->CurrentAddress);
-
-	NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __FUNCTION__));
-		return;
-	}
-	NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
-	FrameLen = sizeof(HEADER_802_11);
-
-	InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_MRQ);
-
-	// fill Dialog Token
-	InsertDialogToken(pAd, (pOutBuffer + FrameLen), &FrameLen, MeasureToken);
-
-	// prepare Measurement IE.
-	NdisZeroMemory(&MeasureReqIE, sizeof(MEASURE_REQ_INFO));
-	MeasureReqIE.Token = RmReqDailogToken;
-	MeasureReqIE.ReqMode.word = MeasureReqMode;
-	MeasureReqIE.ReqType = MeasureReqType;
-	MeasureReqIE.MeasureReq.ChNum = MeasureCh;
-	MeasureReqIE.MeasureReq.MeasureStartTime = cpu2le64(MeasureStartTime);
-	MeasureReqIE.MeasureReq.MeasureDuration = cpu2le16(MeasureDuration);
-	InsertMeasureReqIE(pAd, (pOutBuffer + FrameLen), &FrameLen, &MeasureReqIE);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Prepare Measurement report action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueMeasurementRep(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 DialogToken,
-	IN UINT8 MeasureToken,
-	IN UINT8 MeasureReqMode,
-	IN UINT8 MeasureReqType,
-	IN UINT8 ReportInfoLen,
-	IN PUINT8 pReportInfo)
-{
-	PUCHAR pOutBuffer = NULL;
-	NDIS_STATUS NStatus;
-	ULONG FrameLen;
-	HEADER_802_11 ActHdr;
-	MEASURE_REPORT_INFO MeasureRepIE;
-
-	// build action frame header.
-	MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
-						pAd->CurrentAddress);
-
-	NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __FUNCTION__));
-		return;
-	}
-	NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
-	FrameLen = sizeof(HEADER_802_11);
-
-	InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_MRP);
-
-	// fill Dialog Token
-	InsertDialogToken(pAd, (pOutBuffer + FrameLen), &FrameLen, DialogToken);
-
-	// prepare Measurement IE.
-	NdisZeroMemory(&MeasureRepIE, sizeof(MEASURE_REPORT_INFO));
-	MeasureRepIE.Token = MeasureToken;
-	MeasureRepIE.ReportMode.word = MeasureReqMode;
-	MeasureRepIE.ReportType = MeasureReqType;
-	InsertMeasureReportIE(pAd, (pOutBuffer + FrameLen), &FrameLen, &MeasureRepIE, ReportInfoLen, pReportInfo);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Prepare TPC Request action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueTPCReq(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UCHAR DialogToken)
-{
-	PUCHAR pOutBuffer = NULL;
-	NDIS_STATUS NStatus;
-	ULONG FrameLen;
-
-	HEADER_802_11 ActHdr;
-
-	// build action frame header.
-	MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
-						pAd->CurrentAddress);
-
-	NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __FUNCTION__));
-		return;
-	}
-	NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
-	FrameLen = sizeof(HEADER_802_11);
-
-	InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_TPCRQ);
-
-	// fill Dialog Token
-	InsertDialogToken(pAd, (pOutBuffer + FrameLen), &FrameLen, DialogToken);
-
-	// Insert TPC Request IE.
-	InsertTpcReqIE(pAd, (pOutBuffer + FrameLen), &FrameLen);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Prepare TPC Report action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueTPCRep(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 DialogToken,
-	IN UINT8 TxPwr,
-	IN UINT8 LinkMargin)
-{
-	PUCHAR pOutBuffer = NULL;
-	NDIS_STATUS NStatus;
-	ULONG FrameLen;
-
-	HEADER_802_11 ActHdr;
-
-	// build action frame header.
-	MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
-						pAd->CurrentAddress);
-
-	NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __FUNCTION__));
-		return;
-	}
-	NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
-	FrameLen = sizeof(HEADER_802_11);
-
-	InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_TPCRP);
-
-	// fill Dialog Token
-	InsertDialogToken(pAd, (pOutBuffer + FrameLen), &FrameLen, DialogToken);
-
-	// Insert TPC Request IE.
-	InsertTpcReportIE(pAd, (pOutBuffer + FrameLen), &FrameLen, TxPwr, LinkMargin);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Prepare Channel Switch Announcement action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-		2. Channel switch announcement mode.
-		2. a New selected channel.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueChSwAnn(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 ChSwMode,
-	IN UINT8 NewCh)
-{
-	PUCHAR pOutBuffer = NULL;
-	NDIS_STATUS NStatus;
-	ULONG FrameLen;
-
-	HEADER_802_11 ActHdr;
-
-	// build action frame header.
-	MgtMacHeaderInit(pAd, &ActHdr, SUBTYPE_ACTION, 0, pDA,
-						pAd->CurrentAddress);
-
-	NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-	if(NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("%s() allocate memory failed \n", __FUNCTION__));
-		return;
-	}
-	NdisMoveMemory(pOutBuffer, (PCHAR)&ActHdr, sizeof(HEADER_802_11));
-	FrameLen = sizeof(HEADER_802_11);
-
-	InsertActField(pAd, (pOutBuffer + FrameLen), &FrameLen, CATEGORY_SPECTRUM, SPEC_CHANNEL_SWITCH);
-
-	InsertChSwAnnIE(pAd, (pOutBuffer + FrameLen), &FrameLen, ChSwMode, NewCh, 0);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	return;
-}
-
-static BOOLEAN DfsRequirementCheck(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT8 Channel)
-{
-	BOOLEAN Result = FALSE;
-	INT i;
-
-	do
-	{
-		// check DFS procedure is running.
-		// make sure DFS procedure won't start twice.
-		if (pAd->CommonCfg.RadarDetect.RDMode != RD_NORMAL_MODE)
-		{
-			Result = FALSE;
-			break;
-		}
-
-		// check the new channel carried from Channel Switch Announcemnet is valid.
-		for (i=0; i<pAd->ChannelListNum; i++)
-		{
-			if ((Channel == pAd->ChannelList[i].Channel)
-				&&(pAd->ChannelList[i].RemainingTimeForUse == 0))
-			{
-				// found radar signal in the channel. the channel can't use at least for 30 minutes.
-				pAd->ChannelList[i].RemainingTimeForUse = 1800;//30 min = 1800 sec
-				Result = TRUE;
-				break;
-			}
-		}
-	} while(FALSE);
-
-	return Result;
-}
-
-VOID NotifyChSwAnnToPeerAPs(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pRA,
-	IN PUCHAR pTA,
-	IN UINT8 ChSwMode,
-	IN UINT8 Channel)
-{
-#ifdef WDS_SUPPORT
-	if (!((pRA[0] & 0xff) == 0xff)) // is pRA a broadcase address.
-	{
-		INT i;
-		// info neighbor APs that Radar signal found throgh WDS link.
-		for (i = 0; i < MAX_WDS_ENTRY; i++)
-		{
-			if (ValidWdsEntry(pAd, i))
-			{
-				PUCHAR pDA = pAd->WdsTab.WdsEntry[i].PeerWdsAddr;
-
-				// DA equal to SA. have no necessary orignal AP which found Radar signal.
-				if (MAC_ADDR_EQUAL(pTA, pDA))
-					continue;
-
-				// send Channel Switch Action frame to info Neighbro APs.
-				EnqueueChSwAnn(pAd, pDA, ChSwMode, Channel);
-			}
-		}
-	}
-#endif // WDS_SUPPORT //
-}
-
-static VOID StartDFSProcedure(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR Channel,
-	IN UINT8 ChSwMode)
-{
-	// start DFS procedure
-	pAd->CommonCfg.Channel = Channel;
-#ifdef DOT11_N_SUPPORT
-	N_ChannelCheck(pAd);
-#endif // DOT11_N_SUPPORT //
-	pAd->CommonCfg.RadarDetect.RDMode = RD_SWITCHING_MODE;
-	pAd->CommonCfg.RadarDetect.CSCount = 0;
-}
-
-/*
-	==========================================================================
-	Description:
-		Channel Switch Announcement action frame sanity check.
-
-	Parametrs:
-		1. MLME message containing the received frame
-		2. message length.
-		3. Channel switch announcement infomation buffer.
-
-
-	Return	: None.
-	==========================================================================
- */
-
-/*
-  Channel Switch Announcement IE.
-  +----+-----+-----------+------------+-----------+
-  | ID | Len |Ch Sw Mode | New Ch Num | Ch Sw Cnt |
-  +----+-----+-----------+------------+-----------+
-    1    1        1           1            1
-*/
-static BOOLEAN PeerChSwAnnSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *pMsg,
-	IN ULONG MsgLen,
-	OUT PCH_SW_ANN_INFO pChSwAnnInfo)
-{
-	PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
-	PUCHAR pFramePtr = Fr->Octet;
-	BOOLEAN result = FALSE;
-	PEID_STRUCT eid_ptr;
-
-	// skip 802.11 header.
-	MsgLen -= sizeof(HEADER_802_11);
-
-	// skip category and action code.
-	pFramePtr += 2;
-	MsgLen -= 2;
-
-	if (pChSwAnnInfo == NULL)
-		return result;
-
-	eid_ptr = (PEID_STRUCT)pFramePtr;
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_CHANNEL_SWITCH_ANNOUNCEMENT:
-				NdisMoveMemory(&pChSwAnnInfo->ChSwMode, eid_ptr->Octet, 1);
-				NdisMoveMemory(&pChSwAnnInfo->Channel, eid_ptr->Octet + 1, 1);
-				NdisMoveMemory(&pChSwAnnInfo->ChSwCnt, eid_ptr->Octet + 2, 1);
-
-				result = TRUE;
-                break;
-
-			default:
-				break;
-		}
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-	return result;
-}
-
-/*
-	==========================================================================
-	Description:
-		Measurement request action frame sanity check.
-
-	Parametrs:
-		1. MLME message containing the received frame
-		2. message length.
-		3. Measurement request infomation buffer.
-
-	Return	: None.
-	==========================================================================
- */
-static BOOLEAN PeerMeasureReqSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *pMsg,
-	IN ULONG MsgLen,
-	OUT PUINT8 pDialogToken,
-	OUT PMEASURE_REQ_INFO pMeasureReqInfo)
-{
-	PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
-	PUCHAR pFramePtr = Fr->Octet;
-	BOOLEAN result = FALSE;
-	PEID_STRUCT eid_ptr;
-	PUCHAR ptr;
-	UINT64 MeasureStartTime;
-	UINT16 MeasureDuration;
-
-	// skip 802.11 header.
-	MsgLen -= sizeof(HEADER_802_11);
-
-	// skip category and action code.
-	pFramePtr += 2;
-	MsgLen -= 2;
-
-	if (pMeasureReqInfo == NULL)
-		return result;
-
-	NdisMoveMemory(pDialogToken, pFramePtr, 1);
-	pFramePtr += 1;
-	MsgLen -= 1;
-
-	eid_ptr = (PEID_STRUCT)pFramePtr;
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_MEASUREMENT_REQUEST:
-				NdisMoveMemory(&pMeasureReqInfo->Token, eid_ptr->Octet, 1);
-				NdisMoveMemory(&pMeasureReqInfo->ReqMode.word, eid_ptr->Octet + 1, 1);
-				NdisMoveMemory(&pMeasureReqInfo->ReqType, eid_ptr->Octet + 2, 1);
-				ptr = eid_ptr->Octet + 3;
-				NdisMoveMemory(&pMeasureReqInfo->MeasureReq.ChNum, ptr, 1);
-				NdisMoveMemory(&MeasureStartTime, ptr + 1, 8);
-				pMeasureReqInfo->MeasureReq.MeasureStartTime = SWAP64(MeasureStartTime);
-				NdisMoveMemory(&MeasureDuration, ptr + 9, 2);
-				pMeasureReqInfo->MeasureReq.MeasureDuration = SWAP16(MeasureDuration);
-
-				result = TRUE;
-				break;
-
-			default:
-				break;
-		}
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-	return result;
-}
-
-/*
-	==========================================================================
-	Description:
-		Measurement report action frame sanity check.
-
-	Parametrs:
-		1. MLME message containing the received frame
-		2. message length.
-		3. Measurement report infomation buffer.
-		4. basic report infomation buffer.
-
-	Return	: None.
-	==========================================================================
- */
-
-/*
-  Measurement Report IE.
-  +----+-----+-------+-------------+--------------+----------------+
-  | ID | Len | Token | Report Mode | Measure Type | Measure Report |
-  +----+-----+-------+-------------+--------------+----------------+
-    1     1      1          1             1            variable
-
-  Basic Report.
-  +--------+------------+----------+-----+
-  | Ch Num | Start Time | Duration | Map |
-  +--------+------------+----------+-----+
-      1          8           2        1
-
-  Map Field Bit Format.
-  +-----+---------------+---------------------+-------+------------+----------+
-  | Bss | OFDM Preamble | Unidentified signal | Radar | Unmeasured | Reserved |
-  +-----+---------------+---------------------+-------+------------+----------+
-     0          1                  2              3         4          5-7
-*/
-static BOOLEAN PeerMeasureReportSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *pMsg,
-	IN ULONG MsgLen,
-	OUT PUINT8 pDialogToken,
-	OUT PMEASURE_REPORT_INFO pMeasureReportInfo,
-	OUT PUINT8 pReportBuf)
-{
-	PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
-	PUCHAR pFramePtr = Fr->Octet;
-	BOOLEAN result = FALSE;
-	PEID_STRUCT eid_ptr;
-	PUCHAR ptr;
-
-	// skip 802.11 header.
-	MsgLen -= sizeof(HEADER_802_11);
-
-	// skip category and action code.
-	pFramePtr += 2;
-	MsgLen -= 2;
-
-	if (pMeasureReportInfo == NULL)
-		return result;
-
-	NdisMoveMemory(pDialogToken, pFramePtr, 1);
-	pFramePtr += 1;
-	MsgLen -= 1;
-
-	eid_ptr = (PEID_STRUCT)pFramePtr;
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_MEASUREMENT_REPORT:
-				NdisMoveMemory(&pMeasureReportInfo->Token, eid_ptr->Octet, 1);
-				NdisMoveMemory(&pMeasureReportInfo->ReportMode, eid_ptr->Octet + 1, 1);
-				NdisMoveMemory(&pMeasureReportInfo->ReportType, eid_ptr->Octet + 2, 1);
-				if (pMeasureReportInfo->ReportType == RM_BASIC)
-				{
-					PMEASURE_BASIC_REPORT pReport = (PMEASURE_BASIC_REPORT)pReportBuf;
-					ptr = eid_ptr->Octet + 3;
-					NdisMoveMemory(&pReport->ChNum, ptr, 1);
-					NdisMoveMemory(&pReport->MeasureStartTime, ptr + 1, 8);
-					NdisMoveMemory(&pReport->MeasureDuration, ptr + 9, 2);
-					NdisMoveMemory(&pReport->Map, ptr + 11, 1);
-
-				}
-				else if (pMeasureReportInfo->ReportType == RM_CCA)
-				{
-					PMEASURE_CCA_REPORT pReport = (PMEASURE_CCA_REPORT)pReportBuf;
-					ptr = eid_ptr->Octet + 3;
-					NdisMoveMemory(&pReport->ChNum, ptr, 1);
-					NdisMoveMemory(&pReport->MeasureStartTime, ptr + 1, 8);
-					NdisMoveMemory(&pReport->MeasureDuration, ptr + 9, 2);
-					NdisMoveMemory(&pReport->CCA_Busy_Fraction, ptr + 11, 1);
-
-				}
-				else if (pMeasureReportInfo->ReportType == RM_RPI_HISTOGRAM)
-				{
-					PMEASURE_RPI_REPORT pReport = (PMEASURE_RPI_REPORT)pReportBuf;
-					ptr = eid_ptr->Octet + 3;
-					NdisMoveMemory(&pReport->ChNum, ptr, 1);
-					NdisMoveMemory(&pReport->MeasureStartTime, ptr + 1, 8);
-					NdisMoveMemory(&pReport->MeasureDuration, ptr + 9, 2);
-					NdisMoveMemory(&pReport->RPI_Density, ptr + 11, 8);
-				}
-				result = TRUE;
-                break;
-
-			default:
-				break;
-		}
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-	return result;
-}
-
-/*
-	==========================================================================
-	Description:
-		TPC Request action frame sanity check.
-
-	Parametrs:
-		1. MLME message containing the received frame
-		2. message length.
-		3. Dialog Token.
-
-	Return	: None.
-	==========================================================================
- */
-static BOOLEAN PeerTpcReqSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *pMsg,
-	IN ULONG MsgLen,
-	OUT PUINT8 pDialogToken)
-{
-	PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
-	PUCHAR pFramePtr = Fr->Octet;
-	BOOLEAN result = FALSE;
-	PEID_STRUCT eid_ptr;
-
-	MsgLen -= sizeof(HEADER_802_11);
-
-	// skip category and action code.
-	pFramePtr += 2;
-	MsgLen -= 2;
-
-	if (pDialogToken == NULL)
-		return result;
-
-	NdisMoveMemory(pDialogToken, pFramePtr, 1);
-	pFramePtr += 1;
-	MsgLen -= 1;
-
-	eid_ptr = (PEID_STRUCT)pFramePtr;
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_TPC_REQUEST:
-				result = TRUE;
-                break;
-
-			default:
-				break;
-		}
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-	return result;
-}
-
-/*
-	==========================================================================
-	Description:
-		TPC Report action frame sanity check.
-
-	Parametrs:
-		1. MLME message containing the received frame
-		2. message length.
-		3. Dialog Token.
-		4. TPC Report IE.
-
-	Return	: None.
-	==========================================================================
- */
-static BOOLEAN PeerTpcRepSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN VOID *pMsg,
-	IN ULONG MsgLen,
-	OUT PUINT8 pDialogToken,
-	OUT PTPC_REPORT_INFO pTpcRepInfo)
-{
-	PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
-	PUCHAR pFramePtr = Fr->Octet;
-	BOOLEAN result = FALSE;
-	PEID_STRUCT eid_ptr;
-
-	MsgLen -= sizeof(HEADER_802_11);
-
-	// skip category and action code.
-	pFramePtr += 2;
-	MsgLen -= 2;
-
-	if (pDialogToken == NULL)
-		return result;
-
-	NdisMoveMemory(pDialogToken, pFramePtr, 1);
-	pFramePtr += 1;
-	MsgLen -= 1;
-
-	eid_ptr = (PEID_STRUCT)pFramePtr;
-	while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
-	{
-		switch(eid_ptr->Eid)
-		{
-			case IE_TPC_REPORT:
-				NdisMoveMemory(&pTpcRepInfo->TxPwr, eid_ptr->Octet, 1);
-				NdisMoveMemory(&pTpcRepInfo->LinkMargin, eid_ptr->Octet + 1, 1);
-				result = TRUE;
-                break;
-
-			default:
-				break;
-		}
-		eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
-	}
-
-	return result;
-}
-
-/*
-	==========================================================================
-	Description:
-		Channel Switch Announcement action frame handler.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-static VOID PeerChSwAnnAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	CH_SW_ANN_INFO ChSwAnnInfo;
-	PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
-#ifdef CONFIG_STA_SUPPORT
-	UCHAR index = 0, Channel = 0, NewChannel = 0;
-	ULONG Bssidx = 0;
-#endif // CONFIG_STA_SUPPORT //
-
-	NdisZeroMemory(&ChSwAnnInfo, sizeof(CH_SW_ANN_INFO));
-	if (! PeerChSwAnnSanity(pAd, Elem->Msg, Elem->MsgLen, &ChSwAnnInfo))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("Invalid Channel Switch Action Frame.\n"));
-		return;
-	}
-
-
-#ifdef CONFIG_STA_SUPPORT
-	if (pAd->OpMode == OPMODE_STA)
-	{
-		Bssidx = BssTableSearch(&pAd->ScanTab, pFr->Hdr.Addr3, pAd->CommonCfg.Channel);
-		if (Bssidx == BSS_NOT_FOUND)
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("PeerChSwAnnAction - Bssidx is not found\n"));
-			return;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("\n****Bssidx is %d, Channel = %d\n", index, pAd->ScanTab.BssEntry[Bssidx].Channel));
-		hex_dump("SSID",pAd->ScanTab.BssEntry[Bssidx].Bssid ,6);
-
-		Channel = pAd->CommonCfg.Channel;
-		NewChannel = ChSwAnnInfo.Channel;
-
-		if ((pAd->CommonCfg.bIEEE80211H == 1) && (NewChannel != 0) && (Channel != NewChannel))
-		{
-			// Switching to channel 1 can prevent from rescanning the current channel immediately (by auto reconnection).
-			// In addition, clear the MLME queue and the scan table to discard the RX packets and previous scanning results.
-			AsicSwitchChannel(pAd, 1, FALSE);
-			AsicLockChannel(pAd, 1);
-		    LinkDown(pAd, FALSE);
-			MlmeQueueInit(&pAd->Mlme.Queue);
-			BssTableInit(&pAd->ScanTab);
-		    RTMPusecDelay(1000000);		// use delay to prevent STA do reassoc
-
-			// channel sanity check
-			for (index = 0 ; index < pAd->ChannelListNum; index++)
-			{
-				if (pAd->ChannelList[index].Channel == NewChannel)
-				{
-					pAd->ScanTab.BssEntry[Bssidx].Channel = NewChannel;
-					pAd->CommonCfg.Channel = NewChannel;
-					AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-					AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-					DBGPRINT(RT_DEBUG_TRACE, ("&&&&&&&&&&&&&&&&PeerChSwAnnAction - STA receive channel switch announcement IE (New Channel =%d)\n", NewChannel));
-					break;
-				}
-			}
-
-			if (index >= pAd->ChannelListNum)
-			{
-				DBGPRINT_ERR(("&&&&&&&&&&&&&&&&&&&&&&&&&&PeerChSwAnnAction(can not find New Channel=%d in ChannelList[%d]\n", pAd->CommonCfg.Channel, pAd->ChannelListNum));
-			}
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	return;
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Measurement Request action frame handler.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-static VOID PeerMeasureReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
-	UINT8 DialogToken;
-	MEASURE_REQ_INFO MeasureReqInfo;
-	MEASURE_REPORT_MODE ReportMode;
-
-	if(PeerMeasureReqSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken, &MeasureReqInfo))
-	{
-		ReportMode.word = 0;
-		ReportMode.field.Incapable = 1;
-		EnqueueMeasurementRep(pAd, pFr->Hdr.Addr2, DialogToken, MeasureReqInfo.Token, ReportMode.word, MeasureReqInfo.ReqType, 0, NULL);
-	}
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Measurement Report action frame handler.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-static VOID PeerMeasureReportAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	MEASURE_REPORT_INFO MeasureReportInfo;
-	PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
-	UINT8 DialogToken;
-	PUINT8 pMeasureReportInfo;
-
-//	if (pAd->CommonCfg.bIEEE80211H != TRUE)
-//		return;
-
-	if ((pMeasureReportInfo = kmalloc(sizeof(MEASURE_RPI_REPORT), GFP_ATOMIC)) == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s unable to alloc memory for measure report buffer (size=%d).\n", __FUNCTION__, sizeof(MEASURE_RPI_REPORT)));
-		return;
-	}
-
-	NdisZeroMemory(&MeasureReportInfo, sizeof(MEASURE_REPORT_INFO));
-	NdisZeroMemory(pMeasureReportInfo, sizeof(MEASURE_RPI_REPORT));
-	if (PeerMeasureReportSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken, &MeasureReportInfo, pMeasureReportInfo))
-	{
-		do {
-			PMEASURE_REQ_ENTRY pEntry = NULL;
-
-			// Not a autonomous measure report.
-			// check the dialog token field. drop it if the dialog token doesn't match.
-			if ((DialogToken != 0)
-				&& ((pEntry = MeasureReqLookUp(pAd, DialogToken)) == NULL))
-				break;
-
-			if (pEntry != NULL)
-				MeasureReqDelete(pAd, pEntry->DialogToken);
-
-			if (MeasureReportInfo.ReportType == RM_BASIC)
-			{
-				PMEASURE_BASIC_REPORT pBasicReport = (PMEASURE_BASIC_REPORT)pMeasureReportInfo;
-				if ((pBasicReport->Map.field.Radar)
-					&& (DfsRequirementCheck(pAd, pBasicReport->ChNum) == TRUE))
-				{
-					NotifyChSwAnnToPeerAPs(pAd, pFr->Hdr.Addr1, pFr->Hdr.Addr2, 1, pBasicReport->ChNum);
-					StartDFSProcedure(pAd, pBasicReport->ChNum, 1);
-				}
-			}
-		} while (FALSE);
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, ("Invalid Measurement Report Frame.\n"));
-
-	kfree(pMeasureReportInfo);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		TPC Request action frame handler.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-static VOID PeerTpcReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PFRAME_802_11 pFr = (PFRAME_802_11)Elem->Msg;
-	PUCHAR pFramePtr = pFr->Octet;
-	UINT8 DialogToken;
-	UINT8 TxPwr = GetCurTxPwr(pAd, Elem->Wcid);
-	UINT8 LinkMargin = 0;
-	CHAR RealRssi;
-
-	// link margin: Ratio of the received signal power to the minimum desired by the station (STA). The
-	//				STA may incorporate rate information and channel conditions, including interference, into its computation
-	//				of link margin.
-
-	RealRssi = RTMPMaxRssi(pAd, ConvertToRssi(pAd, Elem->Rssi0, RSSI_0),
-								ConvertToRssi(pAd, Elem->Rssi1, RSSI_1),
-								ConvertToRssi(pAd, Elem->Rssi2, RSSI_2));
-
-	// skip Category and action code.
-	pFramePtr += 2;
-
-	// Dialog token.
-	NdisMoveMemory(&DialogToken, pFramePtr, 1);
-
-	LinkMargin = (RealRssi / MIN_RCV_PWR);
-	if (PeerTpcReqSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken))
-		EnqueueTPCRep(pAd, pFr->Hdr.Addr2, DialogToken, TxPwr, LinkMargin);
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		TPC Report action frame handler.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-static VOID PeerTpcRepAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UINT8 DialogToken;
-	TPC_REPORT_INFO TpcRepInfo;
-	PTPC_REQ_ENTRY pEntry = NULL;
-
-	NdisZeroMemory(&TpcRepInfo, sizeof(TPC_REPORT_INFO));
-	if (PeerTpcRepSanity(pAd, Elem->Msg, Elem->MsgLen, &DialogToken, &TpcRepInfo))
-	{
-		if ((pEntry = TpcReqLookUp(pAd, DialogToken)) != NULL)
-		{
-			TpcReqDelete(pAd, pEntry->DialogToken);
-			DBGPRINT(RT_DEBUG_TRACE, ("%s: DialogToken=%x, TxPwr=%d, LinkMargin=%d\n",
-				__FUNCTION__, DialogToken, TpcRepInfo.TxPwr, TpcRepInfo.LinkMargin));
-		}
-	}
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-		Spectrun action frames Handler such as channel switch annoucement,
-		measurement report, measurement request actions frames.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-VOID PeerSpectrumAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-
-	UCHAR	Action = Elem->Msg[LENGTH_802_11+1];
-
-	if (pAd->CommonCfg.bIEEE80211H != TRUE)
-		return;
-
-	switch(Action)
-	{
-		case SPEC_MRQ:
-			// current rt2860 unable do such measure specified in Measurement Request.
-			// reject all measurement request.
-			PeerMeasureReqAction(pAd, Elem);
-			break;
-
-		case SPEC_MRP:
-			PeerMeasureReportAction(pAd, Elem);
-			break;
-
-		case SPEC_TPCRQ:
-			PeerTpcReqAction(pAd, Elem);
-			break;
-
-		case SPEC_TPCRP:
-			PeerTpcRepAction(pAd, Elem);
-			break;
-
-		case SPEC_CHANNEL_SWITCH:
-{
-#ifdef DOT11N_DRAFT3
-				SEC_CHA_OFFSET_IE	Secondary;
-				CHA_SWITCH_ANNOUNCE_IE	ChannelSwitch;
-
-				// 802.11h only has Channel Switch Announcement IE.
-				RTMPMoveMemory(&ChannelSwitch, &Elem->Msg[LENGTH_802_11+4], sizeof (CHA_SWITCH_ANNOUNCE_IE));
-
-				// 802.11n D3.03 adds secondary channel offset element in the end.
-				if (Elem->MsgLen ==  (LENGTH_802_11 + 2 + sizeof (CHA_SWITCH_ANNOUNCE_IE) + sizeof (SEC_CHA_OFFSET_IE)))
-				{
-					RTMPMoveMemory(&Secondary, &Elem->Msg[LENGTH_802_11+9], sizeof (SEC_CHA_OFFSET_IE));
-				}
-				else
-				{
-					Secondary.SecondaryChannelOffset = 0;
-				}
-
-				if ((Elem->Msg[LENGTH_802_11+2] == IE_CHANNEL_SWITCH_ANNOUNCEMENT) && (Elem->Msg[LENGTH_802_11+3] == 3))
-				{
-					ChannelSwitchAction(pAd, Elem->Wcid, ChannelSwitch.NewChannel, Secondary.SecondaryChannelOffset);
-				}
-#endif // DOT11N_DRAFT3 //
-}
-			PeerChSwAnnAction(pAd, Elem);
-			break;
-	}
-
-	return;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	Parametrs:
-
-	Return	: None.
-	==========================================================================
- */
-INT Set_MeasureReq_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT Aid = 1;
-	UINT ArgIdx;
-	PUCHAR thisChar;
-
-	MEASURE_REQ_MODE MeasureReqMode;
-	UINT8 MeasureReqToken = RandomByte(pAd);
-	UINT8 MeasureReqType = RM_BASIC;
-	UINT8 MeasureCh = 1;
-
-	ArgIdx = 1;
-	while ((thisChar = strsep((char **)&arg, "-")) != NULL)
-	{
-		switch(ArgIdx)
-		{
-			case 1:	// Aid.
-				Aid = simple_strtol(thisChar, 0, 16);
-				break;
-
-			case 2: // Measurement Request Type.
-				MeasureReqType = simple_strtol(thisChar, 0, 16);
-				if (MeasureReqType > 3)
-				{
-					DBGPRINT(RT_DEBUG_ERROR, ("%s: unknow MeasureReqType(%d)\n", __FUNCTION__, MeasureReqType));
-					return TRUE;
-				}
-				break;
-
-			case 3: // Measurement channel.
-				MeasureCh = simple_strtol(thisChar, 0, 16);
-				break;
-		}
-		ArgIdx++;
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s::Aid = %d, MeasureReqType=%d MeasureCh=%d\n", __FUNCTION__, Aid, MeasureReqType, MeasureCh));
-	if (!VALID_WCID(Aid))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: unknow sta of Aid(%d)\n", __FUNCTION__, Aid));
-		return TRUE;
-	}
-
-	MeasureReqMode.word = 0;
-	MeasureReqMode.field.Enable = 1;
-
-	MeasureReqInsert(pAd, MeasureReqToken);
-
-	EnqueueMeasurementReq(pAd, pAd->MacTab.Content[Aid].Addr,
-		MeasureReqToken, MeasureReqMode.word, MeasureReqType, MeasureCh, 2000);
-
-	return TRUE;
-}
-
-INT Set_TpcReq_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT Aid;
-
-	UINT8 TpcReqToken = RandomByte(pAd);
-
-	Aid = simple_strtol(arg, 0, 16);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("%s::Aid = %d\n", __FUNCTION__, Aid));
-	if (!VALID_WCID(Aid))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: unknow sta of Aid(%d)\n", __FUNCTION__, Aid));
-		return TRUE;
-	}
-
-	TpcReqInsert(pAd, TpcReqToken);
-
-	EnqueueTPCReq(pAd, pAd->MacTab.Content[Aid].Addr, TpcReqToken);
-
-	return TRUE;
-}
-
+#include "../../rt2870/common/spectrum.c"
diff --git a/drivers/staging/rt3070/dfs.h b/drivers/staging/rt3070/dfs.h
index 752a635..b9c92e3 100644
--- a/drivers/staging/rt3070/dfs.h
+++ b/drivers/staging/rt3070/dfs.h
@@ -1,100 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    dfs.h
-
-    Abstract:
-    Support DFS function.
-
-    Revision History:
-    Who       When            What
-    --------  ----------      ----------------------------------------------
-    Fonchi    03-12-2007      created
-*/
-
-#define RADAR_PULSE 1
-#define RADAR_WIDTH 2
-
-#define WIDTH_RD_IDLE 0
-#define WIDTH_RD_CHECK 1
-
-
-VOID BbpRadarDetectionStart(
-	IN PRTMP_ADAPTER pAd);
-
-VOID BbpRadarDetectionStop(
-	IN PRTMP_ADAPTER pAd);
-
-VOID RadarDetectionStart(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN CTS_Protect,
-	IN UINT8 CTSPeriod);
-
-VOID RadarDetectionStop(
-	IN PRTMP_ADAPTER	pAd);
-
-VOID RadarDetectPeriodic(
-	IN PRTMP_ADAPTER	pAd);
-
-
-BOOLEAN RadarChannelCheck(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			Ch);
-
-ULONG JapRadarType(
-	IN PRTMP_ADAPTER pAd);
-
-ULONG RTMPBbpReadRadarDuration(
-	IN PRTMP_ADAPTER	pAd);
-
-ULONG RTMPReadRadarDuration(
-	IN PRTMP_ADAPTER	pAd);
-
-VOID RTMPCleanRadarDuration(
-	IN PRTMP_ADAPTER	pAd);
-
-VOID RTMPPrepareRDCTSFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA,
-	IN	ULONG			Duration,
-	IN  UCHAR           RTSRate,
-	IN  ULONG           CTSBaseAddr,
-	IN  UCHAR			FrameGap);
-
-VOID RTMPPrepareRadarDetectParams(
-	IN PRTMP_ADAPTER	pAd);
-
-
-INT Set_ChMovingTime_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg);
-
-INT Set_LongPulseRadarTh_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg);
-
-
+#include "../rt2870/dfs.h"
diff --git a/drivers/staging/rt3070/leap.h b/drivers/staging/rt3070/leap.h
deleted file mode 100644
index 6818c1f..0000000
--- a/drivers/staging/rt3070/leap.h
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	leap.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-*/
-#ifndef __LEAP_H__
-#define __LEAP_H__
-
-// Messages for Associate state machine
-#define LEAP_MACHINE_BASE                   30
-
-#define LEAP_MSG_REQUEST_IDENTITY           31
-#define LEAP_MSG_REQUEST_LEAP               32
-#define LEAP_MSG_SUCCESS                    33
-#define LEAP_MSG_FAILED                     34
-#define LEAP_MSG_RESPONSE_LEAP              35
-#define LEAP_MSG_EAPOLKEY                   36
-#define LEAP_MSG_UNKNOWN                    37
-#define LEAP_MSG                            38
-//! assoc state-machine states
-#define LEAP_IDLE                           0
-#define LEAP_WAIT_IDENTITY_REQUEST          1
-#define LEAP_WAIT_CHANLLENGE_REQUEST        2
-#define LEAP_WAIT_SUCCESS                   3
-#define LEAP_WAIT_CHANLLENGE_RESPONSE       4
-#define LEAP_WAIT_EAPOLKEY                  5
-
-#define LEAP_REASON_INVALID_AUTH                    0x01
-#define LEAP_REASON_AUTH_TIMEOUT                    0x02
-#define LEAP_REASON_CHALLENGE_FROM_AP_FAILED        0x03
-#define LEAP_REASON_CHALLENGE_TO_AP_FAILED          0x04
-
-#define CISCO_AuthModeLEAP                          0x80
-#define CISCO_AuthModeLEAPNone                      0x00
-#define LEAP_AUTH_TIMEOUT                           30000
-#define LEAP_CHALLENGE_RESPONSE_LENGTH              24
-#define LEAP_CHALLENGE_REQUEST_LENGTH               8
-
-typedef struct _LEAP_EAPOL_HEADER_ {
-    UCHAR       Version;
-    UCHAR       Type;
-    UCHAR       Length[2];
-} LEAP_EAPOL_HEADER, *PLEAP_EAPOL_HEADER;
-
-typedef struct _LEAP_EAPOL_PACKET_ {
-    UCHAR       Code;
-    UCHAR       Identifier;
-    UCHAR       Length[2];
-    UCHAR       Type;
-} LEAP_EAPOL_PACKET, *PLEAP_EAPOL_PACKET;
-
-typedef struct _LEAP_EAP_CONTENTS_ {
-    UCHAR       Version;
-    UCHAR       Reserved;
-    UCHAR       Length;
-} LEAP_EAP_CONTENTS, *PLEAP_EAP_CONTENTS;
-
-/*** EAPOL key ***/
-typedef struct _EAPOL_KEY_HEADER_ {
-    UCHAR       Type;
-    UCHAR       Length[2];
-    UCHAR       Counter[8];
-    UCHAR       IV[16];
-    UCHAR       Index;
-    UCHAR       Signature[16];
-} EAPOL_KEY_HEADER, *PEAPOL_KEY_HEADER;
-
-BOOLEAN LeapMsgTypeSubst(
-    IN  UCHAR   EAPType,
-    OUT ULONG   *MsgType);
-
-VOID LeapMachinePerformAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN STATE_MACHINE    *S,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapMacHeaderInit(
-    IN  PRTMP_ADAPTER       pAd,
-    IN  OUT PHEADER_802_11  pHdr80211,
-    IN  UCHAR               wep,
-    IN  PUCHAR              pAddr3);
-
-VOID LeapStartAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapIdentityAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapPeerChallengeAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID HashPwd(
-    IN  PUCHAR  pwd,
-    IN  INT     pwdlen,
-    OUT PUCHAR  hash);
-
-VOID PeerChallengeResponse(
-    IN  PUCHAR  szChallenge,
-    IN  PUCHAR  smbPasswd,
-    OUT PUCHAR  szResponse);
-
-VOID ParityKey(
-    OUT PUCHAR  szOut,
-    IN  PUCHAR  szIn);
-
-VOID DesKey(
-    OUT ULONG   k[16][2],
-    IN  PUCHAR  key,
-    IN  INT     decrypt);
-
-VOID Des(
-    IN  ULONG   ks[16][2],
-    OUT UCHAR   block[8]);
-
-VOID DesEncrypt(
-    IN  PUCHAR  szClear,
-    IN  PUCHAR  szKey,
-    OUT PUCHAR  szOut);
-
-VOID LeapNetworkChallengeAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID LeapNetworkChallengeResponse(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID HashpwdHash(
-    IN  PUCHAR  hash,
-    IN  PUCHAR  hashhash);
-
-VOID ProcessSessionKey(
-    OUT PUCHAR  SessionKey,
-    IN  PUCHAR  hash2,
-    IN  PUCHAR  ChallengeToRadius,
-    IN  PUCHAR  ChallengeResponseFromRadius,
-    IN  PUCHAR  ChallengeFromRadius,
-    IN  PUCHAR  ChallengeResponseToRadius);
-
-VOID LeapEapolKeyAction(
-    IN PRTMP_ADAPTER    pAd,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID RogueApTableInit(
-    IN ROGUEAP_TABLE    *Tab);
-
-ULONG RogueApTableSearch(
-    IN ROGUEAP_TABLE    *Tab,
-    IN PUCHAR           pAddr);
-
-VOID RogueApEntrySet(
-    IN  PRTMP_ADAPTER   pAd,
-    OUT ROGUEAP_ENTRY   *pRogueAp,
-    IN PUCHAR           pAddr,
-    IN UCHAR            FaileCode);
-
-ULONG RogueApTableSetEntry(
-    IN  PRTMP_ADAPTER   pAd,
-    OUT ROGUEAP_TABLE  *Tab,
-    IN PUCHAR           pAddr,
-    IN UCHAR            FaileCode);
-
-VOID RogueApTableDeleteEntry(
-    IN OUT ROGUEAP_TABLE *Tab,
-    IN PUCHAR          pAddr);
-
-VOID LeapAuthTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-VOID LeapSendRogueAPReport(
-    IN  PRTMP_ADAPTER   pAd);
-
-BOOLEAN CCKMAssocRspSanity(
-    IN PRTMP_ADAPTER    pAd,
-    IN VOID             *Msg,
-    IN ULONG            MsgLen);
-
-#endif  // __LEAP_H__
diff --git a/drivers/staging/rt3070/link_list.h b/drivers/staging/rt3070/link_list.h
index f652113..5550b2f 100644
--- a/drivers/staging/rt3070/link_list.h
+++ b/drivers/staging/rt3070/link_list.h
@@ -1,134 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#ifndef __LINK_LIST_H__
-#define __LINK_LIST_H__
-
-typedef struct _LIST_ENTRY
-{
-	struct _LIST_ENTRY *pNext;
-} LIST_ENTRY, *PLIST_ENTRY;
-
-typedef struct _LIST_HEADR
-{
-	PLIST_ENTRY pHead;
-	PLIST_ENTRY pTail;
-	UCHAR size;
-} LIST_HEADER, *PLIST_HEADER;
-
-static inline VOID initList(
-	IN PLIST_HEADER pList)
-{
-	pList->pHead = pList->pTail = NULL;
-	pList->size = 0;
-	return;
-}
-
-static inline VOID insertTailList(
-	IN PLIST_HEADER pList,
-	IN PLIST_ENTRY pEntry)
-{
-	pEntry->pNext = NULL;
-	if (pList->pTail)
-		pList->pTail->pNext = pEntry;
-	else
-		pList->pHead = pEntry;
-	pList->pTail = pEntry;
-	pList->size++;
-
-	return;
-}
-
-static inline PLIST_ENTRY removeHeadList(
-	IN PLIST_HEADER pList)
-{
-	PLIST_ENTRY pNext;
-	PLIST_ENTRY pEntry;
-
-	pEntry = pList->pHead;
-	if (pList->pHead != NULL)
-	{
-		pNext = pList->pHead->pNext;
-		pList->pHead = pNext;
-		if (pNext == NULL)
-			pList->pTail = NULL;
-		pList->size--;
-	}
-	return pEntry;
-}
-
-static inline int getListSize(
-	IN PLIST_HEADER pList)
-{
-	return pList->size;
-}
-
-static inline PLIST_ENTRY delEntryList(
-	IN PLIST_HEADER pList,
-	IN PLIST_ENTRY pEntry)
-{
-	PLIST_ENTRY pCurEntry;
-	PLIST_ENTRY pPrvEntry;
-
-	if(pList->pHead == NULL)
-		return NULL;
-
-	if(pEntry == pList->pHead)
-	{
-		pCurEntry = pList->pHead;
-		pList->pHead = pCurEntry->pNext;
-
-		if(pList->pHead == NULL)
-			pList->pTail = NULL;
-
-		pList->size--;
-		return pCurEntry;
-	}
-
-	pPrvEntry = pList->pHead;
-	pCurEntry = pPrvEntry->pNext;
-	while(pCurEntry != NULL)
-	{
-		if (pEntry == pCurEntry)
-		{
-			pPrvEntry->pNext = pCurEntry->pNext;
-
-			if(pEntry == pList->pTail)
-				pList->pTail = pPrvEntry;
-
-			pList->size--;
-			break;
-		}
-		pPrvEntry = pCurEntry;
-		pCurEntry = pPrvEntry->pNext;
-	}
-
-	return pCurEntry;
-}
-
-#endif // ___LINK_LIST_H__ //
-
+#include "../rt2870/link_list.h"
diff --git a/drivers/staging/rt3070/md5.h b/drivers/staging/rt3070/md5.h
index d85db12..1042a99 100644
--- a/drivers/staging/rt3070/md5.h
+++ b/drivers/staging/rt3070/md5.h
@@ -1,107 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	md5.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-	jan			10-28-03		Initial
-	Rita    	11-23-04		Modify MD5 and SHA-1
-*/
-
-#ifndef	uint8
-#define	uint8  unsigned	char
-#endif
-
-#ifndef	uint32
-#define	uint32 unsigned	long int
-#endif
-
-
-#ifndef	__MD5_H__
-#define	__MD5_H__
-
-#define MD5_MAC_LEN 16
-
-typedef struct _MD5_CTX {
-    UINT32   Buf[4];             // buffers of four states
-	UCHAR   Input[64];          // input message
-	UINT32   LenInBitCount[2];   // length counter for input message, 0 up to 64 bits
-}   MD5_CTX;
-
-VOID MD5Init(MD5_CTX *pCtx);
-VOID MD5Update(MD5_CTX *pCtx, UCHAR *pData, UINT32 LenInBytes);
-VOID MD5Final(UCHAR Digest[16], MD5_CTX *pCtx);
-VOID MD5Transform(UINT32 Buf[4], UINT32 Mes[16]);
-
-void md5_mac(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac);
-void hmac_md5(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac);
-
-//
-// SHA context
-//
-typedef	struct _SHA_CTX
-{
-	UINT32   Buf[5];             // buffers of five states
-	UCHAR   Input[80];          // input message
-	UINT32   LenInBitCount[2];   // length counter for input message, 0 up to 64 bits
-
-}	SHA_CTX;
-
-VOID SHAInit(SHA_CTX *pCtx);
-UCHAR SHAUpdate(SHA_CTX *pCtx, UCHAR *pData, UINT32 LenInBytes);
-VOID SHAFinal(SHA_CTX *pCtx, UCHAR Digest[20]);
-VOID SHATransform(UINT32 Buf[5], UINT32 Mes[20]);
-
-#define SHA_DIGEST_LEN 20
-#endif // __MD5_H__
-
-/******************************************************************************/
-#ifndef	_AES_H
-#define	_AES_H
-
-typedef	struct
-{
-	uint32 erk[64];		/* encryption round	keys */
-	uint32 drk[64];		/* decryption round	keys */
-	int	nr;				/* number of rounds	*/
-}
-aes_context;
-
-int	 rtmp_aes_set_key( aes_context *ctx,	uint8 *key,	int	nbits );
-void rtmp_aes_encrypt( aes_context *ctx,	uint8 input[16], uint8 output[16] );
-void rtmp_aes_decrypt( aes_context *ctx,	uint8 input[16], uint8 output[16] );
-
-void F(char *password, unsigned char *ssid, int ssidlength, int iterations, int count, unsigned char *output);
-int PasswordHash(char *password, unsigned char *ssid, int ssidlength, unsigned char *output);
-
-#endif /* aes.h	*/
-
+#include "../rt2870/md5.h"
diff --git a/drivers/staging/rt3070/mlme.h b/drivers/staging/rt3070/mlme.h
index b0035e1..773c0ed 100644
--- a/drivers/staging/rt3070/mlme.h
+++ b/drivers/staging/rt3070/mlme.h
@@ -1,1468 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	mlme.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang	2003-08-28		Created
-	John Chang  2004-09-06      modified for RT2600
-
-*/
-#ifndef __MLME_H__
-#define __MLME_H__
-
-//extern UCHAR BROADCAST_ADDR[];
-
-// maximum supported capability information -
-// ESS, IBSS, Privacy, Short Preamble, Spectrum mgmt, Short Slot
-#define SUPPORTED_CAPABILITY_INFO   0x0533
-
-#define END_OF_ARGS                 -1
-#define LFSR_MASK                   0x80000057
-#define MLME_TASK_EXEC_INTV         100/*200*/       //
-#define LEAD_TIME                   5
-#define MLME_TASK_EXEC_MULTIPLE       10  /*5*/       // MLME_TASK_EXEC_MULTIPLE * MLME_TASK_EXEC_INTV = 1 sec
-#define REORDER_EXEC_INTV         	100       // 0.1 sec
-//#define TBTT_PRELOAD_TIME         384        // usec. LomgPreamble + 24-byte at 1Mbps
-
-// The definition of Radar detection duration region
-#define CE		0
-#define FCC		1
-#define JAP		2
-#define JAP_W53	3
-#define JAP_W56	4
-#define MAX_RD_REGION 5
-
-#ifdef	NDIS51_MINIPORT
-#define BEACON_LOST_TIME            4000       // 2048 msec = 2 sec
-#else
-#define BEACON_LOST_TIME            4 * OS_HZ    // 2048 msec = 2 sec
-#endif
-
-#define DLS_TIMEOUT                 1200      // unit: msec
-#define AUTH_TIMEOUT                300       // unit: msec
-#define ASSOC_TIMEOUT               300       // unit: msec
-#define JOIN_TIMEOUT                2 * OS_HZ      // unit: msec
-#define SHORT_CHANNEL_TIME          90        // unit: msec
-#define MIN_CHANNEL_TIME            110        // unit: msec, for dual band scan
-#define MAX_CHANNEL_TIME            140       // unit: msec, for single band scan
-#define	FAST_ACTIVE_SCAN_TIME	    30 		  // Active scan waiting for probe response time
-#define CW_MIN_IN_BITS              4         // actual CwMin = 2^CW_MIN_IN_BITS - 1
-
-
-#ifdef CONFIG_STA_SUPPORT
-#ifndef CONFIG_AP_SUPPORT
-#define CW_MAX_IN_BITS              10        // actual CwMax = 2^CW_MAX_IN_BITS - 1
-#endif
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-extern UINT32 CW_MAX_IN_BITS;
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-// Note: RSSI_TO_DBM_OFFSET has been changed to variable for new RF (2004-0720).
-// SHould not refer to this constant anymore
-//#define RSSI_TO_DBM_OFFSET          120 // for RT2530 RSSI-115 = dBm
-#define RSSI_FOR_MID_TX_POWER       -55  // -55 db is considered mid-distance
-#define RSSI_FOR_LOW_TX_POWER       -45  // -45 db is considered very short distance and
-                                        // eligible to use a lower TX power
-#define RSSI_FOR_LOWEST_TX_POWER    -30
-//#define MID_TX_POWER_DELTA          0   // 0 db from full TX power upon mid-distance to AP
-#define LOW_TX_POWER_DELTA          6    // -3 db from full TX power upon very short distance. 1 grade is 0.5 db
-#define LOWEST_TX_POWER_DELTA       16   // -8 db from full TX power upon shortest distance. 1 grade is 0.5 db
-
-#define RSSI_TRIGGERED_UPON_BELOW_THRESHOLD     0
-#define RSSI_TRIGGERED_UPON_EXCCEED_THRESHOLD   1
-#define RSSI_THRESHOLD_FOR_ROAMING              25
-#define RSSI_DELTA                              5
-
-// Channel Quality Indication
-#define CQI_IS_GOOD(cqi)            ((cqi) >= 50)
-//#define CQI_IS_FAIR(cqi)          (((cqi) >= 20) && ((cqi) < 50))
-#define CQI_IS_POOR(cqi)            (cqi < 50)  //(((cqi) >= 5) && ((cqi) < 20))
-#define CQI_IS_BAD(cqi)             (cqi < 5)
-#define CQI_IS_DEAD(cqi)            (cqi == 0)
-
-// weighting factor to calculate Channel quality, total should be 100%
-#define RSSI_WEIGHTING                   50
-#define TX_WEIGHTING                     30
-#define RX_WEIGHTING                     20
-
-//#define PEER_KEY_NOT_USED                0
-//#define PEER_KEY_64_BIT                  64
-//#define PEER_KEY_128_BIT                 128
-
-//#define PEER_KEY_64BIT_LEN               8
-//#define PEER_KEY_128BIT_LEN              16
-
-#define BSS_NOT_FOUND                    0xFFFFFFFF
-
-
-#ifdef CONFIG_STA_SUPPORT
-#define MAX_LEN_OF_MLME_QUEUE            40 //10
-#endif // CONFIG_STA_SUPPORT //
-
-#define SCAN_PASSIVE                     18		// scan with no probe request, only wait beacon and probe response
-#define SCAN_ACTIVE                      19		// scan with probe request, and wait beacon and probe response
-#define	SCAN_CISCO_PASSIVE				 20		// Single channel passive scan
-#define	SCAN_CISCO_ACTIVE				 21		// Single channel active scan
-#define	SCAN_CISCO_NOISE				 22		// Single channel passive scan for noise histogram collection
-#define	SCAN_CISCO_CHANNEL_LOAD			 23		// Single channel passive scan for channel load collection
-#define FAST_SCAN_ACTIVE                 24		// scan with probe request, and wait beacon and probe response
-
-#ifdef DOT11N_DRAFT3
-#define SCAN_2040_BSS_COEXIST                  26
-#endif // DOT11N_DRAFT3 //
-
-//#define BSS_TABLE_EMPTY(x)             ((x).BssNr == 0)
-#define MAC_ADDR_IS_GROUP(Addr)       (((Addr[0]) & 0x01))
-#define MAC_ADDR_HASH(Addr)            (Addr[0] ^ Addr[1] ^ Addr[2] ^ Addr[3] ^ Addr[4] ^ Addr[5])
-#define MAC_ADDR_HASH_INDEX(Addr)      (MAC_ADDR_HASH(Addr) % HASH_TABLE_SIZE)
-#define TID_MAC_HASH(Addr,TID)            (TID^Addr[0] ^ Addr[1] ^ Addr[2] ^ Addr[3] ^ Addr[4] ^ Addr[5])
-#define TID_MAC_HASH_INDEX(Addr,TID)      (TID_MAC_HASH(Addr,TID) % HASH_TABLE_SIZE)
-
-// LED Control
-// assoiation ON. one LED ON. another blinking when TX, OFF when idle
-// no association, both LED off
-#define ASIC_LED_ACT_ON(pAd)        RTMP_IO_WRITE32(pAd, MAC_CSR14, 0x00031e46)
-#define ASIC_LED_ACT_OFF(pAd)       RTMP_IO_WRITE32(pAd, MAC_CSR14, 0x00001e46)
-
-// bit definition of the 2-byte pBEACON->Capability field
-#define CAP_IS_ESS_ON(x)                 (((x) & 0x0001) != 0)
-#define CAP_IS_IBSS_ON(x)                (((x) & 0x0002) != 0)
-#define CAP_IS_CF_POLLABLE_ON(x)         (((x) & 0x0004) != 0)
-#define CAP_IS_CF_POLL_REQ_ON(x)         (((x) & 0x0008) != 0)
-#define CAP_IS_PRIVACY_ON(x)             (((x) & 0x0010) != 0)
-#define CAP_IS_SHORT_PREAMBLE_ON(x)      (((x) & 0x0020) != 0)
-#define CAP_IS_PBCC_ON(x)                (((x) & 0x0040) != 0)
-#define CAP_IS_AGILITY_ON(x)             (((x) & 0x0080) != 0)
-#define CAP_IS_SPECTRUM_MGMT(x)          (((x) & 0x0100) != 0)  // 802.11e d9
-#define CAP_IS_QOS(x)                    (((x) & 0x0200) != 0)  // 802.11e d9
-#define CAP_IS_SHORT_SLOT(x)             (((x) & 0x0400) != 0)
-#define CAP_IS_APSD(x)                   (((x) & 0x0800) != 0)  // 802.11e d9
-#define CAP_IS_IMMED_BA(x)               (((x) & 0x1000) != 0)  // 802.11e d9
-#define CAP_IS_DSSS_OFDM(x)              (((x) & 0x2000) != 0)
-#define CAP_IS_DELAY_BA(x)               (((x) & 0x4000) != 0)  // 802.11e d9
-
-#define CAP_GENERATE(ess,ibss,priv,s_pre,s_slot,spectrum)  (((ess) ? 0x0001 : 0x0000) | ((ibss) ? 0x0002 : 0x0000) | ((priv) ? 0x0010 : 0x0000) | ((s_pre) ? 0x0020 : 0x0000) | ((s_slot) ? 0x0400 : 0x0000) | ((spectrum) ? 0x0100 : 0x0000))
-
-//#define STA_QOS_CAPABILITY               0 // 1-byte. see 802.11e d9.0 for bit definition
-
-#define ERP_IS_NON_ERP_PRESENT(x)        (((x) & 0x01) != 0)    // 802.11g
-#define ERP_IS_USE_PROTECTION(x)         (((x) & 0x02) != 0)    // 802.11g
-#define ERP_IS_USE_BARKER_PREAMBLE(x)    (((x) & 0x04) != 0)    // 802.11g
-
-#define DRS_TX_QUALITY_WORST_BOUND       8// 3  // just test by gary
-#define DRS_PENALTY                      8
-
-#define BA_NOTUSE 	2
-//BA Policy subfiled value in ADDBA frame
-#define IMMED_BA 	1
-#define DELAY_BA	0
-
-// BA Initiator subfield in DELBA frame
-#define ORIGINATOR	1
-#define RECIPIENT	0
-
-// ADDBA Status Code
-#define ADDBA_RESULTCODE_SUCCESS					0
-#define ADDBA_RESULTCODE_REFUSED					37
-#define ADDBA_RESULTCODE_INVALID_PARAMETERS			38
-
-// DELBA Reason Code
-#define DELBA_REASONCODE_QSTA_LEAVING				36
-#define DELBA_REASONCODE_END_BA						37
-#define DELBA_REASONCODE_UNKNOWN_BA					38
-#define DELBA_REASONCODE_TIMEOUT					39
-
-// reset all OneSecTx counters
-#define RESET_ONE_SEC_TX_CNT(__pEntry) \
-if (((__pEntry)) != NULL) \
-{ \
-	(__pEntry)->OneSecTxRetryOkCount = 0; \
-	(__pEntry)->OneSecTxFailCount = 0; \
-	(__pEntry)->OneSecTxNoRetryOkCount = 0; \
-}
-
-//
-// 802.11 frame formats
-//
-//  HT Capability INFO field in HT Cap IE .
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	USHORT	LSIGTxopProSup:1;
-	USHORT	Forty_Mhz_Intolerant:1;
-	USHORT	PSMP:1;
-	USHORT	CCKmodein40:1;
-	USHORT	AMsduSize:1;
-	USHORT	DelayedBA:1;	//rt2860c not support
-	USHORT	RxSTBC:2;
-	USHORT	TxSTBC:1;
-	USHORT	ShortGIfor40:1;	//for40MHz
-	USHORT	ShortGIfor20:1;
-	USHORT	GF:1;	//green field
-	USHORT	MimoPs:2;//momi power safe
-	USHORT	ChannelWidth:1;
-	USHORT	AdvCoding:1;
-#else
-	USHORT	AdvCoding:1;
-	USHORT	ChannelWidth:1;
-	USHORT	MimoPs:2;//momi power safe
-	USHORT	GF:1;	//green field
-	USHORT	ShortGIfor20:1;
-	USHORT	ShortGIfor40:1;	//for40MHz
-	USHORT	TxSTBC:1;
-	USHORT	RxSTBC:2;
-	USHORT	DelayedBA:1;	//rt2860c not support
-	USHORT	AMsduSize:1;	// only support as zero
-	USHORT	CCKmodein40:1;
-	USHORT	PSMP:1;
-	USHORT	Forty_Mhz_Intolerant:1;
-	USHORT	LSIGTxopProSup:1;
-#endif	/* !RT_BIG_ENDIAN */
-} HT_CAP_INFO, *PHT_CAP_INFO;
-
-//  HT Capability INFO field in HT Cap IE .
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:3;//momi power safe
-	UCHAR	MpduDensity:3;
-	UCHAR	MaxRAmpduFactor:2;
-#else
-	UCHAR	MaxRAmpduFactor:2;
-	UCHAR	MpduDensity:3;
-	UCHAR	rsv:3;//momi power safe
-#endif /* !RT_BIG_ENDIAN */
-} HT_CAP_PARM, *PHT_CAP_PARM;
-
-//  HT Capability INFO field in HT Cap IE .
-typedef struct PACKED {
-	UCHAR	MCSSet[10];
-	UCHAR	SupRate[2];  // unit : 1Mbps
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:3;
-	UCHAR	MpduDensity:1;
-	UCHAR	TxStream:2;
-	UCHAR	TxRxNotEqual:1;
-	UCHAR	TxMCSSetDefined:1;
-#else
-	UCHAR	TxMCSSetDefined:1;
-	UCHAR	TxRxNotEqual:1;
-	UCHAR	TxStream:2;
-	UCHAR	MpduDensity:1;
-	UCHAR	rsv:3;
-#endif // RT_BIG_ENDIAN //
-	UCHAR	rsv3[3];
-} HT_MCS_SET, *PHT_MCS_SET;
-
-//  HT Capability INFO field in HT Cap IE .
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv2:4;
-	USHORT	RDGSupport:1;	//reverse Direction Grant  support
-	USHORT	PlusHTC:1;	//+HTC control field support
-	USHORT	MCSFeedback:2;	//0:no MCS feedback, 2:unsolicited MCS feedback, 3:Full MCS feedback,  1:rsv.
-	USHORT	rsv:5;//momi power safe
-	USHORT	TranTime:2;
-	USHORT	Pco:1;
-#else
-	USHORT	Pco:1;
-	USHORT	TranTime:2;
-	USHORT	rsv:5;//momi power safe
-	USHORT	MCSFeedback:2;	//0:no MCS feedback, 2:unsolicited MCS feedback, 3:Full MCS feedback,  1:rsv.
-	USHORT	PlusHTC:1;	//+HTC control field support
-	USHORT	RDGSupport:1;	//reverse Direction Grant  support
-	USHORT	rsv2:4;
-#endif /* RT_BIG_ENDIAN */
-} EXT_HT_CAP_INFO, *PEXT_HT_CAP_INFO;
-
-//  HT Beamforming field in HT Cap IE .
-typedef struct PACKED _HT_BF_CAP{
-#ifdef RT_BIG_ENDIAN
-	ULONG	rsv:3;
-	ULONG	ChanEstimation:2;
-	ULONG	CSIRowBFSup:2;
-	ULONG	ComSteerBFAntSup:2;
-	ULONG	NoComSteerBFAntSup:2;
-	ULONG	CSIBFAntSup:2;
-	ULONG	MinGrouping:2;
-	ULONG	ExpComBF:2;
-	ULONG	ExpNoComBF:2;
-	ULONG	ExpCSIFbk:2;
-	ULONG	ExpComSteerCapable:1;
-	ULONG	ExpNoComSteerCapable:1;
-	ULONG	ExpCSICapable:1;
-	ULONG	Calibration:2;
-	ULONG	ImpTxBFCapable:1;
-	ULONG	TxNDPCapable:1;
-	ULONG	RxNDPCapable:1;
-	ULONG	TxSoundCapable:1;
-	ULONG	RxSoundCapable:1;
-	ULONG	TxBFRecCapable:1;
-#else
-	ULONG	TxBFRecCapable:1;
-	ULONG	RxSoundCapable:1;
-	ULONG	TxSoundCapable:1;
-	ULONG	RxNDPCapable:1;
-	ULONG	TxNDPCapable:1;
-	ULONG	ImpTxBFCapable:1;
-	ULONG	Calibration:2;
-	ULONG	ExpCSICapable:1;
-	ULONG	ExpNoComSteerCapable:1;
-	ULONG	ExpComSteerCapable:1;
-	ULONG	ExpCSIFbk:2;
-	ULONG	ExpNoComBF:2;
-	ULONG	ExpComBF:2;
-	ULONG	MinGrouping:2;
-	ULONG	CSIBFAntSup:2;
-	ULONG	NoComSteerBFAntSup:2;
-	ULONG	ComSteerBFAntSup:2;
-	ULONG	CSIRowBFSup:2;
-	ULONG	ChanEstimation:2;
-	ULONG	rsv:3;
-#endif // RT_BIG_ENDIAN //
-} HT_BF_CAP, *PHT_BF_CAP;
-
-//  HT antenna selection field in HT Cap IE .
-typedef struct PACKED _HT_AS_CAP{
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:1;
-	UCHAR	TxSoundPPDU:1;
-	UCHAR	RxASel:1;
-	UCHAR	AntIndFbk:1;
-	UCHAR	ExpCSIFbk:1;
-	UCHAR	AntIndFbkTxASEL:1;
-	UCHAR	ExpCSIFbkTxASEL:1;
-	UCHAR	AntSelect:1;
-#else
-	UCHAR	AntSelect:1;
-	UCHAR	ExpCSIFbkTxASEL:1;
-	UCHAR	AntIndFbkTxASEL:1;
-	UCHAR	ExpCSIFbk:1;
-	UCHAR	AntIndFbk:1;
-	UCHAR	RxASel:1;
-	UCHAR	TxSoundPPDU:1;
-	UCHAR	rsv:1;
-#endif // RT_BIG_ENDIAN //
-} HT_AS_CAP, *PHT_AS_CAP;
-
-// Draft 1.0 set IE length 26, but is extensible..
-#define SIZE_HT_CAP_IE		26
-// The structure for HT Capability IE.
-typedef struct PACKED _HT_CAPABILITY_IE{
-	HT_CAP_INFO		HtCapInfo;
-	HT_CAP_PARM		HtCapParm;
-//	HT_MCS_SET		HtMCSSet;
-	UCHAR			MCSSet[16];
-	EXT_HT_CAP_INFO	ExtHtCapInfo;
-	HT_BF_CAP		TxBFCap;	// beamforming cap. rt2860c not support beamforming.
-	HT_AS_CAP		ASCap;	//antenna selection.
-} HT_CAPABILITY_IE, *PHT_CAPABILITY_IE;
-
-
-// 802.11n draft3 related structure definitions.
-// 7.3.2.60
-#define dot11OBSSScanPassiveDwell							20	// in TU. min amount of time that the STA continously scans each channel when performing an active OBSS scan.
-#define dot11OBSSScanActiveDwell							10	// in TU.min amount of time that the STA continously scans each channel when performing an passive OBSS scan.
-#define dot11BSSWidthTriggerScanInterval					300  // in sec. max interval between scan operations to be performed to detect BSS channel width trigger events.
-#define dot11OBSSScanPassiveTotalPerChannel					200	// in TU. min total amount of time that the STA scans each channel when performing a passive OBSS scan.
-#define dot11OBSSScanActiveTotalPerChannel					20	//in TU. min total amount of time that the STA scans each channel when performing a active OBSS scan
-#define dot11BSSWidthChannelTransactionDelayFactor			5	// min ratio between the delay time in performing a switch from 20MHz BSS to 20/40 BSS operation and the maxima
-																//	interval between overlapping BSS scan operations.
-#define dot11BSSScanActivityThreshold						25	// in %%, max total time that a STA may be active on the medium during a period of
-																//	(dot11BSSWidthChannelTransactionDelayFactor * dot11BSSWidthTriggerScanInterval) seconds without
-																//	being obligated to perform OBSS Scan operations. default is 25(== 0.25%)
-
-typedef struct PACKED _OVERLAP_BSS_SCAN_IE{
-	USHORT		ScanPassiveDwell;
-	USHORT		ScanActiveDwell;
-	USHORT		TriggerScanInt;				// Trigger scan interval
-	USHORT		PassiveTalPerChannel;		// passive total per channel
-	USHORT		ActiveTalPerChannel;		// active total per channel
-	USHORT		DelayFactor;				// BSS width channel transition delay factor
-	USHORT		ScanActThre;				// Scan Activity threshold
-}OVERLAP_BSS_SCAN_IE, *POVERLAP_BSS_SCAN_IE;
-
-
-//  7.3.2.56. 20/40 Coexistence element used in  Element ID = 72 = IE_2040_BSS_COEXIST
-typedef union PACKED _BSS_2040_COEXIST_IE{
- struct PACKED {
- #ifdef RT_BIG_ENDIAN
-	UCHAR	rsv:5;
-	UCHAR	BSS20WidthReq:1;
-	UCHAR	Intolerant40:1;
-	UCHAR	InfoReq:1;
- #else
-	UCHAR	InfoReq:1;
-	UCHAR	Intolerant40:1;			// Inter-BSS. set 1 when prohibits a receiving BSS from operating as a 20/40 Mhz BSS.
-	UCHAR	BSS20WidthReq:1;		// Intra-BSS set 1 when prohibits a receiving AP from operating its BSS as a 20/40MHz BSS.
-	UCHAR	rsv:5;
-#endif // RT_BIG_ENDIAN //
-    } field;
- UCHAR   word;
-} BSS_2040_COEXIST_IE, *PBSS_2040_COEXIST_IE;
-
-
-typedef struct  _TRIGGER_EVENTA{
-	BOOLEAN			bValid;
-	UCHAR	BSSID[6];
-	UCHAR	RegClass;	// Regulatory Class
-	USHORT	Channel;
-	ULONG	CDCounter;   // Maintain a seperate count down counter for each Event A.
-} TRIGGER_EVENTA, *PTRIGGER_EVENTA;
-
-// 20/40 trigger event table
-// If one Event A delete or created, or if Event B is detected or not detected, STA should send 2040BSSCoexistence to AP.
-#define MAX_TRIGGER_EVENT		64
-typedef struct  _TRIGGER_EVENT_TAB{
-	UCHAR	EventANo;
-	TRIGGER_EVENTA	EventA[MAX_TRIGGER_EVENT];
-	ULONG			EventBCountDown;	// Count down counter for Event B.
-} TRIGGER_EVENT_TAB, *PTRIGGER_EVENT_TAB;
-
-// 7.3.27 20/40 Bss Coexistence Mgmt capability used in extended capabilities information IE( ID = 127 = IE_EXT_CAPABILITY).
-//	This is the first octet and was defined in 802.11n D3.03 and 802.11yD9.0
-typedef struct PACKED _EXT_CAP_INFO_ELEMENT{
-#ifdef RT_BIG_ENDIAN
-	UCHAR	rsv2:5;
-	UCHAR	ExtendChannelSwitch:1;
-	UCHAR	rsv:1;
-	UCHAR	BssCoexistMgmtSupport:1;
-#else
-	UCHAR	BssCoexistMgmtSupport:1;
-	UCHAR	rsv:1;
-	UCHAR	ExtendChannelSwitch:1;
-	UCHAR	rsv2:5;
-#endif // RT_BIG_ENDIAN //
-}EXT_CAP_INFO_ELEMENT, *PEXT_CAP_INFO_ELEMENT;
-
-
-// 802.11n 7.3.2.61
-typedef struct PACKED _BSS_2040_COEXIST_ELEMENT{
-	UCHAR					ElementID;		// ID = IE_2040_BSS_COEXIST = 72
-	UCHAR					Len;
-	BSS_2040_COEXIST_IE		BssCoexistIe;
-}BSS_2040_COEXIST_ELEMENT, *PBSS_2040_COEXIST_ELEMENT;
-
-
-//802.11n 7.3.2.59
-typedef struct PACKED _BSS_2040_INTOLERANT_CH_REPORT{
-	UCHAR				ElementID;		// ID = IE_2040_BSS_INTOLERANT_REPORT = 73
-	UCHAR				Len;
-	UCHAR				RegulatoryClass;
-	UCHAR				ChList[0];
-}BSS_2040_INTOLERANT_CH_REPORT, *PBSS_2040_INTOLERANT_CH_REPORT;
-
-
-// The structure for channel switch annoucement IE. This is in 802.11n D3.03
-typedef struct PACKED _CHA_SWITCH_ANNOUNCE_IE{
-	UCHAR			SwitchMode;	//channel switch mode
-	UCHAR			NewChannel;	//
-	UCHAR			SwitchCount;	//
-} CHA_SWITCH_ANNOUNCE_IE, *PCHA_SWITCH_ANNOUNCE_IE;
-
-
-// The structure for channel switch annoucement IE. This is in 802.11n D3.03
-typedef struct PACKED _SEC_CHA_OFFSET_IE{
-	UCHAR			SecondaryChannelOffset;	 // 1: Secondary above, 3: Secondary below, 0: no Secondary
-} SEC_CHA_OFFSET_IE, *PSEC_CHA_OFFSET_IE;
-
-
-// This structure is extracted from struct RT_HT_CAPABILITY
-typedef struct {
-	BOOLEAN			bHtEnable;	 // If we should use ht rate.
-	BOOLEAN			bPreNHt;	 // If we should use ht rate.
-	//Substract from HT Capability IE
-	UCHAR			MCSSet[16];	//only supoort MCS=0-15,32 ,
-} RT_HT_PHY_INFO, *PRT_HT_PHY_INFO;
-
-//This structure substracts ralink supports from all 802.11n-related features.
-//Features not listed here but contained in 802.11n spec are not supported in rt2860.
-typedef struct {
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv:5;
-	USHORT	AmsduSize:1;	// Max receiving A-MSDU size
-	USHORT	AmsduEnable:1;	// Enable to transmit A-MSDU. Suggest disable. We should use A-MPDU to gain best benifit of 802.11n
-	USHORT	RxSTBC:2;	// 2 bits
-	USHORT	TxSTBC:1;
-	USHORT	ShortGIfor40:1;	//for40MHz
-	USHORT	ShortGIfor20:1;
-	USHORT	GF:1;	//green field
-	USHORT	MimoPs:2;//mimo power safe MMPS_
-	USHORT	ChannelWidth:1;
-#else
-	USHORT	ChannelWidth:1;
-	USHORT	MimoPs:2;//mimo power safe MMPS_
-	USHORT	GF:1;	//green field
-	USHORT	ShortGIfor20:1;
-	USHORT	ShortGIfor40:1;	//for40MHz
-	USHORT	TxSTBC:1;
-	USHORT	RxSTBC:2;	// 2 bits
-	USHORT	AmsduEnable:1;	// Enable to transmit A-MSDU. Suggest disable. We should use A-MPDU to gain best benifit of 802.11n
-	USHORT	AmsduSize:1;	// Max receiving A-MSDU size
-	USHORT	rsv:5;
-#endif
-
-	//Substract from Addiont HT INFO IE
-#ifdef RT_BIG_ENDIAN
-	UCHAR	RecomWidth:1;
-	UCHAR	ExtChanOffset:2;	// Please not the difference with following 	UCHAR	NewExtChannelOffset; from 802.11n
-	UCHAR	MpduDensity:3;
-	UCHAR	MaxRAmpduFactor:2;
-#else
-	UCHAR	MaxRAmpduFactor:2;
-	UCHAR	MpduDensity:3;
-	UCHAR	ExtChanOffset:2;	// Please not the difference with following 	UCHAR	NewExtChannelOffset; from 802.11n
-	UCHAR	RecomWidth:1;
-#endif
-
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv2:11;
-	USHORT	OBSS_NonHTExist:1;
-	USHORT	rsv3:1;
-	USHORT	NonGfPresent:1;
-	USHORT	OperaionMode:2;
-#else
-	USHORT	OperaionMode:2;
-	USHORT	NonGfPresent:1;
-	USHORT	rsv3:1;
-	USHORT	OBSS_NonHTExist:1;
-	USHORT	rsv2:11;
-#endif
-
-	// New Extension Channel Offset IE
-	UCHAR	NewExtChannelOffset;
-	// Extension Capability IE = 127
-	UCHAR	BSSCoexist2040;
-} RT_HT_CAPABILITY, *PRT_HT_CAPABILITY;
-
-//   field in Addtional HT Information IE .
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR	SerInterGranu:3;
-	UCHAR	S_PSMPSup:1;
-	UCHAR	RifsMode:1;
-	UCHAR	RecomWidth:1;
-	UCHAR	ExtChanOffset:2;
-#else
-	UCHAR	ExtChanOffset:2;
-	UCHAR	RecomWidth:1;
-	UCHAR	RifsMode:1;
-	UCHAR	S_PSMPSup:1;	 //Indicate support for scheduled PSMP
-	UCHAR	SerInterGranu:3;	 //service interval granularity
-#endif
-} ADD_HTINFO, *PADD_HTINFO;
-
-typedef struct PACKED{
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv2:11;
-	USHORT	OBSS_NonHTExist:1;
-	USHORT	rsv:1;
-	USHORT	NonGfPresent:1;
-	USHORT	OperaionMode:2;
-#else
-	USHORT	OperaionMode:2;
-	USHORT	NonGfPresent:1;
-	USHORT	rsv:1;
-	USHORT	OBSS_NonHTExist:1;
-	USHORT	rsv2:11;
-#endif
-} ADD_HTINFO2, *PADD_HTINFO2;
-
-
-// TODO: Need sync with spec about the definition of StbcMcs. In Draft 3.03, it's reserved.
-typedef struct PACKED{
-#ifdef RT_BIG_ENDIAN
-	USHORT	rsv:4;
-	USHORT	PcoPhase:1;
-	USHORT	PcoActive:1;
-	USHORT	LsigTxopProt:1;
-	USHORT	STBCBeacon:1;
-	USHORT	DualCTSProtect:1;
-	USHORT	DualBeacon:1;
-	USHORT	StbcMcs:6;
-#else
-	USHORT	StbcMcs:6;
-	USHORT	DualBeacon:1;
-	USHORT	DualCTSProtect:1;
-	USHORT	STBCBeacon:1;
-	USHORT	LsigTxopProt:1;	// L-SIG TXOP protection full support
-	USHORT	PcoActive:1;
-	USHORT	PcoPhase:1;
-	USHORT	rsv:4;
-#endif // RT_BIG_ENDIAN //
-} ADD_HTINFO3, *PADD_HTINFO3;
-
-#define SIZE_ADD_HT_INFO_IE		22
-typedef struct  PACKED{
-	UCHAR				ControlChan;
-	ADD_HTINFO			AddHtInfo;
-	ADD_HTINFO2			AddHtInfo2;
-	ADD_HTINFO3			AddHtInfo3;
-	UCHAR				MCSSet[16];		// Basic MCS set
-} ADD_HT_INFO_IE, *PADD_HT_INFO_IE;
-
-typedef struct  PACKED{
-	UCHAR				NewExtChanOffset;
-} NEW_EXT_CHAN_IE, *PNEW_EXT_CHAN_IE;
-
-
-// 4-byte HTC field.  maybe included in any frame except non-QOS data frame.  The Order bit must set 1.
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    UINT32		RDG:1;	//RDG / More PPDU
-    UINT32		ACConstraint:1;	//feedback request
-    UINT32		rsv:5;  //calibration sequence
-    UINT32		ZLFAnnouce:1;	// ZLF announcement
-    UINT32		CSISTEERING:2;	//CSI/ STEERING
-    UINT32		FBKReq:2;	//feedback request
-    UINT32		CalSeq:2;  //calibration sequence
-    UINT32		CalPos:2;	// calibration position
-    UINT32		MFBorASC:7;	//Link adaptation feedback containing recommended MCS. 0x7f for no feedback or not available
-    UINT32		MFS:3;	//SET to the received value of MRS. 0x111 for unsolicited MFB.
-    UINT32		MRSorASI:3;	// MRQ Sequence identifier. unchanged during entire procedure. 0x000-0x110.
-    UINT32		MRQ:1;	//MCS feedback. Request for a MCS feedback
-    UINT32		TRQ:1;	//sounding request
-    UINT32		MA:1;	//management action payload exist in (QoS Null+HTC)
-#else
-    UINT32		MA:1;	//management action payload exist in (QoS Null+HTC)
-    UINT32		TRQ:1;	//sounding request
-    UINT32		MRQ:1;	//MCS feedback. Request for a MCS feedback
-    UINT32		MRSorASI:3;	// MRQ Sequence identifier. unchanged during entire procedure. 0x000-0x110.
-    UINT32		MFS:3;	//SET to the received value of MRS. 0x111 for unsolicited MFB.
-    UINT32		MFBorASC:7;	//Link adaptation feedback containing recommended MCS. 0x7f for no feedback or not available
-    UINT32		CalPos:2;	// calibration position
-    UINT32		CalSeq:2;  //calibration sequence
-    UINT32		FBKReq:2;	//feedback request
-    UINT32		CSISTEERING:2;	//CSI/ STEERING
-    UINT32		ZLFAnnouce:1;	// ZLF announcement
-    UINT32		rsv:5;  //calibration sequence
-    UINT32		ACConstraint:1;	//feedback request
-    UINT32		RDG:1;	//RDG / More PPDU
-#endif /* !RT_BIG_ENDIAN */
-} HT_CONTROL, *PHT_CONTROL;
-
-// 2-byte QOS CONTROL field
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      Txop_QueueSize:8;
-    USHORT      AMsduPresent:1;
-    USHORT      AckPolicy:2;  //0: normal ACK 1:No ACK 2:scheduled under MTBA/PSMP  3: BA
-    USHORT      EOSP:1;
-    USHORT      TID:4;
-#else
-    USHORT      TID:4;
-    USHORT      EOSP:1;
-    USHORT      AckPolicy:2;  //0: normal ACK 1:No ACK 2:scheduled under MTBA/PSMP  3: BA
-    USHORT      AMsduPresent:1;
-    USHORT      Txop_QueueSize:8;
-#endif /* !RT_BIG_ENDIAN */
-} QOS_CONTROL, *PQOS_CONTROL;
-
-// 2-byte Frame control field
-typedef	struct	PACKED {
-#ifdef RT_BIG_ENDIAN
-	USHORT		Order:1;			// Strict order expected
-	USHORT		Wep:1;				// Wep data
-	USHORT		MoreData:1;			// More data bit
-	USHORT		PwrMgmt:1;			// Power management bit
-	USHORT		Retry:1;			// Retry status bit
-	USHORT		MoreFrag:1;			// More fragment bit
-	USHORT		FrDs:1;				// From DS indication
-	USHORT		ToDs:1;				// To DS indication
-	USHORT		SubType:4;			// MSDU subtype
-	USHORT		Type:2;				// MSDU type
-	USHORT		Ver:2;				// Protocol version
-#else
-	USHORT		Ver:2;				// Protocol version
-	USHORT		Type:2;				// MSDU type
-	USHORT		SubType:4;			// MSDU subtype
-	USHORT		ToDs:1;				// To DS indication
-	USHORT		FrDs:1;				// From DS indication
-	USHORT		MoreFrag:1;			// More fragment bit
-	USHORT		Retry:1;			// Retry status bit
-	USHORT		PwrMgmt:1;			// Power management bit
-	USHORT		MoreData:1;			// More data bit
-	USHORT		Wep:1;				// Wep data
-	USHORT		Order:1;			// Strict order expected
-#endif /* !RT_BIG_ENDIAN */
-} FRAME_CONTROL, *PFRAME_CONTROL;
-
-typedef	struct	PACKED _HEADER_802_11	{
-    FRAME_CONTROL   FC;
-    USHORT          Duration;
-    UCHAR           Addr1[MAC_ADDR_LEN];
-    UCHAR           Addr2[MAC_ADDR_LEN];
-	UCHAR			Addr3[MAC_ADDR_LEN];
-#ifdef RT_BIG_ENDIAN
-	USHORT			Sequence:12;
-	USHORT			Frag:4;
-#else
-	USHORT			Frag:4;
-	USHORT			Sequence:12;
-#endif /* !RT_BIG_ENDIAN */
-	UCHAR			Octet[0];
-}	HEADER_802_11, *PHEADER_802_11;
-
-typedef struct PACKED _FRAME_802_11 {
-    HEADER_802_11   Hdr;
-    UCHAR            Octet[1];
-}   FRAME_802_11, *PFRAME_802_11;
-
-// QoSNull embedding of management action. When HT Control MA field set to 1.
-typedef struct PACKED _MA_BODY {
-    UCHAR            Category;
-    UCHAR            Action;
-    UCHAR            Octet[1];
-}   MA_BODY, *PMA_BODY;
-
-typedef	struct	PACKED _HEADER_802_3	{
-    UCHAR           DAAddr1[MAC_ADDR_LEN];
-    UCHAR           SAAddr2[MAC_ADDR_LEN];
-    UCHAR           Octet[2];
-}	HEADER_802_3, *PHEADER_802_3;
-////Block ACK related format
-// 2-byte BA Parameter  field  in 	DELBA frames to terminate an already set up bA
-typedef struct PACKED{
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;	// value of TC os TS
-    USHORT      Initiator:1;	// 1: originator    0:recipient
-    USHORT      Rsv:11;	// always set to 0
-#else
-    USHORT      Rsv:11;	// always set to 0
-    USHORT      Initiator:1;	// 1: originator    0:recipient
-    USHORT      TID:4;	// value of TC os TS
-#endif /* !RT_BIG_ENDIAN */
-} DELBA_PARM, *PDELBA_PARM;
-
-// 2-byte BA Parameter Set field  in ADDBA frames to signal parm for setting up a BA
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      BufSize:10;	// number of buffe of size 2304 octetsr
-    USHORT      TID:4;	// value of TC os TS
-    USHORT      BAPolicy:1;	// 1: immediately BA    0:delayed BA
-    USHORT      AMSDUSupported:1;	// 0: not permitted		1: permitted
-#else
-    USHORT      AMSDUSupported:1;	// 0: not permitted		1: permitted
-    USHORT      BAPolicy:1;	// 1: immediately BA    0:delayed BA
-    USHORT      TID:4;	// value of TC os TS
-    USHORT      BufSize:10;	// number of buffe of size 2304 octetsr
-#endif /* !RT_BIG_ENDIAN */
-} BA_PARM, *PBA_PARM;
-
-// 2-byte BA Starting Seq CONTROL field
-typedef union PACKED {
-    struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      StartSeq:12;   // sequence number of the 1st MSDU for which this BAR is sent
-	USHORT      FragNum:4;	// always set to 0
-#else
-    USHORT      FragNum:4;	// always set to 0
-	USHORT      StartSeq:12;   // sequence number of the 1st MSDU for which this BAR is sent
-#endif /* RT_BIG_ENDIAN */
-    }   field;
-    USHORT           word;
-} BASEQ_CONTROL, *PBASEQ_CONTROL;
-
-//BAControl and BARControl are the same
-// 2-byte BA CONTROL field in BA frame
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;
-    USHORT      Rsv:9;
-    USHORT      Compressed:1;
-    USHORT      MTID:1;		//EWC V1.24
-    USHORT      ACKPolicy:1; // only related to N-Delayed BA. But not support in RT2860b. 0:NormalACK  1:No ACK
-#else
-    USHORT      ACKPolicy:1; // only related to N-Delayed BA. But not support in RT2860b. 0:NormalACK  1:No ACK
-    USHORT      MTID:1;		//EWC V1.24
-    USHORT      Compressed:1;
-    USHORT      Rsv:9;
-    USHORT      TID:4;
-#endif /* !RT_BIG_ENDIAN */
-} BA_CONTROL, *PBA_CONTROL;
-
-// 2-byte BAR CONTROL field in BAR frame
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;
-    USHORT      Rsv1:9;
-    USHORT      Compressed:1;
-    USHORT      MTID:1;		//if this bit1, use  FRAME_MTBA_REQ,  if 0, use FRAME_BA_REQ
-    USHORT      ACKPolicy:1;
-#else
-    USHORT      ACKPolicy:1; // 0:normal ack,  1:no ack.
-    USHORT      MTID:1;		//if this bit1, use  FRAME_MTBA_REQ,  if 0, use FRAME_BA_REQ
-    USHORT      Compressed:1;
-    USHORT      Rsv1:9;
-    USHORT      TID:4;
-#endif /* !RT_BIG_ENDIAN */
-} BAR_CONTROL, *PBAR_CONTROL;
-
-// BARControl in MTBAR frame
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      NumTID:4;
-    USHORT      Rsv1:9;
-    USHORT      Compressed:1;
-    USHORT      MTID:1;
-    USHORT      ACKPolicy:1;
-#else
-    USHORT      ACKPolicy:1;
-    USHORT      MTID:1;
-    USHORT      Compressed:1;
-    USHORT      Rsv1:9;
-    USHORT      NumTID:4;
-#endif /* !RT_BIG_ENDIAN */
-} MTBAR_CONTROL, *PMTBAR_CONTROL;
-
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-    USHORT      TID:4;
-    USHORT      Rsv1:12;
-#else
-    USHORT      Rsv1:12;
-    USHORT      TID:4;
-#endif /* !RT_BIG_ENDIAN */
-} PER_TID_INFO, *PPER_TID_INFO;
-
-typedef struct {
-	PER_TID_INFO      PerTID;
-	BASEQ_CONTROL 	 BAStartingSeq;
-} EACH_TID, *PEACH_TID;
-
-
-typedef struct PACKED _PSPOLL_FRAME {
-    FRAME_CONTROL   FC;
-    USHORT          Aid;
-    UCHAR           Bssid[MAC_ADDR_LEN];
-    UCHAR           Ta[MAC_ADDR_LEN];
-}   PSPOLL_FRAME, *PPSPOLL_FRAME;
-
-typedef	struct	PACKED _RTS_FRAME	{
-    FRAME_CONTROL   FC;
-    USHORT          Duration;
-    UCHAR           Addr1[MAC_ADDR_LEN];
-    UCHAR           Addr2[MAC_ADDR_LEN];
-}RTS_FRAME, *PRTS_FRAME;
-
-// BAREQ AND MTBAREQ have the same subtype BAR, 802.11n BAR use compressed bitmap.
-typedef struct PACKED _FRAME_BA_REQ {
-	FRAME_CONTROL   FC;
-	USHORT          Duration;
-	UCHAR           Addr1[MAC_ADDR_LEN];
-	UCHAR           Addr2[MAC_ADDR_LEN];
-	BAR_CONTROL  BARControl;
-	BASEQ_CONTROL 	 BAStartingSeq;
-}   FRAME_BA_REQ, *PFRAME_BA_REQ;
-
-typedef struct PACKED _FRAME_MTBA_REQ {
-	FRAME_CONTROL   FC;
-	USHORT          Duration;
-	UCHAR           Addr1[MAC_ADDR_LEN];
-	UCHAR           Addr2[MAC_ADDR_LEN];
-	MTBAR_CONTROL  MTBARControl;
-	PER_TID_INFO	PerTIDInfo;
-	BASEQ_CONTROL 	 BAStartingSeq;
-}   FRAME_MTBA_REQ, *PFRAME_MTBA_REQ;
-
-// Compressed format is mandantory in HT STA
-typedef struct PACKED _FRAME_MTBA {
-	FRAME_CONTROL   FC;
-	USHORT          Duration;
-	UCHAR           Addr1[MAC_ADDR_LEN];
-	UCHAR           Addr2[MAC_ADDR_LEN];
-	BA_CONTROL  BAControl;
-	BASEQ_CONTROL 	 BAStartingSeq;
-	UCHAR		BitMap[8];
-}   FRAME_MTBA, *PFRAME_MTBA;
-
-typedef struct PACKED _FRAME_PSMP_ACTION {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	UCHAR	Psmp;	// 7.3.1.25
-}   FRAME_PSMP_ACTION, *PFRAME_PSMP_ACTION;
-
-typedef struct PACKED _FRAME_ACTION_HDR {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-}   FRAME_ACTION_HDR, *PFRAME_ACTION_HDR;
-
-//Action Frame
-//Action Frame  Category:Spectrum,  Action:Channel Switch. 7.3.2.20
-typedef struct PACKED _CHAN_SWITCH_ANNOUNCE {
-	UCHAR					ElementID;	// ID = IE_CHANNEL_SWITCH_ANNOUNCEMENT = 37
-	UCHAR					Len;
-	CHA_SWITCH_ANNOUNCE_IE	CSAnnounceIe;
-}   CHAN_SWITCH_ANNOUNCE, *PCHAN_SWITCH_ANNOUNCE;
-
-
-//802.11n : 7.3.2.20a
-typedef struct PACKED _SECOND_CHAN_OFFSET {
-	UCHAR				ElementID;		// ID = IE_SECONDARY_CH_OFFSET = 62
-	UCHAR				Len;
-	SEC_CHA_OFFSET_IE	SecChOffsetIe;
-}   SECOND_CHAN_OFFSET, *PSECOND_CHAN_OFFSET;
-
-
-typedef struct PACKED _FRAME_SPETRUM_CS {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	CHAN_SWITCH_ANNOUNCE	CSAnnounce;
-	SECOND_CHAN_OFFSET		SecondChannel;
-}   FRAME_SPETRUM_CS, *PFRAME_SPETRUM_CS;
-
-
-typedef struct PACKED _FRAME_ADDBA_REQ {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	UCHAR	Token;	// 1
-	BA_PARM		BaParm;	      //  2 - 10
-	USHORT		TimeOutValue;	// 0 - 0
-	BASEQ_CONTROL	BaStartSeq; // 0-0
-}   FRAME_ADDBA_REQ, *PFRAME_ADDBA_REQ;
-
-typedef struct PACKED _FRAME_ADDBA_RSP {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	UCHAR	Token;
-	USHORT	StatusCode;
-	BA_PARM		BaParm; //0 - 2
-	USHORT		TimeOutValue;
-}   FRAME_ADDBA_RSP, *PFRAME_ADDBA_RSP;
-
-typedef struct PACKED _FRAME_DELBA_REQ {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	DELBA_PARM		DelbaParm;
-	USHORT	ReasonCode;
-}   FRAME_DELBA_REQ, *PFRAME_DELBA_REQ;
-
-
-//7.2.1.7
-typedef struct PACKED _FRAME_BAR {
-	FRAME_CONTROL   FC;
-	USHORT          Duration;
-	UCHAR           Addr1[MAC_ADDR_LEN];
-	UCHAR           Addr2[MAC_ADDR_LEN];
-	BAR_CONTROL		BarControl;
-	BASEQ_CONTROL	StartingSeq;
-}   FRAME_BAR, *PFRAME_BAR;
-
-//7.2.1.7
-typedef struct PACKED _FRAME_BA {
-	FRAME_CONTROL   FC;
-	USHORT          Duration;
-	UCHAR           Addr1[MAC_ADDR_LEN];
-	UCHAR           Addr2[MAC_ADDR_LEN];
-	BAR_CONTROL		BarControl;
-	BASEQ_CONTROL	StartingSeq;
-	UCHAR		bitmask[8];
-}   FRAME_BA, *PFRAME_BA;
-
-
-// Radio Measuement Request Frame Format
-typedef struct PACKED _FRAME_RM_REQ_ACTION {
-	HEADER_802_11   Hdr;
-	UCHAR	Category;
-	UCHAR	Action;
-	UCHAR	Token;
-	USHORT	Repetition;
-	UCHAR   data[0];
-}   FRAME_RM_REQ_ACTION, *PFRAME_RM_REQ_ACTION;
-
-typedef struct PACKED {
-	UCHAR		ID;
-	UCHAR		Length;
-	UCHAR		ChannelSwitchMode;
-	UCHAR		NewRegClass;
-	UCHAR		NewChannelNum;
-	UCHAR		ChannelSwitchCount;
-} HT_EXT_CHANNEL_SWITCH_ANNOUNCEMENT_IE, *PHT_EXT_CHANNEL_SWITCH_ANNOUNCEMENT_IE;
-
-
-//
-// _Limit must be the 2**n - 1
-// _SEQ1 , _SEQ2 must be within 0 ~ _Limit
-//
-#define SEQ_STEPONE(_SEQ1, _SEQ2, _Limit)	((_SEQ1 == ((_SEQ2+1) & _Limit)))
-#define SEQ_SMALLER(_SEQ1, _SEQ2, _Limit)	(((_SEQ1-_SEQ2) & ((_Limit+1)>>1)))
-#define SEQ_LARGER(_SEQ1, _SEQ2, _Limit)	((_SEQ1 != _SEQ2) && !(((_SEQ1-_SEQ2) & ((_Limit+1)>>1))))
-#define SEQ_WITHIN_WIN(_SEQ1, _SEQ2, _WIN, _Limit) (SEQ_LARGER(_SEQ1, _SEQ2, _Limit) &&  \
-												SEQ_SMALLER(_SEQ1, ((_SEQ2+_WIN+1)&_Limit), _Limit))
-
-//
-// Contention-free parameter (without ID and Length)
-//
-typedef struct PACKED {
-    BOOLEAN     bValid;         // 1: variable contains valid value
-    UCHAR       CfpCount;
-    UCHAR       CfpPeriod;
-    USHORT      CfpMaxDuration;
-    USHORT      CfpDurRemaining;
-} CF_PARM, *PCF_PARM;
-
-typedef	struct	_CIPHER_SUITE	{
-	NDIS_802_11_ENCRYPTION_STATUS	PairCipher;		// Unicast cipher 1, this one has more secured cipher suite
-	NDIS_802_11_ENCRYPTION_STATUS	PairCipherAux;	// Unicast cipher 2 if AP announce two unicast cipher suite
-	NDIS_802_11_ENCRYPTION_STATUS	GroupCipher;	// Group cipher
-	USHORT							RsnCapability;	// RSN capability from beacon
-	BOOLEAN							bMixMode;		// Indicate Pair & Group cipher might be different
-}	CIPHER_SUITE, *PCIPHER_SUITE;
-
-// EDCA configuration from AP's BEACON/ProbeRsp
-typedef struct {
-    BOOLEAN     bValid;         // 1: variable contains valid value
-    BOOLEAN     bAdd;         // 1: variable contains valid value
-    BOOLEAN     bQAck;
-    BOOLEAN     bQueueRequest;
-    BOOLEAN     bTxopRequest;
-    BOOLEAN     bAPSDCapable;
-//  BOOLEAN     bMoreDataAck;
-    UCHAR       EdcaUpdateCount;
-    UCHAR       Aifsn[4];       // 0:AC_BK, 1:AC_BE, 2:AC_VI, 3:AC_VO
-    UCHAR       Cwmin[4];
-    UCHAR       Cwmax[4];
-    USHORT      Txop[4];      // in unit of 32-us
-    BOOLEAN     bACM[4];      // 1: Admission Control of AC_BK is mandattory
-} EDCA_PARM, *PEDCA_PARM;
-
-// QBSS LOAD information from QAP's BEACON/ProbeRsp
-typedef struct {
-    BOOLEAN     bValid;                     // 1: variable contains valid value
-    USHORT      StaNum;
-    UCHAR       ChannelUtilization;
-    USHORT      RemainingAdmissionControl;  // in unit of 32-us
-} QBSS_LOAD_PARM, *PQBSS_LOAD_PARM;
-
-// QBSS Info field in QSTA's assoc req
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR		Rsv2:1;
-	UCHAR		MaxSPLength:2;
-	UCHAR		Rsv1:1;
-	UCHAR		UAPSD_AC_BE:1;
-	UCHAR		UAPSD_AC_BK:1;
-	UCHAR		UAPSD_AC_VI:1;
-	UCHAR		UAPSD_AC_VO:1;
-#else
-    UCHAR		UAPSD_AC_VO:1;
-	UCHAR		UAPSD_AC_VI:1;
-	UCHAR		UAPSD_AC_BK:1;
-	UCHAR		UAPSD_AC_BE:1;
-	UCHAR		Rsv1:1;
-	UCHAR		MaxSPLength:2;
-	UCHAR		Rsv2:1;
-#endif /* !RT_BIG_ENDIAN */
-} QBSS_STA_INFO_PARM, *PQBSS_STA_INFO_PARM;
-
-// QBSS Info field in QAP's Beacon/ProbeRsp
-typedef struct PACKED {
-#ifdef RT_BIG_ENDIAN
-	UCHAR		UAPSD:1;
-	UCHAR		Rsv:3;
-    UCHAR		ParamSetCount:4;
-#else
-    UCHAR		ParamSetCount:4;
-	UCHAR		Rsv:3;
-	UCHAR		UAPSD:1;
-#endif /* !RT_BIG_ENDIAN */
-} QBSS_AP_INFO_PARM, *PQBSS_AP_INFO_PARM;
-
-// QOS Capability reported in QAP's BEACON/ProbeRsp
-// QOS Capability sent out in QSTA's AssociateReq/ReAssociateReq
-typedef struct {
-    BOOLEAN     bValid;                     // 1: variable contains valid value
-    BOOLEAN     bQAck;
-    BOOLEAN     bQueueRequest;
-    BOOLEAN     bTxopRequest;
-//  BOOLEAN     bMoreDataAck;
-    UCHAR       EdcaUpdateCount;
-} QOS_CAPABILITY_PARM, *PQOS_CAPABILITY_PARM;
-
-#ifdef CONFIG_STA_SUPPORT
-typedef struct {
-    UCHAR       IELen;
-    UCHAR       IE[MAX_CUSTOM_LEN];
-} WPA_IE_;
-#endif // CONFIG_STA_SUPPORT //
-
-
-typedef struct {
-    UCHAR   Bssid[MAC_ADDR_LEN];
-    UCHAR   Channel;
-	UCHAR   CentralChannel;	//Store the wide-band central channel for 40MHz.  .used in 40MHz AP. Or this is the same as Channel.
-    UCHAR   BssType;
-    USHORT  AtimWin;
-    USHORT  BeaconPeriod;
-
-    UCHAR   SupRate[MAX_LEN_OF_SUPPORTED_RATES];
-    UCHAR   SupRateLen;
-    UCHAR   ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-    UCHAR   ExtRateLen;
-	HT_CAPABILITY_IE HtCapability;
-	UCHAR			HtCapabilityLen;
-	ADD_HT_INFO_IE AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChanOffset;
-	CHAR    Rssi;
-    UCHAR   Privacy;			// Indicate security function ON/OFF. Don't mess up with auth mode.
-	UCHAR	Hidden;
-
-    USHORT  DtimPeriod;
-    USHORT  CapabilityInfo;
-
-    USHORT  CfpCount;
-    USHORT  CfpPeriod;
-    USHORT  CfpMaxDuration;
-    USHORT  CfpDurRemaining;
-    UCHAR   SsidLen;
-    CHAR    Ssid[MAX_LEN_OF_SSID];
-
-    ULONG   LastBeaconRxTime; // OS's timestamp
-
-	BOOLEAN	bSES;
-
-	// New for WPA2
-	CIPHER_SUITE					WPA;			// AP announced WPA cipher suite
-	CIPHER_SUITE					WPA2;			// AP announced WPA2 cipher suite
-
-	// New for microsoft WPA support
-	NDIS_802_11_FIXED_IEs	FixIEs;
-	NDIS_802_11_AUTHENTICATION_MODE	AuthModeAux;	// Addition mode for WPA2 / WPA capable AP
-	NDIS_802_11_AUTHENTICATION_MODE	AuthMode;
-	NDIS_802_11_WEP_STATUS	WepStatus;				// Unicast Encryption Algorithm extract from VAR_IE
-	USHORT					VarIELen;				// Length of next VIE include EID & Length
-	UCHAR					VarIEs[MAX_VIE_LEN];
-
-	// CCX Ckip information
-    UCHAR   CkipFlag;
-
-	// CCX 2 TSF
-	UCHAR	PTSF[4];		// Parent TSF
-	UCHAR	TTSF[8];		// Target TSF
-
-    // 802.11e d9, and WMM
-	EDCA_PARM           EdcaParm;
-	QOS_CAPABILITY_PARM QosCapability;
-	QBSS_LOAD_PARM      QbssLoad;
-#ifdef CONFIG_STA_SUPPORT
-    WPA_IE_     WpaIE;
-    WPA_IE_     RsnIE;
-#ifdef EXT_BUILD_CHANNEL_LIST
-	UCHAR		CountryString[3];
-	BOOLEAN		bHasCountryIE;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
-} BSS_ENTRY, *PBSS_ENTRY;
-
-typedef struct {
-    UCHAR           BssNr;
-    UCHAR           BssOverlapNr;
-    BSS_ENTRY       BssEntry[MAX_LEN_OF_BSS_TABLE];
-} BSS_TABLE, *PBSS_TABLE;
-
-
-typedef struct _MLME_QUEUE_ELEM {
-    ULONG             Machine;
-    ULONG             MsgType;
-    ULONG             MsgLen;
-    UCHAR             Msg[MGMT_DMA_BUFFER_SIZE];
-    LARGE_INTEGER     TimeStamp;
-    UCHAR             Rssi0;
-    UCHAR             Rssi1;
-    UCHAR             Rssi2;
-    UCHAR             Signal;
-    UCHAR             Channel;
-    UCHAR             Wcid;
-    BOOLEAN           Occupied;
-#ifdef MLME_EX
-	USHORT            Idx;
-#endif // MLME_EX //
-} MLME_QUEUE_ELEM, *PMLME_QUEUE_ELEM;
-
-typedef struct _MLME_QUEUE {
-    ULONG             Num;
-    ULONG             Head;
-    ULONG             Tail;
-    NDIS_SPIN_LOCK   Lock;
-    MLME_QUEUE_ELEM  Entry[MAX_LEN_OF_MLME_QUEUE];
-} MLME_QUEUE, *PMLME_QUEUE;
-
-typedef VOID (*STATE_MACHINE_FUNC)(VOID *Adaptor, MLME_QUEUE_ELEM *Elem);
-
-typedef struct _STATE_MACHINE {
-    ULONG                           Base;
-    ULONG                           NrState;
-    ULONG                           NrMsg;
-    ULONG                           CurrState;
-    STATE_MACHINE_FUNC             *TransFunc;
-} STATE_MACHINE, *PSTATE_MACHINE;
-
-
-// MLME AUX data structure that hold temporarliy settings during a connection attempt.
-// Once this attemp succeeds, all settings will be copy to pAd->StaActive.
-// A connection attempt (user set OID, roaming, CCX fast roaming,..) consists of
-// several steps (JOIN, AUTH, ASSOC or REASSOC) and may fail at any step. We purposely
-// separate this under-trial settings away from pAd->StaActive so that once
-// this new attempt failed, driver can auto-recover back to the active settings.
-typedef struct _MLME_AUX {
-    UCHAR               BssType;
-    UCHAR               Ssid[MAX_LEN_OF_SSID];
-    UCHAR               SsidLen;
-    UCHAR               Bssid[MAC_ADDR_LEN];
-	UCHAR				AutoReconnectSsid[MAX_LEN_OF_SSID];
-	UCHAR				AutoReconnectSsidLen;
-    USHORT              Alg;
-    UCHAR               ScanType;
-    UCHAR               Channel;
-	UCHAR               CentralChannel;
-    USHORT              Aid;
-    USHORT              CapabilityInfo;
-    USHORT              BeaconPeriod;
-    USHORT              CfpMaxDuration;
-    USHORT              CfpPeriod;
-    USHORT              AtimWin;
-
-	// Copy supported rate from desired AP's beacon. We are trying to match
-	// AP's supported and extended rate settings.
-	UCHAR		        SupRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		        ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		        SupRateLen;
-	UCHAR		        ExtRateLen;
-	HT_CAPABILITY_IE		HtCapability;
-	UCHAR		        	HtCapabilityLen;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			NewExtChannelOffset;
-	//RT_HT_CAPABILITY	SupportedHtPhy;
-
-    // new for QOS
-    QOS_CAPABILITY_PARM APQosCapability;    // QOS capability of the current associated AP
-    EDCA_PARM           APEdcaParm;         // EDCA parameters of the current associated AP
-    QBSS_LOAD_PARM      APQbssLoad;         // QBSS load of the current associated AP
-
-    // new to keep Ralink specific feature
-    ULONG               APRalinkIe;
-
-    BSS_TABLE           SsidBssTab;     // AP list for the same SSID
-    BSS_TABLE           RoamTab;        // AP list eligible for roaming
-    ULONG               BssIdx;
-    ULONG               RoamIdx;
-
-	BOOLEAN				CurrReqIsFromNdis;
-
-    RALINK_TIMER_STRUCT BeaconTimer, ScanTimer;
-    RALINK_TIMER_STRUCT AuthTimer;
-    RALINK_TIMER_STRUCT AssocTimer, ReassocTimer, DisassocTimer;
-} MLME_AUX, *PMLME_AUX;
-
-typedef struct _MLME_ADDBA_REQ_STRUCT{
-	UCHAR   Wcid;	//
-	UCHAR   pAddr[MAC_ADDR_LEN];
-	UCHAR   BaBufSize;
-	USHORT	TimeOutValue;
-	UCHAR   TID;
-	UCHAR   Token;
-	USHORT	BaStartSeq;
-} MLME_ADDBA_REQ_STRUCT, *PMLME_ADDBA_REQ_STRUCT;
-
-
-typedef struct _MLME_DELBA_REQ_STRUCT{
-	UCHAR   Wcid;	//
-	UCHAR     Addr[MAC_ADDR_LEN];
-	UCHAR   TID;
-	UCHAR	Initiator;
-} MLME_DELBA_REQ_STRUCT, *PMLME_DELBA_REQ_STRUCT;
-
-// assoc struct is equal to reassoc
-typedef struct _MLME_ASSOC_REQ_STRUCT{
-    UCHAR     Addr[MAC_ADDR_LEN];
-    USHORT    CapabilityInfo;
-    USHORT    ListenIntv;
-    ULONG     Timeout;
-} MLME_ASSOC_REQ_STRUCT, *PMLME_ASSOC_REQ_STRUCT, MLME_REASSOC_REQ_STRUCT, *PMLME_REASSOC_REQ_STRUCT;
-
-typedef struct _MLME_DISASSOC_REQ_STRUCT{
-    UCHAR     Addr[MAC_ADDR_LEN];
-    USHORT    Reason;
-} MLME_DISASSOC_REQ_STRUCT, *PMLME_DISASSOC_REQ_STRUCT;
-
-typedef struct _MLME_AUTH_REQ_STRUCT {
-    UCHAR        Addr[MAC_ADDR_LEN];
-    USHORT       Alg;
-    ULONG        Timeout;
-} MLME_AUTH_REQ_STRUCT, *PMLME_AUTH_REQ_STRUCT;
-
-typedef struct _MLME_DEAUTH_REQ_STRUCT {
-    UCHAR        Addr[MAC_ADDR_LEN];
-    USHORT       Reason;
-} MLME_DEAUTH_REQ_STRUCT, *PMLME_DEAUTH_REQ_STRUCT;
-
-typedef struct {
-    ULONG      BssIdx;
-} MLME_JOIN_REQ_STRUCT;
-
-typedef struct _MLME_SCAN_REQ_STRUCT {
-    UCHAR      Bssid[MAC_ADDR_LEN];
-    UCHAR      BssType;
-    UCHAR      ScanType;
-    UCHAR      SsidLen;
-    CHAR       Ssid[MAX_LEN_OF_SSID];
-} MLME_SCAN_REQ_STRUCT, *PMLME_SCAN_REQ_STRUCT;
-
-typedef struct _MLME_START_REQ_STRUCT {
-    CHAR        Ssid[MAX_LEN_OF_SSID];
-    UCHAR       SsidLen;
-} MLME_START_REQ_STRUCT, *PMLME_START_REQ_STRUCT;
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-// structure for DLS
-typedef struct _RT_802_11_DLS {
-	USHORT						TimeOut;		// Use to time out while slience, unit: second , set by UI
-	USHORT						CountDownTimer;	// Use to time out while slience,unit: second , used by driver only
-	NDIS_802_11_MAC_ADDRESS		MacAddr;		// set by UI
-	UCHAR						Status;			// 0: none , 1: wait STAkey, 2: finish DLS setup , set by driver only
-	BOOLEAN						Valid;			// 1: valid , 0: invalid , set by UI, use to setup or tear down DLS link
-	RALINK_TIMER_STRUCT			Timer;			// Use to time out while handshake
-	USHORT						Sequence;
-	USHORT						MacTabMatchWCID;	// ASIC
-	BOOLEAN						bHTCap;
-	PVOID						pAd;
-} RT_802_11_DLS, *PRT_802_11_DLS;
-
-typedef struct _MLME_DLS_REQ_STRUCT {
-    PRT_802_11_DLS	pDLS;
-    USHORT			Reason;
-} MLME_DLS_REQ_STRUCT, *PMLME_DLS_REQ_STRUCT;
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-typedef struct PACKED {
-    UCHAR   Eid;
-    UCHAR   Len;
-    CHAR   Octet[1];
-} EID_STRUCT,*PEID_STRUCT, BEACON_EID_STRUCT, *PBEACON_EID_STRUCT;
-
-typedef struct PACKED _RTMP_TX_RATE_SWITCH
-{
-	UCHAR   ItemNo;
-#ifdef RT_BIG_ENDIAN
-	UCHAR	Rsv2:2;
-	UCHAR	Mode:2;
-	UCHAR	Rsv1:1;
-	UCHAR	BW:1;
-	UCHAR	ShortGI:1;
-	UCHAR	STBC:1;
-#else
-	UCHAR	STBC:1;
-	UCHAR	ShortGI:1;
-	UCHAR	BW:1;
-	UCHAR	Rsv1:1;
-	UCHAR	Mode:2;
-	UCHAR	Rsv2:2;
-#endif
-	UCHAR   CurrMCS;
-	UCHAR   TrainUp;
-	UCHAR   TrainDown;
-} RRTMP_TX_RATE_SWITCH, *PRTMP_TX_RATE_SWITCH;
-
-// ========================== AP mlme.h ===============================
-#define TBTT_PRELOAD_TIME       384        // usec. LomgPreamble + 24-byte at 1Mbps
-#define DEFAULT_DTIM_PERIOD     1
-
-// weighting factor to calculate Channel quality, total should be 100%
-//#define RSSI_WEIGHTING                   0
-//#define TX_WEIGHTING                     40
-//#define RX_WEIGHTING                     60
-
-#define MAC_TABLE_AGEOUT_TIME			300			// unit: sec
-#define MAC_TABLE_ASSOC_TIMEOUT			5			// unit: sec
-#define MAC_TABLE_FULL(Tab)				((Tab).size == MAX_LEN_OF_MAC_TABLE)
-
-// AP shall drop the sta if contine Tx fail count reach it.
-#define MAC_ENTRY_LIFE_CHECK_CNT		20			// packet cnt.
-
-// Value domain of pMacEntry->Sst
-typedef enum _Sst {
-    SST_NOT_AUTH,   // 0: equivalent to IEEE 802.11/1999 state 1
-    SST_AUTH,       // 1: equivalent to IEEE 802.11/1999 state 2
-    SST_ASSOC       // 2: equivalent to IEEE 802.11/1999 state 3
-} SST;
-
-// value domain of pMacEntry->AuthState
-typedef enum _AuthState {
-    AS_NOT_AUTH,
-    AS_AUTH_OPEN,       // STA has been authenticated using OPEN SYSTEM
-    AS_AUTH_KEY,        // STA has been authenticated using SHARED KEY
-    AS_AUTHENTICATING   // STA is waiting for AUTH seq#3 using SHARED KEY
-} AUTH_STATE;
-
-//for-wpa value domain of pMacEntry->WpaState  802.1i D3   p.114
-typedef enum _ApWpaState {
-    AS_NOTUSE,              // 0
-    AS_DISCONNECT,          // 1
-    AS_DISCONNECTED,        // 2
-    AS_INITIALIZE,          // 3
-    AS_AUTHENTICATION,      // 4
-    AS_AUTHENTICATION2,     // 5
-    AS_INITPMK,             // 6
-    AS_INITPSK,             // 7
-    AS_PTKSTART,            // 8
-    AS_PTKINIT_NEGOTIATING, // 9
-    AS_PTKINITDONE,         // 10
-    AS_UPDATEKEYS,          // 11
-    AS_INTEGRITY_FAILURE,   // 12
-    AS_KEYUPDATE,           // 13
-} AP_WPA_STATE;
-
-// for-wpa value domain of pMacEntry->WpaState  802.1i D3   p.114
-typedef enum _GTKState {
-    REKEY_NEGOTIATING,
-    REKEY_ESTABLISHED,
-    KEYERROR,
-} GTK_STATE;
-
-//  for-wpa  value domain of pMacEntry->WpaState  802.1i D3   p.114
-typedef enum _WpaGTKState {
-    SETKEYS,
-    SETKEYS_DONE,
-} WPA_GTK_STATE;
-// ====================== end of AP mlme.h ============================
-
-
-#endif	// MLME_H__
+#include "../rt2870/mlme.h"
diff --git a/drivers/staging/rt3070/netif_block.h b/drivers/staging/rt3070/netif_block.h
deleted file mode 100644
index 6e5151c..0000000
--- a/drivers/staging/rt3070/netif_block.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#ifndef __NET_IF_BLOCK_H__
-#define __NET_IF_BLOCK_H__
-
-//#include <linux/device.h>
-#include "link_list.h"
-#include "rtmp.h"
-
-#define FREE_NETIF_POOL_SIZE 32
-
-typedef struct _NETIF_ENTRY
-{
-	struct _NETIF_ENTRY *pNext;
-	PNET_DEV pNetDev;
-} NETIF_ENTRY, *PNETIF_ENTRY;
-
-void initblockQueueTab(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN blockNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry,
-	IN PNET_DEV pNetDev);
-
-VOID releaseNetIf(
-	IN PBLOCK_QUEUE_ENTRY pBlockQueueEntry);
-
-VOID StopNetIfQueue(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR QueIdx,
-	IN PNDIS_PACKET pPacket);
-#endif // __NET_IF_BLOCK_H__
-
diff --git a/drivers/staging/rt3070/oid.h b/drivers/staging/rt3070/oid.h
index f78bf0a..cbf16a8 100644
--- a/drivers/staging/rt3070/oid.h
+++ b/drivers/staging/rt3070/oid.h
@@ -1,1142 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	oid.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-*/
-#ifndef _OID_H_
-#define _OID_H_
-
-//#include <linux/wireless.h>
-
-
-#define TRUE				1
-#define FALSE				0
-//
-// IEEE 802.11 Structures and definitions
-//
-#define MAX_TX_POWER_LEVEL              100   /* mW */
-#define MAX_RSSI_TRIGGER                -10    /* dBm */
-#define MIN_RSSI_TRIGGER                -200   /* dBm */
-#define MAX_FRAG_THRESHOLD              2346  /* byte count */
-#define MIN_FRAG_THRESHOLD              256   /* byte count */
-#define MAX_RTS_THRESHOLD               2347  /* byte count */
-
-// new types for Media Specific Indications
-// Extension channel offset
-#define EXTCHA_NONE			0
-#define EXTCHA_ABOVE		0x1
-#define EXTCHA_BELOW		0x3
-
-// BW
-#define BAND_WIDTH_20		0
-#define BAND_WIDTH_40		1
-#define BAND_WIDTH_BOTH		2
-#define BAND_WIDTH_10		3	// 802.11j has 10MHz. This definition is for internal usage. doesn't fill in the IE or other field.
-// SHORTGI
-#define GAP_INTERVAL_400	1	// only support in HT mode
-#define GAP_INTERVAL_800	0
-#define GAP_INTERVAL_BOTH	2
-
-#define NdisMediaStateConnected			1
-#define NdisMediaStateDisconnected		0
-
-#define NDIS_802_11_LENGTH_SSID         32
-#define NDIS_802_11_LENGTH_RATES        8
-#define NDIS_802_11_LENGTH_RATES_EX     16
-#define MAC_ADDR_LENGTH                 6
-#define MAX_NUM_OF_CHS					49 // 14 channels @2.4G +  12@UNII + 4 @MMAC + 11 @HiperLAN2 + 7 @Japan + 1 as NULL terminationc
-#define MAX_NUMBER_OF_EVENT				10  // entry # in EVENT table
-#define MAX_NUMBER_OF_MAC				32 // if MAX_MBSSID_NUM is 8, this value can't be larger than 211
-#define MAX_NUMBER_OF_ACL				64
-#define MAX_LENGTH_OF_SUPPORT_RATES		12    // 1, 2, 5.5, 11, 6, 9, 12, 18, 24, 36, 48, 54
-#define MAX_NUMBER_OF_DLS_ENTRY			4
-
-
-
-#ifndef UNDER_CE
-// OID definition, since NDIS 5.0 didn't define these, we need to define for our own
-//#if _WIN32_WINNT<=0x0500
-
-#define OID_GEN_MACHINE_NAME               0x0001021A
-
-#ifdef RALINK_ATE
-#define RT_QUERY_ATE_TXDONE_COUNT			0x0401
-#endif // RALINK_ATE //
-#define RT_QUERY_SIGNAL_CONTEXT				0x0402
-#define RT_SET_IAPP_PID                 	0x0404
-#define RT_SET_APD_PID						0x0405
-#define RT_SET_DEL_MAC_ENTRY				0x0406
-
-//
-// IEEE 802.11 OIDs
-//
-#define	OID_GET_SET_TOGGLE			0x8000
-
-#define	OID_802_11_NETWORK_TYPES_SUPPORTED			0x0103
-#define	OID_802_11_NETWORK_TYPE_IN_USE				0x0104
-#define	OID_802_11_RSSI_TRIGGER						0x0107
-#define	RT_OID_802_11_RSSI							0x0108 //rt2860	only , kathy
-#define	RT_OID_802_11_RSSI_1						0x0109 //rt2860	only , kathy
-#define	RT_OID_802_11_RSSI_2						0x010A //rt2860	only , kathy
-#define	OID_802_11_NUMBER_OF_ANTENNAS				0x010B
-#define	OID_802_11_RX_ANTENNA_SELECTED				0x010C
-#define	OID_802_11_TX_ANTENNA_SELECTED				0x010D
-#define	OID_802_11_SUPPORTED_RATES					0x010E
-#define	OID_802_11_ADD_WEP							0x0112
-#define	OID_802_11_REMOVE_WEP						0x0113
-#define	OID_802_11_DISASSOCIATE						0x0114
-#define	OID_802_11_PRIVACY_FILTER					0x0118
-#define	OID_802_11_ASSOCIATION_INFORMATION			0x011E
-#define	OID_802_11_TEST								0x011F
-#define	RT_OID_802_11_COUNTRY_REGION				0x0507
-#define	OID_802_11_BSSID_LIST_SCAN					0x0508
-#define	OID_802_11_SSID								0x0509
-#define	OID_802_11_BSSID							0x050A
-#define	RT_OID_802_11_RADIO							0x050B
-#define	RT_OID_802_11_PHY_MODE						0x050C
-#define	RT_OID_802_11_STA_CONFIG					0x050D
-#define	OID_802_11_DESIRED_RATES					0x050E
-#define	RT_OID_802_11_PREAMBLE						0x050F
-#define	OID_802_11_WEP_STATUS						0x0510
-#define	OID_802_11_AUTHENTICATION_MODE				0x0511
-#define	OID_802_11_INFRASTRUCTURE_MODE				0x0512
-#define	RT_OID_802_11_RESET_COUNTERS				0x0513
-#define	OID_802_11_RTS_THRESHOLD					0x0514
-#define	OID_802_11_FRAGMENTATION_THRESHOLD			0x0515
-#define	OID_802_11_POWER_MODE						0x0516
-#define	OID_802_11_TX_POWER_LEVEL					0x0517
-#define	RT_OID_802_11_ADD_WPA						0x0518
-#define	OID_802_11_REMOVE_KEY						0x0519
-#define	OID_802_11_ADD_KEY							0x0520
-#define	OID_802_11_CONFIGURATION					0x0521
-#define	OID_802_11_TX_PACKET_BURST					0x0522
-#define	RT_OID_802_11_QUERY_NOISE_LEVEL				0x0523
-#define	RT_OID_802_11_EXTRA_INFO					0x0524
-#ifdef	DBG
-#define	RT_OID_802_11_HARDWARE_REGISTER				0x0525
-#endif
-#define OID_802_11_ENCRYPTION_STATUS            OID_802_11_WEP_STATUS
-#define OID_802_11_DEAUTHENTICATION                 0x0526
-#define OID_802_11_DROP_UNENCRYPTED                 0x0527
-#define OID_802_11_MIC_FAILURE_REPORT_FRAME         0x0528
-
-// For 802.1x daemin using to require current driver configuration
-#define OID_802_11_RADIUS_QUERY_SETTING				0x0540
-
-#define	RT_OID_DEVICE_NAME							0x0607
-#define	RT_OID_VERSION_INFO							0x0608
-#define	OID_802_11_BSSID_LIST						0x0609
-#define	OID_802_3_CURRENT_ADDRESS					0x060A
-#define	OID_GEN_MEDIA_CONNECT_STATUS				0x060B
-#define	RT_OID_802_11_QUERY_LINK_STATUS				0x060C
-#define	OID_802_11_RSSI								0x060D
-#define	OID_802_11_STATISTICS						0x060E
-#define	OID_GEN_RCV_OK								0x060F
-#define	OID_GEN_RCV_NO_BUFFER						0x0610
-#define	RT_OID_802_11_QUERY_EEPROM_VERSION			0x0611
-#define	RT_OID_802_11_QUERY_FIRMWARE_VERSION		0x0612
-#define	RT_OID_802_11_QUERY_LAST_RX_RATE			0x0613
-#define	RT_OID_802_11_TX_POWER_LEVEL_1				0x0614
-#define	RT_OID_802_11_QUERY_PIDVID					0x0615
-//for WPA_SUPPLICANT_SUPPORT
-#define OID_SET_COUNTERMEASURES                     0x0616
-#define OID_802_11_SET_IEEE8021X                    0x0617
-#define OID_802_11_SET_IEEE8021X_REQUIRE_KEY        0x0618
-#define OID_802_11_PMKID                            0x0620
-#define RT_OID_WPA_SUPPLICANT_SUPPORT               0x0621
-#define RT_OID_WE_VERSION_COMPILED                  0x0622
-#define RT_OID_NEW_DRIVER                           0x0623
-
-
-//rt2860 , kathy
-#define	RT_OID_802_11_SNR_0							0x0630
-#define	RT_OID_802_11_SNR_1							0x0631
-#define	RT_OID_802_11_QUERY_LAST_TX_RATE			0x0632
-#define	RT_OID_802_11_QUERY_HT_PHYMODE				0x0633
-#define	RT_OID_802_11_SET_HT_PHYMODE				0x0634
-#define	OID_802_11_RELOAD_DEFAULTS					0x0635
-#define	RT_OID_802_11_QUERY_APSD_SETTING			0x0636
-#define	RT_OID_802_11_SET_APSD_SETTING				0x0637
-#define	RT_OID_802_11_QUERY_APSD_PSM				0x0638
-#define	RT_OID_802_11_SET_APSD_PSM					0x0639
-#define	RT_OID_802_11_QUERY_DLS						0x063A
-#define	RT_OID_802_11_SET_DLS						0x063B
-#define	RT_OID_802_11_QUERY_DLS_PARAM				0x063C
-#define	RT_OID_802_11_SET_DLS_PARAM					0x063D
-#define RT_OID_802_11_QUERY_WMM              		0x063E
-#define RT_OID_802_11_SET_WMM      					0x063F
-#define RT_OID_802_11_QUERY_IMME_BA_CAP				0x0640
-#define RT_OID_802_11_SET_IMME_BA_CAP				0x0641
-#define RT_OID_802_11_QUERY_BATABLE					0x0642
-#define RT_OID_802_11_ADD_IMME_BA					0x0643
-#define RT_OID_802_11_TEAR_IMME_BA					0x0644
-#define RT_OID_DRIVER_DEVICE_NAME                   0x0645
-#define RT_OID_802_11_QUERY_DAT_HT_PHYMODE          0x0646
-#define RT_OID_QUERY_MULTIPLE_CARD_SUPPORT          0x0647
-
-// Ralink defined OIDs
-// Dennis Lee move to platform specific
-
-#define	RT_OID_802_11_BSSID					  (OID_GET_SET_TOGGLE |	OID_802_11_BSSID)
-#define	RT_OID_802_11_SSID					  (OID_GET_SET_TOGGLE |	OID_802_11_SSID)
-#define	RT_OID_802_11_INFRASTRUCTURE_MODE	  (OID_GET_SET_TOGGLE |	OID_802_11_INFRASTRUCTURE_MODE)
-#define	RT_OID_802_11_ADD_WEP				  (OID_GET_SET_TOGGLE |	OID_802_11_ADD_WEP)
-#define	RT_OID_802_11_ADD_KEY				  (OID_GET_SET_TOGGLE |	OID_802_11_ADD_KEY)
-#define	RT_OID_802_11_REMOVE_WEP			  (OID_GET_SET_TOGGLE |	OID_802_11_REMOVE_WEP)
-#define	RT_OID_802_11_REMOVE_KEY			  (OID_GET_SET_TOGGLE |	OID_802_11_REMOVE_KEY)
-#define	RT_OID_802_11_DISASSOCIATE			  (OID_GET_SET_TOGGLE |	OID_802_11_DISASSOCIATE)
-#define	RT_OID_802_11_AUTHENTICATION_MODE	  (OID_GET_SET_TOGGLE |	OID_802_11_AUTHENTICATION_MODE)
-#define	RT_OID_802_11_PRIVACY_FILTER		  (OID_GET_SET_TOGGLE |	OID_802_11_PRIVACY_FILTER)
-#define	RT_OID_802_11_BSSID_LIST_SCAN		  (OID_GET_SET_TOGGLE |	OID_802_11_BSSID_LIST_SCAN)
-#define	RT_OID_802_11_WEP_STATUS			  (OID_GET_SET_TOGGLE |	OID_802_11_WEP_STATUS)
-#define	RT_OID_802_11_RELOAD_DEFAULTS		  (OID_GET_SET_TOGGLE |	OID_802_11_RELOAD_DEFAULTS)
-#define	RT_OID_802_11_NETWORK_TYPE_IN_USE	  (OID_GET_SET_TOGGLE |	OID_802_11_NETWORK_TYPE_IN_USE)
-#define	RT_OID_802_11_TX_POWER_LEVEL		  (OID_GET_SET_TOGGLE |	OID_802_11_TX_POWER_LEVEL)
-#define	RT_OID_802_11_RSSI_TRIGGER			  (OID_GET_SET_TOGGLE |	OID_802_11_RSSI_TRIGGER)
-#define	RT_OID_802_11_FRAGMENTATION_THRESHOLD (OID_GET_SET_TOGGLE |	OID_802_11_FRAGMENTATION_THRESHOLD)
-#define	RT_OID_802_11_RTS_THRESHOLD			  (OID_GET_SET_TOGGLE |	OID_802_11_RTS_THRESHOLD)
-#define	RT_OID_802_11_RX_ANTENNA_SELECTED	  (OID_GET_SET_TOGGLE |	OID_802_11_RX_ANTENNA_SELECTED)
-#define	RT_OID_802_11_TX_ANTENNA_SELECTED	  (OID_GET_SET_TOGGLE |	OID_802_11_TX_ANTENNA_SELECTED)
-#define	RT_OID_802_11_SUPPORTED_RATES		  (OID_GET_SET_TOGGLE |	OID_802_11_SUPPORTED_RATES)
-#define	RT_OID_802_11_DESIRED_RATES			  (OID_GET_SET_TOGGLE |	OID_802_11_DESIRED_RATES)
-#define	RT_OID_802_11_CONFIGURATION			  (OID_GET_SET_TOGGLE |	OID_802_11_CONFIGURATION)
-#define	RT_OID_802_11_POWER_MODE			  (OID_GET_SET_TOGGLE |	OID_802_11_POWER_MODE)
-
-
-
-typedef enum _NDIS_802_11_STATUS_TYPE
-{
-    Ndis802_11StatusType_Authentication,
-    Ndis802_11StatusType_MediaStreamMode,
-    Ndis802_11StatusType_PMKID_CandidateList,
-    Ndis802_11StatusTypeMax    // not a real type, defined as an upper bound
-} NDIS_802_11_STATUS_TYPE, *PNDIS_802_11_STATUS_TYPE;
-
-typedef UCHAR   NDIS_802_11_MAC_ADDRESS[6];
-
-typedef struct _NDIS_802_11_STATUS_INDICATION
-{
-    NDIS_802_11_STATUS_TYPE StatusType;
-} NDIS_802_11_STATUS_INDICATION, *PNDIS_802_11_STATUS_INDICATION;
-
-// mask for authentication/integrity fields
-#define NDIS_802_11_AUTH_REQUEST_AUTH_FIELDS        0x0f
-
-#define NDIS_802_11_AUTH_REQUEST_REAUTH             0x01
-#define NDIS_802_11_AUTH_REQUEST_KEYUPDATE          0x02
-#define NDIS_802_11_AUTH_REQUEST_PAIRWISE_ERROR     0x06
-#define NDIS_802_11_AUTH_REQUEST_GROUP_ERROR        0x0E
-
-typedef struct _NDIS_802_11_AUTHENTICATION_REQUEST
-{
-    ULONG Length;            // Length of structure
-    NDIS_802_11_MAC_ADDRESS Bssid;
-    ULONG Flags;
-} NDIS_802_11_AUTHENTICATION_REQUEST, *PNDIS_802_11_AUTHENTICATION_REQUEST;
-
-//Added new types for PMKID Candidate lists.
-typedef struct _PMKID_CANDIDATE {
-    NDIS_802_11_MAC_ADDRESS BSSID;
-    ULONG Flags;
-} PMKID_CANDIDATE, *PPMKID_CANDIDATE;
-
-typedef struct _NDIS_802_11_PMKID_CANDIDATE_LIST
-{
-    ULONG Version;       // Version of the structure
-    ULONG NumCandidates; // No. of pmkid candidates
-    PMKID_CANDIDATE CandidateList[1];
-} NDIS_802_11_PMKID_CANDIDATE_LIST, *PNDIS_802_11_PMKID_CANDIDATE_LIST;
-
-//Flags for PMKID Candidate list structure
-#define NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED	0x01
-
-// Added new types for OFDM 5G and 2.4G
-typedef enum _NDIS_802_11_NETWORK_TYPE
-{
-   Ndis802_11FH,
-   Ndis802_11DS,
-    Ndis802_11OFDM5,
-    Ndis802_11OFDM5_N,
-    Ndis802_11OFDM24,
-    Ndis802_11OFDM24_N,
-   Ndis802_11Automode,
-    Ndis802_11NetworkTypeMax    // not a real type, defined as an upper bound
-} NDIS_802_11_NETWORK_TYPE, *PNDIS_802_11_NETWORK_TYPE;
-
-typedef struct _NDIS_802_11_NETWORK_TYPE_LIST
-{
-    UINT                       NumberOfItems;  // in list below, at least 1
-   NDIS_802_11_NETWORK_TYPE    NetworkType [1];
-} NDIS_802_11_NETWORK_TYPE_LIST, *PNDIS_802_11_NETWORK_TYPE_LIST;
-
-typedef enum _NDIS_802_11_POWER_MODE
-{
-    Ndis802_11PowerModeCAM,
-    Ndis802_11PowerModeMAX_PSP,
-    Ndis802_11PowerModeFast_PSP,
-    Ndis802_11PowerModeLegacy_PSP,
-    Ndis802_11PowerModeMax      // not a real mode, defined as an upper bound
-} NDIS_802_11_POWER_MODE, *PNDIS_802_11_POWER_MODE;
-
-typedef ULONG   NDIS_802_11_TX_POWER_LEVEL; // in milliwatts
-
-//
-// Received Signal Strength Indication
-//
-typedef LONG    NDIS_802_11_RSSI;           // in dBm
-
-typedef struct _NDIS_802_11_CONFIGURATION_FH
-{
-   ULONG           Length;            // Length of structure
-   ULONG           HopPattern;        // As defined by 802.11, MSB set
-   ULONG           HopSet;            // to one if non-802.11
-   ULONG           DwellTime;         // units are Kusec
-} NDIS_802_11_CONFIGURATION_FH, *PNDIS_802_11_CONFIGURATION_FH;
-
-typedef struct _NDIS_802_11_CONFIGURATION
-{
-   ULONG                           Length;             // Length of structure
-   ULONG                           BeaconPeriod;       // units are Kusec
-   ULONG                           ATIMWindow;         // units are Kusec
-   ULONG                           DSConfig;           // Frequency, units are kHz
-   NDIS_802_11_CONFIGURATION_FH    FHConfig;
-} NDIS_802_11_CONFIGURATION, *PNDIS_802_11_CONFIGURATION;
-
-typedef struct _NDIS_802_11_STATISTICS
-{
-   ULONG           Length;             // Length of structure
-   LARGE_INTEGER   TransmittedFragmentCount;
-   LARGE_INTEGER   MulticastTransmittedFrameCount;
-   LARGE_INTEGER   FailedCount;
-   LARGE_INTEGER   RetryCount;
-   LARGE_INTEGER   MultipleRetryCount;
-   LARGE_INTEGER   RTSSuccessCount;
-   LARGE_INTEGER   RTSFailureCount;
-   LARGE_INTEGER   ACKFailureCount;
-   LARGE_INTEGER   FrameDuplicateCount;
-   LARGE_INTEGER   ReceivedFragmentCount;
-   LARGE_INTEGER   MulticastReceivedFrameCount;
-   LARGE_INTEGER   FCSErrorCount;
-   LARGE_INTEGER   TKIPLocalMICFailures;
-   LARGE_INTEGER   TKIPRemoteMICErrors;
-   LARGE_INTEGER   TKIPICVErrors;
-   LARGE_INTEGER   TKIPCounterMeasuresInvoked;
-   LARGE_INTEGER   TKIPReplays;
-   LARGE_INTEGER   CCMPFormatErrors;
-   LARGE_INTEGER   CCMPReplays;
-   LARGE_INTEGER   CCMPDecryptErrors;
-   LARGE_INTEGER   FourWayHandshakeFailures;
-} NDIS_802_11_STATISTICS, *PNDIS_802_11_STATISTICS;
-
-typedef  ULONG  NDIS_802_11_KEY_INDEX;
-typedef ULONGLONG   NDIS_802_11_KEY_RSC;
-
-#define MAX_RADIUS_SRV_NUM			2	  // 802.1x failover number
-
-typedef struct PACKED _RADIUS_SRV_INFO {
-	UINT32			radius_ip;
-	UINT32			radius_port;
-	UCHAR			radius_key[64];
-	UCHAR			radius_key_len;
-} RADIUS_SRV_INFO, *PRADIUS_SRV_INFO;
-
-typedef struct PACKED _RADIUS_KEY_INFO
-{
-	UCHAR			radius_srv_num;
-	RADIUS_SRV_INFO	radius_srv_info[MAX_RADIUS_SRV_NUM];
-	UCHAR			ieee8021xWEP;		 // dynamic WEP
-    UCHAR           key_index;
-    UCHAR           key_length;          // length of key in bytes
-    UCHAR           key_material[13];
-} RADIUS_KEY_INFO, *PRADIUS_KEY_INFO;
-
-// It's used by 802.1x daemon to require relative configuration
-typedef struct PACKED _RADIUS_CONF
-{
-    UINT32          Length;             // Length of this structure
-    UCHAR			mbss_num;			// indicate multiple BSS number
-	UINT32			own_ip_addr;
-	UINT32			retry_interval;
-	UINT32			session_timeout_interval;
-	UCHAR			EAPifname[IFNAMSIZ];
-	UCHAR			EAPifname_len;
-	UCHAR 			PreAuthifname[IFNAMSIZ];
-	UCHAR			PreAuthifname_len;
-	RADIUS_KEY_INFO	RadiusInfo[8/*MAX_MBSSID_NUM*/];
-} RADIUS_CONF, *PRADIUS_CONF;
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-// Key mapping keys require a BSSID
-typedef struct _NDIS_802_11_KEY
-{
-    UINT           Length;             // Length of this structure
-    UINT           KeyIndex;
-    UINT           KeyLength;          // length of key in bytes
-    NDIS_802_11_MAC_ADDRESS BSSID;
-    NDIS_802_11_KEY_RSC KeyRSC;
-    UCHAR           KeyMaterial[1];     // variable length depending on above field
-} NDIS_802_11_KEY, *PNDIS_802_11_KEY;
-#endif // CONFIG_STA_SUPPORT //
-
-typedef struct _NDIS_802_11_REMOVE_KEY
-{
-    UINT           Length;             // Length of this structure
-    UINT           KeyIndex;
-    NDIS_802_11_MAC_ADDRESS BSSID;
-} NDIS_802_11_REMOVE_KEY, *PNDIS_802_11_REMOVE_KEY;
-
-typedef struct _NDIS_802_11_WEP
-{
-   UINT     Length;        // Length of this structure
-   UINT     KeyIndex;           // 0 is the per-client key, 1-N are the
-                                        // global keys
-   UINT     KeyLength;     // length of key in bytes
-   UCHAR     KeyMaterial[1];// variable length depending on above field
-} NDIS_802_11_WEP, *PNDIS_802_11_WEP;
-
-
-typedef enum _NDIS_802_11_NETWORK_INFRASTRUCTURE
-{
-   Ndis802_11IBSS,
-   Ndis802_11Infrastructure,
-   Ndis802_11AutoUnknown,
-   Ndis802_11Monitor,
-   Ndis802_11InfrastructureMax     // Not a real value, defined as upper bound
-} NDIS_802_11_NETWORK_INFRASTRUCTURE, *PNDIS_802_11_NETWORK_INFRASTRUCTURE;
-
-// Add new authentication modes
-typedef enum _NDIS_802_11_AUTHENTICATION_MODE
-{
-   Ndis802_11AuthModeOpen,
-   Ndis802_11AuthModeShared,
-   Ndis802_11AuthModeAutoSwitch,
-    Ndis802_11AuthModeWPA,
-    Ndis802_11AuthModeWPAPSK,
-    Ndis802_11AuthModeWPANone,
-   Ndis802_11AuthModeWPA2,
-   Ndis802_11AuthModeWPA2PSK,
-   	Ndis802_11AuthModeWPA1WPA2,
-	Ndis802_11AuthModeWPA1PSKWPA2PSK,
-   Ndis802_11AuthModeMax           // Not a real mode, defined as upper bound
-} NDIS_802_11_AUTHENTICATION_MODE, *PNDIS_802_11_AUTHENTICATION_MODE;
-
-typedef UCHAR   NDIS_802_11_RATES[NDIS_802_11_LENGTH_RATES];        // Set of 8 data rates
-typedef UCHAR   NDIS_802_11_RATES_EX[NDIS_802_11_LENGTH_RATES_EX];  // Set of 16 data rates
-
-typedef struct PACKED _NDIS_802_11_SSID
-{
-    UINT   SsidLength;         // length of SSID field below, in bytes;
-                                // this can be zero.
-    UCHAR   Ssid[NDIS_802_11_LENGTH_SSID];           // SSID information field
-} NDIS_802_11_SSID, *PNDIS_802_11_SSID;
-
-
-typedef struct PACKED _NDIS_WLAN_BSSID
-{
-   ULONG                               Length;     // Length of this structure
-   NDIS_802_11_MAC_ADDRESS             MacAddress; // BSSID
-   UCHAR                               Reserved[2];
-   NDIS_802_11_SSID                    Ssid;       // SSID
-   ULONG                               Privacy;    // WEP encryption requirement
-   NDIS_802_11_RSSI                    Rssi;       // receive signal strength in dBm
-   NDIS_802_11_NETWORK_TYPE            NetworkTypeInUse;
-   NDIS_802_11_CONFIGURATION           Configuration;
-   NDIS_802_11_NETWORK_INFRASTRUCTURE  InfrastructureMode;
-   NDIS_802_11_RATES                   SupportedRates;
-} NDIS_WLAN_BSSID, *PNDIS_WLAN_BSSID;
-
-typedef struct PACKED _NDIS_802_11_BSSID_LIST
-{
-   UINT           NumberOfItems;      // in list below, at least 1
-   NDIS_WLAN_BSSID Bssid[1];
-} NDIS_802_11_BSSID_LIST, *PNDIS_802_11_BSSID_LIST;
-
-// Added Capabilities, IELength and IEs for each BSSID
-typedef struct PACKED _NDIS_WLAN_BSSID_EX
-{
-    ULONG                               Length;             // Length of this structure
-    NDIS_802_11_MAC_ADDRESS             MacAddress;         // BSSID
-    UCHAR                               Reserved[2];
-    NDIS_802_11_SSID                    Ssid;               // SSID
-    UINT                                Privacy;            // WEP encryption requirement
-    NDIS_802_11_RSSI                    Rssi;               // receive signal
-                                                            // strength in dBm
-    NDIS_802_11_NETWORK_TYPE            NetworkTypeInUse;
-    NDIS_802_11_CONFIGURATION           Configuration;
-    NDIS_802_11_NETWORK_INFRASTRUCTURE  InfrastructureMode;
-    NDIS_802_11_RATES_EX                SupportedRates;
-    ULONG                               IELength;
-    UCHAR                               IEs[1];
-} NDIS_WLAN_BSSID_EX, *PNDIS_WLAN_BSSID_EX;
-
-typedef struct PACKED _NDIS_802_11_BSSID_LIST_EX
-{
-    UINT                   NumberOfItems;      // in list below, at least 1
-    NDIS_WLAN_BSSID_EX      Bssid[1];
-} NDIS_802_11_BSSID_LIST_EX, *PNDIS_802_11_BSSID_LIST_EX;
-
-typedef struct PACKED _NDIS_802_11_FIXED_IEs
-{
-    UCHAR Timestamp[8];
-    USHORT BeaconInterval;
-    USHORT Capabilities;
-} NDIS_802_11_FIXED_IEs, *PNDIS_802_11_FIXED_IEs;
-
-typedef struct _NDIS_802_11_VARIABLE_IEs
-{
-    UCHAR ElementID;
-    UCHAR Length;    // Number of bytes in data field
-    UCHAR data[1];
-} NDIS_802_11_VARIABLE_IEs, *PNDIS_802_11_VARIABLE_IEs;
-
-typedef  ULONG   NDIS_802_11_FRAGMENTATION_THRESHOLD;
-
-typedef  ULONG   NDIS_802_11_RTS_THRESHOLD;
-
-typedef  ULONG   NDIS_802_11_ANTENNA;
-
-typedef enum _NDIS_802_11_PRIVACY_FILTER
-{
-   Ndis802_11PrivFilterAcceptAll,
-   Ndis802_11PrivFilter8021xWEP
-} NDIS_802_11_PRIVACY_FILTER, *PNDIS_802_11_PRIVACY_FILTER;
-
-// Added new encryption types
-// Also aliased typedef to new name
-typedef enum _NDIS_802_11_WEP_STATUS
-{
-   Ndis802_11WEPEnabled,
-    Ndis802_11Encryption1Enabled = Ndis802_11WEPEnabled,
-   Ndis802_11WEPDisabled,
-    Ndis802_11EncryptionDisabled = Ndis802_11WEPDisabled,
-   Ndis802_11WEPKeyAbsent,
-    Ndis802_11Encryption1KeyAbsent = Ndis802_11WEPKeyAbsent,
-   Ndis802_11WEPNotSupported,
-    Ndis802_11EncryptionNotSupported = Ndis802_11WEPNotSupported,
-    Ndis802_11Encryption2Enabled,
-    Ndis802_11Encryption2KeyAbsent,
-    Ndis802_11Encryption3Enabled,
-    Ndis802_11Encryption3KeyAbsent,
-    Ndis802_11Encryption4Enabled,	// TKIP or AES mix
-    Ndis802_11Encryption4KeyAbsent,
-} NDIS_802_11_WEP_STATUS, *PNDIS_802_11_WEP_STATUS,
-  NDIS_802_11_ENCRYPTION_STATUS, *PNDIS_802_11_ENCRYPTION_STATUS;
-
-typedef enum _NDIS_802_11_RELOAD_DEFAULTS
-{
-   Ndis802_11ReloadWEPKeys
-} NDIS_802_11_RELOAD_DEFAULTS, *PNDIS_802_11_RELOAD_DEFAULTS;
-
-#define NDIS_802_11_AI_REQFI_CAPABILITIES      1
-#define NDIS_802_11_AI_REQFI_LISTENINTERVAL    2
-#define NDIS_802_11_AI_REQFI_CURRENTAPADDRESS  4
-
-#define NDIS_802_11_AI_RESFI_CAPABILITIES      1
-#define NDIS_802_11_AI_RESFI_STATUSCODE        2
-#define NDIS_802_11_AI_RESFI_ASSOCIATIONID     4
-
-typedef struct _NDIS_802_11_AI_REQFI
-{
-    USHORT Capabilities;
-    USHORT ListenInterval;
-    NDIS_802_11_MAC_ADDRESS  CurrentAPAddress;
-} NDIS_802_11_AI_REQFI, *PNDIS_802_11_AI_REQFI;
-
-typedef struct _NDIS_802_11_AI_RESFI
-{
-    USHORT Capabilities;
-    USHORT StatusCode;
-    USHORT AssociationId;
-} NDIS_802_11_AI_RESFI, *PNDIS_802_11_AI_RESFI;
-
-typedef struct _NDIS_802_11_ASSOCIATION_INFORMATION
-{
-    ULONG                   Length;
-    USHORT                  AvailableRequestFixedIEs;
-    NDIS_802_11_AI_REQFI    RequestFixedIEs;
-    ULONG                   RequestIELength;
-    ULONG                   OffsetRequestIEs;
-    USHORT                  AvailableResponseFixedIEs;
-    NDIS_802_11_AI_RESFI    ResponseFixedIEs;
-    ULONG                   ResponseIELength;
-    ULONG                   OffsetResponseIEs;
-} NDIS_802_11_ASSOCIATION_INFORMATION, *PNDIS_802_11_ASSOCIATION_INFORMATION;
-
-typedef struct _NDIS_802_11_AUTHENTICATION_EVENT
-{
-    NDIS_802_11_STATUS_INDICATION       Status;
-    NDIS_802_11_AUTHENTICATION_REQUEST  Request[1];
-} NDIS_802_11_AUTHENTICATION_EVENT, *PNDIS_802_11_AUTHENTICATION_EVENT;
-
-/*
-typedef struct _NDIS_802_11_TEST
-{
-    ULONG Length;
-    ULONG Type;
-    union
-    {
-        NDIS_802_11_AUTHENTICATION_EVENT AuthenticationEvent;
-        NDIS_802_11_RSSI RssiTrigger;
-    };
-} NDIS_802_11_TEST, *PNDIS_802_11_TEST;
- */
-
-// 802.11 Media stream constraints, associated with OID_802_11_MEDIA_STREAM_MODE
-typedef enum _NDIS_802_11_MEDIA_STREAM_MODE
-{
-    Ndis802_11MediaStreamOff,
-    Ndis802_11MediaStreamOn,
-} NDIS_802_11_MEDIA_STREAM_MODE, *PNDIS_802_11_MEDIA_STREAM_MODE;
-
-// PMKID Structures
-typedef UCHAR   NDIS_802_11_PMKID_VALUE[16];
-
-#ifdef CONFIG_STA_SUPPORT
-typedef struct _BSSID_INFO
-{
-    NDIS_802_11_MAC_ADDRESS BSSID;
-    NDIS_802_11_PMKID_VALUE PMKID;
-} BSSID_INFO, *PBSSID_INFO;
-
-typedef struct _NDIS_802_11_PMKID
-{
-    UINT    Length;
-    UINT    BSSIDInfoCount;
-    BSSID_INFO BSSIDInfo[1];
-} NDIS_802_11_PMKID, *PNDIS_802_11_PMKID;
-#endif // CONFIG_STA_SUPPORT //
-
-
-typedef struct _NDIS_802_11_AUTHENTICATION_ENCRYPTION
-{
-    NDIS_802_11_AUTHENTICATION_MODE AuthModeSupported;
-    NDIS_802_11_ENCRYPTION_STATUS EncryptStatusSupported;
-} NDIS_802_11_AUTHENTICATION_ENCRYPTION, *PNDIS_802_11_AUTHENTICATION_ENCRYPTION;
-
-typedef struct _NDIS_802_11_CAPABILITY
-{
-     ULONG Length;
-     ULONG Version;
-     ULONG NoOfPMKIDs;
-     ULONG NoOfAuthEncryptPairsSupported;
-     NDIS_802_11_AUTHENTICATION_ENCRYPTION AuthenticationEncryptionSupported[1];
-} NDIS_802_11_CAPABILITY, *PNDIS_802_11_CAPABILITY;
-
-//#endif //of WIN 2k
-#endif //UNDER_CE
-
-#if WIRELESS_EXT <= 11
-#ifndef SIOCDEVPRIVATE
-#define SIOCDEVPRIVATE                              0x8BE0
-#endif
-#define SIOCIWFIRSTPRIV								SIOCDEVPRIVATE
-#endif
-
-#ifdef CONFIG_STA_SUPPORT
-#define RT_PRIV_IOCTL_EXT							(SIOCIWFIRSTPRIV + 0x01) // Sync. with AP for wsc upnp daemon
-#define RTPRIV_IOCTL_SET							(SIOCIWFIRSTPRIV + 0x02)
-
-#ifdef DBG
-#define RTPRIV_IOCTL_BBP                            (SIOCIWFIRSTPRIV + 0x03)
-#define RTPRIV_IOCTL_MAC                            (SIOCIWFIRSTPRIV + 0x05)
-#define RTPRIV_IOCTL_RF                             (SIOCIWFIRSTPRIV + 0x13)
-#define RTPRIV_IOCTL_E2P                            (SIOCIWFIRSTPRIV + 0x07)
-#endif
-
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-#define RTPRIV_IOCTL_ATE							(SIOCIWFIRSTPRIV + 0x08)
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-#define RTPRIV_IOCTL_STATISTICS                     (SIOCIWFIRSTPRIV + 0x09)
-#define RTPRIV_IOCTL_ADD_PMKID_CACHE                (SIOCIWFIRSTPRIV + 0x0A)
-#define RTPRIV_IOCTL_RADIUS_DATA                    (SIOCIWFIRSTPRIV + 0x0C)
-#define RTPRIV_IOCTL_GSITESURVEY					(SIOCIWFIRSTPRIV + 0x0D)
-#define RT_PRIV_IOCTL								(SIOCIWFIRSTPRIV + 0x0E) // Sync. with RT61 (for wpa_supplicant)
-#define RTPRIV_IOCTL_GET_MAC_TABLE					(SIOCIWFIRSTPRIV + 0x0F)
-
-#define RTPRIV_IOCTL_SHOW							(SIOCIWFIRSTPRIV + 0x11)
-enum {
-    SHOW_CONN_STATUS = 4,
-    SHOW_DRVIER_VERION = 5,
-    SHOW_BA_INFO = 6,
-	SHOW_DESC_INFO = 7,
-#ifdef RT2870
-	SHOW_RXBULK_INFO = 8,
-	SHOW_TXBULK_INFO = 9,
-#endif // RT2870 //
-    RAIO_OFF = 10,
-    RAIO_ON = 11,
-#ifdef QOS_DLS_SUPPORT
-	SHOW_DLS_ENTRY_INFO = 19,
-#endif // QOS_DLS_SUPPORT //
-	SHOW_CFG_VALUE = 20,
-};
-
-
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-#ifdef SNMP_SUPPORT
-//SNMP ieee 802dot11, kathy , 2008_0220
-// dot11res(3)
-#define RT_OID_802_11_MANUFACTUREROUI			0x0700
-#define RT_OID_802_11_MANUFACTURERNAME			0x0701
-#define RT_OID_802_11_RESOURCETYPEIDNAME		0x0702
-
-// dot11smt(1)
-#define RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED	0x0703
-#define RT_OID_802_11_POWERMANAGEMENTMODE		0x0704
-#define OID_802_11_WEPDEFAULTKEYVALUE			0x0705 // read , write
-#define OID_802_11_WEPDEFAULTKEYID				0x0706
-#define RT_OID_802_11_WEPKEYMAPPINGLENGTH		0x0707
-#define OID_802_11_SHORTRETRYLIMIT				0x0708
-#define OID_802_11_LONGRETRYLIMIT				0x0709
-#define RT_OID_802_11_PRODUCTID					0x0710
-#define RT_OID_802_11_MANUFACTUREID				0x0711
-
-// //dot11Phy(4)
-#define OID_802_11_CURRENTCHANNEL				0x0712
-
-//dot11mac
-#define RT_OID_802_11_MAC_ADDRESS				0x0713
-#endif // SNMP_SUPPORT //
-
-#define OID_802_11_BUILD_CHANNEL_EX				0x0714
-#define OID_802_11_GET_CH_LIST					0x0715
-#define OID_802_11_GET_COUNTRY_CODE				0x0716
-#define OID_802_11_GET_CHANNEL_GEOGRAPHY		0x0717
-
-//#define RT_OID_802_11_STATISTICS              (OID_GET_SET_TOGGLE | OID_802_11_STATISTICS)
-
-#ifdef CONFIG_STA_SUPPORT
-#define RT_OID_WSC_SET_PASSPHRASE                   0x0740 // passphrase for wpa(2)-psk
-#define RT_OID_WSC_DRIVER_AUTO_CONNECT              0x0741
-#define RT_OID_WSC_QUERY_DEFAULT_PROFILE            0x0742
-#define RT_OID_WSC_SET_CONN_BY_PROFILE_INDEX        0x0743
-#define RT_OID_WSC_SET_ACTION                       0x0744
-#define RT_OID_WSC_SET_SSID                         0x0745
-#define RT_OID_WSC_SET_PIN_CODE                     0x0746
-#define RT_OID_WSC_SET_MODE                         0x0747 // PIN or PBC
-#define RT_OID_WSC_SET_CONF_MODE                    0x0748 // Enrollee or Registrar
-#define RT_OID_WSC_SET_PROFILE                      0x0749
-#endif // CONFIG_STA_SUPPORT //
-#define RT_OID_802_11_WSC_QUERY_PROFILE				0x0750
-// for consistency with RT61
-#define RT_OID_WSC_QUERY_STATUS						0x0751
-#define RT_OID_WSC_PIN_CODE							0x0752
-#define RT_OID_WSC_UUID								0x0753
-#define RT_OID_WSC_SET_SELECTED_REGISTRAR			0x0754
-#define RT_OID_WSC_EAPMSG							0x0755
-#define RT_OID_WSC_MANUFACTURER						0x0756
-#define RT_OID_WSC_MODEL_NAME						0x0757
-#define RT_OID_WSC_MODEL_NO							0x0758
-#define RT_OID_WSC_SERIAL_NO						0x0759
-#define RT_OID_WSC_MAC_ADDRESS						0x0760
-
-#ifdef LLTD_SUPPORT
-// for consistency with RT61
-#define RT_OID_GET_PHY_MODE                         0x761
-#endif // LLTD_SUPPORT //
-
-#ifdef NINTENDO_AP
-//#define RT_OID_NINTENDO                             0x0D010770
-#define RT_OID_802_11_NINTENDO_GET_TABLE			0x0771 //((RT_OID_NINTENDO + 0x01) & 0xffff)
-#define RT_OID_802_11_NINTENDO_SET_TABLE			0x0772 //((RT_OID_NINTENDO + 0x02) & 0xffff)
-#define RT_OID_802_11_NINTENDO_CAPABLE				0x0773 //((RT_OID_NINTENDO + 0x03) & 0xffff)
-#endif // NINTENDO_AP //
-
-//Add Paul Chen for Accton
-//#define RT_OID_TX_POWER_LEVEL                 0xFF020010
-//#define RT_OID_SET_TX_POWER_LEVEL	          (OID_GET_SET_TOGGLE | RT_OID_TX_POWER_LEVEL)
-
-// New for MeetingHouse Api support
-#define OID_MH_802_1X_SUPPORTED               0xFFEDC100
-
-// MIMO Tx parameter, ShortGI, MCS, STBC, etc.  these are fields in TXWI. Don't change this definition!!!
-typedef union  _HTTRANSMIT_SETTING {
-#ifdef RT_BIG_ENDIAN
-	struct	{
-	USHORT		MODE:2;	// Use definition MODE_xxx.
-//	USHORT		rsv:3;
-	USHORT		TxBF:1;
-	USHORT		rsv:2;
-	USHORT		STBC:2;	//SPACE
-	USHORT		ShortGI:1;
-	USHORT		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	USHORT   	MCS:7;                 // MCS
-	}	field;
-#else
-	struct	{
-	USHORT   	MCS:7;                 // MCS
-	USHORT		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	USHORT		ShortGI:1;
-	USHORT		STBC:2;	//SPACE
-//	USHORT		rsv:3;
-	USHORT		rsv:2;
-	USHORT		TxBF:1;
-	USHORT		MODE:2;	// Use definition MODE_xxx.
-	}	field;
-#endif
-	USHORT		word;
- } HTTRANSMIT_SETTING, *PHTTRANSMIT_SETTING;
-
-typedef enum _RT_802_11_PREAMBLE {
-    Rt802_11PreambleLong,
-    Rt802_11PreambleShort,
-    Rt802_11PreambleAuto
-} RT_802_11_PREAMBLE, *PRT_802_11_PREAMBLE;
-
-// Only for STA, need to sync with AP
-// 2005-03-08 match current RaConfig.
-typedef enum _RT_802_11_PHY_MODE {
-	PHY_11BG_MIXED = 0,
-	PHY_11B,
-	PHY_11A,
-	PHY_11ABG_MIXED,
-	PHY_11G,
-#ifdef DOT11_N_SUPPORT
-	PHY_11ABGN_MIXED,	// both band   5
-	PHY_11N_2_4G,		// 11n-only with 2.4G band   	6
-	PHY_11GN_MIXED,	// 2.4G band      7
-	PHY_11AN_MIXED,	// 5G  band       8
-	PHY_11BGN_MIXED,	// if check 802.11b.      9
-	PHY_11AGN_MIXED,	// if check 802.11b.      10
-	PHY_11N_5G,			// 11n-only with 5G band		11
-#endif // DOT11_N_SUPPORT //
-} RT_802_11_PHY_MODE;
-
-// put all proprietery for-query objects here to reduce # of Query_OID
-typedef struct _RT_802_11_LINK_STATUS {
-    ULONG   CurrTxRate;         // in units of 0.5Mbps
-    ULONG   ChannelQuality;     // 0..100 %
-    ULONG   TxByteCount;        // both ok and fail
-    ULONG   RxByteCount;        // both ok and fail
-    ULONG	CentralChannel;		// 40MHz central channel number
-} RT_802_11_LINK_STATUS, *PRT_802_11_LINK_STATUS;
-
-typedef struct _RT_802_11_EVENT_LOG {
-    LARGE_INTEGER   SystemTime;  // timestammp via NdisGetCurrentSystemTime()
-    UCHAR           Addr[MAC_ADDR_LENGTH];
-    USHORT          Event;       // EVENT_xxx
-} RT_802_11_EVENT_LOG, *PRT_802_11_EVENT_LOG;
-
-typedef struct _RT_802_11_EVENT_TABLE {
-    ULONG       Num;
-    ULONG       Rsv;     // to align Log[] at LARGE_INEGER boundary
-    RT_802_11_EVENT_LOG   Log[MAX_NUMBER_OF_EVENT];
-} RT_802_11_EVENT_TABLE, PRT_802_11_EVENT_TABLE;
-
-// MIMO Tx parameter, ShortGI, MCS, STBC, etc.  these are fields in TXWI. Don't change this definition!!!
-typedef union  _MACHTTRANSMIT_SETTING {
-	struct	{
-	USHORT   	MCS:7;                 // MCS
-	USHORT		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	USHORT		ShortGI:1;
-	USHORT		STBC:2;	//SPACE
-	USHORT		rsv:3;
-	USHORT		MODE:2;	// Use definition MODE_xxx.
-	}	field;
-	USHORT		word;
- } MACHTTRANSMIT_SETTING, *PMACHTTRANSMIT_SETTING;
-
-typedef struct _RT_802_11_MAC_ENTRY {
-    UCHAR       Addr[MAC_ADDR_LENGTH];
-    UCHAR       Aid;
-    UCHAR       Psm;     // 0:PWR_ACTIVE, 1:PWR_SAVE
-    UCHAR		MimoPs;  // 0:MMPS_STATIC, 1:MMPS_DYNAMIC, 3:MMPS_Enabled
-    CHAR		AvgRssi0;
-	CHAR		AvgRssi1;
-	CHAR		AvgRssi2;
-	UINT32		ConnectedTime;
-    MACHTTRANSMIT_SETTING	TxRate;
-} RT_802_11_MAC_ENTRY, *PRT_802_11_MAC_ENTRY;
-
-typedef struct _RT_802_11_MAC_TABLE {
-    ULONG       Num;
-    RT_802_11_MAC_ENTRY Entry[MAX_NUMBER_OF_MAC];
-} RT_802_11_MAC_TABLE, *PRT_802_11_MAC_TABLE;
-
-// structure for query/set hardware register - MAC, BBP, RF register
-typedef struct _RT_802_11_HARDWARE_REGISTER {
-    ULONG   HardwareType;       // 0:MAC, 1:BBP, 2:RF register, 3:EEPROM
-    ULONG   Offset;             // Q/S register offset addr
-    ULONG   Data;               // R/W data buffer
-} RT_802_11_HARDWARE_REGISTER, *PRT_802_11_HARDWARE_REGISTER;
-
-// structure to tune BBP R17 "RX AGC VGC init"
-//typedef struct _RT_802_11_RX_AGC_VGC_TUNING {
-//    UCHAR   FalseCcaLowerThreshold;  // 0-255, def 10
-//    UCHAR   FalseCcaUpperThreshold;  // 0-255, def 100
-//    UCHAR   VgcDelta;                // R17 +-= VgcDelta whenever flase CCA over UpprThreshold
-//                                     // or lower than LowerThresholdupper threshold
-//    UCHAR   VgcUpperBound;           // max value of R17
-//} RT_802_11_RX_AGC_VGC_TUNING, *PRT_802_11_RX_AGC_VGC_TUNING;
-
-typedef struct _RT_802_11_AP_CONFIG {
-    ULONG   EnableTxBurst;      // 0-disable, 1-enable
-    ULONG   EnableTurboRate;    // 0-disable, 1-enable 72/100mbps turbo rate
-    ULONG   IsolateInterStaTraffic;     // 0-disable, 1-enable isolation
-    ULONG   HideSsid;           // 0-disable, 1-enable hiding
-    ULONG   UseBGProtection;    // 0-AUTO, 1-always ON, 2-always OFF
-    ULONG   UseShortSlotTime;   // 0-no use, 1-use 9-us short slot time
-    ULONG   Rsv1;               // must be 0
-    ULONG   SystemErrorBitmap;  // ignore upon SET, return system error upon QUERY
-} RT_802_11_AP_CONFIG, *PRT_802_11_AP_CONFIG;
-
-// structure to query/set STA_CONFIG
-typedef struct _RT_802_11_STA_CONFIG {
-    ULONG   EnableTxBurst;      // 0-disable, 1-enable
-    ULONG   EnableTurboRate;    // 0-disable, 1-enable 72/100mbps turbo rate
-    ULONG   UseBGProtection;    // 0-AUTO, 1-always ON, 2-always OFF
-    ULONG   UseShortSlotTime;   // 0-no use, 1-use 9-us short slot time when applicable
-    ULONG   AdhocMode; 			// 0-11b rates only (WIFI spec), 1 - b/g mixed, 2 - g only
-    ULONG   HwRadioStatus;      // 0-OFF, 1-ON, default is 1, Read-Only
-    ULONG   Rsv1;               // must be 0
-    ULONG   SystemErrorBitmap;  // ignore upon SET, return system error upon QUERY
-} RT_802_11_STA_CONFIG, *PRT_802_11_STA_CONFIG;
-
-//
-//  For OID Query or Set about BA structure
-//
-typedef	struct	_OID_BACAP_STRUC	{
-		UCHAR		RxBAWinLimit;
-		UCHAR		TxBAWinLimit;
-		UCHAR		Policy;	// 0: DELAY_BA 1:IMMED_BA  (//BA Policy subfiled value in ADDBA frame)   2:BA-not use. other value invalid
-		UCHAR		MpduDensity;	// 0: DELAY_BA 1:IMMED_BA  (//BA Policy subfiled value in ADDBA frame)   2:BA-not use. other value invalid
-		UCHAR       	AmsduEnable;	//Enable AMSDU transmisstion
-		UCHAR       	AmsduSize;	// 0:3839, 1:7935 bytes. UINT  MSDUSizeToBytes[]	= { 3839, 7935};
-		UCHAR       	MMPSmode;	// MIMO power save more, 0:static, 1:dynamic, 2:rsv, 3:mimo enable
-		BOOLEAN		AutoBA;	// Auto BA will automatically
-} OID_BACAP_STRUC, *POID_BACAP_STRUC;
-
-typedef struct _RT_802_11_ACL_ENTRY {
-    UCHAR   Addr[MAC_ADDR_LENGTH];
-    USHORT  Rsv;
-} RT_802_11_ACL_ENTRY, *PRT_802_11_ACL_ENTRY;
-
-typedef struct PACKED _RT_802_11_ACL {
-    ULONG   Policy;             // 0-disable, 1-positive list, 2-negative list
-    ULONG   Num;
-    RT_802_11_ACL_ENTRY Entry[MAX_NUMBER_OF_ACL];
-} RT_802_11_ACL, *PRT_802_11_ACL;
-
-typedef struct _RT_802_11_WDS {
-    ULONG						Num;
-    NDIS_802_11_MAC_ADDRESS		Entry[24/*MAX_NUM_OF_WDS_LINK*/];
-	ULONG						KeyLength;
-	UCHAR						KeyMaterial[32];
-} RT_802_11_WDS, *PRT_802_11_WDS;
-
-typedef struct _RT_802_11_TX_RATES_ {
-    UCHAR       SupRateLen;
-    UCHAR       SupRate[MAX_LENGTH_OF_SUPPORT_RATES];
-    UCHAR       ExtRateLen;
-    UCHAR       ExtRate[MAX_LENGTH_OF_SUPPORT_RATES];
-} RT_802_11_TX_RATES, *PRT_802_11_TX_RATES;
-
-
-// Definition of extra information code
-#define	GENERAL_LINK_UP			0x0			// Link is Up
-#define	GENERAL_LINK_DOWN		0x1			// Link is Down
-#define	HW_RADIO_OFF			0x2			// Hardware radio off
-#define	SW_RADIO_OFF			0x3			// Software radio off
-#define	AUTH_FAIL				0x4			// Open authentication fail
-#define	AUTH_FAIL_KEYS			0x5			// Shared authentication fail
-#define	ASSOC_FAIL				0x6			// Association failed
-#define	EAP_MIC_FAILURE			0x7			// Deauthencation because MIC failure
-#define	EAP_4WAY_TIMEOUT		0x8			// Deauthencation on 4-way handshake timeout
-#define	EAP_GROUP_KEY_TIMEOUT	0x9			// Deauthencation on group key handshake timeout
-#define	EAP_SUCCESS				0xa			// EAP succeed
-#define	DETECT_RADAR_SIGNAL		0xb         // Radar signal occur in current channel
-#define EXTRA_INFO_MAX			0xb			// Indicate Last OID
-
-#define EXTRA_INFO_CLEAR		0xffffffff
-
-// This is OID setting structure. So only GF or MM as Mode. This is valid when our wirelss mode has 802.11n in use.
-typedef struct {
-	RT_802_11_PHY_MODE		PhyMode; 	//
-	UCHAR		TransmitNo;
-	UCHAR		HtMode; 	//HTMODE_GF or HTMODE_MM
-	UCHAR		ExtOffset;	//extension channel above or below
-	UCHAR		MCS;
-	UCHAR   	BW;
-	UCHAR		STBC;
-	UCHAR		SHORTGI;
-	UCHAR		rsv;
-} OID_SET_HT_PHYMODE, *POID_SET_HT_PHYMODE;
-
-#ifdef NINTENDO_AP
-#define NINTENDO_MAX_ENTRY 16
-#define NINTENDO_SSID_NAME_LN 8
-#define NINTENDO_SSID_NAME "NWCUSBAP"
-#define NINTENDO_PROBE_REQ_FLAG_MASK 0x03
-#define NINTENDO_PROBE_REQ_ON 0x01
-#define NINTENDO_PROBE_REQ_SIGNAL 0x02
-#define NINTENDO_PROBE_RSP_ON 0x01
-#define NINTENDO_SSID_NICKNAME_LN 20
-
-#define NINTENDO_WEPKEY_LN 13
-
-typedef struct _NINTENDO_SSID
-{
-	UCHAR	NINTENDOFixChar[NINTENDO_SSID_NAME_LN];
-	UCHAR	zero1;
-	UCHAR	registe;
-	UCHAR	ID;
-	UCHAR	zero2;
-	UCHAR	NICKname[NINTENDO_SSID_NICKNAME_LN];
-} RT_NINTENDO_SSID, *PRT_NINTENDO_SSID;
-
-typedef struct _NINTENDO_ENTRY
-{
-	UCHAR	NICKname[NINTENDO_SSID_NICKNAME_LN];
-    UCHAR   DS_Addr[ETH_LENGTH_OF_ADDRESS];
-	UCHAR	registe;
-	UCHAR	UserSpaceAck;
-} RT_NINTENDO_ENTRY, *PRT_NINTENDO_ENTRY;
-
-//RTPRIV_IOCTL_NINTENDO_GET_TABLE
-//RTPRIV_IOCTL_NINTENDO_SET_TABLE
-typedef struct _NINTENDO_TABLE
-{
-	UINT				number;
-	RT_NINTENDO_ENTRY	entry[NINTENDO_MAX_ENTRY];
-} RT_NINTENDO_TABLE, *PRT_NINTENDO_TABLE;
-
-//RTPRIV_IOCTL_NINTENDO_SEED_WEPKEY
-typedef struct _NINTENDO_SEED_WEPKEY
-{
-	UCHAR	seed[NINTENDO_SSID_NICKNAME_LN];
-	UCHAR	wepkey[16];//use 13 for 104 bits wep key
-} RT_NINTENDO_SEED_WEPKEY, *PRT_NINTENDO_SEED_WEPKEY;
-#endif // NINTENDO_AP //
-
-#ifdef LLTD_SUPPORT
-typedef struct _RT_LLTD_ASSOICATION_ENTRY {
-    UCHAR           Addr[ETH_LENGTH_OF_ADDRESS];
-    unsigned short  MOR;        // maximum operational rate
-    UCHAR           phyMode;
-} RT_LLTD_ASSOICATION_ENTRY, *PRT_LLTD_ASSOICATION_ENTRY;
-
-typedef struct _RT_LLTD_ASSOICATION_TABLE {
-    unsigned int                Num;
-    RT_LLTD_ASSOICATION_ENTRY   Entry[MAX_NUMBER_OF_MAC];
-} RT_LLTD_ASSOICATION_TABLE, *PRT_LLTD_ASSOICATION_TABLE;
-#endif // LLTD_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-//rt2860, kathy 2007-0118
-// structure for DLS
-typedef struct _RT_802_11_DLS_UI {
-	USHORT						TimeOut;		// unit: second , set by UI
-	USHORT						CountDownTimer;	// unit: second , used by driver only
-	NDIS_802_11_MAC_ADDRESS		MacAddr;		// set by UI
-	UCHAR						Status;			// 0: none , 1: wait STAkey, 2: finish DLS setup , set by driver only
-	BOOLEAN						Valid;			// 1: valid , 0: invalid , set by UI, use to setup or tear down DLS link
-} RT_802_11_DLS_UI, *PRT_802_11_DLS_UI;
-
-typedef struct _RT_802_11_DLS_INFO {
-	RT_802_11_DLS_UI	Entry[MAX_NUMBER_OF_DLS_ENTRY];
-	UCHAR				num;
-} RT_802_11_DLS_INFO, *PRT_802_11_DLS_INFO;
-
-typedef enum _RT_802_11_DLS_MODE {
-    DLS_NONE,
-    DLS_WAIT_KEY,
-    DLS_FINISH
-} RT_802_11_DLS_MODE;
-#endif // QOS_DLS_SUPPORT //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-#define	RT_ASSOC_EVENT_FLAG                         0x0101
-#define	RT_DISASSOC_EVENT_FLAG                      0x0102
-#define	RT_REQIE_EVENT_FLAG                         0x0103
-#define	RT_RESPIE_EVENT_FLAG                        0x0104
-#define	RT_ASSOCINFO_EVENT_FLAG                     0x0105
-#define RT_PMKIDCAND_FLAG                           0x0106
-#define RT_INTERFACE_DOWN                           0x0107
-#define RT_INTERFACE_UP                             0x0108
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-
-#define MAX_CUSTOM_LEN 128
-
-#ifdef CONFIG_STA_SUPPORT
-typedef enum _RT_802_11_D_CLIENT_MODE
-{
-   Rt802_11_D_None,
-   Rt802_11_D_Flexible,
-   Rt802_11_D_Strict,
-} RT_802_11_D_CLIENT_MODE, *PRT_802_11_D_CLIENT_MODE;
-#endif // CONFIG_STA_SUPPORT //
-
-typedef struct _RT_CHANNEL_LIST_INFO
-{
-	UCHAR ChannelList[MAX_NUM_OF_CHS];   // list all supported channels for site survey
-	UCHAR ChannelListNum; // number of channel in ChannelList[]
-} RT_CHANNEL_LIST_INFO, *PRT_CHANNEL_LIST_INFO;
-
-// WSC configured credential
-typedef	struct	_WSC_CREDENTIAL
-{
-	NDIS_802_11_SSID	SSID;				// mandatory
-	USHORT				AuthType;			// mandatory, 1: open, 2: wpa-psk, 4: shared, 8:wpa, 0x10: wpa2, 0x20: wpa2-psk
-	USHORT				EncrType;			// mandatory, 1: none, 2: wep, 4: tkip, 8: aes
-	UCHAR				Key[64];			// mandatory, Maximum 64 byte
-	USHORT				KeyLength;
-	UCHAR				MacAddr[6];			// mandatory, AP MAC address
-	UCHAR				KeyIndex;			// optional, default is 1
-	UCHAR				Rsvd[3];			// Make alignment
-}	WSC_CREDENTIAL, *PWSC_CREDENTIAL;
-
-// WSC configured profiles
-typedef	struct	_WSC_PROFILE
-{
-	UINT			ProfileCnt;
-	WSC_CREDENTIAL	Profile[8];				// Support up to 8 profiles
-}	WSC_PROFILE, *PWSC_PROFILE;
-
-
-
-#endif // _OID_H_
-
+#include "../rt2870/oid.h"
diff --git a/drivers/staging/rt3070/rt2870.h b/drivers/staging/rt3070/rt2870.h
index d32a2bf..16d8717 100644
--- a/drivers/staging/rt3070/rt2870.h
+++ b/drivers/staging/rt3070/rt2870.h
@@ -1,756 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#ifndef __RT2870_H__
-#define __RT2870_H__
-
-//usb header files
-#include <linux/usb.h>
-
-/* rtmp_def.h */
-//
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-#define BULKAGGRE_ZISE          100
-#define RT28XX_DRVDATA_SET(_a)                                             usb_set_intfdata(_a, pAd);
-#define RT28XX_PUT_DEVICE                                                  usb_put_dev
-#define RTUSB_ALLOC_URB(iso)                                               usb_alloc_urb(iso, GFP_ATOMIC)
-#define RTUSB_SUBMIT_URB(pUrb)                                             usb_submit_urb(pUrb, GFP_ATOMIC)
-#define	RTUSB_URB_ALLOC_BUFFER(pUsb_Dev, BufSize, pDma_addr)               usb_buffer_alloc(pUsb_Dev, BufSize, GFP_ATOMIC, pDma_addr)
-#define	RTUSB_URB_FREE_BUFFER(pUsb_Dev, BufSize, pTransferBuf, Dma_addr)   usb_buffer_free(pUsb_Dev, BufSize, pTransferBuf, Dma_addr)
-#else
-#define BULKAGGRE_ZISE          60
-#define RT28XX_DRVDATA_SET(_a)
-#define RT28XX_PUT_DEVICE(dev_p)
-#define RTUSB_ALLOC_URB(iso)                                               usb_alloc_urb(iso)
-#define RTUSB_SUBMIT_URB(pUrb)                                             usb_submit_urb(pUrb)
-#define RTUSB_URB_ALLOC_BUFFER(pUsb_Dev, BufSize, pDma_addr)               kmalloc(BufSize, GFP_ATOMIC)
-#define	RTUSB_URB_FREE_BUFFER(pUsb_Dev, BufSize, pTransferBuf, Dma_addr)   kfree(pTransferBuf)
-#endif
-
-#define RXBULKAGGRE_ZISE        12
-#define MAX_TXBULK_LIMIT        (LOCAL_TXBUF_SIZE*(BULKAGGRE_ZISE-1))
-#define MAX_TXBULK_SIZE         (LOCAL_TXBUF_SIZE*BULKAGGRE_ZISE)
-#define MAX_RXBULK_SIZE         (LOCAL_TXBUF_SIZE*RXBULKAGGRE_ZISE)
-#define MAX_MLME_HANDLER_MEMORY 20
-#define BUFFER_SIZE				2400	//2048
-#define	TX_RING					0xa
-#define	PRIO_RING				0xc
-
-
-// Flags for Bulkflags control for bulk out data
-//
-#define	fRTUSB_BULK_OUT_DATA_NULL				0x00000001
-#define fRTUSB_BULK_OUT_RTS						0x00000002
-#define	fRTUSB_BULK_OUT_MLME					0x00000004
-
-#define	fRTUSB_BULK_OUT_DATA_NORMAL				0x00010000
-#define	fRTUSB_BULK_OUT_DATA_NORMAL_2			0x00020000
-#define	fRTUSB_BULK_OUT_DATA_NORMAL_3			0x00040000
-#define	fRTUSB_BULK_OUT_DATA_NORMAL_4			0x00080000
-#define	fRTUSB_BULK_OUT_DATA_NORMAL_5			0x00100000
-
-#define	fRTUSB_BULK_OUT_PSPOLL					0x00000020
-#define	fRTUSB_BULK_OUT_DATA_FRAG				0x00000040
-#define	fRTUSB_BULK_OUT_DATA_FRAG_2				0x00000080
-#define	fRTUSB_BULK_OUT_DATA_FRAG_3				0x00000100
-#define	fRTUSB_BULK_OUT_DATA_FRAG_4				0x00000200
-
-#ifdef RALINK_ATE
-#define	fRTUSB_BULK_OUT_DATA_ATE				0x00100000
-#endif // RALINK_ATE //
-
-#define RT2870_USB_DEVICES	\
-{	\
-	{USB_DEVICE(0x148F,0x2770)}, /* Ralink */		\
-	{USB_DEVICE(0x148F,0x2870)}, /* Ralink */		\
-	{USB_DEVICE(0x148F,0x3070)}, /* Ralink 3070 */	\
-	{USB_DEVICE(0x148F,0x3071)}, /* Ralink 3071 */	\
-	{USB_DEVICE(0x148F,0x3072)}, /* Ralink 3072 */	\
-	{USB_DEVICE(0x0B05,0x1731)}, /* Asus */			\
-	{USB_DEVICE(0x0B05,0x1732)}, /* Asus */			\
-	{USB_DEVICE(0x0B05,0x1742)}, /* Asus */			\
-	{USB_DEVICE(0x0DF6,0x0017)}, /* Sitecom */		\
-	{USB_DEVICE(0x0DF6,0x002B)}, /* Sitecom */		\
-	{USB_DEVICE(0x0DF6,0x002C)}, /* Sitecom */		\
-	{USB_DEVICE(0x0DF6,0x003E)}, /* Sitecom 3070 */	\
-	{USB_DEVICE(0x0DF6,0x002D)}, /* Sitecom */		\
-	{USB_DEVICE(0x0DF6,0x0039)}, /* Sitecom 2770 */	\
-	{USB_DEVICE(0x14B2,0x3C06)}, /* Conceptronic */	\
-	{USB_DEVICE(0x14B2,0x3C28)}, /* Conceptronic */	\
-	{USB_DEVICE(0x2019,0xED06)}, /* Planex Communications, Inc. */		\
-	{USB_DEVICE(0x2019,0xAB25)}, /* Planex Communications, Inc. RT3070 */		\
-	{USB_DEVICE(0x07D1,0x3C09)}, /* D-Link */		\
-	{USB_DEVICE(0x07D1,0x3C11)}, /* D-Link */		\
-	{USB_DEVICE(0x2001,0x3C09)}, /* D-Link */		\
-	{USB_DEVICE(0x2001,0x3C0A)}, /* D-Link 3072*/	\
-	{USB_DEVICE(0x14B2,0x3C07)}, /* AL */			\
-	{USB_DEVICE(0x14B2,0x3C12)}, /* AL 3070 */		\
-	{USB_DEVICE(0x050D,0x8053)}, /* Belkin */		\
-	{USB_DEVICE(0x14B2,0x3C23)}, /* Airlink */		\
-	{USB_DEVICE(0x14B2,0x3C27)}, /* Airlink */		\
-	{USB_DEVICE(0x07AA,0x002F)}, /* Corega */		\
-	{USB_DEVICE(0x07AA,0x003C)}, /* Corega */		\
-	{USB_DEVICE(0x07AA,0x003F)}, /* Corega */		\
-	{USB_DEVICE(0x18C5,0x0012)}, /* Corega 3070 */	\
-	{USB_DEVICE(0x1044,0x800B)}, /* Gigabyte */		\
-	{USB_DEVICE(0x1044,0x800D)}, /* Gigabyte GN-WB32L 3070 */		\
-	{USB_DEVICE(0x15A9,0x0006)}, /* Sparklan */		\
-	{USB_DEVICE(0x083A,0xB522)}, /* SMC */			\
-	{USB_DEVICE(0x083A,0xA618)}, /* SMC */			\
-	{USB_DEVICE(0x083A,0x8522)}, /* Arcadyan */		\
-	{USB_DEVICE(0x083A,0x7512)}, /* Arcadyan 2770 */		\
-	{USB_DEVICE(0x083A,0x7522)}, /* Arcadyan */		\
-	{USB_DEVICE(0x083A,0x7511)}, /* Arcadyan 3070 */ \
-	{USB_DEVICE(0x0CDE,0x0022)}, /* ZCOM */			\
-	{USB_DEVICE(0x0586,0x3416)}, /* Zyxel */		\
-	{USB_DEVICE(0x0CDE,0x0025)}, /* Zyxel */		\
-	{USB_DEVICE(0x1740,0x9701)}, /* EnGenius */		\
-	{USB_DEVICE(0x1740,0x9702)}, /* EnGenius */		\
-	{USB_DEVICE(0x1740,0x9703)}, /* EnGenius 3070 */		\
-	{USB_DEVICE(0x0471,0x200f)}, /* Philips */		\
-	{USB_DEVICE(0x14B2,0x3C25)}, /* Draytek */		\
-	{USB_DEVICE(0x13D3,0x3247)}, /* AzureWave */	\
-	{USB_DEVICE(0x13D3,0x3273)}, /* AzureWave 3070*/	\
-	{USB_DEVICE(0x083A,0x6618)}, /* Accton */		\
-	{USB_DEVICE(0x15c5,0x0008)}, /* Amit */			\
-	{USB_DEVICE(0x0E66,0x0001)}, /* Hawking */		\
-	{USB_DEVICE(0x0E66,0x0003)}, /* Hawking */		\
-	{USB_DEVICE(0x129B,0x1828)}, /* Siemens */		\
-	{USB_DEVICE(0x157E,0x300E)}, /* U-Media */		\
-	{USB_DEVICE(0x050d,0x805c)},					\
-	{USB_DEVICE(0x1482,0x3C09)}, /* Abocom*/		\
-	{USB_DEVICE(0x14B2,0x3C09)}, /* Alpha */		\
-	{USB_DEVICE(0x04E8,0x2018)}, /* samsung */  	\
-	{USB_DEVICE(0x07B8,0x3070)}, /* AboCom 3070 */	\
-	{USB_DEVICE(0x07B8,0x3071)}, /* AboCom 3071 */	\
-	{USB_DEVICE(0x07B8,0x3072)}, /* Abocom 3072 */	\
-	{USB_DEVICE(0x7392,0x7711)}, /* Edimax 3070 */	\
-	{USB_DEVICE(0x5A57,0x0280)}, /* Zinwell */		\
-	{USB_DEVICE(0x5A57,0x0282)}, /* Zinwell */		\
-	{USB_DEVICE(0x1A32,0x0304)}, /* Quanta 3070 */		\
-	{USB_DEVICE(0x0789,0x0162)}, /* Logitec 2870 */		\
-	{USB_DEVICE(0x0789,0x0163)}, /* Logitec 2870 */		\
-	{USB_DEVICE(0x0789,0x0164)}, /* Logitec 2870 */		\
-	{USB_DEVICE(0x1EDA,0x2310)}, /* AirTies 3070 */		\
-	{ }/* Terminating entry */                      \
-}
-
-#define	FREE_HTTX_RING(_p, _b, _t)			\
-{										\
-	if ((_t)->ENextBulkOutPosition == (_t)->CurWritePosition)				\
-	{																	\
-		(_t)->bRingEmpty = TRUE;			\
-	}																	\
-	/*NdisInterlockedDecrement(&(_p)->TxCount); */\
-}
-
-//
-// RXINFO appends at the end of each rx packet.
-//
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _RXINFO_STRUC {
-	UINT32		PlcpSignal:12;
-	UINT32		LastAMSDU:1;
-	UINT32		CipherAlg:1;
-	UINT32		PlcpRssil:1;
-	UINT32		Decrypted:1;
-	UINT32		AMPDU:1;		// To be moved
-	UINT32		L2PAD:1;
-	UINT32		RSSI:1;
-	UINT32		HTC:1;
-	UINT32		AMSDU:1;		// rx with 802.3 header, not 802.11 header.
-	UINT32		CipherErr:2;        // 0: decryption okay, 1:ICV error, 2:MIC error, 3:KEY not valid
-	UINT32		Crc:1;              // 1: CRC error
-	UINT32		MyBss:1;  	// 1: this frame belongs to the same BSSID
-	UINT32		Bcast:1;            // 1: this is a broadcast frame
-	UINT32		Mcast:1;            // 1: this is a multicast frame
-	UINT32		U2M:1;              // 1: this RX frame is unicast to me
-	UINT32		FRAG:1;
-	UINT32		NULLDATA:1;
-	UINT32		DATA:1;
-	UINT32		BA:1;
-}	RXINFO_STRUC, *PRXINFO_STRUC, RT28XX_RXD_STRUC, *PRT28XX_RXD_STRUC;
-#else
-typedef	struct	PACKED _RXINFO_STRUC {
-	UINT32		BA:1;
-	UINT32		DATA:1;
-	UINT32		NULLDATA:1;
-	UINT32		FRAG:1;
-	UINT32		U2M:1;              // 1: this RX frame is unicast to me
-	UINT32		Mcast:1;            // 1: this is a multicast frame
-	UINT32		Bcast:1;            // 1: this is a broadcast frame
-	UINT32		MyBss:1;  	// 1: this frame belongs to the same BSSID
-	UINT32		Crc:1;              // 1: CRC error
-	UINT32		CipherErr:2;        // 0: decryption okay, 1:ICV error, 2:MIC error, 3:KEY not valid
-	UINT32		AMSDU:1;		// rx with 802.3 header, not 802.11 header.
-	UINT32		HTC:1;
-	UINT32		RSSI:1;
-	UINT32		L2PAD:1;
-	UINT32		AMPDU:1;		// To be moved
-	UINT32		Decrypted:1;
-	UINT32		PlcpRssil:1;
-	UINT32		CipherAlg:1;
-	UINT32		LastAMSDU:1;
-	UINT32		PlcpSignal:12;
-}	RXINFO_STRUC, *PRXINFO_STRUC, RT28XX_RXD_STRUC, *PRT28XX_RXD_STRUC;
-#endif
-
-
-//
-// TXINFO
-//
-#ifdef RT_BIG_ENDIAN
-typedef	struct	_TXINFO_STRUC {
-	// Word	0
-	UINT32		USBDMATxburst:1;//used ONLY in USB bulk Aggre. Force USB DMA transmit frame from current selected endpoint
-	UINT32		USBDMANextVLD:1;	//used ONLY in USB bulk Aggregation, NextValid
-	UINT32		rsv2:2;  // Software use.
-	UINT32		SwUseLastRound:1; // Software use.
-	UINT32		QSEL:2;	// select on-chip FIFO ID for 2nd-stage output scheduler.0:MGMT, 1:HCCA 2:EDCA
-	UINT32		WIV:1;	// Wireless Info Valid. 1 if Driver already fill WI,  o if DMA needs to copy WI to correctposition
-	UINT32		rsv:8;
-	UINT32		USBDMATxPktLen:16;	//used ONLY in USB bulk Aggregation,  Total byte counts of all sub-frame.
-}	TXINFO_STRUC, *PTXINFO_STRUC;
-#else
-typedef	struct	_TXINFO_STRUC {
-	// Word	0
-	UINT32		USBDMATxPktLen:16;	//used ONLY in USB bulk Aggregation,  Total byte counts of all sub-frame.
-	UINT32		rsv:8;
-	UINT32		WIV:1;	// Wireless Info Valid. 1 if Driver already fill WI,  o if DMA needs to copy WI to correctposition
-	UINT32		QSEL:2;	// select on-chip FIFO ID for 2nd-stage output scheduler.0:MGMT, 1:HCCA 2:EDCA
-	UINT32		SwUseLastRound:1; // Software use.
-	UINT32		rsv2:2;  // Software use.
-	UINT32		USBDMANextVLD:1;	//used ONLY in USB bulk Aggregation, NextValid
-	UINT32		USBDMATxburst:1;//used ONLY in USB bulk Aggre. Force USB DMA transmit frame from current selected endpoint
-}	TXINFO_STRUC, *PTXINFO_STRUC;
-#endif
-
-#define TXINFO_SIZE				4
-#define RXINFO_SIZE				4
-#define TXPADDING_SIZE			11
-
-//
-// Management ring buffer format
-//
-typedef	struct	_MGMT_STRUC	{
-	BOOLEAN		Valid;
-	PUCHAR		pBuffer;
-	ULONG		Length;
-}	MGMT_STRUC, *PMGMT_STRUC;
-
-
-/* ----------------- EEPROM Related MACRO ----------------- */
-#ifdef RT30xx
-#define RT28xx_EEPROM_READ16(pAd, offset, var)					\
-	do {														\
-		RTUSBReadEEPROM(pAd, offset, (PUCHAR)&(var), 2);		\
-		if(!pAd->bUseEfuse)										\
-			var = le2cpu16(var);								\
-	}while(0)
-
-#define RT28xx_EEPROM_WRITE16(pAd, offset, var)					\
-	do{															\
-		USHORT _tmpVar=var;										\
-		if(!pAd->bUseEfuse)									\
-		_tmpVar = cpu2le16(var);								\
-		RTUSBWriteEEPROM(pAd, offset, (PUCHAR)&(_tmpVar), 2);	\
-	}while(0)
-#endif // RT30xx //
-#ifndef RT30xx
-#define RT28xx_EEPROM_READ16(pAd, offset, var)					\
-	do {														\
-		RTUSBReadEEPROM(pAd, offset, (PUCHAR)&(var), 2);		\
-			var = le2cpu16(var);								\
-	}while(0)
-
-#define RT28xx_EEPROM_WRITE16(pAd, offset, var)					\
-	do{															\
-		USHORT _tmpVar=var;										\
-		_tmpVar = cpu2le16(var);								\
-		RTUSBWriteEEPROM(pAd, offset, (PUCHAR)&(_tmpVar), 2);	\
-	}while(0)
-#endif // RT30xx //
-
-/* ----------------- TASK/THREAD Related MACRO ----------------- */
-#define RT28XX_TASK_THREAD_INIT(pAd, Status)		\
-	Status = CreateThreads(net_dev);
-
-
-/* ----------------- Frimware Related MACRO ----------------- */
-#define RT28XX_WRITE_FIRMWARE(_pAd, _pFwImage, _FwLen)		\
-	RTUSBFirmwareWrite(_pAd, _pFwImage, _FwLen)
-
-/* ----------------- TX Related MACRO ----------------- */
-#define RT28XX_START_DEQUEUE(pAd, QueIdx, irqFlags)				\
-			{													\
-				RTMP_IRQ_LOCK(&pAd->DeQueueLock[QueIdx], irqFlags);		\
-				if (pAd->DeQueueRunning[QueIdx])						\
-				{														\
-					RTMP_IRQ_UNLOCK(&pAd->DeQueueLock[QueIdx], irqFlags);\
-					printk("DeQueueRunning[%d]= TRUE!\n", QueIdx);		\
-					continue;											\
-				}														\
-				else													\
-				{														\
-					pAd->DeQueueRunning[QueIdx] = TRUE;					\
-					RTMP_IRQ_UNLOCK(&pAd->DeQueueLock[QueIdx], irqFlags);\
-				}														\
-			}
-#define RT28XX_STOP_DEQUEUE(pAd, QueIdx, irqFlags)						\
-			do{															\
-				RTMP_IRQ_LOCK(&pAd->DeQueueLock[QueIdx], irqFlags);		\
-				pAd->DeQueueRunning[QueIdx] = FALSE;					\
-				RTMP_IRQ_UNLOCK(&pAd->DeQueueLock[QueIdx], irqFlags);	\
-			}while(0)
-
-
-#define	RT28XX_HAS_ENOUGH_FREE_DESC(pAd, pTxBlk, freeNum, pPacket) \
-		(RTUSBFreeDescriptorRequest(pAd, pTxBlk->QueIdx, (pTxBlk->TotalFrameLen + GET_OS_PKT_LEN(pPacket))) == NDIS_STATUS_SUCCESS)
-
-#define RT28XX_RELEASE_DESC_RESOURCE(pAd, QueIdx)			\
-		do{}while(0)
-
-#define NEED_QUEUE_BACK_FOR_AGG(_pAd, _QueIdx, _freeNum, _TxFrameType) 		\
-		((_TxFrameType == TX_RALINK_FRAME) && (RTUSBNeedQueueBackForAgg(_pAd, _QueIdx)))
-
-
-
-#define fRTMP_ADAPTER_NEED_STOP_TX		\
-		(fRTMP_ADAPTER_NIC_NOT_EXIST | fRTMP_ADAPTER_HALT_IN_PROGRESS |	\
-		 fRTMP_ADAPTER_RESET_IN_PROGRESS | fRTMP_ADAPTER_BULKOUT_RESET | \
-		 fRTMP_ADAPTER_RADIO_OFF | fRTMP_ADAPTER_REMOVE_IN_PROGRESS)
-
-
-#define HAL_WriteSubTxResource(pAd, pTxBlk, bIsLast, pFreeNumber)	\
-			RtmpUSB_WriteSubTxResource(pAd, pTxBlk, bIsLast, pFreeNumber)
-
-#define HAL_WriteTxResource(pAd, pTxBlk,bIsLast, pFreeNumber)	\
-			RtmpUSB_WriteSingleTxResource(pAd, pTxBlk,bIsLast, pFreeNumber)
-
-#define HAL_WriteFragTxResource(pAd, pTxBlk, fragNum, pFreeNumber) \
-			RtmpUSB_WriteFragTxResource(pAd, pTxBlk, fragNum, pFreeNumber)
-
-#define HAL_WriteMultiTxResource(pAd, pTxBlk,frameNum, pFreeNumber)	\
-			RtmpUSB_WriteMultiTxResource(pAd, pTxBlk,frameNum, pFreeNumber)
-
-#define HAL_FinalWriteTxResource(pAd, pTxBlk, totalMPDUSize, TxIdx)	\
-			RtmpUSB_FinalWriteTxResource(pAd, pTxBlk, totalMPDUSize, TxIdx)
-
-#define HAL_LastTxIdx(pAd, QueIdx,TxIdx) \
-			/*RtmpUSBDataLastTxIdx(pAd, QueIdx,TxIdx)*/
-
-#define HAL_KickOutTx(pAd, pTxBlk, QueIdx)	\
-			RtmpUSBDataKickOut(pAd, pTxBlk, QueIdx)
-
-
-#define HAL_KickOutMgmtTx(pAd, QueIdx, pPacket, pSrcBufVA, SrcBufLen)	\
-			RtmpUSBMgmtKickOut(pAd, QueIdx, pPacket, pSrcBufVA, SrcBufLen)
-
-#define HAL_KickOutNullFrameTx(_pAd, _QueIdx, _pNullFrame, _frameLen)	\
-			RtmpUSBNullFrameKickOut(_pAd, _QueIdx, _pNullFrame, _frameLen)
-
-#define RTMP_PKT_TAIL_PADDING 	11 // 3(max 4 byte padding) + 4 (last packet padding) + 4 (MaxBulkOutsize align padding)
-
-extern UCHAR EpToQueue[6];
-
-
-#ifdef RT2870
-#define GET_TXRING_FREENO(_pAd, _QueIdx) 	(_QueIdx) //(_pAd->TxRing[_QueIdx].TxSwFreeIdx)
-#define GET_MGMTRING_FREENO(_pAd) 			(_pAd->MgmtRing.TxSwFreeIdx)
-#endif // RT2870 //
-
-
-/* ----------------- RX Related MACRO ----------------- */
-//#define RT28XX_RX_ERROR_CHECK				RTMPCheckRxWI
-
-#define RT28XX_RV_ALL_BUF_END(bBulkReceive)		\
-	/* We return STATUS_MORE_PROCESSING_REQUIRED so that the completion */	\
-	/* routine (IofCompleteRequest) will stop working on the irp. */		\
-	if (bBulkReceive == TRUE)	RTUSBBulkReceive(pAd);
-
-
-/* ----------------- ASIC Related MACRO ----------------- */
-// reset MAC of a station entry to 0xFFFFFFFFFFFF
-#define RT28XX_STA_ENTRY_MAC_RESET(pAd, Wcid)					\
-	{	RT_SET_ASIC_WCID	SetAsicWcid;						\
-		SetAsicWcid.WCID = Wcid;								\
-		SetAsicWcid.SetTid = 0xffffffff;						\
-		SetAsicWcid.DeleteTid = 0xffffffff;						\
-		RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_SET_ASIC_WCID, 	\
-				&SetAsicWcid, sizeof(RT_SET_ASIC_WCID));	}
-
-// add this entry into ASIC RX WCID search table
-#define RT28XX_STA_ENTRY_ADD(pAd, pEntry)							\
-	RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_SET_CLIENT_MAC_ENTRY, 	\
-							pEntry, sizeof(MAC_TABLE_ENTRY));
-
-// add by johnli, fix "in_interrupt" error when call "MacTableDeleteEntry" in Rx tasklet
-// Set MAC register value according operation mode
-#define RT28XX_UPDATE_PROTECT(pAd)	\
- 	RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_UPDATE_PROTECT, NULL, 0);
-// end johnli
-
-// remove Pair-wise key material from ASIC
-// yet implement
-#define RT28XX_STA_ENTRY_KEY_DEL(pAd, BssIdx, Wcid)
-
-// add Client security information into ASIC WCID table and IVEIV table
-#define RT28XX_STA_SECURITY_INFO_ADD(pAd, apidx, KeyID, pEntry)						\
-	{	RT28XX_STA_ENTRY_MAC_RESET(pAd, pEntry->Aid);								\
-		if (pEntry->Aid >= 1) {														\
-			RT_SET_ASIC_WCID_ATTRI	SetAsicWcidAttri;								\
-			SetAsicWcidAttri.WCID = pEntry->Aid;									\
-			if ((pEntry->AuthMode <= Ndis802_11AuthModeAutoSwitch) &&				\
-				(pEntry->WepStatus == Ndis802_11Encryption1Enabled))				\
-			{																		\
-				SetAsicWcidAttri.Cipher = pAd->SharedKey[apidx][KeyID].CipherAlg;	\
-			}																		\
-			else if (pEntry->AuthMode == Ndis802_11AuthModeWPANone)					\
-			{																		\
-				SetAsicWcidAttri.Cipher = pAd->SharedKey[apidx][KeyID].CipherAlg;	\
-			}																		\
-			else SetAsicWcidAttri.Cipher = 0;										\
-            DBGPRINT(RT_DEBUG_TRACE, ("aid cipher = %ld\n",SetAsicWcidAttri.Cipher));       \
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_SET_ASIC_WCID_CIPHER, 			\
-							&SetAsicWcidAttri, sizeof(RT_SET_ASIC_WCID_ATTRI)); } }
-
-// Insert the BA bitmap to ASIC for the Wcid entry
-#define RT28XX_ADD_BA_SESSION_TO_ASIC(_pAd, _Aid, _TID)					\
-		do{																\
-			RT_SET_ASIC_WCID	SetAsicWcid;							\
-			SetAsicWcid.WCID = (_Aid);									\
-			SetAsicWcid.SetTid = (0x10000<<(_TID));						\
-			SetAsicWcid.DeleteTid = 0xffffffff;							\
-			RTUSBEnqueueInternalCmd((_pAd), CMDTHREAD_SET_ASIC_WCID, &SetAsicWcid, sizeof(RT_SET_ASIC_WCID));	\
-		}while(0)
-
-// Remove the BA bitmap from ASIC for the Wcid entry
-#define RT28XX_DEL_BA_SESSION_FROM_ASIC(_pAd, _Wcid, _TID)				\
-		do{																\
-			RT_SET_ASIC_WCID	SetAsicWcid;							\
-			SetAsicWcid.WCID = (_Wcid);									\
-			SetAsicWcid.SetTid = (0xffffffff);							\
-			SetAsicWcid.DeleteTid = (0x10000<<(_TID) );					\
-			RTUSBEnqueueInternalCmd((_pAd), CMDTHREAD_SET_ASIC_WCID, &SetAsicWcid, sizeof(RT_SET_ASIC_WCID));	\
-		}while(0)
-
-
-/* ----------------- PCI/USB Related MACRO ----------------- */
-#define RT28XX_HANDLE_DEV_ASSIGN(handle, dev_p)			\
-	((POS_COOKIE)handle)->pUsb_Dev = dev_p;
-
-// no use
-#define RT28XX_UNMAP()
-#define RT28XX_IRQ_REQUEST(net_dev)
-#define RT28XX_IRQ_RELEASE(net_dev)
-#define RT28XX_IRQ_INIT(pAd)
-#define RT28XX_IRQ_ENABLE(pAd)
-
-
-/* ----------------- MLME Related MACRO ----------------- */
-#define RT28XX_MLME_HANDLER(pAd)			RTUSBMlmeUp(pAd)
-
-#define RT28XX_MLME_PRE_SANITY_CHECK(pAd)								\
-	{	if ((pAd->CommonCfg.bHardwareRadio == TRUE) && 					\
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&		\
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS))) {	\
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_CHECK_GPIO, NULL, 0); } }
-
-#define RT28XX_MLME_STA_QUICK_RSP_WAKE_UP(pAd)	\
-	{	RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_QKERIODIC_EXECUT, NULL, 0);	\
-		RTUSBMlmeUp(pAd); }
-
-#define RT28XX_MLME_RESET_STATE_MACHINE(pAd)	\
-		        MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_RESET_CONF, 0, NULL);	\
-		        RTUSBMlmeUp(pAd);
-
-#define RT28XX_HANDLE_COUNTER_MEASURE(_pAd, _pEntry)		\
-	{	RTUSBEnqueueInternalCmd(_pAd, CMDTHREAD_802_11_COUNTER_MEASURE, _pEntry, sizeof(MAC_TABLE_ENTRY));	\
-		RTUSBMlmeUp(_pAd);									\
-	}
-
-
-/* ----------------- Power Save Related MACRO ----------------- */
-#define RT28XX_PS_POLL_ENQUEUE(pAd)						\
-	{	RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_PSPOLL);	\
-		RTUSBKickBulkOut(pAd); }
-
-#define RT28xx_CHIP_NAME            "RT2870"
-#define USB_CYC_CFG                 0x02a4
-#define NT_SUCCESS(status)			(((status) > 0) ? (1):(0))
-#define InterlockedIncrement 	 	atomic_inc
-#define NdisInterlockedIncrement 	atomic_inc
-#define InterlockedDecrement		atomic_dec
-#define NdisInterlockedDecrement 	atomic_dec
-#define InterlockedExchange			atomic_set
-//#define NdisMSendComplete			RTMP_SendComplete
-#define NdisMCancelTimer			RTMPCancelTimer
-#define NdisAllocMemory(_ptr, _size, _flag)	\
-									do{_ptr = kmalloc((_size),(_flag));}while(0)
-#define NdisFreeMemory(a, b, c) 	kfree((a))
-#define NdisMSleep					RTMPusecDelay		/* unit: microsecond */
-
-
-#define USBD_TRANSFER_DIRECTION_OUT		0
-#define USBD_TRANSFER_DIRECTION_IN		0
-#define USBD_SHORT_TRANSFER_OK			0
-#define PURB			purbb_t
-
-#define RTUSB_FREE_URB(pUrb)	usb_free_urb(pUrb)
-
-//#undef MlmeAllocateMemory
-//#undef MlmeFreeMemory
-
-typedef struct usb_device	* PUSB_DEV;
-
-/* MACRO for linux usb */
-typedef struct urb *purbb_t;
-typedef struct usb_ctrlrequest devctrlrequest;
-#define PIRP		PVOID
-#define PMDL		PVOID
-#define NDIS_OID	UINT
-#ifndef USB_ST_NOERROR
-#define USB_ST_NOERROR     0
-#endif
-
-// vendor-specific control operations
-#define CONTROL_TIMEOUT_JIFFIES ( (100 * HZ) / 1000)
-#define UNLINK_TIMEOUT_MS		3
-
-/* unlink urb	*/
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,7)
-#define RTUSB_UNLINK_URB(pUrb)		usb_kill_urb(pUrb)
-#else
-#define RTUSB_UNLINK_URB(pUrb)		usb_unlink_urb(pUrb)
-#endif
-
-// Prototypes of completion funuc.
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-#define RTUSBBulkOutDataPacketComplete(purb, pt_regs)    RTUSBBulkOutDataPacketComplete(purb)
-#define RTUSBBulkOutMLMEPacketComplete(pUrb, pt_regs)    RTUSBBulkOutMLMEPacketComplete(pUrb)
-#define RTUSBBulkOutNullFrameComplete(pUrb, pt_regs)     RTUSBBulkOutNullFrameComplete(pUrb)
-#define RTUSBBulkOutRTSFrameComplete(pUrb, pt_regs)      RTUSBBulkOutRTSFrameComplete(pUrb)
-#define RTUSBBulkOutPsPollComplete(pUrb, pt_regs)        RTUSBBulkOutPsPollComplete(pUrb)
-#define RTUSBBulkRxComplete(pUrb, pt_regs)               RTUSBBulkRxComplete(pUrb)
-#endif
-
-
-VOID RTUSBBulkOutDataPacketComplete(purbb_t purb, struct pt_regs *pt_regs);
-VOID RTUSBBulkOutMLMEPacketComplete(purbb_t pUrb, struct pt_regs *pt_regs);
-VOID RTUSBBulkOutNullFrameComplete(purbb_t pUrb, struct pt_regs *pt_regs);
-VOID RTUSBBulkOutRTSFrameComplete(purbb_t pUrb, struct pt_regs *pt_regs);
-VOID RTUSBBulkOutPsPollComplete(purbb_t pUrb, struct pt_regs *pt_regs);
-VOID RTUSBBulkRxComplete(purbb_t pUrb, struct pt_regs *pt_regs);
-
-
-#define RTUSBMlmeUp(pAd)	        \
-{								    \
-	POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;	\
-	if(pObj->MLMEThr_pid>0)		    \
-        up(&(pAd->mlme_semaphore)); \
-}
-
-#define RTUSBCMDUp(pAd)	                \
-{									    \
-	POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;	\
-	if(pObj->RTUSBCmdThr_pid>0)		    \
-	    up(&(pAd->RTUSBCmd_semaphore)); \
-}
-
-
-static inline NDIS_STATUS RTMPAllocateMemory(
-	OUT PVOID *ptr,
-	IN size_t size)
-{
-	*ptr = kmalloc(size, GFP_ATOMIC);
-	if(*ptr)
-		return NDIS_STATUS_SUCCESS;
-	else
-		return NDIS_STATUS_RESOURCES;
-}
-
-/* rtmp.h */
-#define	BEACON_RING_SIZE                2
-#define DEVICE_VENDOR_REQUEST_OUT       0x40
-#define DEVICE_VENDOR_REQUEST_IN        0xc0
-#define INTERFACE_VENDOR_REQUEST_OUT    0x41
-#define INTERFACE_VENDOR_REQUEST_IN     0xc1
-#define MGMTPIPEIDX						0	// EP6 is highest priority
-
-#define BULKOUT_MGMT_RESET_FLAG				0x80
-
-#define RTUSB_SET_BULK_FLAG(_M, _F)				((_M)->BulkFlags |= (_F))
-#define RTUSB_CLEAR_BULK_FLAG(_M, _F)			((_M)->BulkFlags &= ~(_F))
-#define RTUSB_TEST_BULK_FLAG(_M, _F)			(((_M)->BulkFlags & (_F)) != 0)
-
-#define EnqueueCmd(cmdq, cmdqelmt)		\
-{										\
-	if (cmdq->size == 0)				\
-		cmdq->head = cmdqelmt;			\
-	else								\
-		cmdq->tail->next = cmdqelmt;	\
-	cmdq->tail = cmdqelmt;				\
-	cmdqelmt->next = NULL;				\
-	cmdq->size++;						\
-}
-
-typedef struct   _RT_SET_ASIC_WCID {
-	ULONG WCID;          // mechanism for rekeying: 0:disable, 1: time-based, 2: packet-based
-	ULONG SetTid;        // time-based: seconds, packet-based: kilo-packets
-	ULONG DeleteTid;        // time-based: seconds, packet-based: kilo-packets
-} RT_SET_ASIC_WCID,*PRT_SET_ASIC_WCID;
-
-typedef struct   _RT_SET_ASIC_WCID_ATTRI {
-	ULONG	WCID;          // mechanism for rekeying: 0:disable, 1: time-based, 2: packet-based
-	ULONG	Cipher;        // ASIC Cipher definition
-	UCHAR	Addr[ETH_LENGTH_OF_ADDRESS];
-} RT_SET_ASIC_WCID_ATTRI,*PRT_SET_ASIC_WCID_ATTRI;
-
-typedef struct _MLME_MEMORY_STRUCT {
-	PVOID                           AllocVa;    //Pointer to the base virtual address of the allocated memory
-	struct _MLME_MEMORY_STRUCT      *Next;      //Pointer to the next virtual address of the allocated memory
-}   MLME_MEMORY_STRUCT, *PMLME_MEMORY_STRUCT;
-
-typedef struct  _MLME_MEMORY_HANDLER {
-	BOOLEAN                 MemRunning;         //The flag of the Mlme memory handler's status
-	UINT                    MemoryCount;        //Total nonpaged system-space memory not size
-	UINT                    InUseCount;         //Nonpaged system-space memory in used counts
-	UINT                    UnUseCount;         //Nonpaged system-space memory available counts
-	INT                    PendingCount;       //Nonpaged system-space memory for free counts
-	PMLME_MEMORY_STRUCT     pInUseHead;         //Pointer to the first nonpaed memory not used
-	PMLME_MEMORY_STRUCT     pInUseTail;         //Pointer to the last nonpaged memory not used
-	PMLME_MEMORY_STRUCT     pUnUseHead;         //Pointer to the first nonpaged memory in used
-	PMLME_MEMORY_STRUCT     pUnUseTail;         //Pointer to the last nonpaged memory in used
-	PULONG                  MemFreePending[MAX_MLME_HANDLER_MEMORY];   //an array to keep pending free-memory's pointer (32bits)
-}   MLME_MEMORY_HANDLER, *PMLME_MEMORY_HANDLER;
-
-typedef	struct _CmdQElmt	{
-	UINT				command;
-	PVOID				buffer;
-	ULONG				bufferlength;
-	BOOLEAN				CmdFromNdis;
-	BOOLEAN				SetOperation;
-	struct _CmdQElmt	*next;
-}	CmdQElmt, *PCmdQElmt;
-
-typedef	struct	_CmdQ	{
-	UINT		size;
-	CmdQElmt	*head;
-	CmdQElmt	*tail;
-	UINT32		CmdQState;
-}CmdQ, *PCmdQ;
-
-//
-// For WPA SUPPLICANT: WIRELESS EXT support wireless events: v14 or newer
-//
-#if WIRELESS_EXT >= 14
-//#define WPA_SUPPLICANT_SUPPORT  1
-#endif
-
-/* oid.h */
-// Cipher suite type for mixed mode group cipher, P802.11i-2004
-typedef enum _RT_802_11_CIPHER_SUITE_TYPE {
-	Cipher_Type_NONE,
-	Cipher_Type_WEP40,
-	Cipher_Type_TKIP,
-	Cipher_Type_RSVD,
-	Cipher_Type_CCMP,
-	Cipher_Type_WEP104
-} RT_802_11_CIPHER_SUITE_TYPE, *PRT_802_11_CIPHER_SUITE_TYPE;
-
-//CMDTHREAD_MULTI_READ_MAC
-//CMDTHREAD_MULTI_WRITE_MAC
-//CMDTHREAD_VENDOR_EEPROM_READ
-//CMDTHREAD_VENDOR_EEPROM_WRITE
-typedef	struct	_CMDHandler_TLV	{
-	USHORT		Offset;
-	USHORT		Length;
-	UCHAR		DataFirst;
-}	CMDHandler_TLV, *PCMDHandler_TLV;
-
-// New for MeetingHouse Api support
-#define CMDTHREAD_VENDOR_RESET                      0x0D730101	// cmd
-#define CMDTHREAD_VENDOR_UNPLUG                     0x0D730102	// cmd
-#define CMDTHREAD_VENDOR_SWITCH_FUNCTION            0x0D730103	// cmd
-#define CMDTHREAD_MULTI_WRITE_MAC                   0x0D730107	// cmd
-#define CMDTHREAD_MULTI_READ_MAC                    0x0D730108	// cmd
-#define CMDTHREAD_VENDOR_EEPROM_WRITE               0x0D73010A	// cmd
-#define CMDTHREAD_VENDOR_EEPROM_READ                0x0D73010B	// cmd
-#define CMDTHREAD_VENDOR_ENTER_TESTMODE             0x0D73010C	// cmd
-#define CMDTHREAD_VENDOR_EXIT_TESTMODE              0x0D73010D	// cmd
-#define CMDTHREAD_VENDOR_WRITE_BBP                  0x0D730119	// cmd
-#define CMDTHREAD_VENDOR_READ_BBP                   0x0D730118	// cmd
-#define CMDTHREAD_VENDOR_WRITE_RF                   0x0D73011A	// cmd
-#define CMDTHREAD_VENDOR_FLIP_IQ                    0x0D73011D	// cmd
-#define CMDTHREAD_RESET_BULK_OUT                    0x0D730210	// cmd
-#define CMDTHREAD_RESET_BULK_IN                     0x0D730211	// cmd
-#define CMDTHREAD_SET_PSM_BIT_SAVE                  0x0D730212	// cmd
-#define CMDTHREAD_SET_RADIO                         0x0D730214	// cmd
-#define CMDTHREAD_UPDATE_TX_RATE                    0x0D730216	// cmd
-#define CMDTHREAD_802_11_ADD_KEY_WEP                0x0D730218	// cmd
-#define CMDTHREAD_RESET_FROM_ERROR                  0x0D73021A	// cmd
-#define CMDTHREAD_LINK_DOWN                         0x0D73021B	// cmd
-#define CMDTHREAD_RESET_FROM_NDIS                   0x0D73021C	// cmd
-#define CMDTHREAD_CHECK_GPIO                        0x0D730215	// cmd
-#define CMDTHREAD_FORCE_WAKE_UP                     0x0D730222	// cmd
-#define CMDTHREAD_SET_BW                            0x0D730225	// cmd
-#define CMDTHREAD_SET_ASIC_WCID                     0x0D730226	// cmd
-#define CMDTHREAD_SET_ASIC_WCID_CIPHER              0x0D730227	// cmd
-#define CMDTHREAD_QKERIODIC_EXECUT                  0x0D73023D	// cmd
-#define RT_CMD_SET_KEY_TABLE                        0x0D730228  // cmd
-#define RT_CMD_SET_RX_WCID_TABLE                    0x0D730229  // cmd
-#define CMDTHREAD_SET_CLIENT_MAC_ENTRY              0x0D73023E	// cmd
-#define CMDTHREAD_802_11_QUERY_HARDWARE_REGISTER    0x0D710105	// cmd
-#define CMDTHREAD_802_11_SET_PHY_MODE               0x0D79010C	// cmd
-#define CMDTHREAD_802_11_SET_STA_CONFIG             0x0D790111	// cmd
-#define CMDTHREAD_802_11_SET_PREAMBLE               0x0D790101	// cmd
-#define CMDTHREAD_802_11_COUNTER_MEASURE			0x0D790102	// cmd
-// add by johnli, fix "in_interrupt" error when call "MacTableDeleteEntry" in Rx tasklet
-#define CMDTHREAD_UPDATE_PROTECT					0x0D790103	// cmd
-// end johnli
-
-#define WPA1AKMBIT	    0x01
-#define WPA2AKMBIT	    0x02
-#define WPA1PSKAKMBIT   0x04
-#define WPA2PSKAKMBIT   0x08
-#define TKIPBIT         0x01
-#define CCMPBIT         0x02
-
-
-#define RT28XX_STA_FORCE_WAKEUP(pAd, bFromTx) \
-    RT28xxUsbStaAsicForceWakeup(pAd, bFromTx);
-
-#define RT28XX_STA_SLEEP_THEN_AUTO_WAKEUP(pAd, TbttNumToNextWakeUp) \
-    RT28xxUsbStaAsicSleepThenAutoWakeup(pAd, TbttNumToNextWakeUp);
-
-#define RT28XX_MLME_RADIO_ON(pAd) \
-    RT28xxUsbMlmeRadioOn(pAd);
-
-#define RT28XX_MLME_RADIO_OFF(pAd) \
-    RT28xxUsbMlmeRadioOFF(pAd);
-
-#endif //__RT2870_H__
+#include "../rt2870/rt2870.h"
diff --git a/drivers/staging/rt3070/rt28xx.h b/drivers/staging/rt3070/rt28xx.h
index b637c4e..c47ddc8 100644
--- a/drivers/staging/rt3070/rt28xx.h
+++ b/drivers/staging/rt3070/rt28xx.h
@@ -1,2725 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rt28xx.h
-
-	Abstract:
-	RT28xx ASIC related definition & structures
-
-	Revision History:
-	Who			When		  What
-	--------	----------	  ----------------------------------------------
-       Jan Lee           Jan-3-2006     created for RT2860c
-*/
-
-#ifndef	__RT28XX_H__
-#define	__RT28XX_H__
-
-
-//
-// PCI registers - base address 0x0000
-//
-#define PCI_CFG			0x0000
-#define PCI_EECTRL			0x0004
-#define PCI_MCUCTRL			0x0008
-
-#define	OPT_14			0x114
-
-typedef int				NTSTATUS;
-#define	RETRY_LIMIT             10
-#define STATUS_SUCCESS				0x00
-#define STATUS_UNSUCCESSFUL 		0x01
-
-//
-// SCH/DMA registers - base address 0x0200
-//
-// INT_SOURCE_CSR: Interrupt source register. Write one to clear corresponding bit
-//
-#define DMA_CSR0      0x200
-#define INT_SOURCE_CSR      0x200
-#ifdef RT_BIG_ENDIAN
-typedef	union	_INT_SOURCE_CSR_STRUC	{
-	struct	{
-		UINT32       	:14;
-		UINT32       	TxCoherent:1;
-		UINT32       	RxCoherent:1;
-		UINT32       	GPTimer:1;
-		UINT32       	AutoWakeup:1;//bit14
-		UINT32       	TXFifoStatusInt:1;//FIFO Statistics is full, sw should read 0x171c
-		UINT32       	PreTBTT:1;
-		UINT32       	TBTTInt:1;
-		UINT32       	RxTxCoherent:1;
-		UINT32       	MCUCommandINT:1;
-		UINT32       	MgmtDmaDone:1;
-		UINT32       	HccaDmaDone:1;
-		UINT32       	Ac3DmaDone:1;
-		UINT32       	Ac2DmaDone:1;
-		UINT32       	Ac1DmaDone:1;
-		UINT32		Ac0DmaDone:1;
-		UINT32		RxDone:1;
-		UINT32		TxDelayINT:1;	//delayed interrupt, not interrupt until several int or time limit hit
-		UINT32		RxDelayINT:1; //dealyed interrupt
-	}	field;
-	UINT32			word;
-}	INT_SOURCE_CSR_STRUC, *PINT_SOURCE_CSR_STRUC;
-#else
-typedef	union	_INT_SOURCE_CSR_STRUC	{
-	struct	{
-		UINT32		RxDelayINT:1;
-		UINT32		TxDelayINT:1;
-		UINT32		RxDone:1;
-		UINT32		Ac0DmaDone:1;//4
-		UINT32       	Ac1DmaDone:1;
-		UINT32       	Ac2DmaDone:1;
-		UINT32       	Ac3DmaDone:1;
-		UINT32       	HccaDmaDone:1; // bit7
-		UINT32       	MgmtDmaDone:1;
-		UINT32       	MCUCommandINT:1;//bit 9
-		UINT32       	RxTxCoherent:1;
-		UINT32       	TBTTInt:1;
-		UINT32       	PreTBTT:1;
-		UINT32       	TXFifoStatusInt:1;//FIFO Statistics is full, sw should read 0x171c
-		UINT32       	AutoWakeup:1;//bit14
-		UINT32       	GPTimer:1;
-		UINT32       	RxCoherent:1;//bit16
-		UINT32       	TxCoherent:1;
-		UINT32       	:14;
-	}	field;
-	UINT32			word;
-} INT_SOURCE_CSR_STRUC, *PINT_SOURCE_CSR_STRUC;
-#endif
-
-//
-// INT_MASK_CSR:   Interrupt MASK register.   1: the interrupt is mask OFF
-//
-#define INT_MASK_CSR        0x204
-#ifdef RT_BIG_ENDIAN
-typedef	union	_INT_MASK_CSR_STRUC	{
-	struct	{
-		UINT32       	TxCoherent:1;
-		UINT32       	RxCoherent:1;
-		UINT32       	:20;
-		UINT32       	MCUCommandINT:1;
-		UINT32       	MgmtDmaDone:1;
-		UINT32       	HccaDmaDone:1;
-		UINT32       	Ac3DmaDone:1;
-		UINT32       	Ac2DmaDone:1;
-		UINT32       	Ac1DmaDone:1;
-		UINT32		Ac0DmaDone:1;
-		UINT32		RxDone:1;
-		UINT32		TxDelay:1;
-		UINT32		RXDelay_INT_MSK:1;
-	}	field;
-	UINT32			word;
-}INT_MASK_CSR_STRUC, *PINT_MASK_CSR_STRUC;
-#else
-typedef	union	_INT_MASK_CSR_STRUC	{
-	struct	{
-		UINT32		RXDelay_INT_MSK:1;
-		UINT32		TxDelay:1;
-		UINT32		RxDone:1;
-		UINT32		Ac0DmaDone:1;
-		UINT32       	Ac1DmaDone:1;
-		UINT32       	Ac2DmaDone:1;
-		UINT32       	Ac3DmaDone:1;
-		UINT32       	HccaDmaDone:1;
-		UINT32       	MgmtDmaDone:1;
-		UINT32       	MCUCommandINT:1;
-		UINT32       	:20;
-		UINT32       	RxCoherent:1;
-		UINT32       	TxCoherent:1;
-	}	field;
-	UINT32			word;
-} INT_MASK_CSR_STRUC, *PINT_MASK_CSR_STRUC;
-#endif
-#define WPDMA_GLO_CFG 	0x208
-#ifdef RT_BIG_ENDIAN
-typedef	union	_WPDMA_GLO_CFG_STRUC	{
-	struct	{
-		UINT32       	HDR_SEG_LEN:16;
-		UINT32       	RXHdrScater:8;
-		UINT32       	BigEndian:1;
-		UINT32       	EnTXWriteBackDDONE:1;
-		UINT32       	WPDMABurstSIZE:2;
-		UINT32		RxDMABusy:1;
-		UINT32		EnableRxDMA:1;
-		UINT32		TxDMABusy:1;
-		UINT32		EnableTxDMA:1;
-	}	field;
-	UINT32			word;
-}WPDMA_GLO_CFG_STRUC, *PWPDMA_GLO_CFG_STRUC;
-#else
-typedef	union	_WPDMA_GLO_CFG_STRUC	{
-	struct	{
-		UINT32		EnableTxDMA:1;
-		UINT32		TxDMABusy:1;
-		UINT32		EnableRxDMA:1;
-		UINT32		RxDMABusy:1;
-		UINT32       	WPDMABurstSIZE:2;
-		UINT32       	EnTXWriteBackDDONE:1;
-		UINT32       	BigEndian:1;
-		UINT32       	RXHdrScater:8;
-		UINT32       	HDR_SEG_LEN:16;
-	}	field;
-	UINT32			word;
-} WPDMA_GLO_CFG_STRUC, *PWPDMA_GLO_CFG_STRUC;
-#endif
-#define WPDMA_RST_IDX 	0x20c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_WPDMA_RST_IDX_STRUC	{
-	struct	{
-		UINT32       	:15;
-		UINT32       	RST_DRX_IDX0:1;
-		UINT32       	rsv:10;
-		UINT32       	RST_DTX_IDX5:1;
-		UINT32       	RST_DTX_IDX4:1;
-		UINT32		RST_DTX_IDX3:1;
-		UINT32		RST_DTX_IDX2:1;
-		UINT32		RST_DTX_IDX1:1;
-		UINT32		RST_DTX_IDX0:1;
-	}	field;
-	UINT32			word;
-}WPDMA_RST_IDX_STRUC, *PWPDMA_RST_IDX_STRUC;
-#else
-typedef	union	_WPDMA_RST_IDX_STRUC	{
-	struct	{
-		UINT32		RST_DTX_IDX0:1;
-		UINT32		RST_DTX_IDX1:1;
-		UINT32		RST_DTX_IDX2:1;
-		UINT32		RST_DTX_IDX3:1;
-		UINT32       	RST_DTX_IDX4:1;
-		UINT32       	RST_DTX_IDX5:1;
-		UINT32       	rsv:10;
-		UINT32       	RST_DRX_IDX0:1;
-		UINT32       	:15;
-	}	field;
-	UINT32			word;
-} WPDMA_RST_IDX_STRUC, *PWPDMA_RST_IDX_STRUC;
-#endif
-#define DELAY_INT_CFG  0x0210
-#ifdef RT_BIG_ENDIAN
-typedef	union	_DELAY_INT_CFG_STRUC	{
-	struct	{
-		UINT32       	TXDLY_INT_EN:1;
-		UINT32       	TXMAX_PINT:7;
-		UINT32       	TXMAX_PTIME:8;
-		UINT32       	RXDLY_INT_EN:1;
-		UINT32       	RXMAX_PINT:7;
-		UINT32		RXMAX_PTIME:8;
-	}	field;
-	UINT32			word;
-}DELAY_INT_CFG_STRUC, *PDELAY_INT_CFG_STRUC;
-#else
-typedef	union	_DELAY_INT_CFG_STRUC	{
-	struct	{
-		UINT32		RXMAX_PTIME:8;
-		UINT32       	RXMAX_PINT:7;
-		UINT32       	RXDLY_INT_EN:1;
-		UINT32       	TXMAX_PTIME:8;
-		UINT32       	TXMAX_PINT:7;
-		UINT32       	TXDLY_INT_EN:1;
-	}	field;
-	UINT32			word;
-} DELAY_INT_CFG_STRUC, *PDELAY_INT_CFG_STRUC;
-#endif
-#define WMM_AIFSN_CFG   0x0214
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AIFSN_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:16;
-	    UINT32   Aifsn3:4;       // for AC_VO
-	    UINT32   Aifsn2:4;       // for AC_VI
-	    UINT32   Aifsn1:4;       // for AC_BK
-	    UINT32   Aifsn0:4;       // for AC_BE
-	}	field;
-	UINT32			word;
-}	AIFSN_CSR_STRUC, *PAIFSN_CSR_STRUC;
-#else
-typedef	union	_AIFSN_CSR_STRUC	{
-	struct	{
-	    UINT32   Aifsn0:4;       // for AC_BE
-	    UINT32   Aifsn1:4;       // for AC_BK
-	    UINT32   Aifsn2:4;       // for AC_VI
-	    UINT32   Aifsn3:4;       // for AC_VO
-	    UINT32   Rsv:16;
-	}	field;
-	UINT32			word;
-}	AIFSN_CSR_STRUC, *PAIFSN_CSR_STRUC;
-#endif
-//
-// CWMIN_CSR: CWmin for each EDCA AC
-//
-#define WMM_CWMIN_CFG   0x0218
-#ifdef RT_BIG_ENDIAN
-typedef	union	_CWMIN_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:16;
-	    UINT32   Cwmin3:4;       // for AC_VO
-	    UINT32   Cwmin2:4;       // for AC_VI
-	    UINT32   Cwmin1:4;       // for AC_BK
-	    UINT32   Cwmin0:4;       // for AC_BE
-	}	field;
-	UINT32			word;
-}	CWMIN_CSR_STRUC, *PCWMIN_CSR_STRUC;
-#else
-typedef	union	_CWMIN_CSR_STRUC	{
-	struct	{
-	    UINT32   Cwmin0:4;       // for AC_BE
-	    UINT32   Cwmin1:4;       // for AC_BK
-	    UINT32   Cwmin2:4;       // for AC_VI
-	    UINT32   Cwmin3:4;       // for AC_VO
-	    UINT32   Rsv:16;
-	}	field;
-	UINT32			word;
-}	CWMIN_CSR_STRUC, *PCWMIN_CSR_STRUC;
-#endif
-
-//
-// CWMAX_CSR: CWmin for each EDCA AC
-//
-#define WMM_CWMAX_CFG   0x021c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_CWMAX_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:16;
-	    UINT32   Cwmax3:4;       // for AC_VO
-	    UINT32   Cwmax2:4;       // for AC_VI
-	    UINT32   Cwmax1:4;       // for AC_BK
-	    UINT32   Cwmax0:4;       // for AC_BE
-	}	field;
-	UINT32			word;
-}	CWMAX_CSR_STRUC, *PCWMAX_CSR_STRUC;
-#else
-typedef	union	_CWMAX_CSR_STRUC	{
-	struct	{
-	    UINT32   Cwmax0:4;       // for AC_BE
-	    UINT32   Cwmax1:4;       // for AC_BK
-	    UINT32   Cwmax2:4;       // for AC_VI
-	    UINT32   Cwmax3:4;       // for AC_VO
-	    UINT32   Rsv:16;
-	}	field;
-	UINT32			word;
-}	CWMAX_CSR_STRUC, *PCWMAX_CSR_STRUC;
-#endif
-
-
-//
-// AC_TXOP_CSR0: AC_BK/AC_BE TXOP register
-//
-#define WMM_TXOP0_CFG    0x0220
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AC_TXOP_CSR0_STRUC	{
-	struct	{
-	    USHORT  Ac1Txop;        // for AC_BE, in unit of 32us
-	    USHORT  Ac0Txop;        // for AC_BK, in unit of 32us
-	}	field;
-	UINT32			word;
-}	AC_TXOP_CSR0_STRUC, *PAC_TXOP_CSR0_STRUC;
-#else
-typedef	union	_AC_TXOP_CSR0_STRUC	{
-	struct	{
-	    USHORT  Ac0Txop;        // for AC_BK, in unit of 32us
-	    USHORT  Ac1Txop;        // for AC_BE, in unit of 32us
-	}	field;
-	UINT32			word;
-}	AC_TXOP_CSR0_STRUC, *PAC_TXOP_CSR0_STRUC;
-#endif
-
-//
-// AC_TXOP_CSR1: AC_VO/AC_VI TXOP register
-//
-#define WMM_TXOP1_CFG    0x0224
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AC_TXOP_CSR1_STRUC	{
-	struct	{
-	    USHORT  Ac3Txop;        // for AC_VO, in unit of 32us
-	    USHORT  Ac2Txop;        // for AC_VI, in unit of 32us
-	}	field;
-	UINT32			word;
-}	AC_TXOP_CSR1_STRUC, *PAC_TXOP_CSR1_STRUC;
-#else
-typedef	union	_AC_TXOP_CSR1_STRUC	{
-	struct	{
-	    USHORT  Ac2Txop;        // for AC_VI, in unit of 32us
-	    USHORT  Ac3Txop;        // for AC_VO, in unit of 32us
-	}	field;
-	UINT32			word;
-}	AC_TXOP_CSR1_STRUC, *PAC_TXOP_CSR1_STRUC;
-#endif
-#define RINGREG_DIFF			0x10
-#define GPIO_CTRL_CFG    0x0228	//MAC_CSR13
-#define MCU_CMD_CFG    0x022c
-#define TX_BASE_PTR0     0x0230	//AC_BK base address
-#define TX_MAX_CNT0      0x0234
-#define TX_CTX_IDX0       0x0238
-#define TX_DTX_IDX0      0x023c
-#define TX_BASE_PTR1     0x0240 	//AC_BE base address
-#define TX_MAX_CNT1      0x0244
-#define TX_CTX_IDX1       0x0248
-#define TX_DTX_IDX1      0x024c
-#define TX_BASE_PTR2     0x0250 	//AC_VI base address
-#define TX_MAX_CNT2      0x0254
-#define TX_CTX_IDX2       0x0258
-#define TX_DTX_IDX2      0x025c
-#define TX_BASE_PTR3     0x0260 	//AC_VO base address
-#define TX_MAX_CNT3      0x0264
-#define TX_CTX_IDX3       0x0268
-#define TX_DTX_IDX3      0x026c
-#define TX_BASE_PTR4     0x0270 	//HCCA base address
-#define TX_MAX_CNT4      0x0274
-#define TX_CTX_IDX4       0x0278
-#define TX_DTX_IDX4      0x027c
-#define TX_BASE_PTR5     0x0280 	//MGMT base address
-#define  TX_MAX_CNT5     0x0284
-#define TX_CTX_IDX5       0x0288
-#define TX_DTX_IDX5      0x028c
-#define TX_MGMTMAX_CNT      TX_MAX_CNT5
-#define TX_MGMTCTX_IDX       TX_CTX_IDX5
-#define TX_MGMTDTX_IDX      TX_DTX_IDX5
-#define RX_BASE_PTR     0x0290 	//RX base address
-#define RX_MAX_CNT      0x0294
-#define RX_CRX_IDX       0x0298
-#define RX_DRX_IDX      0x029c
-#define USB_DMA_CFG      0x02a0
-#ifdef RT_BIG_ENDIAN
-typedef	union	_USB_DMA_CFG_STRUC	{
-	struct	{
-	    UINT32  TxBusy:1;   	//USB DMA TX FSM busy . debug only
-	    UINT32  RxBusy:1;        //USB DMA RX FSM busy . debug only
-	    UINT32  EpoutValid:6;        //OUT endpoint data valid. debug only
-	    UINT32  TxBulkEn:1;        //Enable USB DMA Tx
-	    UINT32  RxBulkEn:1;        //Enable USB DMA Rx
-	    UINT32  RxBulkAggEn:1;        //Enable Rx Bulk Aggregation
-	    UINT32  TxopHalt:1;        //Halt TXOP count down when TX buffer is full.
-	    UINT32  TxClear:1;        //Clear USB DMA TX path
-	    UINT32  rsv:2;
-	    UINT32  phyclear:1;        		//phy watch dog enable. write 1
-	    UINT32  RxBulkAggLmt:8;        //Rx Bulk Aggregation Limit  in unit of 1024 bytes
-	    UINT32  RxBulkAggTOut:8;        //Rx Bulk Aggregation TimeOut  in unit of 33ns
-	}	field;
-	UINT32			word;
-}	USB_DMA_CFG_STRUC, *PUSB_DMA_CFG_STRUC;
-#else
-typedef	union	_USB_DMA_CFG_STRUC	{
-	struct	{
-	    UINT32  RxBulkAggTOut:8;        //Rx Bulk Aggregation TimeOut  in unit of 33ns
-	    UINT32  RxBulkAggLmt:8;        //Rx Bulk Aggregation Limit  in unit of 256 bytes
-	    UINT32  phyclear:1;        		//phy watch dog enable. write 1
-	    UINT32  rsv:2;
-	    UINT32  TxClear:1;        //Clear USB DMA TX path
-	    UINT32  TxopHalt:1;        //Halt TXOP count down when TX buffer is full.
-	    UINT32  RxBulkAggEn:1;        //Enable Rx Bulk Aggregation
-	    UINT32  RxBulkEn:1;        //Enable USB DMA Rx
-	    UINT32  TxBulkEn:1;        //Enable USB DMA Tx
-	    UINT32  EpoutValid:6;        //OUT endpoint data valid
-	    UINT32  RxBusy:1;        //USB DMA RX FSM busy
-	    UINT32  TxBusy:1;   	//USB DMA TX FSM busy
-	}	field;
-	UINT32			word;
-}	USB_DMA_CFG_STRUC, *PUSB_DMA_CFG_STRUC;
-#endif
-
-//
-//  3  PBF  registers
-//
-//
-// Most are for debug. Driver doesn't touch PBF register.
-#define 	PBF_SYS_CTRL 	 0x0400
-#define     PBF_CFG                 0x0408
-#define 	PBF_MAX_PCNT 	 0x040C
-#define 	PBF_CTRL	 	0x0410
-#define 	PBF_INT_STA	 0x0414
-#define 	PBF_INT_ENA	 0x0418
-#define 	TXRXQ_PCNT  	 0x0438
-#define 	PBF_DBG 	 	 0x043c
-#define     PBF_CAP_CTRL     0x0440
-
-
-// eFuse registers
-#define EFUSE_CTRL              0x0580
-#define EFUSE_DATA0             0x0590
-#define EFUSE_DATA1             0x0594
-#define EFUSE_DATA2             0x0598
-#define EFUSE_DATA3             0x059c
-#define EFUSE_USAGE_MAP_START   0x2d0
-#define EFUSE_USAGE_MAP_END     0x2fc
-#define EFUSE_TAG               0x2fe
-#define EFUSE_USAGE_MAP_SIZE    45
-
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EFUSE_CTRL_STRUC {
-	struct	{
-		UINT32            SEL_EFUSE:1;
-		UINT32            EFSROM_KICK:1;
-		UINT32            RESERVED:4;
-		UINT32            EFSROM_AIN:10;
-		UINT32            EFSROM_LDO_ON_TIME:2;
-		UINT32            EFSROM_LDO_OFF_TIME:6;
-		UINT32            EFSROM_MODE:2;
-		UINT32            EFSROM_AOUT:6;
-	}	field;
-	UINT32			word;
-}	EFUSE_CTRL_STRUC, *PEFUSE_CTRL_STRUC;
-#else
-typedef	union	_EFUSE_CTRL_STRUC {
-	struct	{
-		UINT32            EFSROM_AOUT:6;
-		UINT32            EFSROM_MODE:2;
-		UINT32            EFSROM_LDO_OFF_TIME:6;
-		UINT32            EFSROM_LDO_ON_TIME:2;
-		UINT32            EFSROM_AIN:10;
-		UINT32            RESERVED:4;
-		UINT32            EFSROM_KICK:1;
-		UINT32            SEL_EFUSE:1;
-	}	field;
-	UINT32			word;
-}	EFUSE_CTRL_STRUC, *PEFUSE_CTRL_STRUC;
-#endif // RT_BIG_ENDIAN //
-
-#define LDO_CFG0 				0x05d4
-#define GPIO_SWITCH				0x05dc
-
-//
-//  4  MAC  registers
-//
-//
-//  4.1 MAC SYSTEM  configuration registers (offset:0x1000)
-//
-#define MAC_CSR0            0x1000
-#ifdef RT_BIG_ENDIAN
-typedef	union	_ASIC_VER_ID_STRUC	{
-	struct	{
-	    USHORT  ASICVer;        // version : 2860
-	    USHORT  ASICRev;        // reversion  : 0
-	}	field;
-	UINT32			word;
-}	ASIC_VER_ID_STRUC, *PASIC_VER_ID_STRUC;
-#else
-typedef	union	_ASIC_VER_ID_STRUC	{
-	struct	{
-	    USHORT  ASICRev;        // reversion  : 0
-	    USHORT  ASICVer;        // version : 2860
-	}	field;
-	UINT32			word;
-}	ASIC_VER_ID_STRUC, *PASIC_VER_ID_STRUC;
-#endif
-#define MAC_SYS_CTRL            0x1004		//MAC_CSR1
-#define MAC_ADDR_DW0            		0x1008		// MAC ADDR DW0
-#define MAC_ADDR_DW1           		 0x100c		// MAC ADDR DW1
-//
-// MAC_CSR2: STA MAC register 0
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MAC_DW0_STRUC	{
-	struct	{
-		UCHAR		Byte3;		// MAC address byte 3
-		UCHAR		Byte2;		// MAC address byte 2
-		UCHAR		Byte1;		// MAC address byte 1
-		UCHAR		Byte0;		// MAC address byte 0
-	}	field;
-	UINT32			word;
-}	MAC_DW0_STRUC, *PMAC_DW0_STRUC;
-#else
-typedef	union	_MAC_DW0_STRUC	{
-	struct	{
-		UCHAR		Byte0;		// MAC address byte 0
-		UCHAR		Byte1;		// MAC address byte 1
-		UCHAR		Byte2;		// MAC address byte 2
-		UCHAR		Byte3;		// MAC address byte 3
-	}	field;
-	UINT32			word;
-}	MAC_DW0_STRUC, *PMAC_DW0_STRUC;
-#endif
-
-//
-// MAC_CSR3: STA MAC register 1
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MAC_DW1_STRUC	{
-	struct	{
-		UCHAR		Rsvd1;
-		UCHAR		U2MeMask;
-		UCHAR		Byte5;		// MAC address byte 5
-		UCHAR		Byte4;		// MAC address byte 4
-	}	field;
-	UINT32			word;
-}	MAC_DW1_STRUC, *PMAC_DW1_STRUC;
-#else
-typedef	union	_MAC_DW1_STRUC	{
-	struct	{
-		UCHAR		Byte4;		// MAC address byte 4
-		UCHAR		Byte5;		// MAC address byte 5
-		UCHAR		U2MeMask;
-		UCHAR		Rsvd1;
-	}	field;
-	UINT32			word;
-}	MAC_DW1_STRUC, *PMAC_DW1_STRUC;
-#endif
-
-#define MAC_BSSID_DW0            		0x1010		// MAC BSSID DW0
-#define MAC_BSSID_DW1            		0x1014		// MAC BSSID DW1
-
-//
-// MAC_CSR5: BSSID register 1
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MAC_CSR5_STRUC	{
-	struct	{
-		USHORT		Rsvd:11;
-		USHORT		MBssBcnNum:3;
-		USHORT		BssIdMode:2; // 0: one BSSID, 10: 4 BSSID,  01: 2 BSSID , 11: 8BSSID
-		UCHAR		Byte5;		 // BSSID byte 5
-		UCHAR		Byte4;		 // BSSID byte 4
-	}	field;
-	UINT32			word;
-}	MAC_CSR5_STRUC, *PMAC_CSR5_STRUC;
-#else
-typedef	union	_MAC_CSR5_STRUC	{
-	struct	{
-		UCHAR		Byte4;		 // BSSID byte 4
-		UCHAR		Byte5;		 // BSSID byte 5
-		USHORT      	BssIdMask:2; // 0: one BSSID, 10: 4 BSSID,  01: 2 BSSID , 11: 8BSSID
-		USHORT		MBssBcnNum:3;
-		USHORT		Rsvd:11;
-	}	field;
-	UINT32			word;
-}	MAC_CSR5_STRUC, *PMAC_CSR5_STRUC;
-#endif
-
-#define MAX_LEN_CFG              0x1018		// rt2860b max 16k bytes. bit12:13 Maximum PSDU length (power factor) 0:2^13, 1:2^14, 2:2^15, 3:2^16
-#define BBP_CSR_CFG            		0x101c		//
-//
-// BBP_CSR_CFG: BBP serial control register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_BBP_CSR_CFG_STRUC	{
-	struct	{
-		UINT32		:12;
-		UINT32		BBP_RW_MODE:1;		// 0: use serial mode  1:parallel
-		UINT32		BBP_PAR_DUR:1;		    // 0: 4 MAC clock cycles  1: 8 MAC clock cycles
-		UINT32		Busy:1;				// 1: ASIC is busy execute BBP programming.
-		UINT32		fRead:1;		    // 0: Write	BBP, 1:	Read BBP
-		UINT32		RegNum:8;			// Selected	BBP	register
-		UINT32		Value:8;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	BBP_CSR_CFG_STRUC, *PBBP_CSR_CFG_STRUC;
-#else
-typedef	union	_BBP_CSR_CFG_STRUC	{
-	struct	{
-		UINT32		Value:8;			// Register	value to program into BBP
-		UINT32		RegNum:8;			// Selected	BBP	register
-		UINT32		fRead:1;		    // 0: Write	BBP, 1:	Read BBP
-		UINT32		Busy:1;				// 1: ASIC is busy execute BBP programming.
-		UINT32		BBP_PAR_DUR:1;		     // 0: 4 MAC clock cycles  1: 8 MAC clock cycles
-		UINT32		BBP_RW_MODE:1;		// 0: use serial mode  1:parallel
-		UINT32		:12;
-	}	field;
-	UINT32			word;
-}	BBP_CSR_CFG_STRUC, *PBBP_CSR_CFG_STRUC;
-#endif
-#define RF_CSR_CFG0            		0x1020
-//
-// RF_CSR_CFG: RF control register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG0_STRUC	{
-	struct	{
-		UINT32		Busy:1;		    // 0: idle 1: 8busy
-		UINT32		Sel:1;				// 0:RF_LE0 activate  1:RF_LE1 activate
-		UINT32		StandbyMode:1;		    // 0: high when stand by 1:	low when standby
-		UINT32		bitwidth:5;			// Selected	BBP	register
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG0_STRUC, *PRF_CSR_CFG0_STRUC;
-#else
-typedef	union	_RF_CSR_CFG0_STRUC	{
-	struct	{
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-		UINT32		bitwidth:5;			// Selected	BBP	register
-		UINT32		StandbyMode:1;		    // 0: high when stand by 1:	low when standby
-		UINT32		Sel:1;				// 0:RF_LE0 activate  1:RF_LE1 activate
-		UINT32		Busy:1;		    // 0: idle 1: 8busy
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG0_STRUC, *PRF_CSR_CFG0_STRUC;
-#endif
-#define RF_CSR_CFG1           		0x1024
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG1_STRUC	{
-	struct	{
-		UINT32		rsv:7;		    // 0: idle 1: 8busy
-		UINT32		RFGap:5;			// Gap between BB_CONTROL_RF and RF_LE. 0: 3 system clock cycle (37.5usec) 1: 5 system clock cycle (62.5usec)
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG1_STRUC, *PRF_CSR_CFG1_STRUC;
-#else
-typedef	union	_RF_CSR_CFG1_STRUC	{
-	struct	{
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-		UINT32		RFGap:5;			// Gap between BB_CONTROL_RF and RF_LE. 0: 3 system clock cycle (37.5usec) 1: 5 system clock cycle (62.5usec)
-		UINT32		rsv:7;		    // 0: idle 1: 8busy
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG1_STRUC, *PRF_CSR_CFG1_STRUC;
-#endif
-#define RF_CSR_CFG2           		0x1028		//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG2_STRUC	{
-	struct	{
-		UINT32		rsv:8;		    // 0: idle 1: 8busy
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG2_STRUC, *PRF_CSR_CFG2_STRUC;
-#else
-typedef	union	_RF_CSR_CFG2_STRUC	{
-	struct	{
-		UINT32		RegIdAndContent:24;			// Register	value to program into BBP
-		UINT32		rsv:8;		    // 0: idle 1: 8busy
-	}	field;
-	UINT32			word;
-}	RF_CSR_CFG2_STRUC, *PRF_CSR_CFG2_STRUC;
-#endif
-#define LED_CFG           		0x102c		//  MAC_CSR14
-#ifdef RT_BIG_ENDIAN
-typedef	union	_LED_CFG_STRUC	{
-	struct	{
-		UINT32		:1;
-		UINT32		LedPolar:1;			// Led Polarity.  0: active low1: active high
-		UINT32		YLedMode:2;			// yellow Led Mode
-		UINT32		GLedMode:2;			// green Led Mode
-		UINT32		RLedMode:2;			// red Led Mode    0: off1: blinking upon TX2: periodic slow blinking3: always on
-		UINT32		rsv:2;
-		UINT32		SlowBlinkPeriod:6;			// slow blinking period. unit:1ms
-		UINT32		OffPeriod:8;			// blinking off period unit 1ms
-		UINT32		OnPeriod:8;			// blinking on period unit 1ms
-	}	field;
-	UINT32			word;
-}	LED_CFG_STRUC, *PLED_CFG_STRUC;
-#else
-typedef	union	_LED_CFG_STRUC	{
-	struct	{
-		UINT32		OnPeriod:8;			// blinking on period unit 1ms
-		UINT32		OffPeriod:8;			// blinking off period unit 1ms
-		UINT32		SlowBlinkPeriod:6;			// slow blinking period. unit:1ms
-		UINT32		rsv:2;
-		UINT32		RLedMode:2;			// red Led Mode    0: off1: blinking upon TX2: periodic slow blinking3: always on
-		UINT32		GLedMode:2;			// green Led Mode
-		UINT32		YLedMode:2;			// yellow Led Mode
-		UINT32		LedPolar:1;			// Led Polarity.  0: active low1: active high
-		UINT32		:1;
-	}	field;
-	UINT32			word;
-}	LED_CFG_STRUC, *PLED_CFG_STRUC;
-#endif
-//
-//  4.2 MAC TIMING  configuration registers (offset:0x1100)
-//
-#define XIFS_TIME_CFG             0x1100		 // MAC_CSR8  MAC_CSR9
-#ifdef RT_BIG_ENDIAN
-typedef	union	_IFS_SLOT_CFG_STRUC	{
-	struct	{
-	    UINT32  rsv:2;
-	    UINT32  BBRxendEnable:1;        //  reference RXEND signal to begin XIFS defer
-	    UINT32  EIFS:9;        //  unit 1us
-	    UINT32  OfdmXifsTime:4;        //OFDM SIFS. unit 1us. Applied after OFDM RX when MAC doesn't reference BBP signal BBRXEND
-	    UINT32  OfdmSifsTime:8;        //  unit 1us. Applied after OFDM RX/TX
-	    UINT32  CckmSifsTime:8;        //  unit 1us. Applied after CCK RX/TX
-	}	field;
-	UINT32			word;
-}	IFS_SLOT_CFG_STRUC, *PIFS_SLOT_CFG_STRUC;
-#else
-typedef	union	_IFS_SLOT_CFG_STRUC	{
-	struct	{
-	    UINT32  CckmSifsTime:8;        //  unit 1us. Applied after CCK RX/TX
-	    UINT32  OfdmSifsTime:8;        //  unit 1us. Applied after OFDM RX/TX
-	    UINT32  OfdmXifsTime:4;        //OFDM SIFS. unit 1us. Applied after OFDM RX when MAC doesn't reference BBP signal BBRXEND
-	    UINT32  EIFS:9;        //  unit 1us
-	    UINT32  BBRxendEnable:1;        //  reference RXEND signal to begin XIFS defer
-	    UINT32  rsv:2;
-	}	field;
-	UINT32			word;
-}	IFS_SLOT_CFG_STRUC, *PIFS_SLOT_CFG_STRUC;
-#endif
-
-#define BKOFF_SLOT_CFG             0x1104		 //  mac_csr9 last 8 bits
-#define NAV_TIME_CFG             0x1108		 // NAV  (MAC_CSR15)
-#define CH_TIME_CFG             0x110C		 	// Count as channel busy
-#define PBF_LIFE_TIMER             0x1110		 //TX/RX MPDU timestamp timer (free run)Unit: 1us
-#define BCN_TIME_CFG             0x1114		 // TXRX_CSR9
-
-#define BCN_OFFSET0				0x042C
-#define BCN_OFFSET1				0x0430
-
-//
-// BCN_TIME_CFG : Synchronization control register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_BCN_TIME_CFG_STRUC	{
-	struct	{
-		UINT32		TxTimestampCompensate:8;
-        UINT32       :3;
-		UINT32		bBeaconGen:1;		// Enable beacon generator
-        UINT32       bTBTTEnable:1;
-		UINT32		TsfSyncMode:2;		// Enable TSF sync, 00: disable, 01: infra mode, 10: ad-hoc mode
-		UINT32		bTsfTicking:1;		// Enable TSF auto counting
-		UINT32       BeaconInterval:16;  // in unit of 1/16 TU
-	}	field;
-	UINT32			word;
-}	BCN_TIME_CFG_STRUC, *PBCN_TIME_CFG_STRUC;
-#else
-typedef	union	_BCN_TIME_CFG_STRUC	{
-	struct	{
-		UINT32       BeaconInterval:16;  // in unit of 1/16 TU
-		UINT32		bTsfTicking:1;		// Enable TSF auto counting
-		UINT32		TsfSyncMode:2;		// Enable TSF sync, 00: disable, 01: infra mode, 10: ad-hoc mode
-        UINT32       bTBTTEnable:1;
-		UINT32		bBeaconGen:1;		// Enable beacon generator
-        UINT32       :3;
-		UINT32		TxTimestampCompensate:8;
-	}	field;
-	UINT32			word;
-}	BCN_TIME_CFG_STRUC, *PBCN_TIME_CFG_STRUC;
-#endif
-#define TBTT_SYNC_CFG            0x1118  		// txrx_csr10
-#define TSF_TIMER_DW0             0x111C  		// Local TSF timer lsb 32 bits. Read-only
-#define TSF_TIMER_DW1             0x1120  		// msb 32 bits. Read-only.
-#define TBTT_TIMER             	0x1124  		// TImer remains till next TBTT. Read-only.  TXRX_CSR14
-#define INT_TIMER_CFG              	0x1128  		//
-#define INT_TIMER_EN             	0x112c  		//  GP-timer and pre-tbtt Int enable
-#define CH_IDLE_STA              	0x1130  		//  channel idle time
-#define CH_BUSY_STA              	0x1134  		//  channle busy time
-//
-//  4.2 MAC POWER  configuration registers (offset:0x1200)
-//
-#define MAC_STATUS_CFG             0x1200		 // old MAC_CSR12
-#define PWR_PIN_CFG             0x1204		 // old MAC_CSR12
-#define AUTO_WAKEUP_CFG             0x1208		 // old MAC_CSR10
-//
-// AUTO_WAKEUP_CFG: Manual power control / status register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_AUTO_WAKEUP_STRUC	{
-	struct	{
-		UINT32		:16;
-		UINT32		EnableAutoWakeup:1;	// 0:sleep, 1:awake
-		UINT32       NumofSleepingTbtt:7;          // ForceWake has high privilege than PutToSleep when both set
-		UINT32       AutoLeadTime:8;
-	}	field;
-	UINT32			word;
-}	AUTO_WAKEUP_STRUC, *PAUTO_WAKEUP_STRUC;
-#else
-typedef	union	_AUTO_WAKEUP_STRUC	{
-	struct	{
-		UINT32       AutoLeadTime:8;
-		UINT32       NumofSleepingTbtt:7;          // ForceWake has high privilege than PutToSleep when both set
-		UINT32		EnableAutoWakeup:1;	// 0:sleep, 1:awake
-		UINT32		:16;
-	}	field;
-	UINT32			word;
-}	AUTO_WAKEUP_STRUC, *PAUTO_WAKEUP_STRUC;
-#endif
-//
-//  4.3 MAC TX  configuration registers (offset:0x1300)
-//
-
-#define EDCA_AC0_CFG	0x1300		//AC_TXOP_CSR0 0x3474
-#define EDCA_AC1_CFG	0x1304
-#define EDCA_AC2_CFG	0x1308
-#define EDCA_AC3_CFG	0x130c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EDCA_AC_CFG_STRUC	{
-	struct	{
-	    UINT32  :12;        //
-	    UINT32  Cwmax:4;        //unit power of 2
-	    UINT32  Cwmin:4;        //
-	    UINT32  Aifsn:4;        // # of slot time
-	    UINT32  AcTxop:8;        //  in unit of 32us
-	}	field;
-	UINT32			word;
-}	EDCA_AC_CFG_STRUC, *PEDCA_AC_CFG_STRUC;
-#else
-typedef	union	_EDCA_AC_CFG_STRUC	{
-	struct	{
-	    UINT32  AcTxop:8;        //  in unit of 32us
-	    UINT32  Aifsn:4;        // # of slot time
-	    UINT32  Cwmin:4;        //
-	    UINT32  Cwmax:4;        //unit power of 2
-	    UINT32  :12;       //
-	}	field;
-	UINT32			word;
-}	EDCA_AC_CFG_STRUC, *PEDCA_AC_CFG_STRUC;
-#endif
-
-#define EDCA_TID_AC_MAP	0x1310
-#define TX_PWR_CFG_0	0x1314
-#define TX_PWR_CFG_1	0x1318
-#define TX_PWR_CFG_2	0x131C
-#define TX_PWR_CFG_3	0x1320
-#define TX_PWR_CFG_4	0x1324
-#define TX_PIN_CFG		0x1328
-#define TX_BAND_CFG	0x132c		// 0x1 use upper 20MHz. 0 juse lower 20MHz
-#define TX_SW_CFG0		0x1330
-#define TX_SW_CFG1		0x1334
-#define TX_SW_CFG2		0x1338
-#define TXOP_THRES_CFG		0x133c
-#define TXOP_CTRL_CFG		0x1340
-#define TX_RTS_CFG		0x1344
-
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_RTS_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv:7;
-	    UINT32       RtsFbkEn:1;    // enable rts rate fallback
-	    UINT32       RtsThres:16;    // unit:byte
-	    UINT32       AutoRtsRetryLimit:8;
-	}	field;
-	UINT32			word;
-}	TX_RTS_CFG_STRUC, *PTX_RTS_CFG_STRUC;
-#else
-typedef	union	_TX_RTS_CFG_STRUC	{
-	struct	{
-	    UINT32       AutoRtsRetryLimit:8;
-	    UINT32       RtsThres:16;    // unit:byte
-	    UINT32       RtsFbkEn:1;    // enable rts rate fallback
-	    UINT32       rsv:7;     // 1: HT non-STBC control frame enable
-	}	field;
-	UINT32			word;
-}	TX_RTS_CFG_STRUC, *PTX_RTS_CFG_STRUC;
-#endif
-#define TX_TIMEOUT_CFG	0x1348
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_TIMEOUT_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv2:8;
-	    UINT32       TxopTimeout:8;	//TXOP timeout value for TXOP truncation.  It is recommended that (SLOT_TIME) > (TX_OP_TIMEOUT) > (RX_ACK_TIMEOUT)
-	    UINT32       RxAckTimeout:8;	// unit:slot. Used for TX precedure
-	    UINT32       MpduLifeTime:4;    //  expiration time = 2^(9+MPDU LIFE TIME)  us
-	    UINT32       rsv:4;
-	}	field;
-	UINT32			word;
-}	TX_TIMEOUT_CFG_STRUC, *PTX_TIMEOUT_CFG_STRUC;
-#else
-typedef	union	_TX_TIMEOUT_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv:4;
-	    UINT32       MpduLifeTime:4;    //  expiration time = 2^(9+MPDU LIFE TIME)  us
-	    UINT32       RxAckTimeout:8;	// unit:slot. Used for TX precedure
-	    UINT32       TxopTimeout:8;	//TXOP timeout value for TXOP truncation.  It is recommended that (SLOT_TIME) > (TX_OP_TIMEOUT) > (RX_ACK_TIMEOUT)
-	    UINT32       rsv2:8;     // 1: HT non-STBC control frame enable
-	}	field;
-	UINT32			word;
-}	TX_TIMEOUT_CFG_STRUC, *PTX_TIMEOUT_CFG_STRUC;
-#endif
-#define TX_RTY_CFG	0x134c
-#ifdef RT_BIG_ENDIAN
-typedef	union PACKED _TX_RTY_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv:1;
-	    UINT32       TxautoFBEnable:1;    // Tx retry PHY rate auto fallback enable
-	    UINT32       AggRtyMode:1;	// Aggregate MPDU retry mode.  0:expired by retry limit, 1: expired by mpdu life timer
-	    UINT32       NonAggRtyMode:1;	// Non-Aggregate MPDU retry mode.  0:expired by retry limit, 1: expired by mpdu life timer
-	    UINT32       LongRtyThre:12;	// Long retry threshoold
-	    UINT32       LongRtyLimit:8;	//long retry limit
-	    UINT32       ShortRtyLimit:8;	//  short retry limit
-
-	}	field;
-	UINT32			word;
-}	TX_RTY_CFG_STRUC, *PTX_RTY_CFG_STRUC;
-#else
-typedef	union PACKED _TX_RTY_CFG_STRUC	{
-	struct	{
-	    UINT32       ShortRtyLimit:8;	//  short retry limit
-	    UINT32       LongRtyLimit:8;	//long retry limit
-	    UINT32       LongRtyThre:12;	// Long retry threshoold
-	    UINT32       NonAggRtyMode:1;	// Non-Aggregate MPDU retry mode.  0:expired by retry limit, 1: expired by mpdu life timer
-	    UINT32       AggRtyMode:1;	// Aggregate MPDU retry mode.  0:expired by retry limit, 1: expired by mpdu life timer
-	    UINT32       TxautoFBEnable:1;    // Tx retry PHY rate auto fallback enable
-	    UINT32       rsv:1;     // 1: HT non-STBC control frame enable
-	}	field;
-	UINT32			word;
-}	TX_RTY_CFG_STRUC, *PTX_RTY_CFG_STRUC;
-#endif
-#define TX_LINK_CFG	0x1350
-#ifdef RT_BIG_ENDIAN
-typedef	union	PACKED _TX_LINK_CFG_STRUC	{
-	struct PACKED {
-	    UINT32       RemotMFS:8;	//remote MCS feedback sequence number
-	    UINT32       RemotMFB:8;    //  remote MCS feedback
-	    UINT32       rsv:3;	//
-	    UINT32       TxCFAckEn:1;	//   Piggyback CF-ACK enable
-	    UINT32       TxRDGEn:1;	// RDG TX enable
-	    UINT32       TxMRQEn:1;	//  MCS request TX enable
-	    UINT32       RemoteUMFSEnable:1;	//  remote unsolicit  MFB enable.  0: not apply remote remote unsolicit (MFS=7)
-	    UINT32       MFBEnable:1;	//  TX apply remote MFB 1:enable
-	    UINT32       RemoteMFBLifeTime:8;	//remote MFB life time. unit : 32us
-	}	field;
-	UINT32			word;
-}	TX_LINK_CFG_STRUC, *PTX_LINK_CFG_STRUC;
-#else
-typedef	union	PACKED _TX_LINK_CFG_STRUC	{
-	struct PACKED {
-	    UINT32       RemoteMFBLifeTime:8;	//remote MFB life time. unit : 32us
-	    UINT32       MFBEnable:1;	//  TX apply remote MFB 1:enable
-	    UINT32       RemoteUMFSEnable:1;	//  remote unsolicit  MFB enable.  0: not apply remote remote unsolicit (MFS=7)
-	    UINT32       TxMRQEn:1;	//  MCS request TX enable
-	    UINT32       TxRDGEn:1;	// RDG TX enable
-	    UINT32       TxCFAckEn:1;	//   Piggyback CF-ACK enable
-	    UINT32       rsv:3;	//
-	    UINT32       RemotMFB:8;    //  remote MCS feedback
-	    UINT32       RemotMFS:8;	//remote MCS feedback sequence number
-	}	field;
-	UINT32			word;
-}	TX_LINK_CFG_STRUC, *PTX_LINK_CFG_STRUC;
-#endif
-#define HT_FBK_CFG0	0x1354
-#ifdef RT_BIG_ENDIAN
-typedef	union PACKED _HT_FBK_CFG0_STRUC	{
-	struct	{
-	    UINT32       HTMCS7FBK:4;
-	    UINT32       HTMCS6FBK:4;
-	    UINT32       HTMCS5FBK:4;
-	    UINT32       HTMCS4FBK:4;
-	    UINT32       HTMCS3FBK:4;
-	    UINT32       HTMCS2FBK:4;
-	    UINT32       HTMCS1FBK:4;
-	    UINT32       HTMCS0FBK:4;
-	}	field;
-	UINT32			word;
-}	HT_FBK_CFG0_STRUC, *PHT_FBK_CFG0_STRUC;
-#else
-typedef	union PACKED _HT_FBK_CFG0_STRUC	{
-	struct	{
-	    UINT32       HTMCS0FBK:4;
-	    UINT32       HTMCS1FBK:4;
-	    UINT32       HTMCS2FBK:4;
-	    UINT32       HTMCS3FBK:4;
-	    UINT32       HTMCS4FBK:4;
-	    UINT32       HTMCS5FBK:4;
-	    UINT32       HTMCS6FBK:4;
-	    UINT32       HTMCS7FBK:4;
-	}	field;
-	UINT32			word;
-}	HT_FBK_CFG0_STRUC, *PHT_FBK_CFG0_STRUC;
-#endif
-#define HT_FBK_CFG1	0x1358
-#ifdef RT_BIG_ENDIAN
-typedef	union	_HT_FBK_CFG1_STRUC	{
-	struct	{
-	    UINT32       HTMCS15FBK:4;
-	    UINT32       HTMCS14FBK:4;
-	    UINT32       HTMCS13FBK:4;
-	    UINT32       HTMCS12FBK:4;
-	    UINT32       HTMCS11FBK:4;
-	    UINT32       HTMCS10FBK:4;
-	    UINT32       HTMCS9FBK:4;
-	    UINT32       HTMCS8FBK:4;
-	}	field;
-	UINT32			word;
-}	HT_FBK_CFG1_STRUC, *PHT_FBK_CFG1_STRUC;
-#else
-typedef	union	_HT_FBK_CFG1_STRUC	{
-	struct	{
-	    UINT32       HTMCS8FBK:4;
-	    UINT32       HTMCS9FBK:4;
-	    UINT32       HTMCS10FBK:4;
-	    UINT32       HTMCS11FBK:4;
-	    UINT32       HTMCS12FBK:4;
-	    UINT32       HTMCS13FBK:4;
-	    UINT32       HTMCS14FBK:4;
-	    UINT32       HTMCS15FBK:4;
-	}	field;
-	UINT32			word;
-}	HT_FBK_CFG1_STRUC, *PHT_FBK_CFG1_STRUC;
-#endif
-#define LG_FBK_CFG0	0x135c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_LG_FBK_CFG0_STRUC	{
-	struct	{
-	    UINT32       OFDMMCS7FBK:4;	//initial value is 6
-	    UINT32       OFDMMCS6FBK:4;	//initial value is 5
-	    UINT32       OFDMMCS5FBK:4;	//initial value is 4
-	    UINT32       OFDMMCS4FBK:4;	//initial value is 3
-	    UINT32       OFDMMCS3FBK:4;	//initial value is 2
-	    UINT32       OFDMMCS2FBK:4;	//initial value is 1
-	    UINT32       OFDMMCS1FBK:4;	//initial value is 0
-	    UINT32       OFDMMCS0FBK:4;	//initial value is 0
-	}	field;
-	UINT32			word;
-}	LG_FBK_CFG0_STRUC, *PLG_FBK_CFG0_STRUC;
-#else
-typedef	union	_LG_FBK_CFG0_STRUC	{
-	struct	{
-	    UINT32       OFDMMCS0FBK:4;	//initial value is 0
-	    UINT32       OFDMMCS1FBK:4;	//initial value is 0
-	    UINT32       OFDMMCS2FBK:4;	//initial value is 1
-	    UINT32       OFDMMCS3FBK:4;	//initial value is 2
-	    UINT32       OFDMMCS4FBK:4;	//initial value is 3
-	    UINT32       OFDMMCS5FBK:4;	//initial value is 4
-	    UINT32       OFDMMCS6FBK:4;	//initial value is 5
-	    UINT32       OFDMMCS7FBK:4;	//initial value is 6
-	}	field;
-	UINT32			word;
-}	LG_FBK_CFG0_STRUC, *PLG_FBK_CFG0_STRUC;
-#endif
-#define LG_FBK_CFG1		0x1360
-#ifdef RT_BIG_ENDIAN
-typedef	union	_LG_FBK_CFG1_STRUC	{
-	struct	{
-	    UINT32       rsv:16;
-	    UINT32       CCKMCS3FBK:4;	//initial value is 2
-	    UINT32       CCKMCS2FBK:4;	//initial value is 1
-	    UINT32       CCKMCS1FBK:4;	//initial value is 0
-	    UINT32       CCKMCS0FBK:4;	//initial value is 0
-	}	field;
-	UINT32			word;
-}	LG_FBK_CFG1_STRUC, *PLG_FBK_CFG1_STRUC;
-#else
-typedef	union	_LG_FBK_CFG1_STRUC	{
-	struct	{
-	    UINT32       CCKMCS0FBK:4;	//initial value is 0
-	    UINT32       CCKMCS1FBK:4;	//initial value is 0
-	    UINT32       CCKMCS2FBK:4;	//initial value is 1
-	    UINT32       CCKMCS3FBK:4;	//initial value is 2
-	    UINT32       rsv:16;
-	}	field;
-	UINT32			word;
-}	LG_FBK_CFG1_STRUC, *PLG_FBK_CFG1_STRUC;
-#endif
-
-//=======================================================
-//================ Protection Paramater================================
-//=======================================================
-#define CCK_PROT_CFG	0x1364		//CCK Protection
-#define ASIC_SHORTNAV		1
-#define ASIC_LONGNAV		2
-#define ASIC_RTS		1
-#define ASIC_CTS		2
-#ifdef RT_BIG_ENDIAN
-typedef	union	_PROT_CFG_STRUC	{
-	struct	{
-	    UINT32       rsv:5;
-	    UINT32       RTSThEn:1;	//RTS threshold enable on CCK TX
-	    UINT32       TxopAllowGF40:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowGF20:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowMM40:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowMM20:1;	//CCK TXOP allowance. 0:disallow.
-	    UINT32       TxopAllowOfdm:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowCck:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       ProtectNav:2;	//TXOP protection type for CCK TX. 0:None, 1:ShortNAVprotect,  2:LongNAVProtect, 3:rsv
-	    UINT32       ProtectCtrl:2;	//Protection control frame type for CCK TX. 1:RTS/CTS, 2:CTS-to-self, 0:None, 3:rsv
-	    UINT32       ProtectRate:16;	//Protection control frame rate for CCK TX(RTS/CTS/CFEnd).
-	}	field;
-	UINT32			word;
-}	PROT_CFG_STRUC, *PPROT_CFG_STRUC;
-#else
-typedef	union	_PROT_CFG_STRUC	{
-	struct	{
-	    UINT32       ProtectRate:16;	//Protection control frame rate for CCK TX(RTS/CTS/CFEnd).
-	    UINT32       ProtectCtrl:2;	//Protection control frame type for CCK TX. 1:RTS/CTS, 2:CTS-to-self, 0:None, 3:rsv
-	    UINT32       ProtectNav:2;	//TXOP protection type for CCK TX. 0:None, 1:ShortNAVprotect,  2:LongNAVProtect, 3:rsv
-	    UINT32       TxopAllowCck:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowOfdm:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowMM20:1;	//CCK TXOP allowance. 0:disallow.
-	    UINT32       TxopAllowMM40:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowGF20:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       TxopAllowGF40:1;	//CCK TXOP allowance.0:disallow.
-	    UINT32       RTSThEn:1;	//RTS threshold enable on CCK TX
-	    UINT32       rsv:5;
-	}	field;
-	UINT32			word;
-}	PROT_CFG_STRUC, *PPROT_CFG_STRUC;
-#endif
-
-#define OFDM_PROT_CFG	0x1368		//OFDM Protection
-#define MM20_PROT_CFG	0x136C		//MM20 Protection
-#define MM40_PROT_CFG	0x1370		//MM40 Protection
-#define GF20_PROT_CFG	0x1374		//GF20 Protection
-#define GF40_PROT_CFG	0x1378		//GR40 Protection
-#define EXP_CTS_TIME	0x137C		//
-#define EXP_ACK_TIME	0x1380		//
-
-//
-//  4.4 MAC RX configuration registers (offset:0x1400)
-//
-#define RX_FILTR_CFG	0x1400			//TXRX_CSR0
-#define AUTO_RSP_CFG	0x1404			//TXRX_CSR4
-//
-// TXRX_CSR4: Auto-Responder/
-//
-#ifdef RT_BIG_ENDIAN
-typedef union _AUTO_RSP_CFG_STRUC {
- struct {
-     UINT32        :24;
-     UINT32       AckCtsPsmBit:1;   // Power bit value in conrtrol frame
-     UINT32       DualCTSEn:1;   // Power bit value in conrtrol frame
-     UINT32       rsv:1;   // Power bit value in conrtrol frame
-     UINT32       AutoResponderPreamble:1;    // 0:long, 1:short preamble
-     UINT32       CTS40MRef:1;  // Response CTS 40MHz duplicate mode
-     UINT32       CTS40MMode:1;  // Response CTS 40MHz duplicate mode
-     UINT32       BACAckPolicyEnable:1;    // 0:long, 1:short preamble
-     UINT32       AutoResponderEnable:1;
- } field;
- UINT32   word;
-} AUTO_RSP_CFG_STRUC, *PAUTO_RSP_CFG_STRUC;
-#else
-typedef union _AUTO_RSP_CFG_STRUC {
- struct {
-     UINT32       AutoResponderEnable:1;
-     UINT32       BACAckPolicyEnable:1;    // 0:long, 1:short preamble
-     UINT32       CTS40MMode:1;  // Response CTS 40MHz duplicate mode
-     UINT32       CTS40MRef:1;  // Response CTS 40MHz duplicate mode
-     UINT32       AutoResponderPreamble:1;    // 0:long, 1:short preamble
-     UINT32       rsv:1;   // Power bit value in conrtrol frame
-     UINT32       DualCTSEn:1;   // Power bit value in conrtrol frame
-     UINT32       AckCtsPsmBit:1;   // Power bit value in conrtrol frame
-     UINT32        :24;
- } field;
- UINT32   word;
-} AUTO_RSP_CFG_STRUC, *PAUTO_RSP_CFG_STRUC;
-#endif
-
-#define LEGACY_BASIC_RATE	0x1408	//  TXRX_CSR5           0x3054
-#define HT_BASIC_RATE		0x140c
-#define HT_CTRL_CFG		0x1410
-#define SIFS_COST_CFG		0x1414
-#define RX_PARSER_CFG		0x1418	//Set NAV for all received frames
-
-//
-//  4.5 MAC Security configuration (offset:0x1500)
-//
-#define TX_SEC_CNT0		0x1500		//
-#define RX_SEC_CNT0		0x1504		//
-#define CCMP_FC_MUTE		0x1508		//
-//
-//  4.6 HCCA/PSMP (offset:0x1600)
-//
-#define TXOP_HLDR_ADDR0		0x1600
-#define TXOP_HLDR_ADDR1		0x1604
-#define TXOP_HLDR_ET		0x1608
-#define QOS_CFPOLL_RA_DW0		0x160c
-#define QOS_CFPOLL_A1_DW1		0x1610
-#define QOS_CFPOLL_QC		0x1614
-//
-//  4.7 MAC Statistis registers (offset:0x1700)
-//
-#define RX_STA_CNT0		0x1700		//
-#define RX_STA_CNT1		0x1704		//
-#define RX_STA_CNT2		0x1708		//
-
-//
-// RX_STA_CNT0_STRUC: RX PLCP error count & RX CRC error count
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RX_STA_CNT0_STRUC	{
-	struct	{
-	    USHORT  PhyErr;
-	    USHORT  CrcErr;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT0_STRUC, *PRX_STA_CNT0_STRUC;
-#else
-typedef	union	_RX_STA_CNT0_STRUC	{
-	struct	{
-	    USHORT  CrcErr;
-	    USHORT  PhyErr;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT0_STRUC, *PRX_STA_CNT0_STRUC;
-#endif
-
-//
-// RX_STA_CNT1_STRUC: RX False CCA count & RX LONG frame count
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RX_STA_CNT1_STRUC	{
-	struct	{
-	    USHORT  PlcpErr;
-	    USHORT  FalseCca;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT1_STRUC, *PRX_STA_CNT1_STRUC;
-#else
-typedef	union	_RX_STA_CNT1_STRUC	{
-	struct	{
-	    USHORT  FalseCca;
-	    USHORT  PlcpErr;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT1_STRUC, *PRX_STA_CNT1_STRUC;
-#endif
-
-//
-// RX_STA_CNT2_STRUC:
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RX_STA_CNT2_STRUC	{
-	struct	{
-	    USHORT  RxFifoOverflowCount;
-	    USHORT  RxDupliCount;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT2_STRUC, *PRX_STA_CNT2_STRUC;
-#else
-typedef	union	_RX_STA_CNT2_STRUC	{
-	struct	{
-	    USHORT  RxDupliCount;
-	    USHORT  RxFifoOverflowCount;
-	}	field;
-	UINT32			word;
-}	RX_STA_CNT2_STRUC, *PRX_STA_CNT2_STRUC;
-#endif
-#define TX_STA_CNT0		0x170C		//
-//
-// STA_CSR3: TX Beacon count
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_STA_CNT0_STRUC	{
-	struct	{
-	    USHORT  TxBeaconCount;
-	    USHORT  TxFailCount;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT0_STRUC, *PTX_STA_CNT0_STRUC;
-#else
-typedef	union	_TX_STA_CNT0_STRUC	{
-	struct	{
-	    USHORT  TxFailCount;
-	    USHORT  TxBeaconCount;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT0_STRUC, *PTX_STA_CNT0_STRUC;
-#endif
-#define TX_STA_CNT1		0x1710		//
-//
-// TX_STA_CNT1: TX tx count
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_STA_CNT1_STRUC	{
-	struct	{
-	    USHORT  TxRetransmit;
-	    USHORT  TxSuccess;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT1_STRUC, *PTX_STA_CNT1_STRUC;
-#else
-typedef	union	_TX_STA_CNT1_STRUC	{
-	struct	{
-	    USHORT  TxSuccess;
-	    USHORT  TxRetransmit;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT1_STRUC, *PTX_STA_CNT1_STRUC;
-#endif
-#define TX_STA_CNT2		0x1714		//
-//
-// TX_STA_CNT2: TX tx count
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_STA_CNT2_STRUC	{
-	struct	{
-	    USHORT  TxUnderFlowCount;
-	    USHORT  TxZeroLenCount;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT2_STRUC, *PTX_STA_CNT2_STRUC;
-#else
-typedef	union	_TX_STA_CNT2_STRUC	{
-	struct	{
-	    USHORT  TxZeroLenCount;
-	    USHORT  TxUnderFlowCount;
-	}	field;
-	UINT32			word;
-}	TX_STA_CNT2_STRUC, *PTX_STA_CNT2_STRUC;
-#endif
-#define TX_STA_FIFO		0x1718		//
-//
-// TX_STA_FIFO_STRUC: TX Result for specific PID status fifo register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union PACKED _TX_STA_FIFO_STRUC	{
-	struct	{
-		UINT32		Reserve:2;
-		UINT32		TxBF:1; // 3*3
-		UINT32		SuccessRate:13;	//include MCS, mode ,shortGI, BW settingSame format as TXWI Word 0 Bit 31-16.
-//		UINT32		SuccessRate:16;	//include MCS, mode ,shortGI, BW settingSame format as TXWI Word 0 Bit 31-16.
-		UINT32		wcid:8;		//wireless client index
-		UINT32       	TxAckRequired:1;    // ack required
-		UINT32       	TxAggre:1;    // Tx is aggregated
-		UINT32       	TxSuccess:1;   // Tx success. whether success or not
-		UINT32       	PidType:4;
-		UINT32       	bValid:1;   // 1:This register contains a valid TX result
-	}	field;
-	UINT32			word;
-}	TX_STA_FIFO_STRUC, *PTX_STA_FIFO_STRUC;
-#else
-typedef	union PACKED _TX_STA_FIFO_STRUC	{
-	struct	{
-		UINT32       	bValid:1;   // 1:This register contains a valid TX result
-		UINT32       	PidType:4;
-		UINT32       	TxSuccess:1;   // Tx No retry success
-		UINT32       	TxAggre:1;    // Tx Retry Success
-		UINT32       	TxAckRequired:1;    // Tx fail
-		UINT32		wcid:8;		//wireless client index
-//		UINT32		SuccessRate:16;	//include MCS, mode ,shortGI, BW settingSame format as TXWI Word 0 Bit 31-16.
-		UINT32		SuccessRate:13;	//include MCS, mode ,shortGI, BW settingSame format as TXWI Word 0 Bit 31-16.
-		UINT32		TxBF:1;
-		UINT32		Reserve:2;
-	}	field;
-	UINT32			word;
-}	TX_STA_FIFO_STRUC, *PTX_STA_FIFO_STRUC;
-#endif
-// Debug counter
-#define TX_AGG_CNT	0x171c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT_STRUC	{
-	struct	{
-	    USHORT  AggTxCount;
-	    USHORT  NonAggTxCount;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT_STRUC, *PTX_AGG_CNT_STRUC;
-#else
-typedef	union	_TX_AGG_CNT_STRUC	{
-	struct	{
-	    USHORT  NonAggTxCount;
-	    USHORT  AggTxCount;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT_STRUC, *PTX_AGG_CNT_STRUC;
-#endif
-// Debug counter
-#define TX_AGG_CNT0	0x1720
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT0_STRUC	{
-	struct	{
-	    USHORT  AggSize2Count;
-	    USHORT  AggSize1Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT0_STRUC, *PTX_AGG_CNT0_STRUC;
-#else
-typedef	union	_TX_AGG_CNT0_STRUC	{
-	struct	{
-	    USHORT  AggSize1Count;
-	    USHORT  AggSize2Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT0_STRUC, *PTX_AGG_CNT0_STRUC;
-#endif
-// Debug counter
-#define TX_AGG_CNT1	0x1724
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT1_STRUC	{
-	struct	{
-	    USHORT  AggSize4Count;
-	    USHORT  AggSize3Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT1_STRUC, *PTX_AGG_CNT1_STRUC;
-#else
-typedef	union	_TX_AGG_CNT1_STRUC	{
-	struct	{
-	    USHORT  AggSize3Count;
-	    USHORT  AggSize4Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT1_STRUC, *PTX_AGG_CNT1_STRUC;
-#endif
-#define TX_AGG_CNT2	0x1728
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT2_STRUC	{
-	struct	{
-	    USHORT  AggSize6Count;
-	    USHORT  AggSize5Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT2_STRUC, *PTX_AGG_CNT2_STRUC;
-#else
-typedef	union	_TX_AGG_CNT2_STRUC	{
-	struct	{
-	    USHORT  AggSize5Count;
-	    USHORT  AggSize6Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT2_STRUC, *PTX_AGG_CNT2_STRUC;
-#endif
-// Debug counter
-#define TX_AGG_CNT3	0x172c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT3_STRUC	{
-	struct	{
-	    USHORT  AggSize8Count;
-	    USHORT  AggSize7Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT3_STRUC, *PTX_AGG_CNT3_STRUC;
-#else
-typedef	union	_TX_AGG_CNT3_STRUC	{
-	struct	{
-	    USHORT  AggSize7Count;
-	    USHORT  AggSize8Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT3_STRUC, *PTX_AGG_CNT3_STRUC;
-#endif
-// Debug counter
-#define TX_AGG_CNT4	0x1730
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT4_STRUC	{
-	struct	{
-	    USHORT  AggSize10Count;
-	    USHORT  AggSize9Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT4_STRUC, *PTX_AGG_CNT4_STRUC;
-#else
-typedef	union	_TX_AGG_CNT4_STRUC	{
-	struct	{
-	    USHORT  AggSize9Count;
-	    USHORT  AggSize10Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT4_STRUC, *PTX_AGG_CNT4_STRUC;
-#endif
-#define TX_AGG_CNT5	0x1734
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT5_STRUC	{
-	struct	{
-	    USHORT  AggSize12Count;
-	    USHORT  AggSize11Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT5_STRUC, *PTX_AGG_CNT5_STRUC;
-#else
-typedef	union	_TX_AGG_CNT5_STRUC	{
-	struct	{
-	    USHORT  AggSize11Count;
-	    USHORT  AggSize12Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT5_STRUC, *PTX_AGG_CNT5_STRUC;
-#endif
-#define TX_AGG_CNT6		0x1738
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT6_STRUC	{
-	struct	{
-	    USHORT  AggSize14Count;
-	    USHORT  AggSize13Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT6_STRUC, *PTX_AGG_CNT6_STRUC;
-#else
-typedef	union	_TX_AGG_CNT6_STRUC	{
-	struct	{
-	    USHORT  AggSize13Count;
-	    USHORT  AggSize14Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT6_STRUC, *PTX_AGG_CNT6_STRUC;
-#endif
-#define TX_AGG_CNT7		0x173c
-#ifdef RT_BIG_ENDIAN
-typedef	union	_TX_AGG_CNT7_STRUC	{
-	struct	{
-	    USHORT  AggSize16Count;
-	    USHORT  AggSize15Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT7_STRUC, *PTX_AGG_CNT7_STRUC;
-#else
-typedef	union	_TX_AGG_CNT7_STRUC	{
-	struct	{
-	    USHORT  AggSize15Count;
-	    USHORT  AggSize16Count;
-	}	field;
-	UINT32			word;
-}	TX_AGG_CNT7_STRUC, *PTX_AGG_CNT7_STRUC;
-#endif
-#define MPDU_DENSITY_CNT		0x1740
-#ifdef RT_BIG_ENDIAN
-typedef	union	_MPDU_DEN_CNT_STRUC	{
-	struct	{
-	    USHORT  RXZeroDelCount;	//RX zero length delimiter count
-	    USHORT  TXZeroDelCount;	//TX zero length delimiter count
-	}	field;
-	UINT32			word;
-}	MPDU_DEN_CNT_STRUC, *PMPDU_DEN_CNT_STRUC;
-#else
-typedef	union	_MPDU_DEN_CNT_STRUC	{
-	struct	{
-	    USHORT  TXZeroDelCount;	//TX zero length delimiter count
-	    USHORT  RXZeroDelCount;	//RX zero length delimiter count
-	}	field;
-	UINT32			word;
-}	MPDU_DEN_CNT_STRUC, *PMPDU_DEN_CNT_STRUC;
-#endif
-//
-// TXRX control registers - base address 0x3000
-//
-// rt2860b  UNKNOWN reg use R/O Reg Addr 0x77d0 first..
-#define TXRX_CSR1           0x77d0
-
-//
-// Security key table memory, base address = 0x1000
-//
-#define MAC_WCID_BASE		0x1800 //8-bytes(use only 6-bytes) * 256 entry =
-#define HW_WCID_ENTRY_SIZE   8
-#define PAIRWISE_KEY_TABLE_BASE     0x4000      // 32-byte * 256-entry =  -byte
-#define HW_KEY_ENTRY_SIZE           0x20
-#define PAIRWISE_IVEIV_TABLE_BASE     0x6000      // 8-byte * 256-entry =  -byte
-#define MAC_IVEIV_TABLE_BASE     0x6000      // 8-byte * 256-entry =  -byte
-#define HW_IVEIV_ENTRY_SIZE   8
-#define MAC_WCID_ATTRIBUTE_BASE     0x6800      // 4-byte * 256-entry =  -byte
-#define HW_WCID_ATTRI_SIZE   4
-#define WCID_RESERVED          		0x6bfc
-#define SHARED_KEY_TABLE_BASE       0x6c00      // 32-byte * 16-entry = 512-byte
-#define SHARED_KEY_MODE_BASE       0x7000      // 32-byte * 16-entry = 512-byte
-#define HW_SHARED_KEY_MODE_SIZE   4
-#define SHAREDKEYTABLE			0
-#define PAIRWISEKEYTABLE			1
-
-
-#ifdef RT_BIG_ENDIAN
-typedef	union	_SHAREDKEY_MODE_STRUC	{
-	struct	{
-		UINT32       :1;
-		UINT32       Bss1Key3CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key0CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key3CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key0CipherAlg:3;
-	}	field;
-	UINT32			word;
-}	SHAREDKEY_MODE_STRUC, *PSHAREDKEY_MODE_STRUC;
-#else
-typedef	union	_SHAREDKEY_MODE_STRUC	{
-	struct	{
-		UINT32       Bss0Key0CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss0Key3CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key0CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key1CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key2CipherAlg:3;
-		UINT32       :1;
-		UINT32       Bss1Key3CipherAlg:3;
-		UINT32       :1;
-	}	field;
-	UINT32			word;
-}	SHAREDKEY_MODE_STRUC, *PSHAREDKEY_MODE_STRUC;
-#endif
-// 64-entry for pairwise key table
-typedef struct _HW_WCID_ENTRY {  // 8-byte per entry
-    UCHAR   Address[6];
-    UCHAR   Rsv[2];
-} HW_WCID_ENTRY, PHW_WCID_ENTRY;
-
-
-
-//
-// Other on-chip shared memory space, base = 0x2000
-//
-
-// CIS space - base address = 0x2000
-#define HW_CIS_BASE             0x2000
-
-// Carrier-sense CTS frame base address. It's where mac stores carrier-sense frame for carrier-sense function.
-#define HW_CS_CTS_BASE			0x7700
-// DFS CTS frame base address. It's where mac stores CTS frame for DFS.
-#define HW_DFS_CTS_BASE			0x7780
-#define HW_CTS_FRAME_SIZE		0x80
-
-// 2004-11-08 john - since NULL frame won't be that long (256 byte). We steal 16 tail bytes
-// to save debugging settings
-#define HW_DEBUG_SETTING_BASE   0x77f0  // 0x77f0~0x77ff total 16 bytes
-#define HW_DEBUG_SETTING_BASE2   0x7770  // 0x77f0~0x77ff total 16 bytes
-
-// In order to support maximum 8 MBSS and its maximum length is 512 for each beacon
-// Three section discontinue memory segments will be used.
-// 1. The original region for BCN 0~3
-// 2. Extract memory from FCE table for BCN 4~5
-// 3. Extract memory from Pair-wise key table for BCN 6~7
-//	  It occupied those memory of wcid 238~253 for BCN 6
-//						      and wcid 222~237 for BCN 7
-#define HW_BEACON_MAX_SIZE      0x1000 /* unit: byte */
-#define HW_BEACON_BASE0         0x7800
-#define HW_BEACON_BASE1         0x7A00
-#define HW_BEACON_BASE2         0x7C00
-#define HW_BEACON_BASE3         0x7E00
-#define HW_BEACON_BASE4         0x7200
-#define HW_BEACON_BASE5         0x7400
-#define HW_BEACON_BASE6         0x5DC0
-#define HW_BEACON_BASE7         0x5BC0
-
-#define HW_BEACON_MAX_COUNT     8
-#define HW_BEACON_OFFSET		0x0200
-#define HW_BEACON_CONTENT_LEN	(HW_BEACON_OFFSET - TXWI_SIZE)
-
-// HOST-MCU shared memory - base address = 0x2100
-#define HOST_CMD_CSR		0x404
-#define H2M_MAILBOX_CSR         0x7010
-#define H2M_MAILBOX_CID         0x7014
-#define H2M_MAILBOX_STATUS      0x701c
-#define H2M_INT_SRC             0x7024
-#define H2M_BBP_AGENT           0x7028
-#define M2H_CMD_DONE_CSR        0x000c
-#define MCU_TXOP_ARRAY_BASE     0x000c   // TODO: to be provided by Albert
-#define MCU_TXOP_ENTRY_SIZE     32       // TODO: to be provided by Albert
-#define MAX_NUM_OF_TXOP_ENTRY   16       // TODO: must be same with 8051 firmware
-#define MCU_MBOX_VERSION        0x01     // TODO: to be confirmed by Albert
-#define MCU_MBOX_VERSION_OFFSET 5        // TODO: to be provided by Albert
-
-//
-// Host DMA registers - base address 0x200 .  TX0-3=EDCAQid0-3, TX4=HCCA, TX5=MGMT,
-//
-//
-//  DMA RING DESCRIPTOR
-//
-#define E2PROM_CSR          0x0004
-#define IO_CNTL_CSR         0x77d0
-
-#ifdef RT2870
-// 8051 firmware image for usb - use last-half base address = 0x3000
-#define FIRMWARE_IMAGE_BASE     0x3000
-#define MAX_FIRMWARE_IMAGE_SIZE 0x1000    // 4kbyte
-#endif // RT2870 //
-
-// TODO: ????? old RT2560 registers. to keep them or remove them?
-//#define MCAST0                  0x0178  // multicast filter register 0
-//#define MCAST1                  0x017c  // multicast filter register 1
-
-
-// ================================================================
-// Tx /	Rx / Mgmt ring descriptor definition
-// ================================================================
-
-// the following PID values are used to mark outgoing frame type in TXD->PID so that
-// proper TX statistics can be collected based on these categories
-// b3-2 of PID field -
-#define PID_MGMT			0x05
-#define PID_BEACON			0x0c
-#define PID_DATA_NORMALUCAST	 	0x02
-#define PID_DATA_AMPDU	 	0x04
-#define PID_DATA_NO_ACK    	0x08
-#define PID_DATA_NOT_NORM_ACK	 	0x03
-// value domain of pTxD->HostQId (4-bit: 0~15)
-#define QID_AC_BK               1   // meet ACI definition in 802.11e
-#define QID_AC_BE               0   // meet ACI definition in 802.11e
-#define QID_AC_VI               2
-#define QID_AC_VO               3
-#define QID_HCCA                4
-#define NUM_OF_TX_RING          5
-#define QID_MGMT                13
-#define QID_RX                  14
-#define QID_OTHER               15
-
-
-// ------------------------------------------------------
-// BBP & RF	definition
-// ------------------------------------------------------
-#define	BUSY		                1
-#define	IDLE		                0
-
-#define	RF_R00					    0
-#define	RF_R01					    1
-#define	RF_R02					    2
-#define	RF_R03					    3
-#define	RF_R04					    4
-#define	RF_R05					    5
-#define	RF_R06					    6
-#define	RF_R07					    7
-#define	RF_R08					    8
-#define	RF_R09					    9
-#define	RF_R10					    10
-#define	RF_R11					    11
-#define	RF_R12					    12
-#define	RF_R13					    13
-#define	RF_R14					    14
-#define	RF_R15					    15
-#define	RF_R16					    16
-#define	RF_R17					    17
-#define	RF_R18					    18
-#define	RF_R19					    19
-#define	RF_R20					    20
-#define	RF_R21					    21
-#define	RF_R22					    22
-#define	RF_R23					    23
-#define	RF_R24					    24
-#define	RF_R25					    25
-#define	RF_R26					    26
-#define	RF_R27					    27
-#define	RF_R28					    28
-#define	RF_R29					    29
-#define	RF_R30					    30
-#define	RF_R31					    31
-
-#define	BBP_R0					    0  // version
-#define	BBP_R1				        1  // TSSI
-#define	BBP_R2          			2  // TX configure
-#define BBP_R3                      3
-#define BBP_R4                      4
-#define BBP_R5                      5
-#define BBP_R6                      6
-#define	BBP_R14			            14 // RX configure
-#define BBP_R16                     16
-#define BBP_R17                     17 // RX sensibility
-#define BBP_R18                     18
-#define BBP_R21                     21
-#define BBP_R22                     22
-#define BBP_R24                     24
-#define BBP_R25                     25
-#define BBP_R31                     31
-#define BBP_R49                     49 //TSSI
-#define BBP_R50                     50
-#define BBP_R51                     51
-#define BBP_R52                     52
-#define BBP_R55                     55
-#define BBP_R62                     62 // Rx SQ0 Threshold HIGH
-#define BBP_R63                     63
-#define BBP_R64                     64
-#define BBP_R65                     65
-#define BBP_R66                     66
-#define BBP_R67                     67
-#define BBP_R68                     68
-#define BBP_R69                     69
-#define BBP_R70                     70 // Rx AGC SQ CCK Xcorr threshold
-#define BBP_R73                     73
-#define BBP_R75						75
-#define BBP_R77                     77
-#define BBP_R79                     79
-#define BBP_R80                     80
-#define BBP_R81                     81
-#define BBP_R82                     82
-#define BBP_R83                     83
-#define BBP_R84                     84
-#define BBP_R86						86
-#define BBP_R91						91
-#define BBP_R92						92
-#define BBP_R94                     94 // Tx Gain Control
-#define BBP_R103                    103
-#define BBP_R105                    105
-#define BBP_R113                    113
-#define BBP_R114                    114
-#define BBP_R115                    115
-#define BBP_R116                    116
-#define BBP_R117                    117
-#define BBP_R118                    118
-#define BBP_R119                    119
-#define BBP_R120                    120
-#define BBP_R121                    121
-#define BBP_R122                    122
-#define BBP_R123                    123
-#ifdef RT30xx
-#define BBP_R138                    138 // add by johnli, RF power sequence setup, ADC dynamic on/off control
-#endif // RT30xx //
-
-
-#define BBPR94_DEFAULT              0x06 // Add 1 value will gain 1db
-
-//#define PHY_TR_SWITCH_TIME          5  // usec
-
-//#define BBP_R17_LOW_SENSIBILITY     0x50
-//#define BBP_R17_MID_SENSIBILITY     0x41
-//#define BBP_R17_DYNAMIC_UP_BOUND    0x40
-#define RSSI_FOR_VERY_LOW_SENSIBILITY -35
-#define RSSI_FOR_LOW_SENSIBILITY      -58
-#define RSSI_FOR_MID_LOW_SENSIBILITY  -80
-#define RSSI_FOR_MID_SENSIBILITY      -90
-
-//-------------------------------------------------------------------------
-// EEPROM definition
-//-------------------------------------------------------------------------
-#define EEDO                        0x08
-#define EEDI                        0x04
-#define EECS                        0x02
-#define EESK                        0x01
-#define EERL                        0x80
-
-#define EEPROM_WRITE_OPCODE         0x05
-#define EEPROM_READ_OPCODE          0x06
-#define EEPROM_EWDS_OPCODE          0x10
-#define EEPROM_EWEN_OPCODE          0x13
-
-#define	NUM_EEPROM_BBP_PARMS		19			// Include NIC Config 0, 1, CR, TX ALC step, BBPs
-#define	NUM_EEPROM_TX_G_PARMS		7
-#define	EEPROM_NIC1_OFFSET          0x34		// The address is from NIC config 0, not BBP register ID
-#define	EEPROM_NIC2_OFFSET          0x36		// The address is from NIC config 0, not BBP register ID
-#define	EEPROM_BBP_BASE_OFFSET		0xf0		// The address is from NIC config 0, not BBP register ID
-#define	EEPROM_G_TX_PWR_OFFSET		0x52
-#define	EEPROM_G_TX2_PWR_OFFSET		0x60
-#define EEPROM_LED1_OFFSET			0x3c
-#define EEPROM_LED2_OFFSET			0x3e
-#define EEPROM_LED3_OFFSET			0x40
-#define EEPROM_LNA_OFFSET			0x44
-#define EEPROM_RSSI_BG_OFFSET		0x46
-#define EEPROM_RSSI_A_OFFSET		0x4a
-#define EEPROM_DEFINE_MAX_TXPWR		0x4e
-#define EEPROM_TXPOWER_BYRATE_20MHZ_2_4G	0xde	// 20MHZ 2.4G tx power.
-#define EEPROM_TXPOWER_BYRATE_40MHZ_2_4G	0xee	// 40MHZ 2.4G tx power.
-#define EEPROM_TXPOWER_BYRATE_20MHZ_5G		0xfa	// 20MHZ 5G tx power.
-#define EEPROM_TXPOWER_BYRATE_40MHZ_5G		0x10a	// 40MHZ 5G tx power.
-#define EEPROM_A_TX_PWR_OFFSET      0x78
-#define EEPROM_A_TX2_PWR_OFFSET      0xa6
-//#define EEPROM_Japan_TX_PWR_OFFSET      0x90 // 802.11j
-//#define EEPROM_Japan_TX2_PWR_OFFSET      0xbe
-//#define EEPROM_TSSI_REF_OFFSET	0x54
-//#define EEPROM_TSSI_DELTA_OFFSET	0x24
-//#define EEPROM_CCK_TX_PWR_OFFSET  0x62
-//#define EEPROM_CALIBRATE_OFFSET	0x7c
-#define EEPROM_VERSION_OFFSET       0x02
-#define	EEPROM_FREQ_OFFSET			0x3a
-#define EEPROM_TXPOWER_BYRATE 	0xde	// 20MHZ power.
-#define EEPROM_TXPOWER_DELTA		0x50	// 20MHZ AND 40 MHZ use different power. This is delta in 40MHZ.
-#define VALID_EEPROM_VERSION        1
-
-// PairKeyMode definition
-#define PKMODE_NONE                 0
-#define PKMODE_WEP64                1
-#define PKMODE_WEP128               2
-#define PKMODE_TKIP                 3
-#define PKMODE_AES                  4
-#define PKMODE_CKIP64               5
-#define PKMODE_CKIP128              6
-#define PKMODE_TKIP_NO_MIC          7       // MIC appended by driver: not a valid value in hardware key table
-
-// =================================================================================
-// WCID  format
-// =================================================================================
-//7.1	WCID  ENTRY  format  : 8bytes
-typedef	struct	_WCID_ENTRY_STRUC {
-	UCHAR		RXBABitmap7;    // bit0 for TID8, bit7 for TID 15
-	UCHAR		RXBABitmap0;    // bit0 for TID0, bit7 for TID 7
-	UCHAR		MAC[6];	// 0 for shared key table.  1 for pairwise key table
-}	WCID_ENTRY_STRUC, *PWCID_ENTRY_STRUC;
-
-//8.1.1	SECURITY  KEY  format  : 8DW
-// 32-byte per entry, total 16-entry for shared key table, 64-entry for pairwise key table
-typedef struct _HW_KEY_ENTRY {          // 32-byte per entry
-    UCHAR   Key[16];
-    UCHAR   TxMic[8];
-    UCHAR   RxMic[8];
-} HW_KEY_ENTRY, *PHW_KEY_ENTRY;
-
-//8.1.2	IV/EIV  format  : 2DW
-
-//8.1.3	RX attribute entry format  : 1DW
-#ifdef RT_BIG_ENDIAN
-typedef	struct	_MAC_ATTRIBUTE_STRUC {
-	UINT32		rsv:22;
-	UINT32		RXWIUDF:3;
-	UINT32		BSSIDIdx:3; //multipleBSS index for the WCID
-	UINT32		PairKeyMode:3;
-	UINT32		KeyTab:1;	// 0 for shared key table.  1 for pairwise key table
-}	MAC_ATTRIBUTE_STRUC, *PMAC_ATTRIBUTE_STRUC;
-#else
-typedef	struct	_MAC_ATTRIBUTE_STRUC {
-	UINT32		KeyTab:1;	// 0 for shared key table.  1 for pairwise key table
-	UINT32		PairKeyMode:3;
-	UINT32		BSSIDIdx:3; //multipleBSS index for the WCID
-	UINT32		RXWIUDF:3;
-	UINT32		rsv:22;
-}	MAC_ATTRIBUTE_STRUC, *PMAC_ATTRIBUTE_STRUC;
-#endif
-
-
-// =================================================================================
-// TX / RX ring descriptor format
-// =================================================================================
-
-// the first 24-byte in TXD is called TXINFO and will be DMAed to MAC block through TXFIFO.
-// MAC block use this TXINFO to control the transmission behavior of this frame.
-#define FIFO_MGMT                 0
-#define FIFO_HCCA                 1
-#define FIFO_EDCA                 2
-
-//
-// TX descriptor format, Tx	ring, Mgmt Ring
-//
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _TXD_STRUC {
-	// Word 0
-	UINT32		SDPtr0;
-	// Word 1
-	UINT32		DMADONE:1;
-	UINT32		LastSec0:1;
-	UINT32		SDLen0:14;
-	UINT32		Burst:1;
-	UINT32		LastSec1:1;
-	UINT32		SDLen1:14;
-	// Word 2
-	UINT32		SDPtr1;
-	// Word 3
-	UINT32		ICO:1;
-	UINT32		UCO:1;
-	UINT32		TCO:1;
-	UINT32		rsv:2;
-	UINT32		QSEL:2;	// select on-chip FIFO ID for 2nd-stage output scheduler.0:MGMT, 1:HCCA 2:EDCA
-	UINT32		WIV:1;	// Wireless Info Valid. 1 if Driver already fill WI,  o if DMA needs to copy WI to correctposition
-	UINT32		rsv2:24;
-}	TXD_STRUC, *PTXD_STRUC;
-#else
-typedef	struct	PACKED _TXD_STRUC {
-	// Word	0
-	UINT32		SDPtr0;
-	// Word	1
-	UINT32		SDLen1:14;
-	UINT32		LastSec1:1;
-	UINT32		Burst:1;
-	UINT32		SDLen0:14;
-	UINT32		LastSec0:1;
-	UINT32		DMADONE:1;
-	//Word2
-	UINT32		SDPtr1;
-	//Word3
-	UINT32		rsv2:24;
-	UINT32		WIV:1;	// Wireless Info Valid. 1 if Driver already fill WI,  o if DMA needs to copy WI to correctposition
-	UINT32		QSEL:2;	// select on-chip FIFO ID for 2nd-stage output scheduler.0:MGMT, 1:HCCA 2:EDCA
-	UINT32		rsv:2;
-	UINT32		TCO:1;	//
-	UINT32		UCO:1;	//
-	UINT32		ICO:1;	//
-}	TXD_STRUC, *PTXD_STRUC;
-#endif
-
-
-//
-// TXD Wireless Information format for Tx ring and Mgmt Ring
-//
-//txop : for txop mode
-// 0:txop for the MPDU frame will be handles by ASIC by register
-// 1/2/3:the MPDU frame is send after PIFS/backoff/SIFS
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _TXWI_STRUC {
-	// Word 0
-	UINT32		PHYMODE:2;
-	UINT32		TxBF:1;	// 3*3
-	UINT32		rsv2:1;
-//	UINT32		rsv2:2;
-	UINT32		Ifs:1;	//
-	UINT32		STBC:2;	//channel bandwidth 20MHz or 40 MHz
-	UINT32		ShortGI:1;
-	UINT32		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	UINT32		MCS:7;
-
-	UINT32		rsv:6;
-	UINT32		txop:2;	//tx back off mode 0:HT TXOP rule , 1:PIFS TX ,2:Backoff, 3:sifs only when previous frame exchange is successful.
-	UINT32		MpduDensity:3;
-	UINT32		AMPDU:1;
-
-	UINT32		TS:1;
-	UINT32		CFACK:1;
-	UINT32		MIMOps:1;	// the remote peer is in dynamic MIMO-PS mode
-	UINT32		FRAG:1;		// 1 to inform TKIP engine this is a fragment.
-	// Word 1
-	UINT32		PacketId:4;
-	UINT32		MPDUtotalByteCount:12;
-	UINT32		WirelessCliID:8;
-	UINT32		BAWinSize:6;
-	UINT32		NSEQ:1;
-	UINT32		ACK:1;
-	// Word 2
-	UINT32		IV;
-	// Word 3
-	UINT32		EIV;
-}	TXWI_STRUC, *PTXWI_STRUC;
-#else
-typedef	struct	PACKED _TXWI_STRUC {
-	// Word	0
-	UINT32		FRAG:1;		// 1 to inform TKIP engine this is a fragment.
-	UINT32		MIMOps:1;	// the remote peer is in dynamic MIMO-PS mode
-	UINT32		CFACK:1;
-	UINT32		TS:1;
-
-	UINT32		AMPDU:1;
-	UINT32		MpduDensity:3;
-	UINT32		txop:2;	//FOR "THIS" frame. 0:HT TXOP rule , 1:PIFS TX ,2:Backoff, 3:sifs only when previous frame exchange is successful.
-	UINT32		rsv:6;
-
-	UINT32		MCS:7;
-	UINT32		BW:1;	//channel bandwidth 20MHz or 40 MHz
-	UINT32		ShortGI:1;
-	UINT32		STBC:2;	// 1: STBC support MCS =0-7,   2,3 : RESERVE
-	UINT32		Ifs:1;	//
-//	UINT32		rsv2:2;	//channel bandwidth 20MHz or 40 MHz
-	UINT32		rsv2:1;
-	UINT32		TxBF:1;	// 3*3
-	UINT32		PHYMODE:2;
-	// Word	1
-	UINT32		ACK:1;
-	UINT32		NSEQ:1;
-	UINT32		BAWinSize:6;
-	UINT32		WirelessCliID:8;
-	UINT32		MPDUtotalByteCount:12;
-	UINT32		PacketId:4;
-	//Word2
-	UINT32		IV;
-	//Word3
-	UINT32		EIV;
-}	TXWI_STRUC, *PTXWI_STRUC;
-#endif
-//
-// Rx descriptor format, Rx	Ring
-//
-//
-// RXWI wireless information format, in PBF. invisible in driver.
-//
-#ifdef RT_BIG_ENDIAN
-typedef	struct	PACKED _RXWI_STRUC {
-	// Word 0
-	UINT32		TID:4;
-	UINT32		MPDUtotalByteCount:12;
-	UINT32		UDF:3;
-	UINT32		BSSID:3;
-	UINT32		KeyIndex:2;
-	UINT32		WirelessCliID:8;
-	// Word 1
-	UINT32		PHYMODE:2;              // 1: this RX frame is unicast to me
-	UINT32		rsv:3;
-	UINT32		STBC:2;
-	UINT32		ShortGI:1;
-	UINT32		BW:1;
-	UINT32		MCS:7;
-	UINT32		SEQUENCE:12;
-	UINT32		FRAG:4;
-	// Word 2
-	UINT32		rsv1:8;
-	UINT32		RSSI2:8;
-	UINT32		RSSI1:8;
-	UINT32		RSSI0:8;
-	// Word 3
-	UINT32		rsv2:16;
-	UINT32		SNR1:8;
-	UINT32		SNR0:8;
-}	RXWI_STRUC, *PRXWI_STRUC;
-#else
-typedef	struct	PACKED _RXWI_STRUC {
-	// Word	0
-	UINT32		WirelessCliID:8;
-	UINT32		KeyIndex:2;
-	UINT32		BSSID:3;
-	UINT32		UDF:3;
-	UINT32		MPDUtotalByteCount:12;
-	UINT32		TID:4;
-	// Word	1
-	UINT32		FRAG:4;
-	UINT32		SEQUENCE:12;
-	UINT32		MCS:7;
-	UINT32		BW:1;
-	UINT32		ShortGI:1;
-	UINT32		STBC:2;
-	UINT32		rsv:3;
-	UINT32		PHYMODE:2;              // 1: this RX frame is unicast to me
-	//Word2
-	UINT32		RSSI0:8;
-	UINT32		RSSI1:8;
-	UINT32		RSSI2:8;
-	UINT32		rsv1:8;
-	//Word3
-	UINT32		SNR0:8;
-	UINT32		SNR1:8;
-	UINT32		rsv2:16;
-}	RXWI_STRUC, *PRXWI_STRUC;
-#endif
-
-
-// =================================================================================
-// HOST-MCU communication data structure
-// =================================================================================
-
-//
-// H2M_MAILBOX_CSR: Host-to-MCU Mailbox
-//
-#ifdef RT_BIG_ENDIAN
-typedef union  _H2M_MAILBOX_STRUC {
-    struct {
-        UINT32       Owner:8;
-        UINT32       CmdToken:8;    // 0xff tells MCU not to report CmdDoneInt after excuting the command
-        UINT32       HighByte:8;
-        UINT32       LowByte:8;
-    }   field;
-    UINT32           word;
-} H2M_MAILBOX_STRUC, *PH2M_MAILBOX_STRUC;
-#else
-typedef union  _H2M_MAILBOX_STRUC {
-    struct {
-        UINT32       LowByte:8;
-        UINT32       HighByte:8;
-        UINT32       CmdToken:8;
-        UINT32       Owner:8;
-    }   field;
-    UINT32           word;
-} H2M_MAILBOX_STRUC, *PH2M_MAILBOX_STRUC;
-#endif
-
-//
-// M2H_CMD_DONE_CSR: MCU-to-Host command complete indication
-//
-#ifdef RT_BIG_ENDIAN
-typedef union _M2H_CMD_DONE_STRUC {
-    struct  {
-        UINT32       CmdToken3;
-        UINT32       CmdToken2;
-        UINT32       CmdToken1;
-        UINT32       CmdToken0;
-    } field;
-    UINT32           word;
-} M2H_CMD_DONE_STRUC, *PM2H_CMD_DONE_STRUC;
-#else
-typedef union _M2H_CMD_DONE_STRUC {
-    struct  {
-        UINT32       CmdToken0;
-        UINT32       CmdToken1;
-        UINT32       CmdToken2;
-        UINT32       CmdToken3;
-    } field;
-    UINT32           word;
-} M2H_CMD_DONE_STRUC, *PM2H_CMD_DONE_STRUC;
-#endif
-
-
-
-//
-// MCU_LEDCS: MCU LED Control Setting.
-//
-#ifdef RT_BIG_ENDIAN
-typedef union  _MCU_LEDCS_STRUC {
-	struct	{
-		UCHAR		Polarity:1;
-		UCHAR		LedMode:7;
-	} field;
-	UCHAR				word;
-} MCU_LEDCS_STRUC, *PMCU_LEDCS_STRUC;
-#else
-typedef union  _MCU_LEDCS_STRUC {
-	struct	{
-		UCHAR		LedMode:7;
-		UCHAR		Polarity:1;
-	} field;
-	UCHAR			word;
-} MCU_LEDCS_STRUC, *PMCU_LEDCS_STRUC;
-#endif
-// =================================================================================
-// Register format
-// =================================================================================
-
-
-
-//NAV_TIME_CFG :NAV
-#ifdef RT_BIG_ENDIAN
-typedef	union	_NAV_TIME_CFG_STRUC	{
-	struct	{
-		USHORT		rsv:6;
-		USHORT		ZeroSifs:1;               // Applied zero SIFS timer after OFDM RX 0: disable
-		USHORT		Eifs:9;               // in unit of 1-us
-		UCHAR       SlotTime;    // in unit of 1-us
-		UCHAR		Sifs;               // in unit of 1-us
-	}	field;
-	UINT32			word;
-}	NAV_TIME_CFG_STRUC, *PNAV_TIME_CFG_STRUC;
-#else
-typedef	union	_NAV_TIME_CFG_STRUC	{
-	struct	{
-		UCHAR		Sifs;               // in unit of 1-us
-		UCHAR       SlotTime;    // in unit of 1-us
-		USHORT		Eifs:9;               // in unit of 1-us
-		USHORT		ZeroSifs:1;               // Applied zero SIFS timer after OFDM RX 0: disable
-		USHORT		rsv:6;
-	}	field;
-	UINT32			word;
-}	NAV_TIME_CFG_STRUC, *PNAV_TIME_CFG_STRUC;
-#endif
-
-
-
-
-
-//
-// RX_FILTR_CFG:  /RX configuration register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	RX_FILTR_CFG_STRUC	{
-	struct	{
-		UINT32		:15;
-		UINT32       DropRsvCntlType:1;
-
-        	UINT32       	DropBAR:1;       //
-		UINT32		DropBA:1;		//
-		UINT32		DropPsPoll:1;		// Drop Ps-Poll
-		UINT32		DropRts:1;		// Drop Ps-Poll
-
-		UINT32		DropCts:1;		// Drop Ps-Poll
-		UINT32		DropAck:1;		// Drop Ps-Poll
-		UINT32		DropCFEnd:1;		// Drop Ps-Poll
-		UINT32		DropCFEndAck:1;		// Drop Ps-Poll
-
-		UINT32		DropDuplicate:1;		// Drop duplicate frame
-		UINT32		DropBcast:1;		// Drop broadcast frames
-		UINT32		DropMcast:1;		// Drop multicast frames
-		UINT32		DropVerErr:1;	    // Drop version error frame
-
-		UINT32		DropNotMyBSSID:1;			// Drop fram ToDs bit is true
-		UINT32		DropNotToMe:1;		// Drop not to me unicast frame
-		UINT32		DropPhyErr:1;		// Drop physical error
-		UINT32		DropCRCErr:1;		// Drop CRC error
-	}	field;
-	UINT32			word;
-}	RX_FILTR_CFG_STRUC, *PRX_FILTR_CFG_STRUC;
-#else
-typedef	union	_RX_FILTR_CFG_STRUC	{
-	struct	{
-		UINT32		DropCRCErr:1;		// Drop CRC error
-		UINT32		DropPhyErr:1;		// Drop physical error
-		UINT32		DropNotToMe:1;		// Drop not to me unicast frame
-		UINT32		DropNotMyBSSID:1;			// Drop fram ToDs bit is true
-
-		UINT32		DropVerErr:1;	    // Drop version error frame
-		UINT32		DropMcast:1;		// Drop multicast frames
-		UINT32		DropBcast:1;		// Drop broadcast frames
-		UINT32		DropDuplicate:1;		// Drop duplicate frame
-
-		UINT32		DropCFEndAck:1;		// Drop Ps-Poll
-		UINT32		DropCFEnd:1;		// Drop Ps-Poll
-		UINT32		DropAck:1;		// Drop Ps-Poll
-		UINT32		DropCts:1;		// Drop Ps-Poll
-
-		UINT32		DropRts:1;		// Drop Ps-Poll
-		UINT32		DropPsPoll:1;		// Drop Ps-Poll
-		UINT32		DropBA:1;		//
-        	UINT32       	DropBAR:1;       //
-
-		UINT32       	DropRsvCntlType:1;
-		UINT32		:15;
-	}	field;
-	UINT32			word;
-}	RX_FILTR_CFG_STRUC, *PRX_FILTR_CFG_STRUC;
-#endif
-
-
-
-
-//
-// PHY_CSR4: RF serial control register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_PHY_CSR4_STRUC	{
-	struct	{
-		UINT32		Busy:1;				// 1: ASIC is busy execute RF programming.
-		UINT32		PLL_LD:1;			// RF PLL_LD status
-		UINT32		IFSelect:1;			// 1: select IF	to program,	0: select RF to	program
-		UINT32		NumberOfBits:5;		// Number of bits used in RFRegValue (I:20,	RFMD:22)
-		UINT32		RFRegValue:24;		// Register	value (include register	id)	serial out to RF/IF	chip.
-	}	field;
-	UINT32			word;
-}	PHY_CSR4_STRUC, *PPHY_CSR4_STRUC;
-#else
-typedef	union	_PHY_CSR4_STRUC	{
-	struct	{
-		UINT32		RFRegValue:24;		// Register	value (include register	id)	serial out to RF/IF	chip.
-		UINT32		NumberOfBits:5;		// Number of bits used in RFRegValue (I:20,	RFMD:22)
-		UINT32		IFSelect:1;			// 1: select IF	to program,	0: select RF to	program
-		UINT32		PLL_LD:1;			// RF PLL_LD status
-		UINT32		Busy:1;				// 1: ASIC is busy execute RF programming.
-	}	field;
-	UINT32			word;
-}	PHY_CSR4_STRUC, *PPHY_CSR4_STRUC;
-#endif
-
-
-//
-// SEC_CSR5: shared key table security mode register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_SEC_CSR5_STRUC	{
-	struct	{
-        UINT32       :1;
-        UINT32       Bss3Key3CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key2CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key1CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key0CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key3CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key2CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key1CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key0CipherAlg:3;
-	}	field;
-	UINT32			word;
-}	SEC_CSR5_STRUC, *PSEC_CSR5_STRUC;
-#else
-typedef	union	_SEC_CSR5_STRUC	{
-	struct	{
-        UINT32       Bss2Key0CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key1CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key2CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss2Key3CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key0CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key1CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key2CipherAlg:3;
-        UINT32       :1;
-        UINT32       Bss3Key3CipherAlg:3;
-        UINT32       :1;
-	}	field;
-	UINT32			word;
-}	SEC_CSR5_STRUC, *PSEC_CSR5_STRUC;
-#endif
-
-
-//
-// HOST_CMD_CSR: For HOST to interrupt embedded processor
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_HOST_CMD_CSR_STRUC	{
-	struct	{
-	    UINT32   Rsv:24;
-	    UINT32   HostCommand:8;
-	}	field;
-	UINT32			word;
-}	HOST_CMD_CSR_STRUC, *PHOST_CMD_CSR_STRUC;
-#else
-typedef	union	_HOST_CMD_CSR_STRUC	{
-	struct	{
-	    UINT32   HostCommand:8;
-	    UINT32   Rsv:24;
-	}	field;
-	UINT32			word;
-}	HOST_CMD_CSR_STRUC, *PHOST_CMD_CSR_STRUC;
-#endif
-
-
-//
-// AIFSN_CSR: AIFSN for each EDCA AC
-//
-
-
-
-//
-// E2PROM_CSR: EEPROM control register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_E2PROM_CSR_STRUC	{
-	struct	{
-		UINT32		Rsvd:25;
-		UINT32       LoadStatus:1;   // 1:loading, 0:done
-		UINT32		Type:1;			// 1: 93C46, 0:93C66
-		UINT32		EepromDO:1;
-		UINT32		EepromDI:1;
-		UINT32		EepromCS:1;
-		UINT32		EepromSK:1;
-		UINT32		Reload:1;		// Reload EEPROM content, write one to reload, self-cleared.
-	}	field;
-	UINT32			word;
-}	E2PROM_CSR_STRUC, *PE2PROM_CSR_STRUC;
-#else
-typedef	union	_E2PROM_CSR_STRUC	{
-	struct	{
-		UINT32		Reload:1;		// Reload EEPROM content, write one to reload, self-cleared.
-		UINT32		EepromSK:1;
-		UINT32		EepromCS:1;
-		UINT32		EepromDI:1;
-		UINT32		EepromDO:1;
-		UINT32		Type:1;			// 1: 93C46, 0:93C66
-		UINT32       LoadStatus:1;   // 1:loading, 0:done
-		UINT32		Rsvd:25;
-	}	field;
-	UINT32			word;
-}	E2PROM_CSR_STRUC, *PE2PROM_CSR_STRUC;
-#endif
-
-
-// -------------------------------------------------------------------
-//  E2PROM data layout
-// -------------------------------------------------------------------
-
-//
-// EEPROM antenna select format
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_ANTENNA_STRUC	{
-	struct	{
-		USHORT      Rsv:4;
-		USHORT      RfIcType:4;             // see E2PROM document
-		USHORT		TxPath:4;	// 1: 1T, 2: 2T
-		USHORT		RxPath:4;	// 1: 1R, 2: 2R, 3: 3R
-	}	field;
-	USHORT			word;
-}	EEPROM_ANTENNA_STRUC, *PEEPROM_ANTENNA_STRUC;
-#else
-typedef	union	_EEPROM_ANTENNA_STRUC	{
-	struct	{
-		USHORT		RxPath:4;	// 1: 1R, 2: 2R, 3: 3R
-		USHORT		TxPath:4;	// 1: 1T, 2: 2T
-		USHORT      RfIcType:4;             // see E2PROM document
-		USHORT      Rsv:4;
-	}	field;
-	USHORT			word;
-}	EEPROM_ANTENNA_STRUC, *PEEPROM_ANTENNA_STRUC;
-#endif
-
-#ifdef RT_BIG_ENDIAN
-typedef	union _EEPROM_NIC_CINFIG2_STRUC	{
-	struct	{
-        USHORT		DACTestBit:1;			// control if driver should patch the DAC issue
-		USHORT		Rsv2:3;					// must be 0
-        USHORT		AntDiversity:1;			// Antenna diversity
-		USHORT		Rsv1:1;					// must be 0
-		USHORT		BW40MAvailForA:1;			// 0:enable, 1:disable
-		USHORT		BW40MAvailForG:1;			// 0:enable, 1:disable
-		USHORT		EnableWPSPBC:1;                 // WPS PBC Control bit
-		USHORT		BW40MSidebandForA:1;
-		USHORT		BW40MSidebandForG:1;
-		USHORT		CardbusAcceleration:1;	// !!! NOTE: 0 - enable, 1 - disable
-		USHORT		ExternalLNAForA:1;			// external LNA enable for 5G
-		USHORT		ExternalLNAForG:1;			// external LNA enable for 2.4G
-		USHORT		DynamicTxAgcControl:1;			//
-		USHORT		HardwareRadioControl:1;	// Whether RF is controlled by driver or HW. 1:enable hw control, 0:disable
-	}	field;
-	USHORT			word;
-}	EEPROM_NIC_CONFIG2_STRUC, *PEEPROM_NIC_CONFIG2_STRUC;
-#else
-typedef	union _EEPROM_NIC_CINFIG2_STRUC	{
-	struct {
-		USHORT		HardwareRadioControl:1;	// 1:enable, 0:disable
-		USHORT		DynamicTxAgcControl:1;			//
-		USHORT		ExternalLNAForG:1;				//
-		USHORT		ExternalLNAForA:1;			// external LNA enable for 2.4G
-		USHORT		CardbusAcceleration:1;	// !!! NOTE: 0 - enable, 1 - disable
-		USHORT		BW40MSidebandForG:1;
-		USHORT		BW40MSidebandForA:1;
-		USHORT		EnableWPSPBC:1;                 // WPS PBC Control bit
-		USHORT		BW40MAvailForG:1;			// 0:enable, 1:disable
-		USHORT		BW40MAvailForA:1;			// 0:enable, 1:disable
-		USHORT		Rsv1:1;					// must be 0
-		USHORT		AntDiversity:1;			// Antenna diversity
-		USHORT		Rsv2:3;					// must be 0
-		USHORT		DACTestBit:1;			// control if driver should patch the DAC issue
-	}	field;
-	USHORT			word;
-}	EEPROM_NIC_CONFIG2_STRUC, *PEEPROM_NIC_CONFIG2_STRUC;
-#endif
-
-//
-// TX_PWR Value valid range 0xFA(-6) ~ 0x24(36)
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_TX_PWR_STRUC	{
-	struct	{
-		CHAR	Byte1;				// High Byte
-		CHAR	Byte0;				// Low Byte
-	}	field;
-	USHORT	word;
-}	EEPROM_TX_PWR_STRUC, *PEEPROM_TX_PWR_STRUC;
-#else
-typedef	union	_EEPROM_TX_PWR_STRUC	{
-	struct	{
-		CHAR	Byte0;				// Low Byte
-		CHAR	Byte1;				// High Byte
-	}	field;
-	USHORT	word;
-}	EEPROM_TX_PWR_STRUC, *PEEPROM_TX_PWR_STRUC;
-#endif
-
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_VERSION_STRUC	{
-	struct	{
-		UCHAR	Version;			// High Byte
-		UCHAR	FaeReleaseNumber;	// Low Byte
-	}	field;
-	USHORT	word;
-}	EEPROM_VERSION_STRUC, *PEEPROM_VERSION_STRUC;
-#else
-typedef	union	_EEPROM_VERSION_STRUC	{
-	struct	{
-		UCHAR	FaeReleaseNumber;	// Low Byte
-		UCHAR	Version;			// High Byte
-	}	field;
-	USHORT	word;
-}	EEPROM_VERSION_STRUC, *PEEPROM_VERSION_STRUC;
-#endif
-
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_LED_STRUC	{
-	struct	{
-		USHORT	Rsvd:3;				// Reserved
-		USHORT	LedMode:5;			// Led mode.
-		USHORT	PolarityGPIO_4:1;	// Polarity GPIO#4 setting.
-		USHORT	PolarityGPIO_3:1;	// Polarity GPIO#3 setting.
-		USHORT	PolarityGPIO_2:1;	// Polarity GPIO#2 setting.
-		USHORT	PolarityGPIO_1:1;	// Polarity GPIO#1 setting.
-		USHORT	PolarityGPIO_0:1;	// Polarity GPIO#0 setting.
-		USHORT	PolarityACT:1;		// Polarity ACT setting.
-		USHORT	PolarityRDY_A:1;		// Polarity RDY_A setting.
-		USHORT	PolarityRDY_G:1;		// Polarity RDY_G setting.
-	}	field;
-	USHORT	word;
-}	EEPROM_LED_STRUC, *PEEPROM_LED_STRUC;
-#else
-typedef	union	_EEPROM_LED_STRUC	{
-	struct	{
-		USHORT	PolarityRDY_G:1;		// Polarity RDY_G setting.
-		USHORT	PolarityRDY_A:1;		// Polarity RDY_A setting.
-		USHORT	PolarityACT:1;		// Polarity ACT setting.
-		USHORT	PolarityGPIO_0:1;	// Polarity GPIO#0 setting.
-		USHORT	PolarityGPIO_1:1;	// Polarity GPIO#1 setting.
-		USHORT	PolarityGPIO_2:1;	// Polarity GPIO#2 setting.
-		USHORT	PolarityGPIO_3:1;	// Polarity GPIO#3 setting.
-		USHORT	PolarityGPIO_4:1;	// Polarity GPIO#4 setting.
-		USHORT	LedMode:5;			// Led mode.
-		USHORT	Rsvd:3;				// Reserved
-	}	field;
-	USHORT	word;
-}	EEPROM_LED_STRUC, *PEEPROM_LED_STRUC;
-#endif
-
-#ifdef RT_BIG_ENDIAN
-typedef	union	_EEPROM_TXPOWER_DELTA_STRUC	{
-	struct	{
-		UCHAR	TxPowerEnable:1;// Enable
-		UCHAR	Type:1;			// 1: plus the delta value, 0: minus the delta value
-		UCHAR	DeltaValue:6;	// Tx Power dalta value (MAX=4)
-	}	field;
-	UCHAR	value;
-}	EEPROM_TXPOWER_DELTA_STRUC, *PEEPROM_TXPOWER_DELTA_STRUC;
-#else
-typedef	union	_EEPROM_TXPOWER_DELTA_STRUC	{
-	struct	{
-		UCHAR	DeltaValue:6;	// Tx Power dalta value (MAX=4)
-		UCHAR	Type:1;			// 1: plus the delta value, 0: minus the delta value
-		UCHAR	TxPowerEnable:1;// Enable
-	}	field;
-	UCHAR	value;
-}	EEPROM_TXPOWER_DELTA_STRUC, *PEEPROM_TXPOWER_DELTA_STRUC;
-#endif
-
-//
-// QOS_CSR0: TXOP holder address0 register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_QOS_CSR0_STRUC	{
-	struct	{
-		UCHAR		Byte3;		// MAC address byte 3
-		UCHAR		Byte2;		// MAC address byte 2
-		UCHAR		Byte1;		// MAC address byte 1
-		UCHAR		Byte0;		// MAC address byte 0
-	}	field;
-	UINT32			word;
-}	QOS_CSR0_STRUC, *PQOS_CSR0_STRUC;
-#else
-typedef	union	_QOS_CSR0_STRUC	{
-	struct	{
-		UCHAR		Byte0;		// MAC address byte 0
-		UCHAR		Byte1;		// MAC address byte 1
-		UCHAR		Byte2;		// MAC address byte 2
-		UCHAR		Byte3;		// MAC address byte 3
-	}	field;
-	UINT32			word;
-}	QOS_CSR0_STRUC, *PQOS_CSR0_STRUC;
-#endif
-
-//
-// QOS_CSR1: TXOP holder address1 register
-//
-#ifdef RT_BIG_ENDIAN
-typedef	union	_QOS_CSR1_STRUC	{
-	struct	{
-		UCHAR		Rsvd1;
-		UCHAR		Rsvd0;
-		UCHAR		Byte5;		// MAC address byte 5
-		UCHAR		Byte4;		// MAC address byte 4
-	}	field;
-	UINT32			word;
-}	QOS_CSR1_STRUC, *PQOS_CSR1_STRUC;
-#else
-typedef	union	_QOS_CSR1_STRUC	{
-	struct	{
-		UCHAR		Byte4;		// MAC address byte 4
-		UCHAR		Byte5;		// MAC address byte 5
-		UCHAR		Rsvd0;
-		UCHAR		Rsvd1;
-	}	field;
-	UINT32			word;
-}	QOS_CSR1_STRUC, *PQOS_CSR1_STRUC;
-#endif
-
-#define	RF_CSR_CFG	0x500
-#ifdef RT_BIG_ENDIAN
-typedef	union	_RF_CSR_CFG_STRUC	{
-	struct	{
-		UINT	Rsvd1:14;				// Reserved
-		UINT	RF_CSR_KICK:1;			// kick RF register read/write
-		UINT	RF_CSR_WR:1;			// 0: read  1: write
-		UINT	Rsvd2:3;				// Reserved
-		UINT	TESTCSR_RFACC_REGNUM:5;	// RF register ID
-		UINT	RF_CSR_DATA:8;			// DATA
-	}	field;
-	UINT	word;
-}	RF_CSR_CFG_STRUC, *PRF_CSR_CFG_STRUC;
-#else
-typedef	union	_RF_CSR_CFG_STRUC	{
-	struct	{
-		UINT	RF_CSR_DATA:8;			// DATA
-		UINT	TESTCSR_RFACC_REGNUM:5;	// RF register ID
-		UINT	Rsvd2:3;				// Reserved
-		UINT	RF_CSR_WR:1;			// 0: read  1: write
-		UINT	RF_CSR_KICK:1;			// kick RF register read/write
-		UINT	Rsvd1:14;				// Reserved
-	}	field;
-	UINT	word;
-}	RF_CSR_CFG_STRUC, *PRF_CSR_CFG_STRUC;
-#endif
-
-#endif	// __RT28XX_H__
+#include "../rt2870/rt28xx.h"
diff --git a/drivers/staging/rt3070/rt_ate.c b/drivers/staging/rt3070/rt_ate.c
deleted file mode 100644
index 9238d96..0000000
--- a/drivers/staging/rt3070/rt_ate.c
+++ /dev/null
@@ -1,6506 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#include "rt_config.h"
-
-#ifdef UCOS
-INT IoctlResponse(PUCHAR payload, PUCHAR msg, INT len);
-#endif // UCOS //
-
-#define ATE_BBP_REG_NUM	168
-UCHAR restore_BBP[ATE_BBP_REG_NUM]={0};
-
-#ifdef RALINK_ATE
-UCHAR TemplateFrame[24] = {0x08/* Data type */,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0xAA,0xBB,0x12,0x34,0x56,0x00,0x11,0x22,0xAA,0xBB,0xCC,0x00,0x00};	// 802.11 MAC Header, Type:Data, Length:24bytes
-extern RTMP_RF_REGS RF2850RegTable[];
-extern UCHAR NUM_OF_2850_CHNL;
-
-#ifdef RT2870
-extern UCHAR EpToQueue[];
-extern VOID	RTUSBRejectPendingPackets(	IN	PRTMP_ADAPTER	pAd);
-#endif // RT2870 //
-
-#ifdef RT30xx
-//2008/07/10:KH adds to support 3070 ATE<--
-extern FREQUENCY_ITEM FreqItems3020[];
-extern UCHAR NUM_OF_3020_CHNL;
-//2008/07/10:KH adds to support 3070 ATE-->
-#endif // RT30xx //
-
-#ifdef UCOS
-extern INT ConsoleResponse(IN PUCHAR buff);
-extern int (*remote_display)(char *);
-#endif // UCOS //
-
-static CHAR CCKRateTable[] = {0, 1, 2, 3, 8, 9, 10, 11, -1}; /* CCK Mode. */
-static CHAR OFDMRateTable[] = {0, 1, 2, 3, 4, 5, 6, 7, -1}; /* OFDM Mode. */
-static CHAR HTMIXRateTable[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -1}; /* HT Mix Mode. */
-
-static INT TxDmaBusy(
-	IN PRTMP_ADAPTER pAd);
-
-static INT RxDmaBusy(
-	IN PRTMP_ADAPTER pAd);
-
-static VOID RtmpDmaEnable(
-	IN PRTMP_ADAPTER pAd,
-	IN INT Enable);
-
-static VOID BbpSoftReset(
-	IN PRTMP_ADAPTER pAd);
-
-static VOID RtmpRfIoWrite(
-	IN PRTMP_ADAPTER pAd);
-
-static INT ATESetUpFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT32 TxIdx);
-
-static INT ATETxPwrHandler(
-	IN PRTMP_ADAPTER pAd,
-	IN char index);
-
-static INT ATECmdHandler(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-static int CheckMCSValid(
-	IN UCHAR Mode,
-	IN UCHAR Mcs);
-
-
-#ifdef RT2870
-static VOID ATEWriteTxInfo(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXINFO_STRUC 	pTxInfo,
-	IN	  USHORT		USBDMApktLen,
-	IN	  BOOLEAN		bWiv,
-	IN	  UCHAR			QueueSel,
-	IN	  UCHAR			NextValid,
-	IN	  UCHAR			TxBurst);
-
-static VOID ATEWriteTxWI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXWI_STRUC 	pTxWI,
-	IN	BOOLEAN			FRAG,
-	IN	BOOLEAN			InsTimestamp,
-	IN	BOOLEAN 		AMPDU,
-	IN	BOOLEAN 		Ack,
-	IN	BOOLEAN 		NSeq,		// HW new a sequence.
-	IN	UCHAR			BASize,
-	IN	UCHAR			WCID,
-	IN	ULONG			Length,
-	IN	UCHAR 			PID,
-	IN	UCHAR			MIMOps,
-	IN	UCHAR			Txopmode,
-	IN	BOOLEAN			CfAck,
-	IN	HTTRANSMIT_SETTING	Transmit);
-
-#endif // RT2870 //
-
-static VOID SetJapanFilter(
-	IN	PRTMP_ADAPTER	pAd);
-
-/*=========================end of prototype=========================*/
-
-
-#ifdef RT2870
-static INT TxDmaBusy(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT result;
-	USB_DMA_CFG_STRUC UsbCfg;
-
-	RTMP_IO_READ32(pAd, USB_DMA_CFG, &UsbCfg.word);	// disable DMA
-	if (UsbCfg.field.TxBusy)
-		result = 1;
-	else
-		result = 0;
-
-	return result;
-}
-
-static INT RxDmaBusy(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT result;
-	USB_DMA_CFG_STRUC UsbCfg;
-
-	RTMP_IO_READ32(pAd, USB_DMA_CFG, &UsbCfg.word);	// disable DMA
-	if (UsbCfg.field.RxBusy)
-		result = 1;
-	else
-		result = 0;
-
-	return result;
-}
-
-static VOID RtmpDmaEnable(
-	IN PRTMP_ADAPTER pAd,
-	IN INT Enable)
-{
-	BOOLEAN value;
-	ULONG WaitCnt;
-	USB_DMA_CFG_STRUC UsbCfg;
-
-	value = Enable > 0 ? 1 : 0;
-
-	// check DMA is in busy mode.
-	WaitCnt = 0;
-	while (TxDmaBusy(pAd) || RxDmaBusy(pAd))
-	{
-		RTMPusecDelay(10);
-		if (WaitCnt++ > 100)
-			break;
-	}
-
-	//Why not to clear USB DMA TX path first ???
-	RTMP_IO_READ32(pAd, USB_DMA_CFG, &UsbCfg.word);	// disable DMA
-	UsbCfg.field.TxBulkEn = value;
-	UsbCfg.field.RxBulkEn = value;
-	RTMP_IO_WRITE32(pAd, USB_DMA_CFG, UsbCfg.word);	// abort all TX rings
-	RTMPusecDelay(5000);
-
-	return;
-}
-#endif // RT2870 //
-
-static VOID BbpSoftReset(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR BbpData = 0;
-
-	// Soft reset, set BBP R21 bit0=1->0
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R21, &BbpData);
-	BbpData |= 0x00000001; //set bit0=1
-	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R21, BbpData);
-
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R21, &BbpData);
-	BbpData &= ~(0x00000001); //set bit0=0
-	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R21, BbpData);
-
-	return;
-}
-
-static VOID RtmpRfIoWrite(
-	IN PRTMP_ADAPTER pAd)
-{
-	// Set RF value 1's set R3[bit2] = [0]
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-	RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-	RTMPusecDelay(200);
-
-	// Set RF value 2's set R3[bit2] = [1]
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-	RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 | 0x04));
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-	RTMPusecDelay(200);
-
-	// Set RF value 3's set R3[bit2] = [0]
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R1);
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R2);
-	RTMP_RF_IO_WRITE32(pAd, (pAd->LatchRfRegs.R3 & (~0x04)));
-	RTMP_RF_IO_WRITE32(pAd, pAd->LatchRfRegs.R4);
-
-	return;
-}
-
-static int CheckMCSValid(
-	UCHAR Mode,
-	UCHAR Mcs)
-{
-	int i;
-	PCHAR pRateTab;
-
-	switch(Mode)
-	{
-		case 0:
-			pRateTab = CCKRateTable;
-			break;
-		case 1:
-			pRateTab = OFDMRateTable;
-			break;
-		case 2:
-		case 3:
-			pRateTab = HTMIXRateTable;
-			break;
-		default:
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("unrecognizable Tx Mode %d\n", Mode));
-			return -1;
-			break;
-	}
-
-	i = 0;
-	while(pRateTab[i] != -1)
-	{
-		if (pRateTab[i] == Mcs)
-			return 0;
-		i++;
-	}
-
-	return -1;
-}
-
-#if 1
-static INT ATETxPwrHandler(
-	IN PRTMP_ADAPTER pAd,
-	IN char index)
-{
-	ULONG R;
-	CHAR TxPower;
-	UCHAR Bbp94 = 0;
-	BOOLEAN bPowerReduce = FALSE;
-#ifdef RT30xx
-	UCHAR RFValue;
-#endif // RT30xx //
-#ifdef RALINK_28xx_QA
-	if ((pAd->ate.bQATxStart == TRUE) || (pAd->ate.bQARxStart == TRUE))
-	{
-		/* When QA is used for Tx, pAd->ate.TxPower0/1 and real tx power
-		** are not synchronized.
-		*/
-/*
-		pAd->ate.TxPower0 = pAd->LatchRfRegs.xxx;
-		pAd->ate.TxPower1 = pAd->LatchRfRegs.xxx;
-*/
-		return 0;
-	}
-	else
-#endif // RALINK_28xx_QA //
-	{
-		TxPower = index == 0 ? pAd->ate.TxPower0 : pAd->ate.TxPower1;
-
-		if (pAd->ate.Channel <= 14)
-		{
-			if (TxPower > 31)
-			{
-				//
-				// R3, R4 can't large than 31 (0x24), 31 ~ 36 used by BBP 94
-				//
-				R = 31;
-				if (TxPower <= 36)
-					Bbp94 = BBPR94_DEFAULT + (UCHAR)(TxPower - 31);
-			}
-			else if (TxPower < 0)
-			{
-				//
-				// R3, R4 can't less than 0, -1 ~ -6 used by BBP 94
-				//
-				R = 0;
-				if (TxPower >= -6)
-					Bbp94 = BBPR94_DEFAULT + TxPower;
-			}
-			else
-			{
-				// 0 ~ 31
-				R = (ULONG) TxPower;
-				Bbp94 = BBPR94_DEFAULT;
-			}
-
-			ATEDBGPRINT(RT_DEBUG_TRACE, ("%s (TxPower=%d, R=%ld, BBP_R94=%d)\n", __FUNCTION__, TxPower, R, Bbp94));
-		}
-		else// 5.5 GHz
-		{
-			if (TxPower > 15)
-			{
-				//
-				// R3, R4 can't large than 15 (0x0F)
-				//
-				R = 15;
-			}
-			else if (TxPower < 0)
-			{
-				//
-				// R3, R4 can't less than 0
-				//
-				// -1 ~ -7
-				ASSERT((TxPower >= -7));
-				R = (ULONG)(TxPower + 7);
-				bPowerReduce = TRUE;
-			}
-			else
-			{
-				// 0 ~ 15
-				R = (ULONG) TxPower;
-			}
-
-			ATEDBGPRINT(RT_DEBUG_TRACE, ("%s (TxPower=%d, R=%lu)\n", __FUNCTION__, TxPower, R));
-		}
-//2008/09/10:KH adds to support 3070 ATE TX Power tunning real time<--
-#ifdef RT30xx
-		if(IS_RT30xx(pAd))
-		{
-			// Set Tx Power
-
-					RT30xxReadRFRegister(pAd, RF_R12, (PUCHAR)&RFValue);
-					RFValue = (RFValue & 0xE0) | TxPower;
-					RT30xxWriteRFRegister(pAd, RF_R12, (UCHAR)RFValue);
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("3070 or 2070:%s (TxPower=%d, RFValue=%x)\n", __FUNCTION__, TxPower, RFValue));
-
-		}
-		else
-#endif // RT30xx //
-	      {
-		if (pAd->ate.Channel <= 14)
-		{
-			if (index == 0)
-			{
-				R = R << 9;		// shift TX power control to correct RF(R3) register bit position
-				R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-				pAd->LatchRfRegs.R3 = R;
-			}
-			else
-			{
-				R = R << 6;		// shift TX power control to correct RF(R4) register bit position
-				R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-				pAd->LatchRfRegs.R4 = R;
-			}
-		}
-		else// 5.5GHz
-		{
-			if (bPowerReduce == FALSE)
-			{
-				if (index == 0)
-				{
-					R = (R << 10) | (1 << 9);		// shift TX power control to correct RF(R3) register bit position
-					R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-					pAd->LatchRfRegs.R3 = R;
-				}
-				else
-				{
-					R = (R << 7) | (1 << 6);		// shift TX power control to correct RF(R4) register bit position
-					R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-					pAd->LatchRfRegs.R4 = R;
-				}
-			}
-			else
-			{
-				if (index == 0)
-				{
-					R = (R << 10);		// shift TX power control to correct RF(R3) register bit position
-					R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-
-					/* Clear bit 9 of R3 to reduce 7dB. */
-					pAd->LatchRfRegs.R3 = (R & (~(1 << 9)));
-				}
-				else
-				{
-					R = (R << 7);		// shift TX power control to correct RF(R4) register bit position
-					R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-
-					/* Clear bit 6 of R4 to reduce 7dB. */
-					pAd->LatchRfRegs.R4 = (R & (~(1 << 6)));
-				}
-			}
-		}
-		RtmpRfIoWrite(pAd);
-           }
-//2008/09/10:KH adds to support 3070 ATE TX Power tunning real time-->
-
-		return 0;
-	}
-}
-#else// 1 //
-static INT ATETxPwrHandler(
-	IN PRTMP_ADAPTER pAd,
-	IN char index)
-{
-	ULONG R;
-	CHAR TxPower;
-	UCHAR Bbp94 = 0;
-
-#ifdef RALINK_28xx_QA
-	if ((pAd->ate.bQATxStart == TRUE) || (pAd->ate.bQARxStart == TRUE))
-	{
-		// TODO: how to get current TxPower0/1 from pAd->LatchRfRegs ?
-		/* When QA is used for Tx, pAd->ate.TxPower0/1 and real tx power
-		** are not synchronized.
-		*/
-/*
-		pAd->ate.TxPower0 = pAd->LatchRfRegs.xxx;
-		pAd->ate.TxPower1 = pAd->LatchRfRegs.xxx;
-*/
-		return 0;
-	}
-	else
-#endif // RALINK_28xx_QA //
-	{
-		TxPower = index == 0 ? pAd->ate.TxPower0 : pAd->ate.TxPower1;
-
-	if (TxPower > 31)
-	{
-		//
-		// R3, R4 can't large than 36 (0x24), 31 ~ 36 used by BBP 94
-		//
-		R = 31;
-		if (TxPower <= 36)
-			Bbp94 = BBPR94_DEFAULT + (UCHAR)(TxPower - 31);
-	}
-	else if (TxPower < 0)
-	{
-		//
-		// R3, R4 can't less than 0, -1 ~ -6 used by BBP 94
-		//
-		R = 0;
-		if (TxPower >= -6)
-			Bbp94 = BBPR94_DEFAULT + TxPower;
-	}
-	else
-	{
-		// 0 ~ 31
-		R = (ULONG) TxPower;
-		Bbp94 = BBPR94_DEFAULT;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("%s (TxPower=%d, R3=%ld, BBP_R94=%d)\n", __FUNCTION__, TxPower, R, Bbp94));
-
-		if (pAd->ate.Channel <= 14)
-		{
-	if (index == 0)
-	{
-		R = R << 9;		// shift TX power control to correct RF(R3) register bit position
-		R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-		pAd->LatchRfRegs.R3 = R;
-	}
-	else
-	{
-		R = R << 6;		// shift TX power control to correct RF(R4) register bit position
-		R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-		pAd->LatchRfRegs.R4 = R;
-	}
-		}
-		else
-		{
-			if (index == 0)
-			{
-				R = (R << 10) | (1 << 9);		// shift TX power control to correct RF(R3) register bit position
-				R |= (pAd->LatchRfRegs.R3 & 0xffffc1ff);
-				pAd->LatchRfRegs.R3 = R;
-			}
-			else
-			{
-				R = (R << 7) | (1 << 6);		// shift TX power control to correct RF(R4) register bit position
-				R |= (pAd->LatchRfRegs.R4 & 0xfffff83f);
-				pAd->LatchRfRegs.R4 = R;
-			}
-		}
-
-	RtmpRfIoWrite(pAd);
-
-	return 0;
-	}
-}
-#endif // 1 //
-/*
-    ==========================================================================
-    Description:
-        Set ATE operation mode to
-        0. ATESTART  = Start ATE Mode
-        1. ATESTOP   = Stop ATE Mode
-        2. TXCONT    = Continuous Transmit
-        3. TXCARR    = Transmit Carrier
-        4. TXFRAME   = Transmit Frames
-        5. RXFRAME   = Receive Frames
-#ifdef RALINK_28xx_QA
-        6. TXSTOP    = Stop Any Type of Transmition
-        7. RXSTOP    = Stop Receiving Frames
-#endif // RALINK_28xx_QA //
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-/*                                                           */
-/*                                                           */
-/*=======================End of RT2860=======================*/
-
-
-/*======================Start of RT2870======================*/
-/*                                                           */
-/*                                                           */
-
-#ifdef RT2870
-static INT	ATECmdHandler(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UINT32			Value;
-	UCHAR			BbpData;
-	UINT32          MacData;
-	UINT			i=0, atemode;
-	//NDIS_STATUS		Status = NDIS_STATUS_SUCCESS;
-	//PUCHAR			pDest;
-	UINT32 			temp;
-	ULONG			IrqFlags;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("===> ATECmdHandler()\n"));
-	ATEAsicSwitchChannel(pAd);
-	/* AsicLockChannel() is empty function so far in fact */
-	AsicLockChannel(pAd, pAd->ate.Channel);
-
-	RTMPusecDelay(5000);
-
-	// Default value in BBP R22 is 0x0.
-	BbpData = 0;
-
-	/* Enter ATE mode and set Tx/Rx Idle */
-	if (!strcmp(arg, "ATESTART"))
-	{
-#ifdef CONFIG_STA_SUPPORT
-		BOOLEAN       Cancelled;
-#endif // CONFIG_STA_SUPPORT //
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: ATESTART\n"));
-
-		netif_stop_queue(pAd->net_dev);
-
-		atemode = pAd->ate.Mode;
-		pAd->ate.Mode = ATE_START;
-//		pAd->ate.TxDoneCount = pAd->ate.TxCount;
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Disable auto responder
-		RTMP_IO_READ32(pAd, AUTO_RSP_CFG, &temp);
-		temp = temp & 0xFFFFFFFE;
-		RTMP_IO_WRITE32(pAd, AUTO_RSP_CFG, temp);
-
-		// read MAC_SYS_CTRL and backup MAC_SYS_CTRL value.
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-		// clean bit4 to stop continuous Tx production test.
-		MacData &= 0xFFFFFFEF;
-		// Stop continuous TX production test.
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);//disable or cancel pending irp first ???
-
-        if (atemode & ATE_TXCARR
-#ifdef RT30xx
- || atemode & ATE_TXCONT
-#endif // RT30xx //
-)
-		{
-#ifdef RT30xx
-			//Hardware Reset BBP
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &temp);
-			temp = temp |0x00000002;
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, temp);
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &temp);
-			temp = temp & ~(0x00000002);
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, temp);
-			//Restore All BBP Value
-			for(i=0;i<ATE_BBP_REG_NUM;i++)
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd,i,restore_BBP[i]);
-#endif // RT30xx //
-
-			// No Carrier Test set BBP R22 bit7=0, bit6=0, bit[5~0]=0x0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF00; //clear bit7, bit6, bit[5~0]
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		}
-		else if (atemode & ATE_TXCARRSUPP)
-		{
-#ifdef RT30xx
-			//Hardware Reset BBP
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &temp);
-			temp = temp |0x00000002;
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, temp);
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &temp);
-			temp = temp & ~(0x00000002);
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, temp);
-			//Restore All BBP Value
-			for(i=0;i<ATE_BBP_REG_NUM;i++)
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd,i,restore_BBP[i]);
-#endif // RT30xx //
-
-			// No Cont. TX set BBP R22 bit7=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= ~(1 << 7); //set bit7=0
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-			// No Carrier Suppression set BBP R24 bit0=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R24, &BbpData);
-			BbpData &= 0xFFFFFFFE; //clear bit0
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, BbpData);
-		}
-		// We should free some resource which allocate when ATE_TXFRAME , ATE_STOP, and ATE_TXCONT.
-		// TODO:Should we free some resource which was allocated when LoopBack and ATE_STOP ?
-		else if ((atemode & ATE_TXFRAME) || (atemode == ATE_STOP))
-		{
-			if (atemode & ATE_TXCONT)
-			{
-				// Not Cont. TX anymore, so set BBP R22 bit7=0
-				ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-				BbpData &= ~(1 << 7); //set bit7=0
-				ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-			}
-			// Abort Tx, Rx DMA.
-			RtmpDmaEnable(pAd, 0);
-
-			{
-				// It seems nothing to free,
-				// because we didn't allocate any resource when we entered ATE_TXFRAME mode latestly.
-			}
-
-			// Start Tx, RX DMA
-			RtmpDmaEnable(pAd, 1);
-		}
-
-		RTUSBRejectPendingPackets(pAd);
-		RTUSBCleanUpDataBulkOutQueue(pAd);
-
-#ifdef CONFIG_STA_SUPPORT
-		//
-		// It will be called in MlmeSuspend().
-		//
-		// Cancel pending timers
-		RTMPCancelTimer(&pAd->MlmeAux.AssocTimer,     &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer,   &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer,   &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.AuthTimer,       &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer,     &Cancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer,       &Cancelled);
-#endif // CONFIG_STA_SUPPORT //
-
-		//RTUSBCleanUpMLMEWaitQueue(pAd);	/* not used in RT28xx */
-		RTUSBCleanUpMLMEBulkOutQueue(pAd);
-
-		// Sometimes kernel will hang on, so we avoid calling MlmeSuspend().
-//		MlmeSuspend(pAd, TRUE);
-		//RTMPCancelTimer(&pAd->Mlme.PeriodicTimer, &Cancelled);
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-		// Disable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Make sure there are no pending bulk in/out IRPs before we go on.
-/*=========================================================================*/
-		/* pAd->PendingRx is not of type atomic_t anymore in 28xx */
-//		while ((atomic_read(&pAd->PendingRx) > 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		while ((pAd->PendingRx > 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		{
-#if 1
-			ATE_RTUSBCancelPendingBulkInIRP(pAd);
-#else
-			NdisInterlockedDecrement(&pAd->PendingRx);
-#endif
-			/* delay 0.5 seconds */
-			RTMPusecDelay(500000);
-			pAd->PendingRx = 0;
-		}
-		/* peter : why don't we have to get BulkOutLock first ? */
-		while (((pAd->BulkOutPending[0] == TRUE) ||
-				(pAd->BulkOutPending[1] == TRUE) ||
-				(pAd->BulkOutPending[2] == TRUE) ||
-				(pAd->BulkOutPending[3] == TRUE)) && (pAd->BulkFlags != 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		{
-			do
-			{
-				/* pAd->BulkOutPending[y] will be set to FALSE in RTUSBCancelPendingBulkOutIRP(pAd) */
-				RTUSBCancelPendingBulkOutIRP(pAd);
-			} while (FALSE);
-
-			/* we have enough time delay in RTUSBCancelPendingBulkOutIRP(pAd)
-			** so this is not necessary
-			*/
-//			RTMPusecDelay(500000);
-		}
-
-		/* pAd->PendingRx is not of type atomic_t anymore in 28xx */
-//		ASSERT(atomic_read(&pAd->PendingRx) == 0);
-		ASSERT(pAd->PendingRx == 0);
-/*=========================================================================*/
-
-		// reset Rx statistics.
-		pAd->ate.LastSNR0 = 0;
-		pAd->ate.LastSNR1 = 0;
-		pAd->ate.LastRssi0 = 0;
-		pAd->ate.LastRssi1 = 0;
-		pAd->ate.LastRssi2 = 0;
-		pAd->ate.AvgRssi0 = 0;
-		pAd->ate.AvgRssi1 = 0;
-		pAd->ate.AvgRssi2 = 0;
-		pAd->ate.AvgRssi0X8 = 0;
-		pAd->ate.AvgRssi1X8 = 0;
-		pAd->ate.AvgRssi2X8 = 0;
-		pAd->ate.NumOfAvgRssiSample = 0;
-
-#ifdef RALINK_28xx_QA
-		// Tx frame
-		pAd->ate.bQATxStart = FALSE;
-		pAd->ate.bQARxStart = FALSE;
-		pAd->ate.seq = 0;
-
-		// counters
-		pAd->ate.U2M = 0;
-		pAd->ate.OtherData = 0;
-		pAd->ate.Beacon = 0;
-		pAd->ate.OtherCount = 0;
-		pAd->ate.TxAc0 = 0;
-		pAd->ate.TxAc1 = 0;
-		pAd->ate.TxAc2 = 0;
-		pAd->ate.TxAc3 = 0;
-		pAd->ate.TxHCCA = 0;
-		pAd->ate.TxMgmt = 0;
-		pAd->ate.RSSI0 = 0;
-		pAd->ate.RSSI1 = 0;
-		pAd->ate.RSSI2 = 0;
-		pAd->ate.SNR0 = 0;
-		pAd->ate.SNR1 = 0;
-
-		// control
-		pAd->ate.TxDoneCount = 0;
-		pAd->ate.TxStatus = 0; // task Tx status // 0 --> task is idle, 1 --> task is running
-#endif // RALINK_28xx_QA //
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-
-#ifdef CONFIG_STA_SUPPORT
-		AsicDisableSync(pAd);
-
-		/*
-		** If we skip "LinkDown()", we should disable protection
-		** to prevent from sending out RTS or CTS-to-self.
-		*/
-		ATEDisableAsicProtect(pAd);
-		RTMPStationStop(pAd);
-#endif // CONFIG_STA_SUPPORT //
-
-		// Default value in BBP R22 is 0x0.
-		BbpData = 0;
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-
-		// Clean bit4 to stop continuous Tx production test.
-		MacData &= 0xFFFFFFEF;
-	   	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-	    	RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-		//Clean ATE Bulk in/out counter and continue setup
-		InterlockedExchange(&pAd->BulkOutRemained, 0);
-
-		/* NdisAcquireSpinLock()/NdisReleaseSpinLock() need only one argument in RT28xx */
-		NdisAcquireSpinLock(&pAd->GenericLock);
-		pAd->ContinBulkOut = FALSE;
-		pAd->ContinBulkIn = FALSE;
-		NdisReleaseSpinLock(&pAd->GenericLock);
-
-		RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-	}
-	else if (!strcmp(arg, "ATESTOP"))
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE : ATESTOP ===>\n"));
-
-		// Default value in BBP R22 is 0x0.
-		BbpData = 0;
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);//0820
-		// Clean bit4 to stop continuous Tx production test.
-		MacData &= 0xFFFFFFEF;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData); // recover the MAC_SYS_CTRL register back.
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		/*
-		** Abort Tx, RX DMA.
-		** Q   : How to do the following I/O if Tx, Rx DMA is aborted ?
-		** Ans : Bulk endpoints are aborted, while the control endpoint is not.
-		*/
-		RtmpDmaEnable(pAd, 0);
-
-		// Disable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		/* Make sure there are no pending bulk in/out IRPs before we go on. */
-/*=========================================================================*/
-//		while ((atomic_read(&pAd->PendingRx) > 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		while (pAd->PendingRx > 0)
-		{
-#if 1
-			ATE_RTUSBCancelPendingBulkInIRP(pAd);
-#else
-//			NdisInterlockedDecrement(&pAd->PendingRx);
-			pAd->PendingRx--;
-#endif
-			RTMPusecDelay(500000);
-		}
-
-		while (((pAd->BulkOutPending[0] == TRUE) ||
-				(pAd->BulkOutPending[1] == TRUE) ||
-				(pAd->BulkOutPending[2] == TRUE) ||
-				(pAd->BulkOutPending[3] == TRUE)) && (pAd->BulkFlags != 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		{
-			do
-			{
-				RTUSBCancelPendingBulkOutIRP(pAd);
-			} while (FALSE);
-
-			RTMPusecDelay(500000);
-		}
-
-//		ASSERT(atomic_read(&pAd->PendingRx) == 0);
-		ASSERT(pAd->PendingRx == 0);
-/*=========================================================================*/
-/*      Reset Rx RING                                                      */
-/*=========================================================================*/
-//		InterlockedExchange(&pAd->PendingRx, 0);
-		pAd->PendingRx = 0;
-		pAd->NextRxBulkInReadIndex = 0;	// Next Rx Read index
-		pAd->NextRxBulkInIndex = RX_RING_SIZE - 1;	// Rx Bulk pointer
-		pAd->NextRxBulkInPosition = 0;
-		for (i = 0; i < (RX_RING_SIZE); i++)
-		{
-			PRX_CONTEXT  pRxContext = &(pAd->RxContext[i]);
-			NdisZeroMemory(pRxContext->TransferBuffer, MAX_RXBULK_SIZE);
-			/* peter : why don't we have to get BulkInLock first ? */
-			pRxContext->pAd	= pAd;
-			pRxContext->pIrp = NULL;
-            /* peter debug ++ */
-			pRxContext->BulkInOffset = 0;
-			pRxContext->bRxHandling = FALSE;
-            /* peter debug -- */
-			pRxContext->InUse		= FALSE;
-			pRxContext->IRPPending	= FALSE;
-			pRxContext->Readable	= FALSE;
-//			pRxContext->ReorderInUse = FALSE;
-//			pRxContext->ReadPosOffset = 0;
-		}
-
-/*=========================================================================*/
-/*      Reset Tx RING                                                      */
-/*=========================================================================*/
-		do
-		{
-			RTUSBCancelPendingBulkOutIRP(pAd);
-		} while (FALSE);
-
-/*=========================================================================*/
-		// Enable auto responder.
-		RTMP_IO_READ32(pAd, AUTO_RSP_CFG, &temp);
-		temp = temp | (0x01);
-		RTMP_IO_WRITE32(pAd, AUTO_RSP_CFG, temp);
-
-/*================================================*/
-		AsicEnableBssSync(pAd);
-
-		/* Soft reset BBP.*/
-		/* In 2870 chipset, ATE_BBP_IO_READ8_BY_REG_ID() == RTMP_BBP_IO_READ8_BY_REG_ID() */
-		/* Both rt2870ap and rt2870sta use BbpSoftReset(pAd) to do BBP soft reset */
-		BbpSoftReset(pAd);
-/*================================================*/
-		{
-#ifdef CONFIG_STA_SUPPORT
-			// Set all state machines back IDLE
-			pAd->Mlme.CntlMachine.CurrState    = CNTL_IDLE;
-			pAd->Mlme.AssocMachine.CurrState   = ASSOC_IDLE;
-			pAd->Mlme.AuthMachine.CurrState    = AUTH_REQ_IDLE;
-			pAd->Mlme.AuthRspMachine.CurrState = AUTH_RSP_IDLE;
-			pAd->Mlme.SyncMachine.CurrState    = SYNC_IDLE;
-			pAd->Mlme.ActMachine.CurrState    = ACT_IDLE;
-#endif // CONFIG_STA_SUPPORT //
-
-			//
-			// ===> refer to MlmeRestartStateMachine().
-			// When we entered ATE_START mode, PeriodicTimer was not cancelled.
-			// So we don't have to set it here.
-			//
-			//RTMPSetTimer(pAd, &pAd->Mlme.PeriodicTimer, MLME_TASK_EXEC_INTV);
-
-			ASSERT(pAd->CommonCfg.Channel != 0);
-
-			AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-			AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-
-
-#ifdef CONFIG_STA_SUPPORT
-		    RTMPStationStart(pAd);
-#endif // CONFIG_STA_SUPPORT //
-		}
-//
-// These two steps have been done when entering ATE_STOP mode.
-//
-		// Clean ATE Bulk in/out counter and continue setup.
-		InterlockedExchange(&pAd->BulkOutRemained, 0);
-		NdisAcquireSpinLock(&pAd->GenericLock);
-		pAd->ContinBulkOut = FALSE;
-		pAd->ContinBulkIn = FALSE;
-		NdisReleaseSpinLock(&pAd->GenericLock);
-
-		/* Wait 50ms to prevent next URB to bulkout during HW reset. */
-		/* todo : remove this if not necessary */
-		NdisMSleep(50000);
-
-		pAd->ate.Mode = ATE_STOP;
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-/*=========================================================================*/
-		/* restore RX_FILTR_CFG */
-#ifdef CONFIG_STA_SUPPORT
-		/* restore RX_FILTR_CFG in order that QA maybe set it to 0x3 */
-		RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, STANORMAL);
-#endif // CONFIG_STA_SUPPORT //
-/*=========================================================================*/
-
-		// Enable Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		// Enable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Wait 10ms to wait all of the bulk-in URBs to complete.
-		/* todo : remove this if not necessary */
-		NdisMSleep(10000);
-
-		// Everything is ready to start normal Tx/Rx.
-		RTUSBBulkReceive(pAd);
-		netif_start_queue(pAd->net_dev);
-
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("<=== ATE : ATESTOP \n"));
-	}
-	else if (!strcmp(arg, "TXCARR"))	// Tx Carrier
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXCARR\n"));
-		pAd->ate.Mode |= ATE_TXCARR;
-
-#ifdef RT30xx
-			for(i=0;i<ATE_BBP_REG_NUM;i++)
-				restore_BBP[i]=0;
-			//Record All BBP Value
-			for(i=0;i<ATE_BBP_REG_NUM;i++)
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd,i,&restore_BBP[i]);
-#endif // RT30xx //
-
-		// Disable Rx
-		// May be we need not to do this, because these have been done in ATE_START mode ???
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// QA has done the following steps if it is used.
-		if (pAd->ate.bQATxStart == FALSE)
-		{
-			// Soft reset BBP.
-			BbpSoftReset(pAd);
-
-			// Carrier Test set BBP R22 bit7=1, bit6=1, bit[5~0]=0x01
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF00; //clear bit7, bit6, bit[5~0]
-			BbpData |= 0x000000C1; //set bit7=1, bit6=1, bit[5~0]=0x01
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-			// set MAC_SYS_CTRL(0x1004) Continuous Tx Production Test (bit4) = 1
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-			Value = Value | 0x00000010;
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-		}
-	}
-	else if (!strcmp(arg, "TXCONT"))	// Tx Continue
-	{
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			/* set MAC_SYS_CTRL(0x1004) bit4(Continuous Tx Production Test)
-			   and bit2(MAC TX enable) back to zero. */
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-			MacData &= 0xFFFFFFEB;
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-			// set BBP R22 bit7=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF7F; //set bit7=0
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		}
-
-		/* for TxCont mode.
-		** Step 1: Send 50 packets first then wait for a moment.
-		** Step 2: Send more 50 packet then start continue mode.
-		*/
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXCONT\n"));
-
-#ifdef RT30xx
-				for(i=0;i<ATE_BBP_REG_NUM;i++)
-				restore_BBP[i]=0;
-			//Record All BBP Value
-			for(i=0;i<ATE_BBP_REG_NUM;i++)
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd,i,&restore_BBP[i]);
-#endif // RT30xx //
-
-		// Step 1: send 50 packets first.
-		pAd->ate.Mode |= ATE_TXCONT;
-		pAd->ate.TxCount = 50;
-		pAd->ate.TxDoneCount = 0;
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-
-		/* Only needed if we have to send some normal frames. */
-		SetJapanFilter(pAd);
-
-		// Setup frame format.
-		ATESetUpFrame(pAd, 0);
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Start Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		InterlockedExchange(&pAd->BulkOutRemained, pAd->ate.TxCount);
-
-#ifdef	RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			pAd->ate.TxStatus = 1;
-			//pAd->ate.Repeat = 0;
-		}
-#endif	// RALINK_28xx_QA //
-
-		NdisAcquireSpinLock(&pAd->GenericLock);//0820
-		pAd->ContinBulkOut = FALSE;
-		NdisReleaseSpinLock(&pAd->GenericLock);
-
-		RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-
-		// Kick bulk out
-		RTUSBKickBulkOut(pAd);
-
-		/* To make sure all the 50 frames have been bulk out before executing step 2 */
-		while (atomic_read(&pAd->BulkOutRemained) > 0)
-		{
-			RTMPusecDelay(5000);
-		}
-
-		// Step 2: send more 50 packets then start continue mode.
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-		// Cont. TX set BBP R22 bit7=1
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-		BbpData |= 0x00000080; //set bit7=1
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-		pAd->ate.TxCount = 50;
-		pAd->ate.TxDoneCount = 0;
-
-		SetJapanFilter(pAd);
-
-		// Setup frame format.
-		ATESetUpFrame(pAd, 0);
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-
-		// Start Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		InterlockedExchange(&pAd->BulkOutRemained, pAd->ate.TxCount);
-
-#ifdef	RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			pAd->ate.TxStatus = 1;
-			//pAd->ate.Repeat = 0;
-		}
-#endif	// RALINK_28xx_QA //
-
-		NdisAcquireSpinLock(&pAd->GenericLock);//0820
-		pAd->ContinBulkOut = FALSE;
-		NdisReleaseSpinLock(&pAd->GenericLock);
-
-		RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-		// Kick bulk out
-		RTUSBKickBulkOut(pAd);
-
-#if 1
-		RTMPusecDelay(500);
-#else
-		while (atomic_read(&pAd->BulkOutRemained) > 0)
-		{
-			RTMPusecDelay(5000);
-		}
-#endif // 1 //
-
-		// Set MAC_SYS_CTRL(0x1004) Continuous Tx Production Test (bit4) = 1.
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-		MacData |= 0x00000010;
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-	}
-	else if (!strcmp(arg, "TXFRAME"))	// Tx Frames
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXFRAME(Count=0x%08x)\n", pAd->ate.TxCount));
-		pAd->ate.Mode |= ATE_TXFRAME;
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-		// Default value in BBP R22 is 0x0.
-		BbpData = 0;
-
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-
-		// Clean bit4 to stop continuous Tx production test.
-		MacData &= 0xFFFFFFEF;
-
-	   	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-#ifdef RALINK_28xx_QA
-		// add this for LoopBack mode
-		if (pAd->ate.bQARxStart == FALSE)
-		{
-			// Disable Rx
-			RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-			Value &= ~(1 << 3);
-			RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-		}
-
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			pAd->ate.TxStatus = 1;
-			//pAd->ate.Repeat = 0;
-		}
-#else
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-#endif // RALINK_28xx_QA //
-
-		// Enable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-        SetJapanFilter(pAd);
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-		pAd->ate.TxDoneCount = 0;
-
-        // Setup frame format
-		ATESetUpFrame(pAd, 0);
-
-		// Start Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		// Check count is continuous or not yet.
-		//
-		// Due to the type mismatch between "pAd->BulkOutRemained"(atomic_t) and "pAd->ate.TxCount"(UINT32)
-		//
-		if (pAd->ate.TxCount == 0)
-		{
-			InterlockedExchange(&pAd->BulkOutRemained, 0);
-		}
-		else
-		{
-			InterlockedExchange(&pAd->BulkOutRemained, pAd->ate.TxCount);
-		}
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("bulk out count = %d\n", atomic_read(&pAd->BulkOutRemained)));
-		ASSERT((atomic_read(&pAd->BulkOutRemained) >= 0));
-
-		if (atomic_read(&pAd->BulkOutRemained) == 0)
-		{
-			ATEDBGPRINT(RT_DEBUG_TRACE, ("Send packet countinuously\n"));
-
-			/* In 28xx, NdisAcquireSpinLock() == spin_lock_bh() */
-			/* NdisAcquireSpinLock only need one argument in 28xx. */
-			NdisAcquireSpinLock(&pAd->GenericLock);
-			pAd->ContinBulkOut = TRUE;
-			NdisReleaseSpinLock(&pAd->GenericLock);
-
-			/* In 28xx, BULK_OUT_LOCK() == spin_lock_irqsave() */
-			BULK_OUT_LOCK(&pAd->BulkOutLock[0], IrqFlags);// peter : NdisAcquireSpinLock ==> BULK_OUT_LOCK
-			pAd->BulkOutPending[0] = FALSE;
-			BULK_OUT_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);// peter : NdisAcquireSpinLock ==> BULK_OUT_LOCK
-		}
-		else
-		{
-			ATEDBGPRINT(RT_DEBUG_TRACE, ("Send packets depend on counter\n"));
-
-			NdisAcquireSpinLock(&pAd->GenericLock);
-			pAd->ContinBulkOut = FALSE;
-			NdisReleaseSpinLock(&pAd->GenericLock);
-
-			BULK_OUT_LOCK(&pAd->BulkOutLock[0], IrqFlags);
-			pAd->BulkOutPending[0] = FALSE;
-			BULK_OUT_UNLOCK(&pAd->BulkOutLock[0], IrqFlags);
-		}
-
-		RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-
-		// Kick bulk out
-		RTUSBKickBulkOut(pAd);
-	}
-#ifdef RALINK_28xx_QA
-	else if (!strcmp(arg, "TXSTOP")) 		//Enter ATE mode and set Tx/Rx Idle
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: TXSTOP\n"));
-
-		atemode = pAd->ate.Mode;
-		pAd->ate.Mode &= ATE_TXSTOP;
-		pAd->ate.bQATxStart = FALSE;
-//		pAd->ate.TxDoneCount = pAd->ate.TxCount;
-
-/*=========================================================================*/
-		if (atemode & ATE_TXCARR)
-		{
-			// No Carrier Test set BBP R22 bit7=0, bit6=0, bit[5~0]=0x0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= 0xFFFFFF00; //clear bit7, bit6, bit[5~0]
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		}
-		else if (atemode & ATE_TXCARRSUPP)
-		{
-			// No Cont. TX set BBP R22 bit7=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-			BbpData &= ~(1 << 7); //set bit7=0
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-
-			// No Carrier Suppression set BBP R24 bit0=0
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R24, &BbpData);
-			BbpData &= 0xFFFFFFFE; //clear bit0
-		    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R24, BbpData);
-		}
-		else if ((atemode & ATE_TXFRAME) || (atemode == ATE_STOP))
-		{
-			if (atemode & ATE_TXCONT)
-			{
-				// No Cont. TX set BBP R22 bit7=0
-				ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R22, &BbpData);
-				BbpData &= ~(1 << 7); //set bit7=0
-				ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-			}
-		}
-
-/*=========================================================================*/
-		RTUSBRejectPendingPackets(pAd);
-		RTUSBCleanUpDataBulkOutQueue(pAd);
-
-		/* not used in RT28xx */
-		//RTUSBCleanUpMLMEWaitQueue(pAd);
-		/* empty function so far */
-		RTUSBCleanUpMLMEBulkOutQueue(pAd);
-/*=========================================================================*/
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-/*=========================================================================*/
-
-		/* In 28xx, pAd->PendingRx is not of type atomic_t anymore */
-//		while ((atomic_read(&pAd->PendingRx) > 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		/* peter todo : BulkInLock */
-		while (pAd->PendingRx > 0)
-		{
-#if 1
-			ATE_RTUSBCancelPendingBulkInIRP(pAd);
-#else
-//			NdisInterlockedDecrement(&pAd->PendingRx);
-			pAd->PendingRx--;
-#endif
-			RTMPusecDelay(500000);
-		}
-
-		while (((pAd->BulkOutPending[0] == TRUE) ||
-				(pAd->BulkOutPending[1] == TRUE) ||
-				(pAd->BulkOutPending[2] == TRUE) ||
-				(pAd->BulkOutPending[3] == TRUE)) && (pAd->BulkFlags != 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		{
-			do
-			{
-				RTUSBCancelPendingBulkOutIRP(pAd);
-			} while (FALSE);
-
-			RTMPusecDelay(500000);
-		}
-
-		ASSERT(pAd->PendingRx == 0);
-/*=========================================================================*/
-		// Enable Tx, Rx DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		/* task Tx status : 0 --> task is idle, 1 --> task is running */
-		pAd->ate.TxStatus = 0;
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-
-		// Disable Tx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-		MacData &= (0xfffffffb);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-		//Clean ATE Bulk in/out counter and continue setup
-		InterlockedExchange(&pAd->BulkOutRemained, 0);
-
-		pAd->ContinBulkOut = FALSE;
-	}
-	else if (!strcmp(arg, "RXSTOP"))
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: RXSTOP\n"));
-		atemode = pAd->ate.Mode;
-
-		// Disable Rx
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		pAd->ate.Mode &= ATE_RXSTOP;
-		pAd->ate.bQARxStart = FALSE;
-//		pAd->ate.TxDoneCount = pAd->ate.TxCount;
-
-/*=========================================================================*/
-		RTUSBRejectPendingPackets(pAd);
-		RTUSBCleanUpDataBulkOutQueue(pAd);
-
-		/* not used in RT28xx */
-		//RTUSBCleanUpMLMEWaitQueue(pAd);
-		RTUSBCleanUpMLMEBulkOutQueue(pAd);
-/*=========================================================================*/
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-/*=========================================================================*/
-//		while ((atomic_read(&pAd->PendingRx) > 0))
-		while (pAd->PendingRx > 0)
-		{
-#if 1
-			ATE_RTUSBCancelPendingBulkInIRP(pAd);
-#else
-//			NdisInterlockedDecrement(&pAd->PendingRx);
-			pAd->PendingRx--;
-#endif
-			RTMPusecDelay(500000);
-		}
-
-		while (((pAd->BulkOutPending[0] == TRUE) ||
-				(pAd->BulkOutPending[1] == TRUE) ||
-				(pAd->BulkOutPending[2] == TRUE) ||
-				(pAd->BulkOutPending[3] == TRUE)) && (pAd->BulkFlags != 0))	//pAd->BulkFlags != 0 wait bulk out finish
-		{
-			do
-			{
-				RTUSBCancelPendingBulkOutIRP(pAd);
-			} while (FALSE);
-
-			RTMPusecDelay(500000);
-		}
-
-		ASSERT(pAd->PendingRx == 0);
-/*=========================================================================*/
-
-		// Soft reset BBP.
-		BbpSoftReset(pAd);
-		pAd->ContinBulkIn = FALSE;
-	}
-#endif // RALINK_28xx_QA //
-	else if (!strcmp(arg, "RXFRAME")) // Rx Frames
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: RXFRAME\n"));
-
-		// Disable Rx of MAC block
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Default value in BBP R22 is 0x0.
-		BbpData = 0;
-
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &MacData);
-		// Clean bit4 to stop continuous Tx production test.
-		MacData &= 0xFFFFFFEF;
-
-	   	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R22, BbpData);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, MacData);
-
-		pAd->ate.Mode |= ATE_RXFRAME;
-
-		// Abort Tx, RX DMA.
-		RtmpDmaEnable(pAd, 0);
-
-		// Disable TX of MAC block
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value &= ~(1 << 2);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-        // Reset Rx RING.
-		for ( i = 0; i < (RX_RING_SIZE); i++)
-		{
-			PRX_CONTEXT  pRxContext = &(pAd->RxContext[i]);
-
-			pRxContext->InUse = FALSE;
-			pRxContext->IRPPending = FALSE;
-			pRxContext->Readable = FALSE;
-
-			//
-			// Get the urb from kernel back to driver.
-			//
-			RTUSB_UNLINK_URB(pRxContext->pUrb);
-
-			/* Sleep 200 microsecs to give cancellation time to work. */
-			NdisMSleep(200);
-			pAd->BulkInReq = 0;
-
-//			InterlockedExchange(&pAd->PendingRx, 0);
-			pAd->PendingRx = 0;
-			pAd->NextRxBulkInReadIndex = 0;	// Next Rx Read index
-			pAd->NextRxBulkInIndex		= RX_RING_SIZE - 1;	// Rx Bulk pointer
-			pAd->NextRxBulkInPosition = 0;
-		}
-
-		// read to clear counters
-		RTUSBReadMACRegister(pAd, RX_STA_CNT0, &temp); //RX PHY & RX CRC count
-		RTUSBReadMACRegister(pAd, RX_STA_CNT1, &temp); //RX PLCP error count & CCA false alarm count
-		RTUSBReadMACRegister(pAd, RX_STA_CNT2, &temp); //RX FIFO overflow frame count & RX duplicated filtered frame count
-
-		pAd->ContinBulkIn = TRUE;
-
-		// Enable Tx, RX DMA.
-		RtmpDmaEnable(pAd, 1);
-
-		// Enable RX of MAC block
-		RTMP_IO_READ32(pAd, MAC_SYS_CTRL, &Value);
-		Value |= (1 << 3);
-		RTMP_IO_WRITE32(pAd, MAC_SYS_CTRL, Value);
-
-		// Kick bulk in
-		RTUSBBulkReceive(pAd);
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ATE: Invalid arg!\n"));
-		return FALSE;
-	}
-	RTMPusecDelay(5000);
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("<=== ATECmdHandler()\n"));
-
-	return TRUE;
-}
-#endif // RT2870 //
-
-INT	Set_ATE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	if (ATECmdHandler(pAd, arg))
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_Proc Success\n"));
-
-
-		return TRUE;
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_Proc Failed\n"));
-		return FALSE;
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE ADDR1=DA for TxFrame(AP  : To DS = 0 ; From DS = 1)
-        or
-        Set ATE ADDR3=DA for TxFrame(STA : To DS = 1 ; From DS = 0)
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_DA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR				*value;
-	INT					i;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-    for (i=0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-		AtoH(value, &pAd->ate.Addr3[i++], 1);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	if(i != 6)
-		return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_DA_Proc (DA = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAd->ate.Addr3[0],
-		pAd->ate.Addr3[1], pAd->ate.Addr3[2], pAd->ate.Addr3[3], pAd->ate.Addr3[4], pAd->ate.Addr3[5]));
-#endif // CONFIG_STA_SUPPORT //
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_DA_Proc Success\n"));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE ADDR3=SA for TxFrame(AP  : To DS = 0 ; From DS = 1)
-        or
-        Set ATE ADDR2=SA for TxFrame(STA : To DS = 1 ; From DS = 0)
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_SA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR				*value;
-	INT					i;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-    for (i=0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-		AtoH(value, &pAd->ate.Addr2[i++], 1);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	if(i != 6)
-		return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_SA_Proc (SA = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAd->ate.Addr2[0],
-		pAd->ate.Addr2[1], pAd->ate.Addr2[2], pAd->ate.Addr2[3], pAd->ate.Addr2[4], pAd->ate.Addr2[5]));
-#endif // CONFIG_STA_SUPPORT //
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_SA_Proc Success\n"));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE ADDR2=BSSID for TxFrame(AP  : To DS = 0 ; From DS = 1)
-        or
-        Set ATE ADDR1=BSSID for TxFrame(STA : To DS = 1 ; From DS = 0)
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_BSSID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR				*value;
-	INT					i;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-    for (i=0, value = rstrtok(arg, ":"); value; value = rstrtok(NULL, ":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-		AtoH(value, &pAd->ate.Addr1[i++], 1);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	if(i != 6)
-		return FALSE;  //Invalid
-
-
-#ifdef CONFIG_STA_SUPPORT
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_BSSID_Proc (BSSID = %2X:%2X:%2X:%2X:%2X:%2X)\n",	pAd->ate.Addr1[0],
-		pAd->ate.Addr1[1], pAd->ate.Addr1[2], pAd->ate.Addr1[3], pAd->ate.Addr1[4], pAd->ate.Addr1[5]));
-#endif // CONFIG_STA_SUPPORT //
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_BSSID_Proc Success\n"));
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Channel
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_CHANNEL_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR channel;
-
-	channel = simple_strtol(arg, 0, 10);
-
-	if ((channel < 1) || (channel > 216))// to allow A band channel : ((channel < 1) || (channel > 14))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_CHANNEL_Proc::Out of range, it should be in range of 1~14.\n"));
-		return FALSE;
-	}
-	pAd->ate.Channel = channel;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_CHANNEL_Proc (ATE Channel = %d)\n", pAd->ate.Channel));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_CHANNEL_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Power0
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_POWER0_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR TxPower;
-
-	TxPower = simple_strtol(arg, 0, 10);
-
-	if (pAd->ate.Channel <= 14)
-	{
-		if ((TxPower > 31) || (TxPower < 0))
-		{
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER0_Proc::Out of range (Value=%d)\n", TxPower));
-			return FALSE;
-		}
-	}
-	else// 5.5GHz
-	{
-		if ((TxPower > 15) || (TxPower < -7))
-		{
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER0_Proc::Out of range (Value=%d)\n", TxPower));
-			return FALSE;
-		}
-	}
-
-	pAd->ate.TxPower0 = TxPower;
-	ATETxPwrHandler(pAd, 0);
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_POWER0_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Power1
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_POWER1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR TxPower;
-
-	TxPower = simple_strtol(arg, 0, 10);
-
-	if (pAd->ate.Channel <= 14)
-	{
-	if ((TxPower > 31) || (TxPower < 0))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER1_Proc::Out of range (Value=%d)\n", TxPower));
-		return FALSE;
-	}
-	}
-	else
-	{
-		if ((TxPower > 15) || (TxPower < -7))
-		{
-			ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_POWER1_Proc::Out of range (Value=%d)\n", TxPower));
-			return FALSE;
-		}
-	}
-
-	pAd->ate.TxPower1 = TxPower;
-	ATETxPwrHandler(pAd, 1);
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_POWER1_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx Antenna
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR value;
-
-	value = simple_strtol(arg, 0, 10);
-
-	if ((value > 2) || (value < 0))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_Antenna_Proc::Out of range (Value=%d)\n", value));
-		return FALSE;
-	}
-
-	pAd->ate.TxAntennaSel = value;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_Antenna_Proc (Antenna = %d)\n", pAd->ate.TxAntennaSel));
-	ATEDBGPRINT(RT_DEBUG_TRACE,("Ralink: Set_ATE_TX_Antenna_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Rx Antenna
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_RX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR value;
-
-	value = simple_strtol(arg, 0, 10);
-
-	if ((value > 3) || (value < 0))
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_RX_Antenna_Proc::Out of range (Value=%d)\n", value));
-		return FALSE;
-	}
-
-	pAd->ate.RxAntennaSel = value;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_RX_Antenna_Proc (Antenna = %d)\n", pAd->ate.RxAntennaSel));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_RX_Antenna_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE RF frequence offset
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_FREQOFFSET_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR RFFreqOffset;
-	ULONG R4;
-
-	RFFreqOffset = simple_strtol(arg, 0, 10);
-#ifndef RT30xx
-	if(RFFreqOffset >= 64)
-#endif // RT30xx //
-#ifdef RT30xx
-//2008/08/06: KH modified the limit of offset value from 65 to 95(0x5F)
-	if(RFFreqOffset >= 95)
-#endif // RT30xx //
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_FREQOFFSET_Proc::Out of range, it should be in range of 0~63.\n"));
-		return FALSE;
-	}
-
-	pAd->ate.RFFreqOffset = RFFreqOffset;
-#ifdef RT30xx
-	if(IS_RT30xx(pAd))
-	{
-		// Set RF offset
-		UCHAR RFValue;
-		RT30xxReadRFRegister(pAd, RF_R23, (PUCHAR)&RFValue);
-				//2008/08/06: KH modified "pAd->RFFreqOffset" to "pAd->ate.RFFreqOffset"
-				RFValue = (RFValue & 0x80) | pAd->ate.RFFreqOffset;
-		RT30xxWriteRFRegister(pAd, RF_R23, (UCHAR)RFValue);
-	}
-	else
-#endif // RT30xx //
-	{
-
-		R4 = pAd->ate.RFFreqOffset << 15;		// shift TX power control to correct RF register bit position
-		R4 |= (pAd->LatchRfRegs.R4 & ((~0x001f8000)));
-		pAd->LatchRfRegs.R4 = R4;
-
-		RtmpRfIoWrite(pAd);
-	}
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_FREQOFFSET_Proc (RFFreqOffset = %d)\n", pAd->ate.RFFreqOffset));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_FREQOFFSET_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE RF BW
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_BW_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	int i;
-	UCHAR value = 0;
-	UCHAR BBPCurrentBW;
-
-	BBPCurrentBW = simple_strtol(arg, 0, 10);
-
-	if(BBPCurrentBW == 0)
-		pAd->ate.TxWI.BW = BW_20;
-	else
-		pAd->ate.TxWI.BW = BW_40;
-
-	if(pAd->ate.TxWI.BW == BW_20)
-	{
-		if(pAd->ate.Channel <= 14)
-		{
- 		for (i=0; i<5; i++)
- 		{
-				if (pAd->Tx20MPwrCfgGBand[i] != 0xffffffff)
-				{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx20MPwrCfgGBand[i]);
-					RTMPusecDelay(5000);
-				}
-			}
-		}
-		else
-		{
-			for (i=0; i<5; i++)
-			{
-				if (pAd->Tx20MPwrCfgABand[i] != 0xffffffff)
- 			{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx20MPwrCfgABand[i]);
- 				RTMPusecDelay(5000);
- 			}
- 		}
-		}
-
-		//Set BBP R4 bit[4:3]=0:0
- 		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
- 		value &= (~0x18);
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
-
-  		//Set BBP R66=0x3C
- 		value = 0x3C;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, value);
-		//Set BBP R68=0x0B
-		//to improve Rx sensitivity.
-		value = 0x0B;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R68, value);
-		//Set BBP R69=0x16
-		value = 0x16;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, value);
-		//Set BBP R70=0x08
-		value = 0x08;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, value);
-		//Set BBP R73=0x11
-		value = 0x11;
- 		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, value);
-
-	    // If Channel=14, Bandwidth=20M and Mode=CCK, Set BBP R4 bit5=1
-	    // (Japan filter coefficients)
-	    // This segment of code will only works when ATETXMODE and ATECHANNEL
-	    // were set to MODE_CCK and 14 respectively before ATETXBW is set to 0.
-	    //=====================================================================
-		if (pAd->ate.Channel == 14)
-		{
-			int TxMode = pAd->ate.TxWI.PHYMODE;
-			if (TxMode == MODE_CCK)
-			{
-				// when Channel==14 && Mode==CCK && BandWidth==20M, BBP R4 bit5=1
- 				ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
-				value |= 0x20; //set bit5=1
- 				ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
-			}
-		}
-
-	    //=====================================================================
-		// If bandwidth != 40M, RF Reg4 bit 21 = 0.
-#ifdef RT30xx
-	// Set BW
-		if(IS_RT30xx(pAd))
-			RT30xxWriteRFRegister(pAd, RF_R24, (UCHAR) pAd->Mlme.CaliBW20RfR24);
-		else
-#endif // RT30xx //
-		{
-		pAd->LatchRfRegs.R4 &= ~0x00200000;
-		RtmpRfIoWrite(pAd);
-	}
-
-	}
-	else if(pAd->ate.TxWI.BW == BW_40)
-	{
-		if(pAd->ate.Channel <= 14)
-		{
-			for (i=0; i<5; i++)
-			{
-				if (pAd->Tx40MPwrCfgGBand[i] != 0xffffffff)
-				{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx40MPwrCfgGBand[i]);
-					RTMPusecDelay(5000);
-				}
-			}
-		}
-		else
-		{
-			for (i=0; i<5; i++)
-			{
-				if (pAd->Tx40MPwrCfgABand[i] != 0xffffffff)
-				{
-					RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, pAd->Tx40MPwrCfgABand[i]);
-					RTMPusecDelay(5000);
-				}
-			}
-#ifdef DOT11_N_SUPPORT
-			if ((pAd->ate.TxWI.PHYMODE >= MODE_HTMIX) && (pAd->ate.TxWI.MCS == 7))
-			{
-    			value = 0x28;
-    			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R67, value);
-			}
-#endif // DOT11_N_SUPPORT //
-		}
-
-		//Set BBP R4 bit[4:3]=1:0
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &value);
-		value &= (~0x18);
-		value |= 0x10;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, value);
-
-		//Set BBP R66=0x3C
-		value = 0x3C;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, value);
-		//Set BBP R68=0x0C
-		//to improve Rx sensitivity.
-		value = 0x0C;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R68, value);
-		//Set BBP R69=0x1A
-		value = 0x1A;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, value);
-		//Set BBP R70=0x0A
-		value = 0x0A;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, value);
-		//Set BBP R73=0x16
-		value = 0x16;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, value);
-
-		// If bandwidth = 40M, set RF Reg4 bit 21 = 1.
-#ifdef RT30xx
-	// Set BW
-		if(IS_RT30xx(pAd))
-			RT30xxWriteRFRegister(pAd, RF_R24, (UCHAR) pAd->Mlme.CaliBW40RfR24);
-		else
-#endif // RT30xx //
-		{
-			pAd->LatchRfRegs.R4 |= 0x00200000;
-			RtmpRfIoWrite(pAd);
-		}
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_BW_Proc (BBPCurrentBW = %d)\n", pAd->ate.TxWI.BW));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_BW_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame length
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_LENGTH_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxLength = simple_strtol(arg, 0, 10);
-
-	if((pAd->ate.TxLength < 24) || (pAd->ate.TxLength > (MAX_FRAME_SIZE - 34/* == 2312 */)))
-	{
-		pAd->ate.TxLength = (MAX_FRAME_SIZE - 34/* == 2312 */);
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_LENGTH_Proc::Out of range, it should be in range of 24~%d.\n", (MAX_FRAME_SIZE - 34/* == 2312 */)));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_LENGTH_Proc (TxLength = %d)\n", pAd->ate.TxLength));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_LENGTH_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame count
-
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_COUNT_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxCount = simple_strtol(arg, 0, 10);
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_COUNT_Proc (TxCount = %d)\n", pAd->ate.TxCount));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_COUNT_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame MCS
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_MCS_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR MCS;
-	int result;
-
-	MCS = simple_strtol(arg, 0, 10);
-	result = CheckMCSValid(pAd->ate.TxWI.PHYMODE, MCS);
-
-	if (result != -1)
-	{
-		pAd->ate.TxWI.MCS = (UCHAR)MCS;
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_MCS_Proc::Out of range, refer to rate table.\n"));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_MCS_Proc (MCS = %d)\n", pAd->ate.TxWI.MCS));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_MCS_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame Mode
-        0: MODE_CCK
-        1: MODE_OFDM
-        2: MODE_HTMIX
-        3: MODE_HTGREENFIELD
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_MODE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxWI.PHYMODE = simple_strtol(arg, 0, 10);
-
-	if(pAd->ate.TxWI.PHYMODE > 3)
-	{
-		pAd->ate.TxWI.PHYMODE = 0;
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_MODE_Proc::Out of range. it should be in range of 0~3\n"));
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("0: CCK, 1: OFDM, 2: HT_MIX, 3: HT_GREEN_FIELD.\n"));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_MODE_Proc (TxMode = %d)\n", pAd->ate.TxWI.PHYMODE));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_MODE_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set ATE Tx frame GI
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_ATE_TX_GI_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.TxWI.ShortGI = simple_strtol(arg, 0, 10);
-
-	if(pAd->ate.TxWI.ShortGI > 1)
-	{
-		pAd->ate.TxWI.ShortGI = 0;
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("Set_ATE_TX_GI_Proc::Out of range\n"));
-		return FALSE;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_TX_GI_Proc (GI = %d)\n", pAd->ate.TxWI.ShortGI));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_TX_GI_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-    ==========================================================================
- */
-INT	Set_ATE_RX_FER_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	pAd->ate.bRxFer = simple_strtol(arg, 0, 10);
-
-	if (pAd->ate.bRxFer == 1)
-	{
-		pAd->ate.RxCntPerSec = 0;
-		pAd->ate.RxTotalCnt = 0;
-	}
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Set_ATE_RX_FER_Proc (bRxFer = %d)\n", pAd->ate.bRxFer));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("Ralink: Set_ATE_RX_FER_Proc Success\n"));
-
-
-	return TRUE;
-}
-
-INT Set_ATE_Read_RF_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-#ifdef RT30xx
-//2008/07/10:KH add to support RT30xx ATE<--
-	if(IS_RT30xx(pAd))
-	{
-			/* modify by WY for Read RF Reg. error */
-		UCHAR RFValue;
-		INT index=0;
-		for (index = 0; index < 32; index++)
-		{
-			RT30xxReadRFRegister(pAd, index, (PUCHAR)&RFValue);
-			printk("R%d=%d\n",index,RFValue);
-		}
-	}
-	else
-//2008/07/10:KH add to support RT30xx ATE-->
-#endif // RT30xx //
-	{
-		ate_print(KERN_EMERG "R1 = %lx\n", pAd->LatchRfRegs.R1);
-		ate_print(KERN_EMERG "R2 = %lx\n", pAd->LatchRfRegs.R2);
-		ate_print(KERN_EMERG "R3 = %lx\n", pAd->LatchRfRegs.R3);
-		ate_print(KERN_EMERG "R4 = %lx\n", pAd->LatchRfRegs.R4);
-	}
-	return TRUE;
-}
-
-INT Set_ATE_Write_RF1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-#ifdef RT30xx
-//2008/07/10:KH add to support 3070 ATE<--
-	if(IS_RT30xx(pAd))
-	{
-		printk("Warning!! RT30xx Don't Support\n");
-		return FALSE;
-
-	}
-	else
-//2008/07/10:KH add to support 3070 ATE-->
-#endif // RT30xx //
-	{
-		UINT32 value = simple_strtol(arg, 0, 16);
-
-		pAd->LatchRfRegs.R1 = value;
-		RtmpRfIoWrite(pAd);
-	}
-	return TRUE;
-
-}
-
-INT Set_ATE_Write_RF2_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-#ifdef RT30xx
-//2008/07/10:KH add to support 3070 ATE<--
-	if(IS_RT30xx(pAd))
-	{
-		printk("Warning!! RT30xx Don't Support\n");
-		return FALSE;
-
-	}
-	else
-//2008/07/10:KH add to support 3070 ATE-->
-#endif // RT30xx //
-	{
-		UINT32 value = simple_strtol(arg, 0, 16);
-
-		pAd->LatchRfRegs.R2 = value;
-		RtmpRfIoWrite(pAd);
-	}
-	return TRUE;
-}
-
-INT Set_ATE_Write_RF3_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-#ifdef RT30xx
-//2008/07/10:KH add to support 3070 ATE<--
-	if(IS_RT30xx(pAd))
-	{
-		printk("Warning!! RT30xx Don't Support\n");
-		return FALSE;
-
-	}
-	else
-//2008/07/10:KH add to support 3070 ATE-->
-#endif // RT30xx //
-	{
-		UINT32 value = simple_strtol(arg, 0, 16);
-
-		pAd->LatchRfRegs.R3 = value;
-		RtmpRfIoWrite(pAd);
-	}
-	return TRUE;
-}
-
-INT Set_ATE_Write_RF4_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-#ifdef RT30xx
-//2008/07/10:KH add to support 3070 ATE<--
-	if(IS_RT30xx(pAd))
-	{
-		printk("Warning!! RT30xx Don't Support\n");
-		return FALSE;
-
-	}
-	else
-//2008/07/10:KH add to support 3070 ATE-->
-#endif // RT30xx //
-	{
-		UINT32 value = simple_strtol(arg, 0, 16);
-
-		pAd->LatchRfRegs.R4 = value;
-		RtmpRfIoWrite(pAd);
-	}
-	return TRUE;
-}
-#ifdef RT30xx
-//2008/07/10:KH add to support 3070 ATE<--
-INT	SET_ATE_3070RF_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	CHAR *this_char;
-	CHAR *value;
-	UINT32 Reg,RFValue;
-	if(IS_RT30xx(pAd))
-	{
-		printk("SET_ATE_3070RF_Proc=%s\n",arg);
-		this_char =arg;
-		if ((value = strchr(this_char, ':')) != NULL)
-			*value++ = 0;
-		Reg= simple_strtol(this_char, 0, 16);
-		RFValue= simple_strtol(value, 0, 16);
-		printk("RF Reg[%d]=%d\n",Reg,RFValue);
-		RT30xxWriteRFRegister(pAd, Reg,RFValue);
-	}
-	else
-		printk("Warning!! Only 3070 Support\n");
-	return TRUE;
-}
-//2008/07/10:KH add to support 3070 ATE-->
-#endif // RT30xx //
-/*
-    ==========================================================================
-    Description:
-        Load and Write EEPROM from a binary file prepared in advance.
-
-        Return:
-        	TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-#ifndef UCOS
-INT Set_ATE_Load_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	BOOLEAN		    ret = FALSE;
-	PUCHAR			src = EEPROM_BIN_FILE_NAME;
-	struct file		*srcf;
-	INT32 			retval, orgfsuid, orgfsgid;
-   	mm_segment_t	orgfs;
-	USHORT 			WriteEEPROM[(EEPROM_SIZE/2)];
-	UINT32			FileLength = 0;
-	UINT32 			value = simple_strtol(arg, 0, 10);
-
-	ATEDBGPRINT(RT_DEBUG_ERROR, ("===> %s (value=%d)\n\n", __FUNCTION__, value));
-
-	if (value > 0)
-	{
-		/* zero the e2p buffer */
-		NdisZeroMemory((PUCHAR)WriteEEPROM, EEPROM_SIZE);
-
-		/* save uid and gid used for filesystem access.
-	    ** set user and group to 0 (root)
-	    */
-		orgfsuid = current->fsuid;
-		orgfsgid = current->fsgid;
-		/* as root */
-		current->fsuid = current->fsgid = 0;
-    	orgfs = get_fs();
-    	set_fs(KERNEL_DS);
-
-		do
-		{
-			/* open the bin file */
-			srcf = filp_open(src, O_RDONLY, 0);
-
-			if (IS_ERR(srcf))
-			{
-				ate_print("%s - Error %ld opening %s\n", __FUNCTION__, -PTR_ERR(srcf), src);
-				break;
-			}
-
-			/* the object must have a read method */
-			if ((srcf->f_op == NULL) || (srcf->f_op->read == NULL))
-			{
-				ate_print("%s - %s does not have a read method\n", __FUNCTION__, src);
-				break;
-			}
-
-			/* read the firmware from the file *.bin */
-			FileLength = srcf->f_op->read(srcf,
-										  (PUCHAR)WriteEEPROM,
-										  EEPROM_SIZE,
-										  &srcf->f_pos);
-
-			if (FileLength != EEPROM_SIZE)
-			{
-				ate_print("%s: error file length (=%d) in e2p.bin\n",
-					   __FUNCTION__, FileLength);
-				break;
-			}
-			else
-			{
-				/* write the content of .bin file to EEPROM */
-				rt_ee_write_all(pAd, WriteEEPROM);
-				ret = TRUE;
-			}
-			break;
-		} while(TRUE);
-
-		/* close firmware file */
-		if (IS_ERR(srcf))
-		{
-				;
-		}
-		else
-		{
-			retval = filp_close(srcf, NULL);
-			if (retval)
-			{
-				ATEDBGPRINT(RT_DEBUG_ERROR, ("--> Error %d closing %s\n", -retval, src));
-
-			}
-		}
-
-		/* restore */
-		set_fs(orgfs);
-		current->fsuid = orgfsuid;
-		current->fsgid = orgfsgid;
-	}
-    ATEDBGPRINT(RT_DEBUG_ERROR, ("<=== %s (ret=%d)\n", __FUNCTION__, ret));
-
-    return ret;
-
-}
-#else
-INT Set_ATE_Load_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	USHORT 			WriteEEPROM[(EEPROM_SIZE/2)];
-	struct iwreq	*wrq = (struct iwreq *)arg;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("===> %s (wrq->u.data.length = %d)\n\n", __FUNCTION__, wrq->u.data.length));
-
-	if (wrq->u.data.length != EEPROM_SIZE)
-	{
-		ate_print("%s: error length (=%d) from host\n",
-			   __FUNCTION__, wrq->u.data.length);
-		return FALSE;
-	}
-	else/* (wrq->u.data.length == EEPROM_SIZE) */
-	{
-		/* zero the e2p buffer */
-		NdisZeroMemory((PUCHAR)WriteEEPROM, EEPROM_SIZE);
-
-		/* fill the local buffer */
-		NdisMoveMemory((PUCHAR)WriteEEPROM, wrq->u.data.pointer, wrq->u.data.length);
-
-		do
-		{
-				/* write the content of .bin file to EEPROM */
-				rt_ee_write_all(pAd, WriteEEPROM);
-
-		} while(FALSE);
-		}
-
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("<=== %s\n", __FUNCTION__));
-
-    return TRUE;
-
-}
-#endif // !UCOS //
-
-INT Set_ATE_Read_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	USHORT buffer[EEPROM_SIZE/2];
-	USHORT *p;
-	int i;
-
-	rt_ee_read_all(pAd, (USHORT *)buffer);
-	p = buffer;
-	for (i = 0; i < (EEPROM_SIZE/2); i++)
-	{
-		ate_print("%4.4x ", *p);
-		if (((i+1) % 16) == 0)
-			ate_print("\n");
-		p++;
-	}
-	return TRUE;
-}
-
-INT	Set_ATE_Show_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ate_print("Mode=%d\n", pAd->ate.Mode);
-	ate_print("TxPower0=%d\n", pAd->ate.TxPower0);
-	ate_print("TxPower1=%d\n", pAd->ate.TxPower1);
-	ate_print("TxAntennaSel=%d\n", pAd->ate.TxAntennaSel);
-	ate_print("RxAntennaSel=%d\n", pAd->ate.RxAntennaSel);
-	ate_print("BBPCurrentBW=%d\n", pAd->ate.TxWI.BW);
-	ate_print("GI=%d\n", pAd->ate.TxWI.ShortGI);
-	ate_print("MCS=%d\n", pAd->ate.TxWI.MCS);
-	ate_print("TxMode=%d\n", pAd->ate.TxWI.PHYMODE);
-	ate_print("Addr1=%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pAd->ate.Addr1[0], pAd->ate.Addr1[1], pAd->ate.Addr1[2], pAd->ate.Addr1[3], pAd->ate.Addr1[4], pAd->ate.Addr1[5]);
-	ate_print("Addr2=%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pAd->ate.Addr2[0], pAd->ate.Addr2[1], pAd->ate.Addr2[2], pAd->ate.Addr2[3], pAd->ate.Addr2[4], pAd->ate.Addr2[5]);
-	ate_print("Addr3=%02x:%02x:%02x:%02x:%02x:%02x\n",
-		pAd->ate.Addr3[0], pAd->ate.Addr3[1], pAd->ate.Addr3[2], pAd->ate.Addr3[3], pAd->ate.Addr3[4], pAd->ate.Addr3[5]);
-	ate_print("Channel=%d\n", pAd->ate.Channel);
-	ate_print("TxLength=%d\n", pAd->ate.TxLength);
-	ate_print("TxCount=%u\n", pAd->ate.TxCount);
-	ate_print("RFFreqOffset=%d\n", pAd->ate.RFFreqOffset);
-	ate_print(KERN_EMERG "Set_ATE_Show_Proc Success\n");
-	return TRUE;
-}
-
-INT	Set_ATE_Help_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ate_print("ATE=ATESTART, ATESTOP, TXCONT, TXCARR, TXFRAME, RXFRAME\n");
-	ate_print("ATEDA\n");
-	ate_print("ATESA\n");
-	ate_print("ATEBSSID\n");
-	ate_print("ATECHANNEL, range:0~14(unless A band !)\n");
-	ate_print("ATETXPOW0, set power level of antenna 1.\n");
-	ate_print("ATETXPOW1, set power level of antenna 2.\n");
-	ate_print("ATETXANT, set TX antenna. 0:all, 1:antenna one, 2:antenna two.\n");
-	ate_print("ATERXANT, set RX antenna.0:all, 1:antenna one, 2:antenna two, 3:antenna three.\n");
-	ate_print("ATETXFREQOFFSET, set frequency offset, range 0~63\n");
-	ate_print("ATETXBW, set BandWidth, 0:20MHz, 1:40MHz.\n");
-	ate_print("ATETXLEN, set Frame length, range 24~%d\n", (MAX_FRAME_SIZE - 34/* == 2312 */));
-	ate_print("ATETXCNT, set how many frame going to transmit.\n");
-	ate_print("ATETXMCS, set MCS, reference to rate table.\n");
-	ate_print("ATETXMODE, set Mode 0:CCK, 1:OFDM, 2:HT-Mix, 3:GreenField, reference to rate table.\n");
-	ate_print("ATETXGI, set GI interval, 0:Long, 1:Short\n");
-	ate_print("ATERXFER, 0:disable Rx Frame error rate. 1:enable Rx Frame error rate.\n");
-	ate_print("ATERRF, show all RF registers.\n");
-	ate_print("ATEWRF1, set RF1 register.\n");
-	ate_print("ATEWRF2, set RF2 register.\n");
-	ate_print("ATEWRF3, set RF3 register.\n");
-	ate_print("ATEWRF4, set RF4 register.\n");
-	ate_print("ATELDE2P, load EEPROM from .bin file.\n");
-	ate_print("ATERE2P, display all EEPROM content.\n");
-	ate_print("ATESHOW, display all parameters of ATE.\n");
-	ate_print("ATEHELP, online help.\n");
-
-	return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	AsicSwitchChannel() dedicated for ATE.
-
-    ==========================================================================
-*/
-VOID ATEAsicSwitchChannel(
-    IN PRTMP_ADAPTER pAd)
-{
-	UINT32 R2 = 0, R3 = DEFAULT_RF_TX_POWER, R4 = 0, Value = 0;
-	CHAR TxPwer = 0, TxPwer2 = 0;
-	UCHAR index, BbpValue = 0, R66 = 0x30;
-	RTMP_RF_REGS *RFRegTable;
-	UCHAR Channel;
-
-#ifdef RALINK_28xx_QA
-	if ((pAd->ate.bQATxStart == TRUE) || (pAd->ate.bQARxStart == TRUE))
-	{
-		if (pAd->ate.Channel != pAd->LatchRfRegs.Channel)
-		{
-			pAd->ate.Channel = pAd->LatchRfRegs.Channel;
-		}
-		return;
-	}
-	else
-#endif // RALINK_28xx_QA //
-	Channel = pAd->ate.Channel;
-
-	// Select antenna
-	AsicAntennaSelect(pAd, Channel);
-
-	// fill Tx power value
-	TxPwer = pAd->ate.TxPower0;
-	TxPwer2 = pAd->ate.TxPower1;
-#ifdef RT30xx
-//2008/07/10:KH add to support 3070 ATE<--
-
-	// The RF programming sequence is difference between 3xxx and 2xxx
-	// The 3070 is 1T1R. Therefore, we don't need to set the number of Tx/Rx path and the only job is to set the parameters of channels.
-	if (IS_RT30xx(pAd) && ((pAd->RfIcType == RFIC_3020) ||
-(pAd->RfIcType == RFIC_3021) || (pAd->RfIcType == RFIC_3022) ||
-(pAd->RfIcType == RFIC_2020)))
-	{
-		/* modify by WY for Read RF Reg. error */
-		UCHAR RFValue;
-
-		for (index = 0; index < NUM_OF_3020_CHNL; index++)
-		{
-			if (Channel == FreqItems3020[index].Channel)
-			{
-				// Programming channel parameters
-				RT30xxWriteRFRegister(pAd, RF_R02, FreqItems3020[index].N);
-				RT30xxWriteRFRegister(pAd, RF_R03, FreqItems3020[index].K);
-
-				RT30xxReadRFRegister(pAd, RF_R06, (PUCHAR)&RFValue);
-				RFValue = (RFValue & 0xFC) | FreqItems3020[index].R;
-				RT30xxWriteRFRegister(pAd, RF_R06, (UCHAR)RFValue);
-
-				// Set Tx Power
-				RT30xxReadRFRegister(pAd, RF_R12, (PUCHAR)&RFValue);
-				RFValue = (RFValue & 0xE0) | TxPwer;
-				RT30xxWriteRFRegister(pAd, RF_R12, (UCHAR)RFValue);
-
-				// Set RF offset
-				RT30xxReadRFRegister(pAd, RF_R23, (PUCHAR)&RFValue);
-				//2008/08/06: KH modified "pAd->RFFreqOffset" to "pAd->ate.RFFreqOffset"
-				RFValue = (RFValue & 0x80) | pAd->ate.RFFreqOffset;
-				RT30xxWriteRFRegister(pAd, RF_R23, (UCHAR)RFValue);
-
-				// Set BW
-				if (pAd->ate.TxWI.BW == BW_40)
-				{
-					RFValue = pAd->Mlme.CaliBW40RfR24;
-					//DISABLE_11N_CHECK(pAd);
-				}
-				else
-				{
-					RFValue = pAd->Mlme.CaliBW20RfR24;
-				}
-				RT30xxWriteRFRegister(pAd, RF_R24, (UCHAR)RFValue);
-
-				// Enable RF tuning
-				RT30xxReadRFRegister(pAd, RF_R07, (PUCHAR)&RFValue);
-				RFValue = RFValue | 0x1;
-				RT30xxWriteRFRegister(pAd, RF_R07, (UCHAR)RFValue);
-
-				// latch channel for future usage.
-				pAd->LatchRfRegs.Channel = Channel;
-
-				break;
-			}
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%d, Pwr1=%d, %dT), N=0x%02X, K=0x%02X, R=0x%02X\n",
-			Channel,
-			pAd->RfIcType,
-			TxPwer,
-			TxPwer2,
-			pAd->Antenna.field.TxPath,
-			FreqItems3020[index].N,
-			FreqItems3020[index].K,
-			FreqItems3020[index].R));
-	}
-	else
-//2008/07/10:KH add to support 3070 ATE-->
-#endif // RT30xx //
-{
-	RFRegTable = RF2850RegTable;
-
-	switch (pAd->RfIcType)
-	{
-		/* But only 2850 and 2750 support 5.5GHz band... */
-		case RFIC_2820:
-		case RFIC_2850:
-		case RFIC_2720:
-		case RFIC_2750:
-
-			for (index = 0; index < NUM_OF_2850_CHNL; index++)
-			{
-				if (Channel == RFRegTable[index].Channel)
-				{
-					R2 = RFRegTable[index].R2;
-					if (pAd->Antenna.field.TxPath == 1)
-					{
-						R2 |= 0x4000;	// If TXpath is 1, bit 14 = 1;
-					}
-
-					if (pAd->Antenna.field.RxPath == 2)
-					{
-						switch (pAd->ate.RxAntennaSel)
-						{
-							case 1:
-								R2 |= 0x20040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x00;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							case 2:
-								R2 |= 0x10040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x01;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							default:
-								R2 |= 0x40;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								/* Only enable two Antenna to receive. */
-								BbpValue |= 0x08;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-						}
-					}
-					else if (pAd->Antenna.field.RxPath == 1)
-					{
-						R2 |= 0x20040;	// write 1 to off RxPath
-					}
-
-					if (pAd->Antenna.field.TxPath == 2)
-					{
-						if (pAd->ate.TxAntennaSel == 1)
-						{
-							R2 |= 0x4000;	// If TX Antenna select is 1 , bit 14 = 1; Disable Ant 2
-							ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
-							BbpValue &= 0xE7;		//11100111B
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
-						}
-						else if (pAd->ate.TxAntennaSel == 2)
-						{
-							R2 |= 0x8000;	// If TX Antenna select is 2 , bit 15 = 1; Disable Ant 1
-							ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
-							BbpValue &= 0xE7;
-							BbpValue |= 0x08;
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
-						}
-						else
-						{
-							ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &BbpValue);
-							BbpValue &= 0xE7;
-							BbpValue |= 0x10;
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, BbpValue);
-						}
-					}
-					if (pAd->Antenna.field.RxPath == 3)
-					{
-						switch (pAd->ate.RxAntennaSel)
-						{
-							case 1:
-								R2 |= 0x20040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x00;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							case 2:
-								R2 |= 0x10040;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x01;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							case 3:
-								R2 |= 0x30000;
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x02;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-							default:
-								ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &BbpValue);
-								BbpValue &= 0xE4;
-								BbpValue |= 0x10;
-								ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, BbpValue);
-								break;
-						}
-					}
-
-					if (Channel > 14)
-					{
-						// initialize R3, R4
-						R3 = (RFRegTable[index].R3 & 0xffffc1ff);
-						R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->ate.RFFreqOffset << 15);
-
-                        // According the Rory's suggestion to solve the middle range issue.
-						// 5.5G band power range: 0xF9~0X0F, TX0 Reg3 bit9/TX1 Reg4 bit6="0" means the TX power reduce 7dB
-						// R3
-						if ((TxPwer >= -7) && (TxPwer < 0))
-						{
-							TxPwer = (7+TxPwer);
-							TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
-							R3 |= (TxPwer << 10);
-							ATEDBGPRINT(RT_DEBUG_TRACE, ("ATEAsicSwitchChannel: TxPwer=%d \n", TxPwer));
-						}
-						else
-						{
-							TxPwer = (TxPwer > 0xF) ? (0xF) : (TxPwer);
-							R3 |= (TxPwer << 10) | (1 << 9);
-						}
-
-						// R4
-						if ((TxPwer2 >= -7) && (TxPwer2 < 0))
-						{
-							TxPwer2 = (7+TxPwer2);
-							TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
-							R4 |= (TxPwer2 << 7);
-							ATEDBGPRINT(RT_DEBUG_TRACE, ("ATEAsicSwitchChannel: TxPwer2=%d \n", TxPwer2));
-						}
-						else
-						{
-							TxPwer2 = (TxPwer2 > 0xF) ? (0xF) : (TxPwer2);
-							R4 |= (TxPwer2 << 7) | (1 << 6);
-						}
-					}
-					else
-					{
-						R3 = (RFRegTable[index].R3 & 0xffffc1ff) | (TxPwer << 9); // set TX power0
-						R4 = (RFRegTable[index].R4 & (~0x001f87c0)) | (pAd->ate.RFFreqOffset << 15) | (TxPwer2 <<6);// Set freq offset & TxPwr1
-					}
-
-					// Based on BBP current mode before changing RF channel.
-					if (pAd->ate.TxWI.BW == BW_40)
-					{
-						R4 |=0x200000;
-					}
-
-					// Update variables
-					pAd->LatchRfRegs.Channel = Channel;
-					pAd->LatchRfRegs.R1 = RFRegTable[index].R1;
-					pAd->LatchRfRegs.R2 = R2;
-					pAd->LatchRfRegs.R3 = R3;
-					pAd->LatchRfRegs.R4 = R4;
-
-					RtmpRfIoWrite(pAd);
-
-					break;
-				}
-			}
-			break;
-
-		default:
-			break;
-	}
-}
-	// Change BBP setting during switch from a->g, g->a
-	if (Channel <= 14)
-	{
-	    ULONG	TxPinCfg = 0x00050F0A;// 2007.10.09 by Brian : 0x0005050A ==> 0x00050F0A
-
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
-
-		/* For 1T/2R chip only... */
-	    if (pAd->NicConfig2.field.ExternalLNAForG)
-	    {
-	        ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x62);
-	    }
-	    else
-	    {
-	        ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0x84);
-	    }
-
-        // According the Rory's suggestion to solve the middle range issue.
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R86, &BbpValue);
-		ASSERT((BbpValue == 0x00));
-		if ((BbpValue != 0x00))
-		{
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0x00);
-		}
-
-		// 5.5GHz band selection PIN, bit1 and bit2 are complement
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		Value &= (~0x6);
-		Value |= (0x04);
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-
-        // Turn off unused PA or LNA when only 1T or 1R.
-		if (pAd->Antenna.field.TxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFFFF3;
-		}
-		if (pAd->Antenna.field.RxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFF3FF;
-		}
-
-		RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
-	}
-	else
-	{
-	    ULONG	TxPinCfg = 0x00050F05;//2007.10.09 by Brian : 0x00050505 ==> 0x00050F05
-
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R62, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R63, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R64, (0x37 - GET_LNA_GAIN(pAd)));
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R82, 0xF2);
-
-        // According the Rory's suggestion to solve the middle range issue.
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R86, &BbpValue);
-		ASSERT((BbpValue == 0x00));
-		if ((BbpValue != 0x00))
-		{
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R86, 0x00);
-		}
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R91, &BbpValue);
-		ASSERT((BbpValue == 0x04));
-
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R92, &BbpValue);
-		ASSERT((BbpValue == 0x00));
-
-		// 5.5GHz band selection PIN, bit1 and bit2 are complement
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Value);
-		Value &= (~0x6);
-		Value |= (0x02);
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Value);
-
-        // Turn off unused PA or LNA when only 1T or 1R.
-		if (pAd->Antenna.field.TxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFFFF3;
-	    }
-		if (pAd->Antenna.field.RxPath == 1)
-		{
-			TxPinCfg &= 0xFFFFF3FF;
-		}
-
-		RTMP_IO_WRITE32(pAd, TX_PIN_CFG, TxPinCfg);
-	}
-
-    // R66 should be set according to Channel and use 20MHz when scanning
-	if (Channel <= 14)
-	{
-		// BG band
-		R66 = 0x2E + GET_LNA_GAIN(pAd);
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-	}
-	else
-	{
-		// 5.5 GHz band
-		if (pAd->ate.TxWI.BW == BW_20)
-		{
-			R66 = (UCHAR)(0x32 + (GET_LNA_GAIN(pAd)*5)/3);
-    		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-		}
-		else
-		{
-			R66 = (UCHAR)(0x3A + (GET_LNA_GAIN(pAd)*5)/3);
-			ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, R66);
-		}
-	}
-
-	//
-	// On 11A, We should delay and wait RF/BBP to be stable
-	// and the appropriate time should be 1000 micro seconds
-	// 2005/06/05 - On 11G, We also need this delay time. Otherwise it's difficult to pass the WHQL.
-	//
-	RTMPusecDelay(1000);
-
-	if (Channel > 14)
-	{
-		// When 5.5GHz band the LSB of TxPwr will be used to reduced 7dB or not.
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, %dT) to , R1=0x%08lx, R2=0x%08lx, R3=0x%08lx, R4=0x%08lx\n",
-								  Channel,
-								  pAd->RfIcType,
-								  pAd->Antenna.field.TxPath,
-								  pAd->LatchRfRegs.R1,
-								  pAd->LatchRfRegs.R2,
-								  pAd->LatchRfRegs.R3,
-								  pAd->LatchRfRegs.R4));
-	}
-	else
-	{
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("SwitchChannel#%d(RF=%d, Pwr0=%u, Pwr1=%u, %dT) to , R1=0x%08lx, R2=0x%08lx, R3=0x%08lx, R4=0x%08lx\n",
-								  Channel,
-								  pAd->RfIcType,
-								  (R3 & 0x00003e00) >> 9,
-								  (R4 & 0x000007c0) >> 6,
-								  pAd->Antenna.field.TxPath,
-								  pAd->LatchRfRegs.R1,
-								  pAd->LatchRfRegs.R2,
-								  pAd->LatchRfRegs.R3,
-								  pAd->LatchRfRegs.R4));
-    }
-}
-
-//
-// In fact, no one will call this routine so far !
-//
-/*
-	==========================================================================
-	Description:
-		Gives CCK TX rate 2 more dB TX power.
-		This routine works only in ATE mode.
-
-		calculate desired Tx power in RF R3.Tx0~5,	should consider -
-		0. if current radio is a noisy environment (pAd->DrsCounters.fNoisyEnvironment)
-		1. TxPowerPercentage
-		2. auto calibration based on TSSI feedback
-		3. extra 2 db for CCK
-		4. -10 db upon very-short distance (AvgRSSI >= -40db) to AP
-
-	NOTE: Since this routine requires the value of (pAd->DrsCounters.fNoisyEnvironment),
-		it should be called AFTER MlmeDynamicTxRateSwitching()
-	==========================================================================
- */
-VOID ATEAsicAdjustTxPower(
-	IN PRTMP_ADAPTER pAd)
-{
-	INT			i, j;
-	CHAR		DeltaPwr = 0;
-	BOOLEAN		bAutoTxAgc = FALSE;
-	UCHAR		TssiRef, *pTssiMinusBoundary, *pTssiPlusBoundary, TxAgcStep;
-	UCHAR		BbpR49 = 0, idx;
-	PCHAR		pTxAgcCompensate;
-	ULONG		TxPwr[5];
-	CHAR		Value;
-
-	/* no one calls this procedure so far */
-	if (pAd->ate.TxWI.BW == BW_40)
-	{
-		if (pAd->ate.Channel > 14)
-		{
-			TxPwr[0] = pAd->Tx40MPwrCfgABand[0];
-			TxPwr[1] = pAd->Tx40MPwrCfgABand[1];
-			TxPwr[2] = pAd->Tx40MPwrCfgABand[2];
-			TxPwr[3] = pAd->Tx40MPwrCfgABand[3];
-			TxPwr[4] = pAd->Tx40MPwrCfgABand[4];
-		}
-		else
-		{
-			TxPwr[0] = pAd->Tx40MPwrCfgGBand[0];
-			TxPwr[1] = pAd->Tx40MPwrCfgGBand[1];
-			TxPwr[2] = pAd->Tx40MPwrCfgGBand[2];
-			TxPwr[3] = pAd->Tx40MPwrCfgGBand[3];
-			TxPwr[4] = pAd->Tx40MPwrCfgGBand[4];
-		}
-	}
-	else
-	{
-		if (pAd->ate.Channel > 14)
-		{
-			TxPwr[0] = pAd->Tx20MPwrCfgABand[0];
-			TxPwr[1] = pAd->Tx20MPwrCfgABand[1];
-			TxPwr[2] = pAd->Tx20MPwrCfgABand[2];
-			TxPwr[3] = pAd->Tx20MPwrCfgABand[3];
-			TxPwr[4] = pAd->Tx20MPwrCfgABand[4];
-		}
-		else
-		{
-			TxPwr[0] = pAd->Tx20MPwrCfgGBand[0];
-			TxPwr[1] = pAd->Tx20MPwrCfgGBand[1];
-			TxPwr[2] = pAd->Tx20MPwrCfgGBand[2];
-			TxPwr[3] = pAd->Tx20MPwrCfgGBand[3];
-			TxPwr[4] = pAd->Tx20MPwrCfgGBand[4];
-		}
-	}
-
-	// TX power compensation for temperature variation based on TSSI.
-	// Do it per 4 seconds.
-	if (pAd->Mlme.OneSecPeriodicRound % 4 == 0)
-	{
-		if (pAd->ate.Channel <= 14)
-		{
-			/* bg channel */
-			bAutoTxAgc         = pAd->bAutoTxAgcG;
-			TssiRef            = pAd->TssiRefG;
-			pTssiMinusBoundary = &pAd->TssiMinusBoundaryG[0];
-			pTssiPlusBoundary  = &pAd->TssiPlusBoundaryG[0];
-			TxAgcStep          = pAd->TxAgcStepG;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateG;
-		}
-		else
-		{
-			/* a channel */
-			bAutoTxAgc         = pAd->bAutoTxAgcA;
-			TssiRef            = pAd->TssiRefA;
-			pTssiMinusBoundary = &pAd->TssiMinusBoundaryA[0];
-			pTssiPlusBoundary  = &pAd->TssiPlusBoundaryA[0];
-			TxAgcStep          = pAd->TxAgcStepA;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateA;
-		}
-
-		if (bAutoTxAgc)
-		{
-			/* BbpR49 is unsigned char */
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R49, &BbpR49);
-
-			/* (p) TssiPlusBoundaryG[0] = 0 = (m) TssiMinusBoundaryG[0] */
-			/* compensate: +4     +3   +2   +1    0   -1   -2   -3   -4 * steps */
-			/* step value is defined in pAd->TxAgcStepG for tx power value */
-
-			/* [4]+1+[4]   p4     p3   p2   p1   o1   m1   m2   m3   m4 */
-			/* ex:         0x00 0x15 0x25 0x45 0x88 0xA0 0xB5 0xD0 0xF0
-			   above value are examined in mass factory production */
-			/*             [4]    [3]  [2]  [1]  [0]  [1]  [2]  [3]  [4] */
-
-			/* plus is 0x10 ~ 0x40, minus is 0x60 ~ 0x90 */
-			/* if value is between p1 ~ o1 or o1 ~ s1, no need to adjust tx power */
-			/* if value is 0x65, tx power will be -= TxAgcStep*(2-1) */
-
-			if (BbpR49 > pTssiMinusBoundary[1])
-			{
-				// Reading is larger than the reference value.
-				// Check for how large we need to decrease the Tx power.
-				for (idx = 1; idx < 5; idx++)
-				{
-					if (BbpR49 <= pTssiMinusBoundary[idx])  // Found the range
-						break;
-				}
-				// The index is the step we should decrease, idx = 0 means there is nothing to compensate
-//				if (R3 > (ULONG) (TxAgcStep * (idx-1)))
-					*pTxAgcCompensate = -(TxAgcStep * (idx-1));
-//				else
-//					*pTxAgcCompensate = -((UCHAR)R3);
-
-				DeltaPwr += (*pTxAgcCompensate);
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("-- Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = -%d\n",
-					BbpR49, TssiRef, TxAgcStep, idx-1));
-			}
-			else if (BbpR49 < pTssiPlusBoundary[1])
-			{
-				// Reading is smaller than the reference value
-				// check for how large we need to increase the Tx power
-				for (idx = 1; idx < 5; idx++)
-				{
-					if (BbpR49 >= pTssiPlusBoundary[idx])   // Found the range
-						break;
-				}
-				// The index is the step we should increase, idx = 0 means there is nothing to compensate
-				*pTxAgcCompensate = TxAgcStep * (idx-1);
-				DeltaPwr += (*pTxAgcCompensate);
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("++ Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
-					BbpR49, TssiRef, TxAgcStep, idx-1));
-			}
-			else
-			{
-				*pTxAgcCompensate = 0;
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("   Tx Power, BBP R1=%x, TssiRef=%x, TxAgcStep=%x, step = +%d\n",
-					BbpR49, TssiRef, TxAgcStep, 0));
-			}
-		}
-	}
-	else
-	{
-		if (pAd->ate.Channel <= 14)
-		{
-			bAutoTxAgc         = pAd->bAutoTxAgcG;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateG;
-		}
-		else
-		{
-			bAutoTxAgc         = pAd->bAutoTxAgcA;
-			pTxAgcCompensate   = &pAd->TxAgcCompensateA;
-		}
-
-		if (bAutoTxAgc)
-			DeltaPwr += (*pTxAgcCompensate);
-	}
-
-	/* calculate delta power based on the percentage specified from UI */
-	// E2PROM setting is calibrated for maximum TX power (i.e. 100%)
-	// We lower TX power here according to the percentage specified from UI
-	if (pAd->CommonCfg.TxPowerPercentage == 0xffffffff)       // AUTO TX POWER control
-		;
-	else if (pAd->CommonCfg.TxPowerPercentage > 90)  // 91 ~ 100% & AUTO, treat as 100% in terms of mW
-		;
-	else if (pAd->CommonCfg.TxPowerPercentage > 60)  // 61 ~ 90%, treat as 75% in terms of mW
-	{
-		DeltaPwr -= 1;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 30)  // 31 ~ 60%, treat as 50% in terms of mW
-	{
-		DeltaPwr -= 3;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 15)  // 16 ~ 30%, treat as 25% in terms of mW
-	{
-		DeltaPwr -= 6;
-	}
-	else if (pAd->CommonCfg.TxPowerPercentage > 9)   // 10 ~ 15%, treat as 12.5% in terms of mW
-	{
-		DeltaPwr -= 9;
-	}
-	else                                           // 0 ~ 9 %, treat as MIN(~3%) in terms of mW
-	{
-		DeltaPwr -= 12;
-	}
-
-	/* reset different new tx power for different TX rate */
-	for(i=0; i<5; i++)
-	{
-		if (TxPwr[i] != 0xffffffff)
-		{
-			for (j=0; j<8; j++)
-			{
-				Value = (CHAR)((TxPwr[i] >> j*4) & 0x0F); /* 0 ~ 15 */
-
-				if ((Value + DeltaPwr) < 0)
-				{
-					Value = 0; /* min */
-				}
-				else if ((Value + DeltaPwr) > 0xF)
-				{
-					Value = 0xF; /* max */
-				}
-				else
-				{
-					Value += DeltaPwr; /* temperature compensation */
-				}
-
-				/* fill new value to CSR offset */
-				TxPwr[i] = (TxPwr[i] & ~(0x0000000F << j*4)) | (Value << j*4);
-			}
-
-			/* write tx power value to CSR */
-			/* TX_PWR_CFG_0 (8 tx rate) for	TX power for OFDM 12M/18M
-											TX power for OFDM 6M/9M
-											TX power for CCK5.5M/11M
-											TX power for CCK1M/2M */
-			/* TX_PWR_CFG_1 ~ TX_PWR_CFG_4 */
-			RTMP_IO_WRITE32(pAd, TX_PWR_CFG_0 + i*4, TxPwr[i]);
-
-
-		}
-	}
-
-}
-
-/*
-	========================================================================
-	Routine Description:
-		Write TxWI for ATE mode.
-
-	Return Value:
-		None
-	========================================================================
-*/
-
-#ifdef RT2870
-static VOID ATEWriteTxWI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXWI_STRUC 	pTxWI,
-	IN	BOOLEAN			FRAG,
-	IN	BOOLEAN			InsTimestamp,
-	IN	BOOLEAN 		AMPDU,
-	IN	BOOLEAN 		Ack,
-	IN	BOOLEAN 		NSeq,		// HW new a sequence.
-	IN	UCHAR			BASize,
-	IN	UCHAR			WCID,
-	IN	ULONG			Length,
-	IN	UCHAR 			PID,
-	IN	UCHAR			MIMOps,
-	IN	UCHAR			Txopmode,
-	IN	BOOLEAN			CfAck,
-	IN	HTTRANSMIT_SETTING	Transmit)
-{
-	//
-	// Always use Long preamble before verifiation short preamble functionality works well.
-	// Todo: remove the following line if short preamble functionality works
-	//
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED);
-	pTxWI->FRAG= FRAG;
-	pTxWI->TS= InsTimestamp;
-	pTxWI->AMPDU = AMPDU;
-
-	pTxWI->MIMOps = PWR_ACTIVE;
-	pTxWI->MpduDensity = 4;
-	pTxWI->ACK = Ack;
-	pTxWI->txop = Txopmode;
-	pTxWI->NSEQ = NSeq;
-	pTxWI->BAWinSize = BASize;
-
-	pTxWI->WirelessCliID = WCID;
-	pTxWI->MPDUtotalByteCount = Length;
-	pTxWI->PacketId = PID;
-
-	pTxWI->BW = Transmit.field.BW;
-	pTxWI->ShortGI = Transmit.field.ShortGI;
-	pTxWI->STBC= Transmit.field.STBC;
-
-	pTxWI->MCS = Transmit.field.MCS;
-	pTxWI->PHYMODE= Transmit.field.MODE;
-
-#ifdef DOT11_N_SUPPORT
-	//
-	// MMPS is 802.11n features. Because TxWI->MCS > 7 must be HT mode,
-	// so need not check if it's HT rate.
-	//
-	if ((MIMOps == MMPS_STATIC) && (pTxWI->MCS > 7))
-		pTxWI->MCS = 7;
-
-	if ((MIMOps == MMPS_DYNAMIC) && (pTxWI->MCS > 7)) // SMPS protect 2 spatial.
-		pTxWI->MIMOps = 1;
-#endif // DOT11_N_SUPPORT //
-
-	pTxWI->CFACK = CfAck;
-
-	return;
-}
-#endif // RT2870 //
-/*
-	========================================================================
-
-	Routine Description:
-		Disable protection for ATE.
-	========================================================================
-*/
-VOID ATEDisableAsicProtect(
-	IN		PRTMP_ADAPTER	pAd)
-{
-	PROT_CFG_STRUC	ProtCfg, ProtCfg4;
-	UINT32 Protect[6];
-	USHORT			offset;
-	UCHAR			i;
-	UINT32 MacReg = 0;
-
-	// Config ASIC RTS threshold register
-	RTMP_IO_READ32(pAd, TX_RTS_CFG, &MacReg);
-	MacReg &= 0xFF0000FF;
-	MacReg |= (pAd->CommonCfg.RtsThreshold << 8);
-	RTMP_IO_WRITE32(pAd, TX_RTS_CFG, MacReg);
-
-	// Initial common protection settings
-	RTMPZeroMemory(Protect, sizeof(Protect));
-	ProtCfg4.word = 0;
-	ProtCfg.word = 0;
-	ProtCfg.field.TxopAllowGF40 = 1;
-	ProtCfg.field.TxopAllowGF20 = 1;
-	ProtCfg.field.TxopAllowMM40 = 1;
-	ProtCfg.field.TxopAllowMM20 = 1;
-	ProtCfg.field.TxopAllowOfdm = 1;
-	ProtCfg.field.TxopAllowCck = 1;
-	ProtCfg.field.RTSThEn = 1;
-	ProtCfg.field.ProtectNav = ASIC_SHORTNAV;
-
-	// Handle legacy(B/G) protection
-	ProtCfg.field.ProtectRate = pAd->CommonCfg.RtsRate;
-	ProtCfg.field.ProtectCtrl = 0;
-	Protect[0] = ProtCfg.word;
-	Protect[1] = ProtCfg.word;
-
-	// NO PROTECT
-	// 1.All STAs in the BSS are 20/40 MHz HT
-	// 2. in ai 20/40MHz BSS
-	// 3. all STAs are 20MHz in a 20MHz BSS
-	// Pure HT. no protection.
-
-	// MM20_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 010111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4004 (OFDM 24M)
-	Protect[2] = 0x01744004;
-
-	// MM40_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 111111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4084 (duplicate OFDM 24M)
-	Protect[3] = 0x03f44084;
-
-	// CF20_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 010111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4004 (OFDM 24M)
-	Protect[4] = 0x01744004;
-
-	// CF40_PROT_CFG
-	//	Reserved (31:27)
-	// 	PROT_TXOP(25:20) -- 111111
-	//	PROT_NAV(19:18)  -- 01 (Short NAV protection)
-	//  PROT_CTRL(17:16) -- 00 (None)
-	// 	PROT_RATE(15:0)  -- 0x4084 (duplicate OFDM 24M)
-	Protect[5] = 0x03f44084;
-
-	pAd->CommonCfg.IOTestParm.bRTSLongProtOn = FALSE;
-
-	offset = CCK_PROT_CFG;
-	for (i = 0;i < 6;i++)
-		RTMP_IO_WRITE32(pAd, offset + i*4, Protect[i]);
-
-}
-
-#ifdef RT2870
-/*
-	========================================================================
-	Routine	Description:
-		Write TxInfo for ATE mode.
-
-	Return Value:
-		None
-	========================================================================
-*/
-static VOID ATEWriteTxInfo(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXINFO_STRUC 	pTxInfo,
-	IN	USHORT		USBDMApktLen,
-	IN	BOOLEAN		bWiv,
-	IN	UCHAR			QueueSel,
-	IN	UCHAR			NextValid,
-	IN	UCHAR			TxBurst)
-{
-	pTxInfo->USBDMATxPktLen = USBDMApktLen;
-	pTxInfo->QSEL = QueueSel;
-
-	if (QueueSel != FIFO_EDCA)
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("=======> QueueSel != FIFO_EDCA<=======\n"));
-
-	pTxInfo->USBDMANextVLD = NextValid;
-	pTxInfo->USBDMATxburst = TxBurst;
-	pTxInfo->WIV = bWiv;
-	pTxInfo->SwUseLastRound = 0;
-	pTxInfo->rsv = 0;
-	pTxInfo->rsv2 = 0;
-
-	return;
-}
-#endif // RT2870 //
-
-/* There are two ways to convert Rssi */
-#if 1
-//
-// The way used with GET_LNA_GAIN().
-//
-CHAR ATEConvertToRssi(
-	IN PRTMP_ADAPTER pAd,
-	IN	CHAR	Rssi,
-	IN  UCHAR   RssiNumber)
-{
-	UCHAR	RssiOffset, LNAGain;
-
-	// Rssi equals to zero should be an invalid value
-	if (Rssi == 0)
-		return -99;
-
-	LNAGain = GET_LNA_GAIN(pAd);
-	if (pAd->LatchRfRegs.Channel > 14)
-	{
-		if (RssiNumber == 0)
-			RssiOffset = pAd->ARssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->ARssiOffset1;
-		else
-			RssiOffset = pAd->ARssiOffset2;
-	}
-	else
-	{
-		if (RssiNumber == 0)
-			RssiOffset = pAd->BGRssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->BGRssiOffset1;
-		else
-			RssiOffset = pAd->BGRssiOffset2;
-	}
-
-	return (-12 - RssiOffset - LNAGain - Rssi);
-}
-#else
-//
-// The way originally used in ATE of rt2860ap.
-//
-CHAR ATEConvertToRssi(
-	IN PRTMP_ADAPTER pAd,
-	IN	CHAR			Rssi,
-	IN  UCHAR   RssiNumber)
-{
-	UCHAR	RssiOffset, LNAGain;
-
-	// Rssi equals to zero should be an invalid value
-	if (Rssi == 0)
-		return -99;
-
-    if (pAd->LatchRfRegs.Channel > 14)
-    {
-        LNAGain = pAd->ALNAGain;
-        if (RssiNumber == 0)
-			RssiOffset = pAd->ARssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->ARssiOffset1;
-		else
-			RssiOffset = pAd->ARssiOffset2;
-    }
-    else
-    {
-        LNAGain = pAd->BLNAGain;
-        if (RssiNumber == 0)
-			RssiOffset = pAd->BGRssiOffset0;
-		else if (RssiNumber == 1)
-			RssiOffset = pAd->BGRssiOffset1;
-		else
-			RssiOffset = pAd->BGRssiOffset2;
-    }
-
-    return (-32 - RssiOffset + LNAGain - Rssi);
-}
-#endif /* end of #if 1 */
-
-/*
-	========================================================================
-
-	Routine Description:
-		Set Japan filter coefficients if needed.
-	Note:
-		This routine should only be called when
-		entering TXFRAME mode or TXCONT mode.
-
-	========================================================================
-*/
-static VOID SetJapanFilter(
-	IN		PRTMP_ADAPTER	pAd)
-{
-	UCHAR			BbpData = 0;
-
-	//
-	// If Channel=14 and Bandwidth=20M and Mode=CCK, set BBP R4 bit5=1
-	// (Japan Tx filter coefficients)when (TXFRAME or TXCONT).
-	//
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BbpData);
-
-    if ((pAd->ate.TxWI.PHYMODE == MODE_CCK) && (pAd->ate.Channel == 14) && (pAd->ate.TxWI.BW == BW_20))
-    {
-        BbpData |= 0x20;    // turn on
-        ATEDBGPRINT(RT_DEBUG_TRACE, ("SetJapanFilter!!!\n"));
-    }
-    else
-    {
-		BbpData &= 0xdf;    // turn off
-		ATEDBGPRINT(RT_DEBUG_TRACE, ("ClearJapanFilter!!!\n"));
-    }
-
-	ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BbpData);
-}
-
-VOID ATESampleRssi(
-	IN PRTMP_ADAPTER	pAd,
-	IN PRXWI_STRUC		pRxWI)
-{
-	/* There are two ways to collect RSSI. */
-#if 1
-	//pAd->LastRxRate = (USHORT)((pRxWI->MCS) + (pRxWI->BW <<7) + (pRxWI->ShortGI <<8)+ (pRxWI->PHYMODE <<14)) ;
-	if (pRxWI->RSSI0 != 0)
-	{
-		pAd->ate.LastRssi0	= ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI0, RSSI_0);
-		pAd->ate.AvgRssi0X8	= (pAd->ate.AvgRssi0X8 - pAd->ate.AvgRssi0) + pAd->ate.LastRssi0;
-		pAd->ate.AvgRssi0  	= pAd->ate.AvgRssi0X8 >> 3;
-	}
-	if (pRxWI->RSSI1 != 0)
-	{
-		pAd->ate.LastRssi1	= ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI1, RSSI_1);
-		pAd->ate.AvgRssi1X8	= (pAd->ate.AvgRssi1X8 - pAd->ate.AvgRssi1) + pAd->ate.LastRssi1;
-		pAd->ate.AvgRssi1	= pAd->ate.AvgRssi1X8 >> 3;
-	}
-	if (pRxWI->RSSI2 != 0)
-	{
-		pAd->ate.LastRssi2	= ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI2, RSSI_2);
-		pAd->ate.AvgRssi2X8	= (pAd->ate.AvgRssi2X8 - pAd->ate.AvgRssi2) + pAd->ate.LastRssi2;
-		pAd->ate.AvgRssi2	= pAd->ate.AvgRssi2X8 >> 3;
-	}
-
-	pAd->ate.LastSNR0 = (CHAR)(pRxWI->SNR0);// CHAR ==> UCHAR ?
-	pAd->ate.LastSNR1 = (CHAR)(pRxWI->SNR1);// CHAR ==> UCHAR ?
-
-	pAd->ate.NumOfAvgRssiSample ++;
-#else
-	pAd->ate.LastSNR0 = (CHAR)(pRxWI->SNR0);
-	pAd->ate.LastSNR1 = (CHAR)(pRxWI->SNR1);
-	pAd->ate.RxCntPerSec++;
-	pAd->ate.LastRssi0 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI0, RSSI_0);
-	pAd->ate.LastRssi1 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI1, RSSI_1);
-	pAd->ate.LastRssi2 = ATEConvertToRssi(pAd, (CHAR) pRxWI->RSSI2, RSSI_2);
-	pAd->ate.AvgRssi0X8 = (pAd->ate.AvgRssi0X8 - pAd->ate.AvgRssi0) + pAd->ate.LastRssi0;
-	pAd->ate.AvgRssi0 = pAd->ate.AvgRssi0X8 >> 3;
-	pAd->ate.AvgRssi1X8 = (pAd->ate.AvgRssi1X8 - pAd->ate.AvgRssi1) + pAd->ate.LastRssi1;
-	pAd->ate.AvgRssi1 = pAd->ate.AvgRssi1X8 >> 3;
-	pAd->ate.AvgRssi2X8 = (pAd->ate.AvgRssi2X8 - pAd->ate.AvgRssi2) + pAd->ate.LastRssi2;
-	pAd->ate.AvgRssi2 = pAd->ate.AvgRssi2X8 >> 3;
-	pAd->ate.NumOfAvgRssiSample ++;
-#endif
-}
-
-#ifdef CONFIG_STA_SUPPORT
-VOID RTMPStationStop(
-    IN  PRTMP_ADAPTER   pAd)
-{
-//	BOOLEAN       Cancelled;
-
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("==> RTMPStationStop\n"));
-
-	// For rx statistics, we need to keep this timer running.
-//	RTMPCancelTimer(&pAd->Mlme.PeriodicTimer,      &Cancelled);
-
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("<== RTMPStationStop\n"));
-}
-
-VOID RTMPStationStart(
-    IN  PRTMP_ADAPTER   pAd)
-{
-    ATEDBGPRINT(RT_DEBUG_TRACE, ("==> RTMPStationStart\n"));
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("<== RTMPStationStart\n"));
-}
-#endif // CONFIG_STA_SUPPORT //
-
-/*
-	==========================================================================
-	Description:
-		Setup Frame format.
-	NOTE:
-		This routine should only be used in ATE mode.
-	==========================================================================
- */
-
-#ifdef RT2870
-/*======================Start of RT2870======================*/
-/*                                                           */
-/*                                                           */
-static INT ATESetUpFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UINT32 TxIdx)
-{
-	UINT j;
-	PTX_CONTEXT	pNullContext;
-	PUCHAR			pDest;
-	HTTRANSMIT_SETTING	TxHTPhyMode;
-	PTXWI_STRUC		pTxWI;
-	PTXINFO_STRUC		pTxInfo;
-	UINT32			TransferBufferLength, OrgBufferLength = 0;
-	UCHAR			padLen = 0;
-#ifdef RALINK_28xx_QA
-	PHEADER_802_11	pHeader80211 = NULL;
-#endif // RALINK_28xx_QA //
-
-	if ((RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) ||
-		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)) ||
-		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) ||
-		(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-	{
-		return -1;
-	}
-
-	/* We always use QID_AC_BE and FIFO_EDCA in ATE mode. */
-
-	pNullContext = &(pAd->NullContext);
-	ASSERT(pNullContext != NULL);
-
-	if (pNullContext->InUse == FALSE)
-	{
-		// Set the in use bit
-		pNullContext->InUse = TRUE;
-		NdisZeroMemory(&(pAd->NullFrame), sizeof(HEADER_802_11));
-
-		// Fill 802.11 header.
-#ifdef RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			pHeader80211 = NdisMoveMemory(&(pAd->NullFrame), pAd->ate.Header, pAd->ate.HLen);
-//			pDest = NdisMoveMemory(&(pAd->NullFrame), pAd->ate.Header, pAd->ate.HLen);
-//			pHeader80211 = (PHEADER_802_11)pDest;
-		}
-		else
-#endif // RALINK_28xx_QA //
-		{
-			// Fill 802.11 header.
-			NdisMoveMemory(&(pAd->NullFrame), TemplateFrame, sizeof(HEADER_802_11));
-		}
-#ifdef RT_BIG_ENDIAN
-		RTMPFrameEndianChange(pAd, (PUCHAR)&(pAd->NullFrame), DIR_READ, FALSE);
-#endif // RT_BIG_ENDIAN //
-
-#ifdef RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			/* modify sequence number.... */
-			if (pAd->ate.TxDoneCount == 0)
-			{
-				pAd->ate.seq = pHeader80211->Sequence;
-			}
-			else
-			{
-				pHeader80211->Sequence = ++pAd->ate.seq;
-			}
-			/* We already got all the addr. fields from QA GUI. */
-		}
-		else
-#endif // RALINK_28xx_QA //
-		{
-			COPY_MAC_ADDR(pAd->NullFrame.Addr1, pAd->ate.Addr1);
-			COPY_MAC_ADDR(pAd->NullFrame.Addr2, pAd->ate.Addr2);
-			COPY_MAC_ADDR(pAd->NullFrame.Addr3, pAd->ate.Addr3);
-		}
-
-		RTMPZeroMemory(&pAd->NullContext.TransferBuffer->field.WirelessPacket[0], TX_BUFFER_NORMSIZE);//???
-		pTxInfo = (PTXINFO_STRUC)&pAd->NullContext.TransferBuffer->field.WirelessPacket[0];
-
-#ifdef RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			// Avoid to exceed the range of WirelessPacket[].
-			ASSERT(pAd->ate.TxInfo.USBDMATxPktLen <= (MAX_FRAME_SIZE - 34/* == 2312 */));
-			NdisMoveMemory(pTxInfo, &(pAd->ate.TxInfo), sizeof(pAd->ate.TxInfo));
-		}
-		else
-#endif // RALINK_28xx_QA //
-		{
-			// Avoid to exceed the range of WirelessPacket[].
-			ASSERT(pAd->ate.TxLength <= (MAX_FRAME_SIZE - 34/* == 2312 */));
-
-			// pTxInfo->USBDMATxPktLen will be updated to include padding later.
-			ATEWriteTxInfo(pAd, pTxInfo, (USHORT)(TXWI_SIZE + pAd->ate.TxLength), TRUE, EpToQueue[MGMTPIPEIDX], FALSE,  FALSE);
-			pTxInfo->QSEL = FIFO_EDCA;
-		}
-
-		pTxWI = (PTXWI_STRUC)&pAd->NullContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE];
-
-		// Fill TxWI.
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			TxHTPhyMode.field.BW = pAd->ate.TxWI.BW;
-			TxHTPhyMode.field.ShortGI = pAd->ate.TxWI.ShortGI;
-			TxHTPhyMode.field.STBC = pAd->ate.TxWI.STBC;
-			TxHTPhyMode.field.MCS = pAd->ate.TxWI.MCS;
-			TxHTPhyMode.field.MODE = pAd->ate.TxWI.PHYMODE;
-			ATEWriteTxWI(pAd, pTxWI, pAd->ate.TxWI.FRAG, pAd->ate.TxWI.TS, pAd->ate.TxWI.AMPDU, pAd->ate.TxWI.ACK, pAd->ate.TxWI.NSEQ,
-				pAd->ate.TxWI.BAWinSize, BSSID_WCID, pAd->ate.TxWI.MPDUtotalByteCount/* include 802.11 header */, pAd->ate.TxWI.PacketId, 0, pAd->ate.TxWI.txop/*IFS_HTTXOP*/, pAd->ate.TxWI.CFACK/*FALSE*/, TxHTPhyMode);
-		}
-		else
-		{
-			TxHTPhyMode.field.BW = pAd->ate.TxWI.BW;
-			TxHTPhyMode.field.ShortGI = pAd->ate.TxWI.ShortGI;
-			TxHTPhyMode.field.STBC = 0;
-			TxHTPhyMode.field.MCS = pAd->ate.TxWI.MCS;
-			TxHTPhyMode.field.MODE = pAd->ate.TxWI.PHYMODE;
-
-			ATEWriteTxWI(pAd, pTxWI,  FALSE, FALSE, FALSE, FALSE/* No ack required. */, FALSE, 0, BSSID_WCID, pAd->ate.TxLength,
-				0, 0, IFS_HTTXOP, FALSE, TxHTPhyMode);// "MMPS_STATIC" instead of "MMPS_DYNAMIC" ???
-		}
-
-		RTMPMoveMemory(&pAd->NullContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE+TXWI_SIZE], &pAd->NullFrame, sizeof(HEADER_802_11));
-
-		pDest = &(pAd->NullContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE+TXWI_SIZE+sizeof(HEADER_802_11)]);
-
-		// Prepare frame payload
-#ifdef RALINK_28xx_QA
-		if (pAd->ate.bQATxStart == TRUE)
-		{
-			// copy pattern
-			if ((pAd->ate.PLen != 0))
-			{
-				for (j = 0; j < pAd->ate.DLen; j+=pAd->ate.PLen)
-				{
-					RTMPMoveMemory(pDest, pAd->ate.Pattern, pAd->ate.PLen);
-					pDest += pAd->ate.PLen;
-				}
-			}
-			TransferBufferLength = TXINFO_SIZE + TXWI_SIZE + pAd->ate.TxWI.MPDUtotalByteCount;
-		}
-		else
-#endif // RALINK_28xx_QA //
-		{
-		    for (j = 0; j < (pAd->ate.TxLength - sizeof(HEADER_802_11)); j++)
-		    {
-				*pDest = 0xA5;
-				pDest += 1;
-		    }
-			TransferBufferLength = TXINFO_SIZE + TXWI_SIZE + pAd->ate.TxLength;
-		}
-
-#if 1
-		OrgBufferLength = TransferBufferLength;
-		TransferBufferLength = (TransferBufferLength + 3) & (~3);
-
-		// Always add 4 extra bytes at every packet.
-		padLen = TransferBufferLength - OrgBufferLength + 4;/* 4 == last packet padding */
-		ASSERT((padLen <= (RTMP_PKT_TAIL_PADDING - 4/* 4 == MaxBulkOutsize alignment padding */)));
-
-		/* Now memzero all extra padding bytes. */
-		NdisZeroMemory(pDest, padLen);
-		pDest += padLen;
-#else
-		if ((TransferBufferLength % 4) == 1)
-		{
-			NdisZeroMemory(pDest, 7);
-			pDest += 7;
-			TransferBufferLength  += 3;
-		}
-		else if ((TransferBufferLength % 4) == 2)
-		{
-			NdisZeroMemory(pDest, 6);
-			pDest += 6;
-			TransferBufferLength  += 2;
-		}
-		else if ((TransferBufferLength % 4) == 3)
-		{
-			NdisZeroMemory(pDest, 5);
-			pDest += 5;
-			TransferBufferLength  += 1;
-		}
-#endif // 1 //
-
-		// Update pTxInfo->USBDMATxPktLen to include padding.
-		pTxInfo->USBDMATxPktLen = TransferBufferLength - TXINFO_SIZE;
-
-		TransferBufferLength += 4;
-
-		// If TransferBufferLength is multiple of 64, add extra 4 bytes again.
-		if ((TransferBufferLength % pAd->BulkOutMaxPacketSize) == 0)
-		{
-			NdisZeroMemory(pDest, 4);
-			TransferBufferLength += 4;
-		}
-
-		// Fill out frame length information for global Bulk out arbitor
-		pAd->NullContext.BulkOutSize = TransferBufferLength;
-	}
-#ifdef RT_BIG_ENDIAN
-	RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-	RTMPFrameEndianChange(pAd, (((PUCHAR)pTxInfo)+TXWI_SIZE+TXINFO_SIZE), DIR_WRITE, FALSE);
-    RTMPDescriptorEndianChange((PUCHAR)pTxInfo, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-	return 0;
-}
-
-VOID ATE_RTUSBBulkOutDataPacketComplete(purbb_t pUrb, struct pt_regs *pt_regs)
-{
-	PRTMP_ADAPTER		pAd;
-	PTX_CONTEXT		    pNullContext;
-	UCHAR				BulkOutPipeId;
-	NTSTATUS			Status;
-	unsigned long		IrqFlags;
-	ULONG			    OldValue;
-
-	pNullContext = (PTX_CONTEXT)pUrb->context;
-	pAd = pNullContext->pAd;
-
-
-	// Reset Null frame context flags
-	pNullContext->IRPPending = FALSE;
-	pNullContext->InUse = FALSE;
-	Status = pUrb->status;
-
-	// Store BulkOut PipeId
-	BulkOutPipeId = pNullContext->BulkOutPipeId;
-	pAd->BulkOutDataOneSecCount++;
-
-	if (Status == USB_ST_NOERROR)
-	{
-#ifdef RALINK_28xx_QA
-		if ((ATE_ON(pAd)) && (pAd->ate.bQATxStart == TRUE))
-		{
-			if (pAd->ate.QID == BulkOutPipeId)
-			{
-				// Let Rx can have a chance to break in during Tx process,
-				// especially for loopback mode in QA ATE.
-				// To trade off between tx performance and loopback mode integrity.
-				/* Q   : Now Rx is handled by tasklet, do we still need this delay ? */
-				/* Ans : Even tasklet is used, Rx/Tx < 1 if we do not delay for a while right here. */
-				RTMPusecDelay(500);
-				pAd->ate.TxDoneCount++;
-				pAd->RalinkCounters.KickTxCount++;
-				ASSERT(pAd->ate.QID == 0);
-				pAd->ate.TxAc0++;
-			}
-		}
-#endif // RALINK_28xx_QA //
-		pAd->BulkOutComplete++;
-
-		pAd->Counters8023.GoodTransmits++;
-
-		/* Don't worry about the queue is empty or not. This function will check itself. */
-		RTMPDeQueuePacket(pAd, TRUE, BulkOutPipeId, MAX_TX_PROCESS);
-
-		/* In 28xx, SendTxWaitQueue ==> TxSwQueue  */
-/*
-		if (pAd->SendTxWaitQueue[BulkOutPipeId].Number > 0)
-		{
-			RTMPDeQueuePacket(pAd, BulkOutPipeId);
-		}
-*/
-	}
-	else	// STATUS_OTHER
-	{
-		pAd->BulkOutCompleteOther++;
-
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("BulkOutDataPacket Failed STATUS_OTHER = 0x%x . \n", Status));
-		ATEDBGPRINT(RT_DEBUG_ERROR, (">>BulkOutReq=0x%lx, BulkOutComplete=0x%lx\n", pAd->BulkOutReq, pAd->BulkOutComplete));
-
-		if ((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET)))
-		{
-			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
-			/* In 28xx, RT_OID_USB_RESET_BULK_OUT ==> CMDTHREAD_RESET_BULK_OUT */
-			RTUSBEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_OUT, NULL, 0);
-			// Check
-			BULK_OUT_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-			pAd->BulkOutPending[BulkOutPipeId] = FALSE;
-			pAd->bulkResetPipeid = BulkOutPipeId;
-			BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-			return;
-		}
-	}
-
-
-
-	if (atomic_read(&pAd->BulkOutRemained) > 0)
-	{
-		atomic_dec(&pAd->BulkOutRemained);
-	}
-
-	// 1st - Transmit Success
-	OldValue = pAd->WlanCounters.TransmittedFragmentCount.u.LowPart;
-	pAd->WlanCounters.TransmittedFragmentCount.u.LowPart++;
-
-	if (pAd->WlanCounters.TransmittedFragmentCount.u.LowPart < OldValue)
-	{
-		pAd->WlanCounters.TransmittedFragmentCount.u.HighPart++;
-	}
-
-	if(((pAd->ContinBulkOut == TRUE ) ||(atomic_read(&pAd->BulkOutRemained) > 0)) && (pAd->ate.Mode & ATE_TXFRAME))
-	{
-		RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-	}
-	else
-	{
-		RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-#ifdef RALINK_28xx_QA
-		pAd->ate.TxStatus = 0;
-#endif // RALINK_28xx_QA //
-	}
-
-	BULK_OUT_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-	pAd->BulkOutPending[BulkOutPipeId] = FALSE;
-	BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-
-	// Always call Bulk routine, even reset bulk.
-	// The protection of rest bulk should be in BulkOut routine.
-	RTUSBKickBulkOut(pAd);
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	ATE_RTUSBBulkOutDataPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BulkOutPipeId)
-{
-	PTX_CONTEXT		pNullContext = &(pAd->NullContext);
-	PURB			pUrb;
-	int				ret = 0;
-	unsigned long	IrqFlags;
-
-
-	ASSERT(BulkOutPipeId == 0);
-
-	/* Build up the frame first. */
-//	ATESetUpFrame(pAd, 0);
-
-	BULK_OUT_LOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-
-	if (pAd->BulkOutPending[BulkOutPipeId] == TRUE)
-	{
-		BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-		return;
-	}
-
-	pAd->BulkOutPending[BulkOutPipeId] = TRUE;
-	BULK_OUT_UNLOCK(&pAd->BulkOutLock[BulkOutPipeId], IrqFlags);
-
-	// Increase Total transmit byte counter
-	pAd->RalinkCounters.OneSecTransmittedByteCount +=  pNullContext->BulkOutSize;
-	pAd->RalinkCounters.TransmittedByteCount +=  pNullContext->BulkOutSize;
-
-	// Clear ATE frame bulk out flag
-	RTUSB_CLEAR_BULK_FLAG(pAd, fRTUSB_BULK_OUT_DATA_ATE);
-
-	// Init Tx context descriptor
-	pNullContext->IRPPending = TRUE;
-	RTUSBInitTxDesc(pAd, pNullContext, BulkOutPipeId, (usb_complete_t)ATE_RTUSBBulkOutDataPacketComplete);
-	pUrb = pNullContext->pUrb;
-
-	if((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
-	{
-		ATEDBGPRINT(RT_DEBUG_ERROR, ("ATE_RTUSBBulkOutDataPacket: Submit Tx URB failed %d\n", ret));
-		return;
-	}
-
-	pAd->BulkOutReq++;
-	return;
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	ATE_RTUSBCancelPendingBulkInIRP(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	PRX_CONTEXT		pRxContext;
-	UINT			i;
-
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("--->ATE_RTUSBCancelPendingBulkInIRP\n"));
-#if 1
-	for ( i = 0; i < (RX_RING_SIZE); i++)
-	{
-		pRxContext = &(pAd->RxContext[i]);
-		if(pRxContext->IRPPending == TRUE)
-		{
-			RTUSB_UNLINK_URB(pRxContext->pUrb);
-			pRxContext->IRPPending = FALSE;
-			pRxContext->InUse = FALSE;
-			//NdisInterlockedDecrement(&pAd->PendingRx);
-			//pAd->PendingRx--;
-		}
-	}
-#else
-	for ( i = 0; i < (RX_RING_SIZE); i++)
-	{
-		pRxContext = &(pAd->RxContext[i]);
-		if(atomic_read(&pRxContext->IrpLock) == IRPLOCK_CANCELABLE)
-		{
-			RTUSB_UNLINK_URB(pRxContext->pUrb);
-		}
-		InterlockedExchange(&pRxContext->IrpLock, IRPLOCK_CANCE_START);
-	}
-#endif // 1 //
-	ATEDBGPRINT(RT_DEBUG_TRACE, ("<---ATE_RTUSBCancelPendingBulkInIRP\n"));
-	return;
-}
-#endif // RT2870 //
-
-VOID rt_ee_read_all(PRTMP_ADAPTER pAd, USHORT *Data)
-{
-	USHORT i;
-	USHORT value;
-
-	for (i = 0 ; i < EEPROM_SIZE/2 ; )
-	{
-		/* "value" is expecially for some compilers... */
-		RT28xx_EEPROM_READ16(pAd, i*2, value);
-		Data[i] = value;
-		i++;
-	}
-}
-
-VOID rt_ee_write_all(PRTMP_ADAPTER pAd, USHORT *Data)
-{
-	USHORT i;
-	USHORT value;
-
-	for (i = 0 ; i < EEPROM_SIZE/2 ; )
-	{
-		/* "value" is expecially for some compilers... */
-		value = Data[i];
-		RT28xx_EEPROM_WRITE16(pAd, i*2, value);
-		i ++;
-	}
-}
-#ifdef RALINK_28xx_QA
-VOID ATE_QA_Statistics(
-	IN PRTMP_ADAPTER			pAd,
-	IN PRXWI_STRUC				pRxWI,
-	IN PRT28XX_RXD_STRUC		pRxD,
-	IN PHEADER_802_11			pHeader)
-{
-	// update counter first
-	if (pHeader != NULL)
-	{
-		if (pHeader->FC.Type == BTYPE_DATA)
-		{
-			if (pRxD->U2M)
-				pAd->ate.U2M++;
-			else
-				pAd->ate.OtherData++;
-		}
-		else if (pHeader->FC.Type == BTYPE_MGMT)
-		{
-			if (pHeader->FC.SubType == SUBTYPE_BEACON)
-				pAd->ate.Beacon++;
-			else
-				pAd->ate.OtherCount++;
-		}
-		else if (pHeader->FC.Type == BTYPE_CNTL)
-		{
-			pAd->ate.OtherCount++;
-		}
-	}
-	pAd->ate.RSSI0 = pRxWI->RSSI0;
-	pAd->ate.RSSI1 = pRxWI->RSSI1;
-	pAd->ate.RSSI2 = pRxWI->RSSI2;
-	pAd->ate.SNR0 = pRxWI->SNR0;
-	pAd->ate.SNR1 = pRxWI->SNR1;
-}
-
-/* command id with Cmd Type == 0x0008(for 28xx)/0x0005(for iNIC) */
-#define RACFG_CMD_RF_WRITE_ALL		0x0000
-#define RACFG_CMD_E2PROM_READ16		0x0001
-#define RACFG_CMD_E2PROM_WRITE16	0x0002
-#define RACFG_CMD_E2PROM_READ_ALL	0x0003
-#define RACFG_CMD_E2PROM_WRITE_ALL	0x0004
-#define RACFG_CMD_IO_READ			0x0005
-#define RACFG_CMD_IO_WRITE			0x0006
-#define RACFG_CMD_IO_READ_BULK		0x0007
-#define RACFG_CMD_BBP_READ8			0x0008
-#define RACFG_CMD_BBP_WRITE8		0x0009
-#define RACFG_CMD_BBP_READ_ALL		0x000a
-#define RACFG_CMD_GET_COUNTER		0x000b
-#define RACFG_CMD_CLEAR_COUNTER		0x000c
-
-#define RACFG_CMD_RSV1				0x000d
-#define RACFG_CMD_RSV2				0x000e
-#define RACFG_CMD_RSV3				0x000f
-
-#define RACFG_CMD_TX_START			0x0010
-#define RACFG_CMD_GET_TX_STATUS		0x0011
-#define RACFG_CMD_TX_STOP			0x0012
-#define RACFG_CMD_RX_START			0x0013
-#define RACFG_CMD_RX_STOP			0x0014
-#define RACFG_CMD_GET_NOISE_LEVEL	0x0015
-
-#define RACFG_CMD_ATE_START			0x0080
-#define RACFG_CMD_ATE_STOP			0x0081
-
-#define RACFG_CMD_ATE_START_TX_CARRIER		0x0100
-#define RACFG_CMD_ATE_START_TX_CONT			0x0101
-#define RACFG_CMD_ATE_START_TX_FRAME		0x0102
-#define RACFG_CMD_ATE_SET_BW	            0x0103
-#define RACFG_CMD_ATE_SET_TX_POWER0	        0x0104
-#define RACFG_CMD_ATE_SET_TX_POWER1			0x0105
-#define RACFG_CMD_ATE_SET_FREQ_OFFSET		0x0106
-#define RACFG_CMD_ATE_GET_STATISTICS		0x0107
-#define RACFG_CMD_ATE_RESET_COUNTER			0x0108
-#define RACFG_CMD_ATE_SEL_TX_ANTENNA		0x0109
-#define RACFG_CMD_ATE_SEL_RX_ANTENNA		0x010a
-#define RACFG_CMD_ATE_SET_PREAMBLE			0x010b
-#define RACFG_CMD_ATE_SET_CHANNEL			0x010c
-#define RACFG_CMD_ATE_SET_ADDR1				0x010d
-#define RACFG_CMD_ATE_SET_ADDR2				0x010e
-#define RACFG_CMD_ATE_SET_ADDR3				0x010f
-#define RACFG_CMD_ATE_SET_RATE				0x0110
-#define RACFG_CMD_ATE_SET_TX_FRAME_LEN		0x0111
-#define RACFG_CMD_ATE_SET_TX_FRAME_COUNT	0x0112
-#define RACFG_CMD_ATE_START_RX_FRAME		0x0113
-#define RACFG_CMD_ATE_E2PROM_READ_BULK	0x0114
-#define RACFG_CMD_ATE_E2PROM_WRITE_BULK	0x0115
-#define RACFG_CMD_ATE_IO_WRITE_BULK		0x0116
-#define RACFG_CMD_ATE_BBP_READ_BULK		0x0117
-#define RACFG_CMD_ATE_BBP_WRITE_BULK	0x0118
-#define RACFG_CMD_ATE_RF_READ_BULK		0x0119
-#define RACFG_CMD_ATE_RF_WRITE_BULK		0x011a
-
-
-
-#define A2Hex(_X, _p) 				\
-{									\
-	UCHAR *p;						\
-	_X = 0;							\
-	p = _p;							\
-	while (((*p >= 'a') && (*p <= 'f')) || ((*p >= 'A') && (*p <= 'F')) || ((*p >= '0') && (*p <= '9')))		\
-	{												\
-		if ((*p >= 'a') && (*p <= 'f'))				\
-			_X = _X * 16 + *p - 87;					\
-		else if ((*p >= 'A') && (*p <= 'F'))		\
-			_X = _X * 16 + *p - 55;					\
-		else if ((*p >= '0') && (*p <= '9'))		\
-			_X = _X * 16 + *p - 48;					\
-		p++;										\
-	}												\
-}
-
-
-static VOID memcpy_exl(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len);
-static VOID memcpy_exs(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len);
-static VOID RTMP_IO_READ_BULK(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, UINT32 len);
-
-#ifdef UCOS
-int ate_copy_to_user(
-	IN PUCHAR payload,
-	IN PUCHAR msg,
-	IN INT    len)
-{
-	memmove(payload, msg, len);
-	return 0;
-}
-
-#undef	copy_to_user
-#define copy_to_user(x,y,z) ate_copy_to_user((PUCHAR)x, (PUCHAR)y, z)
-#endif // UCOS //
-
-#define	LEN_OF_ARG 16
-
-VOID RtmpDoAte(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	unsigned short Command_Id;
-	struct ate_racfghdr *pRaCfg;
-	INT	Status = NDIS_STATUS_SUCCESS;
-
-
-
-	if((pRaCfg = kmalloc(sizeof(struct ate_racfghdr), GFP_KERNEL)) == NULL)
-	{
-		Status = -EINVAL;
-		return;
-	}
-
-	NdisZeroMemory(pRaCfg, sizeof(struct ate_racfghdr));
-
-    if (copy_from_user((PUCHAR)pRaCfg, wrq->u.data.pointer, wrq->u.data.length))
-	{
-		Status = -EFAULT;
-		kfree(pRaCfg);
-		return;
-	}
-
-
-	Command_Id = ntohs(pRaCfg->command_id);
-
-	ATEDBGPRINT(RT_DEBUG_TRACE,("\n%s: Command_Id = 0x%04x !\n", __FUNCTION__, Command_Id));
-
-	switch (Command_Id)
-	{
- 		// We will get this command when QA starts.
-		case RACFG_CMD_ATE_START:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START\n"));
-
-				// prepare feedback as soon as we can to avoid QA timeout.
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_TRACE, ("copy_to_user() fail in case RACFG_CMD_ATE_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START is done !\n"));
-				}
-				Set_ATE_Proc(pAdapter, "ATESTART");
-			}
-			break;
-
- 		// We will get this command either QA is closed or ated is killed by user.
-		case RACFG_CMD_ATE_STOP:
-			{
-#ifndef UCOS
-				INT32 ret;
-#endif // !UCOS //
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_STOP\n"));
-
-				// Distinguish this command came from QA(via ated)
-				// or ate daemon according to the existence of pid in payload.
-				// No need to prepare feedback if this cmd came directly from ate daemon.
-				pRaCfg->length = ntohs(pRaCfg->length);
-
-				if (pRaCfg->length == sizeof(pAdapter->ate.AtePid))
-				{
-					// This command came from QA.
-					// Get the pid of ATE daemon.
-					memcpy((UCHAR *)&pAdapter->ate.AtePid,
-						(&pRaCfg->data[0]) - 2/* == &(pRaCfg->status) */,
-						sizeof(pAdapter->ate.AtePid));
-
-					// prepare feedback as soon as we can to avoid QA timeout.
-					pRaCfg->length = htons(2);
-					pRaCfg->status = htons(0);
-
-					wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-										+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-										+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-	            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-	            	{
-	            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_STOP\n"));
-	                    Status = -EFAULT;
-	            	}
-
-					//
-					// kill ATE daemon when leaving ATE mode.
-					// We must kill ATE daemon first before setting ATESTOP,
-					// or Microsoft will report sth. wrong.
-#ifndef UCOS
-					ret = kill_proc(pAdapter->ate.AtePid, SIGTERM, 1);
-					if (ret)
-					{
-						ATEDBGPRINT(RT_DEBUG_ERROR, ("%s: unable to signal thread\n", pAdapter->net_dev->name));
-					}
-#endif // !UCOS //
-				}
-
-#ifdef UCOS
-				// Roger add to avoid error message after close QA
-				if (pAdapter->CSRBaseAddress == RT2860_CSR_ADDR)
-				{
-
-					// prepare feedback as soon as we can to avoid QA timeout.
-					pRaCfg->length = htons(2);
-					pRaCfg->status = htons(0);
-
-					wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-										+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-										+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-	            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-	            	{
-	            		ATEDBGPRINT(RT_DEBUG_TRACE, ("copy_to_user() fail in case RACFG_CMD_AP_START\n"));
-	                    Status = -EFAULT;
-	            	}
-				}
-#endif // UCOS //
-
-				// AP might have in ATE_STOP mode due to cmd from QA.
-				if (ATE_ON(pAdapter))
-				{
-					// Someone has killed ate daemon while QA GUI is still open.
-					Set_ATE_Proc(pAdapter, "ATESTOP");
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_AP_START is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_RF_WRITE_ALL:
-			{
-				UINT32 R1, R2, R3, R4;
-				USHORT channel;
-
-				memcpy(&R1, pRaCfg->data-2, 4);
-				memcpy(&R2, pRaCfg->data+2, 4);
-				memcpy(&R3, pRaCfg->data+6, 4);
-				memcpy(&R4, pRaCfg->data+10, 4);
-				memcpy(&channel, pRaCfg->data+14, 2);
-
-				pAdapter->LatchRfRegs.R1 = ntohl(R1);
-				pAdapter->LatchRfRegs.R2 = ntohl(R2);
-				pAdapter->LatchRfRegs.R3 = ntohl(R3);
-				pAdapter->LatchRfRegs.R4 = ntohl(R4);
-				pAdapter->LatchRfRegs.Channel = ntohs(channel);
-
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R1);
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R2);
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R3);
-				RTMP_RF_IO_WRITE32(pAdapter, pAdapter->LatchRfRegs.R4);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RF_WRITE_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RF_WRITE_ALL is done !\n"));
-				}
-			}
-            break;
-
-		case RACFG_CMD_E2PROM_READ16:
-			{
-				USHORT	offset, value, tmp;
-
-				offset = ntohs(pRaCfg->status);
-				/* "tmp" is expecially for some compilers... */
-				RT28xx_EEPROM_READ16(pAdapter, offset, tmp);
-				value = tmp;
-				value = htons(value);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("EEPROM Read offset = 0x%04x, value = 0x%04x\n", offset, value));
-
-				// prepare feedback
-				pRaCfg->length = htons(4);
-				pRaCfg->status = htons(0);
-				memcpy(pRaCfg->data, &value, 2);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("sizeof(struct ate_racfghdr) = %d\n", sizeof(struct ate_racfghdr)));
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_READ16\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_E2PROM_READ16 is done !\n"));
-				}
-           	}
-			break;
-
-		case RACFG_CMD_E2PROM_WRITE16:
-			{
-				USHORT	offset, value;
-
-				offset = ntohs(pRaCfg->status);
-				memcpy(&value, pRaCfg->data, 2);
-				value = ntohs(value);
-				RT28xx_EEPROM_WRITE16(pAdapter, offset, value);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_WRITE16\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_E2PROM_WRITE16 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_E2PROM_READ_ALL:
-			{
-				USHORT buffer[EEPROM_SIZE/2];
-
-				rt_ee_read_all(pAdapter,(USHORT *)buffer);
-				memcpy_exs(pAdapter, pRaCfg->data, (UCHAR *)buffer, EEPROM_SIZE);
-
-				// prepare feedback
-				pRaCfg->length = htons(2+EEPROM_SIZE);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_READ_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_E2PROM_READ_ALL is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_E2PROM_WRITE_ALL:
-			{
-				USHORT buffer[EEPROM_SIZE/2];
-
-				NdisZeroMemory((UCHAR *)buffer, EEPROM_SIZE);
-				memcpy_exs(pAdapter, (UCHAR *)buffer, (UCHAR *)&pRaCfg->status, EEPROM_SIZE);
-				rt_ee_write_all(pAdapter,(USHORT *)buffer);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_E2PROM_WRITE_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_ERROR, ("RACFG_CMD_E2PROM_WRITE_ALL is done !\n"));
-				}
-
-			}
-			break;
-
-		case RACFG_CMD_IO_READ:
-			{
-				UINT32	offset;
-				UINT32	value;
-
-				memcpy(&offset, &pRaCfg->status, 4);
-				offset = ntohl(offset);
-
-				// We do not need the base address.
-				// So just extract the offset out.
-				offset &= 0x0000FFFF;
-				RTMP_IO_READ32(pAdapter, offset, &value);
-				value = htonl(value);
-
-				// prepare feedback
-				pRaCfg->length = htons(6);
-				pRaCfg->status = htons(0);
-				memcpy(pRaCfg->data, &value, 4);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_IO_READ\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_IO_READ is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_IO_WRITE:
-			{
-				UINT32	offset, value;
-
-				memcpy(&offset, pRaCfg->data-2, 4);
-				memcpy(&value, pRaCfg->data+2, 4);
-
-				offset = ntohl(offset);
-
-				// We do not need the base address.
-				// So just extract out the offset.
-				offset &= 0x0000FFFF;
-				value = ntohl(value);
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_IO_WRITE: offset = %x, value = %x\n", offset, value));
-				RTMP_IO_WRITE32(pAdapter, offset, value);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_IO_WRITE\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_IO_WRITE is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_IO_READ_BULK:
-			{
-				UINT32	offset;
-				USHORT	len;
-
-				memcpy(&offset, &pRaCfg->status, 4);
-				offset = ntohl(offset);
-
-				// We do not need the base address.
-				// So just extract the offset.
-				offset &= 0x0000FFFF;
-				memcpy(&len, pRaCfg->data+2, 2);
-				len = ntohs(len);
-
-				if (len > 371)
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE,("len is too large, make it smaller\n"));
-					pRaCfg->length = htons(2);
-					pRaCfg->status = htons(1);
-					break;
-				}
-
-				RTMP_IO_READ_BULK(pAdapter, pRaCfg->data, (UCHAR *)offset, len*4);// unit in four bytes
-
-				// prepare feedback
-				pRaCfg->length = htons(2+len*4);// unit in four bytes
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_IO_READ_BULK\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_IO_READ_BULK is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_BBP_READ8:
-			{
-				USHORT	offset;
-				UCHAR	value;
-
-				value = 0;
-				offset = ntohs(pRaCfg->status);
-
-				if (ATE_ON(pAdapter))
-				{
-					ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, offset,  &value);
-				}
-				else
-				{
-					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, offset,  &value);
-				}
-				// prepare feedback
-				pRaCfg->length = htons(3);
-				pRaCfg->status = htons(0);
-				pRaCfg->data[0] = value;
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("BBP value = %x\n", value));
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_BBP_READ8\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_BBP_READ8 is done !\n"));
-				}
-			}
-			break;
-		case RACFG_CMD_BBP_WRITE8:
-			{
-				USHORT	offset;
-				UCHAR	value;
-
-				offset = ntohs(pRaCfg->status);
-				memcpy(&value, pRaCfg->data, 1);
-
-				if (ATE_ON(pAdapter))
-				{
-					ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, offset,  value);
-				}
-				else
-				{
-					RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, offset,  value);
-				}
-
-				if ((offset == BBP_R1) || (offset == BBP_R3))
-				{
-					SyncTxRxConfig(pAdapter, offset, value);
-				}
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_BBP_WRITE8\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_BBP_WRITE8 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_BBP_READ_ALL:
-			{
-				USHORT j;
-
-				for (j = 0; j < 137; j++)
-				{
-					pRaCfg->data[j] = 0;
-
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j]);
-					}
-					else
-					{
-						RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j]);
-					}
-				}
-
-				// prepare feedback
-				pRaCfg->length = htons(2+137);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_BBP_READ_ALL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_BBP_READ_ALL is done !\n"));
-				}
-			}
-
-			break;
-
-		case RACFG_CMD_ATE_E2PROM_READ_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT buffer[EEPROM_SIZE/2];
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			rt_ee_read_all(pAdapter,(USHORT *)buffer);
-			if (offset + len <= EEPROM_SIZE)
-				memcpy_exs(pAdapter, pRaCfg->data, (UCHAR *)buffer+offset, len);
-			else
-				ATEDBGPRINT(RT_DEBUG_ERROR, ("exceed EEPROM size\n"));
-
-			// prepare feedback
-			pRaCfg->length = htons(2+len);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_E2PROM_READ_BULK\n"));
-                Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_E2PROM_READ_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_E2PROM_WRITE_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT buffer[EEPROM_SIZE/2];
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			rt_ee_read_all(pAdapter,(USHORT *)buffer);
-			memcpy_exs(pAdapter, (UCHAR *)buffer + offset, (UCHAR *)pRaCfg->data + 2, len);
-			rt_ee_write_all(pAdapter,(USHORT *)buffer);
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_E2PROM_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_ERROR, ("RACFG_CMD_ATE_E2PROM_WRITE_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_IO_WRITE_BULK:
-		{
-			UINT32 offset, i, value;
-			USHORT len;
-
-			memcpy(&offset, &pRaCfg->status, 4);
-			offset = ntohl(offset);
-			memcpy(&len, pRaCfg->data+2, 2);
-			len = ntohs(len);
-
-			for (i = 0; i < len; i += 4)
-			{
-				memcpy_exl(pAdapter, (UCHAR *)&value, pRaCfg->data+4+i, 4);
-				printk("Write %x %x\n", offset + i, value);
-				RTMP_IO_WRITE32(pAdapter, (offset +i) & 0xffff, value);
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_IO_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_ERROR, ("RACFG_CMD_ATE_IO_WRITE_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_BBP_READ_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				pRaCfg->data[j - offset] = 0;
-
-				if (pAdapter->ate.Mode == ATE_STOP)
-				{
-					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j - offset]);
-				}
-				else
-				{
-					ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, j,  &pRaCfg->data[j - offset]);
-				}
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2+len);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_BBP_READ_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_BBP_READ_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_BBP_WRITE_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-			UCHAR *value;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				value = pRaCfg->data + 2 + (j - offset);
-				if (pAdapter->ate.Mode == ATE_STOP)
-				{
-					RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, j,  *value);
-				}
-				else
-				{
-					ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, j,  *value);
-				}
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_BBP_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_BBP_WRITE_BULK is done !\n"));
-			}
-		}
-			break;
-
-#ifdef CONFIG_RALINK_RT3052
-		case RACFG_CMD_ATE_RF_READ_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				pRaCfg->data[j - offset] = 0;
-				RT30xxReadRFRegister(pAdapter, j,  &pRaCfg->data[j - offset]);
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2+len);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_RF_READ_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_RF_READ_BULK is done !\n"));
-			}
-
-		}
-			break;
-
-		case RACFG_CMD_ATE_RF_WRITE_BULK:
-		{
-			USHORT offset;
-			USHORT len;
-			USHORT j;
-			UCHAR *value;
-
-			offset = ntohs(pRaCfg->status);
-			memcpy(&len, pRaCfg->data, 2);
-			len = ntohs(len);
-
-			for (j = offset; j < (offset+len); j++)
-			{
-				value = pRaCfg->data + 2 + (j - offset);
-				RT30xxWriteRFRegister(pAdapter, j,  *value);
-			}
-
-			// prepare feedback
-			pRaCfg->length = htons(2);
-			pRaCfg->status = htons(0);
-			wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-								+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-								+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            {
-            	ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_RF_WRITE_BULK\n"));
-                   Status = -EFAULT;
-            }
-			else
-			{
-               	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_RF_WRITE_BULK is done !\n"));
-			}
-
-		}
-			break;
-#endif
-
-
-		case RACFG_CMD_GET_NOISE_LEVEL:
-			{
-				UCHAR	channel;
-				INT32   buffer[3][10];/* 3 : RxPath ; 10 : no. of per rssi samples */
-
-				channel = (ntohs(pRaCfg->status) & 0x00FF);
-				CalNoiseLevel(pAdapter, channel, buffer);
-				memcpy_exl(pAdapter, (UCHAR *)pRaCfg->data, (UCHAR *)&(buffer[0][0]), (sizeof(INT32)*3*10));
-
-				// prepare feedback
-				pRaCfg->length = htons(2 + (sizeof(INT32)*3*10));
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_GET_NOISE_LEVEL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_GET_NOISE_LEVEL is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_GET_COUNTER:
-			{
-				memcpy_exl(pAdapter, &pRaCfg->data[0], (UCHAR *)&pAdapter->ate.U2M, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[4], (UCHAR *)&pAdapter->ate.OtherData, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[8], (UCHAR *)&pAdapter->ate.Beacon, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[12], (UCHAR *)&pAdapter->ate.OtherCount, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[16], (UCHAR *)&pAdapter->ate.TxAc0, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[20], (UCHAR *)&pAdapter->ate.TxAc1, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[24], (UCHAR *)&pAdapter->ate.TxAc2, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[28], (UCHAR *)&pAdapter->ate.TxAc3, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[32], (UCHAR *)&pAdapter->ate.TxHCCA, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[36], (UCHAR *)&pAdapter->ate.TxMgmt, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&pAdapter->ate.RSSI0, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[44], (UCHAR *)&pAdapter->ate.RSSI1, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[48], (UCHAR *)&pAdapter->ate.RSSI2, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[52], (UCHAR *)&pAdapter->ate.SNR0, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[56], (UCHAR *)&pAdapter->ate.SNR1, 4);
-
-				pRaCfg->length = htons(2+60);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_GET_COUNTER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_GET_COUNTER is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_CLEAR_COUNTER:
-			{
-				pAdapter->ate.U2M = 0;
-				pAdapter->ate.OtherData = 0;
-				pAdapter->ate.Beacon = 0;
-				pAdapter->ate.OtherCount = 0;
-				pAdapter->ate.TxAc0 = 0;
-				pAdapter->ate.TxAc1 = 0;
-				pAdapter->ate.TxAc2 = 0;
-				pAdapter->ate.TxAc3 = 0;
-				pAdapter->ate.TxHCCA = 0;
-				pAdapter->ate.TxMgmt = 0;
-				pAdapter->ate.TxDoneCount = 0;
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_CLEAR_COUNTER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_CLEAR_COUNTER is done !\n"));
-				}
-			}
-
-			break;
-
-		case RACFG_CMD_TX_START:
-			{
-				USHORT *p;
-				USHORT	err = 1;
-				UCHAR   Bbp22Value = 0, Bbp24Value = 0;
-
-				if ((pAdapter->ate.TxStatus != 0) && (pAdapter->ate.Mode & ATE_TXFRAME))
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE,("Ate Tx is already running, to run next Tx, you must stop it first\n"));
-					err = 2;
-					goto TX_START_ERROR;
-				}
-				else if ((pAdapter->ate.TxStatus != 0) && !(pAdapter->ate.Mode & ATE_TXFRAME))
-				{
-					int i = 0;
-
-					while ((i++ < 10) && (pAdapter->ate.TxStatus != 0))
-					{
-						RTMPusecDelay(5000);
-					}
-
-					// force it to stop
-					pAdapter->ate.TxStatus = 0;
-					pAdapter->ate.TxDoneCount = 0;
-					//pAdapter->ate.Repeat = 0;
-					pAdapter->ate.bQATxStart = FALSE;
-				}
-
-				// If pRaCfg->length == 0, this "RACFG_CMD_TX_START" is for Carrier test or Carrier Suppression.
-				if (ntohs(pRaCfg->length) != 0)
-				{
-					// Get frame info
-#ifdef RT2870
-					NdisMoveMemory(&pAdapter->ate.TxInfo, pRaCfg->data - 2, 4);
-#ifdef RT_BIG_ENDIAN
-					RTMPDescriptorEndianChange((PUCHAR) &pAdapter->ate.TxInfo, TYPE_TXINFO);
-#endif // RT_BIG_ENDIAN //
-#endif // RT2870 //
-
-					NdisMoveMemory(&pAdapter->ate.TxWI, pRaCfg->data + 2, 16);
-#ifdef RT_BIG_ENDIAN
-					RTMPWIEndianChange((PUCHAR)&pAdapter->ate.TxWI, TYPE_TXWI);
-#endif // RT_BIG_ENDIAN //
-
-					NdisMoveMemory(&pAdapter->ate.TxCount, pRaCfg->data + 18, 4);
-					pAdapter->ate.TxCount = ntohl(pAdapter->ate.TxCount);
-
-					p = (USHORT *)(&pRaCfg->data[22]);
-					//p = pRaCfg->data + 22;
-					// always use QID_AC_BE
-					pAdapter->ate.QID = 0;
-					p = (USHORT *)(&pRaCfg->data[24]);
-					//p = pRaCfg->data + 24;
-					pAdapter->ate.HLen = ntohs(*p);
-
-					if (pAdapter->ate.HLen > 32)
-					{
-						ATEDBGPRINT(RT_DEBUG_ERROR,("pAdapter->ate.HLen > 32\n"));
-						err = 3;
-						goto TX_START_ERROR;
-					}
-
-					NdisMoveMemory(&pAdapter->ate.Header, pRaCfg->data + 26, pAdapter->ate.HLen);
-
-
-					pAdapter->ate.PLen = ntohs(pRaCfg->length) - (pAdapter->ate.HLen + 28);
-
-					if (pAdapter->ate.PLen > 32)
-					{
-						ATEDBGPRINT(RT_DEBUG_ERROR,("pAdapter->ate.PLen > 32\n"));
-						err = 4;
-						goto TX_START_ERROR;
-					}
-
-					NdisMoveMemory(&pAdapter->ate.Pattern, pRaCfg->data + 26 + pAdapter->ate.HLen, pAdapter->ate.PLen);
-					pAdapter->ate.DLen = pAdapter->ate.TxWI.MPDUtotalByteCount - pAdapter->ate.HLen;
-				}
-
-				ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R22, &Bbp22Value);
-
-				switch (Bbp22Value)
-				{
-					case BBP22_TXFRAME:
-						{
-							if (pAdapter->ate.TxCount == 0)
-							{
-							}
-							ATEDBGPRINT(RT_DEBUG_TRACE,("START TXFRAME\n"));
-							pAdapter->ate.bQATxStart = TRUE;
-							Set_ATE_Proc(pAdapter, "TXFRAME");
-						}
-						break;
-
-					case BBP22_TXCONT_OR_CARRSUPP:
-						{
-							ATEDBGPRINT(RT_DEBUG_TRACE,("BBP22_TXCONT_OR_CARRSUPP\n"));
-							ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, 24, &Bbp24Value);
-
-							switch (Bbp24Value)
-							{
-								case BBP24_TXCONT:
-									{
-										ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCONT\n"));
-										pAdapter->ate.bQATxStart = TRUE;
-										Set_ATE_Proc(pAdapter, "TXCONT");
-									}
-									break;
-
-								case BBP24_CARRSUPP:
-									{
-										ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCARRSUPP\n"));
-										pAdapter->ate.bQATxStart = TRUE;
-										pAdapter->ate.Mode |= ATE_TXCARRSUPP;
-									}
-									break;
-
-								default:
-									{
-										ATEDBGPRINT(RT_DEBUG_ERROR,("Unknown Start TX subtype !"));
-									}
-									break;
-							}
-						}
-						break;
-
-					case BBP22_TXCARR:
-						{
-							ATEDBGPRINT(RT_DEBUG_TRACE,("START TXCARR\n"));
-							pAdapter->ate.bQATxStart = TRUE;
-							Set_ATE_Proc(pAdapter, "TXCARR");
-						}
-						break;
-
-					default:
-						{
-							ATEDBGPRINT(RT_DEBUG_ERROR,("Unknown Start TX subtype !"));
-						}
-						break;
-				}
-
-				if (pAdapter->ate.bQATxStart == TRUE)
-				{
-					// prepare feedback
-					pRaCfg->length = htons(2);
-					pRaCfg->status = htons(0);
-
-					wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-										+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-										+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-	            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-	            	{
-	            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() was failed in case RACFG_CMD_TX_START\n"));
-	                    Status = -EFAULT;
-	            	}
-					else
-					{
-	                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_TX_START is done !\n"));
-					}
-					break;
-				}
-
-TX_START_ERROR:
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(err);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_TX_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("feedback of TX_START_ERROR is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_GET_TX_STATUS:
-			{
-				UINT32 count;
-
-				// prepare feedback
-				pRaCfg->length = htons(6);
-				pRaCfg->status = htons(0);
-				count = htonl(pAdapter->ate.TxDoneCount);
-				NdisMoveMemory(pRaCfg->data, &count, 4);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_GET_TX_STATUS\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_GET_TX_STATUS is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_TX_STOP:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_TX_STOP\n"));
-
-				Set_ATE_Proc(pAdapter, "TXSTOP");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_TRACE, ("copy_to_user() fail in case RACFG_CMD_TX_STOP\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_TX_STOP is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_RX_START:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_START\n"));
-
-				pAdapter->ate.bQARxStart = TRUE;
-				Set_ATE_Proc(pAdapter, "RXFRAME");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RX_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RX_START is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_RX_STOP:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_STOP\n"));
-
-				Set_ATE_Proc(pAdapter, "RXSTOP");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RX_STOP\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RX_STOP is done !\n"));
-				}
-			}
-			break;
-
-		/* The following cases are for new ATE GUI(not QA). */
-		/*==================================================*/
-		case RACFG_CMD_ATE_START_TX_CARRIER:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_CARRIER\n"));
-
-				Set_ATE_Proc(pAdapter, "TXCARR");
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_START_TX_CARRIER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START_TX_CARRIER is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_START_TX_CONT:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_CONT\n"));
-
-				Set_ATE_Proc(pAdapter, "TXCONT");
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_START_TX_CONT\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START_TX_CONT is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_START_TX_FRAME:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_START_TX_FRAME\n"));
-
-				Set_ATE_Proc(pAdapter, "TXFRAME");
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE, ("wrq->u.data.length = %d\n", wrq->u.data.length));
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_START_TX_FRAME\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_START_TX_FRAME is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_BW:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_BW\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-
-				Set_ATE_TX_BW_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_BW\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_BW is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_POWER0:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_POWER0\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_POWER0_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_POWER0\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_POWER0 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_POWER1:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_POWER1\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_POWER1_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_POWER1\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_POWER1 is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_FREQ_OFFSET:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_FREQ_OFFSET\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_FREQOFFSET_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_FREQ_OFFSET\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_FREQ_OFFSET is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_GET_STATISTICS:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_GET_STATISTICS\n"));
-
-				memcpy_exl(pAdapter, &pRaCfg->data[0], (UCHAR *)&pAdapter->ate.TxDoneCount, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[4], (UCHAR *)&pAdapter->WlanCounters.RetryCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[8], (UCHAR *)&pAdapter->WlanCounters.FailedCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[12], (UCHAR *)&pAdapter->WlanCounters.RTSSuccessCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[16], (UCHAR *)&pAdapter->WlanCounters.RTSFailureCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[20], (UCHAR *)&pAdapter->WlanCounters.ReceivedFragmentCount.QuadPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[24], (UCHAR *)&pAdapter->WlanCounters.FCSErrorCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[28], (UCHAR *)&pAdapter->Counters8023.RxNoBuffer, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[32], (UCHAR *)&pAdapter->WlanCounters.FrameDuplicateCount.u.LowPart, 4);
-				memcpy_exl(pAdapter, &pRaCfg->data[36], (UCHAR *)&pAdapter->RalinkCounters.OneSecFalseCCACnt, 4);
-
-				if (pAdapter->ate.RxAntennaSel == 0)
-				{
-					INT32 RSSI0 = 0;
-					INT32 RSSI1 = 0;
-					INT32 RSSI2 = 0;
-
-					RSSI0 = (INT32)(pAdapter->ate.LastRssi0 - pAdapter->BbpRssiToDbmDelta);
-					RSSI1 = (INT32)(pAdapter->ate.LastRssi1 - pAdapter->BbpRssiToDbmDelta);
-					RSSI2 = (INT32)(pAdapter->ate.LastRssi2 - pAdapter->BbpRssiToDbmDelta);
-					memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&RSSI0, 4);
-					memcpy_exl(pAdapter, &pRaCfg->data[44], (UCHAR *)&RSSI1, 4);
-					memcpy_exl(pAdapter, &pRaCfg->data[48], (UCHAR *)&RSSI2, 4);
-					pRaCfg->length = htons(2+52);
-				}
-				else
-				{
-					INT32 RSSI0 = 0;
-
-					RSSI0 = (INT32)(pAdapter->ate.LastRssi0 - pAdapter->BbpRssiToDbmDelta);
-					memcpy_exl(pAdapter, &pRaCfg->data[40], (UCHAR *)&RSSI0, 4);
-					pRaCfg->length = htons(2+44);
-				}
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_GET_STATISTICS\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_GET_STATISTICS is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_RESET_COUNTER:
-			{
-				SHORT    value = 1;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_RESET_COUNTER\n"));
-
-				sprintf((PCHAR)str, "%d", value);
-				Set_ResetStatCounter_Proc(pAdapter, str);
-
-				pAdapter->ate.TxDoneCount = 0;
-
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_RESET_COUNTER\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_RESET_COUNTER is done !\n"));
-				}
-			}
-
-			break;
-
-		case RACFG_CMD_ATE_SEL_TX_ANTENNA:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SEL_TX_ANTENNA\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_Antenna_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SEL_TX_ANTENNA\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SEL_TX_ANTENNA is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SEL_RX_ANTENNA:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SEL_RX_ANTENNA\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_RX_Antenna_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SEL_RX_ANTENNA\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SEL_RX_ANTENNA is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_PREAMBLE:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_PREAMBLE\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_MODE_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_PREAMBLE\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_PREAMBLE is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_CHANNEL:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_CHANNEL\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_CHANNEL_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_CHANNEL\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_CHANNEL is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_ADDR1:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR1\n"));
-
-				// Addr is an array of UCHAR,
-				// so no need to perform endian swap.
-				memcpy(pAdapter->ate.Addr1, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_ADDR1\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_ADDR1 is done !\n (ADDR1 = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAdapter->ate.Addr1[0],
-						pAdapter->ate.Addr1[1], pAdapter->ate.Addr1[2], pAdapter->ate.Addr1[3], pAdapter->ate.Addr1[4], pAdapter->ate.Addr1[5]));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_ADDR2:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR2\n"));
-
-				// Addr is an array of UCHAR,
-				// so no need to perform endian swap.
-				memcpy(pAdapter->ate.Addr2, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_ADDR2\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_ADDR2 is done !\n (ADDR2 = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAdapter->ate.Addr2[0],
-						pAdapter->ate.Addr2[1], pAdapter->ate.Addr2[2], pAdapter->ate.Addr2[3], pAdapter->ate.Addr2[4], pAdapter->ate.Addr2[5]));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_ADDR3:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_ADDR3\n"));
-
-				// Addr is an array of UCHAR,
-				// so no need to perform endian swap.
-				memcpy(pAdapter->ate.Addr3, (PUCHAR)(pRaCfg->data - 2), MAC_ADDR_LEN);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_ADDR3\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-					ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_ADDR3 is done !\n (ADDR3 = %2X:%2X:%2X:%2X:%2X:%2X)\n", pAdapter->ate.Addr3[0],
-						pAdapter->ate.Addr3[1], pAdapter->ate.Addr3[2], pAdapter->ate.Addr3[3], pAdapter->ate.Addr3[4], pAdapter->ate.Addr3[5]));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_RATE:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_RATE\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_MCS_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_RATE\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_RATE is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_FRAME_LEN:
-			{
-				SHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_FRAME_LEN\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				sprintf((PCHAR)str, "%d", value);
-				Set_ATE_TX_LENGTH_Proc(pAdapter, str);
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_FRAME_LEN\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_FRAME_LEN is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_SET_TX_FRAME_COUNT:
-			{
-				USHORT    value = 0;
-				UCHAR    str[LEN_OF_ARG];
-
-				NdisZeroMemory(str, LEN_OF_ARG);
-
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_ATE_SET_TX_FRAME_COUNT\n"));
-
-				memcpy((PUCHAR)&value, (PUCHAR)&(pRaCfg->status), 2);
-				value = ntohs(value);
-				{
-					sprintf((PCHAR)str, "%d", value);
-					Set_ATE_TX_COUNT_Proc(pAdapter, str);
-				}
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_ATE_SET_TX_FRAME_COUNT\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_ATE_SET_TX_FRAME_COUNT is done !\n"));
-				}
-			}
-			break;
-
-		case RACFG_CMD_ATE_START_RX_FRAME:
-			{
-				ATEDBGPRINT(RT_DEBUG_TRACE,("RACFG_CMD_RX_START\n"));
-
-				Set_ATE_Proc(pAdapter, "RXFRAME");
-
-				// prepare feedback
-				pRaCfg->length = htons(2);
-				pRaCfg->status = htons(0);
-				wrq->u.data.length = sizeof(pRaCfg->magic_no) + sizeof(pRaCfg->command_type)
-									+ sizeof(pRaCfg->command_id) + sizeof(pRaCfg->length)
-									+ sizeof(pRaCfg->sequence) + ntohs(pRaCfg->length);
-
-            	if (copy_to_user(wrq->u.data.pointer, pRaCfg, wrq->u.data.length))
-            	{
-            		ATEDBGPRINT(RT_DEBUG_ERROR, ("copy_to_user() fail in case RACFG_CMD_RX_START\n"));
-                    Status = -EFAULT;
-            	}
-				else
-				{
-                	ATEDBGPRINT(RT_DEBUG_TRACE, ("RACFG_CMD_RX_START is done !\n"));
-				}
-			}
-			break;
-		default:
-			break;
-	}
-    ASSERT(pRaCfg != NULL);
-    if (pRaCfg != NULL)
-    {
-    kfree(pRaCfg);
-    }
-	return;
-}
-
-VOID BubbleSort(INT32 n, INT32 a[])
-{
-	INT32 k, j, temp;
-
-	for (k = n-1;  k>0;  k--)
-	{
-		for (j = 0; j<k; j++)
-		{
-			if(a[j] > a[j+1])
-			{
-				temp = a[j];
-				a[j]=a[j+1];
-				a[j+1]=temp;
-			}
-		}
-	}
-}
-
-VOID CalNoiseLevel(PRTMP_ADAPTER pAd, UCHAR channel, INT32 RSSI[3][10])
-{
-	INT32		RSSI0, RSSI1, RSSI2;
- 	CHAR		Rssi0Offset, Rssi1Offset, Rssi2Offset;
-	UCHAR		BbpR50Rssi0 = 0, BbpR51Rssi1 = 0, BbpR52Rssi2 = 0;
-	UCHAR		Org_BBP66value = 0, Org_BBP69value = 0, Org_BBP70value = 0, data = 0;
-	USHORT		LNA_Gain = 0;
-	INT32       j = 0;
-	UCHAR		Org_Channel = pAd->ate.Channel;
-	USHORT	    GainValue = 0, OffsetValue = 0;
-
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &Org_BBP66value);
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R69, &Org_BBP69value);
-	ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R70, &Org_BBP70value);
-
-	//**********************************************************************
-	// Read the value of LNA gain and Rssi offset
-	//**********************************************************************
-	RT28xx_EEPROM_READ16(pAd, EEPROM_LNA_OFFSET, GainValue);
-
-	// for Noise Level
-	if (channel <= 14)
-	{
-		LNA_Gain = GainValue & 0x00FF;
-
-		RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_BG_OFFSET, OffsetValue);
-		Rssi0Offset = OffsetValue & 0x00FF;
-		Rssi1Offset = (OffsetValue & 0xFF00) >> 8;
-		RT28xx_EEPROM_READ16(pAd, (EEPROM_RSSI_BG_OFFSET + 2)/* 0x48 */, OffsetValue);
-		Rssi2Offset = OffsetValue & 0x00FF;
-	}
-	else
-	{
-		LNA_Gain = (GainValue & 0xFF00) >> 8;
-
-		RT28xx_EEPROM_READ16(pAd, EEPROM_RSSI_A_OFFSET, OffsetValue);
-		Rssi0Offset = OffsetValue & 0x00FF;
-		Rssi1Offset = (OffsetValue & 0xFF00) >> 8;
-		RT28xx_EEPROM_READ16(pAd, (EEPROM_RSSI_A_OFFSET + 2)/* 0x4C */, OffsetValue);
-		Rssi2Offset = OffsetValue & 0x00FF;
-	}
-	//**********************************************************************
-	{
-		pAd->ate.Channel = channel;
-		ATEAsicSwitchChannel(pAd);
-		mdelay(5);
-
-		data = 0x10;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, data);
-		data = 0x40;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, data);
-		data = 0x40;
-		ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, data);
-		mdelay(5);
-
-		// Start Rx
-		pAd->ate.bQARxStart = TRUE;
-		Set_ATE_Proc(pAd, "RXFRAME");
-
-		mdelay(5);
-
-		for (j = 0; j < 10; j++)
-		{
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R50, &BbpR50Rssi0);
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R51, &BbpR51Rssi1);
-			ATE_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R52, &BbpR52Rssi2);
-
-			mdelay(10);
-
-			// Calculate RSSI 0
-			if (BbpR50Rssi0 == 0)
-			{
-				RSSI0 = -100;
-			}
-			else
-			{
-				RSSI0 = (INT32)(-12 - BbpR50Rssi0 - LNA_Gain - Rssi0Offset);
-			}
-			RSSI[0][j] = RSSI0;
-
-			if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
-			{
-				// Calculate RSSI 1
-				if (BbpR51Rssi1 == 0)
-				{
-					RSSI1 = -100;
-				}
-				else
-				{
-					RSSI1 = (INT32)(-12 - BbpR51Rssi1 - LNA_Gain - Rssi1Offset);
-				}
-				RSSI[1][j] = RSSI1;
-			}
-
-			if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
-			{
-				// Calculate RSSI 2
-				if (BbpR52Rssi2 == 0)
-					RSSI2 = -100;
-				else
-					RSSI2 = (INT32)(-12 - BbpR52Rssi2 - LNA_Gain - Rssi2Offset);
-
-				RSSI[2][j] = RSSI2;
-			}
-		}
-
-		// Stop Rx
-		Set_ATE_Proc(pAd, "RXSTOP");
-
-		mdelay(5);
-
-		BubbleSort(10, RSSI[0]);	// 1R
-
-		if ( pAd->Antenna.field.RxPath >= 2 ) // 2R
-		{
-			BubbleSort(10, RSSI[1]);
-		}
-
-		if ( pAd->Antenna.field.RxPath >= 3 ) // 3R
-		{
-			BubbleSort(10, RSSI[2]);
-		}
-
-	}
-
-	pAd->ate.Channel = Org_Channel;
-	ATEAsicSwitchChannel(pAd);
-
-	// Restore original value
-    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R66, Org_BBP66value);
-    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, Org_BBP69value);
-    ATE_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, Org_BBP70value);
-
-	return;
-}
-
-BOOLEAN SyncTxRxConfig(PRTMP_ADAPTER pAd, USHORT offset, UCHAR value)
-{
-	UCHAR tmp = 0, bbp_data = 0;
-
-	if (ATE_ON(pAd))
-	{
-		ATE_BBP_IO_READ8_BY_REG_ID(pAd, offset, &bbp_data);
-	}
-	else
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, offset, &bbp_data);
-	}
-
-	/* confirm again */
-	ASSERT(bbp_data == value);
-
-	switch(offset)
-	{
-		case BBP_R1:
-			/* Need to sync. tx configuration with legacy ATE. */
-			tmp = (bbp_data & ((1 << 4) | (1 << 3))/* 0x18 */) >> 3;
-		    switch(tmp)
-		    {
-				/* The BBP R1 bit[4:3] = 2 :: Both DACs will be used by QA. */
-		        case 2:
-					/* All */
-					pAd->ate.TxAntennaSel = 0;
-		            break;
-				/* The BBP R1 bit[4:3] = 0 :: DAC 0 will be used by QA. */
-		        case 0:
-					/* Antenna one */
-					pAd->ate.TxAntennaSel = 1;
-		            break;
-				/* The BBP R1 bit[4:3] = 1 :: DAC 1 will be used by QA. */
-		        case 1:
-					/* Antenna two */
-					pAd->ate.TxAntennaSel = 2;
-		            break;
-		        default:
-		            DBGPRINT(RT_DEBUG_TRACE, ("%s -- Sth. wrong!  : return FALSE; \n", __FUNCTION__));
-		            return FALSE;
-		    }
-			break;/* case BBP_R1 */
-
-		case BBP_R3:
-			/* Need to sync. rx configuration with legacy ATE. */
-			tmp = (bbp_data & ((1 << 1) | (1 << 0))/* 0x03 */);
-		    switch(tmp)
-		    {
-				/* The BBP R3 bit[1:0] = 3 :: All ADCs will be used by QA. */
-		        case 3:
-					/* All */
-					pAd->ate.RxAntennaSel = 0;
-		            break;
-				/* The BBP R3 bit[1:0] = 0 :: ADC 0 will be used by QA, */
-				/* unless the BBP R3 bit[4:3] = 2 */
-		        case 0:
-					/* Antenna one */
-					pAd->ate.RxAntennaSel = 1;
-					tmp = ((bbp_data & ((1 << 4) | (1 << 3))/* 0x03 */) >> 3);
-					if (tmp == 2)// 3R
-					{
-						/* Default : All ADCs will be used by QA */
-						pAd->ate.RxAntennaSel = 0;
-					}
-		            break;
-				/* The BBP R3 bit[1:0] = 1 :: ADC 1 will be used by QA. */
-		        case 1:
-					/* Antenna two */
-					pAd->ate.RxAntennaSel = 2;
-		            break;
-				/* The BBP R3 bit[1:0] = 2 :: ADC 2 will be used by QA. */
-		        case 2:
-					/* Antenna three */
-					pAd->ate.RxAntennaSel = 3;
-		            break;
-		        default:
-		            DBGPRINT(RT_DEBUG_ERROR, ("%s -- Impossible!  : return FALSE; \n", __FUNCTION__));
-		            return FALSE;
-		    }
-			break;/* case BBP_R3 */
-
-        default:
-            DBGPRINT(RT_DEBUG_ERROR, ("%s -- Sth. wrong!  : return FALSE; \n", __FUNCTION__));
-            return FALSE;
-
-	}
-	return TRUE;
-}
-
-static VOID memcpy_exl(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len)
-{
-	ULONG i, Value = 0;
-	ULONG *pDst, *pSrc;
-	UCHAR *p8;
-
-	p8 = src;
-	pDst = (ULONG *) dst;
-	pSrc = (ULONG *) src;
-
-	for (i = 0 ; i < (len/4); i++)
-	{
-		/* For alignment issue, we need a variable "Value". */
-		memmove(&Value, pSrc, 4);
-		Value = htonl(Value);
-		memmove(pDst, &Value, 4);
-		pDst++;
-		pSrc++;
-	}
-	if ((len % 4) != 0)
-	{
-		/* wish that it will never reach here */
-		memmove(&Value, pSrc, (len % 4));
-		Value = htonl(Value);
-		memmove(pDst, &Value, (len % 4));
-	}
-}
-
-static VOID memcpy_exs(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, ULONG len)
-{
-	ULONG i;
-	UCHAR *pDst, *pSrc;
-
-	pDst = dst;
-	pSrc = src;
-
-	for (i = 0; i < (len/2); i++)
-	{
-		memmove(pDst, pSrc, 2);
-		*((USHORT *)pDst) = htons(*((USHORT *)pDst));
-		pDst+=2;
-		pSrc+=2;
-	}
-
-	if ((len % 2) != 0)
-	{
-		memmove(pDst, pSrc, 1);
-	}
-}
-
-static VOID RTMP_IO_READ_BULK(PRTMP_ADAPTER pAd, UCHAR *dst, UCHAR *src, UINT32 len)
-{
-	UINT32 i, Value;
-	UINT32 *pDst, *pSrc;
-
-	pDst = (UINT32 *) dst;
-	pSrc = (UINT32 *) src;
-
-	for (i = 0 ; i < (len/4); i++)
-	{
-		RTMP_IO_READ32(pAd, (ULONG)pSrc, &Value);
-		Value = htonl(Value);
-		memmove(pDst, &Value, 4);
-		pDst++;
-		pSrc++;
-	}
-	return;
-}
-
-INT Set_TxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ATEDBGPRINT(RT_DEBUG_TRACE,("Set_TxStop_Proc\n"));
-
-	if (Set_ATE_Proc(pAd, "TXSTOP"))
-	{
-	return TRUE;
-}
-	else
-	{
-		return FALSE;
-	}
-}
-
-INT Set_RxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	ATEDBGPRINT(RT_DEBUG_TRACE,("Set_RxStop_Proc\n"));
-
-	if (Set_ATE_Proc(pAd, "RXSTOP"))
-	{
-	return TRUE;
-}
-	else
-	{
-		return FALSE;
-	}
-}
-#endif	// RALINK_28xx_QA //
-#endif	// RALINK_ATE //
-
diff --git a/drivers/staging/rt3070/rt_ate.h b/drivers/staging/rt3070/rt_ate.h
deleted file mode 100644
index 829ebb5..0000000
--- a/drivers/staging/rt3070/rt_ate.h
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#ifndef __ATE_H__
-#define __ATE_H__
-
-#ifndef UCOS
-#define ate_print printk
-#define ATEDBGPRINT DBGPRINT
-
-#ifdef RT2870
-#define EEPROM_SIZE								0x400
-#ifdef CONFIG_STA_SUPPORT
-#define EEPROM_BIN_FILE_NAME  "/etc/Wireless/RT2870STA/e2p.bin"
-#endif // CONFIG_STA_SUPPORT //
-#endif // RT2870 //
-#else // !UCOS //
-#define fATE_LOAD_EEPROM						0x0C43
-#ifdef CONFIG_PRINTK
-extern INT ConsoleResponse(IN PUCHAR buff);
-extern int (*remote_display)(char *);
-extern void puts (const char *s);
-
-/* specificly defined to redirect and show ate-related messages to host. */
-/* Try to define ate_print as a macro. */
-#define ate_print(fmt, args...)                 \
-do{   int (*org_remote_display)(char *) = NULL;   \
-	org_remote_display = remote_display;\
-	/* Save original "remote_display" */\
-	remote_display = (int (*)(char *))ConsoleResponse;           \
-	printk(fmt, ## args);                       \
-	/* Restore the remote_display function pointer */        \
-	remote_display = org_remote_display; }while(0)
-
-#define ATEDBGPRINT(Level, Fmt)    	\
-{                                   \
-    if ((Level) <= RTDebugLevel)      \
-    {                               \
-        ate_print Fmt;					\
-    }                               \
-}
-#endif // CONFIG_PRINTK //
-#endif // !UCOS //
-
-#define ATE_ON(_p)              (((_p)->ate.Mode) != ATE_STOP)
-
-/* RT2880_iNIC will define "RT2860". */
-
-/* RT2880_iNIC will define RT2860. */
-
-#ifdef RT2870
-#define EEPROM_SIZE								0x400
-#ifdef CONFIG_STA_SUPPORT
-#define EEPROM_BIN_FILE_NAME  "/etc/Wireless/RT2870STA/e2p.bin"
-#endif // CONFIG_STA_SUPPORT //
-#endif // RT2870 //
-
-#ifdef RT2870
-#define ATE_BBP_IO_READ8_BY_REG_ID(_A, _I, _pV)    RTMP_BBP_IO_READ8_BY_REG_ID(_A, _I, _pV)
-#define ATE_BBP_IO_WRITE8_BY_REG_ID(_A, _I, _V)    RTMP_BBP_IO_WRITE8_BY_REG_ID(_A, _I, _V)
-
-#define BULK_OUT_LOCK(pLock, IrqFlags)	\
-		if(1 /*!(in_interrupt() & 0xffff0000)*/)	\
-			RTMP_IRQ_LOCK((pLock), IrqFlags);
-
-#define BULK_OUT_UNLOCK(pLock, IrqFlags)	\
-		if(1 /*!(in_interrupt() & 0xffff0000)*/)	\
-			RTMP_IRQ_UNLOCK((pLock), IrqFlags);
-
-// Prototypes of completion funuc.
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-#define ATE_RTUSBBulkOutDataPacketComplete(purb, pt_regs)    ATE_RTUSBBulkOutDataPacketComplete(purb)
-#endif
-
-VOID ATE_RTUSBBulkOutDataPacketComplete(
-	IN purbb_t purb,
-	OUT struct pt_regs *pt_regs);
-
-VOID ATE_RTUSBBulkOutDataPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BulkOutPipeId);
-
-VOID ATE_RTUSBCancelPendingBulkInIRP(
-	IN	PRTMP_ADAPTER	pAd);
-#endif // RT2870 //
-
-#ifdef RT30xx
-#define ATE_RF_IO_READ8_BY_REG_ID(_A, _I, _pV)     RTMP_RF_IO_READ8_BY_REG_ID(_A, _I, _pV)
-#define ATE_RF_IO_WRITE8_BY_REG_ID(_A, _I, _V)     RTMP_RF_IO_WRITE8_BY_REG_ID(_A, _I, _V)
-#endif // RT30xx //
-
-
-VOID rt_ee_read_all(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT USHORT *Data);
-
-
-VOID rt_ee_write_all(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  USHORT *Data);
-
-INT Set_ATE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_DA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_SA_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_BSSID_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_CHANNEL_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_POWER0_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_POWER1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_RX_Antenna_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_FREQOFFSET_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_BW_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_LENGTH_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_COUNT_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_MCS_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_MODE_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_TX_GI_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-
-INT	Set_ATE_RX_FER_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Read_RF_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF1_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF2_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF3_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Write_RF4_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Load_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_ATE_Read_E2P_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_Show_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ATE_Help_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-VOID ATE_QA_Statistics(
-	IN PRTMP_ADAPTER		pAd,
-	IN PRXWI_STRUC			pRxWI,
-	IN PRT28XX_RXD_STRUC    p28xxRxD,
-	IN PHEADER_802_11		pHeader);
-
-VOID RtmpDoAte(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID BubbleSort(
-	IN  INT32 n,
-	IN  INT32 a[]);
-
-VOID CalNoiseLevel(
-	IN  PRTMP_ADAPTER   pAdapter,
-	IN  UCHAR           channel,
-	OUT INT32           buffer[3][10]);
-
-BOOLEAN SyncTxRxConfig(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	USHORT			offset,
-	IN	UCHAR			value);
-
-INT Set_TxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_RxStop_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-VOID ATEAsicSwitchChannel(
-	IN PRTMP_ADAPTER pAd);
-
-VOID ATEAsicAdjustTxPower(
-	IN PRTMP_ADAPTER pAd);
-
-VOID ATEDisableAsicProtect(
-	IN		PRTMP_ADAPTER	pAd);
-
-CHAR ATEConvertToRssi(
-	IN PRTMP_ADAPTER  pAd,
-	IN CHAR				Rssi,
-	IN UCHAR    RssiNumber);
-
-VOID ATESampleRssi(
-	IN PRTMP_ADAPTER	pAd,
-	IN PRXWI_STRUC		pRxWI);
-
-
-#ifdef CONFIG_STA_SUPPORT
-VOID RTMPStationStop(
-    IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPStationStart(
-    IN  PRTMP_ADAPTER   pAd);
-#endif // CONFIG_STA_SUPPORT //
-#endif // __ATE_H__ //
diff --git a/drivers/staging/rt3070/rt_config.h b/drivers/staging/rt3070/rt_config.h
index 9e06417..3e8fcbd 100644
--- a/drivers/staging/rt3070/rt_config.h
+++ b/drivers/staging/rt3070/rt_config.h
@@ -1,121 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rt_config.h
-
-	Abstract:
-	Central header file to maintain all include files for all NDIS
-	miniport driver routines.
-
-	Revision History:
-	Who         When          What
-	--------    ----------    ----------------------------------------------
-	Paul Lin    08-01-2002    created
-
-*/
-#ifndef	__RT_CONFIG_H__
-#define	__RT_CONFIG_H__
-
-#include    "rtmp_type.h"
-#ifdef UCOS
-#include "includes.h"
-#include <stdio.h>
-#include 	"rt_ucos.h"
-#endif
-
-#ifdef LINUX
-#include	"rt_linux.h"
-#endif
-#include    "rtmp_def.h"
-#include    "rt28xx.h"
-
-
-#ifdef RT2870
-#include	"rt2870.h"
-#endif // RT2870 //
-
-#include    "oid.h"
-#include    "mlme.h"
-#include    "wpa.h"
-#include    "md5.h"
-#include    "rtmp.h"
-#include	"ap.h"
-#include	"dfs.h"
-#include	"chlist.h"
-#include	"spectrum.h"
-#ifdef MLME_EX
-#include	"mlme_ex_def.h"
-#include	"mlme_ex.h"
-#endif // MLME_EX //
-
-#undef AP_WSC_INCLUDED
-#undef STA_WSC_INCLUDED
-#undef WSC_INCLUDED
-
-
-#ifdef LEAP_SUPPORT
-#include    "leap.h"
-#endif // LEAP_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef BLOCK_NET_IF
-#include "netif_block.h"
-#endif // BLOCK_NET_IF //
-
-#ifdef IGMP_SNOOP_SUPPORT
-#include "igmp_snoop.h"
-#endif // IGMP_SNOOP_SUPPORT //
-
-#ifdef RALINK_ATE
-#include "rt_ate.h"
-#endif // RALINK_ATE //
-
-
-
-#if defined(AP_WSC_INCLUDED) || defined(STA_WSC_INCLUDED)
-#define WSC_INCLUDED
-#endif
-
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-#ifndef WPA_SUPPLICANT_SUPPORT
-#error "Build for being controlled by NetworkManager or wext, please set HAS_WPA_SUPPLICANT=y and HAS_NATIVE_WPA_SUPPLICANT_SUPPORT=y"
-#endif // WPA_SUPPLICANT_SUPPORT //
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-#endif // CONFIG_STA_SUPPORT //
-
-
-#ifdef IKANOS_VX_1X0
-#include	"vr_ikans.h"
-#endif // IKANOS_VX_1X0 //
-
-#endif	// __RT_CONFIG_H__
-
+#include "../rt2870/rt_config.h"
diff --git a/drivers/staging/rt3070/rt_linux.c b/drivers/staging/rt3070/rt_linux.c
index bf33853..6185f2e 100644
--- a/drivers/staging/rt3070/rt_linux.c
+++ b/drivers/staging/rt3070/rt_linux.c
@@ -1,1063 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#include "rt_config.h"
-
-ULONG	RTDebugLevel = RT_DEBUG_ERROR;
-
-BUILD_TIMER_FUNCTION(MlmePeriodicExec);
-//BUILD_TIMER_FUNCTION(MlmeRssiReportExec);
-BUILD_TIMER_FUNCTION(AsicRxAntEvalTimeout);
-BUILD_TIMER_FUNCTION(APSDPeriodicExec);
-BUILD_TIMER_FUNCTION(AsicRfTuningExec);
-#ifdef RT2870
-BUILD_TIMER_FUNCTION(BeaconUpdateExec);
-#endif // RT2870 //
-
-
-#ifdef CONFIG_STA_SUPPORT
-BUILD_TIMER_FUNCTION(BeaconTimeout);
-BUILD_TIMER_FUNCTION(ScanTimeout);
-BUILD_TIMER_FUNCTION(AuthTimeout);
-BUILD_TIMER_FUNCTION(AssocTimeout);
-BUILD_TIMER_FUNCTION(ReassocTimeout);
-BUILD_TIMER_FUNCTION(DisassocTimeout);
-BUILD_TIMER_FUNCTION(LinkDownExec);
-#ifdef LEAP_SUPPORT
-BUILD_TIMER_FUNCTION(LeapAuthTimeout);
-#endif
-BUILD_TIMER_FUNCTION(StaQuickResponeForRateUpExec);
-BUILD_TIMER_FUNCTION(WpaDisassocApAndBlockAssoc);
-#ifdef QOS_DLS_SUPPORT
-BUILD_TIMER_FUNCTION(DlsTimeoutAction);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-
-// for wireless system event message
-char const *pWirelessSysEventText[IW_SYS_EVENT_TYPE_NUM] = {
-	// system status event
-    "had associated successfully",							/* IW_ASSOC_EVENT_FLAG */
-    "had disassociated",									/* IW_DISASSOC_EVENT_FLAG */
-    "had deauthenticated",									/* IW_DEAUTH_EVENT_FLAG */
-    "had been aged-out and disassociated",					/* IW_AGEOUT_EVENT_FLAG */
-    "occurred CounterMeasures attack",						/* IW_COUNTER_MEASURES_EVENT_FLAG */
-    "occurred replay counter different in Key Handshaking",	/* IW_REPLAY_COUNTER_DIFF_EVENT_FLAG */
-    "occurred RSNIE different in Key Handshaking",			/* IW_RSNIE_DIFF_EVENT_FLAG */
-    "occurred MIC different in Key Handshaking",			/* IW_MIC_DIFF_EVENT_FLAG */
-    "occurred ICV error in RX",								/* IW_ICV_ERROR_EVENT_FLAG */
-    "occurred MIC error in RX",								/* IW_MIC_ERROR_EVENT_FLAG */
-	"Group Key Handshaking timeout",						/* IW_GROUP_HS_TIMEOUT_EVENT_FLAG */
-	"Pairwise Key Handshaking timeout",						/* IW_PAIRWISE_HS_TIMEOUT_EVENT_FLAG */
-	"RSN IE sanity check failure",							/* IW_RSNIE_SANITY_FAIL_EVENT_FLAG */
-	"set key done in WPA/WPAPSK",							/* IW_SET_KEY_DONE_WPA1_EVENT_FLAG */
-	"set key done in WPA2/WPA2PSK",                         /* IW_SET_KEY_DONE_WPA2_EVENT_FLAG */
-	"connects with our wireless client",                    /* IW_STA_LINKUP_EVENT_FLAG */
-	"disconnects with our wireless client",                 /* IW_STA_LINKDOWN_EVENT_FLAG */
-	"scan completed"										/* IW_SCAN_COMPLETED_EVENT_FLAG */
-	"scan terminate!! Busy!! Enqueue fail!!"				/* IW_SCAN_ENQUEUE_FAIL_EVENT_FLAG */
-	};
-
-// for wireless IDS_spoof_attack event message
-char const *pWirelessSpoofEventText[IW_SPOOF_EVENT_TYPE_NUM] = {
-    "detected conflict SSID",								/* IW_CONFLICT_SSID_EVENT_FLAG */
-    "detected spoofed association response",				/* IW_SPOOF_ASSOC_RESP_EVENT_FLAG */
-    "detected spoofed reassociation responses",				/* IW_SPOOF_REASSOC_RESP_EVENT_FLAG */
-    "detected spoofed probe response",						/* IW_SPOOF_PROBE_RESP_EVENT_FLAG */
-    "detected spoofed beacon",								/* IW_SPOOF_BEACON_EVENT_FLAG */
-    "detected spoofed disassociation",						/* IW_SPOOF_DISASSOC_EVENT_FLAG */
-    "detected spoofed authentication",						/* IW_SPOOF_AUTH_EVENT_FLAG */
-    "detected spoofed deauthentication",					/* IW_SPOOF_DEAUTH_EVENT_FLAG */
-    "detected spoofed unknown management frame",			/* IW_SPOOF_UNKNOWN_MGMT_EVENT_FLAG */
-	"detected replay attack"								/* IW_REPLAY_ATTACK_EVENT_FLAG */
-	};
-
-// for wireless IDS_flooding_attack event message
-char const *pWirelessFloodEventText[IW_FLOOD_EVENT_TYPE_NUM] = {
-	"detected authentication flooding",						/* IW_FLOOD_AUTH_EVENT_FLAG */
-    "detected association request flooding",				/* IW_FLOOD_ASSOC_REQ_EVENT_FLAG */
-    "detected reassociation request flooding",				/* IW_FLOOD_REASSOC_REQ_EVENT_FLAG */
-    "detected probe request flooding",						/* IW_FLOOD_PROBE_REQ_EVENT_FLAG */
-    "detected disassociation flooding",						/* IW_FLOOD_DISASSOC_EVENT_FLAG */
-    "detected deauthentication flooding",					/* IW_FLOOD_DEAUTH_EVENT_FLAG */
-    "detected 802.1x eap-request flooding"					/* IW_FLOOD_EAP_REQ_EVENT_FLAG */
-	};
-
-
-/* timeout -- ms */
-VOID RTMP_SetPeriodicTimer(
-	IN	NDIS_MINIPORT_TIMER *pTimer,
-	IN	unsigned long timeout)
-{
-	timeout = ((timeout*HZ) / 1000);
-	pTimer->expires = jiffies + timeout;
-	add_timer(pTimer);
-}
-
-/* convert NdisMInitializeTimer --> RTMP_OS_Init_Timer */
-VOID RTMP_OS_Init_Timer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	NDIS_MINIPORT_TIMER *pTimer,
-	IN	TIMER_FUNCTION function,
-	IN	PVOID data)
-{
-	init_timer(pTimer);
-    pTimer->data = (unsigned long)data;
-    pTimer->function = function;
-}
-
-
-VOID RTMP_OS_Add_Timer(
-	IN	NDIS_MINIPORT_TIMER		*pTimer,
-	IN	unsigned long timeout)
-{
-	if (timer_pending(pTimer))
-		return;
-
-	timeout = ((timeout*HZ) / 1000);
-	pTimer->expires = jiffies + timeout;
-	add_timer(pTimer);
-}
-
-VOID RTMP_OS_Mod_Timer(
-	IN	NDIS_MINIPORT_TIMER		*pTimer,
-	IN	unsigned long timeout)
-{
-	timeout = ((timeout*HZ) / 1000);
-	mod_timer(pTimer, jiffies + timeout);
-}
-
-VOID RTMP_OS_Del_Timer(
-	IN	NDIS_MINIPORT_TIMER		*pTimer,
-	OUT	BOOLEAN					*pCancelled)
-{
-	if (timer_pending(pTimer))
-	{
-		*pCancelled = del_timer_sync(pTimer);
-	}
-	else
-	{
-		*pCancelled = TRUE;
-	}
-
-}
-
-VOID RTMP_OS_Release_Packet(
-	IN	PRTMP_ADAPTER pAd,
-	IN	PQUEUE_ENTRY  pEntry)
-{
-	//RTMPFreeNdisPacket(pAd, (struct sk_buff *)pEntry);
-}
-
-// Unify all delay routine by using udelay
-VOID RTMPusecDelay(
-	IN	ULONG	usec)
-{
-	ULONG	i;
-
-	for (i = 0; i < (usec / 50); i++)
-		udelay(50);
-
-	if (usec % 50)
-		udelay(usec % 50);
-}
-
-void RTMP_GetCurrentSystemTime(LARGE_INTEGER *time)
-{
-	time->u.LowPart = jiffies;
-}
-
-// pAd MUST allow to be NULL
-NDIS_STATUS os_alloc_mem(
-	IN	PRTMP_ADAPTER pAd,
-	OUT	PUCHAR *mem,
-	IN	ULONG  size)
-{
-	*mem = (PUCHAR) kmalloc(size, GFP_ATOMIC);
-	if (*mem)
-		return (NDIS_STATUS_SUCCESS);
-	else
-		return (NDIS_STATUS_FAILURE);
-}
-
-// pAd MUST allow to be NULL
-NDIS_STATUS os_free_mem(
-	IN	PRTMP_ADAPTER pAd,
-	IN	PUCHAR mem)
-{
-
-	ASSERT(mem);
-	kfree(mem);
-	return (NDIS_STATUS_SUCCESS);
-}
-
-
-PNDIS_PACKET RTMP_AllocateFragPacketBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length)
-{
-	struct sk_buff *pkt;
-
-	pkt = dev_alloc_skb(Length);
-
-	if (pkt == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("can't allocate frag rx %ld size packet\n",Length));
-	}
-
-	if (pkt)
-	{
-		RTMP_SET_PACKET_SOURCE(OSPKT_TO_RTPKT(pkt), PKTSRC_NDIS);
-	}
-
-	return (PNDIS_PACKET) pkt;
-}
-
-
-PNDIS_PACKET RTMP_AllocateTxPacketBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress)
-{
-	struct sk_buff *pkt;
-
-	pkt = dev_alloc_skb(Length);
-
-	if (pkt == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("can't allocate tx %ld size packet\n",Length));
-	}
-
-	if (pkt)
-	{
-		RTMP_SET_PACKET_SOURCE(OSPKT_TO_RTPKT(pkt), PKTSRC_NDIS);
-		*VirtualAddress = (PVOID) pkt->data;
-	}
-	else
-	{
-		*VirtualAddress = (PVOID) NULL;
-	}
-
-	return (PNDIS_PACKET) pkt;
-}
-
-
-VOID build_tx_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR	pFrame,
-	IN	ULONG	FrameLen)
-{
-
-	struct sk_buff	*pTxPkt;
-
-	ASSERT(pPacket);
-	pTxPkt = RTPKT_TO_OSPKT(pPacket);
-
-	NdisMoveMemory(skb_put(pTxPkt, FrameLen), pFrame, FrameLen);
-}
-
-VOID	RTMPFreeAdapter(
-	IN	PRTMP_ADAPTER	pAd)
-{
-    POS_COOKIE os_cookie;
-	int index;
-
-	os_cookie=(POS_COOKIE)pAd->OS_Cookie;
-
-	kfree(pAd->BeaconBuf);
-
-
-	NdisFreeSpinLock(&pAd->MgmtRingLock);
-
-
-	for (index =0 ; index < NUM_OF_TX_RING; index++)
-	{
-    	NdisFreeSpinLock(&pAd->TxSwQueueLock[index]);
-		NdisFreeSpinLock(&pAd->DeQueueLock[index]);
-		pAd->DeQueueRunning[index] = FALSE;
-	}
-
-	NdisFreeSpinLock(&pAd->irq_lock);
-
-
-	vfree(pAd); // pci_free_consistent(os_cookie->pci_dev,sizeof(RTMP_ADAPTER),pAd,os_cookie->pAd_pa);
-	kfree(os_cookie);
-}
-
-BOOLEAN OS_Need_Clone_Packet(void)
-{
-	return (FALSE);
-}
-
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		clone an input NDIS PACKET to another one. The new internally created NDIS PACKET
-		must have only one NDIS BUFFER
-		return - byte copied. 0 means can't create NDIS PACKET
-		NOTE: internally created NDIS_PACKET should be destroyed by RTMPFreeNdisPacket
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pInsAMSDUHdr	EWC A-MSDU format has extra 14-bytes header. if TRUE, insert this 14-byte hdr in front of MSDU.
-		*pSrcTotalLen			return total packet length. This lenght is calculated with 802.3 format packet.
-
-	Return Value:
-		NDIS_STATUS_SUCCESS
-		NDIS_STATUS_FAILURE
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS RTMPCloneNdisPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	BOOLEAN			pInsAMSDUHdr,
-	IN	PNDIS_PACKET	pInPacket,
-	OUT PNDIS_PACKET   *ppOutPacket)
-{
-
-	struct sk_buff *pkt;
-
-	ASSERT(pInPacket);
-	ASSERT(ppOutPacket);
-
-	// 1. Allocate a packet
-	pkt = dev_alloc_skb(2048);
-
-	if (pkt == NULL)
-	{
-		return NDIS_STATUS_FAILURE;
-	}
-
- 	skb_put(pkt, GET_OS_PKT_LEN(pInPacket));
-	NdisMoveMemory(pkt->data, GET_OS_PKT_DATAPTR(pInPacket), GET_OS_PKT_LEN(pInPacket));
-	*ppOutPacket = OSPKT_TO_RTPKT(pkt);
-
-
-	RTMP_SET_PACKET_SOURCE(OSPKT_TO_RTPKT(pkt), PKTSRC_NDIS);
-
-	printk("###Clone###\n");
-
-	return NDIS_STATUS_SUCCESS;
-}
-
-
-// the allocated NDIS PACKET must be freed via RTMPFreeNdisPacket()
-NDIS_STATUS RTMPAllocateNdisPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT PNDIS_PACKET   *ppPacket,
-	IN	PUCHAR			pHeader,
-	IN	UINT			HeaderLen,
-	IN	PUCHAR			pData,
-	IN	UINT			DataLen)
-{
-	PNDIS_PACKET	pPacket;
-	ASSERT(pData);
-	ASSERT(DataLen);
-
-	// 1. Allocate a packet
-	pPacket = (PNDIS_PACKET *) dev_alloc_skb(HeaderLen + DataLen + TXPADDING_SIZE);
-	if (pPacket == NULL)
- 	{
-		*ppPacket = NULL;
-#ifdef DEBUG
-		printk("RTMPAllocateNdisPacket Fail\n\n");
-#endif
-		return NDIS_STATUS_FAILURE;
-	}
-
-	// 2. clone the frame content
-	if (HeaderLen > 0)
-		NdisMoveMemory(GET_OS_PKT_DATAPTR(pPacket), pHeader, HeaderLen);
-	if (DataLen > 0)
-		NdisMoveMemory(GET_OS_PKT_DATAPTR(pPacket) + HeaderLen, pData, DataLen);
-
-	// 3. update length of packet
- 	skb_put(GET_OS_PKT_TYPE(pPacket), HeaderLen+DataLen);
-
-	RTMP_SET_PACKET_SOURCE(pPacket, PKTSRC_NDIS);
-//	printk("%s : pPacket = %p, len = %d\n", __FUNCTION__, pPacket, GET_OS_PKT_LEN(pPacket));
-	*ppPacket = pPacket;
-	return NDIS_STATUS_SUCCESS;
-}
-
-/*
-  ========================================================================
-  Description:
-	This routine frees a miniport internally allocated NDIS_PACKET and its
-	corresponding NDIS_BUFFER and allocated memory.
-  ========================================================================
-*/
-VOID RTMPFreeNdisPacket(
-	IN PRTMP_ADAPTER pAd,
-	IN PNDIS_PACKET  pPacket)
-{
-	dev_kfree_skb_any(RTPKT_TO_OSPKT(pPacket));
-}
-
-
-// IRQL = DISPATCH_LEVEL
-// NOTE: we do have an assumption here, that Byte0 and Byte1 always reasid at the same
-//			 scatter gather buffer
-NDIS_STATUS Sniff2BytesFromNdisBuffer(
-	IN	PNDIS_BUFFER	pFirstBuffer,
-	IN	UCHAR			DesiredOffset,
-	OUT PUCHAR			pByte0,
-	OUT PUCHAR			pByte1)
-{
-    *pByte0 = *(PUCHAR)(pFirstBuffer + DesiredOffset);
-    *pByte1 = *(PUCHAR)(pFirstBuffer + DesiredOffset + 1);
-
-	return NDIS_STATUS_SUCCESS;
-}
-
-
-void RTMP_QueryPacketInfo(
-	IN  PNDIS_PACKET pPacket,
-	OUT PACKET_INFO  *pPacketInfo,
-	OUT PUCHAR		 *pSrcBufVA,
-	OUT	UINT		 *pSrcBufLen)
-{
-	pPacketInfo->BufferCount = 1;
-	pPacketInfo->pFirstBuffer = GET_OS_PKT_DATAPTR(pPacket);
-	pPacketInfo->PhysicalBufferCount = 1;
-	pPacketInfo->TotalPacketLength = GET_OS_PKT_LEN(pPacket);
-
-	*pSrcBufVA = GET_OS_PKT_DATAPTR(pPacket);
-	*pSrcBufLen = GET_OS_PKT_LEN(pPacket);
-}
-
-void RTMP_QueryNextPacketInfo(
-	IN  PNDIS_PACKET *ppPacket,
-	OUT PACKET_INFO  *pPacketInfo,
-	OUT PUCHAR		 *pSrcBufVA,
-	OUT	UINT		 *pSrcBufLen)
-{
-	PNDIS_PACKET pPacket = NULL;
-
-	if (*ppPacket)
-		pPacket = GET_OS_PKT_NEXT(*ppPacket);
-
-	if (pPacket)
-	{
-		pPacketInfo->BufferCount = 1;
-		pPacketInfo->pFirstBuffer = GET_OS_PKT_DATAPTR(pPacket);
-		pPacketInfo->PhysicalBufferCount = 1;
-		pPacketInfo->TotalPacketLength = GET_OS_PKT_LEN(pPacket);
-
-		*pSrcBufVA = GET_OS_PKT_DATAPTR(pPacket);
-		*pSrcBufLen = GET_OS_PKT_LEN(pPacket);
-		*ppPacket = GET_OS_PKT_NEXT(pPacket);
-	}
-	else
-	{
-		pPacketInfo->BufferCount = 0;
-		pPacketInfo->pFirstBuffer = NULL;
-		pPacketInfo->PhysicalBufferCount = 0;
-		pPacketInfo->TotalPacketLength = 0;
-
-		*pSrcBufVA = NULL;
-		*pSrcBufLen = 0;
-		*ppPacket = NULL;
-	}
-}
-
-// not yet support MBSS
-PNET_DEV get_netdev_from_bssid(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			FromWhichBSSID)
-{
-    PNET_DEV dev_p = NULL;
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		dev_p = pAd->net_dev;
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	ASSERT(dev_p);
-	return dev_p; /* return one of MBSS */
-}
-
-PNDIS_PACKET DuplicatePacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UCHAR			FromWhichBSSID)
-{
-	struct sk_buff	*skb;
-	PNDIS_PACKET	pRetPacket = NULL;
-	USHORT			DataSize;
-	UCHAR			*pData;
-
-	DataSize = (USHORT) GET_OS_PKT_LEN(pPacket);
-	pData = (PUCHAR) GET_OS_PKT_DATAPTR(pPacket);
-
-
-	skb = skb_clone(RTPKT_TO_OSPKT(pPacket), MEM_ALLOC_FLAG);
-	if (skb)
-	{
-		skb->dev = get_netdev_from_bssid(pAd, FromWhichBSSID);
-		pRetPacket = OSPKT_TO_RTPKT(skb);
-	}
-
-	return pRetPacket;
-
-}
-
-PNDIS_PACKET duplicate_pkt(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pHeader802_3,
-    IN  UINT            HdrLen,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	IN	UCHAR			FromWhichBSSID)
-{
-	struct sk_buff	*skb;
-	PNDIS_PACKET	pPacket = NULL;
-
-
-	if ((skb = __dev_alloc_skb(HdrLen + DataSize + 2, MEM_ALLOC_FLAG)) != NULL)
-	{
-		skb_reserve(skb, 2);
-		NdisMoveMemory(skb->tail, pHeader802_3, HdrLen);
-		skb_put(skb, HdrLen);
-		NdisMoveMemory(skb->tail, pData, DataSize);
-		skb_put(skb, DataSize);
-		skb->dev = get_netdev_from_bssid(pAd, FromWhichBSSID);
-		pPacket = OSPKT_TO_RTPKT(skb);
-	}
-
-	return pPacket;
-}
-
-
-#define TKIP_TX_MIC_SIZE		8
-PNDIS_PACKET duplicate_pkt_with_TKIP_MIC(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-	struct sk_buff	*skb, *newskb;
-
-
-	skb = RTPKT_TO_OSPKT(pPacket);
-	if (skb_tailroom(skb) < TKIP_TX_MIC_SIZE)
-	{
-		// alloc a new skb and copy the packet
-		newskb = skb_copy_expand(skb, skb_headroom(skb), TKIP_TX_MIC_SIZE, GFP_ATOMIC);
-		dev_kfree_skb_any(skb);
-		if (newskb == NULL)
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("Extend Tx.MIC for packet failed!, dropping packet!\n"));
-			return NULL;
-		}
-		skb = newskb;
-	}
-
-	return OSPKT_TO_RTPKT(skb);
-}
-
-
-
-
-PNDIS_PACKET ClonePacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize)
-{
-	struct sk_buff	*pRxPkt;
-	struct sk_buff	*pClonedPkt;
-
-	ASSERT(pPacket);
-	pRxPkt = RTPKT_TO_OSPKT(pPacket);
-
-	// clone the packet
-	pClonedPkt = skb_clone(pRxPkt, MEM_ALLOC_FLAG);
-
-	if (pClonedPkt)
-	{
-    	// set the correct dataptr and data len
-    	pClonedPkt->dev = pRxPkt->dev;
-    	pClonedPkt->data = pData;
-    	pClonedPkt->len = DataSize;
-    	pClonedPkt->tail = pClonedPkt->data + pClonedPkt->len;
-		ASSERT(DataSize < 1530);
-	}
-	return pClonedPkt;
-}
-
-//
-// change OS packet DataPtr and DataLen
-//
-void  update_os_packet_info(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN  UCHAR			FromWhichBSSID)
-{
-	struct sk_buff	*pOSPkt;
-
-	ASSERT(pRxBlk->pRxPacket);
-	pOSPkt = RTPKT_TO_OSPKT(pRxBlk->pRxPacket);
-
-	pOSPkt->dev = get_netdev_from_bssid(pAd, FromWhichBSSID);
-	pOSPkt->data = pRxBlk->pData;
-	pOSPkt->len = pRxBlk->DataSize;
-	pOSPkt->tail = pOSPkt->data + pOSPkt->len;
-}
-
-
-void wlan_802_11_to_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	PUCHAR			pHeader802_3,
-	IN  UCHAR			FromWhichBSSID)
-{
-	struct sk_buff	*pOSPkt;
-
-	ASSERT(pRxBlk->pRxPacket);
-	ASSERT(pHeader802_3);
-
-	pOSPkt = RTPKT_TO_OSPKT(pRxBlk->pRxPacket);
-
-	pOSPkt->dev = get_netdev_from_bssid(pAd, FromWhichBSSID);
-	pOSPkt->data = pRxBlk->pData;
-	pOSPkt->len = pRxBlk->DataSize;
-	pOSPkt->tail = pOSPkt->data + pOSPkt->len;
-
-	//
-	// copy 802.3 header
-	//
-	//
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		NdisMoveMemory(skb_push(pOSPkt, LENGTH_802_3), pHeader802_3, LENGTH_802_3);
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-
-
-void announce_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-
-	struct sk_buff	*pRxPkt;
-
-	ASSERT(pPacket);
-
-	pRxPkt = RTPKT_TO_OSPKT(pPacket);
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-    /* Push up the protocol stack */
-#ifdef IKANOS_VX_1X0
-	IKANOS_DataFrameRx(pAd, pRxPkt->dev, pRxPkt, pRxPkt->len);
-#else
-	pRxPkt->protocol = eth_type_trans(pRxPkt, pRxPkt->dev);
-
-//#ifdef CONFIG_5VT_ENHANCE
-//	*(int*)(pRxPkt->cb) = BRIDGE_TAG;
-//#endif
-	netif_rx(pRxPkt);
-#endif // IKANOS_VX_1X0 //
-}
-
-
-PRTMP_SCATTER_GATHER_LIST
-rt_get_sg_list_from_packet(PNDIS_PACKET pPacket, RTMP_SCATTER_GATHER_LIST *sg)
-{
-	sg->NumberOfElements = 1;
-	sg->Elements[0].Address =  GET_OS_PKT_DATAPTR(pPacket);
-	sg->Elements[0].Length = GET_OS_PKT_LEN(pPacket);
-	return (sg);
-}
-
-void hex_dump(char *str, unsigned char *pSrcBufVA, unsigned int SrcBufLen)
-{
-	unsigned char *pt;
-	int x;
-
-	if (RTDebugLevel < RT_DEBUG_TRACE)
-		return;
-
-	pt = pSrcBufVA;
-	printk("%s: %p, len = %d\n",str,  pSrcBufVA, SrcBufLen);
-	for (x=0; x<SrcBufLen; x++)
-	{
-		if (x % 16 == 0)
-			printk("0x%04x : ", x);
-		printk("%02x ", ((unsigned char)pt[x]));
-		if (x%16 == 15) printk("\n");
-	}
-	printk("\n");
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Send log message through wireless event
-
-		Support standard iw_event with IWEVCUSTOM. It is used below.
-
-		iwreq_data.data.flags is used to store event_flag that is defined by user.
-		iwreq_data.data.length is the length of the event log.
-
-		The format of the event log is composed of the entry's MAC address and
-		the desired log message (refer to pWirelessEventText).
-
-			ex: 11:22:33:44:55:66 has associated successfully
-
-		p.s. The requirement of Wireless Extension is v15 or newer.
-
-	========================================================================
-*/
-VOID RTMPSendWirelessEvent(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Event_flag,
-	IN	PUCHAR 			pAddr,
-	IN	UCHAR			BssIdx,
-	IN	CHAR			Rssi)
-{
-#if WIRELESS_EXT >= 15
-
-	union 	iwreq_data      wrqu;
-	PUCHAR 	pBuf = NULL, pBufPtr = NULL;
-	USHORT	event, type, BufLen;
-	UCHAR	event_table_len = 0;
-
-	type = Event_flag & 0xFF00;
-	event = Event_flag & 0x00FF;
-
-	switch (type)
-	{
-		case IW_SYS_EVENT_FLAG_START:
-			event_table_len = IW_SYS_EVENT_TYPE_NUM;
-			break;
-
-		case IW_SPOOF_EVENT_FLAG_START:
-			event_table_len = IW_SPOOF_EVENT_TYPE_NUM;
-			break;
-
-		case IW_FLOOD_EVENT_FLAG_START:
-			event_table_len = IW_FLOOD_EVENT_TYPE_NUM;
-			break;
-	}
-
-	if (event_table_len == 0)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s : The type(%0x02x) is not valid.\n", __FUNCTION__, type));
-		return;
-	}
-
-	if (event >= event_table_len)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("%s : The event(%0x02x) is not valid.\n", __FUNCTION__, event));
-		return;
-	}
-
-	//Allocate memory and copy the msg.
-	if((pBuf = kmalloc(IW_CUSTOM_MAX_LEN, GFP_ATOMIC)) != NULL)
-	{
-		//Prepare the payload
-		memset(pBuf, 0, IW_CUSTOM_MAX_LEN);
-
-		pBufPtr = pBuf;
-
-		if (pAddr)
-			pBufPtr += sprintf(pBufPtr, "(RT2860) STA(%02x:%02x:%02x:%02x:%02x:%02x) ", PRINT_MAC(pAddr));
-		else if (BssIdx < MAX_MBSSID_NUM)
-			pBufPtr += sprintf(pBufPtr, "(RT2860) BSS(ra%d) ", BssIdx);
-		else
-			pBufPtr += sprintf(pBufPtr, "(RT2860) ");
-
-		if (type == IW_SYS_EVENT_FLAG_START)
-			pBufPtr += sprintf(pBufPtr, "%s", pWirelessSysEventText[event]);
-		else if (type == IW_SPOOF_EVENT_FLAG_START)
-			pBufPtr += sprintf(pBufPtr, "%s (RSSI=%d)", pWirelessSpoofEventText[event], Rssi);
-		else if (type == IW_FLOOD_EVENT_FLAG_START)
-			pBufPtr += sprintf(pBufPtr, "%s", pWirelessFloodEventText[event]);
-		else
-			pBufPtr += sprintf(pBufPtr, "%s", "unknown event");
-
-		pBufPtr[pBufPtr - pBuf] = '\0';
-		BufLen = pBufPtr - pBuf;
-
-		memset(&wrqu, 0, sizeof(wrqu));
-	    wrqu.data.flags = Event_flag;
-		wrqu.data.length = BufLen;
-
-		//send wireless event
-	    wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, pBuf);
-
-		//DBGPRINT(RT_DEBUG_TRACE, ("%s : %s\n", __FUNCTION__, pBuf));
-
-		kfree(pBuf);
-	}
-	else
-		DBGPRINT(RT_DEBUG_ERROR, ("%s : Can't allocate memory for wireless event.\n", __FUNCTION__));
-#else
-	DBGPRINT(RT_DEBUG_ERROR, ("%s : The Wireless Extension MUST be v15 or newer.\n", __FUNCTION__));
-#endif  /* WIRELESS_EXT >= 15 */
-}
-
-
-#ifdef CONFIG_STA_SUPPORT
-void send_monitor_packets(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk)
-{
-    struct sk_buff	*pOSPkt;
-    wlan_ng_prism2_header *ph;
-    int rate_index = 0;
-    USHORT header_len = 0;
-    UCHAR temp_header[40] = {0};
-
-    u_int32_t ralinkrate[256] = {2,4,11,22, 12,18,24,36,48,72,96,  108,   109, 110, 111, 112, 13, 26, 39, 52,78,104, 117, 130, 26, 52, 78,104, 156, 208, 234, 260, 27, 54,81,108,162, 216, 243, 270, // Last 38
-	54, 108, 162, 216, 324, 432, 486, 540,  14, 29, 43, 57, 87, 115, 130, 144, 29, 59,87,115, 173, 230,260, 288, 30, 60,90,120,180,240,270,300,60,120,180,240,360,480,540,600, 0,1,2,3,4,5,6,7,8,9,10,
-	11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80};
-
-
-    ASSERT(pRxBlk->pRxPacket);
-    if (pRxBlk->DataSize < 10)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("%s : Size is too small! (%d)\n", __FUNCTION__, pRxBlk->DataSize));
-		goto err_free_sk_buff;
-    }
-
-    if (pRxBlk->DataSize + sizeof(wlan_ng_prism2_header) > RX_BUFFER_AGGRESIZE)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("%s : Size is too large! (%d)\n", __FUNCTION__, pRxBlk->DataSize + sizeof(wlan_ng_prism2_header)));
-		goto err_free_sk_buff;
-    }
-
-    pOSPkt = RTPKT_TO_OSPKT(pRxBlk->pRxPacket);
-	pOSPkt->dev = get_netdev_from_bssid(pAd, BSS0);
-    if (pRxBlk->pHeader->FC.Type == BTYPE_DATA)
-    {
-        pRxBlk->DataSize -= LENGTH_802_11;
-        if ((pRxBlk->pHeader->FC.ToDs == 1) &&
-            (pRxBlk->pHeader->FC.FrDs == 1))
-            header_len = LENGTH_802_11_WITH_ADDR4;
-        else
-            header_len = LENGTH_802_11;
-
-        // QOS
-    	if (pRxBlk->pHeader->FC.SubType & 0x08)
-    	{
-    	    header_len += 2;
-    		// Data skip QOS contorl field
-    		pRxBlk->DataSize -=2;
-    	}
-
-    	// Order bit: A-Ralink or HTC+
-    	if (pRxBlk->pHeader->FC.Order)
-    	{
-    	    header_len += 4;
-			// Data skip HTC contorl field
-			pRxBlk->DataSize -= 4;
-    	}
-
-        // Copy Header
-        if (header_len <= 40)
-            NdisMoveMemory(temp_header, pRxBlk->pData, header_len);
-
-        // skip HW padding
-    	if (pRxBlk->RxD.L2PAD)
-    	    pRxBlk->pData += (header_len + 2);
-        else
-            pRxBlk->pData += header_len;
-    } //end if
-
-
-	if (pRxBlk->DataSize < pOSPkt->len) {
-        skb_trim(pOSPkt,pRxBlk->DataSize);
-    } else {
-        skb_put(pOSPkt,(pRxBlk->DataSize - pOSPkt->len));
-    } //end if
-
-    if ((pRxBlk->pData - pOSPkt->data) > 0) {
-	    skb_put(pOSPkt,(pRxBlk->pData - pOSPkt->data));
-	    skb_pull(pOSPkt,(pRxBlk->pData - pOSPkt->data));
-    } //end if
-
-    if (skb_headroom(pOSPkt) < (sizeof(wlan_ng_prism2_header)+ header_len)) {
-        if (pskb_expand_head(pOSPkt, (sizeof(wlan_ng_prism2_header) + header_len), 0, GFP_ATOMIC)) {
-	        DBGPRINT(RT_DEBUG_ERROR, ("%s : Reallocate header size of sk_buff fail!\n", __FUNCTION__));
-			goto err_free_sk_buff;
-	    } //end if
-    } //end if
-
-    if (header_len > 0)
-        NdisMoveMemory(skb_push(pOSPkt, header_len), temp_header, header_len);
-
-    ph = (wlan_ng_prism2_header *) skb_push(pOSPkt, sizeof(wlan_ng_prism2_header));
-	NdisZeroMemory(ph, sizeof(wlan_ng_prism2_header));
-
-    ph->msgcode		    = DIDmsg_lnxind_wlansniffrm;
-	ph->msglen		    = sizeof(wlan_ng_prism2_header);
-	strcpy(ph->devname, pAd->net_dev->name);
-
-    ph->hosttime.did = DIDmsg_lnxind_wlansniffrm_hosttime;
-	ph->hosttime.status = 0;
-	ph->hosttime.len = 4;
-	ph->hosttime.data = jiffies;
-
-	ph->mactime.did = DIDmsg_lnxind_wlansniffrm_mactime;
-	ph->mactime.status = 0;
-	ph->mactime.len = 0;
-	ph->mactime.data = 0;
-
-    ph->istx.did = DIDmsg_lnxind_wlansniffrm_istx;
-	ph->istx.status = 0;
-	ph->istx.len = 0;
-	ph->istx.data = 0;
-
-    ph->channel.did = DIDmsg_lnxind_wlansniffrm_channel;
-	ph->channel.status = 0;
-	ph->channel.len = 4;
-
-    ph->channel.data = (u_int32_t)pAd->CommonCfg.Channel;
-
-    ph->rssi.did = DIDmsg_lnxind_wlansniffrm_rssi;
-	ph->rssi.status = 0;
-	ph->rssi.len = 4;
-    ph->rssi.data = (u_int32_t)RTMPMaxRssi(pAd, ConvertToRssi(pAd, pRxBlk->pRxWI->RSSI0, RSSI_0), ConvertToRssi(pAd, pRxBlk->pRxWI->RSSI1, RSSI_1), ConvertToRssi(pAd, pRxBlk->pRxWI->RSSI2, RSSI_2));;
-
-	ph->signal.did = DIDmsg_lnxind_wlansniffrm_signal;
-	ph->signal.status = 0;
-	ph->signal.len = 4;
-	ph->signal.data = 0; //rssi + noise;
-
-	ph->noise.did = DIDmsg_lnxind_wlansniffrm_noise;
-	ph->noise.status = 0;
-	ph->noise.len = 4;
-	ph->noise.data = 0;
-
-#ifdef DOT11_N_SUPPORT
-    if (pRxBlk->pRxWI->PHYMODE >= MODE_HTMIX)
-    {
-    	rate_index = 16 + ((UCHAR)pRxBlk->pRxWI->BW *16) + ((UCHAR)pRxBlk->pRxWI->ShortGI *32) + ((UCHAR)pRxBlk->pRxWI->MCS);
-    }
-    else
-#endif // DOT11_N_SUPPORT //
-	if (pRxBlk->pRxWI->PHYMODE == MODE_OFDM)
-    	rate_index = (UCHAR)(pRxBlk->pRxWI->MCS) + 4;
-    else
-    	rate_index = (UCHAR)(pRxBlk->pRxWI->MCS);
-    if (rate_index < 0)
-        rate_index = 0;
-    if (rate_index > 255)
-        rate_index = 255;
-
-	ph->rate.did = DIDmsg_lnxind_wlansniffrm_rate;
-	ph->rate.status = 0;
-	ph->rate.len = 4;
-    ph->rate.data = ralinkrate[rate_index];
-
-	ph->frmlen.did = DIDmsg_lnxind_wlansniffrm_frmlen;
-    ph->frmlen.status = 0;
-	ph->frmlen.len = 4;
-	ph->frmlen.data	= (u_int32_t)pRxBlk->DataSize;
-
-
-    pOSPkt->pkt_type = PACKET_OTHERHOST;
-    pOSPkt->protocol = eth_type_trans(pOSPkt, pOSPkt->dev);
-    pOSPkt->ip_summed = CHECKSUM_NONE;
-    netif_rx(pOSPkt);
-
-    return;
-
-err_free_sk_buff:
-	RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-	return;
-
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-void rtmp_os_thread_init(PUCHAR pThreadName, PVOID pNotify)
-{
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-	daemonize(pThreadName /*"%s",pAd->net_dev->name*/);
-
-	allow_signal(SIGTERM);
-	allow_signal(SIGKILL);
-	current->flags |= PF_NOFREEZE;
-#else
-	unsigned long flags;
-
-	daemonize();
-	reparent_to_init();
-	strcpy(current->comm, pThreadName);
-
-	siginitsetinv(&current->blocked, sigmask(SIGTERM) | sigmask(SIGKILL));
-
-	/* Allow interception of SIGKILL only
-	 * Don't allow other signals to interrupt the transmission */
-#if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,22)
-	spin_lock_irqsave(&current->sigmask_lock, flags);
-	flush_signals(current);
-	recalc_sigpending(current);
-	spin_unlock_irqrestore(&current->sigmask_lock, flags);
-#endif
-#endif
-
-    /* signal that we've started the thread */
-	complete(pNotify);
-
-}
-
-void RTMP_IndicateMediaState(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	if (pAd->CommonCfg.bWirelessEvent)
-	{
-		if (pAd->IndicateMediaState == NdisMediaStateConnected)
-		{
-			RTMPSendWirelessEvent(pAd, IW_STA_LINKUP_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-		}
-		else
-		{
-			RTMPSendWirelessEvent(pAd, IW_STA_LINKDOWN_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-		}
-	}
-}
-
+#include "../rt2870/rt_linux.c"
diff --git a/drivers/staging/rt3070/rt_linux.h b/drivers/staging/rt3070/rt_linux.h
index 0540d02..9f7efee 100644
--- a/drivers/staging/rt3070/rt_linux.h
+++ b/drivers/staging/rt3070/rt_linux.h
@@ -1,887 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-/***********************************************************************/
-/*                                                                     */
-/*   Program:    rt_linux.c                                            */
-/*   Created:    4/21/2006 1:17:38 PM                                  */
-/*   Author:     Wu Xi-Kun                                             */
-/*   Comments:   `description`                                         */
-/*                                                                     */
-/*---------------------------------------------------------------------*/
-/*                                                                     */
-/* History:                                                            */
-/*    Revision 1.1 4/21/2006 1:17:38 PM  xsikun                        */
-/*    Initial revision                                                 */
-/*                                                                     */
-/***********************************************************************/
-
-#include "rtmp_type.h"
-#include <linux/module.h>
-#include <linux/version.h>
-#include <linux/kernel.h>
-
-#include <linux/spinlock.h>
-#include <linux/init.h>
-#include <linux/string.h>
-#include <linux/timer.h>
-#include <linux/errno.h>
-#include <linux/slab.h>
-#include <linux/interrupt.h>
-#include <linux/pci.h>
-#include <linux/netdevice.h>
-#include <linux/etherdevice.h>
-#include <linux/skbuff.h>
-#include <linux/ethtool.h>
-#include <linux/wireless.h>
-#include <linux/proc_fs.h>
-#include <linux/delay.h>
-#include <linux/if_arp.h>
-#include <linux/ctype.h>
-#include <linux/vmalloc.h>
-
-
-#include <linux/wireless.h>
-#include <net/iw_handler.h>
-
-// load firmware
-#define __KERNEL_SYSCALLS__
-#include <linux/unistd.h>
-#include <asm/uaccess.h>
-
-
-#define MEM_ALLOC_FLAG      (GFP_ATOMIC) //(GFP_DMA | GFP_ATOMIC)
-
-#ifndef IFNAMSIZ
-#define IFNAMSIZ 16
-#endif
-
-//#define CONFIG_CKIP_SUPPORT
-
-#undef __inline
-#define __inline	   static inline
-
-typedef int (*HARD_START_XMIT_FUNC)(struct sk_buff *skb, struct net_device *net_dev);
-
-// add by kathy
-
-#ifdef CONFIG_STA_SUPPORT
-
-#ifdef RT2870
-#define STA_PROFILE_PATH			"/etc/Wireless/RT2870STA/RT2870STA.dat"
-#define STA_RT2870_IMAGE_FILE_NAME  "/etc/Wireless/RT2870STA/rt2870.bin"
-#define STA_NIC_DEVICE_NAME			"RT2870STA"
-#define STA_DRIVER_VERSION			"2.0.1.0"
-#ifdef MULTIPLE_CARD_SUPPORT
-#define CARD_INFO_PATH			"/etc/Wireless/RT2870STA/RT2870STACard.dat"
-#endif // MULTIPLE_CARD_SUPPORT //
-#endif // RT2870 //
-
-#endif // CONFIG_STA_SUPPORT //
-
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-
-#define RTMP_TIME_AFTER(a,b)		\
-	(typecheck(unsigned long, (unsigned long)a) && \
-	 typecheck(unsigned long, (unsigned long)b) && \
-	 ((long)(b) - (long)(a) < 0))
-
-#define RTMP_TIME_AFTER_EQ(a,b)	\
-	(typecheck(unsigned long, (unsigned long)a) && \
-	 typecheck(unsigned long, (unsigned long)b) && \
-	 ((long)(a) - (long)(b) >= 0))
-#define RTMP_TIME_BEFORE(a,b)	RTMP_TIME_AFTER_EQ(b,a)
-#else
-#define RTMP_TIME_AFTER(a,b) time_after(a, b)
-#endif
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-#define RT_MOD_INC_USE_COUNT() \
-	if (!try_module_get(THIS_MODULE)) \
-	{ \
-		DBGPRINT(RT_DEBUG_ERROR, ("%s: cannot reserve module\n", __FUNCTION__)); \
-		return -1; \
-	}
-
-#define RT_MOD_DEC_USE_COUNT() module_put(THIS_MODULE);
-#else
-#define RT_MOD_INC_USE_COUNT()	MOD_INC_USE_COUNT;
-#define RT_MOD_DEC_USE_COUNT() MOD_DEC_USE_COUNT;
-#endif
-
-#define OS_HZ			HZ
-
-#define ETH_LENGTH_OF_ADDRESS	6
-
-#define IN
-#define OUT
-
-#define NDIS_STATUS                             INT
-#define NDIS_STATUS_SUCCESS                     0x00
-#define NDIS_STATUS_FAILURE                     0x01
-#define NDIS_STATUS_INVALID_DATA				0x02
-#define NDIS_STATUS_RESOURCES                   0x03
-
-#define MIN_NET_DEVICE_FOR_AID			0x00		//0x00~0x3f
-#define MIN_NET_DEVICE_FOR_MBSSID		0x00		//0x00,0x10,0x20,0x30
-#define MIN_NET_DEVICE_FOR_WDS			0x10		//0x40,0x50,0x60,0x70
-#define MIN_NET_DEVICE_FOR_APCLI		0x20
-#define MIN_NET_DEVICE_FOR_MESH			0x30
-#ifdef CONFIG_STA_SUPPORT
-#define MIN_NET_DEVICE_FOR_DLS			0x40
-#endif // CONFIG_STA_SUPPORT //
-
-
-#ifdef CONFIG_STA_SUPPORT
-#define NDIS_PACKET_TYPE_DIRECTED		0
-#define NDIS_PACKET_TYPE_MULTICAST		1
-#define NDIS_PACKET_TYPE_BROADCAST		2
-#define NDIS_PACKET_TYPE_ALL_MULTICAST	3
-#endif // CONFIG_STA_SUPPORT //
-
-struct os_lock  {
-	spinlock_t		lock;
-	unsigned long  	flags;
-};
-
-
-struct os_cookie {
-
-#ifdef RT2870
-	struct usb_device		*pUsb_Dev;
-
-	struct pid *		MLMEThr_pid;
-	struct pid *		RTUSBCmdThr_pid;
-	struct pid *		TimerQThr_pid;
-#endif // RT2870 //
-
-	struct tasklet_struct 	rx_done_task;
-	struct tasklet_struct 	mgmt_dma_done_task;
-	struct tasklet_struct 	ac0_dma_done_task;
-	struct tasklet_struct 	ac1_dma_done_task;
-	struct tasklet_struct 	ac2_dma_done_task;
-	struct tasklet_struct 	ac3_dma_done_task;
-	struct tasklet_struct 	hcca_dma_done_task;
-	struct tasklet_struct	tbtt_task;
-#ifdef RT2870
-	struct tasklet_struct	null_frame_complete_task;
-	struct tasklet_struct	rts_frame_complete_task;
-	struct tasklet_struct	pspoll_frame_complete_task;
-#endif // RT2870 //
-
-
-	unsigned long			apd_pid; //802.1x daemon pid
-	INT						ioctl_if_type;
-	INT 					ioctl_if;
-};
-
-typedef struct _VIRTUAL_ADAPTER
-{
-	struct net_device		*RtmpDev;
-	struct net_device		*VirtualDev;
-} VIRTUAL_ADAPTER, PVIRTUAL_ADAPTER;
-
-#undef  ASSERT
-#define ASSERT(x)                                                               \
-{                                                                               \
-    if (!(x))                                                                   \
-    {                                                                           \
-        printk(KERN_WARNING __FILE__ ":%d assert " #x "failed\n", __LINE__);    \
-    }                                                                           \
-}
-
-typedef struct os_cookie	* POS_COOKIE;
-typedef struct pci_dev 		* PPCI_DEV;
-typedef struct net_device	* PNET_DEV;
-typedef void				* PNDIS_PACKET;
-typedef char				NDIS_PACKET;
-typedef PNDIS_PACKET		* PPNDIS_PACKET;
-typedef	dma_addr_t			NDIS_PHYSICAL_ADDRESS;
-typedef	dma_addr_t			* PNDIS_PHYSICAL_ADDRESS;
-//typedef struct timer_list	RALINK_TIMER_STRUCT;
-//typedef struct timer_list	* PRALINK_TIMER_STRUCT;
-//typedef struct os_lock		NDIS_SPIN_LOCK;
-typedef spinlock_t			NDIS_SPIN_LOCK;
-typedef struct timer_list	NDIS_MINIPORT_TIMER;
-typedef void				* NDIS_HANDLE;
-typedef char 				* PNDIS_BUFFER;
-
-
-
-void hex_dump(char *str, unsigned char *pSrcBufVA, unsigned int SrcBufLen);
-
-dma_addr_t linux_pci_map_single(void *handle, void *ptr, size_t size, int sd_idx, int direction);
-void linux_pci_unmap_single(void *handle, dma_addr_t dma_addr, size_t size, int direction);
-
-
-////////////////////////////////////////
-// MOVE TO rtmp.h ?
-/////////////////////////////////////////
-#define PKTSRC_NDIS             0x7f
-#define PKTSRC_DRIVER           0x0f
-#define PRINT_MAC(addr)	\
-	addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]
-
-
-#define RT2860_PCI_DEVICE_ID		0x0601
-
-#ifdef RT2870
-#define PCI_MAP_SINGLE(_handle, _ptr, _size, _dir) (ULONG)0
-
-#define PCI_UNMAP_SINGLE(_handle, _ptr, _size, _dir)
-#endif // RT2870 //
-
-
-#define BEACON_FRAME_DMA_CACHE_WBACK(_ptr, _size)	\
-	dma_cache_wback(_ptr, _size)
-
-
-//////////////////////////////////////////
-//
-//////////////////////////////////////////
-
-
-#define NdisMIndicateStatus(_w, _x, _y, _z)
-
-
-typedef struct timer_list	RTMP_OS_TIMER;
-
-#ifdef RT2870
-/* ----------------- Timer Related MARCO ---------------*/
-// In RT2870, we have a lot of timer functions and will read/write register, it's
-//	not allowed in Linux USB sub-system to do it ( because of sleep issue when submit
-//  to ctrl pipe). So we need a wrapper function to take care it.
-
-typedef VOID (*RT2870_TIMER_HANDLE)(
-	IN  PVOID   SystemSpecific1,
-	IN  PVOID   FunctionContext,
-	IN  PVOID   SystemSpecific2,
-	IN  PVOID   SystemSpecific3);
-#endif // RT2870 //
-
-
-typedef struct  _RALINK_TIMER_STRUCT    {
-    RTMP_OS_TIMER		TimerObj;       // Ndis Timer object
-	BOOLEAN				Valid;			// Set to True when call RTMPInitTimer
-    BOOLEAN             State;          // True if timer cancelled
-    BOOLEAN	      		PeriodicType;	// True if timer is periodic timer
-    BOOLEAN             Repeat;         // True if periodic timer
-    ULONG               TimerValue;     // Timer value in milliseconds
-	ULONG				cookie;			// os specific object
-#ifdef RT2870
-	RT2870_TIMER_HANDLE	handle;
-	void				*pAd;
-#endif // RT2870 //
-}   RALINK_TIMER_STRUCT, *PRALINK_TIMER_STRUCT;
-
-
-#ifdef RT2870
-
-typedef enum _RT2870_KERNEL_THREAD_STATUS_
-{
-	RT2870_THREAD_UNKNOWN = 0,
-	RT2870_THREAD_INITED = 1,
-	RT2870_THREAD_RUNNING = 2,
-	RT2870_THREAD_STOPED = 4,
-}RT2870_KERNEL_THREAD_STATUS;
-
-#define RT2870_THREAD_CAN_DO_INSERT		(RT2870_THREAD_INITED |RT2870_THREAD_RUNNING)
-
-typedef struct _RT2870_TIMER_ENTRY_
-{
-	RALINK_TIMER_STRUCT 			*pRaTimer;
-	struct _RT2870_TIMER_ENTRY_ 	*pNext;
-}RT2870_TIMER_ENTRY;
-
-
-#define TIMER_QUEUE_SIZE_MAX	128
-typedef struct _RT2870_TIMER_QUEUE_
-{
-	unsigned int		status;
-	//wait_queue_head_t 	timerWaitQ;
-	//atomic_t			count;
-	UCHAR				*pTimerQPoll;
-	RT2870_TIMER_ENTRY	*pQPollFreeList;
-	RT2870_TIMER_ENTRY 	*pQHead;
-	RT2870_TIMER_ENTRY 	*pQTail;
-}RT2870_TIMER_QUEUE;
-#endif // RT2870 //
-
-
-//#define DBG	1
-
-//
-//  MACRO for debugging information
-//
-
-#ifdef DBG
-extern ULONG    RTDebugLevel;
-
-#define DBGPRINT_RAW(Level, Fmt)    \
-{                                   \
-    if (Level <= RTDebugLevel)      \
-    {                               \
-        printk Fmt;               \
-    }                               \
-}
-
-#define DBGPRINT(Level, Fmt)    DBGPRINT_RAW(Level, Fmt)
-
-
-#define DBGPRINT_ERR(Fmt)           \
-{                                   \
-    printk("ERROR!!! ");          \
-    printk Fmt;                  \
-}
-
-#define DBGPRINT_S(Status, Fmt)		\
-{									\
-	printk Fmt;					\
-}
-
-
-#else
-#define DBGPRINT(Level, Fmt)
-#define DBGPRINT_RAW(Level, Fmt)
-#define DBGPRINT_S(Status, Fmt)
-#define DBGPRINT_ERR(Fmt)
-#endif
-
-
-//
-//  spin_lock enhanced for Nested spin lock
-//
-#define NdisAllocateSpinLock(__lock)      \
-{                                       \
-    spin_lock_init((spinlock_t *)(__lock));               \
-}
-
-#define NdisFreeSpinLock(lock)          \
-{                                       \
-}
-
-
-#define RTMP_SEM_LOCK(__lock)					\
-{												\
-	spin_lock_bh((spinlock_t *)(__lock));				\
-}
-
-#define RTMP_SEM_UNLOCK(__lock)					\
-{												\
-	spin_unlock_bh((spinlock_t *)(__lock));				\
-}
-
-// sample, use semaphore lock to replace IRQ lock, 2007/11/15
-#define RTMP_IRQ_LOCK(__lock, __irqflags)			\
-{													\
-	__irqflags = 0;									\
-	spin_lock_bh((spinlock_t *)(__lock));			\
-	pAd->irq_disabled |= 1; \
-}
-
-#define RTMP_IRQ_UNLOCK(__lock, __irqflag)			\
-{													\
-	pAd->irq_disabled &= 0; \
-	spin_unlock_bh((spinlock_t *)(__lock));			\
-}
-
-#define RTMP_INT_LOCK(__lock, __irqflags)			\
-{													\
-	spin_lock_irqsave((spinlock_t *)__lock, __irqflags);	\
-}
-
-#define RTMP_INT_UNLOCK(__lock, __irqflag)			\
-{													\
-	spin_unlock_irqrestore((spinlock_t *)(__lock), ((unsigned long)__irqflag));	\
-}
-
-#ifdef RT2870
-#define RTMP_IO_READ32(_A, _R, _pV)								\
-	RTUSBReadMACRegister(_A, _R, _pV)
-
-#define RTMP_IO_READ8(_A, _R, _pV)								\
-{																\
-}
-
-#define RTMP_IO_WRITE32(_A, _R, _V)								\
-	RTUSBWriteMACRegister(_A, _R, _V)
-
-
-#define RTMP_IO_WRITE8(_A, _R, _V)								\
-{																\
-	USHORT	_Val = _V;											\
-	RTUSBSingleWrite(_A, _R, _Val);								\
-}
-
-
-#define RTMP_IO_WRITE16(_A, _R, _V)								\
-{																\
-	RTUSBSingleWrite(_A, _R, _V);								\
-}
-#endif // RT2870 //
-
-#ifndef wait_event_interruptible_timeout
-#define __wait_event_interruptible_timeout(wq, condition, ret) \
-do { \
-        wait_queue_t __wait; \
-        init_waitqueue_entry(&__wait, current); \
-        add_wait_queue(&wq, &__wait); \
-        for (;;) { \
-                set_current_state(TASK_INTERRUPTIBLE); \
-                if (condition) \
-                        break; \
-                if (!signal_pending(current)) { \
-                        ret = schedule_timeout(ret); \
-                        if (!ret) \
-                                break; \
-                        continue; \
-                } \
-                ret = -ERESTARTSYS; \
-                break; \
-        } \
-        current->state = TASK_RUNNING; \
-        remove_wait_queue(&wq, &__wait); \
-} while (0)
-
-#define wait_event_interruptible_timeout(wq, condition, timeout) \
-({ \
-        long __ret = timeout; \
-        if (!(condition)) \
-                __wait_event_interruptible_timeout(wq, condition, __ret); \
-        __ret; \
-})
-#endif
-#define ONE_TICK 1
-#define OS_WAIT(_time) \
-{	int _i; \
-	long _loop = ((_time)/(1000/OS_HZ)) > 0 ? ((_time)/(1000/OS_HZ)) : 1;\
-	wait_queue_head_t _wait; \
-	init_waitqueue_head(&_wait); \
-	for (_i=0; _i<(_loop); _i++) \
-		wait_event_interruptible_timeout(_wait, 0, ONE_TICK); }
-
-
-/* Modified by Wu Xi-Kun 4/21/2006 */
-typedef void (*TIMER_FUNCTION)(unsigned long);
-
-#define COPY_MAC_ADDR(Addr1, Addr2)             memcpy((Addr1), (Addr2), MAC_ADDR_LEN)
-
-#define MlmeAllocateMemory(_pAd, _ppVA) os_alloc_mem(_pAd, _ppVA, MGMT_DMA_BUFFER_SIZE)
-#define MlmeFreeMemory(_pAd, _pVA)     os_free_mem(_pAd, _pVA)
-
-
-#ifdef RT2870
-#define BUILD_TIMER_FUNCTION(_func)													\
-void linux_##_func(unsigned long data)												\
-{																					\
-	PRALINK_TIMER_STRUCT	_pTimer = (PRALINK_TIMER_STRUCT)data;					\
-	RT2870_TIMER_ENTRY		*_pQNode;												\
-	RTMP_ADAPTER			*_pAd;													\
-																				\
-	_pTimer->handle = _func;															\
-	_pAd = (RTMP_ADAPTER *)_pTimer->pAd;												\
-	_pQNode = RT2870_TimerQ_Insert(_pAd, _pTimer); 									\
-	if ((_pQNode == NULL) && (_pAd->TimerQ.status & RT2870_THREAD_CAN_DO_INSERT))	\
-		RTMP_OS_Add_Timer(&_pTimer->TimerObj, HZ);               					\
-}
-#endif // RT2870 //
-
-
-#define DECLARE_TIMER_FUNCTION(_func)			\
-void linux_##_func(unsigned long data)
-
-#define GET_TIMER_FUNCTION(_func)				\
-		linux_##_func
-
-DECLARE_TIMER_FUNCTION(MlmePeriodicExec);
-DECLARE_TIMER_FUNCTION(MlmeRssiReportExec);
-DECLARE_TIMER_FUNCTION(AsicRxAntEvalTimeout);
-DECLARE_TIMER_FUNCTION(APSDPeriodicExec);
-DECLARE_TIMER_FUNCTION(AsicRfTuningExec);
-#ifdef RT2870
-DECLARE_TIMER_FUNCTION(BeaconUpdateExec);
-#endif // RT2870 //
-
-
-#ifdef CONFIG_STA_SUPPORT
-DECLARE_TIMER_FUNCTION(BeaconTimeout);
-DECLARE_TIMER_FUNCTION(ScanTimeout);
-DECLARE_TIMER_FUNCTION(AuthTimeout);
-DECLARE_TIMER_FUNCTION(AssocTimeout);
-DECLARE_TIMER_FUNCTION(ReassocTimeout);
-DECLARE_TIMER_FUNCTION(DisassocTimeout);
-DECLARE_TIMER_FUNCTION(LinkDownExec);
-#ifdef LEAP_SUPPORT
-DECLARE_TIMER_FUNCTION(LeapAuthTimeout);
-#endif
-DECLARE_TIMER_FUNCTION(StaQuickResponeForRateUpExec);
-DECLARE_TIMER_FUNCTION(WpaDisassocApAndBlockAssoc);
-DECLARE_TIMER_FUNCTION(PsPollWakeExec);
-DECLARE_TIMER_FUNCTION(RadioOnExec);
-
-#ifdef QOS_DLS_SUPPORT
-DECLARE_TIMER_FUNCTION(DlsTimeoutAction);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-#undef AP_WSC_INCLUDED
-#undef STA_WSC_INCLUDED
-#undef WSC_INCLUDED
-
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-#if defined(AP_WSC_INCLUDED) || defined(STA_WSC_INCLUDED)
-#define WSC_INCLUDED
-#endif
-
-
-
-void RTMP_GetCurrentSystemTime(LARGE_INTEGER *time);
-
-
-/*
- * packet helper
- * 	- convert internal rt packet to os packet or
- *             os packet to rt packet
- */
-#define RTPKT_TO_OSPKT(_p)		((struct sk_buff *)(_p))
-#define OSPKT_TO_RTPKT(_p)		((PNDIS_PACKET)(_p))
-
-#define GET_OS_PKT_DATAPTR(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->data)
-
-#define GET_OS_PKT_LEN(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->len)
-
-#define GET_OS_PKT_DATATAIL(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->tail)
-
-#define GET_OS_PKT_HEAD(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->head)
-
-#define GET_OS_PKT_END(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->end)
-
-#define GET_OS_PKT_NETDEV(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->dev)
-
-#define GET_OS_PKT_TYPE(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt))
-
-#define GET_OS_PKT_NEXT(_pkt) \
-		(RTPKT_TO_OSPKT(_pkt)->next)
-
-
-#define OS_NTOHS(_Val) \
-		(ntohs(_Val))
-#define OS_HTONS(_Val) \
-		(htons(_Val))
-#define OS_NTOHL(_Val) \
-		(ntohl(_Val))
-#define OS_HTONL(_Val) \
-		(htonl(_Val))
-
-/* statistics counter */
-#define STATS_INC_RX_PACKETS(_pAd, _dev)
-#define STATS_INC_TX_PACKETS(_pAd, _dev)
-
-#define STATS_INC_RX_BYTESS(_pAd, _dev, len)
-#define STATS_INC_TX_BYTESS(_pAd, _dev, len)
-
-#define STATS_INC_RX_ERRORS(_pAd, _dev)
-#define STATS_INC_TX_ERRORS(_pAd, _dev)
-
-#define STATS_INC_RX_DROPPED(_pAd, _dev)
-#define STATS_INC_TX_DROPPED(_pAd, _dev)
-
-
-#define CB_OFF  10
-
-
-//   check DDK NDIS_PACKET data structure and find out only MiniportReservedEx[0..7] can be used by our driver without
-//   ambiguity. Fields after pPacket->MiniportReservedEx[8] may be used by other wrapper layer thus crashes the driver
-//
-//#define RTMP_GET_PACKET_MR(_p)			(RTPKT_TO_OSPKT(_p))
-
-// User Priority
-#define RTMP_SET_PACKET_UP(_p, _prio)			(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+0] = _prio)
-#define RTMP_GET_PACKET_UP(_p)					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+0])
-
-// Fragment #
-#define RTMP_SET_PACKET_FRAGMENTS(_p, _num)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+1] = _num)
-#define RTMP_GET_PACKET_FRAGMENTS(_p)			(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+1])
-
-// 0x0 ~0x7f: TX to AP's own BSS which has the specified AID. if AID>127, set bit 7 in RTMP_SET_PACKET_EMACTAB too.
-//(this value also as MAC(on-chip WCID) table index)
-// 0x80~0xff: TX to a WDS link. b0~6: WDS index
-#define RTMP_SET_PACKET_WCID(_p, _wdsidx)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+2] = _wdsidx)
-#define RTMP_GET_PACKET_WCID(_p)          		((UCHAR)(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+2]))
-
-// 0xff: PKTSRC_NDIS, others: local TX buffer index. This value affects how to a packet
-#define RTMP_SET_PACKET_SOURCE(_p, _pktsrc)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+3] = _pktsrc)
-#define RTMP_GET_PACKET_SOURCE(_p)       		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+3])
-
-// RTS/CTS-to-self protection method
-#define RTMP_SET_PACKET_RTS(_p, _num)      		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+4] = _num)
-#define RTMP_GET_PACKET_RTS(_p)          		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+4])
-// see RTMP_S(G)ET_PACKET_EMACTAB
-
-// TX rate index
-#define RTMP_SET_PACKET_TXRATE(_p, _rate)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+5] = _rate)
-#define RTMP_GET_PACKET_TXRATE(_p)		  		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+5])
-
-// From which Interface
-#define RTMP_SET_PACKET_IF(_p, _ifdx)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+6] = _ifdx)
-#define RTMP_GET_PACKET_IF(_p)		  		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+6])
-#define RTMP_SET_PACKET_NET_DEVICE_MBSSID(_p, _bss)		RTMP_SET_PACKET_IF((_p), (_bss))
-#define RTMP_SET_PACKET_NET_DEVICE_WDS(_p, _bss)		RTMP_SET_PACKET_IF((_p), ((_bss) + MIN_NET_DEVICE_FOR_WDS))
-#define RTMP_SET_PACKET_NET_DEVICE_APCLI(_p, _idx)   	RTMP_SET_PACKET_IF((_p), ((_idx) + MIN_NET_DEVICE_FOR_APCLI))
-#define RTMP_SET_PACKET_NET_DEVICE_MESH(_p, _idx)   	RTMP_SET_PACKET_IF((_p), ((_idx) + MIN_NET_DEVICE_FOR_MESH))
-#define RTMP_GET_PACKET_NET_DEVICE_MBSSID(_p)			RTMP_GET_PACKET_IF((_p))
-#define RTMP_GET_PACKET_NET_DEVICE(_p)					RTMP_GET_PACKET_IF((_p))
-
-#define RTMP_SET_PACKET_MOREDATA(_p, _morebit)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+7] = _morebit)
-#define RTMP_GET_PACKET_MOREDATA(_p)				(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+7])
-
-//#define RTMP_SET_PACKET_NET_DEVICE_MBSSID(_p, _bss)	(RTPKT_TO_OSPKT(_p)->cb[8] = _bss)
-//#define RTMP_GET_PACKET_NET_DEVICE_MBSSID(_p)		(RTPKT_TO_OSPKT(_p)->cb[8])
-
-//
-//	Sepcific Pakcet Type definition
-//
-#define RTMP_PACKET_SPECIFIC_CB_OFFSET	11
-
-#define RTMP_PACKET_SPECIFIC_DHCP		0x01
-#define RTMP_PACKET_SPECIFIC_EAPOL		0x02
-#define RTMP_PACKET_SPECIFIC_IPV4		0x04
-#define RTMP_PACKET_SPECIFIC_WAI		0x08
-#define RTMP_PACKET_SPECIFIC_VLAN		0x10
-#define RTMP_PACKET_SPECIFIC_LLCSNAP	0x20
-
-//Specific
-#define RTMP_SET_PACKET_SPECIFIC(_p, _flg)	   	(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] = _flg)
-
-//DHCP
-#define RTMP_SET_PACKET_DHCP(_p, _flg)   													\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_DHCP);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_DHCP);	\
-			}while(0)
-#define RTMP_GET_PACKET_DHCP(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_DHCP)
-
-//EAPOL
-#define RTMP_SET_PACKET_EAPOL(_p, _flg)   													\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_EAPOL);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_EAPOL);	\
-			}while(0)
-#define RTMP_GET_PACKET_EAPOL(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_EAPOL)
-
-//WAI
-#define RTMP_SET_PACKET_WAI(_p, _flg)   													\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_WAI);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_WAI);	\
-			}while(0)
-#define RTMP_GET_PACKET_WAI(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_WAI)
-
-#define RTMP_GET_PACKET_LOWRATE(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & (RTMP_PACKET_SPECIFIC_EAPOL | RTMP_PACKET_SPECIFIC_DHCP | RTMP_PACKET_SPECIFIC_WAI))
-
-//VLAN
-#define RTMP_SET_PACKET_VLAN(_p, _flg)   													\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_VLAN);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_VLAN);	\
-			}while(0)
-#define RTMP_GET_PACKET_VLAN(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_VLAN)
-
-//LLC/SNAP
-#define RTMP_SET_PACKET_LLCSNAP(_p, _flg)   													\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_LLCSNAP);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_LLCSNAP);		\
-			}while(0)
-
-#define RTMP_GET_PACKET_LLCSNAP(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_LLCSNAP)
-
-// IP
-#define RTMP_SET_PACKET_IPV4(_p, _flg)														\
-			do{																				\
-				if (_flg)																	\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) |= (RTMP_PACKET_SPECIFIC_IPV4);		\
-				else																		\
-					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11]) &= (!RTMP_PACKET_SPECIFIC_IPV4);	\
-			}while(0)
-
-#define RTMP_GET_PACKET_IPV4(_p)		(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+11] & RTMP_PACKET_SPECIFIC_IPV4)
-
-// If this flag is set, it indicates that this EAPoL frame MUST be clear.
-#define RTMP_SET_PACKET_CLEAR_EAP_FRAME(_p, _flg)   (RTPKT_TO_OSPKT(_p)->cb[CB_OFF+12] = _flg)
-#define RTMP_GET_PACKET_CLEAR_EAP_FRAME(_p)         (RTPKT_TO_OSPKT(_p)->cb[CB_OFF+12])
-
-#define RTMP_SET_PACKET_5VT(_p, _flg)   (RTPKT_TO_OSPKT(_p)->cb[CB_OFF+22] = _flg)
-#define RTMP_GET_PACKET_5VT(_p)         (RTPKT_TO_OSPKT(_p)->cb[CB_OFF+22])
-
-
-#ifdef INF_AMAZON_SE
-/*Iverson patch for WMM A5-T07 ,WirelessStaToWirelessSta do not bulk out aggregate */
-#define RTMP_SET_PACKET_NOBULKOUT(_p, _morebit)			(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+23] = _morebit)
-#define RTMP_GET_PACKET_NOBULKOUT(_p)					(RTPKT_TO_OSPKT(_p)->cb[CB_OFF+23])
-#endif // INF_AMAZON_SE //
-
-
-
-#ifdef CONFIG_5VT_ENHANCE
-#define BRIDGE_TAG 0x35564252    // depends on 5VT define in br_input.c
-#endif
-
-
-#define NDIS_SET_PACKET_STATUS(_p, _status)
-
-
-#define GET_SG_LIST_FROM_PACKET(_p, _sc)	\
-    rt_get_sg_list_from_packet(_p, _sc)
-
-#define NdisMoveMemory(Destination, Source, Length) memmove(Destination, Source, Length)
-#define NdisZeroMemory(Destination, Length)         memset(Destination, 0, Length)
-#define NdisFillMemory(Destination, Length, Fill)   memset(Destination, Fill, Length)
-#define NdisEqualMemory(Source1, Source2, Length)   (!memcmp(Source1, Source2, Length))
-#define RTMPEqualMemory(Source1, Source2, Length)	(!memcmp(Source1, Source2, Length))
-
-
-#define RTMP_INC_REF(_A)		0
-#define RTMP_DEC_REF(_A)		0
-#define RTMP_GET_REF(_A)		0
-
-
-
-/*
- * ULONG
- * RTMP_GetPhysicalAddressLow(
- *   IN NDIS_PHYSICAL_ADDRESS  PhysicalAddress);
- */
-#define RTMP_GetPhysicalAddressLow(PhysicalAddress)		(PhysicalAddress)
-
-/*
- * ULONG
- * RTMP_GetPhysicalAddressHigh(
- *   IN NDIS_PHYSICAL_ADDRESS  PhysicalAddress);
- */
-#define RTMP_GetPhysicalAddressHigh(PhysicalAddress)		(0)
-
-/*
- * VOID
- * RTMP_SetPhysicalAddressLow(
- *   IN NDIS_PHYSICAL_ADDRESS  PhysicalAddress,
- *   IN ULONG  Value);
- */
-#define RTMP_SetPhysicalAddressLow(PhysicalAddress, Value)	\
-			PhysicalAddress = Value;
-
-/*
- * VOID
- * RTMP_SetPhysicalAddressHigh(
- *   IN NDIS_PHYSICAL_ADDRESS  PhysicalAddress,
- *   IN ULONG  Value);
- */
-#define RTMP_SetPhysicalAddressHigh(PhysicalAddress, Value)
-
-
-//CONTAINING_RECORD(pEntry, NDIS_PACKET, MiniportReservedEx);
-#define QUEUE_ENTRY_TO_PACKET(pEntry) \
-	(PNDIS_PACKET)(pEntry)
-
-#define PACKET_TO_QUEUE_ENTRY(pPacket) \
-	(PQUEUE_ENTRY)(pPacket)
-
-
-#ifndef CONTAINING_RECORD
-#define CONTAINING_RECORD(address, type, field)			\
-((type *)((PCHAR)(address) - offsetof(type, field)))
-#endif
-
-
-#define RELEASE_NDIS_PACKET(_pAd, _pPacket, _Status)                    \
-{                                                                       \
-        RTMPFreeNdisPacket(_pAd, _pPacket);                             \
-}
-
-
-#define SWITCH_PhyAB(_pAA, _pBB)    \
-{                                                                           \
-    ULONG	AABasePaHigh;                           \
-    ULONG	AABasePaLow;                           \
-    ULONG	BBBasePaHigh;                           \
-    ULONG	BBBasePaLow;                           \
-    BBBasePaHigh = RTMP_GetPhysicalAddressHigh(_pBB);                                                 \
-    BBBasePaLow = RTMP_GetPhysicalAddressLow(_pBB);                                                 \
-    AABasePaHigh = RTMP_GetPhysicalAddressHigh(_pAA);                                                 \
-    AABasePaLow = RTMP_GetPhysicalAddressLow(_pAA);                                                 \
-    RTMP_SetPhysicalAddressHigh(_pAA, BBBasePaHigh);                                                 \
-    RTMP_SetPhysicalAddressLow(_pAA, BBBasePaLow);                                                 \
-    RTMP_SetPhysicalAddressHigh(_pBB, AABasePaHigh);                                                 \
-    RTMP_SetPhysicalAddressLow(_pBB, AABasePaLow);                                                 \
-}
-
-
-#define NdisWriteErrorLogEntry(_a, _b, _c, _d)
-#define NdisMAllocateMapRegisters(_a, _b, _c, _d, _e)		NDIS_STATUS_SUCCESS
-
-
-#define NdisAcquireSpinLock		RTMP_SEM_LOCK
-#define NdisReleaseSpinLock		RTMP_SEM_UNLOCK
-
-static inline void NdisGetSystemUpTime(ULONG *time)
-{
-	*time = jiffies;
-}
-
-//pPacket = CONTAINING_RECORD(pEntry, NDIS_PACKET, MiniportReservedEx);
-#define QUEUE_ENTRY_TO_PKT(pEntry) \
-		((PNDIS_PACKET) (pEntry))
-
-int rt28xx_packet_xmit(struct sk_buff *skb);
-
-
-
-void rtmp_os_thread_init(PUCHAR pThreadName, PVOID pNotify);
-
-
-
+#include "../../rt2870/rt_linux.h"
diff --git a/drivers/staging/rt3070/rt_main_dev.c b/drivers/staging/rt3070/rt_main_dev.c
index 81f769c..c8bcd40 100644
--- a/drivers/staging/rt3070/rt_main_dev.c
+++ b/drivers/staging/rt3070/rt_main_dev.c
@@ -1,1801 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    rt_main_dev.c
-
-    Abstract:
-    Create and register network interface.
-
-    Revision History:
-    Who         When            What
-    --------    ----------      ----------------------------------------------
-	Sample		Mar/21/07		Merge RT2870 and RT2860 drivers.
-*/
-
-#include "rt_config.h"
-
-#define FORTY_MHZ_INTOLERANT_INTERVAL	(60*1000) // 1 min
-
-#ifdef MULTIPLE_CARD_SUPPORT
-// record whether the card in the card list is used in the card file
-UINT8  MC_CardUsed[MAX_NUM_OF_MULTIPLE_CARD];
-// record used card mac address in the card list
-static UINT8  MC_CardMac[MAX_NUM_OF_MULTIPLE_CARD][6];
-#endif // MULTIPLE_CARD_SUPPORT //
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-UINT32 CW_MAX_IN_BITS;
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-/*---------------------------------------------------------------------*/
-/* Private Variables Used                                              */
-/*---------------------------------------------------------------------*/
-//static RALINK_TIMER_STRUCT     PeriodicTimer;
-
-char *mac = "";		   // default 00:00:00:00:00:00
-char *hostname = "";		   // default CMPC
-#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,12)
-MODULE_PARM (mac, "s");
-#else
-module_param (mac, charp, 0);
-#endif
-MODULE_PARM_DESC (mac, "rt28xx: wireless mac addr");
-
-
-/*---------------------------------------------------------------------*/
-/* Prototypes of Functions Used                                        */
-/*---------------------------------------------------------------------*/
-#ifdef DOT11_N_SUPPORT
-extern BOOLEAN ba_reordering_resource_init(PRTMP_ADAPTER pAd, int num);
-extern void ba_reordering_resource_release(PRTMP_ADAPTER pAd);
-#endif // DOT11_N_SUPPORT //
-extern NDIS_STATUS NICLoadRateSwitchingParams(IN PRTMP_ADAPTER pAd);
-
-
-// public function prototype
-INT __devinit rt28xx_probe(IN void *_dev_p, IN void *_dev_id_p,
-							IN UINT argc, OUT PRTMP_ADAPTER *ppAd);
-
-// private function prototype
-static int rt28xx_init(IN struct net_device *net_dev);
-INT rt28xx_send_packets(IN struct sk_buff *skb_p, IN struct net_device *net_dev);
-
-#if LINUX_VERSION_CODE <= 0x20402	// Red Hat 7.1
-struct net_device *alloc_netdev(
-	int sizeof_priv,
-	const char *mask,
-	void (*setup)(struct net_device *));
-#endif // LINUX_VERSION_CODE //
-
-static void CfgInitHook(PRTMP_ADAPTER pAd);
-//static BOOLEAN RT28XXAvailRANameAssign(IN CHAR *name_p);
-
-#ifdef CONFIG_STA_SUPPORT
-extern	const struct iw_handler_def rt28xx_iw_handler_def;
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-extern	const struct iw_handler_def rt28xx_ap_iw_handler_def;
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-#if WIRELESS_EXT >= 12
-// This function will be called when query /proc
-struct iw_statistics *rt28xx_get_wireless_stats(
-    IN struct net_device *net_dev);
-#endif
-
-struct net_device_stats *RT28xx_get_ether_stats(
-    IN  struct net_device *net_dev);
-
-/*
-========================================================================
-Routine Description:
-    Close raxx interface.
-
-Arguments:
-	*net_dev			the raxx interface pointer
-
-Return Value:
-    0					Open OK
-	otherwise			Open Fail
-
-Note:
-	1. if open fail, kernel will not call the close function.
-	2. Free memory for
-		(1) Mlme Memory Handler:		MlmeHalt()
-		(2) TX & RX:					RTMPFreeTxRxRingMemory()
-		(3) BA Reordering: 				ba_reordering_resource_release()
-========================================================================
-*/
-int MainVirtualIF_close(IN struct net_device *net_dev)
-{
-    RTMP_ADAPTER *pAd = net_dev->ml_priv;
-
-	// Sanity check for pAd
-	if (pAd == NULL)
-		return 0; // close ok
-
-	netif_carrier_off(pAd->net_dev);
-	netif_stop_queue(pAd->net_dev);
-
-
-
-	VIRTUAL_IF_DOWN(pAd);
-
-	RT_MOD_DEC_USE_COUNT();
-
-	return 0; // close ok
-}
-
-/*
-========================================================================
-Routine Description:
-    Open raxx interface.
-
-Arguments:
-	*net_dev			the raxx interface pointer
-
-Return Value:
-    0					Open OK
-	otherwise			Open Fail
-
-Note:
-	1. if open fail, kernel will not call the close function.
-	2. Free memory for
-		(1) Mlme Memory Handler:		MlmeHalt()
-		(2) TX & RX:					RTMPFreeTxRxRingMemory()
-		(3) BA Reordering: 				ba_reordering_resource_release()
-========================================================================
-*/
-int MainVirtualIF_open(IN struct net_device *net_dev)
-{
-    RTMP_ADAPTER *pAd = net_dev->ml_priv;
-
-	// Sanity check for pAd
-	if (pAd == NULL)
-		return 0; // close ok
-
-	if (VIRTUAL_IF_UP(pAd) != 0)
-		return -1;
-
-	// increase MODULE use count
-	RT_MOD_INC_USE_COUNT();
-
-	netif_start_queue(net_dev);
-	netif_carrier_on(net_dev);
-	netif_wake_queue(net_dev);
-
-	return 0;
-}
-
-/*
-========================================================================
-Routine Description:
-    Close raxx interface.
-
-Arguments:
-	*net_dev			the raxx interface pointer
-
-Return Value:
-    0					Open OK
-	otherwise			Open Fail
-
-Note:
-	1. if open fail, kernel will not call the close function.
-	2. Free memory for
-		(1) Mlme Memory Handler:		MlmeHalt()
-		(2) TX & RX:					RTMPFreeTxRxRingMemory()
-		(3) BA Reordering: 				ba_reordering_resource_release()
-========================================================================
-*/
-int rt28xx_close(IN PNET_DEV dev)
-{
-	struct net_device * net_dev = (struct net_device *)dev;
-    RTMP_ADAPTER	*pAd = net_dev->ml_priv;
-	BOOLEAN 		Cancelled = FALSE;
-	UINT32			i = 0;
-#ifdef RT2870
-	DECLARE_WAIT_QUEUE_HEAD(unlink_wakeup);
-	DECLARE_WAITQUEUE(wait, current);
-
-	//RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_REMOVE_IN_PROGRESS);
-#endif // RT2870 //
-
-
-    DBGPRINT(RT_DEBUG_TRACE, ("===> rt28xx_close\n"));
-
-	// Sanity check for pAd
-	if (pAd == NULL)
-		return 0; // close ok
-
-
-#ifdef WDS_SUPPORT
-	WdsDown(pAd);
-#endif // WDS_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-
-		// If dirver doesn't wake up firmware here,
-		// NICLoadFirmware will hang forever when interface is up again.
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-        {
-		    AsicForceWakeup(pAd, TRUE);
-        }
-
-#ifdef QOS_DLS_SUPPORT
-		// send DLS-TEAR_DOWN message,
-		if (pAd->CommonCfg.bDLSCapable)
-		{
-			UCHAR i;
-
-			// tear down local dls table entry
-			for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-				{
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-					pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				}
-			}
-
-			// tear down peer dls table entry
-			for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-				{
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				}
-			}
-			RT28XX_MLME_HANDLER(pAd);
-		}
-#endif // QOS_DLS_SUPPORT //
-
-		if (INFRA_ON(pAd) &&
-			(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
-		{
-			MLME_DISASSOC_REQ_STRUCT	DisReq;
-			MLME_QUEUE_ELEM *MsgElem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-
-			COPY_MAC_ADDR(DisReq.Addr, pAd->CommonCfg.Bssid);
-			DisReq.Reason =  REASON_DEAUTH_STA_LEAVING;
-
-			MsgElem->Machine = ASSOC_STATE_MACHINE;
-			MsgElem->MsgType = MT2_MLME_DISASSOC_REQ;
-			MsgElem->MsgLen = sizeof(MLME_DISASSOC_REQ_STRUCT);
-			NdisMoveMemory(MsgElem->Msg, &DisReq, sizeof(MLME_DISASSOC_REQ_STRUCT));
-
-			// Prevent to connect AP again in STAMlmePeriodicExec
-			pAd->MlmeAux.AutoReconnectSsidLen= 32;
-			NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen);
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_DISASSOC;
-			MlmeDisassocReqAction(pAd, MsgElem);
-			kfree(MsgElem);
-
-			RTMPusecDelay(1000);
-		}
-
-#ifdef RT2870
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_REMOVE_IN_PROGRESS);
-#endif // RT2870 //
-
-#ifdef CCX_SUPPORT
-		RTMPCancelTimer(&pAd->StaCfg.LeapAuthTimer, &Cancelled);
-#endif
-
-		RTMPCancelTimer(&pAd->StaCfg.StaQuickResponeForRateUpTimer, &Cancelled);
-		RTMPCancelTimer(&pAd->StaCfg.WpaDisassocAndBlockAssocTimer, &Cancelled);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-		{
-			union iwreq_data    wrqu;
-			// send wireless event to wpa_supplicant for infroming interface down.
-			memset(&wrqu, 0, sizeof(wrqu));
-			wrqu.data.flags = RT_INTERFACE_DOWN;
-			wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-		}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-		MlmeRadioOff(pAd);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS);
-
-	for (i = 0 ; i < NUM_OF_TX_RING; i++)
-	{
-		while (pAd->DeQueueRunning[i] == TRUE)
-		{
-			printk("Waiting for TxQueue[%d] done..........\n", i);
-			RTMPusecDelay(1000);
-		}
-	}
-
-#ifdef RT2870
-	// ensure there are no more active urbs.
-	add_wait_queue (&unlink_wakeup, &wait);
-	pAd->wait = &unlink_wakeup;
-
-	// maybe wait for deletions to finish.
-	i = 0;
-	//while((i < 25) && atomic_read(&pAd->PendingRx) > 0)
-	while(i < 25)
-	{
-		unsigned long IrqFlags;
-
-		RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
-		if (pAd->PendingRx == 0)
-		{
-			RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-			break;
-		}
-		RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
-
-#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,9)
-		msleep(UNLINK_TIMEOUT_MS);	//Time in millisecond
-#else
-		RTMPusecDelay(UNLINK_TIMEOUT_MS*1000);	//Time in microsecond
-#endif
-		i++;
-	}
-	pAd->wait = NULL;
-	remove_wait_queue (&unlink_wakeup, &wait);
-#endif // RT2870 //
-
-	//RTUSBCleanUpMLMEWaitQueue(pAd);	/*not used in RT28xx*/
-
-
-#ifdef RT2870
-	// We need clear timerQ related structure before exits of the timer thread.
-	RT2870_TimerQ_Exit(pAd);
-	// Close kernel threads or tasklets
-	RT28xxThreadTerminate(pAd);
-#endif // RT2870 //
-
-	// Stop Mlme state machine
-	MlmeHalt(pAd);
-
-	// Close kernel threads or tasklets
-	kill_thread_task(pAd);
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		MacTableReset(pAd);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-
-	MeasureReqTabExit(pAd);
-	TpcReqTabExit(pAd);
-
-
-
-
-	// Free Ring or USB buffers
-	RTMPFreeTxRxRingMemory(pAd);
-
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS);
-
-#ifdef DOT11_N_SUPPORT
-	// Free BA reorder resource
-	ba_reordering_resource_release(pAd);
-#endif // DOT11_N_SUPPORT //
-
-#ifdef RT2870
-#ifdef INF_AMAZON_SE
-	if (pAd->UsbVendorReqBuf)
-		os_free_mem(pAd, pAd->UsbVendorReqBuf);
-#endif // INF_AMAZON_SE //
-#endif // RT2870 //
-
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_START_UP);
-
-	return 0; // close ok
-} /* End of rt28xx_close */
-
-static int rt28xx_init(IN struct net_device *net_dev)
-{
-	PRTMP_ADAPTER 			pAd = net_dev->ml_priv;
-	UINT					index;
-	UCHAR					TmpPhy;
-//	ULONG					Value=0;
-	NDIS_STATUS				Status;
-//    OID_SET_HT_PHYMODE		SetHT;
-//	WPDMA_GLO_CFG_STRUC     GloCfg;
-	UINT32 		MacCsr0 = 0;
-
-#ifdef RT2870
-#ifdef INF_AMAZON_SE
-	init_MUTEX(&(pAd->UsbVendorReq_semaphore));
-	os_alloc_mem(pAd, (PUCHAR)&pAd->UsbVendorReqBuf, MAX_PARAM_BUFFER_SIZE - 1);
-	if (pAd->UsbVendorReqBuf == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Allocate vendor request temp buffer failed!\n"));
-		goto err0;
-	}
-#endif // INF_AMAZON_SE //
-#endif // RT2870 //
-
-#ifdef DOT11_N_SUPPORT
-	// Allocate BA Reordering memory
-	ba_reordering_resource_init(pAd, MAX_REORDERING_MPDU_NUM);
-#endif // DOT11_N_SUPPORT //
-
-	// Make sure MAC gets ready.
-	index = 0;
-	do
-	{
-		RTMP_IO_READ32(pAd, MAC_CSR0, &MacCsr0);
-		pAd->MACVersion = MacCsr0;
-
-		if ((pAd->MACVersion != 0x00) && (pAd->MACVersion != 0xFFFFFFFF))
-			break;
-
-		RTMPusecDelay(10);
-	} while (index++ < 100);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("MAC_CSR0  [ Ver:Rev=0x%08x]\n", pAd->MACVersion));
-/*Iverson patch PCIE L1 issue */
-
-	// Disable DMA
-	RT28XXDMADisable(pAd);
-
-
-	// Load 8051 firmware
-	Status = NICLoadFirmware(pAd);
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT_ERR(("NICLoadFirmware failed, Status[=0x%08x]\n", Status));
-		goto err1;
-	}
-
-	NICLoadRateSwitchingParams(pAd);
-
-	// Disable interrupts here which is as soon as possible
-	// This statement should never be true. We might consider to remove it later
-
-	Status = RTMPAllocTxRxRingMemory(pAd);
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT_ERR(("RTMPAllocDMAMemory failed, Status[=0x%08x]\n", Status));
-		goto err1;
-	}
-
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE);
-
-	// initialize MLME
-	//
-
-	Status = MlmeInit(pAd);
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT_ERR(("MlmeInit failed, Status[=0x%08x]\n", Status));
-		goto err2;
-	}
-
-	// Initialize pAd->StaCfg, pAd->ApCfg, pAd->CommonCfg to manufacture default
-	//
-	UserCfgInit(pAd);
-
-#ifdef RT2870
-	// We need init timerQ related structure before create the timer thread.
-	RT2870_TimerQ_Init(pAd);
-#endif // RT2870 //
-
-	RT28XX_TASK_THREAD_INIT(pAd, Status);
-	if (Status != NDIS_STATUS_SUCCESS)
-		goto err1;
-
-//	COPY_MAC_ADDR(pAd->ApCfg.MBSSID[apidx].Bssid, netif->hwaddr);
-//	pAd->bForcePrintTX = TRUE;
-
-	CfgInitHook(pAd);
-
-
-#ifdef BLOCK_NET_IF
-	initblockQueueTab(pAd);
-#endif // BLOCK_NET_IF //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		NdisAllocateSpinLock(&pAd->MacTabLock);
-#endif // CONFIG_STA_SUPPORT //
-
-	MeasureReqTabInit(pAd);
-	TpcReqTabInit(pAd);
-
-	//
-	// Init the hardware, we need to init asic before read registry, otherwise mac register will be reset
-	//
-	Status = NICInitializeAdapter(pAd, TRUE);
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT_ERR(("NICInitializeAdapter failed, Status[=0x%08x]\n", Status));
-		if (Status != NDIS_STATUS_SUCCESS)
-		goto err3;
-	}
-
-	// Read parameters from Config File
-	Status = RTMPReadParametersHook(pAd);
-
-	printk("1. Phy Mode = %d\n", pAd->CommonCfg.PhyMode);
-	if (Status != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT_ERR(("NICReadRegParameters failed, Status[=0x%08x]\n",Status));
-		goto err4;
-	}
-
-#ifdef RT2870
-	pAd->CommonCfg.bMultipleIRP = FALSE;
-
-	if (pAd->CommonCfg.bMultipleIRP)
-		pAd->CommonCfg.NumOfBulkInIRP = RX_RING_SIZE;
-	else
-		pAd->CommonCfg.NumOfBulkInIRP = 1;
-#endif // RT2870 //
-
-
-   	//Init Ba Capability parameters.
-//	RT28XX_BA_INIT(pAd);
-#ifdef DOT11_N_SUPPORT
-	pAd->CommonCfg.DesiredHtPhy.MpduDensity = (UCHAR)pAd->CommonCfg.BACapability.field.MpduDensity;
-	pAd->CommonCfg.DesiredHtPhy.AmsduEnable = (USHORT)pAd->CommonCfg.BACapability.field.AmsduEnable;
-	pAd->CommonCfg.DesiredHtPhy.AmsduSize = (USHORT)pAd->CommonCfg.BACapability.field.AmsduSize;
-	pAd->CommonCfg.DesiredHtPhy.MimoPs = (USHORT)pAd->CommonCfg.BACapability.field.MMPSmode;
-	// UPdata to HT IE
-	pAd->CommonCfg.HtCapability.HtCapInfo.MimoPs = (USHORT)pAd->CommonCfg.BACapability.field.MMPSmode;
-	pAd->CommonCfg.HtCapability.HtCapInfo.AMsduSize = (USHORT)pAd->CommonCfg.BACapability.field.AmsduSize;
-	pAd->CommonCfg.HtCapability.HtCapParm.MpduDensity = (UCHAR)pAd->CommonCfg.BACapability.field.MpduDensity;
-#endif // DOT11_N_SUPPORT //
-
-	// after reading Registry, we now know if in AP mode or STA mode
-
-	// Load 8051 firmware; crash when FW image not existent
-	// Status = NICLoadFirmware(pAd);
-	// if (Status != NDIS_STATUS_SUCCESS)
-	//    break;
-
-	printk("2. Phy Mode = %d\n", pAd->CommonCfg.PhyMode);
-
-	// We should read EEPROM for all cases.  rt2860b
-	NICReadEEPROMParameters(pAd, mac);
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-	printk("3. Phy Mode = %d\n", pAd->CommonCfg.PhyMode);
-
-	NICInitAsicFromEEPROM(pAd); //rt2860b
-
-	// Set PHY to appropriate mode
-	TmpPhy = pAd->CommonCfg.PhyMode;
-	pAd->CommonCfg.PhyMode = 0xff;
-	RTMPSetPhyMode(pAd, TmpPhy);
-#ifdef DOT11_N_SUPPORT
-	SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-
-	// No valid channels.
-	if (pAd->ChannelListNum == 0)
-	{
-		printk("Wrong configuration. No valid channel found. Check \"ContryCode\" and \"ChannelGeography\" setting.\n");
-		goto err4;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	printk("MCS Set = %02x %02x %02x %02x %02x\n", pAd->CommonCfg.HtCapability.MCSSet[0],
-           pAd->CommonCfg.HtCapability.MCSSet[1], pAd->CommonCfg.HtCapability.MCSSet[2],
-           pAd->CommonCfg.HtCapability.MCSSet[3], pAd->CommonCfg.HtCapability.MCSSet[4]);
-#endif // DOT11_N_SUPPORT //
-
-#ifdef RT30xx
-    //Init RT30xx RFRegisters after read RFIC type from EEPROM
-	NICInitRT30xxRFRegisters(pAd);
-#endif // RT30xx //
-
-//		APInitialize(pAd);
-
-#ifdef IKANOS_VX_1X0
-	VR_IKANOS_FP_Init(pAd->ApCfg.BssidNum, pAd->PermanentAddress);
-#endif // IKANOS_VX_1X0 //
-
-		//
-	// Initialize RF register to default value
-	//
-	AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-	AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-
-	if (pAd && (Status != NDIS_STATUS_SUCCESS))
-	{
-		//
-		// Undo everything if it failed
-		//
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-		{
-//			NdisMDeregisterInterrupt(&pAd->Interrupt);
-			RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE);
-		}
-//		RTMPFreeAdapter(pAd); // we will free it in disconnect()
-	}
-	else if (pAd)
-	{
-		// Microsoft HCT require driver send a disconnect event after driver initialization.
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-//		pAd->IndicateMediaState = NdisMediaStateDisconnected;
-		RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_MEDIA_STATE_CHANGE);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event B!\n"));
-
-
-#ifdef RT2870
-		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS);
-		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_REMOVE_IN_PROGRESS);
-
-		//
-		// Support multiple BulkIn IRP,
-		// the value on pAd->CommonCfg.NumOfBulkInIRP may be large than 1.
-		//
-		for(index=0; index<pAd->CommonCfg.NumOfBulkInIRP; index++)
-		{
-			RTUSBBulkReceive(pAd);
-			DBGPRINT(RT_DEBUG_TRACE, ("RTUSBBulkReceive!\n" ));
-		}
-#endif // RT2870 //
-	}// end of else
-
-
-	DBGPRINT_S(Status, ("<==== RTMPInitialize, Status=%x\n", Status));
-
-	return TRUE;
-
-
-err4:
-err3:
-	MlmeHalt(pAd);
-err2:
-	RTMPFreeTxRxRingMemory(pAd);
-//	RTMPFreeAdapter(pAd);
-err1:
-
-#ifdef DOT11_N_SUPPORT
-	os_free_mem(pAd, pAd->mpdu_blk_pool.mem); // free BA pool
-#endif // DOT11_N_SUPPORT //
-	RT28XX_IRQ_RELEASE(net_dev);
-
-	// shall not set priv to NULL here because the priv didn't been free yet.
-	//net_dev->ml_priv = 0;
-#ifdef INF_AMAZON_SE
-err0:
-#endif // INF_AMAZON_SE //
-	printk("!!! %s Initialized fail !!!\n", RT28xx_CHIP_NAME);
-	return FALSE;
-} /* End of rt28xx_init */
-
-
-/*
-========================================================================
-Routine Description:
-    Open raxx interface.
-
-Arguments:
-	*net_dev			the raxx interface pointer
-
-Return Value:
-    0					Open OK
-	otherwise			Open Fail
-
-Note:
-========================================================================
-*/
-int rt28xx_open(IN PNET_DEV dev)
-{
-	struct net_device * net_dev = (struct net_device *)dev;
-	PRTMP_ADAPTER pAd = net_dev->ml_priv;
-	int retval = 0;
- 	POS_COOKIE pObj;
-
-
-	// Sanity check for pAd
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -1;
-	}
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	if (pAd->OpMode == OPMODE_AP)
-	{
-		CW_MAX_IN_BITS = 6;
-	}
-	else if (pAd->OpMode == OPMODE_STA)
-	{
-		CW_MAX_IN_BITS = 10;
-	}
-
-#if WIRELESS_EXT >= 12
-	if (net_dev->ml_priv_flags == INT_MAIN)
-	{
-		if (pAd->OpMode == OPMODE_AP)
-			net_dev->wireless_handlers = (struct iw_handler_def *) &rt28xx_ap_iw_handler_def;
-		else if (pAd->OpMode == OPMODE_STA)
-			net_dev->wireless_handlers = (struct iw_handler_def *) &rt28xx_iw_handler_def;
-	}
-#endif // WIRELESS_EXT >= 12 //
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-	// Init
- 	pObj = (POS_COOKIE)pAd->OS_Cookie;
-
-	// reset Adapter flags
-	RTMP_CLEAR_FLAGS(pAd);
-
-	// Request interrupt service routine for PCI device
-	// register the interrupt routine with the os
-	RT28XX_IRQ_REQUEST(net_dev);
-
-
-	// Init BssTab & ChannelInfo tabbles for auto channel select.
-
-
-	// Chip & other init
-	if (rt28xx_init(net_dev) == FALSE)
-		goto err;
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		NdisZeroMemory(pAd->StaCfg.dev_name, 16);
-		NdisMoveMemory(pAd->StaCfg.dev_name, net_dev->name, strlen(net_dev->name));
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Set up the Mac address
-	NdisMoveMemory(net_dev->dev_addr, (void *) pAd->CurrentAddress, 6);
-
-	// Init IRQ parameters
-	RT28XX_IRQ_INIT(pAd);
-
-	// Various AP function init
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-		{
-			union iwreq_data    wrqu;
-			// send wireless event to wpa_supplicant for infroming interface down.
-			memset(&wrqu, 0, sizeof(wrqu));
-			wrqu.data.flags = RT_INTERFACE_UP;
-			wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-		}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	// Enable Interrupt
-	RT28XX_IRQ_ENABLE(pAd);
-
-	// Now Enable RxTx
-	RTMPEnableRxTx(pAd);
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_START_UP);
-
-	{
-	UINT32 reg = 0;
-	RTMP_IO_READ32(pAd, 0x1300, &reg);  // clear garbage interrupts
-	printk("0x1300 = %08x\n", reg);
-	}
-
-	{
-//	u32 reg;
-//	u8  byte;
-//	u16 tmp;
-
-//	RTMP_IO_READ32(pAd, XIFS_TIME_CFG, &reg);
-
-//	tmp = 0x0805;
-//	reg  = (reg & 0xffff0000) | tmp;
-//	RTMP_IO_WRITE32(pAd, XIFS_TIME_CFG, reg);
-
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-	return (retval);
-
-err:
-	return (-1);
-} /* End of rt28xx_open */
-
-static const struct net_device_ops rt3070_netdev_ops = {
-	.ndo_open		= MainVirtualIF_open,
-	.ndo_stop		= MainVirtualIF_close,
-	.ndo_do_ioctl		= rt28xx_ioctl,
-	.ndo_get_stats		= RT28xx_get_ether_stats,
-	.ndo_validate_addr	= NULL,
-	.ndo_set_mac_address	= eth_mac_addr,
-	.ndo_change_mtu		= eth_change_mtu,
-#ifdef IKANOS_VX_1X0
-	.ndo_start_xmit		= IKANOS_DataFramesTx,
-#else
-	.ndo_start_xmit		= rt28xx_send_packets,
-#endif
-};
-
-/* Must not be called for mdev and apdev */
-static NDIS_STATUS rt_ieee80211_if_setup(struct net_device *dev, PRTMP_ADAPTER pAd)
-{
-	NDIS_STATUS Status;
-	INT     i=0;
-	CHAR    slot_name[IFNAMSIZ];
-	struct net_device   *device;
-
-
-	//ether_setup(dev);
-//	dev->set_multicast_list = ieee80211_set_multicast_list;
-//	dev->change_mtu = ieee80211_change_mtu;
-#ifdef CONFIG_STA_SUPPORT
-#if WIRELESS_EXT >= 12
-	if (pAd->OpMode == OPMODE_STA)
-	{
-		dev->wireless_handlers = &rt28xx_iw_handler_def;
-	}
-#endif //WIRELESS_EXT >= 12
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-#if WIRELESS_EXT >= 12
-	if (pAd->OpMode == OPMODE_AP)
-	{
-		dev->wireless_handlers = &rt28xx_ap_iw_handler_def;
-	}
-#endif //WIRELESS_EXT >= 12
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-#if WIRELESS_EXT < 21
-		dev->get_wireless_stats = rt28xx_get_wireless_stats;
-#endif
-//	dev->uninit = ieee80211_if_reinit;
-//	dev->destructor = ieee80211_if_free;
-	dev->priv_flags = INT_MAIN;
-	dev->netdev_ops = &rt3070_netdev_ops;
-	// find available device name
-	for (i = 0; i < 8; i++)
-	{
-#ifdef MULTIPLE_CARD_SUPPORT
-		if (pAd->MC_RowID >= 0)
-			sprintf(slot_name, "ra%02d_%d", pAd->MC_RowID, i);
-		else
-#endif // MULTIPLE_CARD_SUPPORT //
-		sprintf(slot_name, "ra%d", i);
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,26)
-        device = dev_get_by_name(dev_net(dev), slot_name);
-#else
-        device = dev_get_by_name(dev->nd_net, slot_name);
-#endif
-#else
-		device = dev_get_by_name(slot_name);
-#endif
-		if (device != NULL) dev_put(device);
-#else
-		for (device = dev_base; device != NULL; device = device->next)
-		{
-			if (strncmp(device->name, slot_name, 4) == 0)
-				break;
-		}
-#endif
-		if(device == NULL)
-			break;
-	}
-
-	if(i == 8)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("No available slot name\n"));
-		Status = NDIS_STATUS_FAILURE;
-	}
-	else
-	{
-#ifdef MULTIPLE_CARD_SUPPORT
-		if (pAd->MC_RowID >= 0)
-	        sprintf(dev->name, "ra%02d_%d", pAd->MC_RowID, i);
-		else
-#endif // MULTIPLE_CARD_SUPPORT //
-		sprintf(dev->name, "ra%d", i);
-		Status = NDIS_STATUS_SUCCESS;
-	}
-
-	return Status;
-
-}
-
-
-#ifdef MULTIPLE_CARD_SUPPORT
-/*
-========================================================================
-Routine Description:
-    Get card profile path.
-
-Arguments:
-    pAd
-
-Return Value:
-    TRUE		- Find a card profile
-	FALSE		- use default profile
-
-Note:
-========================================================================
-*/
-extern INT RTMPGetKeyParameter(
-    IN  PCHAR   key,
-    OUT PCHAR   dest,
-    IN  INT     destsize,
-    IN  PCHAR   buffer);
-
-BOOLEAN RTMP_CardInfoRead(
-	IN	PRTMP_ADAPTER pAd)
-{
-#define MC_SELECT_CARDID		0	/* use CARD ID (0 ~ 31) to identify different cards */
-#define MC_SELECT_MAC			1	/* use CARD MAC to identify different cards */
-#define MC_SELECT_CARDTYPE		2	/* use CARD type (abgn or bgn) to identify different cards */
-
-#define LETTER_CASE_TRANSLATE(txt_p, card_id)			\
-	{	UINT32 _len; char _char;						\
-		for(_len=0; _len<strlen(card_id); _len++) {		\
-			_char = *(txt_p + _len);					\
-			if (('A' <= _char) && (_char <= 'Z'))		\
-				*(txt_p+_len) = 'a'+(_char-'A');		\
-		} }
-
-	struct file *srcf;
-	INT retval, orgfsuid, orgfsgid;
-   	mm_segment_t orgfs;
-	CHAR *buffer, *tmpbuf, card_id_buf[30], RFIC_word[30];
-	BOOLEAN flg_match_ok = FALSE;
-	INT32 card_select_method;
-	INT32 card_free_id, card_nouse_id, card_same_mac_id, card_match_id;
-	EEPROM_ANTENNA_STRUC antenna;
-	USHORT addr01, addr23, addr45;
-	UINT8 mac[6];
-	UINT32 data, card_index;
-	UCHAR *start_ptr;
-
-
-	// init
-	buffer = kmalloc(MAX_INI_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	if (buffer == NULL)
-        return FALSE;
-
-	tmpbuf = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	if(tmpbuf == NULL)
-	{
-		kfree(buffer);
-        return NDIS_STATUS_FAILURE;
-	}
-
-	orgfsuid = current->fsuid;
-	orgfsgid = current->fsgid;
-	current->fsuid = current->fsgid = 0;
-    orgfs = get_fs();
-    set_fs(KERNEL_DS);
-
-	// get RF IC type
-	RTMP_IO_READ32(pAd, E2PROM_CSR, &data);
-
-	if ((data & 0x30) == 0)
-		pAd->EEPROMAddressNum = 6;	// 93C46
-	else if ((data & 0x30) == 0x10)
-		pAd->EEPROMAddressNum = 8;	// 93C66
-	else
-		pAd->EEPROMAddressNum = 8;	// 93C86
-
-	//antenna.word = RTMP_EEPROM_READ16(pAd, EEPROM_NIC1_OFFSET);
-	RT28xx_EEPROM_READ16(pAd, EEPROM_NIC1_OFFSET, antenna.word);
-
-	if ((antenna.field.RfIcType == RFIC_2850) ||
-		(antenna.field.RfIcType == RFIC_2750))
-	{
-		/* ABGN card */
-		strcpy(RFIC_word, "abgn");
-	}
-	else
-	{
-		/* BGN card */
-		strcpy(RFIC_word, "bgn");
-	}
-
-	// get MAC address
-	//addr01 = RTMP_EEPROM_READ16(pAd, 0x04);
-	//addr23 = RTMP_EEPROM_READ16(pAd, 0x06);
-	//addr45 = RTMP_EEPROM_READ16(pAd, 0x08);
-	RT28xx_EEPROM_READ16(pAd, 0x04, addr01);
-	RT28xx_EEPROM_READ16(pAd, 0x06, addr23);
-	RT28xx_EEPROM_READ16(pAd, 0x08, addr45);
-
-	mac[0] = (UCHAR)(addr01 & 0xff);
-	mac[1] = (UCHAR)(addr01 >> 8);
-	mac[2] = (UCHAR)(addr23 & 0xff);
-	mac[3] = (UCHAR)(addr23 >> 8);
-	mac[4] = (UCHAR)(addr45 & 0xff);
-	mac[5] = (UCHAR)(addr45 >> 8);
-
-	// open card information file
-	srcf = filp_open(CARD_INFO_PATH, O_RDONLY, 0);
-	if (IS_ERR(srcf))
-	{
-		/* card information file does not exist */
-			DBGPRINT(RT_DEBUG_TRACE,
-				("--> Error %ld opening %s\n", -PTR_ERR(srcf), CARD_INFO_PATH));
-		return FALSE;
-	}
-
-	if (srcf->f_op && srcf->f_op->read)
-	{
-		/* card information file exists so reading the card information */
-		memset(buffer, 0x00, MAX_INI_BUFFER_SIZE);
-		retval = srcf->f_op->read(srcf, buffer, MAX_INI_BUFFER_SIZE, &srcf->f_pos);
-		if (retval < 0)
-		{
-			/* read fail */
-				DBGPRINT(RT_DEBUG_TRACE,
-					("--> Read %s error %d\n", CARD_INFO_PATH, -retval));
-		}
-		else
-		{
-			/* get card selection method */
-			memset(tmpbuf, 0x00, MAX_PARAM_BUFFER_SIZE);
-			card_select_method = MC_SELECT_CARDTYPE; // default
-
-			if (RTMPGetKeyParameter("SELECT", tmpbuf, 256, buffer))
-			{
-				if (strcmp(tmpbuf, "CARDID") == 0)
-					card_select_method = MC_SELECT_CARDID;
-				else if (strcmp(tmpbuf, "MAC") == 0)
-					card_select_method = MC_SELECT_MAC;
-				else if (strcmp(tmpbuf, "CARDTYPE") == 0)
-					card_select_method = MC_SELECT_CARDTYPE;
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE,
-					("MC> Card Selection = %d\n", card_select_method));
-
-			// init
-			card_free_id = -1;
-			card_nouse_id = -1;
-			card_same_mac_id = -1;
-			card_match_id = -1;
-
-			// search current card information records
-			for(card_index=0;
-				card_index<MAX_NUM_OF_MULTIPLE_CARD;
-				card_index++)
-			{
-				if ((*(UINT32 *)&MC_CardMac[card_index][0] == 0) &&
-					(*(UINT16 *)&MC_CardMac[card_index][4] == 0))
-				{
-					// MAC is all-0 so the entry is available
-					MC_CardUsed[card_index] = 0;
-
-					if (card_free_id < 0)
-						card_free_id = card_index; // 1st free entry
-				}
-				else
-				{
-					if (memcmp(MC_CardMac[card_index], mac, 6) == 0)
-					{
-						// we find the entry with same MAC
-						if (card_same_mac_id < 0)
-							card_same_mac_id = card_index; // 1st same entry
-					}
-					else
-					{
-						// MAC is not all-0 but used flag == 0
-						if ((MC_CardUsed[card_index] == 0) &&
-							(card_nouse_id < 0))
-						{
-							card_nouse_id = card_index; // 1st available entry
-						}
-					}
-				}
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE,
-					("MC> Free = %d, Same = %d, NOUSE = %d\n",
-					card_free_id, card_same_mac_id, card_nouse_id));
-
-			if ((card_same_mac_id >= 0) &&
-				((card_select_method == MC_SELECT_CARDID) ||
-				(card_select_method == MC_SELECT_CARDTYPE)))
-			{
-				// same MAC entry is found
-				card_match_id = card_same_mac_id;
-
-				if (card_select_method == MC_SELECT_CARDTYPE)
-				{
-					// for CARDTYPE
-					sprintf(card_id_buf, "%02dCARDTYPE%s",
-							card_match_id, RFIC_word);
-
-					if ((start_ptr=rtstrstruncasecmp(buffer, card_id_buf)) != NULL)
-					{
-						// we found the card ID
-						LETTER_CASE_TRANSLATE(start_ptr, card_id_buf);
-					}
-				}
-			}
-			else
-			{
-				// the card is 1st plug-in, try to find the match card profile
-				switch(card_select_method)
-				{
-					case MC_SELECT_CARDID: // CARDID
-					default:
-						if (card_free_id >= 0)
-							card_match_id = card_free_id;
-						else
-							card_match_id = card_nouse_id;
-						break;
-
-					case MC_SELECT_MAC: // MAC
-						sprintf(card_id_buf, "MAC%02x:%02x:%02x:%02x:%02x:%02x",
-								mac[0], mac[1], mac[2],
-								mac[3], mac[4], mac[5]);
-
-						/* try to find the key word in the card file */
-						if ((start_ptr=rtstrstruncasecmp(buffer, card_id_buf)) != NULL)
-						{
-							LETTER_CASE_TRANSLATE(start_ptr, card_id_buf);
-
-							/* get the row ID (2 ASCII characters) */
-							start_ptr -= 2;
-							card_id_buf[0] = *(start_ptr);
-							card_id_buf[1] = *(start_ptr+1);
-							card_id_buf[2] = 0x00;
-
-							card_match_id = simple_strtol(card_id_buf, 0, 10);
-						}
-						break;
-
-					case MC_SELECT_CARDTYPE: // CARDTYPE
-						card_nouse_id = -1;
-
-						for(card_index=0;
-							card_index<MAX_NUM_OF_MULTIPLE_CARD;
-							card_index++)
-						{
-							sprintf(card_id_buf, "%02dCARDTYPE%s",
-									card_index, RFIC_word);
-
-							if ((start_ptr=rtstrstruncasecmp(buffer,
-														card_id_buf)) != NULL)
-							{
-								LETTER_CASE_TRANSLATE(start_ptr, card_id_buf);
-
-								if (MC_CardUsed[card_index] == 0)
-								{
-									/* current the card profile is not used */
-									if ((*(UINT32 *)&MC_CardMac[card_index][0] == 0) &&
-										(*(UINT16 *)&MC_CardMac[card_index][4] == 0))
-									{
-										// find it and no previous card use it
-										card_match_id = card_index;
-										break;
-									}
-									else
-									{
-										// ever a card use it
-										if (card_nouse_id < 0)
-											card_nouse_id = card_index;
-									}
-								}
-							}
-						}
-
-						// if not find a free one, use the available one
-						if (card_match_id < 0)
-							card_match_id = card_nouse_id;
-						break;
-				}
-			}
-
-			if (card_match_id >= 0)
-			{
-				// make up search keyword
-				switch(card_select_method)
-				{
-					case MC_SELECT_CARDID: // CARDID
-						sprintf(card_id_buf, "%02dCARDID", card_match_id);
-						break;
-
-					case MC_SELECT_MAC: // MAC
-						sprintf(card_id_buf,
-								"%02dmac%02x:%02x:%02x:%02x:%02x:%02x",
-								card_match_id,
-								mac[0], mac[1], mac[2],
-								mac[3], mac[4], mac[5]);
-						break;
-
-					case MC_SELECT_CARDTYPE: // CARDTYPE
-					default:
-						sprintf(card_id_buf, "%02dcardtype%s",
-								card_match_id, RFIC_word);
-						break;
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Search Keyword = %s\n", card_id_buf));
-
-				// read card file path
-				if (RTMPGetKeyParameter(card_id_buf, tmpbuf, 256, buffer))
-				{
-					if (strlen(tmpbuf) < sizeof(pAd->MC_FileName))
-					{
-						// backup card information
-						pAd->MC_RowID = card_match_id; /* base 0 */
-						MC_CardUsed[card_match_id] = 1;
-						memcpy(MC_CardMac[card_match_id], mac, sizeof(mac));
-
-						// backup card file path
-						NdisMoveMemory(pAd->MC_FileName, tmpbuf , strlen(tmpbuf));
-						pAd->MC_FileName[strlen(tmpbuf)] = '\0';
-						flg_match_ok = TRUE;
-
-						DBGPRINT(RT_DEBUG_TRACE,
-								("Card Profile Name = %s\n", pAd->MC_FileName));
-					}
-					else
-					{
-						DBGPRINT(RT_DEBUG_ERROR,
-								("Card Profile Name length too large!\n"));
-					}
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_ERROR,
-							("Can not find search key word in card.dat!\n"));
-				}
-
-				if ((flg_match_ok != TRUE) &&
-					(card_match_id < MAX_NUM_OF_MULTIPLE_CARD))
-				{
-					MC_CardUsed[card_match_id] = 0;
-					memset(MC_CardMac[card_match_id], 0, sizeof(mac));
-				}
-			} // if (card_match_id >= 0)
-		}
-	}
-
-	// close file
-	retval = filp_close(srcf, NULL);
-	set_fs(orgfs);
-	current->fsuid = orgfsuid;
-	current->fsgid = orgfsgid;
-	kfree(buffer);
-	kfree(tmpbuf);
-	return flg_match_ok;
-}
-#endif // MULTIPLE_CARD_SUPPORT //
-
-
-/*
-========================================================================
-Routine Description:
-    Probe RT28XX chipset.
-
-Arguments:
-    _dev_p				Point to the PCI or USB device
-	_dev_id_p			Point to the PCI or USB device ID
-
-Return Value:
-    0					Probe OK
-	-ENODEV				Probe Fail
-
-Note:
-========================================================================
-*/
-INT __devinit   rt28xx_probe(
-    IN  void *_dev_p,
-    IN  void *_dev_id_p,
-	IN  UINT argc,
-	OUT PRTMP_ADAPTER *ppAd)
-{
-    struct  net_device	*net_dev;
-    PRTMP_ADAPTER       pAd = (PRTMP_ADAPTER) NULL;
-    INT                 status;
-	PVOID				handle;
-#ifdef RT2870
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)	/* kernel 2.4 series */
-	struct usb_device *dev_p = (struct usb_device *)_dev_p;
-#else
-	struct usb_interface *intf = (struct usb_interface *)_dev_p;
-	struct usb_device *dev_p = interface_to_usbdev(intf);
-
-	dev_p = usb_get_dev(dev_p);
-#endif // LINUX_VERSION_CODE //
-#endif // RT2870 //
-
-
-#ifdef CONFIG_STA_SUPPORT
-    DBGPRINT(RT_DEBUG_TRACE, ("STA Driver version-%s\n", STA_DRIVER_VERSION));
-#endif // CONFIG_STA_SUPPORT //
-
-	// Check chipset vendor/product ID
-//	if (RT28XXChipsetCheck(_dev_p) == FALSE)
-//		goto err_out;
-
-#if LINUX_VERSION_CODE <= 0x20402       // Red Hat 7.1
-    net_dev = alloc_netdev(sizeof(PRTMP_ADAPTER), "eth%d", ether_setup);
-#else
-    net_dev = alloc_etherdev(sizeof(PRTMP_ADAPTER));
-#endif
-    if (net_dev == NULL)
-    {
-        printk("alloc_netdev failed\n");
-
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,15)
-		module_put(THIS_MODULE);
-#endif //LINUX_VERSION_CODE < KERNEL_VERSION(2,6,15)
-#else
-		MOD_DEC_USE_COUNT;
-#endif
-        goto err_out;
-    }
-
-// sample
-//	if (rt_ieee80211_if_setup(net_dev) != NDIS_STATUS_SUCCESS)
-//		goto err_out;
-
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24)
-    SET_MODULE_OWNER(net_dev);
-#endif
-
-	netif_stop_queue(net_dev);
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-/* for supporting Network Manager */
-/* Set the sysfs physical device reference for the network logical device
- * if set prior to registration will cause a symlink during initialization.
- */
-#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0))
-    SET_NETDEV_DEV(net_dev, &(dev_p->dev));
-#endif
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-	// Allocate RTMP_ADAPTER miniport adapter structure
-	handle = kmalloc(sizeof(struct os_cookie), GFP_KERNEL);
-	RT28XX_HANDLE_DEV_ASSIGN(handle, dev_p);
-
-	status = RTMPAllocAdapterBlock(handle, &pAd);
-	if (status != NDIS_STATUS_SUCCESS)
-		goto err_out_free_netdev;
-
-	net_dev->ml_priv = (PVOID)pAd;
-    pAd->net_dev = net_dev; // must be before RT28XXNetDevInit()
-
-	RT28XXNetDevInit(_dev_p, net_dev, pAd);
-
-#ifdef CONFIG_STA_SUPPORT
-    pAd->StaCfg.OriDevType = net_dev->type;
-#endif // CONFIG_STA_SUPPORT //
-
-	// Find and assign a free interface name, raxx
-//	RT28XXAvailRANameAssign(net_dev->name);
-
-	// Post config
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-	if (RT28XXProbePostConfig(_dev_p, pAd, argc) == FALSE)
-		goto err_out_unmap;
-#else
-	if (RT28XXProbePostConfig(_dev_p, pAd, 0) == FALSE)
-		goto err_out_unmap;
-#endif // LINUX_VERSION_CODE //
-
-#ifdef CONFIG_STA_SUPPORT
-	pAd->OpMode = OPMODE_STA;
-#endif // CONFIG_STA_SUPPORT //
-
-
-#ifdef MULTIPLE_CARD_SUPPORT
-	// find its profile path
-	pAd->MC_RowID = -1; // use default profile path
-	RTMP_CardInfoRead(pAd);
-
-	if (pAd->MC_RowID == -1)
-#ifdef CONFIG_STA_SUPPORT
-		strcpy(pAd->MC_FileName, STA_PROFILE_PATH);
-#endif // CONFIG_STA_SUPPORT //
-
-	DBGPRINT(RT_DEBUG_TRACE,
-			("MC> ROW = %d, PATH = %s\n", pAd->MC_RowID, pAd->MC_FileName));
-#endif // MULTIPLE_CARD_SUPPORT //
-
-	// sample move
-	if (rt_ieee80211_if_setup(net_dev, pAd) != NDIS_STATUS_SUCCESS)
-		goto err_out_unmap;
-
-    // Register this device
-    status = register_netdev(net_dev);
-    if (status)
-        goto err_out_unmap;
-
-    // Set driver data
-	RT28XX_DRVDATA_SET(_dev_p);
-
-
-
-	*ppAd = pAd;
-    return 0; // probe ok
-
-
-	/* --------------------------- ERROR HANDLE --------------------------- */
-err_out_unmap:
-	RTMPFreeAdapter(pAd);
-	RT28XX_UNMAP();
-
-err_out_free_netdev:
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
-    free_netdev(net_dev);
-#else
-	kfree(net_dev);
-#endif
-
-err_out:
-	RT28XX_PUT_DEVICE(dev_p);
-
-#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
-	return (LONG)NULL;
-#else
-    return -ENODEV; /* probe fail */
-#endif // LINUX_VERSION_CODE //
-} /* End of rt28xx_probe */
-
-
-/*
-========================================================================
-Routine Description:
-    The entry point for Linux kernel sent packet to our driver.
-
-Arguments:
-    sk_buff *skb		the pointer refer to a sk_buffer.
-
-Return Value:
-    0
-
-Note:
-	This function is the entry point of Tx Path for Os delivery packet to
-	our driver. You only can put OS-depened & STA/AP common handle procedures
-	in here.
-========================================================================
-*/
-int rt28xx_packet_xmit(struct sk_buff *skb)
-{
-	struct net_device *net_dev = skb->dev;
-	PRTMP_ADAPTER pAd = net_dev->ml_priv;
-	int status = 0;
-	PNDIS_PACKET pPacket = (PNDIS_PACKET) skb;
-
-	/* RT2870STA does this in RTMPSendPackets() */
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_RESOURCES);
-		return 0;
-	}
-#endif // RALINK_ATE //
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		// Drop send request since we are in monitor mode
-		if (MONITOR_ON(pAd))
-		{
-			RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-			goto done;
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-        // EapolStart size is 18
-	if (skb->len < 14)
-	{
-		//printk("bad packet size: %d\n", pkt->len);
-		hex_dump("bad packet", skb->data, skb->len);
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-		goto done;
-	}
-
-	RTMP_SET_PACKET_5VT(pPacket, 0);
-//	MiniportMMRequest(pAd, pkt->data, pkt->len);
-#ifdef CONFIG_5VT_ENHANCE
-    if (*(int*)(skb->cb) == BRIDGE_TAG) {
-		RTMP_SET_PACKET_5VT(pPacket, 1);
-    }
-#endif
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-
-		STASendPackets((NDIS_HANDLE)pAd, (PPNDIS_PACKET) &pPacket, 1);
-	}
-
-#endif // CONFIG_STA_SUPPORT //
-
-	status = 0;
-done:
-
-	return status;
-}
-
-
-/*
-========================================================================
-Routine Description:
-    Send a packet to WLAN.
-
-Arguments:
-    skb_p           points to our adapter
-    dev_p           which WLAN network interface
-
-Return Value:
-    0: transmit successfully
-    otherwise: transmit fail
-
-Note:
-========================================================================
-*/
-INT rt28xx_send_packets(
-	IN struct sk_buff 		*skb_p,
-	IN struct net_device 	*net_dev)
-{
-    RTMP_ADAPTER *pAd = net_dev->ml_priv;
-
-	if (!(net_dev->flags & IFF_UP))
-	{
-		RELEASE_NDIS_PACKET(pAd, (PNDIS_PACKET)skb_p, NDIS_STATUS_FAILURE);
-		return 0;
-	}
-
-	NdisZeroMemory((PUCHAR)&skb_p->cb[CB_OFF], 15);
-	RTMP_SET_PACKET_NET_DEVICE_MBSSID(skb_p, MAIN_MBSSID);
-
-	return rt28xx_packet_xmit(skb_p);
-} /* End of MBSS_VirtualIF_PacketSend */
-
-
-
-
-#if LINUX_VERSION_CODE <= 0x20402	// Red Hat 7.1
-//static struct net_device *alloc_netdev(int sizeof_priv, const char *mask, void (*setup)(struct net_device *)) //sample
-struct net_device *alloc_netdev(
-	int sizeof_priv,
-	const char *mask,
-	void (*setup)(struct net_device *))
-{
-    struct net_device	*dev;
-    INT					alloc_size;
-
-
-    /* ensure 32-byte alignment of the private area */
-    alloc_size = sizeof (*dev) + sizeof_priv + 31;
-
-    dev = (struct net_device *) kmalloc(alloc_size, GFP_KERNEL);
-    if (dev == NULL)
-    {
-        DBGPRINT(RT_DEBUG_ERROR,
-				("alloc_netdev: Unable to allocate device memory.\n"));
-        return NULL;
-    }
-
-    memset(dev, 0, alloc_size);
-
-    if (sizeof_priv)
-        dev->ml_priv = (void *) (((long)(dev + 1) + 31) & ~31);
-
-    setup(dev);
-    strcpy(dev->name, mask);
-
-    return dev;
-}
-#endif // LINUX_VERSION_CODE //
-
-
-void CfgInitHook(PRTMP_ADAPTER pAd)
-{
-	pAd->bBroadComHT = TRUE;
-} /* End of CfgInitHook */
-
-
-#if WIRELESS_EXT >= 12
-// This function will be called when query /proc
-struct iw_statistics *rt28xx_get_wireless_stats(
-    IN struct net_device *net_dev)
-{
-	PRTMP_ADAPTER pAd = net_dev->ml_priv;
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("rt28xx_get_wireless_stats --->\n"));
-
-	pAd->iw_stats.status = 0; // Status - device dependent for now
-
-	// link quality
-	pAd->iw_stats.qual.qual = ((pAd->Mlme.ChannelQuality * 12)/10 + 10);
-	if(pAd->iw_stats.qual.qual > 100)
-		pAd->iw_stats.qual.qual = 100;
-
-#ifdef CONFIG_STA_SUPPORT
-	if (pAd->OpMode == OPMODE_STA)
-		pAd->iw_stats.qual.level = RTMPMaxRssi(pAd, pAd->StaCfg.RssiSample.LastRssi0, pAd->StaCfg.RssiSample.LastRssi1, pAd->StaCfg.RssiSample.LastRssi2);
-#endif // CONFIG_STA_SUPPORT //
-
-	pAd->iw_stats.qual.noise = pAd->BbpWriteLatch[66]; // noise level (dBm)
-
-	pAd->iw_stats.qual.noise += 256 - 143;
-	pAd->iw_stats.qual.updated = 1;     // Flags to know if updated
-#ifdef IW_QUAL_DBM
-	pAd->iw_stats.qual.updated |= IW_QUAL_DBM;	// Level + Noise are dBm
-#endif // IW_QUAL_DBM //
-
-	pAd->iw_stats.discard.nwid = 0;     // Rx : Wrong nwid/essid
-	pAd->iw_stats.miss.beacon = 0;      // Missed beacons/superframe
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<--- rt28xx_get_wireless_stats\n"));
-	return &pAd->iw_stats;
-} /* End of rt28xx_get_wireless_stats */
-#endif // WIRELESS_EXT //
-
-
-
-void tbtt_tasklet(unsigned long data)
-{
-#define MAX_TX_IN_TBTT		(16)
-
-}
-
-INT rt28xx_ioctl(
-	IN	struct net_device	*net_dev,
-	IN	OUT	struct ifreq	*rq,
-	IN	INT					cmd)
-{
-	VIRTUAL_ADAPTER	*pVirtualAd = NULL;
-	RTMP_ADAPTER	*pAd = NULL;
-	INT				ret = 0;
-
-	if (net_dev->priv_flags == INT_MAIN)
-	{
-		pAd = net_dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = net_dev->ml_priv;
-		pAd = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-	{
-		ret = rt28xx_sta_ioctl(net_dev, rq, cmd);
-	}
-#endif // CONFIG_STA_SUPPORT //
-
-	return ret;
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-        return ethernet statistics counter
-
-    Arguments:
-        net_dev                     Pointer to net_device
-
-    Return Value:
-        net_device_stats*
-
-    Note:
-
-    ========================================================================
-*/
-struct net_device_stats *RT28xx_get_ether_stats(
-    IN  struct net_device *net_dev)
-{
-    RTMP_ADAPTER *pAd = NULL;
-
-	if (net_dev)
-		pAd = net_dev->ml_priv;
-
-	if (pAd)
-	{
-
-		pAd->stats.rx_packets = pAd->WlanCounters.ReceivedFragmentCount.QuadPart;
-		pAd->stats.tx_packets = pAd->WlanCounters.TransmittedFragmentCount.QuadPart;
-
-		pAd->stats.rx_bytes = pAd->RalinkCounters.ReceivedByteCount;
-		pAd->stats.tx_bytes = pAd->RalinkCounters.TransmittedByteCount;
-
-		pAd->stats.rx_errors = pAd->Counters8023.RxErrors;
-		pAd->stats.tx_errors = pAd->Counters8023.TxErrors;
-
-		pAd->stats.rx_dropped = 0;
-		pAd->stats.tx_dropped = 0;
-
-	    pAd->stats.multicast = pAd->WlanCounters.MulticastReceivedFrameCount.QuadPart;   // multicast packets received
-	    pAd->stats.collisions = pAd->Counters8023.OneCollision + pAd->Counters8023.MoreCollisions;  // Collision packets
-
-	    pAd->stats.rx_length_errors = 0;
-	    pAd->stats.rx_over_errors = pAd->Counters8023.RxNoBuffer;                   // receiver ring buff overflow
-	    pAd->stats.rx_crc_errors = 0;//pAd->WlanCounters.FCSErrorCount;     // recved pkt with crc error
-	    pAd->stats.rx_frame_errors = pAd->Counters8023.RcvAlignmentErrors;          // recv'd frame alignment error
-	    pAd->stats.rx_fifo_errors = pAd->Counters8023.RxNoBuffer;                   // recv'r fifo overrun
-	    pAd->stats.rx_missed_errors = 0;                                            // receiver missed packet
-
-	    // detailed tx_errors
-	    pAd->stats.tx_aborted_errors = 0;
-	    pAd->stats.tx_carrier_errors = 0;
-	    pAd->stats.tx_fifo_errors = 0;
-	    pAd->stats.tx_heartbeat_errors = 0;
-	    pAd->stats.tx_window_errors = 0;
-
-	    // for cslip etc
-	    pAd->stats.rx_compressed = 0;
-	    pAd->stats.tx_compressed = 0;
-
-		return &pAd->stats;
-	}
-	else
-    	return NULL;
-}
-
+#include "../rt2870/rt_main_dev.c"
diff --git a/drivers/staging/rt3070/rt_profile.c b/drivers/staging/rt3070/rt_profile.c
index 6eda27e..ab9eb1d 100644
--- a/drivers/staging/rt3070/rt_profile.c
+++ b/drivers/staging/rt3070/rt_profile.c
@@ -1,2041 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#include "rt_config.h"
-
-#ifdef DOT11_N_SUPPORT
-static void HTParametersHook(
-	IN	PRTMP_ADAPTER pAd,
-	IN	CHAR		  *pValueStr,
-	IN	CHAR		  *pInput);
-#endif // DOT11_N_SUPPORT //
-
-#define ETH_MAC_ADDR_STR_LEN 17  // in format of xx:xx:xx:xx:xx:xx
-
-// We assume the s1 is a sting, s2 is a memory space with 6 bytes. and content of s1 will be changed.
-BOOLEAN rtstrmactohex(char *s1, char *s2)
-{
-	int i = 0;
-	char *ptokS = s1, *ptokE = s1;
-
-	if (strlen(s1) != ETH_MAC_ADDR_STR_LEN)
-		return FALSE;
-
-	while((*ptokS) != '\0')
-	{
-		if((ptokE = strchr(ptokS, ':')) != NULL)
-			*ptokE++ = '\0';
-		if ((strlen(ptokS) != 2) || (!isxdigit(*ptokS)) || (!isxdigit(*(ptokS+1))))
-			break; // fail
-		AtoH(ptokS, &s2[i++], 1);
-		ptokS = ptokE;
-		if (i == 6)
-			break; // parsing finished
-	}
-
-	return ( i == 6 ? TRUE : FALSE);
-
-}
-
-
-// we assume the s1 and s2 both are strings.
-BOOLEAN rtstrcasecmp(char *s1, char *s2)
-{
-	char *p1 = s1, *p2 = s2;
-
-	if (strlen(s1) != strlen(s2))
-		return FALSE;
-
-	while(*p1 != '\0')
-	{
-		if((*p1 != *p2) && ((*p1 ^ *p2) != 0x20))
-			return FALSE;
-		p1++;
-		p2++;
-	}
-
-	return TRUE;
-}
-
-// we assume the s1 (buffer) and s2 (key) both are strings.
-char * rtstrstruncasecmp(char * s1, char * s2)
-{
-	INT l1, l2, i;
-	char temp1, temp2;
-
-	l2 = strlen(s2);
-	if (!l2)
-		return (char *) s1;
-
-	l1 = strlen(s1);
-
-	while (l1 >= l2)
-	{
-		l1--;
-
-		for(i=0; i<l2; i++)
-		{
-			temp1 = *(s1+i);
-			temp2 = *(s2+i);
-
-			if (('a' <= temp1) && (temp1 <= 'z'))
-				temp1 = 'A'+(temp1-'a');
-			if (('a' <= temp2) && (temp2 <= 'z'))
-				temp2 = 'A'+(temp2-'a');
-
-			if (temp1 != temp2)
-				break;
-		}
-
-		if (i == l2)
-			return (char *) s1;
-
-		s1++;
-	}
-
-	return NULL; // not found
-}
-
-//add by kathy
-
- /**
-  * strstr - Find the first substring in a %NUL terminated string
-  * @s1: The string to be searched
-  * @s2: The string to search for
-  */
-char * rtstrstr(const char * s1,const char * s2)
-{
-	INT l1, l2;
-
-	l2 = strlen(s2);
-	if (!l2)
-		return (char *) s1;
-
-	l1 = strlen(s1);
-
-	while (l1 >= l2)
-	{
-		l1--;
-		if (!memcmp(s1,s2,l2))
-			return (char *) s1;
-		s1++;
-	}
-
-	return NULL;
-}
-
-/**
- * rstrtok - Split a string into tokens
- * @s: The string to be searched
- * @ct: The characters to search for
- * * WARNING: strtok is deprecated, use strsep instead. However strsep is not compatible with old architecture.
- */
-char * __rstrtok;
-char * rstrtok(char * s,const char * ct)
-{
-	char *sbegin, *send;
-
-	sbegin  = s ? s : __rstrtok;
-	if (!sbegin)
-	{
-		return NULL;
-	}
-
-	sbegin += strspn(sbegin,ct);
-	if (*sbegin == '\0')
-	{
-		__rstrtok = NULL;
-		return( NULL );
-	}
-
-	send = strpbrk( sbegin, ct);
-	if (send && *send != '\0')
-		*send++ = '\0';
-
-	__rstrtok = send;
-
-	return (sbegin);
-}
-
-/**
- * delimitcnt - return the count of a given delimiter in a given string.
- * @s: The string to be searched.
- * @ct: The delimiter to search for.
- * Notice : We suppose the delimiter is a single-char string(for example : ";").
- */
-INT delimitcnt(char * s,const char * ct)
-{
-	INT count = 0;
-	/* point to the beginning of the line */
-	const char *token = s;
-
-	for ( ;; )
-	{
-		token = strpbrk(token, ct); /* search for delimiters */
-
-        if ( token == NULL )
-		{
-			/* advanced to the terminating null character */
-			break;
-		}
-		/* skip the delimiter */
-	    ++token;
-
-		/*
-		 * Print the found text: use len with %.*s to specify field width.
-		 */
-
-		/* accumulate delimiter count */
-	    ++count;
-	}
-    return count;
-}
-
-/*
-  * converts the Internet host address from the standard numbers-and-dots notation
-  * into binary data.
-  * returns nonzero if the address is valid, zero if not.
-  */
-int rtinet_aton(const char *cp, unsigned int *addr)
-{
-	unsigned int 	val;
-	int         	base, n;
-	char        	c;
-	unsigned int    parts[4];
-	unsigned int    *pp = parts;
-
-	for (;;)
-    {
-         /*
-          * Collect number up to ``.''.
-          * Values are specified as for C:
-          *	0x=hex, 0=octal, other=decimal.
-          */
-         val = 0;
-         base = 10;
-         if (*cp == '0')
-         {
-             if (*++cp == 'x' || *cp == 'X')
-                 base = 16, cp++;
-             else
-                 base = 8;
-         }
-         while ((c = *cp) != '\0')
-         {
-             if (isdigit((unsigned char) c))
-             {
-                 val = (val * base) + (c - '0');
-                 cp++;
-                 continue;
-             }
-             if (base == 16 && isxdigit((unsigned char) c))
-             {
-                 val = (val << 4) +
-                     (c + 10 - (islower((unsigned char) c) ? 'a' : 'A'));
-                 cp++;
-                 continue;
-             }
-             break;
-         }
-         if (*cp == '.')
-         {
-             /*
-              * Internet format: a.b.c.d a.b.c   (with c treated as 16-bits)
-              * a.b     (with b treated as 24 bits)
-              */
-             if (pp >= parts + 3 || val > 0xff)
-                 return 0;
-             *pp++ = val, cp++;
-         }
-         else
-             break;
-     }
-
-     /*
-      * Check for trailing junk.
-      */
-     while (*cp)
-         if (!isspace((unsigned char) *cp++))
-             return 0;
-
-     /*
-      * Concoct the address according to the number of parts specified.
-      */
-     n = pp - parts + 1;
-     switch (n)
-     {
-
-         case 1:         /* a -- 32 bits */
-             break;
-
-         case 2:         /* a.b -- 8.24 bits */
-             if (val > 0xffffff)
-                 return 0;
-             val |= parts[0] << 24;
-             break;
-
-         case 3:         /* a.b.c -- 8.8.16 bits */
-             if (val > 0xffff)
-                 return 0;
-             val |= (parts[0] << 24) | (parts[1] << 16);
-             break;
-
-         case 4:         /* a.b.c.d -- 8.8.8.8 bits */
-             if (val > 0xff)
-                 return 0;
-             val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
-             break;
-     }
-
-     *addr = htonl(val);
-     return 1;
-
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-        Find key section for Get key parameter.
-
-    Arguments:
-        buffer                      Pointer to the buffer to start find the key section
-        section                     the key of the secion to be find
-
-    Return Value:
-        NULL                        Fail
-        Others                      Success
-    ========================================================================
-*/
-PUCHAR  RTMPFindSection(
-    IN  PCHAR   buffer)
-{
-    CHAR temp_buf[32];
-    PUCHAR  ptr;
-
-    strcpy(temp_buf, "Default");
-
-    if((ptr = rtstrstr(buffer, temp_buf)) != NULL)
-            return (ptr+strlen("\n"));
-        else
-            return NULL;
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-        Get key parameter.
-
-    Arguments:
-        key                         Pointer to key string
-        dest                        Pointer to destination
-        destsize                    The datasize of the destination
-        buffer                      Pointer to the buffer to start find the key
-
-    Return Value:
-        TRUE                        Success
-        FALSE                       Fail
-
-    Note:
-        This routine get the value with the matched key (case case-sensitive)
-    ========================================================================
-*/
-INT RTMPGetKeyParameter(
-    IN  PCHAR   key,
-    OUT PCHAR   dest,
-    IN  INT     destsize,
-    IN  PCHAR   buffer)
-{
-    UCHAR *temp_buf1 = NULL;
-    UCHAR *temp_buf2 = NULL;
-    CHAR *start_ptr;
-    CHAR *end_ptr;
-    CHAR *ptr;
-    CHAR *offset = 0;
-    INT  len;
-
-	//temp_buf1 = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	os_alloc_mem(NULL, &temp_buf1, MAX_PARAM_BUFFER_SIZE);
-
-	if(temp_buf1 == NULL)
-        return (FALSE);
-
-	//temp_buf2 = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	os_alloc_mem(NULL, &temp_buf2, MAX_PARAM_BUFFER_SIZE);
-	if(temp_buf2 == NULL)
-	{
-		os_free_mem(NULL, temp_buf1);
-        return (FALSE);
-	}
-
-    //find section
-    if((offset = RTMPFindSection(buffer)) == NULL)
-    {
-    	os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    strcpy(temp_buf1, "\n");
-    strcat(temp_buf1, key);
-    strcat(temp_buf1, "=");
-
-    //search key
-    if((start_ptr=rtstrstr(offset, temp_buf1))==NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    start_ptr+=strlen("\n");
-    if((end_ptr=rtstrstr(start_ptr, "\n"))==NULL)
-       end_ptr=start_ptr+strlen(start_ptr);
-
-    if (end_ptr<start_ptr)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    NdisMoveMemory(temp_buf2, start_ptr, end_ptr-start_ptr);
-    temp_buf2[end_ptr-start_ptr]='\0';
-    len = strlen(temp_buf2);
-    strcpy(temp_buf1, temp_buf2);
-    if((start_ptr=rtstrstr(temp_buf1, "=")) == NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    strcpy(temp_buf2, start_ptr+1);
-    ptr = temp_buf2;
-    //trim space or tab
-    while(*ptr != 0x00)
-    {
-        if( (*ptr == ' ') || (*ptr == '\t') )
-            ptr++;
-        else
-           break;
-    }
-
-    len = strlen(ptr);
-    memset(dest, 0x00, destsize);
-    strncpy(dest, ptr, len >= destsize ?  destsize: len);
-
-	os_free_mem(NULL, temp_buf1);
-    os_free_mem(NULL, temp_buf2);
-    return TRUE;
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-        Get key parameter.
-
-    Arguments:
-        key                         Pointer to key string
-        dest                        Pointer to destination
-        destsize                    The datasize of the destination
-        buffer                      Pointer to the buffer to start find the key
-
-    Return Value:
-        TRUE                        Success
-        FALSE                       Fail
-
-    Note:
-        This routine get the value with the matched key (case case-sensitive).
-        It is called for parsing SSID and any key string.
-    ========================================================================
-*/
-INT RTMPGetCriticalParameter(
-    IN  PCHAR   key,
-    OUT PCHAR   dest,
-    IN  INT     destsize,
-    IN  PCHAR   buffer)
-{
-    UCHAR *temp_buf1 = NULL;
-    UCHAR *temp_buf2 = NULL;
-    CHAR *start_ptr;
-    CHAR *end_ptr;
-    CHAR *ptr;
-    CHAR *offset = 0;
-    INT  len;
-
-	//temp_buf1 = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	os_alloc_mem(NULL, &temp_buf1, MAX_PARAM_BUFFER_SIZE);
-
-	if(temp_buf1 == NULL)
-        return (FALSE);
-
-	//temp_buf2 = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	os_alloc_mem(NULL, &temp_buf2, MAX_PARAM_BUFFER_SIZE);
-	if(temp_buf2 == NULL)
-	{
-		os_free_mem(NULL, temp_buf1);
-        return (FALSE);
-	}
-
-    //find section
-    if((offset = RTMPFindSection(buffer)) == NULL)
-    {
-    	os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    strcpy(temp_buf1, "\n");
-    strcat(temp_buf1, key);
-    strcat(temp_buf1, "=");
-
-    //search key
-    if((start_ptr=rtstrstr(offset, temp_buf1))==NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    start_ptr+=strlen("\n");
-    if((end_ptr=rtstrstr(start_ptr, "\n"))==NULL)
-       end_ptr=start_ptr+strlen(start_ptr);
-
-    if (end_ptr<start_ptr)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    NdisMoveMemory(temp_buf2, start_ptr, end_ptr-start_ptr);
-    temp_buf2[end_ptr-start_ptr]='\0';
-    len = strlen(temp_buf2);
-    strcpy(temp_buf1, temp_buf2);
-    if((start_ptr=rtstrstr(temp_buf1, "=")) == NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    strcpy(temp_buf2, start_ptr+1);
-    ptr = temp_buf2;
-
-    //trim tab
-    /* We cannot trim space(' ') for SSID and key string. */
-    while(*ptr != 0x00)
-    {
-        //if( (*ptr == ' ') || (*ptr == '\t') )
-        if( (*ptr == '\t') )
-            ptr++;
-        else
-           break;
-    }
-
-    len = strlen(ptr);
-    memset(dest, 0x00, destsize);
-    strncpy(dest, ptr, len >= destsize ?  destsize: len);
-
-	os_free_mem(NULL, temp_buf1);
-    os_free_mem(NULL, temp_buf2);
-    return TRUE;
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-        Get multiple key parameter.
-
-    Arguments:
-        key                         Pointer to key string
-        dest                        Pointer to destination
-        destsize                    The datasize of the destination
-        buffer                      Pointer to the buffer to start find the key
-
-    Return Value:
-        TRUE                        Success
-        FALSE                       Fail
-
-    Note:
-        This routine get the value with the matched key (case case-sensitive)
-    ========================================================================
-*/
-INT RTMPGetKeyParameterWithOffset(
-    IN  PCHAR   key,
-    OUT PCHAR   dest,
-    OUT	USHORT	*end_offset,
-    IN  INT     destsize,
-    IN  PCHAR   buffer,
-    IN	BOOLEAN	bTrimSpace)
-{
-    UCHAR *temp_buf1 = NULL;
-    UCHAR *temp_buf2 = NULL;
-    CHAR *start_ptr;
-    CHAR *end_ptr;
-    CHAR *ptr;
-    CHAR *offset = 0;
-    INT  len;
-
-	if (*end_offset >= MAX_INI_BUFFER_SIZE)
-		return (FALSE);
-
-	os_alloc_mem(NULL, &temp_buf1, MAX_PARAM_BUFFER_SIZE);
-
-	if(temp_buf1 == NULL)
-        return (FALSE);
-
-	os_alloc_mem(NULL, &temp_buf2, MAX_PARAM_BUFFER_SIZE);
-	if(temp_buf2 == NULL)
-	{
-		os_free_mem(NULL, temp_buf1);
-        return (FALSE);
-	}
-
-    //find section
-	if(*end_offset == 0)
-    {
-		if ((offset = RTMPFindSection(buffer)) == NULL)
-		{
-			os_free_mem(NULL, temp_buf1);
-	    	os_free_mem(NULL, temp_buf2);
-    	    return (FALSE);
-		}
-    }
-	else
-		offset = buffer + (*end_offset);
-
-    strcpy(temp_buf1, "\n");
-    strcat(temp_buf1, key);
-    strcat(temp_buf1, "=");
-
-    //search key
-    if((start_ptr=rtstrstr(offset, temp_buf1))==NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    start_ptr+=strlen("\n");
-    if((end_ptr=rtstrstr(start_ptr, "\n"))==NULL)
-       end_ptr=start_ptr+strlen(start_ptr);
-
-    if (end_ptr<start_ptr)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-	*end_offset = end_ptr - buffer;
-
-    NdisMoveMemory(temp_buf2, start_ptr, end_ptr-start_ptr);
-    temp_buf2[end_ptr-start_ptr]='\0';
-    len = strlen(temp_buf2);
-    strcpy(temp_buf1, temp_buf2);
-    if((start_ptr=rtstrstr(temp_buf1, "=")) == NULL)
-    {
-		os_free_mem(NULL, temp_buf1);
-    	os_free_mem(NULL, temp_buf2);
-        return (FALSE);
-    }
-
-    strcpy(temp_buf2, start_ptr+1);
-    ptr = temp_buf2;
-    //trim space or tab
-    while(*ptr != 0x00)
-    {
-        if((bTrimSpace && (*ptr == ' ')) || (*ptr == '\t') )
-            ptr++;
-        else
-           break;
-    }
-
-    len = strlen(ptr);
-    memset(dest, 0x00, destsize);
-    strncpy(dest, ptr, len >= destsize ?  destsize: len);
-
-	os_free_mem(NULL, temp_buf1);
-    os_free_mem(NULL, temp_buf2);
-    return TRUE;
-}
-
-
-static int rtmp_parse_key_buffer_from_file(IN  PRTMP_ADAPTER pAd,IN  char *buffer,IN  ULONG KeyType,IN  INT BSSIdx,IN  INT KeyIdx)
-{
-	PUCHAR		keybuff;
-	INT			i = BSSIdx, idx = KeyIdx;
-	ULONG		KeyLen;
-	UCHAR		CipherAlg = CIPHER_WEP64;
-
-	keybuff = buffer;
-	KeyLen = strlen(keybuff);
-
-	if (KeyType == 1)
-	{//Ascii
-		if( (KeyLen == 5) || (KeyLen == 13))
-		{
-			pAd->SharedKey[i][idx].KeyLen = KeyLen;
-			NdisMoveMemory(pAd->SharedKey[i][idx].Key, keybuff, KeyLen);
-			if (KeyLen == 5)
-				CipherAlg = CIPHER_WEP64;
-			else
-				CipherAlg = CIPHER_WEP128;
-			pAd->SharedKey[i][idx].CipherAlg = CipherAlg;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("I/F(ra%d) Key%dStr=%s and type=%s\n", i, idx+1, keybuff, (KeyType == 0) ? "Hex":"Ascii"));
-			return 1;
-		}
-		else
-		{//Invalid key length
-			DBGPRINT(RT_DEBUG_ERROR, ("Key%dStr is Invalid key length! KeyLen = %ld!\n", idx+1, KeyLen));
-			return 0;
-		}
-	}
-	else
-	{//Hex type
-		if( (KeyLen == 10) || (KeyLen == 26))
-		{
-			pAd->SharedKey[i][idx].KeyLen = KeyLen / 2;
-			AtoH(keybuff, pAd->SharedKey[i][idx].Key, KeyLen / 2);
-			if (KeyLen == 10)
-				CipherAlg = CIPHER_WEP64;
-			else
-				CipherAlg = CIPHER_WEP128;
-			pAd->SharedKey[i][idx].CipherAlg = CipherAlg;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("I/F(ra%d) Key%dStr=%s and type=%s\n", i, idx+1, keybuff, (KeyType == 0) ? "Hex":"Ascii"));
-			return 1;
-		}
-		else
-		{//Invalid key length
-			DBGPRINT(RT_DEBUG_ERROR, ("I/F(ra%d) Key%dStr is Invalid key length! KeyLen = %ld!\n", i, idx+1, KeyLen));
-			return 0;
-		}
-	}
-}
-static void rtmp_read_key_parms_from_file(IN  PRTMP_ADAPTER pAd, char *tmpbuf, char *buffer)
-{
-	char		tok_str[16];
-	PUCHAR		macptr;
-	INT			i = 0, idx;
-	ULONG		KeyType[MAX_MBSSID_NUM];
-	ULONG		KeyIdx;
-
-	NdisZeroMemory(KeyType, MAX_MBSSID_NUM);
-
-	//DefaultKeyID
-	if(RTMPGetKeyParameter("DefaultKeyID", tmpbuf, 25, buffer))
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			KeyIdx = simple_strtol(tmpbuf, 0, 10);
-			if((KeyIdx >= 1 ) && (KeyIdx <= 4))
-				pAd->StaCfg.DefaultKeyId = (UCHAR) (KeyIdx - 1);
-			else
-				pAd->StaCfg.DefaultKeyId = 0;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("DefaultKeyID(0~3)=%d\n", pAd->StaCfg.DefaultKeyId));
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-
-	for (idx = 0; idx < 4; idx++)
-	{
-		sprintf(tok_str, "Key%dType", idx + 1);
-		//Key1Type
-		if (RTMPGetKeyParameter(tok_str, tmpbuf, 128, buffer))
-		{
-		    for (i = 0, macptr = rstrtok(tmpbuf,";"); macptr; macptr = rstrtok(NULL,";"), i++)
-		    {
-			    KeyType[i] = simple_strtol(macptr, 0, 10);
-		    }
-
-#ifdef CONFIG_STA_SUPPORT
-			IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-			{
-				sprintf(tok_str, "Key%dStr", idx + 1);
-				if (RTMPGetCriticalParameter(tok_str, tmpbuf, 128, buffer))
-				{
-					rtmp_parse_key_buffer_from_file(pAd, tmpbuf, KeyType[BSS0], BSS0, idx);
-				}
-			}
-#endif // CONFIG_STA_SUPPORT //
-		}
-	}
-}
-
-
-#ifdef CONFIG_STA_SUPPORT
-static void rtmp_read_sta_wmm_parms_from_file(IN  PRTMP_ADAPTER pAd, char *tmpbuf, char *buffer)
-{
-	PUCHAR					macptr;
-	INT						i=0;
-	BOOLEAN					bWmmEnable = FALSE;
-
-	//WmmCapable
-	if(RTMPGetKeyParameter("WmmCapable", tmpbuf, 32, buffer))
-	{
-		if(simple_strtol(tmpbuf, 0, 10) != 0) //Enable
-		{
-			pAd->CommonCfg.bWmmCapable = TRUE;
-			bWmmEnable = TRUE;
-		}
-		else //Disable
-		{
-			pAd->CommonCfg.bWmmCapable = FALSE;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("WmmCapable=%d\n", pAd->CommonCfg.bWmmCapable));
-	}
-
-#ifdef QOS_DLS_SUPPORT
-	//DLSCapable
-	if(RTMPGetKeyParameter("DLSCapable", tmpbuf, 32, buffer))
-	{
-		if(simple_strtol(tmpbuf, 0, 10) != 0)  //Enable
-		{
-			pAd->CommonCfg.bDLSCapable = TRUE;
-		}
-		else //Disable
-		{
-			pAd->CommonCfg.bDLSCapable = FALSE;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("bDLSCapable=%d\n", pAd->CommonCfg.bDLSCapable));
-	}
-#endif // QOS_DLS_SUPPORT //
-
-	//AckPolicy for AC_BK, AC_BE, AC_VI, AC_VO
-	if(RTMPGetKeyParameter("AckPolicy", tmpbuf, 32, buffer))
-	{
-		for (i = 0, macptr = rstrtok(tmpbuf,";"); macptr; macptr = rstrtok(NULL,";"), i++)
-		{
-			pAd->CommonCfg.AckPolicy[i] = (UCHAR)simple_strtol(macptr, 0, 10);
-
-			DBGPRINT(RT_DEBUG_TRACE, ("AckPolicy[%d]=%d\n", i, pAd->CommonCfg.AckPolicy[i]));
-		}
-	}
-
-	if (bWmmEnable)
-	{
-		//APSDCapable
-		if(RTMPGetKeyParameter("APSDCapable", tmpbuf, 10, buffer))
-		{
-			if(simple_strtol(tmpbuf, 0, 10) != 0)  //Enable
-				pAd->CommonCfg.bAPSDCapable = TRUE;
-			else
-				pAd->CommonCfg.bAPSDCapable = FALSE;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("APSDCapable=%d\n", pAd->CommonCfg.bAPSDCapable));
-		}
-
-		//APSDAC for AC_BE, AC_BK, AC_VI, AC_VO
-		if(RTMPGetKeyParameter("APSDAC", tmpbuf, 32, buffer))
-		{
-			BOOLEAN apsd_ac[4];
-
-			for (i = 0, macptr = rstrtok(tmpbuf,";"); macptr; macptr = rstrtok(NULL,";"), i++)
-			{
-				apsd_ac[i] = (BOOLEAN)simple_strtol(macptr, 0, 10);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("APSDAC%d  %d\n", i,  apsd_ac[i]));
-			}
-
-			pAd->CommonCfg.bAPSDAC_BE = apsd_ac[0];
-			pAd->CommonCfg.bAPSDAC_BK = apsd_ac[1];
-			pAd->CommonCfg.bAPSDAC_VI = apsd_ac[2];
-			pAd->CommonCfg.bAPSDAC_VO = apsd_ac[3];
-		}
-	}
-
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-NDIS_STATUS	RTMPReadParametersHook(
-	IN	PRTMP_ADAPTER pAd)
-{
-	PUCHAR					src = NULL;
-	struct file				*srcf;
-	INT 					retval, orgfsuid, orgfsgid;
-   	mm_segment_t			orgfs;
-	CHAR					*buffer;
-	CHAR					*tmpbuf;
-	ULONG					RtsThresh;
-	ULONG					FragThresh;
-#ifdef CONFIG_STA_SUPPORT
-	UCHAR	                keyMaterial[40];
-#endif // CONFIG_STA_SUPPORT //
-
-
-	PUCHAR					macptr;
-	INT						i = 0;
-
-	buffer = kmalloc(MAX_INI_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	if(buffer == NULL)
-        return NDIS_STATUS_FAILURE;
-
-	tmpbuf = kmalloc(MAX_PARAM_BUFFER_SIZE, MEM_ALLOC_FLAG);
-	if(tmpbuf == NULL)
-	{
-		kfree(buffer);
-        return NDIS_STATUS_FAILURE;
-	}
-
-#ifdef CONFIG_STA_SUPPORT
-	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		src = STA_PROFILE_PATH;
-#endif // CONFIG_STA_SUPPORT //
-#ifdef MULTIPLE_CARD_SUPPORT
-	src = pAd->MC_FileName;
-#endif // MULTIPLE_CARD_SUPPORT //
-
-	// Save uid and gid used for filesystem access.
-	// Set user and group to 0 (root)
-#if 0
-	orgfsuid = current->fsuid;
-	orgfsgid = current->fsgid;
-	current->fsuid=current->fsgid = 0;
-#endif
-    orgfs = get_fs();
-    set_fs(KERNEL_DS);
-
-	if (src && *src)
-	{
-		srcf = filp_open(src, O_RDONLY, 0);
-		if (IS_ERR(srcf))
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("--> Error %ld opening %s\n", -PTR_ERR(srcf),src));
-		}
-		else
-		{
-			// The object must have a read method
-			if (srcf->f_op && srcf->f_op->read)
-			{
-				memset(buffer, 0x00, MAX_INI_BUFFER_SIZE);
-				retval=srcf->f_op->read(srcf, buffer, MAX_INI_BUFFER_SIZE, &srcf->f_pos);
-				if (retval < 0)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("--> Read %s error %d\n", src, -retval));
-				}
-				else
-				{
-					// set file parameter to portcfg
-					//CountryRegion
-					if(RTMPGetKeyParameter("CountryRegion", tmpbuf, 25, buffer))
-					{
-						pAd->CommonCfg.CountryRegion = (UCHAR) simple_strtol(tmpbuf, 0, 10);
-						DBGPRINT(RT_DEBUG_TRACE, ("CountryRegion=%d\n", pAd->CommonCfg.CountryRegion));
-					}
-					//CountryRegionABand
-					if(RTMPGetKeyParameter("CountryRegionABand", tmpbuf, 25, buffer))
-					{
-						pAd->CommonCfg.CountryRegionForABand= (UCHAR) simple_strtol(tmpbuf, 0, 10);
-						DBGPRINT(RT_DEBUG_TRACE, ("CountryRegionABand=%d\n", pAd->CommonCfg.CountryRegionForABand));
-					}
-					//CountryCode
-					if(RTMPGetKeyParameter("CountryCode", tmpbuf, 25, buffer))
-					{
-						NdisMoveMemory(pAd->CommonCfg.CountryCode, tmpbuf , 2);
-#ifdef CONFIG_STA_SUPPORT
-#ifdef EXT_BUILD_CHANNEL_LIST
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-							NdisMoveMemory(pAd->StaCfg.StaOriCountryCode, tmpbuf , 2);
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
-						if (strlen(pAd->CommonCfg.CountryCode) != 0)
-						{
-							pAd->CommonCfg.bCountryFlag = TRUE;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, ("CountryCode=%s\n", pAd->CommonCfg.CountryCode));
-					}
-					//ChannelGeography
-					if(RTMPGetKeyParameter("ChannelGeography", tmpbuf, 25, buffer))
-					{
-						UCHAR Geography = (UCHAR) simple_strtol(tmpbuf, 0, 10);
-						if (Geography <= BOTH)
-						{
-							pAd->CommonCfg.Geography = Geography;
-							pAd->CommonCfg.CountryCode[2] =
-								(pAd->CommonCfg.Geography == BOTH) ? ' ' : ((pAd->CommonCfg.Geography == IDOR) ? 'I' : 'O');
-#ifdef CONFIG_STA_SUPPORT
-#ifdef EXT_BUILD_CHANNEL_LIST
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-							pAd->StaCfg.StaOriGeography = pAd->CommonCfg.Geography;
-#endif // EXT_BUILD_CHANNEL_LIST //
-#endif // CONFIG_STA_SUPPORT //
-							DBGPRINT(RT_DEBUG_TRACE, ("ChannelGeography=%d\n", pAd->CommonCfg.Geography));
-						}
-					}
-					else
-					{
-						pAd->CommonCfg.Geography = BOTH;
-						pAd->CommonCfg.CountryCode[2] = ' ';
-					}
-
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-					{
-						//SSID
-						if (RTMPGetCriticalParameter("SSID", tmpbuf, 256, buffer))
-						{
-							if (strlen(tmpbuf) <= 32)
-							{
-			 					pAd->CommonCfg.SsidLen = (UCHAR) strlen(tmpbuf);
-								NdisZeroMemory(pAd->CommonCfg.Ssid, NDIS_802_11_LENGTH_SSID);
-								NdisMoveMemory(pAd->CommonCfg.Ssid, tmpbuf, pAd->CommonCfg.SsidLen);
-								pAd->MlmeAux.AutoReconnectSsidLen = pAd->CommonCfg.SsidLen;
-								NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, NDIS_802_11_LENGTH_SSID);
-								NdisMoveMemory(pAd->MlmeAux.AutoReconnectSsid, tmpbuf, pAd->MlmeAux.AutoReconnectSsidLen);
-								pAd->MlmeAux.SsidLen = pAd->CommonCfg.SsidLen;
-								NdisZeroMemory(pAd->MlmeAux.Ssid, NDIS_802_11_LENGTH_SSID);
-								NdisMoveMemory(pAd->MlmeAux.Ssid, tmpbuf, pAd->MlmeAux.SsidLen);
-								DBGPRINT(RT_DEBUG_TRACE, ("%s::(SSID=%s)\n", __FUNCTION__, tmpbuf));
-							}
-						}
-					}
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-					{
-						//NetworkType
-						if (RTMPGetKeyParameter("NetworkType", tmpbuf, 25, buffer))
-						{
-							pAd->bConfigChanged = TRUE;
-							if (strcmp(tmpbuf, "Adhoc") == 0)
-								pAd->StaCfg.BssType = BSS_ADHOC;
-							else //Default Infrastructure mode
-								pAd->StaCfg.BssType = BSS_INFRA;
-							// Reset Ralink supplicant to not use, it will be set to start when UI set PMK key
-							pAd->StaCfg.WpaState = SS_NOTUSE;
-							DBGPRINT(RT_DEBUG_TRACE, ("%s::(NetworkType=%d)\n", __FUNCTION__, pAd->StaCfg.BssType));
-						}
-					}
-#endif // CONFIG_STA_SUPPORT //
-					//Channel
-					if(RTMPGetKeyParameter("Channel", tmpbuf, 10, buffer))
-					{
-						pAd->CommonCfg.Channel = (UCHAR) simple_strtol(tmpbuf, 0, 10);
-						DBGPRINT(RT_DEBUG_TRACE, ("Channel=%d\n", pAd->CommonCfg.Channel));
-					}
-					//WirelessMode
-					if(RTMPGetKeyParameter("WirelessMode", tmpbuf, 10, buffer))
-					{
-						int value  = 0, maxPhyMode = PHY_11G;
-
-#ifdef DOT11_N_SUPPORT
-						maxPhyMode = PHY_11N_5G;
-#endif // DOT11_N_SUPPORT //
-
-						value = simple_strtol(tmpbuf, 0, 10);
-
-						if (value <= maxPhyMode)
-						{
-							pAd->CommonCfg.PhyMode = value;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, ("PhyMode=%d\n", pAd->CommonCfg.PhyMode));
-					}
-                    //BasicRate
-					if(RTMPGetKeyParameter("BasicRate", tmpbuf, 10, buffer))
-					{
-						pAd->CommonCfg.BasicRateBitmap = (ULONG) simple_strtol(tmpbuf, 0, 10);
-						DBGPRINT(RT_DEBUG_TRACE, ("BasicRate=%ld\n", pAd->CommonCfg.BasicRateBitmap));
-					}
-					//BeaconPeriod
-					if(RTMPGetKeyParameter("BeaconPeriod", tmpbuf, 10, buffer))
-					{
-						pAd->CommonCfg.BeaconPeriod = (USHORT) simple_strtol(tmpbuf, 0, 10);
-						DBGPRINT(RT_DEBUG_TRACE, ("BeaconPeriod=%d\n", pAd->CommonCfg.BeaconPeriod));
-					}
-                    //TxPower
-					if(RTMPGetKeyParameter("TxPower", tmpbuf, 10, buffer))
-					{
-						pAd->CommonCfg.TxPowerPercentage = (ULONG) simple_strtol(tmpbuf, 0, 10);
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-							pAd->CommonCfg.TxPowerDefault = pAd->CommonCfg.TxPowerPercentage;
-#endif // CONFIG_STA_SUPPORT //
-						DBGPRINT(RT_DEBUG_TRACE, ("TxPower=%ld\n", pAd->CommonCfg.TxPowerPercentage));
-					}
-					//BGProtection
-					if(RTMPGetKeyParameter("BGProtection", tmpbuf, 10, buffer))
-					{
-						switch (simple_strtol(tmpbuf, 0, 10))
-						{
-							case 1: //Always On
-								pAd->CommonCfg.UseBGProtection = 1;
-								break;
-							case 2: //Always OFF
-								pAd->CommonCfg.UseBGProtection = 2;
-								break;
-							case 0: //AUTO
-							default:
-								pAd->CommonCfg.UseBGProtection = 0;
-								break;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, ("BGProtection=%ld\n", pAd->CommonCfg.UseBGProtection));
-					}
-					//OLBCDetection
-					if(RTMPGetKeyParameter("DisableOLBC", tmpbuf, 10, buffer))
-					{
-						switch (simple_strtol(tmpbuf, 0, 10))
-						{
-							case 1: //disable OLBC Detection
-								pAd->CommonCfg.DisableOLBCDetect = 1;
-								break;
-							case 0: //enable OLBC Detection
-								pAd->CommonCfg.DisableOLBCDetect = 0;
-								break;
-							default:
-								pAd->CommonCfg.DisableOLBCDetect= 0;
-								break;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, ("OLBCDetection=%ld\n", pAd->CommonCfg.DisableOLBCDetect));
-					}
-					//TxPreamble
-					if(RTMPGetKeyParameter("TxPreamble", tmpbuf, 10, buffer))
-					{
-						switch (simple_strtol(tmpbuf, 0, 10))
-						{
-							case Rt802_11PreambleShort:
-								pAd->CommonCfg.TxPreamble = Rt802_11PreambleShort;
-								break;
-							case Rt802_11PreambleLong:
-							default:
-								pAd->CommonCfg.TxPreamble = Rt802_11PreambleLong;
-								break;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, ("TxPreamble=%ld\n", pAd->CommonCfg.TxPreamble));
-					}
-					//RTSThreshold
-					if(RTMPGetKeyParameter("RTSThreshold", tmpbuf, 10, buffer))
-					{
-						RtsThresh = simple_strtol(tmpbuf, 0, 10);
-						if( (RtsThresh >= 1) && (RtsThresh <= MAX_RTS_THRESHOLD) )
-							pAd->CommonCfg.RtsThreshold  = (USHORT)RtsThresh;
-						else
-							pAd->CommonCfg.RtsThreshold = MAX_RTS_THRESHOLD;
-
-						DBGPRINT(RT_DEBUG_TRACE, ("RTSThreshold=%d\n", pAd->CommonCfg.RtsThreshold));
-					}
-					//FragThreshold
-					if(RTMPGetKeyParameter("FragThreshold", tmpbuf, 10, buffer))
-					{
-						FragThresh = simple_strtol(tmpbuf, 0, 10);
-						pAd->CommonCfg.bUseZeroToDisableFragment = FALSE;
-
-						if (FragThresh > MAX_FRAG_THRESHOLD || FragThresh < MIN_FRAG_THRESHOLD)
-						{ //illegal FragThresh so we set it to default
-							pAd->CommonCfg.FragmentThreshold = MAX_FRAG_THRESHOLD;
-							pAd->CommonCfg.bUseZeroToDisableFragment = TRUE;
-						}
-						else if (FragThresh % 2 == 1)
-						{
-							// The length of each fragment shall always be an even number of octets, except for the last fragment
-							// of an MSDU or MMPDU, which may be either an even or an odd number of octets.
-							pAd->CommonCfg.FragmentThreshold = (USHORT)(FragThresh - 1);
-						}
-						else
-						{
-							pAd->CommonCfg.FragmentThreshold = (USHORT)FragThresh;
-						}
-						//pAd->CommonCfg.AllowFragSize = (pAd->CommonCfg.FragmentThreshold) - LENGTH_802_11 - LENGTH_CRC;
-						DBGPRINT(RT_DEBUG_TRACE, ("FragThreshold=%d\n", pAd->CommonCfg.FragmentThreshold));
-					}
-					//TxBurst
-					if(RTMPGetKeyParameter("TxBurst", tmpbuf, 10, buffer))
-					{
-//#ifdef WIFI_TEST
-//						pAd->CommonCfg.bEnableTxBurst = FALSE;
-//#else
-						if(simple_strtol(tmpbuf, 0, 10) != 0)  //Enable
-							pAd->CommonCfg.bEnableTxBurst = TRUE;
-						else //Disable
-							pAd->CommonCfg.bEnableTxBurst = FALSE;
-//#endif
-						DBGPRINT(RT_DEBUG_TRACE, ("TxBurst=%d\n", pAd->CommonCfg.bEnableTxBurst));
-					}
-
-#ifdef AGGREGATION_SUPPORT
-					//PktAggregate
-					if(RTMPGetKeyParameter("PktAggregate", tmpbuf, 10, buffer))
-					{
-						if(simple_strtol(tmpbuf, 0, 10) != 0)  //Enable
-							pAd->CommonCfg.bAggregationCapable = TRUE;
-						else //Disable
-							pAd->CommonCfg.bAggregationCapable = FALSE;
-#ifdef PIGGYBACK_SUPPORT
-						pAd->CommonCfg.bPiggyBackCapable = pAd->CommonCfg.bAggregationCapable;
-#endif // PIGGYBACK_SUPPORT //
-						DBGPRINT(RT_DEBUG_TRACE, ("PktAggregate=%d\n", pAd->CommonCfg.bAggregationCapable));
-					}
-#else
-					pAd->CommonCfg.bAggregationCapable = FALSE;
-					pAd->CommonCfg.bPiggyBackCapable = FALSE;
-#endif // AGGREGATION_SUPPORT //
-
-					// WmmCapable
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-						rtmp_read_sta_wmm_parms_from_file(pAd, tmpbuf, buffer);
-#endif // CONFIG_STA_SUPPORT //
-
-					//ShortSlot
-					if(RTMPGetKeyParameter("ShortSlot", tmpbuf, 10, buffer))
-					{
-						if(simple_strtol(tmpbuf, 0, 10) != 0)  //Enable
-							pAd->CommonCfg.bUseShortSlotTime = TRUE;
-						else //Disable
-							pAd->CommonCfg.bUseShortSlotTime = FALSE;
-
-						DBGPRINT(RT_DEBUG_TRACE, ("ShortSlot=%d\n", pAd->CommonCfg.bUseShortSlotTime));
-					}
-					//IEEE80211H
-					if(RTMPGetKeyParameter("IEEE80211H", tmpbuf, 10, buffer))
-					{
-					    for (i = 0, macptr = rstrtok(tmpbuf,";"); macptr; macptr = rstrtok(NULL,";"), i++)
-					    {
-    						if(simple_strtol(macptr, 0, 10) != 0)  //Enable
-    							pAd->CommonCfg.bIEEE80211H = TRUE;
-    						else //Disable
-    							pAd->CommonCfg.bIEEE80211H = FALSE;
-
-    						DBGPRINT(RT_DEBUG_TRACE, ("IEEE80211H=%d\n", pAd->CommonCfg.bIEEE80211H));
-					    }
-					}
-					//CSPeriod
-					if(RTMPGetKeyParameter("CSPeriod", tmpbuf, 10, buffer))
-					{
-					    if(simple_strtol(tmpbuf, 0, 10) != 0)
-							pAd->CommonCfg.RadarDetect.CSPeriod = simple_strtol(tmpbuf, 0, 10);
-						else
-							pAd->CommonCfg.RadarDetect.CSPeriod = 0;
-
-   						DBGPRINT(RT_DEBUG_TRACE, ("CSPeriod=%d\n", pAd->CommonCfg.RadarDetect.CSPeriod));
-					}
-
-					//RDRegion
-					if(RTMPGetKeyParameter("RDRegion", tmpbuf, 128, buffer))
-					{
-						if ((strncmp(tmpbuf, "JAP_W53", 7) == 0) || (strncmp(tmpbuf, "jap_w53", 7) == 0))
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = JAP_W53;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 15;
-						}
-						else if ((strncmp(tmpbuf, "JAP_W56", 7) == 0) || (strncmp(tmpbuf, "jap_w56", 7) == 0))
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = JAP_W56;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 13;
-						}
-						else if ((strncmp(tmpbuf, "JAP", 3) == 0) || (strncmp(tmpbuf, "jap", 3) == 0))
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = JAP;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 5;
-						}
-						else  if ((strncmp(tmpbuf, "FCC", 3) == 0) || (strncmp(tmpbuf, "fcc", 3) == 0))
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = FCC;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 5;
-						}
-						else if ((strncmp(tmpbuf, "CE", 2) == 0) || (strncmp(tmpbuf, "ce", 2) == 0))
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = CE;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 13;
-						}
-						else
-						{
-							pAd->CommonCfg.RadarDetect.RDDurRegion = CE;
-							pAd->CommonCfg.RadarDetect.DfsSessionTime = 13;
-						}
-
-						DBGPRINT(RT_DEBUG_TRACE, ("RDRegion=%d\n", pAd->CommonCfg.RadarDetect.RDDurRegion));
-					}
-					else
-					{
-						pAd->CommonCfg.RadarDetect.RDDurRegion = CE;
-						pAd->CommonCfg.RadarDetect.DfsSessionTime = 13;
-					}
-
-					//WirelessEvent
-					if(RTMPGetKeyParameter("WirelessEvent", tmpbuf, 10, buffer))
-					{
-#if WIRELESS_EXT >= 15
-					    if(simple_strtol(tmpbuf, 0, 10) != 0)
-							pAd->CommonCfg.bWirelessEvent = simple_strtol(tmpbuf, 0, 10);
-						else
-							pAd->CommonCfg.bWirelessEvent = 0;	// disable
-#else
-						pAd->CommonCfg.bWirelessEvent = 0;	// disable
-#endif
-   						DBGPRINT(RT_DEBUG_TRACE, ("WirelessEvent=%d\n", pAd->CommonCfg.bWirelessEvent));
-					}
-					if(RTMPGetKeyParameter("WiFiTest", tmpbuf, 10, buffer))
-					{
-					    if(simple_strtol(tmpbuf, 0, 10) != 0)
-							pAd->CommonCfg.bWiFiTest= simple_strtol(tmpbuf, 0, 10);
-						else
-							pAd->CommonCfg.bWiFiTest = 0;	// disable
-
-   						DBGPRINT(RT_DEBUG_TRACE, ("WiFiTest=%d\n", pAd->CommonCfg.bWiFiTest));
-					}
-					//AuthMode
-					if(RTMPGetKeyParameter("AuthMode", tmpbuf, 128, buffer))
-					{
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-						{
-							if ((strcmp(tmpbuf, "WEPAUTO") == 0) || (strcmp(tmpbuf, "wepauto") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeAutoSwitch;
-							else if ((strcmp(tmpbuf, "SHARED") == 0) || (strcmp(tmpbuf, "shared") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-							else if ((strcmp(tmpbuf, "WPAPSK") == 0) || (strcmp(tmpbuf, "wpapsk") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPAPSK;
-							else if ((strcmp(tmpbuf, "WPANONE") == 0) || (strcmp(tmpbuf, "wpanone") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
-							else if ((strcmp(tmpbuf, "WPA2PSK") == 0) || (strcmp(tmpbuf, "wpa2psk") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-#ifdef WPA_SUPPLICANT_SUPPORT
-							else if ((strcmp(tmpbuf, "WPA") == 0) || (strcmp(tmpbuf, "wpa") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
-							else if ((strcmp(tmpbuf, "WPA2") == 0) || (strcmp(tmpbuf, "wpa2") == 0))
-							    pAd->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#endif // WPA_SUPPLICANT_SUPPORT //
-				                        else
-				                            pAd->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-
-				                        pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-
-							DBGPRINT(RT_DEBUG_TRACE, ("%s::(EncrypType=%d)\n", __FUNCTION__, pAd->StaCfg.WepStatus));
-						}
-#endif // CONFIG_STA_SUPPORT //
-					}
-					//EncrypType
-					if(RTMPGetKeyParameter("EncrypType", tmpbuf, 128, buffer))
-					{
-
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-						{
-							if ((strcmp(tmpbuf, "WEP") == 0) || (strcmp(tmpbuf, "wep") == 0))
-								pAd->StaCfg.WepStatus	= Ndis802_11WEPEnabled;
-							else if ((strcmp(tmpbuf, "TKIP") == 0) || (strcmp(tmpbuf, "tkip") == 0))
-								pAd->StaCfg.WepStatus	= Ndis802_11Encryption2Enabled;
-							else if ((strcmp(tmpbuf, "AES") == 0) || (strcmp(tmpbuf, "aes") == 0))
-								pAd->StaCfg.WepStatus	= Ndis802_11Encryption3Enabled;
-							else
-								pAd->StaCfg.WepStatus	= Ndis802_11WEPDisabled;
-
-							// Update all wepstatus related
-							pAd->StaCfg.PairCipher		= pAd->StaCfg.WepStatus;
-							pAd->StaCfg.GroupCipher 	= pAd->StaCfg.WepStatus;
-							pAd->StaCfg.OrigWepStatus 	= pAd->StaCfg.WepStatus;
-							pAd->StaCfg.bMixCipher 		= FALSE;
-
-							//RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, 0);
-							DBGPRINT(RT_DEBUG_TRACE, ("%s::(EncrypType=%d)\n", __FUNCTION__, pAd->StaCfg.WepStatus));
-						}
-#endif // CONFIG_STA_SUPPORT //
-					}
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-					{
-						if(RTMPGetCriticalParameter("WPAPSK", tmpbuf, 512, buffer))
-						{
-							int     err=0;
-
-							tmpbuf[strlen(tmpbuf)] = '\0'; // make STA can process .$^& for WPAPSK input
-
-							if ((pAd->StaCfg.AuthMode != Ndis802_11AuthModeWPAPSK) &&
-								(pAd->StaCfg.AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-								(pAd->StaCfg.AuthMode != Ndis802_11AuthModeWPANone)
-								)
-							{
-								err = 1;
-							}
-							else if ((strlen(tmpbuf) >= 8) && (strlen(tmpbuf) < 64))
-							{
-								PasswordHash((char *)tmpbuf, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen, keyMaterial);
-								NdisMoveMemory(pAd->StaCfg.PMK, keyMaterial, 32);
-
-							}
-							else if (strlen(tmpbuf) == 64)
-							{
-								AtoH(tmpbuf, keyMaterial, 32);
-								NdisMoveMemory(pAd->StaCfg.PMK, keyMaterial, 32);
-							}
-							else
-							{
-								err = 1;
-								DBGPRINT(RT_DEBUG_ERROR, ("%s::(WPAPSK key-string required 8 ~ 64 characters!)\n", __FUNCTION__));
-							}
-
-							if (err == 0)
-	                        			{
-	                        				if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-									(pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-								{
-									// Start STA supplicant state machine
-									pAd->StaCfg.WpaState = SS_START;
-								}
-								else if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-								{
-	/*
-									NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-									pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-									NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, pAd->StaCfg.PMK, LEN_TKIP_EK);
-									NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, &pAd->StaCfg.PMK[16], LEN_TKIP_RXMICK);
-									NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, &pAd->StaCfg.PMK[16], LEN_TKIP_TXMICK);
-
-									// Decide its ChiperAlg
-									if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-										pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-									else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-										pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-									else
-										pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_NONE;
-	*/
-									pAd->StaCfg.WpaState = SS_NOTUSE;
-								}
-
-								DBGPRINT(RT_DEBUG_TRACE, ("%s::(WPAPSK=%s)\n", __FUNCTION__, tmpbuf));
-							}
-						}
-					}
-#endif // CONFIG_STA_SUPPORT //
-
-					//DefaultKeyID, KeyType, KeyStr
-					rtmp_read_key_parms_from_file(pAd, tmpbuf, buffer);
-
-
-					//HSCounter
-					/*if(RTMPGetKeyParameter("HSCounter", tmpbuf, 10, buffer))
-					{
-						switch (simple_strtol(tmpbuf, 0, 10))
-						{
-							case 1: //Enable
-								pAd->CommonCfg.bEnableHSCounter = TRUE;
-								break;
-							case 0: //Disable
-							default:
-								pAd->CommonCfg.bEnableHSCounter = FALSE;
-								break;
-						}
-						DBGPRINT(RT_DEBUG_TRACE, "HSCounter=%d\n", pAd->CommonCfg.bEnableHSCounter);
-					}*/
-
-#ifdef DOT11_N_SUPPORT
-					HTParametersHook(pAd, tmpbuf, buffer);
-#endif // DOT11_N_SUPPORT //
-
-
-#ifdef CARRIER_DETECTION_SUPPORT
-						//CarrierDetect
-						if(RTMPGetKeyParameter("CarrierDetect", tmpbuf, 128, buffer))
-						{
-							if ((strncmp(tmpbuf, "0", 1) == 0))
-								pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-							else if ((strncmp(tmpbuf, "1", 1) == 0))
-								pAd->CommonCfg.CarrierDetect.Enable = TRUE;
-							else
-								pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-
-							DBGPRINT(RT_DEBUG_TRACE, ("CarrierDetect.Enable=%d\n", pAd->CommonCfg.CarrierDetect.Enable));
-						}
-						else
-							pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-#endif // CARRIER_DETECTION_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-					IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-					{
-						//PSMode
-						if (RTMPGetKeyParameter("PSMode", tmpbuf, 10, buffer))
-						{
-							if (pAd->StaCfg.BssType == BSS_INFRA)
-							{
-								if ((strcmp(tmpbuf, "MAX_PSP") == 0) || (strcmp(tmpbuf, "max_psp") == 0))
-								{
-									// do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-									// to exclude certain situations.
-									//	   MlmeSetPsm(pAd, PWR_SAVE);
-									OPSTATUS_SET_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM);
-									if (pAd->StaCfg.bWindowsACCAMEnable == FALSE)
-										pAd->StaCfg.WindowsPowerMode = Ndis802_11PowerModeMAX_PSP;
-									pAd->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeMAX_PSP;
-									pAd->StaCfg.DefaultListenCount = 5;
-								}
-								else if ((strcmp(tmpbuf, "Fast_PSP") == 0) || (strcmp(tmpbuf, "fast_psp") == 0)
-									|| (strcmp(tmpbuf, "FAST_PSP") == 0))
-								{
-									// do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-									// to exclude certain situations.
-									//	   MlmeSetPsmBit(pAd, PWR_SAVE);
-									OPSTATUS_SET_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM);
-									if (pAd->StaCfg.bWindowsACCAMEnable == FALSE)
-										pAd->StaCfg.WindowsPowerMode = Ndis802_11PowerModeFast_PSP;
-									pAd->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeFast_PSP;
-									pAd->StaCfg.DefaultListenCount = 3;
-								}
-								else if ((strcmp(tmpbuf, "Legacy_PSP") == 0) || (strcmp(tmpbuf, "legacy_psp") == 0)
-									|| (strcmp(tmpbuf, "LEGACY_PSP") == 0))
-								{
-									// do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-									// to exclude certain situations.
-									//	   MlmeSetPsmBit(pAd, PWR_SAVE);
-									OPSTATUS_SET_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM);
-									if (pAd->StaCfg.bWindowsACCAMEnable == FALSE)
-										pAd->StaCfg.WindowsPowerMode = Ndis802_11PowerModeLegacy_PSP;
-									pAd->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeLegacy_PSP;
-									pAd->StaCfg.DefaultListenCount = 3;
-								}
-								else
-								{ //Default Ndis802_11PowerModeCAM
-									// clear PSM bit immediately
-									MlmeSetPsmBit(pAd, PWR_ACTIVE);
-									OPSTATUS_SET_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM);
-									if (pAd->StaCfg.bWindowsACCAMEnable == FALSE)
-										pAd->StaCfg.WindowsPowerMode = Ndis802_11PowerModeCAM;
-									pAd->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeCAM;
-								}
-								DBGPRINT(RT_DEBUG_TRACE, ("PSMode=%ld\n", pAd->StaCfg.WindowsPowerMode));
-							}
-						}
-						// FastRoaming
-						if (RTMPGetKeyParameter("FastRoaming", tmpbuf, 32, buffer))
-						{
-							if (simple_strtol(tmpbuf, 0, 10) == 0)
-								pAd->StaCfg.bFastRoaming = FALSE;
-							else
-								pAd->StaCfg.bFastRoaming = TRUE;
-
-							DBGPRINT(RT_DEBUG_TRACE, ("FastRoaming=%d\n", pAd->StaCfg.bFastRoaming));
-						}
-						// RoamThreshold
-						if (RTMPGetKeyParameter("RoamThreshold", tmpbuf, 32, buffer))
-						{
-							long lInfo = simple_strtol(tmpbuf, 0, 10);
-
-							if (lInfo > 90 || lInfo < 60)
-								pAd->StaCfg.dBmToRoam = -70;
-							else
-								pAd->StaCfg.dBmToRoam = (CHAR)(-1)*lInfo;
-
-							DBGPRINT(RT_DEBUG_TRACE, ("RoamThreshold=%d  dBm\n", pAd->StaCfg.dBmToRoam));
-						}
-
-						if(RTMPGetKeyParameter("TGnWifiTest", tmpbuf, 10, buffer))
-						{
-							if(simple_strtol(tmpbuf, 0, 10) == 0)
-								pAd->StaCfg.bTGnWifiTest = FALSE;
-							else
-								pAd->StaCfg.bTGnWifiTest = TRUE;
-								DBGPRINT(RT_DEBUG_TRACE, ("TGnWifiTest=%d\n", pAd->StaCfg.bTGnWifiTest));
-						}
-					}
-#endif // CONFIG_STA_SUPPORT //
-
-
-#ifdef RT30xx
-#ifdef CONFIG_STA_SUPPORT
-						IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-						{
-							if(RTMPGetKeyParameter("AntDiversity", tmpbuf, 10, buffer))
-							{
-								for (i = 0, macptr = rstrtok(tmpbuf,";"); macptr; macptr = rstrtok(NULL,";"), i++)
-								{
-									if(simple_strtol(macptr, 0, 10) != 0)  //Enable
-										pAd->CommonCfg.bRxAntDiversity = TRUE;
-									else //Disable
-										pAd->CommonCfg.bRxAntDiversity = FALSE;
-
-									DBGPRINT(RT_DEBUG_ERROR, ("AntDiversity=%d\n", pAd->CommonCfg.bRxAntDiversity));
-								}
-							}
-						}
-#endif // CONFIG_STA_SUPPORT //
-#endif // RT30xx //
-				}
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("--> %s does not have a write method\n", src));
-			}
-
-			retval=filp_close(srcf,NULL);
-
-			if (retval)
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("--> Error %d closing %s\n", -retval, src));
-			}
-		}
-	}
-
-	set_fs(orgfs);
-#if 0
-	current->fsuid = orgfsuid;
-	current->fsgid = orgfsgid;
-#endif
-
-	kfree(buffer);
-	kfree(tmpbuf);
-
-	return (NDIS_STATUS_SUCCESS);
-}
-
-#ifdef DOT11_N_SUPPORT
-static void	HTParametersHook(
-	IN	PRTMP_ADAPTER pAd,
-	IN	CHAR		  *pValueStr,
-	IN	CHAR		  *pInput)
-{
-
-	INT Value;
-
-    if (RTMPGetKeyParameter("HT_PROTECT", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value == 0)
-        {
-            pAd->CommonCfg.bHTProtect = FALSE;
-        }
-        else
-        {
-            pAd->CommonCfg.bHTProtect = TRUE;
-        }
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: Protection  = %s\n", (Value==0) ? "Disable" : "Enable"));
-    }
-
-    if (RTMPGetKeyParameter("HT_MIMOPSEnable", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value == 0)
-        {
-            pAd->CommonCfg.bMIMOPSEnable = FALSE;
-        }
-        else
-        {
-            pAd->CommonCfg.bMIMOPSEnable = TRUE;
-        }
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: MIMOPSEnable  = %s\n", (Value==0) ? "Disable" : "Enable"));
-    }
-
-
-    if (RTMPGetKeyParameter("HT_MIMOPSMode", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value > MMPS_ENABLE)
-        {
-			pAd->CommonCfg.BACapability.field.MMPSmode = MMPS_ENABLE;
-        }
-        else
-        {
-            //TODO: add mimo power saving mechanism
-            pAd->CommonCfg.BACapability.field.MMPSmode = MMPS_ENABLE;
-			//pAd->CommonCfg.BACapability.field.MMPSmode = Value;
-        }
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: MIMOPS Mode  = %d\n", Value));
-    }
-
-    if (RTMPGetKeyParameter("HT_BADecline", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value == 0)
-        {
-            pAd->CommonCfg.bBADecline = FALSE;
-        }
-        else
-        {
-            pAd->CommonCfg.bBADecline = TRUE;
-        }
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: BA Decline  = %s\n", (Value==0) ? "Disable" : "Enable"));
-    }
-
-
-    if (RTMPGetKeyParameter("HT_DisableReordering", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value == 0)
-        {
-            pAd->CommonCfg.bDisableReordering = FALSE;
-        }
-        else
-        {
-            pAd->CommonCfg.bDisableReordering = TRUE;
-        }
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: DisableReordering  = %s\n", (Value==0) ? "Disable" : "Enable"));
-    }
-
-    if (RTMPGetKeyParameter("HT_AutoBA", pValueStr, 25, pInput))
-    {
-        Value = simple_strtol(pValueStr, 0, 10);
-        if (Value == 0)
-        {
-            pAd->CommonCfg.BACapability.field.AutoBA = FALSE;
-	    pAd->CommonCfg.BACapability.field.Policy = BA_NOTUSE;
-        }
-        else
-        {
-            pAd->CommonCfg.BACapability.field.AutoBA = TRUE;
-	    pAd->CommonCfg.BACapability.field.Policy = IMMED_BA;
-        }
-        pAd->CommonCfg.REGBACapability.field.AutoBA = pAd->CommonCfg.BACapability.field.AutoBA;
-	pAd->CommonCfg.REGBACapability.field.Policy = pAd->CommonCfg.BACapability.field.Policy;
-        DBGPRINT(RT_DEBUG_TRACE, ("HT: Auto BA  = %s\n", (Value==0) ? "Disable" : "Enable"));
-    }
-
-	// Tx_+HTC frame
-    if (RTMPGetKeyParameter("HT_HTC", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == 0)
-		{
-			pAd->HTCEnable = FALSE;
-		}
-		else
-		{
-            		pAd->HTCEnable = TRUE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Tx +HTC frame = %s\n", (Value==0) ? "Disable" : "Enable"));
-	}
-
-	// Enable HT Link Adaptation Control
-	if (RTMPGetKeyParameter("HT_LinkAdapt", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == 0)
-		{
-			pAd->bLinkAdapt = FALSE;
-		}
-		else
-		{
-			pAd->HTCEnable = TRUE;
-			pAd->bLinkAdapt = TRUE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Link Adaptation Control = %s\n", (Value==0) ? "Disable" : "Enable(+HTC)"));
-	}
-
-	// Reverse Direction Mechanism
-    if (RTMPGetKeyParameter("HT_RDG", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == 0)
-		{
-			pAd->CommonCfg.bRdg = FALSE;
-		}
-		else
-		{
-			pAd->HTCEnable = TRUE;
-            pAd->CommonCfg.bRdg = TRUE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: RDG = %s\n", (Value==0) ? "Disable" : "Enable(+HTC)"));
-	}
-
-
-
-
-	// Tx A-MSUD ?
-    if (RTMPGetKeyParameter("HT_AMSDU", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == 0)
-		{
-			pAd->CommonCfg.BACapability.field.AmsduEnable = FALSE;
-		}
-		else
-		{
-            pAd->CommonCfg.BACapability.field.AmsduEnable = TRUE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Tx A-MSDU = %s\n", (Value==0) ? "Disable" : "Enable"));
-	}
-
-	// MPDU Density
-    if (RTMPGetKeyParameter("HT_MpduDensity", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value <=7 && Value >= 0)
-		{
-			pAd->CommonCfg.BACapability.field.MpduDensity = Value;
-			DBGPRINT(RT_DEBUG_TRACE, ("HT: MPDU Density = %d\n", Value));
-		}
-		else
-		{
-			pAd->CommonCfg.BACapability.field.MpduDensity = 4;
-			DBGPRINT(RT_DEBUG_TRACE, ("HT: MPDU Density = %d (Default)\n", 4));
-		}
-	}
-
-	// Max Rx BA Window Size
-    if (RTMPGetKeyParameter("HT_BAWinSize", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-
-		if (Value >=1 && Value <= 64)
-		{
-			pAd->CommonCfg.REGBACapability.field.RxBAWinLimit = Value;
-			pAd->CommonCfg.BACapability.field.RxBAWinLimit = Value;
-			DBGPRINT(RT_DEBUG_TRACE, ("HT: BA Windw Size = %d\n", Value));
-		}
-		else
-		{
-            pAd->CommonCfg.REGBACapability.field.RxBAWinLimit = 64;
-			pAd->CommonCfg.BACapability.field.RxBAWinLimit = 64;
-			DBGPRINT(RT_DEBUG_TRACE, ("HT: BA Windw Size = 64 (Defualt)\n"));
-		}
-
-	}
-
-	// Guard Interval
-	if (RTMPGetKeyParameter("HT_GI", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-
-		if (Value == GI_400)
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.ShortGI = GI_400;
-		}
-		else
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.ShortGI = GI_800;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Guard Interval = %s\n", (Value==GI_400) ? "400" : "800" ));
-	}
-
-	// HT Operation Mode : Mixed Mode , Green Field
-	if (RTMPGetKeyParameter("HT_OpMode", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-
-		if (Value == HTMODE_GF)
-		{
-
-			pAd->CommonCfg.RegTransmitSetting.field.HTMODE  = HTMODE_GF;
-		}
-		else
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.HTMODE  = HTMODE_MM;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Operate Mode = %s\n", (Value==HTMODE_GF) ? "Green Field" : "Mixed Mode" ));
-	}
-
-	// Fixed Tx mode : CCK, OFDM
-	if (RTMPGetKeyParameter("FixedTxMode", pValueStr, 25, pInput))
-	{
-		UCHAR	fix_tx_mode;
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			fix_tx_mode = FIXED_TXMODE_HT;
-
-			if (strcmp(pValueStr, "OFDM") == 0 || strcmp(pValueStr, "ofdm") == 0)
-			{
-				fix_tx_mode = FIXED_TXMODE_OFDM;
-			}
-			else if (strcmp(pValueStr, "CCK") == 0 || strcmp(pValueStr, "cck") == 0)
-			{
-		        fix_tx_mode = FIXED_TXMODE_CCK;
-			}
-			else if (strcmp(pValueStr, "HT") == 0 || strcmp(pValueStr, "ht") == 0)
-			{
-		        fix_tx_mode = FIXED_TXMODE_HT;
-		}
-		else
-		{
-				Value = simple_strtol(pValueStr, 0, 10);
-				// 1 : CCK
-				// 2 : OFDM
-				// otherwise : HT
-				if (Value == FIXED_TXMODE_CCK || Value == FIXED_TXMODE_OFDM)
-					fix_tx_mode = Value;
-				else
-					fix_tx_mode = FIXED_TXMODE_HT;
-		}
-
-			pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode = fix_tx_mode;
-			DBGPRINT(RT_DEBUG_TRACE, ("Fixed Tx Mode = %d\n", fix_tx_mode));
-
-		}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-
-	// Channel Width
-	if (RTMPGetKeyParameter("HT_BW", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-
-		if (Value == BW_40)
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_40;
-		}
-		else
-		{
-            pAd->CommonCfg.RegTransmitSetting.field.BW  = BW_20;
-		}
-
-#ifdef MCAST_RATE_SPECIFIC
-		pAd->CommonCfg.MCastPhyMode.field.BW = pAd->CommonCfg.RegTransmitSetting.field.BW;
-#endif // MCAST_RATE_SPECIFIC //
-
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Channel Width = %s\n", (Value==BW_40) ? "40 MHz" : "20 MHz" ));
-	}
-
-	if (RTMPGetKeyParameter("HT_EXTCHA", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-
-		if (Value == 0)
-		{
-
-			pAd->CommonCfg.RegTransmitSetting.field.EXTCHA  = EXTCHA_BELOW;
-		}
-		else
-		{
-            pAd->CommonCfg.RegTransmitSetting.field.EXTCHA = EXTCHA_ABOVE;
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Ext Channel = %s\n", (Value==0) ? "BELOW" : "ABOVE" ));
-	}
-
-	// MSC
-	if (RTMPGetKeyParameter("HT_MCS", pValueStr, 50, pInput))
-	{
-
-#ifdef CONFIG_STA_SUPPORT
-		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
-		{
-			Value = simple_strtol(pValueStr, 0, 10);
-
-//			if ((Value >= 0 && Value <= 15) || (Value == 32))
-			if ((Value >= 0 && Value <= 23) || (Value == 32)) // 3*3
-		{
-				pAd->StaCfg.DesiredTransmitSetting.field.MCS  = Value;
-				pAd->StaCfg.bAutoTxRateSwitch = FALSE;
-				DBGPRINT(RT_DEBUG_TRACE, ("HT: MCS = %d\n", pAd->StaCfg.DesiredTransmitSetting.field.MCS));
-		}
-		else
-		{
-				pAd->StaCfg.DesiredTransmitSetting.field.MCS  = MCS_AUTO;
-				pAd->StaCfg.bAutoTxRateSwitch = TRUE;
-				DBGPRINT(RT_DEBUG_TRACE, ("HT: MCS = AUTO\n"));
-		}
-	}
-#endif // CONFIG_STA_SUPPORT //
-	}
-
-	// STBC
-    if (RTMPGetKeyParameter("HT_STBC", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == STBC_USE)
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.STBC = STBC_USE;
-		}
-		else
-		{
-			pAd->CommonCfg.RegTransmitSetting.field.STBC = STBC_NONE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: STBC = %d\n", pAd->CommonCfg.RegTransmitSetting.field.STBC));
-	}
-
-	// 40_Mhz_Intolerant
-	if (RTMPGetKeyParameter("HT_40MHZ_INTOLERANT", pValueStr, 25, pInput))
-	{
-		Value = simple_strtol(pValueStr, 0, 10);
-		if (Value == 0)
-		{
-			pAd->CommonCfg.bForty_Mhz_Intolerant = FALSE;
-		}
-		else
-		{
-			pAd->CommonCfg.bForty_Mhz_Intolerant = TRUE;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: 40MHZ INTOLERANT = %d\n", pAd->CommonCfg.bForty_Mhz_Intolerant));
-	}
-	//HT_TxStream
-	if(RTMPGetKeyParameter("HT_TxStream", pValueStr, 10, pInput))
-	{
-		switch (simple_strtol(pValueStr, 0, 10))
-		{
-			case 1:
-				pAd->CommonCfg.TxStream = 1;
-				break;
-			case 2:
-				pAd->CommonCfg.TxStream = 2;
-				break;
-			case 3: // 3*3
-			default:
-				pAd->CommonCfg.TxStream = 3;
-
-				if (pAd->MACVersion < RALINK_2883_VERSION)
-					pAd->CommonCfg.TxStream = 2; // only 2 tx streams for RT2860 series
-				break;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Tx Stream = %d\n", pAd->CommonCfg.TxStream));
-	}
-	//HT_RxStream
-	if(RTMPGetKeyParameter("HT_RxStream", pValueStr, 10, pInput))
-	{
-		switch (simple_strtol(pValueStr, 0, 10))
-		{
-			case 1:
-				pAd->CommonCfg.RxStream = 1;
-				break;
-			case 2:
-				pAd->CommonCfg.RxStream = 2;
-				break;
-			case 3:
-			default:
-				pAd->CommonCfg.RxStream = 3;
-
-				if (pAd->MACVersion < RALINK_2883_VERSION)
-					pAd->CommonCfg.RxStream = 2; // only 2 rx streams for RT2860 series
-				break;
-		}
-		DBGPRINT(RT_DEBUG_TRACE, ("HT: Rx Stream = %d\n", pAd->CommonCfg.RxStream));
-	}
-
-}
-#endif // DOT11_N_SUPPORT //
-
+#include "../rt2870/rt_profile.c"
diff --git a/drivers/staging/rt3070/rtmp.h b/drivers/staging/rt3070/rtmp.h
index d80d74f..5390ca3 100644
--- a/drivers/staging/rt3070/rtmp.h
+++ b/drivers/staging/rt3070/rtmp.h
@@ -1,7728 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    rtmp.h
-
-    Abstract:
-    Miniport generic portion header file
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Paul Lin    2002-08-01    created
-    James Tan   2002-09-06    modified (Revise NTCRegTable)
-    John Chang  2004-09-06    modified for RT2600
-*/
-#ifndef __RTMP_H__
-#define __RTMP_H__
-
-#include "link_list.h"
-#include "spectrum_def.h"
-
-#ifdef MLME_EX
-#include "mlme_ex_def.h"
-#endif // MLME_EX //
-
-#ifdef CONFIG_STA_SUPPORT
-#include "aironet.h"
-#endif // CONFIG_STA_SUPPORT //
-
-#undef AP_WSC_INCLUDED
-#undef STA_WSC_INCLUDED
-#undef WSC_INCLUDED
-
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-#if defined(AP_WSC_INCLUDED) || defined(STA_WSC_INCLUDED)
-#define WSC_INCLUDED
-#endif
-
-
-
-
-
-//#define DBG		1
-
-//#define DBG_DIAGNOSE		1
-
-#if defined(CONFIG_AP_SUPPORT) && defined(CONFIG_STA_SUPPORT)
-#define IF_DEV_CONFIG_OPMODE_ON_AP(_pAd)	if(_pAd->OpMode == OPMODE_AP)
-#define IF_DEV_CONFIG_OPMODE_ON_STA(_pAd)	if(_pAd->OpMode == OPMODE_STA)
-#else
-#define IF_DEV_CONFIG_OPMODE_ON_AP(_pAd)
-#define IF_DEV_CONFIG_OPMODE_ON_STA(_pAd)
-#endif
-
-#define VIRTUAL_IF_INC(__pAd) ((__pAd)->VirtualIfCnt++)
-#define VIRTUAL_IF_DEC(__pAd) ((__pAd)->VirtualIfCnt--)
-#define VIRTUAL_IF_NUM(__pAd) ((__pAd)->VirtualIfCnt)
-
-#ifdef RT2870
-////////////////////////////////////////////////////////////////////////////
-// The TX_BUFFER structure forms the transmitted USB packet to the device
-////////////////////////////////////////////////////////////////////////////
-typedef struct __TX_BUFFER{
-	union	{
-		UCHAR			WirelessPacket[TX_BUFFER_NORMSIZE];
-		HEADER_802_11	NullFrame;
-		PSPOLL_FRAME	PsPollPacket;
-		RTS_FRAME		RTSFrame;
-	}field;
-	UCHAR			Aggregation[4];  //Buffer for save Aggregation size.
-} TX_BUFFER, *PTX_BUFFER;
-
-typedef struct __HTTX_BUFFER{
-	union	{
-		UCHAR			WirelessPacket[MAX_TXBULK_SIZE];
-		HEADER_802_11	NullFrame;
-		PSPOLL_FRAME	PsPollPacket;
-		RTS_FRAME		RTSFrame;
-	}field;
-	UCHAR			Aggregation[4];  //Buffer for save Aggregation size.
-} HTTX_BUFFER, *PHTTX_BUFFER;
-
-
-// used to track driver-generated write irps
-typedef struct _TX_CONTEXT
-{
-	PVOID			pAd;		//Initialized in MiniportInitialize
-	PURB			pUrb;			//Initialized in MiniportInitialize
-	PIRP			pIrp;			//used to cancel pending bulk out.
-									//Initialized in MiniportInitialize
-	PTX_BUFFER		TransferBuffer;	//Initialized in MiniportInitialize
-	ULONG			BulkOutSize;
-	UCHAR			BulkOutPipeId;
-	UCHAR			SelfIdx;
-	BOOLEAN			InUse;
-	BOOLEAN			bWaitingBulkOut; // at least one packet is in this TxContext, ready for making IRP anytime.
-	BOOLEAN			bFullForBulkOut; // all tx buffer are full , so waiting for tx bulkout.
-	BOOLEAN			IRPPending;
-	BOOLEAN			LastOne;
-	BOOLEAN			bAggregatible;
-	UCHAR			Header_802_3[LENGTH_802_3];
-	UCHAR			Rsv[2];
-	ULONG			DataOffset;
-	UINT			TxRate;
-	dma_addr_t		data_dma;		// urb dma on linux
-
-}	TX_CONTEXT, *PTX_CONTEXT, **PPTX_CONTEXT;
-
-
-// used to track driver-generated write irps
-typedef struct _HT_TX_CONTEXT
-{
-	PVOID			pAd;		//Initialized in MiniportInitialize
-	PURB			pUrb;			//Initialized in MiniportInitialize
-	PIRP			pIrp;			//used to cancel pending bulk out.
-									//Initialized in MiniportInitialize
-	PHTTX_BUFFER	TransferBuffer;	//Initialized in MiniportInitialize
-	ULONG			BulkOutSize;	// Indicate the total bulk-out size in bytes in one bulk-transmission
-	UCHAR			BulkOutPipeId;
-	BOOLEAN			IRPPending;
-	BOOLEAN			LastOne;
-	BOOLEAN			bCurWriting;
-	BOOLEAN			bRingEmpty;
-	BOOLEAN			bCopySavePad;
-	UCHAR			SavedPad[8];
-	UCHAR			Header_802_3[LENGTH_802_3];
-	ULONG			CurWritePosition;		// Indicate the buffer offset which packet will be inserted start from.
-	ULONG			CurWriteRealPos;		// Indicate the buffer offset which packet now are writing to.
-	ULONG			NextBulkOutPosition;	// Indicate the buffer start offset of a bulk-transmission
-	ULONG			ENextBulkOutPosition;	// Indicate the buffer end offset of a bulk-transmission
-	UINT			TxRate;
-	dma_addr_t		data_dma;		// urb dma on linux
-}	HT_TX_CONTEXT, *PHT_TX_CONTEXT, **PPHT_TX_CONTEXT;
-
-
-//
-// Structure to keep track of receive packets and buffers to indicate
-// receive data to the protocol.
-//
-typedef struct _RX_CONTEXT
-{
-	PUCHAR				TransferBuffer;
-	PVOID				pAd;
-	PIRP				pIrp;//used to cancel pending bulk in.
-	PURB				pUrb;
-	//These 2 Boolean shouldn't both be 1 at the same time.
-	ULONG				BulkInOffset;	// number of packets waiting for reordering .
-//	BOOLEAN				ReorderInUse;	// At least one packet in this buffer are in reordering buffer and wait for receive indication
-	BOOLEAN				bRxHandling;	// Notify this packet is being process now.
-	BOOLEAN				InUse;			// USB Hardware Occupied. Wait for USB HW to put packet.
-	BOOLEAN				Readable;		// Receive Complete back. OK for driver to indicate receiving packet.
-	BOOLEAN				IRPPending;		// TODO: To be removed
-	atomic_t			IrpLock;
-	NDIS_SPIN_LOCK		RxContextLock;
-	dma_addr_t			data_dma;		// urb dma on linux
-}	RX_CONTEXT, *PRX_CONTEXT;
-#endif // RT2870 //
-
-
-//
-//  NDIS Version definitions
-//
-#ifdef  NDIS50_MINIPORT
-#define RTMP_NDIS_MAJOR_VERSION     5
-#define RTMP_NDIS_MINOR_VERSION     0
-#endif
-
-#ifdef  NDIS51_MINIPORT
-#define RTMP_NDIS_MAJOR_VERSION     5
-#define RTMP_NDIS_MINOR_VERSION     1
-#endif
-
-extern  char    NIC_VENDOR_DESC[];
-extern  int     NIC_VENDOR_DESC_LEN;
-
-extern  unsigned char   SNAP_AIRONET[];
-extern  unsigned char   CipherSuiteCiscoCCKM[];
-extern  unsigned char   CipherSuiteCiscoCCKMLen;
-extern	unsigned char	CipherSuiteCiscoCCKM24[];
-extern	unsigned char	CipherSuiteCiscoCCKM24Len;
-extern  unsigned char   CipherSuiteCCXTkip[];
-extern  unsigned char   CipherSuiteCCXTkipLen;
-extern  unsigned char   CISCO_OUI[];
-extern  UCHAR	BaSizeArray[4];
-
-extern UCHAR BROADCAST_ADDR[MAC_ADDR_LEN];
-extern UCHAR MULTICAST_ADDR[MAC_ADDR_LEN];
-extern UCHAR ZERO_MAC_ADDR[MAC_ADDR_LEN];
-extern ULONG BIT32[32];
-extern UCHAR BIT8[8];
-extern char* CipherName[];
-extern char* MCSToMbps[];
-extern UCHAR	 RxwiMCSToOfdmRate[12];
-extern UCHAR SNAP_802_1H[6];
-extern UCHAR SNAP_BRIDGE_TUNNEL[6];
-extern UCHAR SNAP_AIRONET[8];
-extern UCHAR CKIP_LLC_SNAP[8];
-extern UCHAR EAPOL_LLC_SNAP[8];
-extern UCHAR EAPOL[2];
-extern UCHAR IPX[2];
-extern UCHAR APPLE_TALK[2];
-extern UCHAR RateIdToPlcpSignal[12]; // see IEEE802.11a-1999 p.14
-extern UCHAR	 OfdmRateToRxwiMCS[];
-extern UCHAR OfdmSignalToRateId[16] ;
-extern UCHAR default_cwmin[4];
-extern UCHAR default_cwmax[4];
-extern UCHAR default_sta_aifsn[4];
-extern UCHAR MapUserPriorityToAccessCategory[8];
-
-extern USHORT RateUpPER[];
-extern USHORT RateDownPER[];
-extern UCHAR  Phy11BNextRateDownward[];
-extern UCHAR  Phy11BNextRateUpward[];
-extern UCHAR  Phy11BGNextRateDownward[];
-extern UCHAR  Phy11BGNextRateUpward[];
-extern UCHAR  Phy11ANextRateDownward[];
-extern UCHAR  Phy11ANextRateUpward[];
-extern CHAR   RssiSafeLevelForTxRate[];
-extern UCHAR  RateIdToMbps[];
-extern USHORT RateIdTo500Kbps[];
-
-extern UCHAR  CipherSuiteWpaNoneTkip[];
-extern UCHAR  CipherSuiteWpaNoneTkipLen;
-
-extern UCHAR  CipherSuiteWpaNoneAes[];
-extern UCHAR  CipherSuiteWpaNoneAesLen;
-
-extern UCHAR  SsidIe;
-extern UCHAR  SupRateIe;
-extern UCHAR  ExtRateIe;
-
-#ifdef DOT11_N_SUPPORT
-extern UCHAR  HtCapIe;
-extern UCHAR  AddHtInfoIe;
-extern UCHAR  NewExtChanIe;
-#ifdef DOT11N_DRAFT3
-extern UCHAR  ExtHtCapIe;
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-extern UCHAR  ErpIe;
-extern UCHAR  DsIe;
-extern UCHAR  TimIe;
-extern UCHAR  WpaIe;
-extern UCHAR  Wpa2Ie;
-extern UCHAR  IbssIe;
-extern UCHAR  Ccx2Ie;
-extern UCHAR  WapiIe;
-
-extern UCHAR  WPA_OUI[];
-extern UCHAR  RSN_OUI[];
-extern UCHAR  WAPI_OUI[];
-extern UCHAR  WME_INFO_ELEM[];
-extern UCHAR  WME_PARM_ELEM[];
-extern UCHAR  Ccx2QosInfo[];
-extern UCHAR  Ccx2IeInfo[];
-extern UCHAR  RALINK_OUI[];
-extern UCHAR  PowerConstraintIE[];
-
-
-extern UCHAR  RateSwitchTable[];
-extern UCHAR  RateSwitchTable11B[];
-extern UCHAR  RateSwitchTable11G[];
-extern UCHAR  RateSwitchTable11BG[];
-
-#ifdef DOT11_N_SUPPORT
-extern UCHAR  RateSwitchTable11BGN1S[];
-extern UCHAR  RateSwitchTable11BGN2S[];
-extern UCHAR  RateSwitchTable11BGN2SForABand[];
-extern UCHAR  RateSwitchTable11N1S[];
-extern UCHAR  RateSwitchTable11N2S[];
-extern UCHAR  RateSwitchTable11N2SForABand[];
-
-#ifdef CONFIG_STA_SUPPORT
-extern UCHAR  PRE_N_HT_OUI[];
-#endif // CONFIG_STA_SUPPORT //
-#endif // DOT11_N_SUPPORT //
-
-#define	MAXSEQ		(0xFFF)
-
-#ifdef RALINK_ATE
-typedef	struct _ATE_INFO {
-	UCHAR	Mode;
-	CHAR	TxPower0;
-	CHAR	TxPower1;
-	CHAR    TxAntennaSel;
-	CHAR    RxAntennaSel;
-	TXWI_STRUC  TxWI; 	  // TXWI
-	USHORT	QID;
-	UCHAR	Addr1[MAC_ADDR_LEN];
-	UCHAR	Addr2[MAC_ADDR_LEN];
-	UCHAR	Addr3[MAC_ADDR_LEN];
-	UCHAR	Channel;
-	UINT32	TxLength;
-	UINT32	TxCount;
-	UINT32	TxDoneCount; // Tx DMA Done
-	UINT32	RFFreqOffset;
-	BOOLEAN	bRxFer;
-	BOOLEAN	bQATxStart; // Have compiled QA in and use it to ATE tx.
-	BOOLEAN	bQARxStart;	// Have compiled QA in and use it to ATE rx.
-	UINT32	RxTotalCnt;
-	UINT32	RxCntPerSec;
-
-	CHAR	LastSNR0;             // last received SNR
-	CHAR    LastSNR1;             // last received SNR for 2nd  antenna
-	CHAR    LastRssi0;            // last received RSSI
-	CHAR    LastRssi1;            // last received RSSI for 2nd  antenna
-	CHAR    LastRssi2;            // last received RSSI for 3rd  antenna
-	CHAR    AvgRssi0;             // last 8 frames' average RSSI
-	CHAR    AvgRssi1;             // last 8 frames' average RSSI
-	CHAR    AvgRssi2;             // last 8 frames' average RSSI
-	SHORT   AvgRssi0X8;           // sum of last 8 frames' RSSI
-	SHORT   AvgRssi1X8;           // sum of last 8 frames' RSSI
-	SHORT   AvgRssi2X8;           // sum of last 8 frames' RSSI
-
-	UINT32	NumOfAvgRssiSample;
-
-#ifdef RALINK_28xx_QA
-	// Tx frame
-#ifdef RT2870
-	/* not used in RT2860 */
-	TXINFO_STRUC		TxInfo; // TxInfo
-#endif // RT2870 //
-	USHORT		HLen; // Header Length
-	USHORT		PLen; // Pattern Length
-	UCHAR 		Header[32]; // Header buffer
-	UCHAR		Pattern[32]; // Pattern buffer
-	USHORT		DLen; // Data Length
-	USHORT		seq;
-	UINT32		CID;
-	pid_t 		AtePid;
-	// counters
-	UINT32		U2M;
-	UINT32		OtherData;
-	UINT32		Beacon;
-	UINT32		OtherCount;
-	UINT32		TxAc0;
-	UINT32		TxAc1;
-	UINT32		TxAc2;
-	UINT32		TxAc3;
-	UINT32		TxHCCA;
-	UINT32		TxMgmt;
-	UINT32		RSSI0;
-	UINT32		RSSI1;
-	UINT32		RSSI2;
-	UINT32		SNR0;
-	UINT32		SNR1;
-	// control
-	//UINT32		Repeat; // Tx Cpu count
-	UCHAR		TxStatus; // task Tx status // 0 --> task is idle, 1 --> task is running
-#endif // RALINK_28xx_QA //
-}	ATE_INFO, *PATE_INFO;
-
-#ifdef RALINK_28xx_QA
-struct ate_racfghdr {
- 	UINT32		magic_no;
-	USHORT		command_type;
-	USHORT		command_id;
-	USHORT		length;
-	USHORT		sequence;
-	USHORT		status;
-	UCHAR		data[2046];
-}  __attribute__((packed));
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-#ifdef DOT11_N_SUPPORT
-struct reordering_mpdu
-{
-	struct reordering_mpdu	*next;
-	PNDIS_PACKET			pPacket;		/* coverted to 802.3 frame */
-	int						Sequence;		/* sequence number of MPDU */
-	BOOLEAN					bAMSDU;
-};
-
-struct reordering_list
-{
-	struct reordering_mpdu *next;
-	int 	qlen;
-};
-
-struct reordering_mpdu_pool
-{
-	PVOID					mem;
-	NDIS_SPIN_LOCK			lock;
-	struct reordering_list 	freelist;
-};
-#endif // DOT11_N_SUPPORT //
-
-typedef struct 	_RSSI_SAMPLE {
-	CHAR			LastRssi0;             // last received RSSI
-	CHAR			LastRssi1;             // last received RSSI
-	CHAR			LastRssi2;             // last received RSSI
-	CHAR			AvgRssi0;
-	CHAR			AvgRssi1;
-	CHAR			AvgRssi2;
-	SHORT			AvgRssi0X8;
-	SHORT			AvgRssi1X8;
-	SHORT			AvgRssi2X8;
-} RSSI_SAMPLE;
-
-//
-//  Queue structure and macros
-//
-typedef struct  _QUEUE_ENTRY    {
-	struct _QUEUE_ENTRY     *Next;
-}   QUEUE_ENTRY, *PQUEUE_ENTRY;
-
-// Queue structure
-typedef struct  _QUEUE_HEADER   {
-	PQUEUE_ENTRY    Head;
-	PQUEUE_ENTRY    Tail;
-	ULONG           Number;
-}   QUEUE_HEADER, *PQUEUE_HEADER;
-
-#define InitializeQueueHeader(QueueHeader)              \
-{                                                       \
-	(QueueHeader)->Head = (QueueHeader)->Tail = NULL;   \
-	(QueueHeader)->Number = 0;                          \
-}
-
-#define RemoveHeadQueue(QueueHeader)                \
-(QueueHeader)->Head;                                \
-{                                                   \
-	PQUEUE_ENTRY pNext;                             \
-	if ((QueueHeader)->Head != NULL)				\
-	{												\
-		pNext = (QueueHeader)->Head->Next;          \
-		(QueueHeader)->Head = pNext;                \
-		if (pNext == NULL)                          \
-			(QueueHeader)->Tail = NULL;             \
-		(QueueHeader)->Number--;                    \
-	}												\
-}
-
-#define InsertHeadQueue(QueueHeader, QueueEntry)            \
-{                                                           \
-		((PQUEUE_ENTRY)QueueEntry)->Next = (QueueHeader)->Head; \
-		(QueueHeader)->Head = (PQUEUE_ENTRY)(QueueEntry);       \
-		if ((QueueHeader)->Tail == NULL)                        \
-			(QueueHeader)->Tail = (PQUEUE_ENTRY)(QueueEntry);   \
-		(QueueHeader)->Number++;                                \
-}
-
-#define InsertTailQueue(QueueHeader, QueueEntry)                \
-{                                                               \
-	((PQUEUE_ENTRY)QueueEntry)->Next = NULL;                    \
-	if ((QueueHeader)->Tail)                                    \
-		(QueueHeader)->Tail->Next = (PQUEUE_ENTRY)(QueueEntry); \
-	else                                                        \
-		(QueueHeader)->Head = (PQUEUE_ENTRY)(QueueEntry);       \
-	(QueueHeader)->Tail = (PQUEUE_ENTRY)(QueueEntry);           \
-	(QueueHeader)->Number++;                                    \
-}
-
-//
-//  Macros for flag and ref count operations
-//
-#define RTMP_SET_FLAG(_M, _F)       ((_M)->Flags |= (_F))
-#define RTMP_CLEAR_FLAG(_M, _F)     ((_M)->Flags &= ~(_F))
-#define RTMP_CLEAR_FLAGS(_M)        ((_M)->Flags = 0)
-#define RTMP_TEST_FLAG(_M, _F)      (((_M)->Flags & (_F)) != 0)
-#define RTMP_TEST_FLAGS(_M, _F)     (((_M)->Flags & (_F)) == (_F))
-
-#define OPSTATUS_SET_FLAG(_pAd, _F)     ((_pAd)->CommonCfg.OpStatusFlags |= (_F))
-#define OPSTATUS_CLEAR_FLAG(_pAd, _F)   ((_pAd)->CommonCfg.OpStatusFlags &= ~(_F))
-#define OPSTATUS_TEST_FLAG(_pAd, _F)    (((_pAd)->CommonCfg.OpStatusFlags & (_F)) != 0)
-
-#define CLIENT_STATUS_SET_FLAG(_pEntry,_F)      ((_pEntry)->ClientStatusFlags |= (_F))
-#define CLIENT_STATUS_CLEAR_FLAG(_pEntry,_F)    ((_pEntry)->ClientStatusFlags &= ~(_F))
-#define CLIENT_STATUS_TEST_FLAG(_pEntry,_F)     (((_pEntry)->ClientStatusFlags & (_F)) != 0)
-
-#define RX_FILTER_SET_FLAG(_pAd, _F)    ((_pAd)->CommonCfg.PacketFilter |= (_F))
-#define RX_FILTER_CLEAR_FLAG(_pAd, _F)  ((_pAd)->CommonCfg.PacketFilter &= ~(_F))
-#define RX_FILTER_TEST_FLAG(_pAd, _F)   (((_pAd)->CommonCfg.PacketFilter & (_F)) != 0)
-
-#ifdef CONFIG_STA_SUPPORT
-#define STA_NO_SECURITY_ON(_p)          (_p->StaCfg.WepStatus == Ndis802_11EncryptionDisabled)
-#define STA_WEP_ON(_p)                  (_p->StaCfg.WepStatus == Ndis802_11Encryption1Enabled)
-#define STA_TKIP_ON(_p)                 (_p->StaCfg.WepStatus == Ndis802_11Encryption2Enabled)
-#define STA_AES_ON(_p)                  (_p->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-
-#define STA_TGN_WIFI_ON(_p)             (_p->StaCfg.bTGnWifiTest == TRUE)
-#endif // CONFIG_STA_SUPPORT //
-
-#define CKIP_KP_ON(_p)				((((_p)->StaCfg.CkipFlag) & 0x10) && ((_p)->StaCfg.bCkipCmicOn == TRUE))
-#define CKIP_CMIC_ON(_p)			((((_p)->StaCfg.CkipFlag) & 0x08) && ((_p)->StaCfg.bCkipCmicOn == TRUE))
-
-
-#define INC_RING_INDEX(_idx, _RingSize)    \
-{                                          \
-    (_idx) = (_idx+1) % (_RingSize);       \
-}
-
-// We will have a cost down version which mac version is 0x3090xxxx
-#define IS_RT3090(_pAd)				((((_pAd)->MACVersion & 0xffff0000) == 0x30710000) || (((_pAd)->MACVersion & 0xffff0000) == 0x30900000))
-
-#define IS_RT3070(_pAd)				(((_pAd)->MACVersion & 0xffff0000) == 0x30700000)
-#define IS_RT3071(_pAd)				(((_pAd)->MACVersion & 0xffff0000) == 0x30710000)
-#define IS_RT2070(_pAd)				(((_pAd)->RfIcType == RFIC_2020) || ((_pAd)->EFuseTag == 0x27))
-
-#define IS_RT30xx(_pAd)				(((_pAd)->MACVersion & 0xfff00000) == 0x30700000)
-
-#define RING_PACKET_INIT(_TxRing, _idx)    \
-{                                          \
-    _TxRing->Cell[_idx].pNdisPacket = NULL;                              \
-    _TxRing->Cell[_idx].pNextNdisPacket = NULL;                              \
-}
-
-#define TXDT_INIT(_TxD)    \
-{                                          \
-	NdisZeroMemory(_TxD, TXD_SIZE);	\
-	_TxD->DMADONE = 1;                              \
-}
-
-//Set last data segment
-#define RING_SET_LASTDS(_TxD, _IsSD0)    \
-{                                          \
-    if (_IsSD0) {_TxD->LastSec0 = 1;}     \
-    else {_TxD->LastSec1 = 1;}     \
-}
-
-// Increase TxTsc value for next transmission
-// TODO:
-// When i==6, means TSC has done one full cycle, do re-keying stuff follow specs
-// Should send a special event microsoft defined to request re-key
-#define INC_TX_TSC(_tsc)                                \
-{                                                       \
-    int i=0;                                            \
-    while (++_tsc[i] == 0x0)                            \
-    {                                                   \
-        i++;                                            \
-        if (i == 6)                                     \
-            break;                                      \
-    }                                                   \
-}
-
-#ifdef DOT11_N_SUPPORT
-// StaActive.SupportedHtPhy.MCSSet is copied from AP beacon.  Don't need to update here.
-#define COPY_HTSETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(_pAd)                                 \
-{                                                                                       \
-	_pAd->StaActive.SupportedHtPhy.ChannelWidth = _pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth;      \
-	_pAd->StaActive.SupportedHtPhy.MimoPs = _pAd->MlmeAux.HtCapability.HtCapInfo.MimoPs;      \
-	_pAd->StaActive.SupportedHtPhy.GF = _pAd->MlmeAux.HtCapability.HtCapInfo.GF;      \
-	_pAd->StaActive.SupportedHtPhy.ShortGIfor20 = _pAd->MlmeAux.HtCapability.HtCapInfo.ShortGIfor20;      \
-	_pAd->StaActive.SupportedHtPhy.ShortGIfor40 = _pAd->MlmeAux.HtCapability.HtCapInfo.ShortGIfor40;      \
-	_pAd->StaActive.SupportedHtPhy.TxSTBC = _pAd->MlmeAux.HtCapability.HtCapInfo.TxSTBC;      \
-	_pAd->StaActive.SupportedHtPhy.RxSTBC = _pAd->MlmeAux.HtCapability.HtCapInfo.RxSTBC;      \
-	_pAd->StaActive.SupportedHtPhy.ExtChanOffset = _pAd->MlmeAux.AddHtInfo.AddHtInfo.ExtChanOffset;      \
-	_pAd->StaActive.SupportedHtPhy.RecomWidth = _pAd->MlmeAux.AddHtInfo.AddHtInfo.RecomWidth;      \
-	_pAd->StaActive.SupportedHtPhy.OperaionMode = _pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode;      \
-	_pAd->StaActive.SupportedHtPhy.NonGfPresent = _pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent;      \
-	NdisMoveMemory((_pAd)->MacTab.Content[BSSID_WCID].HTCapability.MCSSet, (_pAd)->StaActive.SupportedPhyInfo.MCSSet, sizeof(UCHAR) * 16);\
-}
-
-#define COPY_AP_HTSETTINGS_FROM_BEACON(_pAd, _pHtCapability)                                 \
-{                                                                                       \
-	_pAd->MacTab.Content[BSSID_WCID].AMsduSize = (UCHAR)(_pHtCapability->HtCapInfo.AMsduSize);	\
-	_pAd->MacTab.Content[BSSID_WCID].MmpsMode= (UCHAR)(_pHtCapability->HtCapInfo.MimoPs);	\
-	_pAd->MacTab.Content[BSSID_WCID].MaxRAmpduFactor = (UCHAR)(_pHtCapability->HtCapParm.MaxRAmpduFactor);	\
-}
-#endif // DOT11_N_SUPPORT //
-
-//
-// MACRO for 32-bit PCI register read / write
-//
-// Usage : RTMP_IO_READ32(
-//              PRTMP_ADAPTER pAd,
-//              ULONG Register_Offset,
-//              PULONG  pValue)
-//
-//         RTMP_IO_WRITE32(
-//              PRTMP_ADAPTER pAd,
-//              ULONG Register_Offset,
-//              ULONG Value)
-//
-
-//
-// BBP & RF are using indirect access. Before write any value into it.
-// We have to make sure there is no outstanding command pending via checking busy bit.
-//
-#define MAX_BUSY_COUNT  100         // Number of retry before failing access BBP & RF indirect register
-//
-
-#ifdef RT2870
-#define RTMP_RF_IO_WRITE32(_A, _V)                 RTUSBWriteRFRegister(_A, _V)
-#define RTMP_BBP_IO_READ8_BY_REG_ID(_A, _I, _pV)   RTUSBReadBBPRegister(_A, _I, _pV)
-#define RTMP_BBP_IO_WRITE8_BY_REG_ID(_A, _I, _V)   RTUSBWriteBBPRegister(_A, _I, _V)
-
-#define BBP_IO_WRITE8_BY_REG_ID(_A, _I, _V)			RTUSBWriteBBPRegister(_A, _I, _V)
-#define BBP_IO_READ8_BY_REG_ID(_A, _I, _pV)   		RTUSBReadBBPRegister(_A, _I, _pV)
-#endif // RT2870 //
-
-#ifdef RT30xx
-#define RTMP_RF_IO_READ8_BY_REG_ID(_A, _I, _pV)    RT30xxReadRFRegister(_A, _I, _pV)
-#define RTMP_RF_IO_WRITE8_BY_REG_ID(_A, _I, _V)    RT30xxWriteRFRegister(_A, _I, _V)
-#endif // RT30xx //
-
-#define     MAP_CHANNEL_ID_TO_KHZ(ch, khz)  {               \
-                switch (ch)                                 \
-                {                                           \
-                    case 1:     khz = 2412000;   break;     \
-                    case 2:     khz = 2417000;   break;     \
-                    case 3:     khz = 2422000;   break;     \
-                    case 4:     khz = 2427000;   break;     \
-                    case 5:     khz = 2432000;   break;     \
-                    case 6:     khz = 2437000;   break;     \
-                    case 7:     khz = 2442000;   break;     \
-                    case 8:     khz = 2447000;   break;     \
-                    case 9:     khz = 2452000;   break;     \
-                    case 10:    khz = 2457000;   break;     \
-                    case 11:    khz = 2462000;   break;     \
-                    case 12:    khz = 2467000;   break;     \
-                    case 13:    khz = 2472000;   break;     \
-                    case 14:    khz = 2484000;   break;     \
-                    case 36:  /* UNII */  khz = 5180000;   break;     \
-                    case 40:  /* UNII */  khz = 5200000;   break;     \
-                    case 44:  /* UNII */  khz = 5220000;   break;     \
-                    case 48:  /* UNII */  khz = 5240000;   break;     \
-                    case 52:  /* UNII */  khz = 5260000;   break;     \
-                    case 56:  /* UNII */  khz = 5280000;   break;     \
-                    case 60:  /* UNII */  khz = 5300000;   break;     \
-                    case 64:  /* UNII */  khz = 5320000;   break;     \
-                    case 149: /* UNII */  khz = 5745000;   break;     \
-                    case 153: /* UNII */  khz = 5765000;   break;     \
-                    case 157: /* UNII */  khz = 5785000;   break;     \
-                    case 161: /* UNII */  khz = 5805000;   break;     \
-                    case 165: /* UNII */  khz = 5825000;   break;     \
-                    case 100: /* HiperLAN2 */  khz = 5500000;   break;     \
-                    case 104: /* HiperLAN2 */  khz = 5520000;   break;     \
-                    case 108: /* HiperLAN2 */  khz = 5540000;   break;     \
-                    case 112: /* HiperLAN2 */  khz = 5560000;   break;     \
-                    case 116: /* HiperLAN2 */  khz = 5580000;   break;     \
-                    case 120: /* HiperLAN2 */  khz = 5600000;   break;     \
-                    case 124: /* HiperLAN2 */  khz = 5620000;   break;     \
-                    case 128: /* HiperLAN2 */  khz = 5640000;   break;     \
-                    case 132: /* HiperLAN2 */  khz = 5660000;   break;     \
-                    case 136: /* HiperLAN2 */  khz = 5680000;   break;     \
-                    case 140: /* HiperLAN2 */  khz = 5700000;   break;     \
-                    case 34:  /* Japan MMAC */   khz = 5170000;   break;   \
-                    case 38:  /* Japan MMAC */   khz = 5190000;   break;   \
-                    case 42:  /* Japan MMAC */   khz = 5210000;   break;   \
-                    case 46:  /* Japan MMAC */   khz = 5230000;   break;   \
-                    case 184: /* Japan */   khz = 4920000;   break;   \
-                    case 188: /* Japan */   khz = 4940000;   break;   \
-                    case 192: /* Japan */   khz = 4960000;   break;   \
-                    case 196: /* Japan */   khz = 4980000;   break;   \
-                    case 208: /* Japan, means J08 */   khz = 5040000;   break;   \
-                    case 212: /* Japan, means J12 */   khz = 5060000;   break;   \
-                    case 216: /* Japan, means J16 */   khz = 5080000;   break;   \
-                    default:    khz = 2412000;   break;     \
-                }                                           \
-            }
-
-#define     MAP_KHZ_TO_CHANNEL_ID(khz, ch)  {               \
-                switch (khz)                                \
-                {                                           \
-                    case 2412000:    ch = 1;     break;     \
-                    case 2417000:    ch = 2;     break;     \
-                    case 2422000:    ch = 3;     break;     \
-                    case 2427000:    ch = 4;     break;     \
-                    case 2432000:    ch = 5;     break;     \
-                    case 2437000:    ch = 6;     break;     \
-                    case 2442000:    ch = 7;     break;     \
-                    case 2447000:    ch = 8;     break;     \
-                    case 2452000:    ch = 9;     break;     \
-                    case 2457000:    ch = 10;    break;     \
-                    case 2462000:    ch = 11;    break;     \
-                    case 2467000:    ch = 12;    break;     \
-                    case 2472000:    ch = 13;    break;     \
-                    case 2484000:    ch = 14;    break;     \
-                    case 5180000:    ch = 36;  /* UNII */  break;     \
-                    case 5200000:    ch = 40;  /* UNII */  break;     \
-                    case 5220000:    ch = 44;  /* UNII */  break;     \
-                    case 5240000:    ch = 48;  /* UNII */  break;     \
-                    case 5260000:    ch = 52;  /* UNII */  break;     \
-                    case 5280000:    ch = 56;  /* UNII */  break;     \
-                    case 5300000:    ch = 60;  /* UNII */  break;     \
-                    case 5320000:    ch = 64;  /* UNII */  break;     \
-                    case 5745000:    ch = 149; /* UNII */  break;     \
-                    case 5765000:    ch = 153; /* UNII */  break;     \
-                    case 5785000:    ch = 157; /* UNII */  break;     \
-                    case 5805000:    ch = 161; /* UNII */  break;     \
-                    case 5825000:    ch = 165; /* UNII */  break;     \
-                    case 5500000:    ch = 100; /* HiperLAN2 */  break;     \
-                    case 5520000:    ch = 104; /* HiperLAN2 */  break;     \
-                    case 5540000:    ch = 108; /* HiperLAN2 */  break;     \
-                    case 5560000:    ch = 112; /* HiperLAN2 */  break;     \
-                    case 5580000:    ch = 116; /* HiperLAN2 */  break;     \
-                    case 5600000:    ch = 120; /* HiperLAN2 */  break;     \
-                    case 5620000:    ch = 124; /* HiperLAN2 */  break;     \
-                    case 5640000:    ch = 128; /* HiperLAN2 */  break;     \
-                    case 5660000:    ch = 132; /* HiperLAN2 */  break;     \
-                    case 5680000:    ch = 136; /* HiperLAN2 */  break;     \
-                    case 5700000:    ch = 140; /* HiperLAN2 */  break;     \
-                    case 5170000:    ch = 34;  /* Japan MMAC */   break;   \
-                    case 5190000:    ch = 38;  /* Japan MMAC */   break;   \
-                    case 5210000:    ch = 42;  /* Japan MMAC */   break;   \
-                    case 5230000:    ch = 46;  /* Japan MMAC */   break;   \
-                    case 4920000:    ch = 184; /* Japan */  break;   \
-                    case 4940000:    ch = 188; /* Japan */  break;   \
-                    case 4960000:    ch = 192; /* Japan */  break;   \
-                    case 4980000:    ch = 196; /* Japan */  break;   \
-                    case 5040000:    ch = 208; /* Japan, means J08 */  break;   \
-                    case 5060000:    ch = 212; /* Japan, means J12 */  break;   \
-                    case 5080000:    ch = 216; /* Japan, means J16 */  break;   \
-                    default:         ch = 1;     break;     \
-                }                                           \
-            }
-
-//
-// Common fragment list structure -  Identical to the scatter gather frag list structure
-//
-//#define RTMP_SCATTER_GATHER_ELEMENT         SCATTER_GATHER_ELEMENT
-//#define PRTMP_SCATTER_GATHER_ELEMENT        PSCATTER_GATHER_ELEMENT
-#define NIC_MAX_PHYS_BUF_COUNT              8
-
-typedef struct _RTMP_SCATTER_GATHER_ELEMENT {
-    PVOID		Address;
-    ULONG		Length;
-    PULONG		Reserved;
-} RTMP_SCATTER_GATHER_ELEMENT, *PRTMP_SCATTER_GATHER_ELEMENT;
-
-
-typedef struct _RTMP_SCATTER_GATHER_LIST {
-    ULONG  NumberOfElements;
-    PULONG Reserved;
-    RTMP_SCATTER_GATHER_ELEMENT Elements[NIC_MAX_PHYS_BUF_COUNT];
-} RTMP_SCATTER_GATHER_LIST, *PRTMP_SCATTER_GATHER_LIST;
-
-//
-//  Some utility macros
-//
-#ifndef min
-#define min(_a, _b)     (((_a) < (_b)) ? (_a) : (_b))
-#endif
-
-#ifndef max
-#define max(_a, _b)     (((_a) > (_b)) ? (_a) : (_b))
-#endif
-
-#define GET_LNA_GAIN(_pAd)	((_pAd->LatchRfRegs.Channel <= 14) ? (_pAd->BLNAGain) : ((_pAd->LatchRfRegs.Channel <= 64) ? (_pAd->ALNAGain0) : ((_pAd->LatchRfRegs.Channel <= 128) ? (_pAd->ALNAGain1) : (_pAd->ALNAGain2))))
-
-#define INC_COUNTER64(Val)          (Val.QuadPart++)
-
-#define INFRA_ON(_p)                (OPSTATUS_TEST_FLAG(_p, fOP_STATUS_INFRA_ON))
-#define ADHOC_ON(_p)                (OPSTATUS_TEST_FLAG(_p, fOP_STATUS_ADHOC_ON))
-#define MONITOR_ON(_p)              (((_p)->StaCfg.BssType) == BSS_MONITOR)
-#define IDLE_ON(_p)                 (!INFRA_ON(_p) && !ADHOC_ON(_p))
-
-// Check LEAP & CCKM flags
-#define LEAP_ON(_p)                 (((_p)->StaCfg.LeapAuthMode) == CISCO_AuthModeLEAP)
-#define LEAP_CCKM_ON(_p)            ((((_p)->StaCfg.LeapAuthMode) == CISCO_AuthModeLEAP) && ((_p)->StaCfg.LeapAuthInfo.CCKM == TRUE))
-
-// if orginal Ethernet frame contains no LLC/SNAP, then an extra LLC/SNAP encap is required
-#define EXTRA_LLCSNAP_ENCAP_FROM_PKT_START(_pBufVA, _pExtraLlcSnapEncap)		\
-{																\
-	if (((*(_pBufVA + 12) << 8) + *(_pBufVA + 13)) > 1500)		\
-	{															\
-		_pExtraLlcSnapEncap = SNAP_802_1H;						\
-		if (NdisEqualMemory(IPX, _pBufVA + 12, 2) || 			\
-			NdisEqualMemory(APPLE_TALK, _pBufVA + 12, 2))		\
-		{														\
-			_pExtraLlcSnapEncap = SNAP_BRIDGE_TUNNEL;			\
-		}														\
-	}															\
-	else														\
-	{															\
-		_pExtraLlcSnapEncap = NULL;								\
-	}															\
-}
-
-// New Define for new Tx Path.
-#define EXTRA_LLCSNAP_ENCAP_FROM_PKT_OFFSET(_pBufVA, _pExtraLlcSnapEncap)	\
-{																\
-	if (((*(_pBufVA) << 8) + *(_pBufVA + 1)) > 1500)			\
-	{															\
-		_pExtraLlcSnapEncap = SNAP_802_1H;						\
-		if (NdisEqualMemory(IPX, _pBufVA, 2) || 				\
-			NdisEqualMemory(APPLE_TALK, _pBufVA, 2))			\
-		{														\
-			_pExtraLlcSnapEncap = SNAP_BRIDGE_TUNNEL;			\
-		}														\
-	}															\
-	else														\
-	{															\
-		_pExtraLlcSnapEncap = NULL;								\
-	}															\
-}
-
-
-#define MAKE_802_3_HEADER(_p, _pMac1, _pMac2, _pType)                   \
-{                                                                       \
-    NdisMoveMemory(_p, _pMac1, MAC_ADDR_LEN);                           \
-    NdisMoveMemory((_p + MAC_ADDR_LEN), _pMac2, MAC_ADDR_LEN);          \
-    NdisMoveMemory((_p + MAC_ADDR_LEN * 2), _pType, LENGTH_802_3_TYPE); \
-}
-
-// if pData has no LLC/SNAP (neither RFC1042 nor Bridge tunnel), keep it that way.
-// else if the received frame is LLC/SNAP-encaped IPX or APPLETALK, preserve the LLC/SNAP field
-// else remove the LLC/SNAP field from the result Ethernet frame
-// Patch for WHQL only, which did not turn on Netbios but use IPX within its payload
-// Note:
-//     _pData & _DataSize may be altered (remove 8-byte LLC/SNAP) by this MACRO
-//     _pRemovedLLCSNAP: pointer to removed LLC/SNAP; NULL is not removed
-#define CONVERT_TO_802_3(_p8023hdr, _pDA, _pSA, _pData, _DataSize, _pRemovedLLCSNAP)      \
-{                                                                       \
-    char LLC_Len[2];                                                    \
-                                                                        \
-    _pRemovedLLCSNAP = NULL;                                            \
-    if (NdisEqualMemory(SNAP_802_1H, _pData, 6)  ||                     \
-        NdisEqualMemory(SNAP_BRIDGE_TUNNEL, _pData, 6))                 \
-    {                                                                   \
-        PUCHAR pProto = _pData + 6;                                     \
-                                                                        \
-        if ((NdisEqualMemory(IPX, pProto, 2) || NdisEqualMemory(APPLE_TALK, pProto, 2)) &&  \
-            NdisEqualMemory(SNAP_802_1H, _pData, 6))                    \
-        {                                                               \
-            LLC_Len[0] = (UCHAR)(_DataSize / 256);                      \
-            LLC_Len[1] = (UCHAR)(_DataSize % 256);                      \
-            MAKE_802_3_HEADER(_p8023hdr, _pDA, _pSA, LLC_Len);          \
-        }                                                               \
-        else                                                            \
-        {                                                               \
-            MAKE_802_3_HEADER(_p8023hdr, _pDA, _pSA, pProto);           \
-            _pRemovedLLCSNAP = _pData;                                  \
-            _DataSize -= LENGTH_802_1_H;                                \
-            _pData += LENGTH_802_1_H;                                   \
-        }                                                               \
-    }                                                                   \
-    else                                                                \
-    {                                                                   \
-        LLC_Len[0] = (UCHAR)(_DataSize / 256);                          \
-        LLC_Len[1] = (UCHAR)(_DataSize % 256);                          \
-        MAKE_802_3_HEADER(_p8023hdr, _pDA, _pSA, LLC_Len);              \
-    }                                                                   \
-}
-
-#define SWITCH_AB( _pAA, _pBB)    \
-{                                                                           \
-    PVOID pCC;                                                          \
-    pCC = _pBB;                                                 \
-    _pBB = _pAA;                                                 \
-    _pAA = pCC;                                                 \
-}
-
-// Enqueue this frame to MLME engine
-// We need to enqueue the whole frame because MLME need to pass data type
-// information from 802.11 header
-#ifdef RT2870
-#define REPORT_MGMT_FRAME_TO_MLME(_pAd, Wcid, _pFrame, _FrameSize, _Rssi0, _Rssi1, _Rssi2, _PlcpSignal)        \
-{                                                                                       \
-    UINT32 High32TSF=0, Low32TSF=0;                                                          \
-    MlmeEnqueueForRecv(_pAd, Wcid, High32TSF, Low32TSF, (UCHAR)_Rssi0, (UCHAR)_Rssi1,(UCHAR)_Rssi2,_FrameSize, _pFrame, (UCHAR)_PlcpSignal);   \
-}
-#endif // RT2870 //
-
-#ifdef RT30xx
-//Need to collect each ant's rssi concurrently
-//rssi1 is report to pair2 Ant and rss2 is reprot to pair1 Ant when 4 Ant
-#define COLLECT_RX_ANTENNA_AVERAGE_RSSI(_pAd, _rssi1, _rssi2)					\
-{																				\
-	SHORT	AvgRssi;															\
-	UCHAR	UsedAnt;															\
-	if (_pAd->RxAnt.EvaluatePeriod == 0)									\
-	{																		\
-		UsedAnt = _pAd->RxAnt.Pair1PrimaryRxAnt;							\
-		AvgRssi = _pAd->RxAnt.Pair1AvgRssi[UsedAnt];						\
-		if (AvgRssi < 0)													\
-			AvgRssi = AvgRssi - (AvgRssi >> 3) + _rssi1;					\
-		else																\
-			AvgRssi = _rssi1 << 3;											\
-		_pAd->RxAnt.Pair1AvgRssi[UsedAnt] = AvgRssi;						\
-	}																		\
-	else																	\
-	{																		\
-		UsedAnt = _pAd->RxAnt.Pair1SecondaryRxAnt;							\
-		AvgRssi = _pAd->RxAnt.Pair1AvgRssi[UsedAnt];						\
-		if ((AvgRssi < 0) && (_pAd->RxAnt.FirstPktArrivedWhenEvaluate))		\
-			AvgRssi = AvgRssi - (AvgRssi >> 3) + _rssi1;					\
-		else																\
-		{																	\
-			_pAd->RxAnt.FirstPktArrivedWhenEvaluate = TRUE;					\
-			AvgRssi = _rssi1 << 3;											\
-		}																	\
-		_pAd->RxAnt.Pair1AvgRssi[UsedAnt] = AvgRssi;						\
-		_pAd->RxAnt.RcvPktNumWhenEvaluate++;								\
-	}																		\
-}
-#endif // RT30xx //
-
-
-#define NDIS_QUERY_BUFFER(_NdisBuf, _ppVA, _pBufLen)                    \
-    NdisQueryBuffer(_NdisBuf, _ppVA, _pBufLen)
-
-#define MAC_ADDR_EQUAL(pAddr1,pAddr2)           RTMPEqualMemory((PVOID)(pAddr1), (PVOID)(pAddr2), MAC_ADDR_LEN)
-#define SSID_EQUAL(ssid1, len1, ssid2, len2)    ((len1==len2) && (RTMPEqualMemory(ssid1, ssid2, len1)))
-
-//
-// Check if it is Japan W53(ch52,56,60,64) channel.
-//
-#define JapanChannelCheck(channel)  ((channel == 52) || (channel == 56) || (channel == 60) || (channel == 64))
-
-#ifdef CONFIG_STA_SUPPORT
-#define STA_PORT_SECURED(_pAd) \
-{ \
-	_pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED; \
-	NdisAcquireSpinLock(&_pAd->MacTabLock); \
-	_pAd->MacTab.Content[BSSID_WCID].PortSecured = _pAd->StaCfg.PortSecured; \
-	NdisReleaseSpinLock(&_pAd->MacTabLock); \
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-//
-// Register set pair for initialzation register set definition
-//
-typedef struct  _RTMP_REG_PAIR
-{
-	ULONG   Register;
-	ULONG   Value;
-} RTMP_REG_PAIR, *PRTMP_REG_PAIR;
-
-typedef struct  _REG_PAIR
-{
-	UCHAR   Register;
-	UCHAR   Value;
-} REG_PAIR, *PREG_PAIR;
-
-//
-// Register set pair for initialzation register set definition
-//
-typedef struct  _RTMP_RF_REGS
-{
-	UCHAR   Channel;
-	ULONG   R1;
-	ULONG   R2;
-	ULONG   R3;
-	ULONG   R4;
-} RTMP_RF_REGS, *PRTMP_RF_REGS;
-
-typedef struct _FREQUENCY_ITEM {
-	UCHAR	Channel;
-	UCHAR	N;
-	UCHAR	R;
-	UCHAR	K;
-} FREQUENCY_ITEM, *PFREQUENCY_ITEM;
-
-//
-//  Data buffer for DMA operation, the buffer must be contiguous physical memory
-//  Both DMA to / from CPU use the same structure.
-//
-typedef struct  _RTMP_DMABUF
-{
-	ULONG                   AllocSize;
-	PVOID                   AllocVa;            // TxBuf virtual address
-	NDIS_PHYSICAL_ADDRESS   AllocPa;            // TxBuf physical address
-} RTMP_DMABUF, *PRTMP_DMABUF;
-
-
-typedef	union	_HEADER_802_11_SEQ{
-#ifdef RT_BIG_ENDIAN
-    struct {
-   	USHORT			Sequence:12;
-	USHORT			Frag:4;
-    }   field;
-#else
-    struct {
-	USHORT			Frag:4;
-	USHORT			Sequence:12;
-    }   field;
-#endif
-    USHORT           value;
-}	HEADER_802_11_SEQ, *PHEADER_802_11_SEQ;
-
-//
-//  Data buffer for DMA operation, the buffer must be contiguous physical memory
-//  Both DMA to / from CPU use the same structure.
-//
-typedef struct  _RTMP_REORDERBUF
-{
-	BOOLEAN			IsFull;
-	PVOID                   AllocVa;            // TxBuf virtual address
-	UCHAR			Header802_3[14];
-	HEADER_802_11_SEQ			Sequence;	//support compressed bitmap BA, so no consider fragment in BA
-	UCHAR 		DataOffset;
-	USHORT 		Datasize;
-	ULONG                   AllocSize;
-#ifdef RT2870
-	PUCHAR					AllocPa;
-#endif // RT2870 //
-}   RTMP_REORDERBUF, *PRTMP_REORDERBUF;
-
-//
-// Control block (Descriptor) for all ring descriptor DMA operation, buffer must be
-// contiguous physical memory. NDIS_PACKET stored the binding Rx packet descriptor
-// which won't be released, driver has to wait until upper layer return the packet
-// before giveing up this rx ring descriptor to ASIC. NDIS_BUFFER is assocaited pair
-// to describe the packet buffer. For Tx, NDIS_PACKET stored the tx packet descriptor
-// which driver should ACK upper layer when the tx is physically done or failed.
-//
-typedef struct _RTMP_DMACB
-{
-	ULONG                   AllocSize;          // Control block size
-	PVOID                   AllocVa;            // Control block virtual address
-	NDIS_PHYSICAL_ADDRESS   AllocPa;            // Control block physical address
-	PNDIS_PACKET pNdisPacket;
-	PNDIS_PACKET pNextNdisPacket;
-
-	RTMP_DMABUF             DmaBuf;             // Associated DMA buffer structure
-} RTMP_DMACB, *PRTMP_DMACB;
-
-typedef struct _RTMP_TX_BUF
-{
-	PQUEUE_ENTRY    Next;
-	UCHAR           Index;
-	ULONG                   AllocSize;          // Control block size
-	PVOID                   AllocVa;            // Control block virtual address
-	NDIS_PHYSICAL_ADDRESS   AllocPa;            // Control block physical address
-} RTMP_TXBUF, *PRTMP_TXBUF;
-
-typedef struct _RTMP_RX_BUF
-{
-	BOOLEAN           InUse;
-	ULONG           	ByBaRecIndex;
-	RTMP_REORDERBUF	MAP_RXBuf[MAX_RX_REORDERBUF];
-} RTMP_RXBUF, *PRTMP_RXBUF;
-typedef struct _RTMP_TX_RING
-{
-	RTMP_DMACB  Cell[TX_RING_SIZE];
-	UINT32		TxCpuIdx;
-	UINT32		TxDmaIdx;
-	UINT32		TxSwFreeIdx; 	// software next free tx index
-} RTMP_TX_RING, *PRTMP_TX_RING;
-
-typedef struct _RTMP_RX_RING
-{
-	RTMP_DMACB  Cell[RX_RING_SIZE];
-	UINT32		RxCpuIdx;
-	UINT32		RxDmaIdx;
-	INT32		RxSwReadIdx; 	// software next read index
-} RTMP_RX_RING, *PRTMP_RX_RING;
-
-typedef struct _RTMP_MGMT_RING
-{
-	RTMP_DMACB  Cell[MGMT_RING_SIZE];
-	UINT32		TxCpuIdx;
-	UINT32		TxDmaIdx;
-	UINT32		TxSwFreeIdx; // software next free tx index
-} RTMP_MGMT_RING, *PRTMP_MGMT_RING;
-
-//
-//  Statistic counter structure
-//
-typedef struct _COUNTER_802_3
-{
-	// General Stats
-	ULONG       GoodTransmits;
-	ULONG       GoodReceives;
-	ULONG       TxErrors;
-	ULONG       RxErrors;
-	ULONG       RxNoBuffer;
-
-	// Ethernet Stats
-	ULONG       RcvAlignmentErrors;
-	ULONG       OneCollision;
-	ULONG       MoreCollisions;
-
-} COUNTER_802_3, *PCOUNTER_802_3;
-
-typedef struct _COUNTER_802_11 {
-	ULONG           Length;
-	LARGE_INTEGER   LastTransmittedFragmentCount;
-	LARGE_INTEGER   TransmittedFragmentCount;
-	LARGE_INTEGER   MulticastTransmittedFrameCount;
-	LARGE_INTEGER   FailedCount;
-	LARGE_INTEGER   RetryCount;
-	LARGE_INTEGER   MultipleRetryCount;
-	LARGE_INTEGER   RTSSuccessCount;
-	LARGE_INTEGER   RTSFailureCount;
-	LARGE_INTEGER   ACKFailureCount;
-	LARGE_INTEGER   FrameDuplicateCount;
-	LARGE_INTEGER   ReceivedFragmentCount;
-	LARGE_INTEGER   MulticastReceivedFrameCount;
-	LARGE_INTEGER   FCSErrorCount;
-} COUNTER_802_11, *PCOUNTER_802_11;
-
-typedef struct _COUNTER_RALINK {
-	ULONG           TransmittedByteCount;   // both successful and failure, used to calculate TX throughput
-	ULONG           ReceivedByteCount;      // both CRC okay and CRC error, used to calculate RX throughput
-	ULONG           BeenDisassociatedCount;
-	ULONG           BadCQIAutoRecoveryCount;
-	ULONG           PoorCQIRoamingCount;
-	ULONG           MgmtRingFullCount;
-	ULONG           RxCountSinceLastNULL;
-	ULONG           RxCount;
-	ULONG           RxRingErrCount;
-	ULONG           KickTxCount;
-	ULONG           TxRingErrCount;
-	LARGE_INTEGER   RealFcsErrCount;
-	ULONG           PendingNdisPacketCount;
-
-	ULONG           OneSecOsTxCount[NUM_OF_TX_RING];
-	ULONG           OneSecDmaDoneCount[NUM_OF_TX_RING];
-	UINT32          OneSecTxDoneCount;
-	ULONG           OneSecRxCount;
-	UINT32          OneSecTxAggregationCount;
-	UINT32          OneSecRxAggregationCount;
-
-	UINT32   		OneSecFrameDuplicateCount;
-
-#ifdef RT2870
-	ULONG           OneSecTransmittedByteCount;   // both successful and failure, used to calculate TX throughput
-#endif // RT2870 //
-
-	UINT32          OneSecTxNoRetryOkCount;
-	UINT32          OneSecTxRetryOkCount;
-	UINT32          OneSecTxFailCount;
-	UINT32          OneSecFalseCCACnt;      // CCA error count, for debug purpose, might move to global counter
-	UINT32          OneSecRxOkCnt;          // RX without error
-	UINT32          OneSecRxOkDataCnt;      // unicast-to-me DATA frame count
-	UINT32          OneSecRxFcsErrCnt;      // CRC error
-	UINT32          OneSecBeaconSentCnt;
-	UINT32          LastOneSecTotalTxCount; // OneSecTxNoRetryOkCount + OneSecTxRetryOkCount + OneSecTxFailCount
-	UINT32          LastOneSecRxOkDataCnt;  // OneSecRxOkDataCnt
-	ULONG		DuplicateRcv;
-	ULONG		TxAggCount;
-	ULONG		TxNonAggCount;
-	ULONG		TxAgg1MPDUCount;
-	ULONG		TxAgg2MPDUCount;
-	ULONG		TxAgg3MPDUCount;
-	ULONG		TxAgg4MPDUCount;
-	ULONG		TxAgg5MPDUCount;
-	ULONG		TxAgg6MPDUCount;
-	ULONG		TxAgg7MPDUCount;
-	ULONG		TxAgg8MPDUCount;
-	ULONG		TxAgg9MPDUCount;
-	ULONG		TxAgg10MPDUCount;
-	ULONG		TxAgg11MPDUCount;
-	ULONG		TxAgg12MPDUCount;
-	ULONG		TxAgg13MPDUCount;
-	ULONG		TxAgg14MPDUCount;
-	ULONG		TxAgg15MPDUCount;
-	ULONG		TxAgg16MPDUCount;
-
-	LARGE_INTEGER       TransmittedOctetsInAMSDU;
-	LARGE_INTEGER       TransmittedAMSDUCount;
-	LARGE_INTEGER       ReceivedOctesInAMSDUCount;
-	LARGE_INTEGER       ReceivedAMSDUCount;
-	LARGE_INTEGER       TransmittedAMPDUCount;
-	LARGE_INTEGER       TransmittedMPDUsInAMPDUCount;
-	LARGE_INTEGER       TransmittedOctetsInAMPDUCount;
-	LARGE_INTEGER       MPDUInReceivedAMPDUCount;
-} COUNTER_RALINK, *PCOUNTER_RALINK;
-
-typedef struct _PID_COUNTER {
-	ULONG           TxAckRequiredCount;      // CRC error
-	ULONG           TxAggreCount;
-	ULONG           TxSuccessCount; // OneSecTxNoRetryOkCount + OneSecTxRetryOkCount + OneSecTxFailCount
-	ULONG		LastSuccessRate;
-} PID_COUNTER, *PPID_COUNTER;
-
-typedef struct _COUNTER_DRS {
-	// to record the each TX rate's quality. 0 is best, the bigger the worse.
-	USHORT          TxQuality[MAX_STEP_OF_TX_RATE_SWITCH];
-	UCHAR           PER[MAX_STEP_OF_TX_RATE_SWITCH];
-	UCHAR           TxRateUpPenalty;      // extra # of second penalty due to last unstable condition
-	ULONG           CurrTxRateStableTime; // # of second in current TX rate
-	BOOLEAN         fNoisyEnvironment;
-	BOOLEAN         fLastSecAccordingRSSI;
-	UCHAR           LastSecTxRateChangeAction; // 0: no change, 1:rate UP, 2:rate down
-	UCHAR			LastTimeTxRateChangeAction; //Keep last time value of LastSecTxRateChangeAction
-	ULONG			LastTxOkCount;
-} COUNTER_DRS, *PCOUNTER_DRS;
-
-//
-//  Arcfour Structure Added by PaulWu
-//
-typedef struct  _ARCFOUR
-{
-	UINT            X;
-	UINT            Y;
-	UCHAR           STATE[256];
-} ARCFOURCONTEXT, *PARCFOURCONTEXT;
-
-// MIMO Tx parameter, ShortGI, MCS, STBC, etc.  these are fields in TXWI too. just copy to TXWI.
-typedef struct  _RECEIVE_SETTING {
-#ifdef RT_BIG_ENDIAN
-	USHORT		MIMO:1;
-	USHORT		OFDM:1;
-	USHORT		rsv:3;
-	USHORT		STBC:2;	//SPACE
-	USHORT		ShortGI:1;
-	USHORT		Mode:2;	//channel bandwidth 20MHz or 40 MHz
-	USHORT   	NumOfRX:2;                 // MIMO. WE HAVE 3R
-#else
-	USHORT   	NumOfRX:2;                 // MIMO. WE HAVE 3R
-	USHORT		Mode:2;	//channel bandwidth 20MHz or 40 MHz
-	USHORT		ShortGI:1;
-	USHORT		STBC:2;	//SPACE
-	USHORT		rsv:3;
-	USHORT		OFDM:1;
-	USHORT		MIMO:1;
-#endif
- } RECEIVE_SETTING, *PRECEIVE_SETTING;
-
-// Shared key data structure
-typedef struct  _WEP_KEY {
-	UCHAR   KeyLen;                     // Key length for each key, 0: entry is invalid
-	UCHAR   Key[MAX_LEN_OF_KEY];        // right now we implement 4 keys, 128 bits max
-} WEP_KEY, *PWEP_KEY;
-
-typedef struct _CIPHER_KEY {
-	UCHAR   Key[16];            // right now we implement 4 keys, 128 bits max
-	UCHAR   RxMic[8];			// make alignment
-	UCHAR   TxMic[8];
-	UCHAR   TxTsc[6];           // 48bit TSC value
-	UCHAR   RxTsc[6];           // 48bit TSC value
-	UCHAR   CipherAlg;          // 0-none, 1:WEP64, 2:WEP128, 3:TKIP, 4:AES, 5:CKIP64, 6:CKIP128
-	UCHAR   KeyLen;
-#ifdef CONFIG_STA_SUPPORT
-	UCHAR   BssId[6];
-#endif // CONFIG_STA_SUPPORT //
-            // Key length for each key, 0: entry is invalid
-	UCHAR   Type;               // Indicate Pairwise/Group when reporting MIC error
-} CIPHER_KEY, *PCIPHER_KEY;
-
-typedef struct _BBP_TUNING_STRUCT {
-	BOOLEAN     Enable;
-	UCHAR       FalseCcaCountUpperBound;  // 100 per sec
-	UCHAR       FalseCcaCountLowerBound;  // 10 per sec
-	UCHAR       R17LowerBound;            // specified in E2PROM
-	UCHAR       R17UpperBound;            // 0x68 according to David Tung
-	UCHAR       CurrentR17Value;
-} BBP_TUNING, *PBBP_TUNING;
-
-typedef struct _SOFT_RX_ANT_DIVERSITY_STRUCT {
-	UCHAR     EvaluatePeriod;		 // 0:not evalute status, 1: evaluate status, 2: switching status
-	UCHAR     EvaluateStableCnt;
-	UCHAR     Pair1PrimaryRxAnt;     // 0:Ant-E1, 1:Ant-E2
-	UCHAR     Pair1SecondaryRxAnt;   // 0:Ant-E1, 1:Ant-E2
-	UCHAR     Pair2PrimaryRxAnt;     // 0:Ant-E3, 1:Ant-E4
-	UCHAR     Pair2SecondaryRxAnt;   // 0:Ant-E3, 1:Ant-E4
-	SHORT     Pair1AvgRssi[2];       // AvgRssi[0]:E1, AvgRssi[1]:E2
-	SHORT     Pair2AvgRssi[2];       // AvgRssi[0]:E3, AvgRssi[1]:E4
-	SHORT     Pair1LastAvgRssi;      //
-	SHORT     Pair2LastAvgRssi;      //
-	ULONG     RcvPktNumWhenEvaluate;
-	BOOLEAN   FirstPktArrivedWhenEvaluate;
-	RALINK_TIMER_STRUCT    RxAntDiversityTimer;
-} SOFT_RX_ANT_DIVERSITY, *PSOFT_RX_ANT_DIVERSITY;
-
-typedef struct _LEAP_AUTH_INFO {
-	BOOLEAN         Enabled;        //Ture: Enable LEAP Authentication
-	BOOLEAN         CCKM;           //Ture: Use Fast Reauthentication with CCKM
-	UCHAR           Reserve[2];
-	UCHAR           UserName[256];  //LEAP, User name
-	ULONG           UserNameLen;
-	UCHAR           Password[256];  //LEAP, User Password
-	ULONG           PasswordLen;
-} LEAP_AUTH_INFO, *PLEAP_AUTH_INFO;
-
-typedef struct {
-	UCHAR        Addr[MAC_ADDR_LEN];
-	UCHAR        ErrorCode[2];  //00 01-Invalid authentication type
-								//00 02-Authentication timeout
-								//00 03-Challenge from AP failed
-								//00 04-Challenge to AP failed
-	BOOLEAN      Reported;
-} ROGUEAP_ENTRY, *PROGUEAP_ENTRY;
-
-typedef struct {
-	UCHAR               RogueApNr;
-	ROGUEAP_ENTRY       RogueApEntry[MAX_LEN_OF_BSS_TABLE];
-} ROGUEAP_TABLE, *PROGUEAP_TABLE;
-
-typedef struct {
-	BOOLEAN     Enable;
-	UCHAR       Delta;
-	BOOLEAN     PlusSign;
-} CCK_TX_POWER_CALIBRATE, *PCCK_TX_POWER_CALIBRATE;
-
-//
-// Receive Tuple Cache Format
-//
-typedef struct  _TUPLE_CACHE    {
-	BOOLEAN         Valid;
-	UCHAR           MacAddress[MAC_ADDR_LEN];
-	USHORT          Sequence;
-	USHORT          Frag;
-} TUPLE_CACHE, *PTUPLE_CACHE;
-
-//
-// Fragment Frame structure
-//
-typedef struct  _FRAGMENT_FRAME {
-	PNDIS_PACKET    pFragPacket;
-	ULONG       RxSize;
-	USHORT      Sequence;
-	USHORT      LastFrag;
-	ULONG       Flags;          // Some extra frame information. bit 0: LLC presented
-} FRAGMENT_FRAME, *PFRAGMENT_FRAME;
-
-
-//
-// Packet information for NdisQueryPacket
-//
-typedef struct  _PACKET_INFO    {
-	UINT            PhysicalBufferCount;    // Physical breaks of buffer descripor chained
-	UINT            BufferCount ;           // Number of Buffer descriptor chained
-	UINT            TotalPacketLength ;     // Self explained
-	PNDIS_BUFFER    pFirstBuffer;           // Pointer to first buffer descriptor
-} PACKET_INFO, *PPACKET_INFO;
-
-//
-// Tkip Key structure which RC4 key & MIC calculation
-//
-typedef struct  _TKIP_KEY_INFO  {
-	UINT        nBytesInM;  // # bytes in M for MICKEY
-	ULONG       IV16;
-	ULONG       IV32;
-	ULONG       K0;         // for MICKEY Low
-	ULONG       K1;         // for MICKEY Hig
-	ULONG       L;          // Current state for MICKEY
-	ULONG       R;          // Current state for MICKEY
-	ULONG       M;          // Message accumulator for MICKEY
-	UCHAR       RC4KEY[16];
-	UCHAR       MIC[8];
-} TKIP_KEY_INFO, *PTKIP_KEY_INFO;
-
-//
-// Private / Misc data, counters for driver internal use
-//
-typedef struct  __PRIVATE_STRUC {
-	UINT       SystemResetCnt;         // System reset counter
-	UINT       TxRingFullCnt;          // Tx ring full occurrance number
-	UINT       PhyRxErrCnt;            // PHY Rx error count, for debug purpose, might move to global counter
-	// Variables for WEP encryption / decryption in rtmp_wep.c
-	UINT       FCSCRC32;
-	ARCFOURCONTEXT  WEPCONTEXT;
-	// Tkip stuff
-	TKIP_KEY_INFO   Tx;
-	TKIP_KEY_INFO   Rx;
-} PRIVATE_STRUC, *PPRIVATE_STRUC;
-
-// structure to tune BBP R66 (BBP TUNING)
-typedef struct _BBP_R66_TUNING {
-	BOOLEAN     bEnable;
-	USHORT      FalseCcaLowerThreshold;  // default 100
-	USHORT      FalseCcaUpperThreshold;  // default 512
-	UCHAR       R66Delta;
-	UCHAR       R66CurrentValue;
-	BOOLEAN		R66LowerUpperSelect; //Before LinkUp, Used LowerBound or UpperBound as R66 value.
-} BBP_R66_TUNING, *PBBP_R66_TUNING;
-
-// structure to store channel TX power
-typedef struct _CHANNEL_TX_POWER {
-	USHORT     RemainingTimeForUse;		//unit: sec
-	UCHAR      Channel;
-#ifdef DOT11N_DRAFT3
-	BOOLEAN       bEffectedChannel;	// For BW 40 operating in 2.4GHz , the "effected channel" is the channel that is covered in 40Mhz.
-#endif // DOT11N_DRAFT3 //
-	CHAR       Power;
-	CHAR       Power2;
-	UCHAR      MaxTxPwr;
-	UCHAR      DfsReq;
-} CHANNEL_TX_POWER, *PCHANNEL_TX_POWER;
-
-// structure to store 802.11j channel TX power
-typedef struct _CHANNEL_11J_TX_POWER {
-	UCHAR      Channel;
-	UCHAR      BW;	// BW_10 or BW_20
-	CHAR       Power;
-	CHAR       Power2;
-	USHORT     RemainingTimeForUse;		//unit: sec
-} CHANNEL_11J_TX_POWER, *PCHANNEL_11J_TX_POWER;
-
-typedef enum _ABGBAND_STATE_ {
-	UNKNOWN_BAND,
-	BG_BAND,
-	A_BAND,
-} ABGBAND_STATE;
-
-typedef struct _MLME_STRUCT {
-#ifdef CONFIG_STA_SUPPORT
-	// STA state machines
-	STATE_MACHINE           CntlMachine;
-	STATE_MACHINE           AssocMachine;
-	STATE_MACHINE           AuthMachine;
-	STATE_MACHINE           AuthRspMachine;
-	STATE_MACHINE           SyncMachine;
-	STATE_MACHINE           WpaPskMachine;
-	STATE_MACHINE           LeapMachine;
-	STATE_MACHINE           AironetMachine;
-	STATE_MACHINE_FUNC      AssocFunc[ASSOC_FUNC_SIZE];
-	STATE_MACHINE_FUNC      AuthFunc[AUTH_FUNC_SIZE];
-	STATE_MACHINE_FUNC      AuthRspFunc[AUTH_RSP_FUNC_SIZE];
-	STATE_MACHINE_FUNC      SyncFunc[SYNC_FUNC_SIZE];
-	STATE_MACHINE_FUNC      WpaPskFunc[WPA_PSK_FUNC_SIZE];
-	STATE_MACHINE_FUNC      AironetFunc[AIRONET_FUNC_SIZE];
-#endif // CONFIG_STA_SUPPORT //
-	STATE_MACHINE_FUNC      ActFunc[ACT_FUNC_SIZE];
-	// Action
-	STATE_MACHINE           ActMachine;
-
-
-#ifdef QOS_DLS_SUPPORT
-	STATE_MACHINE			DlsMachine;
-	STATE_MACHINE_FUNC      DlsFunc[DLS_FUNC_SIZE];
-#endif // QOS_DLS_SUPPORT //
-
-
-
-
-	ULONG                   ChannelQuality;  // 0..100, Channel Quality Indication for Roaming
-	ULONG                   Now32;           // latch the value of NdisGetSystemUpTime()
-	ULONG                   LastSendNULLpsmTime;
-
-	BOOLEAN                 bRunning;
-	NDIS_SPIN_LOCK          TaskLock;
-	MLME_QUEUE              Queue;
-
-	UINT                    ShiftReg;
-
-	RALINK_TIMER_STRUCT     PeriodicTimer;
-	RALINK_TIMER_STRUCT     APSDPeriodicTimer;
-	RALINK_TIMER_STRUCT     LinkDownTimer;
-	RALINK_TIMER_STRUCT     LinkUpTimer;
-	ULONG                   PeriodicRound;
-	ULONG                   OneSecPeriodicRound;
-
-	UCHAR					RealRxPath;
-	BOOLEAN					bLowThroughput;
-	BOOLEAN					bEnableAutoAntennaCheck;
-	RALINK_TIMER_STRUCT		RxAntEvalTimer;
-
-#ifdef RT30xx
-	UCHAR CaliBW40RfR24;
-	UCHAR CaliBW20RfR24;
-#endif // RT30xx //
-
-} MLME_STRUCT, *PMLME_STRUCT;
-
-// structure for radar detection and channel switch
-typedef struct _RADAR_DETECT_STRUCT {
-    //BOOLEAN		IEEE80211H;			// 0: disable, 1: enable IEEE802.11h
-	UCHAR		CSCount;			//Channel switch counter
-	UCHAR		CSPeriod;			//Channel switch period (beacon count)
-	UCHAR		RDCount;			//Radar detection counter
-	UCHAR		RDMode;				//Radar Detection mode
-	UCHAR		RDDurRegion;		//Radar detection duration region
-	UCHAR		BBPR16;
-	UCHAR		BBPR17;
-	UCHAR		BBPR18;
-	UCHAR		BBPR21;
-	UCHAR		BBPR22;
-	UCHAR		BBPR64;
-	ULONG		InServiceMonitorCount; // unit: sec
-	UINT8		DfsSessionTime;
-	BOOLEAN		bFastDfs;
-	UINT8		ChMovingTime;
-	UINT8		LongPulseRadarTh;
-} RADAR_DETECT_STRUCT, *PRADAR_DETECT_STRUCT;
-
-#ifdef CARRIER_DETECTION_SUPPORT
-typedef enum CD_STATE_n
-{
-	CD_NORMAL,
-	CD_SILENCE,
-	CD_MAX_STATE
-} CD_STATE;
-
-typedef struct CARRIER_DETECTION_s
-{
-	BOOLEAN					Enable;
-	UINT8					CDSessionTime;
-	UINT8					CDPeriod;
-	CD_STATE				CD_State;
-} CARRIER_DETECTION, *PCARRIER_DETECTION;
-#endif // CARRIER_DETECTION_SUPPORT //
-
-typedef enum _REC_BLOCKACK_STATUS
-{
-    Recipient_NONE=0,
-	Recipient_USED,
-	Recipient_HandleRes,
-    Recipient_Accept
-} REC_BLOCKACK_STATUS, *PREC_BLOCKACK_STATUS;
-
-typedef enum _ORI_BLOCKACK_STATUS
-{
-    Originator_NONE=0,
-	Originator_USED,
-    Originator_WaitRes,
-    Originator_Done
-} ORI_BLOCKACK_STATUS, *PORI_BLOCKACK_STATUS;
-
-#ifdef DOT11_N_SUPPORT
-typedef struct _BA_ORI_ENTRY{
-	UCHAR   Wcid;
-	UCHAR   TID;
-	UCHAR   BAWinSize;
-	UCHAR   Token;
-// Sequence is to fill every outgoing QoS DATA frame's sequence field in 802.11 header.
-	USHORT	Sequence;
-	USHORT	TimeOutValue;
-	ORI_BLOCKACK_STATUS  ORI_BA_Status;
-	RALINK_TIMER_STRUCT ORIBATimer;
-	PVOID	pAdapter;
-} BA_ORI_ENTRY, *PBA_ORI_ENTRY;
-
-typedef struct _BA_REC_ENTRY {
-	UCHAR   Wcid;
-	UCHAR   TID;
-	UCHAR   BAWinSize;	// 7.3.1.14. each buffer is capable of holding a max AMSDU or MSDU.
-	//UCHAR	NumOfRxPkt;
-	//UCHAR    Curindidx; // the head in the RX reordering buffer
-	USHORT		LastIndSeq;
-//	USHORT		LastIndSeqAtTimer;
-	USHORT		TimeOutValue;
-	RALINK_TIMER_STRUCT RECBATimer;
-	ULONG		LastIndSeqAtTimer;
-	ULONG		nDropPacket;
-	ULONG		rcvSeq;
-	REC_BLOCKACK_STATUS  REC_BA_Status;
-//	UCHAR	RxBufIdxUsed;
-	// corresponding virtual address for RX reordering packet storage.
-	//RTMP_REORDERDMABUF MAP_RXBuf[MAX_RX_REORDERBUF];
-	NDIS_SPIN_LOCK          RxReRingLock;                 // Rx Ring spinlock
-//	struct _BA_REC_ENTRY *pNext;
-	PVOID	pAdapter;
-	struct reordering_list	list;
-} BA_REC_ENTRY, *PBA_REC_ENTRY;
-
-
-typedef struct {
-	ULONG		numAsRecipient;		// I am recipient of numAsRecipient clients. These client are in the BARecEntry[]
-	ULONG		numAsOriginator;	// I am originator of 	numAsOriginator clients. These clients are in the BAOriEntry[]
-	BA_ORI_ENTRY       BAOriEntry[MAX_LEN_OF_BA_ORI_TABLE];
-	BA_REC_ENTRY       BARecEntry[MAX_LEN_OF_BA_REC_TABLE];
-} BA_TABLE, *PBA_TABLE;
-
-//For QureyBATableOID use;
-typedef struct  PACKED _OID_BA_REC_ENTRY{
-	UCHAR   MACAddr[MAC_ADDR_LEN];
-	UCHAR   BaBitmap;   // if (BaBitmap&(1<<TID)), this session with{MACAddr, TID}exists, so read BufSize[TID] for BufferSize
-	UCHAR   rsv;
-	UCHAR   BufSize[8];
-	REC_BLOCKACK_STATUS	REC_BA_Status[8];
-} OID_BA_REC_ENTRY, *POID_BA_REC_ENTRY;
-
-//For QureyBATableOID use;
-typedef struct  PACKED _OID_BA_ORI_ENTRY{
-	UCHAR   MACAddr[MAC_ADDR_LEN];
-	UCHAR   BaBitmap;  // if (BaBitmap&(1<<TID)), this session with{MACAddr, TID}exists, so read BufSize[TID] for BufferSize, read ORI_BA_Status[TID] for status
-	UCHAR   rsv;
-	UCHAR   BufSize[8];
-	ORI_BLOCKACK_STATUS  ORI_BA_Status[8];
-} OID_BA_ORI_ENTRY, *POID_BA_ORI_ENTRY;
-
-typedef struct _QUERYBA_TABLE{
-	OID_BA_ORI_ENTRY       BAOriEntry[32];
-	OID_BA_REC_ENTRY       BARecEntry[32];
-	UCHAR   OriNum;// Number of below BAOriEntry
-	UCHAR   RecNum;// Number of below BARecEntry
-} QUERYBA_TABLE, *PQUERYBA_TABLE;
-
-typedef	union	_BACAP_STRUC	{
-#ifdef RT_BIG_ENDIAN
-	struct	{
-		UINT32     :4;
-		UINT32     b2040CoexistScanSup:1;		//As Sta, support do 2040 coexistence scan for AP. As Ap, support monitor trigger event to check if can use BW 40MHz.
-		UINT32     bHtAdhoc:1;			// adhoc can use ht rate.
-		UINT32     MMPSmode:2;	// MIMO power save more, 0:static, 1:dynamic, 2:rsv, 3:mimo enable
-		UINT32     AmsduSize:1;	// 0:3839, 1:7935 bytes. UINT  MSDUSizeToBytes[]	= { 3839, 7935};
-		UINT32     AmsduEnable:1;	//Enable AMSDU transmisstion
-		UINT32		MpduDensity:3;
-		UINT32		Policy:2;	// 0: DELAY_BA 1:IMMED_BA  (//BA Policy subfiled value in ADDBA frame)   2:BA-not use
-		UINT32		AutoBA:1;	// automatically BA
-		UINT32		TxBAWinLimit:8;
-		UINT32		RxBAWinLimit:8;
-	}	field;
-#else
-	struct	{
-		UINT32		RxBAWinLimit:8;
-		UINT32		TxBAWinLimit:8;
-		UINT32		AutoBA:1;	// automatically BA
-		UINT32		Policy:2;	// 0: DELAY_BA 1:IMMED_BA  (//BA Policy subfiled value in ADDBA frame)   2:BA-not use
-		UINT32		MpduDensity:3;
-		UINT32       	AmsduEnable:1;	//Enable AMSDU transmisstion
-		UINT32       	AmsduSize:1;	// 0:3839, 1:7935 bytes. UINT  MSDUSizeToBytes[]	= { 3839, 7935};
-		UINT32       	MMPSmode:2;	// MIMO power save more, 0:static, 1:dynamic, 2:rsv, 3:mimo enable
-		UINT32       	bHtAdhoc:1;			// adhoc can use ht rate.
-		UINT32       	b2040CoexistScanSup:1;		//As Sta, support do 2040 coexistence scan for AP. As Ap, support monitor trigger event to check if can use BW 40MHz.
-		UINT32       	:4;
-	}	field;
-#endif
-	UINT32			word;
-} BACAP_STRUC, *PBACAP_STRUC;
-#endif // DOT11_N_SUPPORT //
-
-//This structure is for all 802.11n card InterOptibilityTest action. Reset all Num every n second.  (Details see MLMEPeriodic)
-typedef	struct	_IOT_STRUC	{
-	UCHAR			Threshold[2];
-	UCHAR			ReorderTimeOutNum[MAX_LEN_OF_BA_REC_TABLE];	// compare with threshold[0]
-	UCHAR			RefreshNum[MAX_LEN_OF_BA_REC_TABLE];	// compare with threshold[1]
-	ULONG			OneSecInWindowCount;
-	ULONG			OneSecFrameDuplicateCount;
-	ULONG			OneSecOutWindowCount;
-	UCHAR			DelOriAct;
-	UCHAR			DelRecAct;
-	UCHAR			RTSShortProt;
-	UCHAR			RTSLongProt;
-	BOOLEAN			bRTSLongProtOn;
-#ifdef CONFIG_STA_SUPPORT
-	BOOLEAN			bLastAtheros;
-    BOOLEAN			bCurrentAtheros;
-    BOOLEAN         bNowAtherosBurstOn;
-	BOOLEAN			bNextDisableRxBA;
-    BOOLEAN			bToggle;
-#endif // CONFIG_STA_SUPPORT //
-} IOT_STRUC, *PIOT_STRUC;
-
-// This is the registry setting for 802.11n transmit setting.  Used in advanced page.
-typedef union _REG_TRANSMIT_SETTING {
-#ifdef RT_BIG_ENDIAN
- struct {
-         UINT32  rsv:13;
-		 UINT32  EXTCHA:2;
-		 UINT32  HTMODE:1;
-		 UINT32  TRANSNO:2;
-		 UINT32  STBC:1; //SPACE
-		 UINT32  ShortGI:1;
-		 UINT32  BW:1; //channel bandwidth 20MHz or 40 MHz
-		 UINT32  TxBF:1; // 3*3
-		 UINT32  rsv0:10;
-		 //UINT32  MCS:7;                 // MCS
-         //UINT32  PhyMode:4;
-    } field;
-#else
- struct {
-         //UINT32  PhyMode:4;
-         //UINT32  MCS:7;                 // MCS
-		 UINT32  rsv0:10;
-		 UINT32  TxBF:1;
-         UINT32  BW:1; //channel bandwidth 20MHz or 40 MHz
-         UINT32  ShortGI:1;
-         UINT32  STBC:1; //SPACE
-         UINT32  TRANSNO:2;
-         UINT32  HTMODE:1;
-         UINT32  EXTCHA:2;
-         UINT32  rsv:13;
-    } field;
-#endif
- UINT32   word;
-} REG_TRANSMIT_SETTING, *PREG_TRANSMIT_SETTING;
-
-typedef union  _DESIRED_TRANSMIT_SETTING {
-#ifdef RT_BIG_ENDIAN
-	struct	{
-			USHORT		rsv:3;
-			USHORT		FixedTxMode:2;			// If MCS isn't AUTO, fix rate in CCK, OFDM or HT mode.
-			USHORT		PhyMode:4;
-			USHORT   	MCS:7;                 // MCS
-	}	field;
-#else
-	struct	{
-			USHORT   	MCS:7;                 	// MCS
-			USHORT		PhyMode:4;
-			USHORT	 	FixedTxMode:2;			// If MCS isn't AUTO, fix rate in CCK, OFDM or HT mode.
-			USHORT		rsv:3;
-	}	field;
-#endif
-	USHORT		word;
- } DESIRED_TRANSMIT_SETTING, *PDESIRED_TRANSMIT_SETTING;
-
-typedef struct {
-	BOOLEAN		IsRecipient;
-	UCHAR   MACAddr[MAC_ADDR_LEN];
-	UCHAR   TID;
-	UCHAR   nMSDU;
-	USHORT   TimeOut;
-	BOOLEAN bAllTid;  // If True, delete all TID for BA sessions with this MACaddr.
-} OID_ADD_BA_ENTRY, *POID_ADD_BA_ENTRY;
-
-//
-// Multiple SSID structure
-//
-#define WLAN_MAX_NUM_OF_TIM			((MAX_LEN_OF_MAC_TABLE >> 3) + 1) /* /8 + 1 */
-#define WLAN_CT_TIM_BCMC_OFFSET		0 /* unit: 32B */
-
-/* clear bcmc TIM bit */
-#define WLAN_MR_TIM_BCMC_CLEAR(apidx) \
-	pAd->ApCfg.MBSSID[apidx].TimBitmaps[WLAN_CT_TIM_BCMC_OFFSET] &= ~BIT8[0];
-
-/* set bcmc TIM bit */
-#define WLAN_MR_TIM_BCMC_SET(apidx) \
-	pAd->ApCfg.MBSSID[apidx].TimBitmaps[WLAN_CT_TIM_BCMC_OFFSET] |= BIT8[0];
-
-/* clear a station PS TIM bit */
-#define WLAN_MR_TIM_BIT_CLEAR(ad_p, apidx, wcid) \
-	{	UCHAR tim_offset = wcid >> 3; \
-		UCHAR bit_offset = wcid & 0x7; \
-		ad_p->ApCfg.MBSSID[apidx].TimBitmaps[tim_offset] &= (~BIT8[bit_offset]); }
-
-/* set a station PS TIM bit */
-#define WLAN_MR_TIM_BIT_SET(ad_p, apidx, wcid) \
-	{	UCHAR tim_offset = wcid >> 3; \
-		UCHAR bit_offset = wcid & 0x7; \
-		ad_p->ApCfg.MBSSID[apidx].TimBitmaps[tim_offset] |= BIT8[bit_offset]; }
-
-#ifdef RT2870
-#define BEACON_BITMAP_MASK		0xff
-typedef struct _BEACON_SYNC_STRUCT_
-{
-	UCHAR        			BeaconBuf[HW_BEACON_MAX_COUNT][HW_BEACON_OFFSET];
-	UCHAR					BeaconTxWI[HW_BEACON_MAX_COUNT][TXWI_SIZE];
-	ULONG 					TimIELocationInBeacon[HW_BEACON_MAX_COUNT];
-	ULONG					CapabilityInfoLocationInBeacon[HW_BEACON_MAX_COUNT];
-	BOOLEAN					EnableBeacon;		// trigger to enable beacon transmission.
-	UCHAR					BeaconBitMap;		// NOTE: If the MAX_MBSSID_NUM is larger than 8, this parameter need to change.
-	UCHAR					DtimBitOn;			// NOTE: If the MAX_MBSSID_NUM is larger than 8, this parameter need to change.
-}BEACON_SYNC_STRUCT;
-#endif // RT2870 //
-
-typedef struct _MULTISSID_STRUCT {
-	UCHAR								Bssid[MAC_ADDR_LEN];
-    UCHAR                               SsidLen;
-    CHAR                                Ssid[MAX_LEN_OF_SSID];
-    USHORT                              CapabilityInfo;
-
-    PNET_DEV                   			MSSIDDev;
-
-	NDIS_802_11_AUTHENTICATION_MODE     AuthMode;
-	NDIS_802_11_WEP_STATUS              WepStatus;
-	NDIS_802_11_WEP_STATUS				GroupKeyWepStatus;
-	WPA_MIX_PAIR_CIPHER					WpaMixPairCipher;
-
-	ULONG								TxCount;
-	ULONG								RxCount;
-	ULONG								ReceivedByteCount;
-	ULONG								TransmittedByteCount;
-	ULONG								RxErrorCount;
-	ULONG								RxDropCount;
-
-	HTTRANSMIT_SETTING					HTPhyMode, MaxHTPhyMode, MinHTPhyMode;// For transmit phy setting in TXWI.
-	RT_HT_PHY_INFO						DesiredHtPhyInfo;
-	DESIRED_TRANSMIT_SETTING        	DesiredTransmitSetting; // Desired transmit setting. this is for reading registry setting only. not useful.
-	BOOLEAN								bAutoTxRateSwitch;
-
-	//CIPHER_KEY                          SharedKey[SHARE_KEY_NUM]; // ref pAd->SharedKey[BSS][4]
-	UCHAR                               DefaultKeyId;
-
-	UCHAR								TxRate;       // RATE_1, RATE_2, RATE_5_5, RATE_11, ...
-	UCHAR     							DesiredRates[MAX_LEN_OF_SUPPORTED_RATES];// OID_802_11_DESIRED_RATES
-	UCHAR								DesiredRatesIndex;
-	UCHAR     							MaxTxRate;            // RATE_1, RATE_2, RATE_5_5, RATE_11
-
-//	ULONG           					TimBitmap;      // bit0 for broadcast, 1 for AID1, 2 for AID2, ...so on
-//    ULONG           					TimBitmap2;     // b0 for AID32, b1 for AID33, ... and so on
-	UCHAR								TimBitmaps[WLAN_MAX_NUM_OF_TIM];
-
-    // WPA
-    UCHAR                               GMK[32];
-    UCHAR                               PMK[32];
-	UCHAR								GTK[32];
-    BOOLEAN                             IEEE8021X;
-    BOOLEAN                             PreAuth;
-    UCHAR                               GNonce[32];
-    UCHAR                               PortSecured;
-    NDIS_802_11_PRIVACY_FILTER          PrivacyFilter;
-    UCHAR                               BANClass3Data;
-    ULONG                               IsolateInterStaTraffic;
-
-    UCHAR                               RSNIE_Len[2];
-    UCHAR                               RSN_IE[2][MAX_LEN_OF_RSNIE];
-
-
-    UCHAR                   			TimIELocationInBeacon;
-    UCHAR                   			CapabilityInfoLocationInBeacon;
-    // outgoing BEACON frame buffer and corresponding TXWI
-	// PTXWI_STRUC                           BeaconTxWI; //
-    CHAR                                BeaconBuf[MAX_BEACON_SIZE]; // NOTE: BeaconBuf should be 4-byte aligned
-
-    BOOLEAN                             bHideSsid;
-	UINT16								StationKeepAliveTime; // unit: second
-
-    USHORT                              VLAN_VID;
-    USHORT                              VLAN_Priority;
-
-    RT_802_11_ACL						AccessControlList;
-
-	// EDCA Qos
-    BOOLEAN								bWmmCapable;	// 0:disable WMM, 1:enable WMM
-    BOOLEAN								bDLSCapable;	// 0:disable DLS, 1:enable DLS
-
-	UCHAR           					DlsPTK[64];		// Due to windows dirver count on meetinghouse to handle 4-way shake
-
-	// For 802.1x daemon setting per BSS
-	UCHAR								radius_srv_num;
-	RADIUS_SRV_INFO						radius_srv_info[MAX_RADIUS_SRV_NUM];
-
-#ifdef RTL865X_SOC
-	unsigned int						mylinkid;
-#endif
-
-
-	UINT32					RcvdConflictSsidCount;
-	UINT32					RcvdSpoofedAssocRespCount;
-	UINT32					RcvdSpoofedReassocRespCount;
-	UINT32					RcvdSpoofedProbeRespCount;
-	UINT32					RcvdSpoofedBeaconCount;
-	UINT32					RcvdSpoofedDisassocCount;
-	UINT32					RcvdSpoofedAuthCount;
-	UINT32					RcvdSpoofedDeauthCount;
-	UINT32					RcvdSpoofedUnknownMgmtCount;
-	UINT32					RcvdReplayAttackCount;
-
-	CHAR					RssiOfRcvdConflictSsid;
-	CHAR					RssiOfRcvdSpoofedAssocResp;
-	CHAR					RssiOfRcvdSpoofedReassocResp;
-	CHAR					RssiOfRcvdSpoofedProbeResp;
-	CHAR					RssiOfRcvdSpoofedBeacon;
-	CHAR					RssiOfRcvdSpoofedDisassoc;
-	CHAR					RssiOfRcvdSpoofedAuth;
-	CHAR					RssiOfRcvdSpoofedDeauth;
-	CHAR					RssiOfRcvdSpoofedUnknownMgmt;
-	CHAR					RssiOfRcvdReplayAttack;
-
-	BOOLEAN					bBcnSntReq;
-	UCHAR					BcnBufIdx;
-} MULTISSID_STRUCT, *PMULTISSID_STRUCT;
-
-
-
-#ifdef DOT11N_DRAFT3
-typedef enum _BSS2040COEXIST_FLAG{
-	BSS_2040_COEXIST_DISABLE = 0,
-	BSS_2040_COEXIST_TIMER_FIRED  = 1,
-	BSS_2040_COEXIST_INFO_SYNC = 2,
-	BSS_2040_COEXIST_INFO_NOTIFY = 4,
-}BSS2040COEXIST_FLAG;
-#endif // DOT11N_DRAFT3 //
-
-// configuration common to OPMODE_AP as well as OPMODE_STA
-typedef struct _COMMON_CONFIG {
-
-	BOOLEAN		bCountryFlag;
-	UCHAR		CountryCode[3];
-	UCHAR		Geography;
-	UCHAR       CountryRegion;      // Enum of country region, 0:FCC, 1:IC, 2:ETSI, 3:SPAIN, 4:France, 5:MKK, 6:MKK1, 7:Israel
-	UCHAR       CountryRegionForABand;	// Enum of country region for A band
-	UCHAR       PhyMode;            // PHY_11A, PHY_11B, PHY_11BG_MIXED, PHY_ABG_MIXED
-	USHORT      Dsifs;              // in units of usec
-	ULONG       PacketFilter;       // Packet filter for receiving
-
-	CHAR        Ssid[MAX_LEN_OF_SSID]; // NOT NULL-terminated
-	UCHAR       SsidLen;               // the actual ssid length in used
-	UCHAR       LastSsidLen;               // the actual ssid length in used
-	CHAR        LastSsid[MAX_LEN_OF_SSID]; // NOT NULL-terminated
-	UCHAR		LastBssid[MAC_ADDR_LEN];
-
-	UCHAR       Bssid[MAC_ADDR_LEN];
-	USHORT      BeaconPeriod;
-	UCHAR       Channel;
-	UCHAR       CentralChannel;    	// Central Channel when using 40MHz is indicating. not real channel.
-
-	UCHAR       SupRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR       SupRateLen;
-	UCHAR       ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR       ExtRateLen;
-	UCHAR       DesireRate[MAX_LEN_OF_SUPPORTED_RATES];      // OID_802_11_DESIRED_RATES
-	UCHAR       MaxDesiredRate;
-	UCHAR       ExpectedACKRate[MAX_LEN_OF_SUPPORTED_RATES];
-
-	ULONG       BasicRateBitmap;        // backup basic ratebitmap
-
-	BOOLEAN		bAPSDCapable;
-	BOOLEAN		bInServicePeriod;
-	BOOLEAN		bAPSDAC_BE;
-	BOOLEAN		bAPSDAC_BK;
-	BOOLEAN		bAPSDAC_VI;
-	BOOLEAN		bAPSDAC_VO;
-	BOOLEAN		bNeedSendTriggerFrame;
-	BOOLEAN		bAPSDForcePowerSave;	// Force power save mode, should only use in APSD-STAUT
-	ULONG		TriggerTimerCount;
-	UCHAR		MaxSPLength;
-	UCHAR		BBPCurrentBW;	// BW_10, 	BW_20, BW_40
-	// move to MULTISSID_STRUCT for MBSS
-	//HTTRANSMIT_SETTING	HTPhyMode, MaxHTPhyMode, MinHTPhyMode;// For transmit phy setting in TXWI.
-	REG_TRANSMIT_SETTING        RegTransmitSetting; //registry transmit setting. this is for reading registry setting only. not useful.
-	//UCHAR       FixedTxMode;              // Fixed Tx Mode (CCK, OFDM), for HT fixed tx mode (GF, MIX) , refer to RegTransmitSetting.field.HTMode
-	UCHAR       TxRate;                 // Same value to fill in TXD. TxRate is 6-bit
-	UCHAR       MaxTxRate;              // RATE_1, RATE_2, RATE_5_5, RATE_11
-	UCHAR       TxRateIndex;            // Tx rate index in RateSwitchTable
-	UCHAR       TxRateTableSize;        // Valid Tx rate table size in RateSwitchTable
-	//BOOLEAN		bAutoTxRateSwitch;
-	UCHAR       MinTxRate;              // RATE_1, RATE_2, RATE_5_5, RATE_11
-	UCHAR       RtsRate;                // RATE_xxx
-	HTTRANSMIT_SETTING	MlmeTransmit;   // MGMT frame PHY rate setting when operatin at Ht rate.
-	UCHAR       MlmeRate;               // RATE_xxx, used to send MLME frames
-	UCHAR       BasicMlmeRate;          // Default Rate for sending MLME frames
-
-	USHORT      RtsThreshold;           // in unit of BYTE
-	USHORT      FragmentThreshold;      // in unit of BYTE
-
-	UCHAR       TxPower;                // in unit of mW
-	ULONG       TxPowerPercentage;      // 0~100 %
-	ULONG       TxPowerDefault;         // keep for TxPowerPercentage
-
-#ifdef DOT11_N_SUPPORT
-	BACAP_STRUC        BACapability; //   NO USE = 0XFF  ;  IMMED_BA =1  ;  DELAY_BA=0
-	BACAP_STRUC        REGBACapability; //   NO USE = 0XFF  ;  IMMED_BA =1  ;  DELAY_BA=0
-#endif // DOT11_N_SUPPORT //
-	IOT_STRUC		IOTestParm;	// 802.11n InterOpbility Test Parameter;
-	ULONG       TxPreamble;             // Rt802_11PreambleLong, Rt802_11PreambleShort, Rt802_11PreambleAuto
-	BOOLEAN     bUseZeroToDisableFragment;     // Microsoft use 0 as disable
-	ULONG       UseBGProtection;        // 0: auto, 1: always use, 2: always not use
-	BOOLEAN     bUseShortSlotTime;      // 0: disable, 1 - use short slot (9us)
-	BOOLEAN     bEnableTxBurst;         // 1: enble TX PACKET BURST, 0: disable TX PACKET BURST
-	BOOLEAN     bAggregationCapable;      // 1: enable TX aggregation when the peer supports it
-	BOOLEAN     bPiggyBackCapable;		// 1: enable TX piggy-back according MAC's version
-	BOOLEAN     bIEEE80211H;			// 1: enable IEEE802.11h spec.
-	ULONG		DisableOLBCDetect;		// 0: enable OLBC detect; 1 disable OLBC detect
-
-#ifdef DOT11_N_SUPPORT
-	BOOLEAN				bRdg;
-#endif // DOT11_N_SUPPORT //
-	BOOLEAN             bWmmCapable;        // 0:disable WMM, 1:enable WMM
-	QOS_CAPABILITY_PARM APQosCapability;    // QOS capability of the current associated AP
-	EDCA_PARM           APEdcaParm;         // EDCA parameters of the current associated AP
-	QBSS_LOAD_PARM      APQbssLoad;         // QBSS load of the current associated AP
-	UCHAR               AckPolicy[4];       // ACK policy of the specified AC. see ACK_xxx
-#ifdef CONFIG_STA_SUPPORT
-	BOOLEAN				bDLSCapable;		// 0:disable DLS, 1:enable DLS
-#endif // CONFIG_STA_SUPPORT //
-	// a bitmap of BOOLEAN flags. each bit represent an operation status of a particular
-	// BOOLEAN control, either ON or OFF. These flags should always be accessed via
-	// OPSTATUS_TEST_FLAG(), OPSTATUS_SET_FLAG(), OP_STATUS_CLEAR_FLAG() macros.
-	// see fOP_STATUS_xxx in RTMP_DEF.C for detail bit definition
-	ULONG               OpStatusFlags;
-
-	BOOLEAN				NdisRadioStateOff; //For HCT 12.0, set this flag to TRUE instead of called MlmeRadioOff.
-	ABGBAND_STATE		BandState;		// For setting BBP used on B/G or A mode.
-	BOOLEAN				bRxAntDiversity; // 0:disable, 1:enable Software Rx Antenna Diversity.
-
-	// IEEE802.11H--DFS.
-	RADAR_DETECT_STRUCT	RadarDetect;
-
-#ifdef CARRIER_DETECTION_SUPPORT
-	CARRIER_DETECTION		CarrierDetect;
-#endif // CARRIER_DETECTION_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-	// HT
-	UCHAR			BASize;		// USer desired BAWindowSize. Should not exceed our max capability
-	//RT_HT_CAPABILITY	SupportedHtPhy;
-	RT_HT_CAPABILITY	DesiredHtPhy;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHTInfo;	// Useful as AP.
-	//This IE is used with channel switch announcement element when changing to a new 40MHz.
-	//This IE is included in channel switch ammouncement frames 7.4.1.5, beacons, probe Rsp.
-	NEW_EXT_CHAN_IE	NewExtChanOffset;	//7.3.2.20A, 1 if extension channel is above the control channel, 3 if below, 0 if not present
-
-#ifdef DOT11N_DRAFT3
-	UCHAR					Bss2040CoexistFlag;		// bit 0: bBssCoexistTimerRunning, bit 1: NeedSyncAddHtInfo.
-	RALINK_TIMER_STRUCT	Bss2040CoexistTimer;
-
-	//This IE is used for 20/40 BSS Coexistence.
-	BSS_2040_COEXIST_IE		BSS2040CoexistInfo;
-	// ====== 11n D3.0 =======================>
-	USHORT					Dot11OBssScanPassiveDwell;				// Unit : TU. 5~1000
-	USHORT					Dot11OBssScanActiveDwell;				// Unit : TU. 10~1000
-	USHORT					Dot11BssWidthTriggerScanInt;			// Unit : Second
-	USHORT					Dot11OBssScanPassiveTotalPerChannel;	// Unit : TU. 200~10000
-	USHORT					Dot11OBssScanActiveTotalPerChannel;	// Unit : TU. 20~10000
-	USHORT					Dot11BssWidthChanTranDelayFactor;
-	USHORT					Dot11OBssScanActivityThre;				// Unit : percentage
-
-	ULONG					Dot11BssWidthChanTranDelay;			// multiple of (Dot11BssWidthTriggerScanInt * Dot11BssWidthChanTranDelayFactor)
-	ULONG					CountDownCtr;	// CountDown Counter from (Dot11BssWidthTriggerScanInt * Dot11BssWidthChanTranDelayFactor)
-
-	NDIS_SPIN_LOCK          TriggerEventTabLock;
-	BSS_2040_COEXIST_IE		LastBSSCoexist2040;
-	BSS_2040_COEXIST_IE		BSSCoexist2040;
-	TRIGGER_EVENT_TAB		TriggerEventTab;
-	UCHAR					ChannelListIdx;
-	// <====== 11n D3.0 =======================
-	BOOLEAN					bOverlapScanning;
-#endif // DOT11N_DRAFT3 //
-
-    BOOLEAN                 bHTProtect;
-    BOOLEAN                 bMIMOPSEnable;
-    BOOLEAN					bBADecline;
-	BOOLEAN					bDisableReordering;
-	BOOLEAN					bForty_Mhz_Intolerant;
-	BOOLEAN					bExtChannelSwitchAnnouncement;
-	BOOLEAN					bRcvBSSWidthTriggerEvents;
-	ULONG					LastRcvBSSWidthTriggerEventsTime;
-
-	UCHAR					TxBASize;
-#endif // DOT11_N_SUPPORT //
-
-	// Enable wireless event
-	BOOLEAN				bWirelessEvent;
-	BOOLEAN				bWiFiTest;				// Enable this parameter for WiFi test
-
-	// Tx & Rx Stream number selection
-	UCHAR				TxStream;
-	UCHAR				RxStream;
-
-	// transmit phy mode, trasmit rate for Multicast.
-#ifdef MCAST_RATE_SPECIFIC
-	UCHAR				McastTransmitMcs;
-	UCHAR				McastTransmitPhyMode;
-#endif // MCAST_RATE_SPECIFIC //
-
-	BOOLEAN     		bHardwareRadio;     // Hardware controlled Radio enabled
-
-#ifdef RT2870
-	BOOLEAN     		bMultipleIRP;       // Multiple Bulk IN flag
-	UCHAR       		NumOfBulkInIRP;     // if bMultipleIRP == TRUE, NumOfBulkInIRP will be 4 otherwise be 1
- 	RT_HT_CAPABILITY	SupportedHtPhy;
-	ULONG				MaxPktOneTxBulk;
-	UCHAR				TxBulkFactor;
-	UCHAR				RxBulkFactor;
-
-	BEACON_SYNC_STRUCT	*pBeaconSync;
-	RALINK_TIMER_STRUCT	BeaconUpdateTimer;
-	UINT32				BeaconAdjust;
-	UINT32				BeaconFactor;
-	UINT32				BeaconRemain;
-#endif // RT2870 //
-
-
- 	NDIS_SPIN_LOCK			MeasureReqTabLock;
-	PMEASURE_REQ_TAB		pMeasureReqTab;
-
-	NDIS_SPIN_LOCK			TpcReqTabLock;
-	PTPC_REQ_TAB			pTpcReqTab;
-
-	// transmit phy mode, trasmit rate for Multicast.
-#ifdef MCAST_RATE_SPECIFIC
-	HTTRANSMIT_SETTING		MCastPhyMode;
-#endif // MCAST_RATE_SPECIFIC //
-
-#ifdef SINGLE_SKU
-	UINT16					DefineMaxTxPwr;
-#endif // SINGLE_SKU //
-
-
-} COMMON_CONFIG, *PCOMMON_CONFIG;
-
-
-#ifdef CONFIG_STA_SUPPORT
-/* Modified by Wu Xi-Kun 4/21/2006 */
-// STA configuration and status
-typedef struct _STA_ADMIN_CONFIG {
-	// GROUP 1 -
-	//   User configuration loaded from Registry, E2PROM or OID_xxx. These settings describe
-	//   the user intended configuration, but not necessary fully equal to the final
-	//   settings in ACTIVE BSS after negotiation/compromize with the BSS holder (either
-	//   AP or IBSS holder).
-	//   Once initialized, user configuration can only be changed via OID_xxx
-	UCHAR       BssType;              // BSS_INFRA or BSS_ADHOC
-	USHORT      AtimWin;          // used when starting a new IBSS
-
-	// GROUP 2 -
-	//   User configuration loaded from Registry, E2PROM or OID_xxx. These settings describe
-	//   the user intended configuration, and should be always applied to the final
-	//   settings in ACTIVE BSS without compromising with the BSS holder.
-	//   Once initialized, user configuration can only be changed via OID_xxx
-	UCHAR       RssiTrigger;
-	UCHAR       RssiTriggerMode;      // RSSI_TRIGGERED_UPON_BELOW_THRESHOLD or RSSI_TRIGGERED_UPON_EXCCEED_THRESHOLD
-	USHORT      DefaultListenCount;   // default listen count;
-	ULONG       WindowsPowerMode;           // Power mode for AC power
-	ULONG       WindowsBatteryPowerMode;    // Power mode for battery if exists
-	BOOLEAN     bWindowsACCAMEnable;        // Enable CAM power mode when AC on
-	BOOLEAN     bAutoReconnect;         // Set to TRUE when setting OID_802_11_SSID with no matching BSSID
-	ULONG       WindowsPowerProfile;    // Windows power profile, for NDIS5.1 PnP
-
-	// MIB:ieee802dot11.dot11smt(1).dot11StationConfigTable(1)
-	USHORT      Psm;                  // power management mode   (PWR_ACTIVE|PWR_SAVE)
-	USHORT      DisassocReason;
-	UCHAR       DisassocSta[MAC_ADDR_LEN];
-	USHORT      DeauthReason;
-	UCHAR       DeauthSta[MAC_ADDR_LEN];
-	USHORT      AuthFailReason;
-	UCHAR       AuthFailSta[MAC_ADDR_LEN];
-
-	NDIS_802_11_PRIVACY_FILTER          PrivacyFilter;  // PrivacyFilter enum for 802.1X
-	NDIS_802_11_AUTHENTICATION_MODE     AuthMode;       // This should match to whatever microsoft defined
-	NDIS_802_11_WEP_STATUS              WepStatus;
-	NDIS_802_11_WEP_STATUS				OrigWepStatus;	// Original wep status set from OID
-
-	// Add to support different cipher suite for WPA2/WPA mode
-	NDIS_802_11_ENCRYPTION_STATUS		GroupCipher;		// Multicast cipher suite
-	NDIS_802_11_ENCRYPTION_STATUS		PairCipher;			// Unicast cipher suite
-	BOOLEAN								bMixCipher;			// Indicate current Pair & Group use different cipher suites
-	USHORT								RsnCapability;
-
-	NDIS_802_11_WEP_STATUS              GroupKeyWepStatus;
-
-	UCHAR		PMK[32];                // WPA PSK mode PMK
-	UCHAR       PTK[64];                // WPA PSK mode PTK
-	UCHAR		GTK[32];				// GTK from authenticator
-	BSSID_INFO	SavedPMK[PMKID_NO];
-	UINT		SavedPMKNum;			// Saved PMKID number
-
-	UCHAR		DefaultKeyId;
-
-
-	// WPA 802.1x port control, WPA_802_1X_PORT_SECURED, WPA_802_1X_PORT_NOT_SECURED
-	UCHAR       PortSecured;
-
-	// For WPA countermeasures
-	ULONG       LastMicErrorTime;   // record last MIC error time
-	ULONG       MicErrCnt;          // Should be 0, 1, 2, then reset to zero (after disassoiciation).
-	BOOLEAN     bBlockAssoc;        // Block associate attempt for 60 seconds after counter measure occurred.
-	// For WPA-PSK supplicant state
-	WPA_STATE   WpaState;           // Default is SS_NOTUSE and handled by microsoft 802.1x
-	UCHAR       ReplayCounter[8];
-	UCHAR       ANonce[32];         // ANonce for WPA-PSK from aurhenticator
-	UCHAR       SNonce[32];         // SNonce for WPA-PSK
-
-	UCHAR       LastSNR0;             // last received BEACON's SNR
-	UCHAR       LastSNR1;            // last received BEACON's SNR for 2nd  antenna
-	RSSI_SAMPLE RssiSample;
-	ULONG       NumOfAvgRssiSample;
-
-	ULONG       LastBeaconRxTime;     // OS's timestamp of the last BEACON RX time
-	ULONG       Last11bBeaconRxTime;  // OS's timestamp of the last 11B BEACON RX time
-	ULONG		Last11gBeaconRxTime;	// OS's timestamp of the last 11G BEACON RX time
-	ULONG		Last20NBeaconRxTime;	// OS's timestamp of the last 20MHz N BEACON RX time
-
-	ULONG       LastScanTime;       // Record last scan time for issue BSSID_SCAN_LIST
-	ULONG       ScanCnt;            // Scan counts since most recent SSID, BSSID, SCAN OID request
-	BOOLEAN     bSwRadio;           // Software controlled Radio On/Off, TRUE: On
-	BOOLEAN     bHwRadio;           // Hardware controlled Radio On/Off, TRUE: On
-	BOOLEAN     bRadio;             // Radio state, And of Sw & Hw radio state
-	BOOLEAN     bHardwareRadio;     // Hardware controlled Radio enabled
-	BOOLEAN     bShowHiddenSSID;    // Show all known SSID in SSID list get operation
-
-    //BOOLEAN		AdhocBOnlyJoined;	// Indicate Adhoc B Join.
-    //BOOLEAN		AdhocBGJoined;		// Indicate Adhoc B/G Join.
-    //BOOLEAN		Adhoc20NJoined;		// Indicate Adhoc 20MHz N Join.
-
-	// New for WPA, windows want us to to keep association information and
-	// Fixed IEs from last association response
-	NDIS_802_11_ASSOCIATION_INFORMATION     AssocInfo;
-	USHORT       ReqVarIELen;                // Length of next VIE include EID & Length
-	UCHAR       ReqVarIEs[MAX_VIE_LEN];		// The content saved here should be little-endian format.
-	USHORT       ResVarIELen;                // Length of next VIE include EID & Length
-	UCHAR       ResVarIEs[MAX_VIE_LEN];
-
-	UCHAR       RSNIE_Len;
-	UCHAR       RSN_IE[MAX_LEN_OF_RSNIE];	// The content saved here should be little-endian format.
-
-	// New variables used for CCX 1.0
-	BOOLEAN             bCkipOn;
-	BOOLEAN             bCkipCmicOn;
-	UCHAR               CkipFlag;
-	UCHAR               GIV[3];  //for CCX iv
-	UCHAR               RxSEQ[4];
-	UCHAR               TxSEQ[4];
-	UCHAR               CKIPMIC[4];
-	UCHAR               LeapAuthMode;
-	LEAP_AUTH_INFO      LeapAuthInfo;
-	UCHAR               HashPwd[16];
-	UCHAR               NetworkChallenge[8];
-	UCHAR               NetworkChallengeResponse[24];
-	UCHAR               PeerChallenge[8];
-
-	UCHAR               PeerChallengeResponse[24];
-	UCHAR               SessionKey[16]; //Network session keys (NSK)
-	RALINK_TIMER_STRUCT LeapAuthTimer;
-	ROGUEAP_TABLE       RogueApTab;   //Cisco CCX1 Rogue AP Detection
-
-	// New control flags for CCX
-	CCX_CONTROL         CCXControl;                 // Master administration state
-	BOOLEAN             CCXEnable;                  // Actual CCX state
-	UCHAR               CCXScanChannel;             // Selected channel for CCX beacon request
-	USHORT              CCXScanTime;                // Time out to wait for beacon and probe response
-	UCHAR               CCXReqType;                 // Current processing CCX request type
-	BSS_TABLE           CCXBssTab;                  // BSS Table
-	UCHAR               FrameReportBuf[2048];       // Buffer for creating frame report
-	USHORT              FrameReportLen;             // Current Frame report length
-	ULONG               CLBusyBytes;                // Save the total bytes received durning channel load scan time
-	USHORT              RPIDensity[8];              // Array for RPI density collection
-	// Start address of each BSS table within FrameReportBuf
-	// It's important to update the RxPower of the corresponding Bss
-	USHORT              BssReportOffset[MAX_LEN_OF_BSS_TABLE];
-	USHORT              BeaconToken;                // Token for beacon report
-	ULONG               LastBssIndex;               // Most current reported Bss index
-	RM_REQUEST_ACTION   MeasurementRequest[16];     // Saved measurement request
-	UCHAR               RMReqCnt;                   // Number of measurement request saved.
-	UCHAR               CurrentRMReqIdx;            // Number of measurement request saved.
-	BOOLEAN             ParallelReq;                // Parallel measurement, only one request performed,
-													// It must be the same channel with maximum duration
-	USHORT              ParallelDuration;           // Maximum duration for parallel measurement
-	UCHAR               ParallelChannel;            // Only one channel with parallel measurement
-	USHORT              IAPPToken;                  // IAPP dialog token
-	UCHAR               CCXQosECWMin;               // Cisco QOS ECWMin for AC 0
-	UCHAR               CCXQosECWMax;               // Cisco QOS ECWMax for AC 0
-	// Hack for channel load and noise histogram parameters
-	UCHAR               NHFactor;                   // Parameter for Noise histogram
-	UCHAR               CLFactor;                   // Parameter for channel load
-
-	UCHAR               KRK[16];        //Key Refresh Key.
-	UCHAR               BTK[32];        //Base Transient Key
-	BOOLEAN             CCKMLinkUpFlag;
-	ULONG               CCKMRN;    //(Re)Association request number.
-	LARGE_INTEGER       CCKMBeaconAtJoinTimeStamp;  //TSF timer for Re-assocaite to the new AP
-	UCHAR               AironetCellPowerLimit;      //in dBm
-	UCHAR               AironetIPAddress[4];        //eg. 192.168.1.1
-	BOOLEAN             CCXAdjacentAPReportFlag;    //flag for determining report Assoc Lost time
-	CHAR                CCXAdjacentAPSsid[MAX_LEN_OF_SSID]; //Adjacent AP's SSID report
-	UCHAR               CCXAdjacentAPSsidLen;               // the actual ssid length in used
-	UCHAR               CCXAdjacentAPBssid[MAC_ADDR_LEN];         //Adjacent AP's BSSID report
-	USHORT              CCXAdjacentAPChannel;
-	ULONG               CCXAdjacentAPLinkDownTime;  //for Spec S32.
-
-	RALINK_TIMER_STRUCT	StaQuickResponeForRateUpTimer;
-	BOOLEAN				StaQuickResponeForRateUpTimerRunning;
-
-	UCHAR           	DtimCount;      // 0.. DtimPeriod-1
-	UCHAR           	DtimPeriod;     // default = 3
-
-#ifdef QOS_DLS_SUPPORT
-	RT_802_11_DLS		DLSEntry[MAX_NUM_OF_DLS_ENTRY];
-	UCHAR				DlsReplayCounter[8];
-#endif // QOS_DLS_SUPPORT //
-	////////////////////////////////////////////////////////////////////////////////////////
-	// This is only for WHQL test.
-	BOOLEAN				WhqlTest;
-	////////////////////////////////////////////////////////////////////////////////////////
-
-    RALINK_TIMER_STRUCT WpaDisassocAndBlockAssocTimer;
-    // Fast Roaming
-	BOOLEAN		        bFastRoaming;       // 0:disable fast roaming, 1:enable fast roaming
-	CHAR		        dBmToRoam;          // the condition to roam when receiving Rssi less than this value. It's negative value.
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-    BOOLEAN             IEEE8021X;
-    BOOLEAN             IEEE8021x_required_keys;
-    CIPHER_KEY	        DesireSharedKey[4];	// Record user desired WEP keys
-    UCHAR               DesireSharedKeyId;
-
-    // 0: driver ignores wpa_supplicant
-    // 1: wpa_supplicant initiates scanning and AP selection
-    // 2: driver takes care of scanning, AP selection, and IEEE 802.11 association parameters
-    UCHAR               WpaSupplicantUP;
-	UCHAR				WpaSupplicantScanCount;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-    CHAR                dev_name[16];
-    USHORT              OriDevType;
-
-    BOOLEAN             bTGnWifiTest;
-	BOOLEAN			    bScanReqIsFromWebUI;
-
-	HTTRANSMIT_SETTING				HTPhyMode, MaxHTPhyMode, MinHTPhyMode;// For transmit phy setting in TXWI.
-	DESIRED_TRANSMIT_SETTING       	DesiredTransmitSetting;
-	RT_HT_PHY_INFO					DesiredHtPhyInfo;
-	BOOLEAN							bAutoTxRateSwitch;
-
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-	UCHAR				IEEE80211dClientMode;
-	UCHAR				StaOriCountryCode[3];
-	UCHAR				StaOriGeography;
-#endif // EXT_BUILD_CHANNEL_LIST //
-} STA_ADMIN_CONFIG, *PSTA_ADMIN_CONFIG;
-
-// This data structure keep the current active BSS/IBSS's configuration that this STA
-// had agreed upon joining the network. Which means these parameters are usually decided
-// by the BSS/IBSS creator instead of user configuration. Data in this data structurre
-// is valid only when either ADHOC_ON(pAd) or INFRA_ON(pAd) is TRUE.
-// Normally, after SCAN or failed roaming attempts, we need to recover back to
-// the current active settings.
-typedef struct _STA_ACTIVE_CONFIG {
-	USHORT      Aid;
-	USHORT      AtimWin;                // in kusec; IBSS parameter set element
-	USHORT      CapabilityInfo;
-	USHORT      CfpMaxDuration;
-	USHORT      CfpPeriod;
-
-	// Copy supported rate from desired AP's beacon. We are trying to match
-	// AP's supported and extended rate settings.
-	UCHAR       SupRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR       ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR       SupRateLen;
-	UCHAR       ExtRateLen;
-	// Copy supported ht from desired AP's beacon. We are trying to match
-	RT_HT_PHY_INFO		SupportedPhyInfo;
-	RT_HT_CAPABILITY	SupportedHtPhy;
-} STA_ACTIVE_CONFIG, *PSTA_ACTIVE_CONFIG;
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef RT2870
-typedef struct   RT_ADD_PAIRWISE_KEY_ENTRY {
-        NDIS_802_11_MAC_ADDRESS         MacAddr;
-        USHORT                          MacTabMatchWCID;        // ASIC
-        CIPHER_KEY      CipherKey;
-} RT_ADD_PAIRWISE_KEY_ENTRY,*PRT_ADD_PAIRWISE_KEY_ENTRY;
-#endif // RT2870 //
-
-// ----------- start of AP --------------------------
-// AUTH-RSP State Machine Aux data structure
-typedef struct _AP_MLME_AUX {
-	UCHAR               Addr[MAC_ADDR_LEN];
-	USHORT              Alg;
-	CHAR                Challenge[CIPHER_TEXT_LEN];
-} AP_MLME_AUX, *PAP_MLME_AUX;
-
-// structure to define WPA Group Key Rekey Interval
-typedef struct PACKED _RT_802_11_WPA_REKEY {
-	ULONG ReKeyMethod;          // mechanism for rekeying: 0:disable, 1: time-based, 2: packet-based
-	ULONG ReKeyInterval;        // time-based: seconds, packet-based: kilo-packets
-} RT_WPA_REKEY,*PRT_WPA_REKEY, RT_802_11_WPA_REKEY, *PRT_802_11_WPA_REKEY;
-
-typedef struct _MAC_TABLE_ENTRY {
-	//Choose 1 from ValidAsWDS and ValidAsCLI  to validize.
-	BOOLEAN		ValidAsCLI;		// Sta mode, set this TRUE after Linkup,too.
-	BOOLEAN		ValidAsWDS;	// This is WDS Entry. only for AP mode.
-	BOOLEAN		ValidAsApCli;   //This is a AP-Client entry, only for AP mode which enable AP-Client functions.
-	BOOLEAN		ValidAsMesh;
-	BOOLEAN		ValidAsDls;	// This is DLS Entry. only for STA mode.
-	BOOLEAN		isCached;
-	BOOLEAN		bIAmBadAtheros;
-
-	UCHAR         	EnqueueEapolStartTimerRunning;  // Enqueue EAPoL-Start for triggering EAP SM
-	//jan for wpa
-	// record which entry revoke MIC Failure , if it leaves the BSS itself, AP won't update aMICFailTime MIB
-	UCHAR           CMTimerRunning;
-	UCHAR           apidx;			// MBSS number
-	UCHAR           RSNIE_Len;
-	UCHAR           RSN_IE[MAX_LEN_OF_RSNIE];
-	UCHAR           ANonce[LEN_KEY_DESC_NONCE];
-	UCHAR           R_Counter[LEN_KEY_DESC_REPLAY];
-	UCHAR           PTK[64];
-	UCHAR           ReTryCounter;
-	RALINK_TIMER_STRUCT                 RetryTimer;
-	RALINK_TIMER_STRUCT					EnqueueStartForPSKTimer;	// A timer which enqueue EAPoL-Start for triggering PSK SM
-	NDIS_802_11_AUTHENTICATION_MODE     AuthMode;   // This should match to whatever microsoft defined
-	NDIS_802_11_WEP_STATUS              WepStatus;
-	AP_WPA_STATE    WpaState;
-	GTK_STATE       GTKState;
-	USHORT          PortSecured;
-	NDIS_802_11_PRIVACY_FILTER  PrivacyFilter;      // PrivacyFilter enum for 802.1X
-	CIPHER_KEY      PairwiseKey;
-	PVOID           pAd;
-    INT				PMKID_CacheIdx;
-    UCHAR			PMKID[LEN_PMKID];
-
-
-	UCHAR           Addr[MAC_ADDR_LEN];
-	UCHAR           PsMode;
-	SST             Sst;
-	AUTH_STATE      AuthState; // for SHARED KEY authentication state machine used only
-	BOOLEAN			IsReassocSta;	// Indicate whether this is a reassociation procedure
-	USHORT          Aid;
-	USHORT          CapabilityInfo;
-	UCHAR           LastRssi;
-	ULONG           NoDataIdleCount;
-	UINT16			StationKeepAliveCount; // unit: second
-	ULONG           PsQIdleCount;
-	QUEUE_HEADER    PsQueue;
-
-	UINT32			StaConnectTime;		// the live time of this station since associated with AP
-
-
-#ifdef DOT11_N_SUPPORT
-	BOOLEAN			bSendBAR;
-	USHORT			NoBADataCountDown;
-
-	UINT32   		CachedBuf[16];		// UINT (4 bytes) for alignment
-	UINT			TxBFCount; // 3*3
-#endif // DOT11_N_SUPPORT //
-	UINT			FIFOCount;
-	UINT			DebugFIFOCount;
-	UINT			DebugTxCount;
-    BOOLEAN			bDlsInit;
-
-
-//====================================================
-//WDS entry needs these
-// rt2860 add this. if ValidAsWDS==TRUE, MatchWDSTabIdx is the index in WdsTab.MacTab
-	UINT			MatchWDSTabIdx;
-	UCHAR           MaxSupportedRate;
-	UCHAR           CurrTxRate;
-	UCHAR           CurrTxRateIndex;
-	// to record the each TX rate's quality. 0 is best, the bigger the worse.
-	USHORT          TxQuality[MAX_STEP_OF_TX_RATE_SWITCH];
-//	USHORT          OneSecTxOkCount;
-	UINT32			OneSecTxNoRetryOkCount;
-	UINT32          OneSecTxRetryOkCount;
-	UINT32          OneSecTxFailCount;
-	UINT32			ContinueTxFailCnt;
-	UINT32          CurrTxRateStableTime; // # of second in current TX rate
-	UCHAR           TxRateUpPenalty;      // extra # of second penalty due to last unstable condition
-//====================================================
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-	UINT			MatchDlsEntryIdx; // indicate the index in pAd->StaCfg.DLSEntry
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-	BOOLEAN         fNoisyEnvironment;
-	BOOLEAN			fLastSecAccordingRSSI;
-	UCHAR           LastSecTxRateChangeAction; // 0: no change, 1:rate UP, 2:rate down
-	CHAR			LastTimeTxRateChangeAction; //Keep last time value of LastSecTxRateChangeAction
-	ULONG			LastTxOkCount;
-	UCHAR           PER[MAX_STEP_OF_TX_RATE_SWITCH];
-
-	// a bitmap of BOOLEAN flags. each bit represent an operation status of a particular
-	// BOOLEAN control, either ON or OFF. These flags should always be accessed via
-	// CLIENT_STATUS_TEST_FLAG(), CLIENT_STATUS_SET_FLAG(), CLIENT_STATUS_CLEAR_FLAG() macros.
-	// see fOP_STATUS_xxx in RTMP_DEF.C for detail bit definition. fCLIENT_STATUS_AMSDU_INUSED
-	ULONG           ClientStatusFlags;
-
-	// TODO: Shall we move that to DOT11_N_SUPPORT???
-	HTTRANSMIT_SETTING	HTPhyMode, MaxHTPhyMode, MinHTPhyMode;// For transmit phy setting in TXWI.
-
-#ifdef DOT11_N_SUPPORT
-	// HT EWC MIMO-N used parameters
-	USHORT		RXBAbitmap;	// fill to on-chip  RXWI_BA_BITMASK in 8.1.3RX attribute entry format
-	USHORT		TXBAbitmap;	// This bitmap as originator, only keep in software used to mark AMPDU bit in TXWI
-	USHORT		TXAutoBAbitmap;
-	USHORT		BADeclineBitmap;
-	USHORT		BARecWcidArray[NUM_OF_TID];	// The mapping wcid of recipient session. if RXBAbitmap bit is masked
-	USHORT		BAOriWcidArray[NUM_OF_TID]; // The mapping wcid of originator session. if TXBAbitmap bit is masked
-	USHORT		BAOriSequence[NUM_OF_TID]; // The mapping wcid of originator session. if TXBAbitmap bit is masked
-
-	// 802.11n features.
-	UCHAR		MpduDensity;
-	UCHAR		MaxRAmpduFactor;
-	UCHAR		AMsduSize;
-	UCHAR		MmpsMode;	// MIMO power save more.
-
-	HT_CAPABILITY_IE		HTCapability;
-
-#ifdef DOT11N_DRAFT3
-	UCHAR		BSS2040CoexistenceMgmtSupport;
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-	BOOLEAN		bAutoTxRateSwitch;
-
-	UCHAR       RateLen;
-	struct _MAC_TABLE_ENTRY *pNext;
-    USHORT      TxSeq[NUM_OF_TID];
-	USHORT		NonQosDataSeq;
-
-	RSSI_SAMPLE	RssiSample;
-
-	UINT32			TXMCSExpected[16];
-	UINT32			TXMCSSuccessful[16];
-	UINT32			TXMCSFailed[16];
-	UINT32			TXMCSAutoFallBack[16][16];
-
-#ifdef CONFIG_STA_SUPPORT
-        ULONG                   LastBeaconRxTime;
-#endif // CONFIG_STA_SUPPORT //
-} MAC_TABLE_ENTRY, *PMAC_TABLE_ENTRY;
-
-typedef struct _MAC_TABLE {
-	USHORT			Size;
-	MAC_TABLE_ENTRY *Hash[HASH_TABLE_SIZE];
-	MAC_TABLE_ENTRY Content[MAX_LEN_OF_MAC_TABLE];
-	QUEUE_HEADER    McastPsQueue;
-	ULONG           PsQIdleCount;
-	BOOLEAN         fAnyStationInPsm;
-	BOOLEAN         fAnyStationBadAtheros;	// Check if any Station is atheros 802.11n Chip.  We need to use RTS/CTS with Atheros 802,.11n chip.
-	BOOLEAN			fAnyTxOPForceDisable;	// Check if it is necessary to disable BE TxOP
-	BOOLEAN			fAllStationAsRalink; 	// Check if all stations are ralink-chipset
-#ifdef DOT11_N_SUPPORT
-	BOOLEAN         fAnyStationIsLegacy;	// Check if I use legacy rate to transmit to my BSS Station/
-	BOOLEAN         fAnyStationNonGF;		// Check if any Station can't support GF.
-	BOOLEAN         fAnyStation20Only;		// Check if any Station can't support GF.
-	BOOLEAN			fAnyStationMIMOPSDynamic; // Check if any Station is MIMO Dynamic
-	BOOLEAN         fAnyBASession;   // Check if there is BA session.  Force turn on RTS/CTS
-#endif // DOT11_N_SUPPORT //
-} MAC_TABLE, *PMAC_TABLE;
-
-#ifdef DOT11_N_SUPPORT
-#define IS_HT_STA(_pMacEntry)	\
-	(_pMacEntry->MaxHTPhyMode.field.MODE >= MODE_HTMIX)
-
-#define IS_HT_RATE(_pMacEntry)	\
-	(_pMacEntry->HTPhyMode.field.MODE >= MODE_HTMIX)
-
-#define PEER_IS_HT_RATE(_pMacEntry)	\
-	(_pMacEntry->HTPhyMode.field.MODE >= MODE_HTMIX)
-#endif // DOT11_N_SUPPORT //
-
-typedef struct _WDS_ENTRY {
-	BOOLEAN         Valid;
-	UCHAR           Addr[MAC_ADDR_LEN];
-	ULONG           NoDataIdleCount;
-	struct _WDS_ENTRY *pNext;
-} WDS_ENTRY, *PWDS_ENTRY;
-
-typedef struct  _WDS_TABLE_ENTRY {
-	USHORT			Size;
-	UCHAR           WdsAddr[MAC_ADDR_LEN];
-	WDS_ENTRY       *Hash[HASH_TABLE_SIZE];
-	WDS_ENTRY       Content[MAX_LEN_OF_MAC_TABLE];
-	UCHAR           MaxSupportedRate;
-	UCHAR           CurrTxRate;
-	USHORT          TxQuality[MAX_LEN_OF_SUPPORTED_RATES];
-	USHORT          OneSecTxOkCount;
-	USHORT          OneSecTxRetryOkCount;
-	USHORT          OneSecTxFailCount;
-	ULONG           CurrTxRateStableTime; // # of second in current TX rate
-	UCHAR           TxRateUpPenalty;      // extra # of second penalty due to last unstable condition
-} WDS_TABLE_ENTRY, *PWDS_TABLE_ENTRY;
-
-typedef struct _RT_802_11_WDS_ENTRY {
-	PNET_DEV			dev;
-	UCHAR				Valid;
-	UCHAR				PhyMode;
-	UCHAR				PeerWdsAddr[MAC_ADDR_LEN];
-	UCHAR				MacTabMatchWCID;	// ASIC
-	NDIS_802_11_WEP_STATUS  WepStatus;
-	UCHAR					KeyIdx;
-	CIPHER_KEY          	WdsKey;
-	HTTRANSMIT_SETTING				HTPhyMode, MaxHTPhyMode, MinHTPhyMode;
-	RT_HT_PHY_INFO					DesiredHtPhyInfo;
-	BOOLEAN							bAutoTxRateSwitch;
-	DESIRED_TRANSMIT_SETTING       	DesiredTransmitSetting; // Desired transmit setting.
-} RT_802_11_WDS_ENTRY, *PRT_802_11_WDS_ENTRY;
-
-typedef struct _WDS_TABLE {
-	UCHAR               Mode;
-	ULONG               Size;
-	RT_802_11_WDS_ENTRY	WdsEntry[MAX_WDS_ENTRY];
-} WDS_TABLE, *PWDS_TABLE;
-
-typedef struct _APCLI_STRUCT {
-	PNET_DEV				dev;
-#ifdef RTL865X_SOC
-	unsigned int            mylinkid;
-#endif
-	BOOLEAN                 Enable;	// Set it as 1 if the apcli interface was configured to "1"  or by iwpriv cmd "ApCliEnable"
-	BOOLEAN                 Valid;	// Set it as 1 if the apcli interface associated success to remote AP.
-	UCHAR					MacTabWCID;	//WCID value, which point to the entry of ASIC Mac table.
-	UCHAR                   SsidLen;
-	CHAR                    Ssid[MAX_LEN_OF_SSID];
-
-	UCHAR                   CfgSsidLen;
-	CHAR                    CfgSsid[MAX_LEN_OF_SSID];
-	UCHAR                   CfgApCliBssid[ETH_LENGTH_OF_ADDRESS];
-	UCHAR                   CurrentAddress[ETH_LENGTH_OF_ADDRESS];
-
-	ULONG                   ApCliRcvBeaconTime;
-
-	ULONG                   CtrlCurrState;
-	ULONG                   SyncCurrState;
-	ULONG                   AuthCurrState;
-	ULONG                   AssocCurrState;
-	ULONG					WpaPskCurrState;
-
-	USHORT                  AuthReqCnt;
-	USHORT                  AssocReqCnt;
-
-	ULONG                   ClientStatusFlags;
-	UCHAR                   MpduDensity;
-
-	NDIS_802_11_AUTHENTICATION_MODE     AuthMode;   // This should match to whatever microsoft defined
-	NDIS_802_11_WEP_STATUS              WepStatus;
-
-	// Add to support different cipher suite for WPA2/WPA mode
-	NDIS_802_11_ENCRYPTION_STATUS		GroupCipher;		// Multicast cipher suite
-	NDIS_802_11_ENCRYPTION_STATUS		PairCipher;			// Unicast cipher suite
-	BOOLEAN								bMixCipher;			// Indicate current Pair & Group use different cipher suites
-	USHORT								RsnCapability;
-
-	UCHAR		PSK[100];				// reserve PSK key material
-	UCHAR       PSKLen;
-	UCHAR       PMK[32];                // WPA PSK mode PMK
-	//UCHAR       PTK[64];                // WPA PSK mode PTK
-	UCHAR		GTK[32];				// GTK from authenticator
-
-	//CIPHER_KEY		PairwiseKey;
-	CIPHER_KEY      SharedKey[SHARE_KEY_NUM];
-	UCHAR           DefaultKeyId;
-
-	// WPA 802.1x port control, WPA_802_1X_PORT_SECURED, WPA_802_1X_PORT_NOT_SECURED
-	//UCHAR       PortSecured;
-
-	// store RSN_IE built by driver
-	UCHAR		RSN_IE[MAX_LEN_OF_RSNIE];  // The content saved here should be convert to little-endian format.
-	UCHAR		RSNIE_Len;
-
-	// For WPA countermeasures
-	ULONG       LastMicErrorTime;   // record last MIC error time
-	//ULONG       MicErrCnt;          // Should be 0, 1, 2, then reset to zero (after disassoiciation).
-	BOOLEAN                 bBlockAssoc; // Block associate attempt for 60 seconds after counter measure occurred.
-
-	// For WPA-PSK supplicant state
-	//WPA_STATE   	WpaState;           // Default is SS_NOTUSE
-	//UCHAR       	ReplayCounter[8];
-	//UCHAR       	ANonce[32];         // ANonce for WPA-PSK from authenticator
-	UCHAR       	SNonce[32];         // SNonce for WPA-PSK
-	UCHAR			GNonce[32];			// GNonce for WPA-PSK from authenticator
-
-	HTTRANSMIT_SETTING				HTPhyMode, MaxHTPhyMode, MinHTPhyMode;
-	RT_HT_PHY_INFO					DesiredHtPhyInfo;
-	BOOLEAN							bAutoTxRateSwitch;
-	DESIRED_TRANSMIT_SETTING       	DesiredTransmitSetting; // Desired transmit setting.
-} APCLI_STRUCT, *PAPCLI_STRUCT;
-
-// ----------- end of AP ----------------------------
-
-#ifdef BLOCK_NET_IF
-typedef struct _BLOCK_QUEUE_ENTRY
-{
-	BOOLEAN SwTxQueueBlockFlag;
-	LIST_HEADER NetIfList;
-} BLOCK_QUEUE_ENTRY, *PBLOCK_QUEUE_ENTRY;
-#endif // BLOCK_NET_IF //
-
-
-struct wificonf
-{
-	BOOLEAN	bShortGI;
-	BOOLEAN bGreenField;
-};
-
-
-
-
-typedef struct _INF_PCI_CONFIG
-{
-	PUCHAR                  CSRBaseAddress;     // PCI MMIO Base Address, all access will use
-}INF_PCI_CONFIG;
-
-typedef struct _INF_USB_CONFIG
-{
-	UINT                BulkInEpAddr;		// bulk-in endpoint address
-	UINT                BulkOutEpAddr[6];	// bulk-out endpoint address
-
-}INF_USB_CONFIG;
-
-#ifdef IKANOS_VX_1X0
-	typedef void (*IkanosWlanTxCbFuncP)(void *, void *);
-
-	struct IKANOS_TX_INFO
-	{
-		struct net_device *netdev;
-		IkanosWlanTxCbFuncP *fp;
-	};
-#endif // IKANOS_VX_1X0 //
-
-#ifdef NINTENDO_AP
-typedef struct _NINDO_CTRL_BLOCK {
-
-	RT_NINTENDO_TABLE	DS_TABLE;
-
-#ifdef CHIP25XX
-	spinlock_t			NINTENDO_TABLE_Lock;
-#else
-	NDIS_SPIN_LOCK		NINTENDO_TABLE_Lock;
-#endif // CHIP25XX //
-
-	UCHAR				NINTENDO_UP_BUFFER[512];
-	UCHAR				Local_KeyIdx;
-	CIPHER_KEY			Local_SharedKey;
-	UCHAR				Local_bHideSsid;
-	UCHAR				Local_AuthMode;
-	UCHAR				Local_WepStatus;
-	USHORT				Local_CapabilityInfo;
-} NINDO_CTRL_BLOCK;
-#endif // NINTENDO_AP //
-
-
-#ifdef DBG_DIAGNOSE
-#define DIAGNOSE_TIME	10   // 10 sec
-typedef struct _RtmpDiagStrcut_
-{	// Diagnosis Related element
-	unsigned char		inited;
-	unsigned char 	qIdx;
-	unsigned char 	ArrayStartIdx;
-	unsigned char		ArrayCurIdx;
-	// Tx Related Count
-	USHORT			TxDataCnt[DIAGNOSE_TIME];
-	USHORT			TxFailCnt[DIAGNOSE_TIME];
-//	USHORT			TxDescCnt[DIAGNOSE_TIME][16];		// TxDesc queue length in scale of 0~14, >=15
-	USHORT			TxDescCnt[DIAGNOSE_TIME][24]; // 3*3	// TxDesc queue length in scale of 0~14, >=15
-//	USHORT			TxMcsCnt[DIAGNOSE_TIME][16];			// TxDate MCS Count in range from 0 to 15, step in 1.
-	USHORT			TxMcsCnt[DIAGNOSE_TIME][24]; // 3*3
-	USHORT			TxSWQueCnt[DIAGNOSE_TIME][9];		// TxSwQueue length in scale of 0, 1, 2, 3, 4, 5, 6, 7, >=8
-
-	USHORT			TxAggCnt[DIAGNOSE_TIME];
-	USHORT			TxNonAggCnt[DIAGNOSE_TIME];
-//	USHORT			TxAMPDUCnt[DIAGNOSE_TIME][16];		// 10 sec, TxDMA APMDU Aggregation count in range from 0 to 15, in setp of 1.
-	USHORT			TxAMPDUCnt[DIAGNOSE_TIME][24]; // 3*3 // 10 sec, TxDMA APMDU Aggregation count in range from 0 to 15, in setp of 1.
-	USHORT			TxRalinkCnt[DIAGNOSE_TIME];			// TxRalink Aggregation Count in 1 sec scale.
-	USHORT			TxAMSDUCnt[DIAGNOSE_TIME];			// TxAMSUD Aggregation Count in 1 sec scale.
-
-	// Rx Related Count
-	USHORT			RxDataCnt[DIAGNOSE_TIME];			// Rx Total Data count.
-	USHORT			RxCrcErrCnt[DIAGNOSE_TIME];
-//	USHORT			RxMcsCnt[DIAGNOSE_TIME][16];		// Rx MCS Count in range from 0 to 15, step in 1.
-	USHORT			RxMcsCnt[DIAGNOSE_TIME][24]; // 3*3
-}RtmpDiagStruct;
-#endif // DBG_DIAGNOSE //
-
-
-//
-//  The miniport adapter structure
-//
-typedef struct _RTMP_ADAPTER
-{
-	PVOID					OS_Cookie;	// save specific structure relative to OS
-	PNET_DEV				net_dev;
-	ULONG					VirtualIfCnt;
-
-
-
-	NDIS_SPIN_LOCK          irq_lock;
-	UCHAR                   irq_disabled;
-
-#ifdef RT2870
-/*****************************************************************************************/
-/*      USB related parameters                                                           */
-/*****************************************************************************************/
-	struct usb_config_descriptor		*config;
-	UINT								BulkInEpAddr;		// bulk-in endpoint address
-	UINT								BulkOutEpAddr[6];	// bulk-out endpoint address
-
-	UINT								NumberOfPipes;
-	USHORT								BulkOutMaxPacketSize;
-	USHORT								BulkInMaxPacketSize;
-
-	//======Control Flags
-	LONG                    	PendingIoCount;
-	ULONG						BulkFlags;
-	BOOLEAN                     bUsbTxBulkAggre;	// Flags for bulk out data priority
-
-
-	//======Timer Thread
-	RT2870_TIMER_QUEUE		TimerQ;
-	NDIS_SPIN_LOCK			TimerQLock;
-
-
-	//======Cmd Thread
-	CmdQ					CmdQ;
-	NDIS_SPIN_LOCK			CmdQLock;				// CmdQLock spinlock
-
-	BOOLEAN					TimerFunc_kill;
-	BOOLEAN					mlme_kill;
-
-
-	//======Semaphores (event)
-	struct semaphore			mlme_semaphore;			/* to sleep thread on	*/
-	struct semaphore			RTUSBCmd_semaphore;		/* to sleep thread on	*/
-	struct semaphore			RTUSBTimer_semaphore;
-#ifdef INF_AMAZON_SE
-	struct semaphore			UsbVendorReq_semaphore;
-	PVOID						UsbVendorReqBuf;
-#endif // INF_AMAZON_SE //
-	struct completion			TimerQComplete;
-	struct completion			mlmeComplete;
-	struct completion			CmdQComplete;
-	wait_queue_head_t			*wait;
-
-	//======Lock for 2870 ATE
-#ifdef RALINK_ATE
-	NDIS_SPIN_LOCK			GenericLock;		// ATE Tx/Rx generic spinlock
-#endif // RALINK_ATE //
-
-#endif // RT2870 //
-
-
-/*****************************************************************************************/
-	/*      Both PCI/USB related parameters                                                  */
-/*****************************************************************************************/
-
-
-/*****************************************************************************************/
-/*      Tx related parameters                                                           */
-/*****************************************************************************************/
-	BOOLEAN                 DeQueueRunning[NUM_OF_TX_RING];  // for ensuring RTUSBDeQueuePacket get call once
-	NDIS_SPIN_LOCK          DeQueueLock[NUM_OF_TX_RING];
-
-#ifdef RT2870
-	// Data related context and AC specified, 4 AC supported
-	NDIS_SPIN_LOCK			BulkOutLock[6];			// BulkOut spinlock for 4 ACs
-	NDIS_SPIN_LOCK			MLMEBulkOutLock;	// MLME BulkOut lock
-
-	HT_TX_CONTEXT			TxContext[NUM_OF_TX_RING];
-	NDIS_SPIN_LOCK			TxContextQueueLock[NUM_OF_TX_RING];		// TxContextQueue spinlock
-
-	// 4 sets of Bulk Out index and pending flag
-	UCHAR					NextBulkOutIndex[4];	// only used for 4 EDCA bulkout pipe
-
-	BOOLEAN					BulkOutPending[6];	// used for total 6 bulkout pipe
-	UCHAR					bulkResetPipeid;
-	BOOLEAN					MgmtBulkPending;
-	ULONG					bulkResetReq[6];
-#endif // RT2870 //
-
-	// resource for software backlog queues
-	QUEUE_HEADER            TxSwQueue[NUM_OF_TX_RING];  // 4 AC + 1 HCCA
-	NDIS_SPIN_LOCK          TxSwQueueLock[NUM_OF_TX_RING];	// TxSwQueue spinlock
-
-	RTMP_DMABUF             MgmtDescRing;               	// Shared memory for MGMT descriptors
-	RTMP_MGMT_RING          MgmtRing;
-	NDIS_SPIN_LOCK          MgmtRingLock;               	// Prio Ring spinlock
-
-
-/*****************************************************************************************/
-/*      Rx related parameters                                                           */
-/*****************************************************************************************/
-
-
-#ifdef RT2870
-	RX_CONTEXT				RxContext[RX_RING_SIZE];  // 1 for redundant multiple IRP bulk in.
-	NDIS_SPIN_LOCK			BulkInLock;				// BulkIn spinlock for 4 ACs
-	UCHAR					PendingRx;				// The Maxima pending Rx value should be 	RX_RING_SIZE.
-	UCHAR					NextRxBulkInIndex;		// Indicate the current RxContext Index which hold by Host controller.
-	UCHAR					NextRxBulkInReadIndex;	// Indicate the current RxContext Index which driver can read & process it.
-	ULONG					NextRxBulkInPosition;   // Want to contatenate 2 URB buffer while 1st is bulkin failed URB. This Position is 1st URB TransferLength.
-	ULONG					TransferBufferLength;	// current length of the packet buffer
-	ULONG					ReadPosition;			// current read position in a packet buffer
-#endif // RT2870 //
-
-
-/*****************************************************************************************/
-/*      ASIC related parameters                                                          */
-/*****************************************************************************************/
-	UINT32               	MACVersion;      	// MAC version. Record rt2860C(0x28600100) or rt2860D (0x28600101)..
-
-	// ---------------------------
-	// E2PROM
-	// ---------------------------
-	ULONG                   EepromVersion;          // byte 0: version, byte 1: revision, byte 2~3: unused
-	UCHAR                   EEPROMAddressNum;       // 93c46=6  93c66=8
-	USHORT                  EEPROMDefaultValue[NUM_EEPROM_BBP_PARMS];
-	BOOLEAN                 EepromAccess;
-	UCHAR                   EFuseTag;
-	ULONG                   FirmwareVersion;        // byte 0: Minor version, byte 1: Major version, otherwise unused.
-
-	// ---------------------------
-	// BBP Control
-	// ---------------------------
-	UCHAR                   BbpWriteLatch[140];     // record last BBP register value written via BBP_IO_WRITE/BBP_IO_WRITE_VY_REG_ID
-	UCHAR                   BbpRssiToDbmDelta;
-	BBP_R66_TUNING          BbpTuning;
-
-	// ----------------------------
-	// RFIC control
-	// ----------------------------
-	UCHAR                   RfIcType;       // RFIC_xxx
-	ULONG                   RfFreqOffset;   // Frequency offset for channel switching
-	RTMP_RF_REGS            LatchRfRegs;    // latch th latest RF programming value since RF IC doesn't support READ
-
-	EEPROM_ANTENNA_STRUC    Antenna;                            // Since ANtenna definition is different for a & g. We need to save it for future reference.
-	EEPROM_NIC_CONFIG2_STRUC    NicConfig2;
-
-	// This soft Rx Antenna Diversity mechanism is used only when user set
-	// RX Antenna = DIVERSITY ON
-	SOFT_RX_ANT_DIVERSITY   RxAnt;
-
-	UCHAR                   RFProgSeq;
-	CHANNEL_TX_POWER        TxPower[MAX_NUM_OF_CHANNELS];       // Store Tx power value for all channels.
-	CHANNEL_TX_POWER        ChannelList[MAX_NUM_OF_CHANNELS];   // list all supported channels for site survey
-	CHANNEL_11J_TX_POWER    TxPower11J[MAX_NUM_OF_11JCHANNELS];       // 802.11j channel and bw
-	CHANNEL_11J_TX_POWER    ChannelList11J[MAX_NUM_OF_11JCHANNELS];   // list all supported channels for site survey
-
-	UCHAR                   ChannelListNum;                     // number of channel in ChannelList[]
-	UCHAR					Bbp94;
-	BOOLEAN					BbpForCCK;
-	ULONG		Tx20MPwrCfgABand[5];
-	ULONG		Tx20MPwrCfgGBand[5];
-	ULONG		Tx40MPwrCfgABand[5];
-	ULONG		Tx40MPwrCfgGBand[5];
-
-	BOOLEAN     bAutoTxAgcA;                // Enable driver auto Tx Agc control
-	UCHAR	    TssiRefA;					// Store Tssi reference value as 25 temperature.
-	UCHAR	    TssiPlusBoundaryA[5];		// Tssi boundary for increase Tx power to compensate.
-	UCHAR	    TssiMinusBoundaryA[5];		// Tssi boundary for decrease Tx power to compensate.
-	UCHAR	    TxAgcStepA;					// Store Tx TSSI delta increment / decrement value
-	CHAR		TxAgcCompensateA;			// Store the compensation (TxAgcStep * (idx-1))
-
-	BOOLEAN     bAutoTxAgcG;                // Enable driver auto Tx Agc control
-	UCHAR	    TssiRefG;					// Store Tssi reference value as 25 temperature.
-	UCHAR	    TssiPlusBoundaryG[5];		// Tssi boundary for increase Tx power to compensate.
-	UCHAR	    TssiMinusBoundaryG[5];		// Tssi boundary for decrease Tx power to compensate.
-	UCHAR	    TxAgcStepG;					// Store Tx TSSI delta increment / decrement value
-	CHAR		TxAgcCompensateG;			// Store the compensation (TxAgcStep * (idx-1))
-
-	//+++For RT2870, the parameteres is start from BGRssiOffset1 ~ BGRssiOffset3
-	CHAR		BGRssiOffset0;				// Store B/G RSSI#0 Offset value on EEPROM 0x46h
-	CHAR		BGRssiOffset1;				// Store B/G RSSI#1 Offset value
-	CHAR		BGRssiOffset2;				// Store B/G RSSI#2 Offset value
-	//---
-
-	//+++For RT2870, the parameteres is start from ARssiOffset1 ~ ARssiOffset3
-	CHAR		ARssiOffset0;				// Store A RSSI#0 Offset value on EEPROM 0x4Ah
-	CHAR		ARssiOffset1;				// Store A RSSI#1 Offset value
-	CHAR		ARssiOffset2;				// Store A RSSI#2 Offset value
-	//---
-
-	CHAR		BLNAGain;					// Store B/G external LNA#0 value on EEPROM 0x44h
-	CHAR		ALNAGain0;					// Store A external LNA#0 value for ch36~64
-	CHAR		ALNAGain1;					// Store A external LNA#1 value for ch100~128
-	CHAR		ALNAGain2;					// Store A external LNA#2 value for ch132~165
-
-	// ----------------------------
-	// LED control
-	// ----------------------------
-	MCU_LEDCS_STRUC		LedCntl;
-	USHORT				Led1;	// read from EEPROM 0x3c
-	USHORT				Led2;	// EEPROM 0x3e
-	USHORT				Led3;	// EEPROM 0x40
-	UCHAR				LedIndicatorStregth;
-	UCHAR				RssiSingalstrengthOffet;
-    BOOLEAN				bLedOnScanning;
-	UCHAR				LedStatus;
-
-/*****************************************************************************************/
-/*      802.11 related parameters                                                        */
-/*****************************************************************************************/
-	// outgoing BEACON frame buffer and corresponding TXD
-	TXWI_STRUC              	BeaconTxWI;
-	PUCHAR						BeaconBuf;
-	USHORT						BeaconOffset[HW_BEACON_MAX_COUNT];
-
-	// pre-build PS-POLL and NULL frame upon link up. for efficiency purpose.
-	PSPOLL_FRAME            	PsPollFrame;
-	HEADER_802_11           	NullFrame;
-
-#ifdef RT2870
-	TX_CONTEXT				BeaconContext[BEACON_RING_SIZE];
-	TX_CONTEXT				NullContext;
-	TX_CONTEXT				PsPollContext;
-	TX_CONTEXT				RTSContext;
-#endif // RT2870 //
-
-
-
-//=========AP===========
-
-
-//=======STA===========
-#ifdef CONFIG_STA_SUPPORT
-/* Modified by Wu Xi-Kun 4/21/2006 */
-	// -----------------------------------------------
-	// STA specific configuration & operation status
-	// used only when pAd->OpMode == OPMODE_STA
-	// -----------------------------------------------
-	STA_ADMIN_CONFIG        StaCfg;           // user desired settings
-	STA_ACTIVE_CONFIG       StaActive;         // valid only when ADHOC_ON(pAd) || INFRA_ON(pAd)
-	CHAR                    nickname[IW_ESSID_MAX_SIZE+1]; // nickname, only used in the iwconfig i/f
-	NDIS_MEDIA_STATE        PreMediaState;
-#endif // CONFIG_STA_SUPPORT //
-
-//=======Common===========
-	// OP mode: either AP or STA
-	UCHAR                   OpMode;                     // OPMODE_STA, OPMODE_AP
-
-	NDIS_MEDIA_STATE        IndicateMediaState;			// Base on Indication state, default is NdisMediaStateDisConnected
-
-
-	// MAT related parameters
-
-	// configuration: read from Registry & E2PROM
-	BOOLEAN                 bLocalAdminMAC;             // Use user changed MAC
-	UCHAR                   PermanentAddress[MAC_ADDR_LEN];    // Factory default MAC address
-	UCHAR                   CurrentAddress[MAC_ADDR_LEN];      // User changed MAC address
-
-	// ------------------------------------------------------
-	// common configuration to both OPMODE_STA and OPMODE_AP
-	// ------------------------------------------------------
-	COMMON_CONFIG           CommonCfg;
-	MLME_STRUCT             Mlme;
-
-	// AP needs those vaiables for site survey feature.
-	MLME_AUX                MlmeAux;           // temporary settings used during MLME state machine
-	BSS_TABLE               ScanTab;           // store the latest SCAN result
-
-	//About MacTab, the sta driver will use #0 and #1 for multicast and AP.
-	MAC_TABLE                 MacTab;     // ASIC on-chip WCID entry table.  At TX, ASIC always use key according to this on-chip table.
-	NDIS_SPIN_LOCK          MacTabLock;
-
-#ifdef DOT11_N_SUPPORT
-	BA_TABLE			BATable;
-#endif // DOT11_N_SUPPORT //
-	NDIS_SPIN_LOCK          BATabLock;
-	RALINK_TIMER_STRUCT RECBATimer;
-
-	// encryption/decryption KEY tables
-	CIPHER_KEY              SharedKey[MAX_MBSSID_NUM][4]; // STA always use SharedKey[BSS0][0..3]
-
-		// RX re-assembly buffer for fragmentation
-	FRAGMENT_FRAME          FragFrame;                  // Frame storage for fragment frame
-
-	// various Counters
-	COUNTER_802_3           Counters8023;               // 802.3 counters
-	COUNTER_802_11          WlanCounters;               // 802.11 MIB counters
-	COUNTER_RALINK          RalinkCounters;             // Ralink propriety counters
-	COUNTER_DRS             DrsCounters;                // counters for Dynamic TX Rate Switching
-	PRIVATE_STRUC           PrivateInfo;                // Private information & counters
-
-	// flags, see fRTMP_ADAPTER_xxx flags
-	ULONG                   Flags;                      // Represent current device status
-
-	// current TX sequence #
-	USHORT                  Sequence;
-
-#ifdef UNDER_CE
-	NDIS_HANDLE             hGiISR;
-#endif
-
-
-	// Control disconnect / connect event generation
-	//+++Didn't used anymore
-	ULONG                   LinkDownTime;
-	//---
-	ULONG                   LastRxRate;
-	ULONG                   LastTxRate;
-	//+++Used only for Station
-	BOOLEAN                 bConfigChanged;         // Config Change flag for the same SSID setting
-	//---
-
-	ULONG                   ExtraInfo;              // Extra information for displaying status
-	ULONG                   SystemErrorBitmap;      // b0: E2PROM version error
-
-	//+++Didn't used anymore
-	ULONG                   MacIcVersion;           // MAC/BBP serial interface issue solved after ver.D
-	//---
-
-	// ---------------------------
-	// System event log
-	// ---------------------------
-	RT_802_11_EVENT_TABLE   EventTab;
-
-
-	BOOLEAN		HTCEnable;
-
-	/*****************************************************************************************/
-	/*      Statistic related parameters                                                     */
-	/*****************************************************************************************/
-#ifdef RT2870
-	ULONG						BulkOutDataOneSecCount;
-	ULONG						BulkInDataOneSecCount;
-	ULONG						BulkLastOneSecCount; // BulkOutDataOneSecCount + BulkInDataOneSecCount
-	ULONG						watchDogRxCnt;
-	ULONG						watchDogRxOverFlowCnt;
-	ULONG						watchDogTxPendingCnt[NUM_OF_TX_RING];
-#endif // RT2870 //
-
-	BOOLEAN						bUpdateBcnCntDone;
-	ULONG						watchDogMacDeadlock;	// prevent MAC/BBP into deadlock condition
-	// ----------------------------
-	// DEBUG paramerts
-	// ----------------------------
-	//ULONG		DebugSetting[4];
-	BOOLEAN		bBanAllBaSetup;
-	BOOLEAN		bPromiscuous;
-
-	// ----------------------------
-	// rt2860c emulation-use Parameters
-	// ----------------------------
-	ULONG		rtsaccu[30];
-	ULONG		ctsaccu[30];
-	ULONG		cfendaccu[30];
-	ULONG		bacontent[16];
-	ULONG		rxint[RX_RING_SIZE+1];
-	UCHAR		rcvba[60];
-	BOOLEAN		bLinkAdapt;
-	BOOLEAN		bForcePrintTX;
-	BOOLEAN		bForcePrintRX;
-	BOOLEAN		bDisablescanning;		//defined in RT2870 USB
-	BOOLEAN		bStaFifoTest;
-	BOOLEAN		bProtectionTest;
-	BOOLEAN		bHCCATest;
-	BOOLEAN		bGenOneHCCA;
-	BOOLEAN		bBroadComHT;
-	//+++Following add from RT2870 USB.
-	ULONG		BulkOutReq;
-	ULONG		BulkOutComplete;
-	ULONG		BulkOutCompleteOther;
-	ULONG		BulkOutCompleteCancel;	// seems not use now?
-	ULONG		BulkInReq;
-	ULONG		BulkInComplete;
-	ULONG		BulkInCompleteFail;
-	//---
-
-    struct wificonf			WIFItestbed;
-
-#ifdef RALINK_ATE
-	ATE_INFO				ate;
-#ifdef RT2870
-	BOOLEAN					ContinBulkOut;		//ATE bulk out control
-	BOOLEAN					ContinBulkIn;		//ATE bulk in control
-	atomic_t				BulkOutRemained;
-	atomic_t				BulkInRemained;
-#endif // RT2870 //
-#endif // RALINK_ATE //
-
-#ifdef DOT11_N_SUPPORT
-	struct reordering_mpdu_pool mpdu_blk_pool;
-#endif // DOT11_N_SUPPORT //
-
-	ULONG					OneSecondnonBEpackets;		// record non BE packets per second
-
-#if WIRELESS_EXT >= 12
-    struct iw_statistics    iw_stats;
-#endif
-
-	struct net_device_stats	stats;
-
-#ifdef BLOCK_NET_IF
-	BLOCK_QUEUE_ENTRY		blockQueueTab[NUM_OF_TX_RING];
-#endif // BLOCK_NET_IF //
-
-
-
-#ifdef MULTIPLE_CARD_SUPPORT
-	INT32					MC_RowID;
-	UCHAR					MC_FileName[256];
-#endif // MULTIPLE_CARD_SUPPORT //
-
-	ULONG					TbttTickCount;
-#ifdef PCI_MSI_SUPPORT
-	BOOLEAN					HaveMsi;
-#endif // PCI_MSI_SUPPORT //
-
-
-	UCHAR					is_on;
-
-#define TIME_BASE			(1000000/OS_HZ)
-#define TIME_ONE_SECOND		(1000000/TIME_BASE)
-	UCHAR					flg_be_adjust;
-	ULONG					be_adjust_last_time;
-
-#ifdef NINTENDO_AP
-	NINDO_CTRL_BLOCK		nindo_ctrl_block;
-#endif // NINTENDO_AP //
-
-
-#ifdef IKANOS_VX_1X0
-	struct IKANOS_TX_INFO	IkanosTxInfo;
-	struct IKANOS_TX_INFO	IkanosRxInfo[MAX_MBSSID_NUM + MAX_WDS_ENTRY + MAX_APCLI_NUM + MAX_MESH_NUM];
-#endif // IKANOS_VX_1X0 //
-
-
-#ifdef DBG_DIAGNOSE
-	RtmpDiagStruct	DiagStruct;
-#endif // DBG_DIAGNOSE //
-
-
-	UINT8					PM_FlgSuspend;
-
-#ifdef RT30xx
-//======efuse
-	BOOLEAN		bUseEfuse;
-	BOOLEAN		bEEPROMFile;
-#endif // RT30xx //
-
-} RTMP_ADAPTER, *PRTMP_ADAPTER;
-
-//
-// Cisco IAPP format
-//
-typedef struct  _CISCO_IAPP_CONTENT_
-{
-	USHORT     Length;        //IAPP Length
-	UCHAR      MessageType;      //IAPP type
-	UCHAR      FunctionCode;     //IAPP function type
-	UCHAR      DestinaionMAC[MAC_ADDR_LEN];
-	UCHAR      SourceMAC[MAC_ADDR_LEN];
-	USHORT     Tag;           //Tag(element IE) - Adjacent AP report
-	USHORT     TagLength;     //Length of element not including 4 byte header
-	UCHAR      OUI[4];           //0x00, 0x40, 0x96, 0x00
-	UCHAR      PreviousAP[MAC_ADDR_LEN];       //MAC Address of access point
-	USHORT     Channel;
-	USHORT     SsidLen;
-	UCHAR      Ssid[MAX_LEN_OF_SSID];
-	USHORT     Seconds;          //Seconds that the client has been disassociated.
-} CISCO_IAPP_CONTENT, *PCISCO_IAPP_CONTENT;
-
-#define DELAYINTMASK		0x0003fffb
-#define INTMASK				0x0003fffb
-#define IndMask				0x0003fffc
-#define RxINT				0x00000005	// Delayed Rx or indivi rx
-#define TxDataInt			0x000000fa	// Delayed Tx or indivi tx
-#define TxMgmtInt			0x00000102	// Delayed Tx or indivi tx
-#define TxCoherent			0x00020000	// tx coherent
-#define RxCoherent			0x00010000	// rx coherent
-#define McuCommand			0x00000200	// mcu
-#define PreTBTTInt			0x00001000	// Pre-TBTT interrupt
-#define TBTTInt				0x00000800		// TBTT interrupt
-#define GPTimeOutInt			0x00008000		// GPtimeout interrupt
-#define AutoWakeupInt		0x00004000		// AutoWakeupInt interrupt
-#define FifoStaFullInt			0x00002000	//  fifo statistics full interrupt
-
-
-typedef struct _RX_BLK_
-{
-//	RXD_STRUC		RxD; // sample
-	RT28XX_RXD_STRUC	RxD;
-	PRXWI_STRUC			pRxWI;
-	PHEADER_802_11		pHeader;
-	PNDIS_PACKET		pRxPacket;
-	UCHAR				*pData;
-	USHORT				DataSize;
-	USHORT				Flags;
-	UCHAR				UserPriority;	// for calculate TKIP MIC using
-} RX_BLK;
-
-
-#define RX_BLK_SET_FLAG(_pRxBlk, _flag)		(_pRxBlk->Flags |= _flag)
-#define RX_BLK_TEST_FLAG(_pRxBlk, _flag)	(_pRxBlk->Flags & _flag)
-#define RX_BLK_CLEAR_FLAG(_pRxBlk, _flag)	(_pRxBlk->Flags &= ~(_flag))
-
-
-#define fRX_WDS			0x0001
-#define fRX_AMSDU       0x0002
-#define fRX_ARALINK     0x0004
-#define fRX_HTC         0x0008
-#define fRX_PAD         0x0010
-#define fRX_AMPDU       0x0020
-#define fRX_QOS			0x0040
-#define fRX_INFRA		0x0080
-#define fRX_EAP			0x0100
-#define fRX_MESH		0x0200
-#define fRX_APCLI		0x0400
-#define fRX_DLS			0x0800
-#define fRX_WPI			0x1000
-
-#define LENGTH_AMSDU_SUBFRAMEHEAD	14
-#define LENGTH_ARALINK_SUBFRAMEHEAD	14
-#define LENGTH_ARALINK_HEADER_FIELD	 2
-
-#define TX_UNKOWN_FRAME			0x00
-#define TX_MCAST_FRAME			0x01
-#define TX_LEGACY_FRAME			0x02
-#define TX_AMPDU_FRAME			0x04
-#define TX_AMSDU_FRAME			0x08
-#define TX_RALINK_FRAME			0x10
-#define TX_FRAG_FRAME			0x20
-
-
-//	Currently the sizeof(TX_BLK) is 148 bytes.
-typedef struct _TX_BLK_
-{
-	UCHAR				QueIdx;
-	UCHAR				TxFrameType;				// Indicate the Transmission type of the all frames in one batch
-	UCHAR				TotalFrameNum;				// Total frame number want to send-out in one batch
-	USHORT				TotalFragNum;				// Total frame fragments required in one batch
-	USHORT				TotalFrameLen;				// Total length of all frames want to send-out in one batch
-
-	QUEUE_HEADER		TxPacketList;
-	MAC_TABLE_ENTRY		*pMacEntry;					// NULL: packet with 802.11 RA field is multicast/broadcast address
-	HTTRANSMIT_SETTING	*pTransmit;
-
-	// Following structure used for the characteristics of a specific packet.
-	PNDIS_PACKET		pPacket;
-	PUCHAR				pSrcBufHeader;				// Reference to the head of sk_buff->data
-	PUCHAR				pSrcBufData;				// Reference to the sk_buff->data, will changed depends on hanlding progresss
-	UINT				SrcBufLen;					// Length of packet payload which not including Layer 2 header
-	PUCHAR				pExtraLlcSnapEncap;			// NULL means no extra LLC/SNAP is required
-	UCHAR				HeaderBuf[80];				// TempBuffer for TX_INFO + TX_WI + 802.11 Header + padding + AMSDU SubHeader + LLC/SNAP
-	UCHAR				MpduHeaderLen;				// 802.11 header length NOT including the padding
-	UCHAR				HdrPadLen;					// recording Header Padding Length;
-	UCHAR				apidx;						// The interface associated to this packet
-	UCHAR				Wcid;						// The MAC entry associated to this packet
-	UCHAR				UserPriority;				// priority class of packet
-	UCHAR				FrameGap;					// what kind of IFS this packet use
-	UCHAR				MpduReqNum;					// number of fragments of this frame
-	UCHAR				TxRate;						// TODO: Obsoleted? Should change to MCS?
-	UCHAR				CipherAlg;					// cipher alogrithm
-	PCIPHER_KEY			pKey;
-
-
-
-	USHORT				Flags;						//See following definitions for detail.
-
-	//YOU SHOULD NOT TOUCH IT! Following parameters are used for hardware-depended layer.
-	ULONG				Priv;						// Hardware specific value saved in here.
-} TX_BLK, *PTX_BLK;
-
-
-#define fTX_bRtsRequired		0x0001	// Indicate if need send RTS frame for protection. Not used in RT2860/RT2870.
-#define fTX_bAckRequired       	0x0002	// the packet need ack response
-#define fTX_bPiggyBack     		0x0004	// Legacy device use Piggback or not
-#define fTX_bHTRate         	0x0008	// allow to use HT rate
-//#define fTX_bForceLowRate       0x0010	// force to use Low Rate
-#define fTX_bForceNonQoS       	0x0010	// force to transmit frame without WMM-QoS in HT mode
-#define fTX_bAllowFrag       	0x0020	// allow to fragment the packet, A-MPDU, A-MSDU, A-Ralink is not allowed to fragment
-#define fTX_bMoreData			0x0040	// there are more data packets in PowerSave Queue
-#define fTX_bWMM				0x0080	// QOS Data
-
-#define fTX_bClearEAPFrame		0x0100
-
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-#define TX_BLK_ASSIGN_FLAG(_pTxBlk, _flag, value)	\
-		do {										\
-			if (value) 								\
-				(_pTxBlk->Flags |= _flag) 			\
-			else 									\
-				(_pTxBlk->Flags &= ~(_flag))		\
-		}while(0)
-
-#define TX_BLK_SET_FLAG(_pTxBlk, _flag)		(_pTxBlk->Flags |= _flag)
-#define TX_BLK_TEST_FLAG(_pTxBlk, _flag)	(((_pTxBlk->Flags & _flag) == _flag) ? 1 : 0)
-#define TX_BLK_CLEAR_FLAG(_pTxBlk, _flag)	(_pTxBlk->Flags &= ~(_flag))
-
-
-
-
-
-//------------------------------------------------------------------------------------------
-
-
-
-#ifdef RT_BIG_ENDIAN
-static inline VOID	WriteBackToDescriptor(
-	IN  PUCHAR			Dest,
- 	IN	PUCHAR			Src,
-    IN  BOOLEAN			DoEncrypt,
-	IN  ULONG           DescriptorType)
-{
-	UINT32 *p1, *p2;
-
-	p1 = ((UINT32 *)Dest);
-	p2 = ((UINT32 *)Src);
-
-	*p1 = *p2;
-	*(p1+2) = *(p2+2);
-	*(p1+3) = *(p2+3);
-	*(p1+1) = *(p2+1); // Word 1; this must be written back last
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Endian conversion of Tx/Rx descriptor .
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pData			Pointer to Tx/Rx descriptor
-		DescriptorType	Direction of the frame
-
-	Return Value:
-		None
-
-	Note:
-		Call this function when read or update descriptor
-	========================================================================
-*/
-static inline VOID	RTMPWIEndianChange(
-	IN	PUCHAR			pData,
-	IN	ULONG			DescriptorType)
-{
-	int size;
-	int i;
-
-	size = ((DescriptorType == TYPE_TXWI) ? TXWI_SIZE : RXWI_SIZE);
-
-	if(DescriptorType == TYPE_TXWI)
-	{
-		*((UINT32 *)(pData)) = SWAP32(*((UINT32 *)(pData)));		// Byte 0~3
-		*((UINT32 *)(pData + 4)) = SWAP32(*((UINT32 *)(pData+4)));	// Byte 4~7
-	}
-	else
-	{
-		for(i=0; i < size/4 ; i++)
-			*(((UINT32 *)pData) +i) = SWAP32(*(((UINT32 *)pData)+i));
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Endian conversion of Tx/Rx descriptor .
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pData			Pointer to Tx/Rx descriptor
-		DescriptorType	Direction of the frame
-
-	Return Value:
-		None
-
-	Note:
-		Call this function when read or update descriptor
-	========================================================================
-*/
-
-#ifdef RT2870
-static inline VOID	RTMPDescriptorEndianChange(
-	IN	PUCHAR			pData,
-	IN	ULONG			DescriptorType)
-{
-	*((UINT32 *)(pData)) = SWAP32(*((UINT32 *)(pData)));
-}
-#endif // RT2870 //
-/*
-	========================================================================
-
-	Routine Description:
-		Endian conversion of all kinds of 802.11 frames .
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pData			Pointer to the 802.11 frame structure
-		Dir 			Direction of the frame
-		FromRxDoneInt	Caller is from RxDone interrupt
-
-	Return Value:
-		None
-
-	Note:
-		Call this function when read or update buffer data
-	========================================================================
-*/
-static inline VOID	RTMPFrameEndianChange(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pData,
-	IN	ULONG			Dir,
-	IN	BOOLEAN 		FromRxDoneInt)
-{
-	PHEADER_802_11 pFrame;
-	PUCHAR	pMacHdr;
-
-	// swab 16 bit fields - Frame Control field
-	if(Dir == DIR_READ)
-	{
-		*(USHORT *)pData = SWAP16(*(USHORT *)pData);
-	}
-
-	pFrame = (PHEADER_802_11) pData;
-	pMacHdr = (PUCHAR) pFrame;
-
-	// swab 16 bit fields - Duration/ID field
-	*(USHORT *)(pMacHdr + 2) = SWAP16(*(USHORT *)(pMacHdr + 2));
-
-	// swab 16 bit fields - Sequence Control field
-	*(USHORT *)(pMacHdr + 22) = SWAP16(*(USHORT *)(pMacHdr + 22));
-
-	if(pFrame->FC.Type == BTYPE_MGMT)
-	{
-		switch(pFrame->FC.SubType)
-		{
-			case SUBTYPE_ASSOC_REQ:
-			case SUBTYPE_REASSOC_REQ:
-				// swab 16 bit fields - CapabilityInfo field
-				pMacHdr += sizeof(HEADER_802_11);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - Listen Interval field
-				pMacHdr += 2;
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-
-			case SUBTYPE_ASSOC_RSP:
-			case SUBTYPE_REASSOC_RSP:
-				// swab 16 bit fields - CapabilityInfo field
-				pMacHdr += sizeof(HEADER_802_11);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - Status Code field
-				pMacHdr += 2;
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - AID field
-				pMacHdr += 2;
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-
-			case SUBTYPE_AUTH:
-				// If from APHandleRxDoneInterrupt routine, it is still a encrypt format.
-				// The convertion is delayed to RTMPHandleDecryptionDoneInterrupt.
-				if(!FromRxDoneInt && pFrame->FC.Wep == 1)
-					break;
-				else
-				{
-					// swab 16 bit fields - Auth Alg No. field
-					pMacHdr += sizeof(HEADER_802_11);
-					*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-					// swab 16 bit fields - Auth Seq No. field
-					pMacHdr += 2;
-					*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-					// swab 16 bit fields - Status Code field
-					pMacHdr += 2;
-					*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				}
-				break;
-
-			case SUBTYPE_BEACON:
-			case SUBTYPE_PROBE_RSP:
-				// swab 16 bit fields - BeaconInterval field
-				pMacHdr += (sizeof(HEADER_802_11) + TIMESTAMP_LEN);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-
-				// swab 16 bit fields - CapabilityInfo field
-				pMacHdr += sizeof(USHORT);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-
-			case SUBTYPE_DEAUTH:
-			case SUBTYPE_DISASSOC:
-				// swab 16 bit fields - Reason code field
-				pMacHdr += sizeof(HEADER_802_11);
-				*(USHORT *)pMacHdr = SWAP16(*(USHORT *)pMacHdr);
-				break;
-		}
-	}
-	else if( pFrame->FC.Type == BTYPE_DATA )
-	{
-	}
-	else if(pFrame->FC.Type == BTYPE_CNTL)
-	{
-		switch(pFrame->FC.SubType)
-		{
-			case SUBTYPE_BLOCK_ACK_REQ:
-				{
-					PFRAME_BA_REQ pBAReq = (PFRAME_BA_REQ)pFrame;
-					*(USHORT *)(&pBAReq->BARControl) = SWAP16(*(USHORT *)(&pBAReq->BARControl));
-					pBAReq->BAStartingSeq.word = SWAP16(pBAReq->BAStartingSeq.word);
-				}
-				break;
-			case SUBTYPE_BLOCK_ACK:
-				// For Block Ack packet, the HT_CONTROL field is in the same offset with Addr3
-				*(UINT32 *)(&pFrame->Addr3[0]) = SWAP32(*(UINT32 *)(&pFrame->Addr3[0]));
-				break;
-
-			case SUBTYPE_ACK:
-				//For ACK packet, the HT_CONTROL field is in the same offset with Addr2
-				*(UINT32 *)(&pFrame->Addr2[0])=	SWAP32(*(UINT32 *)(&pFrame->Addr2[0]));
-				break;
-		}
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("Invalid Frame Type!!!\n"));
-	}
-
-	// swab 16 bit fields - Frame Control
-	if(Dir == DIR_WRITE)
-	{
-		*(USHORT *)pData = SWAP16(*(USHORT *)pData);
-	}
-}
-#endif // RT_BIG_ENDIAN //
-
-
-static inline VOID ConvertMulticastIP2MAC(
-	IN PUCHAR pIpAddr,
-	IN PUCHAR *ppMacAddr,
-	IN UINT16 ProtoType)
-{
-	if (pIpAddr == NULL)
-		return;
-
-	if (ppMacAddr == NULL || *ppMacAddr == NULL)
-		return;
-
-	switch (ProtoType)
-	{
-		case ETH_P_IPV6:
-//			memset(*ppMacAddr, 0, ETH_LENGTH_OF_ADDRESS);
-			*(*ppMacAddr) = 0x33;
-			*(*ppMacAddr + 1) = 0x33;
-			*(*ppMacAddr + 2) = pIpAddr[12];
-			*(*ppMacAddr + 3) = pIpAddr[13];
-			*(*ppMacAddr + 4) = pIpAddr[14];
-			*(*ppMacAddr + 5) = pIpAddr[15];
-			break;
-
-		case ETH_P_IP:
-		default:
-//			memset(*ppMacAddr, 0, ETH_LENGTH_OF_ADDRESS);
-			*(*ppMacAddr) = 0x01;
-			*(*ppMacAddr + 1) = 0x00;
-			*(*ppMacAddr + 2) = 0x5e;
-			*(*ppMacAddr + 3) = pIpAddr[1] & 0x7f;
-			*(*ppMacAddr + 4) = pIpAddr[2];
-			*(*ppMacAddr + 5) = pIpAddr[3];
-			break;
-	}
-
-	return;
-}
-
-BOOLEAN RTMPCheckForHang(
-	IN  NDIS_HANDLE MiniportAdapterContext
-	);
-
-VOID  RTMPHalt(
-	IN  NDIS_HANDLE MiniportAdapterContext
-	);
-
-//
-//  Private routines in rtmp_init.c
-//
-NDIS_STATUS RTMPAllocAdapterBlock(
-	IN PVOID			handle,
-	OUT PRTMP_ADAPTER   *ppAdapter
-	);
-
-NDIS_STATUS RTMPAllocTxRxRingMemory(
-	IN  PRTMP_ADAPTER   pAd
-	);
-
-NDIS_STATUS RTMPFindAdapter(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  NDIS_HANDLE     WrapperConfigurationContext
-	);
-
-NDIS_STATUS	RTMPReadParametersHook(
-	IN	PRTMP_ADAPTER pAd
-	);
-
-VOID RTMPFreeAdapter(
-	IN  PRTMP_ADAPTER   pAd
-	);
-
-NDIS_STATUS NICReadRegParameters(
-	IN  PRTMP_ADAPTER       pAd,
-	IN  NDIS_HANDLE         WrapperConfigurationContext
-	);
-
-#ifdef RT30xx
-VOID NICInitRT30xxRFRegisters(
-	IN PRTMP_ADAPTER pAd);
-#endif // RT30xx //
-
-VOID NICReadEEPROMParameters(
-	IN  PRTMP_ADAPTER       pAd,
-	IN	PUCHAR				mac_addr);
-
-VOID NICInitAsicFromEEPROM(
-	IN  PRTMP_ADAPTER       pAd);
-
-VOID NICInitTxRxRingAndBacklogQueue(
-	IN  PRTMP_ADAPTER   pAd);
-
-NDIS_STATUS NICInitializeAdapter(
-	IN  PRTMP_ADAPTER   pAd,
-	IN   BOOLEAN    bHardReset);
-
-NDIS_STATUS NICInitializeAsic(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  BOOLEAN		bHardReset);
-
-VOID NICIssueReset(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPRingCleanUp(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           RingType);
-
-VOID RxTest(
-	IN  PRTMP_ADAPTER   pAd);
-
-NDIS_STATUS DbgSendPacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PNDIS_PACKET    pPacket);
-
-VOID UserCfgInit(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID NICResetFromError(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID NICEraseFirmware(
-	IN PRTMP_ADAPTER pAd);
-
-NDIS_STATUS NICLoadFirmware(
-	IN  PRTMP_ADAPTER   pAd);
-
-NDIS_STATUS NICLoadRateSwitchingParams(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN NICCheckForHang(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID NICUpdateFifoStaCounters(
-	IN PRTMP_ADAPTER pAd);
-
-VOID NICUpdateRawCounters(
-	IN  PRTMP_ADAPTER   pAd);
-
-ULONG	RTMPNotAllZero(
-	IN	PVOID	pSrc1,
-	IN	ULONG	Length);
-
-VOID RTMPZeroMemory(
-	IN  PVOID   pSrc,
-	IN  ULONG   Length);
-
-ULONG RTMPCompareMemory(
-	IN  PVOID   pSrc1,
-	IN  PVOID   pSrc2,
-	IN  ULONG   Length);
-
-VOID RTMPMoveMemory(
-	OUT PVOID   pDest,
-	IN  PVOID   pSrc,
-	IN  ULONG   Length);
-
-VOID AtoH(
-	char	*src,
-	UCHAR	*dest,
-	int		destlen);
-
-UCHAR BtoH(
-	char ch);
-
-VOID RTMPPatchMacBbpBug(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPPatchCardBus(
-	IN	PRTMP_ADAPTER	pAdapter);
-
-VOID RTMPPatchRalinkCardBus(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	ULONG			Bus);
-
-ULONG RTMPReadCBConfig(
-	IN	ULONG	Bus,
-	IN	ULONG	Slot,
-	IN	ULONG	Func,
-	IN	ULONG	Offset);
-
-VOID RTMPWriteCBConfig(
-	IN	ULONG	Bus,
-	IN	ULONG	Slot,
-	IN	ULONG	Func,
-	IN	ULONG	Offset,
-	IN	ULONG	Value);
-
-VOID RTMPInitTimer(
-	IN  PRTMP_ADAPTER           pAd,
-	IN  PRALINK_TIMER_STRUCT    pTimer,
-	IN  PVOID                   pTimerFunc,
-	IN	PVOID					pData,
-	IN  BOOLEAN                 Repeat);
-
-VOID RTMPSetTimer(
-	IN  PRALINK_TIMER_STRUCT    pTimer,
-	IN  ULONG                   Value);
-
-
-VOID RTMPModTimer(
-	IN	PRALINK_TIMER_STRUCT	pTimer,
-	IN	ULONG					Value);
-
-VOID RTMPCancelTimer(
-	IN  PRALINK_TIMER_STRUCT    pTimer,
-	OUT BOOLEAN                 *pCancelled);
-
-VOID RTMPSetLED(
-	IN PRTMP_ADAPTER 	pAd,
-	IN UCHAR			Status);
-
-VOID RTMPSetSignalLED(
-	IN PRTMP_ADAPTER 	pAd,
-	IN NDIS_802_11_RSSI Dbm);
-
-VOID RTMPEnableRxTx(
-	IN PRTMP_ADAPTER	pAd);
-
-//
-// prototype in action.c
-//
-VOID ActionStateMachineInit(
-    IN	PRTMP_ADAPTER	pAd,
-    IN  STATE_MACHINE *S,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID MlmeADDBAAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeDELBAAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeDLSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeInvalidAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeQOSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-#ifdef DOT11_N_SUPPORT
-VOID PeerAddBAReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerAddBARspAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerDelBAAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerBAAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-#endif // DOT11_N_SUPPORT //
-
-VOID SendPSMPAction(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			Wcid,
-	IN UCHAR			Psmp);
-
-
-#ifdef DOT11N_DRAFT3
-VOID SendBSS2040CoexistMgmtAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR	Wcid,
-	IN	UCHAR	apidx,
-	IN	UCHAR	InfoReq);
-
-VOID SendNotifyBWActionFrame(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR  Wcid,
-	IN UCHAR apidx);
-
-BOOLEAN ChannelSwitchSanityCheck(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  NewChannel,
-	IN    UCHAR  Secondary);
-
-VOID ChannelSwitchAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN    UCHAR  Channel,
-	IN    UCHAR  Secondary);
-
-ULONG BuildIntolerantChannelRep(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    PUCHAR  pDest);
-
-VOID Update2040CoexistFrameAndNotify(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha);
-
-VOID Send2040CoexistAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR  Wcid,
-	IN	BOOLEAN	bAddIntolerantCha);
-#endif // DOT11N_DRAFT3 //
-
-VOID PeerRMAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerPublicAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-#ifdef CONFIG_STA_SUPPORT
-VOID StaPublicAction(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR Bss2040Coexist);
-#endif // CONFIG_STA_SUPPORT //
-
-
-VOID PeerBSSTranAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-#ifdef DOT11_N_SUPPORT
-VOID PeerHTAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-#endif // DOT11_N_SUPPORT //
-
-VOID PeerQOSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-#ifdef QOS_DLS_SUPPORT
-VOID PeerDLSAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-#endif // QOS_DLS_SUPPORT //
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-VOID DlsParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_DLS_REQ_STRUCT *pDlsReq,
-	IN PRT_802_11_DLS pDls,
-	IN USHORT reason);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-VOID RECBATimerTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-VOID ORIBATimerTimeout(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID SendRefreshBAR(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry);
-#endif // DOT11_N_SUPPORT //
-
-VOID ActHeaderInit(
-    IN	PRTMP_ADAPTER	pAd,
-    IN OUT PHEADER_802_11 pHdr80211,
-    IN PUCHAR Addr1,
-    IN PUCHAR Addr2,
-    IN PUCHAR Addr3);
-
-VOID BarHeaderInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN OUT PFRAME_BAR pCntlBar,
-	IN PUCHAR pDA,
-	IN PUCHAR pSA);
-
-VOID InsertActField(
-	IN PRTMP_ADAPTER pAd,
-	OUT PUCHAR pFrameBuf,
-	OUT PULONG pFrameLen,
-	IN UINT8 Category,
-	IN UINT8 ActCode);
-
-BOOLEAN QosBADataParse(
-	IN PRTMP_ADAPTER	pAd,
-	IN BOOLEAN bAMSDU,
-	IN PUCHAR p8023Header,
-	IN UCHAR	WCID,
-	IN UCHAR	TID,
-	IN USHORT Sequence,
-	IN UCHAR DataOffset,
-	IN USHORT Datasize,
-	IN UINT   CurRxIndex);
-
-#ifdef DOT11_N_SUPPORT
-BOOLEAN CntlEnqueueForRecv(
-    IN	PRTMP_ADAPTER	pAd,
-	IN ULONG Wcid,
-    IN ULONG MsgLen,
-	IN PFRAME_BA_REQ pMsg);
-
-VOID BaAutoManSwitch(
-	IN	PRTMP_ADAPTER	pAd);
-#endif // DOT11_N_SUPPORT //
-
-VOID HTIOTCheck(
-	IN	PRTMP_ADAPTER	pAd,
-	IN    UCHAR     BatRecIdx);
-
-//
-// Private routines in rtmp_data.c
-//
-BOOLEAN RTMPHandleRxDoneInterrupt(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPHandleTxDoneInterrupt(
-	IN  PRTMP_ADAPTER   pAd);
-
-BOOLEAN RTMPHandleTxRingDmaDoneInterrupt(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  INT_SOURCE_CSR_STRUC TxRingBitmap);
-
-VOID RTMPHandleMgmtRingDmaDoneInterrupt(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPHandleTBTTInterrupt(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPHandlePreTBTTInterrupt(
-	IN  PRTMP_ADAPTER   pAd);
-
-void RTMPHandleTwakeupInterrupt(
-	IN PRTMP_ADAPTER pAd);
-
-VOID	RTMPHandleRxCoherentInterrupt(
-	IN	PRTMP_ADAPTER	pAd);
-
-BOOLEAN TxFrameIsAggregatible(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pPrevAddr1,
-	IN  PUCHAR          p8023hdr);
-
-BOOLEAN PeerIsAggreOn(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  ULONG          TxRate,
-    IN  PMAC_TABLE_ENTRY pMacEntry);
-
-NDIS_STATUS Sniff2BytesFromNdisBuffer(
-	IN  PNDIS_BUFFER    pFirstBuffer,
-	IN  UCHAR           DesiredOffset,
-	OUT PUCHAR          pByte0,
-	OUT PUCHAR          pByte1);
-
-NDIS_STATUS STASendPacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PNDIS_PACKET    pPacket);
-
-VOID STASendPackets(
-	IN  NDIS_HANDLE     MiniportAdapterContext,
-	IN  PPNDIS_PACKET   ppPacketArray,
-	IN  UINT            NumberOfPackets);
-
-VOID RTMPDeQueuePacket(
-	IN  PRTMP_ADAPTER   pAd,
-   	IN	BOOLEAN			bIntContext,
-	IN  UCHAR			QueIdx,
-	IN	UCHAR			Max_Tx_Packets);
-
-NDIS_STATUS	RTMPHardTransmit(
-	IN PRTMP_ADAPTER	pAd,
-	IN PNDIS_PACKET		pPacket,
-	IN  UCHAR			QueIdx,
-	OUT	PULONG			pFreeTXDLeft);
-
-NDIS_STATUS	STAHardTransmit(
-	IN PRTMP_ADAPTER	pAd,
-	IN TX_BLK			*pTxBlk,
-	IN  UCHAR			QueIdx);
-
-VOID STARxEAPOLFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-NDIS_STATUS RTMPFreeTXDRequest(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           RingType,
-	IN  UCHAR           NumberRequired,
-	IN 	PUCHAR          FreeNumberIs);
-
-NDIS_STATUS MlmeHardTransmit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR	QueIdx,
-	IN  PNDIS_PACKET    pPacket);
-
-NDIS_STATUS MlmeHardTransmitMgmtRing(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR	QueIdx,
-	IN  PNDIS_PACKET    pPacket);
-
-NDIS_STATUS MlmeHardTransmitTxRing(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR	QueIdx,
-	IN  PNDIS_PACKET    pPacket);
-
-USHORT  RTMPCalcDuration(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Rate,
-	IN  ULONG           Size);
-
-VOID RTMPWriteTxWI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXWI_STRUC		pTxWI,
-	IN  BOOLEAN    		FRAG,
-	IN  BOOLEAN    		CFACK,
-	IN  BOOLEAN    		InsTimestamp,
-	IN	BOOLEAN			AMPDU,
-	IN	BOOLEAN			Ack,
-	IN	BOOLEAN			NSeq,		// HW new a sequence.
-	IN	UCHAR			BASize,
-	IN	UCHAR			WCID,
-	IN	ULONG			Length,
-	IN  UCHAR      		PID,
-	IN	UCHAR			TID,
-	IN	UCHAR			TxRate,
-	IN	UCHAR			Txopmode,
-	IN	BOOLEAN			CfAck,
-	IN	HTTRANSMIT_SETTING	*pTransmit);
-
-
-VOID RTMPWriteTxWI_Data(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	OUT PTXWI_STRUC		pTxWI,
-	IN	TX_BLK				*pTxBlk);
-
-
-VOID RTMPWriteTxWI_Cache(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	OUT PTXWI_STRUC		pTxWI,
-	IN	TX_BLK				*pTxBlk);
-
-VOID RTMPWriteTxDescriptor(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXD_STRUC		pTxD,
-	IN	BOOLEAN			bWIV,
-	IN	UCHAR			QSEL);
-
-VOID RTMPSuspendMsduTransmission(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPResumeMsduTransmission(
-	IN  PRTMP_ADAPTER   pAd);
-
-NDIS_STATUS MiniportMMRequest(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			QueIdx,
-	IN	PUCHAR			pData,
-	IN  UINT            Length);
-
-NDIS_STATUS MiniportDataMMRequest(
-	 IN  PRTMP_ADAPTER   pAd,
-	 IN  UCHAR           QueIdx,
-	 IN  PUCHAR          pData,
-	 IN  UINT            Length);
-
-VOID RTMPSendNullFrame(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           TxRate,
-	IN	BOOLEAN			bQosNull);
-
-VOID RTMPSendDisassociationFrame(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTMPSendRTSFrame(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pDA,
-	IN	unsigned int	NextMpduSize,
-	IN  UCHAR           TxRate,
-	IN  UCHAR           RTSRate,
-	IN  USHORT          AckDuration,
-	IN  UCHAR           QueIdx,
-	IN  UCHAR			FrameGap);
-
-
-NDIS_STATUS RTMPApplyPacketFilter(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PRT28XX_RXD_STRUC      pRxD,
-	IN  PHEADER_802_11  pHeader);
-
-PQUEUE_HEADER   RTMPCheckTxSwQueue(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT UCHAR           *QueIdx);
-
-#ifdef CONFIG_STA_SUPPORT
-VOID RTMPReportMicError(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PCIPHER_KEY     pWpaKey);
-
-VOID	WpaMicFailureReportFrame(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    WpaDisassocApAndBlockAssoc(
-    IN  PVOID SystemSpecific1,
-    IN  PVOID FunctionContext,
-    IN  PVOID SystemSpecific2,
-    IN  PVOID SystemSpecific3);
-#endif // CONFIG_STA_SUPPORT //
-
-NDIS_STATUS RTMPCloneNdisPacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	BOOLEAN    pInsAMSDUHdr,
-	IN  PNDIS_PACKET    pInPacket,
-	OUT PNDIS_PACKET   *ppOutPacket);
-
-NDIS_STATUS RTMPAllocateNdisPacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PNDIS_PACKET    *pPacket,
-	IN  PUCHAR          pHeader,
-	IN  UINT            HeaderLen,
-	IN  PUCHAR          pData,
-	IN  UINT            DataLen);
-
-VOID RTMPFreeNdisPacket(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PNDIS_PACKET    pPacket);
-
-BOOLEAN RTMPFreeTXDUponTxDmaDone(
-	IN PRTMP_ADAPTER    pAd,
-	IN UCHAR            QueIdx);
-
-BOOLEAN RTMPCheckDHCPFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket);
-
-
-BOOLEAN RTMPCheckEtherType(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket);
-
-
-VOID RTMPCckBbpTuning(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UINT			TxRate);
-
-//
-// Private routines in rtmp_wep.c
-//
-VOID RTMPInitWepEngine(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pKey,
-	IN  UCHAR           KeyId,
-	IN  UCHAR           KeyLen,
-	IN  PUCHAR          pDest);
-
-VOID RTMPEncryptData(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pSrc,
-	IN  PUCHAR          pDest,
-	IN  UINT            Len);
-
-BOOLEAN	RTMPDecryptData(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			pSrc,
-	IN	UINT			Len,
-	IN	UINT			idx);
-
-BOOLEAN	RTMPSoftDecryptWEP(
-	IN PRTMP_ADAPTER 	pAd,
-	IN PUCHAR			pData,
-	IN ULONG			DataByteCnt,
-	IN PCIPHER_KEY		pGroupKey);
-
-VOID RTMPSetICV(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pDest);
-
-VOID ARCFOUR_INIT(
-	IN  PARCFOURCONTEXT Ctx,
-	IN  PUCHAR          pKey,
-	IN  UINT            KeyLen);
-
-UCHAR   ARCFOUR_BYTE(
-	IN  PARCFOURCONTEXT     Ctx);
-
-VOID ARCFOUR_DECRYPT(
-	IN  PARCFOURCONTEXT Ctx,
-	IN  PUCHAR          pDest,
-	IN  PUCHAR          pSrc,
-	IN  UINT            Len);
-
-VOID ARCFOUR_ENCRYPT(
-	IN  PARCFOURCONTEXT Ctx,
-	IN  PUCHAR          pDest,
-	IN  PUCHAR          pSrc,
-	IN  UINT            Len);
-
-VOID WPAARCFOUR_ENCRYPT(
-	IN  PARCFOURCONTEXT Ctx,
-	IN  PUCHAR          pDest,
-	IN  PUCHAR          pSrc,
-	IN  UINT            Len);
-
-UINT RTMP_CALC_FCS32(
-	IN  UINT   Fcs,
-	IN  PUCHAR  Cp,
-	IN  INT     Len);
-
-//
-// MLME routines
-//
-
-// Asic/RF/BBP related functions
-
-VOID AsicAdjustTxPower(
-	IN PRTMP_ADAPTER pAd);
-
-VOID 	AsicUpdateProtect(
-	IN		PRTMP_ADAPTER	pAd,
-	IN 		USHORT			OperaionMode,
-	IN 		UCHAR			SetMask,
-	IN		BOOLEAN			bDisableBGProtect,
-	IN		BOOLEAN			bNonGFExist);
-
-VOID AsicSwitchChannel(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			Channel,
-	IN	BOOLEAN			bScan);
-
-VOID AsicLockChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR Channel) ;
-
-VOID AsicAntennaSelect(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Channel);
-
-VOID AsicAntennaSetting(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	ABGBAND_STATE	BandState);
-
-VOID AsicRfTuningExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-#ifdef CONFIG_STA_SUPPORT
-VOID AsicSleepThenAutoWakeup(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  USHORT TbttNumToNextWakeUp);
-
-VOID AsicForceSleep(
-	IN PRTMP_ADAPTER pAd);
-
-VOID AsicForceWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN    bFromTx);
-#endif // CONFIG_STA_SUPPORT //
-
-VOID AsicSetBssid(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR pBssid);
-
-VOID AsicSetMcastWC(
-	IN PRTMP_ADAPTER pAd);
-
-VOID AsicDelWcidTab(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR	Wcid);
-
-VOID AsicEnableRDG(
-	IN PRTMP_ADAPTER pAd);
-
-VOID AsicDisableRDG(
-	IN PRTMP_ADAPTER pAd);
-
-VOID AsicDisableSync(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID AsicEnableBssSync(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID AsicEnableIbssSync(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID AsicSetEdcaParm(
-	IN PRTMP_ADAPTER pAd,
-	IN PEDCA_PARM    pEdcaParm);
-
-VOID AsicSetSlotTime(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN bUseShortSlotTime);
-
-VOID AsicAddSharedKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR         BssIndex,
-	IN UCHAR         KeyIdx,
-	IN UCHAR         CipherAlg,
-	IN PUCHAR        pKey,
-	IN PUCHAR        pTxMic,
-	IN PUCHAR        pRxMic);
-
-VOID AsicRemoveSharedKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR         BssIndex,
-	IN UCHAR         KeyIdx);
-
-VOID AsicUpdateWCIDAttribute(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN UCHAR		BssIndex,
-	IN UCHAR        CipherAlg,
-	IN BOOLEAN		bUsePairewiseKeyTable);
-
-VOID AsicUpdateWCIDIVEIV(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN ULONG        uIV,
-	IN ULONG        uEIV);
-
-VOID AsicUpdateRxWCIDTable(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN PUCHAR        pAddr);
-
-VOID AsicAddKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT		WCID,
-	IN UCHAR		BssIndex,
-	IN UCHAR		KeyIdx,
-	IN PCIPHER_KEY	pCipherKey,
-	IN BOOLEAN		bUsePairewiseKeyTable,
-	IN BOOLEAN		bTxKey);
-
-VOID AsicAddPairwiseKeyEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR        pAddr,
-	IN UCHAR		WCID,
-	IN CIPHER_KEY		 *pCipherKey);
-
-VOID AsicRemovePairwiseKeyEntry(
-	IN PRTMP_ADAPTER  pAd,
-	IN UCHAR		 BssIdx,
-	IN UCHAR		 Wcid);
-
-BOOLEAN AsicSendCommandToMcu(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR         Command,
-	IN UCHAR         Token,
-	IN UCHAR         Arg0,
-	IN UCHAR         Arg1);
-
-
-VOID MacAddrRandomBssid(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT PUCHAR pAddr);
-
-VOID MgtMacHeaderInit(
-	IN  PRTMP_ADAPTER     pAd,
-	IN OUT PHEADER_802_11 pHdr80211,
-	IN UCHAR SubType,
-	IN UCHAR ToDs,
-	IN PUCHAR pDA,
-	IN PUCHAR pBssid);
-
-VOID MlmeRadioOff(
-	IN PRTMP_ADAPTER pAd);
-
-VOID MlmeRadioOn(
-	IN PRTMP_ADAPTER pAd);
-
-
-VOID BssTableInit(
-	IN BSS_TABLE *Tab);
-
-#ifdef DOT11_N_SUPPORT
-VOID BATableInit(
-	IN PRTMP_ADAPTER pAd,
-    IN BA_TABLE *Tab);
-#endif // DOT11_N_SUPPORT //
-
-ULONG BssTableSearch(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR pBssid,
-	IN UCHAR Channel);
-
-ULONG BssSsidTableSearch(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR    pBssid,
-	IN PUCHAR    pSsid,
-	IN UCHAR     SsidLen,
-	IN UCHAR     Channel);
-
-ULONG BssTableSearchWithSSID(
-	IN BSS_TABLE *Tab,
-	IN PUCHAR    Bssid,
-	IN PUCHAR    pSsid,
-	IN UCHAR     SsidLen,
-	IN UCHAR     Channel);
-
-VOID BssTableDeleteEntry(
-	IN OUT  PBSS_TABLE pTab,
-	IN      PUCHAR pBssid,
-	IN      UCHAR Channel);
-
-#ifdef DOT11_N_SUPPORT
-VOID BATableDeleteORIEntry(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		BA_ORI_ENTRY	*pBAORIEntry);
-
-VOID BATableDeleteRECEntry(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		BA_REC_ENTRY	*pBARECEntry);
-
-VOID BATableTearORIEntry(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		UCHAR TID,
-	IN		UCHAR Wcid,
-	IN		BOOLEAN bForceDelete,
-	IN		BOOLEAN ALL);
-
-VOID BATableTearRECEntry(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		UCHAR TID,
-	IN		UCHAR WCID,
-	IN		BOOLEAN ALL);
-#endif // DOT11_N_SUPPORT //
-
-VOID  BssEntrySet(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT PBSS_ENTRY pBss,
-	IN PUCHAR pBssid,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR BssType,
-	IN USHORT BeaconPeriod,
-	IN PCF_PARM CfParm,
-	IN USHORT AtimWin,
-	IN USHORT CapabilityInfo,
-	IN UCHAR SupRate[],
-	IN UCHAR SupRateLen,
-	IN UCHAR ExtRate[],
-	IN UCHAR ExtRateLen,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN ADD_HT_INFO_IE *pAddHtInfo,	// AP might use this additional ht info IE
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			AddHtInfoLen,
-	IN UCHAR			NewExtChanOffset,
-	IN UCHAR Channel,
-	IN CHAR Rssi,
-	IN LARGE_INTEGER TimeStamp,
-	IN UCHAR CkipFlag,
-	IN PEDCA_PARM pEdcaParm,
-	IN PQOS_CAPABILITY_PARM pQosCapability,
-	IN PQBSS_LOAD_PARM pQbssLoad,
-	IN USHORT LengthVIE,
-	IN PNDIS_802_11_VARIABLE_IEs pVIE);
-
-ULONG  BssTableSetEntry(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT PBSS_TABLE pTab,
-	IN PUCHAR pBssid,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR BssType,
-	IN USHORT BeaconPeriod,
-	IN CF_PARM *CfParm,
-	IN USHORT AtimWin,
-	IN USHORT CapabilityInfo,
-	IN UCHAR SupRate[],
-	IN UCHAR SupRateLen,
-	IN UCHAR ExtRate[],
-	IN UCHAR ExtRateLen,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN ADD_HT_INFO_IE *pAddHtInfo,	// AP might use this additional ht info IE
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			AddHtInfoLen,
-	IN UCHAR			NewExtChanOffset,
-	IN UCHAR Channel,
-	IN CHAR Rssi,
-	IN LARGE_INTEGER TimeStamp,
-	IN UCHAR CkipFlag,
-	IN PEDCA_PARM pEdcaParm,
-	IN PQOS_CAPABILITY_PARM pQosCapability,
-	IN PQBSS_LOAD_PARM pQbssLoad,
-	IN USHORT LengthVIE,
-	IN PNDIS_802_11_VARIABLE_IEs pVIE);
-
-#ifdef DOT11_N_SUPPORT
-VOID BATableInsertEntry(
-    IN	PRTMP_ADAPTER	pAd,
-	IN USHORT Aid,
-    IN USHORT		TimeOutValue,
-	IN USHORT		StartingSeq,
-    IN UCHAR TID,
-	IN UCHAR BAWinSize,
-	IN UCHAR OriginatorStatus,
-    IN BOOLEAN IsRecipient);
-
-#ifdef DOT11N_DRAFT3
-VOID Bss2040CoexistTimeOut(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-
-VOID  TriEventInit(
-	IN	PRTMP_ADAPTER	pAd);
-
-ULONG TriEventTableSetEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT TRIGGER_EVENT_TAB *Tab,
-	IN PUCHAR pBssid,
-	IN HT_CAPABILITY_IE *pHtCapability,
-	IN UCHAR			HtCapabilityLen,
-	IN UCHAR			RegClass,
-	IN UCHAR ChannelNo);
-
-VOID TriEventCounterMaintenance(
-	IN	PRTMP_ADAPTER	pAd);
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-VOID BssTableSsidSort(
-	IN  PRTMP_ADAPTER   pAd,
-	OUT BSS_TABLE *OutTab,
-	IN  CHAR Ssid[],
-	IN  UCHAR SsidLen);
-
-VOID  BssTableSortByRssi(
-	IN OUT BSS_TABLE *OutTab);
-
-VOID BssCipherParse(
-	IN OUT  PBSS_ENTRY  pBss);
-
-NDIS_STATUS  MlmeQueueInit(
-	IN MLME_QUEUE *Queue);
-
-VOID  MlmeQueueDestroy(
-	IN MLME_QUEUE *Queue);
-
-BOOLEAN MlmeEnqueue(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG Machine,
-	IN ULONG MsgType,
-	IN ULONG MsgLen,
-	IN VOID *Msg);
-
-BOOLEAN MlmeEnqueueForRecv(
-	IN  PRTMP_ADAPTER   pAd,
-	IN ULONG Wcid,
-	IN ULONG TimeStampHigh,
-	IN ULONG TimeStampLow,
-	IN UCHAR Rssi0,
-	IN UCHAR Rssi1,
-	IN UCHAR Rssi2,
-	IN ULONG MsgLen,
-	IN PVOID Msg,
-	IN UCHAR Signal);
-
-
-BOOLEAN MlmeDequeue(
-	IN MLME_QUEUE *Queue,
-	OUT MLME_QUEUE_ELEM **Elem);
-
-VOID    MlmeRestartStateMachine(
-	IN  PRTMP_ADAPTER   pAd);
-
-BOOLEAN  MlmeQueueEmpty(
-	IN MLME_QUEUE *Queue);
-
-BOOLEAN  MlmeQueueFull(
-	IN MLME_QUEUE *Queue);
-
-BOOLEAN  MsgTypeSubst(
-	IN PRTMP_ADAPTER pAd,
-	IN PFRAME_802_11 pFrame,
-	OUT INT *Machine,
-	OUT INT *MsgType);
-
-VOID StateMachineInit(
-	IN STATE_MACHINE *Sm,
-	IN STATE_MACHINE_FUNC Trans[],
-	IN ULONG StNr,
-	IN ULONG MsgNr,
-	IN STATE_MACHINE_FUNC DefFunc,
-	IN ULONG InitState,
-	IN ULONG Base);
-
-VOID StateMachineSetAction(
-	IN STATE_MACHINE *S,
-	IN ULONG St,
-	ULONG Msg,
-	IN STATE_MACHINE_FUNC F);
-
-VOID StateMachinePerformAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN STATE_MACHINE *S,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID Drop(
-	IN  PRTMP_ADAPTER   pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID AssocStateMachineInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  STATE_MACHINE *Sm,
-	OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID ReassocTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID AssocTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID DisassocTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-//----------------------------------------------
-VOID MlmeDisassocReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeAssocReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeReassocReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeDisassocReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerAssocRspAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerReassocRspAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerDisassocAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID DisassocTimeoutAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID AssocTimeoutAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID  ReassocTimeoutAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID  Cls3errAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR pAddr);
-
-VOID SwitchBetweenWepAndCkip(
-	IN PRTMP_ADAPTER pAd);
-
-VOID  InvalidStateWhenAssoc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID  InvalidStateWhenReassoc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID InvalidStateWhenDisassociate(
-	IN  PRTMP_ADAPTER pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-#ifdef RT2870
-VOID MlmeCntlConfirm(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG MsgType,
-	IN USHORT Msg);
-#endif // RT2870 //
-
-VOID  ComposePsPoll(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID  ComposeNullFrame(
-	IN  PRTMP_ADAPTER pAd);
-
-VOID  AssocPostProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR pAddr2,
-	IN  USHORT CapabilityInfo,
-	IN  USHORT Aid,
-	IN  UCHAR SupRate[],
-	IN  UCHAR SupRateLen,
-	IN  UCHAR ExtRate[],
-	IN  UCHAR ExtRateLen,
-	IN PEDCA_PARM pEdcaParm,
-	IN HT_CAPABILITY_IE		*pHtCapability,
-	IN  UCHAR HtCapabilityLen,
-	IN ADD_HT_INFO_IE		*pAddHtInfo);
-
-VOID AuthStateMachineInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN PSTATE_MACHINE sm,
-	OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID AuthTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID MlmeAuthReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerAuthRspAtSeq2Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerAuthRspAtSeq4Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID AuthTimeoutAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID Cls2errAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR pAddr);
-
-VOID MlmeDeauthReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID InvalidStateWhenAuth(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-//=============================================
-
-VOID AuthRspStateMachineInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PSTATE_MACHINE Sm,
-	IN  STATE_MACHINE_FUNC Trans[]);
-
-VOID PeerDeauthAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerAuthSimpleRspGenAndSend(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PHEADER_802_11  pHdr80211,
-	IN  USHORT Alg,
-	IN  USHORT Seq,
-	IN  USHORT Reason,
-	IN  USHORT Status);
-
-//
-// Private routines in dls.c
-//
-
-#ifdef CONFIG_STA_SUPPORT
-#ifdef QOS_DLS_SUPPORT
-void DlsStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID MlmeDlsReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerDlsReqAction(
-    IN PRTMP_ADAPTER	pAd,
-    IN MLME_QUEUE_ELEM	*Elem);
-
-VOID PeerDlsRspAction(
-    IN PRTMP_ADAPTER	pAd,
-    IN MLME_QUEUE_ELEM	*Elem);
-
-VOID MlmeDlsTearDownAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerDlsTearDownAction(
-    IN PRTMP_ADAPTER	pAd,
-    IN MLME_QUEUE_ELEM	*Elem);
-
-VOID RTMPCheckDLSTimeOut(
-	IN PRTMP_ADAPTER	pAd);
-
-BOOLEAN RTMPRcvFrameDLSCheck(
-	IN PRTMP_ADAPTER	pAd,
-	IN PHEADER_802_11	pHeader,
-	IN ULONG			Len,
-	IN PRT28XX_RXD_STRUC	pRxD);
-
-INT	RTMPCheckDLSFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA);
-
-VOID RTMPSendDLSTearDownFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA);
-
-NDIS_STATUS RTMPSendSTAKeyRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA);
-
-NDIS_STATUS RTMPSendSTAKeyHandShake(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA);
-
-VOID DlsTimeoutAction(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-BOOLEAN MlmeDlsReqSanity(
-	IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PRT_802_11_DLS *pDLS,
-    OUT PUSHORT pReason);
-
-INT Set_DlsEntryInfo_Display_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg);
-
-MAC_TABLE_ENTRY *MacTableInsertDlsEntry(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR	pAddr,
-	IN  UINT	DlsEntryIdx);
-
-BOOLEAN MacTableDeleteDlsEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT wcid,
-	IN PUCHAR pAddr);
-
-MAC_TABLE_ENTRY *DlsEntryTableLookup(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount);
-
-MAC_TABLE_ENTRY *DlsEntryTableLookupByWcid(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR	wcid,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount);
-
-INT	Set_DlsAddEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_DlsTearDownEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // QOS_DLS_SUPPORT //
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef QOS_DLS_SUPPORT
-BOOLEAN PeerDlsReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pDlsTimeout,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-    OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability);
-
-BOOLEAN PeerDlsRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pStatus,
-    OUT UCHAR *pRatesLen,
-    OUT UCHAR Rates[],
-    OUT UCHAR *pHtCapabilityLen,
-    OUT HT_CAPABILITY_IE *pHtCapability);
-
-BOOLEAN PeerDlsTearDownSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pDA,
-    OUT PUCHAR pSA,
-    OUT USHORT *pReason);
-#endif // QOS_DLS_SUPPORT //
-
-//========================================
-
-VOID SyncStateMachineInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  STATE_MACHINE *Sm,
-	OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID BeaconTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID ScanTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID MlmeScanReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID InvalidStateWhenScan(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID InvalidStateWhenJoin(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID InvalidStateWhenStart(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerBeacon(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID EnqueueProbeRequest(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN ScanRunning(
-		IN PRTMP_ADAPTER pAd);
-//=========================================
-
-VOID MlmeCntlInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  STATE_MACHINE *S,
-	OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID MlmeCntlMachinePerformAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  STATE_MACHINE *S,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlIdleProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlOidScanProc(
-	IN  PRTMP_ADAPTER pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlOidSsidProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM * Elem);
-
-VOID CntlOidRTBssidProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM * Elem);
-
-VOID CntlMlmeRoamingProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM * Elem);
-
-VOID CntlWaitDisassocProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitJoinProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitReassocProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitStartProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitAuthProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitAuthProc2(
-	IN  PRTMP_ADAPTER pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID CntlWaitAssocProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-#ifdef QOS_DLS_SUPPORT
-VOID CntlOidDLSSetupProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-#endif // QOS_DLS_SUPPORT //
-
-VOID LinkUp(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR BssType);
-
-VOID LinkDown(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  BOOLEAN         IsReqFromAP);
-
-VOID IterateOnBssTab(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID IterateOnBssTab2(
-	IN  PRTMP_ADAPTER   pAd);;
-
-VOID JoinParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  OUT MLME_JOIN_REQ_STRUCT *JoinReq,
-	IN  ULONG BssIdx);
-
-VOID AssocParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN OUT MLME_ASSOC_REQ_STRUCT *AssocReq,
-	IN  PUCHAR pAddr,
-	IN  USHORT CapabilityInfo,
-	IN  ULONG Timeout,
-	IN  USHORT ListenIntv);
-
-VOID ScanParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  OUT MLME_SCAN_REQ_STRUCT *ScanReq,
-	IN  CHAR Ssid[],
-	IN  UCHAR SsidLen,
-	IN  UCHAR BssType,
-	IN  UCHAR ScanType);
-
-VOID DisassocParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  OUT MLME_DISASSOC_REQ_STRUCT *DisassocReq,
-	IN  PUCHAR pAddr,
-	IN  USHORT Reason);
-
-VOID StartParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  OUT MLME_START_REQ_STRUCT *StartReq,
-	IN  CHAR Ssid[],
-	IN  UCHAR SsidLen);
-
-VOID AuthParmFill(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  OUT MLME_AUTH_REQ_STRUCT *AuthReq,
-	IN  PUCHAR pAddr,
-	IN  USHORT Alg);
-
-VOID EnqueuePsPoll(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID EnqueueBeaconFrame(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID MlmeJoinReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeScanReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID MlmeStartReqAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID ScanTimeoutAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID BeaconTimeoutAtJoinAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerBeaconAtScanAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerBeaconAtJoinAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerBeacon(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID PeerProbeReqAction(
-	IN  PRTMP_ADAPTER pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID ScanNextChannel(
-	IN  PRTMP_ADAPTER   pAd);
-
-ULONG MakeIbssBeacon(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID CCXAdjacentAPReport(
-	IN  PRTMP_ADAPTER   pAd);
-
-BOOLEAN MlmeScanReqSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT UCHAR *BssType,
-	OUT CHAR ssid[],
-	OUT UCHAR *SsidLen,
-	OUT UCHAR *ScanType);
-
-BOOLEAN PeerBeaconAndProbeRspSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	IN  UCHAR MsgChannel,
-	OUT PUCHAR pAddr2,
-	OUT PUCHAR pBssid,
-	OUT CHAR Ssid[],
-	OUT UCHAR *pSsidLen,
-	OUT UCHAR *pBssType,
-	OUT USHORT *pBeaconPeriod,
-	OUT UCHAR *pChannel,
-	OUT UCHAR *pNewChannel,
-	OUT LARGE_INTEGER *pTimestamp,
-	OUT CF_PARM *pCfParm,
-	OUT USHORT *pAtimWin,
-	OUT USHORT *pCapabilityInfo,
-	OUT UCHAR *pErp,
-	OUT UCHAR *pDtimCount,
-	OUT UCHAR *pDtimPeriod,
-	OUT UCHAR *pBcastFlag,
-	OUT UCHAR *pMessageToMe,
-	OUT UCHAR SupRate[],
-	OUT UCHAR *pSupRateLen,
-	OUT UCHAR ExtRate[],
-	OUT UCHAR *pExtRateLen,
-	OUT	UCHAR *pCkipFlag,
-	OUT	UCHAR *pAironetCellPowerLimit,
-	OUT PEDCA_PARM       pEdcaParm,
-	OUT PQBSS_LOAD_PARM  pQbssLoad,
-	OUT PQOS_CAPABILITY_PARM pQosCapability,
-	OUT ULONG *pRalinkIe,
-	OUT UCHAR		 *pHtCapabilityLen,
-#ifdef CONFIG_STA_SUPPORT
-	OUT UCHAR		 *pPreNHtCapabilityLen,
-#endif // CONFIG_STA_SUPPORT //
-	OUT HT_CAPABILITY_IE *pHtCapability,
-	OUT UCHAR		 *AddHtInfoLen,
-	OUT ADD_HT_INFO_IE *AddHtInfo,
-	OUT UCHAR *NewExtChannel,
-	OUT USHORT *LengthVIE,
-	OUT PNDIS_802_11_VARIABLE_IEs pVIE);
-
-BOOLEAN PeerAddBAReqActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *pMsg,
-    IN ULONG MsgLen,
-	OUT PUCHAR pAddr2);
-
-BOOLEAN PeerAddBARspActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *pMsg,
-    IN ULONG MsgLen);
-
-BOOLEAN PeerDelBAActionSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN UCHAR Wcid,
-    IN VOID *pMsg,
-    IN ULONG MsgLen);
-
-BOOLEAN MlmeAssocReqSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pApAddr,
-	OUT USHORT *CapabilityInfo,
-	OUT ULONG *Timeout,
-	OUT USHORT *ListenIntv);
-
-BOOLEAN MlmeAuthReqSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr,
-	OUT ULONG *Timeout,
-	OUT USHORT *Alg);
-
-BOOLEAN MlmeStartReqSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT CHAR Ssid[],
-	OUT UCHAR *Ssidlen);
-
-BOOLEAN PeerAuthSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr,
-	OUT USHORT *Alg,
-	OUT USHORT *Seq,
-	OUT USHORT *Status,
-	OUT CHAR ChlgText[]);
-
-BOOLEAN PeerAssocRspSanity(
-	IN  PRTMP_ADAPTER   pAd,
-    IN VOID *pMsg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr2,
-	OUT USHORT *pCapabilityInfo,
-	OUT USHORT *pStatus,
-	OUT USHORT *pAid,
-	OUT UCHAR SupRate[],
-	OUT UCHAR *pSupRateLen,
-	OUT UCHAR ExtRate[],
-	OUT UCHAR *pExtRateLen,
-    OUT HT_CAPABILITY_IE		*pHtCapability,
-    OUT ADD_HT_INFO_IE		*pAddHtInfo,	// AP might use this additional ht info IE
-    OUT UCHAR			*pHtCapabilityLen,
-    OUT UCHAR			*pAddHtInfoLen,
-    OUT UCHAR			*pNewExtChannelOffset,
-	OUT PEDCA_PARM pEdcaParm,
-	OUT UCHAR *pCkipFlag);
-
-BOOLEAN PeerDisassocSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr2,
-	OUT USHORT *Reason);
-
-BOOLEAN PeerWpaMessageSanity(
-    IN 	PRTMP_ADAPTER 		pAd,
-    IN 	PEAPOL_PACKET 		pMsg,
-    IN 	ULONG 				MsgLen,
-    IN 	UCHAR				MsgType,
-    IN 	MAC_TABLE_ENTRY  	*pEntry);
-
-BOOLEAN PeerDeauthSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr2,
-	OUT USHORT *Reason);
-
-BOOLEAN PeerProbeReqSanity(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  VOID *Msg,
-	IN  ULONG MsgLen,
-	OUT PUCHAR pAddr2,
-	OUT CHAR Ssid[],
-	OUT UCHAR *pSsidLen);
-
-BOOLEAN GetTimBit(
-	IN  CHAR *Ptr,
-	IN  USHORT Aid,
-	OUT UCHAR *TimLen,
-	OUT UCHAR *BcastFlag,
-	OUT UCHAR *DtimCount,
-	OUT UCHAR *DtimPeriod,
-	OUT UCHAR *MessageToMe);
-
-UCHAR ChannelSanity(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR channel);
-
-NDIS_802_11_NETWORK_TYPE NetworkTypeInUseSanity(
-	IN PBSS_ENTRY pBss);
-
-BOOLEAN MlmeDelBAReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen);
-
-BOOLEAN MlmeAddBAReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2);
-
-ULONG MakeOutgoingFrame(
-	OUT CHAR *Buffer,
-	OUT ULONG *Length, ...);
-
-VOID  LfsrInit(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  ULONG Seed);
-
-UCHAR RandomByte(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID AsicUpdateAutoFallBackTable(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pTxRate);
-
-VOID  MlmePeriodicExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID LinkDownExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID LinkUpExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID STAMlmePeriodicExec(
-	PRTMP_ADAPTER pAd);
-
-VOID MlmeAutoScan(
-	IN PRTMP_ADAPTER pAd);
-
-VOID MlmeAutoReconnectLastSSID(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN MlmeValidateSSID(
-	IN PUCHAR pSsid,
-	IN UCHAR  SsidLen);
-
-VOID MlmeCheckForRoaming(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG    Now32);
-
-VOID MlmeCheckForFastRoaming(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  ULONG           Now);
-
-VOID MlmeDynamicTxRateSwitching(
-	IN PRTMP_ADAPTER pAd);
-
-VOID MlmeSetTxRate(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PRTMP_TX_RATE_SWITCH	pTxRate);
-
-VOID MlmeSelectTxRateTable(
-	IN PRTMP_ADAPTER		pAd,
-	IN PMAC_TABLE_ENTRY		pEntry,
-	IN PUCHAR				*ppTable,
-	IN PUCHAR				pTableSize,
-	IN PUCHAR				pInitTxRateIdx);
-
-VOID MlmeCalculateChannelQuality(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG Now);
-
-VOID MlmeCheckPsmChange(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG    Now32);
-
-VOID MlmeSetPsmBit(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT psm);
-
-VOID MlmeSetTxPreamble(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT TxPreamble);
-
-VOID UpdateBasicRateBitmap(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID MlmeUpdateTxRates(
-	IN PRTMP_ADAPTER 	pAd,
-	IN 	BOOLEAN		 	bLinkUp,
-	IN	UCHAR			apidx);
-
-#ifdef DOT11_N_SUPPORT
-VOID MlmeUpdateHtTxRates(
-	IN PRTMP_ADAPTER 		pAd,
-	IN	UCHAR				apidx);
-#endif // DOT11_N_SUPPORT //
-
-VOID    RTMPCheckRates(
-	IN      PRTMP_ADAPTER   pAd,
-	IN OUT  UCHAR           SupRate[],
-	IN OUT  UCHAR           *SupRateLen);
-
-#ifdef CONFIG_STA_SUPPORT
-BOOLEAN RTMPCheckChannel(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR		CentralChannel,
-	IN UCHAR		Channel);
-#endif // CONFIG_STA_SUPPORT //
-
-BOOLEAN 	RTMPCheckHt(
-	IN		PRTMP_ADAPTER	pAd,
-	IN		UCHAR	Wcid,
-	IN OUT	HT_CAPABILITY_IE			*pHtCapability,
-	IN OUT	ADD_HT_INFO_IE			*pAddHtInfo);
-
-VOID StaQuickResponeForRateUpExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID AsicBbpTuning1(
-	IN PRTMP_ADAPTER pAd);
-
-VOID AsicBbpTuning2(
-	IN PRTMP_ADAPTER pAd);
-
-VOID RTMPUpdateMlmeRate(
-	IN PRTMP_ADAPTER	pAd);
-
-CHAR RTMPMaxRssi(
-	IN PRTMP_ADAPTER	pAd,
-	IN CHAR				Rssi0,
-	IN CHAR				Rssi1,
-	IN CHAR				Rssi2);
-
-VOID AsicSetRxAnt(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			Ant);
-
-VOID AsicEvaluateRxAnt(
-	IN PRTMP_ADAPTER	pAd);
-
-VOID AsicRxAntEvalTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID APSDPeriodicExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-BOOLEAN RTMPCheckEntryEnableAutoRateSwitch(
-	IN PRTMP_ADAPTER    pAd,
-	IN PMAC_TABLE_ENTRY	pEntry);
-
-UCHAR RTMPStaFixedTxMode(
-	IN PRTMP_ADAPTER    pAd,
-	IN PMAC_TABLE_ENTRY	pEntry);
-
-VOID RTMPUpdateLegacyTxSetting(
-		UCHAR				fixed_tx_mode,
-		PMAC_TABLE_ENTRY	pEntry);
-
-BOOLEAN RTMPAutoRateSwitchCheck(
-	IN PRTMP_ADAPTER    pAd);
-
-NDIS_STATUS MlmeInit(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID MlmeHandler(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID MlmeHalt(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID MlmeResetRalinkCounters(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID BuildChannelList(
-	IN PRTMP_ADAPTER pAd);
-
-UCHAR FirstChannel(
-	IN  PRTMP_ADAPTER   pAd);
-
-UCHAR NextChannel(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR channel);
-
-VOID ChangeToCellPowerLimit(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR         AironetCellPowerLimit);
-
-VOID RaiseClock(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UINT32 *x);
-
-VOID LowerClock(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UINT32 *x);
-
-USHORT ShiftInBits(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID ShiftOutBits(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  USHORT data,
-	IN  USHORT count);
-
-VOID EEpromCleanup(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID EWDS(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID EWEN(
-	IN  PRTMP_ADAPTER   pAd);
-
-USHORT RTMP_EEPROM_READ16(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  USHORT Offset);
-
-VOID RTMP_EEPROM_WRITE16(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  USHORT Offset,
-	IN  USHORT Data);
-
-//
-// Prototypes of function definition in rtmp_tkip.c
-//
-VOID    RTMPInitTkipEngine(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pTKey,
-	IN  UCHAR           KeyId,
-	IN  PUCHAR          pTA,
-	IN  PUCHAR          pMICKey,
-	IN  PUCHAR          pTSC,
-	OUT PULONG          pIV16,
-	OUT PULONG          pIV32);
-
-VOID    RTMPInitMICEngine(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pKey,
-	IN  PUCHAR          pDA,
-	IN  PUCHAR          pSA,
-	IN  UCHAR           UserPriority,
-	IN  PUCHAR          pMICKey);
-
-BOOLEAN RTMPTkipCompareMICValue(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pSrc,
-	IN  PUCHAR          pDA,
-	IN  PUCHAR          pSA,
-	IN  PUCHAR          pMICKey,
-	IN	UCHAR			UserPriority,
-	IN  UINT            Len);
-
-VOID    RTMPCalculateMICValue(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PNDIS_PACKET    pPacket,
-	IN  PUCHAR          pEncap,
-	IN  PCIPHER_KEY     pKey,
-	IN	UCHAR			apidx);
-
-BOOLEAN RTMPTkipCompareMICValueWithLLC(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pLLC,
-	IN  PUCHAR          pSrc,
-	IN  PUCHAR          pDA,
-	IN  PUCHAR          pSA,
-	IN  PUCHAR          pMICKey,
-	IN  UINT            Len);
-
-VOID    RTMPTkipAppendByte(
-	IN  PTKIP_KEY_INFO  pTkip,
-	IN  UCHAR           uChar);
-
-VOID    RTMPTkipAppend(
-	IN  PTKIP_KEY_INFO  pTkip,
-	IN  PUCHAR          pSrc,
-	IN  UINT            nBytes);
-
-VOID    RTMPTkipGetMIC(
-	IN  PTKIP_KEY_INFO  pTkip);
-
-BOOLEAN RTMPSoftDecryptTKIP(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pData,
-	IN ULONG	DataByteCnt,
-	IN UCHAR    UserPriority,
-	IN PCIPHER_KEY	pWpaKey);
-
-BOOLEAN RTMPSoftDecryptAES(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pData,
-	IN ULONG	DataByteCnt,
-	IN PCIPHER_KEY	pWpaKey);
-
-//
-// Prototypes of function definition in cmm_info.c
-//
-NDIS_STATUS RTMPWPARemoveKeyProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PVOID           pBuf);
-
-VOID    RTMPWPARemoveAllKeys(
-	IN  PRTMP_ADAPTER   pAd);
-
-BOOLEAN RTMPCheckStrPrintAble(
-    IN  CHAR *pInPutStr,
-    IN  UCHAR strLen);
-
-VOID    RTMPSetPhyMode(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  ULONG phymode);
-
-VOID	RTMPUpdateHTIE(
-	IN	RT_HT_CAPABILITY	*pRtHt,
-	IN		UCHAR				*pMcsSet,
-	OUT		HT_CAPABILITY_IE *pHtCapability,
-	OUT		ADD_HT_INFO_IE		*pAddHtInfo);
-
-VOID	RTMPAddWcidAttributeEntry(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BssIdx,
-	IN 	UCHAR		 	KeyIdx,
-	IN 	UCHAR		 	CipherAlg,
-	IN 	MAC_TABLE_ENTRY *pEntry);
-
-CHAR *GetEncryptType(
-	CHAR enc);
-
-CHAR *GetAuthMode(
-	CHAR auth);
-
-VOID RTMPIoctlGetSiteSurvey(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID RTMPIoctlGetMacTable(
-	IN PRTMP_ADAPTER pAd,
-	IN struct iwreq *wrq);
-
-VOID RTMPIndicateWPA2Status(
-	IN  PRTMP_ADAPTER  pAdapter);
-
-VOID	RTMPOPModeSwitching(
-	IN	PRTMP_ADAPTER	pAd);
-
-#ifdef CONFIG_STA_SUPPORT
-VOID    RTMPAddBSSIDCipher(
-    IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR	Aid,
-    IN  PNDIS_802_11_KEY    pKey,
-    IN  UCHAR   CipherAlg);
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-VOID	RTMPSetHT(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	OID_SET_HT_PHYMODE *pHTPhyMode);
-
-VOID	RTMPSetIndividualHT(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	UCHAR				apidx);
-#endif // DOT11_N_SUPPORT //
-
-VOID RTMPSendWirelessEvent(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Event_flag,
-	IN	PUCHAR 			pAddr,
-	IN  UCHAR			BssIdx,
-	IN	CHAR			Rssi);
-
-VOID	NICUpdateCntlCounters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PHEADER_802_11	pHeader,
-	IN    UCHAR			SubType,
-	IN	PRXWI_STRUC 	pRxWI);
-//
-// prototype in wpa.c
-//
-BOOLEAN WpaMsgTypeSubst(
-	IN  UCHAR   EAPType,
-	OUT INT		*MsgType);
-
-VOID WpaPskStateMachineInit(
-	IN  PRTMP_ADAPTER       pAd,
-	IN  STATE_MACHINE       *S,
-	OUT STATE_MACHINE_FUNC Trans[]);
-
-VOID WpaEAPOLKeyAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    WpaPairMsg1Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    WpaPairMsg3Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    WpaGroupMsg1Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    WpaMacHeaderInit(
-	IN      PRTMP_ADAPTER   pAd,
-	IN OUT  PHEADER_802_11  pHdr80211,
-	IN      UCHAR           wep,
-	IN      PUCHAR          pAddr1);
-
-VOID    Wpa2PairMsg1Action(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    Wpa2PairMsg3Action(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  MLME_QUEUE_ELEM *Elem);
-
-BOOLEAN ParseKeyData(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          pKeyData,
-    IN  UCHAR           KeyDataLen,
-	IN	UCHAR			bPairewise);
-
-VOID    RTMPToWirelessSta(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pHeader802_3,
-    IN  UINT            HdrLen,
-	IN  PUCHAR          pData,
-    IN  UINT            DataLen,
-    IN	BOOLEAN			is4wayFrame);
-
-VOID    HMAC_SHA1(
-	IN  UCHAR   *text,
-	IN  UINT    text_len,
-	IN  UCHAR   *key,
-	IN  UINT    key_len,
-	IN  UCHAR   *digest);
-
-VOID    PRF(
-	IN  UCHAR   *key,
-	IN  INT     key_len,
-	IN  UCHAR   *prefix,
-	IN  INT     prefix_len,
-	IN  UCHAR   *data,
-	IN  INT     data_len,
-	OUT UCHAR   *output,
-	IN  INT     len);
-
-VOID    CCKMPRF(
-	IN  UCHAR   *key,
-	IN  INT     key_len,
-	IN  UCHAR   *data,
-	IN  INT     data_len,
-	OUT UCHAR   *output,
-	IN  INT     len);
-
-VOID WpaCountPTK(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR   *PMK,
-	IN  UCHAR   *ANonce,
-	IN  UCHAR   *AA,
-	IN  UCHAR   *SNonce,
-	IN  UCHAR   *SA,
-	OUT UCHAR   *output,
-	IN  UINT    len);
-
-VOID    GenRandom(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	UCHAR			*macAddr,
-	OUT	UCHAR			*random);
-
-//
-// prototype in aironet.c
-//
-VOID    AironetStateMachineInit(
-	IN  PRTMP_ADAPTER       pAd,
-	IN  STATE_MACHINE       *S,
-	OUT STATE_MACHINE_FUNC  Trans[]);
-
-VOID    AironetMsgAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    AironetRequestAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    ChannelLoadRequestAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    NoiseHistRequestAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    BeaconRequestAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    AironetReportAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem);
-
-VOID    ChannelLoadReportAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    NoiseHistReportAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    AironetFinalReportAction(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID    BeaconReportAction(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UCHAR           Index);
-
-VOID    AironetAddBeaconReport(
-	IN  PRTMP_ADAPTER       pAd,
-	IN  ULONG               Index,
-	IN  PMLME_QUEUE_ELEM    pElem);
-
-VOID    AironetCreateBeaconReportFromBssTable(
-	IN  PRTMP_ADAPTER       pAd);
-
-VOID    DBGPRINT_TX_RING(
-	IN PRTMP_ADAPTER  pAd,
-	IN UCHAR          QueIdx);
-
-VOID DBGPRINT_RX_RING(
-	IN PRTMP_ADAPTER  pAd);
-
-CHAR    ConvertToRssi(
-	IN PRTMP_ADAPTER  pAd,
-	IN CHAR				Rssi,
-	IN UCHAR    RssiNumber);
-
-
-#ifdef DOT11N_DRAFT3
-VOID BuildEffectedChannelList(
-	IN PRTMP_ADAPTER pAd);
-#endif // DOT11N_DRAFT3 //
-
-
-VOID APAsicEvaluateRxAnt(
-	IN PRTMP_ADAPTER	pAd);
-
-
-VOID APAsicRxAntEvalTimeout(
-	IN PRTMP_ADAPTER	pAd);
-
-//
-// function prototype in cmm_wpa.c
-//
-BOOLEAN RTMPCheckWPAframe(
-	IN PRTMP_ADAPTER pAd,
-	IN PMAC_TABLE_ENTRY	pEntry,
-	IN PUCHAR 			pData,
-	IN ULONG 			DataByteCount,
-	IN UCHAR			FromWhichBSSID);
-
-VOID AES_GTK_KEY_UNWRAP(
-	IN  UCHAR   *key,
-	OUT UCHAR   *plaintext,
-	IN	UCHAR	c_len,
-	IN  UCHAR   *ciphertext);
-
-BOOLEAN RTMPCheckRSNIE(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pData,
-	IN  UCHAR           DataLen,
-	IN  MAC_TABLE_ENTRY *pEntry,
-	OUT	UCHAR			*Offset);
-
-BOOLEAN RTMPParseEapolKeyData(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pKeyData,
-	IN  UCHAR           KeyDataLen,
-	IN	UCHAR			GroupKeyIndex,
-	IN	UCHAR			MsgType,
-	IN	BOOLEAN			bWPA2,
-	IN  MAC_TABLE_ENTRY *pEntry);
-
-VOID	ConstructEapolMsg(
-	IN 	PRTMP_ADAPTER    	pAd,
-    IN 	UCHAR				PeerAuthMode,
-    IN 	UCHAR				PeerWepStatus,
-    IN 	UCHAR				MyGroupKeyWepStatus,
-    IN 	UCHAR				MsgType,
-    IN	UCHAR				DefaultKeyIdx,
-    IN 	UCHAR				*ReplayCounter,
-	IN 	UCHAR				*KeyNonce,
-	IN	UCHAR				*TxRSC,
-	IN	UCHAR				*PTK,
-	IN	UCHAR				*GTK,
-	IN	UCHAR				*RSNIE,
-	IN	UCHAR				RSNIE_Len,
-    OUT PEAPOL_PACKET       pMsg);
-
-VOID	CalculateMIC(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			PeerWepStatus,
-	IN	UCHAR			*PTK,
-	OUT PEAPOL_PACKET   pMsg);
-
-NDIS_STATUS	RTMPSoftDecryptBroadCastData(
-	IN	PRTMP_ADAPTER					pAd,
-	IN	RX_BLK							*pRxBlk,
-	IN  NDIS_802_11_ENCRYPTION_STATUS 	GroupCipher,
-	IN  PCIPHER_KEY						pShard_key);
-
-VOID	ConstructEapolKeyData(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			PeerAuthMode,
-	IN	UCHAR			PeerWepStatus,
-	IN	UCHAR			GroupKeyWepStatus,
-	IN 	UCHAR			MsgType,
-	IN	UCHAR			DefaultKeyIdx,
-	IN	BOOLEAN			bWPA2Capable,
-	IN	UCHAR			*PTK,
-	IN	UCHAR			*GTK,
-	IN	UCHAR			*RSNIE,
-	IN	UCHAR			RSNIE_LEN,
-	OUT PEAPOL_PACKET   pMsg);
-
-VOID RTMPMakeRSNIE(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  UINT            AuthMode,
-	IN  UINT            WepStatus,
-	IN	UCHAR			apidx);
-
-//
-// function prototype in ap_wpa.c
-//
-
-BOOLEAN APWpaMsgTypeSubst(
-	IN UCHAR    EAPType,
-	OUT INT *MsgType) ;
-
-MAC_TABLE_ENTRY *PACInquiry(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  ULONG           Wcid);
-
-BOOLEAN RTMPCheckMcast(
-	IN PRTMP_ADAPTER pAd,
-	IN PEID_STRUCT      eid_ptr,
-	IN MAC_TABLE_ENTRY  *pEntry);
-
-BOOLEAN RTMPCheckUcast(
-	IN PRTMP_ADAPTER pAd,
-	IN PEID_STRUCT      eid_ptr,
-	IN MAC_TABLE_ENTRY  *pEntry);
-
-BOOLEAN RTMPCheckAUTH(
-	IN PRTMP_ADAPTER pAd,
-	IN PEID_STRUCT      eid_ptr,
-	IN MAC_TABLE_ENTRY  *pEntry);
-
-VOID WPAStart4WayHS(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MAC_TABLE_ENTRY *pEntry,
-	IN	ULONG			TimeInterval);
-
-VOID WPAStart2WayGroupHS(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MAC_TABLE_ENTRY *pEntry);
-
-VOID APWpaEAPPacketAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APWpaEAPOLStartAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APWpaEAPOLLogoffAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APWpaEAPOLKeyAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID APWpaEAPOLASFAlertAction(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  MLME_QUEUE_ELEM  *Elem);
-
-VOID HandleCounterMeasure(
-	IN PRTMP_ADAPTER pAd,
-	IN MAC_TABLE_ENTRY  *pEntry);
-
-VOID PeerPairMsg2Action(
-	IN PRTMP_ADAPTER pAd,
-	IN MAC_TABLE_ENTRY  *pEntry,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID PeerPairMsg4Action(
-	IN PRTMP_ADAPTER pAd,
-	IN MAC_TABLE_ENTRY  *pEntry,
-	IN MLME_QUEUE_ELEM *Elem);
-
-VOID CMTimerExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID WPARetryExec(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3);
-
-VOID EnqueueStartForPSKExec(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3);
-
-VOID RTMPHandleSTAKey(
-    IN PRTMP_ADAPTER    pAdapter,
-    IN MAC_TABLE_ENTRY  *pEntry,
-    IN MLME_QUEUE_ELEM  *Elem);
-
-VOID PeerGroupMsg2Action(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  PMAC_TABLE_ENTRY pEntry,
-	IN  VOID             *Msg,
-	IN  UINT             MsgLen);
-
-VOID PairDisAssocAction(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  PMAC_TABLE_ENTRY pEntry,
-	IN  USHORT           Reason);
-
-VOID MlmeDeAuthAction(
-	IN  PRTMP_ADAPTER    pAd,
-	IN  PMAC_TABLE_ENTRY pEntry,
-	IN  USHORT           Reason);
-
-VOID GREKEYPeriodicExec(
-	IN  PVOID   SystemSpecific1,
-	IN  PVOID   FunctionContext,
-	IN  PVOID   SystemSpecific2,
-	IN  PVOID   SystemSpecific3);
-
-VOID CountGTK(
-	IN  UCHAR   *PMK,
-	IN  UCHAR   *GNonce,
-	IN  UCHAR   *AA,
-	OUT UCHAR   *output,
-	IN  UINT    len);
-
-VOID    GetSmall(
-	IN  PVOID   pSrc1,
-	IN  PVOID   pSrc2,
-	OUT PUCHAR  out,
-	IN  ULONG   Length);
-
-VOID    GetLarge(
-	IN  PVOID   pSrc1,
-	IN  PVOID   pSrc2,
-	OUT PUCHAR  out,
-	IN  ULONG   Length);
-
-VOID APGenRandom(
-	IN PRTMP_ADAPTER pAd,
-	OUT UCHAR       *random);
-
-VOID AES_GTK_KEY_WRAP(
-	IN UCHAR *key,
-	IN UCHAR *plaintext,
-	IN UCHAR p_len,
-	OUT UCHAR *ciphertext);
-
-VOID    WpaSend(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          pPacket,
-    IN  ULONG           Len);
-
-VOID    APToWirelessSta(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MAC_TABLE_ENTRY *pEntry,
-	IN  PUCHAR          pHeader802_3,
-	IN  UINT            HdrLen,
-	IN  PUCHAR          pData,
-	IN  UINT            DataLen,
-    IN	BOOLEAN			bClearFrame);
-
-VOID RTMPAddPMKIDCache(
-	IN  PRTMP_ADAPTER   		pAd,
-	IN	INT						apidx,
-	IN	PUCHAR				pAddr,
-	IN	UCHAR					*PMKID,
-	IN	UCHAR					*PMK);
-
-INT RTMPSearchPMKIDCache(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	INT				apidx,
-	IN	PUCHAR		pAddr);
-
-VOID RTMPDeletePMKIDCache(
-	IN  PRTMP_ADAPTER   pAd,
-	IN	INT				apidx,
-	IN  INT				idx);
-
-VOID RTMPMaintainPMKIDCache(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID	RTMPSendTriggerFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PVOID			pBuffer,
-	IN	ULONG			Length,
-	IN  UCHAR           TxRate,
-	IN	BOOLEAN			bQosNull);
-
-#ifdef RT30xx
-VOID RTMPFilterCalibration(
-	IN PRTMP_ADAPTER pAd);
-#endif // RT30xx //
-
-
-//typedef void (*TIMER_FUNCTION)(unsigned long);
-
-
-/* timeout -- ms */
-VOID RTMP_SetPeriodicTimer(
-	IN	NDIS_MINIPORT_TIMER *pTimer,
-	IN	unsigned long timeout);
-
-VOID RTMP_OS_Init_Timer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	NDIS_MINIPORT_TIMER *pTimer,
-	IN	TIMER_FUNCTION function,
-	IN	PVOID data);
-
-VOID RTMP_OS_Add_Timer(
-	IN	NDIS_MINIPORT_TIMER	*pTimer,
-	IN	unsigned long timeout);
-
-VOID RTMP_OS_Mod_Timer(
-	IN	NDIS_MINIPORT_TIMER	*pTimer,
-	IN	unsigned long timeout);
-
-
-VOID RTMP_OS_Del_Timer(
-	IN	NDIS_MINIPORT_TIMER	*pTimer,
-	OUT	BOOLEAN				 *pCancelled);
-
-
-VOID RTMP_OS_Release_Packet(
-	IN	PRTMP_ADAPTER pAd,
-	IN	PQUEUE_ENTRY  pEntry);
-
-VOID RTMPusecDelay(
-	IN	ULONG	usec);
-
-NDIS_STATUS os_alloc_mem(
-	IN	PRTMP_ADAPTER pAd,
-	OUT	PUCHAR *mem,
-	IN	ULONG  size);
-
-NDIS_STATUS os_free_mem(
-	IN	PRTMP_ADAPTER pAd,
-	IN	PUCHAR mem);
-
-
-void RTMP_AllocateSharedMemory(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-VOID RTMPFreeTxRxRingMemory(
-    IN  PRTMP_ADAPTER   pAd);
-
-NDIS_STATUS AdapterBlockAllocateMemory(
-	IN PVOID	handle,
-	OUT	PVOID	*ppAd);
-
-void RTMP_AllocateTxDescMemory(
-	IN	PRTMP_ADAPTER pAd,
-	IN	UINT	Index,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-void RTMP_AllocateFirstTxBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	UINT	Index,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-void RTMP_AllocateMgmtDescMemory(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-void RTMP_AllocateRxDescMemory(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-PNDIS_PACKET RTMP_AllocateRxPacketBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress,
-	OUT	PNDIS_PHYSICAL_ADDRESS PhysicalAddress);
-
-PNDIS_PACKET RTMP_AllocateTxPacketBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length,
-	IN	BOOLEAN	Cached,
-	OUT	PVOID	*VirtualAddress);
-
-PNDIS_PACKET RTMP_AllocateFragPacketBuffer(
-	IN	PRTMP_ADAPTER pAd,
-	IN	ULONG	Length);
-
-void RTMP_QueryPacketInfo(
-	IN  PNDIS_PACKET pPacket,
-	OUT PACKET_INFO  *pPacketInfo,
-	OUT PUCHAR		 *pSrcBufVA,
-	OUT	UINT		 *pSrcBufLen);
-
-void RTMP_QueryNextPacketInfo(
-	IN  PNDIS_PACKET *ppPacket,
-	OUT PACKET_INFO  *pPacketInfo,
-	OUT PUCHAR		 *pSrcBufVA,
-	OUT	UINT		 *pSrcBufLen);
-
-
-BOOLEAN RTMP_FillTxBlkInfo(
-	IN RTMP_ADAPTER *pAd,
-	IN TX_BLK *pTxBlk);
-
-
-PRTMP_SCATTER_GATHER_LIST
-rt_get_sg_list_from_packet(PNDIS_PACKET pPacket, RTMP_SCATTER_GATHER_LIST *sg);
-
-
- void announce_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket);
-
-
-UINT BA_Reorder_AMSDU_Annnounce(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket);
-
-
-UINT Handle_AMSDU_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	IN  UCHAR			FromWhichBSSID);
-
-
-void convert_802_11_to_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR			p8023hdr,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	IN  UCHAR			FromWhichBSSID);
-
-
-PNET_DEV get_netdev_from_bssid(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			FromWhichBSSID);
-
-
-PNDIS_PACKET duplicate_pkt(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pHeader802_3,
-    IN  UINT            HdrLen,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	IN	UCHAR			FromWhichBSSID);
-
-
-PNDIS_PACKET duplicate_pkt_with_TKIP_MIC(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pOldPkt);
-
-PNDIS_PACKET duplicate_pkt_with_VLAN(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pHeader802_3,
-    IN  UINT            HdrLen,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	IN	UCHAR			FromWhichBSSID);
-
-PNDIS_PACKET duplicate_pkt_with_WPI(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UINT32			ext_head_len,
-	IN	UINT32			ext_tail_len);
-
-UCHAR VLAN_8023_Header_Copy(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pHeader802_3,
-	IN	UINT            HdrLen,
-	OUT PUCHAR			pData,
-	IN	UCHAR			FromWhichBSSID);
-
-#ifdef DOT11_N_SUPPORT
-void ba_flush_reordering_timeout_mpdus(
-	IN PRTMP_ADAPTER	pAd,
-	IN PBA_REC_ENTRY	pBAEntry,
-	IN ULONG			Now32);
-
-
-VOID BAOriSessionSetUp(
-			IN PRTMP_ADAPTER    pAd,
-			IN MAC_TABLE_ENTRY	*pEntry,
-			IN UCHAR			TID,
-			IN USHORT			TimeOut,
-			IN ULONG			DelayTime,
-			IN BOOLEAN		isForced);
-
-VOID BASessionTearDownALL(
-	IN OUT	PRTMP_ADAPTER pAd,
-	IN		UCHAR Wcid);
-#endif // DOT11_N_SUPPORT //
-
-BOOLEAN OS_Need_Clone_Packet(void);
-
-
-VOID build_tx_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR	pFrame,
-	IN	ULONG	FrameLen);
-
-
-VOID BAOriSessionTearDown(
-	IN OUT	PRTMP_ADAPTER	pAd,
-	IN		UCHAR			Wcid,
-	IN		UCHAR			TID,
-	IN		BOOLEAN			bPassive,
-	IN		BOOLEAN			bForceSend);
-
-VOID BARecSessionTearDown(
-	IN OUT	PRTMP_ADAPTER	pAd,
-	IN		UCHAR			Wcid,
-	IN		UCHAR			TID,
-	IN		BOOLEAN			bPassive);
-
-BOOLEAN ba_reordering_resource_init(PRTMP_ADAPTER pAd, int num);
-void ba_reordering_resource_release(PRTMP_ADAPTER pAd);
-
-ULONG AutoChBssInsertEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pBssid,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR ChannelNo,
-	IN CHAR Rssi);
-
-void AutoChBssTableInit(
-	IN PRTMP_ADAPTER pAd);
-
-void ChannelInfoInit(
-	IN PRTMP_ADAPTER pAd);
-
-void AutoChBssTableDestroy(
-	IN PRTMP_ADAPTER pAd);
-
-void ChannelInfoDestroy(
-	IN PRTMP_ADAPTER pAd);
-
-UCHAR New_ApAutoSelectChannel(
-	IN PRTMP_ADAPTER pAd);
-
-
-#ifdef NINTENDO_AP
-VOID	InitNINTENDO_TABLE(
-	IN PRTMP_ADAPTER pAd);
-
-UCHAR	CheckNINTENDO_TABLE(
-	IN PRTMP_ADAPTER pAd,
-	PCHAR pDS_Ssid,
-	UCHAR DS_SsidLen,
-	PUCHAR pDS_Addr);
-
-UCHAR	DelNINTENDO_ENTRY(
-	IN	PRTMP_ADAPTER pAd,
-	UCHAR * pDS_Addr);
-
-VOID	RTMPIoctlNintendoCapable(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	struct iwreq	*wrq);
-
-VOID	RTMPIoctlNintendoGetTable(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	struct iwreq	*wrq);
-
-VOID	RTMPIoctlNintendoSetTable(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	struct iwreq	*wrq);
-
-#endif // NINTENDO_AP //
-
-BOOLEAN rtstrmactohex(
-	IN char *s1,
-	IN char *s2);
-
-BOOLEAN rtstrcasecmp(
-	IN char *s1,
-	IN char *s2);
-
-char *rtstrstruncasecmp(
-	IN char *s1,
-	IN char *s2);
-
-char    *rtstrstr(
-	IN	const char * s1,
-	IN	const char * s2);
-
-char *rstrtok(
-	IN char * s,
-	IN const char * ct);
-
-int rtinet_aton(
-	const char *cp,
-	unsigned int *addr);
-
-////////// common ioctl functions //////////
-INT Set_DriverVersion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_CountryRegion_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_CountryRegionABand_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_WirelessMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_Channel_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ShortSlot_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_TxPower_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_BGProtection_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-
-INT Set_TxPreamble_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-
-INT Set_RTSThreshold_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-
-INT Set_FragThreshold_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-
-INT Set_TxBurst_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-
-#ifdef AGGREGATION_SUPPORT
-INT	Set_PktAggregate_Proc(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PUCHAR			arg);
-#endif
-
-INT	Set_IEEE80211H_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#ifdef DBG
-INT	Set_Debug_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif
-
-INT	Show_DescInfo_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ResetStatCounter_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#ifdef DOT11_N_SUPPORT
-INT	Set_BASetup_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_BADecline_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_BAOriTearDown_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_BARecTearDown_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtBw_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtMcs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtGi_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtOpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtStbc_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtHtc_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtExtcha_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtMpduDensity_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtBaWinSize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtRdg_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtLinkAdapt_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtAmsdu_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtAutoBa_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtProtect_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtMimoPs_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-
-INT	Set_ForceShortGI_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_ForceGF_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	SetCommonHT(
-	IN	PRTMP_ADAPTER	pAd);
-
-INT	Set_SendPSMPAction_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT	Set_HtMIMOPSmode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-
-INT	Set_HtTxBASize_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // DOT11_N_SUPPORT //
-
-
-
-#ifdef CONFIG_STA_SUPPORT
-//Dls ,	kathy
-VOID RTMPSendDLSTearDownFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA);
-
-#ifdef DOT11_N_SUPPORT
-//Block ACK
-VOID QueryBATABLE(
-	IN  PRTMP_ADAPTER pAd,
-	OUT PQUERYBA_TABLE pBAT);
-#endif // DOT11_N_SUPPORT //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-INT	    WpaCheckEapCode(
-	IN  PRTMP_ADAPTER   	pAd,
-	IN  PUCHAR				pFrame,
-	IN  USHORT				FrameLen,
-	IN  USHORT				OffSet);
-
-VOID    WpaSendMicFailureToWpaSupplicant(
-    IN  PRTMP_ADAPTER       pAd,
-    IN  BOOLEAN             bUnicast);
-
-VOID    SendAssocIEsToWpaSupplicant(
-    IN  PRTMP_ADAPTER       pAd);
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-int wext_notify_event_assoc(
-	IN  RTMP_ADAPTER *pAd);
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-#endif // CONFIG_STA_SUPPORT //
-
-
-
-#ifdef DOT11_N_SUPPORT
-VOID Handle_BSS_Width_Trigger_Events(
-	IN PRTMP_ADAPTER pAd);
-
-void build_ext_channel_switch_ie(
-	IN PRTMP_ADAPTER pAd,
-	IN HT_EXT_CHANNEL_SWITCH_ANNOUNCEMENT_IE *pIE);
-#endif // DOT11_N_SUPPORT //
-
-
-BOOLEAN APRxDoneInterruptHandle(
-	IN	PRTMP_ADAPTER	pAd);
-
-BOOLEAN STARxDoneInterruptHandle(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	BOOLEAN			argc);
-
-#ifdef DOT11_N_SUPPORT
-// AMPDU packet indication
-VOID Indicate_AMPDU_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-// AMSDU packet indication
-VOID Indicate_AMSDU_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-#endif // DOT11_N_SUPPORT //
-
-// Normal legacy Rx packet indication
-VOID Indicate_Legacy_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-VOID Indicate_EAPOL_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-void  update_os_packet_info(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-void wlan_802_11_to_802_3_packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	PUCHAR			pHeader802_3,
-	IN  UCHAR			FromWhichBSSID);
-
-UINT deaggregate_AMSDU_announce(
-	IN	PRTMP_ADAPTER	pAd,
-	PNDIS_PACKET		pPacket,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize);
-
-
-#ifdef CONFIG_STA_SUPPORT
-// remove LLC and get 802_3 Header
-#define  RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(_pRxBlk, _pHeader802_3)	\
-{																				\
-	PUCHAR _pRemovedLLCSNAP = NULL, _pDA, _pSA;                                 \
-																				\
-	if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_MESH))                                    \
-	{                                                                           \
-		_pDA = _pRxBlk->pHeader->Addr3;                                         \
-		_pSA = (PUCHAR)_pRxBlk->pHeader + sizeof(HEADER_802_11);                \
-	}                                                                           \
-	else                                                                        \
-	{                                                                           \
-		if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_INFRA))                              	\
-		{                                                                       \
-			_pDA = _pRxBlk->pHeader->Addr1;                                     \
-		if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_DLS))									\
-			_pSA = _pRxBlk->pHeader->Addr2;										\
-		else																	\
-			_pSA = _pRxBlk->pHeader->Addr3;                                     \
-		}                                                                       \
-		else                                                                    \
-		{                                                                       \
-			_pDA = _pRxBlk->pHeader->Addr1;                                     \
-			_pSA = _pRxBlk->pHeader->Addr2;                                     \
-		}                                                                       \
-	}                                                                           \
-																				\
-	CONVERT_TO_802_3(_pHeader802_3, _pDA, _pSA, _pRxBlk->pData, 				\
-		_pRxBlk->DataSize, _pRemovedLLCSNAP);                                   \
-}
-#endif // CONFIG_STA_SUPPORT //
-
-
-BOOLEAN APFowardWirelessStaToWirelessSta(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	ULONG			FromWhichBSSID);
-
-VOID Announce_or_Forward_802_3_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UCHAR			FromWhichBSSID);
-
-VOID Sta_Announce_or_Forward_802_3_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UCHAR			FromWhichBSSID);
-
-
-#ifdef CONFIG_STA_SUPPORT
-#define ANNOUNCE_OR_FORWARD_802_3_PACKET(_pAd, _pPacket, _FromWhichBSS)\
-			Sta_Announce_or_Forward_802_3_Packet(_pAd, _pPacket, _FromWhichBSS);
-			//announce_802_3_packet(_pAd, _pPacket);
-#endif // CONFIG_STA_SUPPORT //
-
-
-PNDIS_PACKET DuplicatePacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UCHAR			FromWhichBSSID);
-
-
-PNDIS_PACKET ClonePacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize);
-
-
-// Normal, AMPDU or AMSDU
-VOID CmmRxnonRalinkFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-VOID CmmRxRalinkFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID);
-
-VOID Update_Rssi_Sample(
-	IN PRTMP_ADAPTER	pAd,
-	IN RSSI_SAMPLE		*pRssi,
-	IN PRXWI_STRUC		pRxWI);
-
-PNDIS_PACKET GetPacketFromRxRing(
-	IN		PRTMP_ADAPTER	pAd,
-	OUT		PRT28XX_RXD_STRUC		pSaveRxD,
-	OUT		BOOLEAN			*pbReschedule,
-	IN OUT	UINT32			*pRxPending);
-
-PNDIS_PACKET RTMPDeFragmentDataFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk);
-
-////////////////////////////////////////
-
-
-
-
-
-#ifdef SNMP_SUPPORT
-//for snmp , kathy
-typedef struct _DefaultKeyIdxValue
-{
-	UCHAR	KeyIdx;
-	UCHAR	Value[16];
-} DefaultKeyIdxValue, *PDefaultKeyIdxValue;
-#endif
-
-
-#ifdef CONFIG_STA_SUPPORT
-enum {
-	DIDmsg_lnxind_wlansniffrm		= 0x00000044,
-	DIDmsg_lnxind_wlansniffrm_hosttime	= 0x00010044,
-	DIDmsg_lnxind_wlansniffrm_mactime	= 0x00020044,
-	DIDmsg_lnxind_wlansniffrm_channel	= 0x00030044,
-	DIDmsg_lnxind_wlansniffrm_rssi		= 0x00040044,
-	DIDmsg_lnxind_wlansniffrm_sq		= 0x00050044,
-	DIDmsg_lnxind_wlansniffrm_signal	= 0x00060044,
-	DIDmsg_lnxind_wlansniffrm_noise		= 0x00070044,
-	DIDmsg_lnxind_wlansniffrm_rate		= 0x00080044,
-	DIDmsg_lnxind_wlansniffrm_istx		= 0x00090044,
-	DIDmsg_lnxind_wlansniffrm_frmlen	= 0x000A0044
-};
-enum {
-	P80211ENUM_msgitem_status_no_value	= 0x00
-};
-enum {
-	P80211ENUM_truth_false			= 0x00,
-	P80211ENUM_truth_true			= 0x01
-};
-
-/* Definition from madwifi */
-typedef struct {
-        UINT32 did;
-        UINT16 status;
-        UINT16 len;
-        UINT32 data;
-} p80211item_uint32_t;
-
-typedef struct {
-        UINT32 msgcode;
-        UINT32 msglen;
-#define WLAN_DEVNAMELEN_MAX 16
-        UINT8 devname[WLAN_DEVNAMELEN_MAX];
-        p80211item_uint32_t hosttime;
-        p80211item_uint32_t mactime;
-        p80211item_uint32_t channel;
-        p80211item_uint32_t rssi;
-        p80211item_uint32_t sq;
-        p80211item_uint32_t signal;
-        p80211item_uint32_t noise;
-        p80211item_uint32_t rate;
-        p80211item_uint32_t istx;
-        p80211item_uint32_t frmlen;
-} wlan_ng_prism2_header;
-
-/* The radio capture header precedes the 802.11 header. */
-typedef struct PACKED _ieee80211_radiotap_header {
-    UINT8	it_version;	/* Version 0. Only increases
-				 * for drastic changes,
-				 * introduction of compatible
-				 * new fields does not count.
-				 */
-    UINT8	it_pad;
-    UINT16     it_len;         /* length of the whole
-				 * header in bytes, including
-				 * it_version, it_pad,
-				 * it_len, and data fields.
-				 */
-    UINT32   it_present;	/* A bitmap telling which
-					 * fields are present. Set bit 31
-					 * (0x80000000) to extend the
-					 * bitmap by another 32 bits.
-					 * Additional extensions are made
-					 * by setting bit 31.
-					 */
-}ieee80211_radiotap_header ;
-
-enum ieee80211_radiotap_type {
-    IEEE80211_RADIOTAP_TSFT = 0,
-    IEEE80211_RADIOTAP_FLAGS = 1,
-    IEEE80211_RADIOTAP_RATE = 2,
-    IEEE80211_RADIOTAP_CHANNEL = 3,
-    IEEE80211_RADIOTAP_FHSS = 4,
-    IEEE80211_RADIOTAP_DBM_ANTSIGNAL = 5,
-    IEEE80211_RADIOTAP_DBM_ANTNOISE = 6,
-    IEEE80211_RADIOTAP_LOCK_QUALITY = 7,
-    IEEE80211_RADIOTAP_TX_ATTENUATION = 8,
-    IEEE80211_RADIOTAP_DB_TX_ATTENUATION = 9,
-    IEEE80211_RADIOTAP_DBM_TX_POWER = 10,
-    IEEE80211_RADIOTAP_ANTENNA = 11,
-    IEEE80211_RADIOTAP_DB_ANTSIGNAL = 12,
-    IEEE80211_RADIOTAP_DB_ANTNOISE = 13
-};
-
-#define WLAN_RADIOTAP_PRESENT (			\
-	(1 << IEEE80211_RADIOTAP_TSFT)	|	\
-	(1 << IEEE80211_RADIOTAP_FLAGS) |	\
-	(1 << IEEE80211_RADIOTAP_RATE)  | 	\
-	 0)
-
-typedef struct _wlan_radiotap_header {
-	ieee80211_radiotap_header wt_ihdr;
-	INT64 wt_tsft;
-	UINT8 wt_flags;
-	UINT8 wt_rate;
-} wlan_radiotap_header;
-/* Definition from madwifi */
-
-void send_monitor_packets(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk);
-
-#if WIRELESS_EXT >= 12
-// This function will be called when query /proc
-struct iw_statistics *rt28xx_get_wireless_stats(
-    IN struct net_device *net_dev);
-#endif
-
-VOID    RTMPSetDesiredRates(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  LONG            Rates);
-#endif // CONFIG_STA_SUPPORT //
-
-INT	Set_FixedTxMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-INT	Set_OpMode_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-
-static inline char* GetPhyMode(
-	int Mode)
-{
-	switch(Mode)
-	{
-		case MODE_CCK:
-			return "CCK";
-
-		case MODE_OFDM:
-			return "OFDM";
-#ifdef DOT11_N_SUPPORT
-		case MODE_HTMIX:
-			return "HTMIX";
-
-		case MODE_HTGREENFIELD:
-			return "GREEN";
-#endif // DOT11_N_SUPPORT //
-		default:
-			return "N/A";
-	}
-}
-
-
-static inline char* GetBW(
-	int BW)
-{
-	switch(BW)
-	{
-		case BW_10:
-			return "10M";
-
-		case BW_20:
-			return "20M";
-#ifdef DOT11_N_SUPPORT
-		case BW_40:
-			return "40M";
-#endif // DOT11_N_SUPPORT //
-		default:
-			return "N/A";
-	}
-}
-
-
-VOID RT28xxThreadTerminate(
-	IN RTMP_ADAPTER *pAd);
-
-BOOLEAN RT28XXChipsetCheck(
-	IN void *_dev_p);
-
-BOOLEAN RT28XXNetDevInit(
-	IN void 				*_dev_p,
-	IN struct  net_device	*net_dev,
-	IN RTMP_ADAPTER 		*pAd);
-
-BOOLEAN RT28XXProbePostConfig(
-	IN void 				*_dev_p,
-	IN RTMP_ADAPTER 		*pAd,
-	IN INT32				argc);
-
-VOID RT28XXDMADisable(
-	IN RTMP_ADAPTER 		*pAd);
-
-VOID RT28XXDMAEnable(
-	IN RTMP_ADAPTER 		*pAd);
-
-VOID RT28xx_UpdateBeaconToAsic(
-	IN RTMP_ADAPTER * pAd,
-	IN INT apidx,
-	IN ULONG BeaconLen,
-	IN ULONG UpdatePos);
-
-INT rt28xx_ioctl(
-	IN	struct net_device	*net_dev,
-	IN	OUT	struct ifreq	*rq,
-	IN	INT			cmd);
-
-
-#ifdef CONFIG_STA_SUPPORT
-INT rt28xx_sta_ioctl(
-	IN	struct net_device	*net_dev,
-	IN	OUT	struct ifreq	*rq,
-	IN	INT			cmd);
-#endif // CONFIG_STA_SUPPORT //
-
-BOOLEAN RT28XXSecurityKeyAdd(
-	IN		PRTMP_ADAPTER		pAd,
-	IN		ULONG				apidx,
-	IN		ULONG				KeyIdx,
-	IN		MAC_TABLE_ENTRY 	*pEntry);
-
-////////////////////////////////////////
-PNDIS_PACKET GetPacketFromRxRing(
-	IN		PRTMP_ADAPTER	pAd,
-	OUT		PRT28XX_RXD_STRUC	pSaveRxD,
-	OUT		BOOLEAN			*pbReschedule,
-	IN OUT	UINT32			*pRxPending);
-
-
-void kill_thread_task(PRTMP_ADAPTER pAd);
-
-void tbtt_tasklet(unsigned long data);
-
-
-VOID AsicTurnOffRFClk(
-	IN PRTMP_ADAPTER    pAd,
-	IN	UCHAR           Channel);
-
-VOID AsicTurnOnRFClk(
-	IN PRTMP_ADAPTER 	pAd,
-	IN	UCHAR			Channel);
-
-#ifdef RT30xx
-NTSTATUS RT30xxWriteRFRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			RegID,
-	IN	UCHAR			Value);
-
-NTSTATUS RT30xxReadRFRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			RegID,
-	IN	PUCHAR			pValue);
-
-//2008/09/11:KH add to support efuse<--
-UCHAR eFuseReadRegisters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT Offset,
-	IN	USHORT Length,
-	OUT	USHORT* pData);
-
-VOID eFuseReadPhysical(
-	IN	PRTMP_ADAPTER	pAd,
-  	IN	PUSHORT lpInBuffer,
-  	IN	ULONG nInBufferSize,
-  	OUT	PUSHORT lpOutBuffer,
-  	IN	ULONG nOutBufferSize
-);
-
-NTSTATUS eFuseRead(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	OUT	PUCHAR			pData,
-	IN	USHORT			Length);
-
-VOID eFusePhysicalWriteRegisters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT Offset,
-	IN	USHORT Length,
-	OUT	USHORT* pData);
-
-NTSTATUS eFuseWriteRegisters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT Offset,
-	IN	USHORT Length,
-	IN	USHORT* pData);
-
-VOID eFuseWritePhysical(
-	IN	PRTMP_ADAPTER	pAd,
-  	PUSHORT lpInBuffer,
-	ULONG nInBufferSize,
-  	PUCHAR lpOutBuffer,
-  	ULONG nOutBufferSize
-);
-
-NTSTATUS eFuseWrite(
-   	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	PUCHAR			pData,
-	IN	USHORT			length);
-
-INT set_eFuseGetFreeBlockCount_Proc(
-   	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT set_eFusedump_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT set_eFuseLoadFromBin_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-NTSTATUS eFuseWriteRegistersFromBin(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT Offset,
-	IN	USHORT Length,
-	IN	USHORT* pData);
-
-VOID eFusePhysicalReadRegisters(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT Offset,
-	IN	USHORT Length,
-	OUT	USHORT* pData);
-
-NDIS_STATUS NICLoadEEPROM(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN bNeedLoadEEPROM(
-	IN	PRTMP_ADAPTER	pAd);
-//2008/09/11:KH add to support efuse-->
-#endif // RT30xx //
-
-#ifdef RT30xx
-// add by johnli, RF power sequence setup
-VOID RT30xxLoadRFNormalModeSetup(
-	IN PRTMP_ADAPTER 	pAd);
-
-VOID RT30xxLoadRFSleepModeSetup(
-	IN PRTMP_ADAPTER 	pAd);
-
-VOID RT30xxReverseRFSleepModeSetup(
-	IN PRTMP_ADAPTER 	pAd);
-// end johnli
-#endif // RT30xx //
-
-#ifdef RT2870
-//
-// Function Prototype in rtusb_bulk.c
-//
-VOID	RTUSBInitTxDesc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTX_CONTEXT		pTxContext,
-	IN	UCHAR			BulkOutPipeId,
-	IN	usb_complete_t	Func);
-
-VOID	RTUSBInitHTTxDesc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PHT_TX_CONTEXT	pTxContext,
-	IN	UCHAR			BulkOutPipeId,
-	IN	ULONG			BulkOutSize,
-	IN	usb_complete_t	Func);
-
-VOID	RTUSBInitRxDesc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PRX_CONTEXT		pRxContext);
-
-VOID RTUSBCleanUpDataBulkOutQueue(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBCancelPendingBulkOutIRP(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBBulkOutDataPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BulkOutPipeId,
-	IN	UCHAR			Index);
-
-VOID RTUSBBulkOutNullFrame(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBBulkOutRTSFrame(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBCancelPendingBulkInIRP(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBCancelPendingIRPs(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBBulkOutMLMEPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index);
-
-VOID RTUSBBulkOutPsPoll(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBCleanUpMLMEBulkOutQueue(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBKickBulkOut(
-	IN	PRTMP_ADAPTER pAd);
-
-VOID	RTUSBBulkReceive(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID DoBulkIn(
-	IN RTMP_ADAPTER *pAd);
-
-VOID RTUSBInitRxDesc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PRX_CONTEXT		pRxContext);
-
-VOID RTUSBBulkRxHandle(
-	IN unsigned long data);
-
-//
-// Function Prototype in rtusb_io.c
-//
-NTSTATUS RTUSBMultiRead(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	OUT	PUCHAR			pData,
-	IN	USHORT			length);
-
-NTSTATUS RTUSBMultiWrite(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	PUCHAR			pData,
-	IN	USHORT			length);
-
-NTSTATUS RTUSBMultiWrite_OneByte(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	PUCHAR			pData);
-
-NTSTATUS RTUSBReadBBPRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Id,
-	IN	PUCHAR			pValue);
-
-NTSTATUS RTUSBWriteBBPRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Id,
-	IN	UCHAR			Value);
-
-NTSTATUS RTUSBWriteRFRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UINT32			Value);
-
-NTSTATUS RTUSB_VendorRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UINT32			TransferFlags,
-	IN	UCHAR			ReservedBits,
-	IN	UCHAR			Request,
-	IN	USHORT			Value,
-	IN	USHORT			Index,
-	IN	PVOID			TransferBuffer,
-	IN	UINT32			TransferBufferLength);
-
-NTSTATUS RTUSBReadEEPROM(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	OUT	PUCHAR			pData,
-	IN	USHORT			length);
-
-NTSTATUS RTUSBWriteEEPROM(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	PUCHAR			pData,
-	IN	USHORT			length);
-
-VOID RTUSBPutToSleep(
-	IN	PRTMP_ADAPTER	pAd);
-
-NTSTATUS RTUSBWakeUp(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID RTUSBInitializeCmdQ(
-	IN	PCmdQ	cmdq);
-
-NDIS_STATUS	RTUSBEnqueueCmdFromNdis(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	NDIS_OID		Oid,
-	IN	BOOLEAN			SetInformation,
-	IN	PVOID			pInformationBuffer,
-	IN	UINT32			InformationBufferLength);
-
-NDIS_STATUS RTUSBEnqueueInternalCmd(
-	IN	PRTMP_ADAPTER	pAd,
-	IN NDIS_OID			Oid,
-	IN PVOID			pInformationBuffer,
-	IN UINT32			InformationBufferLength);
-
-VOID RTUSBDequeueCmd(
-	IN	PCmdQ		cmdq,
-	OUT	PCmdQElmt	*pcmdqelmt);
-
-INT RTUSBCmdThread(
-	IN OUT PVOID Context);
-
-INT TimerQThread(
-	IN OUT PVOID Context);
-
-RT2870_TIMER_ENTRY *RT2870_TimerQ_Insert(
-	IN RTMP_ADAPTER *pAd,
-	IN RALINK_TIMER_STRUCT *pTimer);
-
-BOOLEAN RT2870_TimerQ_Remove(
-	IN RTMP_ADAPTER *pAd,
-	IN RALINK_TIMER_STRUCT *pTimer);
-
-void RT2870_TimerQ_Exit(
-	IN RTMP_ADAPTER *pAd);
-
-void RT2870_TimerQ_Init(
-	IN RTMP_ADAPTER *pAd);
-
-VOID RT2870_BssBeaconExit(
-	IN RTMP_ADAPTER *pAd);
-
-VOID RT2870_BssBeaconStop(
-	IN RTMP_ADAPTER *pAd);
-
-VOID RT2870_BssBeaconStart(
-	IN RTMP_ADAPTER * pAd);
-
-VOID RT2870_BssBeaconInit(
-	IN RTMP_ADAPTER *pAd);
-
-VOID RT2870_WatchDog(
-	IN RTMP_ADAPTER *pAd);
-
-NTSTATUS RTUSBWriteMACRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	IN	UINT32			Value);
-
-NTSTATUS RTUSBReadMACRegister(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	USHORT			Offset,
-	OUT	PUINT32			pValue);
-
-NTSTATUS RTUSBSingleWrite(
-	IN 	RTMP_ADAPTER 	*pAd,
-	IN	USHORT			Offset,
-	IN	USHORT			Value);
-
-NTSTATUS RTUSBFirmwareRun(
-	IN	PRTMP_ADAPTER	pAd);
-
-NTSTATUS RTUSBFirmwareWrite(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR		pFwImage,
-	IN ULONG		FwLen);
-
-NTSTATUS	RTUSBFirmwareOpmode(
-	IN	PRTMP_ADAPTER	pAd,
-	OUT	PUINT32			pValue);
-
-NTSTATUS	RTUSBVenderReset(
-	IN	PRTMP_ADAPTER	pAd);
-
-NDIS_STATUS RTUSBSetHardWareRegister(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PVOID			pBuf);
-
-NDIS_STATUS RTUSBQueryHardWareRegister(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PVOID			pBuf);
-
-VOID CMDHandler(
-    IN PRTMP_ADAPTER pAd);
-
-
-NDIS_STATUS	 CreateThreads(
-	IN	struct net_device *net_dev );
-
-
-VOID MacTableInitialize(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID MlmeSetPsm(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT psm);
-
-NDIS_STATUS RTMPWPAAddKeyProc(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PVOID           pBuf);
-
-VOID AsicRxAntEvalAction(
-	IN PRTMP_ADAPTER pAd);
-
-void append_pkt(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pHeader802_3,
-    IN  UINT            HdrLen,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize,
-	OUT  PNDIS_PACKET	*ppPacket);
-
-UINT deaggregate_AMSDU_announce(
-	IN	PRTMP_ADAPTER	pAd,
-	PNDIS_PACKET		pPacket,
-	IN	PUCHAR			pData,
-	IN	ULONG			DataSize);
-
-NDIS_STATUS	RTMPCheckRxError(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PHEADER_802_11	pHeader,
-	IN	PRXWI_STRUC	pRxWI,
-	IN	PRT28XX_RXD_STRUC	pRxINFO);
-
-
-VOID RTUSBMlmeHardTransmit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PMGMT_STRUC		pMgmt);
-
-INT MlmeThread(
-	IN PVOID Context);
-
-//
-// Function Prototype in rtusb_data.c
-//
-NDIS_STATUS	RTUSBFreeDescriptorRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			BulkOutPipeId,
-	IN	UINT32			NumberRequired);
-
-
-BOOLEAN	RTUSBNeedQueueBackForAgg(
-	IN RTMP_ADAPTER *pAd,
-	IN UCHAR		BulkOutPipeId);
-
-
-VOID RTMPWriteTxInfo(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PTXINFO_STRUC 	pTxInfo,
-	IN	  USHORT		USBDMApktLen,
-	IN	  BOOLEAN		bWiv,
-	IN	  UCHAR			QueueSel,
-	IN	  UCHAR			NextValid,
-	IN	  UCHAR			TxBurst);
-
-//
-// Function Prototype in cmm_data_2870.c
-//
-USHORT RtmpUSB_WriteSubTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	BOOLEAN			bIsLast,
-	OUT	USHORT			*FreeNumber);
-
-USHORT RtmpUSB_WriteSingleTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	BOOLEAN			bIsLast,
-	OUT	USHORT			*FreeNumber);
-
-USHORT	RtmpUSB_WriteFragTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	UCHAR			fragNum,
-	OUT	USHORT			*FreeNumber);
-
-USHORT RtmpUSB_WriteMultiTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	UCHAR			frameNum,
-	OUT	USHORT			*FreeNumber);
-
-VOID RtmpUSB_FinalWriteTxResource(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	USHORT			totalMPDUSize,
-	IN	USHORT			TxIdx);
-
-VOID RtmpUSBDataLastTxIdx(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			QueIdx,
-	IN	USHORT			TxIdx);
-
-VOID RtmpUSBDataKickOut(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk,
-	IN	UCHAR			QueIdx);
-
-
-int RtmpUSBMgmtKickOut(
-	IN RTMP_ADAPTER 	*pAd,
-	IN UCHAR 			QueIdx,
-	IN PNDIS_PACKET		pPacket,
-	IN PUCHAR			pSrcBufVA,
-	IN UINT 			SrcBufLen);
-
-VOID RtmpUSBNullFrameKickOut(
-	IN RTMP_ADAPTER *pAd,
-	IN UCHAR		QueIdx,
-	IN UCHAR		*pNullFrame,
-	IN UINT32		frameLen);
-
-VOID RT28xxUsbStaAsicForceWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN BOOLEAN       bFromTx);
-
-VOID RT28xxUsbStaAsicSleepThenAutoWakeup(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT TbttNumToNextWakeUp);
-
-VOID RT28xxUsbMlmeRadioOn(
-	IN PRTMP_ADAPTER pAd);
-
-VOID RT28xxUsbMlmeRadioOFF(
-	IN PRTMP_ADAPTER pAd);
-#endif // RT2870 //
-
-////////////////////////////////////////
-
-VOID QBSS_LoadInit(
- 	IN		RTMP_ADAPTER	*pAd);
-
-UINT32 QBSS_LoadElementAppend(
- 	IN		RTMP_ADAPTER	*pAd,
-	OUT		UINT8			*buf_p);
-
-VOID QBSS_LoadUpdate(
- 	IN		RTMP_ADAPTER	*pAd);
-
-///////////////////////////////////////
-INT RTMPShowCfgValue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pName,
-	IN	PUCHAR			pBuf);
-
-PCHAR   RTMPGetRalinkAuthModeStr(
-    IN  NDIS_802_11_AUTHENTICATION_MODE authMode);
-
-PCHAR   RTMPGetRalinkEncryModeStr(
-    IN  USHORT encryMode);
-//////////////////////////////////////
-
-#ifdef CONFIG_STA_SUPPORT
-VOID AsicStaBbpTuning(
-	IN PRTMP_ADAPTER pAd);
-
-BOOLEAN StaAddMacTableEntry(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PMAC_TABLE_ENTRY	pEntry,
-	IN  UCHAR				MaxSupportedRateIn500Kbps,
-	IN  HT_CAPABILITY_IE	*pHtCapability,
-	IN  UCHAR				HtCapabilityLen,
-	IN  USHORT        		CapabilityInfo);
-#endif // CONFIG_STA_SUPPORT //
-
-void RTMP_IndicateMediaState(
-	IN	PRTMP_ADAPTER	pAd);
-
-VOID ReSyncBeaconTime(
-	IN  PRTMP_ADAPTER   pAd);
-
-VOID RTMPSetAGCInitValue(
-	IN PRTMP_ADAPTER	pAd,
-	IN UCHAR			BandWidth);
-
-int rt28xx_close(IN PNET_DEV dev);
-int rt28xx_open(IN PNET_DEV dev);
-
-__inline INT VIRTUAL_IF_UP(PRTMP_ADAPTER pAd)
-{
-extern VOID MeshMakeBeacon(IN PRTMP_ADAPTER pAd, IN UCHAR idx);
-extern VOID MeshUpdateBeaconFrame(IN PRTMP_ADAPTER pAd, IN UCHAR idx);
-
-	if (VIRTUAL_IF_NUM(pAd) == 0)
-	{
-		if (rt28xx_open(pAd->net_dev) != 0)
-			return -1;
-	}
-	else
-	{
-	}
-	VIRTUAL_IF_INC(pAd);
-	return 0;
-}
-
-__inline VOID VIRTUAL_IF_DOWN(PRTMP_ADAPTER pAd)
-{
-	VIRTUAL_IF_DEC(pAd);
-	if (VIRTUAL_IF_NUM(pAd) == 0)
-		rt28xx_close(pAd->net_dev);
-	return;
-}
-
-
-#endif  // __RTMP_H__
-
+#include "../rt2870/rtmp.h"
diff --git a/drivers/staging/rt3070/rtmp_ckipmic.h b/drivers/staging/rt3070/rtmp_ckipmic.h
index a3d949a..4956093 100644
--- a/drivers/staging/rt3070/rtmp_ckipmic.h
+++ b/drivers/staging/rt3070/rtmp_ckipmic.h
@@ -1,113 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtmp_ckipmic.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-*/
-#ifndef	__RTMP_CKIPMIC_H__
-#define	__RTMP_CKIPMIC_H__
-
-typedef	struct	_MIC_CONTEXT	{
-	/* --- MMH context                            */
-	UCHAR		CK[16];				/* the key                                    */
-	UCHAR		coefficient[16];	/* current aes counter mode coefficients      */
-	ULONGLONG	accum;				/* accumulated mic, reduced to u32 in final() */
-	UINT		position;			/* current position (byte offset) in message  */
-	UCHAR		part[4];			/* for conversion of message to u32 for mmh   */
-}	MIC_CONTEXT, *PMIC_CONTEXT;
-
-VOID	CKIP_key_permute(
-	OUT	UCHAR	*PK,			/* output permuted key */
-	IN	UCHAR	*CK,			/* input CKIP key */
-	IN	UCHAR	toDsFromDs,		/* input toDs/FromDs bits */
-	IN	UCHAR	*piv);			/* input pointer to IV */
-
-VOID	RTMPCkipMicInit(
-	IN	PMIC_CONTEXT		pContext,
-	IN	PUCHAR				CK);
-
-VOID RTMPMicUpdate(
-    IN  PMIC_CONTEXT        pContext,
-    IN  PUCHAR              pOctets,
-    IN  INT                 len);
-
-ULONG RTMPMicGetCoefficient(
-    IN  PMIC_CONTEXT         pContext);
-
-VOID xor_128(
-    IN  PUCHAR              a,
-    IN  PUCHAR              b,
-    OUT PUCHAR              out);
-
-UCHAR RTMPCkipSbox(
-    IN  UCHAR               a);
-
-VOID xor_32(
-    IN  PUCHAR              a,
-    IN  PUCHAR              b,
-    OUT PUCHAR              out);
-
-VOID next_key(
-    IN  PUCHAR              key,
-    IN  INT                 round);
-
-VOID byte_sub(
-    IN  PUCHAR              in,
-    OUT PUCHAR              out);
-
-VOID shift_row(
-    IN  PUCHAR              in,
-    OUT PUCHAR              out);
-
-VOID mix_column(
-    IN  PUCHAR              in,
-    OUT PUCHAR              out);
-
-VOID RTMPAesEncrypt(
-    IN  PUCHAR              key,
-    IN  PUCHAR              data,
-    IN  PUCHAR              ciphertext);
-
-VOID RTMPMicFinal(
-    IN  PMIC_CONTEXT        pContext,
-    OUT UCHAR               digest[4]);
-
-VOID RTMPCkipInsertCMIC(
-    IN  PRTMP_ADAPTER   pAd,
-    OUT PUCHAR          pMIC,
-    IN  PUCHAR          p80211hdr,
-    IN  PNDIS_PACKET    pPacket,
-    IN  PCIPHER_KEY     pKey,
-    IN  PUCHAR          mic_snap);
-
-#endif //__RTMP_CKIPMIC_H__
+#include "../rt2870/rtmp_ckipmic.h"
diff --git a/drivers/staging/rt3070/rtmp_def.h b/drivers/staging/rt3070/rtmp_def.h
index 2599f7c..fa3b6b5 100644
--- a/drivers/staging/rt3070/rtmp_def.h
+++ b/drivers/staging/rt3070/rtmp_def.h
@@ -1,1559 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    rtmp_def.h
-
-    Abstract:
-    Miniport related definition header
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Paul Lin    08-01-2002    created
-    John Chang  08-05-2003    add definition for 11g & other drafts
-*/
-#ifndef __RTMP_DEF_H__
-#define __RTMP_DEF_H__
-
-#include "oid.h"
-
-#undef AP_WSC_INCLUDED
-#undef STA_WSC_INCLUDED
-#undef WSC_INCLUDED
-
-
-#ifdef CONFIG_STA_SUPPORT
-#endif // CONFIG_STA_SUPPORT //
-
-#if defined(AP_WSC_INCLUDED) || defined(STA_WSC_INCLUDED)
-#define WSC_INCLUDED
-#endif
-//
-//  Debug information verbosity: lower values indicate higher urgency
-//
-#define RT_DEBUG_OFF        0
-#define RT_DEBUG_ERROR      1
-#define RT_DEBUG_WARN       2
-#define RT_DEBUG_TRACE      3
-#define RT_DEBUG_INFO       4
-#define RT_DEBUG_LOUD       5
-
-#define NIC_TAG             ((ULONG)'0682')
-#define NIC_DBG_STRING      ("**RT28xx**")
-
-#ifdef SNMP_SUPPORT
-// for snmp
-// to get manufacturer OUI, kathy, 2008_0220
-#define ManufacturerOUI_LEN			3
-#define ManufacturerNAME			("Ralink Technology Company.")
-#define	ResourceTypeIdName			("Ralink_ID")
-#endif
-
-
-//#define PACKED
-
-#define RALINK_2883_VERSION		((UINT32)0x28830300)
-#define RALINK_2880E_VERSION	((UINT32)0x28720200)
-#define RALINK_3070_VERSION		((UINT32)0x30700200)
-
-//
-// NDIS version in use by the NIC driver.
-// The high byte is the major version. The low byte is the minor version.
-//
-#ifdef  NDIS51_MINIPORT
-#define NIC_DRIVER_VERSION      0x0501
-#else
-#define NIC_DRIVER_VERSION      0x0500
-#endif
-
-//
-// NDIS media type, current is ethernet, change if native wireless supported
-//
-#define NIC_MEDIA_TYPE          NdisMedium802_3
-#define NIC_PCI_HDR_LENGTH      0xe2
-#define NIC_MAX_PACKET_SIZE     2304
-#define NIC_HEADER_SIZE         14
-#define MAX_MAP_REGISTERS_NEEDED 32
-#define MIN_MAP_REGISTERS_NEEDED 2   //Todo: should consider fragment issue.
-
-//
-// interface type, we use PCI
-//
-#define NIC_INTERFACE_TYPE      NdisInterfacePci
-#define NIC_INTERRUPT_MODE      NdisInterruptLevelSensitive
-
-//
-// buffer size passed in NdisMQueryAdapterResources
-// We should only need three adapter resources (IO, interrupt and memory),
-// Some devices get extra resources, so have room for 10 resources
-//                    UF_SIZE   (sizeof(NDIS_RESOURCE_LIST) + (10*sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR)))
-
-
-#define NIC_RESOURCE_B//
-// IO space length
-//
-#define NIC_MAP_IOSPACE_LENGTH  sizeof(CSR_STRUC)
-
-#define MAX_RX_PKT_LEN	1520
-
-//
-// Entry number for each DMA descriptor ring
-//
-
-
-#ifdef RT2870
-#define TX_RING_SIZE            8 // 1
-#define PRIO_RING_SIZE          8
-#define MGMT_RING_SIZE       32 // PRIO_RING_SIZE
-#define RX_RING_SIZE            8
-#define MAX_TX_PROCESS          4
-#define LOCAL_TXBUF_SIZE        2048
-#endif // RT2870 //
-
-#ifdef MULTIPLE_CARD_SUPPORT
-// MC: Multple Cards
-#define MAX_NUM_OF_MULTIPLE_CARD		32
-#endif // MULTIPLE_CARD_SUPPORT //
-
-#define MAX_RX_PROCESS          128 //64 //32
-#define NUM_OF_LOCAL_TXBUF      2
-#define TXD_SIZE                16
-#define TXWI_SIZE               16
-#define RXD_SIZE               	16
-#define RXWI_SIZE             	16
-// TXINFO_SIZE + TXWI_SIZE + 802.11 Header Size + AMSDU sub frame header
-#define TX_DMA_1ST_BUFFER_SIZE  96    // only the 1st physical buffer is pre-allocated
-#define MGMT_DMA_BUFFER_SIZE    1536 //2048
-#define RX_BUFFER_AGGRESIZE     3840 //3904 //3968 //4096 //2048 //4096
-#define RX_BUFFER_NORMSIZE      3840 //3904 //3968 //4096 //2048 //4096
-#define TX_BUFFER_NORMSIZE		RX_BUFFER_NORMSIZE
-#define MAX_FRAME_SIZE          2346                    // Maximum 802.11 frame size
-#define MAX_AGGREGATION_SIZE    3840 //3904 //3968 //4096
-#define MAX_NUM_OF_TUPLE_CACHE  2
-#define MAX_MCAST_LIST_SIZE     32
-#define MAX_LEN_OF_VENDOR_DESC  64
-//#define MAX_SIZE_OF_MCAST_PSQ   (NUM_OF_LOCAL_TXBUF >> 2) // AP won't spend more than 1/4 of total buffers on M/BCAST PSQ
-#define MAX_SIZE_OF_MCAST_PSQ               32
-
-#define MAX_RX_PROCESS_CNT	(RX_RING_SIZE)
-
-
-#define MAX_PACKETS_IN_QUEUE				(512) //(512)    // to pass WMM A5-WPAPSK
-#define MAX_PACKETS_IN_MCAST_PS_QUEUE		32
-#define MAX_PACKETS_IN_PS_QUEUE				128	//32
-#define WMM_NUM_OF_AC                       4  /* AC0, AC1, AC2, and AC3 */
-
-
-//2008/09/11:KH add to support efuse<--
-#define MAX_EEPROM_BIN_FILE_SIZE					1024
-//2008/09/11:KH add to support efuse-->
-
-// RxFilter
-#define STANORMAL	 0x17f97
-#define APNORMAL	 0x15f97
-//
-//  RTMP_ADAPTER flags
-//
-#define fRTMP_ADAPTER_MAP_REGISTER          0x00000001
-#define fRTMP_ADAPTER_INTERRUPT_IN_USE      0x00000002
-#define fRTMP_ADAPTER_HARDWARE_ERROR        0x00000004
-#define fRTMP_ADAPTER_SCATTER_GATHER        0x00000008
-#define fRTMP_ADAPTER_SEND_PACKET_ERROR     0x00000010
-#define fRTMP_ADAPTER_MLME_RESET_IN_PROGRESS 0x00000020
-#define fRTMP_ADAPTER_HALT_IN_PROGRESS      0x00000040
-#define fRTMP_ADAPTER_RESET_IN_PROGRESS     0x00000080
-#define fRTMP_ADAPTER_NIC_NOT_EXIST         0x00000100
-#define fRTMP_ADAPTER_TX_RING_ALLOCATED     0x00000200
-#define fRTMP_ADAPTER_REMOVE_IN_PROGRESS    0x00000400
-#define fRTMP_ADAPTER_MIMORATE_INUSED       0x00000800
-#define fRTMP_ADAPTER_RX_RING_ALLOCATED     0x00001000
-#define fRTMP_ADAPTER_INTERRUPT_ACTIVE      0x00002000
-#define fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS  0x00004000
-#define	fRTMP_ADAPTER_REASSOC_IN_PROGRESS	0x00008000
-#define	fRTMP_ADAPTER_MEDIA_STATE_PENDING	0x00010000
-#define	fRTMP_ADAPTER_RADIO_OFF				0x00020000
-#define fRTMP_ADAPTER_BULKOUT_RESET			0x00040000
-#define	fRTMP_ADAPTER_BULKIN_RESET			0x00080000
-#define fRTMP_ADAPTER_RDG_ACTIVE			0x00100000
-#define fRTMP_ADAPTER_DYNAMIC_BE_TXOP_ACTIVE 0x00200000
-#define fRTMP_ADAPTER_SCAN_2040 			0x04000000
-#define	fRTMP_ADAPTER_RADIO_MEASUREMENT		0x08000000
-
-#define fRTMP_ADAPTER_START_UP         		0x10000000	//Devive already initialized and enabled Tx/Rx.
-#define fRTMP_ADAPTER_MEDIA_STATE_CHANGE    0x20000000
-#define fRTMP_ADAPTER_IDLE_RADIO_OFF        0x40000000
-
-// Lock bit for accessing different ring buffers
-//#define fRTMP_ADAPTER_TX_RING_BUSY        0x80000000
-//#define fRTMP_ADAPTER_MGMT_RING_BUSY      0x40000000
-//#define fRTMP_ADAPTER_ATIM_RING_BUSY      0x20000000
-//#define fRTMP_ADAPTER_RX_RING_BUSY        0x10000000
-
-// Lock bit for accessing different queue
-//#define   fRTMP_ADAPTER_TX_QUEUE_BUSY     0x08000000
-//#define   fRTMP_ADAPTER_MGMT_QUEUE_BUSY   0x04000000
-
-//
-//  STA operation status flags
-//
-#define fOP_STATUS_INFRA_ON                 0x00000001
-#define fOP_STATUS_ADHOC_ON                 0x00000002
-#define fOP_STATUS_BG_PROTECTION_INUSED     0x00000004
-#define fOP_STATUS_SHORT_SLOT_INUSED        0x00000008
-#define fOP_STATUS_SHORT_PREAMBLE_INUSED    0x00000010
-#define fOP_STATUS_RECEIVE_DTIM             0x00000020
-//#define fOP_STATUS_TX_RATE_SWITCH_ENABLED   0x00000040
-#define fOP_STATUS_MEDIA_STATE_CONNECTED    0x00000080
-#define fOP_STATUS_WMM_INUSED               0x00000100
-#define fOP_STATUS_AGGREGATION_INUSED       0x00000200
-#define fOP_STATUS_DOZE                     0x00000400  // debug purpose
-#define fOP_STATUS_PIGGYBACK_INUSED         0x00000800  // piggy-back, and aggregation
-#define fOP_STATUS_APSD_INUSED				0x00001000
-#define fOP_STATUS_TX_AMSDU_INUSED			0x00002000
-#define fOP_STATUS_MAX_RETRY_ENABLED		0x00004000
-#define fOP_STATUS_WAKEUP_NOW               0x00008000
-#define fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE       0x00020000
-
-#ifdef DOT11N_DRAFT3
-#define fOP_STATUS_SCAN_2040               	    0x00040000
-#endif // DOT11N_DRAFT3 //
-
-#define CCKSETPROTECT		0x1
-#define OFDMSETPROTECT		0x2
-#define MM20SETPROTECT		0x4
-#define MM40SETPROTECT		0x8
-#define GF20SETPROTECT		0x10
-#define GR40SETPROTECT		0x20
-#define ALLN_SETPROTECT		(GR40SETPROTECT | GF20SETPROTECT | MM40SETPROTECT | MM20SETPROTECT)
-
-//
-//  AP's client table operation status flags
-//
-#define fCLIENT_STATUS_WMM_CAPABLE          0x00000001  // CLIENT can parse QOS DATA frame
-#define fCLIENT_STATUS_AGGREGATION_CAPABLE  0x00000002  // CLIENT can receive Ralink's proprietary TX aggregation frame
-#define fCLIENT_STATUS_PIGGYBACK_CAPABLE    0x00000004  // CLIENT support piggy-back
-#define fCLIENT_STATUS_AMSDU_INUSED			0x00000008
-#define fCLIENT_STATUS_SGI20_CAPABLE		0x00000010
-#define fCLIENT_STATUS_SGI40_CAPABLE		0x00000020
-#define fCLIENT_STATUS_TxSTBC_CAPABLE		0x00000040
-#define fCLIENT_STATUS_RxSTBC_CAPABLE		0x00000080
-#define fCLIENT_STATUS_HTC_CAPABLE			0x00000100
-#define fCLIENT_STATUS_RDG_CAPABLE			0x00000200
-#define fCLIENT_STATUS_MCSFEEDBACK_CAPABLE  0x00000400
-#define fCLIENT_STATUS_APSD_CAPABLE         0x00000800  /* UAPSD STATION */
-
-#ifdef DOT11N_DRAFT3
-#define fCLIENT_STATUS_BSSCOEXIST_CAPABLE	0x00001000
-#endif // DOT11N_DRAFT3 //
-
-#define fCLIENT_STATUS_RALINK_CHIPSET		0x00100000
-//
-//  STA configuration flags
-//
-//#define fSTA_CFG_ENABLE_TX_BURST          0x00000001
-
-// 802.11n Operating Mode Definition. 0-3 also used in ASICUPdateProtect switch case
-#define HT_NO_PROTECT	0
-#define HT_LEGACY_PROTECT	1
-#define HT_40_PROTECT	2
-#define HT_2040_PROTECT	3
-#define HT_RTSCTS_6M	7
-//following is our own definition in order to turn on our ASIC protection register in INFRASTRUCTURE.
-#define HT_ATHEROS	8
-#define HT_FORCERTSCTS	9	// Force turn on RTS/CTS first. then go to evaluate if this force RTS is necessary.
-
-//
-// RX Packet Filter control flags. Apply on pAd->PacketFilter
-//
-#define fRX_FILTER_ACCEPT_DIRECT            NDIS_PACKET_TYPE_DIRECTED
-#define fRX_FILTER_ACCEPT_MULTICAST         NDIS_PACKET_TYPE_MULTICAST
-#define fRX_FILTER_ACCEPT_BROADCAST         NDIS_PACKET_TYPE_BROADCAST
-#define fRX_FILTER_ACCEPT_ALL_MULTICAST     NDIS_PACKET_TYPE_ALL_MULTICAST
-
-//
-// Error code section
-//
-// NDIS_ERROR_CODE_ADAPTER_NOT_FOUND
-#define ERRLOG_READ_PCI_SLOT_FAILED     0x00000101L
-#define ERRLOG_WRITE_PCI_SLOT_FAILED    0x00000102L
-#define ERRLOG_VENDOR_DEVICE_NOMATCH    0x00000103L
-
-// NDIS_ERROR_CODE_ADAPTER_DISABLED
-#define ERRLOG_BUS_MASTER_DISABLED      0x00000201L
-
-// NDIS_ERROR_CODE_UNSUPPORTED_CONFIGURATION
-#define ERRLOG_INVALID_SPEED_DUPLEX     0x00000301L
-#define ERRLOG_SET_SECONDARY_FAILED     0x00000302L
-
-// NDIS_ERROR_CODE_OUT_OF_RESOURCES
-#define ERRLOG_OUT_OF_MEMORY            0x00000401L
-#define ERRLOG_OUT_OF_SHARED_MEMORY     0x00000402L
-#define ERRLOG_OUT_OF_MAP_REGISTERS     0x00000403L
-#define ERRLOG_OUT_OF_BUFFER_POOL       0x00000404L
-#define ERRLOG_OUT_OF_NDIS_BUFFER       0x00000405L
-#define ERRLOG_OUT_OF_PACKET_POOL       0x00000406L
-#define ERRLOG_OUT_OF_NDIS_PACKET       0x00000407L
-#define ERRLOG_OUT_OF_LOOKASIDE_MEMORY  0x00000408L
-
-// NDIS_ERROR_CODE_HARDWARE_FAILURE
-#define ERRLOG_SELFTEST_FAILED          0x00000501L
-#define ERRLOG_INITIALIZE_ADAPTER       0x00000502L
-#define ERRLOG_REMOVE_MINIPORT          0x00000503L
-
-// NDIS_ERROR_CODE_RESOURCE_CONFLICT
-#define ERRLOG_MAP_IO_SPACE             0x00000601L
-#define ERRLOG_QUERY_ADAPTER_RESOURCES  0x00000602L
-#define ERRLOG_NO_IO_RESOURCE           0x00000603L
-#define ERRLOG_NO_INTERRUPT_RESOURCE    0x00000604L
-#define ERRLOG_NO_MEMORY_RESOURCE       0x00000605L
-
-
-// WDS definition
-#define	MAX_WDS_ENTRY               4
-#define WDS_PAIRWISE_KEY_OFFSET     60    // WDS links uses pairwise key#60 ~ 63 in ASIC pairwise key table
-
-#define	WDS_DISABLE_MODE            0
-#define	WDS_RESTRICT_MODE           1
-#define	WDS_BRIDGE_MODE             2
-#define	WDS_REPEATER_MODE           3
-#define	WDS_LAZY_MODE               4
-
-
-#define MAX_MESH_NUM				0
-
-#define MAX_APCLI_NUM				0
-
-#define MAX_MBSSID_NUM				1
-#ifdef MBSS_SUPPORT
-#undef	MAX_MBSSID_NUM
-#define MAX_MBSSID_NUM				(8 - MAX_MESH_NUM - MAX_APCLI_NUM)
-#endif // MBSS_SUPPORT //
-
-/* sanity check for apidx */
-#define MBSS_MR_APIDX_SANITY_CHECK(apidx) \
-    { if (apidx > MAX_MBSSID_NUM) { \
-          printk("%s> Error! apidx = %d > MAX_MBSSID_NUM!\n", __FUNCTION__, apidx); \
-	  apidx = MAIN_MBSSID; } }
-
-#define VALID_WCID(_wcid)	((_wcid) > 0 && (_wcid) < MAX_LEN_OF_MAC_TABLE )
-
-#define MAIN_MBSSID                 0
-#define FIRST_MBSSID                1
-
-
-#define MAX_BEACON_SIZE				512
-// If the MAX_MBSSID_NUM is larger than 6,
-// it shall reserve some WCID space(wcid 222~253) for beacon frames.
-// -	these wcid 238~253 are reserved for beacon#6(ra6).
-// -	these wcid 222~237 are reserved for beacon#7(ra7).
-#if defined(MAX_MBSSID_NUM) && (MAX_MBSSID_NUM == 8)
-#define HW_RESERVED_WCID	222
-#elif defined(MAX_MBSSID_NUM) && (MAX_MBSSID_NUM == 7)
-#define HW_RESERVED_WCID	238
-#else
-#define HW_RESERVED_WCID	255
-#endif
-
-// Then dedicate wcid of DFS and Carrier-Sense.
-#define DFS_CTS_WCID 		(HW_RESERVED_WCID - 1)
-#define CS_CTS_WCID 		(HW_RESERVED_WCID - 2)
-#define LAST_SPECIFIC_WCID	(HW_RESERVED_WCID - 2)
-
-// If MAX_MBSSID_NUM is 8, the maximum available wcid for the associated STA is 211.
-// If MAX_MBSSID_NUM is 7, the maximum available wcid for the associated STA is 228.
-#define MAX_AVAILABLE_CLIENT_WCID	(LAST_SPECIFIC_WCID - MAX_MBSSID_NUM - 1)
-
-// TX need WCID to find Cipher Key
-// these wcid 212 ~ 219 are reserved for bc/mc packets if MAX_MBSSID_NUM is 8.
-#define GET_GroupKey_WCID(__wcid, __bssidx) \
-	{										\
-		__wcid = LAST_SPECIFIC_WCID - (MAX_MBSSID_NUM) + __bssidx;	\
-	}
-
-#define IsGroupKeyWCID(__wcid) (((__wcid) < LAST_SPECIFIC_WCID) && ((__wcid) >= (LAST_SPECIFIC_WCID - (MAX_MBSSID_NUM))))
-
-
-// definition to support multiple BSSID
-#define BSS0                            0
-#define BSS1                            1
-#define BSS2                            2
-#define BSS3                            3
-#define BSS4                            4
-#define BSS5                            5
-#define BSS6                            6
-#define BSS7                            7
-
-
-//============================================================
-// Length definitions
-#define PEER_KEY_NO                     2
-#define MAC_ADDR_LEN                    6
-#define TIMESTAMP_LEN                   8
-#define MAX_LEN_OF_SUPPORTED_RATES      MAX_LENGTH_OF_SUPPORT_RATES // 1, 2, 5.5, 11, 6, 9, 12, 18, 24, 36, 48, 54
-#define MAX_LEN_OF_KEY                  32      // 32 octets == 256 bits, Redefine for WPA
-#define MAX_NUM_OF_CHANNELS             MAX_NUM_OF_CHS      // 14 channels @2.4G +  12@UNII + 4 @MMAC + 11 @HiperLAN2 + 7 @Japan + 1 as NULL termination
-#define MAX_NUM_OF_11JCHANNELS             20      // 14 channels @2.4G +  12@UNII + 4 @MMAC + 11 @HiperLAN2 + 7 @Japan + 1 as NULL termination
-#define MAX_LEN_OF_SSID                 32
-#define CIPHER_TEXT_LEN                 128
-#define HASH_TABLE_SIZE                 256
-#define MAX_VIE_LEN                     1024   // New for WPA cipher suite variable IE sizes.
-#define MAX_SUPPORT_MCS             32
-
-//============================================================
-// ASIC WCID Table definition.
-//============================================================
-#define BSSID_WCID		1	// in infra mode, always put bssid with this WCID
-#define MCAST_WCID	0x0
-#define BSS0Mcast_WCID	0x0
-#define BSS1Mcast_WCID	0xf8
-#define BSS2Mcast_WCID	0xf9
-#define BSS3Mcast_WCID	0xfa
-#define BSS4Mcast_WCID	0xfb
-#define BSS5Mcast_WCID	0xfc
-#define BSS6Mcast_WCID	0xfd
-#define BSS7Mcast_WCID	0xfe
-#define RESERVED_WCID		0xff
-
-#define MAX_NUM_OF_ACL_LIST				MAX_NUMBER_OF_ACL
-
-#define MAX_LEN_OF_MAC_TABLE            MAX_NUMBER_OF_MAC // if MAX_MBSSID_NUM is 8, this value can't be larger than 211
-
-#if MAX_LEN_OF_MAC_TABLE>MAX_AVAILABLE_CLIENT_WCID
-#error MAX_LEN_OF_MAC_TABLE can not be larger than MAX_AVAILABLE_CLIENT_WCID!!!!
-#endif
-
-#define MAX_NUM_OF_WDS_LINK_PERBSSID	            3
-#define MAX_NUM_OF_WDS_LINK	            (MAX_NUM_OF_WDS_LINK_PERBSSID*MAX_MBSSID_NUM)
-#define MAX_NUM_OF_EVENT                MAX_NUMBER_OF_EVENT
-#define WDS_LINK_START_WCID				(MAX_LEN_OF_MAC_TABLE-1)
-
-#define NUM_OF_TID			8
-#define MAX_AID_BA                    4
-#define MAX_LEN_OF_BA_REC_TABLE          ((NUM_OF_TID * MAX_LEN_OF_MAC_TABLE)/2)//   (NUM_OF_TID*MAX_AID_BA + 32)	 //Block ACK recipient
-#define MAX_LEN_OF_BA_ORI_TABLE          ((NUM_OF_TID * MAX_LEN_OF_MAC_TABLE)/2)//   (NUM_OF_TID*MAX_AID_BA + 32)   // Block ACK originator
-#define MAX_LEN_OF_BSS_TABLE             64
-#define MAX_REORDERING_MPDU_NUM			 512
-
-// key related definitions
-#define SHARE_KEY_NUM                   4
-#define MAX_LEN_OF_SHARE_KEY            16    // byte count
-#define MAX_LEN_OF_PEER_KEY             16    // byte count
-#define PAIRWISE_KEY_NUM                64    // in MAC ASIC pairwise key table
-#define GROUP_KEY_NUM                   4
-#define PMK_LEN                         32
-#define WDS_PAIRWISE_KEY_OFFSET         60    // WDS links uses pairwise key#60 ~ 63 in ASIC pairwise key table
-#define	PMKID_NO                        4     // Number of PMKID saved supported
-#define MAX_LEN_OF_MLME_BUFFER          2048
-
-// power status related definitions
-#define PWR_ACTIVE                      0
-#define PWR_SAVE                        1
-#define PWR_MMPS                        2			//MIMO power save
-//#define PWR_UNKNOWN                   2
-
-// Auth and Assoc mode related definitions
-#define AUTH_MODE_OPEN                  0x00
-#define AUTH_MODE_KEY                   0x01
-//#define AUTH_MODE_AUTO_SWITCH         0x03
-//#define AUTH_MODE_DEAUTH              0x04
-//#define AUTH_MODE_UPLAYER             0x05 // reserved for 802.11i use
-
-// BSS Type definitions
-#define BSS_ADHOC                       0  // = Ndis802_11IBSS
-#define BSS_INFRA                       1  // = Ndis802_11Infrastructure
-#define BSS_ANY                         2  // = Ndis802_11AutoUnknown
-#define BSS_MONITOR			            3  // = Ndis802_11Monitor
-
-
-// Reason code definitions
-#define REASON_RESERVED                 0
-#define REASON_UNSPECIFY                1
-#define REASON_NO_LONGER_VALID          2
-#define REASON_DEAUTH_STA_LEAVING       3
-#define REASON_DISASSOC_INACTIVE        4
-#define REASON_DISASSPC_AP_UNABLE       5
-#define REASON_CLS2ERR                  6
-#define REASON_CLS3ERR                  7
-#define REASON_DISASSOC_STA_LEAVING     8
-#define REASON_STA_REQ_ASSOC_NOT_AUTH   9
-#define REASON_INVALID_IE               13
-#define REASON_MIC_FAILURE              14
-#define REASON_4_WAY_TIMEOUT            15
-#define REASON_GROUP_KEY_HS_TIMEOUT     16
-#define REASON_IE_DIFFERENT             17
-#define REASON_MCIPHER_NOT_VALID        18
-#define REASON_UCIPHER_NOT_VALID        19
-#define REASON_AKMP_NOT_VALID           20
-#define REASON_UNSUPPORT_RSNE_VER       21
-#define REASON_INVALID_RSNE_CAP         22
-#define REASON_8021X_AUTH_FAIL          23
-#define REASON_CIPHER_SUITE_REJECTED    24
-#define REASON_DECLINED                 37
-
-#define REASON_QOS_UNSPECIFY              32
-#define REASON_QOS_LACK_BANDWIDTH         33
-#define REASON_POOR_CHANNEL_CONDITION     34
-#define REASON_QOS_OUTSIDE_TXOP_LIMITION  35
-#define REASON_QOS_QSTA_LEAVING_QBSS      36
-#define REASON_QOS_UNWANTED_MECHANISM     37
-#define REASON_QOS_MECH_SETUP_REQUIRED    38
-#define REASON_QOS_REQUEST_TIMEOUT        39
-#define REASON_QOS_CIPHER_NOT_SUPPORT     45
-
-// Status code definitions
-#define MLME_SUCCESS                    0
-#define MLME_UNSPECIFY_FAIL             1
-#define MLME_CANNOT_SUPPORT_CAP         10
-#define MLME_REASSOC_DENY_ASSOC_EXIST   11
-#define MLME_ASSOC_DENY_OUT_SCOPE       12
-#define MLME_ALG_NOT_SUPPORT            13
-#define MLME_SEQ_NR_OUT_OF_SEQUENCE     14
-#define MLME_REJ_CHALLENGE_FAILURE      15
-#define MLME_REJ_TIMEOUT                  16
-#define MLME_ASSOC_REJ_UNABLE_HANDLE_STA  17
-#define MLME_ASSOC_REJ_DATA_RATE          18
-
-#define MLME_ASSOC_REJ_NO_EXT_RATE        22
-#define MLME_ASSOC_REJ_NO_EXT_RATE_PBCC   23
-#define MLME_ASSOC_REJ_NO_CCK_OFDM        24
-
-#define MLME_QOS_UNSPECIFY                32
-#define MLME_REQUEST_DECLINED             37
-#define MLME_REQUEST_WITH_INVALID_PARAM   38
-#define MLME_DLS_NOT_ALLOW_IN_QBSS        48
-#define MLME_DEST_STA_NOT_IN_QBSS         49
-#define MLME_DEST_STA_IS_NOT_A_QSTA       50
-
-#define MLME_INVALID_FORMAT             0x51
-#define MLME_FAIL_NO_RESOURCE           0x52
-#define MLME_STATE_MACHINE_REJECT       0x53
-#define MLME_MAC_TABLE_FAIL             0x54
-
-// IE code
-#define IE_SSID                         0
-#define IE_SUPP_RATES                   1
-#define IE_FH_PARM                      2
-#define IE_DS_PARM                      3
-#define IE_CF_PARM                      4
-#define IE_TIM                          5
-#define IE_IBSS_PARM                    6
-#define IE_COUNTRY                      7     // 802.11d
-#define IE_802_11D_REQUEST              10    // 802.11d
-#define IE_QBSS_LOAD                    11    // 802.11e d9
-#define IE_EDCA_PARAMETER               12    // 802.11e d9
-#define IE_TSPEC                        13    // 802.11e d9
-#define IE_TCLAS                        14    // 802.11e d9
-#define IE_SCHEDULE                     15    // 802.11e d9
-#define IE_CHALLENGE_TEXT               16
-#define IE_POWER_CONSTRAINT             32    // 802.11h d3.3
-#define IE_POWER_CAPABILITY             33    // 802.11h d3.3
-#define IE_TPC_REQUEST                  34    // 802.11h d3.3
-#define IE_TPC_REPORT                   35    // 802.11h d3.3
-#define IE_SUPP_CHANNELS                36    // 802.11h d3.3
-#define IE_CHANNEL_SWITCH_ANNOUNCEMENT  37    // 802.11h d3.3
-#define IE_MEASUREMENT_REQUEST          38    // 802.11h d3.3
-#define IE_MEASUREMENT_REPORT           39    // 802.11h d3.3
-#define IE_QUIET                        40    // 802.11h d3.3
-#define IE_IBSS_DFS                     41    // 802.11h d3.3
-#define IE_ERP                          42    // 802.11g
-#define IE_TS_DELAY                     43    // 802.11e d9
-#define IE_TCLAS_PROCESSING             44    // 802.11e d9
-#define IE_QOS_CAPABILITY               46    // 802.11e d6
-#define IE_HT_CAP                       45    // 802.11n d1. HT CAPABILITY. ELEMENT ID TBD
-#define IE_AP_CHANNEL_REPORT			51    // 802.11k d6
-#define IE_HT_CAP2                         52    // 802.11n d1. HT CAPABILITY. ELEMENT ID TBD
-#define IE_RSN                          48    // 802.11i d3.0
-#define IE_WPA2                         48    // WPA2
-#define IE_EXT_SUPP_RATES               50    // 802.11g
-#define IE_SUPP_REG_CLASS               59    // 802.11y. Supported regulatory classes.
-#define IE_EXT_CHANNEL_SWITCH_ANNOUNCEMENT	60	// 802.11n
-#define IE_ADD_HT                         61    // 802.11n d1. ADDITIONAL HT CAPABILITY. ELEMENT ID TBD
-#define IE_ADD_HT2                        53    // 802.11n d1. ADDITIONAL HT CAPABILITY. ELEMENT ID TBD
-
-
-// For 802.11n D3.03
-//#define IE_NEW_EXT_CHA_OFFSET             62    // 802.11n d1. New extension channel offset elemet
-#define IE_SECONDARY_CH_OFFSET		62	// 802.11n D3.03	Secondary Channel Offset element
-#define IE_WAPI							68		// WAPI information element
-#define IE_2040_BSS_COEXIST               72    // 802.11n D3.0.3
-#define IE_2040_BSS_INTOLERANT_REPORT     73    // 802.11n D3.03
-#define IE_OVERLAPBSS_SCAN_PARM           74    // 802.11n D3.03
-#define IE_EXT_CAPABILITY                127   // 802.11n D3.03
-
-
-#define IE_WPA                          221   // WPA
-#define IE_VENDOR_SPECIFIC              221   // Wifi WMM (WME)
-
-#define OUI_BROADCOM_HT              51   //
-#define OUI_BROADCOM_HTADD              52   //
-#define OUI_PREN_HT_CAP              51   //
-#define OUI_PREN_ADD_HT              52   //
-
-// CCX information
-#define IE_AIRONET_CKIP                 133   // CCX1.0 ID 85H for CKIP
-#define IE_AP_TX_POWER                  150   // CCX 2.0 for AP transmit power
-#define IE_MEASUREMENT_CAPABILITY       221   // CCX 2.0
-#define IE_CCX_V2                       221
-#define IE_AIRONET_IPADDRESS            149   // CCX ID 95H for IP Address
-#define IE_AIRONET_CCKMREASSOC          156   // CCX ID 9CH for CCKM Reassociation Request element
-#define CKIP_NEGOTIATION_LENGTH         30
-#define AIRONET_IPADDRESS_LENGTH        10
-#define AIRONET_CCKMREASSOC_LENGTH      24
-
-// ========================================================
-// MLME state machine definition
-// ========================================================
-
-// STA MLME state mahcines
-#define ASSOC_STATE_MACHINE             1
-#define AUTH_STATE_MACHINE              2
-#define AUTH_RSP_STATE_MACHINE          3
-#define SYNC_STATE_MACHINE              4
-#define MLME_CNTL_STATE_MACHINE         5
-#define WPA_PSK_STATE_MACHINE           6
-#define LEAP_STATE_MACHINE              7
-#define AIRONET_STATE_MACHINE           8
-#define ACTION_STATE_MACHINE           9
-
-// AP MLME state machines
-#define AP_ASSOC_STATE_MACHINE          11
-#define AP_AUTH_STATE_MACHINE           12
-#define AP_AUTH_RSP_STATE_MACHINE       13
-#define AP_SYNC_STATE_MACHINE           14
-#define AP_CNTL_STATE_MACHINE           15
-#define AP_WPA_STATE_MACHINE            16
-
-#define WSC_STATE_MACHINE            17
-#define WSC_UPNP_STATE_MACHINE		    18
-
-
-
-#ifdef QOS_DLS_SUPPORT
-#define DLS_STATE_MACHINE               26
-#endif // QOS_DLS_SUPPORT //
-
-//
-// STA's CONTROL/CONNECT state machine: states, events, total function #
-//
-#define CNTL_IDLE                       0
-#define CNTL_WAIT_DISASSOC              1
-#define CNTL_WAIT_JOIN                  2
-#define CNTL_WAIT_REASSOC               3
-#define CNTL_WAIT_START                 4
-#define CNTL_WAIT_AUTH                  5
-#define CNTL_WAIT_ASSOC                 6
-#define CNTL_WAIT_AUTH2                 7
-#define CNTL_WAIT_OID_LIST_SCAN         8
-#define CNTL_WAIT_OID_DISASSOC          9
-#ifdef RT2870
-#define CNTL_WAIT_SCAN_FOR_CONNECT      10
-#endif // RT2870 //
-
-#define MT2_ASSOC_CONF                  34
-#define MT2_AUTH_CONF                   35
-#define MT2_DEAUTH_CONF                 36
-#define MT2_DISASSOC_CONF               37
-#define MT2_REASSOC_CONF                38
-#define MT2_PWR_MGMT_CONF               39
-#define MT2_JOIN_CONF                   40
-#define MT2_SCAN_CONF                   41
-#define MT2_START_CONF                  42
-#define MT2_GET_CONF                    43
-#define MT2_SET_CONF                    44
-#define MT2_RESET_CONF                  45
-#define MT2_MLME_ROAMING_REQ            52
-
-#define CNTL_FUNC_SIZE                  1
-
-//
-// STA's ASSOC state machine: states, events, total function #
-//
-#define ASSOC_IDLE                      0
-#define ASSOC_WAIT_RSP                  1
-#define REASSOC_WAIT_RSP                2
-#define DISASSOC_WAIT_RSP               3
-#define MAX_ASSOC_STATE                 4
-
-#define ASSOC_MACHINE_BASE              0
-#define MT2_MLME_ASSOC_REQ              0
-#define MT2_MLME_REASSOC_REQ            1
-#define MT2_MLME_DISASSOC_REQ           2
-#define MT2_PEER_DISASSOC_REQ           3
-#define MT2_PEER_ASSOC_REQ              4
-#define MT2_PEER_ASSOC_RSP              5
-#define MT2_PEER_REASSOC_REQ            6
-#define MT2_PEER_REASSOC_RSP            7
-#define MT2_DISASSOC_TIMEOUT            8
-#define MT2_ASSOC_TIMEOUT               9
-#define MT2_REASSOC_TIMEOUT             10
-#define MAX_ASSOC_MSG                   11
-
-#define ASSOC_FUNC_SIZE                 (MAX_ASSOC_STATE * MAX_ASSOC_MSG)
-
-//
-// ACT state machine: states, events, total function #
-//
-#define ACT_IDLE                      0
-#define MAX_ACT_STATE                 1
-
-#define ACT_MACHINE_BASE              0
-
-//Those PEER_xx_CATE number is based on real Categary value in IEEE spec. Please don'es modify it by your self.
-//Category
-#define MT2_PEER_SPECTRUM_CATE              0
-#define MT2_PEER_QOS_CATE              1
-#define MT2_PEER_DLS_CATE             2
-#define MT2_PEER_BA_CATE             3
-#define MT2_PEER_PUBLIC_CATE             4
-#define MT2_PEER_RM_CATE             5
-#define MT2_PEER_HT_CATE             7	//	7.4.7
-#define MAX_PEER_CATE_MSG                   7
-#define MT2_MLME_ADD_BA_CATE             8
-#define MT2_MLME_ORI_DELBA_CATE             9
-#define MT2_MLME_REC_DELBA_CATE             10
-#define MT2_MLME_QOS_CATE              11
-#define MT2_MLME_DLS_CATE             12
-#define MT2_ACT_INVALID             13
-#define MAX_ACT_MSG                   14
-
-//Category field
-#define CATEGORY_SPECTRUM		0
-#define CATEGORY_QOS			1
-#define CATEGORY_DLS			2
-#define CATEGORY_BA			3
-#define CATEGORY_PUBLIC		4
-#define CATEGORY_RM			5
-#define CATEGORY_HT			7
-
-
-// DLS Action frame definition
-#define ACTION_DLS_REQUEST			0
-#define ACTION_DLS_RESPONSE			1
-#define ACTION_DLS_TEARDOWN			2
-
-//Spectrum  Action field value 802.11h 7.4.1
-#define SPEC_MRQ	0	// Request
-#define SPEC_MRP	1	//Report
-#define SPEC_TPCRQ	2
-#define SPEC_TPCRP	3
-#define SPEC_CHANNEL_SWITCH	4
-
-
-//BA  Action field value
-#define ADDBA_REQ	0
-#define ADDBA_RESP	1
-#define DELBA   2
-
-//Public's  Action field value in Public Category.  Some in 802.11y and some in 11n
-#define ACTION_BSS_2040_COEXIST				0	// 11n
-#define ACTION_DSE_ENABLEMENT					1	// 11y D9.0
-#define ACTION_DSE_DEENABLEMENT				2	// 11y D9.0
-#define ACTION_DSE_REG_LOCATION_ANNOUNCE	3	// 11y D9.0
-#define ACTION_EXT_CH_SWITCH_ANNOUNCE		4	// 11y D9.0
-#define ACTION_DSE_MEASUREMENT_REQ			5	// 11y D9.0
-#define ACTION_DSE_MEASUREMENT_REPORT		6	// 11y D9.0
-#define ACTION_MEASUREMENT_PILOT_ACTION		7  	// 11y D9.0
-#define ACTION_DSE_POWER_CONSTRAINT			8	// 11y D9.0
-
-
-//HT  Action field value
-#define NOTIFY_BW_ACTION				0
-#define SMPS_ACTION						1
-#define PSMP_ACTION   					2
-#define SETPCO_ACTION					3
-#define MIMO_CHA_MEASURE_ACTION			4
-#define MIMO_N_BEACONFORM				5
-#define MIMO_BEACONFORM					6
-#define ANTENNA_SELECT					7
-#define HT_INFO_EXCHANGE				8
-
-#define ACT_FUNC_SIZE                 (MAX_ACT_STATE * MAX_ACT_MSG)
-//
-// STA's AUTHENTICATION state machine: states, evvents, total function #
-//
-#define AUTH_REQ_IDLE                   0
-#define AUTH_WAIT_SEQ2                  1
-#define AUTH_WAIT_SEQ4                  2
-#define MAX_AUTH_STATE                  3
-
-#define AUTH_MACHINE_BASE               0
-#define MT2_MLME_AUTH_REQ               0
-#define MT2_PEER_AUTH_EVEN              1
-#define MT2_AUTH_TIMEOUT                2
-#define MAX_AUTH_MSG                    3
-
-#define AUTH_FUNC_SIZE                  (MAX_AUTH_STATE * MAX_AUTH_MSG)
-
-//
-// STA's AUTH_RSP state machine: states, events, total function #
-//
-#define AUTH_RSP_IDLE                   0
-#define AUTH_RSP_WAIT_CHAL              1
-#define MAX_AUTH_RSP_STATE              2
-
-#define AUTH_RSP_MACHINE_BASE           0
-#define MT2_AUTH_CHALLENGE_TIMEOUT      0
-#define MT2_PEER_AUTH_ODD               1
-#define MT2_PEER_DEAUTH                 2
-#define MAX_AUTH_RSP_MSG                3
-
-#define AUTH_RSP_FUNC_SIZE              (MAX_AUTH_RSP_STATE * MAX_AUTH_RSP_MSG)
-
-//
-// STA's SYNC state machine: states, events, total function #
-//
-#define SYNC_IDLE                       0  // merge NO_BSS,IBSS_IDLE,IBSS_ACTIVE and BSS in to 1 state
-#define JOIN_WAIT_BEACON                1
-#define SCAN_LISTEN                     2
-#define MAX_SYNC_STATE                  3
-
-#define SYNC_MACHINE_BASE               0
-#define MT2_MLME_SCAN_REQ               0
-#define MT2_MLME_JOIN_REQ               1
-#define MT2_MLME_START_REQ              2
-#define MT2_PEER_BEACON                 3
-#define MT2_PEER_PROBE_RSP              4
-#define MT2_PEER_ATIM                   5
-#define MT2_SCAN_TIMEOUT                6
-#define MT2_BEACON_TIMEOUT              7
-#define MT2_ATIM_TIMEOUT                8
-#define MT2_PEER_PROBE_REQ              9
-#define MAX_SYNC_MSG                    10
-
-#define SYNC_FUNC_SIZE                  (MAX_SYNC_STATE * MAX_SYNC_MSG)
-
-//Messages for the DLS state machine
-#define DLS_IDLE						0
-#define MAX_DLS_STATE					1
-
-#define DLS_MACHINE_BASE				0
-#define MT2_MLME_DLS_REQ			    0
-#define MT2_PEER_DLS_REQ			    1
-#define MT2_PEER_DLS_RSP			    2
-#define MT2_MLME_DLS_TEAR_DOWN		    3
-#define MT2_PEER_DLS_TEAR_DOWN		    4
-#define MAX_DLS_MSG				        5
-
-#define DLS_FUNC_SIZE					(MAX_DLS_STATE * MAX_DLS_MSG)
-
-//
-// STA's WPA-PSK State machine: states, events, total function #
-//
-#define WPA_PSK_IDLE					0
-#define MAX_WPA_PSK_STATE				1
-
-#define WPA_MACHINE_BASE                0
-#define MT2_EAPPacket                   0
-#define MT2_EAPOLStart                  1
-#define MT2_EAPOLLogoff                 2
-#define MT2_EAPOLKey                    3
-#define MT2_EAPOLASFAlert               4
-#define MAX_WPA_PSK_MSG                 5
-
-#define	WPA_PSK_FUNC_SIZE				(MAX_WPA_PSK_STATE * MAX_WPA_PSK_MSG)
-
-//
-// STA's CISCO-AIRONET State machine: states, events, total function #
-//
-#define AIRONET_IDLE					0
-#define	AIRONET_SCANNING				1
-#define MAX_AIRONET_STATE				2
-
-#define AIRONET_MACHINE_BASE		    0
-#define MT2_AIRONET_MSG				    0
-#define MT2_AIRONET_SCAN_REQ		    1
-#define MT2_AIRONET_SCAN_DONE		    2
-#define MAX_AIRONET_MSG				    3
-
-#define	AIRONET_FUNC_SIZE				(MAX_AIRONET_STATE * MAX_AIRONET_MSG)
-
-//
-// WSC State machine: states, events, total function #
-//
-
-//
-// AP's CONTROL/CONNECT state machine: states, events, total function #
-//
-#define AP_CNTL_FUNC_SIZE               1
-
-//
-// AP's ASSOC state machine: states, events, total function #
-//
-#define AP_ASSOC_IDLE                   0
-#define AP_MAX_ASSOC_STATE              1
-
-#define AP_ASSOC_MACHINE_BASE           0
-#define APMT2_MLME_DISASSOC_REQ         0
-#define APMT2_PEER_DISASSOC_REQ         1
-#define APMT2_PEER_ASSOC_REQ            2
-#define APMT2_PEER_REASSOC_REQ          3
-#define APMT2_CLS3ERR                   4
-#define AP_MAX_ASSOC_MSG                5
-
-#define AP_ASSOC_FUNC_SIZE              (AP_MAX_ASSOC_STATE * AP_MAX_ASSOC_MSG)
-
-//
-// AP's AUTHENTICATION state machine: states, events, total function #
-//
-#define AP_AUTH_REQ_IDLE                0
-#define AP_MAX_AUTH_STATE               1
-
-#define AP_AUTH_MACHINE_BASE            0
-#define APMT2_MLME_DEAUTH_REQ           0
-#define APMT2_CLS2ERR                   1
-#define AP_MAX_AUTH_MSG                 2
-
-#define AP_AUTH_FUNC_SIZE               (AP_MAX_AUTH_STATE * AP_MAX_AUTH_MSG)
-
-//
-// AP's AUTH-RSP state machine: states, events, total function #
-//
-#define AP_AUTH_RSP_IDLE                0
-#define AP_MAX_AUTH_RSP_STATE           1
-
-#define AP_AUTH_RSP_MACHINE_BASE        0
-#define APMT2_AUTH_CHALLENGE_TIMEOUT    0
-#define APMT2_PEER_AUTH_ODD             1
-#define APMT2_PEER_DEAUTH               2
-#define AP_MAX_AUTH_RSP_MSG             3
-
-#define AP_AUTH_RSP_FUNC_SIZE           (AP_MAX_AUTH_RSP_STATE * AP_MAX_AUTH_RSP_MSG)
-
-//
-// AP's SYNC state machine: states, events, total function #
-//
-#define AP_SYNC_IDLE                    0
-#define AP_SCAN_LISTEN					1
-#define AP_MAX_SYNC_STATE               2
-
-#define AP_SYNC_MACHINE_BASE            0
-#define APMT2_PEER_PROBE_REQ            0
-#define APMT2_PEER_BEACON               1
-#define APMT2_MLME_SCAN_REQ				2
-#define APMT2_PEER_PROBE_RSP			3
-#define APMT2_SCAN_TIMEOUT				4
-#define APMT2_MLME_SCAN_CNCL			5
-#define AP_MAX_SYNC_MSG                 6
-
-#define AP_SYNC_FUNC_SIZE               (AP_MAX_SYNC_STATE * AP_MAX_SYNC_MSG)
-
-//
-// AP's WPA state machine: states, events, total function #
-//
-#define AP_WPA_PTK                      0
-#define AP_MAX_WPA_PTK_STATE            1
-
-#define AP_WPA_MACHINE_BASE             0
-#define APMT2_EAPPacket                 0
-#define APMT2_EAPOLStart                1
-#define APMT2_EAPOLLogoff               2
-#define APMT2_EAPOLKey                  3
-#define APMT2_EAPOLASFAlert             4
-#define AP_MAX_WPA_MSG                  5
-
-#define AP_WPA_FUNC_SIZE                (AP_MAX_WPA_PTK_STATE * AP_MAX_WPA_MSG)
-
-
-
-// =============================================================================
-
-// value domain of 802.11 header FC.Tyte, which is b3..b2 of the 1st-byte of MAC header
-#define BTYPE_MGMT                  0
-#define BTYPE_CNTL                  1
-#define BTYPE_DATA                  2
-
-// value domain of 802.11 MGMT frame's FC.subtype, which is b7..4 of the 1st-byte of MAC header
-#define SUBTYPE_ASSOC_REQ           0
-#define SUBTYPE_ASSOC_RSP           1
-#define SUBTYPE_REASSOC_REQ         2
-#define SUBTYPE_REASSOC_RSP         3
-#define SUBTYPE_PROBE_REQ           4
-#define SUBTYPE_PROBE_RSP           5
-#define SUBTYPE_BEACON              8
-#define SUBTYPE_ATIM                9
-#define SUBTYPE_DISASSOC            10
-#define SUBTYPE_AUTH                11
-#define SUBTYPE_DEAUTH              12
-#define SUBTYPE_ACTION              13
-#define SUBTYPE_ACTION_NO_ACK              14
-
-// value domain of 802.11 CNTL frame's FC.subtype, which is b7..4 of the 1st-byte of MAC header
-#define SUBTYPE_WRAPPER       	7
-#define SUBTYPE_BLOCK_ACK_REQ       8
-#define SUBTYPE_BLOCK_ACK           9
-#define SUBTYPE_PS_POLL             10
-#define SUBTYPE_RTS                 11
-#define SUBTYPE_CTS                 12
-#define SUBTYPE_ACK                 13
-#define SUBTYPE_CFEND               14
-#define SUBTYPE_CFEND_CFACK         15
-
-// value domain of 802.11 DATA frame's FC.subtype, which is b7..4 of the 1st-byte of MAC header
-#define SUBTYPE_DATA                0
-#define SUBTYPE_DATA_CFACK          1
-#define SUBTYPE_DATA_CFPOLL         2
-#define SUBTYPE_DATA_CFACK_CFPOLL   3
-#define SUBTYPE_NULL_FUNC           4
-#define SUBTYPE_CFACK               5
-#define SUBTYPE_CFPOLL              6
-#define SUBTYPE_CFACK_CFPOLL        7
-#define SUBTYPE_QDATA               8
-#define SUBTYPE_QDATA_CFACK         9
-#define SUBTYPE_QDATA_CFPOLL        10
-#define SUBTYPE_QDATA_CFACK_CFPOLL  11
-#define SUBTYPE_QOS_NULL            12
-#define SUBTYPE_QOS_CFACK           13
-#define SUBTYPE_QOS_CFPOLL          14
-#define SUBTYPE_QOS_CFACK_CFPOLL    15
-
-// ACK policy of QOS Control field bit 6:5
-#define NORMAL_ACK                  0x00  // b6:5 = 00
-#define NO_ACK                      0x20  // b6:5 = 01
-#define NO_EXPLICIT_ACK             0x40  // b6:5 = 10
-#define BLOCK_ACK                   0x60  // b6:5 = 11
-
-//
-// rtmp_data.c use these definition
-//
-#define LENGTH_802_11               24
-#define LENGTH_802_11_AND_H         30
-#define LENGTH_802_11_CRC_H         34
-#define LENGTH_802_11_CRC           28
-#define LENGTH_802_11_WITH_ADDR4    30
-#define LENGTH_802_3                14
-#define LENGTH_802_3_TYPE           2
-#define LENGTH_802_1_H              8
-#define LENGTH_EAPOL_H              4
-#define LENGTH_WMMQOS_H				2
-#define LENGTH_CRC                  4
-#define MAX_SEQ_NUMBER              0x0fff
-#define LENGTH_802_3_NO_TYPE		12
-#define LENGTH_802_1Q				4 /* VLAN related */
-
-// STA_CSR4.field.TxResult
-#define TX_RESULT_SUCCESS           0
-#define TX_RESULT_ZERO_LENGTH       1
-#define TX_RESULT_UNDER_RUN         2
-#define TX_RESULT_OHY_ERROR         4
-#define TX_RESULT_RETRY_FAIL        6
-
-// All PHY rate summary in TXD
-// Preamble MODE in TxD
-#define MODE_CCK	0
-#define MODE_OFDM   1
-#ifdef DOT11_N_SUPPORT
-#define MODE_HTMIX	2
-#define MODE_HTGREENFIELD	3
-#endif // DOT11_N_SUPPORT //
-// MCS for CCK.  BW.SGI.STBC are reserved
-#define MCS_LONGP_RATE_1                      0	 // long preamble CCK 1Mbps
-#define MCS_LONGP_RATE_2                      1	// long preamble CCK 1Mbps
-#define MCS_LONGP_RATE_5_5                    2
-#define MCS_LONGP_RATE_11                     3
-#define MCS_SHORTP_RATE_1                      4	 // long preamble CCK 1Mbps. short is forbidden in 1Mbps
-#define MCS_SHORTP_RATE_2                      5	// short preamble CCK 2Mbps
-#define MCS_SHORTP_RATE_5_5                    6
-#define MCS_SHORTP_RATE_11                     7
-// To send duplicate legacy OFDM. set BW=BW_40.  SGI.STBC are reserved
-#define MCS_RATE_6                      0   // legacy OFDM
-#define MCS_RATE_9                      1   // OFDM
-#define MCS_RATE_12                     2   // OFDM
-#define MCS_RATE_18                     3   // OFDM
-#define MCS_RATE_24                     4  // OFDM
-#define MCS_RATE_36                     5   // OFDM
-#define MCS_RATE_48                     6  // OFDM
-#define MCS_RATE_54                     7 // OFDM
-// HT
-#define MCS_0		0	// 1S
-#define MCS_1		1
-#define MCS_2		2
-#define MCS_3		3
-#define MCS_4		4
-#define MCS_5		5
-#define MCS_6		6
-#define MCS_7		7
-#define MCS_8		8	// 2S
-#define MCS_9		9
-#define MCS_10		10
-#define MCS_11		11
-#define MCS_12		12
-#define MCS_13		13
-#define MCS_14		14
-#define MCS_15		15
-#define MCS_16		16	// 3*3
-#define MCS_17		17
-#define MCS_18		18
-#define MCS_19		19
-#define MCS_20		20
-#define MCS_21		21
-#define MCS_22		22
-#define MCS_23		23
-#define MCS_32		32
-#define MCS_AUTO		33
-
-#ifdef DOT11_N_SUPPORT
-// OID_HTPHYMODE
-// MODE
-#define HTMODE_MM	0
-#define HTMODE_GF	1
-#endif // DOT11_N_SUPPORT //
-
-// Fixed Tx MODE - HT, CCK or OFDM
-#define FIXED_TXMODE_HT		0
-#define FIXED_TXMODE_CCK	1
-#define FIXED_TXMODE_OFDM 	2
-// BW
-#define BW_20		BAND_WIDTH_20
-#define BW_40		BAND_WIDTH_40
-#define BW_BOTH		BAND_WIDTH_BOTH
-#define BW_10		BAND_WIDTH_10	// 802.11j has 10MHz. This definition is for internal usage. doesn't fill in the IE or other field.
-
-#ifdef DOT11_N_SUPPORT
-// SHORTGI
-#define GI_400		GAP_INTERVAL_400	// only support in HT mode
-#define GI_BOTH		GAP_INTERVAL_BOTH
-#endif // DOT11_N_SUPPORT //
-#define GI_800		GAP_INTERVAL_800
-// STBC
-#define STBC_NONE	0
-#ifdef DOT11_N_SUPPORT
-#define STBC_USE	1	// limited use in rt2860b phy
-#define RXSTBC_ONE	1	// rx support of one spatial stream
-#define RXSTBC_TWO	2	// rx support of 1 and 2 spatial stream
-#define RXSTBC_THR	3	// rx support of 1~3 spatial stream
-// MCS FEEDBACK
-#define MCSFBK_NONE	0  // not support mcs feedback /
-#define MCSFBK_RSV	1	// reserved
-#define MCSFBK_UNSOLICIT	2	// only support unsolict mcs feedback
-#define MCSFBK_MRQ	3	// response to both MRQ and unsolict mcs feedback
-
-// MIMO power safe
-#define	MMPS_STATIC	0
-#define	MMPS_DYNAMIC		1
-#define   MMPS_RSV		2
-#define MMPS_ENABLE		3
-
-
-// A-MSDU size
-#define	AMSDU_0	0
-#define	AMSDU_1		1
-
-#endif // DOT11_N_SUPPORT //
-
-// MCS use 7 bits
-#define TXRATEMIMO		0x80
-#define TXRATEMCS		0x7F
-#define TXRATEOFDM		0x7F
-#define RATE_1                      0
-#define RATE_2                      1
-#define RATE_5_5                    2
-#define RATE_11                     3
-#define RATE_6                      4   // OFDM
-#define RATE_9                      5   // OFDM
-#define RATE_12                     6   // OFDM
-#define RATE_18                     7   // OFDM
-#define RATE_24                     8   // OFDM
-#define RATE_36                     9   // OFDM
-#define RATE_48                     10  // OFDM
-#define RATE_54                     11  // OFDM
-#define RATE_FIRST_OFDM_RATE        RATE_6
-#define RATE_LAST_OFDM_RATE        	RATE_54
-#define RATE_6_5                    12  // HT mix
-#define RATE_13                     13  // HT mix
-#define RATE_19_5                   14  // HT mix
-#define RATE_26                     15  // HT mix
-#define RATE_39                     16  // HT mix
-#define RATE_52                     17  // HT mix
-#define RATE_58_5                   18  // HT mix
-#define RATE_65                     19  // HT mix
-#define RATE_78                     20  // HT mix
-#define RATE_104                    21  // HT mix
-#define RATE_117                    22  // HT mix
-#define RATE_130                    23  // HT mix
-//#define RATE_AUTO_SWITCH            255 // for StaCfg.FixedTxRate only
-#define HTRATE_0                      12
-#define RATE_FIRST_MM_RATE        HTRATE_0
-#define RATE_FIRST_HT_RATE        HTRATE_0
-#define RATE_LAST_HT_RATE        HTRATE_0
-
-// pTxWI->txop
-#define IFS_HTTXOP                 0	// The txop will be handles by ASIC.
-#define IFS_PIFS                    1
-#define IFS_SIFS                    2
-#define IFS_BACKOFF                 3
-
-// pTxD->RetryMode
-#define LONG_RETRY                  1
-#define SHORT_RETRY                 0
-
-// Country Region definition
-#define REGION_MINIMUM_BG_BAND            0
-#define REGION_0_BG_BAND                  0       // 1-11
-#define REGION_1_BG_BAND                  1       // 1-13
-#define REGION_2_BG_BAND                  2       // 10-11
-#define REGION_3_BG_BAND                  3       // 10-13
-#define REGION_4_BG_BAND                  4       // 14
-#define REGION_5_BG_BAND                  5       // 1-14
-#define REGION_6_BG_BAND                  6       // 3-9
-#define REGION_7_BG_BAND                  7       // 5-13
-#define REGION_31_BG_BAND                 31       // 5-13
-#define REGION_MAXIMUM_BG_BAND            7
-
-#define REGION_MINIMUM_A_BAND             0
-#define REGION_0_A_BAND                   0       // 36, 40, 44, 48, 52, 56, 60, 64, 149, 153, 157, 161, 165
-#define REGION_1_A_BAND                   1       // 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140
-#define REGION_2_A_BAND                   2       // 36, 40, 44, 48, 52, 56, 60, 64
-#define REGION_3_A_BAND                   3       // 52, 56, 60, 64, 149, 153, 157, 161
-#define REGION_4_A_BAND                   4       // 149, 153, 157, 161, 165
-#define REGION_5_A_BAND                   5       // 149, 153, 157, 161
-#define REGION_6_A_BAND                   6       // 36, 40, 44, 48
-#define REGION_7_A_BAND                   7       // 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 149, 153, 157, 161, 165
-#define REGION_8_A_BAND                   8       // 52, 56, 60, 64
-#define REGION_9_A_BAND                   9       // 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 132, 136, 140, 149, 153, 157, 161, 165
-#define REGION_10_A_BAND                  10	  // 36, 40, 44, 48, 149, 153, 157, 161, 165
-#define REGION_11_A_BAND                  11	  // 36, 40, 44, 48, 52, 56, 60, 64, 100, 104, 108, 112, 116, 120, 149, 153, 157, 161
-#define REGION_MAXIMUM_A_BAND             11
-
-// pTxD->CipherAlg
-#define CIPHER_NONE                 0
-#define CIPHER_WEP64                1
-#define CIPHER_WEP128               2
-#define CIPHER_TKIP                 3
-#define CIPHER_AES                  4
-#define CIPHER_CKIP64               5
-#define CIPHER_CKIP128              6
-#define CIPHER_TKIP_NO_MIC          7       // MIC appended by driver: not a valid value in hardware key table
-#define CIPHER_SMS4					8
-
-// value domain of pAd->RfIcType
-#define RFIC_2820                   1       // 2.4G 2T3R
-#define RFIC_2850                   2       // 2.4G/5G 2T3R
-#define RFIC_2720                   3       // 2.4G 1T2R
-#define RFIC_2750                   4       // 2.4G/5G 1T2R
-#define RFIC_3020                   5       // 2.4G 1T1R
-#define RFIC_2020                   6       // 2.4G B/G
-#define RFIC_3021                   7       // 2.4G 1T2R
-#define RFIC_3022                   8       // 2.4G 2T2R
-
-// LED Status.
-#define LED_LINK_DOWN               0
-#define LED_LINK_UP                 1
-#define LED_RADIO_OFF               2
-#define LED_RADIO_ON                3
-#define LED_HALT                    4
-#define LED_WPS                     5
-#define LED_ON_SITE_SURVEY          6
-#define LED_POWER_UP                7
-
-// value domain of pAd->LedCntl.LedMode and E2PROM
-#define LED_MODE_DEFAULT            0
-#define LED_MODE_TWO_LED			1
-#define LED_MODE_SIGNAL_STREGTH		8  // EEPROM define =8
-
-// RC4 init value, used fro WEP & TKIP
-#define PPPINITFCS32                0xffffffff   /* Initial FCS value */
-
-// value domain of pAd->StaCfg.PortSecured. 802.1X controlled port definition
-#define WPA_802_1X_PORT_SECURED     1
-#define WPA_802_1X_PORT_NOT_SECURED 2
-
-#define PAIRWISE_KEY                1
-#define GROUP_KEY                   2
-
-//definition of DRS
-#define MAX_STEP_OF_TX_RATE_SWITCH	32
-
-
-// pre-allocated free NDIS PACKET/BUFFER poll for internal usage
-#define MAX_NUM_OF_FREE_NDIS_PACKET 128
-
-//Block ACK
-#define MAX_TX_REORDERBUF   64
-#define MAX_RX_REORDERBUF   64
-#define DEFAULT_TX_TIMEOUT   30
-#define DEFAULT_RX_TIMEOUT   30
-
-// definition of Recipient or Originator
-#define I_RECIPIENT                  TRUE
-#define I_ORIGINATOR                   FALSE
-
-#define DEFAULT_BBP_TX_POWER        0
-#define DEFAULT_RF_TX_POWER         5
-
-#define MAX_INI_BUFFER_SIZE			4096
-#define MAX_PARAM_BUFFER_SIZE		(2048) // enough for ACL (18*64)
-											//18 : the length of Mac address acceptable format "01:02:03:04:05:06;")
-											//64 : MAX_NUM_OF_ACL_LIST
-// definition of pAd->OpMode
-#define OPMODE_STA                  0
-#define OPMODE_AP                   1
-//#define OPMODE_L3_BRG               2       // as AP and STA at the same time
-
-#ifdef RT_BIG_ENDIAN
-#define DIR_READ                    0
-#define DIR_WRITE                   1
-#define TYPE_TXD                    0
-#define TYPE_RXD                    1
-#define TYPE_TXINFO					0
-#define TYPE_RXINFO					1
-#define TYPE_TXWI					0
-#define TYPE_RXWI					1
-#endif
-
-// ========================= AP rtmp_def.h ===========================
-// value domain for pAd->EventTab.Log[].Event
-#define EVENT_RESET_ACCESS_POINT    0 // Log = "hh:mm:ss   Restart Access Point"
-#define EVENT_ASSOCIATED            1 // Log = "hh:mm:ss   STA 00:01:02:03:04:05 associated"
-#define EVENT_DISASSOCIATED         2 // Log = "hh:mm:ss   STA 00:01:02:03:04:05 left this BSS"
-#define EVENT_AGED_OUT              3 // Log = "hh:mm:ss   STA 00:01:02:03:04:05 was aged-out and removed from this BSS"
-#define EVENT_COUNTER_M             4
-#define EVENT_INVALID_PSK           5
-#define EVENT_MAX_EVENT_TYPE        6
-// ==== end of AP rtmp_def.h ============
-
-// definition RSSI Number
-#define RSSI_0					0
-#define RSSI_1					1
-#define RSSI_2					2
-
-// definition of radar detection
-#define RD_NORMAL_MODE				0	// Not found radar signal
-#define RD_SWITCHING_MODE			1	// Found radar signal, and doing channel switch
-#define RD_SILENCE_MODE				2	// After channel switch, need to be silence a while to ensure radar not found
-
-//Driver defined cid for mapping status and command.
-#define  SLEEPCID	0x11
-#define  WAKECID	0x22
-#define  QUERYPOWERCID	0x33
-#define  OWNERMCU	0x1
-#define  OWNERCPU	0x0
-
-// MBSSID definition
-#define ENTRY_NOT_FOUND             0xFF
-
-
-/* After Linux 2.6.9,
- * VLAN module use Private (from user) interface flags (netdevice->priv_flags).
- * #define IFF_802_1Q_VLAN 0x1         --    802.1Q VLAN device.  in if.h
- * ref to ip_sabotage_out() [ out->priv_flags & IFF_802_1Q_VLAN ] in br_netfilter.c
- *
- * For this reason, we MUST use EVEN value in priv_flags
- */
-#define INT_MAIN                    0x0100
-#define INT_MBSSID                  0x0200
-#define INT_WDS                     0x0300
-#define INT_APCLI                   0x0400
-#define INT_MESH                   	0x0500
-
-// Use bitmap to allow coexist of ATE_TXFRAME and ATE_RXFRAME(i.e.,to support LoopBack mode)
-#ifdef RALINK_ATE
-#define	ATE_START                   0x00   // Start ATE
-#define	ATE_STOP                    0x80   // Stop ATE
-#define	ATE_TXCONT                  0x05   // Continuous Transmit
-#define	ATE_TXCARR                  0x09   // Transmit Carrier
-#define	ATE_TXCARRSUPP              0x11   // Transmit Carrier Suppression
-#define	ATE_TXFRAME                 0x01   // Transmit Frames
-#define	ATE_RXFRAME                 0x02   // Receive Frames
-#ifdef RALINK_28xx_QA
-#define ATE_TXSTOP                  0xe2   // Stop Transmition(i.e., TXCONT, TXCARR, TXCARRSUPP, and TXFRAME)
-#define ATE_RXSTOP					0xfd   // Stop receiving Frames
-#define	BBP22_TXFRAME     			0x00   // Transmit Frames
-#define	BBP22_TXCONT_OR_CARRSUPP    0x80   // Continuous Transmit or Carrier Suppression
-#define	BBP22_TXCARR                0xc1   // Transmit Carrier
-#define	BBP24_TXCONT                0x00   // Continuous Transmit
-#define	BBP24_CARRSUPP              0x01   // Carrier Suppression
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-// WEP Key TYPE
-#define WEP_HEXADECIMAL_TYPE    0
-#define WEP_ASCII_TYPE          1
-
-
-
-// WIRELESS EVENTS definition
-/* Max number of char in custom event, refer to wireless_tools.28/wireless.20.h */
-#define IW_CUSTOM_MAX_LEN				  			255	/* In bytes */
-
-// For system event - start
-#define	IW_SYS_EVENT_FLAG_START                     0x0200
-#define	IW_ASSOC_EVENT_FLAG                         0x0200
-#define	IW_DISASSOC_EVENT_FLAG                      0x0201
-#define	IW_DEAUTH_EVENT_FLAG                      	0x0202
-#define	IW_AGEOUT_EVENT_FLAG                      	0x0203
-#define	IW_COUNTER_MEASURES_EVENT_FLAG              0x0204
-#define	IW_REPLAY_COUNTER_DIFF_EVENT_FLAG           0x0205
-#define	IW_RSNIE_DIFF_EVENT_FLAG           			0x0206
-#define	IW_MIC_DIFF_EVENT_FLAG           			0x0207
-#define IW_ICV_ERROR_EVENT_FLAG						0x0208
-#define IW_MIC_ERROR_EVENT_FLAG						0x0209
-#define IW_GROUP_HS_TIMEOUT_EVENT_FLAG				0x020A
-#define	IW_PAIRWISE_HS_TIMEOUT_EVENT_FLAG			0x020B
-#define IW_RSNIE_SANITY_FAIL_EVENT_FLAG				0x020C
-#define IW_SET_KEY_DONE_WPA1_EVENT_FLAG				0x020D
-#define IW_SET_KEY_DONE_WPA2_EVENT_FLAG				0x020E
-#define IW_STA_LINKUP_EVENT_FLAG					0x020F
-#define IW_STA_LINKDOWN_EVENT_FLAG					0x0210
-#define IW_SCAN_COMPLETED_EVENT_FLAG				0x0211
-#define IW_SCAN_ENQUEUE_FAIL_EVENT_FLAG				0x0212
-// if add new system event flag, please upadte the IW_SYS_EVENT_FLAG_END
-#define	IW_SYS_EVENT_FLAG_END                       0x0212
-#define	IW_SYS_EVENT_TYPE_NUM						(IW_SYS_EVENT_FLAG_END - IW_SYS_EVENT_FLAG_START + 1)
-// For system event - end
-
-// For spoof attack event - start
-#define	IW_SPOOF_EVENT_FLAG_START                   0x0300
-#define IW_CONFLICT_SSID_EVENT_FLAG					0x0300
-#define IW_SPOOF_ASSOC_RESP_EVENT_FLAG				0x0301
-#define IW_SPOOF_REASSOC_RESP_EVENT_FLAG			0x0302
-#define IW_SPOOF_PROBE_RESP_EVENT_FLAG				0x0303
-#define IW_SPOOF_BEACON_EVENT_FLAG					0x0304
-#define IW_SPOOF_DISASSOC_EVENT_FLAG				0x0305
-#define IW_SPOOF_AUTH_EVENT_FLAG					0x0306
-#define IW_SPOOF_DEAUTH_EVENT_FLAG					0x0307
-#define IW_SPOOF_UNKNOWN_MGMT_EVENT_FLAG			0x0308
-#define IW_REPLAY_ATTACK_EVENT_FLAG					0x0309
-// if add new spoof attack event flag, please upadte the IW_SPOOF_EVENT_FLAG_END
-#define	IW_SPOOF_EVENT_FLAG_END                     0x0309
-#define	IW_SPOOF_EVENT_TYPE_NUM						(IW_SPOOF_EVENT_FLAG_END - IW_SPOOF_EVENT_FLAG_START + 1)
-// For spoof attack event - end
-
-// For flooding attack event - start
-#define	IW_FLOOD_EVENT_FLAG_START                   0x0400
-#define IW_FLOOD_AUTH_EVENT_FLAG					0x0400
-#define IW_FLOOD_ASSOC_REQ_EVENT_FLAG				0x0401
-#define IW_FLOOD_REASSOC_REQ_EVENT_FLAG				0x0402
-#define IW_FLOOD_PROBE_REQ_EVENT_FLAG				0x0403
-#define IW_FLOOD_DISASSOC_EVENT_FLAG				0x0404
-#define IW_FLOOD_DEAUTH_EVENT_FLAG					0x0405
-#define IW_FLOOD_EAP_REQ_EVENT_FLAG					0x0406
-// if add new flooding attack event flag, please upadte the IW_FLOOD_EVENT_FLAG_END
-#define	IW_FLOOD_EVENT_FLAG_END                   	0x0406
-#define	IW_FLOOD_EVENT_TYPE_NUM						(IW_FLOOD_EVENT_FLAG_END - IW_FLOOD_EVENT_FLAG_START + 1)
-// For flooding attack - end
-
-// End - WIRELESS EVENTS definition
-
-#ifdef CONFIG_STA_SUPPORT
-// definition for DLS, kathy
-#define	MAX_NUM_OF_INIT_DLS_ENTRY   1
-#define	MAX_NUM_OF_DLS_ENTRY        MAX_NUMBER_OF_DLS_ENTRY
-
-//Block ACK , rt2860, kathy
-#define MAX_TX_REORDERBUF		64
-#define MAX_RX_REORDERBUF		64
-#define DEFAULT_TX_TIMEOUT		30
-#define DEFAULT_RX_TIMEOUT		30
-#ifndef CONFIG_AP_SUPPORT
-#define MAX_BARECI_SESSION		8
-#endif
-
-#ifndef IW_ESSID_MAX_SIZE
-/* Maximum size of the ESSID and pAd->nickname strings */
-#define IW_ESSID_MAX_SIZE   		32
-#endif
-#endif // CONFIG_STA_SUPPORT //
-
-#ifdef MCAST_RATE_SPECIFIC
-#define MCAST_DISABLE	0
-#define MCAST_CCK		1
-#define MCAST_OFDM		2
-#define MCAST_HTMIX		3
-#endif // MCAST_RATE_SPECIFIC //
-
-// For AsicRadioOff/AsicRadioOn function
-#define DOT11POWERSAVE		0
-#define GUIRADIO_OFF		1
-#define RTMP_HALT		    2
-#define GUI_IDLE_POWER_SAVE		3
-// --
-
-
-// definition for WpaSupport flag
-#define WPA_SUPPLICANT_DISABLE				0
-#define WPA_SUPPLICANT_ENABLE				1
-#define	WPA_SUPPLICANT_ENABLE_WITH_WEB_UI	2
-
-// Endian byte swapping codes
-#define SWAP16(x) \
-    ((UINT16)( \
-    (((UINT16)(x) & (UINT16) 0x00ffU) << 8) | \
-    (((UINT16)(x) & (UINT16) 0xff00U) >> 8) ))
-
-#define SWAP32(x) \
-    ((UINT32)( \
-    (((UINT32)(x) & (UINT32) 0x000000ffUL) << 24) | \
-    (((UINT32)(x) & (UINT32) 0x0000ff00UL) <<  8) | \
-    (((UINT32)(x) & (UINT32) 0x00ff0000UL) >>  8) | \
-    (((UINT32)(x) & (UINT32) 0xff000000UL) >> 24) ))
-
-#define SWAP64(x) \
-    ((UINT64)( \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x00000000000000ffULL) << 56) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x000000000000ff00ULL) << 40) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x0000000000ff0000ULL) << 24) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x00000000ff000000ULL) <<  8) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x000000ff00000000ULL) >>  8) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x0000ff0000000000ULL) >> 24) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0x00ff000000000000ULL) >> 40) | \
-    (UINT64)(((UINT64)(x) & (UINT64) 0xff00000000000000ULL) >> 56) ))
-
-#ifdef RT_BIG_ENDIAN
-
-#define cpu2le64(x) SWAP64((x))
-#define le2cpu64(x) SWAP64((x))
-#define cpu2le32(x) SWAP32((x))
-#define le2cpu32(x) SWAP32((x))
-#define cpu2le16(x) SWAP16((x))
-#define le2cpu16(x) SWAP16((x))
-#define cpu2be64(x) ((UINT64)(x))
-#define be2cpu64(x) ((UINT64)(x))
-#define cpu2be32(x) ((UINT32)(x))
-#define be2cpu32(x) ((UINT32)(x))
-#define cpu2be16(x) ((UINT16)(x))
-#define be2cpu16(x) ((UINT16)(x))
-
-#else   // Little_Endian
-
-#define cpu2le64(x) ((UINT64)(x))
-#define le2cpu64(x) ((UINT64)(x))
-#define cpu2le32(x) ((UINT32)(x))
-#define le2cpu32(x) ((UINT32)(x))
-#define cpu2le16(x) ((UINT16)(x))
-#define le2cpu16(x) ((UINT16)(x))
-#define cpu2be64(x) SWAP64((x))
-#define be2cpu64(x) SWAP64((x))
-#define cpu2be32(x) SWAP32((x))
-#define be2cpu32(x) SWAP32((x))
-#define cpu2be16(x) SWAP16((x))
-#define be2cpu16(x) SWAP16((x))
-
-#endif  // RT_BIG_ENDIAN
-
-#endif  // __RTMP_DEF_H__
-
-
+#include "../rt2870/rtmp_def.h"
diff --git a/drivers/staging/rt3070/rtmp_type.h b/drivers/staging/rt3070/rtmp_type.h
index 4e4b168..42384e5 100644
--- a/drivers/staging/rt3070/rtmp_type.h
+++ b/drivers/staging/rt3070/rtmp_type.h
@@ -1,95 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    rtmp_type.h
-
-    Abstract:
-
-    Revision History:
-    Who         When            What
-    --------    ----------      ----------------------------------------------
-    Name        Date            Modification logs
-    Paul Lin    1-2-2004
-*/
-#ifndef __RTMP_TYPE_H__
-#define __RTMP_TYPE_H__
-
-
-#define PACKED  __attribute__ ((packed))
-
-// Put platform dependent declaration here
-// For example, linux type definition
-typedef unsigned char		UINT8;
-typedef unsigned short		UINT16;
-typedef unsigned int		UINT32;
-typedef unsigned long long	UINT64;
-typedef int					INT32;
-typedef long long 			INT64;
-
-typedef unsigned char *			PUINT8;
-typedef unsigned short *		PUINT16;
-typedef unsigned int *			PUINT32;
-typedef unsigned long long *	PUINT64;
-typedef int	*					PINT32;
-typedef long long * 			PINT64;
-
-typedef signed char			CHAR;
-typedef signed short		SHORT;
-typedef signed int			INT;
-typedef signed long			LONG;
-typedef signed long long	LONGLONG;
-
-
-typedef unsigned char		UCHAR;
-typedef unsigned short		USHORT;
-typedef unsigned int		UINT;
-typedef unsigned long		ULONG;
-typedef unsigned long long	ULONGLONG;
-
-typedef unsigned char		BOOLEAN;
-typedef void				VOID;
-
-typedef VOID *				PVOID;
-typedef CHAR *				PCHAR;
-typedef UCHAR * 			PUCHAR;
-typedef USHORT *			PUSHORT;
-typedef LONG *				PLONG;
-typedef ULONG *				PULONG;
-typedef UINT *				PUINT;
-
-typedef unsigned int	NDIS_MEDIA_STATE;
-
-typedef union _LARGE_INTEGER {
-    struct {
-        UINT LowPart;
-        INT32 HighPart;
-    } u;
-    INT64 QuadPart;
-} LARGE_INTEGER;
-
-#endif  // __RTMP_TYPE_H__
-
+#include "../rt2870/rtmp_type.h"
diff --git a/drivers/staging/rt3070/spectrum.h b/drivers/staging/rt3070/spectrum.h
index 94cfa5b..1ca9c25 100644
--- a/drivers/staging/rt3070/spectrum.h
+++ b/drivers/staging/rt3070/spectrum.h
@@ -1,322 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
- */
-
-#ifndef __SPECTRUM_H__
-#define __SPECTRUM_H__
-
-#include "rtmp_type.h"
-#include "spectrum_def.h"
-
-typedef struct PACKED _TPC_REPORT_INFO
-{
-	UINT8 TxPwr;
-	UINT8 LinkMargin;
-} TPC_REPORT_INFO, *PTPC_REPORT_INFO;
-
-typedef struct PACKED _CH_SW_ANN_INFO
-{
-	UINT8 ChSwMode;
-	UINT8 Channel;
-	UINT8 ChSwCnt;
-} CH_SW_ANN_INFO, *PCH_SW_ANN_INFO;
-
-typedef union PACKED _MEASURE_REQ_MODE
-{
-#ifdef RT_BIG_ENDIAN
-	struct PACKED
-	{
-		UINT8 Rev1:4;
-		UINT8 Report:1;
-		UINT8 Request:1;
-		UINT8 Enable:1;
-		UINT8 Rev0:1;
-	} field;
-#else
-	struct PACKED
-	{
-		UINT8 Rev0:1;
-		UINT8 Enable:1;
-		UINT8 Request:1;
-		UINT8 Report:1;
-		UINT8 Rev1:4;
-	} field;
-#endif // RT_BIG_ENDIAN //
-	UINT8 word;
-} MEASURE_REQ_MODE, *PMEASURE_REQ_MODE;
-
-typedef struct PACKED _MEASURE_REQ
-{
-	UINT8 ChNum;
-	UINT64 MeasureStartTime;
-	UINT16 MeasureDuration;
-} MEASURE_REQ, *PMEASURE_REQ;
-
-typedef struct PACKED _MEASURE_REQ_INFO
-{
-	UINT8 Token;
-	MEASURE_REQ_MODE ReqMode;
-	UINT8 ReqType;
-	MEASURE_REQ MeasureReq;
-} MEASURE_REQ_INFO, *PMEASURE_REQ_INFO;
-
-typedef union PACKED _MEASURE_BASIC_REPORT_MAP
-{
-#ifdef RT_BIG_ENDIAN
-	struct PACKED
-	{
-		UINT8 Rev:3;
-		UINT8 Unmeasure:1;
-		UINT8 Radar:1;
-		UINT8 UnidentifiedSignal:1;
-		UINT8 OfdmPreamble:1;
-		UINT8 BSS:1;
-	} field;
-#else
-	struct PACKED
-	{
-		UINT8 BSS:1;
-		UINT8 OfdmPreamble:1;
-		UINT8 UnidentifiedSignal:1;
-		UINT8 Radar:1;
-		UINT8 Unmeasure:1;
-		UINT8 Rev:3;
-	} field;
-#endif // RT_BIG_ENDIAN //
-	UINT8 word;
-} MEASURE_BASIC_REPORT_MAP, *PMEASURE_BASIC_REPORT_MAP;
-
-typedef struct PACKED _MEASURE_BASIC_REPORT
-{
-	UINT8 ChNum;
-	UINT64 MeasureStartTime;
-	UINT16 MeasureDuration;
-	MEASURE_BASIC_REPORT_MAP Map;
-} MEASURE_BASIC_REPORT, *PMEASURE_BASIC_REPORT;
-
-typedef struct PACKED _MEASURE_CCA_REPORT
-{
-	UINT8 ChNum;
-	UINT64 MeasureStartTime;
-	UINT16 MeasureDuration;
-	UINT8 CCA_Busy_Fraction;
-} MEASURE_CCA_REPORT, *PMEASURE_CCA_REPORT;
-
-typedef struct PACKED _MEASURE_RPI_REPORT
-{
-	UINT8 ChNum;
-	UINT64 MeasureStartTime;
-	UINT16 MeasureDuration;
-	UINT8 RPI_Density[8];
-} MEASURE_RPI_REPORT, *PMEASURE_RPI_REPORT;
-
-typedef union PACKED _MEASURE_REPORT_MODE
-{
-	struct PACKED
-	{
-#ifdef RT_BIG_ENDIAN
-		UINT8 Rev:5;
-		UINT8 Refused:1;
-		UINT8 Incapable:1;
-		UINT8 Late:1;
-#else
-		UINT8 Late:1;
-		UINT8 Incapable:1;
-		UINT8 Refused:1;
-		UINT8 Rev:5;
-#endif // RT_BIG_ENDIAN //
-	} field;
-	UINT8 word;
-} MEASURE_REPORT_MODE, *PMEASURE_REPORT_MODE;
-
-typedef struct PACKED _MEASURE_REPORT_INFO
-{
-	UINT8 Token;
-	MEASURE_REPORT_MODE ReportMode;
-	UINT8 ReportType;
-	UINT8 Octect[0];
-} MEASURE_REPORT_INFO, *PMEASURE_REPORT_INFO;
-
-typedef struct PACKED _QUIET_INFO
-{
-	UINT8 QuietCnt;
-	UINT8 QuietPeriod;
-	UINT8 QuietDuration;
-	UINT8 QuietOffset;
-} QUIET_INFO, *PQUIET_INFO;
-
-/*
-	==========================================================================
-	Description:
-		Prepare Measurement request action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueMeasurementReq(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 MeasureToken,
-	IN UINT8 MeasureReqMode,
-	IN UINT8 MeasureReqType,
-	IN UINT8 MeasureCh,
-	IN UINT16 MeasureDuration);
-
-/*
-	==========================================================================
-	Description:
-		Prepare Measurement report action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueMeasurementRep(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 DialogToken,
-	IN UINT8 MeasureToken,
-	IN UINT8 MeasureReqMode,
-	IN UINT8 MeasureReqType,
-	IN UINT8 ReportInfoLen,
-	IN PUINT8 pReportInfo);
-
-/*
-	==========================================================================
-	Description:
-		Prepare TPC Request action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueTPCReq(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UCHAR DialogToken);
-
-/*
-	==========================================================================
-	Description:
-		Prepare TPC Report action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueTPCRep(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 DialogToken,
-	IN UINT8 TxPwr,
-	IN UINT8 LinkMargin);
-
-/*
-	==========================================================================
-	Description:
-		Prepare Channel Switch Announcement action frame and enqueue it into
-		management queue waiting for transmition.
-
-	Parametrs:
-		1. the destination mac address of the frame.
-		2. Channel switch announcement mode.
-		2. a New selected channel.
-
-	Return	: None.
-	==========================================================================
- */
-VOID EnqueueChSwAnn(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pDA,
-	IN UINT8 ChSwMode,
-	IN UINT8 NewCh);
-
-/*
-	==========================================================================
-	Description:
-		Spectrun action frames Handler such as channel switch annoucement,
-		measurement report, measurement request actions frames.
-
-	Parametrs:
-		Elme - MLME message containing the received frame
-
-	Return	: None.
-	==========================================================================
- */
-VOID PeerSpectrumAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem);
-
-/*
-	==========================================================================
-	Description:
-
-	Parametrs:
-
-	Return	: None.
-	==========================================================================
- */
-INT Set_MeasureReq_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-INT Set_TpcReq_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-
-VOID MeasureReqTabInit(
-	IN PRTMP_ADAPTER pAd);
-
-VOID MeasureReqTabExit(
-	IN PRTMP_ADAPTER pAd);
-
-VOID TpcReqTabInit(
-	IN PRTMP_ADAPTER pAd);
-
-VOID TpcReqTabExit(
-	IN PRTMP_ADAPTER pAd);
-
-VOID NotifyChSwAnnToPeerAPs(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pRA,
-	IN PUCHAR pTA,
-	IN UINT8 ChSwMode,
-	IN UINT8 Channel);
-#endif // __SPECTRUM_H__ //
-
+#include "../rt2870/spectrum.h"
diff --git a/drivers/staging/rt3070/spectrum_def.h b/drivers/staging/rt3070/spectrum_def.h
index 4ca4817..892bc88 100644
--- a/drivers/staging/rt3070/spectrum_def.h
+++ b/drivers/staging/rt3070/spectrum_def.h
@@ -1,95 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-	spectrum_def.h
-
-    Abstract:
-    Handle association related requests either from WSTA or from local MLME
-
-    Revision History:
-    Who          When          What
-    ---------    ----------    ----------------------------------------------
-	Fonchi Wu    2008	  	   created for 802.11h
- */
-
-#ifndef __SPECTRUM_DEF_H__
-#define __SPECTRUM_DEF_H__
-
-#define MAX_MEASURE_REQ_TAB_SIZE		3
-#define MAX_HASH_MEASURE_REQ_TAB_SIZE	MAX_MEASURE_REQ_TAB_SIZE
-
-#define MAX_TPC_REQ_TAB_SIZE			3
-#define MAX_HASH_TPC_REQ_TAB_SIZE		MAX_TPC_REQ_TAB_SIZE
-
-#define MIN_RCV_PWR				100		/* Negative value ((dBm) */
-
-#define RM_TPC_REQ				0
-#define RM_MEASURE_REQ			1
-
-#define RM_BASIC				0
-#define RM_CCA					1
-#define RM_RPI_HISTOGRAM		2
-
-#define TPC_REQ_AGE_OUT			500		/* ms */
-#define MQ_REQ_AGE_OUT			500		/* ms */
-
-#define TPC_DIALOGTOKEN_HASH_INDEX(_DialogToken)	((_DialogToken) % MAX_HASH_TPC_REQ_TAB_SIZE)
-#define MQ_DIALOGTOKEN_HASH_INDEX(_DialogToken)		((_DialogToken) % MAX_MEASURE_REQ_TAB_SIZE)
-
-typedef struct _MEASURE_REQ_ENTRY
-{
-	struct _MEASURE_REQ_ENTRY *pNext;
-	ULONG lastTime;
-	BOOLEAN	Valid;
-	UINT8 DialogToken;
-	UINT8 MeasureDialogToken[3];	// 0:basic measure, 1: CCA measure, 2: RPI_Histogram measure.
-} MEASURE_REQ_ENTRY, *PMEASURE_REQ_ENTRY;
-
-typedef struct _MEASURE_REQ_TAB
-{
-	UCHAR Size;
-	PMEASURE_REQ_ENTRY Hash[MAX_HASH_MEASURE_REQ_TAB_SIZE];
-	MEASURE_REQ_ENTRY Content[MAX_MEASURE_REQ_TAB_SIZE];
-} MEASURE_REQ_TAB, *PMEASURE_REQ_TAB;
-
-typedef struct _TPC_REQ_ENTRY
-{
-	struct _TPC_REQ_ENTRY *pNext;
-	ULONG lastTime;
-	BOOLEAN Valid;
-	UINT8 DialogToken;
-} TPC_REQ_ENTRY, *PTPC_REQ_ENTRY;
-
-typedef struct _TPC_REQ_TAB
-{
-	UCHAR Size;
-	PTPC_REQ_ENTRY Hash[MAX_HASH_TPC_REQ_TAB_SIZE];
-	TPC_REQ_ENTRY Content[MAX_TPC_REQ_TAB_SIZE];
-} TPC_REQ_TAB, *PTPC_REQ_TAB;
-
-#endif // __SPECTRUM_DEF_H__ //
-
+#include "../rt2870/spectrum_def.h"
diff --git a/drivers/staging/rt3070/sta/aironet.c b/drivers/staging/rt3070/sta/aironet.c
index 4af4a19..48fcc46 100644
--- a/drivers/staging/rt3070/sta/aironet.c
+++ b/drivers/staging/rt3070/sta/aironet.c
@@ -1,1312 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	aironet.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Paul Lin	04-06-15		Initial
-*/
-#include "../rt_config.h"
-
-/*
-	==========================================================================
-	Description:
-		association	state machine init,	including state	transition and timer init
-	Parameters:
-		S -	pointer	to the association state machine
-	==========================================================================
- */
-VOID	AironetStateMachineInit(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	STATE_MACHINE		*S,
-	OUT	STATE_MACHINE_FUNC	Trans[])
-{
-	StateMachineInit(S,	Trans, MAX_AIRONET_STATE, MAX_AIRONET_MSG, (STATE_MACHINE_FUNC)Drop, AIRONET_IDLE, AIRONET_MACHINE_BASE);
-	StateMachineSetAction(S, AIRONET_IDLE, MT2_AIRONET_MSG, (STATE_MACHINE_FUNC)AironetMsgAction);
-	StateMachineSetAction(S, AIRONET_IDLE, MT2_AIRONET_SCAN_REQ, (STATE_MACHINE_FUNC)AironetRequestAction);
-	StateMachineSetAction(S, AIRONET_SCANNING, MT2_AIRONET_SCAN_DONE, (STATE_MACHINE_FUNC)AironetReportAction);
-}
-
-/*
-	==========================================================================
-	Description:
-		This is	state machine function.
-		When receiving EAPOL packets which is  for 802.1x key management.
-		Use	both in	WPA, and WPAPSK	case.
-		In this	function, further dispatch to different	functions according	to the received	packet.	 3 categories are :
-		  1.  normal 4-way pairwisekey and 2-way groupkey handshake
-		  2.  MIC error	(Countermeasures attack)  report packet	from STA.
-		  3.  Request for pairwise/group key update	from STA
-	Return:
-	==========================================================================
-*/
-VOID	AironetMsgAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-{
-	USHORT							Length;
-	UCHAR							Index, i;
-	PUCHAR							pData;
-	PAIRONET_RM_REQUEST_FRAME		pRMReq;
-	PRM_REQUEST_ACTION				pReqElem;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("-----> AironetMsgAction\n"));
-
-	// 0. Get Aironet IAPP header first
-	pRMReq = (PAIRONET_RM_REQUEST_FRAME) &Elem->Msg[LENGTH_802_11];
-	pData  = (PUCHAR) &Elem->Msg[LENGTH_802_11];
-
-	// 1. Change endian format form network to little endian
-	Length = be2cpu16(pRMReq->IAPP.Length);
-
-	// 2.0 Sanity check, this should only happen when CCX 2.0 support is enabled
-	if (pAd->StaCfg.CCXEnable != TRUE)
-		return;
-
-	// 2.1 Radio measurement must be on
-	if (pAd->StaCfg.CCXControl.field.RMEnable != 1)
-		return;
-
-	// 2.2. Debug print all bit information
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP ID & Length %d\n", Length));
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP Type %x\n", pRMReq->IAPP.Type));
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP SubType %x\n", pRMReq->IAPP.SubType));
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP Dialog Token %x\n", pRMReq->IAPP.Token));
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP Activation Delay %x\n", pRMReq->Delay));
-	DBGPRINT(RT_DEBUG_TRACE, ("IAPP Measurement Offset %x\n", pRMReq->Offset));
-
-	// 3. Check IAPP frame type, it must be 0x32 for Cisco Aironet extension
-	if (pRMReq->IAPP.Type != AIRONET_IAPP_TYPE)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Wrong IAPP type for Cisco Aironet extension\n"));
-		return;
-	}
-
-	// 4. Check IAPP frame subtype, it must be 0x01 for Cisco Aironet extension request.
-	//    Since we are acting as client only, we will disregards reply subtype.
-	if (pRMReq->IAPP.SubType != AIRONET_IAPP_SUBTYPE_REQUEST)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Wrong IAPP subtype for Cisco Aironet extension\n"));
-		return;
-	}
-
-	// 5. Verify Destination MAC and Source MAC, both should be all zeros.
-	if (! MAC_ADDR_EQUAL(pRMReq->IAPP.DA, ZERO_MAC_ADDR))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Wrong IAPP DA for Cisco Aironet extension, it's not Zero\n"));
-		return;
-	}
-
-	if (! MAC_ADDR_EQUAL(pRMReq->IAPP.SA, ZERO_MAC_ADDR))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("Wrong IAPP SA for Cisco Aironet extension, it's not Zero\n"));
-		return;
-	}
-
-	// 6. Reinit all report related fields
-	NdisZeroMemory(pAd->StaCfg.FrameReportBuf, 2048);
-	NdisZeroMemory(pAd->StaCfg.BssReportOffset, sizeof(USHORT) * MAX_LEN_OF_BSS_TABLE);
-	NdisZeroMemory(pAd->StaCfg.MeasurementRequest, sizeof(RM_REQUEST_ACTION) * 4);
-
-	// 7. Point to the start of first element report element
-	pAd->StaCfg.FrameReportLen   = LENGTH_802_11 + sizeof(AIRONET_IAPP_HEADER);
-	DBGPRINT(RT_DEBUG_TRACE, ("FR len = %d\n", pAd->StaCfg.FrameReportLen));
-	pAd->StaCfg.LastBssIndex     = 0xff;
-	pAd->StaCfg.RMReqCnt         = 0;
-	pAd->StaCfg.ParallelReq      = FALSE;
-	pAd->StaCfg.ParallelDuration = 0;
-	pAd->StaCfg.ParallelChannel  = 0;
-	pAd->StaCfg.IAPPToken        = pRMReq->IAPP.Token;
-	pAd->StaCfg.CurrentRMReqIdx  = 0;
-	pAd->StaCfg.CLBusyBytes      = 0;
-	// Reset the statistics
-	for (i = 0; i < 8; i++)
-		pAd->StaCfg.RPIDensity[i] = 0;
-
-	Index = 0;
-
-	// 8. Save dialog token for report
-	pAd->StaCfg.IAPPToken = pRMReq->IAPP.Token;
-
-	// Save Activation delay & measurement offset, Not really needed
-
-	// 9. Point to the first request element
-	pData += sizeof(AIRONET_RM_REQUEST_FRAME);
-	//    Length should exclude the CISCO Aironet SNAP header
-	Length -= (sizeof(AIRONET_RM_REQUEST_FRAME) - LENGTH_802_1_H);
-
-	// 10. Start Parsing the Measurement elements.
-	//    Be careful about multiple MR elements within one frames.
-	while (Length > 0)
-	{
-		pReqElem = (PRM_REQUEST_ACTION) pData;
-		switch (pReqElem->ReqElem.Eid)
-		{
-			case IE_MEASUREMENT_REQUEST:
-				// From the example, it seems we only need to support one request in one frame
-				// There is no multiple request in one frame.
-				// Besides, looks like we need to take care the measurement request only.
-				// The measurement request is always 4 bytes.
-
-				// Start parsing this type of request.
-				// 0. Eid is IE_MEASUREMENT_REQUEST
-				// 1. Length didn't include Eid and Length field, it always be 8.
-				// 2. Measurement Token, we nned to save it for the corresponding report.
-				// 3. Measurement Mode, Although there are definitions, but we din't see value other than
-				//    0 from test specs examples.
-				// 4. Measurement Type, this is what we need to do.
-				switch (pReqElem->ReqElem.Type)
-				{
-					case MSRN_TYPE_CHANNEL_LOAD_REQ:
-					case MSRN_TYPE_NOISE_HIST_REQ:
-					case MSRN_TYPE_BEACON_REQ:
-						// Check the Enable non-serving channel measurement control
-						if (pAd->StaCfg.CCXControl.field.DCRMEnable == 0)
-						{
-							// Check channel before enqueue the action
-							if (pReqElem->Measurement.Channel != pAd->CommonCfg.Channel)
-								break;
-						}
-						else
-						{
-							// If off channel measurement, check the TU duration limit
-							if (pReqElem->Measurement.Channel != pAd->CommonCfg.Channel)
-								if (pReqElem->Measurement.Duration > pAd->StaCfg.CCXControl.field.TuLimit)
-									break;
-						}
-
-						// Save requests and execute actions later
-						NdisMoveMemory(&pAd->StaCfg.MeasurementRequest[Index], pReqElem, sizeof(RM_REQUEST_ACTION));
-						Index += 1;
-						break;
-
-					case MSRN_TYPE_FRAME_REQ:
-						// Since it's option, we will support later
-						// FrameRequestAction(pAd, pData);
-						break;
-
-					default:
-						break;
-				}
-
-				// Point to next Measurement request
-				pData  += sizeof(RM_REQUEST_ACTION);
-				Length -= sizeof(RM_REQUEST_ACTION);
-				break;
-
-			// We accept request only, all others are dropped
-			case IE_MEASUREMENT_REPORT:
-			case IE_AP_TX_POWER:
-			case IE_MEASUREMENT_CAPABILITY:
-			default:
-				return;
-		}
-	}
-
-	// 11. Update some flags and index
-	pAd->StaCfg.RMReqCnt = Index;
-
-	if (Index)
-	{
-		MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_REQ, 0, NULL);
-		RT28XX_MLME_HANDLER(pAd);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<----- AironetMsgAction\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	AironetRequestAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-{
-	PRM_REQUEST_ACTION	pReq;
-
-	// 1. Point to next request element
-	pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[pAd->StaCfg.CurrentRMReqIdx];
-
-	// 2. Parse measurement type and call appropriate functions
-	if (pReq->ReqElem.Type == MSRN_TYPE_CHANNEL_LOAD_REQ)
-		// Channel Load measurement request
-		ChannelLoadRequestAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else if (pReq->ReqElem.Type == MSRN_TYPE_NOISE_HIST_REQ)
-		// Noise Histogram measurement request
-		NoiseHistRequestAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else if (pReq->ReqElem.Type == MSRN_TYPE_BEACON_REQ)
-		// Beacon measurement request
-		BeaconRequestAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else
-		// Unknown. Do nothing and return, this should never happen
-		return;
-
-	// 3. Peek into the next request, if it's parallel, we will update the scan time to the largest one
-	if ((pAd->StaCfg.CurrentRMReqIdx + 1) < pAd->StaCfg.RMReqCnt)
-	{
-		pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[pAd->StaCfg.CurrentRMReqIdx + 1];
-		// Check for parallel bit
-		if ((pReq->ReqElem.Mode & 0x01) && (pReq->Measurement.Channel == pAd->StaCfg.CCXScanChannel))
-		{
-			// Update parallel mode request information
-			pAd->StaCfg.ParallelReq = TRUE;
-			pAd->StaCfg.CCXScanTime = ((pReq->Measurement.Duration > pAd->StaCfg.CCXScanTime) ?
-			(pReq->Measurement.Duration) : (pAd->StaCfg.CCXScanTime));
-		}
-	}
-
-	// 4. Call RT28XX_MLME_HANDLER to execute the request mlme commands, Scan request is the only one used
-	RT28XX_MLME_HANDLER(pAd);
-
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Prepare channel load report action, special scan operation added
-		to support
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		pData		Start from element ID
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	ChannelLoadRequestAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	PRM_REQUEST_ACTION				pReq;
-	MLME_SCAN_REQ_STRUCT			ScanReq;
-	UCHAR							ZeroSsid[32];
-	NDIS_STATUS						NStatus;
-	PUCHAR							pOutBuffer = NULL;
-	PHEADER_802_11					pNullFrame;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ChannelLoadRequestAction ----->\n"));
-
-	pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[Index];
-	NdisZeroMemory(ZeroSsid, 32);
-
-	// Prepare for special scan request
-	// The scan definition is different with our Active, Passive scan definition.
-	// For CCX2, Active means send out probe request with broadcast BSSID.
-	// Passive means no probe request sent, only listen to the beacons.
-	// The channel scanned is fixed as specified, no need to scan all channels.
-	// The scan wait time is specified in the request too.
-	// Passive scan Mode
-
-	// Control state machine is not idle, reject the request
-	if ((pAd->Mlme.CntlMachine.CurrState != CNTL_IDLE) && (Index == 0))
-		return;
-
-	// Fill out stuff for scan request
-	ScanParmFill(pAd, &ScanReq, ZeroSsid, 0, BSS_ANY, SCAN_CISCO_CHANNEL_LOAD);
-	MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-	pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-
-	// Reset some internal control flags to make sure this scan works.
-	BssTableInit(&pAd->StaCfg.CCXBssTab);
-	pAd->StaCfg.ScanCnt        = 0;
-	pAd->StaCfg.CCXScanChannel = pReq->Measurement.Channel;
-	pAd->StaCfg.CCXScanTime    = pReq->Measurement.Duration;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Duration %d, Channel %d!\n", pReq->Measurement.Duration, pReq->Measurement.Channel));
-
-	// If it's non serving channel scan, send out a null frame with PSM bit on.
-	if (pAd->StaCfg.CCXScanChannel != pAd->CommonCfg.Channel)
-	{
-		// Use MLME enqueue method
-		NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-		if (NStatus	!= NDIS_STATUS_SUCCESS)
-			return;
-
-		pNullFrame = (PHEADER_802_11) pOutBuffer;;
-		// Make the power save Null frame with PSM bit on
-		MgtMacHeaderInit(pAd, pNullFrame, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-		pNullFrame->Duration 	= 0;
-		pNullFrame->FC.Type 	= BTYPE_DATA;
-		pNullFrame->FC.PwrMgmt	= PWR_SAVE;
-
-		// Send using priority queue
-		MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-		MlmeFreeMemory(pAd, pOutBuffer);
-		DBGPRINT(RT_DEBUG_TRACE, ("Send PSM Data frame for off channel RM\n"));
-		RTMPusecDelay(5000);
-	}
-
-	pAd->StaCfg.CCXReqType     = MSRN_TYPE_CHANNEL_LOAD_REQ;
-	pAd->StaCfg.CLBusyBytes    = 0;
-	// Enable Rx with promiscuous reception
-	RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, 0x1010);
-
-	// Set channel load measurement flag
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_MEASUREMENT);
-
-	pAd->Mlme.AironetMachine.CurrState = AIRONET_SCANNING;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ChannelLoadRequestAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Prepare noise histogram report action, special scan operation added
-		to support
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		pData		Start from element ID
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	NoiseHistRequestAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	PRM_REQUEST_ACTION				pReq;
-	MLME_SCAN_REQ_STRUCT			ScanReq;
-	UCHAR							ZeroSsid[32], i;
-	NDIS_STATUS						NStatus;
-	PUCHAR							pOutBuffer = NULL;
-	PHEADER_802_11					pNullFrame;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("NoiseHistRequestAction ----->\n"));
-
-	pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[Index];
-	NdisZeroMemory(ZeroSsid, 32);
-
-	// Prepare for special scan request
-	// The scan definition is different with our Active, Passive scan definition.
-	// For CCX2, Active means send out probe request with broadcast BSSID.
-	// Passive means no probe request sent, only listen to the beacons.
-	// The channel scanned is fixed as specified, no need to scan all channels.
-	// The scan wait time is specified in the request too.
-	// Passive scan Mode
-
-	// Control state machine is not idle, reject the request
-	if ((pAd->Mlme.CntlMachine.CurrState != CNTL_IDLE) && (Index == 0))
-		return;
-
-	// Fill out stuff for scan request
-	ScanParmFill(pAd, &ScanReq, ZeroSsid, 0, BSS_ANY, SCAN_CISCO_NOISE);
-	MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-	pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-
-	// Reset some internal control flags to make sure this scan works.
-	BssTableInit(&pAd->StaCfg.CCXBssTab);
-	pAd->StaCfg.ScanCnt        = 0;
-	pAd->StaCfg.CCXScanChannel = pReq->Measurement.Channel;
-	pAd->StaCfg.CCXScanTime    = pReq->Measurement.Duration;
-	pAd->StaCfg.CCXReqType     = MSRN_TYPE_NOISE_HIST_REQ;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Duration %d, Channel %d!\n", pReq->Measurement.Duration, pReq->Measurement.Channel));
-
-	// If it's non serving channel scan, send out a null frame with PSM bit on.
-	if (pAd->StaCfg.CCXScanChannel != pAd->CommonCfg.Channel)
-	{
-		// Use MLME enqueue method
-		NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-		if (NStatus	!= NDIS_STATUS_SUCCESS)
-			return;
-
-		pNullFrame = (PHEADER_802_11) pOutBuffer;
-		// Make the power save Null frame with PSM bit on
-		MgtMacHeaderInit(pAd, pNullFrame, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-		pNullFrame->Duration 	= 0;
-		pNullFrame->FC.Type  	= BTYPE_DATA;
-		pNullFrame->FC.PwrMgmt	= PWR_SAVE;
-
-		// Send using priority queue
-		MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-		MlmeFreeMemory(pAd, pOutBuffer);
-		DBGPRINT(RT_DEBUG_TRACE, ("Send PSM Data frame for off channel RM\n"));
-		RTMPusecDelay(5000);
-	}
-
-	// Reset the statistics
-	for (i = 0; i < 8; i++)
-		pAd->StaCfg.RPIDensity[i] = 0;
-
-	// Enable Rx with promiscuous reception
-	RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, 0x1010);
-
-	// Set channel load measurement flag
-	RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RADIO_MEASUREMENT);
-
-	pAd->Mlme.AironetMachine.CurrState = AIRONET_SCANNING;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("NoiseHistRequestAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Prepare Beacon report action, special scan operation added
-		to support
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		pData		Start from element ID
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	BeaconRequestAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	PRM_REQUEST_ACTION				pReq;
-	NDIS_STATUS						NStatus;
-	PUCHAR							pOutBuffer = NULL;
-	PHEADER_802_11					pNullFrame;
-	MLME_SCAN_REQ_STRUCT			ScanReq;
-	UCHAR							ZeroSsid[32];
-
-	DBGPRINT(RT_DEBUG_TRACE, ("BeaconRequestAction ----->\n"));
-
-	pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[Index];
-	NdisZeroMemory(ZeroSsid, 32);
-
-	// Prepare for special scan request
-	// The scan definition is different with our Active, Passive scan definition.
-	// For CCX2, Active means send out probe request with broadcast BSSID.
-	// Passive means no probe request sent, only listen to the beacons.
-	// The channel scanned is fixed as specified, no need to scan all channels.
-	// The scan wait time is specified in the request too.
-	if (pReq->Measurement.ScanMode == MSRN_SCAN_MODE_PASSIVE)
-	{
-		// Passive scan Mode
-		DBGPRINT(RT_DEBUG_TRACE, ("Passive Scan Mode!\n"));
-
-		// Control state machine is not idle, reject the request
-		if ((pAd->Mlme.CntlMachine.CurrState != CNTL_IDLE) && (Index == 0))
-			return;
-
-		// Fill out stuff for scan request
-		ScanParmFill(pAd, &ScanReq, ZeroSsid, 0, BSS_ANY, SCAN_CISCO_PASSIVE);
-		MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-
-		// Reset some internal control flags to make sure this scan works.
-		BssTableInit(&pAd->StaCfg.CCXBssTab);
-		pAd->StaCfg.ScanCnt        = 0;
-		pAd->StaCfg.CCXScanChannel = pReq->Measurement.Channel;
-		pAd->StaCfg.CCXScanTime    = pReq->Measurement.Duration;
-		pAd->StaCfg.CCXReqType     = MSRN_TYPE_BEACON_REQ;
-		DBGPRINT(RT_DEBUG_TRACE, ("Duration %d!\n", pReq->Measurement.Duration));
-
-		// If it's non serving channel scan, send out a null frame with PSM bit on.
-		if (pAd->StaCfg.CCXScanChannel != pAd->CommonCfg.Channel)
-		{
-			// Use MLME enqueue method
-			NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-			if (NStatus	!= NDIS_STATUS_SUCCESS)
-				return;
-
-			pNullFrame = (PHEADER_802_11) pOutBuffer;
-			// Make the power save Null frame with PSM bit on
-			MgtMacHeaderInit(pAd, pNullFrame, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-			pNullFrame->Duration 	= 0;
-			pNullFrame->FC.Type     = BTYPE_DATA;
-			pNullFrame->FC.PwrMgmt  = PWR_SAVE;
-
-			// Send using priority queue
-			MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-			MlmeFreeMemory(pAd, pOutBuffer);
-			DBGPRINT(RT_DEBUG_TRACE, ("Send PSM Data frame for off channel RM\n"));
-			RTMPusecDelay(5000);
-		}
-
-		pAd->Mlme.AironetMachine.CurrState = AIRONET_SCANNING;
-	}
-	else if (pReq->Measurement.ScanMode == MSRN_SCAN_MODE_ACTIVE)
-	{
-		// Active scan Mode
-		DBGPRINT(RT_DEBUG_TRACE, ("Active Scan Mode!\n"));
-
-		// Control state machine is not idle, reject the request
-		if (pAd->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-			return;
-
-		// Fill out stuff for scan request
-		ScanParmFill(pAd, &ScanReq, ZeroSsid, 0, BSS_ANY, SCAN_CISCO_ACTIVE);
-		MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-
-		// Reset some internal control flags to make sure this scan works.
-		BssTableInit(&pAd->StaCfg.CCXBssTab);
-		pAd->StaCfg.ScanCnt        = 0;
-		pAd->StaCfg.CCXScanChannel = pReq->Measurement.Channel;
-		pAd->StaCfg.CCXScanTime    = pReq->Measurement.Duration;
-		pAd->StaCfg.CCXReqType     = MSRN_TYPE_BEACON_REQ;
-		DBGPRINT(RT_DEBUG_TRACE, ("Duration %d!\n", pReq->Measurement.Duration));
-
-		// If it's non serving channel scan, send out a null frame with PSM bit on.
-		if (pAd->StaCfg.CCXScanChannel != pAd->CommonCfg.Channel)
-		{
-			// Use MLME enqueue method
-			NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);  //Get an unused nonpaged memory
-			if (NStatus	!= NDIS_STATUS_SUCCESS)
-				return;
-
-			pNullFrame = (PHEADER_802_11) pOutBuffer;
-			// Make the power save Null frame with PSM bit on
-			MgtMacHeaderInit(pAd, pNullFrame, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-			pNullFrame->Duration 	= 0;
-			pNullFrame->FC.Type     = BTYPE_DATA;
-			pNullFrame->FC.PwrMgmt  = PWR_SAVE;
-
-			// Send using priority queue
-			MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-			MlmeFreeMemory(pAd, pOutBuffer);
-			DBGPRINT(RT_DEBUG_TRACE, ("Send PSM Data frame for off channel RM\n"));
-			RTMPusecDelay(5000);
-		}
-
-		pAd->Mlme.AironetMachine.CurrState = AIRONET_SCANNING;
-	}
-	else if (pReq->Measurement.ScanMode == MSRN_SCAN_MODE_BEACON_TABLE)
-	{
-		// Beacon report Mode, report all the APS in current bss table
-		DBGPRINT(RT_DEBUG_TRACE, ("Beacon Report Mode!\n"));
-
-		// Copy current BSS table to CCX table, we can omit this step later on.
-		NdisMoveMemory(&pAd->StaCfg.CCXBssTab, &pAd->ScanTab, sizeof(BSS_TABLE));
-
-		// Create beacon report from Bss table
-		AironetCreateBeaconReportFromBssTable(pAd);
-
-		// Set state to scanning
-		pAd->Mlme.AironetMachine.CurrState = AIRONET_SCANNING;
-
-		// Enqueue report request
-		// Cisco scan request is finished, prepare beacon report
-		MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_DONE, 0, NULL);
-	}
-	else
-	{
-		// Wrong scan Mode
-		DBGPRINT(RT_DEBUG_TRACE, ("Wrong Scan Mode!\n"));
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("BeaconRequestAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	AironetReportAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-{
-	PRM_REQUEST_ACTION	pReq;
-	ULONG				Now32;
-
-    NdisGetSystemUpTime(&Now32);
-	pAd->StaCfg.LastBeaconRxTime = Now32;
-
-	pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[pAd->StaCfg.CurrentRMReqIdx];
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AironetReportAction ----->\n"));
-
-	// 1. Parse measurement type and call appropriate functions
-	if (pReq->ReqElem.Type == MSRN_TYPE_CHANNEL_LOAD_REQ)
-		// Channel Load measurement request
-		ChannelLoadReportAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else if (pReq->ReqElem.Type == MSRN_TYPE_NOISE_HIST_REQ)
-		// Noise Histogram measurement request
-		NoiseHistReportAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else if (pReq->ReqElem.Type == MSRN_TYPE_BEACON_REQ)
-		// Beacon measurement request
-		BeaconReportAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-	else
-		// Unknown. Do nothing and return
-		;
-
-	// 2. Point to the correct index of action element, start from 0
-	pAd->StaCfg.CurrentRMReqIdx++;
-
-	// 3. Check for parallel actions
-	if (pAd->StaCfg.ParallelReq == TRUE)
-	{
-		pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[pAd->StaCfg.CurrentRMReqIdx];
-
-		// Process next action right away
-		if (pReq->ReqElem.Type == MSRN_TYPE_CHANNEL_LOAD_REQ)
-			// Channel Load measurement request
-			ChannelLoadReportAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-		else if (pReq->ReqElem.Type == MSRN_TYPE_NOISE_HIST_REQ)
-			// Noise Histogram measurement request
-			NoiseHistReportAction(pAd, pAd->StaCfg.CurrentRMReqIdx);
-
-		pAd->StaCfg.ParallelReq = FALSE;
-		pAd->StaCfg.CurrentRMReqIdx++;
-	}
-
-	if (pAd->StaCfg.CurrentRMReqIdx >= pAd->StaCfg.RMReqCnt)
-	{
-		// 4. There is no more unprocessed measurement request, go for transmit this report
-		AironetFinalReportAction(pAd);
-		pAd->Mlme.AironetMachine.CurrState = AIRONET_IDLE;
-	}
-	else
-	{
-		pReq = (PRM_REQUEST_ACTION) &pAd->StaCfg.MeasurementRequest[pAd->StaCfg.CurrentRMReqIdx];
-
-		if (pReq->Measurement.Channel != pAd->CommonCfg.Channel)
-		{
-			RTMPusecDelay(100000);
-		}
-
-		// 5. There are more requests to be measure
-		MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_REQ, 0, NULL);
-		RT28XX_MLME_HANDLER(pAd);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AironetReportAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	AironetFinalReportAction(
-	IN	PRTMP_ADAPTER	pAd)
-{
-	PUCHAR					pDest;
-	PAIRONET_IAPP_HEADER	pIAPP;
-	PHEADER_802_11			pHeader;
-	UCHAR					AckRate = RATE_2;
-	USHORT					AckDuration = 0;
-	NDIS_STATUS				NStatus;
-	PUCHAR					pOutBuffer = NULL;
-	ULONG					FrameLen = 0;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AironetFinalReportAction ----->\n"));
-
-	// 0. Set up the frame pointer, Frame was inited at the end of message action
-	pDest = &pAd->StaCfg.FrameReportBuf[LENGTH_802_11];
-
-	// 1. Update report IAPP fields
-	pIAPP = (PAIRONET_IAPP_HEADER) pDest;
-
-	// 2. Copy Cisco SNAP header
-	NdisMoveMemory(pIAPP->CiscoSnapHeader, SNAP_AIRONET, LENGTH_802_1_H);
-
-	// 3. network order for this 16bit length
-	pIAPP->Length  = cpu2be16(pAd->StaCfg.FrameReportLen - LENGTH_802_11 - LENGTH_802_1_H);
-
-	// 3.1 sanity check the report length, ignore it if there is nothing to report
-	if (be2cpu16(pIAPP->Length) <= 18)
-		return;
-
-	// 4. Type must be 0x32
-	pIAPP->Type    = AIRONET_IAPP_TYPE;
-
-	// 5. SubType for report must be 0x81
-	pIAPP->SubType = AIRONET_IAPP_SUBTYPE_REPORT;
-
-	// 6. DA is not used and must be zero, although the whole frame was cleared at the start of function
-	//    We will do it again here. We can use BSSID instead
-	COPY_MAC_ADDR(pIAPP->DA, pAd->CommonCfg.Bssid);
-
-	// 7. SA is the client reporting which must be our MAC
-	COPY_MAC_ADDR(pIAPP->SA, pAd->CurrentAddress);
-
-	// 8. Copy the saved dialog token
-	pIAPP->Token = pAd->StaCfg.IAPPToken;
-
-	// 9. Make the Report frame 802.11 header
-	//    Reuse function in wpa.c
-	pHeader = (PHEADER_802_11) pAd->StaCfg.FrameReportBuf;
-	pAd->Sequence ++;
-	WpaMacHeaderInit(pAd, pHeader, 0, pAd->CommonCfg.Bssid);
-
-	// ACK size	is 14 include CRC, and its rate	is based on real time information
-	AckRate     = pAd->CommonCfg.ExpectedACKRate[pAd->CommonCfg.MlmeRate];
-	AckDuration = RTMPCalcDuration(pAd, AckRate, 14);
-	pHeader->Duration = pAd->CommonCfg.Dsifs + AckDuration;
-
-	// Use MLME enqueue method
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus	!= NDIS_STATUS_SUCCESS)
-		return;
-
-	// 10. Prepare report frame with dynamic outbuffer. Just simply copy everything.
-	MakeOutgoingFrame(pOutBuffer,                       &FrameLen,
-	                  pAd->StaCfg.FrameReportLen, pAd->StaCfg.FrameReportBuf,
-		              END_OF_ARGS);
-
-	// 11. Send using priority queue
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	pAd->StaCfg.CCXReqType = MSRN_TYPE_UNUSED;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AironetFinalReportAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	ChannelLoadReportAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	PMEASUREMENT_REPORT_ELEMENT	pReport;
-	PCHANNEL_LOAD_REPORT		pLoad;
-	PUCHAR						pDest;
-	UCHAR						CCABusyFraction;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ChannelLoadReportAction ----->\n"));
-
-	// Disable Rx with promiscuous reception, make it back to normal
-	RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, STANORMAL); // Staion not drop control frame will fail WiFi Certification.
-
-	// 0. Setup pointer for processing beacon & probe response
-	pDest = (PUCHAR) &pAd->StaCfg.FrameReportBuf[pAd->StaCfg.FrameReportLen];
-	pReport = (PMEASUREMENT_REPORT_ELEMENT) pDest;
-
-	// 1. Fill Measurement report element field.
-	pReport->Eid    = IE_MEASUREMENT_REPORT;
-	// Fixed Length at 9, not include Eid and length fields
-	pReport->Length = 9;
-	pReport->Token  = pAd->StaCfg.MeasurementRequest[Index].ReqElem.Token;
-	pReport->Mode   = pAd->StaCfg.MeasurementRequest[Index].ReqElem.Mode;
-	pReport->Type   = MSRN_TYPE_CHANNEL_LOAD_REQ;
-
-	// 2. Fill channel report measurement data
-	pDest += sizeof(MEASUREMENT_REPORT_ELEMENT);
-	pLoad  = (PCHANNEL_LOAD_REPORT) pDest;
-	pLoad->Channel  = pAd->StaCfg.MeasurementRequest[Index].Measurement.Channel;
-	pLoad->Spare    = 0;
-	pLoad->Duration = pAd->StaCfg.MeasurementRequest[Index].Measurement.Duration;
-
-	// 3. Calculate the CCA Busy Fraction
-	//    (Bytes + ACK size) * 8 / Tx speed * 255 / 1000 / measurement duration, use 24 us Tx speed
-	//     =  (Bytes + ACK) / 12 / duration
-	//     9 is the good value for pAd->StaCfg.CLFactor
-	// CCABusyFraction = (UCHAR) (pAd->StaCfg.CLBusyBytes / 9 / pLoad->Duration);
-	CCABusyFraction = (UCHAR) (pAd->StaCfg.CLBusyBytes / pAd->StaCfg.CLFactor / pLoad->Duration);
-	if (CCABusyFraction < 10)
-			CCABusyFraction = (UCHAR) (pAd->StaCfg.CLBusyBytes / 3 / pLoad->Duration) + 1;
-
-	pLoad->CCABusy = CCABusyFraction;
-	DBGPRINT(RT_DEBUG_TRACE, ("CLBusyByte %ld, Duration %d, Result, %d\n", pAd->StaCfg.CLBusyBytes, pLoad->Duration, CCABusyFraction));
-
-	DBGPRINT(RT_DEBUG_TRACE, ("FrameReportLen %d\n", pAd->StaCfg.FrameReportLen));
-	pAd->StaCfg.FrameReportLen += (sizeof(MEASUREMENT_REPORT_ELEMENT) + sizeof(CHANNEL_LOAD_REPORT));
-	DBGPRINT(RT_DEBUG_TRACE, ("FrameReportLen %d\n", pAd->StaCfg.FrameReportLen));
-
-	// 4. Clear channel load measurement flag
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_RADIO_MEASUREMENT);
-
-	// 5. reset to idle state
-	pAd->Mlme.AironetMachine.CurrState = AIRONET_IDLE;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ChannelLoadReportAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	NoiseHistReportAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	PMEASUREMENT_REPORT_ELEMENT	pReport;
-	PNOISE_HIST_REPORT			pNoise;
-	PUCHAR						pDest;
-	UCHAR						i,NoiseCnt;
-	USHORT						TotalRPICnt, TotalRPISum;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("NoiseHistReportAction ----->\n"));
-
-	// 0. Disable Rx with promiscuous reception, make it back to normal
-	RTMP_IO_WRITE32(pAd, RX_FILTR_CFG, STANORMAL); // Staion not drop control frame will fail WiFi Certification.
-	// 1. Setup pointer for processing beacon & probe response
-	pDest = (PUCHAR) &pAd->StaCfg.FrameReportBuf[pAd->StaCfg.FrameReportLen];
-	pReport = (PMEASUREMENT_REPORT_ELEMENT) pDest;
-
-	// 2. Fill Measurement report element field.
-	pReport->Eid    = IE_MEASUREMENT_REPORT;
-	// Fixed Length at 16, not include Eid and length fields
-	pReport->Length = 16;
-	pReport->Token  = pAd->StaCfg.MeasurementRequest[Index].ReqElem.Token;
-	pReport->Mode   = pAd->StaCfg.MeasurementRequest[Index].ReqElem.Mode;
-	pReport->Type   = MSRN_TYPE_NOISE_HIST_REQ;
-
-	// 3. Fill noise histogram report measurement data
-	pDest += sizeof(MEASUREMENT_REPORT_ELEMENT);
-	pNoise  = (PNOISE_HIST_REPORT) pDest;
-	pNoise->Channel  = pAd->StaCfg.MeasurementRequest[Index].Measurement.Channel;
-	pNoise->Spare    = 0;
-	pNoise->Duration = pAd->StaCfg.MeasurementRequest[Index].Measurement.Duration;
-	// 4. Fill Noise histogram, the total RPI counts should be 0.4 * TU
-	//    We estimate 4000 normal packets received durning 10 seconds test.
-	//    Adjust it if required.
-	// 3 is a good value for pAd->StaCfg.NHFactor
-	// TotalRPICnt = pNoise->Duration * 3 / 10;
-	TotalRPICnt = pNoise->Duration * pAd->StaCfg.NHFactor / 10;
-	TotalRPISum = 0;
-
-	for (i = 0; i < 8; i++)
-	{
-		TotalRPISum += pAd->StaCfg.RPIDensity[i];
-		DBGPRINT(RT_DEBUG_TRACE, ("RPI %d Conuts %d\n", i, pAd->StaCfg.RPIDensity[i]));
-	}
-
-	// Double check if the counter is larger than our expectation.
-	// We will replace it with the total number plus a fraction.
-	if (TotalRPISum > TotalRPICnt)
-		TotalRPICnt = TotalRPISum + pNoise->Duration / 20;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Total RPI Conuts %d\n", TotalRPICnt));
-
-	// 5. Initialize noise count for the total summation of 0xff
-	NoiseCnt = 0;
-	for (i = 1; i < 8; i++)
-	{
-		pNoise->Density[i] = (UCHAR) (pAd->StaCfg.RPIDensity[i] * 255 / TotalRPICnt);
-		if ((pNoise->Density[i] == 0) && (pAd->StaCfg.RPIDensity[i] != 0))
-			pNoise->Density[i]++;
-		NoiseCnt += pNoise->Density[i];
-		DBGPRINT(RT_DEBUG_TRACE, ("Reported RPI[%d]  = 0x%02x\n", i, pNoise->Density[i]));
-	}
-
-	// 6. RPI[0] represents the rest of counts
-	pNoise->Density[0] = 0xff - NoiseCnt;
-	DBGPRINT(RT_DEBUG_TRACE, ("Reported RPI[0]  = 0x%02x\n", pNoise->Density[0]));
-
-	pAd->StaCfg.FrameReportLen += (sizeof(MEASUREMENT_REPORT_ELEMENT) + sizeof(NOISE_HIST_REPORT));
-
-	// 7. Clear channel load measurement flag
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_RADIO_MEASUREMENT);
-
-	// 8. reset to idle state
-	pAd->Mlme.AironetMachine.CurrState = AIRONET_IDLE;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("NoiseHistReportAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Prepare Beacon report action,
-
-	Arguments:
-		pAd	Pointer	to our adapter
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	BeaconReportAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			Index)
-{
-	DBGPRINT(RT_DEBUG_TRACE, ("BeaconReportAction ----->\n"));
-
-	// Looks like we don't have anything thing need to do here.
-	// All measurement report already finished in AddBeaconReport
-	// The length is in the FrameReportLen
-
-	// reset Beacon index for next beacon request
-	pAd->StaCfg.LastBssIndex = 0xff;
-
-	// reset to idle state
-	pAd->Mlme.AironetMachine.CurrState = AIRONET_IDLE;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("BeaconReportAction <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-		Index		Current BSSID in CCXBsstab entry index
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	AironetAddBeaconReport(
-	IN	PRTMP_ADAPTER		pAd,
-	IN	ULONG				Index,
-	IN	PMLME_QUEUE_ELEM	pElem)
-{
-	PVOID						pMsg;
-	PUCHAR						pSrc, pDest;
-	UCHAR						ReqIdx;
-	ULONG						MsgLen;
-	USHORT						Length;
-	PFRAME_802_11				pFrame;
-	PMEASUREMENT_REPORT_ELEMENT	pReport;
-	PEID_STRUCT			        pEid;
-	PBEACON_REPORT				pBeaconReport;
-	PBSS_ENTRY					pBss;
-
-	// 0. Setup pointer for processing beacon & probe response
-	pMsg   = pElem->Msg;
-	MsgLen = pElem->MsgLen;
-	pFrame = (PFRAME_802_11) pMsg;
-	pSrc   = pFrame->Octet;				// Start from AP TSF
-	pBss   = (PBSS_ENTRY) &pAd->StaCfg.CCXBssTab.BssEntry[Index];
-	ReqIdx = pAd->StaCfg.CurrentRMReqIdx;
-
-	// 1 Check the Index, if we already create this entry, only update the average RSSI
-	if ((Index <= pAd->StaCfg.LastBssIndex) && (pAd->StaCfg.LastBssIndex != 0xff))
-	{
-		pDest  = (PUCHAR) &pAd->StaCfg.FrameReportBuf[pAd->StaCfg.BssReportOffset[Index]];
-		// Point to bss report information
-		pDest += sizeof(MEASUREMENT_REPORT_ELEMENT);
-		pBeaconReport = (PBEACON_REPORT) pDest;
-
-		// Update Rx power, in dBm
-		// Get the original RSSI readback from BBP
-		pBeaconReport->RxPower += pAd->BbpRssiToDbmDelta;
-		// Average the Rssi reading
-		pBeaconReport->RxPower  = (pBeaconReport->RxPower + pBss->Rssi) / 2;
-		// Get to dBm format
-		pBeaconReport->RxPower -= pAd->BbpRssiToDbmDelta;
-
-		DBGPRINT(RT_DEBUG_TRACE, ("Bssid %02x:%02x:%02x:%02x:%02x:%02x ",
-			pBss->Bssid[0], pBss->Bssid[1], pBss->Bssid[2],
-			pBss->Bssid[3], pBss->Bssid[4], pBss->Bssid[5]));
-		DBGPRINT(RT_DEBUG_TRACE, ("RxPower[%ld] Rssi %d, Avg Rssi %d\n", Index, (pBss->Rssi - pAd->BbpRssiToDbmDelta), pBeaconReport->RxPower - 256));
-		DBGPRINT(RT_DEBUG_TRACE, ("FrameReportLen = %d\n", pAd->StaCfg.BssReportOffset[Index]));
-
-		// Update other information here
-
-		// Done
-		return;
-	}
-
-	// 2. Update reported Index
-	pAd->StaCfg.LastBssIndex = Index;
-
-	// 3. Setup the buffer address for copying this BSSID into reporting frame
-	//    The offset should start after 802.11 header and report frame header.
-	pDest = (PUCHAR) &pAd->StaCfg.FrameReportBuf[pAd->StaCfg.FrameReportLen];
-
-	// 4. Save the start offset of each Bss in report frame
-	pAd->StaCfg.BssReportOffset[Index] = pAd->StaCfg.FrameReportLen;
-
-	// 5. Fill Measurement report fields
-	pReport = (PMEASUREMENT_REPORT_ELEMENT) pDest;
-	pReport->Eid = IE_MEASUREMENT_REPORT;
-	pReport->Length = 0;
-	pReport->Token  = pAd->StaCfg.MeasurementRequest[ReqIdx].ReqElem.Token;
-	pReport->Mode   = pAd->StaCfg.MeasurementRequest[ReqIdx].ReqElem.Mode;
-	pReport->Type   = MSRN_TYPE_BEACON_REQ;
-	Length          = sizeof(MEASUREMENT_REPORT_ELEMENT);
-	pDest          += sizeof(MEASUREMENT_REPORT_ELEMENT);
-
-	// 6. Start thebeacon report format
-	pBeaconReport = (PBEACON_REPORT) pDest;
-	pDest        += sizeof(BEACON_REPORT);
-	Length       += sizeof(BEACON_REPORT);
-
-	// 7. Copy Channel number
-	pBeaconReport->Channel        = pBss->Channel;
-	pBeaconReport->Spare          = 0;
-	pBeaconReport->Duration       = pAd->StaCfg.MeasurementRequest[ReqIdx].Measurement.Duration;
-	pBeaconReport->PhyType        = ((pBss->SupRateLen+pBss->ExtRateLen > 4) ? PHY_ERP : PHY_DSS);
-	// 8. Rx power, in dBm
-	pBeaconReport->RxPower        = pBss->Rssi - pAd->BbpRssiToDbmDelta;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Bssid %02x:%02x:%02x:%02x:%02x:%02x ",
-		pBss->Bssid[0], pBss->Bssid[1], pBss->Bssid[2],
-		pBss->Bssid[3], pBss->Bssid[4], pBss->Bssid[5]));
-	DBGPRINT(RT_DEBUG_TRACE, ("RxPower[%ld], Rssi %d\n", Index, pBeaconReport->RxPower - 256));
-	DBGPRINT(RT_DEBUG_TRACE, ("FrameReportLen = %d\n", pAd->StaCfg.FrameReportLen));
-
-	pBeaconReport->BeaconInterval = pBss->BeaconPeriod;
-	COPY_MAC_ADDR(pBeaconReport->BSSID, pFrame->Hdr.Addr3);
-	NdisMoveMemory(pBeaconReport->ParentTSF, pSrc, 4);
-	NdisMoveMemory(pBeaconReport->TargetTSF, &pElem->TimeStamp.u.LowPart, 4);
-	NdisMoveMemory(&pBeaconReport->TargetTSF[4], &pElem->TimeStamp.u.HighPart, 4);
-
-	// 9. Skip the beacon frame and offset to start of capabilityinfo since we already processed capabilityinfo
-	pSrc += (TIMESTAMP_LEN + 2);
-	pBeaconReport->CapabilityInfo = *(USHORT *)pSrc;
-
-	// 10. Point to start of element ID
-	pSrc += 2;
-	pEid = (PEID_STRUCT) pSrc;
-
-	// 11. Start process all variable Eid oayload and add the appropriate to the frame report
-	while (((PUCHAR) pEid + pEid->Len + 1) < ((PUCHAR) pFrame + MsgLen))
-	{
-		// Only limited EID are required to report for CCX 2. It includes SSID, Supported rate,
-		// FH paramenter set, DS parameter set, CF parameter set, IBSS parameter set,
-		// TIM (report first 4 bytes only, radio measurement capability
-		switch (pEid->Eid)
-		{
-			case IE_SSID:
-			case IE_SUPP_RATES:
-			case IE_FH_PARM:
-			case IE_DS_PARM:
-			case IE_CF_PARM:
-			case IE_IBSS_PARM:
-				NdisMoveMemory(pDest, pEid, pEid->Len + 2);
-				pDest  += (pEid->Len + 2);
-				Length += (pEid->Len + 2);
-				break;
-
-			case IE_MEASUREMENT_CAPABILITY:
-				// Since this IE is duplicated with WPA security IE, we has to do sanity check before
-				// recognize it.
-				// 1. It also has fixed 6 bytes IE length.
-				if (pEid->Len != 6)
-					break;
-				// 2. Check the Cisco Aironet OUI
-				if (NdisEqualMemory(CISCO_OUI, (pSrc + 2), 3))
-				{
-					// Matched, this is what we want
-					NdisMoveMemory(pDest, pEid, pEid->Len + 2);
-					pDest  += (pEid->Len + 2);
-					Length += (pEid->Len + 2);
-				}
-				break;
-
-			case IE_TIM:
-				if (pEid->Len > 4)
-				{
-					// May truncate and report the first 4 bytes only, with the eid & len, total should be 6
-					NdisMoveMemory(pDest, pEid, 6);
-					pDest  += 6;
-					Length += 6;
-				}
-				else
-				{
-					NdisMoveMemory(pDest, pEid, pEid->Len + 2);
-					pDest  += (pEid->Len + 2);
-					Length += (pEid->Len + 2);
-				}
-				break;
-
-			default:
-				break;
-		}
-		// 12. Move to next element ID
-		pSrc += (2 + pEid->Len);
-		pEid = (PEID_STRUCT) pSrc;
-	}
-
-	// 13. Update the length in the header, not include EID and length
-	pReport->Length = Length - 4;
-
-	// 14. Update the frame report buffer data length
-	pAd->StaCfg.FrameReportLen += Length;
-	DBGPRINT(RT_DEBUG_TRACE, ("FR len = %d\n", pAd->StaCfg.FrameReportLen));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-
-	Arguments:
-		Index		Current BSSID in CCXBsstab entry index
-
-	Return Value:
-
-	Note:
-
-	========================================================================
-*/
-VOID	AironetCreateBeaconReportFromBssTable(
-	IN	PRTMP_ADAPTER		pAd)
-{
-	PMEASUREMENT_REPORT_ELEMENT	pReport;
-	PBEACON_REPORT				pBeaconReport;
-	UCHAR						Index, ReqIdx;
-	USHORT						Length;
-	PUCHAR						pDest;
-	PBSS_ENTRY					pBss;
-
-	// 0. setup base pointer
-	ReqIdx = pAd->StaCfg.CurrentRMReqIdx;
-
-	for (Index = 0; Index < pAd->StaCfg.CCXBssTab.BssNr; Index++)
-	{
-		// 1. Setup the buffer address for copying this BSSID into reporting frame
-		//    The offset should start after 802.11 header and report frame header.
-		pDest  = (PUCHAR) &pAd->StaCfg.FrameReportBuf[pAd->StaCfg.FrameReportLen];
-		pBss   = (PBSS_ENTRY) &pAd->StaCfg.CCXBssTab.BssEntry[Index];
-		Length = 0;
-
-		// 2. Fill Measurement report fields
-		pReport         = (PMEASUREMENT_REPORT_ELEMENT) pDest;
-		pReport->Eid    = IE_MEASUREMENT_REPORT;
-		pReport->Length = 0;
-		pReport->Token  = pAd->StaCfg.MeasurementRequest[ReqIdx].ReqElem.Token;
-		pReport->Mode   = pAd->StaCfg.MeasurementRequest[ReqIdx].ReqElem.Mode;
-		pReport->Type   = MSRN_TYPE_BEACON_REQ;
-		Length          = sizeof(MEASUREMENT_REPORT_ELEMENT);
-		pDest          += sizeof(MEASUREMENT_REPORT_ELEMENT);
-
-		// 3. Start the beacon report format
-		pBeaconReport = (PBEACON_REPORT) pDest;
-		pDest        += sizeof(BEACON_REPORT);
-		Length       += sizeof(BEACON_REPORT);
-
-		// 4. Copy Channel number
-		pBeaconReport->Channel        = pBss->Channel;
-		pBeaconReport->Spare          = 0;
-		pBeaconReport->Duration       = pAd->StaCfg.MeasurementRequest[ReqIdx].Measurement.Duration;
-		pBeaconReport->PhyType        = ((pBss->SupRateLen+pBss->ExtRateLen > 4) ? PHY_ERP : PHY_DSS);
-		pBeaconReport->RxPower        = pBss->Rssi - pAd->BbpRssiToDbmDelta;
-		pBeaconReport->BeaconInterval = pBss->BeaconPeriod;
-		pBeaconReport->CapabilityInfo = pBss->CapabilityInfo;
-		COPY_MAC_ADDR(pBeaconReport->BSSID, pBss->Bssid);
-		NdisMoveMemory(pBeaconReport->ParentTSF, pBss->PTSF, 4);
-		NdisMoveMemory(pBeaconReport->TargetTSF, pBss->TTSF, 8);
-
-		// 5. Create SSID
-		*pDest++ = 0x00;
-		*pDest++ = pBss->SsidLen;
-		NdisMoveMemory(pDest, pBss->Ssid, pBss->SsidLen);
-		pDest  += pBss->SsidLen;
-		Length += (2 + pBss->SsidLen);
-
-		// 6. Create SupportRates
-		*pDest++ = 0x01;
-		*pDest++ = pBss->SupRateLen;
-		NdisMoveMemory(pDest, pBss->SupRate, pBss->SupRateLen);
-		pDest  += pBss->SupRateLen;
-		Length += (2 + pBss->SupRateLen);
-
-		// 7. DS Parameter
-		*pDest++ = 0x03;
-		*pDest++ = 1;
-		*pDest++ = pBss->Channel;
-		Length  += 3;
-
-		// 8. IBSS parameter if presents
-		if (pBss->BssType == BSS_ADHOC)
-		{
-			*pDest++ = 0x06;
-			*pDest++ = 2;
-			*(PUSHORT) pDest = pBss->AtimWin;
-			pDest   += 2;
-			Length  += 4;
-		}
-
-		// 9. Update length field, not include EID and length
-		pReport->Length = Length - 4;
-
-		// 10. Update total frame size
-		pAd->StaCfg.FrameReportLen += Length;
-	}
-}
+#include "../../rt2870/sta/aironet.c"
diff --git a/drivers/staging/rt3070/sta/assoc.c b/drivers/staging/rt3070/sta/assoc.c
index 5c33a89..1987a2a 100644
--- a/drivers/staging/rt3070/sta/assoc.c
+++ b/drivers/staging/rt3070/sta/assoc.c
@@ -1,2060 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	assoc.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John		2004-9-3		porting from RT2500
-*/
-#include "../rt_config.h"
-
-UCHAR	CipherWpaTemplate[] = {
-		0xdd, 					// WPA IE
-		0x16,					// Length
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x02,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x02,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x01	// authentication
-		};
-
-UCHAR	CipherWpa2Template[] = {
-		0x30,					// RSN IE
-		0x14,					// Length
-		0x01, 0x00,				// Version
-		0x00, 0x0f, 0xac, 0x02,	// group cipher, TKIP
-		0x01, 0x00,				// number of pairwise
-		0x00, 0x0f, 0xac, 0x02,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x0f, 0xac, 0x02,	// authentication
-		0x00, 0x00,				// RSN capability
-		};
-
-UCHAR	Ccx2IeInfo[] = { 0x00, 0x40, 0x96, 0x03, 0x02};
-
-/*
-	==========================================================================
-	Description:
-		association state machine init, including state transition and timer init
-	Parameters:
-		S - pointer to the association state machine
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
- */
-VOID AssocStateMachineInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  STATE_MACHINE *S,
-	OUT STATE_MACHINE_FUNC Trans[])
-{
-	StateMachineInit(S, Trans, MAX_ASSOC_STATE, MAX_ASSOC_MSG, (STATE_MACHINE_FUNC)Drop, ASSOC_IDLE, ASSOC_MACHINE_BASE);
-
-	// first column
-	StateMachineSetAction(S, ASSOC_IDLE, MT2_MLME_ASSOC_REQ, (STATE_MACHINE_FUNC)MlmeAssocReqAction);
-	StateMachineSetAction(S, ASSOC_IDLE, MT2_MLME_REASSOC_REQ, (STATE_MACHINE_FUNC)MlmeReassocReqAction);
-	StateMachineSetAction(S, ASSOC_IDLE, MT2_MLME_DISASSOC_REQ, (STATE_MACHINE_FUNC)MlmeDisassocReqAction);
-	StateMachineSetAction(S, ASSOC_IDLE, MT2_PEER_DISASSOC_REQ, (STATE_MACHINE_FUNC)PeerDisassocAction);
-
-	// second column
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_MLME_ASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenAssoc);
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_MLME_REASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenReassoc);
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_MLME_DISASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenDisassociate);
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_PEER_DISASSOC_REQ, (STATE_MACHINE_FUNC)PeerDisassocAction);
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_PEER_ASSOC_RSP, (STATE_MACHINE_FUNC)PeerAssocRspAction);
-	//
-	// Patch 3Com AP MOde:3CRWE454G72
-	// We send Assoc request frame to this AP, it always send Reassoc Rsp not Associate Rsp.
-	//
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_PEER_REASSOC_RSP, (STATE_MACHINE_FUNC)PeerAssocRspAction);
-	StateMachineSetAction(S, ASSOC_WAIT_RSP, MT2_ASSOC_TIMEOUT, (STATE_MACHINE_FUNC)AssocTimeoutAction);
-
-	// third column
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_MLME_ASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenAssoc);
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_MLME_REASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenReassoc);
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_MLME_DISASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenDisassociate);
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_PEER_DISASSOC_REQ, (STATE_MACHINE_FUNC)PeerDisassocAction);
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_PEER_REASSOC_RSP, (STATE_MACHINE_FUNC)PeerReassocRspAction);
-	//
-	// Patch, AP doesn't send Reassociate Rsp frame to Station.
-	//
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_PEER_ASSOC_RSP, (STATE_MACHINE_FUNC)PeerReassocRspAction);
-	StateMachineSetAction(S, REASSOC_WAIT_RSP, MT2_REASSOC_TIMEOUT, (STATE_MACHINE_FUNC)ReassocTimeoutAction);
-
-	// fourth column
-	StateMachineSetAction(S, DISASSOC_WAIT_RSP, MT2_MLME_ASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenAssoc);
-	StateMachineSetAction(S, DISASSOC_WAIT_RSP, MT2_MLME_REASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenReassoc);
-	StateMachineSetAction(S, DISASSOC_WAIT_RSP, MT2_MLME_DISASSOC_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenDisassociate);
-	StateMachineSetAction(S, DISASSOC_WAIT_RSP, MT2_PEER_DISASSOC_REQ, (STATE_MACHINE_FUNC)PeerDisassocAction);
-	StateMachineSetAction(S, DISASSOC_WAIT_RSP, MT2_DISASSOC_TIMEOUT, (STATE_MACHINE_FUNC)DisassocTimeoutAction);
-
-	// initialize the timer
-	RTMPInitTimer(pAd, &pAd->MlmeAux.AssocTimer, GET_TIMER_FUNCTION(AssocTimeout), pAd, FALSE);
-	RTMPInitTimer(pAd, &pAd->MlmeAux.ReassocTimer, GET_TIMER_FUNCTION(ReassocTimeout), pAd, FALSE);
-	RTMPInitTimer(pAd, &pAd->MlmeAux.DisassocTimer, GET_TIMER_FUNCTION(DisassocTimeout), pAd, FALSE);
-}
-
-/*
-	==========================================================================
-	Description:
-		Association timeout procedure. After association timeout, this function
-		will be called and it will put a message into the MLME queue
-	Parameters:
-		Standard timer parameters
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AssocTimeout(IN PVOID SystemSpecific1,
-				 IN PVOID FunctionContext,
-				 IN PVOID SystemSpecific2,
-				 IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return;
-
-	MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_ASSOC_TIMEOUT, 0, NULL);
-	RT28XX_MLME_HANDLER(pAd);
-}
-
-/*
-	==========================================================================
-	Description:
-		Reassociation timeout procedure. After reassociation timeout, this
-		function will be called and put a message into the MLME queue
-	Parameters:
-		Standard timer parameters
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID ReassocTimeout(IN PVOID SystemSpecific1,
-					IN PVOID FunctionContext,
-					IN PVOID SystemSpecific2,
-					IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return;
-
-	MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_REASSOC_TIMEOUT, 0, NULL);
-	RT28XX_MLME_HANDLER(pAd);
-}
-
-/*
-	==========================================================================
-	Description:
-		Disassociation timeout procedure. After disassociation timeout, this
-		function will be called and put a message into the MLME queue
-	Parameters:
-		Standard timer parameters
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID DisassocTimeout(IN PVOID SystemSpecific1,
-					IN PVOID FunctionContext,
-					IN PVOID SystemSpecific2,
-					IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return;
-
-	MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_DISASSOC_TIMEOUT, 0, NULL);
-	RT28XX_MLME_HANDLER(pAd);
-}
-
-/*
-	==========================================================================
-	Description:
-		mlme assoc req handling procedure
-	Parameters:
-		Adapter - Adapter pointer
-		Elem - MLME Queue Element
-	Pre:
-		the station has been authenticated and the following information is stored in the config
-			-# SSID
-			-# supported rates and their length
-			-# listen interval (Adapter->StaCfg.default_listen_count)
-			-# Transmit power  (Adapter->StaCfg.tx_power)
-	Post  :
-		-# An association request frame is generated and sent to the air
-		-# Association timer starts
-		-# Association state -> ASSOC_WAIT_RSP
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID MlmeAssocReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR			ApAddr[6];
-	HEADER_802_11	AssocHdr;
-	UCHAR			Ccx2Len = 5;
-	UCHAR			WmeIe[9] = {IE_VENDOR_SPECIFIC, 0x07, 0x00, 0x50, 0xf2, 0x02, 0x00, 0x01, 0x00};
-	USHORT			ListenIntv;
-	ULONG			Timeout;
-	USHORT			CapabilityInfo;
-	BOOLEAN			TimerCancelled;
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen = 0;
-	ULONG			tmp;
-	USHORT			VarIesOffset;
-	UCHAR			CkipFlag;
-	UCHAR			CkipNegotiationBuffer[CKIP_NEGOTIATION_LENGTH];
-	UCHAR			AironetCkipIe = IE_AIRONET_CKIP;
-	UCHAR			AironetCkipLen = CKIP_NEGOTIATION_LENGTH;
-	UCHAR			AironetIPAddressIE = IE_AIRONET_IPADDRESS;
-	UCHAR			AironetIPAddressLen = AIRONET_IPADDRESS_LENGTH;
-	UCHAR			AironetIPAddressBuffer[AIRONET_IPADDRESS_LENGTH] = {0x00, 0x40, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00};
-	USHORT			Status;
-
-	// Block all authentication request durning WPA block period
-	if (pAd->StaCfg.bBlockAssoc == TRUE)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Block Assoc request durning WPA block period!\n"));
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-		Status = MLME_STATE_MACHINE_REJECT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-	}
-	// check sanity first
-	else if (MlmeAssocReqSanity(pAd, Elem->Msg, Elem->MsgLen, ApAddr, &CapabilityInfo, &Timeout, &ListenIntv))
-	{
-		RTMPCancelTimer(&pAd->MlmeAux.AssocTimer, &TimerCancelled);
-		COPY_MAC_ADDR(pAd->MlmeAux.Bssid, ApAddr);
-
-		// Get an unused nonpaged memory
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-		if (NStatus != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("ASSOC - MlmeAssocReqAction() allocate memory failed \n"));
-			pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-			Status = MLME_FAIL_NO_RESOURCE;
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-			return;
-		}
-
-		// Add by James 03/06/27
-		pAd->StaCfg.AssocInfo.Length = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION);
-		// Association don't need to report MAC address
-		pAd->StaCfg.AssocInfo.AvailableRequestFixedIEs =
-			NDIS_802_11_AI_REQFI_CAPABILITIES | NDIS_802_11_AI_REQFI_LISTENINTERVAL;
-		pAd->StaCfg.AssocInfo.RequestFixedIEs.Capabilities = CapabilityInfo;
-		pAd->StaCfg.AssocInfo.RequestFixedIEs.ListenInterval = ListenIntv;
-		// Only reassociate need this
-		//COPY_MAC_ADDR(pAd->StaCfg.AssocInfo.RequestFixedIEs.CurrentAPAddress, ApAddr);
-		pAd->StaCfg.AssocInfo.OffsetRequestIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION);
-
-        NdisZeroMemory(pAd->StaCfg.ReqVarIEs, MAX_VIE_LEN);
-		// First add SSID
-		VarIesOffset = 0;
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &SsidIe, 1);
-		VarIesOffset += 1;
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &pAd->MlmeAux.SsidLen, 1);
-		VarIesOffset += 1;
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-		VarIesOffset += pAd->MlmeAux.SsidLen;
-
-		// Second add Supported rates
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &SupRateIe, 1);
-		VarIesOffset += 1;
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &pAd->MlmeAux.SupRateLen, 1);
-		VarIesOffset += 1;
-		NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, pAd->MlmeAux.SupRate, pAd->MlmeAux.SupRateLen);
-		VarIesOffset += pAd->MlmeAux.SupRateLen;
-		// End Add by James
-
-        if ((pAd->CommonCfg.Channel > 14) &&
-            (pAd->CommonCfg.bIEEE80211H == TRUE))
-            CapabilityInfo |= 0x0100;
-
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Send ASSOC request...\n"));
-		MgtMacHeaderInit(pAd, &AssocHdr, SUBTYPE_ASSOC_REQ, 0, ApAddr, ApAddr);
-
-		// Build basic frame first
-		MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-						  sizeof(HEADER_802_11),	&AssocHdr,
-						  2,						&CapabilityInfo,
-						  2,						&ListenIntv,
-						  1,						&SsidIe,
-						  1,						&pAd->MlmeAux.SsidLen,
-						  pAd->MlmeAux.SsidLen, 	pAd->MlmeAux.Ssid,
-						  1,						&SupRateIe,
-						  1,						&pAd->MlmeAux.SupRateLen,
-						  pAd->MlmeAux.SupRateLen,  pAd->MlmeAux.SupRate,
-						  END_OF_ARGS);
-
-		if (pAd->MlmeAux.ExtRateLen != 0)
-		{
-			MakeOutgoingFrame(pOutBuffer + FrameLen,    &tmp,
-							  1,                        &ExtRateIe,
-							  1,                        &pAd->MlmeAux.ExtRateLen,
-							  pAd->MlmeAux.ExtRateLen,  pAd->MlmeAux.ExtRate,
-							  END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-#ifdef DOT11_N_SUPPORT
-		// HT
-		if ((pAd->MlmeAux.HtCapabilityLen > 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-		{
-			ULONG TmpLen;
-			UCHAR HtLen;
-			UCHAR BROADCOM[4] = {0x0, 0x90, 0x4c, 0x33};
-			if (pAd->StaActive.SupportedPhyInfo.bPreNHt == TRUE)
-			{
-				HtLen = SIZE_HT_CAP_IE + 4;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-							  1,                                &WpaIe,
-							  1,                                &HtLen,
-							  4,                                &BROADCOM[0],
-							 pAd->MlmeAux.HtCapabilityLen,          &pAd->MlmeAux.HtCapability,
-							  END_OF_ARGS);
-			}
-			else
-			{
-#ifdef RT_BIG_ENDIAN
-		        HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
-
-#ifndef RT_BIG_ENDIAN
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-							  1,                                &HtCapIe,
-							  1,                                &pAd->MlmeAux.HtCapabilityLen,
-							 pAd->MlmeAux.HtCapabilityLen,          &pAd->MlmeAux.HtCapability,
-							  END_OF_ARGS);
-#else
-                NdisZeroMemory(&HtCapabilityTmp, sizeof(HT_CAPABILITY_IE));
-                NdisMoveMemory(&HtCapabilityTmp, &pAd->MlmeAux.HtCapability, pAd->MlmeAux.HtCapabilityLen);
-        		*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-        		*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-        		MakeOutgoingFrame(pOutBuffer + FrameLen,         &TmpLen,
-        							1,                           &HtCapIe,
-        							1,                           &pAd->MlmeAux.HtCapabilityLen,
-        							pAd->MlmeAux.HtCapabilityLen,&HtCapabilityTmp,
-        							END_OF_ARGS);
-#endif
-			}
-			FrameLen += TmpLen;
-		}
-#endif // DOT11_N_SUPPORT //
-
-		// add Ralink proprietary IE to inform AP this STA is going to use AGGREGATION or PIGGY-BACK+AGGREGATION
-		// Case I: (Aggregation + Piggy-Back)
-		// 1. user enable aggregation, AND
-		// 2. Mac support piggy-back
-		// 3. AP annouces it's PIGGY-BACK+AGGREGATION-capable in BEACON
-		// Case II: (Aggregation)
-		// 1. user enable aggregation, AND
-		// 2. AP annouces it's AGGREGATION-capable in BEACON
-		if (pAd->CommonCfg.bAggregationCapable)
-		{
-			if ((pAd->CommonCfg.bPiggyBackCapable) && ((pAd->MlmeAux.APRalinkIe & 0x00000003) == 3))
-			{
-				ULONG TmpLen;
-				UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x03, 0x00, 0x00, 0x00};
-				MakeOutgoingFrame(pOutBuffer+FrameLen,           &TmpLen,
-								  9,                             RalinkIe,
-								  END_OF_ARGS);
-				FrameLen += TmpLen;
-			}
-			else if (pAd->MlmeAux.APRalinkIe & 0x00000001)
-			{
-				ULONG TmpLen;
-				UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x01, 0x00, 0x00, 0x00};
-				MakeOutgoingFrame(pOutBuffer+FrameLen,           &TmpLen,
-								  9,                             RalinkIe,
-								  END_OF_ARGS);
-				FrameLen += TmpLen;
-			}
-		}
-		else
-		{
-			ULONG TmpLen;
-			UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x06, 0x00, 0x00, 0x00};
-			MakeOutgoingFrame(pOutBuffer+FrameLen,		 &TmpLen,
-							  9,						 RalinkIe,
-							  END_OF_ARGS);
-			FrameLen += TmpLen;
-		}
-
-		if (pAd->MlmeAux.APEdcaParm.bValid)
-		{
-			if (pAd->CommonCfg.bAPSDCapable && pAd->MlmeAux.APEdcaParm.bAPSDCapable)
-			{
-				QBSS_STA_INFO_PARM QosInfo;
-
-				NdisZeroMemory(&QosInfo, sizeof(QBSS_STA_INFO_PARM));
-				QosInfo.UAPSD_AC_BE = pAd->CommonCfg.bAPSDAC_BE;
-				QosInfo.UAPSD_AC_BK = pAd->CommonCfg.bAPSDAC_BK;
-				QosInfo.UAPSD_AC_VI = pAd->CommonCfg.bAPSDAC_VI;
-				QosInfo.UAPSD_AC_VO = pAd->CommonCfg.bAPSDAC_VO;
-				QosInfo.MaxSPLength = pAd->CommonCfg.MaxSPLength;
-				WmeIe[8] |= *(PUCHAR)&QosInfo;
-			}
-			else
-			{
-                // The Parameter Set Count is set to ¡§0¡¨ in the association request frames
-                // WmeIe[8] |= (pAd->MlmeAux.APEdcaParm.EdcaUpdateCount & 0x0f);
-			}
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen,    &tmp,
-							  9,                        &WmeIe[0],
-							  END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-		//
-		// Let WPA(#221) Element ID on the end of this association frame.
-		// Otherwise some AP will fail on parsing Element ID and set status fail on Assoc Rsp.
-		// For example: Put Vendor Specific IE on the front of WPA IE.
-		// This happens on AP (Model No:Linksys WRK54G)
-		//
-		if (((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-            (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-            (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-            (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2)
-			)
-            )
-		{
-			UCHAR RSNIe = IE_WPA;
-
-			if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-                (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2))
-			{
-				RSNIe = IE_WPA2;
-			}
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-#ifdef SIOCSIWGENIE
-			if (pAd->StaCfg.WpaSupplicantUP != 1)
-#endif // SIOCSIWGENIE //
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-            	RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, BSS0);
-
-            // Check for WPA PMK cache list
-			if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2)
-			{
-			    INT     idx;
-                BOOLEAN FoundPMK = FALSE;
-				// Search chched PMKID, append it if existed
-				for (idx = 0; idx < PMKID_NO; idx++)
-				{
-					if (NdisEqualMemory(ApAddr, &pAd->StaCfg.SavedPMK[idx].BSSID, 6))
-					{
-						FoundPMK = TRUE;
-						break;
-					}
-				}
-
-				if (FoundPMK)
-				{
-					// Set PMK number
-					*(PUSHORT) &pAd->StaCfg.RSN_IE[pAd->StaCfg.RSNIE_Len] = 1;
-					NdisMoveMemory(&pAd->StaCfg.RSN_IE[pAd->StaCfg.RSNIE_Len + 2], &pAd->StaCfg.SavedPMK[idx].PMKID, 16);
-                    pAd->StaCfg.RSNIE_Len += 18;
-				}
-			}
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-#ifdef SIOCSIWGENIE
-			if (pAd->StaCfg.WpaSupplicantUP == 1)
-			{
-				MakeOutgoingFrame(pOutBuffer + FrameLen,    		&tmp,
-		                        	pAd->StaCfg.RSNIE_Len,			pAd->StaCfg.RSN_IE,
-		                        	END_OF_ARGS);
-			}
-			else
-#endif
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-			{
-				MakeOutgoingFrame(pOutBuffer + FrameLen,    		&tmp,
-				              		1,                              &RSNIe,
-		                        	1,                              &pAd->StaCfg.RSNIE_Len,
-		                        	pAd->StaCfg.RSNIE_Len,			pAd->StaCfg.RSN_IE,
-		                        	END_OF_ARGS);
-			}
-
-			FrameLen += tmp;
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-#ifdef SIOCSIWGENIE
-			if (pAd->StaCfg.WpaSupplicantUP != 1)
-#endif
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-			{
-	            // Append Variable IE
-	            NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &RSNIe, 1);
-	            VarIesOffset += 1;
-	            NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, &pAd->StaCfg.RSNIE_Len, 1);
-	            VarIesOffset += 1;
-			}
-			NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, pAd->StaCfg.RSN_IE, pAd->StaCfg.RSNIE_Len);
-			VarIesOffset += pAd->StaCfg.RSNIE_Len;
-
-			// Set Variable IEs Length
-			pAd->StaCfg.ReqVarIELen = VarIesOffset;
-		}
-
-		// We have update that at PeerBeaconAtJoinRequest()
-		CkipFlag = pAd->StaCfg.CkipFlag;
-		if (CkipFlag != 0)
-		{
-			NdisZeroMemory(CkipNegotiationBuffer, CKIP_NEGOTIATION_LENGTH);
-			CkipNegotiationBuffer[2] = 0x66;
-			// Make it try KP & MIC, since we have to follow the result from AssocRsp
-			CkipNegotiationBuffer[8] = 0x18;
-			CkipNegotiationBuffer[CKIP_NEGOTIATION_LENGTH - 1] = 0x22;
-			CkipFlag = 0x18;
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen, 	&tmp,
-						1,						  		&AironetCkipIe,
-						1,						  		&AironetCkipLen,
-						AironetCkipLen, 		  		CkipNegotiationBuffer,
-						END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-		// Add CCX v2 request if CCX2 admin state is on
-		if (pAd->StaCfg.CCXControl.field.Enable == 1)
-		{
-
-			//
-			// Add AironetIPAddressIE for Cisco CCX 2.X
-			// Add CCX Version
-			//
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-						1,							&AironetIPAddressIE,
-						1,							&AironetIPAddressLen,
-						AironetIPAddressLen,		AironetIPAddressBuffer,
-						1,							&Ccx2Ie,
-						1,							&Ccx2Len,
-						Ccx2Len,				    Ccx2IeInfo,
-						END_OF_ARGS);
-			FrameLen += tmp;
-
-			//
-			// Add CipherSuite CCKM or LeapTkip if setting.
-			//
-#ifdef LEAP_SUPPORT
-			if (LEAP_CCKM_ON(pAd))
-			{
-				MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-						CipherSuiteCiscoCCKMLen,		CipherSuiteCiscoCCKM,
-						END_OF_ARGS);
-				FrameLen += tmp;
-
-				// Third add RSN
-				NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, CipherSuiteCiscoCCKM, CipherSuiteCiscoCCKMLen); //Save CipherSuite
-				VarIesOffset += CipherSuiteCiscoCCKMLen;
-			}
-			else if ((pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP) && (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled))
-			{
-				MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-						CipherSuiteCCXTkipLen,	    CipherSuiteCCXTkip,
-						END_OF_ARGS);
-				FrameLen += tmp;
-
-				// Third add RSN
-				NdisMoveMemory(pAd->StaCfg.ReqVarIEs + VarIesOffset, CipherSuiteCCXTkip, CipherSuiteCCXTkipLen);
-				VarIesOffset += CipherSuiteCCXTkipLen;
-			}
-#endif // LEAP_SUPPORT //
-
-			// Add by James 03/06/27
-			// Set Variable IEs Length
-			pAd->StaCfg.ReqVarIELen = VarIesOffset;
-			pAd->StaCfg.AssocInfo.RequestIELength = VarIesOffset;
-
-			// OffsetResponseIEs follow ReqVarIE
-			pAd->StaCfg.AssocInfo.OffsetResponseIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION) + pAd->StaCfg.ReqVarIELen;
-			// End Add by James
-		}
-
-
-		MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer);
-
-		RTMPSetTimer(&pAd->MlmeAux.AssocTimer, Timeout);
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_WAIT_RSP;
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("ASSOC - MlmeAssocReqAction() sanity check failed. BUG!!!!!! \n"));
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-		Status = MLME_INVALID_FORMAT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-	}
-
-}
-
-/*
-	==========================================================================
-	Description:
-		mlme reassoc req handling procedure
-	Parameters:
-		Elem -
-	Pre:
-		-# SSID  (Adapter->StaCfg.ssid[])
-		-# BSSID (AP address, Adapter->StaCfg.bssid)
-		-# Supported rates (Adapter->StaCfg.supported_rates[])
-		-# Supported rates length (Adapter->StaCfg.supported_rates_len)
-		-# Tx power (Adapter->StaCfg.tx_power)
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID MlmeReassocReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR			ApAddr[6];
-	HEADER_802_11	ReassocHdr;
-	UCHAR			Ccx2Len = 5;
-	UCHAR			WmeIe[9] = {IE_VENDOR_SPECIFIC, 0x07, 0x00, 0x50, 0xf2, 0x02, 0x00, 0x01, 0x00};
-	USHORT			CapabilityInfo, ListenIntv;
-	ULONG			Timeout;
-	ULONG			FrameLen = 0;
-	BOOLEAN			TimerCancelled;
-	NDIS_STATUS		NStatus;
-	ULONG			tmp;
-	PUCHAR			pOutBuffer = NULL;
-//CCX 2.X
-#ifdef LEAP_SUPPORT
-	UCHAR			CkipFlag;
-	UCHAR			CkipNegotiationBuffer[CKIP_NEGOTIATION_LENGTH];
-	UCHAR			AironetCkipIe = IE_AIRONET_CKIP;
-	UCHAR			AironetCkipLen = CKIP_NEGOTIATION_LENGTH;
-	UCHAR			AironetIPAddressIE = IE_AIRONET_IPADDRESS;
-	UCHAR			AironetIPAddressLen = AIRONET_IPADDRESS_LENGTH;
-	UCHAR			AironetIPAddressBuffer[AIRONET_IPADDRESS_LENGTH] = {0x00, 0x40, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00};
-	UCHAR			AironetCCKMReassocIE = IE_AIRONET_CCKMREASSOC;
-	UCHAR			AironetCCKMReassocLen = AIRONET_CCKMREASSOC_LENGTH;
-	UCHAR			AironetCCKMReassocBuffer[AIRONET_CCKMREASSOC_LENGTH];
-	UCHAR			AironetOUI[] = {0x00, 0x40, 0x96, 0x00};
-	UCHAR			MICMN[16];
-	UCHAR			CalcMicBuffer[80];
-	ULONG			CalcMicBufferLen = 0;
-#endif // LEAP_SUPPORT //
-	USHORT			Status;
-
-	// Block all authentication request durning WPA block period
-	if (pAd->StaCfg.bBlockAssoc == TRUE)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Block ReAssoc request durning WPA block period!\n"));
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-		Status = MLME_STATE_MACHINE_REJECT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-	}
-	// the parameters are the same as the association
-	else if(MlmeAssocReqSanity(pAd, Elem->Msg, Elem->MsgLen, ApAddr, &CapabilityInfo, &Timeout, &ListenIntv))
-	{
-		RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer, &TimerCancelled);
-
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-		if(NStatus != NDIS_STATUS_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("ASSOC - MlmeReassocReqAction() allocate memory failed \n"));
-			pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-			Status = MLME_FAIL_NO_RESOURCE;
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-			return;
-		}
-
-		COPY_MAC_ADDR(pAd->MlmeAux.Bssid, ApAddr);
-
-		// make frame, use bssid as the AP address??
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Send RE-ASSOC request...\n"));
-		MgtMacHeaderInit(pAd, &ReassocHdr, SUBTYPE_REASSOC_REQ, 0, ApAddr, ApAddr);
-		MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-						  sizeof(HEADER_802_11),    &ReassocHdr,
-						  2,                        &CapabilityInfo,
-						  2,                        &ListenIntv,
-						  MAC_ADDR_LEN,             ApAddr,
-						  1,                        &SsidIe,
-						  1,                        &pAd->MlmeAux.SsidLen,
-						  pAd->MlmeAux.SsidLen,     pAd->MlmeAux.Ssid,
-						  1,                        &SupRateIe,
-						  1,						&pAd->MlmeAux.SupRateLen,
-						  pAd->MlmeAux.SupRateLen,  pAd->MlmeAux.SupRate,
-						  END_OF_ARGS);
-
-		if (pAd->MlmeAux.ExtRateLen != 0)
-		{
-			MakeOutgoingFrame(pOutBuffer + FrameLen,        &tmp,
-							  1,                            &ExtRateIe,
-							  1,                            &pAd->MlmeAux.ExtRateLen,
-							  pAd->MlmeAux.ExtRateLen,	    pAd->MlmeAux.ExtRate,
-							  END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-		if (pAd->MlmeAux.APEdcaParm.bValid)
-		{
-			if (pAd->CommonCfg.bAPSDCapable && pAd->MlmeAux.APEdcaParm.bAPSDCapable)
-			{
-				QBSS_STA_INFO_PARM QosInfo;
-
-				NdisZeroMemory(&QosInfo, sizeof(QBSS_STA_INFO_PARM));
-				QosInfo.UAPSD_AC_BE = pAd->CommonCfg.bAPSDAC_BE;
-				QosInfo.UAPSD_AC_BK = pAd->CommonCfg.bAPSDAC_BK;
-				QosInfo.UAPSD_AC_VI = pAd->CommonCfg.bAPSDAC_VI;
-				QosInfo.UAPSD_AC_VO = pAd->CommonCfg.bAPSDAC_VO;
-				QosInfo.MaxSPLength = pAd->CommonCfg.MaxSPLength;
-				WmeIe[8] |= *(PUCHAR)&QosInfo;
-			}
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen,    &tmp,
-							  9,                        &WmeIe[0],
-							  END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-#ifdef DOT11_N_SUPPORT
-		// HT
-		if ((pAd->MlmeAux.HtCapabilityLen > 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-		{
-			ULONG TmpLen;
-			UCHAR HtLen;
-			UCHAR BROADCOM[4] = {0x0, 0x90, 0x4c, 0x33};
-			if (pAd->StaActive.SupportedPhyInfo.bPreNHt == TRUE)
-			{
-				HtLen = SIZE_HT_CAP_IE + 4;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-							  1,                                &WpaIe,
-							  1,                                &HtLen,
-							  4,                                &BROADCOM[0],
-							 pAd->MlmeAux.HtCapabilityLen,          &pAd->MlmeAux.HtCapability,
-							  END_OF_ARGS);
-			}
-			else
-			{
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-							  1,                                &HtCapIe,
-							  1,                                &pAd->MlmeAux.HtCapabilityLen,
-							 pAd->MlmeAux.HtCapabilityLen,          &pAd->MlmeAux.HtCapability,
-							  END_OF_ARGS);
-			}
-			FrameLen += TmpLen;
-		}
-#endif // DOT11_N_SUPPORT //
-
-		// add Ralink proprietary IE to inform AP this STA is going to use AGGREGATION or PIGGY-BACK+AGGREGATION
-		// Case I: (Aggregation + Piggy-Back)
-		// 1. user enable aggregation, AND
-		// 2. Mac support piggy-back
-		// 3. AP annouces it's PIGGY-BACK+AGGREGATION-capable in BEACON
-		// Case II: (Aggregation)
-		// 1. user enable aggregation, AND
-		// 2. AP annouces it's AGGREGATION-capable in BEACON
-		if (pAd->CommonCfg.bAggregationCapable)
-		{
-			if ((pAd->CommonCfg.bPiggyBackCapable) && ((pAd->MlmeAux.APRalinkIe & 0x00000003) == 3))
-			{
-				ULONG TmpLen;
-				UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x03, 0x00, 0x00, 0x00};
-				MakeOutgoingFrame(pOutBuffer+FrameLen,           &TmpLen,
-								  9,                             RalinkIe,
-								  END_OF_ARGS);
-				FrameLen += TmpLen;
-			}
-			else if (pAd->MlmeAux.APRalinkIe & 0x00000001)
-			{
-				ULONG TmpLen;
-				UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x01, 0x00, 0x00, 0x00};
-				MakeOutgoingFrame(pOutBuffer+FrameLen,           &TmpLen,
-								  9,                             RalinkIe,
-								  END_OF_ARGS);
-				FrameLen += TmpLen;
-			}
-		}
-		else
-		{
-			ULONG TmpLen;
-			UCHAR RalinkIe[9] = {IE_VENDOR_SPECIFIC, 7, 0x00, 0x0c, 0x43, 0x04, 0x00, 0x00, 0x00};
-			MakeOutgoingFrame(pOutBuffer+FrameLen,		 &TmpLen,
-							  9,						 RalinkIe,
-							  END_OF_ARGS);
-			FrameLen += TmpLen;
-		}
-#ifdef LEAP_SUPPORT
-		if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-		{
-			CkipFlag = pAd->StaCfg.CkipFlag;	// We have update that at PeerBeaconAtJoinRequest()
-			if (CkipFlag != 0)
-			{
-				NdisZeroMemory(CkipNegotiationBuffer, CKIP_NEGOTIATION_LENGTH);
-				CkipNegotiationBuffer[2] = 0x66;
-				// Make it try KP & MIC, since we have to follow the result from AssocRsp
-				CkipNegotiationBuffer[8] = 0x18;
-				CkipNegotiationBuffer[CKIP_NEGOTIATION_LENGTH - 1] = 0x22;
-
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &tmp,
-									1,                              &AironetCkipIe,
-									1,                              &AironetCkipLen,
-									AironetCkipLen,                 CkipNegotiationBuffer,
-									END_OF_ARGS);
-				FrameLen += tmp;
-			}
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-							1,                              &AironetIPAddressIE,
-							1,                              &AironetIPAddressLen,
-							AironetIPAddressLen,            AironetIPAddressBuffer,
-							END_OF_ARGS);
-			FrameLen += tmp;
-
-			//
-			// The RN is incremented before each reassociation request.
-			//
-			pAd->StaCfg.CCKMRN++;
-			//
-			// Calculate MIC = hmac-md5(krk, STA-ID|BSSID|RSNIE|TSF|RN);
-			//
-			COPY_MAC_ADDR(CalcMicBuffer, pAd->CurrentAddress);
-			CalcMicBufferLen = MAC_ADDR_LEN;
-			COPY_MAC_ADDR(CalcMicBuffer + CalcMicBufferLen, pAd->MlmeAux.Bssid);
-			CalcMicBufferLen += MAC_ADDR_LEN;
-			NdisMoveMemory(CalcMicBuffer + CalcMicBufferLen, CipherSuiteCiscoCCKM, CipherSuiteCiscoCCKMLen);
-			CalcMicBufferLen += CipherSuiteCiscoCCKMLen;
-			NdisMoveMemory(CalcMicBuffer + CalcMicBufferLen, (PUCHAR) &pAd->StaCfg.CCKMBeaconAtJoinTimeStamp, sizeof(pAd->StaCfg.CCKMBeaconAtJoinTimeStamp));
-			CalcMicBufferLen += sizeof(pAd->StaCfg.CCKMBeaconAtJoinTimeStamp);
-			NdisMoveMemory(CalcMicBuffer + CalcMicBufferLen, (PUCHAR)&pAd->StaCfg.CCKMRN, sizeof(pAd->StaCfg.CCKMRN));
-			CalcMicBufferLen += sizeof(pAd->StaCfg.CCKMRN);
-			hmac_md5(pAd->StaCfg.KRK, LEN_EAP_MICK, CalcMicBuffer, CalcMicBufferLen, MICMN);
-
-			//
-			// fill up CCKM reassociation request element
-			//
-			NdisMoveMemory(AironetCCKMReassocBuffer, AironetOUI, 4);
-			NdisMoveMemory(AironetCCKMReassocBuffer + 4, (PUCHAR)&pAd->StaCfg.CCKMBeaconAtJoinTimeStamp, 8);
-			NdisMoveMemory(AironetCCKMReassocBuffer + 12, (PUCHAR) &pAd->StaCfg.CCKMRN, 4);
-			NdisMoveMemory(AironetCCKMReassocBuffer +16, MICMN, 8);
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-							1,                      &AironetCCKMReassocIE,
-							1,                      &AironetCCKMReassocLen,
-							AironetCCKMReassocLen,  AironetCCKMReassocBuffer,
-							END_OF_ARGS);
-			FrameLen += tmp;
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-							CipherSuiteCiscoCCKMLen,CipherSuiteCiscoCCKM,
-							END_OF_ARGS);
-			FrameLen += tmp;
-		}
-#endif // LEAP_SUPPORT //
-
-		// Add CCX v2 request if CCX2 admin state is on
-		if (pAd->StaCfg.CCXControl.field.Enable == 1)
-		{
-			//
-			// Add CCX Version
-			//
-			MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp,
-						1,							&Ccx2Ie,
-						1,							&Ccx2Len,
-						Ccx2Len,				    Ccx2IeInfo,
-						END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-		MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer);
-
-		RTMPSetTimer(&pAd->MlmeAux.ReassocTimer, Timeout); /* in mSec */
-		pAd->Mlme.AssocMachine.CurrState = REASSOC_WAIT_RSP;
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("ASSOC - MlmeReassocReqAction() sanity check failed. BUG!!!! \n"));
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-		Status = MLME_INVALID_FORMAT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		Upper layer issues disassoc request
-	Parameters:
-		Elem -
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
- */
-VOID MlmeDisassocReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PMLME_DISASSOC_REQ_STRUCT pDisassocReq;
-	HEADER_802_11         DisassocHdr;
-	PHEADER_802_11        pDisassocHdr;
-	PUCHAR                pOutBuffer = NULL;
-	ULONG                 FrameLen = 0;
-	NDIS_STATUS           NStatus;
-	BOOLEAN               TimerCancelled;
-	ULONG                 Timeout = 0;
-	USHORT                Status;
-
-#ifdef QOS_DLS_SUPPORT
-	// send DLS-TEAR_DOWN message,
-	if (pAd->CommonCfg.bDLSCapable)
-	{
-		UCHAR i;
-
-		// tear down local dls table entry
-		for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-			{
-				RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			}
-		}
-
-		// tear down peer dls table entry
-		for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-			{
-				RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			}
-		}
-	}
-#endif // QOS_DLS_SUPPORT //
-
-	// skip sanity check
-	pDisassocReq = (PMLME_DISASSOC_REQ_STRUCT)(Elem->Msg);
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - MlmeDisassocReqAction() allocate memory failed\n"));
-		pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-		Status = MLME_FAIL_NO_RESOURCE;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_DISASSOC_CONF, 2, &Status);
-		return;
-	}
-
-
-
-	RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer, &TimerCancelled);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Send DISASSOC request[BSSID::%02x:%02x:%02x:%02x:%02x:%02x (Reason=%d)\n",
-				pDisassocReq->Addr[0], pDisassocReq->Addr[1], pDisassocReq->Addr[2],
-				pDisassocReq->Addr[3], pDisassocReq->Addr[4], pDisassocReq->Addr[5], pDisassocReq->Reason));
-	MgtMacHeaderInit(pAd, &DisassocHdr, SUBTYPE_DISASSOC, 0, pDisassocReq->Addr, pDisassocReq->Addr);	// patch peap ttls switching issue
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-					  sizeof(HEADER_802_11),&DisassocHdr,
-					  2,                    &pDisassocReq->Reason,
-					  END_OF_ARGS);
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-
-	// To patch Instance and Buffalo(N) AP
-	// Driver has to send deauth to Instance AP, but Buffalo(N) needs to send disassoc to reset Authenticator's state machine
-	// Therefore, we send both of them.
-	pDisassocHdr = (PHEADER_802_11)pOutBuffer;
-	pDisassocHdr->FC.SubType = SUBTYPE_DEAUTH;
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	pAd->StaCfg.DisassocReason = REASON_DISASSOC_STA_LEAVING;
-	COPY_MAC_ADDR(pAd->StaCfg.DisassocSta, pDisassocReq->Addr);
-
-	RTMPSetTimer(&pAd->MlmeAux.DisassocTimer, Timeout); /* in mSec */
-	pAd->Mlme.AssocMachine.CurrState = DISASSOC_WAIT_RSP;
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-    if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-	{
-        union iwreq_data    wrqu;
-        //send disassociate event to wpa_supplicant
-        memset(&wrqu, 0, sizeof(wrqu));
-        wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-    }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-    {
-        union iwreq_data    wrqu;
-        memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-        wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-    }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-}
-
-/*
-	==========================================================================
-	Description:
-		peer sends assoc rsp back
-	Parameters:
-		Elme - MLME message containing the received frame
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID PeerAssocRspAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT        CapabilityInfo, Status, Aid;
-	UCHAR         SupRate[MAX_LEN_OF_SUPPORTED_RATES], SupRateLen;
-	UCHAR         ExtRate[MAX_LEN_OF_SUPPORTED_RATES], ExtRateLen;
-	UCHAR         Addr2[MAC_ADDR_LEN];
-	BOOLEAN       TimerCancelled;
-	UCHAR         CkipFlag;
-	EDCA_PARM     EdcaParm;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			HtCapabilityLen;
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChannelOffset = 0xff;
-
-	if (PeerAssocRspSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &CapabilityInfo, &Status, &Aid, SupRate, &SupRateLen, ExtRate, &ExtRateLen,
-		&HtCapability,&AddHtInfo, &HtCapabilityLen,&AddHtInfoLen,&NewExtChannelOffset, &EdcaParm, &CkipFlag))
-	{
-		// The frame is for me ?
-		if(MAC_ADDR_EQUAL(Addr2, pAd->MlmeAux.Bssid))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("PeerAssocRspAction():ASSOC - receive ASSOC_RSP to me (status=%d)\n", Status));
-#ifdef DOT11_N_SUPPORT
-			DBGPRINT(RT_DEBUG_TRACE, ("PeerAssocRspAction():MacTable [%d].AMsduSize = %d. ClientStatusFlags = 0x%lx \n",Elem->Wcid, pAd->MacTab.Content[BSSID_WCID].AMsduSize, pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
-#endif // DOT11_N_SUPPORT //
-			RTMPCancelTimer(&pAd->MlmeAux.AssocTimer, &TimerCancelled);
-			if(Status == MLME_SUCCESS)
-			{
-				UCHAR			MaxSupportedRateIn500Kbps = 0;
-				UCHAR			idx;
-
-				// supported rates array may not be sorted. sort it and find the maximum rate
-			    for (idx=0; idx<SupRateLen; idx++)
-                {
-			        if (MaxSupportedRateIn500Kbps < (SupRate[idx] & 0x7f))
-			            MaxSupportedRateIn500Kbps = SupRate[idx] & 0x7f;
-                }
-
-				for (idx=0; idx<ExtRateLen; idx++)
-                {
-			        if (MaxSupportedRateIn500Kbps < (ExtRate[idx] & 0x7f))
-			            MaxSupportedRateIn500Kbps = ExtRate[idx] & 0x7f;
-                }
-				// go to procedure listed on page 376
-				AssocPostProc(pAd, Addr2, CapabilityInfo, Aid, SupRate, SupRateLen, ExtRate, ExtRateLen,
-					&EdcaParm, &HtCapability, HtCapabilityLen, &AddHtInfo);
-
-				StaAddMacTableEntry(pAd, &pAd->MacTab.Content[BSSID_WCID], MaxSupportedRateIn500Kbps, &HtCapability, HtCapabilityLen, CapabilityInfo);
-
-				pAd->StaCfg.CkipFlag = CkipFlag;
-				if (CkipFlag & 0x18)
-				{
-					NdisZeroMemory(pAd->StaCfg.TxSEQ, 4);
-					NdisZeroMemory(pAd->StaCfg.RxSEQ, 4);
-					NdisZeroMemory(pAd->StaCfg.CKIPMIC, 4);
-					pAd->StaCfg.GIV[0] = RandomByte(pAd);
-					pAd->StaCfg.GIV[1] = RandomByte(pAd);
-					pAd->StaCfg.GIV[2] = RandomByte(pAd);
-					pAd->StaCfg.bCkipOn = TRUE;
-					DBGPRINT(RT_DEBUG_TRACE, ("<CCX> pAd->StaCfg.CkipFlag = 0x%02x\n", pAd->StaCfg.CkipFlag));
-				}
-			}
-			else
-			{
-				// Faile on Association, we need to check the status code
-				// Is that a Rogue AP?
-#ifdef LEAP_SUPPORT
-				if ((pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP) && (Status == MLME_ALG_NOT_SUPPORT))
-				{ //Possibly Rogue AP
-					RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, pAd->MlmeAux.Bssid, LEAP_REASON_INVALID_AUTH);
-				}
-#endif // LEAP_SUPPORT //
-			}
-			pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-		}
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - PeerAssocRspAction() sanity check fail\n"));
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		peer sends reassoc rsp
-	Parametrs:
-		Elem - MLME message cntaining the received frame
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID PeerReassocRspAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT      CapabilityInfo;
-	USHORT      Status;
-	USHORT      Aid;
-	UCHAR       SupRate[MAX_LEN_OF_SUPPORTED_RATES], SupRateLen;
-	UCHAR       ExtRate[MAX_LEN_OF_SUPPORTED_RATES], ExtRateLen;
-	UCHAR       Addr2[MAC_ADDR_LEN];
-	UCHAR       CkipFlag;
-	BOOLEAN     TimerCancelled;
-	EDCA_PARM   EdcaParm;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			HtCapabilityLen;
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChannelOffset = 0xff;
-
-	if(PeerAssocRspSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &CapabilityInfo, &Status, &Aid, SupRate, &SupRateLen, ExtRate, &ExtRateLen,
-								&HtCapability,	&AddHtInfo, &HtCapabilityLen, &AddHtInfoLen,&NewExtChannelOffset, &EdcaParm, &CkipFlag))
-	{
-		if(MAC_ADDR_EQUAL(Addr2, pAd->MlmeAux.Bssid)) // The frame is for me ?
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - receive REASSOC_RSP to me (status=%d)\n", Status));
-			RTMPCancelTimer(&pAd->MlmeAux.ReassocTimer, &TimerCancelled);
-
-			if(Status == MLME_SUCCESS)
-			{
-				// go to procedure listed on page 376
-				AssocPostProc(pAd, Addr2, CapabilityInfo, Aid, SupRate, SupRateLen, ExtRate, ExtRateLen,
-					 &EdcaParm, &HtCapability, HtCapabilityLen, &AddHtInfo);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-                if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-                {
-                    union iwreq_data    wrqu;
-
-                    SendAssocIEsToWpaSupplicant(pAd);
-                    memset(&wrqu, 0, sizeof(wrqu));
-                    wrqu.data.flags = RT_ASSOC_EVENT_FLAG;
-                    wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-                }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-                {
-                    union iwreq_data    wrqu;
-                    wext_notify_event_assoc(pAd);
-
-                    memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                    memcpy(wrqu.ap_addr.sa_data, pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
-                    wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-
-                }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-			}
-
-			//
-			// Cisco Leap CCKM supported Re-association.
-			//
-#ifdef LEAP_SUPPORT
-			if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-			{
-				if (CCKMAssocRspSanity(pAd, Elem->Msg, Elem->MsgLen) == TRUE)
-				{
-					pAd->StaCfg.CkipFlag = CkipFlag;
-					if (CkipFlag & 0x18)
-					{
-						NdisZeroMemory(pAd->StaCfg.TxSEQ, 4);
-						NdisZeroMemory(pAd->StaCfg.RxSEQ, 4);
-						NdisZeroMemory(pAd->StaCfg.CKIPMIC, 4);
-						pAd->StaCfg.GIV[0] = RandomByte(pAd);
-						pAd->StaCfg.GIV[1] = RandomByte(pAd);
-						pAd->StaCfg.GIV[2] = RandomByte(pAd);
-						pAd->StaCfg.bCkipOn = TRUE;
-						DBGPRINT(RT_DEBUG_TRACE, ("<CCX> pAd->StaCfg.CkipFlag = 0x%02x\n", pAd->StaCfg.CkipFlag));
-					}
-
-					pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-					MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - CCKMAssocRspSanity() sanity check fail\n"));
-				}
-			}
-			else
-#endif // LEAP_SUPPORT //
-			{
-				// CkipFlag is no use for reassociate
-				pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-				MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-			}
-		}
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - PeerReassocRspAction() sanity check fail\n"));
-	}
-
-}
-
-/*
-	==========================================================================
-	Description:
-		procedures on IEEE 802.11/1999 p.376
-	Parametrs:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AssocPostProc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR pAddr2,
-	IN USHORT CapabilityInfo,
-	IN USHORT Aid,
-	IN UCHAR SupRate[],
-	IN UCHAR SupRateLen,
-	IN UCHAR ExtRate[],
-	IN UCHAR ExtRateLen,
-	IN PEDCA_PARM pEdcaParm,
-	IN HT_CAPABILITY_IE		*pHtCapability,
-	IN UCHAR HtCapabilityLen,
-	IN ADD_HT_INFO_IE		*pAddHtInfo)	// AP might use this additional ht info IE
-{
-	ULONG Idx;
-
-	pAd->MlmeAux.BssType = BSS_INFRA;
-	COPY_MAC_ADDR(pAd->MlmeAux.Bssid, pAddr2);
-	pAd->MlmeAux.Aid = Aid;
-	pAd->MlmeAux.CapabilityInfo = CapabilityInfo & SUPPORTED_CAPABILITY_INFO;
-#ifdef DOT11_N_SUPPORT
-	// Some HT AP might lost WMM IE. We add WMM ourselves. beacuase HT requires QoS on.
-	if ((HtCapabilityLen > 0) && (pEdcaParm->bValid == FALSE))
-	{
-		pEdcaParm->bValid = TRUE;
-		pEdcaParm->Aifsn[0] = 3;
-		pEdcaParm->Aifsn[1] = 7;
-		pEdcaParm->Aifsn[2] = 2;
-		pEdcaParm->Aifsn[3] = 2;
-
-		pEdcaParm->Cwmin[0] = 4;
-		pEdcaParm->Cwmin[1] = 4;
-		pEdcaParm->Cwmin[2] = 3;
-		pEdcaParm->Cwmin[3] = 2;
-
-		pEdcaParm->Cwmax[0] = 10;
-		pEdcaParm->Cwmax[1] = 10;
-		pEdcaParm->Cwmax[2] = 4;
-		pEdcaParm->Cwmax[3] = 3;
-
-		pEdcaParm->Txop[0]  = 0;
-		pEdcaParm->Txop[1]  = 0;
-		pEdcaParm->Txop[2]  = 96;
-		pEdcaParm->Txop[3]  = 48;
-
-	}
-#endif // DOT11_N_SUPPORT //
-
-	NdisMoveMemory(&pAd->MlmeAux.APEdcaParm, pEdcaParm, sizeof(EDCA_PARM));
-
-	// filter out un-supported rates
-	pAd->MlmeAux.SupRateLen = SupRateLen;
-	NdisMoveMemory(pAd->MlmeAux.SupRate, SupRate, SupRateLen);
-	RTMPCheckRates(pAd, pAd->MlmeAux.SupRate, &pAd->MlmeAux.SupRateLen);
-
-	// filter out un-supported rates
-	pAd->MlmeAux.ExtRateLen = ExtRateLen;
-	NdisMoveMemory(pAd->MlmeAux.ExtRate, ExtRate, ExtRateLen);
-	RTMPCheckRates(pAd, pAd->MlmeAux.ExtRate, &pAd->MlmeAux.ExtRateLen);
-
-#ifdef DOT11_N_SUPPORT
-	if (HtCapabilityLen > 0)
-	{
-		RTMPCheckHt(pAd, BSSID_WCID, pHtCapability, pAddHtInfo);
-	}
-	DBGPRINT(RT_DEBUG_TRACE, ("AssocPostProc===>  AP.AMsduSize = %d. ClientStatusFlags = 0x%lx \n", pAd->MacTab.Content[BSSID_WCID].AMsduSize, pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
-
-	DBGPRINT(RT_DEBUG_TRACE, ("AssocPostProc===>    (Mmps=%d, AmsduSize=%d, )\n",
-		pAd->MacTab.Content[BSSID_WCID].MmpsMode, pAd->MacTab.Content[BSSID_WCID].AMsduSize));
-#endif // DOT11_N_SUPPORT //
-
-	// Set New WPA information
-	Idx = BssTableSearch(&pAd->ScanTab, pAddr2, pAd->MlmeAux.Channel);
-	if (Idx == BSS_NOT_FOUND)
-	{
-		DBGPRINT_ERR(("ASSOC - Can't find BSS after receiving Assoc response\n"));
-	}
-	else
-	{
-		// Init variable
-		pAd->MacTab.Content[BSSID_WCID].RSNIE_Len = 0;
-		NdisZeroMemory(pAd->MacTab.Content[BSSID_WCID].RSN_IE, MAX_LEN_OF_RSNIE);
-
-		// Store appropriate RSN_IE for WPA SM negotiation later
-		if ((pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA) && (pAd->ScanTab.BssEntry[Idx].VarIELen != 0))
-		{
-			PUCHAR              pVIE;
-			USHORT              len;
-			PEID_STRUCT         pEid;
-
-			pVIE = pAd->ScanTab.BssEntry[Idx].VarIEs;
-			len	 = pAd->ScanTab.BssEntry[Idx].VarIELen;
-
-			while (len > 0)
-			{
-				pEid = (PEID_STRUCT) pVIE;
-				// For WPA/WPAPSK
-				if ((pEid->Eid == IE_WPA) && (NdisEqualMemory(pEid->Octet, WPA_OUI, 4))
-					&& (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA || pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-				{
-					NdisMoveMemory(pAd->MacTab.Content[BSSID_WCID].RSN_IE, pVIE, (pEid->Len + 2));
-					pAd->MacTab.Content[BSSID_WCID].RSNIE_Len = (pEid->Len + 2);
-					DBGPRINT(RT_DEBUG_TRACE, ("AssocPostProc===> Store RSN_IE for WPA SM negotiation \n"));
-				}
-				// For WPA2/WPA2PSK
-				else if ((pEid->Eid == IE_RSN) && (NdisEqualMemory(pEid->Octet + 2, RSN_OUI, 3))
-					&& (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2 || pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-				{
-					NdisMoveMemory(pAd->MacTab.Content[BSSID_WCID].RSN_IE, pVIE, (pEid->Len + 2));
-					pAd->MacTab.Content[BSSID_WCID].RSNIE_Len = (pEid->Len + 2);
-					DBGPRINT(RT_DEBUG_TRACE, ("AssocPostProc===> Store RSN_IE for WPA2 SM negotiation \n"));
-				}
-
-				pVIE += (pEid->Len + 2);
-				len  -= (pEid->Len + 2);
-			}
-		}
-
-		if (pAd->MacTab.Content[BSSID_WCID].RSNIE_Len == 0)
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("AssocPostProc===> no RSN_IE \n"));
-		}
-		else
-		{
-			hex_dump("RSN_IE", pAd->MacTab.Content[BSSID_WCID].RSN_IE, pAd->MacTab.Content[BSSID_WCID].RSNIE_Len);
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		left part of IEEE 802.11/1999 p.374
-	Parameters:
-		Elem - MLME message containing the received frame
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID PeerDisassocAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR         Addr2[MAC_ADDR_LEN];
-	USHORT        Reason;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - PeerDisassocAction()\n"));
-	if(PeerDisassocSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &Reason))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - PeerDisassocAction() Reason = %d\n", Reason));
-		if (INFRA_ON(pAd) && MAC_ADDR_EQUAL(pAd->CommonCfg.Bssid, Addr2))
-		{
-
-			if (pAd->CommonCfg.bWirelessEvent)
-			{
-				RTMPSendWirelessEvent(pAd, IW_DISASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-			}
-
-
-#ifdef LEAP_SUPPORT
-			if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-			{
-				// Cisco_LEAP has start a timer
-				// We should cancel it if using LEAP
-				RTMPCancelTimer(&pAd->StaCfg.LeapAuthTimer, &TimerCancelled);
-				//Check is it mach the LEAP Authentication failed as possible a Rogue AP
-				//on it's PortSecured not equal to WPA_802_1X_PORT_SECURED while process the Association.
-				if ((pAd->Mlme.LeapMachine.CurrState != LEAP_IDLE) && (pAd->StaCfg.PortSecured != WPA_802_1X_PORT_SECURED))
-				{
-					RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, Addr2, LEAP_REASON_AUTH_TIMEOUT);
-				}
-			}
-#endif	// LEAP_SUPPORT //
-			//
-			// Get Current System time and Turn on AdjacentAPReport
-			//
-			NdisGetSystemUpTime(&pAd->StaCfg.CCXAdjacentAPLinkDownTime);
-			pAd->StaCfg.CCXAdjacentAPReportFlag = TRUE;
-			LinkDown(pAd, TRUE);
-			pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-			{
-                union iwreq_data    wrqu;
-                //send disassociate event to wpa_supplicant
-                memset(&wrqu, 0, sizeof(wrqu));
-                wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-                wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-            {
-                union iwreq_data    wrqu;
-                memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-		}
-	}
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - PeerDisassocAction() sanity check fail\n"));
-	}
-
-}
-
-/*
-	==========================================================================
-	Description:
-		what the state machine will do after assoc timeout
-	Parameters:
-		Elme -
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID AssocTimeoutAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT  Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - AssocTimeoutAction\n"));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_REJ_TIMEOUT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-		what the state machine will do after reassoc timeout
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID ReassocTimeoutAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT  Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - ReassocTimeoutAction\n"));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_REJ_TIMEOUT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-		what the state machine will do after disassoc timeout
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID DisassocTimeoutAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT  Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - DisassocTimeoutAction\n"));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_SUCCESS;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_DISASSOC_CONF, 2, &Status);
-}
-
-VOID InvalidStateWhenAssoc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT  Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - InvalidStateWhenAssoc(state=%ld), reset ASSOC state machine\n",
-		pAd->Mlme.AssocMachine.CurrState));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_ASSOC_CONF, 2, &Status);
-}
-
-VOID InvalidStateWhenReassoc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - InvalidStateWhenReassoc(state=%ld), reset ASSOC state machine\n",
-		pAd->Mlme.AssocMachine.CurrState));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_REASSOC_CONF, 2, &Status);
-}
-
-VOID InvalidStateWhenDisassociate(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - InvalidStateWhenDisassoc(state=%ld), reset ASSOC state machine\n",
-		pAd->Mlme.AssocMachine.CurrState));
-	pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_DISASSOC_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-		right part of IEEE 802.11/1999 page 374
-	Note:
-		This event should never cause ASSOC state machine perform state
-		transition, and has no relationship with CNTL machine. So we separate
-		this routine as a service outside of ASSOC state transition table.
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID Cls3errAction(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR        pAddr)
-{
-	HEADER_802_11         DisassocHdr;
-	PHEADER_802_11        pDisassocHdr;
-	PUCHAR                pOutBuffer = NULL;
-	ULONG                 FrameLen = 0;
-	NDIS_STATUS           NStatus;
-	USHORT                Reason = REASON_CLS3ERR;
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ASSOC - Class 3 Error, Send DISASSOC frame\n"));
-	MgtMacHeaderInit(pAd, &DisassocHdr, SUBTYPE_DISASSOC, 0, pAddr, pAd->CommonCfg.Bssid);	// patch peap ttls switching issue
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-					  sizeof(HEADER_802_11),&DisassocHdr,
-					  2,                    &Reason,
-					  END_OF_ARGS);
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-
-	// To patch Instance and Buffalo(N) AP
-	// Driver has to send deauth to Instance AP, but Buffalo(N) needs to send disassoc to reset Authenticator's state machine
-	// Therefore, we send both of them.
-	pDisassocHdr = (PHEADER_802_11)pOutBuffer;
-	pDisassocHdr->FC.SubType = SUBTYPE_DEAUTH;
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	pAd->StaCfg.DisassocReason = REASON_CLS3ERR;
-	COPY_MAC_ADDR(pAd->StaCfg.DisassocSta, pAddr);
-}
-
- /*
-	 ==========================================================================
-	 Description:
-		 Switch between WEP and CKIP upon new association up.
-	 Parameters:
-
-	 IRQL = DISPATCH_LEVEL
-
-	 ==========================================================================
-  */
-VOID SwitchBetweenWepAndCkip(
-	IN PRTMP_ADAPTER pAd)
-{
-	int            i;
-	SHAREDKEY_MODE_STRUC  csr1;
-
-	// if KP is required. change the CipherAlg in hardware shard key table from WEP
-	// to CKIP. else remain as WEP
-	if (pAd->StaCfg.bCkipOn && (pAd->StaCfg.CkipFlag & 0x10))
-	{
-		// modify hardware key table so that MAC use correct algorithm to decrypt RX
-		RTMP_IO_READ32(pAd, SHARED_KEY_MODE_BASE, &csr1.word);
-		if (csr1.field.Bss0Key0CipherAlg == CIPHER_WEP64)
-			csr1.field.Bss0Key0CipherAlg = CIPHER_CKIP64;
-		else if (csr1.field.Bss0Key0CipherAlg == CIPHER_WEP128)
-			csr1.field.Bss0Key0CipherAlg = CIPHER_CKIP128;
-
-		if (csr1.field.Bss0Key1CipherAlg == CIPHER_WEP64)
-			csr1.field.Bss0Key1CipherAlg = CIPHER_CKIP64;
-		else if (csr1.field.Bss0Key1CipherAlg == CIPHER_WEP128)
-			csr1.field.Bss0Key1CipherAlg = CIPHER_CKIP128;
-
-		if (csr1.field.Bss0Key2CipherAlg == CIPHER_WEP64)
-			csr1.field.Bss0Key2CipherAlg = CIPHER_CKIP64;
-		else if (csr1.field.Bss0Key2CipherAlg == CIPHER_WEP128)
-			csr1.field.Bss0Key2CipherAlg = CIPHER_CKIP128;
-
-		if (csr1.field.Bss0Key3CipherAlg == CIPHER_WEP64)
-			csr1.field.Bss0Key3CipherAlg = CIPHER_CKIP64;
-		else if (csr1.field.Bss0Key3CipherAlg == CIPHER_WEP128)
-			csr1.field.Bss0Key3CipherAlg = CIPHER_CKIP128;
-		RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE, csr1.word);
-		DBGPRINT(RT_DEBUG_TRACE, ("SwitchBetweenWepAndCkip: modify BSS0 cipher to %s\n", CipherName[csr1.field.Bss0Key0CipherAlg]));
-
-		// modify software key table so that driver can specify correct algorithm in TXD upon TX
-		for (i=0; i<SHARE_KEY_NUM; i++)
-		{
-			if (pAd->SharedKey[BSS0][i].CipherAlg == CIPHER_WEP64)
-				pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_CKIP64;
-			else if (pAd->SharedKey[BSS0][i].CipherAlg == CIPHER_WEP128)
-				pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_CKIP128;
-		}
-	}
-
-	// else if KP NOT inused. change the CipherAlg in hardware shard key table from CKIP
-	// to WEP.
-	else
-	{
-		// modify hardware key table so that MAC use correct algorithm to decrypt RX
-		RTMP_IO_READ32(pAd, SHARED_KEY_MODE_BASE, &csr1.word);
-		if (csr1.field.Bss0Key0CipherAlg == CIPHER_CKIP64)
-			csr1.field.Bss0Key0CipherAlg = CIPHER_WEP64;
-		else if (csr1.field.Bss0Key0CipherAlg == CIPHER_CKIP128)
-			csr1.field.Bss0Key0CipherAlg = CIPHER_WEP128;
-
-		if (csr1.field.Bss0Key1CipherAlg == CIPHER_CKIP64)
-			csr1.field.Bss0Key1CipherAlg = CIPHER_WEP64;
-		else if (csr1.field.Bss0Key1CipherAlg == CIPHER_CKIP128)
-			csr1.field.Bss0Key1CipherAlg = CIPHER_WEP128;
-
-		if (csr1.field.Bss0Key2CipherAlg == CIPHER_CKIP64)
-			csr1.field.Bss0Key2CipherAlg = CIPHER_WEP64;
-		else if (csr1.field.Bss0Key2CipherAlg == CIPHER_CKIP128)
-			csr1.field.Bss0Key2CipherAlg = CIPHER_WEP128;
-
-		if (csr1.field.Bss0Key3CipherAlg == CIPHER_CKIP64)
-			csr1.field.Bss0Key3CipherAlg = CIPHER_WEP64;
-		else if (csr1.field.Bss0Key3CipherAlg == CIPHER_CKIP128)
-			csr1.field.Bss0Key3CipherAlg = CIPHER_WEP128;
-
-		// modify software key table so that driver can specify correct algorithm in TXD upon TX
-		for (i=0; i<SHARE_KEY_NUM; i++)
-		{
-			if (pAd->SharedKey[BSS0][i].CipherAlg == CIPHER_CKIP64)
-				pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_WEP64;
-			else if (pAd->SharedKey[BSS0][i].CipherAlg == CIPHER_CKIP128)
-				pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_WEP128;
-		}
-
-		//
-		// On WPA-NONE, must update CipherAlg.
-		// Because the OID_802_11_WEP_STATUS was been set after OID_802_11_ADD_KEY
-		// and CipherAlg will be CIPHER_NONE by Windows ZeroConfig.
-		// So we need to update CipherAlg after connect.
-		//
-		if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-		{
-			for (i = 0; i < SHARE_KEY_NUM; i++)
-			{
-				if (pAd->SharedKey[BSS0][i].KeyLen != 0)
-				{
-					if (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled)
-					{
-						pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_TKIP;
-					}
-					else if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-					{
-						pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_AES;
-					}
-				}
-				else
-				{
-					pAd->SharedKey[BSS0][i].CipherAlg = CIPHER_NONE;
-				}
-			}
-
-			csr1.field.Bss0Key0CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-			csr1.field.Bss0Key1CipherAlg = pAd->SharedKey[BSS0][1].CipherAlg;
-			csr1.field.Bss0Key2CipherAlg = pAd->SharedKey[BSS0][2].CipherAlg;
-			csr1.field.Bss0Key3CipherAlg = pAd->SharedKey[BSS0][3].CipherAlg;
-		}
-		RTMP_IO_WRITE32(pAd, SHARED_KEY_MODE_BASE, csr1.word);
-		DBGPRINT(RT_DEBUG_TRACE, ("SwitchBetweenWepAndCkip: modify BSS0 cipher to %s\n", CipherName[csr1.field.Bss0Key0CipherAlg]));
-	}
-}
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-VOID    SendAssocIEsToWpaSupplicant(
-    IN  PRTMP_ADAPTER pAd)
-{
-    union iwreq_data    wrqu;
-    unsigned char custom[IW_CUSTOM_MAX] = {0};
-
-    if ((pAd->StaCfg.ReqVarIELen + 17) <= IW_CUSTOM_MAX)
-    {
-        sprintf(custom, "ASSOCINFO_ReqIEs=");
-	    NdisMoveMemory(custom+17, pAd->StaCfg.ReqVarIEs, pAd->StaCfg.ReqVarIELen);
-	    memset(&wrqu, 0, sizeof(wrqu));
-        wrqu.data.length = pAd->StaCfg.ReqVarIELen + 17;
-        wrqu.data.flags = RT_REQIE_EVENT_FLAG;
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, custom);
-
-        memset(&wrqu, 0, sizeof(wrqu));
-        wrqu.data.flags = RT_ASSOCINFO_EVENT_FLAG;
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-    }
-    else
-        DBGPRINT(RT_DEBUG_TRACE, ("pAd->StaCfg.ReqVarIELen + 17 > MAX_CUSTOM_LEN\n"));
-
-    return;
-}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-int wext_notify_event_assoc(
-	IN  RTMP_ADAPTER *pAd)
-{
-    union iwreq_data    wrqu;
-    char custom[IW_CUSTOM_MAX] = {0};
-
-#if WIRELESS_EXT > 17
-    if (pAd->StaCfg.ReqVarIELen <= IW_CUSTOM_MAX)
-    {
-        wrqu.data.length = pAd->StaCfg.ReqVarIELen;
-        memcpy(custom, pAd->StaCfg.ReqVarIEs, pAd->StaCfg.ReqVarIELen);
-        wireless_send_event(pAd->net_dev, IWEVASSOCREQIE, &wrqu, custom);
-    }
-    else
-        DBGPRINT(RT_DEBUG_TRACE, ("pAd->StaCfg.ReqVarIELen > MAX_CUSTOM_LEN\n"));
-#else
-    if (((pAd->StaCfg.ReqVarIELen*2) + 17) <= IW_CUSTOM_MAX)
-    {
-        UCHAR   idx;
-        wrqu.data.length = (pAd->StaCfg.ReqVarIELen*2) + 17;
-        sprintf(custom, "ASSOCINFO(ReqIEs=");
-        for (idx=0; idx<pAd->StaCfg.ReqVarIELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAd->StaCfg.ReqVarIEs[idx]);
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, custom);
-    }
-    else
-        DBGPRINT(RT_DEBUG_TRACE, ("(pAd->StaCfg.ReqVarIELen*2) + 17 > MAX_CUSTOM_LEN\n"));
-#endif
-
-	return 0;
-
-}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-
-BOOLEAN StaAddMacTableEntry(
-	IN  PRTMP_ADAPTER		pAd,
-	IN  PMAC_TABLE_ENTRY	pEntry,
-	IN  UCHAR				MaxSupportedRateIn500Kbps,
-	IN  HT_CAPABILITY_IE	*pHtCapability,
-	IN  UCHAR				HtCapabilityLen,
-	IN  USHORT        		CapabilityInfo)
-{
-	UCHAR            MaxSupportedRate = RATE_11;
-
-	if (ADHOC_ON(pAd))
-		CLIENT_STATUS_CLEAR_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-
-	switch (MaxSupportedRateIn500Kbps)
-    {
-        case 108: MaxSupportedRate = RATE_54;   break;
-        case 96:  MaxSupportedRate = RATE_48;   break;
-        case 72:  MaxSupportedRate = RATE_36;   break;
-        case 48:  MaxSupportedRate = RATE_24;   break;
-        case 36:  MaxSupportedRate = RATE_18;   break;
-        case 24:  MaxSupportedRate = RATE_12;   break;
-        case 18:  MaxSupportedRate = RATE_9;    break;
-        case 12:  MaxSupportedRate = RATE_6;    break;
-        case 22:  MaxSupportedRate = RATE_11;   break;
-        case 11:  MaxSupportedRate = RATE_5_5;  break;
-        case 4:   MaxSupportedRate = RATE_2;    break;
-        case 2:   MaxSupportedRate = RATE_1;    break;
-        default:  MaxSupportedRate = RATE_11;   break;
-    }
-
-    if ((pAd->CommonCfg.PhyMode == PHY_11G) && (MaxSupportedRate < RATE_FIRST_OFDM_RATE))
-        return FALSE;
-
-#ifdef DOT11_N_SUPPORT
-	// 11n only
-	if (((pAd->CommonCfg.PhyMode == PHY_11N_2_4G) || (pAd->CommonCfg.PhyMode == PHY_11N_5G))&& (HtCapabilityLen == 0))
-		return FALSE;
-#endif // DOT11_N_SUPPORT //
-
-	if (!pEntry)
-        return FALSE;
-
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-	if (pEntry)
-	{
-		pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
-		if ((MaxSupportedRate < RATE_FIRST_OFDM_RATE) ||
-			(pAd->CommonCfg.PhyMode == PHY_11B))
-		{
-			pEntry->RateLen = 4;
-			if (MaxSupportedRate >= RATE_FIRST_OFDM_RATE)
-				MaxSupportedRate = RATE_11;
-		}
-		else
-			pEntry->RateLen = 12;
-
-		pEntry->MaxHTPhyMode.word = 0;
-		pEntry->MinHTPhyMode.word = 0;
-		pEntry->HTPhyMode.word = 0;
-		pEntry->MaxSupportedRate = MaxSupportedRate;
-		if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
-		{
-			pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
-			pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-			pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
-			pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-			pEntry->HTPhyMode.field.MODE = MODE_CCK;
-			pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-		}
-		else
-		{
-			pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
-			pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-			pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
-			pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-			pEntry->HTPhyMode.field.MODE = MODE_OFDM;
-			pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-		}
-		pEntry->CapabilityInfo = CapabilityInfo;
-		CLIENT_STATUS_CLEAR_FLAG(pEntry, fCLIENT_STATUS_AGGREGATION_CAPABLE);
-		CLIENT_STATUS_CLEAR_FLAG(pEntry, fCLIENT_STATUS_PIGGYBACK_CAPABLE);
-	}
-
-#ifdef DOT11_N_SUPPORT
-	// If this Entry supports 802.11n, upgrade to HT rate.
-	if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-	{
-		UCHAR	j, bitmask; //k,bitmask;
-		CHAR    i;
-
-		if (ADHOC_ON(pAd))
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-		if ((pHtCapability->HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-		{
-			pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
-		}
-		else
-		{
-			pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-			pAd->MacTab.fAnyStationNonGF = TRUE;
-			pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
-		}
-
-		if ((pHtCapability->HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
-		{
-			pEntry->MaxHTPhyMode.field.BW= BW_40;
-			pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(pHtCapability->HtCapInfo.ShortGIfor40));
-		}
-		else
-		{
-			pEntry->MaxHTPhyMode.field.BW = BW_20;
-			pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(pHtCapability->HtCapInfo.ShortGIfor20));
-			pAd->MacTab.fAnyStation20Only = TRUE;
-		}
-
-		// 3*3
-		if (pAd->MACVersion >= RALINK_2883_VERSION && pAd->MACVersion < RALINK_3070_VERSION)
-			pEntry->MaxHTPhyMode.field.TxBF = pAd->CommonCfg.RegTransmitSetting.field.TxBF;
-
-		// find max fixed rate
-		for (i=23; i>=0; i--) // 3*3
-		{
-			j = i/8;
-			bitmask = (1<<(i-(j*8)));
-			if ((pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j] & bitmask) && (pHtCapability->MCSSet[j] & bitmask))
-			{
-				pEntry->MaxHTPhyMode.field.MCS = i;
-				break;
-			}
-			if (i==0)
-				break;
-		}
-
-
-		if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
-		{
-			if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
-			{
-				// Fix MCS as HT Duplicated Mode
-				pEntry->MaxHTPhyMode.field.BW = 1;
-				pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-				pEntry->MaxHTPhyMode.field.STBC = 0;
-				pEntry->MaxHTPhyMode.field.ShortGI = 0;
-				pEntry->MaxHTPhyMode.field.MCS = 32;
-			}
-			else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
-			{
-				// STA supports fixed MCS
-				pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
-			}
-		}
-
-		pEntry->MaxHTPhyMode.field.STBC = (pHtCapability->HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
-		pEntry->MpduDensity = pHtCapability->HtCapParm.MpduDensity;
-		pEntry->MaxRAmpduFactor = pHtCapability->HtCapParm.MaxRAmpduFactor;
-		pEntry->MmpsMode = (UCHAR)pHtCapability->HtCapInfo.MimoPs;
-		pEntry->AMsduSize = (UCHAR)pHtCapability->HtCapInfo.AMsduSize;
-		pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-
-		if (pAd->CommonCfg.DesiredHtPhy.AmsduEnable && (pAd->CommonCfg.REGBACapability.field.AutoBA == FALSE))
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_AMSDU_INUSED);
-		if (pHtCapability->HtCapInfo.ShortGIfor20)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
-		if (pHtCapability->HtCapInfo.ShortGIfor40)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
-		if (pHtCapability->HtCapInfo.TxSTBC)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
-		if (pHtCapability->HtCapInfo.RxSTBC)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
-		if (pHtCapability->ExtHtCapInfo.PlusHTC)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
-		if (pAd->CommonCfg.bRdg && pHtCapability->ExtHtCapInfo.RDGSupport)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
-		if (pHtCapability->ExtHtCapInfo.MCSFeedback == 0x03)
-			CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
-	}
-	else
-	{
-		pAd->MacTab.fAnyStationIsLegacy = TRUE;
-	}
-
-	NdisMoveMemory(&pEntry->HTCapability, pHtCapability, sizeof(HT_CAPABILITY_IE));
-#endif // DOT11_N_SUPPORT //
-
-	pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-	pEntry->CurrTxRate = pEntry->MaxSupportedRate;
-
-	// Set asic auto fall back
-	if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-	{
-		PUCHAR					pTable;
-		UCHAR					TableSize = 0;
-
-		MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
-		pEntry->bAutoTxRateSwitch = TRUE;
-	}
-	else
-	{
-		pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-		pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
-		pEntry->bAutoTxRateSwitch = FALSE;
-
-		// If the legacy mode is set, overwrite the transmit setting of this entry.
-		RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-	}
-
-	pEntry->PortSecured = WPA_802_1X_PORT_SECURED;
-	pEntry->Sst = SST_ASSOC;
-	pEntry->AuthState = AS_AUTH_OPEN;
-	pEntry->AuthMode = pAd->StaCfg.AuthMode;
-	pEntry->WepStatus = pAd->StaCfg.WepStatus;
-
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-    if (pAd->StaCfg.WpaSupplicantUP)
-    {
-        union iwreq_data    wrqu;
-
-        SendAssocIEsToWpaSupplicant(pAd);
-        memset(&wrqu, 0, sizeof(wrqu));
-        wrqu.data.flags = RT_ASSOC_EVENT_FLAG;
-        wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-    }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-    {
-        union iwreq_data    wrqu;
-        wext_notify_event_assoc(pAd);
-
-        memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-        memcpy(wrqu.ap_addr.sa_data, pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
-        wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-
-    }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-	return TRUE;
-}
-
-
+#include "../../rt2870/sta/assoc.c"
diff --git a/drivers/staging/rt3070/sta/auth.c b/drivers/staging/rt3070/sta/auth.c
index 032b5df..d551982 100644
--- a/drivers/staging/rt3070/sta/auth.c
+++ b/drivers/staging/rt3070/sta/auth.c
@@ -1,475 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	auth.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John		2004-9-3		porting from RT2500
-*/
-#include "../rt_config.h"
-
-/*
-    ==========================================================================
-    Description:
-        authenticate state machine init, including state transition and timer init
-    Parameters:
-        Sm - pointer to the auth state machine
-    Note:
-        The state machine looks like this
-
-                        AUTH_REQ_IDLE           AUTH_WAIT_SEQ2                   AUTH_WAIT_SEQ4
-    MT2_MLME_AUTH_REQ   mlme_auth_req_action    invalid_state_when_auth          invalid_state_when_auth
-    MT2_PEER_AUTH_EVEN  drop                    peer_auth_even_at_seq2_action    peer_auth_even_at_seq4_action
-    MT2_AUTH_TIMEOUT    Drop                    auth_timeout_action              auth_timeout_action
-
-	IRQL = PASSIVE_LEVEL
-
-    ==========================================================================
- */
-
-void AuthStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[])
-{
-    StateMachineInit(Sm, Trans, MAX_AUTH_STATE, MAX_AUTH_MSG, (STATE_MACHINE_FUNC)Drop, AUTH_REQ_IDLE, AUTH_MACHINE_BASE);
-
-    // the first column
-    StateMachineSetAction(Sm, AUTH_REQ_IDLE, MT2_MLME_AUTH_REQ, (STATE_MACHINE_FUNC)MlmeAuthReqAction);
-
-    // the second column
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ2, MT2_MLME_AUTH_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenAuth);
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ2, MT2_PEER_AUTH_EVEN, (STATE_MACHINE_FUNC)PeerAuthRspAtSeq2Action);
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ2, MT2_AUTH_TIMEOUT, (STATE_MACHINE_FUNC)AuthTimeoutAction);
-
-    // the third column
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ4, MT2_MLME_AUTH_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenAuth);
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ4, MT2_PEER_AUTH_EVEN, (STATE_MACHINE_FUNC)PeerAuthRspAtSeq4Action);
-    StateMachineSetAction(Sm, AUTH_WAIT_SEQ4, MT2_AUTH_TIMEOUT, (STATE_MACHINE_FUNC)AuthTimeoutAction);
-
-	RTMPInitTimer(pAd, &pAd->MlmeAux.AuthTimer, GET_TIMER_FUNCTION(AuthTimeout), pAd, FALSE);
-}
-
-/*
-    ==========================================================================
-    Description:
-        function to be executed at timer thread when auth timer expires
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID AuthTimeout(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3)
-{
-    RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-    DBGPRINT(RT_DEBUG_TRACE,("AUTH - AuthTimeout\n"));
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST))
-		return;
-
-	// send a de-auth to reset AP's state machine (Patch AP-Dir635)
-	if (pAd->Mlme.AuthMachine.CurrState == AUTH_WAIT_SEQ2)
-		Cls2errAction(pAd, pAd->MlmeAux.Bssid);
-
-
-    MlmeEnqueue(pAd, AUTH_STATE_MACHINE, MT2_AUTH_TIMEOUT, 0, NULL);
-    RT28XX_MLME_HANDLER(pAd);
-}
-
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeAuthReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    UCHAR              Addr[6];
-    USHORT             Alg, Seq, Status;
-    ULONG              Timeout;
-    HEADER_802_11      AuthHdr;
-    BOOLEAN            TimerCancelled;
-    NDIS_STATUS        NStatus;
-    PUCHAR             pOutBuffer = NULL;
-    ULONG              FrameLen = 0;
-
-	// Block all authentication request durning WPA block period
-	if (pAd->StaCfg.bBlockAssoc == TRUE)
-	{
-        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Block Auth request durning WPA block period!\n"));
-        pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-        Status = MLME_STATE_MACHINE_REJECT;
-        MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-	}
-    else if(MlmeAuthReqSanity(pAd, Elem->Msg, Elem->MsgLen, Addr, &Timeout, &Alg))
-    {
-        // reset timer
-        RTMPCancelTimer(&pAd->MlmeAux.AuthTimer, &TimerCancelled);
-        COPY_MAC_ADDR(pAd->MlmeAux.Bssid, Addr);
-        pAd->MlmeAux.Alg  = Alg;
-        Seq = 1;
-        Status = MLME_SUCCESS;
-
-        NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-        if(NStatus != NDIS_STATUS_SUCCESS)
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("AUTH - MlmeAuthReqAction(Alg:%d) allocate memory failed\n", Alg));
-            pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-            Status = MLME_FAIL_NO_RESOURCE;
-            MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-            return;
-        }
-
-        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Send AUTH request seq#1 (Alg=%d)...\n", Alg));
-        MgtMacHeaderInit(pAd, &AuthHdr, SUBTYPE_AUTH, 0, Addr, pAd->MlmeAux.Bssid);
-        MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-                          sizeof(HEADER_802_11),&AuthHdr,
-                          2,                    &Alg,
-                          2,                    &Seq,
-                          2,                    &Status,
-                          END_OF_ARGS);
-        MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-    	MlmeFreeMemory(pAd, pOutBuffer);
-
-        RTMPSetTimer(&pAd->MlmeAux.AuthTimer, Timeout);
-        pAd->Mlme.AuthMachine.CurrState = AUTH_WAIT_SEQ2;
-    }
-    else
-    {
-        DBGPRINT_ERR(("AUTH - MlmeAuthReqAction() sanity check failed\n"));
-        pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-        Status = MLME_INVALID_FORMAT;
-        MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerAuthRspAtSeq2Action(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    UCHAR         Addr2[MAC_ADDR_LEN];
-    USHORT        Seq, Status, RemoteStatus, Alg;
-    UCHAR         ChlgText[CIPHER_TEXT_LEN];
-    UCHAR         CyperChlgText[CIPHER_TEXT_LEN + 8 + 8];
-    UCHAR         Element[2];
-    HEADER_802_11 AuthHdr;
-    BOOLEAN       TimerCancelled;
-    PUCHAR        pOutBuffer = NULL;
-    NDIS_STATUS   NStatus;
-    ULONG         FrameLen = 0;
-    USHORT        Status2;
-
-    if (PeerAuthSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &Alg, &Seq, &Status, ChlgText))
-    {
-        if (MAC_ADDR_EQUAL(pAd->MlmeAux.Bssid, Addr2) && Seq == 2)
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Receive AUTH_RSP seq#2 to me (Alg=%d, Status=%d)\n", Alg, Status));
-            RTMPCancelTimer(&pAd->MlmeAux.AuthTimer, &TimerCancelled);
-
-            if (Status == MLME_SUCCESS)
-            {
-                // Authentication Mode "LEAP" has allow for CCX 1.X
-                if ((pAd->MlmeAux.Alg == Ndis802_11AuthModeOpen)
-#ifdef LEAP_SUPPORT
-					|| (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
-				)
-                {
-                    pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-#ifdef LEAP_SUPPORT
-                    pAd->Mlme.LeapMachine.CurrState = LEAP_IDLE;
-#endif // LEAP_SUPPORT //
-                    MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-                }
-                else
-                {
-                    // 2. shared key, need to be challenged
-                    Seq++;
-                    RemoteStatus = MLME_SUCCESS;
-
-					// Get an unused nonpaged memory
-                    NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-                    if(NStatus != NDIS_STATUS_SUCCESS)
-                    {
-                        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - PeerAuthRspAtSeq2Action() allocate memory fail\n"));
-                        pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-                        Status2 = MLME_FAIL_NO_RESOURCE;
-                        MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status2);
-                        return;
-                    }
-
-                    DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Send AUTH request seq#3...\n"));
-                    MgtMacHeaderInit(pAd, &AuthHdr, SUBTYPE_AUTH, 0, Addr2, pAd->MlmeAux.Bssid);
-                    AuthHdr.FC.Wep = 1;
-                    // Encrypt challenge text & auth information
-                    RTMPInitWepEngine(
-                    	pAd,
-                    	pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key,
-                    	pAd->StaCfg.DefaultKeyId,
-                    	pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].KeyLen,
-                    	CyperChlgText);
-
-					Alg = cpu2le16(*(USHORT *)&Alg);
-					Seq = cpu2le16(*(USHORT *)&Seq);
-					RemoteStatus= cpu2le16(*(USHORT *)&RemoteStatus);
-
-					RTMPEncryptData(pAd, (PUCHAR) &Alg, CyperChlgText + 4, 2);
-					RTMPEncryptData(pAd, (PUCHAR) &Seq, CyperChlgText + 6, 2);
-					RTMPEncryptData(pAd, (PUCHAR) &RemoteStatus, CyperChlgText + 8, 2);
-					Element[0] = 16;
-					Element[1] = 128;
-					RTMPEncryptData(pAd, Element, CyperChlgText + 10, 2);
-					RTMPEncryptData(pAd, ChlgText, CyperChlgText + 12, 128);
-					RTMPSetICV(pAd, CyperChlgText + 140);
-                    MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-                                      sizeof(HEADER_802_11),    &AuthHdr,
-                                      CIPHER_TEXT_LEN + 16,     CyperChlgText,
-                                      END_OF_ARGS);
-                    MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-                	MlmeFreeMemory(pAd, pOutBuffer);
-
-                    RTMPSetTimer(&pAd->MlmeAux.AuthTimer, AUTH_TIMEOUT);
-                    pAd->Mlme.AuthMachine.CurrState = AUTH_WAIT_SEQ4;
-                }
-            }
-            else
-            {
-#ifdef LEAP_SUPPORT
-                if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-                {
-                    //Invalid Authentication possible rogue AP
-                    //Add this Ap to Rogue AP.
-                    RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, Addr2, LEAP_REASON_INVALID_AUTH);
-				}
-#endif // LEAP_SUPPORT //
-                pAd->StaCfg.AuthFailReason = Status;
-                COPY_MAC_ADDR(pAd->StaCfg.AuthFailSta, Addr2);
-                pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-                MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-            }
-        }
-    }
-    else
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - PeerAuthSanity() sanity check fail\n"));
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerAuthRspAtSeq4Action(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    UCHAR         Addr2[MAC_ADDR_LEN];
-    USHORT        Alg, Seq, Status;
-    CHAR          ChlgText[CIPHER_TEXT_LEN];
-    BOOLEAN       TimerCancelled;
-
-    if(PeerAuthSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &Alg, &Seq, &Status, ChlgText))
-    {
-        if(MAC_ADDR_EQUAL(pAd->MlmeAux.Bssid, Addr2) && Seq == 4)
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Receive AUTH_RSP seq#4 to me\n"));
-            RTMPCancelTimer(&pAd->MlmeAux.AuthTimer, &TimerCancelled);
-
-            if (Status != MLME_SUCCESS)
-            {
-                pAd->StaCfg.AuthFailReason = Status;
-                COPY_MAC_ADDR(pAd->StaCfg.AuthFailSta, Addr2);
-            }
-
-            pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-            MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-        }
-    }
-    else
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - PeerAuthRspAtSeq4Action() sanity check fail\n"));
-    }
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeDeauthReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    MLME_DEAUTH_REQ_STRUCT *pInfo;
-    HEADER_802_11 DeauthHdr;
-    PUCHAR        pOutBuffer = NULL;
-    NDIS_STATUS   NStatus;
-    ULONG         FrameLen = 0;
-    USHORT        Status;
-
-    pInfo = (MLME_DEAUTH_REQ_STRUCT *)Elem->Msg;
-
-    NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-    if (NStatus != NDIS_STATUS_SUCCESS)
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("AUTH - MlmeDeauthReqAction() allocate memory fail\n"));
-        pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-        Status = MLME_FAIL_NO_RESOURCE;
-        MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_DEAUTH_CONF, 2, &Status);
-        return;
-    }
-
-
-    DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Send DE-AUTH request (Reason=%d)...\n", pInfo->Reason));
-    MgtMacHeaderInit(pAd, &DeauthHdr, SUBTYPE_DEAUTH, 0, pInfo->Addr, pAd->MlmeAux.Bssid);
-    MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-                      sizeof(HEADER_802_11),&DeauthHdr,
-                      2,                    &pInfo->Reason,
-                      END_OF_ARGS);
-    MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-    pAd->StaCfg.DeauthReason = pInfo->Reason;
-    COPY_MAC_ADDR(pAd->StaCfg.DeauthSta, pInfo->Addr);
-    pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-    Status = MLME_SUCCESS;
-    MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_DEAUTH_CONF, 2, &Status);
-
-	// send wireless event - for deauthentication
-	if (pAd->CommonCfg.bWirelessEvent)
-		RTMPSendWirelessEvent(pAd, IW_DEAUTH_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID AuthTimeoutAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    USHORT Status;
-    DBGPRINT(RT_DEBUG_TRACE, ("AUTH - AuthTimeoutAction\n"));
-    pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-    Status = MLME_REJ_TIMEOUT;
-    MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID InvalidStateWhenAuth(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-    USHORT Status;
-    DBGPRINT(RT_DEBUG_TRACE, ("AUTH - InvalidStateWhenAuth (state=%ld), reset AUTH state machine\n", pAd->Mlme.AuthMachine.CurrState));
-    pAd->Mlme.AuthMachine.CurrState = AUTH_REQ_IDLE;
-    Status = MLME_STATE_MACHINE_REJECT;
-    MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_AUTH_CONF, 2, &Status);
-}
-
-/*
-    ==========================================================================
-    Description:
-        Some STA/AP
-    Note:
-        This action should never trigger AUTH state transition, therefore we
-        separate it from AUTH state machine, and make it as a standalone service
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID Cls2errAction(
-    IN PRTMP_ADAPTER pAd,
-    IN PUCHAR pAddr)
-{
-    HEADER_802_11 DeauthHdr;
-    PUCHAR        pOutBuffer = NULL;
-    NDIS_STATUS   NStatus;
-    ULONG         FrameLen = 0;
-    USHORT        Reason = REASON_CLS2ERR;
-
-    NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-    if (NStatus != NDIS_STATUS_SUCCESS)
-        return;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("AUTH - Class 2 error, Send DEAUTH frame...\n"));
-    MgtMacHeaderInit(pAd, &DeauthHdr, SUBTYPE_DEAUTH, 0, pAddr, pAd->MlmeAux.Bssid);
-    MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-                      sizeof(HEADER_802_11),&DeauthHdr,
-                      2,                    &Reason,
-                      END_OF_ARGS);
-    MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-    pAd->StaCfg.DeauthReason = Reason;
-    COPY_MAC_ADDR(pAd->StaCfg.DeauthSta, pAddr);
-}
-
-
+#include "../../rt2870/sta/auth.c"
diff --git a/drivers/staging/rt3070/sta/auth_rsp.c b/drivers/staging/rt3070/sta/auth_rsp.c
index f7aa4b9..c4ea2dc 100644
--- a/drivers/staging/rt3070/sta/auth_rsp.c
+++ b/drivers/staging/rt3070/sta/auth_rsp.c
@@ -1,167 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	auth_rsp.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John		2004-10-1		copy from RT2560
-*/
-#include "../rt_config.h"
-
-/*
-    ==========================================================================
-    Description:
-        authentication state machine init procedure
-    Parameters:
-        Sm - the state machine
-
-	IRQL = PASSIVE_LEVEL
-
-    ==========================================================================
- */
-VOID AuthRspStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN PSTATE_MACHINE Sm,
-    IN STATE_MACHINE_FUNC Trans[])
-{
-    StateMachineInit(Sm, Trans, MAX_AUTH_RSP_STATE, MAX_AUTH_RSP_MSG, (STATE_MACHINE_FUNC)Drop, AUTH_RSP_IDLE, AUTH_RSP_MACHINE_BASE);
-
-    // column 1
-    StateMachineSetAction(Sm, AUTH_RSP_IDLE, MT2_PEER_DEAUTH, (STATE_MACHINE_FUNC)PeerDeauthAction);
-
-    // column 2
-    StateMachineSetAction(Sm, AUTH_RSP_WAIT_CHAL, MT2_PEER_DEAUTH, (STATE_MACHINE_FUNC)PeerDeauthAction);
-
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
-*/
-VOID PeerAuthSimpleRspGenAndSend(
-    IN PRTMP_ADAPTER pAd,
-    IN PHEADER_802_11 pHdr80211,
-    IN USHORT Alg,
-    IN USHORT Seq,
-    IN USHORT Reason,
-    IN USHORT Status)
-{
-    HEADER_802_11     AuthHdr;
-    ULONG             FrameLen = 0;
-    PUCHAR            pOutBuffer = NULL;
-    NDIS_STATUS       NStatus;
-
-    if (Reason != MLME_SUCCESS)
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("Peer AUTH fail...\n"));
-        return;
-    }
-
-	//Get an unused nonpaged memory
-    NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-    if (NStatus != NDIS_STATUS_SUCCESS)
-        return;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Send AUTH response (seq#2)...\n"));
-    MgtMacHeaderInit(pAd, &AuthHdr, SUBTYPE_AUTH, 0, pHdr80211->Addr2, pAd->MlmeAux.Bssid);
-    MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-                      sizeof(HEADER_802_11),    &AuthHdr,
-                      2,                        &Alg,
-                      2,                        &Seq,
-                      2,                        &Reason,
-                      END_OF_ARGS);
-    MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
-*/
-VOID PeerDeauthAction(
-    IN PRTMP_ADAPTER pAd,
-    IN PMLME_QUEUE_ELEM Elem)
-{
-    UCHAR       Addr2[MAC_ADDR_LEN];
-    USHORT      Reason;
-
-    if (PeerDeauthSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, &Reason))
-    {
-        if (INFRA_ON(pAd) && MAC_ADDR_EQUAL(Addr2, pAd->CommonCfg.Bssid))
-        {
-            DBGPRINT(RT_DEBUG_TRACE,("AUTH_RSP - receive DE-AUTH from our AP (Reason=%d)\n", Reason));
-
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-            {
-                union iwreq_data    wrqu;
-                memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-
-			// send wireless event - for deauthentication
-			if (pAd->CommonCfg.bWirelessEvent)
-				RTMPSendWirelessEvent(pAd, IW_DEAUTH_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-
-            LinkDown(pAd, TRUE);
-
-            // Authentication Mode Cisco_LEAP has start a timer
-            // We should cancel it if using LEAP
-#ifdef LEAP_SUPPORT
-            if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-            {
-                RTMPCancelTimer(&pAd->StaCfg.LeapAuthTimer, &TimerCancelled);
-                //Check is it mach the LEAP Authentication failed as possible a Rogue AP
-                //on it's PortSecured not equal to WPA_802_1X_PORT_SECURED while process the Authenticaton.
-                if ((pAd->StaCfg.PortSecured != WPA_802_1X_PORT_SECURED) && (pAd->Mlme.LeapMachine.CurrState != LEAP_IDLE))
-                {
-                    RogueApTableSetEntry(pAd, &pAd->StaCfg.RogueApTab, Addr2, LEAP_REASON_AUTH_TIMEOUT);
-                }
-            }
-#endif // LEAP_SUPPORT //
-        }
-    }
-    else
-    {
-        DBGPRINT(RT_DEBUG_TRACE,("AUTH_RSP - PeerDeauthAction() sanity check fail\n"));
-    }
-}
-
+#include "../../rt2870/sta/auth_rsp.c"
diff --git a/drivers/staging/rt3070/sta/connect.c b/drivers/staging/rt3070/sta/connect.c
index 152c0bd..d77802c 100644
--- a/drivers/staging/rt3070/sta/connect.c
+++ b/drivers/staging/rt3070/sta/connect.c
@@ -1,2857 +1,2 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	connect.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John			2004-08-08			Major modification from RT2560
-*/
-#include "../rt_config.h"
-
-UCHAR	CipherSuiteWpaNoneTkip[] = {
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x02,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x02,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x00	// authentication
-		};
-UCHAR	CipherSuiteWpaNoneTkipLen = (sizeof(CipherSuiteWpaNoneTkip) / sizeof(UCHAR));
-
-UCHAR	CipherSuiteWpaNoneAes[] = {
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x04,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x04,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x00	// authentication
-		};
-UCHAR	CipherSuiteWpaNoneAesLen = (sizeof(CipherSuiteWpaNoneAes) / sizeof(UCHAR));
-
-// The following MACRO is called after 1. starting an new IBSS, 2. succesfully JOIN an IBSS,
-// or 3. succesfully ASSOCIATE to a BSS, 4. successfully RE_ASSOCIATE to a BSS
-// All settings successfuly negotiated furing MLME state machines become final settings
-// and are copied to pAd->StaActive
-#define COPY_SETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(_pAd)                                 \
-{                                                                                       \
-	(_pAd)->CommonCfg.SsidLen = (_pAd)->MlmeAux.SsidLen;                                \
-	NdisMoveMemory((_pAd)->CommonCfg.Ssid, (_pAd)->MlmeAux.Ssid, (_pAd)->MlmeAux.SsidLen); \
-	COPY_MAC_ADDR((_pAd)->CommonCfg.Bssid, (_pAd)->MlmeAux.Bssid);                      \
-	(_pAd)->CommonCfg.Channel = (_pAd)->MlmeAux.Channel;                                \
-	(_pAd)->CommonCfg.CentralChannel = (_pAd)->MlmeAux.CentralChannel;                  \
-	(_pAd)->StaActive.Aid = (_pAd)->MlmeAux.Aid;                                        \
-	(_pAd)->StaActive.AtimWin = (_pAd)->MlmeAux.AtimWin;                                \
-	(_pAd)->StaActive.CapabilityInfo = (_pAd)->MlmeAux.CapabilityInfo;                  \
-	(_pAd)->CommonCfg.BeaconPeriod = (_pAd)->MlmeAux.BeaconPeriod;                      \
-	(_pAd)->StaActive.CfpMaxDuration = (_pAd)->MlmeAux.CfpMaxDuration;                  \
-	(_pAd)->StaActive.CfpPeriod = (_pAd)->MlmeAux.CfpPeriod;                            \
-	(_pAd)->StaActive.SupRateLen = (_pAd)->MlmeAux.SupRateLen;                          \
-	NdisMoveMemory((_pAd)->StaActive.SupRate, (_pAd)->MlmeAux.SupRate, (_pAd)->MlmeAux.SupRateLen);\
-	(_pAd)->StaActive.ExtRateLen = (_pAd)->MlmeAux.ExtRateLen;                          \
-	NdisMoveMemory((_pAd)->StaActive.ExtRate, (_pAd)->MlmeAux.ExtRate, (_pAd)->MlmeAux.ExtRateLen);\
-	NdisMoveMemory(&(_pAd)->CommonCfg.APEdcaParm, &(_pAd)->MlmeAux.APEdcaParm, sizeof(EDCA_PARM));\
-	NdisMoveMemory(&(_pAd)->CommonCfg.APQosCapability, &(_pAd)->MlmeAux.APQosCapability, sizeof(QOS_CAPABILITY_PARM));\
-	NdisMoveMemory(&(_pAd)->CommonCfg.APQbssLoad, &(_pAd)->MlmeAux.APQbssLoad, sizeof(QBSS_LOAD_PARM));\
-	COPY_MAC_ADDR((_pAd)->MacTab.Content[BSSID_WCID].Addr, (_pAd)->MlmeAux.Bssid);      \
-	(_pAd)->MacTab.Content[BSSID_WCID].Aid = (_pAd)->MlmeAux.Aid;                       \
-	(_pAd)->MacTab.Content[BSSID_WCID].PairwiseKey.CipherAlg = (_pAd)->StaCfg.PairCipher;\
-	COPY_MAC_ADDR((_pAd)->MacTab.Content[BSSID_WCID].PairwiseKey.BssId, (_pAd)->MlmeAux.Bssid);\
-	(_pAd)->MacTab.Content[BSSID_WCID].RateLen = (_pAd)->StaActive.SupRateLen + (_pAd)->StaActive.ExtRateLen;\
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = PASSIVE_LEVEL
-
-	==========================================================================
-*/
-VOID MlmeCntlInit(
-	IN PRTMP_ADAPTER pAd,
-	IN STATE_MACHINE *S,
-	OUT STATE_MACHINE_FUNC Trans[])
-{
-	// Control state machine differs from other state machines, the interface
-	// follows the standard interface
-	pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID MlmeCntlMachinePerformAction(
-	IN PRTMP_ADAPTER pAd,
-	IN STATE_MACHINE *S,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	switch(pAd->Mlme.CntlMachine.CurrState)
-	{
-		case CNTL_IDLE:
-			{
-				CntlIdleProc(pAd, Elem);
-			}
-			break;
-		case CNTL_WAIT_DISASSOC:
-			CntlWaitDisassocProc(pAd, Elem);
-			break;
-		case CNTL_WAIT_JOIN:
-			CntlWaitJoinProc(pAd, Elem);
-			break;
-
-		// CNTL_WAIT_REASSOC is the only state in CNTL machine that does
-		// not triggered directly or indirectly by "RTMPSetInformation(OID_xxx)".
-		// Therefore not protected by NDIS's "only one outstanding OID request"
-		// rule. Which means NDIS may SET OID in the middle of ROAMing attempts.
-		// Current approach is to block new SET request at RTMPSetInformation()
-		// when CntlMachine.CurrState is not CNTL_IDLE
-		case CNTL_WAIT_REASSOC:
-			CntlWaitReassocProc(pAd, Elem);
-			break;
-
-		case CNTL_WAIT_START:
-			CntlWaitStartProc(pAd, Elem);
-			break;
-		case CNTL_WAIT_AUTH:
-			CntlWaitAuthProc(pAd, Elem);
-			break;
-		case CNTL_WAIT_AUTH2:
-			CntlWaitAuthProc2(pAd, Elem);
-			break;
-		case CNTL_WAIT_ASSOC:
-			CntlWaitAssocProc(pAd, Elem);
-			break;
-
-		case CNTL_WAIT_OID_LIST_SCAN:
-			if(Elem->MsgType == MT2_SCAN_CONF)
-			{
-				// Resume TxRing after SCANING complete. We hope the out-of-service time
-				// won't be too long to let upper layer time-out the waiting frames
-				RTMPResumeMsduTransmission(pAd);
-				if (pAd->StaCfg.CCXReqType != MSRN_TYPE_UNUSED)
-				{
-					// Cisco scan request is finished, prepare beacon report
-					MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_DONE, 0, NULL);
-				}
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-
-                //
-				// Set LED status to previous status.
-				//
-				if (pAd->bLedOnScanning)
-				{
-					pAd->bLedOnScanning = FALSE;
-					RTMPSetLED(pAd, pAd->LedStatus);
-				}
-#ifdef DOT11N_DRAFT3
-				// AP sent a 2040Coexistence mgmt frame, then station perform a scan, and then send back the respone.
-				if (pAd->CommonCfg.BSSCoexist2040.field.InfoReq == 1)
-				{
-					Update2040CoexistFrameAndNotify(pAd, BSSID_WCID, TRUE);
-				}
-#endif // DOT11N_DRAFT3 //
-			}
-			break;
-
-		case CNTL_WAIT_OID_DISASSOC:
-			if (Elem->MsgType == MT2_DISASSOC_CONF)
-			{
-				LinkDown(pAd, FALSE);
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-			}
-			break;
-#ifdef RT2870
-		//
-		// This state is for that we want to connect to an AP but
-		// it didn't find on BSS List table. So we need to scan the air first,
-		// after that we can try to connect to the desired AP if available.
-		//
-		case CNTL_WAIT_SCAN_FOR_CONNECT:
-			if(Elem->MsgType == MT2_SCAN_CONF)
-			{
-				// Resume TxRing after SCANING complete. We hope the out-of-service time
-				// won't be too long to let upper layer time-out the waiting frames
-				RTMPResumeMsduTransmission(pAd);
-#ifdef CCX_SUPPORT
-				if (pAd->StaCfg.CCXReqType != MSRN_TYPE_UNUSED)
-				{
-					// Cisco scan request is finished, prepare beacon report
-					MlmeEnqueue(pAd, AIRONET_STATE_MACHINE, MT2_AIRONET_SCAN_DONE, 0, NULL);
-				}
-#endif // CCX_SUPPORT //
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-
-				//
-				// Check if we can connect to.
-				//
-				BssTableSsidSort(pAd, &pAd->MlmeAux.SsidBssTab, pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen);
-				if (pAd->MlmeAux.SsidBssTab.BssNr > 0)
-				{
-					MlmeAutoReconnectLastSSID(pAd);
-				}
-			}
-			break;
-#endif // RT2870 //
-		default:
-			DBGPRINT_ERR(("!ERROR! CNTL - Illegal message type(=%ld)", Elem->MsgType));
-			break;
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlIdleProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	MLME_DISASSOC_REQ_STRUCT   DisassocReq;
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))
-		return;
-
-	switch(Elem->MsgType)
-	{
-		case OID_802_11_SSID:
-			CntlOidSsidProc(pAd, Elem);
-			break;
-
-		case OID_802_11_BSSID:
-			CntlOidRTBssidProc(pAd,Elem);
-			break;
-
-		case OID_802_11_BSSID_LIST_SCAN:
-			CntlOidScanProc(pAd,Elem);
-			break;
-
-		case OID_802_11_DISASSOCIATE:
-#ifdef RALINK_ATE
-			if(ATE_ON(pAd))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-			DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-			MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ, sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_DISASSOC;
-#ifdef WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_ENABLE_WITH_WEB_UI)
-#endif // WPA_SUPPLICANT_SUPPORT //
-            {
-    			// Set the AutoReconnectSsid to prevent it reconnect to old SSID
-    			// Since calling this indicate user don't want to connect to that SSID anymore.
-    			pAd->MlmeAux.AutoReconnectSsidLen= 32;
-    			NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.AutoReconnectSsidLen);
-            }
-			break;
-
-		case MT2_MLME_ROAMING_REQ:
-			CntlMlmeRoamingProc(pAd, Elem);
-			break;
-
-        case OID_802_11_MIC_FAILURE_REPORT_FRAME:
-            WpaMicFailureReportFrame(pAd, Elem);
-            break;
-
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_SET_DLS_PARAM:
-			CntlOidDLSSetupProc(pAd, Elem);
-			break;
-#endif // QOS_DLS_SUPPORT //
-
-		default:
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Illegal message in CntlIdleProc(MsgType=%ld)\n",Elem->MsgType));
-			break;
-	}
-}
-
-VOID CntlOidScanProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	MLME_SCAN_REQ_STRUCT       ScanReq;
-	ULONG                      BssIdx = BSS_NOT_FOUND;
-	BSS_ENTRY                  CurrBss;
-
-#ifdef RALINK_ATE
-/* Disable scanning when ATE is running. */
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-
-	// record current BSS if network is connected.
-	// 2003-2-13 do not include current IBSS if this is the only STA in this IBSS.
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-	{
-		BssIdx = BssSsidTableSearch(&pAd->ScanTab, pAd->CommonCfg.Bssid, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen, pAd->CommonCfg.Channel);
-		if (BssIdx != BSS_NOT_FOUND)
-		{
-			NdisMoveMemory(&CurrBss, &pAd->ScanTab.BssEntry[BssIdx], sizeof(BSS_ENTRY));
-		}
-	}
-
-	// clean up previous SCAN result, add current BSS back to table if any
-	BssTableInit(&pAd->ScanTab);
-	if (BssIdx != BSS_NOT_FOUND)
-	{
-		// DDK Note: If the NIC is associated with a particular BSSID and SSID
-		//    that are not contained in the list of BSSIDs generated by this scan, the
-		//    BSSID description of the currently associated BSSID and SSID should be
-		//    appended to the list of BSSIDs in the NIC's database.
-		// To ensure this, we append this BSS as the first entry in SCAN result
-		NdisMoveMemory(&pAd->ScanTab.BssEntry[0], &CurrBss, sizeof(BSS_ENTRY));
-		pAd->ScanTab.BssNr = 1;
-	}
-
-	ScanParmFill(pAd, &ScanReq, "", 0, BSS_ANY, SCAN_ACTIVE);
-	MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ,
-		sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-	pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-}
-
-/*
-	==========================================================================
-	Description:
-		Before calling this routine, user desired SSID should already been
-		recorded in CommonCfg.Ssid[]
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlOidSsidProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM * Elem)
-{
-	PNDIS_802_11_SSID          pOidSsid = (NDIS_802_11_SSID *)Elem->Msg;
-	MLME_DISASSOC_REQ_STRUCT   DisassocReq;
-	ULONG					   Now;
-
-	// Step 1. record the desired user settings to MlmeAux
-	NdisZeroMemory(pAd->MlmeAux.Ssid, MAX_LEN_OF_SSID);
-	NdisMoveMemory(pAd->MlmeAux.Ssid, pOidSsid->Ssid, pOidSsid->SsidLength);
-	pAd->MlmeAux.SsidLen = (UCHAR)pOidSsid->SsidLength;
-	NdisZeroMemory(pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
-	pAd->MlmeAux.BssType = pAd->StaCfg.BssType;
-
-
-	//
-	// Update Reconnect Ssid, that user desired to connect.
-	//
-	NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, MAX_LEN_OF_SSID);
-	NdisMoveMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-	pAd->MlmeAux.AutoReconnectSsidLen = pAd->MlmeAux.SsidLen;
-
-	// step 2. find all matching BSS in the lastest SCAN result (inBssTab)
-	//    & log them into MlmeAux.SsidBssTab for later-on iteration. Sort by RSSI order
-	BssTableSsidSort(pAd, &pAd->MlmeAux.SsidBssTab, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - %d BSS of %d BSS match the desire (%d)SSID - %s\n",
-			pAd->MlmeAux.SsidBssTab.BssNr, pAd->ScanTab.BssNr, pAd->MlmeAux.SsidLen, pAd->MlmeAux.Ssid));
-	NdisGetSystemUpTime(&Now);
-
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) &&
-		(pAd->CommonCfg.SsidLen == pAd->MlmeAux.SsidBssTab.BssEntry[0].SsidLen) &&
-		NdisEqualMemory(pAd->CommonCfg.Ssid, pAd->MlmeAux.SsidBssTab.BssEntry[0].Ssid, pAd->CommonCfg.SsidLen) &&
-		MAC_ADDR_EQUAL(pAd->CommonCfg.Bssid, pAd->MlmeAux.SsidBssTab.BssEntry[0].Bssid))
-	{
-		// Case 1. already connected with an AP who has the desired SSID
-		//         with highest RSSI
-
-		// Add checking Mode "LEAP" for CCX 1.0
-		if (((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-			 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-			 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
-			 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-#ifdef LEAP_SUPPORT
-			 || (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
-			 ) &&
-			(pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-		{
-			// case 1.1 For WPA, WPA-PSK, if the 1x port is not secured, we have to redo
-			//          connection process
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - disassociate with current AP...\n"));
-			DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-			MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
-						sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
-		}
-		else if (pAd->bConfigChanged == TRUE)
-		{
-			// case 1.2 Important Config has changed, we have to reconnect to the same AP
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - disassociate with current AP Because config changed...\n"));
-			DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-			MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
-						sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
-		}
-		else
-		{
-			// case 1.3. already connected to the SSID with highest RSSI.
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - already with this BSSID. ignore this SET_SSID request\n"));
-			//
-			// (HCT 12.1) 1c_wlan_mediaevents required
-			// media connect events are indicated when associating with the same AP
-			//
-			if (INFRA_ON(pAd))
-			{
-				//
-				// Since MediaState already is NdisMediaStateConnected
-				// We just indicate the connect event again to meet the WHQL required.
-				//
-				pAd->IndicateMediaState = NdisMediaStateConnected;
-				RTMP_IndicateMediaState(pAd);
-                pAd->ExtraInfo = GENERAL_LINK_UP;   // Update extra information to link is up
-			}
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-            {
-                union iwreq_data    wrqu;
-
-                memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                memcpy(wrqu.ap_addr.sa_data, pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
-                wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-		}
-	}
-	else if (INFRA_ON(pAd))
-	{
-		//
-		// For RT61
-		// [88888] OID_802_11_SSID should have returned NDTEST_WEP_AP2(Returned: )
-		// RT61 may lost SSID, and not connect to NDTEST_WEP_AP2 and will connect to NDTEST_WEP_AP2 by Autoreconnect
-		// But media status is connected, so the SSID not report correctly.
-		//
-		if (!SSID_EQUAL(pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen))
-		{
-			//
-			// Different SSID means not Roaming case, so we let LinkDown() to Indicate a disconnect event.
-			//
-			pAd->MlmeAux.CurrReqIsFromNdis = TRUE;
-		}
-		// case 2. active INFRA association existent
-		//    roaming is done within miniport driver, nothing to do with configuration
-		//    utility. so upon a new SET(OID_802_11_SSID) is received, we just
-		//    disassociate with the current associated AP,
-		//    then perform a new association with this new SSID, no matter the
-		//    new/old SSID are the same or not.
-		DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - disassociate with current AP...\n"));
-		DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-		MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
-					sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
-	}
-	else
-	{
-		if (ADHOC_ON(pAd))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - drop current ADHOC\n"));
-			LinkDown(pAd, FALSE);
-			OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-			pAd->IndicateMediaState = NdisMediaStateDisconnected;
-			RTMP_IndicateMediaState(pAd);
-            pAd->ExtraInfo = GENERAL_LINK_DOWN;
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():NDIS_STATUS_MEDIA_DISCONNECT Event C!\n"));
-		}
-
-		if ((pAd->MlmeAux.SsidBssTab.BssNr == 0) &&
-			(pAd->StaCfg.bAutoReconnect == TRUE) &&
-			(pAd->MlmeAux.BssType == BSS_INFRA) &&
-			(MlmeValidateSSID(pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen) == TRUE)
-			)
-		{
-			MLME_SCAN_REQ_STRUCT       ScanReq;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("CntlOidSsidProc():CNTL - No matching BSS, start a new scan\n"));
-			ScanParmFill(pAd, &ScanReq, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen, BSS_ANY, SCAN_ACTIVE);
-			MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN;
-			// Reset Missed scan number
-			pAd->StaCfg.LastScanTime = Now;
-		}
-		else
-		{
-			pAd->MlmeAux.BssIdx = 0;
-			IterateOnBssTab(pAd);
-		}
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlOidRTBssidProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM * Elem)
-{
-	ULONG       BssIdx;
-	PUCHAR      pOidBssid = (PUCHAR)Elem->Msg;
-	MLME_DISASSOC_REQ_STRUCT    DisassocReq;
-	MLME_JOIN_REQ_STRUCT        JoinReq;
-
-#ifdef RALINK_ATE
-/* No need to perform this routine when ATE is running. */
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-	// record user desired settings
-	COPY_MAC_ADDR(pAd->MlmeAux.Bssid, pOidBssid);
-	pAd->MlmeAux.BssType = pAd->StaCfg.BssType;
-
-	//
-	// Update Reconnect Ssid, that user desired to connect.
-	//
-	NdisZeroMemory(pAd->MlmeAux.AutoReconnectSsid, MAX_LEN_OF_SSID);
-	pAd->MlmeAux.AutoReconnectSsidLen = pAd->MlmeAux.SsidLen;
-	NdisMoveMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-
-	// find the desired BSS in the latest SCAN result table
-	BssIdx = BssTableSearch(&pAd->ScanTab, pOidBssid, pAd->MlmeAux.Channel);
-	if (BssIdx == BSS_NOT_FOUND)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - BSSID not found. reply NDIS_STATUS_NOT_ACCEPTED\n"));
-		pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-		return;
-	}
-
-	// copy the matched BSS entry from ScanTab to MlmeAux.SsidBssTab. Why?
-	// Because we need this entry to become the JOIN target in later on SYNC state machine
-	pAd->MlmeAux.BssIdx = 0;
-	pAd->MlmeAux.SsidBssTab.BssNr = 1;
-	NdisMoveMemory(&pAd->MlmeAux.SsidBssTab.BssEntry[0], &pAd->ScanTab.BssEntry[BssIdx], sizeof(BSS_ENTRY));
-
-	//pAd->MlmeAux.AutoReconnectSsidLen = pAd->ScanTab.BssEntry[BssIdx].SsidLen;
-	//NdisMoveMemory(pAd->MlmeAux.AutoReconnectSsid, pAd->ScanTab.BssEntry[BssIdx].Ssid, pAd->ScanTab.BssEntry[BssIdx].SsidLen);
-
-	// Add SSID into MlmeAux for site surey joining hidden SSID
-	//pAd->MlmeAux.SsidLen = pAd->ScanTab.BssEntry[BssIdx].SsidLen;
-	//NdisMoveMemory(pAd->MlmeAux.Ssid, pAd->ScanTab.BssEntry[BssIdx].Ssid, pAd->MlmeAux.SsidLen);
-
-	// 2002-11-26 skip the following checking. i.e. if user wants to re-connect to same AP
-	//   we just follow normal procedure. The reason of user doing this may because he/she changed
-	//   AP to another channel, but we still received BEACON from it thus don't claim Link Down.
-	//   Since user knows he's changed AP channel, he'll re-connect again. By skipping the following
-	//   checking, we'll disassociate then re-do normal association with this AP at the new channel.
-	// 2003-1-6 Re-enable this feature based on microsoft requirement which prefer not to re-do
-	//   connection when setting the same BSSID.
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) &&
-		MAC_ADDR_EQUAL(pAd->CommonCfg.Bssid, pOidBssid))
-	{
-		// already connected to the same BSSID, go back to idle state directly
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - already in this BSSID. ignore this SET_BSSID request\n"));
-		pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-            {
-                union iwreq_data    wrqu;
-
-                memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-                memcpy(wrqu.ap_addr.sa_data, pAd->MlmeAux.Bssid, MAC_ADDR_LEN);
-                wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-
-            }
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-	}
-	else
-	{
-		if (INFRA_ON(pAd))
-		{
-			// disassoc from current AP first
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - disassociate with current AP ...\n"));
-			DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_DISASSOC_STA_LEAVING);
-			MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ,
-						sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
-		}
-		else
-		{
-			if (ADHOC_ON(pAd))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - drop current ADHOC\n"));
-				LinkDown(pAd, FALSE);
-				OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-				pAd->IndicateMediaState = NdisMediaStateDisconnected;
-				RTMP_IndicateMediaState(pAd);
-                pAd->ExtraInfo = GENERAL_LINK_DOWN;
-				DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event C!\n"));
-			}
-
-			// Change the wepstatus to original wepstatus
-			pAd->StaCfg.WepStatus   = pAd->StaCfg.OrigWepStatus;
-			pAd->StaCfg.PairCipher  = pAd->StaCfg.OrigWepStatus;
-			pAd->StaCfg.GroupCipher = pAd->StaCfg.OrigWepStatus;
-
-			// Check cipher suite, AP must have more secured cipher than station setting
-			// Set the Pairwise and Group cipher to match the intended AP setting
-			// We can only connect to AP with less secured cipher setting
-			if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-			{
-				pAd->StaCfg.GroupCipher = pAd->ScanTab.BssEntry[BssIdx].WPA.GroupCipher;
-
-				if (pAd->StaCfg.WepStatus == pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipher)
-					pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipher;
-				else if (pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipherAux != Ndis802_11WEPDisabled)
-					pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA.PairCipherAux;
-				else	// There is no PairCipher Aux, downgrade our capability to TKIP
-					pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-			}
-			else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-			{
-				pAd->StaCfg.GroupCipher = pAd->ScanTab.BssEntry[BssIdx].WPA2.GroupCipher;
-
-				if (pAd->StaCfg.WepStatus == pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipher)
-					pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipher;
-				else if (pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipherAux != Ndis802_11WEPDisabled)
-					pAd->StaCfg.PairCipher = pAd->ScanTab.BssEntry[BssIdx].WPA2.PairCipherAux;
-				else	// There is no PairCipher Aux, downgrade our capability to TKIP
-					pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-
-				// RSN capability
-				pAd->StaCfg.RsnCapability = pAd->ScanTab.BssEntry[BssIdx].WPA2.RsnCapability;
-			}
-
-			// Set Mix cipher flag
-			pAd->StaCfg.bMixCipher = (pAd->StaCfg.PairCipher == pAd->StaCfg.GroupCipher) ? FALSE : TRUE;
-			if (pAd->StaCfg.bMixCipher == TRUE)
-			{
-				// If mix cipher, re-build RSNIE
-				RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, 0);
-			}
-			// No active association, join the BSS immediately
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - joining %02x:%02x:%02x:%02x:%02x:%02x ...\n",
-				pOidBssid[0],pOidBssid[1],pOidBssid[2],pOidBssid[3],pOidBssid[4],pOidBssid[5]));
-
-			JoinParmFill(pAd, &JoinReq, pAd->MlmeAux.BssIdx);
-			MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_JOIN_REQ, sizeof(MLME_JOIN_REQ_STRUCT), &JoinReq);
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_JOIN;
-		}
-	}
-}
-
-// Roaming is the only external request triggering CNTL state machine
-// despite of other "SET OID" operation. All "SET OID" related oerations
-// happen in sequence, because no other SET OID will be sent to this device
-// until the the previous SET operation is complete (successful o failed).
-// So, how do we quarantee this ROAMING request won't corrupt other "SET OID"?
-// or been corrupted by other "SET OID"?
-//
-// IRQL = DISPATCH_LEVEL
-VOID CntlMlmeRoamingProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	// TODO:
-	// AP in different channel may show lower RSSI than actual value??
-	// should we add a weighting factor to compensate it?
-	DBGPRINT(RT_DEBUG_TRACE,("CNTL - Roaming in MlmeAux.RoamTab...\n"));
-
-	NdisMoveMemory(&pAd->MlmeAux.SsidBssTab, &pAd->MlmeAux.RoamTab, sizeof(pAd->MlmeAux.RoamTab));
-	pAd->MlmeAux.SsidBssTab.BssNr = pAd->MlmeAux.RoamTab.BssNr;
-
-	BssTableSortByRssi(&pAd->MlmeAux.SsidBssTab);
-	pAd->MlmeAux.BssIdx = 0;
-	IterateOnBssTab(pAd);
-}
-
-#ifdef QOS_DLS_SUPPORT
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlOidDLSSetupProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PRT_802_11_DLS		pDLS = (PRT_802_11_DLS)Elem->Msg;
-	MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-	INT					i;
-	USHORT				reason = REASON_UNSPECIFY;
-
-	DBGPRINT(RT_DEBUG_TRACE,("CNTL - (OID set %02x:%02x:%02x:%02x:%02x:%02x with Valid=%d, Status=%d, TimeOut=%d, CountDownTimer=%d)\n",
-		pDLS->MacAddr[0], pDLS->MacAddr[1], pDLS->MacAddr[2], pDLS->MacAddr[3], pDLS->MacAddr[4], pDLS->MacAddr[5],
-		pDLS->Valid, pDLS->Status, pDLS->TimeOut, pDLS->CountDownTimer));
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return;
-
-	// DLS will not be supported when Adhoc mode
-	if (INFRA_ON(pAd))
-	{
-		for (i = 0; i < MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				(pDLS->TimeOut == pAd->StaCfg.DLSEntry[i].TimeOut) && MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 1. Same setting, just drop it
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - setting unchanged\n"));
-				break;
-			}
-			else if (!pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 2. Disable DLS link case, just tear down DLS link
-				reason = REASON_QOS_UNWANTED_MECHANISM;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - start tear down procedure\n"));
-				break;
-			}
-			else if ((i < MAX_NUM_OF_DLS_ENTRY) && pDLS->Valid && !pAd->StaCfg.DLSEntry[i].Valid)
-			{
-				// 3. Enable case, start DLS setup procedure
-				NdisMoveMemory(&pAd->StaCfg.DLSEntry[i], pDLS, sizeof(RT_802_11_DLS_UI));
-
-				//Update countdown timer
-				pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS setup case\n"));
-				break;
-			}
-			else if ((i < MAX_NUM_OF_DLS_ENTRY) && pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
-				(pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) && !MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 4. update mac case, tear down old DLS and setup new DLS
-				reason = REASON_QOS_UNWANTED_MECHANISM;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				NdisMoveMemory(&pAd->StaCfg.DLSEntry[i], pDLS, sizeof(RT_802_11_DLS_UI));
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS tear down and restart case\n"));
-				break;
-			}
-			else if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
-				MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr) && (pAd->StaCfg.DLSEntry[i].TimeOut != pDLS->TimeOut))
-			{
-				// 5. update timeout case, start DLS setup procedure (no tear down)
-				pAd->StaCfg.DLSEntry[i].TimeOut	= pDLS->TimeOut;
-				//Update countdown timer
-				pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS update timeout case\n"));
-				break;
-			}
-			else if (pDLS->Valid && pAd->StaCfg.DLSEntry[i].Valid &&
-				(pAd->StaCfg.DLSEntry[i].Status != DLS_FINISH) && MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				// 6. re-setup case, start DLS setup procedure (no tear down)
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_REQ, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				DBGPRINT(RT_DEBUG_TRACE,("CNTL - DLS retry setup procedure\n"));
-				break;
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN,("CNTL - DLS not changed in entry - %d - Valid=%d, Status=%d, TimeOut=%d\n",
-					i, pAd->StaCfg.DLSEntry[i].Valid, pAd->StaCfg.DLSEntry[i].Status, pAd->StaCfg.DLSEntry[i].TimeOut));
-			}
-		}
-	}
-}
-#endif // QOS_DLS_SUPPORT //
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitDisassocProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	MLME_START_REQ_STRUCT     StartReq;
-
-	if (Elem->MsgType == MT2_DISASSOC_CONF)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Dis-associate successful\n"));
-
-	    if (pAd->CommonCfg.bWirelessEvent)
-		{
-			RTMPSendWirelessEvent(pAd, IW_DISASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-		}
-
-		LinkDown(pAd, FALSE);
-
-		// case 1. no matching BSS, and user wants ADHOC, so we just start a new one
-		if ((pAd->MlmeAux.SsidBssTab.BssNr==0) && (pAd->StaCfg.BssType == BSS_ADHOC))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - No matching BSS, start a new ADHOC (Ssid=%s)...\n",pAd->MlmeAux.Ssid));
-			StartParmFill(pAd, &StartReq, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-			MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_START_REQ, sizeof(MLME_START_REQ_STRUCT), &StartReq);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_START;
-		}
-		// case 2. try each matched BSS
-		else
-		{
-			pAd->MlmeAux.BssIdx = 0;
-
-			IterateOnBssTab(pAd);
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitJoinProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT                      Reason;
-	MLME_AUTH_REQ_STRUCT        AuthReq;
-
-	if (Elem->MsgType == MT2_JOIN_CONF)
-	{
-		NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
-		if (Reason == MLME_SUCCESS)
-		{
-			// 1. joined an IBSS, we are pretty much done here
-			if (pAd->MlmeAux.BssType == BSS_ADHOC)
-			{
-			    //
-				// 5G bands rules of Japan:
-				// Ad hoc must be disabled in W53(ch52,56,60,64) channels.
-				//
-				if ( (pAd->CommonCfg.bIEEE80211H == 1) &&
-                      RadarChannelCheck(pAd, pAd->CommonCfg.Channel)
-				   )
-				{
-					pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-					DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Channel=%d, Join adhoc on W53(52,56,60,64) Channels are not accepted\n", pAd->CommonCfg.Channel));
-					return;
-				}
-
-				LinkUp(pAd, BSS_ADHOC);
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - join the IBSS = %02x:%02x:%02x:%02x:%02x:%02x ...\n",
-				pAd->CommonCfg.Bssid[0],pAd->CommonCfg.Bssid[1],pAd->CommonCfg.Bssid[2],
-				pAd->CommonCfg.Bssid[3],pAd->CommonCfg.Bssid[4],pAd->CommonCfg.Bssid[5]));
-
-                pAd->IndicateMediaState = NdisMediaStateConnected;
-                pAd->ExtraInfo = GENERAL_LINK_UP;
-			}
-			// 2. joined a new INFRA network, start from authentication
-			else
-			{
-#ifdef LEAP_SUPPORT
-				// Add AuthMode "LEAP" for CCX 1.X
-				if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-				{
-					AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, CISCO_AuthModeLEAP);
-				}
-				else
-#endif // LEAP_SUPPORT //
-				{
-					// either Ndis802_11AuthModeShared or Ndis802_11AuthModeAutoSwitch, try shared key first
-					if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeShared) ||
-						(pAd->StaCfg.AuthMode == Ndis802_11AuthModeAutoSwitch))
-					{
-						AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeShared);
-					}
-					else
-					{
-						AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeOpen);
-					}
-				}
-				MlmeEnqueue(pAd, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
-							sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
-
-				pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH;
-			}
-		}
-		else
-		{
-			// 3. failed, try next BSS
-			pAd->MlmeAux.BssIdx++;
-			IterateOnBssTab(pAd);
-		}
-	}
-}
-
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitStartProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT      Result;
-
-	if (Elem->MsgType == MT2_START_CONF)
-	{
-		NdisMoveMemory(&Result, Elem->Msg, sizeof(USHORT));
-		if (Result == MLME_SUCCESS)
-		{
-		    //
-			// 5G bands rules of Japan:
-			// Ad hoc must be disabled in W53(ch52,56,60,64) channels.
-			//
-			if ( (pAd->CommonCfg.bIEEE80211H == 1) &&
-                  RadarChannelCheck(pAd, pAd->CommonCfg.Channel)
-			   )
-			{
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Channel=%d, Start adhoc on W53(52,56,60,64) Channels are not accepted\n", pAd->CommonCfg.Channel));
-				return;
-			}
-#ifdef DOT11_N_SUPPORT
-			if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-			{
-				N_ChannelCheck(pAd);
-				SetCommonHT(pAd);
-				NdisMoveMemory(&pAd->MlmeAux.AddHtInfo, &pAd->CommonCfg.AddHTInfo, sizeof(ADD_HT_INFO_IE));
-				RTMPCheckHt(pAd, BSSID_WCID, &pAd->CommonCfg.HtCapability, &pAd->CommonCfg.AddHTInfo);
-				pAd->StaActive.SupportedPhyInfo.bHtEnable = TRUE;
-				NdisZeroMemory(&pAd->StaActive.SupportedPhyInfo.MCSSet[0], 16);
-				NdisMoveMemory(&pAd->StaActive.SupportedPhyInfo.MCSSet[0], &pAd->CommonCfg.HtCapability.MCSSet[0], 16);
-				COPY_HTSETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(pAd);
-
-				if ((pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth  == BW_40) &&
-					(pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_ABOVE))
-				{
-					pAd->MlmeAux.CentralChannel = pAd->CommonCfg.Channel + 2;
-				}
-				else if ((pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth  == BW_40) &&
-						 (pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_BELOW))
-				{
-					pAd->MlmeAux.CentralChannel = pAd->CommonCfg.Channel - 2;
-				}
-			}
-			else
-#endif // DOT11_N_SUPPORT //
-			{
-				pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
-			}
-			LinkUp(pAd, BSS_ADHOC);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-			// Before send beacon, driver need do radar detection
-			if ((pAd->CommonCfg.Channel > 14 )
-				&& (pAd->CommonCfg.bIEEE80211H == 1)
-				&& RadarChannelCheck(pAd, pAd->CommonCfg.Channel))
-			{
-				pAd->CommonCfg.RadarDetect.RDMode = RD_SILENCE_MODE;
-				pAd->CommonCfg.RadarDetect.RDCount = 0;
-#ifdef DFS_SUPPORT
-				BbpRadarDetectionStart(pAd);
-#endif // DFS_SUPPORT //
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - start a new IBSS = %02x:%02x:%02x:%02x:%02x:%02x ...\n",
-				pAd->CommonCfg.Bssid[0],pAd->CommonCfg.Bssid[1],pAd->CommonCfg.Bssid[2],
-				pAd->CommonCfg.Bssid[3],pAd->CommonCfg.Bssid[4],pAd->CommonCfg.Bssid[5]));
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Start IBSS fail. BUG!!!!!\n"));
-			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitAuthProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT                       Reason;
-	MLME_ASSOC_REQ_STRUCT        AssocReq;
-	MLME_AUTH_REQ_STRUCT         AuthReq;
-
-	if (Elem->MsgType == MT2_AUTH_CONF)
-	{
-		NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
-		if (Reason == MLME_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH OK\n"));
-			AssocParmFill(pAd, &AssocReq, pAd->MlmeAux.Bssid, pAd->MlmeAux.CapabilityInfo,
-						  ASSOC_TIMEOUT, pAd->StaCfg.DefaultListenCount);
-
-#ifdef LEAP_SUPPORT
-			//
-			// Cisco Leap CCKM supported Re-association.
-			//
-			if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-			{
-				//if CCKM is turn on , that's mean Fast Reauthentication
-				//Use CCKM Reassociation instead of normal association for Fast Roaming.
-				MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_REASSOC_REQ,
-							sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
-
-				pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_REASSOC;
-			}
-			else
-#endif // LEAP_SUPPORT //
-			{
-				MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_ASSOC_REQ,
-							sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
-
-				pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_ASSOC;
-			}
-		}
-		else
-		{
-			// This fail may because of the AP already keep us in its MAC table without
-			// ageing-out. The previous authentication attempt must have let it remove us.
-			// so try Authentication again may help. For D-Link DWL-900AP+ compatibility.
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH FAIL, try again...\n"));
-#ifdef LEAP_SUPPORT
-			//Add AuthMode "LEAP" for CCX 1.X
-			if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-			{
-				AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, CISCO_AuthModeLEAP);
-			}
-			else
-#endif // LEAP_SUPPORT //
-			{
-				if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeShared) ||
-					(pAd->StaCfg.AuthMode == Ndis802_11AuthModeAutoSwitch))
-				{
-					// either Ndis802_11AuthModeShared or Ndis802_11AuthModeAutoSwitch, try shared key first
-					AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeShared);
-				}
-				else
-				{
-					AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeOpen);
-				}
-			}
-			MlmeEnqueue(pAd, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
-						sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH2;
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitAuthProc2(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT                       Reason;
-	MLME_ASSOC_REQ_STRUCT        AssocReq;
-	MLME_AUTH_REQ_STRUCT         AuthReq;
-
-	if (Elem->MsgType == MT2_AUTH_CONF)
-	{
-		NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
-		if (Reason == MLME_SUCCESS)
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH OK\n"));
-			AssocParmFill(pAd, &AssocReq, pAd->MlmeAux.Bssid, pAd->MlmeAux.CapabilityInfo,
-						  ASSOC_TIMEOUT, pAd->StaCfg.DefaultListenCount);
-			MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_ASSOC_REQ,
-						sizeof(MLME_ASSOC_REQ_STRUCT), &AssocReq);
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_ASSOC;
-		}
-		else
-		{
-#ifdef LEAP_SUPPORT
-			// Process LEAP first, since it use different control variable
-			// We don't want to affect other poven operation
-			if (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-			{
-				// LEAP Auth not success, try next BSS
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - *LEAP* AUTH FAIL, give up; try next BSS\n"));
-				DBGPRINT(RT_DEBUG_TRACE, ("Total match BSSID [=%d]\n", pAd->MlmeAux.SsidBssTab.BssNr));
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-				pAd->MlmeAux.BssIdx++;
-				IterateOnBssTab(pAd);
-			}
-			else
-#endif // LEAP_SUPPORT //
-			if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeAutoSwitch) &&
-				 (pAd->MlmeAux.Alg == Ndis802_11AuthModeShared))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH FAIL, try OPEN system...\n"));
-				AuthParmFill(pAd, &AuthReq, pAd->MlmeAux.Bssid, Ndis802_11AuthModeOpen);
-				MlmeEnqueue(pAd, AUTH_STATE_MACHINE, MT2_MLME_AUTH_REQ,
-							sizeof(MLME_AUTH_REQ_STRUCT), &AuthReq);
-
-				pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_AUTH2;
-			}
-			else
-			{
-				// not success, try next BSS
-				DBGPRINT(RT_DEBUG_TRACE, ("CNTL - AUTH FAIL, give up; try next BSS\n"));
-				pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE; //???????
-				pAd->MlmeAux.BssIdx++;
-				IterateOnBssTab(pAd);
-			}
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitAssocProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT      Reason;
-
-	if (Elem->MsgType == MT2_ASSOC_CONF)
-	{
-		NdisMoveMemory(&Reason, Elem->Msg, sizeof(USHORT));
-		if (Reason == MLME_SUCCESS)
-		{
-			LinkUp(pAd, BSS_INFRA);
-			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Association successful on BSS #%ld\n",pAd->MlmeAux.BssIdx));
-
-			if (pAd->CommonCfg.bWirelessEvent)
-			{
-				RTMPSendWirelessEvent(pAd, IW_ASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-			}
-		}
-		else
-		{
-			// not success, try next BSS
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Association fails on BSS #%ld\n",pAd->MlmeAux.BssIdx));
-			pAd->MlmeAux.BssIdx++;
-			IterateOnBssTab(pAd);
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID CntlWaitReassocProc(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT      Result;
-
-	if (Elem->MsgType == MT2_REASSOC_CONF)
-	{
-		NdisMoveMemory(&Result, Elem->Msg, sizeof(USHORT));
-		if (Result == MLME_SUCCESS)
-		{
-			//
-			// NDIS requires a new Link UP indication but no Link Down for RE-ASSOC
-			//
-			LinkUp(pAd, BSS_INFRA);
-
-			// send wireless event - for association
-			if (pAd->CommonCfg.bWirelessEvent)
-				RTMPSendWirelessEvent(pAd, IW_ASSOC_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-
-
-#ifdef LEAP_SUPPORT
-			if (LEAP_CCKM_ON(pAd))
-			{
-				STA_PORT_SECURED(pAd);
-				pAd->StaCfg.WpaState = SS_FINISH;
-			}
-#endif // LEAP_SUPPORT //
-			pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Re-assocition successful on BSS #%ld\n", pAd->MlmeAux.RoamIdx));
-		}
-		else
-		{
-			// reassoc failed, try to pick next BSS in the BSS Table
-			DBGPRINT(RT_DEBUG_TRACE, ("CNTL - Re-assocition fails on BSS #%ld\n", pAd->MlmeAux.RoamIdx));
-			pAd->MlmeAux.RoamIdx++;
-			IterateOnBssTab2(pAd);
-		}
-	}
-}
-
-
-VOID	AdhocTurnOnQos(
-	IN  PRTMP_ADAPTER pAd)
-{
-#define AC0_DEF_TXOP		0
-#define AC1_DEF_TXOP		0
-#define AC2_DEF_TXOP		94
-#define AC3_DEF_TXOP		47
-
-	// Turn on QOs if use HT rate.
-	if (pAd->CommonCfg.APEdcaParm.bValid == FALSE)
-	{
-		pAd->CommonCfg.APEdcaParm.bValid = TRUE;
-		pAd->CommonCfg.APEdcaParm.Aifsn[0] = 3;
-		pAd->CommonCfg.APEdcaParm.Aifsn[1] = 7;
-		pAd->CommonCfg.APEdcaParm.Aifsn[2] = 1;
-		pAd->CommonCfg.APEdcaParm.Aifsn[3] = 1;
-
-		pAd->CommonCfg.APEdcaParm.Cwmin[0] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmin[1] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmin[2] = 3;
-		pAd->CommonCfg.APEdcaParm.Cwmin[3] = 2;
-
-		pAd->CommonCfg.APEdcaParm.Cwmax[0] = 10;
-		pAd->CommonCfg.APEdcaParm.Cwmax[1] = 6;
-		pAd->CommonCfg.APEdcaParm.Cwmax[2] = 4;
-		pAd->CommonCfg.APEdcaParm.Cwmax[3] = 3;
-
-		pAd->CommonCfg.APEdcaParm.Txop[0]  = 0;
-		pAd->CommonCfg.APEdcaParm.Txop[1]  = 0;
-		pAd->CommonCfg.APEdcaParm.Txop[2]  = AC2_DEF_TXOP;
-		pAd->CommonCfg.APEdcaParm.Txop[3]  = AC3_DEF_TXOP;
-	}
-	AsicSetEdcaParm(pAd, &pAd->CommonCfg.APEdcaParm);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID LinkUp(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR BssType)
-{
-	ULONG	Now;
-	UINT32	Data;
-	BOOLEAN	Cancelled;
-	UCHAR	Value = 0, idx;
-	MAC_TABLE_ENTRY *pEntry = NULL, *pCurrEntry;
-
-	pEntry = &pAd->MacTab.Content[BSSID_WCID];
-
-	//
-	// ASSOC - DisassocTimeoutAction
-	// CNTL - Dis-associate successful
-	// !!! LINK DOWN !!!
-	// [88888] OID_802_11_SSID should have returned NDTEST_WEP_AP2(Returned: )
-	//
-	// To prevent DisassocTimeoutAction to call Link down after we link up,
-	// cancel the DisassocTimer no matter what it start or not.
-	//
-	RTMPCancelTimer(&pAd->MlmeAux.DisassocTimer,  &Cancelled);
-
-	COPY_SETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(pAd);
-
-#ifdef DOT11_N_SUPPORT
-	COPY_HTSETTINGS_FROM_MLME_AUX_TO_ACTIVE_CFG(pAd);
-#endif // DOT11_N_SUPPORT //
-	// It's quite difficult to tell if a newly added KEY is WEP or CKIP until a new BSS
-	// is formed (either ASSOC/RE-ASSOC done or IBSS started. LinkUP should be a safe place
-	// to examine if cipher algorithm switching is required.
-	//rt2860b. Don't know why need this
-	SwitchBetweenWepAndCkip(pAd);
-
-
-	if (BssType == BSS_ADHOC)
-	{
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_ADHOC_ON);
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_INFRA_ON);
-
-#ifdef DOT11_N_SUPPORT
-		if ((pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth  == BW_40) &&
-			(pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_ABOVE))
-		{
-			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel + 2;
-		}
-		else if ((pAd->CommonCfg.Channel > 2) &&
-				 (pAd->CommonCfg.HtCapability.HtCapInfo.ChannelWidth  == BW_40) &&
-				 (pAd->CommonCfg.AddHTInfo.AddHtInfo.ExtChanOffset == EXTCHA_BELOW))
-		{
-			pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel - 2;
-		}
-#endif // DOT11_N_SUPPORT //
-
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-		// No carrier detection when adhoc
-		// CarrierDetectionStop(pAd);
-		pAd->CommonCfg.CarrierDetect.CD_State = CD_NORMAL;
-#endif // CARRIER_DETECTION_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-		if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-			AdhocTurnOnQos(pAd);
-#endif // DOT11_N_SUPPORT //
-
-		DBGPRINT(RT_DEBUG_TRACE, ("!!!Adhoc LINK UP !!! \n" ));
-	}
-	else
-	{
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_INFRA_ON);
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_ADHOC_ON);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("!!!Infra LINK UP !!! \n" ));
-	}
-
-	// 3*3
-	// reset Tx beamforming bit
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
-	Value &= (~0x01);
-	Value |= pAd->CommonCfg.RegTransmitSetting.field.TxBF;
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
-
-#ifdef DOT11_N_SUPPORT
-	// Change to AP channel
-    if ((pAd->CommonCfg.CentralChannel > pAd->CommonCfg.Channel) && (pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth == BW_40))
-	{
-		// Must using 40MHz.
-		pAd->CommonCfg.BBPCurrentBW = BW_40;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
-		Value &= (~0x18);
-		Value |= 0x10;
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
-
-		//  RX : control channel at lower
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
-		Value &= (~0x20);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
-
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Data);
-		Data &= 0xfffffffe;
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Data);
-
-		if (pAd->MACVersion == 0x28600100)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x1A);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0A);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x16);
-            DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("!!!40MHz Lower LINK UP !!! Control Channel at Below. Central = %d \n", pAd->CommonCfg.CentralChannel ));
-	}
-	else if ((pAd->CommonCfg.CentralChannel < pAd->CommonCfg.Channel) && (pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth == BW_40))
-    {
-	    // Must using 40MHz.
-		pAd->CommonCfg.BBPCurrentBW = BW_40;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-	    AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
-		Value &= (~0x18);
-		Value |= 0x10;
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
-
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Data);
-		Data |= 0x1;
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Data);
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
-	    Value |= (0x20);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
-
-		if (pAd->MACVersion == 0x28600100)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x1A);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x0A);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x16);
-			    DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
-		}
-
-	    DBGPRINT(RT_DEBUG_TRACE, ("!!! 40MHz Upper LINK UP !!! Control Channel at UpperCentral = %d \n", pAd->CommonCfg.CentralChannel ));
-    }
-    else
-#endif // DOT11_N_SUPPORT //
-    {
-	    pAd->CommonCfg.BBPCurrentBW = BW_20;
-		pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &Value);
-		Value &= (~0x18);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, Value);
-
-		RTMP_IO_READ32(pAd, TX_BAND_CFG, &Data);
-		Data &= 0xfffffffe;
-		RTMP_IO_WRITE32(pAd, TX_BAND_CFG, Data);
-
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &Value);
-		Value &= (~0x20);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, Value);
-
-		if (pAd->MACVersion == 0x28600100)
-		{
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R69, 0x16);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R70, 0x08);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R73, 0x11);
-            DBGPRINT(RT_DEBUG_TRACE, ("!!!rt2860C !!! \n" ));
-		}
-
-	    DBGPRINT(RT_DEBUG_TRACE, ("!!! 20MHz LINK UP !!! \n" ));
-    }
-
-	RTMPSetAGCInitValue(pAd, pAd->CommonCfg.BBPCurrentBW);
-	//
-	// Save BBP_R66 value, it will be used in RTUSBResumeMsduTransmission
-	//
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R66, &pAd->BbpTuning.R66CurrentValue);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !!! (BssType=%d, AID=%d, ssid=%s, Channel=%d, CentralChannel = %d)\n",
-		BssType, pAd->StaActive.Aid, pAd->CommonCfg.Ssid, pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel));
-
-#ifdef DOT11_N_SUPPORT
-	DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !!! (Density =%d, )\n", pAd->MacTab.Content[BSSID_WCID].MpduDensity));
-#endif // DOT11_N_SUPPORT //
-
-		AsicSetBssid(pAd, pAd->CommonCfg.Bssid);
-
-	AsicSetSlotTime(pAd, TRUE);
-	AsicSetEdcaParm(pAd, &pAd->CommonCfg.APEdcaParm);
-
-	// Call this for RTS protectionfor legacy rate, we will always enable RTS threshold, but normally it will not hit
-	AsicUpdateProtect(pAd, 0, (OFDMSETPROTECT | CCKSETPROTECT), TRUE, FALSE);
-
-#ifdef DOT11_N_SUPPORT
-	if ((pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE))
-	{
-		// Update HT protectionfor based on AP's operating mode.
-    	if (pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1)
-    	{
-    		AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode,  ALLN_SETPROTECT, FALSE, TRUE);
-    	}
-    	else
-   			AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode,  ALLN_SETPROTECT, FALSE, FALSE);
-	}
-#endif // DOT11_N_SUPPORT //
-
-	NdisZeroMemory(&pAd->DrsCounters, sizeof(COUNTER_DRS));
-
-	NdisGetSystemUpTime(&Now);
-	pAd->StaCfg.LastBeaconRxTime = Now;   // last RX timestamp
-
-	if ((pAd->CommonCfg.TxPreamble != Rt802_11PreambleLong) &&
-		CAP_IS_SHORT_PREAMBLE_ON(pAd->StaActive.CapabilityInfo))
-	{
-		MlmeSetTxPreamble(pAd, Rt802_11PreambleShort);
-	}
-
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
-
-	if (pAd->CommonCfg.RadarDetect.RDMode == RD_SILENCE_MODE)
-	{
-#ifdef DFS_SUPPORT
-		RadarDetectionStop(pAd);
-#endif // DFS_SUPPORT //
-	}
-	pAd->CommonCfg.RadarDetect.RDMode = RD_NORMAL_MODE;
-
-	if (BssType == BSS_ADHOC)
-	{
-		MakeIbssBeacon(pAd);
-		if ((pAd->CommonCfg.Channel > 14)
-			&& (pAd->CommonCfg.bIEEE80211H == 1)
-			&& RadarChannelCheck(pAd, pAd->CommonCfg.Channel))
-		{
-			; //Do nothing
-		}
-		else
-		{
-			AsicEnableIbssSync(pAd);
-		}
-
-		// In ad hoc mode, use MAC table from index 1.
-		// p.s ASIC use all 0xff as termination of WCID table search.To prevent it's 0xff-ff-ff-ff-ff-ff, Write 0 here.
-		RTMP_IO_WRITE32(pAd, MAC_WCID_BASE, 0x00);
-		RTMP_IO_WRITE32(pAd, 0x1808, 0x00);
-
-		// If WEP is enabled, add key material and cipherAlg into Asic
-		// Fill in Shared Key Table(offset: 0x6c00) and Shared Key Mode(offset: 0x7000)
-
-		if (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)
-		{
-			PUCHAR	Key;
-			UCHAR 	CipherAlg;
-
-			for (idx=0; idx < SHARE_KEY_NUM; idx++)
-        	{
-				CipherAlg = pAd->SharedKey[BSS0][idx].CipherAlg;
-    			Key = pAd->SharedKey[BSS0][idx].Key;
-
-				if (pAd->SharedKey[BSS0][idx].KeyLen > 0)
-				{
-					// Set key material and cipherAlg to Asic
-    				AsicAddSharedKeyEntry(pAd, BSS0, idx, CipherAlg, Key, NULL, NULL);
-
-                    if (idx == pAd->StaCfg.DefaultKeyId)
-					{
-						// Update WCID attribute table and IVEIV table for this group key table
-						RTMPAddWcidAttributeEntry(pAd, BSS0, idx, CipherAlg, NULL);
-					}
-				}
-
-
-			}
-		}
-		// If WPANone is enabled, add key material and cipherAlg into Asic
-		// Fill in Shared Key Table(offset: 0x6c00) and Shared Key Mode(offset: 0x7000)
-		else if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-		{
-			pAd->StaCfg.DefaultKeyId = 0;	// always be zero
-
-            NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-							pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-			NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, pAd->StaCfg.PMK, LEN_TKIP_EK);
-
-            if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-            {
-    			NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, &pAd->StaCfg.PMK[16], LEN_TKIP_RXMICK);
-    			NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, &pAd->StaCfg.PMK[16], LEN_TKIP_TXMICK);
-            }
-
-			// Decide its ChiperAlg
-			if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-				pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-			else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-				pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-			else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Unknow Cipher (=%d), set Cipher to AES\n", pAd->StaCfg.PairCipher));
-				pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-            }
-
-			// Set key material and cipherAlg to Asic
-			AsicAddSharedKeyEntry(pAd,
-								  BSS0,
-								  0,
-								  pAd->SharedKey[BSS0][0].CipherAlg,
-								  pAd->SharedKey[BSS0][0].Key,
-								  pAd->SharedKey[BSS0][0].TxMic,
-								  pAd->SharedKey[BSS0][0].RxMic);
-
-            // Update WCID attribute table and IVEIV table for this group key table
-			RTMPAddWcidAttributeEntry(pAd, BSS0, 0, pAd->SharedKey[BSS0][0].CipherAlg, NULL);
-
-		}
-
-	}
-	else // BSS_INFRA
-	{
-		// Check the new SSID with last SSID
-		while (Cancelled == TRUE)
-		{
-			if (pAd->CommonCfg.LastSsidLen == pAd->CommonCfg.SsidLen)
-			{
-				if (RTMPCompareMemory(pAd->CommonCfg.LastSsid, pAd->CommonCfg.Ssid, pAd->CommonCfg.LastSsidLen) == 0)
-				{
-					// Link to the old one no linkdown is required.
-					break;
-				}
-			}
-			// Send link down event before set to link up
-			pAd->IndicateMediaState = NdisMediaStateDisconnected;
-			RTMP_IndicateMediaState(pAd);
-            pAd->ExtraInfo = GENERAL_LINK_DOWN;
-			DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event AA!\n"));
-			break;
-		}
-
-		//
-		// On WPA mode, Remove All Keys if not connect to the last BSSID
-		// Key will be set after 4-way handshake.
-		//
-		if ((pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA))
-		{
-			ULONG 		IV;
-
-			// Remove all WPA keys
-			RTMPWPARemoveAllKeys(pAd);
-			pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilter8021xWEP;
-
-			// Fixed connection failed with Range Maximizer - 515 AP (Marvell Chip) when security is WPAPSK/TKIP
-			// If IV related values are too large in GroupMsg2, AP would ignore this message.
-			IV = 0;
-			IV |= (pAd->StaCfg.DefaultKeyId << 30);
-			AsicUpdateWCIDIVEIV(pAd, BSSID_WCID, IV, 0);
-		}
-		// NOTE:
-		// the decision of using "short slot time" or not may change dynamically due to
-		// new STA association to the AP. so we have to decide that upon parsing BEACON, not here
-
-		// NOTE:
-		// the decision to use "RTC/CTS" or "CTS-to-self" protection or not may change dynamically
-		// due to new STA association to the AP. so we have to decide that upon parsing BEACON, not here
-
-		ComposePsPoll(pAd);
-		ComposeNullFrame(pAd);
-
-			AsicEnableBssSync(pAd);
-
-		// Add BSSID to WCID search table
-		AsicUpdateRxWCIDTable(pAd, BSSID_WCID, pAd->CommonCfg.Bssid);
-
-		NdisAcquireSpinLock(&pAd->MacTabLock);
-		// add this BSSID entry into HASH table
-		{
-			UCHAR HashIdx;
-
-			//pEntry = &pAd->MacTab.Content[BSSID_WCID];
-			HashIdx = MAC_ADDR_HASH_INDEX(pAd->CommonCfg.Bssid);
-			if (pAd->MacTab.Hash[HashIdx] == NULL)
-			{
-				pAd->MacTab.Hash[HashIdx] = pEntry;
-			}
-			else
-			{
-				pCurrEntry = pAd->MacTab.Hash[HashIdx];
-				while (pCurrEntry->pNext != NULL)
-					pCurrEntry = pCurrEntry->pNext;
-				pCurrEntry->pNext = pEntry;
-			}
-		}
-		NdisReleaseSpinLock(&pAd->MacTabLock);
-
-
-		// If WEP is enabled, add paiewise and shared key
-#ifdef WPA_SUPPLICANT_SUPPORT
-        if (((pAd->StaCfg.WpaSupplicantUP)&&
-             (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)&&
-             (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED)) ||
-            ((pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_DISABLE)&&
-              (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)))
-#else
-		if (pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled)
-#endif // WPA_SUPPLICANT_SUPPORT //
-		{
-			PUCHAR	Key;
-			UCHAR 	CipherAlg;
-
-			for (idx=0; idx < SHARE_KEY_NUM; idx++)
-        	{
-				CipherAlg = pAd->SharedKey[BSS0][idx].CipherAlg;
-    			Key = pAd->SharedKey[BSS0][idx].Key;
-
-				if (pAd->SharedKey[BSS0][idx].KeyLen > 0)
-				{
-					// Set key material and cipherAlg to Asic
-    				AsicAddSharedKeyEntry(pAd, BSS0, idx, CipherAlg, Key, NULL, NULL);
-
-					if (idx == pAd->StaCfg.DefaultKeyId)
-					{
-						// Assign group key info
-						RTMPAddWcidAttributeEntry(pAd, BSS0, idx, CipherAlg, NULL);
-
-						// Assign pairwise key info
-						RTMPAddWcidAttributeEntry(pAd, BSS0, idx, CipherAlg, pEntry);
-					}
-				}
-			}
-		}
-
-		// only INFRASTRUCTURE mode need to indicate connectivity immediately; ADHOC mode
-		// should wait until at least 2 active nodes in this BSSID.
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-
-        // For GUI ++
-		if (pAd->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-		{
-			pAd->IndicateMediaState = NdisMediaStateConnected;
-			pAd->ExtraInfo = GENERAL_LINK_UP;
-			RTMP_IndicateMediaState(pAd);
-		}
-        // --
-
-		// Add BSSID in my MAC Table.
-        NdisAcquireSpinLock(&pAd->MacTabLock);
-		RTMPMoveMemory(pAd->MacTab.Content[BSSID_WCID].Addr, pAd->CommonCfg.Bssid, MAC_ADDR_LEN);
-		pAd->MacTab.Content[BSSID_WCID].Aid = BSSID_WCID;
-		pAd->MacTab.Content[BSSID_WCID].pAd = pAd;
-		pAd->MacTab.Content[BSSID_WCID].ValidAsCLI = TRUE;	//Although this is bssid..still set ValidAsCl
-		pAd->MacTab.Size = 1;	// infra mode always set MACtab size =1.
-		pAd->MacTab.Content[BSSID_WCID].Sst = SST_ASSOC;
-		pAd->MacTab.Content[BSSID_WCID].AuthState = SST_ASSOC;
-		pAd->MacTab.Content[BSSID_WCID].AuthMode = pAd->StaCfg.AuthMode;
-		pAd->MacTab.Content[BSSID_WCID].WepStatus = pAd->StaCfg.WepStatus;
-        NdisReleaseSpinLock(&pAd->MacTabLock);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !!!  ClientStatusFlags=%lx)\n",
-			pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
-
-		MlmeUpdateTxRates(pAd, TRUE, BSS0);
-#ifdef DOT11_N_SUPPORT
-		MlmeUpdateHtTxRates(pAd, BSS0);
-		DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK UP !! (StaActive.bHtEnable =%d, )\n", pAd->StaActive.SupportedPhyInfo.bHtEnable));
-#endif // DOT11_N_SUPPORT //
-
-		//
-		// Report Adjacent AP report.
-		//
-#ifdef LEAP_SUPPORT
-		CCXAdjacentAPReport(pAd);
-#endif // LEAP_SUPPORT //
-
-		if (pAd->CommonCfg.bAggregationCapable)
-		{
-			if ((pAd->CommonCfg.bPiggyBackCapable) && (pAd->MlmeAux.APRalinkIe & 0x00000003) == 3)
-			{
-
-				OPSTATUS_SET_FLAG(pAd, fOP_STATUS_PIGGYBACK_INUSED);
-				OPSTATUS_SET_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
-                RTMPSetPiggyBack(pAd, TRUE);
-				DBGPRINT(RT_DEBUG_TRACE, ("Turn on Piggy-Back\n"));
-			}
-			else if (pAd->MlmeAux.APRalinkIe & 0x00000001)
-			{
-				OPSTATUS_SET_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
-			}
-		}
-
-		if (pAd->MlmeAux.APRalinkIe != 0x0)
-		{
-#ifdef DOT11_N_SUPPORT
-			if (CLIENT_STATUS_TEST_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_RDG_CAPABLE))
-			{
-				AsicEnableRDG(pAd);
-			}
-#endif // DOT11_N_SUPPORT //
-			OPSTATUS_SET_FLAG(pAd, fCLIENT_STATUS_RALINK_CHIPSET);
-			CLIENT_STATUS_SET_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_RALINK_CHIPSET);
-		}
-		else
-		{
-			OPSTATUS_CLEAR_FLAG(pAd, fCLIENT_STATUS_RALINK_CHIPSET);
-			CLIENT_STATUS_CLEAR_FLAG(&pAd->MacTab.Content[BSSID_WCID], fCLIENT_STATUS_RALINK_CHIPSET);
-		}
-	}
-
-#ifdef DOT11_N_SUPPORT
-	DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_CONNECT Event B!.BACapability = %x. ClientStatusFlags = %lx\n", pAd->CommonCfg.BACapability.word, pAd->MacTab.Content[BSSID_WCID].ClientStatusFlags));
-#endif // DOT11_N_SUPPORT //
-
-	// Set LED
-	RTMPSetLED(pAd, LED_LINK_UP);
-
-	pAd->Mlme.PeriodicRound = 0;
-	pAd->Mlme.OneSecPeriodicRound = 0;
-	pAd->bConfigChanged = FALSE;        // Reset config flag
-	pAd->ExtraInfo = GENERAL_LINK_UP;   // Update extra information to link is up
-
-	// Set asic auto fall back
-	{
-		PUCHAR					pTable;
-		UCHAR					TableSize = 0;
-
-		MlmeSelectTxRateTable(pAd, &pAd->MacTab.Content[BSSID_WCID], &pTable, &TableSize, &pAd->CommonCfg.TxRateIndex);
-		AsicUpdateAutoFallBackTable(pAd, pTable);
-	}
-
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-    pEntry->HTPhyMode.word = pAd->StaCfg.HTPhyMode.word;
-    pEntry->MaxHTPhyMode.word = pAd->StaCfg.HTPhyMode.word;
-	if (pAd->StaCfg.bAutoTxRateSwitch == FALSE)
-	{
-		pEntry->bAutoTxRateSwitch = FALSE;
-#ifdef DOT11_N_SUPPORT
-		if (pEntry->HTPhyMode.field.MCS == 32)
-			pEntry->HTPhyMode.field.ShortGI = GI_800;
-
-		if ((pEntry->HTPhyMode.field.MCS > MCS_7) || (pEntry->HTPhyMode.field.MCS == 32))
-			pEntry->HTPhyMode.field.STBC = STBC_NONE;
-#endif // DOT11_N_SUPPORT //
-		// If the legacy mode is set, overwrite the transmit setting of this entry.
-		if (pEntry->HTPhyMode.field.MODE <= MODE_OFDM)
-			RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-	}
-	else
-		pEntry->bAutoTxRateSwitch = TRUE;
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-
-	//  Let Link Status Page display first initial rate.
-	pAd->LastTxRate = (USHORT)(pEntry->HTPhyMode.word);
-	// Select DAC according to HT or Legacy
-	if (pAd->StaActive.SupportedPhyInfo.MCSSet[0] != 0x00)
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &Value);
-		Value &= (~0x18);
-		if (pAd->Antenna.field.TxPath == 2)
-		{
-		    Value |= 0x10;
-		}
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, Value);
-	}
-	else
-	{
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &Value);
-		Value &= (~0x18);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, Value);
-	}
-
-#ifdef DOT11_N_SUPPORT
-	if (pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE)
-	{
-	}
-	else if (pEntry->MaxRAmpduFactor == 0)
-	{
-	    // If HT AP doesn't support MaxRAmpduFactor = 1, we need to set max PSDU to 0.
-	    // Because our Init value is 1 at MACRegTable.
-		RTMP_IO_WRITE32(pAd, MAX_LEN_CFG, 0x0fff);
-	}
-#endif // DOT11_N_SUPPORT //
-
-	// Patch for Marvel AP to gain high throughput
-	// Need to set as following,
-	// 1. Set txop in register-EDCA_AC0_CFG as 0x60
-	// 2. Set EnTXWriteBackDDONE in register-WPDMA_GLO_CFG as zero
-	// 3. PBF_MAX_PCNT as 0x1F3FBF9F
-	// 4. kick per two packets when dequeue
-	//
-	// Txop can only be modified when RDG is off, WMM is disable and TxBurst is enable
-	//
-	// if 1. Legacy AP WMM on,  or 2. 11n AP, AMPDU disable.  Force turn off burst no matter what bEnableTxBurst is.
-#ifdef DOT11_N_SUPPORT
-//	if ((!IS_RT30xx(pAd)) &&
-	if (!((pAd->CommonCfg.RxStream == 1)&&(pAd->CommonCfg.TxStream == 1)) &&
-		(((pAd->StaActive.SupportedPhyInfo.bHtEnable == FALSE) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED))
-		|| ((pAd->StaActive.SupportedPhyInfo.bHtEnable == TRUE) && (pAd->CommonCfg.BACapability.field.Policy == BA_NOTUSE))))
-	{
-		RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
-		Data  &= 0xFFFFFF00;
-		RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
-
-		RTMP_IO_WRITE32(pAd, PBF_MAX_PCNT, 0x1F3F7F9F);
-		DBGPRINT(RT_DEBUG_TRACE, ("Txburst 1\n"));
-	}
-	else
-#endif // DOT11_N_SUPPORT //
-	if (pAd->CommonCfg.bEnableTxBurst)
-	{
-		RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
-		Data  &= 0xFFFFFF00;
-		Data  |= 0x60;
-		RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
-		pAd->CommonCfg.IOTestParm.bNowAtherosBurstOn = TRUE;
-
-		RTMP_IO_WRITE32(pAd, PBF_MAX_PCNT, 0x1F3FBF9F);
-		DBGPRINT(RT_DEBUG_TRACE, ("Txburst 2\n"));
-	}
-	else
-	{
-		RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &Data);
-		Data  &= 0xFFFFFF00;
-		RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, Data);
-
-		RTMP_IO_WRITE32(pAd, PBF_MAX_PCNT, 0x1F3F7F9F);
-		DBGPRINT(RT_DEBUG_TRACE, ("Txburst 3\n"));
-	}
-
-#ifdef DOT11_N_SUPPORT
-	// Re-check to turn on TX burst or not.
-	if ((pAd->CommonCfg.IOTestParm.bLastAtheros == TRUE) && ((STA_WEP_ON(pAd))||(STA_TKIP_ON(pAd))))
-	{
-		pAd->CommonCfg.IOTestParm.bNextDisableRxBA = TRUE;
-		if (pAd->CommonCfg.bEnableTxBurst)
-		{
-		    UINT32 MACValue = 0;
-			// Force disable  TXOP value in this case. The same action in MLMEUpdateProtect too.
-			// I didn't change PBF_MAX_PCNT setting.
-			RTMP_IO_READ32(pAd, EDCA_AC0_CFG, &MACValue);
-			MACValue  &= 0xFFFFFF00;
-			RTMP_IO_WRITE32(pAd, EDCA_AC0_CFG, MACValue);
-			pAd->CommonCfg.IOTestParm.bNowAtherosBurstOn = FALSE;
-		}
-	}
-	else
-	{
-		pAd->CommonCfg.IOTestParm.bNextDisableRxBA = FALSE;
-	}
-#endif // DOT11_N_SUPPORT //
-
-	pAd->CommonCfg.IOTestParm.bLastAtheros = FALSE;
-	COPY_MAC_ADDR(pAd->CommonCfg.LastBssid, pAd->CommonCfg.Bssid);
-	DBGPRINT(RT_DEBUG_TRACE, ("!!!pAd->bNextDisableRxBA= %d \n", pAd->CommonCfg.IOTestParm.bNextDisableRxBA));
-	// BSSID add in one MAC entry too.  Because in Tx, ASIC need to check Cipher and IV/EIV, BAbitmap
-	// Pther information in MACTab.Content[BSSID_WCID] is not necessary for driver.
-	// Note: As STA, The MACTab.Content[BSSID_WCID]. PairwiseKey and Shared Key for BSS0 are the same.
-
-    if (pAd->StaCfg.WepStatus <= Ndis802_11WEPDisabled)
-    {
-        pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-		pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilterAcceptAll;
-	}
-
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-	pEntry->PortSecured = pAd->StaCfg.PortSecured;
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-
-    //
-	// Patch Atheros AP TX will breakdown issue.
-	// AP Model: DLink DWL-8200AP
-	//
-	if (INFRA_ON(pAd) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) && STA_TKIP_ON(pAd))
-	{
-		RTMP_IO_WRITE32(pAd, RX_PARSER_CFG, 0x01);
-	}
-	else
-	{
-		RTMP_IO_WRITE32(pAd, RX_PARSER_CFG, 0x00);
-	}
-
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	if ((pAd->CommonCfg.BACapability.field.b2040CoexistScanSup) && (pAd->CommonCfg.Channel <= 11))
-	{
-		OPSTATUS_SET_FLAG(pAd, fOP_STATUS_SCAN_2040);
-		BuildEffectedChannelList(pAd);
-	}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-}
-
-/*
-	==========================================================================
-
-	Routine	Description:
-		Disconnect current BSSID
-
-	Arguments:
-		pAd				- Pointer to our adapter
-		IsReqFromAP		- Request from AP
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-		We need more information to know it's this requst from AP.
-		If yes! we need to do extra handling, for example, remove the WPA key.
-		Otherwise on 4-way handshaking will faied, since the WPA key didn't be
-		remove while auto reconnect.
-		Disconnect request from AP, it means we will start afresh 4-way handshaking
-		on WPA mode.
-
-	==========================================================================
-*/
-VOID LinkDown(
-	IN PRTMP_ADAPTER pAd,
-	IN  BOOLEAN      IsReqFromAP)
-{
-	UCHAR			    i, ByteValue = 0;
-
-	// Do nothing if monitor mode is on
-	if (MONITOR_ON(pAd))
-		return;
-
-#ifdef RALINK_ATE
-	// Nothing to do in ATE mode.
-	if (ATE_ON(pAd))
-		return;
-#endif // RALINK_ATE //
-
-    if (pAd->CommonCfg.bWirelessEvent)
-	{
-		RTMPSendWirelessEvent(pAd, IW_STA_LINKDOWN_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN !!!\n"));
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED);
-
-	if (ADHOC_ON(pAd))		// Adhoc mode link down
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN 1!!!\n"));
-
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_ADHOC_ON);
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-		pAd->IndicateMediaState = NdisMediaStateDisconnected;
-		RTMP_IndicateMediaState(pAd);
-        pAd->ExtraInfo = GENERAL_LINK_DOWN;
-		BssTableDeleteEntry(&pAd->ScanTab, pAd->CommonCfg.Bssid, pAd->CommonCfg.Channel);
-		DBGPRINT(RT_DEBUG_TRACE, ("!!! MacTab.Size=%d !!!\n", pAd->MacTab.Size));
-	}
-	else					// Infra structure mode
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("!!! LINK DOWN 2!!!\n"));
-
-#ifdef QOS_DLS_SUPPORT
-		// DLS tear down frame must be sent before link down
-		// send DLS-TEAR_DOWN message
-		if (pAd->CommonCfg.bDLSCapable)
-		{
-			// tear down local dls table entry
-			for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-				{
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				}
-			}
-
-			// tear down peer dls table entry
-			for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-			{
-				if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status ==  DLS_FINISH))
-				{
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					RTMPSendDLSTearDownFrame(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-				}
-			}
-		}
-#endif // QOS_DLS_SUPPORT //
-
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_INFRA_ON);
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-
-		// Saved last SSID for linkup comparison
-		pAd->CommonCfg.LastSsidLen = pAd->CommonCfg.SsidLen;
-		NdisMoveMemory(pAd->CommonCfg.LastSsid, pAd->CommonCfg.Ssid, pAd->CommonCfg.LastSsidLen);
-		COPY_MAC_ADDR(pAd->CommonCfg.LastBssid, pAd->CommonCfg.Bssid);
-		if (pAd->MlmeAux.CurrReqIsFromNdis == TRUE)
-		{
-			pAd->IndicateMediaState = NdisMediaStateDisconnected;
-			RTMP_IndicateMediaState(pAd);
-            pAd->ExtraInfo = GENERAL_LINK_DOWN;
-			DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event A!\n"));
-			pAd->MlmeAux.CurrReqIsFromNdis = FALSE;
-		}
-		else
-		{
-            //
-			// If disassociation request is from NDIS, then we don't need to delete BSSID from entry.
-			// Otherwise lost beacon or receive De-Authentication from AP,
-			// then we should delete BSSID from BssTable.
-			// If we don't delete from entry, roaming will fail.
-			//
-			BssTableDeleteEntry(&pAd->ScanTab, pAd->CommonCfg.Bssid, pAd->CommonCfg.Channel);
-		}
-
-		// restore back to -
-		//      1. long slot (20 us) or short slot (9 us) time
-		//      2. turn on/off RTS/CTS and/or CTS-to-self protection
-		//      3. short preamble
-		OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED);
-
-		if (pAd->StaCfg.CCXAdjacentAPReportFlag == TRUE)
-		{
-			//
-			// Record current AP's information.
-			// for later used reporting Adjacent AP report.
-			//
-			pAd->StaCfg.CCXAdjacentAPChannel = pAd->CommonCfg.Channel;
-			pAd->StaCfg.CCXAdjacentAPSsidLen = pAd->CommonCfg.SsidLen;
-			NdisMoveMemory(pAd->StaCfg.CCXAdjacentAPSsid, pAd->CommonCfg.Ssid, pAd->StaCfg.CCXAdjacentAPSsidLen);
-			COPY_MAC_ADDR(pAd->StaCfg.CCXAdjacentAPBssid, pAd->CommonCfg.Bssid);
-		}
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-		// Country IE of the AP will be evaluated and will be used.
-		if (pAd->StaCfg.IEEE80211dClientMode != Rt802_11_D_None)
-		{
-			NdisMoveMemory(&pAd->CommonCfg.CountryCode[0], &pAd->StaCfg.StaOriCountryCode[0], 2);
-			pAd->CommonCfg.Geography = pAd->StaCfg.StaOriGeography;
-			BuildChannelListEx(pAd);
-		}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-	}
-
-	for (i=1; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		if (pAd->MacTab.Content[i].ValidAsCLI == TRUE)
-			MacTableDeleteEntry(pAd, pAd->MacTab.Content[i].Aid, pAd->MacTab.Content[i].Addr);
-	}
-
-	pAd->StaCfg.CCXQosECWMin	= 4;
-	pAd->StaCfg.CCXQosECWMax	= 10;
-
-	AsicSetSlotTime(pAd, TRUE); //FALSE);
-	AsicSetEdcaParm(pAd, NULL);
-
-	// Set LED
-	RTMPSetLED(pAd, LED_LINK_DOWN);
-    pAd->LedIndicatorStregth = 0xF0;
-    RTMPSetSignalLED(pAd, -100);	// Force signal strength Led to be turned off, firmware is not done it.
-
-		AsicDisableSync(pAd);
-
-	pAd->Mlme.PeriodicRound = 0;
-	pAd->Mlme.OneSecPeriodicRound = 0;
-
-	if (pAd->StaCfg.BssType == BSS_INFRA)
-	{
-	// Remove StaCfg Information after link down
-	NdisZeroMemory(pAd->CommonCfg.Bssid, MAC_ADDR_LEN);
-	NdisZeroMemory(pAd->CommonCfg.Ssid, MAX_LEN_OF_SSID);
-		pAd->CommonCfg.SsidLen = 0;
-	}
-#ifdef DOT11_N_SUPPORT
-	NdisZeroMemory(&pAd->MlmeAux.HtCapability, sizeof(HT_CAPABILITY_IE));
-	NdisZeroMemory(&pAd->MlmeAux.AddHtInfo, sizeof(ADD_HT_INFO_IE));
-	pAd->MlmeAux.HtCapabilityLen = 0;
-	pAd->MlmeAux.NewExtChannelOffset = 0xff;
-#endif // DOT11_N_SUPPORT //
-
-	// Reset WPA-PSK state. Only reset when supplicant enabled
-	if (pAd->StaCfg.WpaState != SS_NOTUSE)
-	{
-		pAd->StaCfg.WpaState = SS_START;
-		// Clear Replay counter
-		NdisZeroMemory(pAd->StaCfg.ReplayCounter, 8);
-
-#ifdef QOS_DLS_SUPPORT
-		if (pAd->CommonCfg.bDLSCapable)
-			NdisZeroMemory(pAd->StaCfg.DlsReplayCounter, 8);
-#endif // QOS_DLS_SUPPORT //
-	}
-
-
-	//
-	// if link down come from AP, we need to remove all WPA keys on WPA mode.
-	// otherwise will cause 4-way handshaking failed, since the WPA key not empty.
-	//
-	if ((IsReqFromAP) && (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA))
-	{
-		// Remove all WPA keys
-		RTMPWPARemoveAllKeys(pAd);
-	}
-
-	// 802.1x port control
-#ifdef WPA_SUPPLICANT_SUPPORT
-	// Prevent clear PortSecured here with static WEP
-	// NetworkManger set security policy first then set SSID to connect AP.
-	if (pAd->StaCfg.WpaSupplicantUP &&
-		(pAd->StaCfg.WepStatus == Ndis802_11WEPEnabled) &&
-		(pAd->StaCfg.IEEE8021X == FALSE))
-	{
-		pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-	}
-	else
-#endif // WPA_SUPPLICANT_SUPPORT //
-	{
-		pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-		pAd->StaCfg.PrivacyFilter = Ndis802_11PrivFilter8021xWEP;
-	}
-
-	NdisAcquireSpinLock(&pAd->MacTabLock);
-	pAd->MacTab.Content[BSSID_WCID].PortSecured = pAd->StaCfg.PortSecured;
-	NdisReleaseSpinLock(&pAd->MacTabLock);
-
-	pAd->StaCfg.MicErrCnt = 0;
-
-	// Turn off Ckip control flag
-	pAd->StaCfg.bCkipOn = FALSE;
-	pAd->StaCfg.CCXEnable = FALSE;
-
-    pAd->IndicateMediaState = NdisMediaStateDisconnected;
-	// Update extra information to link is up
-	pAd->ExtraInfo = GENERAL_LINK_DOWN;
-
-    //pAd->StaCfg.AdhocBOnlyJoined = FALSE;
-	//pAd->StaCfg.AdhocBGJoined = FALSE;
-	//pAd->StaCfg.Adhoc20NJoined = FALSE;
-    pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
-
-	// Reset the Current AP's IP address
-	NdisZeroMemory(pAd->StaCfg.AironetIPAddress, 4);
-#ifdef RT2870
-	pAd->bUsbTxBulkAggre = FALSE;
-#endif // RT2870 //
-
-	// Clean association information
-	NdisZeroMemory(&pAd->StaCfg.AssocInfo, sizeof(NDIS_802_11_ASSOCIATION_INFORMATION));
-	pAd->StaCfg.AssocInfo.Length = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION);
-	pAd->StaCfg.ReqVarIELen = 0;
-	pAd->StaCfg.ResVarIELen = 0;
-
-	//
-	// Reset RSSI value after link down
-	//
-	pAd->StaCfg.RssiSample.AvgRssi0 = 0;
-	pAd->StaCfg.RssiSample.AvgRssi0X8 = 0;
-	pAd->StaCfg.RssiSample.AvgRssi1 = 0;
-	pAd->StaCfg.RssiSample.AvgRssi1X8 = 0;
-	pAd->StaCfg.RssiSample.AvgRssi2 = 0;
-	pAd->StaCfg.RssiSample.AvgRssi2X8 = 0;
-
-	// Restore MlmeRate
-	pAd->CommonCfg.MlmeRate = pAd->CommonCfg.BasicMlmeRate;
-	pAd->CommonCfg.RtsRate = pAd->CommonCfg.BasicMlmeRate;
-
-#ifdef DOT11_N_SUPPORT
-	//
-	// After Link down, reset piggy-back setting in ASIC. Disable RDG.
-	//
-	if (pAd->CommonCfg.BBPCurrentBW == BW_40)
-	{
-		pAd->CommonCfg.BBPCurrentBW = BW_20;
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &ByteValue);
-		ByteValue &= (~0x18);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, ByteValue);
-	}
-#endif // DOT11_N_SUPPORT //
-	// Reset DAC
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R1, &ByteValue);
-	ByteValue &= (~0x18);
-	if (pAd->Antenna.field.TxPath == 2)
-	{
-		ByteValue |= 0x10;
-	}
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R1, ByteValue);
-
-	RTMPSetPiggyBack(pAd,FALSE);
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_PIGGYBACK_INUSED);
-
-#ifdef DOT11_N_SUPPORT
-	pAd->CommonCfg.BACapability.word = pAd->CommonCfg.REGBACapability.word;
-#endif // DOT11_N_SUPPORT //
-
-	// Restore all settings in the following.
-	AsicUpdateProtect(pAd, 0, (ALLN_SETPROTECT|CCKSETPROTECT|OFDMSETPROTECT), TRUE, FALSE);
-	AsicDisableRDG(pAd);
-	pAd->CommonCfg.IOTestParm.bCurrentAtheros = FALSE;
-	pAd->CommonCfg.IOTestParm.bNowAtherosBurstOn = FALSE;
-
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-	OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_SCAN_2040);
-	pAd->CommonCfg.BSSCoexist2040.word = 0;
-	TriEventInit(pAd);
-	for (i = 0; i < (pAd->ChannelListNum - 1); i++)
-	{
-		pAd->ChannelList[i].bEffectedChannel = FALSE;
-	}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-	RTMP_IO_WRITE32(pAd, MAX_LEN_CFG, 0x1fff);
-	RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#ifndef NATIVE_WPA_SUPPLICANT_SUPPORT
-	if (pAd->StaCfg.WpaSupplicantUP) {
-		union iwreq_data    wrqu;
-		//send disassociate event to wpa_supplicant
-		memset(&wrqu, 0, sizeof(wrqu));
-		wrqu.data.flags = RT_DISASSOC_EVENT_FLAG;
-		wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, NULL);
-	}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-	{
-		union iwreq_data    wrqu;
-		memset(wrqu.ap_addr.sa_data, 0, MAC_ADDR_LEN);
-		wireless_send_event(pAd->net_dev, SIOCGIWAP, &wrqu, NULL);
-	}
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-
-#ifdef RT30xx
-	if (IS_RT3090(pAd))
-	{
-		UINT32				macdata;
-		// disable MMPS BBP control register
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R3, &ByteValue);
-		ByteValue &= ~(0x04);	//bit 2
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, ByteValue);
-
-		// disable MMPS MAC control register
-		RTMP_IO_READ32(pAd, 0x1210, &macdata);
-		macdata &= ~(0x09);	//bit 0, 3
-		RTMP_IO_WRITE32(pAd, 0x1210, macdata);
-	}
-#endif // RT30xx //
-
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID IterateOnBssTab(
-	IN PRTMP_ADAPTER pAd)
-{
-	MLME_START_REQ_STRUCT   StartReq;
-	MLME_JOIN_REQ_STRUCT    JoinReq;
-	ULONG                   BssIdx;
-
-	// Change the wepstatus to original wepstatus
-	pAd->StaCfg.WepStatus   = pAd->StaCfg.OrigWepStatus;
-	pAd->StaCfg.PairCipher  = pAd->StaCfg.OrigWepStatus;
-	pAd->StaCfg.GroupCipher = pAd->StaCfg.OrigWepStatus;
-
-	BssIdx = pAd->MlmeAux.BssIdx;
-	if (BssIdx < pAd->MlmeAux.SsidBssTab.BssNr)
-	{
-		// Check cipher suite, AP must have more secured cipher than station setting
-		// Set the Pairwise and Group cipher to match the intended AP setting
-		// We can only connect to AP with less secured cipher setting
-		if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-		{
-			pAd->StaCfg.GroupCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.GroupCipher;
-
-			if (pAd->StaCfg.WepStatus == pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipher)
-				pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipher;
-			else if (pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipherAux != Ndis802_11WEPDisabled)
-				pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA.PairCipherAux;
-			else	// There is no PairCipher Aux, downgrade our capability to TKIP
-				pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-		}
-		else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-		{
-			pAd->StaCfg.GroupCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.GroupCipher;
-
-			if (pAd->StaCfg.WepStatus == pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipher)
-				pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipher;
-			else if (pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipherAux != Ndis802_11WEPDisabled)
-				pAd->StaCfg.PairCipher = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.PairCipherAux;
-			else	// There is no PairCipher Aux, downgrade our capability to TKIP
-				pAd->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-
-			// RSN capability
-			pAd->StaCfg.RsnCapability = pAd->MlmeAux.SsidBssTab.BssEntry[BssIdx].WPA2.RsnCapability;
-		}
-
-		// Set Mix cipher flag
-		pAd->StaCfg.bMixCipher = (pAd->StaCfg.PairCipher == pAd->StaCfg.GroupCipher) ? FALSE : TRUE;
-		if (pAd->StaCfg.bMixCipher == TRUE)
-		{
-			// If mix cipher, re-build RSNIE
-			RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, 0);
-		}
-
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - iterate BSS %ld of %d\n", BssIdx, pAd->MlmeAux.SsidBssTab.BssNr));
-		JoinParmFill(pAd, &JoinReq, BssIdx);
-		MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_JOIN_REQ, sizeof(MLME_JOIN_REQ_STRUCT),
-					&JoinReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_JOIN;
-	}
-	else if (pAd->StaCfg.BssType == BSS_ADHOC)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - All BSS fail; start a new ADHOC (Ssid=%s)...\n",pAd->MlmeAux.Ssid));
-		StartParmFill(pAd, &StartReq, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen);
-		MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_START_REQ, sizeof(MLME_START_REQ_STRUCT), &StartReq);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_START;
-	}
-	else // no more BSS
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - All roaming failed, stay @ ch #%d\n", pAd->CommonCfg.Channel));
-		AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-	}
-}
-
-// for re-association only
-// IRQL = DISPATCH_LEVEL
-VOID IterateOnBssTab2(
-	IN PRTMP_ADAPTER pAd)
-{
-	MLME_REASSOC_REQ_STRUCT ReassocReq;
-	ULONG                   BssIdx;
-	BSS_ENTRY               *pBss;
-
-	BssIdx = pAd->MlmeAux.RoamIdx;
-	pBss = &pAd->MlmeAux.RoamTab.BssEntry[BssIdx];
-
-	if (BssIdx < pAd->MlmeAux.RoamTab.BssNr)
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - iterate BSS %ld of %d\n", BssIdx, pAd->MlmeAux.RoamTab.BssNr));
-
-		AsicSwitchChannel(pAd, pBss->Channel, FALSE);
-		AsicLockChannel(pAd, pBss->Channel);
-
-		// reassociate message has the same structure as associate message
-		AssocParmFill(pAd, &ReassocReq, pBss->Bssid, pBss->CapabilityInfo,
-					  ASSOC_TIMEOUT, pAd->StaCfg.DefaultListenCount);
-		MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_REASSOC_REQ,
-					sizeof(MLME_REASSOC_REQ_STRUCT), &ReassocReq);
-
-		pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_REASSOC;
-	}
-	else // no more BSS
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("CNTL - All fast roaming failed, back to ch #%d\n",pAd->CommonCfg.Channel));
-		AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-		pAd->Mlme.CntlMachine.CurrState = CNTL_IDLE;
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID JoinParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_JOIN_REQ_STRUCT *JoinReq,
-	IN ULONG BssIdx)
-{
-	JoinReq->BssIdx = BssIdx;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID ScanParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_SCAN_REQ_STRUCT *ScanReq,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen,
-	IN UCHAR BssType,
-	IN UCHAR ScanType)
-{
-    NdisZeroMemory(ScanReq->Ssid, MAX_LEN_OF_SSID);
-	ScanReq->SsidLen = SsidLen;
-	NdisMoveMemory(ScanReq->Ssid, Ssid, SsidLen);
-	ScanReq->BssType = BssType;
-	ScanReq->ScanType = ScanType;
-}
-
-#ifdef QOS_DLS_SUPPORT
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID DlsParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_DLS_REQ_STRUCT *pDlsReq,
-	IN PRT_802_11_DLS pDls,
-	IN USHORT reason)
-{
-	pDlsReq->pDLS = pDls;
-	pDlsReq->Reason = reason;
-}
-#endif // QOS_DLS_SUPPORT //
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID StartParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_START_REQ_STRUCT *StartReq,
-	IN CHAR Ssid[],
-	IN UCHAR SsidLen)
-{
-	ASSERT(SsidLen <= MAX_LEN_OF_SSID);
-	NdisMoveMemory(StartReq->Ssid, Ssid, SsidLen);
-	StartReq->SsidLen = SsidLen;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-VOID AuthParmFill(
-	IN PRTMP_ADAPTER pAd,
-	IN OUT MLME_AUTH_REQ_STRUCT *AuthReq,
-	IN PUCHAR pAddr,
-	IN USHORT Alg)
-{
-	COPY_MAC_ADDR(AuthReq->Addr, pAddr);
-	AuthReq->Alg = Alg;
-	AuthReq->Timeout = AUTH_TIMEOUT;
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-
-
-#ifdef RT2870
-
-VOID MlmeCntlConfirm(
-	IN PRTMP_ADAPTER pAd,
-	IN ULONG MsgType,
-	IN USHORT Msg)
-{
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MsgType, sizeof(USHORT), &Msg);
-}
-
-VOID ComposePsPoll(
-	IN PRTMP_ADAPTER pAd)
-{
-	PTXINFO_STRUC		pTxInfo;
-	PTXWI_STRUC		pTxWI;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("ComposePsPoll\n"));
-	NdisZeroMemory(&pAd->PsPollFrame, sizeof(PSPOLL_FRAME));
-
-	pAd->PsPollFrame.FC.PwrMgmt = 0;
-	pAd->PsPollFrame.FC.Type = BTYPE_CNTL;
-	pAd->PsPollFrame.FC.SubType = SUBTYPE_PS_POLL;
-	pAd->PsPollFrame.Aid = pAd->StaActive.Aid | 0xC000;
-	COPY_MAC_ADDR(pAd->PsPollFrame.Bssid, pAd->CommonCfg.Bssid);
-	COPY_MAC_ADDR(pAd->PsPollFrame.Ta, pAd->CurrentAddress);
-
-	RTMPZeroMemory(&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[0], 100);
-	pTxInfo = (PTXINFO_STRUC)&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[0];
-	RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(sizeof(PSPOLL_FRAME)+TXWI_SIZE), TRUE, EpToQueue[MGMTPIPEIDX], FALSE,  FALSE);
-	pTxWI = (PTXWI_STRUC)&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE];
-	RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, 0, BSSID_WCID, (sizeof(PSPOLL_FRAME)),
-		0,  0, (UCHAR)pAd->CommonCfg.MlmeTransmit.field.MCS, IFS_BACKOFF, FALSE, &pAd->CommonCfg.MlmeTransmit);
-	RTMPMoveMemory(&pAd->PsPollContext.TransferBuffer->field.WirelessPacket[TXWI_SIZE+TXINFO_SIZE], &pAd->PsPollFrame, sizeof(PSPOLL_FRAME));
-	// Append 4 extra zero bytes.
-	pAd->PsPollContext.BulkOutSize =  TXINFO_SIZE + TXWI_SIZE + sizeof(PSPOLL_FRAME) + 4;
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID ComposeNullFrame(
-	IN PRTMP_ADAPTER pAd)
-{
-	PTXINFO_STRUC		pTxInfo;
-	PTXWI_STRUC		pTxWI;
-
-	NdisZeroMemory(&pAd->NullFrame, sizeof(HEADER_802_11));
-	pAd->NullFrame.FC.Type = BTYPE_DATA;
-	pAd->NullFrame.FC.SubType = SUBTYPE_NULL_FUNC;
-	pAd->NullFrame.FC.ToDs = 1;
-	COPY_MAC_ADDR(pAd->NullFrame.Addr1, pAd->CommonCfg.Bssid);
-	COPY_MAC_ADDR(pAd->NullFrame.Addr2, pAd->CurrentAddress);
-	COPY_MAC_ADDR(pAd->NullFrame.Addr3, pAd->CommonCfg.Bssid);
-	RTMPZeroMemory(&pAd->NullContext.TransferBuffer->field.WirelessPacket[0], 100);
-	pTxInfo = (PTXINFO_STRUC)&pAd->NullContext.TransferBuffer->field.WirelessPacket[0];
-	RTMPWriteTxInfo(pAd, pTxInfo, (USHORT)(sizeof(HEADER_802_11)+TXWI_SIZE), TRUE, EpToQueue[MGMTPIPEIDX], FALSE,  FALSE);
-	pTxWI = (PTXWI_STRUC)&pAd->NullContext.TransferBuffer->field.WirelessPacket[TXINFO_SIZE];
-	RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, 0, BSSID_WCID, (sizeof(HEADER_802_11)),
-		0, 0, (UCHAR)pAd->CommonCfg.MlmeTransmit.field.MCS, IFS_BACKOFF, FALSE, &pAd->CommonCfg.MlmeTransmit);
-	RTMPMoveMemory(&pAd->NullContext.TransferBuffer->field.WirelessPacket[TXWI_SIZE+TXINFO_SIZE], &pAd->NullFrame, sizeof(HEADER_802_11));
-	pAd->NullContext.BulkOutSize =  TXINFO_SIZE + TXWI_SIZE + sizeof(pAd->NullFrame) + 4;
-}
-#endif // RT2870 //
-
-
-/*
-	==========================================================================
-	Description:
-		Pre-build a BEACON frame in the shared memory
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
-*/
-ULONG MakeIbssBeacon(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR         DsLen = 1, IbssLen = 2;
-	UCHAR         LocalErpIe[3] = {IE_ERP, 1, 0x04};
-	HEADER_802_11 BcnHdr;
-	USHORT        CapabilityInfo;
-	LARGE_INTEGER FakeTimestamp;
-	ULONG         FrameLen = 0;
-	PTXWI_STRUC	  pTxWI = &pAd->BeaconTxWI;
-	CHAR         *pBeaconFrame = pAd->BeaconBuf;
-	BOOLEAN       Privacy;
-	UCHAR         SupRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR         SupRateLen = 0;
-	UCHAR         ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR         ExtRateLen = 0;
-	UCHAR         RSNIe = IE_WPA;
-
-	if ((pAd->CommonCfg.PhyMode == PHY_11B) && (pAd->CommonCfg.Channel <= 14))
-	{
-		SupRate[0] = 0x82; // 1 mbps
-		SupRate[1] = 0x84; // 2 mbps
-		SupRate[2] = 0x8b; // 5.5 mbps
-		SupRate[3] = 0x96; // 11 mbps
-		SupRateLen = 4;
-		ExtRateLen = 0;
-	}
-	else if (pAd->CommonCfg.Channel > 14)
-	{
-		SupRate[0]  = 0x8C;    // 6 mbps, in units of 0.5 Mbps, basic rate
-		SupRate[1]  = 0x12;    // 9 mbps, in units of 0.5 Mbps
-		SupRate[2]  = 0x98;    // 12 mbps, in units of 0.5 Mbps, basic rate
-		SupRate[3]  = 0x24;    // 18 mbps, in units of 0.5 Mbps
-		SupRate[4]  = 0xb0;    // 24 mbps, in units of 0.5 Mbps, basic rate
-		SupRate[5]  = 0x48;    // 36 mbps, in units of 0.5 Mbps
-		SupRate[6]  = 0x60;    // 48 mbps, in units of 0.5 Mbps
-		SupRate[7]  = 0x6c;    // 54 mbps, in units of 0.5 Mbps
-		SupRateLen  = 8;
-		ExtRateLen  = 0;
-
-		//
-		// Also Update MlmeRate & RtsRate for G only & A only
-		//
-		pAd->CommonCfg.MlmeRate = RATE_6;
-		pAd->CommonCfg.RtsRate = RATE_6;
-		pAd->CommonCfg.MlmeTransmit.field.MODE = MODE_OFDM;
-		pAd->CommonCfg.MlmeTransmit.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MODE = MODE_OFDM;
-		pAd->MacTab.Content[BSS0Mcast_WCID].HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pAd->CommonCfg.MlmeRate];
-	}
-	else
-	{
-		SupRate[0] = 0x82; // 1 mbps
-		SupRate[1] = 0x84; // 2 mbps
-		SupRate[2] = 0x8b; // 5.5 mbps
-		SupRate[3] = 0x96; // 11 mbps
-		SupRateLen = 4;
-
-		ExtRate[0]  = 0x0C;    // 6 mbps, in units of 0.5 Mbps,
-		ExtRate[1]  = 0x12;    // 9 mbps, in units of 0.5 Mbps
-		ExtRate[2]  = 0x18;    // 12 mbps, in units of 0.5 Mbps,
-		ExtRate[3]  = 0x24;    // 18 mbps, in units of 0.5 Mbps
-		ExtRate[4]  = 0x30;    // 24 mbps, in units of 0.5 Mbps,
-		ExtRate[5]  = 0x48;    // 36 mbps, in units of 0.5 Mbps
-		ExtRate[6]  = 0x60;    // 48 mbps, in units of 0.5 Mbps
-		ExtRate[7]  = 0x6c;    // 54 mbps, in units of 0.5 Mbps
-		ExtRateLen  = 8;
-	}
-
-	pAd->StaActive.SupRateLen = SupRateLen;
-	NdisMoveMemory(pAd->StaActive.SupRate, SupRate, SupRateLen);
-	pAd->StaActive.ExtRateLen = ExtRateLen;
-	NdisMoveMemory(pAd->StaActive.ExtRate, ExtRate, ExtRateLen);
-
-	// compose IBSS beacon frame
-	MgtMacHeaderInit(pAd, &BcnHdr, SUBTYPE_BEACON, 0, BROADCAST_ADDR, pAd->CommonCfg.Bssid);
-	Privacy = (pAd->StaCfg.WepStatus == Ndis802_11Encryption1Enabled) ||
-			  (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
-			  (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled);
-	CapabilityInfo = CAP_GENERATE(0, 1, Privacy, (pAd->CommonCfg.TxPreamble == Rt802_11PreambleShort), 0, 0);
-
-	MakeOutgoingFrame(pBeaconFrame,                &FrameLen,
-					  sizeof(HEADER_802_11),           &BcnHdr,
-					  TIMESTAMP_LEN,                   &FakeTimestamp,
-					  2,                               &pAd->CommonCfg.BeaconPeriod,
-					  2,                               &CapabilityInfo,
-					  1,                               &SsidIe,
-					  1,                               &pAd->CommonCfg.SsidLen,
-					  pAd->CommonCfg.SsidLen,          pAd->CommonCfg.Ssid,
-					  1,                               &SupRateIe,
-					  1,                               &SupRateLen,
-					  SupRateLen,                      SupRate,
-					  1,                               &DsIe,
-					  1,                               &DsLen,
-					  1,                               &pAd->CommonCfg.Channel,
-					  1,                               &IbssIe,
-					  1,                               &IbssLen,
-					  2,                               &pAd->StaActive.AtimWin,
-					  END_OF_ARGS);
-
-	// add ERP_IE and EXT_RAE IE of in 802.11g
-	if (ExtRateLen)
-	{
-		ULONG	tmp;
-
-		MakeOutgoingFrame(pBeaconFrame + FrameLen,         &tmp,
-						  3,                               LocalErpIe,
-						  1,                               &ExtRateIe,
-						  1,                               &ExtRateLen,
-						  ExtRateLen,                      ExtRate,
-						  END_OF_ARGS);
-		FrameLen += tmp;
-	}
-
-	// If adhoc secruity is set for WPA-None, append the cipher suite IE
-	if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-	{
-		ULONG tmp;
-        RTMPMakeRSNIE(pAd, pAd->StaCfg.AuthMode, pAd->StaCfg.WepStatus, BSS0);
-
-		MakeOutgoingFrame(pBeaconFrame + FrameLen,        	&tmp,
-						  1,                              	&RSNIe,
-						  1,                            	&pAd->StaCfg.RSNIE_Len,
-						  pAd->StaCfg.RSNIE_Len,      		pAd->StaCfg.RSN_IE,
-						  END_OF_ARGS);
-		FrameLen += tmp;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-	{
-		ULONG TmpLen;
-		UCHAR HtLen, HtLen1;
-
-#ifdef RT_BIG_ENDIAN
-		HT_CAPABILITY_IE HtCapabilityTmp;
-		ADD_HT_INFO_IE	addHTInfoTmp;
-		USHORT	b2lTmp, b2lTmp2;
-#endif
-
-		// add HT Capability IE
-		HtLen = sizeof(pAd->CommonCfg.HtCapability);
-		HtLen1 = sizeof(pAd->CommonCfg.AddHTInfo);
-#ifndef RT_BIG_ENDIAN
-		MakeOutgoingFrame(pBeaconFrame+FrameLen,	&TmpLen,
-						  1,						&HtCapIe,
-						  1,						&HtLen,
-						  HtLen,					&pAd->CommonCfg.HtCapability,
-						  1,						&AddHtInfoIe,
-						  1,						&HtLen1,
-						  HtLen1,					&pAd->CommonCfg.AddHTInfo,
-						  END_OF_ARGS);
-#else
-		NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, HtLen);
-		*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-		*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-		NdisMoveMemory(&addHTInfoTmp, &pAd->CommonCfg.AddHTInfo, HtLen1);
-		*(USHORT *)(&addHTInfoTmp.AddHtInfo2) = SWAP16(*(USHORT *)(&addHTInfoTmp.AddHtInfo2));
-		*(USHORT *)(&addHTInfoTmp.AddHtInfo3) = SWAP16(*(USHORT *)(&addHTInfoTmp.AddHtInfo3));
-
-		MakeOutgoingFrame(pBeaconFrame+FrameLen,	&TmpLen,
-						  1,						&HtCapIe,
-						  1,						&HtLen,
-						  HtLen,					&HtCapabilityTmp,
-						  1,						&AddHtInfoIe,
-						  1,						&HtLen1,
-						  HtLen1,					&addHTInfoTmp,
-						  END_OF_ARGS);
-#endif
-		FrameLen += TmpLen;
-	}
-#endif // DOT11_N_SUPPORT //
-
-	//beacon use reserved WCID 0xff
-    if (pAd->CommonCfg.Channel > 14)
-    {
-	RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE,  TRUE, FALSE, FALSE, TRUE, 0, 0xff, FrameLen,
-		PID_MGMT, PID_BEACON, RATE_1, IFS_HTTXOP, FALSE, &pAd->CommonCfg.MlmeTransmit);
-    }
-    else
-    {
-        // Set to use 1Mbps for Adhoc beacon.
-		HTTRANSMIT_SETTING Transmit;
-        Transmit.word = 0;
-        RTMPWriteTxWI(pAd, pTxWI, FALSE, FALSE,  TRUE, FALSE, FALSE, TRUE, 0, 0xff, FrameLen,
-    		PID_MGMT, PID_BEACON, RATE_1, IFS_HTTXOP, FALSE, &Transmit);
-    }
-
-#ifdef RT_BIG_ENDIAN
-	RTMPFrameEndianChange(pAd, pBeaconFrame, DIR_WRITE, FALSE);
-	RTMPWIEndianChange((PUCHAR)pTxWI, TYPE_TXWI);
-#endif
-
-    DBGPRINT(RT_DEBUG_TRACE, ("MakeIbssBeacon (len=%ld), SupRateLen=%d, ExtRateLen=%d, Channel=%d, PhyMode=%d\n",
-					FrameLen, SupRateLen, ExtRateLen, pAd->CommonCfg.Channel, pAd->CommonCfg.PhyMode));
-	return FrameLen;
-}
-
+#include "../../rt2870/sta/connect.c"
 
diff --git a/drivers/staging/rt3070/sta/dls.c b/drivers/staging/rt3070/sta/dls.c
deleted file mode 100644
index 8bcd413..0000000
--- a/drivers/staging/rt3070/sta/dls.c
+++ /dev/null
@@ -1,2170 +0,0 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    dls.c
-
-    Abstract:
-    Handle WMM-DLS state machine
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Rory Chen   02-14-2006
-	Arvin Tai	06-03-2008	  Modified for RT28xx
- */
-
-#include "../rt_config.h"
-
-/*
-    ==========================================================================
-    Description:
-        dls state machine init, including state transition and timer init
-    Parameters:
-        Sm - pointer to the dls state machine
-    Note:
-        The state machine looks like this
-
-                            DLS_IDLE
-    MT2_MLME_DLS_REQUEST   MlmeDlsReqAction
-    MT2_PEER_DLS_REQUEST   PeerDlsReqAction
-    MT2_PEER_DLS_RESPONSE  PeerDlsRspAction
-    MT2_MLME_DLS_TEARDOWN  MlmeTearDownAction
-    MT2_PEER_DLS_TEARDOWN  PeerTearDownAction
-
-	IRQL = PASSIVE_LEVEL
-
-    ==========================================================================
- */
-void DlsStateMachineInit(
-    IN PRTMP_ADAPTER pAd,
-    IN STATE_MACHINE *Sm,
-    OUT STATE_MACHINE_FUNC Trans[])
-{
-	UCHAR	i;
-
-    StateMachineInit(Sm, (STATE_MACHINE_FUNC*)Trans, MAX_DLS_STATE, MAX_DLS_MSG, (STATE_MACHINE_FUNC)Drop, DLS_IDLE, DLS_MACHINE_BASE);
-
-    // the first column
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_MLME_DLS_REQ, (STATE_MACHINE_FUNC)MlmeDlsReqAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_PEER_DLS_REQ, (STATE_MACHINE_FUNC)PeerDlsReqAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_PEER_DLS_RSP, (STATE_MACHINE_FUNC)PeerDlsRspAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_MLME_DLS_TEAR_DOWN, (STATE_MACHINE_FUNC)MlmeDlsTearDownAction);
-    StateMachineSetAction(Sm, DLS_IDLE, MT2_PEER_DLS_TEAR_DOWN, (STATE_MACHINE_FUNC)PeerDlsTearDownAction);
-
-	for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		pAd->StaCfg.DLSEntry[i].pAd = pAd;
-		RTMPInitTimer(pAd, &pAd->StaCfg.DLSEntry[i].Timer, GET_TIMER_FUNCTION(DlsTimeoutAction), pAd, FALSE);
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeDlsReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen = 0;
-	HEADER_802_11	DlsReqHdr;
-	PRT_802_11_DLS	pDLS = NULL;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_REQUEST;
-	ULONG			tmp;
-	USHORT			reason;
-	ULONG			Timeout;
-	BOOLEAN			TimerCancelled;
-
-	if(!MlmeDlsReqSanity(pAd, Elem->Msg, Elem->MsgLen, &pDLS, &reason))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - MlmeDlsReqAction() \n"));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("DLS - MlmeDlsReqAction() allocate memory failed \n"));
-		return;
-	}
-
-	ActHeaderInit(pAd, &DlsReqHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-
-	// Build basic frame first
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-					sizeof(HEADER_802_11),		&DlsReqHdr,
-					1,							&Category,
-					1,							&Action,
-					6,							&pDLS->MacAddr,
-					6,							pAd->CurrentAddress,
-					2,							&pAd->StaActive.CapabilityInfo,
-					2,							&pDLS->TimeOut,
-					1,							&SupRateIe,
-					1,							&pAd->MlmeAux.SupRateLen,
-					pAd->MlmeAux.SupRateLen,	pAd->MlmeAux.SupRate,
-					END_OF_ARGS);
-
-	if (pAd->MlmeAux.ExtRateLen != 0)
-	{
-		MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-						  1,						&ExtRateIe,
-						  1,						&pAd->MlmeAux.ExtRateLen,
-						  pAd->MlmeAux.ExtRateLen,	pAd->MlmeAux.ExtRate,
-						  END_OF_ARGS);
-		FrameLen += tmp;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-	{
-		UCHAR HtLen;
-
-#ifdef RT_BIG_ENDIAN
-		HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
-
-		// add HT Capability IE
-		HtLen = sizeof(HT_CAPABILITY_IE);
-#ifndef RT_BIG_ENDIAN
-		MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-							1,						&HtCapIe,
-							1,						&HtLen,
-							HtLen,					&pAd->CommonCfg.HtCapability,
-							END_OF_ARGS);
-#else
-		NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, HtLen);
-							*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-							*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-		MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-							1,						&HtCapIe,
-							1,						&HtLen,
-							HtLen,					&HtCapabilityTmp,
-							END_OF_ARGS);
-#endif
-		FrameLen = FrameLen + tmp;
-	}
-#endif // DOT11_N_SUPPORT //
-
-	RTMPCancelTimer(&pDLS->Timer, &TimerCancelled);
-	Timeout = DLS_TIMEOUT;
-	RTMPSetTimer(&pDLS->Timer, Timeout);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerDlsReqAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen = 0;
-	USHORT			StatusCode = MLME_SUCCESS;
-	HEADER_802_11	DlsRspHdr;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_RESPONSE;
-	ULONG			tmp;
-	USHORT			CapabilityInfo;
-	UCHAR			DA[MAC_ADDR_LEN], SA[MAC_ADDR_LEN];
-	USHORT			DLSTimeOut;
-	SHORT			i;
-	ULONG			Timeout;
-	BOOLEAN			TimerCancelled;
-	PRT_802_11_DLS	pDLS = NULL;
-	UCHAR			MaxSupportedRateIn500Kbps = 0;
-    UCHAR			SupportedRatesLen;
-    UCHAR			SupportedRates[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR			HtCapabilityLen;
-	HT_CAPABILITY_IE	HtCapability;
-
-	if (!PeerDlsReqSanity(pAd, Elem->Msg, Elem->MsgLen, DA, SA, &CapabilityInfo, &DLSTimeOut,
-							&SupportedRatesLen, &SupportedRates[0], &HtCapabilityLen, &HtCapability))
-		return;
-
-    // supported rates array may not be sorted. sort it and find the maximum rate
-    for (i = 0; i < SupportedRatesLen; i++)
-    {
-        if (MaxSupportedRateIn500Kbps < (SupportedRates[i] & 0x7f))
-            MaxSupportedRateIn500Kbps = SupportedRates[i] & 0x7f;
-    }
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsReqAction() from %02x:%02x:%02x:%02x:%02x:%02x\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsReqAction() allocate memory failed \n"));
-		return;
-	}
-
-	if (!INFRA_ON(pAd))
-	{
-		StatusCode = MLME_REQUEST_DECLINED;
-	}
-	else if (!pAd->CommonCfg.bWmmCapable)
-	{
-		StatusCode = MLME_DEST_STA_IS_NOT_A_QSTA;
-	}
-	else if (!pAd->CommonCfg.bDLSCapable)
-	{
-		StatusCode = MLME_REQUEST_DECLINED;
-	}
-	else
-	{
-		// find table to update parameters
-		for (i = (MAX_NUM_OF_DLS_ENTRY-1); i >= 0; i--)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-					pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-				else
-				{
-					RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-					pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-				}
-
-				pAd->StaCfg.DLSEntry[i].Sequence = 0;
-				pAd->StaCfg.DLSEntry[i].TimeOut = DLSTimeOut;
-				pAd->StaCfg.DLSEntry[i].CountDownTimer = DLSTimeOut;
-				if (HtCapabilityLen != 0)
-					pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-				else
-					pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-				pDLS = &pAd->StaCfg.DLSEntry[i];
-				break;
-			}
-		}
-
-		// can not find in table, create a new one
-		if (i < 0)
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsReqAction() can not find same entry \n"));
-			for (i=(MAX_NUM_OF_DLS_ENTRY - 1); i >= MAX_NUM_OF_INIT_DLS_ENTRY; i--)
-			{
-				if (!pAd->StaCfg.DLSEntry[i].Valid)
-				{
-					MAC_TABLE_ENTRY *pEntry;
-					UCHAR MaxSupportedRate = RATE_11;
-
-					if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-					{
-						pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-					}
-					else
-					{
-						RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-						pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-					}
-
-					pAd->StaCfg.DLSEntry[i].Sequence = 0;
-					pAd->StaCfg.DLSEntry[i].Valid = TRUE;
-					pAd->StaCfg.DLSEntry[i].TimeOut = DLSTimeOut;
-					pAd->StaCfg.DLSEntry[i].CountDownTimer = DLSTimeOut;
-					NdisMoveMemory(pAd->StaCfg.DLSEntry[i].MacAddr, SA, MAC_ADDR_LEN);
-					if (HtCapabilityLen != 0)
-						pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-					else
-						pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-					pDLS = &pAd->StaCfg.DLSEntry[i];
-					pEntry = MacTableInsertDlsEntry(pAd, SA, i);
-
-					switch (MaxSupportedRateIn500Kbps)
-					{
-						case 108: MaxSupportedRate = RATE_54;   break;
-						case 96:  MaxSupportedRate = RATE_48;   break;
-						case 72:  MaxSupportedRate = RATE_36;   break;
-						case 48:  MaxSupportedRate = RATE_24;   break;
-						case 36:  MaxSupportedRate = RATE_18;   break;
-						case 24:  MaxSupportedRate = RATE_12;   break;
-						case 18:  MaxSupportedRate = RATE_9;    break;
-						case 12:  MaxSupportedRate = RATE_6;    break;
-						case 22:  MaxSupportedRate = RATE_11;   break;
-						case 11:  MaxSupportedRate = RATE_5_5;  break;
-						case 4:   MaxSupportedRate = RATE_2;    break;
-						case 2:   MaxSupportedRate = RATE_1;    break;
-						default:  MaxSupportedRate = RATE_11;   break;
-					}
-
-					pEntry->MaxSupportedRate = min(pAd->CommonCfg.MaxTxRate, MaxSupportedRate);
-
-					if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->HTPhyMode.field.MODE = MODE_CCK;
-						pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->HTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					}
-
-					pEntry->MaxHTPhyMode.field.BW = BW_20;
-					pEntry->MinHTPhyMode.field.BW = BW_20;
-
-#ifdef DOT11_N_SUPPORT
-					pEntry->HTCapability.MCSSet[0] = 0;
-					pEntry->HTCapability.MCSSet[1] = 0;
-
-					// If this Entry supports 802.11n, upgrade to HT rate.
-					if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-					{
-						UCHAR	j, bitmask; //k,bitmask;
-						CHAR    ii;
-
-						if ((HtCapability.HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-							pAd->MacTab.fAnyStationNonGF = TRUE;
-							pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
-						}
-
-						if ((HtCapability.HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
-						{
-							pEntry->MaxHTPhyMode.field.BW= BW_40;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(HtCapability.HtCapInfo.ShortGIfor40));
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.BW = BW_20;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(HtCapability.HtCapInfo.ShortGIfor20));
-							pAd->MacTab.fAnyStation20Only = TRUE;
-						}
-
-						// find max fixed rate
-						for (ii=15; ii>=0; ii--)
-						{
-							j = ii/8;
-							bitmask = (1<<(ii-(j*8)));
-							if ( (pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j]&bitmask) && (HtCapability.MCSSet[j]&bitmask))
-							{
-								pEntry->MaxHTPhyMode.field.MCS = ii;
-								break;
-							}
-							if (ii==0)
-								break;
-						}
-
-
-						if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
-						{
-
-							printk("@@@ pAd->CommonCfg.RegTransmitSetting.field.MCS = %d\n",
-								pAd->StaCfg.DesiredTransmitSetting.field.MCS);
-							if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
-							{
-								// Fix MCS as HT Duplicated Mode
-								pEntry->MaxHTPhyMode.field.BW = 1;
-								pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-								pEntry->MaxHTPhyMode.field.STBC = 0;
-								pEntry->MaxHTPhyMode.field.ShortGI = 0;
-								pEntry->MaxHTPhyMode.field.MCS = 32;
-							}
-							else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
-							{
-								// STA supports fixed MCS
-								pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
-							}
-						}
-
-						pEntry->MaxHTPhyMode.field.STBC = (HtCapability.HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
-						pEntry->MpduDensity = HtCapability.HtCapParm.MpduDensity;
-						pEntry->MaxRAmpduFactor = HtCapability.HtCapParm.MaxRAmpduFactor;
-						pEntry->MmpsMode = (UCHAR)HtCapability.HtCapInfo.MimoPs;
-						pEntry->AMsduSize = (UCHAR)HtCapability.HtCapInfo.AMsduSize;
-						pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-
-						if (HtCapability.HtCapInfo.ShortGIfor20)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
-						if (HtCapability.HtCapInfo.ShortGIfor40)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
-						if (HtCapability.HtCapInfo.TxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
-						if (HtCapability.HtCapInfo.RxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.PlusHTC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
-						if (pAd->CommonCfg.bRdg && HtCapability.ExtHtCapInfo.RDGSupport)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.MCSFeedback == 0x03)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
-
-						NdisMoveMemory(&pEntry->HTCapability, &HtCapability, sizeof(HT_CAPABILITY_IE));
-					}
-#endif // DOT11_N_SUPPORT //
-
-					pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-					pEntry->CurrTxRate = pEntry->MaxSupportedRate;
-					CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-
-					if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-					{
-						PUCHAR pTable;
-						UCHAR TableSize = 0;
-
-						MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
-						pEntry->bAutoTxRateSwitch = TRUE;
-					}
-					else
-					{
-						pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-						pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
-						pEntry->bAutoTxRateSwitch = FALSE;
-
-						RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-					}
-					pEntry->RateLen = SupportedRatesLen;
-
-					break;
-				}
-			}
-		}
-		StatusCode = MLME_SUCCESS;
-
-		// can not find in table, create a new one
-		if (i < 0)
-		{
-			StatusCode = MLME_QOS_UNSPECIFY;
-			DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsReqAction() DLSEntry table full(only can support %d DLS session) \n", MAX_NUM_OF_DLS_ENTRY - MAX_NUM_OF_INIT_DLS_ENTRY));
-		}
-		else
-		{
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsReqAction() use entry(%d) %02x:%02x:%02x:%02x:%02x:%02x\n",
-				i, SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-		}
-	}
-
-	ActHeaderInit(pAd, &DlsRspHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-
-	// Build basic frame first
-	if (StatusCode == MLME_SUCCESS)
-	{
-		MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-						sizeof(HEADER_802_11),		&DlsRspHdr,
-						1,							&Category,
-						1,							&Action,
-						2,							&StatusCode,
-						6,							SA,
-						6,							pAd->CurrentAddress,
-						2,							&pAd->StaActive.CapabilityInfo,
-						1,							&SupRateIe,
-						1,							&pAd->MlmeAux.SupRateLen,
-						pAd->MlmeAux.SupRateLen,	pAd->MlmeAux.SupRate,
-						END_OF_ARGS);
-
-		if (pAd->MlmeAux.ExtRateLen != 0)
-		{
-			MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-							  1,						&ExtRateIe,
-							  1,						&pAd->MlmeAux.ExtRateLen,
-							  pAd->MlmeAux.ExtRateLen, 	pAd->MlmeAux.ExtRate,
-							  END_OF_ARGS);
-			FrameLen += tmp;
-		}
-
-#ifdef DOT11_N_SUPPORT
-		if ((pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-		{
-			UCHAR HtLen;
-
-#ifdef RT_BIG_ENDIAN
-			HT_CAPABILITY_IE HtCapabilityTmp;
-#endif
-
-			// add HT Capability IE
-			HtLen = sizeof(HT_CAPABILITY_IE);
-#ifndef RT_BIG_ENDIAN
-			MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-								1,						&HtCapIe,
-								1,						&HtLen,
-								HtLen,					&pAd->CommonCfg.HtCapability,
-								END_OF_ARGS);
-#else
-			NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, HtLen);
-								*(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo));
-								*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo));
-
-			MakeOutgoingFrame(pOutBuffer + FrameLen,	&tmp,
-								1,						&HtCapIe,
-								1,						&HtLen,
-								HtLen,					&HtCapabilityTmp,
-								END_OF_ARGS);
-#endif
-			FrameLen = FrameLen + tmp;
-		}
-#endif // DOT11_N_SUPPORT //
-
-		if (pDLS && (pDLS->Status != DLS_FINISH))
-		{
-			RTMPCancelTimer(&pDLS->Timer, &TimerCancelled);
-			Timeout = DLS_TIMEOUT;
-			RTMPSetTimer(&pDLS->Timer, Timeout);
-		}
-	}
-	else
-	{
-		MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-						sizeof(HEADER_802_11),		&DlsRspHdr,
-						1,							&Category,
-						1,							&Action,
-						2,							&StatusCode,
-						6,							SA,
-						6,							pAd->CurrentAddress,
-						END_OF_ARGS);
-	}
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerDlsRspAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT		CapabilityInfo;
-	UCHAR		DA[MAC_ADDR_LEN], SA[MAC_ADDR_LEN];
-	USHORT		StatusCode;
-	SHORT		i;
-	BOOLEAN		TimerCancelled;
-	UCHAR		MaxSupportedRateIn500Kbps = 0;
-    UCHAR		SupportedRatesLen;
-    UCHAR		SupportedRates[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		HtCapabilityLen;
-	HT_CAPABILITY_IE	HtCapability;
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return;
-
-	if (!INFRA_ON(pAd))
-		return;
-
-	if (!PeerDlsRspSanity(pAd, Elem->Msg, Elem->MsgLen, DA, SA, &CapabilityInfo, &StatusCode,
-							&SupportedRatesLen, &SupportedRates[0], &HtCapabilityLen, &HtCapability))
-		return;
-
-    // supported rates array may not be sorted. sort it and find the maximum rate
-    for (i=0; i<SupportedRatesLen; i++)
-    {
-        if (MaxSupportedRateIn500Kbps < (SupportedRates[i] & 0x7f))
-            MaxSupportedRateIn500Kbps = SupportedRates[i] & 0x7f;
-    }
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() from %02x:%02x:%02x:%02x:%02x:%02x with StatusCode=%d, CapabilityInfo=0x%x\n",
-		SA[0], SA[1], SA[2], SA[3], SA[4], SA[5], StatusCode, CapabilityInfo));
-
-	for (i = 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			if (StatusCode == MLME_SUCCESS)
-			{
-				MAC_TABLE_ENTRY *pEntry;
-				UCHAR MaxSupportedRate = RATE_11;
-
-				pEntry = MacTableInsertDlsEntry(pAd, SA, i);
-
-				switch (MaxSupportedRateIn500Kbps)
-				{
-					case 108: MaxSupportedRate = RATE_54;   break;
-					case 96:  MaxSupportedRate = RATE_48;   break;
-					case 72:  MaxSupportedRate = RATE_36;   break;
-					case 48:  MaxSupportedRate = RATE_24;   break;
-					case 36:  MaxSupportedRate = RATE_18;   break;
-					case 24:  MaxSupportedRate = RATE_12;   break;
-					case 18:  MaxSupportedRate = RATE_9;    break;
-					case 12:  MaxSupportedRate = RATE_6;    break;
-					case 22:  MaxSupportedRate = RATE_11;   break;
-					case 11:  MaxSupportedRate = RATE_5_5;  break;
-					case 4:   MaxSupportedRate = RATE_2;    break;
-					case 2:   MaxSupportedRate = RATE_1;    break;
-					default:  MaxSupportedRate = RATE_11;   break;
-				}
-
-				pEntry->MaxSupportedRate = min(pAd->CommonCfg.MaxTxRate, MaxSupportedRate);
-
-				if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
-				{
-					pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
-					pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
-					pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					pEntry->HTPhyMode.field.MODE = MODE_CCK;
-					pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-				}
-				else
-				{
-					pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
-					pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
-					pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					pEntry->HTPhyMode.field.MODE = MODE_OFDM;
-					pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-				}
-
-				pEntry->MaxHTPhyMode.field.BW = BW_20;
-				pEntry->MinHTPhyMode.field.BW = BW_20;
-
-#ifdef DOT11_N_SUPPORT
-				pEntry->HTCapability.MCSSet[0] = 0;
-				pEntry->HTCapability.MCSSet[1] = 0;
-
-				// If this Entry supports 802.11n, upgrade to HT rate.
-				if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-				{
-					UCHAR	j, bitmask; //k,bitmask;
-					CHAR    ii;
-
-					if ((HtCapability.HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-						pAd->MacTab.fAnyStationNonGF = TRUE;
-						pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
-					}
-
-					if ((HtCapability.HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
-					{
-						pEntry->MaxHTPhyMode.field.BW= BW_40;
-						pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(HtCapability.HtCapInfo.ShortGIfor40));
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.BW = BW_20;
-						pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(HtCapability.HtCapInfo.ShortGIfor20));
-						pAd->MacTab.fAnyStation20Only = TRUE;
-					}
-
-					// find max fixed rate
-					for (ii=15; ii>=0; ii--)
-					{
-						j = ii/8;
-						bitmask = (1<<(ii-(j*8)));
-						if ( (pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j]&bitmask) && (HtCapability.MCSSet[j]&bitmask))
-						{
-							pEntry->MaxHTPhyMode.field.MCS = ii;
-							break;
-						}
-						if (ii==0)
-							break;
-					}
-
-					if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
-					{
-						if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
-						{
-							// Fix MCS as HT Duplicated Mode
-							pEntry->MaxHTPhyMode.field.BW = 1;
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-							pEntry->MaxHTPhyMode.field.STBC = 0;
-							pEntry->MaxHTPhyMode.field.ShortGI = 0;
-							pEntry->MaxHTPhyMode.field.MCS = 32;
-						}
-						else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
-						{
-							// STA supports fixed MCS
-							pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
-						}
-					}
-
-					pEntry->MaxHTPhyMode.field.STBC = (HtCapability.HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
-					pEntry->MpduDensity = HtCapability.HtCapParm.MpduDensity;
-					pEntry->MaxRAmpduFactor = HtCapability.HtCapParm.MaxRAmpduFactor;
-					pEntry->MmpsMode = (UCHAR)HtCapability.HtCapInfo.MimoPs;
-					pEntry->AMsduSize = (UCHAR)HtCapability.HtCapInfo.AMsduSize;
-					pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-
-					if (HtCapability.HtCapInfo.ShortGIfor20)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
-					if (HtCapability.HtCapInfo.ShortGIfor40)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
-					if (HtCapability.HtCapInfo.TxSTBC)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
-					if (HtCapability.HtCapInfo.RxSTBC)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
-					if (HtCapability.ExtHtCapInfo.PlusHTC)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
-					if (pAd->CommonCfg.bRdg && HtCapability.ExtHtCapInfo.RDGSupport)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
-					if (HtCapability.ExtHtCapInfo.MCSFeedback == 0x03)
-						CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
-
-					NdisMoveMemory(&pEntry->HTCapability, &HtCapability, sizeof(HT_CAPABILITY_IE));
-				}
-#endif // DOT11_N_SUPPORT //
-				pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-				pEntry->CurrTxRate = pEntry->MaxSupportedRate;
-				CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-
-				if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-				{
-					PUCHAR pTable;
-					UCHAR TableSize = 0;
-
-					MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
-					pEntry->bAutoTxRateSwitch = TRUE;
-				}
-				else
-				{
-					pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-					pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
-					pEntry->bAutoTxRateSwitch = FALSE;
-
-					RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-				}
-				pEntry->RateLen = SupportedRatesLen;
-
-				if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-				{
-					// If support WPA or WPA2, start STAKey hand shake,
-					// If failed hand shake, just tear down peer DLS
-					if (RTMPSendSTAKeyRequest(pAd, pAd->StaCfg.DLSEntry[i].MacAddr) != NDIS_STATUS_SUCCESS)
-					{
-						MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-						USHORT				reason = REASON_QOS_CIPHER_NOT_SUPPORT;
-
-						DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-						MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-						pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-						pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-						DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed when call RTMPSendSTAKeyRequest \n"));
-					}
-					else
-					{
-						pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-						DBGPRINT(RT_DEBUG_TRACE,("DLS - waiting for STAKey handshake procedure\n"));
-					}
-				}
-				else
-				{
-					RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-					pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-					DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() from %02x:%02x:%02x:%02x:%02x:%02x Succeed with WEP or no security\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-				}
-
-				//initialize seq no for DLS frames.
-				pAd->StaCfg.DLSEntry[i].Sequence = 0;
-				if (HtCapabilityLen != 0)
-					pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-				else
-					pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-			}
-			else
-			{
-				// DLS setup procedure failed.
-				pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-				DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed with StatusCode=%d \n", StatusCode));
-			}
-		}
-	}
-
-	if (i >= MAX_NUM_OF_INIT_DLS_ENTRY)
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() update timeout value \n"));
-		for (i=(MAX_NUM_OF_DLS_ENTRY-1); i>=MAX_NUM_OF_INIT_DLS_ENTRY; i--)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				if (StatusCode == MLME_SUCCESS)
-				{
-					MAC_TABLE_ENTRY *pEntry;
-					UCHAR MaxSupportedRate = RATE_11;
-
-					pEntry = MacTableInsertDlsEntry(pAd, SA, i);
-
-					switch (MaxSupportedRateIn500Kbps)
-					{
-						case 108: MaxSupportedRate = RATE_54;   break;
-						case 96:  MaxSupportedRate = RATE_48;   break;
-						case 72:  MaxSupportedRate = RATE_36;   break;
-						case 48:  MaxSupportedRate = RATE_24;   break;
-						case 36:  MaxSupportedRate = RATE_18;   break;
-						case 24:  MaxSupportedRate = RATE_12;   break;
-						case 18:  MaxSupportedRate = RATE_9;    break;
-						case 12:  MaxSupportedRate = RATE_6;    break;
-						case 22:  MaxSupportedRate = RATE_11;   break;
-						case 11:  MaxSupportedRate = RATE_5_5;  break;
-						case 4:   MaxSupportedRate = RATE_2;    break;
-						case 2:   MaxSupportedRate = RATE_1;    break;
-						default:  MaxSupportedRate = RATE_11;   break;
-					}
-
-					pEntry->MaxSupportedRate = min(pAd->CommonCfg.MaxTxRate, MaxSupportedRate);
-
-					if (pEntry->MaxSupportedRate < RATE_FIRST_OFDM_RATE)
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MaxHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->MinHTPhyMode.field.MODE = MODE_CCK;
-						pEntry->MinHTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-						pEntry->HTPhyMode.field.MODE = MODE_CCK;
-						pEntry->HTPhyMode.field.MCS = pEntry->MaxSupportedRate;
-					}
-					else
-					{
-						pEntry->MaxHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MaxHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->MinHTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->MinHTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-						pEntry->HTPhyMode.field.MODE = MODE_OFDM;
-						pEntry->HTPhyMode.field.MCS = OfdmRateToRxwiMCS[pEntry->MaxSupportedRate];
-					}
-
-					pEntry->MaxHTPhyMode.field.BW = BW_20;
-					pEntry->MinHTPhyMode.field.BW = BW_20;
-
-#ifdef DOT11_N_SUPPORT
-					pEntry->HTCapability.MCSSet[0] = 0;
-					pEntry->HTCapability.MCSSet[1] = 0;
-
-					// If this Entry supports 802.11n, upgrade to HT rate.
-					if ((HtCapabilityLen != 0) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-					{
-						UCHAR	j, bitmask; //k,bitmask;
-						CHAR    ii;
-
-						if ((HtCapability.HtCapInfo.GF) && (pAd->CommonCfg.DesiredHtPhy.GF))
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTGREENFIELD;
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-							pAd->MacTab.fAnyStationNonGF = TRUE;
-							pAd->CommonCfg.AddHTInfo.AddHtInfo2.NonGfPresent = 1;
-						}
-
-						if ((HtCapability.HtCapInfo.ChannelWidth) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth))
-						{
-							pEntry->MaxHTPhyMode.field.BW= BW_40;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor40)&(HtCapability.HtCapInfo.ShortGIfor40));
-						}
-						else
-						{
-							pEntry->MaxHTPhyMode.field.BW = BW_20;
-							pEntry->MaxHTPhyMode.field.ShortGI = ((pAd->CommonCfg.DesiredHtPhy.ShortGIfor20)&(HtCapability.HtCapInfo.ShortGIfor20));
-							pAd->MacTab.fAnyStation20Only = TRUE;
-						}
-
-						// find max fixed rate
-						for (ii=15; ii>=0; ii--)
-						{
-							j = ii/8;
-							bitmask = (1<<(ii-(j*8)));
-							if ( (pAd->StaCfg.DesiredHtPhyInfo.MCSSet[j]&bitmask) && (HtCapability.MCSSet[j]&bitmask))
-							{
-								pEntry->MaxHTPhyMode.field.MCS = ii;
-								break;
-							}
-							if (ii==0)
-								break;
-						}
-
-						if (pAd->StaCfg.DesiredTransmitSetting.field.MCS != MCS_AUTO)
-						{
-							printk("@@@ pAd->CommonCfg.RegTransmitSetting.field.MCS = %d\n",
-								pAd->StaCfg.DesiredTransmitSetting.field.MCS);
-							if (pAd->StaCfg.DesiredTransmitSetting.field.MCS == 32)
-							{
-								// Fix MCS as HT Duplicated Mode
-								pEntry->MaxHTPhyMode.field.BW = 1;
-								pEntry->MaxHTPhyMode.field.MODE = MODE_HTMIX;
-								pEntry->MaxHTPhyMode.field.STBC = 0;
-								pEntry->MaxHTPhyMode.field.ShortGI = 0;
-								pEntry->MaxHTPhyMode.field.MCS = 32;
-							}
-							else if (pEntry->MaxHTPhyMode.field.MCS > pAd->StaCfg.HTPhyMode.field.MCS)
-							{
-								// STA supports fixed MCS
-								pEntry->MaxHTPhyMode.field.MCS = pAd->StaCfg.HTPhyMode.field.MCS;
-							}
-						}
-
-						pEntry->MaxHTPhyMode.field.STBC = (HtCapability.HtCapInfo.RxSTBC & (pAd->CommonCfg.DesiredHtPhy.TxSTBC));
-						pEntry->MpduDensity = HtCapability.HtCapParm.MpduDensity;
-						pEntry->MaxRAmpduFactor = HtCapability.HtCapParm.MaxRAmpduFactor;
-						pEntry->MmpsMode = (UCHAR)HtCapability.HtCapInfo.MimoPs;
-						pEntry->AMsduSize = (UCHAR)HtCapability.HtCapInfo.AMsduSize;
-						pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-
-						if (HtCapability.HtCapInfo.ShortGIfor20)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI20_CAPABLE);
-						if (HtCapability.HtCapInfo.ShortGIfor40)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_SGI40_CAPABLE);
-						if (HtCapability.HtCapInfo.TxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_TxSTBC_CAPABLE);
-						if (HtCapability.HtCapInfo.RxSTBC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RxSTBC_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.PlusHTC)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_HTC_CAPABLE);
-						if (pAd->CommonCfg.bRdg && HtCapability.ExtHtCapInfo.RDGSupport)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_RDG_CAPABLE);
-						if (HtCapability.ExtHtCapInfo.MCSFeedback == 0x03)
-							CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_MCSFEEDBACK_CAPABLE);
-
-						NdisMoveMemory(&pEntry->HTCapability, &HtCapability, sizeof(HT_CAPABILITY_IE));
-					}
-#endif // DOT11_N_SUPPORT //
-
-					pEntry->HTPhyMode.word = pEntry->MaxHTPhyMode.word;
-					pEntry->CurrTxRate = pEntry->MaxSupportedRate;
-					CLIENT_STATUS_SET_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE);
-
-					if (pAd->StaCfg.bAutoTxRateSwitch == TRUE)
-					{
-						PUCHAR pTable;
-						UCHAR TableSize = 0;
-
-						MlmeSelectTxRateTable(pAd, pEntry, &pTable, &TableSize, &pEntry->CurrTxRateIndex);
-						pEntry->bAutoTxRateSwitch = TRUE;
-					}
-					else
-					{
-						pEntry->HTPhyMode.field.MODE	= pAd->StaCfg.HTPhyMode.field.MODE;
-						pEntry->HTPhyMode.field.MCS	= pAd->StaCfg.HTPhyMode.field.MCS;
-						pEntry->bAutoTxRateSwitch = FALSE;
-
-						RTMPUpdateLegacyTxSetting((UCHAR)pAd->StaCfg.DesiredTransmitSetting.field.FixedTxMode, pEntry);
-					}
-					pEntry->RateLen = SupportedRatesLen;
-
-					if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-					{
-						// If support WPA or WPA2, start STAKey hand shake,
-						// If failed hand shake, just tear down peer DLS
-						if (RTMPSendSTAKeyRequest(pAd, pAd->StaCfg.DLSEntry[i].MacAddr) != NDIS_STATUS_SUCCESS)
-						{
-							MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-							USHORT				reason = REASON_QOS_CIPHER_NOT_SUPPORT;
-
-							DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-							MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-							pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-							pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-							DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed when call RTMPSendSTAKeyRequest \n"));
-						}
-						else
-						{
-							pAd->StaCfg.DLSEntry[i].Status = DLS_WAIT_KEY;
-							DBGPRINT(RT_DEBUG_TRACE,("DLS - waiting for STAKey handshake procedure\n"));
-						}
-					}
-					else
-					{
-						RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-						pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-						DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsRspAction() from %02x:%02x:%02x:%02x:%02x:%02x Succeed with WEP or no security\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5]));
-					}
-					pAd->StaCfg.DLSEntry[i].Sequence = 0;
-					if (HtCapabilityLen != 0)
-						pAd->StaCfg.DLSEntry[i].bHTCap = TRUE;
-					else
-						pAd->StaCfg.DLSEntry[i].bHTCap = FALSE;
-				}
-				else
-				{
-					// DLS setup procedure failed.
-					pAd->StaCfg.DLSEntry[i].Status = DLS_NONE;
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-					RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-					DBGPRINT(RT_DEBUG_ERROR,("DLS - PeerDlsRspAction failed with StatusCode=%d \n", StatusCode));
-				}
-			}
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID MlmeDlsTearDownAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	ULONG			FrameLen = 0;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_TEARDOWN;
-	USHORT			ReasonCode = REASON_QOS_UNSPECIFY;
-	HEADER_802_11	DlsTearDownHdr;
-	PRT_802_11_DLS	pDLS;
-	BOOLEAN			TimerCancelled;
-	UCHAR			i;
-
-	if(!MlmeDlsReqSanity(pAd, Elem->Msg, Elem->MsgLen, &pDLS, &ReasonCode))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - MlmeDlsTearDownAction() with ReasonCode=%d \n", ReasonCode));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("DLS - MlmeDlsTearDownAction() allocate memory failed \n"));
-		return;
-	}
-
-	ActHeaderInit(pAd, &DlsTearDownHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-
-	// Build basic frame first
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-					sizeof(HEADER_802_11),		&DlsTearDownHdr,
-					1,							&Category,
-					1,							&Action,
-					6,							&pDLS->MacAddr,
-					6,							pAd->CurrentAddress,
-					2,							&ReasonCode,
-					END_OF_ARGS);
-
-	MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-	RTMPCancelTimer(&pDLS->Timer, &TimerCancelled);
-
-	// Remove key in local dls table entry
-	for (i = 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	// clear peer dls table entry
-	for (i = MAX_NUM_OF_INIT_DLS_ENTRY; i < MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (MAC_ADDR_EQUAL(pDLS->MacAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-			pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID PeerDlsTearDownAction(
-    IN PRTMP_ADAPTER pAd,
-    IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR			DA[MAC_ADDR_LEN], SA[MAC_ADDR_LEN];
-	USHORT			ReasonCode;
-	UINT			i;
-	BOOLEAN			TimerCancelled;
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return;
-
-	if (!INFRA_ON(pAd))
-		return;
-
-	if (!PeerDlsTearDownSanity(pAd, Elem->Msg, Elem->MsgLen, DA, SA, &ReasonCode))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - PeerDlsTearDownAction() from %02x:%02x:%02x:%02x:%02x:%02x with ReasonCode=%d\n", SA[0], SA[1], SA[2], SA[3], SA[4], SA[5], ReasonCode));
-
-	// clear local dls table entry
-	for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-			pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-			//AsicDelWcidTab(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			//AsicRemovePairwiseKeyEntry(pAd, BSS0, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	// clear peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(SA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-			pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-			RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-			//AsicDelWcidTab(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			//AsicRemovePairwiseKeyEntry(pAd, BSS0, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID);
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID RTMPCheckDLSTimeOut(
-	IN PRTMP_ADAPTER	pAd)
-{
-	ULONG				i;
-	MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-	USHORT				reason = REASON_QOS_UNSPECIFY;
-
-	if (! pAd->CommonCfg.bDLSCapable)
-		return;
-
-	if (! INFRA_ON(pAd))
-		return;
-
-	// If timeout value is equaled to zero, it means always not be timeout.
-
-	// update local dls table entry
-	for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if ((pAd->StaCfg.DLSEntry[i].Valid) && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& (pAd->StaCfg.DLSEntry[i].TimeOut != 0))
-		{
-			pAd->StaCfg.DLSEntry[i].CountDownTimer --;
-
-			if (pAd->StaCfg.DLSEntry[i].CountDownTimer == 0)
-			{
-				reason = REASON_QOS_REQUEST_TIMEOUT;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-			}
-		}
-	}
-
-	// update peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if ((pAd->StaCfg.DLSEntry[i].Valid) && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& (pAd->StaCfg.DLSEntry[i].TimeOut != 0))
-		{
-			pAd->StaCfg.DLSEntry[i].CountDownTimer --;
-
-			if (pAd->StaCfg.DLSEntry[i].CountDownTimer == 0)
-			{
-				reason = REASON_QOS_REQUEST_TIMEOUT;
-				pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-				pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-				DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-				MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-			}
-		}
-	}
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN RTMPRcvFrameDLSCheck(
-	IN PRTMP_ADAPTER	pAd,
-	IN PHEADER_802_11	pHeader,
-	IN ULONG			Len,
-	IN PRT28XX_RXD_STRUC	pRxD)
-{
-	ULONG			i;
-	BOOLEAN			bFindEntry = FALSE;
-	BOOLEAN			bSTAKeyFrame = FALSE;
-	PEAPOL_PACKET	pEap;
-	PUCHAR			pProto, pAddr = NULL;
-	PUCHAR			pSTAKey = NULL;
-	UCHAR			ZeroReplay[LEN_KEY_DESC_REPLAY];
-	UCHAR			Mic[16], OldMic[16];
-	UCHAR			digest[80];
-	UCHAR			DlsPTK[80];
-	UCHAR			temp[64];
-	BOOLEAN			TimerCancelled;
-	CIPHER_KEY		PairwiseKey;
-
-
-	if (! pAd->CommonCfg.bDLSCapable)
-		return bSTAKeyFrame;
-
-	if (! INFRA_ON(pAd))
-		return bSTAKeyFrame;
-
-	if (! (pHeader->FC.SubType & 0x08))
-		return bSTAKeyFrame;
-
-	if (Len < LENGTH_802_11 + 6 + 2 + 2)
-		return bSTAKeyFrame;
-
-	pProto	= (PUCHAR)pHeader + LENGTH_802_11 + 2 + 6;	// QOS Control field , 0xAA 0xAA 0xAA 0x00 0x00 0x00
-	pAddr	= pHeader->Addr2;
-
-	// L2PAD bit on will pad 2 bytes at LLC
-	if (pRxD->L2PAD)
-	{
-		pProto += 2;
-	}
-
-	if (RTMPEqualMemory(EAPOL, pProto, 2) && (pAd->StaCfg.AuthMode >=  Ndis802_11AuthModeWPA))
-	{
-		pEap = (PEAPOL_PACKET) (pProto + 2);
-
-		DBGPRINT(RT_DEBUG_TRACE,("DLS - Sniff Len=%ld, DataLen=%d, KeyMic=%d, Install=%d, KeyAck=%d, Secure=%d, EKD_DL=%d, Error=%d, Request=%d\n", Len,
-			                                                             (LENGTH_802_11 + 6 + 2 + 2 + sizeof(EAPOL_PACKET) - MAX_LEN_OF_RSNIE + 16),
-			                                                             pEap->KeyDesc.KeyInfo.KeyMic,
-			                                                             pEap->KeyDesc.KeyInfo.Install,
-			                                                             pEap->KeyDesc.KeyInfo.KeyAck,
-			                                                             pEap->KeyDesc.KeyInfo.Secure,
-			                                                             pEap->KeyDesc.KeyInfo.EKD_DL,
-			                                                             pEap->KeyDesc.KeyInfo.Error,
-			                                                             pEap->KeyDesc.KeyInfo.Request));
-
-		if ((Len >= (LENGTH_802_11 + 6 + 2 + 2 + sizeof(EAPOL_PACKET) - MAX_LEN_OF_RSNIE + 16)) && pEap->KeyDesc.KeyInfo.KeyMic
-			&& pEap->KeyDesc.KeyInfo.Install && pEap->KeyDesc.KeyInfo.KeyAck && pEap->KeyDesc.KeyInfo.Secure
-			&& pEap->KeyDesc.KeyInfo.EKD_DL && !pEap->KeyDesc.KeyInfo.Error && !pEap->KeyDesc.KeyInfo.Request)
-		{
-			// First validate replay counter, only accept message with larger replay counter
-			// Let equal pass, some AP start with all zero replay counter
-			NdisZeroMemory(ZeroReplay, LEN_KEY_DESC_REPLAY);
-			if ((RTMPCompareMemory(pEap->KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1) &&
-				(RTMPCompareMemory(pEap->KeyDesc.ReplayCounter, ZeroReplay, LEN_KEY_DESC_REPLAY) != 0))
-				return bSTAKeyFrame;
-
-			//RTMPMoveMemory(pAd->StaCfg.ReplayCounter, pEap->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-			RTMPMoveMemory(pAd->StaCfg.DlsReplayCounter, pEap->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - Sniff replay counter (%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x) Len=%ld, KeyDataLen=%d\n",
-				pAd->StaCfg.ReplayCounter[0], pAd->StaCfg.ReplayCounter[1], pAd->StaCfg.ReplayCounter[2],
-				pAd->StaCfg.ReplayCounter[3], pAd->StaCfg.ReplayCounter[4],	pAd->StaCfg.ReplayCounter[5],
-				pAd->StaCfg.ReplayCounter[6], pAd->StaCfg.ReplayCounter[7], Len, pEap->KeyDesc.KeyData[1]));
-
-			// put these code segment to get the replay counter
-			if (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED)
-				return bSTAKeyFrame;
-
-			// Check MIC value
-			// Save the MIC and replace with zero
-			// use proprietary PTK
-			NdisZeroMemory(temp, 64);
-			NdisMoveMemory(temp, "IEEE802.11 WIRELESS ACCESS POINT", 32);
-			WpaCountPTK(pAd, temp, temp, pAd->CommonCfg.Bssid, temp, pAd->CurrentAddress, DlsPTK, LEN_PTK);
-
-			NdisMoveMemory(OldMic, pEap->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-			NdisZeroMemory(pEap->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-			if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-			{
-				// AES
-				HMAC_SHA1((PUCHAR) pEap, pEap->Body_Len[1] + 4, DlsPTK, LEN_EAP_MICK, digest);
-				NdisMoveMemory(Mic,	digest,	LEN_KEY_DESC_MIC);
-			}
-			else
-			{
-				hmac_md5(DlsPTK, LEN_EAP_MICK, (PUCHAR) pEap, pEap->Body_Len[1] + 4, Mic);
-			}
-
-			if (!NdisEqualMemory(OldMic, Mic, LEN_KEY_DESC_MIC))
-			{
-				DBGPRINT(RT_DEBUG_ERROR, ("MIC Different in Msg1 of STAKey handshake! \n"));
-				return bSTAKeyFrame;
-			}
-			else
-				DBGPRINT(RT_DEBUG_TRACE, ("MIC VALID in Msg1 of STAKey handshake! \n"));
-#if 1
-			if ((pEap->KeyDesc.KeyData[0] == 0xDD) && (pEap->KeyDesc.KeyData[2] == 0x00) && (pEap->KeyDesc.KeyData[3] == 0x0C)
-				&& (pEap->KeyDesc.KeyData[4] == 0x43) && (pEap->KeyDesc.KeyData[5] == 0x02))
-			{
-				pAddr			= pEap->KeyDesc.KeyData + 8;		// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2)
-				pSTAKey			= pEap->KeyDesc.KeyData + 14;	// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2), STAKey_Mac_Addr(6)
-
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 from %02x:%02x:%02x:%02x:%02x:%02x Len=%ld, KeyDataLen=%d\n",
-					pAddr[0], pAddr[1], pAddr[2], pAddr[3], pAddr[4], pAddr[5], Len, pEap->KeyDesc.KeyData[1]));
-
-				bSTAKeyFrame = TRUE;
-			}
-#else
-			if ((pEap->KeyDesc.KeyData[0] == 0xDD) && (pEap->KeyDesc.KeyData[2] == 0x00) && (pEap->KeyDesc.KeyData[3] == 0x0F)
-				&& (pEap->KeyDesc.KeyData[4] == 0xAC) && (pEap->KeyDesc.KeyData[5] == 0x02))
-			{
-				pAddr			= pEap->KeyDesc.KeyData + 8;		// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2)
-				pSTAKey			= pEap->KeyDesc.KeyData + 14;	// Tpe(1), Len(1), OUI(3), DataType(1), Reserved(2), STAKey_Mac_Addr(6)
-
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 from %02x:%02x:%02x:%02x:%02x:%02x Len=%d, KeyDataLen=%d\n",
-					pAddr[0], pAddr[1], pAddr[2], pAddr[3], pAddr[4], pAddr[5], Len, pEap->KeyDesc.KeyData[1]));
-
-				bSTAKeyFrame = TRUE;
-			}
-#endif
-
-		}
-		else if (Len >= (LENGTH_802_11 + 6 + 2 + 2 + sizeof(EAPOL_PACKET) - MAX_LEN_OF_RSNIE))
-		{
-			RTMPMoveMemory(pAd->StaCfg.DlsReplayCounter, pEap->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-			DBGPRINT(RT_DEBUG_TRACE,("DLS - Sniff replay counter 2(%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x) Len=%ld, KeyDataLen=%d\n",
-				pAd->StaCfg.ReplayCounter[0], pAd->StaCfg.ReplayCounter[1], pAd->StaCfg.ReplayCounter[2],
-				pAd->StaCfg.ReplayCounter[3], pAd->StaCfg.ReplayCounter[4],	pAd->StaCfg.ReplayCounter[5],
-				pAd->StaCfg.ReplayCounter[6], pAd->StaCfg.ReplayCounter[7], Len, pEap->KeyDesc.KeyData[1]));
-
-		}
-	}
-
-	// If timeout value is equaled to zero, it means always not be timeout.
-	// update local dls table entry
-	for (i= 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(pAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			if (bSTAKeyFrame)
-			{
-				PMAC_TABLE_ENTRY pEntry;
-
-				// STAKey frame, add pairwise key table
-				pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-				RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-
-				PairwiseKey.KeyLen = LEN_TKIP_EK;
-				NdisMoveMemory(PairwiseKey.Key, &pSTAKey[0], LEN_TKIP_EK);
-				NdisMoveMemory(PairwiseKey.TxMic, &pSTAKey[16], LEN_TKIP_RXMICK);
-				NdisMoveMemory(PairwiseKey.RxMic, &pSTAKey[24], LEN_TKIP_TXMICK);
-
-				PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg;
-
-				pEntry = DlsEntryTableLookup(pAd, pAd->StaCfg.DLSEntry[i].MacAddr, TRUE);
-				//AsicAddKeyEntry(pAd, (USHORT)(i + 2), BSS0, 0, &PairwiseKey, TRUE, TRUE);	// reserve 0 for multicast, 1 for unicast
-				//AsicUpdateRxWCIDTable(pAd, (USHORT)(i + 2), pAddr);
-				// Add Pair-wise key to Asic
-#ifdef RT2870
-//Benson modified for USB interface, avoid in interrupt when write key, 20080724 -->
-                                {
-                                        RT_ADD_PAIRWISE_KEY_ENTRY KeyInfo;
-                                        COPY_MAC_ADDR(KeyInfo.MacAddr,pAd->StaCfg.DLSEntry[i].MacAddr);
-                                        KeyInfo.MacTabMatchWCID=pAd->StaCfg.DLSEntry[i].MacTabMatchWCID;
-                                        NdisMoveMemory(&KeyInfo.CipherKey,  &PairwiseKey,sizeof(CIPHER_KEY));
-                                        RTUSBEnqueueInternalCmd(pAd, RT_CMD_SET_KEY_TABLE, &KeyInfo, sizeof(RT_ADD_PAIRWISE_KEY_ENTRY));
-                                }
-                                {
-                                        PMAC_TABLE_ENTRY pDLSEntry;
-                                        pDLSEntry = DlsEntryTableLookup(pAd, pAd->StaCfg.DLSEntry[i].MacAddr, TRUE);
-                                        pDLSEntry->PairwiseKey.CipherAlg=PairwiseKey.CipherAlg;
-                                        RTUSBEnqueueInternalCmd(pAd, RT_CMD_SET_RX_WCID_TABLE, pDLSEntry, sizeof(MAC_TABLE_ENTRY));
-                                }
-//Benson modified for USB interface, avoid in interrupt when write key, 20080724 <--
-#endif // RT2870 //
-				NdisMoveMemory(&pEntry->PairwiseKey, &PairwiseKey, sizeof(CIPHER_KEY));
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 (Peer STA MAC Address STAKey) \n"));
-
-				RTMPSendSTAKeyHandShake(pAd, pAd->StaCfg.DLSEntry[i].MacAddr);
-
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Finish STAKey handshake procedure (Initiator side)\n"));
-			}
-			else
-			{
-				// Data frame, update timeout value
-				if (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-				{
-					pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-					//AsicUpdateRxWCIDTable(pAd, (USHORT)(i + 2), pAddr);
-				}
-			}
-
-			bFindEntry = TRUE;
-		}
-	}
-
-	// update peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && MAC_ADDR_EQUAL(pAddr, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			if (bSTAKeyFrame)
-			{
-				PMAC_TABLE_ENTRY pEntry = NULL;
-
-				// STAKey frame, add pairwise key table, and send STAkey Msg-2
-				pAd->StaCfg.DLSEntry[i].Status = DLS_FINISH;
-				RTMPCancelTimer(&pAd->StaCfg.DLSEntry[i].Timer, &TimerCancelled);
-
-				PairwiseKey.KeyLen = LEN_TKIP_EK;
-				NdisMoveMemory(PairwiseKey.Key, &pSTAKey[0], LEN_TKIP_EK);
-				NdisMoveMemory(PairwiseKey.TxMic, &pSTAKey[16], LEN_TKIP_RXMICK);
-				NdisMoveMemory(PairwiseKey.RxMic, &pSTAKey[24], LEN_TKIP_TXMICK);
-
-				PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg;
-
-				pEntry = DlsEntryTableLookup(pAd, pAd->StaCfg.DLSEntry[i].MacAddr, TRUE);
-				//AsicAddKeyEntry(pAd, (USHORT)(i + 2), BSS0, 0, &PairwiseKey, TRUE, TRUE);	// reserve 0 for multicast, 1 for unicast
-				//AsicUpdateRxWCIDTable(pAd, (USHORT)(i + 2), pAddr);
-				// Add Pair-wise key to Asic
-#ifdef RT2870
-//Benson modified for USB interface, avoid in interrupt when write key, 20080724 -->
-                                {
-                                        RT_ADD_PAIRWISE_KEY_ENTRY KeyInfo;
-                                        COPY_MAC_ADDR(KeyInfo.MacAddr,pAd->StaCfg.DLSEntry[i].MacAddr);
-                                        KeyInfo.MacTabMatchWCID=pAd->StaCfg.DLSEntry[i].MacTabMatchWCID;
-                                        NdisMoveMemory(&KeyInfo.CipherKey,  &PairwiseKey,sizeof(CIPHER_KEY));
-                                        RTUSBEnqueueInternalCmd(pAd, RT_CMD_SET_KEY_TABLE, &KeyInfo, sizeof(RT_ADD_PAIRWISE_KEY_ENTRY));
-                                }
-                                {
-                                        PMAC_TABLE_ENTRY pDLSEntry;
-                                        pDLSEntry = DlsEntryTableLookup(pAd, pAd->StaCfg.DLSEntry[i].MacAddr, TRUE);
-                                        pDLSEntry->PairwiseKey.CipherAlg=PairwiseKey.CipherAlg;
-                                        RTUSBEnqueueInternalCmd(pAd, RT_CMD_SET_RX_WCID_TABLE, pDLSEntry, sizeof(MAC_TABLE_ENTRY));
-                                }
-//Benson modified for USB interface, avoid in interrupt when write key, 20080724 <--
-#endif // RT2870 //
-				NdisMoveMemory(&pEntry->PairwiseKey, &PairwiseKey, sizeof(CIPHER_KEY));
-				DBGPRINT(RT_DEBUG_TRACE,("DLS - Receive STAKey Message-1 (Initiator STA MAC Address STAKey)\n"));
-
-				// If support WPA or WPA2, start STAKey hand shake,
-				// If failed hand shake, just tear down peer DLS
-				if (RTMPSendSTAKeyHandShake(pAd, pAddr) != NDIS_STATUS_SUCCESS)
-				{
-					MLME_DLS_REQ_STRUCT	MlmeDlsReq;
-					USHORT				reason = REASON_QOS_CIPHER_NOT_SUPPORT;
-
-					pAd->StaCfg.DLSEntry[i].Valid	= FALSE;
-					pAd->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-					DlsParmFill(pAd, &MlmeDlsReq, &pAd->StaCfg.DLSEntry[i], reason);
-					MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-				}
-				else
-				{
-					DBGPRINT(RT_DEBUG_TRACE,("DLS - Finish STAKey handshake procedure (Peer side)\n"));
-				}
-			}
-			else
-			{
-				// Data frame, update timeout value
-				if (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-				{
-					pAd->StaCfg.DLSEntry[i].CountDownTimer = pAd->StaCfg.DLSEntry[i].TimeOut;
-				}
-			}
-
-			bFindEntry = TRUE;
-		}
-	}
-
-
-	return bSTAKeyFrame;
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Check if the frame can be sent through DLS direct link interface
-
-	Arguments:
-		pAd		Pointer	to adapter
-
-	Return Value:
-		DLS entry index
-
-	Note:
-
-	========================================================================
-*/
-INT	RTMPCheckDLSFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA)
-{
-	INT rval = -1;
-	INT	i;
-
-	if (!pAd->CommonCfg.bDLSCapable)
-		return rval;
-
-	if (!INFRA_ON(pAd))
-		return rval;
-
-	do{
-		// check local dls table entry
-		for (i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				rval = i;
-				break;
-			}
-		}
-
-		// check peer dls table entry
-		for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-		{
-			if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH) &&
-				MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-			{
-				rval = i;
-				break;
-			}
-		}
-	} while (FALSE);
-
-	return rval;
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-VOID RTMPSendDLSTearDownFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pDA)
-{
-	PUCHAR			pOutBuffer = NULL;
-	NDIS_STATUS		NStatus;
-	HEADER_802_11	DlsTearDownHdr;
-	ULONG			FrameLen = 0;
-	USHORT			Reason = REASON_QOS_QSTA_LEAVING_QBSS;
-	UCHAR			Category = CATEGORY_DLS;
-	UCHAR			Action = ACTION_DLS_TEARDOWN;
-	UCHAR			i = 0;
-
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS) ||
-		RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS))
-		return;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Send DLS TearDown Frame \n"));
-
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NStatus != NDIS_STATUS_SUCCESS)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("ASSOC - RTMPSendDLSTearDownFrame() allocate memory failed \n"));
-		return;
-	}
-
-	ActHeaderInit(pAd, &DlsTearDownHdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->CommonCfg.Bssid);
-	MakeOutgoingFrame(pOutBuffer,				&FrameLen,
-					sizeof(HEADER_802_11),		&DlsTearDownHdr,
-					1,							&Category,
-					1,							&Action,
-					6,							pDA,
-					6,							pAd->CurrentAddress,
-					2,							&Reason,
-					END_OF_ARGS);
-
-	MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	// Remove key in local dls table entry
-	for (i = 0; i < MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	// Remove key in peer dls table entry
-	for (i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if (pAd->StaCfg.DLSEntry[i].Valid && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH)
-			&& MAC_ADDR_EQUAL(pDA, pAd->StaCfg.DLSEntry[i].MacAddr))
-		{
-			MacTableDeleteDlsEntry(pAd, pAd->StaCfg.DLSEntry[i].MacTabMatchWCID, pAd->StaCfg.DLSEntry[i].MacAddr);
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Send DLS TearDown Frame and remove key in (i=%d) \n", i));
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-NDIS_STATUS RTMPSendSTAKeyRequest(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA)
-{
-	UCHAR				Header802_3[14];
-	NDIS_STATUS			NStatus;
-	ULONG				FrameLen = 0;
-	EAPOL_PACKET		Packet;
-	UCHAR				Mic[16];
-	UCHAR				digest[80];
-	PUCHAR				pOutBuffer = NULL;
-	PNDIS_PACKET		pNdisPacket;
-	UCHAR				temp[64];
-	UCHAR				DlsPTK[80];
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - RTMPSendSTAKeyRequest() to %02x:%02x:%02x:%02x:%02x:%02x\n", pDA[0], pDA[1], pDA[2], pDA[3], pDA[4], pDA[5]));
-
-	pAd->Sequence ++;
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero message body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer = EAPOL_VER;
-	Packet.ProType    = EAPOLKey;
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE + 6 + MAC_ADDR_LEN;		// data field contain KDE andPeer MAC address
-
-	// STAKey Message is as EAPOL-Key(1,1,0,0,G/0,0,0, MIC, 0,Peer MAC KDE)
-	if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-    {
-        Packet.KeyDesc.Type = WPA1_KEY_DESC;
-    }
-    else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-    {
-        Packet.KeyDesc.Type = WPA2_KEY_DESC;
-    }
-
-	// Key descriptor version
-	Packet.KeyDesc.KeyInfo.KeyDescVer =
-		(((pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled) || (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)) ? (DESC_TYPE_AES) : (DESC_TYPE_TKIP));
-
-	Packet.KeyDesc.KeyInfo.KeyMic	= 1;
-	Packet.KeyDesc.KeyInfo.Secure	= 1;
-	Packet.KeyDesc.KeyInfo.Request	= 1;
-
-	Packet.KeyDesc.KeyDataLen[1]	= 12;
-
-	// use our own OUI to distinguish proprietary with standard.
-	Packet.KeyDesc.KeyData[0]		= 0xDD;
-	Packet.KeyDesc.KeyData[1]		= 0x0A;
-	Packet.KeyDesc.KeyData[2]		= 0x00;
-	Packet.KeyDesc.KeyData[3]		= 0x0C;
-	Packet.KeyDesc.KeyData[4]		= 0x43;
-	Packet.KeyDesc.KeyData[5]		= 0x03;
-	NdisMoveMemory(&Packet.KeyDesc.KeyData[6], pDA, MAC_ADDR_LEN);
-
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.DlsReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Allocate buffer for transmitting message
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-	if (NStatus	!= NDIS_STATUS_SUCCESS)
-		return NStatus;
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		              Packet.Body_Len[1] + 4,    &Packet,
-		              END_OF_ARGS);
-
-	// use proprietary PTK
-	NdisZeroMemory(temp, 64);
-	NdisMoveMemory(temp, "IEEE802.11 WIRELESS ACCESS POINT", 32);
-	WpaCountPTK(pAd, temp, temp, pAd->CommonCfg.Bssid, temp, pAd->CurrentAddress, DlsPTK, LEN_PTK);
-
-	// calculate MIC
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		NdisZeroMemory(digest,	sizeof(digest));
-		HMAC_SHA1(pOutBuffer, FrameLen, DlsPTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		NdisZeroMemory(Mic,	sizeof(Mic));
-		hmac_md5(DlsPTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-	}
-
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-	                  sizeof(Header802_3),	Header802_3,
-		              Packet.Body_Len[1] + 4,	&Packet,
-		              END_OF_ARGS);
-
-	NStatus = RTMPAllocateNdisPacket(pAd, &pNdisPacket, NULL, 0, pOutBuffer, FrameLen);
-	if (NStatus == NDIS_STATUS_SUCCESS)
-	{
-		RTMP_SET_PACKET_WCID(pNdisPacket, BSSID_WCID);
-		STASendPacket(pAd, pNdisPacket);
-		RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSendSTAKeyRequest- Send STAKey request (NStatus=%x, FrameLen=%ld)\n", NStatus, FrameLen));
-
-	return NStatus;
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-NDIS_STATUS RTMPSendSTAKeyHandShake(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA)
-{
-	UCHAR				Header802_3[14];
-	NDIS_STATUS			NStatus;
-	ULONG				FrameLen = 0;
-	EAPOL_PACKET		Packet;
-	UCHAR				Mic[16];
-	UCHAR				digest[80];
-	PUCHAR				pOutBuffer = NULL;
-	PNDIS_PACKET		pNdisPacket;
-	UCHAR				temp[64];
-	UCHAR				DlsPTK[80];			// Due to dirver can not get PTK, use proprietary PTK
-
-	DBGPRINT(RT_DEBUG_TRACE,("DLS - RTMPSendSTAKeyHandShake() to %02x:%02x:%02x:%02x:%02x:%02x\n", pDA[0], pDA[1], pDA[2], pDA[3], pDA[4], pDA[5]));
-
-	pAd->Sequence ++;
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero message body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer = EAPOL_VER;
-	Packet.ProType    = EAPOLKey;
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE + 6 + MAC_ADDR_LEN;		// data field contain KDE and Peer MAC address
-
-	// STAKey Message is as EAPOL-Key(1,1,0,0,G/0,0,0, MIC, 0,Peer MAC KDE)
-	if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK))
-    {
-        Packet.KeyDesc.Type = WPA1_KEY_DESC;
-    }
-    else if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) || (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK))
-    {
-        Packet.KeyDesc.Type = WPA2_KEY_DESC;
-    }
-
-	// Key descriptor version
-	Packet.KeyDesc.KeyInfo.KeyDescVer =
-		(((pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled) || (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)) ? (DESC_TYPE_AES) : (DESC_TYPE_TKIP));
-
-	Packet.KeyDesc.KeyInfo.KeyMic	= 1;
-	Packet.KeyDesc.KeyInfo.Secure	= 1;
-
-	Packet.KeyDesc.KeyDataLen[1]	= 12;
-
-	// use our own OUI to distinguish proprietary with standard.
-	Packet.KeyDesc.KeyData[0]		= 0xDD;
-	Packet.KeyDesc.KeyData[1]		= 0x0A;
-	Packet.KeyDesc.KeyData[2]		= 0x00;
-	Packet.KeyDesc.KeyData[3]		= 0x0C;
-	Packet.KeyDesc.KeyData[4]		= 0x43;
-	Packet.KeyDesc.KeyData[5]		= 0x03;
-	NdisMoveMemory(&Packet.KeyDesc.KeyData[6], pDA, MAC_ADDR_LEN);
-
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.DlsReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Allocate buffer for transmitting message
-	NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-	if (NStatus	!= NDIS_STATUS_SUCCESS)
-		return NStatus;
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		              Packet.Body_Len[1] + 4,    &Packet,
-		              END_OF_ARGS);
-
-	// use proprietary PTK
-	NdisZeroMemory(temp, 64);
-	NdisMoveMemory(temp, "IEEE802.11 WIRELESS ACCESS POINT", 32);
-	WpaCountPTK(pAd, temp, temp, pAd->CommonCfg.Bssid, temp, pAd->CurrentAddress, DlsPTK, LEN_PTK);
-
-	// calculate MIC
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		NdisZeroMemory(digest,	sizeof(digest));
-		HMAC_SHA1(pOutBuffer, FrameLen, DlsPTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		NdisZeroMemory(Mic,	sizeof(Mic));
-		hmac_md5(DlsPTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-		NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-	}
-
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-	                  sizeof(Header802_3),	Header802_3,
-		              Packet.Body_Len[1] + 4,	&Packet,
-		              END_OF_ARGS);
-
-	NStatus = RTMPAllocateNdisPacket(pAd, &pNdisPacket, NULL, 0, pOutBuffer, FrameLen);
-	if (NStatus == NDIS_STATUS_SUCCESS)
-	{
-		RTMP_SET_PACKET_WCID(pNdisPacket, BSSID_WCID);
-		STASendPacket(pAd, pNdisPacket);
-		RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-	}
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPSendSTAKeyHandShake- Send STAKey Message-2 (NStatus=%x, FrameLen=%ld)\n", NStatus, FrameLen));
-
-	return NStatus;
-}
-
-VOID DlsTimeoutAction(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	MLME_DLS_REQ_STRUCT		MlmeDlsReq;
-	USHORT					reason;
-	PRT_802_11_DLS			pDLS = (PRT_802_11_DLS)FunctionContext;
-	PRTMP_ADAPTER			pAd = pDLS->pAd;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("DlsTimeout - Tear down DLS links (%02x:%02x:%02x:%02x:%02x:%02x)\n",
-		pDLS->MacAddr[0], pDLS->MacAddr[1], pDLS->MacAddr[2], pDLS->MacAddr[3], pDLS->MacAddr[4], pDLS->MacAddr[5]));
-
-	if ((pDLS) && (pDLS->Valid))
-	{
-		reason			= REASON_QOS_REQUEST_TIMEOUT;
-		pDLS->Valid		= FALSE;
-		pDLS->Status	= DLS_NONE;
-		DlsParmFill(pAd, &MlmeDlsReq, pDLS, reason);
-		MlmeEnqueue(pAd, DLS_STATE_MACHINE, MT2_MLME_DLS_TEAR_DOWN, sizeof(MLME_DLS_REQ_STRUCT), &MlmeDlsReq);
-		RT28XX_MLME_HANDLER(pAd);
-	}
-}
-
-/*
-================================================================
-Description : because DLS and CLI share the same WCID table in ASIC.
-Mesh entry also insert to pAd->MacTab.content[].  Such is marked as ValidAsDls = TRUE.
-Also fills the pairwise key.
-Because front MAX_AID_BA entries have direct mapping to BAEntry, which is only used as CLI. So we insert Dls
-from index MAX_AID_BA.
-================================================================
-*/
-MAC_TABLE_ENTRY *MacTableInsertDlsEntry(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR	pAddr,
-	IN  UINT	DlsEntryIdx)
-{
-	PMAC_TABLE_ENTRY pEntry = NULL;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("====> MacTableInsertDlsEntry\n"));
-	// if FULL, return
-	if (pAd->MacTab.Size >= MAX_LEN_OF_MAC_TABLE)
-		return NULL;
-
-	do
-	{
-		if((pEntry = DlsEntryTableLookup(pAd, pAddr, TRUE)) != NULL)
-			break;
-
-		// allocate one MAC entry
-		pEntry = MacTableInsertEntry(pAd, pAddr, DlsEntryIdx + MIN_NET_DEVICE_FOR_DLS, TRUE);
-		if (pEntry)
-		{
-			pAd->StaCfg.DLSEntry[DlsEntryIdx].MacTabMatchWCID = pEntry->Aid;
-			pEntry->MatchDlsEntryIdx = DlsEntryIdx;
-			pEntry->AuthMode = pAd->StaCfg.AuthMode;
-			pEntry->WepStatus = pAd->StaCfg.WepStatus;
-
-			DBGPRINT(RT_DEBUG_TRACE, ("MacTableInsertDlsEntry - allocate entry #%d, Total= %d\n",pEntry->Aid, pAd->MacTab.Size));
-
-			// If legacy WEP is used, set pair-wise cipherAlg into WCID attribute table for this entry
-			if ((pEntry->ValidAsDls) && (pEntry->WepStatus == Ndis802_11WEPEnabled))
-			{
-				UCHAR KeyIdx = 0;
-				UCHAR CipherAlg = 0;
-
-				KeyIdx	= pAd->StaCfg.DefaultKeyId;
-
-				CipherAlg 	= pAd->SharedKey[BSS0][KeyIdx].CipherAlg;
-
-				RTMPAddWcidAttributeEntry(pAd,
-											BSS0,
-											pAd->StaCfg.DefaultKeyId,
-											pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-											pEntry);
-			}
-
-			break;
-		}
-	} while(FALSE);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==== MacTableInsertDlsEntry\n"));
-
-	return pEntry;
-}
-
-
-/*
-	==========================================================================
-	Description:
-		Delete all Mesh Entry in pAd->MacTab
-	==========================================================================
- */
-BOOLEAN MacTableDeleteDlsEntry(
-	IN PRTMP_ADAPTER pAd,
-	IN USHORT wcid,
-	IN PUCHAR pAddr)
-{
-	DBGPRINT(RT_DEBUG_TRACE, ("====> MacTableDeleteDlsEntry\n"));
-
-	if (!VALID_WCID(wcid))
-		return FALSE;
-
-	MacTableDeleteEntry(pAd, wcid, pAddr);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==== MacTableDeleteDlsEntry\n"));
-
-	return TRUE;
-}
-
-MAC_TABLE_ENTRY *DlsEntryTableLookup(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount)
-{
-	ULONG HashIdx;
-	MAC_TABLE_ENTRY *pEntry = NULL;
-
-	RTMP_SEM_LOCK(&pAd->MacTabLock);
-	HashIdx = MAC_ADDR_HASH_INDEX(pAddr);
-	pEntry = pAd->MacTab.Hash[HashIdx];
-
-	while (pEntry)
-	{
-		if ((pEntry->ValidAsDls == TRUE)
-			&& MAC_ADDR_EQUAL(pEntry->Addr, pAddr))
-		{
-			if(bResetIdelCount)
-				pEntry->NoDataIdleCount = 0;
-			break;
-		}
-		else
-			pEntry = pEntry->pNext;
-	}
-
-	RTMP_SEM_UNLOCK(&pAd->MacTabLock);
-	return pEntry;
-}
-
-MAC_TABLE_ENTRY *DlsEntryTableLookupByWcid(
-	IN PRTMP_ADAPTER pAd,
-	IN UCHAR	wcid,
-	IN PUCHAR	pAddr,
-	IN BOOLEAN	bResetIdelCount)
-{
-	ULONG DLsIndex;
-	PMAC_TABLE_ENTRY pCurEntry = NULL;
-	PMAC_TABLE_ENTRY pEntry = NULL;
-
-	if (!VALID_WCID(wcid))
-		return NULL;
-
-	RTMP_SEM_LOCK(&pAd->MacTabLock);
-
-	do
-	{
-		pCurEntry = &pAd->MacTab.Content[wcid];
-
-		DLsIndex = 0xff;
-		if ((pCurEntry) && (pCurEntry->ValidAsDls== TRUE))
-		{
-			DLsIndex = pCurEntry->MatchDlsEntryIdx;
-		}
-
-		if (DLsIndex == 0xff)
-			break;
-
-		if (MAC_ADDR_EQUAL(pCurEntry->Addr, pAddr))
-		{
-			if(bResetIdelCount)
-				pCurEntry->NoDataIdleCount = 0;
-			pEntry = pCurEntry;
-			break;
-		}
-	} while(FALSE);
-
-	RTMP_SEM_UNLOCK(&pAd->MacTabLock);
-
-	return pEntry;
-}
-
-INT Set_DlsEntryInfo_Display_Proc(
-	IN PRTMP_ADAPTER pAd,
-	IN PUCHAR arg)
-{
-	INT i;
-
-	printk("\n%-19s%-8s\n", "MAC", "TIMEOUT\n");
-	for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-	{
-		if ((pAd->StaCfg.DLSEntry[i].Valid) && (pAd->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-		{
-			printk("%02x:%02x:%02x:%02x:%02x:%02x  ",
-				pAd->StaCfg.DLSEntry[i].MacAddr[0], pAd->StaCfg.DLSEntry[i].MacAddr[1], pAd->StaCfg.DLSEntry[i].MacAddr[2],
-				pAd->StaCfg.DLSEntry[i].MacAddr[3], pAd->StaCfg.DLSEntry[i].MacAddr[4], pAd->StaCfg.DLSEntry[i].MacAddr[5]);
-			printk("%-8d\n", pAd->StaCfg.DLSEntry[i].TimeOut);
-		}
-	}
-
-	return TRUE;
-}
-
-INT	Set_DlsAddEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-    UCHAR	mac[MAC_ADDR_LEN];
-	USHORT	Timeout;
-	char *token, sepValue[] = ":", DASH = '-';
-	INT i;
-    RT_802_11_DLS	Dls;
-
-    if(strlen(arg) < 19)  //Mac address acceptable format 01:02:03:04:05:06 length 17 plus the "-" and timeout value in decimal format.
-		return FALSE;
-
-	token = strchr(arg, DASH);
-	if ((token != NULL) && (strlen(token)>1))
-	{
-		Timeout = simple_strtol((token+1), 0, 10);
-
-		*token = '\0';
-		for (i = 0, token = rstrtok(arg, &sepValue[0]); token; token = rstrtok(NULL, &sepValue[0]), i++)
-		{
-			if((strlen(token) != 2) || (!isxdigit(*token)) || (!isxdigit(*(token+1))))
-				return FALSE;
-			AtoH(token, (PUCHAR)(&mac[i]), 1);
-		}
-		if(i != 6)
-			return FALSE;
-
-	    printk("\n%02x:%02x:%02x:%02x:%02x:%02x-%d", mac[0], mac[1],
-	           mac[2], mac[3], mac[4], mac[5], (int)Timeout);
-
-		NdisZeroMemory(&Dls, sizeof(RT_802_11_DLS));
-		Dls.TimeOut = Timeout;
-		COPY_MAC_ADDR(Dls.MacAddr, mac);
-		Dls.Valid = 1;
-
-		MlmeEnqueue(pAd,
-					MLME_CNTL_STATE_MACHINE,
-					RT_OID_802_11_SET_DLS_PARAM,
-					sizeof(RT_802_11_DLS),
-					&Dls);
-
-		return TRUE;
-	}
-
-	return FALSE;
-
-}
-
-INT	Set_DlsTearDownEntry_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	UCHAR			macAddr[MAC_ADDR_LEN];
-	CHAR			*value;
-	INT				i;
-	RT_802_11_DLS	Dls;
-
-	if(strlen(arg) != 17)  //Mac address acceptable format 01:02:03:04:05:06 length 17
-		return FALSE;
-
-	for (i=0, value = rstrtok(arg,":"); value; value = rstrtok(NULL,":"))
-	{
-		if((strlen(value) != 2) || (!isxdigit(*value)) || (!isxdigit(*(value+1))) )
-			return FALSE;  //Invalid
-
-		AtoH(value, &macAddr[i++], 2);
-	}
-
-	printk("\n%02x:%02x:%02x:%02x:%02x:%02x", macAddr[0], macAddr[1],
-	           macAddr[2], macAddr[3], macAddr[4], macAddr[5]);
-
-	NdisZeroMemory(&Dls, sizeof(RT_802_11_DLS));
-	COPY_MAC_ADDR(Dls.MacAddr, macAddr);
-	Dls.Valid = 0;
-
-	MlmeEnqueue(pAd,
-				MLME_CNTL_STATE_MACHINE,
-				RT_OID_802_11_SET_DLS_PARAM,
-				sizeof(RT_802_11_DLS),
-				&Dls);
-
-	return TRUE;
-}
-
diff --git a/drivers/staging/rt3070/sta/rtmp_data.c b/drivers/staging/rt3070/sta/rtmp_data.c
index b0f259b..bf09120 100644
--- a/drivers/staging/rt3070/sta/rtmp_data.c
+++ b/drivers/staging/rt3070/sta/rtmp_data.c
@@ -1,2637 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	rtmp_data.c
-
-	Abstract:
-	Data path subroutines
-
-	Revision History:
-	Who 		When			What
-	--------	----------		----------------------------------------------
-	John		      Aug/17/04		major modification for RT2561/2661
-	Jan Lee	      Mar/17/06		major modification for RT2860 New Ring Design
-*/
-#include "../rt_config.h"
-
-
-
-VOID STARxEAPOLFrameIndicate(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-	PRT28XX_RXD_STRUC	pRxD = &(pRxBlk->RxD);
-	PRXWI_STRUC		pRxWI = pRxBlk->pRxWI;
-	UCHAR			*pTmpBuf;
-
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-	if (pAd->StaCfg.WpaSupplicantUP)
-	{
-		// All EAPoL frames have to pass to upper layer (ex. WPA_SUPPLICANT daemon)
-		// TBD : process fragmented EAPol frames
-		{
-			// In 802.1x mode, if the received frame is EAP-SUCCESS packet, turn on the PortSecured variable
-			if ( pAd->StaCfg.IEEE8021X == TRUE &&
-				 (EAP_CODE_SUCCESS == WpaCheckEapCode(pAd, pRxBlk->pData, pRxBlk->DataSize, LENGTH_802_1_H)))
-			{
-				PUCHAR	Key;
-				UCHAR 	CipherAlg;
-				int     idx = 0;
-
-				DBGPRINT_RAW(RT_DEBUG_TRACE, ("Receive EAP-SUCCESS Packet\n"));
-				//pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAd);
-
-                if (pAd->StaCfg.IEEE8021x_required_keys == FALSE)
-                {
-                    idx = pAd->StaCfg.DesireSharedKeyId;
-                    CipherAlg = pAd->StaCfg.DesireSharedKey[idx].CipherAlg;
-					Key = pAd->StaCfg.DesireSharedKey[idx].Key;
-
-                    if (pAd->StaCfg.DesireSharedKey[idx].KeyLen > 0)
-    				{
-#ifdef RT2870
-						union
-						{
-							char buf[sizeof(NDIS_802_11_WEP)+MAX_LEN_OF_KEY- 1];
-							NDIS_802_11_WEP keyinfo;
-						}  WepKey;
-						int len;
-
-
-						NdisZeroMemory(&WepKey, sizeof(WepKey));
-						len =pAd->StaCfg.DesireSharedKey[idx].KeyLen;
-
-						NdisMoveMemory(WepKey.keyinfo.KeyMaterial,
-							pAd->StaCfg.DesireSharedKey[idx].Key,
-							pAd->StaCfg.DesireSharedKey[idx].KeyLen);
-
-						WepKey.keyinfo.KeyIndex = 0x80000000 + idx;
-						WepKey.keyinfo.KeyLength = len;
-						pAd->SharedKey[BSS0][idx].KeyLen =(UCHAR) (len <= 5 ? 5 : 13);
-
-						pAd->IndicateMediaState = NdisMediaStateConnected;
-						pAd->ExtraInfo = GENERAL_LINK_UP;
-						// need to enqueue cmd to thread
-						RTUSBEnqueueCmdFromNdis(pAd, OID_802_11_ADD_WEP, TRUE, &WepKey, sizeof(WepKey.keyinfo) + len - 1);
-#endif // RT2870 //
-						// For Preventing ShardKey Table is cleared by remove key procedure.
-    					pAd->SharedKey[BSS0][idx].CipherAlg = CipherAlg;
-						pAd->SharedKey[BSS0][idx].KeyLen = pAd->StaCfg.DesireSharedKey[idx].KeyLen;
-						NdisMoveMemory(pAd->SharedKey[BSS0][idx].Key,
-									   pAd->StaCfg.DesireSharedKey[idx].Key,
-									   pAd->StaCfg.DesireSharedKey[idx].KeyLen);
-    				}
-				}
-			}
-
-			Indicate_Legacy_Packet(pAd, pRxBlk, FromWhichBSSID);
-			return;
-		}
-	}
-	else
-#endif // WPA_SUPPLICANT_SUPPORT //
-	{
-		// Special DATA frame that has to pass to MLME
-		//	 1. Cisco Aironet frames for CCX2. We need pass it to MLME for special process
-		//	 2. EAPOL handshaking frames when driver supplicant enabled, pass to MLME for special process
-		{
-			pTmpBuf = pRxBlk->pData - LENGTH_802_11;
-			NdisMoveMemory(pTmpBuf, pRxBlk->pHeader, LENGTH_802_11);
-			REPORT_MGMT_FRAME_TO_MLME(pAd, pRxWI->WirelessCliID, pTmpBuf, pRxBlk->DataSize + LENGTH_802_11, pRxWI->RSSI0, pRxWI->RSSI1, pRxWI->RSSI2, pRxD->PlcpSignal);
-			DBGPRINT_RAW(RT_DEBUG_TRACE, ("!!! report EAPOL/AIRONET DATA to MLME (len=%d) !!!\n", pRxBlk->DataSize));
-		}
-	}
-
-	RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-	return;
-
-}
-
-VOID STARxDataFrameAnnounce(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk,
-	IN	UCHAR			FromWhichBSSID)
-{
-
-	// non-EAP frame
-	if (!RTMPCheckWPAframe(pAd, pEntry, pRxBlk->pData, pRxBlk->DataSize, FromWhichBSSID))
-	{
-
-		{
-			// drop all non-EAP DATA frame before
-			// this client's Port-Access-Control is secured
-			if (pRxBlk->pHeader->FC.Wep)
-			{
-				// unsupported cipher suite
-				if (pAd->StaCfg.WepStatus == Ndis802_11EncryptionDisabled)
-				{
-					// release packet
-					RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-					return;
-				}
-			}
-			else
-			{
-				// encryption in-use but receive a non-EAPOL clear text frame, drop it
-				if ((pAd->StaCfg.WepStatus != Ndis802_11EncryptionDisabled) &&
-					(pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-				{
-					// release packet
-					RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-					return;
-				}
-			}
-		}
-		RX_BLK_CLEAR_FLAG(pRxBlk, fRX_EAP);
-		if (!RX_BLK_TEST_FLAG(pRxBlk, fRX_ARALINK))
-		{
-			// Normal legacy, AMPDU or AMSDU
-			CmmRxnonRalinkFrameIndicate(pAd, pRxBlk, FromWhichBSSID);
-
-		}
-		else
-		{
-			// ARALINK
-			CmmRxRalinkFrameIndicate(pAd, pEntry, pRxBlk, FromWhichBSSID);
-		}
-#ifdef QOS_DLS_SUPPORT
-		RX_BLK_CLEAR_FLAG(pRxBlk, fRX_DLS);
-#endif // QOS_DLS_SUPPORT //
-	}
-	else
-	{
-		RX_BLK_SET_FLAG(pRxBlk, fRX_EAP);
-#ifdef DOT11_N_SUPPORT
-		if (RX_BLK_TEST_FLAG(pRxBlk, fRX_AMPDU) && (pAd->CommonCfg.bDisableReordering == 0))
-		{
-			Indicate_AMPDU_Packet(pAd, pRxBlk, FromWhichBSSID);
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			// Determin the destination of the EAP frame
-			//  to WPA state machine or upper layer
-			STARxEAPOLFrameIndicate(pAd, pEntry, pRxBlk, FromWhichBSSID);
-		}
-	}
-}
-
-
-// For TKIP frame, calculate the MIC value
-BOOLEAN STACheckTkipMICValue(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MAC_TABLE_ENTRY	*pEntry,
-	IN	RX_BLK			*pRxBlk)
-{
-	PHEADER_802_11	pHeader = pRxBlk->pHeader;
-	UCHAR			*pData = pRxBlk->pData;
-	USHORT			DataSize = pRxBlk->DataSize;
-	UCHAR			UserPriority = pRxBlk->UserPriority;
-	PCIPHER_KEY		pWpaKey;
-	UCHAR			*pDA, *pSA;
-
-	pWpaKey = &pAd->SharedKey[BSS0][pRxBlk->pRxWI->KeyIndex];
-
-	pDA = pHeader->Addr1;
-	if (RX_BLK_TEST_FLAG(pRxBlk, fRX_INFRA))
-	{
-		pSA = pHeader->Addr3;
-	}
-	else
-	{
-		pSA = pHeader->Addr2;
-	}
-
-	if (RTMPTkipCompareMICValue(pAd,
-								pData,
-								pDA,
-								pSA,
-								pWpaKey->RxMic,
-								UserPriority,
-								DataSize) == FALSE)
-	{
-		DBGPRINT_RAW(RT_DEBUG_ERROR,("Rx MIC Value error 2\n"));
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-		if (pAd->StaCfg.WpaSupplicantUP)
-		{
-			WpaSendMicFailureToWpaSupplicant(pAd, (pWpaKey->Type == PAIRWISEKEY) ? TRUE : FALSE);
-		}
-		else
-#endif // WPA_SUPPLICANT_SUPPORT //
-		{
-			RTMPReportMicError(pAd, pWpaKey);
-		}
-
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE);
-		return FALSE;
-	}
-
-	return TRUE;
-}
-
-
-//
-// All Rx routines use RX_BLK structure to hande rx events
-// It is very important to build pRxBlk attributes
-//  1. pHeader pointer to 802.11 Header
-//  2. pData pointer to payload including LLC (just skip Header)
-//  3. set payload size including LLC to DataSize
-//  4. set some flags with RX_BLK_SET_FLAG()
-//
-VOID STAHandleRxDataFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk)
-{
-	PRT28XX_RXD_STRUC				pRxD = &(pRxBlk->RxD);
-	PRXWI_STRUC						pRxWI = pRxBlk->pRxWI;
-	PHEADER_802_11					pHeader = pRxBlk->pHeader;
-	PNDIS_PACKET					pRxPacket = pRxBlk->pRxPacket;
-	BOOLEAN 						bFragment = FALSE;
-	MAC_TABLE_ENTRY	    			*pEntry = NULL;
-	UCHAR							FromWhichBSSID = BSS0;
-	UCHAR                           UserPriority = 0;
-
-	{
-		// before LINK UP, all DATA frames are rejected
-		if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-		{
-			// release packet
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-			return;
-		}
-
-#ifdef QOS_DLS_SUPPORT
-		//if ((pHeader->FC.FrDs == 0) && (pHeader->FC.ToDs == 0))
-		if (RTMPRcvFrameDLSCheck(pAd, pHeader, pRxWI->MPDUtotalByteCount, pRxD))
-		{
-			return;
-		}
-#endif // QOS_DLS_SUPPORT //
-
-		// Drop not my BSS frames
-		if (pRxD->MyBss == 0)
-		{
-			{
-				// release packet
-				RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-				return;
-			}
-		}
-
-		pAd->RalinkCounters.RxCountSinceLastNULL++;
-		if (pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable && (pHeader->FC.SubType & 0x08))
-		{
-			UCHAR *pData;
-			DBGPRINT(RT_DEBUG_TRACE,("bAPSDCapable\n"));
-
-			// Qos bit 4
-			pData = (PUCHAR)pHeader + LENGTH_802_11;
-			if ((*pData >> 4) & 0x01)
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("RxDone- Rcv EOSP frame, driver may fall into sleep\n"));
-				pAd->CommonCfg.bInServicePeriod = FALSE;
-
-				// Force driver to fall into sleep mode when rcv EOSP frame
-				if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-				{
-					USHORT  TbttNumToNextWakeUp;
-					USHORT  NextDtim = pAd->StaCfg.DtimPeriod;
-					ULONG   Now;
-
-					NdisGetSystemUpTime(&Now);
-					NextDtim -= (USHORT)(Now - pAd->StaCfg.LastBeaconRxTime)/pAd->CommonCfg.BeaconPeriod;
-
-					TbttNumToNextWakeUp = pAd->StaCfg.DefaultListenCount;
-					if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM) && (TbttNumToNextWakeUp > NextDtim))
-						TbttNumToNextWakeUp = NextDtim;
-
-					MlmeSetPsmBit(pAd, PWR_SAVE);
-					// if WMM-APSD is failed, try to disable following line
-					AsicSleepThenAutoWakeup(pAd, TbttNumToNextWakeUp);
-				}
-			}
-
-			if ((pHeader->FC.MoreData) && (pAd->CommonCfg.bInServicePeriod))
-			{
-				DBGPRINT(RT_DEBUG_TRACE,("Sending another trigger frame when More Data bit is set to 1\n"));
-			}
-		}
-
-		// Drop NULL, CF-ACK(no data), CF-POLL(no data), and CF-ACK+CF-POLL(no data) data frame
-		if ((pHeader->FC.SubType & 0x04)) // bit 2 : no DATA
-		{
-			// release packet
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-			return;
-		}
-
-	    // Drop not my BSS frame (we can not only check the MyBss bit in RxD)
-#ifdef QOS_DLS_SUPPORT
-	    if (!pAd->CommonCfg.bDLSCapable)
-	    {
-#endif // QOS_DLS_SUPPORT //
-		if (INFRA_ON(pAd))
-		{
-			// Infrastructure mode, check address 2 for BSSID
-			if (!RTMPEqualMemory(&pHeader->Addr2, &pAd->CommonCfg.Bssid, 6))
-			{
-				// Receive frame not my BSSID
-	            // release packet
-	            RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-				return;
-			}
-		}
-		else	// Ad-Hoc mode or Not associated
-		{
-			// Ad-Hoc mode, check address 3 for BSSID
-			if (!RTMPEqualMemory(&pHeader->Addr3, &pAd->CommonCfg.Bssid, 6))
-			{
-				// Receive frame not my BSSID
-	            // release packet
-	            RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-				return;
-			}
-		}
-#ifdef QOS_DLS_SUPPORT
-	    }
-#endif // QOS_DLS_SUPPORT //
-
-		//
-		// find pEntry
-		//
-		if (pRxWI->WirelessCliID < MAX_LEN_OF_MAC_TABLE)
-		{
-			pEntry = &pAd->MacTab.Content[pRxWI->WirelessCliID];
-		}
-		else
-		{
-			// 1. release packet if infra mode
-			// 2. new a pEntry if ad-hoc mode
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-			return;
-		}
-
-		// infra or ad-hoc
-		if (INFRA_ON(pAd))
-		{
-			RX_BLK_SET_FLAG(pRxBlk, fRX_INFRA);
-#ifdef QOS_DLS_SUPPORT
-			if ((pHeader->FC.FrDs == 0) && (pHeader->FC.ToDs == 0))
-				RX_BLK_SET_FLAG(pRxBlk, fRX_DLS);
-			else
-#endif // QOS_DLS_SUPPORT //
-			ASSERT(pRxWI->WirelessCliID == BSSID_WCID);
-		}
-
-		// check Atheros Client
-		if ((pEntry->bIAmBadAtheros == FALSE) &&  (pRxD->AMPDU == 1) && (pHeader->FC.Retry ))
-		{
-			pEntry->bIAmBadAtheros = TRUE;
-			pAd->CommonCfg.IOTestParm.bCurrentAtheros = TRUE;
-			pAd->CommonCfg.IOTestParm.bLastAtheros = TRUE;
-			if (!STA_AES_ON(pAd))
-			{
-				AsicUpdateProtect(pAd, 8, ALLN_SETPROTECT, TRUE, FALSE);
-			}
-		}
-	}
-
-	pRxBlk->pData = (UCHAR *)pHeader;
-
-	//
-	// update RxBlk->pData, DataSize
-	// 802.11 Header, QOS, HTC, Hw Padding
-	//
-
-	// 1. skip 802.11 HEADER
-	{
-		pRxBlk->pData += LENGTH_802_11;
-		pRxBlk->DataSize -= LENGTH_802_11;
-	}
-
-	// 2. QOS
-	if (pHeader->FC.SubType & 0x08)
-	{
-		RX_BLK_SET_FLAG(pRxBlk, fRX_QOS);
-		UserPriority = *(pRxBlk->pData) & 0x0f;
-		// bit 7 in QoS Control field signals the HT A-MSDU format
-		if ((*pRxBlk->pData) & 0x80)
-		{
-			RX_BLK_SET_FLAG(pRxBlk, fRX_AMSDU);
-		}
-
-		// skip QOS contorl field
-		pRxBlk->pData += 2;
-		pRxBlk->DataSize -=2;
-	}
-	pRxBlk->UserPriority = UserPriority;
-
-	// 3. Order bit: A-Ralink or HTC+
-	if (pHeader->FC.Order)
-	{
-#ifdef AGGREGATION_SUPPORT
-		if ((pRxWI->PHYMODE <= MODE_OFDM) && (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED)))
-		{
-			RX_BLK_SET_FLAG(pRxBlk, fRX_ARALINK);
-		}
-		else
-#endif
-		{
-#ifdef DOT11_N_SUPPORT
-			RX_BLK_SET_FLAG(pRxBlk, fRX_HTC);
-			// skip HTC contorl field
-			pRxBlk->pData += 4;
-			pRxBlk->DataSize -= 4;
-#endif // DOT11_N_SUPPORT //
-		}
-	}
-
-	// 4. skip HW padding
-	if (pRxD->L2PAD)
-	{
-		// just move pData pointer
-		// because DataSize excluding HW padding
-		RX_BLK_SET_FLAG(pRxBlk, fRX_PAD);
-		pRxBlk->pData += 2;
-	}
-
-#ifdef DOT11_N_SUPPORT
-	if (pRxD->BA)
-	{
-		RX_BLK_SET_FLAG(pRxBlk, fRX_AMPDU);
-	}
-#endif // DOT11_N_SUPPORT //
-
-
-	//
-	// Case I  Process Broadcast & Multicast data frame
-	//
-	if (pRxD->Bcast || pRxD->Mcast)
-	{
-		INC_COUNTER64(pAd->WlanCounters.MulticastReceivedFrameCount);
-
-		// Drop Mcast/Bcast frame with fragment bit on
-		if (pHeader->FC.MoreFrag)
-		{
-			// release packet
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-			return;
-		}
-
-		// Filter out Bcast frame which AP relayed for us
-		if (pHeader->FC.FrDs && MAC_ADDR_EQUAL(pHeader->Addr3, pAd->CurrentAddress))
-		{
-			// release packet
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-			return;
-		}
-
-		Indicate_Legacy_Packet(pAd, pRxBlk, FromWhichBSSID);
-		return;
-	}
-	else if (pRxD->U2M)
-	{
-		pAd->LastRxRate = (USHORT)((pRxWI->MCS) + (pRxWI->BW <<7) + (pRxWI->ShortGI <<8)+ (pRxWI->PHYMODE <<14)) ;
-
-
-#ifdef QOS_DLS_SUPPORT
-        if (RX_BLK_TEST_FLAG(pRxBlk, fRX_DLS))
-		{
-			MAC_TABLE_ENTRY *pDlsEntry = NULL;
-
-			pDlsEntry = DlsEntryTableLookupByWcid(pAd, pRxWI->WirelessCliID, pHeader->Addr2, TRUE);
-										                        if(pDlsEntry)
-			Update_Rssi_Sample(pAd, &pDlsEntry->RssiSample, pRxWI);
-		}
-		else
-#endif // QOS_DLS_SUPPORT //
-		if (ADHOC_ON(pAd))
-		{
-			pEntry = MacTableLookup(pAd, pHeader->Addr2);
-			if (pEntry)
-				Update_Rssi_Sample(pAd, &pEntry->RssiSample, pRxWI);
-		}
-
-
-		Update_Rssi_Sample(pAd, &pAd->StaCfg.RssiSample, pRxWI);
-
-		pAd->StaCfg.LastSNR0 = (UCHAR)(pRxWI->SNR0);
-		pAd->StaCfg.LastSNR1 = (UCHAR)(pRxWI->SNR1);
-
-		pAd->RalinkCounters.OneSecRxOkDataCnt++;
-
-
-    	if (!((pHeader->Frag == 0) && (pHeader->FC.MoreFrag == 0)))
-    	{
-    		// re-assemble the fragmented packets
-    		// return complete frame (pRxPacket) or NULL
-    		bFragment = TRUE;
-    		pRxPacket = RTMPDeFragmentDataFrame(pAd, pRxBlk);
-    	}
-
-    	if (pRxPacket)
-    	{
-			pEntry = &pAd->MacTab.Content[pRxWI->WirelessCliID];
-
-    		// process complete frame
-    		if (bFragment && (pRxD->Decrypted) && (pEntry->WepStatus == Ndis802_11Encryption2Enabled))
-    		{
-				// Minus MIC length
-				pRxBlk->DataSize -= 8;
-
-    			// For TKIP frame, calculate the MIC value
-    			if (STACheckTkipMICValue(pAd, pEntry, pRxBlk) == FALSE)
-    			{
-    				return;
-    			}
-    		}
-
-    		STARxDataFrameAnnounce(pAd, pEntry, pRxBlk, FromWhichBSSID);
-			return;
-    	}
-    	else
-    	{
-    		// just return
-    		// because RTMPDeFragmentDataFrame() will release rx packet,
-    		// if packet is fragmented
-    		return;
-    	}
-	}
-
-	ASSERT(0);
-	// release packet
-	RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-}
-
-VOID STAHandleRxMgmtFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk)
-{
-	PRT28XX_RXD_STRUC	pRxD = &(pRxBlk->RxD);
-	PRXWI_STRUC		pRxWI = pRxBlk->pRxWI;
-	PHEADER_802_11	pHeader = pRxBlk->pHeader;
-	PNDIS_PACKET	pRxPacket = pRxBlk->pRxPacket;
-
-	do
-	{
-
-		// We should collect RSSI not only U2M data but also my beacon
-		if ((pHeader->FC.SubType == SUBTYPE_BEACON) && (MAC_ADDR_EQUAL(&pAd->CommonCfg.Bssid, &pHeader->Addr2))
-			&& (pAd->RxAnt.EvaluatePeriod == 0))
-		{
-			Update_Rssi_Sample(pAd, &pAd->StaCfg.RssiSample, pRxWI);
-
-			pAd->StaCfg.LastSNR0 = (UCHAR)(pRxWI->SNR0);
-			pAd->StaCfg.LastSNR1 = (UCHAR)(pRxWI->SNR1);
-		}
-
-#ifdef RT30xx
-		// collect rssi information for antenna diversity
-		if (pAd->NicConfig2.field.AntDiversity)
-		{
-			if ((pRxD->U2M) || ((pHeader->FC.SubType == SUBTYPE_BEACON) && (MAC_ADDR_EQUAL(&pAd->CommonCfg.Bssid, &pHeader->Addr2))))
-			{
-					COLLECT_RX_ANTENNA_AVERAGE_RSSI(pAd, ConvertToRssi(pAd, (UCHAR)pRxWI->RSSI0, RSSI_0), 0); //Note: RSSI2 not used on RT73
-					pAd->StaCfg.NumOfAvgRssiSample ++;
-			}
-		}
-#endif // RT30xx //
-
-		// First check the size, it MUST not exceed the mlme queue size
-		if (pRxWI->MPDUtotalByteCount > MGMT_DMA_BUFFER_SIZE)
-		{
-			DBGPRINT_ERR(("STAHandleRxMgmtFrame: frame too large, size = %d \n", pRxWI->MPDUtotalByteCount));
-			break;
-		}
-
-		REPORT_MGMT_FRAME_TO_MLME(pAd, pRxWI->WirelessCliID, pHeader, pRxWI->MPDUtotalByteCount,
-									pRxWI->RSSI0, pRxWI->RSSI1, pRxWI->RSSI2, pRxD->PlcpSignal);
-	} while (FALSE);
-
-	RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_SUCCESS);
-}
-
-VOID STAHandleRxControlFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	RX_BLK			*pRxBlk)
-{
-#ifdef DOT11_N_SUPPORT
-	PRXWI_STRUC		pRxWI = pRxBlk->pRxWI;
-#endif // DOT11_N_SUPPORT //
-	PHEADER_802_11	pHeader = pRxBlk->pHeader;
-	PNDIS_PACKET	pRxPacket = pRxBlk->pRxPacket;
-
-	switch (pHeader->FC.SubType)
-	{
-		case SUBTYPE_BLOCK_ACK_REQ:
-#ifdef DOT11_N_SUPPORT
-			{
-				CntlEnqueueForRecv(pAd, pRxWI->WirelessCliID, (pRxWI->MPDUtotalByteCount), (PFRAME_BA_REQ)pHeader);
-			}
-			break;
-#endif // DOT11_N_SUPPORT //
-		case SUBTYPE_BLOCK_ACK:
-		case SUBTYPE_ACK:
-		default:
-			break;
-	}
-
-	RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Process RxDone interrupt, running in DPC level
-
-	Arguments:
-		pAd Pointer to our adapter
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-		This routine has to maintain Rx ring read pointer.
-		Need to consider QOS DATA format when converting to 802.3
-	========================================================================
-*/
-BOOLEAN STARxDoneInterruptHandle(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	BOOLEAN			argc)
-{
-	NDIS_STATUS			Status;
-	UINT32			RxProcessed, RxPending;
-	BOOLEAN			bReschedule = FALSE;
-	RT28XX_RXD_STRUC	*pRxD;
-	UCHAR			*pData;
-	PRXWI_STRUC		pRxWI;
-	PNDIS_PACKET	pRxPacket;
-	PHEADER_802_11	pHeader;
-	RX_BLK			RxCell;
-
-	RxProcessed = RxPending = 0;
-
-	// process whole rx ring
-	while (1)
-	{
-
-		if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF |
-								fRTMP_ADAPTER_RESET_IN_PROGRESS |
-								fRTMP_ADAPTER_HALT_IN_PROGRESS |
-								fRTMP_ADAPTER_NIC_NOT_EXIST) ||
-			!RTMP_TEST_FLAG(pAd,fRTMP_ADAPTER_START_UP))
-		{
-			break;
-		}
-
-
-		RxProcessed ++; // test
-
-		// 1. allocate a new data packet into rx ring to replace received packet
-		//    then processing the received packet
-		// 2. the callee must take charge of release of packet
-		// 3. As far as driver is concerned ,
-		//    the rx packet must
-		//      a. be indicated to upper layer or
-		//      b. be released if it is discarded
-		pRxPacket = GetPacketFromRxRing(pAd, &(RxCell.RxD), &bReschedule, &RxPending);
-		if (pRxPacket == NULL)
-		{
-			// no more packet to process
-			break;
-		}
-
-		// get rx ring descriptor
-		pRxD = &(RxCell.RxD);
-		// get rx data buffer
-		pData	= GET_OS_PKT_DATAPTR(pRxPacket);
-		pRxWI	= (PRXWI_STRUC) pData;
-		pHeader = (PHEADER_802_11) (pData+RXWI_SIZE) ;
-
-#ifdef RT_BIG_ENDIAN
-	    RTMPFrameEndianChange(pAd, (PUCHAR)pHeader, DIR_READ, TRUE);
-		RTMPWIEndianChange((PUCHAR)pRxWI, TYPE_RXWI);
-#endif
-
-		// build RxCell
-		RxCell.pRxWI = pRxWI;
-		RxCell.pHeader = pHeader;
-		RxCell.pRxPacket = pRxPacket;
-		RxCell.pData = (UCHAR *) pHeader;
-		RxCell.DataSize = pRxWI->MPDUtotalByteCount;
-		RxCell.Flags = 0;
-
-		// Increase Total receive byte counter after real data received no mater any error or not
-		pAd->RalinkCounters.ReceivedByteCount +=  pRxWI->MPDUtotalByteCount;
-		pAd->RalinkCounters.RxCount ++;
-
-		INC_COUNTER64(pAd->WlanCounters.ReceivedFragmentCount);
-
-		if (pRxWI->MPDUtotalByteCount < 14)
-			Status = NDIS_STATUS_FAILURE;
-
-        if (MONITOR_ON(pAd))
-		{
-            send_monitor_packets(pAd, &RxCell);
-			break;
-		}
-		/* RT2870 invokes STARxDoneInterruptHandle() in rtusb_bulk.c */
-#ifdef RALINK_ATE
-		if (ATE_ON(pAd))
-		{
-			pAd->ate.RxCntPerSec++;
-			ATESampleRssi(pAd, pRxWI);
-#ifdef RALINK_28xx_QA
-			if (pAd->ate.bQARxStart == TRUE)
-			{
-				/* (*pRxD) has been swapped in GetPacketFromRxRing() */
-				ATE_QA_Statistics(pAd, pRxWI, pRxD,	pHeader);
-			}
-#endif // RALINK_28xx_QA //
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_SUCCESS);
-			continue;
-		}
-#endif // RALINK_ATE //
-
-		// Check for all RxD errors
-		Status = RTMPCheckRxError(pAd, pHeader, pRxWI, pRxD);
-
-		// Handle the received frame
-		if (Status == NDIS_STATUS_SUCCESS)
-		{
-			switch (pHeader->FC.Type)
-			{
-				// CASE I, receive a DATA frame
-				case BTYPE_DATA:
-				{
-					// process DATA frame
-					STAHandleRxDataFrame(pAd, &RxCell);
-				}
-				break;
-				// CASE II, receive a MGMT frame
-				case BTYPE_MGMT:
-				{
-					STAHandleRxMgmtFrame(pAd, &RxCell);
-				}
-				break;
-				// CASE III. receive a CNTL frame
-				case BTYPE_CNTL:
-				{
-					STAHandleRxControlFrame(pAd, &RxCell);
-				}
-				break;
-				// discard other type
-				default:
-					RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-					break;
-			}
-		}
-		else
-		{
-			pAd->Counters8023.RxErrors++;
-			// discard this frame
-			RELEASE_NDIS_PACKET(pAd, pRxPacket, NDIS_STATUS_FAILURE);
-		}
-	}
-
-	return bReschedule;
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-	Arguments:
-		pAd 	Pointer to our adapter
-
-	IRQL = DISPATCH_LEVEL
-
-	========================================================================
-*/
-VOID	RTMPHandleTwakeupInterrupt(
-	IN PRTMP_ADAPTER pAd)
-{
-	AsicForceWakeup(pAd, FALSE);
-}
-
-/*
-========================================================================
-Routine Description:
-    Early checking and OS-depened parsing for Tx packet send to our STA driver.
-
-Arguments:
-    NDIS_HANDLE 	MiniportAdapterContext	Pointer refer to the device handle, i.e., the pAd.
-	PPNDIS_PACKET	ppPacketArray			The packet array need to do transmission.
-	UINT			NumberOfPackets			Number of packet in packet array.
-
-Return Value:
-	NONE
-
-Note:
-	This function do early checking and classification for send-out packet.
-	You only can put OS-depened & STA related code in here.
-========================================================================
-*/
-VOID STASendPackets(
-	IN	NDIS_HANDLE		MiniportAdapterContext,
-	IN	PPNDIS_PACKET	ppPacketArray,
-	IN	UINT			NumberOfPackets)
-{
-	UINT			Index;
-	PRTMP_ADAPTER	pAd = (PRTMP_ADAPTER) MiniportAdapterContext;
-	PNDIS_PACKET	pPacket;
-	BOOLEAN			allowToSend = FALSE;
-
-
-	for (Index = 0; Index < NumberOfPackets; Index++)
-	{
-		pPacket = ppPacketArray[Index];
-
-		do
-		{
-
-			if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS) ||
-				RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS) ||
-				RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RADIO_OFF))
-			{
-				// Drop send request since hardware is in reset state
-					break;
-			}
-			else if (!INFRA_ON(pAd) && !ADHOC_ON(pAd))
-			{
-				// Drop send request since there are no physical connection yet
-					break;
-			}
-			else
-			{
-				// Record that orignal packet source is from NDIS layer,so that
-				// later on driver knows how to release this NDIS PACKET
-#ifdef QOS_DLS_SUPPORT
-				MAC_TABLE_ENTRY *pEntry;
-				PUCHAR pSrcBufVA = GET_OS_PKT_DATAPTR(pPacket);
-
-				pEntry = MacTableLookup(pAd, pSrcBufVA);
-				if (pEntry && (pEntry->ValidAsDls == TRUE))
-				{
-					RTMP_SET_PACKET_WCID(pPacket, pEntry->Aid);
-				}
-				else
-#endif // QOS_DLS_SUPPORT //
-				RTMP_SET_PACKET_WCID(pPacket, 0); // this field is useless when in STA mode
-				RTMP_SET_PACKET_SOURCE(pPacket, PKTSRC_NDIS);
-				NDIS_SET_PACKET_STATUS(pPacket, NDIS_STATUS_PENDING);
-				pAd->RalinkCounters.PendingNdisPacketCount++;
-
-				allowToSend = TRUE;
-			}
-		} while(FALSE);
-
-		if (allowToSend == TRUE)
-			STASendPacket(pAd, pPacket);
-		else
-			RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-	}
-
-	// Dequeue outgoing frames from TxSwQueue[] and process it
-	RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
-
-}
-
-
-/*
-========================================================================
-Routine Description:
-	This routine is used to do packet parsing and classification for Tx packet
-	to STA device, and it will en-queue packets to our TxSwQueue depends on AC
-	class.
-
-Arguments:
-	pAd    		Pointer to our adapter
-	pPacket 	Pointer to send packet
-
-Return Value:
-	NDIS_STATUS_SUCCESS			If succes to queue the packet into TxSwQueue.
-	NDIS_STATUS_FAILURE			If failed to do en-queue.
-
-Note:
-	You only can put OS-indepened & STA related code in here.
-========================================================================
-*/
-NDIS_STATUS STASendPacket(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket)
-{
-	PACKET_INFO 	PacketInfo;
-	PUCHAR			pSrcBufVA;
-	UINT			SrcBufLen;
-	UINT			AllowFragSize;
-	UCHAR			NumberOfFrag;
-//	UCHAR			RTSRequired;
-	UCHAR			QueIdx, UserPriority;
-	MAC_TABLE_ENTRY *pEntry = NULL;
-	unsigned int 	IrqFlags;
-	UCHAR			FlgIsIP = 0;
-	UCHAR			Rate;
-
-	// Prepare packet information structure for buffer descriptor
-	// chained within a single NDIS packet.
-	RTMP_QueryPacketInfo(pPacket, &PacketInfo, &pSrcBufVA, &SrcBufLen);
-
-	if (pSrcBufVA == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("STASendPacket --> pSrcBufVA == NULL !!!SrcBufLen=%x\n",SrcBufLen));
-		// Resourece is low, system did not allocate virtual address
-		// return NDIS_STATUS_FAILURE directly to upper layer
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-		return NDIS_STATUS_FAILURE;
-	}
-
-
-	if (SrcBufLen < 14)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("STASendPacket --> Ndis Packet buffer error !!!\n"));
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-		return (NDIS_STATUS_FAILURE);
-	}
-
-	// In HT rate adhoc mode, A-MPDU is often used. So need to lookup BA Table and MAC Entry.
-	// Note multicast packets in adhoc also use BSSID_WCID index.
-	{
-		if(INFRA_ON(pAd))
-		{
-#ifdef QOS_DLS_SUPPORT
-			USHORT	tmpWcid;
-
-			tmpWcid = RTMP_GET_PACKET_WCID(pPacket);
-			if (VALID_WCID(tmpWcid) &&
-				(pAd->MacTab.Content[tmpWcid].ValidAsDls== TRUE))
-			{
-				pEntry = &pAd->MacTab.Content[tmpWcid];
-				Rate = pAd->MacTab.Content[tmpWcid].CurrTxRate;
-			}
-			else
-#endif // QOS_DLS_SUPPORT //
-			{
-			pEntry = &pAd->MacTab.Content[BSSID_WCID];
-			RTMP_SET_PACKET_WCID(pPacket, BSSID_WCID);
-			Rate = pAd->CommonCfg.TxRate;
-		}
-		}
-		else if (ADHOC_ON(pAd))
-		{
-			if (*pSrcBufVA & 0x01)
-			{
-				RTMP_SET_PACKET_WCID(pPacket, MCAST_WCID);
-				pEntry = &pAd->MacTab.Content[MCAST_WCID];
-			}
-			else
-			{
-				pEntry = MacTableLookup(pAd, pSrcBufVA);
-			}
-			Rate = pAd->CommonCfg.TxRate;
-		}
-	}
-
-	if (!pEntry)
-	{
-		DBGPRINT(RT_DEBUG_ERROR,("STASendPacket->Cannot find pEntry(%2x:%2x:%2x:%2x:%2x:%2x) in MacTab!\n", PRINT_MAC(pSrcBufVA)));
-		// Resourece is low, system did not allocate virtual address
-		// return NDIS_STATUS_FAILURE directly to upper layer
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-		return NDIS_STATUS_FAILURE;
-	}
-
-	if (ADHOC_ON(pAd)
-		)
-	{
-		RTMP_SET_PACKET_WCID(pPacket, (UCHAR)pEntry->Aid);
-	}
-
-	//
-	// Check the Ethernet Frame type of this packet, and set the RTMP_SET_PACKET_SPECIFIC flags.
-	//		Here we set the PACKET_SPECIFIC flags(LLC, VLAN, DHCP/ARP, EAPOL).
-	RTMPCheckEtherType(pAd, pPacket);
-
-
-
-	//
-	// WPA 802.1x secured port control - drop all non-802.1x frame before port secured
-	//
-	if (((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-		 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-		 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
-		 (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-#ifdef WPA_SUPPLICANT_SUPPORT
-		  || (pAd->StaCfg.IEEE8021X == TRUE)
-#endif // WPA_SUPPLICANT_SUPPORT //
-#ifdef LEAP_SUPPORT
-		  || (pAd->StaCfg.LeapAuthMode == CISCO_AuthModeLEAP)
-#endif // LEAP_SUPPORT //
-		  )
-		  && ((pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED) || (pAd->StaCfg.MicErrCnt >= 2))
-		  && (RTMP_GET_PACKET_EAPOL(pPacket)== FALSE)
-		  )
-	{
-		DBGPRINT(RT_DEBUG_TRACE,("STASendPacket --> Drop packet before port secured !!!\n"));
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-
-		return (NDIS_STATUS_FAILURE);
-	}
-
-
-	// STEP 1. Decide number of fragments required to deliver this MSDU.
-	//	   The estimation here is not very accurate because difficult to
-	//	   take encryption overhead into consideration here. The result
-	//	   "NumberOfFrag" is then just used to pre-check if enough free
-	//	   TXD are available to hold this MSDU.
-
-
-	if (*pSrcBufVA & 0x01)	// fragmentation not allowed on multicast & broadcast
-		NumberOfFrag = 1;
-	else if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_AGGREGATION_INUSED))
-		NumberOfFrag = 1;	// Aggregation overwhelms fragmentation
-	else if (CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_AMSDU_INUSED))
-		NumberOfFrag = 1;	// Aggregation overwhelms fragmentation
-#ifdef DOT11_N_SUPPORT
-	else if ((pAd->StaCfg.HTPhyMode.field.MODE == MODE_HTMIX) || (pAd->StaCfg.HTPhyMode.field.MODE == MODE_HTGREENFIELD))
-		NumberOfFrag = 1;	// MIMO RATE overwhelms fragmentation
-#endif // DOT11_N_SUPPORT //
-	else
-	{
-		// The calculated "NumberOfFrag" is a rough estimation because of various
-		// encryption/encapsulation overhead not taken into consideration. This number is just
-		// used to make sure enough free TXD are available before fragmentation takes place.
-		// In case the actual required number of fragments of an NDIS packet
-		// excceeds "NumberOfFrag"caculated here and not enough free TXD available, the
-		// last fragment (i.e. last MPDU) will be dropped in RTMPHardTransmit() due to out of
-		// resource, and the NDIS packet will be indicated NDIS_STATUS_FAILURE. This should
-		// rarely happen and the penalty is just like a TX RETRY fail. Affordable.
-
-		AllowFragSize = (pAd->CommonCfg.FragmentThreshold) - LENGTH_802_11 - LENGTH_CRC;
-		NumberOfFrag = ((PacketInfo.TotalPacketLength - LENGTH_802_3 + LENGTH_802_1_H) / AllowFragSize) + 1;
-		// To get accurate number of fragmentation, Minus 1 if the size just match to allowable fragment size
-		if (((PacketInfo.TotalPacketLength - LENGTH_802_3 + LENGTH_802_1_H) % AllowFragSize) == 0)
-		{
-			NumberOfFrag--;
-		}
-	}
-
-	// Save fragment number to Ndis packet reserved field
-	RTMP_SET_PACKET_FRAGMENTS(pPacket, NumberOfFrag);
-
-
-	// STEP 2. Check the requirement of RTS:
-	//	   If multiple fragment required, RTS is required only for the first fragment
-	//	   if the fragment size large than RTS threshold
-	//     For RT28xx, Let ASIC send RTS/CTS
-	RTMP_SET_PACKET_RTS(pPacket, 0);
-	RTMP_SET_PACKET_TXRATE(pPacket, pAd->CommonCfg.TxRate);
-
-	//
-	// STEP 3. Traffic classification. outcome = <UserPriority, QueIdx>
-	//
-	UserPriority = 0;
-	QueIdx		 = QID_AC_BE;
-	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) &&
-		CLIENT_STATUS_TEST_FLAG(pEntry, fCLIENT_STATUS_WMM_CAPABLE))
-	{
-		USHORT Protocol;
-		UCHAR  LlcSnapLen = 0, Byte0, Byte1;
-		do
-		{
-			// get Ethernet protocol field
-			Protocol = (USHORT)((pSrcBufVA[12] << 8) + pSrcBufVA[13]);
-			if (Protocol <= 1500)
-			{
-				// get Ethernet protocol field from LLC/SNAP
-				if (Sniff2BytesFromNdisBuffer(PacketInfo.pFirstBuffer, LENGTH_802_3 + 6, &Byte0, &Byte1) != NDIS_STATUS_SUCCESS)
-					break;
-
-				Protocol = (USHORT)((Byte0 << 8) + Byte1);
-				LlcSnapLen = 8;
-			}
-
-			// always AC_BE for non-IP packet
-			if (Protocol != 0x0800)
-				break;
-
-			// get IP header
-			if (Sniff2BytesFromNdisBuffer(PacketInfo.pFirstBuffer, LENGTH_802_3 + LlcSnapLen, &Byte0, &Byte1) != NDIS_STATUS_SUCCESS)
-				break;
-
-			// return AC_BE if packet is not IPv4
-			if ((Byte0 & 0xf0) != 0x40)
-				break;
-
-			FlgIsIP = 1;
-			UserPriority = (Byte1 & 0xe0) >> 5;
-			QueIdx = MapUserPriorityToAccessCategory[UserPriority];
-
-			// TODO: have to check ACM bit. apply TSPEC if ACM is ON
-			// TODO: downgrade UP & QueIdx before passing ACM
-			if (pAd->CommonCfg.APEdcaParm.bACM[QueIdx])
-			{
-				UserPriority = 0;
-				QueIdx		 = QID_AC_BE;
-			}
-		} while (FALSE);
-	}
-
-	RTMP_SET_PACKET_UP(pPacket, UserPriority);
-
-
-
-	// Make sure SendTxWait queue resource won't be used by other threads
-	RTMP_IRQ_LOCK(&pAd->irq_lock, IrqFlags);
-	if (pAd->TxSwQueue[QueIdx].Number >= MAX_PACKETS_IN_QUEUE)
-	{
-		RTMP_IRQ_UNLOCK(&pAd->irq_lock, IrqFlags);
-#ifdef BLOCK_NET_IF
-		StopNetIfQueue(pAd, QueIdx, pPacket);
-#endif // BLOCK_NET_IF //
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-
-		return NDIS_STATUS_FAILURE;
-	}
-	else
-	{
-		InsertTailQueue(&pAd->TxSwQueue[QueIdx], PACKET_TO_QUEUE_ENTRY(pPacket));
-	}
-	RTMP_IRQ_UNLOCK(&pAd->irq_lock, IrqFlags);
-
-#ifdef DOT11_N_SUPPORT
-    if ((pAd->CommonCfg.BACapability.field.AutoBA == TRUE)&&
-        IS_HT_STA(pEntry))
-	{
-	    //PMAC_TABLE_ENTRY pMacEntry = &pAd->MacTab.Content[BSSID_WCID];
-		if (((pEntry->TXBAbitmap & (1<<UserPriority)) == 0) &&
-            ((pEntry->BADeclineBitmap & (1<<UserPriority)) == 0) &&
-            (pEntry->PortSecured == WPA_802_1X_PORT_SECURED)
-			 // For IOT compatibility, if
-			 // 1. It is Ralink chip or
-			 // 2. It is OPEN or AES mode,
-			 // then BA session can be bulit.
-			 && ((pEntry->ValidAsCLI && pAd->MlmeAux.APRalinkIe != 0x0) ||
-			 	 (pEntry->WepStatus == Ndis802_11WEPDisabled || pEntry->WepStatus == Ndis802_11Encryption3Enabled))
-			)
-		{
-			BAOriSessionSetUp(pAd, pEntry, 0, 0, 10, FALSE);
-		}
-	}
-#endif // DOT11_N_SUPPORT //
-
-	pAd->RalinkCounters.OneSecOsTxCount[QueIdx]++; // TODO: for debug only. to be removed
-	return NDIS_STATUS_SUCCESS;
-}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		This subroutine will scan through releative ring descriptor to find
-		out avaliable free ring descriptor and compare with request size.
-
-	Arguments:
-		pAd Pointer to our adapter
-		QueIdx		Selected TX Ring
-
-	Return Value:
-		NDIS_STATUS_FAILURE 	Not enough free descriptor
-		NDIS_STATUS_SUCCESS 	Enough free descriptor
-
-	IRQL = PASSIVE_LEVEL
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-
-#ifdef RT2870
-/*
-	Actually, this function used to check if the TxHardware Queue still has frame need to send.
-	If no frame need to send, go to sleep, else, still wake up.
-*/
-NDIS_STATUS RTMPFreeTXDRequest(
-	IN		PRTMP_ADAPTER	pAd,
-	IN		UCHAR			QueIdx,
-	IN		UCHAR			NumberRequired,
-	IN		PUCHAR			FreeNumberIs)
-{
-	//ULONG		FreeNumber = 0;
-	NDIS_STATUS 	Status = NDIS_STATUS_FAILURE;
-	unsigned long   IrqFlags;
-	HT_TX_CONTEXT	*pHTTXContext;
-
-	switch (QueIdx)
-	{
-		case QID_AC_BK:
-		case QID_AC_BE:
-		case QID_AC_VI:
-		case QID_AC_VO:
-		case QID_HCCA:
-			{
-				pHTTXContext = &pAd->TxContext[QueIdx];
-				RTMP_IRQ_LOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-				if ((pHTTXContext->CurWritePosition != pHTTXContext->ENextBulkOutPosition) ||
-					(pHTTXContext->IRPPending == TRUE))
-				{
-					Status = NDIS_STATUS_FAILURE;
-				}
-				else
-				{
-					Status = NDIS_STATUS_SUCCESS;
-				}
-				RTMP_IRQ_UNLOCK(&pAd->TxContextQueueLock[QueIdx], IrqFlags);
-			}
-			break;
-
-		case QID_MGMT:
-			if (pAd->MgmtRing.TxSwFreeIdx != MGMT_RING_SIZE)
-				Status = NDIS_STATUS_FAILURE;
-			else
-				Status = NDIS_STATUS_SUCCESS;
-			break;
-
-		default:
-			DBGPRINT(RT_DEBUG_ERROR,("RTMPFreeTXDRequest::Invalid QueIdx(=%d)\n", QueIdx));
-			break;
-	}
-
-	return (Status);
-
-}
-#endif // RT2870 //
-
-
-VOID RTMPSendDisassociationFrame(
-	IN	PRTMP_ADAPTER	pAd)
-{
-}
-
-VOID	RTMPSendNullFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	UCHAR			TxRate,
-	IN	BOOLEAN 		bQosNull)
-{
-	UCHAR	NullFrame[48];
-	ULONG	Length;
-	PHEADER_802_11	pHeader_802_11;
-
-
-#ifdef RALINK_ATE
-	if(ATE_ON(pAd))
-	{
-		return;
-	}
-#endif // RALINK_ATE //
-
-    // WPA 802.1x secured port control
-    if (((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-         (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-         (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
-         (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-#ifdef WPA_SUPPLICANT_SUPPORT
-			  || (pAd->StaCfg.IEEE8021X == TRUE)
-#endif
-        ) &&
-       (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-	{
-		return;
-	}
-
-	NdisZeroMemory(NullFrame, 48);
-	Length = sizeof(HEADER_802_11);
-
-	pHeader_802_11 = (PHEADER_802_11) NullFrame;
-
-	pHeader_802_11->FC.Type = BTYPE_DATA;
-	pHeader_802_11->FC.SubType = SUBTYPE_NULL_FUNC;
-	pHeader_802_11->FC.ToDs = 1;
-	COPY_MAC_ADDR(pHeader_802_11->Addr1, pAd->CommonCfg.Bssid);
-	COPY_MAC_ADDR(pHeader_802_11->Addr2, pAd->CurrentAddress);
-	COPY_MAC_ADDR(pHeader_802_11->Addr3, pAd->CommonCfg.Bssid);
-
-	if (pAd->CommonCfg.bAPSDForcePowerSave)
-	{
-		pHeader_802_11->FC.PwrMgmt = PWR_SAVE;
-	}
-	else
-	{
-		pHeader_802_11->FC.PwrMgmt = (pAd->StaCfg.Psm == PWR_SAVE) ? 1: 0;
-	}
-	pHeader_802_11->Duration = pAd->CommonCfg.Dsifs + RTMPCalcDuration(pAd, TxRate, 14);
-
-	pAd->Sequence++;
-	pHeader_802_11->Sequence = pAd->Sequence;
-
-	// Prepare QosNull function frame
-	if (bQosNull)
-	{
-		pHeader_802_11->FC.SubType = SUBTYPE_QOS_NULL;
-
-		// copy QOS control bytes
-		NullFrame[Length]	=  0;
-		NullFrame[Length+1] =  0;
-		Length += 2;// if pad with 2 bytes for alignment, APSD will fail
-	}
-
-	HAL_KickOutNullFrameTx(pAd, 0, NullFrame, Length);
-
-}
-
-// IRQL = DISPATCH_LEVEL
-VOID	RTMPSendRTSFrame(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pDA,
-	IN	unsigned int	NextMpduSize,
-	IN	UCHAR			TxRate,
-	IN	UCHAR			RTSRate,
-	IN	USHORT			AckDuration,
-	IN	UCHAR			QueIdx,
-	IN	UCHAR			FrameGap)
-{
-}
-
-
-
-// --------------------------------------------------------
-//  FIND ENCRYPT KEY AND DECIDE CIPHER ALGORITHM
-//		Find the WPA key, either Group or Pairwise Key
-//		LEAP + TKIP also use WPA key.
-// --------------------------------------------------------
-// Decide WEP bit and cipher suite to be used. Same cipher suite should be used for whole fragment burst
-// In Cisco CCX 2.0 Leap Authentication
-//		   WepStatus is Ndis802_11Encryption1Enabled but the key will use PairwiseKey
-//		   Instead of the SharedKey, SharedKey Length may be Zero.
-VOID STAFindCipherAlgorithm(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk)
-{
-	NDIS_802_11_ENCRYPTION_STATUS	Cipher;				// To indicate cipher used for this packet
-	UCHAR							CipherAlg = CIPHER_NONE;		// cipher alogrithm
-	UCHAR							KeyIdx = 0xff;
-	PUCHAR							pSrcBufVA;
-	PCIPHER_KEY						pKey = NULL;
-
-	pSrcBufVA = GET_OS_PKT_DATAPTR(pTxBlk->pPacket);
-
-	{
-	    // Select Cipher
-	    if ((*pSrcBufVA & 0x01) && (ADHOC_ON(pAd)))
-	        Cipher = pAd->StaCfg.GroupCipher; // Cipher for Multicast or Broadcast
-	    else
-	        Cipher = pAd->StaCfg.PairCipher; // Cipher for Unicast
-
-		if (RTMP_GET_PACKET_EAPOL(pTxBlk->pPacket))
-		{
-			ASSERT(pAd->SharedKey[BSS0][0].CipherAlg <= CIPHER_CKIP128);
-
-			// 4-way handshaking frame must be clear
-			if (!(TX_BLK_TEST_FLAG(pTxBlk, fTX_bClearEAPFrame)) && (pAd->SharedKey[BSS0][0].CipherAlg) &&
-				(pAd->SharedKey[BSS0][0].KeyLen))
-			{
-				CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-				KeyIdx = 0;
-			}
-		}
-		else if (Cipher == Ndis802_11Encryption1Enabled)
-		{
-#ifdef LEAP_SUPPORT
-			if (pAd->StaCfg.CkipFlag & 0x10) // Cisco CKIP KP is on
-			{
-				if (LEAP_CCKM_ON(pAd))
-				{
-					if (((*pSrcBufVA & 0x01) && (ADHOC_ON(pAd))))
-						KeyIdx = 1;
-					else
-						KeyIdx = 0;
-				}
-				else
-					KeyIdx = pAd->StaCfg.DefaultKeyId;
-			}
-			else if (pAd->StaCfg.CkipFlag & 0x08) // only CKIP CMIC
-				KeyIdx = pAd->StaCfg.DefaultKeyId;
-			else if (LEAP_CCKM_ON(pAd))
-			{
-				if ((*pSrcBufVA & 0x01) && (ADHOC_ON(pAd)))
-					KeyIdx = 1;
-				else
-					KeyIdx = 0;
-			}
-			else	// standard WEP64 or WEP128
-#endif // LEAP_SUPPORT //
-				KeyIdx = pAd->StaCfg.DefaultKeyId;
-		}
-		else if ((Cipher == Ndis802_11Encryption2Enabled) ||
-				 (Cipher == Ndis802_11Encryption3Enabled))
-		{
-			if ((*pSrcBufVA & 0x01) && (ADHOC_ON(pAd))) // multicast
-				KeyIdx = pAd->StaCfg.DefaultKeyId;
-			else if (pAd->SharedKey[BSS0][0].KeyLen)
-				KeyIdx = 0;
-			else
-				KeyIdx = pAd->StaCfg.DefaultKeyId;
-		}
-
-		if (KeyIdx == 0xff)
-			CipherAlg = CIPHER_NONE;
-		else if ((Cipher == Ndis802_11EncryptionDisabled) || (pAd->SharedKey[BSS0][KeyIdx].KeyLen == 0))
-			CipherAlg = CIPHER_NONE;
-#ifdef WPA_SUPPLICANT_SUPPORT
-	    else if ( pAd->StaCfg.WpaSupplicantUP &&
-	             (Cipher == Ndis802_11Encryption1Enabled) &&
-	             (pAd->StaCfg.IEEE8021X == TRUE) &&
-	             (pAd->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-	        CipherAlg = CIPHER_NONE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-		else
-		{
-			//Header_802_11.FC.Wep = 1;
-			CipherAlg = pAd->SharedKey[BSS0][KeyIdx].CipherAlg;
-			pKey = &pAd->SharedKey[BSS0][KeyIdx];
-		}
-	}
-
-	pTxBlk->CipherAlg = CipherAlg;
-	pTxBlk->pKey = pKey;
-}
-
-
-VOID STABuildCommon802_11Header(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  TX_BLK          *pTxBlk)
-{
-
-	HEADER_802_11	*pHeader_802_11;
-#ifdef QOS_DLS_SUPPORT
-	BOOLEAN	bDLSFrame = FALSE;
-	INT	DlsEntryIndex = 0;
-#endif // QOS_DLS_SUPPORT //
-
-	//
-	// MAKE A COMMON 802.11 HEADER
-	//
-
-	// normal wlan header size : 24 octets
-	pTxBlk->MpduHeaderLen = sizeof(HEADER_802_11);
-
-	pHeader_802_11 = (HEADER_802_11 *) &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-
-	NdisZeroMemory(pHeader_802_11, sizeof(HEADER_802_11));
-
-	pHeader_802_11->FC.FrDs = 0;
-	pHeader_802_11->FC.Type = BTYPE_DATA;
-	pHeader_802_11->FC.SubType = ((TX_BLK_TEST_FLAG(pTxBlk, fTX_bWMM)) ? SUBTYPE_QDATA : SUBTYPE_DATA);
-
-#ifdef QOS_DLS_SUPPORT
-	if (INFRA_ON(pAd))
-	{
-		// Check if the frame can be sent through DLS direct link interface
-		// If packet can be sent through DLS, then force aggregation disable. (Hard to determine peer STA's capability)
-		DlsEntryIndex = RTMPCheckDLSFrame(pAd, pTxBlk->pSrcBufHeader);
-		if (DlsEntryIndex >= 0)
-			bDLSFrame = TRUE;
-		else
-			bDLSFrame = FALSE;
-	}
-#endif // QOS_DLS_SUPPORT //
-
-    if (pTxBlk->pMacEntry)
-	{
-		if (TX_BLK_TEST_FLAG(pTxBlk, fTX_bForceNonQoS))
-		{
-			pHeader_802_11->Sequence = pTxBlk->pMacEntry->NonQosDataSeq;
-			pTxBlk->pMacEntry->NonQosDataSeq = (pTxBlk->pMacEntry->NonQosDataSeq+1) & MAXSEQ;
-		}
-		else
-		{
-#ifdef QOS_DLS_SUPPORT
-			if (bDLSFrame)
-			{
-				pHeader_802_11->Sequence = pAd->StaCfg.DLSEntry[DlsEntryIndex].Sequence;
-				pAd->StaCfg.DLSEntry[DlsEntryIndex].Sequence = (pAd->StaCfg.DLSEntry[DlsEntryIndex].Sequence+1) & MAXSEQ;
-			}
-			else
-#endif // QOS_DLS_SUPPORT //
-			{
-    	    pHeader_802_11->Sequence = pTxBlk->pMacEntry->TxSeq[pTxBlk->UserPriority];
-    	    pTxBlk->pMacEntry->TxSeq[pTxBlk->UserPriority] = (pTxBlk->pMacEntry->TxSeq[pTxBlk->UserPriority]+1) & MAXSEQ;
-    	}
-	}
-	}
-	else
-	{
-		pHeader_802_11->Sequence = pAd->Sequence;
-		pAd->Sequence = (pAd->Sequence+1) & MAXSEQ; // next sequence
-	}
-
-	pHeader_802_11->Frag = 0;
-
-	pHeader_802_11->FC.MoreData = TX_BLK_TEST_FLAG(pTxBlk, fTX_bMoreData);
-
-	{
-		if (INFRA_ON(pAd))
-		{
-#ifdef QOS_DLS_SUPPORT
-			if (bDLSFrame)
-			{
-				COPY_MAC_ADDR(pHeader_802_11->Addr1, pTxBlk->pSrcBufHeader);
-				COPY_MAC_ADDR(pHeader_802_11->Addr2, pAd->CurrentAddress);
-				COPY_MAC_ADDR(pHeader_802_11->Addr3, pAd->CommonCfg.Bssid);
-				pHeader_802_11->FC.ToDs = 0;
-			}
-			else
-#endif // QOS_DLS_SUPPORT //
-			{
-			COPY_MAC_ADDR(pHeader_802_11->Addr1, pAd->CommonCfg.Bssid);
-			COPY_MAC_ADDR(pHeader_802_11->Addr2, pAd->CurrentAddress);
-			COPY_MAC_ADDR(pHeader_802_11->Addr3, pTxBlk->pSrcBufHeader);
-			pHeader_802_11->FC.ToDs = 1;
-		}
-		}
-		else if (ADHOC_ON(pAd))
-		{
-			COPY_MAC_ADDR(pHeader_802_11->Addr1, pTxBlk->pSrcBufHeader);
-			COPY_MAC_ADDR(pHeader_802_11->Addr2, pAd->CurrentAddress);
-			COPY_MAC_ADDR(pHeader_802_11->Addr3, pAd->CommonCfg.Bssid);
-			pHeader_802_11->FC.ToDs = 0;
-		}
-	}
-
-	if (pTxBlk->CipherAlg != CIPHER_NONE)
-		pHeader_802_11->FC.Wep = 1;
-
-	// -----------------------------------------------------------------
-	// STEP 2. MAKE A COMMON 802.11 HEADER SHARED BY ENTIRE FRAGMENT BURST. Fill sequence later.
-	// -----------------------------------------------------------------
-	if (pAd->CommonCfg.bAPSDForcePowerSave)
-    	pHeader_802_11->FC.PwrMgmt = PWR_SAVE;
-	else
-    	pHeader_802_11->FC.PwrMgmt = (pAd->StaCfg.Psm == PWR_SAVE);
-}
-
-#ifdef DOT11_N_SUPPORT
-VOID STABuildCache802_11Header(
-	IN RTMP_ADAPTER		*pAd,
-	IN TX_BLK			*pTxBlk,
-	IN UCHAR			*pHeader)
-{
-	MAC_TABLE_ENTRY	*pMacEntry;
-	PHEADER_802_11	pHeader80211;
-
-	pHeader80211 = (PHEADER_802_11)pHeader;
-	pMacEntry = pTxBlk->pMacEntry;
-
-	//
-	// Update the cached 802.11 HEADER
-	//
-
-	// normal wlan header size : 24 octets
-	pTxBlk->MpduHeaderLen = sizeof(HEADER_802_11);
-
-	// More Bit
-	pHeader80211->FC.MoreData = TX_BLK_TEST_FLAG(pTxBlk, fTX_bMoreData);
-
-	// Sequence
-	pHeader80211->Sequence = pMacEntry->TxSeq[pTxBlk->UserPriority];
-    pMacEntry->TxSeq[pTxBlk->UserPriority] = (pMacEntry->TxSeq[pTxBlk->UserPriority]+1) & MAXSEQ;
-
-	{
-		// Check if the frame can be sent through DLS direct link interface
-		// If packet can be sent through DLS, then force aggregation disable. (Hard to determine peer STA's capability)
-#ifdef QOS_DLS_SUPPORT
-		BOOLEAN	bDLSFrame = FALSE;
-		INT	DlsEntryIndex = 0;
-
-		DlsEntryIndex = RTMPCheckDLSFrame(pAd, pTxBlk->pSrcBufHeader);
-		if (DlsEntryIndex >= 0)
-			bDLSFrame = TRUE;
-		else
-			bDLSFrame = FALSE;
-#endif // QOS_DLS_SUPPORT //
-
-		// The addr3 of normal packet send from DS is Dest Mac address.
-#ifdef QOS_DLS_SUPPORT
-		if (bDLSFrame)
-		{
-			COPY_MAC_ADDR(pHeader80211->Addr1, pTxBlk->pSrcBufHeader);
-			COPY_MAC_ADDR(pHeader80211->Addr3, pAd->CommonCfg.Bssid);
-			pHeader80211->FC.ToDs = 0;
-		}
-		else
-#endif // QOS_DLS_SUPPORT //
-		if (ADHOC_ON(pAd))
-			COPY_MAC_ADDR(pHeader80211->Addr3, pAd->CommonCfg.Bssid);
-		else
-			COPY_MAC_ADDR(pHeader80211->Addr3, pTxBlk->pSrcBufHeader);
-	}
-
-	// -----------------------------------------------------------------
-	// STEP 2. MAKE A COMMON 802.11 HEADER SHARED BY ENTIRE FRAGMENT BURST. Fill sequence later.
-	// -----------------------------------------------------------------
-	if (pAd->CommonCfg.bAPSDForcePowerSave)
-    	pHeader80211->FC.PwrMgmt = PWR_SAVE;
-	else
-    	pHeader80211->FC.PwrMgmt = (pAd->StaCfg.Psm == PWR_SAVE);
-}
-#endif // DOT11_N_SUPPORT //
-
-static inline PUCHAR STA_Build_ARalink_Frame_Header(
-	IN RTMP_ADAPTER *pAd,
-	IN TX_BLK		*pTxBlk)
-{
-	PUCHAR			pHeaderBufPtr;
-	HEADER_802_11	*pHeader_802_11;
-	PNDIS_PACKET	pNextPacket;
-	UINT32			nextBufLen;
-	PQUEUE_ENTRY	pQEntry;
-
-	STAFindCipherAlgorithm(pAd, pTxBlk);
-	STABuildCommon802_11Header(pAd, pTxBlk);
-
-
-	pHeaderBufPtr = &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-	pHeader_802_11 = (HEADER_802_11 *) pHeaderBufPtr;
-
-	// steal "order" bit to mark "aggregation"
-	pHeader_802_11->FC.Order = 1;
-
-	// skip common header
-	pHeaderBufPtr += pTxBlk->MpduHeaderLen;
-
-	if (TX_BLK_TEST_FLAG(pTxBlk, fTX_bWMM))
-	{
-		//
-		// build QOS Control bytes
-		//
-		*pHeaderBufPtr = (pTxBlk->UserPriority & 0x0F);
-
-		*(pHeaderBufPtr+1) = 0;
-		pHeaderBufPtr +=2;
-		pTxBlk->MpduHeaderLen += 2;
-	}
-
-	// padding at front of LLC header. LLC header should at 4-bytes aligment.
-	pTxBlk->HdrPadLen = (ULONG)pHeaderBufPtr;
-	pHeaderBufPtr = (PCHAR)ROUND_UP(pHeaderBufPtr, 4);
-	pTxBlk->HdrPadLen = (ULONG)(pHeaderBufPtr - pTxBlk->HdrPadLen);
-
-	// For RA Aggregation,
-	// put the 2nd MSDU length(extra 2-byte field) after QOS_CONTROL in little endian format
-	pQEntry = pTxBlk->TxPacketList.Head;
-	pNextPacket = QUEUE_ENTRY_TO_PKT(pQEntry);
-	nextBufLen = GET_OS_PKT_LEN(pNextPacket);
-	if (RTMP_GET_PACKET_VLAN(pNextPacket))
-		nextBufLen -= LENGTH_802_1Q;
-
-	*pHeaderBufPtr = (UCHAR)nextBufLen & 0xff;
-	*(pHeaderBufPtr+1) = (UCHAR)(nextBufLen >> 8);
-
-	pHeaderBufPtr += 2;
-	pTxBlk->MpduHeaderLen += 2;
-
-	return pHeaderBufPtr;
-
-}
-
-#ifdef DOT11_N_SUPPORT
-static inline PUCHAR STA_Build_AMSDU_Frame_Header(
-	IN RTMP_ADAPTER *pAd,
-	IN TX_BLK		*pTxBlk)
-{
-	PUCHAR			pHeaderBufPtr;//, pSaveBufPtr;
-	HEADER_802_11	*pHeader_802_11;
-
-
-	STAFindCipherAlgorithm(pAd, pTxBlk);
-	STABuildCommon802_11Header(pAd, pTxBlk);
-
-	pHeaderBufPtr = &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-	pHeader_802_11 = (HEADER_802_11 *) pHeaderBufPtr;
-
-	// skip common header
-	pHeaderBufPtr += pTxBlk->MpduHeaderLen;
-
-	//
-	// build QOS Control bytes
-	//
-	*pHeaderBufPtr = (pTxBlk->UserPriority & 0x0F);
-
-	//
-	// A-MSDU packet
-	//
-	*pHeaderBufPtr |= 0x80;
-
-	*(pHeaderBufPtr+1) = 0;
-	pHeaderBufPtr +=2;
-	pTxBlk->MpduHeaderLen += 2;
-
-	//pSaveBufPtr = pHeaderBufPtr;
-
-	//
-	// padding at front of LLC header
-	// LLC header should locate at 4-octets aligment
-	//
-	// @@@ MpduHeaderLen excluding padding @@@
-	//
-	pTxBlk->HdrPadLen = (ULONG)pHeaderBufPtr;
-	pHeaderBufPtr = (PCHAR) ROUND_UP(pHeaderBufPtr, 4);
-	pTxBlk->HdrPadLen = (ULONG)(pHeaderBufPtr - pTxBlk->HdrPadLen);
-
-	return pHeaderBufPtr;
-
-}
-
-
-VOID STA_AMPDU_Frame_Tx(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk)
-{
-	HEADER_802_11	*pHeader_802_11;
-	PUCHAR			pHeaderBufPtr;
-	USHORT			FreeNumber;
-	MAC_TABLE_ENTRY	*pMacEntry;
-	BOOLEAN			bVLANPkt;
-	PQUEUE_ENTRY	pQEntry;
-
-	ASSERT(pTxBlk);
-
-	while(pTxBlk->TxPacketList.Head)
-	{
-		pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-		pTxBlk->pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-		if ( RTMP_FillTxBlkInfo(pAd, pTxBlk) != TRUE)
-		{
-			RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-			continue;
-		}
-
-		bVLANPkt = (RTMP_GET_PACKET_VLAN(pTxBlk->pPacket) ? TRUE : FALSE);
-
-		pMacEntry = pTxBlk->pMacEntry;
-		if (pMacEntry->isCached)
-		{
-			// NOTE: Please make sure the size of pMacEntry->CachedBuf[] is smaller than pTxBlk->HeaderBuf[]!!!!
-			NdisMoveMemory((PUCHAR)&pTxBlk->HeaderBuf[TXINFO_SIZE], (PUCHAR)&pMacEntry->CachedBuf[0], TXWI_SIZE + sizeof(HEADER_802_11));
-			pHeaderBufPtr = (PUCHAR)(&pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE]);
-			STABuildCache802_11Header(pAd, pTxBlk, pHeaderBufPtr);
-		}
-		else
-		{
-			STAFindCipherAlgorithm(pAd, pTxBlk);
-			STABuildCommon802_11Header(pAd, pTxBlk);
-
-			pHeaderBufPtr = &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-		}
-
-
-		pHeader_802_11 = (HEADER_802_11 *) pHeaderBufPtr;
-
-		// skip common header
-		pHeaderBufPtr += pTxBlk->MpduHeaderLen;
-
-		//
-		// build QOS Control bytes
-		//
-		*pHeaderBufPtr = (pTxBlk->UserPriority & 0x0F);
-		*(pHeaderBufPtr+1) = 0;
-		pHeaderBufPtr +=2;
-		pTxBlk->MpduHeaderLen += 2;
-
-		//
-		// build HTC+
-		// HTC control filed following QoS field
-		//
-		if ((pAd->CommonCfg.bRdg == TRUE) && CLIENT_STATUS_TEST_FLAG(pTxBlk->pMacEntry, fCLIENT_STATUS_RDG_CAPABLE))
-		{
-			if (pMacEntry->isCached == FALSE)
-			{
-				// mark HTC bit
-				pHeader_802_11->FC.Order = 1;
-
-				NdisZeroMemory(pHeaderBufPtr, 4);
-				*(pHeaderBufPtr+3) |= 0x80;
-			}
-			pHeaderBufPtr += 4;
-			pTxBlk->MpduHeaderLen += 4;
-		}
-
-		//pTxBlk->MpduHeaderLen = pHeaderBufPtr - pTxBlk->HeaderBuf - TXWI_SIZE - TXINFO_SIZE;
-		ASSERT(pTxBlk->MpduHeaderLen >= 24);
-
-		// skip 802.3 header
-		pTxBlk->pSrcBufData = pTxBlk->pSrcBufHeader + LENGTH_802_3;
-		pTxBlk->SrcBufLen  -= LENGTH_802_3;
-
-		// skip vlan tag
-		if (bVLANPkt)
-		{
-			pTxBlk->pSrcBufData	+= LENGTH_802_1Q;
-			pTxBlk->SrcBufLen	-= LENGTH_802_1Q;
-		}
-
-		//
-		// padding at front of LLC header
-		// LLC header should locate at 4-octets aligment
-		//
-		// @@@ MpduHeaderLen excluding padding @@@
-		//
-		pTxBlk->HdrPadLen = (ULONG)pHeaderBufPtr;
-		pHeaderBufPtr = (PCHAR) ROUND_UP(pHeaderBufPtr, 4);
-		pTxBlk->HdrPadLen = (ULONG)(pHeaderBufPtr - pTxBlk->HdrPadLen);
-
-		{
-
-			//
-			// Insert LLC-SNAP encapsulation - 8 octets
-			//
-			EXTRA_LLCSNAP_ENCAP_FROM_PKT_OFFSET(pTxBlk->pSrcBufData-2, pTxBlk->pExtraLlcSnapEncap);
-			if (pTxBlk->pExtraLlcSnapEncap)
-			{
-				NdisMoveMemory(pHeaderBufPtr, pTxBlk->pExtraLlcSnapEncap, 6);
-				pHeaderBufPtr += 6;
-				// get 2 octets (TypeofLen)
-				NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufData-2, 2);
-				pHeaderBufPtr += 2;
-				pTxBlk->MpduHeaderLen += LENGTH_802_1_H;
-			}
-
-		}
-
-		if (pMacEntry->isCached)
-		{
-            RTMPWriteTxWI_Cache(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-		}
-		else
-		{
-			RTMPWriteTxWI_Data(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-
-			NdisZeroMemory((PUCHAR)(&pMacEntry->CachedBuf[0]), sizeof(pMacEntry->CachedBuf));
-			NdisMoveMemory((PUCHAR)(&pMacEntry->CachedBuf[0]), (PUCHAR)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), (pHeaderBufPtr - (PUCHAR)(&pTxBlk->HeaderBuf[TXINFO_SIZE])));
-			pMacEntry->isCached = TRUE;
-		}
-
-		// calculate Transmitted AMPDU count and ByteCount
-		{
-			pAd->RalinkCounters.TransmittedMPDUsInAMPDUCount.u.LowPart ++;
-			pAd->RalinkCounters.TransmittedOctetsInAMPDUCount.QuadPart += pTxBlk->SrcBufLen;
-		}
-
-		//FreeNumber = GET_TXRING_FREENO(pAd, QueIdx);
-
-		HAL_WriteTxResource(pAd, pTxBlk, TRUE, &FreeNumber);
-
-		//
-		// Kick out Tx
-		//
-		HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
-
-		pAd->RalinkCounters.KickTxCount++;
-		pAd->RalinkCounters.OneSecTxDoneCount++;
-	}
-
-}
-
-
-VOID STA_AMSDU_Frame_Tx(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk)
-{
-	PUCHAR			pHeaderBufPtr;
-	USHORT			FreeNumber;
-	USHORT			subFramePayloadLen = 0;	// AMSDU Subframe length without AMSDU-Header / Padding.
-	USHORT			totalMPDUSize=0;
-	UCHAR			*subFrameHeader;
-	UCHAR			padding = 0;
-	USHORT			FirstTx = 0, LastTxIdx = 0;
-	BOOLEAN			bVLANPkt;
-	int 			frameNum = 0;
-	PQUEUE_ENTRY	pQEntry;
-
-
-	ASSERT(pTxBlk);
-
-	ASSERT((pTxBlk->TxPacketList.Number > 1));
-
-	while(pTxBlk->TxPacketList.Head)
-	{
-		pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-		pTxBlk->pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-		if (RTMP_FillTxBlkInfo(pAd, pTxBlk) != TRUE)
-		{
-			RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-			continue;
-		}
-
-		bVLANPkt = (RTMP_GET_PACKET_VLAN(pTxBlk->pPacket) ? TRUE : FALSE);
-
-		// skip 802.3 header
-		pTxBlk->pSrcBufData = pTxBlk->pSrcBufHeader + LENGTH_802_3;
-		pTxBlk->SrcBufLen  -= LENGTH_802_3;
-
-		// skip vlan tag
-		if (bVLANPkt)
-		{
-			pTxBlk->pSrcBufData	+= LENGTH_802_1Q;
-			pTxBlk->SrcBufLen	-= LENGTH_802_1Q;
-		}
-
-		if (frameNum == 0)
-		{
-			pHeaderBufPtr = STA_Build_AMSDU_Frame_Header(pAd, pTxBlk);
-
-			// NOTE: TxWI->MPDUtotalByteCount will be updated after final frame was handled.
-			RTMPWriteTxWI_Data(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-		}
-		else
-		{
-			pHeaderBufPtr = &pTxBlk->HeaderBuf[0];
-			padding = ROUND_UP(LENGTH_AMSDU_SUBFRAMEHEAD + subFramePayloadLen, 4) - (LENGTH_AMSDU_SUBFRAMEHEAD + subFramePayloadLen);
-			NdisZeroMemory(pHeaderBufPtr, padding + LENGTH_AMSDU_SUBFRAMEHEAD);
-			pHeaderBufPtr += padding;
-			pTxBlk->MpduHeaderLen = padding;
-		}
-
-		//
-		// A-MSDU subframe
-		//   DA(6)+SA(6)+Length(2) + LLC/SNAP Encap
-		//
-		subFrameHeader = pHeaderBufPtr;
-		subFramePayloadLen = pTxBlk->SrcBufLen;
-
-		NdisMoveMemory(subFrameHeader, pTxBlk->pSrcBufHeader, 12);
-
-
-		pHeaderBufPtr += LENGTH_AMSDU_SUBFRAMEHEAD;
-		pTxBlk->MpduHeaderLen += LENGTH_AMSDU_SUBFRAMEHEAD;
-
-
-		//
-		// Insert LLC-SNAP encapsulation - 8 octets
-		//
-		EXTRA_LLCSNAP_ENCAP_FROM_PKT_OFFSET(pTxBlk->pSrcBufData-2, pTxBlk->pExtraLlcSnapEncap);
-
-		subFramePayloadLen = pTxBlk->SrcBufLen;
-
-		if (pTxBlk->pExtraLlcSnapEncap)
-		{
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pExtraLlcSnapEncap, 6);
-			pHeaderBufPtr += 6;
-			// get 2 octets (TypeofLen)
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufData-2, 2);
-			pHeaderBufPtr += 2;
-			pTxBlk->MpduHeaderLen += LENGTH_802_1_H;
-			subFramePayloadLen += LENGTH_802_1_H;
-		}
-
-		// update subFrame Length field
-		subFrameHeader[12] = (subFramePayloadLen & 0xFF00) >> 8;
-		subFrameHeader[13] = subFramePayloadLen & 0xFF;
-
-		totalMPDUSize += pTxBlk->MpduHeaderLen + pTxBlk->SrcBufLen;
-
-		if (frameNum ==0)
-			FirstTx = HAL_WriteMultiTxResource(pAd, pTxBlk, frameNum, &FreeNumber);
-		else
-			LastTxIdx = HAL_WriteMultiTxResource(pAd, pTxBlk, frameNum, &FreeNumber);
-
-		frameNum++;
-
-		pAd->RalinkCounters.KickTxCount++;
-		pAd->RalinkCounters.OneSecTxDoneCount++;
-
-		// calculate Transmitted AMSDU Count and ByteCount
-		{
-			pAd->RalinkCounters.TransmittedAMSDUCount.u.LowPart ++;
-			pAd->RalinkCounters.TransmittedOctetsInAMSDU.QuadPart += totalMPDUSize;
-		}
-
-	}
-
-	HAL_FinalWriteTxResource(pAd, pTxBlk, totalMPDUSize, FirstTx);
-	HAL_LastTxIdx(pAd, pTxBlk->QueIdx, LastTxIdx);
-
-	//
-	// Kick out Tx
-	//
-	HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
-}
-#endif // DOT11_N_SUPPORT //
-
-VOID STA_Legacy_Frame_Tx(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk)
-{
-	HEADER_802_11	*pHeader_802_11;
-	PUCHAR			pHeaderBufPtr;
-	USHORT			FreeNumber;
-	BOOLEAN			bVLANPkt;
-	PQUEUE_ENTRY	pQEntry;
-
-	ASSERT(pTxBlk);
-
-
-	pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-	pTxBlk->pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-	if (RTMP_FillTxBlkInfo(pAd, pTxBlk) != TRUE)
-	{
-		RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-	if (pTxBlk->TxFrameType == TX_MCAST_FRAME)
-	{
-		INC_COUNTER64(pAd->WlanCounters.MulticastTransmittedFrameCount);
-	}
-
-	if (RTMP_GET_PACKET_RTS(pTxBlk->pPacket))
-		TX_BLK_SET_FLAG(pTxBlk, fTX_bRtsRequired);
-	else
-		TX_BLK_CLEAR_FLAG(pTxBlk, fTX_bRtsRequired);
-
-	bVLANPkt = (RTMP_GET_PACKET_VLAN(pTxBlk->pPacket) ? TRUE : FALSE);
-
-	if (pTxBlk->TxRate < pAd->CommonCfg.MinTxRate)
-		pTxBlk->TxRate = pAd->CommonCfg.MinTxRate;
-
-	STAFindCipherAlgorithm(pAd, pTxBlk);
-	STABuildCommon802_11Header(pAd, pTxBlk);
-
-
-	// skip 802.3 header
-	pTxBlk->pSrcBufData = pTxBlk->pSrcBufHeader + LENGTH_802_3;
-	pTxBlk->SrcBufLen  -= LENGTH_802_3;
-
-	// skip vlan tag
-	if (bVLANPkt)
-	{
-		pTxBlk->pSrcBufData	+= LENGTH_802_1Q;
-		pTxBlk->SrcBufLen	-= LENGTH_802_1Q;
-	}
-
-	pHeaderBufPtr = &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-	pHeader_802_11 = (HEADER_802_11 *) pHeaderBufPtr;
-
-	// skip common header
-	pHeaderBufPtr += pTxBlk->MpduHeaderLen;
-
-	if (TX_BLK_TEST_FLAG(pTxBlk, fTX_bWMM))
-	{
-		//
-		// build QOS Control bytes
-		//
-		*pHeaderBufPtr = (pTxBlk->UserPriority & 0x0F);
-		*(pHeaderBufPtr+1) = 0;
-		pHeaderBufPtr +=2;
-		pTxBlk->MpduHeaderLen += 2;
-	}
-
-	// The remaining content of MPDU header should locate at 4-octets aligment
-	pTxBlk->HdrPadLen = (ULONG)pHeaderBufPtr;
-	pHeaderBufPtr = (PCHAR) ROUND_UP(pHeaderBufPtr, 4);
-	pTxBlk->HdrPadLen = (ULONG)(pHeaderBufPtr - pTxBlk->HdrPadLen);
-
-	{
-
-		//
-		// Insert LLC-SNAP encapsulation - 8 octets
-		//
-		//
-   		// if original Ethernet frame contains no LLC/SNAP,
-		// then an extra LLC/SNAP encap is required
-		//
-		EXTRA_LLCSNAP_ENCAP_FROM_PKT_START(pTxBlk->pSrcBufHeader, pTxBlk->pExtraLlcSnapEncap);
-		if (pTxBlk->pExtraLlcSnapEncap)
-		{
-			UCHAR vlan_size;
-
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pExtraLlcSnapEncap, 6);
-			pHeaderBufPtr += 6;
-			// skip vlan tag
-			vlan_size =  (bVLANPkt) ? LENGTH_802_1Q : 0;
-			// get 2 octets (TypeofLen)
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufHeader+12+vlan_size, 2);
-			pHeaderBufPtr += 2;
-			pTxBlk->MpduHeaderLen += LENGTH_802_1_H;
-		}
-
-	}
-
-	//
-	// prepare for TXWI
-	// use Wcid as Key Index
-	//
-
-	RTMPWriteTxWI_Data(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-
-	//FreeNumber = GET_TXRING_FREENO(pAd, QueIdx);
-
-	HAL_WriteTxResource(pAd, pTxBlk, TRUE, &FreeNumber);
-
-	pAd->RalinkCounters.KickTxCount++;
-	pAd->RalinkCounters.OneSecTxDoneCount++;
-
-	//
-	// Kick out Tx
-	//
-	HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
-}
-
-
-VOID STA_ARalink_Frame_Tx(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	TX_BLK			*pTxBlk)
-{
-	PUCHAR			pHeaderBufPtr;
-	USHORT			FreeNumber;
-	USHORT			totalMPDUSize=0;
-	USHORT			FirstTx, LastTxIdx;
-	int 			frameNum = 0;
-	BOOLEAN			bVLANPkt;
-	PQUEUE_ENTRY	pQEntry;
-
-
-	ASSERT(pTxBlk);
-
-	ASSERT((pTxBlk->TxPacketList.Number== 2));
-
-
-	FirstTx = LastTxIdx = 0;  // Is it ok init they as 0?
-	while(pTxBlk->TxPacketList.Head)
-	{
-		pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-		pTxBlk->pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-
-		if (RTMP_FillTxBlkInfo(pAd, pTxBlk) != TRUE)
-		{
-			RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-			continue;
-		}
-
-		bVLANPkt = (RTMP_GET_PACKET_VLAN(pTxBlk->pPacket) ? TRUE : FALSE);
-
-		// skip 802.3 header
-		pTxBlk->pSrcBufData = pTxBlk->pSrcBufHeader + LENGTH_802_3;
-		pTxBlk->SrcBufLen  -= LENGTH_802_3;
-
-		// skip vlan tag
-		if (bVLANPkt)
-		{
-			pTxBlk->pSrcBufData	+= LENGTH_802_1Q;
-			pTxBlk->SrcBufLen	-= LENGTH_802_1Q;
-		}
-
-		if (frameNum == 0)
-		{	// For first frame, we need to create the 802.11 header + padding(optional) + RA-AGG-LEN + SNAP Header
-
-			pHeaderBufPtr = STA_Build_ARalink_Frame_Header(pAd, pTxBlk);
-
-			// It's ok write the TxWI here, because the TxWI->MPDUtotalByteCount
-			//	will be updated after final frame was handled.
-			RTMPWriteTxWI_Data(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-
-
-			//
-			// Insert LLC-SNAP encapsulation - 8 octets
-			//
-			EXTRA_LLCSNAP_ENCAP_FROM_PKT_OFFSET(pTxBlk->pSrcBufData-2, pTxBlk->pExtraLlcSnapEncap);
-
-			if (pTxBlk->pExtraLlcSnapEncap)
-			{
-				NdisMoveMemory(pHeaderBufPtr, pTxBlk->pExtraLlcSnapEncap, 6);
-				pHeaderBufPtr += 6;
-				// get 2 octets (TypeofLen)
-				NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufData-2, 2);
-				pHeaderBufPtr += 2;
-				pTxBlk->MpduHeaderLen += LENGTH_802_1_H;
-			}
-		}
-		else
-		{	// For second aggregated frame, we need create the 802.3 header to headerBuf, because PCI will copy it to SDPtr0.
-
-			pHeaderBufPtr = &pTxBlk->HeaderBuf[0];
-			pTxBlk->MpduHeaderLen = 0;
-
-			// A-Ralink sub-sequent frame header is the same as 802.3 header.
-			//   DA(6)+SA(6)+FrameType(2)
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufHeader, 12);
-			pHeaderBufPtr += 12;
-			// get 2 octets (TypeofLen)
-			NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufData-2, 2);
-			pHeaderBufPtr += 2;
-			pTxBlk->MpduHeaderLen = LENGTH_ARALINK_SUBFRAMEHEAD;
-		}
-
-		totalMPDUSize += pTxBlk->MpduHeaderLen + pTxBlk->SrcBufLen;
-
-		//FreeNumber = GET_TXRING_FREENO(pAd, QueIdx);
-		if (frameNum ==0)
-			FirstTx = HAL_WriteMultiTxResource(pAd, pTxBlk, frameNum, &FreeNumber);
-		else
-			LastTxIdx = HAL_WriteMultiTxResource(pAd, pTxBlk, frameNum, &FreeNumber);
-
-		frameNum++;
-
-		pAd->RalinkCounters.OneSecTxAggregationCount++;
-		pAd->RalinkCounters.KickTxCount++;
-		pAd->RalinkCounters.OneSecTxDoneCount++;
-
-	}
-
-	HAL_FinalWriteTxResource(pAd, pTxBlk, totalMPDUSize, FirstTx);
-	HAL_LastTxIdx(pAd, pTxBlk->QueIdx, LastTxIdx);
-
-	//
-	// Kick out Tx
-	//
-	HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
-
-}
-
-
-VOID STA_Fragment_Frame_Tx(
-	IN RTMP_ADAPTER *pAd,
-	IN TX_BLK		*pTxBlk)
-{
-	HEADER_802_11	*pHeader_802_11;
-	PUCHAR			pHeaderBufPtr;
-	USHORT			FreeNumber;
-	UCHAR 			fragNum = 0;
-	PACKET_INFO		PacketInfo;
-	USHORT			EncryptionOverhead = 0;
-	UINT32			FreeMpduSize, SrcRemainingBytes;
-	USHORT			AckDuration;
-	UINT 			NextMpduSize;
-	BOOLEAN			bVLANPkt;
-	PQUEUE_ENTRY	pQEntry;
-
-
-	ASSERT(pTxBlk);
-
-	pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-	pTxBlk->pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-	if (RTMP_FillTxBlkInfo(pAd, pTxBlk) != TRUE)
-	{
-		RELEASE_NDIS_PACKET(pAd, pTxBlk->pPacket, NDIS_STATUS_FAILURE);
-		return;
-	}
-
-	ASSERT(TX_BLK_TEST_FLAG(pTxBlk, fTX_bAllowFrag));
-	bVLANPkt = (RTMP_GET_PACKET_VLAN(pTxBlk->pPacket) ? TRUE : FALSE);
-
-	STAFindCipherAlgorithm(pAd, pTxBlk);
-	STABuildCommon802_11Header(pAd, pTxBlk);
-
-	if (pTxBlk->CipherAlg == CIPHER_TKIP)
-	{
-		pTxBlk->pPacket = duplicate_pkt_with_TKIP_MIC(pAd, pTxBlk->pPacket);
-		if (pTxBlk->pPacket == NULL)
-			return;
-		RTMP_QueryPacketInfo(pTxBlk->pPacket, &PacketInfo, &pTxBlk->pSrcBufHeader, &pTxBlk->SrcBufLen);
-	}
-
-	// skip 802.3 header
-	pTxBlk->pSrcBufData = pTxBlk->pSrcBufHeader + LENGTH_802_3;
-	pTxBlk->SrcBufLen  -= LENGTH_802_3;
-
-
-	// skip vlan tag
-	if (bVLANPkt)
-	{
-		pTxBlk->pSrcBufData	+= LENGTH_802_1Q;
-		pTxBlk->SrcBufLen	-= LENGTH_802_1Q;
-	}
-
-	pHeaderBufPtr = &pTxBlk->HeaderBuf[TXINFO_SIZE + TXWI_SIZE];
-	pHeader_802_11 = (HEADER_802_11 *)pHeaderBufPtr;
-
-
-	// skip common header
-	pHeaderBufPtr += pTxBlk->MpduHeaderLen;
-
-	if (TX_BLK_TEST_FLAG(pTxBlk, fTX_bWMM))
-	{
-		//
-		// build QOS Control bytes
-		//
-		*pHeaderBufPtr = (pTxBlk->UserPriority & 0x0F);
-
-		*(pHeaderBufPtr+1) = 0;
-		pHeaderBufPtr +=2;
-		pTxBlk->MpduHeaderLen += 2;
-	}
-
-	//
-	// padding at front of LLC header
-	// LLC header should locate at 4-octets aligment
-	//
-	pTxBlk->HdrPadLen = (ULONG)pHeaderBufPtr;
-	pHeaderBufPtr = (PCHAR) ROUND_UP(pHeaderBufPtr, 4);
-	pTxBlk->HdrPadLen = (ULONG)(pHeaderBufPtr - pTxBlk->HdrPadLen);
-
-
-
-	//
-	// Insert LLC-SNAP encapsulation - 8 octets
-	//
-	//
-   	// if original Ethernet frame contains no LLC/SNAP,
-	// then an extra LLC/SNAP encap is required
-	//
-	EXTRA_LLCSNAP_ENCAP_FROM_PKT_START(pTxBlk->pSrcBufHeader, pTxBlk->pExtraLlcSnapEncap);
-	if (pTxBlk->pExtraLlcSnapEncap)
-	{
-		UCHAR vlan_size;
-
-		NdisMoveMemory(pHeaderBufPtr, pTxBlk->pExtraLlcSnapEncap, 6);
-		pHeaderBufPtr += 6;
-		// skip vlan tag
-		vlan_size =  (bVLANPkt) ? LENGTH_802_1Q : 0;
-		// get 2 octets (TypeofLen)
-		NdisMoveMemory(pHeaderBufPtr, pTxBlk->pSrcBufHeader+12+vlan_size, 2);
-		pHeaderBufPtr += 2;
-		pTxBlk->MpduHeaderLen += LENGTH_802_1_H;
-	}
-
-
-	// If TKIP is used and fragmentation is required. Driver has to
-	//	append TKIP MIC at tail of the scatter buffer
-	//	MAC ASIC will only perform IV/EIV/ICV insertion but no TKIP MIC
-	if (pTxBlk->CipherAlg == CIPHER_TKIP)
-	{
-
-		// NOTE: DON'T refer the skb->len directly after following copy. Becasue the length is not adjust
-		//			to correct lenght, refer to pTxBlk->SrcBufLen for the packet length in following progress.
-		NdisMoveMemory(pTxBlk->pSrcBufData + pTxBlk->SrcBufLen, &pAd->PrivateInfo.Tx.MIC[0], 8);
-		//skb_put((RTPKT_TO_OSPKT(pTxBlk->pPacket))->tail, 8);
-		pTxBlk->SrcBufLen += 8;
-		pTxBlk->TotalFrameLen += 8;
-		pTxBlk->CipherAlg = CIPHER_TKIP_NO_MIC;
-	}
-
-	//
-	// calcuate the overhead bytes that encryption algorithm may add. This
-	// affects the calculate of "duration" field
-	//
-	if ((pTxBlk->CipherAlg == CIPHER_WEP64) || (pTxBlk->CipherAlg == CIPHER_WEP128))
-		EncryptionOverhead = 8; //WEP: IV[4] + ICV[4];
-	else if (pTxBlk->CipherAlg == CIPHER_TKIP_NO_MIC)
-		EncryptionOverhead = 12;//TKIP: IV[4] + EIV[4] + ICV[4], MIC will be added to TotalPacketLength
-	else if (pTxBlk->CipherAlg == CIPHER_TKIP)
-		EncryptionOverhead = 20;//TKIP: IV[4] + EIV[4] + ICV[4] + MIC[8]
-	else if (pTxBlk->CipherAlg == CIPHER_AES)
-		EncryptionOverhead = 16;	// AES: IV[4] + EIV[4] + MIC[8]
-	else
-		EncryptionOverhead = 0;
-
-	// decide how much time an ACK/CTS frame will consume in the air
-	AckDuration = RTMPCalcDuration(pAd, pAd->CommonCfg.ExpectedACKRate[pTxBlk->TxRate], 14);
-
-	// Init the total payload length of this frame.
-	SrcRemainingBytes = pTxBlk->SrcBufLen;
-
-	pTxBlk->TotalFragNum = 0xff;
-
-	do {
-
-		FreeMpduSize = pAd->CommonCfg.FragmentThreshold - LENGTH_CRC;
-
-		FreeMpduSize -= pTxBlk->MpduHeaderLen;
-
-		if (SrcRemainingBytes <= FreeMpduSize)
-		{	// this is the last or only fragment
-
-			pTxBlk->SrcBufLen = SrcRemainingBytes;
-
-			pHeader_802_11->FC.MoreFrag = 0;
-			pHeader_802_11->Duration = pAd->CommonCfg.Dsifs + AckDuration;
-
-			// Indicate the lower layer that this's the last fragment.
-			pTxBlk->TotalFragNum = fragNum;
-		}
-		else
-		{	// more fragment is required
-
-			pTxBlk->SrcBufLen = FreeMpduSize;
-
-			NextMpduSize = min(((UINT)SrcRemainingBytes - pTxBlk->SrcBufLen), ((UINT)pAd->CommonCfg.FragmentThreshold));
-			pHeader_802_11->FC.MoreFrag = 1;
-			pHeader_802_11->Duration = (3 * pAd->CommonCfg.Dsifs) + (2 * AckDuration) + RTMPCalcDuration(pAd, pTxBlk->TxRate, NextMpduSize + EncryptionOverhead);
-		}
-
-		if (fragNum == 0)
-			pTxBlk->FrameGap = IFS_HTTXOP;
-		else
-			pTxBlk->FrameGap = IFS_SIFS;
-
-		RTMPWriteTxWI_Data(pAd, (PTXWI_STRUC)(&pTxBlk->HeaderBuf[TXINFO_SIZE]), pTxBlk);
-
-		HAL_WriteFragTxResource(pAd, pTxBlk, fragNum, &FreeNumber);
-
-		pAd->RalinkCounters.KickTxCount++;
-		pAd->RalinkCounters.OneSecTxDoneCount++;
-
-		// Update the frame number, remaining size of the NDIS packet payload.
-
-		// space for 802.11 header.
-		if (fragNum == 0 && pTxBlk->pExtraLlcSnapEncap)
-			pTxBlk->MpduHeaderLen -= LENGTH_802_1_H;
-
-		fragNum++;
-		SrcRemainingBytes -= pTxBlk->SrcBufLen;
-		pTxBlk->pSrcBufData += pTxBlk->SrcBufLen;
-
-		pHeader_802_11->Frag++;	 // increase Frag #
-
-	}while(SrcRemainingBytes > 0);
-
-	//
-	// Kick out Tx
-	//
-	HAL_KickOutTx(pAd, pTxBlk, pTxBlk->QueIdx);
-}
-
-
-#define RELEASE_FRAMES_OF_TXBLK(_pAd, _pTxBlk, _pQEntry, _Status) 										\
-		while(_pTxBlk->TxPacketList.Head)														\
-		{																						\
-			_pQEntry = RemoveHeadQueue(&_pTxBlk->TxPacketList);									\
-			RELEASE_NDIS_PACKET(_pAd, QUEUE_ENTRY_TO_PACKET(_pQEntry), _Status);	\
-		}
-
-
-/*
-	========================================================================
-
-	Routine Description:
-		Copy frame from waiting queue into relative ring buffer and set
-	appropriate ASIC register to kick hardware encryption before really
-	sent out to air.
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		PNDIS_PACKET	Pointer to outgoing Ndis frame
-		NumberOfFrag	Number of fragment required
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-NDIS_STATUS STAHardTransmit(
-	IN PRTMP_ADAPTER	pAd,
-	IN TX_BLK 			*pTxBlk,
-	IN	UCHAR			QueIdx)
-{
-	NDIS_PACKET		*pPacket;
-	PQUEUE_ENTRY	pQEntry;
-
-	// ---------------------------------------------
-	// STEP 0. DO SANITY CHECK AND SOME EARLY PREPARATION.
-	// ---------------------------------------------
-	//
-	ASSERT(pTxBlk->TxPacketList.Number);
-	if (pTxBlk->TxPacketList.Head == NULL)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("pTxBlk->TotalFrameNum == %ld!\n", pTxBlk->TxPacketList.Number));
-		return NDIS_STATUS_FAILURE;
-	}
-
-	pPacket = QUEUE_ENTRY_TO_PACKET(pTxBlk->TxPacketList.Head);
-
-	// ------------------------------------------------------------------
-	// STEP 1. WAKE UP PHY
-	//		outgoing frame always wakeup PHY to prevent frame lost and
-	//		turn off PSM bit to improve performance
-	// ------------------------------------------------------------------
-	// not to change PSM bit, just send this frame out?
-	if ((pAd->StaCfg.Psm == PWR_SAVE) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-	{
-	    DBGPRINT_RAW(RT_DEBUG_TRACE, ("AsicForceWakeup At HardTx\n"));
-		AsicForceWakeup(pAd, TRUE);
-	}
-
-	// It should not change PSM bit, when APSD turn on.
-	if ((!(pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable) && (pAd->CommonCfg.bAPSDForcePowerSave == FALSE))
-		|| (RTMP_GET_PACKET_EAPOL(pTxBlk->pPacket))
-		|| (RTMP_GET_PACKET_WAI(pTxBlk->pPacket)))
-	{
-		if ((pAd->StaCfg.Psm == PWR_SAVE) &&
-            (pAd->StaCfg.WindowsPowerMode == Ndis802_11PowerModeFast_PSP))
-			MlmeSetPsmBit(pAd, PWR_ACTIVE);
-	}
-
-	switch (pTxBlk->TxFrameType)
-	{
-#ifdef DOT11_N_SUPPORT
-		case TX_AMPDU_FRAME:
-				STA_AMPDU_Frame_Tx(pAd, pTxBlk);
-			break;
-		case TX_AMSDU_FRAME:
-				STA_AMSDU_Frame_Tx(pAd, pTxBlk);
-			break;
-#endif // DOT11_N_SUPPORT //
-		case TX_LEGACY_FRAME:
-				STA_Legacy_Frame_Tx(pAd, pTxBlk);
-			break;
-		case TX_MCAST_FRAME:
-				STA_Legacy_Frame_Tx(pAd, pTxBlk);
-			break;
-		case TX_RALINK_FRAME:
-				STA_ARalink_Frame_Tx(pAd, pTxBlk);
-			break;
-		case TX_FRAG_FRAME:
-				STA_Fragment_Frame_Tx(pAd, pTxBlk);
-			break;
-		default:
-			{
-				// It should not happened!
-				DBGPRINT(RT_DEBUG_ERROR, ("Send a pacekt was not classified!! It should not happen!\n"));
-				while(pTxBlk->TxPacketList.Number)
-				{
-					pQEntry = RemoveHeadQueue(&pTxBlk->TxPacketList);
-					pPacket = QUEUE_ENTRY_TO_PACKET(pQEntry);
-					if (pPacket)
-						RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-				}
-			}
-			break;
-	}
-
-	return (NDIS_STATUS_SUCCESS);
-
-}
-
-ULONG  HashBytesPolynomial(UCHAR *value, unsigned int len)
-{
-   unsigned char *word = value;
-   unsigned int ret = 0;
-   unsigned int i;
-
-   for(i=0; i < len; i++)
-   {
-	  int mod = i % 32;
-	  ret ^=(unsigned int) (word[i]) << mod;
-	  ret ^=(unsigned int) (word[i]) >> (32 - mod);
-   }
-   return ret;
-}
-
-VOID Sta_Announce_or_Forward_802_3_Packet(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PNDIS_PACKET	pPacket,
-	IN	UCHAR			FromWhichBSSID)
-{
-	if (TRUE
-		)
-	{
-		announce_802_3_packet(pAd, pPacket);
-	}
-	else
-	{
-		// release packet
-		RELEASE_NDIS_PACKET(pAd, pPacket, NDIS_STATUS_FAILURE);
-	}
-}
-
+#include "../../rt2870/sta/rtmp_data.c"
diff --git a/drivers/staging/rt3070/sta/sanity.c b/drivers/staging/rt3070/sta/sanity.c
index 2398724..b495477 100644
--- a/drivers/staging/rt3070/sta/sanity.c
+++ b/drivers/staging/rt3070/sta/sanity.c
@@ -1,420 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	sanity.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang  2004-09-01      add WMM support
-*/
-#include "../rt_config.h"
-
-extern UCHAR	CISCO_OUI[];
-
-extern UCHAR	WPA_OUI[];
-extern UCHAR	RSN_OUI[];
-extern UCHAR	WME_INFO_ELEM[];
-extern UCHAR	WME_PARM_ELEM[];
-extern UCHAR	Ccx2QosInfo[];
-extern UCHAR	RALINK_OUI[];
-extern UCHAR	BROADCOM_OUI[];
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
- */
-BOOLEAN MlmeStartReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT CHAR Ssid[],
-    OUT UCHAR *pSsidLen)
-{
-    MLME_START_REQ_STRUCT *Info;
-
-    Info = (MLME_START_REQ_STRUCT *)(Msg);
-
-    if (Info->SsidLen > MAX_LEN_OF_SSID)
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("MlmeStartReqSanity fail - wrong SSID length\n"));
-        return FALSE;
-    }
-
-    *pSsidLen = Info->SsidLen;
-    NdisMoveMemory(Ssid, Info->Ssid, *pSsidLen);
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-    IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerAssocRspSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *pMsg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT USHORT *pCapabilityInfo,
-    OUT USHORT *pStatus,
-    OUT USHORT *pAid,
-    OUT UCHAR SupRate[],
-    OUT UCHAR *pSupRateLen,
-    OUT UCHAR ExtRate[],
-    OUT UCHAR *pExtRateLen,
-    OUT HT_CAPABILITY_IE		*pHtCapability,
-    OUT ADD_HT_INFO_IE		*pAddHtInfo,	// AP might use this additional ht info IE
-    OUT UCHAR			*pHtCapabilityLen,
-    OUT UCHAR			*pAddHtInfoLen,
-    OUT UCHAR			*pNewExtChannelOffset,
-    OUT PEDCA_PARM pEdcaParm,
-    OUT UCHAR *pCkipFlag)
-{
-    CHAR          IeType, *Ptr;
-    PFRAME_802_11 pFrame = (PFRAME_802_11)pMsg;
-    PEID_STRUCT   pEid;
-    ULONG         Length = 0;
-
-	*pNewExtChannelOffset = 0xff;
-	*pHtCapabilityLen = 0;
-	*pAddHtInfoLen = 0;
-    COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-    Ptr = pFrame->Octet;
-    Length += LENGTH_802_11;
-
-    NdisMoveMemory(pCapabilityInfo, &pFrame->Octet[0], 2);
-    Length += 2;
-    NdisMoveMemory(pStatus,         &pFrame->Octet[2], 2);
-    Length += 2;
-    *pCkipFlag = 0;
-    *pExtRateLen = 0;
-    pEdcaParm->bValid = FALSE;
-
-    if (*pStatus != MLME_SUCCESS)
-        return TRUE;
-
-    NdisMoveMemory(pAid, &pFrame->Octet[4], 2);
-    Length += 2;
-
-    // Aid already swaped byte order in RTMPFrameEndianChange() for big endian platform
-    *pAid = (*pAid) & 0x3fff; // AID is low 14-bit
-
-    // -- get supported rates from payload and advance the pointer
-    IeType = pFrame->Octet[6];
-    *pSupRateLen = pFrame->Octet[7];
-    if ((IeType != IE_SUPP_RATES) || (*pSupRateLen > MAX_LEN_OF_SUPPORTED_RATES))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("PeerAssocRspSanity fail - wrong SupportedRates IE\n"));
-        return FALSE;
-    }
-    else
-        NdisMoveMemory(SupRate, &pFrame->Octet[8], *pSupRateLen);
-
-    Length = Length + 2 + *pSupRateLen;
-
-    // many AP implement proprietary IEs in non-standard order, we'd better
-    // tolerate mis-ordered IEs to get best compatibility
-    pEid = (PEID_STRUCT) &pFrame->Octet[8 + (*pSupRateLen)];
-
-    // get variable fields from payload and advance the pointer
-    while ((Length + 2 + pEid->Len) <= MsgLen)
-    {
-        switch (pEid->Eid)
-        {
-            case IE_EXT_SUPP_RATES:
-                if (pEid->Len <= MAX_LEN_OF_SUPPORTED_RATES)
-                {
-                    NdisMoveMemory(ExtRate, pEid->Octet, pEid->Len);
-                    *pExtRateLen = pEid->Len;
-                }
-                break;
-
-             case IE_HT_CAP:
-            case IE_HT_CAP2:
-			if (pEid->Len >= SIZE_HT_CAP_IE)  //Note: allow extension.!!
-			{
-				NdisMoveMemory(pHtCapability, pEid->Octet, SIZE_HT_CAP_IE);
-
-				*(USHORT *)(&pHtCapability->HtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->HtCapInfo));
-				*(USHORT *)(&pHtCapability->ExtHtCapInfo) = cpu2le16(*(USHORT *)(&pHtCapability->ExtHtCapInfo));
-
-				*pHtCapabilityLen = SIZE_HT_CAP_IE;
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerAssocRspSanity - wrong IE_HT_CAP. \n"));
-			}
-
-		break;
-#ifdef DOT11_N_SUPPORT
-            case IE_ADD_HT:
-            case IE_ADD_HT2:
-			if (pEid->Len >= sizeof(ADD_HT_INFO_IE))
-			{
-				// This IE allows extension, but we can ignore extra bytes beyond our knowledge , so only
-				// copy first sizeof(ADD_HT_INFO_IE)
-				NdisMoveMemory(pAddHtInfo, pEid->Octet, sizeof(ADD_HT_INFO_IE));
-
-				*(USHORT *)(&pAddHtInfo->AddHtInfo2) = cpu2le16(*(USHORT *)(&pAddHtInfo->AddHtInfo2));
-				*(USHORT *)(&pAddHtInfo->AddHtInfo3) = cpu2le16(*(USHORT *)(&pAddHtInfo->AddHtInfo3));
-
-				*pAddHtInfoLen = SIZE_ADD_HT_INFO_IE;
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerAssocRspSanity - wrong IE_ADD_HT. \n"));
-			}
-
-		break;
-            case IE_SECONDARY_CH_OFFSET:
-			if (pEid->Len == 1)
-			{
-				*pNewExtChannelOffset = pEid->Octet[0];
-			}
-			else
-			{
-				DBGPRINT(RT_DEBUG_WARN, ("PeerAssocRspSanity - wrong IE_SECONDARY_CH_OFFSET. \n"));
-			}
-#endif // DOT11_N_SUPPORT //
-		break;
-            case IE_AIRONET_CKIP:
-                // 0. Check Aironet IE length, it must be larger or equal to 28
-                //    Cisco's AP VxWork version(will not be supported) used this IE length as 28
-                //    Cisco's AP IOS version used this IE length as 30
-                if (pEid->Len < (CKIP_NEGOTIATION_LENGTH - 2))
-                break;
-
-                // 1. Copy CKIP flag byte to buffer for process
-                *pCkipFlag = *(pEid->Octet + 8);
-                break;
-
-            case IE_AIRONET_IPADDRESS:
-                if (pEid->Len != 0x0A)
-                break;
-
-                // Get Cisco Aironet IP information
-                if (NdisEqualMemory(pEid->Octet, CISCO_OUI, 3) == 1)
-                    NdisMoveMemory(pAd->StaCfg.AironetIPAddress, pEid->Octet + 4, 4);
-                break;
-
-            // CCX2, WMM use the same IE value
-            // case IE_CCX_V2:
-            case IE_VENDOR_SPECIFIC:
-                // handle WME PARAMTER ELEMENT
-                if (NdisEqualMemory(pEid->Octet, WME_PARM_ELEM, 6) && (pEid->Len == 24))
-                {
-                    PUCHAR ptr;
-                    int i;
-
-                    // parsing EDCA parameters
-                    pEdcaParm->bValid          = TRUE;
-                    pEdcaParm->bQAck           = FALSE; // pEid->Octet[0] & 0x10;
-                    pEdcaParm->bQueueRequest   = FALSE; // pEid->Octet[0] & 0x20;
-                    pEdcaParm->bTxopRequest    = FALSE; // pEid->Octet[0] & 0x40;
-                    //pEdcaParm->bMoreDataAck    = FALSE; // pEid->Octet[0] & 0x80;
-                    pEdcaParm->EdcaUpdateCount = pEid->Octet[6] & 0x0f;
-                    pEdcaParm->bAPSDCapable    = (pEid->Octet[6] & 0x80) ? 1 : 0;
-                    ptr = &pEid->Octet[8];
-                    for (i=0; i<4; i++)
-                    {
-                        UCHAR aci = (*ptr & 0x60) >> 5; // b5~6 is AC INDEX
-                        pEdcaParm->bACM[aci]  = (((*ptr) & 0x10) == 0x10);   // b5 is ACM
-                        pEdcaParm->Aifsn[aci] = (*ptr) & 0x0f;               // b0~3 is AIFSN
-                        pEdcaParm->Cwmin[aci] = *(ptr+1) & 0x0f;             // b0~4 is Cwmin
-                        pEdcaParm->Cwmax[aci] = *(ptr+1) >> 4;               // b5~8 is Cwmax
-                        pEdcaParm->Txop[aci]  = *(ptr+2) + 256 * (*(ptr+3)); // in unit of 32-us
-                        ptr += 4; // point to next AC
-                    }
-                }
-
-                // handle CCX IE
-                else
-                {
-                    // 0. Check the size and CCX admin control
-                    if (pAd->StaCfg.CCXControl.field.Enable == 0)
-                        break;
-                    if (pEid->Len != 5)
-                        break;
-
-                    // Turn CCX2 if matched
-                    if (NdisEqualMemory(pEid->Octet, Ccx2IeInfo, 5) == 1)
-                        pAd->StaCfg.CCXEnable = TRUE;
-                    break;
-                }
-                break;
-
-            default:
-                DBGPRINT(RT_DEBUG_TRACE, ("PeerAssocRspSanity - ignore unrecognized EID = %d\n", pEid->Eid));
-                break;
-        }
-
-        Length = Length + 2 + pEid->Len;
-        pEid = (PEID_STRUCT)((UCHAR*)pEid + 2 + pEid->Len);
-    }
-
-    // Force CCX2 enable to TRUE for those AP didn't replay CCX v2 IE, we still force it to be on
-    if (pAd->StaCfg.CCXControl.field.Enable == 1)
-        pAd->StaCfg.CCXEnable = TRUE;
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        MLME message sanity check
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN PeerProbeReqSanity(
-    IN PRTMP_ADAPTER pAd,
-    IN VOID *Msg,
-    IN ULONG MsgLen,
-    OUT PUCHAR pAddr2,
-    OUT CHAR Ssid[],
-    OUT UCHAR *pSsidLen)
-{
-    UCHAR         Idx;
-    UCHAR	      RateLen;
-    CHAR          IeType;
-    PFRAME_802_11 pFrame = (PFRAME_802_11)Msg;
-
-    COPY_MAC_ADDR(pAddr2, pFrame->Hdr.Addr2);
-
-    if ((pFrame->Octet[0] != IE_SSID) || (pFrame->Octet[1] > MAX_LEN_OF_SSID))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("PeerProbeReqSanity fail - wrong SSID IE(Type=%d,Len=%d)\n",pFrame->Octet[0],pFrame->Octet[1]));
-        return FALSE;
-    }
-
-    *pSsidLen = pFrame->Octet[1];
-    NdisMoveMemory(Ssid, &pFrame->Octet[2], *pSsidLen);
-
-    Idx = *pSsidLen + 2;
-
-    // -- get supported rates from payload and advance the pointer
-    IeType = pFrame->Octet[Idx];
-    RateLen = pFrame->Octet[Idx + 1];
-    if (IeType != IE_SUPP_RATES)
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("PeerProbeReqSanity fail - wrong SupportRates IE(Type=%d,Len=%d)\n",pFrame->Octet[Idx],pFrame->Octet[Idx+1]));
-        return FALSE;
-    }
-    else
-    {
-        if ((pAd->CommonCfg.PhyMode == PHY_11G) && (RateLen < 8))
-            return (FALSE);
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-
-	IRQL = DISPATCH_LEVEL
-
-    ==========================================================================
- */
-BOOLEAN GetTimBit(
-    IN CHAR *Ptr,
-    IN USHORT Aid,
-    OUT UCHAR *TimLen,
-    OUT UCHAR *BcastFlag,
-    OUT UCHAR *DtimCount,
-    OUT UCHAR *DtimPeriod,
-    OUT UCHAR *MessageToMe)
-{
-    UCHAR          BitCntl, N1, N2, MyByte, MyBit;
-    CHAR          *IdxPtr;
-
-    IdxPtr = Ptr;
-
-    IdxPtr ++;
-    *TimLen = *IdxPtr;
-
-    // get DTIM Count from TIM element
-    IdxPtr ++;
-    *DtimCount = *IdxPtr;
-
-    // get DTIM Period from TIM element
-    IdxPtr++;
-    *DtimPeriod = *IdxPtr;
-
-    // get Bitmap Control from TIM element
-    IdxPtr++;
-    BitCntl = *IdxPtr;
-
-    if ((*DtimCount == 0) && (BitCntl & 0x01))
-        *BcastFlag = TRUE;
-    else
-        *BcastFlag = FALSE;
-
-    // Parse Partial Virtual Bitmap from TIM element
-    N1 = BitCntl & 0xfe;    // N1 is the first bitmap byte#
-    N2 = *TimLen - 4 + N1;  // N2 is the last bitmap byte#
-
-    if ((Aid < (N1 << 3)) || (Aid >= ((N2 + 1) << 3)))
-        *MessageToMe = FALSE;
-    else
-    {
-        MyByte = (Aid >> 3) - N1;                       // my byte position in the bitmap byte-stream
-        MyBit = Aid % 16 - ((MyByte & 0x01)? 8:0);
-
-        IdxPtr += (MyByte + 1);
-
-        //if (*IdxPtr)
-        //    DBGPRINT(RT_DEBUG_WARN, ("TIM bitmap = 0x%02x\n", *IdxPtr));
-
-        if (*IdxPtr & (0x01 << MyBit))
-            *MessageToMe = TRUE;
-        else
-            *MessageToMe = FALSE;
-    }
-
-    return TRUE;
-}
-
+#include "../../rt2870/sta/sanity.c"
diff --git a/drivers/staging/rt3070/sta/sync.c b/drivers/staging/rt3070/sta/sync.c
index 2b5b3b0..b7b8eb4 100644
--- a/drivers/staging/rt3070/sta/sync.c
+++ b/drivers/staging/rt3070/sta/sync.c
@@ -1,1755 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	sync.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	John Chang	2004-09-01      modified for rt2561/2661
-	Jan Lee		2006-08-01      modified for rt2860 for 802.11n
-*/
-#include "../rt_config.h"
-
-#define ADHOC_ENTRY_BEACON_LOST_TIME	(2*OS_HZ)	// 2 sec
-
-/*
-	==========================================================================
-	Description:
-		The sync state machine,
-	Parameters:
-		Sm - pointer to the state machine
-	Note:
-		the state machine looks like the following
-
-	==========================================================================
- */
-VOID SyncStateMachineInit(
-	IN PRTMP_ADAPTER pAd,
-	IN STATE_MACHINE *Sm,
-	OUT STATE_MACHINE_FUNC Trans[])
-{
-	StateMachineInit(Sm, Trans, MAX_SYNC_STATE, MAX_SYNC_MSG, (STATE_MACHINE_FUNC)Drop, SYNC_IDLE, SYNC_MACHINE_BASE);
-
-	// column 1
-	StateMachineSetAction(Sm, SYNC_IDLE, MT2_MLME_SCAN_REQ, (STATE_MACHINE_FUNC)MlmeScanReqAction);
-	StateMachineSetAction(Sm, SYNC_IDLE, MT2_MLME_JOIN_REQ, (STATE_MACHINE_FUNC)MlmeJoinReqAction);
-	StateMachineSetAction(Sm, SYNC_IDLE, MT2_MLME_START_REQ, (STATE_MACHINE_FUNC)MlmeStartReqAction);
-	StateMachineSetAction(Sm, SYNC_IDLE, MT2_PEER_BEACON, (STATE_MACHINE_FUNC)PeerBeacon);
-	StateMachineSetAction(Sm, SYNC_IDLE, MT2_PEER_PROBE_REQ, (STATE_MACHINE_FUNC)PeerProbeReqAction);
-
-	//column 2
-	StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_MLME_SCAN_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenScan);
-	StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_MLME_JOIN_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenJoin);
-	StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_MLME_START_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenStart);
-	StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_PEER_BEACON, (STATE_MACHINE_FUNC)PeerBeaconAtJoinAction);
-	StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_BEACON_TIMEOUT, (STATE_MACHINE_FUNC)BeaconTimeoutAtJoinAction);
-
-	// column 3
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_MLME_SCAN_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenScan);
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_MLME_JOIN_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenJoin);
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_MLME_START_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenStart);
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_PEER_BEACON, (STATE_MACHINE_FUNC)PeerBeaconAtScanAction);
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_PEER_PROBE_RSP, (STATE_MACHINE_FUNC)PeerBeaconAtScanAction);
-	StateMachineSetAction(Sm, SCAN_LISTEN, MT2_SCAN_TIMEOUT, (STATE_MACHINE_FUNC)ScanTimeoutAction);
-
-	// timer init
-	RTMPInitTimer(pAd, &pAd->MlmeAux.BeaconTimer, GET_TIMER_FUNCTION(BeaconTimeout), pAd, FALSE);
-	RTMPInitTimer(pAd, &pAd->MlmeAux.ScanTimer, GET_TIMER_FUNCTION(ScanTimeout), pAd, FALSE);
-}
-
-/*
-	==========================================================================
-	Description:
-		Beacon timeout handler, executed in timer thread
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID BeaconTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-	DBGPRINT(RT_DEBUG_TRACE,("SYNC - BeaconTimeout\n"));
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS))
-		return;
-
-#ifdef DOT11_N_SUPPORT
-	if ((pAd->CommonCfg.BBPCurrentBW == BW_40)
-		)
-	{
-		UCHAR        BBPValue = 0;
-		AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE);
-		AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel);
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-		BBPValue &= (~0x18);
-		BBPValue |= 0x10;
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-		DBGPRINT(RT_DEBUG_TRACE, ("SYNC - End of SCAN, restore to 40MHz channel %d, Total BSS[%02d]\n",pAd->CommonCfg.CentralChannel, pAd->ScanTab.BssNr));
-	}
-#endif // DOT11_N_SUPPORT //
-
-	MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_BEACON_TIMEOUT, 0, NULL);
-	RT28XX_MLME_HANDLER(pAd);
-}
-
-/*
-	==========================================================================
-	Description:
-		Scan timeout handler, executed in timer thread
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID ScanTimeout(
-	IN PVOID SystemSpecific1,
-	IN PVOID FunctionContext,
-	IN PVOID SystemSpecific2,
-	IN PVOID SystemSpecific3)
-{
-	RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext;
-
-
-	// Do nothing if the driver is starting halt state.
-	// This might happen when timer already been fired before cancel timer with mlmehalt
-	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS))
-		return;
-
-	if (MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_SCAN_TIMEOUT, 0, NULL))
-	{
-		RT28XX_MLME_HANDLER(pAd);
-	}
-	else
-	{
-		// To prevent SyncMachine.CurrState is SCAN_LISTEN forever.
-		pAd->MlmeAux.Channel = 0;
-		ScanNextChannel(pAd);
-		if (pAd->CommonCfg.bWirelessEvent)
-		{
-			RTMPSendWirelessEvent(pAd, IW_SCAN_ENQUEUE_FAIL_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-		}
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		MLME SCAN req state machine procedure
-	==========================================================================
- */
-VOID MlmeScanReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR          Ssid[MAX_LEN_OF_SSID], SsidLen, ScanType, BssType, BBPValue = 0;
-	BOOLEAN        TimerCancelled;
-	ULONG		   Now;
-	USHORT         Status;
-	PHEADER_802_11 pHdr80211;
-	PUCHAR         pOutBuffer = NULL;
-	NDIS_STATUS    NStatus;
-
-	// Check the total scan tries for one single OID command
-	// If this is the CCX 2.0 Case, skip that!
-	if ( !RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeScanReqAction before Startup\n"));
-		return;
-	}
-
-	// Increase the scan retry counters.
-	pAd->StaCfg.ScanCnt++;
-
-
-	// first check the parameter sanity
-	if (MlmeScanReqSanity(pAd,
-						  Elem->Msg,
-						  Elem->MsgLen,
-						  &BssType,
-						  Ssid,
-						  &SsidLen,
-						  &ScanType))
-	{
-
-		// Check for channel load and noise hist request
-		// Suspend MSDU only at scan request, not the last two mentioned
-		if ((ScanType == SCAN_CISCO_NOISE) || (ScanType == SCAN_CISCO_CHANNEL_LOAD))
-		{
-			if (pAd->StaCfg.CCXScanChannel != pAd->CommonCfg.Channel)
-				RTMPSuspendMsduTransmission(pAd);			// Suspend MSDU transmission here
-		}
-		else
-		{
-			// Suspend MSDU transmission here
-			RTMPSuspendMsduTransmission(pAd);
-		}
-
-		//
-		// To prevent data lost.
-		// Send an NULL data with turned PSM bit on to current associated AP before SCAN progress.
-		// And should send an NULL data with turned PSM bit off to AP, when scan progress done
-		//
-		if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) && (INFRA_ON(pAd)))
-		{
-			NStatus = MlmeAllocateMemory(pAd, (PVOID)&pOutBuffer);
-			if (NStatus	== NDIS_STATUS_SUCCESS)
-			{
-				pHdr80211 = (PHEADER_802_11) pOutBuffer;
-				MgtMacHeaderInit(pAd, pHdr80211, SUBTYPE_NULL_FUNC, 1, pAd->CommonCfg.Bssid, pAd->CommonCfg.Bssid);
-				pHdr80211->Duration = 0;
-				pHdr80211->FC.Type = BTYPE_DATA;
-				pHdr80211->FC.PwrMgmt = PWR_SAVE;
-
-				// Send using priority queue
-				MiniportMMRequest(pAd, 0, pOutBuffer, sizeof(HEADER_802_11));
-				DBGPRINT(RT_DEBUG_TRACE, ("MlmeScanReqAction -- Send PSM Data frame for off channel RM\n"));
-				MlmeFreeMemory(pAd, pOutBuffer);
-				RTMPusecDelay(5000);
-			}
-		}
-
-		NdisGetSystemUpTime(&Now);
-		pAd->StaCfg.LastScanTime = Now;
-		// reset all the timers
-		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled);
-
-		// record desired BSS parameters
-		pAd->MlmeAux.BssType = BssType;
-		pAd->MlmeAux.ScanType = ScanType;
-		pAd->MlmeAux.SsidLen = SsidLen;
-        NdisZeroMemory(pAd->MlmeAux.Ssid, MAX_LEN_OF_SSID);
-		NdisMoveMemory(pAd->MlmeAux.Ssid, Ssid, SsidLen);
-
-		// start from the first channel
-		pAd->MlmeAux.Channel = FirstChannel(pAd);
-
-		// Change the scan channel when dealing with CCX beacon report
-		if ((ScanType == SCAN_CISCO_PASSIVE) || (ScanType == SCAN_CISCO_ACTIVE) ||
-			(ScanType == SCAN_CISCO_CHANNEL_LOAD) || (ScanType == SCAN_CISCO_NOISE))
-			pAd->MlmeAux.Channel = pAd->StaCfg.CCXScanChannel;
-
-		// Let BBP register at 20MHz to do scan
-		RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-		BBPValue &= (~0x18);
-		RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-		DBGPRINT(RT_DEBUG_TRACE, ("SYNC - BBP R4 to 20MHz.l\n"));
-		ScanNextChannel(pAd);
-	}
-	else
-	{
-		DBGPRINT_ERR(("SYNC - MlmeScanReqAction() sanity check fail\n"));
-		pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-		Status = MLME_INVALID_FORMAT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status);
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		MLME JOIN req state machine procedure
-	==========================================================================
- */
-VOID MlmeJoinReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR        BBPValue = 0;
-	BSS_ENTRY    *pBss;
-	BOOLEAN       TimerCancelled;
-	HEADER_802_11 Hdr80211;
-	NDIS_STATUS   NStatus;
-	ULONG         FrameLen = 0;
-	PUCHAR        pOutBuffer = NULL;
-	PUCHAR        pSupRate = NULL;
-	UCHAR         SupRateLen;
-	PUCHAR        pExtRate = NULL;
-	UCHAR         ExtRateLen;
-	UCHAR         ASupRate[] = {0x8C, 0x12, 0x98, 0x24, 0xb0, 0x48, 0x60, 0x6C};
-	UCHAR         ASupRateLen = sizeof(ASupRate)/sizeof(UCHAR);
-	MLME_JOIN_REQ_STRUCT *pInfo = (MLME_JOIN_REQ_STRUCT *)(Elem->Msg);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeJoinReqAction(BSS #%ld)\n", pInfo->BssIdx));
-
-
-	// reset all the timers
-	RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled);
-	RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled);
-
-	pBss = &pAd->MlmeAux.SsidBssTab.BssEntry[pInfo->BssIdx];
-
-	// record the desired SSID & BSSID we're waiting for
-	COPY_MAC_ADDR(pAd->MlmeAux.Bssid, pBss->Bssid);
-
-	// If AP's SSID is not hidden, it is OK for updating ssid to MlmeAux again.
-	if (pBss->Hidden == 0)
-	{
-		NdisMoveMemory(pAd->MlmeAux.Ssid, pBss->Ssid, pBss->SsidLen);
-		pAd->MlmeAux.SsidLen = pBss->SsidLen;
-	}
-
-	pAd->MlmeAux.BssType = pBss->BssType;
-	pAd->MlmeAux.Channel = pBss->Channel;
-	pAd->MlmeAux.CentralChannel = pBss->CentralChannel;
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-	// Country IE of the AP will be evaluated and will be used.
-	if ((pAd->StaCfg.IEEE80211dClientMode != Rt802_11_D_None) &&
-		(pBss->bHasCountryIE == TRUE))
-	{
-		NdisMoveMemory(&pAd->CommonCfg.CountryCode[0], &pBss->CountryString[0], 2);
-		if (pBss->CountryString[2] == 'I')
-			pAd->CommonCfg.Geography = IDOR;
-		else if (pBss->CountryString[2] == 'O')
-			pAd->CommonCfg.Geography = ODOR;
-		else
-			pAd->CommonCfg.Geography = BOTH;
-		BuildChannelListEx(pAd);
-	}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-	// Let BBP register at 20MHz to do scan
-	RTMP_BBP_IO_READ8_BY_REG_ID(pAd, BBP_R4, &BBPValue);
-	BBPValue &= (~0x18);
-	RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R4, BBPValue);
-	DBGPRINT(RT_DEBUG_TRACE, ("SYNC - BBP R4 to 20MHz.l\n"));
-
-	// switch channel and waiting for beacon timer
-	AsicSwitchChannel(pAd, pAd->MlmeAux.Channel, FALSE);
-	AsicLockChannel(pAd, pAd->MlmeAux.Channel);
-	RTMPSetTimer(&pAd->MlmeAux.BeaconTimer, JOIN_TIMEOUT);
-
-    do
-	{
-		if (((pAd->CommonCfg.bIEEE80211H == 1) &&
-            (pAd->MlmeAux.Channel > 14) &&
-             RadarChannelCheck(pAd, pAd->MlmeAux.Channel))
-#ifdef CARRIER_DETECTION_SUPPORT // Roger sync Carrier
-             || (pAd->CommonCfg.CarrierDetect.Enable == TRUE)
-#endif // CARRIER_DETECTION_SUPPORT //
-            )
-		{
-			//
-			// We can't send any Probe request frame to meet 802.11h.
-			//
-			if (pBss->Hidden == 0)
-				break;
-		}
-
-		//
-		// send probe request
-		//
-		NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);
-		if (NStatus == NDIS_STATUS_SUCCESS)
-		{
-			if (pAd->MlmeAux.Channel <= 14)
-			{
-				pSupRate = pAd->CommonCfg.SupRate;
-				SupRateLen = pAd->CommonCfg.SupRateLen;
-				pExtRate = pAd->CommonCfg.ExtRate;
-				ExtRateLen = pAd->CommonCfg.ExtRateLen;
-			}
-			else
-			{
-				//
-				// Overwrite Support Rate, CCK rate are not allowed
-				//
-				pSupRate = ASupRate;
-				SupRateLen = ASupRateLen;
-				ExtRateLen = 0;
-			}
-
-			if (pAd->MlmeAux.BssType == BSS_INFRA)
-				MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, pAd->MlmeAux.Bssid, pAd->MlmeAux.Bssid);
-			else
-				MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, BROADCAST_ADDR, BROADCAST_ADDR);
-
-			MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-							  sizeof(HEADER_802_11),    &Hdr80211,
-							  1,                        &SsidIe,
-							  1,                        &pAd->MlmeAux.SsidLen,
-							  pAd->MlmeAux.SsidLen,	    pAd->MlmeAux.Ssid,
-							  1,                        &SupRateIe,
-							  1,                        &SupRateLen,
-							  SupRateLen,               pSupRate,
-							  END_OF_ARGS);
-
-			if (ExtRateLen)
-			{
-				ULONG Tmp;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &Tmp,
-								  1,                                &ExtRateIe,
-								  1,                                &ExtRateLen,
-								  ExtRateLen,                       pExtRate,
-								  END_OF_ARGS);
-				FrameLen += Tmp;
-			}
-
-
-			MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-			MlmeFreeMemory(pAd, pOutBuffer);
-		}
-    } while (FALSE);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("SYNC - Switch to ch %d, Wait BEACON from %02x:%02x:%02x:%02x:%02x:%02x\n",
-		pBss->Channel, pBss->Bssid[0], pBss->Bssid[1], pBss->Bssid[2], pBss->Bssid[3], pBss->Bssid[4], pBss->Bssid[5]));
-
-	pAd->Mlme.SyncMachine.CurrState = JOIN_WAIT_BEACON;
-}
-
-/*
-	==========================================================================
-	Description:
-		MLME START Request state machine procedure, starting an IBSS
-	==========================================================================
- */
-VOID MlmeStartReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR         Ssid[MAX_LEN_OF_SSID], SsidLen;
-	BOOLEAN       TimerCancelled;
-
-	// New for WPA security suites
-	UCHAR						VarIE[MAX_VIE_LEN]; 	// Total VIE length = MAX_VIE_LEN - -5
-	NDIS_802_11_VARIABLE_IEs	*pVIE = NULL;
-	LARGE_INTEGER				TimeStamp;
-	BOOLEAN Privacy;
-	USHORT Status;
-
-	// Init Variable IE structure
-	pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
-	pVIE->Length = 0;
-	TimeStamp.u.LowPart  = 0;
-	TimeStamp.u.HighPart = 0;
-
-	if (MlmeStartReqSanity(pAd, Elem->Msg, Elem->MsgLen, Ssid, &SsidLen))
-	{
-		// reset all the timers
-		RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled);
-		RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled);
-
-		//
-		// Start a new IBSS. All IBSS parameters are decided now....
-		//
-		DBGPRINT(RT_DEBUG_TRACE, ("MlmeStartReqAction - Start a new IBSS. All IBSS parameters are decided now.... \n"));
-		pAd->MlmeAux.BssType           = BSS_ADHOC;
-		NdisMoveMemory(pAd->MlmeAux.Ssid, Ssid, SsidLen);
-		pAd->MlmeAux.SsidLen           = SsidLen;
-
-		// generate a radom number as BSSID
-		MacAddrRandomBssid(pAd, pAd->MlmeAux.Bssid);
-		DBGPRINT(RT_DEBUG_TRACE, ("MlmeStartReqAction - generate a radom number as BSSID \n"));
-
-		Privacy = (pAd->StaCfg.WepStatus == Ndis802_11Encryption1Enabled) ||
-				  (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
-				  (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled);
-		pAd->MlmeAux.CapabilityInfo    = CAP_GENERATE(0,1,Privacy, (pAd->CommonCfg.TxPreamble == Rt802_11PreambleShort), 1, 0);
-		pAd->MlmeAux.BeaconPeriod      = pAd->CommonCfg.BeaconPeriod;
-		pAd->MlmeAux.AtimWin           = pAd->StaCfg.AtimWin;
-		pAd->MlmeAux.Channel           = pAd->CommonCfg.Channel;
-
-		pAd->CommonCfg.CentralChannel  = pAd->CommonCfg.Channel;
-		pAd->MlmeAux.CentralChannel    = pAd->CommonCfg.CentralChannel;
-
-		pAd->MlmeAux.SupRateLen= pAd->CommonCfg.SupRateLen;
-		NdisMoveMemory(pAd->MlmeAux.SupRate, pAd->CommonCfg.SupRate, MAX_LEN_OF_SUPPORTED_RATES);
-		RTMPCheckRates(pAd, pAd->MlmeAux.SupRate, &pAd->MlmeAux.SupRateLen);
-		pAd->MlmeAux.ExtRateLen = pAd->CommonCfg.ExtRateLen;
-		NdisMoveMemory(pAd->MlmeAux.ExtRate, pAd->CommonCfg.ExtRate, MAX_LEN_OF_SUPPORTED_RATES);
-		RTMPCheckRates(pAd, pAd->MlmeAux.ExtRate, &pAd->MlmeAux.ExtRateLen);
-#ifdef DOT11_N_SUPPORT
-		if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-		{
-			RTMPUpdateHTIE(&pAd->CommonCfg.DesiredHtPhy, &pAd->StaCfg.DesiredHtPhyInfo.MCSSet[0], &pAd->MlmeAux.HtCapability, &pAd->MlmeAux.AddHtInfo);
-			pAd->MlmeAux.HtCapabilityLen = sizeof(HT_CAPABILITY_IE);
-			// Not turn pAd->StaActive.SupportedHtPhy.bHtEnable = TRUE here.
-			DBGPRINT(RT_DEBUG_TRACE, ("SYNC -pAd->StaActive.SupportedHtPhy.bHtEnable = TRUE\n"));
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			pAd->MlmeAux.HtCapabilityLen = 0;
-			pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
-		}
-		// temporarily not support QOS in IBSS
-		NdisZeroMemory(&pAd->MlmeAux.APEdcaParm, sizeof(EDCA_PARM));
-		NdisZeroMemory(&pAd->MlmeAux.APQbssLoad, sizeof(QBSS_LOAD_PARM));
-		NdisZeroMemory(&pAd->MlmeAux.APQosCapability, sizeof(QOS_CAPABILITY_PARM));
-
-		AsicSwitchChannel(pAd, pAd->MlmeAux.Channel, FALSE);
-		AsicLockChannel(pAd, pAd->MlmeAux.Channel);
-
-		DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeStartReqAction(ch= %d,sup rates= %d, ext rates=%d)\n",
-			pAd->MlmeAux.Channel, pAd->MlmeAux.SupRateLen, pAd->MlmeAux.ExtRateLen));
-
-		pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-		Status = MLME_SUCCESS;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_START_CONF, 2, &Status);
-	}
-	else
-	{
-		DBGPRINT_ERR(("SYNC - MlmeStartReqAction() sanity check fail.\n"));
-		pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-		Status = MLME_INVALID_FORMAT;
-		MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_START_CONF, 2, &Status);
-	}
-}
-
-/*
-	==========================================================================
-	Description:
-		peer sends beacon back when scanning
-	==========================================================================
- */
-VOID PeerBeaconAtScanAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR           Bssid[MAC_ADDR_LEN], Addr2[MAC_ADDR_LEN];
-	UCHAR           Ssid[MAX_LEN_OF_SSID], BssType, Channel, NewChannel,
-					SsidLen, DtimCount, DtimPeriod, BcastFlag, MessageToMe;
-	CF_PARM         CfParm;
-	USHORT          BeaconPeriod, AtimWin, CapabilityInfo;
-	PFRAME_802_11   pFrame;
-	LARGE_INTEGER   TimeStamp;
-	UCHAR           Erp;
-	UCHAR         	SupRate[MAX_LEN_OF_SUPPORTED_RATES], ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		  	SupRateLen, ExtRateLen;
-	USHORT 			LenVIE;
-	UCHAR			CkipFlag;
-	UCHAR			AironetCellPowerLimit;
-	EDCA_PARM       EdcaParm;
-	QBSS_LOAD_PARM  QbssLoad;
-	QOS_CAPABILITY_PARM QosCapability;
-	ULONG						RalinkIe;
-	UCHAR						VarIE[MAX_VIE_LEN];		// Total VIE length = MAX_VIE_LEN - -5
-	NDIS_802_11_VARIABLE_IEs	*pVIE = NULL;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			HtCapabilityLen = 0, PreNHtCapabilityLen = 0;
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChannelOffset = 0xff;
-
-
-	// NdisFillMemory(Ssid, MAX_LEN_OF_SSID, 0x00);
-	pFrame = (PFRAME_802_11) Elem->Msg;
-	// Init Variable IE structure
-	pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
-	pVIE->Length = 0;
-#ifdef DOT11_N_SUPPORT
-    RTMPZeroMemory(&HtCapability, sizeof(HtCapability));
-	RTMPZeroMemory(&AddHtInfo, sizeof(ADD_HT_INFO_IE));
-#endif // DOT11_N_SUPPORT //
-
-	if (PeerBeaconAndProbeRspSanity(pAd,
-								Elem->Msg,
-								Elem->MsgLen,
-								Elem->Channel,
-								Addr2,
-								Bssid,
-								Ssid,
-								&SsidLen,
-								&BssType,
-								&BeaconPeriod,
-								&Channel,
-								&NewChannel,
-								&TimeStamp,
-								&CfParm,
-								&AtimWin,
-								&CapabilityInfo,
-								&Erp,
-								&DtimCount,
-								&DtimPeriod,
-								&BcastFlag,
-								&MessageToMe,
-								SupRate,
-								&SupRateLen,
-								ExtRate,
-								&ExtRateLen,
-								&CkipFlag,
-								&AironetCellPowerLimit,
-								&EdcaParm,
-								&QbssLoad,
-								&QosCapability,
-								&RalinkIe,
-								&HtCapabilityLen,
-								&PreNHtCapabilityLen,
-								&HtCapability,
-								&AddHtInfoLen,
-								&AddHtInfo,
-								&NewExtChannelOffset,
-								&LenVIE,
-								pVIE))
-	{
-		ULONG Idx;
-		CHAR Rssi = 0;
-
-		Idx = BssTableSearch(&pAd->ScanTab, Bssid, Channel);
-		if (Idx != BSS_NOT_FOUND)
-			Rssi = pAd->ScanTab.BssEntry[Idx].Rssi;
-
-		Rssi = RTMPMaxRssi(pAd, ConvertToRssi(pAd, Elem->Rssi0, RSSI_0), ConvertToRssi(pAd, Elem->Rssi1, RSSI_1), ConvertToRssi(pAd, Elem->Rssi2, RSSI_2));
-
-
-#ifdef DOT11_N_SUPPORT
-		if ((HtCapabilityLen > 0) || (PreNHtCapabilityLen > 0))
-			HtCapabilityLen = SIZE_HT_CAP_IE;
-#endif // DOT11_N_SUPPORT //
-		if ((pAd->StaCfg.CCXReqType != MSRN_TYPE_UNUSED) && (Channel == pAd->StaCfg.CCXScanChannel))
-		{
-			Idx = BssTableSetEntry(pAd, &pAd->StaCfg.CCXBssTab, Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
-						 &CfParm, AtimWin, CapabilityInfo, SupRate, SupRateLen,ExtRate, ExtRateLen, &HtCapability,
-						 &AddHtInfo, HtCapabilityLen, AddHtInfoLen, NewExtChannelOffset, Channel, Rssi, TimeStamp, CkipFlag,
-						 &EdcaParm, &QosCapability, &QbssLoad, LenVIE, pVIE);
-			if (Idx != BSS_NOT_FOUND)
-			{
-				NdisMoveMemory(pAd->StaCfg.CCXBssTab.BssEntry[Idx].PTSF, &Elem->Msg[24], 4);
-				NdisMoveMemory(&pAd->StaCfg.CCXBssTab.BssEntry[Idx].TTSF[0], &Elem->TimeStamp.u.LowPart, 4);
-				NdisMoveMemory(&pAd->StaCfg.CCXBssTab.BssEntry[Idx].TTSF[4], &Elem->TimeStamp.u.LowPart, 4);
-				if (pAd->StaCfg.CCXReqType == MSRN_TYPE_BEACON_REQ)
-					AironetAddBeaconReport(pAd, Idx, Elem);
-			}
-		}
-		else
-		{
-			Idx = BssTableSetEntry(pAd, &pAd->ScanTab, Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
-						  &CfParm, AtimWin, CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,  &HtCapability,
-						 &AddHtInfo, HtCapabilityLen, AddHtInfoLen, NewExtChannelOffset, Channel, Rssi, TimeStamp, CkipFlag,
-						 &EdcaParm, &QosCapability, &QbssLoad, LenVIE, pVIE);
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-			if (pAd->ChannelList[pAd->CommonCfg.ChannelListIdx].bEffectedChannel == TRUE)
-			{
-				UCHAR		RegClass;
-				PeerBeaconAndProbeRspSanity2(pAd, Elem->Msg, Elem->MsgLen, &RegClass);
-				TriEventTableSetEntry(pAd, &pAd->CommonCfg.TriggerEventTab, Bssid, &HtCapability, HtCapabilityLen, RegClass, Channel);
-			}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-			if (Idx != BSS_NOT_FOUND)
-			{
-				NdisMoveMemory(pAd->ScanTab.BssEntry[Idx].PTSF, &Elem->Msg[24], 4);
-				NdisMoveMemory(&pAd->ScanTab.BssEntry[Idx].TTSF[0], &Elem->TimeStamp.u.LowPart, 4);
-				NdisMoveMemory(&pAd->ScanTab.BssEntry[Idx].TTSF[4], &Elem->TimeStamp.u.LowPart, 4);
-			}
-		}
-	}
-	// sanity check fail, ignored
-}
-
-/*
-	==========================================================================
-	Description:
-		When waiting joining the (I)BSS, beacon received from external
-	==========================================================================
- */
-VOID PeerBeaconAtJoinAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR         Bssid[MAC_ADDR_LEN], Addr2[MAC_ADDR_LEN];
-	UCHAR         Ssid[MAX_LEN_OF_SSID], SsidLen, BssType, Channel, MessageToMe,
-				  DtimCount, DtimPeriod, BcastFlag, NewChannel;
-	LARGE_INTEGER TimeStamp;
-	USHORT        BeaconPeriod, AtimWin, CapabilityInfo;
-	CF_PARM       Cf;
-	BOOLEAN       TimerCancelled;
-	UCHAR         Erp;
-	UCHAR         SupRate[MAX_LEN_OF_SUPPORTED_RATES], ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		  SupRateLen, ExtRateLen;
-	UCHAR         CkipFlag;
-	USHORT 		  LenVIE;
-	UCHAR		  AironetCellPowerLimit;
-	EDCA_PARM       EdcaParm;
-	QBSS_LOAD_PARM  QbssLoad;
-	QOS_CAPABILITY_PARM QosCapability;
-	USHORT        Status;
-	UCHAR						VarIE[MAX_VIE_LEN];		// Total VIE length = MAX_VIE_LEN - -5
-	NDIS_802_11_VARIABLE_IEs	*pVIE = NULL;
-	ULONG           RalinkIe;
-	ULONG         Idx;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR				HtCapabilityLen = 0, PreNHtCapabilityLen = 0;
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChannelOffset = 0xff;
-#ifdef DOT11_N_SUPPORT
-	UCHAR			CentralChannel;
-#endif // DOT11_N_SUPPORT //
-
-	// Init Variable IE structure
-	pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
-	pVIE->Length = 0;
-    RTMPZeroMemory(&HtCapability, sizeof(HtCapability));
-	RTMPZeroMemory(&AddHtInfo, sizeof(ADD_HT_INFO_IE));
-
-
-	if (PeerBeaconAndProbeRspSanity(pAd,
-								Elem->Msg,
-								Elem->MsgLen,
-								Elem->Channel,
-								Addr2,
-								Bssid,
-								Ssid,
-								&SsidLen,
-								&BssType,
-								&BeaconPeriod,
-								&Channel,
-								&NewChannel,
-								&TimeStamp,
-								&Cf,
-								&AtimWin,
-								&CapabilityInfo,
-								&Erp,
-								&DtimCount,
-								&DtimPeriod,
-								&BcastFlag,
-								&MessageToMe,
-								SupRate,
-								&SupRateLen,
-								ExtRate,
-								&ExtRateLen,
-								&CkipFlag,
-								&AironetCellPowerLimit,
-								&EdcaParm,
-								&QbssLoad,
-								&QosCapability,
-								&RalinkIe,
-								&HtCapabilityLen,
-								&PreNHtCapabilityLen,
-								&HtCapability,
-								&AddHtInfoLen,
-								&AddHtInfo,
-								&NewExtChannelOffset,
-								&LenVIE,
-								pVIE))
-	{
-		// Disqualify 11b only adhoc when we are in 11g only adhoc mode
-		if ((BssType == BSS_ADHOC) && (pAd->CommonCfg.PhyMode == PHY_11G) && ((SupRateLen+ExtRateLen)< 12))
-			return;
-
-		// BEACON from desired BSS/IBSS found. We should be able to decide most
-		// BSS parameters here.
-		// Q. But what happen if this JOIN doesn't conclude a successful ASSOCIATEION?
-		//    Do we need to receover back all parameters belonging to previous BSS?
-		// A. Should be not. There's no back-door recover to previous AP. It still need
-		//    a new JOIN-AUTH-ASSOC sequence.
-		if (MAC_ADDR_EQUAL(pAd->MlmeAux.Bssid, Bssid))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("SYNC - receive desired BEACON at JoinWaitBeacon... Channel = %d\n", Channel));
-			RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled);
-
-			// Update RSSI to prevent No signal display when cards first initialized
-			pAd->StaCfg.RssiSample.LastRssi0	= ConvertToRssi(pAd, Elem->Rssi0, RSSI_0);
-			pAd->StaCfg.RssiSample.LastRssi1	= ConvertToRssi(pAd, Elem->Rssi1, RSSI_1);
-			pAd->StaCfg.RssiSample.LastRssi2	= ConvertToRssi(pAd, Elem->Rssi2, RSSI_2);
-			pAd->StaCfg.RssiSample.AvgRssi0	= pAd->StaCfg.RssiSample.LastRssi0;
-			pAd->StaCfg.RssiSample.AvgRssi0X8	= pAd->StaCfg.RssiSample.AvgRssi0 << 3;
-			pAd->StaCfg.RssiSample.AvgRssi1	= pAd->StaCfg.RssiSample.LastRssi1;
-			pAd->StaCfg.RssiSample.AvgRssi1X8	= pAd->StaCfg.RssiSample.AvgRssi1 << 3;
-			pAd->StaCfg.RssiSample.AvgRssi2	= pAd->StaCfg.RssiSample.LastRssi2;
-			pAd->StaCfg.RssiSample.AvgRssi2X8	= pAd->StaCfg.RssiSample.AvgRssi2 << 3;
-
-			//
-			// We need to check if SSID only set to any, then we can record the current SSID.
-			// Otherwise will cause hidden SSID association failed.
-			//
-			if (pAd->MlmeAux.SsidLen == 0)
-			{
-				NdisMoveMemory(pAd->MlmeAux.Ssid, Ssid, SsidLen);
-				pAd->MlmeAux.SsidLen = SsidLen;
-			}
-			else
-			{
-				Idx = BssSsidTableSearch(&pAd->ScanTab, Bssid, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen, Channel);
-
-				if (Idx != BSS_NOT_FOUND)
-				{
-					//
-					// Multiple SSID case, used correct CapabilityInfo
-					//
-					CapabilityInfo = pAd->ScanTab.BssEntry[Idx].CapabilityInfo;
-				}
-			}
-			NdisMoveMemory(pAd->MlmeAux.Bssid, Bssid, MAC_ADDR_LEN);
-			pAd->MlmeAux.CapabilityInfo = CapabilityInfo & SUPPORTED_CAPABILITY_INFO;
-			pAd->MlmeAux.BssType = BssType;
-			pAd->MlmeAux.BeaconPeriod = BeaconPeriod;
-			pAd->MlmeAux.Channel = Channel;
-			pAd->MlmeAux.AtimWin = AtimWin;
-			pAd->MlmeAux.CfpPeriod = Cf.CfpPeriod;
-			pAd->MlmeAux.CfpMaxDuration = Cf.CfpMaxDuration;
-			pAd->MlmeAux.APRalinkIe = RalinkIe;
-
-			// Copy AP's supported rate to MlmeAux for creating assoication request
-			// Also filter out not supported rate
-			pAd->MlmeAux.SupRateLen = SupRateLen;
-			NdisMoveMemory(pAd->MlmeAux.SupRate, SupRate, SupRateLen);
-			RTMPCheckRates(pAd, pAd->MlmeAux.SupRate, &pAd->MlmeAux.SupRateLen);
-			pAd->MlmeAux.ExtRateLen = ExtRateLen;
-			NdisMoveMemory(pAd->MlmeAux.ExtRate, ExtRate, ExtRateLen);
-			RTMPCheckRates(pAd, pAd->MlmeAux.ExtRate, &pAd->MlmeAux.ExtRateLen);
-
-            NdisZeroMemory(pAd->StaActive.SupportedPhyInfo.MCSSet, 16);
-#ifdef DOT11_N_SUPPORT
-			pAd->MlmeAux.NewExtChannelOffset = NewExtChannelOffset;
-			pAd->MlmeAux.HtCapabilityLen = HtCapabilityLen;
-
-			// filter out un-supported ht rates
-			if (((HtCapabilityLen > 0) || (PreNHtCapabilityLen > 0)) && (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED))
-			{
-				RTMPZeroMemory(&pAd->MlmeAux.HtCapability, SIZE_HT_CAP_IE);
-   				RTMPMoveMemory(&pAd->MlmeAux.AddHtInfo, &AddHtInfo, SIZE_ADD_HT_INFO_IE);
-
-				// StaActive.SupportedHtPhy.MCSSet stores Peer AP's 11n Rx capability
-				NdisMoveMemory(pAd->StaActive.SupportedPhyInfo.MCSSet, HtCapability.MCSSet, 16);
-				pAd->MlmeAux.NewExtChannelOffset = NewExtChannelOffset;
-				pAd->MlmeAux.HtCapabilityLen = SIZE_HT_CAP_IE;
-				pAd->StaActive.SupportedPhyInfo.bHtEnable = TRUE;
-				if (PreNHtCapabilityLen > 0)
-					pAd->StaActive.SupportedPhyInfo.bPreNHt = TRUE;
-				RTMPCheckHt(pAd, BSSID_WCID, &HtCapability, &AddHtInfo);
-				// Copy AP Parameter to StaActive.  This is also in LinkUp.
-				DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAtJoinAction! (MpduDensity=%d, MaxRAmpduFactor=%d, BW=%d)\n",
-					pAd->StaActive.SupportedHtPhy.MpduDensity, pAd->StaActive.SupportedHtPhy.MaxRAmpduFactor, HtCapability.HtCapInfo.ChannelWidth));
-
-				if (AddHtInfoLen > 0)
-				{
-					CentralChannel = AddHtInfo.ControlChan;
-		 			// Check again the Bandwidth capability of this AP.
-		 			if ((AddHtInfo.ControlChan > 2)&& (AddHtInfo.AddHtInfo.ExtChanOffset == EXTCHA_BELOW) && (HtCapability.HtCapInfo.ChannelWidth == BW_40))
-		 			{
-		 				CentralChannel = AddHtInfo.ControlChan - 2;
-		 			}
-		 			else if ((AddHtInfo.AddHtInfo.ExtChanOffset == EXTCHA_ABOVE) && (HtCapability.HtCapInfo.ChannelWidth == BW_40))
-		 			{
-		 				CentralChannel = AddHtInfo.ControlChan + 2;
-		 			}
-
-					// Check Error .
-					if (pAd->MlmeAux.CentralChannel != CentralChannel)
-		 				DBGPRINT(RT_DEBUG_ERROR, ("PeerBeaconAtJoinAction HT===>Beacon Central Channel = %d, Control Channel = %d. Mlmeaux CentralChannel = %d\n", CentralChannel, AddHtInfo.ControlChan, pAd->MlmeAux.CentralChannel));
-
-		 			DBGPRINT(RT_DEBUG_TRACE, ("PeerBeaconAtJoinAction HT===>Central Channel = %d, Control Channel = %d,  .\n", CentralChannel, AddHtInfo.ControlChan));
-
-				}
-
-			}
-			else
-#endif // DOT11_N_SUPPORT //
-			{
-   				// To prevent error, let legacy AP must have same CentralChannel and Channel.
-				if ((HtCapabilityLen == 0) && (PreNHtCapabilityLen == 0))
-					pAd->MlmeAux.CentralChannel = pAd->MlmeAux.Channel;
-
-				pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE;
-				RTMPZeroMemory(&pAd->MlmeAux.HtCapability, SIZE_HT_CAP_IE);
-				RTMPZeroMemory(&pAd->MlmeAux.AddHtInfo, SIZE_ADD_HT_INFO_IE);
-			}
-
-			RTMPUpdateMlmeRate(pAd);
-
-			// copy QOS related information
-			if ((pAd->CommonCfg.bWmmCapable)
-#ifdef DOT11_N_SUPPORT
-				 || (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-#endif // DOT11_N_SUPPORT //
-				)
-			{
-				NdisMoveMemory(&pAd->MlmeAux.APEdcaParm, &EdcaParm, sizeof(EDCA_PARM));
-				NdisMoveMemory(&pAd->MlmeAux.APQbssLoad, &QbssLoad, sizeof(QBSS_LOAD_PARM));
-				NdisMoveMemory(&pAd->MlmeAux.APQosCapability, &QosCapability, sizeof(QOS_CAPABILITY_PARM));
-			}
-			else
-			{
-				NdisZeroMemory(&pAd->MlmeAux.APEdcaParm, sizeof(EDCA_PARM));
-				NdisZeroMemory(&pAd->MlmeAux.APQbssLoad, sizeof(QBSS_LOAD_PARM));
-				NdisZeroMemory(&pAd->MlmeAux.APQosCapability, sizeof(QOS_CAPABILITY_PARM));
-			}
-
-			DBGPRINT(RT_DEBUG_TRACE, ("SYNC - after JOIN, SupRateLen=%d, ExtRateLen=%d\n",
-										pAd->MlmeAux.SupRateLen, pAd->MlmeAux.ExtRateLen));
-
-#ifdef LEAP_SUPPORT
-			// Update CkipFlag
-			pAd->StaCfg.CkipFlag = CkipFlag;
-
-			// Keep TimeStamp for Re-Association used.
-			if (LEAP_CCKM_ON(pAd) && (pAd->StaCfg.CCKMLinkUpFlag == TRUE))
-				pAd->StaCfg.CCKMBeaconAtJoinTimeStamp = TimeStamp;
-#endif // LEAP_SUPPORT //
-
-			if (AironetCellPowerLimit != 0xFF)
-			{
-				//We need to change our TxPower for CCX 2.0 AP Control of Client Transmit Power
-				ChangeToCellPowerLimit(pAd, AironetCellPowerLimit);
-			}
-			else  //Used the default TX Power Percentage.
-				pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault;
-
-			pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-			Status = MLME_SUCCESS;
-			MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_JOIN_CONF, 2, &Status);
-		}
-		// not to me BEACON, ignored
-	}
-	// sanity check fail, ignore this frame
-}
-
-/*
-	==========================================================================
-	Description:
-		receive BEACON from peer
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID PeerBeacon(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR         Bssid[MAC_ADDR_LEN], Addr2[MAC_ADDR_LEN];
-	CHAR          Ssid[MAX_LEN_OF_SSID];
-	CF_PARM       CfParm;
-	UCHAR         SsidLen, MessageToMe=0, BssType, Channel, NewChannel, index=0;
-	UCHAR         DtimCount=0, DtimPeriod=0, BcastFlag=0;
-	USHORT        CapabilityInfo, AtimWin, BeaconPeriod;
-	LARGE_INTEGER TimeStamp;
-	USHORT        TbttNumToNextWakeUp;
-	UCHAR         Erp;
-	UCHAR         SupRate[MAX_LEN_OF_SUPPORTED_RATES], ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
-	UCHAR		  SupRateLen, ExtRateLen;
-	UCHAR		  CkipFlag;
-	USHORT        LenVIE;
-	UCHAR		  AironetCellPowerLimit;
-	EDCA_PARM       EdcaParm;
-	QBSS_LOAD_PARM  QbssLoad;
-	QOS_CAPABILITY_PARM QosCapability;
-	ULONG           RalinkIe;
-	// New for WPA security suites
-	UCHAR						VarIE[MAX_VIE_LEN];		// Total VIE length = MAX_VIE_LEN - -5
-	NDIS_802_11_VARIABLE_IEs	*pVIE = NULL;
-	HT_CAPABILITY_IE		HtCapability;
-	ADD_HT_INFO_IE		AddHtInfo;	// AP might use this additional ht info IE
-	UCHAR			HtCapabilityLen, PreNHtCapabilityLen;
-	UCHAR			AddHtInfoLen;
-	UCHAR			NewExtChannelOffset = 0xff;
-
-
-#ifdef RALINK_ATE
-    if (ATE_ON(pAd))
-    {
-		return;
-    }
-#endif // RALINK_ATE //
-
-	if (!(INFRA_ON(pAd) || ADHOC_ON(pAd)
-		))
-		return;
-
-	// Init Variable IE structure
-	pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE;
-	pVIE->Length = 0;
-    RTMPZeroMemory(&HtCapability, sizeof(HtCapability));
-	RTMPZeroMemory(&AddHtInfo, sizeof(ADD_HT_INFO_IE));
-
-	if (PeerBeaconAndProbeRspSanity(pAd,
-								Elem->Msg,
-								Elem->MsgLen,
-								Elem->Channel,
-								Addr2,
-								Bssid,
-								Ssid,
-								&SsidLen,
-								&BssType,
-								&BeaconPeriod,
-								&Channel,
-								&NewChannel,
-								&TimeStamp,
-								&CfParm,
-								&AtimWin,
-								&CapabilityInfo,
-								&Erp,
-								&DtimCount,
-								&DtimPeriod,
-								&BcastFlag,
-								&MessageToMe,
-								SupRate,
-								&SupRateLen,
-								ExtRate,
-								&ExtRateLen,
-								&CkipFlag,
-								&AironetCellPowerLimit,
-								&EdcaParm,
-								&QbssLoad,
-								&QosCapability,
-								&RalinkIe,
-								&HtCapabilityLen,
-								&PreNHtCapabilityLen,
-								&HtCapability,
-								&AddHtInfoLen,
-								&AddHtInfo,
-								&NewExtChannelOffset,
-								&LenVIE,
-								pVIE))
-	{
-		BOOLEAN is_my_bssid, is_my_ssid;
-		ULONG   Bssidx, Now;
-		BSS_ENTRY *pBss;
-		CHAR		RealRssi = RTMPMaxRssi(pAd, ConvertToRssi(pAd, Elem->Rssi0, RSSI_0), ConvertToRssi(pAd, Elem->Rssi1, RSSI_1), ConvertToRssi(pAd, Elem->Rssi2, RSSI_2));
-
-		is_my_bssid = MAC_ADDR_EQUAL(Bssid, pAd->CommonCfg.Bssid)? TRUE : FALSE;
-		is_my_ssid = SSID_EQUAL(Ssid, SsidLen, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen)? TRUE:FALSE;
-
-
-		// ignore BEACON not for my SSID
-		if ((! is_my_ssid) && (! is_my_bssid))
-			return;
-
-		// It means STA waits disassoc completely from this AP, ignores this beacon.
-		if (pAd->Mlme.CntlMachine.CurrState == CNTL_WAIT_DISASSOC)
-			return;
-
-#ifdef DOT11_N_SUPPORT
-		// Copy Control channel for this BSSID.
-		if (AddHtInfoLen != 0)
-			Channel = AddHtInfo.ControlChan;
-
-		if ((HtCapabilityLen > 0) || (PreNHtCapabilityLen > 0))
-			HtCapabilityLen = SIZE_HT_CAP_IE;
-#endif // DOT11_N_SUPPORT //
-
-		//
-		// Housekeeping "SsidBssTab" table for later-on ROAMing usage.
-		//
-		Bssidx = BssTableSearch(&pAd->ScanTab, Bssid, Channel);
-		if (Bssidx == BSS_NOT_FOUND)
-		{
-			// discover new AP of this network, create BSS entry
-			Bssidx = BssTableSetEntry(pAd, &pAd->ScanTab, Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
-						 &CfParm, AtimWin, CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen,
-						&HtCapability, &AddHtInfo,HtCapabilityLen,AddHtInfoLen,NewExtChannelOffset, Channel,
-						RealRssi, TimeStamp, CkipFlag, &EdcaParm, &QosCapability,
-						&QbssLoad, LenVIE, pVIE);
-			if (Bssidx == BSS_NOT_FOUND) // return if BSS table full
-				return;
-
-			NdisMoveMemory(pAd->ScanTab.BssEntry[Bssidx].PTSF, &Elem->Msg[24], 4);
-			NdisMoveMemory(&pAd->ScanTab.BssEntry[Bssidx].TTSF[0], &Elem->TimeStamp.u.LowPart, 4);
-			NdisMoveMemory(&pAd->ScanTab.BssEntry[Bssidx].TTSF[4], &Elem->TimeStamp.u.LowPart, 4);
-
-
-
-		}
-
-		if ((pAd->CommonCfg.bIEEE80211H == 1) && (NewChannel != 0) && (Channel != NewChannel))
-		{
-			// Switching to channel 1 can prevent from rescanning the current channel immediately (by auto reconnection).
-			// In addition, clear the MLME queue and the scan table to discard the RX packets and previous scanning results.
-			AsicSwitchChannel(pAd, 1, FALSE);
-			AsicLockChannel(pAd, 1);
-		    LinkDown(pAd, FALSE);
-			MlmeQueueInit(&pAd->Mlme.Queue);
-			BssTableInit(&pAd->ScanTab);
-		    RTMPusecDelay(1000000);		// use delay to prevent STA do reassoc
-
-			// channel sanity check
-			for (index = 0 ; index < pAd->ChannelListNum; index++)
-			{
-				if (pAd->ChannelList[index].Channel == NewChannel)
-				{
-					pAd->ScanTab.BssEntry[Bssidx].Channel = NewChannel;
-					pAd->CommonCfg.Channel = NewChannel;
-					AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE);
-					AsicLockChannel(pAd, pAd->CommonCfg.Channel);
-					DBGPRINT(RT_DEBUG_TRACE, ("PeerBeacon - STA receive channel switch announcement IE (New Channel =%d)\n", NewChannel));
-					break;
-				}
-			}
-
-			if (index >= pAd->ChannelListNum)
-			{
-				DBGPRINT_ERR(("PeerBeacon(can not find New Channel=%d in ChannelList[%d]\n", pAd->CommonCfg.Channel, pAd->ChannelListNum));
-			}
-		}
-
-		// if the ssid matched & bssid unmatched, we should select the bssid with large value.
-		// This might happened when two STA start at the same time
-		if ((! is_my_bssid) && ADHOC_ON(pAd))
-		{
-			INT	i;
-
-			// Add the safeguard against the mismatch of adhoc wep status
-			if (pAd->StaCfg.WepStatus != pAd->ScanTab.BssEntry[Bssidx].WepStatus)
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("SYNC - Not matched wep status %d %d\n", pAd->StaCfg.WepStatus, pAd->ScanTab.BssEntry[Bssidx].WepStatus));
-				DBGPRINT(RT_DEBUG_TRACE, ("bssid=%s\n", pAd->ScanTab.BssEntry[Bssidx].Bssid));
-				return;
-			}
-
-			// collapse into the ADHOC network which has bigger BSSID value.
-			for (i = 0; i < 6; i++)
-			{
-				if (Bssid[i] > pAd->CommonCfg.Bssid[i])
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("SYNC - merge to the IBSS with bigger BSSID=%02x:%02x:%02x:%02x:%02x:%02x\n",
-						Bssid[0], Bssid[1], Bssid[2], Bssid[3], Bssid[4], Bssid[5]));
-					AsicDisableSync(pAd);
-					COPY_MAC_ADDR(pAd->CommonCfg.Bssid, Bssid);
-					AsicSetBssid(pAd, pAd->CommonCfg.Bssid);
-					MakeIbssBeacon(pAd);        // re-build BEACON frame
-					AsicEnableIbssSync(pAd);    // copy BEACON frame to on-chip memory
-					is_my_bssid = TRUE;
-					break;
-				}
-				else if (Bssid[i] < pAd->CommonCfg.Bssid[i])
-					break;
-			}
-		}
-
-
-		NdisGetSystemUpTime(&Now);
-		pBss = &pAd->ScanTab.BssEntry[Bssidx];
-		pBss->Rssi = RealRssi;       // lastest RSSI
-		pBss->LastBeaconRxTime = Now;   // last RX timestamp
-
-		//
-		// BEACON from my BSSID - either IBSS or INFRA network
-		//
-		if (is_my_bssid)
-		{
-			RXWI_STRUC	RxWI;
-
-			pAd->StaCfg.DtimCount = DtimCount;
-			pAd->StaCfg.DtimPeriod = DtimPeriod;
-			pAd->StaCfg.LastBeaconRxTime = Now;
-
-
-			RxWI.RSSI0 = Elem->Rssi0;
-			RxWI.RSSI1 = Elem->Rssi1;
-			RxWI.RSSI2 = Elem->Rssi2;
-
-			Update_Rssi_Sample(pAd, &pAd->StaCfg.RssiSample, &RxWI);
-			if (AironetCellPowerLimit != 0xFF)
-			{
-				//
-				// We get the Cisco (ccx) "TxPower Limit" required
-				// Changed to appropriate TxPower Limit for Ciso Compatible Extensions
-				//
-				ChangeToCellPowerLimit(pAd, AironetCellPowerLimit);
-			}
-			else
-			{
-				//
-				// AironetCellPowerLimit equal to 0xFF means the Cisco (ccx) "TxPower Limit" not exist.
-				// Used the default TX Power Percentage, that set from UI.
-				//
-				pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault;
-			}
-
-			if (ADHOC_ON(pAd) && (CAP_IS_IBSS_ON(CapabilityInfo)))
-			{
-				UCHAR			MaxSupportedRateIn500Kbps = 0;
-				UCHAR			idx;
-				MAC_TABLE_ENTRY *pEntry;
-
-				// supported rates array may not be sorted. sort it and find the maximum rate
-			    for (idx=0; idx<SupRateLen; idx++)
-						{
-			        if (MaxSupportedRateIn500Kbps < (SupRate[idx] & 0x7f))
-			            MaxSupportedRateIn500Kbps = SupRate[idx] & 0x7f;
-						}
-
-				for (idx=0; idx<ExtRateLen; idx++)
-			    {
-			        if (MaxSupportedRateIn500Kbps < (ExtRate[idx] & 0x7f))
-			            MaxSupportedRateIn500Kbps = ExtRate[idx] & 0x7f;
-					}
-
-				// look up the existing table
-				pEntry = MacTableLookup(pAd, Addr2);
-
-				// Ad-hoc mode is using MAC address as BA session. So we need to continuously find newly joined adhoc station by receiving beacon.
-				// To prevent always check this, we use wcid == RESERVED_WCID to recognize it as newly joined adhoc station.
-				if ((ADHOC_ON(pAd) && (Elem->Wcid == RESERVED_WCID)) ||
-					(pEntry && ((pEntry->LastBeaconRxTime + ADHOC_ENTRY_BEACON_LOST_TIME) < Now)))
-						{
-					if (pEntry == NULL)
-						// Another adhoc joining, add to our MAC table.
-						pEntry = MacTableInsertEntry(pAd, Addr2, BSS0, FALSE);
-
-					if (StaAddMacTableEntry(pAd, pEntry, MaxSupportedRateIn500Kbps, &HtCapability, HtCapabilityLen, CapabilityInfo) == FALSE)
-					{
-						DBGPRINT(RT_DEBUG_TRACE, ("ADHOC - Add Entry failed.\n"));
-						return;
-					}
-
-					if (pEntry &&
-						(Elem->Wcid == RESERVED_WCID))
-				{
-						idx = pAd->StaCfg.DefaultKeyId;
-						RT28XX_STA_SECURITY_INFO_ADD(pAd, BSS0, idx, pEntry);
-				}
-				}
-
-				if (pEntry && pEntry->ValidAsCLI)
-					pEntry->LastBeaconRxTime = Now;
-
-				// At least another peer in this IBSS, declare MediaState as CONNECTED
-				if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))
-				{
-					OPSTATUS_SET_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED);
-
-					pAd->IndicateMediaState = NdisMediaStateConnected;
-					RTMP_IndicateMediaState(pAd);
-	                pAd->ExtraInfo = GENERAL_LINK_UP;
-					AsicSetBssid(pAd, pAd->CommonCfg.Bssid);
-
-					// 2003/03/12 - john
-					// Make sure this entry in "ScanTab" table, thus complies to Microsoft's policy that
-					// "site survey" result should always include the current connected network.
-					//
-					Bssidx = BssTableSearch(&pAd->ScanTab, Bssid, Channel);
-					if (Bssidx == BSS_NOT_FOUND)
-					{
-						Bssidx = BssTableSetEntry(pAd, &pAd->ScanTab, Bssid, Ssid, SsidLen, BssType, BeaconPeriod,
-									&CfParm, AtimWin, CapabilityInfo, SupRate, SupRateLen, ExtRate, ExtRateLen, &HtCapability,
-									&AddHtInfo, HtCapabilityLen, AddHtInfoLen, NewExtChannelOffset, Channel, RealRssi, TimeStamp, 0,
-									&EdcaParm, &QosCapability, &QbssLoad, LenVIE, pVIE);
-					}
-					DBGPRINT(RT_DEBUG_TRACE, ("ADHOC  fOP_STATUS_MEDIA_STATE_CONNECTED.\n"));
-				}
-			}
-
-			if (INFRA_ON(pAd))
-			{
-				BOOLEAN bUseShortSlot, bUseBGProtection;
-
-				// decide to use/change to -
-				//      1. long slot (20 us) or short slot (9 us) time
-				//      2. turn on/off RTS/CTS and/or CTS-to-self protection
-				//      3. short preamble
-
-				//bUseShortSlot = pAd->CommonCfg.bUseShortSlotTime && CAP_IS_SHORT_SLOT(CapabilityInfo);
-				bUseShortSlot = CAP_IS_SHORT_SLOT(CapabilityInfo);
-				if (bUseShortSlot != OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SHORT_SLOT_INUSED))
-					AsicSetSlotTime(pAd, bUseShortSlot);
-
-				bUseBGProtection = (pAd->CommonCfg.UseBGProtection == 1) ||    // always use
-								   ((pAd->CommonCfg.UseBGProtection == 0) && ERP_IS_USE_PROTECTION(Erp));
-
-				if (pAd->CommonCfg.Channel > 14) // always no BG protection in A-band. falsely happened when switching A/G band to a dual-band AP
-					bUseBGProtection = FALSE;
-
-				if (bUseBGProtection != OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED))
-				{
-					if (bUseBGProtection)
-					{
-						OPSTATUS_SET_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED);
-						AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, (OFDMSETPROTECT|CCKSETPROTECT|ALLN_SETPROTECT),FALSE,(pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1));
-					}
-					else
-					{
-						OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED);
-						AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, (OFDMSETPROTECT|CCKSETPROTECT|ALLN_SETPROTECT),TRUE,(pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1));
-					}
-
-					DBGPRINT(RT_DEBUG_WARN, ("SYNC - AP changed B/G protection to %d\n", bUseBGProtection));
-				}
-
-#ifdef DOT11_N_SUPPORT
-				// check Ht protection mode. and adhere to the Non-GF device indication by AP.
-				if ((AddHtInfoLen != 0) &&
-					((AddHtInfo.AddHtInfo2.OperaionMode != pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode) ||
-					(AddHtInfo.AddHtInfo2.NonGfPresent != pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent)))
-				{
-					pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent = AddHtInfo.AddHtInfo2.NonGfPresent;
-					pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode = AddHtInfo.AddHtInfo2.OperaionMode;
-					if (pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1)
-				{
-						AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, ALLN_SETPROTECT, FALSE, TRUE);
-					}
-					else
-						AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, ALLN_SETPROTECT, FALSE, FALSE);
-
-					DBGPRINT(RT_DEBUG_TRACE, ("SYNC - AP changed N OperaionMode to %d\n", pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode));
-				}
-#endif // DOT11_N_SUPPORT //
-
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED) &&
-					ERP_IS_USE_BARKER_PREAMBLE(Erp))
-				{
-					MlmeSetTxPreamble(pAd, Rt802_11PreambleLong);
-					DBGPRINT(RT_DEBUG_TRACE, ("SYNC - AP forced to use LONG preamble\n"));
-				}
-
-				if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED)    &&
-					(EdcaParm.bValid == TRUE)                          &&
-					(EdcaParm.EdcaUpdateCount != pAd->CommonCfg.APEdcaParm.EdcaUpdateCount))
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("SYNC - AP change EDCA parameters(from %d to %d)\n",
-						pAd->CommonCfg.APEdcaParm.EdcaUpdateCount,
-						EdcaParm.EdcaUpdateCount));
-					AsicSetEdcaParm(pAd, &EdcaParm);
-				}
-
-				// copy QOS related information
-				NdisMoveMemory(&pAd->CommonCfg.APQbssLoad, &QbssLoad, sizeof(QBSS_LOAD_PARM));
-				NdisMoveMemory(&pAd->CommonCfg.APQosCapability, &QosCapability, sizeof(QOS_CAPABILITY_PARM));
-			}
-
-			// only INFRASTRUCTURE mode support power-saving feature
-			if ((INFRA_ON(pAd) && (pAd->StaCfg.Psm == PWR_SAVE)) || (pAd->CommonCfg.bAPSDForcePowerSave))
-			{
-				UCHAR FreeNumber;
-				//  1. AP has backlogged unicast-to-me frame, stay AWAKE, send PSPOLL
-				//  2. AP has backlogged broadcast/multicast frame and we want those frames, stay AWAKE
-				//  3. we have outgoing frames in TxRing or MgmtRing, better stay AWAKE
-				//  4. Psm change to PWR_SAVE, but AP not been informed yet, we better stay AWAKE
-				//  5. otherwise, put PHY back to sleep to save battery.
-				if (MessageToMe)
-				{
-					if (pAd->CommonCfg.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable &&
-						pAd->CommonCfg.bAPSDAC_BE && pAd->CommonCfg.bAPSDAC_BK && pAd->CommonCfg.bAPSDAC_VI && pAd->CommonCfg.bAPSDAC_VO)
-					{
-						pAd->CommonCfg.bNeedSendTriggerFrame = TRUE;
-					}
-					else
-						RT28XX_PS_POLL_ENQUEUE(pAd);
-				}
-				else if (BcastFlag && (DtimCount == 0) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM))
-				{
-				}
-				else if ((pAd->TxSwQueue[QID_AC_BK].Number != 0)													||
-						(pAd->TxSwQueue[QID_AC_BE].Number != 0)														||
-						(pAd->TxSwQueue[QID_AC_VI].Number != 0)														||
-						(pAd->TxSwQueue[QID_AC_VO].Number != 0)														||
-						(RTMPFreeTXDRequest(pAd, QID_AC_BK, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS)	||
-						(RTMPFreeTXDRequest(pAd, QID_AC_BE, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS)	||
-						(RTMPFreeTXDRequest(pAd, QID_AC_VI, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS)	||
-						(RTMPFreeTXDRequest(pAd, QID_AC_VO, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS)	||
-						(RTMPFreeTXDRequest(pAd, QID_MGMT, MGMT_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS))
-				{
-					// TODO: consider scheduled HCCA. might not be proper to use traditional DTIM-based power-saving scheme
-					// can we cheat here (i.e. just check MGMT & AC_BE) for better performance?
-				}
-				else
-				{
-					USHORT NextDtim = DtimCount;
-
-					if (NextDtim == 0)
-						NextDtim = DtimPeriod;
-
-					TbttNumToNextWakeUp = pAd->StaCfg.DefaultListenCount;
-					if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM) && (TbttNumToNextWakeUp > NextDtim))
-						TbttNumToNextWakeUp = NextDtim;
-
-					if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE))
-					{
-						AsicSleepThenAutoWakeup(pAd, TbttNumToNextWakeUp);
-					}
-				}
-			}
-		}
-		// not my BSSID, ignore it
-	}
-	// sanity check fail, ignore this frame
-}
-
-/*
-	==========================================================================
-	Description:
-		Receive PROBE REQ from remote peer when operating in IBSS mode
-	==========================================================================
- */
-VOID PeerProbeReqAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	UCHAR         Addr2[MAC_ADDR_LEN];
-	CHAR          Ssid[MAX_LEN_OF_SSID];
-	UCHAR         SsidLen;
-#ifdef DOT11_N_SUPPORT
-	UCHAR		  HtLen, AddHtLen, NewExtLen;
-#endif // DOT11_N_SUPPORT //
-	HEADER_802_11 ProbeRspHdr;
-	NDIS_STATUS   NStatus;
-	PUCHAR        pOutBuffer = NULL;
-	ULONG         FrameLen = 0;
-	LARGE_INTEGER FakeTimestamp;
-	UCHAR         DsLen = 1, IbssLen = 2;
-	UCHAR         LocalErpIe[3] = {IE_ERP, 1, 0};
-	BOOLEAN       Privacy;
-	USHORT        CapabilityInfo;
-	UCHAR		  RSNIe = IE_WPA;
-
-	if (! ADHOC_ON(pAd))
-		return;
-
-	if (PeerProbeReqSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, Ssid, &SsidLen))
-	{
-		if ((SsidLen == 0) || SSID_EQUAL(Ssid, SsidLen, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen))
-		{
-			// allocate and send out ProbeRsp frame
-			NStatus = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-			if (NStatus != NDIS_STATUS_SUCCESS)
-				return;
-
-			//pAd->StaCfg.AtimWin = 0;  // ??????
-
-			Privacy = (pAd->StaCfg.WepStatus == Ndis802_11Encryption1Enabled) ||
-					  (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
-					  (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled);
-			CapabilityInfo = CAP_GENERATE(0, 1, Privacy, (pAd->CommonCfg.TxPreamble == Rt802_11PreambleShort), 0, 0);
-
-			MakeOutgoingFrame(pOutBuffer,                   &FrameLen,
-							  sizeof(HEADER_802_11),        &ProbeRspHdr,
-							  TIMESTAMP_LEN,                &FakeTimestamp,
-							  2,                            &pAd->CommonCfg.BeaconPeriod,
-							  2,                            &CapabilityInfo,
-							  1,                            &SsidIe,
-							  1,                            &pAd->CommonCfg.SsidLen,
-							  pAd->CommonCfg.SsidLen,       pAd->CommonCfg.Ssid,
-							  1,                            &SupRateIe,
-							  1,                            &pAd->StaActive.SupRateLen,
-							  pAd->StaActive.SupRateLen,    pAd->StaActive.SupRate,
-							  1,                            &DsIe,
-							  1,                            &DsLen,
-							  1,                            &pAd->CommonCfg.Channel,
-							  1,                            &IbssIe,
-							  1,                            &IbssLen,
-							  2,                            &pAd->StaActive.AtimWin,
-							  END_OF_ARGS);
-
-			if (pAd->StaActive.ExtRateLen)
-			{
-				ULONG tmp;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,        &tmp,
-								  3,                            LocalErpIe,
-								  1,                            &ExtRateIe,
-								  1,                            &pAd->StaActive.ExtRateLen,
-								  pAd->StaActive.ExtRateLen,    &pAd->StaActive.ExtRate,
-								  END_OF_ARGS);
-				FrameLen += tmp;
-			}
-
-			// If adhoc secruity is set for WPA-None, append the cipher suite IE
-			if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-			{
-				ULONG tmp;
-				MakeOutgoingFrame(pOutBuffer + FrameLen,        	&tmp,
-						  			1,                              &RSNIe,
-						  			1,                            	&pAd->StaCfg.RSNIE_Len,
-						  			pAd->StaCfg.RSNIE_Len,      	pAd->StaCfg.RSN_IE,
-						  			END_OF_ARGS);
-				FrameLen += tmp;
-			}
-#ifdef DOT11_N_SUPPORT
-			if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED)
-			{
-				ULONG TmpLen;
-				UCHAR	BROADCOM[4] = {0x0, 0x90, 0x4c, 0x33};
-				HtLen = sizeof(pAd->CommonCfg.HtCapability);
-				AddHtLen = sizeof(pAd->CommonCfg.AddHTInfo);
-				NewExtLen = 1;
-				//New extension channel offset IE is included in Beacon, Probe Rsp or channel Switch Announcement Frame
-				if (pAd->bBroadComHT == TRUE)
-				{
-					MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-								  1,                                &WpaIe,
-								  4,                                &BROADCOM[0],
-								 pAd->MlmeAux.HtCapabilityLen,          &pAd->MlmeAux.HtCapability,
-								  END_OF_ARGS);
-				}
-				else
-				{
-				MakeOutgoingFrame(pOutBuffer + FrameLen,            &TmpLen,
-								  1,                                &HtCapIe,
-								  1,                                &HtLen,
-								 sizeof(HT_CAPABILITY_IE),          &pAd->CommonCfg.HtCapability,
-								  1,                                &AddHtInfoIe,
-								  1,                                &AddHtLen,
-								 sizeof(ADD_HT_INFO_IE),          &pAd->CommonCfg.AddHTInfo,
-								  1,                                &NewExtChanIe,
-								  1,                                &NewExtLen,
-								 sizeof(NEW_EXT_CHAN_IE),          &pAd->CommonCfg.NewExtChanOffset,
-								  END_OF_ARGS);
-				}
-				FrameLen += TmpLen;
-			}
-#endif // DOT11_N_SUPPORT //
-			MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-			MlmeFreeMemory(pAd, pOutBuffer);
-		}
-	}
-}
-
-VOID BeaconTimeoutAtJoinAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("SYNC - BeaconTimeoutAtJoinAction\n"));
-	pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-	Status = MLME_REJ_TIMEOUT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_JOIN_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-		Scan timeout procedure. basically add channel index by 1 and rescan
-	==========================================================================
- */
-VOID ScanTimeoutAction(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	pAd->MlmeAux.Channel = NextChannel(pAd, pAd->MlmeAux.Channel);
-
-	// Only one channel scanned for CISCO beacon request
-	if ((pAd->MlmeAux.ScanType == SCAN_CISCO_ACTIVE) ||
-		(pAd->MlmeAux.ScanType == SCAN_CISCO_PASSIVE) ||
-		(pAd->MlmeAux.ScanType == SCAN_CISCO_NOISE) ||
-		(pAd->MlmeAux.ScanType == SCAN_CISCO_CHANNEL_LOAD))
-		pAd->MlmeAux.Channel = 0;
-
-	// this routine will stop if pAd->MlmeAux.Channel == 0
-	ScanNextChannel(pAd);
-}
-
-/*
-	==========================================================================
-	Description:
-	==========================================================================
- */
-VOID InvalidStateWhenScan(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("AYNC - InvalidStateWhenScan(state=%ld). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState));
-	pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-	==========================================================================
- */
-VOID InvalidStateWhenJoin(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("InvalidStateWhenJoin(state=%ld). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState));
-	pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_JOIN_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-	==========================================================================
- */
-VOID InvalidStateWhenStart(
-	IN PRTMP_ADAPTER pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	USHORT Status;
-	DBGPRINT(RT_DEBUG_TRACE, ("InvalidStateWhenStart(state=%ld). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState));
-	pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE;
-	Status = MLME_STATE_MACHINE_REJECT;
-	MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_START_CONF, 2, &Status);
-}
-
-/*
-	==========================================================================
-	Description:
-
-	IRQL = DISPATCH_LEVEL
-
-	==========================================================================
- */
-VOID EnqueuePsPoll(
-	IN PRTMP_ADAPTER pAd)
-{
-#ifdef RALINK_ATE
-    if (ATE_ON(pAd))
-    {
-		return;
-    }
-#endif // RALINK_ATE //
-
-
-	if (pAd->StaCfg.WindowsPowerMode == Ndis802_11PowerModeLegacy_PSP)
-    	pAd->PsPollFrame.FC.PwrMgmt = PWR_SAVE;
-	MiniportMMRequest(pAd, 0, (PUCHAR)&pAd->PsPollFrame, sizeof(PSPOLL_FRAME));
-}
-
-
-/*
-	==========================================================================
-	Description:
-	==========================================================================
- */
-VOID EnqueueProbeRequest(
-	IN PRTMP_ADAPTER pAd)
-{
-	NDIS_STATUS     NState;
-	PUCHAR          pOutBuffer;
-	ULONG           FrameLen = 0;
-	HEADER_802_11   Hdr80211;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("force out a ProbeRequest ...\n"));
-
-	NState = MlmeAllocateMemory(pAd, &pOutBuffer);  //Get an unused nonpaged memory
-	if (NState == NDIS_STATUS_SUCCESS)
-	{
-		MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, BROADCAST_ADDR, BROADCAST_ADDR);
-
-		// this ProbeRequest explicitly specify SSID to reduce unwanted ProbeResponse
-		MakeOutgoingFrame(pOutBuffer,                     &FrameLen,
-						  sizeof(HEADER_802_11),          &Hdr80211,
-						  1,                              &SsidIe,
-						  1,                              &pAd->CommonCfg.SsidLen,
-						  pAd->CommonCfg.SsidLen,		  pAd->CommonCfg.Ssid,
-						  1,                              &SupRateIe,
-						  1,                              &pAd->StaActive.SupRateLen,
-						  pAd->StaActive.SupRateLen,      pAd->StaActive.SupRate,
-						  END_OF_ARGS);
-		MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen);
-		MlmeFreeMemory(pAd, pOutBuffer);
-	}
-
-}
-
-#ifdef DOT11_N_SUPPORT
-#ifdef DOT11N_DRAFT3
-VOID BuildEffectedChannelList(
-	IN PRTMP_ADAPTER pAd)
-{
-	UCHAR		EChannel[11];
-	UCHAR		i, j, k;
-	UCHAR		UpperChannel = 0, LowerChannel = 0;
-
-	RTMPZeroMemory(EChannel, 11);
-	i = 0;
-	// Find upper channel and lower channel.
-	if (pAd->CommonCfg.CentralChannel < pAd->CommonCfg.Channel)
-	{
-		UpperChannel = pAd->CommonCfg.Channel;
-		LowerChannel = pAd->CommonCfg.CentralChannel;
-	}
-	else if (pAd->CommonCfg.CentralChannel > pAd->CommonCfg.Channel)
-	{
-		UpperChannel = pAd->CommonCfg.CentralChannel;
-		LowerChannel = pAd->CommonCfg.Channel;
-	}
-	else
-	{
-		return;
-	}
-
-	// Record channels that is below lower channel..
-	if (LowerChannel > 1)
-	{
-		EChannel[0] = LowerChannel - 1;
-		i = 1;
-		if (LowerChannel > 2)
-		{
-			EChannel[1] = LowerChannel - 2;
-			i = 2;
-			if (LowerChannel > 3)
-			{
-				EChannel[2] = LowerChannel - 3;
-				i = 3;
-			}
-		}
-	}
-	// Record channels that is between  lower channel and upper channel.
-	for (k = LowerChannel;k < UpperChannel;k++)
-	{
-		EChannel[i] = k;
-		i++;
-	}
-	// Record channels that is above upper channel..
-	if (LowerChannel < 11)
-	{
-		EChannel[i] = UpperChannel + 1;
-		i++;
-		if (LowerChannel < 10)
-		{
-			EChannel[i] = LowerChannel + 2;
-			i++;
-			if (LowerChannel < 9)
-			{
-				EChannel[i] = LowerChannel + 3;
-				i++;
-			}
-		}
-	}
-	//
-	for (j = 0;j < i;j++)
-	{
-		for (k = 0;k < pAd->ChannelListNum;k++)
-		{
-			if (pAd->ChannelList[k].Channel == EChannel[j])
-			{
-				pAd->ChannelList[k].bEffectedChannel = TRUE;
-				DBGPRINT(RT_DEBUG_TRACE,(" EffectedChannel( =%d)\n", EChannel[j]));
-				break;
-			}
-		}
-	}
-}
-#endif // DOT11N_DRAFT3 //
-#endif // DOT11_N_SUPPORT //
-
-BOOLEAN ScanRunning(
-		IN PRTMP_ADAPTER pAd)
-{
-	return (pAd->Mlme.SyncMachine.CurrState == SCAN_LISTEN) ? TRUE : FALSE;
-}
-
+#include "../../rt2870/sta/sync.c"
diff --git a/drivers/staging/rt3070/sta/wpa.c b/drivers/staging/rt3070/sta/wpa.c
index 63d0830..95543bb 100644
--- a/drivers/staging/rt3070/sta/wpa.c
+++ b/drivers/staging/rt3070/sta/wpa.c
@@ -1,2099 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	wpa.c
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Jan	Lee		03-07-22		Initial
-	Paul Lin	03-11-28		Modify for supplicant
-*/
-#include "../rt_config.h"
-
-#define		WPARSNIE	0xdd
-#define		WPA2RSNIE	0x30
-
-//extern UCHAR BIT8[];
-UCHAR	CipherWpaPskTkip[] = {
-		0xDD, 0x16,				// RSN IE
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x02,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x02,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x02	// authentication
-		};
-UCHAR	CipherWpaPskTkipLen = (sizeof(CipherWpaPskTkip) / sizeof(UCHAR));
-
-UCHAR	CipherWpaPskAes[] = {
-		0xDD, 0x16, 			// RSN IE
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x04,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x04,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x02	// authentication
-		};
-UCHAR	CipherWpaPskAesLen = (sizeof(CipherWpaPskAes) / sizeof(UCHAR));
-
-UCHAR	CipherSuiteCiscoCCKM[] = {
-		0xDD, 0x16,				// RSN IE
-		0x00, 0x50, 0xf2, 0x01, // oui
-		0x01, 0x00,				// Version
-		0x00, 0x40, 0x96, 0x01, // Multicast
-		0x01, 0x00,				// Number of uicast
-		0x00, 0x40, 0x96, 0x01, // unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x40, 0x96, 0x00  // Authentication
-		};
-UCHAR	CipherSuiteCiscoCCKMLen = (sizeof(CipherSuiteCiscoCCKM) / sizeof(UCHAR));
-
-UCHAR	CipherSuiteCiscoCCKM24[] = {
-		0xDD, 0x18,				// RSN IE
-		0x00, 0x50, 0xf2, 0x01, // oui
-		0x01, 0x00,				// Version
-		0x00, 0x40, 0x96, 0x01, // Multicast
-		0x01, 0x00,				// Number of uicast
-		0x00, 0x40, 0x96, 0x01, // unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x40, 0x96, 0x00,
-		0x28, 0x00// Authentication
-		};
-
-UCHAR	CipherSuiteCiscoCCKM24Len = (sizeof(CipherSuiteCiscoCCKM24) / sizeof(UCHAR));
-
-UCHAR	CipherSuiteCCXTkip[] = {
-		0xDD, 0x16,				// RSN IE
-		0x00, 0x50, 0xf2, 0x01,	// oui
-		0x01, 0x00,				// Version
-		0x00, 0x50, 0xf2, 0x02,	// Multicast
-		0x01, 0x00,				// Number of unicast
-		0x00, 0x50, 0xf2, 0x02,	// unicast
-		0x01, 0x00,				// number of authentication method
-		0x00, 0x50, 0xf2, 0x01	// authentication
-		};
-UCHAR	CipherSuiteCCXTkipLen = (sizeof(CipherSuiteCCXTkip) / sizeof(UCHAR));
-
-UCHAR	CCX_LLC_HDR[] = {0xAA, 0xAA, 0x03, 0x00, 0x40, 0x96, 0x00, 0x02};
-UCHAR	LLC_NORMAL[] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00};
-
-UCHAR	EAPOL_FRAME[] = {0x88, 0x8E};
-
-BOOLEAN CheckRSNIE(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pData,
-	IN  UCHAR           DataLen,
-	OUT	UCHAR			*Offset);
-
-void inc_byte_array(UCHAR *counter, int len);
-
-/*
-	========================================================================
-
-	Routine Description:
-		Classify WPA EAP message type
-
-	Arguments:
-		EAPType		Value of EAP message type
-		MsgType		Internal Message definition for MLME state machine
-
-	Return Value:
-		TRUE		Found appropriate message type
-		FALSE		No appropriate message type
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-		All these constants are defined in wpa.h
-		For supplicant, there is only EAPOL Key message avaliable
-
-	========================================================================
-*/
-BOOLEAN	WpaMsgTypeSubst(
-	IN	UCHAR	EAPType,
-	OUT	INT		*MsgType)
-{
-	switch (EAPType)
-	{
-		case EAPPacket:
-			*MsgType = MT2_EAPPacket;
-			break;
-		case EAPOLStart:
-			*MsgType = MT2_EAPOLStart;
-			break;
-		case EAPOLLogoff:
-			*MsgType = MT2_EAPOLLogoff;
-			break;
-		case EAPOLKey:
-			*MsgType = MT2_EAPOLKey;
-			break;
-		case EAPOLASFAlert:
-			*MsgType = MT2_EAPOLASFAlert;
-			break;
-		default:
-			return FALSE;
-	}
-	return TRUE;
-}
-
-/*
-	==========================================================================
-	Description:
-		association	state machine init,	including state	transition and timer init
-	Parameters:
-		S -	pointer	to the association state machine
-	==========================================================================
- */
-VOID WpaPskStateMachineInit(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	STATE_MACHINE *S,
-	OUT	STATE_MACHINE_FUNC Trans[])
-{
-	StateMachineInit(S,	Trans, MAX_WPA_PSK_STATE, MAX_WPA_PSK_MSG, (STATE_MACHINE_FUNC)Drop, WPA_PSK_IDLE, WPA_MACHINE_BASE);
-	StateMachineSetAction(S, WPA_PSK_IDLE, MT2_EAPOLKey, (STATE_MACHINE_FUNC)WpaEAPOLKeyAction);
-}
-
-/*
-	==========================================================================
-	Description:
-		This is	state machine function.
-		When receiving EAPOL packets which is  for 802.1x key management.
-		Use	both in	WPA, and WPAPSK	case.
-		In this	function, further dispatch to different	functions according	to the received	packet.	 3 categories are :
-		  1.  normal 4-way pairwisekey and 2-way groupkey handshake
-		  2.  MIC error	(Countermeasures attack)  report packet	from STA.
-		  3.  Request for pairwise/group key update	from STA
-	Return:
-	==========================================================================
-*/
-VOID WpaEAPOLKeyAction(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-
-{
-	INT             MsgType = EAPOL_MSG_INVALID;
-	PKEY_DESCRIPTER pKeyDesc;
-	PHEADER_802_11  pHeader; //red
-	UCHAR           ZeroReplay[LEN_KEY_DESC_REPLAY];
-	UCHAR EapolVr;
-	KEY_INFO		peerKeyInfo;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("-----> WpaEAPOLKeyAction\n"));
-
-	// Get 802.11 header first
-	pHeader = (PHEADER_802_11) Elem->Msg;
-
-	// Get EAPoL-Key Descriptor
-	pKeyDesc = (PKEY_DESCRIPTER) &Elem->Msg[(LENGTH_802_11 + LENGTH_802_1_H + LENGTH_EAPOL_H)];
-
-	NdisZeroMemory((PUCHAR)&peerKeyInfo, sizeof(peerKeyInfo));
-	NdisMoveMemory((PUCHAR)&peerKeyInfo, (PUCHAR)&pKeyDesc->KeyInfo, sizeof(KEY_INFO));
-
-	*((USHORT *)&peerKeyInfo) = cpu2le16(*((USHORT *)&peerKeyInfo));
-
-
-	// 1. Check EAPOL frame version and type
-	EapolVr	= (UCHAR) Elem->Msg[LENGTH_802_11+LENGTH_802_1_H];
-
-    if (((EapolVr != EAPOL_VER) && (EapolVr != EAPOL_VER2)) || ((pKeyDesc->Type != WPA1_KEY_DESC) && (pKeyDesc->Type != WPA2_KEY_DESC)))
-	{
-        DBGPRINT(RT_DEBUG_ERROR, ("Key descripter does not match with WPA rule\n"));
-			return;
-	}
-
-	// First validate replay counter, only accept message with larger replay counter
-	// Let equal pass, some AP start with all zero replay counter
-	NdisZeroMemory(ZeroReplay, LEN_KEY_DESC_REPLAY);
-
-	if((RTMPCompareMemory(pKeyDesc->ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1) &&
-		(RTMPCompareMemory(pKeyDesc->ReplayCounter, ZeroReplay, LEN_KEY_DESC_REPLAY) != 0))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("   ReplayCounter not match   \n"));
-		return;
-	}
-
-	// Process WPA2PSK frame
-	if(pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-	{
-		if((peerKeyInfo.KeyType == PAIRWISEKEY) &&
-			(peerKeyInfo.EKD_DL == 0) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 0) &&
-			(peerKeyInfo.Secure == 0) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_PAIR_MSG_1;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Pairwise Message 1\n"));
-		} else if((peerKeyInfo.KeyType == PAIRWISEKEY) &&
-			(peerKeyInfo.EKD_DL  == 1) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 1) &&
-			(peerKeyInfo.Secure == 1) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_PAIR_MSG_3;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Pairwise Message 3\n"));
-		} else if((peerKeyInfo.KeyType == GROUPKEY) &&
-			(peerKeyInfo.EKD_DL == 1) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 1) &&
-			(peerKeyInfo.Secure == 1) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_GROUP_MSG_1;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Group Message 1\n"));
-		}
-
-		// We will assume link is up (assoc suceess and port not secured).
-		// All state has to be able to process message from previous state
-		switch(pAd->StaCfg.WpaState)
-		{
-		case SS_START:
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-				Wpa2PairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-			}
-			break;
-
-		case SS_WAIT_MSG_3:
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-				Wpa2PairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-			}
-			else if(MsgType == EAPOL_PAIR_MSG_3)
-			{
-				Wpa2PairMsg3Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_GROUP;
-			}
-			break;
-
-		case SS_WAIT_GROUP:		// When doing group key exchange
-		case SS_FINISH:			// This happened when update group key
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-			    // Reset port secured variable
-				pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-				Wpa2PairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-			}
-			else if(MsgType == EAPOL_PAIR_MSG_3)
-			{
-			    // Reset port secured variable
-				pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-				Wpa2PairMsg3Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_GROUP;
-			}
-			else if(MsgType == EAPOL_GROUP_MSG_1)
-			{
-				WpaGroupMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_FINISH;
-			}
-			break;
-
-		default:
-			break;
-		}
-	}
-	// Process WPAPSK Frame
-	// Classify message Type, either pairwise message 1, 3, or group message 1 for supplicant
-	else if(pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)
-	{
-		if((peerKeyInfo.KeyType == PAIRWISEKEY) &&
-			(peerKeyInfo.KeyIndex == 0) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 0) &&
-			(peerKeyInfo.Secure == 0) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_PAIR_MSG_1;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Pairwise Message 1\n"));
-		}
-		else if((peerKeyInfo.KeyType == PAIRWISEKEY) &&
-			(peerKeyInfo.KeyIndex == 0) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 1) &&
-			(peerKeyInfo.Secure == 0) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_PAIR_MSG_3;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Pairwise Message 3\n"));
-		}
-		else if((peerKeyInfo.KeyType == GROUPKEY) &&
-			(peerKeyInfo.KeyIndex != 0) &&
-			(peerKeyInfo.KeyAck == 1) &&
-			(peerKeyInfo.KeyMic == 1) &&
-			(peerKeyInfo.Secure == 1) &&
-			(peerKeyInfo.Error == 0) &&
-			(peerKeyInfo.Request == 0))
-		{
-			MsgType = EAPOL_GROUP_MSG_1;
-			DBGPRINT(RT_DEBUG_TRACE, ("Receive EAPOL Key Group Message 1\n"));
-		}
-
-		// We will assume link is up (assoc suceess and port not secured).
-		// All state has to be able to process message from previous state
-		switch(pAd->StaCfg.WpaState)
-		{
-		case SS_START:
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-				WpaPairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-			}
-			break;
-
-		case SS_WAIT_MSG_3:
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-				WpaPairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-			}
-			else if(MsgType == EAPOL_PAIR_MSG_3)
-			{
-				WpaPairMsg3Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_GROUP;
-			}
-			break;
-
-		case SS_WAIT_GROUP:		// When doing group key exchange
-		case SS_FINISH:			// This happened when update group key
-			if(MsgType == EAPOL_PAIR_MSG_1)
-			{
-				WpaPairMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_MSG_3;
-				// Reset port secured variable
-				pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			}
-			else if(MsgType == EAPOL_PAIR_MSG_3)
-			{
-				WpaPairMsg3Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_WAIT_GROUP;
-				// Reset port secured variable
-				pAd->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			}
-			else if(MsgType == EAPOL_GROUP_MSG_1)
-			{
-				WpaGroupMsg1Action(pAd, Elem);
-				pAd->StaCfg.WpaState = SS_FINISH;
-			}
-			break;
-
-		default:
-			break;
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<----- WpaEAPOLKeyAction\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Process Pairwise key 4-way handshaking
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		Elem		Message body
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	WpaPairMsg1Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem)
-{
-	PHEADER_802_11      pHeader;
-	UCHAR				*mpool, *PTK, *digest;
-	PUCHAR              pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG               FrameLen = 0;
-	PEAPOL_PACKET       pMsg1;
-	EAPOL_PACKET        Packet;
-	UCHAR               Mic[16];
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaPairMsg1Action ----->\n"));
-
-	// allocate memory pool
-	os_alloc_mem(pAd, (PUCHAR *)&mpool, 256);
-
-	if (mpool == NULL)
-		return;
-
-	// PTK Len = 80.
-	PTK = (UCHAR *) ROUND_UP(mpool, 4);
-	// digest Len = 80.
-	digest = (UCHAR *) ROUND_UP(PTK + 80, 4);
-
-	pHeader = (PHEADER_802_11) Elem->Msg;
-
-	// Process message 1 from authenticator
-	pMsg1 = (PEAPOL_PACKET) &Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
-
-	// 1. Save Replay counter, it will use to verify message 3 and construct message 2
-	NdisMoveMemory(pAd->StaCfg.ReplayCounter, pMsg1->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// 2. Save ANonce
-	NdisMoveMemory(pAd->StaCfg.ANonce, pMsg1->KeyDesc.KeyNonce, LEN_KEY_DESC_NONCE);
-
-	// Generate random SNonce
-	GenRandom(pAd, pAd->CurrentAddress, pAd->StaCfg.SNonce);
-
-	// Calc PTK(ANonce, SNonce)
-	WpaCountPTK(pAd,
-		pAd->StaCfg.PMK,
-		pAd->StaCfg.ANonce,
-		pAd->CommonCfg.Bssid,
-		pAd->StaCfg.SNonce,
-		pAd->CurrentAddress,
-		PTK,
-		LEN_PTK);
-
-	// Save key to PTK entry
-	NdisMoveMemory(pAd->StaCfg.PTK, PTK, LEN_PTK);
-
-	// init 802.3 header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero Message 2 body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-	//
-	// Message 2 as  EAPOL-Key(0,1,0,0,0,P,0,SNonce,MIC,RSN IE)
-	//
-	Packet.KeyDesc.Type = WPA1_KEY_DESC;
-	// 1. Key descriptor version and appropriate RSN IE
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 2;
-	}
-	else	  // TKIP
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 1;
-	}
-
-	// fill in Data Material and its length
-	Packet.KeyDesc.KeyData[0] = IE_WPA;
-	Packet.KeyDesc.KeyData[1] = pAd->StaCfg.RSNIE_Len;
-	Packet.KeyDesc.KeyDataLen[1] = pAd->StaCfg.RSNIE_Len + 2;
-	NdisMoveMemory(&Packet.KeyDesc.KeyData[2], pAd->StaCfg.RSN_IE, pAd->StaCfg.RSNIE_Len);
-
-	// Update packet length after decide Key data payload
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE + Packet.KeyDesc.KeyDataLen[1];
-
-	// Update Key length
-	Packet.KeyDesc.KeyLength[0] = pMsg1->KeyDesc.KeyLength[0];
-	Packet.KeyDesc.KeyLength[1] = pMsg1->KeyDesc.KeyLength[1];
-	// 2. Key Type PeerKey
-	Packet.KeyDesc.KeyInfo.KeyType = PAIRWISEKEY;
-
-	// 3. KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-
-	//Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-
-	// 4. Fill SNonce
-	NdisMoveMemory(Packet.KeyDesc.KeyNonce, pAd->StaCfg.SNonce, LEN_KEY_DESC_NONCE);
-
-	// 5. Key Replay Count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Send EAPOL(0, 1, 0, 0, 0, P, 0, SNonce, MIC, RSN_IE)
-	// Out buffer for transmitting message 2
-	MlmeAllocateMemory(pAd, (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-	{
-		os_free_mem(pAd, mpool);
-		return;
-	}
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		Packet.Body_Len[1] + 4,    &Packet,
-		END_OF_ARGS);
-
-	// 6. Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{	// AES
-
-		HMAC_SHA1(pOutBuffer, FrameLen, PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{	// TKIP
-		hmac_md5(PTK,  LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-	//hex_dump("MIC", Mic, LEN_KEY_DESC_MIC);
-
-		MakeOutgoingFrame(pOutBuffer,           	&FrameLen,
-			  			LENGTH_802_3,     			&Header802_3,
-						Packet.Body_Len[1] + 4,    &Packet,
-						END_OF_ARGS);
-
-
-	// 5. Copy frame to Tx ring and send Msg 2 to authenticator
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, TRUE);
-
-	MlmeFreeMemory(pAd, (PUCHAR)pOutBuffer);
-	os_free_mem(pAd, (PUCHAR)mpool);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaPairMsg1Action <-----\n"));
-}
-
-VOID Wpa2PairMsg1Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem)
-{
-	PHEADER_802_11      pHeader;
-	UCHAR				*mpool, *PTK, *digest;
-	PUCHAR              pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG               FrameLen = 0;
-	PEAPOL_PACKET       pMsg1;
-	EAPOL_PACKET        Packet;
-	UCHAR               Mic[16];
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Wpa2PairMsg1Action ----->\n"));
-
-	// allocate memory pool
-	os_alloc_mem(pAd, (PUCHAR *)&mpool, 256);
-
-	if (mpool == NULL)
-		return;
-
-	// PTK Len = 80.
-	PTK = (UCHAR *) ROUND_UP(mpool, 4);
-	// digest Len = 80.
-	digest = (UCHAR *) ROUND_UP(PTK + 80, 4);
-
-	pHeader = (PHEADER_802_11) Elem->Msg;
-
-	// Process message 1 from authenticator
-		pMsg1 = (PEAPOL_PACKET)	&Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
-
-	// 1. Save Replay counter, it will use to verify message 3 and construct message 2
-	NdisMoveMemory(pAd->StaCfg.ReplayCounter, pMsg1->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// 2. Save ANonce
-	NdisMoveMemory(pAd->StaCfg.ANonce, pMsg1->KeyDesc.KeyNonce, LEN_KEY_DESC_NONCE);
-
-	// Generate random SNonce
-	GenRandom(pAd, pAd->CurrentAddress, pAd->StaCfg.SNonce);
-
-	if(pMsg1->KeyDesc.KeyDataLen[1] > 0 )
-	{
-		// cached PMKID
-	}
-
-	// Calc PTK(ANonce, SNonce)
-	WpaCountPTK(pAd,
-		pAd->StaCfg.PMK,
-		pAd->StaCfg.ANonce,
-		pAd->CommonCfg.Bssid,
-		pAd->StaCfg.SNonce,
-		pAd->CurrentAddress,
-		PTK,
-		LEN_PTK);
-
-	// Save key to PTK entry
-	NdisMoveMemory(pAd->StaCfg.PTK, PTK, LEN_PTK);
-
-	// init 802.3 header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero message 2 body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-	//
-	// Message 2 as  EAPOL-Key(0,1,0,0,0,P,0,SNonce,MIC,RSN IE)
-	//
-	Packet.KeyDesc.Type = WPA2_KEY_DESC;
-
-	// 1. Key descriptor version and appropriate RSN IE
-	if(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 2;
-	}
-	else	  // TKIP
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 1;
-	}
-
-	// fill in Data Material and its length
-	Packet.KeyDesc.KeyData[0] = IE_WPA2;
-	Packet.KeyDesc.KeyData[1] = pAd->StaCfg.RSNIE_Len;
-	Packet.KeyDesc.KeyDataLen[1] = pAd->StaCfg.RSNIE_Len + 2;
-	NdisMoveMemory(&Packet.KeyDesc.KeyData[2], pAd->StaCfg.RSN_IE, pAd->StaCfg.RSNIE_Len);
-
-	// Update packet length after decide Key data payload
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE + Packet.KeyDesc.KeyDataLen[1];
-
-	// 2. Key Type PeerKey
-	Packet.KeyDesc.KeyInfo.KeyType = PAIRWISEKEY;
-
-	// 3. KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-
-	// Update Key Length
-	Packet.KeyDesc.KeyLength[0] = 0;
-	Packet.KeyDesc.KeyLength[1] = pMsg1->KeyDesc.KeyLength[1];
-
-	// 4. Fill SNonce
-	NdisMoveMemory(Packet.KeyDesc.KeyNonce, pAd->StaCfg.SNonce, LEN_KEY_DESC_NONCE);
-
-	// 5. Key Replay Count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-	// Send EAPOL-Key(0,1,0,0,0,P,0,SNonce,MIC,RSN IE)
-	// Out buffer for transmitting message 2
-	MlmeAllocateMemory(pAd,  (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-	{
-		os_free_mem(pAd, mpool);
-		return;
-	}
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,        &FrameLen,
-		Packet.Body_Len[1] + 4, &Packet,
-		END_OF_ARGS);
-
-	// 6. Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		HMAC_SHA1(pOutBuffer, FrameLen, PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(PTK,  LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-
-	// Make  Transmitting frame
-	MakeOutgoingFrame(pOutBuffer,           	&FrameLen,
-			  			LENGTH_802_3,     		&Header802_3,
-						Packet.Body_Len[1] + 4, &Packet,
-						END_OF_ARGS);
-
-
-	// 5. Copy frame to Tx ring
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, TRUE);
-
-	MlmeFreeMemory(pAd, pOutBuffer);
-	os_free_mem(pAd, mpool);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Wpa2PairMsg1Action <-----\n"));
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Process Pairwise key 4-way handshaking
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		Elem		Message body
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	WpaPairMsg3Action(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-
-{
-	PHEADER_802_11      pHeader;
-	PUCHAR          	pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG           	FrameLen = 0;
-	EAPOL_PACKET        Packet;
-	PEAPOL_PACKET       pMsg3;
-	UCHAR           	Mic[16], OldMic[16];
-	MAC_TABLE_ENTRY 	*pEntry = NULL;
-	UCHAR				skip_offset;
-	KEY_INFO			peerKeyInfo;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaPairMsg3Action ----->\n"));
-
-	// Record 802.11 header & the received EAPOL packet Msg3
-	pHeader = (PHEADER_802_11) Elem->Msg;
-	pMsg3 = (PEAPOL_PACKET)	&Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
-
-	NdisZeroMemory((PUCHAR)&peerKeyInfo, sizeof(peerKeyInfo));
-	NdisMoveMemory((PUCHAR)&peerKeyInfo, (PUCHAR)&pMsg3->KeyDesc.KeyInfo, sizeof(KEY_INFO));
-
-	*((USHORT*)&peerKeyInfo) = cpu2le16(*((USHORT*)&peerKeyInfo));
-
-
-	// 1. Verify cipher type match
-	if (pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled && (peerKeyInfo.KeyDescVer != 2))
-	{
-		return;
-	}
-	else if(pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled && (peerKeyInfo.KeyDescVer != 1))
-	{
-		return;
-	}
-
-	// Verify RSN IE
-	//if (!RTMPEqualMemory(pMsg3->KeyDesc.KeyData, pAd->MacTab.Content[BSSID_WCID].RSN_IE, pAd->MacTab.Content[BSSID_WCID].RSNIE_Len))
-	if (!CheckRSNIE(pAd, pMsg3->KeyDesc.KeyData, pMsg3->KeyDesc.KeyDataLen[1], &skip_offset))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("RSN_IE Different in Msg 3 of WPA1 4-way handshake!! \n"));
-		hex_dump("The original RSN_IE", pAd->MacTab.Content[BSSID_WCID].RSN_IE, pAd->MacTab.Content[BSSID_WCID].RSNIE_Len);
-		hex_dump("The received RSN_IE", pMsg3->KeyDesc.KeyData, pMsg3->KeyDesc.KeyDataLen[1]);
-		return;
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, ("RSN_IE VALID in Msg 3 of WPA1 4-way handshake!! \n"));
-
-
-	// 2. Check MIC value
-	// Save the MIC and replace with zero
-	NdisMoveMemory(OldMic, pMsg3->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-	NdisZeroMemory(pMsg3->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		UCHAR digest[80];
-
-		HMAC_SHA1((PUCHAR) pMsg3, pMsg3->Body_Len[1] + 4, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else	// TKIP
-	{
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, (PUCHAR) pMsg3, pMsg3->Body_Len[1] + 4, Mic);
-	}
-
-	if(!NdisEqualMemory(OldMic, Mic, LEN_KEY_DESC_MIC))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, (" MIC Different in msg 3 of 4-way handshake!!!!!!!!!! \n"));
-		return;
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, (" MIC VALID in msg 3 of 4-way handshake!!!!!!!!!! \n"));
-
-	// 3. Check Replay Counter, it has to be larger than last one. No need to be exact one larger
-	if(RTMPCompareMemory(pMsg3->KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1)
-		return;
-
-	// Update new replay counter
-	NdisMoveMemory(pAd->StaCfg.ReplayCounter, pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// 4. Double check ANonce
-	if(!NdisEqualMemory(pAd->StaCfg.ANonce, pMsg3->KeyDesc.KeyNonce, LEN_KEY_DESC_NONCE))
-		return;
-
-	// init 802.3 header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero Message 4 body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE;		// No data field
-
-	//
-	// Message 4 as  EAPOL-Key(0,1,0,0,0,P,0,0,MIC,0)
-	//
-	Packet.KeyDesc.Type = WPA1_KEY_DESC;
-
-	// Key descriptor version and appropriate RSN IE
-	Packet.KeyDesc.KeyInfo.KeyDescVer = peerKeyInfo.KeyDescVer;
-
-	// Update Key Length
-	Packet.KeyDesc.KeyLength[0] = pMsg3->KeyDesc.KeyLength[0];
-	Packet.KeyDesc.KeyLength[1] = pMsg3->KeyDesc.KeyLength[1];
-
-	// Key Type PeerKey
-	Packet.KeyDesc.KeyInfo.KeyType = PAIRWISEKEY;
-
-	// KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-
-	// In Msg3,  KeyInfo.secure =0 if Group Key HS to come. 1 if no group key HS
-	// Station sends Msg4  KeyInfo.secure should be the same as that in Msg.3
-	Packet.KeyDesc.KeyInfo.Secure= peerKeyInfo.Secure;
-
-	// Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-	// Key Replay count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Out buffer for transmitting message 4
-	MlmeAllocateMemory(pAd, (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-		return;
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		Packet.Body_Len[1] + 4,    &Packet,
-		END_OF_ARGS);
-
-	// Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		UCHAR digest[80];
-
-		HMAC_SHA1(pOutBuffer, FrameLen, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-	// Update PTK
-	// Prepare pair-wise key information into shared key table
-	NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-	pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-    NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, &pAd->StaCfg.PTK[32], LEN_TKIP_EK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, &pAd->StaCfg.PTK[48], LEN_TKIP_RXMICK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, &pAd->StaCfg.PTK[48+LEN_TKIP_RXMICK], LEN_TKIP_TXMICK);
-
-	// Decide its ChiperAlg
-	if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-	else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-	else
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_NONE;
-
-	// Update these related information to MAC_TABLE_ENTRY
-	pEntry = &pAd->MacTab.Content[BSSID_WCID];
-	NdisMoveMemory(pEntry->PairwiseKey.Key, &pAd->StaCfg.PTK[32], LEN_TKIP_EK);
-	NdisMoveMemory(pEntry->PairwiseKey.RxMic, &pAd->StaCfg.PTK[48], LEN_TKIP_RXMICK);
-	NdisMoveMemory(pEntry->PairwiseKey.TxMic, &pAd->StaCfg.PTK[48+LEN_TKIP_RXMICK], LEN_TKIP_TXMICK);
-	pEntry->PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-
-	// Update pairwise key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAd,
-						  BSS0,
-						  0,
-						  pAd->SharedKey[BSS0][0].CipherAlg,
-						  pAd->SharedKey[BSS0][0].Key,
-						  pAd->SharedKey[BSS0][0].TxMic,
-						  pAd->SharedKey[BSS0][0].RxMic);
-
-	// Update ASIC WCID attribute table and IVEIV table
-	RTMPAddWcidAttributeEntry(pAd,
-							  BSS0,
-							  0,
-							  pAd->SharedKey[BSS0][0].CipherAlg,
-							  pEntry);
-
-	// Make transmitting frame
-	MakeOutgoingFrame(pOutBuffer,           	&FrameLen,
-			  			LENGTH_802_3,     		&Header802_3,
-						Packet.Body_Len[1] + 4, &Packet,
-						END_OF_ARGS);
-
-
-	// Copy frame to Tx ring and Send Message 4 to authenticator
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, TRUE);
-
-	MlmeFreeMemory(pAd, (PUCHAR)pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaPairMsg3Action <-----\n"));
-}
-
-VOID    Wpa2PairMsg3Action(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  MLME_QUEUE_ELEM *Elem)
-
-{
-	PHEADER_802_11      pHeader;
-	PUCHAR              pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG               FrameLen = 0;
-	EAPOL_PACKET        Packet;
-	PEAPOL_PACKET       pMsg3;
-	UCHAR               Mic[16], OldMic[16];
-	UCHAR               *mpool, *KEYDATA, *digest;
-	UCHAR               Key[32];
-	MAC_TABLE_ENTRY 	*pEntry = NULL;
-	KEY_INFO			peerKeyInfo;
-
-	// allocate memory
-	os_alloc_mem(pAd, (PUCHAR *)&mpool, 1024);
-
-	if(mpool == NULL)
-		return;
-
-	// KEYDATA Len = 512.
-	KEYDATA = (UCHAR *) ROUND_UP(mpool, 4);
-	// digest Len = 80.
-	digest = (UCHAR *) ROUND_UP(KEYDATA + 512, 4);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Wpa2PairMsg3Action ----->\n"));
-
-	pHeader = (PHEADER_802_11) Elem->Msg;
-
-	// Process message 3 frame.
-	pMsg3 = (PEAPOL_PACKET)	&Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
-
-	NdisZeroMemory((PUCHAR)&peerKeyInfo, sizeof(peerKeyInfo));
-	NdisMoveMemory((PUCHAR)&peerKeyInfo, (PUCHAR)&pMsg3->KeyDesc.KeyInfo, sizeof(KEY_INFO));
-
-	*((USHORT*)&peerKeyInfo) = cpu2le16(*((USHORT*)&peerKeyInfo));
-
-	// 1. Verify cipher type match
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled && (peerKeyInfo.KeyDescVer!= 2))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-	else if(pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled && (peerKeyInfo.KeyDescVer != 1))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// 2. Check MIC value
-	// Save the MIC and replace with zero
-	NdisMoveMemory(OldMic, pMsg3->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-	NdisZeroMemory(pMsg3->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		HMAC_SHA1((PUCHAR) pMsg3, pMsg3->Body_Len[1] + 4, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, (PUCHAR) pMsg3, pMsg3->Body_Len[1] + 4, Mic);
-	}
-
-	if(!NdisEqualMemory(OldMic, Mic, LEN_KEY_DESC_MIC))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, (" MIC Different in msg 3 of 4-way handshake!!!!!!!!!! \n"));
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, (" MIC VALID in msg 3 of 4-way handshake!!!!!!!!!! \n"));
-
-	// 3. Check Replay Counter, it has to be larger than last one. No need to be exact one larger
-	if(RTMPCompareMemory(pMsg3->KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1)
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Update new replay counter
-	NdisMoveMemory(pAd->StaCfg.ReplayCounter, pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// 4. Double check ANonce
-	if(!NdisEqualMemory(pAd->StaCfg.ANonce, pMsg3->KeyDesc.KeyNonce, LEN_KEY_DESC_NONCE))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Obtain GTK
-	// 5. Decrypt GTK from Key Data
-	DBGPRINT_RAW(RT_DEBUG_TRACE, ("EKD = %d\n", peerKeyInfo.EKD_DL));
-	if(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// Decrypt AES GTK
-		AES_GTK_KEY_UNWRAP(&pAd->StaCfg.PTK[16], KEYDATA, pMsg3->KeyDesc.KeyDataLen[1],pMsg3->KeyDesc.KeyData);
-	}
-	else	  // TKIP
-	{
-		INT i;
-		// Decrypt TKIP GTK
-		// Construct 32 bytes RC4 Key
-		NdisMoveMemory(Key, pMsg3->KeyDesc.KeyIv, 16);
-		NdisMoveMemory(&Key[16], &pAd->StaCfg.PTK[16], 16);
-		ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, Key, 32);
-		//discard first 256 bytes
-		for(i = 0; i < 256; i++)
-			ARCFOUR_BYTE(&pAd->PrivateInfo.WEPCONTEXT);
-		// Decrypt GTK. Becareful, there is no ICV to check the result is correct or not
-		ARCFOUR_DECRYPT(&pAd->PrivateInfo.WEPCONTEXT, KEYDATA, pMsg3->KeyDesc.KeyData, pMsg3->KeyDesc.KeyDataLen[1]);
-	}
-
-	if (!ParseKeyData(pAd, KEYDATA, pMsg3->KeyDesc.KeyDataLen[1], 1))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Update GTK to ASIC
-	// Update group key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAd,
-						  BSS0,
-						  pAd->StaCfg.DefaultKeyId,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic);
-
-	// Update ASIC WCID attribute table and IVEIV table
-	RTMPAddWcidAttributeEntry(pAd,
-							  BSS0,
-							  pAd->StaCfg.DefaultKeyId,
-							  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-							  NULL);
-
-	// init 802.3 header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero message 4 body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-	Packet.Body_Len[1]  	= sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE;		// No data field
-
-	//
-	// Message 4 as  EAPOL-Key(0,1,0,0,0,P,0,0,MIC,0)
-	//
-	Packet.KeyDesc.Type = WPA2_KEY_DESC;
-
-	// Key descriptor version and appropriate RSN IE
-	Packet.KeyDesc.KeyInfo.KeyDescVer = peerKeyInfo.KeyDescVer;
-
-	// Update Key Length
-	Packet.KeyDesc.KeyLength[0] = pMsg3->KeyDesc.KeyLength[0];
-	Packet.KeyDesc.KeyLength[1] = pMsg3->KeyDesc.KeyLength[1];
-
-	// Key Type PeerKey
-	Packet.KeyDesc.KeyInfo.KeyType = PAIRWISEKEY;
-
-	// KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-	Packet.KeyDesc.KeyInfo.Secure = 1;
-
-	// Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-	// Key Replay count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pMsg3->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Out buffer for transmitting message 4
-	MlmeAllocateMemory(pAd, (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		Packet.Body_Len[1] + 4,    &Packet,
-		END_OF_ARGS);
-
-	// Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		HMAC_SHA1(pOutBuffer, FrameLen, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-	// Update PTK
-	// Prepare pair-wise key information into shared key table
-	NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-	pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-    NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, &pAd->StaCfg.PTK[32], LEN_TKIP_EK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, &pAd->StaCfg.PTK[48], LEN_TKIP_RXMICK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, &pAd->StaCfg.PTK[48+LEN_TKIP_RXMICK], LEN_TKIP_TXMICK);
-
-	// Decide its ChiperAlg
-	if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-	else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-	else
-		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_NONE;
-
-	// Update these related information to MAC_TABLE_ENTRY
-	pEntry = &pAd->MacTab.Content[BSSID_WCID];
-	NdisMoveMemory(&pEntry->PairwiseKey.Key, &pAd->StaCfg.PTK[32], LEN_TKIP_EK);
-	NdisMoveMemory(&pEntry->PairwiseKey.RxMic, &pAd->StaCfg.PTK[48], LEN_TKIP_RXMICK);
-	NdisMoveMemory(&pEntry->PairwiseKey.TxMic, &pAd->StaCfg.PTK[48+LEN_TKIP_RXMICK], LEN_TKIP_TXMICK);
-	pEntry->PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-
-	// Update pairwise key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAd,
-						  BSS0,
-						  0,
-						  pAd->SharedKey[BSS0][0].CipherAlg,
-						  pAd->SharedKey[BSS0][0].Key,
-						  pAd->SharedKey[BSS0][0].TxMic,
-						  pAd->SharedKey[BSS0][0].RxMic);
-
-	// Update ASIC WCID attribute table and IVEIV table
-	RTMPAddWcidAttributeEntry(pAd,
-							  BSS0,
-							  0,
-							  pAd->SharedKey[BSS0][0].CipherAlg,
-							  pEntry);
-
-	// Make  Transmitting frame
-	MakeOutgoingFrame(pOutBuffer,           	&FrameLen,
-			  			LENGTH_802_3,     		&Header802_3,
-						Packet.Body_Len[1] + 4, &Packet,
-						END_OF_ARGS);
-
-
-	// Copy frame to Tx ring and Send Message 4 to authenticator
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, TRUE);
-
-	// set 802.1x port control
-	//pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-	STA_PORT_SECURED(pAd);
-
-    // Indicate Connected for GUI
-    pAd->IndicateMediaState = NdisMediaStateConnected;
-
-	MlmeFreeMemory(pAd, (PUCHAR)pOutBuffer);
-	os_free_mem(pAd, (PUCHAR)mpool);
-
-
-	// send wireless event - for set key done WPA2
-	if (pAd->CommonCfg.bWirelessEvent)
-		RTMPSendWirelessEvent(pAd, IW_SET_KEY_DONE_WPA2_EVENT_FLAG, pEntry->Addr, BSS0, 0);
-
-	DBGPRINT(RT_DEBUG_ERROR, ("Wpa2PairMsg3Action <-----\n"));
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Process Group key 2-way handshaking
-
-	Arguments:
-		pAd	Pointer	to our adapter
-		Elem		Message body
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	WpaGroupMsg1Action(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	MLME_QUEUE_ELEM	*Elem)
-
-{
-	PUCHAR              pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG               FrameLen = 0;
-	EAPOL_PACKET        Packet;
-	PEAPOL_PACKET       pGroup;
-	UCHAR               *mpool, *digest, *KEYDATA;
-	UCHAR               Mic[16], OldMic[16];
-	UCHAR               GTK[32], Key[32];
-	KEY_INFO			peerKeyInfo;
-
-	// allocate memory
-	os_alloc_mem(pAd, (PUCHAR *)&mpool, 1024);
-
-	if(mpool == NULL)
-		return;
-
-	// digest Len = 80.
-	digest = (UCHAR *) ROUND_UP(mpool, 4);
-	// KEYDATA Len = 512.
-	KEYDATA = (UCHAR *) ROUND_UP(digest + 80, 4);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaGroupMsg1Action ----->\n"));
-
-	// Process Group Message 1 frame. skip 802.11 header(24) & LLC_SNAP header(8)
-	pGroup = (PEAPOL_PACKET) &Elem->Msg[LENGTH_802_11 + LENGTH_802_1_H];
-
-	NdisZeroMemory((PUCHAR)&peerKeyInfo, sizeof(peerKeyInfo));
-	NdisMoveMemory((PUCHAR)&peerKeyInfo, (PUCHAR)&pGroup->KeyDesc.KeyInfo, sizeof(KEY_INFO));
-
-	*((USHORT*)&peerKeyInfo) = cpu2le16(*((USHORT*)&peerKeyInfo));
-
-	// 0. Check cipher type match
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled && (peerKeyInfo.KeyDescVer != 2))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-	else if (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled && (peerKeyInfo.KeyDescVer != 1))
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// 1. Verify Replay counter
-	//    Check Replay Counter, it has to be larger than last one. No need to be exact one larger
-	if(RTMPCompareMemory(pGroup->KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY) != 1)
-	{
-		os_free_mem(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Update new replay counter
-	NdisMoveMemory(pAd->StaCfg.ReplayCounter, pGroup->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// 2. Verify MIC is valid
-	// Save the MIC and replace with zero
-	NdisMoveMemory(OldMic, pGroup->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-	NdisZeroMemory(pGroup->KeyDesc.KeyMic, LEN_KEY_DESC_MIC);
-
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{	// AES
-		HMAC_SHA1((PUCHAR) pGroup, pGroup->Body_Len[1] + 4, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{	// TKIP
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, (PUCHAR) pGroup, pGroup->Body_Len[1] + 4, Mic);
-	}
-
-	if(!NdisEqualMemory(OldMic, Mic, LEN_KEY_DESC_MIC))
-	{
-		DBGPRINT(RT_DEBUG_ERROR, (" MIC Different in group msg 1 of 2-way handshake!!!!!!!!!! \n"));
-		MlmeFreeMemory(pAd, (PUCHAR)mpool);
-		return;
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, (" MIC VALID in group msg 1 of 2-way handshake!!!!!!!!!! \n"));
-
-
-	// 3. Decrypt GTK from Key Data
-	if (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled)
-	{
-		// Decrypt AES GTK
-		AES_GTK_KEY_UNWRAP(&pAd->StaCfg.PTK[16], KEYDATA,  pGroup->KeyDesc.KeyDataLen[1], pGroup->KeyDesc.KeyData);
-	}
-	else	// TKIP
-	{
-		INT i;
-
-		// Decrypt TKIP GTK
-		// Construct 32 bytes RC4 Key
-		NdisMoveMemory(Key, pGroup->KeyDesc.KeyIv, 16);
-		NdisMoveMemory(&Key[16], &pAd->StaCfg.PTK[16], 16);
-		ARCFOUR_INIT(&pAd->PrivateInfo.WEPCONTEXT, Key, 32);
-		//discard first 256 bytes
-		for(i = 0; i < 256; i++)
-			ARCFOUR_BYTE(&pAd->PrivateInfo.WEPCONTEXT);
-		// Decrypt GTK. Becareful, there is no ICV to check the result is correct or not
-		ARCFOUR_DECRYPT(&pAd->PrivateInfo.WEPCONTEXT, KEYDATA, pGroup->KeyDesc.KeyData, pGroup->KeyDesc.KeyDataLen[1]);
-	}
-
-	// Process decrypted key data material
-	// Parse keyData to handle KDE format for WPA2PSK
-	if (peerKeyInfo.EKD_DL)
-	{
-		if (!ParseKeyData(pAd, KEYDATA, pGroup->KeyDesc.KeyDataLen[1], 0))
-		{
-			os_free_mem(pAd, (PUCHAR)mpool);
-			return;
-		}
-	}
-	else	// WPAPSK
-	{
-		// set key material, TxMic and RxMic for WPAPSK
-		NdisMoveMemory(GTK, KEYDATA, 32);
-		NdisMoveMemory(pAd->StaCfg.GTK, GTK, 32);
-		pAd->StaCfg.DefaultKeyId = peerKeyInfo.KeyIndex;
-
-		// Prepare pair-wise key information into shared key table
-		NdisZeroMemory(&pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId], sizeof(CIPHER_KEY));
-		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].KeyLen = LEN_TKIP_EK;
-		NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, GTK, LEN_TKIP_EK);
-		NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, &GTK[16], LEN_TKIP_RXMICK);
-		NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, &GTK[24], LEN_TKIP_TXMICK);
-
-		// Update Shared Key CipherAlg
-		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_NONE;
-		if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_TKIP;
-		else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
-			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_AES;
-
-    	//hex_dump("Group Key :", pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, LEN_TKIP_EK);
-	}
-
-	// Update group key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAd,
-						  BSS0,
-						  pAd->StaCfg.DefaultKeyId,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic,
-						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic);
-
-	// Update ASIC WCID attribute table and IVEIV table
-	RTMPAddWcidAttributeEntry(pAd,
-							  BSS0,
-							  pAd->StaCfg.DefaultKeyId,
-							  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-							  NULL);
-
-	// set 802.1x port control
-	//pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-	STA_PORT_SECURED(pAd);
-
-    // Indicate Connected for GUI
-    pAd->IndicateMediaState = NdisMediaStateConnected;
-
-	// init header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	// Zero Group message 1 body
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE;		// No data field
-
-	//
-	// Group Message 2 as  EAPOL-Key(1,0,0,0,G,0,0,MIC,0)
-	//
-	if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-	{
-		Packet.KeyDesc.Type = WPA2_KEY_DESC;
-	}
-	else
-	{
-		Packet.KeyDesc.Type = WPA1_KEY_DESC;
-	}
-
-	// Key descriptor version and appropriate RSN IE
-	Packet.KeyDesc.KeyInfo.KeyDescVer = peerKeyInfo.KeyDescVer;
-
-	// Update Key Length
-	Packet.KeyDesc.KeyLength[0] = pGroup->KeyDesc.KeyLength[0];
-	Packet.KeyDesc.KeyLength[1] = pGroup->KeyDesc.KeyLength[1];
-
-	// Key Index as G-Msg 1
-	if(pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)
-		Packet.KeyDesc.KeyInfo.KeyIndex = peerKeyInfo.KeyIndex;
-
-	// Key Type Group key
-	Packet.KeyDesc.KeyInfo.KeyType = GROUPKEY;
-
-	// KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-
-	// Secure bit
-	Packet.KeyDesc.KeyInfo.Secure  = 1;
-
-	// Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-	// Key Replay count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pGroup->KeyDesc.ReplayCounter, LEN_KEY_DESC_REPLAY);
-
-	// Out buffer for transmitting group message 2
-	MlmeAllocateMemory(pAd, (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-	{
-		MlmeFreeMemory(pAd, (PUCHAR)mpool);
-		return;
-	}
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,           &FrameLen,
-		Packet.Body_Len[1] + 4,    &Packet,
-		END_OF_ARGS);
-
-	// Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{
-		// AES
-		HMAC_SHA1(pOutBuffer, FrameLen, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{
-		hmac_md5(pAd->StaCfg.PTK, LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-
-	MakeOutgoingFrame(pOutBuffer,       		&FrameLen,
-						LENGTH_802_3,     		&Header802_3,
-						Packet.Body_Len[1] + 4, &Packet,
-						END_OF_ARGS);
-
-
-	// 5. Copy frame to Tx ring and prepare for encryption
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, FALSE);
-
-	// 6 Free allocated memory
-	MlmeFreeMemory(pAd, (PUCHAR)pOutBuffer);
-	os_free_mem(pAd, (PUCHAR)mpool);
-
-	// send wireless event - for set key done WPA2
-	if (pAd->CommonCfg.bWirelessEvent)
-		RTMPSendWirelessEvent(pAd, IW_SET_KEY_DONE_WPA2_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaGroupMsg1Action <-----\n"));
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Init WPA MAC header
-
-	Arguments:
-		pAd	Pointer	to our adapter
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID	WpaMacHeaderInit(
-	IN		PRTMP_ADAPTER	pAd,
-	IN OUT	PHEADER_802_11	pHdr80211,
-	IN		UCHAR			wep,
-	IN		PUCHAR		    pAddr1)
-{
-	NdisZeroMemory(pHdr80211, sizeof(HEADER_802_11));
-	pHdr80211->FC.Type	= BTYPE_DATA;
-	pHdr80211->FC.ToDs	= 1;
-	if (wep	== 1)
-		pHdr80211->FC.Wep = 1;
-
-	 //	Addr1: BSSID, Addr2: SA, Addr3:	DA
-	COPY_MAC_ADDR(pHdr80211->Addr1, pAddr1);
-	COPY_MAC_ADDR(pHdr80211->Addr2, pAd->CurrentAddress);
-	COPY_MAC_ADDR(pHdr80211->Addr3, pAd->CommonCfg.Bssid);
-	pHdr80211->Sequence =	pAd->Sequence;
-}
-
-/*
-	========================================================================
-
-	Routine	Description:
-		Copy frame from waiting queue into relative ring buffer and set
-	appropriate ASIC register to kick hardware encryption before really
-	sent out to air.
-
-	Arguments:
-		pAd		Pointer	to our adapter
-		PNDIS_PACKET	Pointer to outgoing Ndis frame
-		NumberOfFrag	Number of fragment required
-
-	Return Value:
-		None
-
-	Note:
-
-	========================================================================
-*/
-VOID    RTMPToWirelessSta(
-	IN	PRTMP_ADAPTER	pAd,
-	IN  PUCHAR          pHeader802_3,
-    IN  UINT            HdrLen,
-	IN  PUCHAR          pData,
-    IN  UINT            DataLen,
-    IN	BOOLEAN			is4wayFrame)
-
-{
-	NDIS_STATUS     Status;
-	PNDIS_PACKET    pPacket;
-	UCHAR   Index;
-
-	do
-	{
-		// 1. build a NDIS packet and call RTMPSendPacket();
-		//    be careful about how/when to release this internal allocated NDIS PACKET buffer
-		Status = RTMPAllocateNdisPacket(pAd, &pPacket, pHeader802_3, HdrLen, pData, DataLen);
-		if (Status != NDIS_STATUS_SUCCESS)
-			break;
-
-		if (is4wayFrame)
-			RTMP_SET_PACKET_CLEAR_EAP_FRAME(pPacket, 1);
-		else
-			RTMP_SET_PACKET_CLEAR_EAP_FRAME(pPacket, 0);
-
-		// 2. send out the packet
-		Status = STASendPacket(pAd, pPacket);
-		if(Status == NDIS_STATUS_SUCCESS)
-		{
-			// Dequeue one frame from TxSwQueue0..3 queue and process it
-			// There are three place calling dequeue for TX ring.
-			// 1. Here, right after queueing the frame.
-			// 2. At the end of TxRingTxDone service routine.
-			// 3. Upon NDIS call RTMPSendPackets
-			if((!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) &&
-				(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS)))
-			{
-				for(Index = 0; Index < 5; Index ++)
-					if(pAd->TxSwQueue[Index].Number > 0)
-						RTMPDeQueuePacket(pAd, FALSE, Index, MAX_TX_PROCESS);
-			}
-		}
-	} while(FALSE);
-
-}
-
-/*
-    ========================================================================
-
-    Routine Description:
-    Check Sanity RSN IE form AP
-
-    Arguments:
-
-    Return Value:
-
-
-    ========================================================================
-*/
-BOOLEAN CheckRSNIE(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pData,
-	IN  UCHAR           DataLen,
-	OUT	UCHAR			*Offset)
-{
-	PUCHAR              pVIE;
-	UCHAR               len;
-	PEID_STRUCT         pEid;
-	BOOLEAN				result = FALSE;
-
-	pVIE = pData;
-	len	 = DataLen;
-	*Offset = 0;
-
-	while (len > sizeof(RSNIE2))
-	{
-		pEid = (PEID_STRUCT) pVIE;
-		// WPA RSN IE
-		if ((pEid->Eid == IE_WPA) && (NdisEqualMemory(pEid->Octet, WPA_OUI, 4)))
-		{
-			if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA || pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) &&
-				(NdisEqualMemory(pVIE, pAd->MacTab.Content[BSSID_WCID].RSN_IE, pAd->MacTab.Content[BSSID_WCID].RSNIE_Len)) &&
-				(pAd->MacTab.Content[BSSID_WCID].RSNIE_Len == (pEid->Len + 2)))
-			{
-					DBGPRINT(RT_DEBUG_TRACE, ("CheckRSNIE ==> WPA/WPAPSK RSN IE matched in Msg 3, Length(%d) \n", (pEid->Len + 2)));
-					result = TRUE;
-			}
-
-			*Offset += (pEid->Len + 2);
-		}
-		// WPA2 RSN IE
-		else if ((pEid->Eid == IE_RSN) && (NdisEqualMemory(pEid->Octet + 2, RSN_OUI, 3)))
-		{
-			if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2 || pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) &&
-				(NdisEqualMemory(pVIE, pAd->MacTab.Content[BSSID_WCID].RSN_IE, pAd->MacTab.Content[BSSID_WCID].RSNIE_Len)) &&
-				(pAd->MacTab.Content[BSSID_WCID].RSNIE_Len == (pEid->Len + 2)))
-			{
-					DBGPRINT(RT_DEBUG_TRACE, ("CheckRSNIE ==> WPA2/WPA2PSK RSN IE matched in Msg 3, Length(%d) \n", (pEid->Len + 2)));
-					result = TRUE;
-			}
-
-			*Offset += (pEid->Len + 2);
-		}
-		else
-		{
-			break;
-		}
-
-		pVIE += (pEid->Len + 2);
-		len  -= (pEid->Len + 2);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("CheckRSNIE ==> skip_offset(%d) \n", *Offset));
-
-	return result;
-
-}
-
-
-/*
-    ========================================================================
-
-    Routine Description:
-    Parse KEYDATA field.  KEYDATA[] May contain 2 RSN IE and optionally GTK.
-    GTK  is encaptulated in KDE format at  p.83 802.11i D10
-
-    Arguments:
-
-    Return Value:
-
-    Note:
-        802.11i D10
-
-    ========================================================================
-*/
-BOOLEAN ParseKeyData(
-	IN  PRTMP_ADAPTER   pAd,
-	IN  PUCHAR          pKeyData,
-	IN  UCHAR           KeyDataLen,
-	IN	UCHAR			bPairewise)
-{
-    PKDE_ENCAP          pKDE = NULL;
-    PUCHAR              pMyKeyData = pKeyData;
-    UCHAR               KeyDataLength = KeyDataLen;
-    UCHAR               GTKLEN;
-	UCHAR				skip_offset;
-
-	// Verify The RSN IE contained in Pairewise-Msg 3 and skip it
-	if (bPairewise)
-    {
-		// Check RSN IE whether it is WPA2/WPA2PSK
-		if (!CheckRSNIE(pAd, pKeyData, KeyDataLen, &skip_offset))
-		{
-			DBGPRINT(RT_DEBUG_ERROR, ("ParseKeyData ==> WPA2/WPA2PSK RSN IE mismatched \n"));
-			hex_dump("Get KEYDATA :", pKeyData, KeyDataLen);
-			return FALSE;
-    	}
-    	else
-		{
-			// skip RSN IE
-			pMyKeyData += skip_offset;
-			KeyDataLength -= skip_offset;
-
-			//DBGPRINT(RT_DEBUG_TRACE, ("ParseKeyData ==> WPA2/WPA2PSK RSN IE matched in Msg 3, Length(%d) \n", skip_offset));
-		}
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE,("ParseKeyData ==> KeyDataLength %d without RSN_IE \n", KeyDataLength));
-
-	// Parse EKD format
-	if (KeyDataLength >= 8)
-    {
-        pKDE = (PKDE_ENCAP) pMyKeyData;
-    }
-	else
-    {
-		DBGPRINT(RT_DEBUG_ERROR, ("ERROR: KeyDataLength is too short \n"));
-        return FALSE;
-    }
-
-
-	// Sanity check - shared key index should not be 0
-	if (pKDE->GTKEncap.Kid == 0)
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("ERROR: GTK Key index zero \n"));
-        return FALSE;
-    }
-
-	// Sanity check - KED length
-	if (KeyDataLength < (pKDE->Len + 2))
-    {
-        DBGPRINT(RT_DEBUG_ERROR, ("ERROR: The len from KDE is too short \n"));
-        return FALSE;
-    }
-
-	// Get GTK length - refer to IEEE 802.11i-2004 p.82
-	GTKLEN = pKDE->Len -6;
-
-	if (GTKLEN < LEN_AES_KEY)
-	{
-		DBGPRINT(RT_DEBUG_ERROR, ("ERROR: GTK Key length is too short (%d) \n", GTKLEN));
-        return FALSE;
-	}
-	else
-		DBGPRINT(RT_DEBUG_TRACE, ("GTK Key with KDE formet got index=%d, len=%d \n", pKDE->GTKEncap.Kid, GTKLEN));
-
-	// Update GTK
-	// set key material, TxMic and RxMic for WPAPSK
-	NdisMoveMemory(pAd->StaCfg.GTK, pKDE->GTKEncap.GTK, 32);
-	pAd->StaCfg.DefaultKeyId = pKDE->GTKEncap.Kid;
-
-	// Update shared key table
-	NdisZeroMemory(&pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId], sizeof(CIPHER_KEY));
-	pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].KeyLen = LEN_TKIP_EK;
-	NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, pKDE->GTKEncap.GTK, LEN_TKIP_EK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, &pKDE->GTKEncap.GTK[16], LEN_TKIP_RXMICK);
-	NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, &pKDE->GTKEncap.GTK[24], LEN_TKIP_TXMICK);
-
-	// Update Shared Key CipherAlg
-	pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_NONE;
-	if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_TKIP;
-	else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
-		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_AES;
-
-	return TRUE;
-
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Cisco CCKM PRF function
-
-	Arguments:
-		key				Cisco Base Transient Key (BTK)
-		key_len			The key length of the BTK
-		data			Ruquest Number(RN) + BSSID
-		data_len		The length of the data
-		output			Store for PTK(Pairwise transient keys)
-		len				The length of the output
-	Return Value:
-		None
-
-	Note:
-		802.1i	Annex F.9
-
-	========================================================================
-*/
-VOID CCKMPRF(
-	IN	UCHAR	*key,
-	IN	INT		key_len,
-	IN	UCHAR	*data,
-	IN	INT		data_len,
-	OUT	UCHAR	*output,
-	IN	INT		len)
-{
-	INT		i;
-	UCHAR	input[1024];
-	INT		currentindex = 0;
-	INT		total_len;
-
-	NdisMoveMemory(input, data, data_len);
-	total_len = data_len;
-	input[total_len] = 0;
-	total_len++;
-	for	(i = 0;	i <	(len + 19) / 20; i++)
-	{
-		HMAC_SHA1(input, total_len,	key, key_len, &output[currentindex]);
-		currentindex +=	20;
-		input[total_len - 1]++;
-	}
-}
-
-/*
-	========================================================================
-
-	Routine Description:
-		Process MIC error indication and record MIC error timer.
-
-	Arguments:
-		pAd 	Pointer to our adapter
-		pWpaKey 		Pointer to the WPA key structure
-
-	Return Value:
-		None
-
-	IRQL = DISPATCH_LEVEL
-
-	Note:
-
-	========================================================================
-*/
-VOID	RTMPReportMicError(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PCIPHER_KEY 	pWpaKey)
-{
-	ULONG	Now;
-    UCHAR   unicastKey = (pWpaKey->Type == PAIRWISE_KEY ? 1:0);
-
-	// Record Last MIC error time and count
-	Now = jiffies;
-	if (pAd->StaCfg.MicErrCnt == 0)
-	{
-		pAd->StaCfg.MicErrCnt++;
-		pAd->StaCfg.LastMicErrorTime = Now;
-        NdisZeroMemory(pAd->StaCfg.ReplayCounter, 8);
-	}
-	else if (pAd->StaCfg.MicErrCnt == 1)
-	{
-		if ((pAd->StaCfg.LastMicErrorTime + (60 * OS_HZ)) < Now)
-		{
-			// Update Last MIC error time, this did not violate two MIC errors within 60 seconds
-			pAd->StaCfg.LastMicErrorTime = Now;
-		}
-		else
-		{
-
-			if (pAd->CommonCfg.bWirelessEvent)
-				RTMPSendWirelessEvent(pAd, IW_COUNTER_MEASURES_EVENT_FLAG, pAd->MacTab.Content[BSSID_WCID].Addr, BSS0, 0);
-
-			pAd->StaCfg.LastMicErrorTime = Now;
-			// Violate MIC error counts, MIC countermeasures kicks in
-			pAd->StaCfg.MicErrCnt++;
-			// We shall block all reception
-			// We shall clean all Tx ring and disassoicate from AP after next EAPOL frame
-			//
-			// No necessary to clean all Tx ring, on RTMPHardTransmit will stop sending non-802.1X EAPOL packets
-			// if pAd->StaCfg.MicErrCnt greater than 2.
-			//
-			// RTMPRingCleanUp(pAd, QID_AC_BK);
-			// RTMPRingCleanUp(pAd, QID_AC_BE);
-			// RTMPRingCleanUp(pAd, QID_AC_VI);
-			// RTMPRingCleanUp(pAd, QID_AC_VO);
-			// RTMPRingCleanUp(pAd, QID_HCCA);
-		}
-	}
-	else
-	{
-		// MIC error count >= 2
-		// This should not happen
-		;
-	}
-    MlmeEnqueue(pAd,
-				MLME_CNTL_STATE_MACHINE,
-				OID_802_11_MIC_FAILURE_REPORT_FRAME,
-				1,
-				&unicastKey);
-
-    if (pAd->StaCfg.MicErrCnt == 2)
-    {
-        RTMPSetTimer(&pAd->StaCfg.WpaDisassocAndBlockAssocTimer, 100);
-    }
-}
-
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-#define	LENGTH_EAP_H    4
-// If the received frame is EAP-Packet ,find out its EAP-Code (Request(0x01), Response(0x02), Success(0x03), Failure(0x04)).
-INT	    WpaCheckEapCode(
-	IN  PRTMP_ADAPTER   		pAd,
-	IN  PUCHAR				pFrame,
-	IN  USHORT				FrameLen,
-	IN  USHORT				OffSet)
-{
-
-	PUCHAR	pData;
-	INT	result = 0;
-
-	if( FrameLen < OffSet + LENGTH_EAPOL_H + LENGTH_EAP_H )
-		return result;
-
-	pData = pFrame + OffSet; // skip offset bytes
-
-	if(*(pData+1) == EAPPacket) 	// 802.1x header - Packet Type
-	{
-		 result = *(pData+4);		// EAP header - Code
-	}
-
-	return result;
-}
-
-VOID    WpaSendMicFailureToWpaSupplicant(
-    IN  PRTMP_ADAPTER    pAd,
-    IN  BOOLEAN          bUnicast)
-{
-    union iwreq_data    wrqu;
-    char custom[IW_CUSTOM_MAX] = {0};
-
-    sprintf(custom, "MLME-MICHAELMICFAILURE.indication");
-    if (bUnicast)
-        sprintf(custom, "%s unicast", custom);
-    wrqu.data.length = strlen(custom);
-    wireless_send_event(pAd->net_dev, IWEVCUSTOM, &wrqu, custom);
-
-    return;
-}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-VOID	WpaMicFailureReportFrame(
-	IN  PRTMP_ADAPTER   pAd,
-	IN MLME_QUEUE_ELEM *Elem)
-{
-	PUCHAR              pOutBuffer = NULL;
-	UCHAR               Header802_3[14];
-	ULONG               FrameLen = 0;
-	EAPOL_PACKET        Packet;
-	UCHAR               Mic[16];
-    BOOLEAN             bUnicast;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaMicFailureReportFrame ----->\n"));
-
-    bUnicast = (Elem->Msg[0] == 1 ? TRUE:FALSE);
-	pAd->Sequence = ((pAd->Sequence) + 1) & (MAX_SEQ_NUMBER);
-
-	// init 802.3 header and Fill Packet
-	MAKE_802_3_HEADER(Header802_3, pAd->CommonCfg.Bssid, pAd->CurrentAddress, EAPOL);
-
-	NdisZeroMemory(&Packet, sizeof(Packet));
-	Packet.ProVer	= EAPOL_VER;
-	Packet.ProType	= EAPOLKey;
-
-	Packet.KeyDesc.Type = WPA1_KEY_DESC;
-
-    // Request field presented
-    Packet.KeyDesc.KeyInfo.Request = 1;
-
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 2;
-	}
-	else	  // TKIP
-	{
-		Packet.KeyDesc.KeyInfo.KeyDescVer = 1;
-	}
-
-    Packet.KeyDesc.KeyInfo.KeyType = (bUnicast ? PAIRWISEKEY : GROUPKEY);
-
-	// KeyMic field presented
-	Packet.KeyDesc.KeyInfo.KeyMic  = 1;
-
-    // Error field presented
-	Packet.KeyDesc.KeyInfo.Error  = 1;
-
-	// Update packet length after decide Key data payload
-	Packet.Body_Len[1]  = sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE;
-
-	// Key Replay Count
-	NdisMoveMemory(Packet.KeyDesc.ReplayCounter, pAd->StaCfg.ReplayCounter, LEN_KEY_DESC_REPLAY);
-    inc_byte_array(pAd->StaCfg.ReplayCounter, 8);
-
-	// Convert to little-endian format.
-	*((USHORT *)&Packet.KeyDesc.KeyInfo) = cpu2le16(*((USHORT *)&Packet.KeyDesc.KeyInfo));
-
-
-	MlmeAllocateMemory(pAd, (PUCHAR *)&pOutBuffer);  // allocate memory
-	if(pOutBuffer == NULL)
-	{
-		return;
-	}
-
-	// Prepare EAPOL frame for MIC calculation
-	// Be careful, only EAPOL frame is counted for MIC calculation
-	MakeOutgoingFrame(pOutBuffer,               &FrameLen,
-		              Packet.Body_Len[1] + 4,   &Packet,
-		              END_OF_ARGS);
-
-	// Prepare and Fill MIC value
-	NdisZeroMemory(Mic, sizeof(Mic));
-	if(pAd->StaCfg.WepStatus  == Ndis802_11Encryption3Enabled)
-	{	// AES
-        UCHAR digest[20] = {0};
-		HMAC_SHA1(pOutBuffer, FrameLen, pAd->StaCfg.PTK, LEN_EAP_MICK, digest);
-		NdisMoveMemory(Mic, digest, LEN_KEY_DESC_MIC);
-	}
-	else
-	{	// TKIP
-		hmac_md5(pAd->StaCfg.PTK,  LEN_EAP_MICK, pOutBuffer, FrameLen, Mic);
-	}
-	NdisMoveMemory(Packet.KeyDesc.KeyMic, Mic, LEN_KEY_DESC_MIC);
-
-    MakeOutgoingFrame(pOutBuffer,           	&FrameLen,
-    	  			LENGTH_802_3,     			&Header802_3,
-    				Packet.Body_Len[1] + 4,     &Packet,
-    				END_OF_ARGS);
-
-	// opy frame to Tx ring and send MIC failure report frame to authenticator
-	RTMPToWirelessSta(pAd, Header802_3, LENGTH_802_3, (PUCHAR)&Packet, Packet.Body_Len[1] + 4, FALSE);
-
-	MlmeFreeMemory(pAd, (PUCHAR)pOutBuffer);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("WpaMicFailureReportFrame <-----\n"));
-}
-
-/** from wpa_supplicant
- * inc_byte_array - Increment arbitrary length byte array by one
- * @counter: Pointer to byte array
- * @len: Length of the counter in bytes
- *
- * This function increments the last byte of the counter by one and continues
- * rolling over to more significant bytes if the byte was incremented from
- * 0xff to 0x00.
- */
-void inc_byte_array(UCHAR *counter, int len)
-{
-	int pos = len - 1;
-	while (pos >= 0) {
-		counter[pos]++;
-		if (counter[pos] != 0)
-			break;
-		pos--;
-	}
-}
-
-VOID WpaDisassocApAndBlockAssoc(
-    IN PVOID SystemSpecific1,
-    IN PVOID FunctionContext,
-    IN PVOID SystemSpecific2,
-    IN PVOID SystemSpecific3)
-{
-    RTMP_ADAPTER                *pAd = (PRTMP_ADAPTER)FunctionContext;
-    MLME_DISASSOC_REQ_STRUCT    DisassocReq;
-
-	// disassoc from current AP first
-	DBGPRINT(RT_DEBUG_TRACE, ("RTMPReportMicError - disassociate with current AP after sending second continuous EAPOL frame\n"));
-	DisassocParmFill(pAd, &DisassocReq, pAd->CommonCfg.Bssid, REASON_MIC_FAILURE);
-	MlmeEnqueue(pAd, ASSOC_STATE_MACHINE, MT2_MLME_DISASSOC_REQ, sizeof(MLME_DISASSOC_REQ_STRUCT), &DisassocReq);
-
-	pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_DISASSOC;
-	pAd->StaCfg.bBlockAssoc = TRUE;
-}
-
+#include "../../rt2870/sta/wpa.c"
diff --git a/drivers/staging/rt3070/sta_ioctl.c b/drivers/staging/rt3070/sta_ioctl.c
index 0794548..ac56507 100644
--- a/drivers/staging/rt3070/sta_ioctl.c
+++ b/drivers/staging/rt3070/sta_ioctl.c
@@ -1,7203 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-    Module Name:
-    sta_ioctl.c
-
-    Abstract:
-    IOCTL related subroutines
-
-    Revision History:
-    Who         When          What
-    --------    ----------    ----------------------------------------------
-    Rory Chen   01-03-2003    created
-	Rory Chen   02-14-2005    modify to support RT61
-*/
-
-#include	"rt_config.h"
-
-#ifdef DBG
-extern ULONG    RTDebugLevel;
-#endif
-
-#define NR_WEP_KEYS 				4
-#define WEP_SMALL_KEY_LEN 			(40/8)
-#define WEP_LARGE_KEY_LEN 			(104/8)
-
-#define GROUP_KEY_NO                4
-
-extern UCHAR    CipherWpa2Template[];
-extern UCHAR    CipherWpaPskTkip[];
-extern UCHAR    CipherWpaPskTkipLen;
-
-typedef struct PACKED _RT_VERSION_INFO{
-    UCHAR       DriverVersionW;
-    UCHAR       DriverVersionX;
-    UCHAR       DriverVersionY;
-    UCHAR       DriverVersionZ;
-    UINT        DriverBuildYear;
-    UINT        DriverBuildMonth;
-    UINT        DriverBuildDay;
-} RT_VERSION_INFO, *PRT_VERSION_INFO;
-
-struct iw_priv_args privtab[] = {
-{ RTPRIV_IOCTL_SET,
-  IW_PRIV_TYPE_CHAR | 1024, 0,
-  "set"},
-
-{ RTPRIV_IOCTL_SHOW, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  ""},
-{ RTPRIV_IOCTL_SHOW, IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  ""},
-/* --- sub-ioctls definitions --- */
-    { SHOW_CONN_STATUS,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "connStatus" },
-	{ SHOW_DRVIER_VERION,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "driverVer" },
-    { SHOW_BA_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "bainfo" },
-	{ SHOW_DESC_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "descinfo" },
-    { RAIO_OFF,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "radio_off" },
-	{ RAIO_ON,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "radio_on" },
-#ifdef QOS_DLS_SUPPORT
-	{ SHOW_DLS_ENTRY_INFO,
-	  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "dlsentryinfo" },
-#endif // QOS_DLS_SUPPORT //
-	{ SHOW_CFG_VALUE,
-	  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, "show" },
-/* --- sub-ioctls relations --- */
-
-#ifdef DBG
-{ RTPRIV_IOCTL_BBP,
-  IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  "bbp"},
-{ RTPRIV_IOCTL_MAC,
-  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | 1024,
-  "mac"},
-#ifdef RT30xx
-{ RTPRIV_IOCTL_RF,
-  IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  "rf"},
-#endif // RT30xx //
-{ RTPRIV_IOCTL_E2P,
-  IW_PRIV_TYPE_CHAR | 1024, IW_PRIV_TYPE_CHAR | 1024,
-  "e2p"},
-#endif  /* DBG */
-
-{ RTPRIV_IOCTL_STATISTICS,
-  0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_MASK,
-  "stat"},
-{ RTPRIV_IOCTL_GSITESURVEY,
-  0, IW_PRIV_TYPE_CHAR | 1024,
-  "get_site_survey"},
-
-
-};
-
-INT Set_SSID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef WMM_SUPPORT
-INT	Set_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif
-
-INT Set_NetworkType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_AuthMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_EncrypType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_DefaultKeyID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key1_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key2_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key3_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_Key4_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-INT Set_WPAPSK_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-
-INT Set_PSMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-INT Set_Wpa_Support(
-    IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg);
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef DBG
-
-VOID RTMPIoctlMAC(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq);
-
-VOID RTMPIoctlE2PROM(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  struct iwreq    *wrq);
-
-#ifdef RT30xx
-VOID RTMPIoctlRF(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  struct iwreq    *wrq);
-#endif // RT30xx //
-#endif // DBG //
-
-
-NDIS_STATUS RTMPWPANoneAddKeyProc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN	PVOID			pBuf);
-
-INT Set_FragTest_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-
-#ifdef DOT11_N_SUPPORT
-INT Set_TGnWifiTest_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg);
-#endif // DOT11_N_SUPPORT //
-
-INT Set_LongRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg);
-
-INT Set_ShortRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg);
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-INT Set_Ieee80211dClientMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg);
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef CARRIER_DETECTION_SUPPORT
-INT Set_CarrierDetect_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg);
-#endif // CARRIER_DETECTION_SUPPORT //
-
-static struct {
-	CHAR *name;
-	INT (*set_proc)(PRTMP_ADAPTER pAdapter, PUCHAR arg);
-} *PRTMP_PRIVATE_SET_PROC, RTMP_PRIVATE_SUPPORT_PROC[] = {
-	{"DriverVersion",				Set_DriverVersion_Proc},
-	{"CountryRegion",				Set_CountryRegion_Proc},
-	{"CountryRegionABand",			Set_CountryRegionABand_Proc},
-	{"SSID",						Set_SSID_Proc},
-	{"WirelessMode",				Set_WirelessMode_Proc},
-	{"TxBurst",					Set_TxBurst_Proc},
-	{"TxPreamble",				Set_TxPreamble_Proc},
-	{"TxPower",					Set_TxPower_Proc},
-	{"Channel",					Set_Channel_Proc},
-	{"BGProtection",				Set_BGProtection_Proc},
-	{"RTSThreshold",				Set_RTSThreshold_Proc},
-	{"FragThreshold",				Set_FragThreshold_Proc},
-#ifdef DOT11_N_SUPPORT
-	{"HtBw",		                Set_HtBw_Proc},
-	{"HtMcs",		                Set_HtMcs_Proc},
-	{"HtGi",		                Set_HtGi_Proc},
-	{"HtOpMode",		            Set_HtOpMode_Proc},
-	{"HtExtcha",		            Set_HtExtcha_Proc},
-	{"HtMpduDensity",		        Set_HtMpduDensity_Proc},
-	{"HtBaWinSize",		        	Set_HtBaWinSize_Proc},
-	{"HtRdg",		        		Set_HtRdg_Proc},
-	{"HtAmsdu",		        		Set_HtAmsdu_Proc},
-	{"HtAutoBa",		        	Set_HtAutoBa_Proc},
-	{"HtBaDecline",					Set_BADecline_Proc},
-	{"HtProtect",		        	Set_HtProtect_Proc},
-	{"HtMimoPs",		        	Set_HtMimoPs_Proc},
-#endif // DOT11_N_SUPPORT //
-
-#ifdef AGGREGATION_SUPPORT
-	{"PktAggregate",				Set_PktAggregate_Proc},
-#endif
-
-#ifdef WMM_SUPPORT
-	{"WmmCapable",					Set_WmmCapable_Proc},
-#endif
-	{"IEEE80211H",					Set_IEEE80211H_Proc},
-    {"NetworkType",                 Set_NetworkType_Proc},
-	{"AuthMode",					Set_AuthMode_Proc},
-	{"EncrypType",					Set_EncrypType_Proc},
-	{"DefaultKeyID",				Set_DefaultKeyID_Proc},
-	{"Key1",						Set_Key1_Proc},
-	{"Key2",						Set_Key2_Proc},
-	{"Key3",						Set_Key3_Proc},
-	{"Key4",						Set_Key4_Proc},
-	{"WPAPSK",						Set_WPAPSK_Proc},
-	{"ResetCounter",				Set_ResetStatCounter_Proc},
-	{"PSMode",                      Set_PSMode_Proc},
-#ifdef DBG
-	{"Debug",						Set_Debug_Proc},
-#endif
-
-#ifdef RALINK_ATE
-	{"ATE",							Set_ATE_Proc},
-	{"ATEDA",						Set_ATE_DA_Proc},
-	{"ATESA",						Set_ATE_SA_Proc},
-	{"ATEBSSID",					Set_ATE_BSSID_Proc},
-	{"ATECHANNEL",					Set_ATE_CHANNEL_Proc},
-	{"ATETXPOW0",					Set_ATE_TX_POWER0_Proc},
-	{"ATETXPOW1",					Set_ATE_TX_POWER1_Proc},
-	{"ATETXANT",					Set_ATE_TX_Antenna_Proc},
-	{"ATERXANT",					Set_ATE_RX_Antenna_Proc},
-	{"ATETXFREQOFFSET",				Set_ATE_TX_FREQOFFSET_Proc},
-	{"ATETXBW",						Set_ATE_TX_BW_Proc},
-	{"ATETXLEN",					Set_ATE_TX_LENGTH_Proc},
-	{"ATETXCNT",					Set_ATE_TX_COUNT_Proc},
-	{"ATETXMCS",					Set_ATE_TX_MCS_Proc},
-	{"ATETXMODE",					Set_ATE_TX_MODE_Proc},
-	{"ATETXGI",						Set_ATE_TX_GI_Proc},
-	{"ATERXFER",					Set_ATE_RX_FER_Proc},
-	{"ATERRF",						Set_ATE_Read_RF_Proc},
-	{"ATEWRF1",						Set_ATE_Write_RF1_Proc},
-	{"ATEWRF2",						Set_ATE_Write_RF2_Proc},
-	{"ATEWRF3",						Set_ATE_Write_RF3_Proc},
-	{"ATEWRF4",						Set_ATE_Write_RF4_Proc},
-	{"ATELDE2P",				    Set_ATE_Load_E2P_Proc},
-	{"ATERE2P",						Set_ATE_Read_E2P_Proc},
-	{"ATESHOW",						Set_ATE_Show_Proc},
-	{"ATEHELP",						Set_ATE_Help_Proc},
-
-#ifdef RALINK_28xx_QA
-	{"TxStop",						Set_TxStop_Proc},
-	{"RxStop",						Set_RxStop_Proc},
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-    {"WpaSupport",                  Set_Wpa_Support},
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-
-	{"FixedTxMode",                 Set_FixedTxMode_Proc},
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	{"OpMode",						Set_OpMode_Proc},
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-#ifdef DOT11_N_SUPPORT
-    {"TGnWifiTest",                 Set_TGnWifiTest_Proc},
-    {"ForceGF",		        		Set_ForceGF_Proc},
-#endif // DOT11_N_SUPPORT //
-#ifdef QOS_DLS_SUPPORT
-	{"DlsAddEntry",					Set_DlsAddEntry_Proc},
-	{"DlsTearDownEntry",			Set_DlsTearDownEntry_Proc},
-#endif // QOS_DLS_SUPPORT //
-	{"LongRetry",	        		Set_LongRetryLimit_Proc},
-	{"ShortRetry",	        		Set_ShortRetryLimit_Proc},
-#ifdef EXT_BUILD_CHANNEL_LIST
-	{"11dClientMode",				Set_Ieee80211dClientMode_Proc},
-#endif // EXT_BUILD_CHANNEL_LIST //
-#ifdef CARRIER_DETECTION_SUPPORT
-	{"CarrierDetect",				Set_CarrierDetect_Proc},
-#endif // CARRIER_DETECTION_SUPPORT //
-//2008/09/11:KH add to support efuse<--
-#ifdef RT30xx
-	{"efuseFreeNumber",				set_eFuseGetFreeBlockCount_Proc},
-	{"efuseDump",					set_eFusedump_Proc},
-	{"efuseLoadFromBin",				set_eFuseLoadFromBin_Proc},
-#endif // RT30xx //
-//2008/09/11:KH add to support efuse-->
-	{NULL,}
-};
-
-
-VOID RTMPAddKey(
-	IN	PRTMP_ADAPTER	    pAd,
-	IN	PNDIS_802_11_KEY    pKey)
-{
-	ULONG				KeyIdx;
-	MAC_TABLE_ENTRY  	*pEntry;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("RTMPAddKey ------>\n"));
-
-	if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-	{
-		if (pKey->KeyIndex & 0x80000000)
-		{
-		    if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-            {
-                NdisZeroMemory(pAd->StaCfg.PMK, 32);
-                NdisMoveMemory(pAd->StaCfg.PMK, pKey->KeyMaterial, pKey->KeyLength);
-                goto end;
-            }
-		    // Update PTK
-		    NdisZeroMemory(&pAd->SharedKey[BSS0][0], sizeof(CIPHER_KEY));
-            pAd->SharedKey[BSS0][0].KeyLen = LEN_TKIP_EK;
-            NdisMoveMemory(pAd->SharedKey[BSS0][0].Key, pKey->KeyMaterial, LEN_TKIP_EK);
-#ifdef WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-            {
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-            else
-#endif // WPA_SUPPLICANT_SUPPORT //
-            {
-            	NdisMoveMemory(pAd->SharedKey[BSS0][0].TxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][0].RxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-
-            // Decide its ChiperAlg
-        	if (pAd->StaCfg.PairCipher == Ndis802_11Encryption2Enabled)
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_TKIP;
-        	else if (pAd->StaCfg.PairCipher == Ndis802_11Encryption3Enabled)
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_AES;
-        	else
-        		pAd->SharedKey[BSS0][0].CipherAlg = CIPHER_NONE;
-
-            // Update these related information to MAC_TABLE_ENTRY
-        	pEntry = &pAd->MacTab.Content[BSSID_WCID];
-            NdisMoveMemory(pEntry->PairwiseKey.Key, pAd->SharedKey[BSS0][0].Key, LEN_TKIP_EK);
-        	NdisMoveMemory(pEntry->PairwiseKey.RxMic, pAd->SharedKey[BSS0][0].RxMic, LEN_TKIP_RXMICK);
-        	NdisMoveMemory(pEntry->PairwiseKey.TxMic, pAd->SharedKey[BSS0][0].TxMic, LEN_TKIP_TXMICK);
-        	pEntry->PairwiseKey.CipherAlg = pAd->SharedKey[BSS0][0].CipherAlg;
-
-        	// Update pairwise key information to ASIC Shared Key Table
-        	AsicAddSharedKeyEntry(pAd,
-        						  BSS0,
-        						  0,
-        						  pAd->SharedKey[BSS0][0].CipherAlg,
-        						  pAd->SharedKey[BSS0][0].Key,
-        						  pAd->SharedKey[BSS0][0].TxMic,
-        						  pAd->SharedKey[BSS0][0].RxMic);
-
-        	// Update ASIC WCID attribute table and IVEIV table
-        	RTMPAddWcidAttributeEntry(pAd,
-        							  BSS0,
-        							  0,
-        							  pAd->SharedKey[BSS0][0].CipherAlg,
-        							  pEntry);
-
-            if (pAd->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-            {
-                // set 802.1x port control
-	            //pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAd);
-
-                // Indicate Connected for GUI
-                pAd->IndicateMediaState = NdisMediaStateConnected;
-            }
-		}
-        else
-        {
-            // Update GTK
-            pAd->StaCfg.DefaultKeyId = (pKey->KeyIndex & 0xFF);
-            NdisZeroMemory(&pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId], sizeof(CIPHER_KEY));
-            pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].KeyLen = LEN_TKIP_EK;
-            NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key, pKey->KeyMaterial, LEN_TKIP_EK);
-#ifdef WPA_SUPPLICANT_SUPPORT
-            if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-            {
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-            else
-#endif // WPA_SUPPLICANT_SUPPORT //
-            {
-            	NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic, pKey->KeyMaterial + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-                NdisMoveMemory(pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic, pKey->KeyMaterial + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-            }
-
-            // Update Shared Key CipherAlg
-    		pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_NONE;
-    		if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption2Enabled)
-    			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_TKIP;
-    		else if (pAd->StaCfg.GroupCipher == Ndis802_11Encryption3Enabled)
-    			pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg = CIPHER_AES;
-
-            // Update group key information to ASIC Shared Key Table
-        	AsicAddSharedKeyEntry(pAd,
-        						  BSS0,
-        						  pAd->StaCfg.DefaultKeyId,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].Key,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].TxMic,
-        						  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].RxMic);
-
-        	// Update ASIC WCID attribute table and IVEIV table
-        	RTMPAddWcidAttributeEntry(pAd,
-        							  BSS0,
-        							  pAd->StaCfg.DefaultKeyId,
-        							  pAd->SharedKey[BSS0][pAd->StaCfg.DefaultKeyId].CipherAlg,
-        							  NULL);
-
-            // set 802.1x port control
-	        //pAd->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-			STA_PORT_SECURED(pAd);
-
-            // Indicate Connected for GUI
-            pAd->IndicateMediaState = NdisMediaStateConnected;
-        }
-	}
-	else	// dynamic WEP from wpa_supplicant
-	{
-		UCHAR	CipherAlg;
-    	PUCHAR	Key;
-
-		if(pKey->KeyLength == 32)
-			goto end;
-
-		KeyIdx = pKey->KeyIndex & 0x0fffffff;
-
-		if (KeyIdx < 4)
-		{
-			// it is a default shared key, for Pairwise key setting
-			if (pKey->KeyIndex & 0x80000000)
-			{
-				pEntry = MacTableLookup(pAd, pKey->BSSID);
-
-				if (pEntry)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("RTMPAddKey: Set Pair-wise Key\n"));
-
-					// set key material and key length
- 					pEntry->PairwiseKey.KeyLen = (UCHAR)pKey->KeyLength;
-					NdisMoveMemory(pEntry->PairwiseKey.Key, &pKey->KeyMaterial, pKey->KeyLength);
-
-					// set Cipher type
-					if (pKey->KeyLength == 5)
-						pEntry->PairwiseKey.CipherAlg = CIPHER_WEP64;
-					else
-						pEntry->PairwiseKey.CipherAlg = CIPHER_WEP128;
-
-					// Add Pair-wise key to Asic
-					AsicAddPairwiseKeyEntry(
-						pAd,
-						pEntry->Addr,
-						(UCHAR)pEntry->Aid,
-                		&pEntry->PairwiseKey);
-
-					// update WCID attribute table and IVEIV table for this entry
-					RTMPAddWcidAttributeEntry(
-						pAd,
-						BSS0,
-						KeyIdx, // The value may be not zero
-						pEntry->PairwiseKey.CipherAlg,
-						pEntry);
-
-				}
-			}
-			else
-            {
-				// Default key for tx (shared key)
-				pAd->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-
-				// set key material and key length
-				pAd->SharedKey[BSS0][KeyIdx].KeyLen = (UCHAR) pKey->KeyLength;
-				NdisMoveMemory(pAd->SharedKey[BSS0][KeyIdx].Key, &pKey->KeyMaterial, pKey->KeyLength);
-
-				// Set Ciper type
-				if (pKey->KeyLength == 5)
-					pAd->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_WEP64;
-				else
-					pAd->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_WEP128;
-
-    			CipherAlg = pAd->SharedKey[BSS0][KeyIdx].CipherAlg;
-    			Key = pAd->SharedKey[BSS0][KeyIdx].Key;
-
-				// Set Group key material to Asic
-    			AsicAddSharedKeyEntry(pAd, BSS0, KeyIdx, CipherAlg, Key, NULL, NULL);
-
-				// Update WCID attribute table and IVEIV table for this group key table
-				RTMPAddWcidAttributeEntry(pAd, BSS0, KeyIdx, CipherAlg, NULL);
-
-			}
-		}
-	}
-end:
-	return;
-}
-
-char * rtstrchr(const char * s, int c)
-{
-    for(; *s != (char) c; ++s)
-        if (*s == '\0')
-            return NULL;
-    return (char *) s;
-}
-
-/*
-This is required for LinEX2004/kernel2.6.7 to provide iwlist scanning function
-*/
-
-int
-rt_ioctl_giwname(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-//	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-#ifdef RT2870
-	strncpy(name, "RT2870 Wireless", IFNAMSIZ);
-#endif // RT2870 //
-	return 0;
-}
-
-int rt_ioctl_siwfreq(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_freq *freq, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-	int 	chan = -1;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-
-	if (freq->e > 1)
-		return -EINVAL;
-
-	if((freq->e == 0) && (freq->m <= 1000))
-		chan = freq->m;	// Setting by channel number
-	else
-		MAP_KHZ_TO_CHANNEL_ID( (freq->m /100) , chan); // Setting by frequency - search the table , like 2.412G, 2.422G,
-
-    if (ChannelSanity(pAdapter, chan) == TRUE)
-    {
-	pAdapter->CommonCfg.Channel = chan;
-	DBGPRINT(RT_DEBUG_ERROR, ("==>rt_ioctl_siwfreq::SIOCSIWFREQ[cmd=0x%x] (Channel=%d)\n", SIOCSIWFREQ, pAdapter->CommonCfg.Channel));
-    }
-    else
-        return -EINVAL;
-
-	return 0;
-}
-int rt_ioctl_giwfreq(struct net_device *dev,
-		   struct iw_request_info *info,
-		   struct iw_freq *freq, char *extra)
-{
-    VIRTUAL_ADAPTER *pVirtualAd = NULL;
-	PRTMP_ADAPTER pAdapter;
-	UCHAR ch;
-	ULONG	m;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-		ch = pAdapter->CommonCfg.Channel;
-
-	DBGPRINT(RT_DEBUG_TRACE,("==>rt_ioctl_giwfreq  %d\n", ch));
-
-    MAP_CHANNEL_ID_TO_KHZ(ch, m);
-	freq->m = m * 100;
-	freq->e = 1;
-	return 0;
-}
-
-int rt_ioctl_siwmode(struct net_device *dev,
-		   struct iw_request_info *info,
-		   __u32 *mode, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-    	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	switch (*mode)
-	{
-		case IW_MODE_ADHOC:
-			Set_NetworkType_Proc(pAdapter, "Adhoc");
-			break;
-		case IW_MODE_INFRA:
-			Set_NetworkType_Proc(pAdapter, "Infra");
-			break;
-#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20))
-        case IW_MODE_MONITOR:
-			Set_NetworkType_Proc(pAdapter, "Monitor");
-			break;
-#endif
-		default:
-			DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_siwmode::SIOCSIWMODE (unknown %d)\n", *mode));
-			return -EINVAL;
-	}
-
-	// Reset Ralink supplicant to not use, it will be set to start when UI set PMK key
-	pAdapter->StaCfg.WpaState = SS_NOTUSE;
-
-	return 0;
-}
-
-int rt_ioctl_giwmode(struct net_device *dev,
-		   struct iw_request_info *info,
-		   __u32 *mode, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	if (ADHOC_ON(pAdapter))
-		*mode = IW_MODE_ADHOC;
-    else if (INFRA_ON(pAdapter))
-		*mode = IW_MODE_INFRA;
-#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20))
-    else if (MONITOR_ON(pAdapter))
-    {
-        *mode = IW_MODE_MONITOR;
-    }
-#endif
-    else
-        *mode = IW_MODE_AUTO;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("==>rt_ioctl_giwmode(mode=%d)\n", *mode));
-	return 0;
-}
-
-int rt_ioctl_siwsens(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-        	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	return 0;
-}
-
-int rt_ioctl_giwsens(struct net_device *dev,
-		   struct iw_request_info *info,
-		   char *name, char *extra)
-{
-	return 0;
-}
-
-int rt_ioctl_giwrange(struct net_device *dev,
-		   struct iw_request_info *info,
-		   struct iw_point *data, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	struct iw_range *range = (struct iw_range *) extra;
-	u16 val;
-	int i;
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===>rt_ioctl_giwrange\n"));
-	data->length = sizeof(struct iw_range);
-	memset(range, 0, sizeof(struct iw_range));
-
-	range->txpower_capa = IW_TXPOW_DBM;
-
-	if (INFRA_ON(pAdapter)||ADHOC_ON(pAdapter))
-	{
-		range->min_pmp = 1 * 1024;
-		range->max_pmp = 65535 * 1024;
-		range->min_pmt = 1 * 1024;
-		range->max_pmt = 1000 * 1024;
-		range->pmp_flags = IW_POWER_PERIOD;
-		range->pmt_flags = IW_POWER_TIMEOUT;
-		range->pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT |
-			IW_POWER_UNICAST_R | IW_POWER_ALL_R;
-	}
-
-	range->we_version_compiled = WIRELESS_EXT;
-	range->we_version_source = 14;
-
-	range->retry_capa = IW_RETRY_LIMIT;
-	range->retry_flags = IW_RETRY_LIMIT;
-	range->min_retry = 0;
-	range->max_retry = 255;
-
-	range->num_channels =  pAdapter->ChannelListNum;
-
-	val = 0;
-	for (i = 1; i <= range->num_channels; i++)
-	{
-		u32 m;
-		range->freq[val].i = pAdapter->ChannelList[i-1].Channel;
-		MAP_CHANNEL_ID_TO_KHZ(pAdapter->ChannelList[i-1].Channel, m);
-		range->freq[val].m = m * 100; /* HZ */
-
-		range->freq[val].e = 1;
-		val++;
-		if (val == IW_MAX_FREQUENCIES)
-			break;
-	}
-	range->num_frequency = val;
-
-	range->max_qual.qual = 100; /* what is correct max? This was not
-					* documented exactly. At least
-					* 69 has been observed. */
-	range->max_qual.level = 0; /* dB */
-	range->max_qual.noise = 0; /* dB */
-
-	/* What would be suitable values for "average/typical" qual? */
-	range->avg_qual.qual = 20;
-	range->avg_qual.level = -60;
-	range->avg_qual.noise = -95;
-	range->sensitivity = 3;
-
-	range->max_encoding_tokens = NR_WEP_KEYS;
-	range->num_encoding_sizes = 2;
-	range->encoding_size[0] = 5;
-	range->encoding_size[1] = 13;
-
-	range->min_rts = 0;
-	range->max_rts = 2347;
-	range->min_frag = 256;
-	range->max_frag = 2346;
-
-#if WIRELESS_EXT > 17
-	/* IW_ENC_CAPA_* bit field */
-	range->enc_capa = IW_ENC_CAPA_WPA | IW_ENC_CAPA_WPA2 |
-					IW_ENC_CAPA_CIPHER_TKIP | IW_ENC_CAPA_CIPHER_CCMP;
-#endif
-
-	return 0;
-}
-
-int rt_ioctl_siwap(struct net_device *dev,
-		      struct iw_request_info *info,
-		      struct sockaddr *ap_addr, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-    NDIS_802_11_MAC_ADDRESS Bssid;
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-    {
-        RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-        DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-    }
-
-    // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-    // this request, because this request is initiated by NDIS.
-    pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-	// Prevent to connect AP again in STAMlmePeriodicExec
-	pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-
-    memset(Bssid, 0, MAC_ADDR_LEN);
-    memcpy(Bssid, ap_addr->sa_data, MAC_ADDR_LEN);
-    MlmeEnqueue(pAdapter,
-                MLME_CNTL_STATE_MACHINE,
-                OID_802_11_BSSID,
-                sizeof(NDIS_802_11_MAC_ADDRESS),
-                (VOID *)&Bssid);
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCSIWAP %02x:%02x:%02x:%02x:%02x:%02x\n",
-        Bssid[0], Bssid[1], Bssid[2], Bssid[3], Bssid[4], Bssid[5]));
-
-	return 0;
-}
-
-int rt_ioctl_giwap(struct net_device *dev,
-		      struct iw_request_info *info,
-		      struct sockaddr *ap_addr, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-	{
-		ap_addr->sa_family = ARPHRD_ETHER;
-		memcpy(ap_addr->sa_data, &pAdapter->CommonCfg.Bssid, ETH_ALEN);
-	}
-#ifdef WPA_SUPPLICANT_SUPPORT
-    // Add for RT2870
-    else if (pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-    {
-        ap_addr->sa_family = ARPHRD_ETHER;
-        memcpy(ap_addr->sa_data, &pAdapter->MlmeAux.Bssid, ETH_ALEN);
-    }
-#endif // WPA_SUPPLICANT_SUPPORT //
-	else
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCGIWAP(=EMPTY)\n"));
-		return -ENOTCONN;
-	}
-
-	return 0;
-}
-
-/*
- * Units are in db above the noise floor. That means the
- * rssi values reported in the tx/rx descriptors in the
- * driver are the SNR expressed in db.
- *
- * If you assume that the noise floor is -95, which is an
- * excellent assumption 99.5 % of the time, then you can
- * derive the absolute signal level (i.e. -95 + rssi).
- * There are some other slight factors to take into account
- * depending on whether the rssi measurement is from 11b,
- * 11g, or 11a.   These differences are at most 2db and
- * can be documented.
- *
- * NB: various calculations are based on the orinoco/wavelan
- *     drivers for compatibility
- */
-static void set_quality(PRTMP_ADAPTER pAdapter,
-                        struct iw_quality *iq,
-                        signed char rssi)
-{
-	__u8 ChannelQuality;
-
-	// Normalize Rssi
-	if (rssi >= -50)
-		ChannelQuality = 100;
-	else if (rssi >= -80) // between -50 ~ -80dbm
-		ChannelQuality = (__u8)(24 + ((rssi + 80) * 26)/10);
-	else if (rssi >= -90)   // between -80 ~ -90dbm
-        ChannelQuality = (__u8)((rssi + 90) * 26)/10;
-	else
-		ChannelQuality = 0;
-
-    iq->qual = (__u8)ChannelQuality;
-
-    iq->level = (__u8)(rssi);
-    iq->noise = (pAdapter->BbpWriteLatch[66] > pAdapter->BbpTuning.FalseCcaUpperThreshold) ? ((__u8)pAdapter->BbpTuning.FalseCcaUpperThreshold) : ((__u8) pAdapter->BbpWriteLatch[66]); 	// noise level (dBm)
-    iq->noise += 256 - 143;
-    iq->updated = pAdapter->iw_stats.qual.updated;
-}
-
-int rt_ioctl_iwaplist(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
- 	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	struct sockaddr addr[IW_MAX_AP];
-	struct iw_quality qual[IW_MAX_AP];
-	int i;
-
-   	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		data->length = 0;
-		return 0;
-        //return -ENETDOWN;
-	}
-
-	for (i = 0; i <IW_MAX_AP ; i++)
-	{
-		if (i >=  pAdapter->ScanTab.BssNr)
-			break;
-		addr[i].sa_family = ARPHRD_ETHER;
-			memcpy(addr[i].sa_data, &pAdapter->ScanTab.BssEntry[i].Bssid, MAC_ADDR_LEN);
-		set_quality(pAdapter, &qual[i], pAdapter->ScanTab.BssEntry[i].Rssi);
-	}
-	data->length = i;
-	memcpy(extra, &addr, i*sizeof(addr[0]));
-	data->flags = 1;		/* signal quality present (sort of) */
-	memcpy(extra + i*sizeof(addr[0]), &qual, i*sizeof(qual[i]));
-
-	return 0;
-}
-
-#ifdef SIOCGIWSCAN
-int rt_ioctl_siwscan(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	ULONG								Now;
-	int Status = NDIS_STATUS_SUCCESS;
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		return -ENETDOWN;
-	}
-
-	if (MONITOR_ON(pAdapter))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is in Monitor Mode now !!!\n"));
-        return -EINVAL;
-    }
-
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-	if (pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-		pAdapter->StaCfg.WpaSupplicantScanCount++;
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-    pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-		return 0;
-	do{
-		Now = jiffies;
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-		if ((pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE) &&
-			(pAdapter->StaCfg.WpaSupplicantScanCount > 3))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! WpaSupplicantScanCount > 3\n"));
-			Status = NDIS_STATUS_SUCCESS;
-			break;
-		}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-		if ((OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED)) &&
-			((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-			(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)) &&
-			(pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, Port Not Secured! ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-			Status = NDIS_STATUS_SUCCESS;
-			break;
-		}
-
-		if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-		{
-			RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-			DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-		}
-
-		// tell CNTL state machine to call NdisMSetInformationComplete() after completing
-		// this request, because this request is initiated by NDIS.
-		pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-		// Reset allowed scan retries
-		pAdapter->StaCfg.ScanCnt = 0;
-		pAdapter->StaCfg.LastScanTime = Now;
-
-		MlmeEnqueue(pAdapter,
-			MLME_CNTL_STATE_MACHINE,
-			OID_802_11_BSSID_LIST_SCAN,
-			0,
-			NULL);
-
-		Status = NDIS_STATUS_SUCCESS;
-		RT28XX_MLME_HANDLER(pAdapter);
-	}while(0);
-	return 0;
-}
-
-int rt_ioctl_giwscan(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_point *data, char *extra)
-{
-
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-	int i=0;
-	char *current_ev = extra, *previous_ev = extra;
-	char *end_buf;
-	char *current_val, custom[MAX_CUSTOM_LEN] = {0};
-#ifndef IWEVGENIE
-	char idx;
-#endif // IWEVGENIE //
-	struct iw_event iwe;
-
-	if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-    {
-		/*
-		 * Still scanning, indicate the caller should try again.
-		 */
-		return -EAGAIN;
-	}
-
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-	if (pAdapter->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-		pAdapter->StaCfg.WpaSupplicantScanCount = 0;
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-	if (pAdapter->ScanTab.BssNr == 0)
-	{
-		data->length = 0;
-		return 0;
-	}
-
-#if WIRELESS_EXT >= 17
-    if (data->length > 0)
-        end_buf = extra + data->length;
-    else
-        end_buf = extra + IW_SCAN_MAX_DATA;
-#else
-    end_buf = extra + IW_SCAN_MAX_DATA;
-#endif
-
-	for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-	{
-		if (current_ev >= end_buf)
-        {
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-        }
-
-		//MAC address
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWAP;
-		iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
-				memcpy(iwe.u.ap_addr.sa_data, &pAdapter->ScanTab.BssEntry[i].Bssid, ETH_ALEN);
-
-        previous_ev = current_ev;
-			current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe, IW_EV_ADDR_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		/*
-		Protocol:
-			it will show scanned AP's WirelessMode .
-			it might be
-					802.11a
-					802.11a/n
-					802.11g/n
-					802.11b/g/n
-					802.11g
-					802.11b/g
-		*/
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWNAME;
-
-
-	{
-		PBSS_ENTRY pBssEntry=&pAdapter->ScanTab.BssEntry[i];
-		BOOLEAN isGonly=FALSE;
-		int rateCnt=0;
-
-		if (pBssEntry->Channel>14)
-		{
-			if (pBssEntry->HtCapabilityLen!=0)
-				strcpy(iwe.u.name,"802.11a/n");
-			else
-				strcpy(iwe.u.name,"802.11a");
-		}
-		else
-		{
-			/*
-				if one of non B mode rate is set supported rate . it mean G only.
-			*/
-			for (rateCnt=0;rateCnt<pBssEntry->SupRateLen;rateCnt++)
-			{
-				/*
-					6Mbps(140) 9Mbps(146) and >=12Mbps(152) are supported rate , it mean G only.
-				*/
-				if (pBssEntry->SupRate[rateCnt]==140 || pBssEntry->SupRate[rateCnt]==146 || pBssEntry->SupRate[rateCnt]>=152)
-					isGonly=TRUE;
-			}
-
-			for (rateCnt=0;rateCnt<pBssEntry->ExtRateLen;rateCnt++)
-			{
-				if (pBssEntry->ExtRate[rateCnt]==140 || pBssEntry->ExtRate[rateCnt]==146 || pBssEntry->ExtRate[rateCnt]>=152)
-					isGonly=TRUE;
-			}
-
-
-			if (pBssEntry->HtCapabilityLen!=0)
-			{
-				if (isGonly==TRUE)
-					strcpy(iwe.u.name,"802.11g/n");
-				else
-					strcpy(iwe.u.name,"802.11b/g/n");
-			}
-			else
-			{
-				if (isGonly==TRUE)
-					strcpy(iwe.u.name,"802.11g");
-				else
-				{
-					if (pBssEntry->SupRateLen==4 && pBssEntry->ExtRateLen==0)
-						strcpy(iwe.u.name,"802.11b");
-					else
-						strcpy(iwe.u.name,"802.11b/g");
-				}
-			}
-		}
-	}
-
-		previous_ev = current_ev;
-		current_ev	 = iwe_stream_add_event(info, current_ev, end_buf, &iwe, IW_EV_ADDR_LEN);
-		if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-	   		return -E2BIG;
-#else
-			break;
-#endif
-
-		//ESSID
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWESSID;
-		iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].SsidLen;
-		iwe.u.data.flags = 1;
-
-        previous_ev = current_ev;
-		current_ev = iwe_stream_add_point(info, current_ev, end_buf, &iwe, pAdapter->ScanTab.BssEntry[i].Ssid);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Network Type
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWMODE;
-		if (pAdapter->ScanTab.BssEntry[i].BssType == Ndis802_11IBSS)
-		{
-			iwe.u.mode = IW_MODE_ADHOC;
-		}
-		else if (pAdapter->ScanTab.BssEntry[i].BssType == Ndis802_11Infrastructure)
-		{
-			iwe.u.mode = IW_MODE_INFRA;
-		}
-		else
-		{
-			iwe.u.mode = IW_MODE_AUTO;
-		}
-		iwe.len = IW_EV_UINT_LEN;
-
-        previous_ev = current_ev;
-		current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe,  IW_EV_UINT_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Channel and Frequency
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWFREQ;
-		if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-			iwe.u.freq.m = pAdapter->ScanTab.BssEntry[i].Channel;
-		else
-			iwe.u.freq.m = pAdapter->ScanTab.BssEntry[i].Channel;
-		iwe.u.freq.e = 0;
-		iwe.u.freq.i = 0;
-
-		previous_ev = current_ev;
-		current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe, IW_EV_FREQ_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-        //Add quality statistics
-        //================================
-        memset(&iwe, 0, sizeof(iwe));
-    	iwe.cmd = IWEVQUAL;
-    	iwe.u.qual.level = 0;
-    	iwe.u.qual.noise = 0;
-        set_quality(pAdapter, &iwe.u.qual, pAdapter->ScanTab.BssEntry[i].Rssi);
-    	current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe, IW_EV_QUAL_LEN);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Encyption key
-		//================================
-		memset(&iwe, 0, sizeof(iwe));
-		iwe.cmd = SIOCGIWENCODE;
-		if (CAP_IS_PRIVACY_ON (pAdapter->ScanTab.BssEntry[i].CapabilityInfo ))
-			iwe.u.data.flags =IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
-		else
-			iwe.u.data.flags = IW_ENCODE_DISABLED;
-
-        previous_ev = current_ev;
-        current_ev = iwe_stream_add_point(info, current_ev, end_buf,&iwe, (char *)pAdapter->SharedKey[BSS0][(iwe.u.data.flags & IW_ENCODE_INDEX)-1].Key);
-        if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-            return -E2BIG;
-#else
-			break;
-#endif
-
-		//Bit Rate
-		//================================
-		if (pAdapter->ScanTab.BssEntry[i].SupRateLen)
-        {
-            UCHAR tmpRate = pAdapter->ScanTab.BssEntry[i].SupRate[pAdapter->ScanTab.BssEntry[i].SupRateLen-1];
-			memset(&iwe, 0, sizeof(iwe));
-			iwe.cmd = SIOCGIWRATE;
-    		current_val = current_ev + IW_EV_LCP_LEN;
-            if (tmpRate == 0x82)
-                iwe.u.bitrate.value =  1 * 1000000;
-            else if (tmpRate == 0x84)
-                iwe.u.bitrate.value =  2 * 1000000;
-            else if (tmpRate == 0x8B)
-                iwe.u.bitrate.value =  5.5 * 1000000;
-            else if (tmpRate == 0x96)
-                iwe.u.bitrate.value =  11 * 1000000;
-            else
-    		    iwe.u.bitrate.value =  (tmpRate/2) * 1000000;
-
-			iwe.u.bitrate.disabled = 0;
-			current_val = iwe_stream_add_value(info, current_ev,
-				current_val, end_buf, &iwe,
-    			IW_EV_PARAM_LEN);
-
-        	if((current_val-current_ev)>IW_EV_LCP_LEN)
-            	current_ev = current_val;
-        	else
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-
-#ifdef IWEVGENIE
-		//WPA IE
-		if (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen > 0)
-		{
-			memset(&iwe, 0, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-			memcpy(custom, &(pAdapter->ScanTab.BssEntry[i].WpaIE.IE[0]),
-						   pAdapter->ScanTab.BssEntry[i].WpaIE.IELen);
-			iwe.cmd = IWEVGENIE;
-			iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].WpaIE.IELen;
-			current_ev = iwe_stream_add_point(info, current_ev, end_buf, &iwe, custom);
-			if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-		}
-
-		//WPA2 IE
-        if (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen > 0)
-        {
-        	memset(&iwe, 0, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-			memcpy(custom, &(pAdapter->ScanTab.BssEntry[i].RsnIE.IE[0]),
-						   pAdapter->ScanTab.BssEntry[i].RsnIE.IELen);
-			iwe.cmd = IWEVGENIE;
-			iwe.u.data.length = pAdapter->ScanTab.BssEntry[i].RsnIE.IELen;
-			current_ev = iwe_stream_add_point(info, current_ev, end_buf, &iwe, custom);
-			if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-#else
-        //WPA IE
-		//================================
-        if (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen > 0)
-        {
-    		NdisZeroMemory(&iwe, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-    		iwe.cmd = IWEVCUSTOM;
-            iwe.u.data.length = (pAdapter->ScanTab.BssEntry[i].WpaIE.IELen * 2) + 7;
-            NdisMoveMemory(custom, "wpa_ie=", 7);
-            for (idx = 0; idx < pAdapter->ScanTab.BssEntry[i].WpaIE.IELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAdapter->ScanTab.BssEntry[i].WpaIE.IE[idx]);
-            previous_ev = current_ev;
-    		current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe,  custom);
-            if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-
-        //WPA2 IE
-        if (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen > 0)
-        {
-    		NdisZeroMemory(&iwe, sizeof(iwe));
-			memset(&custom[0], 0, MAX_CUSTOM_LEN);
-    		iwe.cmd = IWEVCUSTOM;
-            iwe.u.data.length = (pAdapter->ScanTab.BssEntry[i].RsnIE.IELen * 2) + 7;
-            NdisMoveMemory(custom, "rsn_ie=", 7);
-			for (idx = 0; idx < pAdapter->ScanTab.BssEntry[i].RsnIE.IELen; idx++)
-                sprintf(custom, "%s%02x", custom, pAdapter->ScanTab.BssEntry[i].RsnIE.IE[idx]);
-            previous_ev = current_ev;
-    		current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe,  custom);
-            if (current_ev == previous_ev)
-#if WIRELESS_EXT >= 17
-                return -E2BIG;
-#else
-			    break;
-#endif
-        }
-#endif // IWEVGENIE //
-	}
-
-	data->length = current_ev - extra;
-    pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-	DBGPRINT(RT_DEBUG_ERROR ,("===>rt_ioctl_giwscan. %d(%d) BSS returned, data->length = %d\n",i , pAdapter->ScanTab.BssNr, data->length));
-	return 0;
-}
-#endif
-
-int rt_ioctl_siwessid(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *essid)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	//check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-       	DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-       	return -ENETDOWN;
-    }
-
-	if (data->flags)
-	{
-		PCHAR	pSsidString = NULL;
-
-		// Includes null character.
-		if (data->length > (IW_ESSID_MAX_SIZE + 1))
-			return -E2BIG;
-
-		pSsidString = (CHAR *) kmalloc(MAX_LEN_OF_SSID+1, MEM_ALLOC_FLAG);
-		if (pSsidString)
-		{
-			NdisZeroMemory(pSsidString, MAX_LEN_OF_SSID+1);
-			NdisMoveMemory(pSsidString, essid, data->length);
-			if (Set_SSID_Proc(pAdapter, pSsidString) == FALSE)
-				return -EINVAL;
-		}
-		else
-			return -ENOMEM;
-	}
-	else
-	{
-		// ANY ssid
-		if (Set_SSID_Proc(pAdapter, "") == FALSE)
-			return -EINVAL;
-    }
-	return 0;
-}
-
-int rt_ioctl_giwessid(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *essid)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	data->flags = 1;
-    if (MONITOR_ON(pAdapter))
-    {
-        data->length  = 0;
-        return 0;
-    }
-
-	if (OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED))
-	{
-		DBGPRINT(RT_DEBUG_TRACE ,("MediaState is connected\n"));
-		data->length = pAdapter->CommonCfg.SsidLen;
-		memcpy(essid, pAdapter->CommonCfg.Ssid, pAdapter->CommonCfg.SsidLen);
-	}
-#ifdef RT2870
-#ifdef WPA_SUPPLICANT_SUPPORT
-    // Add for RT2870
-    else if (pAdapter->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE)
-    {
-        data->length = pAdapter->CommonCfg.SsidLen;
-		memcpy(essid, pAdapter->CommonCfg.Ssid, pAdapter->CommonCfg.SsidLen);
-	}
-#endif // WPA_SUPPLICANT_SUPPORT //
-#endif // RT2870 //
-	else
-	{//the ANY ssid was specified
-		data->length  = 0;
-		DBGPRINT(RT_DEBUG_TRACE ,("MediaState is not connected, ess\n"));
-	}
-
-	return 0;
-
-}
-
-int rt_ioctl_siwnickn(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *nickname)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE ,("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-	if (data->length > IW_ESSID_MAX_SIZE)
-		return -EINVAL;
-
-	memset(pAdapter->nickname, 0, IW_ESSID_MAX_SIZE + 1);
-	memcpy(pAdapter->nickname, nickname, data->length);
-
-
-	return 0;
-}
-
-int rt_ioctl_giwnickn(struct net_device *dev,
-			 struct iw_request_info *info,
-			 struct iw_point *data, char *nickname)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	if (data->length > strlen(pAdapter->nickname) + 1)
-		data->length = strlen(pAdapter->nickname) + 1;
-	if (data->length > 0) {
-		memcpy(nickname, pAdapter->nickname, data->length-1);
-		nickname[data->length-1] = '\0';
-	}
-	return 0;
-}
-
-int rt_ioctl_siwrts(struct net_device *dev,
-		       struct iw_request_info *info,
-		       struct iw_param *rts, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-	u16 val;
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        return -ENETDOWN;
-    }
-
-	if (rts->disabled)
-		val = MAX_RTS_THRESHOLD;
-	else if (rts->value < 0 || rts->value > MAX_RTS_THRESHOLD)
-		return -EINVAL;
-	else if (rts->value == 0)
-	    val = MAX_RTS_THRESHOLD;
-	else
-		val = rts->value;
-
-	if (val != pAdapter->CommonCfg.RtsThreshold)
-		pAdapter->CommonCfg.RtsThreshold = val;
-
-	return 0;
-}
-
-int rt_ioctl_giwrts(struct net_device *dev,
-		       struct iw_request_info *info,
-		       struct iw_param *rts, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	rts->value = pAdapter->CommonCfg.RtsThreshold;
-	rts->disabled = (rts->value == MAX_RTS_THRESHOLD);
-	rts->fixed = 1;
-
-	return 0;
-}
-
-int rt_ioctl_siwfrag(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_param *frag, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-	u16 val;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	if (frag->disabled)
-		val = MAX_FRAG_THRESHOLD;
-	else if (frag->value >= MIN_FRAG_THRESHOLD || frag->value <= MAX_FRAG_THRESHOLD)
-        val = __cpu_to_le16(frag->value & ~0x1); /* even numbers only */
-	else if (frag->value == 0)
-	    val = MAX_FRAG_THRESHOLD;
-	else
-		return -EINVAL;
-
-	pAdapter->CommonCfg.FragmentThreshold = val;
-	return 0;
-}
-
-int rt_ioctl_giwfrag(struct net_device *dev,
-			struct iw_request_info *info,
-			struct iw_param *frag, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	frag->value = pAdapter->CommonCfg.FragmentThreshold;
-	frag->disabled = (frag->value == MAX_FRAG_THRESHOLD);
-	frag->fixed = 1;
-
-	return 0;
-}
-
-#define MAX_WEP_KEY_SIZE 13
-#define MIN_WEP_KEY_SIZE 5
-int rt_ioctl_siwencode(struct net_device *dev,
-			  struct iw_request_info *info,
-			  struct iw_point *erq, char *extra)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-        	return -ENETDOWN;
-    	}
-
-	if ((erq->length == 0) &&
-        (erq->flags & IW_ENCODE_DISABLED))
-	{
-		pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-		pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-		pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-        pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-        goto done;
-	}
-	else if (erq->flags & IW_ENCODE_RESTRICTED || erq->flags & IW_ENCODE_OPEN)
-	{
-	    //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-		STA_PORT_SECURED(pAdapter);
-		pAdapter->StaCfg.PairCipher = Ndis802_11WEPEnabled;
-		pAdapter->StaCfg.GroupCipher = Ndis802_11WEPEnabled;
-		pAdapter->StaCfg.WepStatus = Ndis802_11WEPEnabled;
-        pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-		if (erq->flags & IW_ENCODE_RESTRICTED)
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-    	else
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-	}
-
-    if (erq->length > 0)
-	{
-		int keyIdx = (erq->flags & IW_ENCODE_INDEX) - 1;
-		/* Check the size of the key */
-		if (erq->length > MAX_WEP_KEY_SIZE)
-		{
-			return -EINVAL;
-		}
-		/* Check key index */
-		if ((keyIdx < 0) || (keyIdx >= NR_WEP_KEYS))
-        {
-            DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::Wrong keyIdx=%d! Using default key instead (%d)\n",
-                                        keyIdx, pAdapter->StaCfg.DefaultKeyId));
-
-            //Using default key
-			keyIdx = pAdapter->StaCfg.DefaultKeyId;
-        }
-		else
-		{
-			pAdapter->StaCfg.DefaultKeyId=keyIdx;
-		}
-
-        NdisZeroMemory(pAdapter->SharedKey[BSS0][keyIdx].Key,  16);
-
-		if (erq->length == MAX_WEP_KEY_SIZE)
-        {
-			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MAX_WEP_KEY_SIZE;
-            pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP128;
-		}
-		else if (erq->length == MIN_WEP_KEY_SIZE)
-        {
-            pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MIN_WEP_KEY_SIZE;
-            pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP64;
-		}
-		else
-			/* Disable the key */
-			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = 0;
-
-		/* Check if the key is not marked as invalid */
-		if(!(erq->flags & IW_ENCODE_NOKEY))
-		{
-			/* Copy the key in the driver */
-			NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, extra, erq->length);
-        }
-	}
-    else
-			{
-		/* Do we want to just set the transmit key index ? */
-		int index = (erq->flags & IW_ENCODE_INDEX) - 1;
-		if ((index >= 0) && (index < 4))
-        {
-			pAdapter->StaCfg.DefaultKeyId = index;
-            }
-        else
-			/* Don't complain if only change the mode */
-		if(!erq->flags & IW_ENCODE_MODE)
-		{
-				return -EINVAL;
-		}
-	}
-
-done:
-    DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::erq->flags=%x\n",erq->flags));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::AuthMode=%x\n",pAdapter->StaCfg.AuthMode));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::DefaultKeyId=%x, KeyLen = %d\n",pAdapter->StaCfg.DefaultKeyId , pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen));
-	DBGPRINT(RT_DEBUG_TRACE ,("==>rt_ioctl_siwencode::WepStatus=%x\n",pAdapter->StaCfg.WepStatus));
-	return 0;
-}
-
-int
-rt_ioctl_giwencode(struct net_device *dev,
-			  struct iw_request_info *info,
-			  struct iw_point *erq, char *key)
-{
-	PRTMP_ADAPTER pAdapter = dev->ml_priv;
-	int kid;
-
-	//check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-	kid = erq->flags & IW_ENCODE_INDEX;
-	DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_giwencode %d\n", erq->flags & IW_ENCODE_INDEX));
-
-	if (pAdapter->StaCfg.WepStatus == Ndis802_11WEPDisabled)
-	{
-		erq->length = 0;
-		erq->flags = IW_ENCODE_DISABLED;
-	}
-	else if ((kid > 0) && (kid <=4))
-	{
-		// copy wep key
-		erq->flags = kid ;			/* NB: base 1 */
-		if (erq->length > pAdapter->SharedKey[BSS0][kid-1].KeyLen)
-			erq->length = pAdapter->SharedKey[BSS0][kid-1].KeyLen;
-		memcpy(key, pAdapter->SharedKey[BSS0][kid-1].Key, erq->length);
-		//if ((kid == pAdapter->PortCfg.DefaultKeyId))
-		//erq->flags |= IW_ENCODE_ENABLED;	/* XXX */
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-
-	}
-	else if (kid == 0)
-	{
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-		erq->length = pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen;
-		memcpy(key, pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key, erq->length);
-		// copy default key ID
-		if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared)
-			erq->flags |= IW_ENCODE_RESTRICTED;		/* XXX */
-		else
-			erq->flags |= IW_ENCODE_OPEN;		/* XXX */
-		erq->flags = pAdapter->StaCfg.DefaultKeyId + 1;			/* NB: base 1 */
-		erq->flags |= IW_ENCODE_ENABLED;	/* XXX */
-	}
-
-	return 0;
-
-}
-
-static int
-rt_ioctl_setparam(struct net_device *dev, struct iw_request_info *info,
-			 void *w, char *extra)
-{
-    VIRTUAL_ADAPTER	*pVirtualAd = NULL;
-	PRTMP_ADAPTER pAdapter;
-	POS_COOKIE pObj;
-	char *this_char = extra;
-	char *value;
-	int  Status=0;
-
-	if (dev->priv_flags == INT_MAIN)
-	{
-		pAdapter = dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		pAdapter = pVirtualAd->RtmpDev->ml_priv;
-	}
-	pObj = (POS_COOKIE) pAdapter->OS_Cookie;
-
-	if (pAdapter == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-	{
-		pObj->ioctl_if_type = INT_MAIN;
-        pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-	//check if the interface is down
-    	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    	{
-      		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-			return -ENETDOWN;
-    	}
-
-	if (!*this_char)
-		return -EINVAL;
-
-	if ((value = rtstrchr(this_char, '=')) != NULL)
-	    *value++ = 0;
-
-	if (!value)
-	    return -EINVAL;
-
-	// reject setting nothing besides ANY ssid(ssidLen=0)
-    if (!*value && (strcmp(this_char, "SSID") != 0))
-        return -EINVAL;
-
-	for (PRTMP_PRIVATE_SET_PROC = RTMP_PRIVATE_SUPPORT_PROC; PRTMP_PRIVATE_SET_PROC->name; PRTMP_PRIVATE_SET_PROC++)
-	{
-	    if (strcmp(this_char, PRTMP_PRIVATE_SET_PROC->name) == 0)
-	    {
-	        if(!PRTMP_PRIVATE_SET_PROC->set_proc(pAdapter, value))
-	        {	//FALSE:Set private failed then return Invalid argument
-			    Status = -EINVAL;
-	        }
-		    break;	//Exit for loop.
-	    }
-	}
-
-	if(PRTMP_PRIVATE_SET_PROC->name == NULL)
-	{  //Not found argument
-	    Status = -EINVAL;
-	    DBGPRINT(RT_DEBUG_TRACE, ("===>rt_ioctl_setparam:: (iwpriv) Not Support Set Command [%s=%s]\n", this_char, value));
-	}
-
-    return Status;
-}
-
-
-static int
-rt_private_get_statistics(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-{
-	INT				Status = 0;
-    PRTMP_ADAPTER   pAd = dev->ml_priv;
-
-    if (extra == NULL)
-    {
-        wrq->length = 0;
-        return -EIO;
-    }
-
-    memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-    sprintf(extra, "\n\n");
-
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-	    sprintf(extra+strlen(extra), "Tx success                      = %ld\n", (ULONG)pAd->ate.TxDoneCount);
-	    //sprintf(extra+strlen(extra), "Tx success without retry        = %ld\n", (ULONG)pAd->ate.TxDoneCount);
-	}
-	else
-#endif // RALINK_ATE //
-	{
-    sprintf(extra+strlen(extra), "Tx success                      = %ld\n", (ULONG)pAd->WlanCounters.TransmittedFragmentCount.QuadPart);
-    sprintf(extra+strlen(extra), "Tx success without retry        = %ld\n", (ULONG)pAd->WlanCounters.TransmittedFragmentCount.QuadPart - (ULONG)pAd->WlanCounters.RetryCount.QuadPart);
-	}
-    sprintf(extra+strlen(extra), "Tx success after retry          = %ld\n", (ULONG)pAd->WlanCounters.RetryCount.QuadPart);
-    sprintf(extra+strlen(extra), "Tx fail to Rcv ACK after retry  = %ld\n", (ULONG)pAd->WlanCounters.FailedCount.QuadPart);
-    sprintf(extra+strlen(extra), "RTS Success Rcv CTS             = %ld\n", (ULONG)pAd->WlanCounters.RTSSuccessCount.QuadPart);
-    sprintf(extra+strlen(extra), "RTS Fail Rcv CTS                = %ld\n", (ULONG)pAd->WlanCounters.RTSFailureCount.QuadPart);
-
-    sprintf(extra+strlen(extra), "Rx success                      = %ld\n", (ULONG)pAd->WlanCounters.ReceivedFragmentCount.QuadPart);
-    sprintf(extra+strlen(extra), "Rx with CRC                     = %ld\n", (ULONG)pAd->WlanCounters.FCSErrorCount.QuadPart);
-    sprintf(extra+strlen(extra), "Rx drop due to out of resource  = %ld\n", (ULONG)pAd->Counters8023.RxNoBuffer);
-    sprintf(extra+strlen(extra), "Rx duplicate frame              = %ld\n", (ULONG)pAd->WlanCounters.FrameDuplicateCount.QuadPart);
-
-    sprintf(extra+strlen(extra), "False CCA (one second)          = %ld\n", (ULONG)pAd->RalinkCounters.OneSecFalseCCACnt);
-#ifdef RALINK_ATE
-	if (ATE_ON(pAd))
-	{
-		if (pAd->ate.RxAntennaSel == 0)
-		{
-    		sprintf(extra+strlen(extra), "RSSI-A                          = %ld\n", (LONG)(pAd->ate.LastRssi0 - pAd->BbpRssiToDbmDelta));
-			sprintf(extra+strlen(extra), "RSSI-B (if available)           = %ld\n", (LONG)(pAd->ate.LastRssi1 - pAd->BbpRssiToDbmDelta));
-			sprintf(extra+strlen(extra), "RSSI-C (if available)           = %ld\n\n", (LONG)(pAd->ate.LastRssi2 - pAd->BbpRssiToDbmDelta));
-		}
-		else
-		{
-    		sprintf(extra+strlen(extra), "RSSI                            = %ld\n", (LONG)(pAd->ate.LastRssi0 - pAd->BbpRssiToDbmDelta));
-		}
-	}
-	else
-#endif // RALINK_ATE //
-	{
-    	sprintf(extra+strlen(extra), "RSSI-A                          = %ld\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi0 - pAd->BbpRssiToDbmDelta));
-        sprintf(extra+strlen(extra), "RSSI-B (if available)           = %ld\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi1 - pAd->BbpRssiToDbmDelta));
-        sprintf(extra+strlen(extra), "RSSI-C (if available)           = %ld\n\n", (LONG)(pAd->StaCfg.RssiSample.LastRssi2 - pAd->BbpRssiToDbmDelta));
-	}
-#ifdef WPA_SUPPLICANT_SUPPORT
-    sprintf(extra+strlen(extra), "WpaSupplicantUP                 = %d\n\n", pAd->StaCfg.WpaSupplicantUP);
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-    DBGPRINT(RT_DEBUG_TRACE, ("<== rt_private_get_statistics, wrq->length = %d\n", wrq->length));
-
-    return Status;
-}
-
-#ifdef DOT11_N_SUPPORT
-void	getBaInfo(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			pOutBuf)
-{
-	INT i, j;
-	BA_ORI_ENTRY *pOriBAEntry;
-	BA_REC_ENTRY *pRecBAEntry;
-
-	for (i=0; i<MAX_LEN_OF_MAC_TABLE; i++)
-	{
-		PMAC_TABLE_ENTRY pEntry = &pAd->MacTab.Content[i];
-		if (((pEntry->ValidAsCLI || pEntry->ValidAsApCli) && (pEntry->Sst == SST_ASSOC))
-			|| (pEntry->ValidAsWDS) || (pEntry->ValidAsMesh))
-		{
-			sprintf(pOutBuf, "%s\n%02X:%02X:%02X:%02X:%02X:%02X (Aid = %d) (AP) -\n",
-                pOutBuf,
-				pEntry->Addr[0], pEntry->Addr[1], pEntry->Addr[2],
-				pEntry->Addr[3], pEntry->Addr[4], pEntry->Addr[5], pEntry->Aid);
-
-			sprintf(pOutBuf, "%s[Recipient]\n", pOutBuf);
-			for (j=0; j < NUM_OF_TID; j++)
-			{
-				if (pEntry->BARecWcidArray[j] != 0)
-				{
-					pRecBAEntry =&pAd->BATable.BARecEntry[pEntry->BARecWcidArray[j]];
-					sprintf(pOutBuf, "%sTID=%d, BAWinSize=%d, LastIndSeq=%d, ReorderingPkts=%d\n", pOutBuf, j, pRecBAEntry->BAWinSize, pRecBAEntry->LastIndSeq, pRecBAEntry->list.qlen);
-				}
-			}
-			sprintf(pOutBuf, "%s\n", pOutBuf);
-
-			sprintf(pOutBuf, "%s[Originator]\n", pOutBuf);
-			for (j=0; j < NUM_OF_TID; j++)
-			{
-				if (pEntry->BAOriWcidArray[j] != 0)
-				{
-					pOriBAEntry =&pAd->BATable.BAOriEntry[pEntry->BAOriWcidArray[j]];
-					sprintf(pOutBuf, "%sTID=%d, BAWinSize=%d, StartSeq=%d, CurTxSeq=%d\n", pOutBuf, j, pOriBAEntry->BAWinSize, pOriBAEntry->Sequence, pEntry->TxSeq[j]);
-				}
-			}
-			sprintf(pOutBuf, "%s\n\n", pOutBuf);
-		}
-        if (strlen(pOutBuf) > (IW_PRIV_SIZE_MASK - 30))
-                break;
-	}
-
-	return;
-}
-#endif // DOT11_N_SUPPORT //
-
-static int
-rt_private_show(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-{
-    INT				Status = 0;
-    VIRTUAL_ADAPTER	*pVirtualAd = NULL;
-    PRTMP_ADAPTER   pAd;
-	POS_COOKIE		pObj;
-    u32             subcmd = wrq->flags;
-
-	if (dev->priv_flags == INT_MAIN)
-		pAd = dev->ml_priv;
-	else
-	{
-		pVirtualAd = dev->ml_priv;
-		pAd = pVirtualAd->RtmpDev->ml_priv;
-	}
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-    if (extra == NULL)
-    {
-        wrq->length = 0;
-        return -EIO;
-    }
-    memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-
-	{
-		pObj->ioctl_if_type = INT_MAIN;
-        pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-    switch(subcmd)
-    {
-
-        case SHOW_CONN_STATUS:
-            if (MONITOR_ON(pAd))
-            {
-#ifdef DOT11_N_SUPPORT
-                if (pAd->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-                    pAd->CommonCfg.RegTransmitSetting.field.BW)
-                    sprintf(extra, "Monitor Mode(CentralChannel %d)\n", pAd->CommonCfg.CentralChannel);
-                else
-#endif // DOT11_N_SUPPORT //
-                    sprintf(extra, "Monitor Mode(Channel %d)\n", pAd->CommonCfg.Channel);
-            }
-            else
-            {
-                if (pAd->IndicateMediaState == NdisMediaStateConnected)
-            	{
-            	    if (INFRA_ON(pAd))
-                    {
-                    sprintf(extra, "Connected(AP: %s[%02X:%02X:%02X:%02X:%02X:%02X])\n",
-                                    pAd->CommonCfg.Ssid,
-                                    pAd->CommonCfg.Bssid[0],
-                                    pAd->CommonCfg.Bssid[1],
-                                    pAd->CommonCfg.Bssid[2],
-                                    pAd->CommonCfg.Bssid[3],
-                                    pAd->CommonCfg.Bssid[4],
-                                    pAd->CommonCfg.Bssid[5]);
-            		DBGPRINT(RT_DEBUG_TRACE ,("Ssid=%s ,Ssidlen = %d\n",pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen));
-            	}
-                    else if (ADHOC_ON(pAd))
-                        sprintf(extra, "Connected\n");
-            	}
-            	else
-            	{
-            	    sprintf(extra, "Disconnected\n");
-            		DBGPRINT(RT_DEBUG_TRACE ,("ConnStatus is not connected\n"));
-            	}
-            }
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-        case SHOW_DRVIER_VERION:
-            sprintf(extra, "Driver version-%s, %s %s\n", STA_DRIVER_VERSION, __DATE__, __TIME__ );
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-#ifdef DOT11_N_SUPPORT
-        case SHOW_BA_INFO:
-            getBaInfo(pAd, extra);
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-#endif // DOT11_N_SUPPORT //
-		case SHOW_DESC_INFO:
-			{
-				Show_DescInfo_Proc(pAd, NULL);
-				wrq->length = 0; // 1: size of '\0'
-			}
-			break;
-        case RAIO_OFF:
-            if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-                sprintf(extra, "Scanning\n");
-                wrq->length = strlen(extra) + 1; // 1: size of '\0'
-                break;
-            }
-            pAd->StaCfg.bSwRadio = FALSE;
-            if (pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
-            {
-                pAd->StaCfg.bRadio = (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio);
-                if (pAd->StaCfg.bRadio == FALSE)
-                {
-                    MlmeRadioOff(pAd);
-                    // Update extra information
-					pAd->ExtraInfo = SW_RADIO_OFF;
-                }
-            }
-            sprintf(extra, "Radio Off\n");
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-        case RAIO_ON:
-            if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-                sprintf(extra, "Scanning\n");
-                wrq->length = strlen(extra) + 1; // 1: size of '\0'
-                break;
-            }
-            pAd->StaCfg.bSwRadio = TRUE;
-            //if (pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
-            {
-                pAd->StaCfg.bRadio = (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio);
-                if (pAd->StaCfg.bRadio == TRUE)
-                {
-                    MlmeRadioOn(pAd);
-                    // Update extra information
-					pAd->ExtraInfo = EXTRA_INFO_CLEAR;
-                }
-            }
-            sprintf(extra, "Radio On\n");
-            wrq->length = strlen(extra) + 1; // 1: size of '\0'
-            break;
-
-
-#ifdef QOS_DLS_SUPPORT
-		case SHOW_DLS_ENTRY_INFO:
-			{
-				Set_DlsEntryInfo_Display_Proc(pAd, NULL);
-				wrq->length = 0; // 1: size of '\0'
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-
-		case SHOW_CFG_VALUE:
-			{
-				Status = RTMPShowCfgValue(pAd, wrq->pointer, extra);
-				if (Status == 0)
-					wrq->length = strlen(extra) + 1; // 1: size of '\0'
-			}
-			break;
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("%s - unknow subcmd = %d\n", __FUNCTION__, subcmd));
-            break;
-    }
-
-    return Status;
-}
-
-#ifdef SIOCSIWMLME
-int rt_ioctl_siwmlme(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-{
-	PRTMP_ADAPTER   pAd = dev->ml_priv;
-	struct iw_mlme *pMlme = (struct iw_mlme *)wrqu->data.pointer;
-	MLME_QUEUE_ELEM				MsgElem;
-	MLME_DISASSOC_REQ_STRUCT	DisAssocReq;
-	MLME_DEAUTH_REQ_STRUCT      DeAuthReq;
-
-	DBGPRINT(RT_DEBUG_TRACE, ("====> %s\n", __FUNCTION__));
-
-	if (pMlme == NULL)
-		return -EINVAL;
-
-	switch(pMlme->cmd)
-	{
-#ifdef IW_MLME_DEAUTH
-		case IW_MLME_DEAUTH:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - IW_MLME_DEAUTH\n", __FUNCTION__));
-			COPY_MAC_ADDR(DeAuthReq.Addr, pAd->CommonCfg.Bssid);
-			DeAuthReq.Reason = pMlme->reason_code;
-			MsgElem.MsgLen = sizeof(MLME_DEAUTH_REQ_STRUCT);
-			NdisMoveMemory(MsgElem.Msg, &DeAuthReq, sizeof(MLME_DEAUTH_REQ_STRUCT));
-			MlmeDeauthReqAction(pAd, &MsgElem);
-			if (INFRA_ON(pAd))
-			{
-			    LinkDown(pAd, FALSE);
-			    pAd->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-			}
-			break;
-#endif // IW_MLME_DEAUTH //
-#ifdef IW_MLME_DISASSOC
-		case IW_MLME_DISASSOC:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - IW_MLME_DISASSOC\n", __FUNCTION__));
-			COPY_MAC_ADDR(DisAssocReq.Addr, pAd->CommonCfg.Bssid);
-			DisAssocReq.Reason =  pMlme->reason_code;
-
-			MsgElem.Machine = ASSOC_STATE_MACHINE;
-			MsgElem.MsgType = MT2_MLME_DISASSOC_REQ;
-			MsgElem.MsgLen = sizeof(MLME_DISASSOC_REQ_STRUCT);
-			NdisMoveMemory(MsgElem.Msg, &DisAssocReq, sizeof(MLME_DISASSOC_REQ_STRUCT));
-
-			pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_DISASSOC;
-			MlmeDisassocReqAction(pAd, &MsgElem);
-			break;
-#endif // IW_MLME_DISASSOC //
-		default:
-			DBGPRINT(RT_DEBUG_TRACE, ("====> %s - Unknow Command\n", __FUNCTION__));
-			break;
-	}
-
-	return 0;
-}
-#endif // SIOCSIWMLME //
-
-#if WIRELESS_EXT > 17
-int rt_ioctl_siwauth(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAdapter = dev->ml_priv;
-	struct iw_param *param = &wrqu->param;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-	switch (param->flags & IW_AUTH_INDEX) {
-    	case IW_AUTH_WPA_VERSION:
-            if (param->value == IW_AUTH_WPA_VERSION_WPA)
-            {
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPAPSK;
-				if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-					pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
-            }
-            else if (param->value == IW_AUTH_WPA_VERSION_WPA2)
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_VERSION - param->value = %d!\n", __FUNCTION__, param->value));
-            break;
-    	case IW_AUTH_CIPHER_PAIRWISE:
-            if (param->value == IW_AUTH_CIPHER_NONE)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_WEP40 ||
-                     param->value == IW_AUTH_CIPHER_WEP104)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPEnabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPEnabled;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-            }
-            else if (param->value == IW_AUTH_CIPHER_TKIP)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11Encryption2Enabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11Encryption2Enabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_CCMP)
-            {
-                pAdapter->StaCfg.WepStatus = Ndis802_11Encryption3Enabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11Encryption3Enabled;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_CIPHER_PAIRWISE - param->value = %d!\n", __FUNCTION__, param->value));
-            break;
-    	case IW_AUTH_CIPHER_GROUP:
-            if (param->value == IW_AUTH_CIPHER_NONE)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_WEP40 ||
-                     param->value == IW_AUTH_CIPHER_WEP104)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11WEPEnabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_TKIP)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11Encryption2Enabled;
-            }
-            else if (param->value == IW_AUTH_CIPHER_CCMP)
-            {
-                pAdapter->StaCfg.GroupCipher = Ndis802_11Encryption3Enabled;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_CIPHER_GROUP - param->value = %d!\n", __FUNCTION__, param->value));
-            break;
-    	case IW_AUTH_KEY_MGMT:
-            if (param->value == IW_AUTH_KEY_MGMT_802_1X)
-            {
-                if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK)
-                {
-                    pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                    pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                }
-                else if (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)
-                {
-                    pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#ifdef WPA_SUPPLICANT_SUPPORT
-                    pAdapter->StaCfg.IEEE8021X = FALSE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                }
-#ifdef WPA_SUPPLICANT_SUPPORT
-                else
-                    // WEP 1x
-                    pAdapter->StaCfg.IEEE8021X = TRUE;
-#endif // WPA_SUPPLICANT_SUPPORT //
-            }
-            else if (param->value == 0)
-            {
-                //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAdapter);
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_KEY_MGMT - param->value = %d!\n", __FUNCTION__, param->value));
-            break;
-    	case IW_AUTH_RX_UNENCRYPTED_EAPOL:
-            break;
-    	case IW_AUTH_PRIVACY_INVOKED:
-            /*if (param->value == 0)
-			{
-                pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-                pAdapter->StaCfg.WepStatus = Ndis802_11WEPDisabled;
-                pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-                pAdapter->StaCfg.PairCipher = Ndis802_11WEPDisabled;
-        	    pAdapter->StaCfg.GroupCipher = Ndis802_11WEPDisabled;
-            }*/
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_PRIVACY_INVOKED - param->value = %d!\n", __FUNCTION__, param->value));
-    		break;
-    	case IW_AUTH_DROP_UNENCRYPTED:
-            if (param->value != 0)
-                pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-			else
-			{
-                //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				STA_PORT_SECURED(pAdapter);
-			}
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_VERSION - param->value = %d!\n", __FUNCTION__, param->value));
-    		break;
-    	case IW_AUTH_80211_AUTH_ALG:
-			if (param->value & IW_AUTH_ALG_SHARED_KEY)
-            {
-				pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-			}
-            else if (param->value & IW_AUTH_ALG_OPEN_SYSTEM)
-            {
-				pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-			}
-            else
-				return -EINVAL;
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_80211_AUTH_ALG - param->value = %d!\n", __FUNCTION__, param->value));
-			break;
-    	case IW_AUTH_WPA_ENABLED:
-    		DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_AUTH_WPA_ENABLED - Driver supports WPA!(param->value = %d)\n", __FUNCTION__, param->value));
-    		break;
-    	default:
-    		return -EOPNOTSUPP;
-}
-
-	return 0;
-}
-
-int rt_ioctl_giwauth(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAdapter = dev->ml_priv;
-	struct iw_param *param = &wrqu->param;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-    }
-
-	switch (param->flags & IW_AUTH_INDEX) {
-	case IW_AUTH_DROP_UNENCRYPTED:
-        param->value = (pAdapter->StaCfg.WepStatus == Ndis802_11WEPDisabled) ? 0 : 1;
-		break;
-
-	case IW_AUTH_80211_AUTH_ALG:
-        param->value = (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeShared) ? IW_AUTH_ALG_SHARED_KEY : IW_AUTH_ALG_OPEN_SYSTEM;
-		break;
-
-	case IW_AUTH_WPA_ENABLED:
-		param->value = (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA) ? 1 : 0;
-		break;
-
-	default:
-		return -EOPNOTSUPP;
-	}
-    DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_giwauth::param->value = %d!\n", param->value));
-	return 0;
-}
-
-void fnSetCipherKey(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  INT             keyIdx,
-    IN  UCHAR           CipherAlg,
-    IN  BOOLEAN         bGTK,
-    IN  struct iw_encode_ext *ext)
-{
-    NdisZeroMemory(&pAdapter->SharedKey[BSS0][keyIdx], sizeof(CIPHER_KEY));
-    pAdapter->SharedKey[BSS0][keyIdx].KeyLen = LEN_TKIP_EK;
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, ext->key, LEN_TKIP_EK);
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].TxMic, ext->key + LEN_TKIP_EK, LEN_TKIP_TXMICK);
-    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].RxMic, ext->key + LEN_TKIP_EK + LEN_TKIP_TXMICK, LEN_TKIP_RXMICK);
-    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CipherAlg;
-
-    // Update group key information to ASIC Shared Key Table
-	AsicAddSharedKeyEntry(pAdapter,
-						  BSS0,
-						  keyIdx,
-						  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-						  pAdapter->SharedKey[BSS0][keyIdx].Key,
-						  pAdapter->SharedKey[BSS0][keyIdx].TxMic,
-						  pAdapter->SharedKey[BSS0][keyIdx].RxMic);
-
-    if (bGTK)
-        // Update ASIC WCID attribute table and IVEIV table
-    	RTMPAddWcidAttributeEntry(pAdapter,
-    							  BSS0,
-    							  keyIdx,
-    							  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-    							  NULL);
-    else
-        // Update ASIC WCID attribute table and IVEIV table
-    	RTMPAddWcidAttributeEntry(pAdapter,
-    							  BSS0,
-    							  keyIdx,
-    							  pAdapter->SharedKey[BSS0][keyIdx].CipherAlg,
-    							  &pAdapter->MacTab.Content[BSSID_WCID]);
-}
-
-int rt_ioctl_siwencodeext(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-			{
-    PRTMP_ADAPTER   pAdapter = dev->ml_priv;
-	struct iw_point *encoding = &wrqu->encoding;
-	struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
-    int keyIdx, alg = ext->alg;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    if (encoding->flags & IW_ENCODE_DISABLED)
-	{
-        keyIdx = (encoding->flags & IW_ENCODE_INDEX) - 1;
-        // set BSSID wcid entry of the Pair-wise Key table as no-security mode
-	    AsicRemovePairwiseKeyEntry(pAdapter, BSS0, BSSID_WCID);
-        pAdapter->SharedKey[BSS0][keyIdx].KeyLen = 0;
-		pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_NONE;
-		AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)keyIdx);
-        NdisZeroMemory(&pAdapter->SharedKey[BSS0][keyIdx], sizeof(CIPHER_KEY));
-        DBGPRINT(RT_DEBUG_TRACE, ("%s::Remove all keys!(encoding->flags = %x)\n", __FUNCTION__, encoding->flags));
-    }
-					else
-    {
-        // Get Key Index and convet to our own defined key index
-    	keyIdx = (encoding->flags & IW_ENCODE_INDEX) - 1;
-    	if((keyIdx < 0) || (keyIdx >= NR_WEP_KEYS))
-    		return -EINVAL;
-
-        if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-        {
-            pAdapter->StaCfg.DefaultKeyId = keyIdx;
-            DBGPRINT(RT_DEBUG_TRACE, ("%s::DefaultKeyId = %d\n", __FUNCTION__, pAdapter->StaCfg.DefaultKeyId));
-        }
-
-        switch (alg) {
-    		case IW_ENCODE_ALG_NONE:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_NONE\n", __FUNCTION__));
-    			break;
-    		case IW_ENCODE_ALG_WEP:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_WEP - ext->key_len = %d, keyIdx = %d\n", __FUNCTION__, ext->key_len, keyIdx));
-    			if (ext->key_len == MAX_WEP_KEY_SIZE)
-                {
-        			pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MAX_WEP_KEY_SIZE;
-                    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP128;
-				}
-        		else if (ext->key_len == MIN_WEP_KEY_SIZE)
-                {
-                    pAdapter->SharedKey[BSS0][keyIdx].KeyLen = MIN_WEP_KEY_SIZE;
-                    pAdapter->SharedKey[BSS0][keyIdx].CipherAlg = CIPHER_WEP64;
-			}
-        		else
-                    return -EINVAL;
-
-                NdisZeroMemory(pAdapter->SharedKey[BSS0][keyIdx].Key,  16);
-			    NdisMoveMemory(pAdapter->SharedKey[BSS0][keyIdx].Key, ext->key, ext->key_len);
-    			break;
-            case IW_ENCODE_ALG_TKIP:
-                DBGPRINT(RT_DEBUG_TRACE, ("%s::IW_ENCODE_ALG_TKIP - keyIdx = %d, ext->key_len = %d\n", __FUNCTION__, keyIdx, ext->key_len));
-                if (ext->key_len == 32)
-                {
-                    if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-                    {
-                        fnSetCipherKey(pAdapter, keyIdx, CIPHER_TKIP, FALSE, ext);
-                        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-                        {
-                            //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-                            STA_PORT_SECURED(pAdapter);
-                        }
-		}
-                    else if (ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY)
-                    {
-                        fnSetCipherKey(pAdapter, keyIdx, CIPHER_TKIP, TRUE, ext);
-
-                        // set 802.1x port control
-            	        //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-            	        STA_PORT_SECURED(pAdapter);
-                    }
-                }
-                else
-                    return -EINVAL;
-                break;
-            case IW_ENCODE_ALG_CCMP:
-                if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
-		{
-                    fnSetCipherKey(pAdapter, keyIdx, CIPHER_AES, FALSE, ext);
-                    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA2)
-                    	//pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-                    	STA_PORT_SECURED(pAdapter);
-                }
-                else if (ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY)
-                {
-                    fnSetCipherKey(pAdapter, keyIdx, CIPHER_AES, TRUE, ext);
-
-                    // set 802.1x port control
-        	        //pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-        	        STA_PORT_SECURED(pAdapter);
-                }
-                break;
-    		default:
-    			return -EINVAL;
-		}
-    }
-
-    return 0;
-}
-
-int
-rt_ioctl_giwencodeext(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER pAd = dev->ml_priv;
-	PCHAR pKey = NULL;
-	struct iw_point *encoding = &wrqu->encoding;
-	struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
-	int idx, max_key_len;
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===> rt_ioctl_giwencodeext\n"));
-
-	max_key_len = encoding->length - sizeof(*ext);
-	if (max_key_len < 0)
-		return -EINVAL;
-
-	idx = encoding->flags & IW_ENCODE_INDEX;
-	if (idx)
-	{
-		if (idx < 1 || idx > 4)
-			return -EINVAL;
-		idx--;
-
-		if ((pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) ||
-			(pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled))
-		{
-			if (idx != pAd->StaCfg.DefaultKeyId)
-			{
-				ext->key_len = 0;
-				return 0;
-			}
-		}
-	}
-	else
-		idx = pAd->StaCfg.DefaultKeyId;
-
-	encoding->flags = idx + 1;
-	memset(ext, 0, sizeof(*ext));
-
-	ext->key_len = 0;
-	switch(pAd->StaCfg.WepStatus) {
-		case Ndis802_11WEPDisabled:
-			ext->alg = IW_ENCODE_ALG_NONE;
-			encoding->flags |= IW_ENCODE_DISABLED;
-			break;
-		case Ndis802_11WEPEnabled:
-			ext->alg = IW_ENCODE_ALG_WEP;
-			if (pAd->SharedKey[BSS0][idx].KeyLen > max_key_len)
-				return -E2BIG;
-			else
-			{
-				ext->key_len = pAd->SharedKey[BSS0][idx].KeyLen;
-				pKey = &(pAd->SharedKey[BSS0][idx].Key[0]);
-			}
-			break;
-		case Ndis802_11Encryption2Enabled:
-		case Ndis802_11Encryption3Enabled:
-			if (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled)
-				ext->alg = IW_ENCODE_ALG_TKIP;
-			else
-				ext->alg = IW_ENCODE_ALG_CCMP;
-
-			if (max_key_len < 32)
-				return -E2BIG;
-			else
-			{
-				ext->key_len = 32;
-				pKey = &pAd->StaCfg.PMK[0];
-			}
-			break;
-		default:
-			return -EINVAL;
-	}
-
-	if (ext->key_len && pKey)
-	{
-		encoding->flags |= IW_ENCODE_ENABLED;
-		memcpy(ext->key, pKey, ext->key_len);
-	}
-
-	return 0;
-}
-
-#ifdef SIOCSIWGENIE
-int rt_ioctl_siwgenie(struct net_device *dev,
-			  struct iw_request_info *info,
-			  union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAd = dev->ml_priv;
-
-	if (wrqu->data.length > MAX_LEN_OF_RSNIE ||
-	    (wrqu->data.length && extra == NULL))
-		return -EINVAL;
-
-	if (wrqu->data.length)
-	{
-		pAd->StaCfg.RSNIE_Len = wrqu->data.length;
-		NdisMoveMemory(&pAd->StaCfg.RSN_IE[0], extra, pAd->StaCfg.RSNIE_Len);
-	}
-	else
-	{
-		pAd->StaCfg.RSNIE_Len = 0;
-		NdisZeroMemory(&pAd->StaCfg.RSN_IE[0], MAX_LEN_OF_RSNIE);
-	}
-
-	return 0;
-}
-#endif // SIOCSIWGENIE //
-
-int rt_ioctl_giwgenie(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-	PRTMP_ADAPTER   pAd = dev->ml_priv;
-
-	if ((pAd->StaCfg.RSNIE_Len == 0) ||
-		(pAd->StaCfg.AuthMode < Ndis802_11AuthModeWPA))
-	{
-		wrqu->data.length = 0;
-		return 0;
-	}
-
-#ifdef NATIVE_WPA_SUPPLICANT_SUPPORT
-#ifdef SIOCSIWGENIE
-	if (pAd->StaCfg.WpaSupplicantUP == WPA_SUPPLICANT_ENABLE)
-	{
-	if (wrqu->data.length < pAd->StaCfg.RSNIE_Len)
-		return -E2BIG;
-
-	wrqu->data.length = pAd->StaCfg.RSNIE_Len;
-	memcpy(extra, &pAd->StaCfg.RSN_IE[0], pAd->StaCfg.RSNIE_Len);
-	}
-	else
-#endif // SIOCSIWGENIE //
-#endif // NATIVE_WPA_SUPPLICANT_SUPPORT //
-	{
-		UCHAR RSNIe = IE_WPA;
-
-		if (wrqu->data.length < (pAd->StaCfg.RSNIE_Len + 2)) // ID, Len
-			return -E2BIG;
-		wrqu->data.length = pAd->StaCfg.RSNIE_Len + 2;
-
-		if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-            (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPA2))
-			RSNIe = IE_RSN;
-
-		extra[0] = (char)RSNIe;
-		extra[1] = pAd->StaCfg.RSNIE_Len;
-		memcpy(extra+2, &pAd->StaCfg.RSN_IE[0], pAd->StaCfg.RSNIE_Len);
-	}
-
-	return 0;
-}
-
-int rt_ioctl_siwpmksa(struct net_device *dev,
-			   struct iw_request_info *info,
-			   union iwreq_data *wrqu,
-			   char *extra)
-{
-	PRTMP_ADAPTER   pAd = dev->ml_priv;
-	struct iw_pmksa *pPmksa = (struct iw_pmksa *)wrqu->data.pointer;
-	INT	CachedIdx = 0, idx = 0;
-
-	if (pPmksa == NULL)
-		return -EINVAL;
-
-	DBGPRINT(RT_DEBUG_TRACE ,("===> rt_ioctl_siwpmksa\n"));
-	switch(pPmksa->cmd)
-	{
-		case IW_PMKSA_FLUSH:
-			NdisZeroMemory(pAd->StaCfg.SavedPMK, sizeof(BSSID_INFO)*PMKID_NO);
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_FLUSH\n"));
-			break;
-		case IW_PMKSA_REMOVE:
-			for (CachedIdx = 0; CachedIdx < pAd->StaCfg.SavedPMKNum; CachedIdx++)
-			{
-		        // compare the BSSID
-		        if (NdisEqualMemory(pPmksa->bssid.sa_data, pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN))
-		        {
-		        	NdisZeroMemory(pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN);
-					NdisZeroMemory(pAd->StaCfg.SavedPMK[CachedIdx].PMKID, 16);
-					for (idx = CachedIdx; idx < (pAd->StaCfg.SavedPMKNum - 1); idx++)
-					{
-						NdisMoveMemory(&pAd->StaCfg.SavedPMK[idx].BSSID[0], &pAd->StaCfg.SavedPMK[idx+1].BSSID[0], MAC_ADDR_LEN);
-						NdisMoveMemory(&pAd->StaCfg.SavedPMK[idx].PMKID[0], &pAd->StaCfg.SavedPMK[idx+1].PMKID[0], 16);
-					}
-					pAd->StaCfg.SavedPMKNum--;
-			        break;
-		        }
-	        }
-
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_REMOVE\n"));
-			break;
-		case IW_PMKSA_ADD:
-			for (CachedIdx = 0; CachedIdx < pAd->StaCfg.SavedPMKNum; CachedIdx++)
-			{
-		        // compare the BSSID
-		        if (NdisEqualMemory(pPmksa->bssid.sa_data, pAd->StaCfg.SavedPMK[CachedIdx].BSSID, MAC_ADDR_LEN))
-			        break;
-	        }
-
-	        // Found, replace it
-	        if (CachedIdx < PMKID_NO)
-	        {
-		        DBGPRINT(RT_DEBUG_OFF, ("Update PMKID, idx = %d\n", CachedIdx));
-		        NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].BSSID[0], pPmksa->bssid.sa_data, MAC_ADDR_LEN);
-				NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].PMKID[0], pPmksa->pmkid, 16);
-		        pAd->StaCfg.SavedPMKNum++;
-	        }
-	        // Not found, replace the last one
-	        else
-	        {
-		        // Randomly replace one
-		        CachedIdx = (pPmksa->bssid.sa_data[5] % PMKID_NO);
-		        DBGPRINT(RT_DEBUG_OFF, ("Update PMKID, idx = %d\n", CachedIdx));
-		        NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].BSSID[0], pPmksa->bssid.sa_data, MAC_ADDR_LEN);
-				NdisMoveMemory(&pAd->StaCfg.SavedPMK[CachedIdx].PMKID[0], pPmksa->pmkid, 16);
-	        }
-
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - IW_PMKSA_ADD\n"));
-			break;
-		default:
-			DBGPRINT(RT_DEBUG_TRACE ,("rt_ioctl_siwpmksa - Unknow Command!!\n"));
-			break;
-	}
-
-	return 0;
-}
-#endif // #if WIRELESS_EXT > 17
-
-#ifdef DBG
-static int
-rt_private_ioctl_bbp(struct net_device *dev, struct iw_request_info *info,
-		struct iw_point *wrq, char *extra)
-			{
-	CHAR				*this_char;
-	CHAR				*value = NULL;
-	UCHAR				regBBP = 0;
-//	CHAR				arg[255]={0};
-	UINT32				bbpId;
-	UINT32				bbpValue;
-	BOOLEAN				bIsPrintAllBBP = FALSE;
-	INT					Status = 0;
-    PRTMP_ADAPTER       pAdapter = dev->ml_priv;
-
-
-	memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-
-	if (wrq->length > 1) //No parameters.
-				{
-		sprintf(extra, "\n");
-
-		//Parsing Read or Write
-		this_char = wrq->pointer;
-		DBGPRINT(RT_DEBUG_TRACE, ("this_char=%s\n", this_char));
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-			DBGPRINT(RT_DEBUG_TRACE, ("this_char=%s, value=%s\n", this_char, value));
-			if (sscanf(this_char, "%d", &(bbpId)) == 1)
-			{
-#ifndef RT30xx
-				if (bbpId <= 136)
-#endif // RT30xx //
-#ifdef RT30xx
-				if (bbpId <= 138)  // edit by johnli, RF power sequence setup, add BBP R138 for ADC dynamic on/off control
-#endif // RT30xx //
-				{
-#ifdef RALINK_ATE
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					else
-#endif // RALINK_ATE //
-					{
-					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X\n", bbpId, bbpId*2, regBBP);
-                    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-					DBGPRINT(RT_DEBUG_TRACE, ("msg=%s\n", extra));
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					bIsPrintAllBBP = TRUE;
-					goto next;
-				}
-			}
-			else
-			{ //Invalid parametes, so default printk all bbp
-				bIsPrintAllBBP = TRUE;
-				goto next;
-			}
-		}
-		else
-		{ //Write
-			if ((sscanf(this_char, "%d", &(bbpId)) == 1) && (sscanf(value, "%x", &(bbpValue)) == 1))
-			{
-#ifndef RT30xx
-				if (bbpId <= 136)
-#endif // RT30xx //
-#ifdef RT30xx
-				if (bbpId <= 138)  // edit by johnli, RF power sequence setup, add BBP R138 for ADC dynamic on/off control
-#endif // RT30xx //
-				{
-#ifdef RALINK_ATE
-					if (ATE_ON(pAdapter))
-					{
-						ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, bbpId, bbpValue);
-						//Read it back for showing
-						ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					}
-					else
-#endif // RALINK_ATE //
-					{
-					    RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, bbpId, bbpValue);
-    					//Read it back for showing
-    					RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			}
-					sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X\n", bbpId, bbpId*2, regBBP);
-                    wrq->length = strlen(extra) + 1; // 1: size of '\0'
-					DBGPRINT(RT_DEBUG_TRACE, ("msg=%s\n", extra));
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					bIsPrintAllBBP = TRUE;
-					goto next;
-				}
-			}
-			else
-			{ //Invalid parametes, so default printk all bbp
-				bIsPrintAllBBP = TRUE;
-				goto next;
-			}
-		}
-		}
-	else
-		bIsPrintAllBBP = TRUE;
-
-next:
-	if (bIsPrintAllBBP)
-	{
-		memset(extra, 0x00, IW_PRIV_SIZE_MASK);
-		sprintf(extra, "\n");
-#ifndef RT30xx
-		for (bbpId = 0; bbpId <= 136; bbpId++)
-#endif // RT30xx //
-#ifdef RT30xx
-		for (bbpId = 0; bbpId <= 138; bbpId++)  // edit by johnli, RF power sequence setup, add BBP R138 for ADC dynamic on/off control
-#endif // RT30xx //
-		{
-		    if (strlen(extra) >= (IW_PRIV_SIZE_MASK - 10))
-                break;
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				ATE_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-			}
-			else
-#endif // RALINK_ATE //
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-/*
-			sprintf(extra+strlen(extra), "R%02d[0x%02X]:%02X    ", bbpId, bbpId*2, regBBP);
-			if (bbpId%5 == 4)
-				sprintf(extra+strlen(extra), "\n");
-*/
-			sprintf(extra+strlen(extra), "%03d = %02X\n", bbpId, regBBP);  // edit by johnli, change display format
-		}
-
-        wrq->length = strlen(extra) + 1; // 1: size of '\0'
-        DBGPRINT(RT_DEBUG_TRACE, ("wrq->length = %d\n", wrq->length));
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==rt_private_ioctl_bbp\n\n"));
-
-    return Status;
-}
-#endif // DBG //
-
-int rt_ioctl_siwrate(struct net_device *dev,
-			struct iw_request_info *info,
-			union iwreq_data *wrqu, char *extra)
-{
-    PRTMP_ADAPTER   pAd = dev->ml_priv;
-    UINT32          rate = wrqu->bitrate.value, fixed = wrqu->bitrate.fixed;
-
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::(rate = %d, fixed = %d)\n", rate, fixed));
-    /* rate = -1 => auto rate
-       rate = X, fixed = 1 => (fixed rate X)
-    */
-    if (rate == -1)
-    {
-		//Auto Rate
-		pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-		pAd->StaCfg.bAutoTxRateSwitch = TRUE;
-		if ((pAd->CommonCfg.PhyMode <= PHY_11G) ||
-		    (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM))
-			RTMPSetDesiredRates(pAd, -1);
-
-#ifdef DOT11_N_SUPPORT
-		SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-    }
-    else
-    {
-        if (fixed)
-        {
-        	pAd->StaCfg.bAutoTxRateSwitch = FALSE;
-            if ((pAd->CommonCfg.PhyMode <= PHY_11G) ||
-                (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM))
-                RTMPSetDesiredRates(pAd, rate);
-            else
-            {
-                pAd->StaCfg.DesiredTransmitSetting.field.MCS = MCS_AUTO;
-#ifdef DOT11_N_SUPPORT
-                SetCommonHT(pAd);
-#endif // DOT11_N_SUPPORT //
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("rt_ioctl_siwrate::(HtMcs=%d)\n",pAd->StaCfg.DesiredTransmitSetting.field.MCS));
-        }
-        else
-        {
-            // TODO: rate = X, fixed = 0 => (rates <= X)
-            return -EOPNOTSUPP;
-        }
-    }
-
-    return 0;
-}
-
-int rt_ioctl_giwrate(struct net_device *dev,
-			       struct iw_request_info *info,
-			       union iwreq_data *wrqu, char *extra)
-{
-    PRTMP_ADAPTER   pAd = dev->ml_priv;
-    int rate_index = 0, rate_count = 0;
-    HTTRANSMIT_SETTING ht_setting;
-    __s32 ralinkrate[] =
-	{2,  4,   11,  22, // CCK
-	12, 18,   24,  36, 48, 72, 96, 108, // OFDM
-	13, 26,   39,  52,  78, 104, 117, 130, 26,  52,  78, 104, 156, 208, 234, 260, // 20MHz, 800ns GI, MCS: 0 ~ 15
-	39, 78,  117, 156, 234, 312, 351, 390,										  // 20MHz, 800ns GI, MCS: 16 ~ 23
-	27, 54,   81, 108, 162, 216, 243, 270, 54, 108, 162, 216, 324, 432, 486, 540, // 40MHz, 800ns GI, MCS: 0 ~ 15
-	81, 162, 243, 324, 486, 648, 729, 810,										  // 40MHz, 800ns GI, MCS: 16 ~ 23
-	14, 29,   43,  57,  87, 115, 130, 144, 29, 59,   87, 115, 173, 230, 260, 288, // 20MHz, 400ns GI, MCS: 0 ~ 15
-	43, 87,  130, 173, 260, 317, 390, 433,										  // 20MHz, 400ns GI, MCS: 16 ~ 23
-	30, 60,   90, 120, 180, 240, 270, 300, 60, 120, 180, 240, 360, 480, 540, 600, // 40MHz, 400ns GI, MCS: 0 ~ 15
-	90, 180, 270, 360, 540, 720, 810, 900};										  // 40MHz, 400ns GI, MCS: 16 ~ 23
-
-    rate_count = sizeof(ralinkrate)/sizeof(__s32);
-    //check if the interface is down
-	if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-	{
-  		DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-    	return -ENETDOWN;
-	}
-
-    if ((pAd->StaCfg.bAutoTxRateSwitch == FALSE) &&
-        (INFRA_ON(pAd)) &&
-        ((pAd->CommonCfg.PhyMode <= PHY_11G) || (pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE <= MODE_OFDM)))
-        ht_setting.word = pAd->StaCfg.HTPhyMode.word;
-    else
-        ht_setting.word = pAd->MacTab.Content[BSSID_WCID].HTPhyMode.word;
-
-#ifdef DOT11_N_SUPPORT
-    if (ht_setting.field.MODE >= MODE_HTMIX)
-    {
-//    	rate_index = 12 + ((UCHAR)ht_setting.field.BW *16) + ((UCHAR)ht_setting.field.ShortGI *32) + ((UCHAR)ht_setting.field.MCS);
-    	rate_index = 12 + ((UCHAR)ht_setting.field.BW *24) + ((UCHAR)ht_setting.field.ShortGI *48) + ((UCHAR)ht_setting.field.MCS);
-    }
-    else
-#endif // DOT11_N_SUPPORT //
-    if (ht_setting.field.MODE == MODE_OFDM)
-    	rate_index = (UCHAR)(ht_setting.field.MCS) + 4;
-    else if (ht_setting.field.MODE == MODE_CCK)
-    	rate_index = (UCHAR)(ht_setting.field.MCS);
-
-    if (rate_index < 0)
-        rate_index = 0;
-
-    if (rate_index > rate_count)
-        rate_index = rate_count;
-
-    wrqu->bitrate.value = ralinkrate[rate_index] * 500000;
-    wrqu->bitrate.disabled = 0;
-
-    return 0;
-}
-
-static const iw_handler rt_handler[] =
-{
-	(iw_handler) NULL,			            /* SIOCSIWCOMMIT */
-	(iw_handler) rt_ioctl_giwname,			/* SIOCGIWNAME   */
-	(iw_handler) NULL,			            /* SIOCSIWNWID   */
-	(iw_handler) NULL,			            /* SIOCGIWNWID   */
-	(iw_handler) rt_ioctl_siwfreq,		    /* SIOCSIWFREQ   */
-	(iw_handler) rt_ioctl_giwfreq,		    /* SIOCGIWFREQ   */
-	(iw_handler) rt_ioctl_siwmode,		    /* SIOCSIWMODE   */
-	(iw_handler) rt_ioctl_giwmode,		    /* SIOCGIWMODE   */
-	(iw_handler) NULL,		                /* SIOCSIWSENS   */
-	(iw_handler) NULL,		                /* SIOCGIWSENS   */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWRANGE  */
-	(iw_handler) rt_ioctl_giwrange,		    /* SIOCGIWRANGE  */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWPRIV   */
-	(iw_handler) NULL /* kernel code */,    /* SIOCGIWPRIV   */
-	(iw_handler) NULL /* not used */,		/* SIOCSIWSTATS  */
-	(iw_handler) rt28xx_get_wireless_stats /* kernel code */,    /* SIOCGIWSTATS  */
-	(iw_handler) NULL,		                /* SIOCSIWSPY    */
-	(iw_handler) NULL,		                /* SIOCGIWSPY    */
-	(iw_handler) NULL,				        /* SIOCSIWTHRSPY */
-	(iw_handler) NULL,				        /* SIOCGIWTHRSPY */
-	(iw_handler) rt_ioctl_siwap,            /* SIOCSIWAP     */
-	(iw_handler) rt_ioctl_giwap,		    /* SIOCGIWAP     */
-#ifdef SIOCSIWMLME
-	(iw_handler) rt_ioctl_siwmlme,	        /* SIOCSIWMLME   */
-#else
-	(iw_handler) NULL,				        /* SIOCSIWMLME */
-#endif // SIOCSIWMLME //
-	(iw_handler) rt_ioctl_iwaplist,		    /* SIOCGIWAPLIST */
-#ifdef SIOCGIWSCAN
-	(iw_handler) rt_ioctl_siwscan,		    /* SIOCSIWSCAN   */
-	(iw_handler) rt_ioctl_giwscan,		    /* SIOCGIWSCAN   */
-#else
-	(iw_handler) NULL,				        /* SIOCSIWSCAN   */
-	(iw_handler) NULL,				        /* SIOCGIWSCAN   */
-#endif /* SIOCGIWSCAN */
-	(iw_handler) rt_ioctl_siwessid,		    /* SIOCSIWESSID  */
-	(iw_handler) rt_ioctl_giwessid,		    /* SIOCGIWESSID  */
-	(iw_handler) rt_ioctl_siwnickn,		    /* SIOCSIWNICKN  */
-	(iw_handler) rt_ioctl_giwnickn,		    /* SIOCGIWNICKN  */
-	(iw_handler) NULL,				        /* -- hole --    */
-	(iw_handler) NULL,				        /* -- hole --    */
-	(iw_handler) rt_ioctl_siwrate,          /* SIOCSIWRATE   */
-	(iw_handler) rt_ioctl_giwrate,          /* SIOCGIWRATE   */
-	(iw_handler) rt_ioctl_siwrts,		    /* SIOCSIWRTS    */
-	(iw_handler) rt_ioctl_giwrts,		    /* SIOCGIWRTS    */
-	(iw_handler) rt_ioctl_siwfrag,		    /* SIOCSIWFRAG   */
-	(iw_handler) rt_ioctl_giwfrag,		    /* SIOCGIWFRAG   */
-	(iw_handler) NULL,		                /* SIOCSIWTXPOW  */
-	(iw_handler) NULL,		                /* SIOCGIWTXPOW  */
-	(iw_handler) NULL,		                /* SIOCSIWRETRY  */
-	(iw_handler) NULL,		                /* SIOCGIWRETRY  */
-	(iw_handler) rt_ioctl_siwencode,		/* SIOCSIWENCODE */
-	(iw_handler) rt_ioctl_giwencode,		/* SIOCGIWENCODE */
-	(iw_handler) NULL,		                /* SIOCSIWPOWER  */
-	(iw_handler) NULL,		                /* SIOCGIWPOWER  */
-	(iw_handler) NULL,						/* -- hole -- */
-	(iw_handler) NULL,						/* -- hole -- */
-#if WIRELESS_EXT > 17
-    (iw_handler) rt_ioctl_siwgenie,         /* SIOCSIWGENIE  */
-	(iw_handler) rt_ioctl_giwgenie,         /* SIOCGIWGENIE  */
-	(iw_handler) rt_ioctl_siwauth,		    /* SIOCSIWAUTH   */
-	(iw_handler) rt_ioctl_giwauth,		    /* SIOCGIWAUTH   */
-	(iw_handler) rt_ioctl_siwencodeext,	    /* SIOCSIWENCODEEXT */
-	(iw_handler) rt_ioctl_giwencodeext,		/* SIOCGIWENCODEEXT */
-	(iw_handler) rt_ioctl_siwpmksa,         /* SIOCSIWPMKSA  */
-#endif
-};
-
-static const iw_handler rt_priv_handlers[] = {
-	(iw_handler) NULL, /* + 0x00 */
-	(iw_handler) NULL, /* + 0x01 */
-#ifndef CONFIG_AP_SUPPORT
-	(iw_handler) rt_ioctl_setparam, /* + 0x02 */
-#else
-	(iw_handler) NULL, /* + 0x02 */
-#endif // CONFIG_AP_SUPPORT //
-#ifdef DBG
-	(iw_handler) rt_private_ioctl_bbp, /* + 0x03 */
-#else
-	(iw_handler) NULL, /* + 0x03 */
-#endif
-	(iw_handler) NULL, /* + 0x04 */
-	(iw_handler) NULL, /* + 0x05 */
-	(iw_handler) NULL, /* + 0x06 */
-	(iw_handler) NULL, /* + 0x07 */
-	(iw_handler) NULL, /* + 0x08 */
-	(iw_handler) rt_private_get_statistics, /* + 0x09 */
-	(iw_handler) NULL, /* + 0x0A */
-	(iw_handler) NULL, /* + 0x0B */
-	(iw_handler) NULL, /* + 0x0C */
-	(iw_handler) NULL, /* + 0x0D */
-	(iw_handler) NULL, /* + 0x0E */
-	(iw_handler) NULL, /* + 0x0F */
-	(iw_handler) NULL, /* + 0x10 */
-	(iw_handler) rt_private_show, /* + 0x11 */
-    (iw_handler) NULL, /* + 0x12 */
-	(iw_handler) NULL, /* + 0x13 */
-	(iw_handler) NULL, /* + 0x15 */
-	(iw_handler) NULL, /* + 0x17 */
-	(iw_handler) NULL, /* + 0x18 */
-};
-
-const struct iw_handler_def rt28xx_iw_handler_def =
-{
-#define	N(a)	(sizeof (a) / sizeof (a[0]))
-	.standard	= (iw_handler *) rt_handler,
-	.num_standard	= sizeof(rt_handler) / sizeof(iw_handler),
-	.private	= (iw_handler *) rt_priv_handlers,
-	.num_private		= N(rt_priv_handlers),
-	.private_args	= (struct iw_priv_args *) privtab,
-	.num_private_args	= N(privtab),
-#if IW_HANDLER_VERSION >= 7
-    .get_wireless_stats = rt28xx_get_wireless_stats,
-#endif
-};
-
-INT RTMPSetInformation(
-    IN  PRTMP_ADAPTER pAdapter,
-    IN  OUT struct ifreq    *rq,
-    IN  INT                 cmd)
-{
-    struct iwreq                        *wrq = (struct iwreq *) rq;
-    NDIS_802_11_SSID                    Ssid;
-    NDIS_802_11_MAC_ADDRESS             Bssid;
-    RT_802_11_PHY_MODE                  PhyMode;
-    RT_802_11_STA_CONFIG                StaConfig;
-    NDIS_802_11_RATES                   aryRates;
-    RT_802_11_PREAMBLE                  Preamble;
-    NDIS_802_11_WEP_STATUS              WepStatus;
-    NDIS_802_11_AUTHENTICATION_MODE     AuthMode = Ndis802_11AuthModeMax;
-    NDIS_802_11_NETWORK_INFRASTRUCTURE  BssType;
-    NDIS_802_11_RTS_THRESHOLD           RtsThresh;
-    NDIS_802_11_FRAGMENTATION_THRESHOLD FragThresh;
-    NDIS_802_11_POWER_MODE              PowerMode;
-    PNDIS_802_11_KEY                    pKey = NULL;
-    PNDIS_802_11_WEP			        pWepKey =NULL;
-    PNDIS_802_11_REMOVE_KEY             pRemoveKey = NULL;
-    NDIS_802_11_CONFIGURATION           Config, *pConfig = NULL;
-    NDIS_802_11_NETWORK_TYPE            NetType;
-    ULONG                               Now;
-    UINT                                KeyIdx = 0;
-    INT                                 Status = NDIS_STATUS_SUCCESS, MaxPhyMode = PHY_11G;
-    ULONG                               PowerTemp;
-    BOOLEAN                             RadioState;
-    BOOLEAN                             StateMachineTouched = FALSE;
-#ifdef DOT11_N_SUPPORT
-	OID_SET_HT_PHYMODE					HT_PhyMode;	//11n ,kathy
-#endif // DOT11_N_SUPPORT //
-#ifdef WPA_SUPPLICANT_SUPPORT
-    PNDIS_802_11_PMKID                  pPmkId = NULL;
-    BOOLEAN				                IEEE8021xState = FALSE;
-    BOOLEAN				                IEEE8021x_required_keys = FALSE;
-    UCHAR                               wpa_supplicant_enable = 0;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef SNMP_SUPPORT
-	TX_RTY_CFG_STRUC			tx_rty_cfg;
-	ULONG						ShortRetryLimit, LongRetryLimit;
-	UCHAR						ctmp;
-#endif // SNMP_SUPPORT //
-
-
-#ifdef DOT11_N_SUPPORT
-	MaxPhyMode = PHY_11N_5G;
-#endif // DOT11_N_SUPPORT //
-
-
-	DBGPRINT(RT_DEBUG_TRACE, ("-->RTMPSetInformation(),	0x%08x\n", cmd&0x7FFF));
-    switch(cmd & 0x7FFF) {
-        case RT_OID_802_11_COUNTRY_REGION:
-            if (wrq->u.data.length < sizeof(UCHAR))
-                Status = -EINVAL;
-			// Only avaliable when EEPROM not programming
-            else if (!(pAdapter->CommonCfg.CountryRegion & 0x80) && !(pAdapter->CommonCfg.CountryRegionForABand & 0x80))
-            {
-                ULONG   Country;
-                UCHAR	TmpPhy;
-
-				Status = copy_from_user(&Country, wrq->u.data.pointer, wrq->u.data.length);
-				pAdapter->CommonCfg.CountryRegion = (UCHAR)(Country & 0x000000FF);
-				pAdapter->CommonCfg.CountryRegionForABand = (UCHAR)((Country >> 8) & 0x000000FF);
-                TmpPhy = pAdapter->CommonCfg.PhyMode;
-				pAdapter->CommonCfg.PhyMode = 0xff;
-				// Build all corresponding channel information
-				RTMPSetPhyMode(pAdapter, TmpPhy);
-#ifdef DOT11_N_SUPPORT
-				SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_COUNTRY_REGION (A:%d  B/G:%d)\n", pAdapter->CommonCfg.CountryRegionForABand,
-				    pAdapter->CommonCfg.CountryRegion));
-            }
-            break;
-        case OID_802_11_BSSID_LIST_SCAN:
- #ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-            Now = jiffies;
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_BSSID_LIST_SCAN, TxCnt = %d \n", pAdapter->RalinkCounters.LastOneSecTotalTxCount));
-
-            if (MONITOR_ON(pAdapter))
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is in Monitor Mode now !!!\n"));
-                break;
-            }
-
-			//Benson add 20080527, when radio off, sta don't need to scan
-			if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_RADIO_OFF))
-				break;
-
-			if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-			{
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Driver is scanning now !!!\n"));
-				pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-				Status = NDIS_STATUS_SUCCESS;
-                break;
-            }
-
-			if (pAdapter->RalinkCounters.LastOneSecTotalTxCount > 100)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-				Status = NDIS_STATUS_SUCCESS;
-				pAdapter->StaCfg.ScanCnt = 99;		// Prevent auto scan triggered by this OID
-				break;
-            }
-
-            if ((OPSTATUS_TEST_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED)) &&
-				((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2) ||
-				(pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK)) &&
-                (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_NOT_SECURED))
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! Link UP, Port Not Secured! ignore this set::OID_802_11_BSSID_LIST_SCAN\n"));
-				Status = NDIS_STATUS_SUCCESS;
-				pAdapter->StaCfg.ScanCnt = 99;		// Prevent auto scan triggered by this OID
-				break;
-            }
-
-
-            if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-            {
-                RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-                DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-            }
-
-            // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-            // this request, because this request is initiated by NDIS.
-            pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-            // Reset allowed scan retries
-            pAdapter->StaCfg.ScanCnt = 0;
-            pAdapter->StaCfg.LastScanTime = Now;
-
-			pAdapter->StaCfg.bScanReqIsFromWebUI = TRUE;
-            RTMP_SET_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS);
-            MlmeEnqueue(pAdapter,
-                        MLME_CNTL_STATE_MACHINE,
-                        OID_802_11_BSSID_LIST_SCAN,
-                        0,
-                        NULL);
-
-            Status = NDIS_STATUS_SUCCESS;
-            StateMachineTouched = TRUE;
-            break;
-        case OID_802_11_SSID:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_SSID))
-                Status = -EINVAL;
-            else
-            {
-            	PCHAR pSsidString = NULL;
-                Status = copy_from_user(&Ssid, wrq->u.data.pointer, wrq->u.data.length);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SSID (Len=%d,Ssid=%s)\n", Ssid.SsidLength, Ssid.Ssid));
-                if (Ssid.SsidLength > MAX_LEN_OF_SSID)
-                    Status = -EINVAL;
-                else
-                {
-                	if (Ssid.SsidLength == 0)
-                	{
-                		Set_SSID_Proc(pAdapter, "");
-                	}
-					else
-                	{
-	                	pSsidString = (CHAR *) kmalloc(MAX_LEN_OF_SSID+1, MEM_ALLOC_FLAG);
-						if (pSsidString)
-						{
-							NdisZeroMemory(pSsidString, MAX_LEN_OF_SSID+1);
-							NdisMoveMemory(pSsidString, Ssid.Ssid, Ssid.SsidLength);
-	                		Set_SSID_Proc(pAdapter, pSsidString);
-							kfree(pSsidString);
-						}
-						else
-							Status = -ENOMEM;
-                	}
-                }
-            }
-            break;
-        case OID_802_11_BSSID:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-            if (wrq->u.data.length != sizeof(NDIS_802_11_MAC_ADDRESS))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Bssid, wrq->u.data.pointer, wrq->u.data.length);
-
-                // tell CNTL state machine to call NdisMSetInformationComplete() after completing
-                // this request, because this request is initiated by NDIS.
-                pAdapter->MlmeAux.CurrReqIsFromNdis = FALSE;
-
-				// Prevent to connect AP again in STAMlmePeriodicExec
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-
-                // Reset allowed scan retries
-				pAdapter->StaCfg.ScanCnt = 0;
-
-                if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-                {
-                    RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-                    DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-                }
-                MlmeEnqueue(pAdapter,
-                            MLME_CNTL_STATE_MACHINE,
-                            OID_802_11_BSSID,
-                            sizeof(NDIS_802_11_MAC_ADDRESS),
-                            (VOID *)&Bssid);
-                Status = NDIS_STATUS_SUCCESS;
-                StateMachineTouched = TRUE;
-
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_BSSID %02x:%02x:%02x:%02x:%02x:%02x\n",
-                                        Bssid[0], Bssid[1], Bssid[2], Bssid[3], Bssid[4], Bssid[5]));
-            }
-            break;
-        case RT_OID_802_11_RADIO:
-            if (wrq->u.data.length != sizeof(BOOLEAN))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&RadioState, wrq->u.data.pointer, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_RADIO (=%d)\n", RadioState));
-                if (pAdapter->StaCfg.bSwRadio != RadioState)
-                {
-                    pAdapter->StaCfg.bSwRadio = RadioState;
-                    if (pAdapter->StaCfg.bRadio != (pAdapter->StaCfg.bHwRadio && pAdapter->StaCfg.bSwRadio))
-                    {
-                        pAdapter->StaCfg.bRadio = (pAdapter->StaCfg.bHwRadio && pAdapter->StaCfg.bSwRadio);
-                        if (pAdapter->StaCfg.bRadio == TRUE)
-                        {
-                            MlmeRadioOn(pAdapter);
-                            // Update extra information
-							pAdapter->ExtraInfo = EXTRA_INFO_CLEAR;
-                        }
-                        else
-                        {
-                            MlmeRadioOff(pAdapter);
-                            // Update extra information
-							pAdapter->ExtraInfo = SW_RADIO_OFF;
-                        }
-                    }
-                }
-            }
-            break;
-        case RT_OID_802_11_PHY_MODE:
-            if (wrq->u.data.length != sizeof(RT_802_11_PHY_MODE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&PhyMode, wrq->u.data.pointer, wrq->u.data.length);
-				if (PhyMode <= MaxPhyMode)
-				{
-                	RTMPSetPhyMode(pAdapter, PhyMode);
-#ifdef DOT11_N_SUPPORT
-					SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-				}
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_PHY_MODE (=%d)\n", PhyMode));
-            }
-            break;
-        case RT_OID_802_11_STA_CONFIG:
-            if (wrq->u.data.length != sizeof(RT_802_11_STA_CONFIG))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&StaConfig, wrq->u.data.pointer, wrq->u.data.length);
-                pAdapter->CommonCfg.bEnableTxBurst = StaConfig.EnableTxBurst;
-                pAdapter->CommonCfg.UseBGProtection = StaConfig.UseBGProtection;
-                pAdapter->CommonCfg.bUseShortSlotTime = 1; // 2003-10-30 always SHORT SLOT capable
-                if ((pAdapter->CommonCfg.PhyMode != StaConfig.AdhocMode) &&
-					(StaConfig.AdhocMode <= MaxPhyMode))
-                {
-                    // allow dynamic change of "USE OFDM rate or not" in ADHOC mode
-                    // if setting changed, need to reset current TX rate as well as BEACON frame format
-                    pAdapter->CommonCfg.PhyMode = StaConfig.AdhocMode;
-                    if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-                    {
-                    	RTMPSetPhyMode(pAdapter, PhyMode);
-                        MlmeUpdateTxRates(pAdapter, FALSE, 0);
-                        MakeIbssBeacon(pAdapter);           // re-build BEACON frame
-                        AsicEnableIbssSync(pAdapter);   // copy to on-chip memory
-                    }
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_STA_CONFIG (Burst=%d, Protection=%ld,ShortSlot=%d\n",
-                                        pAdapter->CommonCfg.bEnableTxBurst,
-                                        pAdapter->CommonCfg.UseBGProtection,
-                                        pAdapter->CommonCfg.bUseShortSlotTime));
-            }
-            break;
-        case OID_802_11_DESIRED_RATES:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_RATES))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&aryRates, wrq->u.data.pointer, wrq->u.data.length);
-                NdisZeroMemory(pAdapter->CommonCfg.DesireRate, MAX_LEN_OF_SUPPORTED_RATES);
-                NdisMoveMemory(pAdapter->CommonCfg.DesireRate, &aryRates, sizeof(NDIS_802_11_RATES));
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DESIRED_RATES (%02x,%02x,%02x,%02x,%02x,%02x,%02x,%02x)\n",
-                    pAdapter->CommonCfg.DesireRate[0],pAdapter->CommonCfg.DesireRate[1],
-                    pAdapter->CommonCfg.DesireRate[2],pAdapter->CommonCfg.DesireRate[3],
-                    pAdapter->CommonCfg.DesireRate[4],pAdapter->CommonCfg.DesireRate[5],
-                    pAdapter->CommonCfg.DesireRate[6],pAdapter->CommonCfg.DesireRate[7] ));
-                // Changing DesiredRate may affect the MAX TX rate we used to TX frames out
-                MlmeUpdateTxRates(pAdapter, FALSE, 0);
-            }
-            break;
-        case RT_OID_802_11_PREAMBLE:
-            if (wrq->u.data.length != sizeof(RT_802_11_PREAMBLE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Preamble, wrq->u.data.pointer, wrq->u.data.length);
-                if (Preamble == Rt802_11PreambleShort)
-                {
-                    pAdapter->CommonCfg.TxPreamble = Preamble;
-                    MlmeSetTxPreamble(pAdapter, Rt802_11PreambleShort);
-                }
-                else if ((Preamble == Rt802_11PreambleLong) || (Preamble == Rt802_11PreambleAuto))
-                {
-                    // if user wants AUTO, initialize to LONG here, then change according to AP's
-                    // capability upon association.
-                    pAdapter->CommonCfg.TxPreamble = Preamble;
-                    MlmeSetTxPreamble(pAdapter, Rt802_11PreambleLong);
-                }
-                else
-                {
-                    Status = -EINVAL;
-                    break;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_PREAMBLE (=%d)\n", Preamble));
-            }
-            break;
-        case OID_802_11_WEP_STATUS:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_WEP_STATUS))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&WepStatus, wrq->u.data.pointer, wrq->u.data.length);
-                // Since TKIP, AES, WEP are all supported. It should not have any invalid setting
-                if (WepStatus <= Ndis802_11Encryption3KeyAbsent)
-                {
-                    if (pAdapter->StaCfg.WepStatus != WepStatus)
-                    {
-                        // Config has changed
-                        pAdapter->bConfigChanged = TRUE;
-                    }
-                    pAdapter->StaCfg.WepStatus     = WepStatus;
-                    pAdapter->StaCfg.OrigWepStatus = WepStatus;
-                    pAdapter->StaCfg.PairCipher    = WepStatus;
-                	pAdapter->StaCfg.GroupCipher   = WepStatus;
-                }
-                else
-                {
-                    Status  = -EINVAL;
-                    break;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEP_STATUS (=%d)\n",WepStatus));
-            }
-            break;
-        case OID_802_11_AUTHENTICATION_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_AUTHENTICATION_MODE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&AuthMode, wrq->u.data.pointer, wrq->u.data.length);
-                if (AuthMode > Ndis802_11AuthModeMax)
-                {
-                    Status  = -EINVAL;
-                    break;
-                }
-                else
-                {
-                    if (pAdapter->StaCfg.AuthMode != AuthMode)
-                    {
-                        // Config has changed
-                        pAdapter->bConfigChanged = TRUE;
-                    }
-                    pAdapter->StaCfg.AuthMode = AuthMode;
-                }
-                pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_AUTHENTICATION_MODE (=%d) \n",pAdapter->StaCfg.AuthMode));
-            }
-            break;
-        case OID_802_11_INFRASTRUCTURE_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_NETWORK_INFRASTRUCTURE))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&BssType, wrq->u.data.pointer, wrq->u.data.length);
-
-				if (BssType == Ndis802_11IBSS)
-					Set_NetworkType_Proc(pAdapter, "Adhoc");
-				else if (BssType == Ndis802_11Infrastructure)
-					Set_NetworkType_Proc(pAdapter, "Infra");
-				else if (BssType == Ndis802_11Monitor)
-					Set_NetworkType_Proc(pAdapter, "Monitor");
-				else
-				{
-					Status  = -EINVAL;
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_INFRASTRUCTURE_MODE (unknown)\n"));
-				}
-			}
-			break;
-	 case OID_802_11_REMOVE_WEP:
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_WEP\n"));
-            if (wrq->u.data.length != sizeof(NDIS_802_11_KEY_INDEX))
-            {
-				Status = -EINVAL;
-            }
-            else
-            {
-				KeyIdx = *(NDIS_802_11_KEY_INDEX *) wrq->u.data.pointer;
-
-				if (KeyIdx & 0x80000000)
-				{
-					// Should never set default bit when remove key
-					Status = -EINVAL;
-				}
-				else
-				{
-					KeyIdx = KeyIdx & 0x0fffffff;
-					if (KeyIdx >= 4){
-						Status = -EINVAL;
-					}
-					else
-					{
-						pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = 0;
-						pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_NONE;
-						AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)KeyIdx);
-					}
-				}
-            }
-            break;
-        case RT_OID_802_11_RESET_COUNTERS:
-            NdisZeroMemory(&pAdapter->WlanCounters, sizeof(COUNTER_802_11));
-            NdisZeroMemory(&pAdapter->Counters8023, sizeof(COUNTER_802_3));
-            NdisZeroMemory(&pAdapter->RalinkCounters, sizeof(COUNTER_RALINK));
-            pAdapter->Counters8023.RxNoBuffer   = 0;
-			pAdapter->Counters8023.GoodReceives = 0;
-			pAdapter->Counters8023.RxNoBuffer   = 0;
-#ifdef RT2870
-			pAdapter->BulkOutComplete	= 0;
-			pAdapter->BulkOutCompleteOther= 0;
-			pAdapter->BulkOutCompleteCancel = 0;
-			pAdapter->BulkOutReq = 0;
-			pAdapter->BulkInReq= 0;
-			pAdapter->BulkInComplete = 0;
-			pAdapter->BulkInCompleteFail = 0;
-#endif // RT2870 //
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_RESET_COUNTERS \n"));
-            break;
-        case OID_802_11_RTS_THRESHOLD:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_RTS_THRESHOLD))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&RtsThresh, wrq->u.data.pointer, wrq->u.data.length);
-                if (RtsThresh > MAX_RTS_THRESHOLD)
-                    Status  = -EINVAL;
-                else
-                    pAdapter->CommonCfg.RtsThreshold = (USHORT)RtsThresh;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_RTS_THRESHOLD (=%ld)\n",RtsThresh));
-            break;
-        case OID_802_11_FRAGMENTATION_THRESHOLD:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_FRAGMENTATION_THRESHOLD))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&FragThresh, wrq->u.data.pointer, wrq->u.data.length);
-                pAdapter->CommonCfg.bUseZeroToDisableFragment = FALSE;
-                if (FragThresh > MAX_FRAG_THRESHOLD || FragThresh < MIN_FRAG_THRESHOLD)
-                {
-                    if (FragThresh == 0)
-                    {
-                        pAdapter->CommonCfg.FragmentThreshold = MAX_FRAG_THRESHOLD;
-                        pAdapter->CommonCfg.bUseZeroToDisableFragment = TRUE;
-                    }
-                    else
-                        Status  = -EINVAL;
-                }
-                else
-                    pAdapter->CommonCfg.FragmentThreshold = (USHORT)FragThresh;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_FRAGMENTATION_THRESHOLD (=%ld) \n",FragThresh));
-            break;
-        case OID_802_11_POWER_MODE:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_POWER_MODE))
-                Status = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&PowerMode, wrq->u.data.pointer, wrq->u.data.length);
-                if (PowerMode == Ndis802_11PowerModeCAM)
-                	Set_PSMode_Proc(pAdapter, "CAM");
-                else if (PowerMode == Ndis802_11PowerModeMAX_PSP)
-                	Set_PSMode_Proc(pAdapter, "Max_PSP");
-                else if (PowerMode == Ndis802_11PowerModeFast_PSP)
-					Set_PSMode_Proc(pAdapter, "Fast_PSP");
-                else if (PowerMode == Ndis802_11PowerModeLegacy_PSP)
-					Set_PSMode_Proc(pAdapter, "Legacy_PSP");
-                else
-                    Status = -EINVAL;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_POWER_MODE (=%d)\n",PowerMode));
-            break;
-         case RT_OID_802_11_TX_POWER_LEVEL_1:
-			if (wrq->u.data.length  < sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&PowerTemp, wrq->u.data.pointer, wrq->u.data.length);
-				if (PowerTemp > 100)
-					PowerTemp = 0xffffffff;  // AUTO
-				pAdapter->CommonCfg.TxPowerDefault = PowerTemp; //keep current setting.
-					pAdapter->CommonCfg.TxPowerPercentage = pAdapter->CommonCfg.TxPowerDefault;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_TX_POWER_LEVEL_1 (=%ld)\n", pAdapter->CommonCfg.TxPowerPercentage));
-			}
-	        break;
-		case OID_802_11_NETWORK_TYPE_IN_USE:
-			if (wrq->u.data.length != sizeof(NDIS_802_11_NETWORK_TYPE))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&NetType, wrq->u.data.pointer, wrq->u.data.length);
-
-				if (NetType == Ndis802_11DS)
-					RTMPSetPhyMode(pAdapter, PHY_11B);
-				else if (NetType == Ndis802_11OFDM24)
-					RTMPSetPhyMode(pAdapter, PHY_11BG_MIXED);
-				else if (NetType == Ndis802_11OFDM5)
-					RTMPSetPhyMode(pAdapter, PHY_11A);
-				else
-					Status = -EINVAL;
-#ifdef DOT11_N_SUPPORT
-				if (Status == NDIS_STATUS_SUCCESS)
-					SetCommonHT(pAdapter);
-#endif // DOT11_N_SUPPORT //
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_NETWORK_TYPE_IN_USE (=%d)\n",NetType));
-		    }
-			break;
-        // For WPA PSK PMK key
-        case RT_OID_802_11_ADD_WPA:
-            pKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-
-            Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA, Failed!!\n"));
-            }
-            else
-            {
-                if ((pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPAPSK) &&
-				    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-				    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone) )
-                {
-                    Status = -EOPNOTSUPP;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA, Failed!! [AuthMode != WPAPSK/WPA2PSK/WPANONE]\n"));
-                }
-                else if ((pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPAPSK) ||
-						 (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPA2PSK) ||
-						 (pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPANone) )     // Only for WPA PSK mode
-				{
-                    NdisMoveMemory(pAdapter->StaCfg.PMK, &pKey->KeyMaterial, pKey->KeyLength);
-                    // Use RaConfig as PSK agent.
-                    // Start STA supplicant state machine
-                    if (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone)
-                        pAdapter->StaCfg.WpaState = SS_START;
-
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-                }
-                else
-                {
-                    pAdapter->StaCfg.WpaState = SS_NOTUSE;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_WPA (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-                }
-            }
-            kfree(pKey);
-            break;
-        case OID_802_11_REMOVE_KEY:
-            pRemoveKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pRemoveKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-
-            Status = copy_from_user(pRemoveKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pRemoveKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!\n"));
-            }
-            else
-            {
-                if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-                {
-                    RTMPWPARemoveKeyProc(pAdapter, pRemoveKey);
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Remove WPA Key!!\n"));
-                }
-                else
-                {
-                    KeyIdx = pRemoveKey->KeyIndex;
-
-                    if (KeyIdx & 0x80000000)
-                    {
-                        // Should never set default bit when remove key
-                        Status  = -EINVAL;
-                        DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!(Should never set default bit when remove key)\n"));
-                    }
-                    else
-                    {
-                        KeyIdx = KeyIdx & 0x0fffffff;
-                        if (KeyIdx > 3)
-                        {
-                            Status  = -EINVAL;
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY, Failed!!(KeyId[%d] out of range)\n", KeyIdx));
-                        }
-                        else
-                        {
-                            pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = 0;
-                            pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CIPHER_NONE;
-                            AsicRemoveSharedKeyEntry(pAdapter, 0, (UCHAR)KeyIdx);
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_REMOVE_KEY (id=0x%x, Len=%d-byte)\n", pRemoveKey->KeyIndex, pRemoveKey->Length));
-                        }
-                    }
-                }
-            }
-            kfree(pRemoveKey);
-            break;
-        // New for WPA
-        case OID_802_11_ADD_KEY:
-            pKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-            if(pKey == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-            Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (pKey->Length != wrq->u.data.length)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_KEY, Failed!!\n"));
-            }
-            else
-            {
-                RTMPAddKey(pAdapter, pKey);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_KEY (id=0x%x, Len=%d-byte)\n", pKey->KeyIndex, pKey->KeyLength));
-            }
-            kfree(pKey);
-            break;
-        case OID_802_11_CONFIGURATION:
-            if (wrq->u.data.length != sizeof(NDIS_802_11_CONFIGURATION))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&Config, wrq->u.data.pointer, wrq->u.data.length);
-                pConfig = &Config;
-
-                if ((pConfig->BeaconPeriod >= 20) && (pConfig->BeaconPeriod <=400))
-                     pAdapter->CommonCfg.BeaconPeriod = (USHORT) pConfig->BeaconPeriod;
-
-                pAdapter->StaActive.AtimWin = (USHORT) pConfig->ATIMWindow;
-                MAP_KHZ_TO_CHANNEL_ID(pConfig->DSConfig, pAdapter->CommonCfg.Channel);
-                //
-				// Save the channel on MlmeAux for CntlOidRTBssidProc used.
-				//
-				pAdapter->MlmeAux.Channel = pAdapter->CommonCfg.Channel;
-
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_CONFIGURATION (BeacnPeriod=%ld,AtimW=%ld,Ch=%d)\n",
-                    pConfig->BeaconPeriod, pConfig->ATIMWindow, pAdapter->CommonCfg.Channel));
-                // Config has changed
-                pAdapter->bConfigChanged = TRUE;
-            }
-            break;
-#ifdef DOT11_N_SUPPORT
-		case RT_OID_802_11_SET_HT_PHYMODE:
-			if (wrq->u.data.length	!= sizeof(OID_SET_HT_PHYMODE))
-				Status = -EINVAL;
-			else
-			{
-			    POID_SET_HT_PHYMODE	pHTPhyMode = &HT_PhyMode;
-
-				Status = copy_from_user(&HT_PhyMode, wrq->u.data.pointer, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::pHTPhyMode	(PhyMode = %d,TransmitNo = %d, HtMode =	%d,	ExtOffset =	%d , MCS = %d, BW =	%d,	STBC = %d, SHORTGI = %d) \n",
-				pHTPhyMode->PhyMode, pHTPhyMode->TransmitNo,pHTPhyMode->HtMode,pHTPhyMode->ExtOffset,
-				pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC,	pHTPhyMode->SHORTGI));
-				if (pAdapter->CommonCfg.PhyMode	>= PHY_11ABGN_MIXED)
-					RTMPSetHT(pAdapter,	pHTPhyMode);
-			}
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_HT_PHYMODE(MCS=%d,BW=%d,SGI=%d,STBC=%d)\n",
-				pAdapter->StaCfg.HTPhyMode.field.MCS, pAdapter->StaCfg.HTPhyMode.field.BW, pAdapter->StaCfg.HTPhyMode.field.ShortGI,
-				pAdapter->StaCfg.HTPhyMode.field.STBC));
-			break;
-#endif // DOT11_N_SUPPORT //
-		case RT_OID_802_11_SET_APSD_SETTING:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				ULONG apsd ;
-				Status = copy_from_user(&apsd, wrq->u.data.pointer,	wrq->u.data.length);
-
-				/*-------------------------------------------------------------------
-				|B31~B7	|	B6~B5	 |	 B4	 |	 B3	 |	B2	 |	B1	 |	   B0		|
-				---------------------------------------------------------------------
-				| Rsvd	| Max SP Len | AC_VO | AC_VI | AC_BK | AC_BE | APSD	Capable	|
-				---------------------------------------------------------------------*/
-				pAdapter->CommonCfg.bAPSDCapable = (apsd & 0x00000001) ? TRUE :	FALSE;
-				pAdapter->CommonCfg.bAPSDAC_BE = ((apsd	& 0x00000002) >> 1)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_BK = ((apsd	& 0x00000004) >> 2)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_VI = ((apsd	& 0x00000008) >> 3)	? TRUE : FALSE;
-				pAdapter->CommonCfg.bAPSDAC_VO = ((apsd	& 0x00000010) >> 4)	? TRUE : FALSE;
-				pAdapter->CommonCfg.MaxSPLength	= (UCHAR)((apsd	& 0x00000060) >> 5);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_APSD_SETTING (apsd=0x%lx, APSDCap=%d, [BE,BK,VI,VO]=[%d/%d/%d/%d],	MaxSPLen=%d)\n", apsd, pAdapter->CommonCfg.bAPSDCapable,
-					pAdapter->CommonCfg.bAPSDAC_BE,	pAdapter->CommonCfg.bAPSDAC_BK,	pAdapter->CommonCfg.bAPSDAC_VI,	pAdapter->CommonCfg.bAPSDAC_VO,	pAdapter->CommonCfg.MaxSPLength));
-			}
-			break;
-
-		case RT_OID_802_11_SET_APSD_PSM:
-			if (wrq->u.data.length	!= sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				// Driver needs	to notify AP when PSM changes
-				Status = copy_from_user(&pAdapter->CommonCfg.bAPSDForcePowerSave, wrq->u.data.pointer, wrq->u.data.length);
-				if (pAdapter->CommonCfg.bAPSDForcePowerSave	!= pAdapter->StaCfg.Psm)
-				{
-					MlmeSetPsmBit(pAdapter,	pAdapter->CommonCfg.bAPSDForcePowerSave);
-					RTMPSendNullFrame(pAdapter,	pAdapter->CommonCfg.TxRate,	TRUE);
-				}
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_APSD_PSM (bAPSDForcePowerSave:%d)\n",	pAdapter->CommonCfg.bAPSDForcePowerSave));
-			}
-			break;
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_SET_DLS:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				BOOLEAN	oldvalue = pAdapter->CommonCfg.bDLSCapable;
-				Status = copy_from_user(&pAdapter->CommonCfg.bDLSCapable, wrq->u.data.pointer, wrq->u.data.length);
-				if (oldvalue &&	!pAdapter->CommonCfg.bDLSCapable)
-				{
-					int	i;
-					// tear	down local dls table entry
-					for	(i=0; i<MAX_NUM_OF_INIT_DLS_ENTRY; i++)
-					{
-						if (pAdapter->StaCfg.DLSEntry[i].Valid && (pAdapter->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-						{
-							pAdapter->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-							pAdapter->StaCfg.DLSEntry[i].Valid	= FALSE;
-							RTMPSendDLSTearDownFrame(pAdapter, pAdapter->StaCfg.DLSEntry[i].MacAddr);
-						}
-					}
-
-					// tear	down peer dls table	entry
-					for	(i=MAX_NUM_OF_INIT_DLS_ENTRY; i<MAX_NUM_OF_DLS_ENTRY; i++)
-					{
-						if (pAdapter->StaCfg.DLSEntry[i].Valid && (pAdapter->StaCfg.DLSEntry[i].Status == DLS_FINISH))
-						{
-							pAdapter->StaCfg.DLSEntry[i].Status	= DLS_NONE;
-							pAdapter->StaCfg.DLSEntry[i].Valid	= FALSE;
-							RTMPSendDLSTearDownFrame(pAdapter, pAdapter->StaCfg.DLSEntry[i].MacAddr);
-						}
-					}
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE,("Set::RT_OID_802_11_SET_DLS (=%d)\n", pAdapter->CommonCfg.bDLSCapable));
-			}
-			break;
-
-		case RT_OID_802_11_SET_DLS_PARAM:
-			if (wrq->u.data.length	!= sizeof(RT_802_11_DLS_UI))
-				Status = -EINVAL;
-			else
-			{
-				RT_802_11_DLS	Dls;
-
-				NdisZeroMemory(&Dls, sizeof(RT_802_11_DLS));
-				RTMPMoveMemory(&Dls, wrq->u.data.pointer, sizeof(RT_802_11_DLS_UI));
-				MlmeEnqueue(pAdapter,
-							MLME_CNTL_STATE_MACHINE,
-							RT_OID_802_11_SET_DLS_PARAM,
-							sizeof(RT_802_11_DLS),
-							&Dls);
-				DBGPRINT(RT_DEBUG_TRACE,("Set::RT_OID_802_11_SET_DLS_PARAM \n"));
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-		case RT_OID_802_11_SET_WMM:
-			if (wrq->u.data.length	!= sizeof(BOOLEAN))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&pAdapter->CommonCfg.bWmmCapable, wrq->u.data.pointer, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_SET_WMM (=%d)	\n", pAdapter->CommonCfg.bWmmCapable));
-			}
-			break;
-
-		case OID_802_11_DISASSOCIATE:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				break;
-			}
-#endif // RALINK_ATE //
-			//
-			// Set NdisRadioStateOff to	TRUE, instead of called	MlmeRadioOff.
-			// Later on, NDIS_802_11_BSSID_LIST_EX->NumberOfItems should be	0
-			// when	query OID_802_11_BSSID_LIST.
-			//
-			// TRUE:  NumberOfItems	will set to	0.
-			// FALSE: NumberOfItems	no change.
-			//
-			pAdapter->CommonCfg.NdisRadioStateOff =	TRUE;
-			// Set to immediately send the media disconnect	event
-			pAdapter->MlmeAux.CurrReqIsFromNdis	= TRUE;
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DISASSOCIATE	\n"));
-
-			if (INFRA_ON(pAdapter))
-			{
-				if (pAdapter->Mlme.CntlMachine.CurrState !=	CNTL_IDLE)
-				{
-					RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-					DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME	busy, reset	MLME state machine !!!\n"));
-				}
-
-				MlmeEnqueue(pAdapter,
-					MLME_CNTL_STATE_MACHINE,
-					OID_802_11_DISASSOCIATE,
-					0,
-					NULL);
-
-				StateMachineTouched	= TRUE;
-			}
-			break;
-
-#ifdef DOT11_N_SUPPORT
-		case RT_OID_802_11_SET_IMME_BA_CAP:
-				if (wrq->u.data.length != sizeof(OID_BACAP_STRUC))
-					Status = -EINVAL;
-				else
-				{
-					OID_BACAP_STRUC Orde ;
-					Status = copy_from_user(&Orde, wrq->u.data.pointer, wrq->u.data.length);
-					if (Orde.Policy > BA_NOTUSE)
-					{
-						Status = NDIS_STATUS_INVALID_DATA;
-					}
-					else if (Orde.Policy == BA_NOTUSE)
-					{
-						pAdapter->CommonCfg.BACapability.field.Policy = BA_NOTUSE;
-						pAdapter->CommonCfg.BACapability.field.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable = Orde.AmsduEnable;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize= Orde.AmsduSize;
-						pAdapter->CommonCfg.DesiredHtPhy.MimoPs= Orde.MMPSmode;
-						pAdapter->CommonCfg.BACapability.field.MMPSmode = Orde.MMPSmode;
-						// UPdata to HT IE
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.AMsduSize = Orde.AmsduSize;
-						pAdapter->CommonCfg.HtCapability.HtCapParm.MpduDensity = Orde.MpduDensity;
-					}
-					else
-					{
-                        pAdapter->CommonCfg.BACapability.field.AutoBA = Orde.AutoBA;
-						pAdapter->CommonCfg.BACapability.field.Policy = IMMED_BA; // we only support immediate BA.
-						pAdapter->CommonCfg.BACapability.field.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.MpduDensity = Orde.MpduDensity;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable = Orde.AmsduEnable;
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize= Orde.AmsduSize;
-						pAdapter->CommonCfg.DesiredHtPhy.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.BACapability.field.MMPSmode = Orde.MMPSmode;
-
-						// UPdata to HT IE
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.MimoPs = Orde.MMPSmode;
-						pAdapter->CommonCfg.HtCapability.HtCapInfo.AMsduSize = Orde.AmsduSize;
-						pAdapter->CommonCfg.HtCapability.HtCapParm.MpduDensity = Orde.MpduDensity;
-
-						if (pAdapter->CommonCfg.BACapability.field.RxBAWinLimit > MAX_RX_REORDERBUF)
-							pAdapter->CommonCfg.BACapability.field.RxBAWinLimit = MAX_RX_REORDERBUF;
-
-					}
-
-					pAdapter->CommonCfg.REGBACapability.word = pAdapter->CommonCfg.BACapability.word;
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::(Orde.AutoBA = %d) (Policy=%d)(ReBAWinLimit=%d)(TxBAWinLimit=%d)(AutoMode=%d)\n",Orde.AutoBA, pAdapter->CommonCfg.BACapability.field.Policy,
-						pAdapter->CommonCfg.BACapability.field.RxBAWinLimit,pAdapter->CommonCfg.BACapability.field.TxBAWinLimit, pAdapter->CommonCfg.BACapability.field.AutoBA));
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::(MimoPs = %d)(AmsduEnable = %d) (AmsduSize=%d)(MpduDensity=%d)\n",pAdapter->CommonCfg.DesiredHtPhy.MimoPs, pAdapter->CommonCfg.DesiredHtPhy.AmsduEnable,
-						pAdapter->CommonCfg.DesiredHtPhy.AmsduSize, pAdapter->CommonCfg.DesiredHtPhy.MpduDensity));
-				}
-
-				break;
-		case RT_OID_802_11_ADD_IMME_BA:
-			DBGPRINT(RT_DEBUG_TRACE, (" Set :: RT_OID_802_11_ADD_IMME_BA \n"));
-			if (wrq->u.data.length != sizeof(OID_ADD_BA_ENTRY))
-					Status = -EINVAL;
-			else
-			{
-				UCHAR		        index;
-				OID_ADD_BA_ENTRY    BA;
-				MAC_TABLE_ENTRY     *pEntry;
-
-				Status = copy_from_user(&BA, wrq->u.data.pointer, wrq->u.data.length);
-				if (BA.TID > 15)
-				{
-					Status = NDIS_STATUS_INVALID_DATA;
-					break;
-				}
-				else
-				{
-					//BATableInsertEntry
-					//As ad-hoc mode, BA pair is not limited to only BSSID. so add via OID.
-					index = BA.TID;
-					// in ad hoc mode, when adding BA pair, we should insert this entry into MACEntry too
-					pEntry = MacTableLookup(pAdapter, BA.MACAddr);
-					if (!pEntry)
-					{
-						DBGPRINT(RT_DEBUG_TRACE, ("RT_OID_802_11_ADD_IMME_BA. break on no connection.----:%x:%x\n", BA.MACAddr[4], BA.MACAddr[5]));
-						break;
-					}
-					if (BA.IsRecipient == FALSE)
-					{
-					    if (pEntry->bIAmBadAtheros == TRUE)
-							pAdapter->CommonCfg.BACapability.field.RxBAWinLimit = 0x10;
-
-						BAOriSessionSetUp(pAdapter, pEntry, index, 0, 100, TRUE);
-					}
-					else
-					{
-						//BATableInsertEntry(pAdapter, pEntry->Aid, BA.MACAddr, 0, 0xffff, BA.TID, BA.nMSDU, BA.IsRecipient);
-					}
-
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_802_11_ADD_IMME_BA. Rec = %d. Mac = %x:%x:%x:%x:%x:%x . \n",
-						BA.IsRecipient, BA.MACAddr[0], BA.MACAddr[1], BA.MACAddr[2], BA.MACAddr[2]
-						, BA.MACAddr[4], BA.MACAddr[5]));
-				}
-			}
-			break;
-
-		case RT_OID_802_11_TEAR_IMME_BA:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA \n"));
-			if (wrq->u.data.length != sizeof(OID_ADD_BA_ENTRY))
-					Status = -EINVAL;
-			else
-			{
-				POID_ADD_BA_ENTRY	pBA;
-				MAC_TABLE_ENTRY *pEntry;
-
-				pBA = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-				if (pBA == NULL)
-				{
-					DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA kmalloc() can't allocate enough memory\n"));
-					Status = NDIS_STATUS_FAILURE;
-				}
-				else
-				{
-					Status = copy_from_user(pBA, wrq->u.data.pointer, wrq->u.data.length);
-					DBGPRINT(RT_DEBUG_TRACE, ("Set :: RT_OID_802_11_TEAR_IMME_BA(TID=%d, bAllTid=%d)\n", pBA->TID, pBA->bAllTid));
-
-					if (!pBA->bAllTid && (pBA->TID > NUM_OF_TID))
-					{
-						Status = NDIS_STATUS_INVALID_DATA;
-						break;
-					}
-
-					if (pBA->IsRecipient == FALSE)
-					{
-						pEntry = MacTableLookup(pAdapter, pBA->MACAddr);
-						DBGPRINT(RT_DEBUG_TRACE, (" pBA->IsRecipient == FALSE\n"));
-						if (pEntry)
-						{
-							DBGPRINT(RT_DEBUG_TRACE, (" pBA->pEntry\n"));
-							BAOriSessionTearDown(pAdapter, pEntry->Aid, pBA->TID, FALSE, TRUE);
-						}
-						else
-							DBGPRINT(RT_DEBUG_TRACE, ("Set :: Not found pEntry \n"));
-					}
-					else
-					{
-						pEntry = MacTableLookup(pAdapter, pBA->MACAddr);
-						if (pEntry)
-						{
-							BARecSessionTearDown( pAdapter, (UCHAR)pEntry->Aid, pBA->TID, TRUE);
-						}
-						else
-							DBGPRINT(RT_DEBUG_TRACE, ("Set :: Not found pEntry \n"));
-					}
-					kfree(pBA);
-				}
-            }
-            break;
-#endif // DOT11_N_SUPPORT //
-
-        // For WPA_SUPPLICANT to set static wep key
-    	case OID_802_11_ADD_WEP:
-    	    pWepKey = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-    	    if(pWepKey == NULL)
-            {
-                Status = -ENOMEM;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed!!\n"));
-                break;
-            }
-            Status = copy_from_user(pWepKey, wrq->u.data.pointer, wrq->u.data.length);
-            if (Status)
-            {
-                Status  = -EINVAL;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed (length mismatch)!!\n"));
-            }
-            else
-            {
-		        KeyIdx = pWepKey->KeyIndex & 0x0fffffff;
-                // KeyIdx must be 0 ~ 3
-                if (KeyIdx > 4)
-    			{
-                    Status  = -EINVAL;
-                    DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, Failed (KeyIdx must be smaller than 4)!!\n"));
-                }
-                else
-                {
-                    UCHAR CipherAlg = 0;
-                    PUCHAR Key;
-
-                    // set key material and key length
-                    NdisZeroMemory(pAdapter->SharedKey[BSS0][KeyIdx].Key, 16);
-                    pAdapter->SharedKey[BSS0][KeyIdx].KeyLen = (UCHAR) pWepKey->KeyLength;
-                    NdisMoveMemory(pAdapter->SharedKey[BSS0][KeyIdx].Key, &pWepKey->KeyMaterial, pWepKey->KeyLength);
-
-                    switch(pWepKey->KeyLength)
-                    {
-                        case 5:
-                            CipherAlg = CIPHER_WEP64;
-                            break;
-                        case 13:
-                            CipherAlg = CIPHER_WEP128;
-                            break;
-                        default:
-                            DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP, only support CIPHER_WEP64(len:5) & CIPHER_WEP128(len:13)!!\n"));
-                            Status = -EINVAL;
-                            break;
-                    }
-                    pAdapter->SharedKey[BSS0][KeyIdx].CipherAlg = CipherAlg;
-
-                    // Default key for tx (shared key)
-                    if (pWepKey->KeyIndex & 0x80000000)
-                    {
-#ifdef WPA_SUPPLICANT_SUPPORT
-                        // set key material and key length
-                        NdisZeroMemory(pAdapter->StaCfg.DesireSharedKey[KeyIdx].Key, 16);
-                        pAdapter->StaCfg.DesireSharedKey[KeyIdx].KeyLen = (UCHAR) pWepKey->KeyLength;
-                        NdisMoveMemory(pAdapter->StaCfg.DesireSharedKey[KeyIdx].Key, &pWepKey->KeyMaterial, pWepKey->KeyLength);
-                        pAdapter->StaCfg.DesireSharedKeyId = KeyIdx;
-                        pAdapter->StaCfg.DesireSharedKey[KeyIdx].CipherAlg = CipherAlg;
-#endif // WPA_SUPPLICANT_SUPPORT //
-                        pAdapter->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-                    }
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-                    if (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED)
-#endif // WPA_SUPPLICANT_SUPPORT
-                    {
-                        Key = pAdapter->SharedKey[BSS0][KeyIdx].Key;
-
-                        // Set key material and cipherAlg to Asic
-        				AsicAddSharedKeyEntry(pAdapter, BSS0, KeyIdx, CipherAlg, Key, NULL, NULL);
-
-                        if (pWepKey->KeyIndex & 0x80000000)
-                        {
-                            PMAC_TABLE_ENTRY pEntry = &pAdapter->MacTab.Content[BSSID_WCID];
-                            // Assign group key info
-    						RTMPAddWcidAttributeEntry(pAdapter, BSS0, KeyIdx, CipherAlg, NULL);
-    						// Assign pairwise key info
-    						RTMPAddWcidAttributeEntry(pAdapter, BSS0, KeyIdx, CipherAlg, pEntry);
-                        }
-                    }
-					DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_ADD_WEP (id=0x%x, Len=%d-byte), %s\n", pWepKey->KeyIndex, pWepKey->KeyLength, (pAdapter->StaCfg.PortSecured == WPA_802_1X_PORT_SECURED) ? "Port Secured":"Port NOT Secured"));
-				}
-            }
-            kfree(pWepKey);
-            break;
-#ifdef WPA_SUPPLICANT_SUPPORT
-	    case OID_SET_COUNTERMEASURES:
-            if (wrq->u.data.length != sizeof(int))
-                Status  = -EINVAL;
-            else
-            {
-                int enabled = 0;
-                Status = copy_from_user(&enabled, wrq->u.data.pointer, wrq->u.data.length);
-                if (enabled == 1)
-                    pAdapter->StaCfg.bBlockAssoc = TRUE;
-                else
-                    // WPA MIC error should block association attempt for 60 seconds
-                    pAdapter->StaCfg.bBlockAssoc = FALSE;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_SET_COUNTERMEASURES bBlockAssoc=%s\n", pAdapter->StaCfg.bBlockAssoc ? "TRUE":"FALSE"));
-            }
-	        break;
-        case RT_OID_WPA_SUPPLICANT_SUPPORT:
-			if (wrq->u.data.length != sizeof(UCHAR))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&wpa_supplicant_enable, wrq->u.data.pointer, wrq->u.data.length);
-    			pAdapter->StaCfg.WpaSupplicantUP = wpa_supplicant_enable;
-    			DBGPRINT(RT_DEBUG_TRACE, ("Set::RT_OID_WPA_SUPPLICANT_SUPPORT (=%d)\n", pAdapter->StaCfg.WpaSupplicantUP));
-			}
-            break;
-        case OID_802_11_DEAUTHENTICATION:
-            if (wrq->u.data.length != sizeof(MLME_DEAUTH_REQ_STRUCT))
-                Status  = -EINVAL;
-            else
-            {
-                MLME_DEAUTH_REQ_STRUCT      *pInfo;
-				MLME_QUEUE_ELEM *MsgElem = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);
-
-                pInfo = (MLME_DEAUTH_REQ_STRUCT *) MsgElem->Msg;
-                Status = copy_from_user(pInfo, wrq->u.data.pointer, wrq->u.data.length);
-                MlmeDeauthReqAction(pAdapter, MsgElem);
-				kfree(MsgElem);
-
-                if (INFRA_ON(pAdapter))
-                {
-                    LinkDown(pAdapter, FALSE);
-                    pAdapter->Mlme.AssocMachine.CurrState = ASSOC_IDLE;
-                }
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DEAUTHENTICATION (Reason=%d)\n", pInfo->Reason));
-            }
-            break;
-        case OID_802_11_DROP_UNENCRYPTED:
-            if (wrq->u.data.length != sizeof(int))
-                Status  = -EINVAL;
-            else
-            {
-                int enabled = 0;
-                Status = copy_from_user(&enabled, wrq->u.data.pointer, wrq->u.data.length);
-                if (enabled == 1)
-                    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-                else
-                    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_SECURED;
-				NdisAcquireSpinLock(&pAdapter->MacTabLock);
-				pAdapter->MacTab.Content[BSSID_WCID].PortSecured = pAdapter->StaCfg.PortSecured;
-				NdisReleaseSpinLock(&pAdapter->MacTabLock);
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_DROP_UNENCRYPTED (=%d)\n", enabled));
-            }
-            break;
-        case OID_802_11_SET_IEEE8021X:
-            if (wrq->u.data.length != sizeof(BOOLEAN))
-                Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&IEEE8021xState, wrq->u.data.pointer, wrq->u.data.length);
-		        pAdapter->StaCfg.IEEE8021X = IEEE8021xState;
-                DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SET_IEEE8021X (=%d)\n", IEEE8021xState));
-            }
-            break;
-        case OID_802_11_SET_IEEE8021X_REQUIRE_KEY:
-			if (wrq->u.data.length != sizeof(BOOLEAN))
-				 Status  = -EINVAL;
-            else
-            {
-                Status = copy_from_user(&IEEE8021x_required_keys, wrq->u.data.pointer, wrq->u.data.length);
-				pAdapter->StaCfg.IEEE8021x_required_keys = IEEE8021x_required_keys;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SET_IEEE8021X_REQUIRE_KEY (%d)\n", IEEE8021x_required_keys));
-			}
-			break;
-        case OID_802_11_PMKID:
-	        pPmkId = kmalloc(wrq->u.data.length, MEM_ALLOC_FLAG);
-
-	        if(pPmkId == NULL) {
-                Status = -ENOMEM;
-                break;
-            }
-            Status = copy_from_user(pPmkId, wrq->u.data.pointer, wrq->u.data.length);
-
-	        // check the PMKID information
-	        if (pPmkId->BSSIDInfoCount == 0)
-                NdisZeroMemory(pAdapter->StaCfg.SavedPMK, sizeof(BSSID_INFO)*PMKID_NO);
-	        else
-	        {
-		        PBSSID_INFO	pBssIdInfo;
-		        UINT		BssIdx;
-		        UINT		CachedIdx;
-
-		        for (BssIdx = 0; BssIdx < pPmkId->BSSIDInfoCount; BssIdx++)
-		        {
-			        // point to the indexed BSSID_INFO structure
-			        pBssIdInfo = (PBSSID_INFO) ((PUCHAR) pPmkId + 2 * sizeof(UINT) + BssIdx * sizeof(BSSID_INFO));
-			        // Find the entry in the saved data base.
-			        for (CachedIdx = 0; CachedIdx < pAdapter->StaCfg.SavedPMKNum; CachedIdx++)
-			        {
-				        // compare the BSSID
-				        if (NdisEqualMemory(pBssIdInfo->BSSID, pAdapter->StaCfg.SavedPMK[CachedIdx].BSSID, sizeof(NDIS_802_11_MAC_ADDRESS)))
-					        break;
-			        }
-
-			        // Found, replace it
-			        if (CachedIdx < PMKID_NO)
-			        {
-				        DBGPRINT(RT_DEBUG_OFF, ("Update OID_802_11_PMKID, idx = %d\n", CachedIdx));
-				        NdisMoveMemory(&pAdapter->StaCfg.SavedPMK[CachedIdx], pBssIdInfo, sizeof(BSSID_INFO));
-				        pAdapter->StaCfg.SavedPMKNum++;
-			        }
-			        // Not found, replace the last one
-			        else
-			        {
-				        // Randomly replace one
-				        CachedIdx = (pBssIdInfo->BSSID[5] % PMKID_NO);
-				        DBGPRINT(RT_DEBUG_OFF, ("Update OID_802_11_PMKID, idx = %d\n", CachedIdx));
-				        NdisMoveMemory(&pAdapter->StaCfg.SavedPMK[CachedIdx], pBssIdInfo, sizeof(BSSID_INFO));
-			        }
-		        }
-			}
-			if(pPmkId)
-				kfree(pPmkId);
-	        break;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-
-
-#ifdef SNMP_SUPPORT
-		case OID_802_11_SHORTRETRYLIMIT:
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&ShortRetryLimit, wrq->u.data.pointer, wrq->u.data.length);
-				RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-				tx_rty_cfg.field.ShortRtyLimit = ShortRetryLimit;
-				RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_SHORTRETRYLIMIT (tx_rty_cfg.field.ShortRetryLimit=%d, ShortRetryLimit=%ld)\n", tx_rty_cfg.field.ShortRtyLimit, ShortRetryLimit));
-			}
-			break;
-
-		case OID_802_11_LONGRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_LONGRETRYLIMIT \n"));
-			if (wrq->u.data.length != sizeof(ULONG))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&LongRetryLimit, wrq->u.data.pointer, wrq->u.data.length);
-				RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-				tx_rty_cfg.field.LongRtyLimit = LongRetryLimit;
-				RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_LONGRETRYLIMIT (tx_rty_cfg.field.LongRetryLimit= %d,LongRetryLimit=%ld)\n", tx_rty_cfg.field.LongRtyLimit, LongRetryLimit));
-			}
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYVALUE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYVALUE\n"));
-			pKey = kmalloc(wrq->u.data.length, GFP_KERNEL);
-			Status = copy_from_user(pKey, wrq->u.data.pointer, wrq->u.data.length);
-			//pKey = &WepKey;
-
-			if ( pKey->Length != wrq->u.data.length)
-			{
-				Status = -EINVAL;
-				DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYVALUE, Failed!!\n"));
-			}
-			KeyIdx = pKey->KeyIndex & 0x0fffffff;
-			DBGPRINT(RT_DEBUG_TRACE,("pKey->KeyIndex =%d, pKey->KeyLength=%d\n", pKey->KeyIndex, pKey->KeyLength));
-
-			// it is a shared key
-			if (KeyIdx > 4)
-				Status = -EINVAL;
-			else
-			{
-				pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen = (UCHAR) pKey->KeyLength;
-				NdisMoveMemory(&pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key, &pKey->KeyMaterial, pKey->KeyLength);
-				if (pKey->KeyIndex & 0x80000000)
-				{
-					// Default key for tx (shared key)
-					pAdapter->StaCfg.DefaultKeyId = (UCHAR) KeyIdx;
-				}
-				//RestartAPIsRequired = TRUE;
-			}
-			break;
-
-
-		case OID_802_11_WEPDEFAULTKEYID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_WEPDEFAULTKEYID \n"));
-
-			if (wrq->u.data.length != sizeof(UCHAR))
-				Status = -EINVAL;
-			else
-				Status = copy_from_user(&pAdapter->StaCfg.DefaultKeyId, wrq->u.data.pointer, wrq->u.data.length);
-
-			break;
-
-
-		case OID_802_11_CURRENTCHANNEL:
-			DBGPRINT(RT_DEBUG_TRACE, ("Set::OID_802_11_CURRENTCHANNEL \n"));
-			if (wrq->u.data.length != sizeof(UCHAR))
-				Status = -EINVAL;
-			else
-			{
-				Status = copy_from_user(&ctmp, wrq->u.data.pointer, wrq->u.data.length);
-				sprintf(&ctmp,"%d", ctmp);
-				Set_Channel_Proc(pAdapter, &ctmp);
-			}
-			break;
-#endif
-
-
-
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("Set::unknown IOCTL's subcmd = 0x%08x\n", cmd));
-            Status = -EOPNOTSUPP;
-            break;
-    }
-
-
-    return Status;
-}
-
-INT RTMPQueryInformation(
-    IN  PRTMP_ADAPTER pAdapter,
-    IN  OUT struct ifreq    *rq,
-    IN  INT                 cmd)
-{
-    struct iwreq                        *wrq = (struct iwreq *) rq;
-    NDIS_802_11_BSSID_LIST_EX           *pBssidList = NULL;
-    PNDIS_WLAN_BSSID_EX                 pBss;
-    NDIS_802_11_SSID                    Ssid;
-    NDIS_802_11_CONFIGURATION           *pConfiguration = NULL;
-    RT_802_11_LINK_STATUS               *pLinkStatus = NULL;
-    RT_802_11_STA_CONFIG                *pStaConfig = NULL;
-    NDIS_802_11_STATISTICS              *pStatistics = NULL;
-    NDIS_802_11_RTS_THRESHOLD           RtsThresh;
-    NDIS_802_11_FRAGMENTATION_THRESHOLD FragThresh;
-    NDIS_802_11_POWER_MODE              PowerMode;
-    NDIS_802_11_NETWORK_INFRASTRUCTURE  BssType;
-    RT_802_11_PREAMBLE                  PreamType;
-    NDIS_802_11_AUTHENTICATION_MODE     AuthMode;
-    NDIS_802_11_WEP_STATUS              WepStatus;
-    NDIS_MEDIA_STATE                    MediaState;
-    ULONG                               BssBufSize, ulInfo=0, NetworkTypeList[4], apsd = 0;
-    USHORT                              BssLen = 0;
-    PUCHAR                              pBuf = NULL, pPtr;
-    INT                                 Status = NDIS_STATUS_SUCCESS;
-    UINT                                we_version_compiled;
-    UCHAR                               i, Padding = 0;
-    BOOLEAN                             RadioState;
-	UCHAR	driverVersion[8];
-    OID_SET_HT_PHYMODE			        *pHTPhyMode = NULL;
-
-
-#ifdef SNMP_SUPPORT
-	//for snmp, kathy
-	DefaultKeyIdxValue			*pKeyIdxValue;
-	INT							valueLen;
-	TX_RTY_CFG_STRUC			tx_rty_cfg;
-	ULONG						ShortRetryLimit, LongRetryLimit;
-	UCHAR						tmp[64];
-#endif //SNMP
-
-    switch(cmd)
-    {
-        case RT_OID_DEVICE_NAME:
-            wrq->u.data.length = sizeof(STA_NIC_DEVICE_NAME);
-            Status = copy_to_user(wrq->u.data.pointer, STA_NIC_DEVICE_NAME, wrq->u.data.length);
-            break;
-        case RT_OID_VERSION_INFO:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_VERSION_INFO \n"));
-			wrq->u.data.length = 8*sizeof(UCHAR);
-			sprintf(&driverVersion[0], "%s", STA_DRIVER_VERSION);
-			driverVersion[7] = '\0';
-			if (copy_to_user(wrq->u.data.pointer, &driverVersion, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            break;
-#ifdef RALINK_ATE
-		case RT_QUERY_ATE_TXDONE_COUNT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_QUERY_ATE_TXDONE_COUNT \n"));
-			wrq->u.data.length = sizeof(UINT32);
-			if (copy_to_user(wrq->u.data.pointer, &pAdapter->ate.TxDoneCount, wrq->u.data.length))
-			{
-				Status = -EFAULT;
-			}
-			break;
-#endif // RALINK_ATE //
-        case OID_802_11_BSSID_LIST:
-            if (RTMP_TEST_FLAG(pAdapter, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))
-            {
-            	/*
-            	 * Still scanning, indicate the caller should try again.
-            	 */
-            	DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID_LIST (Still scanning)\n"));
-				return -EAGAIN;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID_LIST (%d BSS returned)\n",pAdapter->ScanTab.BssNr));
-			pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-            // Claculate total buffer size required
-            BssBufSize = sizeof(ULONG);
-
-            for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-            {
-                // Align pointer to 4 bytes boundary.
-                //Padding = 4 - (pAdapter->ScanTab.BssEntry[i].VarIELen & 0x0003);
-                //if (Padding == 4)
-                //    Padding = 0;
-                BssBufSize += (sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen + Padding);
-            }
-
-            // For safety issue, we add 256 bytes just in case
-            BssBufSize += 256;
-            // Allocate the same size as passed from higher layer
-            pBuf = kmalloc(BssBufSize, MEM_ALLOC_FLAG);
-            if(pBuf == NULL)
-            {
-                Status = -ENOMEM;
-                break;
-            }
-            // Init 802_11_BSSID_LIST_EX structure
-            NdisZeroMemory(pBuf, BssBufSize);
-            pBssidList = (PNDIS_802_11_BSSID_LIST_EX) pBuf;
-            pBssidList->NumberOfItems = pAdapter->ScanTab.BssNr;
-
-            // Calculate total buffer length
-            BssLen = 4; // Consist of NumberOfItems
-            // Point to start of NDIS_WLAN_BSSID_EX
-            // pPtr = pBuf + sizeof(ULONG);
-            pPtr = (PUCHAR) &pBssidList->Bssid[0];
-            for (i = 0; i < pAdapter->ScanTab.BssNr; i++)
-            {
-                pBss = (PNDIS_WLAN_BSSID_EX) pPtr;
-                NdisMoveMemory(&pBss->MacAddress, &pAdapter->ScanTab.BssEntry[i].Bssid, MAC_ADDR_LEN);
-                if ((pAdapter->ScanTab.BssEntry[i].Hidden == 1) && (pAdapter->StaCfg.bShowHiddenSSID == FALSE))
-                {
-                    //
-					// We must return this SSID during 4way handshaking, otherwise Aegis will failed to parse WPA infomation
-					// and then failed to send EAPOl farame.
-					//
-					if ((pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA) && (pAdapter->StaCfg.PortSecured != WPA_802_1X_PORT_SECURED))
-					{
-						pBss->Ssid.SsidLength = pAdapter->ScanTab.BssEntry[i].SsidLen;
-						NdisMoveMemory(pBss->Ssid.Ssid, pAdapter->ScanTab.BssEntry[i].Ssid, pAdapter->ScanTab.BssEntry[i].SsidLen);
-					}
-					else
-                    	pBss->Ssid.SsidLength = 0;
-                }
-                else
-                {
-                    pBss->Ssid.SsidLength = pAdapter->ScanTab.BssEntry[i].SsidLen;
-                    NdisMoveMemory(pBss->Ssid.Ssid, pAdapter->ScanTab.BssEntry[i].Ssid, pAdapter->ScanTab.BssEntry[i].SsidLen);
-                }
-                pBss->Privacy = pAdapter->ScanTab.BssEntry[i].Privacy;
-                pBss->Rssi = pAdapter->ScanTab.BssEntry[i].Rssi - pAdapter->BbpRssiToDbmDelta;
-                pBss->NetworkTypeInUse = NetworkTypeInUseSanity(&pAdapter->ScanTab.BssEntry[i]);
-                pBss->Configuration.Length = sizeof(NDIS_802_11_CONFIGURATION);
-                pBss->Configuration.BeaconPeriod = pAdapter->ScanTab.BssEntry[i].BeaconPeriod;
-                pBss->Configuration.ATIMWindow = pAdapter->ScanTab.BssEntry[i].AtimWin;
-
-                MAP_CHANNEL_ID_TO_KHZ(pAdapter->ScanTab.BssEntry[i].Channel, pBss->Configuration.DSConfig);
-
-                if (pAdapter->ScanTab.BssEntry[i].BssType == BSS_INFRA)
-                    pBss->InfrastructureMode = Ndis802_11Infrastructure;
-                else
-                    pBss->InfrastructureMode = Ndis802_11IBSS;
-
-                NdisMoveMemory(pBss->SupportedRates, pAdapter->ScanTab.BssEntry[i].SupRate, pAdapter->ScanTab.BssEntry[i].SupRateLen);
-                NdisMoveMemory(pBss->SupportedRates + pAdapter->ScanTab.BssEntry[i].SupRateLen,
-                               pAdapter->ScanTab.BssEntry[i].ExtRate,
-                               pAdapter->ScanTab.BssEntry[i].ExtRateLen);
-
-                if (pAdapter->ScanTab.BssEntry[i].VarIELen == 0)
-                {
-                    pBss->IELength = sizeof(NDIS_802_11_FIXED_IEs);
-                    NdisMoveMemory(pBss->IEs, &pAdapter->ScanTab.BssEntry[i].FixIEs, sizeof(NDIS_802_11_FIXED_IEs));
-                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs);
-                }
-                else
-                {
-                    pBss->IELength = (ULONG)(sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen);
-                    pPtr = pPtr + sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs);
-                    NdisMoveMemory(pBss->IEs, &pAdapter->ScanTab.BssEntry[i].FixIEs, sizeof(NDIS_802_11_FIXED_IEs));
-                    NdisMoveMemory(pBss->IEs + sizeof(NDIS_802_11_FIXED_IEs), pAdapter->ScanTab.BssEntry[i].VarIEs, pAdapter->ScanTab.BssEntry[i].VarIELen);
-                    pPtr += pAdapter->ScanTab.BssEntry[i].VarIELen;
-                }
-                pBss->Length = (ULONG)(sizeof(NDIS_WLAN_BSSID_EX) - 1 + sizeof(NDIS_802_11_FIXED_IEs) + pAdapter->ScanTab.BssEntry[i].VarIELen + Padding);
-
-#if WIRELESS_EXT < 17
-                if ((BssLen + pBss->Length) < wrq->u.data.length)
-                BssLen += pBss->Length;
-                else
-                {
-                    pBssidList->NumberOfItems = i;
-                    break;
-                }
-#else
-                BssLen += pBss->Length;
-#endif
-            }
-
-#if WIRELESS_EXT < 17
-            wrq->u.data.length = BssLen;
-#else
-            if (BssLen > wrq->u.data.length)
-            {
-                kfree(pBssidList);
-                return -E2BIG;
-            }
-            else
-                wrq->u.data.length = BssLen;
-#endif
-            Status = copy_to_user(wrq->u.data.pointer, pBssidList, BssLen);
-            kfree(pBssidList);
-            break;
-        case OID_802_3_CURRENT_ADDRESS:
-            wrq->u.data.length = MAC_ADDR_LEN;
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-            break;
-        case OID_GEN_MEDIA_CONNECT_STATUS:
-            if (pAdapter->IndicateMediaState == NdisMediaStateConnected)
-                MediaState = NdisMediaStateConnected;
-            else
-                MediaState = NdisMediaStateDisconnected;
-
-            wrq->u.data.length = sizeof(NDIS_MEDIA_STATE);
-            Status = copy_to_user(wrq->u.data.pointer, &MediaState, wrq->u.data.length);
-            break;
-        case OID_802_11_BSSID:
-#ifdef RALINK_ATE
-			if (ATE_ON(pAdapter))
-			{
-				DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
-				Status = NDIS_STATUS_RESOURCES;
-				break;
-			}
-#endif // RALINK_ATE //
-            if (INFRA_ON(pAdapter) || ADHOC_ON(pAdapter))
-            {
-                Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Bssid, sizeof(NDIS_802_11_MAC_ADDRESS));
-
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BSSID(=EMPTY)\n"));
-                Status = -ENOTCONN;
-            }
-            break;
-        case OID_802_11_SSID:
-			NdisZeroMemory(&Ssid, sizeof(NDIS_802_11_SSID));
-			NdisZeroMemory(Ssid.Ssid, MAX_LEN_OF_SSID);
-            Ssid.SsidLength = pAdapter->CommonCfg.SsidLen;
-			memcpy(Ssid.Ssid, pAdapter->CommonCfg.Ssid,	Ssid.SsidLength);
-            wrq->u.data.length = sizeof(NDIS_802_11_SSID);
-            Status = copy_to_user(wrq->u.data.pointer, &Ssid, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_SSID (Len=%d, ssid=%s)\n", Ssid.SsidLength,Ssid.Ssid));
-            break;
-        case RT_OID_802_11_QUERY_LINK_STATUS:
-            pLinkStatus = (RT_802_11_LINK_STATUS *) kmalloc(sizeof(RT_802_11_LINK_STATUS), MEM_ALLOC_FLAG);
-            if (pLinkStatus)
-            {
-                pLinkStatus->CurrTxRate = RateIdTo500Kbps[pAdapter->CommonCfg.TxRate];   // unit : 500 kbps
-                pLinkStatus->ChannelQuality = pAdapter->Mlme.ChannelQuality;
-                pLinkStatus->RxByteCount = pAdapter->RalinkCounters.ReceivedByteCount;
-                pLinkStatus->TxByteCount = pAdapter->RalinkCounters.TransmittedByteCount;
-        		pLinkStatus->CentralChannel = pAdapter->CommonCfg.CentralChannel;
-                wrq->u.data.length = sizeof(RT_802_11_LINK_STATUS);
-                Status = copy_to_user(wrq->u.data.pointer, pLinkStatus, wrq->u.data.length);
-                kfree(pLinkStatus);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LINK_STATUS\n"));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LINK_STATUS(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_802_11_CONFIGURATION:
-            pConfiguration = (NDIS_802_11_CONFIGURATION *) kmalloc(sizeof(NDIS_802_11_CONFIGURATION), MEM_ALLOC_FLAG);
-            if (pConfiguration)
-            {
-                pConfiguration->Length = sizeof(NDIS_802_11_CONFIGURATION);
-                pConfiguration->BeaconPeriod = pAdapter->CommonCfg.BeaconPeriod;
-                pConfiguration->ATIMWindow = pAdapter->StaActive.AtimWin;
-                MAP_CHANNEL_ID_TO_KHZ(pAdapter->CommonCfg.Channel, pConfiguration->DSConfig);
-                wrq->u.data.length = sizeof(NDIS_802_11_CONFIGURATION);
-                Status = copy_to_user(wrq->u.data.pointer, pConfiguration, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CONFIGURATION(BeaconPeriod=%ld,AtimW=%ld,Channel=%d) \n",
-                                        pConfiguration->BeaconPeriod, pConfiguration->ATIMWindow, pAdapter->CommonCfg.Channel));
-				kfree(pConfiguration);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CONFIGURATION(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-		case RT_OID_802_11_SNR_0:
-			if ((pAdapter->StaCfg.LastSNR0 > 0))
-			{
-				ulInfo = ((0xeb	- pAdapter->StaCfg.LastSNR0) * 3) /	16 ;
-				wrq->u.data.length = sizeof(ulInfo);
-				Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_SNR_0(0x=%lx)\n", ulInfo));
-			}
-            else
-			    Status = -EFAULT;
-			break;
-		case RT_OID_802_11_SNR_1:
-			if ((pAdapter->Antenna.field.RxPath	> 1) &&
-                (pAdapter->StaCfg.LastSNR1 > 0))
-			{
-				ulInfo = ((0xeb	- pAdapter->StaCfg.LastSNR1) * 3) /	16 ;
-				wrq->u.data.length = sizeof(ulInfo);
-				Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE,("Query::RT_OID_802_11_SNR_1(0x=%lx)\n",ulInfo));
-			}
-			else
-				Status = -EFAULT;
-            DBGPRINT(RT_DEBUG_TRACE,("Query::RT_OID_802_11_SNR_1(pAdapter->StaCfg.LastSNR1=%d)\n",pAdapter->StaCfg.LastSNR1));
-			break;
-        case OID_802_11_RSSI_TRIGGER:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi0 - pAdapter->BbpRssiToDbmDelta;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_RSSI_TRIGGER(=%ld)\n", ulInfo));
-            break;
-		case OID_802_11_RSSI:
-        case RT_OID_802_11_RSSI:
-			ulInfo = pAdapter->StaCfg.RssiSample.LastRssi0;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-		case RT_OID_802_11_RSSI_1:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi1;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-        case RT_OID_802_11_RSSI_2:
-            ulInfo = pAdapter->StaCfg.RssiSample.LastRssi2;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			break;
-        case OID_802_11_STATISTICS:
-            pStatistics = (NDIS_802_11_STATISTICS *) kmalloc(sizeof(NDIS_802_11_STATISTICS), MEM_ALLOC_FLAG);
-            if (pStatistics)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_STATISTICS \n"));
-                // add the most up-to-date h/w raw counters into software counters
-			    NICUpdateRawCounters(pAdapter);
-
-                // Sanity check for calculation of sucessful count
-                if (pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart < pAdapter->WlanCounters.RetryCount.QuadPart)
-                    pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart = pAdapter->WlanCounters.RetryCount.QuadPart;
-
-                pStatistics->TransmittedFragmentCount.QuadPart = pAdapter->WlanCounters.TransmittedFragmentCount.QuadPart;
-                pStatistics->MulticastTransmittedFrameCount.QuadPart = pAdapter->WlanCounters.MulticastTransmittedFrameCount.QuadPart;
-                pStatistics->FailedCount.QuadPart = pAdapter->WlanCounters.FailedCount.QuadPart;
-                pStatistics->RetryCount.QuadPart = pAdapter->WlanCounters.RetryCount.QuadPart;
-                pStatistics->MultipleRetryCount.QuadPart = pAdapter->WlanCounters.MultipleRetryCount.QuadPart;
-                pStatistics->RTSSuccessCount.QuadPart = pAdapter->WlanCounters.RTSSuccessCount.QuadPart;
-                pStatistics->RTSFailureCount.QuadPart = pAdapter->WlanCounters.RTSFailureCount.QuadPart;
-                pStatistics->ACKFailureCount.QuadPart = pAdapter->WlanCounters.ACKFailureCount.QuadPart;
-                pStatistics->FrameDuplicateCount.QuadPart = pAdapter->WlanCounters.FrameDuplicateCount.QuadPart;
-                pStatistics->ReceivedFragmentCount.QuadPart = pAdapter->WlanCounters.ReceivedFragmentCount.QuadPart;
-                pStatistics->MulticastReceivedFrameCount.QuadPart = pAdapter->WlanCounters.MulticastReceivedFrameCount.QuadPart;
-#ifdef DBG
-                pStatistics->FCSErrorCount = pAdapter->RalinkCounters.RealFcsErrCount;
-#else
-                pStatistics->FCSErrorCount.QuadPart = pAdapter->WlanCounters.FCSErrorCount.QuadPart;
-                pStatistics->FrameDuplicateCount.u.LowPart = pAdapter->WlanCounters.FrameDuplicateCount.u.LowPart / 100;
-#endif
-                wrq->u.data.length = sizeof(NDIS_802_11_STATISTICS);
-                Status = copy_to_user(wrq->u.data.pointer, pStatistics, wrq->u.data.length);
-                kfree(pStatistics);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_STATISTICS(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_GEN_RCV_OK:
-            ulInfo = pAdapter->Counters8023.GoodReceives;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            break;
-        case OID_GEN_RCV_NO_BUFFER:
-            ulInfo = pAdapter->Counters8023.RxNoBuffer;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            break;
-        case RT_OID_802_11_PHY_MODE:
-            ulInfo = (ULONG)pAdapter->CommonCfg.PhyMode;
-            wrq->u.data.length = sizeof(ulInfo);
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PHY_MODE (=%ld)\n", ulInfo));
-            break;
-        case RT_OID_802_11_STA_CONFIG:
-            pStaConfig = (RT_802_11_STA_CONFIG *) kmalloc(sizeof(RT_802_11_STA_CONFIG), MEM_ALLOC_FLAG);
-            if (pStaConfig)
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG\n"));
-                pStaConfig->EnableTxBurst = pAdapter->CommonCfg.bEnableTxBurst;
-                pStaConfig->EnableTurboRate = 0;
-                pStaConfig->UseBGProtection = pAdapter->CommonCfg.UseBGProtection;
-                pStaConfig->UseShortSlotTime = pAdapter->CommonCfg.bUseShortSlotTime;
-                //pStaConfig->AdhocMode = pAdapter->StaCfg.AdhocMode;
-                pStaConfig->HwRadioStatus = (pAdapter->StaCfg.bHwRadio == TRUE) ? 1 : 0;
-                pStaConfig->Rsv1 = 0;
-                pStaConfig->SystemErrorBitmap = pAdapter->SystemErrorBitmap;
-                wrq->u.data.length = sizeof(RT_802_11_STA_CONFIG);
-                Status = copy_to_user(wrq->u.data.pointer, pStaConfig, wrq->u.data.length);
-                kfree(pStaConfig);
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case OID_802_11_RTS_THRESHOLD:
-            RtsThresh = pAdapter->CommonCfg.RtsThreshold;
-            wrq->u.data.length = sizeof(RtsThresh);
-            Status = copy_to_user(wrq->u.data.pointer, &RtsThresh, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_RTS_THRESHOLD(=%ld)\n", RtsThresh));
-            break;
-        case OID_802_11_FRAGMENTATION_THRESHOLD:
-            FragThresh = pAdapter->CommonCfg.FragmentThreshold;
-            if (pAdapter->CommonCfg.bUseZeroToDisableFragment == TRUE)
-                FragThresh = 0;
-            wrq->u.data.length = sizeof(FragThresh);
-            Status = copy_to_user(wrq->u.data.pointer, &FragThresh, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_FRAGMENTATION_THRESHOLD(=%ld)\n", FragThresh));
-            break;
-        case OID_802_11_POWER_MODE:
-            PowerMode = pAdapter->StaCfg.WindowsPowerMode;
-            wrq->u.data.length = sizeof(PowerMode);
-            Status = copy_to_user(wrq->u.data.pointer, &PowerMode, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_POWER_MODE(=%d)\n", PowerMode));
-            break;
-        case RT_OID_802_11_RADIO:
-            RadioState = (BOOLEAN) pAdapter->StaCfg.bSwRadio;
-            wrq->u.data.length = sizeof(RadioState);
-            Status = copy_to_user(wrq->u.data.pointer, &RadioState, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_RADIO (=%d)\n", RadioState));
-            break;
-        case OID_802_11_INFRASTRUCTURE_MODE:
-            if (pAdapter->StaCfg.BssType == BSS_ADHOC)
-                BssType = Ndis802_11IBSS;
-            else if (pAdapter->StaCfg.BssType == BSS_INFRA)
-                BssType = Ndis802_11Infrastructure;
-            else if (pAdapter->StaCfg.BssType == BSS_MONITOR)
-                BssType = Ndis802_11Monitor;
-            else
-                BssType = Ndis802_11AutoUnknown;
-
-            wrq->u.data.length = sizeof(BssType);
-            Status = copy_to_user(wrq->u.data.pointer, &BssType, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_INFRASTRUCTURE_MODE(=%d)\n", BssType));
-            break;
-        case RT_OID_802_11_PREAMBLE:
-            PreamType = pAdapter->CommonCfg.TxPreamble;
-            wrq->u.data.length = sizeof(PreamType);
-            Status = copy_to_user(wrq->u.data.pointer, &PreamType, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PREAMBLE(=%d)\n", PreamType));
-            break;
-        case OID_802_11_AUTHENTICATION_MODE:
-            AuthMode = pAdapter->StaCfg.AuthMode;
-            wrq->u.data.length = sizeof(AuthMode);
-            Status = copy_to_user(wrq->u.data.pointer, &AuthMode, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_AUTHENTICATION_MODE(=%d)\n", AuthMode));
-            break;
-        case OID_802_11_WEP_STATUS:
-            WepStatus = pAdapter->StaCfg.WepStatus;
-            wrq->u.data.length = sizeof(WepStatus);
-            Status = copy_to_user(wrq->u.data.pointer, &WepStatus, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_WEP_STATUS(=%d)\n", WepStatus));
-            break;
-        case OID_802_11_TX_POWER_LEVEL:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.TxPower, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_TX_POWER_LEVEL %x\n",pAdapter->CommonCfg.TxPower));
-			break;
-        case RT_OID_802_11_TX_POWER_LEVEL_1:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.TxPowerPercentage, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_TX_POWER_LEVEL_1 (=%ld)\n", pAdapter->CommonCfg.TxPowerPercentage));
-			break;
-        case OID_802_11_NETWORK_TYPES_SUPPORTED:
-			if ((pAdapter->RfIcType	== RFIC_2850) || (pAdapter->RfIcType ==	RFIC_2750))
-			{
-				NetworkTypeList[0] = 3;                 // NumberOfItems = 3
-				NetworkTypeList[1] = Ndis802_11DS;      // NetworkType[1] = 11b
-				NetworkTypeList[2] = Ndis802_11OFDM24;  // NetworkType[2] = 11g
-				NetworkTypeList[3] = Ndis802_11OFDM5;   // NetworkType[3] = 11a
-                wrq->u.data.length = 16;
-				Status = copy_to_user(wrq->u.data.pointer, &NetworkTypeList[0], wrq->u.data.length);
-			}
-			else
-			{
-				NetworkTypeList[0] = 2;                 // NumberOfItems = 2
-				NetworkTypeList[1] = Ndis802_11DS;      // NetworkType[1] = 11b
-				NetworkTypeList[2] = Ndis802_11OFDM24;  // NetworkType[2] = 11g
-			    wrq->u.data.length = 12;
-				Status = copy_to_user(wrq->u.data.pointer, &NetworkTypeList[0], wrq->u.data.length);
-			}
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_NETWORK_TYPES_SUPPORTED\n"));
-				break;
-	    case OID_802_11_NETWORK_TYPE_IN_USE:
-            wrq->u.data.length = sizeof(ULONG);
-			if (pAdapter->CommonCfg.PhyMode == PHY_11A)
-				ulInfo = Ndis802_11OFDM5;
-			else if ((pAdapter->CommonCfg.PhyMode == PHY_11BG_MIXED) || (pAdapter->CommonCfg.PhyMode == PHY_11G))
-				ulInfo = Ndis802_11OFDM24;
-			else
-				ulInfo = Ndis802_11DS;
-            Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-        case RT_OID_802_11_QUERY_LAST_RX_RATE:
-            ulInfo = (ULONG)pAdapter->LastRxRate;
-            wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LAST_RX_RATE (=%ld)\n", ulInfo));
-			break;
-		case RT_OID_802_11_QUERY_LAST_TX_RATE:
-			//ulInfo = (ULONG)pAdapter->LastTxRate;
-			ulInfo = (ULONG)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word;
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo,	wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_LAST_TX_RATE (=%lx)\n", ulInfo));
-			break;
-        case RT_OID_802_11_QUERY_EEPROM_VERSION:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->EepromVersion, wrq->u.data.length);
-            break;
-        case RT_OID_802_11_QUERY_FIRMWARE_VERSION:
-            wrq->u.data.length = sizeof(ULONG);
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->FirmwareVersion, wrq->u.data.length);
-			break;
-	    case RT_OID_802_11_QUERY_NOISE_LEVEL:
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->BbpWriteLatch[66], wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_NOISE_LEVEL (=%d)\n", pAdapter->BbpWriteLatch[66]));
-			break;
-	    case RT_OID_802_11_EXTRA_INFO:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->ExtraInfo, wrq->u.data.length);
-	        DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_EXTRA_INFO (=%ld)\n", pAdapter->ExtraInfo));
-	        break;
-	    case RT_OID_WE_VERSION_COMPILED:
-	        wrq->u.data.length = sizeof(UINT);
-	        we_version_compiled = WIRELESS_EXT;
-	        Status = copy_to_user(wrq->u.data.pointer, &we_version_compiled, wrq->u.data.length);
-	        break;
-		case RT_OID_802_11_QUERY_APSD_SETTING:
-			apsd = (pAdapter->CommonCfg.bAPSDCapable | (pAdapter->CommonCfg.bAPSDAC_BE << 1) | (pAdapter->CommonCfg.bAPSDAC_BK << 2)
-				| (pAdapter->CommonCfg.bAPSDAC_VI << 3)	| (pAdapter->CommonCfg.bAPSDAC_VO << 4)	| (pAdapter->CommonCfg.MaxSPLength << 5));
-
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &apsd, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_APSD_SETTING (=0x%lx,APSDCap=%d,AC_BE=%d,AC_BK=%d,AC_VI=%d,AC_VO=%d,MAXSPLen=%d)\n",
-				apsd,pAdapter->CommonCfg.bAPSDCapable,pAdapter->CommonCfg.bAPSDAC_BE,pAdapter->CommonCfg.bAPSDAC_BK,pAdapter->CommonCfg.bAPSDAC_VI,pAdapter->CommonCfg.bAPSDAC_VO,pAdapter->CommonCfg.MaxSPLength));
-			break;
-		case RT_OID_802_11_QUERY_APSD_PSM:
-			wrq->u.data.length = sizeof(ULONG);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bAPSDForcePowerSave, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_APSD_PSM (=%d)\n", pAdapter->CommonCfg.bAPSDForcePowerSave));
-			break;
-		case RT_OID_802_11_QUERY_WMM:
-			wrq->u.data.length = sizeof(BOOLEAN);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bWmmCapable, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_WMM (=%d)\n",	pAdapter->CommonCfg.bWmmCapable));
-			break;
-#ifdef WPA_SUPPLICANT_SUPPORT
-        case RT_OID_NEW_DRIVER:
-            {
-                UCHAR enabled = 1;
-    	        wrq->u.data.length = sizeof(UCHAR);
-    	        Status = copy_to_user(wrq->u.data.pointer, &enabled, wrq->u.data.length);
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_NEW_DRIVER (=%d)\n", enabled));
-            }
-	        break;
-        case RT_OID_WPA_SUPPLICANT_SUPPORT:
-	        wrq->u.data.length = sizeof(UCHAR);
-	        Status = copy_to_user(wrq->u.data.pointer, &pAdapter->StaCfg.WpaSupplicantUP, wrq->u.data.length);
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_WPA_SUPPLICANT_SUPPORT (=%d)\n", pAdapter->StaCfg.WpaSupplicantUP));
-	        break;
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-        case RT_OID_DRIVER_DEVICE_NAME:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_DRIVER_DEVICE_NAME \n"));
-			wrq->u.data.length = 16;
-			if (copy_to_user(wrq->u.data.pointer, pAdapter->StaCfg.dev_name, wrq->u.data.length))
-			{
-				Status = -EFAULT;
-			}
-            break;
-        case RT_OID_802_11_QUERY_HT_PHYMODE:
-            pHTPhyMode = (OID_SET_HT_PHYMODE *) kmalloc(sizeof(OID_SET_HT_PHYMODE), MEM_ALLOC_FLAG);
-            if (pHTPhyMode)
-            {
-                pHTPhyMode->PhyMode = pAdapter->CommonCfg.PhyMode;
-    			pHTPhyMode->HtMode = (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.MODE;
-    			pHTPhyMode->BW = (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.BW;
-    			pHTPhyMode->MCS= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.MCS;
-    			pHTPhyMode->SHORTGI= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.ShortGI;
-    			pHTPhyMode->STBC= (UCHAR)pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.field.STBC;
-
-    			pHTPhyMode->ExtOffset = ((pAdapter->CommonCfg.CentralChannel < pAdapter->CommonCfg.Channel) ? (EXTCHA_BELOW) : (EXTCHA_ABOVE));
-                wrq->u.data.length = sizeof(OID_SET_HT_PHYMODE);
-                if (copy_to_user(wrq->u.data.pointer, pHTPhyMode, wrq->u.data.length))
-    			{
-    				Status = -EFAULT;
-    			}
-    			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_HT_PHYMODE (PhyMode = %d, MCS =%d, BW = %d, STBC = %d, ExtOffset=%d)\n",
-    				pHTPhyMode->HtMode, pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC, pHTPhyMode->ExtOffset));
-    			DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (.word = %x )\n", pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case RT_OID_802_11_COUNTRY_REGION:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_COUNTRY_REGION \n"));
-			wrq->u.data.length = sizeof(ulInfo);
-            ulInfo = pAdapter->CommonCfg.CountryRegionForABand;
-            ulInfo = (ulInfo << 8)|(pAdapter->CommonCfg.CountryRegion);
-			if (copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            break;
-        case RT_OID_802_11_QUERY_DAT_HT_PHYMODE:
-            pHTPhyMode = (OID_SET_HT_PHYMODE *) kmalloc(sizeof(OID_SET_HT_PHYMODE), MEM_ALLOC_FLAG);
-            if (pHTPhyMode)
-            {
-                pHTPhyMode->PhyMode = pAdapter->CommonCfg.PhyMode;
-    			pHTPhyMode->HtMode = (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.HTMODE;
-    			pHTPhyMode->BW = (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.BW;
-    			pHTPhyMode->MCS= (UCHAR)pAdapter->StaCfg.DesiredTransmitSetting.field.MCS;
-    			pHTPhyMode->SHORTGI= (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.ShortGI;
-    			pHTPhyMode->STBC= (UCHAR)pAdapter->CommonCfg.RegTransmitSetting.field.STBC;
-
-                wrq->u.data.length = sizeof(OID_SET_HT_PHYMODE);
-                if (copy_to_user(wrq->u.data.pointer, pHTPhyMode, wrq->u.data.length))
-    			{
-    				Status = -EFAULT;
-    			}
-    			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_HT_PHYMODE (PhyMode = %d, MCS =%d, BW = %d, STBC = %d, ExtOffset=%d)\n",
-    				pHTPhyMode->HtMode, pHTPhyMode->MCS, pHTPhyMode->BW, pHTPhyMode->STBC, pHTPhyMode->ExtOffset));
-    			DBGPRINT(RT_DEBUG_TRACE, (" MlmeUpdateTxRates (.word = %x )\n", pAdapter->MacTab.Content[BSSID_WCID].HTPhyMode.word));
-            }
-            else
-            {
-                DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_STA_CONFIG(kmalloc failed)\n"));
-                Status = -EFAULT;
-            }
-            break;
-        case RT_OID_QUERY_MULTIPLE_CARD_SUPPORT:
-			wrq->u.data.length = sizeof(UCHAR);
-            i = 0;
-#ifdef MULTIPLE_CARD_SUPPORT
-            i = 1;
-#endif // MULTIPLE_CARD_SUPPORT //
-			if (copy_to_user(wrq->u.data.pointer, &i, wrq->u.data.length))
-            {
-				Status = -EFAULT;
-            }
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_QUERY_MULTIPLE_CARD_SUPPORT(=%d) \n", i));
-            break;
-#ifdef SNMP_SUPPORT
-		case RT_OID_802_11_MAC_ADDRESS:
-            wrq->u.data.length = MAC_ADDR_LEN;
-            Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTUREROUI:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTUREROUI \n"));
-			wrq->u.data.length = ManufacturerOUI_LEN;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CurrentAddress, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTURERNAME:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTURERNAME \n"));
-			wrq->u.data.length = strlen(ManufacturerNAME);
-			Status = copy_to_user(wrq->u.data.pointer, ManufacturerNAME, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_RESOURCETYPEIDNAME:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_RESOURCETYPEIDNAME \n"));
-			wrq->u.data.length = strlen(ResourceTypeIdName);
-			Status = copy_to_user(wrq->u.data.pointer, ResourceTypeIdName, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PRIVACYOPTIONIMPLEMENTED \n"));
-			ulInfo = 1; // 1 is support wep else 2 is not support.
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_POWERMANAGEMENTMODE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_POWERMANAGEMENTMODE \n"));
-			if (pAdapter->StaCfg.Psm == PSMP_ACTION)
-				ulInfo = 1; // 1 is power active else 2 is power save.
-			else
-				ulInfo = 2;
-
-			wrq->u.data.length = sizeof(ulInfo);
-			Status = copy_to_user(wrq->u.data.pointer, &ulInfo, wrq->u.data.length);
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYVALUE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_WEPDEFAULTKEYVALUE \n"));
-			//KeyIdxValue.KeyIdx = pAd->PortCfg.MBSSID[pAd->IoctlIF].DefaultKeyId;
-			pKeyIdxValue = wrq->u.data.pointer;
-			DBGPRINT(RT_DEBUG_TRACE,("KeyIdxValue.KeyIdx = %d, \n",pKeyIdxValue->KeyIdx));
-			valueLen = pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen;
-			NdisMoveMemory(pKeyIdxValue->Value,
-						   &pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].Key,
-						   valueLen);
-			pKeyIdxValue->Value[valueLen]='\0';
-
-			wrq->u.data.length = sizeof(DefaultKeyIdxValue);
-
-			Status = copy_to_user(wrq->u.data.pointer, pKeyIdxValue, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE,("DefaultKeyId = %d, total len = %d, str len=%d, KeyValue= %02x %02x %02x %02x \n", pAdapter->StaCfg.DefaultKeyId, wrq->u.data.length, pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen,
-			pAdapter->SharedKey[BSS0][0].Key[0],
-			pAdapter->SharedKey[BSS0][1].Key[0],
-			pAdapter->SharedKey[BSS0][2].Key[0],
-			pAdapter->SharedKey[BSS0][3].Key[0]));
-			break;
-
-		case OID_802_11_WEPDEFAULTKEYID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_WEPDEFAULTKEYID \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->StaCfg.DefaultKeyId, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("DefaultKeyId =%d \n", pAdapter->StaCfg.DefaultKeyId));
-			break;
-
-		case RT_OID_802_11_WEPKEYMAPPINGLENGTH:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_WEPKEYMAPPINGLENGTH \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			Status = copy_to_user(wrq->u.data.pointer,
-									&pAdapter->SharedKey[BSS0][pAdapter->StaCfg.DefaultKeyId].KeyLen,
-									wrq->u.data.length);
-			break;
-
-		case OID_802_11_SHORTRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_SHORTRETRYLIMIT \n"));
-			wrq->u.data.length = sizeof(ULONG);
-			RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-			ShortRetryLimit = tx_rty_cfg.field.ShortRtyLimit;
-			DBGPRINT(RT_DEBUG_TRACE, ("ShortRetryLimit =%ld,  tx_rty_cfg.field.ShortRetryLimit=%d\n", ShortRetryLimit, tx_rty_cfg.field.ShortRtyLimit));
-			Status = copy_to_user(wrq->u.data.pointer, &ShortRetryLimit, wrq->u.data.length);
-			break;
-
-		case OID_802_11_LONGRETRYLIMIT:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_LONGRETRYLIMIT \n"));
-			wrq->u.data.length = sizeof(ULONG);
-			RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-			LongRetryLimit = tx_rty_cfg.field.LongRtyLimit;
-			DBGPRINT(RT_DEBUG_TRACE, ("LongRetryLimit =%ld,  tx_rty_cfg.field.LongRtyLimit=%d\n", LongRetryLimit, tx_rty_cfg.field.LongRtyLimit));
-			Status = copy_to_user(wrq->u.data.pointer, &LongRetryLimit, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_PRODUCTID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_PRODUCTID \n"));
-
-#ifdef RT2870
-			sprintf(tmp, "%04x %04x\n", ((POS_COOKIE)pAdapter->OS_Cookie)->pUsb_Dev->descriptor.idVendor ,((POS_COOKIE)pAdapter->OS_Cookie)->pUsb_Dev->descriptor.idProduct);
-
-#endif // RT2870 //
-			wrq->u.data.length = strlen(tmp);
-			Status = copy_to_user(wrq->u.data.pointer, tmp, wrq->u.data.length);
-			break;
-
-		case RT_OID_802_11_MANUFACTUREID:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_MANUFACTUREID \n"));
-			wrq->u.data.length = strlen(ManufacturerNAME);
-			Status = copy_to_user(wrq->u.data.pointer, ManufacturerNAME, wrq->u.data.length);
-			break;
-
-		case OID_802_11_CURRENTCHANNEL:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_CURRENTCHANNEL \n"));
-			wrq->u.data.length = sizeof(UCHAR);
-			DBGPRINT(RT_DEBUG_TRACE, ("sizeof UCHAR=%d, channel=%d \n", sizeof(UCHAR), pAdapter->CommonCfg.Channel));
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Channel, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-#endif //SNMP_SUPPORT
-
-		case OID_802_11_BUILD_CHANNEL_EX:
-			{
-				UCHAR value;
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_BUILD_CHANNEL_EX \n"));
-				wrq->u.data.length = sizeof(UCHAR);
-#ifdef EXT_BUILD_CHANNEL_LIST
-				DBGPRINT(RT_DEBUG_TRACE, ("Support EXT_BUILD_CHANNEL_LIST.\n"));
-				value = 1;
-#else
-				DBGPRINT(RT_DEBUG_TRACE, ("Doesn't support EXT_BUILD_CHANNEL_LIST.\n"));
-				value = 0;
-#endif // EXT_BUILD_CHANNEL_LIST //
-				Status = copy_to_user(wrq->u.data.pointer, &value, 1);
-				DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			}
-			break;
-
-		case OID_802_11_GET_CH_LIST:
-			{
-				PRT_CHANNEL_LIST_INFO pChListBuf;
-
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_CH_LIST \n"));
-				if (pAdapter->ChannelListNum == 0)
-				{
-					wrq->u.data.length = 0;
-					break;
-				}
-
-				pChListBuf = (RT_CHANNEL_LIST_INFO *) kmalloc(sizeof(RT_CHANNEL_LIST_INFO), MEM_ALLOC_FLAG);
-				if (pChListBuf == NULL)
-				{
-					wrq->u.data.length = 0;
-					break;
-				}
-
-				pChListBuf->ChannelListNum = pAdapter->ChannelListNum;
-				for (i = 0; i < pChListBuf->ChannelListNum; i++)
-					pChListBuf->ChannelList[i] = pAdapter->ChannelList[i].Channel;
-
-				wrq->u.data.length = sizeof(RT_CHANNEL_LIST_INFO);
-				Status = copy_to_user(wrq->u.data.pointer, pChListBuf, sizeof(RT_CHANNEL_LIST_INFO));
-				DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-
-				if (pChListBuf)
-					kfree(pChListBuf);
-			}
-			break;
-
-		case OID_802_11_GET_COUNTRY_CODE:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_COUNTRY_CODE \n"));
-			wrq->u.data.length = 2;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.CountryCode, 2);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-
-		case OID_802_11_GET_CHANNEL_GEOGRAPHY:
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::OID_802_11_GET_CHANNEL_GEOGRAPHY \n"));
-			wrq->u.data.length = 1;
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.Geography, 1);
-			DBGPRINT(RT_DEBUG_TRACE, ("Status=%d\n", Status));
-			break;
-
-
-#ifdef QOS_DLS_SUPPORT
-		case RT_OID_802_11_QUERY_DLS:
-			wrq->u.data.length = sizeof(BOOLEAN);
-			Status = copy_to_user(wrq->u.data.pointer, &pAdapter->CommonCfg.bDLSCapable, wrq->u.data.length);
-			DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_DLS(=%d)\n", pAdapter->CommonCfg.bDLSCapable));
-			break;
-
-		case RT_OID_802_11_QUERY_DLS_PARAM:
-			{
-				PRT_802_11_DLS_INFO	pDlsInfo = kmalloc(sizeof(RT_802_11_DLS_INFO), GFP_ATOMIC);
-				if (pDlsInfo == NULL)
-					break;
-
-				for (i=0; i<MAX_NUM_OF_DLS_ENTRY; i++)
-				{
-					RTMPMoveMemory(&pDlsInfo->Entry[i], &pAdapter->StaCfg.DLSEntry[i], sizeof(RT_802_11_DLS_UI));
-				}
-
-				pDlsInfo->num = MAX_NUM_OF_DLS_ENTRY;
-				wrq->u.data.length = sizeof(RT_802_11_DLS_INFO);
-				Status = copy_to_user(wrq->u.data.pointer, pDlsInfo, wrq->u.data.length);
-				DBGPRINT(RT_DEBUG_TRACE, ("Query::RT_OID_802_11_QUERY_DLS_PARAM\n"));
-
-				if (pDlsInfo)
-					kfree(pDlsInfo);
-			}
-			break;
-#endif // QOS_DLS_SUPPORT //
-        default:
-            DBGPRINT(RT_DEBUG_TRACE, ("Query::unknown IOCTL's subcmd = 0x%08x\n", cmd));
-            Status = -EOPNOTSUPP;
-            break;
-    }
-    return Status;
-}
-
-INT rt28xx_sta_ioctl(
-	IN	struct net_device	*net_dev,
-	IN	OUT	struct ifreq	*rq,
-	IN	INT					cmd)
-{
-	POS_COOKIE			pObj;
-	VIRTUAL_ADAPTER		*pVirtualAd = NULL;
-	RTMP_ADAPTER        *pAd = NULL;
-	struct iwreq        *wrq = (struct iwreq *) rq;
-	BOOLEAN				StateMachineTouched = FALSE;
-	INT					Status = NDIS_STATUS_SUCCESS;
-	USHORT				subcmd;
-
-	if (net_dev->priv_flags == INT_MAIN)
-	{
-		pAd = net_dev->ml_priv;
-	}
-	else
-	{
-		pVirtualAd = net_dev->ml_priv;
-		pAd = pVirtualAd->RtmpDev->ml_priv;
-	}
-	pObj = (POS_COOKIE) pAd->OS_Cookie;
-
-	if (pAd == NULL)
-	{
-		/* if 1st open fail, pAd will be free;
-		   So the net_dev->ml_priv will be NULL in 2rd open */
-		return -ENETDOWN;
-	}
-
-    //check if the interface is down
-    if(!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_INTERRUPT_IN_USE))
-    {
-#ifdef CONFIG_APSTA_MIXED_SUPPORT
-	    if (wrq->u.data.pointer == NULL)
-	    {
-		    return Status;
-	    }
-
-	    if (strstr(wrq->u.data.pointer, "OpMode") == NULL)
-#endif // CONFIG_APSTA_MIXED_SUPPORT //
-        {
-            DBGPRINT(RT_DEBUG_TRACE, ("INFO::Network is down!\n"));
-		    return -ENETDOWN;
-        }
-    }
-
-	{	// determine this ioctl command is comming from which interface.
-		pObj->ioctl_if_type = INT_MAIN;
-		pObj->ioctl_if = MAIN_MBSSID;
-	}
-
-	switch(cmd)
-	{
-#ifdef RALINK_ATE
-#ifdef RALINK_28xx_QA
-		case RTPRIV_IOCTL_ATE:
-			{
-				RtmpDoAte(pAd, wrq);
-			}
-			break;
-#endif // RALINK_28xx_QA //
-#endif // RALINK_ATE //
-        case SIOCGIFHWADDR:
-			DBGPRINT(RT_DEBUG_TRACE, ("IOCTL::SIOCGIFHWADDR\n"));
-			memcpy(wrq->u.name, pAd->CurrentAddress, ETH_ALEN);
-			break;
-		case SIOCGIWNAME:
-        {
-        	char *name=&wrq->u.name[0];
-        	rt_ioctl_giwname(net_dev, NULL, name, NULL);
-			break;
-		}
-		case SIOCGIWESSID:  //Get ESSID
-        {
-        	struct iw_point *essid=&wrq->u.essid;
-        	rt_ioctl_giwessid(net_dev, NULL, essid, essid->pointer);
-			break;
-		}
-		case SIOCSIWESSID:  //Set ESSID
-        {
-        	struct iw_point	*essid=&wrq->u.essid;
-        	rt_ioctl_siwessid(net_dev, NULL, essid, essid->pointer);
-			break;
-		}
-		case SIOCSIWNWID:   // set network id (the cell)
-		case SIOCGIWNWID:   // get network id
-			Status = -EOPNOTSUPP;
-			break;
-		case SIOCSIWFREQ:   //set channel/frequency (Hz)
-        {
-        	struct iw_freq *freq=&wrq->u.freq;
-        	rt_ioctl_siwfreq(net_dev, NULL, freq, NULL);
-			break;
-		}
-		case SIOCGIWFREQ:   // get channel/frequency (Hz)
-        {
-        	struct iw_freq *freq=&wrq->u.freq;
-        	rt_ioctl_giwfreq(net_dev, NULL, freq, NULL);
-			break;
-		}
-		case SIOCSIWNICKN: //set node name/nickname
-        {
-        	struct iw_point *data=&wrq->u.data;
-        	rt_ioctl_siwnickn(net_dev, NULL, data, NULL);
-			break;
-		}
-		case SIOCGIWNICKN: //get node name/nickname
-        {
-        	struct iw_point *data=&wrq->u.data;
-        	rt_ioctl_giwnickn(net_dev, NULL, data, NULL);
-			break;
-		}
-		case SIOCGIWRATE:   //get default bit rate (bps)
-		    rt_ioctl_giwrate(net_dev, NULL, &wrq->u, NULL);
-            break;
-	    case SIOCSIWRATE:  //set default bit rate (bps)
-	        rt_ioctl_siwrate(net_dev, NULL, &wrq->u, NULL);
-            break;
-        case SIOCGIWRTS:  // get RTS/CTS threshold (bytes)
-        {
-        	struct iw_param *rts=&wrq->u.rts;
-        	rt_ioctl_giwrts(net_dev, NULL, rts, NULL);
-			break;
-		}
-        case SIOCSIWRTS:  //set RTS/CTS threshold (bytes)
-        {
-        	struct iw_param *rts=&wrq->u.rts;
-        	rt_ioctl_siwrts(net_dev, NULL, rts, NULL);
-			break;
-		}
-        case SIOCGIWFRAG:  //get fragmentation thr (bytes)
-        {
-        	struct iw_param *frag=&wrq->u.frag;
-        	rt_ioctl_giwfrag(net_dev, NULL, frag, NULL);
-			break;
-		}
-        case SIOCSIWFRAG:  //set fragmentation thr (bytes)
-        {
-        	struct iw_param *frag=&wrq->u.frag;
-        	rt_ioctl_siwfrag(net_dev, NULL, frag, NULL);
-			break;
-		}
-        case SIOCGIWENCODE:  //get encoding token & mode
-        {
-        	struct iw_point *erq=&wrq->u.encoding;
-        	if(erq->pointer)
-        		rt_ioctl_giwencode(net_dev, NULL, erq, erq->pointer);
-			break;
-		}
-        case SIOCSIWENCODE:  //set encoding token & mode
-        {
-        	struct iw_point *erq=&wrq->u.encoding;
-        	if(erq->pointer)
-        		rt_ioctl_siwencode(net_dev, NULL, erq, erq->pointer);
-			break;
-		}
-		case SIOCGIWAP:     //get access point MAC addresses
-        {
-        	struct sockaddr *ap_addr=&wrq->u.ap_addr;
-        	rt_ioctl_giwap(net_dev, NULL, ap_addr, ap_addr->sa_data);
-			break;
-		}
-	    case SIOCSIWAP:  //set access point MAC addresses
-        {
-        	struct sockaddr *ap_addr=&wrq->u.ap_addr;
-        	rt_ioctl_siwap(net_dev, NULL, ap_addr, ap_addr->sa_data);
-			break;
-		}
-		case SIOCGIWMODE:   //get operation mode
-        {
-        	__u32 *mode=&wrq->u.mode;
-        	rt_ioctl_giwmode(net_dev, NULL, mode, NULL);
-			break;
-		}
-		case SIOCSIWMODE:   //set operation mode
-        {
-        	__u32 *mode=&wrq->u.mode;
-        	rt_ioctl_siwmode(net_dev, NULL, mode, NULL);
-			break;
-		}
-		case SIOCGIWSENS:   //get sensitivity (dBm)
-		case SIOCSIWSENS:	//set sensitivity (dBm)
-		case SIOCGIWPOWER:  //get Power Management settings
-		case SIOCSIWPOWER:  //set Power Management settings
-		case SIOCGIWTXPOW:  //get transmit power (dBm)
-		case SIOCSIWTXPOW:  //set transmit power (dBm)
-		case SIOCGIWRANGE:	//Get range of parameters
-		case SIOCGIWRETRY:	//get retry limits and lifetime
-		case SIOCSIWRETRY:	//set retry limits and lifetime
-			Status = -EOPNOTSUPP;
-			break;
-		case RT_PRIV_IOCTL:
-        case RT_PRIV_IOCTL_EXT:
-			subcmd = wrq->u.data.flags;
-			if( subcmd & OID_GET_SET_TOGGLE)
-				Status = RTMPSetInformation(pAd, rq, subcmd);
-			else
-				Status = RTMPQueryInformation(pAd, rq, subcmd);
-			break;
-		case SIOCGIWPRIV:
-			if (wrq->u.data.pointer)
-			{
-				if ( access_ok(VERIFY_WRITE, wrq->u.data.pointer, sizeof(privtab)) != TRUE)
-					break;
-				wrq->u.data.length = sizeof(privtab) / sizeof(privtab[0]);
-				if (copy_to_user(wrq->u.data.pointer, privtab, sizeof(privtab)))
-					Status = -EFAULT;
-			}
-			break;
-		case RTPRIV_IOCTL_SET:
-			if(access_ok(VERIFY_READ, wrq->u.data.pointer, wrq->u.data.length) != TRUE)
-				break;
-			rt_ioctl_setparam(net_dev, NULL, NULL, wrq->u.data.pointer);
-			break;
-		case RTPRIV_IOCTL_GSITESURVEY:
-			RTMPIoctlGetSiteSurvey(pAd, wrq);
-		    break;
-#ifdef DBG
-		case RTPRIV_IOCTL_MAC:
-			RTMPIoctlMAC(pAd, wrq);
-			break;
-		case RTPRIV_IOCTL_E2P:
-			RTMPIoctlE2PROM(pAd, wrq);
-			break;
-#ifdef RT30xx
-		case RTPRIV_IOCTL_RF:
-			RTMPIoctlRF(pAd, wrq);
-			break;
-#endif // RT30xx //
-#endif // DBG //
-        case SIOCETHTOOL:
-                break;
-		default:
-			DBGPRINT(RT_DEBUG_ERROR, ("IOCTL::unknown IOCTL's cmd = 0x%08x\n", cmd));
-			Status = -EOPNOTSUPP;
-			break;
-	}
-
-    if(StateMachineTouched) // Upper layer sent a MLME-related operations
-    	RT28XX_MLME_HANDLER(pAd);
-
-	return Status;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set SSID
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_SSID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    NDIS_802_11_SSID                    Ssid, *pSsid=NULL;
-    BOOLEAN                             StateMachineTouched = FALSE;
-    int                                 success = TRUE;
-
-    if( strlen(arg) <= MAX_LEN_OF_SSID)
-    {
-        NdisZeroMemory(&Ssid, sizeof(NDIS_802_11_SSID));
-        if (strlen(arg) != 0)
-        {
-            NdisMoveMemory(Ssid.Ssid, arg, strlen(arg));
-            Ssid.SsidLength = strlen(arg);
-        }
-        else   //ANY ssid
-        {
-            Ssid.SsidLength = 0;
-		    memcpy(Ssid.Ssid, "", 0);
-			pAdapter->StaCfg.BssType = BSS_INFRA;
-			pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-	        pAdapter->StaCfg.WepStatus  = Ndis802_11EncryptionDisabled;
-		}
-        pSsid = &Ssid;
-
-        if (pAdapter->Mlme.CntlMachine.CurrState != CNTL_IDLE)
-        {
-            RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-            DBGPRINT(RT_DEBUG_TRACE, ("!!! MLME busy, reset MLME state machine !!!\n"));
-        }
-
-        pAdapter->MlmeAux.CurrReqIsFromNdis = TRUE;
-        pAdapter->StaCfg.bScanReqIsFromWebUI = FALSE;
-		pAdapter->bConfigChanged = TRUE;
-
-        MlmeEnqueue(pAdapter,
-                    MLME_CNTL_STATE_MACHINE,
-                    OID_802_11_SSID,
-                    sizeof(NDIS_802_11_SSID),
-                    (VOID *)pSsid);
-
-        StateMachineTouched = TRUE;
-        DBGPRINT(RT_DEBUG_TRACE, ("Set_SSID_Proc::(Len=%d,Ssid=%s)\n", Ssid.SsidLength, Ssid.Ssid));
-    }
-    else
-        success = FALSE;
-
-    if (StateMachineTouched) // Upper layer sent a MLME-related operations
-    	RT28XX_MLME_HANDLER(pAdapter);
-
-    return success;
-}
-
-#ifdef WMM_SUPPORT
-/*
-    ==========================================================================
-    Description:
-        Set WmmCapable Enable or Disable
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT	Set_WmmCapable_Proc(
-	IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-	BOOLEAN	bWmmCapable;
-
-	bWmmCapable = simple_strtol(arg, 0, 10);
-
-	if ((bWmmCapable == 1)
-#ifdef RT2870
-		&& (pAd->NumberOfPipes >= 5)
-#endif // RT2870 //
-		)
-		pAd->CommonCfg.bWmmCapable = TRUE;
-	else if (bWmmCapable == 0)
-		pAd->CommonCfg.bWmmCapable = FALSE;
-	else
-		return FALSE;  //Invalid argument
-
-	DBGPRINT(RT_DEBUG_TRACE, ("Set_WmmCapable_Proc::(bWmmCapable=%d)\n",
-		pAd->CommonCfg.bWmmCapable));
-
-	return TRUE;
-}
-#endif // WMM_SUPPORT //
-
-/*
-    ==========================================================================
-    Description:
-        Set Network Type(Infrastructure/Adhoc mode)
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_NetworkType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    UINT32	Value = 0;
-
-    if (strcmp(arg, "Adhoc") == 0)
-	{
-		if (pAdapter->StaCfg.BssType != BSS_ADHOC)
-		{
-			// Config has changed
-			pAdapter->bConfigChanged = TRUE;
-            if (MONITOR_ON(pAdapter))
-            {
-                RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, STANORMAL);
-                RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-				Value &= (~0x80);
-				RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-                OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-                pAdapter->StaCfg.bAutoReconnect = TRUE;
-                LinkDown(pAdapter, FALSE);
-            }
-			if (INFRA_ON(pAdapter))
-			{
-				//BOOLEAN Cancelled;
-				// Set the AutoReconnectSsid to prevent it reconnect to old SSID
-				// Since calling this indicate user don't want to connect to that SSID anymore.
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-				NdisZeroMemory(pAdapter->MlmeAux.AutoReconnectSsid, pAdapter->MlmeAux.AutoReconnectSsidLen);
-
-				LinkDown(pAdapter, FALSE);
-
-				DBGPRINT(RT_DEBUG_TRACE, ("NDIS_STATUS_MEDIA_DISCONNECT Event BB!\n"));
-			}
-		}
-		pAdapter->StaCfg.BssType = BSS_ADHOC;
-        pAdapter->net_dev->type = pAdapter->StaCfg.OriDevType;
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(AD-HOC)\n"));
-	}
-    else if (strcmp(arg, "Infra") == 0)
-	{
-		if (pAdapter->StaCfg.BssType != BSS_INFRA)
-		{
-			// Config has changed
-			pAdapter->bConfigChanged = TRUE;
-            if (MONITOR_ON(pAdapter))
-            {
-                RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, STANORMAL);
-                RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-				Value &= (~0x80);
-				RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-                OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-                pAdapter->StaCfg.bAutoReconnect = TRUE;
-                LinkDown(pAdapter, FALSE);
-            }
-			if (ADHOC_ON(pAdapter))
-			{
-				// Set the AutoReconnectSsid to prevent it reconnect to old SSID
-				// Since calling this indicate user don't want to connect to that SSID anymore.
-				pAdapter->MlmeAux.AutoReconnectSsidLen= 32;
-				NdisZeroMemory(pAdapter->MlmeAux.AutoReconnectSsid, pAdapter->MlmeAux.AutoReconnectSsidLen);
-
-				LinkDown(pAdapter, FALSE);
-			}
-		}
-		pAdapter->StaCfg.BssType = BSS_INFRA;
-        pAdapter->net_dev->type = pAdapter->StaCfg.OriDevType;
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(INFRA)\n"));
-
-        pAdapter->StaCfg.BssType = BSS_INFRA;
-	}
-    else if (strcmp(arg, "Monitor") == 0)
-    {
-		UCHAR	bbpValue = 0;
-		BCN_TIME_CFG_STRUC csr;
-		OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_INFRA_ON);
-        OPSTATUS_CLEAR_FLAG(pAdapter, fOP_STATUS_ADHOC_ON);
-		OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_MEDIA_STATE_CONNECTED);
-		// disable all periodic state machine
-		pAdapter->StaCfg.bAutoReconnect = FALSE;
-		// reset all mlme state machine
-		RT28XX_MLME_RESET_STATE_MACHINE(pAdapter);
-		DBGPRINT(RT_DEBUG_TRACE, ("fOP_STATUS_MEDIA_STATE_CONNECTED \n"));
-        if (pAdapter->CommonCfg.CentralChannel == 0)
-        {
-#ifdef DOT11_N_SUPPORT
-            if (pAdapter->CommonCfg.PhyMode == PHY_11AN_MIXED)
-                pAdapter->CommonCfg.CentralChannel = 36;
-            else
-#endif // DOT11_N_SUPPORT //
-                pAdapter->CommonCfg.CentralChannel = 6;
-        }
-#ifdef DOT11_N_SUPPORT
-        else
-            N_ChannelCheck(pAdapter);
-#endif // DOT11_N_SUPPORT //
-
-#ifdef DOT11_N_SUPPORT
-	if (pAdapter->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-            pAdapter->CommonCfg.RegTransmitSetting.field.BW == BW_40 &&
-            pAdapter->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_ABOVE)
-		{
-			// 40MHz ,control channel at lower
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			bbpValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_40;
-			//  RX : control channel at lower
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R3, &bbpValue);
-			bbpValue &= (~0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R3, bbpValue);
-
-			RTMP_IO_READ32(pAdapter, TX_BAND_CFG, &Value);
-			Value &= 0xfffffffe;
-			RTMP_IO_WRITE32(pAdapter, TX_BAND_CFG, Value);
-			pAdapter->CommonCfg.CentralChannel = pAdapter->CommonCfg.Channel + 2;
-            AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.CentralChannel, FALSE);
-		    AsicLockChannel(pAdapter, pAdapter->CommonCfg.CentralChannel);
-            DBGPRINT(RT_DEBUG_TRACE, ("BW_40 ,control_channel(%d), CentralChannel(%d) \n",
-                                       pAdapter->CommonCfg.Channel,
-                                       pAdapter->CommonCfg.CentralChannel));
-		}
-		else if (pAdapter->CommonCfg.PhyMode >= PHY_11ABGN_MIXED &&
-                 pAdapter->CommonCfg.RegTransmitSetting.field.BW == BW_40 &&
-                 pAdapter->CommonCfg.RegTransmitSetting.field.EXTCHA == EXTCHA_BELOW)
-		{
-			// 40MHz ,control channel at upper
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			bbpValue |= 0x10;
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_40;
-			RTMP_IO_READ32(pAdapter, TX_BAND_CFG, &Value);
-			Value |= 0x1;
-			RTMP_IO_WRITE32(pAdapter, TX_BAND_CFG, Value);
-
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R3, &bbpValue);
-			bbpValue |= (0x20);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R3, bbpValue);
-			pAdapter->CommonCfg.CentralChannel = pAdapter->CommonCfg.Channel - 2;
-            AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.CentralChannel, FALSE);
-		    AsicLockChannel(pAdapter, pAdapter->CommonCfg.CentralChannel);
-            DBGPRINT(RT_DEBUG_TRACE, ("BW_40 ,control_channel(%d), CentralChannel(%d) \n",
-                                       pAdapter->CommonCfg.Channel,
-                                       pAdapter->CommonCfg.CentralChannel));
-		}
-		else
-#endif // DOT11_N_SUPPORT //
-		{
-			// 20MHz
-			RTMP_BBP_IO_READ8_BY_REG_ID(pAdapter, BBP_R4, &bbpValue);
-			bbpValue &= (~0x18);
-			RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R4, bbpValue);
-			pAdapter->CommonCfg.BBPCurrentBW = BW_20;
-			AsicSwitchChannel(pAdapter, pAdapter->CommonCfg.Channel, FALSE);
-			AsicLockChannel(pAdapter, pAdapter->CommonCfg.Channel);
-			DBGPRINT(RT_DEBUG_TRACE, ("BW_20, Channel(%d)\n", pAdapter->CommonCfg.Channel));
-		}
-		// Enable Rx with promiscuous reception
-		RTMP_IO_WRITE32(pAdapter, RX_FILTR_CFG, 0x3);
-		// ASIC supporsts sniffer function with replacing RSSI with timestamp.
-		//RTMP_IO_READ32(pAdapter, MAC_SYS_CTRL, &Value);
-		//Value |= (0x80);
-		//RTMP_IO_WRITE32(pAdapter, MAC_SYS_CTRL, Value);
-		// disable sync
-		RTMP_IO_READ32(pAdapter, BCN_TIME_CFG, &csr.word);
-		csr.field.bBeaconGen = 0;
-		csr.field.bTBTTEnable = 0;
-		csr.field.TsfSyncMode = 0;
-		RTMP_IO_WRITE32(pAdapter, BCN_TIME_CFG, csr.word);
-
-		pAdapter->StaCfg.BssType = BSS_MONITOR;
-        pAdapter->net_dev->type = ARPHRD_IEEE80211_PRISM; //ARPHRD_IEEE80211; // IEEE80211
-		DBGPRINT(RT_DEBUG_TRACE, ("===>Set_NetworkType_Proc::(MONITOR)\n"));
-    }
-
-    // Reset Ralink supplicant to not use, it will be set to start when UI set PMK key
-    pAdapter->StaCfg.WpaState = SS_NOTUSE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_NetworkType_Proc::(NetworkType=%d)\n", pAdapter->StaCfg.BssType));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Authentication mode
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_AuthMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if ((strcmp(arg, "WEPAUTO") == 0) || (strcmp(arg, "wepauto") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeAutoSwitch;
-    else if ((strcmp(arg, "OPEN") == 0) || (strcmp(arg, "open") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
-    else if ((strcmp(arg, "SHARED") == 0) || (strcmp(arg, "shared") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeShared;
-    else if ((strcmp(arg, "WPAPSK") == 0) || (strcmp(arg, "wpapsk") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPAPSK;
-    else if ((strcmp(arg, "WPANONE") == 0) || (strcmp(arg, "wpanone") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPANone;
-    else if ((strcmp(arg, "WPA2PSK") == 0) || (strcmp(arg, "wpa2psk") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2PSK;
-#ifdef WPA_SUPPLICANT_SUPPORT
-    else if ((strcmp(arg, "WPA") == 0) || (strcmp(arg, "wpa") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA;
-    else if ((strcmp(arg, "WPA2") == 0) || (strcmp(arg, "wpa2") == 0))
-        pAdapter->StaCfg.AuthMode = Ndis802_11AuthModeWPA2;
-#endif // WPA_SUPPLICANT_SUPPORT //
-    else
-        return FALSE;
-
-    pAdapter->StaCfg.PortSecured = WPA_802_1X_PORT_NOT_SECURED;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_AuthMode_Proc::(AuthMode=%d)\n", pAdapter->StaCfg.AuthMode));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Encryption Type
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_EncrypType_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if ((strcmp(arg, "NONE") == 0) || (strcmp(arg, "none") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11WEPDisabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11WEPDisabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11WEPDisabled;
-    }
-    else if ((strcmp(arg, "WEP") == 0) || (strcmp(arg, "wep") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11WEPEnabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11WEPEnabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11WEPEnabled;
-    }
-    else if ((strcmp(arg, "TKIP") == 0) || (strcmp(arg, "tkip") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11Encryption2Enabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11Encryption2Enabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11Encryption2Enabled;
-    }
-    else if ((strcmp(arg, "AES") == 0) || (strcmp(arg, "aes") == 0))
-    {
-        if (pAdapter->StaCfg.AuthMode < Ndis802_11AuthModeWPA)
-            return TRUE;    // do nothing
-
-        pAdapter->StaCfg.WepStatus     = Ndis802_11Encryption3Enabled;
-        pAdapter->StaCfg.PairCipher    = Ndis802_11Encryption3Enabled;
-	    pAdapter->StaCfg.GroupCipher   = Ndis802_11Encryption3Enabled;
-    }
-    else
-        return FALSE;
-
-    pAdapter->StaCfg.OrigWepStatus = pAdapter->StaCfg.WepStatus;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_EncrypType_Proc::(EncrypType=%d)\n", pAdapter->StaCfg.WepStatus));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Default Key ID
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_DefaultKeyID_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    ULONG                               KeyIdx;
-
-    KeyIdx = simple_strtol(arg, 0, 10);
-    if((KeyIdx >= 1 ) && (KeyIdx <= 4))
-        pAdapter->StaCfg.DefaultKeyId = (UCHAR) (KeyIdx - 1 );
-    else
-        return FALSE;  //Invalid argument
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_DefaultKeyID_Proc::(DefaultKeyID=%d)\n", pAdapter->StaCfg.DefaultKeyId));
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY1
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key1_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][0].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][0].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][0].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][0].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][0].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::(Key1=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key1_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-
-    pAdapter->SharedKey[BSS0][0].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              0,
-                              pAdapter->SharedKey[BSS0][0].CipherAlg,
-                              pAdapter->SharedKey[BSS0][0].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-
-    Description:
-        Set WEP KEY2
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key2_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][1].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][1].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][1].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][1].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][1].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::(Key2=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key2_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][1].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              1,
-                              pAdapter->SharedKey[BSS0][1].CipherAlg,
-                              pAdapter->SharedKey[BSS0][1].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY3
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key3_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][2].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Ascii)\n", arg));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][2].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Hex)\n", arg));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][2].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Ascii)\n", arg));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][2].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][2].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::(Key3=%s and type=Hex)\n", arg));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key3_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][2].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              2,
-                              pAdapter->SharedKey[BSS0][2].CipherAlg,
-                              pAdapter->SharedKey[BSS0][2].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-/*
-    ==========================================================================
-    Description:
-        Set WEP KEY4
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Key4_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    int                                 KeyLen;
-    int                                 i;
-    UCHAR                               CipherAlg=CIPHER_WEP64;
-
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        return TRUE;    // do nothing
-
-    KeyLen = strlen(arg);
-
-    switch (KeyLen)
-    {
-        case 5: //wep 40 Ascii type
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][3].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 10: //wep 40 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][3].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP64;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Hex"));
-            break;
-        case 13: //wep 104 Ascii type
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen;
-            memcpy(pAdapter->SharedKey[BSS0][3].Key, arg, KeyLen);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Ascii"));
-            break;
-        case 26: //wep 104 Hex type
-            for(i=0; i < KeyLen; i++)
-            {
-                if( !isxdigit(*(arg+i)) )
-                    return FALSE;  //Not Hex value;
-            }
-            pAdapter->SharedKey[BSS0][3].KeyLen = KeyLen / 2 ;
-            AtoH(arg, pAdapter->SharedKey[BSS0][3].Key, KeyLen / 2);
-            CipherAlg = CIPHER_WEP128;
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::(Key4=%s and type=%s)\n", arg, "Hex"));
-            break;
-        default: //Invalid argument
-            DBGPRINT(RT_DEBUG_TRACE, ("Set_Key4_Proc::Invalid argument (=%s)\n", arg));
-            return FALSE;
-    }
-    pAdapter->SharedKey[BSS0][3].CipherAlg = CipherAlg;
-
-    // Set keys (into ASIC)
-    if (pAdapter->StaCfg.AuthMode >= Ndis802_11AuthModeWPA)
-        ;   // not support
-    else    // Old WEP stuff
-    {
-        AsicAddSharedKeyEntry(pAdapter,
-                              0,
-                              3,
-                              pAdapter->SharedKey[BSS0][3].CipherAlg,
-                              pAdapter->SharedKey[BSS0][3].Key,
-                              NULL,
-                              NULL);
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set WPA PSK key
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_WPAPSK_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    UCHAR                   keyMaterial[40];
-
-    if ((pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPAPSK) &&
-        (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPA2PSK) &&
-	    (pAdapter->StaCfg.AuthMode != Ndis802_11AuthModeWPANone)
-		)
-        return TRUE;    // do nothing
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_WPAPSK_Proc::(WPAPSK=%s)\n", arg));
-
-    NdisZeroMemory(keyMaterial, 40);
-
-    if ((strlen(arg) < 8) || (strlen(arg) > 64))
-    {
-        DBGPRINT(RT_DEBUG_TRACE, ("Set failed!!(WPAPSK=%s), WPAPSK key-string required 8 ~ 64 characters \n", arg));
-        return FALSE;
-    }
-
-    if (strlen(arg) == 64)
-    {
-        AtoH(arg, keyMaterial, 32);
-        NdisMoveMemory(pAdapter->StaCfg.PMK, keyMaterial, 32);
-
-    }
-    else
-    {
-        PasswordHash((char *)arg, pAdapter->MlmeAux.Ssid, pAdapter->MlmeAux.SsidLen, keyMaterial);
-        NdisMoveMemory(pAdapter->StaCfg.PMK, keyMaterial, 32);
-    }
-
-
-
-    if(pAdapter->StaCfg.BssType == BSS_ADHOC &&
-       pAdapter->StaCfg.AuthMode == Ndis802_11AuthModeWPANone)
-    {
-         pAdapter->StaCfg.WpaState = SS_NOTUSE;
-    }
-    else
-    {
-        // Start STA supplicant state machine
-        pAdapter->StaCfg.WpaState = SS_START;
-    }
-
-    return TRUE;
-}
-
-/*
-    ==========================================================================
-    Description:
-        Set Power Saving mode
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_PSMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if (pAdapter->StaCfg.BssType == BSS_INFRA)
-    {
-        if ((strcmp(arg, "Max_PSP") == 0) ||
-			(strcmp(arg, "max_psp") == 0) ||
-			(strcmp(arg, "MAX_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeMAX_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeMAX_PSP;
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            pAdapter->StaCfg.DefaultListenCount = 5;
-
-        }
-        else if ((strcmp(arg, "Fast_PSP") == 0) ||
-				 (strcmp(arg, "fast_psp") == 0) ||
-                 (strcmp(arg, "FAST_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeFast_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeFast_PSP;
-            pAdapter->StaCfg.DefaultListenCount = 3;
-        }
-        else if ((strcmp(arg, "Legacy_PSP") == 0) ||
-                 (strcmp(arg, "legacy_psp") == 0) ||
-                 (strcmp(arg, "LEGACY_PSP") == 0))
-        {
-            // do NOT turn on PSM bit here, wait until MlmeCheckForPsmChange()
-            // to exclude certain situations.
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeLegacy_PSP;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeLegacy_PSP;
-            pAdapter->StaCfg.DefaultListenCount = 3;
-        }
-        else
-        {
-            //Default Ndis802_11PowerModeCAM
-            // clear PSM bit immediately
-            MlmeSetPsmBit(pAdapter, PWR_ACTIVE);
-            OPSTATUS_SET_FLAG(pAdapter, fOP_STATUS_RECEIVE_DTIM);
-            if (pAdapter->StaCfg.bWindowsACCAMEnable == FALSE)
-                pAdapter->StaCfg.WindowsPowerMode = Ndis802_11PowerModeCAM;
-            pAdapter->StaCfg.WindowsBatteryPowerMode = Ndis802_11PowerModeCAM;
-        }
-
-        DBGPRINT(RT_DEBUG_TRACE, ("Set_PSMode_Proc::(PSMode=%ld)\n", pAdapter->StaCfg.WindowsPowerMode));
-    }
-    else
-        return FALSE;
-
-
-    return TRUE;
-}
-
-#ifdef WPA_SUPPLICANT_SUPPORT
-/*
-    ==========================================================================
-    Description:
-        Set WpaSupport flag.
-    Value:
-        0: Driver ignore wpa_supplicant.
-        1: wpa_supplicant initiates scanning and AP selection.
-        2: driver takes care of scanning, AP selection, and IEEE 802.11 association parameters.
-    Return:
-        TRUE if all parameters are OK, FALSE otherwise
-    ==========================================================================
-*/
-INT Set_Wpa_Support(
-    IN	PRTMP_ADAPTER	pAd,
-	IN	PUCHAR			arg)
-{
-
-    if ( simple_strtol(arg, 0, 10) == 0)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_DISABLE;
-    else if ( simple_strtol(arg, 0, 10) == 1)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_ENABLE;
-    else if ( simple_strtol(arg, 0, 10) == 2)
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_ENABLE_WITH_WEB_UI;
-    else
-        pAd->StaCfg.WpaSupplicantUP = WPA_SUPPLICANT_DISABLE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_Wpa_Support::(WpaSupplicantUP=%d)\n", pAd->StaCfg.WpaSupplicantUP));
-
-    return TRUE;
-}
-#endif // WPA_SUPPLICANT_SUPPORT //
-
-#ifdef DBG
-/*
-    ==========================================================================
-    Description:
-        Read / Write MAC
-    Arguments:
-        pAdapter                    Pointer to our adapter
-        wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-               1.) iwpriv ra0 mac 0        ==> read MAC where Addr=0x0
-               2.) iwpriv ra0 mac 0=12     ==> write MAC where Addr=0x0, value=12
-    ==========================================================================
-*/
-VOID RTMPIoctlMAC(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	CHAR				*this_char;
-	CHAR				*value;
-	INT					j = 0, k = 0;
-	CHAR				msg[1024];
-	CHAR				arg[255];
-	ULONG				macAddr = 0;
-	UCHAR				temp[16], temp2[16];
-	UINT32				macValue = 0;
-	INT					Status;
-	BOOLEAN				bIsPrintAllMAC = FALSE;
-
-
-	memset(msg, 0x00, 1024);
-	if (wrq->u.data.length > 1) //No parameters.
-	{
-	    Status = copy_from_user(arg, wrq->u.data.pointer, (wrq->u.data.length > 255) ? 255 : wrq->u.data.length);
-		sprintf(msg, "\n");
-
-		//Parsing Read or Write
-	    this_char = arg;
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-			// Sanity check
-			if(strlen(this_char) > 4)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			// Mac Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			if(strlen(this_char) == 4)
-			{
-				AtoH(this_char, temp, 2);
-				macAddr = *temp*256 + temp[1];
-				if (macAddr < 0xFFFF)
-				{
-					RTMP_IO_READ32(pAdapter, macAddr, &macValue);
-					DBGPRINT(RT_DEBUG_TRACE, ("MacAddr=%lx, MacValue=%x\n", macAddr, macValue));
-					sprintf(msg+strlen(msg), "[0x%08lX]:%08X  ", macAddr , macValue);
-				}
-				else
-				{//Invalid parametes, so default printk all mac
-					bIsPrintAllMAC = TRUE;
-					goto next;
-				}
-			}
-		}
-		else
-		{ //Write
-			memcpy(&temp2, value, strlen(value));
-			temp2[strlen(value)] = '\0';
-
-			// Sanity check
-			if((strlen(this_char) > 4) || strlen(temp2) > 8)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			j = strlen(temp2);
-			while(j-- > 0)
-			{
-				if(temp2[j] > 'f' || temp2[j] < '0')
-					return;
-			}
-
-			//MAC Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			//MAC value
-			k = j = strlen(temp2);
-			while(j-- > 0)
-			{
-				temp2[8-k+j] = temp2[j];
-			}
-
-			while(k < 8)
-				temp2[7-k++]='0';
-			temp2[8]='\0';
-
-			{
-				AtoH(this_char, temp, 2);
-				macAddr = *temp*256 + temp[1];
-
-				AtoH(temp2, temp, 4);
-				macValue = *temp*256*256*256 + temp[1]*256*256 + temp[2]*256 + temp[3];
-
-				// debug mode
-				if (macAddr == (HW_DEBUG_SETTING_BASE + 4))
-				{
-					// 0x2bf4: byte0 non-zero: enable R17 tuning, 0: disable R17 tuning
-                    if (macValue & 0x000000ff)
-                    {
-                        pAdapter->BbpTuning.bEnable = TRUE;
-                        DBGPRINT(RT_DEBUG_TRACE,("turn on R17 tuning\n"));
-                    }
-                    else
-                    {
-                        UCHAR R66;
-                        pAdapter->BbpTuning.bEnable = FALSE;
-                        R66 = 0x26 + GET_LNA_GAIN(pAdapter);
-#ifdef RALINK_ATE
-						if (ATE_ON(pAdapter))
-						{
-							ATE_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R66, (0x26 + GET_LNA_GAIN(pAdapter)));
-						}
-						else
-#endif // RALINK_ATE //
-						RTMP_BBP_IO_WRITE8_BY_REG_ID(pAdapter, BBP_R66, (0x26 + GET_LNA_GAIN(pAdapter)));
-                        DBGPRINT(RT_DEBUG_TRACE,("turn off R17 tuning, restore to 0x%02x\n", R66));
-                    }
-					return;
-				}
-
-				DBGPRINT(RT_DEBUG_TRACE, ("MacAddr=%02lx, MacValue=0x%x\n", macAddr, macValue));
-
-				RTMP_IO_WRITE32(pAdapter, macAddr, macValue);
-				sprintf(msg+strlen(msg), "[0x%08lX]:%08X  ", macAddr, macValue);
-			}
-		}
-	}
-	else
-		bIsPrintAllMAC = TRUE;
-next:
-	if (bIsPrintAllMAC)
-	{
-		struct file		*file_w;
-		PCHAR			fileName = "MacDump.txt";
-		mm_segment_t	orig_fs;
-
-		orig_fs = get_fs();
-		set_fs(KERNEL_DS);
-
-		// open file
-		file_w = filp_open(fileName, O_WRONLY|O_CREAT, 0);
-		if (IS_ERR(file_w))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("-->2) %s: Error %ld opening %s\n", __FUNCTION__, -PTR_ERR(file_w), fileName));
-		}
-		else
-		{
-			if (file_w->f_op && file_w->f_op->write)
-			{
-				file_w->f_pos = 0;
-				macAddr = 0x1000;
-
-				while (macAddr <= 0x1800)
-				{
-					RTMP_IO_READ32(pAdapter, macAddr, &macValue);
-					sprintf(msg, "%08lx = %08X\n", macAddr, macValue);
-
-					// write data to file
-					file_w->f_op->write(file_w, msg, strlen(msg), &file_w->f_pos);
-
-					printk("%s", msg);
-					macAddr += 4;
-				}
-				sprintf(msg, "\nDump all MAC values to %s\n", fileName);
-			}
-			filp_close(file_w, NULL);
-		}
-		set_fs(orig_fs);
-	}
-	if(strlen(msg) == 1)
-		sprintf(msg+strlen(msg), "===>Error command format!");
-
-	// Copy the information into the user buffer
-	wrq->u.data.length = strlen(msg);
-	Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==RTMPIoctlMAC\n\n"));
-}
-
-/*
-    ==========================================================================
-    Description:
-        Read / Write E2PROM
-    Arguments:
-        pAdapter                    Pointer to our adapter
-        wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-               1.) iwpriv ra0 e2p 0     	==> read E2PROM where Addr=0x0
-               2.) iwpriv ra0 e2p 0=1234    ==> write E2PROM where Addr=0x0, value=1234
-    ==========================================================================
-*/
-VOID RTMPIoctlE2PROM(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	CHAR				*this_char;
-	CHAR				*value;
-	INT					j = 0, k = 0;
-	CHAR				msg[1024];
-	CHAR				arg[255];
-	USHORT				eepAddr = 0;
-	UCHAR				temp[16], temp2[16];
-	USHORT				eepValue;
-	int					Status;
-	BOOLEAN				bIsPrintAllE2P = FALSE;
-
-
-	memset(msg, 0x00, 1024);
-	if (wrq->u.data.length > 1) //No parameters.
-	{
-	    Status = copy_from_user(arg, wrq->u.data.pointer, (wrq->u.data.length > 255) ? 255 : wrq->u.data.length);
-		sprintf(msg, "\n");
-
-	    //Parsing Read or Write
-		this_char = arg;
-
-
-		if (!*this_char)
-			goto next;
-
-		if ((value = rtstrchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-
-			// Sanity check
-			if(strlen(this_char) > 4)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-
-			// E2PROM addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			if(strlen(this_char) == 4)
-			{
-				AtoH(this_char, temp, 2);
-				eepAddr = *temp*256 + temp[1];
-				if (eepAddr < 0xFFFF)
-				{
-					RT28xx_EEPROM_READ16(pAdapter, eepAddr, eepValue);
-					sprintf(msg+strlen(msg), "[0x%04X]:0x%04X  ", eepAddr , eepValue);
-				}
-				else
-				{//Invalid parametes, so default printk all bbp
-					bIsPrintAllE2P = TRUE;
-					goto next;
-				}
-			}
-		}
-		else
-		{ //Write
-			memcpy(&temp2, value, strlen(value));
-			temp2[strlen(value)] = '\0';
-
-			// Sanity check
-			if((strlen(this_char) > 4) || strlen(temp2) > 8)
-				goto next;
-
-			j = strlen(this_char);
-			while(j-- > 0)
-			{
-				if(this_char[j] > 'f' || this_char[j] < '0')
-					return;
-			}
-			j = strlen(temp2);
-			while(j-- > 0)
-			{
-				if(temp2[j] > 'f' || temp2[j] < '0')
-					return;
-			}
-
-			//MAC Addr
-			k = j = strlen(this_char);
-			while(j-- > 0)
-			{
-				this_char[4-k+j] = this_char[j];
-			}
-
-			while(k < 4)
-				this_char[3-k++]='0';
-			this_char[4]='\0';
-
-			//MAC value
-			k = j = strlen(temp2);
-			while(j-- > 0)
-			{
-				temp2[4-k+j] = temp2[j];
-			}
-
-			while(k < 4)
-				temp2[3-k++]='0';
-			temp2[4]='\0';
-
-			AtoH(this_char, temp, 2);
-			eepAddr = *temp*256 + temp[1];
-
-			AtoH(temp2, temp, 2);
-			eepValue = *temp*256 + temp[1];
-
-			RT28xx_EEPROM_WRITE16(pAdapter, eepAddr, eepValue);
-			sprintf(msg+strlen(msg), "[0x%02X]:%02X  ", eepAddr, eepValue);
-		}
-	}
-	else
-		bIsPrintAllE2P = TRUE;
-next:
-	if (bIsPrintAllE2P)
-	{
-		struct file		*file_w;
-		PCHAR			fileName = "EEPROMDump.txt";
-		mm_segment_t	orig_fs;
-
-		orig_fs = get_fs();
-		set_fs(KERNEL_DS);
-
-		// open file
-		file_w = filp_open(fileName, O_WRONLY|O_CREAT, 0);
-		if (IS_ERR(file_w))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("-->2) %s: Error %ld opening %s\n", __FUNCTION__, -PTR_ERR(file_w), fileName));
-		}
-		else
-		{
-			if (file_w->f_op && file_w->f_op->write)
-			{
-				file_w->f_pos = 0;
-				eepAddr = 0x00;
-
-				while (eepAddr <= 0xFE)
-				{
-					RT28xx_EEPROM_READ16(pAdapter, eepAddr, eepValue);
-					sprintf(msg, "%08x = %04x\n", eepAddr , eepValue);
-
-					// write data to file
-					file_w->f_op->write(file_w, msg, strlen(msg), &file_w->f_pos);
-
-					printk("%s", msg);
-					eepAddr += 2;
-				}
-				sprintf(msg, "\nDump all EEPROM values to %s\n", fileName);
-			}
-			filp_close(file_w, NULL);
-		}
-		set_fs(orig_fs);
-	}
-	if(strlen(msg) == 1)
-		sprintf(msg+strlen(msg), "===>Error command format!");
-
-
-	// Copy the information into the user buffer
-	wrq->u.data.length = strlen(msg);
-	Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==RTMPIoctlE2PROM\n"));
-}
-#ifdef RT30xx
-/*
-    ==========================================================================
-    Description:
-        Read / Write RF register
-Arguments:
-    pAdapter                    Pointer to our adapter
-    wrq                         Pointer to the ioctl argument
-
-    Return Value:
-        None
-
-    Note:
-        Usage:
-               1.) iwpriv ra0 rf                ==> read all RF registers
-               2.) iwpriv ra0 rf 1              ==> read RF where RegID=1
-               3.) iwpriv ra0 rf 1=10		    ==> write RF R1=0x10
-    ==========================================================================
-*/
-VOID RTMPIoctlRF(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	struct iwreq	*wrq)
-{
-	CHAR				*this_char;
-	CHAR				*value;
-	UCHAR				regRF = 0;
-	CHAR				msg[2048];
-	CHAR				arg[255];
-	INT					rfId;
-	LONG				rfValue;
-	int					Status;
-	BOOLEAN				bIsPrintAllRF = FALSE;
-
-
-	memset(msg, 0x00, 2048);
-	if (wrq->u.data.length > 1) //No parameters.
-	{
-	    Status = copy_from_user(arg, wrq->u.data.pointer, (wrq->u.data.length > 255) ? 255 : wrq->u.data.length);
-		sprintf(msg, "\n");
-
-	    //Parsing Read or Write
-		this_char = arg;
-		if (!*this_char)
-			goto next;
-
-		if ((value = strchr(this_char, '=')) != NULL)
-			*value++ = 0;
-
-		if (!value || !*value)
-		{ //Read
-			if (sscanf(this_char, "%d", &(rfId)) == 1)
-			{
-				if (rfId <= 31)
-				{
-					// In RT2860 ATE mode, we do not load 8051 firmware.
-                                            //We must access RF directly.
-                    // For RT2870 ATE mode, ATE_RF_IO_WRITE8(/READ8)_BY_REG_ID are redefined.
-#ifdef RALINK_ATE
-					if (ATE_ON(pAdapter))
-					{
-						ATE_RF_IO_READ8_BY_REG_ID(pAdapter, rfId, &regRF);
-					}
-					else
-#endif // RALINK_ATE //
-					// according to Andy, Gary, David require.
-					// the command rf shall read rf register directly for dubug.
-					// BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					RT30xxReadRFRegister(pAdapter, rfId, &regRF);
-
-					sprintf(msg+strlen(msg), "R%02d[0x%02x]:%02X  ", rfId, rfId*2, regRF);
-				}
-				else
-				{//Invalid parametes, so default printk all RF
-					bIsPrintAllRF = TRUE;
-					goto next;
-				}
-			}
-			else
-			{ //Invalid parametes, so default printk all RF
-				bIsPrintAllRF = TRUE;
-				goto next;
-			}
-		}
-		else
-		{ //Write
-			if ((sscanf(this_char, "%d", &(rfId)) == 1) && (sscanf(value, "%lx", &(rfValue)) == 1))
-			{
-				if (rfId <= 31)
-				{
-					// In RT2860 ATE mode, we do not load 8051 firmware.
-					// We should access RF registers directly.
-                    // For RT2870 ATE mode, ATE_RF_IO_WRITE8/READ8_BY_REG_ID are redefined.
-#ifdef RALINK_ATE
-						if (ATE_ON(pAdapter))
-						{
-							ATE_RF_IO_READ8_BY_REG_ID(pAdapter, rfId, &regRF);
-							ATE_RF_IO_WRITE8_BY_REG_ID(pAdapter, (UCHAR)rfId,(UCHAR) rfValue);
-							//Read it back for showing
-							ATE_RF_IO_READ8_BY_REG_ID(pAdapter, rfId, &regRF);
-							sprintf(msg+strlen(msg), "R%02d[0x%02X]:%02X\n", rfId, rfId*2, regRF);
-						}
-						else
-#endif // RALINK_ATE //
-						{
-							// according to Andy, Gary, David require.
-							// the command RF shall read/write RF register directly for dubug.
-							//BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-					                //BBP_IO_WRITE8_BY_REG_ID(pAdapter, (UCHAR)bbpId,(UCHAR) bbpValue);
-							RT30xxReadRFRegister(pAdapter, rfId, &regRF);
-							RT30xxWriteRFRegister(pAdapter, (UCHAR)rfId,(UCHAR) rfValue);
-					                //Read it back for showing
-							//BBP_IO_READ8_BY_REG_ID(pAdapter, bbpId, &regBBP);
-							RT30xxReadRFRegister(pAdapter, rfId, &regRF);
-					                sprintf(msg+strlen(msg), "R%02d[0x%02X]:%02X\n", rfId, rfId*2, regRF);
-				                }
-				}
-				else
-				{//Invalid parametes, so default printk all RF
-					bIsPrintAllRF = TRUE;
-				}
-			}
-			else
-			{ //Invalid parametes, so default printk all RF
-				bIsPrintAllRF = TRUE;
-			}
-		}
-	}
-	else
-		bIsPrintAllRF = TRUE;
-next:
-	if (bIsPrintAllRF)
-	{
-		memset(msg, 0x00, 2048);
-		sprintf(msg, "\n");
-		for (rfId = 0; rfId <= 31; rfId++)
-		{
-			// In RT2860 ATE mode, we do not load 8051 firmware.
-            // We should access RF registers directly.
-            // For RT2870 ATE mode, ATE_RF_IO_WRITE8/READ8_BY_REG_ID are redefined.
-#ifdef RALINK_ATE
-				if (ATE_ON(pAdapter))
-				{
-					ATE_RF_IO_READ8_BY_REG_ID(pAdapter, rfId, &regRF);
-				}
-				else
-#endif // RALINK_ATE //
-
-			// according to Andy, Gary, David require.
-			// the command RF shall read/write RF register directly for dubug.
-			RT30xxReadRFRegister(pAdapter, rfId, &regRF);
-			sprintf(msg+strlen(msg), "%03d = %02X\n", rfId, regRF);
-		}
-		// Copy the information into the user buffer
-		DBGPRINT(RT_DEBUG_TRACE, ("strlen(msg)=%d\n", (UINT32)strlen(msg)));
-		wrq->u.data.length = strlen(msg);
-		if (copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length))
-		{
-			DBGPRINT(RT_DEBUG_TRACE, ("%s: copy_to_user() fail\n", __FUNCTION__));
-		}
-	}
-	else
-	{
-		if(strlen(msg) == 1)
-			sprintf(msg+strlen(msg), "===>Error command format!");
-
-		DBGPRINT(RT_DEBUG_TRACE, ("copy to user [msg=%s]\n", msg));
-		// Copy the information into the user buffer
-		DBGPRINT(RT_DEBUG_TRACE, ("strlen(msg) =%d\n", (UINT32)strlen(msg)));
-
-		// Copy the information into the user buffer
-		wrq->u.data.length = strlen(msg);
-		Status = copy_to_user(wrq->u.data.pointer, msg, wrq->u.data.length);
-	}
-
-	DBGPRINT(RT_DEBUG_TRACE, ("<==RTMPIoctlRF\n\n"));
-}
-#endif // RT30xx //
-#endif // DBG //
-
-
-
-
-INT Set_TGnWifiTest_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAd->StaCfg.bTGnWifiTest = FALSE;
-    else
-        pAd->StaCfg.bTGnWifiTest = TRUE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IF Set_TGnWifiTest_Proc::(bTGnWifiTest=%d)\n", pAd->StaCfg.bTGnWifiTest));
-	return TRUE;
-}
-
-INT Set_LongRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg)
-{
-	TX_RTY_CFG_STRUC	tx_rty_cfg;
-	UCHAR				LongRetryLimit = (UCHAR)simple_strtol(arg, 0, 10);
-
-	RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-	tx_rty_cfg.field.LongRtyLimit = LongRetryLimit;
-	RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-	DBGPRINT(RT_DEBUG_TRACE, ("IF Set_LongRetryLimit_Proc::(tx_rty_cfg=0x%x)\n", tx_rty_cfg.word));
-	return TRUE;
-}
-
-INT Set_ShortRetryLimit_Proc(
-	IN	PRTMP_ADAPTER	pAdapter,
-	IN	PUCHAR			arg)
-{
-	TX_RTY_CFG_STRUC	tx_rty_cfg;
-	UCHAR				ShortRetryLimit = (UCHAR)simple_strtol(arg, 0, 10);
-
-	RTMP_IO_READ32(pAdapter, TX_RTY_CFG, &tx_rty_cfg.word);
-	tx_rty_cfg.field.ShortRtyLimit = ShortRetryLimit;
-	RTMP_IO_WRITE32(pAdapter, TX_RTY_CFG, tx_rty_cfg.word);
-	DBGPRINT(RT_DEBUG_TRACE, ("IF Set_ShortRetryLimit_Proc::(tx_rty_cfg=0x%x)\n", tx_rty_cfg.word));
-	return TRUE;
-}
-
-#ifdef EXT_BUILD_CHANNEL_LIST
-INT Set_Ieee80211dClientMode_Proc(
-    IN  PRTMP_ADAPTER   pAdapter,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_None;
-    else if (simple_strtol(arg, 0, 10) == 1)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_Flexible;
-    else if (simple_strtol(arg, 0, 10) == 2)
-        pAdapter->StaCfg.IEEE80211dClientMode = Rt802_11_D_Strict;
-    else
-        return FALSE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("Set_Ieee802dMode_Proc::(IEEEE0211dMode=%d)\n", pAdapter->StaCfg.IEEE80211dClientMode));
-    return TRUE;
-}
-#endif // EXT_BUILD_CHANNEL_LIST //
-
-#ifdef CARRIER_DETECTION_SUPPORT
-INT Set_CarrierDetect_Proc(
-    IN  PRTMP_ADAPTER   pAd,
-    IN  PUCHAR          arg)
-{
-    if (simple_strtol(arg, 0, 10) == 0)
-        pAd->CommonCfg.CarrierDetect.Enable = FALSE;
-    else
-        pAd->CommonCfg.CarrierDetect.Enable = TRUE;
-
-    DBGPRINT(RT_DEBUG_TRACE, ("IF Set_CarrierDetect_Proc::(CarrierDetect.Enable=%d)\n", pAd->CommonCfg.CarrierDetect.Enable));
-	return TRUE;
-}
-#endif // CARRIER_DETECTION_SUPPORT //
-
+#include "../rt2870/sta_ioctl.c"
diff --git a/drivers/staging/rt3070/wpa.h b/drivers/staging/rt3070/wpa.h
index 88c7c8b..94bb232 100644
--- a/drivers/staging/rt3070/wpa.h
+++ b/drivers/staging/rt3070/wpa.h
@@ -1,356 +1 @@
-/*
- *************************************************************************
- * Ralink Tech Inc.
- * 5F., No.36, Taiyuan St., Jhubei City,
- * Hsinchu County 302,
- * Taiwan, R.O.C.
- *
- * (c) Copyright 2002-2007, Ralink Technology, Inc.
- *
- * This program is free software; you can redistribute it and/or modify  *
- * it under the terms of the GNU General Public License as published by  *
- * the Free Software Foundation; either version 2 of the License, or     *
- * (at your option) any later version.                                   *
- *                                                                       *
- * This program is distributed in the hope that it will be useful,       *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
- * GNU General Public License for more details.                          *
- *                                                                       *
- * You should have received a copy of the GNU General Public License     *
- * along with this program; if not, write to the                         *
- * Free Software Foundation, Inc.,                                       *
- * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
- *                                                                       *
- *************************************************************************
-
-	Module Name:
-	wpa.h
-
-	Abstract:
-
-	Revision History:
-	Who			When			What
-	--------	----------		----------------------------------------------
-	Name		Date			Modification logs
-*/
-
-#ifndef	__WPA_H__
-#define	__WPA_H__
-
-// EAPOL Key descripter frame format related length
-#define LEN_KEY_DESC_NONCE			32
-#define LEN_KEY_DESC_IV				16
-#define LEN_KEY_DESC_RSC			8
-#define LEN_KEY_DESC_ID				8
-#define LEN_KEY_DESC_REPLAY			8
-#define LEN_KEY_DESC_MIC			16
-
-// The length is the EAPoL-Key frame except key data field.
-// Please refer to 802.11i-2004 ,Figure 43u in p.78
-#define LEN_EAPOL_KEY_MSG			(sizeof(KEY_DESCRIPTER) - MAX_LEN_OF_RSNIE)
-
-// EAP Code Type.
-#define EAP_CODE_REQUEST	1
-#define EAP_CODE_RESPONSE	2
-#define EAP_CODE_SUCCESS    3
-#define EAP_CODE_FAILURE    4
-
-// EAPOL frame Protocol Version
-#define	EAPOL_VER					1
-#define	EAPOL_VER2					2
-
-// EAPOL-KEY Descriptor Type
-#define	WPA1_KEY_DESC				0xfe
-#define WPA2_KEY_DESC               0x02
-
-// Key Descriptor Version of Key Information
-#define	DESC_TYPE_TKIP				1
-#define	DESC_TYPE_AES				2
-#define DESC_TYPE_MESH				3
-
-#define LEN_MSG1_2WAY               0x7f
-#define MAX_LEN_OF_EAP_HS           256
-
-#define LEN_MASTER_KEY				32
-
-// EAPOL EK, MK
-#define LEN_EAP_EK					16
-#define LEN_EAP_MICK				16
-#define LEN_EAP_KEY					((LEN_EAP_EK)+(LEN_EAP_MICK))
-// TKIP key related
-#define LEN_PMKID					16
-#define LEN_TKIP_EK					16
-#define LEN_TKIP_RXMICK				8
-#define LEN_TKIP_TXMICK				8
-#define LEN_AES_EK					16
-#define LEN_AES_KEY					LEN_AES_EK
-#define LEN_TKIP_KEY				((LEN_TKIP_EK)+(LEN_TKIP_RXMICK)+(LEN_TKIP_TXMICK))
-#define TKIP_AP_TXMICK_OFFSET		((LEN_EAP_KEY)+(LEN_TKIP_EK))
-#define TKIP_AP_RXMICK_OFFSET		(TKIP_AP_TXMICK_OFFSET+LEN_TKIP_TXMICK)
-#define TKIP_GTK_LENGTH				((LEN_TKIP_EK)+(LEN_TKIP_RXMICK)+(LEN_TKIP_TXMICK))
-#define LEN_PTK						((LEN_EAP_KEY)+(LEN_TKIP_KEY))
-
-// RSN IE Length definition
-#define MAX_LEN_OF_RSNIE         	90
-#define MIN_LEN_OF_RSNIE         	8
-
-//EAP Packet Type
-#define	EAPPacket		0
-#define	EAPOLStart		1
-#define	EAPOLLogoff		2
-#define	EAPOLKey		3
-#define	EAPOLASFAlert	4
-#define	EAPTtypeMax		5
-
-#define	EAPOL_MSG_INVALID	0
-#define	EAPOL_PAIR_MSG_1	1
-#define	EAPOL_PAIR_MSG_2	2
-#define	EAPOL_PAIR_MSG_3	3
-#define	EAPOL_PAIR_MSG_4	4
-#define	EAPOL_GROUP_MSG_1	5
-#define	EAPOL_GROUP_MSG_2	6
-
-#define PAIRWISEKEY					1
-#define GROUPKEY					0
-
-// Retry timer counter initial value
-#define PEER_MSG1_RETRY_TIMER_CTR           0
-#define PEER_MSG3_RETRY_TIMER_CTR           10
-#define GROUP_MSG1_RETRY_TIMER_CTR          20
-
-
-#define EAPOL_START_DISABLE					0
-#define EAPOL_START_PSK						1
-#define EAPOL_START_1X						2
-
-#define MIX_CIPHER_WPA_TKIP_ON(x)       (((x) & 0x08) != 0)
-#define MIX_CIPHER_WPA_AES_ON(x)        (((x) & 0x04) != 0)
-#define MIX_CIPHER_WPA2_TKIP_ON(x)      (((x) & 0x02) != 0)
-#define MIX_CIPHER_WPA2_AES_ON(x)       (((x) & 0x01) != 0)
-
-#define ROUND_UP(__x, __y) \
-	(((ULONG)((__x)+((__y)-1))) & ((ULONG)~((__y)-1)))
-
-#define	ADD_ONE_To_64BIT_VAR(_V)		\
-{										\
-	UCHAR	cnt = LEN_KEY_DESC_REPLAY;	\
-	do									\
-	{									\
-		cnt--;							\
-		_V[cnt]++;						\
-		if (cnt == 0)					\
-			break;						\
-	}while (_V[cnt] == 0);				\
-}
-
-#define IS_WPA_CAPABILITY(a)       (((a) >= Ndis802_11AuthModeWPA) && ((a) <= Ndis802_11AuthModeWPA1PSKWPA2PSK))
-
-// EAPOL Key Information definition within Key descriptor format
-typedef	struct PACKED _KEY_INFO
-{
-#ifdef RT_BIG_ENDIAN
-	UCHAR	KeyAck:1;
-    UCHAR	Install:1;
-    UCHAR	KeyIndex:2;
-    UCHAR	KeyType:1;
-    UCHAR	KeyDescVer:3;
-    UCHAR	Rsvd:3;
-    UCHAR	EKD_DL:1;		// EKD for AP; DL for STA
-    UCHAR	Request:1;
-    UCHAR	Error:1;
-    UCHAR	Secure:1;
-    UCHAR	KeyMic:1;
-#else
-	UCHAR	KeyMic:1;
-	UCHAR	Secure:1;
-	UCHAR	Error:1;
-	UCHAR	Request:1;
-	UCHAR	EKD_DL:1;       // EKD for AP; DL for STA
-	UCHAR	Rsvd:3;
-	UCHAR	KeyDescVer:3;
-	UCHAR	KeyType:1;
-	UCHAR	KeyIndex:2;
-	UCHAR	Install:1;
-	UCHAR	KeyAck:1;
-#endif
-}	KEY_INFO, *PKEY_INFO;
-
-// EAPOL Key descriptor format
-typedef	struct PACKED _KEY_DESCRIPTER
-{
-	UCHAR		Type;
-	KEY_INFO	KeyInfo;
-	UCHAR		KeyLength[2];
-	UCHAR		ReplayCounter[LEN_KEY_DESC_REPLAY];
-	UCHAR		KeyNonce[LEN_KEY_DESC_NONCE];
-	UCHAR		KeyIv[LEN_KEY_DESC_IV];
-	UCHAR		KeyRsc[LEN_KEY_DESC_RSC];
-	UCHAR		KeyId[LEN_KEY_DESC_ID];
-	UCHAR		KeyMic[LEN_KEY_DESC_MIC];
-	UCHAR		KeyDataLen[2];
-	UCHAR		KeyData[MAX_LEN_OF_RSNIE];
-}	KEY_DESCRIPTER, *PKEY_DESCRIPTER;
-
-typedef	struct PACKED _EAPOL_PACKET
-{
-	UCHAR	 			ProVer;
-	UCHAR	 			ProType;
-	UCHAR	 			Body_Len[2];
-	KEY_DESCRIPTER		KeyDesc;
-}	EAPOL_PACKET, *PEAPOL_PACKET;
-
-//802.11i D10 page 83
-typedef struct PACKED _GTK_ENCAP
-{
-#ifndef RT_BIG_ENDIAN
-    UCHAR               Kid:2;
-    UCHAR               tx:1;
-    UCHAR               rsv:5;
-    UCHAR               rsv1;
-#else
-    UCHAR               rsv:5;
-    UCHAR               tx:1;
-    UCHAR               Kid:2;
-    UCHAR               rsv1;
-#endif
-    UCHAR               GTK[TKIP_GTK_LENGTH];
-}   GTK_ENCAP, *PGTK_ENCAP;
-
-typedef struct PACKED _KDE_ENCAP
-{
-    UCHAR               Type;
-    UCHAR               Len;
-    UCHAR               OUI[3];
-    UCHAR               DataType;
-    GTK_ENCAP      GTKEncap;
-}   KDE_ENCAP, *PKDE_ENCAP;
-
-// For WPA1
-typedef struct PACKED _RSNIE {
-    UCHAR   oui[4];
-    USHORT  version;
-    UCHAR   mcast[4];
-    USHORT  ucount;
-    struct PACKED {
-        UCHAR oui[4];
-    }ucast[1];
-} RSNIE, *PRSNIE;
-
-// For WPA2
-typedef struct PACKED _RSNIE2 {
-    USHORT  version;
-    UCHAR   mcast[4];
-    USHORT  ucount;
-    struct PACKED {
-        UCHAR oui[4];
-    }ucast[1];
-} RSNIE2, *PRSNIE2;
-
-// AKM Suite
-typedef struct PACKED _RSNIE_AUTH {
-    USHORT acount;
-    struct PACKED {
-        UCHAR oui[4];
-    }auth[1];
-} RSNIE_AUTH,*PRSNIE_AUTH;
-
-typedef	union PACKED _RSN_CAPABILITIES	{
-	struct	PACKED {
-#ifdef RT_BIG_ENDIAN
-        USHORT		Rsvd:10;
-        USHORT		GTKSA_R_Counter:2;
-        USHORT		PTKSA_R_Counter:2;
-        USHORT		No_Pairwise:1;
-		USHORT		PreAuth:1;
-#else
-        USHORT		PreAuth:1;
-		USHORT		No_Pairwise:1;
-		USHORT		PTKSA_R_Counter:2;
-		USHORT		GTKSA_R_Counter:2;
-		USHORT		Rsvd:10;
-#endif
-	}	field;
-	USHORT			word;
-}	RSN_CAPABILITIES, *PRSN_CAPABILITIES;
-
-typedef struct PACKED _EAP_HDR {
-    UCHAR   ProVer;
-    UCHAR   ProType;
-    UCHAR   Body_Len[2];
-    UCHAR   code;
-    UCHAR   identifier;
-    UCHAR   length[2]; // including code and identifier, followed by length-2 octets of data
-} EAP_HDR, *PEAP_HDR;
-
-// For supplicant state machine states. 802.11i Draft 4.1, p. 97
-// We simplified it
-typedef	enum	_WpaState
-{
-	SS_NOTUSE,				// 0
-	SS_START,				// 1
-	SS_WAIT_MSG_3,			// 2
-	SS_WAIT_GROUP,			// 3
-	SS_FINISH,  			// 4
-	SS_KEYUPDATE,			// 5
-}	WPA_STATE;
-
-//
-//	The definition of the cipher combination
-//
-// 	 bit3	bit2  bit1   bit0
-//	+------------+------------+
-// 	|	  WPA	 |	   WPA2   |
-//	+------+-----+------+-----+
-//	| TKIP | AES | TKIP | AES |
-//	|	0  |  1  |   1  |  0  | -> 0x06
-//	|	0  |  1  |   1  |  1  | -> 0x07
-//	|	1  |  0  |   0  |  1  | -> 0x09
-//	|	1  |  0  |   1  |  1  | -> 0x0B
-//	|	1  |  1  |   0  |  1  | -> 0x0D
-//	|	1  |  1  |   1  |  0  | -> 0x0E
-//	|	1  |  1  |   1  |  1  |	-> 0x0F
-//	+------+-----+------+-----+
-//
-typedef	enum	_WpaMixPairCipher
-{
-	MIX_CIPHER_NOTUSE 			= 0x00,
-	WPA_NONE_WPA2_TKIPAES		= 0x03,		// WPA2-TKIPAES
-	WPA_AES_WPA2_TKIP 			= 0x06,
-	WPA_AES_WPA2_TKIPAES		= 0x07,
-	WPA_TKIP_WPA2_AES			= 0x09,
-	WPA_TKIP_WPA2_TKIPAES		= 0x0B,
-	WPA_TKIPAES_WPA2_NONE		= 0x0C,		// WPA-TKIPAES
-	WPA_TKIPAES_WPA2_AES		= 0x0D,
-	WPA_TKIPAES_WPA2_TKIP		= 0x0E,
-	WPA_TKIPAES_WPA2_TKIPAES	= 0x0F,
-}	WPA_MIX_PAIR_CIPHER;
-
-typedef struct PACKED _RSN_IE_HEADER_STRUCT	{
-	UCHAR		Eid;
-	UCHAR		Length;
-	USHORT		Version;	// Little endian format
-}	RSN_IE_HEADER_STRUCT, *PRSN_IE_HEADER_STRUCT;
-
-// Cipher suite selector types
-typedef struct PACKED _CIPHER_SUITE_STRUCT	{
-	UCHAR		Oui[3];
-	UCHAR		Type;
-}	CIPHER_SUITE_STRUCT, *PCIPHER_SUITE_STRUCT;
-
-// Authentication and Key Management suite selector
-typedef struct PACKED _AKM_SUITE_STRUCT	{
-	UCHAR		Oui[3];
-	UCHAR		Type;
-}	AKM_SUITE_STRUCT, *PAKM_SUITE_STRUCT;
-
-// RSN capability
-typedef struct	PACKED _RSN_CAPABILITY	{
-	USHORT		Rsv:10;
-	USHORT		GTKSAReplayCnt:2;
-	USHORT		PTKSAReplayCnt:2;
-	USHORT		NoPairwise:1;
-	USHORT		PreAuth:1;
-}	RSN_CAPABILITY, *PRSN_CAPABILITY;
-
-#endif
+#include "../rt2870/wpa.h"
diff --git a/drivers/staging/rtl8187se/Kconfig b/drivers/staging/rtl8187se/Kconfig
index f636296..236e427 100644
--- a/drivers/staging/rtl8187se/Kconfig
+++ b/drivers/staging/rtl8187se/Kconfig
@@ -1,6 +1,6 @@
 config RTL8187SE
 	tristate "RealTek RTL8187SE Wireless LAN NIC driver"
 	depends on PCI
-	depends on WIRELESS_EXT && COMPAT_NET_DEV_OPS
+	depends on WIRELESS_EXT
 	default N
 	---help---
diff --git a/drivers/staging/rtl8187se/ieee80211/ieee80211_module.c b/drivers/staging/rtl8187se/ieee80211/ieee80211_module.c
index 0c9fef0..c2b61e6 100644
--- a/drivers/staging/rtl8187se/ieee80211/ieee80211_module.c
+++ b/drivers/staging/rtl8187se/ieee80211/ieee80211_module.c
@@ -114,7 +114,6 @@
 		goto failed;
 	}
 	ieee = netdev_priv(dev);
-	dev->hard_start_xmit = ieee80211_xmit;
 
 	ieee->dev = dev;
 
diff --git a/drivers/staging/rtl8187se/ieee80211/ieee80211_rx.c b/drivers/staging/rtl8187se/ieee80211/ieee80211_rx.c
index 23519b3..4d4ee56 100644
--- a/drivers/staging/rtl8187se/ieee80211/ieee80211_rx.c
+++ b/drivers/staging/rtl8187se/ieee80211/ieee80211_rx.c
@@ -1680,7 +1680,7 @@
 	if(src->wmm_param[0].ac_aci_acm_aifsn|| \
 	   src->wmm_param[1].ac_aci_acm_aifsn|| \
 	   src->wmm_param[2].ac_aci_acm_aifsn|| \
-	   src->wmm_param[1].ac_aci_acm_aifsn) {
+	   src->wmm_param[3].ac_aci_acm_aifsn) {
 	  memcpy(dst->wmm_param, src->wmm_param, WME_AC_PRAM_LEN);
 	}
 	dst->QoS_Enable = src->QoS_Enable;
diff --git a/drivers/staging/rtl8187se/r8180_core.c b/drivers/staging/rtl8187se/r8180_core.c
index e10413c..7e2feca 100644
--- a/drivers/staging/rtl8187se/r8180_core.c
+++ b/drivers/staging/rtl8187se/r8180_core.c
@@ -198,7 +198,8 @@
 static void rtl8180_shutdown (struct pci_dev *pdev)
 {
 	struct net_device *dev = pci_get_drvdata(pdev);
-	dev->stop(dev);
+	if (dev->netdev_ops->ndo_stop)
+		dev->netdev_ops->ndo_stop(dev);
 	pci_disable_device(pdev);
 }
 
@@ -4551,8 +4552,6 @@
 		//DMESG("Reported EEPROM chip is a 93c46 (1Kbit)");
 	}
 
-	dev->get_stats = rtl8180_stats;
-
 	dev->dev_addr[0]=eprom_read(dev,MAC_ADR) & 0xff;
 	dev->dev_addr[1]=(eprom_read(dev,MAC_ADR) & 0xff00)>>8;
 	dev->dev_addr[2]=eprom_read(dev,MAC_ADR+1) & 0xff;
@@ -5832,6 +5831,18 @@
      -----------------------------PCI STUFF---------------------------
 *****************************************************************************/
 
+static const struct net_device_ops rtl8180_netdev_ops = {
+	.ndo_open		= rtl8180_open,
+	.ndo_stop		= rtl8180_close,
+	.ndo_get_stats		= rtl8180_stats,
+	.ndo_tx_timeout		= rtl8180_restart,
+	.ndo_do_ioctl		= rtl8180_ioctl,
+	.ndo_set_multicast_list	= r8180_set_multicast,
+	.ndo_set_mac_address	= r8180_set_mac_adr,
+	.ndo_validate_addr	= eth_validate_addr,
+	.ndo_change_mtu		= eth_change_mtu,
+	.ndo_start_xmit		= ieee80211_xmit,
+};
 
 static int __devinit rtl8180_pci_probe(struct pci_dev *pdev,
 				       const struct pci_device_id *id)
@@ -5936,14 +5947,8 @@
 	dev->irq = pdev->irq;
 	priv->irq = 0;
 
-	dev->open = rtl8180_open;
-	dev->stop = rtl8180_close;
-	//dev->hard_start_xmit = ieee80211_xmit;
-	dev->tx_timeout = rtl8180_restart;
+	dev->netdev_ops = &rtl8180_netdev_ops;
 	dev->wireless_handlers = &r8180_wx_handlers_def;
-	dev->do_ioctl = rtl8180_ioctl;
-	dev->set_multicast_list = r8180_set_multicast;
-	dev->set_mac_address = r8180_set_mac_adr;
 
 #if WIRELESS_EXT >= 12
 #if WIRELESS_EXT < 17
diff --git a/drivers/staging/rtl8187se/r8180_dm.c b/drivers/staging/rtl8187se/r8180_dm.c
index 93b5a7b..e772f0f 100644
--- a/drivers/staging/rtl8187se/r8180_dm.c
+++ b/drivers/staging/rtl8187se/r8180_dm.c
@@ -132,7 +132,7 @@
 //      struct r8180_priv *priv = container_of(work, struct r8180_priv, watch_dog_wq);
 //      struct ieee80211_device * ieee = (struct ieee80211_device*)
 //                                             container_of(work, struct ieee80211_device, watch_dog_wq);
-        struct delayed_work *dwork = container_of(work,struct delayed_work,work);
+	struct delayed_work *dwork = to_delayed_work(work);
         struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,tx_pw_wq);
         struct net_device *dev = ieee->dev;
 #else
@@ -314,7 +314,7 @@
 //      struct r8180_priv *priv = container_of(work, struct r8180_priv, watch_dog_wq);
 //      struct ieee80211_device * ieee = (struct ieee80211_device*)
 //                                             container_of(work, struct ieee80211_device, watch_dog_wq);
-        struct delayed_work *dwork = container_of(work,struct delayed_work,work);
+	struct delayed_work *dwork = to_delayed_work(work);
         struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,hw_dig_wq);
         struct net_device *dev = ieee->dev;
 #else
@@ -1250,7 +1250,7 @@
 #if LINUX_VERSION_CODE >=KERNEL_VERSION(2,6,20)
 void rtl8180_rate_adapter(struct work_struct * work)
 {
-	struct delayed_work *dwork = container_of(work,struct delayed_work,work);
+	struct delayed_work *dwork = to_delayed_work(work);
         struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,rate_adapter_wq);
         struct net_device *dev = ieee->dev;
 #else
diff --git a/drivers/staging/rtl8187se/r8180_pm.c b/drivers/staging/rtl8187se/r8180_pm.c
index 3851b93..2b3d642 100644
--- a/drivers/staging/rtl8187se/r8180_pm.c
+++ b/drivers/staging/rtl8187se/r8180_pm.c
@@ -30,7 +30,8 @@
 	if (!netif_running(dev))
 		goto out_pci_suspend;
 
-	dev->stop(dev);
+	if (dev->netdev_ops->ndo_stop)
+		dev->netdev_ops->ndo_stop(dev);
 
 	netif_device_detach(dev);
 
@@ -71,7 +72,8 @@
 	if(!netif_running(dev))
 		goto out;
 
-	dev->open(dev);
+	if (dev->netdev_ops->ndo_open)
+		dev->netdev_ops->ndo_open(dev);
 	netif_device_attach(dev);
 out:
 	return 0;
diff --git a/drivers/staging/rtl8192su/Kconfig b/drivers/staging/rtl8192su/Kconfig
new file mode 100644
index 0000000..4b5552c
--- /dev/null
+++ b/drivers/staging/rtl8192su/Kconfig
@@ -0,0 +1,6 @@
+config RTL8192SU
+	tristate "RealTek RTL8192SU Wireless LAN NIC driver"
+	depends on PCI
+	depends on WIRELESS_EXT && COMPAT_NET_DEV_OPS
+	default N
+	---help---
diff --git a/drivers/staging/rtl8192su/Makefile b/drivers/staging/rtl8192su/Makefile
new file mode 100644
index 0000000..f010ab5
--- /dev/null
+++ b/drivers/staging/rtl8192su/Makefile
@@ -0,0 +1,66 @@
+NIC_SELECT = RTL8192SU
+
+EXTRA_CFLAGS += -std=gnu89
+EXTRA_CFLAGS += -O2
+EXTRA_CFLAGS += -mhard-float -DCONFIG_FORCE_HARD_FLOAT=y
+
+EXTRA_CFLAGS += -DJACKSON_NEW_RX
+EXTRA_CFLAGS += -DTHOMAS_BEACON -DTHOMAS_TURBO
+#EXTRA_CFLAGS += -DUSE_ONE_PIPE
+EXTRA_CFLAGS += -DENABLE_DOT11D
+
+EXTRA_CFLAGS += -DRTL8192SU
+EXTRA_CFLAGS += -DRTL8190_Download_Firmware_From_Header=1
+EXTRA_CFLAGS += -DRTL8192S_PREPARE_FOR_NORMAL_RELEASE
+EXTRA_CFLAGS += -DRTL8192SU_DISABLE_IQK=1
+
+#EXTRA_CFLAGS += -DEEPROM_OLD_FORMAT_SUPPORT
+
+#EXTRA_CFLAGS += -DUSB_RX_AGGREGATION_SUPPORT=0
+#EXTRA_CFLAGS += -DUSB_TX_DRIVER_AGGREGATION_ENABLE=0
+#EXTRA_CFLAGS += -DRTL8192SU_DISABLE_CCK_RATE=0
+EXTRA_CFLAGS += -DRTL8192S_DISABLE_FW_DM=0
+EXTRA_CFLAGS += -DDISABLE_BB_RF=0
+EXTRA_CFLAGS += -DRTL8192SU_USE_PARAM_TXPWR=0
+EXTRA_CFLAGS += -DRTL8192SU_FPGA_UNSPECIFIED_NETWORK=0
+#EXTRA_CFLAGS += -DRTL8192SU_FPGA_2MAC_VERIFICATION #=0
+EXTRA_CFLAGS += -DRTL8192SU_ASIC_VERIFICATION
+EXTRA_CFLAGS += -DRTL8192SU_USB_PHY_TEST=0
+
+#EXTRA_CFLAGS += -DMUTIPLE_BULK_OUT
+EXTRA_CFLAGS += -DCONFIG_RTL8192_PM
+
+r8192s_usb-objs :=		\
+	r8180_93cx6.o		\
+	r8192U_wx.o		\
+	r8192S_phy.o		\
+	r8192S_rtl6052.o	\
+	r8192S_rtl8225.o	\
+	r819xU_cmdpkt.o		\
+	r8192U_dm.o		\
+	r8192SU_HWImg.o		\
+	r8192S_firmware.o	\
+	r8192S_Efuse.o		\
+	r8192U_core.o		\
+	r8192U_pm.o
+
+ieee80211-rsl-objs :=			\
+	ieee80211/ieee80211_rx.o	\
+	ieee80211/ieee80211_softmac.o	\
+	ieee80211/ieee80211_tx.o	\
+	ieee80211/ieee80211_wx.o	\
+	ieee80211/ieee80211_module.o	\
+	ieee80211/ieee80211_softmac_wx.o\
+	ieee80211/rtl819x_HTProc.o	\
+	ieee80211/rtl819x_TSProc.o	\
+	ieee80211/rtl819x_BAProc.o	\
+	ieee80211/dot11d.o
+
+obj-$(CONFIG_RTL8192SU) += r8192s_usb.o
+obj-$(CONFIG_RTL8192SU) += ieee80211-rsl.o
+obj-$(CONFIG_RTL8192SU) += ieee80211/ieee80211_crypt.o
+obj-$(CONFIG_RTL8192SU) += ieee80211/ieee80211_crypt_tkip.o
+obj-$(CONFIG_RTL8192SU) += ieee80211/ieee80211_crypt_ccmp.o
+obj-$(CONFIG_RTL8192SU) += ieee80211/ieee80211_crypt_wep.o
+
+
diff --git a/drivers/staging/rtl8192su/authors b/drivers/staging/rtl8192su/authors
new file mode 100644
index 0000000..b08bbae
--- /dev/null
+++ b/drivers/staging/rtl8192su/authors
@@ -0,0 +1 @@
+Andrea Merello <andreamrl@tiscali.it>
diff --git a/drivers/staging/rtl8192su/dot11d.h b/drivers/staging/rtl8192su/dot11d.h
new file mode 100644
index 0000000..15b7a4b
--- /dev/null
+++ b/drivers/staging/rtl8192su/dot11d.h
@@ -0,0 +1,102 @@
+#ifndef __INC_DOT11D_H
+#define __INC_DOT11D_H
+
+#ifdef ENABLE_DOT11D
+#include "ieee80211.h"
+
+//#define ENABLE_DOT11D
+
+//#define DOT11D_MAX_CHNL_NUM 83
+
+typedef struct _CHNL_TXPOWER_TRIPLE {
+	u8 FirstChnl;
+	u8  NumChnls;
+	u8  MaxTxPowerInDbm;
+}CHNL_TXPOWER_TRIPLE, *PCHNL_TXPOWER_TRIPLE;
+
+typedef enum _DOT11D_STATE {
+	DOT11D_STATE_NONE = 0,
+	DOT11D_STATE_LEARNED,
+	DOT11D_STATE_DONE,
+}DOT11D_STATE;
+
+typedef struct _RT_DOT11D_INFO {
+	//DECLARE_RT_OBJECT(RT_DOT11D_INFO);
+
+	bool bEnabled; // dot11MultiDomainCapabilityEnabled
+
+	u16 CountryIeLen; // > 0 if CountryIeBuf[] contains valid country information element.
+	u8  CountryIeBuf[MAX_IE_LEN];
+	u8  CountryIeSrcAddr[6]; // Source AP of the country IE.
+	u8  CountryIeWatchdog;
+
+	u8  channel_map[MAX_CHANNEL_NUMBER+1];  //!!!Value 0: Invalid, 1: Valid (active scan), 2: Valid (passive scan)
+	//u8  ChnlListLen; // #Bytes valid in ChnlList[].
+	//u8  ChnlList[DOT11D_MAX_CHNL_NUM];
+	u8  MaxTxPwrDbmList[MAX_CHANNEL_NUMBER+1];
+
+	DOT11D_STATE State;
+}RT_DOT11D_INFO, *PRT_DOT11D_INFO;
+#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 )
+#define cpMacAddr(des,src)	      ((des)[0]=(src)[0],(des)[1]=(src)[1],(des)[2]=(src)[2],(des)[3]=(src)[3],(des)[4]=(src)[4],(des)[5]=(src)[5])
+#define GET_DOT11D_INFO(__pIeeeDev) ((PRT_DOT11D_INFO)((__pIeeeDev)->pDot11dInfo))
+
+#define IS_DOT11D_ENABLE(__pIeeeDev) GET_DOT11D_INFO(__pIeeeDev)->bEnabled
+#define IS_COUNTRY_IE_VALID(__pIeeeDev) (GET_DOT11D_INFO(__pIeeeDev)->CountryIeLen > 0)
+
+#define IS_EQUAL_CIE_SRC(__pIeeeDev, __pTa) eqMacAddr(GET_DOT11D_INFO(__pIeeeDev)->CountryIeSrcAddr, __pTa)
+#define UPDATE_CIE_SRC(__pIeeeDev, __pTa) cpMacAddr(GET_DOT11D_INFO(__pIeeeDev)->CountryIeSrcAddr, __pTa)
+
+#define IS_COUNTRY_IE_CHANGED(__pIeeeDev, __Ie) \
+	(((__Ie).Length == 0 || (__Ie).Length != GET_DOT11D_INFO(__pIeeeDev)->CountryIeLen) ? \
+	FALSE : \
+	(!memcmp(GET_DOT11D_INFO(__pIeeeDev)->CountryIeBuf, (__Ie).Octet, (__Ie).Length)))
+
+#define CIE_WATCHDOG_TH 1
+#define GET_CIE_WATCHDOG(__pIeeeDev) GET_DOT11D_INFO(__pIeeeDev)->CountryIeWatchdog
+#define RESET_CIE_WATCHDOG(__pIeeeDev) GET_CIE_WATCHDOG(__pIeeeDev) = 0
+#define UPDATE_CIE_WATCHDOG(__pIeeeDev) ++GET_CIE_WATCHDOG(__pIeeeDev)
+
+#define IS_DOT11D_STATE_DONE(__pIeeeDev) (GET_DOT11D_INFO(__pIeeeDev)->State == DOT11D_STATE_DONE)
+
+
+void
+Dot11d_Init(
+	struct ieee80211_device *dev
+	);
+
+void
+Dot11d_Reset(
+	struct ieee80211_device *dev
+	);
+
+void
+Dot11d_UpdateCountryIe(
+	struct ieee80211_device *dev,
+	u8 *		pTaddr,
+	u16	CoutryIeLen,
+	u8 * pCoutryIe
+	);
+
+u8
+DOT11D_GetMaxTxPwrInDbm(
+	struct ieee80211_device *dev,
+	u8 Channel
+	);
+
+void
+DOT11D_ScanComplete(
+	struct ieee80211_device * dev
+	);
+
+int IsLegalChannel(
+	struct ieee80211_device * dev,
+	u8 channel
+);
+
+int ToLegalChannel(
+	struct ieee80211_device * dev,
+	u8 channel
+);
+#endif //ENABLE_DOT11D
+#endif // #ifndef __INC_DOT11D_H
diff --git a/drivers/staging/rtl8192su/ieee80211.h b/drivers/staging/rtl8192su/ieee80211.h
new file mode 100644
index 0000000..0edb09a
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211.h
@@ -0,0 +1,2901 @@
+/*
+ * Merged with mainline ieee80211.h in Aug 2004.  Original ieee802_11
+ * remains copyright by the original authors
+ *
+ * Portions of the merged code are based on Host AP (software wireless
+ * LAN access point) driver for Intersil Prism2/2.5/3.
+ *
+ * Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen
+ * <jkmaline@cc.hut.fi>
+ * Copyright (c) 2002-2003, Jouni Malinen <jkmaline@cc.hut.fi>
+ *
+ * Adaption to a generic IEEE 802.11 stack by James Ketrenos
+ * <jketreno@linux.intel.com>
+ * Copyright (c) 2004, Intel Corporation
+ *
+ * Modified for Realtek's wi-fi cards by Andrea Merello
+ * <andreamrl@tiscali.it>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. See README and COPYING for
+ * more details.
+ */
+#ifndef IEEE80211_H
+#define IEEE80211_H
+#include <linux/if_ether.h> /* ETH_ALEN */
+#include <linux/kernel.h>   /* ARRAY_SIZE */
+#include <linux/version.h>
+#include <linux/module.h>
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+#include <linux/jiffies.h>
+#else
+#include <linux/jffs.h>
+#include <linux/tqueue.h>
+#endif
+#include <linux/timer.h>
+#include <linux/sched.h>
+
+#include <linux/delay.h>
+#include <linux/wireless.h>
+
+#include "ieee80211/rtl819x_HT.h"
+#include "ieee80211/rtl819x_BA.h"
+#include "ieee80211/rtl819x_TS.h"
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20))
+#ifndef bool
+typedef enum{false = 0, true} bool;
+#endif
+#endif
+
+#ifndef IW_MODE_MONITOR
+#define IW_MODE_MONITOR 6
+#endif
+
+#ifndef IWEVCUSTOM
+#define IWEVCUSTOM 0x8c02
+#endif
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+#ifndef __bitwise
+#define __bitwise __attribute__((bitwise))
+#endif
+typedef __u16  __le16;
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,4,27))
+struct iw_spy_data{
+	/* --- Standard spy support --- */
+	int 			spy_number;
+	u_char 			spy_address[IW_MAX_SPY][ETH_ALEN];
+	struct iw_quality	spy_stat[IW_MAX_SPY];
+	/* --- Enhanced spy support (event) */
+	struct iw_quality	spy_thr_low; /* Low threshold */
+	struct iw_quality	spy_thr_high; /* High threshold */
+	u_char			spy_thr_under[IW_MAX_SPY];
+};
+#endif
+#endif
+
+#ifndef container_of
+/**
+ * container_of - cast a member of a structure out to the containing structure
+ *
+ * @ptr:        the pointer to the member.
+ * @type:       the type of the container struct this is embedded in.
+ * @member:     the name of the member within the struct.
+ *
+ */
+#define container_of(ptr, type, member) ({                      \
+        const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
+        (type *)( (char *)__mptr - offsetof(type,member) );})
+#endif
+
+#define KEY_TYPE_NA		0x0
+#define KEY_TYPE_WEP40 		0x1
+#define KEY_TYPE_TKIP		0x2
+#define KEY_TYPE_CCMP		0x4
+#define KEY_TYPE_WEP104		0x5
+
+/* added for rtl819x tx procedure */
+#define MAX_QUEUE_SIZE		0x10
+
+//
+// 8190 queue mapping
+//
+#define BK_QUEUE                               0
+#define BE_QUEUE                               1
+#define VI_QUEUE                               2
+#define VO_QUEUE                               3
+#define HCCA_QUEUE                             4
+#define TXCMD_QUEUE                            5
+#define MGNT_QUEUE                             6
+#define HIGH_QUEUE                             7
+#define BEACON_QUEUE                           8
+
+#define LOW_QUEUE                              BE_QUEUE
+#define NORMAL_QUEUE                           MGNT_QUEUE
+
+//added by amy for ps
+#define SWRF_TIMEOUT				50
+
+//added by amy for LEAP related
+#define IE_CISCO_FLAG_POSITION		0x08	// Flag byte: byte 8, numbered from 0.
+#define SUPPORT_CKIP_MIC			0x08	// bit3
+#define SUPPORT_CKIP_PK			0x10	// bit4
+//added by amy for ps
+// RF Off Level for IPS or HW/SW radio off
+#define	RT_RF_OFF_LEVL_ASPM			BIT0	// PCI ASPM
+#define	RT_RF_OFF_LEVL_CLK_REQ		BIT1	// PCI clock request
+#define	RT_RF_OFF_LEVL_PCI_D3			BIT2	// PCI D3 mode
+#define	RT_RF_OFF_LEVL_HALT_NIC		BIT3	// NIC halt, re-initialize hw parameters
+#define	RT_RF_OFF_LEVL_FREE_FW		BIT4	// FW free, re-download the FW
+#define	RT_RF_OFF_LEVL_FW_32K		BIT5	// FW in 32k
+#define	RT_RF_PS_LEVEL_ALWAYS_ASPM	BIT6	// Always enable ASPM and Clock Req in initialization.
+#define	RT_RF_LPS_DISALBE_2R			BIT30	// When LPS is on, disable 2R if no packet is received or transmittd.
+#define	RT_RF_LPS_LEVEL_ASPM			BIT31	// LPS with ASPM
+#define	RT_IN_PS_LEVEL(pPSC, _PS_FLAG)	((pPSC->CurPsLevel & _PS_FLAG) ? true : false)
+#define	RT_CLEAR_PS_LEVEL(pPSC, _PS_FLAG)	(pPSC->CurPsLevel &= (~(_PS_FLAG)))
+#define	RT_SET_PS_LEVEL(pPSC, _PS_FLAG)	(pPSC->CurPsLevel->CurPsLevel |= _PS_FLAG)
+/* defined for skb cb field */
+/* At most 28 byte */
+typedef struct cb_desc {
+        /* Tx Desc Related flags (8-9) */
+	u8 bLastIniPkt:1;
+	u8 bCmdOrInit:1;
+        u8 bFirstSeg:1;
+        u8 bLastSeg:1;
+        u8 bEncrypt:1;
+        u8 bTxDisableRateFallBack:1;
+        u8 bTxUseDriverAssingedRate:1;
+        u8 bHwSec:1; //indicate whether use Hw security. WB
+
+        u8 reserved1;
+
+        /* Tx Firmware Relaged flags (10-11)*/
+        u8 bCTSEnable:1;
+        u8 bRTSEnable:1;
+        u8 bUseShortGI:1;
+        u8 bUseShortPreamble:1;
+        u8 bTxEnableFwCalcDur:1;
+        u8 bAMPDUEnable:1;
+        u8 bRTSSTBC:1;
+        u8 RTSSC:1;
+
+        u8 bRTSBW:1;
+        u8 bPacketBW:1;
+	u8 bRTSUseShortPreamble:1;
+	u8 bRTSUseShortGI:1;
+	u8 bMulticast:1;
+	u8 bBroadcast:1;
+        //u8 reserved2:2;
+        u8 drv_agg_enable:1;
+        u8 reserved2:1;
+
+        /* Tx Desc related element(12-19) */
+        u8 rata_index;
+        u8 queue_index;
+        //u8 reserved3;
+        //u8 reserved4;
+        u16 txbuf_size;
+        //u8 reserved5;
+	u8 RATRIndex;
+        u8 reserved6;
+        u8 reserved7;
+        u8 reserved8;
+
+        /* Tx firmware related element(20-27) */
+        u8 data_rate;
+        u8 rts_rate;
+        u8 ampdu_factor;
+        u8 ampdu_density;
+        //u8 reserved9;
+        //u8 reserved10;
+        //u8 reserved11;
+        u8 DrvAggrNum;
+	u16 pkt_size;
+        u8 reserved12;
+}cb_desc, *pcb_desc;
+
+/*--------------------------Define -------------------------------------------*/
+#define MGN_1M                  0x02
+#define MGN_2M                  0x04
+#define MGN_5_5M                0x0b
+#define MGN_11M                 0x16
+
+#define MGN_6M                  0x0c
+#define MGN_9M                  0x12
+#define MGN_12M                 0x18
+#define MGN_18M                 0x24
+#define MGN_24M                 0x30
+#define MGN_36M                 0x48
+#define MGN_48M                 0x60
+#define MGN_54M                 0x6c
+
+#define MGN_MCS0                0x80
+#define MGN_MCS1                0x81
+#define MGN_MCS2                0x82
+#define MGN_MCS3                0x83
+#define MGN_MCS4                0x84
+#define MGN_MCS5                0x85
+#define MGN_MCS6                0x86
+#define MGN_MCS7                0x87
+#define MGN_MCS8                0x88
+#define MGN_MCS9                0x89
+#define MGN_MCS10               0x8a
+#define MGN_MCS11               0x8b
+#define MGN_MCS12               0x8c
+#define MGN_MCS13               0x8d
+#define MGN_MCS14               0x8e
+#define MGN_MCS15               0x8f
+#define	MGN_MCS0_SG			0x90
+#define	MGN_MCS1_SG			0x91
+#define	MGN_MCS2_SG			0x92
+#define	MGN_MCS3_SG			0x93
+#define	MGN_MCS4_SG			0x94
+#define	MGN_MCS5_SG			0x95
+#define	MGN_MCS6_SG			0x96
+#define	MGN_MCS7_SG			0x97
+#define	MGN_MCS8_SG			0x98
+#define	MGN_MCS9_SG			0x99
+#define	MGN_MCS10_SG		0x9a
+#define	MGN_MCS11_SG		0x9b
+#define	MGN_MCS12_SG		0x9c
+#define	MGN_MCS13_SG		0x9d
+#define	MGN_MCS14_SG		0x9e
+#define	MGN_MCS15_SG		0x9f
+
+
+//----------------------------------------------------------------------------
+//		802.11 Management frame Reason Code field
+//----------------------------------------------------------------------------
+enum	_ReasonCode{
+	unspec_reason	= 0x1,
+	auth_not_valid	= 0x2,
+	deauth_lv_ss	= 0x3,
+	inactivity		= 0x4,
+	ap_overload 	= 0x5,
+	class2_err		= 0x6,
+	class3_err		= 0x7,
+	disas_lv_ss 	= 0x8,
+	asoc_not_auth	= 0x9,
+
+	//----MIC_CHECK
+	mic_failure 	= 0xe,
+	//----END MIC_CHECK
+
+	// Reason code defined in 802.11i D10.0 p.28.
+	invalid_IE		= 0x0d,
+	four_way_tmout	= 0x0f,
+	two_way_tmout	= 0x10,
+	IE_dismatch 	= 0x11,
+	invalid_Gcipher = 0x12,
+	invalid_Pcipher = 0x13,
+	invalid_AKMP	= 0x14,
+	unsup_RSNIEver = 0x15,
+	invalid_RSNIE	= 0x16,
+	auth_802_1x_fail= 0x17,
+	ciper_reject		= 0x18,
+
+	// Reason code defined in 7.3.1.7, 802.1e D13.0, p.42. Added by Annie, 2005-11-15.
+	QoS_unspec		= 0x20, // 32
+	QAP_bandwidth	= 0x21, // 33
+	poor_condition	= 0x22, // 34
+	no_facility 	= 0x23, // 35
+							// Where is 36???
+	req_declined	= 0x25, // 37
+	invalid_param	= 0x26, // 38
+	req_not_honored= 0x27,	// 39
+	TS_not_created	= 0x2F, // 47
+	DL_not_allowed	= 0x30, // 48
+	dest_not_exist	= 0x31, // 49
+	dest_not_QSTA	= 0x32, // 50
+};
+
+
+
+#define aSifsTime	 (((priv->ieee80211->current_network.mode == IEEE_A)||(priv->ieee80211->current_network.mode == IEEE_N_24G)||(priv->ieee80211->current_network.mode == IEEE_N_5G))? 16 : 10)
+
+#define MGMT_QUEUE_NUM 5
+
+#define IEEE_CMD_SET_WPA_PARAM			1
+#define	IEEE_CMD_SET_WPA_IE			2
+#define IEEE_CMD_SET_ENCRYPTION			3
+#define IEEE_CMD_MLME				4
+
+#define IEEE_PARAM_WPA_ENABLED			1
+#define IEEE_PARAM_TKIP_COUNTERMEASURES		2
+#define IEEE_PARAM_DROP_UNENCRYPTED		3
+#define IEEE_PARAM_PRIVACY_INVOKED		4
+#define IEEE_PARAM_AUTH_ALGS			5
+#define IEEE_PARAM_IEEE_802_1X			6
+//It should consistent with the driver_XXX.c
+//   David, 2006.9.26
+#define IEEE_PARAM_WPAX_SELECT			7
+//Added for notify the encryption type selection
+//   David, 2006.9.26
+#define IEEE_PROTO_WPA				1
+#define IEEE_PROTO_RSN				2
+//Added for notify the encryption type selection
+//   David, 2006.9.26
+#define IEEE_WPAX_USEGROUP			0
+#define IEEE_WPAX_WEP40				1
+#define IEEE_WPAX_TKIP				2
+#define IEEE_WPAX_WRAP   			3
+#define IEEE_WPAX_CCMP				4
+#define IEEE_WPAX_WEP104			5
+
+#define IEEE_KEY_MGMT_IEEE8021X			1
+#define IEEE_KEY_MGMT_PSK			2
+
+#define IEEE_MLME_STA_DEAUTH			1
+#define IEEE_MLME_STA_DISASSOC			2
+
+
+#define IEEE_CRYPT_ERR_UNKNOWN_ALG		2
+#define IEEE_CRYPT_ERR_UNKNOWN_ADDR		3
+#define IEEE_CRYPT_ERR_CRYPT_INIT_FAILED	4
+#define IEEE_CRYPT_ERR_KEY_SET_FAILED		5
+#define IEEE_CRYPT_ERR_TX_KEY_SET_FAILED	6
+#define IEEE_CRYPT_ERR_CARD_CONF_FAILED		7
+
+
+#define	IEEE_CRYPT_ALG_NAME_LEN			16
+
+#define MAX_IE_LEN  0xff
+
+// added for kernel conflict
+#define ieee80211_crypt_deinit_entries 	ieee80211_crypt_deinit_entries_rsl
+#define ieee80211_crypt_deinit_handler 	ieee80211_crypt_deinit_handler_rsl
+#define ieee80211_crypt_delayed_deinit 	ieee80211_crypt_delayed_deinit_rsl
+#define ieee80211_register_crypto_ops  	ieee80211_register_crypto_ops_rsl
+#define ieee80211_unregister_crypto_ops ieee80211_unregister_crypto_ops_rsl
+#define ieee80211_get_crypto_ops 	ieee80211_get_crypto_ops_rsl
+
+#define ieee80211_ccmp_null		ieee80211_ccmp_null_rsl
+
+#define ieee80211_tkip_null		ieee80211_tkip_null_rsl
+
+#define ieee80211_wep_null		ieee80211_wep_null_rsl
+
+#define free_ieee80211          	free_ieee80211_rsl
+#define alloc_ieee80211        		alloc_ieee80211_rsl
+
+#define ieee80211_rx 			ieee80211_rx_rsl
+#define ieee80211_rx_mgt		ieee80211_rx_mgt_rsl
+
+#define ieee80211_get_beacon		ieee80211_get_beacon_rsl
+#define ieee80211_wake_queue		ieee80211_wake_queue_rsl
+#define ieee80211_stop_queue		ieee80211_stop_queue_rsl
+#define ieee80211_reset_queue		ieee80211_reset_queue_rsl
+#define ieee80211_softmac_stop_protocol	ieee80211_softmac_stop_protocol_rsl
+#define ieee80211_softmac_start_protocol ieee80211_softmac_start_protocol_rsl
+#define ieee80211_is_shortslot		ieee80211_is_shortslot_rsl
+#define ieee80211_is_54g		ieee80211_is_54g_rsl
+#define ieee80211_wpa_supplicant_ioctl	ieee80211_wpa_supplicant_ioctl_rsl
+#define ieee80211_ps_tx_ack		ieee80211_ps_tx_ack_rsl
+#define ieee80211_softmac_xmit		ieee80211_softmac_xmit_rsl
+#define ieee80211_stop_send_beacons	ieee80211_stop_send_beacons_rsl
+#define notify_wx_assoc_event		notify_wx_assoc_event_rsl
+#define SendDisassociation		SendDisassociation_rsl
+#define ieee80211_disassociate		ieee80211_disassociate_rsl
+#define ieee80211_start_send_beacons	ieee80211_start_send_beacons_rsl
+#define ieee80211_stop_scan		ieee80211_stop_scan_rsl
+#define ieee80211_send_probe_requests	ieee80211_send_probe_requests_rsl
+#define ieee80211_softmac_scan_syncro	ieee80211_softmac_scan_syncro_rsl
+#define ieee80211_start_scan_syncro	ieee80211_start_scan_syncro_rsl
+
+#define ieee80211_wx_get_essid		ieee80211_wx_get_essid_rsl
+#define ieee80211_wx_set_essid		ieee80211_wx_set_essid_rsl
+#define ieee80211_wx_set_rate		ieee80211_wx_set_rate_rsl
+#define ieee80211_wx_get_rate		ieee80211_wx_get_rate_rsl
+#define ieee80211_wx_set_wap		ieee80211_wx_set_wap_rsl
+#define ieee80211_wx_get_wap		ieee80211_wx_get_wap_rsl
+#define ieee80211_wx_set_mode		ieee80211_wx_set_mode_rsl
+#define ieee80211_wx_get_mode		ieee80211_wx_get_mode_rsl
+#define ieee80211_wx_set_scan		ieee80211_wx_set_scan_rsl
+#define ieee80211_wx_get_freq		ieee80211_wx_get_freq_rsl
+#define ieee80211_wx_set_freq		ieee80211_wx_set_freq_rsl
+#define ieee80211_wx_set_rawtx		ieee80211_wx_set_rawtx_rsl
+#define ieee80211_wx_get_name		ieee80211_wx_get_name_rsl
+#define ieee80211_wx_set_power		ieee80211_wx_set_power_rsl
+#define ieee80211_wx_get_power		ieee80211_wx_get_power_rsl
+#define ieee80211_wlan_frequencies	ieee80211_wlan_frequencies_rsl
+#define ieee80211_wx_set_rts		ieee80211_wx_set_rts_rsl
+#define ieee80211_wx_get_rts		ieee80211_wx_get_rts_rsl
+
+#define ieee80211_txb_free		ieee80211_txb_free_rsl
+
+#define ieee80211_wx_set_gen_ie		ieee80211_wx_set_gen_ie_rsl
+#define ieee80211_wx_get_scan		ieee80211_wx_get_scan_rsl
+#define ieee80211_wx_set_encode		ieee80211_wx_set_encode_rsl
+#define ieee80211_wx_get_encode		ieee80211_wx_get_encode_rsl
+#if WIRELESS_EXT >= 18
+#define ieee80211_wx_set_mlme		ieee80211_wx_set_mlme_rsl
+#define ieee80211_wx_set_auth		ieee80211_wx_set_auth_rsl
+#define ieee80211_wx_set_encode_ext	ieee80211_wx_set_encode_ext_rsl
+#define ieee80211_wx_get_encode_ext	ieee80211_wx_get_encode_ext_rsl
+#endif
+
+
+typedef struct ieee_param {
+	u32 cmd;
+	u8 sta_addr[ETH_ALEN];
+        union {
+		struct {
+			u8 name;
+			u32 value;
+		} wpa_param;
+		struct {
+			u32 len;
+			u8 reserved[32];
+			u8 data[0];
+		} wpa_ie;
+	        struct{
+			int command;
+    			int reason_code;
+		} mlme;
+		struct {
+			u8 alg[IEEE_CRYPT_ALG_NAME_LEN];
+			u8 set_tx;
+			u32 err;
+			u8 idx;
+			u8 seq[8]; /* sequence counter (set: RX, get: TX) */
+			u16 key_len;
+			u8 key[0];
+		} crypt;
+	} u;
+}ieee_param;
+
+
+#if WIRELESS_EXT < 17
+#define IW_QUAL_QUAL_INVALID   0x10
+#define IW_QUAL_LEVEL_INVALID  0x20
+#define IW_QUAL_NOISE_INVALID  0x40
+#define IW_QUAL_QUAL_UPDATED   0x1
+#define IW_QUAL_LEVEL_UPDATED  0x2
+#define IW_QUAL_NOISE_UPDATED  0x4
+#endif
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+static inline void tq_init(struct tq_struct * task, void(*func)(void *), void *data)
+{
+	task->routine = func;
+	task->data 	= data;
+	//task->next = NULL;
+	INIT_LIST_HEAD(&task->list);
+	task->sync = 0;
+}
+#endif
+
+// linux under 2.6.9 release may not support it, so modify it for common use
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,9))
+//#define MSECS(t)	(1000 * ((t) / HZ) + 1000 * ((t) % HZ) / HZ)
+#define MSECS(t)	(HZ * ((t) / 1000) + (HZ * ((t) % 1000)) / 1000)
+static inline unsigned long msleep_interruptible_rsl(unsigned int msecs)
+{
+         unsigned long timeout = MSECS(msecs) + 1;
+
+         while (timeout) {
+                 set_current_state(TASK_INTERRUPTIBLE);
+                 timeout = schedule_timeout(timeout);
+         }
+         return timeout;
+}
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,4,31))
+static inline void msleep(unsigned int msecs)
+{
+         unsigned long timeout = MSECS(msecs) + 1;
+
+         while (timeout) {
+                 set_current_state(TASK_UNINTERRUPTIBLE);
+                 timeout = schedule_timeout(timeout);
+         }
+}
+#endif
+#else
+#define MSECS(t) msecs_to_jiffies(t)
+#define msleep_interruptible_rsl  msleep_interruptible
+#endif
+
+#define IEEE80211_DATA_LEN		2304
+/* Maximum size for the MA-UNITDATA primitive, 802.11 standard section
+   6.2.1.1.2.
+
+   The figure in section 7.1.2 suggests a body size of up to 2312
+   bytes is allowed, which is a bit confusing, I suspect this
+   represents the 2304 bytes of real data, plus a possible 8 bytes of
+   WEP IV and ICV. (this interpretation suggested by Ramiro Barreiro) */
+#define IEEE80211_1ADDR_LEN 10
+#define IEEE80211_2ADDR_LEN 16
+#define IEEE80211_3ADDR_LEN 24
+#define IEEE80211_4ADDR_LEN 30
+#define IEEE80211_FCS_LEN    4
+#define IEEE80211_HLEN                  (IEEE80211_4ADDR_LEN)
+#define IEEE80211_FRAME_LEN             (IEEE80211_DATA_LEN + IEEE80211_HLEN)
+#define IEEE80211_MGMT_HDR_LEN 24
+#define IEEE80211_DATA_HDR3_LEN 24
+#define IEEE80211_DATA_HDR4_LEN 30
+
+#define MIN_FRAG_THRESHOLD     256U
+#define MAX_FRAG_THRESHOLD     2346U
+
+
+/* Frame control field constants */
+#define IEEE80211_FCTL_VERS		0x0003
+#define IEEE80211_FCTL_FTYPE		0x000c
+#define IEEE80211_FCTL_STYPE		0x00f0
+#define IEEE80211_FCTL_FRAMETYPE	0x00fc
+#define IEEE80211_FCTL_TODS		0x0100
+#define IEEE80211_FCTL_FROMDS		0x0200
+#define IEEE80211_FCTL_DSTODS		0x0300 //added by david
+#define IEEE80211_FCTL_MOREFRAGS	0x0400
+#define IEEE80211_FCTL_RETRY		0x0800
+#define IEEE80211_FCTL_PM		0x1000
+#define IEEE80211_FCTL_MOREDATA		0x2000
+#define IEEE80211_FCTL_WEP		0x4000
+#define IEEE80211_FCTL_ORDER		0x8000
+
+#define IEEE80211_FTYPE_MGMT		0x0000
+#define IEEE80211_FTYPE_CTL		0x0004
+#define IEEE80211_FTYPE_DATA		0x0008
+
+/* management */
+#define IEEE80211_STYPE_ASSOC_REQ	0x0000
+#define IEEE80211_STYPE_ASSOC_RESP 	0x0010
+#define IEEE80211_STYPE_REASSOC_REQ	0x0020
+#define IEEE80211_STYPE_REASSOC_RESP	0x0030
+#define IEEE80211_STYPE_PROBE_REQ	0x0040
+#define IEEE80211_STYPE_PROBE_RESP	0x0050
+#define IEEE80211_STYPE_BEACON		0x0080
+#define IEEE80211_STYPE_ATIM		0x0090
+#define IEEE80211_STYPE_DISASSOC	0x00A0
+#define IEEE80211_STYPE_AUTH		0x00B0
+#define IEEE80211_STYPE_DEAUTH		0x00C0
+#define IEEE80211_STYPE_MANAGE_ACT	0x00D0
+
+/* control */
+#define IEEE80211_STYPE_PSPOLL		0x00A0
+#define IEEE80211_STYPE_RTS		0x00B0
+#define IEEE80211_STYPE_CTS		0x00C0
+#define IEEE80211_STYPE_ACK		0x00D0
+#define IEEE80211_STYPE_CFEND		0x00E0
+#define IEEE80211_STYPE_CFENDACK	0x00F0
+#define IEEE80211_STYPE_BLOCKACK   0x0094
+
+/* data */
+#define IEEE80211_STYPE_DATA		0x0000
+#define IEEE80211_STYPE_DATA_CFACK	0x0010
+#define IEEE80211_STYPE_DATA_CFPOLL	0x0020
+#define IEEE80211_STYPE_DATA_CFACKPOLL	0x0030
+#define IEEE80211_STYPE_NULLFUNC	0x0040
+#define IEEE80211_STYPE_CFACK		0x0050
+#define IEEE80211_STYPE_CFPOLL		0x0060
+#define IEEE80211_STYPE_CFACKPOLL	0x0070
+#define IEEE80211_STYPE_QOS_DATA	0x0080 //added for WMM 2006/8/2
+#define IEEE80211_STYPE_QOS_NULL	0x00C0
+
+#define IEEE80211_SCTL_FRAG		0x000F
+#define IEEE80211_SCTL_SEQ		0xFFF0
+
+/* QOS control */
+#define IEEE80211_QCTL_TID              0x000F
+
+#define	FC_QOS_BIT					BIT7
+#define IsDataFrame(pdu)			( ((pdu[0] & 0x0C)==0x08) ? true : false )
+#define	IsLegacyDataFrame(pdu)	(IsDataFrame(pdu) && (!(pdu[0]&FC_QOS_BIT)) )
+//added by wb. Is this right?
+#define IsQoSDataFrame(pframe)  ((*(u16*)pframe&(IEEE80211_STYPE_QOS_DATA|IEEE80211_FTYPE_DATA)) == (IEEE80211_STYPE_QOS_DATA|IEEE80211_FTYPE_DATA))
+#define Frame_Order(pframe)     (*(u16*)pframe&IEEE80211_FCTL_ORDER)
+#define SN_LESS(a, b)		(((a-b)&0x800)!=0)
+#define SN_EQUAL(a, b)	(a == b)
+#define MAX_DEV_ADDR_SIZE 8
+typedef enum _ACT_CATEGORY{
+        ACT_CAT_QOS = 1,
+        ACT_CAT_DLS = 2,
+        ACT_CAT_BA  = 3,
+        ACT_CAT_HT  = 7,
+        ACT_CAT_WMM = 17,
+} ACT_CATEGORY, *PACT_CATEGORY;
+
+typedef enum _TS_ACTION{
+        ACT_ADDTSREQ = 0,
+        ACT_ADDTSRSP = 1,
+        ACT_DELTS    = 2,
+        ACT_SCHEDULE = 3,
+} TS_ACTION, *PTS_ACTION;
+
+typedef enum _BA_ACTION{
+        ACT_ADDBAREQ = 0,
+        ACT_ADDBARSP = 1,
+        ACT_DELBA    = 2,
+} BA_ACTION, *PBA_ACTION;
+
+typedef enum _InitialGainOpType{
+	IG_Backup=0,
+	IG_Restore,
+	IG_Max
+}InitialGainOpType;
+//added by amy for LED 090319
+//================================================================================
+// LED customization.
+//================================================================================
+typedef enum _LED_CTL_MODE{
+        LED_CTL_POWER_ON = 1,
+        LED_CTL_LINK = 2,
+        LED_CTL_NO_LINK = 3,
+        LED_CTL_TX = 4,
+        LED_CTL_RX = 5,
+        LED_CTL_SITE_SURVEY = 6,
+        LED_CTL_POWER_OFF = 7,
+        LED_CTL_START_TO_LINK = 8,
+        LED_CTL_START_WPS = 9,
+        LED_CTL_STOP_WPS = 10,
+        LED_CTL_START_WPS_BOTTON = 11, //added for runtop
+}LED_CTL_MODE;
+
+/* debug macros */
+#define CONFIG_IEEE80211_DEBUG
+#ifdef CONFIG_IEEE80211_DEBUG
+extern u32 ieee80211_debug_level;
+#define IEEE80211_DEBUG(level, fmt, args...) \
+do { if (ieee80211_debug_level & (level)) \
+  printk(KERN_DEBUG "ieee80211: " fmt, ## args); } while (0)
+//wb added to debug out data buf
+//if you want print DATA buffer related BA, please set ieee80211_debug_level to DATA|BA
+#define IEEE80211_DEBUG_DATA(level, data, datalen)	\
+	do{ if ((ieee80211_debug_level & (level)) == (level))	\
+		{ 	\
+			int i;					\
+			u8* pdata = (u8*) data;			\
+			printk(KERN_DEBUG "ieee80211: %s()\n", __FUNCTION__);	\
+			for(i=0; i<(int)(datalen); i++)			\
+			{						\
+				printk("%2x ", pdata[i]);		\
+				if ((i+1)%16 == 0) printk("\n");	\
+			}				\
+			printk("\n");			\
+		}					\
+	} while (0)
+#else
+#define IEEE80211_DEBUG(level, fmt, args...) do {} while (0)
+#define IEEE80211_DEBUG_DATA(level, data, datalen) do {} while(0)
+#endif	/* CONFIG_IEEE80211_DEBUG */
+
+/* debug macros not dependent on CONFIG_IEEE80211_DEBUG */
+
+#define MAC_FMT "%02x:%02x:%02x:%02x:%02x:%02x"
+#define MAC_ARG(x) ((u8*)(x))[0],((u8*)(x))[1],((u8*)(x))[2],((u8*)(x))[3],((u8*)(x))[4],((u8*)(x))[5]
+
+/*
+ * To use the debug system;
+ *
+ * If you are defining a new debug classification, simply add it to the #define
+ * list here in the form of:
+ *
+ * #define IEEE80211_DL_xxxx VALUE
+ *
+ * shifting value to the left one bit from the previous entry.  xxxx should be
+ * the name of the classification (for example, WEP)
+ *
+ * You then need to either add a IEEE80211_xxxx_DEBUG() macro definition for your
+ * classification, or use IEEE80211_DEBUG(IEEE80211_DL_xxxx, ...) whenever you want
+ * to send output to that classification.
+ *
+ * To add your debug level to the list of levels seen when you perform
+ *
+ * % cat /proc/net/ipw/debug_level
+ *
+ * you simply need to add your entry to the ipw_debug_levels array.
+ *
+ * If you do not see debug_level in /proc/net/ipw then you do not have
+ * CONFIG_IEEE80211_DEBUG defined in your kernel configuration
+ *
+ */
+
+#define IEEE80211_DL_INFO          (1<<0)
+#define IEEE80211_DL_WX            (1<<1)
+#define IEEE80211_DL_SCAN          (1<<2)
+#define IEEE80211_DL_STATE         (1<<3)
+#define IEEE80211_DL_MGMT          (1<<4)
+#define IEEE80211_DL_FRAG          (1<<5)
+#define IEEE80211_DL_EAP           (1<<6)
+#define IEEE80211_DL_DROP          (1<<7)
+
+#define IEEE80211_DL_TX            (1<<8)
+#define IEEE80211_DL_RX            (1<<9)
+
+#define IEEE80211_DL_HT		   (1<<10)  //HT
+#define IEEE80211_DL_BA		   (1<<11)  //ba
+#define IEEE80211_DL_TS		   (1<<12)  //TS
+#define IEEE80211_DL_QOS           (1<<13)
+#define IEEE80211_DL_REORDER	   (1<<14)
+#define IEEE80211_DL_IOT	   (1<<15)
+#define IEEE80211_DL_IPS	   (1<<16)
+#define IEEE80211_DL_TRACE	   (1<<29)  //trace function, need to user net_ratelimit() together in order not to print too much to the screen
+#define IEEE80211_DL_DATA	   (1<<30)   //use this flag to control whether print data buf out.
+#define IEEE80211_DL_ERR	   (1<<31)   //always open
+#define IEEE80211_ERROR(f, a...) printk(KERN_ERR "ieee80211: " f, ## a)
+#define IEEE80211_WARNING(f, a...) printk(KERN_WARNING "ieee80211: " f, ## a)
+#define IEEE80211_DEBUG_INFO(f, a...)   IEEE80211_DEBUG(IEEE80211_DL_INFO, f, ## a)
+
+#define IEEE80211_DEBUG_WX(f, a...)     IEEE80211_DEBUG(IEEE80211_DL_WX, f, ## a)
+#define IEEE80211_DEBUG_SCAN(f, a...)   IEEE80211_DEBUG(IEEE80211_DL_SCAN, f, ## a)
+#define IEEE80211_DEBUG_STATE(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_STATE, f, ## a)
+#define IEEE80211_DEBUG_MGMT(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_MGMT, f, ## a)
+#define IEEE80211_DEBUG_FRAG(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_FRAG, f, ## a)
+#define IEEE80211_DEBUG_EAP(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_EAP, f, ## a)
+#define IEEE80211_DEBUG_DROP(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_DROP, f, ## a)
+#define IEEE80211_DEBUG_TX(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_TX, f, ## a)
+#define IEEE80211_DEBUG_RX(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_RX, f, ## a)
+#define IEEE80211_DEBUG_QOS(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_QOS, f, ## a)
+
+#ifdef CONFIG_IEEE80211_DEBUG
+/* Added by Annie, 2005-11-22. */
+#define MAX_STR_LEN     64
+/* I want to see ASCII 33 to 126 only. Otherwise, I print '?'. Annie, 2005-11-22.*/
+#define PRINTABLE(_ch)  (_ch>'!' && _ch<'~')
+#define IEEE80211_PRINT_STR(_Comp, _TitleString, _Ptr, _Len)                            	\
+                        if((_Comp) & level)   							\
+                        {                                                                       \
+                                int             __i;                                            \
+                                u8  buffer[MAX_STR_LEN];                                    	\
+                                int length = (_Len<MAX_STR_LEN)? _Len : (MAX_STR_LEN-1) ;  	\
+                                memset(buffer, 0, MAX_STR_LEN);                      		\
+                                memcpy(buffer, (u8 *)_Ptr, length );            		\
+                                for( __i=0; __i<MAX_STR_LEN; __i++ )                            \
+                                {                                                               \
+                                     if( !PRINTABLE(buffer[__i]) )   buffer[__i] = '?';     	\
+                                }                                                               \
+                                buffer[length] = '\0';                                          \
+                                printk("Rtl819x: ");                                         	\
+                                printk(_TitleString);                                         \
+                                printk(": %d, <%s>\n", _Len, buffer);                         \
+                        }
+#else
+#define IEEE80211_PRINT_STR(_Comp, _TitleString, _Ptr, _Len)  do {} while (0)
+#endif
+
+#include <linux/netdevice.h>
+#include <linux/if_arp.h> /* ARPHRD_ETHER */
+
+#ifndef WIRELESS_SPY
+#define WIRELESS_SPY		// enable iwspy support
+#endif
+#include <net/iw_handler.h>	// new driver API
+
+#ifndef ETH_P_PAE
+#define ETH_P_PAE 0x888E /* Port Access Entity (IEEE 802.1X) */
+#endif /* ETH_P_PAE */
+
+#define ETH_P_PREAUTH 0x88C7 /* IEEE 802.11i pre-authentication */
+
+#ifndef ETH_P_80211_RAW
+#define ETH_P_80211_RAW (ETH_P_ECONET + 1)
+#endif
+
+/* IEEE 802.11 defines */
+
+#define P80211_OUI_LEN 3
+
+struct ieee80211_snap_hdr {
+
+        u8    dsap;   /* always 0xAA */
+        u8    ssap;   /* always 0xAA */
+        u8    ctrl;   /* always 0x03 */
+        u8    oui[P80211_OUI_LEN];    /* organizational universal id */
+
+} __attribute__ ((packed));
+
+#define SNAP_SIZE sizeof(struct ieee80211_snap_hdr)
+
+#define WLAN_FC_GET_VERS(fc) ((fc) & IEEE80211_FCTL_VERS)
+#define WLAN_FC_GET_TYPE(fc) ((fc) & IEEE80211_FCTL_FTYPE)
+#define WLAN_FC_GET_STYPE(fc) ((fc) & IEEE80211_FCTL_STYPE)
+
+#define WLAN_FC_GET_FRAMETYPE(fc) ((fc) & IEEE80211_FCTL_FRAMETYPE)
+#define WLAN_GET_SEQ_FRAG(seq) ((seq) & IEEE80211_SCTL_FRAG)
+#define WLAN_GET_SEQ_SEQ(seq)  (((seq) & IEEE80211_SCTL_SEQ) >> 4)
+
+/* Authentication algorithms */
+#define WLAN_AUTH_OPEN 0
+#define WLAN_AUTH_SHARED_KEY 1
+#define WLAN_AUTH_LEAP 2
+
+#define WLAN_AUTH_CHALLENGE_LEN 128
+
+#define WLAN_CAPABILITY_BSS (1<<0)
+#define WLAN_CAPABILITY_IBSS (1<<1)
+#define WLAN_CAPABILITY_CF_POLLABLE (1<<2)
+#define WLAN_CAPABILITY_CF_POLL_REQUEST (1<<3)
+#define WLAN_CAPABILITY_PRIVACY (1<<4)
+#define WLAN_CAPABILITY_SHORT_PREAMBLE (1<<5)
+#define WLAN_CAPABILITY_PBCC (1<<6)
+#define WLAN_CAPABILITY_CHANNEL_AGILITY (1<<7)
+#define WLAN_CAPABILITY_SPECTRUM_MGMT (1<<8)
+#define WLAN_CAPABILITY_QOS (1<<9)
+#define WLAN_CAPABILITY_SHORT_SLOT (1<<10)
+#define WLAN_CAPABILITY_DSSS_OFDM (1<<13)
+
+/* 802.11g ERP information element */
+#define WLAN_ERP_NON_ERP_PRESENT (1<<0)
+#define WLAN_ERP_USE_PROTECTION (1<<1)
+#define WLAN_ERP_BARKER_PREAMBLE (1<<2)
+
+/* Status codes */
+enum ieee80211_statuscode {
+        WLAN_STATUS_SUCCESS = 0,
+        WLAN_STATUS_UNSPECIFIED_FAILURE = 1,
+        WLAN_STATUS_CAPS_UNSUPPORTED = 10,
+        WLAN_STATUS_REASSOC_NO_ASSOC = 11,
+        WLAN_STATUS_ASSOC_DENIED_UNSPEC = 12,
+        WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG = 13,
+        WLAN_STATUS_UNKNOWN_AUTH_TRANSACTION = 14,
+        WLAN_STATUS_CHALLENGE_FAIL = 15,
+        WLAN_STATUS_AUTH_TIMEOUT = 16,
+        WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA = 17,
+        WLAN_STATUS_ASSOC_DENIED_RATES = 18,
+        /* 802.11b */
+        WLAN_STATUS_ASSOC_DENIED_NOSHORTPREAMBLE = 19,
+        WLAN_STATUS_ASSOC_DENIED_NOPBCC = 20,
+        WLAN_STATUS_ASSOC_DENIED_NOAGILITY = 21,
+        /* 802.11h */
+        WLAN_STATUS_ASSOC_DENIED_NOSPECTRUM = 22,
+        WLAN_STATUS_ASSOC_REJECTED_BAD_POWER = 23,
+        WLAN_STATUS_ASSOC_REJECTED_BAD_SUPP_CHAN = 24,
+        /* 802.11g */
+        WLAN_STATUS_ASSOC_DENIED_NOSHORTTIME = 25,
+        WLAN_STATUS_ASSOC_DENIED_NODSSSOFDM = 26,
+        /* 802.11i */
+        WLAN_STATUS_INVALID_IE = 40,
+        WLAN_STATUS_INVALID_GROUP_CIPHER = 41,
+        WLAN_STATUS_INVALID_PAIRWISE_CIPHER = 42,
+        WLAN_STATUS_INVALID_AKMP = 43,
+        WLAN_STATUS_UNSUPP_RSN_VERSION = 44,
+        WLAN_STATUS_INVALID_RSN_IE_CAP = 45,
+        WLAN_STATUS_CIPHER_SUITE_REJECTED = 46,
+};
+
+/* Reason codes */
+enum ieee80211_reasoncode {
+        WLAN_REASON_UNSPECIFIED = 1,
+        WLAN_REASON_PREV_AUTH_NOT_VALID = 2,
+        WLAN_REASON_DEAUTH_LEAVING = 3,
+        WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY = 4,
+        WLAN_REASON_DISASSOC_AP_BUSY = 5,
+        WLAN_REASON_CLASS2_FRAME_FROM_NONAUTH_STA = 6,
+        WLAN_REASON_CLASS3_FRAME_FROM_NONASSOC_STA = 7,
+        WLAN_REASON_DISASSOC_STA_HAS_LEFT = 8,
+        WLAN_REASON_STA_REQ_ASSOC_WITHOUT_AUTH = 9,
+        /* 802.11h */
+        WLAN_REASON_DISASSOC_BAD_POWER = 10,
+        WLAN_REASON_DISASSOC_BAD_SUPP_CHAN = 11,
+        /* 802.11i */
+        WLAN_REASON_INVALID_IE = 13,
+        WLAN_REASON_MIC_FAILURE = 14,
+        WLAN_REASON_4WAY_HANDSHAKE_TIMEOUT = 15,
+        WLAN_REASON_GROUP_KEY_HANDSHAKE_TIMEOUT = 16,
+        WLAN_REASON_IE_DIFFERENT = 17,
+        WLAN_REASON_INVALID_GROUP_CIPHER = 18,
+        WLAN_REASON_INVALID_PAIRWISE_CIPHER = 19,
+        WLAN_REASON_INVALID_AKMP = 20,
+        WLAN_REASON_UNSUPP_RSN_VERSION = 21,
+        WLAN_REASON_INVALID_RSN_IE_CAP = 22,
+        WLAN_REASON_IEEE8021X_FAILED = 23,
+        WLAN_REASON_CIPHER_SUITE_REJECTED = 24,
+};
+
+#define IEEE80211_STATMASK_SIGNAL (1<<0)
+#define IEEE80211_STATMASK_RSSI (1<<1)
+#define IEEE80211_STATMASK_NOISE (1<<2)
+#define IEEE80211_STATMASK_RATE (1<<3)
+#define IEEE80211_STATMASK_WEMASK 0x7
+
+#define IEEE80211_CCK_MODULATION    (1<<0)
+#define IEEE80211_OFDM_MODULATION   (1<<1)
+
+#define IEEE80211_24GHZ_BAND     (1<<0)
+#define IEEE80211_52GHZ_BAND     (1<<1)
+
+#define IEEE80211_CCK_RATE_LEN  		4
+#define IEEE80211_CCK_RATE_1MB		        0x02
+#define IEEE80211_CCK_RATE_2MB		        0x04
+#define IEEE80211_CCK_RATE_5MB		        0x0B
+#define IEEE80211_CCK_RATE_11MB		        0x16
+#define IEEE80211_OFDM_RATE_LEN 		8
+#define IEEE80211_OFDM_RATE_6MB		        0x0C
+#define IEEE80211_OFDM_RATE_9MB		        0x12
+#define IEEE80211_OFDM_RATE_12MB		0x18
+#define IEEE80211_OFDM_RATE_18MB		0x24
+#define IEEE80211_OFDM_RATE_24MB		0x30
+#define IEEE80211_OFDM_RATE_36MB		0x48
+#define IEEE80211_OFDM_RATE_48MB		0x60
+#define IEEE80211_OFDM_RATE_54MB		0x6C
+#define IEEE80211_BASIC_RATE_MASK		0x80
+
+#define IEEE80211_CCK_RATE_1MB_MASK		(1<<0)
+#define IEEE80211_CCK_RATE_2MB_MASK		(1<<1)
+#define IEEE80211_CCK_RATE_5MB_MASK		(1<<2)
+#define IEEE80211_CCK_RATE_11MB_MASK		(1<<3)
+#define IEEE80211_OFDM_RATE_6MB_MASK		(1<<4)
+#define IEEE80211_OFDM_RATE_9MB_MASK		(1<<5)
+#define IEEE80211_OFDM_RATE_12MB_MASK		(1<<6)
+#define IEEE80211_OFDM_RATE_18MB_MASK		(1<<7)
+#define IEEE80211_OFDM_RATE_24MB_MASK		(1<<8)
+#define IEEE80211_OFDM_RATE_36MB_MASK		(1<<9)
+#define IEEE80211_OFDM_RATE_48MB_MASK		(1<<10)
+#define IEEE80211_OFDM_RATE_54MB_MASK		(1<<11)
+
+#define IEEE80211_CCK_RATES_MASK	        0x0000000F
+#define IEEE80211_CCK_BASIC_RATES_MASK	(IEEE80211_CCK_RATE_1MB_MASK | \
+	IEEE80211_CCK_RATE_2MB_MASK)
+#define IEEE80211_CCK_DEFAULT_RATES_MASK	(IEEE80211_CCK_BASIC_RATES_MASK | \
+        IEEE80211_CCK_RATE_5MB_MASK | \
+        IEEE80211_CCK_RATE_11MB_MASK)
+
+#define IEEE80211_OFDM_RATES_MASK		0x00000FF0
+#define IEEE80211_OFDM_BASIC_RATES_MASK	(IEEE80211_OFDM_RATE_6MB_MASK | \
+	IEEE80211_OFDM_RATE_12MB_MASK | \
+	IEEE80211_OFDM_RATE_24MB_MASK)
+#define IEEE80211_OFDM_DEFAULT_RATES_MASK	(IEEE80211_OFDM_BASIC_RATES_MASK | \
+	IEEE80211_OFDM_RATE_9MB_MASK  | \
+	IEEE80211_OFDM_RATE_18MB_MASK | \
+	IEEE80211_OFDM_RATE_36MB_MASK | \
+	IEEE80211_OFDM_RATE_48MB_MASK | \
+	IEEE80211_OFDM_RATE_54MB_MASK)
+#define IEEE80211_DEFAULT_RATES_MASK (IEEE80211_OFDM_DEFAULT_RATES_MASK | \
+                                IEEE80211_CCK_DEFAULT_RATES_MASK)
+
+#define IEEE80211_NUM_OFDM_RATES	    8
+#define IEEE80211_NUM_CCK_RATES	            4
+#define IEEE80211_OFDM_SHIFT_MASK_A         4
+
+
+/* this is stolen and modified from the madwifi driver*/
+#define IEEE80211_FC0_TYPE_MASK		0x0c
+#define IEEE80211_FC0_TYPE_DATA		0x08
+#define IEEE80211_FC0_SUBTYPE_MASK	0xB0
+#define IEEE80211_FC0_SUBTYPE_QOS	0x80
+
+#define IEEE80211_QOS_HAS_SEQ(fc) \
+	(((fc) & (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) == \
+	 (IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_QOS))
+
+/* this is stolen from ipw2200 driver */
+#define IEEE_IBSS_MAC_HASH_SIZE 31
+struct ieee_ibss_seq {
+	u8 mac[ETH_ALEN];
+	u16 seq_num[17];
+	u16 frag_num[17];
+	unsigned long packet_time[17];
+	struct list_head list;
+};
+
+/* NOTE: This data is for statistical purposes; not all hardware provides this
+ *       information for frames received.  Not setting these will not cause
+ *       any adverse affects. */
+struct ieee80211_rx_stats {
+#if 1
+	u32 mac_time[2];
+	s8 rssi;
+	u8 signal;
+	u8 noise;
+	u16 rate; /* in 100 kbps */
+	u8 received_channel;
+	u8 control;
+	u8 mask;
+	u8 freq;
+	u16 len;
+	u64 tsf;
+	u32 beacon_time;
+	u8 nic_type;
+	u16       Length;
+	//      u8        DataRate;      // In 0.5 Mbps
+	u8        SignalQuality; // in 0-100 index.
+	s32       RecvSignalPower; // Real power in dBm for this packet, no beautification and aggregation.
+	s8        RxPower; // in dBm Translate from PWdB
+	u8        SignalStrength; // in 0-100 index.
+	u16       bHwError:1;
+	u16       bCRC:1;
+	u16       bICV:1;
+	u16       bShortPreamble:1;
+	u16       Antenna:1;      //for rtl8185
+	u16       Decrypted:1;    //for rtl8185, rtl8187
+	u16       Wakeup:1;       //for rtl8185
+	u16       Reserved0:1;    //for rtl8185
+	u8        AGC;
+	u32       TimeStampLow;
+	u32       TimeStampHigh;
+	bool      bShift;
+	bool      bIsQosData;             // Added by Annie, 2005-12-22.
+	u8        UserPriority;
+
+	//1!!!!!!!!!!!!!!!!!!!!!!!!!!!
+	//1Attention Please!!!<11n or 8190 specific code should be put below this line>
+	//1!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+	u8        RxDrvInfoSize;
+	u8        RxBufShift;
+	bool      bIsAMPDU;
+	bool      bFirstMPDU;
+	bool      bContainHTC;
+	bool      RxIs40MHzPacket;
+	u32       RxPWDBAll;
+	u8        RxMIMOSignalStrength[4];        // in 0~100 index
+	s8        RxMIMOSignalQuality[2];
+	bool      bPacketMatchBSSID;
+	bool      bIsCCK;
+	bool      bPacketToSelf;
+	//added by amy
+	u8*       virtual_address;
+	u16          packetlength;              // Total packet length: Must equal to sum of all FragLength
+	u16          fraglength;                        // FragLength should equal to PacketLength in non-fragment case
+	u16          fragoffset;                        // Data offset for this fragment
+	u16          ntotalfrag;
+	bool      	  bisrxaggrsubframe;
+	bool		  bPacketBeacon;	//cosa add for rssi
+	bool		  bToSelfBA;		//cosa add for rssi
+	char 	  cck_adc_pwdb[4];	//cosa add for rx path selection
+	u16		  Seq_Num;
+	u8		nTotalAggPkt;		// Number of aggregated packets.
+#endif
+
+};
+
+/* IEEE 802.11 requires that STA supports concurrent reception of at least
+ * three fragmented frames. This define can be increased to support more
+ * concurrent frames, but it should be noted that each entry can consume about
+ * 2 kB of RAM and increasing cache size will slow down frame reassembly. */
+#define IEEE80211_FRAG_CACHE_LEN 4
+
+struct ieee80211_frag_entry {
+	unsigned long first_frag_time;
+	unsigned int seq;
+	unsigned int last_frag;
+	struct sk_buff *skb;
+	u8 src_addr[ETH_ALEN];
+	u8 dst_addr[ETH_ALEN];
+};
+
+struct ieee80211_stats {
+	unsigned int tx_unicast_frames;
+	unsigned int tx_multicast_frames;
+	unsigned int tx_fragments;
+	unsigned int tx_unicast_octets;
+	unsigned int tx_multicast_octets;
+	unsigned int tx_deferred_transmissions;
+	unsigned int tx_single_retry_frames;
+	unsigned int tx_multiple_retry_frames;
+	unsigned int tx_retry_limit_exceeded;
+	unsigned int tx_discards;
+	unsigned int rx_unicast_frames;
+	unsigned int rx_multicast_frames;
+	unsigned int rx_fragments;
+	unsigned int rx_unicast_octets;
+	unsigned int rx_multicast_octets;
+	unsigned int rx_fcs_errors;
+	unsigned int rx_discards_no_buffer;
+	unsigned int tx_discards_wrong_sa;
+	unsigned int rx_discards_undecryptable;
+	unsigned int rx_message_in_msg_fragments;
+	unsigned int rx_message_in_bad_msg_fragments;
+};
+
+struct ieee80211_device;
+
+#include "ieee80211_crypt.h"
+
+#define SEC_KEY_1         (1<<0)
+#define SEC_KEY_2         (1<<1)
+#define SEC_KEY_3         (1<<2)
+#define SEC_KEY_4         (1<<3)
+#define SEC_ACTIVE_KEY    (1<<4)
+#define SEC_AUTH_MODE     (1<<5)
+#define SEC_UNICAST_GROUP (1<<6)
+#define SEC_LEVEL         (1<<7)
+#define SEC_ENABLED       (1<<8)
+#define SEC_ENCRYPT       (1<<9)
+
+#define SEC_LEVEL_0      0 /* None */
+#define SEC_LEVEL_1      1 /* WEP 40 and 104 bit */
+#define SEC_LEVEL_2      2 /* Level 1 + TKIP */
+#define SEC_LEVEL_2_CKIP 3 /* Level 1 + CKIP */
+#define SEC_LEVEL_3      4 /* Level 2 + CCMP */
+
+#define SEC_ALG_NONE            0
+#define SEC_ALG_WEP             1
+#define SEC_ALG_TKIP            2
+#define SEC_ALG_CCMP            3
+
+#define WEP_KEYS 		4
+#define WEP_KEY_LEN		13
+#define SCM_KEY_LEN             32
+#define SCM_TEMPORAL_KEY_LENGTH 16
+
+struct ieee80211_security {
+	u16 active_key:2,
+            enabled:1,
+	    auth_mode:2,
+            auth_algo:4,
+            unicast_uses_group:1,
+	    encrypt:1;
+	u8 key_sizes[WEP_KEYS];
+	u8 keys[WEP_KEYS][SCM_KEY_LEN];
+	u8 level;
+	u16 flags;
+} __attribute__ ((packed));
+
+
+/*
+ 802.11 data frame from AP
+      ,-------------------------------------------------------------------.
+Bytes |  2   |  2   |    6    |    6    |    6    |  2   | 0..2312 |   4  |
+      |------|------|---------|---------|---------|------|---------|------|
+Desc. | ctrl | dura |  DA/RA  |   TA    |    SA   | Sequ |  frame  |  fcs |
+      |      | tion | (BSSID) |         |         | ence |  data   |      |
+      `-------------------------------------------------------------------'
+Total: 28-2340 bytes
+*/
+
+/* Management Frame Information Element Types */
+enum ieee80211_mfie {
+        MFIE_TYPE_SSID = 0,
+        MFIE_TYPE_RATES = 1,
+        MFIE_TYPE_FH_SET = 2,
+        MFIE_TYPE_DS_SET = 3,
+        MFIE_TYPE_CF_SET = 4,
+        MFIE_TYPE_TIM = 5,
+        MFIE_TYPE_IBSS_SET = 6,
+        MFIE_TYPE_COUNTRY = 7,
+        MFIE_TYPE_HOP_PARAMS = 8,
+        MFIE_TYPE_HOP_TABLE = 9,
+        MFIE_TYPE_REQUEST = 10,
+        MFIE_TYPE_CHALLENGE = 16,
+        MFIE_TYPE_POWER_CONSTRAINT = 32,
+        MFIE_TYPE_POWER_CAPABILITY = 33,
+        MFIE_TYPE_TPC_REQUEST = 34,
+        MFIE_TYPE_TPC_REPORT = 35,
+        MFIE_TYPE_SUPP_CHANNELS = 36,
+        MFIE_TYPE_CSA = 37,
+        MFIE_TYPE_MEASURE_REQUEST = 38,
+        MFIE_TYPE_MEASURE_REPORT = 39,
+        MFIE_TYPE_QUIET = 40,
+        MFIE_TYPE_IBSS_DFS = 41,
+        MFIE_TYPE_ERP = 42,
+        MFIE_TYPE_RSN = 48,
+        MFIE_TYPE_RATES_EX = 50,
+        MFIE_TYPE_HT_CAP= 45,
+	 MFIE_TYPE_HT_INFO= 61,
+	 MFIE_TYPE_AIRONET=133,
+        MFIE_TYPE_GENERIC = 221,
+        MFIE_TYPE_QOS_PARAMETER = 222,
+};
+
+/* Minimal header; can be used for passing 802.11 frames with sufficient
+ * information to determine what type of underlying data type is actually
+ * stored in the data. */
+struct ieee80211_hdr {
+        __le16 frame_ctl;
+        __le16 duration_id;
+        u8 payload[0];
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_1addr {
+        __le16 frame_ctl;
+        __le16 duration_id;
+        u8 addr1[ETH_ALEN];
+        u8 payload[0];
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_2addr {
+        __le16 frame_ctl;
+        __le16 duration_id;
+        u8 addr1[ETH_ALEN];
+        u8 addr2[ETH_ALEN];
+        u8 payload[0];
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_3addr {
+	__le16 frame_ctl;
+	__le16 duration_id;
+	u8 addr1[ETH_ALEN];
+	u8 addr2[ETH_ALEN];
+	u8 addr3[ETH_ALEN];
+	__le16 seq_ctl;
+        u8 payload[0];
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_4addr {
+	__le16 frame_ctl;
+	__le16 duration_id;
+	u8 addr1[ETH_ALEN];
+	u8 addr2[ETH_ALEN];
+	u8 addr3[ETH_ALEN];
+	__le16 seq_ctl;
+	u8 addr4[ETH_ALEN];
+        u8 payload[0];
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_3addrqos {
+	__le16 frame_ctl;
+	__le16 duration_id;
+	u8 addr1[ETH_ALEN];
+	u8 addr2[ETH_ALEN];
+	u8 addr3[ETH_ALEN];
+	__le16 seq_ctl;
+        u8 payload[0];
+	__le16 qos_ctl;
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_4addrqos {
+	__le16 frame_ctl;
+	__le16 duration_id;
+	u8 addr1[ETH_ALEN];
+	u8 addr2[ETH_ALEN];
+	u8 addr3[ETH_ALEN];
+	__le16 seq_ctl;
+	u8 addr4[ETH_ALEN];
+        u8 payload[0];
+	__le16 qos_ctl;
+} __attribute__ ((packed));
+
+struct ieee80211_info_element {
+	u8 id;
+	u8 len;
+	u8 data[0];
+} __attribute__ ((packed));
+
+struct ieee80211_authentication {
+	struct ieee80211_hdr_3addr header;
+	__le16 algorithm;
+	__le16 transaction;
+	__le16 status;
+	/*challenge*/
+	struct ieee80211_info_element info_element[0];
+} __attribute__ ((packed));
+
+struct ieee80211_disassoc {
+        struct ieee80211_hdr_3addr header;
+        __le16 reason;
+} __attribute__ ((packed));
+
+struct ieee80211_probe_request {
+	struct ieee80211_hdr_3addr header;
+	/* SSID, supported rates */
+        struct ieee80211_info_element info_element[0];
+} __attribute__ ((packed));
+
+struct ieee80211_probe_response {
+	struct ieee80211_hdr_3addr header;
+	u32 time_stamp[2];
+	__le16 beacon_interval;
+	__le16 capability;
+        /* SSID, supported rates, FH params, DS params,
+         * CF params, IBSS params, TIM (if beacon), RSN */
+        struct ieee80211_info_element info_element[0];
+} __attribute__ ((packed));
+
+/* Alias beacon for probe_response */
+#define ieee80211_beacon ieee80211_probe_response
+
+struct ieee80211_assoc_request_frame {
+	struct ieee80211_hdr_3addr header;
+	__le16 capability;
+	__le16 listen_interval;
+	/* SSID, supported rates, RSN */
+        struct ieee80211_info_element info_element[0];
+} __attribute__ ((packed));
+
+struct ieee80211_reassoc_request_frame {
+	struct ieee80211_hdr_3addr header;
+	__le16 capability;
+	__le16 listen_interval;
+	u8 current_ap[ETH_ALEN];
+	/* SSID, supported rates, RSN */
+        struct ieee80211_info_element info_element[0];
+} __attribute__ ((packed));
+
+struct ieee80211_assoc_response_frame {
+	struct ieee80211_hdr_3addr header;
+	__le16 capability;
+	__le16 status;
+	__le16 aid;
+	struct ieee80211_info_element info_element[0]; /* supported rates */
+} __attribute__ ((packed));
+
+struct ieee80211_txb {
+	u8 nr_frags;
+	u8 encrypted;
+	u8 queue_index;
+	u8 rts_included;
+	u16 reserved;
+	__le16 frag_size;
+	__le16 payload_size;
+	struct sk_buff *fragments[0];
+};
+
+#define MAX_TX_AGG_COUNT		  16
+struct ieee80211_drv_agg_txb {
+	u8 nr_drv_agg_frames;
+	struct sk_buff *tx_agg_frames[MAX_TX_AGG_COUNT];
+}__attribute__((packed));
+
+#define MAX_SUBFRAME_COUNT 		  64
+struct ieee80211_rxb {
+	u8 nr_subframes;
+	struct sk_buff *subframes[MAX_SUBFRAME_COUNT];
+	u8 dst[ETH_ALEN];
+	u8 src[ETH_ALEN];
+}__attribute__((packed));
+
+typedef union _frameqos {
+	u16 shortdata;
+	u8  chardata[2];
+	struct {
+		u16 tid:4;
+		u16 eosp:1;
+		u16 ack_policy:2;
+		u16 reserved:1;
+		u16 txop:8;
+	}field;
+}frameqos,*pframeqos;
+
+/* SWEEP TABLE ENTRIES NUMBER*/
+#define MAX_SWEEP_TAB_ENTRIES		  42
+#define MAX_SWEEP_TAB_ENTRIES_PER_PACKET  7
+/* MAX_RATES_LENGTH needs to be 12.  The spec says 8, and many APs
+ * only use 8, and then use extended rates for the remaining supported
+ * rates.  Other APs, however, stick all of their supported rates on the
+ * main rates information element... */
+#define MAX_RATES_LENGTH                  ((u8)12)
+#define MAX_RATES_EX_LENGTH               ((u8)16)
+#define MAX_NETWORK_COUNT                  128
+
+#define MAX_CHANNEL_NUMBER                 161
+#define IEEE80211_SOFTMAC_SCAN_TIME	   100
+//(HZ / 2)
+#define IEEE80211_SOFTMAC_ASSOC_RETRY_TIME (HZ * 2)
+
+#define CRC_LENGTH                 4U
+
+#define MAX_WPA_IE_LEN 64
+
+#define NETWORK_EMPTY_ESSID (1<<0)
+#define NETWORK_HAS_OFDM    (1<<1)
+#define NETWORK_HAS_CCK     (1<<2)
+
+/* QoS structure */
+#define NETWORK_HAS_QOS_PARAMETERS      (1<<3)
+#define NETWORK_HAS_QOS_INFORMATION     (1<<4)
+#define NETWORK_HAS_QOS_MASK            (NETWORK_HAS_QOS_PARAMETERS | \
+                                         NETWORK_HAS_QOS_INFORMATION)
+/* 802.11h */
+#define NETWORK_HAS_POWER_CONSTRAINT    (1<<5)
+#define NETWORK_HAS_CSA                 (1<<6)
+#define NETWORK_HAS_QUIET               (1<<7)
+#define NETWORK_HAS_IBSS_DFS            (1<<8)
+#define NETWORK_HAS_TPC_REPORT          (1<<9)
+
+#define NETWORK_HAS_ERP_VALUE           (1<<10)
+
+#define QOS_QUEUE_NUM                   4
+#define QOS_OUI_LEN                     3
+#define QOS_OUI_TYPE                    2
+#define QOS_ELEMENT_ID                  221
+#define QOS_OUI_INFO_SUB_TYPE           0
+#define QOS_OUI_PARAM_SUB_TYPE          1
+#define QOS_VERSION_1                   1
+#define QOS_AIFSN_MIN_VALUE             2
+#if 1
+struct ieee80211_qos_information_element {
+        u8 elementID;
+        u8 length;
+        u8 qui[QOS_OUI_LEN];
+        u8 qui_type;
+        u8 qui_subtype;
+        u8 version;
+        u8 ac_info;
+} __attribute__ ((packed));
+
+struct ieee80211_qos_ac_parameter {
+        u8 aci_aifsn;
+        u8 ecw_min_max;
+        __le16 tx_op_limit;
+} __attribute__ ((packed));
+
+struct ieee80211_qos_parameter_info {
+        struct ieee80211_qos_information_element info_element;
+        u8 reserved;
+        struct ieee80211_qos_ac_parameter ac_params_record[QOS_QUEUE_NUM];
+} __attribute__ ((packed));
+
+struct ieee80211_qos_parameters {
+        __le16 cw_min[QOS_QUEUE_NUM];
+        __le16 cw_max[QOS_QUEUE_NUM];
+        u8 aifs[QOS_QUEUE_NUM];
+        u8 flag[QOS_QUEUE_NUM];
+        __le16 tx_op_limit[QOS_QUEUE_NUM];
+} __attribute__ ((packed));
+
+struct ieee80211_qos_data {
+        struct ieee80211_qos_parameters parameters;
+        int active;
+        int supported;
+        u8 param_count;
+        u8 old_param_count;
+};
+
+struct ieee80211_tim_parameters {
+        u8 tim_count;
+        u8 tim_period;
+} __attribute__ ((packed));
+
+//#else
+struct ieee80211_wmm_ac_param {
+	u8 ac_aci_acm_aifsn;
+	u8 ac_ecwmin_ecwmax;
+	u16 ac_txop_limit;
+};
+
+struct ieee80211_wmm_ts_info {
+	u8 ac_dir_tid;
+	u8 ac_up_psb;
+	u8 reserved;
+} __attribute__ ((packed));
+
+struct ieee80211_wmm_tspec_elem {
+	struct ieee80211_wmm_ts_info ts_info;
+	u16 norm_msdu_size;
+	u16 max_msdu_size;
+	u32 min_serv_inter;
+	u32 max_serv_inter;
+	u32 inact_inter;
+	u32 suspen_inter;
+	u32 serv_start_time;
+	u32 min_data_rate;
+	u32 mean_data_rate;
+	u32 peak_data_rate;
+	u32 max_burst_size;
+	u32 delay_bound;
+	u32 min_phy_rate;
+	u16 surp_band_allow;
+	u16 medium_time;
+}__attribute__((packed));
+#endif
+enum eap_type {
+	EAP_PACKET = 0,
+	EAPOL_START,
+	EAPOL_LOGOFF,
+	EAPOL_KEY,
+	EAPOL_ENCAP_ASF_ALERT
+};
+
+static const char *eap_types[] = {
+	[EAP_PACKET]		= "EAP-Packet",
+	[EAPOL_START]		= "EAPOL-Start",
+	[EAPOL_LOGOFF]		= "EAPOL-Logoff",
+	[EAPOL_KEY]		= "EAPOL-Key",
+	[EAPOL_ENCAP_ASF_ALERT]	= "EAPOL-Encap-ASF-Alert"
+};
+
+static inline const char *eap_get_type(int type)
+{
+	return ((u32)type >= ARRAY_SIZE(eap_types)) ? "Unknown" : eap_types[type];
+}
+//added by amy for reorder
+static inline u8 Frame_QoSTID(u8* buf)
+{
+	struct ieee80211_hdr_3addr *hdr;
+	u16 fc;
+	hdr = (struct ieee80211_hdr_3addr *)buf;
+	fc = le16_to_cpu(hdr->frame_ctl);
+	return (u8)((frameqos*)(buf + (((fc & IEEE80211_FCTL_TODS)&&(fc & IEEE80211_FCTL_FROMDS))? 30 : 24)))->field.tid;
+}
+
+//added by amy for reorder
+
+struct eapol {
+	u8 snap[6];
+	u16 ethertype;
+	u8 version;
+	u8 type;
+	u16 length;
+} __attribute__ ((packed));
+
+struct ieee80211_softmac_stats{
+	unsigned int rx_ass_ok;
+	unsigned int rx_ass_err;
+	unsigned int rx_probe_rq;
+	unsigned int tx_probe_rs;
+	unsigned int tx_beacons;
+	unsigned int rx_auth_rq;
+	unsigned int rx_auth_rs_ok;
+	unsigned int rx_auth_rs_err;
+	unsigned int tx_auth_rq;
+	unsigned int no_auth_rs;
+	unsigned int no_ass_rs;
+	unsigned int tx_ass_rq;
+	unsigned int rx_ass_rq;
+	unsigned int tx_probe_rq;
+	unsigned int reassoc;
+	unsigned int swtxstop;
+	unsigned int swtxawake;
+	unsigned char CurrentShowTxate;
+	unsigned char last_packet_rate;
+	unsigned int txretrycount;
+};
+
+#define BEACON_PROBE_SSID_ID_POSITION 12
+
+struct ieee80211_info_element_hdr {
+	u8 id;
+	u8 len;
+} __attribute__ ((packed));
+
+/*
+ * These are the data types that can make up management packets
+ *
+	u16 auth_algorithm;
+	u16 auth_sequence;
+	u16 beacon_interval;
+	u16 capability;
+	u8 current_ap[ETH_ALEN];
+	u16 listen_interval;
+	struct {
+		u16 association_id:14, reserved:2;
+	} __attribute__ ((packed));
+	u32 time_stamp[2];
+	u16 reason;
+	u16 status;
+*/
+
+#define IEEE80211_DEFAULT_TX_ESSID "Penguin"
+#define IEEE80211_DEFAULT_BASIC_RATE 2 //1Mbps
+
+enum {WMM_all_frame, WMM_two_frame, WMM_four_frame, WMM_six_frame};
+#define MAX_SP_Len  (WMM_all_frame << 4)
+#define IEEE80211_QOS_TID 0x0f
+#define QOS_CTL_NOTCONTAIN_ACK (0x01 << 5)
+
+#define IEEE80211_DTIM_MBCAST 4
+#define IEEE80211_DTIM_UCAST 2
+#define IEEE80211_DTIM_VALID 1
+#define IEEE80211_DTIM_INVALID 0
+
+#define IEEE80211_PS_DISABLED 0
+#define IEEE80211_PS_UNICAST IEEE80211_DTIM_UCAST
+#define IEEE80211_PS_MBCAST IEEE80211_DTIM_MBCAST
+
+//added by David for QoS 2006/6/30
+//#define WMM_Hang_8187
+#ifdef WMM_Hang_8187
+#undef WMM_Hang_8187
+#endif
+
+#define WME_AC_BK   0x00
+#define WME_AC_BE   0x01
+#define WME_AC_VI   0x02
+#define WME_AC_VO   0x03
+#define WME_ACI_MASK 0x03
+#define WME_AIFSN_MASK 0x03
+#define WME_AC_PRAM_LEN 16
+
+#define MAX_RECEIVE_BUFFER_SIZE 9100
+
+//UP Mapping to AC, using in MgntQuery_SequenceNumber() and maybe for DSCP
+//#define UP2AC(up)	((up<3) ? ((up==0)?1:0) : (up>>1))
+#if 1
+#define UP2AC(up) (		   \
+	((up) < 1) ? WME_AC_BE : \
+	((up) < 3) ? WME_AC_BK : \
+	((up) < 4) ? WME_AC_BE : \
+	((up) < 6) ? WME_AC_VI : \
+	WME_AC_VO)
+#endif
+//AC Mapping to UP, using in Tx part for selecting the corresponding TX queue
+#define AC2UP(_ac)	(       \
+	((_ac) == WME_AC_VO) ? 6 : \
+	((_ac) == WME_AC_VI) ? 5 : \
+	((_ac) == WME_AC_BK) ? 1 : \
+	0)
+
+#define	ETHER_ADDR_LEN		6	/* length of an Ethernet address */
+#define ETHERNET_HEADER_SIZE    14      /* length of two Ethernet address plus ether type*/
+
+struct	ether_header {
+	u8 ether_dhost[ETHER_ADDR_LEN];
+	u8 ether_shost[ETHER_ADDR_LEN];
+	u16 ether_type;
+} __attribute__((packed));
+
+#ifndef ETHERTYPE_PAE
+#define	ETHERTYPE_PAE	0x888e		/* EAPOL PAE/802.1x */
+#endif
+#ifndef ETHERTYPE_IP
+#define	ETHERTYPE_IP	0x0800		/* IP protocol */
+#endif
+
+typedef struct _bss_ht{
+
+	bool				support_ht;
+
+	// HT related elements
+	u8					ht_cap_buf[32];
+	u16					ht_cap_len;
+	u8					ht_info_buf[32];
+	u16					ht_info_len;
+
+	HT_SPEC_VER			ht_spec_ver;
+	//HT_CAPABILITY_ELE			bdHTCapEle;
+	//HT_INFORMATION_ELE		bdHTInfoEle;
+
+	bool				aggregation;
+	bool				long_slot_time;
+}bss_ht, *pbss_ht;
+
+typedef enum _erp_t{
+	ERP_NonERPpresent	= 0x01,
+	ERP_UseProtection	= 0x02,
+	ERP_BarkerPreambleMode = 0x04,
+} erp_t;
+
+
+struct ieee80211_network {
+	/* These entries are used to identify a unique network */
+	u8 bssid[ETH_ALEN];
+	u8 channel;
+	/* Ensure null-terminated for any debug msgs */
+	u8 ssid[IW_ESSID_MAX_SIZE + 1];
+	u8 ssid_len;
+#if 1
+        struct ieee80211_qos_data qos_data;
+#else
+       // Qos related. Added by Annie, 2005-11-01.
+        BSS_QOS   BssQos;
+#endif
+
+	//added by amy for LEAP
+	bool	bWithAironetIE;
+	bool	bCkipSupported;
+	bool	bCcxRmEnable;
+	u16 	CcxRmState[2];
+	// CCXv4 S59, MBSSID.
+	bool	bMBssidValid;
+	u8	MBssidMask;
+	u8	MBssid[6];
+	// CCX 2 S38, WLAN Device Version Number element. Annie, 2006-08-20.
+	bool	bWithCcxVerNum;
+	u8	BssCcxVerNumber;
+	/* These are network statistics */
+	struct ieee80211_rx_stats stats;
+	u16 capability;
+	u8  rates[MAX_RATES_LENGTH];
+	u8  rates_len;
+	u8  rates_ex[MAX_RATES_EX_LENGTH];
+	u8  rates_ex_len;
+	unsigned long last_scanned;
+	u8  mode;
+	u32 flags;
+	u32 last_associate;
+	u32 time_stamp[2];
+	u16 beacon_interval;
+	u16 listen_interval;
+	u16 atim_window;
+	u8  erp_value;
+	u8  wpa_ie[MAX_WPA_IE_LEN];
+	size_t wpa_ie_len;
+	u8  rsn_ie[MAX_WPA_IE_LEN];
+	size_t rsn_ie_len;
+
+        struct ieee80211_tim_parameters tim;
+	u8  dtim_period;
+	u8  dtim_data;
+	u32 last_dtim_sta_time[2];
+
+        //appeded for QoS
+        u8 wmm_info;
+        struct ieee80211_wmm_ac_param wmm_param[4];
+        u8 QoS_Enable;
+#ifdef THOMAS_TURBO
+	u8 Turbo_Enable;//enable turbo mode, added by thomas
+#endif
+#ifdef ENABLE_DOT11D
+	u16 CountryIeLen;
+	u8 CountryIeBuf[MAX_IE_LEN];
+#endif
+        // HT Related, by amy, 2008.04.29
+	BSS_HT	bssht;
+	// Add to handle broadcom AP management frame CCK rate.
+	bool broadcom_cap_exist;
+	bool realtek_cap_exit;
+	bool marvell_cap_exist;
+	bool ralink_cap_exist;
+	bool atheros_cap_exist;
+	bool cisco_cap_exist;
+	bool unknown_cap_exist;
+//	u8	berp_info;
+	bool	berp_info_valid;
+	bool buseprotection;
+	//put at the end of the structure.
+	struct list_head list;
+};
+
+#if 1
+enum ieee80211_state {
+
+	/* the card is not linked at all */
+	IEEE80211_NOLINK = 0,
+
+	/* IEEE80211_ASSOCIATING* are for BSS client mode
+	 * the driver shall not perform RX filtering unless
+	 * the state is LINKED.
+	 * The driver shall just check for the state LINKED and
+	 * defaults to NOLINK for ALL the other states (including
+	 * LINKED_SCANNING)
+	 */
+
+	/* the association procedure will start (wq scheduling)*/
+	IEEE80211_ASSOCIATING,
+	IEEE80211_ASSOCIATING_RETRY,
+
+	/* the association procedure is sending AUTH request*/
+	IEEE80211_ASSOCIATING_AUTHENTICATING,
+
+	/* the association procedure has successfully authentcated
+	 * and is sending association request
+	 */
+	IEEE80211_ASSOCIATING_AUTHENTICATED,
+
+	/* the link is ok. the card associated to a BSS or linked
+	 * to a ibss cell or acting as an AP and creating the bss
+	 */
+	IEEE80211_LINKED,
+
+	/* same as LINKED, but the driver shall apply RX filter
+	 * rules as we are in NO_LINK mode. As the card is still
+	 * logically linked, but it is doing a syncro site survey
+	 * then it will be back to LINKED state.
+	 */
+	IEEE80211_LINKED_SCANNING,
+
+};
+#else
+enum ieee80211_state {
+        IEEE80211_UNINITIALIZED = 0,
+        IEEE80211_INITIALIZED,
+        IEEE80211_ASSOCIATING,
+        IEEE80211_ASSOCIATED,
+        IEEE80211_AUTHENTICATING,
+        IEEE80211_AUTHENTICATED,
+        IEEE80211_SHUTDOWN
+};
+#endif
+
+#define DEFAULT_MAX_SCAN_AGE (15 * HZ)
+#define DEFAULT_FTS 2346
+
+#define CFG_IEEE80211_RESERVE_FCS (1<<0)
+#define CFG_IEEE80211_COMPUTE_FCS (1<<1)
+#define CFG_IEEE80211_RTS (1<<2)
+
+#define IEEE80211_24GHZ_MIN_CHANNEL 1
+#define IEEE80211_24GHZ_MAX_CHANNEL 14
+#define IEEE80211_24GHZ_CHANNELS (IEEE80211_24GHZ_MAX_CHANNEL - \
+                                  IEEE80211_24GHZ_MIN_CHANNEL + 1)
+
+#define IEEE80211_52GHZ_MIN_CHANNEL 34
+#define IEEE80211_52GHZ_MAX_CHANNEL 165
+#define IEEE80211_52GHZ_CHANNELS (IEEE80211_52GHZ_MAX_CHANNEL - \
+                                  IEEE80211_52GHZ_MIN_CHANNEL + 1)
+
+#if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,11))
+extern inline int is_multicast_ether_addr(const u8 *addr)
+{
+        return ((addr[0] != 0xff) && (0x01 & addr[0]));
+}
+#endif
+
+#if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13))
+extern inline int is_broadcast_ether_addr(const u8 *addr)
+{
+	return ((addr[0] == 0xff) && (addr[1] == 0xff) && (addr[2] == 0xff) &&   \
+		(addr[3] == 0xff) && (addr[4] == 0xff) && (addr[5] == 0xff));
+}
+#endif
+
+typedef struct tx_pending_t{
+	int frag;
+	struct ieee80211_txb *txb;
+}tx_pending_t;
+
+typedef struct _bandwidth_autoswitch
+{
+	long threshold_20Mhzto40Mhz;
+	long	threshold_40Mhzto20Mhz;
+	bool bforced_tx20Mhz;
+	bool bautoswitch_enable;
+}bandwidth_autoswitch,*pbandwidth_autoswitch;
+
+
+//added by amy for order
+
+#define REORDER_WIN_SIZE	128
+#define REORDER_ENTRY_NUM	128
+typedef struct _RX_REORDER_ENTRY
+{
+	struct list_head	List;
+	u16			SeqNum;
+	struct ieee80211_rxb* prxb;
+} RX_REORDER_ENTRY, *PRX_REORDER_ENTRY;
+//added by amy for order
+typedef enum _Fsync_State{
+	Default_Fsync,
+	HW_Fsync,
+	SW_Fsync
+}Fsync_State;
+
+// Power save mode configured.
+typedef	enum _RT_PS_MODE
+{
+	eActive,	// Active/Continuous access.
+	eMaxPs,		// Max power save mode.
+	eFastPs		// Fast power save mode.
+}RT_PS_MODE;
+
+typedef enum _IPS_CALLBACK_FUNCION
+{
+	IPS_CALLBACK_NONE = 0,
+	IPS_CALLBACK_MGNT_LINK_REQUEST = 1,
+	IPS_CALLBACK_JOIN_REQUEST = 2,
+}IPS_CALLBACK_FUNCION;
+
+typedef enum _RT_JOIN_ACTION{
+	RT_JOIN_INFRA   = 1,
+	RT_JOIN_IBSS  = 2,
+	RT_START_IBSS = 3,
+	RT_NO_ACTION  = 4,
+}RT_JOIN_ACTION;
+
+typedef struct _IbssParms{
+	u16   atimWin;
+}IbssParms, *PIbssParms;
+#define MAX_NUM_RATES	264 // Max num of support rates element: 8,  Max num of ext. support rate: 255. 061122, by rcnjko.
+
+// RF state.
+typedef	enum _RT_RF_POWER_STATE
+{
+	eRfOn,
+	eRfSleep,
+	eRfOff
+}RT_RF_POWER_STATE;
+
+typedef struct _RT_POWER_SAVE_CONTROL
+{
+
+	//
+	// Inactive Power Save(IPS) : Disable RF when disconnected
+	//
+	bool				bInactivePs;
+	bool				bIPSModeBackup;
+	bool				bHaltAdapterClkRQ;
+	bool				bSwRfProcessing;
+	RT_RF_POWER_STATE	eInactivePowerState;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	struct work_struct 	InactivePsWorkItem;
+#else
+	struct tq_struct	InactivePsWorkItem;
+#endif
+	struct timer_list	InactivePsTimer;
+
+	// Return point for join action
+	IPS_CALLBACK_FUNCION	ReturnPoint;
+
+	// Recored Parameters for rescheduled JoinRequest
+	bool				bTmpBssDesc;
+	RT_JOIN_ACTION		tmpJoinAction;
+	struct ieee80211_network tmpBssDesc;
+
+	// Recored Parameters for rescheduled MgntLinkRequest
+	bool				bTmpScanOnly;
+	bool				bTmpActiveScan;
+	bool				bTmpFilterHiddenAP;
+	bool				bTmpUpdateParms;
+	u8					tmpSsidBuf[33];
+	OCTET_STRING			tmpSsid2Scan;
+	bool				bTmpSsid2Scan;
+	u8					tmpNetworkType;
+	u8					tmpChannelNumber;
+	u16					tmpBcnPeriod;
+	u8					tmpDtimPeriod;
+	u16					tmpmCap;
+	OCTET_STRING			tmpSuppRateSet;
+	u8					tmpSuppRateBuf[MAX_NUM_RATES];
+	bool				bTmpSuppRate;
+	IbssParms				tmpIbpm;
+	bool				bTmpIbpm;
+
+	//
+	// Leisre Poswer Save : Disable RF if connected but traffic is not busy
+	//
+	bool				bLeisurePs;
+	u32				PowerProfile;
+	u8				LpsIdleCount;
+	u8				RegMaxLPSAwakeIntvl;
+	u8				LPSAwakeIntvl;
+
+	//RF OFF Level
+	u32				CurPsLevel;
+	u32				RegRfPsLevel;
+
+	//Fw Control LPS
+	bool				bFwCtrlLPS;
+	u8				FWCtrlPSMode;
+
+	//2009.01.01 added by tynli
+	// Record if there is a link request in IPS RF off progress.
+	bool				LinkReqInIPSRFOffPgs;
+	// To make sure that connect info should be executed, so we set the bit to filter the link info which comes after the connect info.
+	bool				BufConnectinfoBefore;
+
+}RT_POWER_SAVE_CONTROL,*PRT_POWER_SAVE_CONTROL;
+
+typedef u32 RT_RF_CHANGE_SOURCE;
+#define RF_CHANGE_BY_SW BIT31
+#define RF_CHANGE_BY_HW BIT30
+#define RF_CHANGE_BY_PS BIT29
+#define RF_CHANGE_BY_IPS BIT28
+#define RF_CHANGE_BY_INIT	0	// Do not change the RFOff reason. Defined by Bruce, 2008-01-17.
+
+#ifdef ENABLE_DOT11D
+typedef enum
+{
+	COUNTRY_CODE_FCC = 0,
+	COUNTRY_CODE_IC = 1,
+	COUNTRY_CODE_ETSI = 2,
+	COUNTRY_CODE_SPAIN = 3,
+	COUNTRY_CODE_FRANCE = 4,
+	COUNTRY_CODE_MKK = 5,
+	COUNTRY_CODE_MKK1 = 6,
+	COUNTRY_CODE_ISRAEL = 7,
+	COUNTRY_CODE_TELEC,
+	COUNTRY_CODE_MIC,
+	COUNTRY_CODE_GLOBAL_DOMAIN
+}country_code_type_t;
+#endif
+	// Firmware realted CMD IO.
+typedef	enum _FW_CMD_IO_TYPE{
+	FW_CMD_DIG_ENABLE = 0, // For DIG DM
+	FW_CMD_DIG_DISABLE = 1,
+	FW_CMD_DIG_HALT = 2,
+	FW_CMD_DIG_RESUME = 3,
+	FW_CMD_HIGH_PWR_ENABLE = 4, // For High Power DM
+	FW_CMD_HIGH_PWR_DISABLE = 5,
+	FW_CMD_RA_RESET = 6, // For Rate adaptive DM
+	FW_CMD_RA_ACTIVE= 7,
+	FW_CMD_RA_REFRESH_N= 8,
+	FW_CMD_RA_REFRESH_BG= 9,
+	FW_CMD_IQK_ENABLE = 10, // For FW supported IQK
+	FW_CMD_TXPWR_TRACK_ENABLE = 11,	// Tx power tracking switch
+	FW_CMD_TXPWR_TRACK_DISABLE = 12,	// Tx power tracking switch
+	FW_CMD_PAUSE_DM_BY_SCAN = 13,
+	FW_CMD_RESUME_DM_BY_SCAN = 14,
+	FW_CMD_MID_HIGH_PWR_ENABLE = 15,
+	FW_CMD_LPS_ENTER = 16,			// Indifate firmware that driver enters LPS, For PS-Poll hardware bug
+	FW_CMD_LPS_LEAVE = 17,			// Indicate firmware that driver leave LPS, 2009/1/4, by Emily
+}FW_CMD_IO_TYPE,*PFW_CMD_IO_TYPE;
+#define RT_MAX_LD_SLOT_NUM	10
+typedef struct _RT_LINK_DETECT_T{
+
+	u32				NumRecvBcnInPeriod;
+	u32				NumRecvDataInPeriod;
+
+	u32				RxBcnNum[RT_MAX_LD_SLOT_NUM];	// number of Rx beacon / CheckForHang_period  to determine link status
+	u32				RxDataNum[RT_MAX_LD_SLOT_NUM];	// number of Rx data / CheckForHang_period  to determine link status
+	u16				SlotNum;	// number of CheckForHang period to determine link status
+	u16				SlotIndex;
+
+	u32				NumTxOkInPeriod;
+	u32				NumRxOkInPeriod;
+	bool				bBusyTraffic;
+}RT_LINK_DETECT_T, *PRT_LINK_DETECT_T;
+
+
+struct ieee80211_device {
+	struct net_device *dev;
+        struct ieee80211_security sec;
+
+	//hw security related
+//	u8 hwsec_support; //support?
+	u8 hwsec_active;  //hw security active.
+	bool is_silent_reset;
+	bool is_roaming;
+	bool ieee_up;
+	//added by amy
+	bool bSupportRemoteWakeUp;
+	RT_PS_MODE	dot11PowerSaveMode; // Power save mode configured.
+	bool actscanning;
+	//added by amy 090313
+	bool be_scan_inprogress;
+	bool beinretry;
+	RT_RF_POWER_STATE		eRFPowerState;
+	RT_RF_CHANGE_SOURCE	RfOffReason;
+	bool is_set_key;
+	//11n spec related I wonder if These info structure need to be moved out of ieee80211_device
+
+	//11n HT below
+	PRT_HIGH_THROUGHPUT	pHTInfo;
+	//struct timer_list		SwBwTimer;
+//	spinlock_t chnlop_spinlock;
+	spinlock_t bw_spinlock;
+
+	spinlock_t reorder_spinlock;
+	// for HT operation rate set.  we use this one for HT data rate to seperate different descriptors
+	//the way fill this is the same as in the IE
+	u8	Regdot11HTOperationalRateSet[16];		//use RATR format
+	u8	dot11HTOperationalRateSet[16];		//use RATR format
+	u8	RegHTSuppRateSet[16];
+	u8				HTCurrentOperaRate;
+	u8				HTHighestOperaRate;
+	//wb added for rate operation mode to firmware
+	u8	bTxDisableRateFallBack;
+	u8 	bTxUseDriverAssingedRate;
+	atomic_t	atm_chnlop;
+	atomic_t	atm_swbw;
+//	u8	HTHighestOperaRate;
+//	u8 	HTCurrentOperaRate;
+
+	// 802.11e and WMM Traffic Stream Info (TX)
+	struct list_head		Tx_TS_Admit_List;
+	struct list_head		Tx_TS_Pending_List;
+	struct list_head		Tx_TS_Unused_List;
+	TX_TS_RECORD		TxTsRecord[TOTAL_TS_NUM];
+	// 802.11e and WMM Traffic Stream Info (RX)
+	struct list_head		Rx_TS_Admit_List;
+	struct list_head		Rx_TS_Pending_List;
+	struct list_head		Rx_TS_Unused_List;
+	RX_TS_RECORD		RxTsRecord[TOTAL_TS_NUM];
+//#ifdef TO_DO_LIST
+	RX_REORDER_ENTRY	RxReorderEntry[128];
+	struct list_head		RxReorder_Unused_List;
+//#endif
+	// Qos related. Added by Annie, 2005-11-01.
+//	PSTA_QOS			pStaQos;
+	u8				ForcedPriority;		// Force per-packet priority 1~7. (default: 0, not to force it.)
+
+
+	/* Bookkeeping structures */
+	struct net_device_stats stats;
+	struct ieee80211_stats ieee_stats;
+	struct ieee80211_softmac_stats softmac_stats;
+
+	/* Probe / Beacon management */
+	struct list_head network_free_list;
+	struct list_head network_list;
+	struct ieee80211_network *networks;
+	int scans;
+	int scan_age;
+
+	int iw_mode; /* operating mode (IW_MODE_*) */
+	struct iw_spy_data spy_data;
+
+	spinlock_t lock;
+	spinlock_t wpax_suitlist_lock;
+
+	int tx_headroom; /* Set to size of any additional room needed at front
+			  * of allocated Tx SKBs */
+	u32 config;
+
+	/* WEP and other encryption related settings at the device level */
+	int open_wep; /* Set to 1 to allow unencrypted frames */
+	int auth_mode;
+	int reset_on_keychange; /* Set to 1 if the HW needs to be reset on
+				 * WEP key changes */
+
+	/* If the host performs {en,de}cryption, then set to 1 */
+	int host_encrypt;
+	int host_encrypt_msdu;
+	int host_decrypt;
+        /* host performs multicast decryption */
+        int host_mc_decrypt;
+
+        /* host should strip IV and ICV from protected frames */
+        /* meaningful only when hardware decryption is being used */
+        int host_strip_iv_icv;
+
+        int host_open_frag;
+        int host_build_iv;
+	int ieee802_1x; /* is IEEE 802.1X used */
+
+	/* WPA data */
+	bool bHalfWirelessN24GMode;
+	int wpa_enabled;
+	int drop_unencrypted;
+	int tkip_countermeasures;
+	int privacy_invoked;
+	size_t wpa_ie_len;
+	u8 *wpa_ie;
+	u8 ap_mac_addr[6];
+	u16 pairwise_key_type;
+	u16 group_key_type;
+	struct list_head crypt_deinit_list;
+	struct ieee80211_crypt_data *crypt[WEP_KEYS];
+	int tx_keyidx; /* default TX key index (crypt[tx_keyidx]) */
+	struct timer_list crypt_deinit_timer;
+        int crypt_quiesced;
+
+	int bcrx_sta_key; /* use individual keys to override default keys even
+			   * with RX of broad/multicast frames */
+
+	/* Fragmentation structures */
+	// each streaming contain a entry
+	struct ieee80211_frag_entry frag_cache[17][IEEE80211_FRAG_CACHE_LEN];
+	unsigned int frag_next_idx[17];
+	u16 fts; /* Fragmentation Threshold */
+#define DEFAULT_RTS_THRESHOLD 2346U
+#define MIN_RTS_THRESHOLD 1
+#define MAX_RTS_THRESHOLD 2346U
+        u16 rts; /* RTS threshold */
+
+        /* Association info */
+        u8 bssid[ETH_ALEN];
+
+	/* This stores infos for the current network.
+	 * Either the network we are associated in INFRASTRUCTURE
+	 * or the network that we are creating in MASTER mode.
+	 * ad-hoc is a mixture ;-).
+	 * Note that in infrastructure mode, even when not associated,
+	 * fields bssid and essid may be valid (if wpa_set and essid_set
+	 * are true) as thy carry the value set by the user via iwconfig
+	 */
+	struct ieee80211_network current_network;
+
+	enum ieee80211_state state;
+
+	int short_slot;
+	int reg_mode;
+	int mode;       /* A, B, G */
+	int modulation; /* CCK, OFDM */
+	int freq_band;  /* 2.4Ghz, 5.2Ghz, Mixed */
+	int abg_true;   /* ABG flag              */
+
+	/* used for forcing the ibss workqueue to terminate
+	 * without wait for the syncro scan to terminate
+	 */
+	short sync_scan_hurryup;
+	u16 scan_watch_dog;
+        int perfect_rssi;
+        int worst_rssi;
+
+        u16 prev_seq_ctl;       /* used to drop duplicate frames */
+
+	/* map of allowed channels. 0 is dummy */
+	// FIXME: remeber to default to a basic channel plan depending of the PHY type
+#ifdef ENABLE_DOT11D
+	void* pDot11dInfo;
+	bool bGlobalDomain;
+#else
+	int channel_map[MAX_CHANNEL_NUMBER+1];
+#endif
+	int rate;       /* current rate */
+	int basic_rate;
+	//FIXME: pleace callback, see if redundant with softmac_features
+	short active_scan;
+
+	/* this contains flags for selectively enable softmac support */
+	u16 softmac_features;
+
+	/* if the sequence control field is not filled by HW */
+	u16 seq_ctrl[5];
+
+	/* association procedure transaction sequence number */
+	u16 associate_seq;
+
+	/* AID for RTXed association responses */
+	u16 assoc_id;
+
+	/* power save mode related*/
+	u8 ack_tx_to_ieee;
+	short ps;
+	short sta_sleep;
+	int ps_timeout;
+	int ps_period;
+	struct tasklet_struct ps_task;
+	u32 ps_th;
+	u32 ps_tl;
+
+	short raw_tx;
+	/* used if IEEE_SOFTMAC_TX_QUEUE is set */
+	short queue_stop;
+	short scanning;
+	short proto_started;
+
+	struct semaphore wx_sem;
+	struct semaphore scan_sem;
+
+	spinlock_t mgmt_tx_lock;
+	spinlock_t beacon_lock;
+
+	short beacon_txing;
+
+	short wap_set;
+	short ssid_set;
+
+	u8  wpax_type_set;    //{added by David, 2006.9.28}
+	u32 wpax_type_notify; //{added by David, 2006.9.26}
+
+	/* QoS related flag */
+	char init_wmmparam_flag;
+	/* set on initialization */
+	u8  qos_support;
+
+	/* for discarding duplicated packets in IBSS */
+	struct list_head ibss_mac_hash[IEEE_IBSS_MAC_HASH_SIZE];
+
+	/* for discarding duplicated packets in BSS */
+	u16 last_rxseq_num[17]; /* rx seq previous per-tid */
+	u16 last_rxfrag_num[17];/* tx frag previous per-tid */
+	unsigned long last_packet_time[17];
+
+	/* for PS mode */
+	unsigned long last_rx_ps_time;
+
+	/* used if IEEE_SOFTMAC_SINGLE_QUEUE is set */
+	struct sk_buff *mgmt_queue_ring[MGMT_QUEUE_NUM];
+	int mgmt_queue_head;
+	int mgmt_queue_tail;
+//{ added for rtl819x
+#define IEEE80211_QUEUE_LIMIT 128
+	u8 AsocRetryCount;
+	unsigned int hw_header;
+	struct sk_buff_head skb_waitQ[MAX_QUEUE_SIZE];
+	struct sk_buff_head  skb_aggQ[MAX_QUEUE_SIZE];
+	struct sk_buff_head  skb_drv_aggQ[MAX_QUEUE_SIZE];
+	u32	sta_edca_param[4];
+	bool aggregation;
+	// Enable/Disable Rx immediate BA capability.
+	bool enable_rx_imm_BA;
+	bool bibsscoordinator;
+
+	//+by amy for DM ,080515
+	//Dynamic Tx power for near/far range enable/Disable  , by amy , 2008-05-15
+	bool	bdynamic_txpower_enable;
+
+	bool bCTSToSelfEnable;
+	u8 	CTSToSelfTH;
+
+	u32 	fsync_time_interval;
+	u32	fsync_rate_bitmap;
+	u8	fsync_rssi_threshold;
+	bool	bfsync_enable;
+
+	u8	fsync_multiple_timeinterval;		// FsyncMultipleTimeInterval * FsyncTimeInterval
+	u32	fsync_firstdiff_ratethreshold;		// low threshold
+	u32	fsync_seconddiff_ratethreshold;	 // decrease threshold
+	Fsync_State			fsync_state;
+	bool		bis_any_nonbepkts;
+	//20Mhz 40Mhz AutoSwitch Threshold
+	bandwidth_autoswitch bandwidth_auto_switch;
+	//for txpower tracking
+	bool FwRWRF;
+
+	//added by amy for AP roaming
+	RT_LINK_DETECT_T	LinkDetectInfo;
+        //added by amy for ps
+	RT_POWER_SAVE_CONTROL	PowerSaveControl;
+//}
+	/* used if IEEE_SOFTMAC_TX_QUEUE is set */
+	struct  tx_pending_t tx_pending;
+
+	/* used if IEEE_SOFTMAC_ASSOCIATE is set */
+	struct timer_list associate_timer;
+
+	/* used if IEEE_SOFTMAC_BEACONS is set */
+	struct timer_list beacon_timer;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+        struct work_struct associate_complete_wq;
+        struct work_struct associate_procedure_wq;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+        struct delayed_work softmac_scan_wq;
+        struct delayed_work associate_retry_wq;
+	 struct delayed_work start_ibss_wq;
+	 struct delayed_work hw_wakeup_wq;
+	struct delayed_work hw_sleep_wq;
+	struct delayed_work link_change_wq;
+#else
+        struct work_struct softmac_scan_wq;
+        struct work_struct associate_retry_wq;
+	struct work_struct start_ibss_wq;
+	struct work_struct hw_wakeup_wq;
+	struct work_struct hw_sleep_wq;
+	struct work_struct link_change_wq;
+#endif
+        struct work_struct wx_sync_scan_wq;
+        struct workqueue_struct *wq;
+#else
+	/* used for periodly scan */
+	struct timer_list scan_timer;
+
+	struct tq_struct associate_complete_wq;
+	struct tq_struct associate_retry_wq;
+	struct tq_struct start_ibss_wq;
+	struct tq_struct associate_procedure_wq;
+	struct tq_struct softmac_scan_wq;
+	struct tq_struct wx_sync_scan_wq;
+	struct tq_struct hw_wakeup_wq;
+	struct tq_struct hw_sleep_wq;
+	struct tq_struct link_change_wq;
+
+#endif
+        // Qos related. Added by Annie, 2005-11-01.
+        //STA_QOS  StaQos;
+
+        //u32 STA_EDCA_PARAM[4];
+	//CHANNEL_ACCESS_SETTING ChannelAccessSetting;
+
+
+	/* Callback functions */
+	void (*set_security)(struct net_device *dev,
+			     struct ieee80211_security *sec);
+
+	/* Used to TX data frame by using txb structs.
+	 * this is not used if in the softmac_features
+	 * is set the flag IEEE_SOFTMAC_TX_QUEUE
+	 */
+	int (*hard_start_xmit)(struct ieee80211_txb *txb,
+			       struct net_device *dev);
+
+	int (*reset_port)(struct net_device *dev);
+        int (*is_queue_full) (struct net_device * dev, int pri);
+
+        int (*handle_management) (struct net_device * dev,
+                                  struct ieee80211_network * network, u16 type);
+        int (*is_qos_active) (struct net_device *dev, struct sk_buff *skb);
+
+	/* Softmac-generated frames (mamagement) are TXed via this
+	 * callback if the flag IEEE_SOFTMAC_SINGLE_QUEUE is
+	 * not set. As some cards may have different HW queues that
+	 * one might want to use for data and management frames
+	 * the option to have two callbacks might be useful.
+	 * This fucntion can't sleep.
+	 */
+	int (*softmac_hard_start_xmit)(struct sk_buff *skb,
+			       struct net_device *dev);
+
+	/* used instead of hard_start_xmit (not softmac_hard_start_xmit)
+	 * if the IEEE_SOFTMAC_TX_QUEUE feature is used to TX data
+	 * frames. I the option IEEE_SOFTMAC_SINGLE_QUEUE is also set
+	 * then also management frames are sent via this callback.
+	 * This function can't sleep.
+	 */
+	void (*softmac_data_hard_start_xmit)(struct sk_buff *skb,
+			       struct net_device *dev,int rate);
+
+	/* stops the HW queue for DATA frames. Useful to avoid
+	 * waste time to TX data frame when we are reassociating
+	 * This function can sleep.
+	 */
+	void (*data_hard_stop)(struct net_device *dev);
+
+	/* OK this is complementar to data_poll_hard_stop */
+	void (*data_hard_resume)(struct net_device *dev);
+
+	/* ask to the driver to retune the radio .
+	 * This function can sleep. the driver should ensure
+	 * the radio has been swithced before return.
+	 */
+	void (*set_chan)(struct net_device *dev,short ch);
+
+	/* These are not used if the ieee stack takes care of
+	 * scanning (IEEE_SOFTMAC_SCAN feature set).
+	 * In this case only the set_chan is used.
+	 *
+	 * The syncro version is similar to the start_scan but
+	 * does not return until all channels has been scanned.
+	 * this is called in user context and should sleep,
+	 * it is called in a work_queue when swithcing to ad-hoc mode
+	 * or in behalf of iwlist scan when the card is associated
+	 * and root user ask for a scan.
+	 * the fucntion stop_scan should stop both the syncro and
+	 * background scanning and can sleep.
+	 * The fucntion start_scan should initiate the background
+	 * scanning and can't sleep.
+	 */
+	void (*scan_syncro)(struct net_device *dev);
+	void (*start_scan)(struct net_device *dev);
+	void (*stop_scan)(struct net_device *dev);
+
+	/* indicate the driver that the link state is changed
+	 * for example it may indicate the card is associated now.
+	 * Driver might be interested in this to apply RX filter
+	 * rules or simply light the LINK led
+	 */
+	void (*link_change)(struct net_device *dev);
+
+	/* these two function indicates to the HW when to start
+	 * and stop to send beacons. This is used when the
+	 * IEEE_SOFTMAC_BEACONS is not set. For now the
+	 * stop_send_bacons is NOT guaranteed to be called only
+	 * after start_send_beacons.
+	 */
+	void (*start_send_beacons) (struct net_device *dev);
+	void (*stop_send_beacons) (struct net_device *dev);
+
+	/* power save mode related */
+	void (*sta_wake_up) (struct net_device *dev);
+//	void (*ps_request_tx_ack) (struct net_device *dev);
+	void (*enter_sleep_state) (struct net_device *dev, u32 th, u32 tl);
+	short (*ps_is_queue_empty) (struct net_device *dev);
+#if 0
+	/* Typical STA methods */
+        int (*handle_auth) (struct net_device * dev,
+                            struct ieee80211_auth * auth);
+        int (*handle_deauth) (struct net_device * dev,
+                              struct ieee80211_deauth * auth);
+        int (*handle_action) (struct net_device * dev,
+                              struct ieee80211_action * action,
+                              struct ieee80211_rx_stats * stats);
+        int (*handle_disassoc) (struct net_device * dev,
+                                struct ieee80211_disassoc * assoc);
+#endif
+        int (*handle_beacon) (struct net_device * dev, struct ieee80211_beacon * beacon, struct ieee80211_network * network);
+#if 0
+        int (*handle_probe_response) (struct net_device * dev,
+                                      struct ieee80211_probe_response * resp,
+                                      struct ieee80211_network * network);
+        int (*handle_probe_request) (struct net_device * dev,
+                                     struct ieee80211_probe_request * req,
+                                     struct ieee80211_rx_stats * stats);
+#endif
+        int (*handle_assoc_response) (struct net_device * dev, struct ieee80211_assoc_response_frame * resp, struct ieee80211_network * network);
+
+#if 0
+        /* Typical AP methods */
+        int (*handle_assoc_request) (struct net_device * dev);
+        int (*handle_reassoc_request) (struct net_device * dev,
+                                       struct ieee80211_reassoc_request * req);
+#endif
+
+	/* check whether Tx hw resouce available */
+	short (*check_nic_enough_desc)(struct net_device *dev, int queue_index);
+	//added by wb for HT related
+//	void (*SwChnlByTimerHandler)(struct net_device *dev, int channel);
+	void (*SetBWModeHandler)(struct net_device *dev, HT_CHANNEL_WIDTH Bandwidth, HT_EXTCHNL_OFFSET Offset);
+//	void (*UpdateHalRATRTableHandler)(struct net_device* dev, u8* pMcsRate);
+	bool (*GetNmodeSupportBySecCfg)(struct net_device* dev);
+	void (*SetWirelessMode)(struct net_device* dev, u8 wireless_mode);
+	bool (*GetHalfNmodeSupportByAPsHandler)(struct net_device* dev);
+	bool (*is_ap_in_wep_tkip)(struct net_device* dev);
+	void (*InitialGainHandler)(struct net_device *dev, u8 Operation);
+	bool (*SetFwCmdHandler)(struct net_device *dev,	FW_CMD_IO_TYPE		FwCmdIO);
+	void (*LedControlHandler)(struct net_device * dev, LED_CTL_MODE LedAction);
+	/* This must be the last item so that it points to the data
+	 * allocated beyond this structure by alloc_ieee80211 */
+	u8 priv[0];
+};
+
+#define IEEE_A            (1<<0)
+#define IEEE_B            (1<<1)
+#define IEEE_G            (1<<2)
+#define IEEE_N_24G 		  (1<<4)
+#define	IEEE_N_5G		  (1<<5)
+#define IEEE_MODE_MASK    (IEEE_A|IEEE_B|IEEE_G)
+
+/* Generate a 802.11 header */
+
+/* Uses the channel change callback directly
+ * instead of [start/stop] scan callbacks
+ */
+#define IEEE_SOFTMAC_SCAN (1<<2)
+
+/* Perform authentication and association handshake */
+#define IEEE_SOFTMAC_ASSOCIATE (1<<3)
+
+/* Generate probe requests */
+#define IEEE_SOFTMAC_PROBERQ (1<<4)
+
+/* Generate respones to probe requests */
+#define IEEE_SOFTMAC_PROBERS (1<<5)
+
+/* The ieee802.11 stack will manages the netif queue
+ * wake/stop for the driver, taking care of 802.11
+ * fragmentation. See softmac.c for details. */
+#define IEEE_SOFTMAC_TX_QUEUE (1<<7)
+
+/* Uses only the softmac_data_hard_start_xmit
+ * even for TX management frames.
+ */
+#define IEEE_SOFTMAC_SINGLE_QUEUE (1<<8)
+
+/* Generate beacons.  The stack will enqueue beacons
+ * to the card
+ */
+#define IEEE_SOFTMAC_BEACONS (1<<6)
+
+static inline void *ieee80211_priv(struct net_device *dev)
+{
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	return ((struct ieee80211_device *)netdev_priv(dev))->priv;
+#else
+	return ((struct ieee80211_device *)dev->priv)->priv;
+#endif
+}
+
+extern inline int ieee80211_is_empty_essid(const char *essid, int essid_len)
+{
+	/* Single white space is for Linksys APs */
+	if (essid_len == 1 && essid[0] == ' ')
+		return 1;
+
+	/* Otherwise, if the entire essid is 0, we assume it is hidden */
+	while (essid_len) {
+		essid_len--;
+		if (essid[essid_len] != '\0')
+			return 0;
+	}
+
+	return 1;
+}
+
+extern inline int ieee80211_is_valid_mode(struct ieee80211_device *ieee, int mode)
+{
+	/*
+	 * It is possible for both access points and our device to support
+	 * combinations of modes, so as long as there is one valid combination
+	 * of ap/device supported modes, then return success
+	 *
+	 */
+	if ((mode & IEEE_A) &&
+	    (ieee->modulation & IEEE80211_OFDM_MODULATION) &&
+	    (ieee->freq_band & IEEE80211_52GHZ_BAND))
+		return 1;
+
+	if ((mode & IEEE_G) &&
+	    (ieee->modulation & IEEE80211_OFDM_MODULATION) &&
+	    (ieee->freq_band & IEEE80211_24GHZ_BAND))
+		return 1;
+
+	if ((mode & IEEE_B) &&
+	    (ieee->modulation & IEEE80211_CCK_MODULATION) &&
+	    (ieee->freq_band & IEEE80211_24GHZ_BAND))
+		return 1;
+
+	return 0;
+}
+
+extern inline int ieee80211_get_hdrlen(u16 fc)
+{
+	int hdrlen = IEEE80211_3ADDR_LEN;
+
+	switch (WLAN_FC_GET_TYPE(fc)) {
+	case IEEE80211_FTYPE_DATA:
+		if ((fc & IEEE80211_FCTL_FROMDS) && (fc & IEEE80211_FCTL_TODS))
+			hdrlen = IEEE80211_4ADDR_LEN; /* Addr4 */
+		if(IEEE80211_QOS_HAS_SEQ(fc))
+			hdrlen += 2; /* QOS ctrl*/
+		break;
+	case IEEE80211_FTYPE_CTL:
+		switch (WLAN_FC_GET_STYPE(fc)) {
+		case IEEE80211_STYPE_CTS:
+		case IEEE80211_STYPE_ACK:
+			hdrlen = IEEE80211_1ADDR_LEN;
+			break;
+		default:
+			hdrlen = IEEE80211_2ADDR_LEN;
+			break;
+		}
+		break;
+	}
+
+	return hdrlen;
+}
+
+static inline u8 *ieee80211_get_payload(struct ieee80211_hdr *hdr)
+{
+        switch (ieee80211_get_hdrlen(le16_to_cpu(hdr->frame_ctl))) {
+        case IEEE80211_1ADDR_LEN:
+                return ((struct ieee80211_hdr_1addr *)hdr)->payload;
+        case IEEE80211_2ADDR_LEN:
+                return ((struct ieee80211_hdr_2addr *)hdr)->payload;
+        case IEEE80211_3ADDR_LEN:
+                return ((struct ieee80211_hdr_3addr *)hdr)->payload;
+        case IEEE80211_4ADDR_LEN:
+                return ((struct ieee80211_hdr_4addr *)hdr)->payload;
+        }
+        return NULL;
+}
+
+static inline int ieee80211_is_ofdm_rate(u8 rate)
+{
+        switch (rate & ~IEEE80211_BASIC_RATE_MASK) {
+        case IEEE80211_OFDM_RATE_6MB:
+        case IEEE80211_OFDM_RATE_9MB:
+        case IEEE80211_OFDM_RATE_12MB:
+        case IEEE80211_OFDM_RATE_18MB:
+        case IEEE80211_OFDM_RATE_24MB:
+        case IEEE80211_OFDM_RATE_36MB:
+        case IEEE80211_OFDM_RATE_48MB:
+        case IEEE80211_OFDM_RATE_54MB:
+                return 1;
+        }
+        return 0;
+}
+
+static inline int ieee80211_is_cck_rate(u8 rate)
+{
+        switch (rate & ~IEEE80211_BASIC_RATE_MASK) {
+        case IEEE80211_CCK_RATE_1MB:
+        case IEEE80211_CCK_RATE_2MB:
+        case IEEE80211_CCK_RATE_5MB:
+        case IEEE80211_CCK_RATE_11MB:
+                return 1;
+        }
+        return 0;
+}
+
+
+/* ieee80211.c */
+extern void free_ieee80211(struct net_device *dev);
+extern struct net_device *alloc_ieee80211(int sizeof_priv);
+
+extern int ieee80211_set_encryption(struct ieee80211_device *ieee);
+
+/* ieee80211_tx.c */
+
+extern int ieee80211_encrypt_fragment(
+	struct ieee80211_device *ieee,
+	struct sk_buff *frag,
+	int hdr_len);
+
+extern int ieee80211_xmit(struct sk_buff *skb,
+			  struct net_device *dev);
+extern void ieee80211_txb_free(struct ieee80211_txb *);
+
+
+/* ieee80211_rx.c */
+extern int ieee80211_rx(struct ieee80211_device *ieee, struct sk_buff *skb,
+			struct ieee80211_rx_stats *rx_stats);
+extern void ieee80211_rx_mgt(struct ieee80211_device *ieee,
+			     struct ieee80211_hdr_4addr *header,
+			     struct ieee80211_rx_stats *stats);
+
+/* ieee80211_wx.c */
+extern int ieee80211_wx_get_scan(struct ieee80211_device *ieee,
+				 struct iw_request_info *info,
+				 union iwreq_data *wrqu, char *key);
+extern int ieee80211_wx_set_encode(struct ieee80211_device *ieee,
+				   struct iw_request_info *info,
+				   union iwreq_data *wrqu, char *key);
+extern int ieee80211_wx_get_encode(struct ieee80211_device *ieee,
+				   struct iw_request_info *info,
+				   union iwreq_data *wrqu, char *key);
+#if WIRELESS_EXT >= 18
+extern int ieee80211_wx_get_encode_ext(struct ieee80211_device *ieee,
+                            struct iw_request_info *info,
+                            union iwreq_data* wrqu, char *extra);
+extern int ieee80211_wx_set_encode_ext(struct ieee80211_device *ieee,
+                            struct iw_request_info *info,
+                            union iwreq_data* wrqu, char *extra);
+extern int ieee80211_wx_set_auth(struct ieee80211_device *ieee,
+                               struct iw_request_info *info,
+                               struct iw_param *data, char *extra);
+extern int ieee80211_wx_set_mlme(struct ieee80211_device *ieee,
+                               struct iw_request_info *info,
+                               union iwreq_data *wrqu, char *extra);
+#endif
+extern int ieee80211_wx_set_gen_ie(struct ieee80211_device *ieee, u8 *ie, size_t len);
+
+/* ieee80211_softmac.c */
+extern short ieee80211_is_54g(struct ieee80211_network net);
+extern short ieee80211_is_shortslot(struct ieee80211_network net);
+extern int ieee80211_rx_frame_softmac(struct ieee80211_device *ieee, struct sk_buff *skb,
+			struct ieee80211_rx_stats *rx_stats, u16 type,
+			u16 stype);
+extern void ieee80211_softmac_new_net(struct ieee80211_device *ieee, struct ieee80211_network *net);
+
+void SendDisassociation(struct ieee80211_device *ieee, u8* asSta, u8 asRsn);
+extern void ieee80211_softmac_xmit(struct ieee80211_txb *txb, struct ieee80211_device *ieee);
+
+extern void ieee80211_stop_send_beacons(struct ieee80211_device *ieee);
+extern void notify_wx_assoc_event(struct ieee80211_device *ieee);
+extern void ieee80211_softmac_check_all_nets(struct ieee80211_device *ieee);
+extern void ieee80211_start_bss(struct ieee80211_device *ieee);
+extern void ieee80211_start_master_bss(struct ieee80211_device *ieee);
+extern void ieee80211_start_ibss(struct ieee80211_device *ieee);
+extern void ieee80211_softmac_init(struct ieee80211_device *ieee);
+extern void ieee80211_softmac_free(struct ieee80211_device *ieee);
+extern void ieee80211_associate_abort(struct ieee80211_device *ieee);
+extern void ieee80211_disassociate(struct ieee80211_device *ieee);
+extern void ieee80211_stop_scan(struct ieee80211_device *ieee);
+extern void ieee80211_start_scan_syncro(struct ieee80211_device *ieee);
+extern void ieee80211_check_all_nets(struct ieee80211_device *ieee);
+extern void ieee80211_start_protocol(struct ieee80211_device *ieee);
+extern void ieee80211_stop_protocol(struct ieee80211_device *ieee);
+extern void ieee80211_softmac_start_protocol(struct ieee80211_device *ieee);
+extern void ieee80211_softmac_stop_protocol(struct ieee80211_device *ieee);
+extern void ieee80211_reset_queue(struct ieee80211_device *ieee);
+extern void ieee80211_wake_queue(struct ieee80211_device *ieee);
+extern void ieee80211_stop_queue(struct ieee80211_device *ieee);
+extern struct sk_buff *ieee80211_get_beacon(struct ieee80211_device *ieee);
+extern void ieee80211_start_send_beacons(struct ieee80211_device *ieee);
+extern void ieee80211_stop_send_beacons(struct ieee80211_device *ieee);
+extern int ieee80211_wpa_supplicant_ioctl(struct ieee80211_device *ieee, struct iw_point *p);
+extern void notify_wx_assoc_event(struct ieee80211_device *ieee);
+extern void ieee80211_ps_tx_ack(struct ieee80211_device *ieee, short success);
+
+extern void softmac_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee);
+
+/* ieee80211_crypt_ccmp&tkip&wep.c */
+extern void ieee80211_tkip_null(void);
+extern void ieee80211_wep_null(void);
+extern void ieee80211_ccmp_null(void);
+
+/* ieee80211_softmac_wx.c */
+
+extern int ieee80211_wx_get_wap(struct ieee80211_device *ieee,
+			    struct iw_request_info *info,
+			    union iwreq_data *wrqu, char *ext);
+
+extern int ieee80211_wx_set_wap(struct ieee80211_device *ieee,
+			 struct iw_request_info *info,
+			 union iwreq_data *awrq,
+			 char *extra);
+
+extern int ieee80211_wx_get_essid(struct ieee80211_device *ieee, struct iw_request_info *a,union iwreq_data *wrqu,char *b);
+
+extern int ieee80211_wx_set_rate(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_get_rate(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_set_mode(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b);
+
+extern int ieee80211_wx_set_scan(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b);
+
+extern int ieee80211_wx_set_essid(struct ieee80211_device *ieee,
+			      struct iw_request_info *a,
+			      union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_get_mode(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b);
+
+extern int ieee80211_wx_set_freq(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b);
+
+extern int ieee80211_wx_get_freq(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b);
+
+//extern void ieee80211_wx_sync_scan_wq(struct ieee80211_device *ieee);
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern void ieee80211_wx_sync_scan_wq(struct work_struct *work);
+#else
+ extern void ieee80211_wx_sync_scan_wq(struct ieee80211_device *ieee);
+#endif
+
+
+extern int ieee80211_wx_set_rawtx(struct ieee80211_device *ieee,
+			       struct iw_request_info *info,
+			       union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_get_name(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_set_power(struct ieee80211_device *ieee,
+				 struct iw_request_info *info,
+				 union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_get_power(struct ieee80211_device *ieee,
+				 struct iw_request_info *info,
+				 union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_set_rts(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_get_rts(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra);
+//HT
+#define MAX_RECEIVE_BUFFER_SIZE 9100  //
+extern void HTDebugHTCapability(u8* CapIE, u8* TitleString );
+extern void HTDebugHTInfo(u8*  InfoIE, u8* TitleString);
+
+void HTSetConnectBwMode(struct ieee80211_device* ieee, HT_CHANNEL_WIDTH Bandwidth, HT_EXTCHNL_OFFSET    Offset);
+extern void HTUpdateDefaultSetting(struct ieee80211_device* ieee);
+extern void HTConstructCapabilityElement(struct ieee80211_device* ieee, u8* posHTCap, u8* len, u8 isEncrypt);
+extern void HTConstructInfoElement(struct ieee80211_device* ieee, u8* posHTInfo, u8* len, u8 isEncrypt);
+extern void HTConstructRT2RTAggElement(struct ieee80211_device* ieee, u8* posRT2RTAgg, u8* len);
+extern void HTOnAssocRsp(struct ieee80211_device *ieee);
+extern void HTInitializeHTInfo(struct ieee80211_device* ieee);
+extern void HTInitializeBssDesc(PBSS_HT pBssHT);
+extern void HTResetSelfAndSavePeerSetting(struct ieee80211_device* ieee, struct ieee80211_network * pNetwork);
+extern void HTUpdateSelfAndPeerSetting(struct ieee80211_device* ieee,   struct ieee80211_network * pNetwork);
+extern u8 HTGetHighestMCSRate(struct ieee80211_device* ieee, u8* pMCSRateSet, u8* pMCSFilter);
+extern u8 MCS_FILTER_ALL[];
+extern u16 MCS_DATA_RATE[2][2][77] ;
+extern u8 HTCCheck(struct ieee80211_device* ieee, u8*   pFrame);
+//extern void HTSetConnectBwModeCallback(unsigned long data);
+extern void HTResetIOTSetting(PRT_HIGH_THROUGHPUT  pHTInfo);
+extern bool IsHTHalfNmodeAPs(struct ieee80211_device* ieee);
+extern u16 HTHalfMcsToDataRate(struct ieee80211_device* ieee,  u8      nMcsRate);
+extern u16 HTMcsToDataRate( struct ieee80211_device* ieee, u8 nMcsRate);
+extern u16  TxCountToDataRate( struct ieee80211_device* ieee, u8 nDataRate);
+//function in BAPROC.c
+extern int ieee80211_rx_ADDBAReq( struct ieee80211_device* ieee, struct sk_buff *skb);
+extern int ieee80211_rx_ADDBARsp( struct ieee80211_device* ieee, struct sk_buff *skb);
+extern int ieee80211_rx_DELBA(struct ieee80211_device* ieee,struct sk_buff *skb);
+extern void TsInitAddBA( struct ieee80211_device* ieee, PTX_TS_RECORD   pTS, u8 Policy, u8 bOverwritePending);
+extern void TsInitDelBA( struct ieee80211_device* ieee, PTS_COMMON_INFO pTsCommonInfo, TR_SELECT TxRxSelect);
+extern void BaSetupTimeOut(unsigned long data);
+extern void TxBaInactTimeout(unsigned long data);
+extern void RxBaInactTimeout(unsigned long data);
+extern void ResetBaEntry( PBA_RECORD pBA);
+//function in TS.c
+extern bool GetTs(
+        struct ieee80211_device*        ieee,
+        PTS_COMMON_INFO                 *ppTS,
+        u8*                             Addr,
+        u8                              TID,
+        TR_SELECT                       TxRxSelect,  //Rx:1, Tx:0
+        bool                            bAddNewTs
+        );
+extern void TSInitialize(struct ieee80211_device *ieee);
+extern  void TsStartAddBaProcess(struct ieee80211_device* ieee, PTX_TS_RECORD   pTxTS);
+extern void RemovePeerTS(struct ieee80211_device* ieee, u8* Addr);
+extern void RemoveAllTS(struct ieee80211_device* ieee);
+void ieee80211_softmac_scan_syncro(struct ieee80211_device *ieee);
+
+extern const long ieee80211_wlan_frequencies[];
+
+extern inline void ieee80211_increment_scans(struct ieee80211_device *ieee)
+{
+	ieee->scans++;
+}
+
+extern inline int ieee80211_get_scans(struct ieee80211_device *ieee)
+{
+	return ieee->scans;
+}
+
+static inline const char *escape_essid(const char *essid, u8 essid_len) {
+	static char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
+	const char *s = essid;
+	char *d = escaped;
+
+	if (ieee80211_is_empty_essid(essid, essid_len)) {
+		memcpy(escaped, "<hidden>", sizeof("<hidden>"));
+		return escaped;
+	}
+
+	essid_len = min(essid_len, (u8)IW_ESSID_MAX_SIZE);
+	while (essid_len--) {
+		if (*s == '\0') {
+			*d++ = '\\';
+			*d++ = '0';
+			s++;
+		} else {
+			*d++ = *s++;
+		}
+	}
+	*d = '\0';
+	return escaped;
+}
+
+/* For the function is more related to hardware setting, it's better to use the
+ * ieee handler to refer to it.
+ */
+extern short check_nic_enough_desc(struct net_device *dev, int queue_index);
+extern int ieee80211_data_xmit(struct sk_buff *skb, struct net_device *dev);
+extern int ieee80211_parse_info_param(struct ieee80211_device *ieee,
+		struct ieee80211_info_element *info_element,
+		u16 length,
+		struct ieee80211_network *network,
+		struct ieee80211_rx_stats *stats);
+
+void ieee80211_indicate_packets(struct ieee80211_device *ieee, struct ieee80211_rxb** prxbIndicateArray,u8  index);
+#define RT_ASOC_RETRY_LIMIT	5
+#endif /* IEEE80211_H */
diff --git a/drivers/staging/rtl8192su/ieee80211/EndianFree.h b/drivers/staging/rtl8192su/ieee80211/EndianFree.h
new file mode 100644
index 0000000..0c417a6
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/EndianFree.h
@@ -0,0 +1,199 @@
+#ifndef __INC_ENDIANFREE_H
+#define __INC_ENDIANFREE_H
+
+/*
+ *	Call endian free function when
+ *		1. Read/write packet content.
+ *		2. Before write integer to IO.
+ *		3. After read integer from IO.
+ */
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20))
+#ifndef bool
+typedef enum{false = 0, true} bool;
+#endif
+#endif
+
+#define __MACHINE_LITTLE_ENDIAN 1234    /* LSB first: i386, vax */
+#define __MACHINE_BIG_ENDIAN    4321    /* MSB first: 68000, ibm, net, ppc */
+
+#define BYTE_ORDER __MACHINE_LITTLE_ENDIAN
+
+#if BYTE_ORDER == __MACHINE_LITTLE_ENDIAN
+// Convert data
+#define EF1Byte(_val)				((u8)(_val))
+#define EF2Byte(_val)				((u16)(_val))
+#define EF4Byte(_val)				((u32)(_val))
+
+#else
+// Convert data
+#define EF1Byte(_val)				((u8)(_val))
+#define EF2Byte(_val)				(((((u16)(_val))&0x00ff)<<8)|((((u16)(_val))&0xff00)>>8))
+#define EF4Byte(_val)				(((((u32)(_val))&0x000000ff)<<24)|\
+						((((u32)(_val))&0x0000ff00)<<8)|\
+						((((u32)(_val))&0x00ff0000)>>8)|\
+						((((u32)(_val))&0xff000000)>>24))
+#endif
+
+// Read data from memory
+#define ReadEF1Byte(_ptr)		EF1Byte(*((u8 *)(_ptr)))
+#define ReadEF2Byte(_ptr)		EF2Byte(*((u16 *)(_ptr)))
+#define ReadEF4Byte(_ptr)		EF4Byte(*((u32 *)(_ptr)))
+
+// Write data to memory
+#define WriteEF1Byte(_ptr, _val)	(*((u8 *)(_ptr)))=EF1Byte(_val)
+#define WriteEF2Byte(_ptr, _val)	(*((u16 *)(_ptr)))=EF2Byte(_val)
+#define WriteEF4Byte(_ptr, _val)	(*((u32 *)(_ptr)))=EF4Byte(_val)
+// Convert Host system specific byte ording (litten or big endia) to Network byte ording (big endian).
+// 2006.05.07, by rcnjko.
+#if BYTE_ORDER == __MACHINE_LITTLE_ENDIAN
+#define H2N1BYTE(_val)	((u8)(_val))
+#define H2N2BYTE(_val)	(((((u16)(_val))&0x00ff)<<8)|\
+			((((u16)(_val))&0xff00)>>8))
+#define H2N4BYTE(_val)	(((((u32)(_val))&0x000000ff)<<24)|\
+			((((u32)(_val))&0x0000ff00)<<8)	|\
+			((((u32)(_val))&0x00ff0000)>>8)	|\
+			((((u32)(_val))&0xff000000)>>24))
+#else
+#define H2N1BYTE(_val)			((u8)(_val))
+#define H2N2BYTE(_val)			((u16)(_val))
+#define H2N4BYTE(_val)			((u32)(_val))
+#endif
+
+// Convert from Network byte ording (big endian) to Host system specific byte ording (litten or big endia).
+// 2006.05.07, by rcnjko.
+#if BYTE_ORDER == __MACHINE_LITTLE_ENDIAN
+#define N2H1BYTE(_val)	((u8)(_val))
+#define N2H2BYTE(_val)	(((((u16)(_val))&0x00ff)<<8)|\
+			((((u16)(_val))&0xff00)>>8))
+#define N2H4BYTE(_val)	(((((u32)(_val))&0x000000ff)<<24)|\
+			((((u32)(_val))&0x0000ff00)<<8)	|\
+			((((u32)(_val))&0x00ff0000)>>8)	|\
+			((((u32)(_val))&0xff000000)>>24))
+#else
+#define N2H1BYTE(_val)			((u8)(_val))
+#define N2H2BYTE(_val)			((u16)(_val))
+#define N2H4BYTE(_val)			((u32)(_val))
+#endif
+
+//
+//	Example:
+//		BIT_LEN_MASK_32(0) => 0x00000000
+//		BIT_LEN_MASK_32(1) => 0x00000001
+//		BIT_LEN_MASK_32(2) => 0x00000003
+//		BIT_LEN_MASK_32(32) => 0xFFFFFFFF
+//
+#define BIT_LEN_MASK_32(__BitLen) (0xFFFFFFFF >> (32 - (__BitLen)))
+//
+//	Example:
+//		BIT_OFFSET_LEN_MASK_32(0, 2) => 0x00000003
+//		BIT_OFFSET_LEN_MASK_32(16, 2) => 0x00030000
+//
+#define BIT_OFFSET_LEN_MASK_32(__BitOffset, __BitLen) (BIT_LEN_MASK_32(__BitLen) << (__BitOffset))
+
+//
+//	Description:
+//		Return 4-byte value in host byte ordering from
+//		4-byte pointer in litten-endian system.
+//
+#define LE_P4BYTE_TO_HOST_4BYTE(__pStart) (EF4Byte(*((u32 *)(__pStart))))
+
+//
+//	Description:
+//		Translate subfield (continuous bits in little-endian) of 4-byte value in litten byte to
+//		4-byte value in host byte ordering.
+//
+#define LE_BITS_TO_4BYTE(__pStart, __BitOffset, __BitLen) \
+	( \
+	  ( LE_P4BYTE_TO_HOST_4BYTE(__pStart) >> (__BitOffset) ) \
+	  & \
+	  BIT_LEN_MASK_32(__BitLen) \
+	)
+
+//
+//	Description:
+//		Mask subfield (continuous bits in little-endian) of 4-byte value in litten byte oredering
+//		and return the result in 4-byte value in host byte ordering.
+//
+#define LE_BITS_CLEARED_TO_4BYTE(__pStart, __BitOffset, __BitLen) \
+	( \
+	  LE_P4BYTE_TO_HOST_4BYTE(__pStart) \
+	  & \
+	  ( ~BIT_OFFSET_LEN_MASK_32(__BitOffset, __BitLen) ) \
+	)
+
+//
+//	Description:
+//		Set subfield of little-endian 4-byte value to specified value.
+//
+#define SET_BITS_TO_LE_4BYTE(__pStart, __BitOffset, __BitLen, __Value) \
+	*((u32 *)(__pStart)) = \
+	EF4Byte( \
+	LE_BITS_CLEARED_TO_4BYTE(__pStart, __BitOffset, __BitLen) \
+	| \
+	( (((u32)__Value) & BIT_LEN_MASK_32(__BitLen)) << (__BitOffset) ) \
+       );
+
+
+#define BIT_LEN_MASK_16(__BitLen) \
+	(0xFFFF >> (16 - (__BitLen)))
+
+#define BIT_OFFSET_LEN_MASK_16(__BitOffset, __BitLen) \
+	(BIT_LEN_MASK_16(__BitLen) << (__BitOffset))
+
+#define LE_P2BYTE_TO_HOST_2BYTE(__pStart) \
+	(EF2Byte(*((u16 *)(__pStart))))
+
+#define LE_BITS_TO_2BYTE(__pStart, __BitOffset, __BitLen) \
+	( \
+	  ( LE_P2BYTE_TO_HOST_2BYTE(__pStart) >> (__BitOffset) ) \
+	  & \
+	  BIT_LEN_MASK_16(__BitLen) \
+	)
+
+#define LE_BITS_CLEARED_TO_2BYTE(__pStart, __BitOffset, __BitLen) \
+	( \
+	  LE_P2BYTE_TO_HOST_2BYTE(__pStart) \
+	  & \
+	  ( ~BIT_OFFSET_LEN_MASK_16(__BitOffset, __BitLen) ) \
+	)
+
+#define SET_BITS_TO_LE_2BYTE(__pStart, __BitOffset, __BitLen, __Value) \
+	*((u16 *)(__pStart)) = \
+	EF2Byte( \
+		LE_BITS_CLEARED_TO_2BYTE(__pStart, __BitOffset, __BitLen) \
+		| \
+		( (((u16)__Value) & BIT_LEN_MASK_16(__BitLen)) << (__BitOffset) ) \
+       );
+
+#define BIT_LEN_MASK_8(__BitLen) \
+	(0xFF >> (8 - (__BitLen)))
+
+#define BIT_OFFSET_LEN_MASK_8(__BitOffset, __BitLen) \
+	(BIT_LEN_MASK_8(__BitLen) << (__BitOffset))
+
+#define LE_P1BYTE_TO_HOST_1BYTE(__pStart) \
+	(EF1Byte(*((u8 *)(__pStart))))
+
+#define LE_BITS_TO_1BYTE(__pStart, __BitOffset, __BitLen) \
+	( \
+	  ( LE_P1BYTE_TO_HOST_1BYTE(__pStart) >> (__BitOffset) ) \
+	  & \
+	  BIT_LEN_MASK_8(__BitLen) \
+	)
+
+#define LE_BITS_CLEARED_TO_1BYTE(__pStart, __BitOffset, __BitLen) \
+	( \
+	  LE_P1BYTE_TO_HOST_1BYTE(__pStart) \
+	  & \
+	  ( ~BIT_OFFSET_LEN_MASK_8(__BitOffset, __BitLen) ) \
+	)
+
+#define SET_BITS_TO_LE_1BYTE(__pStart, __BitOffset, __BitLen, __Value) \
+	*((u8 *)(__pStart)) = \
+	EF1Byte( \
+		LE_BITS_CLEARED_TO_1BYTE(__pStart, __BitOffset, __BitLen) \
+		| \
+		( (((u8)__Value) & BIT_LEN_MASK_8(__BitLen)) << (__BitOffset) ) \
+       );
+
+#endif // #ifndef __INC_ENDIANFREE_H
diff --git a/drivers/staging/rtl8192su/ieee80211/Makefile b/drivers/staging/rtl8192su/ieee80211/Makefile
new file mode 100644
index 0000000..295a18f
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/Makefile
@@ -0,0 +1,31 @@
+NIC_SELECT = RTL8192SU
+
+EXTRA_CFLAGS += -O2
+EXTRA_CFLAGS += -DRTL8192S_DISABLE_FW_DM=0
+EXTRA_CFLAGS += -DRTL8192SU
+#EXTRA_CFLAGS += -DJOHN_NOCPY
+EXTRA_CFLAGS += -DTHOMAS_TURBO
+#flags to enable or disble 80211D feature
+EXTRA_CFLAGS += -DENABLE_DOT11D
+ieee80211-rsl-objs := ieee80211_rx.o \
+		      ieee80211_softmac.o \
+		      ieee80211_tx.o \
+		      ieee80211_wx.o \
+		      ieee80211_module.o \
+		      ieee80211_softmac_wx.o\
+		      rtl819x_HTProc.o\
+		      rtl819x_TSProc.o\
+		      rtl819x_BAProc.o\
+		      dot11d.o
+
+ieee80211_crypt-rsl-objs := ieee80211_crypt.o
+ieee80211_crypt_tkip-rsl-objs := ieee80211_crypt_tkip.o
+ieee80211_crypt_ccmp-rsl-objs := ieee80211_crypt_ccmp.o
+ieee80211_crypt_wep-rsl-objs := ieee80211_crypt_wep.o
+
+obj-m +=ieee80211-rsl.o
+obj-m +=ieee80211_crypt-rsl.o
+obj-m +=ieee80211_crypt_wep-rsl.o
+obj-m +=ieee80211_crypt_tkip-rsl.o
+obj-m +=ieee80211_crypt_ccmp-rsl.o
+
diff --git a/drivers/staging/rtl8192su/ieee80211/aes.c b/drivers/staging/rtl8192su/ieee80211/aes.c
new file mode 100644
index 0000000..0c176e2
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/aes.c
@@ -0,0 +1,469 @@
+/*
+ * Cryptographic API.
+ *
+ * AES Cipher Algorithm.
+ *
+ * Based on Brian Gladman's code.
+ *
+ * Linux developers:
+ *  Alexander Kjeldaas <astor@fast.no>
+ *  Herbert Valerio Riedel <hvr@hvrlab.org>
+ *  Kyle McMartin <kyle@debian.org>
+ *  Adam J. Richter <adam@yggdrasil.com> (conversion to 2.5 API).
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * ---------------------------------------------------------------------------
+ * Copyright (c) 2002, Dr Brian Gladman <brg@gladman.me.uk>, Worcester, UK.
+ * All rights reserved.
+ *
+ * LICENSE TERMS
+ *
+ * The free distribution and use of this software in both source and binary
+ * form is allowed (with or without changes) provided that:
+ *
+ *   1. distributions of this source code include the above copyright
+ *      notice, this list of conditions and the following disclaimer;
+ *
+ *   2. distributions in binary form include the above copyright
+ *      notice, this list of conditions and the following disclaimer
+ *      in the documentation and/or other associated materials;
+ *
+ *   3. the copyright holder's name is not used to endorse products
+ *      built using this software without specific written permission.
+ *
+ * ALTERNATIVELY, provided that this notice is retained in full, this product
+ * may be distributed under the terms of the GNU General Public License (GPL),
+ * in which case the provisions of the GPL apply INSTEAD OF those given above.
+ *
+ * DISCLAIMER
+ *
+ * This software is provided 'as is' with no explicit or implied warranties
+ * in respect of its properties, including, but not limited to, correctness
+ * and/or fitness for purpose.
+ * ---------------------------------------------------------------------------
+ */
+
+/* Some changes from the Gladman version:
+    s/RIJNDAEL(e_key)/E_KEY/g
+    s/RIJNDAEL(d_key)/D_KEY/g
+*/
+
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/types.h>
+#include <linux/errno.h>
+//#include <linux/crypto.h>
+#include "rtl_crypto.h"
+#include <asm/byteorder.h>
+
+#define AES_MIN_KEY_SIZE	16
+#define AES_MAX_KEY_SIZE	32
+
+#define AES_BLOCK_SIZE		16
+
+static inline
+u32 generic_rotr32 (const u32 x, const unsigned bits)
+{
+	const unsigned n = bits % 32;
+	return (x >> n) | (x << (32 - n));
+}
+
+static inline
+u32 generic_rotl32 (const u32 x, const unsigned bits)
+{
+	const unsigned n = bits % 32;
+	return (x << n) | (x >> (32 - n));
+}
+
+#define rotl generic_rotl32
+#define rotr generic_rotr32
+
+/*
+ * #define byte(x, nr) ((unsigned char)((x) >> (nr*8)))
+ */
+inline static u8
+byte(const u32 x, const unsigned n)
+{
+	return x >> (n << 3);
+}
+
+#define u32_in(x) le32_to_cpu(*(const u32 *)(x))
+#define u32_out(to, from) (*(u32 *)(to) = cpu_to_le32(from))
+
+struct aes_ctx {
+	int key_length;
+	u32 E[60];
+	u32 D[60];
+};
+
+#define E_KEY ctx->E
+#define D_KEY ctx->D
+
+static u8 pow_tab[256] __initdata;
+static u8 log_tab[256] __initdata;
+static u8 sbx_tab[256] __initdata;
+static u8 isb_tab[256] __initdata;
+static u32 rco_tab[10];
+static u32 ft_tab[4][256];
+static u32 it_tab[4][256];
+
+static u32 fl_tab[4][256];
+static u32 il_tab[4][256];
+
+static inline u8 __init
+f_mult (u8 a, u8 b)
+{
+	u8 aa = log_tab[a], cc = aa + log_tab[b];
+
+	return pow_tab[cc + (cc < aa ? 1 : 0)];
+}
+
+#define ff_mult(a,b)    (a && b ? f_mult(a, b) : 0)
+
+#define f_rn(bo, bi, n, k)					\
+    bo[n] =  ft_tab[0][byte(bi[n],0)] ^				\
+             ft_tab[1][byte(bi[(n + 1) & 3],1)] ^		\
+             ft_tab[2][byte(bi[(n + 2) & 3],2)] ^		\
+             ft_tab[3][byte(bi[(n + 3) & 3],3)] ^ *(k + n)
+
+#define i_rn(bo, bi, n, k)					\
+    bo[n] =  it_tab[0][byte(bi[n],0)] ^				\
+             it_tab[1][byte(bi[(n + 3) & 3],1)] ^		\
+             it_tab[2][byte(bi[(n + 2) & 3],2)] ^		\
+             it_tab[3][byte(bi[(n + 1) & 3],3)] ^ *(k + n)
+
+#define ls_box(x)				\
+    ( fl_tab[0][byte(x, 0)] ^			\
+      fl_tab[1][byte(x, 1)] ^			\
+      fl_tab[2][byte(x, 2)] ^			\
+      fl_tab[3][byte(x, 3)] )
+
+#define f_rl(bo, bi, n, k)					\
+    bo[n] =  fl_tab[0][byte(bi[n],0)] ^				\
+             fl_tab[1][byte(bi[(n + 1) & 3],1)] ^		\
+             fl_tab[2][byte(bi[(n + 2) & 3],2)] ^		\
+             fl_tab[3][byte(bi[(n + 3) & 3],3)] ^ *(k + n)
+
+#define i_rl(bo, bi, n, k)					\
+    bo[n] =  il_tab[0][byte(bi[n],0)] ^				\
+             il_tab[1][byte(bi[(n + 3) & 3],1)] ^		\
+             il_tab[2][byte(bi[(n + 2) & 3],2)] ^		\
+             il_tab[3][byte(bi[(n + 1) & 3],3)] ^ *(k + n)
+
+static void __init
+gen_tabs (void)
+{
+	u32 i, t;
+	u8 p, q;
+
+	/* log and power tables for GF(2**8) finite field with
+	   0x011b as modular polynomial - the simplest primitive
+	   root is 0x03, used here to generate the tables */
+
+	for (i = 0, p = 1; i < 256; ++i) {
+		pow_tab[i] = (u8) p;
+		log_tab[p] = (u8) i;
+
+		p ^= (p << 1) ^ (p & 0x80 ? 0x01b : 0);
+	}
+
+	log_tab[1] = 0;
+
+	for (i = 0, p = 1; i < 10; ++i) {
+		rco_tab[i] = p;
+
+		p = (p << 1) ^ (p & 0x80 ? 0x01b : 0);
+	}
+
+	for (i = 0; i < 256; ++i) {
+		p = (i ? pow_tab[255 - log_tab[i]] : 0);
+		q = ((p >> 7) | (p << 1)) ^ ((p >> 6) | (p << 2));
+		p ^= 0x63 ^ q ^ ((q >> 6) | (q << 2));
+		sbx_tab[i] = p;
+		isb_tab[p] = (u8) i;
+	}
+
+	for (i = 0; i < 256; ++i) {
+		p = sbx_tab[i];
+
+		t = p;
+		fl_tab[0][i] = t;
+		fl_tab[1][i] = rotl (t, 8);
+		fl_tab[2][i] = rotl (t, 16);
+		fl_tab[3][i] = rotl (t, 24);
+
+		t = ((u32) ff_mult (2, p)) |
+		    ((u32) p << 8) |
+		    ((u32) p << 16) | ((u32) ff_mult (3, p) << 24);
+
+		ft_tab[0][i] = t;
+		ft_tab[1][i] = rotl (t, 8);
+		ft_tab[2][i] = rotl (t, 16);
+		ft_tab[3][i] = rotl (t, 24);
+
+		p = isb_tab[i];
+
+		t = p;
+		il_tab[0][i] = t;
+		il_tab[1][i] = rotl (t, 8);
+		il_tab[2][i] = rotl (t, 16);
+		il_tab[3][i] = rotl (t, 24);
+
+		t = ((u32) ff_mult (14, p)) |
+		    ((u32) ff_mult (9, p) << 8) |
+		    ((u32) ff_mult (13, p) << 16) |
+		    ((u32) ff_mult (11, p) << 24);
+
+		it_tab[0][i] = t;
+		it_tab[1][i] = rotl (t, 8);
+		it_tab[2][i] = rotl (t, 16);
+		it_tab[3][i] = rotl (t, 24);
+	}
+}
+
+#define star_x(x) (((x) & 0x7f7f7f7f) << 1) ^ ((((x) & 0x80808080) >> 7) * 0x1b)
+
+#define imix_col(y,x)       \
+    u   = star_x(x);        \
+    v   = star_x(u);        \
+    w   = star_x(v);        \
+    t   = w ^ (x);          \
+   (y)  = u ^ v ^ w;        \
+   (y) ^= rotr(u ^ t,  8) ^ \
+          rotr(v ^ t, 16) ^ \
+          rotr(t,24)
+
+/* initialise the key schedule from the user supplied key */
+
+#define loop4(i)                                    \
+{   t = rotr(t,  8); t = ls_box(t) ^ rco_tab[i];    \
+    t ^= E_KEY[4 * i];     E_KEY[4 * i + 4] = t;    \
+    t ^= E_KEY[4 * i + 1]; E_KEY[4 * i + 5] = t;    \
+    t ^= E_KEY[4 * i + 2]; E_KEY[4 * i + 6] = t;    \
+    t ^= E_KEY[4 * i + 3]; E_KEY[4 * i + 7] = t;    \
+}
+
+#define loop6(i)                                    \
+{   t = rotr(t,  8); t = ls_box(t) ^ rco_tab[i];    \
+    t ^= E_KEY[6 * i];     E_KEY[6 * i + 6] = t;    \
+    t ^= E_KEY[6 * i + 1]; E_KEY[6 * i + 7] = t;    \
+    t ^= E_KEY[6 * i + 2]; E_KEY[6 * i + 8] = t;    \
+    t ^= E_KEY[6 * i + 3]; E_KEY[6 * i + 9] = t;    \
+    t ^= E_KEY[6 * i + 4]; E_KEY[6 * i + 10] = t;   \
+    t ^= E_KEY[6 * i + 5]; E_KEY[6 * i + 11] = t;   \
+}
+
+#define loop8(i)                                    \
+{   t = rotr(t,  8); ; t = ls_box(t) ^ rco_tab[i];  \
+    t ^= E_KEY[8 * i];     E_KEY[8 * i + 8] = t;    \
+    t ^= E_KEY[8 * i + 1]; E_KEY[8 * i + 9] = t;    \
+    t ^= E_KEY[8 * i + 2]; E_KEY[8 * i + 10] = t;   \
+    t ^= E_KEY[8 * i + 3]; E_KEY[8 * i + 11] = t;   \
+    t  = E_KEY[8 * i + 4] ^ ls_box(t);    \
+    E_KEY[8 * i + 12] = t;                \
+    t ^= E_KEY[8 * i + 5]; E_KEY[8 * i + 13] = t;   \
+    t ^= E_KEY[8 * i + 6]; E_KEY[8 * i + 14] = t;   \
+    t ^= E_KEY[8 * i + 7]; E_KEY[8 * i + 15] = t;   \
+}
+
+static int
+aes_set_key(void *ctx_arg, const u8 *in_key, unsigned int key_len, u32 *flags)
+{
+	struct aes_ctx *ctx = ctx_arg;
+	u32 i, t, u, v, w;
+
+	if (key_len != 16 && key_len != 24 && key_len != 32) {
+		*flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
+		return -EINVAL;
+	}
+
+	ctx->key_length = key_len;
+
+	E_KEY[0] = u32_in (in_key);
+	E_KEY[1] = u32_in (in_key + 4);
+	E_KEY[2] = u32_in (in_key + 8);
+	E_KEY[3] = u32_in (in_key + 12);
+
+	switch (key_len) {
+	case 16:
+		t = E_KEY[3];
+		for (i = 0; i < 10; ++i)
+			loop4 (i);
+		break;
+
+	case 24:
+		E_KEY[4] = u32_in (in_key + 16);
+		t = E_KEY[5] = u32_in (in_key + 20);
+		for (i = 0; i < 8; ++i)
+			loop6 (i);
+		break;
+
+	case 32:
+		E_KEY[4] = u32_in (in_key + 16);
+		E_KEY[5] = u32_in (in_key + 20);
+		E_KEY[6] = u32_in (in_key + 24);
+		t = E_KEY[7] = u32_in (in_key + 28);
+		for (i = 0; i < 7; ++i)
+			loop8 (i);
+		break;
+	}
+
+	D_KEY[0] = E_KEY[0];
+	D_KEY[1] = E_KEY[1];
+	D_KEY[2] = E_KEY[2];
+	D_KEY[3] = E_KEY[3];
+
+	for (i = 4; i < key_len + 24; ++i) {
+		imix_col (D_KEY[i], E_KEY[i]);
+	}
+
+	return 0;
+}
+
+/* encrypt a block of text */
+
+#define f_nround(bo, bi, k) \
+    f_rn(bo, bi, 0, k);     \
+    f_rn(bo, bi, 1, k);     \
+    f_rn(bo, bi, 2, k);     \
+    f_rn(bo, bi, 3, k);     \
+    k += 4
+
+#define f_lround(bo, bi, k) \
+    f_rl(bo, bi, 0, k);     \
+    f_rl(bo, bi, 1, k);     \
+    f_rl(bo, bi, 2, k);     \
+    f_rl(bo, bi, 3, k)
+
+static void aes_encrypt(void *ctx_arg, u8 *out, const u8 *in)
+{
+	const struct aes_ctx *ctx = ctx_arg;
+	u32 b0[4], b1[4];
+	const u32 *kp = E_KEY + 4;
+
+	b0[0] = u32_in (in) ^ E_KEY[0];
+	b0[1] = u32_in (in + 4) ^ E_KEY[1];
+	b0[2] = u32_in (in + 8) ^ E_KEY[2];
+	b0[3] = u32_in (in + 12) ^ E_KEY[3];
+
+	if (ctx->key_length > 24) {
+		f_nround (b1, b0, kp);
+		f_nround (b0, b1, kp);
+	}
+
+	if (ctx->key_length > 16) {
+		f_nround (b1, b0, kp);
+		f_nround (b0, b1, kp);
+	}
+
+	f_nround (b1, b0, kp);
+	f_nround (b0, b1, kp);
+	f_nround (b1, b0, kp);
+	f_nround (b0, b1, kp);
+	f_nround (b1, b0, kp);
+	f_nround (b0, b1, kp);
+	f_nround (b1, b0, kp);
+	f_nround (b0, b1, kp);
+	f_nround (b1, b0, kp);
+	f_lround (b0, b1, kp);
+
+	u32_out (out, b0[0]);
+	u32_out (out + 4, b0[1]);
+	u32_out (out + 8, b0[2]);
+	u32_out (out + 12, b0[3]);
+}
+
+/* decrypt a block of text */
+
+#define i_nround(bo, bi, k) \
+    i_rn(bo, bi, 0, k);     \
+    i_rn(bo, bi, 1, k);     \
+    i_rn(bo, bi, 2, k);     \
+    i_rn(bo, bi, 3, k);     \
+    k -= 4
+
+#define i_lround(bo, bi, k) \
+    i_rl(bo, bi, 0, k);     \
+    i_rl(bo, bi, 1, k);     \
+    i_rl(bo, bi, 2, k);     \
+    i_rl(bo, bi, 3, k)
+
+static void aes_decrypt(void *ctx_arg, u8 *out, const u8 *in)
+{
+	const struct aes_ctx *ctx = ctx_arg;
+	u32 b0[4], b1[4];
+	const int key_len = ctx->key_length;
+	const u32 *kp = D_KEY + key_len + 20;
+
+	b0[0] = u32_in (in) ^ E_KEY[key_len + 24];
+	b0[1] = u32_in (in + 4) ^ E_KEY[key_len + 25];
+	b0[2] = u32_in (in + 8) ^ E_KEY[key_len + 26];
+	b0[3] = u32_in (in + 12) ^ E_KEY[key_len + 27];
+
+	if (key_len > 24) {
+		i_nround (b1, b0, kp);
+		i_nround (b0, b1, kp);
+	}
+
+	if (key_len > 16) {
+		i_nround (b1, b0, kp);
+		i_nround (b0, b1, kp);
+	}
+
+	i_nround (b1, b0, kp);
+	i_nround (b0, b1, kp);
+	i_nround (b1, b0, kp);
+	i_nround (b0, b1, kp);
+	i_nround (b1, b0, kp);
+	i_nround (b0, b1, kp);
+	i_nround (b1, b0, kp);
+	i_nround (b0, b1, kp);
+	i_nround (b1, b0, kp);
+	i_lround (b0, b1, kp);
+
+	u32_out (out, b0[0]);
+	u32_out (out + 4, b0[1]);
+	u32_out (out + 8, b0[2]);
+	u32_out (out + 12, b0[3]);
+}
+
+
+static struct crypto_alg aes_alg = {
+	.cra_name		=	"aes",
+	.cra_flags		=	CRYPTO_ALG_TYPE_CIPHER,
+	.cra_blocksize		=	AES_BLOCK_SIZE,
+	.cra_ctxsize		=	sizeof(struct aes_ctx),
+	.cra_module		=	THIS_MODULE,
+	.cra_list		=	LIST_HEAD_INIT(aes_alg.cra_list),
+	.cra_u			=	{
+		.cipher = {
+			.cia_min_keysize	=	AES_MIN_KEY_SIZE,
+			.cia_max_keysize	=	AES_MAX_KEY_SIZE,
+			.cia_setkey	   	= 	aes_set_key,
+			.cia_encrypt	 	=	aes_encrypt,
+			.cia_decrypt	  	=	aes_decrypt
+		}
+	}
+};
+
+static int __init aes_init(void)
+{
+	gen_tabs();
+	return crypto_register_alg(&aes_alg);
+}
+
+static void __exit aes_fini(void)
+{
+	crypto_unregister_alg(&aes_alg);
+}
+
+module_init(aes_init);
+module_exit(aes_fini);
+
+MODULE_DESCRIPTION("Rijndael (AES) Cipher Algorithm");
+MODULE_LICENSE("Dual BSD/GPL");
+
diff --git a/drivers/staging/rtl8192su/ieee80211/api.c b/drivers/staging/rtl8192su/ieee80211/api.c
new file mode 100644
index 0000000..c627d02
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/api.c
@@ -0,0 +1,246 @@
+/*
+ * Scatterlist Cryptographic API.
+ *
+ * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
+ * Copyright (c) 2002 David S. Miller (davem@redhat.com)
+ *
+ * Portions derived from Cryptoapi, by Alexander Kjeldaas <astor@fast.no>
+ * and Nettle, by Niels M鰈ler.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ */
+#include "kmap_types.h"
+
+#include <linux/init.h>
+#include <linux/module.h>
+//#include <linux/crypto.h>
+#include "rtl_crypto.h"
+#include <linux/errno.h>
+#include <linux/rwsem.h>
+#include <linux/slab.h>
+#include "internal.h"
+
+LIST_HEAD(crypto_alg_list);
+DECLARE_RWSEM(crypto_alg_sem);
+
+static inline int crypto_alg_get(struct crypto_alg *alg)
+{
+	return try_inc_mod_count(alg->cra_module);
+}
+
+static inline void crypto_alg_put(struct crypto_alg *alg)
+{
+	if (alg->cra_module)
+		__MOD_DEC_USE_COUNT(alg->cra_module);
+}
+
+struct crypto_alg *crypto_alg_lookup(const char *name)
+{
+	struct crypto_alg *q, *alg = NULL;
+
+	if (!name)
+		return NULL;
+
+	down_read(&crypto_alg_sem);
+
+	list_for_each_entry(q, &crypto_alg_list, cra_list) {
+		if (!(strcmp(q->cra_name, name))) {
+			if (crypto_alg_get(q))
+				alg = q;
+			break;
+		}
+	}
+
+	up_read(&crypto_alg_sem);
+	return alg;
+}
+
+static int crypto_init_flags(struct crypto_tfm *tfm, u32 flags)
+{
+	tfm->crt_flags = 0;
+
+	switch (crypto_tfm_alg_type(tfm)) {
+	case CRYPTO_ALG_TYPE_CIPHER:
+		return crypto_init_cipher_flags(tfm, flags);
+
+	case CRYPTO_ALG_TYPE_DIGEST:
+		return crypto_init_digest_flags(tfm, flags);
+
+	case CRYPTO_ALG_TYPE_COMPRESS:
+		return crypto_init_compress_flags(tfm, flags);
+
+	default:
+		break;
+	}
+
+	BUG();
+	return -EINVAL;
+}
+
+static int crypto_init_ops(struct crypto_tfm *tfm)
+{
+	switch (crypto_tfm_alg_type(tfm)) {
+	case CRYPTO_ALG_TYPE_CIPHER:
+		return crypto_init_cipher_ops(tfm);
+
+	case CRYPTO_ALG_TYPE_DIGEST:
+		return crypto_init_digest_ops(tfm);
+
+	case CRYPTO_ALG_TYPE_COMPRESS:
+		return crypto_init_compress_ops(tfm);
+
+	default:
+		break;
+	}
+
+	BUG();
+	return -EINVAL;
+}
+
+static void crypto_exit_ops(struct crypto_tfm *tfm)
+{
+	switch (crypto_tfm_alg_type(tfm)) {
+	case CRYPTO_ALG_TYPE_CIPHER:
+		crypto_exit_cipher_ops(tfm);
+		break;
+
+	case CRYPTO_ALG_TYPE_DIGEST:
+		crypto_exit_digest_ops(tfm);
+		break;
+
+	case CRYPTO_ALG_TYPE_COMPRESS:
+		crypto_exit_compress_ops(tfm);
+		break;
+
+	default:
+		BUG();
+
+	}
+}
+
+struct crypto_tfm *crypto_alloc_tfm(const char *name, u32 flags)
+{
+	struct crypto_tfm *tfm = NULL;
+	struct crypto_alg *alg;
+
+	alg = crypto_alg_mod_lookup(name);
+	if (alg == NULL)
+		goto out;
+
+	tfm = kmalloc(sizeof(*tfm) + alg->cra_ctxsize, GFP_KERNEL);
+	if (tfm == NULL)
+		goto out_put;
+
+	memset(tfm, 0, sizeof(*tfm) + alg->cra_ctxsize);
+
+	tfm->__crt_alg = alg;
+
+	if (crypto_init_flags(tfm, flags))
+		goto out_free_tfm;
+
+	if (crypto_init_ops(tfm)) {
+		crypto_exit_ops(tfm);
+		goto out_free_tfm;
+	}
+
+	goto out;
+
+out_free_tfm:
+	kfree(tfm);
+	tfm = NULL;
+out_put:
+	crypto_alg_put(alg);
+out:
+	return tfm;
+}
+
+void crypto_free_tfm(struct crypto_tfm *tfm)
+{
+	struct crypto_alg *alg = tfm->__crt_alg;
+	int size = sizeof(*tfm) + alg->cra_ctxsize;
+
+	crypto_exit_ops(tfm);
+	crypto_alg_put(alg);
+	memset(tfm, 0, size);
+	kfree(tfm);
+}
+
+int crypto_register_alg(struct crypto_alg *alg)
+{
+	int ret = 0;
+	struct crypto_alg *q;
+
+	down_write(&crypto_alg_sem);
+
+	list_for_each_entry(q, &crypto_alg_list, cra_list) {
+		if (!(strcmp(q->cra_name, alg->cra_name))) {
+			ret = -EEXIST;
+			goto out;
+		}
+	}
+
+	list_add_tail(&alg->cra_list, &crypto_alg_list);
+out:
+	up_write(&crypto_alg_sem);
+	return ret;
+}
+
+int crypto_unregister_alg(struct crypto_alg *alg)
+{
+	int ret = -ENOENT;
+	struct crypto_alg *q;
+
+	BUG_ON(!alg->cra_module);
+
+	down_write(&crypto_alg_sem);
+	list_for_each_entry(q, &crypto_alg_list, cra_list) {
+		if (alg == q) {
+			list_del(&alg->cra_list);
+			ret = 0;
+			goto out;
+		}
+	}
+out:
+	up_write(&crypto_alg_sem);
+	return ret;
+}
+
+int crypto_alg_available(const char *name, u32 flags)
+{
+	int ret = 0;
+	struct crypto_alg *alg = crypto_alg_mod_lookup(name);
+
+	if (alg) {
+		crypto_alg_put(alg);
+		ret = 1;
+	}
+
+	return ret;
+}
+
+static int __init init_crypto(void)
+{
+	printk(KERN_INFO "Initializing Cryptographic API\n");
+	crypto_init_proc();
+	return 0;
+}
+
+__initcall(init_crypto);
+
+/*
+EXPORT_SYMBOL_GPL(crypto_register_alg);
+EXPORT_SYMBOL_GPL(crypto_unregister_alg);
+EXPORT_SYMBOL_GPL(crypto_alloc_tfm);
+EXPORT_SYMBOL_GPL(crypto_free_tfm);
+EXPORT_SYMBOL_GPL(crypto_alg_available);
+*/
+
+EXPORT_SYMBOL_NOVERS(crypto_register_alg);
+EXPORT_SYMBOL_NOVERS(crypto_unregister_alg);
+EXPORT_SYMBOL_NOVERS(crypto_alloc_tfm);
+EXPORT_SYMBOL_NOVERS(crypto_free_tfm);
+EXPORT_SYMBOL_NOVERS(crypto_alg_available);
diff --git a/drivers/staging/rtl8192su/ieee80211/arc4.c b/drivers/staging/rtl8192su/ieee80211/arc4.c
new file mode 100644
index 0000000..e408472
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/arc4.c
@@ -0,0 +1,103 @@
+/*
+ * Cryptographic API
+ *
+ * ARC4 Cipher Algorithm
+ *
+ * Jon Oberheide <jon@oberheide.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ */
+#include <linux/module.h>
+#include <linux/init.h>
+#include "rtl_crypto.h"
+
+#define ARC4_MIN_KEY_SIZE	1
+#define ARC4_MAX_KEY_SIZE	256
+#define ARC4_BLOCK_SIZE		1
+
+struct arc4_ctx {
+	u8 S[256];
+	u8 x, y;
+};
+
+static int arc4_set_key(void *ctx_arg, const u8 *in_key, unsigned int key_len, u32 *flags)
+{
+	struct arc4_ctx *ctx = ctx_arg;
+	int i, j = 0, k = 0;
+
+	ctx->x = 1;
+	ctx->y = 0;
+
+	for(i = 0; i < 256; i++)
+		ctx->S[i] = i;
+
+	for(i = 0; i < 256; i++)
+	{
+		u8 a = ctx->S[i];
+		j = (j + in_key[k] + a) & 0xff;
+		ctx->S[i] = ctx->S[j];
+		ctx->S[j] = a;
+		if((unsigned int)++k >= key_len)
+			k = 0;
+	}
+
+	return 0;
+}
+
+static void arc4_crypt(void *ctx_arg, u8 *out, const u8 *in)
+{
+	struct arc4_ctx *ctx = ctx_arg;
+
+	u8 *const S = ctx->S;
+	u8 x = ctx->x;
+	u8 y = ctx->y;
+	u8 a, b;
+
+	a = S[x];
+	y = (y + a) & 0xff;
+	b = S[y];
+	S[x] = b;
+	S[y] = a;
+	x = (x + 1) & 0xff;
+	*out++ = *in ^ S[(a + b) & 0xff];
+
+	ctx->x = x;
+	ctx->y = y;
+}
+
+static struct crypto_alg arc4_alg = {
+	.cra_name		=	"arc4",
+	.cra_flags		=	CRYPTO_ALG_TYPE_CIPHER,
+	.cra_blocksize		=	ARC4_BLOCK_SIZE,
+	.cra_ctxsize		=	sizeof(struct arc4_ctx),
+	.cra_module		=	THIS_MODULE,
+	.cra_list		=	LIST_HEAD_INIT(arc4_alg.cra_list),
+	.cra_u			=	{ .cipher = {
+	.cia_min_keysize	=	ARC4_MIN_KEY_SIZE,
+	.cia_max_keysize	=	ARC4_MAX_KEY_SIZE,
+	.cia_setkey	   	= 	arc4_set_key,
+	.cia_encrypt	 	=	arc4_crypt,
+	.cia_decrypt	  	=	arc4_crypt } }
+};
+
+static int __init arc4_init(void)
+{
+	return crypto_register_alg(&arc4_alg);
+}
+
+
+static void __exit arc4_exit(void)
+{
+	crypto_unregister_alg(&arc4_alg);
+}
+
+module_init(arc4_init);
+module_exit(arc4_exit);
+
+MODULE_LICENSE("GPL");
+MODULE_DESCRIPTION("ARC4 Cipher Algorithm");
+MODULE_AUTHOR("Jon Oberheide <jon@oberheide.org>");
diff --git a/drivers/staging/rtl8192su/ieee80211/autoload.c b/drivers/staging/rtl8192su/ieee80211/autoload.c
new file mode 100644
index 0000000..c97756f
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/autoload.c
@@ -0,0 +1,40 @@
+/*
+ * Cryptographic API.
+ *
+ * Algorithm autoloader.
+ *
+ * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ */
+#include "kmap_types.h"
+
+#include <linux/kernel.h>
+//#include <linux/crypto.h>
+#include "rtl_crypto.h"
+#include <linux/string.h>
+#include <linux/kmod.h>
+#include "internal.h"
+
+/*
+ * A far more intelligent version of this is planned.  For now, just
+ * try an exact match on the name of the algorithm.
+ */
+void crypto_alg_autoload(const char *name)
+{
+	request_module(name);
+}
+
+struct crypto_alg *crypto_alg_mod_lookup(const char *name)
+{
+	struct crypto_alg *alg = crypto_alg_lookup(name);
+	if (alg == NULL) {
+		crypto_alg_autoload(name);
+		alg = crypto_alg_lookup(name);
+	}
+	return alg;
+}
diff --git a/drivers/staging/rtl8192su/ieee80211/cipher.c b/drivers/staging/rtl8192su/ieee80211/cipher.c
new file mode 100644
index 0000000..1968acf
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/cipher.c
@@ -0,0 +1,299 @@
+/*
+ * Cryptographic API.
+ *
+ * Cipher operations.
+ *
+ * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ */
+#include <linux/kernel.h>
+//#include <linux/crypto.h>
+#include "rtl_crypto.h"
+#include <linux/errno.h>
+#include <linux/mm.h>
+#include <linux/slab.h>
+#include <asm/scatterlist.h>
+#include "internal.h"
+#include "scatterwalk.h"
+
+typedef void (cryptfn_t)(void *, u8 *, const u8 *);
+typedef void (procfn_t)(struct crypto_tfm *, u8 *,
+                        u8*, cryptfn_t, int enc, void *, int);
+
+static inline void xor_64(u8 *a, const u8 *b)
+{
+	((u32 *)a)[0] ^= ((u32 *)b)[0];
+	((u32 *)a)[1] ^= ((u32 *)b)[1];
+}
+
+static inline void xor_128(u8 *a, const u8 *b)
+{
+	((u32 *)a)[0] ^= ((u32 *)b)[0];
+	((u32 *)a)[1] ^= ((u32 *)b)[1];
+	((u32 *)a)[2] ^= ((u32 *)b)[2];
+	((u32 *)a)[3] ^= ((u32 *)b)[3];
+}
+
+
+/*
+ * Generic encrypt/decrypt wrapper for ciphers, handles operations across
+ * multiple page boundaries by using temporary blocks.  In user context,
+ * the kernel is given a chance to schedule us once per block.
+ */
+static int crypt(struct crypto_tfm *tfm,
+		 struct scatterlist *dst,
+		 struct scatterlist *src,
+                 unsigned int nbytes, cryptfn_t crfn,
+                 procfn_t prfn, int enc, void *info)
+{
+	struct scatter_walk walk_in, walk_out;
+	const unsigned int bsize = crypto_tfm_alg_blocksize(tfm);
+	u8 tmp_src[bsize];
+	u8 tmp_dst[bsize];
+
+	if (!nbytes)
+		return 0;
+
+	if (nbytes % bsize) {
+		tfm->crt_flags |= CRYPTO_TFM_RES_BAD_BLOCK_LEN;
+		return -EINVAL;
+	}
+
+	scatterwalk_start(&walk_in, src);
+	scatterwalk_start(&walk_out, dst);
+
+	for(;;) {
+		u8 *src_p, *dst_p;
+		int in_place;
+
+		scatterwalk_map(&walk_in, 0);
+		scatterwalk_map(&walk_out, 1);
+		src_p = scatterwalk_whichbuf(&walk_in, bsize, tmp_src);
+		dst_p = scatterwalk_whichbuf(&walk_out, bsize, tmp_dst);
+		in_place = scatterwalk_samebuf(&walk_in, &walk_out,
+					       src_p, dst_p);
+
+		nbytes -= bsize;
+
+		scatterwalk_copychunks(src_p, &walk_in, bsize, 0);
+
+		prfn(tfm, dst_p, src_p, crfn, enc, info, in_place);
+
+		scatterwalk_done(&walk_in, 0, nbytes);
+
+		scatterwalk_copychunks(dst_p, &walk_out, bsize, 1);
+		scatterwalk_done(&walk_out, 1, nbytes);
+
+		if (!nbytes)
+			return 0;
+
+		crypto_yield(tfm);
+	}
+}
+
+static void cbc_process(struct crypto_tfm *tfm, u8 *dst, u8 *src,
+			cryptfn_t fn, int enc, void *info, int in_place)
+{
+	u8 *iv = info;
+
+	/* Null encryption */
+	if (!iv)
+		return;
+
+	if (enc) {
+		tfm->crt_u.cipher.cit_xor_block(iv, src);
+		fn(crypto_tfm_ctx(tfm), dst, iv);
+		memcpy(iv, dst, crypto_tfm_alg_blocksize(tfm));
+	} else {
+		u8 stack[in_place ? crypto_tfm_alg_blocksize(tfm) : 0];
+		u8 *buf = in_place ? stack : dst;
+
+		fn(crypto_tfm_ctx(tfm), buf, src);
+		tfm->crt_u.cipher.cit_xor_block(buf, iv);
+		memcpy(iv, src, crypto_tfm_alg_blocksize(tfm));
+		if (buf != dst)
+			memcpy(dst, buf, crypto_tfm_alg_blocksize(tfm));
+	}
+}
+
+static void ecb_process(struct crypto_tfm *tfm, u8 *dst, u8 *src,
+			cryptfn_t fn, int enc, void *info, int in_place)
+{
+	fn(crypto_tfm_ctx(tfm), dst, src);
+}
+
+static int setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen)
+{
+	struct cipher_alg *cia = &tfm->__crt_alg->cra_cipher;
+
+	if (keylen < cia->cia_min_keysize || keylen > cia->cia_max_keysize) {
+		tfm->crt_flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
+		return -EINVAL;
+	} else
+		return cia->cia_setkey(crypto_tfm_ctx(tfm), key, keylen,
+		                       &tfm->crt_flags);
+}
+
+static int ecb_encrypt(struct crypto_tfm *tfm,
+		       struct scatterlist *dst,
+                       struct scatterlist *src, unsigned int nbytes)
+{
+	return crypt(tfm, dst, src, nbytes,
+	             tfm->__crt_alg->cra_cipher.cia_encrypt,
+	             ecb_process, 1, NULL);
+}
+
+static int ecb_decrypt(struct crypto_tfm *tfm,
+                       struct scatterlist *dst,
+                       struct scatterlist *src,
+		       unsigned int nbytes)
+{
+	return crypt(tfm, dst, src, nbytes,
+	             tfm->__crt_alg->cra_cipher.cia_decrypt,
+	             ecb_process, 1, NULL);
+}
+
+static int cbc_encrypt(struct crypto_tfm *tfm,
+                       struct scatterlist *dst,
+                       struct scatterlist *src,
+		       unsigned int nbytes)
+{
+	return crypt(tfm, dst, src, nbytes,
+	             tfm->__crt_alg->cra_cipher.cia_encrypt,
+	             cbc_process, 1, tfm->crt_cipher.cit_iv);
+}
+
+static int cbc_encrypt_iv(struct crypto_tfm *tfm,
+                          struct scatterlist *dst,
+                          struct scatterlist *src,
+                          unsigned int nbytes, u8 *iv)
+{
+	return crypt(tfm, dst, src, nbytes,
+	             tfm->__crt_alg->cra_cipher.cia_encrypt,
+	             cbc_process, 1, iv);
+}
+
+static int cbc_decrypt(struct crypto_tfm *tfm,
+                       struct scatterlist *dst,
+                       struct scatterlist *src,
+		       unsigned int nbytes)
+{
+	return crypt(tfm, dst, src, nbytes,
+	             tfm->__crt_alg->cra_cipher.cia_decrypt,
+	             cbc_process, 0, tfm->crt_cipher.cit_iv);
+}
+
+static int cbc_decrypt_iv(struct crypto_tfm *tfm,
+                          struct scatterlist *dst,
+                          struct scatterlist *src,
+                          unsigned int nbytes, u8 *iv)
+{
+	return crypt(tfm, dst, src, nbytes,
+	             tfm->__crt_alg->cra_cipher.cia_decrypt,
+	             cbc_process, 0, iv);
+}
+
+static int nocrypt(struct crypto_tfm *tfm,
+                   struct scatterlist *dst,
+                   struct scatterlist *src,
+		   unsigned int nbytes)
+{
+	return -ENOSYS;
+}
+
+static int nocrypt_iv(struct crypto_tfm *tfm,
+                      struct scatterlist *dst,
+                      struct scatterlist *src,
+                      unsigned int nbytes, u8 *iv)
+{
+	return -ENOSYS;
+}
+
+int crypto_init_cipher_flags(struct crypto_tfm *tfm, u32 flags)
+{
+	u32 mode = flags & CRYPTO_TFM_MODE_MASK;
+
+	tfm->crt_cipher.cit_mode = mode ? mode : CRYPTO_TFM_MODE_ECB;
+	if (flags & CRYPTO_TFM_REQ_WEAK_KEY)
+		tfm->crt_flags = CRYPTO_TFM_REQ_WEAK_KEY;
+
+	return 0;
+}
+
+int crypto_init_cipher_ops(struct crypto_tfm *tfm)
+{
+	int ret = 0;
+	struct cipher_tfm *ops = &tfm->crt_cipher;
+
+	ops->cit_setkey = setkey;
+
+	switch (tfm->crt_cipher.cit_mode) {
+	case CRYPTO_TFM_MODE_ECB:
+		ops->cit_encrypt = ecb_encrypt;
+		ops->cit_decrypt = ecb_decrypt;
+		break;
+
+	case CRYPTO_TFM_MODE_CBC:
+		ops->cit_encrypt = cbc_encrypt;
+		ops->cit_decrypt = cbc_decrypt;
+		ops->cit_encrypt_iv = cbc_encrypt_iv;
+		ops->cit_decrypt_iv = cbc_decrypt_iv;
+		break;
+
+	case CRYPTO_TFM_MODE_CFB:
+		ops->cit_encrypt = nocrypt;
+		ops->cit_decrypt = nocrypt;
+		ops->cit_encrypt_iv = nocrypt_iv;
+		ops->cit_decrypt_iv = nocrypt_iv;
+		break;
+
+	case CRYPTO_TFM_MODE_CTR:
+		ops->cit_encrypt = nocrypt;
+		ops->cit_decrypt = nocrypt;
+		ops->cit_encrypt_iv = nocrypt_iv;
+		ops->cit_decrypt_iv = nocrypt_iv;
+		break;
+
+	default:
+		BUG();
+	}
+
+	if (ops->cit_mode == CRYPTO_TFM_MODE_CBC) {
+
+	    	switch (crypto_tfm_alg_blocksize(tfm)) {
+	    	case 8:
+	    		ops->cit_xor_block = xor_64;
+	    		break;
+
+	    	case 16:
+	    		ops->cit_xor_block = xor_128;
+	    		break;
+
+	    	default:
+	    		printk(KERN_WARNING "%s: block size %u not supported\n",
+	    		       crypto_tfm_alg_name(tfm),
+	    		       crypto_tfm_alg_blocksize(tfm));
+	    		ret = -EINVAL;
+	    		goto out;
+	    	}
+
+		ops->cit_ivsize = crypto_tfm_alg_blocksize(tfm);
+	    	ops->cit_iv = kmalloc(ops->cit_ivsize, GFP_KERNEL);
+		if (ops->cit_iv == NULL)
+			ret = -ENOMEM;
+	}
+
+out:
+	return ret;
+}
+
+void crypto_exit_cipher_ops(struct crypto_tfm *tfm)
+{
+	if (tfm->crt_cipher.cit_iv)
+		kfree(tfm->crt_cipher.cit_iv);
+}
diff --git a/drivers/staging/rtl8192su/ieee80211/compress.c b/drivers/staging/rtl8192su/ieee80211/compress.c
new file mode 100644
index 0000000..c2df80e
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/compress.c
@@ -0,0 +1,64 @@
+/*
+ * Cryptographic API.
+ *
+ * Compression operations.
+ *
+ * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ */
+#include <linux/types.h>
+//#include <linux/crypto.h>
+#include "rtl_crypto.h"
+#include <linux/errno.h>
+#include <asm/scatterlist.h>
+#include <linux/string.h>
+#include "internal.h"
+
+static int crypto_compress(struct crypto_tfm *tfm,
+                            const u8 *src, unsigned int slen,
+                            u8 *dst, unsigned int *dlen)
+{
+	return tfm->__crt_alg->cra_compress.coa_compress(crypto_tfm_ctx(tfm),
+	                                                 src, slen, dst,
+	                                                 dlen);
+}
+
+static int crypto_decompress(struct crypto_tfm *tfm,
+                             const u8 *src, unsigned int slen,
+                             u8 *dst, unsigned int *dlen)
+{
+	return tfm->__crt_alg->cra_compress.coa_decompress(crypto_tfm_ctx(tfm),
+	                                                   src, slen, dst,
+	                                                   dlen);
+}
+
+int crypto_init_compress_flags(struct crypto_tfm *tfm, u32 flags)
+{
+	return flags ? -EINVAL : 0;
+}
+
+int crypto_init_compress_ops(struct crypto_tfm *tfm)
+{
+	int ret = 0;
+	struct compress_tfm *ops = &tfm->crt_compress;
+
+	ret = tfm->__crt_alg->cra_compress.coa_init(crypto_tfm_ctx(tfm));
+	if (ret)
+		goto out;
+
+	ops->cot_compress = crypto_compress;
+	ops->cot_decompress = crypto_decompress;
+
+out:
+	return ret;
+}
+
+void crypto_exit_compress_ops(struct crypto_tfm *tfm)
+{
+	tfm->__crt_alg->cra_compress.coa_exit(crypto_tfm_ctx(tfm));
+}
diff --git a/drivers/staging/rtl8192su/ieee80211/crypto_compat.h b/drivers/staging/rtl8192su/ieee80211/crypto_compat.h
new file mode 100644
index 0000000..587e8bb
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/crypto_compat.h
@@ -0,0 +1,90 @@
+/*
+ * Header file to maintain compatibility among different kernel versions.
+ *
+ * Copyright (c) 2004-2006  <lawrence_wang@realsil.com.cn>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. See README and COPYING for
+ * more details.
+ */
+
+#include <linux/crypto.h>
+
+static inline int crypto_cipher_encrypt(struct crypto_tfm *tfm,
+                                        struct scatterlist *dst,
+                                        struct scatterlist *src,
+                                        unsigned int nbytes)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	return tfm->crt_cipher.cit_encrypt(tfm, dst, src, nbytes);
+}
+
+
+static inline int crypto_cipher_decrypt(struct crypto_tfm *tfm,
+                                        struct scatterlist *dst,
+                                        struct scatterlist *src,
+                                        unsigned int nbytes)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	return tfm->crt_cipher.cit_decrypt(tfm, dst, src, nbytes);
+}
+
+#if 0
+/*
+ *	crypto_free_tfm - Free crypto transform
+ *	@tfm: Transform to free
+ *
+ *	crypto_free_tfm() frees up the transform and any associated resources,
+ *	then drops the refcount on the associated algorithm.
+ */
+void crypto_free_tfm(struct crypto_tfm *tfm)
+{
+	struct crypto_alg *alg;
+	int size;
+
+	if (unlikely(!tfm))
+		return;
+
+	alg = tfm->__crt_alg;
+	size = sizeof(*tfm) + alg->cra_ctxsize;
+
+	if (alg->cra_exit)
+		alg->cra_exit(tfm);
+	crypto_exit_ops(tfm);
+	crypto_mod_put(alg);
+	memset(tfm, 0, size);
+	kfree(tfm);
+}
+
+#endif
+#if 1
+ struct crypto_tfm *crypto_alloc_tfm(const char *name, u32 flags)
+{
+	struct crypto_tfm *tfm = NULL;
+	int err;
+	printk("call crypto_alloc_tfm!!!\n");
+	do {
+		struct crypto_alg *alg;
+
+		alg = crypto_alg_mod_lookup(name, 0, CRYPTO_ALG_ASYNC);
+		err = PTR_ERR(alg);
+		if (IS_ERR(alg))
+			continue;
+
+		tfm = __crypto_alloc_tfm(alg, flags);
+		err = 0;
+		if (IS_ERR(tfm)) {
+			crypto_mod_put(alg);
+			err = PTR_ERR(tfm);
+			tfm = NULL;
+		}
+	} while (err == -EAGAIN && !signal_pending(current));
+
+	return tfm;
+}
+#endif
+//EXPORT_SYMBOL_GPL(crypto_alloc_tfm);
+//EXPORT_SYMBOL_GPL(crypto_free_tfm);
+
+
diff --git a/drivers/staging/rtl8192su/ieee80211/digest.c b/drivers/staging/rtl8192su/ieee80211/digest.c
new file mode 100644
index 0000000..1a95f2d
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/digest.c
@@ -0,0 +1,108 @@
+/*
+ * Cryptographic API.
+ *
+ * Digest operations.
+ *
+ * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ */
+//#include <linux/crypto.h>
+#include "rtl_crypto.h"
+#include <linux/mm.h>
+#include <linux/errno.h>
+#include <linux/highmem.h>
+#include <asm/scatterlist.h>
+#include "internal.h"
+
+static void init(struct crypto_tfm *tfm)
+{
+	tfm->__crt_alg->cra_digest.dia_init(crypto_tfm_ctx(tfm));
+}
+
+static void update(struct crypto_tfm *tfm,
+                   struct scatterlist *sg, unsigned int nsg)
+{
+	unsigned int i;
+
+	for (i = 0; i < nsg; i++) {
+
+		struct page *pg = sg[i].page;
+		unsigned int offset = sg[i].offset;
+		unsigned int l = sg[i].length;
+
+		do {
+			unsigned int bytes_from_page = min(l, ((unsigned int)
+							   (PAGE_SIZE)) -
+							   offset);
+			char *p = crypto_kmap(pg, 0) + offset;
+
+			tfm->__crt_alg->cra_digest.dia_update
+					(crypto_tfm_ctx(tfm), p,
+					 bytes_from_page);
+			crypto_kunmap(p, 0);
+			crypto_yield(tfm);
+			offset = 0;
+			pg++;
+			l -= bytes_from_page;
+		} while (l > 0);
+	}
+}
+
+static void final(struct crypto_tfm *tfm, u8 *out)
+{
+	tfm->__crt_alg->cra_digest.dia_final(crypto_tfm_ctx(tfm), out);
+}
+
+static int setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen)
+{
+	u32 flags;
+	if (tfm->__crt_alg->cra_digest.dia_setkey == NULL)
+		return -ENOSYS;
+	return tfm->__crt_alg->cra_digest.dia_setkey(crypto_tfm_ctx(tfm),
+						     key, keylen, &flags);
+}
+
+static void digest(struct crypto_tfm *tfm,
+                   struct scatterlist *sg, unsigned int nsg, u8 *out)
+{
+	unsigned int i;
+
+	tfm->crt_digest.dit_init(tfm);
+
+	for (i = 0; i < nsg; i++) {
+		char *p = crypto_kmap(sg[i].page, 0) + sg[i].offset;
+		tfm->__crt_alg->cra_digest.dia_update(crypto_tfm_ctx(tfm),
+		                                      p, sg[i].length);
+		crypto_kunmap(p, 0);
+		crypto_yield(tfm);
+	}
+	crypto_digest_final(tfm, out);
+}
+
+int crypto_init_digest_flags(struct crypto_tfm *tfm, u32 flags)
+{
+	return flags ? -EINVAL : 0;
+}
+
+int crypto_init_digest_ops(struct crypto_tfm *tfm)
+{
+	struct digest_tfm *ops = &tfm->crt_digest;
+
+	ops->dit_init	= init;
+	ops->dit_update	= update;
+	ops->dit_final	= final;
+	ops->dit_digest	= digest;
+	ops->dit_setkey	= setkey;
+
+	return crypto_alloc_hmac_block(tfm);
+}
+
+void crypto_exit_digest_ops(struct crypto_tfm *tfm)
+{
+	crypto_free_hmac_block(tfm);
+}
diff --git a/drivers/staging/rtl8192su/ieee80211/dot11d.c b/drivers/staging/rtl8192su/ieee80211/dot11d.c
new file mode 100644
index 0000000..e5f2ded
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/dot11d.c
@@ -0,0 +1,239 @@
+#ifdef ENABLE_DOT11D
+//-----------------------------------------------------------------------------
+//	File:
+//		Dot11d.c
+//
+//	Description:
+//		Implement 802.11d.
+//
+//-----------------------------------------------------------------------------
+
+#include "dot11d.h"
+
+void
+Dot11d_Init(struct ieee80211_device *ieee)
+{
+	PRT_DOT11D_INFO pDot11dInfo = GET_DOT11D_INFO(ieee);
+
+	pDot11dInfo->bEnabled = 0;
+
+	pDot11dInfo->State = DOT11D_STATE_NONE;
+	pDot11dInfo->CountryIeLen = 0;
+	memset(pDot11dInfo->channel_map, 0, MAX_CHANNEL_NUMBER+1);
+	memset(pDot11dInfo->MaxTxPwrDbmList, 0xFF, MAX_CHANNEL_NUMBER+1);
+	RESET_CIE_WATCHDOG(ieee);
+
+	printk("Dot11d_Init()\n");
+}
+
+//
+//	Description:
+//		Reset to the state as we are just entering a regulatory domain.
+//
+void
+Dot11d_Reset(struct ieee80211_device *ieee)
+{
+	u32 i;
+	PRT_DOT11D_INFO pDot11dInfo = GET_DOT11D_INFO(ieee);
+#if 0
+	if(!pDot11dInfo->bEnabled)
+		return;
+#endif
+	// Clear old channel map
+	memset(pDot11dInfo->channel_map, 0, MAX_CHANNEL_NUMBER+1);
+	memset(pDot11dInfo->MaxTxPwrDbmList, 0xFF, MAX_CHANNEL_NUMBER+1);
+	// Set new channel map
+	for (i=1; i<=11; i++) {
+		(pDot11dInfo->channel_map)[i] = 1;
+	}
+	for (i=12; i<=14; i++) {
+		(pDot11dInfo->channel_map)[i] = 2;
+	}
+
+	pDot11dInfo->State = DOT11D_STATE_NONE;
+	pDot11dInfo->CountryIeLen = 0;
+	RESET_CIE_WATCHDOG(ieee);
+
+	//printk("Dot11d_Reset()\n");
+}
+
+//
+//	Description:
+//		Update country IE from Beacon or Probe Resopnse
+//		and configure PHY for operation in the regulatory domain.
+//
+//	TODO:
+//		Configure Tx power.
+//
+//	Assumption:
+//		1. IS_DOT11D_ENABLE() is TRUE.
+//		2. Input IE is an valid one.
+//
+void
+Dot11d_UpdateCountryIe(
+	struct ieee80211_device *dev,
+	u8 *		pTaddr,
+	u16	CoutryIeLen,
+	u8 * pCoutryIe
+	)
+{
+	PRT_DOT11D_INFO pDot11dInfo = GET_DOT11D_INFO(dev);
+	u8 i, j, NumTriples, MaxChnlNum;
+	PCHNL_TXPOWER_TRIPLE pTriple;
+
+	memset(pDot11dInfo->channel_map, 0, MAX_CHANNEL_NUMBER+1);
+	memset(pDot11dInfo->MaxTxPwrDbmList, 0xFF, MAX_CHANNEL_NUMBER+1);
+	MaxChnlNum = 0;
+	NumTriples = (CoutryIeLen - 3) / 3; // skip 3-byte country string.
+	pTriple = (PCHNL_TXPOWER_TRIPLE)(pCoutryIe + 3);
+	for(i = 0; i < NumTriples; i++)
+	{
+		if(MaxChnlNum >= pTriple->FirstChnl)
+		{ // It is not in a monotonically increasing order, so stop processing.
+			printk("Dot11d_UpdateCountryIe(): Invalid country IE, skip it........1\n");
+			return;
+		}
+		if(MAX_CHANNEL_NUMBER < (pTriple->FirstChnl + pTriple->NumChnls))
+		{ // It is not a valid set of channel id, so stop processing.
+			printk("Dot11d_UpdateCountryIe(): Invalid country IE, skip it........2\n");
+			return;
+		}
+
+		for(j = 0 ; j < pTriple->NumChnls; j++)
+		{
+			pDot11dInfo->channel_map[pTriple->FirstChnl + j] = 1;
+			pDot11dInfo->MaxTxPwrDbmList[pTriple->FirstChnl + j] = pTriple->MaxTxPowerInDbm;
+			MaxChnlNum = pTriple->FirstChnl + j;
+		}
+
+		pTriple = (PCHNL_TXPOWER_TRIPLE)((u8*)pTriple + 3);
+	}
+#if 1
+	//printk("Dot11d_UpdateCountryIe(): Channel List:\n");
+	printk("Channel List:");
+	for(i=1; i<= MAX_CHANNEL_NUMBER; i++)
+		if(pDot11dInfo->channel_map[i] > 0)
+			printk(" %d", i);
+	printk("\n");
+#endif
+
+	UPDATE_CIE_SRC(dev, pTaddr);
+
+	pDot11dInfo->CountryIeLen = CoutryIeLen;
+	memcpy(pDot11dInfo->CountryIeBuf, pCoutryIe,CoutryIeLen);
+	pDot11dInfo->State = DOT11D_STATE_LEARNED;
+}
+
+
+u8
+DOT11D_GetMaxTxPwrInDbm(
+	struct ieee80211_device *dev,
+	u8 Channel
+	)
+{
+	PRT_DOT11D_INFO pDot11dInfo = GET_DOT11D_INFO(dev);
+	u8 MaxTxPwrInDbm = 255;
+
+	if(MAX_CHANNEL_NUMBER < Channel)
+	{
+		printk("DOT11D_GetMaxTxPwrInDbm(): Invalid Channel\n");
+		return MaxTxPwrInDbm;
+	}
+	if(pDot11dInfo->channel_map[Channel])
+	{
+		MaxTxPwrInDbm = pDot11dInfo->MaxTxPwrDbmList[Channel];
+	}
+
+	return MaxTxPwrInDbm;
+}
+
+
+void
+DOT11D_ScanComplete(
+	struct ieee80211_device * dev
+	)
+{
+	PRT_DOT11D_INFO pDot11dInfo = GET_DOT11D_INFO(dev);
+
+	switch(pDot11dInfo->State)
+	{
+	case DOT11D_STATE_LEARNED:
+		pDot11dInfo->State = DOT11D_STATE_DONE;
+		break;
+
+	case DOT11D_STATE_DONE:
+		if( GET_CIE_WATCHDOG(dev) == 0 )
+		{ // Reset country IE if previous one is gone.
+			Dot11d_Reset(dev);
+		}
+		break;
+	case DOT11D_STATE_NONE:
+		break;
+	}
+}
+
+int IsLegalChannel(
+	struct ieee80211_device * dev,
+	u8 channel
+)
+{
+	PRT_DOT11D_INFO pDot11dInfo = GET_DOT11D_INFO(dev);
+
+	if(MAX_CHANNEL_NUMBER < channel)
+	{
+		printk("IsLegalChannel(): Invalid Channel\n");
+		return 0;
+	}
+	if(pDot11dInfo->channel_map[channel] > 0)
+		return 1;
+	return 0;
+}
+
+int ToLegalChannel(
+	struct ieee80211_device * dev,
+	u8 channel
+)
+{
+	PRT_DOT11D_INFO pDot11dInfo = GET_DOT11D_INFO(dev);
+	u8 default_chn = 0;
+	u32 i = 0;
+
+	for (i=1; i<= MAX_CHANNEL_NUMBER; i++)
+	{
+		if(pDot11dInfo->channel_map[i] > 0)
+		{
+			default_chn = i;
+			break;
+		}
+	}
+
+	if(MAX_CHANNEL_NUMBER < channel)
+	{
+		printk("IsLegalChannel(): Invalid Channel\n");
+		return default_chn;
+	}
+
+	if(pDot11dInfo->channel_map[channel] > 0)
+		return channel;
+
+	return default_chn;
+}
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+EXPORT_SYMBOL(Dot11d_Init);
+EXPORT_SYMBOL(Dot11d_Reset);
+EXPORT_SYMBOL(Dot11d_UpdateCountryIe);
+EXPORT_SYMBOL(DOT11D_GetMaxTxPwrInDbm);
+EXPORT_SYMBOL(DOT11D_ScanComplete);
+EXPORT_SYMBOL(IsLegalChannel);
+EXPORT_SYMBOL(ToLegalChannel);
+#else
+EXPORT_SYMBOL_NOVERS(Dot11d_Init);
+EXPORT_SYMBOL_NOVERS(Dot11d_Reset);
+EXPORT_SYMBOL_NOVERS(Dot11d_UpdateCountryIe);
+EXPORT_SYMBOL_NOVERS(DOT11D_GetMaxTxPwrInDbm);
+EXPORT_SYMBOL_NOVERS(DOT11D_ScanComplete);
+EXPORT_SYMBOL_NOVERS(IsLegalChannel);
+EXPORT_SYMBOL_NOVERS(ToLegalChannel);
+#endif
+
+#endif
diff --git a/drivers/staging/rtl8192su/ieee80211/dot11d.h b/drivers/staging/rtl8192su/ieee80211/dot11d.h
new file mode 100644
index 0000000..15b7a4b
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/dot11d.h
@@ -0,0 +1,102 @@
+#ifndef __INC_DOT11D_H
+#define __INC_DOT11D_H
+
+#ifdef ENABLE_DOT11D
+#include "ieee80211.h"
+
+//#define ENABLE_DOT11D
+
+//#define DOT11D_MAX_CHNL_NUM 83
+
+typedef struct _CHNL_TXPOWER_TRIPLE {
+	u8 FirstChnl;
+	u8  NumChnls;
+	u8  MaxTxPowerInDbm;
+}CHNL_TXPOWER_TRIPLE, *PCHNL_TXPOWER_TRIPLE;
+
+typedef enum _DOT11D_STATE {
+	DOT11D_STATE_NONE = 0,
+	DOT11D_STATE_LEARNED,
+	DOT11D_STATE_DONE,
+}DOT11D_STATE;
+
+typedef struct _RT_DOT11D_INFO {
+	//DECLARE_RT_OBJECT(RT_DOT11D_INFO);
+
+	bool bEnabled; // dot11MultiDomainCapabilityEnabled
+
+	u16 CountryIeLen; // > 0 if CountryIeBuf[] contains valid country information element.
+	u8  CountryIeBuf[MAX_IE_LEN];
+	u8  CountryIeSrcAddr[6]; // Source AP of the country IE.
+	u8  CountryIeWatchdog;
+
+	u8  channel_map[MAX_CHANNEL_NUMBER+1];  //!!!Value 0: Invalid, 1: Valid (active scan), 2: Valid (passive scan)
+	//u8  ChnlListLen; // #Bytes valid in ChnlList[].
+	//u8  ChnlList[DOT11D_MAX_CHNL_NUM];
+	u8  MaxTxPwrDbmList[MAX_CHANNEL_NUMBER+1];
+
+	DOT11D_STATE State;
+}RT_DOT11D_INFO, *PRT_DOT11D_INFO;
+#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 )
+#define cpMacAddr(des,src)	      ((des)[0]=(src)[0],(des)[1]=(src)[1],(des)[2]=(src)[2],(des)[3]=(src)[3],(des)[4]=(src)[4],(des)[5]=(src)[5])
+#define GET_DOT11D_INFO(__pIeeeDev) ((PRT_DOT11D_INFO)((__pIeeeDev)->pDot11dInfo))
+
+#define IS_DOT11D_ENABLE(__pIeeeDev) GET_DOT11D_INFO(__pIeeeDev)->bEnabled
+#define IS_COUNTRY_IE_VALID(__pIeeeDev) (GET_DOT11D_INFO(__pIeeeDev)->CountryIeLen > 0)
+
+#define IS_EQUAL_CIE_SRC(__pIeeeDev, __pTa) eqMacAddr(GET_DOT11D_INFO(__pIeeeDev)->CountryIeSrcAddr, __pTa)
+#define UPDATE_CIE_SRC(__pIeeeDev, __pTa) cpMacAddr(GET_DOT11D_INFO(__pIeeeDev)->CountryIeSrcAddr, __pTa)
+
+#define IS_COUNTRY_IE_CHANGED(__pIeeeDev, __Ie) \
+	(((__Ie).Length == 0 || (__Ie).Length != GET_DOT11D_INFO(__pIeeeDev)->CountryIeLen) ? \
+	FALSE : \
+	(!memcmp(GET_DOT11D_INFO(__pIeeeDev)->CountryIeBuf, (__Ie).Octet, (__Ie).Length)))
+
+#define CIE_WATCHDOG_TH 1
+#define GET_CIE_WATCHDOG(__pIeeeDev) GET_DOT11D_INFO(__pIeeeDev)->CountryIeWatchdog
+#define RESET_CIE_WATCHDOG(__pIeeeDev) GET_CIE_WATCHDOG(__pIeeeDev) = 0
+#define UPDATE_CIE_WATCHDOG(__pIeeeDev) ++GET_CIE_WATCHDOG(__pIeeeDev)
+
+#define IS_DOT11D_STATE_DONE(__pIeeeDev) (GET_DOT11D_INFO(__pIeeeDev)->State == DOT11D_STATE_DONE)
+
+
+void
+Dot11d_Init(
+	struct ieee80211_device *dev
+	);
+
+void
+Dot11d_Reset(
+	struct ieee80211_device *dev
+	);
+
+void
+Dot11d_UpdateCountryIe(
+	struct ieee80211_device *dev,
+	u8 *		pTaddr,
+	u16	CoutryIeLen,
+	u8 * pCoutryIe
+	);
+
+u8
+DOT11D_GetMaxTxPwrInDbm(
+	struct ieee80211_device *dev,
+	u8 Channel
+	);
+
+void
+DOT11D_ScanComplete(
+	struct ieee80211_device * dev
+	);
+
+int IsLegalChannel(
+	struct ieee80211_device * dev,
+	u8 channel
+);
+
+int ToLegalChannel(
+	struct ieee80211_device * dev,
+	u8 channel
+);
+#endif //ENABLE_DOT11D
+#endif // #ifndef __INC_DOT11D_H
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211.h b/drivers/staging/rtl8192su/ieee80211/ieee80211.h
new file mode 100644
index 0000000..720bfcb
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211.h
@@ -0,0 +1,2901 @@
+/*
+ * Merged with mainline ieee80211.h in Aug 2004.  Original ieee802_11
+ * remains copyright by the original authors
+ *
+ * Portions of the merged code are based on Host AP (software wireless
+ * LAN access point) driver for Intersil Prism2/2.5/3.
+ *
+ * Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen
+ * <jkmaline@cc.hut.fi>
+ * Copyright (c) 2002-2003, Jouni Malinen <jkmaline@cc.hut.fi>
+ *
+ * Adaption to a generic IEEE 802.11 stack by James Ketrenos
+ * <jketreno@linux.intel.com>
+ * Copyright (c) 2004, Intel Corporation
+ *
+ * Modified for Realtek's wi-fi cards by Andrea Merello
+ * <andreamrl@tiscali.it>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. See README and COPYING for
+ * more details.
+ */
+#ifndef IEEE80211_H
+#define IEEE80211_H
+#include <linux/if_ether.h> /* ETH_ALEN */
+#include <linux/kernel.h>   /* ARRAY_SIZE */
+#include <linux/version.h>
+#include <linux/module.h>
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+#include <linux/jiffies.h>
+#else
+#include <linux/jffs.h>
+#include <linux/tqueue.h>
+#endif
+#include <linux/timer.h>
+#include <linux/sched.h>
+
+#include <linux/delay.h>
+#include <linux/wireless.h>
+
+#include "rtl819x_HT.h"
+#include "rtl819x_BA.h"
+#include "rtl819x_TS.h"
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20))
+#ifndef bool
+typedef enum{false = 0, true} bool;
+#endif
+#endif
+
+#ifndef IW_MODE_MONITOR
+#define IW_MODE_MONITOR 6
+#endif
+
+#ifndef IWEVCUSTOM
+#define IWEVCUSTOM 0x8c02
+#endif
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+#ifndef __bitwise
+#define __bitwise __attribute__((bitwise))
+#endif
+typedef __u16  __le16;
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,4,27))
+struct iw_spy_data{
+	/* --- Standard spy support --- */
+	int 			spy_number;
+	u_char 			spy_address[IW_MAX_SPY][ETH_ALEN];
+	struct iw_quality	spy_stat[IW_MAX_SPY];
+	/* --- Enhanced spy support (event) */
+	struct iw_quality	spy_thr_low; /* Low threshold */
+	struct iw_quality	spy_thr_high; /* High threshold */
+	u_char			spy_thr_under[IW_MAX_SPY];
+};
+#endif
+#endif
+
+#ifndef container_of
+/**
+ * container_of - cast a member of a structure out to the containing structure
+ *
+ * @ptr:        the pointer to the member.
+ * @type:       the type of the container struct this is embedded in.
+ * @member:     the name of the member within the struct.
+ *
+ */
+#define container_of(ptr, type, member) ({                      \
+        const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
+        (type *)( (char *)__mptr - offsetof(type,member) );})
+#endif
+
+#define KEY_TYPE_NA		0x0
+#define KEY_TYPE_WEP40 		0x1
+#define KEY_TYPE_TKIP		0x2
+#define KEY_TYPE_CCMP		0x4
+#define KEY_TYPE_WEP104		0x5
+
+/* added for rtl819x tx procedure */
+#define MAX_QUEUE_SIZE		0x10
+
+//
+// 8190 queue mapping
+//
+#define BK_QUEUE                               0
+#define BE_QUEUE                               1
+#define VI_QUEUE                               2
+#define VO_QUEUE                               3
+#define HCCA_QUEUE                             4
+#define TXCMD_QUEUE                            5
+#define MGNT_QUEUE                             6
+#define HIGH_QUEUE                             7
+#define BEACON_QUEUE                           8
+
+#define LOW_QUEUE                              BE_QUEUE
+#define NORMAL_QUEUE                           MGNT_QUEUE
+
+//added by amy for ps
+#define SWRF_TIMEOUT				50
+
+//added by amy for LEAP related
+#define IE_CISCO_FLAG_POSITION		0x08	// Flag byte: byte 8, numbered from 0.
+#define SUPPORT_CKIP_MIC			0x08	// bit3
+#define SUPPORT_CKIP_PK			0x10	// bit4
+//added by amy for ps
+// RF Off Level for IPS or HW/SW radio off
+#define	RT_RF_OFF_LEVL_ASPM			BIT0	// PCI ASPM
+#define	RT_RF_OFF_LEVL_CLK_REQ		BIT1	// PCI clock request
+#define	RT_RF_OFF_LEVL_PCI_D3			BIT2	// PCI D3 mode
+#define	RT_RF_OFF_LEVL_HALT_NIC		BIT3	// NIC halt, re-initialize hw parameters
+#define	RT_RF_OFF_LEVL_FREE_FW		BIT4	// FW free, re-download the FW
+#define	RT_RF_OFF_LEVL_FW_32K		BIT5	// FW in 32k
+#define	RT_RF_PS_LEVEL_ALWAYS_ASPM	BIT6	// Always enable ASPM and Clock Req in initialization.
+#define	RT_RF_LPS_DISALBE_2R			BIT30	// When LPS is on, disable 2R if no packet is received or transmittd.
+#define	RT_RF_LPS_LEVEL_ASPM			BIT31	// LPS with ASPM
+#define	RT_IN_PS_LEVEL(pPSC, _PS_FLAG)	((pPSC->CurPsLevel & _PS_FLAG) ? true : false)
+#define	RT_CLEAR_PS_LEVEL(pPSC, _PS_FLAG)	(pPSC->CurPsLevel &= (~(_PS_FLAG)))
+#define	RT_SET_PS_LEVEL(pPSC, _PS_FLAG)	(pPSC->CurPsLevel->CurPsLevel |= _PS_FLAG)
+/* defined for skb cb field */
+/* At most 28 byte */
+typedef struct cb_desc {
+        /* Tx Desc Related flags (8-9) */
+	u8 bLastIniPkt:1;
+	u8 bCmdOrInit:1;
+        u8 bFirstSeg:1;
+        u8 bLastSeg:1;
+        u8 bEncrypt:1;
+        u8 bTxDisableRateFallBack:1;
+        u8 bTxUseDriverAssingedRate:1;
+        u8 bHwSec:1; //indicate whether use Hw security. WB
+
+        u8 reserved1;
+
+        /* Tx Firmware Relaged flags (10-11)*/
+        u8 bCTSEnable:1;
+        u8 bRTSEnable:1;
+        u8 bUseShortGI:1;
+        u8 bUseShortPreamble:1;
+        u8 bTxEnableFwCalcDur:1;
+        u8 bAMPDUEnable:1;
+        u8 bRTSSTBC:1;
+        u8 RTSSC:1;
+
+        u8 bRTSBW:1;
+        u8 bPacketBW:1;
+	u8 bRTSUseShortPreamble:1;
+	u8 bRTSUseShortGI:1;
+	u8 bMulticast:1;
+	u8 bBroadcast:1;
+        //u8 reserved2:2;
+        u8 drv_agg_enable:1;
+        u8 reserved2:1;
+
+        /* Tx Desc related element(12-19) */
+        u8 rata_index;
+        u8 queue_index;
+        //u8 reserved3;
+        //u8 reserved4;
+        u16 txbuf_size;
+        //u8 reserved5;
+	u8 RATRIndex;
+        u8 reserved6;
+        u8 reserved7;
+        u8 reserved8;
+
+        /* Tx firmware related element(20-27) */
+        u8 data_rate;
+        u8 rts_rate;
+        u8 ampdu_factor;
+        u8 ampdu_density;
+        //u8 reserved9;
+        //u8 reserved10;
+        //u8 reserved11;
+        u8 DrvAggrNum;
+	u16 pkt_size;
+        u8 reserved12;
+}cb_desc, *pcb_desc;
+
+/*--------------------------Define -------------------------------------------*/
+#define MGN_1M                  0x02
+#define MGN_2M                  0x04
+#define MGN_5_5M                0x0b
+#define MGN_11M                 0x16
+
+#define MGN_6M                  0x0c
+#define MGN_9M                  0x12
+#define MGN_12M                 0x18
+#define MGN_18M                 0x24
+#define MGN_24M                 0x30
+#define MGN_36M                 0x48
+#define MGN_48M                 0x60
+#define MGN_54M                 0x6c
+
+#define MGN_MCS0                0x80
+#define MGN_MCS1                0x81
+#define MGN_MCS2                0x82
+#define MGN_MCS3                0x83
+#define MGN_MCS4                0x84
+#define MGN_MCS5                0x85
+#define MGN_MCS6                0x86
+#define MGN_MCS7                0x87
+#define MGN_MCS8                0x88
+#define MGN_MCS9                0x89
+#define MGN_MCS10               0x8a
+#define MGN_MCS11               0x8b
+#define MGN_MCS12               0x8c
+#define MGN_MCS13               0x8d
+#define MGN_MCS14               0x8e
+#define MGN_MCS15               0x8f
+#define	MGN_MCS0_SG			0x90
+#define	MGN_MCS1_SG			0x91
+#define	MGN_MCS2_SG			0x92
+#define	MGN_MCS3_SG			0x93
+#define	MGN_MCS4_SG			0x94
+#define	MGN_MCS5_SG			0x95
+#define	MGN_MCS6_SG			0x96
+#define	MGN_MCS7_SG			0x97
+#define	MGN_MCS8_SG			0x98
+#define	MGN_MCS9_SG			0x99
+#define	MGN_MCS10_SG		0x9a
+#define	MGN_MCS11_SG		0x9b
+#define	MGN_MCS12_SG		0x9c
+#define	MGN_MCS13_SG		0x9d
+#define	MGN_MCS14_SG		0x9e
+#define	MGN_MCS15_SG		0x9f
+
+
+//----------------------------------------------------------------------------
+//		802.11 Management frame Reason Code field
+//----------------------------------------------------------------------------
+enum	_ReasonCode{
+	unspec_reason	= 0x1,
+	auth_not_valid	= 0x2,
+	deauth_lv_ss	= 0x3,
+	inactivity		= 0x4,
+	ap_overload 	= 0x5,
+	class2_err		= 0x6,
+	class3_err		= 0x7,
+	disas_lv_ss 	= 0x8,
+	asoc_not_auth	= 0x9,
+
+	//----MIC_CHECK
+	mic_failure 	= 0xe,
+	//----END MIC_CHECK
+
+	// Reason code defined in 802.11i D10.0 p.28.
+	invalid_IE		= 0x0d,
+	four_way_tmout	= 0x0f,
+	two_way_tmout	= 0x10,
+	IE_dismatch 	= 0x11,
+	invalid_Gcipher = 0x12,
+	invalid_Pcipher = 0x13,
+	invalid_AKMP	= 0x14,
+	unsup_RSNIEver = 0x15,
+	invalid_RSNIE	= 0x16,
+	auth_802_1x_fail= 0x17,
+	ciper_reject		= 0x18,
+
+	// Reason code defined in 7.3.1.7, 802.1e D13.0, p.42. Added by Annie, 2005-11-15.
+	QoS_unspec		= 0x20, // 32
+	QAP_bandwidth	= 0x21, // 33
+	poor_condition	= 0x22, // 34
+	no_facility 	= 0x23, // 35
+							// Where is 36???
+	req_declined	= 0x25, // 37
+	invalid_param	= 0x26, // 38
+	req_not_honored= 0x27,	// 39
+	TS_not_created	= 0x2F, // 47
+	DL_not_allowed	= 0x30, // 48
+	dest_not_exist	= 0x31, // 49
+	dest_not_QSTA	= 0x32, // 50
+};
+
+
+
+#define aSifsTime	 (((priv->ieee80211->current_network.mode == IEEE_A)||(priv->ieee80211->current_network.mode == IEEE_N_24G)||(priv->ieee80211->current_network.mode == IEEE_N_5G))? 16 : 10)
+
+#define MGMT_QUEUE_NUM 5
+
+#define IEEE_CMD_SET_WPA_PARAM			1
+#define	IEEE_CMD_SET_WPA_IE			2
+#define IEEE_CMD_SET_ENCRYPTION			3
+#define IEEE_CMD_MLME				4
+
+#define IEEE_PARAM_WPA_ENABLED			1
+#define IEEE_PARAM_TKIP_COUNTERMEASURES		2
+#define IEEE_PARAM_DROP_UNENCRYPTED		3
+#define IEEE_PARAM_PRIVACY_INVOKED		4
+#define IEEE_PARAM_AUTH_ALGS			5
+#define IEEE_PARAM_IEEE_802_1X			6
+//It should consistent with the driver_XXX.c
+//   David, 2006.9.26
+#define IEEE_PARAM_WPAX_SELECT			7
+//Added for notify the encryption type selection
+//   David, 2006.9.26
+#define IEEE_PROTO_WPA				1
+#define IEEE_PROTO_RSN				2
+//Added for notify the encryption type selection
+//   David, 2006.9.26
+#define IEEE_WPAX_USEGROUP			0
+#define IEEE_WPAX_WEP40				1
+#define IEEE_WPAX_TKIP				2
+#define IEEE_WPAX_WRAP   			3
+#define IEEE_WPAX_CCMP				4
+#define IEEE_WPAX_WEP104			5
+
+#define IEEE_KEY_MGMT_IEEE8021X			1
+#define IEEE_KEY_MGMT_PSK			2
+
+#define IEEE_MLME_STA_DEAUTH			1
+#define IEEE_MLME_STA_DISASSOC			2
+
+
+#define IEEE_CRYPT_ERR_UNKNOWN_ALG		2
+#define IEEE_CRYPT_ERR_UNKNOWN_ADDR		3
+#define IEEE_CRYPT_ERR_CRYPT_INIT_FAILED	4
+#define IEEE_CRYPT_ERR_KEY_SET_FAILED		5
+#define IEEE_CRYPT_ERR_TX_KEY_SET_FAILED	6
+#define IEEE_CRYPT_ERR_CARD_CONF_FAILED		7
+
+
+#define	IEEE_CRYPT_ALG_NAME_LEN			16
+
+#define MAX_IE_LEN  0xff
+
+// added for kernel conflict
+#define ieee80211_crypt_deinit_entries 	ieee80211_crypt_deinit_entries_rsl
+#define ieee80211_crypt_deinit_handler 	ieee80211_crypt_deinit_handler_rsl
+#define ieee80211_crypt_delayed_deinit 	ieee80211_crypt_delayed_deinit_rsl
+#define ieee80211_register_crypto_ops  	ieee80211_register_crypto_ops_rsl
+#define ieee80211_unregister_crypto_ops ieee80211_unregister_crypto_ops_rsl
+#define ieee80211_get_crypto_ops 	ieee80211_get_crypto_ops_rsl
+
+#define ieee80211_ccmp_null		ieee80211_ccmp_null_rsl
+
+#define ieee80211_tkip_null		ieee80211_tkip_null_rsl
+
+#define ieee80211_wep_null		ieee80211_wep_null_rsl
+
+#define free_ieee80211          	free_ieee80211_rsl
+#define alloc_ieee80211        		alloc_ieee80211_rsl
+
+#define ieee80211_rx 			ieee80211_rx_rsl
+#define ieee80211_rx_mgt		ieee80211_rx_mgt_rsl
+
+#define ieee80211_get_beacon		ieee80211_get_beacon_rsl
+#define ieee80211_wake_queue		ieee80211_wake_queue_rsl
+#define ieee80211_stop_queue		ieee80211_stop_queue_rsl
+#define ieee80211_reset_queue		ieee80211_reset_queue_rsl
+#define ieee80211_softmac_stop_protocol	ieee80211_softmac_stop_protocol_rsl
+#define ieee80211_softmac_start_protocol ieee80211_softmac_start_protocol_rsl
+#define ieee80211_is_shortslot		ieee80211_is_shortslot_rsl
+#define ieee80211_is_54g		ieee80211_is_54g_rsl
+#define ieee80211_wpa_supplicant_ioctl	ieee80211_wpa_supplicant_ioctl_rsl
+#define ieee80211_ps_tx_ack		ieee80211_ps_tx_ack_rsl
+#define ieee80211_softmac_xmit		ieee80211_softmac_xmit_rsl
+#define ieee80211_stop_send_beacons	ieee80211_stop_send_beacons_rsl
+#define notify_wx_assoc_event		notify_wx_assoc_event_rsl
+#define SendDisassociation		SendDisassociation_rsl
+#define ieee80211_disassociate		ieee80211_disassociate_rsl
+#define ieee80211_start_send_beacons	ieee80211_start_send_beacons_rsl
+#define ieee80211_stop_scan		ieee80211_stop_scan_rsl
+#define ieee80211_send_probe_requests	ieee80211_send_probe_requests_rsl
+#define ieee80211_softmac_scan_syncro	ieee80211_softmac_scan_syncro_rsl
+#define ieee80211_start_scan_syncro	ieee80211_start_scan_syncro_rsl
+
+#define ieee80211_wx_get_essid		ieee80211_wx_get_essid_rsl
+#define ieee80211_wx_set_essid		ieee80211_wx_set_essid_rsl
+#define ieee80211_wx_set_rate		ieee80211_wx_set_rate_rsl
+#define ieee80211_wx_get_rate		ieee80211_wx_get_rate_rsl
+#define ieee80211_wx_set_wap		ieee80211_wx_set_wap_rsl
+#define ieee80211_wx_get_wap		ieee80211_wx_get_wap_rsl
+#define ieee80211_wx_set_mode		ieee80211_wx_set_mode_rsl
+#define ieee80211_wx_get_mode		ieee80211_wx_get_mode_rsl
+#define ieee80211_wx_set_scan		ieee80211_wx_set_scan_rsl
+#define ieee80211_wx_get_freq		ieee80211_wx_get_freq_rsl
+#define ieee80211_wx_set_freq		ieee80211_wx_set_freq_rsl
+#define ieee80211_wx_set_rawtx		ieee80211_wx_set_rawtx_rsl
+#define ieee80211_wx_get_name		ieee80211_wx_get_name_rsl
+#define ieee80211_wx_set_power		ieee80211_wx_set_power_rsl
+#define ieee80211_wx_get_power		ieee80211_wx_get_power_rsl
+#define ieee80211_wlan_frequencies	ieee80211_wlan_frequencies_rsl
+#define ieee80211_wx_set_rts		ieee80211_wx_set_rts_rsl
+#define ieee80211_wx_get_rts		ieee80211_wx_get_rts_rsl
+
+#define ieee80211_txb_free		ieee80211_txb_free_rsl
+
+#define ieee80211_wx_set_gen_ie		ieee80211_wx_set_gen_ie_rsl
+#define ieee80211_wx_get_scan		ieee80211_wx_get_scan_rsl
+#define ieee80211_wx_set_encode		ieee80211_wx_set_encode_rsl
+#define ieee80211_wx_get_encode		ieee80211_wx_get_encode_rsl
+#if WIRELESS_EXT >= 18
+#define ieee80211_wx_set_mlme		ieee80211_wx_set_mlme_rsl
+#define ieee80211_wx_set_auth		ieee80211_wx_set_auth_rsl
+#define ieee80211_wx_set_encode_ext	ieee80211_wx_set_encode_ext_rsl
+#define ieee80211_wx_get_encode_ext	ieee80211_wx_get_encode_ext_rsl
+#endif
+
+
+typedef struct ieee_param {
+	u32 cmd;
+	u8 sta_addr[ETH_ALEN];
+        union {
+		struct {
+			u8 name;
+			u32 value;
+		} wpa_param;
+		struct {
+			u32 len;
+			u8 reserved[32];
+			u8 data[0];
+		} wpa_ie;
+	        struct{
+			int command;
+    			int reason_code;
+		} mlme;
+		struct {
+			u8 alg[IEEE_CRYPT_ALG_NAME_LEN];
+			u8 set_tx;
+			u32 err;
+			u8 idx;
+			u8 seq[8]; /* sequence counter (set: RX, get: TX) */
+			u16 key_len;
+			u8 key[0];
+		} crypt;
+	} u;
+}ieee_param;
+
+
+#if WIRELESS_EXT < 17
+#define IW_QUAL_QUAL_INVALID   0x10
+#define IW_QUAL_LEVEL_INVALID  0x20
+#define IW_QUAL_NOISE_INVALID  0x40
+#define IW_QUAL_QUAL_UPDATED   0x1
+#define IW_QUAL_LEVEL_UPDATED  0x2
+#define IW_QUAL_NOISE_UPDATED  0x4
+#endif
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+static inline void tq_init(struct tq_struct * task, void(*func)(void *), void *data)
+{
+	task->routine = func;
+	task->data 	= data;
+	//task->next = NULL;
+	INIT_LIST_HEAD(&task->list);
+	task->sync = 0;
+}
+#endif
+
+// linux under 2.6.9 release may not support it, so modify it for common use
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,9))
+//#define MSECS(t)	(1000 * ((t) / HZ) + 1000 * ((t) % HZ) / HZ)
+#define MSECS(t)	(HZ * ((t) / 1000) + (HZ * ((t) % 1000)) / 1000)
+static inline unsigned long msleep_interruptible_rsl(unsigned int msecs)
+{
+         unsigned long timeout = MSECS(msecs) + 1;
+
+         while (timeout) {
+                 set_current_state(TASK_INTERRUPTIBLE);
+                 timeout = schedule_timeout(timeout);
+         }
+         return timeout;
+}
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,4,31))
+static inline void msleep(unsigned int msecs)
+{
+         unsigned long timeout = MSECS(msecs) + 1;
+
+         while (timeout) {
+                 set_current_state(TASK_UNINTERRUPTIBLE);
+                 timeout = schedule_timeout(timeout);
+         }
+}
+#endif
+#else
+#define MSECS(t) msecs_to_jiffies(t)
+#define msleep_interruptible_rsl  msleep_interruptible
+#endif
+
+#define IEEE80211_DATA_LEN		2304
+/* Maximum size for the MA-UNITDATA primitive, 802.11 standard section
+   6.2.1.1.2.
+
+   The figure in section 7.1.2 suggests a body size of up to 2312
+   bytes is allowed, which is a bit confusing, I suspect this
+   represents the 2304 bytes of real data, plus a possible 8 bytes of
+   WEP IV and ICV. (this interpretation suggested by Ramiro Barreiro) */
+#define IEEE80211_1ADDR_LEN 10
+#define IEEE80211_2ADDR_LEN 16
+#define IEEE80211_3ADDR_LEN 24
+#define IEEE80211_4ADDR_LEN 30
+#define IEEE80211_FCS_LEN    4
+#define IEEE80211_HLEN                  (IEEE80211_4ADDR_LEN)
+#define IEEE80211_FRAME_LEN             (IEEE80211_DATA_LEN + IEEE80211_HLEN)
+#define IEEE80211_MGMT_HDR_LEN 24
+#define IEEE80211_DATA_HDR3_LEN 24
+#define IEEE80211_DATA_HDR4_LEN 30
+
+#define MIN_FRAG_THRESHOLD     256U
+#define MAX_FRAG_THRESHOLD     2346U
+
+
+/* Frame control field constants */
+#define IEEE80211_FCTL_VERS		0x0003
+#define IEEE80211_FCTL_FTYPE		0x000c
+#define IEEE80211_FCTL_STYPE		0x00f0
+#define IEEE80211_FCTL_FRAMETYPE	0x00fc
+#define IEEE80211_FCTL_TODS		0x0100
+#define IEEE80211_FCTL_FROMDS		0x0200
+#define IEEE80211_FCTL_DSTODS		0x0300 //added by david
+#define IEEE80211_FCTL_MOREFRAGS	0x0400
+#define IEEE80211_FCTL_RETRY		0x0800
+#define IEEE80211_FCTL_PM		0x1000
+#define IEEE80211_FCTL_MOREDATA		0x2000
+#define IEEE80211_FCTL_WEP		0x4000
+#define IEEE80211_FCTL_ORDER		0x8000
+
+#define IEEE80211_FTYPE_MGMT		0x0000
+#define IEEE80211_FTYPE_CTL		0x0004
+#define IEEE80211_FTYPE_DATA		0x0008
+
+/* management */
+#define IEEE80211_STYPE_ASSOC_REQ	0x0000
+#define IEEE80211_STYPE_ASSOC_RESP 	0x0010
+#define IEEE80211_STYPE_REASSOC_REQ	0x0020
+#define IEEE80211_STYPE_REASSOC_RESP	0x0030
+#define IEEE80211_STYPE_PROBE_REQ	0x0040
+#define IEEE80211_STYPE_PROBE_RESP	0x0050
+#define IEEE80211_STYPE_BEACON		0x0080
+#define IEEE80211_STYPE_ATIM		0x0090
+#define IEEE80211_STYPE_DISASSOC	0x00A0
+#define IEEE80211_STYPE_AUTH		0x00B0
+#define IEEE80211_STYPE_DEAUTH		0x00C0
+#define IEEE80211_STYPE_MANAGE_ACT	0x00D0
+
+/* control */
+#define IEEE80211_STYPE_PSPOLL		0x00A0
+#define IEEE80211_STYPE_RTS		0x00B0
+#define IEEE80211_STYPE_CTS		0x00C0
+#define IEEE80211_STYPE_ACK		0x00D0
+#define IEEE80211_STYPE_CFEND		0x00E0
+#define IEEE80211_STYPE_CFENDACK	0x00F0
+#define IEEE80211_STYPE_BLOCKACK   0x0094
+
+/* data */
+#define IEEE80211_STYPE_DATA		0x0000
+#define IEEE80211_STYPE_DATA_CFACK	0x0010
+#define IEEE80211_STYPE_DATA_CFPOLL	0x0020
+#define IEEE80211_STYPE_DATA_CFACKPOLL	0x0030
+#define IEEE80211_STYPE_NULLFUNC	0x0040
+#define IEEE80211_STYPE_CFACK		0x0050
+#define IEEE80211_STYPE_CFPOLL		0x0060
+#define IEEE80211_STYPE_CFACKPOLL	0x0070
+#define IEEE80211_STYPE_QOS_DATA	0x0080 //added for WMM 2006/8/2
+#define IEEE80211_STYPE_QOS_NULL	0x00C0
+
+#define IEEE80211_SCTL_FRAG		0x000F
+#define IEEE80211_SCTL_SEQ		0xFFF0
+
+/* QOS control */
+#define IEEE80211_QCTL_TID              0x000F
+
+#define	FC_QOS_BIT					BIT7
+#define IsDataFrame(pdu)			( ((pdu[0] & 0x0C)==0x08) ? true : false )
+#define	IsLegacyDataFrame(pdu)	(IsDataFrame(pdu) && (!(pdu[0]&FC_QOS_BIT)) )
+//added by wb. Is this right?
+#define IsQoSDataFrame(pframe)  ((*(u16*)pframe&(IEEE80211_STYPE_QOS_DATA|IEEE80211_FTYPE_DATA)) == (IEEE80211_STYPE_QOS_DATA|IEEE80211_FTYPE_DATA))
+#define Frame_Order(pframe)     (*(u16*)pframe&IEEE80211_FCTL_ORDER)
+#define SN_LESS(a, b)		(((a-b)&0x800)!=0)
+#define SN_EQUAL(a, b)	(a == b)
+#define MAX_DEV_ADDR_SIZE 8
+typedef enum _ACT_CATEGORY{
+        ACT_CAT_QOS = 1,
+        ACT_CAT_DLS = 2,
+        ACT_CAT_BA  = 3,
+        ACT_CAT_HT  = 7,
+        ACT_CAT_WMM = 17,
+} ACT_CATEGORY, *PACT_CATEGORY;
+
+typedef enum _TS_ACTION{
+        ACT_ADDTSREQ = 0,
+        ACT_ADDTSRSP = 1,
+        ACT_DELTS    = 2,
+        ACT_SCHEDULE = 3,
+} TS_ACTION, *PTS_ACTION;
+
+typedef enum _BA_ACTION{
+        ACT_ADDBAREQ = 0,
+        ACT_ADDBARSP = 1,
+        ACT_DELBA    = 2,
+} BA_ACTION, *PBA_ACTION;
+
+typedef enum _InitialGainOpType{
+	IG_Backup=0,
+	IG_Restore,
+	IG_Max
+}InitialGainOpType;
+//added by amy for LED 090319
+//================================================================================
+// LED customization.
+//================================================================================
+typedef enum _LED_CTL_MODE{
+        LED_CTL_POWER_ON = 1,
+        LED_CTL_LINK = 2,
+        LED_CTL_NO_LINK = 3,
+        LED_CTL_TX = 4,
+        LED_CTL_RX = 5,
+        LED_CTL_SITE_SURVEY = 6,
+        LED_CTL_POWER_OFF = 7,
+        LED_CTL_START_TO_LINK = 8,
+        LED_CTL_START_WPS = 9,
+        LED_CTL_STOP_WPS = 10,
+        LED_CTL_START_WPS_BOTTON = 11, //added for runtop
+}LED_CTL_MODE;
+
+/* debug macros */
+#define CONFIG_IEEE80211_DEBUG
+#ifdef CONFIG_IEEE80211_DEBUG
+extern u32 ieee80211_debug_level;
+#define IEEE80211_DEBUG(level, fmt, args...) \
+do { if (ieee80211_debug_level & (level)) \
+  printk(KERN_DEBUG "ieee80211: " fmt, ## args); } while (0)
+//wb added to debug out data buf
+//if you want print DATA buffer related BA, please set ieee80211_debug_level to DATA|BA
+#define IEEE80211_DEBUG_DATA(level, data, datalen)	\
+	do{ if ((ieee80211_debug_level & (level)) == (level))	\
+		{ 	\
+			int i;					\
+			u8* pdata = (u8*) data;			\
+			printk(KERN_DEBUG "ieee80211: %s()\n", __FUNCTION__);	\
+			for(i=0; i<(int)(datalen); i++)			\
+			{						\
+				printk("%2x ", pdata[i]);		\
+				if ((i+1)%16 == 0) printk("\n");	\
+			}				\
+			printk("\n");			\
+		}					\
+	} while (0)
+#else
+#define IEEE80211_DEBUG(level, fmt, args...) do {} while (0)
+#define IEEE80211_DEBUG_DATA(level, data, datalen) do {} while(0)
+#endif	/* CONFIG_IEEE80211_DEBUG */
+
+/* debug macros not dependent on CONFIG_IEEE80211_DEBUG */
+
+#define MAC_FMT "%02x:%02x:%02x:%02x:%02x:%02x"
+#define MAC_ARG(x) ((u8*)(x))[0],((u8*)(x))[1],((u8*)(x))[2],((u8*)(x))[3],((u8*)(x))[4],((u8*)(x))[5]
+
+/*
+ * To use the debug system;
+ *
+ * If you are defining a new debug classification, simply add it to the #define
+ * list here in the form of:
+ *
+ * #define IEEE80211_DL_xxxx VALUE
+ *
+ * shifting value to the left one bit from the previous entry.  xxxx should be
+ * the name of the classification (for example, WEP)
+ *
+ * You then need to either add a IEEE80211_xxxx_DEBUG() macro definition for your
+ * classification, or use IEEE80211_DEBUG(IEEE80211_DL_xxxx, ...) whenever you want
+ * to send output to that classification.
+ *
+ * To add your debug level to the list of levels seen when you perform
+ *
+ * % cat /proc/net/ipw/debug_level
+ *
+ * you simply need to add your entry to the ipw_debug_levels array.
+ *
+ * If you do not see debug_level in /proc/net/ipw then you do not have
+ * CONFIG_IEEE80211_DEBUG defined in your kernel configuration
+ *
+ */
+
+#define IEEE80211_DL_INFO          (1<<0)
+#define IEEE80211_DL_WX            (1<<1)
+#define IEEE80211_DL_SCAN          (1<<2)
+#define IEEE80211_DL_STATE         (1<<3)
+#define IEEE80211_DL_MGMT          (1<<4)
+#define IEEE80211_DL_FRAG          (1<<5)
+#define IEEE80211_DL_EAP           (1<<6)
+#define IEEE80211_DL_DROP          (1<<7)
+
+#define IEEE80211_DL_TX            (1<<8)
+#define IEEE80211_DL_RX            (1<<9)
+
+#define IEEE80211_DL_HT		   (1<<10)  //HT
+#define IEEE80211_DL_BA		   (1<<11)  //ba
+#define IEEE80211_DL_TS		   (1<<12)  //TS
+#define IEEE80211_DL_QOS           (1<<13)
+#define IEEE80211_DL_REORDER	   (1<<14)
+#define IEEE80211_DL_IOT	   (1<<15)
+#define IEEE80211_DL_IPS	   (1<<16)
+#define IEEE80211_DL_TRACE	   (1<<29)  //trace function, need to user net_ratelimit() together in order not to print too much to the screen
+#define IEEE80211_DL_DATA	   (1<<30)   //use this flag to control whether print data buf out.
+#define IEEE80211_DL_ERR	   (1<<31)   //always open
+#define IEEE80211_ERROR(f, a...) printk(KERN_ERR "ieee80211: " f, ## a)
+#define IEEE80211_WARNING(f, a...) printk(KERN_WARNING "ieee80211: " f, ## a)
+#define IEEE80211_DEBUG_INFO(f, a...)   IEEE80211_DEBUG(IEEE80211_DL_INFO, f, ## a)
+
+#define IEEE80211_DEBUG_WX(f, a...)     IEEE80211_DEBUG(IEEE80211_DL_WX, f, ## a)
+#define IEEE80211_DEBUG_SCAN(f, a...)   IEEE80211_DEBUG(IEEE80211_DL_SCAN, f, ## a)
+#define IEEE80211_DEBUG_STATE(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_STATE, f, ## a)
+#define IEEE80211_DEBUG_MGMT(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_MGMT, f, ## a)
+#define IEEE80211_DEBUG_FRAG(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_FRAG, f, ## a)
+#define IEEE80211_DEBUG_EAP(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_EAP, f, ## a)
+#define IEEE80211_DEBUG_DROP(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_DROP, f, ## a)
+#define IEEE80211_DEBUG_TX(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_TX, f, ## a)
+#define IEEE80211_DEBUG_RX(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_RX, f, ## a)
+#define IEEE80211_DEBUG_QOS(f, a...)  IEEE80211_DEBUG(IEEE80211_DL_QOS, f, ## a)
+
+#ifdef CONFIG_IEEE80211_DEBUG
+/* Added by Annie, 2005-11-22. */
+#define MAX_STR_LEN     64
+/* I want to see ASCII 33 to 126 only. Otherwise, I print '?'. Annie, 2005-11-22.*/
+#define PRINTABLE(_ch)  (_ch>'!' && _ch<'~')
+#define IEEE80211_PRINT_STR(_Comp, _TitleString, _Ptr, _Len)                            	\
+                        if((_Comp) & level)   							\
+                        {                                                                       \
+                                int             __i;                                            \
+                                u8  buffer[MAX_STR_LEN];                                    	\
+                                int length = (_Len<MAX_STR_LEN)? _Len : (MAX_STR_LEN-1) ;  	\
+                                memset(buffer, 0, MAX_STR_LEN);                      		\
+                                memcpy(buffer, (u8 *)_Ptr, length );            		\
+                                for( __i=0; __i<MAX_STR_LEN; __i++ )                            \
+                                {                                                               \
+                                     if( !PRINTABLE(buffer[__i]) )   buffer[__i] = '?';     	\
+                                }                                                               \
+                                buffer[length] = '\0';                                          \
+                                printk("Rtl819x: ");                                         	\
+                                printk(_TitleString);                                         \
+                                printk(": %d, <%s>\n", _Len, buffer);                         \
+                        }
+#else
+#define IEEE80211_PRINT_STR(_Comp, _TitleString, _Ptr, _Len)  do {} while (0)
+#endif
+
+#include <linux/netdevice.h>
+#include <linux/if_arp.h> /* ARPHRD_ETHER */
+
+#ifndef WIRELESS_SPY
+#define WIRELESS_SPY		// enable iwspy support
+#endif
+#include <net/iw_handler.h>	// new driver API
+
+#ifndef ETH_P_PAE
+#define ETH_P_PAE 0x888E /* Port Access Entity (IEEE 802.1X) */
+#endif /* ETH_P_PAE */
+
+#define ETH_P_PREAUTH 0x88C7 /* IEEE 802.11i pre-authentication */
+
+#ifndef ETH_P_80211_RAW
+#define ETH_P_80211_RAW (ETH_P_ECONET + 1)
+#endif
+
+/* IEEE 802.11 defines */
+
+#define P80211_OUI_LEN 3
+
+struct ieee80211_snap_hdr {
+
+        u8    dsap;   /* always 0xAA */
+        u8    ssap;   /* always 0xAA */
+        u8    ctrl;   /* always 0x03 */
+        u8    oui[P80211_OUI_LEN];    /* organizational universal id */
+
+} __attribute__ ((packed));
+
+#define SNAP_SIZE sizeof(struct ieee80211_snap_hdr)
+
+#define WLAN_FC_GET_VERS(fc) ((fc) & IEEE80211_FCTL_VERS)
+#define WLAN_FC_GET_TYPE(fc) ((fc) & IEEE80211_FCTL_FTYPE)
+#define WLAN_FC_GET_STYPE(fc) ((fc) & IEEE80211_FCTL_STYPE)
+
+#define WLAN_FC_GET_FRAMETYPE(fc) ((fc) & IEEE80211_FCTL_FRAMETYPE)
+#define WLAN_GET_SEQ_FRAG(seq) ((seq) & IEEE80211_SCTL_FRAG)
+#define WLAN_GET_SEQ_SEQ(seq)  (((seq) & IEEE80211_SCTL_SEQ) >> 4)
+
+/* Authentication algorithms */
+#define WLAN_AUTH_OPEN 0
+#define WLAN_AUTH_SHARED_KEY 1
+#define WLAN_AUTH_LEAP 2
+
+#define WLAN_AUTH_CHALLENGE_LEN 128
+
+#define WLAN_CAPABILITY_BSS (1<<0)
+#define WLAN_CAPABILITY_IBSS (1<<1)
+#define WLAN_CAPABILITY_CF_POLLABLE (1<<2)
+#define WLAN_CAPABILITY_CF_POLL_REQUEST (1<<3)
+#define WLAN_CAPABILITY_PRIVACY (1<<4)
+#define WLAN_CAPABILITY_SHORT_PREAMBLE (1<<5)
+#define WLAN_CAPABILITY_PBCC (1<<6)
+#define WLAN_CAPABILITY_CHANNEL_AGILITY (1<<7)
+#define WLAN_CAPABILITY_SPECTRUM_MGMT (1<<8)
+#define WLAN_CAPABILITY_QOS (1<<9)
+#define WLAN_CAPABILITY_SHORT_SLOT (1<<10)
+#define WLAN_CAPABILITY_DSSS_OFDM (1<<13)
+
+/* 802.11g ERP information element */
+#define WLAN_ERP_NON_ERP_PRESENT (1<<0)
+#define WLAN_ERP_USE_PROTECTION (1<<1)
+#define WLAN_ERP_BARKER_PREAMBLE (1<<2)
+
+/* Status codes */
+enum ieee80211_statuscode {
+        WLAN_STATUS_SUCCESS = 0,
+        WLAN_STATUS_UNSPECIFIED_FAILURE = 1,
+        WLAN_STATUS_CAPS_UNSUPPORTED = 10,
+        WLAN_STATUS_REASSOC_NO_ASSOC = 11,
+        WLAN_STATUS_ASSOC_DENIED_UNSPEC = 12,
+        WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG = 13,
+        WLAN_STATUS_UNKNOWN_AUTH_TRANSACTION = 14,
+        WLAN_STATUS_CHALLENGE_FAIL = 15,
+        WLAN_STATUS_AUTH_TIMEOUT = 16,
+        WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA = 17,
+        WLAN_STATUS_ASSOC_DENIED_RATES = 18,
+        /* 802.11b */
+        WLAN_STATUS_ASSOC_DENIED_NOSHORTPREAMBLE = 19,
+        WLAN_STATUS_ASSOC_DENIED_NOPBCC = 20,
+        WLAN_STATUS_ASSOC_DENIED_NOAGILITY = 21,
+        /* 802.11h */
+        WLAN_STATUS_ASSOC_DENIED_NOSPECTRUM = 22,
+        WLAN_STATUS_ASSOC_REJECTED_BAD_POWER = 23,
+        WLAN_STATUS_ASSOC_REJECTED_BAD_SUPP_CHAN = 24,
+        /* 802.11g */
+        WLAN_STATUS_ASSOC_DENIED_NOSHORTTIME = 25,
+        WLAN_STATUS_ASSOC_DENIED_NODSSSOFDM = 26,
+        /* 802.11i */
+        WLAN_STATUS_INVALID_IE = 40,
+        WLAN_STATUS_INVALID_GROUP_CIPHER = 41,
+        WLAN_STATUS_INVALID_PAIRWISE_CIPHER = 42,
+        WLAN_STATUS_INVALID_AKMP = 43,
+        WLAN_STATUS_UNSUPP_RSN_VERSION = 44,
+        WLAN_STATUS_INVALID_RSN_IE_CAP = 45,
+        WLAN_STATUS_CIPHER_SUITE_REJECTED = 46,
+};
+
+/* Reason codes */
+enum ieee80211_reasoncode {
+        WLAN_REASON_UNSPECIFIED = 1,
+        WLAN_REASON_PREV_AUTH_NOT_VALID = 2,
+        WLAN_REASON_DEAUTH_LEAVING = 3,
+        WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY = 4,
+        WLAN_REASON_DISASSOC_AP_BUSY = 5,
+        WLAN_REASON_CLASS2_FRAME_FROM_NONAUTH_STA = 6,
+        WLAN_REASON_CLASS3_FRAME_FROM_NONASSOC_STA = 7,
+        WLAN_REASON_DISASSOC_STA_HAS_LEFT = 8,
+        WLAN_REASON_STA_REQ_ASSOC_WITHOUT_AUTH = 9,
+        /* 802.11h */
+        WLAN_REASON_DISASSOC_BAD_POWER = 10,
+        WLAN_REASON_DISASSOC_BAD_SUPP_CHAN = 11,
+        /* 802.11i */
+        WLAN_REASON_INVALID_IE = 13,
+        WLAN_REASON_MIC_FAILURE = 14,
+        WLAN_REASON_4WAY_HANDSHAKE_TIMEOUT = 15,
+        WLAN_REASON_GROUP_KEY_HANDSHAKE_TIMEOUT = 16,
+        WLAN_REASON_IE_DIFFERENT = 17,
+        WLAN_REASON_INVALID_GROUP_CIPHER = 18,
+        WLAN_REASON_INVALID_PAIRWISE_CIPHER = 19,
+        WLAN_REASON_INVALID_AKMP = 20,
+        WLAN_REASON_UNSUPP_RSN_VERSION = 21,
+        WLAN_REASON_INVALID_RSN_IE_CAP = 22,
+        WLAN_REASON_IEEE8021X_FAILED = 23,
+        WLAN_REASON_CIPHER_SUITE_REJECTED = 24,
+};
+
+#define IEEE80211_STATMASK_SIGNAL (1<<0)
+#define IEEE80211_STATMASK_RSSI (1<<1)
+#define IEEE80211_STATMASK_NOISE (1<<2)
+#define IEEE80211_STATMASK_RATE (1<<3)
+#define IEEE80211_STATMASK_WEMASK 0x7
+
+#define IEEE80211_CCK_MODULATION    (1<<0)
+#define IEEE80211_OFDM_MODULATION   (1<<1)
+
+#define IEEE80211_24GHZ_BAND     (1<<0)
+#define IEEE80211_52GHZ_BAND     (1<<1)
+
+#define IEEE80211_CCK_RATE_LEN  		4
+#define IEEE80211_CCK_RATE_1MB		        0x02
+#define IEEE80211_CCK_RATE_2MB		        0x04
+#define IEEE80211_CCK_RATE_5MB		        0x0B
+#define IEEE80211_CCK_RATE_11MB		        0x16
+#define IEEE80211_OFDM_RATE_LEN 		8
+#define IEEE80211_OFDM_RATE_6MB		        0x0C
+#define IEEE80211_OFDM_RATE_9MB		        0x12
+#define IEEE80211_OFDM_RATE_12MB		0x18
+#define IEEE80211_OFDM_RATE_18MB		0x24
+#define IEEE80211_OFDM_RATE_24MB		0x30
+#define IEEE80211_OFDM_RATE_36MB		0x48
+#define IEEE80211_OFDM_RATE_48MB		0x60
+#define IEEE80211_OFDM_RATE_54MB		0x6C
+#define IEEE80211_BASIC_RATE_MASK		0x80
+
+#define IEEE80211_CCK_RATE_1MB_MASK		(1<<0)
+#define IEEE80211_CCK_RATE_2MB_MASK		(1<<1)
+#define IEEE80211_CCK_RATE_5MB_MASK		(1<<2)
+#define IEEE80211_CCK_RATE_11MB_MASK		(1<<3)
+#define IEEE80211_OFDM_RATE_6MB_MASK		(1<<4)
+#define IEEE80211_OFDM_RATE_9MB_MASK		(1<<5)
+#define IEEE80211_OFDM_RATE_12MB_MASK		(1<<6)
+#define IEEE80211_OFDM_RATE_18MB_MASK		(1<<7)
+#define IEEE80211_OFDM_RATE_24MB_MASK		(1<<8)
+#define IEEE80211_OFDM_RATE_36MB_MASK		(1<<9)
+#define IEEE80211_OFDM_RATE_48MB_MASK		(1<<10)
+#define IEEE80211_OFDM_RATE_54MB_MASK		(1<<11)
+
+#define IEEE80211_CCK_RATES_MASK	        0x0000000F
+#define IEEE80211_CCK_BASIC_RATES_MASK	(IEEE80211_CCK_RATE_1MB_MASK | \
+	IEEE80211_CCK_RATE_2MB_MASK)
+#define IEEE80211_CCK_DEFAULT_RATES_MASK	(IEEE80211_CCK_BASIC_RATES_MASK | \
+        IEEE80211_CCK_RATE_5MB_MASK | \
+        IEEE80211_CCK_RATE_11MB_MASK)
+
+#define IEEE80211_OFDM_RATES_MASK		0x00000FF0
+#define IEEE80211_OFDM_BASIC_RATES_MASK	(IEEE80211_OFDM_RATE_6MB_MASK | \
+	IEEE80211_OFDM_RATE_12MB_MASK | \
+	IEEE80211_OFDM_RATE_24MB_MASK)
+#define IEEE80211_OFDM_DEFAULT_RATES_MASK	(IEEE80211_OFDM_BASIC_RATES_MASK | \
+	IEEE80211_OFDM_RATE_9MB_MASK  | \
+	IEEE80211_OFDM_RATE_18MB_MASK | \
+	IEEE80211_OFDM_RATE_36MB_MASK | \
+	IEEE80211_OFDM_RATE_48MB_MASK | \
+	IEEE80211_OFDM_RATE_54MB_MASK)
+#define IEEE80211_DEFAULT_RATES_MASK (IEEE80211_OFDM_DEFAULT_RATES_MASK | \
+                                IEEE80211_CCK_DEFAULT_RATES_MASK)
+
+#define IEEE80211_NUM_OFDM_RATES	    8
+#define IEEE80211_NUM_CCK_RATES	            4
+#define IEEE80211_OFDM_SHIFT_MASK_A         4
+
+
+/* this is stolen and modified from the madwifi driver*/
+#define IEEE80211_FC0_TYPE_MASK		0x0c
+#define IEEE80211_FC0_TYPE_DATA		0x08
+#define IEEE80211_FC0_SUBTYPE_MASK	0xB0
+#define IEEE80211_FC0_SUBTYPE_QOS	0x80
+
+#define IEEE80211_QOS_HAS_SEQ(fc) \
+	(((fc) & (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) == \
+	 (IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_QOS))
+
+/* this is stolen from ipw2200 driver */
+#define IEEE_IBSS_MAC_HASH_SIZE 31
+struct ieee_ibss_seq {
+	u8 mac[ETH_ALEN];
+	u16 seq_num[17];
+	u16 frag_num[17];
+	unsigned long packet_time[17];
+	struct list_head list;
+};
+
+/* NOTE: This data is for statistical purposes; not all hardware provides this
+ *       information for frames received.  Not setting these will not cause
+ *       any adverse affects. */
+struct ieee80211_rx_stats {
+#if 1
+	u32 mac_time[2];
+	s8 rssi;
+	u8 signal;
+	u8 noise;
+	u16 rate; /* in 100 kbps */
+	u8 received_channel;
+	u8 control;
+	u8 mask;
+	u8 freq;
+	u16 len;
+	u64 tsf;
+	u32 beacon_time;
+	u8 nic_type;
+	u16       Length;
+	//      u8        DataRate;      // In 0.5 Mbps
+	u8        SignalQuality; // in 0-100 index.
+	s32       RecvSignalPower; // Real power in dBm for this packet, no beautification and aggregation.
+	s8        RxPower; // in dBm Translate from PWdB
+	u8        SignalStrength; // in 0-100 index.
+	u16       bHwError:1;
+	u16       bCRC:1;
+	u16       bICV:1;
+	u16       bShortPreamble:1;
+	u16       Antenna:1;      //for rtl8185
+	u16       Decrypted:1;    //for rtl8185, rtl8187
+	u16       Wakeup:1;       //for rtl8185
+	u16       Reserved0:1;    //for rtl8185
+	u8        AGC;
+	u32       TimeStampLow;
+	u32       TimeStampHigh;
+	bool      bShift;
+	bool      bIsQosData;             // Added by Annie, 2005-12-22.
+	u8        UserPriority;
+
+	//1!!!!!!!!!!!!!!!!!!!!!!!!!!!
+	//1Attention Please!!!<11n or 8190 specific code should be put below this line>
+	//1!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+	u8        RxDrvInfoSize;
+	u8        RxBufShift;
+	bool      bIsAMPDU;
+	bool      bFirstMPDU;
+	bool      bContainHTC;
+	bool      RxIs40MHzPacket;
+	u32       RxPWDBAll;
+	u8        RxMIMOSignalStrength[4];        // in 0~100 index
+	s8        RxMIMOSignalQuality[2];
+	bool      bPacketMatchBSSID;
+	bool      bIsCCK;
+	bool      bPacketToSelf;
+	//added by amy
+	u8*       virtual_address;
+	u16          packetlength;              // Total packet length: Must equal to sum of all FragLength
+	u16          fraglength;                        // FragLength should equal to PacketLength in non-fragment case
+	u16          fragoffset;                        // Data offset for this fragment
+	u16          ntotalfrag;
+	bool      	  bisrxaggrsubframe;
+	bool		  bPacketBeacon;	//cosa add for rssi
+	bool		  bToSelfBA;		//cosa add for rssi
+	char 	  cck_adc_pwdb[4];	//cosa add for rx path selection
+	u16		  Seq_Num;
+	u8		nTotalAggPkt;		// Number of aggregated packets.
+#endif
+
+};
+
+/* IEEE 802.11 requires that STA supports concurrent reception of at least
+ * three fragmented frames. This define can be increased to support more
+ * concurrent frames, but it should be noted that each entry can consume about
+ * 2 kB of RAM and increasing cache size will slow down frame reassembly. */
+#define IEEE80211_FRAG_CACHE_LEN 4
+
+struct ieee80211_frag_entry {
+	unsigned long first_frag_time;
+	unsigned int seq;
+	unsigned int last_frag;
+	struct sk_buff *skb;
+	u8 src_addr[ETH_ALEN];
+	u8 dst_addr[ETH_ALEN];
+};
+
+struct ieee80211_stats {
+	unsigned int tx_unicast_frames;
+	unsigned int tx_multicast_frames;
+	unsigned int tx_fragments;
+	unsigned int tx_unicast_octets;
+	unsigned int tx_multicast_octets;
+	unsigned int tx_deferred_transmissions;
+	unsigned int tx_single_retry_frames;
+	unsigned int tx_multiple_retry_frames;
+	unsigned int tx_retry_limit_exceeded;
+	unsigned int tx_discards;
+	unsigned int rx_unicast_frames;
+	unsigned int rx_multicast_frames;
+	unsigned int rx_fragments;
+	unsigned int rx_unicast_octets;
+	unsigned int rx_multicast_octets;
+	unsigned int rx_fcs_errors;
+	unsigned int rx_discards_no_buffer;
+	unsigned int tx_discards_wrong_sa;
+	unsigned int rx_discards_undecryptable;
+	unsigned int rx_message_in_msg_fragments;
+	unsigned int rx_message_in_bad_msg_fragments;
+};
+
+struct ieee80211_device;
+
+#include "ieee80211_crypt.h"
+
+#define SEC_KEY_1         (1<<0)
+#define SEC_KEY_2         (1<<1)
+#define SEC_KEY_3         (1<<2)
+#define SEC_KEY_4         (1<<3)
+#define SEC_ACTIVE_KEY    (1<<4)
+#define SEC_AUTH_MODE     (1<<5)
+#define SEC_UNICAST_GROUP (1<<6)
+#define SEC_LEVEL         (1<<7)
+#define SEC_ENABLED       (1<<8)
+#define SEC_ENCRYPT       (1<<9)
+
+#define SEC_LEVEL_0      0 /* None */
+#define SEC_LEVEL_1      1 /* WEP 40 and 104 bit */
+#define SEC_LEVEL_2      2 /* Level 1 + TKIP */
+#define SEC_LEVEL_2_CKIP 3 /* Level 1 + CKIP */
+#define SEC_LEVEL_3      4 /* Level 2 + CCMP */
+
+#define SEC_ALG_NONE            0
+#define SEC_ALG_WEP             1
+#define SEC_ALG_TKIP            2
+#define SEC_ALG_CCMP            3
+
+#define WEP_KEYS 		4
+#define WEP_KEY_LEN		13
+#define SCM_KEY_LEN             32
+#define SCM_TEMPORAL_KEY_LENGTH 16
+
+struct ieee80211_security {
+	u16 active_key:2,
+            enabled:1,
+	    auth_mode:2,
+            auth_algo:4,
+            unicast_uses_group:1,
+	    encrypt:1;
+	u8 key_sizes[WEP_KEYS];
+	u8 keys[WEP_KEYS][SCM_KEY_LEN];
+	u8 level;
+	u16 flags;
+} __attribute__ ((packed));
+
+
+/*
+ 802.11 data frame from AP
+      ,-------------------------------------------------------------------.
+Bytes |  2   |  2   |    6    |    6    |    6    |  2   | 0..2312 |   4  |
+      |------|------|---------|---------|---------|------|---------|------|
+Desc. | ctrl | dura |  DA/RA  |   TA    |    SA   | Sequ |  frame  |  fcs |
+      |      | tion | (BSSID) |         |         | ence |  data   |      |
+      `-------------------------------------------------------------------'
+Total: 28-2340 bytes
+*/
+
+/* Management Frame Information Element Types */
+enum ieee80211_mfie {
+        MFIE_TYPE_SSID = 0,
+        MFIE_TYPE_RATES = 1,
+        MFIE_TYPE_FH_SET = 2,
+        MFIE_TYPE_DS_SET = 3,
+        MFIE_TYPE_CF_SET = 4,
+        MFIE_TYPE_TIM = 5,
+        MFIE_TYPE_IBSS_SET = 6,
+        MFIE_TYPE_COUNTRY = 7,
+        MFIE_TYPE_HOP_PARAMS = 8,
+        MFIE_TYPE_HOP_TABLE = 9,
+        MFIE_TYPE_REQUEST = 10,
+        MFIE_TYPE_CHALLENGE = 16,
+        MFIE_TYPE_POWER_CONSTRAINT = 32,
+        MFIE_TYPE_POWER_CAPABILITY = 33,
+        MFIE_TYPE_TPC_REQUEST = 34,
+        MFIE_TYPE_TPC_REPORT = 35,
+        MFIE_TYPE_SUPP_CHANNELS = 36,
+        MFIE_TYPE_CSA = 37,
+        MFIE_TYPE_MEASURE_REQUEST = 38,
+        MFIE_TYPE_MEASURE_REPORT = 39,
+        MFIE_TYPE_QUIET = 40,
+        MFIE_TYPE_IBSS_DFS = 41,
+        MFIE_TYPE_ERP = 42,
+        MFIE_TYPE_RSN = 48,
+        MFIE_TYPE_RATES_EX = 50,
+        MFIE_TYPE_HT_CAP= 45,
+	 MFIE_TYPE_HT_INFO= 61,
+	 MFIE_TYPE_AIRONET=133,
+        MFIE_TYPE_GENERIC = 221,
+        MFIE_TYPE_QOS_PARAMETER = 222,
+};
+
+/* Minimal header; can be used for passing 802.11 frames with sufficient
+ * information to determine what type of underlying data type is actually
+ * stored in the data. */
+struct ieee80211_hdr {
+        __le16 frame_ctl;
+        __le16 duration_id;
+        u8 payload[0];
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_1addr {
+        __le16 frame_ctl;
+        __le16 duration_id;
+        u8 addr1[ETH_ALEN];
+        u8 payload[0];
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_2addr {
+        __le16 frame_ctl;
+        __le16 duration_id;
+        u8 addr1[ETH_ALEN];
+        u8 addr2[ETH_ALEN];
+        u8 payload[0];
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_3addr {
+	__le16 frame_ctl;
+	__le16 duration_id;
+	u8 addr1[ETH_ALEN];
+	u8 addr2[ETH_ALEN];
+	u8 addr3[ETH_ALEN];
+	__le16 seq_ctl;
+        u8 payload[0];
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_4addr {
+	__le16 frame_ctl;
+	__le16 duration_id;
+	u8 addr1[ETH_ALEN];
+	u8 addr2[ETH_ALEN];
+	u8 addr3[ETH_ALEN];
+	__le16 seq_ctl;
+	u8 addr4[ETH_ALEN];
+        u8 payload[0];
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_3addrqos {
+	__le16 frame_ctl;
+	__le16 duration_id;
+	u8 addr1[ETH_ALEN];
+	u8 addr2[ETH_ALEN];
+	u8 addr3[ETH_ALEN];
+	__le16 seq_ctl;
+        u8 payload[0];
+	__le16 qos_ctl;
+} __attribute__ ((packed));
+
+struct ieee80211_hdr_4addrqos {
+	__le16 frame_ctl;
+	__le16 duration_id;
+	u8 addr1[ETH_ALEN];
+	u8 addr2[ETH_ALEN];
+	u8 addr3[ETH_ALEN];
+	__le16 seq_ctl;
+	u8 addr4[ETH_ALEN];
+        u8 payload[0];
+	__le16 qos_ctl;
+} __attribute__ ((packed));
+
+struct ieee80211_info_element {
+	u8 id;
+	u8 len;
+	u8 data[0];
+} __attribute__ ((packed));
+
+struct ieee80211_authentication {
+	struct ieee80211_hdr_3addr header;
+	__le16 algorithm;
+	__le16 transaction;
+	__le16 status;
+	/*challenge*/
+	struct ieee80211_info_element info_element[0];
+} __attribute__ ((packed));
+
+struct ieee80211_disassoc {
+        struct ieee80211_hdr_3addr header;
+        __le16 reason;
+} __attribute__ ((packed));
+
+struct ieee80211_probe_request {
+	struct ieee80211_hdr_3addr header;
+	/* SSID, supported rates */
+        struct ieee80211_info_element info_element[0];
+} __attribute__ ((packed));
+
+struct ieee80211_probe_response {
+	struct ieee80211_hdr_3addr header;
+	u32 time_stamp[2];
+	__le16 beacon_interval;
+	__le16 capability;
+        /* SSID, supported rates, FH params, DS params,
+         * CF params, IBSS params, TIM (if beacon), RSN */
+        struct ieee80211_info_element info_element[0];
+} __attribute__ ((packed));
+
+/* Alias beacon for probe_response */
+#define ieee80211_beacon ieee80211_probe_response
+
+struct ieee80211_assoc_request_frame {
+	struct ieee80211_hdr_3addr header;
+	__le16 capability;
+	__le16 listen_interval;
+	/* SSID, supported rates, RSN */
+        struct ieee80211_info_element info_element[0];
+} __attribute__ ((packed));
+
+struct ieee80211_reassoc_request_frame {
+	struct ieee80211_hdr_3addr header;
+	__le16 capability;
+	__le16 listen_interval;
+	u8 current_ap[ETH_ALEN];
+	/* SSID, supported rates, RSN */
+        struct ieee80211_info_element info_element[0];
+} __attribute__ ((packed));
+
+struct ieee80211_assoc_response_frame {
+	struct ieee80211_hdr_3addr header;
+	__le16 capability;
+	__le16 status;
+	__le16 aid;
+	struct ieee80211_info_element info_element[0]; /* supported rates */
+} __attribute__ ((packed));
+
+struct ieee80211_txb {
+	u8 nr_frags;
+	u8 encrypted;
+	u8 queue_index;
+	u8 rts_included;
+	u16 reserved;
+	__le16 frag_size;
+	__le16 payload_size;
+	struct sk_buff *fragments[0];
+};
+
+#define MAX_TX_AGG_COUNT		  16
+struct ieee80211_drv_agg_txb {
+	u8 nr_drv_agg_frames;
+	struct sk_buff *tx_agg_frames[MAX_TX_AGG_COUNT];
+}__attribute__((packed));
+
+#define MAX_SUBFRAME_COUNT 		  64
+struct ieee80211_rxb {
+	u8 nr_subframes;
+	struct sk_buff *subframes[MAX_SUBFRAME_COUNT];
+	u8 dst[ETH_ALEN];
+	u8 src[ETH_ALEN];
+}__attribute__((packed));
+
+typedef union _frameqos {
+	u16 shortdata;
+	u8  chardata[2];
+	struct {
+		u16 tid:4;
+		u16 eosp:1;
+		u16 ack_policy:2;
+		u16 reserved:1;
+		u16 txop:8;
+	}field;
+}frameqos,*pframeqos;
+
+/* SWEEP TABLE ENTRIES NUMBER*/
+#define MAX_SWEEP_TAB_ENTRIES		  42
+#define MAX_SWEEP_TAB_ENTRIES_PER_PACKET  7
+/* MAX_RATES_LENGTH needs to be 12.  The spec says 8, and many APs
+ * only use 8, and then use extended rates for the remaining supported
+ * rates.  Other APs, however, stick all of their supported rates on the
+ * main rates information element... */
+#define MAX_RATES_LENGTH                  ((u8)12)
+#define MAX_RATES_EX_LENGTH               ((u8)16)
+#define MAX_NETWORK_COUNT                  128
+
+#define MAX_CHANNEL_NUMBER                 161
+#define IEEE80211_SOFTMAC_SCAN_TIME	   100
+//(HZ / 2)
+#define IEEE80211_SOFTMAC_ASSOC_RETRY_TIME (HZ * 2)
+
+#define CRC_LENGTH                 4U
+
+#define MAX_WPA_IE_LEN 64
+
+#define NETWORK_EMPTY_ESSID (1<<0)
+#define NETWORK_HAS_OFDM    (1<<1)
+#define NETWORK_HAS_CCK     (1<<2)
+
+/* QoS structure */
+#define NETWORK_HAS_QOS_PARAMETERS      (1<<3)
+#define NETWORK_HAS_QOS_INFORMATION     (1<<4)
+#define NETWORK_HAS_QOS_MASK            (NETWORK_HAS_QOS_PARAMETERS | \
+                                         NETWORK_HAS_QOS_INFORMATION)
+/* 802.11h */
+#define NETWORK_HAS_POWER_CONSTRAINT    (1<<5)
+#define NETWORK_HAS_CSA                 (1<<6)
+#define NETWORK_HAS_QUIET               (1<<7)
+#define NETWORK_HAS_IBSS_DFS            (1<<8)
+#define NETWORK_HAS_TPC_REPORT          (1<<9)
+
+#define NETWORK_HAS_ERP_VALUE           (1<<10)
+
+#define QOS_QUEUE_NUM                   4
+#define QOS_OUI_LEN                     3
+#define QOS_OUI_TYPE                    2
+#define QOS_ELEMENT_ID                  221
+#define QOS_OUI_INFO_SUB_TYPE           0
+#define QOS_OUI_PARAM_SUB_TYPE          1
+#define QOS_VERSION_1                   1
+#define QOS_AIFSN_MIN_VALUE             2
+#if 1
+struct ieee80211_qos_information_element {
+        u8 elementID;
+        u8 length;
+        u8 qui[QOS_OUI_LEN];
+        u8 qui_type;
+        u8 qui_subtype;
+        u8 version;
+        u8 ac_info;
+} __attribute__ ((packed));
+
+struct ieee80211_qos_ac_parameter {
+        u8 aci_aifsn;
+        u8 ecw_min_max;
+        __le16 tx_op_limit;
+} __attribute__ ((packed));
+
+struct ieee80211_qos_parameter_info {
+        struct ieee80211_qos_information_element info_element;
+        u8 reserved;
+        struct ieee80211_qos_ac_parameter ac_params_record[QOS_QUEUE_NUM];
+} __attribute__ ((packed));
+
+struct ieee80211_qos_parameters {
+        __le16 cw_min[QOS_QUEUE_NUM];
+        __le16 cw_max[QOS_QUEUE_NUM];
+        u8 aifs[QOS_QUEUE_NUM];
+        u8 flag[QOS_QUEUE_NUM];
+        __le16 tx_op_limit[QOS_QUEUE_NUM];
+} __attribute__ ((packed));
+
+struct ieee80211_qos_data {
+        struct ieee80211_qos_parameters parameters;
+        int active;
+        int supported;
+        u8 param_count;
+        u8 old_param_count;
+};
+
+struct ieee80211_tim_parameters {
+        u8 tim_count;
+        u8 tim_period;
+} __attribute__ ((packed));
+
+//#else
+struct ieee80211_wmm_ac_param {
+	u8 ac_aci_acm_aifsn;
+	u8 ac_ecwmin_ecwmax;
+	u16 ac_txop_limit;
+};
+
+struct ieee80211_wmm_ts_info {
+	u8 ac_dir_tid;
+	u8 ac_up_psb;
+	u8 reserved;
+} __attribute__ ((packed));
+
+struct ieee80211_wmm_tspec_elem {
+	struct ieee80211_wmm_ts_info ts_info;
+	u16 norm_msdu_size;
+	u16 max_msdu_size;
+	u32 min_serv_inter;
+	u32 max_serv_inter;
+	u32 inact_inter;
+	u32 suspen_inter;
+	u32 serv_start_time;
+	u32 min_data_rate;
+	u32 mean_data_rate;
+	u32 peak_data_rate;
+	u32 max_burst_size;
+	u32 delay_bound;
+	u32 min_phy_rate;
+	u16 surp_band_allow;
+	u16 medium_time;
+}__attribute__((packed));
+#endif
+enum eap_type {
+	EAP_PACKET = 0,
+	EAPOL_START,
+	EAPOL_LOGOFF,
+	EAPOL_KEY,
+	EAPOL_ENCAP_ASF_ALERT
+};
+
+static const char *eap_types[] = {
+	[EAP_PACKET]		= "EAP-Packet",
+	[EAPOL_START]		= "EAPOL-Start",
+	[EAPOL_LOGOFF]		= "EAPOL-Logoff",
+	[EAPOL_KEY]		= "EAPOL-Key",
+	[EAPOL_ENCAP_ASF_ALERT]	= "EAPOL-Encap-ASF-Alert"
+};
+
+static inline const char *eap_get_type(int type)
+{
+	return ((u32)type >= ARRAY_SIZE(eap_types)) ? "Unknown" : eap_types[type];
+}
+//added by amy for reorder
+static inline u8 Frame_QoSTID(u8* buf)
+{
+	struct ieee80211_hdr_3addr *hdr;
+	u16 fc;
+	hdr = (struct ieee80211_hdr_3addr *)buf;
+	fc = le16_to_cpu(hdr->frame_ctl);
+	return (u8)((frameqos*)(buf + (((fc & IEEE80211_FCTL_TODS)&&(fc & IEEE80211_FCTL_FROMDS))? 30 : 24)))->field.tid;
+}
+
+//added by amy for reorder
+
+struct eapol {
+	u8 snap[6];
+	u16 ethertype;
+	u8 version;
+	u8 type;
+	u16 length;
+} __attribute__ ((packed));
+
+struct ieee80211_softmac_stats{
+	unsigned int rx_ass_ok;
+	unsigned int rx_ass_err;
+	unsigned int rx_probe_rq;
+	unsigned int tx_probe_rs;
+	unsigned int tx_beacons;
+	unsigned int rx_auth_rq;
+	unsigned int rx_auth_rs_ok;
+	unsigned int rx_auth_rs_err;
+	unsigned int tx_auth_rq;
+	unsigned int no_auth_rs;
+	unsigned int no_ass_rs;
+	unsigned int tx_ass_rq;
+	unsigned int rx_ass_rq;
+	unsigned int tx_probe_rq;
+	unsigned int reassoc;
+	unsigned int swtxstop;
+	unsigned int swtxawake;
+	unsigned char CurrentShowTxate;
+	unsigned char last_packet_rate;
+	unsigned int txretrycount;
+};
+
+#define BEACON_PROBE_SSID_ID_POSITION 12
+
+struct ieee80211_info_element_hdr {
+	u8 id;
+	u8 len;
+} __attribute__ ((packed));
+
+/*
+ * These are the data types that can make up management packets
+ *
+	u16 auth_algorithm;
+	u16 auth_sequence;
+	u16 beacon_interval;
+	u16 capability;
+	u8 current_ap[ETH_ALEN];
+	u16 listen_interval;
+	struct {
+		u16 association_id:14, reserved:2;
+	} __attribute__ ((packed));
+	u32 time_stamp[2];
+	u16 reason;
+	u16 status;
+*/
+
+#define IEEE80211_DEFAULT_TX_ESSID "Penguin"
+#define IEEE80211_DEFAULT_BASIC_RATE 2 //1Mbps
+
+enum {WMM_all_frame, WMM_two_frame, WMM_four_frame, WMM_six_frame};
+#define MAX_SP_Len  (WMM_all_frame << 4)
+#define IEEE80211_QOS_TID 0x0f
+#define QOS_CTL_NOTCONTAIN_ACK (0x01 << 5)
+
+#define IEEE80211_DTIM_MBCAST 4
+#define IEEE80211_DTIM_UCAST 2
+#define IEEE80211_DTIM_VALID 1
+#define IEEE80211_DTIM_INVALID 0
+
+#define IEEE80211_PS_DISABLED 0
+#define IEEE80211_PS_UNICAST IEEE80211_DTIM_UCAST
+#define IEEE80211_PS_MBCAST IEEE80211_DTIM_MBCAST
+
+//added by David for QoS 2006/6/30
+//#define WMM_Hang_8187
+#ifdef WMM_Hang_8187
+#undef WMM_Hang_8187
+#endif
+
+#define WME_AC_BK   0x00
+#define WME_AC_BE   0x01
+#define WME_AC_VI   0x02
+#define WME_AC_VO   0x03
+#define WME_ACI_MASK 0x03
+#define WME_AIFSN_MASK 0x03
+#define WME_AC_PRAM_LEN 16
+
+#define MAX_RECEIVE_BUFFER_SIZE 9100
+
+//UP Mapping to AC, using in MgntQuery_SequenceNumber() and maybe for DSCP
+//#define UP2AC(up)	((up<3) ? ((up==0)?1:0) : (up>>1))
+#if 1
+#define UP2AC(up) (		   \
+	((up) < 1) ? WME_AC_BE : \
+	((up) < 3) ? WME_AC_BK : \
+	((up) < 4) ? WME_AC_BE : \
+	((up) < 6) ? WME_AC_VI : \
+	WME_AC_VO)
+#endif
+//AC Mapping to UP, using in Tx part for selecting the corresponding TX queue
+#define AC2UP(_ac)	(       \
+	((_ac) == WME_AC_VO) ? 6 : \
+	((_ac) == WME_AC_VI) ? 5 : \
+	((_ac) == WME_AC_BK) ? 1 : \
+	0)
+
+#define	ETHER_ADDR_LEN		6	/* length of an Ethernet address */
+#define ETHERNET_HEADER_SIZE    14      /* length of two Ethernet address plus ether type*/
+
+struct	ether_header {
+	u8 ether_dhost[ETHER_ADDR_LEN];
+	u8 ether_shost[ETHER_ADDR_LEN];
+	u16 ether_type;
+} __attribute__((packed));
+
+#ifndef ETHERTYPE_PAE
+#define	ETHERTYPE_PAE	0x888e		/* EAPOL PAE/802.1x */
+#endif
+#ifndef ETHERTYPE_IP
+#define	ETHERTYPE_IP	0x0800		/* IP protocol */
+#endif
+
+typedef struct _bss_ht{
+
+	bool				support_ht;
+
+	// HT related elements
+	u8					ht_cap_buf[32];
+	u16					ht_cap_len;
+	u8					ht_info_buf[32];
+	u16					ht_info_len;
+
+	HT_SPEC_VER			ht_spec_ver;
+	//HT_CAPABILITY_ELE			bdHTCapEle;
+	//HT_INFORMATION_ELE		bdHTInfoEle;
+
+	bool				aggregation;
+	bool				long_slot_time;
+}bss_ht, *pbss_ht;
+
+typedef enum _erp_t{
+	ERP_NonERPpresent	= 0x01,
+	ERP_UseProtection	= 0x02,
+	ERP_BarkerPreambleMode = 0x04,
+} erp_t;
+
+
+struct ieee80211_network {
+	/* These entries are used to identify a unique network */
+	u8 bssid[ETH_ALEN];
+	u8 channel;
+	/* Ensure null-terminated for any debug msgs */
+	u8 ssid[IW_ESSID_MAX_SIZE + 1];
+	u8 ssid_len;
+#if 1
+        struct ieee80211_qos_data qos_data;
+#else
+       // Qos related. Added by Annie, 2005-11-01.
+        BSS_QOS   BssQos;
+#endif
+
+	//added by amy for LEAP
+	bool	bWithAironetIE;
+	bool	bCkipSupported;
+	bool	bCcxRmEnable;
+	u16 	CcxRmState[2];
+	// CCXv4 S59, MBSSID.
+	bool	bMBssidValid;
+	u8	MBssidMask;
+	u8	MBssid[6];
+	// CCX 2 S38, WLAN Device Version Number element. Annie, 2006-08-20.
+	bool	bWithCcxVerNum;
+	u8	BssCcxVerNumber;
+	/* These are network statistics */
+	struct ieee80211_rx_stats stats;
+	u16 capability;
+	u8  rates[MAX_RATES_LENGTH];
+	u8  rates_len;
+	u8  rates_ex[MAX_RATES_EX_LENGTH];
+	u8  rates_ex_len;
+	unsigned long last_scanned;
+	u8  mode;
+	u32 flags;
+	u32 last_associate;
+	u32 time_stamp[2];
+	u16 beacon_interval;
+	u16 listen_interval;
+	u16 atim_window;
+	u8  erp_value;
+	u8  wpa_ie[MAX_WPA_IE_LEN];
+	size_t wpa_ie_len;
+	u8  rsn_ie[MAX_WPA_IE_LEN];
+	size_t rsn_ie_len;
+
+        struct ieee80211_tim_parameters tim;
+	u8  dtim_period;
+	u8  dtim_data;
+	u32 last_dtim_sta_time[2];
+
+        //appeded for QoS
+        u8 wmm_info;
+        struct ieee80211_wmm_ac_param wmm_param[4];
+        u8 QoS_Enable;
+#ifdef THOMAS_TURBO
+	u8 Turbo_Enable;//enable turbo mode, added by thomas
+#endif
+#ifdef ENABLE_DOT11D
+	u16 CountryIeLen;
+	u8 CountryIeBuf[MAX_IE_LEN];
+#endif
+        // HT Related, by amy, 2008.04.29
+	BSS_HT	bssht;
+	// Add to handle broadcom AP management frame CCK rate.
+	bool broadcom_cap_exist;
+	bool realtek_cap_exit;
+	bool marvell_cap_exist;
+	bool ralink_cap_exist;
+	bool atheros_cap_exist;
+	bool cisco_cap_exist;
+	bool unknown_cap_exist;
+//	u8	berp_info;
+	bool	berp_info_valid;
+	bool buseprotection;
+	//put at the end of the structure.
+	struct list_head list;
+};
+
+#if 1
+enum ieee80211_state {
+
+	/* the card is not linked at all */
+	IEEE80211_NOLINK = 0,
+
+	/* IEEE80211_ASSOCIATING* are for BSS client mode
+	 * the driver shall not perform RX filtering unless
+	 * the state is LINKED.
+	 * The driver shall just check for the state LINKED and
+	 * defaults to NOLINK for ALL the other states (including
+	 * LINKED_SCANNING)
+	 */
+
+	/* the association procedure will start (wq scheduling)*/
+	IEEE80211_ASSOCIATING,
+	IEEE80211_ASSOCIATING_RETRY,
+
+	/* the association procedure is sending AUTH request*/
+	IEEE80211_ASSOCIATING_AUTHENTICATING,
+
+	/* the association procedure has successfully authentcated
+	 * and is sending association request
+	 */
+	IEEE80211_ASSOCIATING_AUTHENTICATED,
+
+	/* the link is ok. the card associated to a BSS or linked
+	 * to a ibss cell or acting as an AP and creating the bss
+	 */
+	IEEE80211_LINKED,
+
+	/* same as LINKED, but the driver shall apply RX filter
+	 * rules as we are in NO_LINK mode. As the card is still
+	 * logically linked, but it is doing a syncro site survey
+	 * then it will be back to LINKED state.
+	 */
+	IEEE80211_LINKED_SCANNING,
+
+};
+#else
+enum ieee80211_state {
+        IEEE80211_UNINITIALIZED = 0,
+        IEEE80211_INITIALIZED,
+        IEEE80211_ASSOCIATING,
+        IEEE80211_ASSOCIATED,
+        IEEE80211_AUTHENTICATING,
+        IEEE80211_AUTHENTICATED,
+        IEEE80211_SHUTDOWN
+};
+#endif
+
+#define DEFAULT_MAX_SCAN_AGE (15 * HZ)
+#define DEFAULT_FTS 2346
+
+#define CFG_IEEE80211_RESERVE_FCS (1<<0)
+#define CFG_IEEE80211_COMPUTE_FCS (1<<1)
+#define CFG_IEEE80211_RTS (1<<2)
+
+#define IEEE80211_24GHZ_MIN_CHANNEL 1
+#define IEEE80211_24GHZ_MAX_CHANNEL 14
+#define IEEE80211_24GHZ_CHANNELS (IEEE80211_24GHZ_MAX_CHANNEL - \
+                                  IEEE80211_24GHZ_MIN_CHANNEL + 1)
+
+#define IEEE80211_52GHZ_MIN_CHANNEL 34
+#define IEEE80211_52GHZ_MAX_CHANNEL 165
+#define IEEE80211_52GHZ_CHANNELS (IEEE80211_52GHZ_MAX_CHANNEL - \
+                                  IEEE80211_52GHZ_MIN_CHANNEL + 1)
+
+#if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,11))
+extern inline int is_multicast_ether_addr(const u8 *addr)
+{
+        return ((addr[0] != 0xff) && (0x01 & addr[0]));
+}
+#endif
+
+#if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,13))
+extern inline int is_broadcast_ether_addr(const u8 *addr)
+{
+	return ((addr[0] == 0xff) && (addr[1] == 0xff) && (addr[2] == 0xff) &&   \
+		(addr[3] == 0xff) && (addr[4] == 0xff) && (addr[5] == 0xff));
+}
+#endif
+
+typedef struct tx_pending_t{
+	int frag;
+	struct ieee80211_txb *txb;
+}tx_pending_t;
+
+typedef struct _bandwidth_autoswitch
+{
+	long threshold_20Mhzto40Mhz;
+	long	threshold_40Mhzto20Mhz;
+	bool bforced_tx20Mhz;
+	bool bautoswitch_enable;
+}bandwidth_autoswitch,*pbandwidth_autoswitch;
+
+
+//added by amy for order
+
+#define REORDER_WIN_SIZE	128
+#define REORDER_ENTRY_NUM	128
+typedef struct _RX_REORDER_ENTRY
+{
+	struct list_head	List;
+	u16			SeqNum;
+	struct ieee80211_rxb* prxb;
+} RX_REORDER_ENTRY, *PRX_REORDER_ENTRY;
+//added by amy for order
+typedef enum _Fsync_State{
+	Default_Fsync,
+	HW_Fsync,
+	SW_Fsync
+}Fsync_State;
+
+// Power save mode configured.
+typedef	enum _RT_PS_MODE
+{
+	eActive,	// Active/Continuous access.
+	eMaxPs,		// Max power save mode.
+	eFastPs		// Fast power save mode.
+}RT_PS_MODE;
+
+typedef enum _IPS_CALLBACK_FUNCION
+{
+	IPS_CALLBACK_NONE = 0,
+	IPS_CALLBACK_MGNT_LINK_REQUEST = 1,
+	IPS_CALLBACK_JOIN_REQUEST = 2,
+}IPS_CALLBACK_FUNCION;
+
+typedef enum _RT_JOIN_ACTION{
+	RT_JOIN_INFRA   = 1,
+	RT_JOIN_IBSS  = 2,
+	RT_START_IBSS = 3,
+	RT_NO_ACTION  = 4,
+}RT_JOIN_ACTION;
+
+typedef struct _IbssParms{
+	u16   atimWin;
+}IbssParms, *PIbssParms;
+#define MAX_NUM_RATES	264 // Max num of support rates element: 8,  Max num of ext. support rate: 255. 061122, by rcnjko.
+
+// RF state.
+typedef	enum _RT_RF_POWER_STATE
+{
+	eRfOn,
+	eRfSleep,
+	eRfOff
+}RT_RF_POWER_STATE;
+
+typedef struct _RT_POWER_SAVE_CONTROL
+{
+
+	//
+	// Inactive Power Save(IPS) : Disable RF when disconnected
+	//
+	bool				bInactivePs;
+	bool				bIPSModeBackup;
+	bool				bHaltAdapterClkRQ;
+	bool				bSwRfProcessing;
+	RT_RF_POWER_STATE	eInactivePowerState;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	struct work_struct 	InactivePsWorkItem;
+#else
+	struct tq_struct	InactivePsWorkItem;
+#endif
+	struct timer_list	InactivePsTimer;
+
+	// Return point for join action
+	IPS_CALLBACK_FUNCION	ReturnPoint;
+
+	// Recored Parameters for rescheduled JoinRequest
+	bool				bTmpBssDesc;
+	RT_JOIN_ACTION		tmpJoinAction;
+	struct ieee80211_network tmpBssDesc;
+
+	// Recored Parameters for rescheduled MgntLinkRequest
+	bool				bTmpScanOnly;
+	bool				bTmpActiveScan;
+	bool				bTmpFilterHiddenAP;
+	bool				bTmpUpdateParms;
+	u8					tmpSsidBuf[33];
+	OCTET_STRING			tmpSsid2Scan;
+	bool				bTmpSsid2Scan;
+	u8					tmpNetworkType;
+	u8					tmpChannelNumber;
+	u16					tmpBcnPeriod;
+	u8					tmpDtimPeriod;
+	u16					tmpmCap;
+	OCTET_STRING			tmpSuppRateSet;
+	u8					tmpSuppRateBuf[MAX_NUM_RATES];
+	bool				bTmpSuppRate;
+	IbssParms				tmpIbpm;
+	bool				bTmpIbpm;
+
+	//
+	// Leisre Poswer Save : Disable RF if connected but traffic is not busy
+	//
+	bool				bLeisurePs;
+	u32				PowerProfile;
+	u8				LpsIdleCount;
+	u8				RegMaxLPSAwakeIntvl;
+	u8				LPSAwakeIntvl;
+
+	//RF OFF Level
+	u32				CurPsLevel;
+	u32				RegRfPsLevel;
+
+	//Fw Control LPS
+	bool				bFwCtrlLPS;
+	u8				FWCtrlPSMode;
+
+	//2009.01.01 added by tynli
+	// Record if there is a link request in IPS RF off progress.
+	bool				LinkReqInIPSRFOffPgs;
+	// To make sure that connect info should be executed, so we set the bit to filter the link info which comes after the connect info.
+	bool				BufConnectinfoBefore;
+
+}RT_POWER_SAVE_CONTROL,*PRT_POWER_SAVE_CONTROL;
+
+typedef u32 RT_RF_CHANGE_SOURCE;
+#define RF_CHANGE_BY_SW BIT31
+#define RF_CHANGE_BY_HW BIT30
+#define RF_CHANGE_BY_PS BIT29
+#define RF_CHANGE_BY_IPS BIT28
+#define RF_CHANGE_BY_INIT	0	// Do not change the RFOff reason. Defined by Bruce, 2008-01-17.
+
+#ifdef ENABLE_DOT11D
+typedef enum
+{
+	COUNTRY_CODE_FCC = 0,
+	COUNTRY_CODE_IC = 1,
+	COUNTRY_CODE_ETSI = 2,
+	COUNTRY_CODE_SPAIN = 3,
+	COUNTRY_CODE_FRANCE = 4,
+	COUNTRY_CODE_MKK = 5,
+	COUNTRY_CODE_MKK1 = 6,
+	COUNTRY_CODE_ISRAEL = 7,
+	COUNTRY_CODE_TELEC,
+	COUNTRY_CODE_MIC,
+	COUNTRY_CODE_GLOBAL_DOMAIN
+}country_code_type_t;
+#endif
+	// Firmware realted CMD IO.
+typedef	enum _FW_CMD_IO_TYPE{
+	FW_CMD_DIG_ENABLE = 0, // For DIG DM
+	FW_CMD_DIG_DISABLE = 1,
+	FW_CMD_DIG_HALT = 2,
+	FW_CMD_DIG_RESUME = 3,
+	FW_CMD_HIGH_PWR_ENABLE = 4, // For High Power DM
+	FW_CMD_HIGH_PWR_DISABLE = 5,
+	FW_CMD_RA_RESET = 6, // For Rate adaptive DM
+	FW_CMD_RA_ACTIVE= 7,
+	FW_CMD_RA_REFRESH_N= 8,
+	FW_CMD_RA_REFRESH_BG= 9,
+	FW_CMD_IQK_ENABLE = 10, // For FW supported IQK
+	FW_CMD_TXPWR_TRACK_ENABLE = 11,	// Tx power tracking switch
+	FW_CMD_TXPWR_TRACK_DISABLE = 12,	// Tx power tracking switch
+	FW_CMD_PAUSE_DM_BY_SCAN = 13,
+	FW_CMD_RESUME_DM_BY_SCAN = 14,
+	FW_CMD_MID_HIGH_PWR_ENABLE = 15,
+	FW_CMD_LPS_ENTER = 16,			// Indifate firmware that driver enters LPS, For PS-Poll hardware bug
+	FW_CMD_LPS_LEAVE = 17,			// Indicate firmware that driver leave LPS, 2009/1/4, by Emily
+}FW_CMD_IO_TYPE,*PFW_CMD_IO_TYPE;
+#define RT_MAX_LD_SLOT_NUM	10
+typedef struct _RT_LINK_DETECT_T{
+
+	u32				NumRecvBcnInPeriod;
+	u32				NumRecvDataInPeriod;
+
+	u32				RxBcnNum[RT_MAX_LD_SLOT_NUM];	// number of Rx beacon / CheckForHang_period  to determine link status
+	u32				RxDataNum[RT_MAX_LD_SLOT_NUM];	// number of Rx data / CheckForHang_period  to determine link status
+	u16				SlotNum;	// number of CheckForHang period to determine link status
+	u16				SlotIndex;
+
+	u32				NumTxOkInPeriod;
+	u32				NumRxOkInPeriod;
+	bool				bBusyTraffic;
+}RT_LINK_DETECT_T, *PRT_LINK_DETECT_T;
+
+
+struct ieee80211_device {
+	struct net_device *dev;
+        struct ieee80211_security sec;
+
+	//hw security related
+//	u8 hwsec_support; //support?
+	u8 hwsec_active;  //hw security active.
+	bool is_silent_reset;
+	bool is_roaming;
+	bool ieee_up;
+	//added by amy
+	bool bSupportRemoteWakeUp;
+	RT_PS_MODE	dot11PowerSaveMode; // Power save mode configured.
+	bool actscanning;
+	//added by amy 090313
+	bool be_scan_inprogress;
+	bool beinretry;
+	RT_RF_POWER_STATE		eRFPowerState;
+	RT_RF_CHANGE_SOURCE	RfOffReason;
+	bool is_set_key;
+	//11n spec related I wonder if These info structure need to be moved out of ieee80211_device
+
+	//11n HT below
+	PRT_HIGH_THROUGHPUT	pHTInfo;
+	//struct timer_list		SwBwTimer;
+//	spinlock_t chnlop_spinlock;
+	spinlock_t bw_spinlock;
+
+	spinlock_t reorder_spinlock;
+	// for HT operation rate set.  we use this one for HT data rate to seperate different descriptors
+	//the way fill this is the same as in the IE
+	u8	Regdot11HTOperationalRateSet[16];		//use RATR format
+	u8	dot11HTOperationalRateSet[16];		//use RATR format
+	u8	RegHTSuppRateSet[16];
+	u8				HTCurrentOperaRate;
+	u8				HTHighestOperaRate;
+	//wb added for rate operation mode to firmware
+	u8	bTxDisableRateFallBack;
+	u8 	bTxUseDriverAssingedRate;
+	atomic_t	atm_chnlop;
+	atomic_t	atm_swbw;
+//	u8	HTHighestOperaRate;
+//	u8 	HTCurrentOperaRate;
+
+	// 802.11e and WMM Traffic Stream Info (TX)
+	struct list_head		Tx_TS_Admit_List;
+	struct list_head		Tx_TS_Pending_List;
+	struct list_head		Tx_TS_Unused_List;
+	TX_TS_RECORD		TxTsRecord[TOTAL_TS_NUM];
+	// 802.11e and WMM Traffic Stream Info (RX)
+	struct list_head		Rx_TS_Admit_List;
+	struct list_head		Rx_TS_Pending_List;
+	struct list_head		Rx_TS_Unused_List;
+	RX_TS_RECORD		RxTsRecord[TOTAL_TS_NUM];
+//#ifdef TO_DO_LIST
+	RX_REORDER_ENTRY	RxReorderEntry[128];
+	struct list_head		RxReorder_Unused_List;
+//#endif
+	// Qos related. Added by Annie, 2005-11-01.
+//	PSTA_QOS			pStaQos;
+	u8				ForcedPriority;		// Force per-packet priority 1~7. (default: 0, not to force it.)
+
+
+	/* Bookkeeping structures */
+	struct net_device_stats stats;
+	struct ieee80211_stats ieee_stats;
+	struct ieee80211_softmac_stats softmac_stats;
+
+	/* Probe / Beacon management */
+	struct list_head network_free_list;
+	struct list_head network_list;
+	struct ieee80211_network *networks;
+	int scans;
+	int scan_age;
+
+	int iw_mode; /* operating mode (IW_MODE_*) */
+	struct iw_spy_data spy_data;
+
+	spinlock_t lock;
+	spinlock_t wpax_suitlist_lock;
+
+	int tx_headroom; /* Set to size of any additional room needed at front
+			  * of allocated Tx SKBs */
+	u32 config;
+
+	/* WEP and other encryption related settings at the device level */
+	int open_wep; /* Set to 1 to allow unencrypted frames */
+	int auth_mode;
+	int reset_on_keychange; /* Set to 1 if the HW needs to be reset on
+				 * WEP key changes */
+
+	/* If the host performs {en,de}cryption, then set to 1 */
+	int host_encrypt;
+	int host_encrypt_msdu;
+	int host_decrypt;
+        /* host performs multicast decryption */
+        int host_mc_decrypt;
+
+        /* host should strip IV and ICV from protected frames */
+        /* meaningful only when hardware decryption is being used */
+        int host_strip_iv_icv;
+
+        int host_open_frag;
+        int host_build_iv;
+	int ieee802_1x; /* is IEEE 802.1X used */
+
+	/* WPA data */
+	bool bHalfWirelessN24GMode;
+	int wpa_enabled;
+	int drop_unencrypted;
+	int tkip_countermeasures;
+	int privacy_invoked;
+	size_t wpa_ie_len;
+	u8 *wpa_ie;
+	u8 ap_mac_addr[6];
+	u16 pairwise_key_type;
+	u16 group_key_type;
+	struct list_head crypt_deinit_list;
+	struct ieee80211_crypt_data *crypt[WEP_KEYS];
+	int tx_keyidx; /* default TX key index (crypt[tx_keyidx]) */
+	struct timer_list crypt_deinit_timer;
+        int crypt_quiesced;
+
+	int bcrx_sta_key; /* use individual keys to override default keys even
+			   * with RX of broad/multicast frames */
+
+	/* Fragmentation structures */
+	// each streaming contain a entry
+	struct ieee80211_frag_entry frag_cache[17][IEEE80211_FRAG_CACHE_LEN];
+	unsigned int frag_next_idx[17];
+	u16 fts; /* Fragmentation Threshold */
+#define DEFAULT_RTS_THRESHOLD 2346U
+#define MIN_RTS_THRESHOLD 1
+#define MAX_RTS_THRESHOLD 2346U
+        u16 rts; /* RTS threshold */
+
+        /* Association info */
+        u8 bssid[ETH_ALEN];
+
+	/* This stores infos for the current network.
+	 * Either the network we are associated in INFRASTRUCTURE
+	 * or the network that we are creating in MASTER mode.
+	 * ad-hoc is a mixture ;-).
+	 * Note that in infrastructure mode, even when not associated,
+	 * fields bssid and essid may be valid (if wpa_set and essid_set
+	 * are true) as thy carry the value set by the user via iwconfig
+	 */
+	struct ieee80211_network current_network;
+
+	enum ieee80211_state state;
+
+	int short_slot;
+	int reg_mode;
+	int mode;       /* A, B, G */
+	int modulation; /* CCK, OFDM */
+	int freq_band;  /* 2.4Ghz, 5.2Ghz, Mixed */
+	int abg_true;   /* ABG flag              */
+
+	/* used for forcing the ibss workqueue to terminate
+	 * without wait for the syncro scan to terminate
+	 */
+	short sync_scan_hurryup;
+	u16 scan_watch_dog;
+        int perfect_rssi;
+        int worst_rssi;
+
+        u16 prev_seq_ctl;       /* used to drop duplicate frames */
+
+	/* map of allowed channels. 0 is dummy */
+	// FIXME: remeber to default to a basic channel plan depending of the PHY type
+#ifdef ENABLE_DOT11D
+	void* pDot11dInfo;
+	bool bGlobalDomain;
+#else
+	int channel_map[MAX_CHANNEL_NUMBER+1];
+#endif
+	int rate;       /* current rate */
+	int basic_rate;
+	//FIXME: pleace callback, see if redundant with softmac_features
+	short active_scan;
+
+	/* this contains flags for selectively enable softmac support */
+	u16 softmac_features;
+
+	/* if the sequence control field is not filled by HW */
+	u16 seq_ctrl[5];
+
+	/* association procedure transaction sequence number */
+	u16 associate_seq;
+
+	/* AID for RTXed association responses */
+	u16 assoc_id;
+
+	/* power save mode related*/
+	u8 ack_tx_to_ieee;
+	short ps;
+	short sta_sleep;
+	int ps_timeout;
+	int ps_period;
+	struct tasklet_struct ps_task;
+	u32 ps_th;
+	u32 ps_tl;
+
+	short raw_tx;
+	/* used if IEEE_SOFTMAC_TX_QUEUE is set */
+	short queue_stop;
+	short scanning;
+	short proto_started;
+
+	struct semaphore wx_sem;
+	struct semaphore scan_sem;
+
+	spinlock_t mgmt_tx_lock;
+	spinlock_t beacon_lock;
+
+	short beacon_txing;
+
+	short wap_set;
+	short ssid_set;
+
+	u8  wpax_type_set;    //{added by David, 2006.9.28}
+	u32 wpax_type_notify; //{added by David, 2006.9.26}
+
+	/* QoS related flag */
+	char init_wmmparam_flag;
+	/* set on initialization */
+	u8  qos_support;
+
+	/* for discarding duplicated packets in IBSS */
+	struct list_head ibss_mac_hash[IEEE_IBSS_MAC_HASH_SIZE];
+
+	/* for discarding duplicated packets in BSS */
+	u16 last_rxseq_num[17]; /* rx seq previous per-tid */
+	u16 last_rxfrag_num[17];/* tx frag previous per-tid */
+	unsigned long last_packet_time[17];
+
+	/* for PS mode */
+	unsigned long last_rx_ps_time;
+
+	/* used if IEEE_SOFTMAC_SINGLE_QUEUE is set */
+	struct sk_buff *mgmt_queue_ring[MGMT_QUEUE_NUM];
+	int mgmt_queue_head;
+	int mgmt_queue_tail;
+//{ added for rtl819x
+#define IEEE80211_QUEUE_LIMIT 128
+	u8 AsocRetryCount;
+	unsigned int hw_header;
+	struct sk_buff_head skb_waitQ[MAX_QUEUE_SIZE];
+	struct sk_buff_head  skb_aggQ[MAX_QUEUE_SIZE];
+	struct sk_buff_head  skb_drv_aggQ[MAX_QUEUE_SIZE];
+	u32	sta_edca_param[4];
+	bool aggregation;
+	// Enable/Disable Rx immediate BA capability.
+	bool enable_rx_imm_BA;
+	bool bibsscoordinator;
+
+	//+by amy for DM ,080515
+	//Dynamic Tx power for near/far range enable/Disable  , by amy , 2008-05-15
+	bool	bdynamic_txpower_enable;
+
+	bool bCTSToSelfEnable;
+	u8 	CTSToSelfTH;
+
+	u32 	fsync_time_interval;
+	u32	fsync_rate_bitmap;
+	u8	fsync_rssi_threshold;
+	bool	bfsync_enable;
+
+	u8	fsync_multiple_timeinterval;		// FsyncMultipleTimeInterval * FsyncTimeInterval
+	u32	fsync_firstdiff_ratethreshold;		// low threshold
+	u32	fsync_seconddiff_ratethreshold;	 // decrease threshold
+	Fsync_State			fsync_state;
+	bool		bis_any_nonbepkts;
+	//20Mhz 40Mhz AutoSwitch Threshold
+	bandwidth_autoswitch bandwidth_auto_switch;
+	//for txpower tracking
+	bool FwRWRF;
+
+	//added by amy for AP roaming
+	RT_LINK_DETECT_T	LinkDetectInfo;
+        //added by amy for ps
+	RT_POWER_SAVE_CONTROL	PowerSaveControl;
+//}
+	/* used if IEEE_SOFTMAC_TX_QUEUE is set */
+	struct  tx_pending_t tx_pending;
+
+	/* used if IEEE_SOFTMAC_ASSOCIATE is set */
+	struct timer_list associate_timer;
+
+	/* used if IEEE_SOFTMAC_BEACONS is set */
+	struct timer_list beacon_timer;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+        struct work_struct associate_complete_wq;
+        struct work_struct associate_procedure_wq;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+        struct delayed_work softmac_scan_wq;
+        struct delayed_work associate_retry_wq;
+	 struct delayed_work start_ibss_wq;
+	 struct delayed_work hw_wakeup_wq;
+	struct delayed_work hw_sleep_wq;
+	struct delayed_work link_change_wq;
+#else
+        struct work_struct softmac_scan_wq;
+        struct work_struct associate_retry_wq;
+	struct work_struct start_ibss_wq;
+	struct work_struct hw_wakeup_wq;
+	struct work_struct hw_sleep_wq;
+	struct work_struct link_change_wq;
+#endif
+        struct work_struct wx_sync_scan_wq;
+        struct workqueue_struct *wq;
+#else
+	/* used for periodly scan */
+	struct timer_list scan_timer;
+
+	struct tq_struct associate_complete_wq;
+	struct tq_struct associate_retry_wq;
+	struct tq_struct start_ibss_wq;
+	struct tq_struct associate_procedure_wq;
+	struct tq_struct softmac_scan_wq;
+	struct tq_struct wx_sync_scan_wq;
+	struct tq_struct hw_wakeup_wq;
+	struct tq_struct hw_sleep_wq;
+	struct tq_struct link_change_wq;
+
+#endif
+        // Qos related. Added by Annie, 2005-11-01.
+        //STA_QOS  StaQos;
+
+        //u32 STA_EDCA_PARAM[4];
+	//CHANNEL_ACCESS_SETTING ChannelAccessSetting;
+
+
+	/* Callback functions */
+	void (*set_security)(struct net_device *dev,
+			     struct ieee80211_security *sec);
+
+	/* Used to TX data frame by using txb structs.
+	 * this is not used if in the softmac_features
+	 * is set the flag IEEE_SOFTMAC_TX_QUEUE
+	 */
+	int (*hard_start_xmit)(struct ieee80211_txb *txb,
+			       struct net_device *dev);
+
+	int (*reset_port)(struct net_device *dev);
+        int (*is_queue_full) (struct net_device * dev, int pri);
+
+        int (*handle_management) (struct net_device * dev,
+                                  struct ieee80211_network * network, u16 type);
+        int (*is_qos_active) (struct net_device *dev, struct sk_buff *skb);
+
+	/* Softmac-generated frames (mamagement) are TXed via this
+	 * callback if the flag IEEE_SOFTMAC_SINGLE_QUEUE is
+	 * not set. As some cards may have different HW queues that
+	 * one might want to use for data and management frames
+	 * the option to have two callbacks might be useful.
+	 * This fucntion can't sleep.
+	 */
+	int (*softmac_hard_start_xmit)(struct sk_buff *skb,
+			       struct net_device *dev);
+
+	/* used instead of hard_start_xmit (not softmac_hard_start_xmit)
+	 * if the IEEE_SOFTMAC_TX_QUEUE feature is used to TX data
+	 * frames. I the option IEEE_SOFTMAC_SINGLE_QUEUE is also set
+	 * then also management frames are sent via this callback.
+	 * This function can't sleep.
+	 */
+	void (*softmac_data_hard_start_xmit)(struct sk_buff *skb,
+			       struct net_device *dev,int rate);
+
+	/* stops the HW queue for DATA frames. Useful to avoid
+	 * waste time to TX data frame when we are reassociating
+	 * This function can sleep.
+	 */
+	void (*data_hard_stop)(struct net_device *dev);
+
+	/* OK this is complementar to data_poll_hard_stop */
+	void (*data_hard_resume)(struct net_device *dev);
+
+	/* ask to the driver to retune the radio .
+	 * This function can sleep. the driver should ensure
+	 * the radio has been swithced before return.
+	 */
+	void (*set_chan)(struct net_device *dev,short ch);
+
+	/* These are not used if the ieee stack takes care of
+	 * scanning (IEEE_SOFTMAC_SCAN feature set).
+	 * In this case only the set_chan is used.
+	 *
+	 * The syncro version is similar to the start_scan but
+	 * does not return until all channels has been scanned.
+	 * this is called in user context and should sleep,
+	 * it is called in a work_queue when swithcing to ad-hoc mode
+	 * or in behalf of iwlist scan when the card is associated
+	 * and root user ask for a scan.
+	 * the fucntion stop_scan should stop both the syncro and
+	 * background scanning and can sleep.
+	 * The fucntion start_scan should initiate the background
+	 * scanning and can't sleep.
+	 */
+	void (*scan_syncro)(struct net_device *dev);
+	void (*start_scan)(struct net_device *dev);
+	void (*stop_scan)(struct net_device *dev);
+
+	/* indicate the driver that the link state is changed
+	 * for example it may indicate the card is associated now.
+	 * Driver might be interested in this to apply RX filter
+	 * rules or simply light the LINK led
+	 */
+	void (*link_change)(struct net_device *dev);
+
+	/* these two function indicates to the HW when to start
+	 * and stop to send beacons. This is used when the
+	 * IEEE_SOFTMAC_BEACONS is not set. For now the
+	 * stop_send_bacons is NOT guaranteed to be called only
+	 * after start_send_beacons.
+	 */
+	void (*start_send_beacons) (struct net_device *dev);
+	void (*stop_send_beacons) (struct net_device *dev);
+
+	/* power save mode related */
+	void (*sta_wake_up) (struct net_device *dev);
+//	void (*ps_request_tx_ack) (struct net_device *dev);
+	void (*enter_sleep_state) (struct net_device *dev, u32 th, u32 tl);
+	short (*ps_is_queue_empty) (struct net_device *dev);
+#if 0
+	/* Typical STA methods */
+        int (*handle_auth) (struct net_device * dev,
+                            struct ieee80211_auth * auth);
+        int (*handle_deauth) (struct net_device * dev,
+                              struct ieee80211_deauth * auth);
+        int (*handle_action) (struct net_device * dev,
+                              struct ieee80211_action * action,
+                              struct ieee80211_rx_stats * stats);
+        int (*handle_disassoc) (struct net_device * dev,
+                                struct ieee80211_disassoc * assoc);
+#endif
+        int (*handle_beacon) (struct net_device * dev, struct ieee80211_beacon * beacon, struct ieee80211_network * network);
+#if 0
+        int (*handle_probe_response) (struct net_device * dev,
+                                      struct ieee80211_probe_response * resp,
+                                      struct ieee80211_network * network);
+        int (*handle_probe_request) (struct net_device * dev,
+                                     struct ieee80211_probe_request * req,
+                                     struct ieee80211_rx_stats * stats);
+#endif
+        int (*handle_assoc_response) (struct net_device * dev, struct ieee80211_assoc_response_frame * resp, struct ieee80211_network * network);
+
+#if 0
+        /* Typical AP methods */
+        int (*handle_assoc_request) (struct net_device * dev);
+        int (*handle_reassoc_request) (struct net_device * dev,
+                                       struct ieee80211_reassoc_request * req);
+#endif
+
+	/* check whether Tx hw resouce available */
+	short (*check_nic_enough_desc)(struct net_device *dev, int queue_index);
+	//added by wb for HT related
+//	void (*SwChnlByTimerHandler)(struct net_device *dev, int channel);
+	void (*SetBWModeHandler)(struct net_device *dev, HT_CHANNEL_WIDTH Bandwidth, HT_EXTCHNL_OFFSET Offset);
+//	void (*UpdateHalRATRTableHandler)(struct net_device* dev, u8* pMcsRate);
+	bool (*GetNmodeSupportBySecCfg)(struct net_device* dev);
+	void (*SetWirelessMode)(struct net_device* dev, u8 wireless_mode);
+	bool (*GetHalfNmodeSupportByAPsHandler)(struct net_device* dev);
+	bool (*is_ap_in_wep_tkip)(struct net_device* dev);
+	void (*InitialGainHandler)(struct net_device *dev, u8 Operation);
+	bool (*SetFwCmdHandler)(struct net_device *dev,	FW_CMD_IO_TYPE		FwCmdIO);
+	void (*LedControlHandler)(struct net_device * dev, LED_CTL_MODE LedAction);
+	/* This must be the last item so that it points to the data
+	 * allocated beyond this structure by alloc_ieee80211 */
+	u8 priv[0];
+};
+
+#define IEEE_A            (1<<0)
+#define IEEE_B            (1<<1)
+#define IEEE_G            (1<<2)
+#define IEEE_N_24G 		  (1<<4)
+#define	IEEE_N_5G		  (1<<5)
+#define IEEE_MODE_MASK    (IEEE_A|IEEE_B|IEEE_G)
+
+/* Generate a 802.11 header */
+
+/* Uses the channel change callback directly
+ * instead of [start/stop] scan callbacks
+ */
+#define IEEE_SOFTMAC_SCAN (1<<2)
+
+/* Perform authentication and association handshake */
+#define IEEE_SOFTMAC_ASSOCIATE (1<<3)
+
+/* Generate probe requests */
+#define IEEE_SOFTMAC_PROBERQ (1<<4)
+
+/* Generate respones to probe requests */
+#define IEEE_SOFTMAC_PROBERS (1<<5)
+
+/* The ieee802.11 stack will manages the netif queue
+ * wake/stop for the driver, taking care of 802.11
+ * fragmentation. See softmac.c for details. */
+#define IEEE_SOFTMAC_TX_QUEUE (1<<7)
+
+/* Uses only the softmac_data_hard_start_xmit
+ * even for TX management frames.
+ */
+#define IEEE_SOFTMAC_SINGLE_QUEUE (1<<8)
+
+/* Generate beacons.  The stack will enqueue beacons
+ * to the card
+ */
+#define IEEE_SOFTMAC_BEACONS (1<<6)
+
+static inline void *ieee80211_priv(struct net_device *dev)
+{
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	return ((struct ieee80211_device *)netdev_priv(dev))->priv;
+#else
+	return ((struct ieee80211_device *)dev->priv)->priv;
+#endif
+}
+
+extern inline int ieee80211_is_empty_essid(const char *essid, int essid_len)
+{
+	/* Single white space is for Linksys APs */
+	if (essid_len == 1 && essid[0] == ' ')
+		return 1;
+
+	/* Otherwise, if the entire essid is 0, we assume it is hidden */
+	while (essid_len) {
+		essid_len--;
+		if (essid[essid_len] != '\0')
+			return 0;
+	}
+
+	return 1;
+}
+
+extern inline int ieee80211_is_valid_mode(struct ieee80211_device *ieee, int mode)
+{
+	/*
+	 * It is possible for both access points and our device to support
+	 * combinations of modes, so as long as there is one valid combination
+	 * of ap/device supported modes, then return success
+	 *
+	 */
+	if ((mode & IEEE_A) &&
+	    (ieee->modulation & IEEE80211_OFDM_MODULATION) &&
+	    (ieee->freq_band & IEEE80211_52GHZ_BAND))
+		return 1;
+
+	if ((mode & IEEE_G) &&
+	    (ieee->modulation & IEEE80211_OFDM_MODULATION) &&
+	    (ieee->freq_band & IEEE80211_24GHZ_BAND))
+		return 1;
+
+	if ((mode & IEEE_B) &&
+	    (ieee->modulation & IEEE80211_CCK_MODULATION) &&
+	    (ieee->freq_band & IEEE80211_24GHZ_BAND))
+		return 1;
+
+	return 0;
+}
+
+extern inline int ieee80211_get_hdrlen(u16 fc)
+{
+	int hdrlen = IEEE80211_3ADDR_LEN;
+
+	switch (WLAN_FC_GET_TYPE(fc)) {
+	case IEEE80211_FTYPE_DATA:
+		if ((fc & IEEE80211_FCTL_FROMDS) && (fc & IEEE80211_FCTL_TODS))
+			hdrlen = IEEE80211_4ADDR_LEN; /* Addr4 */
+		if(IEEE80211_QOS_HAS_SEQ(fc))
+			hdrlen += 2; /* QOS ctrl*/
+		break;
+	case IEEE80211_FTYPE_CTL:
+		switch (WLAN_FC_GET_STYPE(fc)) {
+		case IEEE80211_STYPE_CTS:
+		case IEEE80211_STYPE_ACK:
+			hdrlen = IEEE80211_1ADDR_LEN;
+			break;
+		default:
+			hdrlen = IEEE80211_2ADDR_LEN;
+			break;
+		}
+		break;
+	}
+
+	return hdrlen;
+}
+
+static inline u8 *ieee80211_get_payload(struct ieee80211_hdr *hdr)
+{
+        switch (ieee80211_get_hdrlen(le16_to_cpu(hdr->frame_ctl))) {
+        case IEEE80211_1ADDR_LEN:
+                return ((struct ieee80211_hdr_1addr *)hdr)->payload;
+        case IEEE80211_2ADDR_LEN:
+                return ((struct ieee80211_hdr_2addr *)hdr)->payload;
+        case IEEE80211_3ADDR_LEN:
+                return ((struct ieee80211_hdr_3addr *)hdr)->payload;
+        case IEEE80211_4ADDR_LEN:
+                return ((struct ieee80211_hdr_4addr *)hdr)->payload;
+        }
+        return NULL;
+}
+
+static inline int ieee80211_is_ofdm_rate(u8 rate)
+{
+        switch (rate & ~IEEE80211_BASIC_RATE_MASK) {
+        case IEEE80211_OFDM_RATE_6MB:
+        case IEEE80211_OFDM_RATE_9MB:
+        case IEEE80211_OFDM_RATE_12MB:
+        case IEEE80211_OFDM_RATE_18MB:
+        case IEEE80211_OFDM_RATE_24MB:
+        case IEEE80211_OFDM_RATE_36MB:
+        case IEEE80211_OFDM_RATE_48MB:
+        case IEEE80211_OFDM_RATE_54MB:
+                return 1;
+        }
+        return 0;
+}
+
+static inline int ieee80211_is_cck_rate(u8 rate)
+{
+        switch (rate & ~IEEE80211_BASIC_RATE_MASK) {
+        case IEEE80211_CCK_RATE_1MB:
+        case IEEE80211_CCK_RATE_2MB:
+        case IEEE80211_CCK_RATE_5MB:
+        case IEEE80211_CCK_RATE_11MB:
+                return 1;
+        }
+        return 0;
+}
+
+
+/* ieee80211.c */
+extern void free_ieee80211(struct net_device *dev);
+extern struct net_device *alloc_ieee80211(int sizeof_priv);
+
+extern int ieee80211_set_encryption(struct ieee80211_device *ieee);
+
+/* ieee80211_tx.c */
+
+extern int ieee80211_encrypt_fragment(
+	struct ieee80211_device *ieee,
+	struct sk_buff *frag,
+	int hdr_len);
+
+extern int ieee80211_xmit(struct sk_buff *skb,
+			  struct net_device *dev);
+extern void ieee80211_txb_free(struct ieee80211_txb *);
+
+
+/* ieee80211_rx.c */
+extern int ieee80211_rx(struct ieee80211_device *ieee, struct sk_buff *skb,
+			struct ieee80211_rx_stats *rx_stats);
+extern void ieee80211_rx_mgt(struct ieee80211_device *ieee,
+			     struct ieee80211_hdr_4addr *header,
+			     struct ieee80211_rx_stats *stats);
+
+/* ieee80211_wx.c */
+extern int ieee80211_wx_get_scan(struct ieee80211_device *ieee,
+				 struct iw_request_info *info,
+				 union iwreq_data *wrqu, char *key);
+extern int ieee80211_wx_set_encode(struct ieee80211_device *ieee,
+				   struct iw_request_info *info,
+				   union iwreq_data *wrqu, char *key);
+extern int ieee80211_wx_get_encode(struct ieee80211_device *ieee,
+				   struct iw_request_info *info,
+				   union iwreq_data *wrqu, char *key);
+#if WIRELESS_EXT >= 18
+extern int ieee80211_wx_get_encode_ext(struct ieee80211_device *ieee,
+                            struct iw_request_info *info,
+                            union iwreq_data* wrqu, char *extra);
+extern int ieee80211_wx_set_encode_ext(struct ieee80211_device *ieee,
+                            struct iw_request_info *info,
+                            union iwreq_data* wrqu, char *extra);
+extern int ieee80211_wx_set_auth(struct ieee80211_device *ieee,
+                               struct iw_request_info *info,
+                               struct iw_param *data, char *extra);
+extern int ieee80211_wx_set_mlme(struct ieee80211_device *ieee,
+                               struct iw_request_info *info,
+                               union iwreq_data *wrqu, char *extra);
+#endif
+extern int ieee80211_wx_set_gen_ie(struct ieee80211_device *ieee, u8 *ie, size_t len);
+
+/* ieee80211_softmac.c */
+extern short ieee80211_is_54g(struct ieee80211_network net);
+extern short ieee80211_is_shortslot(struct ieee80211_network net);
+extern int ieee80211_rx_frame_softmac(struct ieee80211_device *ieee, struct sk_buff *skb,
+			struct ieee80211_rx_stats *rx_stats, u16 type,
+			u16 stype);
+extern void ieee80211_softmac_new_net(struct ieee80211_device *ieee, struct ieee80211_network *net);
+
+void SendDisassociation(struct ieee80211_device *ieee, u8* asSta, u8 asRsn);
+extern void ieee80211_softmac_xmit(struct ieee80211_txb *txb, struct ieee80211_device *ieee);
+
+extern void ieee80211_stop_send_beacons(struct ieee80211_device *ieee);
+extern void notify_wx_assoc_event(struct ieee80211_device *ieee);
+extern void ieee80211_softmac_check_all_nets(struct ieee80211_device *ieee);
+extern void ieee80211_start_bss(struct ieee80211_device *ieee);
+extern void ieee80211_start_master_bss(struct ieee80211_device *ieee);
+extern void ieee80211_start_ibss(struct ieee80211_device *ieee);
+extern void ieee80211_softmac_init(struct ieee80211_device *ieee);
+extern void ieee80211_softmac_free(struct ieee80211_device *ieee);
+extern void ieee80211_associate_abort(struct ieee80211_device *ieee);
+extern void ieee80211_disassociate(struct ieee80211_device *ieee);
+extern void ieee80211_stop_scan(struct ieee80211_device *ieee);
+extern void ieee80211_start_scan_syncro(struct ieee80211_device *ieee);
+extern void ieee80211_check_all_nets(struct ieee80211_device *ieee);
+extern void ieee80211_start_protocol(struct ieee80211_device *ieee);
+extern void ieee80211_stop_protocol(struct ieee80211_device *ieee);
+extern void ieee80211_softmac_start_protocol(struct ieee80211_device *ieee);
+extern void ieee80211_softmac_stop_protocol(struct ieee80211_device *ieee);
+extern void ieee80211_reset_queue(struct ieee80211_device *ieee);
+extern void ieee80211_wake_queue(struct ieee80211_device *ieee);
+extern void ieee80211_stop_queue(struct ieee80211_device *ieee);
+extern struct sk_buff *ieee80211_get_beacon(struct ieee80211_device *ieee);
+extern void ieee80211_start_send_beacons(struct ieee80211_device *ieee);
+extern void ieee80211_stop_send_beacons(struct ieee80211_device *ieee);
+extern int ieee80211_wpa_supplicant_ioctl(struct ieee80211_device *ieee, struct iw_point *p);
+extern void notify_wx_assoc_event(struct ieee80211_device *ieee);
+extern void ieee80211_ps_tx_ack(struct ieee80211_device *ieee, short success);
+
+extern void softmac_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee);
+
+/* ieee80211_crypt_ccmp&tkip&wep.c */
+extern void ieee80211_tkip_null(void);
+extern void ieee80211_wep_null(void);
+extern void ieee80211_ccmp_null(void);
+
+/* ieee80211_softmac_wx.c */
+
+extern int ieee80211_wx_get_wap(struct ieee80211_device *ieee,
+			    struct iw_request_info *info,
+			    union iwreq_data *wrqu, char *ext);
+
+extern int ieee80211_wx_set_wap(struct ieee80211_device *ieee,
+			 struct iw_request_info *info,
+			 union iwreq_data *awrq,
+			 char *extra);
+
+extern int ieee80211_wx_get_essid(struct ieee80211_device *ieee, struct iw_request_info *a,union iwreq_data *wrqu,char *b);
+
+extern int ieee80211_wx_set_rate(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_get_rate(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_set_mode(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b);
+
+extern int ieee80211_wx_set_scan(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b);
+
+extern int ieee80211_wx_set_essid(struct ieee80211_device *ieee,
+			      struct iw_request_info *a,
+			      union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_get_mode(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b);
+
+extern int ieee80211_wx_set_freq(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b);
+
+extern int ieee80211_wx_get_freq(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b);
+
+//extern void ieee80211_wx_sync_scan_wq(struct ieee80211_device *ieee);
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern void ieee80211_wx_sync_scan_wq(struct work_struct *work);
+#else
+ extern void ieee80211_wx_sync_scan_wq(struct ieee80211_device *ieee);
+#endif
+
+
+extern int ieee80211_wx_set_rawtx(struct ieee80211_device *ieee,
+			       struct iw_request_info *info,
+			       union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_get_name(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_set_power(struct ieee80211_device *ieee,
+				 struct iw_request_info *info,
+				 union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_get_power(struct ieee80211_device *ieee,
+				 struct iw_request_info *info,
+				 union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_set_rts(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra);
+
+extern int ieee80211_wx_get_rts(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra);
+//HT
+#define MAX_RECEIVE_BUFFER_SIZE 9100  //
+extern void HTDebugHTCapability(u8* CapIE, u8* TitleString );
+extern void HTDebugHTInfo(u8*  InfoIE, u8* TitleString);
+
+void HTSetConnectBwMode(struct ieee80211_device* ieee, HT_CHANNEL_WIDTH Bandwidth, HT_EXTCHNL_OFFSET    Offset);
+extern void HTUpdateDefaultSetting(struct ieee80211_device* ieee);
+extern void HTConstructCapabilityElement(struct ieee80211_device* ieee, u8* posHTCap, u8* len, u8 isEncrypt);
+extern void HTConstructInfoElement(struct ieee80211_device* ieee, u8* posHTInfo, u8* len, u8 isEncrypt);
+extern void HTConstructRT2RTAggElement(struct ieee80211_device* ieee, u8* posRT2RTAgg, u8* len);
+extern void HTOnAssocRsp(struct ieee80211_device *ieee);
+extern void HTInitializeHTInfo(struct ieee80211_device* ieee);
+extern void HTInitializeBssDesc(PBSS_HT pBssHT);
+extern void HTResetSelfAndSavePeerSetting(struct ieee80211_device* ieee, struct ieee80211_network * pNetwork);
+extern void HTUpdateSelfAndPeerSetting(struct ieee80211_device* ieee,   struct ieee80211_network * pNetwork);
+extern u8 HTGetHighestMCSRate(struct ieee80211_device* ieee, u8* pMCSRateSet, u8* pMCSFilter);
+extern u8 MCS_FILTER_ALL[];
+extern u16 MCS_DATA_RATE[2][2][77] ;
+extern u8 HTCCheck(struct ieee80211_device* ieee, u8*   pFrame);
+//extern void HTSetConnectBwModeCallback(unsigned long data);
+extern void HTResetIOTSetting(PRT_HIGH_THROUGHPUT  pHTInfo);
+extern bool IsHTHalfNmodeAPs(struct ieee80211_device* ieee);
+extern u16 HTHalfMcsToDataRate(struct ieee80211_device* ieee,  u8      nMcsRate);
+extern u16 HTMcsToDataRate( struct ieee80211_device* ieee, u8 nMcsRate);
+extern u16  TxCountToDataRate( struct ieee80211_device* ieee, u8 nDataRate);
+//function in BAPROC.c
+extern int ieee80211_rx_ADDBAReq( struct ieee80211_device* ieee, struct sk_buff *skb);
+extern int ieee80211_rx_ADDBARsp( struct ieee80211_device* ieee, struct sk_buff *skb);
+extern int ieee80211_rx_DELBA(struct ieee80211_device* ieee,struct sk_buff *skb);
+extern void TsInitAddBA( struct ieee80211_device* ieee, PTX_TS_RECORD   pTS, u8 Policy, u8 bOverwritePending);
+extern void TsInitDelBA( struct ieee80211_device* ieee, PTS_COMMON_INFO pTsCommonInfo, TR_SELECT TxRxSelect);
+extern void BaSetupTimeOut(unsigned long data);
+extern void TxBaInactTimeout(unsigned long data);
+extern void RxBaInactTimeout(unsigned long data);
+extern void ResetBaEntry( PBA_RECORD pBA);
+//function in TS.c
+extern bool GetTs(
+        struct ieee80211_device*        ieee,
+        PTS_COMMON_INFO                 *ppTS,
+        u8*                             Addr,
+        u8                              TID,
+        TR_SELECT                       TxRxSelect,  //Rx:1, Tx:0
+        bool                            bAddNewTs
+        );
+extern void TSInitialize(struct ieee80211_device *ieee);
+extern  void TsStartAddBaProcess(struct ieee80211_device* ieee, PTX_TS_RECORD   pTxTS);
+extern void RemovePeerTS(struct ieee80211_device* ieee, u8* Addr);
+extern void RemoveAllTS(struct ieee80211_device* ieee);
+void ieee80211_softmac_scan_syncro(struct ieee80211_device *ieee);
+
+extern const long ieee80211_wlan_frequencies[];
+
+extern inline void ieee80211_increment_scans(struct ieee80211_device *ieee)
+{
+	ieee->scans++;
+}
+
+extern inline int ieee80211_get_scans(struct ieee80211_device *ieee)
+{
+	return ieee->scans;
+}
+
+static inline const char *escape_essid(const char *essid, u8 essid_len) {
+	static char escaped[IW_ESSID_MAX_SIZE * 2 + 1];
+	const char *s = essid;
+	char *d = escaped;
+
+	if (ieee80211_is_empty_essid(essid, essid_len)) {
+		memcpy(escaped, "<hidden>", sizeof("<hidden>"));
+		return escaped;
+	}
+
+	essid_len = min(essid_len, (u8)IW_ESSID_MAX_SIZE);
+	while (essid_len--) {
+		if (*s == '\0') {
+			*d++ = '\\';
+			*d++ = '0';
+			s++;
+		} else {
+			*d++ = *s++;
+		}
+	}
+	*d = '\0';
+	return escaped;
+}
+
+/* For the function is more related to hardware setting, it's better to use the
+ * ieee handler to refer to it.
+ */
+extern short check_nic_enough_desc(struct net_device *dev, int queue_index);
+extern int ieee80211_data_xmit(struct sk_buff *skb, struct net_device *dev);
+extern int ieee80211_parse_info_param(struct ieee80211_device *ieee,
+		struct ieee80211_info_element *info_element,
+		u16 length,
+		struct ieee80211_network *network,
+		struct ieee80211_rx_stats *stats);
+
+void ieee80211_indicate_packets(struct ieee80211_device *ieee, struct ieee80211_rxb** prxbIndicateArray,u8  index);
+#define RT_ASOC_RETRY_LIMIT	5
+#endif /* IEEE80211_H */
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt.c b/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt.c
new file mode 100644
index 0000000..199ee16
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt.c
@@ -0,0 +1,273 @@
+/*
+ * Host AP crypto routines
+ *
+ * Copyright (c) 2002-2003, Jouni Malinen <jkmaline@cc.hut.fi>
+ * Portions Copyright (C) 2004, Intel Corporation <jketreno@linux.intel.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. See README and COPYING for
+ * more details.
+ *
+ */
+
+//#include <linux/config.h>
+#include <linux/version.h>
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/slab.h>
+#include <asm/string.h>
+#include <asm/errno.h>
+
+#include "ieee80211.h"
+
+MODULE_AUTHOR("Jouni Malinen");
+MODULE_DESCRIPTION("HostAP crypto");
+MODULE_LICENSE("GPL");
+
+struct ieee80211_crypto_alg {
+	struct list_head list;
+	struct ieee80211_crypto_ops *ops;
+};
+
+
+struct ieee80211_crypto {
+	struct list_head algs;
+	spinlock_t lock;
+};
+
+static struct ieee80211_crypto *hcrypt;
+
+void ieee80211_crypt_deinit_entries(struct ieee80211_device *ieee,
+					   int force)
+{
+	struct list_head *ptr, *n;
+	struct ieee80211_crypt_data *entry;
+
+	for (ptr = ieee->crypt_deinit_list.next, n = ptr->next;
+	     ptr != &ieee->crypt_deinit_list; ptr = n, n = ptr->next) {
+		entry = list_entry(ptr, struct ieee80211_crypt_data, list);
+
+		if (atomic_read(&entry->refcnt) != 0 && !force)
+			continue;
+
+		list_del(ptr);
+
+		if (entry->ops) {
+			entry->ops->deinit(entry->priv);
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
+			module_put(entry->ops->owner);
+#else
+			__MOD_DEC_USE_COUNT(entry->ops->owner);
+#endif
+		}
+		kfree(entry);
+	}
+}
+
+void ieee80211_crypt_deinit_handler(unsigned long data)
+{
+	struct ieee80211_device *ieee = (struct ieee80211_device *)data;
+	unsigned long flags;
+
+	spin_lock_irqsave(&ieee->lock, flags);
+	ieee80211_crypt_deinit_entries(ieee, 0);
+	if (!list_empty(&ieee->crypt_deinit_list)) {
+		printk(KERN_DEBUG "%s: entries remaining in delayed crypt "
+		       "deletion list\n", ieee->dev->name);
+		ieee->crypt_deinit_timer.expires = jiffies + HZ;
+		add_timer(&ieee->crypt_deinit_timer);
+	}
+	spin_unlock_irqrestore(&ieee->lock, flags);
+
+}
+
+void ieee80211_crypt_delayed_deinit(struct ieee80211_device *ieee,
+				    struct ieee80211_crypt_data **crypt)
+{
+	struct ieee80211_crypt_data *tmp;
+	unsigned long flags;
+
+	if (*crypt == NULL)
+		return;
+
+	tmp = *crypt;
+	*crypt = NULL;
+
+	/* must not run ops->deinit() while there may be pending encrypt or
+	 * decrypt operations. Use a list of delayed deinits to avoid needing
+	 * locking. */
+
+	spin_lock_irqsave(&ieee->lock, flags);
+	list_add(&tmp->list, &ieee->crypt_deinit_list);
+	if (!timer_pending(&ieee->crypt_deinit_timer)) {
+		ieee->crypt_deinit_timer.expires = jiffies + HZ;
+		add_timer(&ieee->crypt_deinit_timer);
+	}
+	spin_unlock_irqrestore(&ieee->lock, flags);
+}
+
+int ieee80211_register_crypto_ops(struct ieee80211_crypto_ops *ops)
+{
+	unsigned long flags;
+	struct ieee80211_crypto_alg *alg;
+
+	if (hcrypt == NULL)
+		return -1;
+
+	alg = kmalloc(sizeof(*alg), GFP_KERNEL);
+	if (alg == NULL)
+		return -ENOMEM;
+
+	memset(alg, 0, sizeof(*alg));
+	alg->ops = ops;
+
+	spin_lock_irqsave(&hcrypt->lock, flags);
+	list_add(&alg->list, &hcrypt->algs);
+	spin_unlock_irqrestore(&hcrypt->lock, flags);
+
+	printk(KERN_DEBUG "ieee80211_crypt: registered algorithm '%s'\n",
+	       ops->name);
+
+	return 0;
+}
+
+int ieee80211_unregister_crypto_ops(struct ieee80211_crypto_ops *ops)
+{
+	unsigned long flags;
+	struct list_head *ptr;
+	struct ieee80211_crypto_alg *del_alg = NULL;
+
+	if (hcrypt == NULL)
+		return -1;
+
+	spin_lock_irqsave(&hcrypt->lock, flags);
+	for (ptr = hcrypt->algs.next; ptr != &hcrypt->algs; ptr = ptr->next) {
+		struct ieee80211_crypto_alg *alg =
+			(struct ieee80211_crypto_alg *) ptr;
+		if (alg->ops == ops) {
+			list_del(&alg->list);
+			del_alg = alg;
+			break;
+		}
+	}
+	spin_unlock_irqrestore(&hcrypt->lock, flags);
+
+	if (del_alg) {
+		printk(KERN_DEBUG "ieee80211_crypt: unregistered algorithm "
+		       "'%s'\n", ops->name);
+		kfree(del_alg);
+	}
+
+	return del_alg ? 0 : -1;
+}
+
+
+struct ieee80211_crypto_ops * ieee80211_get_crypto_ops(const char *name)
+{
+	unsigned long flags;
+	struct list_head *ptr;
+	struct ieee80211_crypto_alg *found_alg = NULL;
+
+	if (hcrypt == NULL)
+		return NULL;
+
+	spin_lock_irqsave(&hcrypt->lock, flags);
+	for (ptr = hcrypt->algs.next; ptr != &hcrypt->algs; ptr = ptr->next) {
+		struct ieee80211_crypto_alg *alg =
+			(struct ieee80211_crypto_alg *) ptr;
+		if (strcmp(alg->ops->name, name) == 0) {
+			found_alg = alg;
+			break;
+		}
+	}
+	spin_unlock_irqrestore(&hcrypt->lock, flags);
+
+	if (found_alg)
+		return found_alg->ops;
+	else
+		return NULL;
+}
+
+
+static void * ieee80211_crypt_null_init(int keyidx) { return (void *) 1; }
+static void ieee80211_crypt_null_deinit(void *priv) {}
+
+static struct ieee80211_crypto_ops ieee80211_crypt_null = {
+	.name			= "NULL",
+	.init			= ieee80211_crypt_null_init,
+	.deinit			= ieee80211_crypt_null_deinit,
+	.encrypt_mpdu		= NULL,
+	.decrypt_mpdu		= NULL,
+	.encrypt_msdu		= NULL,
+	.decrypt_msdu		= NULL,
+	.set_key		= NULL,
+	.get_key		= NULL,
+	.extra_prefix_len	= 0,
+	.extra_postfix_len	= 0,
+	.owner			= THIS_MODULE,
+};
+
+
+static int __init ieee80211_crypto_init(void)
+{
+	int ret = -ENOMEM;
+
+	hcrypt = kmalloc(sizeof(*hcrypt), GFP_KERNEL);
+	if (!hcrypt)
+		goto out;
+
+	memset(hcrypt, 0, sizeof(*hcrypt));
+	INIT_LIST_HEAD(&hcrypt->algs);
+	spin_lock_init(&hcrypt->lock);
+
+	ret = ieee80211_register_crypto_ops(&ieee80211_crypt_null);
+	if (ret < 0) {
+		kfree(hcrypt);
+		hcrypt = NULL;
+	}
+out:
+	return ret;
+}
+
+
+static void __exit ieee80211_crypto_deinit(void)
+{
+	struct list_head *ptr, *n;
+
+	if (hcrypt == NULL)
+		return;
+
+	for (ptr = hcrypt->algs.next, n = ptr->next; ptr != &hcrypt->algs;
+	     ptr = n, n = ptr->next) {
+		struct ieee80211_crypto_alg *alg =
+			(struct ieee80211_crypto_alg *) ptr;
+		list_del(ptr);
+		printk(KERN_DEBUG "ieee80211_crypt: unregistered algorithm "
+		       "'%s' (deinit)\n", alg->ops->name);
+		kfree(alg);
+	}
+
+	kfree(hcrypt);
+}
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+EXPORT_SYMBOL(ieee80211_crypt_deinit_entries);
+EXPORT_SYMBOL(ieee80211_crypt_deinit_handler);
+EXPORT_SYMBOL(ieee80211_crypt_delayed_deinit);
+
+EXPORT_SYMBOL(ieee80211_register_crypto_ops);
+EXPORT_SYMBOL(ieee80211_unregister_crypto_ops);
+EXPORT_SYMBOL(ieee80211_get_crypto_ops);
+#else
+EXPORT_SYMBOL_NOVERS(ieee80211_crypt_deinit_entries);
+EXPORT_SYMBOL_NOVERS(ieee80211_crypt_deinit_handler);
+EXPORT_SYMBOL_NOVERS(ieee80211_crypt_delayed_deinit);
+
+EXPORT_SYMBOL_NOVERS(ieee80211_register_crypto_ops);
+EXPORT_SYMBOL_NOVERS(ieee80211_unregister_crypto_ops);
+EXPORT_SYMBOL_NOVERS(ieee80211_get_crypto_ops);
+#endif
+
+module_init(ieee80211_crypto_init);
+module_exit(ieee80211_crypto_deinit);
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt.h b/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt.h
new file mode 100644
index 0000000..a84df4b
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt.h
@@ -0,0 +1,93 @@
+/*
+ * Original code based on Host AP (software wireless LAN access point) driver
+ * for Intersil Prism2/2.5/3.
+ *
+ * Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen
+ * <jkmaline@cc.hut.fi>
+ * Copyright (c) 2002-2003, Jouni Malinen <jkmaline@cc.hut.fi>
+ *
+ * Adaption to a generic IEEE 802.11 stack by James Ketrenos
+ * <jketreno@linux.intel.com>
+ *
+ * Copyright (c) 2004, Intel Corporation
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. See README and COPYING for
+ * more details.
+ */
+
+/*
+ * This file defines the interface to the ieee80211 crypto module.
+ */
+#ifndef IEEE80211_CRYPT_H
+#define IEEE80211_CRYPT_H
+
+#include <linux/skbuff.h>
+
+struct ieee80211_crypto_ops {
+	const char *name;
+
+	/* init new crypto context (e.g., allocate private data space,
+	 * select IV, etc.); returns NULL on failure or pointer to allocated
+	 * private data on success */
+	void * (*init)(int keyidx);
+
+	/* deinitialize crypto context and free allocated private data */
+	void (*deinit)(void *priv);
+
+	/* encrypt/decrypt return < 0 on error or >= 0 on success. The return
+	 * value from decrypt_mpdu is passed as the keyidx value for
+	 * decrypt_msdu. skb must have enough head and tail room for the
+	 * encryption; if not, error will be returned; these functions are
+	 * called for all MPDUs (i.e., fragments).
+	 */
+	int (*encrypt_mpdu)(struct sk_buff *skb, int hdr_len, void *priv);
+	int (*decrypt_mpdu)(struct sk_buff *skb, int hdr_len, void *priv);
+
+	/* These functions are called for full MSDUs, i.e. full frames.
+	 * These can be NULL if full MSDU operations are not needed. */
+	int (*encrypt_msdu)(struct sk_buff *skb, int hdr_len, void *priv);
+	int (*decrypt_msdu)(struct sk_buff *skb, int keyidx, int hdr_len,
+			    void *priv);
+
+	int (*set_key)(void *key, int len, u8 *seq, void *priv);
+	int (*get_key)(void *key, int len, u8 *seq, void *priv);
+
+	/* procfs handler for printing out key information and possible
+	 * statistics */
+	char * (*print_stats)(char *p, void *priv);
+
+	/* maximum number of bytes added by encryption; encrypt buf is
+	 * allocated with extra_prefix_len bytes, copy of in_buf, and
+	 * extra_postfix_len; encrypt need not use all this space, but
+	 * the result must start at the beginning of the buffer and correct
+	 * length must be returned */
+	int extra_prefix_len, extra_postfix_len;
+
+	struct module *owner;
+};
+
+struct ieee80211_crypt_data {
+	struct list_head list; /* delayed deletion list */
+	struct ieee80211_crypto_ops *ops;
+	void *priv;
+	atomic_t refcnt;
+};
+
+int ieee80211_register_crypto_ops(struct ieee80211_crypto_ops *ops);
+int ieee80211_unregister_crypto_ops(struct ieee80211_crypto_ops *ops);
+struct ieee80211_crypto_ops * ieee80211_get_crypto_ops(const char *name);
+void ieee80211_crypt_deinit_entries(struct ieee80211_device *, int);
+void ieee80211_crypt_deinit_handler(unsigned long);
+void ieee80211_crypt_delayed_deinit(struct ieee80211_device *ieee,
+				    struct ieee80211_crypt_data **crypt);
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+#define offset_in_page(p) ((unsigned long)(p) & ~PAGE_MASK)
+#endif
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,4,31))
+#define crypto_alloc_tfm crypto_alloc_tfm_rsl
+#define crypto_free_tfm crypto_free_tfm_rsl
+#endif
+
+#endif
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt_ccmp.c b/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt_ccmp.c
new file mode 100644
index 0000000..a86c26e
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt_ccmp.c
@@ -0,0 +1,534 @@
+/*
+ * Host AP crypt: host-based CCMP encryption implementation for Host AP driver
+ *
+ * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. See README and COPYING for
+ * more details.
+ */
+
+//#include <linux/config.h>
+#include <linux/version.h>
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/slab.h>
+#include <linux/random.h>
+#include <linux/skbuff.h>
+#include <linux/netdevice.h>
+#include <linux/if_ether.h>
+#include <linux/if_arp.h>
+#include <asm/string.h>
+#include <linux/wireless.h>
+
+#include "ieee80211.h"
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+#include "rtl_crypto.h"
+#else
+#include <linux/crypto.h>
+#endif
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20)
+    #include <asm/scatterlist.h>
+#else
+    #include <linux/scatterlist.h>
+#endif
+//#include <asm/scatterlist.h>
+
+MODULE_AUTHOR("Jouni Malinen");
+MODULE_DESCRIPTION("Host AP crypt: CCMP");
+MODULE_LICENSE("GPL");
+
+#ifndef OPENSUSE_SLED
+#define OPENSUSE_SLED 0
+#endif
+
+#define AES_BLOCK_LEN 16
+#define CCMP_HDR_LEN 8
+#define CCMP_MIC_LEN 8
+#define CCMP_TK_LEN 16
+#define CCMP_PN_LEN 6
+
+struct ieee80211_ccmp_data {
+	u8 key[CCMP_TK_LEN];
+	int key_set;
+
+	u8 tx_pn[CCMP_PN_LEN];
+	u8 rx_pn[CCMP_PN_LEN];
+
+	u32 dot11RSNAStatsCCMPFormatErrors;
+	u32 dot11RSNAStatsCCMPReplays;
+	u32 dot11RSNAStatsCCMPDecryptErrors;
+
+	int key_idx;
+
+	struct crypto_tfm *tfm;
+
+	/* scratch buffers for virt_to_page() (crypto API) */
+	u8 tx_b0[AES_BLOCK_LEN], tx_b[AES_BLOCK_LEN],
+		tx_e[AES_BLOCK_LEN], tx_s0[AES_BLOCK_LEN];
+	u8 rx_b0[AES_BLOCK_LEN], rx_b[AES_BLOCK_LEN], rx_a[AES_BLOCK_LEN];
+};
+
+void ieee80211_ccmp_aes_encrypt(struct crypto_tfm *tfm,
+			     const u8 pt[16], u8 ct[16])
+{
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	struct scatterlist src, dst;
+
+	src.page = virt_to_page(pt);
+	src.offset = offset_in_page(pt);
+	src.length = AES_BLOCK_LEN;
+
+	dst.page = virt_to_page(ct);
+	dst.offset = offset_in_page(ct);
+	dst.length = AES_BLOCK_LEN;
+
+	crypto_cipher_encrypt(tfm, &dst, &src, AES_BLOCK_LEN);
+#else
+	crypto_cipher_encrypt_one((void*)tfm, ct, pt);
+#endif
+}
+
+static void * ieee80211_ccmp_init(int key_idx)
+{
+	struct ieee80211_ccmp_data *priv;
+
+	priv = kmalloc(sizeof(*priv), GFP_ATOMIC);
+	if (priv == NULL)
+		goto fail;
+	memset(priv, 0, sizeof(*priv));
+	priv->key_idx = key_idx;
+
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	priv->tfm = crypto_alloc_tfm("aes", 0);
+	if (priv->tfm == NULL) {
+		printk(KERN_DEBUG "ieee80211_crypt_ccmp: could not allocate "
+		       "crypto API aes\n");
+		goto fail;
+	}
+       #else
+       priv->tfm = (void*)crypto_alloc_cipher("aes", 0, CRYPTO_ALG_ASYNC);
+	if (IS_ERR(priv->tfm)) {
+		printk(KERN_DEBUG "ieee80211_crypt_ccmp: could not allocate "
+		       "crypto API aes\n");
+		priv->tfm = NULL;
+		goto fail;
+	}
+	#endif
+	return priv;
+
+fail:
+	if (priv) {
+		if (priv->tfm)
+			#if(LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21))
+			crypto_free_tfm(priv->tfm);
+                    #else
+			crypto_free_cipher((void*)priv->tfm);
+		      #endif
+		kfree(priv);
+	}
+
+	return NULL;
+}
+
+
+static void ieee80211_ccmp_deinit(void *priv)
+{
+	struct ieee80211_ccmp_data *_priv = priv;
+	if (_priv && _priv->tfm)
+#if(LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21))
+		crypto_free_tfm(_priv->tfm);
+#else
+		crypto_free_cipher((void*)_priv->tfm);
+#endif
+	kfree(priv);
+}
+
+
+static inline void xor_block(u8 *b, u8 *a, size_t len)
+{
+	int i;
+	for (i = 0; i < len; i++)
+		b[i] ^= a[i];
+}
+
+
+
+static void ccmp_init_blocks(struct crypto_tfm *tfm,
+			     struct ieee80211_hdr_4addr *hdr,
+			     u8 *pn, size_t dlen, u8 *b0, u8 *auth,
+			     u8 *s0)
+{
+	u8 *pos, qc = 0;
+	size_t aad_len;
+	u16 fc;
+	int a4_included, qc_included;
+	u8 aad[2 * AES_BLOCK_LEN];
+
+	fc = le16_to_cpu(hdr->frame_ctl);
+	a4_included = ((fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) ==
+		       (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS));
+	/*
+	qc_included = ((WLAN_FC_GET_TYPE(fc) == IEEE80211_FTYPE_DATA) &&
+		       (WLAN_FC_GET_STYPE(fc) & 0x08));
+        */
+	// fixed by David :2006.9.6
+	qc_included = ((WLAN_FC_GET_TYPE(fc) == IEEE80211_FTYPE_DATA) &&
+		       (WLAN_FC_GET_STYPE(fc) & 0x80));
+	aad_len = 22;
+	if (a4_included)
+		aad_len += 6;
+	if (qc_included) {
+		pos = (u8 *) &hdr->addr4;
+		if (a4_included)
+			pos += 6;
+		qc = *pos & 0x0f;
+		aad_len += 2;
+	}
+	/* CCM Initial Block:
+	 * Flag (Include authentication header, M=3 (8-octet MIC),
+	 *       L=1 (2-octet Dlen))
+	 * Nonce: 0x00 | A2 | PN
+	 * Dlen */
+	b0[0] = 0x59;
+	b0[1] = qc;
+	memcpy(b0 + 2, hdr->addr2, ETH_ALEN);
+	memcpy(b0 + 8, pn, CCMP_PN_LEN);
+	b0[14] = (dlen >> 8) & 0xff;
+	b0[15] = dlen & 0xff;
+
+	/* AAD:
+	 * FC with bits 4..6 and 11..13 masked to zero; 14 is always one
+	 * A1 | A2 | A3
+	 * SC with bits 4..15 (seq#) masked to zero
+	 * A4 (if present)
+	 * QC (if present)
+	 */
+	pos = (u8 *) hdr;
+	aad[0] = 0; /* aad_len >> 8 */
+	aad[1] = aad_len & 0xff;
+	aad[2] = pos[0] & 0x8f;
+	aad[3] = pos[1] & 0xc7;
+	memcpy(aad + 4, hdr->addr1, 3 * ETH_ALEN);
+	pos = (u8 *) &hdr->seq_ctl;
+	aad[22] = pos[0] & 0x0f;
+	aad[23] = 0; /* all bits masked */
+	memset(aad + 24, 0, 8);
+	if (a4_included)
+		memcpy(aad + 24, hdr->addr4, ETH_ALEN);
+	if (qc_included) {
+		aad[a4_included ? 30 : 24] = qc;
+		/* rest of QC masked */
+	}
+
+	/* Start with the first block and AAD */
+	ieee80211_ccmp_aes_encrypt(tfm, b0, auth);
+	xor_block(auth, aad, AES_BLOCK_LEN);
+	ieee80211_ccmp_aes_encrypt(tfm, auth, auth);
+	xor_block(auth, &aad[AES_BLOCK_LEN], AES_BLOCK_LEN);
+	ieee80211_ccmp_aes_encrypt(tfm, auth, auth);
+	b0[0] &= 0x07;
+	b0[14] = b0[15] = 0;
+	ieee80211_ccmp_aes_encrypt(tfm, b0, s0);
+}
+
+
+
+static int ieee80211_ccmp_encrypt(struct sk_buff *skb, int hdr_len, void *priv)
+{
+	struct ieee80211_ccmp_data *key = priv;
+	int data_len, i;
+	u8 *pos;
+	struct ieee80211_hdr_4addr *hdr;
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+
+	if (skb_headroom(skb) < CCMP_HDR_LEN ||
+	    skb_tailroom(skb) < CCMP_MIC_LEN ||
+	    skb->len < hdr_len)
+		return -1;
+
+	data_len = skb->len - hdr_len;
+	pos = skb_push(skb, CCMP_HDR_LEN);
+	memmove(pos, pos + CCMP_HDR_LEN, hdr_len);
+	pos += hdr_len;
+//	mic = skb_put(skb, CCMP_MIC_LEN);
+
+	i = CCMP_PN_LEN - 1;
+	while (i >= 0) {
+		key->tx_pn[i]++;
+		if (key->tx_pn[i] != 0)
+			break;
+		i--;
+	}
+
+	*pos++ = key->tx_pn[5];
+	*pos++ = key->tx_pn[4];
+	*pos++ = 0;
+	*pos++ = (key->key_idx << 6) | (1 << 5) /* Ext IV included */;
+	*pos++ = key->tx_pn[3];
+	*pos++ = key->tx_pn[2];
+	*pos++ = key->tx_pn[1];
+	*pos++ = key->tx_pn[0];
+
+
+	hdr = (struct ieee80211_hdr_4addr *) skb->data;
+	if (!tcb_desc->bHwSec)
+	{
+		int blocks, last, len;
+		u8 *mic;
+		u8 *b0 = key->tx_b0;
+		u8 *b = key->tx_b;
+		u8 *e = key->tx_e;
+		u8 *s0 = key->tx_s0;
+
+		//mic is moved to here by john
+		mic = skb_put(skb, CCMP_MIC_LEN);
+
+		ccmp_init_blocks(key->tfm, hdr, key->tx_pn, data_len, b0, b, s0);
+
+		blocks = (data_len + AES_BLOCK_LEN - 1) / AES_BLOCK_LEN;
+		last = data_len % AES_BLOCK_LEN;
+
+		for (i = 1; i <= blocks; i++) {
+			len = (i == blocks && last) ? last : AES_BLOCK_LEN;
+			/* Authentication */
+			xor_block(b, pos, len);
+			ieee80211_ccmp_aes_encrypt(key->tfm, b, b);
+			/* Encryption, with counter */
+			b0[14] = (i >> 8) & 0xff;
+			b0[15] = i & 0xff;
+			ieee80211_ccmp_aes_encrypt(key->tfm, b0, e);
+			xor_block(pos, e, len);
+			pos += len;
+		}
+
+		for (i = 0; i < CCMP_MIC_LEN; i++)
+			mic[i] = b[i] ^ s0[i];
+	}
+	return 0;
+}
+
+
+static int ieee80211_ccmp_decrypt(struct sk_buff *skb, int hdr_len, void *priv)
+{
+	struct ieee80211_ccmp_data *key = priv;
+	u8 keyidx, *pos;
+	struct ieee80211_hdr_4addr *hdr;
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	u8 pn[6];
+
+	if (skb->len < hdr_len + CCMP_HDR_LEN + CCMP_MIC_LEN) {
+		key->dot11RSNAStatsCCMPFormatErrors++;
+		return -1;
+	}
+
+	hdr = (struct ieee80211_hdr_4addr *) skb->data;
+	pos = skb->data + hdr_len;
+	keyidx = pos[3];
+	if (!(keyidx & (1 << 5))) {
+		if (net_ratelimit()) {
+			printk(KERN_DEBUG "CCMP: received packet without ExtIV"
+			       " flag from " MAC_FMT "\n", MAC_ARG(hdr->addr2));
+		}
+		key->dot11RSNAStatsCCMPFormatErrors++;
+		return -2;
+	}
+	keyidx >>= 6;
+	if (key->key_idx != keyidx) {
+		printk(KERN_DEBUG "CCMP: RX tkey->key_idx=%d frame "
+		       "keyidx=%d priv=%p\n", key->key_idx, keyidx, priv);
+		return -6;
+	}
+	if (!key->key_set) {
+		if (net_ratelimit()) {
+			printk(KERN_DEBUG "CCMP: received packet from " MAC_FMT
+			       " with keyid=%d that does not have a configured"
+			       " key\n", MAC_ARG(hdr->addr2), keyidx);
+		}
+		return -3;
+	}
+
+	pn[0] = pos[7];
+	pn[1] = pos[6];
+	pn[2] = pos[5];
+	pn[3] = pos[4];
+	pn[4] = pos[1];
+	pn[5] = pos[0];
+	pos += 8;
+
+	if (memcmp(pn, key->rx_pn, CCMP_PN_LEN) <= 0) {
+		if (net_ratelimit()) {
+			printk(KERN_DEBUG "CCMP: replay detected: STA=" MAC_FMT
+			       " previous PN %02x%02x%02x%02x%02x%02x "
+			       "received PN %02x%02x%02x%02x%02x%02x\n",
+			       MAC_ARG(hdr->addr2), MAC_ARG(key->rx_pn),
+			       MAC_ARG(pn));
+		}
+		key->dot11RSNAStatsCCMPReplays++;
+		return -4;
+	}
+	if (!tcb_desc->bHwSec)
+	{
+		size_t data_len = skb->len - hdr_len - CCMP_HDR_LEN - CCMP_MIC_LEN;
+		u8 *mic = skb->data + skb->len - CCMP_MIC_LEN;
+		u8 *b0 = key->rx_b0;
+		u8 *b = key->rx_b;
+		u8 *a = key->rx_a;
+		int i, blocks, last, len;
+
+
+		ccmp_init_blocks(key->tfm, hdr, pn, data_len, b0, a, b);
+		xor_block(mic, b, CCMP_MIC_LEN);
+
+		blocks = (data_len + AES_BLOCK_LEN - 1) / AES_BLOCK_LEN;
+		last = data_len % AES_BLOCK_LEN;
+
+		for (i = 1; i <= blocks; i++) {
+			len = (i == blocks && last) ? last : AES_BLOCK_LEN;
+			/* Decrypt, with counter */
+			b0[14] = (i >> 8) & 0xff;
+			b0[15] = i & 0xff;
+			ieee80211_ccmp_aes_encrypt(key->tfm, b0, b);
+			xor_block(pos, b, len);
+			/* Authentication */
+			xor_block(a, pos, len);
+			ieee80211_ccmp_aes_encrypt(key->tfm, a, a);
+			pos += len;
+		}
+
+		if (memcmp(mic, a, CCMP_MIC_LEN) != 0) {
+			if (net_ratelimit()) {
+				printk(KERN_DEBUG "CCMP: decrypt failed: STA="
+				MAC_FMT "\n", MAC_ARG(hdr->addr2));
+			}
+			key->dot11RSNAStatsCCMPDecryptErrors++;
+			return -5;
+		}
+
+		memcpy(key->rx_pn, pn, CCMP_PN_LEN);
+	}
+	/* Remove hdr and MIC */
+	memmove(skb->data + CCMP_HDR_LEN, skb->data, hdr_len);
+	skb_pull(skb, CCMP_HDR_LEN);
+	skb_trim(skb, skb->len - CCMP_MIC_LEN);
+
+	return keyidx;
+}
+
+
+static int ieee80211_ccmp_set_key(void *key, int len, u8 *seq, void *priv)
+{
+	struct ieee80211_ccmp_data *data = priv;
+	int keyidx;
+	struct crypto_tfm *tfm = data->tfm;
+
+	keyidx = data->key_idx;
+	memset(data, 0, sizeof(*data));
+	data->key_idx = keyidx;
+	data->tfm = tfm;
+	if (len == CCMP_TK_LEN) {
+		memcpy(data->key, key, CCMP_TK_LEN);
+		data->key_set = 1;
+		if (seq) {
+			data->rx_pn[0] = seq[5];
+			data->rx_pn[1] = seq[4];
+			data->rx_pn[2] = seq[3];
+			data->rx_pn[3] = seq[2];
+			data->rx_pn[4] = seq[1];
+			data->rx_pn[5] = seq[0];
+		}
+		crypto_cipher_setkey((void*)data->tfm, data->key, CCMP_TK_LEN);
+	} else if (len == 0)
+		data->key_set = 0;
+	else
+		return -1;
+
+	return 0;
+}
+
+
+static int ieee80211_ccmp_get_key(void *key, int len, u8 *seq, void *priv)
+{
+	struct ieee80211_ccmp_data *data = priv;
+
+	if (len < CCMP_TK_LEN)
+		return -1;
+
+	if (!data->key_set)
+		return 0;
+	memcpy(key, data->key, CCMP_TK_LEN);
+
+	if (seq) {
+		seq[0] = data->tx_pn[5];
+		seq[1] = data->tx_pn[4];
+		seq[2] = data->tx_pn[3];
+		seq[3] = data->tx_pn[2];
+		seq[4] = data->tx_pn[1];
+		seq[5] = data->tx_pn[0];
+	}
+
+	return CCMP_TK_LEN;
+}
+
+
+static char * ieee80211_ccmp_print_stats(char *p, void *priv)
+{
+	struct ieee80211_ccmp_data *ccmp = priv;
+	p += sprintf(p, "key[%d] alg=CCMP key_set=%d "
+		     "tx_pn=%02x%02x%02x%02x%02x%02x "
+		     "rx_pn=%02x%02x%02x%02x%02x%02x "
+		     "format_errors=%d replays=%d decrypt_errors=%d\n",
+		     ccmp->key_idx, ccmp->key_set,
+		     MAC_ARG(ccmp->tx_pn), MAC_ARG(ccmp->rx_pn),
+		     ccmp->dot11RSNAStatsCCMPFormatErrors,
+		     ccmp->dot11RSNAStatsCCMPReplays,
+		     ccmp->dot11RSNAStatsCCMPDecryptErrors);
+
+	return p;
+}
+
+void ieee80211_ccmp_null(void)
+{
+//    printk("============>%s()\n", __FUNCTION__);
+	return;
+}
+
+static struct ieee80211_crypto_ops ieee80211_crypt_ccmp = {
+	.name			= "CCMP",
+	.init			= ieee80211_ccmp_init,
+	.deinit			= ieee80211_ccmp_deinit,
+	.encrypt_mpdu		= ieee80211_ccmp_encrypt,
+	.decrypt_mpdu		= ieee80211_ccmp_decrypt,
+	.encrypt_msdu		= NULL,
+	.decrypt_msdu		= NULL,
+	.set_key		= ieee80211_ccmp_set_key,
+	.get_key		= ieee80211_ccmp_get_key,
+	.print_stats		= ieee80211_ccmp_print_stats,
+	.extra_prefix_len	= CCMP_HDR_LEN,
+	.extra_postfix_len	= CCMP_MIC_LEN,
+	.owner			= THIS_MODULE,
+};
+
+
+static int __init ieee80211_crypto_ccmp_init(void)
+{
+	return ieee80211_register_crypto_ops(&ieee80211_crypt_ccmp);
+}
+
+
+static void __exit ieee80211_crypto_ccmp_exit(void)
+{
+	ieee80211_unregister_crypto_ops(&ieee80211_crypt_ccmp);
+}
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+EXPORT_SYMBOL(ieee80211_ccmp_null);
+#else
+EXPORT_SYMBOL_NOVERS(ieee80211_ccmp_null);
+#endif
+
+module_init(ieee80211_crypto_ccmp_init);
+module_exit(ieee80211_crypto_ccmp_exit);
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt_tkip.c b/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt_tkip.c
new file mode 100644
index 0000000..b031b64
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt_tkip.c
@@ -0,0 +1,1034 @@
+/*
+ * Host AP crypt: host-based TKIP encryption implementation for Host AP driver
+ *
+ * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. See README and COPYING for
+ * more details.
+ */
+
+//#include <linux/config.h>
+#include <linux/version.h>
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/slab.h>
+#include <linux/random.h>
+#include <linux/skbuff.h>
+#include <linux/netdevice.h>
+#include <linux/if_ether.h>
+#include <linux/if_arp.h>
+#include <asm/string.h>
+
+#include "ieee80211.h"
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,20))
+//#include "crypto_compat.h"
+#endif
+
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+#include "rtl_crypto.h"
+#else
+#include <linux/crypto.h>
+#endif
+//#include <asm/scatterlist.h>
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20)
+    #include <asm/scatterlist.h>
+#else
+        #include <linux/scatterlist.h>
+#endif
+
+#include <linux/crc32.h>
+
+MODULE_AUTHOR("Jouni Malinen");
+MODULE_DESCRIPTION("Host AP crypt: TKIP");
+MODULE_LICENSE("GPL");
+
+#ifndef OPENSUSE_SLED
+#define OPENSUSE_SLED 0
+#endif
+
+struct ieee80211_tkip_data {
+#define TKIP_KEY_LEN 32
+	u8 key[TKIP_KEY_LEN];
+	int key_set;
+
+	u32 tx_iv32;
+	u16 tx_iv16;
+	u16 tx_ttak[5];
+	int tx_phase1_done;
+
+	u32 rx_iv32;
+	u16 rx_iv16;
+	u16 rx_ttak[5];
+	int rx_phase1_done;
+	u32 rx_iv32_new;
+	u16 rx_iv16_new;
+
+	u32 dot11RSNAStatsTKIPReplays;
+	u32 dot11RSNAStatsTKIPICVErrors;
+	u32 dot11RSNAStatsTKIPLocalMICFailures;
+
+	int key_idx;
+#if((LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,21)) || (OPENSUSE_SLED))
+	struct crypto_blkcipher *rx_tfm_arc4;
+	struct crypto_hash *rx_tfm_michael;
+	struct crypto_blkcipher *tx_tfm_arc4;
+	struct crypto_hash *tx_tfm_michael;
+#else
+	struct crypto_tfm *tx_tfm_arc4;
+	struct crypto_tfm *tx_tfm_michael;
+	struct crypto_tfm *rx_tfm_arc4;
+	struct crypto_tfm *rx_tfm_michael;
+#endif
+	/* scratch buffers for virt_to_page() (crypto API) */
+	u8 rx_hdr[16], tx_hdr[16];
+};
+
+static void * ieee80211_tkip_init(int key_idx)
+{
+	struct ieee80211_tkip_data *priv;
+
+	priv = kmalloc(sizeof(*priv), GFP_ATOMIC);
+	if (priv == NULL)
+		goto fail;
+	memset(priv, 0, sizeof(*priv));
+	priv->key_idx = key_idx;
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	priv->tx_tfm_arc4 = crypto_alloc_tfm("arc4", 0);
+	if (priv->tx_tfm_arc4 == NULL) {
+		printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate "
+				"crypto API arc4\n");
+		goto fail;
+	}
+
+	priv->tx_tfm_michael = crypto_alloc_tfm("michael_mic", 0);
+	if (priv->tx_tfm_michael == NULL) {
+		printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate "
+				"crypto API michael_mic\n");
+		goto fail;
+	}
+
+	priv->rx_tfm_arc4 = crypto_alloc_tfm("arc4", 0);
+	if (priv->rx_tfm_arc4 == NULL) {
+		printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate "
+				"crypto API arc4\n");
+		goto fail;
+	}
+
+	priv->rx_tfm_michael = crypto_alloc_tfm("michael_mic", 0);
+	if (priv->rx_tfm_michael == NULL) {
+		printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate "
+				"crypto API michael_mic\n");
+		goto fail;
+	}
+#else
+	priv->tx_tfm_arc4 = crypto_alloc_blkcipher("ecb(arc4)", 0,
+			CRYPTO_ALG_ASYNC);
+	if (IS_ERR(priv->tx_tfm_arc4)) {
+		printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate "
+				"crypto API arc4\n");
+		priv->tx_tfm_arc4 = NULL;
+		goto fail;
+	}
+
+	priv->tx_tfm_michael = crypto_alloc_hash("michael_mic", 0,
+			CRYPTO_ALG_ASYNC);
+	if (IS_ERR(priv->tx_tfm_michael)) {
+		printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate "
+				"crypto API michael_mic\n");
+		priv->tx_tfm_michael = NULL;
+		goto fail;
+	}
+
+	priv->rx_tfm_arc4 = crypto_alloc_blkcipher("ecb(arc4)", 0,
+			CRYPTO_ALG_ASYNC);
+	if (IS_ERR(priv->rx_tfm_arc4)) {
+		printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate "
+				"crypto API arc4\n");
+		priv->rx_tfm_arc4 = NULL;
+		goto fail;
+	}
+
+	priv->rx_tfm_michael = crypto_alloc_hash("michael_mic", 0,
+			CRYPTO_ALG_ASYNC);
+	if (IS_ERR(priv->rx_tfm_michael)) {
+		printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate "
+				"crypto API michael_mic\n");
+		priv->rx_tfm_michael = NULL;
+		goto fail;
+	}
+#endif
+	return priv;
+
+fail:
+	if (priv) {
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+		if (priv->tx_tfm_michael)
+			crypto_free_tfm(priv->tx_tfm_michael);
+		if (priv->tx_tfm_arc4)
+			crypto_free_tfm(priv->tx_tfm_arc4);
+		if (priv->rx_tfm_michael)
+			crypto_free_tfm(priv->rx_tfm_michael);
+		if (priv->rx_tfm_arc4)
+			crypto_free_tfm(priv->rx_tfm_arc4);
+
+#else
+		if (priv->tx_tfm_michael)
+			crypto_free_hash(priv->tx_tfm_michael);
+		if (priv->tx_tfm_arc4)
+			crypto_free_blkcipher(priv->tx_tfm_arc4);
+		if (priv->rx_tfm_michael)
+			crypto_free_hash(priv->rx_tfm_michael);
+		if (priv->rx_tfm_arc4)
+			crypto_free_blkcipher(priv->rx_tfm_arc4);
+#endif
+		kfree(priv);
+	}
+
+	return NULL;
+}
+
+
+static void ieee80211_tkip_deinit(void *priv)
+{
+	struct ieee80211_tkip_data *_priv = priv;
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	if (_priv->tx_tfm_michael)
+		crypto_free_tfm(_priv->tx_tfm_michael);
+	if (_priv->tx_tfm_arc4)
+		crypto_free_tfm(_priv->tx_tfm_arc4);
+	if (_priv->rx_tfm_michael)
+		crypto_free_tfm(_priv->rx_tfm_michael);
+	if (_priv->rx_tfm_arc4)
+		crypto_free_tfm(_priv->rx_tfm_arc4);
+#else
+	if (_priv) {
+		if (_priv->tx_tfm_michael)
+			crypto_free_hash(_priv->tx_tfm_michael);
+		if (_priv->tx_tfm_arc4)
+			crypto_free_blkcipher(_priv->tx_tfm_arc4);
+		if (_priv->rx_tfm_michael)
+			crypto_free_hash(_priv->rx_tfm_michael);
+		if (_priv->rx_tfm_arc4)
+			crypto_free_blkcipher(_priv->rx_tfm_arc4);
+	}
+#endif
+	kfree(priv);
+}
+
+
+static inline u16 RotR1(u16 val)
+{
+	return (val >> 1) | (val << 15);
+}
+
+
+static inline u8 Lo8(u16 val)
+{
+	return val & 0xff;
+}
+
+
+static inline u8 Hi8(u16 val)
+{
+	return val >> 8;
+}
+
+
+static inline u16 Lo16(u32 val)
+{
+	return val & 0xffff;
+}
+
+
+static inline u16 Hi16(u32 val)
+{
+	return val >> 16;
+}
+
+
+static inline u16 Mk16(u8 hi, u8 lo)
+{
+	return lo | (((u16) hi) << 8);
+}
+
+
+static inline u16 Mk16_le(u16 *v)
+{
+	return le16_to_cpu(*v);
+}
+
+
+static const u16 Sbox[256] =
+{
+	0xC6A5, 0xF884, 0xEE99, 0xF68D, 0xFF0D, 0xD6BD, 0xDEB1, 0x9154,
+	0x6050, 0x0203, 0xCEA9, 0x567D, 0xE719, 0xB562, 0x4DE6, 0xEC9A,
+	0x8F45, 0x1F9D, 0x8940, 0xFA87, 0xEF15, 0xB2EB, 0x8EC9, 0xFB0B,
+	0x41EC, 0xB367, 0x5FFD, 0x45EA, 0x23BF, 0x53F7, 0xE496, 0x9B5B,
+	0x75C2, 0xE11C, 0x3DAE, 0x4C6A, 0x6C5A, 0x7E41, 0xF502, 0x834F,
+	0x685C, 0x51F4, 0xD134, 0xF908, 0xE293, 0xAB73, 0x6253, 0x2A3F,
+	0x080C, 0x9552, 0x4665, 0x9D5E, 0x3028, 0x37A1, 0x0A0F, 0x2FB5,
+	0x0E09, 0x2436, 0x1B9B, 0xDF3D, 0xCD26, 0x4E69, 0x7FCD, 0xEA9F,
+	0x121B, 0x1D9E, 0x5874, 0x342E, 0x362D, 0xDCB2, 0xB4EE, 0x5BFB,
+	0xA4F6, 0x764D, 0xB761, 0x7DCE, 0x527B, 0xDD3E, 0x5E71, 0x1397,
+	0xA6F5, 0xB968, 0x0000, 0xC12C, 0x4060, 0xE31F, 0x79C8, 0xB6ED,
+	0xD4BE, 0x8D46, 0x67D9, 0x724B, 0x94DE, 0x98D4, 0xB0E8, 0x854A,
+	0xBB6B, 0xC52A, 0x4FE5, 0xED16, 0x86C5, 0x9AD7, 0x6655, 0x1194,
+	0x8ACF, 0xE910, 0x0406, 0xFE81, 0xA0F0, 0x7844, 0x25BA, 0x4BE3,
+	0xA2F3, 0x5DFE, 0x80C0, 0x058A, 0x3FAD, 0x21BC, 0x7048, 0xF104,
+	0x63DF, 0x77C1, 0xAF75, 0x4263, 0x2030, 0xE51A, 0xFD0E, 0xBF6D,
+	0x814C, 0x1814, 0x2635, 0xC32F, 0xBEE1, 0x35A2, 0x88CC, 0x2E39,
+	0x9357, 0x55F2, 0xFC82, 0x7A47, 0xC8AC, 0xBAE7, 0x322B, 0xE695,
+	0xC0A0, 0x1998, 0x9ED1, 0xA37F, 0x4466, 0x547E, 0x3BAB, 0x0B83,
+	0x8CCA, 0xC729, 0x6BD3, 0x283C, 0xA779, 0xBCE2, 0x161D, 0xAD76,
+	0xDB3B, 0x6456, 0x744E, 0x141E, 0x92DB, 0x0C0A, 0x486C, 0xB8E4,
+	0x9F5D, 0xBD6E, 0x43EF, 0xC4A6, 0x39A8, 0x31A4, 0xD337, 0xF28B,
+	0xD532, 0x8B43, 0x6E59, 0xDAB7, 0x018C, 0xB164, 0x9CD2, 0x49E0,
+	0xD8B4, 0xACFA, 0xF307, 0xCF25, 0xCAAF, 0xF48E, 0x47E9, 0x1018,
+	0x6FD5, 0xF088, 0x4A6F, 0x5C72, 0x3824, 0x57F1, 0x73C7, 0x9751,
+	0xCB23, 0xA17C, 0xE89C, 0x3E21, 0x96DD, 0x61DC, 0x0D86, 0x0F85,
+	0xE090, 0x7C42, 0x71C4, 0xCCAA, 0x90D8, 0x0605, 0xF701, 0x1C12,
+	0xC2A3, 0x6A5F, 0xAEF9, 0x69D0, 0x1791, 0x9958, 0x3A27, 0x27B9,
+	0xD938, 0xEB13, 0x2BB3, 0x2233, 0xD2BB, 0xA970, 0x0789, 0x33A7,
+	0x2DB6, 0x3C22, 0x1592, 0xC920, 0x8749, 0xAAFF, 0x5078, 0xA57A,
+	0x038F, 0x59F8, 0x0980, 0x1A17, 0x65DA, 0xD731, 0x84C6, 0xD0B8,
+	0x82C3, 0x29B0, 0x5A77, 0x1E11, 0x7BCB, 0xA8FC, 0x6DD6, 0x2C3A,
+};
+
+
+static inline u16 _S_(u16 v)
+{
+	u16 t = Sbox[Hi8(v)];
+	return Sbox[Lo8(v)] ^ ((t << 8) | (t >> 8));
+}
+
+
+#define PHASE1_LOOP_COUNT 8
+
+
+static void tkip_mixing_phase1(u16 *TTAK, const u8 *TK, const u8 *TA, u32 IV32)
+{
+	int i, j;
+
+	/* Initialize the 80-bit TTAK from TSC (IV32) and TA[0..5] */
+	TTAK[0] = Lo16(IV32);
+	TTAK[1] = Hi16(IV32);
+	TTAK[2] = Mk16(TA[1], TA[0]);
+	TTAK[3] = Mk16(TA[3], TA[2]);
+	TTAK[4] = Mk16(TA[5], TA[4]);
+
+	for (i = 0; i < PHASE1_LOOP_COUNT; i++) {
+		j = 2 * (i & 1);
+		TTAK[0] += _S_(TTAK[4] ^ Mk16(TK[1 + j], TK[0 + j]));
+		TTAK[1] += _S_(TTAK[0] ^ Mk16(TK[5 + j], TK[4 + j]));
+		TTAK[2] += _S_(TTAK[1] ^ Mk16(TK[9 + j], TK[8 + j]));
+		TTAK[3] += _S_(TTAK[2] ^ Mk16(TK[13 + j], TK[12 + j]));
+		TTAK[4] += _S_(TTAK[3] ^ Mk16(TK[1 + j], TK[0 + j])) + i;
+	}
+}
+
+
+static void tkip_mixing_phase2(u8 *WEPSeed, const u8 *TK, const u16 *TTAK,
+			       u16 IV16)
+{
+	/* Make temporary area overlap WEP seed so that the final copy can be
+	 * avoided on little endian hosts. */
+	u16 *PPK = (u16 *) &WEPSeed[4];
+
+	/* Step 1 - make copy of TTAK and bring in TSC */
+	PPK[0] = TTAK[0];
+	PPK[1] = TTAK[1];
+	PPK[2] = TTAK[2];
+	PPK[3] = TTAK[3];
+	PPK[4] = TTAK[4];
+	PPK[5] = TTAK[4] + IV16;
+
+	/* Step 2 - 96-bit bijective mixing using S-box */
+	PPK[0] += _S_(PPK[5] ^ Mk16_le((u16 *) &TK[0]));
+	PPK[1] += _S_(PPK[0] ^ Mk16_le((u16 *) &TK[2]));
+	PPK[2] += _S_(PPK[1] ^ Mk16_le((u16 *) &TK[4]));
+	PPK[3] += _S_(PPK[2] ^ Mk16_le((u16 *) &TK[6]));
+	PPK[4] += _S_(PPK[3] ^ Mk16_le((u16 *) &TK[8]));
+	PPK[5] += _S_(PPK[4] ^ Mk16_le((u16 *) &TK[10]));
+
+	PPK[0] += RotR1(PPK[5] ^ Mk16_le((u16 *) &TK[12]));
+	PPK[1] += RotR1(PPK[0] ^ Mk16_le((u16 *) &TK[14]));
+	PPK[2] += RotR1(PPK[1]);
+	PPK[3] += RotR1(PPK[2]);
+	PPK[4] += RotR1(PPK[3]);
+	PPK[5] += RotR1(PPK[4]);
+
+	/* Step 3 - bring in last of TK bits, assign 24-bit WEP IV value
+	 * WEPSeed[0..2] is transmitted as WEP IV */
+	WEPSeed[0] = Hi8(IV16);
+	WEPSeed[1] = (Hi8(IV16) | 0x20) & 0x7F;
+	WEPSeed[2] = Lo8(IV16);
+	WEPSeed[3] = Lo8((PPK[5] ^ Mk16_le((u16 *) &TK[0])) >> 1);
+
+#ifdef __BIG_ENDIAN
+	{
+		int i;
+		for (i = 0; i < 6; i++)
+			PPK[i] = (PPK[i] << 8) | (PPK[i] >> 8);
+	}
+#endif
+}
+
+
+static int ieee80211_tkip_encrypt(struct sk_buff *skb, int hdr_len, void *priv)
+{
+	struct ieee80211_tkip_data *tkey = priv;
+		int len;
+	u8 *pos;
+	struct ieee80211_hdr_4addr *hdr;
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+
+	#if((LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,21)) || (OPENSUSE_SLED))
+	struct blkcipher_desc desc = {.tfm = tkey->tx_tfm_arc4};
+	int ret = 0;
+	#endif
+	u8 rc4key[16],  *icv;
+	u32 crc;
+	struct scatterlist sg;
+
+	if (skb_headroom(skb) < 8 || skb_tailroom(skb) < 4 ||
+	    skb->len < hdr_len)
+		return -1;
+
+	hdr = (struct ieee80211_hdr_4addr *) skb->data;
+
+#if 0
+printk("@@ tkey\n");
+printk("%x|", ((u32*)tkey->key)[0]);
+printk("%x|", ((u32*)tkey->key)[1]);
+printk("%x|", ((u32*)tkey->key)[2]);
+printk("%x|", ((u32*)tkey->key)[3]);
+printk("%x|", ((u32*)tkey->key)[4]);
+printk("%x|", ((u32*)tkey->key)[5]);
+printk("%x|", ((u32*)tkey->key)[6]);
+printk("%x\n", ((u32*)tkey->key)[7]);
+#endif
+
+	if (!tcb_desc->bHwSec)
+	{
+		if (!tkey->tx_phase1_done) {
+			tkip_mixing_phase1(tkey->tx_ttak, tkey->key, hdr->addr2,
+					tkey->tx_iv32);
+			tkey->tx_phase1_done = 1;
+		}
+		tkip_mixing_phase2(rc4key, tkey->key, tkey->tx_ttak, tkey->tx_iv16);
+	}
+	else
+	tkey->tx_phase1_done = 1;
+
+
+	len = skb->len - hdr_len;
+	pos = skb_push(skb, 8);
+	memmove(pos, pos + 8, hdr_len);
+	pos += hdr_len;
+
+	if (tcb_desc->bHwSec)
+	{
+		*pos++ = Hi8(tkey->tx_iv16);
+		*pos++ = (Hi8(tkey->tx_iv16) | 0x20) & 0x7F;
+		*pos++ = Lo8(tkey->tx_iv16);
+	}
+	else
+	{
+		*pos++ = rc4key[0];
+		*pos++ = rc4key[1];
+		*pos++ = rc4key[2];
+	}
+
+	*pos++ = (tkey->key_idx << 6) | (1 << 5) /* Ext IV included */;
+	*pos++ = tkey->tx_iv32 & 0xff;
+	*pos++ = (tkey->tx_iv32 >> 8) & 0xff;
+	*pos++ = (tkey->tx_iv32 >> 16) & 0xff;
+	*pos++ = (tkey->tx_iv32 >> 24) & 0xff;
+
+	if (!tcb_desc->bHwSec)
+	{
+		icv = skb_put(skb, 4);
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+		crc = ~crc32_le(~0, pos, len);
+#else
+		crc = ~ether_crc_le(len, pos);
+#endif
+		icv[0] = crc;
+		icv[1] = crc >> 8;
+		icv[2] = crc >> 16;
+		icv[3] = crc >> 24;
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+		crypto_cipher_setkey(tkey->tx_tfm_arc4, rc4key, 16);
+		sg.page = virt_to_page(pos);
+		sg.offset = offset_in_page(pos);
+		sg.length = len + 4;
+		crypto_cipher_encrypt(tkey->tx_tfm_arc4, &sg, &sg, len + 4);
+#else
+		crypto_blkcipher_setkey(tkey->tx_tfm_arc4, rc4key, 16);
+#if(LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24))
+		sg.page = virt_to_page(pos);
+		sg.offset = offset_in_page(pos);
+		sg.length = len + 4;
+#else
+		sg_init_one(&sg, pos, len+4);
+#endif
+		ret= crypto_blkcipher_encrypt(&desc, &sg, &sg, len + 4);
+#endif
+
+	}
+
+	tkey->tx_iv16++;
+	if (tkey->tx_iv16 == 0) {
+		tkey->tx_phase1_done = 0;
+		tkey->tx_iv32++;
+	}
+
+	if (!tcb_desc->bHwSec)
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+		return 0;
+	#else
+		return ret;
+	#endif
+	else
+        	return 0;
+
+
+}
+
+static int ieee80211_tkip_decrypt(struct sk_buff *skb, int hdr_len, void *priv)
+{
+	struct ieee80211_tkip_data *tkey = priv;
+	u8 keyidx, *pos;
+	u32 iv32;
+	u16 iv16;
+	struct ieee80211_hdr_4addr *hdr;
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	#if((LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,21)) || (OPENSUSE_SLED))
+	struct blkcipher_desc desc = {.tfm = tkey->rx_tfm_arc4};
+	#endif
+	u8 rc4key[16];
+	u8 icv[4];
+	u32 crc;
+	struct scatterlist sg;
+	int plen;
+	if (skb->len < hdr_len + 8 + 4)
+		return -1;
+
+	hdr = (struct ieee80211_hdr_4addr *) skb->data;
+	pos = skb->data + hdr_len;
+	keyidx = pos[3];
+	if (!(keyidx & (1 << 5))) {
+		if (net_ratelimit()) {
+			printk(KERN_DEBUG "TKIP: received packet without ExtIV"
+			       " flag from " MAC_FMT "\n", MAC_ARG(hdr->addr2));
+		}
+		return -2;
+	}
+	keyidx >>= 6;
+	if (tkey->key_idx != keyidx) {
+		printk(KERN_DEBUG "TKIP: RX tkey->key_idx=%d frame "
+		       "keyidx=%d priv=%p\n", tkey->key_idx, keyidx, priv);
+		return -6;
+	}
+	if (!tkey->key_set) {
+		if (net_ratelimit()) {
+			printk(KERN_DEBUG "TKIP: received packet from " MAC_FMT
+			       " with keyid=%d that does not have a configured"
+			       " key\n", MAC_ARG(hdr->addr2), keyidx);
+		}
+		return -3;
+	}
+	iv16 = (pos[0] << 8) | pos[2];
+	iv32 = pos[4] | (pos[5] << 8) | (pos[6] << 16) | (pos[7] << 24);
+	pos += 8;
+
+	if (!tcb_desc->bHwSec)
+	{
+		if (iv32 < tkey->rx_iv32 ||
+		(iv32 == tkey->rx_iv32 && iv16 <= tkey->rx_iv16)) {
+			if (net_ratelimit()) {
+				printk(KERN_DEBUG "TKIP: replay detected: STA=" MAC_FMT
+				" previous TSC %08x%04x received TSC "
+				"%08x%04x\n", MAC_ARG(hdr->addr2),
+				tkey->rx_iv32, tkey->rx_iv16, iv32, iv16);
+			}
+			tkey->dot11RSNAStatsTKIPReplays++;
+			return -4;
+		}
+
+		if (iv32 != tkey->rx_iv32 || !tkey->rx_phase1_done) {
+			tkip_mixing_phase1(tkey->rx_ttak, tkey->key, hdr->addr2, iv32);
+			tkey->rx_phase1_done = 1;
+		}
+		tkip_mixing_phase2(rc4key, tkey->key, tkey->rx_ttak, iv16);
+
+		plen = skb->len - hdr_len - 12;
+
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+		crypto_cipher_setkey(tkey->rx_tfm_arc4, rc4key, 16);
+		sg.page = virt_to_page(pos);
+		sg.offset = offset_in_page(pos);
+		sg.length = plen + 4;
+		crypto_cipher_decrypt(tkey->rx_tfm_arc4, &sg, &sg, plen + 4);
+#else
+		crypto_blkcipher_setkey(tkey->rx_tfm_arc4, rc4key, 16);
+#if(LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24))
+		sg.page = virt_to_page(pos);
+		sg.offset = offset_in_page(pos);
+		sg.length = plen + 4;
+#else
+		sg_init_one(&sg, pos, plen+4);
+#endif
+		if (crypto_blkcipher_decrypt(&desc, &sg, &sg, plen + 4)) {
+			if (net_ratelimit()) {
+				printk(KERN_DEBUG ": TKIP: failed to decrypt "
+						"received packet from " MAC_FMT "\n",
+						MAC_ARG(hdr->addr2));
+			}
+			return -7;
+		}
+#endif
+
+	#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+		crc = ~crc32_le(~0, pos, plen);
+	#else
+		crc = ~ether_crc_le(plen, pos);
+	#endif
+		icv[0] = crc;
+		icv[1] = crc >> 8;
+		icv[2] = crc >> 16;
+		icv[3] = crc >> 24;
+
+		if (memcmp(icv, pos + plen, 4) != 0) {
+			if (iv32 != tkey->rx_iv32) {
+				/* Previously cached Phase1 result was already lost, so
+				* it needs to be recalculated for the next packet. */
+				tkey->rx_phase1_done = 0;
+			}
+			if (net_ratelimit()) {
+				printk(KERN_DEBUG "TKIP: ICV error detected: STA="
+				MAC_FMT "\n", MAC_ARG(hdr->addr2));
+			}
+			tkey->dot11RSNAStatsTKIPICVErrors++;
+			return -5;
+		}
+
+	}
+
+	/* Update real counters only after Michael MIC verification has
+	 * completed */
+	tkey->rx_iv32_new = iv32;
+	tkey->rx_iv16_new = iv16;
+
+	/* Remove IV and ICV */
+	memmove(skb->data + 8, skb->data, hdr_len);
+	skb_pull(skb, 8);
+	skb_trim(skb, skb->len - 4);
+
+//john's test
+#ifdef JOHN_DUMP
+if( ((u16*)skb->data)[0] & 0x4000){
+        printk("@@ rx decrypted skb->data");
+        int i;
+        for(i=0;i<skb->len;i++){
+                if( (i%24)==0 ) printk("\n");
+                printk("%2x ", ((u8*)skb->data)[i]);
+        }
+        printk("\n");
+}
+#endif /*JOHN_DUMP*/
+	return keyidx;
+}
+
+
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+static int michael_mic(struct crypto_tfm * tfm_michael, u8 *key, u8 *hdr,
+		       u8 *data, size_t data_len, u8 *mic)
+{
+	struct scatterlist sg[2];
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+        struct hash_desc desc;
+        int ret = 0;
+#endif
+
+	if (tfm_michael == NULL){
+		printk(KERN_WARNING "michael_mic: tfm_michael == NULL\n");
+		return -1;
+	}
+	sg[0].page = virt_to_page(hdr);
+	sg[0].offset = offset_in_page(hdr);
+	sg[0].length = 16;
+
+	sg[1].page = virt_to_page(data);
+	sg[1].offset = offset_in_page(data);
+	sg[1].length = data_len;
+
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20)
+	crypto_digest_init(tfm_michael);
+        crypto_digest_setkey(tfm_michael, key, 8);
+        crypto_digest_update(tfm_michael, sg, 2);
+        crypto_digest_final(tfm_michael, mic);
+        return 0;
+#else
+if (crypto_hash_setkey(tkey->tfm_michael, key, 8))
+                return -1;
+
+//      return 0;
+              desc.tfm = tkey->tfm_michael;
+              desc.flags = 0;
+              ret = crypto_hash_digest(&desc, sg, data_len + 16, mic);
+              return ret;
+#endif
+}
+#else
+static int michael_mic(struct crypto_hash *tfm_michael, u8 * key, u8 * hdr,
+                       u8 * data, size_t data_len, u8 * mic)
+{
+        struct hash_desc desc;
+        struct scatterlist sg[2];
+
+        if (tfm_michael == NULL) {
+                printk(KERN_WARNING "michael_mic: tfm_michael == NULL\n");
+                return -1;
+        }
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24)
+        sg[0].page = virt_to_page(hdr);
+        sg[0].offset = offset_in_page(hdr);
+        sg[0].length = 16;
+
+        sg[1].page = virt_to_page(data);
+        sg[1].offset = offset_in_page(data);
+        sg[1].length = data_len;
+#else
+        sg_init_table(sg, 2);
+        sg_set_buf(&sg[0], hdr, 16);
+        sg_set_buf(&sg[1], data, data_len);
+#endif
+
+        if (crypto_hash_setkey(tfm_michael, key, 8))
+                return -1;
+
+        desc.tfm = tfm_michael;
+        desc.flags = 0;
+        return crypto_hash_digest(&desc, sg, data_len + 16, mic);
+}
+#endif
+
+
+
+static void michael_mic_hdr(struct sk_buff *skb, u8 *hdr)
+{
+	struct ieee80211_hdr_4addr *hdr11;
+
+	hdr11 = (struct ieee80211_hdr_4addr *) skb->data;
+	switch (le16_to_cpu(hdr11->frame_ctl) &
+		(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS)) {
+	case IEEE80211_FCTL_TODS:
+		memcpy(hdr, hdr11->addr3, ETH_ALEN); /* DA */
+		memcpy(hdr + ETH_ALEN, hdr11->addr2, ETH_ALEN); /* SA */
+		break;
+	case IEEE80211_FCTL_FROMDS:
+		memcpy(hdr, hdr11->addr1, ETH_ALEN); /* DA */
+		memcpy(hdr + ETH_ALEN, hdr11->addr3, ETH_ALEN); /* SA */
+		break;
+	case IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS:
+		memcpy(hdr, hdr11->addr3, ETH_ALEN); /* DA */
+		memcpy(hdr + ETH_ALEN, hdr11->addr4, ETH_ALEN); /* SA */
+		break;
+	case 0:
+		memcpy(hdr, hdr11->addr1, ETH_ALEN); /* DA */
+		memcpy(hdr + ETH_ALEN, hdr11->addr2, ETH_ALEN); /* SA */
+		break;
+	}
+
+	hdr[12] = 0; /* priority */
+
+	hdr[13] = hdr[14] = hdr[15] = 0; /* reserved */
+}
+
+
+static int ieee80211_michael_mic_add(struct sk_buff *skb, int hdr_len, void *priv)
+{
+	struct ieee80211_tkip_data *tkey = priv;
+	u8 *pos;
+	struct ieee80211_hdr_4addr *hdr;
+
+	hdr = (struct ieee80211_hdr_4addr *) skb->data;
+
+	if (skb_tailroom(skb) < 8 || skb->len < hdr_len) {
+		printk(KERN_DEBUG "Invalid packet for Michael MIC add "
+		       "(tailroom=%d hdr_len=%d skb->len=%d)\n",
+		       skb_tailroom(skb), hdr_len, skb->len);
+		return -1;
+	}
+
+	michael_mic_hdr(skb, tkey->tx_hdr);
+
+	// { david, 2006.9.1
+	// fix the wpa process with wmm enabled.
+	if(IEEE80211_QOS_HAS_SEQ(le16_to_cpu(hdr->frame_ctl))) {
+		tkey->tx_hdr[12] = *(skb->data + hdr_len - 2) & 0x07;
+	}
+	// }
+	pos = skb_put(skb, 8);
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	if (michael_mic(tkey->tx_tfm_michael, &tkey->key[16], tkey->tx_hdr,
+				skb->data + hdr_len, skb->len - 8 - hdr_len, pos))
+#else
+	if (michael_mic(tkey->tx_tfm_michael, &tkey->key[16], tkey->tx_hdr,
+				skb->data + hdr_len, skb->len - 8 - hdr_len, pos))
+#endif
+		return -1;
+
+	return 0;
+}
+
+
+#if WIRELESS_EXT >= 18
+static void ieee80211_michael_mic_failure(struct net_device *dev,
+				       struct ieee80211_hdr_4addr *hdr,
+				       int keyidx)
+{
+	union iwreq_data wrqu;
+	struct iw_michaelmicfailure ev;
+
+	/* TODO: needed parameters: count, keyid, key type, TSC */
+	memset(&ev, 0, sizeof(ev));
+	ev.flags = keyidx & IW_MICFAILURE_KEY_ID;
+	if (hdr->addr1[0] & 0x01)
+		ev.flags |= IW_MICFAILURE_GROUP;
+	else
+		ev.flags |= IW_MICFAILURE_PAIRWISE;
+	ev.src_addr.sa_family = ARPHRD_ETHER;
+	memcpy(ev.src_addr.sa_data, hdr->addr2, ETH_ALEN);
+	memset(&wrqu, 0, sizeof(wrqu));
+	wrqu.data.length = sizeof(ev);
+	wireless_send_event(dev, IWEVMICHAELMICFAILURE, &wrqu, (char *) &ev);
+}
+#elif WIRELESS_EXT >= 15
+static void ieee80211_michael_mic_failure(struct net_device *dev,
+				       struct ieee80211_hdr_4addr *hdr,
+				       int keyidx)
+{
+	union iwreq_data wrqu;
+	char buf[128];
+
+	/* TODO: needed parameters: count, keyid, key type, TSC */
+	sprintf(buf, "MLME-MICHAELMICFAILURE.indication(keyid=%d %scast addr="
+		MAC_FMT ")", keyidx, hdr->addr1[0] & 0x01 ? "broad" : "uni",
+		MAC_ARG(hdr->addr2));
+	memset(&wrqu, 0, sizeof(wrqu));
+	wrqu.data.length = strlen(buf);
+	wireless_send_event(dev, IWEVCUSTOM, &wrqu, buf);
+}
+#else /* WIRELESS_EXT >= 15 */
+static inline void ieee80211_michael_mic_failure(struct net_device *dev,
+					      struct ieee80211_hdr_4addr *hdr,
+					      int keyidx)
+{
+}
+#endif /* WIRELESS_EXT >= 15 */
+
+static int ieee80211_michael_mic_verify(struct sk_buff *skb, int keyidx,
+				     int hdr_len, void *priv)
+{
+	struct ieee80211_tkip_data *tkey = priv;
+	u8 mic[8];
+	struct ieee80211_hdr_4addr *hdr;
+
+	hdr = (struct ieee80211_hdr_4addr *) skb->data;
+
+	if (!tkey->key_set)
+		return -1;
+
+	michael_mic_hdr(skb, tkey->rx_hdr);
+	// { david, 2006.9.1
+	// fix the wpa process with wmm enabled.
+	if(IEEE80211_QOS_HAS_SEQ(le16_to_cpu(hdr->frame_ctl))) {
+		tkey->rx_hdr[12] = *(skb->data + hdr_len - 2) & 0x07;
+	}
+	// }
+
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	if (michael_mic(tkey->rx_tfm_michael, &tkey->key[24], tkey->rx_hdr,
+				skb->data + hdr_len, skb->len - 8 - hdr_len, mic))
+#else
+	if (michael_mic(tkey->rx_tfm_michael, &tkey->key[24], tkey->rx_hdr,
+				skb->data + hdr_len, skb->len - 8 - hdr_len, mic))
+#endif
+            	return -1;
+	if (memcmp(mic, skb->data + skb->len - 8, 8) != 0) {
+		struct ieee80211_hdr_4addr *hdr;
+		hdr = (struct ieee80211_hdr_4addr *) skb->data;
+		printk(KERN_DEBUG "%s: Michael MIC verification failed for "
+		       "MSDU from " MAC_FMT " keyidx=%d\n",
+		       skb->dev ? skb->dev->name : "N/A", MAC_ARG(hdr->addr2),
+		       keyidx);
+		if (skb->dev)
+			ieee80211_michael_mic_failure(skb->dev, hdr, keyidx);
+		tkey->dot11RSNAStatsTKIPLocalMICFailures++;
+		return -1;
+	}
+
+	/* Update TSC counters for RX now that the packet verification has
+	 * completed. */
+	tkey->rx_iv32 = tkey->rx_iv32_new;
+	tkey->rx_iv16 = tkey->rx_iv16_new;
+
+	skb_trim(skb, skb->len - 8);
+
+	return 0;
+}
+
+
+static int ieee80211_tkip_set_key(void *key, int len, u8 *seq, void *priv)
+{
+	struct ieee80211_tkip_data *tkey = priv;
+	int keyidx;
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	struct crypto_tfm *tfm = tkey->tx_tfm_michael;
+	struct crypto_tfm *tfm2 = tkey->tx_tfm_arc4;
+	struct crypto_tfm *tfm3 = tkey->rx_tfm_michael;
+	struct crypto_tfm *tfm4 = tkey->rx_tfm_arc4;
+#else
+	struct crypto_hash *tfm = tkey->tx_tfm_michael;
+	struct crypto_blkcipher *tfm2 = tkey->tx_tfm_arc4;
+	struct crypto_hash *tfm3 = tkey->rx_tfm_michael;
+	struct crypto_blkcipher *tfm4 = tkey->rx_tfm_arc4;
+#endif
+
+	keyidx = tkey->key_idx;
+	memset(tkey, 0, sizeof(*tkey));
+	tkey->key_idx = keyidx;
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	tkey->tx_tfm_michael = tfm;
+	tkey->tx_tfm_arc4 = tfm2;
+	tkey->rx_tfm_michael = tfm3;
+	tkey->rx_tfm_arc4 = tfm4;
+#else
+	tkey->tx_tfm_michael = tfm;
+	tkey->tx_tfm_arc4 = tfm2;
+	tkey->rx_tfm_michael = tfm3;
+	tkey->rx_tfm_arc4 = tfm4;
+#endif
+
+	if (len == TKIP_KEY_LEN) {
+		memcpy(tkey->key, key, TKIP_KEY_LEN);
+		tkey->key_set = 1;
+		tkey->tx_iv16 = 1; /* TSC is initialized to 1 */
+		if (seq) {
+			tkey->rx_iv32 = (seq[5] << 24) | (seq[4] << 16) |
+				(seq[3] << 8) | seq[2];
+			tkey->rx_iv16 = (seq[1] << 8) | seq[0];
+		}
+	} else if (len == 0)
+		tkey->key_set = 0;
+	else
+		return -1;
+
+	return 0;
+}
+
+
+static int ieee80211_tkip_get_key(void *key, int len, u8 *seq, void *priv)
+{
+	struct ieee80211_tkip_data *tkey = priv;
+
+	if (len < TKIP_KEY_LEN)
+		return -1;
+
+	if (!tkey->key_set)
+		return 0;
+	memcpy(key, tkey->key, TKIP_KEY_LEN);
+
+	if (seq) {
+		/* Return the sequence number of the last transmitted frame. */
+		u16 iv16 = tkey->tx_iv16;
+		u32 iv32 = tkey->tx_iv32;
+		if (iv16 == 0)
+			iv32--;
+		iv16--;
+		seq[0] = tkey->tx_iv16;
+		seq[1] = tkey->tx_iv16 >> 8;
+		seq[2] = tkey->tx_iv32;
+		seq[3] = tkey->tx_iv32 >> 8;
+		seq[4] = tkey->tx_iv32 >> 16;
+		seq[5] = tkey->tx_iv32 >> 24;
+	}
+
+	return TKIP_KEY_LEN;
+}
+
+
+static char * ieee80211_tkip_print_stats(char *p, void *priv)
+{
+	struct ieee80211_tkip_data *tkip = priv;
+	p += sprintf(p, "key[%d] alg=TKIP key_set=%d "
+		     "tx_pn=%02x%02x%02x%02x%02x%02x "
+		     "rx_pn=%02x%02x%02x%02x%02x%02x "
+		     "replays=%d icv_errors=%d local_mic_failures=%d\n",
+		     tkip->key_idx, tkip->key_set,
+		     (tkip->tx_iv32 >> 24) & 0xff,
+		     (tkip->tx_iv32 >> 16) & 0xff,
+		     (tkip->tx_iv32 >> 8) & 0xff,
+		     tkip->tx_iv32 & 0xff,
+		     (tkip->tx_iv16 >> 8) & 0xff,
+		     tkip->tx_iv16 & 0xff,
+		     (tkip->rx_iv32 >> 24) & 0xff,
+		     (tkip->rx_iv32 >> 16) & 0xff,
+		     (tkip->rx_iv32 >> 8) & 0xff,
+		     tkip->rx_iv32 & 0xff,
+		     (tkip->rx_iv16 >> 8) & 0xff,
+		     tkip->rx_iv16 & 0xff,
+		     tkip->dot11RSNAStatsTKIPReplays,
+		     tkip->dot11RSNAStatsTKIPICVErrors,
+		     tkip->dot11RSNAStatsTKIPLocalMICFailures);
+	return p;
+}
+
+
+static struct ieee80211_crypto_ops ieee80211_crypt_tkip = {
+	.name			= "TKIP",
+	.init			= ieee80211_tkip_init,
+	.deinit			= ieee80211_tkip_deinit,
+	.encrypt_mpdu		= ieee80211_tkip_encrypt,
+	.decrypt_mpdu		= ieee80211_tkip_decrypt,
+	.encrypt_msdu		= ieee80211_michael_mic_add,
+	.decrypt_msdu		= ieee80211_michael_mic_verify,
+	.set_key		= ieee80211_tkip_set_key,
+	.get_key		= ieee80211_tkip_get_key,
+	.print_stats		= ieee80211_tkip_print_stats,
+	.extra_prefix_len	= 4 + 4, /* IV + ExtIV */
+	.extra_postfix_len	= 8 + 4, /* MIC + ICV */
+	.owner		        = THIS_MODULE,
+};
+
+
+static int __init ieee80211_crypto_tkip_init(void)
+{
+	return ieee80211_register_crypto_ops(&ieee80211_crypt_tkip);
+}
+
+
+static void __exit ieee80211_crypto_tkip_exit(void)
+{
+	ieee80211_unregister_crypto_ops(&ieee80211_crypt_tkip);
+}
+
+void ieee80211_tkip_null(void)
+{
+//    printk("============>%s()\n", __FUNCTION__);
+        return;
+}
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+EXPORT_SYMBOL(ieee80211_tkip_null);
+#else
+EXPORT_SYMBOL_NOVERS(ieee80211_tkip_null);
+#endif
+
+module_init(ieee80211_crypto_tkip_init);
+module_exit(ieee80211_crypto_tkip_exit);
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt_wep.c b/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt_wep.c
new file mode 100644
index 0000000..7e39432
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211_crypt_wep.c
@@ -0,0 +1,397 @@
+/*
+ * Host AP crypt: host-based WEP encryption implementation for Host AP driver
+ *
+ * Copyright (c) 2002-2004, Jouni Malinen <jkmaline@cc.hut.fi>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. See README and COPYING for
+ * more details.
+ */
+
+//#include <linux/config.h>
+#include <linux/version.h>
+#include <linux/module.h>
+#include <linux/init.h>
+#include <linux/slab.h>
+#include <linux/random.h>
+#include <linux/skbuff.h>
+#include <asm/string.h>
+
+#include "ieee80211.h"
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,20))
+//#include "crypto_compat.h"
+#endif
+
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+#include "rtl_crypto.h"
+#else
+#include <linux/crypto.h>
+#endif
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20)
+    #include <asm/scatterlist.h>
+#else
+    #include <linux/scatterlist.h>
+#endif
+//#include <asm/scatterlist.h>
+#include <linux/crc32.h>
+//
+/*
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+#include "rtl_crypto.h"
+#else
+#include <linux/crypto.h>
+#endif
+
+#include <asm/scatterlist.h>
+#include <linux/crc32.h>
+*/
+MODULE_AUTHOR("Jouni Malinen");
+MODULE_DESCRIPTION("Host AP crypt: WEP");
+MODULE_LICENSE("GPL");
+#ifndef OPENSUSE_SLED
+#define OPENSUSE_SLED 0
+#endif
+
+struct prism2_wep_data {
+	u32 iv;
+#define WEP_KEY_LEN 13
+	u8 key[WEP_KEY_LEN + 1];
+	u8 key_len;
+	u8 key_idx;
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	struct crypto_tfm *tfm;
+	#else
+        struct crypto_blkcipher *tx_tfm;
+        struct crypto_blkcipher *rx_tfm;
+        #endif
+};
+
+
+static void * prism2_wep_init(int keyidx)
+{
+	struct prism2_wep_data *priv;
+
+	priv = kmalloc(sizeof(*priv), GFP_ATOMIC);
+	if (priv == NULL)
+		goto fail;
+	memset(priv, 0, sizeof(*priv));
+	priv->key_idx = keyidx;
+
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	priv->tfm = crypto_alloc_tfm("arc4", 0);
+	if (priv->tfm == NULL) {
+		printk(KERN_DEBUG "ieee80211_crypt_wep: could not allocate "
+		       "crypto API arc4\n");
+		goto fail;
+	}
+	#else
+	priv->tx_tfm = crypto_alloc_blkcipher("ecb(arc4)", 0, CRYPTO_ALG_ASYNC);
+        if (IS_ERR(priv->tx_tfm)) {
+                printk(KERN_DEBUG "ieee80211_crypt_wep: could not allocate "
+                       "crypto API arc4\n");
+                priv->tx_tfm = NULL;
+                goto fail;
+        }
+        priv->rx_tfm = crypto_alloc_blkcipher("ecb(arc4)", 0, CRYPTO_ALG_ASYNC);
+        if (IS_ERR(priv->rx_tfm)) {
+                printk(KERN_DEBUG "ieee80211_crypt_wep: could not allocate "
+                       "crypto API arc4\n");
+                priv->rx_tfm = NULL;
+                goto fail;
+        }
+        #endif
+
+	/* start WEP IV from a random value */
+	get_random_bytes(&priv->iv, 4);
+
+	return priv;
+
+fail:
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	if (priv) {
+		if (priv->tfm)
+			crypto_free_tfm(priv->tfm);
+		kfree(priv);
+	}
+	#else
+	if (priv) {
+                if (priv->tx_tfm)
+                        crypto_free_blkcipher(priv->tx_tfm);
+                if (priv->rx_tfm)
+                        crypto_free_blkcipher(priv->rx_tfm);
+                kfree(priv);
+        }
+        #endif
+	return NULL;
+}
+
+
+static void prism2_wep_deinit(void *priv)
+{
+	struct prism2_wep_data *_priv = priv;
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+	if (_priv && _priv->tfm)
+		crypto_free_tfm(_priv->tfm);
+	#else
+	if (_priv) {
+                if (_priv->tx_tfm)
+                        crypto_free_blkcipher(_priv->tx_tfm);
+                if (_priv->rx_tfm)
+                        crypto_free_blkcipher(_priv->rx_tfm);
+        }
+        #endif
+	kfree(priv);
+}
+
+/* Perform WEP encryption on given skb that has at least 4 bytes of headroom
+ * for IV and 4 bytes of tailroom for ICV. Both IV and ICV will be transmitted,
+ * so the payload length increases with 8 bytes.
+ *
+ * WEP frame payload: IV + TX key idx, RC4(data), ICV = RC4(CRC32(data))
+ */
+static int prism2_wep_encrypt(struct sk_buff *skb, int hdr_len, void *priv)
+{
+	struct prism2_wep_data *wep = priv;
+	u32 klen, len;
+	u8 key[WEP_KEY_LEN + 3];
+	u8 *pos;
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	#if((LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,21)) || (OPENSUSE_SLED))
+	struct blkcipher_desc desc = {.tfm = wep->tx_tfm};
+	#endif
+	u32 crc;
+	u8 *icv;
+	struct scatterlist sg;
+	if (skb_headroom(skb) < 4 || skb_tailroom(skb) < 4 ||
+	    skb->len < hdr_len)
+		return -1;
+
+	len = skb->len - hdr_len;
+	pos = skb_push(skb, 4);
+	memmove(pos, pos + 4, hdr_len);
+	pos += hdr_len;
+
+	klen = 3 + wep->key_len;
+
+	wep->iv++;
+
+	/* Fluhrer, Mantin, and Shamir have reported weaknesses in the key
+	 * scheduling algorithm of RC4. At least IVs (KeyByte + 3, 0xff, N)
+	 * can be used to speedup attacks, so avoid using them. */
+	if ((wep->iv & 0xff00) == 0xff00) {
+		u8 B = (wep->iv >> 16) & 0xff;
+		if (B >= 3 && B < klen)
+			wep->iv += 0x0100;
+	}
+
+	/* Prepend 24-bit IV to RC4 key and TX frame */
+	*pos++ = key[0] = (wep->iv >> 16) & 0xff;
+	*pos++ = key[1] = (wep->iv >> 8) & 0xff;
+	*pos++ = key[2] = wep->iv & 0xff;
+	*pos++ = wep->key_idx << 6;
+
+	/* Copy rest of the WEP key (the secret part) */
+	memcpy(key + 3, wep->key, wep->key_len);
+
+	if (!tcb_desc->bHwSec)
+	{
+
+		/* Append little-endian CRC32 and encrypt it to produce ICV */
+	#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+		crc = ~crc32_le(~0, pos, len);
+	#else
+		crc = ~ether_crc_le(len, pos);
+	#endif
+		icv = skb_put(skb, 4);
+		icv[0] = crc;
+		icv[1] = crc >> 8;
+		icv[2] = crc >> 16;
+		icv[3] = crc >> 24;
+
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+		crypto_cipher_setkey(wep->tfm, key, klen);
+		sg.page = virt_to_page(pos);
+		sg.offset = offset_in_page(pos);
+		sg.length = len + 4;
+		crypto_cipher_encrypt(wep->tfm, &sg, &sg, len + 4);
+		return 0;
+	#else
+		crypto_blkcipher_setkey(wep->tx_tfm, key, klen);
+	#if(LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24))
+		sg.page = virt_to_page(pos);
+		sg.offset = offset_in_page(pos);
+		sg.length = len + 4;
+	#else
+		sg_init_one(&sg, pos, len+4);
+	#endif
+		return crypto_blkcipher_encrypt(&desc, &sg, &sg, len + 4);
+	#endif
+	}
+
+	return 0;
+}
+
+
+/* Perform WEP decryption on given buffer. Buffer includes whole WEP part of
+ * the frame: IV (4 bytes), encrypted payload (including SNAP header),
+ * ICV (4 bytes). len includes both IV and ICV.
+ *
+ * Returns 0 if frame was decrypted successfully and ICV was correct and -1 on
+ * failure. If frame is OK, IV and ICV will be removed.
+ */
+static int prism2_wep_decrypt(struct sk_buff *skb, int hdr_len, void *priv)
+{
+	struct prism2_wep_data *wep = priv;
+	u32  klen, plen;
+	u8 key[WEP_KEY_LEN + 3];
+	u8 keyidx, *pos;
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	#if((LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,21)) || (OPENSUSE_SLED))
+	struct blkcipher_desc desc = {.tfm = wep->rx_tfm};
+	#endif
+	u32 crc;
+	u8 icv[4];
+	struct scatterlist sg;
+	if (skb->len < hdr_len + 8)
+		return -1;
+
+	pos = skb->data + hdr_len;
+	key[0] = *pos++;
+	key[1] = *pos++;
+	key[2] = *pos++;
+	keyidx = *pos++ >> 6;
+	if (keyidx != wep->key_idx)
+		return -1;
+
+	klen = 3 + wep->key_len;
+
+	/* Copy rest of the WEP key (the secret part) */
+	memcpy(key + 3, wep->key, wep->key_len);
+
+	/* Apply RC4 to data and compute CRC32 over decrypted data */
+	plen = skb->len - hdr_len - 8;
+
+	if (!tcb_desc->bHwSec)
+	{
+#if((LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)) && (!OPENSUSE_SLED))
+		crypto_cipher_setkey(wep->tfm, key, klen);
+		sg.page = virt_to_page(pos);
+		sg.offset = offset_in_page(pos);
+		sg.length = plen + 4;
+		crypto_cipher_decrypt(wep->tfm, &sg, &sg, plen + 4);
+	#else
+		crypto_blkcipher_setkey(wep->rx_tfm, key, klen);
+	#if(LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24))
+		sg.page = virt_to_page(pos);
+		sg.offset = offset_in_page(pos);
+		sg.length = plen + 4;
+	#else
+		sg_init_one(&sg, pos, plen+4);
+	#endif
+		if (crypto_blkcipher_decrypt(&desc, &sg, &sg, plen + 4))
+			return -7;
+	#endif
+	#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+		crc = ~crc32_le(~0, pos, plen);
+	#else
+		crc = ~ether_crc_le(plen, pos);
+	#endif
+		icv[0] = crc;
+		icv[1] = crc >> 8;
+		icv[2] = crc >> 16;
+		icv[3] = crc >> 24;
+		if (memcmp(icv, pos + plen, 4) != 0) {
+			/* ICV mismatch - drop frame */
+			return -2;
+		}
+	}
+	/* Remove IV and ICV */
+	memmove(skb->data + 4, skb->data, hdr_len);
+	skb_pull(skb, 4);
+	skb_trim(skb, skb->len - 4);
+
+	return 0;
+}
+
+
+static int prism2_wep_set_key(void *key, int len, u8 *seq, void *priv)
+{
+	struct prism2_wep_data *wep = priv;
+
+	if (len < 0 || len > WEP_KEY_LEN)
+		return -1;
+
+	memcpy(wep->key, key, len);
+	wep->key_len = len;
+
+	return 0;
+}
+
+
+static int prism2_wep_get_key(void *key, int len, u8 *seq, void *priv)
+{
+	struct prism2_wep_data *wep = priv;
+
+	if (len < wep->key_len)
+		return -1;
+
+	memcpy(key, wep->key, wep->key_len);
+
+	return wep->key_len;
+}
+
+
+static char * prism2_wep_print_stats(char *p, void *priv)
+{
+	struct prism2_wep_data *wep = priv;
+	p += sprintf(p, "key[%d] alg=WEP len=%d\n",
+		     wep->key_idx, wep->key_len);
+	return p;
+}
+
+
+static struct ieee80211_crypto_ops ieee80211_crypt_wep = {
+	.name			= "WEP",
+	.init			= prism2_wep_init,
+	.deinit			= prism2_wep_deinit,
+	.encrypt_mpdu		= prism2_wep_encrypt,
+	.decrypt_mpdu		= prism2_wep_decrypt,
+	.encrypt_msdu		= NULL,
+	.decrypt_msdu		= NULL,
+	.set_key		= prism2_wep_set_key,
+	.get_key		= prism2_wep_get_key,
+	.print_stats		= prism2_wep_print_stats,
+	.extra_prefix_len	= 4, /* IV */
+	.extra_postfix_len	= 4, /* ICV */
+	.owner			= THIS_MODULE,
+};
+
+
+static int __init ieee80211_crypto_wep_init(void)
+{
+	return ieee80211_register_crypto_ops(&ieee80211_crypt_wep);
+}
+
+
+static void __exit ieee80211_crypto_wep_exit(void)
+{
+	ieee80211_unregister_crypto_ops(&ieee80211_crypt_wep);
+}
+
+void ieee80211_wep_null(void)
+{
+//	printk("============>%s()\n", __FUNCTION__);
+        return;
+}
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+EXPORT_SYMBOL(ieee80211_wep_null);
+#else
+EXPORT_SYMBOL_NOVERS(ieee80211_wep_null);
+#endif
+
+module_init(ieee80211_crypto_wep_init);
+module_exit(ieee80211_crypto_wep_exit);
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211_module.c b/drivers/staging/rtl8192su/ieee80211/ieee80211_module.c
new file mode 100644
index 0000000..f408b45
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211_module.c
@@ -0,0 +1,394 @@
+/*******************************************************************************
+
+  Copyright(c) 2004 Intel Corporation. All rights reserved.
+
+  Portions of this file are based on the WEP enablement code provided by the
+  Host AP project hostap-drivers v0.1.3
+  Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen
+  <jkmaline@cc.hut.fi>
+  Copyright (c) 2002-2003, Jouni Malinen <jkmaline@cc.hut.fi>
+
+  This program is free software; you can redistribute it and/or modify it
+  under the terms of version 2 of the GNU General Public License as
+  published by the Free Software Foundation.
+
+  This program is distributed in the hope that it will be useful, but WITHOUT
+  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+  more details.
+
+  You should have received a copy of the GNU General Public License along with
+  this program; if not, write to the Free Software Foundation, Inc., 59
+  Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+
+  The full GNU General Public License is included in this distribution in the
+  file called LICENSE.
+
+  Contact Information:
+  James P. Ketrenos <ipw2100-admin@linux.intel.com>
+  Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
+
+*******************************************************************************/
+
+#include <linux/compiler.h>
+//#include <linux/config.h>
+#include <linux/errno.h>
+#include <linux/if_arp.h>
+#include <linux/in6.h>
+#include <linux/in.h>
+#include <linux/ip.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/netdevice.h>
+#include <linux/pci.h>
+#include <linux/proc_fs.h>
+#include <linux/skbuff.h>
+#include <linux/slab.h>
+#include <linux/tcp.h>
+#include <linux/types.h>
+#include <linux/version.h>
+#include <linux/wireless.h>
+#include <linux/etherdevice.h>
+#include <asm/uaccess.h>
+#include <net/arp.h>
+
+#include "ieee80211.h"
+
+MODULE_DESCRIPTION("802.11 data/management/control stack");
+MODULE_AUTHOR("Copyright (C) 2004 Intel Corporation <jketreno@linux.intel.com>");
+MODULE_LICENSE("GPL");
+
+#define DRV_NAME "ieee80211"
+
+static inline int ieee80211_networks_allocate(struct ieee80211_device *ieee)
+{
+	if (ieee->networks)
+		return 0;
+
+	ieee->networks = kmalloc(
+		MAX_NETWORK_COUNT * sizeof(struct ieee80211_network),
+		GFP_KERNEL);
+	if (!ieee->networks) {
+		printk(KERN_WARNING "%s: Out of memory allocating beacons\n",
+		       ieee->dev->name);
+		return -ENOMEM;
+	}
+
+	memset(ieee->networks, 0,
+	       MAX_NETWORK_COUNT * sizeof(struct ieee80211_network));
+
+	return 0;
+}
+
+static inline void ieee80211_networks_free(struct ieee80211_device *ieee)
+{
+	if (!ieee->networks)
+		return;
+	kfree(ieee->networks);
+	ieee->networks = NULL;
+}
+
+static inline void ieee80211_networks_initialize(struct ieee80211_device *ieee)
+{
+	int i;
+
+	INIT_LIST_HEAD(&ieee->network_free_list);
+	INIT_LIST_HEAD(&ieee->network_list);
+	for (i = 0; i < MAX_NETWORK_COUNT; i++)
+		list_add_tail(&ieee->networks[i].list, &ieee->network_free_list);
+}
+
+
+struct net_device *alloc_ieee80211(int sizeof_priv)
+{
+	struct ieee80211_device *ieee;
+	struct net_device *dev;
+	int i,err;
+
+	IEEE80211_DEBUG_INFO("Initializing...\n");
+
+	dev = alloc_etherdev(sizeof(struct ieee80211_device) + sizeof_priv);
+	if (!dev) {
+		IEEE80211_ERROR("Unable to network device.\n");
+		goto failed;
+	}
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0))
+	ieee = netdev_priv(dev);
+#else
+	ieee = (struct ieee80211_device *)dev->priv;
+#endif
+	dev->hard_start_xmit = ieee80211_xmit;
+
+	memset(ieee, 0, sizeof(struct ieee80211_device)+sizeof_priv);
+	ieee->dev = dev;
+
+	err = ieee80211_networks_allocate(ieee);
+	if (err) {
+		IEEE80211_ERROR("Unable to allocate beacon storage: %d\n",
+				err);
+		goto failed;
+	}
+	ieee80211_networks_initialize(ieee);
+
+
+	/* Default fragmentation threshold is maximum payload size */
+	ieee->fts = DEFAULT_FTS;
+	ieee->scan_age = DEFAULT_MAX_SCAN_AGE;
+	ieee->open_wep = 1;
+
+	/* Default to enabling full open WEP with host based encrypt/decrypt */
+	ieee->host_encrypt = 1;
+	ieee->host_decrypt = 1;
+	ieee->ieee802_1x = 1; /* Default to supporting 802.1x */
+
+	INIT_LIST_HEAD(&ieee->crypt_deinit_list);
+	init_timer(&ieee->crypt_deinit_timer);
+	ieee->crypt_deinit_timer.data = (unsigned long)ieee;
+	ieee->crypt_deinit_timer.function = ieee80211_crypt_deinit_handler;
+
+	spin_lock_init(&ieee->lock);
+	spin_lock_init(&ieee->wpax_suitlist_lock);
+	spin_lock_init(&ieee->bw_spinlock);
+	spin_lock_init(&ieee->reorder_spinlock);
+	//added by WB
+	atomic_set(&(ieee->atm_chnlop), 0);
+	atomic_set(&(ieee->atm_swbw), 0);
+
+	ieee->wpax_type_set = 0;
+ 	ieee->wpa_enabled = 0;
+ 	ieee->tkip_countermeasures = 0;
+ 	ieee->drop_unencrypted = 0;
+ 	ieee->privacy_invoked = 0;
+ 	ieee->ieee802_1x = 1;
+	ieee->raw_tx = 0;
+	//ieee->hwsec_support = 1; //defalt support hw security. //use module_param instead.
+	ieee->hwsec_active = 0; //disable hwsec, switch it on when necessary.
+
+	ieee80211_softmac_init(ieee);
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,13))
+	ieee->pHTInfo = (RT_HIGH_THROUGHPUT*)kzalloc(sizeof(RT_HIGH_THROUGHPUT), GFP_KERNEL);
+#else
+	ieee->pHTInfo = (RT_HIGH_THROUGHPUT*)kmalloc(sizeof(RT_HIGH_THROUGHPUT), GFP_KERNEL);
+	memset(ieee->pHTInfo,0,sizeof(RT_HIGH_THROUGHPUT));
+#endif
+	if (ieee->pHTInfo == NULL)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't alloc memory for HTInfo\n");
+		return NULL;
+	}
+	HTUpdateDefaultSetting(ieee);
+	HTInitializeHTInfo(ieee); //may move to other place.
+	TSInitialize(ieee);
+#if 0
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+ 	INIT_WORK(&ieee->ht_onAssRsp, (void(*)(void*)) HTOnAssocRsp_wq);
+#else
+	INIT_WORK(&ieee->ht_onAssRsp, (void(*)(void*)) HTOnAssocRsp_wq, ieee);
+#endif
+#endif
+	for (i = 0; i < IEEE_IBSS_MAC_HASH_SIZE; i++)
+		INIT_LIST_HEAD(&ieee->ibss_mac_hash[i]);
+
+	for (i = 0; i < 17; i++) {
+	  ieee->last_rxseq_num[i] = -1;
+	  ieee->last_rxfrag_num[i] = -1;
+	  ieee->last_packet_time[i] = 0;
+	}
+
+//These function were added to load crypte module autoly
+	ieee80211_tkip_null();
+	ieee80211_wep_null();
+	ieee80211_ccmp_null();
+
+	return dev;
+
+ failed:
+	if (dev)
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0))
+		free_netdev(dev);
+#else
+		kfree(dev);
+#endif
+	return NULL;
+}
+
+
+void free_ieee80211(struct net_device *dev)
+{
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0))
+	struct ieee80211_device *ieee = netdev_priv(dev);
+#else
+	struct ieee80211_device *ieee = (struct ieee80211_device *)dev->priv;
+#endif
+	int i;
+	//struct list_head *p, *q;
+//	del_timer_sync(&ieee->SwBwTimer);
+#if 1
+	if (ieee->pHTInfo != NULL)
+	{
+		kfree(ieee->pHTInfo);
+		ieee->pHTInfo = NULL;
+	}
+#endif
+	RemoveAllTS(ieee);
+	ieee80211_softmac_free(ieee);
+	del_timer_sync(&ieee->crypt_deinit_timer);
+	ieee80211_crypt_deinit_entries(ieee, 1);
+
+	for (i = 0; i < WEP_KEYS; i++) {
+		struct ieee80211_crypt_data *crypt = ieee->crypt[i];
+		if (crypt) {
+			if (crypt->ops) {
+				crypt->ops->deinit(crypt->priv);
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
+				module_put(crypt->ops->owner);
+#else
+				__MOD_DEC_USE_COUNT(crypt->ops->owner);
+#endif
+			}
+			kfree(crypt);
+			ieee->crypt[i] = NULL;
+		}
+	}
+
+	ieee80211_networks_free(ieee);
+#if 0
+	for (i = 0; i < IEEE_IBSS_MAC_HASH_SIZE; i++) {
+		list_for_each_safe(p, q, &ieee->ibss_mac_hash[i]) {
+			kfree(list_entry(p, struct ieee_ibss_seq, list));
+			list_del(p);
+		}
+	}
+
+#endif
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0))
+	free_netdev(dev);
+#else
+	kfree(dev);
+#endif
+}
+
+#ifdef CONFIG_IEEE80211_DEBUG
+
+u32 ieee80211_debug_level = 0;
+static int debug = \
+	//		    IEEE80211_DL_INFO	|
+	//		    IEEE80211_DL_WX	|
+	//		    IEEE80211_DL_SCAN	|
+	//		    IEEE80211_DL_STATE	|
+	//		    IEEE80211_DL_MGMT	|
+	//		    IEEE80211_DL_FRAG	|
+	//		    IEEE80211_DL_EAP	|
+	//		    IEEE80211_DL_DROP	|
+	//		    IEEE80211_DL_TX	|
+	//		    IEEE80211_DL_RX	|
+			    //IEEE80211_DL_QOS    |
+	//		    IEEE80211_DL_HT 	|
+	//		    IEEE80211_DL_TS	|
+//			    IEEE80211_DL_BA 	|
+	//		    IEEE80211_DL_REORDER|
+//			    IEEE80211_DL_TRACE  |
+			    //IEEE80211_DL_DATA	|
+			    IEEE80211_DL_ERR	  //awayls open this flags to show error out
+			    ;
+struct proc_dir_entry *ieee80211_proc = NULL;
+
+static int show_debug_level(char *page, char **start, off_t offset,
+			    int count, int *eof, void *data)
+{
+	return snprintf(page, count, "0x%08X\n", ieee80211_debug_level);
+}
+
+static int store_debug_level(struct file *file, const char *buffer,
+			     unsigned long count, void *data)
+{
+	char buf[] = "0x00000000";
+	unsigned long len = min(sizeof(buf) - 1, (u32)count);
+	char *p = (char *)buf;
+	unsigned long val;
+
+	if (copy_from_user(buf, buffer, len))
+		return count;
+	buf[len] = 0;
+	if (p[1] == 'x' || p[1] == 'X' || p[0] == 'x' || p[0] == 'X') {
+		p++;
+		if (p[0] == 'x' || p[0] == 'X')
+			p++;
+		val = simple_strtoul(p, &p, 16);
+	} else
+		val = simple_strtoul(p, &p, 10);
+	if (p == buf)
+		printk(KERN_INFO DRV_NAME
+		       ": %s is not in hex or decimal form.\n", buf);
+	else
+		ieee80211_debug_level = val;
+
+	return strnlen(buf, count);
+}
+
+static int __init ieee80211_init(void)
+{
+	struct proc_dir_entry *e;
+
+	ieee80211_debug_level = debug;
+#if(LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24))
+	ieee80211_proc = create_proc_entry(DRV_NAME, S_IFDIR, proc_net);
+#else
+	ieee80211_proc = create_proc_entry(DRV_NAME, S_IFDIR, init_net.proc_net);
+#endif
+	if (ieee80211_proc == NULL) {
+		IEEE80211_ERROR("Unable to create " DRV_NAME
+				" proc directory\n");
+		return -EIO;
+	}
+	e = create_proc_entry("debug_level", S_IFREG | S_IRUGO | S_IWUSR,
+			      ieee80211_proc);
+	if (!e) {
+#if(LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24))
+		remove_proc_entry(DRV_NAME, proc_net);
+#else
+		remove_proc_entry(DRV_NAME, init_net.proc_net);
+#endif
+		ieee80211_proc = NULL;
+		return -EIO;
+	}
+	e->read_proc = show_debug_level;
+	e->write_proc = store_debug_level;
+	e->data = NULL;
+
+	return 0;
+}
+
+static void __exit ieee80211_exit(void)
+{
+	if (ieee80211_proc) {
+		remove_proc_entry("debug_level", ieee80211_proc);
+#if(LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24))
+		remove_proc_entry(DRV_NAME, proc_net);
+#else
+		remove_proc_entry(DRV_NAME, init_net.proc_net);
+#endif
+		ieee80211_proc = NULL;
+	}
+}
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+#include <linux/moduleparam.h>
+module_param(debug, int, 0444);
+MODULE_PARM_DESC(debug, "debug output mask");
+
+
+module_exit(ieee80211_exit);
+module_init(ieee80211_init);
+#endif
+#endif
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+EXPORT_SYMBOL(alloc_ieee80211);
+EXPORT_SYMBOL(free_ieee80211);
+#else
+EXPORT_SYMBOL_NOVERS(alloc_ieee80211);
+EXPORT_SYMBOL_NOVERS(free_ieee80211);
+#endif
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211_rx.c b/drivers/staging/rtl8192su/ieee80211/ieee80211_rx.c
new file mode 100644
index 0000000..2b2ffd3
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211_rx.c
@@ -0,0 +1,2832 @@
+/*
+ * Original code based Host AP (software wireless LAN access point) driver
+ * for Intersil Prism2/2.5/3 - hostap.o module, common routines
+ *
+ * Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen
+ * <jkmaline@cc.hut.fi>
+ * Copyright (c) 2002-2003, Jouni Malinen <jkmaline@cc.hut.fi>
+ * Copyright (c) 2004, Intel Corporation
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. See README and COPYING for
+ * more details.
+ ******************************************************************************
+
+  Few modifications for Realtek's Wi-Fi drivers by
+  Andrea Merello <andreamrl@tiscali.it>
+
+  A special thanks goes to Realtek for their support !
+
+******************************************************************************/
+
+
+#include <linux/compiler.h>
+//#include <linux/config.h>
+#include <linux/errno.h>
+#include <linux/if_arp.h>
+#include <linux/in6.h>
+#include <linux/in.h>
+#include <linux/ip.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/netdevice.h>
+#include <linux/pci.h>
+#include <linux/proc_fs.h>
+#include <linux/skbuff.h>
+#include <linux/slab.h>
+#include <linux/tcp.h>
+#include <linux/types.h>
+#include <linux/version.h>
+#include <linux/wireless.h>
+#include <linux/etherdevice.h>
+#include <asm/uaccess.h>
+#include <linux/ctype.h>
+
+#include "ieee80211.h"
+#ifdef ENABLE_DOT11D
+#include "dot11d.h"
+#endif
+static inline void ieee80211_monitor_rx(struct ieee80211_device *ieee,
+					struct sk_buff *skb,
+					struct ieee80211_rx_stats *rx_stats)
+{
+	struct ieee80211_hdr_4addr *hdr = (struct ieee80211_hdr_4addr *)skb->data;
+	u16 fc = le16_to_cpu(hdr->frame_ctl);
+
+	skb->dev = ieee->dev;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
+        skb_reset_mac_header(skb);
+#else
+        skb->mac.raw = skb->data;
+#endif
+
+	skb_pull(skb, ieee80211_get_hdrlen(fc));
+	skb->pkt_type = PACKET_OTHERHOST;
+	skb->protocol = __constant_htons(ETH_P_80211_RAW);
+	memset(skb->cb, 0, sizeof(skb->cb));
+	netif_rx(skb);
+}
+
+
+/* Called only as a tasklet (software IRQ) */
+static struct ieee80211_frag_entry *
+ieee80211_frag_cache_find(struct ieee80211_device *ieee, unsigned int seq,
+			  unsigned int frag, u8 tid,u8 *src, u8 *dst)
+{
+	struct ieee80211_frag_entry *entry;
+	int i;
+
+	for (i = 0; i < IEEE80211_FRAG_CACHE_LEN; i++) {
+		entry = &ieee->frag_cache[tid][i];
+		if (entry->skb != NULL &&
+		    time_after(jiffies, entry->first_frag_time + 2 * HZ)) {
+			IEEE80211_DEBUG_FRAG(
+				"expiring fragment cache entry "
+				"seq=%u last_frag=%u\n",
+				entry->seq, entry->last_frag);
+			dev_kfree_skb_any(entry->skb);
+			entry->skb = NULL;
+		}
+
+		if (entry->skb != NULL && entry->seq == seq &&
+		    (entry->last_frag + 1 == frag || frag == -1) &&
+		    memcmp(entry->src_addr, src, ETH_ALEN) == 0 &&
+		    memcmp(entry->dst_addr, dst, ETH_ALEN) == 0)
+			return entry;
+	}
+
+	return NULL;
+}
+
+/* Called only as a tasklet (software IRQ) */
+static struct sk_buff *
+ieee80211_frag_cache_get(struct ieee80211_device *ieee,
+			 struct ieee80211_hdr_4addr *hdr)
+{
+	struct sk_buff *skb = NULL;
+	u16 fc = le16_to_cpu(hdr->frame_ctl);
+	u16 sc = le16_to_cpu(hdr->seq_ctl);
+	unsigned int frag = WLAN_GET_SEQ_FRAG(sc);
+	unsigned int seq = WLAN_GET_SEQ_SEQ(sc);
+	struct ieee80211_frag_entry *entry;
+	struct ieee80211_hdr_3addrqos *hdr_3addrqos;
+	struct ieee80211_hdr_4addrqos *hdr_4addrqos;
+	u8 tid;
+
+	if (((fc & IEEE80211_FCTL_DSTODS) == IEEE80211_FCTL_DSTODS)&&IEEE80211_QOS_HAS_SEQ(fc)) {
+	  hdr_4addrqos = (struct ieee80211_hdr_4addrqos *)hdr;
+	  tid = le16_to_cpu(hdr_4addrqos->qos_ctl) & IEEE80211_QCTL_TID;
+	  tid = UP2AC(tid);
+	  tid ++;
+	} else if (IEEE80211_QOS_HAS_SEQ(fc)) {
+	  hdr_3addrqos = (struct ieee80211_hdr_3addrqos *)hdr;
+	  tid = le16_to_cpu(hdr_3addrqos->qos_ctl) & IEEE80211_QCTL_TID;
+	  tid = UP2AC(tid);
+	  tid ++;
+	} else {
+	  tid = 0;
+	}
+
+	if (frag == 0) {
+		/* Reserve enough space to fit maximum frame length */
+		skb = dev_alloc_skb(ieee->dev->mtu +
+				    sizeof(struct ieee80211_hdr_4addr) +
+				    8 /* LLC */ +
+				    2 /* alignment */ +
+				    8 /* WEP */ +
+				    ETH_ALEN /* WDS */ +
+				    (IEEE80211_QOS_HAS_SEQ(fc)?2:0) /* QOS Control */);
+		if (skb == NULL)
+			return NULL;
+
+		entry = &ieee->frag_cache[tid][ieee->frag_next_idx[tid]];
+		ieee->frag_next_idx[tid]++;
+		if (ieee->frag_next_idx[tid] >= IEEE80211_FRAG_CACHE_LEN)
+			ieee->frag_next_idx[tid] = 0;
+
+		if (entry->skb != NULL)
+			dev_kfree_skb_any(entry->skb);
+
+		entry->first_frag_time = jiffies;
+		entry->seq = seq;
+		entry->last_frag = frag;
+		entry->skb = skb;
+		memcpy(entry->src_addr, hdr->addr2, ETH_ALEN);
+		memcpy(entry->dst_addr, hdr->addr1, ETH_ALEN);
+	} else {
+		/* received a fragment of a frame for which the head fragment
+		 * should have already been received */
+		entry = ieee80211_frag_cache_find(ieee, seq, frag, tid,hdr->addr2,
+						  hdr->addr1);
+		if (entry != NULL) {
+			entry->last_frag = frag;
+			skb = entry->skb;
+		}
+	}
+
+	return skb;
+}
+
+
+/* Called only as a tasklet (software IRQ) */
+static int ieee80211_frag_cache_invalidate(struct ieee80211_device *ieee,
+					   struct ieee80211_hdr_4addr *hdr)
+{
+	u16 fc = le16_to_cpu(hdr->frame_ctl);
+	u16 sc = le16_to_cpu(hdr->seq_ctl);
+	unsigned int seq = WLAN_GET_SEQ_SEQ(sc);
+	struct ieee80211_frag_entry *entry;
+	struct ieee80211_hdr_3addrqos *hdr_3addrqos;
+	struct ieee80211_hdr_4addrqos *hdr_4addrqos;
+	u8 tid;
+
+	if(((fc & IEEE80211_FCTL_DSTODS) == IEEE80211_FCTL_DSTODS)&&IEEE80211_QOS_HAS_SEQ(fc)) {
+	  hdr_4addrqos = (struct ieee80211_hdr_4addrqos *)hdr;
+	  tid = le16_to_cpu(hdr_4addrqos->qos_ctl) & IEEE80211_QCTL_TID;
+	  tid = UP2AC(tid);
+	  tid ++;
+	} else if (IEEE80211_QOS_HAS_SEQ(fc)) {
+	  hdr_3addrqos = (struct ieee80211_hdr_3addrqos *)hdr;
+	  tid = le16_to_cpu(hdr_3addrqos->qos_ctl) & IEEE80211_QCTL_TID;
+	  tid = UP2AC(tid);
+	  tid ++;
+	} else {
+	  tid = 0;
+	}
+
+	entry = ieee80211_frag_cache_find(ieee, seq, -1, tid,hdr->addr2,
+					  hdr->addr1);
+
+	if (entry == NULL) {
+		IEEE80211_DEBUG_FRAG(
+			"could not invalidate fragment cache "
+			"entry (seq=%u)\n", seq);
+		return -1;
+	}
+
+	entry->skb = NULL;
+	return 0;
+}
+
+
+
+/* ieee80211_rx_frame_mgtmt
+ *
+ * Responsible for handling management control frames
+ *
+ * Called by ieee80211_rx */
+static inline int
+ieee80211_rx_frame_mgmt(struct ieee80211_device *ieee, struct sk_buff *skb,
+			struct ieee80211_rx_stats *rx_stats, u16 type,
+			u16 stype)
+{
+	/* On the struct stats definition there is written that
+	 * this is not mandatory.... but seems that the probe
+	 * response parser uses it
+	 */
+        struct ieee80211_hdr_3addr * hdr = (struct ieee80211_hdr_3addr *)skb->data;
+
+	rx_stats->len = skb->len;
+	ieee80211_rx_mgt(ieee,(struct ieee80211_hdr_4addr *)skb->data,rx_stats);
+        //if ((ieee->state == IEEE80211_LINKED) && (memcmp(hdr->addr3, ieee->current_network.bssid, ETH_ALEN)))
+        if ((memcmp(hdr->addr1, ieee->dev->dev_addr, ETH_ALEN)))//use ADDR1 to perform address matching for Management frames
+        {
+                dev_kfree_skb_any(skb);
+                return 0;
+        }
+
+	ieee80211_rx_frame_softmac(ieee, skb, rx_stats, type, stype);
+
+	dev_kfree_skb_any(skb);
+
+	return 0;
+
+	#ifdef NOT_YET
+	if (ieee->iw_mode == IW_MODE_MASTER) {
+		printk(KERN_DEBUG "%s: Master mode not yet suppported.\n",
+		       ieee->dev->name);
+		return 0;
+/*
+  hostap_update_sta_ps(ieee, (struct hostap_ieee80211_hdr_4addr *)
+  skb->data);*/
+	}
+
+	if (ieee->hostapd && type == IEEE80211_TYPE_MGMT) {
+		if (stype == WLAN_FC_STYPE_BEACON &&
+		    ieee->iw_mode == IW_MODE_MASTER) {
+			struct sk_buff *skb2;
+			/* Process beacon frames also in kernel driver to
+			 * update STA(AP) table statistics */
+			skb2 = skb_clone(skb, GFP_ATOMIC);
+			if (skb2)
+				hostap_rx(skb2->dev, skb2, rx_stats);
+		}
+
+		/* send management frames to the user space daemon for
+		 * processing */
+		ieee->apdevstats.rx_packets++;
+		ieee->apdevstats.rx_bytes += skb->len;
+		prism2_rx_80211(ieee->apdev, skb, rx_stats, PRISM2_RX_MGMT);
+		return 0;
+	}
+
+	    if (ieee->iw_mode == IW_MODE_MASTER) {
+		if (type != WLAN_FC_TYPE_MGMT && type != WLAN_FC_TYPE_CTRL) {
+			printk(KERN_DEBUG "%s: unknown management frame "
+			       "(type=0x%02x, stype=0x%02x) dropped\n",
+			       skb->dev->name, type, stype);
+			return -1;
+		}
+
+		hostap_rx(skb->dev, skb, rx_stats);
+		return 0;
+	}
+
+	printk(KERN_DEBUG "%s: hostap_rx_frame_mgmt: management frame "
+	       "received in non-Host AP mode\n", skb->dev->name);
+	return -1;
+	#endif
+}
+
+
+
+/* See IEEE 802.1H for LLC/SNAP encapsulation/decapsulation */
+/* Ethernet-II snap header (RFC1042 for most EtherTypes) */
+static unsigned char rfc1042_header[] =
+{ 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
+/* Bridge-Tunnel header (for EtherTypes ETH_P_AARP and ETH_P_IPX) */
+static unsigned char bridge_tunnel_header[] =
+{ 0xaa, 0xaa, 0x03, 0x00, 0x00, 0xf8 };
+/* No encapsulation header if EtherType < 0x600 (=length) */
+
+/* Called by ieee80211_rx_frame_decrypt */
+static int ieee80211_is_eapol_frame(struct ieee80211_device *ieee,
+				    struct sk_buff *skb, size_t hdrlen)
+{
+	struct net_device *dev = ieee->dev;
+	u16 fc, ethertype;
+	struct ieee80211_hdr_4addr *hdr;
+	u8 *pos;
+
+	if (skb->len < 24)
+		return 0;
+
+	hdr = (struct ieee80211_hdr_4addr *) skb->data;
+	fc = le16_to_cpu(hdr->frame_ctl);
+
+	/* check that the frame is unicast frame to us */
+	if ((fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) ==
+	    IEEE80211_FCTL_TODS &&
+	    memcmp(hdr->addr1, dev->dev_addr, ETH_ALEN) == 0 &&
+	    memcmp(hdr->addr3, dev->dev_addr, ETH_ALEN) == 0) {
+		/* ToDS frame with own addr BSSID and DA */
+	} else if ((fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) ==
+		   IEEE80211_FCTL_FROMDS &&
+		   memcmp(hdr->addr1, dev->dev_addr, ETH_ALEN) == 0) {
+		/* FromDS frame with own addr as DA */
+	} else
+		return 0;
+
+	if (skb->len < 24 + 8)
+		return 0;
+
+	/* check for port access entity Ethernet type */
+//	pos = skb->data + 24;
+	pos = skb->data + hdrlen;
+	ethertype = (pos[6] << 8) | pos[7];
+	if (ethertype == ETH_P_PAE)
+		return 1;
+
+	return 0;
+}
+
+/* Called only as a tasklet (software IRQ), by ieee80211_rx */
+static inline int
+ieee80211_rx_frame_decrypt(struct ieee80211_device* ieee, struct sk_buff *skb,
+			   struct ieee80211_crypt_data *crypt)
+{
+	struct ieee80211_hdr_4addr *hdr;
+	int res, hdrlen;
+
+	if (crypt == NULL || crypt->ops->decrypt_mpdu == NULL)
+		return 0;
+#if 1
+	if (ieee->hwsec_active)
+	{
+		cb_desc *tcb_desc = (cb_desc *)(skb->cb+ MAX_DEV_ADDR_SIZE);
+		tcb_desc->bHwSec = 1;
+	}
+#endif
+	hdr = (struct ieee80211_hdr_4addr *) skb->data;
+	hdrlen = ieee80211_get_hdrlen(le16_to_cpu(hdr->frame_ctl));
+
+#ifdef CONFIG_IEEE80211_CRYPT_TKIP
+	if (ieee->tkip_countermeasures &&
+	    strcmp(crypt->ops->name, "TKIP") == 0) {
+		if (net_ratelimit()) {
+			printk(KERN_DEBUG "%s: TKIP countermeasures: dropped "
+			       "received packet from " MAC_FMT "\n",
+			       ieee->dev->name, MAC_ARG(hdr->addr2));
+		}
+		return -1;
+	}
+#endif
+
+	atomic_inc(&crypt->refcnt);
+	res = crypt->ops->decrypt_mpdu(skb, hdrlen, crypt->priv);
+	atomic_dec(&crypt->refcnt);
+	if (res < 0) {
+		IEEE80211_DEBUG_DROP(
+			"decryption failed (SA=" MAC_FMT
+			") res=%d\n", MAC_ARG(hdr->addr2), res);
+		if (res == -2)
+			IEEE80211_DEBUG_DROP("Decryption failed ICV "
+					     "mismatch (key %d)\n",
+					     skb->data[hdrlen + 3] >> 6);
+		ieee->ieee_stats.rx_discards_undecryptable++;
+		return -1;
+	}
+
+	return res;
+}
+
+
+/* Called only as a tasklet (software IRQ), by ieee80211_rx */
+static inline int
+ieee80211_rx_frame_decrypt_msdu(struct ieee80211_device* ieee, struct sk_buff *skb,
+			     int keyidx, struct ieee80211_crypt_data *crypt)
+{
+	struct ieee80211_hdr_4addr *hdr;
+	int res, hdrlen;
+
+	if (crypt == NULL || crypt->ops->decrypt_msdu == NULL)
+		return 0;
+	if (ieee->hwsec_active)
+	{
+		cb_desc *tcb_desc = (cb_desc *)(skb->cb+ MAX_DEV_ADDR_SIZE);
+		tcb_desc->bHwSec = 1;
+	}
+
+	hdr = (struct ieee80211_hdr_4addr *) skb->data;
+	hdrlen = ieee80211_get_hdrlen(le16_to_cpu(hdr->frame_ctl));
+
+	atomic_inc(&crypt->refcnt);
+	res = crypt->ops->decrypt_msdu(skb, keyidx, hdrlen, crypt->priv);
+	atomic_dec(&crypt->refcnt);
+	if (res < 0) {
+		printk(KERN_DEBUG "%s: MSDU decryption/MIC verification failed"
+		       " (SA=" MAC_FMT " keyidx=%d)\n",
+		       ieee->dev->name, MAC_ARG(hdr->addr2), keyidx);
+		return -1;
+	}
+
+	return 0;
+}
+
+
+/* this function is stolen from ipw2200 driver*/
+#define IEEE_PACKET_RETRY_TIME (5*HZ)
+static int is_duplicate_packet(struct ieee80211_device *ieee,
+				      struct ieee80211_hdr_4addr *header)
+{
+	u16 fc = le16_to_cpu(header->frame_ctl);
+	u16 sc = le16_to_cpu(header->seq_ctl);
+	u16 seq = WLAN_GET_SEQ_SEQ(sc);
+	u16 frag = WLAN_GET_SEQ_FRAG(sc);
+	u16 *last_seq, *last_frag;
+	unsigned long *last_time;
+	struct ieee80211_hdr_3addrqos *hdr_3addrqos;
+	struct ieee80211_hdr_4addrqos *hdr_4addrqos;
+	u8 tid;
+
+
+	//TO2DS and QoS
+	if(((fc & IEEE80211_FCTL_DSTODS) == IEEE80211_FCTL_DSTODS)&&IEEE80211_QOS_HAS_SEQ(fc)) {
+	  hdr_4addrqos = (struct ieee80211_hdr_4addrqos *)header;
+	  tid = le16_to_cpu(hdr_4addrqos->qos_ctl) & IEEE80211_QCTL_TID;
+	  tid = UP2AC(tid);
+	  tid ++;
+	} else if(IEEE80211_QOS_HAS_SEQ(fc)) { //QoS
+	  hdr_3addrqos = (struct ieee80211_hdr_3addrqos*)header;
+	  tid = le16_to_cpu(hdr_3addrqos->qos_ctl) & IEEE80211_QCTL_TID;
+	  tid = UP2AC(tid);
+	  tid ++;
+	} else { // no QoS
+	  tid = 0;
+	}
+
+	switch (ieee->iw_mode) {
+	case IW_MODE_ADHOC:
+	{
+		struct list_head *p;
+		struct ieee_ibss_seq *entry = NULL;
+		u8 *mac = header->addr2;
+		int index = mac[5] % IEEE_IBSS_MAC_HASH_SIZE;
+		//for (pos = (head)->next; pos != (head); pos = pos->next)
+		//__list_for_each(p, &ieee->ibss_mac_hash[index]) {
+		list_for_each(p, &ieee->ibss_mac_hash[index]) {
+			entry = list_entry(p, struct ieee_ibss_seq, list);
+			if (!memcmp(entry->mac, mac, ETH_ALEN))
+				break;
+		}
+	//	if (memcmp(entry->mac, mac, ETH_ALEN)){
+		if (p == &ieee->ibss_mac_hash[index]) {
+			entry = kmalloc(sizeof(struct ieee_ibss_seq), GFP_ATOMIC);
+			if (!entry) {
+				printk(KERN_WARNING "Cannot malloc new mac entry\n");
+				return 0;
+			}
+			memcpy(entry->mac, mac, ETH_ALEN);
+			entry->seq_num[tid] = seq;
+			entry->frag_num[tid] = frag;
+			entry->packet_time[tid] = jiffies;
+			list_add(&entry->list, &ieee->ibss_mac_hash[index]);
+			return 0;
+		}
+		last_seq = &entry->seq_num[tid];
+		last_frag = &entry->frag_num[tid];
+		last_time = &entry->packet_time[tid];
+		break;
+	}
+
+	case IW_MODE_INFRA:
+		last_seq = &ieee->last_rxseq_num[tid];
+		last_frag = &ieee->last_rxfrag_num[tid];
+		last_time = &ieee->last_packet_time[tid];
+
+		break;
+	default:
+		return 0;
+	}
+
+//	if(tid != 0) {
+//		printk(KERN_WARNING ":)))))))))))%x %x %x, fc(%x)\n", tid, *last_seq, seq, header->frame_ctl);
+//	}
+	if ((*last_seq == seq) &&
+	    time_after(*last_time + IEEE_PACKET_RETRY_TIME, jiffies)) {
+		if (*last_frag == frag){
+			//printk(KERN_WARNING "[1] go drop!\n");
+			goto drop;
+
+		}
+		if (*last_frag + 1 != frag)
+			/* out-of-order fragment */
+			//printk(KERN_WARNING "[2] go drop!\n");
+			goto drop;
+	} else
+		*last_seq = seq;
+
+	*last_frag = frag;
+	*last_time = jiffies;
+	return 0;
+
+drop:
+//	BUG_ON(!(fc & IEEE80211_FCTL_RETRY));
+//	printk("DUP\n");
+
+	return 1;
+}
+bool
+AddReorderEntry(
+	PRX_TS_RECORD			pTS,
+	PRX_REORDER_ENTRY		pReorderEntry
+	)
+{
+	struct list_head *pList = &pTS->RxPendingPktList;
+#if  1
+	while(pList->next != &pTS->RxPendingPktList)
+	{
+		if( SN_LESS(pReorderEntry->SeqNum, ((PRX_REORDER_ENTRY)list_entry(pList->next,RX_REORDER_ENTRY,List))->SeqNum) )
+		{
+			pList = pList->next;
+		}
+		else if( SN_EQUAL(pReorderEntry->SeqNum, ((PRX_REORDER_ENTRY)list_entry(pList->next,RX_REORDER_ENTRY,List))->SeqNum) )
+		{
+			return false;
+		}
+		else
+		{
+			break;
+		}
+	}
+#endif
+	pReorderEntry->List.next = pList->next;
+	pReorderEntry->List.next->prev = &pReorderEntry->List;
+	pReorderEntry->List.prev = pList;
+	pList->next = &pReorderEntry->List;
+
+	return true;
+}
+
+void ieee80211_indicate_packets(struct ieee80211_device *ieee, struct ieee80211_rxb** prxbIndicateArray,u8  index)
+{
+	u8 i = 0 , j=0;
+	u16 ethertype;
+//	if(index > 1)
+//		IEEE80211_DEBUG(IEEE80211_DL_REORDER,"%s(): hahahahhhh, We indicate packet from reorder list, index is %u\n",__FUNCTION__,index);
+	for(j = 0; j<index; j++)
+	{
+//added by amy for reorder
+		struct ieee80211_rxb* prxb = prxbIndicateArray[j];
+		for(i = 0; i<prxb->nr_subframes; i++) {
+			struct sk_buff *sub_skb = prxb->subframes[i];
+
+		/* convert hdr + possible LLC headers into Ethernet header */
+			ethertype = (sub_skb->data[6] << 8) | sub_skb->data[7];
+			if (sub_skb->len >= 8 &&
+				((memcmp(sub_skb->data, rfc1042_header, SNAP_SIZE) == 0 &&
+				  ethertype != ETH_P_AARP && ethertype != ETH_P_IPX) ||
+				 memcmp(sub_skb->data, bridge_tunnel_header, SNAP_SIZE) == 0)) {
+			/* remove RFC1042 or Bridge-Tunnel encapsulation and
+			 * replace EtherType */
+				skb_pull(sub_skb, SNAP_SIZE);
+				memcpy(skb_push(sub_skb, ETH_ALEN), prxb->src, ETH_ALEN);
+				memcpy(skb_push(sub_skb, ETH_ALEN), prxb->dst, ETH_ALEN);
+			} else {
+				u16 len;
+			/* Leave Ethernet header part of hdr and full payload */
+				len = htons(sub_skb->len);
+				memcpy(skb_push(sub_skb, 2), &len, 2);
+				memcpy(skb_push(sub_skb, ETH_ALEN), prxb->src, ETH_ALEN);
+				memcpy(skb_push(sub_skb, ETH_ALEN), prxb->dst, ETH_ALEN);
+			}
+			//stats->rx_packets++;
+			//stats->rx_bytes += sub_skb->len;
+
+		/* Indicat the packets to upper layer */
+			if (sub_skb) {
+				//printk("0skb_len(%d)\n", skb->len);
+				sub_skb->protocol = eth_type_trans(sub_skb, ieee->dev);
+				memset(sub_skb->cb, 0, sizeof(sub_skb->cb));
+				sub_skb->dev = ieee->dev;
+				sub_skb->ip_summed = CHECKSUM_NONE; /* 802.11 crc not sufficient */
+				//skb->ip_summed = CHECKSUM_UNNECESSARY; /* 802.11 crc not sufficient */
+				ieee->last_rx_ps_time = jiffies;
+				//printk("1skb_len(%d)\n", skb->len);
+				netif_rx(sub_skb);
+			}
+		}
+		kfree(prxb);
+		prxb = NULL;
+	}
+}
+
+
+void RxReorderIndicatePacket( struct ieee80211_device *ieee,
+		struct ieee80211_rxb* prxb,
+		PRX_TS_RECORD		pTS,
+		u16			SeqNum)
+{
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	PRX_REORDER_ENTRY 	pReorderEntry = NULL;
+	struct ieee80211_rxb* prxbIndicateArray[REORDER_WIN_SIZE];
+	u8			WinSize = pHTInfo->RxReorderWinSize;
+	u16			WinEnd = (pTS->RxIndicateSeq + WinSize -1)%4096;
+	u8			index = 0;
+	bool			bMatchWinStart = false, bPktInBuf = false;
+	IEEE80211_DEBUG(IEEE80211_DL_REORDER,"%s(): Seq is %d,pTS->RxIndicateSeq is %d, WinSize is %d\n",__FUNCTION__,SeqNum,pTS->RxIndicateSeq,WinSize);
+#if 0
+	if(!list_empty(&ieee->RxReorder_Unused_List))
+		IEEE80211_DEBUG(IEEE80211_DL_REORDER,"%s(): ieee->RxReorder_Unused_List is nut NULL\n");
+#endif
+	/* Rx Reorder initialize condition.*/
+	if(pTS->RxIndicateSeq == 0xffff) {
+		pTS->RxIndicateSeq = SeqNum;
+	}
+
+	/* Drop out the packet which SeqNum is smaller than WinStart */
+	if(SN_LESS(SeqNum, pTS->RxIndicateSeq)) {
+		IEEE80211_DEBUG(IEEE80211_DL_REORDER,"Packet Drop! IndicateSeq: %d, NewSeq: %d\n",
+				 pTS->RxIndicateSeq, SeqNum);
+		pHTInfo->RxReorderDropCounter++;
+		{
+			int i;
+			for(i =0; i < prxb->nr_subframes; i++) {
+				dev_kfree_skb(prxb->subframes[i]);
+			}
+			kfree(prxb);
+			prxb = NULL;
+		}
+		return;
+	}
+
+	/*
+	 * Sliding window manipulation. Conditions includes:
+	 * 1. Incoming SeqNum is equal to WinStart =>Window shift 1
+	 * 2. Incoming SeqNum is larger than the WinEnd => Window shift N
+	 */
+	if(SN_EQUAL(SeqNum, pTS->RxIndicateSeq)) {
+		pTS->RxIndicateSeq = (pTS->RxIndicateSeq + 1) % 4096;
+		bMatchWinStart = true;
+	} else if(SN_LESS(WinEnd, SeqNum)) {
+		if(SeqNum >= (WinSize - 1)) {
+			pTS->RxIndicateSeq = SeqNum + 1 -WinSize;
+		} else {
+			pTS->RxIndicateSeq = 4095 - (WinSize - (SeqNum +1)) + 1;
+		}
+		IEEE80211_DEBUG(IEEE80211_DL_REORDER, "Window Shift! IndicateSeq: %d, NewSeq: %d\n",pTS->RxIndicateSeq, SeqNum);
+	}
+
+	/*
+	 * Indication process.
+	 * After Packet dropping and Sliding Window shifting as above, we can now just indicate the packets
+	 * with the SeqNum smaller than latest WinStart and buffer other packets.
+	 */
+	/* For Rx Reorder condition:
+	 * 1. All packets with SeqNum smaller than WinStart => Indicate
+	 * 2. All packets with SeqNum larger than or equal to WinStart => Buffer it.
+	 */
+	if(bMatchWinStart) {
+		/* Current packet is going to be indicated.*/
+		IEEE80211_DEBUG(IEEE80211_DL_REORDER, "Packets indication!! IndicateSeq: %d, NewSeq: %d\n",\
+				pTS->RxIndicateSeq, SeqNum);
+		prxbIndicateArray[0] = prxb;
+//		printk("========================>%s(): SeqNum is %d\n",__FUNCTION__,SeqNum);
+		index = 1;
+	} else {
+		/* Current packet is going to be inserted into pending list.*/
+		//IEEE80211_DEBUG(IEEE80211_DL_REORDER,"%s(): We RX no ordered packed, insert to orderd list\n",__FUNCTION__);
+		if(!list_empty(&ieee->RxReorder_Unused_List)) {
+			pReorderEntry = (PRX_REORDER_ENTRY)list_entry(ieee->RxReorder_Unused_List.next,RX_REORDER_ENTRY,List);
+			list_del_init(&pReorderEntry->List);
+
+			/* Make a reorder entry and insert into a the packet list.*/
+			pReorderEntry->SeqNum = SeqNum;
+			pReorderEntry->prxb = prxb;
+	//		IEEE80211_DEBUG(IEEE80211_DL_REORDER,"%s(): pREorderEntry->SeqNum is %d\n",__FUNCTION__,pReorderEntry->SeqNum);
+
+#if 1
+			if(!AddReorderEntry(pTS, pReorderEntry)) {
+				IEEE80211_DEBUG(IEEE80211_DL_REORDER, "%s(): Duplicate packet is dropped!! IndicateSeq: %d, NewSeq: %d\n",
+					__FUNCTION__, pTS->RxIndicateSeq, SeqNum);
+				list_add_tail(&pReorderEntry->List,&ieee->RxReorder_Unused_List);
+				{
+					int i;
+					for(i =0; i < prxb->nr_subframes; i++) {
+						dev_kfree_skb(prxb->subframes[i]);
+					}
+					kfree(prxb);
+					prxb = NULL;
+				}
+			} else {
+				IEEE80211_DEBUG(IEEE80211_DL_REORDER,
+					 "Pkt insert into buffer!! IndicateSeq: %d, NewSeq: %d\n",pTS->RxIndicateSeq, SeqNum);
+			}
+#endif
+		}
+		else {
+			/*
+			 * Packets are dropped if there is not enough reorder entries.
+			 * This part shall be modified!! We can just indicate all the
+			 * packets in buffer and get reorder entries.
+			 */
+			IEEE80211_DEBUG(IEEE80211_DL_ERR, "RxReorderIndicatePacket(): There is no reorder entry!! Packet is dropped!!\n");
+			{
+				int i;
+				for(i =0; i < prxb->nr_subframes; i++) {
+					dev_kfree_skb(prxb->subframes[i]);
+				}
+				kfree(prxb);
+				prxb = NULL;
+			}
+		}
+	}
+
+	/* Check if there is any packet need indicate.*/
+	while(!list_empty(&pTS->RxPendingPktList)) {
+		IEEE80211_DEBUG(IEEE80211_DL_REORDER,"%s(): start RREORDER indicate\n",__FUNCTION__);
+#if 1
+		pReorderEntry = (PRX_REORDER_ENTRY)list_entry(pTS->RxPendingPktList.prev,RX_REORDER_ENTRY,List);
+		if( SN_LESS(pReorderEntry->SeqNum, pTS->RxIndicateSeq) ||
+				SN_EQUAL(pReorderEntry->SeqNum, pTS->RxIndicateSeq))
+		{
+			/* This protect buffer from overflow. */
+			if(index >= REORDER_WIN_SIZE) {
+				IEEE80211_DEBUG(IEEE80211_DL_ERR, "RxReorderIndicatePacket(): Buffer overflow!! \n");
+				bPktInBuf = true;
+				break;
+			}
+
+			list_del_init(&pReorderEntry->List);
+
+			if(SN_EQUAL(pReorderEntry->SeqNum, pTS->RxIndicateSeq))
+				pTS->RxIndicateSeq = (pTS->RxIndicateSeq + 1) % 4096;
+
+			IEEE80211_DEBUG(IEEE80211_DL_REORDER,"Packets indication!! IndicateSeq: %d, NewSeq: %d\n",pTS->RxIndicateSeq, SeqNum);
+			prxbIndicateArray[index] = pReorderEntry->prxb;
+		//	printk("========================>%s(): pReorderEntry->SeqNum is %d\n",__FUNCTION__,pReorderEntry->SeqNum);
+			index++;
+
+			list_add_tail(&pReorderEntry->List,&ieee->RxReorder_Unused_List);
+		} else {
+			bPktInBuf = true;
+			break;
+		}
+#endif
+	}
+
+	/* Handling pending timer. Set this timer to prevent from long time Rx buffering.*/
+	if(index>0) {
+		// Cancel previous pending timer.
+		if(timer_pending(&pTS->RxPktPendingTimer))
+		{
+			del_timer_sync(&pTS->RxPktPendingTimer);
+		}
+	//	del_timer_sync(&pTS->RxPktPendingTimer);
+		pTS->RxTimeoutIndicateSeq = 0xffff;
+
+		// Indicate packets
+		if(index>REORDER_WIN_SIZE){
+			IEEE80211_DEBUG(IEEE80211_DL_ERR, "RxReorderIndicatePacket(): Rx Reorer buffer full!! \n");
+			return;
+		}
+		ieee80211_indicate_packets(ieee, prxbIndicateArray, index);
+		bPktInBuf = false;
+	}
+
+#if 1
+	if(bPktInBuf && pTS->RxTimeoutIndicateSeq==0xffff) {
+		// Set new pending timer.
+		IEEE80211_DEBUG(IEEE80211_DL_REORDER,"%s(): SET rx timeout timer\n", __FUNCTION__);
+		pTS->RxTimeoutIndicateSeq = pTS->RxIndicateSeq;
+#if 0
+		if(timer_pending(&pTS->RxPktPendingTimer))
+			del_timer_sync(&pTS->RxPktPendingTimer);
+		pTS->RxPktPendingTimer.expires = jiffies + MSECS(pHTInfo->RxReorderPendingTime);
+		add_timer(&pTS->RxPktPendingTimer);
+#else
+		mod_timer(&pTS->RxPktPendingTimer,  jiffies + MSECS(pHTInfo->RxReorderPendingTime));
+#endif
+	}
+#endif
+}
+
+u8 parse_subframe(struct sk_buff *skb,
+                  struct ieee80211_rx_stats *rx_stats,
+		  struct ieee80211_rxb *rxb,u8* src,u8* dst)
+{
+	struct ieee80211_hdr_3addr  *hdr = (struct ieee80211_hdr_3addr* )skb->data;
+	u16		fc = le16_to_cpu(hdr->frame_ctl);
+
+	u16		LLCOffset= sizeof(struct ieee80211_hdr_3addr);
+	u16		ChkLength;
+	bool		bIsAggregateFrame = false;
+	u16		nSubframe_Length;
+	u8		nPadding_Length = 0;
+	u16		SeqNum=0;
+
+	struct sk_buff *sub_skb;
+	u8             *data_ptr;
+	/* just for debug purpose */
+	SeqNum = WLAN_GET_SEQ_SEQ(le16_to_cpu(hdr->seq_ctl));
+
+	if((IEEE80211_QOS_HAS_SEQ(fc))&&\
+			(((frameqos *)(skb->data + IEEE80211_3ADDR_LEN))->field.reserved)) {
+		bIsAggregateFrame = true;
+	}
+
+	if(IEEE80211_QOS_HAS_SEQ(fc)) {
+		LLCOffset += 2;
+	}
+
+	if(rx_stats->bContainHTC) {
+		LLCOffset += sHTCLng;
+	}
+	//printk("ChkLength = %d\n", LLCOffset);
+	// Null packet, don't indicate it to upper layer
+	ChkLength = LLCOffset;/* + (Frame_WEP(frame)!=0 ?Adapter->MgntInfo.SecurityInfo.EncryptionHeadOverhead:0);*/
+
+	if( skb->len <= ChkLength ) {
+		return 0;
+	}
+
+	skb_pull(skb, LLCOffset);
+
+	if(!bIsAggregateFrame) {
+		rxb->nr_subframes = 1;
+#ifdef JOHN_NOCPY
+		rxb->subframes[0] = skb;
+#else
+		rxb->subframes[0] = skb_copy(skb, GFP_ATOMIC);
+#endif
+
+		memcpy(rxb->src,src,ETH_ALEN);
+		memcpy(rxb->dst,dst,ETH_ALEN);
+		//IEEE80211_DEBUG_DATA(IEEE80211_DL_RX,skb->data,skb->len);
+		return 1;
+	} else {
+		rxb->nr_subframes = 0;
+		memcpy(rxb->src,src,ETH_ALEN);
+		memcpy(rxb->dst,dst,ETH_ALEN);
+		while(skb->len > ETHERNET_HEADER_SIZE) {
+			/* Offset 12 denote 2 mac address */
+			nSubframe_Length = *((u16*)(skb->data + 12));
+			//==m==>change the length order
+			nSubframe_Length = (nSubframe_Length>>8) + (nSubframe_Length<<8);
+
+			if(skb->len<(ETHERNET_HEADER_SIZE + nSubframe_Length)) {
+#if 0//cosa
+				RT_ASSERT(
+						(nRemain_Length>=(ETHERNET_HEADER_SIZE + nSubframe_Length)),
+						("ParseSubframe(): A-MSDU subframe parse error!! Subframe Length: %d\n", nSubframe_Length) );
+#endif
+				printk("%s: A-MSDU parse error!! pRfd->nTotalSubframe : %d\n",\
+						__FUNCTION__,rxb->nr_subframes);
+				printk("%s: A-MSDU parse error!! Subframe Length: %d\n",__FUNCTION__, nSubframe_Length);
+				printk("nRemain_Length is %d and nSubframe_Length is : %d\n",skb->len,nSubframe_Length);
+				printk("The Packet SeqNum is %d\n",SeqNum);
+				return 0;
+			}
+
+			/* move the data point to data content */
+			skb_pull(skb, ETHERNET_HEADER_SIZE);
+
+#ifdef JOHN_NOCPY
+			sub_skb = skb_clone(skb, GFP_ATOMIC);
+			sub_skb->len = nSubframe_Length;
+			sub_skb->tail = sub_skb->data + nSubframe_Length;
+#else
+			/* Allocate new skb for releasing to upper layer */
+			sub_skb = dev_alloc_skb(nSubframe_Length + 12);
+			skb_reserve(sub_skb, 12);
+			data_ptr = (u8 *)skb_put(sub_skb, nSubframe_Length);
+			memcpy(data_ptr,skb->data,nSubframe_Length);
+#endif
+			rxb->subframes[rxb->nr_subframes++] = sub_skb;
+			if(rxb->nr_subframes >= MAX_SUBFRAME_COUNT) {
+				IEEE80211_DEBUG_RX("ParseSubframe(): Too many Subframes! Packets dropped!\n");
+				break;
+			}
+			skb_pull(skb,nSubframe_Length);
+
+			if(skb->len != 0) {
+				nPadding_Length = 4 - ((nSubframe_Length + ETHERNET_HEADER_SIZE) % 4);
+				if(nPadding_Length == 4) {
+					nPadding_Length = 0;
+				}
+
+				if(skb->len < nPadding_Length) {
+					return 0;
+				}
+
+				skb_pull(skb,nPadding_Length);
+			}
+		}
+#ifdef JOHN_NOCPY
+		dev_kfree_skb(skb);
+#endif
+		//{just for debug added by david
+		//printk("AMSDU::rxb->nr_subframes = %d\n",rxb->nr_subframes);
+		//}
+		return rxb->nr_subframes;
+	}
+}
+
+/* All received frames are sent to this function. @skb contains the frame in
+ * IEEE 802.11 format, i.e., in the format it was sent over air.
+ * This function is called only as a tasklet (software IRQ). */
+int ieee80211_rx(struct ieee80211_device *ieee, struct sk_buff *skb,
+		 struct ieee80211_rx_stats *rx_stats)
+{
+	struct net_device *dev = ieee->dev;
+	struct ieee80211_hdr_4addr *hdr;
+	//struct ieee80211_hdr_3addrqos *hdr;
+
+	size_t hdrlen;
+	u16 fc, type, stype, sc;
+	struct net_device_stats *stats;
+	unsigned int frag;
+	u8 *payload;
+	u16 ethertype;
+	//added by amy for reorder
+	u8	TID = 0;
+	u16	SeqNum = 0;
+	PRX_TS_RECORD pTS = NULL;
+	//bool bIsAggregateFrame = false;
+	//added by amy for reorder
+#ifdef NOT_YET
+	struct net_device *wds = NULL;
+	struct sk_buff *skb2 = NULL;
+	struct net_device *wds = NULL;
+	int frame_authorized = 0;
+	int from_assoc_ap = 0;
+	void *sta = NULL;
+#endif
+//	u16 qos_ctl = 0;
+	u8 dst[ETH_ALEN];
+	u8 src[ETH_ALEN];
+	u8 bssid[ETH_ALEN];
+	struct ieee80211_crypt_data *crypt = NULL;
+	int keyidx = 0;
+
+	int i;
+	struct ieee80211_rxb* rxb = NULL;
+	// cheat the the hdr type
+	hdr = (struct ieee80211_hdr_4addr *)skb->data;
+	stats = &ieee->stats;
+
+	if (skb->len < 10) {
+		printk(KERN_INFO "%s: SKB length < 10\n",
+		       dev->name);
+		goto rx_dropped;
+	}
+
+	fc = le16_to_cpu(hdr->frame_ctl);
+	type = WLAN_FC_GET_TYPE(fc);
+	stype = WLAN_FC_GET_STYPE(fc);
+	sc = le16_to_cpu(hdr->seq_ctl);
+
+	frag = WLAN_GET_SEQ_FRAG(sc);
+	hdrlen = ieee80211_get_hdrlen(fc);
+
+	if(HTCCheck(ieee, skb->data))
+	{
+		if(net_ratelimit())
+		printk("find HTCControl\n");
+		hdrlen += 4;
+		rx_stats->bContainHTC = 1;
+	}
+
+	//IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, skb->data, skb->len);
+#ifdef NOT_YET
+#if WIRELESS_EXT > 15
+	/* Put this code here so that we avoid duplicating it in all
+	 * Rx paths. - Jean II */
+#ifdef IW_WIRELESS_SPY		/* defined in iw_handler.h */
+	/* If spy monitoring on */
+	if (iface->spy_data.spy_number > 0) {
+		struct iw_quality wstats;
+		wstats.level = rx_stats->rssi;
+		wstats.noise = rx_stats->noise;
+		wstats.updated = 6;	/* No qual value */
+		/* Update spy records */
+		wireless_spy_update(dev, hdr->addr2, &wstats);
+	}
+#endif /* IW_WIRELESS_SPY */
+#endif /* WIRELESS_EXT > 15 */
+	hostap_update_rx_stats(local->ap, hdr, rx_stats);
+#endif
+
+#if WIRELESS_EXT > 15
+	if (ieee->iw_mode == IW_MODE_MONITOR) {
+		ieee80211_monitor_rx(ieee, skb, rx_stats);
+		stats->rx_packets++;
+		stats->rx_bytes += skb->len;
+		return 1;
+	}
+#endif
+	if (ieee->host_decrypt) {
+		int idx = 0;
+		if (skb->len >= hdrlen + 3)
+			idx = skb->data[hdrlen + 3] >> 6;
+		crypt = ieee->crypt[idx];
+#ifdef NOT_YET
+		sta = NULL;
+
+		/* Use station specific key to override default keys if the
+		 * receiver address is a unicast address ("individual RA"). If
+		 * bcrx_sta_key parameter is set, station specific key is used
+		 * even with broad/multicast targets (this is against IEEE
+		 * 802.11, but makes it easier to use different keys with
+		 * stations that do not support WEP key mapping). */
+
+		if (!(hdr->addr1[0] & 0x01) || local->bcrx_sta_key)
+			(void) hostap_handle_sta_crypto(local, hdr, &crypt,
+							&sta);
+#endif
+
+		/* allow NULL decrypt to indicate an station specific override
+		 * for default encryption */
+		if (crypt && (crypt->ops == NULL ||
+			      crypt->ops->decrypt_mpdu == NULL))
+			crypt = NULL;
+
+		if (!crypt && (fc & IEEE80211_FCTL_WEP)) {
+			/* This seems to be triggered by some (multicast?)
+			 * frames from other than current BSS, so just drop the
+			 * frames silently instead of filling system log with
+			 * these reports. */
+			IEEE80211_DEBUG_DROP("Decryption failed (not set)"
+					     " (SA=" MAC_FMT ")\n",
+					     MAC_ARG(hdr->addr2));
+			ieee->ieee_stats.rx_discards_undecryptable++;
+			goto rx_dropped;
+		}
+	}
+
+	if (skb->len < IEEE80211_DATA_HDR3_LEN)
+		goto rx_dropped;
+
+	// if QoS enabled, should check the sequence for each of the AC
+	if( (ieee->pHTInfo->bCurRxReorderEnable == false) || !ieee->current_network.qos_data.active|| !IsDataFrame(skb->data) || IsLegacyDataFrame(skb->data)){
+		if (is_duplicate_packet(ieee, hdr))
+		goto rx_dropped;
+
+	}
+	else
+	{
+		PRX_TS_RECORD pRxTS = NULL;
+	#if 0
+		struct ieee80211_hdr_3addr *hdr;
+		u16 fc;
+		hdr = (struct ieee80211_hdr_3addr *)skb->data;
+		fc = le16_to_cpu(hdr->frame_ctl);
+		u8 tmp = (fc & IEEE80211_FCTL_FROMDS) && (fc & IEEE80211_FCTL_TODS);
+
+		u8 tid = (*((u8*)skb->data + (((fc& IEEE80211_FCTL_FROMDS) && (fc & IEEE80211_FCTL_TODS))?30:24)))&0xf;
+		printk("====================>fc:%x, tid:%d, tmp:%d\n", fc, tid, tmp);
+		//u8 tid =  (u8)((frameqos*)(buf + ((fc & IEEE80211_FCTL_TODS)&&(fc & IEEE80211_FCTL_FROMDS))? 30 : 24))->field.tid;
+	#endif
+			//IEEE80211_DEBUG(IEEE80211_DL_REORDER,"%s(): QOS ENABLE AND RECEIVE QOS DATA , we will get Ts, tid:%d\n",__FUNCTION__, tid);
+#if 1
+		if(GetTs(
+				ieee,
+				(PTS_COMMON_INFO*) &pRxTS,
+				hdr->addr2,
+				(u8)Frame_QoSTID((u8*)(skb->data)),
+				RX_DIR,
+				true))
+		{
+
+		//	IEEE80211_DEBUG(IEEE80211_DL_REORDER,"%s(): pRxTS->RxLastFragNum is %d,frag is %d,pRxTS->RxLastSeqNum is %d,seq is %d\n",__FUNCTION__,pRxTS->RxLastFragNum,frag,pRxTS->RxLastSeqNum,WLAN_GET_SEQ_SEQ(sc));
+			if( 	(fc & (1<<11))  &&
+					(frag == pRxTS->RxLastFragNum) &&
+					(WLAN_GET_SEQ_SEQ(sc) == pRxTS->RxLastSeqNum)	)
+			{
+				goto rx_dropped;
+			}
+			else
+			{
+				pRxTS->RxLastFragNum = frag;
+				pRxTS->RxLastSeqNum = WLAN_GET_SEQ_SEQ(sc);
+			}
+		}
+		else
+		{
+			IEEE80211_DEBUG(IEEE80211_DL_ERR, "%s(): No TS!! Skip the check!!\n",__FUNCTION__);
+			goto rx_dropped;
+		}
+	}
+#endif
+	if (type == IEEE80211_FTYPE_MGMT) {
+
+	#if 0
+		if ( stype == IEEE80211_STYPE_AUTH &&
+		    fc & IEEE80211_FCTL_WEP && ieee->host_decrypt &&
+		    (keyidx = hostap_rx_frame_decrypt(ieee, skb, crypt)) < 0)
+		{
+			printk(KERN_DEBUG "%s: failed to decrypt mgmt::auth "
+			       "from " MAC_FMT "\n", dev->name,
+			       MAC_ARG(hdr->addr2));
+			/* TODO: could inform hostapd about this so that it
+			 * could send auth failure report */
+			goto rx_dropped;
+		}
+	#endif
+
+	//IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, skb->data, skb->len);
+		if (ieee80211_rx_frame_mgmt(ieee, skb, rx_stats, type, stype))
+			goto rx_dropped;
+		else
+			goto rx_exit;
+	}
+
+	/* Data frame - extract src/dst addresses */
+	switch (fc & (IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS)) {
+	case IEEE80211_FCTL_FROMDS:
+		memcpy(dst, hdr->addr1, ETH_ALEN);
+		memcpy(src, hdr->addr3, ETH_ALEN);
+		memcpy(bssid, hdr->addr2, ETH_ALEN);
+		break;
+	case IEEE80211_FCTL_TODS:
+		memcpy(dst, hdr->addr3, ETH_ALEN);
+		memcpy(src, hdr->addr2, ETH_ALEN);
+		memcpy(bssid, hdr->addr1, ETH_ALEN);
+		break;
+	case IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS:
+		if (skb->len < IEEE80211_DATA_HDR4_LEN)
+			goto rx_dropped;
+		memcpy(dst, hdr->addr3, ETH_ALEN);
+		memcpy(src, hdr->addr4, ETH_ALEN);
+		memcpy(bssid, ieee->current_network.bssid, ETH_ALEN);
+		break;
+	case 0:
+		memcpy(dst, hdr->addr1, ETH_ALEN);
+		memcpy(src, hdr->addr2, ETH_ALEN);
+		memcpy(bssid, hdr->addr3, ETH_ALEN);
+		break;
+	}
+
+#ifdef NOT_YET
+	if (hostap_rx_frame_wds(ieee, hdr, fc, &wds))
+		goto rx_dropped;
+	if (wds) {
+		skb->dev = dev = wds;
+		stats = hostap_get_stats(dev);
+	}
+
+	if (ieee->iw_mode == IW_MODE_MASTER && !wds &&
+	    (fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) == IEEE80211_FCTL_FROMDS &&
+	    ieee->stadev &&
+	    memcmp(hdr->addr2, ieee->assoc_ap_addr, ETH_ALEN) == 0) {
+		/* Frame from BSSID of the AP for which we are a client */
+		skb->dev = dev = ieee->stadev;
+		stats = hostap_get_stats(dev);
+		from_assoc_ap = 1;
+	}
+#endif
+
+	dev->last_rx = jiffies;
+
+#ifdef NOT_YET
+	if ((ieee->iw_mode == IW_MODE_MASTER ||
+	     ieee->iw_mode == IW_MODE_REPEAT) &&
+	    !from_assoc_ap) {
+		switch (hostap_handle_sta_rx(ieee, dev, skb, rx_stats,
+					     wds != NULL)) {
+		case AP_RX_CONTINUE_NOT_AUTHORIZED:
+			frame_authorized = 0;
+			break;
+		case AP_RX_CONTINUE:
+			frame_authorized = 1;
+			break;
+		case AP_RX_DROP:
+			goto rx_dropped;
+		case AP_RX_EXIT:
+			goto rx_exit;
+		}
+	}
+#endif
+	//IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, skb->data, skb->len);
+	/* Nullfunc frames may have PS-bit set, so they must be passed to
+	 * hostap_handle_sta_rx() before being dropped here. */
+	if (stype != IEEE80211_STYPE_DATA &&
+	    stype != IEEE80211_STYPE_DATA_CFACK &&
+	    stype != IEEE80211_STYPE_DATA_CFPOLL &&
+	    stype != IEEE80211_STYPE_DATA_CFACKPOLL&&
+	    stype != IEEE80211_STYPE_QOS_DATA//add by David,2006.8.4
+	    ) {
+		if (stype != IEEE80211_STYPE_NULLFUNC)
+			IEEE80211_DEBUG_DROP(
+				"RX: dropped data frame "
+				"with no data (type=0x%02x, "
+				"subtype=0x%02x, len=%d)\n",
+				type, stype, skb->len);
+		goto rx_dropped;
+	}
+        if (memcmp(bssid, ieee->current_network.bssid, ETH_ALEN))
+                goto rx_dropped;
+
+	/* skb: hdr + (possibly fragmented, possibly encrypted) payload */
+
+	if (ieee->host_decrypt && (fc & IEEE80211_FCTL_WEP) &&
+	    (keyidx = ieee80211_rx_frame_decrypt(ieee, skb, crypt)) < 0)
+	{
+		printk("decrypt frame error\n");
+		goto rx_dropped;
+	}
+
+
+	hdr = (struct ieee80211_hdr_4addr *) skb->data;
+
+	/* skb: hdr + (possibly fragmented) plaintext payload */
+	// PR: FIXME: hostap has additional conditions in the "if" below:
+	// ieee->host_decrypt && (fc & IEEE80211_FCTL_WEP) &&
+	if ((frag != 0 || (fc & IEEE80211_FCTL_MOREFRAGS))) {
+		int flen;
+		struct sk_buff *frag_skb = ieee80211_frag_cache_get(ieee, hdr);
+		IEEE80211_DEBUG_FRAG("Rx Fragment received (%u)\n", frag);
+
+		if (!frag_skb) {
+			IEEE80211_DEBUG(IEEE80211_DL_RX | IEEE80211_DL_FRAG,
+					"Rx cannot get skb from fragment "
+					"cache (morefrag=%d seq=%u frag=%u)\n",
+					(fc & IEEE80211_FCTL_MOREFRAGS) != 0,
+					WLAN_GET_SEQ_SEQ(sc), frag);
+			goto rx_dropped;
+		}
+		flen = skb->len;
+		if (frag != 0)
+			flen -= hdrlen;
+
+		if (frag_skb->tail + flen > frag_skb->end) {
+			printk(KERN_WARNING "%s: host decrypted and "
+			       "reassembled frame did not fit skb\n",
+			       dev->name);
+			ieee80211_frag_cache_invalidate(ieee, hdr);
+			goto rx_dropped;
+		}
+
+		if (frag == 0) {
+			/* copy first fragment (including full headers) into
+			 * beginning of the fragment cache skb */
+			memcpy(skb_put(frag_skb, flen), skb->data, flen);
+		} else {
+			/* append frame payload to the end of the fragment
+			 * cache skb */
+			memcpy(skb_put(frag_skb, flen), skb->data + hdrlen,
+			       flen);
+		}
+		dev_kfree_skb_any(skb);
+		skb = NULL;
+
+		if (fc & IEEE80211_FCTL_MOREFRAGS) {
+			/* more fragments expected - leave the skb in fragment
+			 * cache for now; it will be delivered to upper layers
+			 * after all fragments have been received */
+			goto rx_exit;
+		}
+
+		/* this was the last fragment and the frame will be
+		 * delivered, so remove skb from fragment cache */
+		skb = frag_skb;
+		hdr = (struct ieee80211_hdr_4addr *) skb->data;
+		ieee80211_frag_cache_invalidate(ieee, hdr);
+	}
+
+	/* skb: hdr + (possible reassembled) full MSDU payload; possibly still
+	 * encrypted/authenticated */
+	if (ieee->host_decrypt && (fc & IEEE80211_FCTL_WEP) &&
+	    ieee80211_rx_frame_decrypt_msdu(ieee, skb, keyidx, crypt))
+	{
+		printk("==>decrypt msdu error\n");
+		goto rx_dropped;
+	}
+
+	//added by amy for AP roaming
+	ieee->LinkDetectInfo.NumRecvDataInPeriod++;
+	ieee->LinkDetectInfo.NumRxOkInPeriod++;
+
+	hdr = (struct ieee80211_hdr_4addr *) skb->data;
+	if (crypt && !(fc & IEEE80211_FCTL_WEP) && !ieee->open_wep) {
+		if (/*ieee->ieee802_1x &&*/
+		    ieee80211_is_eapol_frame(ieee, skb, hdrlen)) {
+
+#ifdef CONFIG_IEEE80211_DEBUG
+			/* pass unencrypted EAPOL frames even if encryption is
+			 * configured */
+			struct eapol *eap = (struct eapol *)(skb->data +
+				24);
+			IEEE80211_DEBUG_EAP("RX: IEEE 802.1X EAPOL frame: %s\n",
+						eap_get_type(eap->type));
+#endif
+		} else {
+			IEEE80211_DEBUG_DROP(
+				"encryption configured, but RX "
+				"frame not encrypted (SA=" MAC_FMT ")\n",
+				MAC_ARG(hdr->addr2));
+			goto rx_dropped;
+		}
+	}
+
+#ifdef CONFIG_IEEE80211_DEBUG
+	if (crypt && !(fc & IEEE80211_FCTL_WEP) &&
+	    ieee80211_is_eapol_frame(ieee, skb, hdrlen)) {
+			struct eapol *eap = (struct eapol *)(skb->data +
+				24);
+			IEEE80211_DEBUG_EAP("RX: IEEE 802.1X EAPOL frame: %s\n",
+						eap_get_type(eap->type));
+	}
+#endif
+
+	if (crypt && !(fc & IEEE80211_FCTL_WEP) && !ieee->open_wep &&
+	    !ieee80211_is_eapol_frame(ieee, skb, hdrlen)) {
+		IEEE80211_DEBUG_DROP(
+			"dropped unencrypted RX data "
+			"frame from " MAC_FMT
+			" (drop_unencrypted=1)\n",
+			MAC_ARG(hdr->addr2));
+		goto rx_dropped;
+	}
+/*
+	if(ieee80211_is_eapol_frame(ieee, skb, hdrlen)) {
+		printk(KERN_WARNING "RX: IEEE802.1X EPAOL frame!\n");
+	}
+*/
+//added by amy for reorder
+#if 1
+	if(ieee->current_network.qos_data.active && IsQoSDataFrame(skb->data)
+		&& !is_multicast_ether_addr(hdr->addr1) && !is_broadcast_ether_addr(hdr->addr1))
+	{
+		TID = Frame_QoSTID(skb->data);
+		SeqNum = WLAN_GET_SEQ_SEQ(sc);
+		GetTs(ieee,(PTS_COMMON_INFO*) &pTS,hdr->addr2,TID,RX_DIR,true);
+		if(TID !=0 && TID !=3)
+		{
+			ieee->bis_any_nonbepkts = true;
+		}
+	}
+#endif
+//added by amy for reorder
+	/* skb: hdr + (possible reassembled) full plaintext payload */
+	payload = skb->data + hdrlen;
+	//ethertype = (payload[6] << 8) | payload[7];
+	rxb = (struct ieee80211_rxb*)kmalloc(sizeof(struct ieee80211_rxb),GFP_ATOMIC);
+	if(rxb == NULL)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR,"%s(): kmalloc rxb error\n",__FUNCTION__);
+		goto rx_dropped;
+	}
+	/* to parse amsdu packets */
+	/* qos data packets & reserved bit is 1 */
+	if(parse_subframe(skb,rx_stats,rxb,src,dst) == 0) {
+		/* only to free rxb, and not submit the packets to upper layer */
+		for(i =0; i < rxb->nr_subframes; i++) {
+			dev_kfree_skb(rxb->subframes[i]);
+		}
+		kfree(rxb);
+		rxb = NULL;
+		goto rx_dropped;
+	}
+
+	ieee->last_rx_ps_time = jiffies;
+//added by amy for reorder
+	if(ieee->pHTInfo->bCurRxReorderEnable == false ||pTS == NULL){
+//added by amy for reorder
+		for(i = 0; i<rxb->nr_subframes; i++) {
+			struct sk_buff *sub_skb = rxb->subframes[i];
+
+			if (sub_skb) {
+				/* convert hdr + possible LLC headers into Ethernet header */
+				ethertype = (sub_skb->data[6] << 8) | sub_skb->data[7];
+				if (sub_skb->len >= 8 &&
+						((memcmp(sub_skb->data, rfc1042_header, SNAP_SIZE) == 0 &&
+						  ethertype != ETH_P_AARP && ethertype != ETH_P_IPX) ||
+						 memcmp(sub_skb->data, bridge_tunnel_header, SNAP_SIZE) == 0)) {
+					/* remove RFC1042 or Bridge-Tunnel encapsulation and
+					 * replace EtherType */
+					skb_pull(sub_skb, SNAP_SIZE);
+					memcpy(skb_push(sub_skb, ETH_ALEN), src, ETH_ALEN);
+					memcpy(skb_push(sub_skb, ETH_ALEN), dst, ETH_ALEN);
+				} else {
+					u16 len;
+					/* Leave Ethernet header part of hdr and full payload */
+					len = htons(sub_skb->len);
+					memcpy(skb_push(sub_skb, 2), &len, 2);
+					memcpy(skb_push(sub_skb, ETH_ALEN), src, ETH_ALEN);
+					memcpy(skb_push(sub_skb, ETH_ALEN), dst, ETH_ALEN);
+				}
+
+				stats->rx_packets++;
+				stats->rx_bytes += sub_skb->len;
+				if(is_multicast_ether_addr(dst)) {
+					stats->multicast++;
+				}
+
+				/* Indicat the packets to upper layer */
+				//printk("0skb_len(%d)\n", skb->len);
+				sub_skb->protocol = eth_type_trans(sub_skb, dev);
+				memset(sub_skb->cb, 0, sizeof(sub_skb->cb));
+				sub_skb->dev = dev;
+				sub_skb->ip_summed = CHECKSUM_NONE; /* 802.11 crc not sufficient */
+				//skb->ip_summed = CHECKSUM_UNNECESSARY; /* 802.11 crc not sufficient */
+				//printk("1skb_len(%d)\n", skb->len);
+				netif_rx(sub_skb);
+			}
+		}
+		kfree(rxb);
+		rxb = NULL;
+
+	}
+	else
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_REORDER,"%s(): REORDER ENABLE AND PTS not NULL, and we will enter RxReorderIndicatePacket()\n",__FUNCTION__);
+		RxReorderIndicatePacket(ieee, rxb, pTS, SeqNum);
+	}
+#ifndef JOHN_NOCPY
+	dev_kfree_skb(skb);
+#endif
+
+ rx_exit:
+#ifdef NOT_YET
+	if (sta)
+		hostap_handle_sta_release(sta);
+#endif
+	return 1;
+
+ rx_dropped:
+	if (rxb != NULL)
+	{
+		kfree(rxb);
+		rxb = NULL;
+	}
+	stats->rx_dropped++;
+
+	/* Returning 0 indicates to caller that we have not handled the SKB--
+	 * so it is still allocated and can be used again by underlying
+	 * hardware as a DMA target */
+	return 0;
+}
+
+#define MGMT_FRAME_FIXED_PART_LENGTH            0x24
+
+static u8 qos_oui[QOS_OUI_LEN] = { 0x00, 0x50, 0xF2 };
+
+/*
+* Make ther structure we read from the beacon packet has
+* the right values
+*/
+static int ieee80211_verify_qos_info(struct ieee80211_qos_information_element
+                                     *info_element, int sub_type)
+{
+
+        if (info_element->qui_subtype != sub_type)
+                return -1;
+        if (memcmp(info_element->qui, qos_oui, QOS_OUI_LEN))
+                return -1;
+        if (info_element->qui_type != QOS_OUI_TYPE)
+                return -1;
+        if (info_element->version != QOS_VERSION_1)
+                return -1;
+
+        return 0;
+}
+
+
+/*
+ * Parse a QoS parameter element
+ */
+static int ieee80211_read_qos_param_element(struct ieee80211_qos_parameter_info
+                                            *element_param, struct ieee80211_info_element
+                                            *info_element)
+{
+        int ret = 0;
+        u16 size = sizeof(struct ieee80211_qos_parameter_info) - 2;
+
+        if ((info_element == NULL) || (element_param == NULL))
+                return -1;
+
+        if (info_element->id == QOS_ELEMENT_ID && info_element->len == size) {
+                memcpy(element_param->info_element.qui, info_element->data,
+                       info_element->len);
+                element_param->info_element.elementID = info_element->id;
+                element_param->info_element.length = info_element->len;
+        } else
+                ret = -1;
+        if (ret == 0)
+                ret = ieee80211_verify_qos_info(&element_param->info_element,
+                                                QOS_OUI_PARAM_SUB_TYPE);
+        return ret;
+}
+
+/*
+ * Parse a QoS information element
+ */
+static int ieee80211_read_qos_info_element(struct
+                                           ieee80211_qos_information_element
+                                           *element_info, struct ieee80211_info_element
+                                           *info_element)
+{
+        int ret = 0;
+        u16 size = sizeof(struct ieee80211_qos_information_element) - 2;
+
+        if (element_info == NULL)
+                return -1;
+        if (info_element == NULL)
+                return -1;
+
+        if ((info_element->id == QOS_ELEMENT_ID) && (info_element->len == size)) {
+                memcpy(element_info->qui, info_element->data,
+                       info_element->len);
+                element_info->elementID = info_element->id;
+                element_info->length = info_element->len;
+        } else
+                ret = -1;
+
+        if (ret == 0)
+                ret = ieee80211_verify_qos_info(element_info,
+                                                QOS_OUI_INFO_SUB_TYPE);
+        return ret;
+}
+
+
+/*
+ * Write QoS parameters from the ac parameters.
+ */
+static int ieee80211_qos_convert_ac_to_parameters(struct
+                                                  ieee80211_qos_parameter_info
+                                                  *param_elm, struct
+                                                  ieee80211_qos_parameters
+                                                  *qos_param)
+{
+        int rc = 0;
+        int i;
+        struct ieee80211_qos_ac_parameter *ac_params;
+	u8 aci;
+        //u8 cw_min;
+        //u8 cw_max;
+
+        for (i = 0; i < QOS_QUEUE_NUM; i++) {
+                ac_params = &(param_elm->ac_params_record[i]);
+
+		aci = (ac_params->aci_aifsn & 0x60) >> 5;
+
+		if(aci >= QOS_QUEUE_NUM)
+			continue;
+                qos_param->aifs[aci] = (ac_params->aci_aifsn) & 0x0f;
+
+		/* WMM spec P.11: The minimum value for AIFSN shall be 2 */
+                qos_param->aifs[aci] = (qos_param->aifs[aci] < 2) ? 2:qos_param->aifs[aci];
+
+                qos_param->cw_min[aci] = ac_params->ecw_min_max & 0x0F;
+
+                qos_param->cw_max[aci] = (ac_params->ecw_min_max & 0xF0) >> 4;
+
+                qos_param->flag[aci] =
+                    (ac_params->aci_aifsn & 0x10) ? 0x01 : 0x00;
+                qos_param->tx_op_limit[aci] = le16_to_cpu(ac_params->tx_op_limit);
+        }
+        return rc;
+}
+
+/*
+ * we have a generic data element which it may contain QoS information or
+ * parameters element. check the information element length to decide
+ * which type to read
+ */
+static int ieee80211_parse_qos_info_param_IE(struct ieee80211_info_element
+                                             *info_element,
+                                             struct ieee80211_network *network)
+{
+        int rc = 0;
+        struct ieee80211_qos_parameters *qos_param = NULL;
+        struct ieee80211_qos_information_element qos_info_element;
+
+        rc = ieee80211_read_qos_info_element(&qos_info_element, info_element);
+
+        if (rc == 0) {
+                network->qos_data.param_count = qos_info_element.ac_info & 0x0F;
+                network->flags |= NETWORK_HAS_QOS_INFORMATION;
+        } else {
+                struct ieee80211_qos_parameter_info param_element;
+
+                rc = ieee80211_read_qos_param_element(&param_element,
+                                                      info_element);
+                if (rc == 0) {
+                        qos_param = &(network->qos_data.parameters);
+                        ieee80211_qos_convert_ac_to_parameters(&param_element,
+                                                               qos_param);
+                        network->flags |= NETWORK_HAS_QOS_PARAMETERS;
+                        network->qos_data.param_count =
+                            param_element.info_element.ac_info & 0x0F;
+                }
+        }
+
+        if (rc == 0) {
+                IEEE80211_DEBUG_QOS("QoS is supported\n");
+                network->qos_data.supported = 1;
+        }
+        return rc;
+}
+
+#ifdef CONFIG_IEEE80211_DEBUG
+#define MFIE_STRING(x) case MFIE_TYPE_ ##x: return #x
+
+static const char *get_info_element_string(u16 id)
+{
+        switch (id) {
+                MFIE_STRING(SSID);
+                MFIE_STRING(RATES);
+                MFIE_STRING(FH_SET);
+                MFIE_STRING(DS_SET);
+                MFIE_STRING(CF_SET);
+                MFIE_STRING(TIM);
+                MFIE_STRING(IBSS_SET);
+                MFIE_STRING(COUNTRY);
+                MFIE_STRING(HOP_PARAMS);
+                MFIE_STRING(HOP_TABLE);
+                MFIE_STRING(REQUEST);
+                MFIE_STRING(CHALLENGE);
+                MFIE_STRING(POWER_CONSTRAINT);
+                MFIE_STRING(POWER_CAPABILITY);
+                MFIE_STRING(TPC_REQUEST);
+                MFIE_STRING(TPC_REPORT);
+                MFIE_STRING(SUPP_CHANNELS);
+                MFIE_STRING(CSA);
+                MFIE_STRING(MEASURE_REQUEST);
+                MFIE_STRING(MEASURE_REPORT);
+                MFIE_STRING(QUIET);
+                MFIE_STRING(IBSS_DFS);
+               // MFIE_STRING(ERP_INFO);
+                MFIE_STRING(RSN);
+                MFIE_STRING(RATES_EX);
+                MFIE_STRING(GENERIC);
+                MFIE_STRING(QOS_PARAMETER);
+        default:
+                return "UNKNOWN";
+        }
+}
+#endif
+
+#ifdef ENABLE_DOT11D
+static inline void ieee80211_extract_country_ie(
+	struct ieee80211_device *ieee,
+	struct ieee80211_info_element *info_element,
+	struct ieee80211_network *network,
+	u8 * addr2
+)
+{
+	if(IS_DOT11D_ENABLE(ieee))
+	{
+		if(info_element->len!= 0)
+		{
+			memcpy(network->CountryIeBuf, info_element->data, info_element->len);
+			network->CountryIeLen = info_element->len;
+
+			if(!IS_COUNTRY_IE_VALID(ieee))
+			{
+				Dot11d_UpdateCountryIe(ieee, addr2, info_element->len, info_element->data);
+			}
+		}
+
+		//
+		// 070305, rcnjko: I update country IE watch dog here because
+		// some AP (e.g. Cisco 1242) don't include country IE in their
+		// probe response frame.
+		//
+		if(IS_EQUAL_CIE_SRC(ieee, addr2) )
+		{
+			UPDATE_CIE_WATCHDOG(ieee);
+		}
+	}
+
+}
+#endif
+
+int ieee80211_parse_info_param(struct ieee80211_device *ieee,
+		struct ieee80211_info_element *info_element,
+		u16 length,
+		struct ieee80211_network *network,
+		struct ieee80211_rx_stats *stats)
+{
+	u8 i;
+	short offset;
+        u16	tmp_htcap_len=0;
+	u16	tmp_htinfo_len=0;
+	u16 ht_realtek_agg_len=0;
+	u8  ht_realtek_agg_buf[MAX_IE_LEN];
+//	u16 broadcom_len = 0;
+#ifdef CONFIG_IEEE80211_DEBUG
+	char rates_str[64];
+	char *p;
+#endif
+
+	while (length >= sizeof(*info_element)) {
+		if (sizeof(*info_element) + info_element->len > length) {
+			IEEE80211_DEBUG_MGMT("Info elem: parse failed: "
+					     "info_element->len + 2 > left : "
+					     "info_element->len+2=%zd left=%d, id=%d.\n",
+					     info_element->len +
+					     sizeof(*info_element),
+					     length, info_element->id);
+			/* We stop processing but don't return an error here
+			 * because some misbehaviour APs break this rule. ie.
+			 * Orinoco AP1000. */
+			break;
+		}
+
+		switch (info_element->id) {
+		case MFIE_TYPE_SSID:
+			if (ieee80211_is_empty_essid(info_element->data,
+						     info_element->len)) {
+				network->flags |= NETWORK_EMPTY_ESSID;
+				break;
+			}
+
+			network->ssid_len = min(info_element->len,
+						(u8) IW_ESSID_MAX_SIZE);
+			memcpy(network->ssid, info_element->data, network->ssid_len);
+			if (network->ssid_len < IW_ESSID_MAX_SIZE)
+				memset(network->ssid + network->ssid_len, 0,
+				       IW_ESSID_MAX_SIZE - network->ssid_len);
+
+			IEEE80211_DEBUG_MGMT("MFIE_TYPE_SSID: '%s' len=%d.\n",
+					     network->ssid, network->ssid_len);
+			break;
+
+		case MFIE_TYPE_RATES:
+#ifdef CONFIG_IEEE80211_DEBUG
+			p = rates_str;
+#endif
+			network->rates_len = min(info_element->len,
+						 MAX_RATES_LENGTH);
+			for (i = 0; i < network->rates_len; i++) {
+				network->rates[i] = info_element->data[i];
+#ifdef CONFIG_IEEE80211_DEBUG
+				p += snprintf(p, sizeof(rates_str) -
+					      (p - rates_str), "%02X ",
+					      network->rates[i]);
+#endif
+				if (ieee80211_is_ofdm_rate
+				    (info_element->data[i])) {
+					network->flags |= NETWORK_HAS_OFDM;
+					if (info_element->data[i] &
+					    IEEE80211_BASIC_RATE_MASK)
+						network->flags &=
+						    ~NETWORK_HAS_CCK;
+				}
+			}
+
+			IEEE80211_DEBUG_MGMT("MFIE_TYPE_RATES: '%s' (%d)\n",
+					     rates_str, network->rates_len);
+			break;
+
+		case MFIE_TYPE_RATES_EX:
+#ifdef CONFIG_IEEE80211_DEBUG
+			p = rates_str;
+#endif
+			network->rates_ex_len = min(info_element->len,
+						    MAX_RATES_EX_LENGTH);
+			for (i = 0; i < network->rates_ex_len; i++) {
+				network->rates_ex[i] = info_element->data[i];
+#ifdef CONFIG_IEEE80211_DEBUG
+				p += snprintf(p, sizeof(rates_str) -
+					      (p - rates_str), "%02X ",
+					      network->rates[i]);
+#endif
+				if (ieee80211_is_ofdm_rate
+				    (info_element->data[i])) {
+					network->flags |= NETWORK_HAS_OFDM;
+					if (info_element->data[i] &
+					    IEEE80211_BASIC_RATE_MASK)
+						network->flags &=
+						    ~NETWORK_HAS_CCK;
+				}
+			}
+
+			IEEE80211_DEBUG_MGMT("MFIE_TYPE_RATES_EX: '%s' (%d)\n",
+					     rates_str, network->rates_ex_len);
+			break;
+
+		case MFIE_TYPE_DS_SET:
+			IEEE80211_DEBUG_MGMT("MFIE_TYPE_DS_SET: %d\n",
+					     info_element->data[0]);
+			network->channel = info_element->data[0];
+			break;
+
+		case MFIE_TYPE_FH_SET:
+			IEEE80211_DEBUG_MGMT("MFIE_TYPE_FH_SET: ignored\n");
+			break;
+
+		case MFIE_TYPE_CF_SET:
+			IEEE80211_DEBUG_MGMT("MFIE_TYPE_CF_SET: ignored\n");
+			break;
+
+		case MFIE_TYPE_TIM:
+			if(info_element->len < 4)
+				break;
+
+			network->tim.tim_count = info_element->data[0];
+			network->tim.tim_period = info_element->data[1];
+
+                        network->dtim_period = info_element->data[1];
+                        if(ieee->state != IEEE80211_LINKED)
+                                break;
+#if 0
+                        network->last_dtim_sta_time[0] = stats->mac_time[0];
+#else
+			//we use jiffies for legacy Power save
+			network->last_dtim_sta_time[0] = jiffies;
+#endif
+                        network->last_dtim_sta_time[1] = stats->mac_time[1];
+
+                        network->dtim_data = IEEE80211_DTIM_VALID;
+
+                        if(info_element->data[0] != 0)
+                                break;
+
+                        if(info_element->data[2] & 1)
+                                network->dtim_data |= IEEE80211_DTIM_MBCAST;
+
+                        offset = (info_element->data[2] >> 1)*2;
+
+                        //printk("offset1:%x aid:%x\n",offset, ieee->assoc_id);
+
+                        if(ieee->assoc_id < 8*offset ||
+                                ieee->assoc_id > 8*(offset + info_element->len -3))
+
+                                break;
+
+                        offset = (ieee->assoc_id / 8) - offset;// + ((aid % 8)? 0 : 1) ;
+
+                        if(info_element->data[3+offset] & (1<<(ieee->assoc_id%8)))
+                                network->dtim_data |= IEEE80211_DTIM_UCAST;
+
+			//IEEE80211_DEBUG_MGMT("MFIE_TYPE_TIM: partially ignored\n");
+			break;
+
+		case MFIE_TYPE_ERP:
+			network->erp_value = info_element->data[0];
+			network->flags |= NETWORK_HAS_ERP_VALUE;
+			IEEE80211_DEBUG_MGMT("MFIE_TYPE_ERP_SET: %d\n",
+					     network->erp_value);
+			break;
+		case MFIE_TYPE_IBSS_SET:
+			network->atim_window = info_element->data[0];
+			IEEE80211_DEBUG_MGMT("MFIE_TYPE_IBSS_SET: %d\n",
+					     network->atim_window);
+			break;
+
+		case MFIE_TYPE_CHALLENGE:
+			IEEE80211_DEBUG_MGMT("MFIE_TYPE_CHALLENGE: ignored\n");
+			break;
+
+		case MFIE_TYPE_GENERIC:
+			IEEE80211_DEBUG_MGMT("MFIE_TYPE_GENERIC: %d bytes\n",
+					     info_element->len);
+			if (!ieee80211_parse_qos_info_param_IE(info_element,
+							       network))
+				break;
+
+			if (info_element->len >= 4 &&
+			    info_element->data[0] == 0x00 &&
+			    info_element->data[1] == 0x50 &&
+			    info_element->data[2] == 0xf2 &&
+			    info_element->data[3] == 0x01) {
+				network->wpa_ie_len = min(info_element->len + 2,
+							  MAX_WPA_IE_LEN);
+				memcpy(network->wpa_ie, info_element,
+				       network->wpa_ie_len);
+				break;
+			}
+
+#ifdef THOMAS_TURBO
+                        if (info_element->len == 7 &&
+                            info_element->data[0] == 0x00 &&
+                            info_element->data[1] == 0xe0 &&
+                            info_element->data[2] == 0x4c &&
+                            info_element->data[3] == 0x01 &&
+                            info_element->data[4] == 0x02) {
+                                network->Turbo_Enable = 1;
+                        }
+#endif
+
+                        //for HTcap and HTinfo parameters
+			if(tmp_htcap_len == 0){
+				if(info_element->len >= 4 &&
+				   info_element->data[0] == 0x00 &&
+				   info_element->data[1] == 0x90 &&
+				   info_element->data[2] == 0x4c &&
+				   info_element->data[3] == 0x033){
+
+						tmp_htcap_len = min(info_element->len,(u8)MAX_IE_LEN);
+				   		if(tmp_htcap_len != 0){
+				   			network->bssht.bdHTSpecVer = HT_SPEC_VER_EWC;
+							network->bssht.bdHTCapLen = tmp_htcap_len > sizeof(network->bssht.bdHTCapBuf)?\
+								sizeof(network->bssht.bdHTCapBuf):tmp_htcap_len;
+							memcpy(network->bssht.bdHTCapBuf,info_element->data,network->bssht.bdHTCapLen);
+				   		}
+				}
+				if(tmp_htcap_len != 0){
+					network->bssht.bdSupportHT = true;
+					network->bssht.bdHT1R = ((((PHT_CAPABILITY_ELE)(network->bssht.bdHTCapBuf))->MCS[1]) == 0);
+				}else{
+					network->bssht.bdSupportHT = false;
+					network->bssht.bdHT1R = false;
+				}
+			}
+
+
+			if(tmp_htinfo_len == 0){
+				if(info_element->len >= 4 &&
+					info_element->data[0] == 0x00 &&
+				   	info_element->data[1] == 0x90 &&
+				   	info_element->data[2] == 0x4c &&
+				   	info_element->data[3] == 0x034){
+
+						tmp_htinfo_len = min(info_element->len,(u8)MAX_IE_LEN);
+						if(tmp_htinfo_len != 0){
+							network->bssht.bdHTSpecVer = HT_SPEC_VER_EWC;
+							if(tmp_htinfo_len){
+								network->bssht.bdHTInfoLen = tmp_htinfo_len > sizeof(network->bssht.bdHTInfoBuf)?\
+									sizeof(network->bssht.bdHTInfoBuf):tmp_htinfo_len;
+								memcpy(network->bssht.bdHTInfoBuf,info_element->data,network->bssht.bdHTInfoLen);
+							}
+
+						}
+
+				}
+			}
+
+			if(ieee->aggregation){
+				if(network->bssht.bdSupportHT){
+					if(info_element->len >= 4 &&
+						info_element->data[0] == 0x00 &&
+						info_element->data[1] == 0xe0 &&
+						info_element->data[2] == 0x4c &&
+						info_element->data[3] == 0x02){
+
+						ht_realtek_agg_len = min(info_element->len,(u8)MAX_IE_LEN);
+						memcpy(ht_realtek_agg_buf,info_element->data,info_element->len);
+
+					}
+					if(ht_realtek_agg_len >= 5){
+						network->realtek_cap_exit = true;
+						network->bssht.bdRT2RTAggregation = true;
+
+						if((ht_realtek_agg_buf[4] == 1) && (ht_realtek_agg_buf[5] & 0x02))
+						network->bssht.bdRT2RTLongSlotTime = true;
+
+						if((ht_realtek_agg_buf[4]==1) && (ht_realtek_agg_buf[5] & RT_HT_CAP_USE_92SE))
+						{
+							network->bssht.RT2RT_HT_Mode |= RT_HT_CAP_USE_92SE;
+							//bssDesc->Vender = HT_IOT_PEER_REALTEK_92SE;
+						}
+					}
+				}
+
+			}
+
+			//if(tmp_htcap_len !=0  ||  tmp_htinfo_len != 0)
+			{
+				if((info_element->len >= 3 &&
+					 info_element->data[0] == 0x00 &&
+					 info_element->data[1] == 0x05 &&
+					 info_element->data[2] == 0xb5) ||
+					 (info_element->len >= 3 &&
+					 info_element->data[0] == 0x00 &&
+					 info_element->data[1] == 0x0a &&
+					 info_element->data[2] == 0xf7) ||
+					 (info_element->len >= 3 &&
+					 info_element->data[0] == 0x00 &&
+					 info_element->data[1] == 0x10 &&
+					 info_element->data[2] == 0x18)){
+
+						network->broadcom_cap_exist = true;
+
+				}
+			}
+#if 0
+			if (tmp_htcap_len !=0)
+				{
+					u16 cap_ext = ((PHT_CAPABILITY_ELE)&info_element->data[0])->ExtHTCapInfo;
+					if ((cap_ext & 0x0c00) == 0x0c00)
+						{
+							network->ralink_cap_exist = true;
+						}
+				}
+#endif
+			if(info_element->len >= 3 &&
+				info_element->data[0] == 0x00 &&
+				info_element->data[1] == 0x0c &&
+				info_element->data[2] == 0x43)
+			{
+				network->ralink_cap_exist = true;
+			}
+			else
+				network->ralink_cap_exist = false;
+			//added by amy for atheros AP
+			if((info_element->len >= 3 &&
+				info_element->data[0] == 0x00 &&
+				info_element->data[1] == 0x03 &&
+				info_element->data[2] == 0x7f) ||
+				(info_element->len >= 3 &&
+				info_element->data[0] == 0x00 &&
+				info_element->data[1] == 0x13 &&
+				info_element->data[2] == 0x74))
+			{
+			//	printk("========>%s(): athros AP is exist\n",__FUNCTION__);
+				network->atheros_cap_exist = true;
+			}
+			else
+				network->atheros_cap_exist = false;
+
+			if ((info_element->len >= 3 &&
+				info_element->data[0] == 0x00 &&
+				info_element->data[1] == 0x50 &&
+				info_element->data[2] == 0x43) )
+				{
+					network->marvell_cap_exist = true;
+				}
+			else
+				network->marvell_cap_exist = false;
+
+			if(info_element->len >= 3 &&
+				info_element->data[0] == 0x00 &&
+				info_element->data[1] == 0x40 &&
+				info_element->data[2] == 0x96)
+			{
+				network->cisco_cap_exist = true;
+			}
+			else
+				network->cisco_cap_exist = false;
+			//added by amy for LEAP of cisco
+			if(info_element->len > 4 &&
+				info_element->data[0] == 0x00 &&
+				info_element->data[1] == 0x40 &&
+				info_element->data[2] == 0x96 &&
+				info_element->data[3] == 0x01)
+			{
+				if(info_element->len == 6)
+				{
+					memcpy(network->CcxRmState, &info_element[4], 2);
+					if(network->CcxRmState[0] != 0)
+					{
+						network->bCcxRmEnable = true;
+					}
+					else
+						network->bCcxRmEnable = false;
+					//
+					// CCXv4 Table 59-1 MBSSID Masks.
+					//
+					network->MBssidMask = network->CcxRmState[1] & 0x07;
+					if(network->MBssidMask != 0)
+					{
+						network->bMBssidValid = true;
+						network->MBssidMask = 0xff << (network->MBssidMask);
+						cpMacAddr(network->MBssid, network->bssid);
+						network->MBssid[5] &= network->MBssidMask;
+					}
+					else
+					{
+						network->bMBssidValid = false;
+					}
+				}
+				else
+				{
+					network->bCcxRmEnable = false;
+				}
+			}
+			if(info_element->len > 4  &&
+				info_element->data[0] == 0x00 &&
+				info_element->data[1] == 0x40 &&
+				info_element->data[2] == 0x96 &&
+				info_element->data[3] == 0x03)
+			{
+				if(info_element->len == 5)
+				{
+					network->bWithCcxVerNum = true;
+					network->BssCcxVerNumber = info_element->data[4];
+				}
+				else
+				{
+					network->bWithCcxVerNum = false;
+					network->BssCcxVerNumber = 0;
+				}
+			}
+			break;
+
+		case MFIE_TYPE_RSN:
+			IEEE80211_DEBUG_MGMT("MFIE_TYPE_RSN: %d bytes\n",
+					     info_element->len);
+			network->rsn_ie_len = min(info_element->len + 2,
+						  MAX_WPA_IE_LEN);
+			memcpy(network->rsn_ie, info_element,
+			       network->rsn_ie_len);
+			break;
+
+                        //HT related element.
+		case MFIE_TYPE_HT_CAP:
+			IEEE80211_DEBUG_SCAN("MFIE_TYPE_HT_CAP: %d bytes\n",
+					     info_element->len);
+			tmp_htcap_len = min(info_element->len,(u8)MAX_IE_LEN);
+			if(tmp_htcap_len != 0){
+				network->bssht.bdHTSpecVer = HT_SPEC_VER_EWC;
+				network->bssht.bdHTCapLen = tmp_htcap_len > sizeof(network->bssht.bdHTCapBuf)?\
+					sizeof(network->bssht.bdHTCapBuf):tmp_htcap_len;
+				memcpy(network->bssht.bdHTCapBuf,info_element->data,network->bssht.bdHTCapLen);
+
+				//If peer is HT, but not WMM, call QosSetLegacyWMMParamWithHT()
+				// windows driver will update WMM parameters each beacon received once connected
+                                // Linux driver is a bit different.
+				network->bssht.bdSupportHT = true;
+				network->bssht.bdHT1R = ((((PHT_CAPABILITY_ELE)(network->bssht.bdHTCapBuf))->MCS[1]) == 0);
+			}
+			else{
+				network->bssht.bdSupportHT = false;
+				network->bssht.bdHT1R = false;
+			}
+			break;
+
+
+		case MFIE_TYPE_HT_INFO:
+			IEEE80211_DEBUG_SCAN("MFIE_TYPE_HT_INFO: %d bytes\n",
+					     info_element->len);
+			tmp_htinfo_len = min(info_element->len,(u8)MAX_IE_LEN);
+			if(tmp_htinfo_len){
+				network->bssht.bdHTSpecVer = HT_SPEC_VER_IEEE;
+				network->bssht.bdHTInfoLen = tmp_htinfo_len > sizeof(network->bssht.bdHTInfoBuf)?\
+					sizeof(network->bssht.bdHTInfoBuf):tmp_htinfo_len;
+				memcpy(network->bssht.bdHTInfoBuf,info_element->data,network->bssht.bdHTInfoLen);
+			}
+			break;
+
+		case MFIE_TYPE_AIRONET:
+			IEEE80211_DEBUG_SCAN("MFIE_TYPE_AIRONET: %d bytes\n",
+					     info_element->len);
+			if(info_element->len >IE_CISCO_FLAG_POSITION)
+			{
+				network->bWithAironetIE = true;
+
+				// CCX 1 spec v1.13, A01.1 CKIP Negotiation (page23):
+				// "A Cisco access point advertises support for CKIP in beacon and probe response packets,
+				//  by adding an Aironet element and setting one or both of the CKIP negotiation bits."
+				if(	(info_element->data[IE_CISCO_FLAG_POSITION]&SUPPORT_CKIP_MIC)	||
+					(info_element->data[IE_CISCO_FLAG_POSITION]&SUPPORT_CKIP_PK)	)
+				{
+		 			network->bCkipSupported = true;
+				}
+				else
+				{
+					network->bCkipSupported = false;
+				}
+			}
+			else
+			{
+				network->bWithAironetIE = false;
+		 		network->bCkipSupported = false;
+			}
+			break;
+		case MFIE_TYPE_QOS_PARAMETER:
+			printk(KERN_ERR
+			       "QoS Error need to parse QOS_PARAMETER IE\n");
+			break;
+
+#ifdef ENABLE_DOT11D
+		case MFIE_TYPE_COUNTRY:
+			IEEE80211_DEBUG_SCAN("MFIE_TYPE_COUNTRY: %d bytes\n",
+					     info_element->len);
+			//printk("=====>Receive <%s> Country IE\n",network->ssid);
+			ieee80211_extract_country_ie(ieee, info_element, network, network->bssid);//addr2 is same as addr3 when from an AP
+			break;
+#endif
+/* TODO */
+#if 0
+			/* 802.11h */
+		case MFIE_TYPE_POWER_CONSTRAINT:
+			network->power_constraint = info_element->data[0];
+			network->flags |= NETWORK_HAS_POWER_CONSTRAINT;
+			break;
+
+		case MFIE_TYPE_CSA:
+			network->power_constraint = info_element->data[0];
+			network->flags |= NETWORK_HAS_CSA;
+			break;
+
+		case MFIE_TYPE_QUIET:
+			network->quiet.count = info_element->data[0];
+			network->quiet.period = info_element->data[1];
+			network->quiet.duration = info_element->data[2];
+			network->quiet.offset = info_element->data[3];
+			network->flags |= NETWORK_HAS_QUIET;
+			break;
+
+		case MFIE_TYPE_IBSS_DFS:
+			if (network->ibss_dfs)
+				break;
+			network->ibss_dfs = kmemdup(info_element->data,
+						    info_element->len,
+						    GFP_ATOMIC);
+			if (!network->ibss_dfs)
+				return 1;
+			network->flags |= NETWORK_HAS_IBSS_DFS;
+			break;
+
+		case MFIE_TYPE_TPC_REPORT:
+			network->tpc_report.transmit_power =
+			    info_element->data[0];
+			network->tpc_report.link_margin = info_element->data[1];
+			network->flags |= NETWORK_HAS_TPC_REPORT;
+			break;
+#endif
+		default:
+			IEEE80211_DEBUG_MGMT
+			    ("Unsupported info element: %s (%d)\n",
+			     get_info_element_string(info_element->id),
+			     info_element->id);
+			break;
+		}
+
+		length -= sizeof(*info_element) + info_element->len;
+		info_element =
+		    (struct ieee80211_info_element *)&info_element->
+		    data[info_element->len];
+	}
+
+	if(!network->atheros_cap_exist && !network->broadcom_cap_exist &&
+		!network->cisco_cap_exist && !network->ralink_cap_exist && !network->bssht.bdRT2RTAggregation)
+	{
+		network->unknown_cap_exist = true;
+	}
+	else
+	{
+		network->unknown_cap_exist = false;
+	}
+	return 0;
+}
+
+static inline u8 ieee80211_SignalStrengthTranslate(
+	u8  CurrSS
+	)
+{
+	u8 RetSS;
+
+	// Step 1. Scale mapping.
+	if(CurrSS >= 71 && CurrSS <= 100)
+	{
+		RetSS = 90 + ((CurrSS - 70) / 3);
+	}
+	else if(CurrSS >= 41 && CurrSS <= 70)
+	{
+		RetSS = 78 + ((CurrSS - 40) / 3);
+	}
+	else if(CurrSS >= 31 && CurrSS <= 40)
+	{
+		RetSS = 66 + (CurrSS - 30);
+	}
+	else if(CurrSS >= 21 && CurrSS <= 30)
+	{
+		RetSS = 54 + (CurrSS - 20);
+	}
+	else if(CurrSS >= 5 && CurrSS <= 20)
+	{
+		RetSS = 42 + (((CurrSS - 5) * 2) / 3);
+	}
+	else if(CurrSS == 4)
+	{
+		RetSS = 36;
+	}
+	else if(CurrSS == 3)
+	{
+		RetSS = 27;
+	}
+	else if(CurrSS == 2)
+	{
+		RetSS = 18;
+	}
+	else if(CurrSS == 1)
+	{
+		RetSS = 9;
+	}
+	else
+	{
+		RetSS = CurrSS;
+	}
+	//RT_TRACE(COMP_DBG, DBG_LOUD, ("##### After Mapping:  LastSS: %d, CurrSS: %d, RetSS: %d\n", LastSS, CurrSS, RetSS));
+
+	// Step 2. Smoothing.
+
+	//RT_TRACE(COMP_DBG, DBG_LOUD, ("$$$$$ After Smoothing:  LastSS: %d, CurrSS: %d, RetSS: %d\n", LastSS, CurrSS, RetSS));
+
+	return RetSS;
+}
+
+long ieee80211_translate_todbm(u8 signal_strength_index	)// 0-100 index.
+{
+	long	signal_power; // in dBm.
+
+	// Translate to dBm (x=0.5y-95).
+	signal_power = (long)((signal_strength_index + 1) >> 1);
+	signal_power -= 95;
+
+	return signal_power;
+}
+
+static inline int ieee80211_network_init(
+	struct ieee80211_device *ieee,
+	struct ieee80211_probe_response *beacon,
+	struct ieee80211_network *network,
+	struct ieee80211_rx_stats *stats)
+{
+#ifdef CONFIG_IEEE80211_DEBUG
+	//char rates_str[64];
+	//char *p;
+#endif
+
+        network->qos_data.active = 0;
+        network->qos_data.supported = 0;
+        network->qos_data.param_count = 0;
+        network->qos_data.old_param_count = 0;
+
+	/* Pull out fixed field data */
+	memcpy(network->bssid, beacon->header.addr3, ETH_ALEN);
+	network->capability = le16_to_cpu(beacon->capability);
+	network->last_scanned = jiffies;
+	network->time_stamp[0] = le32_to_cpu(beacon->time_stamp[0]);
+	network->time_stamp[1] = le32_to_cpu(beacon->time_stamp[1]);
+	network->beacon_interval = le32_to_cpu(beacon->beacon_interval);
+	/* Where to pull this? beacon->listen_interval;*/
+	network->listen_interval = 0x0A;
+	network->rates_len = network->rates_ex_len = 0;
+	network->last_associate = 0;
+	network->ssid_len = 0;
+	network->flags = 0;
+	network->atim_window = 0;
+	network->erp_value = (network->capability & WLAN_CAPABILITY_IBSS) ?
+            0x3 : 0x0;
+	network->berp_info_valid = false;
+        network->broadcom_cap_exist = false;
+	network->ralink_cap_exist = false;
+	network->atheros_cap_exist = false;
+	network->cisco_cap_exist = false;
+	network->unknown_cap_exist = false;
+	network->realtek_cap_exit = false;
+	network->marvell_cap_exist = false;
+#ifdef THOMAS_TURBO
+	network->Turbo_Enable = 0;
+#endif
+#ifdef ENABLE_DOT11D
+	network->CountryIeLen = 0;
+	memset(network->CountryIeBuf, 0, MAX_IE_LEN);
+#endif
+//Initialize HT parameters
+	//ieee80211_ht_initialize(&network->bssht);
+	HTInitializeBssDesc(&network->bssht);
+	if (stats->freq == IEEE80211_52GHZ_BAND) {
+		/* for A band (No DS info) */
+		network->channel = stats->received_channel;
+	} else
+		network->flags |= NETWORK_HAS_CCK;
+
+ 	network->wpa_ie_len = 0;
+ 	network->rsn_ie_len = 0;
+
+        if (ieee80211_parse_info_param
+            (ieee,beacon->info_element, stats->len - sizeof(*beacon), network, stats))
+                return 1;
+
+	network->mode = 0;
+	if (stats->freq == IEEE80211_52GHZ_BAND)
+		network->mode = IEEE_A;
+	else {
+		if (network->flags & NETWORK_HAS_OFDM)
+			network->mode |= IEEE_G;
+		if (network->flags & NETWORK_HAS_CCK)
+			network->mode |= IEEE_B;
+	}
+
+	if (network->mode == 0) {
+		IEEE80211_DEBUG_SCAN("Filtered out '%s (" MAC_FMT ")' "
+				     "network.\n",
+				     escape_essid(network->ssid,
+						  network->ssid_len),
+				     MAC_ARG(network->bssid));
+		return 1;
+	}
+
+	if(network->bssht.bdSupportHT){
+		if(network->mode == IEEE_A)
+			network->mode = IEEE_N_5G;
+		else if(network->mode & (IEEE_G | IEEE_B))
+			network->mode = IEEE_N_24G;
+	}
+	if (ieee80211_is_empty_essid(network->ssid, network->ssid_len))
+		network->flags |= NETWORK_EMPTY_ESSID;
+
+#if 1
+	stats->signal = 30 + (stats->SignalStrength * 70) / 100;
+	//stats->signal = ieee80211_SignalStrengthTranslate(stats->signal);
+	stats->noise = ieee80211_translate_todbm((u8)(100-stats->signal)) -25;
+#endif
+
+	memcpy(&network->stats, stats, sizeof(network->stats));
+
+	return 0;
+}
+
+static inline int is_same_network(struct ieee80211_network *src,
+				  struct ieee80211_network *dst, struct ieee80211_device* ieee)
+{
+	/* A network is only a duplicate if the channel, BSSID, ESSID
+	 * and the capability field (in particular IBSS and BSS) all match.
+	 * We treat all <hidden> with the same BSSID and channel
+	 * as one network */
+	return //((src->ssid_len == dst->ssid_len) &&
+		(((src->ssid_len == dst->ssid_len) || (ieee->iw_mode == IW_MODE_INFRA)) &&
+		(src->channel == dst->channel) &&
+		!memcmp(src->bssid, dst->bssid, ETH_ALEN) &&
+		//!memcmp(src->ssid, dst->ssid, src->ssid_len) &&
+		(!memcmp(src->ssid, dst->ssid, src->ssid_len) || (ieee->iw_mode == IW_MODE_INFRA)) &&
+		((src->capability & WLAN_CAPABILITY_IBSS) ==
+		(dst->capability & WLAN_CAPABILITY_IBSS)) &&
+		((src->capability & WLAN_CAPABILITY_BSS) ==
+		(dst->capability & WLAN_CAPABILITY_BSS)));
+}
+
+static inline void update_network(struct ieee80211_network *dst,
+				  struct ieee80211_network *src)
+{
+	int qos_active;
+	u8 old_param;
+
+	memcpy(&dst->stats, &src->stats, sizeof(struct ieee80211_rx_stats));
+	dst->capability = src->capability;
+	memcpy(dst->rates, src->rates, src->rates_len);
+	dst->rates_len = src->rates_len;
+	memcpy(dst->rates_ex, src->rates_ex, src->rates_ex_len);
+	dst->rates_ex_len = src->rates_ex_len;
+	if(src->ssid_len > 0)
+	{
+		memset(dst->ssid, 0, dst->ssid_len);
+		dst->ssid_len = src->ssid_len;
+		memcpy(dst->ssid, src->ssid, src->ssid_len);
+	}
+	dst->mode = src->mode;
+	dst->flags = src->flags;
+	dst->time_stamp[0] = src->time_stamp[0];
+	dst->time_stamp[1] = src->time_stamp[1];
+	if (src->flags & NETWORK_HAS_ERP_VALUE)
+	{
+		dst->erp_value = src->erp_value;
+		dst->berp_info_valid = src->berp_info_valid = true;
+	}
+	dst->beacon_interval = src->beacon_interval;
+	dst->listen_interval = src->listen_interval;
+	dst->atim_window = src->atim_window;
+	dst->dtim_period = src->dtim_period;
+	dst->dtim_data = src->dtim_data;
+	dst->last_dtim_sta_time[0] = src->last_dtim_sta_time[0];
+	dst->last_dtim_sta_time[1] = src->last_dtim_sta_time[1];
+	memcpy(&dst->tim, &src->tim, sizeof(struct ieee80211_tim_parameters));
+
+        dst->bssht.bdSupportHT = src->bssht.bdSupportHT;
+	dst->bssht.bdRT2RTAggregation = src->bssht.bdRT2RTAggregation;
+	dst->bssht.bdHTCapLen= src->bssht.bdHTCapLen;
+	memcpy(dst->bssht.bdHTCapBuf,src->bssht.bdHTCapBuf,src->bssht.bdHTCapLen);
+	dst->bssht.bdHTInfoLen= src->bssht.bdHTInfoLen;
+	memcpy(dst->bssht.bdHTInfoBuf,src->bssht.bdHTInfoBuf,src->bssht.bdHTInfoLen);
+	dst->bssht.bdHTSpecVer = src->bssht.bdHTSpecVer;
+	dst->bssht.bdRT2RTLongSlotTime = src->bssht.bdRT2RTLongSlotTime;
+	dst->broadcom_cap_exist = src->broadcom_cap_exist;
+	dst->ralink_cap_exist = src->ralink_cap_exist;
+	dst->atheros_cap_exist = src->atheros_cap_exist;
+	dst->realtek_cap_exit = src->realtek_cap_exit;
+	dst->marvell_cap_exist = src->marvell_cap_exist;
+	dst->cisco_cap_exist = src->cisco_cap_exist;
+	dst->unknown_cap_exist = src->unknown_cap_exist;
+	memcpy(dst->wpa_ie, src->wpa_ie, src->wpa_ie_len);
+	dst->wpa_ie_len = src->wpa_ie_len;
+	memcpy(dst->rsn_ie, src->rsn_ie, src->rsn_ie_len);
+	dst->rsn_ie_len = src->rsn_ie_len;
+
+	dst->last_scanned = jiffies;
+	/* qos related parameters */
+	//qos_active = src->qos_data.active;
+	qos_active = dst->qos_data.active;
+	//old_param = dst->qos_data.old_param_count;
+	old_param = dst->qos_data.param_count;
+	if(dst->flags & NETWORK_HAS_QOS_MASK){
+        //not update QOS paramter in beacon, as most AP will set all these parameter to 0.//WB
+	//	printk("====>%s(), aifs:%x, %x\n", __FUNCTION__, dst->qos_data.parameters.aifs[0], src->qos_data.parameters.aifs[0]);
+	//	memcpy(&dst->qos_data, &src->qos_data,
+	//		sizeof(struct ieee80211_qos_data));
+	}
+	else {
+		dst->qos_data.supported = src->qos_data.supported;
+		dst->qos_data.param_count = src->qos_data.param_count;
+	}
+
+	if(dst->qos_data.supported == 1) {
+		dst->QoS_Enable = 1;
+		if(dst->ssid_len)
+			IEEE80211_DEBUG_QOS
+				("QoS the network %s is QoS supported\n",
+				dst->ssid);
+		else
+			IEEE80211_DEBUG_QOS
+				("QoS the network is QoS supported\n");
+	}
+	dst->qos_data.active = qos_active;
+	dst->qos_data.old_param_count = old_param;
+
+	/* dst->last_associate is not overwritten */
+#if 1
+	dst->wmm_info = src->wmm_info; //sure to exist in beacon or probe response frame.
+	if(src->wmm_param[0].ac_aci_acm_aifsn|| \
+	   src->wmm_param[1].ac_aci_acm_aifsn|| \
+	   src->wmm_param[2].ac_aci_acm_aifsn|| \
+	   src->wmm_param[1].ac_aci_acm_aifsn) {
+	  memcpy(dst->wmm_param, src->wmm_param, WME_AC_PRAM_LEN);
+	}
+	//dst->QoS_Enable = src->QoS_Enable;
+#else
+	dst->QoS_Enable = 1;//for Rtl8187 simulation
+#endif
+#ifdef THOMAS_TURBO
+	dst->Turbo_Enable = src->Turbo_Enable;
+#endif
+
+#ifdef ENABLE_DOT11D
+	dst->CountryIeLen = src->CountryIeLen;
+	memcpy(dst->CountryIeBuf, src->CountryIeBuf, src->CountryIeLen);
+#endif
+
+	//added by amy for LEAP
+	dst->bWithAironetIE = src->bWithAironetIE;
+	dst->bCkipSupported = src->bCkipSupported;
+	memcpy(dst->CcxRmState,src->CcxRmState,2);
+	dst->bCcxRmEnable = src->bCcxRmEnable;
+	dst->MBssidMask = src->MBssidMask;
+	dst->bMBssidValid = src->bMBssidValid;
+	memcpy(dst->MBssid,src->MBssid,6);
+	dst->bWithCcxVerNum = src->bWithCcxVerNum;
+	dst->BssCcxVerNumber = src->BssCcxVerNumber;
+
+}
+
+static inline int is_beacon(__le16 fc)
+{
+	return (WLAN_FC_GET_STYPE(le16_to_cpu(fc)) == IEEE80211_STYPE_BEACON);
+}
+
+static inline void ieee80211_process_probe_response(
+	struct ieee80211_device *ieee,
+	struct ieee80211_probe_response *beacon,
+	struct ieee80211_rx_stats *stats)
+{
+	struct ieee80211_network network;
+	struct ieee80211_network *target;
+	struct ieee80211_network *oldest = NULL;
+#ifdef CONFIG_IEEE80211_DEBUG
+	struct ieee80211_info_element *info_element = &beacon->info_element[0];
+#endif
+	unsigned long flags;
+	short renew;
+	//u8 wmm_info;
+
+	memset(&network, 0, sizeof(struct ieee80211_network));
+	IEEE80211_DEBUG_SCAN(
+		"'%s' (" MAC_FMT "): %c%c%c%c %c%c%c%c-%c%c%c%c %c%c%c%c\n",
+		escape_essid(info_element->data, info_element->len),
+		MAC_ARG(beacon->header.addr3),
+		(beacon->capability & (1<<0xf)) ? '1' : '0',
+		(beacon->capability & (1<<0xe)) ? '1' : '0',
+		(beacon->capability & (1<<0xd)) ? '1' : '0',
+		(beacon->capability & (1<<0xc)) ? '1' : '0',
+		(beacon->capability & (1<<0xb)) ? '1' : '0',
+		(beacon->capability & (1<<0xa)) ? '1' : '0',
+		(beacon->capability & (1<<0x9)) ? '1' : '0',
+		(beacon->capability & (1<<0x8)) ? '1' : '0',
+		(beacon->capability & (1<<0x7)) ? '1' : '0',
+		(beacon->capability & (1<<0x6)) ? '1' : '0',
+		(beacon->capability & (1<<0x5)) ? '1' : '0',
+		(beacon->capability & (1<<0x4)) ? '1' : '0',
+		(beacon->capability & (1<<0x3)) ? '1' : '0',
+		(beacon->capability & (1<<0x2)) ? '1' : '0',
+		(beacon->capability & (1<<0x1)) ? '1' : '0',
+		(beacon->capability & (1<<0x0)) ? '1' : '0');
+
+	if (ieee80211_network_init(ieee, beacon, &network, stats)) {
+		IEEE80211_DEBUG_SCAN("Dropped '%s' (" MAC_FMT ") via %s.\n",
+				     escape_essid(info_element->data,
+						  info_element->len),
+				     MAC_ARG(beacon->header.addr3),
+				     WLAN_FC_GET_STYPE(beacon->header.frame_ctl) ==
+				     IEEE80211_STYPE_PROBE_RESP ?
+				     "PROBE RESPONSE" : "BEACON");
+		return;
+	}
+
+#ifdef ENABLE_DOT11D
+	// For Asus EeePc request,
+	// (1) if wireless adapter receive get any 802.11d country code in AP beacon,
+	//	   wireless adapter should follow the country code.
+	// (2)  If there is no any country code in beacon,
+	//       then wireless adapter should do active scan from ch1~11 and
+	//       passive scan from ch12~14
+
+	if( !IsLegalChannel(ieee, network.channel) )
+		return;
+	if(ieee->bGlobalDomain)
+	{
+		if (WLAN_FC_GET_STYPE(beacon->header.frame_ctl) == IEEE80211_STYPE_PROBE_RESP)
+		{
+			// Case 1: Country code
+			if(IS_COUNTRY_IE_VALID(ieee) )
+			{
+				if( !IsLegalChannel(ieee, network.channel) )
+				{
+					printk("GetScanInfo(): For Country code, filter probe response at channel(%d).\n", network.channel);
+					return;
+				}
+			}
+			// Case 2: No any country code.
+			else
+			{
+				// Filter over channel ch12~14
+				if(network.channel > 11)
+				{
+					printk("GetScanInfo(): For Global Domain, filter probe response at channel(%d).\n", network.channel);
+					return;
+				}
+			}
+		}
+		else
+		{
+			// Case 1: Country code
+			if(IS_COUNTRY_IE_VALID(ieee) )
+			{
+				if( !IsLegalChannel(ieee, network.channel) )
+				{
+					printk("GetScanInfo(): For Country code, filter beacon at channel(%d).\n",network.channel);
+					return;
+				}
+			}
+			// Case 2: No any country code.
+			else
+			{
+				// Filter over channel ch12~14
+				if(network.channel > 14)
+				{
+					printk("GetScanInfo(): For Global Domain, filter beacon at channel(%d).\n",network.channel);
+					return;
+				}
+			}
+		}
+	}
+#endif
+
+	/* The network parsed correctly -- so now we scan our known networks
+	 * to see if we can find it in our list.
+	 *
+	 * NOTE:  This search is definitely not optimized.  Once its doing
+	 *        the "right thing" we'll optimize it for efficiency if
+	 *        necessary */
+
+	/* Search for this entry in the list and update it if it is
+	 * already there. */
+
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	if(is_same_network(&ieee->current_network, &network, ieee)) {
+		update_network(&ieee->current_network, &network);
+		if((ieee->current_network.mode == IEEE_N_24G || ieee->current_network.mode == IEEE_G)
+		&& ieee->current_network.berp_info_valid){
+		if(ieee->current_network.erp_value& ERP_UseProtection)
+			ieee->current_network.buseprotection = true;
+		else
+			ieee->current_network.buseprotection = false;
+		}
+		if(is_beacon(beacon->header.frame_ctl))
+		{
+			if(ieee->state == IEEE80211_LINKED)
+				ieee->LinkDetectInfo.NumRecvBcnInPeriod++;
+		}
+		else //hidden AP
+			network.flags = (~NETWORK_EMPTY_ESSID & network.flags)|(NETWORK_EMPTY_ESSID & ieee->current_network.flags);
+	}
+
+	list_for_each_entry(target, &ieee->network_list, list) {
+		if (is_same_network(target, &network, ieee))
+			break;
+		if ((oldest == NULL) ||
+		    (target->last_scanned < oldest->last_scanned))
+			oldest = target;
+	}
+
+	/* If we didn't find a match, then get a new network slot to initialize
+	 * with this beacon's information */
+	if (&target->list == &ieee->network_list) {
+		if (list_empty(&ieee->network_free_list)) {
+			/* If there are no more slots, expire the oldest */
+			list_del(&oldest->list);
+			target = oldest;
+			IEEE80211_DEBUG_SCAN("Expired '%s' (" MAC_FMT ") from "
+					     "network list.\n",
+					     escape_essid(target->ssid,
+							  target->ssid_len),
+					     MAC_ARG(target->bssid));
+		} else {
+			/* Otherwise just pull from the free list */
+			target = list_entry(ieee->network_free_list.next,
+					    struct ieee80211_network, list);
+			list_del(ieee->network_free_list.next);
+		}
+
+
+#ifdef CONFIG_IEEE80211_DEBUG
+		IEEE80211_DEBUG_SCAN("Adding '%s' (" MAC_FMT ") via %s.\n",
+				     escape_essid(network.ssid,
+						  network.ssid_len),
+				     MAC_ARG(network.bssid),
+				     WLAN_FC_GET_STYPE(beacon->header.frame_ctl) ==
+				     IEEE80211_STYPE_PROBE_RESP ?
+				     "PROBE RESPONSE" : "BEACON");
+#endif
+		memcpy(target, &network, sizeof(*target));
+		list_add_tail(&target->list, &ieee->network_list);
+		if(ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE)
+			ieee80211_softmac_new_net(ieee,&network);
+	} else {
+		IEEE80211_DEBUG_SCAN("Updating '%s' (" MAC_FMT ") via %s.\n",
+				     escape_essid(target->ssid,
+						  target->ssid_len),
+				     MAC_ARG(target->bssid),
+				     WLAN_FC_GET_STYPE(beacon->header.frame_ctl) ==
+				     IEEE80211_STYPE_PROBE_RESP ?
+				     "PROBE RESPONSE" : "BEACON");
+
+		/* we have an entry and we are going to update it. But this entry may
+		 * be already expired. In this case we do the same as we found a new
+		 * net and call the new_net handler
+		 */
+		renew = !time_after(target->last_scanned + ieee->scan_age, jiffies);
+		//YJ,add,080819,for hidden ap
+		if(is_beacon(beacon->header.frame_ctl) == 0)
+			network.flags = (~NETWORK_EMPTY_ESSID & network.flags)|(NETWORK_EMPTY_ESSID & target->flags);
+		//if(strncmp(network.ssid, "linksys-c",9) == 0)
+		//	printk("====>2 network.ssid=%s FLAG=%d target.ssid=%s FLAG=%d\n", network.ssid, network.flags, target->ssid, target->flags);
+		if(((network.flags & NETWORK_EMPTY_ESSID) == NETWORK_EMPTY_ESSID) \
+		    && (((network.ssid_len > 0) && (strncmp(target->ssid, network.ssid, network.ssid_len)))\
+		    ||((ieee->current_network.ssid_len == network.ssid_len)&&(strncmp(ieee->current_network.ssid, network.ssid, network.ssid_len) == 0)&&(ieee->state == IEEE80211_NOLINK))))
+			renew = 1;
+		//YJ,add,080819,for hidden ap,end
+
+		update_network(target, &network);
+		if(renew && (ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE))
+			ieee80211_softmac_new_net(ieee,&network);
+	}
+
+	spin_unlock_irqrestore(&ieee->lock, flags);
+	if (is_beacon(beacon->header.frame_ctl)&&is_same_network(&ieee->current_network, &network, ieee)&&\
+		(ieee->state == IEEE80211_LINKED)) {
+		if(ieee->handle_beacon != NULL) {
+			ieee->handle_beacon(ieee->dev,beacon,&ieee->current_network);
+		}
+	}
+}
+
+void ieee80211_rx_mgt(struct ieee80211_device *ieee,
+		      struct ieee80211_hdr_4addr *header,
+		      struct ieee80211_rx_stats *stats)
+{
+	if(ieee->sta_sleep || (ieee->ps != IEEE80211_PS_DISABLED &&
+				ieee->iw_mode == IW_MODE_INFRA &&
+				ieee->state == IEEE80211_LINKED))
+	{
+		tasklet_schedule(&ieee->ps_task);
+	}
+
+	if(WLAN_FC_GET_STYPE(header->frame_ctl) != IEEE80211_STYPE_PROBE_RESP &&
+		WLAN_FC_GET_STYPE(header->frame_ctl) != IEEE80211_STYPE_BEACON)
+		ieee->last_rx_ps_time = jiffies;
+
+	switch (WLAN_FC_GET_STYPE(header->frame_ctl)) {
+
+	case IEEE80211_STYPE_BEACON:
+		IEEE80211_DEBUG_MGMT("received BEACON (%d)\n",
+				     WLAN_FC_GET_STYPE(header->frame_ctl));
+		IEEE80211_DEBUG_SCAN("Beacon\n");
+		ieee80211_process_probe_response(
+			ieee, (struct ieee80211_probe_response *)header, stats);
+		break;
+
+	case IEEE80211_STYPE_PROBE_RESP:
+		IEEE80211_DEBUG_MGMT("received PROBE RESPONSE (%d)\n",
+				     WLAN_FC_GET_STYPE(header->frame_ctl));
+		IEEE80211_DEBUG_SCAN("Probe response\n");
+		ieee80211_process_probe_response(
+			ieee, (struct ieee80211_probe_response *)header, stats);
+		break;
+
+	}
+}
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+EXPORT_SYMBOL(ieee80211_rx_mgt);
+EXPORT_SYMBOL(ieee80211_rx);
+#else
+EXPORT_SYMBOL_NOVERS(ieee80211_rx_mgt);
+EXPORT_SYMBOL_NOVERS(ieee80211_rx);
+#endif
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211_softmac.c b/drivers/staging/rtl8192su/ieee80211/ieee80211_softmac.c
new file mode 100644
index 0000000..6773e84
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211_softmac.c
@@ -0,0 +1,3580 @@
+/* IEEE 802.11 SoftMAC layer
+ * Copyright (c) 2005 Andrea Merello <andreamrl@tiscali.it>
+ *
+ * Mostly extracted from the rtl8180-sa2400 driver for the
+ * in-kernel generic ieee802.11 stack.
+ *
+ * Few lines might be stolen from other part of the ieee80211
+ * stack. Copyright who own it's copyright
+ *
+ * WPA code stolen from the ipw2200 driver.
+ * Copyright who own it's copyright.
+ *
+ * released under the GPL
+ */
+
+
+#include "ieee80211.h"
+
+#include <linux/random.h>
+#include <linux/delay.h>
+#include <linux/version.h>
+#include <asm/uaccess.h>
+#ifdef ENABLE_DOT11D
+#include "dot11d.h"
+#endif
+
+u8 rsn_authen_cipher_suite[16][4] = {
+	{0x00,0x0F,0xAC,0x00}, //Use group key, //Reserved
+	{0x00,0x0F,0xAC,0x01}, //WEP-40         //RSNA default
+	{0x00,0x0F,0xAC,0x02}, //TKIP           //NONE		//{used just as default}
+	{0x00,0x0F,0xAC,0x03}, //WRAP-historical
+	{0x00,0x0F,0xAC,0x04}, //CCMP
+	{0x00,0x0F,0xAC,0x05}, //WEP-104
+};
+
+short ieee80211_is_54g(struct ieee80211_network net)
+{
+	return ((net.rates_ex_len > 0) || (net.rates_len > 4));
+}
+
+short ieee80211_is_shortslot(struct ieee80211_network net)
+{
+	return (net.capability & WLAN_CAPABILITY_SHORT_SLOT);
+}
+
+/* returns the total length needed for pleacing the RATE MFIE
+ * tag and the EXTENDED RATE MFIE tag if needed.
+ * It encludes two bytes per tag for the tag itself and its len
+ */
+unsigned int ieee80211_MFIE_rate_len(struct ieee80211_device *ieee)
+{
+	unsigned int rate_len = 0;
+
+	if (ieee->modulation & IEEE80211_CCK_MODULATION)
+		rate_len = IEEE80211_CCK_RATE_LEN + 2;
+
+	if (ieee->modulation & IEEE80211_OFDM_MODULATION)
+
+		rate_len += IEEE80211_OFDM_RATE_LEN + 2;
+
+	return rate_len;
+}
+
+/* pleace the MFIE rate, tag to the memory (double) poined.
+ * Then it updates the pointer so that
+ * it points after the new MFIE tag added.
+ */
+void ieee80211_MFIE_Brate(struct ieee80211_device *ieee, u8 **tag_p)
+{
+	u8 *tag = *tag_p;
+
+	if (ieee->modulation & IEEE80211_CCK_MODULATION){
+		*tag++ = MFIE_TYPE_RATES;
+		*tag++ = 4;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_1MB;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_2MB;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_5MB;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_11MB;
+	}
+
+	/* We may add an option for custom rates that specific HW might support */
+	*tag_p = tag;
+}
+
+void ieee80211_MFIE_Grate(struct ieee80211_device *ieee, u8 **tag_p)
+{
+	u8 *tag = *tag_p;
+
+		if (ieee->modulation & IEEE80211_OFDM_MODULATION){
+
+		*tag++ = MFIE_TYPE_RATES_EX;
+		*tag++ = 8;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_6MB;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_9MB;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_12MB;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_18MB;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_24MB;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_36MB;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_48MB;
+		*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_54MB;
+
+	}
+
+	/* We may add an option for custom rates that specific HW might support */
+	*tag_p = tag;
+}
+
+
+void ieee80211_WMM_Info(struct ieee80211_device *ieee, u8 **tag_p) {
+	u8 *tag = *tag_p;
+
+	*tag++ = MFIE_TYPE_GENERIC; //0
+	*tag++ = 7;
+	*tag++ = 0x00;
+	*tag++ = 0x50;
+	*tag++ = 0xf2;
+	*tag++ = 0x02;//5
+	*tag++ = 0x00;
+	*tag++ = 0x01;
+#ifdef SUPPORT_USPD
+	if(ieee->current_network.wmm_info & 0x80) {
+		*tag++ = 0x0f|MAX_SP_Len;
+	} else {
+		*tag++ = MAX_SP_Len;
+	}
+#else
+	*tag++ = MAX_SP_Len;
+#endif
+	*tag_p = tag;
+}
+
+#ifdef THOMAS_TURBO
+void ieee80211_TURBO_Info(struct ieee80211_device *ieee, u8 **tag_p) {
+	u8 *tag = *tag_p;
+
+        *tag++ = MFIE_TYPE_GENERIC; //0
+        *tag++ = 7;
+        *tag++ = 0x00;
+        *tag++ = 0xe0;
+        *tag++ = 0x4c;
+        *tag++ = 0x01;//5
+        *tag++ = 0x02;
+        *tag++ = 0x11;
+	*tag++ = 0x00;
+
+	*tag_p = tag;
+	printk(KERN_ALERT "This is enable turbo mode IE process\n");
+}
+#endif
+
+void enqueue_mgmt(struct ieee80211_device *ieee, struct sk_buff *skb)
+{
+	int nh;
+	nh = (ieee->mgmt_queue_head +1) % MGMT_QUEUE_NUM;
+
+/*
+ * if the queue is full but we have newer frames then
+ * just overwrites the oldest.
+ *
+ * if (nh == ieee->mgmt_queue_tail)
+ *		return -1;
+ */
+	ieee->mgmt_queue_head = nh;
+	ieee->mgmt_queue_ring[nh] = skb;
+
+	//return 0;
+}
+
+struct sk_buff *dequeue_mgmt(struct ieee80211_device *ieee)
+{
+	struct sk_buff *ret;
+
+	if(ieee->mgmt_queue_tail == ieee->mgmt_queue_head)
+		return NULL;
+
+	ret = ieee->mgmt_queue_ring[ieee->mgmt_queue_tail];
+
+	ieee->mgmt_queue_tail =
+		(ieee->mgmt_queue_tail+1) % MGMT_QUEUE_NUM;
+
+	return ret;
+}
+
+void init_mgmt_queue(struct ieee80211_device *ieee)
+{
+	ieee->mgmt_queue_tail = ieee->mgmt_queue_head = 0;
+}
+
+u8 MgntQuery_MgntFrameTxRate(struct ieee80211_device *ieee)
+{
+	PRT_HIGH_THROUGHPUT      pHTInfo = ieee->pHTInfo;
+	u8 rate;
+
+	// 2008/01/25 MH For broadcom, MGNT frame set as OFDM 6M.
+	if(pHTInfo->IOTAction & HT_IOT_ACT_MGNT_USE_CCK_6M)
+		rate = 0x0c;
+	else
+		rate = ieee->basic_rate & 0x7f;
+
+	if(rate == 0){
+		// 2005.01.26, by rcnjko.
+		if(ieee->mode == IEEE_A||
+		   ieee->mode== IEEE_N_5G||
+		   (ieee->mode== IEEE_N_24G&&!pHTInfo->bCurSuppCCK))
+			rate = 0x0c;
+		else
+			rate = 0x02;
+	}
+
+	/*
+	// Data rate of ProbeReq is already decided. Annie, 2005-03-31
+	if( pMgntInfo->bScanInProgress || (pMgntInfo->bDualModeScanStep!=0) )
+	{
+	if(pMgntInfo->dot11CurrentWirelessMode==WIRELESS_MODE_A)
+	rate = 0x0c;
+	else
+	rate = 0x02;
+	}
+	 */
+	return rate;
+}
+
+
+void ieee80211_sta_wakeup(struct ieee80211_device *ieee, short nl);
+
+inline void softmac_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee)
+{
+	unsigned long flags;
+	short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
+	struct ieee80211_hdr_3addr  *header=
+		(struct ieee80211_hdr_3addr  *) skb->data;
+
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + 8);
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	/* called with 2nd param 0, no mgmt lock required */
+	ieee80211_sta_wakeup(ieee,0);
+
+	tcb_desc->queue_index = MGNT_QUEUE;
+	tcb_desc->data_rate = MgntQuery_MgntFrameTxRate(ieee);
+        tcb_desc->RATRIndex = 7;
+        tcb_desc->bTxDisableRateFallBack = 1;
+        tcb_desc->bTxUseDriverAssingedRate = 1;
+
+	if(single){
+		if(ieee->queue_stop){
+			enqueue_mgmt(ieee,skb);
+		}else{
+			header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0]<<4);
+
+			if (ieee->seq_ctrl[0] == 0xFFF)
+				ieee->seq_ctrl[0] = 0;
+			else
+				ieee->seq_ctrl[0]++;
+
+			/* avoid watchdog triggers */
+	//		ieee->dev->trans_start = jiffies;
+			ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
+			//dev_kfree_skb_any(skb);//edit by thomas
+		}
+
+		spin_unlock_irqrestore(&ieee->lock, flags);
+	}else{
+		spin_unlock_irqrestore(&ieee->lock, flags);
+		spin_lock_irqsave(&ieee->mgmt_tx_lock, flags);
+
+		header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
+
+		if (ieee->seq_ctrl[0] == 0xFFF)
+			ieee->seq_ctrl[0] = 0;
+		else
+			ieee->seq_ctrl[0]++;
+
+		/* check wether the managed packet queued greater than 5 */
+		if(!ieee->check_nic_enough_desc(ieee->dev,tcb_desc->queue_index)||\
+				(skb_queue_len(&ieee->skb_waitQ[tcb_desc->queue_index]) != 0)||\
+				(ieee->queue_stop) ) {
+			/* insert the skb packet to the management queue */
+			/* as for the completion function, it does not need
+			 * to check it any more.
+			 * */
+			printk("%s():insert to waitqueue!\n",__FUNCTION__);
+			skb_queue_tail(&ieee->skb_waitQ[tcb_desc->queue_index], skb);
+		} else {
+			//printk("TX packet!\n");
+			ieee->softmac_hard_start_xmit(skb,ieee->dev);
+			//dev_kfree_skb_any(skb);//edit by thomas
+		}
+		spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags);
+	}
+}
+
+inline void softmac_ps_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee)
+{
+
+	short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
+	struct ieee80211_hdr_3addr  *header =
+		(struct ieee80211_hdr_3addr  *) skb->data;
+        cb_desc *tcb_desc = (cb_desc *)(skb->cb + 8);
+
+	tcb_desc->queue_index = MGNT_QUEUE;
+	tcb_desc->data_rate = MgntQuery_MgntFrameTxRate(ieee);
+	tcb_desc->RATRIndex = 7;
+	tcb_desc->bTxDisableRateFallBack = 1;
+	tcb_desc->bTxUseDriverAssingedRate = 1;
+	//printk("=============>%s()\n", __FUNCTION__);
+	if(single){
+
+		header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
+
+		if (ieee->seq_ctrl[0] == 0xFFF)
+			ieee->seq_ctrl[0] = 0;
+		else
+			ieee->seq_ctrl[0]++;
+
+		/* avoid watchdog triggers */
+	//	ieee->dev->trans_start = jiffies;
+		ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
+
+	}else{
+
+		header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
+
+		if (ieee->seq_ctrl[0] == 0xFFF)
+			ieee->seq_ctrl[0] = 0;
+		else
+			ieee->seq_ctrl[0]++;
+
+		ieee->softmac_hard_start_xmit(skb,ieee->dev);
+
+	}
+	//dev_kfree_skb_any(skb);//edit by thomas
+}
+
+inline struct sk_buff *ieee80211_probe_req(struct ieee80211_device *ieee)
+{
+	unsigned int len,rate_len;
+	u8 *tag;
+	struct sk_buff *skb;
+	struct ieee80211_probe_request *req;
+
+	len = ieee->current_network.ssid_len;
+
+	rate_len = ieee80211_MFIE_rate_len(ieee);
+
+	skb = dev_alloc_skb(sizeof(struct ieee80211_probe_request) +
+			    2 + len + rate_len + ieee->tx_headroom);
+	if (!skb)
+		return NULL;
+
+	skb_reserve(skb, ieee->tx_headroom);
+
+	req = (struct ieee80211_probe_request *) skb_put(skb,sizeof(struct ieee80211_probe_request));
+	req->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_PROBE_REQ);
+	req->header.duration_id = 0; //FIXME: is this OK ?
+
+	memset(req->header.addr1, 0xff, ETH_ALEN);
+	memcpy(req->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
+	memset(req->header.addr3, 0xff, ETH_ALEN);
+
+	tag = (u8 *) skb_put(skb,len+2+rate_len);
+
+	*tag++ = MFIE_TYPE_SSID;
+	*tag++ = len;
+	memcpy(tag, ieee->current_network.ssid, len);
+	tag += len;
+
+	ieee80211_MFIE_Brate(ieee,&tag);
+	ieee80211_MFIE_Grate(ieee,&tag);
+	return skb;
+}
+
+struct sk_buff *ieee80211_get_beacon_(struct ieee80211_device *ieee);
+void ieee80211_send_beacon(struct ieee80211_device *ieee)
+{
+	struct sk_buff *skb;
+	if(!ieee->ieee_up)
+		return;
+	//unsigned long flags;
+	skb = ieee80211_get_beacon_(ieee);
+
+	if (skb){
+		softmac_mgmt_xmit(skb, ieee);
+		ieee->softmac_stats.tx_beacons++;
+		//dev_kfree_skb_any(skb);//edit by thomas
+	}
+//	ieee->beacon_timer.expires = jiffies +
+//		(MSECS( ieee->current_network.beacon_interval -5));
+
+	//spin_lock_irqsave(&ieee->beacon_lock,flags);
+	if(ieee->beacon_txing && ieee->ieee_up){
+//		if(!timer_pending(&ieee->beacon_timer))
+//			add_timer(&ieee->beacon_timer);
+		mod_timer(&ieee->beacon_timer,jiffies+(MSECS(ieee->current_network.beacon_interval-5)));
+	}
+	//spin_unlock_irqrestore(&ieee->beacon_lock,flags);
+}
+
+
+void ieee80211_send_beacon_cb(unsigned long _ieee)
+{
+	struct ieee80211_device *ieee =
+		(struct ieee80211_device *) _ieee;
+	unsigned long flags;
+
+	spin_lock_irqsave(&ieee->beacon_lock, flags);
+	ieee80211_send_beacon(ieee);
+	spin_unlock_irqrestore(&ieee->beacon_lock, flags);
+}
+
+
+void ieee80211_send_probe(struct ieee80211_device *ieee)
+{
+	struct sk_buff *skb;
+
+	skb = ieee80211_probe_req(ieee);
+	if (skb){
+		softmac_mgmt_xmit(skb, ieee);
+		ieee->softmac_stats.tx_probe_rq++;
+		//dev_kfree_skb_any(skb);//edit by thomas
+	}
+}
+
+void ieee80211_send_probe_requests(struct ieee80211_device *ieee)
+{
+	if (ieee->active_scan && (ieee->softmac_features & IEEE_SOFTMAC_PROBERQ)){
+		ieee80211_send_probe(ieee);
+		ieee80211_send_probe(ieee);
+	}
+}
+
+/* this performs syncro scan blocking the caller until all channels
+ * in the allowed channel map has been checked.
+ */
+void ieee80211_softmac_scan_syncro(struct ieee80211_device *ieee)
+{
+	short ch = 0;
+#ifdef ENABLE_DOT11D
+	u8 channel_map[MAX_CHANNEL_NUMBER+1];
+	memcpy(channel_map, GET_DOT11D_INFO(ieee)->channel_map, MAX_CHANNEL_NUMBER+1);
+#endif
+	ieee->be_scan_inprogress = true;
+	down(&ieee->scan_sem);
+
+	while(1)
+	{
+
+		do{
+			ch++;
+			if (ch > MAX_CHANNEL_NUMBER)
+				goto out; /* scan completed */
+#ifdef ENABLE_DOT11D
+		}while(!channel_map[ch]);
+#else
+		}while(!ieee->channel_map[ch]);
+#endif
+
+		/* this fuction can be called in two situations
+		 * 1- We have switched to ad-hoc mode and we are
+		 *    performing a complete syncro scan before conclude
+		 *    there are no interesting cell and to create a
+		 *    new one. In this case the link state is
+		 *    IEEE80211_NOLINK until we found an interesting cell.
+		 *    If so the ieee8021_new_net, called by the RX path
+		 *    will set the state to IEEE80211_LINKED, so we stop
+		 *    scanning
+		 * 2- We are linked and the root uses run iwlist scan.
+		 *    So we switch to IEEE80211_LINKED_SCANNING to remember
+		 *    that we are still logically linked (not interested in
+		 *    new network events, despite for updating the net list,
+		 *    but we are temporarly 'unlinked' as the driver shall
+		 *    not filter RX frames and the channel is changing.
+		 * So the only situation in witch are interested is to check
+		 * if the state become LINKED because of the #1 situation
+		 */
+
+		if (ieee->state == IEEE80211_LINKED)
+			goto out;
+		ieee->set_chan(ieee->dev, ch);
+#ifdef ENABLE_DOT11D
+		if(channel_map[ch] == 1)
+#endif
+		ieee80211_send_probe_requests(ieee);
+
+		/* this prevent excessive time wait when we
+		 * need to wait for a syncro scan to end..
+		 */
+		if(ieee->state < IEEE80211_LINKED)
+			;
+		else
+		if (ieee->sync_scan_hurryup)
+			goto out;
+
+
+		msleep_interruptible_rsl(IEEE80211_SOFTMAC_SCAN_TIME);
+
+	}
+out:
+	if(ieee->state < IEEE80211_LINKED){
+		ieee->actscanning = false;
+		up(&ieee->scan_sem);
+		ieee->be_scan_inprogress = false;
+	}
+	else{
+	ieee->sync_scan_hurryup = 0;
+#ifdef ENABLE_DOT11D
+	if(IS_DOT11D_ENABLE(ieee))
+		DOT11D_ScanComplete(ieee);
+#endif
+	up(&ieee->scan_sem);
+	ieee->be_scan_inprogress = false;
+}
+}
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+/* called both by wq with ieee->lock held */
+void ieee80211_softmac_scan(struct ieee80211_device *ieee)
+{
+#if 0
+	short watchdog = 0;
+	do{
+		ieee->current_network.channel =
+			(ieee->current_network.channel + 1) % MAX_CHANNEL_NUMBER;
+		if (watchdog++ > MAX_CHANNEL_NUMBER)
+				return; /* no good chans */
+
+	}while(!ieee->channel_map[ieee->current_network.channel]);
+#endif
+
+	schedule_task(&ieee->softmac_scan_wq);
+}
+#endif
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+void ieee80211_softmac_scan_wq(struct work_struct *work)
+{
+        struct delayed_work *dwork = container_of(work, struct delayed_work, work);
+        struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, softmac_scan_wq);
+#else
+void ieee80211_softmac_scan_wq(struct ieee80211_device *ieee)
+{
+#endif
+	u8 last_channel = ieee->current_network.channel; //recored init channel inorder not change current channel when comming out the scan unexpectedly. WB.
+#ifdef ENABLE_DOT11D
+	u8 channel_map[MAX_CHANNEL_NUMBER+1];
+	memcpy(channel_map, GET_DOT11D_INFO(ieee)->channel_map, MAX_CHANNEL_NUMBER+1);
+#endif
+	if(!ieee->ieee_up)
+		return;
+	down(&ieee->scan_sem);
+	do{
+		ieee->current_network.channel =
+			(ieee->current_network.channel + 1) % MAX_CHANNEL_NUMBER;
+		if (ieee->scan_watch_dog++ > MAX_CHANNEL_NUMBER)
+		{
+		//if current channel is not in channel map, set to default channel.
+		#ifdef ENABLE_DOT11D
+      			if (!channel_map[ieee->current_network.channel]);
+		#else
+			if (!ieee->channel_map[ieee->current_network.channel]);
+		#endif
+				ieee->current_network.channel = 6;
+				goto out; /* no good chans */
+		}
+#ifdef ENABLE_DOT11D
+        }while(!channel_map[ieee->current_network.channel]);
+#else
+	}while(!ieee->channel_map[ieee->current_network.channel]);
+#endif
+	if (ieee->scanning == 0 )
+		goto out;
+	ieee->set_chan(ieee->dev, ieee->current_network.channel);
+#ifdef ENABLE_DOT11D
+	if(channel_map[ieee->current_network.channel] == 1)
+#endif
+	ieee80211_send_probe_requests(ieee);
+
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	queue_delayed_work(ieee->wq, &ieee->softmac_scan_wq, IEEE80211_SOFTMAC_SCAN_TIME);
+#else
+	//ieee->scan_timer.expires = jiffies + MSECS(IEEE80211_SOFTMAC_SCAN_TIME);
+	if (ieee->scanning == 1)
+		mod_timer(&ieee->scan_timer,(jiffies + MSECS(IEEE80211_SOFTMAC_SCAN_TIME)));
+#endif
+
+	up(&ieee->scan_sem);
+	return;
+out:
+#ifdef ENABLE_DOT11D
+	if(IS_DOT11D_ENABLE(ieee))
+		DOT11D_ScanComplete(ieee);
+#endif
+	ieee->current_network.channel = last_channel;
+        ieee->actscanning = false;
+	ieee->scan_watch_dog = 0;
+	ieee->scanning = 0;
+	up(&ieee->scan_sem);
+}
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+void ieee80211_softmac_scan_cb(unsigned long _dev)
+{
+	unsigned long flags;
+	struct ieee80211_device *ieee = (struct ieee80211_device *)_dev;
+
+	spin_lock_irqsave(&ieee->lock, flags);
+	ieee80211_softmac_scan(ieee);
+	spin_unlock_irqrestore(&ieee->lock, flags);
+}
+#endif
+
+
+void ieee80211_beacons_start(struct ieee80211_device *ieee)
+{
+	unsigned long flags;
+	spin_lock_irqsave(&ieee->beacon_lock,flags);
+
+	ieee->beacon_txing = 1;
+	ieee80211_send_beacon(ieee);
+
+	spin_unlock_irqrestore(&ieee->beacon_lock,flags);
+}
+
+void ieee80211_beacons_stop(struct ieee80211_device *ieee)
+{
+	unsigned long flags;
+
+	spin_lock_irqsave(&ieee->beacon_lock,flags);
+
+	ieee->beacon_txing = 0;
+ 	del_timer_sync(&ieee->beacon_timer);
+
+	spin_unlock_irqrestore(&ieee->beacon_lock,flags);
+
+}
+
+
+void ieee80211_stop_send_beacons(struct ieee80211_device *ieee)
+{
+	if(ieee->stop_send_beacons)
+		ieee->stop_send_beacons(ieee->dev);
+	if (ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
+		ieee80211_beacons_stop(ieee);
+}
+
+
+void ieee80211_start_send_beacons(struct ieee80211_device *ieee)
+{
+	if(ieee->start_send_beacons)
+		ieee->start_send_beacons(ieee->dev);
+	if(ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
+		ieee80211_beacons_start(ieee);
+}
+
+
+void ieee80211_softmac_stop_scan(struct ieee80211_device *ieee)
+{
+//	unsigned long flags;
+
+	//ieee->sync_scan_hurryup = 1;
+
+	down(&ieee->scan_sem);
+//	spin_lock_irqsave(&ieee->lock, flags);
+	ieee->scan_watch_dog = 0;
+	if (ieee->scanning == 1){
+		ieee->scanning = 0;
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+		cancel_delayed_work(&ieee->softmac_scan_wq);
+#else
+		del_timer_sync(&ieee->scan_timer);
+#endif
+	}
+
+//	spin_unlock_irqrestore(&ieee->lock, flags);
+	up(&ieee->scan_sem);
+}
+
+void ieee80211_stop_scan(struct ieee80211_device *ieee)
+{
+	if (ieee->softmac_features & IEEE_SOFTMAC_SCAN)
+		ieee80211_softmac_stop_scan(ieee);
+	else
+		ieee->stop_scan(ieee->dev);
+}
+
+/* called with ieee->lock held */
+void ieee80211_start_scan(struct ieee80211_device *ieee)
+{
+#ifdef ENABLE_DOT11D
+	if(IS_DOT11D_ENABLE(ieee) )
+	{
+		if(IS_COUNTRY_IE_VALID(ieee))
+		{
+			RESET_CIE_WATCHDOG(ieee);
+		}
+	}
+#endif
+	if (ieee->softmac_features & IEEE_SOFTMAC_SCAN){
+		if (ieee->scanning == 0){
+			ieee->scanning = 1;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+			queue_delayed_work(ieee->wq, &ieee->softmac_scan_wq, 0);
+#else
+
+			queue_work(ieee->wq, &ieee->softmac_scan_wq);
+#endif
+#else
+			ieee80211_softmac_scan(ieee);
+#endif
+		}
+	}else
+		ieee->start_scan(ieee->dev);
+
+}
+
+/* called with wx_sem held */
+void ieee80211_start_scan_syncro(struct ieee80211_device *ieee)
+{
+#ifdef ENABLE_DOT11D
+	if(IS_DOT11D_ENABLE(ieee) )
+	{
+		if(IS_COUNTRY_IE_VALID(ieee))
+		{
+			RESET_CIE_WATCHDOG(ieee);
+		}
+	}
+#endif
+	ieee->sync_scan_hurryup = 0;
+	if (ieee->softmac_features & IEEE_SOFTMAC_SCAN)
+		ieee80211_softmac_scan_syncro(ieee);
+	else
+		ieee->scan_syncro(ieee->dev);
+
+}
+
+inline struct sk_buff *ieee80211_authentication_req(struct ieee80211_network *beacon,
+	struct ieee80211_device *ieee, int challengelen)
+{
+	struct sk_buff *skb;
+	struct ieee80211_authentication *auth;
+	int len = sizeof(struct ieee80211_authentication) + challengelen + ieee->tx_headroom;
+
+
+	skb = dev_alloc_skb(len);
+	if (!skb) return NULL;
+
+	skb_reserve(skb, ieee->tx_headroom);
+	auth = (struct ieee80211_authentication *)
+		skb_put(skb, sizeof(struct ieee80211_authentication));
+
+	auth->header.frame_ctl = IEEE80211_STYPE_AUTH;
+	if (challengelen) auth->header.frame_ctl |= IEEE80211_FCTL_WEP;
+
+	auth->header.duration_id = 0x013a; //FIXME
+
+	memcpy(auth->header.addr1, beacon->bssid, ETH_ALEN);
+	memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
+	memcpy(auth->header.addr3, beacon->bssid, ETH_ALEN);
+
+	//auth->algorithm = ieee->open_wep ? WLAN_AUTH_OPEN : WLAN_AUTH_SHARED_KEY;
+	if(ieee->auth_mode == 0)
+		auth->algorithm = WLAN_AUTH_OPEN;
+	else if(ieee->auth_mode == 1)
+		auth->algorithm = WLAN_AUTH_SHARED_KEY;
+	else if(ieee->auth_mode == 2)
+		auth->algorithm = WLAN_AUTH_OPEN;//0x80;
+	printk("=================>%s():auth->algorithm is %d\n",__FUNCTION__,auth->algorithm);
+	auth->transaction = cpu_to_le16(ieee->associate_seq);
+	ieee->associate_seq++;
+
+	auth->status = cpu_to_le16(WLAN_STATUS_SUCCESS);
+
+	return skb;
+
+}
+
+
+static struct sk_buff* ieee80211_probe_resp(struct ieee80211_device *ieee, u8 *dest)
+{
+	u8 *tag;
+	int beacon_size;
+	struct ieee80211_probe_response *beacon_buf;
+	struct sk_buff *skb = NULL;
+	int encrypt;
+	int atim_len,erp_len;
+	struct ieee80211_crypt_data* crypt;
+
+	char *ssid = ieee->current_network.ssid;
+	int ssid_len = ieee->current_network.ssid_len;
+	int rate_len = ieee->current_network.rates_len+2;
+	int rate_ex_len = ieee->current_network.rates_ex_len;
+	int wpa_ie_len = ieee->wpa_ie_len;
+	u8 erpinfo_content = 0;
+
+	u8* tmp_ht_cap_buf;
+	u8 tmp_ht_cap_len=0;
+	u8* tmp_ht_info_buf;
+	u8 tmp_ht_info_len=0;
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	u8* tmp_generic_ie_buf=NULL;
+	u8 tmp_generic_ie_len=0;
+
+	if(rate_ex_len > 0) rate_ex_len+=2;
+
+	if(ieee->current_network.capability & WLAN_CAPABILITY_IBSS)
+		atim_len = 4;
+	else
+		atim_len = 0;
+
+#if 1
+	if(ieee80211_is_54g(ieee->current_network))
+		erp_len = 3;
+	else
+		erp_len = 0;
+#else
+      if((ieee->current_network.mode == IEEE_G)
+	  	||( ieee->current_network.mode == IEEE_N_24G && ieee->pHTInfo->bCurSuppCCK)) {
+	  	erp_len = 3;
+		erpinfo_content = 0;
+		if(ieee->current_network.buseprotection)
+			erpinfo_content |= ERP_UseProtection;
+      	}
+	else
+		erp_len = 0;
+#endif
+
+
+	crypt = ieee->crypt[ieee->tx_keyidx];
+
+
+	encrypt = ieee->host_encrypt && crypt && crypt->ops &&
+		((0 == strcmp(crypt->ops->name, "WEP") || wpa_ie_len));
+	//HT ralated element
+#if 1
+	tmp_ht_cap_buf =(u8*) &(ieee->pHTInfo->SelfHTCap);
+	tmp_ht_cap_len = sizeof(ieee->pHTInfo->SelfHTCap);
+	tmp_ht_info_buf =(u8*) &(ieee->pHTInfo->SelfHTInfo);
+	tmp_ht_info_len = sizeof(ieee->pHTInfo->SelfHTInfo);
+	HTConstructCapabilityElement(ieee, tmp_ht_cap_buf, &tmp_ht_cap_len,encrypt);
+	HTConstructInfoElement(ieee,tmp_ht_info_buf,&tmp_ht_info_len, encrypt);
+
+
+        if(pHTInfo->bRegRT2RTAggregation)
+        {
+        	tmp_generic_ie_buf = ieee->pHTInfo->szRT2RTAggBuffer;
+		tmp_generic_ie_len = sizeof(ieee->pHTInfo->szRT2RTAggBuffer);
+		HTConstructRT2RTAggElement(ieee, tmp_generic_ie_buf, &tmp_generic_ie_len);
+        }
+//	printk("===============>tmp_ht_cap_len is %d,tmp_ht_info_len is %d, tmp_generic_ie_len is %d\n",tmp_ht_cap_len,tmp_ht_info_len,tmp_generic_ie_len);
+#endif
+	beacon_size = sizeof(struct ieee80211_probe_response)+2+
+		ssid_len
+		+3 //channel
+		+rate_len
+		+rate_ex_len
+		+atim_len
+		+erp_len
+                +wpa_ie_len
+	//	+tmp_ht_cap_len
+	//	+tmp_ht_info_len
+	//	+tmp_generic_ie_len
+//		+wmm_len+2
+		+ieee->tx_headroom;
+	skb = dev_alloc_skb(beacon_size);
+	if (!skb)
+		return NULL;
+	skb_reserve(skb, ieee->tx_headroom);
+	beacon_buf = (struct ieee80211_probe_response*) skb_put(skb, (beacon_size - ieee->tx_headroom));
+	memcpy (beacon_buf->header.addr1, dest,ETH_ALEN);
+	memcpy (beacon_buf->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
+	memcpy (beacon_buf->header.addr3, ieee->current_network.bssid, ETH_ALEN);
+
+	beacon_buf->header.duration_id = 0; //FIXME
+	beacon_buf->beacon_interval =
+		cpu_to_le16(ieee->current_network.beacon_interval);
+	beacon_buf->capability =
+		cpu_to_le16(ieee->current_network.capability & WLAN_CAPABILITY_IBSS);
+	beacon_buf->capability |=
+		cpu_to_le16(ieee->current_network.capability & WLAN_CAPABILITY_SHORT_PREAMBLE); //add short preamble here
+
+	if(ieee->short_slot && (ieee->current_network.capability & WLAN_CAPABILITY_SHORT_SLOT))
+		cpu_to_le16((beacon_buf->capability |= WLAN_CAPABILITY_SHORT_SLOT));
+
+	crypt = ieee->crypt[ieee->tx_keyidx];
+#if 0
+	encrypt = ieee->host_encrypt && crypt && crypt->ops &&
+		(0 == strcmp(crypt->ops->name, "WEP"));
+#endif
+	if (encrypt)
+		beacon_buf->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
+
+
+	beacon_buf->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_PROBE_RESP);
+	beacon_buf->info_element[0].id = MFIE_TYPE_SSID;
+	beacon_buf->info_element[0].len = ssid_len;
+
+	tag = (u8*) beacon_buf->info_element[0].data;
+
+	memcpy(tag, ssid, ssid_len);
+
+	tag += ssid_len;
+
+	*(tag++) = MFIE_TYPE_RATES;
+	*(tag++) = rate_len-2;
+	memcpy(tag,ieee->current_network.rates,rate_len-2);
+	tag+=rate_len-2;
+
+	*(tag++) = MFIE_TYPE_DS_SET;
+	*(tag++) = 1;
+	*(tag++) = ieee->current_network.channel;
+
+	if(atim_len){
+	u16 val16;
+		*(tag++) = MFIE_TYPE_IBSS_SET;
+		*(tag++) = 2;
+		//*((u16*)(tag)) = cpu_to_le16(ieee->current_network.atim_window);
+		 val16 = cpu_to_le16(ieee->current_network.atim_window);
+		memcpy((u8 *)tag, (u8 *)&val16, 2);
+		tag+=2;
+	}
+
+	if(erp_len){
+		*(tag++) = MFIE_TYPE_ERP;
+		*(tag++) = 1;
+		*(tag++) = erpinfo_content;
+	}
+#if 0
+	//Include High Throuput capability
+
+	*(tag++) = MFIE_TYPE_HT_CAP;
+	*(tag++) = tmp_ht_cap_len - 2;
+	memcpy(tag, tmp_ht_cap_buf, tmp_ht_cap_len - 2);
+	tag += tmp_ht_cap_len - 2;
+#endif
+	if(rate_ex_len){
+		*(tag++) = MFIE_TYPE_RATES_EX;
+		*(tag++) = rate_ex_len-2;
+		memcpy(tag,ieee->current_network.rates_ex,rate_ex_len-2);
+		tag+=rate_ex_len-2;
+	}
+
+#if 0
+	//Include High Throuput info
+
+	*(tag++) = MFIE_TYPE_HT_INFO;
+	*(tag++) = tmp_ht_info_len - 2;
+	memcpy(tag, tmp_ht_info_buf, tmp_ht_info_len -2);
+	tag += tmp_ht_info_len - 2;
+#endif
+	if (wpa_ie_len)
+	{
+		if (ieee->iw_mode == IW_MODE_ADHOC)
+		{//as Windows will set pairwise key same as the group key which is not allowed in Linux, so set this for IOT issue. WB 2008.07.07
+			memcpy(&ieee->wpa_ie[14], &ieee->wpa_ie[8], 4);
+		}
+		memcpy(tag, ieee->wpa_ie, ieee->wpa_ie_len);
+		tag += wpa_ie_len;
+	}
+
+#if 0
+	//
+	// Construct Realtek Proprietary Aggregation mode (Set AMPDU Factor to 2, 32k)
+	//
+	if(pHTInfo->bRegRT2RTAggregation)
+	{
+		(*tag++) = 0xdd;
+		(*tag++) = tmp_generic_ie_len - 2;
+		memcpy(tag,tmp_generic_ie_buf,tmp_generic_ie_len -2);
+		tag += tmp_generic_ie_len -2;
+
+	}
+#endif
+#if 0
+	if(ieee->qos_support)
+	{
+		(*tag++) = 0xdd;
+		(*tag++) = wmm_len;
+		memcpy(tag,QosOui,wmm_len);
+		tag += wmm_len;
+	}
+#endif
+	//skb->dev = ieee->dev;
+	return skb;
+}
+
+
+struct sk_buff* ieee80211_assoc_resp(struct ieee80211_device *ieee, u8 *dest)
+{
+	struct sk_buff *skb;
+	u8* tag;
+
+	struct ieee80211_crypt_data* crypt;
+	struct ieee80211_assoc_response_frame *assoc;
+	short encrypt;
+
+	unsigned int rate_len = ieee80211_MFIE_rate_len(ieee);
+	int len = sizeof(struct ieee80211_assoc_response_frame) + rate_len + ieee->tx_headroom;
+
+	skb = dev_alloc_skb(len);
+
+	if (!skb)
+		return NULL;
+
+	skb_reserve(skb, ieee->tx_headroom);
+
+	assoc = (struct ieee80211_assoc_response_frame *)
+		skb_put(skb,sizeof(struct ieee80211_assoc_response_frame));
+
+	assoc->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_ASSOC_RESP);
+	memcpy(assoc->header.addr1, dest,ETH_ALEN);
+	memcpy(assoc->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
+	memcpy(assoc->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
+	assoc->capability = cpu_to_le16(ieee->iw_mode == IW_MODE_MASTER ?
+		WLAN_CAPABILITY_BSS : WLAN_CAPABILITY_IBSS);
+
+
+	if(ieee->short_slot)
+		assoc->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
+
+	if (ieee->host_encrypt)
+		crypt = ieee->crypt[ieee->tx_keyidx];
+	else crypt = NULL;
+
+	encrypt = ( crypt && crypt->ops);
+
+	if (encrypt)
+		assoc->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
+
+	assoc->status = 0;
+	assoc->aid = cpu_to_le16(ieee->assoc_id);
+	if (ieee->assoc_id == 0x2007) ieee->assoc_id=0;
+	else ieee->assoc_id++;
+
+	tag = (u8*) skb_put(skb, rate_len);
+
+	ieee80211_MFIE_Brate(ieee, &tag);
+	ieee80211_MFIE_Grate(ieee, &tag);
+
+	return skb;
+}
+
+struct sk_buff* ieee80211_auth_resp(struct ieee80211_device *ieee,int status, u8 *dest)
+{
+	struct sk_buff *skb;
+	struct ieee80211_authentication *auth;
+	int len = ieee->tx_headroom + sizeof(struct ieee80211_authentication)+1;
+
+	skb = dev_alloc_skb(len);
+
+	if (!skb)
+		return NULL;
+
+	skb->len = sizeof(struct ieee80211_authentication);
+
+	auth = (struct ieee80211_authentication *)skb->data;
+
+	auth->status = cpu_to_le16(status);
+	auth->transaction = cpu_to_le16(2);
+	auth->algorithm = cpu_to_le16(WLAN_AUTH_OPEN);
+
+	memcpy(auth->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
+	memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
+	memcpy(auth->header.addr1, dest, ETH_ALEN);
+	auth->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_AUTH);
+	return skb;
+
+
+}
+
+struct sk_buff* ieee80211_null_func(struct ieee80211_device *ieee,short pwr)
+{
+	struct sk_buff *skb;
+	struct ieee80211_hdr_3addr* hdr;
+
+	skb = dev_alloc_skb(sizeof(struct ieee80211_hdr_3addr));
+
+	if (!skb)
+		return NULL;
+
+	hdr = (struct ieee80211_hdr_3addr*)skb_put(skb,sizeof(struct ieee80211_hdr_3addr));
+
+	memcpy(hdr->addr1, ieee->current_network.bssid, ETH_ALEN);
+	memcpy(hdr->addr2, ieee->dev->dev_addr, ETH_ALEN);
+	memcpy(hdr->addr3, ieee->current_network.bssid, ETH_ALEN);
+
+	hdr->frame_ctl = cpu_to_le16(IEEE80211_FTYPE_DATA |
+		IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_TODS |
+		(pwr ? IEEE80211_FCTL_PM:0));
+
+	return skb;
+
+
+}
+
+
+void ieee80211_resp_to_assoc_rq(struct ieee80211_device *ieee, u8* dest)
+{
+	struct sk_buff *buf = ieee80211_assoc_resp(ieee, dest);
+
+	if (buf)
+		softmac_mgmt_xmit(buf, ieee);
+}
+
+
+void ieee80211_resp_to_auth(struct ieee80211_device *ieee, int s, u8* dest)
+{
+	struct sk_buff *buf = ieee80211_auth_resp(ieee, s, dest);
+
+	if (buf)
+		softmac_mgmt_xmit(buf, ieee);
+}
+
+
+void ieee80211_resp_to_probe(struct ieee80211_device *ieee, u8 *dest)
+{
+
+
+	struct sk_buff *buf = ieee80211_probe_resp(ieee, dest);
+	if (buf)
+		softmac_mgmt_xmit(buf, ieee);
+}
+
+
+inline struct sk_buff *ieee80211_association_req(struct ieee80211_network *beacon,struct ieee80211_device *ieee)
+{
+	struct sk_buff *skb;
+	//unsigned long flags;
+
+	struct ieee80211_assoc_request_frame *hdr;
+	u8 *tag;//,*rsn_ie;
+	//short info_addr = 0;
+	//int i;
+	//u16 suite_count = 0;
+	//u8 suit_select = 0;
+	//unsigned int wpa_len = beacon->wpa_ie_len;
+	//for HT
+	u8* ht_cap_buf = NULL;
+	u8 ht_cap_len=0;
+	u8* realtek_ie_buf=NULL;
+	u8 realtek_ie_len=0;
+	int wpa_ie_len= ieee->wpa_ie_len;
+	unsigned int ckip_ie_len=0;
+	unsigned int ccxrm_ie_len=0;
+	unsigned int cxvernum_ie_len=0;
+	struct ieee80211_crypt_data* crypt;
+	int encrypt;
+
+	unsigned int rate_len = ieee80211_MFIE_rate_len(ieee);
+	unsigned int wmm_info_len = beacon->qos_data.supported?9:0;
+#ifdef THOMAS_TURBO
+	unsigned int turbo_info_len = beacon->Turbo_Enable?9:0;
+#endif
+
+	int len = 0;
+
+	crypt = ieee->crypt[ieee->tx_keyidx];
+	encrypt = ieee->host_encrypt && crypt && crypt->ops && ((0 == strcmp(crypt->ops->name,"WEP") || wpa_ie_len));
+
+	//Include High Throuput capability && Realtek proprietary
+	if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT)
+	{
+		ht_cap_buf = (u8*)&(ieee->pHTInfo->SelfHTCap);
+		ht_cap_len = sizeof(ieee->pHTInfo->SelfHTCap);
+		HTConstructCapabilityElement(ieee, ht_cap_buf, &ht_cap_len, encrypt);
+		if(ieee->pHTInfo->bCurrentRT2RTAggregation)
+		{
+			realtek_ie_buf = ieee->pHTInfo->szRT2RTAggBuffer;
+			realtek_ie_len = sizeof( ieee->pHTInfo->szRT2RTAggBuffer);
+			HTConstructRT2RTAggElement(ieee, realtek_ie_buf, &realtek_ie_len);
+
+		}
+	}
+	if(ieee->qos_support){
+		wmm_info_len = beacon->qos_data.supported?9:0;
+	}
+
+
+	if(beacon->bCkipSupported)
+	{
+		ckip_ie_len = 30+2;
+	}
+	if(beacon->bCcxRmEnable)
+	{
+		ccxrm_ie_len = 6+2;
+	}
+	if( beacon->BssCcxVerNumber >= 2 )
+	{
+		cxvernum_ie_len = 5+2;
+	}
+#ifdef THOMAS_TURBO
+	len = sizeof(struct ieee80211_assoc_request_frame)+ 2
+		+ beacon->ssid_len//essid tagged val
+		+ rate_len//rates tagged val
+		+ wpa_ie_len
+		+ wmm_info_len
+		+ turbo_info_len
+                + ht_cap_len
+		+ realtek_ie_len
+		+ ckip_ie_len
+		+ ccxrm_ie_len
+		+ cxvernum_ie_len
+		+ ieee->tx_headroom;
+#else
+	len = sizeof(struct ieee80211_assoc_request_frame)+ 2
+		+ beacon->ssid_len//essid tagged val
+		+ rate_len//rates tagged val
+		+ wpa_ie_len
+		+ wmm_info_len
+                + ht_cap_len
+		+ realtek_ie_len
+		+ ckip_ie_len
+		+ ccxrm_ie_len
+		+ cxvernum_ie_len
+		+ ieee->tx_headroom;
+#endif
+
+	skb = dev_alloc_skb(len);
+
+	if (!skb)
+		return NULL;
+
+	skb_reserve(skb, ieee->tx_headroom);
+
+	hdr = (struct ieee80211_assoc_request_frame *)
+		skb_put(skb, sizeof(struct ieee80211_assoc_request_frame)+2);
+
+
+	hdr->header.frame_ctl = IEEE80211_STYPE_ASSOC_REQ;
+	hdr->header.duration_id= 37; //FIXME
+	memcpy(hdr->header.addr1, beacon->bssid, ETH_ALEN);
+	memcpy(hdr->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
+	memcpy(hdr->header.addr3, beacon->bssid, ETH_ALEN);
+
+	memcpy(ieee->ap_mac_addr, beacon->bssid, ETH_ALEN);//for HW security, John
+
+	hdr->capability = cpu_to_le16(WLAN_CAPABILITY_BSS);
+	if (beacon->capability & WLAN_CAPABILITY_PRIVACY )
+		hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
+
+	if (beacon->capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
+		hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_PREAMBLE); //add short_preamble here
+
+	if(ieee->short_slot)
+		hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
+ 	if (wmm_info_len) //QOS
+	hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_QOS);
+
+	hdr->listen_interval = 0xa; //FIXME
+
+	hdr->info_element[0].id = MFIE_TYPE_SSID;
+
+	hdr->info_element[0].len = beacon->ssid_len;
+	tag = skb_put(skb, beacon->ssid_len);
+	memcpy(tag, beacon->ssid, beacon->ssid_len);
+
+	tag = skb_put(skb, rate_len);
+
+	ieee80211_MFIE_Brate(ieee, &tag);
+	ieee80211_MFIE_Grate(ieee, &tag);
+	// For CCX 1 S13, CKIP. Added by Annie, 2006-08-14.
+	if( beacon->bCkipSupported )
+	{
+		static u8	AironetIeOui[] = {0x00, 0x01, 0x66}; // "4500-client"
+		u8	CcxAironetBuf[30];
+		OCTET_STRING	osCcxAironetIE;
+
+		memset(CcxAironetBuf, 0,30);
+		osCcxAironetIE.Octet = CcxAironetBuf;
+		osCcxAironetIE.Length = sizeof(CcxAironetBuf);
+		//
+		// Ref. CCX test plan v3.61, 3.2.3.1 step 13.
+		// We want to make the device type as "4500-client". 060926, by CCW.
+		//
+		memcpy(osCcxAironetIE.Octet, AironetIeOui, sizeof(AironetIeOui));
+
+		// CCX1 spec V1.13, A01.1 CKIP Negotiation (page23):
+		// "The CKIP negotiation is started with the associate request from the client to the access point,
+		//  containing an Aironet element with both the MIC and KP bits set."
+		osCcxAironetIE.Octet[IE_CISCO_FLAG_POSITION] |=  (SUPPORT_CKIP_PK|SUPPORT_CKIP_MIC) ;
+		tag = skb_put(skb, ckip_ie_len);
+		*tag++ = MFIE_TYPE_AIRONET;
+		*tag++ = osCcxAironetIE.Length;
+		memcpy(tag,osCcxAironetIE.Octet,osCcxAironetIE.Length);
+		tag += osCcxAironetIE.Length;
+	}
+
+	if(beacon->bCcxRmEnable)
+	{
+		static u8 CcxRmCapBuf[] = {0x00, 0x40, 0x96, 0x01, 0x01, 0x00};
+		OCTET_STRING osCcxRmCap;
+
+		osCcxRmCap.Octet = CcxRmCapBuf;
+		osCcxRmCap.Length = sizeof(CcxRmCapBuf);
+		tag = skb_put(skb,ccxrm_ie_len);
+		*tag++ = MFIE_TYPE_GENERIC;
+		*tag++ = osCcxRmCap.Length;
+		memcpy(tag,osCcxRmCap.Octet,osCcxRmCap.Length);
+		tag += osCcxRmCap.Length;
+	}
+
+	if( beacon->BssCcxVerNumber >= 2 )
+	{
+		u8			CcxVerNumBuf[] = {0x00, 0x40, 0x96, 0x03, 0x00};
+		OCTET_STRING	osCcxVerNum;
+		CcxVerNumBuf[4] = beacon->BssCcxVerNumber;
+		osCcxVerNum.Octet = CcxVerNumBuf;
+		osCcxVerNum.Length = sizeof(CcxVerNumBuf);
+		tag = skb_put(skb,cxvernum_ie_len);
+		*tag++ = MFIE_TYPE_GENERIC;
+		*tag++ = osCcxVerNum.Length;
+		memcpy(tag,osCcxVerNum.Octet,osCcxVerNum.Length);
+		tag += osCcxVerNum.Length;
+	}
+        //HT cap element
+	if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT){
+		if(ieee->pHTInfo->ePeerHTSpecVer != HT_SPEC_VER_EWC)
+		{
+			tag = skb_put(skb, ht_cap_len);
+			*tag++ = MFIE_TYPE_HT_CAP;
+			*tag++ = ht_cap_len - 2;
+			memcpy(tag, ht_cap_buf,ht_cap_len -2);
+			tag += ht_cap_len -2;
+		}
+	}
+
+
+	//choose what wpa_supplicant gives to associate.
+	tag = skb_put(skb, wpa_ie_len);
+	if (wpa_ie_len){
+		memcpy(tag, ieee->wpa_ie, ieee->wpa_ie_len);
+	}
+
+	tag = skb_put(skb,wmm_info_len);
+	if(wmm_info_len) {
+	  ieee80211_WMM_Info(ieee, &tag);
+	}
+#ifdef THOMAS_TURBO
+	tag = skb_put(skb,turbo_info_len);
+        if(turbo_info_len) {
+                ieee80211_TURBO_Info(ieee, &tag);
+        }
+#endif
+
+	if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT){
+		if(ieee->pHTInfo->ePeerHTSpecVer == HT_SPEC_VER_EWC)
+		{
+			tag = skb_put(skb, ht_cap_len);
+			*tag++ = MFIE_TYPE_GENERIC;
+			*tag++ = ht_cap_len - 2;
+			memcpy(tag, ht_cap_buf,ht_cap_len - 2);
+			tag += ht_cap_len -2;
+		}
+
+		if(ieee->pHTInfo->bCurrentRT2RTAggregation){
+			tag = skb_put(skb, realtek_ie_len);
+			*tag++ = MFIE_TYPE_GENERIC;
+			*tag++ = realtek_ie_len - 2;
+			memcpy(tag, realtek_ie_buf,realtek_ie_len -2 );
+		}
+	}
+//	printk("<=====%s(), %p, %p\n", __FUNCTION__, ieee->dev, ieee->dev->dev_addr);
+//	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, skb->data, skb->len);
+	return skb;
+}
+
+void ieee80211_associate_abort(struct ieee80211_device *ieee)
+{
+
+	unsigned long flags;
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	ieee->associate_seq++;
+
+	/* don't scan, and avoid to have the RX path possibily
+	 * try again to associate. Even do not react to AUTH or
+	 * ASSOC response. Just wait for the retry wq to be scheduled.
+	 * Here we will check if there are good nets to associate
+	 * with, so we retry or just get back to NO_LINK and scanning
+	 */
+	if (ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATING){
+		IEEE80211_DEBUG_MGMT("Authentication failed\n");
+		ieee->softmac_stats.no_auth_rs++;
+	}else{
+		IEEE80211_DEBUG_MGMT("Association failed\n");
+		ieee->softmac_stats.no_ass_rs++;
+	}
+
+	ieee->state = IEEE80211_ASSOCIATING_RETRY;
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	queue_delayed_work(ieee->wq, &ieee->associate_retry_wq, \
+                           IEEE80211_SOFTMAC_ASSOC_RETRY_TIME);
+#else
+	schedule_task(&ieee->associate_retry_wq);
+#endif
+
+	spin_unlock_irqrestore(&ieee->lock, flags);
+}
+
+void ieee80211_associate_abort_cb(unsigned long dev)
+{
+	ieee80211_associate_abort((struct ieee80211_device *) dev);
+}
+
+
+void ieee80211_associate_step1(struct ieee80211_device *ieee)
+{
+	struct ieee80211_network *beacon = &ieee->current_network;
+	struct sk_buff *skb;
+
+	IEEE80211_DEBUG_MGMT("Stopping scan\n");
+
+	ieee->softmac_stats.tx_auth_rq++;
+	skb=ieee80211_authentication_req(beacon, ieee, 0);
+
+	if (!skb)
+		ieee80211_associate_abort(ieee);
+	else{
+		ieee->state = IEEE80211_ASSOCIATING_AUTHENTICATING ;
+		IEEE80211_DEBUG_MGMT("Sending authentication request\n");
+		//printk(KERN_WARNING "Sending authentication request\n");
+		softmac_mgmt_xmit(skb, ieee);
+		//BUGON when you try to add_timer twice, using mod_timer may be better, john0709
+		if(!timer_pending(&ieee->associate_timer)){
+			ieee->associate_timer.expires = jiffies + (HZ / 2);
+			add_timer(&ieee->associate_timer);
+		}
+		//dev_kfree_skb_any(skb);//edit by thomas
+	}
+}
+
+void ieee80211_auth_challenge(struct ieee80211_device *ieee, u8 *challenge, int chlen)
+{
+	u8 *c;
+	struct sk_buff *skb;
+	struct ieee80211_network *beacon = &ieee->current_network;
+//	int hlen = sizeof(struct ieee80211_authentication);
+
+	ieee->associate_seq++;
+	ieee->softmac_stats.tx_auth_rq++;
+
+	skb = ieee80211_authentication_req(beacon, ieee, chlen+2);
+	if (!skb)
+		ieee80211_associate_abort(ieee);
+	else{
+		c = skb_put(skb, chlen+2);
+		*(c++) = MFIE_TYPE_CHALLENGE;
+		*(c++) = chlen;
+		memcpy(c, challenge, chlen);
+
+		IEEE80211_DEBUG_MGMT("Sending authentication challenge response\n");
+
+		ieee80211_encrypt_fragment(ieee, skb, sizeof(struct ieee80211_hdr_3addr  ));
+
+		softmac_mgmt_xmit(skb, ieee);
+		mod_timer(&ieee->associate_timer, jiffies + (HZ/2));
+#if 0
+		ieee->associate_timer.expires = jiffies + (HZ / 2);
+		add_timer(&ieee->associate_timer);
+#endif
+		//dev_kfree_skb_any(skb);//edit by thomas
+	}
+	kfree(challenge);
+}
+
+void ieee80211_associate_step2(struct ieee80211_device *ieee)
+{
+	struct sk_buff* skb;
+	struct ieee80211_network *beacon = &ieee->current_network;
+
+	del_timer_sync(&ieee->associate_timer);
+
+	IEEE80211_DEBUG_MGMT("Sending association request\n");
+
+	ieee->softmac_stats.tx_ass_rq++;
+	skb=ieee80211_association_req(beacon, ieee);
+	if (!skb)
+		ieee80211_associate_abort(ieee);
+	else{
+		softmac_mgmt_xmit(skb, ieee);
+		mod_timer(&ieee->associate_timer, jiffies + (HZ/2));
+#if 0
+		ieee->associate_timer.expires = jiffies + (HZ / 2);
+		add_timer(&ieee->associate_timer);
+#endif
+		//dev_kfree_skb_any(skb);//edit by thomas
+	}
+}
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+void ieee80211_associate_complete_wq(struct work_struct *work)
+{
+        struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, associate_complete_wq);
+#else
+void ieee80211_associate_complete_wq(struct ieee80211_device *ieee)
+{
+#endif
+	printk(KERN_INFO "Associated successfully\n");
+	ieee->is_roaming = false;
+	if(ieee80211_is_54g(ieee->current_network) &&
+		(ieee->modulation & IEEE80211_OFDM_MODULATION)){
+
+		ieee->rate = 108;
+		printk(KERN_INFO"Using G rates:%d\n", ieee->rate);
+	}else{
+		ieee->rate = 22;
+		printk(KERN_INFO"Using B rates:%d\n", ieee->rate);
+	}
+	if (ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT)
+	{
+		printk("Successfully associated, ht enabled\n");
+		HTOnAssocRsp(ieee);
+	}
+	else
+	{
+		printk("Successfully associated, ht not enabled(%d, %d)\n", ieee->pHTInfo->bCurrentHTSupport, ieee->pHTInfo->bEnableHT);
+		memset(ieee->dot11HTOperationalRateSet, 0, 16);
+		//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
+	}
+	ieee->LinkDetectInfo.SlotNum = 2 * (1 + ieee->current_network.beacon_interval/500);
+	// To prevent the immediately calling watch_dog after association.
+	if(ieee->LinkDetectInfo.NumRecvBcnInPeriod==0||ieee->LinkDetectInfo.NumRecvDataInPeriod==0 )
+	{
+		ieee->LinkDetectInfo.NumRecvBcnInPeriod = 1;
+		ieee->LinkDetectInfo.NumRecvDataInPeriod= 1;
+	}
+	ieee->link_change(ieee->dev);
+	if(ieee->is_silent_reset == 0){
+		printk("============>normal associate\n");
+	notify_wx_assoc_event(ieee);
+	}
+	else if(ieee->is_silent_reset == 1)
+	{
+		printk("==================>silent reset associate\n");
+		ieee->is_silent_reset = 0;
+	}
+
+	if (ieee->data_hard_resume)
+		ieee->data_hard_resume(ieee->dev);
+	netif_carrier_on(ieee->dev);
+}
+
+void ieee80211_associate_complete(struct ieee80211_device *ieee)
+{
+//	int i;
+//	struct net_device* dev = ieee->dev;
+	del_timer_sync(&ieee->associate_timer);
+
+#if 0
+	for(i = 0; i < 6; i++) {
+	  ieee->seq_ctrl[i] = 0;
+	}
+#endif
+	ieee->state = IEEE80211_LINKED;
+#if 0
+	if (ieee->pHTInfo->bCurrentHTSupport)
+	{
+		printk("Successfully associated, ht enabled\n");
+		queue_work(ieee->wq, &ieee->ht_onAssRsp);
+	}
+	else
+	{
+		printk("Successfully associated, ht not enabled\n");
+		memset(ieee->dot11HTOperationalRateSet, 0, 16);
+		HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
+	}
+#endif
+	//ieee->UpdateHalRATRTableHandler(dev, ieee->dot11HTOperationalRateSet);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	queue_work(ieee->wq, &ieee->associate_complete_wq);
+#else
+	schedule_task(&ieee->associate_complete_wq);
+#endif
+}
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+void ieee80211_associate_procedure_wq(struct work_struct *work)
+{
+        struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, associate_procedure_wq);
+#else
+void ieee80211_associate_procedure_wq(struct ieee80211_device *ieee)
+{
+#endif
+	ieee->sync_scan_hurryup = 1;
+	down(&ieee->wx_sem);
+
+	if (ieee->data_hard_stop)
+		ieee->data_hard_stop(ieee->dev);
+
+	ieee80211_stop_scan(ieee);
+	printk("===>%s(), chan:%d\n", __FUNCTION__, ieee->current_network.channel);
+	//ieee->set_chan(ieee->dev, ieee->current_network.channel);
+	HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
+
+	ieee->associate_seq = 1;
+	ieee80211_associate_step1(ieee);
+
+	up(&ieee->wx_sem);
+}
+
+inline void ieee80211_softmac_new_net(struct ieee80211_device *ieee, struct ieee80211_network *net)
+{
+	u8 tmp_ssid[IW_ESSID_MAX_SIZE+1];
+	int tmp_ssid_len = 0;
+
+	short apset,ssidset,ssidbroad,apmatch,ssidmatch;
+
+	/* we are interested in new new only if we are not associated
+	 * and we are not associating / authenticating
+	 */
+	if (ieee->state != IEEE80211_NOLINK)
+		return;
+
+	if ((ieee->iw_mode == IW_MODE_INFRA) && !(net->capability & WLAN_CAPABILITY_BSS))
+		return;
+
+	if ((ieee->iw_mode == IW_MODE_ADHOC) && !(net->capability & WLAN_CAPABILITY_IBSS))
+		return;
+
+
+	if (ieee->iw_mode == IW_MODE_INFRA || ieee->iw_mode == IW_MODE_ADHOC){
+		/* if the user specified the AP MAC, we need also the essid
+		 * This could be obtained by beacons or, if the network does not
+		 * broadcast it, it can be put manually.
+		 */
+		apset = ieee->wap_set;//(memcmp(ieee->current_network.bssid, zero,ETH_ALEN)!=0 );
+		ssidset = ieee->ssid_set;//ieee->current_network.ssid[0] != '\0';
+		ssidbroad =  !(net->ssid_len == 0 || net->ssid[0]== '\0');
+		apmatch = (memcmp(ieee->current_network.bssid, net->bssid, ETH_ALEN)==0);
+		ssidmatch = (ieee->current_network.ssid_len == net->ssid_len)&&\
+				(!strncmp(ieee->current_network.ssid, net->ssid, net->ssid_len));
+
+
+		if (	/* if the user set the AP check if match.
+		         * if the network does not broadcast essid we check the user supplyed ANY essid
+			 * if the network does broadcast and the user does not set essid it is OK
+			 * if the network does broadcast and the user did set essid chech if essid match
+			 */
+			( apset && apmatch &&
+				((ssidset && ssidbroad && ssidmatch) || (ssidbroad && !ssidset) || (!ssidbroad && ssidset)) ) ||
+			/* if the ap is not set, check that the user set the bssid
+			 * and the network does bradcast and that those two bssid matches
+			 */
+			(!apset && ssidset && ssidbroad && ssidmatch)
+			){
+				/* if the essid is hidden replace it with the
+				* essid provided by the user.
+				*/
+				if (!ssidbroad){
+					strncpy(tmp_ssid, ieee->current_network.ssid, IW_ESSID_MAX_SIZE);
+					tmp_ssid_len = ieee->current_network.ssid_len;
+				}
+				memcpy(&ieee->current_network, net, sizeof(struct ieee80211_network));
+
+				if (!ssidbroad){
+					strncpy(ieee->current_network.ssid, tmp_ssid, IW_ESSID_MAX_SIZE);
+					ieee->current_network.ssid_len = tmp_ssid_len;
+				}
+				printk(KERN_INFO"Linking with %s,channel:%d, qos:%d, myHT:%d, networkHT:%d, mode:%x\n",ieee->current_network.ssid,ieee->current_network.channel, ieee->current_network.qos_data.supported, ieee->pHTInfo->bEnableHT, ieee->current_network.bssht.bdSupportHT, ieee->current_network.mode);
+
+				//ieee->pHTInfo->IOTAction = 0;
+				HTResetIOTSetting(ieee->pHTInfo);
+				if (ieee->iw_mode == IW_MODE_INFRA){
+					/* Join the network for the first time */
+					ieee->AsocRetryCount = 0;
+					//for HT by amy 080514
+					if((ieee->current_network.qos_data.supported == 1) &&
+					  // (ieee->pHTInfo->bEnableHT && ieee->current_network.bssht.bdSupportHT))
+					   ieee->current_network.bssht.bdSupportHT)
+/*WB, 2008.09.09:bCurrentHTSupport and bEnableHT two flags are going to put together to check whether we are in HT now, so needn't to check bEnableHT flags here. That's is to say we will set to HT support whenever joined AP has the ability to support HT. And whether we are in HT or not, please check bCurrentHTSupport&&bEnableHT now please.*/
+					{
+					//	ieee->pHTInfo->bCurrentHTSupport = true;
+						HTResetSelfAndSavePeerSetting(ieee, &(ieee->current_network));
+					}
+					else
+					{
+						ieee->pHTInfo->bCurrentHTSupport = false;
+					}
+
+					ieee->state = IEEE80211_ASSOCIATING;
+					if(ieee->LedControlHandler != NULL)
+					        ieee->LedControlHandler(ieee->dev, LED_CTL_START_TO_LINK);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+					queue_work(ieee->wq, &ieee->associate_procedure_wq);
+#else
+					schedule_task(&ieee->associate_procedure_wq);
+#endif
+				}else{
+					if(ieee80211_is_54g(ieee->current_network) &&
+						(ieee->modulation & IEEE80211_OFDM_MODULATION)){
+						ieee->rate = 108;
+						ieee->SetWirelessMode(ieee->dev, IEEE_G);
+						printk(KERN_INFO"Using G rates\n");
+					}else{
+						ieee->rate = 22;
+						ieee->SetWirelessMode(ieee->dev, IEEE_B);
+						printk(KERN_INFO"Using B rates\n");
+					}
+					memset(ieee->dot11HTOperationalRateSet, 0, 16);
+					//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
+					ieee->state = IEEE80211_LINKED;
+				}
+
+		}
+	}
+
+}
+
+void ieee80211_softmac_check_all_nets(struct ieee80211_device *ieee)
+{
+	unsigned long flags;
+	struct ieee80211_network *target;
+
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	list_for_each_entry(target, &ieee->network_list, list) {
+
+		/* if the state become different that NOLINK means
+		 * we had found what we are searching for
+		 */
+
+		if (ieee->state != IEEE80211_NOLINK)
+			break;
+
+		if (ieee->scan_age == 0 || time_after(target->last_scanned + ieee->scan_age, jiffies))
+		ieee80211_softmac_new_net(ieee, target);
+	}
+
+	spin_unlock_irqrestore(&ieee->lock, flags);
+
+}
+
+
+static inline u16 auth_parse(struct sk_buff *skb, u8** challenge, int *chlen)
+{
+	struct ieee80211_authentication *a;
+	u8 *t;
+	if (skb->len <  (sizeof(struct ieee80211_authentication)-sizeof(struct ieee80211_info_element))){
+		IEEE80211_DEBUG_MGMT("invalid len in auth resp: %d\n",skb->len);
+		return 0xcafe;
+	}
+	*challenge = NULL;
+	a = (struct ieee80211_authentication*) skb->data;
+	if(skb->len > (sizeof(struct ieee80211_authentication) +3)){
+		t = skb->data + sizeof(struct ieee80211_authentication);
+
+		if(*(t++) == MFIE_TYPE_CHALLENGE){
+			*chlen = *(t++);
+			*challenge = (u8*)kmalloc(*chlen, GFP_ATOMIC);
+			memcpy(*challenge, t, *chlen);
+		}
+	}
+
+	return cpu_to_le16(a->status);
+
+}
+
+
+int auth_rq_parse(struct sk_buff *skb,u8* dest)
+{
+	struct ieee80211_authentication *a;
+
+	if (skb->len <  (sizeof(struct ieee80211_authentication)-sizeof(struct ieee80211_info_element))){
+		IEEE80211_DEBUG_MGMT("invalid len in auth request: %d\n",skb->len);
+		return -1;
+	}
+	a = (struct ieee80211_authentication*) skb->data;
+
+	memcpy(dest,a->header.addr2, ETH_ALEN);
+
+	if (le16_to_cpu(a->algorithm) != WLAN_AUTH_OPEN)
+		return  WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG;
+
+	return WLAN_STATUS_SUCCESS;
+}
+
+static short probe_rq_parse(struct ieee80211_device *ieee, struct sk_buff *skb, u8 *src)
+{
+	u8 *tag;
+	u8 *skbend;
+	u8 *ssid=NULL;
+	u8 ssidlen = 0;
+
+	struct ieee80211_hdr_3addr   *header =
+		(struct ieee80211_hdr_3addr   *) skb->data;
+
+	if (skb->len < sizeof (struct ieee80211_hdr_3addr  ))
+		return -1; /* corrupted */
+
+	memcpy(src,header->addr2, ETH_ALEN);
+
+	skbend = (u8*)skb->data + skb->len;
+
+	tag = skb->data + sizeof (struct ieee80211_hdr_3addr  );
+
+	while (tag+1 < skbend){
+		if (*tag == 0){
+			ssid = tag+2;
+			ssidlen = *(tag+1);
+			break;
+		}
+		tag++; /* point to the len field */
+		tag = tag + *(tag); /* point to the last data byte of the tag */
+		tag++; /* point to the next tag */
+	}
+
+	//IEEE80211DMESG("Card MAC address is "MACSTR, MAC2STR(src));
+	if (ssidlen == 0) return 1;
+
+	if (!ssid) return 1; /* ssid not found in tagged param */
+	return (!strncmp(ssid, ieee->current_network.ssid, ssidlen));
+
+}
+
+int assoc_rq_parse(struct sk_buff *skb,u8* dest)
+{
+	struct ieee80211_assoc_request_frame *a;
+
+	if (skb->len < (sizeof(struct ieee80211_assoc_request_frame) -
+		sizeof(struct ieee80211_info_element))) {
+
+		IEEE80211_DEBUG_MGMT("invalid len in auth request:%d \n", skb->len);
+		return -1;
+	}
+
+	a = (struct ieee80211_assoc_request_frame*) skb->data;
+
+	memcpy(dest,a->header.addr2,ETH_ALEN);
+
+	return 0;
+}
+
+static inline u16 assoc_parse(struct ieee80211_device *ieee, struct sk_buff *skb, int *aid)
+{
+	struct ieee80211_assoc_response_frame *response_head;
+	u16 status_code;
+
+	if (skb->len <  sizeof(struct ieee80211_assoc_response_frame)){
+		IEEE80211_DEBUG_MGMT("invalid len in auth resp: %d\n", skb->len);
+		return 0xcafe;
+	}
+
+	response_head = (struct ieee80211_assoc_response_frame*) skb->data;
+	*aid = le16_to_cpu(response_head->aid) & 0x3fff;
+
+	status_code = le16_to_cpu(response_head->status);
+	if((status_code==WLAN_STATUS_ASSOC_DENIED_RATES || \
+	   status_code==WLAN_STATUS_CAPS_UNSUPPORTED)&&
+	   ((ieee->mode == IEEE_G) &&
+	    (ieee->current_network.mode == IEEE_N_24G) &&
+            (ieee->AsocRetryCount++ < (RT_ASOC_RETRY_LIMIT-1)))) {
+                 ieee->pHTInfo->IOTAction |= HT_IOT_ACT_PURE_N_MODE;
+	}else {
+		 ieee->AsocRetryCount = 0;
+	}
+
+	return le16_to_cpu(response_head->status);
+}
+
+static inline void
+ieee80211_rx_probe_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
+{
+	u8 dest[ETH_ALEN];
+
+	//IEEE80211DMESG("Rx probe");
+	ieee->softmac_stats.rx_probe_rq++;
+	//DMESG("Dest is "MACSTR, MAC2STR(dest));
+	if (probe_rq_parse(ieee, skb, dest)){
+		//IEEE80211DMESG("Was for me!");
+		ieee->softmac_stats.tx_probe_rs++;
+		ieee80211_resp_to_probe(ieee, dest);
+	}
+}
+
+static inline void
+ieee80211_rx_auth_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
+{
+	u8 dest[ETH_ALEN];
+	int status;
+	//IEEE80211DMESG("Rx probe");
+	ieee->softmac_stats.rx_auth_rq++;
+
+	if ((status = auth_rq_parse(skb, dest))!= -1){
+		ieee80211_resp_to_auth(ieee, status, dest);
+	}
+	//DMESG("Dest is "MACSTR, MAC2STR(dest));
+
+}
+
+static inline void
+ieee80211_rx_assoc_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
+{
+
+	u8 dest[ETH_ALEN];
+	//unsigned long flags;
+
+	ieee->softmac_stats.rx_ass_rq++;
+	if (assoc_rq_parse(skb,dest) != -1){
+		ieee80211_resp_to_assoc_rq(ieee, dest);
+	}
+
+	printk(KERN_INFO"New client associated: "MAC_FMT"\n", MAC_ARG(dest));
+	//FIXME
+	#if 0
+	spin_lock_irqsave(&ieee->lock,flags);
+	add_associate(ieee,dest);
+	spin_unlock_irqrestore(&ieee->lock,flags);
+	#endif
+}
+
+
+
+void ieee80211_sta_ps_send_null_frame(struct ieee80211_device *ieee, short pwr)
+{
+
+	struct sk_buff *buf = ieee80211_null_func(ieee, pwr);
+
+	if (buf)
+		softmac_ps_mgmt_xmit(buf, ieee);
+
+}
+
+
+short ieee80211_sta_ps_sleep(struct ieee80211_device *ieee, u32 *time_h, u32 *time_l)
+{
+	int timeout = ieee->ps_timeout;
+	u8 dtim;
+	/*if(ieee->ps == IEEE80211_PS_DISABLED ||
+		ieee->iw_mode != IW_MODE_INFRA ||
+		ieee->state != IEEE80211_LINKED)
+
+		return 0;
+	*/
+	dtim = ieee->current_network.dtim_data;
+	//printk("DTIM\n");
+	if(!(dtim & IEEE80211_DTIM_VALID))
+		return 0;
+	timeout = ieee->current_network.beacon_interval; //should we use ps_timeout value or beacon_interval
+	//printk("VALID\n");
+	ieee->current_network.dtim_data = IEEE80211_DTIM_INVALID;
+
+	if(dtim & ((IEEE80211_DTIM_UCAST | IEEE80211_DTIM_MBCAST)& ieee->ps))
+		return 2;
+
+	if(!time_after(jiffies, ieee->dev->trans_start + MSECS(timeout)))
+		return 0;
+
+	if(!time_after(jiffies, ieee->last_rx_ps_time + MSECS(timeout)))
+		return 0;
+
+	if((ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE ) &&
+		(ieee->mgmt_queue_tail != ieee->mgmt_queue_head))
+		return 0;
+
+	if(time_l){
+		*time_l = ieee->current_network.last_dtim_sta_time[0]
+			+ (ieee->current_network.beacon_interval);
+		//	* ieee->current_network.dtim_period) * 1000;
+	}
+
+	if(time_h){
+		*time_h = ieee->current_network.last_dtim_sta_time[1];
+		if(time_l && *time_l < ieee->current_network.last_dtim_sta_time[0])
+			*time_h += 1;
+	}
+
+	return 1;
+
+
+}
+
+inline void ieee80211_sta_ps(struct ieee80211_device *ieee)
+{
+
+	u32 th,tl;
+	short sleep;
+
+	unsigned long flags,flags2;
+
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	if((ieee->ps == IEEE80211_PS_DISABLED ||
+		ieee->iw_mode != IW_MODE_INFRA ||
+		ieee->state != IEEE80211_LINKED)){
+
+	//	#warning CHECK_LOCK_HERE
+		spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
+
+		ieee80211_sta_wakeup(ieee, 1);
+
+		spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
+	}
+
+	sleep = ieee80211_sta_ps_sleep(ieee,&th, &tl);
+	/* 2 wake, 1 sleep, 0 do nothing */
+	if(sleep == 0)
+		goto out;
+
+	if(sleep == 1){
+
+		if(ieee->sta_sleep == 1)
+			ieee->enter_sleep_state(ieee->dev,th,tl);
+
+		else if(ieee->sta_sleep == 0){
+		//	printk("send null 1\n");
+			spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
+
+			if(ieee->ps_is_queue_empty(ieee->dev)){
+
+
+				ieee->sta_sleep = 2;
+
+				ieee->ack_tx_to_ieee = 1;
+
+				ieee80211_sta_ps_send_null_frame(ieee,1);
+
+				ieee->ps_th = th;
+				ieee->ps_tl = tl;
+			}
+			spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
+
+		}
+
+
+	}else if(sleep == 2){
+//#warning CHECK_LOCK_HERE
+		spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
+
+		ieee80211_sta_wakeup(ieee,1);
+
+		spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
+	}
+
+out:
+	spin_unlock_irqrestore(&ieee->lock, flags);
+
+}
+
+void ieee80211_sta_wakeup(struct ieee80211_device *ieee, short nl)
+{
+	if(ieee->sta_sleep == 0){
+		if(nl){
+			printk("Warning: driver is probably failing to report TX ps error\n");
+			ieee->ack_tx_to_ieee = 1;
+			ieee80211_sta_ps_send_null_frame(ieee, 0);
+		}
+		return;
+
+	}
+
+	if(ieee->sta_sleep == 1)
+		ieee->sta_wake_up(ieee->dev);
+
+	ieee->sta_sleep = 0;
+
+	if(nl){
+		ieee->ack_tx_to_ieee = 1;
+		ieee80211_sta_ps_send_null_frame(ieee, 0);
+	}
+}
+
+void ieee80211_ps_tx_ack(struct ieee80211_device *ieee, short success)
+{
+	unsigned long flags,flags2;
+
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	if(ieee->sta_sleep == 2){
+		/* Null frame with PS bit set */
+		if(success){
+			ieee->sta_sleep = 1;
+			ieee->enter_sleep_state(ieee->dev,ieee->ps_th,ieee->ps_tl);
+		}
+		/* if the card report not success we can't be sure the AP
+		 * has not RXed so we can't assume the AP believe us awake
+		 */
+	}
+	/* 21112005 - tx again null without PS bit if lost */
+	else {
+
+		if((ieee->sta_sleep == 0) && !success){
+			spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
+			ieee80211_sta_ps_send_null_frame(ieee, 0);
+			spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
+		}
+	}
+	spin_unlock_irqrestore(&ieee->lock, flags);
+}
+void ieee80211_process_action(struct ieee80211_device* ieee, struct sk_buff* skb)
+{
+	struct ieee80211_hdr* header = (struct ieee80211_hdr*)skb->data;
+	u8* act = ieee80211_get_payload(header);
+	u8 tmp = 0;
+//	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
+	if (act == NULL)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "error to get payload of action frame\n");
+		return;
+	}
+	tmp = *act;
+	act ++;
+	switch (tmp)
+	{
+		case ACT_CAT_BA:
+			if (*act == ACT_ADDBAREQ)
+			ieee80211_rx_ADDBAReq(ieee, skb);
+			else if (*act == ACT_ADDBARSP)
+			ieee80211_rx_ADDBARsp(ieee, skb);
+			else if (*act == ACT_DELBA)
+			ieee80211_rx_DELBA(ieee, skb);
+			break;
+		default:
+//			if (net_ratelimit())
+//			IEEE80211_DEBUG(IEEE80211_DL_BA, "unknown action frame(%d)\n", tmp);
+			break;
+	}
+	return;
+
+}
+inline int
+ieee80211_rx_frame_softmac(struct ieee80211_device *ieee, struct sk_buff *skb,
+			struct ieee80211_rx_stats *rx_stats, u16 type,
+			u16 stype)
+{
+	struct ieee80211_hdr_3addr *header = (struct ieee80211_hdr_3addr *) skb->data;
+	u16 errcode;
+	u8* challenge;
+	int chlen=0;
+	int aid;
+	struct ieee80211_assoc_response_frame *assoc_resp;
+//	struct ieee80211_info_element *info_element;
+	bool bSupportNmode = true, bHalfSupportNmode = false; //default support N mode, disable halfNmode
+
+	if(!ieee->proto_started)
+		return 0;
+#if 0
+	printk("%d, %d, %d, %d\n", ieee->sta_sleep, ieee->ps, ieee->iw_mode, ieee->state);
+	if(ieee->sta_sleep || (ieee->ps != IEEE80211_PS_DISABLED &&
+		ieee->iw_mode == IW_MODE_INFRA &&
+		ieee->state == IEEE80211_LINKED))
+
+		tasklet_schedule(&ieee->ps_task);
+
+	if(WLAN_FC_GET_STYPE(header->frame_ctl) != IEEE80211_STYPE_PROBE_RESP &&
+		WLAN_FC_GET_STYPE(header->frame_ctl) != IEEE80211_STYPE_BEACON)
+		ieee->last_rx_ps_time = jiffies;
+#endif
+
+	switch (WLAN_FC_GET_STYPE(header->frame_ctl)) {
+
+		case IEEE80211_STYPE_ASSOC_RESP:
+		case IEEE80211_STYPE_REASSOC_RESP:
+
+			IEEE80211_DEBUG_MGMT("received [RE]ASSOCIATION RESPONSE (%d)\n",
+					WLAN_FC_GET_STYPE(header->frame_ctl));
+			if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
+				ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATED &&
+				ieee->iw_mode == IW_MODE_INFRA){
+				struct ieee80211_network network_resp;
+				struct ieee80211_network *network = &network_resp;
+
+				if (0 == (errcode=assoc_parse(ieee,skb, &aid))){
+					ieee->state=IEEE80211_LINKED;
+					ieee->assoc_id = aid;
+					ieee->softmac_stats.rx_ass_ok++;
+					/* station support qos */
+					/* Let the register setting defaultly with Legacy station */
+					if(ieee->qos_support) {
+						assoc_resp = (struct ieee80211_assoc_response_frame*)skb->data;
+						memset(network, 0, sizeof(*network));
+						if (ieee80211_parse_info_param(ieee,assoc_resp->info_element,\
+									rx_stats->len - sizeof(*assoc_resp),\
+									network,rx_stats)){
+							return 1;
+						}
+						else
+						{	//filling the PeerHTCap. //maybe not neccesary as we can get its info from current_network.
+							memcpy(ieee->pHTInfo->PeerHTCapBuf, network->bssht.bdHTCapBuf, network->bssht.bdHTCapLen);
+							memcpy(ieee->pHTInfo->PeerHTInfoBuf, network->bssht.bdHTInfoBuf, network->bssht.bdHTInfoLen);
+						}
+						if (ieee->handle_assoc_response != NULL)
+							ieee->handle_assoc_response(ieee->dev, (struct ieee80211_assoc_response_frame*)header, network);
+					}
+					ieee80211_associate_complete(ieee);
+				} else {
+					/* aid could not been allocated */
+					ieee->softmac_stats.rx_ass_err++;
+					printk(
+						"Association response status code 0x%x\n",
+						errcode);
+					IEEE80211_DEBUG_MGMT(
+						"Association response status code 0x%x\n",
+						errcode);
+					if(ieee->AsocRetryCount < RT_ASOC_RETRY_LIMIT) {
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+						queue_work(ieee->wq, &ieee->associate_procedure_wq);
+#else
+						schedule_task(&ieee->associate_procedure_wq);
+#endif
+					} else {
+						ieee80211_associate_abort(ieee);
+					}
+				}
+			}
+			break;
+
+		case IEEE80211_STYPE_ASSOC_REQ:
+		case IEEE80211_STYPE_REASSOC_REQ:
+
+			if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
+				ieee->iw_mode == IW_MODE_MASTER)
+
+				ieee80211_rx_assoc_rq(ieee, skb);
+			break;
+
+		case IEEE80211_STYPE_AUTH:
+
+			if (ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE){
+				if (ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATING &&
+				ieee->iw_mode == IW_MODE_INFRA){
+
+						IEEE80211_DEBUG_MGMT("Received authentication response");
+
+						if (0 == (errcode=auth_parse(skb, &challenge, &chlen))){
+							if(ieee->open_wep || !challenge){
+								ieee->state = IEEE80211_ASSOCIATING_AUTHENTICATED;
+								ieee->softmac_stats.rx_auth_rs_ok++;
+								if(!(ieee->pHTInfo->IOTAction&HT_IOT_ACT_PURE_N_MODE))
+								{
+									if (!ieee->GetNmodeSupportBySecCfg(ieee->dev))
+									{
+												// WEP or TKIP encryption
+										if(IsHTHalfNmodeAPs(ieee))
+										{
+											bSupportNmode = true;
+											bHalfSupportNmode = true;
+										}
+										else
+										{
+											bSupportNmode = false;
+											bHalfSupportNmode = false;
+										}
+									printk("==========>to link with AP using SEC(%d, %d)", bSupportNmode, bHalfSupportNmode);
+									}
+								}
+								/* Dummy wirless mode setting to avoid encryption issue */
+								if(bSupportNmode) {
+									//N mode setting
+									ieee->SetWirelessMode(ieee->dev, \
+											ieee->current_network.mode);
+								}else{
+									//b/g mode setting
+									/*TODO*/
+									ieee->SetWirelessMode(ieee->dev, IEEE_G);
+								}
+
+								if (ieee->current_network.mode == IEEE_N_24G && bHalfSupportNmode == true)
+								{
+									printk("===============>entern half N mode\n");
+									ieee->bHalfWirelessN24GMode = true;
+								}
+								else
+									ieee->bHalfWirelessN24GMode = false;
+
+								ieee80211_associate_step2(ieee);
+							}else{
+								ieee80211_auth_challenge(ieee, challenge, chlen);
+							}
+						}else{
+							ieee->softmac_stats.rx_auth_rs_err++;
+							IEEE80211_DEBUG_MGMT("Authentication respose status code 0x%x",errcode);
+
+							printk("Authentication respose status code 0x%x",errcode);
+							ieee80211_associate_abort(ieee);
+						}
+
+					}else if (ieee->iw_mode == IW_MODE_MASTER){
+						ieee80211_rx_auth_rq(ieee, skb);
+					}
+				}
+			break;
+
+		case IEEE80211_STYPE_PROBE_REQ:
+
+			if ((ieee->softmac_features & IEEE_SOFTMAC_PROBERS) &&
+				((ieee->iw_mode == IW_MODE_ADHOC ||
+				ieee->iw_mode == IW_MODE_MASTER) &&
+				ieee->state == IEEE80211_LINKED)){
+				ieee80211_rx_probe_rq(ieee, skb);
+			}
+			break;
+
+		case IEEE80211_STYPE_DISASSOC:
+		case IEEE80211_STYPE_DEAUTH:
+			/* FIXME for now repeat all the association procedure
+			* both for disassociation and deauthentication
+			*/
+			if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
+				ieee->state == IEEE80211_LINKED &&
+				ieee->iw_mode == IW_MODE_INFRA){
+				printk("==========>received disassoc/deauth(%x) frame, reason code:%x\n",WLAN_FC_GET_STYPE(header->frame_ctl), ((struct ieee80211_disassoc*)skb->data)->reason);
+				ieee->state = IEEE80211_ASSOCIATING;
+				ieee->softmac_stats.reassoc++;
+				ieee->is_roaming = true;
+				ieee80211_disassociate(ieee);
+			//	notify_wx_assoc_event(ieee);
+				//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
+				RemovePeerTS(ieee, header->addr2);
+				if(ieee->LedControlHandler != NULL)
+				        ieee->LedControlHandler(ieee->dev, LED_CTL_START_TO_LINK); //added by amy for LED 090318
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+				queue_work(ieee->wq, &ieee->associate_procedure_wq);
+#else
+				schedule_task(&ieee->associate_procedure_wq);
+#endif
+			}
+			break;
+		case IEEE80211_STYPE_MANAGE_ACT:
+			ieee80211_process_action(ieee,skb);
+			break;
+		default:
+			return -1;
+			break;
+	}
+
+	//dev_kfree_skb_any(skb);
+	return 0;
+}
+
+/* following are for a simplier TX queue management.
+ * Instead of using netif_[stop/wake]_queue the driver
+ * will uses these two function (plus a reset one), that
+ * will internally uses the kernel netif_* and takes
+ * care of the ieee802.11 fragmentation.
+ * So the driver receives a fragment per time and might
+ * call the stop function when it want without take care
+ * to have enought room to TX an entire packet.
+ * This might be useful if each fragment need it's own
+ * descriptor, thus just keep a total free memory > than
+ * the max fragmentation treshold is not enought.. If the
+ * ieee802.11 stack passed a TXB struct then you needed
+ * to keep N free descriptors where
+ * N = MAX_PACKET_SIZE / MIN_FRAG_TRESHOLD
+ * In this way you need just one and the 802.11 stack
+ * will take care of buffering fragments and pass them to
+ * to the driver later, when it wakes the queue.
+ */
+void ieee80211_softmac_xmit(struct ieee80211_txb *txb, struct ieee80211_device *ieee)
+{
+
+	unsigned int queue_index = txb->queue_index;
+	unsigned long flags;
+	int  i;
+	cb_desc *tcb_desc = NULL;
+
+	spin_lock_irqsave(&ieee->lock,flags);
+
+	/* called with 2nd parm 0, no tx mgmt lock required */
+	ieee80211_sta_wakeup(ieee,0);
+
+	/* update the tx status */
+//	ieee->stats.tx_bytes += txb->payload_size;
+//	ieee->stats.tx_packets++;
+	tcb_desc = (cb_desc *)(txb->fragments[0]->cb + MAX_DEV_ADDR_SIZE);
+	if(tcb_desc->bMulticast) {
+		ieee->stats.multicast++;
+	}
+#if 1
+	/* if xmit available, just xmit it immediately, else just insert it to the wait queue */
+	for(i = 0; i < txb->nr_frags; i++) {
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+		if ((skb_queue_len(&ieee->skb_drv_aggQ[queue_index]) != 0) ||
+#else
+		if ((skb_queue_len(&ieee->skb_waitQ[queue_index]) != 0) ||
+#endif
+		(!ieee->check_nic_enough_desc(ieee->dev,queue_index))||\
+		     (ieee->queue_stop)) {
+			/* insert the skb packet to the wait queue */
+			/* as for the completion function, it does not need
+			 * to check it any more.
+			 * */
+			//printk("error:no descriptor left@queue_index %d, %d, %d\n", queue_index, skb_queue_len(&ieee->skb_waitQ[queue_index]), ieee->check_nic_enough_desc(ieee->dev,queue_index));
+			//ieee80211_stop_queue(ieee);
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+			skb_queue_tail(&ieee->skb_drv_aggQ[queue_index], txb->fragments[i]);
+#else
+			skb_queue_tail(&ieee->skb_waitQ[queue_index], txb->fragments[i]);
+#endif
+		}else{
+			ieee->softmac_data_hard_start_xmit(
+					txb->fragments[i],
+					ieee->dev,ieee->rate);
+			//ieee->stats.tx_packets++;
+			//ieee->stats.tx_bytes += txb->fragments[i]->len;
+			//ieee->dev->trans_start = jiffies;
+		}
+	}
+#endif
+	ieee80211_txb_free(txb);
+
+//exit:
+	spin_unlock_irqrestore(&ieee->lock,flags);
+
+}
+
+/* called with ieee->lock acquired */
+void ieee80211_resume_tx(struct ieee80211_device *ieee)
+{
+	int i;
+	for(i = ieee->tx_pending.frag; i < ieee->tx_pending.txb->nr_frags; i++) {
+
+		if (ieee->queue_stop){
+			ieee->tx_pending.frag = i;
+			return;
+		}else{
+
+			ieee->softmac_data_hard_start_xmit(
+				ieee->tx_pending.txb->fragments[i],
+				ieee->dev,ieee->rate);
+				//(i+1)<ieee->tx_pending.txb->nr_frags);
+			ieee->stats.tx_packets++;
+		//	ieee->dev->trans_start = jiffies;
+		}
+	}
+
+
+	ieee80211_txb_free(ieee->tx_pending.txb);
+	ieee->tx_pending.txb = NULL;
+}
+
+
+void ieee80211_reset_queue(struct ieee80211_device *ieee)
+{
+	unsigned long flags;
+
+	spin_lock_irqsave(&ieee->lock,flags);
+	init_mgmt_queue(ieee);
+	if (ieee->tx_pending.txb){
+		ieee80211_txb_free(ieee->tx_pending.txb);
+		ieee->tx_pending.txb = NULL;
+	}
+	ieee->queue_stop = 0;
+	spin_unlock_irqrestore(&ieee->lock,flags);
+
+}
+
+void ieee80211_wake_queue(struct ieee80211_device *ieee)
+{
+
+	unsigned long flags;
+	struct sk_buff *skb;
+	struct ieee80211_hdr_3addr  *header;
+
+	spin_lock_irqsave(&ieee->lock,flags);
+	if (! ieee->queue_stop) goto exit;
+
+	ieee->queue_stop = 0;
+
+	if(ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE){
+		while (!ieee->queue_stop && (skb = dequeue_mgmt(ieee))){
+
+			header = (struct ieee80211_hdr_3addr  *) skb->data;
+
+			header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
+
+			if (ieee->seq_ctrl[0] == 0xFFF)
+				ieee->seq_ctrl[0] = 0;
+			else
+				ieee->seq_ctrl[0]++;
+
+			ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
+			//dev_kfree_skb_any(skb);//edit by thomas
+		}
+	}
+	if (!ieee->queue_stop && ieee->tx_pending.txb)
+		ieee80211_resume_tx(ieee);
+
+	if (!ieee->queue_stop && netif_queue_stopped(ieee->dev)){
+		ieee->softmac_stats.swtxawake++;
+		netif_wake_queue(ieee->dev);
+	}
+
+exit :
+	spin_unlock_irqrestore(&ieee->lock,flags);
+}
+
+
+void ieee80211_stop_queue(struct ieee80211_device *ieee)
+{
+	//unsigned long flags;
+	//spin_lock_irqsave(&ieee->lock,flags);
+
+	if (! netif_queue_stopped(ieee->dev)){
+		netif_stop_queue(ieee->dev);
+		ieee->softmac_stats.swtxstop++;
+	}
+	ieee->queue_stop = 1;
+	//spin_unlock_irqrestore(&ieee->lock,flags);
+
+}
+
+
+inline void ieee80211_randomize_cell(struct ieee80211_device *ieee)
+{
+
+	get_random_bytes(ieee->current_network.bssid, ETH_ALEN);
+
+	/* an IBSS cell address must have the two less significant
+	 * bits of the first byte = 2
+	 */
+	ieee->current_network.bssid[0] &= ~0x01;
+	ieee->current_network.bssid[0] |= 0x02;
+}
+
+/* called in user context only */
+void ieee80211_start_master_bss(struct ieee80211_device *ieee)
+{
+	ieee->assoc_id = 1;
+
+	if (ieee->current_network.ssid_len == 0){
+		strncpy(ieee->current_network.ssid,
+			IEEE80211_DEFAULT_TX_ESSID,
+			IW_ESSID_MAX_SIZE);
+
+		ieee->current_network.ssid_len = strlen(IEEE80211_DEFAULT_TX_ESSID);
+		ieee->ssid_set = 1;
+	}
+
+	memcpy(ieee->current_network.bssid, ieee->dev->dev_addr, ETH_ALEN);
+
+	ieee->set_chan(ieee->dev, ieee->current_network.channel);
+	ieee->state = IEEE80211_LINKED;
+	ieee->link_change(ieee->dev);
+	notify_wx_assoc_event(ieee);
+
+	if (ieee->data_hard_resume)
+		ieee->data_hard_resume(ieee->dev);
+
+	netif_carrier_on(ieee->dev);
+}
+
+void ieee80211_start_monitor_mode(struct ieee80211_device *ieee)
+{
+	if(ieee->raw_tx){
+
+		if (ieee->data_hard_resume)
+			ieee->data_hard_resume(ieee->dev);
+
+		netif_carrier_on(ieee->dev);
+	}
+}
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+void ieee80211_start_ibss_wq(struct work_struct *work)
+{
+
+        struct delayed_work *dwork = container_of(work, struct delayed_work, work);
+        struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, start_ibss_wq);
+#else
+void ieee80211_start_ibss_wq(struct ieee80211_device *ieee)
+{
+#endif
+	/* iwconfig mode ad-hoc will schedule this and return
+	 * on the other hand this will block further iwconfig SET
+	 * operations because of the wx_sem hold.
+	 * Anyway some most set operations set a flag to speed-up
+	 * (abort) this wq (when syncro scanning) before sleeping
+	 * on the semaphore
+	 */
+	if(!ieee->proto_started){
+		printk("==========oh driver down return\n");
+		return;
+	}
+	down(&ieee->wx_sem);
+	//FIXME:set back to 20M whenever HT for ibss is not ready. Otherwise,after being connected to 40M AP, it will still stay in 40M when set to ibss mode. WB 2009.02.04
+	HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
+
+	if (ieee->current_network.ssid_len == 0){
+		strcpy(ieee->current_network.ssid,IEEE80211_DEFAULT_TX_ESSID);
+		ieee->current_network.ssid_len = strlen(IEEE80211_DEFAULT_TX_ESSID);
+		ieee->ssid_set = 1;
+	}
+
+	/* check if we have this cell in our network list */
+	ieee80211_softmac_check_all_nets(ieee);
+
+
+#ifdef ENABLE_DOT11D //if creating an ad-hoc, set its channel to 10 temporarily--this is the requirement for ASUS, not 11D, so disable 11d.
+//	if((IS_DOT11D_ENABLE(ieee)) && (ieee->state == IEEE80211_NOLINK))
+	if (ieee->state == IEEE80211_NOLINK)
+		ieee->current_network.channel = 6;
+#endif
+	/* if not then the state is not linked. Maybe the user swithced to
+	 * ad-hoc mode just after being in monitor mode, or just after
+	 * being very few time in managed mode (so the card have had no
+	 * time to scan all the chans..) or we have just run up the iface
+	 * after setting ad-hoc mode. So we have to give another try..
+	 * Here, in ibss mode, should be safe to do this without extra care
+	 * (in bss mode we had to make sure no-one tryed to associate when
+	 * we had just checked the ieee->state and we was going to start the
+	 * scan) beacause in ibss mode the ieee80211_new_net function, when
+	 * finds a good net, just set the ieee->state to IEEE80211_LINKED,
+	 * so, at worst, we waste a bit of time to initiate an unneeded syncro
+	 * scan, that will stop at the first round because it sees the state
+	 * associated.
+	 */
+	if (ieee->state == IEEE80211_NOLINK)
+		ieee80211_start_scan_syncro(ieee);
+
+	/* the network definitively is not here.. create a new cell */
+	if (ieee->state == IEEE80211_NOLINK){
+		printk("creating new IBSS cell\n");
+		if(!ieee->wap_set)
+			ieee80211_randomize_cell(ieee);
+
+		if(ieee->modulation & IEEE80211_CCK_MODULATION){
+
+			ieee->current_network.rates_len = 4;
+
+			ieee->current_network.rates[0] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_1MB;
+			ieee->current_network.rates[1] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_2MB;
+			ieee->current_network.rates[2] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_5MB;
+			ieee->current_network.rates[3] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_11MB;
+
+		}else
+			ieee->current_network.rates_len = 0;
+
+		if(ieee->modulation & IEEE80211_OFDM_MODULATION){
+			ieee->current_network.rates_ex_len = 8;
+
+			ieee->current_network.rates_ex[0] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_6MB;
+			ieee->current_network.rates_ex[1] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_9MB;
+			ieee->current_network.rates_ex[2] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_12MB;
+			ieee->current_network.rates_ex[3] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_18MB;
+			ieee->current_network.rates_ex[4] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_24MB;
+			ieee->current_network.rates_ex[5] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_36MB;
+			ieee->current_network.rates_ex[6] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_48MB;
+			ieee->current_network.rates_ex[7] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_54MB;
+
+			ieee->rate = 108;
+		}else{
+			ieee->current_network.rates_ex_len = 0;
+			ieee->rate = 22;
+		}
+
+		// By default, WMM function will be disabled in IBSS mode
+		ieee->current_network.QoS_Enable = 0;
+		ieee->SetWirelessMode(ieee->dev, IEEE_G);
+		ieee->current_network.atim_window = 0;
+		ieee->current_network.capability = WLAN_CAPABILITY_IBSS;
+		if(ieee->short_slot)
+			ieee->current_network.capability |= WLAN_CAPABILITY_SHORT_SLOT;
+
+	}
+
+	ieee->state = IEEE80211_LINKED;
+
+	ieee->set_chan(ieee->dev, ieee->current_network.channel);
+	ieee->link_change(ieee->dev);
+	if(ieee->LedControlHandler != NULL)
+	        ieee->LedControlHandler(ieee->dev,LED_CTL_LINK);
+	notify_wx_assoc_event(ieee);
+
+	ieee80211_start_send_beacons(ieee);
+
+	if (ieee->data_hard_resume)
+		ieee->data_hard_resume(ieee->dev);
+	netif_carrier_on(ieee->dev);
+
+	up(&ieee->wx_sem);
+}
+
+inline void ieee80211_start_ibss(struct ieee80211_device *ieee)
+{
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	queue_delayed_work(ieee->wq, &ieee->start_ibss_wq, 150);
+#else
+	schedule_task(&ieee->start_ibss_wq);
+#endif
+}
+
+/* this is called only in user context, with wx_sem held */
+void ieee80211_start_bss(struct ieee80211_device *ieee)
+{
+	unsigned long flags;
+#ifdef ENABLE_DOT11D
+	//
+	// Ref: 802.11d 11.1.3.3
+	// STA shall not start a BSS unless properly formed Beacon frame including a Country IE.
+	//
+	if(IS_DOT11D_ENABLE(ieee) && !IS_COUNTRY_IE_VALID(ieee))
+	{
+		if(! ieee->bGlobalDomain)
+		{
+			return;
+		}
+	}
+#endif
+	/* check if we have already found the net we
+	 * are interested in (if any).
+	 * if not (we are disassociated and we are not
+	 * in associating / authenticating phase) start the background scanning.
+	 */
+	ieee80211_softmac_check_all_nets(ieee);
+
+	/* ensure no-one start an associating process (thus setting
+	 * the ieee->state to ieee80211_ASSOCIATING) while we
+	 * have just cheked it and we are going to enable scan.
+	 * The ieee80211_new_net function is always called with
+	 * lock held (from both ieee80211_softmac_check_all_nets and
+	 * the rx path), so we cannot be in the middle of such function
+	 */
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	if (ieee->state == IEEE80211_NOLINK){
+		ieee->actscanning = true;
+		ieee80211_start_scan(ieee);
+	}
+	spin_unlock_irqrestore(&ieee->lock, flags);
+}
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+void ieee80211_link_change_wq(struct work_struct *work)
+{
+        struct delayed_work *dwork = container_of(work, struct delayed_work, work);
+        struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, link_change_wq);
+#else
+void ieee80211_link_change_wq(struct ieee80211_device *ieee)
+{
+#endif
+	ieee->link_change(ieee->dev);
+}
+/* called only in userspace context */
+void ieee80211_disassociate(struct ieee80211_device *ieee)
+{
+
+
+	netif_carrier_off(ieee->dev);
+	if (ieee->softmac_features & IEEE_SOFTMAC_TX_QUEUE)
+			ieee80211_reset_queue(ieee);
+
+	if (ieee->data_hard_stop)
+			ieee->data_hard_stop(ieee->dev);
+#ifdef ENABLE_DOT11D
+	if(IS_DOT11D_ENABLE(ieee))
+		Dot11d_Reset(ieee);
+#endif
+	ieee->state = IEEE80211_NOLINK;
+	ieee->is_set_key = false;
+
+	//LZM for usb dev crash.
+	//ieee->link_change(ieee->dev);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	queue_delayed_work(ieee->wq, &ieee->link_change_wq, 0);
+#else
+	schedule_task(&ieee->link_change_wq);
+#endif
+
+	//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
+	notify_wx_assoc_event(ieee);
+
+}
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+void ieee80211_associate_retry_wq(struct work_struct *work)
+{
+        struct delayed_work *dwork = container_of(work, struct delayed_work, work);
+        struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, associate_retry_wq);
+#else
+void ieee80211_associate_retry_wq(struct ieee80211_device *ieee)
+{
+#endif
+	unsigned long flags;
+
+	down(&ieee->wx_sem);
+	if(!ieee->proto_started)
+		goto exit;
+
+	if(ieee->state != IEEE80211_ASSOCIATING_RETRY)
+		goto exit;
+
+	/* until we do not set the state to IEEE80211_NOLINK
+	* there are no possibility to have someone else trying
+	* to start an association procdure (we get here with
+	* ieee->state = IEEE80211_ASSOCIATING).
+	* When we set the state to IEEE80211_NOLINK it is possible
+	* that the RX path run an attempt to associate, but
+	* both ieee80211_softmac_check_all_nets and the
+	* RX path works with ieee->lock held so there are no
+	* problems. If we are still disassociated then start a scan.
+	* the lock here is necessary to ensure no one try to start
+	* an association procedure when we have just checked the
+	* state and we are going to start the scan.
+	*/
+	ieee->beinretry = true;
+	ieee->state = IEEE80211_NOLINK;
+
+	ieee80211_softmac_check_all_nets(ieee);
+
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	if(ieee->state == IEEE80211_NOLINK)
+	{
+		ieee->actscanning = true;
+		ieee80211_start_scan(ieee);
+	}
+	spin_unlock_irqrestore(&ieee->lock, flags);
+
+	ieee->beinretry = false;
+exit:
+	up(&ieee->wx_sem);
+}
+
+struct sk_buff *ieee80211_get_beacon_(struct ieee80211_device *ieee)
+{
+	u8 broadcast_addr[] = {0xff,0xff,0xff,0xff,0xff,0xff};
+
+	struct sk_buff *skb;
+	struct ieee80211_probe_response *b;
+
+	skb = ieee80211_probe_resp(ieee, broadcast_addr);
+
+	if (!skb)
+		return NULL;
+
+	b = (struct ieee80211_probe_response *) skb->data;
+	b->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_BEACON);
+
+	return skb;
+
+}
+
+struct sk_buff *ieee80211_get_beacon(struct ieee80211_device *ieee)
+{
+	struct sk_buff *skb;
+	struct ieee80211_probe_response *b;
+
+	skb = ieee80211_get_beacon_(ieee);
+	if(!skb)
+		return NULL;
+
+	b = (struct ieee80211_probe_response *) skb->data;
+	b->header.seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
+
+	if (ieee->seq_ctrl[0] == 0xFFF)
+		ieee->seq_ctrl[0] = 0;
+	else
+		ieee->seq_ctrl[0]++;
+
+	return skb;
+}
+
+void ieee80211_softmac_stop_protocol(struct ieee80211_device *ieee)
+{
+	ieee->sync_scan_hurryup = 1;
+	down(&ieee->wx_sem);
+	ieee80211_stop_protocol(ieee);
+	up(&ieee->wx_sem);
+}
+
+
+void ieee80211_stop_protocol(struct ieee80211_device *ieee)
+{
+	if (!ieee->proto_started)
+		return;
+
+	ieee->proto_started = 0;
+
+	ieee80211_stop_send_beacons(ieee);
+	del_timer_sync(&ieee->associate_timer);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	cancel_delayed_work(&ieee->associate_retry_wq);
+	cancel_delayed_work(&ieee->start_ibss_wq);
+	cancel_delayed_work(&ieee->link_change_wq);
+#endif
+	ieee80211_stop_scan(ieee);
+
+	ieee80211_disassociate(ieee);
+	RemoveAllTS(ieee); //added as we disconnect from the previous BSS, Remove all TS
+}
+
+void ieee80211_softmac_start_protocol(struct ieee80211_device *ieee)
+{
+	ieee->sync_scan_hurryup = 0;
+	down(&ieee->wx_sem);
+	ieee80211_start_protocol(ieee);
+	up(&ieee->wx_sem);
+}
+
+void ieee80211_start_protocol(struct ieee80211_device *ieee)
+{
+	short ch = 0;
+ 	int i = 0;
+	if (ieee->proto_started)
+		return;
+
+	ieee->proto_started = 1;
+
+	if (ieee->current_network.channel == 0){
+		do{
+			ch++;
+			if (ch > MAX_CHANNEL_NUMBER)
+				return; /* no channel found */
+#ifdef ENABLE_DOT11D
+		}while(!GET_DOT11D_INFO(ieee)->channel_map[ch]);
+#else
+		}while(!ieee->channel_map[ch]);
+#endif
+		ieee->current_network.channel = ch;
+	}
+
+	if (ieee->current_network.beacon_interval == 0)
+		ieee->current_network.beacon_interval = 100;
+//	printk("===>%s(), chan:%d\n", __FUNCTION__, ieee->current_network.channel);
+//	ieee->set_chan(ieee->dev,ieee->current_network.channel);
+
+       	for(i = 0; i < 17; i++) {
+	  ieee->last_rxseq_num[i] = -1;
+	  ieee->last_rxfrag_num[i] = -1;
+	  ieee->last_packet_time[i] = 0;
+	}
+
+	ieee->init_wmmparam_flag = 0;//reinitialize AC_xx_PARAM registers.
+
+
+	/* if the user set the MAC of the ad-hoc cell and then
+	 * switch to managed mode, shall we  make sure that association
+	 * attempts does not fail just because the user provide the essid
+	 * and the nic is still checking for the AP MAC ??
+	 */
+	if (ieee->iw_mode == IW_MODE_INFRA)
+		ieee80211_start_bss(ieee);
+
+	else if (ieee->iw_mode == IW_MODE_ADHOC)
+		ieee80211_start_ibss(ieee);
+
+	else if (ieee->iw_mode == IW_MODE_MASTER)
+		ieee80211_start_master_bss(ieee);
+
+	else if(ieee->iw_mode == IW_MODE_MONITOR)
+		ieee80211_start_monitor_mode(ieee);
+}
+
+
+#define DRV_NAME  "Ieee80211"
+void ieee80211_softmac_init(struct ieee80211_device *ieee)
+{
+	int i;
+	memset(&ieee->current_network, 0, sizeof(struct ieee80211_network));
+
+	ieee->state = IEEE80211_NOLINK;
+	ieee->sync_scan_hurryup = 0;
+	for(i = 0; i < 5; i++) {
+	  ieee->seq_ctrl[i] = 0;
+	}
+#ifdef ENABLE_DOT11D
+	ieee->pDot11dInfo = kmalloc(sizeof(RT_DOT11D_INFO), GFP_ATOMIC);
+	if (!ieee->pDot11dInfo)
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't alloc memory for DOT11D\n");
+	memset(ieee->pDot11dInfo, 0, sizeof(RT_DOT11D_INFO));
+#endif
+	//added for  AP roaming
+	ieee->LinkDetectInfo.SlotNum = 2;
+	ieee->LinkDetectInfo.NumRecvBcnInPeriod=0;
+        ieee->LinkDetectInfo.NumRecvDataInPeriod=0;
+
+	ieee->assoc_id = 0;
+	ieee->queue_stop = 0;
+	ieee->scanning = 0;
+	ieee->softmac_features = 0; //so IEEE2100-like driver are happy
+	ieee->wap_set = 0;
+	ieee->ssid_set = 0;
+	ieee->proto_started = 0;
+	ieee->basic_rate = IEEE80211_DEFAULT_BASIC_RATE;
+	ieee->rate = 22;
+	ieee->ps = IEEE80211_PS_DISABLED;
+	ieee->sta_sleep = 0;
+	ieee->Regdot11HTOperationalRateSet[0]= 0xff;//support MCS 0~7
+	ieee->Regdot11HTOperationalRateSet[1]= 0xff;//support MCS 8~15
+	ieee->Regdot11HTOperationalRateSet[4]= 0x01;
+	//added by amy
+	ieee->actscanning = false;
+	ieee->beinretry = false;
+	ieee->is_set_key = false;
+	init_mgmt_queue(ieee);
+
+	ieee->sta_edca_param[0] = 0x0000A403;
+	ieee->sta_edca_param[1] = 0x0000A427;
+	ieee->sta_edca_param[2] = 0x005E4342;
+	ieee->sta_edca_param[3] = 0x002F3262;
+	ieee->aggregation = true;
+	ieee->enable_rx_imm_BA = 1;
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+	init_timer(&ieee->scan_timer);
+	ieee->scan_timer.data = (unsigned long)ieee;
+	ieee->scan_timer.function = ieee80211_softmac_scan_cb;
+#endif
+	ieee->tx_pending.txb = NULL;
+
+	init_timer(&ieee->associate_timer);
+	ieee->associate_timer.data = (unsigned long)ieee;
+	ieee->associate_timer.function = ieee80211_associate_abort_cb;
+
+	init_timer(&ieee->beacon_timer);
+	ieee->beacon_timer.data = (unsigned long) ieee;
+	ieee->beacon_timer.function = ieee80211_send_beacon_cb;
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+#ifdef PF_SYNCTHREAD
+	ieee->wq = create_workqueue(DRV_NAME,0);
+#else
+	ieee->wq = create_workqueue(DRV_NAME);
+#endif
+#endif
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+        INIT_DELAYED_WORK(&ieee->link_change_wq,ieee80211_link_change_wq);
+        INIT_DELAYED_WORK(&ieee->start_ibss_wq,ieee80211_start_ibss_wq);
+        INIT_WORK(&ieee->associate_complete_wq, ieee80211_associate_complete_wq);
+        INIT_WORK(&ieee->associate_procedure_wq, ieee80211_associate_procedure_wq);
+        INIT_DELAYED_WORK(&ieee->softmac_scan_wq,ieee80211_softmac_scan_wq);
+        INIT_DELAYED_WORK(&ieee->associate_retry_wq, ieee80211_associate_retry_wq);
+        INIT_WORK(&ieee->wx_sync_scan_wq,ieee80211_wx_sync_scan_wq);
+
+#else
+	INIT_WORK(&ieee->link_change_wq,(void(*)(void*)) ieee80211_link_change_wq,ieee);
+	INIT_WORK(&ieee->start_ibss_wq,(void(*)(void*)) ieee80211_start_ibss_wq,ieee);
+	INIT_WORK(&ieee->associate_retry_wq,(void(*)(void*)) ieee80211_associate_retry_wq,ieee);
+	INIT_WORK(&ieee->associate_complete_wq,(void(*)(void*)) ieee80211_associate_complete_wq,ieee);
+	INIT_WORK(&ieee->associate_procedure_wq,(void(*)(void*)) ieee80211_associate_procedure_wq,ieee);
+	INIT_WORK(&ieee->softmac_scan_wq,(void(*)(void*)) ieee80211_softmac_scan_wq,ieee);
+	INIT_WORK(&ieee->wx_sync_scan_wq,(void(*)(void*)) ieee80211_wx_sync_scan_wq,ieee);
+#endif
+
+#else
+	tq_init(&ieee->link_change_wq,(void(*)(void*)) ieee80211_link_change_wq,ieee);
+	tq_init(&ieee->start_ibss_wq,(void(*)(void*)) ieee80211_start_ibss_wq,ieee);
+	tq_init(&ieee->associate_retry_wq,(void(*)(void*)) ieee80211_associate_retry_wq,ieee);
+	tq_init(&ieee->associate_complete_wq,(void(*)(void*)) ieee80211_associate_complete_wq,ieee);
+	tq_init(&ieee->associate_procedure_wq,(void(*)(void*)) ieee80211_associate_procedure_wq,ieee);
+	tq_init(&ieee->softmac_scan_wq,(void(*)(void*)) ieee80211_softmac_scan_wq,ieee);
+	tq_init(&ieee->wx_sync_scan_wq,(void(*)(void*)) ieee80211_wx_sync_scan_wq,ieee);
+#endif
+	sema_init(&ieee->wx_sem, 1);
+	sema_init(&ieee->scan_sem, 1);
+
+	spin_lock_init(&ieee->mgmt_tx_lock);
+	spin_lock_init(&ieee->beacon_lock);
+
+	tasklet_init(&ieee->ps_task,
+	     (void(*)(unsigned long)) ieee80211_sta_ps,
+	     (unsigned long)ieee);
+
+}
+
+void ieee80211_softmac_free(struct ieee80211_device *ieee)
+{
+	down(&ieee->wx_sem);
+#ifdef ENABLE_DOT11D
+	if(NULL != ieee->pDot11dInfo)
+	{
+		kfree(ieee->pDot11dInfo);
+		ieee->pDot11dInfo = NULL;
+	}
+#endif
+	del_timer_sync(&ieee->associate_timer);
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	cancel_delayed_work(&ieee->associate_retry_wq);
+	destroy_workqueue(ieee->wq);
+#endif
+
+	up(&ieee->wx_sem);
+}
+
+/********************************************************
+ * Start of WPA code.                                   *
+ * this is stolen from the ipw2200 driver               *
+ ********************************************************/
+
+
+static int ieee80211_wpa_enable(struct ieee80211_device *ieee, int value)
+{
+	/* This is called when wpa_supplicant loads and closes the driver
+	 * interface. */
+	printk("%s WPA\n",value ? "enabling" : "disabling");
+	ieee->wpa_enabled = value;
+	memset(ieee->ap_mac_addr, 0, 6); //reset ap_mac_addr everytime it starts wpa.
+	return 0;
+}
+
+
+void ieee80211_wpa_assoc_frame(struct ieee80211_device *ieee, char *wpa_ie, int wpa_ie_len)
+{
+	/* make sure WPA is enabled */
+	ieee80211_wpa_enable(ieee, 1);
+
+	ieee80211_disassociate(ieee);
+}
+
+
+static int ieee80211_wpa_mlme(struct ieee80211_device *ieee, int command, int reason)
+{
+
+	int ret = 0;
+
+	switch (command) {
+	case IEEE_MLME_STA_DEAUTH:
+		// silently ignore
+		break;
+
+	case IEEE_MLME_STA_DISASSOC:
+		ieee80211_disassociate(ieee);
+		break;
+
+	default:
+		printk("Unknown MLME request: %d\n", command);
+		ret = -EOPNOTSUPP;
+	}
+
+	return ret;
+}
+
+
+static int ieee80211_wpa_set_wpa_ie(struct ieee80211_device *ieee,
+			      struct ieee_param *param, int plen)
+{
+	u8 *buf;
+
+	if (param->u.wpa_ie.len > MAX_WPA_IE_LEN ||
+	    (param->u.wpa_ie.len && param->u.wpa_ie.data == NULL))
+		return -EINVAL;
+
+	if (param->u.wpa_ie.len) {
+		buf = kmalloc(param->u.wpa_ie.len, GFP_KERNEL);
+		if (buf == NULL)
+			return -ENOMEM;
+
+		memcpy(buf, param->u.wpa_ie.data, param->u.wpa_ie.len);
+		kfree(ieee->wpa_ie);
+		ieee->wpa_ie = buf;
+		ieee->wpa_ie_len = param->u.wpa_ie.len;
+	} else {
+		kfree(ieee->wpa_ie);
+		ieee->wpa_ie = NULL;
+		ieee->wpa_ie_len = 0;
+	}
+
+	ieee80211_wpa_assoc_frame(ieee, ieee->wpa_ie, ieee->wpa_ie_len);
+	return 0;
+}
+
+#define AUTH_ALG_OPEN_SYSTEM			0x1
+#define AUTH_ALG_SHARED_KEY			0x2
+#define AUTH_ALG_LEAP				0x4
+static int ieee80211_wpa_set_auth_algs(struct ieee80211_device *ieee, int value)
+{
+
+	struct ieee80211_security sec = {
+		.flags = SEC_AUTH_MODE,
+	};
+	int ret = 0;
+
+	if (value & AUTH_ALG_SHARED_KEY) {
+		sec.auth_mode = WLAN_AUTH_SHARED_KEY;
+		ieee->open_wep = 0;
+		ieee->auth_mode = 1;
+	} else if (value & AUTH_ALG_OPEN_SYSTEM){
+		sec.auth_mode = WLAN_AUTH_OPEN;
+		ieee->open_wep = 1;
+		ieee->auth_mode = 0;
+	}
+	else if (value & AUTH_ALG_LEAP){
+		sec.auth_mode = WLAN_AUTH_LEAP;
+		ieee->open_wep = 1;
+		ieee->auth_mode = 2;
+	}
+
+
+	if (ieee->set_security)
+		ieee->set_security(ieee->dev, &sec);
+	//else
+	//	ret = -EOPNOTSUPP;
+
+	return ret;
+}
+
+static int ieee80211_wpa_set_param(struct ieee80211_device *ieee, u8 name, u32 value)
+{
+	int ret=0;
+	unsigned long flags;
+
+	switch (name) {
+	case IEEE_PARAM_WPA_ENABLED:
+		ret = ieee80211_wpa_enable(ieee, value);
+		break;
+
+	case IEEE_PARAM_TKIP_COUNTERMEASURES:
+		ieee->tkip_countermeasures=value;
+		break;
+
+	case IEEE_PARAM_DROP_UNENCRYPTED: {
+		/* HACK:
+		 *
+		 * wpa_supplicant calls set_wpa_enabled when the driver
+		 * is loaded and unloaded, regardless of if WPA is being
+		 * used.  No other calls are made which can be used to
+		 * determine if encryption will be used or not prior to
+		 * association being expected.  If encryption is not being
+		 * used, drop_unencrypted is set to false, else true -- we
+		 * can use this to determine if the CAP_PRIVACY_ON bit should
+		 * be set.
+		 */
+		struct ieee80211_security sec = {
+			.flags = SEC_ENABLED,
+			.enabled = value,
+		};
+ 		ieee->drop_unencrypted = value;
+		/* We only change SEC_LEVEL for open mode. Others
+		 * are set by ipw_wpa_set_encryption.
+		 */
+		if (!value) {
+			sec.flags |= SEC_LEVEL;
+			sec.level = SEC_LEVEL_0;
+		}
+		else {
+			sec.flags |= SEC_LEVEL;
+			sec.level = SEC_LEVEL_1;
+		}
+		if (ieee->set_security)
+			ieee->set_security(ieee->dev, &sec);
+		break;
+	}
+
+	case IEEE_PARAM_PRIVACY_INVOKED:
+		ieee->privacy_invoked=value;
+		break;
+
+	case IEEE_PARAM_AUTH_ALGS:
+		ret = ieee80211_wpa_set_auth_algs(ieee, value);
+		break;
+
+	case IEEE_PARAM_IEEE_802_1X:
+		ieee->ieee802_1x=value;
+		break;
+	case IEEE_PARAM_WPAX_SELECT:
+		// added for WPA2 mixed mode
+		spin_lock_irqsave(&ieee->wpax_suitlist_lock,flags);
+		ieee->wpax_type_set = 1;
+		ieee->wpax_type_notify = value;
+		spin_unlock_irqrestore(&ieee->wpax_suitlist_lock,flags);
+		break;
+
+	default:
+		printk("Unknown WPA param: %d\n",name);
+		ret = -EOPNOTSUPP;
+	}
+
+	return ret;
+}
+
+/* implementation borrowed from hostap driver */
+
+static int ieee80211_wpa_set_encryption(struct ieee80211_device *ieee,
+				  struct ieee_param *param, int param_len)
+{
+	int ret = 0;
+
+	struct ieee80211_crypto_ops *ops;
+	struct ieee80211_crypt_data **crypt;
+
+	struct ieee80211_security sec = {
+		.flags = 0,
+	};
+
+	param->u.crypt.err = 0;
+	param->u.crypt.alg[IEEE_CRYPT_ALG_NAME_LEN - 1] = '\0';
+
+	if (param_len !=
+	    (int) ((char *) param->u.crypt.key - (char *) param) +
+	    param->u.crypt.key_len) {
+		printk("Len mismatch %d, %d\n", param_len,
+			       param->u.crypt.key_len);
+		return -EINVAL;
+	}
+	if (param->sta_addr[0] == 0xff && param->sta_addr[1] == 0xff &&
+	    param->sta_addr[2] == 0xff && param->sta_addr[3] == 0xff &&
+	    param->sta_addr[4] == 0xff && param->sta_addr[5] == 0xff) {
+		if (param->u.crypt.idx >= WEP_KEYS)
+			return -EINVAL;
+		crypt = &ieee->crypt[param->u.crypt.idx];
+	} else {
+		return -EINVAL;
+	}
+
+	if (strcmp(param->u.crypt.alg, "none") == 0) {
+		if (crypt) {
+			sec.enabled = 0;
+			// FIXME FIXME
+			//sec.encrypt = 0;
+			sec.level = SEC_LEVEL_0;
+			sec.flags |= SEC_ENABLED | SEC_LEVEL;
+			ieee80211_crypt_delayed_deinit(ieee, crypt);
+		}
+		goto done;
+	}
+	sec.enabled = 1;
+// FIXME FIXME
+//	sec.encrypt = 1;
+	sec.flags |= SEC_ENABLED;
+
+	/* IPW HW cannot build TKIP MIC, host decryption still needed. */
+	if (!(ieee->host_encrypt || ieee->host_decrypt) &&
+	    strcmp(param->u.crypt.alg, "TKIP"))
+		goto skip_host_crypt;
+
+	ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
+	if (ops == NULL && strcmp(param->u.crypt.alg, "WEP") == 0) {
+		request_module("ieee80211_crypt_wep");
+		ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
+		//set WEP40 first, it will be modified according to WEP104 or WEP40 at other place
+	} else if (ops == NULL && strcmp(param->u.crypt.alg, "TKIP") == 0) {
+		request_module("ieee80211_crypt_tkip");
+		ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
+	} else if (ops == NULL && strcmp(param->u.crypt.alg, "CCMP") == 0) {
+		request_module("ieee80211_crypt_ccmp");
+		ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
+	}
+	if (ops == NULL) {
+		printk("unknown crypto alg '%s'\n", param->u.crypt.alg);
+		param->u.crypt.err = IEEE_CRYPT_ERR_UNKNOWN_ALG;
+		ret = -EINVAL;
+		goto done;
+	}
+
+	if (*crypt == NULL || (*crypt)->ops != ops) {
+		struct ieee80211_crypt_data *new_crypt;
+
+		ieee80211_crypt_delayed_deinit(ieee, crypt);
+
+		new_crypt = (struct ieee80211_crypt_data *)
+			kmalloc(sizeof(*new_crypt), GFP_KERNEL);
+		if (new_crypt == NULL) {
+			ret = -ENOMEM;
+			goto done;
+		}
+		memset(new_crypt, 0, sizeof(struct ieee80211_crypt_data));
+		new_crypt->ops = ops;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
+		if (new_crypt->ops && try_module_get(new_crypt->ops->owner))
+#else
+		if (new_crypt->ops && try_inc_mod_count(new_crypt->ops->owner))
+#endif
+			new_crypt->priv =
+				new_crypt->ops->init(param->u.crypt.idx);
+
+		if (new_crypt->priv == NULL) {
+			kfree(new_crypt);
+			param->u.crypt.err = IEEE_CRYPT_ERR_CRYPT_INIT_FAILED;
+			ret = -EINVAL;
+			goto done;
+		}
+
+		*crypt = new_crypt;
+	}
+
+	if (param->u.crypt.key_len > 0 && (*crypt)->ops->set_key &&
+	    (*crypt)->ops->set_key(param->u.crypt.key,
+				   param->u.crypt.key_len, param->u.crypt.seq,
+				   (*crypt)->priv) < 0) {
+		printk("key setting failed\n");
+		param->u.crypt.err = IEEE_CRYPT_ERR_KEY_SET_FAILED;
+		ret = -EINVAL;
+		goto done;
+	}
+
+ skip_host_crypt:
+	if (param->u.crypt.set_tx) {
+		ieee->tx_keyidx = param->u.crypt.idx;
+		sec.active_key = param->u.crypt.idx;
+		sec.flags |= SEC_ACTIVE_KEY;
+	} else
+		sec.flags &= ~SEC_ACTIVE_KEY;
+
+	if (param->u.crypt.alg != NULL) {
+		memcpy(sec.keys[param->u.crypt.idx],
+		       param->u.crypt.key,
+		       param->u.crypt.key_len);
+		sec.key_sizes[param->u.crypt.idx] = param->u.crypt.key_len;
+		sec.flags |= (1 << param->u.crypt.idx);
+
+		if (strcmp(param->u.crypt.alg, "WEP") == 0) {
+			sec.flags |= SEC_LEVEL;
+			sec.level = SEC_LEVEL_1;
+		} else if (strcmp(param->u.crypt.alg, "TKIP") == 0) {
+			sec.flags |= SEC_LEVEL;
+			sec.level = SEC_LEVEL_2;
+		} else if (strcmp(param->u.crypt.alg, "CCMP") == 0) {
+			sec.flags |= SEC_LEVEL;
+			sec.level = SEC_LEVEL_3;
+		}
+	}
+ done:
+	if (ieee->set_security)
+		ieee->set_security(ieee->dev, &sec);
+
+	/* Do not reset port if card is in Managed mode since resetting will
+	 * generate new IEEE 802.11 authentication which may end up in looping
+	 * with IEEE 802.1X.  If your hardware requires a reset after WEP
+	 * configuration (for example... Prism2), implement the reset_port in
+	 * the callbacks structures used to initialize the 802.11 stack. */
+	if (ieee->reset_on_keychange &&
+	    ieee->iw_mode != IW_MODE_INFRA &&
+	    ieee->reset_port &&
+	    ieee->reset_port(ieee->dev)) {
+		printk("reset_port failed\n");
+		param->u.crypt.err = IEEE_CRYPT_ERR_CARD_CONF_FAILED;
+		return -EINVAL;
+	}
+
+	return ret;
+}
+
+inline struct sk_buff *ieee80211_disassociate_skb(
+							struct ieee80211_network *beacon,
+							struct ieee80211_device *ieee,
+							u8	asRsn)
+{
+	struct sk_buff *skb;
+	struct ieee80211_disassoc *disass;
+
+	skb = dev_alloc_skb(sizeof(struct ieee80211_disassoc));
+	if (!skb)
+		return NULL;
+
+	disass = (struct ieee80211_disassoc *) skb_put(skb,sizeof(struct ieee80211_disassoc));
+	disass->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_DISASSOC);
+	disass->header.duration_id = 0;
+
+	memcpy(disass->header.addr1, beacon->bssid, ETH_ALEN);
+	memcpy(disass->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
+	memcpy(disass->header.addr3, beacon->bssid, ETH_ALEN);
+
+	disass->reason = asRsn;
+	return skb;
+}
+
+
+void
+SendDisassociation(
+		struct ieee80211_device *ieee,
+		u8* 					asSta,
+		u8						asRsn
+)
+{
+		struct ieee80211_network *beacon = &ieee->current_network;
+		struct sk_buff *skb;
+		skb = ieee80211_disassociate_skb(beacon,ieee,asRsn);
+		if (skb){
+				softmac_mgmt_xmit(skb, ieee);
+				//dev_kfree_skb_any(skb);//edit by thomas
+		}
+}
+
+int ieee80211_wpa_supplicant_ioctl(struct ieee80211_device *ieee, struct iw_point *p)
+{
+	struct ieee_param *param;
+	int ret=0;
+
+	down(&ieee->wx_sem);
+	//IEEE_DEBUG_INFO("wpa_supplicant: len=%d\n", p->length);
+
+	if (p->length < sizeof(struct ieee_param) || !p->pointer){
+		ret = -EINVAL;
+		goto out;
+	}
+
+	param = (struct ieee_param *)kmalloc(p->length, GFP_KERNEL);
+	if (param == NULL){
+		ret = -ENOMEM;
+		goto out;
+	}
+	if (copy_from_user(param, p->pointer, p->length)) {
+		kfree(param);
+		ret = -EFAULT;
+		goto out;
+	}
+
+	switch (param->cmd) {
+
+	case IEEE_CMD_SET_WPA_PARAM:
+		ret = ieee80211_wpa_set_param(ieee, param->u.wpa_param.name,
+					param->u.wpa_param.value);
+		break;
+
+	case IEEE_CMD_SET_WPA_IE:
+		ret = ieee80211_wpa_set_wpa_ie(ieee, param, p->length);
+		break;
+
+	case IEEE_CMD_SET_ENCRYPTION:
+		ret = ieee80211_wpa_set_encryption(ieee, param, p->length);
+		break;
+
+	case IEEE_CMD_MLME:
+		ret = ieee80211_wpa_mlme(ieee, param->u.mlme.command,
+				   param->u.mlme.reason_code);
+		break;
+
+	default:
+		printk("Unknown WPA supplicant request: %d\n",param->cmd);
+		ret = -EOPNOTSUPP;
+		break;
+	}
+
+	if (ret == 0 && copy_to_user(p->pointer, param, p->length))
+		ret = -EFAULT;
+
+	kfree(param);
+out:
+	up(&ieee->wx_sem);
+
+	return ret;
+}
+
+void notify_wx_assoc_event(struct ieee80211_device *ieee)
+{
+	union iwreq_data wrqu;
+	wrqu.ap_addr.sa_family = ARPHRD_ETHER;
+	if (ieee->state == IEEE80211_LINKED)
+		memcpy(wrqu.ap_addr.sa_data, ieee->current_network.bssid, ETH_ALEN);
+	else
+		memset(wrqu.ap_addr.sa_data, 0, ETH_ALEN);
+	wireless_send_event(ieee->dev, SIOCGIWAP, &wrqu, NULL);
+}
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+EXPORT_SYMBOL(ieee80211_get_beacon);
+EXPORT_SYMBOL(ieee80211_wake_queue);
+EXPORT_SYMBOL(ieee80211_stop_queue);
+EXPORT_SYMBOL(ieee80211_reset_queue);
+EXPORT_SYMBOL(ieee80211_softmac_stop_protocol);
+EXPORT_SYMBOL(ieee80211_softmac_start_protocol);
+EXPORT_SYMBOL(ieee80211_is_shortslot);
+EXPORT_SYMBOL(ieee80211_is_54g);
+EXPORT_SYMBOL(ieee80211_wpa_supplicant_ioctl);
+EXPORT_SYMBOL(ieee80211_ps_tx_ack);
+EXPORT_SYMBOL(ieee80211_softmac_xmit);
+EXPORT_SYMBOL(ieee80211_stop_send_beacons);
+EXPORT_SYMBOL(notify_wx_assoc_event);
+EXPORT_SYMBOL(SendDisassociation);
+EXPORT_SYMBOL(ieee80211_disassociate);
+EXPORT_SYMBOL(ieee80211_start_send_beacons);
+EXPORT_SYMBOL(ieee80211_stop_scan);
+EXPORT_SYMBOL(ieee80211_send_probe_requests);
+EXPORT_SYMBOL(ieee80211_softmac_scan_syncro);
+EXPORT_SYMBOL(ieee80211_start_scan_syncro);
+#else
+EXPORT_SYMBOL_NOVERS(ieee80211_get_beacon);
+EXPORT_SYMBOL_NOVERS(ieee80211_wake_queue);
+EXPORT_SYMBOL_NOVERS(ieee80211_stop_queue);
+EXPORT_SYMBOL_NOVERS(ieee80211_reset_queue);
+EXPORT_SYMBOL_NOVERS(ieee80211_softmac_stop_protocol);
+EXPORT_SYMBOL_NOVERS(ieee80211_softmac_start_protocol);
+EXPORT_SYMBOL_NOVERS(ieee80211_is_shortslot);
+EXPORT_SYMBOL_NOVERS(ieee80211_is_54g);
+EXPORT_SYMBOL_NOVERS(ieee80211_wpa_supplicant_ioctl);
+EXPORT_SYMBOL_NOVERS(ieee80211_ps_tx_ack);
+EXPORT_SYMBOL_NOVERS(ieee80211_softmac_xmit);
+EXPORT_SYMBOL_NOVERS(ieee80211_stop_send_beacons);
+EXPORT_SYMBOL_NOVERS(notify_wx_assoc_event);
+EXPORT_SYMBOL_NOVERS(SendDisassociation);
+EXPORT_SYMBOL_NOVERS(ieee80211_disassociate);
+EXPORT_SYMBOL_NOVERS(ieee80211_start_send_beacons);
+EXPORT_SYMBOL_NOVERS(ieee80211_stop_scan);
+EXPORT_SYMBOL_NOVERS(ieee80211_send_probe_requests);
+EXPORT_SYMBOL_NOVERS(ieee80211_softmac_scan_syncro);
+EXPORT_SYMBOL_NOVERS(ieee80211_start_scan_syncro);
+#endif
+//EXPORT_SYMBOL(ieee80211_sta_ps_send_null_frame);
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211_softmac_wx.c b/drivers/staging/rtl8192su/ieee80211/ieee80211_softmac_wx.c
new file mode 100644
index 0000000..1f50c46
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211_softmac_wx.c
@@ -0,0 +1,711 @@
+/* IEEE 802.11 SoftMAC layer
+ * Copyright (c) 2005 Andrea Merello <andreamrl@tiscali.it>
+ *
+ * Mostly extracted from the rtl8180-sa2400 driver for the
+ * in-kernel generic ieee802.11 stack.
+ *
+ * Some pieces of code might be stolen from ipw2100 driver
+ * copyright of who own it's copyright ;-)
+ *
+ * PS wx handler mostly stolen from hostap, copyright who
+ * own it's copyright ;-)
+ *
+ * released under the GPL
+ */
+
+
+#include "ieee80211.h"
+#ifdef ENABLE_DOT11D
+#include "dot11d.h"
+#endif
+/* FIXME: add A freqs */
+
+const long ieee80211_wlan_frequencies[] = {
+	2412, 2417, 2422, 2427,
+	2432, 2437, 2442, 2447,
+	2452, 2457, 2462, 2467,
+	2472, 2484
+};
+
+
+int ieee80211_wx_set_freq(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b)
+{
+	int ret;
+	struct iw_freq *fwrq = & wrqu->freq;
+
+	down(&ieee->wx_sem);
+
+	if(ieee->iw_mode == IW_MODE_INFRA){
+		ret = -EOPNOTSUPP;
+		goto out;
+	}
+
+	/* if setting by freq convert to channel */
+	if (fwrq->e == 1) {
+		if ((fwrq->m >= (int) 2.412e8 &&
+		     fwrq->m <= (int) 2.487e8)) {
+			int f = fwrq->m / 100000;
+			int c = 0;
+
+			while ((c < 14) && (f != ieee80211_wlan_frequencies[c]))
+				c++;
+
+			/* hack to fall through */
+			fwrq->e = 0;
+			fwrq->m = c + 1;
+		}
+	}
+
+	if (fwrq->e > 0 || fwrq->m > 14 || fwrq->m < 1 ){
+		ret = -EOPNOTSUPP;
+		goto out;
+
+	}else { /* Set the channel */
+
+#ifdef ENABLE_DOT11D
+		if (!(GET_DOT11D_INFO(ieee)->channel_map)[fwrq->m]) {
+			ret = -EINVAL;
+			goto out;
+		}
+#endif
+		ieee->current_network.channel = fwrq->m;
+		ieee->set_chan(ieee->dev, ieee->current_network.channel);
+
+		if(ieee->iw_mode == IW_MODE_ADHOC || ieee->iw_mode == IW_MODE_MASTER)
+			if(ieee->state == IEEE80211_LINKED){
+
+			ieee80211_stop_send_beacons(ieee);
+			ieee80211_start_send_beacons(ieee);
+			}
+	}
+
+	ret = 0;
+out:
+	up(&ieee->wx_sem);
+	return ret;
+}
+
+
+int ieee80211_wx_get_freq(struct ieee80211_device *ieee,
+			     struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b)
+{
+	struct iw_freq *fwrq = & wrqu->freq;
+
+	if (ieee->current_network.channel == 0)
+		return -1;
+	//NM 0.7.0 will not accept channel any more.
+	fwrq->m = ieee80211_wlan_frequencies[ieee->current_network.channel-1] * 100000;
+	fwrq->e = 1;
+//	fwrq->m = ieee->current_network.channel;
+//	fwrq->e = 0;
+
+	return 0;
+}
+
+int ieee80211_wx_get_wap(struct ieee80211_device *ieee,
+			    struct iw_request_info *info,
+			    union iwreq_data *wrqu, char *extra)
+{
+	unsigned long flags;
+
+	wrqu->ap_addr.sa_family = ARPHRD_ETHER;
+
+	if (ieee->iw_mode == IW_MODE_MONITOR)
+		return -1;
+
+	/* We want avoid to give to the user inconsistent infos*/
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	if (ieee->state != IEEE80211_LINKED &&
+		ieee->state != IEEE80211_LINKED_SCANNING &&
+		ieee->wap_set == 0)
+
+		memset(wrqu->ap_addr.sa_data, 0, ETH_ALEN);
+	else
+		memcpy(wrqu->ap_addr.sa_data,
+		       ieee->current_network.bssid, ETH_ALEN);
+
+	spin_unlock_irqrestore(&ieee->lock, flags);
+
+	return 0;
+}
+
+
+int ieee80211_wx_set_wap(struct ieee80211_device *ieee,
+			 struct iw_request_info *info,
+			 union iwreq_data *awrq,
+			 char *extra)
+{
+
+	int ret = 0;
+	u8 zero[] = {0,0,0,0,0,0};
+	unsigned long flags;
+
+	short ifup = ieee->proto_started;//dev->flags & IFF_UP;
+	struct sockaddr *temp = (struct sockaddr *)awrq;
+
+	ieee->sync_scan_hurryup = 1;
+
+	down(&ieee->wx_sem);
+	/* use ifconfig hw ether */
+	if (ieee->iw_mode == IW_MODE_MASTER){
+		ret = -1;
+		goto out;
+	}
+
+	if (temp->sa_family != ARPHRD_ETHER){
+		ret = -EINVAL;
+		goto out;
+	}
+
+	if (ifup)
+		ieee80211_stop_protocol(ieee);
+
+	/* just to avoid to give inconsistent infos in the
+	 * get wx method. not really needed otherwise
+	 */
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	memcpy(ieee->current_network.bssid, temp->sa_data, ETH_ALEN);
+	ieee->wap_set = memcmp(temp->sa_data, zero,ETH_ALEN)!=0;
+
+	spin_unlock_irqrestore(&ieee->lock, flags);
+
+	if (ifup)
+		ieee80211_start_protocol(ieee);
+out:
+	up(&ieee->wx_sem);
+	return ret;
+}
+
+ int ieee80211_wx_get_essid(struct ieee80211_device *ieee, struct iw_request_info *a,union iwreq_data *wrqu,char *b)
+{
+	int len,ret = 0;
+	unsigned long flags;
+
+	if (ieee->iw_mode == IW_MODE_MONITOR)
+		return -1;
+
+	/* We want avoid to give to the user inconsistent infos*/
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	if (ieee->current_network.ssid[0] == '\0' ||
+		ieee->current_network.ssid_len == 0){
+		ret = -1;
+		goto out;
+	}
+
+	if (ieee->state != IEEE80211_LINKED &&
+		ieee->state != IEEE80211_LINKED_SCANNING &&
+		ieee->ssid_set == 0){
+		ret = -1;
+		goto out;
+	}
+	len = ieee->current_network.ssid_len;
+	wrqu->essid.length = len;
+	strncpy(b,ieee->current_network.ssid,len);
+	wrqu->essid.flags = 1;
+
+out:
+	spin_unlock_irqrestore(&ieee->lock, flags);
+
+	return ret;
+
+}
+
+int ieee80211_wx_set_rate(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+
+	u32 target_rate = wrqu->bitrate.value;
+
+	ieee->rate = target_rate/100000;
+	//FIXME: we might want to limit rate also in management protocols.
+	return 0;
+}
+
+
+
+int ieee80211_wx_get_rate(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	u32 tmp_rate = 0;
+#ifdef RTL8192SU
+	//printk("===>mode:%d, halfNmode:%d\n", ieee->mode, ieee->bHalfWirelessN24GMode);
+	if (ieee->mode & (IEEE_A | IEEE_B | IEEE_G))
+		tmp_rate = ieee->rate;
+	else if (ieee->mode & IEEE_N_5G)
+		tmp_rate = 580;
+	else if (ieee->mode & IEEE_N_24G)
+	{
+		if (ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev))
+			tmp_rate = HTHalfMcsToDataRate(ieee, 15);
+		else
+			tmp_rate = HTMcsToDataRate(ieee, 15);
+	}
+#else
+	tmp_rate = TxCountToDataRate(ieee, ieee->softmac_stats.CurrentShowTxate);
+
+#endif
+	wrqu->bitrate.value = tmp_rate * 500000;
+
+	return 0;
+}
+
+
+int ieee80211_wx_set_rts(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	if (wrqu->rts.disabled || !wrqu->rts.fixed)
+		ieee->rts = DEFAULT_RTS_THRESHOLD;
+	else
+	{
+		if (wrqu->rts.value < MIN_RTS_THRESHOLD ||
+				wrqu->rts.value > MAX_RTS_THRESHOLD)
+			return -EINVAL;
+		ieee->rts = wrqu->rts.value;
+	}
+	return 0;
+}
+
+int ieee80211_wx_get_rts(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	wrqu->rts.value = ieee->rts;
+	wrqu->rts.fixed = 0;	/* no auto select */
+	wrqu->rts.disabled = (wrqu->rts.value == DEFAULT_RTS_THRESHOLD);
+	return 0;
+}
+int ieee80211_wx_set_mode(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b)
+{
+
+	ieee->sync_scan_hurryup = 1;
+
+	down(&ieee->wx_sem);
+
+	if (wrqu->mode == ieee->iw_mode)
+		goto out;
+
+	if (wrqu->mode == IW_MODE_MONITOR){
+
+		ieee->dev->type = ARPHRD_IEEE80211;
+	}else{
+		ieee->dev->type = ARPHRD_ETHER;
+	}
+
+	if (!ieee->proto_started){
+		ieee->iw_mode = wrqu->mode;
+	}else{
+		ieee80211_stop_protocol(ieee);
+		ieee->iw_mode = wrqu->mode;
+		ieee80211_start_protocol(ieee);
+	}
+
+out:
+	up(&ieee->wx_sem);
+	return 0;
+}
+
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+void ieee80211_wx_sync_scan_wq(struct work_struct *work)
+{
+        struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, wx_sync_scan_wq);
+#else
+void ieee80211_wx_sync_scan_wq(struct ieee80211_device *ieee)
+{
+#endif
+	short chan;
+	HT_EXTCHNL_OFFSET chan_offset=0;
+	HT_CHANNEL_WIDTH bandwidth=0;
+	int b40M = 0;
+	static int count = 0;
+	chan = ieee->current_network.channel;
+	netif_carrier_off(ieee->dev);
+
+	if (ieee->data_hard_stop)
+		ieee->data_hard_stop(ieee->dev);
+
+	ieee80211_stop_send_beacons(ieee);
+
+	ieee->state = IEEE80211_LINKED_SCANNING;
+	ieee->link_change(ieee->dev);
+#ifndef RTL8192SE
+	ieee->InitialGainHandler(ieee->dev,IG_Backup);
+#endif
+#if(RTL8192S_DISABLE_FW_DM == 0)
+	if (ieee->SetFwCmdHandler)
+	{
+		ieee->SetFwCmdHandler(ieee->dev, FW_CMD_DIG_HALT);
+		ieee->SetFwCmdHandler(ieee->dev, FW_CMD_HIGH_PWR_DISABLE);
+	}
+#endif
+	if (ieee->pHTInfo->bCurrentHTSupport && ieee->pHTInfo->bEnableHT && ieee->pHTInfo->bCurBW40MHz) {
+		b40M = 1;
+		chan_offset = ieee->pHTInfo->CurSTAExtChnlOffset;
+		bandwidth = (HT_CHANNEL_WIDTH)ieee->pHTInfo->bCurBW40MHz;
+		printk("Scan in 40M, force to 20M first:%d, %d\n", chan_offset, bandwidth);
+		ieee->SetBWModeHandler(ieee->dev, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
+		}
+	ieee80211_start_scan_syncro(ieee);
+	if (b40M) {
+		printk("Scan in 20M, back to 40M\n");
+		if (chan_offset == HT_EXTCHNL_OFFSET_UPPER)
+			ieee->set_chan(ieee->dev, chan + 2);
+		else if (chan_offset == HT_EXTCHNL_OFFSET_LOWER)
+			ieee->set_chan(ieee->dev, chan - 2);
+		else
+			ieee->set_chan(ieee->dev, chan);
+		ieee->SetBWModeHandler(ieee->dev, bandwidth, chan_offset);
+	} else {
+		ieee->set_chan(ieee->dev, chan);
+	}
+
+#ifndef RTL8192SE
+	ieee->InitialGainHandler(ieee->dev,IG_Restore);
+#endif
+#if(RTL8192S_DISABLE_FW_DM == 0)
+	if (ieee->SetFwCmdHandler)
+	{
+		ieee->SetFwCmdHandler(ieee->dev, FW_CMD_DIG_RESUME);
+		ieee->SetFwCmdHandler(ieee->dev, FW_CMD_HIGH_PWR_ENABLE);
+	}
+#endif
+	ieee->state = IEEE80211_LINKED;
+	ieee->link_change(ieee->dev);
+	// To prevent the immediately calling watch_dog after scan.
+	if(ieee->LinkDetectInfo.NumRecvBcnInPeriod==0||ieee->LinkDetectInfo.NumRecvDataInPeriod==0 )
+	{
+		ieee->LinkDetectInfo.NumRecvBcnInPeriod = 1;
+		ieee->LinkDetectInfo.NumRecvDataInPeriod= 1;
+	}
+	if (ieee->data_hard_resume)
+		ieee->data_hard_resume(ieee->dev);
+
+	if(ieee->iw_mode == IW_MODE_ADHOC || ieee->iw_mode == IW_MODE_MASTER)
+		ieee80211_start_send_beacons(ieee);
+
+	netif_carrier_on(ieee->dev);
+	count = 0;
+	up(&ieee->wx_sem);
+
+}
+
+int ieee80211_wx_set_scan(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b)
+{
+	int ret = 0;
+
+	down(&ieee->wx_sem);
+
+	if (ieee->iw_mode == IW_MODE_MONITOR || !(ieee->proto_started)){
+		ret = -1;
+		goto out;
+	}
+
+	if ( ieee->state == IEEE80211_LINKED){
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+		queue_work(ieee->wq, &ieee->wx_sync_scan_wq);
+#else
+		schedule_task(&ieee->wx_sync_scan_wq);
+#endif
+		/* intentionally forget to up sem */
+		return 0;
+	}
+
+out:
+	up(&ieee->wx_sem);
+	return ret;
+}
+
+int ieee80211_wx_set_essid(struct ieee80211_device *ieee,
+			      struct iw_request_info *a,
+			      union iwreq_data *wrqu, char *extra)
+{
+
+	int ret=0,len;
+	short proto_started;
+	unsigned long flags;
+
+	ieee->sync_scan_hurryup = 1;
+	down(&ieee->wx_sem);
+
+	proto_started = ieee->proto_started;
+
+	if (wrqu->essid.length > IW_ESSID_MAX_SIZE){
+		ret= -E2BIG;
+		goto out;
+	}
+
+	if (ieee->iw_mode == IW_MODE_MONITOR){
+		ret= -1;
+		goto out;
+	}
+
+	if(proto_started)
+		ieee80211_stop_protocol(ieee);
+
+
+	/* this is just to be sure that the GET wx callback
+	 * has consisten infos. not needed otherwise
+	 */
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	if (wrqu->essid.flags && wrqu->essid.length) {
+		//first flush current network.ssid
+		len = ((wrqu->essid.length-1) < IW_ESSID_MAX_SIZE) ? (wrqu->essid.length-1) : IW_ESSID_MAX_SIZE;
+#if LINUX_VERSION_CODE <  KERNEL_VERSION(2,6,20)
+		strncpy(ieee->current_network.ssid, extra, len);
+		ieee->current_network.ssid_len = len;
+#if 0
+		{
+			int i;
+			for (i=0; i<len; i++)
+				printk("%c ", extra[i]);
+			printk("\n");
+		}
+#endif
+#else
+		strncpy(ieee->current_network.ssid, extra, len+1);
+		ieee->current_network.ssid_len = len+1;
+#if 0
+		{
+			int i;
+			for (i=0; i<len + 1; i++)
+				printk("%c ", extra[i]);
+			printk("\n");
+		}
+#endif
+#endif
+		ieee->ssid_set = 1;
+	}
+	else{
+		ieee->ssid_set = 0;
+		ieee->current_network.ssid[0] = '\0';
+		ieee->current_network.ssid_len = 0;
+	}
+	spin_unlock_irqrestore(&ieee->lock, flags);
+
+	if (proto_started)
+		ieee80211_start_protocol(ieee);
+out:
+	up(&ieee->wx_sem);
+	return ret;
+}
+
+ int ieee80211_wx_get_mode(struct ieee80211_device *ieee, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b)
+{
+
+	wrqu->mode = ieee->iw_mode;
+	return 0;
+}
+
+ int ieee80211_wx_set_rawtx(struct ieee80211_device *ieee,
+			       struct iw_request_info *info,
+			       union iwreq_data *wrqu, char *extra)
+{
+
+	int *parms = (int *)extra;
+	int enable = (parms[0] > 0);
+	short prev = ieee->raw_tx;
+
+	down(&ieee->wx_sem);
+
+	if(enable)
+		ieee->raw_tx = 1;
+	else
+		ieee->raw_tx = 0;
+
+	printk(KERN_INFO"raw TX is %s\n",
+	      ieee->raw_tx ? "enabled" : "disabled");
+
+	if(ieee->iw_mode == IW_MODE_MONITOR)
+	{
+		if(prev == 0 && ieee->raw_tx){
+			if (ieee->data_hard_resume)
+				ieee->data_hard_resume(ieee->dev);
+
+			netif_carrier_on(ieee->dev);
+		}
+
+		if(prev && ieee->raw_tx == 1)
+			netif_carrier_off(ieee->dev);
+	}
+
+	up(&ieee->wx_sem);
+
+	return 0;
+}
+
+int ieee80211_wx_get_name(struct ieee80211_device *ieee,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	strcpy(wrqu->name, "802.11");
+	if(ieee->modulation & IEEE80211_CCK_MODULATION){
+		strcat(wrqu->name, "b");
+		if(ieee->modulation & IEEE80211_OFDM_MODULATION)
+			strcat(wrqu->name, "/g");
+	}else if(ieee->modulation & IEEE80211_OFDM_MODULATION)
+		strcat(wrqu->name, "g");
+	if (ieee->mode & (IEEE_N_24G | IEEE_N_5G))
+		strcat(wrqu->name, "/n");
+
+	if((ieee->state == IEEE80211_LINKED) ||
+		(ieee->state == IEEE80211_LINKED_SCANNING))
+		strcat(wrqu->name," linked");
+	else if(ieee->state != IEEE80211_NOLINK)
+		strcat(wrqu->name," link..");
+
+
+	return 0;
+}
+
+
+/* this is mostly stolen from hostap */
+int ieee80211_wx_set_power(struct ieee80211_device *ieee,
+				 struct iw_request_info *info,
+				 union iwreq_data *wrqu, char *extra)
+{
+	int ret = 0;
+#if 1
+	if(
+		(!ieee->sta_wake_up) ||
+	//	(!ieee->ps_request_tx_ack) ||
+		(!ieee->enter_sleep_state) ||
+		(!ieee->ps_is_queue_empty)){
+
+	//	printk("ERROR. PS mode is tryied to be use but driver missed a callback\n\n");
+
+		return -1;
+	}
+#endif
+	down(&ieee->wx_sem);
+
+	if (wrqu->power.disabled){
+		ieee->ps = IEEE80211_PS_DISABLED;
+		goto exit;
+	}
+	if (wrqu->power.flags & IW_POWER_TIMEOUT) {
+		//ieee->ps_period = wrqu->power.value / 1000;
+		ieee->ps_timeout = wrqu->power.value / 1000;
+	}
+
+	if (wrqu->power.flags & IW_POWER_PERIOD) {
+
+		//ieee->ps_timeout = wrqu->power.value / 1000;
+		ieee->ps_period = wrqu->power.value / 1000;
+		//wrq->value / 1024;
+
+	}
+	switch (wrqu->power.flags & IW_POWER_MODE) {
+	case IW_POWER_UNICAST_R:
+		ieee->ps = IEEE80211_PS_UNICAST;
+		break;
+	case IW_POWER_MULTICAST_R:
+		ieee->ps = IEEE80211_PS_MBCAST;
+		break;
+	case IW_POWER_ALL_R:
+		ieee->ps = IEEE80211_PS_UNICAST | IEEE80211_PS_MBCAST;
+		break;
+
+	case IW_POWER_ON:
+	//	ieee->ps = IEEE80211_PS_DISABLED;
+		break;
+
+	default:
+		ret = -EINVAL;
+		goto exit;
+
+	}
+exit:
+	up(&ieee->wx_sem);
+	return ret;
+
+}
+
+/* this is stolen from hostap */
+int ieee80211_wx_get_power(struct ieee80211_device *ieee,
+				 struct iw_request_info *info,
+				 union iwreq_data *wrqu, char *extra)
+{
+	int ret =0;
+
+	down(&ieee->wx_sem);
+
+	if(ieee->ps == IEEE80211_PS_DISABLED){
+		wrqu->power.disabled = 1;
+		goto exit;
+	}
+
+	wrqu->power.disabled = 0;
+
+	if ((wrqu->power.flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {
+		wrqu->power.flags = IW_POWER_TIMEOUT;
+		wrqu->power.value = ieee->ps_timeout * 1000;
+	} else {
+//		ret = -EOPNOTSUPP;
+//		goto exit;
+		wrqu->power.flags = IW_POWER_PERIOD;
+		wrqu->power.value = ieee->ps_period * 1000;
+//ieee->current_network.dtim_period * ieee->current_network.beacon_interval * 1024;
+	}
+
+       if ((ieee->ps & (IEEE80211_PS_MBCAST | IEEE80211_PS_UNICAST)) == (IEEE80211_PS_MBCAST | IEEE80211_PS_UNICAST))
+	   	wrqu->power.flags |= IW_POWER_ALL_R;
+	else if (ieee->ps & IEEE80211_PS_MBCAST)
+		wrqu->power.flags |= IW_POWER_MULTICAST_R;
+	else
+		wrqu->power.flags |= IW_POWER_UNICAST_R;
+
+exit:
+	up(&ieee->wx_sem);
+	return ret;
+
+}
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+EXPORT_SYMBOL(ieee80211_wx_get_essid);
+EXPORT_SYMBOL(ieee80211_wx_set_essid);
+EXPORT_SYMBOL(ieee80211_wx_set_rate);
+EXPORT_SYMBOL(ieee80211_wx_get_rate);
+EXPORT_SYMBOL(ieee80211_wx_set_wap);
+EXPORT_SYMBOL(ieee80211_wx_get_wap);
+EXPORT_SYMBOL(ieee80211_wx_set_mode);
+EXPORT_SYMBOL(ieee80211_wx_get_mode);
+EXPORT_SYMBOL(ieee80211_wx_set_scan);
+EXPORT_SYMBOL(ieee80211_wx_get_freq);
+EXPORT_SYMBOL(ieee80211_wx_set_freq);
+EXPORT_SYMBOL(ieee80211_wx_set_rawtx);
+EXPORT_SYMBOL(ieee80211_wx_get_name);
+EXPORT_SYMBOL(ieee80211_wx_set_power);
+EXPORT_SYMBOL(ieee80211_wx_get_power);
+EXPORT_SYMBOL(ieee80211_wlan_frequencies);
+EXPORT_SYMBOL(ieee80211_wx_set_rts);
+EXPORT_SYMBOL(ieee80211_wx_get_rts);
+#else
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_get_essid);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_essid);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_rate);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_get_rate);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_wap);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_get_wap);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_mode);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_get_mode);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_scan);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_get_freq);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_freq);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_rawtx);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_get_name);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_power);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_get_power);
+EXPORT_SYMBOL_NOVERS(ieee80211_wlan_frequencies);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_rts);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_get_rts);
+#endif
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211_tx.c b/drivers/staging/rtl8192su/ieee80211/ieee80211_tx.c
new file mode 100644
index 0000000..7294572
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211_tx.c
@@ -0,0 +1,947 @@
+/******************************************************************************
+
+  Copyright(c) 2003 - 2004 Intel Corporation. All rights reserved.
+
+  This program is free software; you can redistribute it and/or modify it
+  under the terms of version 2 of the GNU General Public License as
+  published by the Free Software Foundation.
+
+  This program is distributed in the hope that it will be useful, but WITHOUT
+  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+  more details.
+
+  You should have received a copy of the GNU General Public License along with
+  this program; if not, write to the Free Software Foundation, Inc., 59
+  Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+
+  The full GNU General Public License is included in this distribution in the
+  file called LICENSE.
+
+  Contact Information:
+  James P. Ketrenos <ipw2100-admin@linux.intel.com>
+  Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
+
+******************************************************************************
+
+  Few modifications for Realtek's Wi-Fi drivers by
+  Andrea Merello <andreamrl@tiscali.it>
+
+  A special thanks goes to Realtek for their support !
+
+******************************************************************************/
+
+#include <linux/compiler.h>
+//#include <linux/config.h>
+#include <linux/errno.h>
+#include <linux/if_arp.h>
+#include <linux/in6.h>
+#include <linux/in.h>
+#include <linux/ip.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/netdevice.h>
+#include <linux/pci.h>
+#include <linux/proc_fs.h>
+#include <linux/skbuff.h>
+#include <linux/slab.h>
+#include <linux/tcp.h>
+#include <linux/types.h>
+#include <linux/version.h>
+#include <linux/wireless.h>
+#include <linux/etherdevice.h>
+#include <asm/uaccess.h>
+#include <linux/if_vlan.h>
+
+#include "ieee80211.h"
+
+
+/*
+
+
+802.11 Data Frame
+
+
+802.11 frame_contorl for data frames - 2 bytes
+     ,-----------------------------------------------------------------------------------------.
+bits | 0  |  1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |  9  |  a  |  b  |  c  |  d  |  e   |
+     |----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|------|
+val  | 0  |  0  |  0  |  1  |  x  |  0  |  0  |  0  |  1  |  0  |  x  |  x  |  x  |  x  |  x   |
+     |----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|------|
+desc | ^-ver-^  |  ^type-^  |  ^-----subtype-----^  | to  |from |more |retry| pwr |more |wep   |
+     |          |           | x=0 data,x=1 data+ack | DS  | DS  |frag |     | mgm |data |      |
+     '-----------------------------------------------------------------------------------------'
+		                                    /\
+                                                    |
+802.11 Data Frame                                   |
+           ,--------- 'ctrl' expands to >-----------'
+          |
+      ,--'---,-------------------------------------------------------------.
+Bytes |  2   |  2   |    6    |    6    |    6    |  2   | 0..2312 |   4  |
+      |------|------|---------|---------|---------|------|---------|------|
+Desc. | ctrl | dura |  DA/RA  |   TA    |    SA   | Sequ |  Frame  |  fcs |
+      |      | tion | (BSSID) |         |         | ence |  data   |      |
+      `--------------------------------------------------|         |------'
+Total: 28 non-data bytes                                 `----.----'
+                                                              |
+       .- 'Frame data' expands to <---------------------------'
+       |
+       V
+      ,---------------------------------------------------.
+Bytes |  1   |  1   |    1    |    3     |  2   |  0-2304 |
+      |------|------|---------|----------|------|---------|
+Desc. | SNAP | SNAP | Control |Eth Tunnel| Type | IP      |
+      | DSAP | SSAP |         |          |      | Packet  |
+      | 0xAA | 0xAA |0x03 (UI)|0x00-00-F8|      |         |
+      `-----------------------------------------|         |
+Total: 8 non-data bytes                         `----.----'
+                                                     |
+       .- 'IP Packet' expands, if WEP enabled, to <--'
+       |
+       V
+      ,-----------------------.
+Bytes |  4  |   0-2296  |  4  |
+      |-----|-----------|-----|
+Desc. | IV  | Encrypted | ICV |
+      |     | IP Packet |     |
+      `-----------------------'
+Total: 8 non-data bytes
+
+
+802.3 Ethernet Data Frame
+
+      ,-----------------------------------------.
+Bytes |   6   |   6   |  2   |  Variable |   4  |
+      |-------|-------|------|-----------|------|
+Desc. | Dest. | Source| Type | IP Packet |  fcs |
+      |  MAC  |  MAC  |      |           |      |
+      `-----------------------------------------'
+Total: 18 non-data bytes
+
+In the event that fragmentation is required, the incoming payload is split into
+N parts of size ieee->fts.  The first fragment contains the SNAP header and the
+remaining packets are just data.
+
+If encryption is enabled, each fragment payload size is reduced by enough space
+to add the prefix and postfix (IV and ICV totalling 8 bytes in the case of WEP)
+So if you have 1500 bytes of payload with ieee->fts set to 500 without
+encryption it will take 3 frames.  With WEP it will take 4 frames as the
+payload of each frame is reduced to 492 bytes.
+
+* SKB visualization
+*
+*  ,- skb->data
+* |
+* |    ETHERNET HEADER        ,-<-- PAYLOAD
+* |                           |     14 bytes from skb->data
+* |  2 bytes for Type --> ,T. |     (sizeof ethhdr)
+* |                       | | |
+* |,-Dest.--. ,--Src.---. | | |
+* |  6 bytes| | 6 bytes | | | |
+* v         | |         | | | |
+* 0         | v       1 | v | v           2
+* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+*     ^     | ^         | ^ |
+*     |     | |         | | |
+*     |     | |         | `T' <---- 2 bytes for Type
+*     |     | |         |
+*     |     | '---SNAP--' <-------- 6 bytes for SNAP
+*     |     |
+*     `-IV--' <-------------------- 4 bytes for IV (WEP)
+*
+*      SNAP HEADER
+*
+*/
+
+static u8 P802_1H_OUI[P80211_OUI_LEN] = { 0x00, 0x00, 0xf8 };
+static u8 RFC1042_OUI[P80211_OUI_LEN] = { 0x00, 0x00, 0x00 };
+
+static inline int ieee80211_put_snap(u8 *data, u16 h_proto)
+{
+	struct ieee80211_snap_hdr *snap;
+	u8 *oui;
+
+	snap = (struct ieee80211_snap_hdr *)data;
+	snap->dsap = 0xaa;
+	snap->ssap = 0xaa;
+	snap->ctrl = 0x03;
+
+	if (h_proto == 0x8137 || h_proto == 0x80f3)
+		oui = P802_1H_OUI;
+	else
+		oui = RFC1042_OUI;
+	snap->oui[0] = oui[0];
+	snap->oui[1] = oui[1];
+	snap->oui[2] = oui[2];
+
+	*(u16 *)(data + SNAP_SIZE) = htons(h_proto);
+
+	return SNAP_SIZE + sizeof(u16);
+}
+
+int ieee80211_encrypt_fragment(
+	struct ieee80211_device *ieee,
+	struct sk_buff *frag,
+	int hdr_len)
+{
+	struct ieee80211_crypt_data* crypt = ieee->crypt[ieee->tx_keyidx];
+	int res;
+
+	if (!(crypt && crypt->ops))
+	{
+		printk("=========>%s(), crypt is null\n", __FUNCTION__);
+		return -1;
+	}
+#ifdef CONFIG_IEEE80211_CRYPT_TKIP
+	struct ieee80211_hdr *header;
+
+	if (ieee->tkip_countermeasures &&
+	    crypt && crypt->ops && strcmp(crypt->ops->name, "TKIP") == 0) {
+		header = (struct ieee80211_hdr *) frag->data;
+		if (net_ratelimit()) {
+			printk(KERN_DEBUG "%s: TKIP countermeasures: dropped "
+			       "TX packet to " MAC_FMT "\n",
+			       ieee->dev->name, MAC_ARG(header->addr1));
+		}
+		return -1;
+	}
+#endif
+	/* To encrypt, frame format is:
+	 * IV (4 bytes), clear payload (including SNAP), ICV (4 bytes) */
+
+	// PR: FIXME: Copied from hostap. Check fragmentation/MSDU/MPDU encryption.
+	/* Host-based IEEE 802.11 fragmentation for TX is not yet supported, so
+	 * call both MSDU and MPDU encryption functions from here. */
+	atomic_inc(&crypt->refcnt);
+	res = 0;
+	if (crypt->ops->encrypt_msdu)
+		res = crypt->ops->encrypt_msdu(frag, hdr_len, crypt->priv);
+	if (res == 0 && crypt->ops->encrypt_mpdu)
+		res = crypt->ops->encrypt_mpdu(frag, hdr_len, crypt->priv);
+
+	atomic_dec(&crypt->refcnt);
+	if (res < 0) {
+		printk(KERN_INFO "%s: Encryption failed: len=%d.\n",
+		       ieee->dev->name, frag->len);
+		ieee->ieee_stats.tx_discards++;
+		return -1;
+	}
+
+	return 0;
+}
+
+
+void ieee80211_txb_free(struct ieee80211_txb *txb) {
+	//int i;
+	if (unlikely(!txb))
+		return;
+#if 0
+	for (i = 0; i < txb->nr_frags; i++)
+		if (txb->fragments[i])
+			dev_kfree_skb_any(txb->fragments[i]);
+#endif
+	kfree(txb);
+}
+
+struct ieee80211_txb *ieee80211_alloc_txb(int nr_frags, int txb_size,
+					  int gfp_mask)
+{
+	struct ieee80211_txb *txb;
+	int i;
+	txb = kmalloc(
+		sizeof(struct ieee80211_txb) + (sizeof(u8*) * nr_frags),
+		gfp_mask);
+	if (!txb)
+		return NULL;
+
+	memset(txb, 0, sizeof(struct ieee80211_txb));
+	txb->nr_frags = nr_frags;
+	txb->frag_size = txb_size;
+
+	for (i = 0; i < nr_frags; i++) {
+		txb->fragments[i] = dev_alloc_skb(txb_size);
+		if (unlikely(!txb->fragments[i])) {
+			i--;
+			break;
+		}
+		memset(txb->fragments[i]->cb, 0, sizeof(txb->fragments[i]->cb));
+	}
+	if (unlikely(i != nr_frags)) {
+		while (i >= 0)
+			dev_kfree_skb_any(txb->fragments[i--]);
+		kfree(txb);
+		return NULL;
+	}
+	return txb;
+}
+
+// Classify the to-be send data packet
+// Need to acquire the sent queue index.
+static int
+ieee80211_classify(struct sk_buff *skb, struct ieee80211_network *network)
+{
+	struct ethhdr *eth;
+	struct iphdr *ip;
+	eth = (struct ethhdr *)skb->data;
+	if (eth->h_proto != htons(ETH_P_IP))
+		return 0;
+
+//	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, skb->data, skb->len);
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22))
+	ip = ip_hdr(skb);
+#else
+	ip = (struct iphdr*)(skb->data + sizeof(struct ether_header));
+#endif
+	switch (ip->tos & 0xfc) {
+		case 0x20:
+			return 2;
+		case 0x40:
+			return 1;
+		case 0x60:
+			return 3;
+		case 0x80:
+			return 4;
+		case 0xa0:
+			return 5;
+		case 0xc0:
+			return 6;
+		case 0xe0:
+			return 7;
+		default:
+			return 0;
+	}
+}
+
+#define SN_LESS(a, b)		(((a-b)&0x800)!=0)
+void ieee80211_tx_query_agg_cap(struct ieee80211_device* ieee, struct sk_buff* skb, cb_desc* tcb_desc)
+{
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	PTX_TS_RECORD			pTxTs = NULL;
+	struct ieee80211_hdr_1addr* hdr = (struct ieee80211_hdr_1addr*)skb->data;
+
+	if (!pHTInfo->bCurrentHTSupport||!pHTInfo->bEnableHT)
+		return;
+	if (!IsQoSDataFrame(skb->data))
+		return;
+
+	if (is_multicast_ether_addr(hdr->addr1) || is_broadcast_ether_addr(hdr->addr1))
+		return;
+	//check packet and mode later
+#ifdef TO_DO_LIST
+	if(pTcb->PacketLength >= 4096)
+		return;
+	// For RTL819X, if pairwisekey = wep/tkip, we don't aggrregation.
+	if(!Adapter->HalFunc.GetNmodeSupportBySecCfgHandler(Adapter))
+		return;
+#endif
+
+	if(pHTInfo->IOTAction & HT_IOT_ACT_TX_NO_AGGREGATION)
+		return;
+
+#if 1
+	if(!ieee->GetNmodeSupportBySecCfg(ieee->dev))
+	{
+		return;
+	}
+#endif
+	if(pHTInfo->bCurrentAMPDUEnable)
+	{
+		if (!GetTs(ieee, (PTS_COMMON_INFO*)(&pTxTs), hdr->addr1, skb->priority, TX_DIR, true))
+		{
+			printk("===>can't get TS\n");
+			return;
+		}
+		if (pTxTs->TxAdmittedBARecord.bValid == false)
+		{
+			//as some AP will refuse our action frame until key handshake has been finished. WB
+			if (ieee->wpa_ie_len && (ieee->pairwise_key_type == KEY_TYPE_NA))
+			;
+			else
+			TsStartAddBaProcess(ieee, pTxTs);
+			goto FORCED_AGG_SETTING;
+		}
+		else if (pTxTs->bUsingBa == false)
+		{
+			if (SN_LESS(pTxTs->TxAdmittedBARecord.BaStartSeqCtrl.field.SeqNum, (pTxTs->TxCurSeq+1)%4096))
+				pTxTs->bUsingBa = true;
+			else
+				goto FORCED_AGG_SETTING;
+		}
+
+		if (ieee->iw_mode == IW_MODE_INFRA)
+		{
+			tcb_desc->bAMPDUEnable = true;
+			tcb_desc->ampdu_factor = pHTInfo->CurrentAMPDUFactor;
+			tcb_desc->ampdu_density = pHTInfo->CurrentMPDUDensity;
+		}
+	}
+FORCED_AGG_SETTING:
+	switch(pHTInfo->ForcedAMPDUMode )
+	{
+		case HT_AGG_AUTO:
+			break;
+
+		case HT_AGG_FORCE_ENABLE:
+			tcb_desc->bAMPDUEnable = true;
+			tcb_desc->ampdu_density = pHTInfo->ForcedMPDUDensity;
+			tcb_desc->ampdu_factor = pHTInfo->ForcedAMPDUFactor;
+			break;
+
+		case HT_AGG_FORCE_DISABLE:
+			tcb_desc->bAMPDUEnable = false;
+			tcb_desc->ampdu_density = 0;
+			tcb_desc->ampdu_factor = 0;
+			break;
+
+	}
+		return;
+}
+
+extern void ieee80211_qurey_ShortPreambleMode(struct ieee80211_device* ieee, cb_desc* tcb_desc)
+{
+	tcb_desc->bUseShortPreamble = false;
+	if (tcb_desc->data_rate == 2)
+	{//// 1M can only use Long Preamble. 11B spec
+		return;
+	}
+	else if (ieee->current_network.capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
+	{
+		tcb_desc->bUseShortPreamble = true;
+	}
+	return;
+}
+extern	void
+ieee80211_query_HTCapShortGI(struct ieee80211_device *ieee, cb_desc *tcb_desc)
+{
+	PRT_HIGH_THROUGHPUT		pHTInfo = ieee->pHTInfo;
+
+	tcb_desc->bUseShortGI 		= false;
+
+	if(!pHTInfo->bCurrentHTSupport||!pHTInfo->bEnableHT)
+		return;
+
+	if(pHTInfo->bForcedShortGI)
+	{
+		tcb_desc->bUseShortGI = true;
+		return;
+	}
+
+	if((pHTInfo->bCurBW40MHz==true) && pHTInfo->bCurShortGI40MHz)
+		tcb_desc->bUseShortGI = true;
+	else if((pHTInfo->bCurBW40MHz==false) && pHTInfo->bCurShortGI20MHz)
+		tcb_desc->bUseShortGI = true;
+}
+
+void ieee80211_query_BandwidthMode(struct ieee80211_device* ieee, cb_desc *tcb_desc)
+{
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+
+	tcb_desc->bPacketBW = false;
+
+	if(!pHTInfo->bCurrentHTSupport||!pHTInfo->bEnableHT)
+		return;
+
+	if(tcb_desc->bMulticast || tcb_desc->bBroadcast)
+		return;
+
+	if((tcb_desc->data_rate & 0x80)==0) // If using legacy rate, it shall use 20MHz channel.
+		return;
+	//BandWidthAutoSwitch is for auto switch to 20 or 40 in long distance
+	if(pHTInfo->bCurBW40MHz && pHTInfo->bCurTxBW40MHz && !ieee->bandwidth_auto_switch.bforced_tx20Mhz)
+		tcb_desc->bPacketBW = true;
+	return;
+}
+
+void ieee80211_query_protectionmode(struct ieee80211_device* ieee, cb_desc* tcb_desc, struct sk_buff* skb)
+{
+	// Common Settings
+	tcb_desc->bRTSSTBC			= false;
+	tcb_desc->bRTSUseShortGI		= false; // Since protection frames are always sent by legacy rate, ShortGI will never be used.
+	tcb_desc->bCTSEnable			= false; // Most of protection using RTS/CTS
+	tcb_desc->RTSSC				= 0;		// 20MHz: Don't care;  40MHz: Duplicate.
+	tcb_desc->bRTSBW			= false; // RTS frame bandwidth is always 20MHz
+
+	if(tcb_desc->bBroadcast || tcb_desc->bMulticast)//only unicast frame will use rts/cts
+		return;
+
+	if (is_broadcast_ether_addr(skb->data+16))  //check addr3 as infrastructure add3 is DA.
+		return;
+
+	if (ieee->mode < IEEE_N_24G) //b, g mode
+	{
+			// (1) RTS_Threshold is compared to the MPDU, not MSDU.
+			// (2) If there are more than one frag in  this MSDU, only the first frag uses protection frame.
+			//		Other fragments are protected by previous fragment.
+			//		So we only need to check the length of first fragment.
+		if (skb->len > ieee->rts)
+		{
+			tcb_desc->bRTSEnable = true;
+			tcb_desc->rts_rate = MGN_24M;
+		}
+		else if (ieee->current_network.buseprotection)
+		{
+			// Use CTS-to-SELF in protection mode.
+			tcb_desc->bRTSEnable = true;
+			tcb_desc->bCTSEnable = true;
+			tcb_desc->rts_rate = MGN_24M;
+		}
+		//otherwise return;
+		return;
+	}
+	else
+	{// 11n High throughput case.
+		PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
+		while (true)
+		{
+			//check IOT action
+			if(pHTInfo->IOTAction & HT_IOT_ACT_FORCED_CTS2SELF)
+			{
+				tcb_desc->bCTSEnable	= true;
+				tcb_desc->rts_rate  = 	MGN_24M;
+#if defined(RTL8192SE) || defined(RTL8192SU)
+				tcb_desc->bRTSEnable = false;
+#else
+				tcb_desc->bRTSEnable = true;
+#endif
+				break;
+			}
+			else if(pHTInfo->IOTAction & (HT_IOT_ACT_FORCED_RTS|HT_IOT_ACT_PURE_N_MODE))
+			{
+				tcb_desc->bRTSEnable = true;
+				tcb_desc->rts_rate  = 	MGN_24M;
+				break;
+			}
+			//check ERP protection
+			if (ieee->current_network.buseprotection)
+			{// CTS-to-SELF
+				tcb_desc->bRTSEnable = true;
+				tcb_desc->bCTSEnable = true;
+				tcb_desc->rts_rate = MGN_24M;
+				break;
+			}
+			//check HT op mode
+			if(pHTInfo->bCurrentHTSupport  && pHTInfo->bEnableHT)
+			{
+				u8 HTOpMode = pHTInfo->CurrentOpMode;
+				if((pHTInfo->bCurBW40MHz && (HTOpMode == 2 || HTOpMode == 3)) ||
+							(!pHTInfo->bCurBW40MHz && HTOpMode == 3) )
+				{
+					tcb_desc->rts_rate = MGN_24M; // Rate is 24Mbps.
+					tcb_desc->bRTSEnable = true;
+					break;
+				}
+			}
+			//check rts
+			if (skb->len > ieee->rts)
+			{
+				tcb_desc->rts_rate = MGN_24M; // Rate is 24Mbps.
+				tcb_desc->bRTSEnable = true;
+				break;
+			}
+			//to do list: check MIMO power save condition.
+			//check AMPDU aggregation for TXOP
+			if(tcb_desc->bAMPDUEnable)
+			{
+				tcb_desc->rts_rate = MGN_24M; // Rate is 24Mbps.
+				// According to 8190 design, firmware sends CF-End only if RTS/CTS is enabled. However, it degrads
+				// throughput around 10M, so we disable of this mechanism. 2007.08.03 by Emily
+				tcb_desc->bRTSEnable = false;
+				break;
+			}
+			// Totally no protection case!!
+			goto NO_PROTECTION;
+		}
+		}
+	// For test , CTS replace with RTS
+	if( 0 )
+	{
+		tcb_desc->bCTSEnable	= true;
+		tcb_desc->rts_rate = MGN_24M;
+		tcb_desc->bRTSEnable 	= true;
+	}
+	if (ieee->current_network.capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
+		tcb_desc->bUseShortPreamble = true;
+	if (ieee->mode == IW_MODE_MASTER)
+			goto NO_PROTECTION;
+	return;
+NO_PROTECTION:
+	tcb_desc->bRTSEnable	= false;
+	tcb_desc->bCTSEnable	= false;
+	tcb_desc->rts_rate		= 0;
+	tcb_desc->RTSSC		= 0;
+	tcb_desc->bRTSBW		= false;
+}
+
+
+void ieee80211_txrate_selectmode(struct ieee80211_device* ieee, cb_desc* tcb_desc)
+{
+#ifdef TO_DO_LIST
+	if(!IsDataFrame(pFrame))
+	{
+		pTcb->bTxDisableRateFallBack = TRUE;
+		pTcb->bTxUseDriverAssingedRate = TRUE;
+		pTcb->RATRIndex = 7;
+		return;
+	}
+
+	if(pMgntInfo->ForcedDataRate!= 0)
+	{
+		pTcb->bTxDisableRateFallBack = TRUE;
+		pTcb->bTxUseDriverAssingedRate = TRUE;
+		return;
+	}
+#endif
+	if(ieee->bTxDisableRateFallBack)
+		tcb_desc->bTxDisableRateFallBack = true;
+
+	if(ieee->bTxUseDriverAssingedRate)
+		tcb_desc->bTxUseDriverAssingedRate = true;
+	if(!tcb_desc->bTxDisableRateFallBack || !tcb_desc->bTxUseDriverAssingedRate)
+	{
+		if (ieee->iw_mode == IW_MODE_INFRA || ieee->iw_mode == IW_MODE_ADHOC)
+			tcb_desc->RATRIndex = 0;
+	}
+}
+
+void ieee80211_query_seqnum(struct ieee80211_device*ieee, struct sk_buff* skb, u8* dst)
+{
+	if (is_multicast_ether_addr(dst) || is_broadcast_ether_addr(dst))
+		return;
+	if (IsQoSDataFrame(skb->data)) //we deal qos data only
+	{
+		PTX_TS_RECORD pTS = NULL;
+		if (!GetTs(ieee, (PTS_COMMON_INFO*)(&pTS), dst, skb->priority, TX_DIR, true))
+		{
+			return;
+		}
+		pTS->TxCurSeq = (pTS->TxCurSeq+1)%4096;
+	}
+}
+
+int ieee80211_xmit(struct sk_buff *skb, struct net_device *dev)
+{
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0))
+	struct ieee80211_device *ieee = netdev_priv(dev);
+#else
+	struct ieee80211_device *ieee = (struct ieee80211_device *)dev->priv;
+#endif
+	struct ieee80211_txb *txb = NULL;
+	struct ieee80211_hdr_3addrqos *frag_hdr;
+	int i, bytes_per_frag, nr_frags, bytes_last_frag, frag_size;
+	unsigned long flags;
+	struct net_device_stats *stats = &ieee->stats;
+	int ether_type = 0, encrypt;
+	int bytes, fc, qos_ctl = 0, hdr_len;
+	struct sk_buff *skb_frag;
+	struct ieee80211_hdr_3addrqos header = { /* Ensure zero initialized */
+		.duration_id = 0,
+		.seq_ctl = 0,
+		.qos_ctl = 0
+	};
+	u8 dest[ETH_ALEN], src[ETH_ALEN];
+	int qos_actived = ieee->current_network.qos_data.active;
+
+	struct ieee80211_crypt_data* crypt;
+
+	cb_desc *tcb_desc;
+
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	/* If there is no driver handler to take the TXB, dont' bother
+	 * creating it... */
+	if ((!ieee->hard_start_xmit && !(ieee->softmac_features & IEEE_SOFTMAC_TX_QUEUE))||
+	   ((!ieee->softmac_data_hard_start_xmit && (ieee->softmac_features & IEEE_SOFTMAC_TX_QUEUE)))) {
+		printk(KERN_WARNING "%s: No xmit handler.\n",
+		       ieee->dev->name);
+		goto success;
+	}
+
+
+	if(likely(ieee->raw_tx == 0)){
+		if (unlikely(skb->len < SNAP_SIZE + sizeof(u16))) {
+			printk(KERN_WARNING "%s: skb too small (%d).\n",
+			ieee->dev->name, skb->len);
+			goto success;
+		}
+
+		memset(skb->cb, 0, sizeof(skb->cb));
+		ether_type = ntohs(((struct ethhdr *)skb->data)->h_proto);
+
+		crypt = ieee->crypt[ieee->tx_keyidx];
+
+		encrypt = !(ether_type == ETH_P_PAE && ieee->ieee802_1x) &&
+			ieee->host_encrypt && crypt && crypt->ops;
+
+		if (!encrypt && ieee->ieee802_1x &&
+		ieee->drop_unencrypted && ether_type != ETH_P_PAE) {
+			stats->tx_dropped++;
+			goto success;
+		}
+	#ifdef CONFIG_IEEE80211_DEBUG
+		if (crypt && !encrypt && ether_type == ETH_P_PAE) {
+			struct eapol *eap = (struct eapol *)(skb->data +
+				sizeof(struct ethhdr) - SNAP_SIZE - sizeof(u16));
+			IEEE80211_DEBUG_EAP("TX: IEEE 802.11 EAPOL frame: %s\n",
+				eap_get_type(eap->type));
+		}
+	#endif
+
+		/* Save source and destination addresses */
+		memcpy(&dest, skb->data, ETH_ALEN);
+		memcpy(&src, skb->data+ETH_ALEN, ETH_ALEN);
+
+                /* Advance the SKB to the start of the payload */
+                skb_pull(skb, sizeof(struct ethhdr));
+
+                /* Determine total amount of storage required for TXB packets */
+                bytes = skb->len + SNAP_SIZE + sizeof(u16);
+
+		if (encrypt)
+			fc = IEEE80211_FTYPE_DATA | IEEE80211_FCTL_WEP;
+		else
+
+                        fc = IEEE80211_FTYPE_DATA;
+
+		//if(ieee->current_network.QoS_Enable)
+		if(qos_actived)
+			fc |= IEEE80211_STYPE_QOS_DATA;
+		else
+			fc |= IEEE80211_STYPE_DATA;
+
+		if (ieee->iw_mode == IW_MODE_INFRA) {
+			fc |= IEEE80211_FCTL_TODS;
+			/* To DS: Addr1 = BSSID, Addr2 = SA,
+			Addr3 = DA */
+			memcpy(&header.addr1, ieee->current_network.bssid, ETH_ALEN);
+			memcpy(&header.addr2, &src, ETH_ALEN);
+			memcpy(&header.addr3, &dest, ETH_ALEN);
+		} else if (ieee->iw_mode == IW_MODE_ADHOC) {
+			/* not From/To DS: Addr1 = DA, Addr2 = SA,
+			Addr3 = BSSID */
+			memcpy(&header.addr1, dest, ETH_ALEN);
+			memcpy(&header.addr2, src, ETH_ALEN);
+			memcpy(&header.addr3, ieee->current_network.bssid, ETH_ALEN);
+		}
+
+                header.frame_ctl = cpu_to_le16(fc);
+
+		/* Determine fragmentation size based on destination (multicast
+		* and broadcast are not fragmented) */
+		if (is_multicast_ether_addr(header.addr1) ||
+		is_broadcast_ether_addr(header.addr1)) {
+			frag_size = MAX_FRAG_THRESHOLD;
+			qos_ctl |= QOS_CTL_NOTCONTAIN_ACK;
+		}
+		else {
+			frag_size = ieee->fts;//default:392
+			qos_ctl = 0;
+		}
+
+		//if (ieee->current_network.QoS_Enable)
+		if(qos_actived)
+		{
+			hdr_len = IEEE80211_3ADDR_LEN + 2;
+
+			skb->priority = ieee80211_classify(skb, &ieee->current_network);
+			qos_ctl |= skb->priority; //set in the ieee80211_classify
+			header.qos_ctl = cpu_to_le16(qos_ctl & IEEE80211_QOS_TID);
+		} else {
+			hdr_len = IEEE80211_3ADDR_LEN;
+		}
+		/* Determine amount of payload per fragment.  Regardless of if
+		* this stack is providing the full 802.11 header, one will
+		* eventually be affixed to this fragment -- so we must account for
+		* it when determining the amount of payload space. */
+		bytes_per_frag = frag_size - hdr_len;
+		if (ieee->config &
+		(CFG_IEEE80211_COMPUTE_FCS | CFG_IEEE80211_RESERVE_FCS))
+			bytes_per_frag -= IEEE80211_FCS_LEN;
+
+		/* Each fragment may need to have room for encryptiong pre/postfix */
+		if (encrypt)
+			bytes_per_frag -= crypt->ops->extra_prefix_len +
+				crypt->ops->extra_postfix_len;
+
+		/* Number of fragments is the total bytes_per_frag /
+		* payload_per_fragment */
+		nr_frags = bytes / bytes_per_frag;
+		bytes_last_frag = bytes % bytes_per_frag;
+		if (bytes_last_frag)
+			nr_frags++;
+		else
+			bytes_last_frag = bytes_per_frag;
+
+		/* When we allocate the TXB we allocate enough space for the reserve
+		* and full fragment bytes (bytes_per_frag doesn't include prefix,
+		* postfix, header, FCS, etc.) */
+		txb = ieee80211_alloc_txb(nr_frags, frag_size + ieee->tx_headroom, GFP_ATOMIC);
+		if (unlikely(!txb)) {
+			printk(KERN_WARNING "%s: Could not allocate TXB\n",
+			ieee->dev->name);
+			goto failed;
+		}
+		txb->encrypted = encrypt;
+		txb->payload_size = bytes;
+
+		//if (ieee->current_network.QoS_Enable)
+		if(qos_actived)
+		{
+			txb->queue_index = UP2AC(skb->priority);
+		} else {
+			txb->queue_index = WME_AC_BK;;
+		}
+
+
+
+		for (i = 0; i < nr_frags; i++) {
+			skb_frag = txb->fragments[i];
+			tcb_desc = (cb_desc *)(skb_frag->cb + MAX_DEV_ADDR_SIZE);
+			if(qos_actived){
+				skb_frag->priority = skb->priority;//UP2AC(skb->priority);
+				tcb_desc->queue_index =  UP2AC(skb->priority);
+			} else {
+				skb_frag->priority = WME_AC_BK;
+				tcb_desc->queue_index = WME_AC_BK;
+			}
+			skb_reserve(skb_frag, ieee->tx_headroom);
+
+			if (encrypt){
+				if (ieee->hwsec_active)
+					tcb_desc->bHwSec = 1;
+				else
+					tcb_desc->bHwSec = 0;
+				skb_reserve(skb_frag, crypt->ops->extra_prefix_len);
+			}
+			else
+			{
+				tcb_desc->bHwSec = 0;
+			}
+			frag_hdr = (struct ieee80211_hdr_3addrqos *)skb_put(skb_frag, hdr_len);
+			memcpy(frag_hdr, &header, hdr_len);
+
+			/* If this is not the last fragment, then add the MOREFRAGS
+			* bit to the frame control */
+			if (i != nr_frags - 1) {
+				frag_hdr->frame_ctl = cpu_to_le16(
+					fc | IEEE80211_FCTL_MOREFRAGS);
+				bytes = bytes_per_frag;
+
+			} else {
+				/* The last fragment takes the remaining length */
+				bytes = bytes_last_frag;
+			}
+			//if(ieee->current_network.QoS_Enable)
+			if(qos_actived)
+			{
+				// add 1 only indicate to corresponding seq number control 2006/7/12
+				frag_hdr->seq_ctl = cpu_to_le16(ieee->seq_ctrl[UP2AC(skb->priority)+1]<<4 | i);
+			} else {
+				frag_hdr->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0]<<4 | i);
+			}
+
+			/* Put a SNAP header on the first fragment */
+			if (i == 0) {
+				ieee80211_put_snap(
+					skb_put(skb_frag, SNAP_SIZE + sizeof(u16)),
+					ether_type);
+				bytes -= SNAP_SIZE + sizeof(u16);
+			}
+
+			memcpy(skb_put(skb_frag, bytes), skb->data, bytes);
+
+			/* Advance the SKB... */
+			skb_pull(skb, bytes);
+
+			/* Encryption routine will move the header forward in order
+			* to insert the IV between the header and the payload */
+			if (encrypt)
+				ieee80211_encrypt_fragment(ieee, skb_frag, hdr_len);
+			if (ieee->config &
+			(CFG_IEEE80211_COMPUTE_FCS | CFG_IEEE80211_RESERVE_FCS))
+				skb_put(skb_frag, 4);
+		}
+
+		if(qos_actived)
+		{
+		  if (ieee->seq_ctrl[UP2AC(skb->priority) + 1] == 0xFFF)
+			ieee->seq_ctrl[UP2AC(skb->priority) + 1] = 0;
+		  else
+			ieee->seq_ctrl[UP2AC(skb->priority) + 1]++;
+		} else {
+  		  if (ieee->seq_ctrl[0] == 0xFFF)
+			ieee->seq_ctrl[0] = 0;
+		  else
+			ieee->seq_ctrl[0]++;
+		}
+	}else{
+		if (unlikely(skb->len < sizeof(struct ieee80211_hdr_3addr))) {
+			printk(KERN_WARNING "%s: skb too small (%d).\n",
+			ieee->dev->name, skb->len);
+			goto success;
+		}
+
+		txb = ieee80211_alloc_txb(1, skb->len, GFP_ATOMIC);
+		if(!txb){
+			printk(KERN_WARNING "%s: Could not allocate TXB\n",
+			ieee->dev->name);
+			goto failed;
+		}
+
+		txb->encrypted = 0;
+		txb->payload_size = skb->len;
+		memcpy(skb_put(txb->fragments[0],skb->len), skb->data, skb->len);
+	}
+
+ success:
+//WB add to fill data tcb_desc here. only first fragment is considered, need to change, and you may remove to other place.
+	if (txb)
+	{
+#if 1
+		cb_desc *tcb_desc = (cb_desc *)(txb->fragments[0]->cb + MAX_DEV_ADDR_SIZE);
+		tcb_desc->bTxEnableFwCalcDur = 1;
+		if (is_multicast_ether_addr(header.addr1))
+			tcb_desc->bMulticast = 1;
+		if (is_broadcast_ether_addr(header.addr1))
+			tcb_desc->bBroadcast = 1;
+		ieee80211_txrate_selectmode(ieee, tcb_desc);
+		if ( tcb_desc->bMulticast ||  tcb_desc->bBroadcast)
+			tcb_desc->data_rate = ieee->basic_rate;
+		else
+			//tcb_desc->data_rate = CURRENT_RATE(ieee->current_network.mode, ieee->rate, ieee->HTCurrentOperaRate);
+			tcb_desc->data_rate = CURRENT_RATE(ieee->mode, ieee->rate, ieee->HTCurrentOperaRate);
+		ieee80211_qurey_ShortPreambleMode(ieee, tcb_desc);
+		ieee80211_tx_query_agg_cap(ieee, txb->fragments[0], tcb_desc);
+		ieee80211_query_HTCapShortGI(ieee, tcb_desc);
+		ieee80211_query_BandwidthMode(ieee, tcb_desc);
+		ieee80211_query_protectionmode(ieee, tcb_desc, txb->fragments[0]);
+		ieee80211_query_seqnum(ieee, txb->fragments[0], header.addr1);
+//		IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, txb->fragments[0]->data, txb->fragments[0]->len);
+		//IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, tcb_desc, sizeof(cb_desc));
+#endif
+	}
+	spin_unlock_irqrestore(&ieee->lock, flags);
+	dev_kfree_skb_any(skb);
+	if (txb) {
+		if (ieee->softmac_features & IEEE_SOFTMAC_TX_QUEUE){
+			ieee80211_softmac_xmit(txb, ieee);
+		}else{
+			if ((*ieee->hard_start_xmit)(txb, dev) == 0) {
+				stats->tx_packets++;
+				stats->tx_bytes += txb->payload_size;
+				return 0;
+			}
+			ieee80211_txb_free(txb);
+		}
+	}
+
+	return 0;
+
+ failed:
+	spin_unlock_irqrestore(&ieee->lock, flags);
+	netif_stop_queue(dev);
+	stats->tx_errors++;
+	return 1;
+
+}
+
+EXPORT_SYMBOL(ieee80211_txb_free);
diff --git a/drivers/staging/rtl8192su/ieee80211/ieee80211_wx.c b/drivers/staging/rtl8192su/ieee80211/ieee80211_wx.c
new file mode 100644
index 0000000..ae11e25
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/ieee80211_wx.c
@@ -0,0 +1,1032 @@
+/******************************************************************************
+
+  Copyright(c) 2004 Intel Corporation. All rights reserved.
+
+  Portions of this file are based on the WEP enablement code provided by the
+  Host AP project hostap-drivers v0.1.3
+  Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen
+  <jkmaline@cc.hut.fi>
+  Copyright (c) 2002-2003, Jouni Malinen <jkmaline@cc.hut.fi>
+
+  This program is free software; you can redistribute it and/or modify it
+  under the terms of version 2 of the GNU General Public License as
+  published by the Free Software Foundation.
+
+  This program is distributed in the hope that it will be useful, but WITHOUT
+  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+  more details.
+
+  You should have received a copy of the GNU General Public License along with
+  this program; if not, write to the Free Software Foundation, Inc., 59
+  Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+
+  The full GNU General Public License is included in this distribution in the
+  file called LICENSE.
+
+  Contact Information:
+  James P. Ketrenos <ipw2100-admin@linux.intel.com>
+  Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
+
+******************************************************************************/
+#include <linux/wireless.h>
+#include <linux/version.h>
+#include <linux/kmod.h>
+#include <linux/module.h>
+
+#include "ieee80211.h"
+#if 0
+static const char *ieee80211_modes[] = {
+	"?", "a", "b", "ab", "g", "ag", "bg", "abg"
+};
+#endif
+struct modes_unit {
+	char *mode_string;
+	int mode_size;
+};
+struct modes_unit ieee80211_modes[] = {
+	{"a",1},
+	{"b",1},
+	{"g",1},
+	{"?",1},
+	{"N-24G",5},
+	{"N-5G",4},
+};
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,4,20)) && (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+static inline char *
+iwe_stream_add_event_rsl(char *     stream,         /* Stream of events */
+                     char *     ends,           /* End of stream */
+                     struct iw_event *iwe,      /* Payload */
+                     int        event_len)      /* Real size of payload */
+{
+        /* Check if it's possible */
+        if((stream + event_len) < ends) {
+                iwe->len = event_len;
+		ndelay(1);   //new
+                memcpy(stream, (char *) iwe, event_len);
+                stream += event_len;
+        }
+        return stream;
+}
+#else
+#define iwe_stream_add_event_rsl iwe_stream_add_event
+#endif
+
+#define MAX_CUSTOM_LEN 64
+static inline char *rtl819x_translate_scan(struct ieee80211_device *ieee,
+ 					   char *start, char *stop,
+					   struct ieee80211_network *network,
+                                           struct iw_request_info *info)
+{
+	char custom[MAX_CUSTOM_LEN];
+	char proto_name[IFNAMSIZ];
+	char *pname = proto_name;
+	char *p;
+	struct iw_event iwe;
+	int i, j;
+	u16 max_rate, rate;
+	static u8	EWC11NHTCap[] = {0x00, 0x90, 0x4c, 0x33};
+
+	/* First entry *MUST* be the AP MAC address */
+	iwe.cmd = SIOCGIWAP;
+	iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
+	memcpy(iwe.u.ap_addr.sa_data, network->bssid, ETH_ALEN);
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+	start = iwe_stream_add_event_rsl(info, start, stop, &iwe, IW_EV_ADDR_LEN);
+#else
+	start = iwe_stream_add_event_rsl(start, stop, &iwe, IW_EV_ADDR_LEN);
+#endif
+	/* Remaining entries will be displayed in the order we provide them */
+
+	/* Add the ESSID */
+	iwe.cmd = SIOCGIWESSID;
+	iwe.u.data.flags = 1;
+//	if (network->flags & NETWORK_EMPTY_ESSID) {
+	if (network->ssid_len == 0) {
+		iwe.u.data.length = sizeof("<hidden>");
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+                start = iwe_stream_add_point(info, start, stop, &iwe, "<hidden>");
+#else
+                start = iwe_stream_add_point(start, stop, &iwe, "<hidden>");
+#endif
+        } else {
+		iwe.u.data.length = min(network->ssid_len, (u8)32);
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+                start = iwe_stream_add_point(info, start, stop, &iwe, network->ssid);
+#else
+                start = iwe_stream_add_point(start, stop, &iwe, network->ssid);
+#endif
+        }
+	/* Add the protocol name */
+	iwe.cmd = SIOCGIWNAME;
+	for(i=0; i<(sizeof(ieee80211_modes)/sizeof(ieee80211_modes[0])); i++) {
+		if(network->mode&(1<<i)) {
+			sprintf(pname,ieee80211_modes[i].mode_string,ieee80211_modes[i].mode_size);
+			pname +=ieee80211_modes[i].mode_size;
+		}
+	}
+	*pname = '\0';
+	snprintf(iwe.u.name, IFNAMSIZ, "IEEE802.11%s", proto_name);
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+        start = iwe_stream_add_event_rsl(info, start, stop, &iwe, IW_EV_CHAR_LEN);
+#else
+        start = iwe_stream_add_event_rsl(start, stop, &iwe, IW_EV_CHAR_LEN);
+#endif
+        /* Add mode */
+        iwe.cmd = SIOCGIWMODE;
+        if (network->capability &
+	    (WLAN_CAPABILITY_BSS | WLAN_CAPABILITY_IBSS)) {
+		if (network->capability & WLAN_CAPABILITY_BSS)
+			iwe.u.mode = IW_MODE_MASTER;
+		else
+			iwe.u.mode = IW_MODE_ADHOC;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+                start = iwe_stream_add_event_rsl(info, start, stop, &iwe, IW_EV_UINT_LEN);
+#else
+                start = iwe_stream_add_event_rsl(start, stop, &iwe, IW_EV_UINT_LEN);
+#endif
+        }
+
+        /* Add frequency/channel */
+	iwe.cmd = SIOCGIWFREQ;
+/*	iwe.u.freq.m = ieee80211_frequency(network->channel, network->mode);
+	iwe.u.freq.e = 3; */
+	iwe.u.freq.m = network->channel;
+	iwe.u.freq.e = 0;
+	iwe.u.freq.i = 0;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+        start = iwe_stream_add_event_rsl(info, start, stop, &iwe, IW_EV_FREQ_LEN);
+#else
+        start = iwe_stream_add_event_rsl(start, stop, &iwe, IW_EV_FREQ_LEN);
+#endif
+	/* Add encryption capability */
+	iwe.cmd = SIOCGIWENCODE;
+	if (network->capability & WLAN_CAPABILITY_PRIVACY)
+		iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
+	else
+		iwe.u.data.flags = IW_ENCODE_DISABLED;
+	iwe.u.data.length = 0;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+        start = iwe_stream_add_point(info, start, stop, &iwe, network->ssid);
+#else
+        start = iwe_stream_add_point(start, stop, &iwe, network->ssid);
+#endif
+	/* Add basic and extended rates */
+	max_rate = 0;
+	p = custom;
+	p += snprintf(p, MAX_CUSTOM_LEN - (p - custom), " Rates (Mb/s): ");
+	for (i = 0, j = 0; i < network->rates_len; ) {
+		if (j < network->rates_ex_len &&
+		    ((network->rates_ex[j] & 0x7F) <
+		     (network->rates[i] & 0x7F)))
+			rate = network->rates_ex[j++] & 0x7F;
+		else
+			rate = network->rates[i++] & 0x7F;
+		if (rate > max_rate)
+			max_rate = rate;
+		p += snprintf(p, MAX_CUSTOM_LEN - (p - custom),
+			      "%d%s ", rate >> 1, (rate & 1) ? ".5" : "");
+	}
+	for (; j < network->rates_ex_len; j++) {
+		rate = network->rates_ex[j] & 0x7F;
+		p += snprintf(p, MAX_CUSTOM_LEN - (p - custom),
+			      "%d%s ", rate >> 1, (rate & 1) ? ".5" : "");
+		if (rate > max_rate)
+			max_rate = rate;
+	}
+
+	if (network->mode >= IEEE_N_24G)//add N rate here;
+	{
+		PHT_CAPABILITY_ELE ht_cap = NULL;
+		bool is40M = false, isShortGI = false;
+		u8 max_mcs = 0;
+		if (!memcmp(network->bssht.bdHTCapBuf, EWC11NHTCap, 4))
+			ht_cap = (PHT_CAPABILITY_ELE)&network->bssht.bdHTCapBuf[4];
+		else
+			ht_cap = (PHT_CAPABILITY_ELE)&network->bssht.bdHTCapBuf[0];
+		is40M = (ht_cap->ChlWidth)?1:0;
+		isShortGI = (ht_cap->ChlWidth)?
+						((ht_cap->ShortGI40Mhz)?1:0):
+						((ht_cap->ShortGI20Mhz)?1:0);
+
+		max_mcs = HTGetHighestMCSRate(ieee, ht_cap->MCS, MCS_FILTER_ALL);
+		rate = MCS_DATA_RATE[is40M][isShortGI][max_mcs&0x7f];
+		if (rate > max_rate)
+			max_rate = rate;
+	}
+#if 0
+	printk("max rate:%d ===basic rate:\n", max_rate);
+	for (i=0;i<network->rates_len;i++)
+		printk(" %x", network->rates[i]);
+	printk("\n=======extend rate\n");
+	for (i=0; i<network->rates_ex_len; i++)
+		printk(" %x", network->rates_ex[i]);
+	printk("\n");
+#endif
+	iwe.cmd = SIOCGIWRATE;
+	iwe.u.bitrate.fixed = iwe.u.bitrate.disabled = 0;
+	iwe.u.bitrate.value = max_rate * 500000;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+        start = iwe_stream_add_event_rsl(info, start, stop, &iwe,
+				     IW_EV_PARAM_LEN);
+#else
+        start = iwe_stream_add_event_rsl(start, stop, &iwe,
+				     IW_EV_PARAM_LEN);
+#endif
+	iwe.cmd = IWEVCUSTOM;
+	iwe.u.data.length = p - custom;
+	if (iwe.u.data.length)
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+        start = iwe_stream_add_point(info, start, stop, &iwe, custom);
+#else
+        start = iwe_stream_add_point(start, stop, &iwe, custom);
+#endif
+	/* Add quality statistics */
+	/* TODO: Fix these values... */
+	iwe.cmd = IWEVQUAL;
+	iwe.u.qual.qual = network->stats.signal;
+	iwe.u.qual.level = network->stats.rssi;
+	iwe.u.qual.noise = network->stats.noise;
+	iwe.u.qual.updated = network->stats.mask & IEEE80211_STATMASK_WEMASK;
+	if (!(network->stats.mask & IEEE80211_STATMASK_RSSI))
+		iwe.u.qual.updated |= IW_QUAL_LEVEL_INVALID;
+	if (!(network->stats.mask & IEEE80211_STATMASK_NOISE))
+		iwe.u.qual.updated |= IW_QUAL_NOISE_INVALID;
+	if (!(network->stats.mask & IEEE80211_STATMASK_SIGNAL))
+		iwe.u.qual.updated |= IW_QUAL_QUAL_INVALID;
+	iwe.u.qual.updated = 7;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+        start = iwe_stream_add_event_rsl(info, start, stop, &iwe, IW_EV_QUAL_LEN);
+#else
+        start = iwe_stream_add_event_rsl(start, stop, &iwe, IW_EV_QUAL_LEN);
+#endif
+	iwe.cmd = IWEVCUSTOM;
+	p = custom;
+
+	iwe.u.data.length = p - custom;
+	if (iwe.u.data.length)
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+            start = iwe_stream_add_point(info, start, stop, &iwe, custom);
+#else
+            start = iwe_stream_add_point(start, stop, &iwe, custom);
+#endif
+#if (WIRELESS_EXT < 18)
+	if (ieee->wpa_enabled && network->wpa_ie_len){
+		char buf[MAX_WPA_IE_LEN * 2 + 30];
+	//	printk("WPA IE\n");
+		u8 *p = buf;
+		p += sprintf(p, "wpa_ie=");
+		for (i = 0; i < network->wpa_ie_len; i++) {
+			p += sprintf(p, "%02x", network->wpa_ie[i]);
+		}
+
+		memset(&iwe, 0, sizeof(iwe));
+		iwe.cmd = IWEVCUSTOM;
+		iwe.u.data.length = strlen(buf);
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+                start = iwe_stream_add_point(info, start, stop, &iwe, buf);
+#else
+                start = iwe_stream_add_point(start, stop, &iwe, buf);
+#endif
+        }
+
+	if (ieee->wpa_enabled && network->rsn_ie_len){
+		char buf[MAX_WPA_IE_LEN * 2 + 30];
+
+		u8 *p = buf;
+		p += sprintf(p, "rsn_ie=");
+		for (i = 0; i < network->rsn_ie_len; i++) {
+			p += sprintf(p, "%02x", network->rsn_ie[i]);
+		}
+
+		memset(&iwe, 0, sizeof(iwe));
+		iwe.cmd = IWEVCUSTOM;
+		iwe.u.data.length = strlen(buf);
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+                start = iwe_stream_add_point(info, start, stop, &iwe, buf);
+#else
+                start = iwe_stream_add_point(start, stop, &iwe, buf);
+#endif
+        }
+#else
+	memset(&iwe, 0, sizeof(iwe));
+	if (network->wpa_ie_len)
+	{
+		char buf[MAX_WPA_IE_LEN];
+		memcpy(buf, network->wpa_ie, network->wpa_ie_len);
+		iwe.cmd = IWEVGENIE;
+		iwe.u.data.length = network->wpa_ie_len;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+                start = iwe_stream_add_point(info, start, stop, &iwe, buf);
+#else
+                start = iwe_stream_add_point(start, stop, &iwe, buf);
+#endif
+        }
+	memset(&iwe, 0, sizeof(iwe));
+	if (network->rsn_ie_len)
+	{
+		char buf[MAX_WPA_IE_LEN];
+		memcpy(buf, network->rsn_ie, network->rsn_ie_len);
+		iwe.cmd = IWEVGENIE;
+		iwe.u.data.length = network->rsn_ie_len;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+                start = iwe_stream_add_point(info, start, stop, &iwe, buf);
+#else
+                start = iwe_stream_add_point(start, stop, &iwe, buf);
+#endif
+        }
+#endif
+
+
+	/* Add EXTRA: Age to display seconds since last beacon/probe response
+	 * for given network. */
+	iwe.cmd = IWEVCUSTOM;
+	p = custom;
+	p += snprintf(p, MAX_CUSTOM_LEN - (p - custom),
+		      " Last beacon: %lums ago", (jiffies - network->last_scanned) / (HZ / 100));
+	iwe.u.data.length = p - custom;
+	if (iwe.u.data.length)
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)
+            start = iwe_stream_add_point(info, start, stop, &iwe, custom);
+#else
+            start = iwe_stream_add_point(start, stop, &iwe, custom);
+#endif
+
+	return start;
+}
+
+int ieee80211_wx_get_scan(struct ieee80211_device *ieee,
+			  struct iw_request_info *info,
+			  union iwreq_data *wrqu, char *extra)
+{
+	struct ieee80211_network *network;
+	unsigned long flags;
+
+	char *ev = extra;
+//	char *stop = ev + IW_SCAN_MAX_DATA;
+	char *stop = ev + wrqu->data.length;//IW_SCAN_MAX_DATA;
+	//char *stop = ev + IW_SCAN_MAX_DATA;
+	int i = 0;
+	int err = 0;
+	IEEE80211_DEBUG_WX("Getting scan\n");
+	down(&ieee->wx_sem);
+	spin_lock_irqsave(&ieee->lock, flags);
+
+	list_for_each_entry(network, &ieee->network_list, list) {
+		i++;
+		if((stop-ev)<200)
+		{
+			err = -E2BIG;
+			break;
+												}
+		if (ieee->scan_age == 0 ||
+		    time_after(network->last_scanned + ieee->scan_age, jiffies))
+			ev = rtl819x_translate_scan(ieee, ev, stop, network, info);
+		else
+			IEEE80211_DEBUG_SCAN(
+				"Not showing network '%s ("
+				MAC_FMT ")' due to age (%lums).\n",
+				escape_essid(network->ssid,
+					     network->ssid_len),
+				MAC_ARG(network->bssid),
+				(jiffies - network->last_scanned) / (HZ / 100));
+	}
+
+	spin_unlock_irqrestore(&ieee->lock, flags);
+	up(&ieee->wx_sem);
+	wrqu->data.length = ev -  extra;
+	wrqu->data.flags = 0;
+
+	IEEE80211_DEBUG_WX("exit: %d networks returned.\n", i);
+
+	return err;
+}
+
+int ieee80211_wx_set_encode(struct ieee80211_device *ieee,
+			    struct iw_request_info *info,
+			    union iwreq_data *wrqu, char *keybuf)
+{
+	struct iw_point *erq = &(wrqu->encoding);
+	struct net_device *dev = ieee->dev;
+	struct ieee80211_security sec = {
+		.flags = 0
+	};
+	int i, key, key_provided, len;
+	struct ieee80211_crypt_data **crypt;
+
+	IEEE80211_DEBUG_WX("SET_ENCODE\n");
+
+	key = erq->flags & IW_ENCODE_INDEX;
+	if (key) {
+		if (key > WEP_KEYS)
+			return -EINVAL;
+		key--;
+		key_provided = 1;
+	} else {
+		key_provided = 0;
+		key = ieee->tx_keyidx;
+	}
+
+	IEEE80211_DEBUG_WX("Key: %d [%s]\n", key, key_provided ?
+			   "provided" : "default");
+	crypt = &ieee->crypt[key];
+
+	if (erq->flags & IW_ENCODE_DISABLED) {
+		if (key_provided && *crypt) {
+			IEEE80211_DEBUG_WX("Disabling encryption on key %d.\n",
+					   key);
+			ieee80211_crypt_delayed_deinit(ieee, crypt);
+		} else
+			IEEE80211_DEBUG_WX("Disabling encryption.\n");
+
+		/* Check all the keys to see if any are still configured,
+		 * and if no key index was provided, de-init them all */
+		for (i = 0; i < WEP_KEYS; i++) {
+			if (ieee->crypt[i] != NULL) {
+				if (key_provided)
+					break;
+				ieee80211_crypt_delayed_deinit(
+					ieee, &ieee->crypt[i]);
+			}
+		}
+
+		if (i == WEP_KEYS) {
+			sec.enabled = 0;
+			sec.level = SEC_LEVEL_0;
+			sec.flags |= SEC_ENABLED | SEC_LEVEL;
+		}
+
+		goto done;
+	}
+
+
+
+	sec.enabled = 1;
+	sec.flags |= SEC_ENABLED;
+
+	if (*crypt != NULL && (*crypt)->ops != NULL &&
+	    strcmp((*crypt)->ops->name, "WEP") != 0) {
+		/* changing to use WEP; deinit previously used algorithm
+		 * on this key */
+		ieee80211_crypt_delayed_deinit(ieee, crypt);
+	}
+
+	if (*crypt == NULL) {
+		struct ieee80211_crypt_data *new_crypt;
+
+		/* take WEP into use */
+		new_crypt = kmalloc(sizeof(struct ieee80211_crypt_data),
+				    GFP_KERNEL);
+		if (new_crypt == NULL)
+			return -ENOMEM;
+		memset(new_crypt, 0, sizeof(struct ieee80211_crypt_data));
+		new_crypt->ops = ieee80211_get_crypto_ops("WEP");
+		if (!new_crypt->ops) {
+			request_module("ieee80211_crypt_wep");
+			new_crypt->ops = ieee80211_get_crypto_ops("WEP");
+		}
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
+		if (new_crypt->ops && try_module_get(new_crypt->ops->owner))
+#else
+		if (new_crypt->ops && try_inc_mod_count(new_crypt->ops->owner))
+#endif
+			new_crypt->priv = new_crypt->ops->init(key);
+
+		if (!new_crypt->ops || !new_crypt->priv) {
+			kfree(new_crypt);
+			new_crypt = NULL;
+
+			printk(KERN_WARNING "%s: could not initialize WEP: "
+			       "load module ieee80211_crypt_wep\n",
+			       dev->name);
+			return -EOPNOTSUPP;
+		}
+		*crypt = new_crypt;
+	}
+
+	/* If a new key was provided, set it up */
+	if (erq->length > 0) {
+		len = erq->length <= 5 ? 5 : 13;
+		memcpy(sec.keys[key], keybuf, erq->length);
+		if (len > erq->length)
+			memset(sec.keys[key] + erq->length, 0,
+			       len - erq->length);
+		IEEE80211_DEBUG_WX("Setting key %d to '%s' (%d:%d bytes)\n",
+				   key, escape_essid(sec.keys[key], len),
+				   erq->length, len);
+		sec.key_sizes[key] = len;
+ 		(*crypt)->ops->set_key(sec.keys[key], len, NULL,
+				       (*crypt)->priv);
+		sec.flags |= (1 << key);
+		/* This ensures a key will be activated if no key is
+		 * explicitely set */
+		if (key == sec.active_key)
+			sec.flags |= SEC_ACTIVE_KEY;
+		ieee->tx_keyidx = key;
+
+	} else {
+		len = (*crypt)->ops->get_key(sec.keys[key], WEP_KEY_LEN,
+					     NULL, (*crypt)->priv);
+		if (len == 0) {
+			/* Set a default key of all 0 */
+			printk("Setting key %d to all zero.\n",
+					   key);
+
+			IEEE80211_DEBUG_WX("Setting key %d to all zero.\n",
+					   key);
+			memset(sec.keys[key], 0, 13);
+			(*crypt)->ops->set_key(sec.keys[key], 13, NULL,
+					       (*crypt)->priv);
+			sec.key_sizes[key] = 13;
+			sec.flags |= (1 << key);
+		}
+
+		/* No key data - just set the default TX key index */
+		if (key_provided) {
+			IEEE80211_DEBUG_WX(
+				"Setting key %d to default Tx key.\n", key);
+			ieee->tx_keyidx = key;
+			sec.active_key = key;
+			sec.flags |= SEC_ACTIVE_KEY;
+		}
+	}
+
+ done:
+	ieee->open_wep = !(erq->flags & IW_ENCODE_RESTRICTED);
+	ieee->auth_mode = ieee->open_wep ? WLAN_AUTH_OPEN : WLAN_AUTH_SHARED_KEY;
+	sec.auth_mode = ieee->open_wep ? WLAN_AUTH_OPEN : WLAN_AUTH_SHARED_KEY;
+	sec.flags |= SEC_AUTH_MODE;
+	IEEE80211_DEBUG_WX("Auth: %s\n", sec.auth_mode == WLAN_AUTH_OPEN ?
+			   "OPEN" : "SHARED KEY");
+
+	/* For now we just support WEP, so only set that security level...
+	 * TODO: When WPA is added this is one place that needs to change */
+	sec.flags |= SEC_LEVEL;
+	sec.level = SEC_LEVEL_1; /* 40 and 104 bit WEP */
+
+	if (ieee->set_security)
+		ieee->set_security(dev, &sec);
+
+	/* Do not reset port if card is in Managed mode since resetting will
+	 * generate new IEEE 802.11 authentication which may end up in looping
+	 * with IEEE 802.1X.  If your hardware requires a reset after WEP
+	 * configuration (for example... Prism2), implement the reset_port in
+	 * the callbacks structures used to initialize the 802.11 stack. */
+	if (ieee->reset_on_keychange &&
+	    ieee->iw_mode != IW_MODE_INFRA &&
+	    ieee->reset_port && ieee->reset_port(dev)) {
+		printk(KERN_DEBUG "%s: reset_port failed\n", dev->name);
+		return -EINVAL;
+	}
+	return 0;
+}
+
+int ieee80211_wx_get_encode(struct ieee80211_device *ieee,
+			    struct iw_request_info *info,
+			    union iwreq_data *wrqu, char *keybuf)
+{
+	struct iw_point *erq = &(wrqu->encoding);
+	int len, key;
+	struct ieee80211_crypt_data *crypt;
+
+	IEEE80211_DEBUG_WX("GET_ENCODE\n");
+
+	if(ieee->iw_mode == IW_MODE_MONITOR)
+		return -1;
+
+	key = erq->flags & IW_ENCODE_INDEX;
+	if (key) {
+		if (key > WEP_KEYS)
+			return -EINVAL;
+		key--;
+	} else
+		key = ieee->tx_keyidx;
+
+	crypt = ieee->crypt[key];
+	erq->flags = key + 1;
+
+	if (crypt == NULL || crypt->ops == NULL) {
+		erq->length = 0;
+		erq->flags |= IW_ENCODE_DISABLED;
+		return 0;
+	}
+#if 0
+	if (strcmp(crypt->ops->name, "WEP") != 0) {
+		/* only WEP is supported with wireless extensions, so just
+		 * report that encryption is used */
+		erq->length = 0;
+		erq->flags |= IW_ENCODE_ENABLED;
+		return 0;
+	}
+#endif
+	len = crypt->ops->get_key(keybuf, SCM_KEY_LEN, NULL, crypt->priv);
+	erq->length = (len >= 0 ? len : 0);
+
+	erq->flags |= IW_ENCODE_ENABLED;
+
+	if (ieee->open_wep)
+		erq->flags |= IW_ENCODE_OPEN;
+	else
+		erq->flags |= IW_ENCODE_RESTRICTED;
+
+	return 0;
+}
+#if (WIRELESS_EXT >= 18)
+int ieee80211_wx_set_encode_ext(struct ieee80211_device *ieee,
+                               struct iw_request_info *info,
+                               union iwreq_data *wrqu, char *extra)
+{
+	int ret = 0;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	struct net_device *dev = ieee->dev;
+        struct iw_point *encoding = &wrqu->encoding;
+        struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
+        int i, idx;
+        int group_key = 0;
+        const char *alg, *module;
+        struct ieee80211_crypto_ops *ops;
+        struct ieee80211_crypt_data **crypt;
+
+        struct ieee80211_security sec = {
+                .flags = 0,
+        };
+	//printk("======>encoding flag:%x,ext flag:%x, ext alg:%d\n", encoding->flags,ext->ext_flags, ext->alg);
+        idx = encoding->flags & IW_ENCODE_INDEX;
+        if (idx) {
+                if (idx < 1 || idx > WEP_KEYS)
+                        return -EINVAL;
+                idx--;
+        } else
+                idx = ieee->tx_keyidx;
+
+        if (ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY) {
+
+                crypt = &ieee->crypt[idx];
+
+                group_key = 1;
+        } else {
+                /* some Cisco APs use idx>0 for unicast in dynamic WEP */
+		//printk("not group key, flags:%x, ext->alg:%d\n", ext->ext_flags, ext->alg);
+                if (idx != 0 && ext->alg != IW_ENCODE_ALG_WEP)
+                        return -EINVAL;
+                if (ieee->iw_mode == IW_MODE_INFRA)
+
+                        crypt = &ieee->crypt[idx];
+
+                else
+                        return -EINVAL;
+        }
+
+        sec.flags |= SEC_ENABLED;// | SEC_ENCRYPT;
+        if ((encoding->flags & IW_ENCODE_DISABLED) ||
+            ext->alg == IW_ENCODE_ALG_NONE) {
+                if (*crypt)
+                        ieee80211_crypt_delayed_deinit(ieee, crypt);
+
+                for (i = 0; i < WEP_KEYS; i++)
+
+			if (ieee->crypt[i] != NULL)
+
+                                break;
+
+                if (i == WEP_KEYS) {
+                        sec.enabled = 0;
+                      //  sec.encrypt = 0;
+                        sec.level = SEC_LEVEL_0;
+                        sec.flags |= SEC_LEVEL;
+                }
+		//printk("disabled: flag:%x\n", encoding->flags);
+                goto done;
+        }
+
+	sec.enabled = 1;
+    //    sec.encrypt = 1;
+#if 0
+        if (group_key ? !ieee->host_mc_decrypt :
+            !(ieee->host_encrypt || ieee->host_decrypt ||
+              ieee->host_encrypt_msdu))
+                goto skip_host_crypt;
+#endif
+        switch (ext->alg) {
+        case IW_ENCODE_ALG_WEP:
+                alg = "WEP";
+                module = "ieee80211_crypt_wep";
+                break;
+        case IW_ENCODE_ALG_TKIP:
+                alg = "TKIP";
+                module = "ieee80211_crypt_tkip";
+                break;
+        case IW_ENCODE_ALG_CCMP:
+                alg = "CCMP";
+                module = "ieee80211_crypt_ccmp";
+                break;
+        default:
+                IEEE80211_DEBUG_WX("%s: unknown crypto alg %d\n",
+                                   dev->name, ext->alg);
+                ret = -EINVAL;
+                goto done;
+        }
+	printk("alg name:%s\n",alg);
+
+	 ops = ieee80211_get_crypto_ops(alg);
+        if (ops == NULL) {
+                request_module("%s", module);
+                ops = ieee80211_get_crypto_ops(alg);
+        }
+        if (ops == NULL) {
+                IEEE80211_DEBUG_WX("%s: unknown crypto alg %d\n",
+                                   dev->name, ext->alg);
+		printk("========>unknown crypto alg %d\n", ext->alg);
+                ret = -EINVAL;
+                goto done;
+        }
+
+        if (*crypt == NULL || (*crypt)->ops != ops) {
+                struct ieee80211_crypt_data *new_crypt;
+
+                ieee80211_crypt_delayed_deinit(ieee, crypt);
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,13))
+                new_crypt = kzalloc(sizeof(*new_crypt), GFP_KERNEL);
+#else
+                new_crypt = kmalloc(sizeof(*new_crypt), GFP_KERNEL);
+		memset(new_crypt,0,sizeof(*new_crypt));
+#endif
+                if (new_crypt == NULL) {
+                        ret = -ENOMEM;
+                        goto done;
+                }
+                new_crypt->ops = ops;
+                if (new_crypt->ops && try_module_get(new_crypt->ops->owner))
+                        new_crypt->priv = new_crypt->ops->init(idx);
+                if (new_crypt->priv == NULL) {
+                        kfree(new_crypt);
+                        ret = -EINVAL;
+                        goto done;
+                }
+                *crypt = new_crypt;
+
+ 	}
+
+        if (ext->key_len > 0 && (*crypt)->ops->set_key &&
+            (*crypt)->ops->set_key(ext->key, ext->key_len, ext->rx_seq,
+                                   (*crypt)->priv) < 0) {
+                IEEE80211_DEBUG_WX("%s: key setting failed\n", dev->name);
+		printk("key setting failed\n");
+                ret = -EINVAL;
+                goto done;
+        }
+#if 1
+ //skip_host_crypt:
+	//printk("skip_host_crypt:ext_flags:%x\n", ext->ext_flags);
+        if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY) {
+                ieee->tx_keyidx = idx;
+                sec.active_key = idx;
+                sec.flags |= SEC_ACTIVE_KEY;
+        }
+
+        if (ext->alg != IW_ENCODE_ALG_NONE) {
+                //memcpy(sec.keys[idx], ext->key, ext->key_len);
+                sec.key_sizes[idx] = ext->key_len;
+                sec.flags |= (1 << idx);
+                if (ext->alg == IW_ENCODE_ALG_WEP) {
+                      //  sec.encode_alg[idx] = SEC_ALG_WEP;
+                        sec.flags |= SEC_LEVEL;
+                        sec.level = SEC_LEVEL_1;
+                } else if (ext->alg == IW_ENCODE_ALG_TKIP) {
+                      //  sec.encode_alg[idx] = SEC_ALG_TKIP;
+                        sec.flags |= SEC_LEVEL;
+                        sec.level = SEC_LEVEL_2;
+                } else if (ext->alg == IW_ENCODE_ALG_CCMP) {
+                       // sec.encode_alg[idx] = SEC_ALG_CCMP;
+                        sec.flags |= SEC_LEVEL;
+                        sec.level = SEC_LEVEL_3;
+                }
+                /* Don't set sec level for group keys. */
+                if (group_key)
+                        sec.flags &= ~SEC_LEVEL;
+        }
+#endif
+done:
+        if (ieee->set_security)
+                ieee->set_security(ieee->dev, &sec);
+
+	 if (ieee->reset_on_keychange &&
+            ieee->iw_mode != IW_MODE_INFRA &&
+            ieee->reset_port && ieee->reset_port(dev)) {
+                IEEE80211_DEBUG_WX("%s: reset_port failed\n", dev->name);
+                return -EINVAL;
+        }
+#endif
+        return ret;
+}
+
+int ieee80211_wx_get_encode_ext(struct ieee80211_device *ieee,
+			       struct iw_request_info *info,
+			       union iwreq_data *wrqu, char *extra)
+{
+	struct iw_point *encoding = &wrqu->encoding;
+	struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
+	struct ieee80211_crypt_data *crypt;
+	int idx, max_key_len;
+
+	max_key_len = encoding->length - sizeof(*ext);
+	if (max_key_len < 0)
+		return -EINVAL;
+
+	idx = encoding->flags & IW_ENCODE_INDEX;
+	if (idx) {
+		if (idx < 1 || idx > WEP_KEYS)
+			return -EINVAL;
+		idx--;
+	} else
+		idx = ieee->tx_keyidx;
+
+	if (!(ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY) &&
+	    ext->alg != IW_ENCODE_ALG_WEP)
+		if (idx != 0 || ieee->iw_mode != IW_MODE_INFRA)
+			return -EINVAL;
+
+	crypt = ieee->crypt[idx];
+	encoding->flags = idx + 1;
+	memset(ext, 0, sizeof(*ext));
+
+	if (crypt == NULL || crypt->ops == NULL ) {
+		ext->alg = IW_ENCODE_ALG_NONE;
+		ext->key_len = 0;
+		encoding->flags |= IW_ENCODE_DISABLED;
+	} else {
+		if (strcmp(crypt->ops->name, "WEP") == 0 )
+			ext->alg = IW_ENCODE_ALG_WEP;
+		else if (strcmp(crypt->ops->name, "TKIP"))
+			ext->alg = IW_ENCODE_ALG_TKIP;
+		else if (strcmp(crypt->ops->name, "CCMP"))
+			ext->alg = IW_ENCODE_ALG_CCMP;
+		else
+			return -EINVAL;
+		ext->key_len = crypt->ops->get_key(ext->key, SCM_KEY_LEN, NULL, crypt->priv);
+		encoding->flags |= IW_ENCODE_ENABLED;
+		if (ext->key_len &&
+		    (ext->alg == IW_ENCODE_ALG_TKIP ||
+		     ext->alg == IW_ENCODE_ALG_CCMP))
+			ext->ext_flags |= IW_ENCODE_EXT_TX_SEQ_VALID;
+
+	}
+
+	return 0;
+}
+
+int ieee80211_wx_set_mlme(struct ieee80211_device *ieee,
+                               struct iw_request_info *info,
+                               union iwreq_data *wrqu, char *extra)
+{
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	struct iw_mlme *mlme = (struct iw_mlme *) extra;
+	switch (mlme->cmd) {
+        case IW_MLME_DEAUTH:
+	case IW_MLME_DISASSOC:
+		ieee80211_disassociate(ieee);
+		break;
+	 default:
+                return -EOPNOTSUPP;
+        }
+#endif
+	return 0;
+}
+
+int ieee80211_wx_set_auth(struct ieee80211_device *ieee,
+                               struct iw_request_info *info,
+                               struct iw_param *data, char *extra)
+{
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	switch (data->flags & IW_AUTH_INDEX) {
+        case IW_AUTH_WPA_VERSION:
+	     /*need to support wpa2 here*/
+		//printk("wpa version:%x\n", data->value);
+		break;
+        case IW_AUTH_CIPHER_PAIRWISE:
+        case IW_AUTH_CIPHER_GROUP:
+        case IW_AUTH_KEY_MGMT:
+                /*
+ *                  * Host AP driver does not use these parameters and allows
+ *                                   * wpa_supplicant to control them internally.
+ *                                                    */
+                break;
+        case IW_AUTH_TKIP_COUNTERMEASURES:
+                ieee->tkip_countermeasures = data->value;
+                break;
+        case IW_AUTH_DROP_UNENCRYPTED:
+                ieee->drop_unencrypted = data->value;
+		break;
+
+	case IW_AUTH_80211_AUTH_ALG:
+		//printk("======>%s():data->value is %d\n",__FUNCTION__,data->value);
+	//	ieee->open_wep = (data->value&IW_AUTH_ALG_OPEN_SYSTEM)?1:0;
+		if(data->value & IW_AUTH_ALG_SHARED_KEY){
+			ieee->open_wep = 0;
+			ieee->auth_mode = 1;
+		}
+		else if(data->value & IW_AUTH_ALG_OPEN_SYSTEM){
+			ieee->open_wep = 1;
+			ieee->auth_mode = 0;
+		}
+		else if(data->value & IW_AUTH_ALG_LEAP){
+			ieee->open_wep = 1;
+			ieee->auth_mode = 2;
+			//printk("hahahaa:LEAP\n");
+		}
+		else
+			return -EINVAL;
+		//printk("open_wep:%d\n", ieee->open_wep);
+		break;
+
+#if 1
+	case IW_AUTH_WPA_ENABLED:
+		ieee->wpa_enabled = (data->value)?1:0;
+		//printk("enalbe wpa:%d\n", ieee->wpa_enabled);
+		break;
+
+#endif
+	case IW_AUTH_RX_UNENCRYPTED_EAPOL:
+                ieee->ieee802_1x = data->value;
+		break;
+	case IW_AUTH_PRIVACY_INVOKED:
+		ieee->privacy_invoked = data->value;
+		break;
+	default:
+                return -EOPNOTSUPP;
+	}
+#endif
+	return 0;
+}
+#endif
+#if 1
+int ieee80211_wx_set_gen_ie(struct ieee80211_device *ieee, u8 *ie, size_t len)
+{
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+#if 0
+	printk("====>%s()\n", __FUNCTION__);
+	{
+		int i;
+		for (i=0; i<len; i++)
+		printk("%2x ", ie[i]&0xff);
+		printk("\n");
+	}
+#endif
+	u8 *buf;
+
+	if (len>MAX_WPA_IE_LEN || (len && ie == NULL))
+	{
+	//	printk("return error out, len:%d\n", len);
+	return -EINVAL;
+	}
+
+
+	if (len)
+	{
+		if (len != ie[1]+2)
+		{
+			printk("len:%d, ie:%d\n", len, ie[1]);
+			return -EINVAL;
+		}
+		buf = kmalloc(len, GFP_KERNEL);
+		if (buf == NULL)
+			return -ENOMEM;
+		memcpy(buf, ie, len);
+		kfree(ieee->wpa_ie);
+		ieee->wpa_ie = buf;
+		ieee->wpa_ie_len = len;
+	}
+	else{
+		if (ieee->wpa_ie)
+		kfree(ieee->wpa_ie);
+		ieee->wpa_ie = NULL;
+		ieee->wpa_ie_len = 0;
+	}
+#endif
+	return 0;
+
+}
+#endif
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+EXPORT_SYMBOL(ieee80211_wx_set_gen_ie);
+#if (WIRELESS_EXT >= 18)
+EXPORT_SYMBOL(ieee80211_wx_set_mlme);
+EXPORT_SYMBOL(ieee80211_wx_set_auth);
+EXPORT_SYMBOL(ieee80211_wx_set_encode_ext);
+EXPORT_SYMBOL(ieee80211_wx_get_encode_ext);
+#endif
+EXPORT_SYMBOL(ieee80211_wx_get_scan);
+EXPORT_SYMBOL(ieee80211_wx_set_encode);
+EXPORT_SYMBOL(ieee80211_wx_get_encode);
+#else
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_gen_ie);
+//EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_mlme);
+//EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_auth);
+//EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_encode_ext);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_get_scan);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_set_encode);
+EXPORT_SYMBOL_NOVERS(ieee80211_wx_get_encode);
+#endif
diff --git a/drivers/staging/rtl8192su/ieee80211/internal.h b/drivers/staging/rtl8192su/ieee80211/internal.h
new file mode 100644
index 0000000..ddc2235
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/internal.h
@@ -0,0 +1,115 @@
+/*
+ * Cryptographic API.
+ *
+ * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ */
+#ifndef _CRYPTO_INTERNAL_H
+#define _CRYPTO_INTERNAL_H
+
+
+//#include <linux/crypto.h>
+#include "rtl_crypto.h"
+#include <linux/mm.h>
+#include <linux/highmem.h>
+#include <linux/init.h>
+#include <asm/hardirq.h>
+#include <asm/softirq.h>
+#include <asm/kmap_types.h>
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,4,20))
+#define list_for_each_entry(pos, head, member)				\
+	for (pos = list_entry((head)->next, typeof(*pos), member),	\
+		     prefetch(pos->member.next);			\
+	     &pos->member != (head); 					\
+	     pos = list_entry(pos->member.next, typeof(*pos), member),	\
+		     prefetch(pos->member.next))
+
+static inline void cond_resched(void)
+{
+	if (need_resched()) {
+		set_current_state(TASK_RUNNING);
+		schedule();
+	}
+}
+#endif
+
+extern enum km_type crypto_km_types[];
+
+static inline enum km_type crypto_kmap_type(int out)
+{
+	return crypto_km_types[(in_softirq() ? 2 : 0) + out];
+}
+
+static inline void *crypto_kmap(struct page *page, int out)
+{
+	return kmap_atomic(page, crypto_kmap_type(out));
+}
+
+static inline void crypto_kunmap(void *vaddr, int out)
+{
+	kunmap_atomic(vaddr, crypto_kmap_type(out));
+}
+
+static inline void crypto_yield(struct crypto_tfm *tfm)
+{
+	if (!in_softirq())
+		cond_resched();
+}
+
+static inline void *crypto_tfm_ctx(struct crypto_tfm *tfm)
+{
+	return (void *)&tfm[1];
+}
+
+struct crypto_alg *crypto_alg_lookup(const char *name);
+
+#ifdef CONFIG_KMOD
+void crypto_alg_autoload(const char *name);
+struct crypto_alg *crypto_alg_mod_lookup(const char *name);
+#else
+static inline struct crypto_alg *crypto_alg_mod_lookup(const char *name)
+{
+	return crypto_alg_lookup(name);
+}
+#endif
+
+#ifdef CONFIG_CRYPTO_HMAC
+int crypto_alloc_hmac_block(struct crypto_tfm *tfm);
+void crypto_free_hmac_block(struct crypto_tfm *tfm);
+#else
+static inline int crypto_alloc_hmac_block(struct crypto_tfm *tfm)
+{
+	return 0;
+}
+
+static inline void crypto_free_hmac_block(struct crypto_tfm *tfm)
+{ }
+#endif
+
+#ifdef CONFIG_PROC_FS
+void __init crypto_init_proc(void);
+#else
+static inline void crypto_init_proc(void)
+{ }
+#endif
+
+int crypto_init_digest_flags(struct crypto_tfm *tfm, u32 flags);
+int crypto_init_cipher_flags(struct crypto_tfm *tfm, u32 flags);
+int crypto_init_compress_flags(struct crypto_tfm *tfm, u32 flags);
+
+int crypto_init_digest_ops(struct crypto_tfm *tfm);
+int crypto_init_cipher_ops(struct crypto_tfm *tfm);
+int crypto_init_compress_ops(struct crypto_tfm *tfm);
+
+void crypto_exit_digest_ops(struct crypto_tfm *tfm);
+void crypto_exit_cipher_ops(struct crypto_tfm *tfm);
+void crypto_exit_compress_ops(struct crypto_tfm *tfm);
+
+#endif	/* _CRYPTO_INTERNAL_H */
+
diff --git a/drivers/staging/rtl8192su/ieee80211/kmap_types.h b/drivers/staging/rtl8192su/ieee80211/kmap_types.h
new file mode 100644
index 0000000..de67bb0
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/kmap_types.h
@@ -0,0 +1,20 @@
+#ifndef __KMAP_TYPES_H
+
+#define __KMAP_TYPES_H
+
+
+enum km_type {
+	KM_BOUNCE_READ,
+	KM_SKB_SUNRPC_DATA,
+	KM_SKB_DATA_SOFTIRQ,
+	KM_USER0,
+	KM_USER1,
+	KM_BH_IRQ,
+	KM_SOFTIRQ0,
+	KM_SOFTIRQ1,
+	KM_TYPE_NR
+};
+
+#define _ASM_KMAP_TYPES_H
+
+#endif
diff --git a/drivers/staging/rtl8192su/ieee80211/michael_mic.c b/drivers/staging/rtl8192su/ieee80211/michael_mic.c
new file mode 100644
index 0000000..df256e4
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/michael_mic.c
@@ -0,0 +1,194 @@
+/*
+ * Cryptographic API
+ *
+ * Michael MIC (IEEE 802.11i/TKIP) keyed digest
+ *
+ * Copyright (c) 2004 Jouni Malinen <jkmaline@cc.hut.fi>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ */
+
+#include <linux/init.h>
+#include <linux/module.h>
+#include <linux/string.h>
+//#include <linux/crypto.h>
+#include "rtl_crypto.h"
+
+
+struct michael_mic_ctx {
+	u8 pending[4];
+	size_t pending_len;
+
+	u32 l, r;
+};
+
+
+static inline u32 rotl(u32 val, int bits)
+{
+	return (val << bits) | (val >> (32 - bits));
+}
+
+
+static inline u32 rotr(u32 val, int bits)
+{
+	return (val >> bits) | (val << (32 - bits));
+}
+
+
+static inline u32 xswap(u32 val)
+{
+	return ((val & 0x00ff00ff) << 8) | ((val & 0xff00ff00) >> 8);
+}
+
+
+#define michael_block(l, r)	\
+do {				\
+	r ^= rotl(l, 17);	\
+	l += r;			\
+	r ^= xswap(l);		\
+	l += r;			\
+	r ^= rotl(l, 3);	\
+	l += r;			\
+	r ^= rotr(l, 2);	\
+	l += r;			\
+} while (0)
+
+
+static inline u32 get_le32(const u8 *p)
+{
+	return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
+}
+
+
+static inline void put_le32(u8 *p, u32 v)
+{
+	p[0] = v;
+	p[1] = v >> 8;
+	p[2] = v >> 16;
+	p[3] = v >> 24;
+}
+
+
+static void michael_init(void *ctx)
+{
+	struct michael_mic_ctx *mctx = ctx;
+	mctx->pending_len = 0;
+}
+
+
+static void michael_update(void *ctx, const u8 *data, unsigned int len)
+{
+	struct michael_mic_ctx *mctx = ctx;
+
+	if (mctx->pending_len) {
+		int flen = 4 - mctx->pending_len;
+		if (flen > len)
+			flen = len;
+		memcpy(&mctx->pending[mctx->pending_len], data, flen);
+		mctx->pending_len += flen;
+		data += flen;
+		len -= flen;
+
+		if (mctx->pending_len < 4)
+			return;
+
+		mctx->l ^= get_le32(mctx->pending);
+		michael_block(mctx->l, mctx->r);
+		mctx->pending_len = 0;
+	}
+
+	while (len >= 4) {
+		mctx->l ^= get_le32(data);
+		michael_block(mctx->l, mctx->r);
+		data += 4;
+		len -= 4;
+	}
+
+	if (len > 0) {
+		mctx->pending_len = len;
+		memcpy(mctx->pending, data, len);
+	}
+}
+
+
+static void michael_final(void *ctx, u8 *out)
+{
+	struct michael_mic_ctx *mctx = ctx;
+	u8 *data = mctx->pending;
+
+	/* Last block and padding (0x5a, 4..7 x 0) */
+	switch (mctx->pending_len) {
+	case 0:
+		mctx->l ^= 0x5a;
+		break;
+	case 1:
+		mctx->l ^= data[0] | 0x5a00;
+		break;
+	case 2:
+		mctx->l ^= data[0] | (data[1] << 8) | 0x5a0000;
+		break;
+	case 3:
+		mctx->l ^= data[0] | (data[1] << 8) | (data[2] << 16) |
+			0x5a000000;
+		break;
+	}
+	michael_block(mctx->l, mctx->r);
+	/* l ^= 0; */
+	michael_block(mctx->l, mctx->r);
+
+	put_le32(out, mctx->l);
+	put_le32(out + 4, mctx->r);
+}
+
+
+static int michael_setkey(void *ctx, const u8 *key, unsigned int keylen,
+			  u32 *flags)
+{
+	struct michael_mic_ctx *mctx = ctx;
+	if (keylen != 8) {
+		if (flags)
+			*flags = CRYPTO_TFM_RES_BAD_KEY_LEN;
+		return -EINVAL;
+	}
+	mctx->l = get_le32(key);
+	mctx->r = get_le32(key + 4);
+	return 0;
+}
+
+
+static struct crypto_alg michael_mic_alg = {
+	.cra_name	= "michael_mic",
+	.cra_flags	= CRYPTO_ALG_TYPE_DIGEST,
+	.cra_blocksize	= 8,
+	.cra_ctxsize	= sizeof(struct michael_mic_ctx),
+	.cra_module	= THIS_MODULE,
+	.cra_list	= LIST_HEAD_INIT(michael_mic_alg.cra_list),
+	.cra_u		= { .digest = {
+	.dia_digestsize	= 8,
+	.dia_init	= michael_init,
+	.dia_update	= michael_update,
+	.dia_final	= michael_final,
+	.dia_setkey	= michael_setkey } }
+};
+
+
+static int __init michael_mic_init(void)
+{
+	return crypto_register_alg(&michael_mic_alg);
+}
+
+
+static void __exit michael_mic_exit(void)
+{
+	crypto_unregister_alg(&michael_mic_alg);
+}
+
+
+module_init(michael_mic_init);
+module_exit(michael_mic_exit);
+
+MODULE_LICENSE("GPL v2");
+MODULE_DESCRIPTION("Michael MIC");
+MODULE_AUTHOR("Jouni Malinen <jkmaline@cc.hut.fi>");
diff --git a/drivers/staging/rtl8192su/ieee80211/proc.c b/drivers/staging/rtl8192su/ieee80211/proc.c
new file mode 100644
index 0000000..4f3f9ed
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/proc.c
@@ -0,0 +1,116 @@
+/*
+ * Scatterlist Cryptographic API.
+ *
+ * Procfs information.
+ *
+ * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ */
+#include <linux/init.h>
+//#include <linux/crypto.h>
+#include "rtl_crypto.h"
+#include <linux/rwsem.h>
+#include <linux/proc_fs.h>
+#include <linux/seq_file.h>
+#include "internal.h"
+
+extern struct list_head crypto_alg_list;
+extern struct rw_semaphore crypto_alg_sem;
+
+static void *c_start(struct seq_file *m, loff_t *pos)
+{
+	struct list_head *v;
+	loff_t n = *pos;
+
+	down_read(&crypto_alg_sem);
+	list_for_each(v, &crypto_alg_list)
+		if (!n--)
+			return list_entry(v, struct crypto_alg, cra_list);
+	return NULL;
+}
+
+static void *c_next(struct seq_file *m, void *p, loff_t *pos)
+{
+	struct list_head *v = p;
+
+	(*pos)++;
+	v = v->next;
+	return (v == &crypto_alg_list) ?
+		NULL : list_entry(v, struct crypto_alg, cra_list);
+}
+
+static void c_stop(struct seq_file *m, void *p)
+{
+	up_read(&crypto_alg_sem);
+}
+
+static int c_show(struct seq_file *m, void *p)
+{
+	struct crypto_alg *alg = (struct crypto_alg *)p;
+
+	seq_printf(m, "name         : %s\n", alg->cra_name);
+	seq_printf(m, "module       : %s\n",
+		   (alg->cra_module ?
+		    alg->cra_module->name :
+		    "kernel"));
+
+	switch (alg->cra_flags & CRYPTO_ALG_TYPE_MASK) {
+	case CRYPTO_ALG_TYPE_CIPHER:
+		seq_printf(m, "type         : cipher\n");
+		seq_printf(m, "blocksize    : %u\n", alg->cra_blocksize);
+		seq_printf(m, "min keysize  : %u\n",
+					alg->cra_cipher.cia_min_keysize);
+		seq_printf(m, "max keysize  : %u\n",
+					alg->cra_cipher.cia_max_keysize);
+		break;
+
+	case CRYPTO_ALG_TYPE_DIGEST:
+		seq_printf(m, "type         : digest\n");
+		seq_printf(m, "blocksize    : %u\n", alg->cra_blocksize);
+		seq_printf(m, "digestsize   : %u\n",
+		           alg->cra_digest.dia_digestsize);
+		break;
+	case CRYPTO_ALG_TYPE_COMPRESS:
+		seq_printf(m, "type         : compression\n");
+		break;
+	default:
+		seq_printf(m, "type         : unknown\n");
+		break;
+	}
+
+	seq_putc(m, '\n');
+	return 0;
+}
+
+static struct seq_operations crypto_seq_ops = {
+	.start		= c_start,
+	.next		= c_next,
+	.stop		= c_stop,
+	.show		= c_show
+};
+
+static int crypto_info_open(struct inode *inode, struct file *file)
+{
+	return seq_open(file, &crypto_seq_ops);
+}
+
+static struct file_operations proc_crypto_ops = {
+	.open		= crypto_info_open,
+	.read		= seq_read,
+	.llseek		= seq_lseek,
+	.release	= seq_release
+};
+
+void __init crypto_init_proc(void)
+{
+	struct proc_dir_entry *proc;
+
+	proc = create_proc_entry("crypto", 0, NULL);
+	if (proc)
+		proc->proc_fops = &proc_crypto_ops;
+}
diff --git a/drivers/staging/rtl8192su/ieee80211/readme b/drivers/staging/rtl8192su/ieee80211/readme
new file mode 100644
index 0000000..5764f28
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/readme
@@ -0,0 +1,162 @@
+What this layer should do
+
+- It mantain the old mechanism as alternative, so the
+  ipw2100 driver works with really few changes.
+- Encapsulate / Decapsulate ieee80211 packet
+- Handle fragmentation
+- Optionally provide an alterantive mechanism for netif queue stop/wake,
+  so that the ieee80211 layer will pass one fragment per time instead of
+  one txb struct per time. so the driver can stop the queue in the middle
+  of a packet.
+- Provide two different TX interfaces for cards that can handle management
+  frames on one HW queue, and data on another, and for cards that have only
+  one HW queue  (the latter untested and very, very rough).
+- Optionally provide the logic for handling IBSS/MASTER/MONITOR/BSS modes
+  and for the channel, essid and wap get/set wireless extension requests.
+  so that the driver has only to change channel when the ieee stack tell it.
+- Optionally provide a scanning mechanism so that the driver has not to
+  worry about this, just implement the set channel calback and pass
+  frames to the upper layer
+- Optionally provide the bss client protocol handshaking (just with open
+  authentication)
+- Optionally provide the probe request send mechanism
+- Optionally provide the bss master mode logic to handle association
+  protocol (only open authentication) and probe responses.
+- SW wep encryption (with open authentication)
+- It collects some stats
+- It provides beacons to the card when it ask for them
+
+What this layer doesn't do (yet)
+- Perform shared authentication
+- Have full support for master mode (the AP should loop back in the air
+  frames from an associated client to another. This could be done easily
+  with few lines of code, and it is done in my previous version of the
+  stach, but a table of association must be keept and a disassociation
+  policy must be decided and implemented.
+- Handle cleanly the full ieee 802.11 protocol. In AP mode it never
+  disassociate clients, and it is really prone to always allow access.
+  In bss client mode it is a bit rough with AP deauth and disassoc requests.
+- It has not any entry point to view the collected stats.
+- Altought it takes care of the card supported rates in the management frame
+  it sends, support for rate changing on TXed packet is not complete.
+- Give up once associated in bss client mode (it never detect a
+  signal loss condition to disassociate and restart scanning)
+- Provide a mechanism for enabling the TX in monitor mode, so
+  userspace programs can TX raw packets.
+- Provide a mechanism for cards that need that the SW take care of beacon
+  TX completely, in sense that the SW has to enqueue by itself beacons
+  to the card so it TX them (if any...)
+APIs
+
+Callback functions in the original stack has been mantained.
+following has been added (from ieee80211.h)
+
+	/* Softmac-generated frames (mamagement) are TXed via this
+	 * callback if the flag IEEE_SOFTMAC_SINGLE_QUEUE is
+	 * not set. As some cards may have different HW queues that
+	 * one might want to use for data and management frames
+	 * the option to have two callbacks might be useful.
+	 * This fucntion can't sleep.
+	 */
+	int (*softmac_hard_start_xmit)(struct sk_buff *skb,
+			       struct net_device *dev);
+
+	/* used instead of hard_start_xmit (not softmac_hard_start_xmit)
+	 * if the IEEE_SOFTMAC_TX_QUEUE feature is used to TX data
+	 * frames. I the option IEEE_SOFTMAC_SINGLE_QUEUE is also set
+	 * then also management frames are sent via this callback.
+	 * This function can't sleep.
+	 */
+	void (*softmac_data_hard_start_xmit)(struct sk_buff *skb,
+			       struct net_device *dev);
+
+	/* stops the HW queue for DATA frames. Useful to avoid
+	 * waste time to TX data frame when we are reassociating
+	 * This function can sleep.
+	 */
+	void (*data_hard_stop)(struct net_device *dev);
+
+	/* OK this is complementar to data_poll_hard_stop */
+	void (*data_hard_resume)(struct net_device *dev);
+
+	/* ask to the driver to retune the radio .
+	 * This function can sleep. the driver should ensure
+	 * the radio has been swithced before return.
+	 */
+	void (*set_chan)(struct net_device *dev,short ch);
+
+	/* These are not used if the ieee stack takes care of
+	 * scanning (IEEE_SOFTMAC_SCAN feature set).
+	 * In this case only the set_chan is used.
+	 *
+	 * The syncro version is similar to the start_scan but
+	 * does not return until all channels has been scanned.
+	 * this is called in user context and should sleep,
+	 * it is called in a work_queue when swithcing to ad-hoc mode
+	 * or in behalf of iwlist scan when the card is associated
+	 * and root user ask for a scan.
+	 * the fucntion stop_scan should stop both the syncro and
+	 * background scanning and can sleep.
+	 * The fucntion start_scan should initiate the background
+	 * scanning and can't sleep.
+	 */
+	void (*scan_syncro)(struct net_device *dev);
+	void (*start_scan)(struct net_device *dev);
+	void (*stop_scan)(struct net_device *dev);
+
+	/* indicate the driver that the link state is changed
+	 * for example it may indicate the card is associated now.
+	 * Driver might be interested in this to apply RX filter
+	 * rules or simply light the LINK led
+	 */
+	void (*link_change)(struct net_device *dev);
+
+Functions hard_data_[resume/stop] are optional and should not be used
+if the driver decides to uses data+management frames enqueue in a
+single HQ queue (thus using just the softmac_hard_data_start_xmit
+callback).
+
+Function that the driver can use are:
+
+ieee80211_get_beacon             - this is called by the driver when
+                                   the HW needs a beacon.
+ieee80211_softmac_start_protocol - this should normally be called in the
+                                   driver open function
+ieee80211_softmac_stop_protocol  - the opposite of the above
+ieee80211_wake_queue             - this is similar to netif_wake_queue
+ieee80211_reset_queue            - this throw away fragments pending(if any)
+ieee80211_stop_queue             - this is similar to netif_stop_queue
+
+
+known BUGS:
+- When performing syncro scan (possiblily when swithcing to ad-hoc mode
+  and when running iwlist scan when associated) there is still an odd
+  behaviour.. I have not looked in this more accurately (yet).
+
+locking:
+locking is done by means of three structures.
+1- ieee->lock (by means of spin_[un]lock_irq[save/restore]
+2- ieee->wx_sem
+3- ieee->scan_sem
+
+the lock 1 is what protect most of the critical sections in the ieee stack.
+the lock 2 is used to avoid that more than one of the SET wireless extension
+handlers (as well as start/stop protocol function) are running at the same time.
+the lock 1 is used when we need to modify or read the shared data in the wx handlers.
+In other words the lock 2 will prevent one SET action will run across another SET
+action (by make sleep the 2nd one) but allow GET actions, while the lock 1
+make atomic those little shared data access in both GET and SET operation.
+So get operation will be never be delayed really: they will never sleep..
+Furthermore in the top of some SET operations a flag is set before acquiring
+the lock. This is an help to make the previous running SET operation to
+finish faster if needed (just in case the second one will totally undo the
+first, so there is not need to complete the 1st really.. ).
+The background scanning mechaninsm is protected by the lock 1 except for the
+workqueue. this wq is here just to let the set_chan callback sleep (I thinked it
+might be appreciated by USB network card driver developer). In this case the lock 3
+take its turn.
+Thus the stop function needs both the locks.
+Funny in the syncro scan the lock 2 play its role (as both the syncro_scan
+function and the stop scan function are called with this semaphore held).
+
+
diff --git a/drivers/staging/rtl8192su/ieee80211/rtl819x_BA.h b/drivers/staging/rtl8192su/ieee80211/rtl819x_BA.h
new file mode 100644
index 0000000..8ddc8bf9
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/rtl819x_BA.h
@@ -0,0 +1,69 @@
+#ifndef _BATYPE_H_
+#define _BATYPE_H_
+
+#define 	TOTAL_TXBA_NUM	16
+#define	TOTAL_RXBA_NUM	16
+
+#define	BA_SETUP_TIMEOUT	200
+#define	BA_INACT_TIMEOUT	60000
+
+#define	BA_POLICY_DELAYED		0
+#define	BA_POLICY_IMMEDIATE	1
+
+#define	ADDBA_STATUS_SUCCESS			0
+#define	ADDBA_STATUS_REFUSED		37
+#define	ADDBA_STATUS_INVALID_PARAM	38
+
+#define	DELBA_REASON_QSTA_LEAVING	36
+#define	DELBA_REASON_END_BA			37
+#define	DELBA_REASON_UNKNOWN_BA	38
+#define	DELBA_REASON_TIMEOUT			39
+/*  whether need define BA Action frames here?
+struct ieee80211_ADDBA_Req{
+	struct ieee80211_header_data header;
+	u8	category;
+	u8
+} __attribute__ ((packed));
+*/
+//Is this need?I put here just to make it easier to define structure BA_RECORD //WB
+typedef union _SEQUENCE_CONTROL{
+	u16 ShortData;
+	struct
+	{
+		u16	FragNum:4;
+		u16	SeqNum:12;
+	}field;
+}SEQUENCE_CONTROL, *PSEQUENCE_CONTROL;
+
+typedef union _BA_PARAM_SET {
+	u8 charData[2];
+	u16 shortData;
+	struct {
+		u16 AMSDU_Support:1;
+		u16 BAPolicy:1;
+		u16 TID:4;
+		u16 BufferSize:10;
+	} field;
+} BA_PARAM_SET, *PBA_PARAM_SET;
+
+typedef union _DELBA_PARAM_SET {
+	u8 charData[2];
+	u16 shortData;
+	struct {
+		u16 Reserved:11;
+		u16 Initiator:1;
+		u16 TID:4;
+	} field;
+} DELBA_PARAM_SET, *PDELBA_PARAM_SET;
+
+typedef struct _BA_RECORD {
+	struct timer_list		Timer;
+	u8				bValid;
+	u8				DialogToken;
+	BA_PARAM_SET		BaParamSet;
+	u16				BaTimeoutValue;
+	SEQUENCE_CONTROL	BaStartSeqCtrl;
+} BA_RECORD, *PBA_RECORD;
+
+#endif //end _BATYPE_H_
+
diff --git a/drivers/staging/rtl8192su/ieee80211/rtl819x_BAProc.c b/drivers/staging/rtl8192su/ieee80211/rtl819x_BAProc.c
new file mode 100644
index 0000000..cc5623a
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/rtl819x_BAProc.c
@@ -0,0 +1,781 @@
+/********************************************************************************************************************************
+ * This file is created to process BA Action Frame. According to 802.11 spec, there are 3 BA action types at all. And as BA is
+ * related to TS, this part need some struture defined in QOS side code. Also TX RX is going to be resturctured, so how to send
+ * ADDBAREQ ADDBARSP and DELBA packet is still on consideration. Temporarily use MANAGE QUEUE instead of Normal Queue.
+ * WB 2008-05-27
+ * *****************************************************************************************************************************/
+#include "ieee80211.h"
+#include "rtl819x_BA.h"
+
+/********************************************************************************************************************
+ *function:  Activate BA entry. And if Time is nozero, start timer.
+ *   input:  PBA_RECORD 		pBA  //BA entry to be enabled
+ *   	     u16 			Time //indicate time delay.
+ *  output:  none
+********************************************************************************************************************/
+void ActivateBAEntry(struct ieee80211_device* ieee, PBA_RECORD pBA, u16 Time)
+{
+	pBA->bValid = true;
+	if(Time != 0)
+		mod_timer(&pBA->Timer, jiffies + MSECS(Time));
+}
+
+/********************************************************************************************************************
+ *function:  deactivate BA entry, including its timer.
+ *   input:  PBA_RECORD 		pBA  //BA entry to be disabled
+ *  output:  none
+********************************************************************************************************************/
+void DeActivateBAEntry( struct ieee80211_device* ieee, PBA_RECORD pBA)
+{
+	pBA->bValid = false;
+	del_timer_sync(&pBA->Timer);
+}
+/********************************************************************************************************************
+ *function: deactivete BA entry in Tx Ts, and send DELBA.
+ *   input:
+ *   	     PTX_TS_RECORD		pTxTs //Tx Ts which is to deactivate BA entry.
+ *  output:  none
+ *  notice:  As PTX_TS_RECORD structure will be defined in QOS, so wait to be merged. //FIXME
+********************************************************************************************************************/
+u8 TxTsDeleteBA( struct ieee80211_device* ieee, PTX_TS_RECORD	pTxTs)
+{
+	PBA_RECORD		pAdmittedBa = &pTxTs->TxAdmittedBARecord;  //These two BA entries must exist in TS structure
+	PBA_RECORD		pPendingBa = &pTxTs->TxPendingBARecord;
+	u8			bSendDELBA = false;
+
+	// Delete pending BA
+	if(pPendingBa->bValid)
+	{
+		DeActivateBAEntry(ieee, pPendingBa);
+		bSendDELBA = true;
+	}
+
+	// Delete admitted BA
+	if(pAdmittedBa->bValid)
+	{
+		DeActivateBAEntry(ieee, pAdmittedBa);
+		bSendDELBA = true;
+	}
+
+	return bSendDELBA;
+}
+
+/********************************************************************************************************************
+ *function: deactivete BA entry in Tx Ts, and send DELBA.
+ *   input:
+ *   	     PRX_TS_RECORD		pRxTs //Rx Ts which is to deactivate BA entry.
+ *  output:  none
+ *  notice:  As PRX_TS_RECORD structure will be defined in QOS, so wait to be merged. //FIXME, same with above
+********************************************************************************************************************/
+u8 RxTsDeleteBA( struct ieee80211_device* ieee, PRX_TS_RECORD	pRxTs)
+{
+	PBA_RECORD		pBa = &pRxTs->RxAdmittedBARecord;
+	u8			bSendDELBA = false;
+
+	if(pBa->bValid)
+	{
+		DeActivateBAEntry(ieee, pBa);
+		bSendDELBA = true;
+	}
+
+	return bSendDELBA;
+}
+
+/********************************************************************************************************************
+ *function: reset BA entry
+ *   input:
+ *   	     PBA_RECORD		pBA //entry to be reset
+ *  output:  none
+********************************************************************************************************************/
+void ResetBaEntry( PBA_RECORD pBA)
+{
+	pBA->bValid			= false;
+	pBA->BaParamSet.shortData	= 0;
+	pBA->BaTimeoutValue		= 0;
+	pBA->DialogToken		= 0;
+	pBA->BaStartSeqCtrl.ShortData	= 0;
+}
+//These functions need porting here or not?
+/*******************************************************************************************************************************
+ *function:  construct ADDBAREQ and ADDBARSP frame here together.
+ *   input:  u8* 		Dst 	//ADDBA frame's destination
+ *   	     PBA_RECORD 	pBA	//BA_RECORD entry which stores the necessary information for BA.
+ *   	     u16 		StatusCode  //status code in RSP and I will use it to indicate whether it's RSP or REQ(will I?)
+ *   	     u8			type	//indicate whether it's RSP(ACT_ADDBARSP) ow REQ(ACT_ADDBAREQ)
+ *  output:  none
+ *  return:  sk_buff* 		skb     //return constructed skb to xmit
+*******************************************************************************************************************************/
+static struct sk_buff* ieee80211_ADDBA(struct ieee80211_device* ieee, u8* Dst, PBA_RECORD pBA, u16 StatusCode, u8 type)
+{
+	struct sk_buff *skb = NULL;
+	 struct ieee80211_hdr_3addr* BAReq = NULL;
+	u8* tag = NULL;
+	u16 tmp = 0;
+	u16 len = ieee->tx_headroom + 9;
+	//category(1) + action field(1) + Dialog Token(1) + BA Parameter Set(2) +  BA Timeout Value(2) +  BA Start SeqCtrl(2)(or StatusCode(2))
+	IEEE80211_DEBUG(IEEE80211_DL_TRACE | IEEE80211_DL_BA, "========>%s(), frame(%d) sentd to:"MAC_FMT", ieee->dev:%p\n", __FUNCTION__, type, MAC_ARG(Dst), ieee->dev);
+	if (pBA == NULL||ieee == NULL)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "pBA(%p) is NULL or ieee(%p) is NULL\n", pBA, ieee);
+		return NULL;
+	}
+	skb = dev_alloc_skb(len + sizeof( struct ieee80211_hdr_3addr)); //need to add something others? FIXME
+	if (skb == NULL)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't alloc skb for ADDBA_REQ\n");
+		return NULL;
+	}
+
+	memset(skb->data, 0, sizeof( struct ieee80211_hdr_3addr));  	//I wonder whether it's necessary. Apparently kernel will not do it when alloc a skb.
+	skb_reserve(skb, ieee->tx_headroom);
+
+	BAReq = ( struct ieee80211_hdr_3addr *) skb_put(skb,sizeof( struct ieee80211_hdr_3addr));
+
+	memcpy(BAReq->addr1, Dst, ETH_ALEN);
+	memcpy(BAReq->addr2, ieee->dev->dev_addr, ETH_ALEN);
+
+	memcpy(BAReq->addr3, ieee->current_network.bssid, ETH_ALEN);
+
+	BAReq->frame_ctl = cpu_to_le16(IEEE80211_STYPE_MANAGE_ACT); //action frame
+
+	//tag += sizeof( struct ieee80211_hdr_3addr); //move to action field
+	tag = (u8*)skb_put(skb, 9);
+	*tag ++= ACT_CAT_BA;
+	*tag ++= type;
+	// Dialog Token
+	*tag ++= pBA->DialogToken;
+
+	if (ACT_ADDBARSP == type)
+	{
+		// Status Code
+		printk("=====>to send ADDBARSP\n");
+		tmp = cpu_to_le16(StatusCode);
+		memcpy(tag, (u8*)&tmp, 2);
+		tag += 2;
+	}
+	// BA Parameter Set
+	tmp = cpu_to_le16(pBA->BaParamSet.shortData);
+	memcpy(tag, (u8*)&tmp, 2);
+	tag += 2;
+	// BA Timeout Value
+	tmp = cpu_to_le16(pBA->BaTimeoutValue);
+	memcpy(tag, (u8*)&tmp, 2);
+	tag += 2;
+
+	if (ACT_ADDBAREQ == type)
+	{
+	// BA Start SeqCtrl
+		memcpy(tag,(u8*)&(pBA->BaStartSeqCtrl), 2);
+		tag += 2;
+	}
+
+	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
+	return skb;
+	//return NULL;
+}
+
+#if 0 //I try to merge ADDBA_REQ and ADDBA_RSP frames together..
+/********************************************************************************************************************
+ *function:  construct ADDBAREQ frame
+ *   input:  u8* 		dst 	//ADDBARsp frame's destination
+ *   	     PBA_RECORD 	pBA	//BA_RECORD entry which stores the necessary information for BA_RSP.
+ *   	     u16 		StatusCode  //status code.
+ *  output:  none
+ *  return:  sk_buff* 		skb     //return constructed skb to xmit
+********************************************************************************************************************/
+static struct sk_buff* ieee80211_ADDBA_Rsp( IN	struct ieee80211_device* ieee, u8* dst, PBA_RECORD pBA, u16 StatusCode)
+{
+	OCTET_STRING	osADDBAFrame, tmp;
+
+	FillOctetString(osADDBAFrame, Buffer, 0);
+	*pLength = 0;
+
+	ConstructMaFrameHdr(
+					Adapter,
+					Addr,
+					ACT_CAT_BA,
+					ACT_ADDBARSP,
+					&osADDBAFrame	);
+
+	// Dialog Token
+	FillOctetString(tmp, &pBA->DialogToken, 1);
+	PacketAppendData(&osADDBAFrame, tmp);
+
+	// Status Code
+	FillOctetString(tmp, &StatusCode, 2);
+	PacketAppendData(&osADDBAFrame, tmp);
+
+	// BA Parameter Set
+	FillOctetString(tmp, &pBA->BaParamSet, 2);
+	PacketAppendData(&osADDBAFrame, tmp);
+
+	// BA Timeout Value
+	FillOctetString(tmp, &pBA->BaTimeoutValue, 2);
+	PacketAppendData(&osADDBAFrame, tmp);
+
+	*pLength = osADDBAFrame.Length;
+}
+#endif
+
+/********************************************************************************************************************
+ *function:  construct DELBA frame
+ *   input:  u8* 		dst 	//DELBA frame's destination
+ *   	     PBA_RECORD 	pBA	//BA_RECORD entry which stores the necessary information for BA
+ *   	     TR_SELECT	        TxRxSelect  //TX RX direction
+ *   	     u16 		ReasonCode  //status code.
+ *  output:  none
+ *  return:  sk_buff* 		skb     //return constructed skb to xmit
+********************************************************************************************************************/
+static struct sk_buff* ieee80211_DELBA(
+	struct ieee80211_device* ieee,
+	u8*		         dst,
+	PBA_RECORD		 pBA,
+	TR_SELECT		 TxRxSelect,
+	u16			 ReasonCode
+	)
+{
+	DELBA_PARAM_SET	DelbaParamSet;
+	struct sk_buff *skb = NULL;
+	 struct ieee80211_hdr_3addr* Delba = NULL;
+	u8* tag = NULL;
+	u16 tmp = 0;
+	//len = head len + DELBA Parameter Set(2) + Reason Code(2)
+	u16 len = 6 + ieee->tx_headroom;
+
+	if (net_ratelimit())
+	IEEE80211_DEBUG(IEEE80211_DL_TRACE | IEEE80211_DL_BA, "========>%s(), ReasonCode(%d) sentd to:"MAC_FMT"\n", __FUNCTION__, ReasonCode, MAC_ARG(dst));
+
+	memset(&DelbaParamSet, 0, 2);
+
+	DelbaParamSet.field.Initiator	= (TxRxSelect==TX_DIR)?1:0;
+	DelbaParamSet.field.TID	= pBA->BaParamSet.field.TID;
+
+	skb = dev_alloc_skb(len + sizeof( struct ieee80211_hdr_3addr)); //need to add something others? FIXME
+	if (skb == NULL)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't alloc skb for ADDBA_REQ\n");
+		return NULL;
+	}
+//	memset(skb->data, 0, len+sizeof( struct ieee80211_hdr_3addr));
+	skb_reserve(skb, ieee->tx_headroom);
+
+	Delba = ( struct ieee80211_hdr_3addr *) skb_put(skb,sizeof( struct ieee80211_hdr_3addr));
+
+	memcpy(Delba->addr1, dst, ETH_ALEN);
+	memcpy(Delba->addr2, ieee->dev->dev_addr, ETH_ALEN);
+	memcpy(Delba->addr3, ieee->current_network.bssid, ETH_ALEN);
+	Delba->frame_ctl = cpu_to_le16(IEEE80211_STYPE_MANAGE_ACT); //action frame
+
+	tag = (u8*)skb_put(skb, 6);
+
+	*tag ++= ACT_CAT_BA;
+	*tag ++= ACT_DELBA;
+
+	// DELBA Parameter Set
+	tmp = cpu_to_le16(DelbaParamSet.shortData);
+	memcpy(tag, (u8*)&tmp, 2);
+	tag += 2;
+	// Reason Code
+	tmp = cpu_to_le16(ReasonCode);
+	memcpy(tag, (u8*)&tmp, 2);
+	tag += 2;
+
+	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
+	if (net_ratelimit())
+	IEEE80211_DEBUG(IEEE80211_DL_TRACE | IEEE80211_DL_BA, "<=====%s()\n", __FUNCTION__);
+	return skb;
+}
+
+/********************************************************************************************************************
+ *function: send ADDBAReq frame out
+ *   input:  u8* 		dst 	//ADDBAReq frame's destination
+ *   	     PBA_RECORD 	pBA	//BA_RECORD entry which stores the necessary information for BA
+ *  output:  none
+ *  notice: If any possible, please hide pBA in ieee. And temporarily use Manage Queue as softmac_mgmt_xmit() usually does
+********************************************************************************************************************/
+void ieee80211_send_ADDBAReq(struct ieee80211_device* ieee, u8*	dst, PBA_RECORD	pBA)
+{
+	struct sk_buff *skb = NULL;
+	skb = ieee80211_ADDBA(ieee, dst, pBA, 0, ACT_ADDBAREQ); //construct ACT_ADDBAREQ frames so set statuscode zero.
+
+	if (skb)
+	{
+		softmac_mgmt_xmit(skb, ieee);
+		//add statistic needed here.
+		//and skb will be freed in softmac_mgmt_xmit(), so omit all dev_kfree_skb_any() outside softmac_mgmt_xmit()
+		//WB
+	}
+	else
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "alloc skb error in function %s()\n", __FUNCTION__);
+	}
+	return;
+}
+
+/********************************************************************************************************************
+ *function: send ADDBARSP frame out
+ *   input:  u8* 		dst 	//DELBA frame's destination
+ *   	     PBA_RECORD 	pBA	//BA_RECORD entry which stores the necessary information for BA
+ *   	     u16		StatusCode //RSP StatusCode
+ *  output:  none
+ *  notice: If any possible, please hide pBA in ieee. And temporarily use Manage Queue as softmac_mgmt_xmit() usually does
+********************************************************************************************************************/
+void ieee80211_send_ADDBARsp(struct ieee80211_device* ieee, u8* dst, PBA_RECORD pBA, u16 StatusCode)
+{
+	struct sk_buff *skb = NULL;
+	skb = ieee80211_ADDBA(ieee, dst, pBA, StatusCode, ACT_ADDBARSP); //construct ACT_ADDBARSP frames
+	if (skb)
+	{
+		softmac_mgmt_xmit(skb, ieee);
+		//same above
+	}
+	else
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "alloc skb error in function %s()\n", __FUNCTION__);
+	}
+
+	return;
+
+}
+/********************************************************************************************************************
+ *function: send ADDBARSP frame out
+ *   input:  u8* 		dst 	//DELBA frame's destination
+ *   	     PBA_RECORD 	pBA	//BA_RECORD entry which stores the necessary information for BA
+ *   	     TR_SELECT          TxRxSelect //TX or RX
+ *   	     u16		ReasonCode //DEL ReasonCode
+ *  output:  none
+ *  notice: If any possible, please hide pBA in ieee. And temporarily use Manage Queue as softmac_mgmt_xmit() usually does
+********************************************************************************************************************/
+
+void ieee80211_send_DELBA(struct ieee80211_device* ieee, u8* dst, PBA_RECORD pBA, TR_SELECT TxRxSelect, u16 ReasonCode)
+{
+	struct sk_buff *skb = NULL;
+	skb = ieee80211_DELBA(ieee, dst, pBA, TxRxSelect, ReasonCode); //construct ACT_ADDBARSP frames
+	if (skb)
+	{
+		softmac_mgmt_xmit(skb, ieee);
+		//same above
+	}
+	else
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "alloc skb error in function %s()\n", __FUNCTION__);
+	}
+	return ;
+}
+
+/********************************************************************************************************************
+ *function: RX ADDBAReq
+ *   input:  struct sk_buff *   skb	//incoming ADDBAReq skb.
+ *  return:  0(pass), other(fail)
+ *  notice:  As this function need support of QOS, I comment some code out. And when qos is ready, this code need to be support.
+********************************************************************************************************************/
+int ieee80211_rx_ADDBAReq( struct ieee80211_device* ieee, struct sk_buff *skb)
+{
+	 struct ieee80211_hdr_3addr* req = NULL;
+	u16 rc = 0;
+	u8 * dst = NULL, *pDialogToken = NULL, *tag = NULL;
+	PBA_RECORD pBA = NULL;
+	PBA_PARAM_SET	pBaParamSet = NULL;
+	u16* pBaTimeoutVal = NULL;
+	PSEQUENCE_CONTROL pBaStartSeqCtrl = NULL;
+	PRX_TS_RECORD	pTS = NULL;
+
+	if (skb->len < sizeof( struct ieee80211_hdr_3addr) + 9)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, " Invalid skb len in BAREQ(%d / %d)\n", skb->len, 	(sizeof( struct ieee80211_hdr_3addr) + 9));
+		return -1;
+	}
+
+	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
+
+	req = ( struct ieee80211_hdr_3addr*) skb->data;
+	tag = (u8*)req;
+	dst = (u8*)(&req->addr2[0]);
+	tag += sizeof( struct ieee80211_hdr_3addr);
+	pDialogToken = tag + 2;  //category+action
+	pBaParamSet = (PBA_PARAM_SET)(tag + 3);   //+DialogToken
+	pBaTimeoutVal = (u16*)(tag + 5);
+	pBaStartSeqCtrl = (PSEQUENCE_CONTROL)(req + 7);
+
+	printk("====================>rx ADDBAREQ from :"MAC_FMT"\n", MAC_ARG(dst));
+//some other capability is not ready now.
+	if(	(ieee->current_network.qos_data.active == 0) ||
+		(ieee->pHTInfo->bCurrentHTSupport == false) ||
+		(ieee->pHTInfo->IOTAction & HT_IOT_ACT_REJECT_ADDBA_REQ)) //||
+	//	(ieee->pStaQos->bEnableRxImmBA == false)	)
+	{
+		rc = ADDBA_STATUS_REFUSED;
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "Failed to reply on ADDBA_REQ as some capability is not ready(%d, %d)\n", ieee->current_network.qos_data.active, ieee->pHTInfo->bCurrentHTSupport);
+		goto OnADDBAReq_Fail;
+	}
+	// Search for related traffic stream.
+	// If there is no matched TS, reject the ADDBA request.
+	if(	!GetTs(
+			ieee,
+			(PTS_COMMON_INFO*)(&pTS),
+			dst,
+			(u8)(pBaParamSet->field.TID),
+			RX_DIR,
+			true)	)
+	{
+		rc = ADDBA_STATUS_REFUSED;
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't get TS in %s()\n", __FUNCTION__);
+		goto OnADDBAReq_Fail;
+	}
+	pBA = &pTS->RxAdmittedBARecord;
+	// To Determine the ADDBA Req content
+	// We can do much more check here, including BufferSize, AMSDU_Support, Policy, StartSeqCtrl...
+	// I want to check StartSeqCtrl to make sure when we start aggregation!!!
+	//
+	if(pBaParamSet->field.BAPolicy == BA_POLICY_DELAYED)
+	{
+		rc = ADDBA_STATUS_INVALID_PARAM;
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "BA Policy is not correct in %s()\n", __FUNCTION__);
+		goto OnADDBAReq_Fail;
+	}
+		// Admit the ADDBA Request
+	//
+	DeActivateBAEntry(ieee, pBA);
+	pBA->DialogToken = *pDialogToken;
+	pBA->BaParamSet = *pBaParamSet;
+	pBA->BaTimeoutValue = *pBaTimeoutVal;
+	pBA->BaStartSeqCtrl = *pBaStartSeqCtrl;
+	//for half N mode we only aggregate 1 frame
+	if (ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev)||
+	(ieee->pHTInfo->IOTAction & HT_IOT_ACT_ALLOW_PEER_AGG_ONE_PKT))
+	pBA->BaParamSet.field.BufferSize = 1;
+	else
+	pBA->BaParamSet.field.BufferSize = 32;
+	ActivateBAEntry(ieee, pBA, 0);//pBA->BaTimeoutValue);
+	ieee80211_send_ADDBARsp(ieee, dst, pBA, ADDBA_STATUS_SUCCESS);
+
+	// End of procedure.
+	return 0;
+
+OnADDBAReq_Fail:
+	{
+		BA_RECORD	BA;
+		BA.BaParamSet = *pBaParamSet;
+		BA.BaTimeoutValue = *pBaTimeoutVal;
+		BA.DialogToken = *pDialogToken;
+		BA.BaParamSet.field.BAPolicy = BA_POLICY_IMMEDIATE;
+		ieee80211_send_ADDBARsp(ieee, dst, &BA, rc);
+		return 0; //we send RSP out.
+	}
+
+}
+
+/********************************************************************************************************************
+ *function: RX ADDBARSP
+ *   input:  struct sk_buff *   skb	//incoming ADDBAReq skb.
+ *  return:  0(pass), other(fail)
+ *  notice:  As this function need support of QOS, I comment some code out. And when qos is ready, this code need to be support.
+********************************************************************************************************************/
+int ieee80211_rx_ADDBARsp( struct ieee80211_device* ieee, struct sk_buff *skb)
+{
+	 struct ieee80211_hdr_3addr* rsp = NULL;
+	PBA_RECORD		pPendingBA, pAdmittedBA;
+	PTX_TS_RECORD		pTS = NULL;
+	u8* dst = NULL, *pDialogToken = NULL, *tag = NULL;
+	u16* pStatusCode = NULL, *pBaTimeoutVal = NULL;
+	PBA_PARAM_SET		pBaParamSet = NULL;
+	u16			ReasonCode;
+
+	if (skb->len < sizeof( struct ieee80211_hdr_3addr) + 9)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, " Invalid skb len in BARSP(%d / %d)\n", skb->len, 	(sizeof( struct ieee80211_hdr_3addr) + 9));
+		return -1;
+	}
+	rsp = ( struct ieee80211_hdr_3addr*)skb->data;
+	tag = (u8*)rsp;
+	dst = (u8*)(&rsp->addr2[0]);
+	tag += sizeof( struct ieee80211_hdr_3addr);
+	pDialogToken = tag + 2;
+	pStatusCode = (u16*)(tag + 3);
+	pBaParamSet = (PBA_PARAM_SET)(tag + 5);
+	pBaTimeoutVal = (u16*)(tag + 7);
+
+	// Check the capability
+	// Since we can always receive A-MPDU, we just check if it is under HT mode.
+	if(     ieee->current_network.qos_data.active == 0  ||
+		ieee->pHTInfo->bCurrentHTSupport == false ||
+		ieee->pHTInfo->bCurrentAMPDUEnable == false )
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "reject to ADDBA_RSP as some capability is not ready(%d, %d, %d)\n",ieee->current_network.qos_data.active, ieee->pHTInfo->bCurrentHTSupport, ieee->pHTInfo->bCurrentAMPDUEnable);
+		ReasonCode = DELBA_REASON_UNKNOWN_BA;
+		goto OnADDBARsp_Reject;
+	}
+
+
+	//
+	// Search for related TS.
+	// If there is no TS found, we wil reject ADDBA Rsp by sending DELBA frame.
+	//
+	if (!GetTs(
+			ieee,
+			(PTS_COMMON_INFO*)(&pTS),
+			dst,
+			(u8)(pBaParamSet->field.TID),
+			TX_DIR,
+			false)	)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't get TS in %s()\n", __FUNCTION__);
+		ReasonCode = DELBA_REASON_UNKNOWN_BA;
+		goto OnADDBARsp_Reject;
+	}
+
+	pTS->bAddBaReqInProgress = false;
+	pPendingBA = &pTS->TxPendingBARecord;
+	pAdmittedBA = &pTS->TxAdmittedBARecord;
+
+
+	//
+	// Check if related BA is waiting for setup.
+	// If not, reject by sending DELBA frame.
+	//
+	if((pAdmittedBA->bValid==true))
+	{
+		// Since BA is already setup, we ignore all other ADDBA Response.
+		IEEE80211_DEBUG(IEEE80211_DL_BA, "OnADDBARsp(): Recv ADDBA Rsp. Drop because already admit it! \n");
+		return -1;
+	}
+	else if((pPendingBA->bValid == false) ||(*pDialogToken != pPendingBA->DialogToken))
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR,  "OnADDBARsp(): Recv ADDBA Rsp. BA invalid, DELBA! \n");
+		ReasonCode = DELBA_REASON_UNKNOWN_BA;
+		goto OnADDBARsp_Reject;
+	}
+	else
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_BA, "OnADDBARsp(): Recv ADDBA Rsp. BA is admitted! Status code:%X\n", *pStatusCode);
+		DeActivateBAEntry(ieee, pPendingBA);
+	}
+
+
+	if(*pStatusCode == ADDBA_STATUS_SUCCESS)
+	{
+		//
+		// Determine ADDBA Rsp content here.
+		// We can compare the value of BA parameter set that Peer returned and Self sent.
+		// If it is OK, then admitted. Or we can send DELBA to cancel BA mechanism.
+		//
+		if(pBaParamSet->field.BAPolicy == BA_POLICY_DELAYED)
+		{
+			// Since this is a kind of ADDBA failed, we delay next ADDBA process.
+			pTS->bAddBaReqDelayed = true;
+			DeActivateBAEntry(ieee, pAdmittedBA);
+			ReasonCode = DELBA_REASON_END_BA;
+			goto OnADDBARsp_Reject;
+		}
+
+
+		//
+		// Admitted condition
+		//
+		pAdmittedBA->DialogToken = *pDialogToken;
+		pAdmittedBA->BaTimeoutValue = *pBaTimeoutVal;
+		pAdmittedBA->BaStartSeqCtrl = pPendingBA->BaStartSeqCtrl;
+		pAdmittedBA->BaParamSet = *pBaParamSet;
+		DeActivateBAEntry(ieee, pAdmittedBA);
+		ActivateBAEntry(ieee, pAdmittedBA, *pBaTimeoutVal);
+	}
+	else
+	{
+		// Delay next ADDBA process.
+		pTS->bAddBaReqDelayed = true;
+	}
+
+	// End of procedure
+	return 0;
+
+OnADDBARsp_Reject:
+	{
+		BA_RECORD	BA;
+		BA.BaParamSet = *pBaParamSet;
+		ieee80211_send_DELBA(ieee, dst, &BA, TX_DIR, ReasonCode);
+		return 0;
+	}
+
+}
+
+/********************************************************************************************************************
+ *function: RX DELBA
+ *   input:  struct sk_buff *   skb	//incoming ADDBAReq skb.
+ *  return:  0(pass), other(fail)
+ *  notice:  As this function need support of QOS, I comment some code out. And when qos is ready, this code need to be support.
+********************************************************************************************************************/
+int ieee80211_rx_DELBA(struct ieee80211_device* ieee,struct sk_buff *skb)
+{
+	 struct ieee80211_hdr_3addr* delba = NULL;
+	PDELBA_PARAM_SET	pDelBaParamSet = NULL;
+	u16*			pReasonCode = NULL;
+	u8*			dst = NULL;
+
+	if (skb->len < sizeof( struct ieee80211_hdr_3addr) + 6)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, " Invalid skb len in DELBA(%d / %d)\n", skb->len, 	(sizeof( struct ieee80211_hdr_3addr) + 6));
+		return -1;
+	}
+
+	if(ieee->current_network.qos_data.active == 0 ||
+		ieee->pHTInfo->bCurrentHTSupport == false )
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "received DELBA while QOS or HT is not supported(%d, %d)\n",ieee->current_network.qos_data.active, ieee->pHTInfo->bCurrentHTSupport);
+		return -1;
+	}
+
+	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
+	delba = ( struct ieee80211_hdr_3addr*)skb->data;
+	dst = (u8*)(&delba->addr2[0]);
+	delba += sizeof( struct ieee80211_hdr_3addr);
+	pDelBaParamSet = (PDELBA_PARAM_SET)(delba+2);
+	pReasonCode = (u16*)(delba+4);
+
+	if(pDelBaParamSet->field.Initiator == 1)
+	{
+		PRX_TS_RECORD 	pRxTs;
+
+		if( !GetTs(
+				ieee,
+				(PTS_COMMON_INFO*)&pRxTs,
+				dst,
+				(u8)pDelBaParamSet->field.TID,
+				RX_DIR,
+				false)	)
+		{
+			IEEE80211_DEBUG(IEEE80211_DL_ERR,  "can't get TS for RXTS in %s()\n", __FUNCTION__);
+			return -1;
+		}
+
+		RxTsDeleteBA(ieee, pRxTs);
+	}
+	else
+	{
+		PTX_TS_RECORD	pTxTs;
+
+		if(!GetTs(
+			ieee,
+			(PTS_COMMON_INFO*)&pTxTs,
+			dst,
+			(u8)pDelBaParamSet->field.TID,
+			TX_DIR,
+			false)	)
+		{
+			IEEE80211_DEBUG(IEEE80211_DL_ERR,  "can't get TS for TXTS in %s()\n", __FUNCTION__);
+			return -1;
+		}
+
+		pTxTs->bUsingBa = false;
+		pTxTs->bAddBaReqInProgress = false;
+		pTxTs->bAddBaReqDelayed = false;
+		del_timer_sync(&pTxTs->TsAddBaTimer);
+		//PlatformCancelTimer(Adapter, &pTxTs->TsAddBaTimer);
+		TxTsDeleteBA(ieee, pTxTs);
+	}
+	return 0;
+}
+
+//
+// ADDBA initiate. This can only be called by TX side.
+//
+void
+TsInitAddBA(
+	struct ieee80211_device* ieee,
+	PTX_TS_RECORD	pTS,
+	u8		Policy,
+	u8		bOverwritePending
+	)
+{
+	PBA_RECORD			pBA = &pTS->TxPendingBARecord;
+
+	if(pBA->bValid==true && bOverwritePending==false)
+		return;
+
+	// Set parameters to "Pending" variable set
+	DeActivateBAEntry(ieee, pBA);
+
+	pBA->DialogToken++;						// DialogToken: Only keep the latest dialog token
+	pBA->BaParamSet.field.AMSDU_Support = 0;	// Do not support A-MSDU with A-MPDU now!!
+	pBA->BaParamSet.field.BAPolicy = Policy;	// Policy: Delayed or Immediate
+	pBA->BaParamSet.field.TID = pTS->TsCommonInfo.TSpec.f.TSInfo.field.ucTSID;	// TID
+	// BufferSize: This need to be set according to A-MPDU vector
+	pBA->BaParamSet.field.BufferSize = 32;		// BufferSize: This need to be set according to A-MPDU vector
+	pBA->BaTimeoutValue = 0;					// Timeout value: Set 0 to disable Timer
+	pBA->BaStartSeqCtrl.field.SeqNum = (pTS->TxCurSeq + 3) % 4096; 	// Block Ack will start after 3 packets later.
+
+	ActivateBAEntry(ieee, pBA, BA_SETUP_TIMEOUT);
+
+	ieee80211_send_ADDBAReq(ieee, pTS->TsCommonInfo.Addr, pBA);
+}
+
+void
+TsInitDelBA( struct ieee80211_device* ieee, PTS_COMMON_INFO pTsCommonInfo, TR_SELECT TxRxSelect)
+{
+
+	if(TxRxSelect == TX_DIR)
+	{
+		PTX_TS_RECORD	pTxTs = (PTX_TS_RECORD)pTsCommonInfo;
+
+		if(TxTsDeleteBA(ieee, pTxTs))
+			ieee80211_send_DELBA(
+				ieee,
+				pTsCommonInfo->Addr,
+				(pTxTs->TxAdmittedBARecord.bValid)?(&pTxTs->TxAdmittedBARecord):(&pTxTs->TxPendingBARecord),
+				TxRxSelect,
+				DELBA_REASON_END_BA);
+	}
+	else if(TxRxSelect == RX_DIR)
+	{
+		PRX_TS_RECORD	pRxTs = (PRX_TS_RECORD)pTsCommonInfo;
+		if(RxTsDeleteBA(ieee, pRxTs))
+			ieee80211_send_DELBA(
+				ieee,
+				pTsCommonInfo->Addr,
+				&pRxTs->RxAdmittedBARecord,
+				TxRxSelect,
+				DELBA_REASON_END_BA	);
+	}
+}
+/********************************************************************************************************************
+ *function:  BA setup timer
+ *   input:  unsigned long	 data		//acturally we send TX_TS_RECORD or RX_TS_RECORD to these timer
+ *  return:  NULL
+ *  notice:
+********************************************************************************************************************/
+void BaSetupTimeOut(unsigned long data)
+{
+	PTX_TS_RECORD	pTxTs = (PTX_TS_RECORD)data;
+
+	pTxTs->bAddBaReqInProgress = false;
+	pTxTs->bAddBaReqDelayed = true;
+	pTxTs->TxPendingBARecord.bValid = false;
+}
+
+void TxBaInactTimeout(unsigned long data)
+{
+	PTX_TS_RECORD	pTxTs = (PTX_TS_RECORD)data;
+	struct ieee80211_device *ieee = container_of(pTxTs, struct ieee80211_device, TxTsRecord[pTxTs->num]);
+	TxTsDeleteBA(ieee, pTxTs);
+	ieee80211_send_DELBA(
+		ieee,
+		pTxTs->TsCommonInfo.Addr,
+		&pTxTs->TxAdmittedBARecord,
+		TX_DIR,
+		DELBA_REASON_TIMEOUT);
+}
+
+void RxBaInactTimeout(unsigned long data)
+{
+	PRX_TS_RECORD	pRxTs = (PRX_TS_RECORD)data;
+	struct ieee80211_device *ieee = container_of(pRxTs, struct ieee80211_device, RxTsRecord[pRxTs->num]);
+
+	RxTsDeleteBA(ieee, pRxTs);
+	ieee80211_send_DELBA(
+		ieee,
+		pRxTs->TsCommonInfo.Addr,
+		&pRxTs->RxAdmittedBARecord,
+		RX_DIR,
+		DELBA_REASON_TIMEOUT);
+	return ;
+}
+
diff --git a/drivers/staging/rtl8192su/ieee80211/rtl819x_HT.h b/drivers/staging/rtl8192su/ieee80211/rtl819x_HT.h
new file mode 100644
index 0000000..16a7462
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/rtl819x_HT.h
@@ -0,0 +1,517 @@
+#ifndef _RTL819XU_HTTYPE_H_
+#define _RTL819XU_HTTYPE_H_
+
+//------------------------------------------------------------
+// The HT Capability element is present in beacons, association request,
+//	reassociation request and probe response frames
+//------------------------------------------------------------
+
+//
+// Operation mode value
+//
+#define HT_OPMODE_NO_PROTECT		0
+#define HT_OPMODE_OPTIONAL		1
+#define HT_OPMODE_40MHZ_PROTECT	2
+#define HT_OPMODE_MIXED			3
+
+//
+// MIMO Power Save Setings
+//
+#define MIMO_PS_STATIC				0
+#define MIMO_PS_DYNAMIC			1
+#define MIMO_PS_NOLIMIT			3
+
+
+//
+//	There should be 128 bits to cover all of the MCS rates. However, since
+//	8190 does not support too much rates, one integer is quite enough.
+//
+
+#define sHTCLng	4
+
+
+#define HT_SUPPORTED_MCS_1SS_BITMAP					0x000000ff
+#define HT_SUPPORTED_MCS_2SS_BITMAP					0x0000ff00
+#define HT_SUPPORTED_MCS_1SS_2SS_BITMAP			HT_MCS_1SS_BITMAP|HT_MCS_1SS_2SS_BITMAP
+
+
+typedef enum _HT_MCS_RATE{
+	HT_MCS0   = 0x00000001,
+	HT_MCS1   = 0x00000002,
+	HT_MCS2   = 0x00000004,
+	HT_MCS3   = 0x00000008,
+	HT_MCS4   = 0x00000010,
+	HT_MCS5   = 0x00000020,
+	HT_MCS6   = 0x00000040,
+	HT_MCS7   = 0x00000080,
+	HT_MCS8   = 0x00000100,
+	HT_MCS9   = 0x00000200,
+	HT_MCS10 = 0x00000400,
+	HT_MCS11 = 0x00000800,
+	HT_MCS12 = 0x00001000,
+	HT_MCS13 = 0x00002000,
+	HT_MCS14 = 0x00004000,
+	HT_MCS15 = 0x00008000,
+	// Do not define MCS32 here although 8190 support MCS32
+}HT_MCS_RATE,*PHT_MCS_RATE;
+
+//
+// Represent Channel Width in HT Capabilities
+//
+typedef enum _HT_CHANNEL_WIDTH{
+	HT_CHANNEL_WIDTH_20 = 0,
+	HT_CHANNEL_WIDTH_20_40 = 1,
+}HT_CHANNEL_WIDTH, *PHT_CHANNEL_WIDTH;
+
+//
+// Represent Extention Channel Offset in HT Capabilities
+// This is available only in 40Mhz mode.
+//
+typedef enum _HT_EXTCHNL_OFFSET{
+	HT_EXTCHNL_OFFSET_NO_EXT = 0,
+	HT_EXTCHNL_OFFSET_UPPER = 1,
+	HT_EXTCHNL_OFFSET_NO_DEF = 2,
+	HT_EXTCHNL_OFFSET_LOWER = 3,
+}HT_EXTCHNL_OFFSET, *PHT_EXTCHNL_OFFSET;
+
+typedef enum _CHNLOP{
+	CHNLOP_NONE = 0, // No Action now
+	CHNLOP_SCAN = 1, // Scan in progress
+	CHNLOP_SWBW = 2, // Bandwidth switching in progress
+	CHNLOP_SWCHNL = 3, // Software Channel switching in progress
+} CHNLOP, *PCHNLOP;
+
+// Determine if the Channel Operation is in progress
+#define CHHLOP_IN_PROGRESS(_pHTInfo)	\
+		((_pHTInfo)->ChnlOp > CHNLOP_NONE) ? TRUE : FALSE
+
+/*
+typedef	union _HT_CAPABILITY{
+	u16	ShortData;
+	u8	CharData[2];
+	struct
+	{
+		u16	AdvCoding:1;
+		u16	ChlWidth:1;
+		u16	MimoPwrSave:2;
+		u16	GreenField:1;
+		u16	ShortGI20Mhz:1;
+		u16	ShortGI40Mhz:1;
+		u16	STBC:1;
+		u16	BeamForm:1;
+		u16	DelayBA:1;
+		u16	MaxAMSDUSize:1;
+		u16	DssCCk:1;
+		u16	PSMP:1;
+		u16	Rsvd:3;
+	}Field;
+}HT_CAPABILITY, *PHT_CAPABILITY;
+
+typedef	union _HT_CAPABILITY_MACPARA{
+	u8	ShortData;
+	u8	CharData[1];
+	struct
+	{
+		u8	MaxRxAMPDU:2;
+		u8	MPDUDensity:2;
+		u8	Rsvd:4;
+	}Field;
+}HT_CAPABILITY_MACPARA, *PHT_CAPABILITY_MACPARA;
+*/
+
+typedef enum _HT_ACTION{
+	ACT_RECOMMAND_WIDTH		= 0,
+	ACT_MIMO_PWR_SAVE 		= 1,
+	ACT_PSMP					= 2,
+	ACT_SET_PCO_PHASE		= 3,
+	ACT_MIMO_CHL_MEASURE	= 4,
+	ACT_RECIPROCITY_CORRECT	= 5,
+	ACT_MIMO_CSI_MATRICS		= 6,
+	ACT_MIMO_NOCOMPR_STEER	= 7,
+	ACT_MIMO_COMPR_STEER		= 8,
+	ACT_ANTENNA_SELECT		= 9,
+} HT_ACTION, *PHT_ACTION;
+
+
+/* 2007/06/07 MH Define sub-carrier mode for 40MHZ. */
+typedef enum _HT_Bandwidth_40MHZ_Sub_Carrier{
+	SC_MODE_DUPLICATE = 0,
+	SC_MODE_LOWER = 1,
+	SC_MODE_UPPER = 2,
+	SC_MODE_FULL40MHZ = 3,
+}HT_BW40_SC_E;
+
+typedef	struct _HT_CAPABILITY_ELE{
+
+	//HT capability info
+	u8	AdvCoding:1;
+	u8	ChlWidth:1;
+	u8	MimoPwrSave:2;
+	u8	GreenField:1;
+	u8	ShortGI20Mhz:1;
+	u8	ShortGI40Mhz:1;
+	u8	TxSTBC:1;
+	u8	RxSTBC:2;
+	u8	DelayBA:1;
+	u8	MaxAMSDUSize:1;
+	u8	DssCCk:1;
+	u8	PSMP:1;
+	u8	Rsvd1:1;
+	u8	LSigTxopProtect:1;
+
+	//MAC HT parameters info
+	u8	MaxRxAMPDUFactor:2;
+	u8	MPDUDensity:3;
+	u8	Rsvd2:3;
+
+	//Supported MCS set
+	u8	MCS[16];
+
+
+	//Extended HT Capability Info
+	u16	ExtHTCapInfo;
+
+	//TXBF Capabilities
+	u8	TxBFCap[4];
+
+	//Antenna Selection Capabilities
+	u8	ASCap;
+
+} __attribute__ ((packed)) HT_CAPABILITY_ELE, *PHT_CAPABILITY_ELE;
+
+//------------------------------------------------------------
+// The HT Information element is present in beacons
+// Only AP is required to include this element
+//------------------------------------------------------------
+
+typedef struct _HT_INFORMATION_ELE{
+	u8	ControlChl;
+
+	u8	ExtChlOffset:2;
+	u8	RecommemdedTxWidth:1;
+	u8	RIFS:1;
+	u8	PSMPAccessOnly:1;
+	u8	SrvIntGranularity:3;
+
+	u8	OptMode:2;
+	u8	NonGFDevPresent:1;
+	u8	Revd1:5;
+	u8	Revd2:8;
+
+	u8	Rsvd3:6;
+	u8	DualBeacon:1;
+	u8	DualCTSProtect:1;
+
+	u8	SecondaryBeacon:1;
+	u8	LSigTxopProtectFull:1;
+	u8	PcoActive:1;
+	u8	PcoPhase:1;
+	u8	Rsvd4:4;
+
+	u8	BasicMSC[16];
+} __attribute__ ((packed)) HT_INFORMATION_ELE, *PHT_INFORMATION_ELE;
+
+//
+// MIMO Power Save control field.
+// This is appear in MIMO Power Save Action Frame
+//
+typedef struct _MIMOPS_CTRL{
+	u8	MimoPsEnable:1;
+	u8	MimoPsMode:1;
+	u8	Reserved:6;
+} MIMOPS_CTRL, *PMIMOPS_CTRL;
+
+typedef enum _HT_SPEC_VER{
+	HT_SPEC_VER_IEEE = 0,
+	HT_SPEC_VER_EWC = 1,
+}HT_SPEC_VER, *PHT_SPEC_VER;
+
+typedef enum _HT_AGGRE_MODE_E{
+	HT_AGG_AUTO = 0,
+	HT_AGG_FORCE_ENABLE = 1,
+	HT_AGG_FORCE_DISABLE = 2,
+}HT_AGGRE_MODE_E, *PHT_AGGRE_MODE_E;
+
+//------------------------------------------------------------
+//  The Data structure is used to keep HT related variables when card is
+//  configured as non-AP STA mode.  **Note**  Current_xxx should be set
+//	to default value in HTInitializeHTInfo()
+//------------------------------------------------------------
+
+typedef struct _RT_HIGH_THROUGHPUT{
+	u8				bEnableHT;
+	u8				bCurrentHTSupport;
+
+	u8				bRegBW40MHz;				// Tx 40MHz channel capablity
+	u8				bCurBW40MHz;				// Tx 40MHz channel capability
+
+	u8				bRegShortGI40MHz;			// Tx Short GI for 40Mhz
+	u8				bCurShortGI40MHz;			// Tx Short GI for 40MHz
+
+	u8				bRegShortGI20MHz;			// Tx Short GI for 20MHz
+	u8				bCurShortGI20MHz;			// Tx Short GI for 20MHz
+
+	u8				bRegSuppCCK;				// Tx CCK rate capability
+	u8				bCurSuppCCK;				// Tx CCK rate capability
+
+	// 802.11n spec version for "peer"
+	HT_SPEC_VER			ePeerHTSpecVer;
+
+
+	// HT related information for "Self"
+	HT_CAPABILITY_ELE	SelfHTCap;		// This is HT cap element sent to peer STA, which also indicate HT Rx capabilities.
+	HT_INFORMATION_ELE	SelfHTInfo;		// This is HT info element sent to peer STA, which also indicate HT Rx capabilities.
+
+	// HT related information for "Peer"
+	u8				PeerHTCapBuf[32];
+	u8				PeerHTInfoBuf[32];
+
+
+	// A-MSDU related
+	u8				bAMSDU_Support;			// This indicates Tx A-MSDU capability
+	u16				nAMSDU_MaxSize;			// This indicates Tx A-MSDU capability
+	u8				bCurrent_AMSDU_Support;	// This indicates Tx A-MSDU capability
+	u16				nCurrent_AMSDU_MaxSize;	// This indicates Tx A-MSDU capability
+
+
+	// AMPDU  related <2006.08.10 Emily>
+	u8				bAMPDUEnable;				// This indicate Tx A-MPDU capability
+	u8				bCurrentAMPDUEnable;		// This indicate Tx A-MPDU capability
+	u8				AMPDU_Factor;				// This indicate Tx A-MPDU capability
+	u8				CurrentAMPDUFactor;		// This indicate Tx A-MPDU capability
+	u8				MPDU_Density;				// This indicate Tx A-MPDU capability
+	u8				CurrentMPDUDensity;			// This indicate Tx A-MPDU capability
+
+	// Forced A-MPDU enable
+	HT_AGGRE_MODE_E	ForcedAMPDUMode;
+	u8				ForcedAMPDUFactor;
+	u8				ForcedMPDUDensity;
+
+	// Forced A-MSDU enable
+	HT_AGGRE_MODE_E	ForcedAMSDUMode;
+	u16				ForcedAMSDUMaxSize;
+
+	u8				bForcedShortGI;
+
+	u8				CurrentOpMode;
+
+	// MIMO PS related
+	u8				SelfMimoPs;
+	u8				PeerMimoPs;
+
+	// 40MHz Channel Offset settings.
+	HT_EXTCHNL_OFFSET	CurSTAExtChnlOffset;
+	u8				bCurTxBW40MHz;	// If we use 40 MHz to Tx
+	u8				PeerBandwidth;
+
+	// For Bandwidth Switching
+	u8				bSwBwInProgress;
+	CHNLOP				ChnlOp; // software switching channel in progress. By Bruce, 2008-02-15.
+	u8				SwBwStep;
+	//struct timer_list		SwBwTimer;  //moved to ieee80211_device. as timer_list need include some header file here.
+
+	// For Realtek proprietary A-MPDU factor for aggregation
+	u8				bRegRT2RTAggregation;
+	u8				RT2RT_HT_Mode;
+	u8				bCurrentRT2RTAggregation;
+	u8				bCurrentRT2RTLongSlotTime;
+	u8				szRT2RTAggBuffer[10];
+
+	// Rx Reorder control
+	u8				bRegRxReorderEnable;
+	u8				bCurRxReorderEnable;
+	u8				RxReorderWinSize;
+	u8				RxReorderPendingTime;
+	u16				RxReorderDropCounter;
+
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+	u8				UsbTxAggrNum;
+#endif
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	u8				UsbRxFwAggrEn;
+	u8				UsbRxFwAggrPageNum;
+	u8				UsbRxFwAggrPacketNum;
+	u8				UsbRxFwAggrTimeout;
+#endif
+
+	// Add for Broadcom(Linksys) IOT. Joseph
+	u8				bIsPeerBcm;
+
+	// For IOT issue.
+	u8				IOTPeer;
+	u32				IOTAction;
+	u8				IOTRaFunc;
+} __attribute__ ((packed)) RT_HIGH_THROUGHPUT, *PRT_HIGH_THROUGHPUT;
+
+
+//------------------------------------------------------------
+// The Data structure is used to keep HT related variable for "each Sta"
+// when card is configured as "AP mode"
+//------------------------------------------------------------
+
+typedef struct _RT_HTINFO_STA_ENTRY{
+	u8			bEnableHT;
+
+	u8			bSupportCck;
+
+	u16			AMSDU_MaxSize;
+
+	u8			AMPDU_Factor;
+	u8			MPDU_Density;
+
+	u8			HTHighestOperaRate;
+
+	u8			bBw40MHz;
+
+	u8			MimoPs;
+
+	u8			McsRateSet[16];
+
+
+}RT_HTINFO_STA_ENTRY, *PRT_HTINFO_STA_ENTRY;
+
+
+
+
+
+//------------------------------------------------------------
+// The Data structure is used to keep HT related variable for "each AP"
+// when card is configured as "STA mode"
+//------------------------------------------------------------
+
+typedef struct _BSS_HT{
+
+	u8				bdSupportHT;
+
+	// HT related elements
+	u8					bdHTCapBuf[32];
+	u16					bdHTCapLen;
+	u8					bdHTInfoBuf[32];
+	u16					bdHTInfoLen;
+
+	HT_SPEC_VER				bdHTSpecVer;
+	//HT_CAPABILITY_ELE			bdHTCapEle;
+	//HT_INFORMATION_ELE		bdHTInfoEle;
+
+	u8					bdRT2RTAggregation;
+	u8					bdRT2RTLongSlotTime;
+	u8					RT2RT_HT_Mode;
+	bool					bdHT1R;
+} __attribute__ ((packed)) BSS_HT, *PBSS_HT;
+
+typedef struct _MIMO_RSSI{
+	u32	EnableAntenna;
+	u32	AntennaA;
+	u32 	AntennaB;
+	u32 	AntennaC;
+	u32 	AntennaD;
+	u32	Average;
+}MIMO_RSSI, *PMIMO_RSSI;
+
+typedef struct _MIMO_EVM{
+	u32	EVM1;
+	u32    EVM2;
+}MIMO_EVM, *PMIMO_EVM;
+
+typedef struct _FALSE_ALARM_STATISTICS{
+	u32	Cnt_Parity_Fail;
+	u32    Cnt_Rate_Illegal;
+	u32	Cnt_Crc8_fail;
+	u32	Cnt_all;
+}FALSE_ALARM_STATISTICS, *PFALSE_ALARM_STATISTICS;
+
+
+extern u8 MCS_FILTER_ALL[16];
+extern u8 MCS_FILTER_1SS[16];
+
+/* 2007/07/11 MH Modify the macro. Becaus STA may link with a N-AP. If we set
+   STA in A/B/G mode and AP is still in N mode. The macro will be wrong. We have
+   to add a macro to judge wireless mode. */
+#define PICK_RATE(_nLegacyRate, _nMcsRate)	\
+		(_nMcsRate==0)?(_nLegacyRate&0x7f):(_nMcsRate)
+/* 2007/07/12 MH We only define legacy and HT wireless mode now. */
+#define	LEGACY_WIRELESS_MODE	IEEE_MODE_MASK
+
+#define CURRENT_RATE(WirelessMode, LegacyRate, HTRate)	\
+					((WirelessMode & (LEGACY_WIRELESS_MODE))!=0)?\
+						(LegacyRate):\
+						(PICK_RATE(LegacyRate, HTRate))
+
+
+
+// MCS Bw 40 {1~7, 12~15,32}
+#define	RATE_ADPT_1SS_MASK 		0xFF
+#define	RATE_ADPT_2SS_MASK	   	0xF0 //Skip MCS8~11 because mcs7 > mcs6, 9, 10, 11. 2007.01.16 by Emily
+#define	RATE_ADPT_MCS32_MASK		0x01
+
+#define 	IS_11N_MCS_RATE(rate)		(rate&0x80)
+
+typedef enum _HT_AGGRE_SIZE{
+	HT_AGG_SIZE_8K = 0,
+	HT_AGG_SIZE_16K = 1,
+	HT_AGG_SIZE_32K = 2,
+	HT_AGG_SIZE_64K = 3,
+}HT_AGGRE_SIZE_E, *PHT_AGGRE_SIZE_E;
+
+/* Indicate different AP vendor for IOT issue */
+typedef enum _HT_IOT_PEER
+{
+	HT_IOT_PEER_UNKNOWN = 0,
+	HT_IOT_PEER_REALTEK = 1,
+	HT_IOT_PEER_REALTEK_92SE = 2,
+	HT_IOT_PEER_BROADCOM = 3,
+	HT_IOT_PEER_RALINK = 4,
+	HT_IOT_PEER_ATHEROS = 5,
+	HT_IOT_PEER_CISCO= 6,
+	HT_IOT_PEER_MARVELL=7,
+	HT_IOT_PEER_92U_SOFTAP = 8,
+	HT_IOT_PEER_SELF_SOFTAP = 9,
+	HT_IOT_PEER_MAX = 10,
+}HT_IOT_PEER_E, *PHTIOT_PEER_E;
+
+//
+// IOT Action for different AP
+//
+typedef enum _HT_IOT_ACTION{
+	HT_IOT_ACT_TX_USE_AMSDU_4K = 0x00000001,
+	HT_IOT_ACT_TX_USE_AMSDU_8K = 0x00000002,
+	HT_IOT_ACT_DISABLE_MCS14 = 0x00000004,
+	HT_IOT_ACT_DISABLE_MCS15 = 0x00000008,
+	HT_IOT_ACT_DISABLE_ALL_2SS = 0x00000010,
+	HT_IOT_ACT_DISABLE_EDCA_TURBO = 0x00000020,
+	HT_IOT_ACT_MGNT_USE_CCK_6M = 0x00000040,
+	HT_IOT_ACT_CDD_FSYNC = 0x00000080,
+	HT_IOT_ACT_PURE_N_MODE = 0x00000100,
+	HT_IOT_ACT_FORCED_CTS2SELF = 0x00000200,
+	HT_IOT_ACT_FORCED_RTS = 0x00000400,
+	HT_IOT_ACT_AMSDU_ENABLE = 0x00000800,
+	HT_IOT_ACT_MID_HIGHPOWER = 0x00001000,
+	HT_IOT_ACT_REJECT_ADDBA_REQ = 0x00002000,
+	HT_IOT_ACT_ALLOW_PEER_AGG_ONE_PKT = 0x00004000,
+	HT_IOT_ACT_EDCA_BIAS_ON_RX = 0x00008000,
+
+	HT_IOT_ACT_HYBRID_AGGREGATION = 0x00010000,
+	HT_IOT_ACT_DISABLE_SHORT_GI = 0x00020000,
+	HT_IOT_ACT_DISABLE_HIGH_POWER = 0x00040000,
+	HT_IOT_ACT_DISABLE_TX_40_MHZ = 0x00080000,
+	HT_IOT_ACT_TX_NO_AGGREGATION = 0x00100000,
+	HT_IOT_ACT_DISABLE_TX_2SS = 0x00200000,
+}HT_IOT_ACTION_E, *PHT_IOT_ACTION_E;
+
+typedef enum _HT_IOT_RAFUNC{
+	HT_IOT_RAFUNC_PEER_1R = 0x01,
+	HT_IOT_RAFUNC_TX_AMSDU = 0x02,
+	HT_IOT_RAFUNC_DISABLE_ALL = 0x80,
+}HT_IOT_RAFUNC, *PHT_IOT_RAFUNC;
+
+typedef enum _RT_HT_CAP{
+	RT_HT_CAP_USE_TURBO_AGGR = 0x01,
+	RT_HT_CAP_USE_LONG_PREAMBLE = 0x02,
+	RT_HT_CAP_USE_AMPDU = 0x04,
+	RT_HT_CAP_USE_WOW = 0x8,
+	RT_HT_CAP_USE_SOFTAP = 0x10,
+	RT_HT_CAP_USE_92SE = 0x20,
+}RT_HT_CAPBILITY, *PRT_HT_CAPBILITY;
+
+#endif //_RTL819XU_HTTYPE_H_
+
diff --git a/drivers/staging/rtl8192su/ieee80211/rtl819x_HTProc.c b/drivers/staging/rtl8192su/ieee80211/rtl819x_HTProc.c
new file mode 100644
index 0000000..f357085
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/rtl819x_HTProc.c
@@ -0,0 +1,2037 @@
+
+//As this function is mainly ported from Windows driver, so leave the name little changed. If any confusion caused, tell me. Created by WB. 2008.05.08
+#include "ieee80211.h"
+#include "rtl819x_HT.h"
+u8 MCS_FILTER_ALL[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+u8 MCS_FILTER_1SS[16] = {0xff, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+u16 MCS_DATA_RATE[2][2][77] =
+	{	{	{13, 26, 39, 52, 78, 104, 117, 130, 26, 52, 78 ,104, 156, 208, 234, 260,
+			39, 78, 117, 234, 312, 351, 390, 52, 104, 156, 208, 312, 416, 468, 520,
+			0, 78, 104, 130, 117, 156, 195, 104, 130, 130, 156, 182, 182, 208, 156, 195,
+			195, 234, 273, 273, 312, 130, 156, 181, 156, 181, 208, 234, 208, 234, 260, 260,
+			286, 195, 234, 273, 234, 273, 312, 351, 312, 351, 390, 390, 429},			// Long GI, 20MHz
+			{14, 29, 43, 58, 87, 116, 130, 144, 29, 58, 87, 116, 173, 231, 260, 289,
+			43, 87, 130, 173, 260, 347, 390, 433, 58, 116, 173, 231, 347, 462, 520, 578,
+			0, 87, 116, 144, 130, 173, 217, 116, 144, 144, 173, 202, 202, 231, 173, 217,
+			217, 260, 303, 303, 347, 144, 173, 202, 173, 202, 231, 260, 231, 260, 289, 289,
+			318, 217, 260, 303, 260, 303, 347, 390, 347, 390, 433, 433, 477}	},		// Short GI, 20MHz
+		{	{27, 54, 81, 108, 162, 216, 243, 270, 54, 108, 162, 216, 324, 432, 486, 540,
+			81, 162, 243, 324, 486, 648, 729, 810, 108, 216, 324, 432, 648, 864, 972, 1080,
+			12, 162, 216, 270, 243, 324, 405, 216, 270, 270, 324, 378, 378, 432, 324, 405,
+			405, 486, 567, 567, 648, 270, 324, 378, 324, 378, 432, 486, 432, 486, 540, 540,
+			594, 405, 486, 567, 486, 567, 648, 729, 648, 729, 810, 810, 891}, 	// Long GI, 40MHz
+			{30, 60, 90, 120, 180, 240, 270, 300, 60, 120, 180, 240, 360, 480, 540, 600,
+			90, 180, 270, 360, 540, 720, 810, 900, 120, 240, 360, 480, 720, 960, 1080, 1200,
+			13, 180, 240, 300, 270, 360, 450, 240, 300, 300, 360, 420, 420, 480, 360, 450,
+			450, 540, 630, 630, 720, 300, 360, 420, 360, 420, 480, 540, 480, 540, 600, 600,
+			660, 450, 540, 630, 540, 630, 720, 810, 720, 810, 900, 900, 990}	}	// Short GI, 40MHz
+	};
+
+static u8 UNKNOWN_BORADCOM[3] = {0x00, 0x14, 0xbf};
+static u8 LINKSYSWRT330_LINKSYSWRT300_BROADCOM[3] = {0x00, 0x1a, 0x70};
+static u8 LINKSYSWRT350_LINKSYSWRT150_BROADCOM[3] = {0x00, 0x1d, 0x7e};
+static u8 NETGEAR834Bv2_BROADCOM[3] = {0x00, 0x1b, 0x2f};
+static u8 BELKINF5D8233V1_RALINK[3] = {0x00, 0x17, 0x3f};	//cosa 03202008
+static u8 BELKINF5D82334V3_RALINK[3] = {0x00, 0x1c, 0xdf};
+static u8 PCI_RALINK[3] = {0x00, 0x90, 0xcc};
+static u8 EDIMAX_RALINK[3] = {0x00, 0x0e, 0x2e};
+static u8 AIRLINK_RALINK[3] = {0x00, 0x18, 0x02};
+static u8 DLINK_ATHEROS_1[3] = {0x00, 0x1c, 0xf0};
+static u8 DLINK_ATHEROS_2[3] = {0x00, 0x21, 0x91};
+static u8 CISCO_BROADCOM[3] = {0x00, 0x17, 0x94};
+static u8 LINKSYS_MARVELL_4400N[3] = {0x00, 0x14, 0xa4};
+// 2008/04/01 MH For Cisco G mode RX TP We need to change FW duration. Shoud we put the
+// code in other place??
+//static u8 WIFI_CISCO_G_AP[3] = {0x00, 0x40, 0x96};
+/********************************************************************************************************************
+ *function:  This function update default settings in pHTInfo structure
+ *   input:  PRT_HIGH_THROUGHPUT	pHTInfo
+ *  output:  none
+ *  return:  none
+ *  notice:  These value need be modified if any changes.
+ * *****************************************************************************************************************/
+void HTUpdateDefaultSetting(struct ieee80211_device* ieee)
+{
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	//const typeof( ((struct ieee80211_device *)0)->pHTInfo ) *__mptr = &pHTInfo;
+
+	//printk("pHTinfo:%p, &pHTinfo:%p, mptr:%p,  offsetof:%x\n", pHTInfo, &pHTInfo, __mptr, offsetof(struct ieee80211_device, pHTInfo));
+	//printk("===>ieee:%p,\n", ieee);
+	// ShortGI support
+	pHTInfo->bRegShortGI20MHz= 1;
+	pHTInfo->bRegShortGI40MHz= 1;
+
+	// 40MHz channel support
+	pHTInfo->bRegBW40MHz = 1;
+
+	// CCK rate support in 40MHz channel
+	if(pHTInfo->bRegBW40MHz)
+		pHTInfo->bRegSuppCCK = 1;
+	else
+		pHTInfo->bRegSuppCCK = true;
+
+	// AMSDU related
+	pHTInfo->nAMSDU_MaxSize = 7935UL;
+	pHTInfo->bAMSDU_Support = 0;
+
+	// AMPDU related
+	pHTInfo->bAMPDUEnable = 1; //YJ,test,090311
+	pHTInfo->AMPDU_Factor = 2; //// 0: 2n13(8K), 1:2n14(16K), 2:2n15(32K), 3:2n16(64k)
+	pHTInfo->MPDU_Density = 0;// 0: No restriction, 1: 1/8usec, 2: 1/4usec, 3: 1/2usec, 4: 1usec, 5: 2usec, 6: 4usec, 7:8usec
+
+	// MIMO Power Save
+	pHTInfo->SelfMimoPs = 3;// 0: Static Mimo Ps, 1: Dynamic Mimo Ps, 3: No Limitation, 2: Reserved(Set to 3 automatically.)
+	if(pHTInfo->SelfMimoPs == 2)
+		pHTInfo->SelfMimoPs = 3;
+	// 8190 only. Assign rate operation mode to firmware
+	ieee->bTxDisableRateFallBack = 0;
+	ieee->bTxUseDriverAssingedRate = 0;
+
+#ifdef 	TO_DO_LIST
+	// 8190 only. Assign duration operation mode to firmware
+	pMgntInfo->bTxEnableFwCalcDur = (BOOLEAN)pNdisCommon->bRegTxEnableFwCalcDur;
+#endif
+	// 8190 only, Realtek proprietary aggregation mode
+	// Set MPDUDensity=2,   1: Set MPDUDensity=2(32k)  for Realtek AP and set MPDUDensity=0(8k) for others
+	pHTInfo->bRegRT2RTAggregation = 1;//0: Set MPDUDensity=2,   1: Set MPDUDensity=2(32k)  for Realtek AP and set MPDUDensity=0(8k) for others
+
+	// For Rx Reorder Control
+	pHTInfo->bRegRxReorderEnable = 1;//YJ,test,090311
+	pHTInfo->RxReorderWinSize = 64;
+	pHTInfo->RxReorderPendingTime = 30;
+
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+	pHTInfo->UsbTxAggrNum = 4;
+#endif
+#ifdef USB_RX_AGGREGATION_SUPPORT
+#ifdef RTL8192SU
+	pHTInfo->UsbRxFwAggrEn = 1;
+	pHTInfo->UsbRxFwAggrPageNum = 16;
+	pHTInfo->UsbRxFwAggrPacketNum = 8;
+	pHTInfo->UsbRxFwAggrTimeout = 4; ////usb rx FW aggregation timeout threshold.It's in units of 64us
+	// For page size of receive packet buffer.
+	pHTInfo->UsbRxPageSize= 128;
+#else
+	pHTInfo->UsbRxFwAggrEn = 1;
+	pHTInfo->UsbRxFwAggrPageNum = 24;
+	pHTInfo->UsbRxFwAggrPacketNum = 8;
+	pHTInfo->UsbRxFwAggrTimeout = 16; ////usb rx FW aggregation timeout threshold.It's in units of 64us
+#endif
+#endif
+
+
+}
+/********************************************************************************************************************
+ *function:  This function print out each field on HT capability IE mainly from (Beacon/ProbeRsp/AssocReq)
+ *   input:  u8*	CapIE       //Capability IE to be printed out
+ *   	     u8* 	TitleString //mainly print out caller function
+ *  output:  none
+ *  return:  none
+ *  notice:  Driver should not print out this message by default.
+ * *****************************************************************************************************************/
+void HTDebugHTCapability(u8* CapIE, u8* TitleString )
+{
+
+	static u8	EWC11NHTCap[] = {0x00, 0x90, 0x4c, 0x33};	// For 11n EWC definition, 2007.07.17, by Emily
+	PHT_CAPABILITY_ELE 		pCapELE;
+
+	if(!memcmp(CapIE, EWC11NHTCap, sizeof(EWC11NHTCap)))
+	{
+		//EWC IE
+		IEEE80211_DEBUG(IEEE80211_DL_HT, "EWC IE in %s()\n", __FUNCTION__);
+		pCapELE = (PHT_CAPABILITY_ELE)(&CapIE[4]);
+	}else
+		pCapELE = (PHT_CAPABILITY_ELE)(&CapIE[0]);
+
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "<Log HT Capability>. Called by %s\n", TitleString );
+
+	IEEE80211_DEBUG(IEEE80211_DL_HT,  "\tSupported Channel Width = %s\n", (pCapELE->ChlWidth)?"20MHz": "20/40MHz");
+	IEEE80211_DEBUG(IEEE80211_DL_HT,  "\tSupport Short GI for 20M = %s\n", (pCapELE->ShortGI20Mhz)?"YES": "NO");
+	IEEE80211_DEBUG(IEEE80211_DL_HT,  "\tSupport Short GI for 40M = %s\n", (pCapELE->ShortGI40Mhz)?"YES": "NO");
+	IEEE80211_DEBUG(IEEE80211_DL_HT,  "\tSupport TX STBC = %s\n", (pCapELE->TxSTBC)?"YES": "NO");
+	IEEE80211_DEBUG(IEEE80211_DL_HT,  "\tMax AMSDU Size = %s\n", (pCapELE->MaxAMSDUSize)?"3839": "7935");
+	IEEE80211_DEBUG(IEEE80211_DL_HT,  "\tSupport CCK in 20/40 mode = %s\n", (pCapELE->DssCCk)?"YES": "NO");
+	IEEE80211_DEBUG(IEEE80211_DL_HT,  "\tMax AMPDU Factor = %d\n", pCapELE->MaxRxAMPDUFactor);
+	IEEE80211_DEBUG(IEEE80211_DL_HT,  "\tMPDU Density = %d\n", pCapELE->MPDUDensity);
+	IEEE80211_DEBUG(IEEE80211_DL_HT,  "\tMCS Rate Set = [%x][%x][%x][%x][%x]\n", pCapELE->MCS[0],\
+				pCapELE->MCS[1], pCapELE->MCS[2], pCapELE->MCS[3], pCapELE->MCS[4]);
+	return;
+
+}
+/********************************************************************************************************************
+ *function:  This function print out each field on HT Information IE mainly from (Beacon/ProbeRsp)
+ *   input:  u8*	InfoIE       //Capability IE to be printed out
+ *   	     u8* 	TitleString //mainly print out caller function
+ *  output:  none
+ *  return:  none
+ *  notice:  Driver should not print out this message by default.
+ * *****************************************************************************************************************/
+void HTDebugHTInfo(u8*	InfoIE, u8* TitleString)
+{
+
+	static u8	EWC11NHTInfo[] = {0x00, 0x90, 0x4c, 0x34};	// For 11n EWC definition, 2007.07.17, by Emily
+	PHT_INFORMATION_ELE		pHTInfoEle;
+
+	if(!memcmp(InfoIE, EWC11NHTInfo, sizeof(EWC11NHTInfo)))
+	{
+		// Not EWC IE
+		IEEE80211_DEBUG(IEEE80211_DL_HT, "EWC IE in %s()\n", __FUNCTION__);
+		pHTInfoEle = (PHT_INFORMATION_ELE)(&InfoIE[4]);
+	}else
+		pHTInfoEle = (PHT_INFORMATION_ELE)(&InfoIE[0]);
+
+
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "<Log HT Information Element>. Called by %s\n", TitleString);
+
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "\tPrimary channel = %d\n", pHTInfoEle->ControlChl);
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "\tSenondary channel =");
+	switch(pHTInfoEle->ExtChlOffset)
+	{
+		case 0:
+			IEEE80211_DEBUG(IEEE80211_DL_HT, "Not Present\n");
+			break;
+		case 1:
+			IEEE80211_DEBUG(IEEE80211_DL_HT, "Upper channel\n");
+			break;
+		case 2:
+			IEEE80211_DEBUG(IEEE80211_DL_HT, "Reserved. Eooro!!!\n");
+			break;
+		case 3:
+			IEEE80211_DEBUG(IEEE80211_DL_HT, "Lower Channel\n");
+			break;
+	}
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "\tRecommended channel width = %s\n", (pHTInfoEle->RecommemdedTxWidth)?"20Mhz": "40Mhz");
+
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "\tOperation mode for protection = ");
+	switch(pHTInfoEle->OptMode)
+	{
+		case 0:
+			IEEE80211_DEBUG(IEEE80211_DL_HT, "No Protection\n");
+			break;
+		case 1:
+			IEEE80211_DEBUG(IEEE80211_DL_HT, "HT non-member protection mode\n");
+			break;
+		case 2:
+			IEEE80211_DEBUG(IEEE80211_DL_HT, "Suggest to open protection\n");
+			break;
+		case 3:
+			IEEE80211_DEBUG(IEEE80211_DL_HT, "HT mixed mode\n");
+			break;
+	}
+
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "\tBasic MCS Rate Set = [%x][%x][%x][%x][%x]\n", pHTInfoEle->BasicMSC[0],\
+				pHTInfoEle->BasicMSC[1], pHTInfoEle->BasicMSC[2], pHTInfoEle->BasicMSC[3], pHTInfoEle->BasicMSC[4]);
+	return;
+}
+
+/*
+*	Return:     	true if station in half n mode and AP supports 40 bw
+*/
+bool IsHTHalfNmode40Bandwidth(struct ieee80211_device* ieee)
+{
+	bool			retValue = false;
+	PRT_HIGH_THROUGHPUT	 pHTInfo = ieee->pHTInfo;
+
+	if(pHTInfo->bCurrentHTSupport == false )	// wireless is n mode
+		retValue = false;
+	else if(pHTInfo->bRegBW40MHz == false)	// station supports 40 bw
+		retValue = false;
+	else if(!ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev)) 	// station in half n mode
+		retValue = false;
+	else if(((PHT_CAPABILITY_ELE)(pHTInfo->PeerHTCapBuf))->ChlWidth) // ap support 40 bw
+		retValue = true;
+	else
+		retValue = false;
+
+	return retValue;
+}
+
+bool IsHTHalfNmodeSGI(struct ieee80211_device* ieee, bool is40MHz)
+{
+	bool			retValue = false;
+	PRT_HIGH_THROUGHPUT	 pHTInfo = ieee->pHTInfo;
+
+	if(pHTInfo->bCurrentHTSupport == false )	// wireless is n mode
+		retValue = false;
+	else if(!ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev)) 	// station in half n mode
+		retValue = false;
+	else if(is40MHz) // ap support 40 bw
+	{
+		if(((PHT_CAPABILITY_ELE)(pHTInfo->PeerHTCapBuf))->ShortGI40Mhz) // ap support 40 bw short GI
+			retValue = true;
+		else
+			retValue = false;
+	}
+	else
+	{
+		if(((PHT_CAPABILITY_ELE)(pHTInfo->PeerHTCapBuf))->ShortGI20Mhz) // ap support 40 bw short GI
+			retValue = true;
+		else
+			retValue = false;
+	}
+
+	return retValue;
+}
+
+u16 HTHalfMcsToDataRate(struct ieee80211_device* ieee, 	u8	nMcsRate)
+{
+
+	u8	is40MHz;
+	u8	isShortGI;
+
+	is40MHz  =  (IsHTHalfNmode40Bandwidth(ieee))?1:0;
+	isShortGI = (IsHTHalfNmodeSGI(ieee, is40MHz))? 1:0;
+
+	return MCS_DATA_RATE[is40MHz][isShortGI][(nMcsRate&0x7f)];
+}
+
+
+u16 HTMcsToDataRate( struct ieee80211_device* ieee, u8 nMcsRate)
+{
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+
+	u8	is40MHz = (pHTInfo->bCurBW40MHz)?1:0;
+	u8	isShortGI = (pHTInfo->bCurBW40MHz)?
+						((pHTInfo->bCurShortGI40MHz)?1:0):
+						((pHTInfo->bCurShortGI20MHz)?1:0);
+	return MCS_DATA_RATE[is40MHz][isShortGI][(nMcsRate&0x7f)];
+}
+
+/********************************************************************************************************************
+ *function:  This function returns current datarate.
+ *   input:  struct ieee80211_device* 	ieee
+ *   	     u8 			nDataRate
+ *  output:  none
+ *  return:  tx rate
+ *  notice:  quite unsure about how to use this function //wb
+ * *****************************************************************************************************************/
+u16  TxCountToDataRate( struct ieee80211_device* ieee, u8 nDataRate)
+{
+	//PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	u16		CCKOFDMRate[12] = {0x02 , 0x04 , 0x0b , 0x16 , 0x0c , 0x12 , 0x18 , 0x24 , 0x30 , 0x48 , 0x60 , 0x6c};
+	u8	is40MHz = 0;
+	u8	isShortGI = 0;
+
+	if(nDataRate < 12)
+	{
+		return CCKOFDMRate[nDataRate];
+	}
+	else
+	{
+		if (nDataRate >= 0x10 && nDataRate <= 0x1f)//if(nDataRate > 11 && nDataRate < 28 )
+		{
+			is40MHz = 0;
+			isShortGI = 0;
+
+		      // nDataRate = nDataRate - 12;
+		}
+		else if(nDataRate >=0x20  && nDataRate <= 0x2f ) //(27, 44)
+		{
+			is40MHz = 1;
+			isShortGI = 0;
+
+			//nDataRate = nDataRate - 28;
+		}
+		else if(nDataRate >= 0x30  && nDataRate <= 0x3f )  //(43, 60)
+		{
+			is40MHz = 0;
+			isShortGI = 1;
+
+			//nDataRate = nDataRate - 44;
+		}
+		else if(nDataRate >= 0x40  && nDataRate <= 0x4f ) //(59, 76)
+		{
+			is40MHz = 1;
+			isShortGI = 1;
+
+			//nDataRate = nDataRate - 60;
+		}
+		return MCS_DATA_RATE[is40MHz][isShortGI][nDataRate&0xf];
+	}
+}
+
+
+
+bool IsHTHalfNmodeAPs(struct ieee80211_device* ieee)
+{
+	bool			retValue = false;
+	struct ieee80211_network* net = &ieee->current_network;
+#if 0
+	if(pMgntInfo->bHalfNMode == false)
+		retValue = false;
+	else
+#endif
+	if((memcmp(net->bssid, BELKINF5D8233V1_RALINK, 3)==0) ||
+		     (memcmp(net->bssid, BELKINF5D82334V3_RALINK, 3)==0) ||
+		     (memcmp(net->bssid, PCI_RALINK, 3)==0) ||
+		     (memcmp(net->bssid, EDIMAX_RALINK, 3)==0) ||
+		     (memcmp(net->bssid, AIRLINK_RALINK, 3)==0) ||
+		     (net->ralink_cap_exist))
+		retValue = true;
+	else if((memcmp(net->bssid, UNKNOWN_BORADCOM, 3)==0) ||
+    		    (memcmp(net->bssid, LINKSYSWRT330_LINKSYSWRT300_BROADCOM, 3)==0)||
+    		    (memcmp(net->bssid, LINKSYSWRT350_LINKSYSWRT150_BROADCOM, 3)==0)||
+    		    (memcmp(net->bssid, NETGEAR834Bv2_BROADCOM, 3)==0) ||
+    		    (net->broadcom_cap_exist))
+    		  retValue = true;
+	else if(net->bssht.bdRT2RTAggregation)
+		retValue = true;
+	else
+		retValue = false;
+
+	return retValue;
+}
+
+/********************************************************************************************************************
+ *function:  This function returns peer IOT.
+ *   input:  struct ieee80211_device* 	ieee
+ *  output:  none
+ *  return:
+ *  notice:
+ * *****************************************************************************************************************/
+void HTIOTPeerDetermine(struct ieee80211_device* ieee)
+{
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	struct ieee80211_network* net = &ieee->current_network;
+	//FIXME: need to decide  92U_SOFTAP //LZM,090320
+	if(net->bssht.bdRT2RTAggregation){
+		pHTInfo->IOTPeer = HT_IOT_PEER_REALTEK;
+		if(net->bssht.RT2RT_HT_Mode & RT_HT_CAP_USE_92SE){
+			pHTInfo->IOTPeer = HT_IOT_PEER_REALTEK_92SE;
+		}
+	}
+	else if(net->broadcom_cap_exist)
+		pHTInfo->IOTPeer = HT_IOT_PEER_BROADCOM;
+	else if((memcmp(net->bssid, UNKNOWN_BORADCOM, 3)==0) ||
+			(memcmp(net->bssid, LINKSYSWRT330_LINKSYSWRT300_BROADCOM, 3)==0)||
+			(memcmp(net->bssid, LINKSYSWRT350_LINKSYSWRT150_BROADCOM, 3)==0)||
+			(memcmp(net->bssid, NETGEAR834Bv2_BROADCOM, 3)==0) )
+		pHTInfo->IOTPeer = HT_IOT_PEER_BROADCOM;
+	else if((memcmp(net->bssid, BELKINF5D8233V1_RALINK, 3)==0) ||
+			(memcmp(net->bssid, BELKINF5D82334V3_RALINK, 3)==0) ||
+			(memcmp(net->bssid, PCI_RALINK, 3)==0) ||
+			(memcmp(net->bssid, EDIMAX_RALINK, 3)==0) ||
+			(memcmp(net->bssid, AIRLINK_RALINK, 3)==0) ||
+			 net->ralink_cap_exist)
+		pHTInfo->IOTPeer = HT_IOT_PEER_RALINK;
+	else if((net->atheros_cap_exist )||
+		(memcmp(net->bssid, DLINK_ATHEROS_1, 3) == 0)||
+		(memcmp(net->bssid, DLINK_ATHEROS_2, 3) == 0))
+		pHTInfo->IOTPeer = HT_IOT_PEER_ATHEROS;
+	else if(memcmp(net->bssid, CISCO_BROADCOM, 3)==0)
+		pHTInfo->IOTPeer = HT_IOT_PEER_CISCO;
+	else if ((memcmp(net->bssid, LINKSYS_MARVELL_4400N, 3) == 0) ||
+		  net->marvell_cap_exist)
+		pHTInfo->IOTPeer = HT_IOT_PEER_MARVELL;
+	else
+		pHTInfo->IOTPeer = HT_IOT_PEER_UNKNOWN;
+
+	IEEE80211_DEBUG(IEEE80211_DL_IOT, "Joseph debug!! IOTPEER: %x\n", pHTInfo->IOTPeer);
+}
+/********************************************************************************************************************
+ *function:  Check whether driver should declare received rate up to MCS13 only since some chipset is not good
+ *	     at receiving MCS14~15 frame from some AP.
+ *   input:  struct ieee80211_device* 	ieee
+ *   	     u8 *			PeerMacAddr
+ *  output:  none
+ *  return:  return 1 if driver should declare MCS13 only(otherwise return 0)
+  * *****************************************************************************************************************/
+u8 HTIOTActIsDisableMCS14(struct ieee80211_device* ieee, u8* PeerMacAddr)
+{
+	u8 ret = 0;
+#if 0
+	// Apply for 819u only
+#if (HAL_CODE_BASE==RTL8192 && DEV_BUS_TYPE==USB_INTERFACE)
+	if((memcmp(PeerMacAddr, UNKNOWN_BORADCOM, 3)==0) ||
+    		(memcmp(PeerMacAddr, LINKSYSWRT330_LINKSYSWRT300_BROADCOM, 3)==0)
+	    )
+	{
+		ret = 1;
+	}
+
+
+	if(pHTInfo->bCurrentRT2RTAggregation)
+	{
+		// The parameter of pHTInfo->bCurrentRT2RTAggregation must be decided previously
+		ret = 1;
+	}
+#endif
+#endif
+	return ret;
+ }
+
+
+/**
+* Function:	HTIOTActIsDisableMCS15
+*
+* Overview:	Check whether driver should declare capability of receving MCS15
+*
+* Input:
+*			PADAPTER		Adapter,
+*
+* Output:		None
+* Return:     	true if driver should disable MCS15
+* 2008.04.15	Emily
+*/
+bool HTIOTActIsDisableMCS15(struct ieee80211_device* ieee)
+{
+	bool retValue = false;
+
+#ifdef TODO
+	// Apply for 819u only
+#if (HAL_CODE_BASE==RTL8192)
+
+#if (DEV_BUS_TYPE == USB_INTERFACE)
+	// Alway disable MCS15 by Jerry Chang's request.by Emily, 2008.04.15
+	retValue = true;
+#elif (DEV_BUS_TYPE == PCI_INTERFACE)
+	// Enable MCS15 if the peer is Cisco AP. by Emily, 2008.05.12
+//	if(pBssDesc->bCiscoCapExist)
+//		retValue = false;
+//	else
+		retValue = false;
+#endif
+#endif
+#endif
+	// Jerry Chang suggest that 8190 1x2 does not need to disable MCS15
+
+	return retValue;
+}
+
+/**
+* Function:	HTIOTActIsDisableMCSTwoSpatialStream
+*
+* Overview:	Check whether driver should declare capability of receving All 2 ss packets
+*
+* Input:
+*		PADAPTER		Adapter,
+*
+* Output:	None
+* Return:     	true if driver should disable all two spatial stream packet
+* 2008.04.21	Emily
+*/
+bool HTIOTActIsDisableMCSTwoSpatialStream(struct ieee80211_device* ieee)
+{
+	bool retValue = false;
+#ifdef TODO
+	// Apply for 819u only
+//#if (HAL_CODE_BASE==RTL8192)
+
+	//This rule only apply to Belkin(Ralink) AP
+	if(IS_UNDER_11N_AES_MODE(Adapter))
+	{
+		if((PlatformCompareMemory(PeerMacAddr, BELKINF5D8233V1_RALINK, 3)==0) ||
+				(PlatformCompareMemory(PeerMacAddr, PCI_RALINK, 3)==0) ||
+				(PlatformCompareMemory(PeerMacAddr, EDIMAX_RALINK, 3)==0))
+		{
+			//Set True to disable this function. Disable by default, Emily, 2008.04.23
+			retValue = false;
+		}
+	}
+
+//#endif
+#endif
+#if 1
+#if (defined(RTL8192SE) || (defined(RTL8192SU)))
+       PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	if(ieee->is_ap_in_wep_tkip && ieee->is_ap_in_wep_tkip(ieee->dev))
+	{
+		if( (pHTInfo->IOTPeer != HT_IOT_PEER_ATHEROS) &&
+		    (pHTInfo->IOTPeer != HT_IOT_PEER_UNKNOWN) &&
+		    (pHTInfo->IOTPeer != HT_IOT_PEER_MARVELL) )
+			retValue = true;
+	}
+#endif
+#endif
+	return retValue;
+}
+
+/********************************************************************************************************************
+ *function:  Check whether driver should disable EDCA turbo mode
+ *   input:  struct ieee80211_device* 	ieee
+ *   	     u8* 			PeerMacAddr
+ *  output:  none
+ *  return:  return 1 if driver should disable EDCA turbo mode(otherwise return 0)
+  * *****************************************************************************************************************/
+u8 HTIOTActIsDisableEDCATurbo(struct ieee80211_device* 	ieee, u8* PeerMacAddr)
+{
+	u8	retValue = false;	// default enable EDCA Turbo mode.
+	// Set specific EDCA parameter for different AP in DM handler.
+
+	return retValue;
+#if 0
+	if((memcmp(PeerMacAddr, UNKNOWN_BORADCOM, 3)==0)||
+		(memcmp(PeerMacAddr, LINKSYSWRT330_LINKSYSWRT300_BROADCOM, 3)==0)||
+		(memcmp(PeerMacAddr, LINKSYSWRT350_LINKSYSWRT150_BROADCOM, 3)==0)||
+		(memcmp(PeerMacAddr, NETGEAR834Bv2_BROADCOM, 3)==0))
+
+	{
+		retValue = 1;	//Linksys disable EDCA turbo mode
+	}
+
+	return retValue;
+#endif
+}
+
+/********************************************************************************************************************
+ *function:  Check whether we need to use OFDM to sned MGNT frame for broadcom AP
+ *   input:  struct ieee80211_network *network   //current network we live
+ *  output:  none
+ *  return:  return 1 if true
+  * *****************************************************************************************************************/
+u8 HTIOTActIsMgntUseCCK6M(struct ieee80211_network *network)
+{
+	u8	retValue = 0;
+
+	// 2008/01/25 MH Judeg if we need to use OFDM to sned MGNT frame for broadcom AP.
+	// 2008/01/28 MH We must prevent that we select null bssid to link.
+
+	if(network->broadcom_cap_exist)
+	{
+		retValue = 1;
+	}
+
+	return retValue;
+}
+
+u8 HTIOTActIsForcedCTS2Self(struct ieee80211_network *network)
+{
+	u8 	retValue = 0;
+
+	if(network->marvell_cap_exist)
+	{
+		retValue = 1;
+	}
+
+	return retValue;
+}
+
+u8 HTIOTActIsForcedRTSCTS(struct ieee80211_device *ieee, struct ieee80211_network *network)
+{
+	u8	retValue = 0;
+	printk("============>%s(), %d\n", __FUNCTION__, network->realtek_cap_exit);
+	// Force protection
+#if defined(RTL8192SE) || defined(RTL8192SU)
+	if(ieee->pHTInfo->bCurrentHTSupport)
+	{
+		//if(!network->realtek_cap_exit)
+		if((ieee->pHTInfo->IOTPeer != HT_IOT_PEER_REALTEK)&&
+		   (ieee->pHTInfo->IOTPeer != HT_IOT_PEER_REALTEK_92SE))
+	{
+			if((ieee->pHTInfo->IOTAction & HT_IOT_ACT_TX_NO_AGGREGATION) == 0)
+				retValue = 1;
+		}
+	}
+#endif
+	return retValue;
+}
+
+u8
+HTIOTActIsForcedAMSDU8K(struct ieee80211_device *ieee, struct ieee80211_network *network)
+{
+	u8 retValue = 0;
+
+	return retValue;
+}
+
+u8 HTIOTActIsCCDFsync(u8* PeerMacAddr)
+{
+	u8	retValue = 0;
+#ifndef RTL8192SE
+	if(	(memcmp(PeerMacAddr, UNKNOWN_BORADCOM, 3)==0) ||
+	    	(memcmp(PeerMacAddr, LINKSYSWRT330_LINKSYSWRT300_BROADCOM, 3)==0) ||
+	    	(memcmp(PeerMacAddr, LINKSYSWRT350_LINKSYSWRT150_BROADCOM, 3) ==0))
+	{
+		retValue = 1;
+	}
+#endif
+	return retValue;
+}
+
+/*
+  *  819xS single chip b-cut series cannot handle BAR
+  */
+u8
+HTIOCActRejcectADDBARequest(struct ieee80211_network *network)
+{
+	u8	retValue = 0;
+	//if(IS_HARDWARE_TYPE_8192SE(Adapter) ||
+	//	IS_HARDWARE_TYPE_8192SU(Adapter)
+	//)
+#if (defined RTL8192SE || defined RTL8192SU)
+	{
+		// Do not reject ADDBA REQ because some of the AP may
+		// keep on sending ADDBA REQ qhich cause DHCP fail or ping loss!
+		// by HPFan, 2008/12/30
+
+		//if(pBssDesc->Vender == HT_IOT_PEER_MARVELL)
+		//	return FALSE;
+
+	}
+#endif
+
+	return retValue;
+
+}
+
+/*
+  *  EDCA parameters bias on downlink
+  */
+  u8
+  HTIOTActIsEDCABiasRx(struct ieee80211_device* ieee,struct ieee80211_network *network)
+{
+	u8	retValue = 0;
+	//if(IS_HARDWARE_TYPE_8192SU(Adapter))
+#ifdef RTL8192SU
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	{
+//#if UNDER_VISTA
+//		if(pBssDesc->Vender==HT_IOT_PEER_ATHEROS ||
+//			pBssDesc->Vender==HT_IOT_PEER_RALINK)
+//#else
+		if(pHTInfo->IOTPeer==HT_IOT_PEER_ATHEROS ||
+		   pHTInfo->IOTPeer==HT_IOT_PEER_BROADCOM ||
+		   pHTInfo->IOTPeer==HT_IOT_PEER_RALINK)
+//#endif
+			return 1;
+
+	}
+#endif
+	return retValue;
+}
+
+u8
+HTIOTActDisableShortGI(struct ieee80211_device* ieee,struct ieee80211_network *network)
+{
+	u8	retValue = 0;
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+
+	if(pHTInfo->IOTPeer==HT_IOT_PEER_RALINK)
+	{
+		if(network->bssht.bdHT1R)
+			retValue = 1;
+	}
+
+	return retValue;
+}
+
+u8
+HTIOTActDisableHighPower(struct ieee80211_device* ieee,struct ieee80211_network *network)
+{
+	u8	retValue = 0;
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+
+	if(pHTInfo->IOTPeer==HT_IOT_PEER_RALINK)
+	{
+		if(network->bssht.bdHT1R)
+			retValue = 1;
+	}
+
+	return retValue;
+}
+
+void
+HTIOTActDetermineRaFunc(struct ieee80211_device* ieee,	bool	bPeerRx2ss)
+{
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	pHTInfo->IOTRaFunc &= HT_IOT_RAFUNC_DISABLE_ALL;
+
+	if(pHTInfo->IOTPeer == HT_IOT_PEER_RALINK && !bPeerRx2ss)
+		pHTInfo->IOTRaFunc |= HT_IOT_RAFUNC_PEER_1R;
+
+	if(pHTInfo->IOTAction & HT_IOT_ACT_AMSDU_ENABLE)
+		pHTInfo->IOTRaFunc |= HT_IOT_RAFUNC_TX_AMSDU;
+
+	printk("!!!!!!!!!!!!!!!!!!!!!!!!!!!IOTRaFunc = %8.8x\n", pHTInfo->IOTRaFunc);
+}
+
+
+u8
+HTIOTActIsDisableTx40MHz(struct ieee80211_device* ieee,struct ieee80211_network *network)
+{
+	u8	retValue = 0;
+
+#if (defined RTL8192SU || defined RTL8192SE)
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	if(	(KEY_TYPE_WEP104 == ieee->pairwise_key_type) ||
+		(KEY_TYPE_WEP40 == ieee->pairwise_key_type) ||
+		(KEY_TYPE_WEP104 == ieee->group_key_type) ||
+		(KEY_TYPE_WEP40 == ieee->group_key_type) ||
+		(KEY_TYPE_TKIP == ieee->pairwise_key_type) )
+	{
+		if((pHTInfo->IOTPeer==HT_IOT_PEER_REALTEK) && (network->bssht.bdSupportHT))
+			retValue = 1;
+	}
+#endif
+
+	return retValue;
+}
+
+u8
+HTIOTActIsTxNoAggregation(struct ieee80211_device* ieee,struct ieee80211_network *network)
+{
+	u8 retValue = 0;
+
+#if (defined RTL8192SU || defined RTL8192SE)
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	if(	(KEY_TYPE_WEP104 == ieee->pairwise_key_type) ||
+		(KEY_TYPE_WEP40 == ieee->pairwise_key_type) ||
+		(KEY_TYPE_WEP104 == ieee->group_key_type) ||
+		(KEY_TYPE_WEP40 == ieee->group_key_type) ||
+		(KEY_TYPE_TKIP == ieee->pairwise_key_type) )
+	{
+		if(pHTInfo->IOTPeer==HT_IOT_PEER_REALTEK ||
+		    pHTInfo->IOTPeer==HT_IOT_PEER_UNKNOWN)
+			retValue = 1;
+	}
+#endif
+
+	return retValue;
+}
+
+
+u8
+HTIOTActIsDisableTx2SS(struct ieee80211_device* ieee,struct ieee80211_network *network)
+{
+	u8	retValue = 0;
+
+#if (defined RTL8192SU || defined RTL8192SE)
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	if(	(KEY_TYPE_WEP104 == ieee->pairwise_key_type) ||
+		(KEY_TYPE_WEP40 == ieee->pairwise_key_type) ||
+		(KEY_TYPE_WEP104 == ieee->group_key_type) ||
+		(KEY_TYPE_WEP40 == ieee->group_key_type) ||
+		(KEY_TYPE_TKIP == ieee->pairwise_key_type) )
+	{
+		if((pHTInfo->IOTPeer==HT_IOT_PEER_REALTEK) && (network->bssht.bdSupportHT))
+			retValue = 1;
+	}
+#endif
+
+	return retValue;
+}
+
+
+bool HTIOCActAllowPeerAggOnePacket(struct ieee80211_device* ieee,struct ieee80211_network *network)
+{
+	bool 	retValue = false;
+#if defined(RTL8192SE) || defined(RTL8192SU)
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	{
+		if(pHTInfo->IOTPeer == HT_IOT_PEER_MARVELL)
+			return true;
+
+	}
+#endif
+	return retValue;
+}
+
+void HTResetIOTSetting(
+	PRT_HIGH_THROUGHPUT		pHTInfo
+)
+{
+	pHTInfo->IOTAction = 0;
+	pHTInfo->IOTPeer = HT_IOT_PEER_UNKNOWN;
+	pHTInfo->IOTRaFunc = 0;
+}
+
+
+/********************************************************************************************************************
+ *function:  Construct Capablility Element in Beacon... if HTEnable is turned on
+ *   input:  struct ieee80211_device* 	ieee
+ *   	     u8* 			posHTCap //pointer to store Capability Ele
+ *   	     u8*			len //store length of CE
+ *   	     u8				IsEncrypt //whether encrypt, needed further
+ *  output:  none
+ *  return:  none
+ *  notice:  posHTCap can't be null and should be initialized before.
+  * *****************************************************************************************************************/
+void HTConstructCapabilityElement(struct ieee80211_device* ieee, u8* posHTCap, u8* len, u8 IsEncrypt)
+{
+	PRT_HIGH_THROUGHPUT	pHT = ieee->pHTInfo;
+	PHT_CAPABILITY_ELE 	pCapELE = NULL;
+	//u8 bIsDeclareMCS13;
+
+	if ((posHTCap == NULL) || (pHT == NULL))
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "posHTCap or pHTInfo can't be null in HTConstructCapabilityElement()\n");
+		return;
+	}
+	memset(posHTCap, 0, *len);
+	if(pHT->ePeerHTSpecVer == HT_SPEC_VER_EWC)
+	{
+		u8	EWC11NHTCap[] = {0x00, 0x90, 0x4c, 0x33};	// For 11n EWC definition, 2007.07.17, by Emily
+		memcpy(posHTCap, EWC11NHTCap, sizeof(EWC11NHTCap));
+		pCapELE = (PHT_CAPABILITY_ELE)&(posHTCap[4]);
+	}else
+	{
+		pCapELE = (PHT_CAPABILITY_ELE)posHTCap;
+	}
+
+
+	//HT capability info
+	pCapELE->AdvCoding 		= 0; // This feature is not supported now!!
+	if(ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev))
+	{
+		pCapELE->ChlWidth = 0;
+	}
+	else
+	{
+		pCapELE->ChlWidth = (pHT->bRegBW40MHz?1:0);
+	}
+
+//	pCapELE->ChlWidth 		= (pHT->bRegBW40MHz?1:0);
+	pCapELE->MimoPwrSave 		= pHT->SelfMimoPs;
+	pCapELE->GreenField		= 0; // This feature is not supported now!!
+	pCapELE->ShortGI20Mhz		= 1; // We can receive Short GI!!
+	pCapELE->ShortGI40Mhz		= 1; // We can receive Short GI!!
+	//DbgPrint("TX HT cap/info ele BW=%d SG20=%d SG40=%d\n\r",
+		//pCapELE->ChlWidth, pCapELE->ShortGI20Mhz, pCapELE->ShortGI40Mhz);
+	pCapELE->TxSTBC 		= 1;
+	pCapELE->RxSTBC 		= 0;
+	pCapELE->DelayBA		= 0;	// Do not support now!!
+	pCapELE->MaxAMSDUSize	= (MAX_RECEIVE_BUFFER_SIZE>=7935)?1:0;
+	pCapELE->DssCCk 		= ((pHT->bRegBW40MHz)?(pHT->bRegSuppCCK?1:0):0);
+	pCapELE->PSMP			= 0; // Do not support now!!
+	pCapELE->LSigTxopProtect	= 0; // Do not support now!!
+
+
+	//MAC HT parameters info
+        // TODO: Nedd to take care of this part
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "TX HT cap/info ele BW=%d MaxAMSDUSize:%d DssCCk:%d\n", pCapELE->ChlWidth, pCapELE->MaxAMSDUSize, pCapELE->DssCCk);
+
+	if( IsEncrypt)
+	{
+		pCapELE->MPDUDensity 	= 7; // 8us
+		pCapELE->MaxRxAMPDUFactor 	= 2; // 2 is for 32 K and 3 is 64K
+	}
+	else
+	{
+		pCapELE->MaxRxAMPDUFactor 	= 3; // 2 is for 32 K and 3 is 64K
+		pCapELE->MPDUDensity 	= 0; // no density
+	}
+
+	//Supported MCS set
+	memcpy(pCapELE->MCS, ieee->Regdot11HTOperationalRateSet, 16);
+	if(pHT->IOTAction & HT_IOT_ACT_DISABLE_MCS15)
+		pCapELE->MCS[1] &= 0x7f;
+
+	if(pHT->IOTAction & HT_IOT_ACT_DISABLE_MCS14)
+		pCapELE->MCS[1] &= 0xbf;
+
+	if(pHT->IOTAction & HT_IOT_ACT_DISABLE_ALL_2SS)
+		pCapELE->MCS[1] &= 0x00;
+
+	// 2008.06.12
+	// For RTL819X, if pairwisekey = wep/tkip, ap is ralink, we support only MCS0~7.
+	if(ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev))
+	{
+		int i;
+		for(i = 1; i< 16; i++)
+			pCapELE->MCS[i] = 0;
+	}
+
+	//Extended HT Capability Info
+	memset(&pCapELE->ExtHTCapInfo, 0, 2);
+
+
+	//TXBF Capabilities
+	memset(pCapELE->TxBFCap, 0, 4);
+
+	//Antenna Selection Capabilities
+	pCapELE->ASCap = 0;
+//add 2 to give space for element ID and len when construct frames
+	if(pHT->ePeerHTSpecVer == HT_SPEC_VER_EWC)
+		*len = 30 + 2;
+	else
+		*len = 26 + 2;
+
+
+
+//	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA | IEEE80211_DL_HT, posHTCap, *len -2);
+
+	//Print each field in detail. Driver should not print out this message by default
+//	HTDebugHTCapability(posHTCap, (u8*)"HTConstructCapability()");
+	return;
+
+}
+/********************************************************************************************************************
+ *function:  Construct  Information Element in Beacon... if HTEnable is turned on
+ *   input:  struct ieee80211_device* 	ieee
+ *   	     u8* 			posHTCap //pointer to store Information Ele
+ *   	     u8*			len   //store len of
+ *   	     u8				IsEncrypt //whether encrypt, needed further
+ *  output:  none
+ *  return:  none
+ *  notice:  posHTCap can't be null and be initialized before. only AP and IBSS sta should do this
+  * *****************************************************************************************************************/
+void HTConstructInfoElement(struct ieee80211_device* ieee, u8* posHTInfo, u8* len, u8 IsEncrypt)
+{
+	PRT_HIGH_THROUGHPUT	pHT = ieee->pHTInfo;
+	PHT_INFORMATION_ELE		pHTInfoEle = (PHT_INFORMATION_ELE)posHTInfo;
+	if ((posHTInfo == NULL) || (pHTInfoEle == NULL))
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "posHTInfo or pHTInfoEle can't be null in HTConstructInfoElement()\n");
+		return;
+	}
+
+	memset(posHTInfo, 0, *len);
+	if ( (ieee->iw_mode == IW_MODE_ADHOC) || (ieee->iw_mode == IW_MODE_MASTER)) //ap mode is not currently supported
+	{
+		pHTInfoEle->ControlChl 			= ieee->current_network.channel;
+		pHTInfoEle->ExtChlOffset 			= ((pHT->bRegBW40MHz == false)?HT_EXTCHNL_OFFSET_NO_EXT:
+											(ieee->current_network.channel<=6)?
+												HT_EXTCHNL_OFFSET_UPPER:HT_EXTCHNL_OFFSET_LOWER);
+		pHTInfoEle->RecommemdedTxWidth	= pHT->bRegBW40MHz;
+		pHTInfoEle->RIFS 					= 0;
+		pHTInfoEle->PSMPAccessOnly		= 0;
+		pHTInfoEle->SrvIntGranularity		= 0;
+		pHTInfoEle->OptMode				= pHT->CurrentOpMode;
+		pHTInfoEle->NonGFDevPresent		= 0;
+		pHTInfoEle->DualBeacon			= 0;
+		pHTInfoEle->SecondaryBeacon		= 0;
+		pHTInfoEle->LSigTxopProtectFull		= 0;
+		pHTInfoEle->PcoActive				= 0;
+		pHTInfoEle->PcoPhase				= 0;
+
+		memset(pHTInfoEle->BasicMSC, 0, 16);
+
+
+		*len = 22 + 2; //same above
+
+	}
+	else
+	{
+		//STA should not generate High Throughput Information Element
+		*len = 0;
+	}
+	//IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA | IEEE80211_DL_HT, posHTInfo, *len - 2);
+	//HTDebugHTInfo(posHTInfo, "HTConstructInforElement");
+	return;
+}
+
+/*
+  *  According to experiment, Realtek AP to STA (based on rtl8190) may achieve best performance
+  *  if both STA and AP set limitation of aggregation size to 32K, that is, set AMPDU density to 2
+  *  (Ref: IEEE 11n specification). However, if Realtek STA associates to other AP, STA should set
+  *  limitation of aggregation size to 8K, otherwise, performance of traffic stream from STA to AP
+  *  will be much less than the traffic stream from AP to STA if both of the stream runs concurrently
+  *  at the same time.
+  *
+  *  Frame Format
+  *  Element ID		Length		OUI			Type1		Reserved
+  *  1 byte			1 byte		3 bytes		1 byte		1 byte
+  *
+  *  OUI 		= 0x00, 0xe0, 0x4c,
+  *  Type 	= 0x02
+  *  Reserved 	= 0x00
+  *
+  *  2007.8.21 by Emily
+*/
+/********************************************************************************************************************
+ *function:  Construct  Information Element in Beacon... in RT2RT condition
+ *   input:  struct ieee80211_device* 	ieee
+ *   	     u8* 			posRT2RTAgg //pointer to store Information Ele
+ *   	     u8*			len   //store len
+ *  output:  none
+ *  return:  none
+ *  notice:
+  * *****************************************************************************************************************/
+void HTConstructRT2RTAggElement(struct ieee80211_device* ieee, u8* posRT2RTAgg, u8* len)
+{
+	if (posRT2RTAgg == NULL) {
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "posRT2RTAgg can't be null in HTConstructRT2RTAggElement()\n");
+		return;
+	}
+	memset(posRT2RTAgg, 0, *len);
+	*posRT2RTAgg++ = 0x00;
+	*posRT2RTAgg++ = 0xe0;
+	*posRT2RTAgg++ = 0x4c;
+	*posRT2RTAgg++ = 0x02;
+	*posRT2RTAgg++ = 0x01;
+	*posRT2RTAgg = 0x10;//*posRT2RTAgg = 0x02;
+
+	if(ieee->bSupportRemoteWakeUp) {
+		*posRT2RTAgg |= 0x08;//RT_HT_CAP_USE_WOW;
+	}
+
+	*len = 6 + 2;
+	return;
+#ifdef TODO
+#if(HAL_CODE_BASE == RTL8192 && DEV_BUS_TYPE == USB_INTERFACE)
+	/*
+	//Emily. If it is required to Ask Realtek AP to send AMPDU during AES mode, enable this
+	   section of code.
+	if(IS_UNDER_11N_AES_MODE(Adapter))
+	{
+		posRT2RTAgg->Octet[5] |=RT_HT_CAP_USE_AMPDU;
+	}else
+	{
+		posRT2RTAgg->Octet[5] &= 0xfb;
+	}
+	*/
+
+#else
+	// Do Nothing
+#endif
+
+	posRT2RTAgg->Length = 6;
+#endif
+
+
+
+
+}
+
+
+/********************************************************************************************************************
+ *function:  Pick the right Rate Adaptive table to use
+ *   input:  struct ieee80211_device* 	ieee
+ *   	     u8* 			pOperateMCS //A pointer to MCS rate bitmap
+ *  return:  always we return true
+ *  notice:
+  * *****************************************************************************************************************/
+u8 HT_PickMCSRate(struct ieee80211_device* ieee, u8* pOperateMCS)
+{
+	u8					i;
+	if (pOperateMCS == NULL)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "pOperateMCS can't be null in HT_PickMCSRate()\n");
+		return false;
+	}
+
+	switch(ieee->mode)
+	{
+	case IEEE_A:
+	case IEEE_B:
+	case IEEE_G:
+			//legacy rate routine handled at selectedrate
+
+			//no MCS rate
+			for(i=0;i<=15;i++){
+				pOperateMCS[i] = 0;
+			}
+			break;
+
+	case IEEE_N_24G:	//assume CCK rate ok
+	case IEEE_N_5G:
+			// Legacy part we only use 6, 5.5,2,1 for N_24G and 6 for N_5G.
+			// Legacy part shall be handled at SelectRateSet().
+
+			//HT part
+			// TODO: may be different if we have different number of antenna
+			pOperateMCS[0] &=RATE_ADPT_1SS_MASK;	//support MCS 0~7
+			pOperateMCS[1] &=RATE_ADPT_2SS_MASK;
+			pOperateMCS[3] &=RATE_ADPT_MCS32_MASK;
+			break;
+
+	//should never reach here
+	default:
+
+			break;
+
+	}
+
+	return true;
+}
+
+/*
+*	Description:
+*		This function will get the highest speed rate in input MCS set.
+*
+*	/param 	Adapter			Pionter to Adapter entity
+*			pMCSRateSet		Pointer to MCS rate bitmap
+*			pMCSFilter		Pointer to MCS rate filter
+*
+*	/return	Highest MCS rate included in pMCSRateSet and filtered by pMCSFilter.
+*
+*/
+/********************************************************************************************************************
+ *function:  This function will get the highest speed rate in input MCS set.
+ *   input:  struct ieee80211_device* 	ieee
+ *   	     u8* 			pMCSRateSet //Pointer to MCS rate bitmap
+ *   	     u8*			pMCSFilter //Pointer to MCS rate filter
+ *  return:  Highest MCS rate included in pMCSRateSet and filtered by pMCSFilter
+ *  notice:
+  * *****************************************************************************************************************/
+u8 HTGetHighestMCSRate(struct ieee80211_device* ieee, u8* pMCSRateSet, u8* pMCSFilter)
+{
+	u8		i, j;
+	u8		bitMap;
+	u8		mcsRate = 0;
+	u8		availableMcsRate[16];
+	if (pMCSRateSet == NULL || pMCSFilter == NULL)
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "pMCSRateSet or pMCSFilter can't be null in HTGetHighestMCSRate()\n");
+		return false;
+	}
+	for(i=0; i<16; i++)
+		availableMcsRate[i] = pMCSRateSet[i] & pMCSFilter[i];
+
+	for(i = 0; i < 16; i++)
+	{
+		if(availableMcsRate[i] != 0)
+			break;
+	}
+	if(i == 16)
+		return false;
+
+	for(i = 0; i < 16; i++)
+	{
+		if(availableMcsRate[i] != 0)
+		{
+			bitMap = availableMcsRate[i];
+			for(j = 0; j < 8; j++)
+			{
+				if((bitMap%2) != 0)
+				{
+					if(HTMcsToDataRate(ieee, (8*i+j)) > HTMcsToDataRate(ieee, mcsRate))
+						mcsRate = (8*i+j);
+				}
+				bitMap = bitMap>>1;
+			}
+		}
+	}
+	return (mcsRate|0x80);
+}
+
+
+
+/*
+**
+**1.Filter our operation rate set with AP's rate set
+**2.shall reference channel bandwidth, STBC, Antenna number
+**3.generate rate adative table for firmware
+**David 20060906
+**
+** \pHTSupportedCap: the connected STA's supported rate Capability element
+*/
+u8 HTFilterMCSRate( struct ieee80211_device* ieee, u8* pSupportMCS, u8* pOperateMCS)
+{
+
+	u8 i=0;
+
+	// filter out operational rate set not supported by AP, the lenth of it is 16
+	for(i=0;i<=15;i++){
+		pOperateMCS[i] = ieee->Regdot11HTOperationalRateSet[i]&pSupportMCS[i];
+	}
+
+
+	// TODO: adjust our operational rate set  according to our channel bandwidth, STBC and Antenna number
+
+	// TODO: fill suggested rate adaptive rate index and give firmware info using Tx command packet
+	// we also shall suggested the first start rate set according to our singal strength
+	HT_PickMCSRate(ieee, pOperateMCS);
+
+	// For RTL819X, if pairwisekey = wep/tkip, we support only MCS0~7.
+	if(ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev))
+		pOperateMCS[1] = 0;
+
+	//
+	// For RTL819X, we support only MCS0~15.
+	// And also, we do not know how to use MCS32 now.
+	//
+	for(i=2; i<=15; i++)
+		pOperateMCS[i] = 0;
+
+	return true;
+}
+void HTSetConnectBwMode(struct ieee80211_device* ieee, HT_CHANNEL_WIDTH	Bandwidth, HT_EXTCHNL_OFFSET	Offset);
+#if 0
+//I need move this function to other places, such as rx?
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+void HTOnAssocRsp_wq(struct work_struct *work)
+{
+	struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, ht_onAssRsp);
+#else
+void HTOnAssocRsp_wq(struct ieee80211_device *ieee)
+{
+#endif
+#endif
+void HTOnAssocRsp(struct ieee80211_device *ieee)
+{
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	PHT_CAPABILITY_ELE		pPeerHTCap = NULL;
+	PHT_INFORMATION_ELE		pPeerHTInfo = NULL;
+	u16	nMaxAMSDUSize = 0;
+	u8*	pMcsFilter = NULL;
+
+	static u8				EWC11NHTCap[] = {0x00, 0x90, 0x4c, 0x33};		// For 11n EWC definition, 2007.07.17, by Emily
+	static u8				EWC11NHTInfo[] = {0x00, 0x90, 0x4c, 0x34};	// For 11n EWC definition, 2007.07.17, by Emily
+
+	if( pHTInfo->bCurrentHTSupport == false )
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "<=== HTOnAssocRsp(): HT_DISABLE\n");
+		return;
+	}
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "===> HTOnAssocRsp_wq(): HT_ENABLE\n");
+//	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, pHTInfo->PeerHTCapBuf, sizeof(HT_CAPABILITY_ELE));
+//	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, pHTInfo->PeerHTInfoBuf, sizeof(HT_INFORMATION_ELE));
+
+//	HTDebugHTCapability(pHTInfo->PeerHTCapBuf,"HTOnAssocRsp_wq");
+//	HTDebugHTInfo(pHTInfo->PeerHTInfoBuf,"HTOnAssocRsp_wq");
+	//
+	if(!memcmp(pHTInfo->PeerHTCapBuf,EWC11NHTCap, sizeof(EWC11NHTCap)))
+		pPeerHTCap = (PHT_CAPABILITY_ELE)(&pHTInfo->PeerHTCapBuf[4]);
+	else
+		pPeerHTCap = (PHT_CAPABILITY_ELE)(pHTInfo->PeerHTCapBuf);
+
+	if(!memcmp(pHTInfo->PeerHTInfoBuf, EWC11NHTInfo, sizeof(EWC11NHTInfo)))
+		pPeerHTInfo = (PHT_INFORMATION_ELE)(&pHTInfo->PeerHTInfoBuf[4]);
+	else
+		pPeerHTInfo = (PHT_INFORMATION_ELE)(pHTInfo->PeerHTInfoBuf);
+
+
+	////////////////////////////////////////////////////////
+	// Configurations:
+	////////////////////////////////////////////////////////
+	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_HT, pPeerHTCap, sizeof(HT_CAPABILITY_ELE));
+//	IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_HT, pPeerHTInfo, sizeof(HT_INFORMATION_ELE));
+	// Config Supported Channel Width setting
+	//
+	HTSetConnectBwMode(ieee, (HT_CHANNEL_WIDTH)(pPeerHTCap->ChlWidth), (HT_EXTCHNL_OFFSET)(pPeerHTInfo->ExtChlOffset));
+
+//	if(pHTInfo->bCurBW40MHz == true)
+		pHTInfo->bCurTxBW40MHz = ((pPeerHTInfo->RecommemdedTxWidth == 1)?true:false);
+
+	//
+	// Update short GI/ long GI setting
+	//
+	// TODO:
+	pHTInfo->bCurShortGI20MHz=
+		((pHTInfo->bRegShortGI20MHz)?((pPeerHTCap->ShortGI20Mhz==1)?true:false):false);
+	pHTInfo->bCurShortGI40MHz=
+		((pHTInfo->bRegShortGI40MHz)?((pPeerHTCap->ShortGI40Mhz==1)?true:false):false);
+
+	//
+	// Config TX STBC setting
+	//
+	// TODO:
+
+	//
+	// Config DSSS/CCK  mode in 40MHz mode
+	//
+	// TODO:
+	pHTInfo->bCurSuppCCK =
+		((pHTInfo->bRegSuppCCK)?((pPeerHTCap->DssCCk==1)?true:false):false);
+
+
+	//
+	// Config and configure A-MSDU setting
+	//
+	pHTInfo->bCurrent_AMSDU_Support = pHTInfo->bAMSDU_Support;
+
+	nMaxAMSDUSize = (pPeerHTCap->MaxAMSDUSize==0)?3839:7935;
+
+	if(pHTInfo->nAMSDU_MaxSize > nMaxAMSDUSize )
+		pHTInfo->nCurrent_AMSDU_MaxSize = nMaxAMSDUSize;
+	else
+		pHTInfo->nCurrent_AMSDU_MaxSize = pHTInfo->nAMSDU_MaxSize;
+
+	//
+	// Config A-MPDU setting
+	//
+	pHTInfo->bCurrentAMPDUEnable = pHTInfo->bAMPDUEnable;
+	if(ieee->is_ap_in_wep_tkip && ieee->is_ap_in_wep_tkip(ieee->dev))
+	{
+		if( (pHTInfo->IOTPeer== HT_IOT_PEER_ATHEROS) ||
+				(pHTInfo->IOTPeer == HT_IOT_PEER_UNKNOWN) )
+			pHTInfo->bCurrentAMPDUEnable = false;
+	}
+
+	// <1> Decide AMPDU Factor
+
+	// By Emily
+	if(!pHTInfo->bRegRT2RTAggregation)
+	{
+		// Decide AMPDU Factor according to protocol handshake
+		if(pHTInfo->AMPDU_Factor > pPeerHTCap->MaxRxAMPDUFactor)
+			pHTInfo->CurrentAMPDUFactor = pPeerHTCap->MaxRxAMPDUFactor;
+		else
+			pHTInfo->CurrentAMPDUFactor = pHTInfo->AMPDU_Factor;
+
+	}else
+	{
+		// Set MPDU density to 2 to Realtek AP, and set it to 0 for others
+		// Replace MPDU factor declared in original association response frame format. 2007.08.20 by Emily
+#if 0
+		osTmp= PacketGetElement( asocpdu, EID_Vendor, OUI_SUB_REALTEK_AGG, OUI_SUBTYPE_DONT_CARE);
+		if(osTmp.Length >= 5)	//00:e0:4c:02:00
+#endif
+		if (ieee->current_network.bssht.bdRT2RTAggregation)
+		{
+			if( ieee->pairwise_key_type != KEY_TYPE_NA)
+				// Realtek may set 32k in security mode and 64k for others
+				pHTInfo->CurrentAMPDUFactor = pPeerHTCap->MaxRxAMPDUFactor;
+			else
+				pHTInfo->CurrentAMPDUFactor = HT_AGG_SIZE_64K;
+		}else
+		{
+			if(pPeerHTCap->MaxRxAMPDUFactor < HT_AGG_SIZE_32K)
+				pHTInfo->CurrentAMPDUFactor = pPeerHTCap->MaxRxAMPDUFactor;
+			else
+				pHTInfo->CurrentAMPDUFactor = HT_AGG_SIZE_32K;
+		}
+	}
+
+	// <2> Set AMPDU Minimum MPDU Start Spacing
+	// 802.11n 3.0 section 9.7d.3
+#if 1
+	if(pHTInfo->MPDU_Density > pPeerHTCap->MPDUDensity)
+		pHTInfo->CurrentMPDUDensity = pHTInfo->MPDU_Density;
+	else
+		pHTInfo->CurrentMPDUDensity = pPeerHTCap->MPDUDensity;
+	if(ieee->pairwise_key_type != KEY_TYPE_NA )
+		pHTInfo->CurrentMPDUDensity 	= 7; // 8us
+#else
+	if(pHTInfo->MPDU_Density > pPeerHTCap->MPDUDensity)
+		pHTInfo->CurrentMPDUDensity = pHTInfo->MPDU_Density;
+	else
+		pHTInfo->CurrentMPDUDensity = pPeerHTCap->MPDUDensity;
+#endif
+	// Force TX AMSDU
+
+	// Lanhsin: mark for tmp to avoid deauth by ap from  s3
+	//if(memcmp(pMgntInfo->Bssid, NETGEAR834Bv2_BROADCOM, 3)==0)
+	if(pHTInfo->IOTAction & HT_IOT_ACT_TX_USE_AMSDU_8K)
+		{
+
+			pHTInfo->bCurrentAMPDUEnable = false;
+			pHTInfo->ForcedAMSDUMode = HT_AGG_FORCE_ENABLE;
+			pHTInfo->ForcedAMSDUMaxSize = 7935;
+	}
+
+	// Rx Reorder Setting
+	pHTInfo->bCurRxReorderEnable = pHTInfo->bRegRxReorderEnable;
+
+	//
+	// Filter out unsupported HT rate for this AP
+	// Update RATR table
+	// This is only for 8190 ,8192 or later product which using firmware to handle rate adaptive mechanism.
+	//
+
+	// Handle Ralink AP bad MCS rate set condition. Joseph.
+	// This fix the bug of Ralink AP. This may be removed in the future.
+	if(pPeerHTCap->MCS[0] == 0)
+		pPeerHTCap->MCS[0] = 0xff;
+
+	// Joseph test //LZM ADD 090318
+	HTIOTActDetermineRaFunc(ieee, ((pPeerHTCap->MCS[1])!=0));
+
+	HTFilterMCSRate(ieee, pPeerHTCap->MCS, ieee->dot11HTOperationalRateSet);
+
+	//
+	// Config MIMO Power Save setting
+	//
+	pHTInfo->PeerMimoPs = pPeerHTCap->MimoPwrSave;
+	if(pHTInfo->PeerMimoPs == MIMO_PS_STATIC)
+		pMcsFilter = MCS_FILTER_1SS;
+	else
+		pMcsFilter = MCS_FILTER_ALL;
+	//WB add for MCS8 bug
+//	pMcsFilter = MCS_FILTER_1SS;
+	ieee->HTHighestOperaRate = HTGetHighestMCSRate(ieee, ieee->dot11HTOperationalRateSet, pMcsFilter);
+	ieee->HTCurrentOperaRate = ieee->HTHighestOperaRate;
+
+	//
+	// Config current operation mode.
+	//
+	pHTInfo->CurrentOpMode = pPeerHTInfo->OptMode;
+
+
+
+}
+
+void HTSetConnectBwModeCallback(struct ieee80211_device* ieee);
+/********************************************************************************************************************
+ *function:  initialize HT info(struct PRT_HIGH_THROUGHPUT)
+ *   input:  struct ieee80211_device* 	ieee
+ *  output:  none
+ *  return:  none
+ *  notice: This function is called when *  (1) MPInitialization Phase *  (2) Receiving of Deauthentication from AP
+********************************************************************************************************************/
+// TODO: Should this funciton be called when receiving of Disassociation?
+void HTInitializeHTInfo(struct ieee80211_device* ieee)
+{
+	PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
+
+	//
+	// These parameters will be reset when receiving deauthentication packet
+	//
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "===========>%s()\n", __FUNCTION__);
+	pHTInfo->bCurrentHTSupport = false;
+
+	// 40MHz channel support
+	pHTInfo->bCurBW40MHz = false;
+	pHTInfo->bCurTxBW40MHz = false;
+
+	// Short GI support
+	pHTInfo->bCurShortGI20MHz = false;
+	pHTInfo->bCurShortGI40MHz = false;
+	pHTInfo->bForcedShortGI = false;
+
+	// CCK rate support
+	// This flag is set to true to support CCK rate by default.
+	// It will be affected by "pHTInfo->bRegSuppCCK" and AP capabilities only when associate to
+	// 11N BSS.
+	pHTInfo->bCurSuppCCK = true;
+
+	// AMSDU related
+	pHTInfo->bCurrent_AMSDU_Support = false;
+	pHTInfo->nCurrent_AMSDU_MaxSize = pHTInfo->nAMSDU_MaxSize;
+
+	// AMPUD related
+	pHTInfo->CurrentMPDUDensity = pHTInfo->MPDU_Density;
+	pHTInfo->CurrentAMPDUFactor = pHTInfo->AMPDU_Factor;
+
+
+
+	// Initialize all of the parameters related to 11n
+	memset((void*)(&(pHTInfo->SelfHTCap)), 0, sizeof(pHTInfo->SelfHTCap));
+	memset((void*)(&(pHTInfo->SelfHTInfo)), 0, sizeof(pHTInfo->SelfHTInfo));
+	memset((void*)(&(pHTInfo->PeerHTCapBuf)), 0, sizeof(pHTInfo->PeerHTCapBuf));
+	memset((void*)(&(pHTInfo->PeerHTInfoBuf)), 0, sizeof(pHTInfo->PeerHTInfoBuf));
+
+	pHTInfo->bSwBwInProgress = false;
+	pHTInfo->ChnlOp = CHNLOP_NONE;
+
+	// Set default IEEE spec for Draft N
+	pHTInfo->ePeerHTSpecVer = HT_SPEC_VER_IEEE;
+
+	// Realtek proprietary aggregation mode
+	pHTInfo->bCurrentRT2RTAggregation = false;
+	pHTInfo->bCurrentRT2RTLongSlotTime = false;
+	pHTInfo->RT2RT_HT_Mode = (RT_HT_CAPBILITY)0;
+
+	pHTInfo->IOTPeer = 0;
+	pHTInfo->IOTAction = 0;
+	pHTInfo->IOTRaFunc = 0;
+
+	//MCS rate initialized here
+	{
+		u8* RegHTSuppRateSets = &(ieee->RegHTSuppRateSet[0]);
+		RegHTSuppRateSets[0] = 0xFF;	//support MCS 0~7
+		RegHTSuppRateSets[1] = 0xFF;	//support MCS 8~15
+		RegHTSuppRateSets[4] = 0x01;	//support MCS 32
+	}
+}
+/********************************************************************************************************************
+ *function:  initialize Bss HT structure(struct PBSS_HT)
+ *   input:  PBSS_HT pBssHT //to be initialized
+ *  output:  none
+ *  return:  none
+ *  notice: This function is called when initialize network structure
+********************************************************************************************************************/
+void HTInitializeBssDesc(PBSS_HT pBssHT)
+{
+
+	pBssHT->bdSupportHT = false;
+	memset(pBssHT->bdHTCapBuf, 0, sizeof(pBssHT->bdHTCapBuf));
+	pBssHT->bdHTCapLen = 0;
+	memset(pBssHT->bdHTInfoBuf, 0, sizeof(pBssHT->bdHTInfoBuf));
+	pBssHT->bdHTInfoLen = 0;
+
+	pBssHT->bdHTSpecVer= HT_SPEC_VER_IEEE;
+
+	pBssHT->bdRT2RTAggregation = false;
+	pBssHT->bdRT2RTLongSlotTime = false;
+	pBssHT->RT2RT_HT_Mode = (RT_HT_CAPBILITY)0;
+}
+#if 0
+//below function has merged into ieee80211_network_init() in ieee80211_rx.c
+void
+HTParsingHTCapElement(
+	IN	PADAPTER		Adapter,
+	IN	OCTET_STRING	HTCapIE,
+	OUT	PRT_WLAN_BSS	pBssDesc
+)
+{
+	PMGNT_INFO      			pMgntInfo = &Adapter->MgntInfo;
+
+	if( HTCapIE.Length > sizeof(pBssDesc->BssHT.bdHTCapBuf) )
+	{
+		RT_TRACE( COMP_HT, DBG_LOUD, ("HTParsingHTCapElement(): HT Capability Element length is too long!\n") );
+		return;
+	}
+
+	// TODO: Check the correctness of HT Cap
+	//Print each field in detail. Driver should not print out this message by default
+	if(!pMgntInfo->mActingAsAp && !pMgntInfo->mAssoc)
+		HTDebugHTCapability(DBG_TRACE, Adapter, &HTCapIE, (pu8)"HTParsingHTCapElement()");
+
+	HTCapIE.Length = HTCapIE.Length > sizeof(pBssDesc->BssHT.bdHTCapBuf)?\
+		sizeof(pBssDesc->BssHT.bdHTCapBuf):HTCapIE.Length;	//prevent from overflow
+
+	CopyMem(pBssDesc->BssHT.bdHTCapBuf, HTCapIE.Octet, HTCapIE.Length);
+	pBssDesc->BssHT.bdHTCapLen = HTCapIE.Length;
+
+}
+
+
+void
+HTParsingHTInfoElement(
+	PADAPTER		Adapter,
+	OCTET_STRING	HTInfoIE,
+	PRT_WLAN_BSS	pBssDesc
+)
+{
+	PMGNT_INFO      			pMgntInfo = &Adapter->MgntInfo;
+
+	if( HTInfoIE.Length > sizeof(pBssDesc->BssHT.bdHTInfoBuf))
+	{
+		RT_TRACE( COMP_HT, DBG_LOUD, ("HTParsingHTInfoElement(): HT Information Element length is too long!\n") );
+		return;
+	}
+
+	// TODO: Check the correctness of HT Info
+	//Print each field in detail. Driver should not print out this message by default
+	if(!pMgntInfo->mActingAsAp && !pMgntInfo->mAssoc)
+		HTDebugHTInfo(DBG_TRACE, Adapter, &HTInfoIE, (pu8)"HTParsingHTInfoElement()");
+
+	HTInfoIE.Length = HTInfoIE.Length > sizeof(pBssDesc->BssHT.bdHTInfoBuf)?\
+		sizeof(pBssDesc->BssHT.bdHTInfoBuf):HTInfoIE.Length;	//prevent from overflow
+
+	CopyMem( pBssDesc->BssHT.bdHTInfoBuf, HTInfoIE.Octet, HTInfoIE.Length);
+	pBssDesc->BssHT.bdHTInfoLen = HTInfoIE.Length;
+}
+
+/*
+  * Get HT related information from beacon and save it in BssDesc
+  *
+  * (1) Parse HTCap, and HTInfo, and record whether it is 11n AP
+  * (2) If peer is HT, but not WMM, call QosSetLegacyWMMParamWithHT()
+  * (3) Check whether peer is Realtek AP (for Realtek proprietary aggregation mode).
+  * Input:
+  * 		PADAPTER	Adapter
+  *
+  * Output:
+  *		PRT_TCB		BssDesc
+  *
+*/
+void HTGetValueFromBeaconOrProbeRsp(
+	PADAPTER			Adapter,
+	POCTET_STRING		pSRCmmpdu,
+	PRT_WLAN_BSS		bssDesc
+)
+{
+	PMGNT_INFO      			pMgntInfo = &Adapter->MgntInfo;
+	PRT_HIGH_THROUGHPUT		pHTInfo = GET_HT_INFO(pMgntInfo);
+	OCTET_STRING				HTCapIE, HTInfoIE, HTRealtekAgg, mmpdu;
+	OCTET_STRING				BroadcomElement, CiscoElement;
+
+	mmpdu.Octet = pSRCmmpdu->Octet;
+	mmpdu.Length = pSRCmmpdu->Length;
+
+	//2Note:
+	//   Mark for IOT testing using  Linksys WRT350N, This AP does not contain WMM IE  when
+	//   it is configured at pure-N mode.
+	//	if(bssDesc->BssQos.bdQoSMode & QOS_WMM)
+	//
+
+	HTInitializeBssDesc (&bssDesc->BssHT);
+
+	//2<1> Parse HTCap, and HTInfo
+	// Get HT Capability IE: (1) Get IEEE Draft N IE or (2) Get EWC IE
+	HTCapIE = PacketGetElement(mmpdu, EID_HTCapability, OUI_SUB_DONT_CARE, OUI_SUBTYPE_DONT_CARE);
+	if(HTCapIE.Length == 0)
+	{
+		HTCapIE = PacketGetElement(mmpdu, EID_Vendor, OUI_SUB_11N_EWC_HT_CAP, OUI_SUBTYPE_DONT_CARE);
+		if(HTCapIE.Length != 0)
+			bssDesc->BssHT.bdHTSpecVer= HT_SPEC_VER_EWC;
+	}
+	if(HTCapIE.Length != 0)
+		HTParsingHTCapElement(Adapter, HTCapIE, bssDesc);
+
+	// Get HT Information IE: (1) Get IEEE Draft N IE or (2) Get EWC IE
+	HTInfoIE = PacketGetElement(mmpdu, EID_HTInfo, OUI_SUB_DONT_CARE, OUI_SUBTYPE_DONT_CARE);
+	if(HTInfoIE.Length == 0)
+	{
+		HTInfoIE = PacketGetElement(mmpdu, EID_Vendor, OUI_SUB_11N_EWC_HT_INFO, OUI_SUBTYPE_DONT_CARE);
+		if(HTInfoIE.Length != 0)
+				bssDesc->BssHT.bdHTSpecVer  = HT_SPEC_VER_EWC;
+	}
+	if(HTInfoIE.Length != 0)
+		HTParsingHTInfoElement(Adapter, HTInfoIE, bssDesc);
+
+	//2<2>If peer is HT, but not WMM, call QosSetLegacyWMMParamWithHT()
+	if(HTCapIE.Length != 0)
+	{
+		bssDesc->BssHT.bdSupportHT = true;
+		if(bssDesc->BssQos.bdQoSMode == QOS_DISABLE)
+			QosSetLegacyWMMParamWithHT(Adapter, bssDesc);
+	}
+	else
+	{
+		bssDesc->BssHT.bdSupportHT = false;
+	}
+
+	//2<3>Check whether the peer is Realtek AP/STA
+	if(pHTInfo->bRegRT2RTAggregation)
+	{
+		if(bssDesc->BssHT.bdSupportHT)
+		{
+			HTRealtekAgg = PacketGetElement(mmpdu, EID_Vendor, OUI_SUB_REALTEK_AGG, OUI_SUBTYPE_DONT_CARE);
+			if(HTRealtekAgg.Length >=5 )
+			{
+				bssDesc->BssHT.bdRT2RTAggregation = true;
+
+				if((HTRealtekAgg.Octet[4]==1) && (HTRealtekAgg.Octet[5] & 0x02))
+					bssDesc->BssHT.bdRT2RTLongSlotTime = true;
+			}
+		}
+	}
+
+	//
+	// 2008/01/25 MH Get Broadcom AP IE for manamgent frame CCK rate problem.
+	// AP can not receive CCK managemtn from from 92E.
+	//
+
+	// Initialize every new bss broadcom cap exist as false..
+	bssDesc->bBroadcomCapExist= false;
+
+	if(HTCapIE.Length != 0 || HTInfoIE.Length != 0)
+	{
+		u4Byte	Length = 0;
+
+		FillOctetString(BroadcomElement, NULL, 0);
+
+		BroadcomElement = PacketGetElement( mmpdu, EID_Vendor, OUI_SUB_BROADCOM_IE_1, OUI_SUBTYPE_DONT_CARE);
+		Length += BroadcomElement.Length;
+		BroadcomElement = PacketGetElement( mmpdu, EID_Vendor, OUI_SUB_BROADCOM_IE_2, OUI_SUBTYPE_DONT_CARE);
+		Length += BroadcomElement.Length;
+		BroadcomElement = PacketGetElement( mmpdu, EID_Vendor, OUI_SUB_BROADCOM_IE_3, OUI_SUBTYPE_DONT_CARE);
+		Length += BroadcomElement.Length;
+
+		if(Length > 0)
+			bssDesc->bBroadcomCapExist = true;
+	}
+
+
+	// For Cisco IOT issue
+	CiscoElement = PacketGetElement( mmpdu, EID_Vendor, OUI_SUB_CISCO_IE, OUI_SUBTYPE_DONT_CARE);
+	if(CiscoElement.Length != 0){ // 3: 0x00, 0x40, 0x96 ....
+		bssDesc->bCiscoCapExist = true;
+	}else{
+		bssDesc->bCiscoCapExist = false;
+	}
+}
+
+
+#endif
+/********************************************************************************************************************
+ *function:  initialize Bss HT structure(struct PBSS_HT)
+ *   input:  struct ieee80211_device 	*ieee
+ *   	     struct ieee80211_network 	*pNetwork //usually current network we are live in
+ *  output:  none
+ *  return:  none
+ *  notice: This function should ONLY be called before association
+********************************************************************************************************************/
+void HTResetSelfAndSavePeerSetting(struct ieee80211_device* ieee, 	struct ieee80211_network * pNetwork)
+{
+	PRT_HIGH_THROUGHPUT		pHTInfo = ieee->pHTInfo;
+//	u16						nMaxAMSDUSize;
+//	PHT_CAPABILITY_ELE		pPeerHTCap = (PHT_CAPABILITY_ELE)pNetwork->bssht.bdHTCapBuf;
+//	PHT_INFORMATION_ELE		pPeerHTInfo = (PHT_INFORMATION_ELE)pNetwork->bssht.bdHTInfoBuf;
+//	u8*	pMcsFilter;
+	u8	bIOTAction = 0;
+
+	//
+	//  Save Peer Setting before Association
+	//
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "==============>%s()\n", __FUNCTION__);
+	/*unmark bEnableHT flag here is the same reason why unmarked in function ieee80211_softmac_new_net. WB 2008.09.10*/
+//	if( pHTInfo->bEnableHT &&  pNetwork->bssht.bdSupportHT)
+	if (pNetwork->bssht.bdSupportHT)
+	{
+		pHTInfo->bCurrentHTSupport = true;
+		pHTInfo->ePeerHTSpecVer = pNetwork->bssht.bdHTSpecVer;
+
+		// Save HTCap and HTInfo information Element
+		if(pNetwork->bssht.bdHTCapLen > 0 && 	pNetwork->bssht.bdHTCapLen <= sizeof(pHTInfo->PeerHTCapBuf))
+			memcpy(pHTInfo->PeerHTCapBuf, pNetwork->bssht.bdHTCapBuf, pNetwork->bssht.bdHTCapLen);
+
+		if(pNetwork->bssht.bdHTInfoLen > 0 && pNetwork->bssht.bdHTInfoLen <= sizeof(pHTInfo->PeerHTInfoBuf))
+			memcpy(pHTInfo->PeerHTInfoBuf, pNetwork->bssht.bdHTInfoBuf, pNetwork->bssht.bdHTInfoLen);
+
+		// Check whether RT to RT aggregation mode is enabled
+		if(pHTInfo->bRegRT2RTAggregation)
+		{
+			pHTInfo->bCurrentRT2RTAggregation = pNetwork->bssht.bdRT2RTAggregation;
+			pHTInfo->bCurrentRT2RTLongSlotTime = pNetwork->bssht.bdRT2RTLongSlotTime;
+			pHTInfo->RT2RT_HT_Mode = pNetwork->bssht.RT2RT_HT_Mode;
+		}
+		else
+		{
+			pHTInfo->bCurrentRT2RTAggregation = false;
+			pHTInfo->bCurrentRT2RTLongSlotTime = false;
+			pHTInfo->RT2RT_HT_Mode = (RT_HT_CAPBILITY)0;
+		}
+
+		// Determine the IOT Peer Vendor.
+		HTIOTPeerDetermine(ieee);
+
+		// Decide IOT Action
+		// Must be called after the parameter of pHTInfo->bCurrentRT2RTAggregation is decided
+		pHTInfo->IOTAction = 0;
+		bIOTAction = HTIOTActIsDisableMCS14(ieee, pNetwork->bssid);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_MCS14;
+
+		bIOTAction = HTIOTActIsDisableMCS15(ieee);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_MCS15;
+
+		bIOTAction = HTIOTActIsDisableMCSTwoSpatialStream(ieee);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_ALL_2SS;
+
+
+		bIOTAction = HTIOTActIsDisableEDCATurbo(ieee, pNetwork->bssid);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_EDCA_TURBO;
+
+		bIOTAction = HTIOTActIsMgntUseCCK6M(pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_MGNT_USE_CCK_6M;
+
+		bIOTAction = HTIOTActIsCCDFsync(pNetwork->bssid);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_CDD_FSYNC;
+
+		bIOTAction = HTIOTActIsForcedCTS2Self(pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_FORCED_CTS2SELF;
+
+		//bIOTAction = HTIOTActIsForcedRTSCTS(ieee, pNetwork);
+		//if(bIOTAction)
+		//	pHTInfo->IOTAction |= HT_IOT_ACT_FORCED_RTS;
+
+#if defined(RTL8192SU)
+		bIOTAction = HTIOCActRejcectADDBARequest(pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_REJECT_ADDBA_REQ;
+#endif
+
+		bIOTAction = HTIOCActAllowPeerAggOnePacket(ieee, pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_ALLOW_PEER_AGG_ONE_PKT;
+
+		bIOTAction = HTIOTActIsEDCABiasRx(ieee, pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_EDCA_BIAS_ON_RX;
+
+#if defined(RTL8192SU)
+		bIOTAction = HTIOTActDisableShortGI(ieee, pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_SHORT_GI;
+
+		bIOTAction = HTIOTActDisableHighPower(ieee, pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_HIGH_POWER;
+#endif
+
+		bIOTAction = HTIOTActIsForcedAMSDU8K(ieee, pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_TX_USE_AMSDU_8K;
+
+#if defined(RTL8192SU)
+		bIOTAction = HTIOTActIsTxNoAggregation(ieee, pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_TX_NO_AGGREGATION;
+
+		bIOTAction = HTIOTActIsDisableTx40MHz(ieee, pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_TX_40_MHZ;
+
+		bIOTAction = HTIOTActIsDisableTx2SS(ieee, pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_TX_2SS;
+#endif
+		//must after HT_IOT_ACT_TX_NO_AGGREGATION
+		bIOTAction = HTIOTActIsForcedRTSCTS(ieee, pNetwork);
+		if(bIOTAction)
+			pHTInfo->IOTAction |= HT_IOT_ACT_FORCED_RTS;
+
+		printk("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!IOTAction = %8.8x\n", pHTInfo->IOTAction);
+	}
+	else
+	{
+		pHTInfo->bCurrentHTSupport = false;
+		pHTInfo->bCurrentRT2RTAggregation = false;
+		pHTInfo->bCurrentRT2RTLongSlotTime = false;
+		pHTInfo->RT2RT_HT_Mode = (RT_HT_CAPBILITY)0;
+
+		pHTInfo->IOTAction = 0;
+		pHTInfo->IOTRaFunc = 0;
+	}
+
+}
+
+void HTUpdateSelfAndPeerSetting(struct ieee80211_device* ieee, 	struct ieee80211_network * pNetwork)
+{
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+//	PHT_CAPABILITY_ELE		pPeerHTCap = (PHT_CAPABILITY_ELE)pNetwork->bssht.bdHTCapBuf;
+	PHT_INFORMATION_ELE		pPeerHTInfo = (PHT_INFORMATION_ELE)pNetwork->bssht.bdHTInfoBuf;
+
+	if(pHTInfo->bCurrentHTSupport)
+	{
+		//
+		// Config current operation mode.
+		//
+		if(pNetwork->bssht.bdHTInfoLen != 0)
+			pHTInfo->CurrentOpMode = pPeerHTInfo->OptMode;
+
+		//
+		// <TODO: Config according to OBSS non-HT STA present!!>
+		//
+	}
+}
+
+void HTUseDefaultSetting(struct ieee80211_device* ieee)
+{
+	PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
+//	u8	regBwOpMode;
+
+	if(pHTInfo->bEnableHT)
+	{
+		pHTInfo->bCurrentHTSupport = true;
+
+		pHTInfo->bCurSuppCCK = pHTInfo->bRegSuppCCK;
+
+		pHTInfo->bCurBW40MHz = pHTInfo->bRegBW40MHz;
+
+		pHTInfo->bCurShortGI20MHz= pHTInfo->bRegShortGI20MHz;
+
+		pHTInfo->bCurShortGI40MHz= pHTInfo->bRegShortGI40MHz;
+
+		pHTInfo->bCurrent_AMSDU_Support = pHTInfo->bAMSDU_Support;
+
+		pHTInfo->nCurrent_AMSDU_MaxSize = pHTInfo->nAMSDU_MaxSize;
+
+		pHTInfo->bCurrentAMPDUEnable = pHTInfo->bAMPDUEnable;
+
+		pHTInfo->CurrentAMPDUFactor = pHTInfo->AMPDU_Factor;
+
+		pHTInfo->CurrentMPDUDensity = pHTInfo->CurrentMPDUDensity;
+
+		// Set BWOpMode register
+
+		//update RATR index0
+		HTFilterMCSRate(ieee, ieee->Regdot11HTOperationalRateSet, ieee->dot11HTOperationalRateSet);
+	//function below is not implemented at all. WB
+#ifdef TODO
+		Adapter->HalFunc.InitHalRATRTableHandler( Adapter, &pMgntInfo->dot11OperationalRateSet, pMgntInfo->dot11HTOperationalRateSet);
+#endif
+		ieee->HTHighestOperaRate = HTGetHighestMCSRate(ieee, ieee->dot11HTOperationalRateSet, MCS_FILTER_ALL);
+		ieee->HTCurrentOperaRate = ieee->HTHighestOperaRate;
+
+	}
+	else
+	{
+		pHTInfo->bCurrentHTSupport = false;
+	}
+	return;
+}
+/********************************************************************************************************************
+ *function:  check whether HT control field exists
+ *   input:  struct ieee80211_device 	*ieee
+ *   	     u8*			pFrame //coming skb->data
+ *  output:  none
+ *  return:  return true if HT control field exists(false otherwise)
+ *  notice:
+********************************************************************************************************************/
+u8 HTCCheck(struct ieee80211_device* ieee, u8*	pFrame)
+{
+	if(ieee->pHTInfo->bCurrentHTSupport)
+	{
+		if( (IsQoSDataFrame(pFrame) && Frame_Order(pFrame)) == 1)
+		{
+			IEEE80211_DEBUG(IEEE80211_DL_HT, "HT CONTROL FILED EXIST!!\n");
+			return true;
+		}
+	}
+	return false;
+}
+
+//
+// This function set bandwidth mode in protocol layer.
+//
+void HTSetConnectBwMode(struct ieee80211_device* ieee, HT_CHANNEL_WIDTH	Bandwidth, HT_EXTCHNL_OFFSET	Offset)
+{
+	PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
+//	u32 flags = 0;
+
+	if(pHTInfo->bRegBW40MHz == false)
+		return;
+
+
+
+	// To reduce dummy operation
+//	if((pHTInfo->bCurBW40MHz==false && Bandwidth==HT_CHANNEL_WIDTH_20) ||
+//	   (pHTInfo->bCurBW40MHz==true && Bandwidth==HT_CHANNEL_WIDTH_20_40 && Offset==pHTInfo->CurSTAExtChnlOffset))
+//		return;
+
+//	spin_lock_irqsave(&(ieee->bw_spinlock), flags);
+	if(pHTInfo->bSwBwInProgress) {
+//		spin_unlock_irqrestore(&(ieee->bw_spinlock), flags);
+		return;
+	}
+	//if in half N mode, set to 20M bandwidth please 09.08.2008 WB.
+	if(Bandwidth==HT_CHANNEL_WIDTH_20_40 && (!ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev)))
+	 {
+	 		// Handle Illegal extention channel offset!!
+		if(ieee->current_network.channel<2 && Offset==HT_EXTCHNL_OFFSET_LOWER)
+			Offset = HT_EXTCHNL_OFFSET_NO_EXT;
+		if(Offset==HT_EXTCHNL_OFFSET_UPPER || Offset==HT_EXTCHNL_OFFSET_LOWER) {
+			pHTInfo->bCurBW40MHz = true;
+			pHTInfo->CurSTAExtChnlOffset = Offset;
+		} else {
+			pHTInfo->bCurBW40MHz = false;
+			pHTInfo->CurSTAExtChnlOffset = HT_EXTCHNL_OFFSET_NO_EXT;
+		}
+	} else {
+		pHTInfo->bCurBW40MHz = false;
+		pHTInfo->CurSTAExtChnlOffset = HT_EXTCHNL_OFFSET_NO_EXT;
+	}
+
+	pHTInfo->bSwBwInProgress = true;
+
+	// TODO: 2007.7.13 by Emily Wait 2000ms  in order to garantee that switching
+	//   bandwidth is executed after scan is finished. It is a temporal solution
+	//   because software should ganrantee the last operation of switching bandwidth
+	//   is executed properlly.
+	HTSetConnectBwModeCallback(ieee);
+
+//	spin_unlock_irqrestore(&(ieee->bw_spinlock), flags);
+}
+
+void HTSetConnectBwModeCallback(struct ieee80211_device* ieee)
+{
+	PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
+
+	IEEE80211_DEBUG(IEEE80211_DL_HT, "======>%s()\n", __FUNCTION__);
+	if(pHTInfo->bCurBW40MHz)
+	{
+		if(pHTInfo->CurSTAExtChnlOffset==HT_EXTCHNL_OFFSET_UPPER)
+			ieee->set_chan(ieee->dev, ieee->current_network.channel+2);
+		else if(pHTInfo->CurSTAExtChnlOffset==HT_EXTCHNL_OFFSET_LOWER)
+			ieee->set_chan(ieee->dev, ieee->current_network.channel-2);
+		else
+			ieee->set_chan(ieee->dev, ieee->current_network.channel);
+
+		ieee->SetBWModeHandler(ieee->dev, HT_CHANNEL_WIDTH_20_40, pHTInfo->CurSTAExtChnlOffset);
+	} else {
+		ieee->set_chan(ieee->dev, ieee->current_network.channel);
+		ieee->SetBWModeHandler(ieee->dev, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
+	}
+
+	pHTInfo->bSwBwInProgress = false;
+}
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+EXPORT_SYMBOL_NOVERS(HTUpdateSelfAndPeerSetting);
+#else
+EXPORT_SYMBOL(HTUpdateSelfAndPeerSetting);
+#endif
diff --git a/drivers/staging/rtl8192su/ieee80211/rtl819x_Qos.h b/drivers/staging/rtl8192su/ieee80211/rtl819x_Qos.h
new file mode 100644
index 0000000..f7b882b
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/rtl819x_Qos.h
@@ -0,0 +1,749 @@
+#ifndef __INC_QOS_TYPE_H
+#define __INC_QOS_TYPE_H
+
+//#include "EndianFree.h"
+#define BIT0                    0x00000001
+#define BIT1                    0x00000002
+#define BIT2                    0x00000004
+#define BIT3                    0x00000008
+#define BIT4                    0x00000010
+#define BIT5                    0x00000020
+#define BIT6                    0x00000040
+#define BIT7                    0x00000080
+#define BIT8                    0x00000100
+#define BIT9                    0x00000200
+#define BIT10                   0x00000400
+#define BIT11                   0x00000800
+#define BIT12                   0x00001000
+#define BIT13                   0x00002000
+#define BIT14                   0x00004000
+#define BIT15                   0x00008000
+#define BIT16                   0x00010000
+#define BIT17                   0x00020000
+#define BIT18                   0x00040000
+#define BIT19                   0x00080000
+#define BIT20                   0x00100000
+#define BIT21                   0x00200000
+#define BIT22                   0x00400000
+#define BIT23                   0x00800000
+#define BIT24                   0x01000000
+#define BIT25                   0x02000000
+#define BIT26                   0x04000000
+#define BIT27                   0x08000000
+#define BIT28                   0x10000000
+#define BIT29                   0x20000000
+#define BIT30                   0x40000000
+#define BIT31                   0x80000000
+
+#define	MAX_WMMELE_LENGTH	64
+
+//
+// QoS mode.
+// enum 0, 1, 2, 4: since we can use the OR(|) operation.
+//
+// QOS_MODE is redefined for enum can't be ++, | under C++ compiler, 2006.05.17, by rcnjko.
+//typedef	enum _QOS_MODE{
+//	QOS_DISABLE		= 0,
+//	QOS_WMM			= 1,
+//	QOS_EDCA			= 2,
+//	QOS_HCCA			= 4,
+//}QOS_MODE,*PQOS_MODE;
+//
+typedef u32 QOS_MODE, *PQOS_MODE;
+#define QOS_DISABLE		0
+#define QOS_WMM			1
+#define QOS_WMMSA		2
+#define QOS_EDCA		4
+#define QOS_HCCA		8
+#define QOS_WMM_UAPSD		16   //WMM Power Save, 2006-06-14 Isaiah
+
+#define AC_PARAM_SIZE	4
+#define WMM_PARAM_ELE_BODY_LEN	18
+
+//
+// QoS ACK Policy Field Values
+// Ref: WMM spec 2.1.6: QoS Control Field, p.10.
+//
+typedef	enum _ACK_POLICY{
+	eAckPlc0_ACK		= 0x00,
+	eAckPlc1_NoACK		= 0x01,
+}ACK_POLICY,*PACK_POLICY;
+
+#define WMM_PARAM_ELEMENT_SIZE	(8+(4*AC_PARAM_SIZE))
+#if 0
+#define GET_QOS_CTRL(_pStart)	ReadEF2Byte((u8 *)(_pStart) + 24)
+#define SET_QOS_CTRL(_pStart, _value)	WriteEF2Byte((u8 *)(_pStart) + 24, _value)
+
+// WMM control field.
+#define GET_QOS_CTRL_WMM_UP(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 0, 3))
+#define SET_QOS_CTRL_WMM_UP(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 0, 3, (u8)(_value))
+
+#define GET_QOS_CTRL_WMM_EOSP(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 4, 1))
+#define SET_QOS_CTRL_WMM_EOSP(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 4, 1, (u8)(_value))
+
+#define GET_QOS_CTRL_WMM_ACK_POLICY(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 5, 2))
+#define SET_QOS_CTRL_WMM_ACK_POLICY(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 5, 2, (u8)(_value))
+
+// 802.11e control field (by STA, data)
+#define GET_QOS_CTRL_STA_DATA_TID(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 0, 4))
+#define SET_QOS_CTRL_STA_DATA_TID(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 0, 4, (u8)(_value))
+
+#define GET_QOS_CTRL_STA_DATA_QSIZE_FLAG(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 4, 1))
+#define SET_QOS_CTRL_STA_DATA_QSIZE_FLAG(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 4, 1, (u8)(_value))
+
+#define GET_QOS_CTRL_STA_DATA_ACK_POLICY(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 5, 2))
+#define SET_QOS_CTRL_STA_DATA_ACK_POLICY(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 5, 2, (u8)(_value))
+
+#define GET_QOS_CTRL_STA_DATA_TXOP(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 8, 8))
+#define SET_QOS_CTRL_STA_DATA_TXOP(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 8, 8, (u8)(_value))
+
+#define GET_QOS_CTRL_STA_DATA_QSIZE(_pStart)	GET_QOS_CTRL_STA_DATA_TXOP(_pStart)
+#define SET_QOS_CTRL_STA_DATA_QSIZE(_pStart, _value)	SET_QOS_CTRL_STA_DATA_TXOP(_pStart)
+
+// 802.11e control field (by HC, data)
+#define GET_QOS_CTRL_HC_DATA_TID(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 0, 4))
+#define SET_QOS_CTRL_HC_DATA_TID(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 0, 4, (u8)(_value))
+
+#define GET_QOS_CTRL_HC_DATA_EOSP(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 4, 1))
+#define SET_QOS_CTRL_HC_DATA_EOSP(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 4, 1, (u8)(_value))
+
+#define GET_QOS_CTRL_HC_DATA_ACK_POLICY(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 5, 2))
+#define SET_QOS_CTRL_HC_DATA_ACK_POLICY(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 5, 2, (u8)(_value))
+
+#define GET_QOS_CTRL_HC_DATA_PS_BUFSTATE(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 8, 8))
+#define SET_QOS_CTRL_HC_DATA_PS_BUFSTATE(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 8, 8, (u8)(_value))
+
+// 802.11e control field (by HC, CFP)
+#define GET_QOS_CTRL_HC_CFP_TID(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 0, 4))
+#define SET_QOS_CTRL_HC_CFP_TID(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 0, 4, (u8)(_value))
+
+#define GET_QOS_CTRL_HC_CFP_EOSP(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 4, 1))
+#define SET_QOS_CTRL_HC_CFP_EOSP(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 4, 1, (u8)(_value))
+
+#define GET_QOS_CTRL_HC_CFP_ACK_POLICY(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 5, 2))
+#define SET_QOS_CTRL_HC_CFP_ACK_POLICY(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 5, 2, (u8)(_value))
+
+#define GET_QOS_CTRL_HC_CFP_TXOP_LIMIT(_pStart)	((u8)LE_BITS_TO_2BYTE((u8 *)(_pStart)+24, 8, 8))
+#define SET_QOS_CTRL_HC_CFP_TXOP_LIMIT(_pStart, _value)	SET_BITS_TO_LE_2BYTE((u8 *)(_pStart)+24, 8, 8, (u8)(_value))
+
+#define SET_WMM_QOS_INFO_FIELD(_pStart, _val)	WriteEF1Byte(_pStart, _val)
+
+#define GET_WMM_QOS_INFO_FIELD_PARAMETERSET_COUNT(_pStart)	LE_BITS_TO_1BYTE(_pStart, 0, 4)
+#define SET_WMM_QOS_INFO_FIELD_PARAMETERSET_COUNT(_pStart, _val)	SET_BITS_TO_LE_1BYTE(_pStart, 0, 4, _val)
+
+#define GET_WMM_QOS_INFO_FIELD_AP_UAPSD(_pStart)	LE_BITS_TO_1BYTE(_pStart, 7, 1)
+#define SET_WMM_QOS_INFO_FIELD_AP_UAPSD(_pStart, _val)	SET_BITS_TO_LE_1BYTE(_pStart, 7, 1, _val)
+
+#define GET_WMM_QOS_INFO_FIELD_STA_AC_VO_UAPSD(_pStart)	LE_BITS_TO_1BYTE(_pStart, 0, 1)
+#define SET_WMM_QOS_INFO_FIELD_STA_AC_VO_UAPSD(_pStart, _val)	SET_BITS_TO_LE_1BYTE(_pStart, 0, 1, _val)
+
+#define GET_WMM_QOS_INFO_FIELD_STA_AC_VI_UAPSD(_pStart)	LE_BITS_TO_1BYTE(_pStart, 1, 1)
+#define SET_WMM_QOS_INFO_FIELD_STA_AC_VI_UAPSD(_pStart, _val)	SET_BITS_TO_LE_1BYTE(_pStart, 1, 1, _val)
+
+#define GET_WMM_QOS_INFO_FIELD_STA_AC_BE_UAPSD(_pStart)	LE_BITS_TO_1BYTE(_pStart, 2, 1)
+#define SET_WMM_QOS_INFO_FIELD_STA_AC_BE_UAPSD(_pStart, _val)	SET_BITS_TO_LE_1BYTE(_pStart, 2, 1, _val)
+
+#define GET_WMM_QOS_INFO_FIELD_STA_AC_BK_UAPSD(_pStart)	LE_BITS_TO_1BYTE(_pStart, 3, 1)
+#define SET_WMM_QOS_INFO_FIELD_STA_AC_BK_UAPSD(_pStart, _val)	SET_BITS_TO_LE_1BYTE(_pStart, 3, 1, _val)
+
+#define GET_WMM_QOS_INFO_FIELD_STA_MAX_SP_LEN(_pStart)	LE_BITS_TO_1BYTE(_pStart, 5, 2)
+#define SET_WMM_QOS_INFO_FIELD_STA_MAX_SP_LEN(_pStart, _val)	SET_BITS_TO_LE_1BYTE(_pStart, 5, 2, _val)
+
+
+#define WMM_INFO_ELEMENT_SIZE	7
+
+#define GET_WMM_INFO_ELE_OUI(_pStart)	((u8 *)(_pStart))
+#define SET_WMM_INFO_ELE_OUI(_pStart, _pVal)	PlatformMoveMemory(_pStart, _pVal, 3);
+
+#define GET_WMM_INFO_ELE_OUI_TYPE(_pStart)	( EF1Byte( *((u8 *)(_pStart)+3) ) )
+#define SET_WMM_INFO_ELE_OUI_TYPE(_pStart, _val)	( *((u8 *)(_pStart)+3) = EF1Byte(_val) )
+
+#define GET_WMM_INFO_ELE_OUI_SUBTYPE(_pStart)	( EF1Byte( *((u8 *)(_pStart)+4) ) )
+#define SET_WMM_INFO_ELE_OUI_SUBTYPE(_pStart, _val)	( *((u8 *)(_pStart)+4) = EF1Byte(_val) )
+
+#define GET_WMM_INFO_ELE_VERSION(_pStart)	( EF1Byte( *((u8 *)(_pStart)+5) ) )
+#define SET_WMM_INFO_ELE_VERSION(_pStart, _val)	( *((u8 *)(_pStart)+5) = EF1Byte(_val) )
+
+#define GET_WMM_INFO_ELE_QOS_INFO_FIELD(_pStart)	( EF1Byte( *((u8 *)(_pStart)+6) ) )
+#define SET_WMM_INFO_ELE_QOS_INFO_FIELD(_pStart, _val)	( *((u8 *)(_pStart)+6) = EF1Byte(_val) )
+
+
+
+#define GET_WMM_AC_PARAM_AIFSN(_pStart)	( (u8)LE_BITS_TO_4BYTE(_pStart, 0, 4) )
+#define SET_WMM_AC_PARAM_AIFSN(_pStart, _val)	SET_BITS_TO_LE_4BYTE(_pStart, 0, 4, _val)
+
+#define GET_WMM_AC_PARAM_ACM(_pStart)	( (u8)LE_BITS_TO_4BYTE(_pStart, 4, 1) )
+#define SET_WMM_AC_PARAM_ACM(_pStart, _val)	SET_BITS_TO_LE_4BYTE(_pStart, 4, 1, _val)
+
+#define GET_WMM_AC_PARAM_ACI(_pStart)		( (u8)LE_BITS_TO_4BYTE(_pStart, 5, 2) )
+#define SET_WMM_AC_PARAM_ACI(_pStart, _val)	SET_BITS_TO_LE_4BYTE(_pStart, 5, 2, _val)
+
+#define GET_WMM_AC_PARAM_ACI_AIFSN(_pStart)	( (u8)LE_BITS_TO_4BYTE(_pStart, 0, 8) )
+#define SET_WMM_AC_PARAM_ACI_AIFSN(_pStart, _val)	SET_BTIS_TO_LE_4BYTE(_pStart, 0, 8, _val)
+
+#define GET_WMM_AC_PARAM_ECWMIN(_pStart)	( (u8)LE_BITS_TO_4BYTE(_pStart, 8, 4) )
+#define SET_WMM_AC_PARAM_ECWMIN(_pStart, _val)	SET_BITS_TO_LE_4BYTE(_pStart, 8, 4, _val)
+
+#define GET_WMM_AC_PARAM_ECWMAX(_pStart)	( (u8)LE_BITS_TO_4BYTE(_pStart, 12, 4) )
+#define SET_WMM_AC_PARAM_ECWMAX(_pStart, _val)	SET_BITS_TO_LE_4BYTE(_pStart, 12, 4, _val)
+
+#define GET_WMM_AC_PARAM_TXOP_LIMIT(_pStart)		( (u16)LE_BITS_TO_4BYTE(_pStart, 16, 16) )
+#define SET_WMM_AC_PARAM_TXOP_LIMIT(_pStart, _val)	SET_BITS_TO_LE_4BYTE(_pStart, 16, 16, _val)
+
+
+
+
+#define GET_WMM_PARAM_ELE_OUI(_pStart)	((u8 *)(_pStart))
+#define SET_WMM_PARAM_ELE_OUI(_pStart, _pVal)	PlatformMoveMemory(_pStart, _pVal, 3)
+
+#define GET_WMM_PARAM_ELE_OUI_TYPE(_pStart)	( EF1Byte( *((u8 *)(_pStart)+3) ) )
+#define SET_WMM_PARAM_ELE_OUI_TYPE(_pStart, _val)	( *((u8 *)(_pStart)+3) = EF1Byte(_val) )
+
+#define GET_WMM_PARAM_ELE_OUI_SUBTYPE(_pStart)	( EF1Byte( *((u8 *)(_pStart)+4) ) )
+#define SET_WMM_PARAM_ELE_OUI_SUBTYPE(_pStart, _val)	( *((u8 *)(_pStart)+4) = EF1Byte(_val) )
+
+#define GET_WMM_PARAM_ELE_VERSION(_pStart)	( EF1Byte( *((u8 *)(_pStart)+5) ) )
+#define SET_WMM_PARAM_ELE_VERSION(_pStart, _val)	( *((u8 *)(_pStart)+5) = EF1Byte(_val) )
+
+#define GET_WMM_PARAM_ELE_QOS_INFO_FIELD(_pStart)	( EF1Byte( *((u8 *)(_pStart)+6) ) )
+#define SET_WMM_PARAM_ELE_QOS_INFO_FIELD(_pStart, _val)	( *((u8 *)(_pStart)+6) = EF1Byte(_val) )
+
+#define GET_WMM_PARAM_ELE_AC_PARAM(_pStart)	( (u8 *)(_pStart)+8 )
+#define SET_WMM_PARAM_ELE_AC_PARAM(_pStart, _pVal) PlatformMoveMemory((_pStart)+8, _pVal, 16)
+#endif
+
+//
+// QoS Control Field
+// Ref:
+//	1. WMM spec 2.1.6: QoS Control Field, p.9.
+//	2. 802.11e/D13.0 7.1.3.5, p.26.
+//
+typedef	union _QOS_CTRL_FIELD{
+	u8	charData[2];
+	u16	shortData;
+
+	// WMM spec
+	struct
+	{
+		u8		UP:3;
+		u8		usRsvd1:1;
+		u8		EOSP:1;
+		u8		AckPolicy:2;
+		u8		usRsvd2:1;
+		u8		ucRsvdByte;
+	}WMM;
+
+	// 802.11e: QoS data type frame sent by non-AP QSTAs.
+	struct
+	{
+		u8		TID:4;
+		u8		bIsQsize:1;// 0: BIT[8:15] is TXOP Duration Requested, 1: BIT[8:15] is Queue Size.
+		u8		AckPolicy:2;
+		u8		usRsvd:1;
+		u8		TxopOrQsize;	// (BIT4=0)TXOP Duration Requested or (BIT4=1)Queue Size.
+	}BySta;
+
+	// 802.11e: QoS data, QoS Null, and QoS Data+CF-Ack frames sent by HC.
+	struct
+	{
+		u8		TID:4;
+		u8		EOSP:1;
+		u8		AckPolicy:2;
+		u8		usRsvd:1;
+		u8		PSBufState;		// QAP PS Buffer State.
+	}ByHc_Data;
+
+	// 802.11e: QoS (+) CF-Poll frames sent by HC.
+	struct
+	{
+		u8		TID:4;
+		u8		EOSP:1;
+		u8		AckPolicy:2;
+		u8		usRsvd:1;
+		u8		TxopLimit;		// TXOP Limit.
+	}ByHc_CFP;
+
+}QOS_CTRL_FIELD, *PQOS_CTRL_FIELD;
+
+
+//
+// QoS Info Field
+// Ref:
+//	1. WMM spec 2.2.1: WME Information Element, p.11.
+//	2. 8185 QoS code: QOS_INFO [def. in QoS_mp.h]
+//
+typedef	union _QOS_INFO_FIELD{
+	u8	charData;
+
+	struct
+	{
+		u8		ucParameterSetCount:4;
+		u8		ucReserved:4;
+	}WMM;
+
+	struct
+	{
+		//Ref WMM_Specification_1-1.pdf, 2006-06-13 Isaiah
+		u8		ucAC_VO_UAPSD:1;
+		u8		ucAC_VI_UAPSD:1;
+		u8		ucAC_BE_UAPSD:1;
+		u8		ucAC_BK_UAPSD:1;
+		u8		ucReserved1:1;
+		u8		ucMaxSPLen:2;
+		u8		ucReserved2:1;
+
+	}ByWmmPsSta;
+
+	struct
+	{
+		//Ref WMM_Specification_1-1.pdf, 2006-06-13 Isaiah
+		u8		ucParameterSetCount:4;
+		u8		ucReserved:3;
+		u8		ucApUapsd:1;
+	}ByWmmPsAp;
+
+	struct
+	{
+		u8		ucAC3_UAPSD:1;
+		u8		ucAC2_UAPSD:1;
+		u8		ucAC1_UAPSD:1;
+		u8		ucAC0_UAPSD:1;
+		u8		ucQAck:1;
+		u8		ucMaxSPLen:2;
+		u8		ucMoreDataAck:1;
+	} By11eSta;
+
+	struct
+	{
+		u8		ucParameterSetCount:4;
+		u8		ucQAck:1;
+		u8		ucQueueReq:1;
+		u8		ucTXOPReq:1;
+		u8		ucReserved:1;
+	} By11eAp;
+
+	struct
+	{
+		u8		ucReserved1:4;
+		u8		ucQAck:1;
+		u8		ucReserved2:2;
+		u8		ucMoreDataAck:1;
+	} ByWmmsaSta;
+
+	struct
+	{
+		u8		ucReserved1:4;
+		u8		ucQAck:1;
+		u8		ucQueueReq:1;
+		u8		ucTXOPReq:1;
+		u8		ucReserved2:1;
+	} ByWmmsaAp;
+
+	struct
+	{
+		u8		ucAC3_UAPSD:1;
+		u8		ucAC2_UAPSD:1;
+		u8		ucAC1_UAPSD:1;
+		u8		ucAC0_UAPSD:1;
+		u8		ucQAck:1;
+		u8		ucMaxSPLen:2;
+		u8		ucMoreDataAck:1;
+	} ByAllSta;
+
+	struct
+	{
+		u8		ucParameterSetCount:4;
+		u8		ucQAck:1;
+		u8		ucQueueReq:1;
+		u8		ucTXOPReq:1;
+		u8		ucApUapsd:1;
+	} ByAllAp;
+
+}QOS_INFO_FIELD, *PQOS_INFO_FIELD;
+
+#if 0
+//
+// WMM Information Element
+// Ref: WMM spec 2.2.1: WME Information Element, p.10.
+//
+typedef struct _WMM_INFO_ELEMENT{
+//	u8			ElementID;
+//	u8			Length;
+	u8			OUI[3];
+	u8			OUI_Type;
+	u8			OUI_SubType;
+	u8			Version;
+	QOS_INFO_FIELD	QosInfo;
+}WMM_INFO_ELEMENT, *PWMM_INFO_ELEMENT;
+#endif
+
+//
+// ACI to AC coding.
+// Ref: WMM spec 2.2.2: WME Parameter Element, p.13.
+//
+// AC_CODING is redefined for enum can't be ++, | under C++ compiler, 2006.05.17, by rcnjko.
+//typedef	enum _AC_CODING{
+//	AC0_BE	= 0,		// ACI: 0x00	// Best Effort
+//	AC1_BK	= 1,		// ACI: 0x01	// Background
+//	AC2_VI	= 2,		// ACI: 0x10	// Video
+//	AC3_VO	= 3,		// ACI: 0x11	// Voice
+//	AC_MAX = 4,		// Max: define total number; Should not to be used as a real enum.
+//}AC_CODING,*PAC_CODING;
+//
+typedef u32 AC_CODING;
+#define AC0_BE	0		// ACI: 0x00	// Best Effort
+#define AC1_BK	1		// ACI: 0x01	// Background
+#define AC2_VI	2		// ACI: 0x10	// Video
+#define AC3_VO	3		// ACI: 0x11	// Voice
+#define AC_MAX	4		// Max: define total number; Should not to be used as a real enum.
+
+//
+// ACI/AIFSN Field.
+// Ref: WMM spec 2.2.2: WME Parameter Element, p.12.
+//
+typedef	union _ACI_AIFSN{
+	u8	charData;
+
+	struct
+	{
+		u8	AIFSN:4;
+		u8	ACM:1;
+		u8	ACI:2;
+		u8	Reserved:1;
+	}f;	// Field
+}ACI_AIFSN, *PACI_AIFSN;
+
+//
+// ECWmin/ECWmax field.
+// Ref: WMM spec 2.2.2: WME Parameter Element, p.13.
+//
+typedef	union _ECW{
+	u8	charData;
+	struct
+	{
+		u8	ECWmin:4;
+		u8	ECWmax:4;
+	}f;	// Field
+}ECW, *PECW;
+
+//
+// AC Parameters Record Format.
+// Ref: WMM spec 2.2.2: WME Parameter Element, p.12.
+//
+typedef	union _AC_PARAM{
+	u32	longData;
+	u8	charData[4];
+
+	struct
+	{
+		ACI_AIFSN	AciAifsn;
+		ECW		Ecw;
+		u16		TXOPLimit;
+	}f;	// Field
+}AC_PARAM, *PAC_PARAM;
+
+
+
+//
+// QoS element subtype
+//
+typedef	enum _QOS_ELE_SUBTYPE{
+	QOSELE_TYPE_INFO	= 0x00,		// 0x00: Information element
+	QOSELE_TYPE_PARAM	= 0x01,		// 0x01: parameter element
+}QOS_ELE_SUBTYPE,*PQOS_ELE_SUBTYPE;
+
+
+//
+// Direction Field Values.
+// Ref: WMM spec 2.2.11: WME TSPEC Element, p.18.
+//
+typedef	enum _DIRECTION_VALUE{
+	DIR_UP			= 0,		// 0x00	// UpLink
+	DIR_DOWN		= 1,		// 0x01	// DownLink
+	DIR_DIRECT		= 2,		// 0x10	// DirectLink
+	DIR_BI_DIR		= 3,		// 0x11	// Bi-Direction
+}DIRECTION_VALUE,*PDIRECTION_VALUE;
+
+
+//
+// TS Info field in WMM TSPEC Element.
+// Ref:
+//	1. WMM spec 2.2.11: WME TSPEC Element, p.18.
+//	2. 8185 QoS code: QOS_TSINFO [def. in QoS_mp.h]
+//
+typedef union _QOS_TSINFO{
+	u8		charData[3];
+	struct {
+		u8		ucTrafficType:1;			//WMM is reserved
+		u8		ucTSID:4;
+		u8		ucDirection:2;
+		u8		ucAccessPolicy:2;	//WMM: bit8=0, bit7=1
+		u8		ucAggregation:1;		//WMM is reserved
+		u8		ucPSB:1;				//WMMSA is APSD
+		u8		ucUP:3;
+		u8		ucTSInfoAckPolicy:2;		//WMM is reserved
+		u8		ucSchedule:1;			//WMM is reserved
+		u8		ucReserved:7;
+	}field;
+}QOS_TSINFO, *PQOS_TSINFO;
+
+//
+// WMM TSPEC Body.
+// Ref: WMM spec 2.2.11: WME TSPEC Element, p.16.
+//
+typedef union _TSPEC_BODY{
+	u8		charData[55];
+
+	struct
+	{
+		QOS_TSINFO	TSInfo;	//u8	TSInfo[3];
+		u16	NominalMSDUsize;
+		u16	MaxMSDUsize;
+		u32	MinServiceItv;
+		u32	MaxServiceItv;
+		u32	InactivityItv;
+		u32	SuspenItv;
+		u32	ServiceStartTime;
+		u32	MinDataRate;
+		u32	MeanDataRate;
+		u32	PeakDataRate;
+		u32	MaxBurstSize;
+		u32	DelayBound;
+		u32	MinPhyRate;
+		u16	SurplusBandwidthAllowance;
+		u16	MediumTime;
+	} f;	// Field
+}TSPEC_BODY, *PTSPEC_BODY;
+
+
+//
+// WMM TSPEC Element.
+// Ref: WMM spec 2.2.11: WME TSPEC Element, p.16.
+//
+typedef struct _WMM_TSPEC{
+	u8		ID;
+	u8		Length;
+	u8		OUI[3];
+	u8		OUI_Type;
+	u8		OUI_SubType;
+	u8		Version;
+	TSPEC_BODY	Body;
+} WMM_TSPEC, *PWMM_TSPEC;
+
+//
+// ACM implementation method.
+// Annie, 2005-12-13.
+//
+typedef	enum _ACM_METHOD{
+	eAcmWay0_SwAndHw		= 0,		// By SW and HW.
+	eAcmWay1_HW			= 1,		// By HW.
+	eAcmWay2_SW			= 2,		// By SW.
+}ACM_METHOD,*PACM_METHOD;
+
+
+typedef struct _ACM{
+//	u8		RegEnableACM;
+	u64		UsedTime;
+	u64		MediumTime;
+	u8		HwAcmCtl;	// TRUE: UsedTime exceed => Do NOT USE this AC. It wll be written to ACM_CONTROL(0xBF BIT 0/1/2 in 8185B).
+}ACM, *PACM;
+
+typedef	u8		AC_UAPSD, *PAC_UAPSD;
+
+#define	GET_VO_UAPSD(_apsd) ((_apsd) & BIT0)
+#define	SET_VO_UAPSD(_apsd) ((_apsd) |= BIT0)
+
+#define	GET_VI_UAPSD(_apsd) ((_apsd) & BIT1)
+#define	SET_VI_UAPSD(_apsd) ((_apsd) |= BIT1)
+
+#define	GET_BK_UAPSD(_apsd) ((_apsd) & BIT2)
+#define	SET_BK_UAPSD(_apsd) ((_apsd) |= BIT2)
+
+#define	GET_BE_UAPSD(_apsd) ((_apsd) & BIT3)
+#define	SET_BE_UAPSD(_apsd) ((_apsd) |= BIT3)
+
+
+//typedef struct _TCLASS{
+// TODO
+//} TCLASS, *PTCLASS;
+typedef union _QOS_TCLAS{
+
+	struct _TYPE_GENERAL{
+		u8		Priority;
+		u8 		ClassifierType;
+		u8 		Mask;
+	} TYPE_GENERAL;
+
+	struct _TYPE0_ETH{
+		u8		Priority;
+		u8 		ClassifierType;
+		u8 		Mask;
+		u8		SrcAddr[6];
+		u8		DstAddr[6];
+		u16		Type;
+	} TYPE0_ETH;
+
+	struct _TYPE1_IPV4{
+		u8		Priority;
+		u8 		ClassifierType;
+		u8 		Mask;
+		u8 		Version;
+		u8		SrcIP[4];
+		u8		DstIP[4];
+		u16		SrcPort;
+		u16		DstPort;
+		u8		DSCP;
+		u8		Protocol;
+		u8		Reserved;
+	} TYPE1_IPV4;
+
+	struct _TYPE1_IPV6{
+		u8		Priority;
+		u8 		ClassifierType;
+		u8 		Mask;
+		u8 		Version;
+		u8		SrcIP[16];
+		u8		DstIP[16];
+		u16		SrcPort;
+		u16		DstPort;
+		u8		FlowLabel[3];
+	} TYPE1_IPV6;
+
+	struct _TYPE2_8021Q{
+		u8		Priority;
+		u8 		ClassifierType;
+		u8 		Mask;
+		u16		TagType;
+	} TYPE2_8021Q;
+} QOS_TCLAS, *PQOS_TCLAS;
+
+//typedef struct _WMM_TSTREAM{
+//
+//- TSPEC
+//- AC (which to mapping)
+//} WMM_TSTREAM, *PWMM_TSTREAM;
+typedef struct _QOS_TSTREAM{
+	u8			AC;
+	WMM_TSPEC		TSpec;
+	QOS_TCLAS		TClass;
+} QOS_TSTREAM, *PQOS_TSTREAM;
+
+//typedef struct _U_APSD{
+//- TriggerEnable [4]
+//- MaxSPLength
+//- HighestAcBuffered
+//} U_APSD, *PU_APSD;
+
+//joseph TODO:
+//	UAPSD function should be implemented by 2 data structure
+//	"Qos control field" and "Qos info field"
+//typedef struct _QOS_UAPSD{
+//	u8			bTriggerEnable[4];
+//	u8 			MaxSPLength;
+//	u8			HighestBufAC;
+//} QOS_UAPSD, *PQOS_APSD;
+
+//----------------------------------------------------------------------------
+//      802.11 Management frame Status Code field
+//----------------------------------------------------------------------------
+typedef struct _OCTET_STRING{
+        u8        	*Octet;
+        u16             Length;
+}OCTET_STRING, *POCTET_STRING;
+#if 0
+#define FillOctetString(_os,_octet,_len)             \
+        (_os).Octet=(u8 *)(_octet);                  \
+        (_os).Length=(_len);
+
+#define WMM_ELEM_HDR_LEN        		     6
+#define WMMElemSkipHdr(_osWMMElem)                   \
+        (_osWMMElem).Octet += WMM_ELEM_HDR_LEN;      \
+        (_osWMMElem).Length -= WMM_ELEM_HDR_LEN;
+#endif
+//
+// STA QoS data.
+// Ref: DOT11_QOS in 8185 code. [def. in QoS_mp.h]
+//
+typedef struct _STA_QOS{
+	//DECLARE_RT_OBJECT(STA_QOS);
+	u8				WMMIEBuf[MAX_WMMELE_LENGTH];
+	u8*				WMMIE;
+
+	// Part 1. Self QoS Mode.
+	QOS_MODE			QosCapability; //QoS Capability, 2006-06-14 Isaiah
+	QOS_MODE			CurrentQosMode;
+
+	// For WMM Power Save Mode :
+	// ACs are trigger/delivery enabled or legacy power save enabled. 2006-06-13 Isaiah
+	AC_UAPSD			b4ac_Uapsd;  //VoUapsd(bit0), ViUapsd(bit1),  BkUapsd(bit2), BeUapsd(bit3),
+	AC_UAPSD			Curr4acUapsd;
+	u8				bInServicePeriod;
+	u8				MaxSPLength;
+	int 				NumBcnBeforeTrigger;
+
+	// Part 2. EDCA Parameter (perAC)
+	u8 *				pWMMInfoEle;
+	u8				WMMParamEle[WMM_PARAM_ELEMENT_SIZE];
+	u8				WMMPELength;
+
+	// <Bruce_Note>
+	//2 ToDo: remove the Qos Info Field and replace it by the above WMM Info element.
+	// By Bruce, 2008-01-30.
+	// Part 2. EDCA Parameter (perAC)
+	QOS_INFO_FIELD			QosInfoField_STA; 	// Maintained by STA
+	QOS_INFO_FIELD			QosInfoField_AP;	// Retrieved from AP
+
+	AC_PARAM			CurAcParameters[4];
+
+	// Part 3. ACM
+	ACM				acm[4];
+	ACM_METHOD			AcmMethod;
+
+	// Part 4. Per TID (Part 5: TCLASS will be described by TStream)
+	QOS_TSTREAM			TStream[16];
+	WMM_TSPEC			TSpec;
+
+	u32				QBssWirelessMode;
+
+	// No Ack Setting
+	u8				bNoAck;
+
+	// Enable/Disable Rx immediate BA capability.
+	u8				bEnableRxImmBA;
+
+}STA_QOS, *PSTA_QOS;
+
+//
+// BSS QOS data.
+// Ref: BssDscr in 8185 code. [def. in BssDscr.h]
+//
+typedef struct _BSS_QOS{
+	QOS_MODE		bdQoSMode;
+
+	u8			bdWMMIEBuf[MAX_WMMELE_LENGTH];
+	u8*		bdWMMIE;
+
+	QOS_ELE_SUBTYPE		EleSubType;
+
+	u8 *			pWMMInfoEle;
+	u8 *			pWMMParamEle;
+
+	QOS_INFO_FIELD		QosInfoField;
+	AC_PARAM		AcParameter[4];
+}BSS_QOS, *PBSS_QOS;
+
+
+//
+// Ref: sQoSCtlLng and QoSCtl definition in 8185 QoS code.
+//#define QoSCtl   ((	(Adapter->bRegQoS) && (Adapter->dot11QoS.QoSMode &(QOS_EDCA|QOS_HCCA))	  )  ?sQoSCtlLng:0)
+//
+#define sQoSCtlLng			2
+#define	QOS_CTRL_LEN(_QosMode)		((_QosMode > QOS_DISABLE)? sQoSCtlLng : 0)
+
+
+//Added by joseph
+//UP Mapping to AC, using in MgntQuery_SequenceNumber() and maybe for DSCP
+//#define UP2AC(up)			((up<3)?((up==0)?1:0):(up>>1))
+#define IsACValid(ac)			((ac<=7 )?true:false )
+
+#endif // #ifndef __INC_QOS_TYPE_H
diff --git a/drivers/staging/rtl8192su/ieee80211/rtl819x_TS.h b/drivers/staging/rtl8192su/ieee80211/rtl819x_TS.h
new file mode 100644
index 0000000..baaac21
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/rtl819x_TS.h
@@ -0,0 +1,56 @@
+#ifndef _TSTYPE_H_
+#define _TSTYPE_H_
+#include "rtl819x_Qos.h"
+#define TS_SETUP_TIMEOUT	60  // In millisecond
+#define TS_INACT_TIMEOUT	60
+#define TS_ADDBA_DELAY		60
+
+#define TOTAL_TS_NUM		16
+#define TCLAS_NUM		4
+
+// This define the Tx/Rx directions
+typedef enum _TR_SELECT {
+	TX_DIR = 0,
+	RX_DIR = 1,
+} TR_SELECT, *PTR_SELECT;
+
+typedef struct _TS_COMMON_INFO{
+	struct list_head		List;
+	struct timer_list		SetupTimer;
+	struct timer_list		InactTimer;
+	u8				Addr[6];
+	TSPEC_BODY			TSpec;
+	QOS_TCLAS			TClass[TCLAS_NUM];
+	u8				TClasProc;
+	u8				TClasNum;
+} TS_COMMON_INFO, *PTS_COMMON_INFO;
+
+typedef struct _TX_TS_RECORD{
+	TS_COMMON_INFO		TsCommonInfo;
+	u16				TxCurSeq;
+	BA_RECORD			TxPendingBARecord;  	// For BA Originator
+	BA_RECORD			TxAdmittedBARecord;	// For BA Originator
+//	QOS_DL_RECORD		DLRecord;
+	u8				bAddBaReqInProgress;
+	u8				bAddBaReqDelayed;
+	u8				bUsingBa;
+	struct timer_list		TsAddBaTimer;
+	u8				num;
+} TX_TS_RECORD, *PTX_TS_RECORD;
+
+typedef struct _RX_TS_RECORD {
+	TS_COMMON_INFO		TsCommonInfo;
+	u16				RxIndicateSeq;
+	u16				RxTimeoutIndicateSeq;
+	struct list_head		RxPendingPktList;
+	struct timer_list		RxPktPendingTimer;
+	BA_RECORD			RxAdmittedBARecord;	 // For BA Recepient
+	u16				RxLastSeqNum;
+	u8				RxLastFragNum;
+	u8				num;
+//	QOS_DL_RECORD		DLRecord;
+} RX_TS_RECORD, *PRX_TS_RECORD;
+
+
+#endif
+
diff --git a/drivers/staging/rtl8192su/ieee80211/rtl819x_TSProc.c b/drivers/staging/rtl8192su/ieee80211/rtl819x_TSProc.c
new file mode 100644
index 0000000..6fb7033
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/rtl819x_TSProc.c
@@ -0,0 +1,667 @@
+#include "ieee80211.h"
+#include <linux/etherdevice.h>
+#include "rtl819x_TS.h"
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+#define list_for_each_entry_safe(pos, n, head, member) \
+	for (pos = list_entry((head)->next, typeof(*pos), member), \
+		n = list_entry(pos->member.next, typeof(*pos), member); \
+		&pos->member != (head); \
+		pos = n, n = list_entry(n->member.next, typeof(*n), member))
+#endif
+void TsSetupTimeOut(unsigned long data)
+{
+	// Not implement yet
+	// This is used for WMMSA and ACM , that would send ADDTSReq frame.
+}
+
+void TsInactTimeout(unsigned long data)
+{
+	// Not implement yet
+	// This is used for WMMSA and ACM.
+	// This function would be call when TS is no Tx/Rx for some period of time.
+}
+
+/********************************************************************************************************************
+ *function:  I still not understand this function, so wait for further implementation
+ *   input:  unsigned long	 data		//acturally we send TX_TS_RECORD or RX_TS_RECORD to these timer
+ *  return:  NULL
+ *  notice:
+********************************************************************************************************************/
+#if 1
+void RxPktPendingTimeout(unsigned long data)
+{
+	PRX_TS_RECORD	pRxTs = (PRX_TS_RECORD)data;
+	struct ieee80211_device *ieee = container_of(pRxTs, struct ieee80211_device, RxTsRecord[pRxTs->num]);
+
+	PRX_REORDER_ENTRY 	pReorderEntry = NULL;
+
+	//u32 flags = 0;
+	unsigned long flags = 0;
+	struct ieee80211_rxb *stats_IndicateArray[REORDER_WIN_SIZE];
+	u8 index = 0;
+	bool bPktInBuf = false;
+
+
+	spin_lock_irqsave(&(ieee->reorder_spinlock), flags);
+	//PlatformAcquireSpinLock(Adapter, RT_RX_SPINLOCK);
+	IEEE80211_DEBUG(IEEE80211_DL_REORDER,"==================>%s()\n",__FUNCTION__);
+	if(pRxTs->RxTimeoutIndicateSeq != 0xffff)
+	{
+		// Indicate the pending packets sequentially according to SeqNum until meet the gap.
+		while(!list_empty(&pRxTs->RxPendingPktList))
+		{
+			pReorderEntry = (PRX_REORDER_ENTRY)list_entry(pRxTs->RxPendingPktList.prev,RX_REORDER_ENTRY,List);
+			if(index == 0)
+				pRxTs->RxIndicateSeq = pReorderEntry->SeqNum;
+
+			if( SN_LESS(pReorderEntry->SeqNum, pRxTs->RxIndicateSeq) ||
+				SN_EQUAL(pReorderEntry->SeqNum, pRxTs->RxIndicateSeq)	)
+			{
+				list_del_init(&pReorderEntry->List);
+
+				if(SN_EQUAL(pReorderEntry->SeqNum, pRxTs->RxIndicateSeq))
+					pRxTs->RxIndicateSeq = (pRxTs->RxIndicateSeq + 1) % 4096;
+
+				IEEE80211_DEBUG(IEEE80211_DL_REORDER,"RxPktPendingTimeout(): IndicateSeq: %d\n", pReorderEntry->SeqNum);
+				stats_IndicateArray[index] = pReorderEntry->prxb;
+				index++;
+
+				list_add_tail(&pReorderEntry->List, &ieee->RxReorder_Unused_List);
+			}
+			else
+			{
+				bPktInBuf = true;
+				break;
+			}
+		}
+	}
+
+	if(index>0)
+	{
+		// Set RxTimeoutIndicateSeq to 0xffff to indicate no pending packets in buffer now.
+		pRxTs->RxTimeoutIndicateSeq = 0xffff;
+
+		// Indicate packets
+		if(index > REORDER_WIN_SIZE){
+			IEEE80211_DEBUG(IEEE80211_DL_ERR, "RxReorderIndicatePacket(): Rx Reorer buffer full!! \n");
+			spin_unlock_irqrestore(&(ieee->reorder_spinlock), flags);
+			return;
+		}
+		ieee80211_indicate_packets(ieee, stats_IndicateArray, index);
+		 bPktInBuf = false;
+
+	}
+
+	if(bPktInBuf && (pRxTs->RxTimeoutIndicateSeq==0xffff))
+	{
+		pRxTs->RxTimeoutIndicateSeq = pRxTs->RxIndicateSeq;
+#if 0
+		if(timer_pending(&pTS->RxPktPendingTimer))
+			del_timer_sync(&pTS->RxPktPendingTimer);
+		pTS->RxPktPendingTimer.expires = jiffies + MSECS(pHTInfo->RxReorderPendingTime);
+		add_timer(&pTS->RxPktPendingTimer);
+#else
+		mod_timer(&pRxTs->RxPktPendingTimer,  jiffies + MSECS(ieee->pHTInfo->RxReorderPendingTime));
+#endif
+
+#if 0
+		if(timer_pending(&pRxTs->RxPktPendingTimer))
+			del_timer_sync(&pRxTs->RxPktPendingTimer);
+		pRxTs->RxPktPendingTimer.expires = jiffies + ieee->pHTInfo->RxReorderPendingTime;
+		add_timer(&pRxTs->RxPktPendingTimer);
+#endif
+	}
+	spin_unlock_irqrestore(&(ieee->reorder_spinlock), flags);
+	//PlatformReleaseSpinLock(Adapter, RT_RX_SPINLOCK);
+}
+#endif
+
+/********************************************************************************************************************
+ *function:  Add BA timer function
+ *   input:  unsigned long	 data		//acturally we send TX_TS_RECORD or RX_TS_RECORD to these timer
+ *  return:  NULL
+ *  notice:
+********************************************************************************************************************/
+void TsAddBaProcess(unsigned long data)
+{
+	PTX_TS_RECORD	pTxTs = (PTX_TS_RECORD)data;
+	u8 num = pTxTs->num;
+	struct ieee80211_device *ieee = container_of(pTxTs, struct ieee80211_device, TxTsRecord[num]);
+
+	TsInitAddBA(ieee, pTxTs, BA_POLICY_IMMEDIATE, false);
+	IEEE80211_DEBUG(IEEE80211_DL_BA, "TsAddBaProcess(): ADDBA Req is started!! \n");
+}
+
+
+void ResetTsCommonInfo(PTS_COMMON_INFO	pTsCommonInfo)
+{
+	memset(pTsCommonInfo->Addr, 0, 6);
+	memset(&pTsCommonInfo->TSpec, 0, sizeof(TSPEC_BODY));
+	memset(&pTsCommonInfo->TClass, 0, sizeof(QOS_TCLAS)*TCLAS_NUM);
+	pTsCommonInfo->TClasProc = 0;
+	pTsCommonInfo->TClasNum = 0;
+}
+
+void ResetTxTsEntry(PTX_TS_RECORD pTS)
+{
+	ResetTsCommonInfo(&pTS->TsCommonInfo);
+	pTS->TxCurSeq = 0;
+	pTS->bAddBaReqInProgress = false;
+	pTS->bAddBaReqDelayed = false;
+	pTS->bUsingBa = false;
+	ResetBaEntry(&pTS->TxAdmittedBARecord); //For BA Originator
+	ResetBaEntry(&pTS->TxPendingBARecord);
+}
+
+void ResetRxTsEntry(PRX_TS_RECORD pTS)
+{
+	ResetTsCommonInfo(&pTS->TsCommonInfo);
+	pTS->RxIndicateSeq = 0xffff; // This indicate the RxIndicateSeq is not used now!!
+	pTS->RxTimeoutIndicateSeq = 0xffff; // This indicate the RxTimeoutIndicateSeq is not used now!!
+	ResetBaEntry(&pTS->RxAdmittedBARecord);	  // For BA Recepient
+}
+
+void TSInitialize(struct ieee80211_device *ieee)
+{
+	PTX_TS_RECORD		pTxTS  = ieee->TxTsRecord;
+	PRX_TS_RECORD		pRxTS  = ieee->RxTsRecord;
+	PRX_REORDER_ENTRY	pRxReorderEntry = ieee->RxReorderEntry;
+	u8				count = 0;
+	IEEE80211_DEBUG(IEEE80211_DL_TS, "==========>%s()\n", __FUNCTION__);
+	// Initialize Tx TS related info.
+	INIT_LIST_HEAD(&ieee->Tx_TS_Admit_List);
+	INIT_LIST_HEAD(&ieee->Tx_TS_Pending_List);
+	INIT_LIST_HEAD(&ieee->Tx_TS_Unused_List);
+
+	for(count = 0; count < TOTAL_TS_NUM; count++)
+	{
+		//
+		pTxTS->num = count;
+		// The timers for the operation of Traffic Stream and Block Ack.
+		// DLS related timer will be add here in the future!!
+		init_timer(&pTxTS->TsCommonInfo.SetupTimer);
+		pTxTS->TsCommonInfo.SetupTimer.data = (unsigned long)pTxTS;
+		pTxTS->TsCommonInfo.SetupTimer.function = TsSetupTimeOut;
+
+		init_timer(&pTxTS->TsCommonInfo.InactTimer);
+		pTxTS->TsCommonInfo.InactTimer.data = (unsigned long)pTxTS;
+		pTxTS->TsCommonInfo.InactTimer.function = TsInactTimeout;
+
+		init_timer(&pTxTS->TsAddBaTimer);
+		pTxTS->TsAddBaTimer.data = (unsigned long)pTxTS;
+		pTxTS->TsAddBaTimer.function = TsAddBaProcess;
+
+		init_timer(&pTxTS->TxPendingBARecord.Timer);
+		pTxTS->TxPendingBARecord.Timer.data = (unsigned long)pTxTS;
+		pTxTS->TxPendingBARecord.Timer.function = BaSetupTimeOut;
+
+		init_timer(&pTxTS->TxAdmittedBARecord.Timer);
+		pTxTS->TxAdmittedBARecord.Timer.data = (unsigned long)pTxTS;
+		pTxTS->TxAdmittedBARecord.Timer.function = TxBaInactTimeout;
+
+		ResetTxTsEntry(pTxTS);
+		list_add_tail(&pTxTS->TsCommonInfo.List, &ieee->Tx_TS_Unused_List);
+		pTxTS++;
+	}
+
+	// Initialize Rx TS related info.
+	INIT_LIST_HEAD(&ieee->Rx_TS_Admit_List);
+	INIT_LIST_HEAD(&ieee->Rx_TS_Pending_List);
+	INIT_LIST_HEAD(&ieee->Rx_TS_Unused_List);
+	for(count = 0; count < TOTAL_TS_NUM; count++)
+	{
+		pRxTS->num = count;
+		INIT_LIST_HEAD(&pRxTS->RxPendingPktList);
+
+		init_timer(&pRxTS->TsCommonInfo.SetupTimer);
+		pRxTS->TsCommonInfo.SetupTimer.data = (unsigned long)pRxTS;
+		pRxTS->TsCommonInfo.SetupTimer.function = TsSetupTimeOut;
+
+		init_timer(&pRxTS->TsCommonInfo.InactTimer);
+		pRxTS->TsCommonInfo.InactTimer.data = (unsigned long)pRxTS;
+		pRxTS->TsCommonInfo.InactTimer.function = TsInactTimeout;
+
+		init_timer(&pRxTS->RxAdmittedBARecord.Timer);
+		pRxTS->RxAdmittedBARecord.Timer.data = (unsigned long)pRxTS;
+		pRxTS->RxAdmittedBARecord.Timer.function = RxBaInactTimeout;
+
+		init_timer(&pRxTS->RxPktPendingTimer);
+		pRxTS->RxPktPendingTimer.data = (unsigned long)pRxTS;
+		pRxTS->RxPktPendingTimer.function = RxPktPendingTimeout;
+
+		ResetRxTsEntry(pRxTS);
+		list_add_tail(&pRxTS->TsCommonInfo.List, &ieee->Rx_TS_Unused_List);
+		pRxTS++;
+	}
+	// Initialize unused Rx Reorder List.
+	INIT_LIST_HEAD(&ieee->RxReorder_Unused_List);
+//#ifdef TO_DO_LIST
+	for(count = 0; count < REORDER_ENTRY_NUM; count++)
+	{
+		list_add_tail( &pRxReorderEntry->List,&ieee->RxReorder_Unused_List);
+		if(count == (REORDER_ENTRY_NUM-1))
+			break;
+		pRxReorderEntry = &ieee->RxReorderEntry[count+1];
+	}
+//#endif
+
+}
+
+void AdmitTS(struct ieee80211_device *ieee, PTS_COMMON_INFO pTsCommonInfo, u32 InactTime)
+{
+	del_timer_sync(&pTsCommonInfo->SetupTimer);
+	del_timer_sync(&pTsCommonInfo->InactTimer);
+
+	if(InactTime!=0)
+		mod_timer(&pTsCommonInfo->InactTimer, jiffies + MSECS(InactTime));
+}
+
+
+PTS_COMMON_INFO SearchAdmitTRStream(struct ieee80211_device *ieee, u8*	Addr, u8 TID, TR_SELECT	TxRxSelect)
+{
+	//DIRECTION_VALUE 	dir;
+	u8 	dir;
+	bool				search_dir[4] = {0, 0, 0, 0};
+	struct list_head*		psearch_list; //FIXME
+	PTS_COMMON_INFO	pRet = NULL;
+	if(ieee->iw_mode == IW_MODE_MASTER) //ap mode
+	{
+		if(TxRxSelect == TX_DIR)
+		{
+			search_dir[DIR_DOWN] = true;
+			search_dir[DIR_BI_DIR]= true;
+		}
+		else
+		{
+			search_dir[DIR_UP] 	= true;
+			search_dir[DIR_BI_DIR]= true;
+		}
+	}
+	else if(ieee->iw_mode == IW_MODE_ADHOC)
+	{
+		if(TxRxSelect == TX_DIR)
+			search_dir[DIR_UP] 	= true;
+		else
+			search_dir[DIR_DOWN] = true;
+	}
+	else
+	{
+		if(TxRxSelect == TX_DIR)
+		{
+			search_dir[DIR_UP] 	= true;
+			search_dir[DIR_BI_DIR]= true;
+			search_dir[DIR_DIRECT]= true;
+		}
+		else
+		{
+			search_dir[DIR_DOWN] = true;
+			search_dir[DIR_BI_DIR]= true;
+			search_dir[DIR_DIRECT]= true;
+		}
+	}
+
+	if(TxRxSelect == TX_DIR)
+		psearch_list = &ieee->Tx_TS_Admit_List;
+	else
+		psearch_list = &ieee->Rx_TS_Admit_List;
+
+	//for(dir = DIR_UP; dir <= DIR_BI_DIR; dir++)
+	for(dir = 0; dir <= DIR_BI_DIR; dir++)
+	{
+		if(search_dir[dir] ==false )
+			continue;
+		list_for_each_entry(pRet, psearch_list, List){
+	//		IEEE80211_DEBUG(IEEE80211_DL_TS, "ADD:"MAC_FMT", TID:%d, dir:%d\n", MAC_ARG(pRet->Addr), pRet->TSpec.f.TSInfo.field.ucTSID, pRet->TSpec.f.TSInfo.field.ucDirection);
+			if (memcmp(pRet->Addr, Addr, 6) == 0)
+				if (pRet->TSpec.f.TSInfo.field.ucTSID == TID)
+					if(pRet->TSpec.f.TSInfo.field.ucDirection == dir)
+					{
+	//					printk("Bingo! got it\n");
+						break;
+					}
+
+		}
+		if(&pRet->List  != psearch_list)
+			break;
+	}
+
+	if(&pRet->List  != psearch_list){
+		return pRet ;
+	}
+	else
+		return NULL;
+}
+
+void MakeTSEntry(
+		PTS_COMMON_INFO	pTsCommonInfo,
+		u8*		Addr,
+		PTSPEC_BODY	pTSPEC,
+		PQOS_TCLAS	pTCLAS,
+		u8		TCLAS_Num,
+		u8		TCLAS_Proc
+	)
+{
+	u8	count;
+
+	if(pTsCommonInfo == NULL)
+		return;
+
+	memcpy(pTsCommonInfo->Addr, Addr, 6);
+
+	if(pTSPEC != NULL)
+		memcpy((u8*)(&(pTsCommonInfo->TSpec)), (u8*)pTSPEC, sizeof(TSPEC_BODY));
+
+	for(count = 0; count < TCLAS_Num; count++)
+		memcpy((u8*)(&(pTsCommonInfo->TClass[count])), (u8*)pTCLAS, sizeof(QOS_TCLAS));
+
+	pTsCommonInfo->TClasProc = TCLAS_Proc;
+	pTsCommonInfo->TClasNum = TCLAS_Num;
+}
+
+
+bool GetTs(
+	struct ieee80211_device*	ieee,
+	PTS_COMMON_INFO			*ppTS,
+	u8*				Addr,
+	u8				TID,
+	TR_SELECT			TxRxSelect,  //Rx:1, Tx:0
+	bool				bAddNewTs
+	)
+{
+	u8	UP = 0;
+	//
+	// We do not build any TS for Broadcast or Multicast stream.
+	// So reject these kinds of search here.
+	//
+	if(is_broadcast_ether_addr(Addr) || is_multicast_ether_addr(Addr))
+	{
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "get TS for Broadcast or Multicast\n");
+		return false;
+	}
+#if 0
+	if(ieee->pStaQos->CurrentQosMode == QOS_DISABLE)
+	{	UP = 0; } //only use one TS
+	else if(ieee->pStaQos->CurrentQosMode & QOS_WMM)
+	{
+#else
+	if (ieee->current_network.qos_data.supported == 0)
+		UP = 0;
+	else
+	{
+#endif
+		// In WMM case: we use 4 TID only
+		if (!IsACValid(TID))
+		{
+			IEEE80211_DEBUG(IEEE80211_DL_ERR, " in %s(), TID(%d) is not valid\n", __FUNCTION__, TID);
+			return false;
+		}
+
+		switch(TID)
+		{
+		case 0:
+		case 3:
+			UP = 0;
+			break;
+
+		case 1:
+		case 2:
+			UP = 2;
+			break;
+
+		case 4:
+		case 5:
+			UP = 5;
+			break;
+
+		case 6:
+		case 7:
+			UP = 7;
+			break;
+		}
+	}
+
+	*ppTS = SearchAdmitTRStream(
+			ieee,
+			Addr,
+			UP,
+			TxRxSelect);
+	if(*ppTS != NULL)
+	{
+		return true;
+	}
+	else
+	{
+		if(bAddNewTs == false)
+		{
+			IEEE80211_DEBUG(IEEE80211_DL_TS, "add new TS failed(tid:%d)\n", UP);
+			return false;
+		}
+		else
+		{
+			//
+			// Create a new Traffic stream for current Tx/Rx
+			// This is for EDCA and WMM to add a new TS.
+			// For HCCA or WMMSA, TS cannot be addmit without negotiation.
+			//
+			TSPEC_BODY	TSpec;
+			PQOS_TSINFO		pTSInfo = &TSpec.f.TSInfo;
+			struct list_head*	pUnusedList =
+								(TxRxSelect == TX_DIR)?
+								(&ieee->Tx_TS_Unused_List):
+								(&ieee->Rx_TS_Unused_List);
+
+			struct list_head*	pAddmitList =
+								(TxRxSelect == TX_DIR)?
+								(&ieee->Tx_TS_Admit_List):
+								(&ieee->Rx_TS_Admit_List);
+
+			DIRECTION_VALUE		Dir =		(ieee->iw_mode == IW_MODE_MASTER)?
+								((TxRxSelect==TX_DIR)?DIR_DOWN:DIR_UP):
+								((TxRxSelect==TX_DIR)?DIR_UP:DIR_DOWN);
+			IEEE80211_DEBUG(IEEE80211_DL_TS, "to add Ts\n");
+			if(!list_empty(pUnusedList))
+			{
+				(*ppTS) = list_entry(pUnusedList->next, TS_COMMON_INFO, List);
+				list_del_init(&(*ppTS)->List);
+				if(TxRxSelect==TX_DIR)
+				{
+					PTX_TS_RECORD tmp = container_of(*ppTS, TX_TS_RECORD, TsCommonInfo);
+					ResetTxTsEntry(tmp);
+				}
+				else{
+					PRX_TS_RECORD tmp = container_of(*ppTS, RX_TS_RECORD, TsCommonInfo);
+					ResetRxTsEntry(tmp);
+				}
+
+				IEEE80211_DEBUG(IEEE80211_DL_TS, "to init current TS, UP:%d, Dir:%d, addr:"MAC_FMT"\n", UP, Dir, MAC_ARG(Addr));
+				// Prepare TS Info releated field
+				pTSInfo->field.ucTrafficType = 0;			// Traffic type: WMM is reserved in this field
+				pTSInfo->field.ucTSID = UP;			// TSID
+				pTSInfo->field.ucDirection = Dir;			// Direction: if there is DirectLink, this need additional consideration.
+				pTSInfo->field.ucAccessPolicy = 1;		// Access policy
+				pTSInfo->field.ucAggregation = 0; 		// Aggregation
+				pTSInfo->field.ucPSB = 0; 				// Aggregation
+				pTSInfo->field.ucUP = UP;				// User priority
+				pTSInfo->field.ucTSInfoAckPolicy = 0;		// Ack policy
+				pTSInfo->field.ucSchedule = 0;			// Schedule
+
+				MakeTSEntry(*ppTS, Addr, &TSpec, NULL, 0, 0);
+				AdmitTS(ieee, *ppTS, 0);
+				list_add_tail(&((*ppTS)->List), pAddmitList);
+				// if there is DirectLink, we need to do additional operation here!!
+
+				return true;
+			}
+			else
+			{
+				IEEE80211_DEBUG(IEEE80211_DL_ERR, "in function %s() There is not enough TS record to be used!!", __FUNCTION__);
+				return false;
+			}
+		}
+	}
+}
+
+void RemoveTsEntry(
+	struct ieee80211_device*	ieee,
+	PTS_COMMON_INFO			pTs,
+	TR_SELECT			TxRxSelect
+	)
+{
+	//u32 flags = 0;
+	unsigned long flags = 0;
+	del_timer_sync(&pTs->SetupTimer);
+	del_timer_sync(&pTs->InactTimer);
+	TsInitDelBA(ieee, pTs, TxRxSelect);
+
+	if(TxRxSelect == RX_DIR)
+	{
+//#ifdef TO_DO_LIST
+		PRX_REORDER_ENTRY	pRxReorderEntry;
+		PRX_TS_RECORD 		pRxTS = (PRX_TS_RECORD)pTs;
+		if(timer_pending(&pRxTS->RxPktPendingTimer))
+			del_timer_sync(&pRxTS->RxPktPendingTimer);
+
+                while(!list_empty(&pRxTS->RxPendingPktList))
+                {
+                //      PlatformAcquireSpinLock(Adapter, RT_RX_SPINLOCK);
+                        spin_lock_irqsave(&(ieee->reorder_spinlock), flags);
+                        //pRxReorderEntry = list_entry(&pRxTS->RxPendingPktList.prev,RX_REORDER_ENTRY,List);
+			pRxReorderEntry = (PRX_REORDER_ENTRY)list_entry(pRxTS->RxPendingPktList.prev,RX_REORDER_ENTRY,List);
+                        list_del_init(&pRxReorderEntry->List);
+                        {
+                                int i = 0;
+                                struct ieee80211_rxb * prxb = pRxReorderEntry->prxb;
+				if (unlikely(!prxb))
+				{
+					spin_unlock_irqrestore(&(ieee->reorder_spinlock), flags);
+					return;
+				}
+                                for(i =0; i < prxb->nr_subframes; i++) {
+                                        dev_kfree_skb(prxb->subframes[i]);
+                                }
+                                kfree(prxb);
+                                prxb = NULL;
+                        }
+                        list_add_tail(&pRxReorderEntry->List,&ieee->RxReorder_Unused_List);
+                        //PlatformReleaseSpinLock(Adapter, RT_RX_SPINLOCK);
+                        spin_unlock_irqrestore(&(ieee->reorder_spinlock), flags);
+                }
+
+//#endif
+	}
+	else
+	{
+		PTX_TS_RECORD pTxTS = (PTX_TS_RECORD)pTs;
+		del_timer_sync(&pTxTS->TsAddBaTimer);
+	}
+}
+
+void RemovePeerTS(struct ieee80211_device* ieee, u8* Addr)
+{
+	PTS_COMMON_INFO	pTS, pTmpTS;
+	printk("===========>RemovePeerTS,"MAC_FMT"\n", MAC_ARG(Addr));
+#if 1
+	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Tx_TS_Pending_List, List)
+	{
+		if (memcmp(pTS->Addr, Addr, 6) == 0)
+		{
+			RemoveTsEntry(ieee, pTS, TX_DIR);
+			list_del_init(&pTS->List);
+			list_add_tail(&pTS->List, &ieee->Tx_TS_Unused_List);
+		}
+	}
+
+	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Tx_TS_Admit_List, List)
+	{
+		if (memcmp(pTS->Addr, Addr, 6) == 0)
+		{
+			printk("====>remove Tx_TS_admin_list\n");
+			RemoveTsEntry(ieee, pTS, TX_DIR);
+			list_del_init(&pTS->List);
+			list_add_tail(&pTS->List, &ieee->Tx_TS_Unused_List);
+		}
+	}
+
+	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Rx_TS_Pending_List, List)
+	{
+		if (memcmp(pTS->Addr, Addr, 6) == 0)
+		{
+			RemoveTsEntry(ieee, pTS, RX_DIR);
+			list_del_init(&pTS->List);
+			list_add_tail(&pTS->List, &ieee->Rx_TS_Unused_List);
+		}
+	}
+
+	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Rx_TS_Admit_List, List)
+	{
+		if (memcmp(pTS->Addr, Addr, 6) == 0)
+		{
+			RemoveTsEntry(ieee, pTS, RX_DIR);
+			list_del_init(&pTS->List);
+			list_add_tail(&pTS->List, &ieee->Rx_TS_Unused_List);
+		}
+	}
+#endif
+}
+
+void RemoveAllTS(struct ieee80211_device* ieee)
+{
+	PTS_COMMON_INFO pTS, pTmpTS;
+#if 1
+	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Tx_TS_Pending_List, List)
+	{
+		RemoveTsEntry(ieee, pTS, TX_DIR);
+		list_del_init(&pTS->List);
+		list_add_tail(&pTS->List, &ieee->Tx_TS_Unused_List);
+	}
+
+	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Tx_TS_Admit_List, List)
+	{
+		RemoveTsEntry(ieee, pTS, TX_DIR);
+		list_del_init(&pTS->List);
+		list_add_tail(&pTS->List, &ieee->Tx_TS_Unused_List);
+	}
+
+	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Rx_TS_Pending_List, List)
+	{
+		RemoveTsEntry(ieee, pTS, RX_DIR);
+		list_del_init(&pTS->List);
+		list_add_tail(&pTS->List, &ieee->Rx_TS_Unused_List);
+	}
+
+	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Rx_TS_Admit_List, List)
+	{
+		RemoveTsEntry(ieee, pTS, RX_DIR);
+		list_del_init(&pTS->List);
+		list_add_tail(&pTS->List, &ieee->Rx_TS_Unused_List);
+	}
+#endif
+}
+
+void TsStartAddBaProcess(struct ieee80211_device* ieee, PTX_TS_RECORD	pTxTS)
+{
+	if(pTxTS->bAddBaReqInProgress == false)
+	{
+		pTxTS->bAddBaReqInProgress = true;
+#if 1
+		if(pTxTS->bAddBaReqDelayed)
+		{
+			IEEE80211_DEBUG(IEEE80211_DL_BA, "TsStartAddBaProcess(): Delayed Start ADDBA after 60 sec!!\n");
+			mod_timer(&pTxTS->TsAddBaTimer, jiffies + MSECS(TS_ADDBA_DELAY));
+		}
+		else
+		{
+			IEEE80211_DEBUG(IEEE80211_DL_BA,"TsStartAddBaProcess(): Immediately Start ADDBA now!!\n");
+			mod_timer(&pTxTS->TsAddBaTimer, jiffies+10); //set 10 ticks
+		}
+#endif
+	}
+	else
+		IEEE80211_DEBUG(IEEE80211_DL_ERR, "%s()==>BA timer is already added\n", __FUNCTION__);
+}
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+EXPORT_SYMBOL_NOVERS(RemovePeerTS);
+#else
+EXPORT_SYMBOL(RemovePeerTS);
+#endif
diff --git a/drivers/staging/rtl8192su/ieee80211/rtl_crypto.h b/drivers/staging/rtl8192su/ieee80211/rtl_crypto.h
new file mode 100644
index 0000000..ccf6ae7
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/rtl_crypto.h
@@ -0,0 +1,399 @@
+/*
+ * Scatterlist Cryptographic API.
+ *
+ * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
+ * Copyright (c) 2002 David S. Miller (davem@redhat.com)
+ *
+ * Portions derived from Cryptoapi, by Alexander Kjeldaas <astor@fast.no>
+ * and Nettle, by Niels M鰈ler.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ */
+#ifndef _LINUX_CRYPTO_H
+#define _LINUX_CRYPTO_H
+
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/types.h>
+#include <linux/list.h>
+#include <linux/string.h>
+#include <asm/page.h>
+#include <asm/errno.h>
+
+#define crypto_register_alg crypto_register_alg_rsl
+#define crypto_unregister_alg crypto_unregister_alg_rsl
+#define crypto_alloc_tfm crypto_alloc_tfm_rsl
+#define crypto_free_tfm crypto_free_tfm_rsl
+#define crypto_alg_available crypto_alg_available_rsl
+
+/*
+ * Algorithm masks and types.
+ */
+#define CRYPTO_ALG_TYPE_MASK		0x000000ff
+#define CRYPTO_ALG_TYPE_CIPHER		0x00000001
+#define CRYPTO_ALG_TYPE_DIGEST		0x00000002
+#define CRYPTO_ALG_TYPE_COMPRESS	0x00000004
+
+/*
+ * Transform masks and values (for crt_flags).
+ */
+#define CRYPTO_TFM_MODE_MASK		0x000000ff
+#define CRYPTO_TFM_REQ_MASK		0x000fff00
+#define CRYPTO_TFM_RES_MASK		0xfff00000
+
+#define CRYPTO_TFM_MODE_ECB		0x00000001
+#define CRYPTO_TFM_MODE_CBC		0x00000002
+#define CRYPTO_TFM_MODE_CFB		0x00000004
+#define CRYPTO_TFM_MODE_CTR		0x00000008
+
+#define CRYPTO_TFM_REQ_WEAK_KEY		0x00000100
+#define CRYPTO_TFM_RES_WEAK_KEY		0x00100000
+#define CRYPTO_TFM_RES_BAD_KEY_LEN   	0x00200000
+#define CRYPTO_TFM_RES_BAD_KEY_SCHED 	0x00400000
+#define CRYPTO_TFM_RES_BAD_BLOCK_LEN 	0x00800000
+#define CRYPTO_TFM_RES_BAD_FLAGS 	0x01000000
+
+/*
+ * Miscellaneous stuff.
+ */
+#define CRYPTO_UNSPEC			0
+#define CRYPTO_MAX_ALG_NAME		64
+
+struct scatterlist;
+
+/*
+ * Algorithms: modular crypto algorithm implementations, managed
+ * via crypto_register_alg() and crypto_unregister_alg().
+ */
+struct cipher_alg {
+	unsigned int cia_min_keysize;
+	unsigned int cia_max_keysize;
+	int (*cia_setkey)(void *ctx, const u8 *key,
+	                  unsigned int keylen, u32 *flags);
+	void (*cia_encrypt)(void *ctx, u8 *dst, const u8 *src);
+	void (*cia_decrypt)(void *ctx, u8 *dst, const u8 *src);
+};
+
+struct digest_alg {
+	unsigned int dia_digestsize;
+	void (*dia_init)(void *ctx);
+	void (*dia_update)(void *ctx, const u8 *data, unsigned int len);
+	void (*dia_final)(void *ctx, u8 *out);
+	int (*dia_setkey)(void *ctx, const u8 *key,
+	                  unsigned int keylen, u32 *flags);
+};
+
+struct compress_alg {
+	int (*coa_init)(void *ctx);
+	void (*coa_exit)(void *ctx);
+	int (*coa_compress)(void *ctx, const u8 *src, unsigned int slen,
+	                    u8 *dst, unsigned int *dlen);
+	int (*coa_decompress)(void *ctx, const u8 *src, unsigned int slen,
+	                      u8 *dst, unsigned int *dlen);
+};
+
+#define cra_cipher	cra_u.cipher
+#define cra_digest	cra_u.digest
+#define cra_compress	cra_u.compress
+
+struct crypto_alg {
+	struct list_head cra_list;
+	u32 cra_flags;
+	unsigned int cra_blocksize;
+	unsigned int cra_ctxsize;
+	const char cra_name[CRYPTO_MAX_ALG_NAME];
+
+	union {
+		struct cipher_alg cipher;
+		struct digest_alg digest;
+		struct compress_alg compress;
+	} cra_u;
+
+	struct module *cra_module;
+};
+
+/*
+ * Algorithm registration interface.
+ */
+int crypto_register_alg(struct crypto_alg *alg);
+int crypto_unregister_alg(struct crypto_alg *alg);
+
+/*
+ * Algorithm query interface.
+ */
+int crypto_alg_available(const char *name, u32 flags);
+
+/*
+ * Transforms: user-instantiated objects which encapsulate algorithms
+ * and core processing logic.  Managed via crypto_alloc_tfm() and
+ * crypto_free_tfm(), as well as the various helpers below.
+ */
+struct crypto_tfm;
+
+struct cipher_tfm {
+	void *cit_iv;
+	unsigned int cit_ivsize;
+	u32 cit_mode;
+	int (*cit_setkey)(struct crypto_tfm *tfm,
+	                  const u8 *key, unsigned int keylen);
+	int (*cit_encrypt)(struct crypto_tfm *tfm,
+			   struct scatterlist *dst,
+			   struct scatterlist *src,
+			   unsigned int nbytes);
+	int (*cit_encrypt_iv)(struct crypto_tfm *tfm,
+	                      struct scatterlist *dst,
+	                      struct scatterlist *src,
+	                      unsigned int nbytes, u8 *iv);
+	int (*cit_decrypt)(struct crypto_tfm *tfm,
+			   struct scatterlist *dst,
+			   struct scatterlist *src,
+			   unsigned int nbytes);
+	int (*cit_decrypt_iv)(struct crypto_tfm *tfm,
+			   struct scatterlist *dst,
+			   struct scatterlist *src,
+			   unsigned int nbytes, u8 *iv);
+	void (*cit_xor_block)(u8 *dst, const u8 *src);
+};
+
+struct digest_tfm {
+	void (*dit_init)(struct crypto_tfm *tfm);
+	void (*dit_update)(struct crypto_tfm *tfm,
+	                   struct scatterlist *sg, unsigned int nsg);
+	void (*dit_final)(struct crypto_tfm *tfm, u8 *out);
+	void (*dit_digest)(struct crypto_tfm *tfm, struct scatterlist *sg,
+	                   unsigned int nsg, u8 *out);
+	int (*dit_setkey)(struct crypto_tfm *tfm,
+	                  const u8 *key, unsigned int keylen);
+#ifdef CONFIG_CRYPTO_HMAC
+	void *dit_hmac_block;
+#endif
+};
+
+struct compress_tfm {
+	int (*cot_compress)(struct crypto_tfm *tfm,
+	                    const u8 *src, unsigned int slen,
+	                    u8 *dst, unsigned int *dlen);
+	int (*cot_decompress)(struct crypto_tfm *tfm,
+	                      const u8 *src, unsigned int slen,
+	                      u8 *dst, unsigned int *dlen);
+};
+
+#define crt_cipher	crt_u.cipher
+#define crt_digest	crt_u.digest
+#define crt_compress	crt_u.compress
+
+struct crypto_tfm {
+
+	u32 crt_flags;
+
+	union {
+		struct cipher_tfm cipher;
+		struct digest_tfm digest;
+		struct compress_tfm compress;
+	} crt_u;
+
+	struct crypto_alg *__crt_alg;
+};
+
+/*
+ * Transform user interface.
+ */
+
+/*
+ * crypto_alloc_tfm() will first attempt to locate an already loaded algorithm.
+ * If that fails and the kernel supports dynamically loadable modules, it
+ * will then attempt to load a module of the same name or alias.  A refcount
+ * is grabbed on the algorithm which is then associated with the new transform.
+ *
+ * crypto_free_tfm() frees up the transform and any associated resources,
+ * then drops the refcount on the associated algorithm.
+ */
+struct crypto_tfm *crypto_alloc_tfm(const char *alg_name, u32 tfm_flags);
+void crypto_free_tfm(struct crypto_tfm *tfm);
+
+/*
+ * Transform helpers which query the underlying algorithm.
+ */
+static inline const char *crypto_tfm_alg_name(struct crypto_tfm *tfm)
+{
+	return tfm->__crt_alg->cra_name;
+}
+
+static inline const char *crypto_tfm_alg_modname(struct crypto_tfm *tfm)
+{
+	struct crypto_alg *alg = tfm->__crt_alg;
+
+	if (alg->cra_module)
+		return alg->cra_module->name;
+	else
+		return NULL;
+}
+
+static inline u32 crypto_tfm_alg_type(struct crypto_tfm *tfm)
+{
+	return tfm->__crt_alg->cra_flags & CRYPTO_ALG_TYPE_MASK;
+}
+
+static inline unsigned int crypto_tfm_alg_min_keysize(struct crypto_tfm *tfm)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	return tfm->__crt_alg->cra_cipher.cia_min_keysize;
+}
+
+static inline unsigned int crypto_tfm_alg_max_keysize(struct crypto_tfm *tfm)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	return tfm->__crt_alg->cra_cipher.cia_max_keysize;
+}
+
+static inline unsigned int crypto_tfm_alg_ivsize(struct crypto_tfm *tfm)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	return tfm->crt_cipher.cit_ivsize;
+}
+
+static inline unsigned int crypto_tfm_alg_blocksize(struct crypto_tfm *tfm)
+{
+	return tfm->__crt_alg->cra_blocksize;
+}
+
+static inline unsigned int crypto_tfm_alg_digestsize(struct crypto_tfm *tfm)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_DIGEST);
+	return tfm->__crt_alg->cra_digest.dia_digestsize;
+}
+
+/*
+ * API wrappers.
+ */
+static inline void crypto_digest_init(struct crypto_tfm *tfm)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_DIGEST);
+	tfm->crt_digest.dit_init(tfm);
+}
+
+static inline void crypto_digest_update(struct crypto_tfm *tfm,
+                                        struct scatterlist *sg,
+                                        unsigned int nsg)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_DIGEST);
+	tfm->crt_digest.dit_update(tfm, sg, nsg);
+}
+
+static inline void crypto_digest_final(struct crypto_tfm *tfm, u8 *out)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_DIGEST);
+	tfm->crt_digest.dit_final(tfm, out);
+}
+
+static inline void crypto_digest_digest(struct crypto_tfm *tfm,
+                                        struct scatterlist *sg,
+                                        unsigned int nsg, u8 *out)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_DIGEST);
+	tfm->crt_digest.dit_digest(tfm, sg, nsg, out);
+}
+
+static inline int crypto_digest_setkey(struct crypto_tfm *tfm,
+                                       const u8 *key, unsigned int keylen)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_DIGEST);
+	if (tfm->crt_digest.dit_setkey == NULL)
+		return -ENOSYS;
+	return tfm->crt_digest.dit_setkey(tfm, key, keylen);
+}
+
+static inline int crypto_cipher_setkey(struct crypto_tfm *tfm,
+                                       const u8 *key, unsigned int keylen)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	return tfm->crt_cipher.cit_setkey(tfm, key, keylen);
+}
+
+static inline int crypto_cipher_encrypt(struct crypto_tfm *tfm,
+                                        struct scatterlist *dst,
+                                        struct scatterlist *src,
+                                        unsigned int nbytes)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	return tfm->crt_cipher.cit_encrypt(tfm, dst, src, nbytes);
+}
+
+static inline int crypto_cipher_encrypt_iv(struct crypto_tfm *tfm,
+                                           struct scatterlist *dst,
+                                           struct scatterlist *src,
+                                           unsigned int nbytes, u8 *iv)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	BUG_ON(tfm->crt_cipher.cit_mode == CRYPTO_TFM_MODE_ECB);
+	return tfm->crt_cipher.cit_encrypt_iv(tfm, dst, src, nbytes, iv);
+}
+
+static inline int crypto_cipher_decrypt(struct crypto_tfm *tfm,
+                                        struct scatterlist *dst,
+                                        struct scatterlist *src,
+                                        unsigned int nbytes)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	return tfm->crt_cipher.cit_decrypt(tfm, dst, src, nbytes);
+}
+
+static inline int crypto_cipher_decrypt_iv(struct crypto_tfm *tfm,
+                                           struct scatterlist *dst,
+                                           struct scatterlist *src,
+                                           unsigned int nbytes, u8 *iv)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	BUG_ON(tfm->crt_cipher.cit_mode == CRYPTO_TFM_MODE_ECB);
+	return tfm->crt_cipher.cit_decrypt_iv(tfm, dst, src, nbytes, iv);
+}
+
+static inline void crypto_cipher_set_iv(struct crypto_tfm *tfm,
+                                        const u8 *src, unsigned int len)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	memcpy(tfm->crt_cipher.cit_iv, src, len);
+}
+
+static inline void crypto_cipher_get_iv(struct crypto_tfm *tfm,
+                                        u8 *dst, unsigned int len)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_CIPHER);
+	memcpy(dst, tfm->crt_cipher.cit_iv, len);
+}
+
+static inline int crypto_comp_compress(struct crypto_tfm *tfm,
+                                       const u8 *src, unsigned int slen,
+                                       u8 *dst, unsigned int *dlen)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_COMPRESS);
+	return tfm->crt_compress.cot_compress(tfm, src, slen, dst, dlen);
+}
+
+static inline int crypto_comp_decompress(struct crypto_tfm *tfm,
+                                         const u8 *src, unsigned int slen,
+                                         u8 *dst, unsigned int *dlen)
+{
+	BUG_ON(crypto_tfm_alg_type(tfm) != CRYPTO_ALG_TYPE_COMPRESS);
+	return tfm->crt_compress.cot_decompress(tfm, src, slen, dst, dlen);
+}
+
+/*
+ * HMAC support.
+ */
+#ifdef CONFIG_CRYPTO_HMAC
+void crypto_hmac_init(struct crypto_tfm *tfm, u8 *key, unsigned int *keylen);
+void crypto_hmac_update(struct crypto_tfm *tfm,
+                        struct scatterlist *sg, unsigned int nsg);
+void crypto_hmac_final(struct crypto_tfm *tfm, u8 *key,
+                       unsigned int *keylen, u8 *out);
+void crypto_hmac(struct crypto_tfm *tfm, u8 *key, unsigned int *keylen,
+                 struct scatterlist *sg, unsigned int nsg, u8 *out);
+#endif	/* CONFIG_CRYPTO_HMAC */
+
+#endif	/* _LINUX_CRYPTO_H */
+
diff --git a/drivers/staging/rtl8192su/ieee80211/scatterwalk.c b/drivers/staging/rtl8192su/ieee80211/scatterwalk.c
new file mode 100644
index 0000000..49f401f
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/scatterwalk.c
@@ -0,0 +1,126 @@
+/*
+ * Cryptographic API.
+ *
+ * Cipher operations.
+ *
+ * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
+ *               2002 Adam J. Richter <adam@yggdrasil.com>
+ *               2004 Jean-Luc Cooke <jlcooke@certainkey.com>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ */
+#include "kmap_types.h"
+
+#include <linux/kernel.h>
+#include <linux/mm.h>
+#include <linux/pagemap.h>
+#include <linux/highmem.h>
+#include <asm/scatterlist.h>
+#include "internal.h"
+#include "scatterwalk.h"
+
+enum km_type crypto_km_types[] = {
+	KM_USER0,
+	KM_USER1,
+	KM_SOFTIRQ0,
+	KM_SOFTIRQ1,
+};
+
+void *scatterwalk_whichbuf(struct scatter_walk *walk, unsigned int nbytes, void *scratch)
+{
+	if (nbytes <= walk->len_this_page &&
+	    (((unsigned long)walk->data) & (PAGE_CACHE_SIZE - 1)) + nbytes <=
+	    PAGE_CACHE_SIZE)
+		return walk->data;
+	else
+		return scratch;
+}
+
+static void memcpy_dir(void *buf, void *sgdata, size_t nbytes, int out)
+{
+	if (out)
+		memcpy(sgdata, buf, nbytes);
+	else
+		memcpy(buf, sgdata, nbytes);
+}
+
+void scatterwalk_start(struct scatter_walk *walk, struct scatterlist *sg)
+{
+	unsigned int rest_of_page;
+
+	walk->sg = sg;
+
+	walk->page = sg->page;
+	walk->len_this_segment = sg->length;
+
+	rest_of_page = PAGE_CACHE_SIZE - (sg->offset & (PAGE_CACHE_SIZE - 1));
+	walk->len_this_page = min(sg->length, rest_of_page);
+	walk->offset = sg->offset;
+}
+
+void scatterwalk_map(struct scatter_walk *walk, int out)
+{
+	walk->data = crypto_kmap(walk->page, out) + walk->offset;
+}
+
+static void scatterwalk_pagedone(struct scatter_walk *walk, int out,
+				 unsigned int more)
+{
+	/* walk->data may be pointing the first byte of the next page;
+	   however, we know we transfered at least one byte.  So,
+	   walk->data - 1 will be a virtual address in the mapped page. */
+
+	if (out)
+		flush_dcache_page(walk->page);
+
+	if (more) {
+		walk->len_this_segment -= walk->len_this_page;
+
+		if (walk->len_this_segment) {
+			walk->page++;
+			walk->len_this_page = min(walk->len_this_segment,
+						  (unsigned)PAGE_CACHE_SIZE);
+			walk->offset = 0;
+		}
+		else
+			scatterwalk_start(walk, sg_next(walk->sg));
+	}
+}
+
+void scatterwalk_done(struct scatter_walk *walk, int out, int more)
+{
+	crypto_kunmap(walk->data, out);
+	if (walk->len_this_page == 0 || !more)
+		scatterwalk_pagedone(walk, out, more);
+}
+
+/*
+ * Do not call this unless the total length of all of the fragments
+ * has been verified as multiple of the block size.
+ */
+int scatterwalk_copychunks(void *buf, struct scatter_walk *walk,
+			   size_t nbytes, int out)
+{
+	if (buf != walk->data) {
+		while (nbytes > walk->len_this_page) {
+			memcpy_dir(buf, walk->data, walk->len_this_page, out);
+			buf += walk->len_this_page;
+			nbytes -= walk->len_this_page;
+
+			crypto_kunmap(walk->data, out);
+			scatterwalk_pagedone(walk, out, 1);
+			scatterwalk_map(walk, out);
+		}
+
+		memcpy_dir(buf, walk->data, nbytes, out);
+	}
+
+	walk->offset += nbytes;
+	walk->len_this_page -= nbytes;
+	walk->len_this_segment -= nbytes;
+	return 0;
+}
diff --git a/drivers/staging/rtl8192su/ieee80211/scatterwalk.h b/drivers/staging/rtl8192su/ieee80211/scatterwalk.h
new file mode 100644
index 0000000..b164465
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211/scatterwalk.h
@@ -0,0 +1,51 @@
+/*
+ * Cryptographic API.
+ *
+ * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
+ * Copyright (c) 2002 Adam J. Richter <adam@yggdrasil.com>
+ * Copyright (c) 2004 Jean-Luc Cooke <jlcooke@certainkey.com>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ *
+ */
+
+#ifndef _CRYPTO_SCATTERWALK_H
+#define _CRYPTO_SCATTERWALK_H
+#include <linux/mm.h>
+#include <asm/scatterlist.h>
+
+struct scatter_walk {
+	struct scatterlist	*sg;
+	struct page		*page;
+	void			*data;
+	unsigned int		len_this_page;
+	unsigned int		len_this_segment;
+	unsigned int		offset;
+};
+
+/* Define sg_next is an inline routine now in case we want to change
+   scatterlist to a linked list later. */
+static inline struct scatterlist *sg_next(struct scatterlist *sg)
+{
+	return sg + 1;
+}
+
+static inline int scatterwalk_samebuf(struct scatter_walk *walk_in,
+				      struct scatter_walk *walk_out,
+				      void *src_p, void *dst_p)
+{
+	return walk_in->page == walk_out->page &&
+	       walk_in->offset == walk_out->offset &&
+	       walk_in->data == src_p && walk_out->data == dst_p;
+}
+
+void *scatterwalk_whichbuf(struct scatter_walk *walk, unsigned int nbytes, void *scratch);
+void scatterwalk_start(struct scatter_walk *walk, struct scatterlist *sg);
+int scatterwalk_copychunks(void *buf, struct scatter_walk *walk, size_t nbytes, int out);
+void scatterwalk_map(struct scatter_walk *walk, int out);
+void scatterwalk_done(struct scatter_walk *walk, int out, int more);
+
+#endif  /* _CRYPTO_SCATTERWALK_H */
diff --git a/drivers/staging/rtl8192su/ieee80211_crypt.h b/drivers/staging/rtl8192su/ieee80211_crypt.h
new file mode 100644
index 0000000..b58a3bc
--- /dev/null
+++ b/drivers/staging/rtl8192su/ieee80211_crypt.h
@@ -0,0 +1,86 @@
+/*
+ * Original code based on Host AP (software wireless LAN access point) driver
+ * for Intersil Prism2/2.5/3.
+ *
+ * Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen
+ * <jkmaline@cc.hut.fi>
+ * Copyright (c) 2002-2003, Jouni Malinen <jkmaline@cc.hut.fi>
+ *
+ * Adaption to a generic IEEE 802.11 stack by James Ketrenos
+ * <jketreno@linux.intel.com>
+ *
+ * Copyright (c) 2004, Intel Corporation
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation. See README and COPYING for
+ * more details.
+ */
+
+/*
+ * This file defines the interface to the ieee80211 crypto module.
+ */
+#ifndef IEEE80211_CRYPT_H
+#define IEEE80211_CRYPT_H
+
+#include <linux/skbuff.h>
+
+struct ieee80211_crypto_ops {
+	const char *name;
+
+	/* init new crypto context (e.g., allocate private data space,
+	 * select IV, etc.); returns NULL on failure or pointer to allocated
+	 * private data on success */
+	void * (*init)(int keyidx);
+
+	/* deinitialize crypto context and free allocated private data */
+	void (*deinit)(void *priv);
+
+	/* encrypt/decrypt return < 0 on error or >= 0 on success. The return
+	 * value from decrypt_mpdu is passed as the keyidx value for
+	 * decrypt_msdu. skb must have enough head and tail room for the
+	 * encryption; if not, error will be returned; these functions are
+	 * called for all MPDUs (i.e., fragments).
+	 */
+	int (*encrypt_mpdu)(struct sk_buff *skb, int hdr_len, void *priv);
+	int (*decrypt_mpdu)(struct sk_buff *skb, int hdr_len, void *priv);
+
+	/* These functions are called for full MSDUs, i.e. full frames.
+	 * These can be NULL if full MSDU operations are not needed. */
+	int (*encrypt_msdu)(struct sk_buff *skb, int hdr_len, void *priv);
+	int (*decrypt_msdu)(struct sk_buff *skb, int keyidx, int hdr_len,
+			    void *priv);
+
+	int (*set_key)(void *key, int len, u8 *seq, void *priv);
+	int (*get_key)(void *key, int len, u8 *seq, void *priv);
+
+	/* procfs handler for printing out key information and possible
+	 * statistics */
+	char * (*print_stats)(char *p, void *priv);
+
+	/* maximum number of bytes added by encryption; encrypt buf is
+	 * allocated with extra_prefix_len bytes, copy of in_buf, and
+	 * extra_postfix_len; encrypt need not use all this space, but
+	 * the result must start at the beginning of the buffer and correct
+	 * length must be returned */
+	int extra_prefix_len, extra_postfix_len;
+
+	struct module *owner;
+};
+
+struct ieee80211_crypt_data {
+	struct list_head list; /* delayed deletion list */
+	struct ieee80211_crypto_ops *ops;
+	void *priv;
+	atomic_t refcnt;
+};
+
+int ieee80211_register_crypto_ops(struct ieee80211_crypto_ops *ops);
+int ieee80211_unregister_crypto_ops(struct ieee80211_crypto_ops *ops);
+struct ieee80211_crypto_ops * ieee80211_get_crypto_ops(const char *name);
+void ieee80211_crypt_deinit_entries(struct ieee80211_device *, int);
+void ieee80211_crypt_deinit_handler(unsigned long);
+void ieee80211_crypt_delayed_deinit(struct ieee80211_device *ieee,
+				    struct ieee80211_crypt_data **crypt);
+
+#endif
diff --git a/drivers/staging/rtl8192su/r8180_93cx6.c b/drivers/staging/rtl8192su/r8180_93cx6.c
new file mode 100644
index 0000000..8878cfe
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8180_93cx6.c
@@ -0,0 +1,146 @@
+/*
+   This files contains card eeprom (93c46 or 93c56) programming routines,
+   memory is addressed by 16 bits words.
+
+   This is part of rtl8180 OpenSource driver.
+   Copyright (C) Andrea Merello 2004  <andreamrl@tiscali.it>
+   Released under the terms of GPL (General Public Licence)
+
+   Parts of this driver are based on the GPL part of the
+   official realtek driver.
+
+   Parts of this driver are based on the rtl8180 driver skeleton
+   from Patric Schenke & Andres Salomon.
+
+   Parts of this driver are based on the Intel Pro Wireless 2100 GPL driver.
+
+   We want to tanks the Authors of those projects and the Ndiswrapper
+   project Authors.
+*/
+
+#include "r8180_93cx6.h"
+
+void eprom_cs(struct net_device *dev, short bit)
+{
+	if(bit)
+		write_nic_byte_E(dev, EPROM_CMD,
+			       (1<<EPROM_CS_SHIFT) | \
+			       read_nic_byte_E(dev, EPROM_CMD)); //enable EPROM
+	else
+		write_nic_byte_E(dev, EPROM_CMD, read_nic_byte_E(dev, EPROM_CMD)\
+			       &~(1<<EPROM_CS_SHIFT)); //disable EPROM
+
+	force_pci_posting(dev);
+	udelay(EPROM_DELAY);
+}
+
+
+void eprom_ck_cycle(struct net_device *dev)
+{
+	write_nic_byte_E(dev, EPROM_CMD,
+		       (1<<EPROM_CK_SHIFT) | read_nic_byte_E(dev,EPROM_CMD));
+	force_pci_posting(dev);
+	udelay(EPROM_DELAY);
+	write_nic_byte_E(dev, EPROM_CMD,
+		       read_nic_byte_E(dev, EPROM_CMD) &~ (1<<EPROM_CK_SHIFT));
+	force_pci_posting(dev);
+	udelay(EPROM_DELAY);
+}
+
+
+void eprom_w(struct net_device *dev,short bit)
+{
+	if(bit)
+		write_nic_byte_E(dev, EPROM_CMD, (1<<EPROM_W_SHIFT) | \
+			       read_nic_byte_E(dev,EPROM_CMD));
+	else
+		write_nic_byte_E(dev, EPROM_CMD, read_nic_byte_E(dev,EPROM_CMD)\
+			       &~(1<<EPROM_W_SHIFT));
+
+	force_pci_posting(dev);
+	udelay(EPROM_DELAY);
+}
+
+
+short eprom_r(struct net_device *dev)
+{
+	short bit;
+
+	bit=(read_nic_byte_E(dev, EPROM_CMD) & (1<<EPROM_R_SHIFT) );
+	udelay(EPROM_DELAY);
+
+	if(bit) return 1;
+	return 0;
+}
+
+
+void eprom_send_bits_string(struct net_device *dev, short b[], int len)
+{
+	int i;
+
+	for(i=0; i<len; i++){
+		eprom_w(dev, b[i]);
+		eprom_ck_cycle(dev);
+	}
+}
+
+
+u32 eprom_read(struct net_device *dev, u32 addr)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	short read_cmd[]={1,1,0};
+	short addr_str[8];
+	int i;
+	int addr_len;
+	u32 ret;
+
+	ret=0;
+        //enable EPROM programming
+	write_nic_byte_E(dev, EPROM_CMD,
+		       (EPROM_CMD_PROGRAM<<EPROM_CMD_OPERATING_MODE_SHIFT));
+	force_pci_posting(dev);
+	udelay(EPROM_DELAY);
+
+	if (priv->epromtype==EPROM_93c56){
+		addr_str[7]=addr & 1;
+		addr_str[6]=addr & (1<<1);
+		addr_str[5]=addr & (1<<2);
+		addr_str[4]=addr & (1<<3);
+		addr_str[3]=addr & (1<<4);
+		addr_str[2]=addr & (1<<5);
+		addr_str[1]=addr & (1<<6);
+		addr_str[0]=addr & (1<<7);
+		addr_len=8;
+	}else{
+		addr_str[5]=addr & 1;
+		addr_str[4]=addr & (1<<1);
+		addr_str[3]=addr & (1<<2);
+		addr_str[2]=addr & (1<<3);
+		addr_str[1]=addr & (1<<4);
+		addr_str[0]=addr & (1<<5);
+		addr_len=6;
+	}
+	eprom_cs(dev, 1);
+	eprom_ck_cycle(dev);
+	eprom_send_bits_string(dev, read_cmd, 3);
+	eprom_send_bits_string(dev, addr_str, addr_len);
+
+	//keep chip pin D to low state while reading.
+	//I'm unsure if it is necessary, but anyway shouldn't hurt
+	eprom_w(dev, 0);
+
+	for(i=0;i<16;i++){
+		//eeprom needs a clk cycle between writing opcode&adr
+		//and reading data. (eeprom outs a dummy 0)
+		eprom_ck_cycle(dev);
+		ret |= (eprom_r(dev)<<(15-i));
+	}
+
+	eprom_cs(dev, 0);
+	eprom_ck_cycle(dev);
+
+	//disable EPROM programming
+	write_nic_byte_E(dev, EPROM_CMD,
+		       (EPROM_CMD_NORMAL<<EPROM_CMD_OPERATING_MODE_SHIFT));
+	return ret;
+}
diff --git a/drivers/staging/rtl8192su/r8180_93cx6.h b/drivers/staging/rtl8192su/r8180_93cx6.h
new file mode 100644
index 0000000..ca228d3
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8180_93cx6.h
@@ -0,0 +1,45 @@
+/*
+	This is part of rtl8187 OpenSource driver
+	Copyright (C) Andrea Merello 2004-2005  <andreamrl@tiscali.it>
+	Released under the terms of GPL (General Public Licence)
+
+	Parts of this driver are based on the GPL part of the official realtek driver
+	Parts of this driver are based on the rtl8180 driver skeleton from Patric Schenke & Andres Salomon
+	Parts of this driver are based on the Intel Pro Wireless 2100 GPL driver
+
+	We want to tanks the Authors of such projects and the Ndiswrapper project Authors.
+*/
+
+/*This files contains card eeprom (93c46 or 93c56) programming routines*/
+/*memory is addressed by WORDS*/
+
+#ifdef RTL8192SU
+#include "r8192U.h"
+#include "r8192S_hw.h"
+#else
+#include "r8192U.h"
+#include "r8192U_hw.h"
+#endif
+
+#define EPROM_DELAY 10
+
+#define EPROM_ANAPARAM_ADDRLWORD 0xd
+#define EPROM_ANAPARAM_ADDRHWORD 0xe
+
+#define EPROM_RFCHIPID 0x6
+#define EPROM_TXPW_BASE 0x05
+#define EPROM_RFCHIPID_RTL8225U 5
+#define EPROM_RF_PARAM 0x4
+#define EPROM_CONFIG2 0xc
+
+#define EPROM_VERSION 0x1E
+#define MAC_ADR 0x7
+
+#define CIS 0x18
+
+#define EPROM_TXPW0 0x16
+#define EPROM_TXPW2 0x1b
+#define EPROM_TXPW1 0x3d
+
+
+u32 eprom_read(struct net_device *dev,u32 addr); //reads a 16 bits word
diff --git a/drivers/staging/rtl8192su/r8190_rtl8256.c b/drivers/staging/rtl8192su/r8190_rtl8256.c
new file mode 100644
index 0000000..74ff337
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8190_rtl8256.c
@@ -0,0 +1,312 @@
+/*
+  This is part of the rtl8192 driver
+  released under the GPL (See file COPYING for details).
+
+  This files contains programming code for the rtl8256
+  radio frontend.
+
+  *Many* thanks to Realtek Corp. for their great support!
+
+*/
+
+#include "r8192U.h"
+#include "r8192U_hw.h"
+#include "r819xU_phyreg.h"
+#include "r819xU_phy.h"
+#include "r8190_rtl8256.h"
+
+/*--------------------------------------------------------------------------
+ * Overview:   	set RF band width (20M or 40M)
+ * Input:       struct net_device*	dev
+ * 		WIRELESS_BANDWIDTH_E	Bandwidth	//20M or 40M
+ * Output:      NONE
+ * Return:      NONE
+ * Note:	8226 support both 20M  and 40 MHz
+ *---------------------------------------------------------------------------*/
+void PHY_SetRF8256Bandwidth(struct net_device* dev , HT_CHANNEL_WIDTH Bandwidth)	//20M or 40M
+{
+	u8	eRFPath;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	//for(eRFPath = RF90_PATH_A; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
+	for(eRFPath = 0; eRFPath <RF90_PATH_MAX; eRFPath++)
+	{
+		if (!rtl8192_phy_CheckIsLegalRFPath(dev, eRFPath))
+				continue;
+
+		switch(Bandwidth)
+		{
+			case HT_CHANNEL_WIDTH_20:
+				if(priv->card_8192_version == VERSION_819xU_A || priv->card_8192_version == VERSION_819xU_B)// 8256 D-cut, E-cut, xiong: consider it later!
+				{
+					rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x0b, bMask12Bits, 0x100); //phy para:1ba
+					rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x2c, bMask12Bits, 0x3d7);
+					rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x0e, bMask12Bits, 0x021);
+
+					//cosa add for sd3's request 01/23/2008
+					rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x14, bMask12Bits, 0x5ab);
+				}
+				else
+				{
+					RT_TRACE(COMP_ERR, "PHY_SetRF8256Bandwidth(): unknown hardware version\n");
+				}
+
+				break;
+			case HT_CHANNEL_WIDTH_20_40:
+				if(priv->card_8192_version == VERSION_819xU_A ||priv->card_8192_version == VERSION_819xU_B)// 8256 D-cut, E-cut, xiong: consider it later!
+				{
+					rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x0b, bMask12Bits, 0x300); //phy para:3ba
+					rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x2c, bMask12Bits, 0x3df);
+					rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x0e, bMask12Bits, 0x0a1);
+
+					//cosa add for sd3's request 01/23/2008
+					if(priv->chan == 3 || priv->chan == 9) //I need to set priv->chan whenever current channel changes
+						rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x14, bMask12Bits, 0x59b);
+					else
+						rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x14, bMask12Bits, 0x5ab);
+				}
+				else
+				{
+					RT_TRACE(COMP_ERR, "PHY_SetRF8256Bandwidth(): unknown hardware version\n");
+				}
+
+
+				break;
+			default:
+				RT_TRACE(COMP_ERR, "PHY_SetRF8256Bandwidth(): unknown Bandwidth: %#X\n",Bandwidth );
+				break;
+
+		}
+	}
+	return;
+}
+/*--------------------------------------------------------------------------
+ * Overview:    Interface to config 8256
+ * Input:       struct net_device*	dev
+ * Output:      NONE
+ * Return:      NONE
+ *---------------------------------------------------------------------------*/
+void PHY_RF8256_Config(struct net_device* dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	// Initialize general global value
+	//
+	// TODO: Extend RF_PATH_C and RF_PATH_D in the future
+	priv->NumTotalRFPath = RTL819X_TOTAL_RF_PATH;
+	// Config BB and RF
+	phy_RF8256_Config_ParaFile(dev);
+
+	return;
+}
+/*--------------------------------------------------------------------------
+ * Overview:    Interface to config 8256
+ * Input:       struct net_device*	dev
+ * Output:      NONE
+ * Return:      NONE
+ *---------------------------------------------------------------------------*/
+void phy_RF8256_Config_ParaFile(struct net_device* dev)
+{
+	u32 	u4RegValue = 0;
+	//static s1Byte				szRadioAFile[] = RTL819X_PHY_RADIO_A;
+	//static s1Byte				szRadioBFile[] = RTL819X_PHY_RADIO_B;
+	//static s1Byte				szRadioCFile[] = RTL819X_PHY_RADIO_C;
+	//static s1Byte				szRadioDFile[] = RTL819X_PHY_RADIO_D;
+	u8 	eRFPath;
+	BB_REGISTER_DEFINITION_T	*pPhyReg;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32	RegOffSetToBeCheck = 0x3;
+	u32 	RegValueToBeCheck = 0x7f1;
+	u32	RF3_Final_Value = 0;
+	u8	ConstRetryTimes = 5, RetryTimes = 5;
+	u8 ret = 0;
+	//3//-----------------------------------------------------------------
+	//3// <2> Initialize RF
+	//3//-----------------------------------------------------------------
+	for(eRFPath = (RF90_RADIO_PATH_E)RF90_PATH_A; eRFPath <priv->NumTotalRFPath; eRFPath++)
+	{
+		if (!rtl8192_phy_CheckIsLegalRFPath(dev, eRFPath))
+				continue;
+
+		pPhyReg = &priv->PHYRegDef[eRFPath];
+
+		// Joseph test for shorten RF config
+	//	pHalData->RfReg0Value[eRFPath] =  rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, rGlobalCtrl, bMaskDWord);
+
+		/*----Store original RFENV control type----*/
+		switch(eRFPath)
+		{
+		case RF90_PATH_A:
+		case RF90_PATH_C:
+			u4RegValue = rtl8192_QueryBBReg(dev, pPhyReg->rfintfs, bRFSI_RFENV);
+			break;
+		case RF90_PATH_B :
+		case RF90_PATH_D:
+			u4RegValue = rtl8192_QueryBBReg(dev, pPhyReg->rfintfs, bRFSI_RFENV<<16);
+			break;
+		}
+
+		/*----Set RF_ENV enable----*/
+		rtl8192_setBBreg(dev, pPhyReg->rfintfe, bRFSI_RFENV<<16, 0x1);
+
+		/*----Set RF_ENV output high----*/
+		rtl8192_setBBreg(dev, pPhyReg->rfintfo, bRFSI_RFENV, 0x1);
+
+		/* Set bit number of Address and Data for RF register */
+		rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2, b3WireAddressLength, 0x0); 	// Set 0 to 4 bits for Z-serial and set 1 to 6 bits for 8258
+		rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2, b3WireDataLength, 0x0);	// Set 0 to 12 bits for Z-serial and 8258, and set 1 to 14 bits for ???
+
+		rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E) eRFPath, 0x0, bMask12Bits, 0xbf);
+
+		/*----Check RF block (for FPGA platform only)----*/
+		// TODO: this function should be removed on ASIC , Emily 2007.2.2
+		if (rtl8192_phy_checkBBAndRF(dev, HW90_BLOCK_RF, (RF90_RADIO_PATH_E)eRFPath))
+		{
+			RT_TRACE(COMP_ERR, "PHY_RF8256_Config():Check Radio[%d] Fail!!\n", eRFPath);
+			goto phy_RF8256_Config_ParaFile_Fail;
+		}
+
+		RetryTimes = ConstRetryTimes;
+		RF3_Final_Value = 0;
+		/*----Initialize RF fom connfiguration file----*/
+		switch(eRFPath)
+		{
+		case RF90_PATH_A:
+			while(RF3_Final_Value!=RegValueToBeCheck && RetryTimes!=0)
+			{
+				ret = rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
+				RF3_Final_Value = rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, RegOffSetToBeCheck, bMask12Bits);
+				RT_TRACE(COMP_RF, "RF %d %d register final value: %x\n", eRFPath, RegOffSetToBeCheck, RF3_Final_Value);
+				RetryTimes--;
+			}
+			break;
+		case RF90_PATH_B:
+			while(RF3_Final_Value!=RegValueToBeCheck && RetryTimes!=0)
+			{
+				ret = rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
+				RF3_Final_Value = rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, RegOffSetToBeCheck, bMask12Bits);
+				RT_TRACE(COMP_RF, "RF %d %d register final value: %x\n", eRFPath, RegOffSetToBeCheck, RF3_Final_Value);
+				RetryTimes--;
+			}
+			break;
+		case RF90_PATH_C:
+			while(RF3_Final_Value!=RegValueToBeCheck && RetryTimes!=0)
+			{
+				ret = rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
+				RF3_Final_Value = rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, RegOffSetToBeCheck, bMask12Bits);
+				RT_TRACE(COMP_RF, "RF %d %d register final value: %x\n", eRFPath, RegOffSetToBeCheck, RF3_Final_Value);
+				RetryTimes--;
+			}
+			break;
+		case RF90_PATH_D:
+			while(RF3_Final_Value!=RegValueToBeCheck && RetryTimes!=0)
+			{
+				ret = rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
+				RF3_Final_Value = rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, RegOffSetToBeCheck, bMask12Bits);
+				RT_TRACE(COMP_RF, "RF %d %d register final value: %x\n", eRFPath, RegOffSetToBeCheck, RF3_Final_Value);
+				RetryTimes--;
+			}
+			break;
+		}
+
+		/*----Restore RFENV control type----*/;
+		switch(eRFPath)
+		{
+		case RF90_PATH_A:
+		case RF90_PATH_C:
+			rtl8192_setBBreg(dev, pPhyReg->rfintfs, bRFSI_RFENV, u4RegValue);
+			break;
+		case RF90_PATH_B :
+		case RF90_PATH_D:
+			rtl8192_setBBreg(dev, pPhyReg->rfintfs, bRFSI_RFENV<<16, u4RegValue);
+			break;
+		}
+
+		if(ret){
+			RT_TRACE(COMP_ERR, "phy_RF8256_Config_ParaFile():Radio[%d] Fail!!", eRFPath);
+			goto phy_RF8256_Config_ParaFile_Fail;
+		}
+
+	}
+
+	RT_TRACE(COMP_PHY, "PHY Initialization Success\n") ;
+	return ;
+
+phy_RF8256_Config_ParaFile_Fail:
+	RT_TRACE(COMP_ERR, "PHY Initialization failed\n") ;
+	return ;
+}
+
+
+void PHY_SetRF8256CCKTxPower(struct net_device*	dev, u8	powerlevel)
+{
+	u32	TxAGC=0;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//modified by vivi, 20080109
+	TxAGC = powerlevel;
+
+	if(priv->bDynamicTxLowPower == TRUE ) //cosa 05/22/2008 for scan
+	{
+		if(priv->CustomerID == RT_CID_819x_Netcore)
+			TxAGC = 0x22;
+		else
+		TxAGC += priv->CckPwEnl;
+	}
+
+	if(TxAGC > 0x24)
+		TxAGC = 0x24;
+	rtl8192_setBBreg(dev, rTxAGC_CCK_Mcs32, bTxAGCRateCCK, TxAGC);
+}
+
+
+void PHY_SetRF8256OFDMTxPower(struct net_device* dev, u8 powerlevel)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//Joseph TxPower for 8192 testing
+	u32 writeVal, powerBase0, powerBase1, writeVal_tmp;
+	u8 index = 0;
+	u16 RegOffset[6] = {0xe00, 0xe04, 0xe10, 0xe14, 0xe18, 0xe1c};
+	u8 byte0, byte1, byte2, byte3;
+
+	powerBase0 = powerlevel + priv->TxPowerDiff;	//OFDM rates
+	powerBase0 = (powerBase0<<24) | (powerBase0<<16) |(powerBase0<<8) |powerBase0;
+	powerBase1 = powerlevel;							//MCS rates
+	powerBase1 = (powerBase1<<24) | (powerBase1<<16) |(powerBase1<<8) |powerBase1;
+
+	for(index=0; index<6; index++)
+	{
+		writeVal = priv->MCSTxPowerLevelOriginalOffset[index] + ((index<2)?powerBase0:powerBase1);
+		byte0 = (u8)(writeVal & 0x7f);
+		byte1 = (u8)((writeVal & 0x7f00)>>8);
+		byte2 = (u8)((writeVal & 0x7f0000)>>16);
+		byte3 = (u8)((writeVal & 0x7f000000)>>24);
+		if(byte0 > 0x24)	// Max power index = 0x24
+			byte0 = 0x24;
+		if(byte1 > 0x24)
+			byte1 = 0x24;
+		if(byte2 > 0x24)
+			byte2 = 0x24;
+		if(byte3 > 0x24)
+			byte3 = 0x24;
+
+		//for tx power track
+		if(index == 3)
+		{
+			writeVal_tmp = (byte3<<24) | (byte2<<16) |(byte1<<8) |byte0;
+			priv->Pwr_Track = writeVal_tmp;
+		}
+
+		if(priv->bDynamicTxHighPower == TRUE)     //Add by Jacken 2008/03/06
+		{
+			// Emily, 20080613. Set low tx power for both MCS and legacy OFDM
+			writeVal = 0x03030303;
+		}
+		else
+		{
+			writeVal = (byte3<<24) | (byte2<<16) |(byte1<<8) |byte0;
+		}
+		rtl8192_setBBreg(dev, RegOffset[index], 0x7f7f7f7f, writeVal);
+	}
+	return;
+
+}
+
diff --git a/drivers/staging/rtl8192su/r8190_rtl8256.h b/drivers/staging/rtl8192su/r8190_rtl8256.h
new file mode 100644
index 0000000..5c1f650
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8190_rtl8256.h
@@ -0,0 +1,27 @@
+/*
+  This is part of the rtl8180-sa2400 driver
+  released under the GPL (See file COPYING for details).
+  Copyright (c) 2005 Andrea Merello <andreamrl@tiscali.it>
+
+  This files contains programming code for the rtl8256
+  radio frontend.
+
+  *Many* thanks to Realtek Corp. for their great support!
+
+*/
+
+#ifndef RTL8225H
+#define RTL8225H
+
+#ifdef RTL8190P
+#define RTL819X_TOTAL_RF_PATH 4 //for 90P
+#else
+#define RTL819X_TOTAL_RF_PATH 2 //for 8192U
+#endif
+extern void PHY_SetRF8256Bandwidth(struct net_device* dev , HT_CHANNEL_WIDTH Bandwidth);
+extern void PHY_RF8256_Config(struct net_device* dev);
+extern void phy_RF8256_Config_ParaFile(struct net_device* dev);
+extern void PHY_SetRF8256CCKTxPower(struct net_device*	dev, u8	powerlevel);
+extern void PHY_SetRF8256OFDMTxPower(struct net_device* dev, u8 powerlevel);
+
+#endif
diff --git a/drivers/staging/rtl8192su/r8192SU_HWImg.c b/drivers/staging/rtl8192su/r8192SU_HWImg.c
new file mode 100644
index 0000000..cbb6579
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192SU_HWImg.c
@@ -0,0 +1,4902 @@
+/*Created on  2009/ 1/15,  3:10*/
+
+#include "r8192SU_HWImg.h"
+
+u8 Rtl8192SUFwImgArray[ImgArrayLength] = {
+0x92,0x81,0x2b,0x90,0x30,0x00,0x00,0x00,0x08,0x74,0x00,0x00,0x88,0x96,0x00,0x00,
+0x30,0x00,0x00,0x00,0x00,0x95,0x00,0x00,0x00,0x00,0x2b,0x00,0x03,0x03,0x23,0x00,
+0x92,0x81,0x02,0x01,0x00,0x00,0x12,0x04,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x01,0x01,0x01,0x00,0x00,
+0x00,0x01,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x7f,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x1f,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x25,0xb0,0x1a,0x3c,0x80,0x03,0x5a,0x37,0x00,0x80,0x1b,0x3c,0x80,0x00,0x7b,0x37,
+0x00,0x00,0x5b,0xaf,0x25,0xb0,0x1a,0x3c,0x18,0x03,0x5a,0x37,0x00,0x80,0x1b,0x3c,
+0x80,0x00,0x7b,0x37,0x00,0x00,0x5b,0xaf,0x00,0x80,0x1a,0x3c,0x10,0x6d,0x5a,0x27,
+0x08,0x00,0x40,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x04,0x00,0xa1,0xaf,0x08,0x00,0xa2,0xaf,0x0c,0x00,0xa3,0xaf,0x10,0x00,0xa4,0xaf,
+0x14,0x00,0xa5,0xaf,0x18,0x00,0xa6,0xaf,0x1c,0x00,0xa7,0xaf,0x20,0x00,0xa8,0xaf,
+0x24,0x00,0xa9,0xaf,0x28,0x00,0xaa,0xaf,0x2c,0x00,0xab,0xaf,0x30,0x00,0xac,0xaf,
+0x34,0x00,0xad,0xaf,0x38,0x00,0xae,0xaf,0x3c,0x00,0xaf,0xaf,0x12,0x40,0x00,0x00,
+0x10,0x48,0x00,0x00,0x00,0x70,0x0a,0x40,0x40,0x00,0xb0,0xaf,0x44,0x00,0xb1,0xaf,
+0x48,0x00,0xb2,0xaf,0x4c,0x00,0xb3,0xaf,0x50,0x00,0xb4,0xaf,0x54,0x00,0xb5,0xaf,
+0x58,0x00,0xb6,0xaf,0x5c,0x00,0xb7,0xaf,0x60,0x00,0xb8,0xaf,0x64,0x00,0xb9,0xaf,
+0x68,0x00,0xbc,0xaf,0x6c,0x00,0xbd,0xaf,0x70,0x00,0xbe,0xaf,0x74,0x00,0xbf,0xaf,
+0x78,0x00,0xa8,0xaf,0x7c,0x00,0xa9,0xaf,0x80,0x00,0xaa,0xaf,0xdf,0x1a,0x00,0x08,
+0x21,0x20,0xa0,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x25,0xb0,0x06,0x3c,0x00,0x80,0x02,0x3c,0xe8,0xff,0xbd,0x27,0x18,0x03,0xc3,0x34,
+0x00,0x03,0x42,0x24,0x14,0x00,0xbf,0xaf,0x10,0x00,0xb0,0xaf,0x00,0x00,0x62,0xac,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0x42,0xb0,0x03,0x3c,
+0x03,0x00,0x63,0x34,0x00,0x00,0x62,0x90,0x02,0x80,0x0a,0x3c,0x02,0x80,0x10,0x3c,
+0xff,0x00,0x42,0x30,0x00,0x46,0x02,0x00,0x10,0x00,0x42,0x30,0x13,0x00,0x40,0x10,
+0x03,0x46,0x08,0x00,0xc4,0x7d,0x42,0x8d,0x68,0x15,0x05,0x26,0xd4,0x63,0xa4,0x94,
+0x01,0x00,0x47,0x24,0x10,0x00,0x02,0x24,0xb0,0x03,0xc9,0x34,0x00,0x00,0x62,0xa0,
+0x07,0x00,0x80,0x10,0x1c,0x03,0xc6,0x34,0xd8,0x63,0xa2,0x8c,0xd4,0x63,0xa0,0xa4,
+0xd8,0x63,0xa0,0xac,0x00,0x00,0x04,0x24,0x00,0x00,0xc2,0xac,0x00,0x00,0x20,0xad,
+0x01,0x00,0x82,0x24,0xc4,0x7d,0x47,0xad,0xd4,0x63,0xa2,0xa4,0x12,0x00,0x00,0x05,
+0x42,0xb0,0x02,0x3c,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,
+0x00,0x60,0x81,0x40,0x68,0x15,0x04,0x26,0x0c,0x4b,0x83,0x94,0x08,0x4b,0x85,0x94,
+0x14,0x00,0xbf,0x8f,0x10,0x00,0xb0,0x8f,0x80,0x00,0x63,0x30,0x41,0xb0,0x02,0x3c,
+0x25,0x18,0x65,0x00,0x08,0x00,0x42,0x34,0x18,0x00,0xbd,0x27,0x00,0x00,0x43,0xa4,
+0x08,0x00,0xe0,0x03,0x08,0x4b,0x83,0xa4,0x80,0xff,0x03,0x24,0x03,0x00,0x42,0x34,
+0x00,0x00,0x43,0xa0,0xc8,0x0e,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x68,0x15,0x04,0x26,
+0x0c,0x4b,0x83,0x94,0x08,0x4b,0x85,0x94,0x14,0x00,0xbf,0x8f,0x10,0x00,0xb0,0x8f,
+0x80,0x00,0x63,0x30,0x41,0xb0,0x02,0x3c,0x25,0x18,0x65,0x00,0x08,0x00,0x42,0x34,
+0x18,0x00,0xbd,0x27,0x00,0x00,0x43,0xa4,0x08,0x00,0xe0,0x03,0x08,0x4b,0x83,0xa4,
+0xff,0x00,0x84,0x30,0x0b,0x00,0x82,0x2c,0xff,0xff,0xe7,0x30,0x10,0x00,0xa8,0x93,
+0x19,0x00,0x40,0x10,0x21,0x18,0x00,0x00,0x02,0x80,0x03,0x3c,0x80,0x10,0x04,0x00,
+0xc0,0x91,0x63,0x24,0x21,0x10,0x43,0x00,0x00,0x00,0x44,0x8c,0x00,0x00,0x00,0x00,
+0x08,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x43,0xb0,0x02,0x3c,0x78,0x00,0x44,0x34,
+0x07,0x00,0xe2,0x30,0x00,0x00,0x85,0xac,0x04,0x00,0x86,0xac,0x04,0x00,0x40,0x18,
+0x00,0x00,0x00,0x00,0xf8,0xff,0xe2,0x30,0x08,0x00,0x42,0x24,0xff,0xff,0x47,0x30,
+0x21,0x10,0xe8,0x00,0x00,0x80,0x03,0x3c,0x08,0x00,0x82,0xac,0x25,0x10,0x43,0x00,
+0x08,0x00,0x82,0xac,0x01,0x00,0x03,0x24,0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,
+0x43,0xb0,0x02,0x3c,0x20,0x01,0x00,0x08,0x6c,0x00,0x44,0x34,0x43,0xb0,0x02,0x3c,
+0x20,0x01,0x00,0x08,0x60,0x00,0x44,0x34,0x43,0xb0,0x02,0x3c,0x20,0x01,0x00,0x08,
+0x54,0x00,0x44,0x34,0x43,0xb0,0x02,0x3c,0x20,0x01,0x00,0x08,0x48,0x00,0x44,0x34,
+0x43,0xb0,0x02,0x3c,0x20,0x01,0x00,0x08,0x3c,0x00,0x44,0x34,0x43,0xb0,0x02,0x3c,
+0x20,0x01,0x00,0x08,0x30,0x00,0x44,0x34,0x43,0xb0,0x02,0x3c,0x20,0x01,0x00,0x08,
+0x24,0x00,0x44,0x34,0x43,0xb0,0x02,0x3c,0x20,0x01,0x00,0x08,0x18,0x00,0x44,0x34,
+0x43,0xb0,0x02,0x3c,0x20,0x01,0x00,0x08,0x0c,0x00,0x44,0x34,0x20,0x01,0x00,0x08,
+0x43,0xb0,0x04,0x3c,0x01,0x00,0x02,0x24,0x25,0xb0,0x03,0x3c,0x04,0x20,0x82,0x00,
+0x18,0x03,0x67,0x34,0x00,0x80,0x02,0x3c,0x43,0xb0,0x03,0x3c,0x34,0x05,0x46,0x24,
+0x88,0x00,0x65,0x34,0x21,0x10,0x00,0x00,0x01,0x00,0x42,0x24,0xff,0xff,0x42,0x30,
+0x05,0x00,0x43,0x2c,0xfd,0xff,0x60,0x14,0x01,0x00,0x42,0x24,0x00,0x00,0xe6,0xac,
+0x00,0x00,0xa2,0x94,0x00,0x00,0x00,0x00,0xff,0xff,0x42,0x30,0x24,0x10,0x44,0x00,
+0xf4,0xff,0x40,0x1c,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x25,0xb0,0x08,0x3c,0x00,0x80,0x02,0x3c,0xc8,0xff,0xbd,0x27,0x18,0x03,0x03,0x35,
+0x90,0x05,0x42,0x24,0x00,0x00,0x62,0xac,0x30,0x00,0xb6,0xaf,0x28,0x00,0xb4,0xaf,
+0x24,0x00,0xb3,0xaf,0x1c,0x00,0xb1,0xaf,0x34,0x00,0xbf,0xaf,0x2c,0x00,0xb5,0xaf,
+0x20,0x00,0xb2,0xaf,0x18,0x00,0xb0,0xaf,0x0c,0x00,0xf2,0x84,0x08,0x00,0xf5,0x8c,
+0xff,0x00,0xc6,0x30,0x00,0x01,0x02,0x24,0x23,0x10,0x46,0x00,0xff,0xff,0x51,0x30,
+0xd0,0x03,0x08,0x35,0xff,0x00,0x96,0x30,0x00,0x00,0x12,0xad,0x21,0xa0,0xa0,0x00,
+0x21,0x30,0xc5,0x00,0x00,0x00,0x15,0xad,0x21,0x20,0xc0,0x02,0x21,0x28,0xa0,0x02,
+0x21,0x38,0x20,0x02,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0x23,0x18,0x51,0x02,
+0xff,0xff,0x82,0x32,0x00,0x94,0x03,0x00,0x03,0x94,0x12,0x00,0xa6,0x01,0x00,0x08,
+0x02,0x9a,0x02,0x00,0x28,0xb0,0x03,0x3c,0xc0,0x10,0x13,0x00,0x21,0x10,0x43,0x00,
+0x00,0x00,0x44,0x90,0x25,0xb0,0x10,0x3c,0x20,0x10,0x02,0x3c,0xff,0x00,0x93,0x30,
+0x00,0x22,0x13,0x00,0xff,0xff,0x43,0x32,0x01,0x01,0x45,0x2a,0x21,0xa0,0x82,0x00,
+0x21,0xa8,0xb1,0x02,0xd0,0x03,0x02,0x36,0x00,0x01,0x11,0x24,0x0b,0x88,0x65,0x00,
+0x21,0x20,0xc0,0x02,0x00,0x00,0x53,0xac,0x4d,0x01,0x00,0x0c,0xb0,0x03,0x10,0x36,
+0x21,0x30,0x80,0x02,0x21,0x20,0xc0,0x02,0x21,0x28,0xa0,0x02,0x21,0x38,0x20,0x02,
+0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0x23,0x18,0x51,0x02,0x00,0x94,0x03,0x00,
+0x03,0x94,0x12,0x00,0x00,0x00,0x12,0xae,0xe2,0xff,0x40,0x1e,0x00,0x00,0x00,0x00,
+0x34,0x00,0xbf,0x8f,0x30,0x00,0xb6,0x8f,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,
+0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,
+0x08,0x00,0xe0,0x03,0x38,0x00,0xbd,0x27,0xc8,0xff,0xbd,0x27,0x02,0x80,0x02,0x3c,
+0x25,0xb0,0x04,0x3c,0x20,0x00,0xb2,0xaf,0x68,0x15,0x52,0x24,0x00,0x80,0x02,0x3c,
+0x18,0x03,0x83,0x34,0xc8,0x06,0x42,0x24,0x28,0x00,0xb4,0xaf,0x24,0x00,0xb3,0xaf,
+0x30,0x00,0xbf,0xaf,0x2c,0x00,0xb5,0xaf,0x1c,0x00,0xb1,0xaf,0x18,0x00,0xb0,0xaf,
+0x00,0x00,0x62,0xac,0xb0,0x03,0x93,0x34,0x21,0xa0,0x40,0x02,0x54,0x64,0x42,0x8e,
+0xc0,0x64,0x50,0x8e,0x21,0x20,0x00,0x00,0x00,0x00,0x62,0xae,0x58,0x64,0x42,0xae,
+0x00,0x00,0x70,0xae,0x4d,0x01,0x00,0x0c,0x00,0x00,0x00,0x00,0xc0,0x64,0x44,0x8e,
+0xc4,0x64,0x43,0x8e,0x20,0x00,0x84,0x24,0x3f,0x00,0x62,0x24,0x2b,0x10,0x44,0x00,
+0x0a,0x18,0x82,0x00,0xc0,0x64,0x43,0xae,0xc0,0x64,0x85,0x8e,0x00,0x00,0x00,0x00,
+0x00,0x00,0x65,0xae,0x02,0x80,0x02,0x3c,0xff,0xff,0x10,0x32,0x25,0x80,0x02,0x02,
+0x00,0x00,0x70,0xae,0x0c,0x00,0x02,0x92,0xff,0x00,0x15,0x24,0x21,0x20,0x00,0x00,
+0x00,0x00,0x62,0xae,0x0c,0x00,0x11,0x92,0x20,0x10,0x02,0x3c,0x20,0x00,0x07,0x24,
+0x00,0x1a,0x11,0x00,0x21,0x18,0x62,0x00,0x05,0x00,0x35,0x12,0x21,0x30,0x60,0x00,
+0x08,0x64,0x91,0xa2,0x54,0x64,0x83,0xae,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,
+0x04,0x00,0x04,0x8e,0x08,0x00,0x03,0x8e,0xff,0xe0,0x02,0x3c,0xff,0xff,0x42,0x34,
+0x1f,0x00,0x84,0x30,0x24,0x18,0x62,0x00,0x00,0x26,0x04,0x00,0xff,0xdf,0x02,0x3c,
+0x25,0x18,0x64,0x00,0xff,0xff,0x42,0x34,0x24,0x18,0x62,0x00,0x00,0x40,0x04,0x3c,
+0x25,0x18,0x64,0x00,0xc0,0xff,0x02,0x24,0x24,0x18,0x62,0x00,0x08,0x00,0x03,0xae,
+0xc9,0x64,0x84,0x92,0x2a,0xb0,0x02,0x3c,0x01,0x00,0x03,0x24,0x01,0x00,0x84,0x24,
+0x01,0x00,0x42,0x34,0x00,0x00,0x43,0xa0,0xc4,0xff,0x35,0x16,0xc9,0x64,0x84,0xa2,
+0xfc,0x4a,0x82,0x8e,0x41,0xb0,0x03,0x3c,0x30,0x00,0xbf,0x8f,0x00,0x38,0x42,0x34,
+0x00,0x00,0x62,0xac,0x2c,0x00,0xb5,0x8f,0xfc,0x4a,0x82,0xae,0x24,0x00,0xb3,0x8f,
+0x28,0x00,0xb4,0x8f,0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,
+0x08,0x00,0xe0,0x03,0x38,0x00,0xbd,0x27,0x25,0xb0,0x04,0x3c,0x00,0x80,0x02,0x3c,
+0xc8,0xff,0xbd,0x27,0x18,0x03,0x83,0x34,0x38,0x08,0x42,0x24,0x34,0x00,0xbf,0xaf,
+0x30,0x00,0xb6,0xaf,0x2c,0x00,0xb5,0xaf,0x28,0x00,0xb4,0xaf,0x24,0x00,0xb3,0xaf,
+0x20,0x00,0xb2,0xaf,0x1c,0x00,0xb1,0xaf,0x18,0x00,0xb0,0xaf,0x00,0x00,0x62,0xac,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0x02,0x80,0x16,0x3c,
+0x68,0x15,0xd2,0x26,0xb0,0x03,0x93,0x34,0x2d,0x02,0x00,0x08,0x21,0xa8,0x40,0x02,
+0x2a,0xb0,0x02,0x3c,0x08,0x00,0x04,0xae,0x09,0x00,0x42,0x34,0x01,0x00,0x03,0x24,
+0x02,0x00,0x04,0x24,0x00,0x00,0x43,0xa0,0x00,0x00,0x44,0xa0,0x42,0x00,0x34,0x12,
+0x00,0x00,0x00,0x00,0x6c,0x64,0x42,0x8e,0xd8,0x64,0x50,0x8e,0x01,0x00,0x04,0x24,
+0x00,0x00,0x62,0xae,0x70,0x64,0x42,0xae,0x00,0x00,0x70,0xae,0x4d,0x01,0x00,0x0c,
+0x00,0x00,0x00,0x00,0xd8,0x64,0x44,0x8e,0xdc,0x64,0x43,0x8e,0x20,0x00,0x84,0x24,
+0x3f,0x00,0x62,0x24,0x2b,0x10,0x44,0x00,0x0a,0x18,0x82,0x00,0xd8,0x64,0x43,0xae,
+0xd8,0x64,0xa5,0x8e,0x00,0x00,0x00,0x00,0x00,0x00,0x65,0xae,0x02,0x80,0x02,0x3c,
+0xff,0xff,0x10,0x32,0x25,0x80,0x02,0x02,0x00,0x00,0x70,0xae,0x0c,0x00,0x02,0x92,
+0xff,0x00,0x14,0x24,0x01,0x00,0x04,0x24,0x00,0x00,0x62,0xae,0x0c,0x00,0x11,0x92,
+0x20,0x10,0x02,0x3c,0x20,0x00,0x07,0x24,0x00,0x1a,0x11,0x00,0x21,0x18,0x62,0x00,
+0x05,0x00,0x34,0x12,0x21,0x30,0x60,0x00,0x6c,0x64,0xa3,0xae,0x10,0x64,0xb1,0xa2,
+0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0x04,0x00,0x04,0x8e,0x08,0x00,0x03,0x8e,
+0xff,0xe0,0x02,0x3c,0xff,0xff,0x42,0x34,0x1f,0x00,0x84,0x30,0x24,0x18,0x62,0x00,
+0x00,0x26,0x04,0x00,0xff,0xdf,0x02,0x3c,0x25,0x18,0x64,0x00,0xff,0xff,0x42,0x34,
+0x24,0x18,0x62,0x00,0x00,0x40,0x04,0x3c,0x25,0x18,0x64,0x00,0xc0,0xff,0x05,0x24,
+0x82,0x11,0x03,0x00,0x24,0x20,0x65,0x00,0x01,0x00,0x42,0x30,0xc0,0xff,0x40,0x10,
+0x04,0x00,0x84,0x34,0x2a,0xb0,0x02,0x3c,0x08,0x00,0x03,0xae,0x09,0x00,0x42,0x34,
+0x01,0x00,0x03,0x24,0x02,0x00,0x04,0x24,0x00,0x00,0x43,0xa0,0x00,0x00,0x44,0xa0,
+0xc0,0xff,0x34,0x16,0x00,0x00,0x00,0x00,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x68,0x15,0xc2,0x26,0xfc,0x4a,0x43,0x8c,
+0x34,0x00,0xbf,0x8f,0x30,0x00,0xb6,0x8f,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,
+0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,
+0x00,0x38,0x63,0x34,0x41,0xb0,0x04,0x3c,0x38,0x00,0xbd,0x27,0x00,0x00,0x83,0xac,
+0x08,0x00,0xe0,0x03,0xfc,0x4a,0x43,0xac,0x25,0xb0,0x04,0x3c,0x00,0x80,0x02,0x3c,
+0xc0,0xff,0xbd,0x27,0x18,0x03,0x83,0x34,0x08,0x0a,0x42,0x24,0x38,0x00,0xbf,0xaf,
+0x34,0x00,0xb7,0xaf,0x30,0x00,0xb6,0xaf,0x2c,0x00,0xb5,0xaf,0x28,0x00,0xb4,0xaf,
+0x24,0x00,0xb3,0xaf,0x20,0x00,0xb2,0xaf,0x1c,0x00,0xb1,0xaf,0x18,0x00,0xb0,0xaf,
+0x00,0x00,0x62,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0x02,0x80,0x17,0x3c,0x68,0x15,0xf2,0x26,0xb0,0x03,0x93,0x34,0x02,0x80,0x14,0x3c,
+0xab,0x02,0x00,0x08,0x21,0xb0,0x40,0x02,0x2a,0xb0,0x03,0x3c,0x08,0x00,0x04,0xae,
+0x05,0x00,0x63,0x34,0x01,0x00,0x02,0x24,0x02,0x00,0x04,0x24,0x00,0x00,0x62,0xa0,
+0x00,0x00,0x64,0xa0,0xca,0x7d,0x82,0x96,0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x24,
+0xca,0x7d,0x82,0xa6,0xca,0x7d,0x83,0x96,0x25,0xb0,0x02,0x3c,0x66,0x03,0x42,0x34,
+0x00,0x00,0x43,0xa4,0x4a,0x00,0x35,0x12,0x00,0x00,0x00,0x00,0x60,0x64,0x42,0x8e,
+0xcc,0x64,0x50,0x8e,0x01,0x00,0x04,0x24,0x00,0x00,0x62,0xae,0x64,0x64,0x42,0xae,
+0x00,0x00,0x70,0xae,0x4d,0x01,0x00,0x0c,0x00,0x00,0x00,0x00,0xcc,0x64,0x44,0x8e,
+0xd0,0x64,0x43,0x8e,0x20,0x00,0x84,0x24,0x3f,0x00,0x62,0x24,0x2b,0x10,0x44,0x00,
+0x0a,0x18,0x82,0x00,0xcc,0x64,0x43,0xae,0xcc,0x64,0xc5,0x8e,0x00,0x00,0x00,0x00,
+0x00,0x00,0x65,0xae,0x02,0x80,0x02,0x3c,0xff,0xff,0x10,0x32,0x25,0x80,0x02,0x02,
+0x00,0x00,0x70,0xae,0x0c,0x00,0x02,0x92,0xff,0x00,0x15,0x24,0x01,0x00,0x04,0x24,
+0x00,0x00,0x62,0xae,0x0c,0x00,0x11,0x92,0x20,0x10,0x02,0x3c,0x20,0x00,0x07,0x24,
+0x00,0x1a,0x11,0x00,0x21,0x18,0x62,0x00,0x05,0x00,0x35,0x12,0x21,0x30,0x60,0x00,
+0x60,0x64,0xc3,0xae,0x0c,0x64,0xd1,0xa2,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,
+0x04,0x00,0x04,0x8e,0x08,0x00,0x03,0x8e,0xff,0xe0,0x02,0x3c,0xff,0xff,0x42,0x34,
+0x1f,0x00,0x84,0x30,0x24,0x18,0x62,0x00,0x00,0x26,0x04,0x00,0xff,0xdf,0x02,0x3c,
+0x25,0x18,0x64,0x00,0xff,0xff,0x42,0x34,0x24,0x18,0x62,0x00,0x00,0x40,0x04,0x3c,
+0x25,0x18,0x64,0x00,0xc0,0xff,0x05,0x24,0x82,0x11,0x03,0x00,0x24,0x20,0x65,0x00,
+0x01,0x00,0x42,0x30,0xb8,0xff,0x40,0x10,0x04,0x00,0x84,0x34,0x08,0x00,0x03,0xae,
+0x2a,0xb0,0x03,0x3c,0x05,0x00,0x63,0x34,0x01,0x00,0x02,0x24,0x02,0x00,0x04,0x24,
+0x00,0x00,0x62,0xa0,0x00,0x00,0x64,0xa0,0xca,0x7d,0x82,0x96,0x00,0x00,0x00,0x00,
+0x01,0x00,0x42,0x24,0xca,0x7d,0x82,0xa6,0xca,0x7d,0x83,0x96,0x25,0xb0,0x02,0x3c,
+0x66,0x03,0x42,0x34,0x00,0x00,0x43,0xa4,0xb8,0xff,0x35,0x16,0x00,0x00,0x00,0x00,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x68,0x15,0xe2,0x26,0xfc,0x4a,0x43,0x8c,0x38,0x00,0xbf,0x8f,0x34,0x00,0xb7,0x8f,
+0x30,0x00,0xb6,0x8f,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,
+0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,0x00,0x38,0x63,0x34,
+0x41,0xb0,0x04,0x3c,0x40,0x00,0xbd,0x27,0x00,0x00,0x83,0xac,0x08,0x00,0xe0,0x03,
+0xfc,0x4a,0x43,0xac,0xc0,0xff,0xbd,0x27,0x2c,0x00,0xb5,0xaf,0x38,0x00,0xbf,0xaf,
+0x34,0x00,0xb7,0xaf,0x30,0x00,0xb6,0xaf,0x28,0x00,0xb4,0xaf,0x24,0x00,0xb3,0xaf,
+0x20,0x00,0xb2,0xaf,0x1c,0x00,0xb1,0xaf,0x18,0x00,0xb0,0xaf,0x02,0x80,0x06,0x3c,
+0x7c,0x7e,0xc5,0x90,0x00,0x80,0x03,0x3c,0x25,0xb0,0x02,0x3c,0x18,0x03,0x42,0x34,
+0x24,0x0c,0x63,0x24,0x40,0x00,0xa4,0x30,0x00,0x00,0x43,0xac,0x21,0xa8,0x00,0x00,
+0x03,0x00,0x80,0x10,0x7f,0x00,0xa2,0x30,0xbf,0x00,0xa2,0x30,0x01,0x00,0x15,0x24,
+0x7c,0x7e,0xc2,0xa0,0x7c,0x7e,0xc2,0x90,0x25,0xb0,0x04,0x3c,0x88,0x02,0x83,0x34,
+0x00,0x00,0x62,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0x02,0x80,0x16,0x3c,0x68,0x15,0xd2,0x26,0xb0,0x03,0x93,0x34,0x02,0x80,0x14,0x3c,
+0x43,0x03,0x00,0x08,0x21,0xb8,0x40,0x02,0x24,0x10,0xa2,0x00,0x04,0x00,0x42,0x34,
+0x2a,0xb0,0x07,0x3c,0x08,0x00,0x02,0xae,0x0d,0x00,0xe2,0x34,0x04,0x00,0x43,0x24,
+0x0b,0x10,0x75,0x00,0x01,0x00,0x04,0x24,0x02,0x00,0x03,0x24,0x00,0x00,0x44,0xa0,
+0x00,0x00,0x43,0xa0,0xca,0x7d,0x84,0x96,0x25,0xb0,0x06,0x3c,0x66,0x03,0xc5,0x34,
+0x01,0x00,0x84,0x24,0xca,0x7d,0x84,0xa6,0xca,0x7d,0x82,0x96,0xff,0x00,0x03,0x24,
+0x00,0x00,0xa2,0xa4,0x5a,0x00,0x23,0x12,0x00,0x00,0x00,0x00,0x24,0x64,0x42,0x8e,
+0x90,0x64,0x50,0x8e,0x03,0x00,0x04,0x24,0x00,0x00,0x62,0xae,0x28,0x64,0x42,0xae,
+0x00,0x00,0x70,0xae,0x4d,0x01,0x00,0x0c,0x00,0x00,0x00,0x00,0x90,0x64,0x44,0x8e,
+0x94,0x64,0x43,0x8e,0x20,0x00,0x84,0x24,0x3f,0x00,0x62,0x24,0x2b,0x10,0x44,0x00,
+0x0a,0x18,0x82,0x00,0x90,0x64,0x43,0xae,0x90,0x64,0xe2,0x8e,0x00,0x00,0x00,0x00,
+0x00,0x00,0x62,0xae,0x02,0x80,0x02,0x3c,0xff,0xff,0x10,0x32,0x25,0x80,0x02,0x02,
+0x00,0x00,0x70,0xae,0x0c,0x00,0x02,0x92,0x00,0x00,0x00,0x00,0x00,0x00,0x62,0xae,
+0x0c,0x00,0x11,0x92,0xff,0x00,0x02,0x24,0x0d,0x00,0x22,0x12,0x00,0x12,0x11,0x00,
+0x20,0x10,0x03,0x3c,0x21,0x10,0x43,0x00,0x5a,0x00,0xa0,0x12,0x24,0x64,0xe2,0xae,
+0xec,0x63,0xf1,0xa2,0x68,0x15,0xc2,0x26,0x24,0x64,0x46,0x8c,0x90,0x64,0x45,0x8c,
+0x03,0x00,0x04,0x24,0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,
+0x04,0x00,0x04,0x8e,0x14,0x00,0x03,0x8e,0x08,0x00,0x05,0x8e,0xff,0xe0,0x02,0x3c,
+0x1f,0x00,0x84,0x30,0x42,0x1a,0x03,0x00,0xff,0xff,0x42,0x34,0x00,0x26,0x04,0x00,
+0x24,0x28,0xa2,0x00,0x3f,0x00,0x63,0x30,0x25,0x28,0xa4,0x00,0x0c,0x00,0x63,0x28,
+0x06,0x00,0x60,0x14,0x21,0x20,0xa0,0x00,0x00,0x00,0x02,0x96,0x00,0x00,0x00,0x00,
+0xfd,0x0f,0x42,0x28,0x08,0x00,0x40,0x14,0x82,0x11,0x05,0x00,0xff,0xdf,0x02,0x3c,
+0xff,0xff,0x42,0x34,0x24,0x28,0x82,0x00,0x00,0x40,0x03,0x3c,0x25,0x20,0xa3,0x00,
+0x21,0x28,0x80,0x00,0x82,0x11,0x05,0x00,0x01,0x00,0x42,0x30,0xa6,0xff,0x40,0x10,
+0xc0,0xff,0x02,0x24,0x2a,0xb0,0x07,0x3c,0x0d,0x00,0xe2,0x34,0x04,0x00,0x43,0x24,
+0x08,0x00,0x04,0xae,0x0b,0x10,0x75,0x00,0x01,0x00,0x04,0x24,0x02,0x00,0x03,0x24,
+0x00,0x00,0x44,0xa0,0x00,0x00,0x43,0xa0,0xca,0x7d,0x84,0x96,0x25,0xb0,0x06,0x3c,
+0x66,0x03,0xc5,0x34,0x01,0x00,0x84,0x24,0xca,0x7d,0x84,0xa6,0xca,0x7d,0x82,0x96,
+0xff,0x00,0x03,0x24,0x00,0x00,0xa2,0xa4,0xa8,0xff,0x23,0x16,0x00,0x00,0x00,0x00,
+0x22,0x00,0xa0,0x12,0x68,0x15,0xc2,0x26,0xec,0x63,0x43,0x90,0x41,0x00,0xe4,0x34,
+0xb0,0x03,0xc5,0x34,0x00,0x00,0x83,0xa0,0x00,0x00,0xa3,0xac,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x68,0x15,0xc5,0x26,0xfc,0x4a,0xa4,0x8c,
+0x01,0x00,0x02,0x3c,0x38,0x00,0xbf,0x8f,0x34,0x00,0xb7,0x8f,0x30,0x00,0xb6,0x8f,
+0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,
+0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,0x00,0x80,0x42,0x34,0x25,0x20,0x82,0x00,
+0x41,0xb0,0x03,0x3c,0x40,0x00,0xbd,0x27,0x00,0x00,0x64,0xac,0x08,0x00,0xe0,0x03,
+0xfc,0x4a,0xa4,0xac,0x65,0x03,0x00,0x08,0xe8,0x63,0xf1,0xa2,0xe8,0x63,0x43,0x90,
+0x40,0x00,0xe4,0x34,0xb0,0x03,0xc5,0x34,0x00,0x00,0x83,0xa0,0x00,0x00,0xa3,0xac,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x68,0x15,0xc5,0x26,
+0xfc,0x4a,0xa4,0x8c,0x01,0x00,0x02,0x3c,0x38,0x00,0xbf,0x8f,0x34,0x00,0xb7,0x8f,
+0x30,0x00,0xb6,0x8f,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,
+0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,0x00,0x80,0x42,0x34,
+0x25,0x20,0x82,0x00,0x41,0xb0,0x03,0x3c,0x40,0x00,0xbd,0x27,0x00,0x00,0x64,0xac,
+0x08,0x00,0xe0,0x03,0xfc,0x4a,0xa4,0xac,0xc0,0xff,0xbd,0x27,0x2c,0x00,0xb5,0xaf,
+0x38,0x00,0xbf,0xaf,0x34,0x00,0xb7,0xaf,0x30,0x00,0xb6,0xaf,0x28,0x00,0xb4,0xaf,
+0x24,0x00,0xb3,0xaf,0x20,0x00,0xb2,0xaf,0x1c,0x00,0xb1,0xaf,0x18,0x00,0xb0,0xaf,
+0x02,0x80,0x06,0x3c,0x7c,0x7e,0xc5,0x90,0x00,0x80,0x03,0x3c,0x25,0xb0,0x02,0x3c,
+0x18,0x03,0x42,0x34,0x78,0x0f,0x63,0x24,0x10,0x00,0xa4,0x30,0x00,0x00,0x43,0xac,
+0x21,0xa8,0x00,0x00,0x03,0x00,0x80,0x10,0xdf,0x00,0xa2,0x30,0xef,0x00,0xa2,0x30,
+0x01,0x00,0x15,0x24,0x7c,0x7e,0xc2,0xa0,0x7c,0x7e,0xc3,0x90,0x25,0xb0,0x02,0x3c,
+0xb0,0x03,0x42,0x34,0x00,0x00,0x43,0xac,0x00,0x00,0x43,0xac,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0x02,0x80,0x16,0x3c,0x68,0x15,0xd2,0x26,
+0x21,0x98,0x40,0x00,0x02,0x80,0x14,0x3c,0x19,0x04,0x00,0x08,0x21,0xb8,0x40,0x02,
+0x24,0x10,0xa2,0x00,0x04,0x00,0x42,0x34,0x2a,0xb0,0x07,0x3c,0x08,0x00,0x02,0xae,
+0x15,0x00,0xe2,0x34,0x04,0x00,0x43,0x24,0x0b,0x10,0x75,0x00,0x01,0x00,0x04,0x24,
+0x02,0x00,0x03,0x24,0x00,0x00,0x44,0xa0,0x00,0x00,0x43,0xa0,0xca,0x7d,0x84,0x96,
+0x25,0xb0,0x06,0x3c,0x66,0x03,0xc5,0x34,0x01,0x00,0x84,0x24,0xca,0x7d,0x84,0xa6,
+0xca,0x7d,0x82,0x96,0xff,0x00,0x03,0x24,0x00,0x00,0xa2,0xa4,0x5a,0x00,0x23,0x12,
+0x00,0x00,0x00,0x00,0x30,0x64,0x42,0x8e,0x9c,0x64,0x50,0x8e,0x04,0x00,0x04,0x24,
+0x00,0x00,0x62,0xae,0x34,0x64,0x42,0xae,0x00,0x00,0x70,0xae,0x4d,0x01,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x9c,0x64,0x44,0x8e,0xa0,0x64,0x43,0x8e,0x20,0x00,0x84,0x24,
+0x3f,0x00,0x62,0x24,0x2b,0x10,0x44,0x00,0x0a,0x18,0x82,0x00,0x9c,0x64,0x43,0xae,
+0x9c,0x64,0xe2,0x8e,0x00,0x00,0x00,0x00,0x00,0x00,0x62,0xae,0x02,0x80,0x02,0x3c,
+0xff,0xff,0x10,0x32,0x25,0x80,0x02,0x02,0x00,0x00,0x70,0xae,0x0c,0x00,0x02,0x92,
+0x00,0x00,0x00,0x00,0x00,0x00,0x62,0xae,0x0c,0x00,0x11,0x92,0xff,0x00,0x02,0x24,
+0x0d,0x00,0x22,0x12,0x00,0x12,0x11,0x00,0x20,0x10,0x03,0x3c,0x21,0x10,0x43,0x00,
+0x59,0x00,0xa0,0x12,0x30,0x64,0xe2,0xae,0xf4,0x63,0xf1,0xa2,0x68,0x15,0xc2,0x26,
+0x30,0x64,0x46,0x8c,0x9c,0x64,0x45,0x8c,0x04,0x00,0x04,0x24,0x20,0x00,0x07,0x24,
+0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0x04,0x00,0x04,0x8e,0x14,0x00,0x03,0x8e,
+0x08,0x00,0x05,0x8e,0xff,0xe0,0x02,0x3c,0x1f,0x00,0x84,0x30,0x42,0x1a,0x03,0x00,
+0xff,0xff,0x42,0x34,0x00,0x26,0x04,0x00,0x24,0x28,0xa2,0x00,0x3f,0x00,0x63,0x30,
+0x25,0x28,0xa4,0x00,0x0c,0x00,0x63,0x28,0x06,0x00,0x60,0x14,0x21,0x20,0xa0,0x00,
+0x00,0x00,0x02,0x96,0x00,0x00,0x00,0x00,0xfd,0x0f,0x42,0x28,0x08,0x00,0x40,0x14,
+0x82,0x11,0x05,0x00,0xff,0xdf,0x02,0x3c,0xff,0xff,0x42,0x34,0x24,0x28,0x82,0x00,
+0x00,0x40,0x03,0x3c,0x25,0x20,0xa3,0x00,0x21,0x28,0x80,0x00,0x82,0x11,0x05,0x00,
+0x01,0x00,0x42,0x30,0xa6,0xff,0x40,0x10,0xc0,0xff,0x02,0x24,0x2a,0xb0,0x07,0x3c,
+0x15,0x00,0xe2,0x34,0x04,0x00,0x43,0x24,0x08,0x00,0x04,0xae,0x0b,0x10,0x75,0x00,
+0x01,0x00,0x04,0x24,0x02,0x00,0x03,0x24,0x00,0x00,0x44,0xa0,0x00,0x00,0x43,0xa0,
+0xca,0x7d,0x84,0x96,0x25,0xb0,0x06,0x3c,0x66,0x03,0xc5,0x34,0x01,0x00,0x84,0x24,
+0xca,0x7d,0x84,0xa6,0xca,0x7d,0x82,0x96,0xff,0x00,0x03,0x24,0x00,0x00,0xa2,0xa4,
+0xa8,0xff,0x23,0x16,0x00,0x00,0x00,0x00,0x21,0x00,0xa0,0x12,0x68,0x15,0xc2,0x26,
+0xf4,0x63,0x43,0x90,0x43,0x00,0xe4,0x34,0xb0,0x03,0xc5,0x34,0x00,0x00,0x83,0xa0,
+0x00,0x00,0xa3,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x68,0x15,0xc5,0x26,0xfc,0x4a,0xa2,0x8c,0x38,0x00,0xbf,0x8f,0x34,0x00,0xb7,0x8f,
+0x30,0x00,0xb6,0x8f,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,
+0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,0x06,0x00,0x03,0x3c,
+0x25,0x10,0x43,0x00,0x41,0xb0,0x04,0x3c,0x40,0x00,0xbd,0x27,0x00,0x00,0x82,0xac,
+0x08,0x00,0xe0,0x03,0xfc,0x4a,0xa2,0xac,0x3b,0x04,0x00,0x08,0xf0,0x63,0xf1,0xa2,
+0xf0,0x63,0x43,0x90,0x42,0x00,0xe4,0x34,0xb0,0x03,0xc5,0x34,0x00,0x00,0x83,0xa0,
+0x00,0x00,0xa3,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x68,0x15,0xc5,0x26,0xfc,0x4a,0xa2,0x8c,0x38,0x00,0xbf,0x8f,0x34,0x00,0xb7,0x8f,
+0x30,0x00,0xb6,0x8f,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,
+0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,0x06,0x00,0x03,0x3c,
+0x25,0x10,0x43,0x00,0x41,0xb0,0x04,0x3c,0x40,0x00,0xbd,0x27,0x00,0x00,0x82,0xac,
+0x08,0x00,0xe0,0x03,0xfc,0x4a,0xa2,0xac,0xc0,0xff,0xbd,0x27,0x2c,0x00,0xb5,0xaf,
+0x38,0x00,0xbf,0xaf,0x34,0x00,0xb7,0xaf,0x30,0x00,0xb6,0xaf,0x28,0x00,0xb4,0xaf,
+0x24,0x00,0xb3,0xaf,0x20,0x00,0xb2,0xaf,0x1c,0x00,0xb1,0xaf,0x18,0x00,0xb0,0xaf,
+0x02,0x80,0x06,0x3c,0x7c,0x7e,0xc5,0x90,0x00,0x80,0x03,0x3c,0x25,0xb0,0x02,0x3c,
+0x18,0x03,0x42,0x34,0xc8,0x12,0x63,0x24,0x01,0x00,0xa4,0x30,0x00,0x00,0x43,0xac,
+0x21,0xa8,0x00,0x00,0x03,0x00,0x80,0x10,0xf7,0x00,0xa2,0x30,0xfe,0x00,0xa2,0x30,
+0x01,0x00,0x15,0x24,0x7c,0x7e,0xc2,0xa0,0x7c,0x7e,0xc3,0x90,0x25,0xb0,0x02,0x3c,
+0xb0,0x03,0x42,0x34,0x00,0x00,0x43,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x00,0x60,0x81,0x40,0x02,0x80,0x16,0x3c,0x68,0x15,0xd2,0x26,0x21,0x98,0x40,0x00,
+0x02,0x80,0x14,0x3c,0xf8,0x04,0x00,0x08,0x21,0xb8,0x40,0x02,0x00,0x00,0x02,0x96,
+0x00,0x00,0x00,0x00,0xfd,0x0f,0x42,0x28,0x54,0x00,0x40,0x10,0xff,0xdf,0x02,0x3c,
+0x00,0x20,0x02,0x3c,0x25,0x28,0xa2,0x00,0x82,0x11,0x05,0x00,0x01,0x00,0x42,0x30,
+0x57,0x00,0x40,0x14,0x2a,0xb0,0x07,0x3c,0xc0,0xff,0x02,0x24,0x24,0x10,0xa2,0x00,
+0x04,0x00,0x42,0x34,0x2a,0xb0,0x07,0x3c,0x08,0x00,0x02,0xae,0x1d,0x00,0xe2,0x34,
+0x04,0x00,0x43,0x24,0x0b,0x10,0x75,0x00,0x01,0x00,0x04,0x24,0x02,0x00,0x03,0x24,
+0x00,0x00,0x44,0xa0,0x00,0x00,0x43,0xa0,0xca,0x7d,0x84,0x96,0x25,0xb0,0x06,0x3c,
+0x66,0x03,0xc5,0x34,0x01,0x00,0x84,0x24,0xca,0x7d,0x84,0xa6,0xca,0x7d,0x82,0x96,
+0xff,0x00,0x03,0x24,0x00,0x00,0xa2,0xa4,0x53,0x00,0x23,0x12,0x00,0x00,0x00,0x00,
+0x3c,0x64,0x42,0x8e,0xa8,0x64,0x50,0x8e,0x05,0x00,0x04,0x24,0x00,0x00,0x62,0xae,
+0x40,0x64,0x42,0xae,0x00,0x00,0x70,0xae,0x4d,0x01,0x00,0x0c,0x00,0x00,0x00,0x00,
+0xa8,0x64,0x44,0x8e,0xac,0x64,0x43,0x8e,0x20,0x00,0x84,0x24,0x3f,0x00,0x62,0x24,
+0x2b,0x10,0x44,0x00,0x0a,0x18,0x82,0x00,0xa8,0x64,0x43,0xae,0xa8,0x64,0xe2,0x8e,
+0x00,0x00,0x00,0x00,0x00,0x00,0x62,0xae,0x02,0x80,0x02,0x3c,0xff,0xff,0x10,0x32,
+0x25,0x80,0x02,0x02,0x00,0x00,0x70,0xae,0x0c,0x00,0x02,0x92,0x00,0x00,0x00,0x00,
+0x00,0x00,0x62,0xae,0x0c,0x00,0x11,0x92,0xff,0x00,0x02,0x24,0x0d,0x00,0x22,0x12,
+0x00,0x12,0x11,0x00,0x20,0x10,0x03,0x3c,0x21,0x10,0x43,0x00,0x52,0x00,0xa0,0x12,
+0x3c,0x64,0xe2,0xae,0x04,0x64,0xf1,0xa2,0x68,0x15,0xc2,0x26,0x3c,0x64,0x46,0x8c,
+0xa8,0x64,0x45,0x8c,0x05,0x00,0x04,0x24,0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,
+0x10,0x00,0xa0,0xaf,0x14,0x00,0x03,0x8e,0x04,0x00,0x04,0x8e,0x08,0x00,0x05,0x8e,
+0x42,0x1a,0x03,0x00,0xff,0xe0,0x02,0x3c,0x1f,0x00,0x84,0x30,0x3f,0x00,0x63,0x30,
+0xff,0xff,0x42,0x34,0x24,0x28,0xa2,0x00,0x00,0x26,0x04,0x00,0x0c,0x00,0x63,0x28,
+0xaa,0xff,0x60,0x10,0x25,0x28,0xa4,0x00,0xff,0xdf,0x02,0x3c,0xff,0xff,0x42,0x34,
+0x24,0x10,0xa2,0x00,0x00,0x40,0x03,0x3c,0x25,0x28,0x43,0x00,0x82,0x11,0x05,0x00,
+0x01,0x00,0x42,0x30,0xad,0xff,0x40,0x10,0xc0,0xff,0x02,0x24,0x2a,0xb0,0x07,0x3c,
+0x1d,0x00,0xe2,0x34,0x04,0x00,0x43,0x24,0x0b,0x10,0x75,0x00,0x01,0x00,0x04,0x24,
+0x02,0x00,0x03,0x24,0x08,0x00,0x05,0xae,0x00,0x00,0x44,0xa0,0x00,0x00,0x43,0xa0,
+0xca,0x7d,0x84,0x96,0x25,0xb0,0x06,0x3c,0x66,0x03,0xc5,0x34,0x01,0x00,0x84,0x24,
+0xca,0x7d,0x84,0xa6,0xca,0x7d,0x82,0x96,0xff,0x00,0x03,0x24,0x00,0x00,0xa2,0xa4,
+0xaf,0xff,0x23,0x16,0x00,0x00,0x00,0x00,0x21,0x00,0xa0,0x12,0x68,0x15,0xc2,0x26,
+0x04,0x64,0x43,0x90,0x45,0x00,0xe4,0x34,0xb0,0x03,0xc5,0x34,0x00,0x00,0x83,0xa0,
+0x00,0x00,0xa3,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x68,0x15,0xc5,0x26,0xfc,0x4a,0xa2,0x8c,0x38,0x00,0xbf,0x8f,0x34,0x00,0xb7,0x8f,
+0x30,0x00,0xb6,0x8f,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,
+0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,0x18,0x00,0x03,0x3c,
+0x25,0x10,0x43,0x00,0x41,0xb0,0x04,0x3c,0x40,0x00,0xbd,0x27,0x00,0x00,0x82,0xac,
+0x08,0x00,0xe0,0x03,0xfc,0x4a,0xa2,0xac,0x1a,0x05,0x00,0x08,0xf8,0x63,0xf1,0xa2,
+0xf8,0x63,0x43,0x90,0x44,0x00,0xe4,0x34,0xb0,0x03,0xc5,0x34,0x00,0x00,0x83,0xa0,
+0x00,0x00,0xa3,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x68,0x15,0xc5,0x26,0xfc,0x4a,0xa2,0x8c,0x38,0x00,0xbf,0x8f,0x34,0x00,0xb7,0x8f,
+0x30,0x00,0xb6,0x8f,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,
+0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,0x18,0x00,0x03,0x3c,
+0x25,0x10,0x43,0x00,0x41,0xb0,0x04,0x3c,0x40,0x00,0xbd,0x27,0x00,0x00,0x82,0xac,
+0x08,0x00,0xe0,0x03,0xfc,0x4a,0xa2,0xac,0xc0,0xff,0xbd,0x27,0x2c,0x00,0xb5,0xaf,
+0x38,0x00,0xbf,0xaf,0x34,0x00,0xb7,0xaf,0x30,0x00,0xb6,0xaf,0x28,0x00,0xb4,0xaf,
+0x24,0x00,0xb3,0xaf,0x20,0x00,0xb2,0xaf,0x1c,0x00,0xb1,0xaf,0x18,0x00,0xb0,0xaf,
+0x02,0x80,0x06,0x3c,0x7c,0x7e,0xc5,0x90,0x00,0x80,0x03,0x3c,0x25,0xb0,0x02,0x3c,
+0x18,0x03,0x42,0x34,0x28,0x16,0x63,0x24,0x02,0x00,0xa4,0x30,0x00,0x00,0x43,0xac,
+0x21,0xa8,0x00,0x00,0x03,0x00,0x80,0x10,0xfb,0x00,0xa2,0x30,0xfd,0x00,0xa2,0x30,
+0x01,0x00,0x15,0x24,0x7c,0x7e,0xc2,0xa0,0x7c,0x7e,0xc3,0x90,0x25,0xb0,0x02,0x3c,
+0xb0,0x03,0x42,0x34,0x00,0x00,0x43,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x00,0x60,0x81,0x40,0x02,0x80,0x16,0x3c,0x68,0x15,0xd2,0x26,0x21,0x98,0x40,0x00,
+0x02,0x80,0x14,0x3c,0xd0,0x05,0x00,0x08,0x21,0xb8,0x40,0x02,0x00,0x00,0x02,0x96,
+0x00,0x00,0x00,0x00,0xfd,0x0f,0x42,0x28,0x54,0x00,0x40,0x10,0xff,0xdf,0x02,0x3c,
+0x00,0x20,0x02,0x3c,0x25,0x28,0xa2,0x00,0x82,0x11,0x05,0x00,0x01,0x00,0x42,0x30,
+0x57,0x00,0x40,0x14,0x2a,0xb0,0x07,0x3c,0xc0,0xff,0x02,0x24,0x24,0x10,0xa2,0x00,
+0x04,0x00,0x42,0x34,0x2a,0xb0,0x07,0x3c,0x08,0x00,0x02,0xae,0x25,0x00,0xe2,0x34,
+0x04,0x00,0x43,0x24,0x0b,0x10,0x75,0x00,0x01,0x00,0x04,0x24,0x02,0x00,0x03,0x24,
+0x00,0x00,0x44,0xa0,0x00,0x00,0x43,0xa0,0xca,0x7d,0x84,0x96,0x25,0xb0,0x06,0x3c,
+0x66,0x03,0xc5,0x34,0x01,0x00,0x84,0x24,0xca,0x7d,0x84,0xa6,0xca,0x7d,0x82,0x96,
+0xff,0x00,0x03,0x24,0x00,0x00,0xa2,0xa4,0x53,0x00,0x23,0x12,0x00,0x00,0x00,0x00,
+0x48,0x64,0x42,0x8e,0xb4,0x64,0x50,0x8e,0x06,0x00,0x04,0x24,0x00,0x00,0x62,0xae,
+0x4c,0x64,0x42,0xae,0x00,0x00,0x70,0xae,0x4d,0x01,0x00,0x0c,0x00,0x00,0x00,0x00,
+0xb4,0x64,0x44,0x8e,0xb8,0x64,0x43,0x8e,0x20,0x00,0x84,0x24,0x3f,0x00,0x62,0x24,
+0x2b,0x10,0x44,0x00,0x0a,0x18,0x82,0x00,0xb4,0x64,0x43,0xae,0xb4,0x64,0xe2,0x8e,
+0x00,0x00,0x00,0x00,0x00,0x00,0x62,0xae,0x02,0x80,0x02,0x3c,0xff,0xff,0x10,0x32,
+0x25,0x80,0x02,0x02,0x00,0x00,0x70,0xae,0x0c,0x00,0x02,0x92,0x00,0x00,0x00,0x00,
+0x00,0x00,0x62,0xae,0x0c,0x00,0x11,0x92,0xff,0x00,0x02,0x24,0x0d,0x00,0x22,0x12,
+0x00,0x12,0x11,0x00,0x20,0x10,0x03,0x3c,0x21,0x10,0x43,0x00,0x52,0x00,0xa0,0x12,
+0x48,0x64,0xe2,0xae,0x00,0x64,0xf1,0xa2,0x68,0x15,0xc2,0x26,0x48,0x64,0x46,0x8c,
+0xb4,0x64,0x45,0x8c,0x06,0x00,0x04,0x24,0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,
+0x10,0x00,0xa0,0xaf,0x14,0x00,0x03,0x8e,0x04,0x00,0x04,0x8e,0x08,0x00,0x05,0x8e,
+0x42,0x1a,0x03,0x00,0xff,0xe0,0x02,0x3c,0x1f,0x00,0x84,0x30,0x3f,0x00,0x63,0x30,
+0xff,0xff,0x42,0x34,0x24,0x28,0xa2,0x00,0x00,0x26,0x04,0x00,0x0c,0x00,0x63,0x28,
+0xaa,0xff,0x60,0x10,0x25,0x28,0xa4,0x00,0xff,0xdf,0x02,0x3c,0xff,0xff,0x42,0x34,
+0x24,0x10,0xa2,0x00,0x00,0x40,0x03,0x3c,0x25,0x28,0x43,0x00,0x82,0x11,0x05,0x00,
+0x01,0x00,0x42,0x30,0xad,0xff,0x40,0x10,0xc0,0xff,0x02,0x24,0x2a,0xb0,0x07,0x3c,
+0x25,0x00,0xe2,0x34,0x04,0x00,0x43,0x24,0x0b,0x10,0x75,0x00,0x01,0x00,0x04,0x24,
+0x02,0x00,0x03,0x24,0x08,0x00,0x05,0xae,0x00,0x00,0x44,0xa0,0x00,0x00,0x43,0xa0,
+0xca,0x7d,0x84,0x96,0x25,0xb0,0x06,0x3c,0x66,0x03,0xc5,0x34,0x01,0x00,0x84,0x24,
+0xca,0x7d,0x84,0xa6,0xca,0x7d,0x82,0x96,0xff,0x00,0x03,0x24,0x00,0x00,0xa2,0xa4,
+0xaf,0xff,0x23,0x16,0x00,0x00,0x00,0x00,0x21,0x00,0xa0,0x12,0x68,0x15,0xc2,0x26,
+0x00,0x64,0x43,0x90,0x47,0x00,0xe4,0x34,0xb0,0x03,0xc5,0x34,0x00,0x00,0x83,0xa0,
+0x00,0x00,0xa3,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x68,0x15,0xc5,0x26,0xfc,0x4a,0xa2,0x8c,0x38,0x00,0xbf,0x8f,0x34,0x00,0xb7,0x8f,
+0x30,0x00,0xb6,0x8f,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,
+0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,0x60,0x00,0x03,0x3c,
+0x25,0x10,0x43,0x00,0x41,0xb0,0x04,0x3c,0x40,0x00,0xbd,0x27,0x00,0x00,0x82,0xac,
+0x08,0x00,0xe0,0x03,0xfc,0x4a,0xa2,0xac,0xf2,0x05,0x00,0x08,0xfc,0x63,0xf1,0xa2,
+0xfc,0x63,0x43,0x90,0x46,0x00,0xe4,0x34,0xb0,0x03,0xc5,0x34,0x00,0x00,0x83,0xa0,
+0x00,0x00,0xa3,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x68,0x15,0xc5,0x26,0xfc,0x4a,0xa2,0x8c,0x38,0x00,0xbf,0x8f,0x34,0x00,0xb7,0x8f,
+0x30,0x00,0xb6,0x8f,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,
+0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,0x60,0x00,0x03,0x3c,
+0x25,0x10,0x43,0x00,0x41,0xb0,0x04,0x3c,0x40,0x00,0xbd,0x27,0x00,0x00,0x82,0xac,
+0x08,0x00,0xe0,0x03,0xfc,0x4a,0xa2,0xac,0x00,0x80,0x03,0x3c,0x25,0xb0,0x02,0x3c,
+0x88,0x19,0x63,0x24,0x18,0x03,0x42,0x34,0x00,0x00,0x43,0xac,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x02,0x80,0x05,0x3c,0x68,0x15,0xa5,0x24,
+0x04,0x4b,0xa2,0x8c,0xfc,0x4a,0xa4,0x8c,0x00,0x08,0x03,0x3c,0x24,0x10,0x43,0x00,
+0x25,0x20,0x82,0x00,0x41,0xb0,0x03,0x3c,0x00,0x00,0x64,0xac,0x08,0x00,0xe0,0x03,
+0xfc,0x4a,0xa4,0xac,0x25,0xb0,0x04,0x3c,0x00,0x80,0x02,0x3c,0xc0,0xff,0xbd,0x27,
+0x18,0x03,0x83,0x34,0xe4,0x19,0x42,0x24,0x3c,0x00,0xbf,0xaf,0x38,0x00,0xbe,0xaf,
+0x34,0x00,0xb7,0xaf,0x30,0x00,0xb6,0xaf,0x2c,0x00,0xb5,0xaf,0x28,0x00,0xb4,0xaf,
+0x24,0x00,0xb3,0xaf,0x20,0x00,0xb2,0xaf,0x1c,0x00,0xb1,0xaf,0x18,0x00,0xb0,0xaf,
+0x00,0x00,0x62,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0x02,0x80,0x02,0x3c,0x2a,0xb0,0x03,0x3c,0x68,0x15,0x51,0x24,0xb0,0x03,0x93,0x34,
+0x2c,0x00,0x77,0x34,0x02,0x80,0x15,0x3c,0x02,0x80,0x16,0x3c,0x9c,0x06,0x00,0x08,
+0x02,0x80,0x1e,0x3c,0x14,0x64,0x26,0x92,0xe4,0x64,0x25,0x8e,0x00,0x32,0x06,0x00,
+0x21,0x30,0xc2,0x00,0x78,0x64,0x26,0xae,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,
+0xe4,0x64,0x30,0x8e,0x0a,0x00,0x04,0x24,0x21,0x90,0x00,0x00,0x00,0x00,0x70,0xae,
+0x4d,0x01,0x00,0x0c,0xff,0xff,0x10,0x32,0x02,0x80,0x02,0x3c,0x25,0x80,0x02,0x02,
+0x0c,0x00,0x05,0x92,0x02,0x00,0x04,0x92,0xff,0x00,0x02,0x24,0xff,0x00,0xa3,0x30,
+0x04,0x00,0x62,0x10,0x21,0x80,0x04,0x02,0x00,0x00,0x63,0xae,0x01,0x00,0x12,0x24,
+0x14,0x64,0x25,0xa2,0x88,0x96,0xb0,0xae,0x21,0x28,0x00,0x02,0x02,0x00,0xa2,0x90,
+0x08,0x00,0x10,0x26,0x21,0x20,0x00,0x02,0xff,0x00,0x42,0x30,0x00,0x00,0x62,0xae,
+0x03,0x00,0xa3,0x90,0x00,0x00,0x00,0x00,0x7f,0x00,0x63,0x30,0x00,0x00,0x63,0xae,
+0x00,0x00,0x72,0xae,0x03,0x00,0xa2,0x90,0x84,0x96,0xc3,0x92,0x02,0x00,0xa2,0x90,
+0x00,0x00,0x00,0x00,0xff,0x00,0x42,0x30,0x2c,0x00,0x42,0x28,0x11,0x00,0x40,0x10,
+0x08,0x00,0x02,0x24,0x03,0x00,0xa2,0x90,0x00,0x00,0x00,0x00,0x7f,0x00,0x42,0x30,
+0x84,0x96,0xc2,0xa2,0x02,0x00,0xa3,0x90,0x02,0x80,0x02,0x3c,0x74,0x84,0x42,0x24,
+0xff,0x00,0x63,0x30,0xc0,0x18,0x03,0x00,0x21,0x18,0x62,0x00,0x04,0x00,0x62,0x8c,
+0x00,0x00,0x00,0x00,0x09,0xf8,0x40,0x00,0x80,0x96,0xc2,0xaf,0x21,0xa0,0x40,0x00,
+0x08,0x00,0x02,0x24,0x0a,0x00,0x04,0x24,0x05,0x00,0x82,0x12,0x00,0x01,0x07,0x24,
+0x01,0x00,0x02,0x24,0x02,0x00,0x03,0x24,0x01,0x00,0xe2,0xa2,0x01,0x00,0xe3,0xa2,
+0xbc,0xff,0x40,0x16,0x20,0x10,0x02,0x3c,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0xfc,0x4a,0x22,0x8e,0x00,0x04,0x03,0x3c,
+0x41,0xb0,0x04,0x3c,0x25,0x10,0x43,0x00,0x00,0x00,0x82,0xac,0x3c,0x00,0xbf,0x8f,
+0xfc,0x4a,0x22,0xae,0x38,0x00,0xbe,0x8f,0x34,0x00,0xb7,0x8f,0x30,0x00,0xb6,0x8f,
+0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,
+0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x40,0x00,0xbd,0x27,
+0xc8,0xff,0xbd,0x27,0xff,0xff,0xa8,0x30,0x02,0x80,0x02,0x3c,0x25,0x40,0x02,0x01,
+0x30,0x00,0xb6,0xaf,0x20,0x00,0xb2,0xaf,0x34,0x00,0xbf,0xaf,0x2c,0x00,0xb5,0xaf,
+0x28,0x00,0xb4,0xaf,0x24,0x00,0xb3,0xaf,0x1c,0x00,0xb1,0xaf,0x18,0x00,0xb0,0xaf,
+0x00,0x00,0x03,0x8d,0xff,0xff,0xd2,0x30,0x21,0xb0,0xa0,0x00,0x00,0xc0,0x02,0x24,
+0x08,0x00,0x45,0x26,0x04,0x00,0x06,0x8d,0x24,0x18,0x62,0x00,0xff,0x3f,0xa5,0x30,
+0xf0,0xff,0x02,0x3c,0x25,0x18,0x65,0x00,0xff,0xff,0x42,0x34,0x24,0x18,0x62,0x00,
+0x00,0x80,0x05,0x3c,0x25,0x18,0x65,0x00,0xff,0x01,0xc6,0x34,0x00,0x00,0x03,0xad,
+0x04,0x00,0x06,0xad,0x21,0x48,0x80,0x00,0xff,0xff,0xe7,0x30,0x18,0x00,0x12,0xa5,
+0x1a,0x00,0x07,0xa1,0x18,0x00,0x03,0x8d,0xff,0x7f,0x02,0x3c,0xff,0xff,0x42,0x34,
+0x24,0x18,0x62,0x00,0x02,0x80,0x15,0x3c,0x18,0x00,0x03,0xad,0x68,0x15,0xa5,0x26,
+0xd6,0x63,0xa3,0x90,0x00,0x00,0x00,0x00,0x01,0x00,0x62,0x24,0xd6,0x63,0xa2,0xa0,
+0x18,0x00,0x04,0x8d,0xff,0x80,0x02,0x3c,0x20,0x00,0x45,0x26,0xff,0xff,0x42,0x34,
+0x7f,0x00,0x63,0x30,0xff,0xff,0xb2,0x30,0x24,0x20,0x82,0x00,0x00,0x1e,0x03,0x00,
+0x25,0xb0,0x02,0x3c,0xc0,0x00,0x42,0x34,0x25,0x20,0x83,0x00,0x07,0x00,0x45,0x32,
+0x18,0x00,0x04,0xad,0x00,0x00,0x52,0xa4,0x03,0x00,0xa0,0x10,0xff,0xff,0x42,0x32,
+0x08,0x00,0x42,0x26,0xff,0xff,0x42,0x30,0x68,0x15,0xb4,0x26,0x54,0x65,0x86,0x8e,
+0x58,0x65,0x90,0x8e,0xf8,0xff,0x52,0x30,0x21,0x10,0xd2,0x00,0x2b,0x10,0x02,0x02,
+0x31,0x00,0x40,0x10,0xff,0x00,0x33,0x31,0x23,0x80,0x06,0x02,0x21,0x28,0xc0,0x02,
+0xff,0xff,0x07,0x32,0x01,0x00,0x11,0x24,0x21,0x20,0x60,0x02,0x10,0x01,0x00,0x0c,
+0x10,0x00,0xb1,0xaf,0x23,0x18,0x50,0x02,0xff,0xff,0x72,0x30,0x22,0x10,0x02,0x3c,
+0x21,0x10,0x42,0x02,0x21,0x20,0x60,0x02,0x4d,0x01,0x00,0x0c,0x54,0x65,0x82,0xae,
+0x21,0x28,0xd0,0x02,0x21,0x38,0x40,0x02,0x21,0x20,0x60,0x02,0x10,0x00,0xb1,0xaf,
+0x22,0x10,0x06,0x3c,0x10,0x01,0x00,0x0c,0x68,0x15,0xb1,0x26,0x54,0x65,0x23,0x8e,
+0x25,0xb0,0x10,0x3c,0xb0,0x03,0x02,0x36,0x21,0x20,0x60,0x02,0x00,0x00,0x43,0xac,
+0x4d,0x01,0x00,0x0c,0x00,0x00,0x00,0x00,0x54,0x65,0x25,0x8e,0xec,0x00,0x02,0x36,
+0xbd,0x00,0x04,0x36,0x00,0x00,0x45,0xac,0x00,0x00,0x83,0x90,0xc2,0x00,0x10,0x36,
+0x34,0x00,0xbf,0x8f,0x10,0x00,0x63,0x34,0x00,0x00,0x83,0xa0,0x30,0x00,0xb6,0x8f,
+0x00,0x00,0x05,0xa6,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,
+0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,0x01,0x00,0x02,0x24,
+0x08,0x00,0xe0,0x03,0x38,0x00,0xbd,0x27,0x21,0x28,0xc0,0x02,0x21,0x20,0x60,0x02,
+0x21,0x38,0x40,0x02,0x01,0x00,0x02,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xa2,0xaf,
+0x54,0x65,0x83,0x8e,0x68,0x15,0xb1,0x26,0x25,0xb0,0x10,0x3c,0x21,0x18,0x72,0x00,
+0x54,0x65,0x83,0xae,0x54,0x65,0x23,0x8e,0xb0,0x03,0x02,0x36,0x21,0x20,0x60,0x02,
+0x00,0x00,0x43,0xac,0x4d,0x01,0x00,0x0c,0x00,0x00,0x00,0x00,0x54,0x65,0x25,0x8e,
+0xec,0x00,0x02,0x36,0xbd,0x00,0x04,0x36,0x00,0x00,0x45,0xac,0x00,0x00,0x83,0x90,
+0xc2,0x00,0x10,0x36,0x34,0x00,0xbf,0x8f,0x10,0x00,0x63,0x34,0x00,0x00,0x83,0xa0,
+0x30,0x00,0xb6,0x8f,0x00,0x00,0x05,0xa6,0x2c,0x00,0xb5,0x8f,0x28,0x00,0xb4,0x8f,
+0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,
+0x01,0x00,0x02,0x24,0x08,0x00,0xe0,0x03,0x38,0x00,0xbd,0x27,0xe0,0xff,0xbd,0x27,
+0x25,0xb0,0x02,0x3c,0x14,0x00,0xb1,0xaf,0x18,0x00,0xbf,0xaf,0x10,0x00,0xb0,0xaf,
+0xbf,0x00,0x42,0x34,0x00,0x00,0x43,0x90,0x21,0x28,0x00,0x00,0x08,0x00,0x06,0x24,
+0x04,0x00,0x63,0x2c,0x12,0x00,0x60,0x14,0x21,0x88,0x80,0x00,0x00,0x60,0x02,0x40,
+0x01,0x00,0x41,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x02,0x80,0x03,0x3c,
+0x00,0x7b,0x63,0x24,0x04,0x00,0x64,0x8c,0x00,0x00,0x23,0xae,0x04,0x00,0x71,0xac,
+0x00,0x00,0x91,0xac,0x04,0x00,0x24,0xae,0x00,0x60,0x82,0x40,0x18,0x00,0xbf,0x8f,
+0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,
+0x08,0x00,0x82,0x94,0x02,0x80,0x04,0x3c,0x97,0x45,0x00,0x0c,0x25,0x20,0x44,0x00,
+0x00,0x60,0x10,0x40,0x01,0x00,0x01,0x36,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x08,0x00,0x25,0x8e,0x0c,0x00,0x26,0x96,0x14,0x00,0x27,0x96,0xf0,0x06,0x00,0x0c,
+0x09,0x00,0x04,0x24,0x04,0x00,0x23,0x8e,0x00,0x00,0x22,0x8e,0x21,0x20,0x20,0x02,
+0x00,0x00,0x62,0xac,0x04,0x00,0x43,0xac,0x00,0x00,0x31,0xae,0xbd,0x4e,0x00,0x0c,
+0x04,0x00,0x31,0xae,0x00,0x60,0x90,0x40,0x18,0x00,0xbf,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,0x02,0x80,0x02,0x3c,
+0x68,0x15,0x47,0x24,0x8c,0x64,0xe3,0x90,0xff,0xff,0xa5,0x30,0x09,0x00,0xa3,0x10,
+0x21,0x20,0xc0,0x00,0xfc,0x64,0xe2,0x8c,0x00,0x00,0x00,0x00,0x08,0x00,0xc2,0xac,
+0x06,0x65,0xe3,0x94,0x0e,0x00,0x02,0x24,0x14,0x00,0xc2,0xac,0x8b,0x07,0x00,0x08,
+0x0c,0x00,0xc3,0xac,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x00,0x80,0x03,0x3c,
+0x25,0xb0,0x02,0x3c,0xd0,0xff,0xbd,0x27,0x4c,0x1f,0x63,0x24,0x18,0x03,0x42,0x34,
+0x28,0x00,0xbf,0xaf,0x24,0x00,0xb3,0xaf,0x20,0x00,0xb2,0xaf,0x1c,0x00,0xb1,0xaf,
+0x18,0x00,0xb0,0xaf,0x00,0x00,0x43,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x00,0x60,0x81,0x40,0x2a,0xb0,0x02,0x3c,0x36,0x00,0x42,0x34,0x00,0x00,0x43,0x90,
+0x02,0x80,0x13,0x3c,0x68,0x15,0x66,0x26,0xc0,0x18,0x03,0x00,0x5c,0x65,0xc5,0x8c,
+0x23,0xb0,0x04,0x3c,0xf0,0x07,0x63,0x30,0xff,0x1f,0x02,0x3c,0x21,0x18,0x64,0x00,
+0xff,0xff,0x42,0x34,0x24,0x20,0x62,0x00,0x23,0x88,0x85,0x00,0x2b,0x38,0x85,0x00,
+0x00,0x04,0x22,0x26,0x00,0x65,0xc3,0x8c,0x0b,0x88,0x47,0x00,0x01,0x04,0x25,0x2e,
+0xfc,0x64,0xc3,0xac,0x60,0x65,0xc4,0xac,0x06,0x65,0xc0,0xa4,0x11,0x00,0xa0,0x14,
+0x05,0x65,0xc0,0xa0,0x00,0xfc,0x83,0x24,0x23,0x10,0x02,0x3c,0x0b,0x18,0x87,0x00,
+0xff,0x03,0x42,0x34,0x2b,0x10,0x43,0x00,0x33,0x00,0x40,0x14,0x00,0x00,0x00,0x00,
+0x23,0x88,0x83,0x00,0x2b,0x10,0x83,0x00,0x5c,0x65,0xc3,0xac,0x03,0x00,0x40,0x10,
+0x01,0x04,0x25,0x2e,0x00,0x04,0x31,0x26,0x01,0x04,0x25,0x2e,0x0e,0x00,0xa0,0x10,
+0x68,0x15,0x70,0x26,0x68,0x15,0x70,0x26,0x60,0x65,0x03,0x8e,0x5c,0x65,0x04,0x8e,
+0x00,0x00,0x00,0x00,0x2b,0x10,0x83,0x00,0x25,0x00,0x40,0x14,0x2b,0x10,0x64,0x00,
+0x51,0x00,0x40,0x14,0x25,0xb0,0x02,0x3c,0x80,0x00,0x03,0x24,0xd0,0x03,0x42,0x34,
+0x00,0x00,0x43,0xac,0x68,0x15,0x70,0x26,0x5c,0x65,0x03,0x96,0x2a,0xb0,0x02,0x3c,
+0x35,0x00,0x42,0x34,0xc2,0x88,0x03,0x00,0x00,0x00,0x51,0xa0,0x8f,0x10,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x06,0x65,0x03,0x96,0x25,0xb0,0x02,0x3c,0xb0,0x03,0x42,0x34,
+0x00,0x00,0x43,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,
+0x00,0x60,0x81,0x40,0xfc,0x4a,0x02,0x8e,0x80,0x00,0x03,0x3c,0x41,0xb0,0x04,0x3c,
+0x25,0x10,0x43,0x00,0x00,0x00,0x82,0xac,0x28,0x00,0xbf,0x8f,0xfc,0x4a,0x02,0xae,
+0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,
+0x08,0x00,0xe0,0x03,0x30,0x00,0xbd,0x27,0x00,0x08,0x00,0x08,0x00,0xfc,0x63,0x24,
+0xfc,0x64,0x05,0x8e,0x21,0x30,0x80,0x00,0xff,0xff,0x27,0x32,0x09,0x00,0x04,0x24,
+0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0xfc,0x64,0x03,0x8e,0x06,0x65,0x05,0x96,
+0x5c,0x65,0x02,0x8e,0x21,0x18,0x71,0x00,0x21,0x28,0x25,0x02,0x21,0x10,0x51,0x00,
+0x09,0x00,0x04,0x24,0x5c,0x65,0x02,0xae,0xfc,0x64,0x03,0xae,0x4d,0x01,0x00,0x0c,
+0x06,0x65,0x05,0xa6,0x68,0x15,0x70,0x26,0x5c,0x65,0x03,0x96,0x2a,0xb0,0x02,0x3c,
+0x35,0x00,0x42,0x34,0xc2,0x88,0x03,0x00,0x00,0x00,0x51,0xa0,0x8f,0x10,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x06,0x65,0x03,0x96,0x25,0xb0,0x02,0x3c,0xb0,0x03,0x42,0x34,
+0x00,0x00,0x43,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,
+0x00,0x60,0x81,0x40,0xfc,0x4a,0x02,0x8e,0x80,0x00,0x03,0x3c,0x41,0xb0,0x04,0x3c,
+0x25,0x10,0x43,0x00,0x00,0x00,0x82,0xac,0x28,0x00,0xbf,0x8f,0xfc,0x4a,0x02,0xae,
+0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,
+0x08,0x00,0xe0,0x03,0x30,0x00,0xbd,0x27,0x64,0x65,0x02,0x8e,0xfc,0x64,0x05,0x8e,
+0x21,0x30,0x80,0x00,0x23,0x88,0x44,0x00,0xff,0xff,0x27,0x32,0x09,0x00,0x04,0x24,
+0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0xfc,0x64,0x03,0x8e,0x06,0x65,0x02,0x96,
+0x60,0x65,0x12,0x96,0x21,0x18,0x71,0x00,0x21,0x10,0x22,0x02,0x23,0x10,0x11,0x3c,
+0xfc,0x64,0x03,0xae,0x06,0x65,0x02,0xa6,0x06,0x00,0x40,0x16,0x5c,0x65,0x11,0xae,
+0x09,0x00,0x04,0x24,0x4d,0x01,0x00,0x0c,0x68,0x15,0x70,0x26,0x46,0x08,0x00,0x08,
+0x00,0x00,0x00,0x00,0x4d,0x01,0x00,0x0c,0x09,0x00,0x04,0x24,0xfc,0x64,0x05,0x8e,
+0x09,0x00,0x04,0x24,0x23,0x10,0x06,0x3c,0x21,0x38,0x40,0x02,0x10,0x01,0x00,0x0c,
+0x10,0x00,0xa0,0xaf,0xfc,0x64,0x03,0x8e,0x06,0x65,0x02,0x96,0x21,0x20,0x51,0x02,
+0x21,0x18,0x72,0x00,0x21,0x10,0x42,0x02,0x5c,0x65,0x04,0xae,0x09,0x00,0x04,0x24,
+0xfc,0x64,0x03,0xae,0x75,0x08,0x00,0x08,0x06,0x65,0x02,0xa6,0x02,0x80,0x09,0x3c,
+0x68,0x15,0x28,0x25,0xdc,0x63,0x06,0x8d,0xff,0xff,0x02,0x34,0x3f,0x00,0xc2,0x10,
+0x21,0x38,0x80,0x00,0x2b,0x10,0xc7,0x00,0x30,0x00,0x40,0x10,0x02,0x19,0x06,0x00,
+0x21,0x10,0xc7,0x00,0x23,0x10,0x43,0x00,0x10,0x00,0x46,0x24,0xdc,0x63,0x06,0xad,
+0x68,0x15,0x26,0x25,0x04,0x40,0xc4,0x8c,0xe0,0x63,0x02,0xad,0xff,0xff,0x02,0x34,
+0x2f,0x00,0x82,0x10,0x00,0x00,0x00,0x00,0x2b,0x10,0x87,0x00,0x1f,0x00,0x40,0x10,
+0x02,0x19,0x04,0x00,0x21,0x10,0x87,0x00,0x23,0x10,0x43,0x00,0x10,0x00,0x44,0x24,
+0x04,0x40,0xc4,0xac,0xe0,0x63,0xc2,0xac,0xc0,0x10,0x05,0x00,0x21,0x10,0x45,0x00,
+0x80,0x10,0x02,0x00,0x21,0x10,0x45,0x00,0x68,0x15,0x23,0x25,0x80,0x10,0x02,0x00,
+0x21,0x28,0x43,0x00,0x68,0x51,0xa6,0x8c,0x00,0x21,0x07,0x00,0xff,0xff,0xc2,0x38,
+0x0a,0x30,0x82,0x00,0x2b,0x18,0xc7,0x00,0x07,0x00,0x60,0x10,0x21,0x10,0xc7,0x00,
+0x02,0x19,0x06,0x00,0x23,0x10,0x43,0x00,0x10,0x00,0x46,0x24,0x68,0x51,0xa6,0xac,
+0x08,0x00,0xe0,0x03,0x6c,0x51,0xa2,0xac,0x02,0x19,0x06,0x00,0x23,0x10,0x43,0x00,
+0x68,0x51,0xa2,0xac,0x08,0x00,0xe0,0x03,0x6c,0x51,0xa2,0xac,0x21,0x10,0x87,0x00,
+0x23,0x10,0x43,0x00,0xa5,0x08,0x00,0x08,0x04,0x40,0xc2,0xac,0x21,0x10,0xc7,0x00,
+0x68,0x15,0x26,0x25,0x04,0x40,0xc4,0x8c,0x23,0x10,0x43,0x00,0xdc,0x63,0x02,0xad,
+0xe0,0x63,0x02,0xad,0xff,0xff,0x02,0x34,0xd4,0xff,0x82,0x14,0x2b,0x10,0x87,0x00,
+0x00,0x21,0x07,0x00,0x9e,0x08,0x00,0x08,0x04,0x40,0xc4,0xac,0x00,0x31,0x04,0x00,
+0x91,0x08,0x00,0x08,0xdc,0x63,0x06,0xad,0x63,0x00,0x82,0x24,0x77,0x00,0x42,0x2c,
+0x00,0x00,0x85,0x28,0x04,0x00,0x40,0x10,0x21,0x18,0x00,0x00,0x64,0x00,0x82,0x24,
+0x64,0x00,0x03,0x24,0x0b,0x18,0x45,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,
+0x0c,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,0x3f,0x00,0x42,0x30,0x04,0x00,0x42,0x28,
+0x17,0x00,0x40,0x10,0x25,0xb0,0x02,0x3c,0x24,0x08,0x42,0x34,0x00,0x00,0x43,0x8c,
+0x00,0x00,0x00,0x00,0x00,0x02,0x63,0x30,0x16,0x00,0x60,0x14,0x01,0x00,0x02,0x24,
+0x05,0x00,0xa3,0x90,0x00,0x00,0x00,0x00,0x82,0x21,0x03,0x00,0x28,0x00,0x82,0x10,
+0xf5,0xff,0x02,0x24,0x02,0x00,0x82,0x28,0x39,0x00,0x40,0x14,0x02,0x00,0x02,0x24,
+0x2e,0x00,0x82,0x10,0xe9,0xff,0x02,0x24,0x03,0x00,0x02,0x24,0x24,0x00,0x82,0x10,
+0x3e,0x00,0x63,0x30,0x05,0x00,0xc4,0x24,0xd2,0x08,0x00,0x08,0x00,0x00,0x00,0x00,
+0x04,0x00,0xa4,0x90,0x00,0x00,0x00,0x00,0x42,0x20,0x04,0x00,0xd2,0x08,0x00,0x08,
+0x96,0xff,0x84,0x24,0x05,0x00,0xa3,0x90,0x00,0x00,0x00,0x00,0x60,0x00,0x64,0x30,
+0x42,0x21,0x04,0x00,0x0e,0x00,0x82,0x10,0x1f,0x00,0x62,0x30,0x02,0x00,0x82,0x28,
+0x1d,0x00,0x40,0x14,0x02,0x00,0x02,0x24,0x14,0x00,0x82,0x10,0x1f,0x00,0x62,0x30,
+0x03,0x00,0x02,0x24,0xeb,0xff,0x82,0x14,0x1f,0x00,0x62,0x30,0x40,0x10,0x02,0x00,
+0xdd,0xff,0x03,0x24,0x23,0x30,0x62,0x00,0xf6,0x08,0x00,0x08,0x05,0x00,0xc4,0x24,
+0x40,0x10,0x02,0x00,0xf5,0xff,0x03,0x24,0x0e,0x09,0x00,0x08,0x23,0x30,0x62,0x00,
+0x3e,0x00,0x63,0x30,0x23,0x30,0x43,0x00,0xf6,0x08,0x00,0x08,0x05,0x00,0xc4,0x24,
+0xdd,0xff,0x02,0x24,0x16,0x09,0x00,0x08,0x23,0x30,0x43,0x00,0x40,0x10,0x02,0x00,
+0xe9,0xff,0x03,0x24,0x0e,0x09,0x00,0x08,0x23,0x30,0x62,0x00,0x3e,0x00,0x63,0x30,
+0x16,0x09,0x00,0x08,0x23,0x30,0x43,0x00,0xd2,0xff,0x80,0x14,0x1f,0x00,0x62,0x30,
+0x40,0x10,0x02,0x00,0xf8,0xff,0x03,0x24,0x0e,0x09,0x00,0x08,0x23,0x30,0x62,0x00,
+0xcc,0xff,0x80,0x14,0x3e,0x00,0x63,0x30,0xf8,0xff,0x02,0x24,0x16,0x09,0x00,0x08,
+0x23,0x30,0x43,0x00,0xa0,0xff,0xbd,0x27,0x02,0x80,0x02,0x3c,0x4c,0x00,0xb5,0xaf,
+0x5c,0x00,0xbf,0xaf,0x58,0x00,0xbe,0xaf,0x54,0x00,0xb7,0xaf,0x50,0x00,0xb6,0xaf,
+0x48,0x00,0xb4,0xaf,0x44,0x00,0xb3,0xaf,0x40,0x00,0xb2,0xaf,0x3c,0x00,0xb1,0xaf,
+0x38,0x00,0xb0,0xaf,0x68,0x15,0x55,0x24,0x25,0xb0,0x03,0x3c,0x04,0x01,0x62,0x34,
+0x00,0x00,0x43,0x8c,0x44,0x65,0xa7,0x8e,0x00,0x00,0x00,0x00,0x33,0x00,0xe3,0x10,
+0x48,0x65,0xa3,0xae,0x2b,0x10,0x67,0x00,0xa8,0x00,0x40,0x14,0x2b,0x10,0xe3,0x00,
+0xd1,0x00,0x40,0x14,0x02,0x80,0x02,0x3c,0x68,0x15,0x44,0x24,0x18,0x65,0x83,0x94,
+0x02,0x80,0x02,0x3c,0x21,0x88,0x00,0x00,0x19,0x00,0x40,0x1a,0x25,0x98,0x62,0x00,
+0x21,0xb8,0x80,0x00,0x21,0xb0,0x80,0x00,0x01,0x00,0x14,0x24,0x21,0x20,0x00,0x00,
+0x21,0x80,0x93,0x00,0x00,0x00,0x05,0x8e,0x00,0x00,0x00,0x00,0x07,0x00,0xa0,0x10,
+0x01,0x00,0x22,0x26,0x04,0x00,0x02,0x8e,0x00,0xf0,0x03,0x3c,0x00,0x20,0x04,0x3c,
+0x24,0x10,0x43,0x00,0x1e,0x00,0x44,0x10,0x06,0x00,0x22,0x26,0xff,0xff,0x51,0x30,
+0x82,0x16,0x05,0x00,0x01,0x00,0x42,0x30,0x34,0x00,0x54,0x10,0x00,0x00,0x00,0x00,
+0x80,0x20,0x11,0x00,0x2a,0x10,0x92,0x00,0xed,0xff,0x40,0x14,0x00,0x00,0x00,0x00,
+0xbd,0x4e,0x00,0x0c,0x21,0x20,0xc0,0x03,0x02,0x80,0x02,0x3c,0x08,0x04,0x44,0x24,
+0x21,0x28,0x00,0x00,0x21,0x30,0x00,0x00,0x31,0x1c,0x00,0x0c,0x21,0x38,0x00,0x00,
+0x25,0xb0,0x03,0x3c,0x04,0x01,0x62,0x34,0x00,0x00,0x43,0x8c,0x44,0x65,0xa7,0x8e,
+0x00,0x00,0x00,0x00,0xcf,0xff,0xe3,0x14,0x48,0x65,0xa3,0xae,0x25,0xb0,0x03,0x3c,
+0x00,0x01,0x62,0x34,0x00,0x00,0x47,0xac,0x66,0x09,0x00,0x08,0x44,0x65,0xa7,0xae,
+0xb0,0x4c,0xe2,0x8e,0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x24,0xb0,0x4c,0xe2,0xae,
+0x0c,0x00,0x04,0x8e,0x0c,0x00,0x02,0x24,0x3f,0x00,0x83,0x30,0x64,0x00,0x62,0x10,
+0x21,0x28,0xe0,0x02,0x3f,0x00,0x83,0x30,0x0d,0x00,0x02,0x24,0x59,0x00,0x62,0x10,
+0x00,0x00,0x00,0x00,0x3f,0x00,0x83,0x30,0x0e,0x00,0x02,0x24,0x04,0x00,0x62,0x10,
+0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x8e,0x5b,0x09,0x00,0x08,0x06,0x00,0x22,0x26,
+0xbc,0x4c,0xe2,0x8e,0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x24,0xbc,0x4c,0xe2,0xae,
+0x00,0x00,0x05,0x8e,0x5b,0x09,0x00,0x08,0x06,0x00,0x22,0x26,0x00,0x40,0xc2,0x8e,
+0x00,0x00,0x00,0x00,0x02,0x12,0x02,0x00,0x0f,0x00,0x42,0x30,0x05,0x00,0x54,0x10,
+0xc2,0x13,0x05,0x00,0x1e,0x00,0x42,0x30,0x21,0x10,0x51,0x00,0x60,0x09,0x00,0x08,
+0xff,0xff,0x51,0x30,0x02,0x40,0xc2,0x92,0x00,0x00,0x00,0x00,0x1e,0x00,0x40,0x14,
+0x02,0x80,0x03,0x3c,0x04,0x00,0x03,0x8e,0x00,0x00,0x00,0x00,0x02,0x14,0x03,0x00,
+0x0f,0x00,0x42,0x30,0x17,0x00,0x40,0x14,0x02,0x17,0x03,0x00,0x03,0x00,0x44,0x30,
+0x08,0x00,0x80,0x10,0x00,0xc0,0x02,0x3c,0x24,0x10,0x62,0x00,0x11,0x00,0x40,0x14,
+0x03,0x00,0x02,0x24,0x10,0x00,0x82,0x10,0x02,0x80,0x03,0x3c,0x0f,0x00,0x80,0x10,
+0x68,0x15,0x63,0x24,0x80,0x10,0x11,0x00,0x21,0x28,0x53,0x00,0xec,0xff,0xa3,0x8c,
+0x25,0xb0,0x02,0x3c,0xd4,0x02,0x42,0x34,0x21,0x20,0x00,0x02,0x00,0x00,0x43,0xac,
+0xdc,0x08,0x00,0x0c,0x00,0x00,0x00,0x00,0x21,0x20,0x40,0x00,0x8b,0x08,0x00,0x0c,
+0x21,0x28,0x00,0x00,0x02,0x80,0x03,0x3c,0x68,0x15,0x63,0x24,0x02,0x40,0x62,0x90,
+0x00,0x00,0x00,0x00,0x85,0x00,0x54,0x10,0x00,0x00,0x00,0x00,0x02,0x80,0x04,0x3c,
+0x68,0x15,0x84,0x24,0x02,0x40,0x83,0x90,0x02,0x00,0x02,0x24,0x68,0x00,0x62,0x10,
+0x00,0x00,0x00,0x00,0x25,0xb0,0x03,0x3c,0x4c,0x00,0x63,0x34,0x00,0x00,0x62,0x90,
+0x00,0x00,0x00,0x00,0x03,0x00,0x42,0x30,0x08,0x00,0x54,0x10,0x02,0x80,0x04,0x3c,
+0x00,0x00,0x05,0x8e,0x00,0x00,0x00,0x00,0xc2,0x13,0x05,0x00,0x1e,0x00,0x42,0x30,
+0x21,0x10,0x51,0x00,0x60,0x09,0x00,0x08,0xff,0xff,0x51,0x30,0xd0,0x02,0x02,0x24,
+0x68,0x15,0x84,0x24,0xdc,0x63,0x82,0xac,0x00,0x00,0x05,0x8e,0xd3,0x09,0x00,0x08,
+0xc2,0x13,0x05,0x00,0xb8,0x4c,0xa2,0x8c,0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x24,
+0xb8,0x4c,0xa2,0xac,0x0c,0x00,0x04,0x8e,0x86,0x09,0x00,0x08,0x3f,0x00,0x83,0x30,
+0xb4,0x4c,0xe2,0x8e,0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x24,0xb4,0x4c,0xe2,0xae,
+0x0c,0x00,0x04,0x8e,0x82,0x09,0x00,0x08,0x3f,0x00,0x83,0x30,0x4c,0x65,0xa2,0x8e,
+0xff,0xff,0x71,0x30,0x23,0x10,0x47,0x00,0xff,0xff,0x50,0x30,0x21,0x18,0x11,0x02,
+0xff,0xff,0x72,0x30,0xa1,0x4e,0x00,0x0c,0x21,0x20,0x40,0x02,0x76,0x00,0x40,0x10,
+0x21,0xf0,0x40,0x00,0x08,0x00,0x42,0x8c,0x44,0x65,0xa6,0x8e,0x21,0x38,0x00,0x02,
+0x21,0x18,0x52,0x00,0x21,0x28,0x40,0x00,0x08,0x00,0x04,0x24,0x14,0x65,0xa3,0xae,
+0x18,0x65,0xa2,0xae,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0x4d,0x01,0x00,0x0c,
+0x08,0x00,0x04,0x24,0x18,0x65,0xa5,0x8e,0x25,0xb0,0x03,0x3c,0x24,0x10,0x02,0x3c,
+0x21,0x28,0xb0,0x00,0x00,0x01,0x70,0x34,0x00,0x00,0x02,0xae,0x21,0x38,0x20,0x02,
+0x08,0x00,0x04,0x24,0x24,0x10,0x06,0x3c,0x44,0x65,0xa2,0xae,0x10,0x01,0x00,0x0c,
+0x10,0x00,0xa0,0xaf,0x48,0x65,0xa3,0x8e,0x08,0x00,0x04,0x24,0x4d,0x01,0x00,0x0c,
+0x44,0x65,0xa3,0xae,0x44,0x65,0xa2,0x8e,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0xae,
+0x46,0x09,0x00,0x08,0x02,0x80,0x02,0x3c,0x23,0x10,0x67,0x00,0xff,0xff,0x52,0x30,
+0xa1,0x4e,0x00,0x0c,0x21,0x20,0x40,0x02,0x56,0x00,0x40,0x10,0x21,0xf0,0x40,0x00,
+0x08,0x00,0x42,0x8c,0x44,0x65,0xa6,0x8e,0x08,0x00,0x04,0x24,0x21,0x18,0x52,0x00,
+0x21,0x28,0x40,0x00,0x21,0x38,0x40,0x02,0x14,0x65,0xa3,0xae,0x18,0x65,0xa2,0xae,
+0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0x48,0x65,0xa3,0x8e,0x08,0x00,0x04,0x24,
+0x4d,0x01,0x00,0x0c,0x44,0x65,0xa3,0xae,0x44,0x65,0xa3,0x8e,0x25,0xb0,0x04,0x3c,
+0x00,0x01,0x82,0x34,0x00,0x00,0x43,0xac,0x46,0x09,0x00,0x08,0x02,0x80,0x02,0x3c,
+0x04,0x00,0x03,0x8e,0x00,0x00,0x00,0x00,0x02,0x14,0x03,0x00,0x0f,0x00,0x42,0x30,
+0x08,0x00,0x42,0x28,0x93,0xff,0x40,0x10,0x02,0x17,0x03,0x00,0x03,0x00,0x42,0x30,
+0x90,0xff,0x40,0x14,0x80,0x10,0x11,0x00,0x21,0x28,0x53,0x00,0xec,0xff,0xa3,0x8c,
+0x25,0xb0,0x02,0x3c,0xd4,0x02,0x42,0x34,0x21,0x20,0x00,0x02,0x00,0x00,0x43,0xac,
+0xdc,0x08,0x00,0x0c,0x00,0x00,0x00,0x00,0x21,0x20,0x40,0x00,0x8b,0x08,0x00,0x0c,
+0x21,0x28,0x00,0x00,0xca,0x09,0x00,0x08,0x25,0xb0,0x03,0x3c,0x04,0x00,0x03,0x8e,
+0x00,0x00,0x00,0x00,0x02,0x14,0x03,0x00,0x0f,0x00,0x42,0x30,0x08,0x00,0x42,0x28,
+0x06,0x00,0x40,0x10,0x00,0xc0,0x02,0x3c,0x02,0x17,0x03,0x00,0x03,0x00,0x42,0x30,
+0x0c,0x00,0x40,0x10,0x80,0x10,0x11,0x00,0x00,0xc0,0x02,0x3c,0x24,0x10,0x62,0x00,
+0x6f,0xff,0x40,0x14,0x02,0x80,0x04,0x3c,0x02,0x17,0x03,0x00,0x03,0x00,0x42,0x30,
+0x03,0x00,0x03,0x24,0x6b,0xff,0x43,0x10,0x68,0x15,0x84,0x24,0x67,0xff,0x40,0x10,
+0x80,0x10,0x11,0x00,0x21,0x28,0x53,0x00,0xec,0xff,0xa3,0x8c,0x25,0xb0,0x02,0x3c,
+0xd4,0x02,0x42,0x34,0x21,0x20,0x00,0x02,0x00,0x00,0x43,0xac,0xdc,0x08,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x21,0x20,0x40,0x00,0x8b,0x08,0x00,0x0c,0x21,0x28,0x00,0x00,
+0xc4,0x09,0x00,0x08,0x02,0x80,0x04,0x3c,0x25,0xb0,0x04,0x3c,0x44,0x44,0x02,0x3c,
+0xbc,0x02,0x83,0x34,0x44,0x44,0x42,0x34,0x00,0x00,0x62,0xac,0x67,0x09,0x00,0x08,
+0x02,0x80,0x02,0x3c,0x48,0x65,0xa5,0x8e,0x25,0xb0,0x04,0x3c,0x66,0x66,0x02,0x3c,
+0x00,0x01,0x83,0x34,0x66,0x66,0x42,0x34,0xbc,0x02,0x84,0x34,0x00,0x00,0x65,0xac,
+0x00,0x00,0x82,0xac,0x66,0x09,0x00,0x08,0x44,0x65,0xa5,0xae,0x00,0x60,0x02,0x40,
+0x01,0x00,0x41,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x02,0x80,0x03,0x3c,
+0xd8,0x8c,0x64,0xac,0x00,0x60,0x82,0x40,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x02,0x80,0x02,0x3c,0xd8,0x8c,0x45,0x8c,0x00,0x80,0x03,0x3c,0x25,0xb0,0x02,0x3c,
+0x18,0x03,0x42,0x34,0x10,0x2a,0x63,0x24,0x00,0x00,0x43,0xac,0x04,0x00,0x02,0x24,
+0x1e,0x00,0xa2,0x10,0x05,0x00,0xa2,0x2c,0x10,0x00,0x40,0x10,0x05,0x00,0x02,0x24,
+0x03,0x00,0x02,0x24,0x08,0x00,0xa2,0x10,0x00,0x19,0x04,0x00,0x80,0x10,0x04,0x00,
+0x21,0x10,0x44,0x00,0xc0,0x10,0x02,0x00,0x23,0x10,0x44,0x00,0x00,0x11,0x02,0x00,
+0x21,0x10,0x44,0x00,0x40,0x19,0x02,0x00,0xff,0xff,0x63,0x24,0xfe,0xff,0x60,0x14,
+0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0xf3,0xff,0xa2,0x10,
+0x06,0x00,0x02,0x24,0xf2,0xff,0xa2,0x14,0x80,0x10,0x04,0x00,0x40,0x11,0x04,0x00,
+0x23,0x10,0x44,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x44,0x00,0x00,0x19,0x02,0x00,
+0x23,0x18,0x62,0x00,0x9a,0x0a,0x00,0x08,0x00,0x19,0x03,0x00,0x80,0x10,0x04,0x00,
+0x21,0x10,0x44,0x00,0xc0,0x10,0x02,0x00,0x23,0x10,0x44,0x00,0x00,0x11,0x02,0x00,
+0x21,0x10,0x44,0x00,0x9a,0x0a,0x00,0x08,0x00,0x19,0x02,0x00,0x02,0x80,0x02,0x3c,
+0xd8,0x8c,0x45,0x8c,0x00,0x80,0x03,0x3c,0x25,0xb0,0x02,0x3c,0x18,0x03,0x42,0x34,
+0xcc,0x2a,0x63,0x24,0x00,0x00,0x43,0xac,0x05,0x00,0x02,0x24,0x10,0x00,0xa2,0x10,
+0x06,0x00,0xa2,0x2c,0x09,0x00,0x40,0x14,0x04,0x00,0x02,0x24,0x06,0x00,0x02,0x24,
+0x0f,0x00,0xa2,0x10,0x00,0x11,0x04,0x00,0xff,0xff,0x84,0x24,0xfe,0xff,0x80,0x14,
+0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0xfa,0xff,0xa2,0x14,
+0x80,0x10,0x04,0x00,0x21,0x10,0x44,0x00,0xc2,0x0a,0x00,0x08,0x40,0x20,0x02,0x00,
+0x80,0x10,0x04,0x00,0x21,0x10,0x44,0x00,0xc2,0x0a,0x00,0x08,0x80,0x20,0x02,0x00,
+0x23,0x10,0x44,0x00,0xc2,0x0a,0x00,0x08,0x40,0x20,0x02,0x00,0xff,0xff,0x85,0x30,
+0x21,0x30,0x00,0x00,0x25,0xb0,0x03,0x3c,0x2a,0xb0,0x04,0x3c,0xb4,0x00,0x63,0x34,
+0x01,0x00,0xa2,0x24,0x31,0x00,0x84,0x34,0x00,0x00,0x65,0xa0,0x00,0x00,0x85,0xa0,
+0xff,0xff,0x45,0x30,0x12,0x00,0xa0,0x10,0x01,0x00,0x03,0x24,0x28,0xb0,0x07,0x3c,
+0xe8,0x0a,0x00,0x08,0xff,0xff,0x08,0x24,0x00,0x00,0x83,0xa0,0x01,0x00,0x63,0x24,
+0xff,0xff,0x63,0x30,0x2b,0x10,0xa3,0x00,0x09,0x00,0x40,0x14,0x08,0x00,0xc6,0x24,
+0xf9,0xff,0x65,0x14,0x21,0x20,0xc7,0x00,0x01,0x00,0x63,0x24,0xff,0xff,0x63,0x30,
+0x2b,0x10,0xa3,0x00,0x00,0x00,0x88,0xa0,0xf9,0xff,0x40,0x10,0x08,0x00,0xc6,0x24,
+0x00,0x01,0xa2,0x2c,0x13,0x00,0x40,0x10,0x21,0x18,0xa0,0x00,0xff,0x00,0x08,0x24,
+0x28,0xb0,0x07,0x3c,0xfc,0x0a,0x00,0x08,0xff,0xff,0x09,0x24,0xff,0xff,0x43,0x30,
+0x00,0x00,0xa2,0xa0,0x00,0x01,0x62,0x2c,0x0a,0x00,0x40,0x10,0x08,0x00,0xc6,0x24,
+0x01,0x00,0x62,0x24,0xf9,0xff,0x68,0x14,0x21,0x28,0xc7,0x00,0x00,0x01,0x02,0x24,
+0xff,0xff,0x43,0x30,0x00,0x01,0x62,0x2c,0x00,0x00,0xa9,0xa0,0xf8,0xff,0x40,0x14,
+0x08,0x00,0xc6,0x24,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0xd8,0xff,0xbd,0x27,
+0x24,0x00,0xbf,0xaf,0x20,0x00,0xb4,0xaf,0x1c,0x00,0xb3,0xaf,0x18,0x00,0xb2,0xaf,
+0x14,0x00,0xb1,0xaf,0x10,0x00,0xb0,0xaf,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x25,0xb0,0x10,0x3c,0x42,0x00,0x14,0x36,
+0xff,0xff,0x02,0x24,0x00,0x00,0x82,0xa2,0xd8,0x00,0x05,0x36,0x40,0x00,0x11,0x36,
+0xa8,0x00,0x13,0x36,0xa0,0x00,0x12,0x36,0x00,0x10,0x03,0x24,0xa4,0x00,0x10,0x36,
+0x00,0x80,0x02,0x3c,0x00,0x00,0x23,0xa6,0x00,0x00,0xa0,0xa0,0x00,0x00,0x40,0xae,
+0x00,0x00,0x00,0xae,0x00,0x00,0x62,0xae,0x00,0x00,0xa3,0x90,0x80,0xff,0x02,0x24,
+0xfd,0x00,0x04,0x24,0x25,0x18,0x62,0x00,0xfc,0x17,0x02,0x24,0x00,0x00,0xa3,0xa0,
+0x00,0x00,0x22,0xa6,0xd3,0x0a,0x00,0x0c,0x00,0x00,0x00,0x00,0x02,0x80,0x02,0x3c,
+0x68,0x15,0x42,0x24,0x68,0x4b,0x45,0x8c,0x60,0x4b,0x43,0x8c,0x64,0x4b,0x44,0x8c,
+0xfc,0x37,0x02,0x24,0x00,0x00,0x43,0xae,0x00,0x00,0x04,0xae,0x00,0x00,0x65,0xae,
+0x00,0x00,0x22,0xa6,0x00,0x00,0x80,0xa2,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x00,0x60,0x81,0x40,0x24,0x00,0xbf,0x8f,0x20,0x00,0xb4,0x8f,0x1c,0x00,0xb3,0x8f,
+0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,
+0x28,0x00,0xbd,0x27,0xd0,0xff,0xbd,0x27,0x2c,0x00,0xbf,0xaf,0x28,0x00,0xb6,0xaf,
+0x24,0x00,0xb5,0xaf,0x20,0x00,0xb4,0xaf,0x1c,0x00,0xb3,0xaf,0x18,0x00,0xb2,0xaf,
+0x14,0x00,0xb1,0xaf,0x10,0x00,0xb0,0xaf,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x25,0xb0,0x10,0x3c,0x40,0x00,0x05,0x36,
+0x00,0x00,0xa2,0x94,0x24,0xfa,0x03,0x24,0xa8,0x00,0x13,0x36,0x24,0x10,0x43,0x00,
+0x00,0x00,0xa2,0xa4,0xa0,0x00,0x12,0x36,0xa4,0x00,0x10,0x36,0x00,0x00,0x55,0x8e,
+0x00,0x00,0x16,0x8e,0x00,0x00,0x71,0x8e,0x00,0x80,0x14,0x3c,0xfc,0x37,0x02,0x24,
+0x00,0x00,0x40,0xae,0xfd,0x00,0x04,0x24,0x00,0x00,0x00,0xae,0x21,0x88,0x34,0x02,
+0x00,0x00,0x74,0xae,0x00,0x00,0xa2,0xa4,0xd3,0x0a,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x00,0x00,0x55,0xae,0x00,0x00,0x16,0xae,0x00,0x00,0x71,0xae,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0x2c,0x00,0xbf,0x8f,0x28,0x00,0xb6,0x8f,
+0x24,0x00,0xb5,0x8f,0x20,0x00,0xb4,0x8f,0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,
+0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x30,0x00,0xbd,0x27,
+0xd0,0xff,0xbd,0x27,0x2c,0x00,0xbf,0xaf,0x28,0x00,0xb6,0xaf,0x24,0x00,0xb5,0xaf,
+0x20,0x00,0xb4,0xaf,0x1c,0x00,0xb3,0xaf,0x18,0x00,0xb2,0xaf,0x14,0x00,0xb1,0xaf,
+0x10,0x00,0xb0,0xaf,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,
+0x00,0x60,0x81,0x40,0x25,0xb0,0x10,0x3c,0x40,0x00,0x05,0x36,0x00,0x00,0xa2,0x94,
+0xaf,0xff,0x03,0x24,0xa8,0x00,0x13,0x36,0x24,0x10,0x43,0x00,0x00,0x00,0xa2,0xa4,
+0xa0,0x00,0x12,0x36,0xa4,0x00,0x10,0x36,0x00,0x00,0x55,0x8e,0x00,0x00,0x16,0x8e,
+0x00,0x00,0x71,0x8e,0x00,0x80,0x14,0x3c,0xfc,0x37,0x02,0x24,0x00,0x00,0x40,0xae,
+0xfd,0x00,0x04,0x24,0x00,0x00,0x00,0xae,0x21,0x88,0x34,0x02,0x00,0x00,0x74,0xae,
+0x00,0x00,0xa2,0xa4,0xd3,0x0a,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0x55,0xae,
+0x00,0x00,0x16,0xae,0x00,0x00,0x71,0xae,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x00,0x60,0x81,0x40,0x2c,0x00,0xbf,0x8f,0x28,0x00,0xb6,0x8f,0x24,0x00,0xb5,0x8f,
+0x20,0x00,0xb4,0x8f,0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x30,0x00,0xbd,0x27,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x25,0xb0,0x04,0x3c,
+0x40,0x00,0x84,0x34,0x00,0x00,0x82,0x94,0xd8,0xfd,0x03,0x24,0x24,0x10,0x43,0x00,
+0xfc,0x37,0x03,0x24,0x00,0x00,0x82,0xa4,0x00,0x00,0x83,0xa4,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x00,0x00,0x82,0x8c,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0xff,0xff,0xc6,0x30,
+0x10,0x00,0x02,0x24,0x0c,0x00,0xc2,0x10,0x11,0x00,0xc3,0x28,0x06,0x00,0x60,0x10,
+0x20,0x00,0x02,0x24,0x08,0x00,0x02,0x24,0x0d,0x00,0xc2,0x10,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x06,0x00,0xc2,0x10,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x85,0xa4,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x00,0x00,0x85,0xac,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x00,0x00,0x85,0xa0,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x25,0xb0,0x02,0x3c,
+0x0a,0x00,0x42,0x34,0x00,0x00,0x43,0x90,0xff,0xff,0xa5,0x24,0x00,0x2c,0x05,0x00,
+0xfd,0x00,0x63,0x30,0x03,0x2c,0x05,0x00,0xff,0xff,0x87,0x30,0x00,0x00,0x43,0xa0,
+0x1a,0x00,0xa0,0x04,0x00,0x00,0x00,0x00,0x21,0x30,0x40,0x00,0x07,0x10,0xa7,0x00,
+0x01,0x00,0x42,0x30,0xfd,0x00,0x64,0x30,0x00,0x00,0x42,0x38,0x02,0x00,0x63,0x34,
+0x0a,0x18,0x82,0x00,0x00,0x00,0xc3,0xa0,0x04,0x00,0x63,0x34,0x00,0x00,0xc3,0xa0,
+0x09,0x00,0x02,0x24,0xff,0xff,0x42,0x24,0xff,0xff,0x41,0x04,0xff,0xff,0x42,0x24,
+0xfb,0x00,0x63,0x30,0x00,0x00,0xc3,0xa0,0x04,0x00,0x02,0x24,0xff,0xff,0x42,0x24,
+0xff,0xff,0x41,0x04,0xff,0xff,0x42,0x24,0xff,0xff,0xa2,0x24,0x00,0x2c,0x02,0x00,
+0x03,0x2c,0x05,0x00,0xea,0xff,0xa1,0x04,0x07,0x10,0xa7,0x00,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x25,0xb0,0x02,0x3c,0x0a,0x00,0x42,0x34,0x00,0x00,0x43,0x90,
+0xff,0xff,0x84,0x24,0x00,0x24,0x04,0x00,0x03,0x24,0x04,0x00,0xff,0x00,0x65,0x30,
+0x1d,0x00,0x80,0x04,0x21,0x38,0x00,0x00,0x21,0x30,0x40,0x00,0x01,0x00,0x08,0x24,
+0x04,0x00,0xa5,0x34,0x00,0x00,0xc5,0xa0,0x00,0x00,0xc2,0x90,0x00,0x00,0x00,0x00,
+0xff,0x00,0x45,0x30,0x01,0x00,0xa3,0x30,0x05,0x00,0x60,0x10,0x04,0x00,0x02,0x24,
+0x04,0x10,0x88,0x00,0x25,0x10,0x47,0x00,0xff,0xff,0x47,0x30,0x04,0x00,0x02,0x24,
+0xff,0xff,0x42,0x24,0xff,0xff,0x41,0x04,0xff,0xff,0x42,0x24,0xfb,0x00,0xa5,0x30,
+0x00,0x00,0xc5,0xa0,0x09,0x00,0x02,0x24,0xff,0xff,0x42,0x24,0xff,0xff,0x41,0x04,
+0xff,0xff,0x42,0x24,0xff,0xff,0x82,0x24,0x00,0x24,0x02,0x00,0x03,0x24,0x04,0x00,
+0xe7,0xff,0x81,0x04,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0xe0,0x00,
+0xe0,0xff,0xbd,0x27,0x10,0x00,0xb0,0xaf,0x25,0xb0,0x10,0x3c,0x0a,0x00,0x10,0x36,
+0x18,0x00,0xbf,0xaf,0x14,0x00,0xb1,0xaf,0x00,0x00,0x02,0x92,0xff,0xff,0x91,0x30,
+0x03,0x00,0x05,0x24,0xc0,0x00,0x42,0x30,0x80,0x00,0x43,0x34,0x00,0x00,0x03,0xa2,
+0x04,0x00,0x63,0x34,0x00,0x00,0x03,0xa2,0xfb,0x00,0x63,0x30,0x00,0x00,0x03,0xa2,
+0x08,0x00,0x63,0x34,0x00,0x00,0x03,0xa2,0x04,0x00,0x63,0x34,0x00,0x00,0x03,0xa2,
+0xfb,0x00,0x63,0x30,0x00,0x00,0x03,0xa2,0xd7,0x0b,0x00,0x0c,0x06,0x00,0x04,0x24,
+0x42,0x20,0x11,0x00,0xd7,0x0b,0x00,0x0c,0x06,0x00,0x05,0x24,0xfd,0x0b,0x00,0x0c,
+0x10,0x00,0x04,0x24,0x00,0x00,0x03,0x92,0x18,0x00,0xbf,0x8f,0x14,0x00,0xb1,0x8f,
+0xc0,0x00,0x63,0x30,0x00,0x00,0x03,0xa2,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,
+0x20,0x00,0xbd,0x27,0xe0,0xff,0xbd,0x27,0x14,0x00,0xb1,0xaf,0xff,0xff,0xb1,0x30,
+0x18,0x00,0xb2,0xaf,0x10,0x00,0xb0,0xaf,0x1c,0x00,0xbf,0xaf,0x21,0x90,0xc0,0x00,
+0x0a,0x00,0x20,0x12,0xff,0xff,0x90,0x30,0x24,0x0c,0x00,0x0c,0x21,0x20,0x00,0x02,
+0xfe,0xff,0x23,0x26,0x02,0x00,0x04,0x26,0x00,0x00,0x42,0xa6,0xff,0xff,0x71,0x30,
+0xff,0xff,0x90,0x30,0xf8,0xff,0x20,0x16,0x02,0x00,0x52,0x26,0x1c,0x00,0xbf,0x8f,
+0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,
+0x20,0x00,0xbd,0x27,0x25,0xb0,0x03,0x3c,0x0a,0x00,0x68,0x34,0x00,0x00,0x02,0x91,
+0xff,0xff,0xa5,0x30,0xff,0x00,0x84,0x30,0x1f,0x00,0xa0,0x10,0xff,0x00,0x47,0x30,
+0x21,0x48,0x00,0x01,0x0c,0x00,0x6c,0x34,0x0b,0x00,0x6b,0x34,0xc0,0xff,0x0a,0x24,
+0x21,0x68,0x00,0x01,0x25,0x10,0xea,0x00,0xff,0x00,0x47,0x30,0x00,0x00,0x64,0xa1,
+0x00,0x00,0x27,0xa1,0x00,0x00,0x22,0x91,0x00,0x00,0x00,0x00,0xff,0x00,0x47,0x30,
+0xc0,0x00,0xe3,0x30,0x08,0x00,0x60,0x10,0x00,0x00,0x00,0x00,0x21,0x40,0xa0,0x01,
+0x00,0x00,0x02,0x91,0x00,0x00,0x00,0x00,0xff,0x00,0x47,0x30,0xc0,0x00,0xe3,0x30,
+0xfb,0xff,0x60,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x82,0x8d,0xfc,0xff,0xa3,0x24,
+0x04,0x00,0x84,0x24,0xff,0xff,0x65,0x30,0x00,0x00,0xc2,0xac,0xff,0x00,0x84,0x30,
+0xe8,0xff,0xa0,0x14,0x04,0x00,0xc6,0x24,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0xff,0x00,0x84,0x30,0x21,0x68,0xe0,0x00,0xff,0xff,0xa5,0x30,0xc0,0x50,0x04,0x00,
+0x00,0x60,0x0c,0x40,0x01,0x00,0x81,0x35,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x00,0x00,0xc2,0x90,0x01,0x00,0xc3,0x90,0x25,0xb0,0x07,0x3c,0x00,0x14,0x02,0x00,
+0x25,0x28,0xa2,0x00,0x00,0x1e,0x03,0x00,0x01,0x80,0x08,0x3c,0x25,0x20,0xa3,0x00,
+0x40,0x02,0xe9,0x34,0x25,0x18,0x48,0x01,0x44,0x02,0xe7,0x34,0x00,0x00,0xe4,0xac,
+0x00,0x00,0x23,0xad,0x03,0x00,0xc2,0x90,0x02,0x00,0xc4,0x90,0x04,0x00,0xc3,0x90,
+0x05,0x00,0xc5,0x90,0x00,0x12,0x02,0x00,0x25,0x20,0x82,0x00,0x00,0x1c,0x03,0x00,
+0x01,0x00,0x4a,0x25,0x25,0x20,0x83,0x00,0x00,0x2e,0x05,0x00,0x25,0x40,0x48,0x01,
+0x25,0x20,0x85,0x00,0x00,0x00,0xe4,0xac,0x01,0x00,0x4a,0x25,0x00,0x00,0x28,0xad,
+0x01,0x80,0x0b,0x3c,0x21,0x40,0x00,0x00,0x21,0x10,0xa8,0x01,0x01,0x00,0x43,0x90,
+0x00,0x00,0x45,0x90,0x02,0x00,0x44,0x90,0x03,0x00,0x46,0x90,0x00,0x1a,0x03,0x00,
+0x25,0x28,0xa3,0x00,0x00,0x24,0x04,0x00,0x25,0x28,0xa4,0x00,0x00,0x36,0x06,0x00,
+0x04,0x00,0x08,0x25,0x25,0x10,0x4b,0x01,0x25,0x20,0xa6,0x00,0x10,0x00,0x03,0x2d,
+0x00,0x00,0xe4,0xac,0x01,0x00,0x4a,0x25,0x00,0x00,0x22,0xad,0xee,0xff,0x60,0x14,
+0x00,0x00,0x00,0x00,0x00,0x60,0x8c,0x40,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0xff,0xff,0x84,0x30,0x42,0xb0,0x08,0x3c,0x80,0x10,0x04,0x00,0x21,0x10,0x48,0x00,
+0x04,0x00,0x46,0xac,0x00,0x00,0x07,0x91,0x40,0x18,0x04,0x00,0x03,0x00,0x06,0x24,
+0xff,0x00,0xe7,0x30,0x04,0x30,0x66,0x00,0x01,0x00,0x02,0x24,0x04,0x10,0x62,0x00,
+0x25,0x30,0xc7,0x00,0xff,0xff,0xa5,0x30,0x25,0x10,0x47,0x00,0x02,0x00,0xa0,0x14,
+0xff,0x00,0xc7,0x30,0xff,0x00,0x47,0x30,0x42,0xb0,0x02,0x3c,0x00,0x00,0x47,0xa0,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x42,0xb0,0x02,0x3c,0x03,0x00,0x47,0x34,
+0x00,0x00,0xe3,0x90,0xff,0x00,0x84,0x30,0x04,0x00,0x84,0x24,0xff,0x00,0x65,0x30,
+0x01,0x00,0x02,0x24,0x04,0x30,0x82,0x00,0x07,0x18,0x85,0x00,0x25,0xb0,0x02,0x3c,
+0xe8,0x03,0x42,0x34,0x01,0x00,0x63,0x30,0x21,0x20,0xc0,0x00,0x00,0x00,0x45,0xa0,
+0x02,0x00,0x60,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0xe6,0xa0,0x08,0x00,0xe0,0x03,
+0x24,0x10,0x85,0x00,0x00,0x60,0x03,0x40,0x01,0x00,0x61,0x34,0x01,0x00,0x21,0x38,
+0x00,0x60,0x81,0x40,0x02,0x80,0x02,0x3c,0xdc,0x8c,0x42,0x24,0x04,0x00,0x45,0x8c,
+0x00,0x00,0x82,0xac,0x04,0x00,0x44,0xac,0x00,0x00,0xa4,0xac,0x04,0x00,0x85,0xac,
+0x00,0x60,0x83,0x40,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x14,0x00,0x83,0x90,
+0x01,0x00,0x02,0x24,0x08,0x00,0x86,0xac,0x18,0x00,0x85,0xac,0x00,0x00,0x84,0xac,
+0x03,0x00,0x62,0x10,0x04,0x00,0x84,0xac,0xed,0x0c,0x00,0x08,0x0c,0x00,0x80,0xac,
+0x0c,0x00,0x82,0x8c,0xed,0x0c,0x00,0x08,0x10,0x00,0x82,0xac,0x00,0x60,0x03,0x40,
+0x01,0x00,0x61,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x04,0x00,0x85,0x8c,
+0x00,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0xa2,0xac,0x04,0x00,0x45,0xac,
+0x00,0x00,0x84,0xac,0x04,0x00,0x84,0xac,0x00,0x60,0x83,0x40,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0xd0,0xff,0xbd,0x27,0x28,0x00,0xb6,0xaf,0x24,0x00,0xb5,0xaf,
+0x20,0x00,0xb4,0xaf,0x14,0x00,0xb1,0xaf,0x2c,0x00,0xbf,0xaf,0x1c,0x00,0xb3,0xaf,
+0x18,0x00,0xb2,0xaf,0x10,0x00,0xb0,0xaf,0x00,0x80,0x16,0x3c,0x02,0x80,0x14,0x3c,
+0x02,0x80,0x11,0x3c,0x02,0x80,0x15,0x3c,0xc4,0x7d,0x24,0x8e,0x25,0xb0,0x02,0x3c,
+0x54,0x34,0xc3,0x26,0x18,0x03,0x42,0x34,0x00,0x00,0x43,0xac,0xdc,0x8c,0x90,0x8e,
+0x18,0x00,0x80,0x10,0xdc,0x8c,0x82,0x26,0x15,0x00,0x02,0x12,0x00,0x00,0x00,0x00,
+0x21,0x98,0x40,0x00,0x01,0x00,0x12,0x24,0x14,0x00,0x02,0x92,0x00,0x00,0x00,0x00,
+0x1d,0x00,0x52,0x10,0x00,0x00,0x00,0x00,0x09,0x00,0x40,0x14,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x03,0x8e,0xc4,0x7d,0x22,0x8e,0x00,0x00,0x00,0x00,0x23,0x20,0x62,0x00,
+0x2b,0x10,0x43,0x00,0x0e,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0x0c,0x00,0x04,0xae,
+0x00,0x00,0x10,0x8e,0x00,0x00,0x00,0x00,0xef,0xff,0x13,0x16,0x00,0x00,0x00,0x00,
+0xc4,0x7d,0x20,0xae,0x08,0x0c,0xa4,0x26,0x21,0x28,0x00,0x00,0x21,0x30,0x00,0x00,
+0x31,0x1c,0x00,0x0c,0x21,0x38,0x00,0x00,0x22,0x0d,0x00,0x08,0x00,0x00,0x00,0x00,
+0x08,0x00,0x02,0x8e,0x18,0x00,0x04,0x8e,0x09,0xf8,0x40,0x00,0x00,0x00,0x00,0x00,
+0x3c,0x0d,0x00,0x08,0x0c,0x00,0x02,0xae,0x0c,0x00,0x03,0x8e,0xc4,0x7d,0x22,0x8e,
+0x00,0x00,0x00,0x00,0x23,0x20,0x62,0x00,0x2b,0x10,0x43,0x00,0xe7,0xff,0x40,0x14,
+0x00,0x00,0x00,0x00,0x08,0x00,0x02,0x8e,0x18,0x00,0x04,0x8e,0x09,0xf8,0x40,0x00,
+0x00,0x00,0x00,0x00,0x10,0x00,0x03,0x8e,0x3c,0x0d,0x00,0x08,0x0c,0x00,0x03,0xae,
+0xff,0x00,0xa5,0x30,0x25,0xb0,0x02,0x3c,0x21,0x28,0xa2,0x00,0xff,0x00,0x84,0x30,
+0x60,0x01,0xa4,0xa0,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0xff,0x00,0x84,0x30,
+0x01,0x00,0x03,0x24,0x10,0x00,0x02,0x3c,0x04,0x18,0x83,0x00,0xf0,0x70,0x42,0x34,
+0x15,0x00,0x84,0x2c,0x06,0x00,0x80,0x10,0x24,0x28,0x62,0x00,0x0f,0x00,0x63,0x30,
+0x04,0x00,0xa0,0x14,0x01,0x00,0x02,0x24,0x02,0x00,0x60,0x14,0x02,0x00,0x02,0x24,
+0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0xff,0x00,0xa5,0x30,
+0x04,0x00,0xa2,0x2c,0x14,0x00,0x40,0x10,0xff,0x00,0x84,0x30,0x02,0x80,0x03,0x3c,
+0x8e,0x7d,0x62,0x90,0x00,0x00,0x00,0x00,0xef,0xff,0x42,0x24,0xff,0x00,0x42,0x30,
+0x02,0x00,0x42,0x2c,0x0e,0x00,0x40,0x10,0x02,0x00,0x03,0x24,0x24,0x00,0x83,0x10,
+0x0f,0x10,0x02,0x3c,0x03,0x00,0x82,0x28,0x14,0x00,0x40,0x10,0x03,0x00,0x02,0x24,
+0x01,0x00,0x02,0x24,0x2f,0x00,0x82,0x10,0x00,0x00,0x00,0x00,0xff,0x1f,0x02,0x3c,
+0x08,0x00,0xe0,0x03,0xff,0xff,0x42,0x34,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x35,0x00,0x83,0x10,0x0f,0x1f,0x02,0x3c,0x03,0x00,0x82,0x28,0x16,0x00,0x40,0x10,
+0x03,0x00,0x02,0x24,0x01,0x00,0x02,0x24,0xf4,0xff,0x82,0x14,0x00,0x00,0x00,0x00,
+0x0f,0x1f,0x02,0x3c,0x08,0x00,0xe0,0x03,0x00,0x80,0x42,0x34,0xf0,0xff,0x82,0x14,
+0xff,0x1f,0x02,0x3c,0x01,0x00,0x02,0x24,0x29,0x00,0xa2,0x10,0x0f,0x10,0x02,0x3c,
+0x02,0x00,0xa2,0x28,0x1f,0x00,0x40,0x14,0x00,0x00,0x00,0x00,0x28,0x00,0xa3,0x10,
+0x00,0x00,0x00,0x00,0xe5,0xff,0xa4,0x14,0x00,0x00,0x00,0x00,0x0f,0x10,0x02,0x3c,
+0x08,0x00,0xe0,0x03,0x00,0xf0,0x42,0x34,0xe1,0xff,0x82,0x14,0xff,0x1f,0x02,0x3c,
+0x01,0x00,0x02,0x24,0x1c,0x00,0xa2,0x10,0x0f,0x00,0x02,0x3c,0x02,0x00,0xa2,0x28,
+0x0b,0x00,0x40,0x14,0x00,0x00,0x00,0x00,0x1c,0x00,0xa3,0x10,0x00,0x00,0x00,0x00,
+0xd6,0xff,0xa4,0x14,0x00,0x00,0x00,0x00,0x0f,0x00,0x02,0x3c,0x08,0x00,0xe0,0x03,
+0x00,0xf0,0x42,0x34,0x0f,0x10,0x02,0x3c,0x08,0x00,0xe0,0x03,0x00,0x80,0x42,0x34,
+0xce,0xff,0xa0,0x14,0x00,0x00,0x00,0x00,0x0f,0x00,0x02,0x3c,0x08,0x00,0xe0,0x03,
+0x15,0xf0,0x42,0x34,0xc9,0xff,0xa0,0x14,0x00,0x00,0x00,0x00,0x0f,0x10,0x02,0x3c,
+0x08,0x00,0xe0,0x03,0x15,0xf0,0x42,0x34,0x08,0x00,0xe0,0x03,0x00,0xf0,0x42,0x34,
+0x08,0x00,0xe0,0x03,0x10,0xf0,0x42,0x34,0x08,0x00,0xe0,0x03,0x10,0xf0,0x42,0x34,
+0x0f,0x10,0x02,0x3c,0x08,0x00,0xe0,0x03,0x05,0xf0,0x42,0x34,0x0f,0x00,0x02,0x3c,
+0x08,0x00,0xe0,0x03,0x05,0xf0,0x42,0x34,0xc0,0x40,0x04,0x00,0x21,0x18,0x04,0x01,
+0x80,0x18,0x03,0x00,0x21,0x18,0x64,0x00,0x02,0x80,0x02,0x3c,0x80,0x18,0x03,0x00,
+0x68,0x15,0x42,0x24,0x21,0x18,0x62,0x00,0x74,0x51,0x66,0x8c,0x21,0x38,0x60,0x00,
+0x7a,0x51,0x60,0xa0,0x7b,0x51,0x60,0xa0,0x1c,0x00,0x05,0x24,0xdf,0x0d,0x00,0x08,
+0x01,0x00,0x03,0x24,0x08,0x00,0xa0,0x04,0x21,0x10,0x04,0x01,0x04,0x10,0xa3,0x00,
+0x24,0x10,0xc2,0x00,0xfb,0xff,0x40,0x10,0xff,0xff,0xa5,0x24,0x01,0x00,0xa5,0x24,
+0x7a,0x51,0xe5,0xa0,0x21,0x10,0x04,0x01,0x80,0x10,0x02,0x00,0x21,0x10,0x44,0x00,
+0x02,0x80,0x03,0x3c,0x80,0x10,0x02,0x00,0x68,0x15,0x63,0x24,0x21,0x18,0x43,0x00,
+0x74,0x51,0x66,0x8c,0x21,0x28,0x00,0x00,0xf3,0x0d,0x00,0x08,0x01,0x00,0x07,0x24,
+0x1d,0x00,0xa2,0x28,0x08,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0x04,0x10,0xa7,0x00,
+0x24,0x10,0xc2,0x00,0xfa,0xff,0x40,0x10,0x01,0x00,0xa5,0x24,0xff,0xff,0xa5,0x24,
+0x08,0x00,0xe0,0x03,0x7b,0x51,0x65,0xa0,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0xc8,0xff,0xbd,0x27,0x28,0x00,0xb6,0xaf,0x02,0x80,0x16,0x3c,0x30,0x00,0xbe,0xaf,
+0x2c,0x00,0xb7,0xaf,0x24,0x00,0xb5,0xaf,0x20,0x00,0xb4,0xaf,0x18,0x00,0xb2,0xaf,
+0x14,0x00,0xb1,0xaf,0x01,0x00,0x15,0x24,0x21,0x88,0x00,0x00,0x68,0x15,0xde,0x26,
+0x21,0xa0,0x00,0x00,0x21,0x90,0x00,0x00,0x25,0xb0,0x17,0x3c,0x34,0x00,0xbf,0xaf,
+0x1c,0x00,0xb3,0xaf,0x14,0x0e,0x00,0x08,0x10,0x00,0xb0,0xaf,0x01,0x00,0x31,0x26,
+0x20,0x00,0x22,0x2e,0x94,0x00,0x52,0x26,0x2e,0x00,0x40,0x10,0x94,0x00,0x94,0x26,
+0x68,0x15,0xc2,0x26,0x21,0x30,0x42,0x02,0x78,0x51,0xc5,0x8c,0x00,0x00,0x00,0x00,
+0x02,0x13,0x05,0x00,0x01,0x00,0x42,0x30,0xf4,0xff,0x55,0x14,0x42,0x1a,0x05,0x00,
+0x68,0x51,0xc2,0x8c,0x07,0x00,0x64,0x30,0x02,0x11,0x02,0x00,0x7f,0x00,0x43,0x30,
+0x2d,0x00,0x95,0x10,0x07,0x00,0xb3,0x30,0x02,0x00,0x82,0x28,0x3a,0x00,0x40,0x14,
+0x02,0x00,0x02,0x24,0x30,0x00,0x82,0x10,0x03,0x00,0x02,0x24,0x3c,0x00,0x82,0x10,
+0x1a,0x00,0x62,0x2c,0x21,0x80,0x9e,0x02,0x78,0x51,0x02,0x8e,0x04,0x00,0x63,0x2e,
+0x42,0x12,0x02,0x00,0x0a,0x00,0x60,0x10,0x07,0x00,0x44,0x30,0x73,0x0d,0x00,0x0c,
+0x21,0x28,0x60,0x02,0x80,0x20,0x13,0x00,0x70,0x51,0x02,0xae,0x21,0x20,0x97,0x00,
+0x84,0x01,0x83,0x8c,0x00,0x00,0x00,0x00,0x24,0x18,0x62,0x00,0x74,0x51,0x03,0xae,
+0xce,0x0d,0x00,0x0c,0x21,0x20,0x20,0x02,0x21,0x10,0x37,0x02,0x01,0x00,0x31,0x26,
+0x60,0x01,0x43,0x90,0x20,0x00,0x22,0x2e,0x94,0x00,0x52,0x26,0xd4,0xff,0x40,0x14,
+0x94,0x00,0x94,0x26,0x34,0x00,0xbf,0x8f,0x30,0x00,0xbe,0x8f,0x2c,0x00,0xb7,0x8f,
+0x28,0x00,0xb6,0x8f,0x24,0x00,0xb5,0x8f,0x20,0x00,0xb4,0x8f,0x1c,0x00,0xb3,0x8f,
+0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x38,0x00,0xbd,0x27,0x32,0x00,0x62,0x2c,0xda,0xff,0x40,0x10,
+0x21,0x80,0x9e,0x02,0xff,0xf1,0x03,0x24,0x24,0x10,0xa3,0x00,0x00,0x04,0x42,0x34,
+0x29,0x0e,0x00,0x08,0x78,0x51,0xc2,0xac,0x38,0x00,0x62,0x2c,0x12,0x00,0x40,0x14,
+0x14,0x00,0x62,0x2c,0xff,0xf1,0x03,0x24,0x24,0x10,0xa3,0x00,0x00,0x02,0x42,0x34,
+0x29,0x0e,0x00,0x08,0x78,0x51,0xc2,0xac,0xcb,0xff,0x80,0x14,0x21,0x80,0x9e,0x02,
+0xff,0xf1,0x03,0x24,0x24,0x10,0xa3,0x00,0x2a,0x0e,0x00,0x08,0x78,0x51,0xc2,0xac,
+0xc5,0xff,0x40,0x14,0x21,0x80,0x9e,0x02,0xff,0xf1,0x03,0x24,0x24,0x10,0xa3,0x00,
+0x54,0x0e,0x00,0x08,0x00,0x04,0x42,0x34,0xbf,0xff,0x40,0x10,0x21,0x80,0x9e,0x02,
+0xff,0xf1,0x03,0x24,0x24,0x10,0xa3,0x00,0x00,0x06,0x42,0x34,0x2a,0x0e,0x00,0x08,
+0x78,0x51,0xc2,0xac,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0xd8,0xff,0xbd,0x27,
+0x10,0x00,0xb0,0xaf,0xc0,0x80,0x04,0x00,0x21,0x80,0x04,0x02,0x80,0x80,0x10,0x00,
+0x21,0x80,0x04,0x02,0x02,0x80,0x02,0x3c,0x68,0x15,0x42,0x24,0x80,0x80,0x10,0x00,
+0x20,0x00,0xbf,0xaf,0x1c,0x00,0xb3,0xaf,0x18,0x00,0xb2,0xaf,0x21,0x80,0x02,0x02,
+0x14,0x00,0xb1,0xaf,0x78,0x51,0x03,0x8e,0x25,0xb0,0x02,0x3c,0x80,0x01,0x53,0x34,
+0x07,0x00,0x63,0x30,0x80,0x18,0x03,0x00,0x21,0x18,0x62,0x00,0x00,0x00,0x71,0x92,
+0x70,0x51,0x05,0x8e,0x84,0x01,0x62,0x8c,0x21,0x90,0x80,0x00,0xff,0x00,0x31,0x32,
+0x24,0x10,0x45,0x00,0xce,0x0d,0x00,0x0c,0x74,0x51,0x02,0xae,0x7a,0x51,0x04,0x92,
+0x5c,0x0d,0x00,0x0c,0xff,0x00,0x45,0x32,0x7a,0x51,0x04,0x92,0x63,0x0d,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x38,0x04,0x00,0x03,0x24,0x0a,0x88,0x62,0x00,
+0x00,0x00,0x71,0xa2,0x20,0x00,0xbf,0x8f,0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,
+0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x28,0x00,0xbd,0x27,
+0xff,0xff,0x84,0x30,0x00,0x02,0x82,0x30,0x07,0x00,0x03,0x24,0x0d,0x00,0x40,0x14,
+0x0b,0x00,0x84,0x30,0x0c,0x00,0x82,0x2c,0x0a,0x00,0x40,0x10,0x00,0x00,0x00,0x00,
+0x02,0x80,0x03,0x3c,0x80,0x10,0x04,0x00,0xf0,0x91,0x63,0x24,0x21,0x10,0x43,0x00,
+0x00,0x00,0x44,0x8c,0x00,0x00,0x00,0x00,0x08,0x00,0x80,0x00,0x00,0x00,0x00,0x00,
+0x07,0x00,0x03,0x24,0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,0x06,0x00,0x03,0x24,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,0x05,0x00,0x03,0x24,0x08,0x00,0xe0,0x03,
+0x21,0x10,0x60,0x00,0x04,0x00,0x03,0x24,0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,
+0x03,0x00,0x03,0x24,0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,0x02,0x00,0x03,0x24,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,0x01,0x00,0x03,0x24,0x08,0x00,0xe0,0x03,
+0x21,0x10,0x60,0x00,0x21,0x18,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,
+0xa0,0xff,0xbd,0x27,0x02,0x80,0x02,0x3c,0x58,0x00,0xbe,0xaf,0x54,0x00,0xb7,0xaf,
+0x50,0x00,0xb6,0xaf,0x4c,0x00,0xb5,0xaf,0x48,0x00,0xb4,0xaf,0x40,0x00,0xb2,0xaf,
+0x3c,0x00,0xb1,0xaf,0x5c,0x00,0xbf,0xaf,0x44,0x00,0xb3,0xaf,0x38,0x00,0xb0,0xaf,
+0x20,0x92,0x42,0x24,0x00,0x00,0x53,0x8c,0x08,0x00,0x03,0x24,0x02,0x80,0x0b,0x3c,
+0x21,0x90,0x00,0x00,0x21,0xa0,0x00,0x00,0x21,0xb8,0x00,0x00,0x21,0xf0,0x00,0x00,
+0x21,0xa8,0x00,0x00,0x21,0xb0,0x00,0x00,0x21,0x88,0x60,0x02,0x10,0x00,0xa3,0xaf,
+0x14,0x00,0xa0,0xaf,0x18,0x00,0xa0,0xaf,0x1c,0x00,0xa0,0xaf,0x20,0x00,0xa0,0xaf,
+0x24,0x00,0xa0,0xaf,0x28,0x00,0xa0,0xaf,0x7a,0x0f,0x00,0x08,0x2c,0x00,0xa0,0xaf,
+0x44,0x51,0x22,0xae,0x60,0x51,0x24,0x8e,0x5c,0x51,0x27,0x8e,0x48,0x51,0x28,0x8e,
+0x4c,0x51,0x25,0x8e,0x54,0x51,0x26,0x8e,0x58,0x51,0x23,0x8e,0x21,0x38,0xe4,0x00,
+0x02,0x80,0x04,0x3c,0x68,0x15,0x84,0x24,0x21,0x10,0x04,0x02,0x21,0x40,0x05,0x01,
+0x21,0x30,0xc3,0x00,0xca,0x44,0x42,0x90,0x44,0x51,0x2a,0x8e,0x0c,0x00,0xe0,0x10,
+0x21,0x48,0x00,0x00,0x2b,0x48,0x47,0x00,0x0b,0x00,0x20,0x15,0x02,0x80,0x02,0x3c,
+0x07,0x00,0x02,0x2e,0x59,0x01,0x40,0x14,0xc0,0x10,0x07,0x00,0x0c,0x00,0x02,0x24,
+0x55,0x01,0x02,0x12,0x0d,0x00,0x02,0x24,0x54,0x01,0x02,0x12,0xc0,0x10,0x07,0x00,
+0x92,0x00,0x20,0x11,0x02,0x80,0x02,0x3c,0x68,0x15,0x42,0x24,0x80,0x18,0x10,0x00,
+0x21,0x18,0x62,0x00,0x21,0x20,0x30,0x02,0xb6,0x51,0x85,0x90,0xec,0x44,0x62,0x8c,
+0x00,0x00,0x00,0x00,0x04,0x10,0xa2,0x00,0x2b,0x10,0x4a,0x00,0x87,0x00,0x40,0x10,
+0x00,0x00,0x00,0x00,0xd4,0x51,0x22,0x8e,0x01,0x00,0x07,0x24,0x04,0x18,0x07,0x02,
+0x24,0x10,0x43,0x00,0xf0,0x00,0x40,0x10,0x1c,0x00,0x02,0x2e,0x21,0x28,0x30,0x02,
+0x7c,0x51,0xa6,0x90,0xb6,0x51,0xa2,0x90,0x0a,0x00,0x04,0x24,0xff,0x00,0xc3,0x30,
+0x04,0x20,0x44,0x00,0x2a,0x18,0x64,0x00,0xe7,0x00,0x60,0x10,0x1c,0x00,0x02,0x2e,
+0x01,0x00,0xc2,0x24,0xff,0x00,0x43,0x30,0x56,0x01,0x64,0x10,0x7c,0x51,0xa2,0xa0,
+0x68,0x15,0x65,0x25,0x80,0x10,0x10,0x00,0x21,0x10,0x45,0x00,0x60,0x45,0x44,0x8c,
+0xec,0x44,0x43,0x8c,0x21,0x30,0xc5,0x02,0x40,0x10,0x04,0x00,0x21,0x10,0x44,0x00,
+0x21,0x18,0x62,0x00,0x82,0x50,0x03,0x00,0x44,0x51,0xca,0xac,0x8c,0x65,0xa3,0x8c,
+0xff,0xff,0x02,0x34,0x07,0x00,0x62,0x10,0x21,0x20,0x00,0x02,0x21,0x20,0x00,0x02,
+0xff,0x00,0x45,0x32,0x5c,0x0d,0x00,0x0c,0x30,0x00,0xab,0xaf,0x30,0x00,0xab,0x8f,
+0x21,0x20,0x00,0x02,0x63,0x0d,0x00,0x0c,0x30,0x00,0xab,0xaf,0x10,0x00,0xa4,0x8f,
+0x01,0x00,0x42,0x38,0x04,0x00,0x03,0x24,0x0a,0x20,0x62,0x00,0x10,0x00,0xa4,0xaf,
+0x30,0x00,0xab,0x8f,0x11,0x00,0x40,0x16,0x68,0x15,0x62,0x25,0x58,0x51,0x47,0x8c,
+0x54,0x51,0x43,0x8c,0x4c,0x51,0x44,0x94,0x48,0x51,0x45,0x94,0x50,0x51,0x46,0x94,
+0x21,0x18,0x67,0x00,0x00,0x24,0x04,0x00,0x25,0xb0,0x02,0x3c,0x00,0x1c,0x03,0x00,
+0x21,0x28,0xa4,0x00,0x21,0x30,0xc3,0x00,0x6c,0x0c,0x44,0x34,0x68,0x0c,0x42,0x34,
+0x00,0x00,0x45,0xac,0x00,0x00,0x86,0xac,0x68,0x15,0x62,0x25,0x21,0x10,0x82,0x02,
+0x58,0x51,0x40,0xac,0x5c,0x51,0x40,0xac,0x60,0x51,0x40,0xac,0x48,0x51,0x40,0xac,
+0x4c,0x51,0x40,0xac,0x50,0x51,0x40,0xac,0x54,0x51,0x40,0xac,0x2c,0x00,0xa2,0x8f,
+0x28,0x00,0xa4,0x8f,0x01,0x00,0x52,0x26,0x94,0x00,0x42,0x24,0x2c,0x00,0xa2,0xaf,
+0x24,0x00,0xa2,0x8f,0x94,0x00,0x84,0x24,0x28,0x00,0xa4,0xaf,0x94,0x00,0x42,0x24,
+0x20,0x00,0xa4,0x8f,0x24,0x00,0xa2,0xaf,0x1c,0x00,0xa2,0x8f,0x94,0x00,0x84,0x24,
+0x20,0x00,0xa4,0xaf,0x94,0x00,0x42,0x24,0x18,0x00,0xa4,0x8f,0x1c,0x00,0xa2,0xaf,
+0x14,0x00,0xa2,0x8f,0x94,0x00,0x84,0x24,0x20,0x00,0x43,0x2a,0x94,0x00,0x42,0x24,
+0x94,0x00,0x31,0x26,0x94,0x00,0xd6,0x26,0x94,0x00,0xb5,0x26,0x18,0x00,0xa4,0xaf,
+0x14,0x00,0xa2,0xaf,0x94,0x00,0xde,0x27,0x94,0x00,0x73,0x26,0x94,0x00,0xf7,0x26,
+0xe5,0x00,0x60,0x10,0x94,0x00,0x94,0x26,0x78,0x51,0x22,0x8e,0x00,0x00,0x00,0x00,
+0x02,0x13,0x02,0x00,0x01,0x00,0x42,0x30,0xd3,0xff,0x40,0x10,0x25,0xb0,0x02,0x3c,
+0x21,0x10,0x42,0x02,0x60,0x01,0x44,0x90,0x60,0x51,0x23,0x8e,0x5c,0x51,0x26,0x8e,
+0xff,0x00,0x90,0x30,0x02,0x80,0x04,0x3c,0x68,0x15,0x84,0x24,0x21,0x10,0x04,0x02,
+0x73,0x44,0x44,0x90,0x56,0x44,0x45,0x90,0x44,0x51,0x27,0x8e,0x18,0x00,0x64,0x00,
+0x12,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x00,0xc5,0x00,
+0x12,0x30,0x00,0x00,0x21,0x30,0xc3,0x00,0x2b,0x10,0xe6,0x00,0x54,0xff,0x40,0x10,
+0x23,0x10,0xe6,0x00,0xe9,0x0e,0x00,0x08,0x44,0x51,0x20,0xae,0x62,0x00,0xe0,0x10,
+0x00,0x00,0x00,0x00,0x63,0x00,0x20,0x15,0x68,0x15,0x62,0x25,0x40,0x10,0x07,0x00,
+0x21,0x10,0x47,0x00,0x82,0x10,0x02,0x00,0x2b,0x10,0x46,0x00,0x99,0xff,0x40,0x10,
+0x21,0x20,0x00,0x02,0x68,0x15,0x68,0x25,0x21,0x20,0xa8,0x02,0x21,0x30,0x90,0x00,
+0xd4,0x51,0x83,0x8c,0x01,0x00,0x05,0x24,0x04,0x10,0x05,0x02,0x99,0x51,0xc7,0x90,
+0x27,0x10,0x02,0x00,0x24,0x18,0x62,0x00,0xd4,0x51,0x83,0xac,0x09,0x00,0xe5,0x10,
+0x7c,0x51,0xc0,0xa0,0x18,0x00,0xa2,0x8f,0x21,0x38,0x00,0x00,0x21,0x20,0x48,0x00,
+0x21,0x18,0x87,0x00,0x01,0x00,0xe7,0x24,0x1d,0x00,0xe2,0x28,0xfc,0xff,0x40,0x14,
+0xb6,0x51,0x60,0xa0,0x14,0x00,0xa4,0x8f,0x68,0x15,0x63,0x25,0x21,0x50,0x60,0x00,
+0x21,0x10,0x83,0x00,0x21,0x10,0x50,0x00,0x99,0x51,0x40,0xa0,0x02,0x80,0x03,0x3c,
+0x02,0x80,0x02,0x3c,0x4c,0x91,0x49,0x24,0xd8,0x90,0x68,0x24,0x21,0x38,0x00,0x00,
+0x80,0x18,0x07,0x00,0x21,0x10,0x69,0x00,0x21,0x20,0x68,0x00,0x00,0x00,0x46,0x8c,
+0x00,0x00,0x85,0x8c,0x01,0x00,0xe7,0x24,0x21,0x18,0x6a,0x00,0x1d,0x00,0xe2,0x28,
+0xec,0x44,0x65,0xac,0xf6,0xff,0x40,0x14,0x60,0x45,0x66,0xac,0x14,0x00,0x00,0x12,
+0x68,0x15,0x63,0x25,0x7b,0x51,0x62,0x92,0xff,0xff,0x07,0x26,0x2a,0x10,0xe2,0x00,
+0x0e,0x00,0x40,0x14,0x02,0x80,0x0b,0x3c,0x68,0x15,0x62,0x25,0x21,0x10,0xc2,0x03,
+0x7b,0x51,0x45,0x90,0x74,0x51,0x44,0x8c,0x01,0x00,0x06,0x24,0x04,0x18,0xe6,0x00,
+0x24,0x10,0x83,0x00,0xb3,0x00,0x43,0x10,0x00,0x00,0x00,0x00,0xff,0xff,0xe7,0x24,
+0x2a,0x10,0xe5,0x00,0xfa,0xff,0x40,0x10,0x04,0x18,0xe6,0x00,0x68,0x15,0x63,0x25,
+0x80,0x10,0x10,0x00,0x21,0x10,0x43,0x00,0x60,0x45,0x45,0x8c,0xec,0x44,0x44,0x8c,
+0x02,0x80,0x03,0x3c,0x40,0x10,0x05,0x00,0x8e,0x7d,0x66,0x90,0x21,0x10,0x45,0x00,
+0x21,0x20,0x82,0x00,0x22,0x00,0x02,0x24,0x98,0x00,0xc2,0x10,0x82,0x50,0x04,0x00,
+0xd4,0x51,0x63,0x8e,0x01,0x00,0x02,0x24,0x04,0x10,0x02,0x02,0x25,0x18,0x62,0x00,
+0xd4,0x51,0x63,0xae,0x68,0x15,0x63,0x25,0x21,0x10,0xe3,0x02,0x44,0x51,0x4a,0xac,
+0x8c,0x65,0x64,0x8c,0xff,0xff,0x02,0x34,0x3c,0xff,0x82,0x14,0x21,0x20,0x00,0x02,
+0x39,0x0f,0x00,0x08,0x00,0x00,0x00,0x00,0x3e,0xff,0x20,0x11,0x21,0x20,0x00,0x02,
+0x68,0x15,0x62,0x25,0x80,0x18,0x10,0x00,0x21,0x18,0x62,0x00,0x60,0x45,0x64,0x8c,
+0x00,0x00,0x00,0x00,0x2b,0x20,0x44,0x01,0x36,0xff,0x80,0x10,0x21,0x20,0x00,0x02,
+0xa2,0x0f,0x00,0x08,0x68,0x15,0x68,0x25,0x1e,0xff,0x40,0x10,0x68,0x15,0x65,0x25,
+0x21,0x20,0x30,0x02,0x99,0x51,0x83,0x90,0x01,0x00,0x02,0x24,0x63,0x00,0x62,0x10,
+0x02,0x80,0x02,0x3c,0x2c,0x00,0xa3,0x8f,0x68,0x15,0x42,0x24,0x21,0x38,0x00,0x00,
+0x21,0x20,0x62,0x00,0x21,0x18,0x87,0x00,0x01,0x00,0xe7,0x24,0x1d,0x00,0xe2,0x28,
+0xfc,0xff,0x40,0x14,0xb6,0x51,0x60,0xa0,0x28,0x00,0xa3,0x8f,0x02,0x80,0x0b,0x3c,
+0x68,0x15,0x65,0x25,0x21,0x30,0x65,0x00,0xd4,0x51,0xc2,0x8c,0x01,0x00,0x03,0x24,
+0x04,0x18,0x03,0x02,0x27,0x18,0x03,0x00,0x21,0x20,0xd0,0x00,0x24,0x10,0x43,0x00,
+0x99,0x51,0x80,0xa0,0xd4,0x51,0xc2,0xac,0x12,0x00,0x00,0x16,0x7c,0x51,0x80,0xa0,
+0x7a,0x51,0xc2,0x90,0x00,0x00,0x00,0x00,0x0e,0x00,0x40,0x10,0x01,0x00,0x07,0x24,
+0x24,0x00,0xa4,0x8f,0x01,0x00,0x06,0x24,0x21,0x10,0x85,0x00,0x7a,0x51,0x44,0x90,
+0x74,0x51,0x45,0x8c,0x04,0x18,0xe6,0x00,0x24,0x10,0xa3,0x00,0x5b,0x00,0x43,0x10,
+0x00,0x00,0x00,0x00,0x01,0x00,0xe7,0x24,0x2a,0x10,0x87,0x00,0xfa,0xff,0x40,0x10,
+0x04,0x18,0xe6,0x00,0x20,0x00,0xa2,0x8f,0x02,0x80,0x0b,0x3c,0x68,0x15,0x64,0x25,
+0x21,0x18,0x44,0x00,0x7a,0x51,0x62,0x90,0x01,0x00,0x07,0x26,0x2a,0x10,0x47,0x00,
+0x0e,0x00,0x40,0x14,0x01,0x00,0x06,0x24,0x1c,0x00,0xa3,0x8f,0x00,0x00,0x00,0x00,
+0x21,0x10,0x64,0x00,0x7a,0x51,0x45,0x90,0x74,0x51,0x44,0x8c,0x04,0x18,0xe6,0x00,
+0x24,0x10,0x83,0x00,0x42,0x00,0x43,0x10,0x00,0x00,0x00,0x00,0x01,0x00,0xe7,0x24,
+0x2a,0x10,0xa7,0x00,0xfa,0xff,0x40,0x10,0x04,0x18,0xe6,0x00,0x02,0x80,0x02,0x3c,
+0x8e,0x7d,0x44,0x90,0x22,0x00,0x03,0x24,0xd6,0xfe,0x83,0x14,0x68,0x15,0x65,0x25,
+0xee,0xff,0x02,0x26,0xff,0x00,0x42,0x30,0x02,0x00,0x42,0x2c,0x18,0x00,0x03,0x24,
+0x25,0x0f,0x00,0x08,0x0b,0x80,0x62,0x00,0xc0,0x10,0x07,0x00,0x23,0x10,0x47,0x00,
+0xc2,0x10,0x02,0x00,0x2b,0x10,0x48,0x00,0xb6,0xfe,0x40,0x14,0x00,0x00,0x00,0x00,
+0x04,0x0f,0x00,0x08,0x00,0x00,0x00,0x00,0x10,0x00,0xa3,0x8f,0x5c,0x00,0xbf,0x8f,
+0x58,0x00,0xbe,0x8f,0x54,0x00,0xb7,0x8f,0x50,0x00,0xb6,0x8f,0x4c,0x00,0xb5,0x8f,
+0x48,0x00,0xb4,0x8f,0x44,0x00,0xb3,0x8f,0x40,0x00,0xb2,0x8f,0x3c,0x00,0xb1,0x8f,
+0x38,0x00,0xb0,0x8f,0x25,0xb0,0x02,0x3c,0x80,0x01,0x42,0x34,0x60,0x00,0xbd,0x27,
+0x00,0x00,0x43,0xa0,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x18,0x00,0x02,0x2e,
+0x0a,0x00,0x40,0x14,0x05,0x00,0x02,0x2e,0xb6,0x51,0x83,0x90,0x00,0x00,0x00,0x00,
+0x05,0x00,0x62,0x2c,0xa0,0xff,0x40,0x10,0x01,0x00,0x62,0x24,0x16,0x10,0x00,0x08,
+0xb6,0x51,0x82,0xa0,0x24,0x0f,0x00,0x08,0x99,0x51,0xa7,0xa0,0x04,0x00,0x40,0x10,
+0x00,0x00,0x00,0x00,0xb6,0x51,0x83,0x90,0x75,0x10,0x00,0x08,0x03,0x00,0x62,0x2c,
+0xb6,0x51,0x83,0x90,0x75,0x10,0x00,0x08,0x04,0x00,0x62,0x2c,0x13,0x00,0x02,0x24,
+0x67,0xff,0x02,0x16,0x68,0x15,0x63,0x25,0xf3,0x0f,0x00,0x08,0x21,0x10,0xe3,0x02,
+0xff,0x00,0xf0,0x30,0x4c,0x10,0x00,0x08,0x02,0x80,0x02,0x3c,0x35,0x10,0x00,0x08,
+0xff,0x00,0xf0,0x30,0xdf,0x0f,0x00,0x08,0xff,0x00,0xf0,0x30,0xd8,0xff,0xbd,0x27,
+0x02,0x80,0x02,0x3c,0x14,0x00,0xb1,0xaf,0x24,0x00,0xbf,0xaf,0x20,0x00,0xb4,0xaf,
+0x1c,0x00,0xb3,0xaf,0x18,0x00,0xb2,0xaf,0x10,0x00,0xb0,0xaf,0x68,0x15,0x45,0x24,
+0x05,0x65,0xa4,0x90,0x00,0x65,0xa3,0x8c,0xfc,0x64,0xa2,0x8c,0x21,0x88,0x64,0x00,
+0x2b,0x10,0x22,0x02,0x60,0x00,0x40,0x10,0x21,0x80,0xa0,0x00,0x02,0x80,0x14,0x3c,
+0x21,0x98,0xa0,0x00,0xa8,0x10,0x00,0x08,0x21,0x90,0xa0,0x00,0xfc,0x64,0x42,0x8e,
+0x10,0x00,0x31,0x26,0x2b,0x10,0x22,0x02,0x57,0x00,0x40,0x10,0x21,0x80,0x40,0x02,
+0x05,0x65,0x02,0x92,0xff,0xff,0x23,0x32,0x02,0x80,0x05,0x3c,0x10,0x00,0x42,0x24,
+0x25,0x28,0x65,0x00,0x2c,0x79,0x84,0x26,0x10,0x00,0x06,0x24,0x9f,0x45,0x00,0x0c,
+0x05,0x65,0x02,0xa2,0xc8,0x63,0x06,0x8e,0x00,0x00,0x00,0x00,0x42,0x24,0x06,0x00,
+0x1f,0x00,0x84,0x30,0xc0,0x10,0x04,0x00,0x21,0x10,0x44,0x00,0x80,0x10,0x02,0x00,
+0x21,0x10,0x44,0x00,0x80,0x10,0x02,0x00,0x21,0x38,0x50,0x00,0x78,0x51,0xe3,0x8c,
+0x00,0x00,0x00,0x00,0x02,0x1b,0x03,0x00,0x01,0x00,0x63,0x30,0xe3,0xff,0x60,0x10,
+0x25,0xb0,0x02,0x3c,0xc4,0x63,0x05,0x8e,0x21,0x10,0x82,0x00,0x60,0x01,0x44,0x90,
+0x82,0x1d,0x05,0x00,0x3f,0x00,0x63,0x30,0x04,0x00,0x0a,0x24,0x05,0x00,0x62,0x28,
+0x21,0x40,0x40,0x01,0x0b,0x40,0x62,0x00,0x07,0x00,0xa0,0x04,0xff,0x00,0x89,0x30,
+0x64,0x51,0xe2,0x8c,0x04,0x00,0x08,0x24,0x01,0x00,0x42,0x24,0x64,0x51,0xe2,0xac,
+0xc8,0x63,0x66,0x8e,0x00,0x00,0x00,0x00,0x02,0x13,0x06,0x00,0x1f,0x00,0x42,0x30,
+0x08,0x00,0x42,0x28,0xcd,0xff,0x40,0x10,0x00,0x00,0x00,0x00,0xc4,0x63,0x62,0x8e,
+0x00,0x00,0x00,0x00,0x3f,0x00,0x42,0x30,0xc8,0xff,0x49,0x14,0x00,0x00,0x00,0x00,
+0x29,0x00,0x00,0x11,0x01,0x00,0x02,0x24,0x2e,0x00,0x02,0x11,0x02,0x00,0x02,0x24,
+0x33,0x00,0x02,0x11,0x03,0x00,0x02,0x24,0x38,0x00,0x02,0x11,0x00,0x00,0x00,0x00,
+0x3b,0x00,0x0a,0x11,0x00,0x00,0x00,0x00,0x68,0x51,0xe2,0x8c,0x21,0x18,0x33,0x01,
+0x90,0x44,0x64,0x90,0x02,0x11,0x02,0x00,0x2b,0x10,0x44,0x00,0x3e,0x00,0x40,0x14,
+0x00,0x00,0x00,0x00,0x5c,0x51,0xe3,0x8c,0x80,0x10,0x09,0x00,0x21,0x10,0x49,0x00,
+0x01,0x00,0x63,0x24,0x21,0x10,0x53,0x00,0x5c,0x51,0xe3,0xac,0x21,0x10,0x48,0x00,
+0x34,0x43,0x44,0x90,0x44,0x51,0xe3,0x8c,0x00,0x00,0x00,0x00,0x21,0x18,0x64,0x00,
+0x44,0x51,0xe3,0xac,0xfc,0x64,0x42,0x8e,0x10,0x00,0x31,0x26,0x2b,0x10,0x22,0x02,
+0xab,0xff,0x40,0x14,0x21,0x80,0x40,0x02,0x24,0x00,0xbf,0x8f,0x20,0x00,0xb4,0x8f,
+0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,
+0x08,0x00,0xe0,0x03,0x28,0x00,0xbd,0x27,0x48,0x51,0xe2,0x8c,0x00,0x00,0x00,0x00,
+0x01,0x00,0x42,0x24,0x48,0x51,0xe2,0xac,0x01,0x00,0x02,0x24,0xd4,0xff,0x02,0x15,
+0x02,0x00,0x02,0x24,0x4c,0x51,0xe2,0x8c,0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x24,
+0x4c,0x51,0xe2,0xac,0x02,0x00,0x02,0x24,0xcf,0xff,0x02,0x15,0x03,0x00,0x02,0x24,
+0x50,0x51,0xe2,0x8c,0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x24,0x50,0x51,0xe2,0xac,
+0x03,0x00,0x02,0x24,0xca,0xff,0x02,0x15,0x00,0x00,0x00,0x00,0x54,0x51,0xe2,0x8c,
+0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x24,0xc7,0xff,0x0a,0x15,0x54,0x51,0xe2,0xac,
+0x58,0x51,0xe2,0x8c,0x21,0x18,0x33,0x01,0x01,0x00,0x42,0x24,0x58,0x51,0xe2,0xac,
+0x68,0x51,0xe2,0x8c,0x90,0x44,0x64,0x90,0x02,0x11,0x02,0x00,0x2b,0x10,0x44,0x00,
+0xc4,0xff,0x40,0x10,0x00,0x00,0x00,0x00,0x60,0x51,0xe3,0x8c,0x80,0x10,0x09,0x00,
+0x21,0x10,0x49,0x00,0x01,0x00,0x63,0x24,0x21,0x10,0x53,0x00,0x60,0x51,0xe3,0xac,
+0x21,0x10,0x48,0x00,0xc5,0x43,0x44,0x90,0x44,0x51,0xe3,0x8c,0x00,0x00,0x00,0x00,
+0x21,0x18,0x64,0x00,0xf9,0x10,0x00,0x08,0x44,0x51,0xe3,0xac,0x25,0xb0,0x02,0x3c,
+0x25,0xb0,0x05,0x3c,0x02,0x80,0x03,0x3c,0x58,0x00,0x4a,0x34,0x5c,0x00,0x4b,0x34,
+0x4c,0x00,0xa2,0x34,0x00,0x00,0x44,0x90,0x68,0x15,0x66,0x24,0xed,0x4a,0xc2,0x90,
+0x29,0xb0,0x07,0x3c,0x03,0x00,0x84,0x30,0x21,0x18,0xc0,0x00,0x0f,0x00,0x44,0x10,
+0x04,0x00,0xe8,0x34,0x07,0x00,0x80,0x14,0x58,0x0c,0xa9,0x34,0xe6,0x42,0xc2,0x90,
+0x1c,0x00,0x06,0x24,0x03,0x00,0x40,0x14,0x50,0x0c,0xa5,0x34,0x00,0x00,0xa6,0xa0,
+0x00,0x00,0x26,0xa1,0x00,0x00,0x42,0x8d,0xed,0x4a,0x64,0xa0,0x00,0x00,0xe2,0xac,
+0x00,0x00,0x62,0x8d,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0xad,0x08,0x00,0xe0,0x03,
+0x21,0x10,0x00,0x00,0x25,0xb0,0x0d,0x3c,0xe8,0xff,0xbd,0x27,0x10,0x00,0xbf,0xaf,
+0x2d,0x0a,0xa7,0x35,0xa2,0x0d,0xa2,0x35,0xa4,0x0d,0xa3,0x35,0xa6,0x0d,0xa4,0x35,
+0xa8,0x0d,0xa5,0x35,0x00,0x00,0x48,0x94,0x00,0x00,0x69,0x94,0x00,0x00,0x8a,0x94,
+0x00,0x00,0xab,0x94,0x00,0x00,0xe3,0x90,0x5b,0x0a,0xa4,0x35,0x5c,0x0a,0xa6,0x35,
+0x00,0x2e,0x03,0x00,0x03,0x2e,0x05,0x00,0x40,0x00,0xa2,0x34,0x00,0x00,0xe2,0xa0,
+0x00,0x00,0x85,0x90,0x00,0x00,0xc3,0x90,0x02,0x80,0x0e,0x3c,0x68,0x15,0xcc,0x25,
+0xff,0xff,0x22,0x31,0xff,0x00,0xa5,0x30,0xff,0xff,0x04,0x31,0x21,0x20,0x82,0x00,
+0xff,0x00,0x63,0x30,0x00,0x40,0x87,0x8d,0x00,0x2a,0x05,0x00,0xff,0xff,0x46,0x31,
+0x21,0x28,0xa3,0x00,0xff,0xff,0x62,0x31,0x21,0x20,0x86,0x00,0x21,0x20,0x82,0x00,
+0xff,0xff,0xa3,0x30,0x64,0x0c,0xa2,0x35,0x00,0x00,0x45,0xa4,0x21,0x20,0x83,0x00,
+0x0f,0x00,0xe7,0x30,0x01,0x00,0x02,0x24,0xe0,0x42,0x84,0xad,0xd8,0x42,0x88,0xa5,
+0xda,0x42,0x89,0xa5,0xdc,0x42,0x8a,0xa5,0xde,0x42,0x8b,0xa5,0x07,0x00,0xe2,0x10,
+0xe4,0x42,0x85,0xa5,0xa8,0x56,0x00,0x0c,0x00,0x00,0x00,0x00,0x10,0x00,0xbf,0x8f,
+0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x18,0x00,0xbd,0x27,0x4c,0x00,0xa3,0x35,
+0x00,0x00,0x62,0x90,0x00,0x00,0x00,0x00,0x03,0x00,0x42,0x30,0x67,0x00,0x47,0x10,
+0x68,0x15,0xc4,0x25,0xe6,0x42,0x82,0x90,0x00,0x00,0x00,0x00,0x2d,0x00,0x40,0x10,
+0x01,0x00,0x03,0x24,0x68,0x15,0xc5,0x25,0xe6,0x42,0xa3,0x90,0xff,0x00,0x02,0x24,
+0xec,0xff,0x62,0x14,0x25,0xb0,0x03,0x3c,0xc8,0x42,0xa2,0x94,0xe0,0x42,0xa6,0x8c,
+0x50,0x0c,0x63,0x34,0x00,0x00,0x64,0x90,0x2b,0x10,0xc2,0x00,0x5e,0x00,0x40,0x14,
+0x7f,0x00,0x84,0x30,0xca,0x42,0xa2,0x94,0x00,0x00,0x00,0x00,0x2b,0x10,0xc2,0x00,
+0x09,0x00,0x40,0x14,0x00,0x00,0x00,0x00,0xcc,0x42,0xa2,0x94,0x00,0x00,0x00,0x00,
+0x2b,0x10,0xc2,0x00,0x02,0x00,0x40,0x10,0x02,0x00,0x82,0x24,0x01,0x00,0x82,0x24,
+0xff,0x00,0x44,0x30,0x68,0x15,0xc5,0x25,0xd0,0x42,0xa3,0x90,0x00,0x00,0x00,0x00,
+0x2b,0x10,0x64,0x00,0x4e,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0x21,0x20,0x60,0x00,
+0x68,0x15,0xc3,0x25,0xe0,0x42,0x62,0x8c,0x00,0x00,0x00,0x00,0xe9,0x03,0x42,0x2c,
+0x02,0x00,0x40,0x14,0x25,0xb0,0x02,0x3c,0xd0,0x42,0x64,0x90,0x58,0x0c,0x43,0x34,
+0x50,0x0c,0x42,0x34,0x00,0x00,0x44,0xa0,0x00,0x00,0x64,0xa0,0x85,0x11,0x00,0x08,
+0x00,0x00,0x00,0x00,0x00,0x40,0x82,0x8c,0x00,0x00,0x00,0x00,0x02,0x12,0x02,0x00,
+0x0f,0x00,0x42,0x30,0xd0,0xff,0x43,0x14,0x68,0x15,0xc5,0x25,0x25,0xb0,0x02,0x3c,
+0x4c,0x00,0x42,0x34,0x00,0x00,0x43,0x90,0x00,0x00,0x00,0x00,0x03,0x00,0x63,0x30,
+0xb8,0xff,0x60,0x10,0xff,0xff,0x02,0x34,0xdc,0x63,0x83,0x8c,0x00,0x00,0x00,0x00,
+0xb4,0xff,0x62,0x10,0x00,0x00,0x00,0x00,0xe0,0x42,0x83,0x8c,0x00,0x00,0x00,0x00,
+0x65,0x00,0x62,0x2c,0x3b,0x00,0x40,0x14,0x28,0x00,0x62,0x2c,0xd2,0x42,0x83,0x90,
+0x00,0x00,0x00,0x00,0x00,0x16,0x03,0x00,0x03,0x16,0x02,0x00,0xfe,0xff,0x42,0x24,
+0xfc,0xff,0x42,0x28,0x02,0x00,0x40,0x10,0xfe,0xff,0x62,0x24,0xfc,0xff,0x02,0x24,
+0xd2,0x42,0x82,0xa0,0x68,0x15,0xc4,0x25,0xdc,0x63,0x82,0x8c,0xd2,0x42,0x83,0x90,
+0xce,0x42,0x86,0x90,0x02,0x11,0x02,0x00,0x7f,0x00,0x42,0x30,0x0a,0x00,0x45,0x24,
+0x23,0x18,0xa3,0x00,0x00,0x2e,0x03,0x00,0x03,0x2e,0x05,0x00,0xff,0x00,0xc2,0x30,
+0x2a,0x10,0x45,0x00,0x17,0x00,0x40,0x10,0x25,0xb0,0x02,0x3c,0x00,0x2e,0x06,0x00,
+0x03,0x2e,0x05,0x00,0x58,0x0c,0x43,0x34,0x50,0x0c,0x42,0x34,0x00,0x00,0x45,0xa0,
+0x00,0x00,0x65,0xa0,0x85,0x11,0x00,0x08,0x00,0x00,0x00,0x00,0xe6,0x42,0x82,0x91,
+0x00,0x00,0x00,0x00,0x97,0xff,0x40,0x14,0x00,0x00,0x00,0x00,0xff,0xff,0x02,0x24,
+0x91,0x11,0x00,0x08,0xe6,0x42,0x82,0xa1,0xac,0x11,0x00,0x08,0xff,0xff,0x82,0x24,
+0xd1,0x42,0xa3,0x90,0x00,0x00,0x00,0x00,0x2b,0x10,0x83,0x00,0xb4,0x11,0x00,0x08,
+0x0b,0x20,0x62,0x00,0xcf,0x42,0x83,0x80,0x00,0x00,0x00,0x00,0xff,0x00,0x62,0x30,
+0x2a,0x10,0xa2,0x00,0x0b,0x28,0x62,0x00,0x25,0xb0,0x02,0x3c,0x58,0x0c,0x43,0x34,
+0x50,0x0c,0x42,0x34,0x00,0x00,0x45,0xa0,0x00,0x00,0x65,0xa0,0x85,0x11,0x00,0x08,
+0x00,0x00,0x00,0x00,0xcf,0xff,0x40,0x10,0x00,0x00,0x00,0x00,0xd2,0x42,0x83,0x90,
+0x00,0x00,0x00,0x00,0x00,0x16,0x03,0x00,0x03,0x16,0x02,0x00,0x02,0x00,0x42,0x24,
+0x0d,0x00,0x42,0x28,0x03,0x00,0x40,0x14,0x00,0x00,0x00,0x00,0xe0,0x11,0x00,0x08,
+0x0c,0x00,0x02,0x24,0xe0,0x11,0x00,0x08,0x02,0x00,0x62,0x24,0xc0,0xff,0xbd,0x27,
+0x18,0x00,0xb0,0xaf,0x25,0xb0,0x10,0x3c,0x28,0x00,0xb4,0xaf,0x24,0x00,0xb3,0xaf,
+0x1c,0x00,0xb1,0xaf,0x3c,0x00,0xbf,0xaf,0x38,0x00,0xbe,0xaf,0x34,0x00,0xb7,0xaf,
+0x30,0x00,0xb6,0xaf,0x2c,0x00,0xb5,0xaf,0x20,0x00,0xb2,0xaf,0xd8,0x00,0x06,0x36,
+0x00,0x00,0xc3,0x90,0x02,0x80,0x02,0x3c,0x68,0x15,0x54,0x24,0x2a,0xb0,0x11,0x3c,
+0xa0,0xff,0x02,0x24,0x25,0x18,0x62,0x00,0x34,0x00,0x25,0x36,0xfe,0xff,0x02,0x24,
+0xbc,0x42,0x92,0x92,0x40,0x00,0x04,0x24,0x00,0x00,0xc3,0xa0,0x00,0x00,0xa2,0xa0,
+0xa1,0x4e,0x00,0x0c,0x00,0x96,0x12,0x00,0x21,0x98,0x40,0x00,0x6b,0x00,0x60,0x12,
+0x00,0x40,0x02,0x3c,0x08,0x00,0x63,0x8e,0xb0,0x03,0x02,0x36,0x21,0x20,0x60,0x02,
+0x00,0x00,0x43,0xac,0x3a,0x45,0x00,0x0c,0x21,0xb8,0x80,0x02,0x01,0x00,0x1e,0x24,
+0x42,0x00,0x16,0x36,0x03,0x0c,0x11,0x36,0x17,0x0e,0x15,0x36,0x04,0x00,0x14,0x24,
+0x2a,0xb0,0x03,0x3c,0x06,0x00,0x63,0x34,0x00,0x00,0x62,0x94,0x00,0x00,0x00,0x00,
+0x00,0xff,0x42,0x30,0x0a,0x00,0x40,0x18,0x00,0x00,0x00,0x00,0x02,0x80,0x04,0x3c,
+0xc8,0x94,0x84,0x24,0x00,0x00,0x83,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0x62,0x94,
+0x00,0x00,0x00,0x00,0x00,0xff,0x42,0x30,0xfc,0xff,0x40,0x1c,0x00,0x00,0x00,0x00,
+0x08,0x00,0x65,0x8e,0x20,0x10,0x06,0x3c,0x00,0xfe,0xc6,0x34,0x40,0x00,0x07,0x24,
+0x01,0x00,0x04,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xbe,0xaf,0x4d,0x01,0x00,0x0c,
+0x01,0x00,0x04,0x24,0x2a,0xb0,0x02,0x3c,0x05,0x00,0x42,0x34,0xff,0xff,0x03,0x24,
+0x00,0x00,0x5e,0xa0,0x00,0x00,0xc3,0xa2,0x00,0x00,0x22,0x92,0xc1,0x42,0xe5,0x92,
+0x2a,0xb0,0x04,0x3c,0x02,0x00,0x03,0x24,0x40,0x00,0x42,0x34,0x05,0x00,0x84,0x34,
+0x00,0x00,0x22,0xa2,0x00,0x00,0x83,0xa0,0xef,0xff,0x02,0x24,0x00,0x00,0xb0,0x92,
+0x64,0x00,0x04,0x24,0x00,0x00,0xa5,0xa2,0x00,0x00,0xc2,0xa2,0xb3,0x0a,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x00,0x00,0x22,0x92,0xbf,0xff,0x03,0x24,0x84,0x03,0x04,0x24,
+0x24,0x10,0x43,0x00,0x00,0x00,0x22,0xa2,0xb3,0x0a,0x00,0x0c,0xff,0x00,0x10,0x32,
+0x25,0xb0,0x02,0x3c,0xf4,0x08,0x42,0x34,0x00,0x00,0x44,0x8c,0x00,0x00,0xb0,0xa2,
+0x00,0x00,0xc0,0xa2,0x00,0x00,0x22,0x92,0xbe,0x42,0xe3,0x92,0x1f,0x00,0x85,0x30,
+0x40,0x00,0x42,0x34,0x00,0x00,0x22,0xa2,0x00,0x80,0x02,0x3c,0xdf,0x07,0x42,0x34,
+0x2b,0x18,0xa3,0x00,0x09,0x00,0x60,0x10,0x24,0x20,0x82,0x00,0xbf,0x42,0xe2,0x92,
+0x00,0x00,0x00,0x00,0x2b,0x10,0x45,0x00,0x05,0x00,0x40,0x10,0x02,0x80,0x02,0x3c,
+0x01,0x00,0x02,0x3c,0x25,0x10,0xa2,0x00,0x21,0x90,0x42,0x02,0x02,0x80,0x02,0x3c,
+0x8e,0x7d,0x43,0x90,0x22,0x00,0x02,0x24,0x1c,0x00,0x62,0x10,0x92,0x00,0x02,0x24,
+0x1b,0x00,0x62,0x10,0x02,0x80,0x03,0x3c,0xff,0xff,0x94,0x26,0xb3,0x0a,0x00,0x0c,
+0xf4,0x01,0x04,0x24,0xab,0xff,0x81,0x06,0x2a,0xb0,0x03,0x3c,0x04,0x00,0x60,0x12,
+0x25,0xb0,0x02,0x3c,0xbd,0x4e,0x00,0x0c,0x21,0x20,0x60,0x02,0x25,0xb0,0x02,0x3c,
+0xd8,0x02,0x42,0x34,0x00,0x00,0x52,0xac,0x21,0x10,0x40,0x02,0x3c,0x00,0xbf,0x8f,
+0x38,0x00,0xbe,0x8f,0x34,0x00,0xb7,0x8f,0x30,0x00,0xb6,0x8f,0x2c,0x00,0xb5,0x8f,
+0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,
+0x18,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x40,0x00,0xbd,0x27,0x02,0x80,0x03,0x3c,
+0x68,0x15,0x63,0x24,0xbe,0x42,0x62,0x90,0xc0,0x07,0x83,0x30,0x82,0x19,0x03,0x00,
+0x2b,0x10,0x62,0x00,0xe0,0xff,0x40,0x10,0x02,0x80,0x04,0x3c,0x68,0x15,0x84,0x24,
+0xbf,0x42,0x82,0x90,0x00,0x00,0x00,0x00,0x2b,0x10,0x43,0x00,0xda,0xff,0x40,0x10,
+0x00,0x12,0x03,0x00,0x10,0x00,0x03,0x3c,0x25,0x10,0x43,0x00,0x9a,0x12,0x00,0x08,
+0x21,0x90,0x42,0x02,0xe8,0xff,0xbd,0x27,0x10,0x00,0xb0,0xaf,0x0f,0x00,0x10,0x3c,
+0xff,0xff,0x05,0x36,0xf0,0xf8,0x06,0x34,0x14,0x00,0xbf,0xaf,0xba,0x44,0x00,0x0c,
+0x15,0x00,0x04,0x24,0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0xff,0xff,0x05,0x36,
+0x56,0x30,0x06,0x24,0xba,0x44,0x00,0x0c,0x1a,0x00,0x04,0x24,0xb3,0x0a,0x00,0x0c,
+0x64,0x00,0x04,0x24,0x02,0x80,0x0b,0x3c,0x68,0x15,0x64,0x25,0x04,0x43,0x83,0x90,
+0x04,0x00,0x02,0x24,0x19,0x00,0x62,0x10,0x25,0xb0,0x02,0x3c,0x14,0x43,0x8a,0x8c,
+0x18,0x43,0x88,0x8c,0x25,0xb0,0x02,0x3c,0x1c,0x0e,0x49,0x34,0x00,0x0e,0x43,0x34,
+0x04,0x0e,0x44,0x34,0x08,0x0e,0x45,0x34,0x10,0x0e,0x46,0x34,0x14,0x0e,0x47,0x34,
+0x18,0x0e,0x42,0x34,0x00,0x00,0x6a,0xac,0x00,0x00,0x8a,0xac,0x00,0x00,0xa8,0xac,
+0x00,0x00,0xca,0xac,0x00,0x00,0xea,0xac,0x00,0x00,0x4a,0xac,0x00,0x00,0x2a,0xad,
+0x14,0x00,0xbf,0x8f,0x10,0x00,0xb0,0x8f,0x68,0x15,0x63,0x25,0x04,0x00,0x02,0x24,
+0x18,0x00,0xbd,0x27,0x08,0x00,0xe0,0x03,0x04,0x43,0x62,0xa0,0x00,0x0e,0x42,0x34,
+0x00,0x00,0x43,0x8c,0x14,0x43,0x8a,0x8c,0x00,0x00,0x00,0x00,0xe4,0xff,0x6a,0x14,
+0x00,0x00,0x00,0x00,0xec,0x12,0x00,0x08,0x00,0x00,0x00,0x00,0xe8,0xff,0xbd,0x27,
+0x10,0x00,0xb0,0xaf,0x0f,0x00,0x10,0x3c,0xff,0xff,0x05,0x36,0xf0,0xf8,0x06,0x34,
+0x14,0x00,0xbf,0xaf,0xba,0x44,0x00,0x0c,0x15,0x00,0x04,0x24,0xb3,0x0a,0x00,0x0c,
+0x64,0x00,0x04,0x24,0xff,0xff,0x05,0x36,0x56,0x30,0x06,0x24,0xba,0x44,0x00,0x0c,
+0x1a,0x00,0x04,0x24,0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0x02,0x80,0x04,0x3c,
+0x68,0x15,0x83,0x24,0x04,0x43,0x65,0x90,0x21,0x70,0x60,0x00,0x10,0x10,0x03,0x3c,
+0x25,0xb0,0x02,0x3c,0x10,0x10,0x66,0x34,0x01,0x00,0x03,0x24,0x1c,0x0e,0x4d,0x34,
+0x00,0x0e,0x4a,0x34,0x04,0x0e,0x4b,0x34,0x08,0x0e,0x4c,0x34,0x10,0x0e,0x47,0x34,
+0x14,0x0e,0x48,0x34,0x0f,0x00,0xa3,0x10,0x18,0x0e,0x49,0x34,0x10,0x10,0x02,0x24,
+0x00,0x00,0x46,0xad,0x00,0x00,0x66,0xad,0x00,0x00,0x82,0xad,0x00,0x00,0xe6,0xac,
+0x00,0x00,0x06,0xad,0x00,0x00,0x26,0xad,0x00,0x00,0xa6,0xad,0x14,0x00,0xbf,0x8f,
+0x10,0x00,0xb0,0x8f,0x01,0x00,0x02,0x24,0x18,0x00,0xbd,0x27,0x08,0x00,0xe0,0x03,
+0x04,0x43,0xc2,0xa1,0x00,0x00,0x44,0x8d,0x00,0x00,0x00,0x00,0xf0,0xff,0x86,0x14,
+0x10,0x10,0x02,0x24,0x23,0x13,0x00,0x08,0x00,0x00,0x00,0x00,0xe0,0xff,0xbd,0x27,
+0x14,0x00,0xb1,0xaf,0x10,0x00,0xb0,0xaf,0x01,0x00,0x11,0x3c,0x0f,0x00,0x10,0x3c,
+0xff,0xff,0x05,0x36,0xf4,0x98,0x26,0x36,0x18,0x00,0xbf,0xaf,0xba,0x44,0x00,0x0c,
+0x15,0x00,0x04,0x24,0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0xff,0xff,0x05,0x36,
+0x56,0x30,0x26,0x36,0xba,0x44,0x00,0x0c,0x1a,0x00,0x04,0x24,0x02,0x80,0x10,0x3c,
+0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0x68,0x15,0x04,0x26,0x04,0x43,0x82,0x90,
+0x00,0x00,0x00,0x00,0x0d,0x00,0x40,0x14,0x25,0xb0,0x02,0x3c,0x00,0x0e,0x42,0x34,
+0x00,0x00,0x43,0x8c,0xec,0x42,0x8f,0x8c,0x00,0x00,0x00,0x00,0x08,0x00,0x6f,0x14,
+0x68,0x15,0x02,0x26,0x18,0x00,0xbf,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,
+0x20,0x00,0xbd,0x27,0x08,0x00,0xe0,0x03,0x04,0x43,0x40,0xa0,0xec,0x42,0x8f,0x8c,
+0xe8,0x42,0x88,0x8c,0xf0,0x42,0x8a,0x8c,0xf4,0x42,0x8b,0x8c,0xf8,0x42,0x8c,0x8c,
+0xfc,0x42,0x8d,0x8c,0x25,0xb0,0x02,0x3c,0x00,0x43,0x8e,0x8c,0x1c,0x0e,0x49,0x34,
+0x08,0x0e,0x43,0x34,0x00,0x0e,0x44,0x34,0x04,0x0e,0x45,0x34,0x10,0x0e,0x46,0x34,
+0x14,0x0e,0x47,0x34,0x18,0x0e,0x42,0x34,0x00,0x00,0x68,0xac,0x18,0x00,0xbf,0x8f,
+0x00,0x00,0x8f,0xac,0x14,0x00,0xb1,0x8f,0x00,0x00,0xaa,0xac,0x00,0x00,0xcb,0xac,
+0x00,0x00,0xec,0xac,0x00,0x00,0x4d,0xac,0x68,0x15,0x02,0x26,0x10,0x00,0xb0,0x8f,
+0x20,0x00,0xbd,0x27,0x00,0x00,0x2e,0xad,0x08,0x00,0xe0,0x03,0x04,0x43,0x40,0xa0,
+0xe0,0xff,0xbd,0x27,0x14,0x00,0xb1,0xaf,0x10,0x00,0xb0,0xaf,0x01,0x00,0x11,0x3c,
+0x0f,0x00,0x10,0x3c,0xff,0xff,0x05,0x36,0xf4,0x98,0x26,0x36,0x18,0x00,0xbf,0xaf,
+0xba,0x44,0x00,0x0c,0x15,0x00,0x04,0x24,0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,
+0xff,0xff,0x05,0x36,0x56,0x30,0x26,0x36,0xba,0x44,0x00,0x0c,0x1a,0x00,0x04,0x24,
+0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0x02,0x80,0x18,0x3c,0x68,0x15,0x05,0x27,
+0x04,0x43,0xa3,0x90,0x03,0x00,0x02,0x24,0x2a,0x00,0x62,0x10,0x25,0xb0,0x02,0x3c,
+0xec,0x42,0xaf,0x8c,0x08,0x43,0xa3,0x8c,0xe8,0x42,0xa2,0x8c,0xf0,0x42,0xac,0x8c,
+0xf4,0x42,0xad,0x8c,0xf8,0x42,0xa9,0x8c,0xfc,0x42,0xaa,0x8c,0x00,0x43,0xab,0x8c,
+0x21,0x70,0x43,0x00,0xff,0xff,0x02,0x3c,0x25,0xb0,0x03,0x3c,0xff,0x00,0x42,0x34,
+0x00,0xff,0xc4,0x31,0x04,0x0e,0x65,0x34,0x10,0x0e,0x66,0x34,0x14,0x0e,0x67,0x34,
+0x18,0x0e,0x68,0x34,0x24,0x80,0xc2,0x01,0x08,0x0e,0x71,0x34,0x00,0x0e,0x62,0x34,
+0x01,0x3f,0x84,0x2c,0x1c,0x0e,0x63,0x34,0x00,0x00,0x4f,0xac,0x00,0x00,0xac,0xac,
+0x00,0x00,0xcd,0xac,0x00,0x00,0xe9,0xac,0x00,0x00,0x0a,0xad,0x00,0x00,0x6b,0xac,
+0x0a,0x00,0x80,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x2e,0xae,0x18,0x00,0xbf,0x8f,
+0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x68,0x15,0x03,0x27,0x03,0x00,0x02,0x24,
+0x20,0x00,0xbd,0x27,0x08,0x00,0xe0,0x03,0x04,0x43,0x62,0xa0,0xa6,0x13,0x00,0x08,
+0x00,0x3f,0x0e,0x36,0x00,0x0e,0x42,0x34,0x00,0x00,0x43,0x8c,0xec,0x42,0xaf,0x8c,
+0x00,0x00,0x00,0x00,0xd3,0xff,0x6f,0x14,0x00,0x00,0x00,0x00,0xa7,0x13,0x00,0x08,
+0x00,0x00,0x00,0x00,0xd0,0xff,0xbd,0x27,0x18,0x00,0xb2,0xaf,0x02,0x80,0x12,0x3c,
+0x24,0x00,0xb5,0xaf,0x20,0x00,0xb4,0xaf,0x28,0x00,0xbf,0xaf,0x1c,0x00,0xb3,0xaf,
+0x14,0x00,0xb1,0xaf,0x10,0x00,0xb0,0xaf,0x68,0x15,0x44,0x26,0x02,0x80,0x14,0x3c,
+0x00,0x40,0x85,0x8c,0xdc,0x63,0x83,0x8c,0x8e,0x7d,0x86,0x92,0x25,0xb0,0x02,0x3c,
+0x0f,0x0c,0x42,0x34,0x00,0x00,0x46,0xa0,0x02,0x19,0x03,0x00,0xf0,0xf0,0xa5,0x30,
+0x00,0x10,0x02,0x24,0x04,0x43,0x93,0x90,0x71,0x00,0xa2,0x10,0x7f,0x00,0x75,0x30,
+0x25,0xb0,0x09,0x3c,0x4c,0x00,0x23,0x35,0x00,0x00,0x62,0x90,0x00,0x00,0x00,0x00,
+0x03,0x00,0x42,0x30,0x09,0x00,0x40,0x10,0x68,0x15,0x45,0x26,0x68,0x15,0x4a,0x26,
+0x00,0x40,0x42,0x8d,0x00,0x00,0x00,0x00,0x02,0x13,0x02,0x00,0x0f,0x00,0x42,0x30,
+0x33,0x00,0x40,0x10,0x00,0x0e,0x25,0x35,0x68,0x15,0x45,0x26,0x04,0x43,0xa2,0x8c,
+0x00,0x00,0x00,0x00,0x02,0x12,0x02,0x00,0x0f,0x00,0x40,0x14,0x68,0x15,0x4a,0x26,
+0x25,0xb0,0x02,0x3c,0x84,0x01,0x42,0x34,0x00,0x00,0x44,0x8c,0x0d,0x00,0x03,0x24,
+0x7e,0x00,0x83,0x10,0x3e,0x00,0x02,0x24,0x4a,0x00,0x03,0x24,0x1f,0x43,0xa2,0xa0,
+0x1c,0x43,0xa3,0xa0,0x45,0x00,0x02,0x24,0x43,0x00,0x03,0x24,0x1d,0x43,0xa2,0xa0,
+0x1e,0x43,0xa3,0xa0,0x68,0x15,0x4a,0x26,0xdc,0x63,0x4c,0x8d,0x04,0x40,0x42,0x8d,
+0x00,0x40,0x4b,0x8d,0x1e,0x43,0x4d,0x91,0x1c,0x43,0x4e,0x91,0x25,0xb0,0x09,0x3c,
+0x02,0x11,0x02,0x00,0x60,0x0c,0x27,0x35,0x02,0x19,0x0c,0x00,0x98,0x0c,0x24,0x35,
+0x00,0x00,0xe3,0xa0,0x66,0x0c,0x25,0x35,0x00,0x00,0x82,0xa0,0x67,0x0c,0x26,0x35,
+0xf0,0xf0,0x68,0x31,0x10,0x10,0x02,0x24,0x00,0x00,0xad,0xa0,0x00,0x00,0xce,0xa0,
+0x43,0x00,0x02,0x11,0xff,0xff,0x02,0x34,0x28,0x00,0xbf,0x8f,0x24,0x00,0xb5,0x8f,
+0x20,0x00,0xb4,0x8f,0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x30,0x00,0xbd,0x27,
+0x00,0x00,0xa2,0x8c,0x00,0x00,0x00,0x00,0x5d,0x00,0x40,0x10,0x10,0x0e,0x28,0x35,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x08,0x0e,0x22,0x35,0x04,0x0e,0x24,0x35,0x00,0x00,0x43,0x8c,0x00,0x00,0xa5,0x8c,
+0x00,0x00,0x82,0x8c,0xe8,0x42,0x43,0xad,0xec,0x42,0x45,0xad,0xf0,0x42,0x42,0xad,
+0x14,0x0e,0x24,0x35,0x18,0x0e,0x22,0x35,0x1c,0x0e,0x25,0x35,0x00,0x00,0x08,0x8d,
+0x8e,0x7d,0x8b,0x92,0x00,0x00,0x86,0x8c,0x00,0xff,0x63,0x30,0x00,0x00,0x47,0x8c,
+0x00,0x00,0xa4,0x8c,0x9a,0x0c,0x22,0x35,0x02,0x1a,0x03,0x00,0x00,0x00,0x43,0xa0,
+0x22,0x00,0x02,0x24,0xf4,0x42,0x48,0xad,0xf8,0x42,0x46,0xad,0xfc,0x42,0x47,0xad,
+0x58,0x00,0x62,0x11,0x00,0x43,0x44,0xad,0x92,0x00,0x02,0x24,0x56,0x00,0x62,0x11,
+0x0d,0x08,0x22,0x35,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0x68,0x15,0x44,0x26,0x00,0x40,0x83,0x8c,0xff,0xff,0x02,0x3c,0xff,0x0f,0x42,0x34,
+0x24,0x18,0x62,0x00,0x00,0x10,0x63,0x34,0xde,0x13,0x00,0x08,0x00,0x40,0x83,0xac,
+0x01,0x00,0x02,0x24,0x35,0x00,0x62,0x12,0x04,0x00,0x02,0x24,0x33,0x00,0x62,0x12,
+0x68,0x15,0x43,0x26,0xff,0xff,0x02,0x24,0xd0,0x13,0x00,0x08,0x04,0x43,0x62,0xa0,
+0xbd,0xff,0x82,0x11,0x02,0x12,0x0b,0x00,0x0f,0x00,0x48,0x30,0x01,0x00,0x03,0x24,
+0xb9,0xff,0x03,0x15,0x4c,0x00,0x23,0x35,0x00,0x00,0x62,0x90,0x00,0x00,0x00,0x00,
+0x03,0x00,0x42,0x30,0xb4,0xff,0x40,0x10,0x03,0x00,0x02,0x24,0x5f,0x00,0x62,0x12,
+0x04,0x00,0x62,0x2a,0x45,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0x64,0x00,0x60,0x12,
+0xff,0x00,0xa2,0x31,0xac,0xff,0x68,0x16,0xff,0x00,0xc2,0x31,0x2b,0x10,0xa2,0x02,
+0x52,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0x1f,0x43,0x42,0x91,0x00,0x00,0x00,0x00,
+0x2b,0x10,0x55,0x00,0x44,0x00,0x40,0x14,0x00,0x00,0x00,0x00,0x2f,0x13,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x06,0x14,0x00,0x08,0x00,0x00,0x00,0x00,0x3b,0x00,0x02,0x24,
+0x46,0x00,0x03,0x24,0x1f,0x43,0xa2,0xa0,0x1c,0x43,0xa3,0xa0,0x41,0x00,0x02,0x24,
+0x40,0x00,0x03,0x24,0x1d,0x43,0xa2,0xa0,0xf1,0x13,0x00,0x08,0x1e,0x43,0xa3,0xa0,
+0x00,0x00,0x03,0x8d,0x3f,0x3f,0x02,0x3c,0x3f,0x3f,0x42,0x34,0xa0,0xff,0x62,0x14,
+0x00,0x00,0x00,0x00,0xdf,0x13,0x00,0x08,0x68,0x15,0x45,0x26,0x0f,0x00,0x10,0x3c,
+0x01,0x00,0x11,0x3c,0xff,0xff,0x05,0x36,0xf4,0x98,0x26,0x36,0xba,0x44,0x00,0x0c,
+0x15,0x00,0x04,0x24,0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0xff,0xff,0x05,0x36,
+0x56,0x30,0x26,0x36,0xba,0x44,0x00,0x0c,0x1a,0x00,0x04,0x24,0xb3,0x0a,0x00,0x0c,
+0x64,0x00,0x04,0x24,0x68,0x15,0x43,0x26,0xff,0xff,0x02,0x24,0xd0,0x13,0x00,0x08,
+0x04,0x43,0x62,0xa0,0x0d,0x08,0x22,0x35,0x00,0x00,0x43,0x90,0x00,0x00,0x00,0x00,
+0x0f,0x00,0x63,0x30,0x08,0x00,0x62,0x2c,0x0f,0x00,0x63,0x38,0xa5,0xff,0x40,0x14,
+0x01,0x00,0x65,0x24,0x00,0x16,0x05,0x00,0x00,0x24,0x05,0x00,0x00,0x1a,0x05,0x00,
+0x25,0x10,0x44,0x00,0x25,0x10,0x43,0x00,0x25,0x10,0x45,0x00,0x25,0x18,0x65,0x00,
+0x18,0x43,0x43,0xad,0x35,0x14,0x00,0x08,0x14,0x43,0x42,0xad,0x04,0x00,0x02,0x24,
+0x0d,0x00,0x62,0x12,0xff,0x00,0x02,0x24,0x67,0xff,0x62,0x16,0xff,0x00,0xa2,0x31,
+0x2b,0x10,0xa2,0x02,0x1d,0x00,0x40,0x14,0xff,0x00,0xc2,0x31,0x2b,0x10,0xa2,0x02,
+0x0a,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0xfb,0x12,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x06,0x14,0x00,0x08,0x00,0x00,0x00,0x00,0x1d,0x43,0x42,0x91,0x00,0x00,0x00,0x00,
+0x2b,0x10,0x55,0x00,0xf8,0xff,0x40,0x10,0x00,0x00,0x00,0x00,0xc5,0x12,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x06,0x14,0x00,0x08,0x00,0x00,0x00,0x00,0x20,0x43,0x42,0x91,
+0x00,0x00,0x00,0x00,0x2b,0x10,0xa2,0x02,0xac,0xff,0x40,0x10,0x00,0x00,0x00,0x00,
+0x70,0x13,0x00,0x0c,0x00,0x00,0x00,0x00,0x06,0x14,0x00,0x08,0x00,0x00,0x00,0x00,
+0x2b,0x10,0xa2,0x02,0xe8,0xff,0x40,0x10,0x00,0x00,0x00,0x00,0x21,0x43,0x42,0x91,
+0x00,0x00,0x00,0x00,0x2b,0x10,0x55,0x00,0xa0,0xff,0x40,0x14,0x00,0x00,0x00,0x00,
+0x70,0x13,0x00,0x0c,0x00,0x00,0x00,0x00,0x06,0x14,0x00,0x08,0x00,0x00,0x00,0x00,
+0x02,0x80,0x08,0x3c,0x68,0x15,0x05,0x25,0xdc,0x63,0xa4,0x8c,0xe6,0x42,0xa3,0x90,
+0x02,0x11,0x04,0x00,0x1f,0x00,0x60,0x14,0x7f,0x00,0x46,0x30,0x25,0xb0,0x07,0x3c,
+0x4c,0x00,0xe2,0x34,0x00,0x00,0x43,0x90,0x00,0x00,0x00,0x00,0x19,0x00,0x60,0x10,
+0x00,0x00,0x00,0x00,0xff,0xff,0x02,0x34,0x16,0x00,0x82,0x10,0x00,0x00,0x00,0x00,
+0x00,0x08,0xe3,0x34,0x00,0x00,0x62,0x90,0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x30,
+0x12,0x00,0x40,0x10,0x4b,0x00,0xc2,0x2c,0x29,0x00,0x40,0x10,0x01,0x00,0x04,0x24,
+0xd8,0xff,0xc2,0x24,0x1e,0x00,0x42,0x2c,0x2f,0x00,0x40,0x10,0x23,0x00,0xc2,0x2c,
+0x68,0x15,0x04,0x25,0xd3,0x42,0x82,0x90,0x00,0x00,0x00,0x00,0x29,0x00,0x40,0x10,
+0x25,0xb0,0x02,0x3c,0x20,0x00,0x03,0x24,0x87,0x0c,0x42,0x34,0x00,0x00,0x43,0xa0,
+0xd3,0x42,0x80,0xa0,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x0f,0x00,0x40,0x10,
+0x01,0x00,0x04,0x24,0xd8,0xff,0xc2,0x24,0x1e,0x00,0x42,0x2c,0x2c,0x00,0x40,0x10,
+0x23,0x00,0xc2,0x2c,0x68,0x15,0x04,0x25,0xd3,0x42,0x82,0x90,0x00,0x00,0x00,0x00,
+0x26,0x00,0x40,0x10,0x25,0xb0,0x02,0x3c,0x44,0x00,0x03,0x24,0x30,0x0c,0x42,0x34,
+0x00,0x00,0x43,0xa0,0xed,0x14,0x00,0x08,0xd3,0x42,0x80,0xa0,0xd3,0x42,0xa2,0x90,
+0x00,0x00,0x00,0x00,0xef,0xff,0x44,0x10,0x30,0x0c,0xe3,0x34,0x43,0x00,0x02,0x24,
+0xd3,0x42,0xa4,0xa0,0x00,0x00,0x62,0xa0,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0xd3,0x42,0xa2,0x90,0x00,0x00,0x00,0x00,0xd5,0xff,0x44,0x10,0x87,0x0c,0xe3,0x34,
+0x10,0x00,0x02,0x24,0xd3,0x42,0xa4,0xa0,0x00,0x00,0x62,0xa0,0x06,0x15,0x00,0x08,
+0x00,0x00,0x00,0x00,0x23,0x00,0xc2,0x2c,0xda,0xff,0x40,0x10,0x00,0x00,0x00,0x00,
+0x68,0x15,0x04,0x25,0xd3,0x42,0x82,0x90,0x02,0x00,0x03,0x24,0xd5,0xff,0x43,0x10,
+0x00,0x00,0x00,0x00,0x25,0xb0,0x02,0x3c,0x87,0x0c,0x42,0x34,0xd3,0x42,0x83,0xa0,
+0x00,0x00,0x40,0xa0,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x23,0x00,0xc2,0x2c,
+0xcc,0xff,0x40,0x10,0x00,0x00,0x00,0x00,0x68,0x15,0x04,0x25,0xd3,0x42,0x82,0x90,
+0x02,0x00,0x03,0x24,0xc7,0xff,0x43,0x10,0x00,0x00,0x00,0x00,0x25,0xb0,0x02,0x3c,
+0xd3,0x42,0x83,0xa0,0x30,0x0c,0x42,0x34,0x42,0x00,0x03,0x24,0x00,0x00,0x43,0xa0,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x02,0x80,0x02,0x3c,0x68,0x15,0x45,0x24,
+0xd5,0x42,0xa3,0x90,0x02,0x00,0x02,0x24,0x03,0x00,0x62,0x10,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0xdc,0x63,0xa2,0x8c,0x25,0xb0,0x03,0x3c,
+0x0a,0x0a,0x68,0x34,0x02,0x11,0x02,0x00,0x7f,0x00,0x42,0x30,0x1a,0x00,0x44,0x2c,
+0x14,0x00,0x42,0x2c,0x01,0x0a,0x66,0x34,0x0b,0x00,0x40,0x14,0x2e,0x0a,0x67,0x34,
+0xf3,0xff,0x80,0x14,0x00,0x00,0x00,0x00,0xd4,0x42,0xa4,0x90,0x01,0x00,0x02,0x24,
+0x01,0x0a,0x67,0x34,0x0f,0x00,0x82,0x10,0x2e,0x0a,0x66,0x34,0xd4,0x42,0xa0,0xa0,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x40,0x00,0x02,0x24,0x00,0x00,0xc2,0xa0,
+0x01,0x00,0x03,0x24,0xdf,0xff,0x02,0x24,0xd4,0x42,0xa3,0xa0,0x00,0x00,0xe2,0xa0,
+0x03,0x00,0x03,0x24,0x21,0x10,0x00,0x00,0x00,0x00,0x03,0xa1,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x47,0x00,0x02,0x24,0x00,0x00,0xe2,0xa0,0xd3,0xff,0x03,0x24,
+0x83,0xff,0x02,0x24,0x00,0x00,0xc3,0xa0,0x00,0x00,0x02,0xa1,0x48,0x15,0x00,0x08,
+0xd4,0x42,0xa0,0xa0,0xd0,0xff,0xbd,0x27,0x1c,0x00,0xb1,0xaf,0x28,0x00,0xbf,0xaf,
+0x24,0x00,0xb3,0xaf,0x20,0x00,0xb2,0xaf,0x18,0x00,0xb0,0xaf,0xff,0xff,0x11,0x24,
+0x02,0x80,0x13,0x3c,0x41,0xb0,0x02,0x3c,0x68,0x15,0x66,0x26,0x04,0x00,0x42,0x34,
+0x00,0x00,0x47,0x8c,0x00,0x4b,0xc5,0x8c,0x02,0x80,0x03,0x3c,0x96,0x7d,0x64,0x90,
+0xfc,0x4a,0xc8,0x8c,0x02,0x80,0x02,0x3c,0xb8,0x7d,0x49,0x90,0x25,0xb0,0x0a,0x3c,
+0x25,0x90,0xa7,0x00,0xb0,0x03,0x42,0x35,0x00,0x00,0x52,0xac,0x00,0x24,0x04,0x00,
+0x00,0x00,0x48,0xac,0x84,0x02,0x43,0x35,0x8c,0x02,0x45,0x35,0x01,0x00,0x02,0x24,
+0x00,0x00,0x72,0xac,0x00,0x00,0xa4,0xac,0xb9,0x04,0x22,0x11,0x00,0x4b,0xd2,0xac,
+0x68,0x15,0x66,0x26,0xfc,0x4a,0xc2,0x8c,0x00,0x00,0x00,0x00,0x24,0x28,0x52,0x00,
+0x01,0x00,0xa3,0x30,0x09,0x00,0x60,0x10,0x04,0x00,0xa2,0x30,0x00,0x4b,0xc2,0x8c,
+0x25,0xb0,0x03,0x3c,0x01,0x00,0x04,0x24,0x01,0x00,0x42,0x38,0xb0,0x03,0x63,0x34,
+0x00,0x00,0x64,0xac,0x00,0x4b,0xc2,0xac,0x04,0x00,0xa2,0x30,0x09,0x00,0x40,0x10,
+0x08,0x00,0xa2,0x30,0x00,0x4b,0xc2,0x8c,0x25,0xb0,0x03,0x3c,0x04,0x00,0x04,0x24,
+0x04,0x00,0x42,0x38,0xb0,0x03,0x63,0x34,0x00,0x00,0x64,0xac,0x00,0x4b,0xc2,0xac,
+0x08,0x00,0xa2,0x30,0x0e,0x00,0x40,0x10,0x68,0x15,0x64,0x26,0xc9,0x64,0xc2,0x90,
+0x00,0x00,0x00,0x00,0x05,0x00,0x40,0x18,0x2a,0xb0,0x02,0x3c,0x02,0x00,0x03,0x24,
+0x01,0x00,0x42,0x34,0x00,0x00,0x43,0xa0,0xc9,0x64,0xc0,0xa0,0x00,0x4b,0xc2,0x8c,
+0x00,0x00,0x00,0x00,0x08,0x00,0x42,0x38,0x00,0x4b,0xc2,0xac,0x68,0x15,0x64,0x26,
+0xfc,0x4a,0x82,0x8c,0x00,0x00,0x00,0x00,0x24,0x10,0x52,0x00,0x10,0x00,0x42,0x30,
+0x0d,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0xc9,0x64,0x82,0x90,0x00,0x00,0x00,0x00,
+0x05,0x00,0x40,0x18,0x2a,0xb0,0x02,0x3c,0x02,0x00,0x03,0x24,0x01,0x00,0x42,0x34,
+0x00,0x00,0x43,0xa0,0xc9,0x64,0x80,0xa0,0x00,0x4b,0x82,0x8c,0x00,0x00,0x00,0x00,
+0x10,0x00,0x42,0x38,0x00,0x4b,0x82,0xac,0x68,0x15,0x64,0x26,0xfc,0x4a,0x82,0x8c,
+0x00,0x00,0x00,0x00,0x24,0x10,0x52,0x00,0x20,0x00,0x42,0x30,0x0e,0x00,0x40,0x10,
+0x00,0x00,0x00,0x00,0xc9,0x64,0x82,0x90,0x00,0x00,0x00,0x00,0x05,0x00,0x40,0x18,
+0x2a,0xb0,0x02,0x3c,0x02,0x00,0x03,0x24,0x01,0x00,0x42,0x34,0x00,0x00,0x43,0xa0,
+0xc9,0x64,0x80,0xa0,0x00,0x4b,0x82,0x8c,0x00,0x00,0x00,0x00,0x20,0x00,0x42,0x38,
+0x00,0x4b,0x82,0xac,0x68,0x15,0x64,0x26,0xfc,0x4a,0x82,0x8c,0x00,0x00,0x00,0x00,
+0x24,0x10,0x52,0x00,0x40,0x00,0x42,0x30,0x0d,0x00,0x40,0x10,0x00,0x00,0x00,0x00,
+0xc9,0x64,0x82,0x90,0x00,0x00,0x00,0x00,0x05,0x00,0x40,0x18,0x2a,0xb0,0x02,0x3c,
+0x02,0x00,0x03,0x24,0x01,0x00,0x42,0x34,0x00,0x00,0x43,0xa0,0xc9,0x64,0x80,0xa0,
+0x00,0x4b,0x82,0x8c,0x00,0x00,0x00,0x00,0x40,0x00,0x42,0x38,0x00,0x4b,0x82,0xac,
+0x68,0x15,0x64,0x26,0xfc,0x4a,0x82,0x8c,0x00,0x00,0x00,0x00,0x24,0x10,0x52,0x00,
+0x80,0x00,0x42,0x30,0x0e,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0xc9,0x64,0x82,0x90,
+0x00,0x00,0x00,0x00,0x05,0x00,0x40,0x18,0x2a,0xb0,0x02,0x3c,0x02,0x00,0x03,0x24,
+0x01,0x00,0x42,0x34,0x00,0x00,0x43,0xa0,0xc9,0x64,0x80,0xa0,0x00,0x4b,0x82,0x8c,
+0x00,0x00,0x00,0x00,0x80,0x00,0x42,0x38,0x00,0x4b,0x82,0xac,0x68,0x15,0x64,0x26,
+0xfc,0x4a,0x82,0x8c,0x00,0x00,0x00,0x00,0x24,0x10,0x52,0x00,0x00,0x01,0x42,0x30,
+0x0d,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0xc9,0x64,0x82,0x90,0x00,0x00,0x00,0x00,
+0x05,0x00,0x40,0x18,0x2a,0xb0,0x02,0x3c,0x02,0x00,0x03,0x24,0x01,0x00,0x42,0x34,
+0x00,0x00,0x43,0xa0,0xc9,0x64,0x80,0xa0,0x00,0x4b,0x82,0x8c,0x00,0x00,0x00,0x00,
+0x00,0x01,0x42,0x38,0x00,0x4b,0x82,0xac,0x68,0x15,0x64,0x26,0xfc,0x4a,0x82,0x8c,
+0x00,0x00,0x00,0x00,0x24,0x10,0x52,0x00,0x00,0x02,0x42,0x30,0x0e,0x00,0x40,0x10,
+0x00,0x00,0x00,0x00,0xc9,0x64,0x82,0x90,0x00,0x00,0x00,0x00,0x05,0x00,0x40,0x18,
+0x2a,0xb0,0x02,0x3c,0x02,0x00,0x03,0x24,0x01,0x00,0x42,0x34,0x00,0x00,0x43,0xa0,
+0xc9,0x64,0x80,0xa0,0x00,0x4b,0x82,0x8c,0x00,0x00,0x00,0x00,0x00,0x02,0x42,0x38,
+0x00,0x4b,0x82,0xac,0x68,0x15,0x64,0x26,0xfc,0x4a,0x82,0x8c,0x00,0x00,0x00,0x00,
+0x24,0x10,0x52,0x00,0x00,0x04,0x42,0x30,0x0d,0x00,0x40,0x10,0x00,0x00,0x00,0x00,
+0xc9,0x64,0x82,0x90,0x00,0x00,0x00,0x00,0x05,0x00,0x40,0x18,0x2a,0xb0,0x02,0x3c,
+0x02,0x00,0x03,0x24,0x01,0x00,0x42,0x34,0x00,0x00,0x43,0xa0,0xc9,0x64,0x80,0xa0,
+0x00,0x4b,0x82,0x8c,0x00,0x00,0x00,0x00,0x00,0x04,0x42,0x38,0x00,0x4b,0x82,0xac,
+0x68,0x15,0x63,0x26,0xfc,0x4a,0x62,0x8c,0x00,0x00,0x00,0x00,0x24,0x10,0x52,0x00,
+0x00,0x08,0x42,0x30,0x3a,0x00,0x40,0x10,0x2a,0xb0,0x05,0x3c,0x00,0x00,0xa8,0x8c,
+0xff,0x00,0x02,0x24,0xff,0x00,0x04,0x31,0x31,0x00,0x82,0x10,0x00,0x80,0x02,0x31,
+0x08,0x04,0x40,0x14,0x00,0x80,0x02,0x3c,0x00,0xff,0x02,0x3c,0x24,0x10,0x02,0x01,
+0x05,0x00,0x40,0x14,0x00,0x00,0x00,0x00,0xc9,0x64,0x62,0x90,0x00,0x00,0x00,0x00,
+0x0b,0x00,0x40,0x18,0xff,0x00,0x02,0x24,0x08,0x64,0x62,0x90,0x20,0xb0,0x03,0x3c,
+0x00,0x12,0x02,0x00,0x21,0x10,0x43,0x00,0x0c,0x00,0x48,0x8c,0x25,0xb0,0x03,0x3c,
+0xb0,0x03,0x63,0x34,0x00,0x00,0x68,0xac,0xff,0x00,0x04,0x31,0xff,0x00,0x02,0x24,
+0x1a,0x00,0x82,0x10,0x68,0x15,0x70,0x26,0xff,0x00,0x03,0x31,0xc0,0x64,0x05,0x8e,
+0x20,0x10,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,0x21,0x30,0x60,0x00,
+0x54,0x64,0x03,0xae,0x21,0x20,0x00,0x00,0x08,0x64,0x08,0xa2,0x20,0x00,0x07,0x24,
+0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0xfc,0x4a,0x05,0x8e,0x02,0x80,0x06,0x3c,
+0x6c,0x7e,0xc4,0x8c,0xff,0xc7,0x02,0x24,0x24,0x28,0xa2,0x00,0x25,0xb0,0x02,0x3c,
+0x04,0x00,0x84,0x34,0x80,0x03,0x42,0x34,0x41,0xb0,0x03,0x3c,0x00,0x00,0x44,0xac,
+0x00,0x00,0x65,0xac,0x6c,0x7e,0xc4,0xac,0xfc,0x4a,0x05,0xae,0x68,0x15,0x63,0x26,
+0x00,0x4b,0x62,0x8c,0x00,0x00,0x00,0x00,0x00,0x08,0x42,0x38,0x00,0x4b,0x62,0xac,
+0x68,0x15,0x65,0x26,0xfc,0x4a,0xa2,0x8c,0x00,0x00,0x00,0x00,0x24,0x10,0x52,0x00,
+0x00,0x10,0x42,0x30,0x38,0x00,0x40,0x10,0x2a,0xb0,0x02,0x3c,0x08,0x00,0x43,0x34,
+0x00,0x00,0x68,0x8c,0xff,0x00,0x02,0x24,0xff,0x00,0x04,0x31,0x2c,0x00,0x82,0x10,
+0x00,0x80,0x02,0x31,0xca,0x03,0x40,0x14,0x00,0x80,0x02,0x3c,0x00,0xff,0x02,0x3c,
+0x24,0x10,0x02,0x01,0x0b,0x00,0x40,0x10,0xff,0x00,0x02,0x24,0x10,0x64,0xa2,0x90,
+0x20,0xb0,0x03,0x3c,0x00,0x12,0x02,0x00,0x21,0x10,0x43,0x00,0x0c,0x00,0x48,0x8c,
+0x25,0xb0,0x03,0x3c,0xb0,0x03,0x63,0x34,0x00,0x00,0x68,0xac,0xff,0x00,0x04,0x31,
+0xff,0x00,0x02,0x24,0x1a,0x00,0x82,0x10,0x68,0x15,0x70,0x26,0xff,0x00,0x03,0x31,
+0xd8,0x64,0x05,0x8e,0x20,0x10,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,
+0x21,0x30,0x60,0x00,0x6c,0x64,0x03,0xae,0x01,0x00,0x04,0x24,0x10,0x64,0x08,0xa2,
+0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0xfc,0x4a,0x05,0x8e,
+0x02,0x80,0x06,0x3c,0x6c,0x7e,0xc4,0x8c,0xff,0xc7,0x02,0x24,0x24,0x28,0xa2,0x00,
+0x25,0xb0,0x02,0x3c,0x10,0x00,0x84,0x34,0x80,0x03,0x42,0x34,0x41,0xb0,0x03,0x3c,
+0x00,0x00,0x44,0xac,0x00,0x00,0x65,0xac,0x6c,0x7e,0xc4,0xac,0xfc,0x4a,0x05,0xae,
+0x68,0x15,0x63,0x26,0x00,0x4b,0x62,0x8c,0x00,0x00,0x00,0x00,0x00,0x10,0x42,0x38,
+0x00,0x4b,0x62,0xac,0x68,0x15,0x65,0x26,0xfc,0x4a,0xa2,0x8c,0x00,0x00,0x00,0x00,
+0x24,0x10,0x52,0x00,0x00,0x20,0x42,0x30,0x37,0x00,0x40,0x10,0x2a,0xb0,0x02,0x3c,
+0x04,0x00,0x43,0x34,0x00,0x00,0x68,0x8c,0xff,0x00,0x02,0x24,0xff,0x00,0x04,0x31,
+0xab,0x03,0x82,0x10,0x00,0x80,0x02,0x31,0x90,0x03,0x40,0x14,0x00,0x80,0x02,0x3c,
+0x00,0xff,0x02,0x3c,0x24,0x10,0x02,0x01,0x0b,0x00,0x40,0x10,0xff,0x00,0x02,0x24,
+0x0c,0x64,0xa2,0x90,0x20,0xb0,0x03,0x3c,0x00,0x12,0x02,0x00,0x21,0x10,0x43,0x00,
+0x0c,0x00,0x48,0x8c,0x25,0xb0,0x03,0x3c,0xb0,0x03,0x63,0x34,0x00,0x00,0x68,0xac,
+0xff,0x00,0x04,0x31,0xff,0x00,0x02,0x24,0x1a,0x00,0x82,0x10,0xff,0x00,0x03,0x31,
+0x68,0x15,0x70,0x26,0xcc,0x64,0x05,0x8e,0x20,0x10,0x02,0x3c,0x00,0x1a,0x03,0x00,
+0x21,0x18,0x62,0x00,0x21,0x30,0x60,0x00,0x60,0x64,0x03,0xae,0x01,0x00,0x04,0x24,
+0x0c,0x64,0x08,0xa2,0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,
+0xfc,0x4a,0x05,0x8e,0x02,0x80,0x06,0x3c,0x6c,0x7e,0xc4,0x8c,0xff,0xc7,0x02,0x24,
+0x24,0x28,0xa2,0x00,0x25,0xb0,0x02,0x3c,0x20,0x00,0x84,0x34,0x80,0x03,0x42,0x34,
+0x41,0xb0,0x03,0x3c,0x00,0x00,0x44,0xac,0x00,0x00,0x65,0xac,0x6c,0x7e,0xc4,0xac,
+0xfc,0x4a,0x05,0xae,0x68,0x15,0x63,0x26,0x00,0x4b,0x62,0x8c,0x00,0x00,0x00,0x00,
+0x00,0x20,0x42,0x38,0x00,0x4b,0x62,0xac,0x68,0x15,0x65,0x26,0xfc,0x4a,0xa2,0x8c,
+0x00,0x00,0x00,0x00,0x24,0x10,0x52,0x00,0x00,0x80,0x42,0x30,0x59,0x00,0x40,0x10,
+0x2a,0xb0,0x06,0x3c,0x0c,0x00,0xc3,0x34,0x00,0x00,0x68,0x8c,0xff,0x00,0x07,0x24,
+0xff,0x00,0x04,0x31,0x78,0x03,0x87,0x10,0x00,0x80,0x02,0x31,0x24,0x00,0x40,0x14,
+0x00,0x80,0x02,0x3c,0x00,0xff,0x02,0x3c,0x24,0x10,0x02,0x01,0x22,0x00,0x40,0x10,
+0xff,0x00,0x02,0x24,0x40,0x00,0xc6,0x34,0x00,0x00,0xc2,0x90,0x00,0x00,0x00,0x00,
+0xff,0x00,0x44,0x30,0x0f,0x00,0x87,0x10,0x68,0x15,0x62,0x26,0xe8,0x63,0xa4,0xa0,
+0x00,0x00,0xc2,0x90,0xff,0x00,0x83,0x30,0xff,0x00,0x44,0x30,0x09,0x00,0x83,0x10,
+0x68,0x15,0x62,0x26,0x21,0x38,0xa0,0x00,0x21,0x28,0xc0,0x00,0x00,0x00,0xa2,0x90,
+0x21,0x18,0x80,0x00,0xfd,0xff,0x62,0x14,0xff,0x00,0x44,0x30,0xe8,0x63,0xe3,0xa0,
+0x68,0x15,0x62,0x26,0xe8,0x63,0x43,0x90,0x20,0xb0,0x02,0x3c,0x00,0x1a,0x03,0x00,
+0x21,0x18,0x62,0x00,0x0c,0x00,0x68,0x8c,0x25,0xb0,0x02,0x3c,0xb0,0x03,0x42,0x34,
+0xff,0x00,0x04,0x31,0x00,0x00,0x48,0xac,0x16,0x17,0x00,0x08,0xff,0x00,0x02,0x24,
+0x00,0x00,0x62,0xac,0xff,0x00,0x02,0x24,0x24,0x00,0x82,0x10,0x68,0x15,0x70,0x26,
+0xff,0x00,0x03,0x31,0x90,0x64,0x05,0x8e,0x20,0x10,0x02,0x3c,0x00,0x1a,0x03,0x00,
+0x21,0x18,0x62,0x00,0x21,0x30,0x60,0x00,0xe8,0x63,0x08,0xa2,0x24,0x64,0x03,0xae,
+0x03,0x00,0x04,0x24,0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,
+0x02,0x80,0x0a,0x3c,0x7c,0x7e,0x47,0x91,0x02,0x80,0x09,0x3c,0x6c,0x7e,0x25,0x8d,
+0xfc,0x4a,0x06,0x8e,0x01,0x00,0x08,0x3c,0x80,0xff,0x02,0x24,0x25,0x38,0xe2,0x00,
+0x00,0x80,0x03,0x35,0x80,0x00,0xa5,0x34,0x27,0x18,0x03,0x00,0x00,0x26,0x07,0x00,
+0x25,0xb0,0x02,0x3c,0x24,0x30,0xc3,0x00,0x25,0x20,0x85,0x00,0x80,0x03,0x42,0x34,
+0x41,0xb0,0x03,0x3c,0x00,0x00,0x44,0xac,0x27,0x88,0x08,0x00,0x00,0x00,0x66,0xac,
+0x6c,0x7e,0x25,0xad,0x7c,0x7e,0x47,0xa1,0xfc,0x4a,0x06,0xae,0x68,0x15,0x63,0x26,
+0x00,0x4b,0x62,0x8c,0x00,0x00,0x00,0x00,0x00,0x80,0x42,0x38,0x00,0x4b,0x62,0xac,
+0x68,0x15,0x65,0x26,0xfc,0x4a,0xa2,0x8c,0x01,0x00,0x03,0x3c,0x24,0x10,0x52,0x00,
+0x24,0x10,0x51,0x00,0x24,0x10,0x43,0x00,0x56,0x00,0x40,0x10,0x2a,0xb0,0x06,0x3c,
+0x10,0x00,0xc3,0x34,0x00,0x00,0x68,0x8c,0xff,0x00,0x07,0x24,0xff,0x00,0x04,0x31,
+0x23,0x03,0x87,0x10,0x25,0xb0,0x02,0x3c,0x00,0x80,0x02,0x31,0x23,0x00,0x40,0x14,
+0x00,0x80,0x02,0x3c,0x00,0xff,0x02,0x3c,0x24,0x10,0x02,0x01,0x21,0x00,0x40,0x10,
+0xff,0x00,0x02,0x24,0x41,0x00,0xc6,0x34,0x00,0x00,0xc2,0x90,0x00,0x00,0x00,0x00,
+0xff,0x00,0x44,0x30,0x0e,0x00,0x87,0x10,0x68,0x15,0x62,0x26,0xec,0x63,0xa4,0xa0,
+0x00,0x00,0xc2,0x90,0xff,0x00,0x83,0x30,0xff,0x00,0x44,0x30,0x07,0x00,0x83,0x10,
+0x21,0x38,0xa0,0x00,0x21,0x28,0xc0,0x00,0x00,0x00,0xa2,0x90,0x21,0x18,0x80,0x00,
+0xfd,0xff,0x62,0x14,0xff,0x00,0x44,0x30,0xec,0x63,0xe3,0xa0,0x68,0x15,0x62,0x26,
+0xec,0x63,0x43,0x90,0x20,0xb0,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,
+0x0c,0x00,0x68,0x8c,0x25,0xb0,0x02,0x3c,0xb0,0x03,0x42,0x34,0xff,0x00,0x04,0x31,
+0x00,0x00,0x48,0xac,0x75,0x17,0x00,0x08,0xff,0x00,0x02,0x24,0x00,0x00,0x62,0xac,
+0xff,0x00,0x02,0x24,0x22,0x00,0x82,0x10,0x68,0x15,0x70,0x26,0xff,0x00,0x03,0x31,
+0x90,0x64,0x05,0x8e,0x20,0x10,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,
+0x21,0x30,0x60,0x00,0xec,0x63,0x08,0xa2,0x24,0x64,0x03,0xae,0x03,0x00,0x04,0x24,
+0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0x02,0x80,0x09,0x3c,
+0x7c,0x7e,0x27,0x91,0x02,0x80,0x08,0x3c,0x6c,0x7e,0x05,0x8d,0xfc,0x4a,0x06,0x8e,
+0x01,0x00,0x02,0x3c,0x00,0x80,0x42,0x34,0x40,0x00,0xe7,0x34,0x27,0x10,0x02,0x00,
+0x24,0x30,0xc2,0x00,0x80,0x00,0xa5,0x34,0x00,0x26,0x07,0x00,0x25,0xb0,0x02,0x3c,
+0x25,0x20,0x85,0x00,0x80,0x03,0x42,0x34,0x41,0xb0,0x03,0x3c,0x00,0x00,0x44,0xac,
+0x00,0x00,0x66,0xac,0x6c,0x7e,0x05,0xad,0x7c,0x7e,0x27,0xa1,0xfc,0x4a,0x06,0xae,
+0x68,0x15,0x62,0x26,0x00,0x4b,0x43,0x8c,0x01,0x00,0x04,0x3c,0x26,0x18,0x64,0x00,
+0x00,0x4b,0x43,0xac,0x68,0x15,0x65,0x26,0xfc,0x4a,0xa2,0x8c,0x02,0x00,0x03,0x3c,
+0x24,0x10,0x52,0x00,0x24,0x10,0x43,0x00,0x5a,0x00,0x40,0x10,0x2a,0xb0,0x06,0x3c,
+0x14,0x00,0xc3,0x34,0x00,0x00,0x68,0x8c,0xff,0x00,0x07,0x24,0xff,0x00,0x04,0x31,
+0xcc,0x02,0x87,0x10,0x25,0xb0,0x02,0x3c,0x00,0x80,0x02,0x31,0x23,0x00,0x40,0x14,
+0x00,0x80,0x02,0x3c,0x00,0xff,0x02,0x3c,0x24,0x10,0x02,0x01,0x21,0x00,0x40,0x10,
+0xff,0x00,0x02,0x24,0x42,0x00,0xc6,0x34,0x00,0x00,0xc2,0x90,0x00,0x00,0x00,0x00,
+0xff,0x00,0x44,0x30,0x0e,0x00,0x87,0x10,0x68,0x15,0x62,0x26,0xf0,0x63,0xa4,0xa0,
+0x00,0x00,0xc2,0x90,0xff,0x00,0x83,0x30,0xff,0x00,0x44,0x30,0x07,0x00,0x83,0x10,
+0x21,0x38,0xa0,0x00,0x21,0x28,0xc0,0x00,0x00,0x00,0xa2,0x90,0x21,0x18,0x80,0x00,
+0xfd,0xff,0x62,0x14,0xff,0x00,0x44,0x30,0xf0,0x63,0xe3,0xa0,0x68,0x15,0x62,0x26,
+0xf0,0x63,0x43,0x90,0x20,0xb0,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,
+0x0c,0x00,0x68,0x8c,0x25,0xb0,0x02,0x3c,0xb0,0x03,0x42,0x34,0xff,0x00,0x04,0x31,
+0x00,0x00,0x48,0xac,0xd1,0x17,0x00,0x08,0xff,0x00,0x02,0x24,0x00,0x00,0x62,0xac,
+0xff,0x00,0x02,0x24,0x25,0x00,0x82,0x10,0x68,0x15,0x70,0x26,0xff,0x00,0x03,0x31,
+0x9c,0x64,0x05,0x8e,0x20,0x10,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,
+0x21,0x30,0x60,0x00,0xf0,0x63,0x08,0xa2,0x30,0x64,0x03,0xae,0x04,0x00,0x04,0x24,
+0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0x02,0x80,0x0a,0x3c,
+0x7c,0x7e,0x47,0x91,0x02,0x80,0x09,0x3c,0x6c,0x7e,0x25,0x8d,0xfc,0x4a,0x06,0x8e,
+0x06,0x00,0x02,0x3c,0x20,0x00,0xe7,0x34,0x27,0x10,0x02,0x00,0x24,0x30,0xc2,0x00,
+0x00,0x01,0xa5,0x34,0x25,0xb0,0x03,0x3c,0x04,0x00,0x02,0x3c,0x00,0x26,0x07,0x00,
+0x26,0x88,0x22,0x02,0xb0,0x03,0x68,0x34,0x25,0x20,0x85,0x00,0x80,0x03,0x63,0x34,
+0x41,0xb0,0x02,0x3c,0x00,0x00,0x64,0xac,0x00,0x00,0x46,0xac,0x6c,0x7e,0x25,0xad,
+0x7c,0x7e,0x47,0xa1,0xfc,0x4a,0x06,0xae,0x00,0x00,0x11,0xad,0x68,0x15,0x62,0x26,
+0x00,0x4b,0x43,0x8c,0x02,0x00,0x04,0x3c,0x26,0x18,0x64,0x00,0x00,0x4b,0x43,0xac,
+0x68,0x15,0x65,0x26,0xfc,0x4a,0xa2,0x8c,0x04,0x00,0x03,0x3c,0x24,0x10,0x52,0x00,
+0x24,0x10,0x51,0x00,0x24,0x10,0x43,0x00,0x58,0x00,0x40,0x10,0x25,0xb0,0x03,0x3c,
+0xb0,0x03,0x62,0x34,0x2a,0xb0,0x09,0x3c,0x00,0x00,0x51,0xac,0x18,0x00,0x26,0x35,
+0x00,0x00,0xc8,0x8c,0xff,0x00,0x07,0x24,0xff,0x00,0x04,0x31,0x3a,0x02,0x87,0x10,
+0x04,0x00,0x02,0x24,0x00,0x80,0x02,0x31,0x23,0x00,0x40,0x14,0x00,0x80,0x02,0x3c,
+0x00,0xff,0x02,0x3c,0x24,0x10,0x02,0x01,0x21,0x00,0x40,0x10,0xff,0x00,0x02,0x24,
+0x43,0x00,0x26,0x35,0x00,0x00,0xc2,0x90,0x00,0x00,0x00,0x00,0xff,0x00,0x44,0x30,
+0x0e,0x00,0x87,0x10,0x68,0x15,0x62,0x26,0xf4,0x63,0xa4,0xa0,0x00,0x00,0xc2,0x90,
+0xff,0x00,0x83,0x30,0xff,0x00,0x44,0x30,0x07,0x00,0x83,0x10,0x21,0x38,0xa0,0x00,
+0x21,0x28,0xc0,0x00,0x00,0x00,0xa2,0x90,0x21,0x18,0x80,0x00,0xfd,0xff,0x62,0x14,
+0xff,0x00,0x44,0x30,0xf4,0x63,0xe3,0xa0,0x68,0x15,0x62,0x26,0xf4,0x63,0x43,0x90,
+0x20,0xb0,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,0x0c,0x00,0x68,0x8c,
+0x25,0xb0,0x02,0x3c,0xb0,0x03,0x42,0x34,0xff,0x00,0x04,0x31,0x00,0x00,0x48,0xac,
+0x34,0x18,0x00,0x08,0xff,0x00,0x02,0x24,0x00,0x00,0xc2,0xac,0xff,0x00,0x02,0x24,
+0x21,0x00,0x82,0x10,0x68,0x15,0x70,0x26,0xff,0x00,0x03,0x31,0x9c,0x64,0x05,0x8e,
+0x20,0x10,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,0x21,0x30,0x60,0x00,
+0xf4,0x63,0x08,0xa2,0x30,0x64,0x03,0xae,0x04,0x00,0x04,0x24,0x20,0x00,0x07,0x24,
+0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0x02,0x80,0x09,0x3c,0x7c,0x7e,0x27,0x91,
+0x02,0x80,0x08,0x3c,0x6c,0x7e,0x05,0x8d,0xfc,0x4a,0x06,0x8e,0x06,0x00,0x02,0x3c,
+0x10,0x00,0xe7,0x34,0x27,0x10,0x02,0x00,0x24,0x30,0xc2,0x00,0x00,0x01,0xa5,0x34,
+0x00,0x26,0x07,0x00,0x25,0xb0,0x02,0x3c,0x25,0x20,0x85,0x00,0x80,0x03,0x42,0x34,
+0x41,0xb0,0x03,0x3c,0x00,0x00,0x44,0xac,0x00,0x00,0x66,0xac,0x6c,0x7e,0x05,0xad,
+0x7c,0x7e,0x27,0xa1,0xfc,0x4a,0x06,0xae,0x68,0x15,0x62,0x26,0x00,0x4b,0x43,0x8c,
+0x04,0x00,0x04,0x3c,0x26,0x18,0x64,0x00,0x00,0x4b,0x43,0xac,0x68,0x15,0x65,0x26,
+0xfc,0x4a,0xa2,0x8c,0x08,0x00,0x03,0x3c,0x24,0x10,0x52,0x00,0x24,0x10,0x43,0x00,
+0x5a,0x00,0x40,0x10,0x2a,0xb0,0x06,0x3c,0x1c,0x00,0xc3,0x34,0x00,0x00,0x68,0x8c,
+0xff,0x00,0x07,0x24,0xff,0x00,0x04,0x31,0x13,0x02,0x87,0x10,0x25,0xb0,0x02,0x3c,
+0x00,0x80,0x02,0x31,0x23,0x00,0x40,0x14,0x00,0x80,0x02,0x3c,0x00,0xff,0x02,0x3c,
+0x24,0x10,0x02,0x01,0x21,0x00,0x40,0x10,0xff,0x00,0x02,0x24,0x44,0x00,0xc6,0x34,
+0x00,0x00,0xc2,0x90,0x00,0x00,0x00,0x00,0xff,0x00,0x44,0x30,0x0e,0x00,0x87,0x10,
+0x68,0x15,0x62,0x26,0xf8,0x63,0xa4,0xa0,0x00,0x00,0xc2,0x90,0xff,0x00,0x83,0x30,
+0xff,0x00,0x44,0x30,0x07,0x00,0x83,0x10,0x21,0x38,0xa0,0x00,0x21,0x28,0xc0,0x00,
+0x00,0x00,0xa2,0x90,0x21,0x18,0x80,0x00,0xfd,0xff,0x62,0x14,0xff,0x00,0x44,0x30,
+0xf8,0x63,0xe3,0xa0,0x68,0x15,0x62,0x26,0xf8,0x63,0x43,0x90,0x20,0xb0,0x02,0x3c,
+0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,0x0c,0x00,0x68,0x8c,0x25,0xb0,0x02,0x3c,
+0xb0,0x03,0x42,0x34,0xff,0x00,0x04,0x31,0x00,0x00,0x48,0xac,0x8f,0x18,0x00,0x08,
+0xff,0x00,0x02,0x24,0x00,0x00,0x62,0xac,0xff,0x00,0x02,0x24,0x25,0x00,0x82,0x10,
+0x68,0x15,0x70,0x26,0xff,0x00,0x03,0x31,0xa8,0x64,0x05,0x8e,0x20,0x10,0x02,0x3c,
+0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,0x21,0x30,0x60,0x00,0xf8,0x63,0x08,0xa2,
+0x3c,0x64,0x03,0xae,0x05,0x00,0x04,0x24,0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,
+0x10,0x00,0xa0,0xaf,0x02,0x80,0x0a,0x3c,0x7c,0x7e,0x47,0x91,0x02,0x80,0x09,0x3c,
+0x6c,0x7e,0x25,0x8d,0xfc,0x4a,0x06,0x8e,0x18,0x00,0x02,0x3c,0x08,0x00,0xe7,0x34,
+0x27,0x10,0x02,0x00,0x24,0x30,0xc2,0x00,0x00,0x02,0xa5,0x34,0x25,0xb0,0x03,0x3c,
+0x10,0x00,0x02,0x3c,0x00,0x26,0x07,0x00,0x26,0x88,0x22,0x02,0xb0,0x03,0x68,0x34,
+0x25,0x20,0x85,0x00,0x80,0x03,0x63,0x34,0x41,0xb0,0x02,0x3c,0x00,0x00,0x64,0xac,
+0x00,0x00,0x46,0xac,0x6c,0x7e,0x25,0xad,0x7c,0x7e,0x47,0xa1,0xfc,0x4a,0x06,0xae,
+0x00,0x00,0x11,0xad,0x68,0x15,0x62,0x26,0x00,0x4b,0x43,0x8c,0x08,0x00,0x04,0x3c,
+0x26,0x18,0x64,0x00,0x00,0x4b,0x43,0xac,0x68,0x15,0x65,0x26,0xfc,0x4a,0xa2,0x8c,
+0x10,0x00,0x03,0x3c,0x24,0x10,0x52,0x00,0x24,0x10,0x51,0x00,0x24,0x10,0x43,0x00,
+0x58,0x00,0x40,0x10,0x25,0xb0,0x06,0x3c,0xb0,0x03,0xc2,0x34,0x2a,0xb0,0x09,0x3c,
+0x00,0x00,0x51,0xac,0x20,0x00,0x23,0x35,0x00,0x00,0x68,0x8c,0xff,0x00,0x07,0x24,
+0xff,0x00,0x04,0x31,0x80,0x01,0x87,0x10,0x90,0x03,0xc2,0x34,0x00,0x80,0x02,0x31,
+0x23,0x00,0x40,0x14,0x00,0x80,0x02,0x3c,0x00,0xff,0x02,0x3c,0x24,0x10,0x02,0x01,
+0x21,0x00,0x40,0x10,0xff,0x00,0x02,0x24,0x45,0x00,0x26,0x35,0x00,0x00,0xc2,0x90,
+0x00,0x00,0x00,0x00,0xff,0x00,0x44,0x30,0x0e,0x00,0x87,0x10,0x68,0x15,0x62,0x26,
+0x04,0x64,0xa4,0xa0,0x00,0x00,0xc2,0x90,0xff,0x00,0x83,0x30,0xff,0x00,0x44,0x30,
+0x07,0x00,0x83,0x10,0x21,0x38,0xa0,0x00,0x21,0x28,0xc0,0x00,0x00,0x00,0xa2,0x90,
+0x21,0x18,0x80,0x00,0xfd,0xff,0x62,0x14,0xff,0x00,0x44,0x30,0x04,0x64,0xe3,0xa0,
+0x68,0x15,0x62,0x26,0x04,0x64,0x43,0x90,0x20,0xb0,0x02,0x3c,0x00,0x1a,0x03,0x00,
+0x21,0x18,0x62,0x00,0x0c,0x00,0x68,0x8c,0x25,0xb0,0x02,0x3c,0xb0,0x03,0x42,0x34,
+0xff,0x00,0x04,0x31,0x00,0x00,0x48,0xac,0xf2,0x18,0x00,0x08,0xff,0x00,0x02,0x24,
+0x00,0x00,0x62,0xac,0xff,0x00,0x02,0x24,0x21,0x00,0x82,0x10,0x68,0x15,0x70,0x26,
+0xff,0x00,0x03,0x31,0xa8,0x64,0x05,0x8e,0x20,0x10,0x02,0x3c,0x00,0x1a,0x03,0x00,
+0x21,0x18,0x62,0x00,0x21,0x30,0x60,0x00,0x04,0x64,0x08,0xa2,0x3c,0x64,0x03,0xae,
+0x05,0x00,0x04,0x24,0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,
+0x02,0x80,0x09,0x3c,0x7c,0x7e,0x27,0x91,0x02,0x80,0x08,0x3c,0x6c,0x7e,0x05,0x8d,
+0xfc,0x4a,0x06,0x8e,0x18,0x00,0x02,0x3c,0x01,0x00,0xe7,0x34,0x27,0x10,0x02,0x00,
+0x24,0x30,0xc2,0x00,0x00,0x02,0xa5,0x34,0x00,0x26,0x07,0x00,0x25,0xb0,0x02,0x3c,
+0x25,0x20,0x85,0x00,0x80,0x03,0x42,0x34,0x41,0xb0,0x03,0x3c,0x00,0x00,0x44,0xac,
+0x00,0x00,0x66,0xac,0x6c,0x7e,0x05,0xad,0x7c,0x7e,0x27,0xa1,0xfc,0x4a,0x06,0xae,
+0x68,0x15,0x62,0x26,0x00,0x4b,0x43,0x8c,0x10,0x00,0x04,0x3c,0x26,0x18,0x64,0x00,
+0x00,0x4b,0x43,0xac,0x68,0x15,0x65,0x26,0xfc,0x4a,0xa2,0x8c,0x20,0x00,0x03,0x3c,
+0x24,0x10,0x52,0x00,0x24,0x10,0x43,0x00,0x5a,0x00,0x40,0x10,0x2a,0xb0,0x06,0x3c,
+0x24,0x00,0xc3,0x34,0x00,0x00,0x68,0x8c,0xff,0x00,0x07,0x24,0xff,0x00,0x04,0x31,
+0x28,0x01,0x87,0x10,0x25,0xb0,0x02,0x3c,0x00,0x80,0x02,0x31,0x23,0x00,0x40,0x14,
+0x00,0x80,0x02,0x3c,0x00,0xff,0x02,0x3c,0x24,0x10,0x02,0x01,0x21,0x00,0x40,0x10,
+0xff,0x00,0x02,0x24,0x46,0x00,0xc6,0x34,0x00,0x00,0xc2,0x90,0x00,0x00,0x00,0x00,
+0xff,0x00,0x44,0x30,0x0e,0x00,0x87,0x10,0x68,0x15,0x62,0x26,0xfc,0x63,0xa4,0xa0,
+0x00,0x00,0xc2,0x90,0xff,0x00,0x83,0x30,0xff,0x00,0x44,0x30,0x07,0x00,0x83,0x10,
+0x21,0x38,0xa0,0x00,0x21,0x28,0xc0,0x00,0x00,0x00,0xa2,0x90,0x21,0x18,0x80,0x00,
+0xfd,0xff,0x62,0x14,0xff,0x00,0x44,0x30,0xfc,0x63,0xe3,0xa0,0x68,0x15,0x62,0x26,
+0xfc,0x63,0x43,0x90,0x20,0xb0,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,
+0x0c,0x00,0x68,0x8c,0x25,0xb0,0x02,0x3c,0xb0,0x03,0x42,0x34,0xff,0x00,0x04,0x31,
+0x00,0x00,0x48,0xac,0x4d,0x19,0x00,0x08,0xff,0x00,0x02,0x24,0x00,0x00,0x62,0xac,
+0xff,0x00,0x02,0x24,0x25,0x00,0x82,0x10,0x68,0x15,0x70,0x26,0xff,0x00,0x03,0x31,
+0xb4,0x64,0x05,0x8e,0x20,0x10,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,
+0x21,0x30,0x60,0x00,0xfc,0x63,0x08,0xa2,0x48,0x64,0x03,0xae,0x06,0x00,0x04,0x24,
+0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0x02,0x80,0x0a,0x3c,
+0x7c,0x7e,0x47,0x91,0x02,0x80,0x09,0x3c,0x6c,0x7e,0x25,0x8d,0xfc,0x4a,0x06,0x8e,
+0x60,0x00,0x02,0x3c,0x04,0x00,0xe7,0x34,0x27,0x10,0x02,0x00,0x24,0x30,0xc2,0x00,
+0x00,0x04,0xa5,0x34,0x25,0xb0,0x03,0x3c,0x40,0x00,0x02,0x3c,0x00,0x26,0x07,0x00,
+0x26,0x88,0x22,0x02,0xb0,0x03,0x68,0x34,0x25,0x20,0x85,0x00,0x80,0x03,0x63,0x34,
+0x41,0xb0,0x02,0x3c,0x00,0x00,0x64,0xac,0x00,0x00,0x46,0xac,0x6c,0x7e,0x25,0xad,
+0x7c,0x7e,0x47,0xa1,0xfc,0x4a,0x06,0xae,0x00,0x00,0x11,0xad,0x68,0x15,0x62,0x26,
+0x00,0x4b,0x43,0x8c,0x20,0x00,0x04,0x3c,0x26,0x18,0x64,0x00,0x00,0x4b,0x43,0xac,
+0x68,0x15,0x65,0x26,0xfc,0x4a,0xa2,0x8c,0x40,0x00,0x03,0x3c,0x24,0x10,0x52,0x00,
+0x24,0x10,0x51,0x00,0x24,0x10,0x43,0x00,0x5a,0x00,0x40,0x10,0x68,0x15,0x70,0x26,
+0x25,0xb0,0x02,0x3c,0x2a,0xb0,0x07,0x3c,0xb0,0x03,0x42,0x34,0x00,0x00,0x51,0xac,
+0x28,0x00,0xe3,0x34,0x00,0x00,0x68,0x8c,0xff,0x00,0x06,0x24,0xff,0x00,0x04,0x31,
+0xc9,0x00,0x86,0x10,0x25,0xbd,0x02,0x3c,0x00,0x80,0x02,0x31,0x23,0x00,0x40,0x14,
+0x00,0x80,0x02,0x3c,0x00,0xff,0x02,0x3c,0x24,0x10,0x02,0x01,0x21,0x00,0x40,0x10,
+0xff,0x00,0x02,0x24,0x47,0x00,0xe7,0x34,0x00,0x00,0xe2,0x90,0x00,0x00,0x00,0x00,
+0xff,0x00,0x44,0x30,0x0e,0x00,0x86,0x10,0x68,0x15,0x62,0x26,0x00,0x64,0xa4,0xa0,
+0x00,0x00,0xe2,0x90,0xff,0x00,0x83,0x30,0xff,0x00,0x44,0x30,0x07,0x00,0x83,0x10,
+0x21,0x30,0xa0,0x00,0x21,0x28,0xe0,0x00,0x00,0x00,0xa2,0x90,0x21,0x18,0x80,0x00,
+0xfd,0xff,0x62,0x14,0xff,0x00,0x44,0x30,0x00,0x64,0xc3,0xa0,0x68,0x15,0x62,0x26,
+0x00,0x64,0x43,0x90,0x20,0xb0,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,
+0x0c,0x00,0x68,0x8c,0x25,0xb0,0x02,0x3c,0xb0,0x03,0x42,0x34,0xff,0x00,0x04,0x31,
+0x00,0x00,0x48,0xac,0xb1,0x19,0x00,0x08,0xff,0x00,0x02,0x24,0x00,0x00,0x62,0xac,
+0xff,0x00,0x02,0x24,0x21,0x00,0x82,0x10,0x68,0x15,0x70,0x26,0xff,0x00,0x03,0x31,
+0xb4,0x64,0x05,0x8e,0x20,0x10,0x02,0x3c,0x00,0x1a,0x03,0x00,0x21,0x18,0x62,0x00,
+0x21,0x30,0x60,0x00,0x00,0x64,0x08,0xa2,0x48,0x64,0x03,0xae,0x06,0x00,0x04,0x24,
+0x20,0x00,0x07,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xa0,0xaf,0x02,0x80,0x09,0x3c,
+0x7c,0x7e,0x27,0x91,0x02,0x80,0x08,0x3c,0x6c,0x7e,0x05,0x8d,0xfc,0x4a,0x06,0x8e,
+0x60,0x00,0x02,0x3c,0x02,0x00,0xe7,0x34,0x27,0x10,0x02,0x00,0x24,0x30,0xc2,0x00,
+0x00,0x04,0xa5,0x34,0x00,0x26,0x07,0x00,0x25,0xb0,0x02,0x3c,0x25,0x20,0x85,0x00,
+0x80,0x03,0x42,0x34,0x41,0xb0,0x03,0x3c,0x00,0x00,0x44,0xac,0x00,0x00,0x66,0xac,
+0x6c,0x7e,0x05,0xad,0x7c,0x7e,0x27,0xa1,0xfc,0x4a,0x06,0xae,0x68,0x15,0x62,0x26,
+0x00,0x4b,0x43,0x8c,0x40,0x00,0x04,0x3c,0x26,0x18,0x64,0x00,0x00,0x4b,0x43,0xac,
+0x68,0x15,0x70,0x26,0xfc,0x4a,0x06,0x8e,0x00,0x04,0x11,0x3c,0x24,0x10,0xd2,0x00,
+0x24,0x10,0x51,0x00,0x4c,0x00,0x40,0x14,0x00,0x00,0x00,0x00,0x24,0x28,0xd2,0x00,
+0x00,0x08,0x04,0x3c,0x24,0x10,0xa4,0x00,0x08,0x00,0x40,0x10,0x80,0x00,0x07,0x3c,
+0x00,0x4b,0x03,0x8e,0x25,0xb0,0x02,0x3c,0xb0,0x03,0x42,0x34,0x26,0x18,0x64,0x00,
+0x00,0x00,0x44,0xac,0x00,0x4b,0x03,0xae,0x80,0x00,0x07,0x3c,0x24,0x10,0xa7,0x00,
+0x21,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0x00,0x4b,0x03,0x8e,0x25,0xb0,0x08,0x3c,
+0xb0,0x03,0x09,0x35,0x2a,0xb0,0x02,0x3c,0x00,0x00,0x23,0xad,0x36,0x00,0x42,0x34,
+0x00,0x00,0x43,0x90,0x23,0xb0,0x04,0x3c,0xff,0x1f,0x02,0x3c,0xc0,0x18,0x03,0x00,
+0xf0,0x07,0x63,0x30,0x5c,0x65,0x05,0x8e,0x21,0x18,0x64,0x00,0xff,0xff,0x42,0x34,
+0x24,0x18,0x62,0x00,0x59,0x00,0x65,0x10,0x60,0x65,0x03,0xae,0x02,0x80,0x05,0x3c,
+0x6c,0x7e,0xa3,0x8c,0x27,0x20,0x07,0x00,0x24,0x20,0xc4,0x00,0x00,0x08,0x63,0x34,
+0x41,0xb0,0x02,0x3c,0x00,0x00,0x23,0xad,0x00,0x00,0x44,0xac,0x6c,0x7e,0xa3,0xac,
+0xfc,0x4a,0x04,0xae,0x68,0x15,0x62,0x26,0x00,0x4b,0x43,0x8c,0x80,0x00,0x04,0x3c,
+0x26,0x18,0x64,0x00,0x00,0x4b,0x43,0xac,0x68,0x15,0x66,0x26,0xfc,0x4a,0xc3,0x8c,
+0x00,0x01,0x04,0x3c,0x24,0x28,0x72,0x00,0x24,0x10,0xa4,0x00,0x06,0x00,0x40,0x10,
+0x25,0xb0,0x02,0x3c,0x00,0x4b,0xc3,0x8c,0xb0,0x03,0x42,0x34,0x26,0x18,0x64,0x00,
+0x00,0x00,0x44,0xac,0x00,0x4b,0xc3,0xac,0x00,0x02,0x04,0x3c,0x24,0x10,0xa4,0x00,
+0x06,0x00,0x40,0x10,0x25,0xb0,0x03,0x3c,0x00,0x4b,0xc2,0x8c,0xb0,0x03,0x63,0x34,
+0x26,0x10,0x44,0x00,0x00,0x4b,0xc2,0xac,0x00,0x00,0x64,0xac,0x28,0x00,0xbf,0x8f,
+0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,0x18,0x00,0xb0,0x8f,
+0x08,0x00,0xe0,0x03,0x30,0x00,0xbd,0x27,0x5b,0x4e,0x00,0x0c,0x07,0x00,0x04,0x24,
+0x00,0x4b,0x03,0x8e,0xfc,0x4a,0x06,0x8e,0x25,0xb0,0x02,0x3c,0x26,0x18,0x71,0x00,
+0xb0,0x03,0x42,0x34,0x00,0x00,0x43,0xac,0xdf,0x19,0x00,0x08,0x00,0x4b,0x03,0xae,
+0x56,0x01,0x42,0x35,0x00,0x00,0x43,0x94,0x00,0x00,0x00,0x00,0x44,0xfb,0x60,0x10,
+0x00,0x00,0x00,0x00,0x5b,0x4e,0x00,0x0c,0x07,0x00,0x04,0x24,0x7d,0x15,0x00,0x08,
+0x68,0x15,0x66,0x26,0x00,0x00,0xa2,0xac,0x48,0x16,0x00,0x08,0xff,0x00,0x02,0x24,
+0x00,0x00,0x62,0xac,0x85,0x16,0x00,0x08,0xff,0x00,0x02,0x24,0x00,0x00,0x62,0xac,
+0xc2,0x16,0x00,0x08,0xff,0x00,0x02,0x24,0x90,0x03,0x63,0x34,0x00,0x00,0x62,0xac,
+0x57,0x18,0x00,0x08,0x68,0x15,0x62,0x26,0x00,0x00,0x40,0xac,0x15,0x19,0x00,0x08,
+0x68,0x15,0x62,0x26,0x02,0x00,0x03,0x24,0x90,0x03,0x42,0x34,0x00,0x00,0x43,0xac,
+0x74,0x19,0x00,0x08,0x68,0x15,0x62,0x26,0x01,0x00,0x03,0x24,0x90,0x03,0x42,0x34,
+0x00,0x00,0x43,0xac,0xd4,0x19,0x00,0x08,0x68,0x15,0x62,0x26,0xd0,0x03,0x03,0x35,
+0x80,0x00,0x02,0x24,0x00,0x00,0x62,0xac,0x0a,0x1a,0x00,0x08,0x68,0x15,0x62,0x26,
+0x25,0xb0,0x02,0x3c,0x07,0x00,0x03,0x24,0x90,0x03,0x42,0x34,0x00,0x00,0x43,0xac,
+0x68,0x15,0x63,0x26,0x00,0x4b,0x62,0x8c,0x00,0x00,0x00,0x00,0x00,0x20,0x42,0x38,
+0xe2,0x16,0x00,0x08,0x00,0x4b,0x62,0xac,0x25,0xb0,0x02,0x3c,0x07,0x00,0x03,0x24,
+0x90,0x03,0x42,0x34,0x00,0x00,0x43,0xac,0x68,0x15,0x63,0x26,0x00,0x4b,0x62,0x8c,
+0x00,0x00,0x00,0x00,0x00,0x80,0x42,0x38,0x40,0x17,0x00,0x08,0x00,0x4b,0x62,0xac,
+0x06,0x00,0x03,0x24,0x90,0x03,0x42,0x34,0x00,0x00,0x43,0xac,0x99,0x17,0x00,0x08,
+0x68,0x15,0x62,0x26,0x05,0x00,0x03,0x24,0x90,0x03,0x42,0x34,0x00,0x00,0x43,0xac,
+0xf8,0x17,0x00,0x08,0x68,0x15,0x62,0x26,0x03,0x00,0x03,0x24,0x90,0x03,0x42,0x34,
+0x00,0x00,0x43,0xac,0xb6,0x18,0x00,0x08,0x68,0x15,0x62,0x26,0x25,0xb0,0x0d,0x3c,
+0x00,0x80,0x02,0x3c,0x18,0x03,0xa4,0x35,0xfc,0x69,0x42,0x24,0x02,0x80,0x03,0x3c,
+0x41,0xb0,0x08,0x3c,0x00,0x00,0x82,0xac,0x68,0x15,0x6a,0x24,0x0a,0x00,0x02,0x35,
+0x00,0x00,0x44,0x94,0x0a,0x4b,0x43,0x95,0x08,0x4b,0x4b,0x95,0x25,0x18,0x64,0x00,
+0xff,0xff,0x6c,0x30,0x24,0x10,0x8b,0x01,0x02,0x00,0x42,0x30,0x4d,0x00,0x40,0x10,
+0x02,0x00,0x64,0x38,0x02,0x00,0x02,0x24,0xc0,0x03,0xa3,0x35,0x00,0x00,0x62,0xac,
+0x0a,0x4b,0x44,0xa5,0x24,0x38,0x8b,0x01,0x04,0x00,0xe2,0x30,0x0a,0x00,0x40,0x10,
+0x08,0x00,0xe2,0x30,0x0a,0x4b,0x43,0x95,0x0c,0x00,0x04,0x35,0xc0,0x03,0xa5,0x35,
+0x04,0x00,0x63,0x38,0x04,0x00,0x02,0x24,0x00,0x00,0x86,0x8c,0x00,0x00,0xa2,0xac,
+0x0a,0x4b,0x43,0xa5,0x08,0x00,0xe2,0x30,0x08,0x00,0x40,0x10,0x10,0x00,0xe2,0x30,
+0x0a,0x4b,0x42,0x95,0xc0,0x03,0xa4,0x35,0x08,0x00,0x03,0x24,0x08,0x00,0x42,0x38,
+0x00,0x00,0x83,0xac,0x0a,0x4b,0x42,0xa5,0x10,0x00,0xe2,0x30,0x08,0x00,0x40,0x10,
+0x20,0x00,0xe2,0x30,0x0a,0x4b,0x42,0x95,0xc0,0x03,0xa4,0x35,0x10,0x00,0x03,0x24,
+0x10,0x00,0x42,0x38,0x00,0x00,0x83,0xac,0x0a,0x4b,0x42,0xa5,0x20,0x00,0xe2,0x30,
+0x08,0x00,0x40,0x10,0x80,0x00,0xe2,0x30,0x0a,0x4b,0x42,0x95,0xc0,0x03,0xa4,0x35,
+0x20,0x00,0x03,0x24,0x20,0x00,0x42,0x38,0x00,0x00,0x83,0xac,0x0a,0x4b,0x42,0xa5,
+0x80,0x00,0xe2,0x30,0x15,0x00,0x40,0x10,0x24,0x10,0x8b,0x01,0x02,0x80,0x09,0x3c,
+0x0a,0x4b,0x46,0x95,0x6c,0x7e,0x25,0x8d,0x08,0x00,0x02,0x3c,0x7f,0xff,0x04,0x24,
+0x24,0x20,0x64,0x01,0x25,0x28,0xa2,0x00,0x80,0x00,0xc6,0x38,0xb0,0x03,0xa7,0x35,
+0x08,0x00,0x08,0x35,0xc0,0x03,0xa3,0x35,0x80,0x00,0x02,0x24,0x00,0x00,0x62,0xac,
+0x21,0x58,0x80,0x00,0x00,0x00,0xe5,0xac,0x0a,0x4b,0x46,0xa5,0x6c,0x7e,0x25,0xad,
+0x00,0x00,0x04,0xa5,0x08,0x4b,0x44,0xa5,0x24,0x10,0x8b,0x01,0x00,0x30,0x42,0x30,
+0x06,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0x0a,0x4b,0x42,0x95,0x00,0x00,0x00,0x00,
+0x00,0x10,0x42,0x38,0x00,0x20,0x42,0x34,0x0a,0x4b,0x42,0xa5,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x95,0x1a,0x00,0x08,0x0a,0x4b,0x43,0xa5,0xf8,0xff,0xbd,0x27,
+0x04,0x00,0xb1,0xaf,0x00,0x00,0xb0,0xaf,0x00,0x40,0x02,0x40,0x00,0x68,0x08,0x40,
+0x00,0x70,0x02,0x40,0x00,0x60,0x09,0x40,0x25,0xb0,0x05,0x3c,0x00,0x80,0x02,0x3c,
+0x18,0x03,0xa3,0x34,0x7c,0x6b,0x42,0x24,0x00,0x00,0x62,0xac,0x80,0x00,0x87,0x8c,
+0x7c,0x02,0xa2,0x34,0x84,0x02,0xa3,0x34,0x88,0x02,0xa6,0x34,0x00,0x00,0x47,0xac,
+0x00,0x00,0x68,0xac,0x00,0x00,0xc9,0xac,0x74,0x00,0x83,0x8c,0x8c,0x02,0xa2,0x34,
+0x90,0x02,0xa7,0x34,0x00,0x00,0x43,0xac,0x08,0x00,0x86,0x8c,0x94,0x02,0xa8,0x34,
+0x98,0x02,0xa9,0x34,0x00,0x00,0xe6,0xac,0x0c,0x00,0x82,0x8c,0x9c,0x02,0xa6,0x34,
+0xa0,0x02,0xa7,0x34,0x00,0x00,0x02,0xad,0x10,0x00,0x83,0x8c,0xa4,0x02,0xa8,0x34,
+0xa8,0x02,0xaa,0x34,0x00,0x00,0x23,0xad,0x14,0x00,0x82,0x8c,0xac,0x02,0xa9,0x34,
+0xb0,0x02,0xab,0x34,0x00,0x00,0xc2,0xac,0x18,0x00,0x83,0x8c,0xb4,0x02,0xa6,0x34,
+0xb8,0x02,0xac,0x34,0x00,0x00,0xe3,0xac,0x1c,0x00,0x82,0x8c,0xbc,0x02,0xa7,0x34,
+0xc0,0x02,0xad,0x34,0x00,0x00,0x02,0xad,0x20,0x00,0x83,0x8c,0xc4,0x02,0xa8,0x34,
+0xc8,0x02,0xae,0x34,0x00,0x00,0x43,0xad,0x24,0x00,0x82,0x8c,0xcc,0x02,0xaa,0x34,
+0xd0,0x02,0xaf,0x34,0x00,0x00,0x22,0xad,0x28,0x00,0x83,0x8c,0xd4,0x02,0xa9,0x34,
+0xd8,0x02,0xb0,0x34,0x00,0x00,0x63,0xad,0x2c,0x00,0x82,0x8c,0x70,0x02,0xab,0x34,
+0x74,0x02,0xb1,0x34,0x00,0x00,0xc2,0xac,0x30,0x00,0x83,0x8c,0x78,0x02,0xa5,0x34,
+0x00,0x00,0x83,0xad,0x34,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0xe2,0xac,
+0x38,0x00,0x83,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0xa3,0xad,0x3c,0x00,0x82,0x8c,
+0x00,0x00,0x00,0x00,0x00,0x00,0x02,0xad,0x40,0x00,0x83,0x8c,0x00,0x00,0x00,0x00,
+0x00,0x00,0xc3,0xad,0x44,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0x42,0xad,
+0x48,0x00,0x83,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0xe3,0xad,0x4c,0x00,0x82,0x8c,
+0x00,0x00,0x00,0x00,0x00,0x00,0x22,0xad,0x50,0x00,0x83,0x8c,0x00,0x00,0x00,0x00,
+0x00,0x00,0x03,0xae,0x54,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0x62,0xad,
+0x58,0x00,0x83,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0x23,0xae,0x5c,0x00,0x82,0x8c,
+0x00,0x00,0x00,0x00,0x00,0x00,0xa2,0xac,0x42,0x1b,0x00,0x08,0x00,0x00,0x00,0x00,
+0x00,0x80,0x1b,0x3c,0x10,0x6d,0x7b,0x27,0x25,0xb0,0x1a,0x3c,0x18,0x03,0x5a,0x27,
+0x00,0x00,0x5b,0xaf,0x21,0xd8,0xa0,0x03,0x82,0xda,0x1b,0x00,0x80,0xda,0x1b,0x00,
+0x08,0x00,0x7b,0x27,0x04,0x00,0x61,0xaf,0x08,0x00,0x62,0xaf,0x0c,0x00,0x63,0xaf,
+0x10,0x00,0x64,0xaf,0x14,0x00,0x65,0xaf,0x18,0x00,0x66,0xaf,0x1c,0x00,0x67,0xaf,
+0x20,0x00,0x68,0xaf,0x24,0x00,0x69,0xaf,0x28,0x00,0x6a,0xaf,0x2c,0x00,0x6b,0xaf,
+0x30,0x00,0x6c,0xaf,0x34,0x00,0x6d,0xaf,0x38,0x00,0x6e,0xaf,0x3c,0x00,0x6f,0xaf,
+0x12,0x40,0x00,0x00,0x10,0x48,0x00,0x00,0x00,0x70,0x0a,0x40,0x40,0x00,0x70,0xaf,
+0x44,0x00,0x71,0xaf,0x48,0x00,0x72,0xaf,0x4c,0x00,0x73,0xaf,0x50,0x00,0x74,0xaf,
+0x54,0x00,0x75,0xaf,0x58,0x00,0x76,0xaf,0x5c,0x00,0x77,0xaf,0x60,0x00,0x78,0xaf,
+0x64,0x00,0x79,0xaf,0x68,0x00,0x7c,0xaf,0x6c,0x00,0x7d,0xaf,0x70,0x00,0x7e,0xaf,
+0x74,0x00,0x7f,0xaf,0x78,0x00,0x68,0xaf,0x7c,0x00,0x69,0xaf,0x80,0x00,0x6a,0xaf,
+0x00,0x68,0x1a,0x40,0x25,0xb0,0x1b,0x3c,0x1c,0x03,0x7b,0x37,0x00,0x00,0x00,0x00,
+0x00,0x00,0x7a,0xaf,0x7f,0x00,0x5b,0x33,0x30,0x00,0x60,0x13,0x00,0x00,0x00,0x00,
+0x25,0xb0,0x1b,0x3c,0x30,0x03,0x7b,0x37,0x00,0x00,0x00,0x00,0x00,0x00,0x7a,0xaf,
+0x00,0x00,0x00,0x00,0x21,0xd8,0xa0,0x03,0x82,0xda,0x1b,0x00,0x80,0xda,0x1b,0x00,
+0x08,0x00,0x7b,0x27,0x04,0x00,0x61,0xaf,0x08,0x00,0x62,0xaf,0x0c,0x00,0x63,0xaf,
+0x10,0x00,0x64,0xaf,0x14,0x00,0x65,0xaf,0x18,0x00,0x66,0xaf,0x1c,0x00,0x67,0xaf,
+0x20,0x00,0x68,0xaf,0x24,0x00,0x69,0xaf,0x28,0x00,0x6a,0xaf,0x2c,0x00,0x6b,0xaf,
+0x30,0x00,0x6c,0xaf,0x34,0x00,0x6d,0xaf,0x38,0x00,0x6e,0xaf,0x3c,0x00,0x6f,0xaf,
+0x12,0x40,0x00,0x00,0x10,0x48,0x00,0x00,0x00,0x70,0x0a,0x40,0x40,0x00,0x70,0xaf,
+0x44,0x00,0x71,0xaf,0x48,0x00,0x72,0xaf,0x4c,0x00,0x73,0xaf,0x50,0x00,0x74,0xaf,
+0x54,0x00,0x75,0xaf,0x58,0x00,0x76,0xaf,0x5c,0x00,0x77,0xaf,0x60,0x00,0x78,0xaf,
+0x64,0x00,0x79,0xaf,0x68,0x00,0x7c,0xaf,0x6c,0x00,0x7d,0xaf,0x70,0x00,0x7e,0xaf,
+0x74,0x00,0x7f,0xaf,0x78,0x00,0x68,0xaf,0x7c,0x00,0x69,0xaf,0x80,0x00,0x6a,0xaf,
+0xdf,0x1a,0x00,0x08,0x21,0x20,0x60,0x03,0x00,0x00,0x00,0x00,0x25,0xb0,0x08,0x3c,
+0x20,0x03,0x08,0x35,0x00,0x00,0x00,0x00,0x00,0x00,0x1a,0xad,0x00,0x04,0x5b,0x33,
+0x0a,0x00,0x60,0x13,0x00,0x00,0x00,0x00,0x00,0x80,0x08,0x3c,0x74,0x55,0x08,0x25,
+0x00,0x00,0x00,0x00,0x25,0xb0,0x1b,0x3c,0x24,0x03,0x7b,0x37,0x00,0x00,0x00,0x00,
+0x00,0x00,0x68,0xaf,0x09,0xf8,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x08,0x5b,0x33,
+0x25,0xb0,0x08,0x3c,0x28,0x03,0x08,0x35,0x00,0x00,0x00,0x00,0x00,0x00,0x1b,0xad,
+0x06,0x00,0x60,0x13,0x00,0x00,0x00,0x00,0x00,0x80,0x08,0x3c,0xfc,0x69,0x08,0x25,
+0x00,0x00,0x00,0x00,0x09,0xf8,0x00,0x01,0x00,0x00,0x00,0x00,0x02,0x80,0x1a,0x3c,
+0x6c,0x7e,0x5a,0x27,0x04,0x00,0x5b,0x97,0x25,0xb0,0x08,0x3c,0x30,0x03,0x08,0x35,
+0x00,0x00,0x00,0x00,0x00,0x00,0x1b,0xad,0x18,0x00,0x60,0x13,0x00,0x00,0x00,0x00,
+0x08,0xec,0x9b,0x27,0x00,0x00,0x00,0x00,0x04,0x00,0x61,0x8f,0xfc,0x03,0x70,0x7b,
+0x7c,0x00,0x62,0x7b,0xbc,0x00,0x64,0x7b,0xfc,0x00,0x66,0x7b,0x3c,0x01,0x68,0x7b,
+0x13,0x00,0x00,0x02,0x11,0x00,0x20,0x02,0x7c,0x01,0x6a,0x7b,0xbc,0x01,0x6c,0x7b,
+0xfc,0x01,0x6e,0x7b,0x3c,0x02,0x70,0x7b,0x7c,0x02,0x72,0x7b,0xbc,0x02,0x74,0x7b,
+0xfc,0x02,0x76,0x7b,0x3c,0x03,0x78,0x7b,0x7c,0x03,0x7c,0x7b,0xbc,0x03,0x7e,0x7b,
+0x80,0x00,0x7b,0x8f,0x2f,0x1c,0x00,0x08,0x00,0x00,0x00,0x00,0x21,0xd8,0xa0,0x03,
+0x82,0xda,0x1b,0x00,0x80,0xda,0x1b,0x00,0x08,0x00,0x7b,0x27,0x08,0x00,0x5b,0xaf,
+0xfc,0xef,0x9d,0x27,0x00,0x00,0x4a,0x8f,0x00,0x00,0x00,0x00,0x21,0x00,0x40,0x11,
+0x00,0x00,0x00,0x00,0x02,0x80,0x08,0x3c,0xcc,0x7d,0x08,0x25,0x21,0x48,0x00,0x00,
+0x21,0x58,0x00,0x00,0x01,0x00,0x6b,0x25,0x1a,0x00,0x40,0x11,0x24,0x70,0x4b,0x01,
+0x14,0x00,0xc0,0x11,0x01,0x00,0x04,0x24,0x00,0x00,0x00,0x00,0x04,0x00,0x44,0xa3,
+0x26,0x50,0x4b,0x01,0x00,0x00,0x4a,0xaf,0x80,0x80,0x09,0x00,0x21,0x80,0x08,0x02,
+0x00,0x00,0x10,0x8e,0x00,0x00,0x00,0x00,0x09,0xf8,0x00,0x02,0x00,0x00,0x00,0x00,
+0x00,0x80,0x1b,0x3c,0xe8,0x6f,0x7b,0x27,0x25,0xb0,0x1a,0x3c,0x18,0x03,0x5a,0x27,
+0x00,0x00,0x5b,0xaf,0x02,0x80,0x1a,0x3c,0x6c,0x7e,0x5a,0x27,0xe1,0xff,0x00,0x10,
+0x00,0x00,0x00,0x00,0x01,0x00,0x29,0x25,0x40,0x58,0x0b,0x00,0xf2,0x1b,0x00,0x08,
+0x00,0x00,0x00,0x00,0x02,0x80,0x1b,0x3c,0x6c,0x7e,0x7b,0x27,0x21,0x60,0x00,0x00,
+0x04,0x00,0x6c,0xa7,0x08,0x00,0x7a,0x8f,0x00,0x00,0x00,0x00,0xf8,0xff,0x5a,0x27,
+0x00,0x00,0x5a,0x8f,0x00,0x00,0x00,0x00,0x08,0x00,0x5a,0x27,0x84,0x00,0x44,0x8f,
+0x00,0x00,0x00,0x00,0xf9,0xff,0x80,0x10,0x00,0x00,0x00,0x00,0x04,0x00,0x41,0x8f,
+0xfc,0x03,0x50,0x7b,0x7c,0x00,0x42,0x7b,0xbc,0x00,0x44,0x7b,0xfc,0x00,0x46,0x7b,
+0x3c,0x01,0x48,0x7b,0x13,0x00,0x00,0x02,0x11,0x00,0x20,0x02,0x7c,0x01,0x4a,0x7b,
+0xbc,0x01,0x4c,0x7b,0xfc,0x01,0x4e,0x7b,0x3c,0x02,0x50,0x7b,0x7c,0x02,0x52,0x7b,
+0xbc,0x02,0x54,0x7b,0xfc,0x02,0x56,0x7b,0x3c,0x03,0x58,0x7b,0x7c,0x03,0x5c,0x7b,
+0xbc,0x03,0x5e,0x7b,0x80,0x00,0x5b,0x8f,0x00,0x00,0x00,0x00,0x08,0x00,0x60,0x03,
+0x10,0x00,0x00,0x42,0x00,0x60,0x05,0x40,0x42,0x28,0x05,0x00,0x40,0x28,0x05,0x00,
+0x00,0x60,0x85,0x40,0x04,0x00,0x81,0xac,0x08,0x00,0x82,0xac,0x0c,0x00,0x83,0xac,
+0x20,0x00,0x88,0xac,0x24,0x00,0x89,0xac,0x28,0x00,0x8a,0xac,0x2c,0x00,0x8b,0xac,
+0x30,0x00,0x8c,0xac,0x34,0x00,0x8d,0xac,0x38,0x00,0x8e,0xac,0x3c,0x00,0x8f,0xac,
+0x12,0x40,0x00,0x00,0x10,0x48,0x00,0x00,0x40,0x00,0x90,0xac,0x44,0x00,0x91,0xac,
+0x48,0x00,0x92,0xac,0x4c,0x00,0x93,0xac,0x50,0x00,0x94,0xac,0x54,0x00,0x95,0xac,
+0x58,0x00,0x96,0xac,0x5c,0x00,0x97,0xac,0x60,0x00,0x98,0xac,0x64,0x00,0x99,0xac,
+0x68,0x00,0x9c,0xac,0x6c,0x00,0x9d,0xac,0x70,0x00,0x9e,0xac,0x74,0x00,0x9f,0xac,
+0x78,0x00,0x88,0xac,0x7c,0x00,0x89,0xac,0x80,0x00,0x9f,0xac,0xf8,0xff,0x84,0x24,
+0x00,0x00,0x84,0x8c,0x00,0x00,0x00,0x00,0x08,0x00,0x84,0x24,0x84,0x00,0x86,0x8c,
+0x00,0x00,0x00,0x00,0xf9,0xff,0xc0,0x10,0x00,0x00,0x00,0x00,0x21,0xd8,0x80,0x00,
+0x01,0x00,0xba,0x24,0x04,0x00,0x61,0x8f,0xfc,0x03,0x70,0x7b,0x7c,0x00,0x62,0x7b,
+0xbc,0x00,0x64,0x7b,0xfc,0x00,0x66,0x7b,0x3c,0x01,0x68,0x7b,0x13,0x00,0x00,0x02,
+0x11,0x00,0x20,0x02,0x7c,0x01,0x6a,0x7b,0xbc,0x01,0x6c,0x7b,0xfc,0x01,0x6e,0x7b,
+0x3c,0x02,0x70,0x7b,0x7c,0x02,0x72,0x7b,0xbc,0x02,0x74,0x7b,0xfc,0x02,0x76,0x7b,
+0x3c,0x03,0x78,0x7b,0x7c,0x03,0x7c,0x7b,0xbc,0x03,0x7e,0x7b,0x80,0x00,0x7b,0x8f,
+0x00,0x00,0x00,0x00,0x08,0x00,0x60,0x03,0x00,0x60,0x9a,0x40,0x00,0x60,0x05,0x40,
+0x42,0x28,0x05,0x00,0x40,0x28,0x05,0x00,0x00,0x60,0x85,0x40,0x04,0x00,0x81,0xac,
+0x08,0x00,0x82,0xac,0x0c,0x00,0x83,0xac,0x20,0x00,0x88,0xac,0x24,0x00,0x89,0xac,
+0x28,0x00,0x8a,0xac,0x2c,0x00,0x8b,0xac,0x30,0x00,0x8c,0xac,0x34,0x00,0x8d,0xac,
+0x38,0x00,0x8e,0xac,0x3c,0x00,0x8f,0xac,0x12,0x40,0x00,0x00,0x10,0x48,0x00,0x00,
+0x40,0x00,0x90,0xac,0x44,0x00,0x91,0xac,0x48,0x00,0x92,0xac,0x4c,0x00,0x93,0xac,
+0x50,0x00,0x94,0xac,0x54,0x00,0x94,0xac,0x58,0x00,0x96,0xac,0x5c,0x00,0x96,0xac,
+0x60,0x00,0x98,0xac,0x64,0x00,0x99,0xac,0x68,0x00,0x9c,0xac,0x6c,0x00,0x9d,0xac,
+0x70,0x00,0x9e,0xac,0x78,0x00,0x88,0xac,0x7c,0x00,0x89,0xac,0x80,0x00,0x9f,0xac,
+0x84,0x00,0x80,0xac,0xf8,0xff,0x84,0x24,0x00,0x00,0x84,0x8c,0x00,0x00,0x00,0x00,
+0x08,0x00,0x84,0x24,0x84,0x00,0x86,0x8c,0xfa,0xff,0xc0,0x10,0x00,0x00,0x00,0x00,
+0x21,0xd8,0x80,0x00,0x01,0x00,0xba,0x24,0x04,0x00,0x61,0x8f,0xfc,0x03,0x70,0x7b,
+0x7c,0x00,0x62,0x7b,0xbc,0x00,0x64,0x7b,0xfc,0x00,0x66,0x7b,0x3c,0x01,0x68,0x7b,
+0x13,0x00,0x00,0x02,0x11,0x00,0x20,0x02,0x7c,0x01,0x6a,0x7b,0xbc,0x01,0x6c,0x7b,
+0xfc,0x01,0x6e,0x7b,0x3c,0x02,0x70,0x7b,0x7c,0x02,0x72,0x7b,0xbc,0x02,0x74,0x7b,
+0xfc,0x02,0x76,0x7b,0x3c,0x03,0x78,0x7b,0x7c,0x03,0x7c,0x7b,0xbc,0x03,0x7e,0x7b,
+0x80,0x00,0x7b,0x8f,0x08,0x00,0x60,0x03,0x00,0x60,0x9a,0x40,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0xc6,0x7f,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x80,0x1b,0x3c,0x00,0x00,0x7b,0x27,
+0x25,0xb0,0x1a,0x3c,0x18,0x03,0x5a,0x27,0x00,0x00,0x5b,0xaf,0x00,0x00,0x05,0x24,
+0x03,0x00,0xa4,0x24,0x00,0xa0,0x80,0x40,0x00,0xa0,0x84,0x40,0x01,0x80,0x04,0x3c,
+0x98,0x03,0x84,0x24,0x08,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x01,0x80,0x1b,0x3c,0x98,0x03,0x7b,0x27,0x25,0xb0,0x1a,0x3c,0x18,0x03,0x5a,0x27,
+0x00,0x00,0x5b,0xaf,0x02,0x80,0x1a,0x3c,0x00,0x00,0x5a,0x27,0xfc,0x03,0x5d,0x27,
+0x02,0x80,0x1c,0x3c,0x00,0x14,0x9c,0x27,0x00,0xf0,0x08,0x3c,0x00,0x0c,0x08,0x35,
+0x00,0x60,0x88,0x40,0x02,0x80,0x04,0x3c,0x00,0x00,0x84,0x24,0xff,0x7f,0x05,0x3c,
+0xff,0xff,0xa5,0x34,0x24,0x20,0x85,0x00,0x00,0x20,0x84,0x4c,0xff,0xff,0x05,0x34,
+0x21,0x28,0xa4,0x00,0x00,0x28,0x85,0x4c,0x00,0x80,0x04,0x3c,0x00,0x00,0x84,0x24,
+0xff,0x7f,0x05,0x3c,0xff,0xff,0xa5,0x34,0x24,0x20,0x85,0x00,0x00,0x00,0x84,0x4c,
+0xff,0x7f,0x06,0x24,0x21,0x30,0xc4,0x00,0x24,0x30,0xc5,0x00,0x00,0x08,0x86,0x4c,
+0x00,0xa0,0x04,0x40,0x10,0x00,0x84,0x34,0x00,0xa0,0x84,0x40,0x01,0x80,0x1b,0x3c,
+0x24,0x04,0x7b,0x27,0x25,0xb0,0x1a,0x3c,0x18,0x03,0x5a,0x27,0x00,0x00,0x5b,0xaf,
+0x00,0x00,0x00,0x00,0x25,0xb0,0x04,0x3c,0x44,0x00,0x84,0x34,0x00,0x00,0x85,0x84,
+0x20,0x00,0x06,0x24,0x25,0x28,0xa6,0x00,0x00,0x00,0x85,0xa4,0x01,0x80,0x1b,0x3c,
+0x54,0x04,0x7b,0x27,0x25,0xb0,0x1a,0x3c,0x18,0x03,0x5a,0x27,0x00,0x00,0x5b,0xaf,
+0x25,0xb0,0x04,0x3c,0x44,0x00,0x84,0x34,0x00,0x00,0x85,0x8c,0x00,0x00,0x00,0x00,
+0x10,0x00,0xa5,0x30,0xfc,0xff,0xa0,0x10,0x00,0x00,0x00,0x00,0xff,0x1f,0x07,0x3c,
+0xff,0xff,0xe7,0x34,0x02,0x80,0x05,0x3c,0x88,0x7d,0xa5,0x24,0xff,0xff,0xa5,0x30,
+0x40,0xb0,0x04,0x3c,0x25,0x28,0xa4,0x00,0x24,0x28,0xa7,0x00,0x21,0x30,0x00,0x00,
+0x43,0xb0,0x02,0x3c,0x00,0x80,0x04,0x3c,0x40,0x00,0x84,0x34,0x00,0x00,0x45,0xac,
+0x04,0x00,0x46,0xac,0x08,0x00,0x44,0xac,0x4e,0x58,0x00,0x08,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x09,0x00,0x02,0x24,0xff,0xff,0x42,0x24,
+0xff,0xff,0x41,0x04,0xff,0xff,0x42,0x24,0x08,0x00,0xe0,0x03,0x01,0x00,0x42,0x24,
+0x00,0x60,0x02,0x40,0x01,0x00,0x41,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x82,0xac,0x00,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,
+0x21,0x18,0x40,0x00,0x00,0x60,0x83,0x40,0x08,0x00,0xe0,0x03,0x00,0x00,0x82,0xac,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,
+0x00,0x60,0x81,0x40,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x01,0x80,0x03,0x3c,
+0x25,0xb0,0x02,0x3c,0x44,0x05,0x63,0x24,0x18,0x03,0x42,0x34,0x00,0x00,0x43,0xac,
+0x04,0x00,0x85,0x8c,0x00,0x80,0x03,0x3c,0x01,0x00,0x02,0x24,0x25,0x28,0xa3,0x00,
+0x00,0x00,0xa4,0x8c,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x01,0x80,0x03,0x3c,
+0x25,0xb0,0x02,0x3c,0x74,0x05,0x63,0x24,0x18,0x03,0x42,0x34,0x00,0x00,0x43,0xac,
+0x04,0x00,0x82,0x8c,0x02,0x00,0x83,0x94,0x00,0x80,0x07,0x3c,0x25,0x28,0x47,0x00,
+0x00,0x00,0xa2,0x8c,0x10,0x00,0x02,0x24,0x13,0x00,0x62,0x10,0x11,0x00,0x66,0x28,
+0x06,0x00,0xc0,0x10,0x20,0x00,0x02,0x24,0x08,0x00,0x02,0x24,0x17,0x00,0x62,0x10,
+0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,0xfd,0xff,0x62,0x14,
+0x00,0x00,0x00,0x00,0x08,0x00,0x83,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0xa3,0xac,
+0x04,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,0x25,0x10,0x47,0x00,0x00,0x00,0x42,0x8c,
+0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,0x08,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,
+0x00,0x00,0xa2,0xa4,0x04,0x00,0x83,0x8c,0x00,0x00,0x00,0x00,0x25,0x18,0x67,0x00,
+0x00,0x00,0x62,0x94,0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,0x08,0x00,0x82,0x8c,
+0x00,0x00,0x00,0x00,0x00,0x00,0xa2,0xa0,0x04,0x00,0x83,0x8c,0x00,0x00,0x00,0x00,
+0x25,0x18,0x67,0x00,0x00,0x00,0x62,0x90,0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,
+0xe0,0xff,0xbd,0x27,0x14,0x00,0xb1,0xaf,0x02,0x80,0x11,0x3c,0x1c,0x00,0xbf,0xaf,
+0x18,0x00,0xb2,0xaf,0x10,0x00,0xb0,0xaf,0x68,0x15,0x31,0x26,0xe4,0x64,0x30,0x96,
+0x02,0x80,0x02,0x3c,0x01,0x80,0x03,0x3c,0x25,0x80,0x02,0x02,0x25,0xb0,0x02,0x3c,
+0x38,0x06,0x63,0x24,0x18,0x03,0x42,0x34,0x60,0x00,0x04,0x26,0x80,0x00,0x05,0x26,
+0x00,0x00,0x43,0xac,0xab,0x45,0x00,0x0c,0x03,0x00,0x06,0x24,0x21,0x20,0x00,0x02,
+0x21,0x28,0x00,0x00,0x97,0x45,0x00,0x0c,0x08,0x00,0x06,0x24,0xe4,0x64,0x22,0x8e,
+0x0c,0x00,0x03,0x24,0x0c,0x00,0x43,0xae,0x08,0x00,0x42,0xae,0x12,0x00,0x02,0x24,
+0x14,0x00,0x42,0xae,0x21,0x20,0x40,0x02,0x1c,0x00,0xbf,0x8f,0x18,0x00,0xb2,0x8f,
+0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x8b,0x07,0x00,0x08,0x20,0x00,0xbd,0x27,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,
+0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,0x02,0x80,0x02,0x3c,0x21,0x48,0x80,0x00,
+0x68,0x15,0x48,0x24,0x21,0x38,0x00,0x00,0x21,0x28,0x27,0x01,0x00,0x00,0xa2,0x90,
+0x21,0x20,0xe8,0x00,0x01,0x00,0xe7,0x24,0x38,0x4c,0x82,0xa0,0x1e,0x00,0xa3,0x90,
+0x1e,0x00,0xe6,0x28,0x56,0x4c,0x83,0xa0,0x3c,0x00,0xa2,0x90,0x00,0x00,0x00,0x00,
+0x74,0x4c,0x82,0xa0,0x5a,0x00,0xa3,0x90,0xf3,0xff,0xc0,0x14,0x92,0x4c,0x83,0xa0,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,
+0x20,0xbd,0x03,0x3c,0x58,0x00,0x63,0x34,0x00,0x00,0x62,0x90,0x0f,0x27,0x07,0x24,
+0x20,0x00,0x42,0x34,0x00,0x00,0x62,0xa0,0xff,0xff,0xe7,0x24,0xff,0xff,0xe1,0x04,
+0xff,0xff,0xe7,0x24,0x62,0xbd,0x04,0x3c,0x24,0x10,0x82,0x34,0x00,0x00,0x40,0xa0,
+0x28,0x10,0x83,0x34,0x0c,0x11,0x86,0x34,0x0e,0x00,0x02,0x24,0x00,0x00,0x60,0xa0,
+0x00,0x11,0x85,0x34,0x00,0x00,0xc2,0xa0,0x00,0x00,0xa7,0x8c,0xdf,0xff,0x02,0x24,
+0x10,0x00,0x86,0x34,0x24,0x38,0xe2,0x00,0x49,0x0c,0x03,0x24,0xcf,0xff,0x02,0x24,
+0x00,0x00,0xc3,0xac,0x04,0x00,0x84,0x34,0x00,0x00,0xa7,0xac,0x24,0x38,0xe2,0x00,
+0x41,0x0c,0x02,0x24,0x00,0x00,0xa7,0xac,0x00,0x00,0x80,0xac,0x00,0x00,0xc2,0xac,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0xd0,0xff,0xbd,0x27,0x25,0xb0,0x03,0x3c,
+0x01,0x80,0x02,0x3c,0xb0,0x03,0x68,0x34,0x1c,0x00,0xb1,0xaf,0x18,0x03,0x63,0x34,
+0xd8,0xff,0x91,0x24,0xa0,0x08,0x42,0x24,0x00,0x00,0x62,0xac,0x28,0x00,0xbf,0xaf,
+0x00,0x00,0x11,0xad,0x24,0x00,0xb3,0xaf,0x20,0x00,0xb2,0xaf,0x18,0x00,0xb0,0xaf,
+0x02,0x80,0x13,0x3c,0x00,0x00,0x23,0x96,0x68,0x15,0x73,0x26,0xff,0xff,0x32,0x32,
+0x40,0x10,0x02,0x3c,0x78,0x64,0x65,0x8e,0x25,0x90,0x42,0x02,0x02,0x80,0x10,0x3c,
+0x8c,0x96,0x10,0x26,0x20,0x00,0x42,0x26,0x00,0x00,0x03,0xad,0x20,0x00,0x06,0x24,
+0x00,0x00,0x02,0xad,0x21,0x38,0x00,0x02,0x0c,0x00,0x03,0xae,0x0a,0x00,0x04,0x24,
+0x64,0x01,0x00,0x0c,0x08,0x00,0x02,0xae,0x04,0x00,0x23,0x8e,0xff,0xe0,0x02,0x24,
+0x28,0x00,0x04,0x24,0x24,0x18,0x62,0x00,0x00,0x10,0x63,0x34,0x02,0x00,0x24,0xa2,
+0x04,0x00,0x23,0xae,0x0c,0x00,0x02,0x8e,0x0a,0x00,0x04,0x24,0xf8,0xff,0x42,0x24,
+0x4d,0x01,0x00,0x0c,0x00,0x00,0x22,0xa6,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x0c,0x00,0x07,0x8e,0x20,0x10,0x06,0x3c,
+0x21,0x28,0x40,0x02,0x20,0x00,0xe7,0x24,0x00,0xfe,0xc6,0x34,0xff,0xff,0xe7,0x30,
+0x01,0x00,0x11,0x24,0x0a,0x00,0x04,0x24,0x10,0x01,0x00,0x0c,0x10,0x00,0xb1,0xaf,
+0xd5,0x4a,0x63,0x92,0x2a,0xb0,0x10,0x3c,0x32,0x00,0x02,0x36,0x01,0x00,0x63,0x24,
+0x00,0x00,0x43,0xa0,0x4d,0x01,0x00,0x0c,0x0a,0x00,0x04,0x24,0xc9,0x64,0x62,0x92,
+0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x24,0xc9,0x64,0x62,0xa2,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0x01,0x00,0x10,0x36,0x00,0x00,0x11,0xa2,
+0x28,0x00,0xbf,0x8f,0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,
+0x18,0x00,0xb0,0x8f,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x30,0x00,0xbd,0x27,
+0x25,0xb0,0x05,0x3c,0x01,0x80,0x03,0x3c,0x21,0x38,0x80,0x00,0x18,0x03,0xa2,0x34,
+0xe8,0x09,0x63,0x24,0x01,0x00,0x04,0x24,0x00,0x00,0x43,0xac,0x35,0x00,0xe4,0x10,
+0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x10,0x20,0x08,0xa2,0x34,0x02,0x00,0x02,0x24,
+0x83,0x00,0xe2,0x10,0x03,0x00,0x02,0x24,0x5a,0x00,0xe2,0x10,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x02,0x80,0x03,0x3c,0x00,0x00,0x44,0x8c,
+0x68,0x15,0x66,0x24,0x70,0x08,0x02,0x24,0xe0,0x08,0x03,0x24,0x74,0x4b,0xc2,0xac,
+0x40,0x08,0x02,0x24,0x78,0x4b,0xc3,0xac,0x84,0x4b,0xc2,0xac,0x78,0x08,0x03,0x24,
+0x0c,0x08,0x02,0x24,0x88,0x4b,0xc3,0xac,0x8c,0x4b,0xc2,0xac,0x10,0x08,0x03,0x24,
+0x20,0x08,0x02,0x24,0x90,0x4b,0xc3,0xac,0x94,0x4b,0xc2,0xac,0x24,0x08,0x03,0x24,
+0x58,0x08,0x02,0x24,0x98,0x4b,0xc3,0xac,0x9c,0x4b,0xc2,0xac,0x50,0x0c,0x03,0x24,
+0x54,0x0c,0x02,0x24,0xa0,0x4b,0xc3,0xac,0xa4,0x4b,0xc2,0xac,0x14,0x0c,0x03,0x24,
+0x10,0x0c,0x02,0x24,0x60,0x08,0x05,0x24,0xa8,0x4b,0xc3,0xac,0xac,0x4b,0xc2,0xac,
+0x80,0x0c,0x03,0x24,0x84,0x0c,0x02,0x24,0x00,0x01,0x84,0x30,0xb4,0x4b,0xc2,0xac,
+0x80,0x4b,0xc5,0xac,0xb0,0x4b,0xc3,0xac,0x71,0x4b,0xc0,0xa0,0x7c,0x4b,0xc5,0xac,
+0x02,0x00,0x80,0x10,0xa0,0x08,0x02,0x24,0xb8,0x08,0x02,0x24,0x08,0x00,0xe0,0x03,
+0xb8,0x4b,0xc2,0xac,0x28,0x08,0xa2,0x34,0x02,0x80,0x03,0x3c,0x00,0x00,0x44,0x8c,
+0x68,0x15,0x66,0x24,0x70,0x08,0x02,0x24,0xe0,0x08,0x03,0x24,0x74,0x4b,0xc2,0xac,
+0x44,0x08,0x02,0x24,0x78,0x4b,0xc3,0xac,0x84,0x4b,0xc2,0xac,0x78,0x08,0x03,0x24,
+0x0c,0x08,0x02,0x24,0x88,0x4b,0xc3,0xac,0x8c,0x4b,0xc2,0xac,0x14,0x08,0x03,0x24,
+0x28,0x08,0x02,0x24,0x90,0x4b,0xc3,0xac,0x94,0x4b,0xc2,0xac,0x2c,0x08,0x03,0x24,
+0x58,0x08,0x02,0x24,0x98,0x4b,0xc3,0xac,0x9c,0x4b,0xc2,0xac,0x58,0x0c,0x03,0x24,
+0x5c,0x0c,0x02,0x24,0xa0,0x4b,0xc3,0xac,0xa4,0x4b,0xc2,0xac,0x1c,0x0c,0x03,0x24,
+0x18,0x0c,0x02,0x24,0x64,0x08,0x05,0x24,0xa8,0x4b,0xc3,0xac,0xac,0x4b,0xc2,0xac,
+0x88,0x0c,0x03,0x24,0x8c,0x0c,0x02,0x24,0x00,0x01,0x84,0x30,0xb4,0x4b,0xc2,0xac,
+0x71,0x4b,0xc7,0xa0,0x80,0x4b,0xc5,0xac,0xb0,0x4b,0xc3,0xac,0x7c,0x4b,0xc5,0xac,
+0xd6,0xff,0x80,0x10,0xa4,0x08,0x02,0x24,0xbc,0x08,0x02,0x24,0x08,0x00,0xe0,0x03,
+0xb8,0x4b,0xc2,0xac,0x02,0x80,0x02,0x3c,0x68,0x15,0x42,0x24,0xac,0x08,0x03,0x24,
+0xb8,0x4b,0x43,0xac,0x74,0x08,0x03,0x24,0xe4,0x08,0x04,0x24,0x74,0x4b,0x43,0xac,
+0x4c,0x08,0x03,0x24,0x78,0x4b,0x44,0xac,0x84,0x4b,0x43,0xac,0x7c,0x08,0x04,0x24,
+0x0c,0x08,0x03,0x24,0x88,0x4b,0x44,0xac,0x8c,0x4b,0x43,0xac,0x1c,0x08,0x04,0x24,
+0x38,0x08,0x03,0x24,0x90,0x4b,0x44,0xac,0x94,0x4b,0x43,0xac,0x3c,0x08,0x04,0x24,
+0x5c,0x08,0x03,0x24,0x98,0x4b,0x44,0xac,0x9c,0x4b,0x43,0xac,0x68,0x0c,0x04,0x24,
+0x6c,0x0c,0x03,0x24,0xa0,0x4b,0x44,0xac,0xa4,0x4b,0x43,0xac,0x2c,0x0c,0x04,0x24,
+0x28,0x0c,0x03,0x24,0x6c,0x08,0x05,0x24,0xa8,0x4b,0x44,0xac,0xac,0x4b,0x43,0xac,
+0x98,0x0c,0x04,0x24,0x9c,0x0c,0x03,0x24,0x71,0x4b,0x47,0xa0,0x80,0x4b,0x45,0xac,
+0xb0,0x4b,0x44,0xac,0xb4,0x4b,0x43,0xac,0x08,0x00,0xe0,0x03,0x7c,0x4b,0x45,0xac,
+0x02,0x80,0x02,0x3c,0x68,0x15,0x42,0x24,0xa8,0x08,0x03,0x24,0xb8,0x4b,0x43,0xac,
+0x74,0x08,0x03,0x24,0xe4,0x08,0x04,0x24,0x74,0x4b,0x43,0xac,0x48,0x08,0x03,0x24,
+0x78,0x4b,0x44,0xac,0x84,0x4b,0x43,0xac,0x7c,0x08,0x04,0x24,0x0c,0x08,0x03,0x24,
+0x88,0x4b,0x44,0xac,0x8c,0x4b,0x43,0xac,0x18,0x08,0x04,0x24,0x30,0x08,0x03,0x24,
+0x90,0x4b,0x44,0xac,0x94,0x4b,0x43,0xac,0x34,0x08,0x04,0x24,0x5c,0x08,0x03,0x24,
+0x98,0x4b,0x44,0xac,0x9c,0x4b,0x43,0xac,0x60,0x0c,0x04,0x24,0x64,0x0c,0x03,0x24,
+0xa0,0x4b,0x44,0xac,0xa4,0x4b,0x43,0xac,0x24,0x0c,0x04,0x24,0x20,0x0c,0x03,0x24,
+0x68,0x08,0x05,0x24,0xa8,0x4b,0x44,0xac,0xac,0x4b,0x43,0xac,0x90,0x0c,0x04,0x24,
+0x94,0x0c,0x03,0x24,0x71,0x4b,0x47,0xa0,0x80,0x4b,0x45,0xac,0xb0,0x4b,0x44,0xac,
+0xb4,0x4b,0x43,0xac,0x08,0x00,0xe0,0x03,0x7c,0x4b,0x45,0xac,0x36,0x43,0x00,0x08,
+0x21,0x18,0x00,0x00,0x20,0x00,0x62,0x2c,0x06,0x00,0x40,0x10,0x00,0x00,0x00,0x00,
+0x06,0x10,0x64,0x00,0x01,0x00,0x42,0x30,0xfa,0xff,0x40,0x10,0x01,0x00,0x63,0x24,
+0xff,0xff,0x63,0x24,0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,0xd8,0xff,0xbd,0x27,
+0x25,0xb0,0x02,0x3c,0x18,0x00,0xb2,0xaf,0x21,0x90,0x82,0x00,0xff,0xff,0x02,0x24,
+0x1c,0x00,0xb3,0xaf,0x14,0x00,0xb1,0xaf,0x20,0x00,0xbf,0xaf,0x10,0x00,0xb0,0xaf,
+0x21,0x88,0xa0,0x00,0x21,0x20,0xa0,0x00,0x21,0x18,0x40,0x02,0x10,0x00,0xa2,0x10,
+0x21,0x98,0xc0,0x00,0x00,0x00,0x50,0x8e,0x31,0x43,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x04,0x10,0x53,0x00,0x27,0x18,0x11,0x00,0x25,0x18,0x62,0x00,0x24,0x18,0x70,0x00,
+0x00,0x00,0x43,0xae,0x20,0x00,0xbf,0x8f,0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,
+0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x28,0x00,0xbd,0x27,
+0x20,0x00,0xbf,0x8f,0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x28,0x00,0xbd,0x27,0x00,0x00,0x66,0xac,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x02,0x80,0x02,0x3c,0x21,0x30,0x80,0x00,0xec,0x60,0x44,0x8c,
+0x3d,0x43,0x00,0x08,0xff,0xff,0x05,0x24,0xe0,0xff,0xbd,0x27,0x25,0xb0,0x02,0x3c,
+0x18,0x00,0xbf,0xaf,0x14,0x00,0xb1,0xaf,0x10,0x00,0xb0,0xaf,0x21,0x20,0x82,0x00,
+0x00,0x00,0x90,0x8c,0x21,0x88,0xa0,0x00,0x31,0x43,0x00,0x0c,0x21,0x20,0xa0,0x00,
+0x24,0x80,0x11,0x02,0x06,0x10,0x50,0x00,0x18,0x00,0xbf,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,0xd0,0xff,0xbd,0x27,
+0x14,0x00,0xb1,0xaf,0x02,0x80,0x11,0x3c,0x28,0x00,0xbf,0xaf,0x20,0x00,0xb4,0xaf,
+0x1c,0x00,0xb3,0xaf,0x18,0x00,0xb2,0xaf,0x24,0x00,0xb5,0xaf,0x10,0x00,0xb0,0xaf,
+0x68,0x15,0x31,0x26,0x98,0x4b,0x22,0x8e,0x25,0xb0,0x12,0x3c,0x24,0x08,0x53,0x36,
+0x21,0x10,0x52,0x00,0x00,0x00,0x70,0x8e,0x00,0x00,0x55,0x8c,0x7f,0x80,0x03,0x3c,
+0xff,0x7f,0x02,0x3c,0xff,0xff,0x63,0x34,0xff,0xff,0x42,0x34,0x24,0x10,0x02,0x02,
+0x24,0x18,0xa3,0x02,0xc0,0x25,0x04,0x00,0x25,0x18,0x64,0x00,0x00,0x80,0x14,0x3c,
+0x00,0x00,0x62,0xae,0x01,0x00,0x04,0x24,0x84,0x0a,0x00,0x0c,0x25,0xa8,0x74,0x00,
+0x98,0x4b,0x22,0x8e,0x25,0x80,0x14,0x02,0x01,0x00,0x04,0x24,0x21,0x10,0x52,0x00,
+0x00,0x00,0x55,0xac,0x84,0x0a,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0xae,
+0x84,0x0a,0x00,0x0c,0x01,0x00,0x04,0x24,0xb8,0x4b,0x24,0x8e,0x0f,0x00,0x05,0x3c,
+0x28,0x00,0xbf,0x8f,0x24,0x00,0xb5,0x8f,0x20,0x00,0xb4,0x8f,0x1c,0x00,0xb3,0x8f,
+0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0xff,0xff,0xa5,0x34,
+0x68,0x43,0x00,0x08,0x30,0x00,0xbd,0x27,0xe0,0xff,0xbd,0x27,0x14,0x00,0xb1,0xaf,
+0x02,0x80,0x11,0x3c,0x10,0x00,0xb0,0xaf,0x18,0x00,0xbf,0xaf,0x68,0x15,0x27,0x26,
+0x73,0x4b,0xe5,0x90,0x01,0x80,0x03,0x3c,0x25,0xb0,0x02,0x3c,0xb0,0x0e,0x63,0x24,
+0x18,0x03,0x42,0x34,0x02,0x00,0x06,0x24,0x00,0x00,0x43,0xac,0x34,0x00,0xa6,0x10,
+0x21,0x80,0x80,0x00,0x03,0x00,0x03,0x24,0x3a,0x00,0xa3,0x10,0x2e,0x00,0x02,0x2e,
+0x10,0x00,0x02,0x2e,0x07,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0xff,0x00,0x04,0x32,
+0x18,0x00,0xbf,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x79,0x43,0x00,0x08,
+0x20,0x00,0xbd,0x27,0xfa,0xff,0xa6,0x14,0xff,0x00,0x04,0x32,0x71,0x4b,0xe4,0x90,
+0x01,0x00,0x02,0x24,0x33,0x00,0x82,0x10,0x02,0x00,0x82,0x28,0x38,0x00,0x40,0x14,
+0x00,0x00,0x00,0x00,0x38,0x00,0x85,0x10,0x68,0x15,0x22,0x26,0x2e,0x00,0x83,0x10,
+0x00,0x00,0x00,0x00,0x00,0x08,0x04,0x24,0x68,0x43,0x00,0x0c,0xff,0xff,0x05,0x24,
+0xff,0xfc,0x06,0x3c,0xff,0xff,0xc6,0x34,0x24,0x30,0x46,0x00,0x00,0x08,0x04,0x24,
+0x3d,0x43,0x00,0x0c,0xff,0xff,0x05,0x24,0x68,0x15,0x22,0x26,0x71,0x4b,0x44,0x90,
+0x01,0x00,0x03,0x24,0x07,0x00,0x83,0x10,0x02,0x00,0x82,0x28,0x2c,0x00,0x40,0x14,
+0x02,0x00,0x02,0x24,0x2c,0x00,0x82,0x10,0x03,0x00,0x02,0x24,0xdb,0xff,0x82,0x14,
+0x00,0x00,0x00,0x00,0x68,0x15,0x22,0x26,0x74,0x4b,0x44,0x8c,0x0f,0x00,0x05,0x3c,
+0x3d,0x43,0x00,0x0c,0x21,0x30,0x00,0x00,0xc2,0x43,0x00,0x08,0xff,0x00,0x04,0x32,
+0x25,0x00,0x82,0x2c,0xcc,0xff,0x40,0x14,0x03,0x00,0x03,0x24,0x18,0x00,0xbf,0x8f,
+0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x20,0x00,0xbd,0x27,0xc7,0xff,0x40,0x14,0x10,0x00,0x02,0x2e,0x18,0x00,0xbf,0x8f,
+0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x20,0x00,0xbd,0x27,0x68,0x15,0x22,0x26,0x74,0x4b,0x44,0x8c,0x0f,0x00,0x05,0x3c,
+0x3d,0x43,0x00,0x0c,0x0f,0x00,0x06,0x24,0xd4,0x43,0x00,0x08,0x00,0x08,0x04,0x24,
+0xcc,0xff,0x80,0x14,0x68,0x15,0x22,0x26,0x74,0x4b,0x44,0x8c,0x0f,0x00,0x05,0x24,
+0x3d,0x43,0x00,0x0c,0x0f,0x00,0x06,0x24,0xd4,0x43,0x00,0x08,0x00,0x08,0x04,0x24,
+0xb2,0xff,0x80,0x14,0x00,0x00,0x00,0x00,0x68,0x15,0x22,0x26,0x74,0x4b,0x44,0x8c,
+0x0f,0x00,0x05,0x24,0x3d,0x43,0x00,0x0c,0x21,0x30,0x00,0x00,0xc2,0x43,0x00,0x08,
+0xff,0x00,0x04,0x32,0xe0,0xff,0xbd,0x27,0x14,0x00,0xb1,0xaf,0x02,0x80,0x11,0x3c,
+0x68,0x15,0x28,0x26,0x73,0x4b,0x06,0x91,0x01,0x80,0x03,0x3c,0x25,0xb0,0x02,0x3c,
+0x5c,0x10,0x63,0x24,0x18,0x03,0x42,0x34,0x02,0x00,0x07,0x24,0x18,0x00,0xb2,0xaf,
+0x10,0x00,0xb0,0xaf,0x1c,0x00,0xbf,0xaf,0x00,0x00,0x43,0xac,0x21,0x90,0xa0,0x00,
+0x39,0x00,0xc7,0x10,0xff,0x00,0x90,0x30,0x03,0x00,0x03,0x24,0x3f,0x00,0xc3,0x10,
+0x2e,0x00,0x02,0x2e,0x10,0x00,0x02,0x2e,0x0c,0x00,0x40,0x10,0x00,0x00,0x00,0x00,
+0x0f,0x00,0x04,0x3c,0xff,0xff,0x84,0x34,0x24,0x20,0x44,0x02,0x00,0x15,0x10,0x00,
+0x1c,0x00,0xbf,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,
+0x25,0x20,0x44,0x00,0x63,0x43,0x00,0x08,0x20,0x00,0xbd,0x27,0xf5,0xff,0xc7,0x14,
+0x0f,0x00,0x04,0x3c,0x71,0x4b,0x04,0x91,0x01,0x00,0x02,0x24,0x33,0x00,0x82,0x10,
+0x02,0x00,0x82,0x28,0x38,0x00,0x40,0x14,0x00,0x00,0x00,0x00,0x38,0x00,0x86,0x10,
+0x68,0x15,0x22,0x26,0x2e,0x00,0x83,0x10,0x00,0x00,0x00,0x00,0x00,0x08,0x04,0x24,
+0x68,0x43,0x00,0x0c,0xff,0xff,0x05,0x24,0xff,0xfc,0x06,0x3c,0xff,0xff,0xc6,0x34,
+0x24,0x30,0x46,0x00,0x00,0x08,0x04,0x24,0x3d,0x43,0x00,0x0c,0xff,0xff,0x05,0x24,
+0x68,0x15,0x22,0x26,0x71,0x4b,0x44,0x90,0x01,0x00,0x03,0x24,0x07,0x00,0x83,0x10,
+0x02,0x00,0x82,0x28,0x2c,0x00,0x40,0x14,0x02,0x00,0x02,0x24,0x2c,0x00,0x82,0x10,
+0x03,0x00,0x02,0x24,0xd6,0xff,0x82,0x14,0x00,0x00,0x00,0x00,0x68,0x15,0x22,0x26,
+0x74,0x4b,0x44,0x8c,0x0f,0x00,0x05,0x3c,0x3d,0x43,0x00,0x0c,0x21,0x30,0x00,0x00,
+0x2f,0x44,0x00,0x08,0x0f,0x00,0x04,0x3c,0x25,0x00,0x02,0x2e,0xc7,0xff,0x40,0x14,
+0x03,0x00,0x03,0x24,0x1c,0x00,0xbf,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,0xc1,0xff,0x40,0x14,
+0x00,0x00,0x00,0x00,0x1c,0x00,0xbf,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,0x68,0x15,0x22,0x26,
+0x74,0x4b,0x44,0x8c,0x0f,0x00,0x05,0x3c,0x3d,0x43,0x00,0x0c,0x0f,0x00,0x06,0x24,
+0x46,0x44,0x00,0x08,0x00,0x08,0x04,0x24,0xcc,0xff,0x80,0x14,0x68,0x15,0x22,0x26,
+0x74,0x4b,0x44,0x8c,0x0f,0x00,0x05,0x24,0x3d,0x43,0x00,0x0c,0x0f,0x00,0x06,0x24,
+0x46,0x44,0x00,0x08,0x00,0x08,0x04,0x24,0xad,0xff,0x80,0x14,0x00,0x00,0x00,0x00,
+0x68,0x15,0x22,0x26,0x74,0x4b,0x44,0x8c,0x0f,0x00,0x05,0x24,0x3d,0x43,0x00,0x0c,
+0x21,0x30,0x00,0x00,0x2f,0x44,0x00,0x08,0x0f,0x00,0x04,0x3c,0xe8,0xff,0xbd,0x27,
+0x10,0x00,0xb0,0xaf,0x21,0x80,0x80,0x00,0x14,0x00,0xbf,0xaf,0x79,0x43,0x00,0x0c,
+0x21,0x20,0x00,0x00,0x40,0x01,0x44,0x34,0x21,0x18,0x40,0x00,0x1f,0x00,0x02,0x2e,
+0x00,0x23,0x04,0x00,0x10,0x00,0x40,0x10,0x10,0x00,0x05,0x2e,0x00,0x01,0x64,0x34,
+0x06,0x00,0xa0,0x10,0x00,0x23,0x04,0x00,0x21,0x10,0x00,0x02,0x14,0x00,0xbf,0x8f,
+0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x18,0x00,0xbd,0x27,0x63,0x43,0x00,0x0c,
+0xf1,0xff,0x10,0x26,0x21,0x10,0x00,0x02,0x14,0x00,0xbf,0x8f,0x10,0x00,0xb0,0x8f,
+0x08,0x00,0xe0,0x03,0x18,0x00,0xbd,0x27,0x63,0x43,0x00,0x0c,0xe2,0xff,0x10,0x26,
+0x21,0x10,0x00,0x02,0x14,0x00,0xbf,0x8f,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,
+0x18,0x00,0xbd,0x27,0x25,0xb0,0x02,0x3c,0x27,0x38,0x05,0x00,0x21,0x40,0x82,0x00,
+0xff,0xff,0x02,0x24,0x07,0x00,0xa2,0x10,0x25,0x38,0xe6,0x00,0x00,0x00,0x02,0x8d,
+0x00,0x00,0x00,0x00,0x24,0x10,0xe2,0x00,0x00,0x00,0x02,0xad,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x00,0x00,0x06,0xad,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x01,0x80,0x02,0x3c,0x25,0xb0,0x03,0x3c,0xe8,0x12,0x42,0x24,0x18,0x03,0x63,0x34,
+0xd8,0xff,0xbd,0x27,0x00,0x00,0x62,0xac,0x0f,0x00,0x02,0x3c,0x14,0x00,0xb1,0xaf,
+0xff,0xff,0x42,0x34,0x21,0x88,0xa0,0x00,0x1c,0x00,0xb3,0xaf,0x18,0x00,0xb2,0xaf,
+0x20,0x00,0xbf,0xaf,0x10,0x00,0xb0,0xaf,0x21,0x90,0xc0,0x00,0x21,0x28,0xc0,0x00,
+0x0a,0x00,0x22,0x12,0x21,0x98,0x80,0x00,0xac,0x43,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x21,0x20,0x20,0x02,0x31,0x43,0x00,0x0c,0x21,0x80,0x40,0x00,0x04,0x10,0x52,0x00,
+0x27,0x28,0x11,0x00,0x25,0x28,0xa2,0x00,0x24,0x28,0xb0,0x00,0xff,0x00,0x64,0x32,
+0x20,0x00,0xbf,0x8f,0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x17,0x44,0x00,0x08,0x28,0x00,0xbd,0x27,0x01,0x80,0x03,0x3c,
+0x25,0xb0,0x02,0x3c,0x74,0x13,0x63,0x24,0x18,0x03,0x42,0x34,0xe0,0xff,0xbd,0x27,
+0x00,0x00,0x43,0xac,0x18,0x00,0xbf,0xaf,0x14,0x00,0xb1,0xaf,0x10,0x00,0xb0,0xaf,
+0xac,0x43,0x00,0x0c,0x21,0x88,0xa0,0x00,0x21,0x80,0x40,0x00,0x31,0x43,0x00,0x0c,
+0x21,0x20,0x20,0x02,0x24,0x80,0x11,0x02,0x06,0x10,0x50,0x00,0x18,0x00,0xbf,0x8f,
+0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x01,0x00,0x02,0x24,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0xc8,0xff,0xbd,0x27,0x2c,0x00,0xb1,0xaf,0xff,0xff,0x05,0x24,0x21,0x88,0x80,0x00,
+0x02,0x00,0x06,0x24,0x10,0x00,0xa4,0x27,0x34,0x00,0xbf,0xaf,0x30,0x00,0xb2,0xaf,
+0x97,0x45,0x00,0x0c,0x28,0x00,0xb0,0xaf,0x08,0x00,0x30,0x96,0x02,0x80,0x02,0x3c,
+0x21,0x28,0x00,0x00,0x25,0x80,0x02,0x02,0x21,0x20,0x00,0x02,0x97,0x45,0x00,0x0c,
+0x10,0x00,0x06,0x24,0x20,0x00,0x02,0x96,0x24,0x00,0x04,0x26,0x10,0x00,0xa5,0x27,
+0x03,0xff,0x42,0x30,0xc8,0x00,0x42,0x34,0x20,0x00,0x02,0xa6,0x9f,0x45,0x00,0x0c,
+0x06,0x00,0x06,0x24,0x25,0xb0,0x03,0x3c,0x50,0x00,0x62,0x34,0x00,0x00,0x44,0x8c,
+0x54,0x00,0x65,0x34,0x58,0x00,0x66,0x34,0x18,0x00,0xa4,0xaf,0x00,0x00,0xa2,0x8c,
+0x5c,0x00,0x63,0x34,0x2a,0x00,0x04,0x26,0x1c,0x00,0xa2,0xaf,0x00,0x00,0xc7,0x8c,
+0x18,0x00,0xa5,0x27,0x06,0x00,0x06,0x24,0x20,0x00,0xa7,0xaf,0x00,0x00,0x62,0x8c,
+0x1a,0x00,0x12,0x24,0x9f,0x45,0x00,0x0c,0x24,0x00,0xa2,0xaf,0x30,0x00,0x04,0x26,
+0x20,0x00,0xa5,0x27,0x9f,0x45,0x00,0x0c,0x06,0x00,0x06,0x24,0x13,0x00,0x03,0x24,
+0x14,0x00,0x23,0xae,0x0c,0x00,0x32,0xae,0x08,0x00,0x05,0x8e,0x04,0x00,0x04,0x8e,
+0xff,0xdf,0x02,0x3c,0x14,0x00,0x06,0x8e,0xff,0xff,0x42,0x34,0x10,0x00,0x07,0x8e,
+0xff,0xe0,0x03,0x24,0x24,0x28,0xa2,0x00,0x00,0x40,0x02,0x3c,0x24,0x20,0x83,0x00,
+0x25,0x28,0xa2,0x00,0xff,0x81,0x03,0x24,0xfe,0xff,0x02,0x3c,0x24,0x30,0xc3,0x00,
+0xff,0xff,0x42,0x34,0x00,0x12,0x84,0x34,0x00,0x80,0x03,0x3c,0x24,0x20,0x82,0x00,
+0x25,0x38,0xe3,0x00,0x00,0x26,0xc6,0x34,0x80,0x00,0xa5,0x34,0x20,0x00,0x02,0x24,
+0x00,0x00,0x12,0xa6,0x10,0x00,0x07,0xae,0x02,0x00,0x02,0xa2,0x14,0x00,0x06,0xae,
+0x04,0x00,0x04,0xae,0x08,0x00,0x05,0xae,0x34,0x00,0xbf,0x8f,0x30,0x00,0xb2,0x8f,
+0x2c,0x00,0xb1,0x8f,0x28,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x38,0x00,0xbd,0x27,
+0x93,0x45,0x00,0x08,0xff,0x00,0xa5,0x30,0x00,0x00,0x85,0xa0,0xff,0xff,0xc6,0x24,
+0x01,0x00,0x84,0x24,0xfc,0xff,0xc0,0x14,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x05,0x00,0xc0,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x85,0xac,
+0xff,0xff,0xc6,0x24,0xfd,0xff,0xc0,0x14,0x04,0x00,0x84,0x24,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x21,0x38,0x80,0x00,0x08,0x00,0xc0,0x10,0xff,0xff,0xc3,0x24,
+0xff,0xff,0x06,0x24,0x00,0x00,0xa2,0x90,0xff,0xff,0x63,0x24,0x01,0x00,0xa5,0x24,
+0x00,0x00,0xe2,0xa0,0xfb,0xff,0x66,0x14,0x01,0x00,0xe7,0x24,0x08,0x00,0xe0,0x03,
+0x21,0x10,0x80,0x00,0x21,0x38,0x80,0x00,0x08,0x00,0xc0,0x10,0xff,0xff,0xc3,0x24,
+0xff,0xff,0x06,0x24,0x00,0x00,0xa2,0x8c,0xff,0xff,0x63,0x24,0x04,0x00,0xa5,0x24,
+0x00,0x00,0xe2,0xac,0xfb,0xff,0x66,0x14,0x04,0x00,0xe7,0x24,0x08,0x00,0xe0,0x03,
+0x21,0x10,0x80,0x00,0x2b,0x10,0xa4,0x00,0x0d,0x00,0x40,0x14,0xff,0xff,0x02,0x24,
+0xff,0xff,0xc6,0x24,0x08,0x00,0xc2,0x10,0x21,0x18,0x80,0x00,0xff,0xff,0x07,0x24,
+0x00,0x00,0xa2,0x90,0xff,0xff,0xc6,0x24,0x01,0x00,0xa5,0x24,0x00,0x00,0x62,0xa0,
+0xfb,0xff,0xc7,0x14,0x01,0x00,0x63,0x24,0x08,0x00,0xe0,0x03,0x21,0x10,0x80,0x00,
+0x21,0x28,0xa6,0x00,0x21,0x18,0x86,0x00,0xff,0xff,0xc6,0x24,0xfa,0xff,0xc2,0x10,
+0x00,0x00,0x00,0x00,0xff,0xff,0x07,0x24,0xff,0xff,0xa5,0x24,0x00,0x00,0xa2,0x90,
+0xff,0xff,0x63,0x24,0xff,0xff,0xc6,0x24,0xfb,0xff,0xc7,0x14,0x00,0x00,0x62,0xa0,
+0x08,0x00,0xe0,0x03,0x21,0x10,0x80,0x00,0x0c,0x00,0xc0,0x10,0x00,0x00,0x00,0x00,
+0x00,0x00,0x82,0x90,0x00,0x00,0xa3,0x90,0x01,0x00,0x84,0x24,0x23,0x10,0x43,0x00,
+0x00,0x16,0x02,0x00,0x03,0x16,0x02,0x00,0x04,0x00,0x40,0x14,0x01,0x00,0xa5,0x24,
+0xff,0xff,0xc6,0x24,0xf6,0xff,0xc0,0x14,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x21,0x10,0xc0,0x00,0xea,0x45,0x00,0x08,0x21,0x18,0x86,0x00,0x00,0x00,0x82,0x90,
+0x00,0x00,0x00,0x00,0x04,0x00,0x45,0x10,0x00,0x00,0x00,0x00,0x01,0x00,0x84,0x24,
+0xfa,0xff,0x83,0x14,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x80,0x00,
+0x09,0x00,0xc0,0x10,0xff,0xff,0xc3,0x24,0xff,0x00,0xa5,0x30,0xff,0xff,0x06,0x24,
+0x00,0x00,0x82,0x90,0xff,0xff,0x63,0x24,0x05,0x00,0x45,0x10,0x01,0x00,0x84,0x24,
+0xfb,0xff,0x66,0x14,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0xff,0xff,0x82,0x24,0x21,0x38,0x00,0x00,0x1f,0x00,0xc0,0x10,
+0x21,0x18,0x00,0x00,0x02,0x80,0x02,0x3c,0x80,0x95,0x4b,0x24,0x00,0x00,0x87,0x90,
+0x00,0x00,0xa3,0x90,0xff,0xff,0xc6,0x24,0x01,0x00,0x84,0x24,0x21,0x10,0xeb,0x00,
+0x16,0x00,0xe0,0x10,0x01,0x00,0xa5,0x24,0x14,0x00,0x60,0x10,0x21,0x48,0x6b,0x00,
+0x10,0x00,0xe3,0x10,0x20,0x00,0xe8,0x24,0x00,0x00,0x42,0x90,0x00,0x00,0x00,0x00,
+0x01,0x00,0x42,0x30,0x02,0x00,0x40,0x10,0x20,0x00,0x6a,0x24,0xff,0x00,0x07,0x31,
+0x00,0x00,0x22,0x91,0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x30,0x02,0x00,0x40,0x10,
+0xff,0x00,0xe7,0x30,0xff,0x00,0x43,0x31,0xff,0x00,0x63,0x30,0x03,0x00,0xe3,0x14,
+0x00,0x00,0x00,0x00,0xe5,0xff,0xc0,0x14,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x23,0x10,0xe3,0x00,0x21,0x18,0x80,0x00,0x00,0x00,0xa2,0x90,0x01,0x00,0xa5,0x24,
+0x00,0x00,0x82,0xa0,0xfc,0xff,0x40,0x14,0x01,0x00,0x84,0x24,0x08,0x00,0xe0,0x03,
+0x21,0x10,0x60,0x00,0x21,0x38,0x80,0x00,0xff,0xff,0x03,0x24,0xff,0xff,0xc6,0x24,
+0x06,0x00,0xc3,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0xa2,0x90,0x01,0x00,0xa5,0x24,
+0x00,0x00,0x82,0xa0,0xf9,0xff,0x40,0x14,0x01,0x00,0x84,0x24,0x08,0x00,0xe0,0x03,
+0x21,0x10,0xe0,0x00,0x00,0x00,0x82,0x80,0x39,0x46,0x00,0x08,0x21,0x18,0x80,0x00,
+0x01,0x00,0x84,0x24,0x00,0x00,0x82,0x80,0x00,0x00,0x00,0x00,0xfc,0xff,0x40,0x14,
+0x00,0x00,0x00,0x00,0x00,0x00,0xa2,0x90,0x01,0x00,0xa5,0x24,0x00,0x00,0x82,0xa0,
+0xfc,0xff,0x40,0x14,0x01,0x00,0x84,0x24,0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,
+0x12,0x00,0xc0,0x10,0x21,0x18,0x80,0x00,0x00,0x00,0x82,0x80,0x4a,0x46,0x00,0x08,
+0x00,0x00,0x00,0x00,0x01,0x00,0x84,0x24,0x00,0x00,0x82,0x80,0x00,0x00,0x00,0x00,
+0xfc,0xff,0x40,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0xa2,0x90,0x01,0x00,0xa5,0x24,
+0x00,0x00,0x82,0xa0,0x05,0x00,0x40,0x10,0x01,0x00,0x84,0x24,0xff,0xff,0xc6,0x24,
+0xf9,0xff,0xc0,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xa0,0x08,0x00,0xe0,0x03,
+0x21,0x10,0x60,0x00,0x00,0x00,0x83,0x90,0x00,0x00,0xa2,0x90,0x01,0x00,0x84,0x24,
+0x23,0x10,0x62,0x00,0x00,0x16,0x02,0x00,0x03,0x16,0x02,0x00,0x03,0x00,0x40,0x14,
+0x01,0x00,0xa5,0x24,0xf7,0xff,0x60,0x14,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x21,0x10,0x00,0x00,0x0b,0x00,0xc0,0x10,0x00,0x00,0x00,0x00,
+0x00,0x00,0xa2,0x90,0x00,0x00,0x83,0x90,0xff,0xff,0xc6,0x24,0x23,0x10,0x62,0x00,
+0x00,0x16,0x02,0x00,0x03,0x16,0x02,0x00,0x03,0x00,0x40,0x14,0x01,0x00,0xa5,0x24,
+0xf5,0xff,0x60,0x14,0x01,0x00,0x84,0x24,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x00,0x00,0x83,0x80,0x00,0x2e,0x05,0x00,0x21,0x10,0x80,0x00,0x7b,0x46,0x00,0x08,
+0x03,0x2e,0x05,0x00,0x07,0x00,0x60,0x10,0x01,0x00,0x42,0x24,0x00,0x00,0x43,0x80,
+0x00,0x00,0x00,0x00,0xfb,0xff,0x65,0x14,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x00,0x00,0x00,0x82,0x80,
+0x87,0x46,0x00,0x08,0x21,0x18,0x80,0x00,0x01,0x00,0x63,0x24,0x00,0x00,0x62,0x80,
+0x00,0x00,0x00,0x00,0xfc,0xff,0x40,0x14,0x23,0x10,0x64,0x00,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0xe0,0xff,0xbd,0x27,0x10,0x00,0xb0,0xaf,0x21,0x80,0xa0,0x00,
+0x14,0x00,0xb1,0xaf,0x18,0x00,0xbf,0xaf,0x21,0x88,0x80,0x00,0x81,0x46,0x00,0x0c,
+0x00,0x86,0x10,0x00,0x21,0x18,0x51,0x00,0x03,0x86,0x10,0x00,0x00,0x00,0x62,0x80,
+0x00,0x00,0x00,0x00,0x0a,0x00,0x50,0x10,0x21,0x10,0x60,0x00,0xff,0xff,0x63,0x24,
+0x2b,0x10,0x71,0x00,0xf9,0xff,0x40,0x10,0x21,0x10,0x00,0x00,0x18,0x00,0xbf,0x8f,
+0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,
+0x18,0x00,0xbf,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,
+0x20,0x00,0xbd,0x27,0x21,0x30,0x80,0x00,0x0d,0x00,0xa0,0x10,0xff,0xff,0xa3,0x24,
+0x00,0x00,0x82,0x80,0x00,0x00,0x00,0x00,0x09,0x00,0x40,0x10,0x00,0x00,0x00,0x00,
+0xff,0xff,0x05,0x24,0xff,0xff,0x63,0x24,0x05,0x00,0x65,0x10,0x01,0x00,0xc6,0x24,
+0x00,0x00,0xc2,0x80,0x00,0x00,0x00,0x00,0xfa,0xff,0x40,0x14,0x00,0x00,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x23,0x10,0xc4,0x00,0x00,0x00,0x82,0x90,0x00,0x00,0x00,0x00,
+0x19,0x00,0x40,0x10,0x21,0x40,0x00,0x00,0x00,0x00,0xa9,0x80,0x00,0x00,0x00,0x00,
+0x17,0x00,0x20,0x11,0x21,0x30,0xa0,0x00,0x00,0x3e,0x02,0x00,0x03,0x3e,0x07,0x00,
+0x21,0x18,0x20,0x01,0x15,0x00,0xe3,0x10,0x00,0x00,0x00,0x00,0x01,0x00,0xc6,0x24,
+0x00,0x00,0xc2,0x90,0x00,0x00,0x00,0x00,0x00,0x1e,0x02,0x00,0x03,0x1e,0x03,0x00,
+0xf8,0xff,0x60,0x14,0x00,0x16,0x02,0x00,0x03,0x16,0x02,0x00,0x06,0x00,0x40,0x10,
+0x00,0x00,0x00,0x00,0x01,0x00,0x84,0x24,0x00,0x00,0x82,0x90,0x00,0x00,0x00,0x00,
+0xeb,0xff,0x40,0x14,0x01,0x00,0x08,0x25,0x08,0x00,0xe0,0x03,0x21,0x10,0x00,0x01,
+0x00,0x00,0xa2,0x90,0xcc,0x46,0x00,0x08,0x00,0x16,0x02,0x00,0x00,0x00,0xc2,0x90,
+0xcc,0x46,0x00,0x08,0x00,0x16,0x02,0x00,0x00,0x00,0x87,0x90,0x00,0x00,0x00,0x00,
+0x14,0x00,0xe0,0x10,0x21,0x10,0x80,0x00,0x00,0x00,0xa4,0x90,0x00,0x00,0x00,0x00,
+0x00,0x1e,0x04,0x00,0x03,0x1e,0x03,0x00,0x09,0x00,0x60,0x10,0x21,0x30,0xa0,0x00,
+0x00,0x3e,0x07,0x00,0x03,0x3e,0x07,0x00,0x0b,0x00,0xe3,0x10,0x01,0x00,0xc6,0x24,
+0x00,0x00,0xc3,0x80,0x00,0x00,0x00,0x00,0xfb,0xff,0x60,0x14,0x00,0x00,0x00,0x00,
+0x01,0x00,0x42,0x24,0x00,0x00,0x47,0x90,0x00,0x00,0x00,0x00,0xf0,0xff,0xe0,0x14,
+0x00,0x00,0x00,0x00,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0xe0,0xff,0xbd,0x27,0x14,0x00,0xb1,0xaf,0x10,0x00,0xb0,0xaf,0x18,0x00,0xbf,0xaf,
+0x21,0x80,0x80,0x00,0x1d,0x00,0x80,0x10,0x21,0x88,0xa0,0x00,0xb8,0x46,0x00,0x0c,
+0x21,0x20,0x00,0x02,0x21,0x80,0x02,0x02,0x00,0x00,0x02,0x82,0x21,0x28,0x20,0x02,
+0x21,0x20,0x00,0x02,0x22,0x00,0x40,0x10,0x21,0x18,0x00,0x00,0xdc,0x46,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x05,0x00,0x40,0x10,0x21,0x18,0x40,0x00,0x00,0x00,0x42,0x80,
+0x00,0x00,0x00,0x00,0x0a,0x00,0x40,0x14,0x00,0x00,0x00,0x00,0x02,0x80,0x02,0x3c,
+0xa8,0x96,0x43,0xac,0x21,0x18,0x00,0x02,0x18,0x00,0xbf,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x21,0x10,0x60,0x00,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,
+0x00,0x00,0x60,0xa0,0x0d,0x47,0x00,0x08,0x01,0x00,0x63,0x24,0x02,0x80,0x02,0x3c,
+0xa8,0x96,0x50,0x8c,0x00,0x00,0x00,0x00,0xf3,0xff,0x00,0x12,0x21,0x18,0x00,0x00,
+0xb8,0x46,0x00,0x0c,0x21,0x20,0x00,0x02,0x21,0x80,0x02,0x02,0x00,0x00,0x02,0x82,
+0x21,0x28,0x20,0x02,0x21,0x20,0x00,0x02,0xe0,0xff,0x40,0x14,0x21,0x18,0x00,0x00,
+0x18,0x00,0xbf,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x02,0x80,0x02,0x3c,
+0xa8,0x96,0x40,0xac,0x20,0x00,0xbd,0x27,0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,
+0xe0,0xff,0xbd,0x27,0x18,0x00,0xb2,0xaf,0x14,0x00,0xb1,0xaf,0x1c,0x00,0xbf,0xaf,
+0x10,0x00,0xb0,0xaf,0x00,0x00,0x90,0x8c,0x21,0x90,0x80,0x00,0x21,0x88,0xa0,0x00,
+0x21,0x18,0x00,0x00,0x0f,0x00,0x00,0x12,0x21,0x20,0x00,0x02,0xb8,0x46,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x21,0x80,0x02,0x02,0x00,0x00,0x02,0x82,0x21,0x28,0x20,0x02,
+0x21,0x20,0x00,0x02,0x07,0x00,0x40,0x10,0x21,0x18,0x00,0x00,0xdc,0x46,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x21,0x18,0x40,0x00,0x09,0x00,0x40,0x14,0x00,0x00,0x42,0xae,
+0x21,0x18,0x00,0x02,0x1c,0x00,0xbf,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x21,0x10,0x60,0x00,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,
+0x00,0x00,0x42,0x80,0x00,0x00,0x00,0x00,0xf5,0xff,0x40,0x10,0x01,0x00,0x64,0x24,
+0x00,0x00,0x60,0xa0,0x46,0x47,0x00,0x08,0x00,0x00,0x44,0xae,0xd8,0xff,0xbd,0x27,
+0x14,0x00,0xb1,0xaf,0x21,0x88,0x80,0x00,0x21,0x20,0xa0,0x00,0x1c,0x00,0xb3,0xaf,
+0x18,0x00,0xb2,0xaf,0x20,0x00,0xbf,0xaf,0x10,0x00,0xb0,0xaf,0x81,0x46,0x00,0x0c,
+0x21,0x98,0xa0,0x00,0x21,0x90,0x40,0x00,0x08,0x00,0x40,0x16,0x21,0x10,0x20,0x02,
+0x20,0x00,0xbf,0x8f,0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x28,0x00,0xbd,0x27,0x81,0x46,0x00,0x0c,
+0x21,0x20,0x20,0x02,0x21,0x80,0x40,0x00,0x2a,0x10,0x52,0x00,0x0a,0x00,0x40,0x14,
+0x00,0x00,0x00,0x00,0x21,0x20,0x20,0x02,0x21,0x28,0x60,0x02,0x21,0x30,0x40,0x02,
+0xd4,0x45,0x00,0x0c,0xff,0xff,0x10,0x26,0x0b,0x00,0x40,0x10,0x2a,0x18,0x12,0x02,
+0xf8,0xff,0x60,0x10,0x01,0x00,0x31,0x26,0x20,0x00,0xbf,0x8f,0x1c,0x00,0xb3,0x8f,
+0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x21,0x10,0x00,0x00,
+0x08,0x00,0xe0,0x03,0x28,0x00,0xbd,0x27,0x62,0x47,0x00,0x08,0x21,0x10,0x20,0x02,
+0x01,0x80,0x02,0x3c,0xc0,0xff,0xbd,0x27,0x08,0x1e,0x44,0x24,0x25,0xb0,0x02,0x3c,
+0x28,0x00,0xb4,0xaf,0x02,0x80,0x03,0x3c,0x25,0xb0,0x14,0x3c,0x18,0x03,0x42,0x34,
+0x38,0x00,0xbe,0xaf,0x34,0x00,0xb7,0xaf,0x30,0x00,0xb6,0xaf,0x2c,0x00,0xb5,0xaf,
+0x24,0x00,0xb3,0xaf,0x3c,0x00,0xbf,0xaf,0x20,0x00,0xb2,0xaf,0x1c,0x00,0xb1,0xaf,
+0x18,0x00,0xb0,0xaf,0x68,0x15,0x73,0x24,0x00,0x00,0x44,0xac,0x02,0x80,0x16,0x3c,
+0x02,0x80,0x15,0x3c,0xc4,0x02,0x9e,0x36,0x64,0x03,0x97,0x36,0x01,0x80,0x04,0x3c,
+0x08,0x1e,0x82,0x24,0x18,0x03,0x83,0x36,0x00,0x00,0x62,0xac,0xa0,0x02,0x87,0x36,
+0x00,0x00,0xe4,0x8c,0xd8,0x63,0x63,0x8e,0xff,0x0f,0x02,0x3c,0xff,0xff,0x46,0x34,
+0x24,0x80,0x86,0x00,0x01,0x00,0x05,0x3c,0x01,0x00,0x63,0x24,0x2b,0x10,0xb0,0x00,
+0x07,0x00,0x40,0x10,0xd8,0x63,0x63,0xae,0xa4,0x02,0x82,0x36,0x00,0x00,0x51,0x8c,
+0x00,0xb0,0x03,0x3c,0x25,0x80,0x03,0x02,0x00,0x00,0x11,0xae,0x00,0x00,0xe0,0xac,
+0xb0,0x02,0x84,0x36,0x00,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,0x24,0x80,0x46,0x00,
+0x2b,0x18,0xb0,0x00,0x08,0x00,0x60,0x10,0xc0,0x02,0x82,0x36,0x00,0xb0,0x02,0x3c,
+0x25,0x80,0x02,0x02,0x00,0x00,0x11,0x8e,0xb4,0x02,0x82,0x36,0x00,0x00,0x51,0xac,
+0x00,0x00,0x80,0xac,0xc0,0x02,0x82,0x36,0x00,0x00,0x50,0x8c,0xff,0x00,0x08,0x3c,
+0xff,0xff,0x02,0x35,0x2b,0x10,0x50,0x00,0x47,0x00,0x40,0x10,0x00,0x00,0x00,0x00,
+0x00,0x00,0x82,0x8e,0x00,0xff,0x06,0x3c,0xac,0x02,0x84,0x36,0x01,0x00,0x45,0x24,
+0xbc,0x02,0x83,0x36,0xff,0x00,0xc2,0x34,0x00,0xfd,0x07,0x3c,0x00,0x00,0x85,0xac,
+0x00,0x00,0x70,0xac,0x24,0x18,0x02,0x02,0x07,0x00,0xe2,0x34,0x00,0x00,0x85,0x8c,
+0x52,0x03,0x62,0x10,0x25,0xb0,0x12,0x3c,0x2b,0x10,0x43,0x00,0xa2,0x00,0x40,0x14,
+0xa4,0x00,0xe2,0x34,0x00,0xf8,0x04,0x3c,0x15,0x00,0x82,0x34,0x57,0x03,0x62,0x10,
+0x2b,0x10,0x43,0x00,0xc8,0x00,0x40,0x14,0x00,0xf9,0x05,0x3c,0x00,0xf0,0x05,0x3c,
+0x20,0x00,0xa2,0x34,0x67,0x03,0x62,0x10,0x2b,0x10,0x43,0x00,0x20,0x01,0x40,0x14,
+0x10,0x00,0x82,0x34,0x70,0x03,0x65,0x10,0x2b,0x10,0xa3,0x00,0xc8,0x01,0x40,0x14,
+0x02,0x00,0xa2,0x34,0x00,0xd0,0x02,0x3c,0x2a,0x02,0x62,0x10,0x2b,0x10,0x43,0x00,
+0xaf,0x02,0x40,0x14,0x00,0xe0,0x02,0x3c,0x00,0xc0,0x02,0x3c,0xbb,0x03,0x62,0x10,
+0xff,0x00,0x03,0x3c,0x00,0xf0,0x02,0x3c,0x24,0x30,0x02,0x02,0x18,0x00,0xc2,0x10,
+0x02,0x1d,0x10,0x00,0x00,0x70,0x05,0x3c,0x24,0x10,0x05,0x02,0x02,0x4f,0x02,0x00,
+0x0f,0x00,0x02,0x3c,0xff,0xff,0x42,0x34,0x00,0x50,0x07,0x3c,0xff,0x00,0x68,0x30,
+0xff,0x00,0x04,0x32,0x96,0x01,0xc7,0x10,0x24,0x18,0x02,0x02,0x2b,0x10,0xe6,0x00,
+0x8a,0x01,0x40,0x14,0x00,0x80,0x02,0x3c,0x00,0x20,0x02,0x3c,0x1a,0x03,0xc2,0x10,
+0x2b,0x10,0x46,0x00,0x82,0x02,0x40,0x14,0x00,0x30,0x02,0x3c,0x17,0x03,0xc0,0x10,
+0x80,0x10,0x08,0x00,0x00,0x10,0x02,0x3c,0x14,0x03,0xc2,0x10,0x80,0x10,0x08,0x00,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x00,0x00,0xe2,0x92,0x25,0xb0,0x07,0x3c,
+0xc8,0x7d,0xc2,0xa2,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0xc8,0x7d,0xc2,0x92,0x00,0x00,0x00,0x00,0x01,0x00,0x42,0x30,0x4e,0x00,0x40,0x10,
+0x02,0x80,0x03,0x3c,0x00,0x40,0x62,0x8e,0xf0,0xff,0x03,0x24,0xd7,0x42,0x60,0xa2,
+0x24,0x10,0x43,0x00,0x01,0x00,0x42,0x34,0x00,0x40,0x62,0xae,0xc8,0x7d,0xc2,0x92,
+0x00,0x00,0x00,0x00,0x02,0x00,0x42,0x30,0x3d,0x00,0x40,0x10,0x0f,0xff,0x03,0x24,
+0x00,0x40,0x62,0x8e,0x00,0x00,0x00,0x00,0x24,0x10,0x43,0x00,0x10,0x00,0x42,0x34,
+0x00,0x40,0x62,0xae,0xc8,0x7d,0xc2,0x92,0x00,0x00,0x00,0x00,0x04,0x00,0x42,0x30,
+0x30,0x00,0x40,0x10,0xff,0xf0,0x03,0x24,0x00,0x40,0x62,0x8e,0x00,0x00,0x00,0x00,
+0x24,0x10,0x43,0x00,0x00,0x01,0x42,0x34,0x25,0xb0,0x05,0x3c,0x00,0x40,0x62,0xae,
+0x4c,0x00,0xa3,0x34,0x00,0x00,0x62,0x90,0x00,0x00,0x00,0x00,0x03,0x00,0x42,0x30,
+0x05,0x00,0x40,0x14,0xff,0xff,0x02,0x3c,0x00,0x40,0x63,0x8e,0xff,0x0f,0x42,0x34,
+0x24,0x18,0x62,0x00,0x00,0x40,0x63,0xae,0x00,0x7b,0xa4,0x8e,0x01,0x80,0x06,0x3c,
+0x08,0x1f,0xc2,0x24,0x18,0x03,0xa3,0x34,0x00,0x7b,0xa6,0x26,0x00,0x00,0x62,0xac,
+0x10,0x00,0x86,0x10,0x02,0x80,0x02,0x3c,0xbf,0x00,0xb2,0x34,0x68,0x15,0x51,0x24,
+0x21,0x80,0xc0,0x00,0x00,0x00,0x42,0x92,0x00,0x00,0x00,0x00,0x04,0x00,0x42,0x2c,
+0x09,0x00,0x40,0x10,0x02,0x80,0x07,0x3c,0x98,0x65,0x24,0x8e,0x8b,0x07,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x00,0x7b,0xa2,0x8e,0x00,0x00,0x00,0x00,0xf5,0xff,0x50,0x14,
+0x00,0x00,0x00,0x00,0x02,0x80,0x07,0x3c,0x08,0x08,0xe4,0x24,0x21,0x28,0x00,0x00,
+0x21,0x30,0x00,0x00,0x31,0x1c,0x00,0x0c,0x21,0x38,0x00,0x00,0x9a,0x47,0x00,0x08,
+0x01,0x80,0x04,0x3c,0x00,0x40,0x62,0x8e,0x30,0x48,0x00,0x08,0x24,0x10,0x43,0x00,
+0x00,0x40,0x62,0x8e,0x04,0x43,0x64,0x92,0x24,0x10,0x43,0x00,0x00,0x40,0x62,0xae,
+0x27,0x48,0x00,0x08,0x04,0x43,0x64,0xae,0x68,0x15,0x66,0x24,0x00,0x40,0xc2,0x8c,
+0xd7,0x42,0xc4,0x90,0xf0,0xff,0x03,0x24,0x24,0x10,0x43,0x00,0xb3,0xff,0x80,0x14,
+0x00,0x40,0xc2,0xac,0x1c,0x00,0x04,0x24,0x58,0x0c,0xe5,0x34,0x50,0x0c,0xe3,0x34,
+0x01,0x00,0x02,0x24,0xd7,0x42,0xc2,0xa0,0x00,0x00,0x64,0xa0,0x00,0x00,0xa4,0xa0,
+0x1d,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xb2,0x02,0x62,0x10,0x2b,0x10,0x43,0x00,
+0x3f,0x00,0x40,0x14,0xaf,0x00,0xe2,0x34,0x20,0x00,0xe2,0x34,0xc0,0x02,0x62,0x10,
+0x2b,0x10,0x43,0x00,0xe3,0x00,0x40,0x14,0x29,0x00,0xe2,0x34,0x15,0x00,0xe2,0x34,
+0x0c,0x03,0x62,0x10,0x2b,0x10,0x43,0x00,0x9d,0x01,0x40,0x14,0x17,0x00,0xe2,0x34,
+0x09,0x00,0xe2,0x34,0xd8,0x03,0x62,0x10,0x2b,0x10,0x62,0x00,0x81,0x02,0x40,0x14,
+0x14,0x00,0xe2,0x34,0x64,0xff,0x62,0x14,0x00,0xf0,0x02,0x3c,0xff,0x00,0x07,0x3c,
+0x00,0xff,0xe7,0x34,0x24,0x10,0x07,0x02,0x7a,0xff,0x40,0x10,0xc0,0x02,0x82,0x36,
+0x04,0x43,0x64,0x92,0xff,0x00,0x02,0x3c,0x24,0x10,0x02,0x02,0x00,0xff,0x03,0x32,
+0x02,0x14,0x02,0x00,0x02,0x1a,0x03,0x00,0xfb,0xff,0x45,0x24,0x1c,0x43,0x62,0xa2,
+0x00,0x01,0x84,0x34,0xfb,0xff,0x66,0x24,0xc0,0x02,0x82,0x36,0x04,0x43,0x64,0xae,
+0x1d,0x43,0x65,0xa2,0x1f,0x43,0x66,0xa2,0x1e,0x43,0x63,0xa2,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x05,0x00,0xa2,0x34,0x91,0x02,0x62,0x10,
+0x2b,0x10,0x43,0x00,0x8e,0x00,0x40,0x14,0x00,0x00,0x00,0x00,0xde,0x02,0x65,0x10,
+0x2b,0x10,0xa3,0x00,0x32,0x01,0x40,0x14,0x02,0x00,0xa2,0x34,0x17,0x00,0x82,0x34,
+0x61,0x04,0x62,0x10,0x2b,0x10,0x62,0x00,0xa9,0x03,0x40,0x14,0x18,0x00,0x82,0x34,
+0x3d,0xff,0x62,0x14,0x00,0xf0,0x02,0x3c,0x74,0x0b,0x00,0x0c,0x00,0x00,0x00,0x00,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0xa8,0x02,0x62,0x10,0x2b,0x10,0x43,0x00,0x95,0x00,0x40,0x14,0x0c,0x00,0xc2,0x34,
+0xaa,0x00,0xe2,0x34,0xdc,0x02,0x62,0x10,0x2b,0x10,0x43,0x00,0xd9,0x00,0x40,0x14,
+0xac,0x00,0xe2,0x34,0xa6,0x00,0xe2,0x34,0x1c,0x04,0x62,0x10,0x2b,0x10,0x62,0x00,
+0x69,0x03,0x40,0x14,0xa7,0x00,0xe2,0x34,0x27,0xff,0x62,0x14,0x00,0xf0,0x02,0x3c,
+0x00,0xff,0x02,0x32,0xff,0x00,0x04,0x3c,0x02,0x8a,0x02,0x00,0x24,0x18,0x04,0x02,
+0x01,0x00,0x02,0x24,0xa6,0x04,0x22,0x12,0x02,0x1c,0x03,0x00,0x02,0x00,0x02,0x24,
+0xc9,0x04,0x22,0x12,0x03,0x00,0x02,0x24,0xdf,0x04,0x22,0x12,0x04,0x00,0x02,0x24,
+0xd1,0x04,0x22,0x12,0x08,0x00,0x02,0x24,0x2e,0x05,0x22,0x12,0x09,0x00,0x02,0x24,
+0x1e,0x05,0x22,0x12,0x0a,0x00,0x02,0x24,0x0e,0x05,0x22,0x12,0x0b,0x00,0x02,0x24,
+0xfe,0x04,0x22,0x12,0x0c,0x00,0x02,0x24,0x5e,0x05,0x22,0x12,0x0d,0x00,0x02,0x24,
+0x4e,0x05,0x22,0x12,0x0e,0x00,0x02,0x24,0x3e,0x05,0x22,0x12,0x0f,0x00,0x02,0x24,
+0x2e,0x05,0x22,0x12,0x10,0x00,0x02,0x24,0x22,0xff,0x22,0x16,0xc0,0x02,0x82,0x36,
+0xc0,0x10,0x03,0x00,0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,
+0x80,0x10,0x02,0x00,0x21,0x10,0x53,0x00,0x4c,0x51,0x43,0x94,0x48,0x51,0x44,0x94,
+0x25,0xb0,0x06,0x3c,0x00,0x1c,0x03,0x00,0x21,0x20,0x83,0x00,0x00,0x00,0xc4,0xaf,
+0x58,0x51,0x45,0x8c,0x54,0x51,0x43,0x8c,0x50,0x51,0x44,0x94,0xc8,0x02,0xc6,0x34,
+0x21,0x18,0x65,0x00,0x00,0x1c,0x03,0x00,0x21,0x20,0x83,0x00,0xc0,0x02,0x82,0x36,
+0x00,0x00,0xc4,0xac,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x66,0x02,0x62,0x10,0x2b,0x10,0x43,0x00,0xbf,0x00,0x40,0x14,0x12,0x00,0x82,0x34,
+0x00,0xf1,0x04,0x3c,0x01,0x00,0x82,0x34,0xc1,0x02,0x62,0x10,0x2b,0x10,0x43,0x00,
+0xb7,0x01,0x40,0x14,0x02,0x00,0x82,0x34,0xe3,0xfe,0x64,0x14,0x00,0xf0,0x02,0x3c,
+0xff,0x00,0x04,0x3c,0x00,0xff,0x84,0x34,0x24,0x10,0x04,0x02,0x02,0x8a,0x02,0x00,
+0x80,0x1a,0x11,0x00,0x00,0xf4,0x63,0x24,0x94,0x00,0x82,0x36,0x00,0x00,0x51,0xa4,
+0x26,0xb0,0x04,0x3c,0x42,0x89,0x03,0x00,0x98,0x00,0x86,0x36,0xff,0x01,0x02,0x24,
+0x10,0x00,0x03,0x24,0x9a,0x00,0x85,0x36,0x00,0x00,0xa2,0xa4,0x7c,0x00,0x89,0x34,
+0x00,0x00,0xc3,0xa4,0x01,0x00,0x02,0x24,0x04,0x00,0x03,0x24,0x96,0x00,0x87,0x36,
+0x7a,0x00,0x84,0x34,0xb0,0x03,0x88,0x36,0x25,0xb0,0x06,0x3c,0x00,0x00,0xe2,0xa4,
+0x44,0x00,0xc6,0x34,0x00,0x00,0x83,0xa0,0x00,0x00,0x11,0xad,0x00,0x00,0x31,0xa5,
+0x00,0x00,0xc3,0x94,0xff,0xfd,0x02,0x24,0x24,0x18,0x62,0x00,0x00,0x00,0xc3,0xa4,
+0x00,0x00,0xc2,0x94,0x00,0x00,0x00,0x00,0x00,0x02,0x42,0x34,0x00,0x00,0xc2,0xa4,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x65,0x01,0x67,0x10,0x2b,0x10,0xe3,0x00,0xc5,0x00,0x40,0x14,0x02,0x00,0xe2,0x34,
+0x07,0x00,0xa2,0x34,0xfc,0x02,0x62,0x10,0x2b,0x10,0x62,0x00,0xa9,0x01,0x40,0x14,
+0x20,0x00,0xa2,0x34,0xb0,0xfe,0x62,0x14,0x00,0xf0,0x02,0x3c,0xff,0x00,0x03,0x3c,
+0x00,0xff,0x63,0x34,0x24,0x10,0x03,0x02,0x02,0x3a,0x02,0x00,0x80,0x04,0xe0,0x10,
+0x02,0x80,0x04,0x3c,0x05,0x00,0x02,0x24,0xc2,0xfe,0xe2,0x14,0xc0,0x02,0x82,0x36,
+0x02,0x80,0x06,0x3c,0x8f,0x7d,0xc2,0x90,0x00,0x00,0x00,0x00,0x00,0x00,0xc2,0xaf,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x2e,0x02,0x62,0x10,0x2b,0x10,0x43,0x00,0x98,0x00,0x40,0x14,0x0e,0x00,0xc2,0x34,
+0x01,0x00,0xc2,0x34,0xab,0x03,0x62,0x10,0x2b,0x10,0x43,0x00,0x48,0x01,0x40,0x14,
+0x00,0xff,0x02,0x3c,0x94,0xfe,0x66,0x14,0x00,0xf0,0x02,0x3c,0x5b,0x4e,0x00,0x0c,
+0x21,0x20,0x00,0x00,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x4c,0x02,0x62,0x10,0x2b,0x10,0x43,0x00,0xa6,0x00,0x40,0x14,
+0xa1,0x00,0xe2,0x34,0x22,0x00,0xe2,0x34,0xbd,0x02,0x62,0x10,0x2b,0x10,0x62,0x00,
+0x88,0x01,0x40,0x14,0x00,0x20,0x02,0x3c,0x28,0x00,0xe2,0x34,0x82,0xfe,0x62,0x14,
+0x00,0xf0,0x02,0x3c,0x0f,0x00,0x04,0x3c,0xff,0xff,0x85,0x34,0x60,0x00,0x06,0x24,
+0xba,0x44,0x00,0x0c,0x24,0x00,0x04,0x24,0x84,0x0a,0x00,0x0c,0xe8,0x03,0x04,0x24,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x0f,0x00,0x06,0x3c,0x24,0x00,0x04,0x24,0xdd,0x44,0x00,0x0c,0xff,0xff,0xc5,0x34,
+0x1f,0x00,0x51,0x30,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0xc0,0x02,0x82,0x36,0x00,0x00,0xd1,0xa3,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x18,0x02,0xc2,0x10,
+0x2b,0x10,0x46,0x00,0x01,0x01,0x40,0x14,0x00,0xa0,0x02,0x3c,0x00,0x60,0x02,0x3c,
+0x04,0x00,0xc2,0x10,0x80,0x10,0x08,0x00,0x7a,0xfe,0xc5,0x14,0xc0,0x02,0x82,0x36,
+0x80,0x10,0x08,0x00,0x21,0x10,0x48,0x00,0x21,0x10,0x53,0x00,0x21,0x10,0x49,0x00,
+0xc1,0x43,0x44,0xa0,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x3f,0x03,0x62,0x10,0x2b,0x10,0x62,0x00,0xb6,0x02,0x40,0x14,
+0xad,0x00,0xe2,0x34,0xc7,0x03,0x62,0x10,0xae,0x00,0xe2,0x34,0x4e,0xfe,0x62,0x14,
+0x00,0xf0,0x02,0x3c,0xff,0x00,0x02,0x3c,0x24,0x20,0x02,0x02,0x00,0xff,0x05,0x32,
+0x02,0x24,0x04,0x00,0x69,0x4f,0x00,0x0c,0x02,0x2a,0x05,0x00,0x00,0x00,0xc2,0xa3,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x4b,0x02,0x62,0x10,0x2b,0x10,0x62,0x00,0x17,0x01,0x40,0x14,0x03,0x00,0xa2,0x34,
+0x82,0x03,0x62,0x10,0x08,0x00,0xa2,0x34,0x3b,0xfe,0x62,0x14,0x00,0xf0,0x02,0x3c,
+0x00,0xff,0x02,0x32,0x02,0x82,0x02,0x00,0xcc,0x02,0x83,0x36,0x00,0x00,0x70,0xac,
+0x12,0x04,0x00,0x12,0x01,0x00,0x02,0x24,0x9c,0x04,0x02,0x12,0x00,0x00,0x00,0x00,
+0x7a,0x42,0x00,0x0c,0x21,0x20,0x00,0x00,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x4e,0x02,0x62,0x10,0x2b,0x10,0x62,0x00,
+0xe4,0x00,0x40,0x14,0x00,0xff,0x02,0x32,0x13,0x00,0x82,0x34,0x4c,0x03,0x62,0x10,
+0x14,0x00,0x82,0x34,0x24,0xfe,0x62,0x14,0x00,0xf0,0x02,0x3c,0xd3,0x0a,0x00,0x0c,
+0xfd,0x00,0x04,0x24,0x10,0x10,0x03,0x3c,0xa0,0x00,0x82,0x36,0x10,0x10,0x63,0x34,
+0x00,0xc0,0x07,0x3c,0x25,0xb0,0x06,0x3c,0x00,0x00,0x43,0xac,0xa4,0x00,0x84,0x36,
+0x00,0xa1,0xe7,0x34,0xa8,0x00,0xc6,0x34,0xc0,0x02,0x82,0x36,0x00,0x00,0x80,0xac,
+0x00,0x00,0xc7,0xac,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x60,0x02,0x62,0x10,0x2b,0x10,0x62,0x00,0xf6,0x00,0x40,0x14,0x03,0x00,0xa2,0x34,
+0x4b,0x03,0x62,0x10,0x04,0x00,0xa2,0x34,0x0b,0xfe,0x62,0x14,0x00,0xf0,0x02,0x3c,
+0xf4,0x63,0x62,0x92,0x00,0x00,0x00,0x00,0x00,0x00,0xc2,0xaf,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x61,0x02,0x62,0x10,
+0x2b,0x10,0x62,0x00,0xfe,0x00,0x40,0x14,0x01,0x00,0x02,0x24,0x0f,0x00,0xc2,0x34,
+0x63,0x03,0x62,0x10,0x10,0x00,0xc2,0x34,0xfb,0xfd,0x62,0x14,0x00,0xf0,0x02,0x3c,
+0x00,0xff,0x03,0x32,0x00,0xff,0x02,0x34,0x9d,0x03,0x62,0x10,0xc0,0x02,0x82,0x36,
+0x8c,0x65,0x60,0xae,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x47,0x02,0x62,0x10,0x2b,0x10,0x62,0x00,0x02,0x01,0x40,0x14,0x03,0x00,0xe2,0x34,
+0x8d,0x03,0x62,0x10,0x04,0x00,0xe2,0x34,0xeb,0xfd,0x62,0x14,0x00,0xf0,0x02,0x3c,
+0x1e,0x57,0x00,0x0c,0x00,0x00,0x00,0x00,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x9b,0x01,0x62,0x10,0x2b,0x10,0x43,0x00,
+0xcf,0x00,0x40,0x14,0xa2,0x00,0xe2,0x34,0xa0,0x00,0xe2,0x34,0xde,0xfd,0x62,0x14,
+0x00,0xf0,0x02,0x3c,0x00,0x0f,0x02,0x32,0x02,0x22,0x02,0x00,0x01,0x00,0x03,0x24,
+0x3c,0x04,0x83,0x10,0x02,0x00,0x02,0x24,0x34,0x04,0x82,0x10,0x03,0x00,0x02,0x24,
+0x46,0x03,0x82,0x10,0x00,0x00,0x00,0x00,0xde,0x4f,0x00,0x0c,0x21,0x20,0x00,0x00,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x46,0x02,0x62,0x10,0x2b,0x10,0x62,0x00,0xe6,0xfd,0x40,0x14,0xc0,0x02,0x82,0x36,
+0x18,0x00,0xe2,0x34,0x45,0x03,0x62,0x10,0x19,0x00,0xe2,0x34,0xc6,0xfd,0x62,0x14,
+0x00,0xf0,0x02,0x3c,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x94,0x0e,0x83,0x36,
+0x9c,0x0e,0x82,0x36,0xa4,0x0e,0x84,0x36,0xac,0x0e,0x87,0x36,0x00,0x00,0x65,0x8c,
+0x00,0x00,0x48,0x8c,0x00,0x00,0x8a,0x8c,0x00,0x00,0xe6,0x8c,0x02,0x80,0x07,0x3c,
+0x68,0x15,0xed,0x24,0xb4,0x0e,0x82,0x36,0x00,0x00,0x47,0x8c,0x0c,0x40,0xa3,0x8d,
+0xff,0x03,0x02,0x3c,0x10,0x40,0xa4,0x8d,0x24,0x28,0xa2,0x00,0x24,0x30,0xc2,0x00,
+0xbc,0x0e,0x82,0x36,0x00,0x00,0x4b,0x8c,0x00,0xfc,0x02,0x24,0x02,0x2c,0x05,0x00,
+0x24,0x18,0x62,0x00,0x02,0x34,0x06,0x00,0x24,0x20,0x82,0x00,0xc4,0x0e,0x82,0x36,
+0x25,0x18,0x65,0x00,0x25,0x20,0x86,0x00,0x00,0x00,0x45,0x8c,0xff,0x03,0x06,0x3c,
+0xf0,0xff,0x02,0x3c,0xff,0x03,0x42,0x34,0x24,0x38,0xe6,0x00,0x82,0x39,0x07,0x00,
+0x24,0x20,0x82,0x00,0x24,0x40,0x06,0x01,0x08,0x40,0xa9,0x8d,0x25,0x20,0x87,0x00,
+0xcc,0x0e,0x8c,0x36,0xff,0x03,0x07,0x3c,0x00,0x00,0x86,0x8d,0x24,0x18,0x62,0x00,
+0x24,0x50,0x47,0x01,0x24,0x58,0x67,0x01,0x82,0x41,0x08,0x00,0xff,0x9f,0x02,0x3c,
+0x0f,0xc0,0x07,0x3c,0xff,0xff,0xe7,0x34,0xff,0xff,0x42,0x34,0x25,0x18,0x68,0x00,
+0x24,0x48,0x22,0x01,0x24,0x18,0x67,0x00,0xff,0x03,0x02,0x3c,0x24,0x20,0x87,0x00,
+0xff,0x00,0x07,0x3c,0x24,0x28,0xa2,0x00,0x24,0x30,0xc2,0x00,0x00,0x51,0x0a,0x00,
+0x00,0x20,0x02,0x3c,0x00,0x59,0x0b,0x00,0x00,0xff,0xe7,0x34,0x25,0x48,0x22,0x01,
+0x25,0x18,0x6a,0x00,0x25,0x20,0x8b,0x00,0x02,0x2c,0x05,0x00,0x02,0x34,0x06,0x00,
+0x24,0x10,0x07,0x02,0x08,0x40,0xa9,0xad,0x0c,0x40,0xa3,0xad,0x10,0x40,0xa4,0xad,
+0x14,0x40,0xa5,0xa5,0x4e,0x03,0x40,0x10,0x16,0x40,0xa6,0xa5,0xff,0x00,0x02,0x3c,
+0x24,0x10,0x02,0x02,0x02,0x14,0x02,0x00,0x02,0x1a,0x10,0x00,0xc7,0x42,0xa2,0xa1,
+0xc3,0x42,0xa3,0xa1,0xc3,0x42,0x62,0x92,0x25,0xb0,0x03,0x3c,0x61,0x0c,0x63,0x34,
+0x10,0x00,0xa4,0x27,0x00,0x00,0x62,0xa0,0x7a,0x54,0x00,0x0c,0x00,0x00,0x00,0x00,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x95,0x00,0xc2,0x10,0x00,0x40,0x02,0x3c,0x09,0xff,0xc2,0x10,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x7b,0x02,0xc2,0x10,
+0x2b,0x10,0x46,0x00,0x83,0x00,0x40,0x14,0x00,0xb0,0x02,0x3c,0x00,0x90,0x02,0x3c,
+0x78,0xfd,0xc2,0x14,0xc0,0x02,0x82,0x36,0x21,0x10,0x13,0x01,0x73,0x44,0x44,0xa0,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x55,0xfd,0x62,0x14,0x00,0xf0,0x02,0x3c,0x6a,0x56,0x00,0x0c,0x21,0x20,0x00,0x02,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x07,0x00,0x42,0x34,0x4c,0xfd,0x62,0x14,0x00,0xf0,0x02,0x3c,0x5b,0x4e,0x00,0x0c,
+0x07,0x00,0x04,0x24,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x02,0x1a,0x02,0x00,0x21,0x88,0x00,0x00,0xaf,0x4a,0x00,0x08,
+0x27,0xb0,0x06,0x3c,0x01,0x00,0x31,0x26,0x00,0x01,0x22,0x2e,0x08,0x00,0x40,0x10,
+0xff,0x00,0x22,0x2e,0x00,0x00,0xc2,0x94,0x00,0x00,0x00,0x00,0xff,0x00,0x42,0x30,
+0xf8,0xff,0x43,0x14,0x08,0x00,0xc6,0x24,0x00,0x00,0xd1,0xa7,0xff,0x00,0x22,0x2e,
+0x50,0xfd,0x40,0x14,0xc0,0x02,0x82,0x36,0x12,0x87,0x02,0x3c,0x00,0x00,0xc2,0xaf,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x2d,0xfd,0x62,0x14,0x00,0xf0,0x02,0x3c,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xff,0x00,0x03,0x3c,0x00,0xff,0x63,0x34,
+0x24,0x10,0x03,0x02,0x02,0x82,0x02,0x00,0xcc,0x02,0x83,0x36,0x00,0x00,0x70,0xac,
+0x00,0x00,0xd1,0x8f,0x21,0x10,0x14,0x02,0x00,0x00,0x51,0xac,0x00,0x00,0x51,0x8c,
+0xc0,0x02,0x82,0x36,0x00,0x00,0xd1,0xaf,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x00,0x64,0x62,0x92,0x00,0x00,0x00,0x00,0x00,0x00,0xc2,0xaf,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0xf4,0x02,0x62,0x10,0xa3,0x00,0xe2,0x34,0x0f,0xfd,0x62,0x14,0x00,0xf0,0x02,0x3c,
+0xc0,0x02,0x82,0x36,0x8c,0x65,0x60,0xae,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xec,0x63,0x62,0x92,0x00,0x00,0x00,0x00,0x00,0x00,0xc2,0xaf,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0xe6,0x63,0x62,0xa6,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x08,0x40,0x63,0x8e,0xff,0x9f,0x07,0x3c,0xff,0xff,0xe7,0x34,
+0x02,0x2c,0x10,0x00,0x00,0x1f,0x04,0x32,0x24,0x18,0x67,0x00,0x25,0x18,0x62,0x00,
+0x02,0x8a,0x04,0x00,0x3f,0x00,0xa5,0x30,0xc0,0x02,0x82,0x36,0x08,0x40,0x63,0xae,
+0xbc,0x42,0x71,0xa2,0xc1,0x42,0x65,0xa2,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x00,0x00,0xe2,0x92,0x00,0x00,0x00,0x00,0xfa,0x00,0x42,0x30,
+0x00,0x00,0xe2,0xa2,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x00,0x00,0xe2,0x92,0x00,0x00,0x00,0x00,0xfd,0x00,0x42,0x30,
+0x00,0x00,0xe2,0xa2,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xf7,0xfc,0xc2,0x14,0xc0,0x02,0x82,0x36,0x80,0x10,0x08,0x00,
+0x21,0x10,0x53,0x00,0x60,0x45,0x43,0xac,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x80,0x10,0x08,0x00,0x21,0x10,0x48,0x00,
+0x21,0x10,0x53,0x00,0x21,0x10,0x49,0x00,0x34,0x43,0x44,0xa0,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x77,0x56,0x00,0x0c,
+0x21,0x20,0x00,0x02,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xff,0xff,0x02,0x34,0x8c,0x65,0x62,0xae,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x07,0x0b,0x00,0x0c,
+0x00,0x00,0x00,0x00,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xf0,0x63,0x62,0x92,0x00,0x00,0x00,0x00,0x00,0x00,0xc2,0xaf,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x08,0x40,0x62,0x8e,0xff,0x9f,0x03,0x3c,0xff,0xff,0x63,0x34,0x24,0x10,0x43,0x00,
+0x08,0x40,0x62,0xae,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,
+0x00,0x60,0x81,0x40,0x22,0x51,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xff,0x00,0x07,0x3c,0x00,0xff,0xe7,0x34,
+0x24,0x10,0x07,0x02,0x02,0x82,0x02,0x00,0xcc,0x02,0x43,0x36,0x00,0x00,0x70,0xac,
+0x21,0x10,0x12,0x02,0x00,0x00,0x51,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0xd1,0xaf,
+0x00,0x00,0x51,0x8c,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xb7,0x4f,0x00,0x0c,0x00,0x00,0x00,0x00,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x21,0x88,0x00,0x00,
+0x6c,0x4b,0x00,0x08,0x27,0xb0,0x04,0x3c,0x01,0x00,0x31,0x26,0x00,0x01,0x22,0x2e,
+0x0a,0x00,0x40,0x10,0xff,0x00,0x22,0x2e,0x00,0x00,0x83,0x94,0x00,0x00,0x00,0x00,
+0xff,0xff,0x67,0x30,0xff,0x00,0xe2,0x30,0xf0,0x00,0x42,0x28,0xf6,0xff,0x40,0x14,
+0x08,0x00,0x84,0x24,0x00,0x00,0xc7,0xa7,0xff,0x00,0x22,0x2e,0x91,0xfc,0x40,0x14,
+0xc0,0x02,0x82,0x36,0x12,0x87,0x02,0x3c,0x00,0x00,0xc2,0xaf,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xe4,0x63,0x62,0x96,
+0x00,0x00,0x00,0x00,0x00,0x00,0xc2,0xa7,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x04,0x64,0x62,0x92,0x00,0x00,0x00,0x00,
+0x00,0x00,0xc2,0xaf,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x00,0xff,0x02,0x32,0x02,0x12,0x02,0x00,0x03,0x00,0x43,0x2c,
+0x02,0x00,0x60,0x10,0x00,0x00,0x00,0x00,0x02,0x40,0x62,0xa2,0x02,0x40,0x63,0x92,
+0x90,0x0c,0x42,0x36,0x00,0x00,0x43,0xa0,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xd7,0x56,0x00,0x0c,0x00,0x00,0x00,0x00,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x21,0x10,0x13,0x01,0x56,0x44,0x44,0xa0,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xff,0x00,0x03,0x3c,0x24,0x20,0x03,0x02,
+0x73,0x0e,0x00,0x0c,0x02,0x24,0x04,0x00,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x02,0x1c,0x10,0x00,0x00,0x1f,0x02,0x32,
+0x02,0x8a,0x02,0x00,0x3f,0x00,0x65,0x30,0xc1,0x42,0x65,0xa2,0xbc,0x42,0x71,0xa2,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x1f,0x12,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0xc2,0xaf,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0x03,0x40,0x62,0x92,0x0e,0x0c,0x44,0x36,
+0x01,0x00,0x42,0x24,0xff,0x00,0x43,0x30,0x00,0x00,0x83,0xa0,0x03,0x40,0x62,0xa2,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x00,0xff,0x02,0x32,0x02,0x3a,0x02,0x00,0x1a,0x01,0xe0,0x10,0x4f,0x00,0x82,0x36,
+0x94,0x00,0x42,0x36,0x00,0x00,0x43,0x94,0xff,0xff,0xe2,0x24,0xb0,0x03,0x45,0x36,
+0xff,0xff,0x71,0x30,0x1b,0x00,0x27,0x02,0x02,0x00,0xe0,0x14,0x00,0x00,0x00,0x00,
+0x0d,0x00,0x07,0x00,0xff,0xff,0x47,0x30,0x00,0x00,0xb1,0xac,0x80,0xff,0x02,0x24,
+0x00,0x19,0x07,0x00,0x25,0x18,0x62,0x00,0x4f,0x00,0x44,0x36,0x9e,0x00,0x46,0x36,
+0x00,0x00,0xa7,0xac,0x00,0x00,0x83,0xa0,0x25,0xb0,0x04,0x3c,0x44,0x00,0x84,0x34,
+0x12,0x88,0x00,0x00,0x80,0x12,0x11,0x00,0x00,0xfc,0x42,0x24,0x00,0x00,0xb1,0xac,
+0x00,0x00,0xd1,0xa4,0x42,0x89,0x02,0x00,0x26,0xb0,0x02,0x3c,0x7c,0x00,0x42,0x34,
+0x00,0x00,0xb1,0xac,0x00,0x00,0x51,0xa4,0x25,0xb0,0x02,0x3c,0x44,0x00,0x42,0x34,
+0x00,0x00,0x43,0x94,0xff,0xfd,0x02,0x24,0x24,0x18,0x62,0x00,0x00,0x00,0x83,0xa4,
+0x00,0x00,0x82,0x94,0x00,0x00,0x00,0x00,0x00,0x02,0x42,0x34,0x00,0x00,0x82,0xa4,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x24,0x10,0x08,0x02,0xcc,0x02,0x43,0x36,0x00,0xff,0x04,0x32,0x02,0x3c,0x02,0x00,
+0x00,0x00,0x70,0xac,0x04,0x00,0xe0,0x10,0x02,0x82,0x04,0x00,0x01,0x00,0x02,0x24,
+0x02,0x00,0xe2,0x10,0x01,0x00,0x04,0x24,0x21,0x20,0x00,0x00,0x7a,0x42,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x0f,0x00,0x06,0x3c,0x21,0x20,0x00,0x02,0xdd,0x44,0x00,0x0c,
+0xff,0xff,0xc5,0x34,0x0f,0x00,0x07,0x3c,0xff,0xff,0xe7,0x34,0x24,0x88,0x47,0x00,
+0xc0,0x02,0x82,0x36,0x00,0x00,0xd1,0xaf,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x28,0xb0,0x02,0x3c,0x00,0x00,0x43,0x90,0xff,0x00,0x02,0x24,
+0xff,0x00,0x70,0x30,0xf3,0xfb,0x02,0x12,0xc0,0x02,0x82,0x36,0x28,0xb0,0x05,0x3c,
+0xff,0x00,0x04,0x24,0xc0,0x10,0x10,0x00,0x21,0x10,0x45,0x00,0x00,0x00,0x43,0x90,
+0x00,0x00,0x00,0x00,0xff,0x00,0x70,0x30,0xfb,0xff,0x04,0x16,0xc0,0x10,0x10,0x00,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x00,0x1f,0x02,0x32,0x02,0x1c,0x10,0x00,0x02,0x8a,0x02,0x00,0x3f,0x00,0x65,0x30,
+0xc0,0x02,0x82,0x36,0xbc,0x42,0x71,0xa2,0xc1,0x42,0x65,0xa2,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xff,0x00,0x07,0x3c,0x24,0x20,0x07,0x02,
+0x15,0x51,0x00,0x0c,0x02,0x24,0x04,0x00,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xe8,0x63,0x62,0x92,0x00,0x00,0x00,0x00,
+0x00,0x00,0xc2,0xaf,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xfc,0x63,0x62,0x92,0x00,0x00,0x00,0x00,0x00,0x00,0xc2,0xaf,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x00,0x00,0xe2,0x92,0x00,0x00,0x00,0x00,0xff,0x00,0x51,0x30,0x05,0x00,0x23,0x36,
+0xc0,0x02,0x82,0x36,0x00,0x00,0xe3,0xa2,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xc0,0x02,0x82,0x36,0xe6,0x63,0x60,0xa6,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xbd,0x56,0x00,0x0c,0x21,0x20,0x00,0x02,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x41,0x0b,0x00,0x0c,0x00,0x00,0x00,0x00,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0xe2,0x92,0x00,0x00,0x00,0x00,
+0xff,0x00,0x51,0x30,0x02,0x00,0x23,0x36,0xc0,0x02,0x82,0x36,0x00,0x00,0xe3,0xa2,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x02,0x80,0x02,0x3c,
+0xec,0x91,0x42,0x24,0x00,0x00,0x47,0x8c,0xc0,0x02,0x43,0x36,0x25,0xb0,0x0c,0x3c,
+0x08,0x40,0xe4,0x8c,0x00,0x00,0x60,0xac,0x42,0x17,0x04,0x00,0x03,0x00,0x42,0x30,
+0x60,0x00,0x40,0x14,0x03,0x0d,0x42,0x36,0x00,0x00,0x45,0x90,0x10,0x40,0xe6,0x8c,
+0xff,0x9f,0x03,0x3c,0xff,0xff,0x63,0x34,0xff,0x3f,0x02,0x3c,0x24,0x20,0x83,0x00,
+0xff,0xff,0x42,0x34,0x00,0x20,0x03,0x3c,0x24,0x58,0xc2,0x00,0x25,0x20,0x83,0x00,
+0x00,0x40,0x02,0x3c,0x70,0x00,0xa5,0x30,0x25,0x58,0x62,0x01,0x08,0x01,0xa0,0x10,
+0x08,0x40,0xe4,0xac,0x94,0x0e,0x82,0x35,0x9c,0x0e,0x83,0x35,0xa4,0x0e,0x86,0x35,
+0x00,0x00,0x45,0x8c,0xac,0x0e,0x87,0x35,0x00,0x00,0x68,0x8c,0x00,0x00,0xca,0x8c,
+0x02,0x80,0x06,0x3c,0x00,0x00,0xe4,0x8c,0x68,0x15,0xc6,0x24,0x0c,0x40,0xc3,0x8c,
+0xb4,0x0e,0x82,0x35,0x00,0x00,0x47,0x8c,0xff,0x03,0x02,0x3c,0x00,0xfc,0x06,0x24,
+0x24,0x28,0xa2,0x00,0x24,0x20,0x82,0x00,0xbc,0x0e,0x82,0x35,0x00,0x00,0x49,0x8c,
+0x02,0x2c,0x05,0x00,0x24,0x10,0x66,0x01,0x24,0x18,0x66,0x00,0x02,0x24,0x04,0x00,
+0xc4,0x0e,0x86,0x35,0x25,0x18,0x65,0x00,0x25,0x10,0x44,0x00,0x00,0x00,0xc5,0x8c,
+0xff,0x03,0x04,0x3c,0xf0,0xff,0x06,0x3c,0xff,0x03,0xc6,0x34,0x24,0x38,0xe4,0x00,
+0xcc,0x0e,0x8b,0x35,0x24,0x40,0x04,0x01,0x82,0x39,0x07,0x00,0x00,0x00,0x64,0x8d,
+0x24,0x10,0x46,0x00,0x24,0x18,0x66,0x00,0x25,0x10,0x47,0x00,0x82,0x41,0x08,0x00,
+0xff,0x03,0x07,0x3c,0x0f,0xc0,0x06,0x3c,0x24,0x50,0x47,0x01,0x24,0x48,0x27,0x01,
+0xff,0xff,0xc6,0x34,0x25,0x18,0x68,0x00,0x24,0x28,0xa7,0x00,0x24,0x20,0x87,0x00,
+0x00,0x51,0x0a,0x00,0x24,0x18,0x66,0x00,0x00,0x49,0x09,0x00,0x24,0x10,0x46,0x00,
+0x02,0x80,0x07,0x3c,0x68,0x15,0xe7,0x24,0x25,0x18,0x6a,0x00,0x25,0x10,0x49,0x00,
+0x02,0x2c,0x05,0x00,0x02,0x24,0x04,0x00,0x0c,0x40,0xe3,0xac,0x10,0x40,0xe2,0xac,
+0x14,0x40,0xe5,0xa4,0x16,0x40,0xe4,0xa4,0x02,0x80,0x02,0x3c,0x68,0x15,0x43,0x24,
+0x0c,0x40,0x62,0x8c,0x00,0x00,0x00,0x00,0xbd,0x00,0x40,0x04,0x00,0x00,0x00,0x00,
+0x00,0xff,0x02,0x32,0xc6,0x00,0x40,0x10,0x00,0x00,0x00,0x00,0x02,0x12,0x02,0x00,
+0xc3,0x42,0x62,0xa0,0x7a,0x54,0x00,0x0c,0x10,0x00,0xa4,0x27,0xc2,0x53,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x0c,0x40,0x62,0x8e,0x00,0x80,0x03,0x3c,0x25,0x10,0x43,0x00,
+0x0c,0x40,0x62,0xae,0xc3,0x42,0x62,0x92,0x25,0xb0,0x03,0x3c,0x61,0x0c,0x63,0x34,
+0x00,0x00,0x62,0xa0,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xcf,0x4e,0x00,0x0c,0x21,0x20,0x00,0x02,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x17,0x51,0x00,0x0c,
+0x00,0x00,0x00,0x00,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x9e,0x00,0x83,0x36,0x00,0x00,0x40,0xa0,0x00,0x00,0x60,0xa4,
+0x94,0x00,0x82,0x36,0x00,0x00,0x43,0x94,0x25,0xb0,0x06,0x3c,0x44,0x00,0xc6,0x34,
+0xff,0xff,0x71,0x30,0x80,0x12,0x11,0x00,0x00,0xf8,0x42,0x24,0x42,0x89,0x02,0x00,
+0x26,0xb0,0x02,0x3c,0xb0,0x03,0x83,0x36,0x7c,0x00,0x42,0x34,0x00,0x00,0x71,0xac,
+0x00,0x00,0x51,0xa4,0x00,0x00,0xc3,0x94,0xff,0xfd,0x02,0x24,0x24,0x18,0x62,0x00,
+0x00,0x00,0xc3,0xa4,0x00,0x00,0xc2,0x94,0x00,0x00,0x00,0x00,0x00,0x02,0x42,0x34,
+0x00,0x00,0xc2,0xa4,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x5b,0x4e,0x00,0x0c,0x01,0x00,0x04,0x24,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x80,0x10,0x08,0x00,
+0x21,0x10,0x53,0x00,0xec,0x44,0x43,0xac,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xa7,0x0b,0x00,0x0c,0x00,0x00,0x00,0x00,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x28,0xb0,0x11,0x3c,0x00,0x00,0x22,0x96,0xff,0x00,0x04,0x3c,0x24,0x18,0x04,0x02,
+0x02,0x24,0x03,0x00,0xff,0x00,0x42,0x30,0x0a,0x00,0x82,0x10,0xff,0x7f,0x02,0x3c,
+0x08,0x00,0x31,0x26,0x00,0x00,0x22,0x96,0xff,0xff,0x23,0x32,0xff,0x00,0x42,0x30,
+0x03,0x00,0x82,0x10,0x00,0x08,0x63,0x2c,0xf9,0xff,0x60,0x14,0x00,0x00,0x00,0x00,
+0xff,0x7f,0x02,0x3c,0xff,0xff,0x42,0x34,0x24,0x10,0x22,0x02,0x00,0x00,0xc2,0xaf,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0xf8,0x63,0x62,0x92,0x00,0x00,0x00,0x00,0x00,0x00,0xc2,0xaf,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xff,0x00,0x03,0x3c,
+0x24,0x10,0x03,0x02,0x00,0xff,0x04,0x32,0xcc,0x02,0x83,0x36,0x02,0x3c,0x02,0x00,
+0x00,0x00,0x70,0xac,0x04,0x00,0xe0,0x10,0x02,0x82,0x04,0x00,0x01,0x00,0x02,0x24,
+0x02,0x00,0xe2,0x10,0x01,0x00,0x04,0x24,0x21,0x20,0x00,0x00,0x7a,0x42,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x00,0x00,0xd1,0x8f,0x0f,0x00,0x06,0x3c,0xff,0xff,0xc5,0x34,
+0x21,0x20,0x00,0x02,0xba,0x44,0x00,0x0c,0x21,0x30,0x20,0x02,0x0f,0x00,0x07,0x3c,
+0x21,0x20,0x00,0x02,0xdd,0x44,0x00,0x0c,0xff,0xff,0xe5,0x34,0x00,0x00,0xc2,0xaf,
+0x21,0x88,0x40,0x00,0x25,0xb0,0x02,0x3c,0xc8,0x02,0x42,0x34,0x00,0x00,0x51,0xac,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x25,0xb0,0x06,0x3c,0xff,0x00,0x02,0x24,0x56,0x01,0xc6,0x34,0x00,0x00,0xc2,0xa4,
+0x01,0x00,0x03,0x24,0x02,0x80,0x07,0x3c,0xc0,0x02,0x82,0x36,0xb8,0x7d,0xe3,0xa0,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xde,0x4f,0x00,0x0c,
+0x03,0x00,0x04,0x24,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xde,0x4e,0x00,0x0c,0x21,0x20,0x00,0x02,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x08,0x40,0x62,0x8e,
+0xff,0x9f,0x04,0x3c,0xff,0xff,0x84,0x34,0x24,0x10,0x44,0x00,0x08,0x40,0x62,0xae,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0xc0,0x10,0x03,0x00,0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,
+0x80,0x10,0x02,0x00,0x21,0x10,0x53,0x00,0x70,0x51,0x43,0x8c,0xc0,0x02,0x82,0x36,
+0x00,0x00,0xc3,0xaf,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x7a,0x54,0x00,0x0c,0x10,0x00,0xa4,0x27,0xc3,0x42,0x62,0x92,0x25,0xb0,0x03,0x3c,
+0x61,0x0c,0x63,0x34,0x00,0x00,0x62,0xa0,0xd4,0x4c,0x00,0x08,0xc0,0x02,0x82,0x36,
+0x22,0x51,0x00,0x0c,0x10,0x40,0xeb,0xac,0xbd,0x4c,0x00,0x08,0x02,0x80,0x02,0x3c,
+0xc6,0x4c,0x00,0x08,0x12,0x00,0x02,0x24,0x1a,0x57,0x00,0x0c,0x00,0x00,0x00,0x00,
+0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0xff,0xff,0x02,0x34,0x8c,0x65,0x62,0xae,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xc0,0x10,0x03,0x00,0x21,0x10,0x43,0x00,
+0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x53,0x00,
+0x74,0x51,0x43,0x8c,0xc0,0x02,0x82,0x36,0x00,0x00,0xc3,0xaf,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xc0,0x10,0x03,0x00,0x21,0x10,0x43,0x00,
+0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x53,0x00,
+0xd4,0x51,0x43,0x8c,0xc0,0x02,0x82,0x36,0x00,0x00,0xc3,0xaf,0x00,0x00,0x40,0xac,
+0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xc0,0x10,0x03,0x00,0x21,0x10,0x43,0x00,
+0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,0x02,0x80,0x06,0x3c,0x80,0x10,0x02,0x00,
+0xe0,0x66,0xc3,0x24,0x21,0x10,0x43,0x00,0x00,0x00,0x44,0x8c,0xc0,0x02,0x82,0x36,
+0x00,0x00,0xc4,0xaf,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,
+0x12,0x00,0x02,0x24,0xc7,0x42,0xa2,0xa1,0x77,0x4a,0x00,0x08,0xc3,0x42,0xa2,0xa1,
+0x88,0x7d,0x82,0x94,0x00,0x00,0x00,0x00,0x00,0x00,0xc2,0xaf,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x7a,0x42,0x00,0x0c,
+0x21,0x20,0x00,0x00,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xff,0x00,0x06,0x3c,0x00,0xff,0xc6,0x34,0x00,0x00,0xc5,0x8f,
+0x24,0x20,0x06,0x02,0xe1,0x50,0x00,0x0c,0x02,0x22,0x04,0x00,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xc0,0x10,0x03,0x00,
+0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,0x02,0x80,0x07,0x3c,
+0x80,0x10,0x02,0x00,0xf0,0x66,0xe3,0x24,0x21,0x10,0x43,0x00,0x00,0x00,0x44,0x8c,
+0xc0,0x02,0x82,0x36,0x00,0x00,0xc4,0xaf,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xc0,0x10,0x03,0x00,0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,
+0x21,0x10,0x43,0x00,0x02,0x80,0x06,0x3c,0x80,0x10,0x02,0x00,0xec,0x66,0xc3,0x24,
+0x21,0x10,0x43,0x00,0x00,0x00,0x44,0x8c,0xc0,0x02,0x82,0x36,0x00,0x00,0xc4,0xaf,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xc0,0x10,0x03,0x00,
+0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,0x02,0x80,0x04,0x3c,
+0xe8,0x66,0x83,0x24,0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,0x00,0x00,0x44,0x8c,
+0xc0,0x02,0x82,0x36,0x00,0x00,0xc4,0xaf,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xc0,0x10,0x03,0x00,0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,
+0x21,0x10,0x43,0x00,0x02,0x80,0x07,0x3c,0x80,0x10,0x02,0x00,0xe4,0x66,0xe3,0x24,
+0x21,0x10,0x43,0x00,0x00,0x00,0x44,0x8c,0xc0,0x02,0x82,0x36,0x00,0x00,0xc4,0xaf,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xc0,0x10,0x03,0x00,
+0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,0x02,0x80,0x04,0x3c,
+0x00,0x67,0x83,0x24,0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,0x00,0x00,0x44,0x8c,
+0xc0,0x02,0x82,0x36,0x00,0x00,0xc4,0xaf,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xc0,0x10,0x03,0x00,0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,
+0x21,0x10,0x43,0x00,0x02,0x80,0x07,0x3c,0x80,0x10,0x02,0x00,0xfc,0x66,0xe3,0x24,
+0x21,0x10,0x43,0x00,0x00,0x00,0x44,0x8c,0xc0,0x02,0x82,0x36,0x00,0x00,0xc4,0xaf,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xc0,0x10,0x03,0x00,
+0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,0x02,0x80,0x06,0x3c,
+0x80,0x10,0x02,0x00,0xf8,0x66,0xc3,0x24,0x21,0x10,0x43,0x00,0x00,0x00,0x44,0x8c,
+0xc0,0x02,0x82,0x36,0x00,0x00,0xc4,0xaf,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xc0,0x10,0x03,0x00,0x21,0x10,0x43,0x00,0x80,0x10,0x02,0x00,
+0x21,0x10,0x43,0x00,0x02,0x80,0x04,0x3c,0xf4,0x66,0x83,0x24,0x80,0x10,0x02,0x00,
+0x21,0x10,0x43,0x00,0x00,0x00,0x44,0x8c,0xc0,0x02,0x82,0x36,0x00,0x00,0xc4,0xaf,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0xde,0x4f,0x00,0x0c,
+0x02,0x00,0x04,0x24,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0xde,0x4f,0x00,0x0c,0x01,0x00,0x04,0x24,0xc0,0x02,0x82,0x36,
+0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,0x00,0x00,0x00,0x00,0x7a,0x42,0x00,0x0c,
+0x01,0x00,0x04,0x24,0xc0,0x02,0x82,0x36,0x00,0x00,0x40,0xac,0x08,0x48,0x00,0x08,
+0x00,0x00,0x00,0x00,0x25,0xb0,0x05,0x3c,0x01,0x00,0x06,0x24,0x01,0x80,0x02,0x3c,
+0x04,0x30,0x86,0x00,0xf1,0x02,0xa7,0x34,0xed,0x02,0xa4,0x34,0x6c,0x39,0x42,0x24,
+0x18,0x03,0xa5,0x34,0x08,0x00,0x03,0x24,0x00,0x00,0xa2,0xac,0x00,0x00,0xe3,0xa0,
+0x00,0x00,0x80,0xa0,0x00,0x00,0x86,0xa0,0x00,0x00,0x80,0xa0,0x00,0x00,0x86,0xa0,
+0x00,0x00,0x80,0xa0,0x00,0x00,0x86,0xa0,0x00,0x00,0x80,0xa0,0x00,0x00,0x86,0xa0,
+0x00,0x00,0x80,0xa0,0x00,0x00,0xe0,0xa0,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x01,0x80,0x02,0x3c,0x25,0xb0,0x03,0x3c,0xc8,0x39,0x42,0x24,0x18,0x03,0x63,0x34,
+0x00,0x00,0x62,0xac,0x00,0x00,0x83,0x90,0x30,0x00,0x02,0x24,0x05,0x00,0x62,0x10,
+0x21,0x20,0x00,0x00,0x31,0x00,0x02,0x24,0x02,0x00,0x62,0x10,0x01,0x00,0x04,0x24,
+0x07,0x00,0x04,0x24,0x5b,0x4e,0x00,0x08,0x00,0x00,0x00,0x00,0x01,0x80,0x02,0x3c,
+0x25,0xb0,0x03,0x3c,0x04,0x3a,0x42,0x24,0x18,0x03,0x63,0x34,0x02,0x80,0x04,0x3c,
+0x00,0x00,0x62,0xac,0x08,0x00,0xe0,0x03,0xc4,0x7d,0x80,0xac,0x02,0x80,0x02,0x3c,
+0x08,0x7b,0x42,0x24,0xc0,0x20,0x04,0x00,0x21,0x20,0x82,0x00,0x21,0x28,0x00,0x00,
+0x00,0x60,0x06,0x40,0x01,0x00,0xc1,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,
+0x00,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,0x09,0x00,0x44,0x10,0x00,0x00,0x00,0x00,
+0x04,0x00,0x43,0x8c,0x21,0x28,0x40,0x00,0x00,0x00,0x42,0x8c,0x00,0x00,0x00,0x00,
+0x00,0x00,0x62,0xac,0x04,0x00,0x43,0xac,0x00,0x00,0xa5,0xac,0x04,0x00,0xa5,0xac,
+0x00,0x60,0x86,0x40,0x08,0x00,0xe0,0x03,0x21,0x10,0xa0,0x00,0x21,0x18,0x80,0x00,
+0xe8,0xff,0xbd,0x27,0x01,0x01,0x62,0x2c,0x10,0x00,0xbf,0xaf,0x01,0x00,0x04,0x24,
+0x01,0x02,0x65,0x2c,0x0a,0x00,0x40,0x14,0x21,0x30,0x00,0x00,0x02,0x00,0x04,0x24,
+0x07,0x00,0xa0,0x14,0x01,0x08,0x62,0x2c,0x05,0x00,0x40,0x14,0x03,0x00,0x04,0x24,
+0x10,0x00,0xbf,0x8f,0x21,0x10,0xc0,0x00,0x08,0x00,0xe0,0x03,0x18,0x00,0xbd,0x27,
+0x89,0x4e,0x00,0x0c,0x00,0x00,0x00,0x00,0x10,0x00,0xbf,0x8f,0x21,0x30,0x40,0x00,
+0x21,0x10,0xc0,0x00,0x08,0x00,0xe0,0x03,0x18,0x00,0xbd,0x27,0x02,0x80,0x03,0x3c,
+0x20,0x7b,0x62,0x8c,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x00,0x60,0x06,0x40,
+0x01,0x00,0xc1,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x10,0x00,0x83,0x8c,
+0x02,0x80,0x02,0x3c,0x08,0x7b,0x42,0x24,0xc0,0x18,0x03,0x00,0x21,0x18,0x62,0x00,
+0x00,0x00,0x65,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0x85,0xac,0x04,0x00,0xa4,0xac,
+0x00,0x00,0x64,0xac,0x04,0x00,0x83,0xac,0x00,0x60,0x86,0x40,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x02,0x24,0x04,0x00,0xff,0x00,0x84,0x30,0xc0,0x18,0x04,0x00,
+0x21,0x18,0x64,0x00,0x80,0x18,0x03,0x00,0x21,0x18,0x64,0x00,0x02,0x80,0x02,0x3c,
+0x68,0x15,0x42,0x24,0x80,0x18,0x03,0x00,0x21,0x18,0x62,0x00,0x78,0x51,0x64,0x8c,
+0xff,0xf1,0x02,0x24,0x24,0x20,0x82,0x00,0x08,0x00,0xe0,0x03,0x78,0x51,0x64,0xac,
+0x02,0x24,0x04,0x00,0xff,0x00,0x84,0x30,0xc0,0x18,0x04,0x00,0x21,0x18,0x64,0x00,
+0x80,0x18,0x03,0x00,0x21,0x18,0x64,0x00,0x02,0x80,0x02,0x3c,0x68,0x15,0x42,0x24,
+0x80,0x18,0x03,0x00,0x21,0x18,0x62,0x00,0x78,0x51,0x64,0x8c,0xff,0xf1,0x02,0x24,
+0x24,0x20,0x82,0x00,0x00,0x02,0x84,0x34,0x08,0x00,0xe0,0x03,0x78,0x51,0x64,0xac,
+0xe0,0xff,0xbd,0x27,0x10,0x00,0xb0,0xaf,0xc0,0x80,0x04,0x00,0x21,0x80,0x04,0x02,
+0x80,0x80,0x10,0x00,0x21,0x80,0x04,0x02,0x02,0x80,0x02,0x3c,0x68,0x15,0x42,0x24,
+0x80,0x80,0x10,0x00,0x21,0x80,0x02,0x02,0x1c,0x00,0xbf,0xaf,0x18,0x00,0xb2,0xaf,
+0x14,0x00,0xb1,0xaf,0x78,0x51,0x05,0x8e,0xff,0x1f,0x02,0x3c,0x25,0xb0,0x12,0x3c,
+0xff,0xff,0x42,0x34,0x70,0x51,0x02,0xae,0x84,0x01,0x43,0x36,0xf8,0xff,0x02,0x24,
+0x00,0x00,0x66,0x8c,0x24,0x28,0xa2,0x00,0xff,0xfe,0x02,0x24,0x24,0x28,0xa2,0x00,
+0xff,0xef,0x03,0x24,0x24,0x28,0xa3,0x00,0x74,0x51,0x06,0xae,0x78,0x51,0x05,0xae,
+0xce,0x0d,0x00,0x0c,0x21,0x88,0x80,0x00,0x7a,0x51,0x02,0x92,0x21,0x88,0x32,0x02,
+0x1c,0x00,0xbf,0x8f,0x60,0x01,0x22,0xa2,0x18,0x00,0xb2,0x8f,0x64,0x51,0x00,0xae,
+0x48,0x51,0x00,0xae,0x4c,0x51,0x00,0xae,0x50,0x51,0x00,0xae,0x54,0x51,0x00,0xae,
+0x58,0x51,0x00,0xae,0x5c,0x51,0x00,0xae,0x60,0x51,0x00,0xae,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,0xff,0x00,0xa5,0x30,
+0xc0,0x10,0x05,0x00,0x21,0x10,0x45,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x45,0x00,
+0x02,0x80,0x03,0x3c,0x68,0x15,0x63,0x24,0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,
+0x78,0x51,0x43,0x8c,0x25,0xb0,0x05,0x3c,0xff,0x00,0xc6,0x30,0x21,0x30,0xc5,0x00,
+0xaf,0x01,0xc2,0x90,0x07,0x00,0x63,0x30,0x80,0x18,0x03,0x00,0x21,0x18,0x65,0x00,
+0xff,0x00,0x88,0x30,0xff,0x00,0x49,0x30,0x84,0x01,0x66,0x8c,0x21,0x50,0x00,0x00,
+0x21,0x58,0x00,0x00,0x2b,0x00,0x20,0x11,0x21,0x20,0x00,0x01,0x2b,0x00,0xc0,0x10,
+0x2b,0x10,0x09,0x01,0x21,0x28,0x00,0x00,0x3e,0x4f,0x00,0x08,0x01,0x00,0x07,0x24,
+0xff,0x00,0x65,0x30,0x1d,0x00,0xa2,0x2c,0x07,0x00,0x40,0x10,0xff,0xff,0x02,0x25,
+0x04,0x10,0xa7,0x00,0x24,0x10,0x46,0x00,0xf9,0xff,0x40,0x10,0x01,0x00,0xa3,0x24,
+0x21,0x58,0xa0,0x00,0xff,0xff,0x02,0x25,0xff,0x00,0x45,0x30,0x2b,0x18,0xab,0x00,
+0x0f,0x00,0x60,0x14,0x2b,0x10,0x49,0x01,0x01,0x00,0x04,0x24,0x04,0x10,0xa4,0x00,
+0x24,0x10,0x46,0x00,0xff,0xff,0xa7,0x24,0x04,0x00,0x40,0x10,0x01,0x00,0x43,0x25,
+0x17,0x00,0x49,0x11,0xff,0x00,0x6a,0x30,0x21,0x40,0xa0,0x00,0xff,0x00,0xe5,0x30,
+0x2b,0x10,0xab,0x00,0xf6,0xff,0x40,0x10,0x04,0x10,0xa4,0x00,0x2b,0x10,0x49,0x01,
+0x08,0x00,0x40,0x10,0x21,0x20,0x00,0x01,0x23,0x10,0x2a,0x01,0x2a,0x10,0x62,0x01,
+0x04,0x00,0x40,0x14,0x21,0x20,0x00,0x00,0x23,0x10,0x69,0x01,0x21,0x10,0x4a,0x00,
+0xff,0x00,0x44,0x30,0x08,0x00,0xe0,0x03,0x21,0x10,0x80,0x00,0xfd,0xff,0x40,0x14,
+0x21,0x20,0x00,0x00,0x23,0x10,0x09,0x01,0x5f,0x4f,0x00,0x08,0xff,0x00,0x44,0x30,
+0x21,0x20,0x00,0x01,0x08,0x00,0xe0,0x03,0x21,0x10,0x80,0x00,0xff,0x00,0x84,0x30,
+0xc0,0x10,0x04,0x00,0x21,0x10,0x44,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x44,0x00,
+0x02,0x80,0x03,0x3c,0x68,0x15,0x63,0x24,0x80,0x10,0x02,0x00,0x21,0x10,0x43,0x00,
+0x25,0xb0,0x06,0x3c,0x78,0x51,0x43,0x8c,0xff,0x00,0xa5,0x30,0x21,0x20,0x86,0x00,
+0x21,0x28,0xa6,0x00,0x60,0x01,0x82,0x90,0xaf,0x01,0xa4,0x90,0x07,0x00,0x63,0x30,
+0x80,0x18,0x03,0x00,0x21,0x18,0x66,0x00,0xff,0x00,0x48,0x30,0xff,0x00,0x89,0x30,
+0x84,0x01,0x66,0x8c,0x21,0x50,0x00,0x00,0x21,0x58,0x00,0x00,0x2b,0x00,0x20,0x11,
+0x21,0x20,0x00,0x01,0x2b,0x00,0xc0,0x10,0x2b,0x10,0x09,0x01,0x21,0x28,0x00,0x00,
+0x8c,0x4f,0x00,0x08,0x01,0x00,0x07,0x24,0xff,0x00,0x65,0x30,0x1d,0x00,0xa2,0x2c,
+0x07,0x00,0x40,0x10,0xff,0xff,0x02,0x25,0x04,0x10,0xa7,0x00,0x24,0x10,0x46,0x00,
+0xf9,0xff,0x40,0x10,0x01,0x00,0xa3,0x24,0x21,0x58,0xa0,0x00,0xff,0xff,0x02,0x25,
+0xff,0x00,0x45,0x30,0x2b,0x18,0xab,0x00,0x0f,0x00,0x60,0x14,0x2b,0x10,0x49,0x01,
+0x01,0x00,0x04,0x24,0x04,0x10,0xa4,0x00,0x24,0x10,0x46,0x00,0xff,0xff,0xa7,0x24,
+0x04,0x00,0x40,0x10,0x01,0x00,0x43,0x25,0x17,0x00,0x49,0x11,0xff,0x00,0x6a,0x30,
+0x21,0x40,0xa0,0x00,0xff,0x00,0xe5,0x30,0x2b,0x10,0xab,0x00,0xf6,0xff,0x40,0x10,
+0x04,0x10,0xa4,0x00,0x2b,0x10,0x49,0x01,0x08,0x00,0x40,0x10,0x21,0x20,0x00,0x01,
+0x23,0x10,0x2a,0x01,0x2a,0x10,0x62,0x01,0x04,0x00,0x40,0x14,0x21,0x20,0x00,0x00,
+0x23,0x10,0x69,0x01,0x21,0x10,0x4a,0x00,0xff,0x00,0x44,0x30,0x08,0x00,0xe0,0x03,
+0x21,0x10,0x80,0x00,0xfd,0xff,0x40,0x14,0x21,0x20,0x00,0x00,0x23,0x10,0x09,0x01,
+0xad,0x4f,0x00,0x08,0xff,0x00,0x44,0x30,0x21,0x20,0x00,0x01,0x08,0x00,0xe0,0x03,
+0x21,0x10,0x80,0x00,0xe0,0xff,0xbd,0x27,0x02,0x80,0x02,0x3c,0x10,0x00,0xb0,0xaf,
+0x68,0x15,0x50,0x24,0x18,0x00,0xb2,0xaf,0x14,0x00,0xb1,0xaf,0x1c,0x00,0xbf,0xaf,
+0x21,0x88,0x00,0x00,0x21,0x90,0x00,0x02,0xee,0x4e,0x00,0x0c,0x21,0x20,0x20,0x02,
+0x7a,0x51,0x02,0x92,0x21,0x28,0x00,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x52,0x00,
+0xec,0x44,0x44,0x8c,0x60,0x45,0x43,0x8c,0x00,0x00,0x00,0x00,0x21,0x18,0x64,0x00,
+0x42,0x18,0x03,0x00,0x44,0x51,0x03,0xae,0x21,0x10,0x05,0x02,0x01,0x00,0xa5,0x24,
+0x1d,0x00,0xa3,0x28,0xb6,0x51,0x40,0xa0,0x7c,0x51,0x40,0xa0,0xfa,0xff,0x60,0x14,
+0x99,0x51,0x40,0xa0,0x01,0x00,0x31,0x26,0x20,0x00,0x22,0x2a,0xd4,0x51,0x00,0xae,
+0xe9,0xff,0x40,0x14,0x94,0x00,0x10,0x26,0x1c,0x00,0xbf,0x8f,0x18,0x00,0xb2,0x8f,
+0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,
+0xc8,0xff,0xbd,0x27,0x02,0x80,0x02,0x3c,0x30,0x00,0xbe,0xaf,0x28,0x00,0xb6,0xaf,
+0x68,0x15,0x46,0x24,0x34,0x00,0xbf,0xaf,0x2c,0x00,0xb7,0xaf,0x24,0x00,0xb5,0xaf,
+0x20,0x00,0xb4,0xaf,0x1c,0x00,0xb3,0xaf,0x18,0x00,0xb2,0xaf,0x14,0x00,0xb1,0xaf,
+0x10,0x00,0xb0,0xaf,0x8c,0x65,0xc2,0x8c,0xff,0x00,0x8d,0x30,0xff,0x00,0x03,0x24,
+0xff,0xff,0x42,0x38,0x21,0xf0,0x00,0x00,0xff,0xff,0x04,0x34,0x0a,0xf0,0x62,0x00,
+0x8c,0x65,0xc4,0xac,0xb0,0x00,0xa0,0x11,0x08,0x00,0x16,0x24,0x02,0x80,0x02,0x3c,
+0xb8,0x90,0x45,0x24,0x90,0x44,0xc4,0x24,0xff,0x4f,0x00,0x08,0x21,0x88,0x00,0x00,
+0x01,0x00,0x31,0x26,0x00,0x00,0x82,0xa0,0x1d,0x00,0x22,0x2a,0x0b,0x00,0x40,0x10,
+0x01,0x00,0x84,0x24,0x21,0x10,0x25,0x02,0x00,0x00,0x42,0x90,0x00,0x00,0x00,0x00,
+0xf7,0xff,0x40,0x10,0xfd,0xff,0x43,0x24,0x01,0x00,0x31,0x26,0x1d,0x00,0x22,0x2a,
+0x00,0x00,0x83,0xa0,0xf7,0xff,0x40,0x14,0x01,0x00,0x84,0x24,0x02,0x80,0x02,0x3c,
+0x68,0x15,0x4a,0x24,0x02,0x80,0x03,0x3c,0x02,0x80,0x02,0x3c,0x50,0x8e,0x6c,0x24,
+0xd8,0x8d,0x4b,0x24,0x21,0x88,0x00,0x00,0x21,0x48,0x00,0x00,0x21,0x30,0x00,0x00,
+0x21,0x40,0x2a,0x01,0x21,0x38,0x2c,0x01,0x21,0x10,0xe6,0x00,0x91,0x00,0x44,0x90,
+0x00,0x00,0x45,0x90,0x21,0x18,0x06,0x01,0x01,0x00,0xc6,0x24,0x05,0x00,0xc2,0x28,
+0xc5,0x43,0x64,0xa0,0xf8,0xff,0x40,0x14,0x34,0x43,0x65,0xa0,0x21,0x10,0x2b,0x02,
+0x1d,0x00,0x44,0x90,0x00,0x00,0x45,0x90,0x21,0x18,0x2a,0x02,0x01,0x00,0x31,0x26,
+0x1d,0x00,0x22,0x2a,0x73,0x44,0x64,0xa0,0x56,0x44,0x65,0xa0,0xeb,0xff,0x40,0x14,
+0x05,0x00,0x29,0x25,0xa6,0x00,0xa0,0x11,0x02,0x80,0x02,0x3c,0x68,0x15,0x48,0x24,
+0x02,0x80,0x03,0x3c,0x02,0x80,0x02,0x3c,0x4c,0x91,0x69,0x24,0xd8,0x90,0x47,0x24,
+0x21,0x88,0x00,0x00,0x80,0x18,0x11,0x00,0x21,0x10,0x69,0x00,0x21,0x20,0x67,0x00,
+0x00,0x00,0x46,0x8c,0x00,0x00,0x85,0x8c,0x01,0x00,0x31,0x26,0x21,0x18,0x68,0x00,
+0x04,0x00,0x22,0x2a,0xec,0x44,0x65,0xac,0xf6,0xff,0x40,0x14,0x60,0x45,0x66,0xac,
+0x02,0x80,0x02,0x3c,0x68,0x15,0x49,0x24,0x02,0x80,0x03,0x3c,0x02,0x80,0x02,0x3c,
+0x4c,0x91,0x68,0x24,0xd8,0x90,0x47,0x24,0x04,0x00,0x11,0x24,0x80,0x20,0x11,0x00,
+0x21,0x10,0x88,0x00,0x21,0x30,0x87,0x00,0x00,0x00,0x45,0x8c,0x00,0x00,0xc3,0x8c,
+0x01,0x00,0x31,0x26,0x21,0x20,0x89,0x00,0x82,0x28,0x05,0x00,0x82,0x18,0x03,0x00,
+0x1d,0x00,0x22,0x2a,0xec,0x44,0x83,0xac,0xf4,0xff,0x40,0x14,0x60,0x45,0x85,0xac,
+0x02,0x80,0x02,0x3c,0x68,0x15,0x55,0x24,0x21,0x88,0x00,0x00,0x21,0xb8,0xa0,0x02,
+0x21,0xa0,0x00,0x00,0x5a,0x50,0x00,0x08,0x21,0x90,0xa0,0x02,0x01,0x00,0x31,0x26,
+0x20,0x00,0x22,0x2a,0x94,0x00,0x52,0x26,0x38,0x00,0x40,0x10,0x94,0x00,0x94,0x26,
+0x78,0x51,0x44,0x8e,0x01,0x00,0x03,0x24,0x02,0x13,0x04,0x00,0x01,0x00,0x53,0x30,
+0xf6,0xff,0x63,0x16,0x07,0x00,0x82,0x30,0x25,0xb0,0x03,0x3c,0x80,0x10,0x02,0x00,
+0x21,0x10,0x43,0x00,0x84,0x01,0x45,0x8c,0x70,0x51,0x43,0x8e,0x21,0x20,0x20,0x02,
+0x24,0x28,0xa3,0x00,0xce,0x0d,0x00,0x0c,0x74,0x51,0x45,0xae,0x7a,0x51,0x44,0x92,
+0x5c,0x0d,0x00,0x0c,0xff,0x00,0x25,0x32,0x7a,0x51,0x50,0x92,0x00,0x00,0x00,0x00,
+0x21,0x20,0x00,0x02,0x63,0x0d,0x00,0x0c,0x80,0x80,0x10,0x00,0x21,0x80,0x17,0x02,
+0x48,0x51,0x40,0xae,0x4c,0x51,0x40,0xae,0x50,0x51,0x40,0xae,0x54,0x51,0x40,0xae,
+0x58,0x51,0x40,0xae,0x5c,0x51,0x40,0xae,0x60,0x51,0x40,0xae,0x64,0x51,0x40,0xae,
+0xec,0x44,0x04,0x8e,0x60,0x45,0x03,0x8e,0x26,0x10,0x53,0x00,0x21,0x30,0x00,0x00,
+0x21,0x18,0x64,0x00,0x42,0x18,0x03,0x00,0x04,0x00,0x04,0x24,0x0a,0xb0,0x82,0x00,
+0x44,0x51,0x43,0xae,0x21,0x20,0x95,0x02,0x21,0x10,0x86,0x00,0x01,0x00,0xc6,0x24,
+0x1d,0x00,0xc3,0x28,0xb6,0x51,0x40,0xa0,0x7c,0x51,0x40,0xa0,0xfa,0xff,0x60,0x14,
+0x99,0x51,0x40,0xa0,0x01,0x00,0x31,0x26,0x20,0x00,0x22,0x2a,0xd4,0x51,0x80,0xac,
+0x94,0x00,0x52,0x26,0xca,0xff,0x40,0x14,0x94,0x00,0x94,0x26,0x25,0xb0,0x02,0x3c,
+0x80,0x01,0x42,0x34,0x00,0x00,0x56,0xa0,0x03,0x00,0xc0,0x17,0x02,0x80,0x03,0x3c,
+0x68,0x15,0x62,0x24,0x8c,0x65,0x40,0xac,0x34,0x00,0xbf,0x8f,0x30,0x00,0xbe,0x8f,
+0x2c,0x00,0xb7,0x8f,0x28,0x00,0xb6,0x8f,0x24,0x00,0xb5,0x8f,0x20,0x00,0xb4,0x8f,
+0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,
+0x08,0x00,0xe0,0x03,0x38,0x00,0xbd,0x27,0x02,0x80,0x02,0x3c,0xb8,0x90,0x45,0x24,
+0x90,0x44,0xc4,0x24,0x21,0x88,0x00,0x00,0x21,0x10,0x25,0x02,0x00,0x00,0x43,0x90,
+0x01,0x00,0x31,0x26,0x1d,0x00,0x22,0x2a,0x00,0x00,0x83,0xa0,0xfa,0xff,0x40,0x14,
+0x01,0x00,0x84,0x24,0x02,0x80,0x02,0x3c,0x68,0x15,0x4a,0x24,0x02,0x80,0x03,0x3c,
+0x02,0x80,0x02,0x3c,0x74,0x8f,0x6c,0x24,0x14,0x8e,0x4b,0x24,0x21,0x88,0x00,0x00,
+0x21,0x48,0x00,0x00,0x21,0x30,0x00,0x00,0x21,0x40,0x2a,0x01,0x21,0x38,0x2c,0x01,
+0x21,0x10,0xe6,0x00,0x91,0x00,0x44,0x90,0x00,0x00,0x45,0x90,0x21,0x18,0x06,0x01,
+0x01,0x00,0xc6,0x24,0x05,0x00,0xc2,0x28,0xc5,0x43,0x64,0xa0,0xf8,0xff,0x40,0x14,
+0x34,0x43,0x65,0xa0,0x21,0x10,0x2b,0x02,0x1d,0x00,0x44,0x90,0x00,0x00,0x45,0x90,
+0x21,0x18,0x2a,0x02,0x01,0x00,0x31,0x26,0x1d,0x00,0x22,0x2a,0x73,0x44,0x64,0xa0,
+0x56,0x44,0x65,0xa0,0xeb,0xff,0x40,0x14,0x05,0x00,0x29,0x25,0x02,0x80,0x02,0x3c,
+0x68,0x15,0x49,0x24,0x02,0x80,0x03,0x3c,0x02,0x80,0x02,0x3c,0x4c,0x91,0x68,0x24,
+0xd8,0x90,0x47,0x24,0x21,0x88,0x00,0x00,0x80,0x18,0x11,0x00,0x21,0x10,0x68,0x00,
+0x21,0x20,0x67,0x00,0x00,0x00,0x46,0x8c,0x00,0x00,0x85,0x8c,0x01,0x00,0x31,0x26,
+0x21,0x18,0x69,0x00,0x1d,0x00,0x22,0x2a,0xec,0x44,0x65,0xac,0xf6,0xff,0x40,0x14,
+0x60,0x45,0x66,0xac,0x4f,0x50,0x00,0x08,0x02,0x80,0x02,0x3c,0xd8,0xff,0xbd,0x27,
+0xff,0xff,0x84,0x30,0x18,0x00,0xb2,0xaf,0xf0,0x01,0x92,0x30,0x02,0x91,0x12,0x00,
+0x14,0x00,0xb1,0xaf,0xc0,0x88,0x12,0x00,0x21,0x88,0x32,0x02,0x80,0x88,0x11,0x00,
+0x21,0x88,0x32,0x02,0x02,0x80,0x02,0x3c,0x68,0x15,0x42,0x24,0x80,0x88,0x11,0x00,
+0x21,0x88,0x22,0x02,0x20,0x00,0xbf,0xaf,0x1c,0x00,0xb3,0xaf,0x10,0x00,0xb0,0xaf,
+0x78,0x51,0x30,0x8e,0x00,0x02,0x82,0x30,0xff,0xfe,0x03,0x24,0x2b,0x10,0x02,0x00,
+0x00,0x10,0x10,0x36,0x24,0x80,0x03,0x02,0x00,0x12,0x02,0x00,0x25,0x80,0x02,0x02,
+0x70,0x51,0x25,0xae,0x78,0x51,0x30,0xae,0xa0,0x0e,0x00,0x0c,0x21,0x98,0xa0,0x00,
+0xf8,0xff,0x03,0x24,0x24,0x80,0x03,0x02,0x07,0x00,0x42,0x30,0x25,0x80,0x02,0x02,
+0x07,0x00,0x03,0x32,0x25,0xb0,0x02,0x3c,0x80,0x18,0x03,0x00,0x78,0x51,0x30,0xae,
+0x21,0x18,0x62,0x00,0x84,0x01,0x62,0x8c,0x21,0x20,0x40,0x02,0x24,0x10,0x53,0x00,
+0xce,0x0d,0x00,0x0c,0x74,0x51,0x22,0xae,0x7a,0x51,0x24,0x92,0x21,0x28,0x40,0x02,
+0x20,0x00,0xbf,0x8f,0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x5c,0x0d,0x00,0x08,0x28,0x00,0xbd,0x27,0xee,0x4e,0x00,0x08,
+0xff,0x00,0x84,0x30,0x02,0x80,0x02,0x3c,0x68,0x15,0x43,0x24,0x1f,0x00,0x04,0x24,
+0x78,0x51,0x62,0x8c,0xff,0xff,0x84,0x24,0x00,0x10,0x42,0x34,0x78,0x51,0x62,0xac,
+0xfb,0xff,0x81,0x04,0x94,0x00,0x63,0x24,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x78,0xff,0xbd,0x27,0x60,0x00,0xb0,0xaf,0x25,0xb0,0x10,0x3c,0x70,0x00,0xb4,0xaf,
+0xc4,0x02,0x14,0x36,0x00,0x00,0x80,0xae,0x74,0x00,0xb5,0xaf,0x6c,0x00,0xb3,0xaf,
+0x68,0x00,0xb2,0xaf,0x64,0x00,0xb1,0xaf,0x84,0x00,0xbf,0xaf,0x80,0x00,0xbe,0xaf,
+0x7c,0x00,0xb7,0xaf,0x78,0x00,0xb6,0xaf,0x04,0x00,0x02,0x36,0x04,0x0c,0x13,0x36,
+0x00,0x00,0x43,0x8c,0x00,0x00,0x62,0x8e,0x0f,0x00,0x11,0x3c,0x24,0x18,0x71,0x00,
+0x08,0x0c,0x12,0x36,0x4c,0x00,0xa2,0xaf,0x02,0xac,0x03,0x00,0x00,0x00,0x43,0x8e,
+0x00,0x00,0x00,0x00,0x50,0x00,0xa3,0xaf,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x21,0x20,0x00,0x00,0xdd,0x44,0x00,0x0c,
+0xff,0xff,0x25,0x36,0x10,0x00,0xa2,0xaf,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x00,0x60,0x81,0x40,0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0x7a,0x42,0x00,0x0c,
+0x01,0x00,0x04,0x24,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,
+0x00,0x60,0x81,0x40,0x21,0x20,0x00,0x00,0xdd,0x44,0x00,0x0c,0xff,0xff,0x25,0x36,
+0x14,0x00,0xa2,0xaf,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0x7a,0x42,0x00,0x0c,0x21,0x20,0x00,0x00,
+0xe0,0x0e,0x05,0x36,0x00,0x00,0xad,0x8c,0xdc,0x0e,0x06,0x36,0x70,0x0e,0x07,0x36,
+0x18,0x00,0xad,0xaf,0x00,0x00,0xc2,0x8c,0x74,0x0e,0x08,0x36,0x78,0x0e,0x09,0x36,
+0x1c,0x00,0xa2,0xaf,0x00,0x00,0xe3,0x8c,0x7c,0x0e,0x0a,0x36,0x80,0x0e,0x0b,0x36,
+0x20,0x00,0xa3,0xaf,0x00,0x00,0x0d,0x8d,0x84,0x0e,0x0c,0x36,0x88,0x0e,0x17,0x36,
+0x24,0x00,0xad,0xaf,0x00,0x00,0x22,0x8d,0x8c,0x0e,0x0e,0x36,0xd0,0x0e,0x18,0x36,
+0x28,0x00,0xa2,0xaf,0x00,0x00,0x43,0x8d,0xd8,0x0e,0x11,0x36,0xd4,0x0e,0x10,0x36,
+0x2c,0x00,0xa3,0xaf,0x00,0x00,0x6d,0x8d,0xed,0x3f,0x04,0x3c,0xfb,0x92,0x84,0x34,
+0x30,0x00,0xad,0xaf,0x00,0x00,0x82,0x8d,0x25,0xb0,0x1e,0x3c,0x21,0xb0,0x00,0x00,
+0x34,0x00,0xa2,0xaf,0x00,0x00,0xe3,0x8e,0xff,0x03,0x0f,0x3c,0x38,0x00,0xa3,0xaf,
+0x00,0x00,0xcd,0x8d,0x00,0x00,0x00,0x00,0x3c,0x00,0xad,0xaf,0x00,0x00,0x02,0x8f,
+0x00,0x00,0x00,0x00,0x40,0x00,0xa2,0xaf,0x00,0x00,0x03,0x8e,0x00,0x00,0x00,0x00,
+0x44,0x00,0xa3,0xaf,0x00,0x00,0x2d,0x8e,0x00,0x00,0x00,0x00,0x48,0x00,0xad,0xaf,
+0x00,0x00,0xa4,0xac,0x00,0x00,0xc4,0xac,0x00,0x00,0xe4,0xac,0x00,0x00,0x04,0xad,
+0x00,0x00,0x24,0xad,0x00,0x00,0x44,0xad,0x00,0x00,0x64,0xad,0x00,0x00,0x84,0xad,
+0x00,0x00,0xe4,0xae,0x00,0x00,0xc4,0xad,0x00,0x00,0x04,0xaf,0x00,0x00,0x04,0xae,
+0x00,0x00,0x24,0xae,0xd0,0x51,0x00,0x08,0x00,0x00,0x00,0x00,0x7a,0x00,0xa2,0x12,
+0x00,0x10,0x03,0x3c,0xac,0x0e,0xc2,0x37,0x94,0x0e,0xc3,0x37,0x25,0xb0,0x09,0x3c,
+0x00,0x00,0x4a,0x8c,0xbc,0x0e,0x29,0x35,0x00,0x00,0x64,0x8c,0xb4,0x0e,0xc2,0x37,
+0x9c,0x0e,0xc3,0x37,0x00,0x00,0x45,0x8c,0x00,0x00,0x66,0x8c,0x00,0x00,0x27,0x8d,
+0x24,0x20,0x8f,0x00,0x00,0xd8,0x02,0x3c,0x24,0x10,0x42,0x01,0x24,0x28,0xaf,0x00,
+0x24,0x30,0xcf,0x00,0x24,0x38,0xef,0x00,0x02,0x24,0x04,0x00,0x20,0x01,0x03,0x24,
+0x01,0x00,0x42,0x2c,0x02,0x2c,0x05,0x00,0x02,0x34,0x06,0x00,0xf2,0x00,0x83,0x10,
+0x02,0x3c,0x07,0x00,0xf0,0x00,0xa3,0x10,0x20,0x00,0x03,0x24,0xee,0x00,0xc3,0x10,
+0x00,0x00,0x00,0x00,0xec,0x00,0xe3,0x10,0x01,0x00,0x08,0x24,0x80,0x00,0x03,0x24,
+0x08,0x00,0x83,0x10,0x21,0x20,0x00,0x00,0x06,0x00,0xa3,0x10,0x21,0x20,0x00,0x00,
+0xe0,0x03,0x03,0x24,0x03,0x00,0xc3,0x10,0x00,0x00,0x00,0x00,0xe5,0x00,0xe3,0x10,
+0x01,0x00,0x04,0x24,0x06,0x00,0x40,0x10,0x09,0x00,0x02,0x24,0x04,0x00,0x00,0x11,
+0x00,0x00,0x00,0x00,0x6d,0x01,0x80,0x14,0x25,0xb0,0x12,0x3c,0x09,0x00,0x02,0x24,
+0xde,0x00,0xc2,0x12,0x25,0xb0,0x04,0x3c,0x01,0x00,0xd6,0x26,0x0a,0x00,0xc2,0x2e,
+0x1d,0x01,0x40,0x10,0x00,0x00,0x00,0x00,0xc8,0xff,0xa0,0x16,0x01,0x00,0x02,0x24,
+0xa0,0x00,0x03,0x3c,0x25,0xb0,0x09,0x3c,0x30,0x54,0x62,0x34,0x04,0x0c,0x29,0x35,
+0x00,0x00,0x22,0xad,0x25,0xb0,0x0d,0x3c,0x08,0x00,0x02,0x3c,0xe4,0x00,0x42,0x34,
+0x08,0x0c,0xad,0x35,0x25,0xb0,0x09,0x3c,0x00,0x00,0xa2,0xad,0x28,0x0e,0x29,0x35,
+0x80,0x80,0x02,0x3c,0x00,0x00,0x22,0xad,0x14,0x02,0x04,0x3c,0x16,0x68,0x02,0x3c,
+0x48,0x01,0x83,0x34,0x40,0x0e,0xc5,0x37,0x44,0x0e,0xc6,0x37,0xa2,0x04,0x42,0x34,
+0x25,0xb0,0x0d,0x3c,0x00,0x00,0xa3,0xac,0x4c,0x0e,0xad,0x35,0x00,0x00,0xc2,0xac,
+0xd1,0x28,0x02,0x24,0x00,0x00,0xa2,0xad,0x14,0x02,0x03,0x3c,0x16,0x28,0x02,0x3c,
+0x4d,0x01,0x63,0x34,0x60,0x0e,0xc7,0x37,0x64,0x0e,0xc8,0x37,0xba,0x08,0x42,0x34,
+0x00,0x00,0xe3,0xac,0x25,0xb0,0x06,0x3c,0x00,0x00,0x02,0xad,0x00,0xfb,0x0d,0x3c,
+0x25,0xb0,0x09,0x3c,0x00,0xf8,0x02,0x3c,0xd1,0x28,0x07,0x24,0x6c,0x0e,0xc6,0x34,
+0x48,0x0e,0x29,0x35,0x01,0x00,0x42,0x34,0x01,0x00,0xad,0x35,0x00,0x00,0xc7,0xac,
+0x03,0x00,0x04,0x24,0x00,0x00,0x2d,0xad,0x00,0x00,0x22,0xad,0x84,0x0a,0x00,0x0c,
+0x58,0x00,0xaf,0xaf,0xa0,0x00,0x04,0x3c,0x25,0xb0,0x03,0x3c,0x25,0xb0,0x06,0x3c,
+0x25,0xb0,0x07,0x3c,0xe4,0x00,0x02,0x24,0x33,0x54,0x84,0x34,0x04,0x0c,0x63,0x34,
+0x08,0x0c,0xc6,0x34,0x28,0x0e,0xe7,0x34,0x00,0x00,0x64,0xac,0x00,0x00,0xc2,0xac,
+0x00,0x00,0xe0,0xac,0x01,0x00,0x02,0x24,0x58,0x00,0xaf,0x8f,0x8a,0xff,0xa2,0x16,
+0xac,0x0e,0xc2,0x37,0x00,0x10,0x03,0x3c,0x1f,0xdc,0x79,0x34,0x1f,0x8c,0x7f,0x34,
+0x23,0x8c,0x6d,0x34,0xa0,0x00,0x03,0x3c,0x30,0x54,0x65,0x34,0x00,0x01,0x17,0x3c,
+0x25,0xb0,0x09,0x3c,0x25,0xb0,0x03,0x3c,0x00,0x01,0xe2,0x36,0x20,0x08,0x29,0x35,
+0x20,0x08,0x63,0x34,0x00,0x00,0x30,0x8d,0x00,0x00,0x62,0xac,0x25,0xb0,0x03,0x3c,
+0x28,0x08,0x63,0x34,0x00,0x00,0x62,0xac,0x25,0xb0,0x02,0x3c,0x04,0x0c,0x42,0x34,
+0x00,0x00,0x45,0xac,0x25,0xb0,0x03,0x3c,0x08,0x00,0x02,0x3c,0xe4,0x00,0x42,0x34,
+0x08,0x0c,0x63,0x34,0x00,0x00,0x62,0xac,0x25,0xb0,0x03,0x3c,0x00,0x7c,0xf3,0x36,
+0x00,0x48,0xf4,0x36,0x30,0x0e,0xc6,0x37,0x34,0x0e,0xc7,0x37,0x80,0x80,0x02,0x3c,
+0x28,0x0e,0x63,0x34,0x00,0x00,0x62,0xac,0x00,0x00,0xd3,0xac,0x00,0x00,0xf4,0xac,
+0x14,0x02,0x06,0x3c,0x16,0x68,0x07,0x3c,0x38,0x0e,0xc8,0x37,0x40,0x0e,0xca,0x37,
+0x44,0x0e,0xcb,0x37,0x3c,0x0e,0xc9,0x37,0x02,0x01,0xc6,0x34,0xc7,0x04,0xe7,0x34,
+0x00,0x00,0x19,0xad,0x25,0xb0,0x03,0x3c,0x00,0x00,0x3f,0xad,0x00,0x00,0x46,0xad,
+0x25,0xb0,0x09,0x3c,0x00,0x00,0x67,0xad,0x25,0xb0,0x06,0x3c,0x00,0x10,0x07,0x3c,
+0x50,0x0e,0xcc,0x37,0x58,0x0e,0xce,0x37,0x5c,0x0e,0xd8,0x37,0xd1,0x28,0x02,0x24,
+0x23,0xdc,0xe7,0x34,0x4c,0x0e,0x29,0x35,0x6c,0x0e,0x63,0x34,0x54,0x0e,0xc6,0x34,
+0x00,0x00,0x22,0xad,0x00,0x00,0x62,0xac,0x14,0x02,0x09,0x3c,0x00,0x00,0x93,0xad,
+0x25,0xb0,0x02,0x3c,0x00,0x00,0xd4,0xac,0x00,0x00,0xc7,0xad,0x00,0x00,0x0d,0xaf,
+0x16,0x28,0x0d,0x3c,0x48,0x0e,0x42,0x34,0x00,0xf8,0x06,0x3c,0x02,0x01,0x29,0x35,
+0x07,0x0d,0xad,0x35,0x00,0xfb,0x03,0x3c,0x60,0x0e,0xd1,0x37,0x64,0x0e,0xd2,0x37,
+0x00,0x00,0x29,0xae,0x03,0x00,0x04,0x24,0x00,0x00,0x4d,0xae,0x00,0x00,0x43,0xac,
+0x00,0x00,0x46,0xac,0x84,0x0a,0x00,0x0c,0x58,0x00,0xaf,0xaf,0x00,0x02,0x02,0x3c,
+0x25,0xb0,0x07,0x3c,0x25,0xb0,0x09,0x3c,0xd1,0x28,0x42,0x34,0x4c,0x0e,0xe7,0x34,
+0x6c,0x0e,0x29,0x35,0x25,0xb0,0x0d,0x3c,0x00,0x00,0xe2,0xac,0x48,0x0e,0xad,0x35,
+0x00,0x00,0x22,0xad,0x00,0xf8,0x03,0x3c,0x00,0xfb,0x02,0x3c,0x00,0x00,0xa2,0xad,
+0x03,0x00,0x04,0x24,0x00,0x00,0xa3,0xad,0x84,0x0a,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x4c,0x00,0xa6,0x8f,0x25,0xb0,0x04,0x3c,0x04,0x0c,0x84,0x34,0x00,0x00,0x86,0xac,
+0x50,0x00,0xa9,0x8f,0x25,0xb0,0x07,0x3c,0x25,0xb0,0x0d,0x3c,0x00,0x01,0x10,0x32,
+0x08,0x0c,0xe7,0x34,0x28,0x0e,0xad,0x35,0x00,0x00,0xe9,0xac,0x2b,0x80,0x10,0x00,
+0x00,0x00,0xa0,0xad,0x58,0x00,0xaf,0x8f,0x17,0xff,0x00,0x16,0xac,0x0e,0xc2,0x37,
+0x25,0xb0,0x02,0x3c,0x25,0xb0,0x03,0x3c,0x20,0x08,0x42,0x34,0x28,0x08,0x63,0x34,
+0x00,0x00,0x57,0xac,0x25,0xb0,0x09,0x3c,0x00,0x00,0x77,0xac,0xac,0x0e,0xc2,0x37,
+0x94,0x0e,0xc3,0x37,0x00,0x00,0x4a,0x8c,0xbc,0x0e,0x29,0x35,0x00,0x00,0x64,0x8c,
+0xb4,0x0e,0xc2,0x37,0x9c,0x0e,0xc3,0x37,0x00,0x00,0x45,0x8c,0x00,0x00,0x66,0x8c,
+0x00,0x00,0x27,0x8d,0x24,0x20,0x8f,0x00,0x00,0xd8,0x02,0x3c,0x24,0x10,0x42,0x01,
+0x24,0x28,0xaf,0x00,0x24,0x30,0xcf,0x00,0x24,0x38,0xef,0x00,0x02,0x24,0x04,0x00,
+0x20,0x01,0x03,0x24,0x01,0x00,0x42,0x2c,0x02,0x2c,0x05,0x00,0x02,0x34,0x06,0x00,
+0x10,0xff,0x83,0x14,0x02,0x3c,0x07,0x00,0x80,0x00,0x03,0x24,0x16,0xff,0x83,0x14,
+0x21,0x40,0x00,0x00,0xc3,0x51,0x00,0x08,0x21,0x20,0x00,0x00,0xff,0xff,0x02,0x34,
+0xc4,0x02,0x84,0x34,0x00,0x00,0x82,0xac,0x94,0x0e,0xc3,0x37,0x9c,0x0e,0xc2,0x37,
+0xa4,0x0e,0xc4,0x37,0xac,0x0e,0xc7,0x37,0x00,0x00,0x66,0x8c,0x00,0x00,0x49,0x8c,
+0x00,0x00,0x8b,0x8c,0x00,0x00,0xe5,0x8c,0x02,0x80,0x07,0x3c,0x68,0x15,0xe7,0x24,
+0x0c,0x40,0xe3,0x8c,0x10,0x40,0xe4,0x8c,0xb4,0x0e,0xc2,0x37,0x00,0x00,0x47,0x8c,
+0x25,0xb0,0x0d,0x3c,0x00,0xfc,0x02,0x24,0x24,0x30,0xcf,0x00,0x24,0x28,0xaf,0x00,
+0xbc,0x0e,0xad,0x35,0x00,0x00,0xa8,0x8d,0x24,0x20,0x82,0x00,0x02,0x34,0x06,0x00,
+0x24,0x18,0x62,0x00,0x02,0x2c,0x05,0x00,0xc4,0x0e,0xca,0x37,0xcc,0x0e,0xcc,0x37,
+0xf0,0xff,0x02,0x3c,0xff,0x03,0x42,0x34,0x25,0x18,0x66,0x00,0x25,0x20,0x85,0x00,
+0x00,0x00,0x46,0x8d,0x24,0x48,0x2f,0x01,0x00,0x00,0x85,0x8d,0x24,0x38,0xef,0x00,
+0x24,0x20,0x82,0x00,0x24,0x18,0x62,0x00,0x82,0x49,0x09,0x00,0x82,0x39,0x07,0x00,
+0x0f,0xc0,0x02,0x3c,0xff,0xff,0x42,0x34,0x25,0x18,0x69,0x00,0x25,0x20,0x87,0x00,
+0x24,0x58,0x6f,0x01,0x24,0x40,0x0f,0x01,0x24,0x20,0x82,0x00,0x24,0x18,0x62,0x00,
+0x00,0x59,0x0b,0x00,0x00,0x41,0x08,0x00,0x24,0x30,0xcf,0x00,0x24,0x28,0xaf,0x00,
+0x02,0x80,0x02,0x3c,0x68,0x15,0x42,0x24,0x25,0x18,0x6b,0x00,0x25,0x20,0x88,0x00,
+0x02,0x34,0x06,0x00,0x02,0x2c,0x05,0x00,0x01,0x00,0xd6,0x26,0x0c,0x40,0x43,0xac,
+0x10,0x40,0x44,0xac,0x14,0x40,0x46,0xa4,0x16,0x40,0x45,0xa4,0x0a,0x00,0xc2,0x2e,
+0xe5,0xfe,0x40,0x14,0x00,0x00,0x00,0x00,0x18,0x00,0xad,0x8f,0x25,0xb0,0x02,0x3c,
+0xe0,0x0e,0x43,0x34,0x10,0x00,0xa6,0x8f,0x00,0x00,0x6d,0xac,0x1c,0x00,0xa3,0x8f,
+0xdc,0x0e,0x47,0x34,0x70,0x0e,0x48,0x34,0x00,0x00,0xe3,0xac,0x20,0x00,0xa7,0x8f,
+0x74,0x0e,0x49,0x34,0x78,0x0e,0x4a,0x34,0x00,0x00,0x07,0xad,0x24,0x00,0xad,0x8f,
+0x7c,0x0e,0x4b,0x34,0x80,0x0e,0x4c,0x34,0x00,0x00,0x2d,0xad,0x28,0x00,0xa3,0x8f,
+0x25,0xb0,0x0d,0x3c,0x84,0x0e,0xad,0x35,0x00,0x00,0x43,0xad,0x2c,0x00,0xa7,0x8f,
+0x88,0x0e,0x52,0x34,0x8c,0x0e,0x4e,0x34,0x00,0x00,0x67,0xad,0x30,0x00,0xa9,0x8f,
+0xd4,0x0e,0x51,0x34,0xd0,0x0e,0x42,0x34,0x00,0x00,0x89,0xad,0x34,0x00,0xa3,0x8f,
+0x0f,0x00,0x10,0x3c,0xff,0xff,0x05,0x36,0x00,0x00,0xa3,0xad,0x38,0x00,0xa7,0x8f,
+0x21,0x20,0x00,0x00,0x00,0x00,0x47,0xae,0x3c,0x00,0xa9,0x8f,0x00,0x00,0x00,0x00,
+0x00,0x00,0xc9,0xad,0x40,0x00,0xad,0x8f,0x00,0x00,0x00,0x00,0x00,0x00,0x4d,0xac,
+0x44,0x00,0xa2,0x8f,0x00,0x00,0x00,0x00,0x00,0x00,0x22,0xae,0x48,0x00,0xa3,0x8f,
+0x00,0x00,0x00,0x00,0x00,0x00,0x43,0xae,0xba,0x44,0x00,0x0c,0x00,0x00,0x00,0x00,
+0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0x7a,0x42,0x00,0x0c,0x01,0x00,0x04,0x24,
+0x14,0x00,0xa6,0x8f,0xff,0xff,0x05,0x36,0xba,0x44,0x00,0x0c,0x21,0x20,0x00,0x00,
+0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0x84,0x00,0xbf,0x8f,0x80,0x00,0xbe,0x8f,
+0x7c,0x00,0xb7,0x8f,0x78,0x00,0xb6,0x8f,0x74,0x00,0xb5,0x8f,0x70,0x00,0xb4,0x8f,
+0x6c,0x00,0xb3,0x8f,0x68,0x00,0xb2,0x8f,0x64,0x00,0xb1,0x8f,0x60,0x00,0xb0,0x8f,
+0x21,0x20,0x00,0x00,0x7a,0x42,0x00,0x08,0x88,0x00,0xbd,0x27,0x94,0x0e,0x42,0x36,
+0x9c,0x0e,0x43,0x36,0xa4,0x0e,0x44,0x36,0xac,0x0e,0x45,0x36,0x02,0x80,0x0d,0x3c,
+0x00,0x00,0x47,0x8c,0x68,0x15,0xad,0x25,0x00,0x00,0x6a,0x8c,0x00,0x00,0x8c,0x8c,
+0x00,0x00,0xa3,0x8c,0x10,0x40,0xa4,0x8d,0xb4,0x0e,0x42,0x36,0x00,0x00,0x48,0x8c,
+0x0c,0x40,0xa5,0x8d,0x25,0xb0,0x02,0x3c,0x00,0xfc,0x13,0x24,0xbc,0x0e,0x42,0x34,
+0x24,0x18,0x6f,0x00,0x00,0x00,0x49,0x8c,0x02,0x1c,0x03,0x00,0x24,0x38,0xef,0x00,
+0x24,0x20,0x93,0x00,0xf0,0xff,0x06,0x3c,0x25,0x20,0x83,0x00,0xff,0x03,0xc6,0x34,
+0x02,0x3c,0x07,0x00,0xc4,0x0e,0x42,0x36,0x24,0x28,0xb3,0x00,0x24,0x40,0x0f,0x01,
+0xcc,0x0e,0x4b,0x36,0x25,0x28,0xa7,0x00,0x24,0x20,0x86,0x00,0x00,0x00,0x47,0x8c,
+0x24,0x50,0x4f,0x01,0x00,0x00,0x63,0x8d,0x82,0x41,0x08,0x00,0x0f,0xc0,0x02,0x3c,
+0xff,0xff,0x42,0x34,0x25,0x20,0x88,0x00,0x82,0x51,0x0a,0x00,0x24,0x28,0xa6,0x00,
+0x24,0x48,0x2f,0x01,0x24,0x88,0x82,0x00,0x25,0x28,0xaa,0x00,0x24,0x60,0x8f,0x01,
+0x00,0x49,0x09,0x00,0x25,0x88,0x29,0x02,0x24,0x28,0xa2,0x00,0x24,0x18,0x6f,0x00,
+0x00,0x61,0x0c,0x00,0x24,0x38,0xef,0x00,0x25,0x28,0xac,0x00,0x02,0x3c,0x07,0x00,
+0x02,0x1c,0x03,0x00,0x82,0x27,0x11,0x00,0x01,0x00,0x02,0x24,0x16,0x40,0xa3,0xa5,
+0x14,0x40,0xa7,0xa5,0x0c,0x40,0xa5,0xad,0x4a,0x00,0x82,0x10,0x10,0x40,0xb1,0xad,
+0x80,0x0c,0x4c,0x36,0x00,0x00,0x8a,0x8d,0x82,0x72,0x05,0x00,0xff,0x03,0xce,0x31,
+0x00,0x02,0xc3,0x31,0x25,0x10,0xd3,0x01,0x0b,0x70,0x43,0x00,0x82,0x85,0x0a,0x00,
+0x18,0x00,0xd0,0x01,0xff,0x03,0xaf,0x30,0x00,0x02,0xa3,0x30,0x25,0x10,0xf3,0x01,
+0x0b,0x78,0x43,0x00,0x02,0x75,0x11,0x00,0xff,0x03,0xce,0x31,0xc0,0xff,0x08,0x3c,
+0x25,0x18,0xd3,0x01,0x00,0x02,0xc2,0x31,0x00,0xfc,0x06,0x35,0x0b,0x70,0x62,0x00,
+0x24,0x38,0x46,0x01,0x94,0x0c,0x4a,0x36,0xff,0x0f,0x09,0x3c,0xff,0xff,0x29,0x35,
+0x88,0x0c,0x54,0x36,0x12,0x20,0x00,0x00,0x02,0x22,0x04,0x00,0x3f,0x00,0x82,0x30,
+0x18,0x00,0xf0,0x01,0x82,0x7a,0x11,0x00,0xff,0x03,0xef,0x31,0x00,0x14,0x02,0x00,
+0x25,0x38,0xe2,0x00,0x00,0x02,0xe3,0x31,0x25,0x10,0xf3,0x01,0x0b,0x78,0x43,0x00,
+0xc0,0x03,0x84,0x30,0x80,0x25,0x04,0x00,0x9c,0x0c,0x4b,0x36,0x12,0x28,0x00,0x00,
+0x02,0x2a,0x05,0x00,0xff,0x03,0xa2,0x30,0x25,0x10,0xe2,0x00,0x00,0x00,0x82,0xad,
+0x00,0x00,0x42,0x8d,0x00,0x00,0x00,0x00,0x24,0x10,0x49,0x00,0x25,0x10,0x44,0x00,
+0x00,0x00,0x42,0xad,0x00,0x00,0x8a,0x8e,0x00,0x00,0x00,0x00,0x24,0x40,0x48,0x01,
+0x82,0x85,0x08,0x00,0x18,0x00,0xd0,0x01,0x24,0x30,0x46,0x01,0x12,0x18,0x00,0x00,
+0x02,0x1a,0x03,0x00,0x3f,0x00,0x62,0x30,0x18,0x00,0xf0,0x01,0x00,0x14,0x02,0x00,
+0x25,0x30,0xc2,0x00,0xc0,0x03,0x63,0x30,0x80,0x1d,0x03,0x00,0x12,0x20,0x00,0x00,
+0x02,0x22,0x04,0x00,0xff,0x03,0x82,0x30,0x25,0x10,0xc2,0x00,0x00,0x00,0x82,0xae,
+0x00,0x00,0x62,0x8d,0x00,0x00,0x00,0x00,0x24,0x10,0x49,0x00,0x25,0x10,0x43,0x00,
+0x00,0x00,0x62,0xad,0x00,0x17,0x16,0x00,0x25,0xb0,0x03,0x3c,0xdd,0xdd,0x42,0x34,
+0xc4,0x02,0x63,0x34,0x00,0x00,0x62,0xac,0xec,0x52,0x00,0x08,0x00,0x00,0x00,0x00,
+0xe0,0xff,0xbd,0x27,0x44,0x00,0x02,0x24,0x10,0x00,0xa2,0xa3,0x49,0x00,0x03,0x24,
+0x47,0x00,0x02,0x24,0x02,0x80,0x07,0x3c,0x8c,0x97,0xe7,0x24,0x11,0x00,0xa3,0xa3,
+0x12,0x00,0xa2,0xa3,0x10,0x27,0x03,0x24,0x01,0x00,0x02,0x24,0x01,0x80,0x06,0x3c,
+0x10,0x00,0xa5,0x27,0x21,0x20,0xe0,0x00,0xe8,0x51,0xc6,0x24,0x0c,0x00,0xe3,0xac,
+0x14,0x00,0xe2,0xa0,0x18,0x00,0xbf,0xaf,0xfb,0x0c,0x00,0x0c,0x13,0x00,0xa0,0xa3,
+0x18,0x00,0xbf,0x8f,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,
+0xd0,0xff,0xbd,0x27,0x25,0xb0,0x02,0x3c,0x20,0x00,0xb4,0xaf,0x1c,0x00,0xb3,0xaf,
+0x03,0x0d,0x44,0x34,0x2c,0x00,0xbf,0xaf,0x28,0x00,0xb6,0xaf,0x24,0x00,0xb5,0xaf,
+0x18,0x00,0xb2,0xaf,0x14,0x00,0xb1,0xaf,0x10,0x00,0xb0,0xaf,0x00,0x00,0x83,0x90,
+0x42,0x00,0x45,0x34,0xff,0x00,0x73,0x30,0x70,0x00,0x74,0x32,0x29,0x00,0x80,0x16,
+0x8f,0x00,0x62,0x32,0xff,0xff,0x02,0x24,0x00,0x00,0xa2,0xa0,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x0f,0x00,0x11,0x3c,
+0x18,0x00,0x04,0x24,0xdd,0x44,0x00,0x0c,0xff,0xff,0x25,0x36,0x21,0x80,0x40,0x00,
+0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0xb3,0x0a,0x00,0x0c,
+0x64,0x00,0x04,0x24,0x00,0x80,0x06,0x36,0xff,0xff,0x25,0x36,0xba,0x44,0x00,0x0c,
+0x18,0x00,0x04,0x24,0x84,0x0a,0x00,0x0c,0x03,0x00,0x04,0x24,0x21,0x30,0xa0,0x02,
+0xff,0xff,0x25,0x36,0x5c,0x00,0x80,0x16,0x21,0x20,0x00,0x00,0x2c,0x00,0xbf,0x8f,
+0x28,0x00,0xb6,0x8f,0x24,0x00,0xb5,0x8f,0x20,0x00,0xb4,0x8f,0x1c,0x00,0xb3,0x8f,
+0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,0x25,0xb0,0x02,0x3c,
+0x42,0x00,0x42,0x34,0x30,0x00,0xbd,0x27,0x00,0x00,0x40,0xa0,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x00,0x00,0x82,0xa0,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x0f,0x00,0x11,0x3c,0x21,0x20,0x00,0x00,
+0xdd,0x44,0x00,0x0c,0xff,0xff,0x25,0x36,0x21,0xa8,0x40,0x00,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,
+0x7a,0x42,0x00,0x0c,0x01,0x00,0x04,0x24,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x21,0x20,0x00,0x00,0xdd,0x44,0x00,0x0c,
+0xff,0xff,0x25,0x36,0x21,0xb0,0x40,0x00,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x00,0x60,0x81,0x40,0x64,0x00,0x04,0x24,0xb3,0x0a,0x00,0x0c,0x08,0x00,0x10,0x3c,
+0xff,0xff,0x10,0x36,0x7a,0x42,0x00,0x0c,0x21,0x20,0x00,0x00,0x01,0x00,0x12,0x3c,
+0x24,0x30,0xb0,0x02,0x25,0x30,0xd2,0x00,0xff,0xff,0x25,0x36,0xba,0x44,0x00,0x0c,
+0x21,0x20,0x00,0x00,0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0x24,0x80,0xd0,0x02,
+0x7a,0x42,0x00,0x0c,0x01,0x00,0x04,0x24,0x25,0x30,0x12,0x02,0xff,0xff,0x25,0x36,
+0xba,0x44,0x00,0x0c,0x21,0x20,0x00,0x00,0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,
+0x7a,0x42,0x00,0x0c,0x21,0x20,0x00,0x00,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,
+0x01,0x00,0x21,0x38,0x00,0x60,0x81,0x40,0x0f,0x00,0x11,0x3c,0x18,0x00,0x04,0x24,
+0xdd,0x44,0x00,0x0c,0xff,0xff,0x25,0x36,0x21,0x80,0x40,0x00,0x00,0x60,0x01,0x40,
+0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,
+0x00,0x80,0x06,0x36,0xff,0xff,0x25,0x36,0xba,0x44,0x00,0x0c,0x18,0x00,0x04,0x24,
+0x84,0x0a,0x00,0x0c,0x03,0x00,0x04,0x24,0x21,0x30,0xa0,0x02,0xff,0xff,0x25,0x36,
+0xa6,0xff,0x80,0x12,0x21,0x20,0x00,0x00,0x25,0xb0,0x02,0x3c,0x03,0x0d,0x42,0x34,
+0x00,0x00,0x53,0xa0,0xba,0x44,0x00,0x0c,0x00,0x00,0x00,0x00,0xb3,0x0a,0x00,0x0c,
+0x64,0x00,0x04,0x24,0x7a,0x42,0x00,0x0c,0x01,0x00,0x04,0x24,0xff,0xff,0x25,0x36,
+0x21,0x30,0xc0,0x02,0xba,0x44,0x00,0x0c,0x21,0x20,0x00,0x00,0xb3,0x0a,0x00,0x0c,
+0x64,0x00,0x04,0x24,0x2c,0x00,0xbf,0x8f,0x28,0x00,0xb6,0x8f,0x24,0x00,0xb5,0x8f,
+0x20,0x00,0xb4,0x8f,0x1c,0x00,0xb3,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x21,0x20,0x00,0x00,0x7a,0x42,0x00,0x08,0x30,0x00,0xbd,0x27,
+0xd0,0xff,0xbd,0x27,0x28,0x00,0xb4,0xaf,0x02,0x80,0x14,0x3c,0x2c,0x00,0xbf,0xaf,
+0x24,0x00,0xb3,0xaf,0x20,0x00,0xb2,0xaf,0x1c,0x00,0xb1,0xaf,0x18,0x00,0xb0,0xaf,
+0x68,0x15,0x86,0x26,0x0c,0x40,0xc2,0x8c,0x00,0x00,0x00,0x00,0x82,0x17,0x02,0x00,
+0x01,0x00,0x42,0x30,0x07,0x00,0x40,0x14,0x68,0x15,0x85,0x26,0x08,0x40,0xc2,0x8c,
+0x01,0x00,0x03,0x24,0x42,0x17,0x02,0x00,0x03,0x00,0x42,0x30,0xf0,0x00,0x43,0x10,
+0x25,0xb0,0x02,0x3c,0x0c,0x40,0xa2,0x8c,0x01,0x00,0x03,0x24,0x82,0x17,0x02,0x00,
+0x01,0x00,0x44,0x30,0x0a,0x00,0x83,0x10,0x00,0x00,0x00,0x00,0x2c,0x00,0xbf,0x8f,
+0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,
+0x18,0x00,0xb0,0x8f,0x21,0x10,0x00,0x00,0x08,0x00,0xe0,0x03,0x30,0x00,0xbd,0x27,
+0x08,0x40,0xa2,0x8c,0x00,0x00,0x00,0x00,0x42,0x17,0x02,0x00,0x03,0x00,0x42,0x30,
+0xf2,0xff,0x44,0x14,0x25,0xb0,0x02,0x3c,0x0e,0x0c,0x44,0x34,0x00,0x00,0x83,0x90,
+0x00,0x01,0x02,0x24,0xff,0x00,0x63,0x30,0x01,0x00,0x63,0x24,0x8b,0x01,0x62,0x10,
+0x00,0x00,0x00,0x00,0x00,0x00,0x83,0xa0,0x68,0x15,0x84,0x26,0x10,0x40,0x82,0x8c,
+0x01,0x00,0x03,0x24,0x82,0x17,0x02,0x00,0xa4,0x01,0x43,0x10,0x0f,0x00,0x10,0x3c,
+0xc7,0x42,0x92,0x90,0x68,0x15,0x90,0x26,0xc6,0x42,0x03,0x92,0x25,0xb0,0x11,0x3c,
+0x62,0x0c,0x22,0x36,0x00,0x00,0x52,0xa0,0x17,0x01,0x60,0x10,0x01,0x00,0x02,0x24,
+0x03,0x0d,0x23,0x36,0x00,0x00,0x62,0x90,0x00,0x00,0x00,0x00,0x70,0x00,0x42,0x30,
+0x3e,0x01,0x40,0x14,0x63,0x0c,0x23,0x36,0xc4,0x42,0x02,0x96,0x00,0x00,0x00,0x00,
+0x23,0x20,0x52,0x00,0x2b,0x18,0x52,0x00,0x23,0x10,0x42,0x02,0x0a,0x10,0x83,0x00,
+0x03,0x00,0x42,0x2c,0x0b,0x01,0x40,0x10,0x00,0x00,0x00,0x00,0xc4,0x42,0x03,0x96,
+0x63,0x0c,0x22,0x36,0x00,0x00,0x43,0xa0,0x68,0x15,0x83,0x26,0xc3,0x42,0x62,0x90,
+0x08,0x40,0x66,0x8c,0xc2,0x42,0x72,0xa0,0x23,0x20,0x52,0x00,0x2b,0x38,0x42,0x02,
+0x23,0x50,0x42,0x02,0x02,0x2c,0x06,0x00,0x0b,0x50,0x87,0x00,0x3f,0x00,0xa5,0x30,
+0x3f,0x00,0xc4,0x30,0x24,0x00,0x02,0x24,0x20,0x00,0x03,0x24,0x23,0x10,0x44,0x00,
+0x2d,0x01,0x40,0x15,0x23,0x18,0x65,0x00,0x21,0x30,0x80,0x00,0x21,0x48,0xa0,0x00,
+0x02,0x80,0x0b,0x3c,0x68,0x15,0x83,0x26,0x80,0x10,0x06,0x00,0x21,0x10,0x43,0x00,
+0x0c,0x40,0x63,0x8c,0x18,0x40,0x44,0x8c,0xff,0x03,0x67,0x30,0x1b,0x01,0xe0,0x10,
+0x82,0x2d,0x04,0x00,0x00,0x02,0x62,0x30,0x04,0x00,0x40,0x10,0x18,0x00,0xe5,0x00,
+0x00,0xfc,0x02,0x24,0x25,0x38,0xe2,0x00,0x18,0x00,0xe5,0x00,0x82,0x22,0x03,0x00,
+0xff,0x03,0x84,0x30,0x00,0x02,0x83,0x30,0x12,0x10,0x00,0x00,0x02,0x12,0x02,0x00,
+0x03,0x00,0x60,0x10,0xff,0x03,0x48,0x30,0x00,0xfc,0x02,0x24,0x25,0x20,0x82,0x00,
+0x18,0x00,0x85,0x00,0x80,0x2d,0x05,0x00,0x25,0xb0,0x06,0x3c,0x80,0x0c,0xc7,0x34,
+0x94,0x0c,0xc6,0x34,0x12,0x20,0x00,0x00,0x02,0x22,0x04,0x00,0x3f,0x00,0x82,0x30,
+0x00,0x14,0x02,0x00,0x25,0x28,0xa2,0x00,0x25,0x28,0xa8,0x00,0x10,0x00,0xa5,0xaf,
+0x00,0x00,0xe5,0xac,0x00,0x00,0xc3,0x8c,0xff,0x0f,0x02,0x3c,0xc0,0x03,0x84,0x30,
+0xff,0xff,0x42,0x34,0x80,0x25,0x04,0x00,0x24,0x18,0x62,0x00,0x25,0x18,0x64,0x00,
+0x10,0x00,0xa3,0xaf,0x00,0x00,0xc3,0xac,0x68,0x15,0x83,0x26,0x08,0x40,0x62,0x8c,
+0x00,0x00,0x00,0x00,0x08,0x01,0x40,0x04,0xc0,0x28,0x09,0x00,0x21,0x28,0xa3,0x00,
+0xac,0x40,0xa3,0x90,0x25,0xb0,0x04,0x3c,0x22,0x0a,0x82,0x34,0x00,0x00,0x43,0xa0,
+0xad,0x40,0xa6,0x90,0x23,0x0a,0x82,0x34,0x24,0x0a,0x87,0x34,0x00,0x00,0x46,0xa0,
+0xae,0x40,0xa3,0x90,0x25,0x0a,0x86,0x34,0x26,0x0a,0x88,0x34,0x00,0x00,0xe3,0xa0,
+0xaf,0x40,0xa2,0x90,0x27,0x0a,0x87,0x34,0x28,0x0a,0x89,0x34,0x00,0x00,0xc2,0xa0,
+0xb0,0x40,0xa3,0x90,0x29,0x0a,0x84,0x34,0x00,0x00,0x03,0xa1,0xb1,0x40,0xa2,0x90,
+0x00,0x00,0x00,0x00,0x00,0x00,0xe2,0xa0,0xb2,0x40,0xa3,0x90,0x00,0x00,0x00,0x00,
+0x00,0x00,0x23,0xa1,0xb3,0x40,0xa2,0x90,0x00,0x00,0x00,0x00,0x00,0x00,0x82,0xa0,
+0x8e,0x7d,0x63,0x91,0x22,0x00,0x02,0x24,0x03,0x00,0x62,0x10,0x92,0x00,0x02,0x24,
+0x62,0xff,0x62,0x14,0x00,0x00,0x00,0x00,0x68,0x15,0x82,0x26,0x08,0x40,0x43,0x8c,
+0x01,0x00,0x44,0x39,0x24,0x00,0x02,0x24,0x02,0x1a,0x03,0x00,0x3f,0x00,0x63,0x30,
+0x01,0x00,0x84,0x30,0x04,0x01,0x80,0x10,0x23,0x28,0x43,0x00,0x42,0x18,0x0a,0x00,
+0x40,0x10,0x03,0x00,0x21,0x50,0x43,0x00,0x68,0x15,0x83,0x26,0xc3,0x42,0x62,0x90,
+0x00,0x00,0x00,0x00,0x2b,0x10,0x42,0x02,0x08,0x01,0x40,0x10,0x21,0x20,0x00,0x00,
+0x2b,0x10,0x45,0x01,0x07,0x00,0x40,0x10,0x24,0x00,0x04,0x24,0x08,0x40,0x62,0x8c,
+0x00,0x00,0x00,0x00,0x02,0x12,0x02,0x00,0x3f,0x00,0x42,0x30,0x21,0x20,0x4a,0x00,
+0x68,0x15,0x83,0x26,0x80,0x10,0x04,0x00,0x10,0x40,0x66,0x8c,0x21,0x10,0x43,0x00,
+0x18,0x40,0x44,0x8c,0x82,0x3a,0x06,0x00,0xff,0x03,0xe7,0x30,0xf0,0x00,0xe0,0x10,
+0x82,0x2d,0x04,0x00,0x00,0x02,0xe2,0x30,0x04,0x00,0x40,0x10,0x18,0x00,0xe5,0x00,
+0x00,0xfc,0x02,0x24,0x25,0x38,0xe2,0x00,0x18,0x00,0xe5,0x00,0x02,0x25,0x06,0x00,
+0xff,0x03,0x84,0x30,0x00,0x02,0x83,0x30,0x12,0x10,0x00,0x00,0x02,0x12,0x02,0x00,
+0x03,0x00,0x60,0x10,0xff,0x03,0x48,0x30,0x00,0xfc,0x02,0x24,0x25,0x20,0x82,0x00,
+0x18,0x00,0x85,0x00,0x80,0x2d,0x05,0x00,0x25,0xb0,0x06,0x3c,0x88,0x0c,0xc7,0x34,
+0x9c,0x0c,0xc6,0x34,0x12,0x20,0x00,0x00,0x02,0x22,0x04,0x00,0x3f,0x00,0x82,0x30,
+0x00,0x14,0x02,0x00,0x25,0x28,0xa2,0x00,0x25,0x28,0xa8,0x00,0x10,0x00,0xa5,0xaf,
+0x00,0x00,0xe5,0xac,0x00,0x00,0xc3,0x8c,0xff,0x0f,0x02,0x3c,0xc0,0x03,0x84,0x30,
+0xff,0xff,0x42,0x34,0x80,0x25,0x04,0x00,0x24,0x18,0x62,0x00,0x25,0x18,0x64,0x00,
+0x10,0x00,0xa3,0xaf,0x00,0x00,0xc3,0xac,0x95,0x54,0x00,0x08,0x00,0x00,0x00,0x00,
+0x80,0x0c,0x42,0x34,0x00,0x00,0x43,0x8c,0xc0,0xff,0x02,0x3c,0x21,0x88,0x00,0x00,
+0x24,0x28,0x62,0x00,0xc0,0xff,0x04,0x3c,0x8a,0x55,0x00,0x08,0x18,0x40,0xc3,0x24,
+0x01,0x00,0x31,0x26,0x25,0x00,0x22,0x2e,0x0d,0x00,0x40,0x10,0x02,0x80,0x0b,0x3c,
+0x00,0x00,0x62,0x8c,0x00,0x00,0x00,0x00,0x24,0x10,0x44,0x00,0xf8,0xff,0x45,0x14,
+0x04,0x00,0x63,0x24,0x08,0x40,0xc2,0x8c,0xc0,0xff,0x03,0x24,0x3f,0x00,0x24,0x32,
+0x24,0x10,0x43,0x00,0x25,0x10,0x44,0x00,0x08,0x40,0xc2,0xac,0x02,0x80,0x0b,0x3c,
+0x8e,0x7d,0x63,0x91,0x22,0x00,0x02,0x24,0x3e,0x00,0x62,0x10,0x92,0x00,0x02,0x24,
+0x3d,0x00,0x62,0x10,0x25,0xb0,0x02,0x3c,0x25,0xb0,0x02,0x3c,0x24,0x0a,0x42,0x34,
+0x00,0x00,0x44,0x8c,0x3f,0x3f,0x03,0x3c,0x3f,0x3f,0x63,0x34,0x24,0x20,0x83,0x00,
+0x02,0x80,0x02,0x3c,0x02,0x80,0x03,0x3c,0x16,0x56,0x53,0x24,0x1e,0x57,0x72,0x24,
+0x21,0x88,0x00,0x00,0xb1,0x55,0x00,0x08,0x10,0x00,0xa4,0xaf,0xd4,0x45,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x47,0x00,0x40,0x10,0x68,0x15,0x85,0x26,0x01,0x00,0x31,0x26,
+0x21,0x00,0x22,0x2e,0x17,0x00,0x40,0x10,0x68,0x15,0x84,0x26,0xc0,0x80,0x11,0x00,
+0x10,0x00,0xa4,0x27,0x21,0x28,0x13,0x02,0xd4,0x45,0x00,0x0c,0x04,0x00,0x06,0x24,
+0x21,0x28,0x12,0x02,0x10,0x00,0xa4,0x27,0xf0,0xff,0x40,0x14,0x04,0x00,0x06,0x24,
+0x68,0x15,0x85,0x26,0x08,0x40,0xa3,0x8c,0xc0,0xff,0x02,0x3c,0xff,0xff,0x42,0x34,
+0x3f,0x00,0x24,0x32,0x24,0x18,0x62,0x00,0x00,0x24,0x04,0x00,0xff,0x7f,0x02,0x3c,
+0x25,0x18,0x64,0x00,0xff,0xff,0x42,0x34,0x24,0x18,0x62,0x00,0x08,0x40,0xa3,0xac,
+0x68,0x15,0x84,0x26,0x0c,0x40,0x83,0x8c,0x00,0x40,0x02,0x3c,0x25,0x18,0x62,0x00,
+0x25,0xb0,0x02,0x3c,0x0e,0x0c,0x42,0x34,0x0c,0x40,0x83,0xac,0x00,0x00,0x40,0xa0,
+0x8f,0x54,0x00,0x08,0x68,0x15,0x85,0x26,0xc6,0x42,0x02,0xa2,0xba,0x54,0x00,0x08,
+0xc4,0x42,0x12,0xa6,0xda,0x53,0x00,0x0c,0x00,0x00,0x00,0x00,0xc9,0x54,0x00,0x08,
+0xc4,0x42,0x12,0xa6,0x25,0xb0,0x02,0x3c,0x88,0x0c,0x42,0x34,0x00,0x00,0x44,0x8c,
+0x02,0x80,0x03,0x3c,0x68,0x15,0x66,0x24,0xc0,0xff,0x02,0x3c,0x24,0x28,0x82,0x00,
+0x21,0x88,0x00,0x00,0xc0,0xff,0x04,0x3c,0xe6,0x55,0x00,0x08,0x18,0x40,0xc3,0x24,
+0x01,0x00,0x31,0x26,0x25,0x00,0x22,0x2e,0xb8,0xff,0x40,0x10,0x25,0xb0,0x02,0x3c,
+0x00,0x00,0x62,0x8c,0x00,0x00,0x00,0x00,0x24,0x10,0x44,0x00,0xf8,0xff,0x45,0x14,
+0x04,0x00,0x63,0x24,0x08,0x40,0xc2,0x8c,0x3f,0x00,0x23,0x32,0xff,0xc0,0x04,0x24,
+0x24,0x10,0x44,0x00,0x00,0x1a,0x03,0x00,0x25,0x10,0x43,0x00,0x9c,0x55,0x00,0x08,
+0x08,0x40,0xc2,0xac,0x08,0x40,0xa3,0x8c,0xc0,0xff,0x02,0x3c,0xff,0xff,0x42,0x34,
+0x3f,0x00,0x24,0x32,0x24,0x18,0x62,0x00,0x00,0x24,0x04,0x00,0x25,0x18,0x64,0x00,
+0x00,0x80,0x02,0x3c,0xc5,0x55,0x00,0x08,0x25,0x18,0x62,0x00,0xcc,0xff,0x02,0x24,
+0x00,0x00,0x62,0xa0,0xcd,0x54,0x00,0x08,0x68,0x15,0x83,0x26,0x25,0xb0,0x02,0x3c,
+0x94,0x0c,0x43,0x34,0x80,0x0c,0x42,0x34,0x00,0x00,0x44,0xac,0x00,0x00,0x60,0xac,
+0x0d,0x55,0x00,0x08,0x68,0x15,0x83,0x26,0x2f,0x00,0xe0,0x10,0x21,0x30,0x00,0x00,
+0x2b,0x10,0x42,0x01,0x21,0x20,0x8a,0x00,0x00,0x00,0x42,0x38,0x24,0x00,0x06,0x24,
+0x2b,0x18,0x43,0x01,0x0b,0x30,0x82,0x00,0xcd,0xfe,0x60,0x10,0x20,0x00,0x09,0x24,
+0x68,0x15,0x83,0x26,0x0a,0x40,0x62,0x94,0x02,0x80,0x0b,0x3c,0x3f,0x00,0x42,0x30,
+0xe0,0x54,0x00,0x08,0x21,0x48,0x4a,0x00,0x21,0x28,0xa3,0x00,0xb4,0x41,0xa3,0x90,
+0x25,0xb0,0x04,0x3c,0x22,0x0a,0x82,0x34,0x00,0x00,0x43,0xa0,0xb5,0x41,0xa6,0x90,
+0x23,0x0a,0x82,0x34,0x24,0x0a,0x87,0x34,0x00,0x00,0x46,0xa0,0xb6,0x41,0xa3,0x90,
+0x25,0x0a,0x86,0x34,0x26,0x0a,0x88,0x34,0x00,0x00,0xe3,0xa0,0xb7,0x41,0xa2,0x90,
+0x27,0x0a,0x87,0x34,0x28,0x0a,0x89,0x34,0x00,0x00,0xc2,0xa0,0xb8,0x41,0xa3,0x90,
+0x29,0x0a,0x84,0x34,0x00,0x00,0x03,0xa1,0xb9,0x41,0xa2,0x90,0x00,0x00,0x00,0x00,
+0x00,0x00,0xe2,0xa0,0xba,0x41,0xa3,0x90,0x00,0x00,0x00,0x00,0x00,0x00,0x23,0xa1,
+0xbb,0x41,0xa2,0x90,0x2d,0x55,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xa0,
+0xad,0x54,0x00,0x08,0x68,0x15,0x84,0x26,0x23,0x10,0x8a,0x00,0x2b,0x18,0x44,0x01,
+0x2b,0x20,0x45,0x01,0x0b,0x30,0x43,0x00,0xa1,0xfe,0x80,0x14,0x23,0x48,0xaa,0x00,
+0xde,0x54,0x00,0x08,0x21,0x48,0x00,0x00,0xff,0xff,0x43,0x25,0x42,0x18,0x03,0x00,
+0x40,0x10,0x03,0x00,0x21,0x10,0x43,0x00,0x40,0x55,0x00,0x08,0x01,0x00,0x4a,0x24,
+0x25,0xb0,0x02,0x3c,0x9c,0x0c,0x43,0x34,0x88,0x0c,0x42,0x34,0x00,0x00,0x44,0xac,
+0x00,0x00,0x60,0xac,0x95,0x54,0x00,0x08,0x00,0x00,0x00,0x00,0x08,0x40,0x62,0x8c,
+0x00,0x00,0x00,0x00,0x02,0x12,0x02,0x00,0x3f,0x00,0x42,0x30,0x23,0x18,0x4a,0x00,
+0x2b,0x10,0x42,0x01,0x4e,0x55,0x00,0x08,0x0b,0x20,0x62,0x00,0xff,0xff,0x05,0x36,
+0x60,0x00,0x06,0x24,0xba,0x44,0x00,0x0c,0x24,0x00,0x04,0x24,0x84,0x0a,0x00,0x0c,
+0xe8,0x03,0x04,0x24,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x01,0x00,0x21,0x38,
+0x00,0x60,0x81,0x40,0x24,0x00,0x04,0x24,0xdd,0x44,0x00,0x0c,0xff,0xff,0x05,0x36,
+0x1f,0x00,0x52,0x30,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0xb3,0x0a,0x00,0x0c,0x64,0x00,0x04,0x24,0xb4,0x54,0x00,0x08,0x68,0x15,0x90,0x26,
+0x00,0xff,0x84,0x30,0x02,0x22,0x04,0x00,0x08,0x00,0x80,0x10,0x02,0x80,0x02,0x3c,
+0xff,0x00,0x02,0x24,0x04,0x00,0x82,0x10,0xcc,0xff,0x03,0x24,0x02,0x80,0x02,0x3c,
+0x08,0x00,0xe0,0x03,0x4e,0x58,0x43,0xa0,0x02,0x80,0x02,0x3c,0x08,0x00,0xe0,0x03,
+0x4e,0x58,0x44,0xa0,0x02,0x24,0x04,0x00,0xff,0x00,0x84,0x30,0xc0,0x10,0x04,0x00,
+0x21,0x10,0x44,0x00,0x80,0x10,0x02,0x00,0x21,0x10,0x44,0x00,0x02,0x80,0x03,0x3c,
+0x80,0x10,0x02,0x00,0x68,0x15,0x63,0x24,0x20,0x00,0x84,0x2c,0x09,0x00,0x80,0x10,
+0x21,0x10,0x43,0x00,0x68,0x51,0x43,0x8c,0x25,0xb0,0x02,0x3c,0xc4,0x02,0x42,0x34,
+0x02,0x19,0x03,0x00,0x7f,0x00,0x63,0x30,0x00,0x00,0x43,0xac,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x02,0x80,0x02,0x3c,0x44,0x79,0x43,0x8c,0x25,0xb0,0x02,0x3c,
+0xc4,0x02,0x42,0x34,0x02,0x19,0x03,0x00,0x7f,0x00,0x63,0x30,0x00,0x00,0x43,0xac,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0xff,0x00,0x85,0x30,0xd2,0xff,0xa3,0x24,
+0xfe,0xff,0xa2,0x24,0xda,0xff,0xa4,0x24,0x04,0x00,0x63,0x2c,0x08,0x00,0x84,0x2c,
+0x06,0x00,0x60,0x14,0xff,0x00,0x42,0x30,0xf0,0xff,0xa2,0x24,0xfc,0xff,0xa3,0x24,
+0x16,0x00,0x46,0x2c,0x03,0x00,0x80,0x10,0xff,0x00,0x62,0x30,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0xfa,0xff,0xa3,0x24,0xfc,0xff,0xc0,0x10,0x21,0x10,0xa0,0x00,
+0x08,0x00,0xe0,0x03,0xff,0x00,0x62,0x30,0x25,0xb0,0x04,0x3c,0x03,0x0d,0x85,0x34,
+0x00,0x00,0xa3,0x90,0x2d,0x0a,0x84,0x34,0xff,0x00,0x63,0x30,0x08,0x00,0x63,0x34,
+0x00,0x00,0xa3,0xa0,0x00,0x00,0xa2,0x90,0x00,0x00,0x00,0x00,0xf7,0x00,0x42,0x30,
+0x00,0x00,0xa2,0xa0,0x00,0x00,0x83,0x90,0x00,0x00,0x00,0x00,0x3f,0x00,0x63,0x30,
+0x00,0x00,0x83,0xa0,0x00,0x00,0x82,0x90,0x80,0xff,0x03,0x24,0x25,0x10,0x43,0x00,
+0x00,0x00,0x82,0xa0,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x25,0xb0,0x02,0x3c,
+0xff,0x00,0x03,0x3c,0x82,0x01,0x49,0x34,0x81,0x01,0x48,0x34,0x24,0x10,0x83,0x00,
+0x02,0x3c,0x02,0x00,0x00,0xff,0x63,0x34,0x02,0x80,0x02,0x3c,0x68,0x15,0x45,0x24,
+0x02,0x32,0x04,0x00,0x01,0x00,0x02,0x24,0x24,0x20,0x83,0x00,0xc2,0x4c,0xa2,0xa0,
+0xb0,0x4c,0xa0,0xac,0xb4,0x4c,0xa0,0xac,0xb8,0x4c,0xa0,0xac,0x06,0x00,0x80,0x14,
+0xbc,0x4c,0xa0,0xac,0x00,0x00,0x02,0x91,0x00,0x00,0x23,0x91,0xc0,0x4c,0xa2,0xa0,
+0x08,0x00,0xe0,0x03,0xc1,0x4c,0xa3,0xa0,0xc1,0x4c,0xa7,0xa0,0x08,0x00,0xe0,0x03,
+0xc0,0x4c,0xa6,0xa0,0x02,0x80,0x03,0x3c,0x68,0x15,0x63,0x24,0xc1,0x4c,0x66,0x90,
+0xc0,0x4c,0x65,0x90,0x25,0xb0,0x02,0x3c,0x82,0x01,0x44,0x34,0x81,0x01,0x42,0x34,
+0x00,0x00,0x45,0xa0,0x00,0x00,0x86,0xa0,0x08,0x00,0xe0,0x03,0xc2,0x4c,0x60,0xa0,
+0x02,0x80,0x08,0x3c,0x68,0x15,0x04,0x25,0xc2,0x4c,0x82,0x90,0x00,0x00,0x00,0x00,
+0x15,0x00,0x40,0x10,0x21,0x18,0x00,0x00,0xb4,0x4c,0x82,0x8c,0xb0,0x4c,0x85,0x8c,
+0x25,0xb0,0x03,0x3c,0x40,0x11,0x02,0x00,0x2b,0x10,0xa2,0x00,0x82,0x01,0x67,0x34,
+0x0f,0x00,0x40,0x10,0x81,0x01,0x66,0x34,0xc1,0x4c,0x83,0x90,0xc0,0x4c,0x82,0x90,
+0xf0,0x00,0x63,0x30,0x1f,0x00,0x42,0x30,0x00,0x00,0xc2,0xa0,0x00,0x00,0xe3,0xa0,
+0x68,0x15,0x02,0x25,0x01,0x00,0x03,0x24,0xbc,0x4c,0x40,0xac,0xb0,0x4c,0x40,0xac,
+0xb4,0x4c,0x40,0xac,0xb8,0x4c,0x40,0xac,0x08,0x00,0xe0,0x03,0x21,0x10,0x60,0x00,
+0xb8,0x4c,0x82,0x8c,0x25,0xb0,0x03,0x3c,0x82,0x01,0x69,0x34,0x40,0x11,0x02,0x00,
+0x2b,0x10,0xa2,0x00,0x0e,0x00,0x40,0x14,0x81,0x01,0x66,0x34,0xbc,0x4c,0x82,0x8c,
+0x00,0x00,0x00,0x00,0x40,0x11,0x02,0x00,0x2b,0x10,0xa2,0x00,0x08,0x00,0x40,0x14,
+0x00,0x00,0x00,0x00,0xc1,0x4c,0x83,0x90,0xc0,0x4c,0x82,0x90,0x00,0x00,0x00,0x00,
+0x00,0x00,0xc2,0xa0,0x00,0x00,0x23,0xa1,0xf7,0x56,0x00,0x08,0x68,0x15,0x02,0x25,
+0xc1,0x4c,0x83,0x90,0xc0,0x4c,0x82,0x90,0xf0,0x00,0x63,0x30,0x7f,0x00,0x42,0x30,
+0x00,0x00,0xc2,0xa0,0x00,0x00,0x23,0xa1,0xf7,0x56,0x00,0x08,0x68,0x15,0x02,0x25,
+0x02,0x00,0x03,0x24,0x02,0x80,0x02,0x3c,0x08,0x00,0xe0,0x03,0x3d,0x58,0x43,0xa0,
+0xcc,0xff,0x03,0x24,0x02,0x80,0x02,0x3c,0x08,0x00,0xe0,0x03,0x3d,0x58,0x43,0xa0,
+0x25,0xb0,0x03,0x3c,0x33,0x02,0x65,0x34,0x00,0x11,0x04,0x00,0x00,0x00,0xa2,0xa0,
+0x30,0x02,0x63,0x34,0x00,0x00,0x65,0x8c,0x0f,0x00,0x02,0x3c,0xff,0xff,0x42,0x34,
+0x24,0x28,0xa2,0x00,0x01,0x00,0x03,0x24,0x04,0x18,0x83,0x00,0x02,0x00,0xa0,0x10,
+0x21,0x10,0x00,0x00,0xff,0xff,0x62,0x30,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0xe0,0xff,0xbd,0x27,0x14,0x00,0xb1,0xaf,0x25,0xb0,0x11,0x3c,0x18,0x00,0xb2,0xaf,
+0x4c,0x00,0x22,0x36,0x1c,0x00,0xbf,0xaf,0x10,0x00,0xb0,0xaf,0x00,0x00,0x44,0x90,
+0x02,0x80,0x03,0x3c,0x02,0x00,0x02,0x24,0xff,0x00,0x84,0x30,0x07,0x00,0x82,0x10,
+0x68,0x15,0x72,0x24,0x1c,0x00,0xbf,0x8f,0x18,0x00,0xb2,0x8f,0x14,0x00,0xb1,0x8f,
+0x10,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,0xe6,0x63,0x43,0x96,
+0x01,0x00,0x02,0x24,0xf7,0xff,0x62,0x14,0x21,0x20,0x00,0x00,0x22,0x57,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x04,0x00,0x04,0x24,0x22,0x57,0x00,0x0c,0x21,0x80,0x40,0x00,
+0x25,0x80,0x02,0x02,0x33,0x02,0x23,0x36,0x08,0x00,0x02,0x24,0xff,0xff,0x10,0x32,
+0x40,0x00,0x25,0x36,0x00,0x00,0x62,0xa0,0xea,0xff,0x00,0x16,0x00,0x00,0x00,0x00,
+0x00,0x00,0xa2,0x94,0xe4,0x63,0x43,0x96,0xff,0xdf,0x42,0x30,0x00,0x20,0x44,0x34,
+0x01,0x00,0x63,0x24,0xe4,0x63,0x43,0xa6,0x00,0x00,0xa2,0xa4,0x00,0x00,0xa4,0xa4,
+0x3f,0x57,0x00,0x08,0x00,0x00,0x00,0x00,0x01,0x80,0x03,0x3c,0x25,0xb0,0x02,0x3c,
+0x18,0x03,0x42,0x34,0x80,0x5d,0x63,0x24,0x00,0x00,0x43,0xac,0x63,0x00,0x02,0x24,
+0xff,0xff,0x42,0x24,0xff,0xff,0x41,0x04,0xff,0xff,0x42,0x24,0x02,0x80,0x02,0x3c,
+0x88,0x7d,0x45,0x94,0x02,0x80,0x03,0x3c,0x02,0x80,0x02,0x3c,0x8b,0x7d,0x66,0x90,
+0x98,0x7d,0x47,0x90,0x02,0x80,0x03,0x3c,0x02,0x80,0x02,0x3c,0xa3,0x7d,0x69,0x90,
+0xa5,0x7d,0x4a,0x90,0x02,0x80,0x03,0x3c,0x02,0x80,0x02,0x3c,0xa8,0x7d,0x6b,0x90,
+0xaa,0x7d,0x4c,0x90,0x07,0x00,0x03,0x24,0x02,0x80,0x02,0x3c,0x25,0xb0,0x04,0x3c,
+0x95,0x7d,0x43,0xa0,0xb0,0x03,0x84,0x34,0x02,0x80,0x02,0x3c,0x02,0x80,0x18,0x3c,
+0x8a,0x7d,0x08,0x93,0x00,0x00,0x85,0xac,0x96,0x7d,0x40,0xa0,0x02,0x80,0x02,0x3c,
+0x00,0x00,0x86,0xac,0x02,0x80,0x0f,0x3c,0x97,0x7d,0x40,0xa0,0x02,0x80,0x02,0x3c,
+0x00,0x00,0x87,0xac,0x68,0x15,0xee,0x25,0xb8,0x7d,0x40,0xa0,0xfd,0xff,0x02,0x24,
+0xd5,0x4a,0xc2,0xa1,0x01,0x00,0x03,0x24,0x00,0x78,0x02,0x24,0xd4,0x4a,0xc3,0xa1,
+0xd8,0x4a,0xc2,0xa5,0xff,0x07,0x03,0x24,0x0f,0x00,0x0d,0x31,0x02,0x00,0x02,0x24,
+0xda,0x4a,0xc3,0xa5,0x00,0x00,0x88,0xac,0x00,0x00,0x89,0xac,0x00,0x00,0x8a,0xac,
+0x00,0x00,0x8b,0xac,0x00,0x00,0x8c,0xac,0x17,0x00,0xa2,0x11,0x02,0x80,0x02,0x3c,
+0x8a,0x7d,0x02,0x93,0x01,0x00,0x03,0x24,0x0f,0x00,0x42,0x30,0x05,0x00,0x43,0x10,
+0x00,0x00,0x00,0x00,0x02,0x80,0x02,0x3c,0xca,0x7d,0x40,0xa4,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x00,0x80,0x02,0x3c,0x68,0x15,0xe4,0x25,0x02,0xbc,0x42,0x34,
+0x68,0x4b,0x82,0xac,0x15,0x15,0x03,0x3c,0x02,0x02,0x02,0x3c,0x07,0x07,0x63,0x34,
+0x64,0x4b,0x82,0xac,0x02,0x80,0x02,0x3c,0x60,0x4b,0x83,0xac,0xca,0x7d,0x40,0xa4,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x8f,0x7d,0x44,0x90,0x06,0x00,0x03,0x24,
+0x15,0x00,0x83,0x10,0x0b,0x00,0x02,0x24,0x0a,0x00,0x82,0x10,0x00,0xe0,0x02,0x3c,
+0x68,0x15,0xe4,0x25,0x00,0xb2,0x42,0x34,0x00,0x1c,0x03,0x3c,0x68,0x4b,0x82,0xac,
+0x00,0x1c,0x63,0x34,0x00,0x04,0x02,0x24,0x60,0x4b,0x83,0xac,0x9a,0x57,0x00,0x08,
+0x64,0x4b,0x82,0xac,0x00,0x80,0x02,0x3c,0x00,0xbc,0x42,0x34,0x15,0x15,0x03,0x3c,
+0x68,0x4b,0xc2,0xad,0x07,0x07,0x63,0x34,0x03,0x03,0x02,0x3c,0x60,0x4b,0xc3,0xad,
+0x9a,0x57,0x00,0x08,0x64,0x4b,0xc2,0xad,0x00,0xc0,0x02,0x3c,0x00,0xb2,0x42,0x34,
+0x1c,0x1c,0x03,0x3c,0x68,0x4b,0xc2,0xad,0x07,0x07,0x63,0x34,0x00,0x04,0x02,0x24,
+0x60,0x4b,0xc3,0xad,0x9a,0x57,0x00,0x08,0x64,0x4b,0xc2,0xad,0x25,0xb0,0x02,0x3c,
+0x4d,0x00,0x44,0x34,0xff,0x00,0x03,0x3c,0xec,0x02,0x42,0x34,0x00,0x00,0x43,0xac,
+0x00,0x00,0x80,0xa0,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x01,0x80,0x03,0x3c,
+0x25,0xb0,0x02,0x3c,0x64,0x5f,0x63,0x24,0x18,0x03,0x42,0x34,0x00,0x00,0x43,0xac,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x7f,0x00,0x02,0x3c,0xfd,0xbf,0x45,0x34,
+0x80,0x04,0x03,0x3c,0x25,0x28,0xa3,0x00,0x00,0x08,0x04,0x3c,0x02,0x80,0x02,0x3c,
+0x68,0x15,0x42,0x24,0x25,0x28,0xa4,0x00,0x41,0xb0,0x03,0x3c,0x00,0x00,0x65,0xac,
+0x04,0x4b,0x45,0xac,0xfc,0x4a,0x45,0xac,0x08,0x00,0x63,0x34,0x86,0x00,0x05,0x24,
+0x00,0x00,0x65,0xa4,0x08,0x4b,0x45,0xa4,0x00,0x4b,0x40,0xac,0x0a,0x4b,0x40,0xa4,
+0x0c,0x4b,0x45,0xa4,0x00,0x60,0x01,0x40,0x01,0x00,0x21,0x34,0x00,0x60,0x81,0x40,
+0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0xf8,0x57,0x00,0x08,0x00,0x00,0x00,0x00,
+0x42,0xb0,0x02,0x3c,0xa0,0xff,0x03,0x24,0x01,0x00,0x42,0x34,0xe8,0xff,0xbd,0x27,
+0x21,0x20,0x00,0x00,0x01,0x00,0x05,0x24,0x00,0x01,0x06,0x24,0x00,0x00,0x43,0xa0,
+0x10,0x00,0xbf,0xaf,0xc4,0x0c,0x00,0x0c,0x00,0x00,0x00,0x00,0x10,0x00,0xbf,0x8f,
+0x03,0x00,0x04,0x24,0x01,0x00,0x05,0x24,0x40,0x1f,0x06,0x24,0xc4,0x0c,0x00,0x08,
+0x18,0x00,0xbd,0x27,0xe8,0xff,0xbd,0x27,0x10,0x00,0xb0,0xaf,0x14,0x00,0xbf,0xaf,
+0x21,0x5b,0x00,0x0c,0x00,0x00,0x00,0x00,0x02,0x80,0x02,0x3c,0x68,0x15,0x42,0x24,
+0x48,0x01,0x03,0x24,0xe0,0x63,0x43,0xac,0xdc,0x63,0x43,0xac,0x21,0x80,0x40,0x00,
+0x1f,0x00,0x03,0x24,0xff,0xff,0x63,0x24,0xc4,0x4c,0x40,0xa4,0xc6,0x4c,0x40,0xa4,
+0xc8,0x4c,0x40,0xa4,0xca,0x4c,0x40,0xa4,0xcc,0x4c,0x40,0xa4,0xce,0x4c,0x40,0xa4,
+0xd0,0x4c,0x40,0xa4,0xd2,0x4c,0x40,0xa4,0xd4,0x4c,0x40,0xa4,0xf5,0xff,0x61,0x04,
+0x24,0x00,0x42,0x24,0x25,0xb0,0x02,0x3c,0x10,0x00,0x03,0x24,0xb0,0x03,0x42,0x34,
+0x02,0x80,0x04,0x3c,0x8c,0x58,0x84,0x24,0x00,0x00,0x43,0xac,0x21,0x28,0x00,0x00,
+0x97,0x45,0x00,0x0c,0x04,0x00,0x06,0x24,0xef,0x5b,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x71,0x5c,0x00,0x0c,0x8c,0x65,0x00,0xae,0xa7,0x5d,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x4b,0x5e,0x00,0x0c,0x00,0x00,0x00,0x00,0x02,0x80,0x03,0x3c,0x8e,0x7d,0x64,0x90,
+0x92,0x00,0x02,0x24,0x03,0x00,0x82,0x10,0x00,0x00,0x00,0x00,0xf7,0x5d,0x00,0x0c,
+0x00,0x00,0x00,0x00,0xdd,0x5d,0x00,0x0c,0x00,0x00,0x00,0x00,0x8b,0x5c,0x00,0x0c,
+0x00,0x00,0x00,0x00,0xe4,0x63,0x00,0xa6,0x67,0x5e,0x00,0x0c,0xe6,0x63,0x00,0xa6,
+0x14,0x00,0xbf,0x8f,0x10,0x00,0xb0,0x8f,0x02,0x80,0x04,0x3c,0x02,0x80,0x05,0x3c,
+0xf8,0x7a,0x82,0x24,0x00,0x7b,0xa3,0x24,0x18,0x00,0xbd,0x27,0x04,0x00,0x42,0xac,
+0xf8,0x7a,0x82,0xac,0x00,0x7b,0xa3,0xac,0x08,0x00,0xe0,0x03,0x04,0x00,0x63,0xac,
+0xe8,0xff,0xbd,0x27,0x10,0x00,0xb0,0xaf,0x01,0x80,0x02,0x3c,0x25,0xb0,0x10,0x3c,
+0x18,0x03,0x03,0x36,0x38,0x61,0x42,0x24,0x00,0x00,0x62,0xac,0x14,0x00,0xbf,0xaf,
+0x60,0x57,0x00,0x0c,0x00,0x00,0x00,0x00,0xd5,0x58,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x01,0x00,0x03,0x24,0x02,0x80,0x02,0x3c,0xfd,0x5a,0x00,0x0c,0xdb,0x60,0x43,0xa0,
+0xd1,0x57,0x00,0x0c,0x00,0x00,0x00,0x00,0x32,0x41,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x0b,0x58,0x00,0x0c,0x00,0x00,0x00,0x00,0x44,0x00,0x03,0x36,0x00,0x00,0x62,0x94,
+0x00,0x00,0x00,0x00,0x40,0x00,0x42,0x34,0x00,0x00,0x62,0xa4,0xd9,0x57,0x00,0x0c,
+0x00,0x00,0x00,0x00,0xfa,0x57,0x00,0x0c,0x00,0x00,0x00,0x00,0xc9,0x5a,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x8e,0x5a,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x80,0x04,0x3c,
+0xb4,0x24,0x84,0x24,0xe6,0x5a,0x00,0x0c,0x01,0x00,0x05,0x24,0x01,0x80,0x04,0x3c,
+0x08,0x1e,0x84,0x24,0xe6,0x5a,0x00,0x0c,0x02,0x00,0x05,0x24,0x81,0x4e,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x00,0x80,0x04,0x3c,0x54,0x34,0x84,0x24,0xe6,0x5a,0x00,0x0c,
+0x03,0x00,0x05,0x24,0x02,0x80,0x02,0x3c,0x98,0x7d,0x43,0x90,0x43,0x00,0x04,0x36,
+0x29,0x00,0x60,0x10,0xd8,0x00,0x10,0x36,0x07,0x00,0x02,0x24,0x2b,0x00,0x62,0x10,
+0x25,0xb0,0x04,0x3c,0x10,0x02,0x86,0x34,0x43,0x00,0x85,0x34,0x03,0x00,0x02,0x24,
+0x10,0x00,0x03,0x24,0x00,0x00,0xa2,0xa0,0xd8,0x00,0x84,0x34,0x00,0x00,0xc3,0xa0,
+0x00,0x00,0x82,0x90,0x80,0xff,0x03,0x24,0x42,0xb0,0x05,0x3c,0x25,0x10,0x43,0x00,
+0x00,0x00,0x82,0xa0,0x25,0xb0,0x04,0x3c,0x44,0x00,0x84,0x34,0x00,0x00,0x82,0x94,
+0x00,0x00,0x00,0x00,0xc0,0x00,0x42,0x34,0x00,0x00,0x82,0xa4,0x00,0x00,0xa3,0x90,
+0x00,0x00,0x00,0x00,0x01,0x00,0x63,0x34,0x00,0x00,0xa3,0xa0,0xe0,0x57,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x02,0x80,0x04,0x3c,0x08,0x00,0x84,0x24,0x21,0x28,0x00,0x00,
+0x21,0x30,0x00,0x00,0x31,0x1c,0x00,0x0c,0x21,0x38,0x00,0x00,0xf8,0x57,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x14,0x00,0xbf,0x8f,0x10,0x00,0xb0,0x8f,0x01,0x00,0x02,0x24,
+0x08,0x00,0xe0,0x03,0x18,0x00,0xbd,0x27,0x00,0x00,0x80,0xa0,0x00,0x00,0x03,0x92,
+0x80,0xff,0x02,0x24,0x25,0x18,0x62,0x00,0x00,0x00,0x03,0xa2,0x25,0xb0,0x04,0x3c,
+0x44,0x00,0x84,0x34,0x00,0x00,0x82,0x94,0x42,0xb0,0x05,0x3c,0xc0,0x00,0x42,0x34,
+0x00,0x00,0x82,0xa4,0x00,0x00,0xa3,0x90,0x00,0x00,0x00,0x00,0x01,0x00,0x63,0x34,
+0x00,0x00,0xa3,0xa0,0xe0,0x57,0x00,0x0c,0x00,0x00,0x00,0x00,0x02,0x80,0x04,0x3c,
+0x08,0x00,0x84,0x24,0x21,0x28,0x00,0x00,0x21,0x30,0x00,0x00,0x31,0x1c,0x00,0x0c,
+0x21,0x38,0x00,0x00,0xf8,0x57,0x00,0x0c,0x00,0x00,0x00,0x00,0x14,0x00,0xbf,0x8f,
+0x10,0x00,0xb0,0x8f,0x01,0x00,0x02,0x24,0x08,0x00,0xe0,0x03,0x18,0x00,0xbd,0x27,
+0x21,0x20,0x00,0x00,0x20,0xb0,0x06,0x3c,0xff,0xff,0x05,0x34,0x21,0x18,0x86,0x00,
+0x04,0x00,0x84,0x24,0x2a,0x10,0xa4,0x00,0x00,0x00,0x60,0xac,0xfb,0xff,0x40,0x10,
+0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0xb8,0xff,0xbd,0x27,
+0x25,0xb0,0x04,0x3c,0x44,0x00,0xbf,0xaf,0x40,0x00,0xbe,0xaf,0x3c,0x00,0xb7,0xaf,
+0x38,0x00,0xb6,0xaf,0x34,0x00,0xb5,0xaf,0x30,0x00,0xb4,0xaf,0x2c,0x00,0xb3,0xaf,
+0x28,0x00,0xb2,0xaf,0x24,0x00,0xb1,0xaf,0x20,0x00,0xb0,0xaf,0x0a,0x00,0x83,0x34,
+0x00,0x00,0x62,0x90,0x00,0x00,0x00,0x00,0x20,0x00,0x42,0x30,0x0c,0x00,0x40,0x10,
+0x4c,0x87,0x02,0x3c,0x00,0x00,0x62,0x90,0x00,0x00,0x00,0x00,0x10,0x00,0x42,0x30,
+0x66,0x01,0x40,0x10,0x4c,0x87,0x02,0x3c,0x54,0x00,0x83,0x34,0x50,0x00,0x82,0x34,
+0x00,0x00,0x45,0xac,0x00,0x00,0x65,0xa4,0xf9,0x58,0x00,0x08,0x02,0x80,0x03,0x3c,
+0x54,0x00,0x85,0x34,0x00,0xe0,0x42,0x34,0x50,0x00,0x84,0x34,0x12,0x01,0x03,0x24,
+0x00,0x00,0x82,0xac,0x00,0x00,0xa3,0xac,0x02,0x80,0x03,0x3c,0x68,0x15,0x62,0x24,
+0xd5,0x4a,0x43,0x90,0xda,0x4a,0x45,0x94,0x25,0xb0,0x1e,0x3c,0x1c,0x00,0xa3,0xa3,
+0x60,0x4b,0x43,0x8c,0x58,0x00,0xc6,0x37,0xff,0xff,0x04,0x24,0x10,0x00,0xa3,0xaf,
+0x64,0x4b,0x43,0x8c,0x5c,0x00,0xc7,0x37,0x60,0x00,0xc8,0x37,0x14,0x00,0xa3,0xaf,
+0x68,0x4b,0x42,0x8c,0x64,0x00,0xc9,0x37,0x8a,0x00,0xca,0x37,0x18,0x00,0xa2,0xaf,
+0x24,0x10,0x02,0x3c,0x21,0x28,0xa2,0x00,0x4c,0x81,0x02,0x3c,0x00,0xe0,0x42,0x34,
+0x00,0x00,0xc2,0xac,0x96,0x01,0x03,0x24,0x28,0x28,0x02,0x24,0x00,0x00,0xe3,0xac,
+0x89,0x00,0xcb,0x37,0x00,0x00,0x04,0xad,0x8c,0x00,0xcc,0x37,0x00,0x00,0x24,0xad,
+0x09,0x00,0x03,0x24,0x00,0x00,0x42,0xa5,0x10,0x10,0x02,0x24,0x00,0x00,0x63,0xa1,
+0x8e,0x00,0xcd,0x37,0x00,0x00,0x82,0xa5,0x0a,0x0a,0x03,0x24,0x13,0x00,0x02,0x24,
+0x90,0x00,0xce,0x37,0x00,0x00,0xa3,0xa5,0x00,0x00,0xc2,0xa1,0x25,0xb0,0x02,0x3c,
+0x40,0x00,0x03,0x24,0x91,0x00,0x42,0x34,0x00,0x00,0x43,0xa0,0x25,0xb0,0x03,0x3c,
+0x3a,0x01,0x02,0x24,0x92,0x00,0x63,0x34,0x00,0x00,0x62,0xa4,0xb5,0x00,0xd1,0x37,
+0x21,0x00,0x03,0x24,0x00,0x00,0x23,0xa2,0x10,0x00,0xa2,0x8f,0xa0,0x00,0xd2,0x37,
+0xa4,0x00,0xd3,0x37,0x00,0x00,0x42,0xae,0x14,0x00,0xa3,0x8f,0xa8,0x00,0xd4,0x37,
+0xac,0x00,0xd5,0x37,0x00,0x00,0x63,0xae,0x18,0x00,0xa2,0x8f,0x25,0xb0,0x03,0x3c,
+0xb0,0x00,0x63,0x34,0x00,0x00,0x82,0xae,0x21,0x10,0x02,0x3c,0xff,0x77,0x42,0x34,
+0x00,0x00,0xa2,0xae,0x25,0xb0,0x02,0x3c,0xd8,0x00,0x42,0x34,0x00,0x00,0x65,0xac,
+0x00,0x00,0x40,0xa0,0x1c,0x00,0xa2,0x93,0x25,0xb0,0x03,0x3c,0xb4,0x00,0x63,0x34,
+0x00,0x00,0x62,0xa0,0x25,0xb0,0x03,0x3c,0x04,0x00,0x02,0x24,0xb6,0x00,0x63,0x34,
+0x00,0x00,0x62,0xa0,0x25,0xb0,0x03,0x3c,0x0f,0x00,0x02,0x24,0xba,0x00,0x63,0x34,
+0xb9,0x00,0xdf,0x37,0x00,0x00,0xe4,0xa3,0x00,0x00,0x62,0xa4,0x25,0xb0,0x02,0x3c,
+0x1a,0x01,0x42,0x34,0x16,0x01,0xd0,0x37,0x18,0x01,0xcf,0x37,0x00,0x00,0x00,0xa6,
+0x25,0xb0,0x03,0x3c,0x00,0x00,0xe0,0xa5,0x00,0x00,0x40,0xa4,0xff,0xff,0x02,0x3c,
+0xff,0x0f,0x42,0x34,0xdc,0x00,0x63,0x34,0x00,0x00,0x62,0xac,0x2f,0x00,0x03,0x3c,
+0x25,0xb0,0x02,0x3c,0x32,0x32,0x63,0x34,0xd0,0x01,0x42,0x34,0x00,0x00,0x43,0xac,
+0x5e,0x00,0x02,0x3c,0x25,0xb0,0x03,0x3c,0x32,0x43,0x42,0x34,0xd4,0x01,0x63,0x34,
+0x00,0x00,0x62,0xac,0x08,0x00,0x03,0x3c,0x25,0xb0,0x02,0x3c,0x30,0xa5,0x63,0x34,
+0xd8,0x01,0x42,0x34,0x00,0x00,0x43,0xac,0xdc,0x01,0xc4,0x37,0x02,0x80,0x03,0x3c,
+0x49,0xa5,0x02,0x34,0x8e,0x7d,0x6d,0x90,0x00,0x00,0x82,0xac,0xc2,0x00,0x02,0x3c,
+0x1a,0x06,0x03,0x24,0x51,0x10,0x42,0x34,0xe0,0x01,0xc5,0x37,0xf4,0x01,0xc6,0x37,
+0xf8,0x01,0xc7,0x37,0x07,0x07,0x04,0x24,0x00,0x00,0xa3,0xa4,0x00,0x02,0xc8,0x37,
+0x00,0x00,0xc4,0xa4,0x26,0x00,0x03,0x24,0x00,0x00,0xe2,0xac,0x03,0x02,0xc9,0x37,
+0x04,0x00,0x02,0x24,0x00,0x00,0x03,0xa5,0x36,0x02,0xca,0x37,0x00,0x00,0x22,0xa1,
+0xc0,0x01,0x03,0x24,0x0c,0x00,0x02,0x24,0x34,0x02,0xcb,0x37,0x00,0x00,0x42,0xa1,
+0x37,0x02,0xcc,0x37,0x00,0x00,0x63,0xa5,0x03,0x00,0x02,0x24,0x22,0x00,0x03,0x24,
+0x00,0x00,0x82,0xa1,0xd6,0x00,0xa3,0x11,0x1b,0x1b,0x02,0x3c,0x13,0x13,0x02,0x3c,
+0x13,0x13,0x42,0x34,0x60,0x01,0xc3,0x37,0x64,0x01,0xc4,0x37,0x68,0x01,0xc5,0x37,
+0x7c,0x01,0xca,0x37,0x6c,0x01,0xc6,0x37,0x70,0x01,0xc7,0x37,0x74,0x01,0xc8,0x37,
+0x78,0x01,0xc9,0x37,0x00,0x00,0x62,0xac,0x00,0x00,0x82,0xac,0x02,0x80,0x03,0x3c,
+0x00,0x00,0xa2,0xac,0x00,0x00,0xc2,0xac,0x00,0x00,0xe2,0xac,0x00,0x00,0x02,0xad,
+0x00,0x00,0x22,0xad,0x00,0x00,0x42,0xad,0x8e,0x7d,0x65,0x90,0x25,0xb0,0x0c,0x3c,
+0x01,0x70,0x03,0x3c,0x80,0x01,0x82,0x35,0x08,0x5f,0x63,0x34,0x22,0x00,0x04,0x24,
+0x00,0x00,0x43,0xac,0xb5,0x00,0xa4,0x10,0x0f,0x1f,0x02,0x3c,0x92,0x00,0x02,0x24,
+0xb2,0x00,0xa2,0x10,0x0f,0x1f,0x02,0x3c,0x0f,0x10,0x02,0x3c,0x00,0xf0,0x51,0x34,
+0xf7,0x01,0x92,0x35,0x15,0xf0,0x4d,0x34,0x77,0x00,0x0e,0x24,0x84,0x01,0x87,0x35,
+0x88,0x01,0x88,0x35,0x10,0xf0,0x44,0x34,0x8c,0x01,0x85,0x35,0x05,0xf0,0x42,0x34,
+0x00,0x00,0xed,0xac,0x90,0x01,0x83,0x35,0x00,0x00,0x04,0xad,0x94,0x01,0x86,0x35,
+0x00,0x00,0xa2,0xac,0xf5,0x0f,0x02,0x24,0x00,0x00,0x71,0xac,0x25,0xb0,0x05,0x3c,
+0x00,0x00,0xc2,0xac,0x98,0x01,0x89,0x35,0x9c,0x01,0x8a,0x35,0xf0,0x0f,0x03,0x24,
+0x0d,0x00,0x02,0x24,0x00,0x00,0x23,0xad,0xa0,0x01,0x8b,0x35,0x00,0x00,0x42,0xad,
+0xa7,0x01,0xb7,0x34,0xf6,0x01,0x8c,0x35,0xff,0xff,0x02,0x24,0x00,0x00,0x6d,0xad,
+0x00,0x00,0x8e,0xa1,0x00,0x00,0x4e,0xa2,0x00,0x00,0xe2,0xa2,0x25,0xb0,0x02,0x3c,
+0xa8,0x01,0xb6,0x34,0xff,0xff,0x09,0x24,0xac,0x01,0x42,0x34,0x00,0x00,0xc9,0xae,
+0x03,0x04,0x04,0x3c,0x00,0x00,0x49,0xac,0x07,0x08,0x03,0x3c,0x25,0xb0,0x02,0x3c,
+0x01,0x02,0x84,0x34,0x05,0x06,0x63,0x34,0xb4,0x01,0xb1,0x34,0xb8,0x01,0xb2,0x34,
+0xbc,0x01,0xb3,0x34,0xb0,0x01,0x42,0x34,0x00,0x00,0x44,0xac,0x00,0x00,0x23,0xae,
+0x25,0xb0,0x02,0x3c,0x00,0x00,0x44,0xae,0x00,0x00,0x63,0xae,0x25,0xb0,0x03,0x3c,
+0x0c,0x00,0x06,0x24,0xc0,0x01,0xb4,0x34,0xc1,0x01,0xb5,0x34,0x0d,0x00,0x08,0x24,
+0xc2,0x01,0x63,0x34,0xc3,0x01,0x42,0x34,0x00,0x00,0x86,0xa2,0xc4,0x01,0xab,0x34,
+0x00,0x00,0xa6,0xa2,0xc5,0x01,0xac,0x34,0x00,0x00,0x66,0xa0,0x0e,0x00,0x07,0x24,
+0x00,0x00,0x48,0xa0,0xc6,0x01,0xaa,0x34,0xc7,0x01,0xad,0x34,0x0f,0x00,0x02,0x24,
+0x00,0x00,0x68,0xa1,0x00,0x00,0x87,0xa1,0x00,0x00,0x47,0xa1,0x00,0x00,0xa2,0xa1,
+0x57,0x01,0x02,0x3c,0x48,0x00,0xbf,0x34,0x46,0x00,0xae,0x34,0x0e,0xe2,0x42,0x34,
+0x00,0x00,0xc0,0xa5,0x4c,0x00,0xbe,0x34,0x00,0x00,0xe2,0xaf,0x4d,0x00,0xb9,0x34,
+0x80,0xff,0x02,0x24,0x00,0x00,0xc0,0xa3,0x00,0x00,0x22,0xa3,0x25,0xb0,0x02,0x3c,
+0xbc,0x00,0x03,0x24,0x40,0x00,0x42,0x34,0x00,0x00,0x43,0xa4,0x25,0xb0,0x03,0x3c,
+0x64,0x03,0xb8,0x34,0xfc,0x37,0x02,0x24,0x40,0x00,0x63,0x34,0x00,0x00,0x00,0xa3,
+0xd8,0x00,0xa7,0x34,0x00,0x00,0x62,0xa4,0x00,0x00,0xe3,0x90,0x2a,0xb0,0x04,0x3c,
+0x80,0xff,0x02,0x24,0x26,0xb0,0x06,0x3c,0x25,0x18,0x62,0x00,0x30,0x00,0x89,0x34,
+0x20,0x20,0x02,0x24,0x38,0x00,0x84,0x34,0x00,0x00,0xe3,0xa0,0x79,0x00,0xc8,0x34,
+0x00,0x00,0x82,0xa4,0x40,0x00,0x03,0x24,0x16,0x00,0x02,0x24,0x00,0x00,0x23,0xa1,
+0x94,0x00,0xaa,0x34,0x00,0x00,0x02,0xa1,0x98,0x00,0xab,0x34,0x64,0x00,0x03,0x24,
+0x22,0x00,0x02,0x24,0x00,0x00,0x43,0xa5,0x7c,0x00,0xd1,0x34,0x00,0x00,0x62,0xa5,
+0x04,0x00,0x12,0x24,0x9c,0x00,0xac,0x34,0x7a,0x00,0xc6,0x34,0x20,0x0c,0x02,0x24,
+0x0a,0x00,0x03,0x24,0x00,0x00,0xd2,0xa0,0x9a,0x00,0xad,0x34,0x00,0x00,0x22,0xa6,
+0x96,0x00,0xae,0x34,0x00,0x00,0x83,0xa1,0xff,0x03,0x02,0x24,0x02,0x00,0x03,0x24,
+0x00,0x00,0xa2,0xa5,0x00,0x00,0xc3,0xa5,0x25,0xb0,0x03,0x3c,0x20,0x00,0x02,0x24,
+0xb7,0x00,0x63,0x34,0x00,0x00,0x62,0xa0,0x25,0xb0,0x02,0x3c,0x09,0x00,0x03,0x24,
+0x89,0x00,0x42,0x34,0x00,0x00,0x43,0xa0,0x44,0x00,0xa5,0x34,0x00,0x00,0xa2,0x94,
+0x02,0x80,0x03,0x3c,0x68,0x15,0x66,0x24,0xff,0xfd,0x03,0x24,0x24,0x10,0x43,0x00,
+0x00,0x00,0xa2,0xa4,0x00,0x00,0xa3,0x94,0xd5,0x4a,0xc4,0x90,0x29,0xb0,0x02,0x3c,
+0x40,0x00,0x42,0x34,0x00,0x02,0x63,0x34,0x00,0x00,0xa3,0xa4,0x00,0x00,0x52,0xa0,
+0xd3,0x0a,0x00,0x0c,0x00,0x00,0x00,0x00,0x44,0x00,0xbf,0x8f,0x40,0x00,0xbe,0x8f,
+0x3c,0x00,0xb7,0x8f,0x38,0x00,0xb6,0x8f,0x34,0x00,0xb5,0x8f,0x30,0x00,0xb4,0x8f,
+0x2c,0x00,0xb3,0x8f,0x28,0x00,0xb2,0x8f,0x24,0x00,0xb1,0x8f,0x20,0x00,0xb0,0x8f,
+0x01,0x00,0x02,0x24,0x08,0x00,0xe0,0x03,0x48,0x00,0xbd,0x27,0x54,0x00,0x85,0x34,
+0x00,0xe0,0x42,0x34,0x50,0x00,0x84,0x34,0x12,0x01,0x03,0x24,0x00,0x00,0x82,0xac,
+0x00,0x00,0xa3,0xa4,0xf9,0x58,0x00,0x08,0x02,0x80,0x03,0x3c,0x00,0xf0,0x51,0x34,
+0xf7,0x01,0x92,0x35,0x15,0xf0,0x4d,0x34,0xad,0x59,0x00,0x08,0xff,0xff,0x0e,0x24,
+0x8b,0x59,0x00,0x08,0x1b,0x1b,0x42,0x34,0x25,0xb0,0x03,0x3c,0x25,0xb0,0x08,0x3c,
+0xfc,0x37,0x02,0x24,0x40,0x00,0x63,0x34,0x02,0x80,0x04,0x3c,0x00,0x00,0x62,0xa4,
+0x14,0x80,0x84,0x24,0xff,0x00,0x07,0x24,0xb0,0x03,0x06,0x35,0x00,0x00,0x83,0x94,
+0x00,0x00,0x00,0x00,0xff,0x00,0x62,0x30,0x21,0x18,0x68,0x00,0x0a,0x00,0x47,0x10,
+0xff,0x00,0x65,0x30,0x04,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0x62,0xac,
+0x00,0x00,0xc3,0xac,0x04,0x00,0x82,0x8c,0x08,0x00,0x84,0x24,0x00,0x00,0xc2,0xac,
+0xf2,0xff,0xa7,0x14,0x00,0x00,0x00,0x00,0x25,0xb0,0x08,0x3c,0x01,0x80,0x02,0x3c,
+0x0c,0x7a,0x44,0x24,0xff,0x00,0x07,0x24,0xb0,0x03,0x06,0x35,0x00,0x00,0x83,0x94,
+0x00,0x00,0x00,0x00,0xff,0x00,0x62,0x30,0x21,0x18,0x68,0x00,0x0a,0x00,0x47,0x10,
+0xff,0x00,0x65,0x30,0x04,0x00,0x82,0x8c,0x00,0x00,0x00,0x00,0x00,0x00,0x62,0xac,
+0x00,0x00,0xc3,0xac,0x04,0x00,0x82,0x8c,0x08,0x00,0x84,0x24,0x00,0x00,0xc2,0xac,
+0xf2,0xff,0xa7,0x14,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,
+0x01,0x80,0x02,0x3c,0x02,0x80,0x05,0x3c,0x10,0x6b,0x42,0x24,0x02,0x80,0x03,0x3c,
+0xcc,0x7d,0xa2,0xac,0x00,0x80,0x02,0x3c,0x6c,0x7e,0x60,0xac,0xcc,0x7d,0xa4,0x24,
+0x02,0x80,0x03,0x3c,0xc8,0x06,0x42,0x24,0x70,0x7e,0x60,0xa4,0x08,0x00,0x82,0xac,
+0x02,0x80,0x03,0x3c,0x00,0x80,0x02,0x3c,0x72,0x7e,0x60,0xa4,0x02,0x80,0x06,0x3c,
+0x08,0x0a,0x42,0x24,0x00,0x80,0x03,0x3c,0x74,0x7e,0xc7,0x24,0x14,0x00,0x82,0xac,
+0x38,0x08,0x63,0x24,0x02,0x80,0x02,0x3c,0x74,0x7e,0xc0,0xac,0x10,0x00,0x83,0xac,
+0x04,0x00,0xe0,0xac,0x7c,0x7e,0x40,0xa0,0x00,0x80,0x02,0x3c,0x88,0x19,0x42,0x24,
+0x3c,0x00,0x82,0xac,0x00,0x80,0x03,0x3c,0x00,0x80,0x02,0x3c,0x24,0x0c,0x63,0x24,
+0x78,0x0f,0x42,0x24,0x1c,0x00,0x83,0xac,0x20,0x00,0x82,0xac,0x00,0x80,0x03,0x3c,
+0x00,0x80,0x02,0x3c,0xc8,0x12,0x63,0x24,0x28,0x16,0x42,0x24,0x24,0x00,0x83,0xac,
+0x28,0x00,0x82,0xac,0x00,0x80,0x03,0x3c,0x01,0x80,0x02,0x3c,0x4c,0x1f,0x63,0x24,
+0xd0,0x04,0x42,0x24,0x2c,0x00,0x83,0xac,0x30,0x00,0x82,0xac,0x00,0x80,0x03,0x3c,
+0x00,0x80,0x02,0x3c,0xe4,0x19,0x63,0x24,0x00,0x03,0x42,0x24,0x38,0x00,0x83,0xac,
+0x08,0x00,0xe0,0x03,0x4c,0x00,0x82,0xac,0x25,0xb0,0x02,0x3c,0x08,0x00,0x42,0x34,
+0x00,0x00,0x43,0x8c,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x02,0x80,0x0e,0x3c,
+0x02,0x80,0x08,0x3c,0x02,0x80,0x02,0x3c,0x02,0x80,0x03,0x3c,0xf8,0x03,0x4d,0x24,
+0x00,0x14,0x6c,0x24,0x01,0x00,0x07,0x24,0x00,0x00,0xcb,0x25,0xff,0xff,0x0a,0x24,
+0x00,0x04,0x09,0x25,0x80,0x1a,0x07,0x00,0x21,0x10,0x6b,0x00,0x00,0x00,0x42,0xac,
+0x90,0x00,0x4a,0xac,0x00,0x04,0x04,0x8d,0x01,0x00,0xe7,0x24,0x08,0x00,0x45,0x24,
+0x21,0x18,0x6d,0x00,0x05,0x00,0xe6,0x28,0x04,0x00,0x82,0xac,0x00,0x00,0x44,0xac,
+0x04,0x00,0x49,0xac,0x00,0x04,0x02,0xad,0x8c,0x00,0x40,0xac,0x6c,0x00,0xa3,0xac,
+0xf0,0xff,0xc0,0x14,0x68,0x00,0xac,0xac,0x08,0x00,0xe0,0x03,0x00,0x00,0xc9,0xad,
+0x05,0x00,0xa2,0x2c,0x13,0x00,0x40,0x10,0xff,0xff,0x07,0x24,0x02,0x80,0x02,0x3c,
+0x80,0x1a,0x05,0x00,0x00,0x00,0x42,0x24,0x0e,0x00,0xa0,0x10,0x21,0x30,0x62,0x00,
+0x90,0x00,0xc3,0x8c,0xff,0xff,0x02,0x24,0x0a,0x00,0x62,0x14,0x00,0x00,0x00,0x00,
+0x8c,0x00,0xc2,0x8c,0x00,0x00,0x00,0x00,0x06,0x00,0x40,0x14,0x00,0x00,0x00,0x00,
+0x01,0x00,0x02,0x24,0x88,0x00,0xc4,0xac,0x8c,0x00,0xc2,0xac,0x90,0x00,0xc5,0xac,
+0x21,0x38,0xa0,0x00,0x08,0x00,0xe0,0x03,0x21,0x10,0xe0,0x00,0x25,0xb0,0x04,0x3c,
+0x01,0x80,0x02,0x3c,0x18,0x03,0x85,0x34,0xf4,0x6b,0x42,0x24,0xe0,0xff,0xbd,0x27,
+0x00,0x00,0xa2,0xac,0x1b,0x00,0x86,0x34,0xdb,0xff,0x03,0x24,0x27,0x00,0x84,0x34,
+0x07,0x00,0x02,0x24,0x14,0x00,0xb1,0xaf,0x10,0x00,0xb0,0xaf,0x00,0x00,0x83,0xa0,
+0x18,0x00,0xbf,0xaf,0x00,0x00,0xc2,0xa0,0x01,0x00,0x11,0x24,0x21,0x80,0x00,0x00,
+0x7a,0x42,0x00,0x0c,0x21,0x20,0x00,0x02,0x01,0x00,0x02,0x26,0xff,0x00,0x50,0x30,
+0x2b,0x18,0x30,0x02,0xfa,0xff,0x60,0x10,0x00,0x00,0x00,0x00,0x7a,0x42,0x00,0x0c,
+0x21,0x20,0x00,0x00,0x18,0x00,0xbf,0x8f,0x14,0x00,0xb1,0x8f,0x10,0x00,0xb0,0x8f,
+0x01,0x00,0x02,0x24,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,0x08,0x00,0xe0,0x03,
+0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x00,0x00,0x00,0x00,0x02,0x80,0x02,0x3c,
+0x68,0x15,0x42,0x24,0x40,0x10,0x03,0x3c,0xff,0xff,0x44,0x30,0x25,0xc0,0x83,0x00,
+0x94,0x64,0x58,0xac,0x40,0x00,0x18,0x27,0xa0,0x64,0x58,0xac,0x40,0x00,0x18,0x27,
+0xac,0x64,0x58,0xac,0x40,0x00,0x18,0x27,0xb8,0x64,0x58,0xac,0x40,0x00,0x18,0x27,
+0xe0,0xff,0xbd,0x27,0xc4,0x64,0x58,0xac,0x40,0x00,0x18,0x27,0x1c,0x00,0xb7,0xaf,
+0x18,0x00,0xb6,0xaf,0x14,0x00,0xb5,0xaf,0x10,0x00,0xb4,0xaf,0x0c,0x00,0xb3,0xaf,
+0x08,0x00,0xb2,0xaf,0x04,0x00,0xb1,0xaf,0x00,0x00,0xb0,0xaf,0xd0,0x64,0x58,0xac,
+0xa0,0x64,0x45,0x8c,0xac,0x64,0x46,0x8c,0xb8,0x64,0x47,0x8c,0xc4,0x64,0x48,0x8c,
+0xd0,0x64,0x49,0x8c,0x40,0x00,0x18,0x27,0xdc,0x64,0x58,0xac,0x21,0x50,0x00,0x03,
+0x25,0x20,0x83,0x00,0x40,0x00,0x18,0x27,0x20,0x10,0x03,0x3c,0x90,0x64,0x44,0xac,
+0x9c,0x64,0x45,0xac,0xa8,0x64,0x46,0xac,0xb4,0x64,0x47,0xac,0xc0,0x64,0x48,0xac,
+0xcc,0x64,0x49,0xac,0x25,0xb0,0x06,0x3c,0x28,0x64,0x43,0xac,0x24,0x64,0x43,0xac,
+0x34,0x64,0x43,0xac,0x30,0x64,0x43,0xac,0x40,0x64,0x43,0xac,0x3c,0x64,0x43,0xac,
+0x4c,0x64,0x43,0xac,0x48,0x64,0x43,0xac,0xe8,0x64,0x58,0xac,0x00,0x02,0x18,0x27,
+0xd8,0x64,0x4a,0xac,0x00,0x65,0x58,0xac,0x58,0x64,0x43,0xac,0x54,0x64,0x43,0xac,
+0x64,0x64,0x43,0xac,0x60,0x64,0x43,0xac,0x70,0x64,0x43,0xac,0x6c,0x64,0x43,0xac,
+0xac,0x00,0xc4,0x34,0xb0,0x00,0xc5,0x34,0x00,0x00,0x92,0x8c,0xe8,0x64,0x50,0x8c,
+0x00,0x00,0xb3,0x8c,0x21,0x10,0x04,0x3c,0x23,0x10,0x09,0x3c,0x22,0x10,0x0c,0x3c,
+0x02,0x80,0x14,0x3c,0x02,0x80,0x15,0x3c,0x02,0x80,0x16,0x3c,0x02,0x80,0x17,0x3c,
+0x24,0x10,0x05,0x3c,0x21,0x88,0x00,0x03,0x08,0x7b,0x87,0x26,0x00,0x04,0x18,0x27,
+0x10,0x7b,0xa8,0x26,0x18,0x7b,0xca,0x26,0x20,0x7b,0xeb,0x26,0x00,0x04,0x2d,0x35,
+0x00,0x40,0x8e,0x34,0x00,0x80,0x8f,0x35,0x00,0x01,0xc6,0x34,0xe4,0x64,0x50,0xac,
+0xfc,0x64,0x51,0xac,0x64,0x65,0x4d,0xac,0x28,0x65,0x52,0xac,0x34,0x65,0x4e,0xac,
+0x58,0x65,0x4f,0xac,0x4c,0x65,0x53,0xac,0x00,0x00,0xc5,0xac,0x48,0x65,0x45,0xac,
+0x68,0x65,0x43,0xac,0x74,0x65,0x58,0xac,0x7c,0x64,0x43,0xac,0x78,0x64,0x43,0xac,
+0x06,0x65,0x40,0xa4,0x05,0x65,0x40,0xa0,0x04,0x65,0x40,0xa0,0x5c,0x65,0x49,0xac,
+0x60,0x65,0x49,0xac,0x20,0x65,0x44,0xac,0x24,0x65,0x44,0xac,0x2c,0x65,0x44,0xac,
+0x30,0x65,0x44,0xac,0x50,0x65,0x4c,0xac,0x54,0x65,0x4c,0xac,0x44,0x65,0x45,0xac,
+0x6c,0x65,0x43,0xac,0x78,0x65,0x58,0xac,0x04,0x00,0x08,0xad,0x08,0x7b,0x87,0xae,
+0x04,0x00,0x4a,0xad,0x10,0x7b,0xa8,0xae,0x04,0x00,0x6b,0xad,0x18,0x7b,0xca,0xae,
+0x20,0x7b,0xeb,0xae,0x04,0x00,0xe7,0xac,0x02,0x80,0x02,0x3c,0x00,0x14,0x43,0x24,
+0x21,0x20,0xe0,0x00,0x03,0x00,0x06,0x24,0x21,0x10,0x80,0x00,0xff,0xff,0xc6,0x24,
+0x08,0x00,0x78,0xac,0x00,0x00,0x63,0xac,0x10,0x00,0x60,0xac,0x00,0x00,0x67,0xac,
+0x21,0x20,0x60,0x00,0x04,0x00,0x62,0xac,0x00,0x00,0x43,0xac,0x00,0x01,0x18,0x27,
+0xf5,0xff,0xc1,0x04,0x18,0x00,0x63,0x24,0x02,0x80,0x02,0x3c,0x10,0x7b,0x49,0x24,
+0x02,0x80,0x03,0x3c,0x02,0x80,0x02,0x3c,0x04,0x00,0x28,0x8d,0x60,0x14,0x4b,0x24,
+0x04,0x00,0xe4,0xac,0x00,0x14,0x6a,0x24,0x01,0x00,0x07,0x24,0x21,0x28,0x00,0x00,
+0x07,0x00,0x06,0x24,0x21,0x20,0xab,0x00,0x21,0x10,0xaa,0x00,0xff,0xff,0xc6,0x24,
+0x68,0x00,0x58,0xac,0x70,0x00,0x47,0xac,0x18,0x00,0xa5,0x24,0x00,0x00,0x89,0xac,
+0x04,0x00,0x88,0xac,0x00,0x00,0x04,0xad,0x00,0x01,0x18,0x27,0xf5,0xff,0xc1,0x04,
+0x21,0x40,0x80,0x00,0x02,0x80,0x02,0x3c,0x18,0x7b,0x4a,0x24,0x02,0x80,0x03,0x3c,
+0x02,0x80,0x02,0x3c,0x04,0x00,0x45,0x8d,0x20,0x15,0x4b,0x24,0x04,0x00,0x24,0xad,
+0x02,0x00,0x07,0x24,0x00,0x14,0x69,0x24,0x21,0x20,0x00,0x00,0x01,0x00,0x06,0x24,
+0x21,0x40,0x8b,0x00,0x21,0x10,0x89,0x00,0xff,0xff,0xc6,0x24,0x28,0x01,0x58,0xac,
+0x30,0x01,0x47,0xac,0x18,0x00,0x84,0x24,0x00,0x00,0x0a,0xad,0x04,0x00,0x05,0xad,
+0x00,0x00,0xa8,0xac,0x00,0x02,0x18,0x27,0xf5,0xff,0xc1,0x04,0x21,0x28,0x00,0x01,
+0x02,0x80,0x05,0x3c,0x20,0x7b,0xa5,0x24,0x04,0x00,0xa6,0x8c,0x1c,0x00,0xb7,0x8f,
+0x18,0x00,0xb6,0x8f,0x14,0x00,0xb5,0x8f,0x10,0x00,0xb4,0x8f,0x0c,0x00,0xb3,0x8f,
+0x08,0x00,0xb2,0x8f,0x04,0x00,0xb1,0x8f,0x00,0x00,0xb0,0x8f,0x02,0x80,0x07,0x3c,
+0x02,0x80,0x03,0x3c,0x50,0x15,0xe4,0x24,0x00,0x14,0x63,0x24,0x03,0x00,0x02,0x24,
+0x20,0x00,0xbd,0x27,0x58,0x01,0x78,0xac,0x04,0x00,0x48,0xad,0x04,0x00,0xa4,0xac,
+0x60,0x01,0x62,0xac,0x50,0x15,0xe5,0xac,0x04,0x00,0x86,0xac,0x08,0x00,0xe0,0x03,
+0x00,0x00,0xc4,0xac,0xd0,0xff,0xbd,0x27,0x02,0x80,0x02,0x3c,0x20,0x00,0xb2,0xaf,
+0x02,0x80,0x03,0x3c,0x4c,0x91,0x52,0x24,0x02,0x80,0x02,0x3c,0x28,0x00,0xb4,0xaf,
+0x24,0x00,0xb3,0xaf,0x1c,0x00,0xb1,0xaf,0x18,0x00,0xb0,0xaf,0x2c,0x00,0xbf,0xaf,
+0xd8,0x90,0x73,0x24,0x68,0x15,0x50,0x24,0x21,0x88,0x00,0x00,0x02,0x80,0x14,0x3c,
+0xee,0x4e,0x00,0x0c,0x21,0x20,0x20,0x02,0x78,0x51,0x05,0x8e,0x6c,0x00,0x66,0x8e,
+0xb8,0x90,0x82,0x26,0x6c,0x00,0x43,0x8e,0x1b,0x00,0x44,0x90,0xff,0xf1,0x02,0x24,
+0x21,0x18,0x66,0x00,0x24,0x28,0xa2,0x00,0x00,0x21,0x04,0x00,0x42,0x18,0x03,0x00,
+0x00,0x02,0xa5,0x34,0x44,0x51,0x03,0xae,0x68,0x51,0x04,0xae,0x78,0x51,0x05,0xae,
+0x6c,0x51,0x04,0xae,0x21,0x30,0x00,0x00,0x21,0x10,0x06,0x02,0x01,0x00,0xc6,0x24,
+0x1d,0x00,0xc3,0x28,0x99,0x51,0x40,0xa0,0x7c,0x51,0x40,0xa0,0xfa,0xff,0x60,0x14,
+0xb6,0x51,0x40,0xa0,0x01,0x00,0x31,0x26,0x20,0x00,0x22,0x2a,0xd4,0x51,0x00,0xae,
+0xe3,0xff,0x40,0x14,0x94,0x00,0x10,0x26,0x02,0x80,0x02,0x3c,0x02,0x80,0x03,0x3c,
+0x68,0x15,0x4b,0x24,0x02,0x80,0x02,0x3c,0x4c,0x91,0x6f,0x24,0xd8,0x90,0x4d,0x24,
+0x02,0x80,0x03,0x3c,0x02,0x80,0x02,0x3c,0xb8,0x90,0x6e,0x24,0x98,0x90,0x4c,0x24,
+0x21,0x88,0x00,0x00,0x80,0x18,0x11,0x00,0x21,0x20,0x6d,0x00,0x21,0x10,0x6f,0x00,
+0x21,0x28,0x2e,0x02,0x21,0x30,0x2c,0x02,0x00,0x00,0x88,0x8c,0x00,0x00,0xa9,0x90,
+0x00,0x00,0xc7,0x90,0x00,0x00,0x4a,0x8c,0x21,0x10,0x2b,0x02,0x01,0x00,0x31,0x26,
+0x21,0x18,0x6b,0x00,0x1d,0x00,0x24,0x2a,0xec,0x44,0x68,0xac,0xca,0x44,0x47,0xa0,
+0x60,0x45,0x6a,0xac,0xef,0xff,0x80,0x14,0x90,0x44,0x49,0xa0,0x02,0x80,0x02,0x3c,
+0x68,0x15,0x4a,0x24,0x02,0x80,0x03,0x3c,0x02,0x80,0x02,0x3c,0x74,0x8f,0x6b,0x24,
+0x14,0x8e,0x4c,0x24,0x21,0x88,0x00,0x00,0x21,0x48,0x00,0x00,0x21,0x30,0x00,0x00,
+0x21,0x40,0x2a,0x01,0x21,0x38,0x2b,0x01,0x21,0x10,0xe6,0x00,0x91,0x00,0x44,0x90,
+0x00,0x00,0x45,0x90,0x21,0x18,0x06,0x01,0x01,0x00,0xc6,0x24,0x05,0x00,0xc2,0x28,
+0xc5,0x43,0x64,0xa0,0xf8,0xff,0x40,0x14,0x34,0x43,0x65,0xa0,0x21,0x10,0x2c,0x02,
+0x1d,0x00,0x44,0x90,0x00,0x00,0x45,0x90,0x21,0x18,0x2a,0x02,0x01,0x00,0x31,0x26,
+0x1d,0x00,0x22,0x2a,0x73,0x44,0x64,0xa0,0x56,0x44,0x65,0xa0,0xeb,0xff,0x40,0x14,
+0x05,0x00,0x29,0x25,0x52,0x00,0x02,0x24,0x10,0x00,0xa2,0xa3,0x41,0x00,0x03,0x24,
+0x4d,0x00,0x02,0x24,0x02,0x80,0x07,0x3c,0x1c,0x97,0xe7,0x24,0x11,0x00,0xa3,0xa3,
+0x12,0x00,0xa2,0xa3,0xe8,0x03,0x03,0x24,0x01,0x00,0x02,0x24,0x00,0x80,0x06,0x3c,
+0x10,0x00,0xa5,0x27,0x21,0x20,0xe0,0x00,0xf0,0x37,0xc6,0x24,0x0c,0x00,0xe3,0xac,
+0x14,0x00,0xe2,0xa0,0xfb,0x0c,0x00,0x0c,0x13,0x00,0xa0,0xa3,0x2c,0x00,0xbf,0x8f,
+0x28,0x00,0xb4,0x8f,0x24,0x00,0xb3,0x8f,0x20,0x00,0xb2,0x8f,0x1c,0x00,0xb1,0x8f,
+0x18,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x30,0x00,0xbd,0x27,0xe0,0xff,0xbd,0x27,
+0x02,0x80,0x02,0x3c,0x42,0x00,0x03,0x24,0x10,0x00,0xa3,0xa3,0x55,0x60,0x40,0xa0,
+0x4e,0x00,0x03,0x24,0x43,0x00,0x02,0x24,0x02,0x80,0x07,0x3c,0x54,0x97,0xe7,0x24,
+0x11,0x00,0xa2,0xa3,0x12,0x00,0xa3,0xa3,0xd0,0x07,0x02,0x24,0x01,0x00,0x03,0x24,
+0x00,0x80,0x06,0x3c,0x10,0x00,0xa5,0x27,0x21,0x20,0xe0,0x00,0xdc,0x44,0xc6,0x24,
+0x0c,0x00,0xe2,0xac,0x14,0x00,0xe3,0xa0,0x18,0x00,0xbf,0xaf,0xfb,0x0c,0x00,0x0c,
+0x13,0x00,0xa0,0xa3,0x18,0x00,0xbf,0x8f,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x20,0x00,0xbd,0x27,0x48,0xfd,0xbd,0x27,0xb4,0x02,0xb3,0xaf,0x02,0x80,0x02,0x3c,
+0x02,0x80,0x13,0x3c,0x24,0x92,0x46,0x24,0x68,0x15,0x63,0x26,0xb0,0x02,0xb2,0xaf,
+0xac,0x02,0xb1,0xaf,0xa8,0x02,0xb0,0xaf,0x03,0x40,0x60,0xa0,0x21,0x38,0xa0,0x03,
+0x90,0x00,0xc8,0x24,0x00,0x00,0xc2,0x8c,0x04,0x00,0xc3,0x8c,0x08,0x00,0xc4,0x8c,
+0x0c,0x00,0xc5,0x8c,0x10,0x00,0xc6,0x24,0x00,0x00,0xe2,0xac,0x04,0x00,0xe3,0xac,
+0x08,0x00,0xe4,0xac,0x0c,0x00,0xe5,0xac,0xf6,0xff,0xc8,0x14,0x10,0x00,0xe7,0x24,
+0x00,0x00,0xc3,0x8c,0x02,0x80,0x02,0x3c,0xb8,0x92,0x58,0x24,0x00,0x00,0xe3,0xac,
+0x98,0x00,0xb9,0x27,0x00,0x01,0x12,0x27,0x01,0x00,0x02,0x93,0x05,0x00,0x03,0x93,
+0x09,0x00,0x04,0x93,0x0d,0x00,0x05,0x93,0x00,0x00,0x11,0x93,0x02,0x00,0x0d,0x93,
+0x04,0x00,0x10,0x93,0x06,0x00,0x0c,0x93,0x08,0x00,0x0f,0x93,0x0a,0x00,0x07,0x93,
+0x0c,0x00,0x0e,0x93,0x0e,0x00,0x06,0x93,0x03,0x00,0x08,0x93,0x07,0x00,0x09,0x93,
+0x0b,0x00,0x0a,0x93,0x0f,0x00,0x0b,0x93,0x00,0x12,0x02,0x00,0x00,0x1a,0x03,0x00,
+0x00,0x22,0x04,0x00,0x00,0x2a,0x05,0x00,0x25,0x10,0x51,0x00,0x25,0x18,0x70,0x00,
+0x25,0x20,0x8f,0x00,0x25,0x28,0xae,0x00,0x00,0x6c,0x0d,0x00,0x00,0x64,0x0c,0x00,
+0x00,0x3c,0x07,0x00,0x00,0x34,0x06,0x00,0x25,0x68,0xa2,0x01,0x25,0x60,0x83,0x01,
+0x25,0x38,0xe4,0x00,0x25,0x30,0xc5,0x00,0x00,0x46,0x08,0x00,0x00,0x4e,0x09,0x00,
+0x00,0x56,0x0a,0x00,0x00,0x5e,0x0b,0x00,0x25,0x40,0x0d,0x01,0x25,0x48,0x2c,0x01,
+0x25,0x50,0x47,0x01,0x25,0x58,0x66,0x01,0x10,0x00,0x18,0x27,0x00,0x00,0x28,0xaf,
+0x04,0x00,0x29,0xaf,0x08,0x00,0x2a,0xaf,0x0c,0x00,0x2b,0xaf,0xd2,0xff,0x12,0x17,
+0x10,0x00,0x39,0x27,0x01,0x00,0x02,0x93,0x05,0x00,0x03,0x93,0x00,0x00,0x09,0x93,
+0x02,0x00,0x04,0x93,0x04,0x00,0x08,0x93,0x06,0x00,0x05,0x93,0x07,0x00,0x06,0x93,
+0x03,0x00,0x07,0x93,0x00,0x12,0x02,0x00,0x00,0x1a,0x03,0x00,0x25,0x10,0x49,0x00,
+0x25,0x18,0x68,0x00,0x00,0x24,0x04,0x00,0x00,0x2c,0x05,0x00,0x25,0x20,0x82,0x00,
+0x25,0x28,0xa3,0x00,0x00,0x3e,0x07,0x00,0x00,0x36,0x06,0x00,0x02,0x80,0x02,0x3c,
+0x25,0x38,0xe4,0x00,0x25,0x30,0xc5,0x00,0xc0,0x93,0x58,0x24,0x04,0x00,0x26,0xaf,
+0x00,0x00,0x27,0xaf,0x00,0x01,0x12,0x27,0xa0,0x01,0xb9,0x27,0x01,0x00,0x02,0x93,
+0x05,0x00,0x03,0x93,0x09,0x00,0x04,0x93,0x0d,0x00,0x05,0x93,0x00,0x00,0x11,0x93,
+0x02,0x00,0x0d,0x93,0x04,0x00,0x10,0x93,0x06,0x00,0x0c,0x93,0x08,0x00,0x0f,0x93,
+0x0a,0x00,0x07,0x93,0x0c,0x00,0x0e,0x93,0x0e,0x00,0x06,0x93,0x03,0x00,0x08,0x93,
+0x07,0x00,0x09,0x93,0x0b,0x00,0x0a,0x93,0x0f,0x00,0x0b,0x93,0x00,0x12,0x02,0x00,
+0x00,0x1a,0x03,0x00,0x00,0x22,0x04,0x00,0x00,0x2a,0x05,0x00,0x25,0x10,0x51,0x00,
+0x25,0x18,0x70,0x00,0x25,0x20,0x8f,0x00,0x25,0x28,0xae,0x00,0x00,0x6c,0x0d,0x00,
+0x00,0x64,0x0c,0x00,0x00,0x3c,0x07,0x00,0x00,0x34,0x06,0x00,0x25,0x68,0xa2,0x01,
+0x25,0x60,0x83,0x01,0x25,0x38,0xe4,0x00,0x25,0x30,0xc5,0x00,0x00,0x46,0x08,0x00,
+0x00,0x4e,0x09,0x00,0x00,0x56,0x0a,0x00,0x00,0x5e,0x0b,0x00,0x25,0x40,0x0d,0x01,
+0x25,0x48,0x2c,0x01,0x25,0x50,0x47,0x01,0x25,0x58,0x66,0x01,0x10,0x00,0x18,0x27,
+0x00,0x00,0x28,0xaf,0x04,0x00,0x29,0xaf,0x08,0x00,0x2a,0xaf,0x0c,0x00,0x2b,0xaf,
+0xd2,0xff,0x12,0x17,0x10,0x00,0x39,0x27,0x01,0x00,0x02,0x93,0x05,0x00,0x03,0x93,
+0x00,0x00,0x09,0x93,0x02,0x00,0x04,0x93,0x04,0x00,0x08,0x93,0x06,0x00,0x05,0x93,
+0x07,0x00,0x06,0x93,0x03,0x00,0x07,0x93,0x00,0x12,0x02,0x00,0x00,0x1a,0x03,0x00,
+0x25,0x10,0x49,0x00,0x25,0x18,0x68,0x00,0x00,0x24,0x04,0x00,0x00,0x2c,0x05,0x00,
+0x25,0x20,0x82,0x00,0x25,0x28,0xa3,0x00,0x00,0x3e,0x07,0x00,0x00,0x36,0x06,0x00,
+0x25,0x30,0xc5,0x00,0x25,0x38,0xe4,0x00,0x02,0x80,0x02,0x3c,0x04,0x00,0x26,0xaf,
+0x00,0x00,0x27,0xaf,0x68,0x15,0x46,0x24,0x21,0x50,0x00,0x00,0x80,0x20,0x0a,0x00,
+0x21,0x10,0x9d,0x00,0x00,0x00,0x45,0x8c,0x01,0x00,0x43,0x25,0xff,0x00,0x6a,0x30,
+0x21,0x20,0x86,0x00,0x25,0x00,0x42,0x2d,0xf8,0xff,0x40,0x14,0x18,0x40,0x85,0xac,
+0x02,0x80,0x02,0x3c,0x68,0x15,0x4b,0x24,0x21,0x50,0x00,0x00,0xc0,0x10,0x0a,0x00,
+0x21,0x48,0x5d,0x00,0x21,0x38,0x00,0x00,0x21,0x40,0x4b,0x00,0x21,0x10,0x27,0x01,
+0xa0,0x01,0x46,0x90,0x98,0x00,0x45,0x90,0x01,0x00,0xe4,0x24,0x21,0x18,0x07,0x01,
+0xff,0x00,0x87,0x30,0x08,0x00,0xe2,0x2c,0xb4,0x41,0x66,0xa0,0xf7,0xff,0x40,0x14,
+0xac,0x40,0x65,0xa0,0x01,0x00,0x42,0x25,0xff,0x00,0x4a,0x30,0x21,0x00,0x43,0x2d,
+0xef,0xff,0x60,0x14,0xc0,0x10,0x0a,0x00,0x25,0xb0,0x02,0x3c,0x0a,0x00,0x42,0x34,
+0x00,0x00,0x43,0x90,0x00,0x00,0x00,0x00,0x20,0x00,0x63,0x30,0x42,0x00,0x60,0x10,
+0x68,0x15,0x64,0x26,0x33,0x00,0x02,0x24,0xc1,0x42,0x62,0xa1,0x1c,0x00,0x03,0x24,
+0x0f,0x00,0x02,0x24,0xbc,0x42,0x63,0xa1,0xbd,0x42,0x62,0xa1,0x68,0x15,0x65,0x26,
+0x08,0x40,0xa4,0x8c,0xff,0x7f,0x08,0x3c,0xff,0xff,0x08,0x35,0xc0,0xff,0x02,0x24,
+0x24,0x20,0x88,0x00,0x24,0x20,0x82,0x00,0x0c,0x00,0x84,0x34,0xff,0xc0,0x02,0x24,
+0x24,0x20,0x82,0x00,0xc0,0xff,0x02,0x3c,0xff,0xff,0x42,0x34,0x00,0x18,0x84,0x34,
+0xbf,0xff,0x03,0x3c,0x24,0x20,0x82,0x00,0xff,0xff,0x63,0x34,0x7f,0xff,0x02,0x3c,
+0x24,0x20,0x83,0x00,0xff,0xff,0x42,0x34,0x24,0x20,0x82,0x00,0x0c,0x40,0xa6,0x8c,
+0x7f,0xff,0x03,0x24,0x40,0x40,0x84,0x34,0xff,0xff,0x02,0x3c,0x24,0x20,0x83,0x00,
+0xff,0x7f,0x42,0x34,0xff,0xbf,0x03,0x3c,0x10,0x40,0xa7,0x8c,0x24,0x20,0x82,0x00,
+0xff,0xff,0x63,0x34,0xff,0x9f,0x02,0x3c,0x24,0x30,0xc3,0x00,0xff,0xff,0x42,0x34,
+0xff,0x3f,0x03,0x3c,0x24,0x20,0x82,0x00,0xff,0xff,0x63,0x34,0x12,0x00,0x02,0x24,
+0xb4,0x02,0xb3,0x8f,0xb0,0x02,0xb2,0x8f,0xac,0x02,0xb1,0x8f,0xa8,0x02,0xb0,0x8f,
+0x24,0x38,0xe3,0x00,0xc7,0x42,0xa2,0xa0,0x1f,0x00,0x03,0x24,0x01,0x00,0x02,0x24,
+0x24,0x30,0xc8,0x00,0xbe,0x42,0xa3,0xa0,0xc0,0x42,0xa2,0xa0,0xff,0x00,0x03,0x24,
+0xff,0xff,0x02,0x24,0xb8,0x02,0xbd,0x27,0x08,0x40,0xa4,0xac,0x10,0x40,0xa7,0xac,
+0x0c,0x40,0xa6,0xac,0xc2,0x42,0xa2,0xa0,0xc4,0x42,0xa3,0xa4,0xbf,0x42,0xa0,0xa0,
+0x08,0x00,0xe0,0x03,0xc6,0x42,0xa0,0xa0,0x33,0x00,0x02,0x24,0xc1,0x42,0x82,0xa0,
+0x0d,0x00,0x03,0x24,0x03,0x00,0x02,0x24,0xbc,0x42,0x83,0xa0,0x65,0x5d,0x00,0x08,
+0xbd,0x42,0x82,0xa0,0xe0,0xff,0xbd,0x27,0x02,0x80,0x07,0x3c,0x68,0x15,0xe7,0x24,
+0x18,0x00,0xbf,0xaf,0x00,0x40,0xe3,0x8c,0xf0,0xff,0x02,0x24,0x02,0x80,0x08,0x3c,
+0x24,0x18,0x62,0x00,0xff,0xf0,0x02,0x24,0x24,0x18,0x62,0x00,0x00,0x40,0xe3,0xac,
+0x1c,0x00,0x03,0x24,0x36,0x00,0x02,0x24,0xcf,0x42,0xe3,0xa0,0x20,0x00,0x03,0x24,
+0xce,0x42,0xe2,0xa0,0xd1,0x42,0xe3,0xa0,0x32,0x00,0x02,0x24,0x20,0x00,0x03,0x24,
+0xd0,0x42,0xe2,0xa0,0xc8,0x42,0xe3,0xa4,0x0a,0x00,0x02,0x24,0x00,0x02,0x03,0x24,
+0xd2,0x42,0xe2,0xa0,0xcc,0x42,0xe3,0xa4,0x00,0x01,0x02,0x24,0x49,0x00,0x03,0x24,
+0x38,0x97,0x08,0x25,0xff,0xff,0x0a,0x34,0x01,0x00,0x09,0x24,0x11,0x00,0xa3,0xa3,
+0xca,0x42,0xe2,0xa4,0xd0,0x07,0x03,0x24,0x44,0x00,0x02,0x24,0x00,0x80,0x06,0x3c,
+0x10,0x00,0xa2,0xa3,0x10,0x00,0xa5,0x27,0x47,0x00,0x02,0x24,0x21,0x20,0x00,0x01,
+0x54,0x45,0xc6,0x24,0x04,0x40,0xea,0xac,0x02,0x40,0xe9,0xa0,0x0c,0x00,0x03,0xad,
+0x14,0x00,0x09,0xa1,0xe6,0x42,0xe0,0xa0,0xdc,0x63,0xea,0xac,0xd7,0x42,0xe0,0xa0,
+0x12,0x00,0xa2,0xa3,0xfb,0x0c,0x00,0x0c,0x13,0x00,0xa0,0xa3,0x18,0x00,0xbf,0x8f,
+0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,0xe0,0xff,0xbd,0x27,
+0x02,0x80,0x02,0x3c,0x50,0x00,0x03,0x24,0x10,0x00,0xa3,0xa3,0x2a,0x62,0x40,0xa0,
+0x41,0x00,0x03,0x24,0x52,0x00,0x02,0x24,0x02,0x80,0x07,0x3c,0xc4,0x97,0xe7,0x24,
+0x11,0x00,0xa2,0xa3,0x12,0x00,0xa3,0xa3,0xd0,0x07,0x02,0x24,0x01,0x00,0x03,0x24,
+0x01,0x80,0x06,0x3c,0x10,0x00,0xa5,0x27,0x21,0x20,0xe0,0x00,0x88,0x5b,0xc6,0x24,
+0x0c,0x00,0xe2,0xac,0x14,0x00,0xe3,0xa0,0x18,0x00,0xbf,0xaf,0xfb,0x0c,0x00,0x0c,
+0x13,0x00,0xa0,0xa3,0x18,0x00,0xbf,0x8f,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x20,0x00,0xbd,0x27,0xd8,0xff,0xbd,0x27,0x18,0x00,0xb0,0xaf,0x02,0x80,0x10,0x3c,
+0x68,0x15,0x10,0x26,0x20,0x00,0xbf,0xaf,0x1c,0x00,0xb1,0xaf,0x00,0x40,0x09,0x8e,
+0xff,0xff,0x02,0x24,0xff,0x00,0x4b,0x30,0x0f,0xff,0x02,0x24,0x24,0x48,0x22,0x01,
+0xff,0xff,0x02,0x3c,0xff,0x0f,0x42,0x34,0x24,0x48,0x22,0x01,0x01,0x00,0x07,0x3c,
+0x47,0x00,0x02,0x24,0x3b,0x00,0x03,0x24,0x02,0x80,0x08,0x3c,0x10,0x00,0xa2,0xa3,
+0x11,0x00,0xa3,0xa3,0xe0,0x97,0x08,0x25,0x56,0x30,0xea,0x34,0xd0,0x07,0x02,0x24,
+0x01,0x00,0x03,0x24,0xf4,0x98,0xe7,0x34,0x00,0x80,0x06,0x3c,0x04,0x43,0x0b,0xae,
+0x00,0x40,0x09,0xae,0x43,0x00,0x11,0x24,0x10,0x00,0xa5,0x27,0x0c,0x43,0x07,0xae,
+0x10,0x43,0x0a,0xae,0x0c,0x00,0x02,0xad,0x14,0x00,0x03,0xa1,0x08,0x43,0x00,0xae,
+0x14,0x43,0x00,0xae,0x18,0x43,0x00,0xae,0x21,0x20,0x00,0x01,0xe4,0x4e,0xc6,0x24,
+0x12,0x00,0xb1,0xa3,0xfb,0x0c,0x00,0x0c,0x13,0x00,0xa0,0xa3,0x1e,0x00,0x02,0x24,
+0x21,0x43,0x02,0xa2,0x4a,0x00,0x03,0x24,0x45,0x00,0x02,0x24,0x1c,0x43,0x03,0xa2,
+0x1d,0x43,0x02,0xa2,0x23,0x00,0x03,0x24,0x3e,0x00,0x02,0x24,0x1e,0x43,0x11,0xa2,
+0x1f,0x43,0x02,0xa2,0x20,0x43,0x03,0xa2,0x20,0x00,0xbf,0x8f,0x1c,0x00,0xb1,0x8f,
+0x18,0x00,0xb0,0x8f,0x08,0x00,0xe0,0x03,0x28,0x00,0xbd,0x27,0xe0,0xff,0xbd,0x27,
+0x3b,0x00,0x02,0x24,0x43,0x00,0x03,0x24,0x10,0x00,0xa2,0xa3,0x11,0x00,0xa3,0xa3,
+0x36,0x00,0x02,0x24,0x02,0x80,0x03,0x3c,0x02,0x80,0x07,0x3c,0xfc,0x97,0xe7,0x24,
+0x12,0x00,0xa2,0xa3,0x3b,0x58,0x60,0xa0,0xd0,0x07,0x02,0x24,0x01,0x00,0x03,0x24,
+0x00,0x80,0x06,0x3c,0x10,0x00,0xa5,0x27,0x21,0x20,0xe0,0x00,0x20,0x53,0xc6,0x24,
+0x0c,0x00,0xe2,0xac,0x14,0x00,0xe3,0xa0,0x18,0x00,0xbf,0xaf,0xfb,0x0c,0x00,0x0c,
+0x13,0x00,0xa0,0xa3,0x18,0x00,0xbf,0x8f,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x20,0x00,0xbd,0x27,0xff,0xff,0x07,0x24,0x02,0x80,0x02,0x3c,0xe0,0xff,0xbd,0x27,
+0x3d,0x58,0x47,0xa0,0x3b,0x00,0x03,0x24,0x43,0x00,0x02,0x24,0x10,0x00,0xa3,0xa3,
+0x11,0x00,0xa2,0xa3,0x36,0x00,0x03,0x24,0x16,0x00,0x02,0x24,0x02,0x80,0x08,0x3c,
+0x18,0x98,0x08,0x25,0x12,0x00,0xa3,0xa3,0x13,0x00,0xa2,0xa3,0xd0,0x07,0x03,0x24,
+0x01,0x00,0x02,0x24,0x00,0x80,0x06,0x3c,0x10,0x00,0xa5,0x27,0x21,0x20,0x00,0x01,
+0x0c,0x00,0x03,0xad,0x14,0x00,0x02,0xa1,0x18,0x00,0xbf,0xaf,0xfb,0x0c,0x00,0x0c,
+0xb8,0x54,0xc6,0x24,0x18,0x00,0xbf,0x8f,0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,
+0x20,0x00,0xbd,0x27,0xe0,0xff,0xbd,0x27,0x02,0x80,0x02,0x3c,0x52,0x00,0x03,0x24,
+0x10,0x00,0xa3,0xa3,0x4c,0x79,0x40,0xa4,0x54,0x00,0x03,0x24,0x53,0x00,0x02,0x24,
+0x02,0x80,0x07,0x3c,0x34,0x98,0xe7,0x24,0x11,0x00,0xa2,0xa3,0x12,0x00,0xa3,0xa3,
+0xf4,0x01,0x02,0x24,0x01,0x00,0x03,0x24,0x01,0x80,0x06,0x3c,0x10,0x00,0xa5,0x27,
+0x21,0x20,0xe0,0x00,0xc8,0x5c,0xc6,0x24,0x0c,0x00,0xe2,0xac,0x14,0x00,0xe3,0xa0,
+0x18,0x00,0xbf,0xaf,0xfb,0x0c,0x00,0x0c,0x13,0x00,0xa0,0xa3,0x18,0x00,0xbf,0x8f,
+0x00,0x00,0x00,0x00,0x08,0x00,0xe0,0x03,0x20,0x00,0xbd,0x27,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x78,0x0c,0x00,0x00,0x01,0x00,0x00,0x5e,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x01,0x5e,0x78,0x0c,0x00,0x00,0x01,0x00,0x02,0x5e,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x03,0x5e,0x78,0x0c,0x00,0x00,0x01,0x00,0x04,0x5d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x05,0x5b,0x78,0x0c,0x00,0x00,0x01,0x00,0x06,0x59,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x07,0x57,0x78,0x0c,0x00,0x00,0x01,0x00,0x08,0x55,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x09,0x53,0x78,0x0c,0x00,0x00,0x01,0x00,0x0a,0x51,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x0b,0x4f,0x78,0x0c,0x00,0x00,0x01,0x00,0x0c,0x4d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x0d,0x4b,0x78,0x0c,0x00,0x00,0x01,0x00,0x0e,0x49,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x0f,0x47,0x78,0x0c,0x00,0x00,0x01,0x00,0x10,0x45,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x11,0x43,0x78,0x0c,0x00,0x00,0x01,0x00,0x12,0x41,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x13,0x3f,0x78,0x0c,0x00,0x00,0x01,0x00,0x14,0x3d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x15,0x3b,0x78,0x0c,0x00,0x00,0x01,0x00,0x16,0x39,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x17,0x37,0x78,0x0c,0x00,0x00,0x01,0x00,0x18,0x35,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x19,0x33,0x78,0x0c,0x00,0x00,0x01,0x00,0x1a,0x31,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x1b,0x2f,0x78,0x0c,0x00,0x00,0x01,0x00,0x1c,0x2d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x1d,0x2b,0x78,0x0c,0x00,0x00,0x01,0x00,0x1e,0x29,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x1f,0x27,0x78,0x0c,0x00,0x00,0x01,0x00,0x20,0x25,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x21,0x23,0x78,0x0c,0x00,0x00,0x01,0x00,0x22,0x21,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x23,0x1f,0x78,0x0c,0x00,0x00,0x01,0x00,0x24,0x1d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x25,0x1b,0x78,0x0c,0x00,0x00,0x01,0x00,0x26,0x19,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x27,0x17,0x78,0x0c,0x00,0x00,0x01,0x00,0x28,0x15,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x29,0x13,0x78,0x0c,0x00,0x00,0x01,0x00,0x2a,0x11,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x2b,0x0f,0x78,0x0c,0x00,0x00,0x01,0x00,0x2c,0x0d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x2d,0x0b,0x78,0x0c,0x00,0x00,0x01,0x00,0x2e,0x09,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x2f,0x07,0x78,0x0c,0x00,0x00,0x01,0x00,0x30,0x05,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x31,0x03,0x78,0x0c,0x00,0x00,0x01,0x00,0x32,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x33,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x34,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x35,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x36,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x37,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x38,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x39,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x3a,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x3b,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x3c,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x3d,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x3e,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x3f,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x40,0x5e,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x41,0x5e,0x78,0x0c,0x00,0x00,0x01,0x00,0x42,0x5e,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x43,0x5e,0x78,0x0c,0x00,0x00,0x01,0x00,0x44,0x5d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x45,0x5b,0x78,0x0c,0x00,0x00,0x01,0x00,0x46,0x59,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x47,0x57,0x78,0x0c,0x00,0x00,0x01,0x00,0x48,0x55,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x49,0x53,0x78,0x0c,0x00,0x00,0x01,0x00,0x4a,0x51,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x4b,0x4f,0x78,0x0c,0x00,0x00,0x01,0x00,0x4c,0x4d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x4d,0x4b,0x78,0x0c,0x00,0x00,0x01,0x00,0x4e,0x49,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x4f,0x47,0x78,0x0c,0x00,0x00,0x01,0x00,0x50,0x45,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x51,0x43,0x78,0x0c,0x00,0x00,0x01,0x00,0x52,0x41,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x53,0x3f,0x78,0x0c,0x00,0x00,0x01,0x00,0x54,0x3d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x55,0x3b,0x78,0x0c,0x00,0x00,0x01,0x00,0x56,0x39,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x57,0x37,0x78,0x0c,0x00,0x00,0x01,0x00,0x58,0x35,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x59,0x33,0x78,0x0c,0x00,0x00,0x01,0x00,0x5a,0x31,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x5b,0x2f,0x78,0x0c,0x00,0x00,0x01,0x00,0x5c,0x2d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x5d,0x2b,0x78,0x0c,0x00,0x00,0x01,0x00,0x5e,0x29,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x5f,0x27,0x78,0x0c,0x00,0x00,0x01,0x00,0x60,0x25,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x61,0x23,0x78,0x0c,0x00,0x00,0x01,0x00,0x62,0x21,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x63,0x1f,0x78,0x0c,0x00,0x00,0x01,0x00,0x64,0x1d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x65,0x1b,0x78,0x0c,0x00,0x00,0x01,0x00,0x66,0x19,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x67,0x17,0x78,0x0c,0x00,0x00,0x01,0x00,0x68,0x15,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x69,0x13,0x78,0x0c,0x00,0x00,0x01,0x00,0x6a,0x11,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x6b,0x0f,0x78,0x0c,0x00,0x00,0x01,0x00,0x6c,0x0d,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x6d,0x0b,0x78,0x0c,0x00,0x00,0x01,0x00,0x6e,0x09,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x6f,0x07,0x78,0x0c,0x00,0x00,0x01,0x00,0x70,0x05,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x71,0x03,0x78,0x0c,0x00,0x00,0x01,0x00,0x72,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x73,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x74,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x75,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x76,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x77,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x78,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x79,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x7a,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x7b,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x7c,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x7d,0x01,0x78,0x0c,0x00,0x00,0x01,0x00,0x7e,0x01,0x78,0x0c,0x00,0x00,
+0x01,0x00,0x7f,0x01,0x78,0x0c,0x00,0x00,0x1e,0x00,0x00,0x30,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x01,0x30,0x78,0x0c,0x00,0x00,0x1e,0x00,0x02,0x30,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x03,0x30,0x78,0x0c,0x00,0x00,0x1e,0x00,0x04,0x30,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x05,0x30,0x78,0x0c,0x00,0x00,0x1e,0x00,0x06,0x30,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x07,0x30,0x78,0x0c,0x00,0x00,0x1e,0x00,0x08,0x3e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x09,0x40,0x78,0x0c,0x00,0x00,0x1e,0x00,0x0a,0x42,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x0b,0x44,0x78,0x0c,0x00,0x00,0x1e,0x00,0x0c,0x46,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x0d,0x48,0x78,0x0c,0x00,0x00,0x1e,0x00,0x0e,0x48,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x0f,0x4a,0x78,0x0c,0x00,0x00,0x1e,0x00,0x10,0x4a,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x11,0x4c,0x78,0x0c,0x00,0x00,0x1e,0x00,0x12,0x4c,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x13,0x4e,0x78,0x0c,0x00,0x00,0x1e,0x00,0x14,0x50,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x15,0x50,0x78,0x0c,0x00,0x00,0x1e,0x00,0x16,0x50,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x17,0x52,0x78,0x0c,0x00,0x00,0x1e,0x00,0x18,0x52,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x19,0x52,0x78,0x0c,0x00,0x00,0x1e,0x00,0x1a,0x54,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x1b,0x54,0x78,0x0c,0x00,0x00,0x1e,0x00,0x1c,0x54,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x1d,0x56,0x78,0x0c,0x00,0x00,0x1e,0x00,0x1e,0x56,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x1f,0x56,0x78,0x0c,0x00,0x00,0x1e,0x00,0x20,0x56,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x21,0x58,0x78,0x0c,0x00,0x00,0x1e,0x00,0x22,0x58,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x23,0x58,0x78,0x0c,0x00,0x00,0x1e,0x00,0x24,0x58,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x25,0x5a,0x78,0x0c,0x00,0x00,0x1e,0x00,0x26,0x5a,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x27,0x5a,0x78,0x0c,0x00,0x00,0x1e,0x00,0x28,0x5c,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x29,0x5c,0x78,0x0c,0x00,0x00,0x1e,0x00,0x2a,0x5e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x2b,0x5e,0x78,0x0c,0x00,0x00,0x1e,0x00,0x2c,0x5e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x2d,0x5e,0x78,0x0c,0x00,0x00,0x1e,0x00,0x2e,0x5e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x2f,0x5e,0x78,0x0c,0x00,0x00,0x1e,0x00,0x30,0x5e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x31,0x5e,0x78,0x0c,0x00,0x00,0x1e,0x00,0x32,0x5e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x33,0x5e,0x78,0x0c,0x00,0x00,0x1e,0x00,0x34,0x5e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x35,0x5e,0x78,0x0c,0x00,0x00,0x1e,0x00,0x36,0x5e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x37,0x5e,0x78,0x0c,0x00,0x00,0x1e,0x00,0x38,0x5e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x39,0x5e,0x78,0x0c,0x00,0x00,0x1e,0x00,0x3a,0x5e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x3b,0x5e,0x78,0x0c,0x00,0x00,0x1e,0x00,0x3c,0x5e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x3d,0x5e,0x78,0x0c,0x00,0x00,0x1e,0x00,0x3e,0x5e,0x78,0x0c,0x00,0x00,
+0x1e,0x00,0x3f,0x5e,0xff,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0x00,0x08,0x00,0x00,
+0x00,0x00,0x04,0x03,0x04,0x08,0x00,0x00,0x03,0x00,0x00,0x00,0x08,0x08,0x00,0x00,
+0x00,0xfc,0x00,0x00,0x0c,0x08,0x00,0x00,0x0a,0x00,0x00,0x04,0x10,0x08,0x00,0x00,
+0xff,0x10,0x10,0x80,0x14,0x08,0x00,0x00,0x10,0x3d,0x0c,0x02,0x18,0x08,0x00,0x00,
+0xc5,0x03,0x00,0x00,0x1c,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x08,0x00,0x00,
+0x04,0x00,0x00,0x00,0x24,0x08,0x00,0x00,0x00,0x02,0x69,0x00,0x28,0x08,0x00,0x00,
+0x04,0x00,0x00,0x00,0x2c,0x08,0x00,0x00,0x00,0x02,0x69,0x00,0x30,0x08,0x00,0x00,
+0x04,0x00,0x00,0x00,0x34,0x08,0x00,0x00,0x00,0x02,0x69,0x00,0x38,0x08,0x00,0x00,
+0x04,0x00,0x00,0x00,0x3c,0x08,0x00,0x00,0x00,0x02,0x69,0x00,0x40,0x08,0x00,0x00,
+0x00,0x00,0x00,0x00,0x44,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x08,0x00,0x00,
+0x00,0x00,0x00,0x00,0x4c,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x50,0x08,0x00,0x00,
+0x00,0x00,0x00,0x00,0x54,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x58,0x08,0x00,0x00,
+0x65,0xa9,0x65,0xa9,0x5c,0x08,0x00,0x00,0x65,0xa9,0x65,0xa9,0x60,0x08,0x00,0x00,
+0x30,0x01,0x7f,0x0f,0x64,0x08,0x00,0x00,0x30,0x01,0x7f,0x0f,0x68,0x08,0x00,0x00,
+0x30,0x01,0x7f,0x0f,0x6c,0x08,0x00,0x00,0x30,0x01,0x7f,0x0f,0x70,0x08,0x00,0x00,
+0x00,0x03,0x00,0x03,0x74,0x08,0x00,0x00,0x00,0x03,0x00,0x03,0x78,0x08,0x00,0x00,
+0x00,0x00,0x00,0x00,0x7c,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x90,0x08,0x00,0x00,
+0x00,0x00,0x00,0x00,0x94,0x08,0x00,0x00,0xfe,0xff,0xff,0xff,0x98,0x08,0x00,0x00,
+0x10,0x20,0x30,0x40,0x9c,0x08,0x00,0x00,0x50,0x60,0x70,0x00,0xb0,0x08,0x00,0x00,
+0x00,0x00,0x00,0x00,0xe0,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0xe4,0x08,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x0e,0x00,0x00,0x03,0x03,0x03,0x03,0x04,0x0e,0x00,0x00,
+0x03,0x03,0x03,0x03,0x08,0x0e,0x00,0x00,0x03,0x03,0x00,0x00,0x0c,0x0e,0x00,0x00,
+0x00,0x00,0x00,0x00,0x10,0x0e,0x00,0x00,0x03,0x03,0x03,0x03,0x14,0x0e,0x00,0x00,
+0x03,0x03,0x03,0x03,0x18,0x0e,0x00,0x00,0x03,0x03,0x03,0x03,0x1c,0x0e,0x00,0x00,
+0x03,0x03,0x03,0x03,0x00,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x09,0x00,0x00,
+0x23,0x00,0x00,0x00,0x08,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x0c,0x09,0x00,0x00,
+0x33,0x13,0x32,0x03,0x08,0x0a,0x00,0x00,0x00,0x86,0x88,0x8f,0x2c,0x0a,0x00,0x00,
+0x00,0x00,0x92,0x00,0x00,0x0c,0x00,0x00,0x80,0x00,0x00,0x00,0x04,0x0c,0x00,0x00,
+0x33,0x54,0x00,0x00,0x08,0x0c,0x00,0x00,0xe4,0x00,0x00,0x00,0x0c,0x0c,0x00,0x00,
+0x6c,0x6c,0x6c,0x6c,0x10,0x0c,0x00,0x00,0x00,0x00,0x00,0x08,0x14,0x0c,0x00,0x00,
+0x00,0x01,0x00,0x40,0x18,0x0c,0x00,0x00,0x00,0x00,0x00,0x08,0x1c,0x0c,0x00,0x00,
+0x00,0x01,0x00,0x40,0x20,0x0c,0x00,0x00,0x00,0x00,0x00,0x08,0x24,0x0c,0x00,0x00,
+0x00,0x01,0x00,0x40,0x28,0x0c,0x00,0x00,0x00,0x00,0x00,0x08,0x2c,0x0c,0x00,0x00,
+0x00,0x01,0x00,0x40,0x30,0x0c,0x00,0x00,0x44,0x6a,0xe9,0x8d,0x34,0x0c,0x00,0x00,
+0xcd,0x52,0x96,0x46,0x38,0x0c,0x00,0x00,0x90,0x5a,0x01,0x48,0x3c,0x0c,0x00,0x00,
+0x64,0x97,0x97,0x1a,0x40,0x0c,0x00,0x00,0x3f,0x42,0x7c,0x1f,0x44,0x0c,0x00,0x00,
+0xb7,0x00,0x01,0x00,0x48,0x0c,0x00,0x00,0x00,0x00,0x02,0xec,0x4c,0x0c,0x00,0x00,
+0x03,0x03,0xfc,0x00,0x50,0x0c,0x00,0x00,0x1c,0x34,0x54,0x69,0x54,0x0c,0x00,0x00,
+0x94,0x00,0x3c,0x43,0x58,0x0c,0x00,0x00,0x1c,0x34,0x54,0x69,0x5c,0x0c,0x00,0x00,
+0x94,0x00,0x3c,0x43,0x60,0x0c,0x00,0x00,0x1c,0x34,0x54,0x69,0x64,0x0c,0x00,0x00,
+0x94,0x00,0x3c,0x43,0x68,0x0c,0x00,0x00,0x1c,0x34,0x54,0x69,0x6c,0x0c,0x00,0x00,
+0x94,0x00,0x3c,0x43,0x70,0x0c,0x00,0x00,0x0d,0x00,0x5a,0x2c,0x74,0x0c,0x00,0x00,
+0x1b,0x15,0x86,0x01,0x78,0x0c,0x00,0x00,0x1f,0x00,0x00,0x00,0x7c,0x0c,0x00,0x00,
+0x12,0x16,0xb9,0x00,0x80,0x0c,0x00,0x00,0x80,0x00,0x00,0x20,0x84,0x0c,0x00,0x00,
+0x00,0x00,0x00,0x00,0x88,0x0c,0x00,0x00,0x80,0x00,0x00,0x20,0x8c,0x0c,0x00,0x00,
+0x00,0x00,0x20,0x08,0x90,0x0c,0x00,0x00,0x00,0x01,0x00,0x40,0x94,0x0c,0x00,0x00,
+0x00,0x00,0x00,0x00,0x98,0x0c,0x00,0x00,0x00,0x01,0x00,0x40,0x9c,0x0c,0x00,0x00,
+0x00,0x00,0x00,0x00,0xa0,0x0c,0x00,0x00,0x92,0x24,0x49,0x00,0xa4,0x0c,0x00,0x00,
+0x00,0x00,0x00,0x00,0xa8,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0xac,0x0c,0x00,0x00,
+0x00,0x00,0x00,0x00,0xb0,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0xb4,0x0c,0x00,0x00,
+0x00,0x00,0x00,0x00,0xb8,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0xbc,0x0c,0x00,0x00,
+0x92,0x24,0x49,0x00,0xc0,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0xc4,0x0c,0x00,0x00,
+0x00,0x00,0x00,0x00,0xc8,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0xcc,0x0c,0x00,0x00,
+0x00,0x00,0x00,0x00,0xd0,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0xd4,0x0c,0x00,0x00,
+0x00,0x00,0x00,0x00,0xd8,0x0c,0x00,0x00,0x27,0x24,0xb2,0x64,0xdc,0x0c,0x00,0x00,
+0x32,0x69,0x76,0x00,0xe0,0x0c,0x00,0x00,0x22,0x22,0x22,0x00,0xe4,0x0c,0x00,0x00,
+0x00,0x00,0x00,0x00,0xe8,0x0c,0x00,0x00,0x02,0x43,0x64,0x07,0x00,0x0d,0x00,0x00,
+0x80,0x07,0x00,0x00,0x04,0x0d,0x00,0x00,0x03,0x04,0x00,0x00,0x08,0x0d,0x00,0x00,
+0x7f,0x90,0x00,0x00,0x0c,0x0d,0x00,0x00,0x01,0x00,0x00,0x00,0x10,0x0d,0x00,0x00,
+0x99,0x99,0x69,0xa0,0x14,0x0d,0x00,0x00,0x67,0x3c,0x99,0x99,0x18,0x0d,0x00,0x00,
+0x6b,0x5b,0x8f,0x6a,0x1c,0x0d,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x0d,0x00,0x00,
+0x00,0x00,0x00,0x00,0x24,0x0d,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x0d,0x00,0x00,
+0x00,0x00,0x00,0x00,0x2c,0x0d,0x00,0x00,0x75,0x19,0x97,0xcc,0x30,0x0d,0x00,0x00,
+0x00,0x00,0x00,0x00,0x34,0x0d,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x0d,0x00,0x00,
+0x00,0x00,0x00,0x00,0x3c,0x0d,0x00,0x00,0x93,0x72,0x02,0x00,0x40,0x0d,0x00,0x00,
+0x00,0x00,0x00,0x00,0x44,0x0d,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x0d,0x00,0x00,
+0x00,0x00,0x00,0x00,0x50,0x0d,0x00,0x00,0x0a,0x14,0x37,0x64,0x54,0x0d,0x00,0x00,
+0x02,0xbd,0x4d,0x02,0x58,0x0d,0x00,0x00,0x00,0x00,0x00,0x00,0x5c,0x0d,0x00,0x00,
+0x64,0x20,0x03,0x30,0x60,0x0d,0x00,0x00,0x68,0xde,0x53,0x46,0x64,0x0d,0x00,0x00,
+0x3c,0x8a,0x51,0x00,0x68,0x0d,0x00,0x00,0x06,0x01,0x00,0x00,0xff,0x00,0x00,0x00,
+0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
+0x44,0x05,0x01,0x80,0x10,0x00,0x00,0x00,0x74,0x05,0x01,0x80,0x10,0x00,0x00,0x00,
+0xe0,0x2e,0x00,0x80,0x10,0x00,0x00,0x00,0xec,0x2e,0x00,0x80,0x10,0x00,0x00,0x00,
+0xa0,0x08,0x01,0x80,0x08,0x00,0x00,0x00,0x38,0x06,0x01,0x80,0x00,0xb7,0x00,0x00,
+0x01,0xe0,0x0e,0x00,0x02,0x4d,0x04,0x00,0x03,0x41,0x04,0x00,0x04,0xc3,0x08,0x00,
+0x05,0x72,0x0c,0x00,0x06,0xe6,0x00,0x00,0x07,0x2a,0x08,0x00,0x08,0x3f,0x00,0x00,
+0x09,0x35,0x03,0x00,0x0a,0xd4,0x09,0x00,0x0b,0xbb,0x07,0x00,0x0c,0x50,0x08,0x00,
+0x0d,0xdf,0x0c,0x00,0x0e,0x2b,0x00,0x00,0x0f,0x14,0x01,0x00,0x00,0xb7,0x01,0x00,
+0x01,0x01,0x00,0x00,0x02,0x00,0x04,0x00,0x01,0x02,0x00,0x00,0x02,0x01,0x04,0x00,
+0x01,0x03,0x00,0x00,0x02,0x02,0x04,0x00,0x01,0x04,0x00,0x00,0x02,0x03,0x04,0x00,
+0x01,0x05,0x00,0x00,0x02,0x04,0x04,0x00,0x01,0x06,0x00,0x00,0x02,0x05,0x04,0x00,
+0x01,0x07,0x00,0x00,0x02,0x08,0x04,0x00,0x01,0x08,0x00,0x00,0x02,0x09,0x04,0x00,
+0x01,0x09,0x00,0x00,0x02,0x0a,0x04,0x00,0x01,0x0a,0x00,0x00,0x02,0x0b,0x04,0x00,
+0x01,0x0b,0x00,0x00,0x02,0x02,0x05,0x00,0x01,0x0c,0x00,0x00,0x02,0x03,0x05,0x00,
+0x01,0x0d,0x00,0x00,0x02,0x04,0x05,0x00,0x01,0x0e,0x00,0x00,0x02,0x05,0x05,0x00,
+0x01,0x0f,0x00,0x00,0x02,0x40,0x05,0x00,0x01,0x10,0x00,0x00,0x02,0x41,0x05,0x00,
+0x01,0x11,0x00,0x00,0x02,0x42,0x05,0x00,0x01,0x12,0x00,0x00,0x02,0x43,0x05,0x00,
+0x01,0x13,0x00,0x00,0x02,0x44,0x05,0x00,0x01,0x14,0x00,0x00,0x02,0x45,0x05,0x00,
+0x01,0x15,0x00,0x00,0x02,0x80,0x05,0x00,0x01,0x16,0x00,0x00,0x02,0x81,0x05,0x00,
+0x01,0x17,0x00,0x00,0x02,0x82,0x05,0x00,0x01,0x18,0x00,0x00,0x02,0x83,0x05,0x00,
+0x01,0x19,0x00,0x00,0x02,0x84,0x05,0x00,0x01,0x1a,0x00,0x00,0x02,0x85,0x05,0x00,
+0x01,0x1b,0x00,0x00,0x02,0x88,0x05,0x00,0x01,0x1c,0x00,0x00,0x02,0x89,0x05,0x00,
+0x01,0x1d,0x00,0x00,0x02,0x8a,0x05,0x00,0x01,0x1e,0x00,0x00,0x02,0x8b,0x05,0x00,
+0x01,0x1f,0x00,0x00,0x02,0x43,0x06,0x00,0x01,0x20,0x00,0x00,0x02,0x44,0x06,0x00,
+0x01,0x21,0x00,0x00,0x02,0x45,0x06,0x00,0x01,0x22,0x00,0x00,0x02,0x80,0x06,0x00,
+0x01,0x23,0x00,0x00,0x02,0x81,0x06,0x00,0x01,0x24,0x00,0x00,0x02,0x82,0x06,0x00,
+0x01,0x25,0x00,0x00,0x02,0x83,0x06,0x00,0x01,0x26,0x00,0x00,0x02,0x84,0x06,0x00,
+0x01,0x27,0x00,0x00,0x02,0x85,0x06,0x00,0x01,0x28,0x00,0x00,0x02,0x88,0x06,0x00,
+0x01,0x29,0x00,0x00,0x02,0x89,0x06,0x00,0x01,0x2a,0x00,0x00,0x02,0x8a,0x06,0x00,
+0x01,0x2b,0x00,0x00,0x02,0x8b,0x06,0x00,0x01,0x2c,0x00,0x00,0x02,0x8c,0x06,0x00,
+0x01,0x2d,0x00,0x00,0x02,0x42,0x07,0x00,0x01,0x2e,0x00,0x00,0x02,0x43,0x07,0x00,
+0x01,0x2f,0x00,0x00,0x02,0x44,0x07,0x00,0x01,0x30,0x00,0x00,0x02,0x45,0x07,0x00,
+0x01,0x31,0x00,0x00,0x02,0x80,0x07,0x00,0x01,0x32,0x00,0x00,0x02,0x81,0x07,0x00,
+0x01,0x33,0x00,0x00,0x02,0x82,0x07,0x00,0x01,0x34,0x00,0x00,0x02,0x83,0x07,0x00,
+0x01,0x35,0x00,0x00,0x02,0x84,0x07,0x00,0x01,0x36,0x00,0x00,0x02,0x85,0x07,0x00,
+0x01,0x37,0x00,0x00,0x02,0x88,0x07,0x00,0x01,0x38,0x00,0x00,0x02,0x89,0x07,0x00,
+0x01,0x39,0x00,0x00,0x02,0x8a,0x07,0x00,0x01,0x3a,0x00,0x00,0x02,0x8b,0x07,0x00,
+0x01,0x3b,0x00,0x00,0x02,0x8c,0x07,0x00,0x01,0x3c,0x00,0x00,0x02,0x8d,0x07,0x00,
+0x01,0x3d,0x00,0x00,0x02,0x90,0x07,0x00,0x01,0x3e,0x00,0x00,0x02,0x91,0x07,0x00,
+0x01,0x3f,0x00,0x00,0x02,0x92,0x07,0x00,0x01,0x40,0x00,0x00,0x02,0x93,0x07,0x00,
+0x01,0x41,0x00,0x00,0x02,0x94,0x07,0x00,0x01,0x42,0x00,0x00,0x02,0x95,0x07,0x00,
+0x01,0x43,0x00,0x00,0x02,0x98,0x07,0x00,0x01,0x44,0x00,0x00,0x02,0x99,0x07,0x00,
+0x01,0x45,0x00,0x00,0x02,0x9a,0x07,0x00,0x01,0x46,0x00,0x00,0x02,0x9b,0x07,0x00,
+0x01,0x47,0x00,0x00,0x02,0x9c,0x07,0x00,0x01,0x48,0x00,0x00,0x02,0x9d,0x07,0x00,
+0x01,0x49,0x00,0x00,0x02,0xa0,0x07,0x00,0x01,0x4a,0x00,0x00,0x02,0xa1,0x07,0x00,
+0x01,0x4b,0x00,0x00,0x02,0xa2,0x07,0x00,0x01,0x4c,0x00,0x00,0x02,0xa3,0x07,0x00,
+0x01,0x4d,0x00,0x00,0x02,0xa4,0x07,0x00,0x01,0x4e,0x00,0x00,0x02,0xa5,0x07,0x00,
+0x01,0x4f,0x00,0x00,0x02,0xa8,0x07,0x00,0x01,0x50,0x00,0x00,0x02,0xa9,0x07,0x00,
+0x01,0x51,0x00,0x00,0x02,0xaa,0x03,0x00,0x01,0x52,0x00,0x00,0x02,0xab,0x03,0x00,
+0x01,0x53,0x00,0x00,0x02,0xac,0x03,0x00,0x01,0x54,0x00,0x00,0x02,0xad,0x03,0x00,
+0x01,0x55,0x00,0x00,0x02,0xb0,0x03,0x00,0x01,0x56,0x00,0x00,0x02,0xb1,0x03,0x00,
+0x01,0x57,0x00,0x00,0x02,0xb2,0x03,0x00,0x01,0x58,0x00,0x00,0x02,0xb3,0x03,0x00,
+0x01,0x59,0x00,0x00,0x02,0xb4,0x03,0x00,0x01,0x5a,0x00,0x00,0x02,0xb5,0x03,0x00,
+0x01,0x5b,0x00,0x00,0x02,0xb8,0x03,0x00,0x01,0x5c,0x00,0x00,0x02,0xb9,0x03,0x00,
+0x01,0x5d,0x00,0x00,0x02,0xba,0x03,0x00,0x01,0x5e,0x00,0x00,0x02,0xbb,0x03,0x00,
+0x01,0x5f,0x00,0x00,0x02,0xbb,0x03,0x00,0x03,0x80,0x00,0x00,0x05,0x04,0x00,0x00,
+0x00,0xb7,0x00,0x00,0xfe,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,
+0x02,0x4d,0x0c,0x00,0xfe,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,0x02,0x4d,0x04,0x00,
+0x00,0xbf,0x02,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x00,0xb7,0x00,0x00,
+0x01,0xe0,0x0e,0x00,0x02,0x4d,0x04,0x00,0x03,0x41,0x04,0x00,0x04,0xc3,0x08,0x00,
+0x05,0x72,0x0c,0x00,0x06,0xe6,0x00,0x00,0x07,0x2a,0x08,0x00,0x08,0x3f,0x00,0x00,
+0x09,0x35,0x03,0x00,0x0a,0xd4,0x09,0x00,0x0b,0xbb,0x07,0x00,0x0c,0x50,0x08,0x00,
+0x0d,0xdf,0x0c,0x00,0x0e,0x2b,0x00,0x00,0x0f,0x14,0x01,0x00,0x00,0xb7,0x01,0x00,
+0x01,0x01,0x00,0x00,0x02,0x00,0x04,0x00,0x01,0x02,0x00,0x00,0x02,0x01,0x04,0x00,
+0x01,0x03,0x00,0x00,0x02,0x02,0x04,0x00,0x01,0x04,0x00,0x00,0x02,0x03,0x04,0x00,
+0x01,0x05,0x00,0x00,0x02,0x04,0x04,0x00,0x01,0x06,0x00,0x00,0x02,0x05,0x04,0x00,
+0x01,0x07,0x00,0x00,0x02,0x08,0x04,0x00,0x01,0x08,0x00,0x00,0x02,0x09,0x04,0x00,
+0x01,0x09,0x00,0x00,0x02,0x0a,0x04,0x00,0x01,0x0a,0x00,0x00,0x02,0x0b,0x04,0x00,
+0x01,0x0b,0x00,0x00,0x02,0x02,0x05,0x00,0x01,0x0c,0x00,0x00,0x02,0x03,0x05,0x00,
+0x01,0x0d,0x00,0x00,0x02,0x04,0x05,0x00,0x01,0x0e,0x00,0x00,0x02,0x05,0x05,0x00,
+0x01,0x0f,0x00,0x00,0x02,0x40,0x05,0x00,0x01,0x10,0x00,0x00,0x02,0x41,0x05,0x00,
+0x01,0x11,0x00,0x00,0x02,0x42,0x05,0x00,0x01,0x12,0x00,0x00,0x02,0x43,0x05,0x00,
+0x01,0x13,0x00,0x00,0x02,0x44,0x05,0x00,0x01,0x14,0x00,0x00,0x02,0x45,0x05,0x00,
+0x01,0x15,0x00,0x00,0x02,0x80,0x05,0x00,0x01,0x16,0x00,0x00,0x02,0x81,0x05,0x00,
+0x01,0x17,0x00,0x00,0x02,0x82,0x05,0x00,0x01,0x18,0x00,0x00,0x02,0x83,0x05,0x00,
+0x01,0x19,0x00,0x00,0x02,0x84,0x05,0x00,0x01,0x1a,0x00,0x00,0x02,0x85,0x05,0x00,
+0x01,0x1b,0x00,0x00,0x02,0x88,0x05,0x00,0x01,0x1c,0x00,0x00,0x02,0x89,0x05,0x00,
+0x01,0x1d,0x00,0x00,0x02,0x8a,0x05,0x00,0x01,0x1e,0x00,0x00,0x02,0x8b,0x05,0x00,
+0x01,0x1f,0x00,0x00,0x02,0x43,0x06,0x00,0x01,0x20,0x00,0x00,0x02,0x44,0x06,0x00,
+0x01,0x21,0x00,0x00,0x02,0x45,0x06,0x00,0x01,0x22,0x00,0x00,0x02,0x80,0x06,0x00,
+0x01,0x23,0x00,0x00,0x02,0x81,0x06,0x00,0x01,0x24,0x00,0x00,0x02,0x82,0x06,0x00,
+0x01,0x25,0x00,0x00,0x02,0x83,0x06,0x00,0x01,0x26,0x00,0x00,0x02,0x84,0x06,0x00,
+0x01,0x27,0x00,0x00,0x02,0x85,0x06,0x00,0x01,0x28,0x00,0x00,0x02,0x88,0x06,0x00,
+0x01,0x29,0x00,0x00,0x02,0x89,0x06,0x00,0x01,0x2a,0x00,0x00,0x02,0x8a,0x06,0x00,
+0x01,0x2b,0x00,0x00,0x02,0x8b,0x06,0x00,0x01,0x2c,0x00,0x00,0x02,0x8c,0x06,0x00,
+0x01,0x2d,0x00,0x00,0x02,0x42,0x07,0x00,0x01,0x2e,0x00,0x00,0x02,0x43,0x07,0x00,
+0x01,0x2f,0x00,0x00,0x02,0x44,0x07,0x00,0x01,0x30,0x00,0x00,0x02,0x45,0x07,0x00,
+0x01,0x31,0x00,0x00,0x02,0x80,0x07,0x00,0x01,0x32,0x00,0x00,0x02,0x81,0x07,0x00,
+0x01,0x33,0x00,0x00,0x02,0x82,0x07,0x00,0x01,0x34,0x00,0x00,0x02,0x83,0x07,0x00,
+0x01,0x35,0x00,0x00,0x02,0x84,0x07,0x00,0x01,0x36,0x00,0x00,0x02,0x85,0x07,0x00,
+0x01,0x37,0x00,0x00,0x02,0x88,0x07,0x00,0x01,0x38,0x00,0x00,0x02,0x89,0x07,0x00,
+0x01,0x39,0x00,0x00,0x02,0x8a,0x07,0x00,0x01,0x3a,0x00,0x00,0x02,0x8b,0x07,0x00,
+0x01,0x3b,0x00,0x00,0x02,0x8c,0x07,0x00,0x01,0x3c,0x00,0x00,0x02,0x8d,0x07,0x00,
+0x01,0x3d,0x00,0x00,0x02,0x90,0x07,0x00,0x01,0x3e,0x00,0x00,0x02,0x91,0x07,0x00,
+0x01,0x3f,0x00,0x00,0x02,0x92,0x07,0x00,0x01,0x40,0x00,0x00,0x02,0x93,0x07,0x00,
+0x01,0x41,0x00,0x00,0x02,0x94,0x07,0x00,0x01,0x42,0x00,0x00,0x02,0x95,0x07,0x00,
+0x01,0x43,0x00,0x00,0x02,0x98,0x07,0x00,0x01,0x44,0x00,0x00,0x02,0x99,0x07,0x00,
+0x01,0x45,0x00,0x00,0x02,0x9a,0x07,0x00,0x01,0x46,0x00,0x00,0x02,0x9b,0x07,0x00,
+0x01,0x47,0x00,0x00,0x02,0x9c,0x07,0x00,0x01,0x48,0x00,0x00,0x02,0x9d,0x07,0x00,
+0x01,0x49,0x00,0x00,0x02,0xa0,0x07,0x00,0x01,0x4a,0x00,0x00,0x02,0xa1,0x07,0x00,
+0x01,0x4b,0x00,0x00,0x02,0xa2,0x07,0x00,0x01,0x4c,0x00,0x00,0x02,0xa3,0x07,0x00,
+0x01,0x4d,0x00,0x00,0x02,0xa4,0x07,0x00,0x01,0x4e,0x00,0x00,0x02,0xa5,0x07,0x00,
+0x01,0x4f,0x00,0x00,0x02,0xa8,0x07,0x00,0x01,0x50,0x00,0x00,0x02,0xa9,0x07,0x00,
+0x01,0x51,0x00,0x00,0x02,0xaa,0x03,0x00,0x01,0x52,0x00,0x00,0x02,0xab,0x03,0x00,
+0x01,0x53,0x00,0x00,0x02,0xac,0x03,0x00,0x01,0x54,0x00,0x00,0x02,0xad,0x03,0x00,
+0x01,0x55,0x00,0x00,0x02,0xb0,0x03,0x00,0x01,0x56,0x00,0x00,0x02,0xb1,0x03,0x00,
+0x01,0x57,0x00,0x00,0x02,0xb2,0x03,0x00,0x01,0x58,0x00,0x00,0x02,0xb3,0x03,0x00,
+0x01,0x59,0x00,0x00,0x02,0xb4,0x03,0x00,0x01,0x5a,0x00,0x00,0x02,0xb5,0x03,0x00,
+0x01,0x5b,0x00,0x00,0x02,0xb8,0x03,0x00,0x01,0x5c,0x00,0x00,0x02,0xb9,0x03,0x00,
+0x01,0x5d,0x00,0x00,0x02,0xba,0x03,0x00,0x01,0x5e,0x00,0x00,0x02,0xbb,0x03,0x00,
+0x01,0x5f,0x00,0x00,0x02,0xbb,0x03,0x00,0x03,0x80,0x00,0x00,0x05,0x04,0x00,0x00,
+0x00,0xb7,0x00,0x00,0xfe,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,
+0x02,0x4d,0x0c,0x00,0xfe,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,0x02,0x4d,0x04,0x00,
+0x00,0xbf,0x02,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x0a,0x00,0x00,0x00,
+0x4f,0x6e,0x41,0x73,0x73,0x6f,0x63,0x52,0x65,0x71,0x00,0x00,0x4f,0x6e,0x41,0x73,
+0x73,0x6f,0x63,0x52,0x73,0x70,0x00,0x00,0x4f,0x6e,0x52,0x65,0x41,0x73,0x73,0x6f,
+0x63,0x52,0x65,0x71,0x00,0x00,0x00,0x00,0x4f,0x6e,0x52,0x65,0x41,0x73,0x73,0x6f,
+0x63,0x52,0x73,0x70,0x00,0x00,0x00,0x00,0x4f,0x6e,0x50,0x72,0x6f,0x62,0x65,0x52,
+0x65,0x71,0x00,0x00,0x4f,0x6e,0x50,0x72,0x6f,0x62,0x65,0x52,0x73,0x70,0x00,0x00,
+0x44,0x6f,0x52,0x65,0x73,0x65,0x72,0x76,0x65,0x64,0x00,0x00,0x44,0x6f,0x52,0x65,
+0x73,0x65,0x72,0x76,0x65,0x64,0x00,0x00,0x4f,0x6e,0x42,0x65,0x61,0x63,0x6f,0x6e,
+0x00,0x00,0x00,0x00,0x4f,0x6e,0x41,0x54,0x49,0x4d,0x00,0x00,0x4f,0x6e,0x44,0x69,
+0x73,0x61,0x73,0x73,0x6f,0x63,0x00,0x00,0x4f,0x6e,0x41,0x75,0x74,0x68,0x00,0x00,
+0x4f,0x6e,0x44,0x65,0x41,0x75,0x74,0x68,0x00,0x00,0x00,0x00,0x4f,0x6e,0x41,0x63,
+0x74,0x69,0x6f,0x6e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x88,0x8b,0x01,0x80,
+0x28,0x14,0x01,0x80,0x10,0x00,0x00,0x00,0x94,0x8b,0x01,0x80,0x30,0x14,0x01,0x80,
+0x20,0x00,0x00,0x00,0xa0,0x8b,0x01,0x80,0x28,0x14,0x01,0x80,0x30,0x00,0x00,0x00,
+0xb0,0x8b,0x01,0x80,0x30,0x14,0x01,0x80,0x40,0x00,0x00,0x00,0xc0,0x8b,0x01,0x80,
+0x38,0x14,0x01,0x80,0x50,0x00,0x00,0x00,0xcc,0x8b,0x01,0x80,0x40,0x14,0x01,0x80,
+0x00,0x00,0x00,0x00,0xd8,0x8b,0x01,0x80,0xa8,0x14,0x01,0x80,0x00,0x00,0x00,0x00,
+0xe4,0x8b,0x01,0x80,0xa8,0x14,0x01,0x80,0x80,0x00,0x00,0x00,0xf0,0x8b,0x01,0x80,
+0x48,0x14,0x01,0x80,0x90,0x00,0x00,0x00,0xfc,0x8b,0x01,0x80,0x50,0x14,0x01,0x80,
+0xa0,0x00,0x00,0x00,0x04,0x8c,0x01,0x80,0x58,0x14,0x01,0x80,0xb0,0x00,0x00,0x00,
+0x10,0x8c,0x01,0x80,0x90,0x14,0x01,0x80,0xc0,0x00,0x00,0x00,0x18,0x8c,0x01,0x80,
+0x98,0x14,0x01,0x80,0xd0,0x00,0x00,0x00,0x24,0x8c,0x01,0x80,0xa0,0x14,0x01,0x80,
+0x00,0x00,0x00,0x00,0xdc,0x8c,0x01,0x80,0xdc,0x8c,0x01,0x80,0x31,0x10,0x10,0x00,
+0x00,0x30,0x00,0x00,0x31,0x20,0x10,0x00,0x00,0x30,0x00,0x00,0x31,0x28,0x10,0x00,
+0x00,0x30,0x00,0x00,0x31,0x2c,0x10,0x10,0x00,0x30,0x00,0x00,0x31,0x2f,0x10,0x10,
+0x00,0x30,0x00,0x00,0x31,0x30,0x18,0x00,0x00,0x30,0x00,0x00,0x31,0x30,0x20,0x10,
+0x00,0x30,0x00,0x00,0x22,0x20,0x18,0x08,0x00,0x20,0x00,0x00,0x22,0x21,0x14,0x08,
+0x00,0x20,0x00,0x00,0x22,0x21,0x1c,0x08,0x00,0x20,0x00,0x00,0x22,0x21,0x20,0x08,
+0x00,0x20,0x00,0x00,0x22,0x21,0x20,0x10,0x00,0x20,0x00,0x00,0x22,0x21,0x20,0x18,
+0x00,0x20,0x00,0x00,0x1a,0x19,0x18,0x10,0x00,0x18,0x00,0x00,0x12,0x11,0x10,0x08,
+0x00,0x10,0x00,0x00,0x0a,0x09,0x08,0x00,0x00,0x08,0x00,0x00,0x0a,0x09,0x08,0x02,
+0x00,0x08,0x00,0x00,0x0a,0x09,0x08,0x04,0x00,0x08,0x00,0x00,0x0a,0x09,0x08,0x06,
+0x00,0x08,0x00,0x00,0x08,0x07,0x06,0x04,0x00,0x06,0x00,0x00,0x06,0x05,0x04,0x02,
+0x00,0x04,0x00,0x00,0x06,0x05,0x04,0x03,0x00,0x04,0x00,0x00,0x05,0x04,0x03,0x02,
+0x00,0x03,0x00,0x00,0x09,0x08,0x07,0x06,0x07,0x06,0x06,0x05,0x05,0x04,0x04,0x03,
+0x06,0x05,0x05,0x04,0x04,0x03,0x03,0x03,0x05,0x04,0x04,0x03,0x03,0x02,0x02,0x02,
+0x00,0x09,0x08,0x07,0x06,0x07,0x06,0x06,0x05,0x05,0x04,0x04,0x03,0x05,0x04,0x04,
+0x03,0x03,0x02,0x02,0x02,0x04,0x03,0x03,0x02,0x02,0x01,0x01,0x01,0x00,0x00,0x00,
+0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x10,0x10,0x20,0x08,0x08,0x08,0x08,
+0x20,0x20,0x20,0x20,0x08,0x08,0x08,0x08,0x08,0x20,0x20,0x20,0x30,0x08,0x08,0x08,
+0x08,0x18,0x18,0x18,0x18,0x18,0x20,0x30,0x30,0x10,0x20,0x20,0x20,0x20,0x20,0x30,
+0x30,0x08,0x10,0x20,0x30,0x30,0x30,0x30,0x30,0x30,0x00,0x00,0x08,0x08,0x08,0x08,
+0x08,0x08,0x08,0x08,0x08,0x10,0x10,0x20,0x08,0x08,0x08,0x08,0x08,0x20,0x20,0x20,
+0x08,0x08,0x08,0x08,0x08,0x20,0x20,0x20,0x20,0x08,0x08,0x08,0x08,0x18,0x18,0x18,
+0x18,0x18,0x20,0x30,0x30,0x10,0x20,0x20,0x20,0x20,0x20,0x30,0x30,0x08,0x10,0x20,
+0x30,0x30,0x30,0x30,0x30,0x30,0x00,0x00,0x0a,0x09,0x08,0x04,0x00,0x0a,0x09,0x08,
+0x04,0x00,0x0a,0x09,0x08,0x04,0x00,0x0a,0x09,0x08,0x04,0x00,0x0a,0x09,0x08,0x00,
+0x00,0x0a,0x09,0x08,0x00,0x00,0x0a,0x09,0x08,0x00,0x00,0x0a,0x09,0x08,0x00,0x00,
+0x0a,0x09,0x08,0x00,0x00,0x12,0x11,0x10,0x08,0x00,0x12,0x11,0x10,0x08,0x00,0x22,
+0x21,0x20,0x18,0x00,0x0a,0x09,0x08,0x00,0x00,0x0a,0x09,0x08,0x00,0x00,0x0a,0x09,
+0x08,0x00,0x00,0x0a,0x09,0x08,0x00,0x00,0x22,0x21,0x20,0x18,0x00,0x22,0x21,0x20,
+0x18,0x00,0x22,0x21,0x1c,0x08,0x00,0x22,0x20,0x18,0x08,0x00,0x0a,0x09,0x08,0x02,
+0x00,0x0a,0x09,0x08,0x02,0x00,0x0a,0x09,0x08,0x02,0x00,0x0a,0x09,0x08,0x02,0x00,
+0x0a,0x09,0x08,0x00,0x00,0x22,0x21,0x20,0x10,0x00,0x22,0x21,0x20,0x08,0x00,0x22,
+0x21,0x1c,0x08,0x00,0x31,0x30,0x18,0x00,0x00,0x0a,0x09,0x08,0x04,0x00,0x0a,0x09,
+0x08,0x04,0x00,0x0a,0x09,0x08,0x04,0x00,0x0a,0x09,0x08,0x04,0x00,0x1a,0x19,0x18,
+0x10,0x00,0x1a,0x19,0x18,0x10,0x00,0x1a,0x19,0x18,0x10,0x00,0x1a,0x19,0x18,0x10,
+0x00,0x1a,0x19,0x18,0x10,0x00,0x22,0x21,0x20,0x08,0x00,0x31,0x2c,0x10,0x10,0x00,
+0x31,0x28,0x10,0x00,0x00,0x12,0x11,0x10,0x08,0x00,0x22,0x21,0x20,0x18,0x00,0x22,
+0x21,0x20,0x18,0x00,0x22,0x21,0x20,0x08,0x00,0x22,0x21,0x14,0x08,0x00,0x22,0x20,
+0x18,0x08,0x00,0x31,0x30,0x20,0x10,0x00,0x31,0x2c,0x10,0x10,0x00,0x0a,0x09,0x08,
+0x00,0x00,0x12,0x11,0x10,0x08,0x00,0x22,0x21,0x20,0x18,0x00,0x22,0x21,0x20,0x18,
+0x00,0x31,0x30,0x20,0x10,0x00,0x31,0x2f,0x10,0x10,0x00,0x31,0x2f,0x10,0x10,0x00,
+0x31,0x10,0x10,0x00,0x00,0x31,0x2c,0x10,0x10,0x00,0x00,0x00,0x0a,0x09,0x08,0x04,
+0x00,0x0a,0x09,0x08,0x04,0x00,0x0a,0x09,0x08,0x04,0x00,0x0a,0x09,0x08,0x04,0x00,
+0x0a,0x09,0x08,0x00,0x00,0x0a,0x09,0x08,0x00,0x00,0x0a,0x09,0x08,0x00,0x00,0x0a,
+0x09,0x08,0x00,0x00,0x0a,0x09,0x08,0x00,0x00,0x12,0x11,0x10,0x08,0x00,0x12,0x11,
+0x10,0x08,0x00,0x22,0x21,0x20,0x18,0x00,0x0a,0x09,0x08,0x04,0x00,0x0a,0x09,0x08,
+0x04,0x00,0x0a,0x09,0x08,0x02,0x00,0x0a,0x09,0x08,0x00,0x00,0x0a,0x09,0x08,0x00,
+0x00,0x22,0x21,0x20,0x18,0x00,0x22,0x21,0x1c,0x08,0x00,0x22,0x21,0x14,0x08,0x00,
+0x0a,0x09,0x08,0x02,0x00,0x0a,0x09,0x08,0x02,0x00,0x0a,0x09,0x08,0x02,0x00,0x0a,
+0x09,0x08,0x02,0x00,0x0a,0x09,0x08,0x00,0x00,0x22,0x21,0x20,0x10,0x00,0x22,0x21,
+0x20,0x08,0x00,0x22,0x21,0x14,0x08,0x00,0x22,0x21,0x14,0x08,0x00,0x0a,0x09,0x08,
+0x04,0x00,0x0a,0x09,0x08,0x04,0x00,0x0a,0x09,0x08,0x04,0x00,0x0a,0x09,0x08,0x04,
+0x00,0x1a,0x19,0x18,0x10,0x00,0x1a,0x19,0x18,0x10,0x00,0x1a,0x19,0x18,0x10,0x00,
+0x1a,0x19,0x18,0x10,0x00,0x1a,0x19,0x18,0x10,0x00,0x22,0x21,0x20,0x08,0x00,0x31,
+0x2c,0x10,0x10,0x00,0x31,0x28,0x10,0x00,0x00,0x12,0x11,0x10,0x08,0x00,0x22,0x21,
+0x20,0x18,0x00,0x22,0x21,0x20,0x18,0x00,0x22,0x21,0x20,0x08,0x00,0x22,0x21,0x14,
+0x08,0x00,0x22,0x20,0x18,0x08,0x00,0x31,0x30,0x20,0x10,0x00,0x31,0x2c,0x10,0x10,
+0x00,0x0a,0x09,0x08,0x00,0x00,0x12,0x11,0x10,0x08,0x00,0x22,0x21,0x20,0x18,0x00,
+0x22,0x21,0x20,0x18,0x00,0x31,0x30,0x20,0x10,0x00,0x31,0x2f,0x10,0x10,0x00,0x31,
+0x2f,0x10,0x10,0x00,0x31,0x10,0x10,0x00,0x00,0x31,0x2c,0x10,0x10,0x00,0x00,0x00,
+0x01,0x02,0x04,0x08,0x02,0x04,0x08,0x0c,0x10,0x18,0x20,0x30,0x02,0x04,0x08,0x0c,
+0x10,0x18,0x20,0x30,0x06,0x0c,0x10,0x18,0x24,0x30,0x3c,0x48,0x48,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x25,0x27,0x2c,0x19,0x1b,0x1e,0x20,
+0x23,0x29,0x2a,0x2b,0x00,0x00,0x00,0x00,0x25,0x29,0x2b,0x2e,0x2e,0x00,0x00,0x00,
+0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x10,0x00,0x00,0x00,
+0x18,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x48,0x00,0x00,0x00,
+0x60,0x00,0x00,0x00,0x90,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0xd8,0x00,0x00,0x00,
+0x50,0x00,0x00,0x00,0x78,0x00,0x00,0x00,0xa0,0x00,0x00,0x00,0xc8,0x00,0x00,0x00,
+0x40,0x01,0x00,0x00,0x90,0x01,0x00,0x00,0xe0,0x01,0x00,0x00,0x30,0x02,0x00,0x00,
+0x2c,0x01,0x00,0x00,0x40,0x01,0x00,0x00,0xe0,0x01,0x00,0x00,0xd0,0x02,0x00,0x00,
+0x80,0x0c,0x00,0x00,0x80,0x0c,0x00,0x00,0x80,0x0c,0x00,0x00,0xa0,0x0f,0x00,0x00,
+0xa0,0x0f,0x00,0x00,0x02,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
+0x08,0x00,0x00,0x00,0x0c,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x18,0x00,0x00,0x00,
+0x24,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x48,0x00,0x00,0x00,0x60,0x00,0x00,0x00,
+0x6c,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x3c,0x00,0x00,0x00,0x50,0x00,0x00,0x00,
+0x64,0x00,0x00,0x00,0xa0,0x00,0x00,0x00,0xc8,0x00,0x00,0x00,0xf0,0x00,0x00,0x00,
+0x18,0x01,0x00,0x00,0x64,0x00,0x00,0x00,0xa0,0x00,0x00,0x00,0xf0,0x00,0x00,0x00,
+0x68,0x01,0x00,0x00,0x40,0x06,0x00,0x00,0x40,0x06,0x00,0x00,0x40,0x06,0x00,0x00,
+0xd0,0x07,0x00,0x00,0xd0,0x07,0x00,0x00,0x2c,0x05,0x00,0x80,0x20,0x05,0x00,0x80,
+0x14,0x05,0x00,0x80,0x08,0x05,0x00,0x80,0xfc,0x04,0x00,0x80,0xf0,0x04,0x00,0x80,
+0xe4,0x04,0x00,0x80,0xd8,0x04,0x00,0x80,0xcc,0x04,0x00,0x80,0xc0,0x04,0x00,0x80,
+0x78,0x04,0x00,0x80,0x68,0x15,0x02,0x80,0xc0,0x3a,0x00,0x80,0xcc,0x3a,0x00,0x80,
+0xd8,0x3a,0x00,0x80,0xe4,0x3a,0x00,0x80,0xc0,0x3a,0x00,0x80,0xc0,0x3a,0x00,0x80,
+0xc0,0x3a,0x00,0x80,0xc0,0x3a,0x00,0x80,0xf0,0x3a,0x00,0x80,0xfc,0x3a,0x00,0x80,
+0x08,0x3b,0x00,0x80,0x14,0x3b,0x00,0x80,0x68,0x15,0x02,0x80,0xfe,0x01,0x80,0x7f,
+0xe2,0x01,0x80,0x78,0xc7,0x01,0xc0,0x71,0xae,0x01,0x80,0x6b,0x95,0x01,0x40,0x65,
+0x7f,0x01,0xc0,0x5f,0x69,0x01,0x40,0x5a,0x55,0x01,0x40,0x55,0x42,0x01,0x80,0x50,
+0x30,0x01,0x00,0x4c,0x1f,0x01,0xc0,0x47,0x0f,0x01,0xc0,0x43,0x00,0x01,0x00,0x40,
+0xf2,0x00,0x80,0x3c,0xe4,0x00,0x00,0x39,0xd7,0x00,0xc0,0x35,0xcb,0x00,0xc0,0x32,
+0xc0,0x00,0x00,0x30,0xb5,0x00,0x40,0x2d,0xab,0x00,0xc0,0x2a,0xa2,0x00,0x80,0x28,
+0x98,0x00,0x00,0x26,0x90,0x00,0x00,0x24,0x88,0x00,0x00,0x22,0x80,0x00,0x00,0x20,
+0x79,0x00,0x40,0x1e,0x72,0x00,0x80,0x1c,0x6c,0x00,0x00,0x1b,0x66,0x00,0x80,0x19,
+0x60,0x00,0x00,0x18,0x5b,0x00,0xc0,0x16,0x56,0x00,0x80,0x15,0x51,0x00,0x40,0x14,
+0x4c,0x00,0x00,0x13,0x48,0x00,0x00,0x12,0x44,0x00,0x00,0x11,0x40,0x00,0x00,0x10,
+0x36,0x35,0x2e,0x25,0x1c,0x12,0x09,0x04,0x33,0x32,0x2b,0x23,0x1a,0x11,0x08,0x04,
+0x30,0x2f,0x29,0x21,0x19,0x10,0x08,0x03,0x2d,0x2d,0x27,0x1f,0x18,0x0f,0x08,0x03,
+0x2b,0x2a,0x25,0x1e,0x16,0x0e,0x07,0x03,0x28,0x28,0x22,0x1c,0x15,0x0d,0x07,0x03,
+0x26,0x25,0x21,0x1b,0x14,0x0d,0x06,0x03,0x24,0x23,0x1f,0x19,0x13,0x0c,0x06,0x03,
+0x22,0x21,0x1d,0x18,0x11,0x0b,0x06,0x02,0x20,0x20,0x1b,0x16,0x11,0x08,0x05,0x02,
+0x1f,0x1e,0x1a,0x15,0x10,0x0a,0x05,0x02,0x1d,0x1c,0x18,0x14,0x0f,0x0a,0x05,0x02,
+0x1b,0x1a,0x17,0x13,0x0e,0x09,0x04,0x02,0x1a,0x19,0x16,0x12,0x0d,0x09,0x04,0x02,
+0x18,0x17,0x15,0x11,0x0c,0x08,0x04,0x02,0x17,0x16,0x13,0x10,0x0c,0x08,0x04,0x02,
+0x16,0x15,0x12,0x0f,0x0b,0x07,0x04,0x01,0x14,0x14,0x11,0x0e,0x0b,0x07,0x03,0x02,
+0x13,0x13,0x10,0x0d,0x0a,0x06,0x03,0x01,0x12,0x12,0x0f,0x0c,0x09,0x06,0x03,0x01,
+0x11,0x11,0x0f,0x0c,0x09,0x06,0x03,0x01,0x10,0x10,0x0e,0x0b,0x08,0x05,0x03,0x01,
+0x0f,0x0f,0x0d,0x0b,0x08,0x05,0x03,0x01,0x0e,0x0e,0x0c,0x0a,0x08,0x05,0x02,0x01,
+0x0d,0x0d,0x0c,0x0a,0x07,0x05,0x02,0x01,0x0d,0x0c,0x0b,0x09,0x07,0x04,0x02,0x01,
+0x0c,0x0c,0x0a,0x09,0x06,0x04,0x02,0x01,0x0b,0x0b,0x0a,0x08,0x06,0x04,0x02,0x01,
+0x0b,0x0a,0x09,0x08,0x06,0x04,0x02,0x01,0x0a,0x0a,0x09,0x07,0x05,0x03,0x02,0x01,
+0x0a,0x09,0x08,0x07,0x05,0x03,0x02,0x01,0x09,0x09,0x08,0x06,0x05,0x03,0x01,0x01,
+0x09,0x08,0x07,0x06,0x04,0x03,0x01,0x01,0x36,0x35,0x2e,0x1b,0x00,0x00,0x00,0x00,
+0x33,0x32,0x2b,0x19,0x00,0x00,0x00,0x00,0x30,0x2f,0x29,0x18,0x00,0x00,0x00,0x00,
+0x2d,0x2d,0x17,0x17,0x00,0x00,0x00,0x00,0x2b,0x2a,0x25,0x15,0x00,0x00,0x00,0x00,
+0x28,0x28,0x24,0x14,0x00,0x00,0x00,0x00,0x26,0x25,0x21,0x13,0x00,0x00,0x00,0x00,
+0x24,0x23,0x1f,0x12,0x00,0x00,0x00,0x00,0x22,0x21,0x1d,0x11,0x00,0x00,0x00,0x00,
+0x20,0x20,0x1b,0x10,0x00,0x00,0x00,0x00,0x1f,0x1e,0x1a,0x0f,0x00,0x00,0x00,0x00,
+0x1d,0x1c,0x18,0x0e,0x00,0x00,0x00,0x00,0x1b,0x1a,0x17,0x0e,0x00,0x00,0x00,0x00,
+0x1a,0x19,0x16,0x0d,0x00,0x00,0x00,0x00,0x18,0x17,0x15,0x0c,0x00,0x00,0x00,0x00,
+0x17,0x16,0x13,0x0b,0x00,0x00,0x00,0x00,0x16,0x15,0x12,0x0b,0x00,0x00,0x00,0x00,
+0x14,0x14,0x11,0x0a,0x00,0x00,0x00,0x00,0x13,0x13,0x10,0x0a,0x00,0x00,0x00,0x00,
+0x12,0x12,0x0f,0x09,0x00,0x00,0x00,0x00,0x11,0x11,0x0f,0x09,0x00,0x00,0x00,0x00,
+0x10,0x10,0x0e,0x08,0x00,0x00,0x00,0x00,0x0f,0x0f,0x0d,0x08,0x00,0x00,0x00,0x00,
+0x0e,0x0e,0x0c,0x07,0x00,0x00,0x00,0x00,0x0d,0x0d,0x0c,0x07,0x00,0x00,0x00,0x00,
+0x0d,0x0c,0x0b,0x06,0x00,0x00,0x00,0x00,0x0c,0x0c,0x0a,0x06,0x00,0x00,0x00,0x00,
+0x0b,0x0b,0x0a,0x06,0x00,0x00,0x00,0x00,0x0b,0x0a,0x09,0x05,0x00,0x00,0x00,0x00,
+0x0a,0x0a,0x09,0x05,0x00,0x00,0x00,0x00,0x0a,0x09,0x08,0x05,0x00,0x00,0x00,0x00,
+0x09,0x09,0x08,0x05,0x00,0x00,0x00,0x00,0x09,0x08,0x07,0x04,0x00,0x00,0x00,0x00,
+0x06,0x00,0x2a,0xb0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,
+0x08,0x28,0x28,0x28,0x28,0x28,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,
+0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0xa0,0x10,0x10,0x10,0x10,0x10,0x10,0x10,
+0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,
+0x04,0x04,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x41,0x41,0x41,0x41,0x41,0x41,0x01,
+0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,
+0x01,0x01,0x01,0x10,0x10,0x10,0x10,0x10,0x10,0x42,0x42,0x42,0x42,0x42,0x42,0x02,
+0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,
+0x02,0x02,0x02,0x10,0x10,0x10,0x10,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xa0,0x10,0x10,0x10,0x10,0x10,0x10,0x10,
+0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,
+0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,
+0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x10,
+0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,
+0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x10,
+0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x00,0x19,0x77,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x26,0x72,0xb0,0x00,0x26,0x72,0xb0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x26,0x65,0x60,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x02,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0xf2,0x30,0xb8,0xff,0xff,0xff,0xff,
+};
+
+u8 Rtl8192SUFwMainArray[MainArrayLength] = {
+0x0, };
+
+u8 Rtl8192SUFwDataArray[DataArrayLength] = {
+0x0, };
+
+u32 Rtl8192SUPHY_REG_2T2RArray[PHY_REG_2T2RArrayLength] = {
+0x01c,0x07000000,
+0x800,0x00040000,
+0x804,0x00008003,
+0x808,0x0000fc00,
+0x80c,0x0000000a,
+0x810,0x10005088,
+0x814,0x020c3d10,
+0x818,0x00200185,
+0x81c,0x00000000,
+0x820,0x01000000,
+0x824,0x00390004,
+0x828,0x01000000,
+0x82c,0x00390004,
+0x830,0x00000004,
+0x834,0x00690200,
+0x838,0x00000004,
+0x83c,0x00690200,
+0x840,0x00010000,
+0x844,0x00010000,
+0x848,0x00000000,
+0x84c,0x00000000,
+0x850,0x00000000,
+0x854,0x00000000,
+0x858,0x48484848,
+0x85c,0x65a965a9,
+0x860,0x0f7f0130,
+0x864,0x0f7f0130,
+0x868,0x0f7f0130,
+0x86c,0x0f7f0130,
+0x870,0x03000700,
+0x874,0x03000300,
+0x878,0x00020002,
+0x87c,0x004f0201,
+0x880,0xa8300ac1,
+0x884,0x00000058,
+0x888,0x00000008,
+0x88c,0x00000004,
+0x890,0x00000000,
+0x894,0xfffffffe,
+0x898,0x40302010,
+0x89c,0x00706050,
+0x8b0,0x00000000,
+0x8e0,0x00000000,
+0x8e4,0x00000000,
+0xe00,0x30333333,
+0xe04,0x2a2d2e2f,
+0xe08,0x00003232,
+0xe10,0x30333333,
+0xe14,0x2a2d2e2f,
+0xe18,0x30333333,
+0xe1c,0x2a2d2e2f,
+0xe30,0x01007c00,
+0xe34,0x01004800,
+0xe38,0x1000dc1f,
+0xe3c,0x10008c1f,
+0xe40,0x021400a0,
+0xe44,0x281600a0,
+0xe48,0xf8000001,
+0xe4c,0x00002910,
+0xe50,0x01007c00,
+0xe54,0x01004800,
+0xe58,0x1000dc1f,
+0xe5c,0x10008c1f,
+0xe60,0x021400a0,
+0xe64,0x281600a0,
+0xe6c,0x00002910,
+0xe70,0x31ed92fb,
+0xe74,0x361536fb,
+0xe78,0x361536fb,
+0xe7c,0x361536fb,
+0xe80,0x361536fb,
+0xe84,0x000d92fb,
+0xe88,0x000d92fb,
+0xe8c,0x31ed92fb,
+0xed0,0x31ed92fb,
+0xed4,0x31ed92fb,
+0xed8,0x000d92fb,
+0xedc,0x000d92fb,
+0xee0,0x000d92fb,
+0xee4,0x015e5448,
+0xee8,0x21555448,
+0x900,0x00000000,
+0x904,0x00000023,
+0x908,0x00000000,
+0x90c,0x03321333,
+0xa00,0x00d047c8,
+0xa04,0x80ff0008,
+0xa08,0x8ccd8300,
+0xa0c,0x2e62120f,
+0xa10,0x9500bb78,
+0xa14,0x11144028,
+0xa18,0x00881117,
+0xa1c,0x89140f00,
+0xa20,0x1a1b0000,
+0xa24,0x090e1317,
+0xa28,0x00000204,
+0xa2c,0x10d30000,
+0xc00,0x40071d40,
+0xc04,0x00a05633,
+0xc08,0x000000e4,
+0xc0c,0x6c6c6c6c,
+0xc10,0x08800000,
+0xc14,0x40000100,
+0xc18,0x08000000,
+0xc1c,0x40000100,
+0xc20,0x08000000,
+0xc24,0x40000100,
+0xc28,0x08000000,
+0xc2c,0x40000100,
+0xc30,0x6de9ac44,
+0xc34,0x469652cf,
+0xc38,0x49795994,
+0xc3c,0x0a979764,
+0xc40,0x1f7c403f,
+0xc44,0x000100b7,
+0xc48,0xec020000,
+0xc4c,0x007f037f,
+0xc50,0x69543420,
+0xc54,0x433c0094,
+0xc58,0x69543420,
+0xc5c,0x433c0094,
+0xc60,0x69543420,
+0xc64,0x433c0094,
+0xc68,0x69543420,
+0xc6c,0x433c0094,
+0xc70,0x2c7f000d,
+0xc74,0x0186155b,
+0xc78,0x0000001f,
+0xc7c,0x00b91612,
+0xc80,0x40000100,
+0xc84,0x20f60000,
+0xc88,0x20000080,
+0xc8c,0x20200000,
+0xc90,0x40000100,
+0xc94,0x00000000,
+0xc98,0x40000100,
+0xc9c,0x00000000,
+0xca0,0x00492492,
+0xca4,0x00000000,
+0xca8,0x00000000,
+0xcac,0x00000000,
+0xcb0,0x00000000,
+0xcb4,0x00000000,
+0xcb8,0x00000000,
+0xcbc,0x28000000,
+0xcc0,0x00000000,
+0xcc4,0x00000000,
+0xcc8,0x00000000,
+0xccc,0x00000000,
+0xcd0,0x00000000,
+0xcd4,0x00000000,
+0xcd8,0x64b22427,
+0xcdc,0x00766932,
+0xce0,0x00222222,
+0xce4,0x00000000,
+0xce8,0x37644302,
+0xcec,0x2f97d40c,
+0xd00,0x00000750,
+0xd04,0x00000403,
+0xd08,0x0000907f,
+0xd0c,0x00000001,
+0xd10,0xa0633333,
+0xd14,0x33333c63,
+0xd18,0x6a8f5b6b,
+0xd1c,0x00000000,
+0xd20,0x00000000,
+0xd24,0x00000000,
+0xd28,0x00000000,
+0xd2c,0xcc979975,
+0xd30,0x00000000,
+0xd34,0x00000000,
+0xd38,0x00000000,
+0xd3c,0x00027293,
+0xd40,0x00000000,
+0xd44,0x00000000,
+0xd48,0x00000000,
+0xd50,0x6437140a,
+0xd54,0x024dbd02,
+0xd58,0x00000000,
+0xd5c,0x30032064,
+0xd60,0x4653de68,
+0xd64,0x00518a3c,
+0xd68,0x00002101,
+0xf14,0x00000003,
+0xf4c,0x00000000,
+0xf00,0x00000300,
+};
+
+u32 Rtl8192SUPHY_REG_1T2RArray[PHY_REG_1T2RArrayLength] = {
+0x0, };
+
+u32 Rtl8192SUPHY_ChangeTo_1T1RArray[PHY_ChangeTo_1T1RArrayLength] = {
+0x844,0xffffffff,0x00010000,
+0x804,0x0000000f,0x00000001,
+0x824,0x00f0000f,0x00300004,
+0x82c,0x00f0000f,0x00100002,
+0x870,0x04000000,0x00000001,
+0x864,0x00000400,0x00000000,
+0x878,0x000f000f,0x00000002,
+0xe74,0x0f000000,0x00000002,
+0xe78,0x0f000000,0x00000002,
+0xe7c,0x0f000000,0x00000002,
+0xe80,0x0f000000,0x00000002,
+0x90c,0x000000ff,0x00000011,
+0xc04,0x000000ff,0x00000011,
+0xd04,0x0000000f,0x00000001,
+0x1f4,0xffff0000,0x00007777,
+0x234,0xf8000000,0x0000000a,
+};
+
+u32 Rtl8192SUPHY_ChangeTo_1T2RArray[PHY_ChangeTo_1T2RArrayLength] = {
+0x804,0x0000000f,0x00000003,
+0x824,0x00f0000f,0x00300004,
+0x82c,0x00f0000f,0x00300002,
+0x870,0x04000000,0x00000001,
+0x864,0x00000400,0x00000000,
+0x878,0x000f000f,0x00000002,
+0xe74,0x0f000000,0x00000002,
+0xe78,0x0f000000,0x00000002,
+0xe7c,0x0f000000,0x00000002,
+0xe80,0x0f000000,0x00000002,
+0x90c,0x000000ff,0x00000011,
+0xc04,0x000000ff,0x00000033,
+0xd04,0x0000000f,0x00000003,
+0x1f4,0xffff0000,0x00007777,
+0x234,0xf8000000,0x0000000a,
+};
+
+u32 Rtl8192SUPHY_ChangeTo_2T2RArray[PHY_ChangeTo_2T2RArrayLength] = {
+0x804,0x0000000f,0x00000003,
+0x824,0x00f0000f,0x00300004,
+0x82c,0x00f0000f,0x00300004,
+0x870,0x04000000,0x00000001,
+0x864,0x00000400,0x00000001,
+0x878,0x000f000f,0x00020002,
+0xe74,0x0f000000,0x00000006,
+0xe78,0x0f000000,0x00000006,
+0xe7c,0x0f000000,0x00000006,
+0xe80,0x0f000000,0x00000006,
+0x90c,0x000000ff,0x00000033,
+0xc04,0x000000ff,0x00000033,
+0xd04,0x0000000f,0x00000003,
+0x1f4,0xffff0000,0x0000ffff,
+0x234,0xf8000000,0x00000013,
+};
+
+u32 Rtl8192SUPHY_REG_Array_PG[PHY_REG_Array_PGLength] = {
+0xe00,0xffffffff,0x06090909,
+0xe04,0xffffffff,0x00030406,
+0xe08,0x0000ff00,0x00000000,
+0xe10,0xffffffff,0x0a0c0d0e,
+0xe14,0xffffffff,0x04070809,
+0xe18,0xffffffff,0x0a0c0d0e,
+0xe1c,0xffffffff,0x04070809,
+};
+
+u32 Rtl8192SURadioA_1T_Array[RadioA_1T_ArrayLength] = {
+0x000,0x00030159,
+0x001,0x00030250,
+0x002,0x00010000,
+0x010,0x0008000f,
+0x011,0x000231fc,
+0x010,0x000c000f,
+0x011,0x0003f9f8,
+0x010,0x0002000f,
+0x011,0x00020101,
+0x014,0x0001093e,
+0x014,0x0009093e,
+0x015,0x000198f4,
+0x017,0x000f6500,
+0x01a,0x00013056,
+0x01b,0x00060000,
+0x01c,0x00000300,
+0x01e,0x00031059,
+0x021,0x00054000,
+0x022,0x0000083c,
+0x023,0x00001558,
+0x024,0x00000060,
+0x025,0x00022583,
+0x026,0x0000f200,
+0x027,0x000eacf1,
+0x028,0x0009bd54,
+0x029,0x00004582,
+0x02a,0x00000001,
+0x02b,0x00021334,
+0x02a,0x00000000,
+0x02b,0x0000000a,
+0x02a,0x00000001,
+0x02b,0x00000808,
+0x02b,0x00053333,
+0x02c,0x0000000c,
+0x02a,0x00000002,
+0x02b,0x00000808,
+0x02b,0x0005b333,
+0x02c,0x0000000d,
+0x02a,0x00000003,
+0x02b,0x00000808,
+0x02b,0x00063333,
+0x02c,0x0000000d,
+0x02a,0x00000004,
+0x02b,0x00000808,
+0x02b,0x0006b333,
+0x02c,0x0000000d,
+0x02a,0x00000005,
+0x02b,0x00000709,
+0x02b,0x00053333,
+0x02c,0x0000000d,
+0x02a,0x00000006,
+0x02b,0x00000709,
+0x02b,0x0005b333,
+0x02c,0x0000000d,
+0x02a,0x00000007,
+0x02b,0x00000709,
+0x02b,0x00063333,
+0x02c,0x0000000d,
+0x02a,0x00000008,
+0x02b,0x00000709,
+0x02b,0x0006b333,
+0x02c,0x0000000d,
+0x02a,0x00000009,
+0x02b,0x0000060a,
+0x02b,0x00053333,
+0x02c,0x0000000d,
+0x02a,0x0000000a,
+0x02b,0x0000060a,
+0x02b,0x0005b333,
+0x02c,0x0000000d,
+0x02a,0x0000000b,
+0x02b,0x0000060a,
+0x02b,0x00063333,
+0x02c,0x0000000d,
+0x02a,0x0000000c,
+0x02b,0x0000060a,
+0x02b,0x0006b333,
+0x02c,0x0000000d,
+0x02a,0x0000000d,
+0x02b,0x0000050b,
+0x02b,0x00053333,
+0x02c,0x0000000d,
+0x02a,0x0000000e,
+0x02b,0x0000050b,
+0x02b,0x00066623,
+0x02c,0x0000001a,
+0x02a,0x000e4000,
+0x030,0x00020000,
+0x031,0x000b9631,
+0x032,0x0000130d,
+0x033,0x00000187,
+0x013,0x00019e6c,
+0x013,0x00015e94,
+0x000,0x00010159,
+0x018,0x0000f401,
+0x0fe,0x00000000,
+0x01e,0x0003105b,
+0x0fe,0x00000000,
+0x000,0x00030159,
+0x010,0x0004000f,
+0x011,0x000203f9,
+};
+
+u32 Rtl8192SURadioB_Array[RadioB_ArrayLength] = {
+0x000,0x00030159,
+0x001,0x00001041,
+0x002,0x00011000,
+0x005,0x00080fc0,
+0x007,0x000fc803,
+0x013,0x00017cb0,
+0x013,0x00011cc0,
+0x013,0x0000dc60,
+0x013,0x00008c60,
+0x013,0x00004450,
+0x013,0x00000020,
+};
+
+u32 Rtl8192SURadioA_to1T_Array[RadioA_to1T_ArrayLength] = {
+0x000,0x00000000,
+};
+
+u32 Rtl8192SURadioA_to2T_Array[RadioA_to2T_ArrayLength] = {
+0x000,0x00000000,
+};
+
+u32 Rtl8192SURadioB_GM_Array[RadioB_GM_ArrayLength] = {
+0x000,0x00030159,
+0x001,0x00001041,
+0x002,0x00011000,
+0x005,0x00080fc0,
+0x007,0x000fc803,
+0x013,0x0000bef0,
+0x013,0x00007e90,
+0x013,0x00003e30,
+};
+
+u32 Rtl8192SUMAC_2T_Array[MAC_2T_ArrayLength] = {
+0x020,0x00000035,
+0x048,0x0000000e,
+0x049,0x000000f0,
+0x04a,0x00000077,
+0x04b,0x00000083,
+0x0b5,0x00000021,
+0x0dc,0x000000ff,
+0x0dd,0x000000ff,
+0x0de,0x000000ff,
+0x0df,0x000000ff,
+0x116,0x00000000,
+0x117,0x00000000,
+0x118,0x00000000,
+0x119,0x00000000,
+0x11a,0x00000000,
+0x11b,0x00000000,
+0x11c,0x00000000,
+0x11d,0x00000000,
+0x160,0x0000000b,
+0x161,0x0000000b,
+0x162,0x0000000b,
+0x163,0x0000000b,
+0x164,0x0000000b,
+0x165,0x0000000b,
+0x166,0x0000000b,
+0x167,0x0000000b,
+0x168,0x0000000b,
+0x169,0x0000000b,
+0x16a,0x0000000b,
+0x16b,0x0000000b,
+0x16c,0x0000000b,
+0x16d,0x0000000b,
+0x16e,0x0000000b,
+0x16f,0x0000000b,
+0x170,0x0000000b,
+0x171,0x0000000b,
+0x172,0x0000000b,
+0x173,0x0000000b,
+0x174,0x0000000b,
+0x175,0x0000000b,
+0x176,0x0000000b,
+0x177,0x0000000b,
+0x178,0x0000000b,
+0x179,0x0000000b,
+0x17a,0x0000000b,
+0x17b,0x0000000b,
+0x17c,0x0000000b,
+0x17d,0x0000000b,
+0x17e,0x0000000b,
+0x17f,0x0000000b,
+0x236,0x0000000c,
+0x503,0x00000022,
+0x560,0x00000009,
+};
+
+u32 Rtl8192SUMACPHY_Array_PG[MACPHY_Array_PGLength] = {
+0x0, };
+
+u32 Rtl8192SUAGCTAB_Array[AGCTAB_ArrayLength] = {
+0xc78,0x7f000001,
+0xc78,0x7f010001,
+0xc78,0x7e020001,
+0xc78,0x7d030001,
+0xc78,0x7c040001,
+0xc78,0x7b050001,
+0xc78,0x7a060001,
+0xc78,0x79070001,
+0xc78,0x78080001,
+0xc78,0x77090001,
+0xc78,0x760a0001,
+0xc78,0x750b0001,
+0xc78,0x740c0001,
+0xc78,0x730d0001,
+0xc78,0x720e0001,
+0xc78,0x710f0001,
+0xc78,0x70100001,
+0xc78,0x6f110001,
+0xc78,0x6f120001,
+0xc78,0x6e130001,
+0xc78,0x6d140001,
+0xc78,0x6d150001,
+0xc78,0x6c160001,
+0xc78,0x6b170001,
+0xc78,0x6a180001,
+0xc78,0x6a190001,
+0xc78,0x691a0001,
+0xc78,0x681b0001,
+0xc78,0x671c0001,
+0xc78,0x661d0001,
+0xc78,0x651e0001,
+0xc78,0x641f0001,
+0xc78,0x63200001,
+0xc78,0x4c210001,
+0xc78,0x4b220001,
+0xc78,0x4a230001,
+0xc78,0x49240001,
+0xc78,0x48250001,
+0xc78,0x47260001,
+0xc78,0x46270001,
+0xc78,0x45280001,
+0xc78,0x44290001,
+0xc78,0x2c2a0001,
+0xc78,0x2b2b0001,
+0xc78,0x2a2c0001,
+0xc78,0x292d0001,
+0xc78,0x282e0001,
+0xc78,0x272f0001,
+0xc78,0x26300001,
+0xc78,0x25310001,
+0xc78,0x24320001,
+0xc78,0x23330001,
+0xc78,0x22340001,
+0xc78,0x09350001,
+0xc78,0x08360001,
+0xc78,0x07370001,
+0xc78,0x06380001,
+0xc78,0x05390001,
+0xc78,0x043a0001,
+0xc78,0x033b0001,
+0xc78,0x023c0001,
+0xc78,0x013d0001,
+0xc78,0x003e0001,
+0xc78,0x003f0001,
+0xc78,0x7f400001,
+0xc78,0x7f410001,
+0xc78,0x7e420001,
+0xc78,0x7d430001,
+0xc78,0x7c440001,
+0xc78,0x7b450001,
+0xc78,0x7a460001,
+0xc78,0x79470001,
+0xc78,0x78480001,
+0xc78,0x77490001,
+0xc78,0x764a0001,
+0xc78,0x754b0001,
+0xc78,0x744c0001,
+0xc78,0x734d0001,
+0xc78,0x724e0001,
+0xc78,0x714f0001,
+0xc78,0x70500001,
+0xc78,0x6f510001,
+0xc78,0x6f520001,
+0xc78,0x6e530001,
+0xc78,0x6d540001,
+0xc78,0x6d550001,
+0xc78,0x6c560001,
+0xc78,0x6b570001,
+0xc78,0x6a580001,
+0xc78,0x6a590001,
+0xc78,0x695a0001,
+0xc78,0x685b0001,
+0xc78,0x675c0001,
+0xc78,0x665d0001,
+0xc78,0x655e0001,
+0xc78,0x645f0001,
+0xc78,0x63600001,
+0xc78,0x4c610001,
+0xc78,0x4b620001,
+0xc78,0x4a630001,
+0xc78,0x49640001,
+0xc78,0x48650001,
+0xc78,0x47660001,
+0xc78,0x46670001,
+0xc78,0x45680001,
+0xc78,0x44690001,
+0xc78,0x2c6a0001,
+0xc78,0x2b6b0001,
+0xc78,0x2a6c0001,
+0xc78,0x296d0001,
+0xc78,0x286e0001,
+0xc78,0x276f0001,
+0xc78,0x26700001,
+0xc78,0x25710001,
+0xc78,0x24720001,
+0xc78,0x23730001,
+0xc78,0x22740001,
+0xc78,0x09750001,
+0xc78,0x08760001,
+0xc78,0x07770001,
+0xc78,0x06780001,
+0xc78,0x05790001,
+0xc78,0x047a0001,
+0xc78,0x037b0001,
+0xc78,0x027c0001,
+0xc78,0x017d0001,
+0xc78,0x007e0001,
+0xc78,0x007f0001,
+0xc78,0x3000001e,
+0xc78,0x3001001e,
+0xc78,0x3002001e,
+0xc78,0x3003001e,
+0xc78,0x3004001e,
+0xc78,0x3405001e,
+0xc78,0x3806001e,
+0xc78,0x3e07001e,
+0xc78,0x3e08001e,
+0xc78,0x4409001e,
+0xc78,0x460a001e,
+0xc78,0x480b001e,
+0xc78,0x480c001e,
+0xc78,0x4e0d001e,
+0xc78,0x560e001e,
+0xc78,0x5a0f001e,
+0xc78,0x5e10001e,
+0xc78,0x6211001e,
+0xc78,0x6c12001e,
+0xc78,0x7213001e,
+0xc78,0x7214001e,
+0xc78,0x7215001e,
+0xc78,0x7216001e,
+0xc78,0x7217001e,
+0xc78,0x7218001e,
+0xc78,0x7219001e,
+0xc78,0x721a001e,
+0xc78,0x721b001e,
+0xc78,0x721c001e,
+0xc78,0x721d001e,
+0xc78,0x721e001e,
+0xc78,0x721f001e,
+};
+
diff --git a/drivers/staging/rtl8192su/r8192SU_HWImg.h b/drivers/staging/rtl8192su/r8192SU_HWImg.h
new file mode 100644
index 0000000..96b1525
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192SU_HWImg.h
@@ -0,0 +1,44 @@
+#ifndef __INC_HAL8192SU_FW_IMG_H
+#define __INC_HAL8192SU_FW_IMG_H
+
+#include <linux/types.h>
+
+/*Created on  2009/ 3/ 6,  5:29*/
+
+#define ImgArrayLength 68368
+extern u8 Rtl8192SUFwImgArray[ImgArrayLength];
+#define MainArrayLength 1
+extern u8 Rtl8192SUFwMainArray[MainArrayLength];
+#define DataArrayLength 1
+extern u8 Rtl8192SUFwDataArray[DataArrayLength];
+#define PHY_REG_2T2RArrayLength 372
+extern u32 Rtl8192SUPHY_REG_2T2RArray[PHY_REG_2T2RArrayLength];
+#define PHY_REG_1T2RArrayLength 1
+extern u32 Rtl8192SUPHY_REG_1T2RArray[PHY_REG_1T2RArrayLength];
+#define PHY_ChangeTo_1T1RArrayLength 48
+extern u32 Rtl8192SUPHY_ChangeTo_1T1RArray[PHY_ChangeTo_1T1RArrayLength];
+#define PHY_ChangeTo_1T2RArrayLength 45
+extern u32 Rtl8192SUPHY_ChangeTo_1T2RArray[PHY_ChangeTo_1T2RArrayLength];
+#define PHY_ChangeTo_2T2RArrayLength 45
+extern u32 Rtl8192SUPHY_ChangeTo_2T2RArray[PHY_ChangeTo_2T2RArrayLength];
+#define PHY_REG_Array_PGLength 21
+extern u32 Rtl8192SUPHY_REG_Array_PG[PHY_REG_Array_PGLength];
+#define RadioA_1T_ArrayLength 202
+extern u32 Rtl8192SURadioA_1T_Array[RadioA_1T_ArrayLength];
+#define RadioB_ArrayLength 22
+extern u32 Rtl8192SURadioB_Array[RadioB_ArrayLength];
+#define RadioA_to1T_ArrayLength 2
+extern u32 Rtl8192SURadioA_to1T_Array[RadioA_to1T_ArrayLength];
+#define RadioA_to2T_ArrayLength 2
+extern u32 Rtl8192SURadioA_to2T_Array[RadioA_to2T_ArrayLength];
+#define RadioB_GM_ArrayLength 16
+extern u32 Rtl8192SURadioB_GM_Array[RadioB_GM_ArrayLength];
+#define MAC_2T_ArrayLength 106
+extern u32 Rtl8192SUMAC_2T_Array[MAC_2T_ArrayLength];
+#define MACPHY_Array_PGLength 1
+extern u32 Rtl8192SUMACPHY_Array_PG[MACPHY_Array_PGLength];
+#define AGCTAB_ArrayLength 320
+extern u32 Rtl8192SUAGCTAB_Array[AGCTAB_ArrayLength];
+
+#endif //__INC_HAL8192SU_FW_IMG_H
+
diff --git a/drivers/staging/rtl8192su/r8192S_Efuse.c b/drivers/staging/rtl8192su/r8192S_Efuse.c
new file mode 100644
index 0000000..394ab96
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_Efuse.c
@@ -0,0 +1,2442 @@
+/******************************************************************************
+ *
+ *     (c) Copyright  2008, RealTEK Technologies Inc. All Rights Reserved.
+ *
+ * Module:	Efuse.c	( Source C File)
+ *
+ * Note:		Copy from WMAC for the first version!!!!
+ *
+ *
+ * Function:
+ *
+ * Export:
+ *
+ * Abbrev:
+ *
+ * History:
+ * Data			Who		Remark
+ *
+ * 09/23/2008	MHC		Porting Efuse R/W API from WMAC.
+ * 11/10/2008	MHC		1. Porting from 8712 EFUSE.
+ *						2. Add description and reorganize code arch.
+ * 11/16/2008 	MHC		1. Reorganize code architecture.
+ *						2. Rename for some API and change extern or static type.
+ *
+******************************************************************************/
+#include "r8192U.h"
+#include "r8192S_hw.h"
+#include "r8192S_phy.h"
+#include "r8192S_phyreg.h"
+#include "r8192S_Efuse.h"
+
+#include <linux/types.h>
+
+//typedef  int	INT32;
+//
+// In the future, we will always support EFUSE!!
+//
+#ifdef RTL8192SU
+/*---------------------------Define Local Constant---------------------------*/
+#define 	_POWERON_DELAY_
+#define 	_PRE_EXECUTE_READ_CMD_
+
+#define		EFUSE_REPEAT_THRESHOLD_		3
+#define		EFUSE_ERROE_HANDLE		1
+
+
+// From 8712!!!!!
+typedef struct _EFUSE_MAP_A{
+	u8 offset;		//0~15
+	u8 word_start;	//0~3
+	u8 byte_start;	//0 or 1
+	u8 byte_cnts;
+
+}EFUSE_MAP, *PEFUSE_MAP;
+
+typedef struct PG_PKT_STRUCT_A{
+	u8 offset;
+	u8 word_en;
+	u8 data[8];
+}PGPKT_STRUCT,*PPGPKT_STRUCT;
+
+typedef enum _EFUSE_DATA_ITEM{
+	EFUSE_CHIP_ID=0,
+	EFUSE_LDO_SETTING,
+	EFUSE_CLK_SETTING,
+	EFUSE_SDIO_SETTING,
+	EFUSE_CCCR,
+	EFUSE_SDIO_MODE,
+	EFUSE_OCR,
+	EFUSE_F0CIS,
+	EFUSE_F1CIS,
+	EFUSE_MAC_ADDR,
+	EFUSE_EEPROM_VER,
+	EFUSE_CHAN_PLAN,
+	EFUSE_TXPW_TAB
+} EFUSE_DATA_ITEM;
+
+struct efuse_priv
+{
+	u8		id[2];
+	u8		ldo_setting[2];
+	u8		clk_setting[2];
+	u8		cccr;
+	u8		sdio_mode;
+	u8		ocr[3];
+	u8		cis0[17];
+	u8		cis1[48];
+	u8		mac_addr[6];
+	u8		eeprom_verno;
+	u8		channel_plan;
+	u8		tx_power_b[14];
+	u8		tx_power_g[14];
+};
+
+/*---------------------------Define Local Constant---------------------------*/
+
+
+/*------------------------Define global variable-----------------------------*/
+const u8 MAX_PGPKT_SIZE = 9; //header+ 2* 4 words (BYTES)
+const u8 PGPKT_DATA_SIZE = 8; //BYTES sizeof(u8)*8
+const u32 EFUSE_MAX_SIZE = 512;
+
+
+const EFUSE_MAP RTL8712_SDIO_EFUSE_TABLE[]={
+				//offset	word_s	byte_start	byte_cnts
+/*ID*/			{0		,0		,0			,2	}, // 00~01h
+/*LDO Setting*/	{0		,1		,0			,2	}, // 02~03h
+/*CLK Setting*/	{0		,2		,0			,2	}, // 04~05h
+/*SDIO Setting*/	{1		,0		,0			,1	}, // 08h
+/*CCCR*/		{1		,0		,1			,1	}, // 09h
+/*SDIO MODE*/	{1		,1		,0			,1	}, // 0Ah
+/*OCR*/			{1		,1		,1			,3	}, // 0B~0Dh
+/*CCIS*/			{1		,3		,0			,17	}, // 0E~1Eh  2...1
+/*F1CIS*/		{3		,3		,1			,48	}, // 1F~4Eh  6...0
+/*MAC Addr*/		{10		,0		,0			,6	}, // 50~55h
+/*EEPROM ver*/	{10		,3		,0			,1	}, // 56h
+/*Channel plan*/	{10		,3		,1			,1	}, // 57h
+/*TxPwIndex */	{11		,0		,0			,28	}  // 58~73h  3...4
+};
+
+/*------------------------Define global variable-----------------------------*/
+
+
+/*------------------------Define local variable------------------------------*/
+
+/*------------------------Define local variable------------------------------*/
+
+
+/*--------------------Define function prototype-----------------------*/
+//
+// From WMAC Efuse one byte R/W
+//
+extern	void
+EFUSE_Initialize(struct net_device* dev);
+extern	u8
+EFUSE_Read1Byte(struct net_device* dev, u16 Address);
+extern	void
+EFUSE_Write1Byte(struct net_device* dev, u16 Address,u8 Value);
+
+//
+// Efuse Shadow Area operation
+//
+static	void
+efuse_ShadowRead1Byte(struct net_device* dev,u16 Offset,u8 *Value);
+static	void
+efuse_ShadowRead2Byte(struct net_device* dev,	u16 Offset,u16 *Value	);
+static	void
+efuse_ShadowRead4Byte(struct net_device* dev,	u16 Offset,u32 *Value	);
+static	void
+efuse_ShadowWrite1Byte(struct net_device* dev,	u16 Offset, u8 Value);
+static	void
+efuse_ShadowWrite2Byte(struct net_device* dev,	u16 Offset,u16 Value);
+static	void
+efuse_ShadowWrite4Byte(struct net_device* dev,	u16 Offset,u32 Value);
+
+//
+// Real Efuse operation
+//
+static	u8
+efuse_OneByteRead(struct net_device* dev,u16 addr,u8 *data);
+static	u8
+efuse_OneByteWrite(struct net_device* dev,u16 addr, u8 data);
+
+//
+// HW setting map file operation
+//
+static	void
+efuse_ReadAllMap(struct net_device* dev,u8 *Efuse);
+#ifdef TO_DO_LIST
+static	void
+efuse_WriteAllMap(struct net_device* dev,u8 *eeprom,u32 eeprom_size);
+static	bool
+efuse_ParsingMap(char* szStr,u32* pu4bVal,u32* pu4bMove);
+#endif
+//
+// Reald Efuse R/W or other operation API.
+//
+static	u8
+efuse_PgPacketRead(	struct net_device* dev,u8	offset,u8 *data);
+static	u8
+efuse_PgPacketWrite(struct net_device* dev,u8 offset,u8 word_en,u8	*data);
+static	void
+efuse_WordEnableDataRead(	u8 word_en,u8 *sourdata,u8 *targetdata);
+static	u8
+efuse_WordEnableDataWrite(	struct net_device* dev, u16 efuse_addr, u8 word_en, u8 *data);
+static	void
+efuse_PowerSwitch(struct net_device* dev,u8 PwrState);
+static	u16
+efuse_GetCurrentSize(struct net_device* dev);
+static u8
+efuse_CalculateWordCnts(u8 word_en);
+#if 0
+static	void
+efuse_ResetLoader(struct net_device* dev);
+#endif
+//
+// API for power on power off!!!
+//
+#ifdef TO_DO_LIST
+static void efuse_reg_ctrl(struct net_device* dev, u8 bPowerOn);
+#endif
+/*--------------------Define function prototype-----------------------*/
+
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	EFUSE_Initialize
+ *
+ * Overview:	Copy from WMAC fot EFUSE testing setting init.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 09/23/2008 	MHC		Copy from WMAC.
+ *
+ *---------------------------------------------------------------------------*/
+extern	void
+EFUSE_Initialize(struct net_device* dev)
+{
+	u8	Bytetemp = {0x00};
+	u8	temp = {0x00};
+
+	//Enable Digital Core Vdd : 0x2[13]=1
+	Bytetemp = read_nic_byte(dev, SYS_FUNC_EN+1);
+	temp = Bytetemp | 0x20;
+	write_nic_byte(dev, SYS_FUNC_EN+1, temp);
+
+	//EE loader to retention path1: attach 0x0[8]=0
+	Bytetemp = read_nic_byte(dev, SYS_ISO_CTRL+1);
+	temp = Bytetemp & 0xFE;
+	write_nic_byte(dev, SYS_ISO_CTRL+1, temp);
+
+
+	//Enable E-fuse use 2.5V LDO : 0x37[7]=1
+	Bytetemp = read_nic_byte(dev, EFUSE_TEST+3);
+	temp = Bytetemp | 0x80;
+	write_nic_byte(dev, EFUSE_TEST+3, temp);
+
+	//E-fuse clk switch from 500k to 40M : 0x2F8[1:0]=11b
+	write_nic_byte(dev, 0x2F8, 0x3);
+
+	//Set E-fuse program time & read time : 0x30[30:24]=1110010b
+	write_nic_byte(dev, EFUSE_CTRL+3, 0x72);
+
+}	/* EFUSE_Initialize */
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	EFUSE_Read1Byte
+ *
+ * Overview:	Copy from WMAC fot EFUSE read 1 byte.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 09/23/2008 	MHC		Copy from WMAC.
+ *
+ *---------------------------------------------------------------------------*/
+extern	u8
+EFUSE_Read1Byte(struct net_device* dev, u16	Address)
+{
+	u8	data;
+	u8	Bytetemp = {0x00};
+	u8	temp = {0x00};
+	u32	k=0;
+
+	if (Address < EFUSE_MAC_LEN)	//E-fuse 512Byte
+	{
+		//Write E-fuse Register address bit0~7
+		temp = Address & 0xFF;
+		write_nic_byte(dev, EFUSE_CTRL+1, temp);
+		Bytetemp = read_nic_byte(dev, EFUSE_CTRL+2);
+		//Write E-fuse Register address bit8~9
+		temp = ((Address >> 8) & 0x03) | (Bytetemp & 0xFC);
+		write_nic_byte(dev, EFUSE_CTRL+2, temp);
+
+		//Write 0x30[31]=0
+		Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
+		temp = Bytetemp & 0x7F;
+		write_nic_byte(dev, EFUSE_CTRL+3, temp);
+
+		//Wait Write-ready (0x30[31]=1)
+		Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
+		while(!(Bytetemp & 0x80))
+		{
+			Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
+			k++;
+			if(k==1000)
+			{
+				k=0;
+				break;
+			}
+		}
+		data=read_nic_byte(dev, EFUSE_CTRL);
+		return data;
+	}
+	else
+		return 0xFF;
+
+}	/* EFUSE_Read1Byte */
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	EFUSE_Write1Byte
+ *
+ * Overview:	Copy from WMAC fot EFUSE write 1 byte.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 09/23/2008 	MHC		Copy from WMAC.
+ *
+ *---------------------------------------------------------------------------*/
+extern	void
+EFUSE_Write1Byte(struct net_device* dev, u16 Address,u8 Value)
+{
+	//u8	data;
+	u8	Bytetemp = {0x00};
+	u8	temp = {0x00};
+	u32	k=0;
+
+	//RT_TRACE(COMP_EFUSE, "Addr=%x Data =%x\n", Address, Value);
+
+	if( Address < EFUSE_MAC_LEN)	//E-fuse 512Byte
+	{
+		write_nic_byte(dev, EFUSE_CTRL, Value);
+
+		//Write E-fuse Register address bit0~7
+		temp = Address & 0xFF;
+		write_nic_byte(dev, EFUSE_CTRL+1, temp);
+		Bytetemp = read_nic_byte(dev, EFUSE_CTRL+2);
+
+		//Write E-fuse Register address bit8~9
+		temp = ((Address >> 8) & 0x03) | (Bytetemp & 0xFC);
+		write_nic_byte(dev, EFUSE_CTRL+2, temp);
+
+		//Write 0x30[31]=1
+		Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
+		temp = Bytetemp | 0x80;
+		write_nic_byte(dev, EFUSE_CTRL+3, temp);
+
+		//Wait Write-ready (0x30[31]=0)
+		Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
+		while(Bytetemp & 0x80)
+		{
+			Bytetemp = read_nic_byte(dev, EFUSE_CTRL+3);
+			k++;
+			if(k==100)
+			{
+				k=0;
+				break;
+			}
+		}
+	}
+
+}	/* EFUSE_Write1Byte */
+
+
+#ifdef EFUSE_FOR_92SU
+//
+//	Description:
+//		1. Process CR93C46 Data polling cycle.
+//		2. Refered from SD1 Richard.
+//
+//	Assumption:
+//		1. Boot from E-Fuse and successfully auto-load.
+//		2. PASSIVE_LEVEL (USB interface)
+//
+//	Created by Roger, 2008.10.21.
+//
+void do_93c46(struct net_device* dev,  u8 addorvalue)
+{
+    	//u8  clear[1] = {0x0};      // cs=0 , sk=0 , di=0 , do=0
+	u8  cs[1] = {0x88};        // cs=1 , sk=0 , di=0 , do=0
+	u8  cssk[1] = {0x8c};      // cs=1 , sk=1 , di=0 , do=0
+	u8  csdi[1] = {0x8a};      // cs=1 , sk=0 , di=1 , do=0
+    	u8  csskdi[1] = {0x8e};    // cs=1 , sk=1 , di=1 , do=0
+	//u8  di[1] = {0x82};        // cs=0 , sk=0 , di=1 , do=0
+    	u8  count;
+
+    	for(count=0 ; count<8 ; count++)
+	{
+		if((addorvalue&0x80)!=0)
+		{
+			write_nic_byte(dev, EPROM_CMD, csdi[0]);
+			write_nic_byte(dev, EPROM_CMD, csskdi[0]);
+		}
+		else
+		{
+			write_nic_byte(dev, EPROM_CMD, cs[0]);
+			write_nic_byte(dev, EPROM_CMD, cssk[0]);
+		}
+		addorvalue = addorvalue << 1;
+	}
+}
+
+
+//
+//	Description:
+//		Process CR93C46 Data read polling cycle.
+//		Refered from SD1 Richard.
+//
+//	Assumption:
+//		1. Boot from E-Fuse and successfully auto-load.
+//		2. PASSIVE_LEVEL (USB interface)
+//
+//	Created by Roger, 2008.10.21.
+//
+u16 Read93C46(struct net_device*	dev,	u16	Reg	)
+{
+
+   	u8  	clear[1] = {0x0};      // cs=0 , sk=0 , di=0 , do=0
+	u8  	cs[1] = {0x88};        // cs=1 , sk=0 , di=0 , do=0
+	u8  	cssk[1] = {0x8c};      // cs=1 , sk=1 , di=0 , do=0
+	u8  	csdi[1] = {0x8a};      // cs=1 , sk=0 , di=1 , do=0
+   	u8  	csskdi[1] = {0x8e};    // cs=1 , sk=1 , di=1 , do=0
+	//u8  	di[1] = {0x82};        // cs=0 , sk=0 , di=1 , do=0
+	u8  	EepromSEL[1]={0x00};
+	u8  	address;
+
+	u16   	storedataF[1] = {0x0};   //93c46 data packet for 16bits
+	u8   	t,data[1],storedata[1];
+
+
+	address = (u8)Reg;
+
+	// Suggested by SD1 Alex, 2008.10.20. Revised by Roger.
+	*EepromSEL= read_nic_byte(dev, EPROM_CMD);
+
+	if((*EepromSEL & 0x10) == 0x10) // select 93c46
+	{
+		address = address | 0x80;
+
+		write_nic_byte(dev, EPROM_CMD, csdi[0]);
+		write_nic_byte(dev, EPROM_CMD, csskdi[0]);
+   		do_93c46(dev, address);
+	}
+
+
+	for(t=0 ; t<16 ; t++)      //if read 93c46 , t=16
+	{
+		write_nic_byte(dev, EPROM_CMD, cs[0]);
+		write_nic_byte(dev, EPROM_CMD, cssk[0]);
+		*data= read_nic_byte(dev, EPROM_CMD);
+
+		if(*data & 0x8d) //original code
+		{
+			*data = *data & 0x01;
+			*storedata = *data;
+		}
+		else
+		{
+			*data = *data & 0x01 ;
+			*storedata = *data;
+		}
+		*storedataF = (*storedataF << 1 ) + *storedata;
+	}
+	write_nic_byte(dev, EPROM_CMD, cs[0]);
+	write_nic_byte(dev, EPROM_CMD, clear[0]);
+
+	return *storedataF;
+}
+
+
+//
+//	Description:
+//		Execute E-Fuse read byte operation.
+//		Refered from SD1 Richard.
+//
+//	Assumption:
+//		1. Boot from E-Fuse and successfully auto-load.
+//		2. PASSIVE_LEVEL (USB interface)
+//
+//	Created by Roger, 2008.10.21.
+//
+void
+ReadEFuseByte(struct net_device* dev,u16 _offset, u8 *pbuf)
+{
+
+	//u16 	indexk=0;
+	u32  value32;
+	u8 	readbyte;
+	u16 	retry;
+
+
+	//Write Address
+	write_nic_byte(dev, EFUSE_CTRL+1, (_offset & 0xff));
+	readbyte = read_nic_byte(dev, EFUSE_CTRL+2);
+	write_nic_byte(dev, EFUSE_CTRL+2, ((_offset >> 8) & 0x03) | (readbyte & 0xfc));
+
+	//Write bit 32 0
+	readbyte = read_nic_byte(dev, EFUSE_CTRL+3);
+	write_nic_byte(dev, EFUSE_CTRL+3, (readbyte & 0x7f));
+
+	//Check bit 32 read-ready
+	retry = 0;
+	value32 = read_nic_dword(dev, EFUSE_CTRL);
+	//while(!(((value32 >> 24) & 0xff) & 0x80)  && (retry<10))
+	while(!(((value32 >> 24) & 0xff) & 0x80)  && (retry<10000))
+	{
+		value32 = read_nic_dword(dev, EFUSE_CTRL);
+		retry++;
+	}
+	*pbuf = (u8)(value32 & 0xff);
+}
+
+
+#define		EFUSE_READ_SWITCH		1
+//
+//	Description:
+//		1. Execute E-Fuse read byte operation according as map offset and
+//		    save to E-Fuse table.
+//		2. Refered from SD1 Richard.
+//
+//	Assumption:
+//		1. Boot from E-Fuse and successfully auto-load.
+//		2. PASSIVE_LEVEL (USB interface)
+//
+//	Created by Roger, 2008.10.21.
+//
+void
+ReadEFuse(struct net_device* dev, u16	 _offset, u16 _size_byte, u8 *pbuf)
+{
+
+	u8  	efuseTbl[128];
+	u8  	rtemp8[1];
+	u16 	eFuse_Addr = 0;
+	u8  	offset, wren;
+	u16  	i, j;
+	u16 	eFuseWord[16][4];// = {0xFF};//FIXLZM
+
+	for(i=0; i<16; i++)
+		for(j=0; j<4; j++)
+			eFuseWord[i][j]=0xFF;
+
+	// Do NOT excess total size of EFuse table. Added by Roger, 2008.11.10.
+	if((_offset + _size_byte)>128)
+	{// total E-Fuse table is 128bytes
+		//RT_TRACE(COMP_EFUSE, "ReadEFuse(): Invalid offset(%#x) with read bytes(%#x)!!\n",_offset, _size_byte);
+		printk("ReadEFuse(): Invalid offset with read bytes!!\n");
+		return;
+	}
+
+	// Refresh efuse init map as all oxFF.
+	for (i = 0; i < 128; i++)
+		efuseTbl[i] = 0xFF;
+
+#if (EFUSE_READ_SWITCH == 1)
+	ReadEFuseByte(dev, eFuse_Addr, rtemp8);
+#else
+	rtemp8[0] = EFUSE_Read1Byte(dev, eFuse_Addr);
+#endif
+	if(*rtemp8 != 0xFF)		eFuse_Addr++;
+	while((*rtemp8 != 0xFF) && (eFuse_Addr < 512)){
+		offset = ((*rtemp8 >> 4) & 0x0f);
+		if(offset <= 0x0F){
+			wren = (*rtemp8 & 0x0f);
+			for(i=0; i<4; i++){
+				if(!(wren & 0x01)){
+#if (EFUSE_READ_SWITCH == 1)
+					ReadEFuseByte(dev, eFuse_Addr, rtemp8);	eFuse_Addr++;
+#else
+					rtemp8[0] = EFUSE_Read1Byte(dev, eFuse_Addr);	eFuse_Addr++;
+#endif
+					eFuseWord[offset][i] = (*rtemp8 & 0xff);
+					if(eFuse_Addr >= 512) break;
+#if (EFUSE_READ_SWITCH == 1)
+					ReadEFuseByte(dev, eFuse_Addr, rtemp8);	eFuse_Addr++;
+#else
+					rtemp8[0] = EFUSE_Read1Byte(dev, eFuse_Addr);	eFuse_Addr++;
+#endif
+					eFuseWord[offset][i] |= (((u16)*rtemp8 << 8) & 0xff00);
+					if(eFuse_Addr >= 512) break;
+				}
+				wren >>= 1;
+			}
+		}
+#if (EFUSE_READ_SWITCH == 1)
+		ReadEFuseByte(dev, eFuse_Addr, rtemp8);
+#else
+		rtemp8[0] = EFUSE_Read1Byte(dev, eFuse_Addr);	eFuse_Addr++;
+#endif
+		if(*rtemp8 != 0xFF && (eFuse_Addr < 512))	eFuse_Addr++;
+	}
+
+	for(i=0; i<16; i++){
+		for(j=0; j<4; j++){
+			efuseTbl[(i*8)+(j*2)]=(eFuseWord[i][j] & 0xff);
+			efuseTbl[(i*8)+((j*2)+1)]=((eFuseWord[i][j] >> 8) & 0xff);
+		}
+	}
+	for(i=0; i<_size_byte; i++)
+		pbuf[i] = efuseTbl[_offset+i];
+}
+#endif	// #if (EFUSE_FOR_92SU == 1)
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	EFUSE_ShadowRead
+ *
+ * Overview:	Read from efuse init map !!!!!
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/12/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+extern void
+EFUSE_ShadowRead(	struct net_device*	dev,	u8 Type, u16 Offset, u32 *Value)
+{
+	//HAL_DATA_TYPE	*pHalData = GET_HAL_DATA(pAdapter);
+
+	if (Type == 1)
+		efuse_ShadowRead1Byte(dev, Offset, (u8 *)Value);
+	else if (Type == 2)
+		efuse_ShadowRead2Byte(dev, Offset, (u16 *)Value);
+	else if (Type == 4)
+		efuse_ShadowRead4Byte(dev, Offset, (u32 *)Value);
+
+}	// EFUSE_ShadowRead
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	EFUSE_ShadowWrite
+ *
+ * Overview:	Write efuse modify map for later update operation to use!!!!!
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/12/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+extern	void
+EFUSE_ShadowWrite(	struct net_device*	dev,	u8 Type, u16 Offset,u32	Value)
+{
+	//HAL_DATA_TYPE	*pHalData = GET_HAL_DATA(pAdapter);
+
+	if (Offset >= 0x18 && Offset <= 0x1F)
+		return;
+
+	if (Type == 1)
+		efuse_ShadowWrite1Byte(dev, Offset, (u8)Value);
+	else if (Type == 2)
+		efuse_ShadowWrite2Byte(dev, Offset, (u16)Value);
+	else if (Type == 4)
+		efuse_ShadowWrite4Byte(dev, Offset, (u32)Value);
+
+}	// EFUSE_ShadowWrite
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	EFUSE_ShadowUpdate
+ *
+ * Overview:	Compare init and modify map to update Efuse!!!!!
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/12/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+extern	void
+EFUSE_ShadowUpdate(struct net_device* dev)
+{
+	//HAL_DATA_TYPE	*pHalData = GET_HAL_DATA(pAdapter);
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u16			i, offset, base = 0;
+	u8			word_en = 0x0F;
+	bool first_pg = false;
+	// For Efuse write action, we must enable LDO2.5V and 40MHZ clk.
+	efuse_PowerSwitch(dev, TRUE);
+
+	//
+	// Efuse support 16 write are with PG header packet!!!!
+	//
+	for (offset = 0; offset < 16; offset++)
+	{
+		// Offset 0x18-1F are reserved now!!!
+#ifdef RTL8192SE
+		if(priv->card_8192 == NIC_8192SE){
+			if (offset == 3)
+				continue;
+		}
+#endif
+		word_en = 0x0F;
+		base = offset * 8;
+
+		//
+		// Decide Word Enable Bit for the Efuse section
+		// One section contain 4 words = 8 bytes!!!!!
+		//
+		for (i = 0; i < 8; i++)
+		{
+			if (offset == 0 && priv->EfuseMap[EFUSE_INIT_MAP][base+i] == 0xFF)
+			{
+				first_pg = TRUE;
+			}
+
+			// 2008/12/11 MH HW autoload fail workaround for A/BCUT.
+#ifdef RTL8192SE
+			if (first_pg == TRUE && offset == 1 && (priv->card_8192 == NIC_8192SE))
+			{
+				continue;
+			}
+#endif
+
+			if (first_pg == TRUE)
+			{
+				word_en &= ~(1<<(i/2));
+				priv->EfuseMap[EFUSE_INIT_MAP][base+i] =
+				priv->EfuseMap[EFUSE_MODIFY_MAP][base+i];
+			}else
+			{
+			if (	priv->EfuseMap[EFUSE_INIT_MAP][base+i] !=
+				priv->EfuseMap[EFUSE_MODIFY_MAP][base+i])
+			{
+				word_en &= ~(EFUSE_BIT(i/2));
+				//RT_TRACE(COMP_EFUSE,  "Offset=%d Addr%x %x ==> %x Word_En=%02x\n",
+				//offset, base+i, priv->EfuseMap[0][base+i], priv->EfuseMap[1][base+i],word_en);
+
+				// Update init table!!!
+				priv->EfuseMap[EFUSE_INIT_MAP][base+i] =
+				priv->EfuseMap[EFUSE_MODIFY_MAP][base+i];
+				}
+			}
+		}
+
+		//
+		// Call Efuse real write section !!!!
+		//
+		if (word_en != 0x0F)
+		{
+			u8	tmpdata[8];
+
+			//FIXLZM
+			memcpy(tmpdata, &(priv->EfuseMap[EFUSE_MODIFY_MAP][base]), 8);
+			//RT_PRINT_DATA(COMP_INIT, DBG_LOUD, ("U-EFUSE\n"), tmpdata, 8);
+			efuse_PgPacketWrite(dev,(u8)offset,word_en,tmpdata);
+		}
+
+	}
+	// 2008/12/01 MH For Efuse HW load bug workarounf method!!!!
+	// We will force write 0x10EC into address 10&11 after all Efuse content.
+	//
+#ifdef RTL8192SE
+	if (first_pg == TRUE && (priv->card_8192 == NIC_8192SE))
+	{
+		// 2008/12/11 MH Use new method to prevent HW autoload fail.
+		u8	tmpdata[8];
+
+		memcpy(tmpdata, (&priv->EfuseMap[EFUSE_MODIFY_MAP][8]), 8);
+		efuse_PgPacketWrite(dev, 1, 0x0, tmpdata);
+#if 0
+		u1Byte	tmpdata[8] = {0xFF, 0xFF, 0xEC, 0x10, 0xFF, 0xFF, 0xFF, 0xFF};
+
+		efuse_PgPacketWrite(pAdapter, 1, 0xD, tmpdata);
+#endif
+	}
+#endif
+
+
+	// For warm reboot, we must resume Efuse clock to 500K.
+	efuse_PowerSwitch(dev, FALSE);
+	// 2008/12/01 MH We update shadow content again!!!!
+	EFUSE_ShadowMapUpdate(dev);
+
+}	// EFUSE_ShadowUpdate
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	EFUSE_ShadowMapUpdate
+ *
+ * Overview:	Transfer current EFUSE content to shadow init and modify map.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/13/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+extern void EFUSE_ShadowMapUpdate(struct net_device* dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	if (priv->AutoloadFailFlag == true){
+		memset(&(priv->EfuseMap[EFUSE_INIT_MAP][0]), 0xff, 128);
+	}else{
+		efuse_ReadAllMap(dev, &priv->EfuseMap[EFUSE_INIT_MAP][0]);
+	}
+	//PlatformMoveMemory(&priv->EfuseMap[EFUSE_MODIFY_MAP][0],
+		//&priv->EfuseMap[EFUSE_INIT_MAP][0], HWSET_MAX_SIZE_92S);//FIXLZM
+	memcpy(&priv->EfuseMap[EFUSE_MODIFY_MAP][0],
+		&priv->EfuseMap[EFUSE_INIT_MAP][0], HWSET_MAX_SIZE_92S);
+
+}	// EFUSE_ShadowMapUpdate
+
+extern	void
+EFUSE_ForceWriteVendorId( struct net_device* dev)
+{
+	u8 tmpdata[8] = {0xFF, 0xFF, 0xEC, 0x10, 0xFF, 0xFF, 0xFF, 0xFF};
+
+	efuse_PowerSwitch(dev, TRUE);
+
+	efuse_PgPacketWrite(dev, 1, 0xD, tmpdata);
+
+	efuse_PowerSwitch(dev, FALSE);
+
+}	// EFUSE_ForceWriteVendorId
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_ShadowRead1Byte
+ *			efuse_ShadowRead2Byte
+ *			efuse_ShadowRead4Byte
+ *
+ * Overview:	Read from efuse init map by one/two/four bytes !!!!!
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/12/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+efuse_ShadowRead1Byte(struct net_device*	dev,	u16 Offset,	u8 *Value)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	*Value = priv->EfuseMap[EFUSE_MODIFY_MAP][Offset];
+
+}	// EFUSE_ShadowRead1Byte
+
+//---------------Read Two Bytes
+static	void
+efuse_ShadowRead2Byte(struct net_device*	dev,	u16 Offset,	u16 *Value)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	*Value = priv->EfuseMap[EFUSE_MODIFY_MAP][Offset];
+	*Value |= priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+1]<<8;
+
+}	// EFUSE_ShadowRead2Byte
+
+//---------------Read Four Bytes
+static	void
+efuse_ShadowRead4Byte(struct net_device*	dev,	u16 Offset,	u32 *Value)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	*Value = priv->EfuseMap[EFUSE_MODIFY_MAP][Offset];
+	*Value |= priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+1]<<8;
+	*Value |= priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+2]<<16;
+	*Value |= priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+3]<<24;
+
+}	// efuse_ShadowRead4Byte
+
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_ShadowWrite1Byte
+ *			efuse_ShadowWrite2Byte
+ *			efuse_ShadowWrite4Byte
+ *
+ * Overview:	Write efuse modify map by one/two/four byte.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/12/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+efuse_ShadowWrite1Byte(struct net_device*	dev,	u16 Offset,	u8 Value)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	priv->EfuseMap[EFUSE_MODIFY_MAP][Offset] = Value;
+
+}	// efuse_ShadowWrite1Byte
+
+//---------------Write Two Bytes
+static	void
+efuse_ShadowWrite2Byte(struct net_device*	dev,	u16 Offset,	u16 Value)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	priv->EfuseMap[EFUSE_MODIFY_MAP][Offset] = Value&0x00FF;
+	priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+1] = Value>>8;
+
+}	// efuse_ShadowWrite1Byte
+
+//---------------Write Four Bytes
+static	void
+efuse_ShadowWrite4Byte(struct net_device*	dev,	u16 Offset,	u32 Value)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	priv->EfuseMap[EFUSE_MODIFY_MAP][Offset] = (u8)(Value&0x000000FF);
+	priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+1] = (u8)((Value>>8)&0x0000FF);
+	priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+2] = (u8)((Value>>16)&0x00FF);
+	priv->EfuseMap[EFUSE_MODIFY_MAP][Offset+3] = (u8)((Value>>24)&0xFF);
+
+}	// efuse_ShadowWrite1Byte
+
+
+/*  11/16/2008 MH Read one byte from real Efuse. */
+static	u8
+efuse_OneByteRead(struct net_device* dev, u16 addr,u8 *data)
+{
+	u8 tmpidx = 0;
+	u8 bResult;
+
+	// -----------------e-fuse reg ctrl ---------------------------------
+	//address
+	write_nic_byte(dev, EFUSE_CTRL+1, (u8)(addr&0xff));
+	write_nic_byte(dev, EFUSE_CTRL+2, ((u8)((addr>>8) &0x03) ) |
+	(read_nic_byte(dev, EFUSE_CTRL+2)&0xFC ));
+
+	write_nic_byte(dev, EFUSE_CTRL+3,  0x72);//read cmd
+
+	while(!(0x80 &read_nic_byte(dev, EFUSE_CTRL+3))&&(tmpidx<100))
+	{
+		tmpidx++;
+	}
+	if(tmpidx<100)
+	{
+		*data=read_nic_byte(dev, EFUSE_CTRL);
+		bResult = TRUE;
+	}
+	else
+	{
+		*data = 0xff;
+		bResult = FALSE;
+	}
+	return bResult;
+}	// efuse_OneByteRead
+
+/*  11/16/2008 MH Write one byte to reald Efuse. */
+static	u8
+efuse_OneByteWrite(struct net_device* dev,  u16 addr, u8 data)
+{
+	u8 tmpidx = 0;
+	u8 bResult;
+
+	//RT_TRACE(COMP_EFUSE, "Addr = %x Data=%x\n", addr, data);
+
+	//return	0;
+
+	// -----------------e-fuse reg ctrl ---------------------------------
+	//address
+	write_nic_byte(dev, EFUSE_CTRL+1, (u8)(addr&0xff));
+	write_nic_byte(dev, EFUSE_CTRL+2,
+	read_nic_byte(dev, EFUSE_CTRL+2)|(u8)((addr>>8)&0x03) );
+
+	write_nic_byte(dev, EFUSE_CTRL, data);//data
+	write_nic_byte(dev, EFUSE_CTRL+3, 0xF2);//write cmd
+
+	while((0x80 &  read_nic_byte(dev, EFUSE_CTRL+3)) && (tmpidx<100) ){
+		tmpidx++;
+	}
+
+	if(tmpidx<100)
+	{
+		bResult = TRUE;
+	}
+	else
+	{
+		bResult = FALSE;
+	}
+
+	return bResult;
+}	// efuse_OneByteWrite
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_ReadAllMap
+ *
+ * Overview:	Read All Efuse content
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/11/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+efuse_ReadAllMap(struct net_device*	dev, u8	*Efuse)
+{
+	//u8 	pg_data[8];
+	//u8 	offset = 0;
+	//u8 	tmpidx;
+	//static	u8	index = 0;
+
+	//
+	// We must enable clock and LDO 2.5V otherwise, read all map will be fail!!!!
+	//
+	efuse_PowerSwitch(dev, TRUE);
+	ReadEFuse(dev, 0, 128, Efuse);
+	efuse_PowerSwitch(dev, FALSE);
+#if 0
+	// ==> Prevent efuse read error!!!
+	RT_TRACE(COMP_INIT, "efuse_ResetLoader\n");
+	efuse_ResetLoader(dev);
+
+	// Change Efuse Clock for write action to 40MHZ
+	write_nic_byte(dev, EFUSE_CLK, 0x03);
+
+	ReadEFuse(dev, 0, 128, Efuse);
+
+	// Change Efuse Clock for write action to 500K
+	write_nic_byte(dev, EFUSE_CLK, 0x02);
+#if 0	// Error !!!!!!
+	for(offset = 0;offset<16;offset++)	// For 8192SE
+	{
+		PlatformFillMemory((PVOID)pg_data, 8, 0xff);
+		efuse_PgPacketRead(pAdapter,offset,pg_data);
+
+		PlatformMoveMemory((PVOID)&Efuse[offset*8], (PVOID)pg_data, 8);
+	}
+#endif
+
+	//
+	// Error Check and Reset Again!!!!
+	//
+	if (Efuse[0] != 0x29 || Efuse[1] != 0x81)
+	{
+		// SW autoload fail, we have to read again!!!
+		if (index ++ < 5)
+		{
+			RT_TRACE(COMP_INIT, "EFUSE R FAIL %d\n", index);
+			efuse_ReadAllMap(dev, Efuse);
+			// Wait a few time ???? Or need to do some setting ???
+			// When we reload driver, efuse will be OK!!
+		}
+	}
+	else
+	{
+		index = 0;
+	}
+
+	//efuse_PowerSwitch(pAdapter, FALSE);
+#endif
+}	// efuse_ReadAllMap
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_WriteAllMap
+ *
+ * Overview:	Write All Efuse content
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/11/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+#ifdef TO_DO_LIST
+static	void
+efuse_WriteAllMap(struct net_device* dev,u8 *eeprom, u32 eeprom_size)
+{
+	unsigned char word_en = 0x00;
+
+	unsigned char tmpdata[8];
+	unsigned char offset;
+
+	// For Efuse write action, we must enable LDO2.5V and 40MHZ clk.
+	efuse_PowerSwitch(dev, TRUE);
+
+	//sdio contents
+	for(offset=0 ; offset< eeprom_size/PGPKT_DATA_SIZE ; offset++)
+	{
+		// 92S will only reserv 0x18-1F 8 bytes now. The 3rd efuse write area!
+		if (IS_HARDWARE_TYPE_8192SE(dev))
+		{
+			// Refer to
+			// 0x18-1f Reserve >0x50 Reserve for tx power
+			if (offset == 3/* || offset > 9*/)
+				continue;//word_en = 0x0F;
+			//else if (offset == 9)	// 0x4c-4f Reserve
+				//word_en = 0x0C;
+			else
+				word_en = 0x00;
+		}
+		//RT_TRACE(COMP_EFUSE, ("Addr=%d size=%d Word_En=%02x\n", offset, eeprom_size, word_en));
+
+		//memcpy(tmpdata,eeprom+(offset*PGPKT_DATA_SIZE),8);
+		memcpy(tmpdata, (eeprom+(offset*PGPKT_DATA_SIZE)), 8);
+
+		//RT_PRINT_DATA(COMP_INIT, DBG_LOUD, ("EFUSE\t"), tmpdata, 8);
+
+		efuse_PgPacketWrite(dev,offset,word_en,tmpdata);
+
+
+	}
+
+	// For warm reboot, we must resume Efuse clock to 500K.
+	efuse_PowerSwitch(dev, FALSE);
+
+}	// efuse_WriteAllMap
+#endif
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_PgPacketRead
+ *
+ * Overview:	Receive dedicated Efuse are content. For92s, we support 16
+ *				area now. It will return 8 bytes content for every area.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/16/2008 	MHC		Reorganize code Arch and assign as local API.
+ *
+ *---------------------------------------------------------------------------*/
+static	u8
+efuse_PgPacketRead(	struct net_device*	dev,	u8 offset, u8	*data)
+{
+	u8 ReadState = PG_STATE_HEADER;
+
+	bool bContinual = TRUE;
+	bool  bDataEmpty = TRUE ;
+
+	u8 efuse_data,word_cnts=0;
+	u16 efuse_addr = 0;
+	u8 hoffset=0,hworden=0;
+	u8 tmpidx=0;
+	u8 tmpdata[8];
+
+	if(data==NULL)	return FALSE;
+	if(offset>15)		return FALSE;
+
+	//FIXLZM
+	//PlatformFillMemory((PVOID)data, sizeof(u8)*PGPKT_DATA_SIZE, 0xff);
+	//PlatformFillMemory((PVOID)tmpdata, sizeof(u8)*PGPKT_DATA_SIZE, 0xff);
+	memset(data, 0xff, sizeof(u8)*PGPKT_DATA_SIZE);
+	memset(tmpdata, 0xff, sizeof(u8)*PGPKT_DATA_SIZE);
+
+	//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("efuse_PgPacketRead-1\n"), data, 8);
+
+	//efuse_reg_ctrl(pAdapter,TRUE);//power on
+	while(bContinual && (efuse_addr  < EFUSE_MAX_SIZE) )
+	{
+		//-------  Header Read -------------
+		if(ReadState & PG_STATE_HEADER)
+		{
+			if(efuse_OneByteRead(dev, efuse_addr ,&efuse_data)&&(efuse_data!=0xFF)){
+				hoffset = (efuse_data>>4) & 0x0F;
+				hworden =  efuse_data & 0x0F;
+				word_cnts = efuse_CalculateWordCnts(hworden);
+				bDataEmpty = TRUE ;
+
+				if(hoffset==offset){
+					for(tmpidx = 0;tmpidx< word_cnts*2 ;tmpidx++){
+						if(efuse_OneByteRead(dev, efuse_addr+1+tmpidx ,&efuse_data) ){
+							tmpdata[tmpidx] = efuse_data;
+							if(efuse_data!=0xff){
+								bDataEmpty = FALSE;
+							}
+						}
+					}
+					if(bDataEmpty==FALSE){
+						ReadState = PG_STATE_DATA;
+					}else{//read next header
+						efuse_addr = efuse_addr + (word_cnts*2)+1;
+						ReadState = PG_STATE_HEADER;
+					}
+				}
+				else{//read next header
+					efuse_addr = efuse_addr + (word_cnts*2)+1;
+					ReadState = PG_STATE_HEADER;
+				}
+
+			}
+			else{
+				bContinual = FALSE ;
+			}
+		}
+		//-------  Data section Read -------------
+		else if(ReadState & PG_STATE_DATA)
+		{
+			efuse_WordEnableDataRead(hworden,tmpdata,data);
+			efuse_addr = efuse_addr + (word_cnts*2)+1;
+			ReadState = PG_STATE_HEADER;
+		}
+
+	}
+	//efuse_reg_ctrl(pAdapter,FALSE);//power off
+
+	//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("efuse_PgPacketRead-2\n"), data, 8);
+
+	if(	(data[0]==0xff) &&(data[1]==0xff) && (data[2]==0xff)  && (data[3]==0xff) &&
+		(data[4]==0xff) &&(data[5]==0xff) && (data[6]==0xff)  && (data[7]==0xff))
+		return FALSE;
+	else
+		return TRUE;
+
+}	// efuse_PgPacketRead
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_PgPacketWrite
+ *
+ * Overview:	Send A G package for different section in real efuse area.
+ *				For 92S, One PG package contain 8 bytes content and 4 word
+ *				unit. PG header = 0x[bit7-4=offset][bit3-0word enable]
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/16/2008 	MHC		Reorganize code Arch and assign as local API.
+ *
+ *---------------------------------------------------------------------------*/
+static u8 efuse_PgPacketWrite(struct net_device* dev, u8 offset, u8 word_en,u8 *data)
+{
+	u8 WriteState = PG_STATE_HEADER;
+
+	bool bContinual = TRUE,bDataEmpty=TRUE, bResult = TRUE;
+	u16 efuse_addr = 0;
+	u8 efuse_data;
+
+	u8 pg_header = 0;
+
+	//u16 tmp_addr=0;
+	u8 tmp_word_cnts=0,target_word_cnts=0;
+	u8 tmp_header,match_word_en,tmp_word_en;
+
+	//u8	efuse_clk_ori,efuse_clk_new;
+
+	PGPKT_STRUCT target_pkt;
+	PGPKT_STRUCT tmp_pkt;
+
+	u8 originaldata[sizeof(u8)*8];
+	u8 tmpindex = 0,badworden = 0x0F;
+
+	static u32 repeat_times = 0;
+
+	if( efuse_GetCurrentSize(dev) >= EFUSE_MAX_SIZE)
+	{
+		printk("efuse_PgPacketWrite error \n");
+		return FALSE;
+	}
+
+	// Init the 8 bytes content as 0xff
+	target_pkt.offset = offset;
+	target_pkt.word_en= word_en;
+
+	//PlatformFillMemory((PVOID)target_pkt.data, sizeof(u8)*8, 0xFF);
+	memset(target_pkt.data,0xFF,sizeof(u8)*8);
+
+	efuse_WordEnableDataRead(word_en,data,target_pkt.data);
+	target_word_cnts = efuse_CalculateWordCnts(target_pkt.word_en);
+
+	//efuse_reg_ctrl(pAdapter,TRUE);//power on
+	printk("EFUSE Power ON\n");
+
+	while( bContinual && (efuse_addr  < EFUSE_MAX_SIZE) )
+	{
+
+		if(WriteState==PG_STATE_HEADER)
+		{
+			bDataEmpty=TRUE;
+			badworden = 0x0F;
+			//************  so *******************
+			printk("EFUSE PG_STATE_HEADER\n");
+			if (	efuse_OneByteRead(dev, efuse_addr ,&efuse_data) &&
+				(efuse_data!=0xFF))
+			{
+				tmp_header  =  efuse_data;
+
+				tmp_pkt.offset 	= (tmp_header>>4) & 0x0F;
+				tmp_pkt.word_en 	= tmp_header & 0x0F;
+				tmp_word_cnts =  efuse_CalculateWordCnts(tmp_pkt.word_en);
+
+				//************  so-1 *******************
+				if(tmp_pkt.offset  != target_pkt.offset)
+				{
+					efuse_addr = efuse_addr + (tmp_word_cnts*2) +1; //Next pg_packet
+					#if (EFUSE_ERROE_HANDLE == 1)
+					WriteState = PG_STATE_HEADER;
+					#endif
+				}
+				else
+				{
+					//************  so-2 *******************
+					for(tmpindex=0 ; tmpindex<(tmp_word_cnts*2) ; tmpindex++)
+					{
+						if(efuse_OneByteRead(dev, (efuse_addr+1+tmpindex) ,&efuse_data)&&(efuse_data != 0xFF)){
+							bDataEmpty = FALSE;
+						}
+					}
+					//************  so-2-1 *******************
+					if(bDataEmpty == FALSE)
+					{
+						efuse_addr = efuse_addr + (tmp_word_cnts*2) +1; //Next pg_packet
+						#if (EFUSE_ERROE_HANDLE == 1)
+						WriteState=PG_STATE_HEADER;
+						#endif
+					}
+					else
+					{//************  so-2-2 *******************
+						match_word_en = 0x0F;
+						if(   !( (target_pkt.word_en&BIT0)|(tmp_pkt.word_en&BIT0)  ))
+						{
+							 match_word_en &= (~BIT0);
+						}
+						if(   !( (target_pkt.word_en&BIT1)|(tmp_pkt.word_en&BIT1)  ))
+						{
+							 match_word_en &= (~BIT1);
+						}
+						if(   !( (target_pkt.word_en&BIT2)|(tmp_pkt.word_en&BIT2)  ))
+						{
+							 match_word_en &= (~BIT2);
+						}
+						if(   !( (target_pkt.word_en&BIT3)|(tmp_pkt.word_en&BIT3)  ))
+						{
+							 match_word_en &= (~BIT3);
+						}
+
+						//************  so-2-2-A *******************
+						if((match_word_en&0x0F)!=0x0F)
+						{
+							badworden = efuse_WordEnableDataWrite(dev,efuse_addr+1, tmp_pkt.word_en ,target_pkt.data);
+
+							//************  so-2-2-A-1 *******************
+							//############################
+							if(0x0F != (badworden&0x0F))
+							{
+								u8 reorg_offset = offset;
+								u8 reorg_worden=badworden;
+								efuse_PgPacketWrite(dev,reorg_offset,reorg_worden,originaldata);
+							}
+							//############################
+
+							tmp_word_en = 0x0F;
+							if(  (target_pkt.word_en&BIT0)^(match_word_en&BIT0)  )
+							{
+								tmp_word_en &= (~BIT0);
+							}
+							if(   (target_pkt.word_en&BIT1)^(match_word_en&BIT1) )
+							{
+								tmp_word_en &=  (~BIT1);
+							}
+							if(   (target_pkt.word_en&BIT2)^(match_word_en&BIT2) )
+							{
+								tmp_word_en &= (~BIT2);
+							}
+							if(   (target_pkt.word_en&BIT3)^(match_word_en&BIT3) )
+							{
+								tmp_word_en &=(~BIT3);
+							}
+
+							//************  so-2-2-A-2 *******************
+							if((tmp_word_en&0x0F)!=0x0F){
+								//reorganize other pg packet
+								//efuse_addr = efuse_addr + (2*tmp_word_cnts) +1;//next pg packet addr
+								efuse_addr = efuse_GetCurrentSize(dev);
+								//===========================
+								target_pkt.offset = offset;
+								target_pkt.word_en= tmp_word_en;
+								//===========================
+							}else{
+								bContinual = FALSE;
+							}
+							#if (EFUSE_ERROE_HANDLE == 1)
+							WriteState=PG_STATE_HEADER;
+							repeat_times++;
+							if(repeat_times>EFUSE_REPEAT_THRESHOLD_){
+								bContinual = FALSE;
+								bResult = FALSE;
+							}
+							#endif
+						}
+						else{//************  so-2-2-B *******************
+							//reorganize other pg packet
+							efuse_addr = efuse_addr + (2*tmp_word_cnts) +1;//next pg packet addr
+							//===========================
+							target_pkt.offset = offset;
+							target_pkt.word_en= target_pkt.word_en;
+							//===========================
+							#if (EFUSE_ERROE_HANDLE == 1)
+							WriteState=PG_STATE_HEADER;
+							#endif
+						}
+					}
+				}
+				printk("EFUSE PG_STATE_HEADER-1\n");
+			}
+			else		//************  s1: header == oxff  *******************
+			{
+				pg_header = ((target_pkt.offset << 4)&0xf0) |target_pkt.word_en;
+
+				efuse_OneByteWrite(dev,efuse_addr, pg_header);
+				efuse_OneByteRead(dev,efuse_addr, &tmp_header);
+
+				if(tmp_header == pg_header)
+				{ //************  s1-1*******************
+					WriteState = PG_STATE_DATA;
+				}
+				#if (EFUSE_ERROE_HANDLE == 1)
+				else if(tmp_header == 0xFF){//************  s1-3: if Write or read func doesn't work *******************
+					//efuse_addr doesn't change
+					WriteState = PG_STATE_HEADER;
+					repeat_times++;
+					if(repeat_times>EFUSE_REPEAT_THRESHOLD_){
+						bContinual = FALSE;
+						bResult = FALSE;
+					}
+				}
+				#endif
+				else
+				{//************  s1-2 : fixed the header procedure *******************
+					tmp_pkt.offset = (tmp_header>>4) & 0x0F;
+					tmp_pkt.word_en=  tmp_header & 0x0F;
+					tmp_word_cnts =  efuse_CalculateWordCnts(tmp_pkt.word_en);
+
+					//************  s1-2-A :cover the exist data *******************
+					memset(originaldata,0xff,sizeof(u8)*8);
+					//PlatformFillMemory((PVOID)originaldata, sizeof(u8)*8, 0xff);
+
+					if(efuse_PgPacketRead( dev, tmp_pkt.offset,originaldata))
+					{	//check if data exist
+						//efuse_reg_ctrl(pAdapter,TRUE);//power on
+						badworden = efuse_WordEnableDataWrite(dev,efuse_addr+1,tmp_pkt.word_en,originaldata);
+						//############################
+						if(0x0F != (badworden&0x0F))
+						{
+							u8 reorg_offset = tmp_pkt.offset;
+							u8 reorg_worden=badworden;
+							efuse_PgPacketWrite(dev,reorg_offset,reorg_worden,originaldata);
+							efuse_addr = efuse_GetCurrentSize(dev);
+						}
+						//############################
+						else{
+							efuse_addr = efuse_addr + (tmp_word_cnts*2) +1; //Next pg_packet
+						}
+					}
+					 //************  s1-2-B: wrong address*******************
+					else
+					{
+						efuse_addr = efuse_addr + (tmp_word_cnts*2) +1; //Next pg_packet
+					}
+
+					#if (EFUSE_ERROE_HANDLE == 1)
+					WriteState=PG_STATE_HEADER;
+					repeat_times++;
+					if(repeat_times>EFUSE_REPEAT_THRESHOLD_){
+						bContinual = FALSE;
+						bResult = FALSE;
+					}
+					#endif
+
+					printk("EFUSE PG_STATE_HEADER-2\n");
+				}
+
+			}
+
+		}
+		//write data state
+		else if(WriteState==PG_STATE_DATA)
+		{	//************  s1-1  *******************
+			printk("EFUSE PG_STATE_DATA\n");
+			badworden = 0x0f;
+			badworden = efuse_WordEnableDataWrite(dev,efuse_addr+1,target_pkt.word_en,target_pkt.data);
+			if((badworden&0x0F)==0x0F)
+			{ //************  s1-1-A *******************
+				bContinual = FALSE;
+			}
+			else
+			{//reorganize other pg packet //************  s1-1-B *******************
+				efuse_addr = efuse_addr + (2*target_word_cnts) +1;//next pg packet addr
+
+				//===========================
+				target_pkt.offset = offset;
+				target_pkt.word_en= badworden;
+				target_word_cnts =  efuse_CalculateWordCnts(target_pkt.word_en);
+				//===========================
+				#if (EFUSE_ERROE_HANDLE == 1)
+				WriteState=PG_STATE_HEADER;
+				repeat_times++;
+				if(repeat_times>EFUSE_REPEAT_THRESHOLD_){
+					bContinual = FALSE;
+					bResult = FALSE;
+				}
+				#endif
+				printk("EFUSE PG_STATE_HEADER-3\n");
+			}
+		}
+	}
+
+	//efuse_reg_ctrl(pAdapter,FALSE);//power off
+
+	return TRUE;
+}	// efuse_PgPacketWrite
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_WordEnableDataRead
+ *
+ * Overview:	Read allowed word in current efuse section data.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/16/2008 	MHC		Create Version 0.
+ * 11/21/2008 	MHC		Fix Write bug when we only enable late word.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+efuse_WordEnableDataRead(	u8 word_en,u8 *sourdata,u8 *targetdata)
+{
+	//u8 tmpindex = 0;
+
+	//DbgPrint("efuse_WordEnableDataRead word_en = %x\n", word_en);
+
+	//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("sourdata\n"), sourdata, 8);
+	//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("targetdata\n"), targetdata, 8);
+
+	if (!(word_en&BIT0))
+	{
+		targetdata[0] = sourdata[0];//sourdata[tmpindex++];
+		targetdata[1] = sourdata[1];//sourdata[tmpindex++];
+	}
+	if (!(word_en&BIT1))
+	{
+		targetdata[2] = sourdata[2];//sourdata[tmpindex++];
+		targetdata[3] = sourdata[3];//sourdata[tmpindex++];
+	}
+	if (!(word_en&BIT2))
+	{
+		targetdata[4] = sourdata[4];//sourdata[tmpindex++];
+		targetdata[5] = sourdata[5];//sourdata[tmpindex++];
+	}
+	if (!(word_en&BIT3))
+	{
+		targetdata[6] = sourdata[6];//sourdata[tmpindex++];
+		targetdata[7] = sourdata[7];//sourdata[tmpindex++];
+	}
+}	// efuse_WordEnableDataRead
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_WordEnableDataWrite
+ *
+ * Overview:	Write necessary word unit into current efuse section!
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/16/2008 	MHC		Reorganize Efuse operate flow!!.
+ *
+ *---------------------------------------------------------------------------*/
+static	u8
+efuse_WordEnableDataWrite(	struct net_device*	dev,	u16 efuse_addr, u8 word_en, u8 *data)
+{
+	u16 tmpaddr = 0;
+	u16 start_addr = efuse_addr;
+	u8 badworden = 0x0F;
+	//u8 NextState;
+	u8 tmpdata[8];
+
+	memset(tmpdata,0xff,PGPKT_DATA_SIZE);
+	//PlatformFillMemory((PVOID)tmpdata, PGPKT_DATA_SIZE, 0xff);
+
+	//RT_TRACE(COMP_EFUSE, "word_en = %x efuse_addr=%x\n", word_en, efuse_addr);
+
+	//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("U-EFUSE\n"), data, 8);
+
+	if(!(word_en&BIT0))
+	{
+		tmpaddr = start_addr;
+		efuse_OneByteWrite(dev,start_addr++, data[0]);
+		efuse_OneByteWrite(dev,start_addr++, data[1]);
+
+		efuse_OneByteRead(dev,tmpaddr, &tmpdata[0]);
+		efuse_OneByteRead(dev,tmpaddr+1, &tmpdata[1]);
+		if((data[0]!=tmpdata[0])||(data[1]!=tmpdata[1])){
+			badworden &= (~BIT0);
+		}
+	}
+	if(!(word_en&BIT1))
+	{
+		tmpaddr = start_addr;
+		efuse_OneByteWrite(dev,start_addr++, data[2]);
+		efuse_OneByteWrite(dev,start_addr++, data[3]);
+
+		efuse_OneByteRead(dev,tmpaddr    , &tmpdata[2]);
+		efuse_OneByteRead(dev,tmpaddr+1, &tmpdata[3]);
+		if((data[2]!=tmpdata[2])||(data[3]!=tmpdata[3])){
+			badworden &=( ~BIT1);
+		}
+	}
+	if(!(word_en&BIT2))
+	{
+		tmpaddr = start_addr;
+		efuse_OneByteWrite(dev,start_addr++, data[4]);
+		efuse_OneByteWrite(dev,start_addr++, data[5]);
+
+		efuse_OneByteRead(dev,tmpaddr, &tmpdata[4]);
+		efuse_OneByteRead(dev,tmpaddr+1, &tmpdata[5]);
+		if((data[4]!=tmpdata[4])||(data[5]!=tmpdata[5])){
+			badworden &=( ~BIT2);
+		}
+	}
+	if(!(word_en&BIT3))
+	{
+		tmpaddr = start_addr;
+		efuse_OneByteWrite(dev,start_addr++, data[6]);
+		efuse_OneByteWrite(dev,start_addr++, data[7]);
+
+		efuse_OneByteRead(dev,tmpaddr, &tmpdata[6]);
+		efuse_OneByteRead(dev,tmpaddr+1, &tmpdata[7]);
+		if((data[6]!=tmpdata[6])||(data[7]!=tmpdata[7])){
+			badworden &=( ~BIT3);
+		}
+	}
+	return badworden;
+}	// efuse_WordEnableDataWrite
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_PowerSwitch
+ *
+ * Overview:	When we want to enable write operation, we should change to
+ *				pwr on state. When we stop write, we should switch to 500k mode
+ *				and disable LDO 2.5V.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/17/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+efuse_PowerSwitch(struct net_device* dev, u8 PwrState)
+{
+	u8	tempval;
+	if (PwrState == TRUE)
+	{
+		// Enable LDO 2.5V for write action
+		tempval = read_nic_byte(dev, EFUSE_TEST+3);
+		write_nic_byte(dev, EFUSE_TEST+3, (tempval | 0x80));
+
+		// Change Efuse Clock for write action to 40MHZ
+		write_nic_byte(dev, EFUSE_CLK, 0x03);
+	}
+	else
+	{
+		// Enable LDO 2.5V for write action
+		tempval = read_nic_byte(dev, EFUSE_TEST+3);
+		write_nic_byte(dev, EFUSE_TEST+3, (tempval & 0x7F));
+
+		// Change Efuse Clock for write action to 500K
+		write_nic_byte(dev, EFUSE_CLK, 0x02);
+	}
+
+}	/* efuse_PowerSwitch */
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_GetCurrentSize
+ *
+ * Overview:	Get current efuse size!!!
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/16/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+static	u16
+efuse_GetCurrentSize(struct net_device*	dev)
+{
+	bool bContinual = TRUE;
+
+	u16 efuse_addr = 0;
+	u8 hoffset=0,hworden=0;
+	u8 efuse_data,word_cnts=0;
+
+	//efuse_reg_ctrl(pAdapter,TRUE);//power on
+
+	while (	bContinual &&
+			efuse_OneByteRead(dev, efuse_addr ,&efuse_data) &&
+			(efuse_addr  < EFUSE_MAX_SIZE) )
+	{
+		if(efuse_data!=0xFF)
+		{
+			hoffset = (efuse_data>>4) & 0x0F;
+			hworden =  efuse_data & 0x0F;
+			word_cnts = efuse_CalculateWordCnts(hworden);
+			//read next header
+			efuse_addr = efuse_addr + (word_cnts*2)+1;
+		}
+		else
+		{
+			bContinual = FALSE ;
+		}
+	}
+
+	//efuse_reg_ctrl(pAdapter,FALSE);//power off
+
+	return efuse_addr;
+
+}	// efuse_GetCurrentSize}
+
+
+/*  11/16/2008 MH Add description. Get current efuse area enabled word!!. */
+static u8
+efuse_CalculateWordCnts(u8	word_en)
+{
+	u8 word_cnts = 0;
+	if(!(word_en & BIT0))	word_cnts++; // 0 : write enable
+	if(!(word_en & BIT1))	word_cnts++;
+	if(!(word_en & BIT2))	word_cnts++;
+	if(!(word_en & BIT3))	word_cnts++;
+	return word_cnts;
+}	// efuse_CalculateWordCnts
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_ResetLoader
+ *
+ * Overview:	When read Efuse Fail we must reset loader!!!!
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/22/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+#if 0
+static void efuse_ResetLoader(struct net_device* dev)
+{
+	u16	tmpU2b;
+
+	//
+	// 2008/11/22 MH Sometimes, we may read efuse fail, for preventing the condition
+	// We have to reset loader.
+	//
+	tmpU2b = read_nic_word(dev, SYS_FUNC_EN);
+	write_nic_word(dev, SYS_FUNC_EN, (tmpU2b&~(BIT12)));
+	//PlatformStallExecution(10000);	// How long should we delay!!!
+	mdelay(10);
+	write_nic_word(dev, SYS_FUNC_EN, (tmpU2b|BIT12));
+	//PlatformStallExecution(10000);	// How long should we delay!!!
+	mdelay(10);
+
+}	// efuse_ResetLoader
+#endif
+
+/*-----------------------------------------------------------------------------
+ * Function:	EFUSE_ProgramMap
+ *
+ * Overview:	Read EFUSE map file and execute PG.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/10/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+ #ifdef TO_DO_LIST
+extern	bool	// 0=Shadow 1=Real Efuse
+EFUSE_ProgramMap(struct net_device* dev, char* pFileName,u8	TableType)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	s4Byte			nLinesRead, ithLine;
+	RT_STATUS		rtStatus = RT_STATUS_SUCCESS;
+	char* 			szLine;
+	u32			u4bRegValue, u4RegMask;
+	u32			u4bMove;
+	u16			index = 0;
+	u16			i;
+	u8			eeprom[HWSET_MAX_SIZE_92S];
+
+	rtStatus = PlatformReadFile(
+					dev,
+					pFileName,
+					(u8*)(priv->BufOfLines),
+					MAX_LINES_HWCONFIG_TXT,
+					MAX_BYTES_LINE_HWCONFIG_TXT,
+					&nLinesRead
+					);
+
+	if(rtStatus == RT_STATUS_SUCCESS)
+	{
+		memcp(pHalData->BufOfLines3, pHalData->BufOfLines,
+			nLinesRead*MAX_BYTES_LINE_HWCONFIG_TXT);
+		pHalData->nLinesRead3 = nLinesRead;
+	}
+
+	if(rtStatus == RT_STATUS_SUCCESS)
+	{
+		printk("szEepromFile(): read %s ok\n", pFileName);
+		for(ithLine = 0; ithLine < nLinesRead; ithLine++)
+		{
+			szLine = pHalData->BufOfLines[ithLine];
+			printk("Line-%d String =%s\n", ithLine, szLine);
+
+			if(!IsCommentString(szLine))
+			{
+				// EEPROM map one line has 8 words content.
+				for (i = 0; i < 8; i++)
+				{
+					u32	j;
+
+					//GetHexValueFromString(szLine, &u4bRegValue, &u4bMove);
+					efuse_ParsingMap(szLine, &u4bRegValue, &u4bMove);
+
+					// Get next hex value as EEPROM value.
+					szLine += u4bMove;
+					//WriteEEprom(dev, (u16)(ithLine*8+i), (u16)u4bRegValue);
+					eeprom[index++] = (u8)(u4bRegValue&0xff);
+					eeprom[index++] = (u8)((u4bRegValue>>8)&0xff);
+
+					printk("Addr-%d = %x\n", (ithLine*8+i), u4bRegValue);
+				}
+			}
+
+		}
+
+	}
+	else
+	{
+		printk("szEepromFile(): Fail read%s\n", pFileName);
+		return	RT_STATUS_FAILURE;
+	}
+
+
+	//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("EFUSE "), eeprom, HWSET_MAX_SIZE_92S);
+
+	// Use map file to update real Efuse or shadow modify table.
+	if (TableType == 1)
+	{
+		efuse_WriteAllMap(dev, eeprom, HWSET_MAX_SIZE_92S);
+	}
+	else
+	{
+		// Modify shadow table.
+		for (i = 0; i < HWSET_MAX_SIZE_92S; i++)
+			EFUSE_ShadowWrite(dev, 1, i, (u32)eeprom[i]);
+	}
+
+	return	rtStatus;
+}	/* EFUSE_ProgramMap */
+
+#endif
+
+//
+//	Description:
+//		Return TRUE if chTmp is represent for hex digit and
+//		FALSE otherwise.
+//
+//
+bool IsHexDigit(	char chTmp)
+{
+	if( (chTmp >= '0' && chTmp <= '9') ||
+		(chTmp >= 'a' && chTmp <= 'f') ||
+		(chTmp >= 'A' && chTmp <= 'F') )
+	{
+		return TRUE;
+	}
+	else
+	{
+		return FALSE;
+	}
+}
+
+//
+//	Description:
+//		Translate a character to hex digit.
+//
+u32 MapCharToHexDigit(char chTmp)
+{
+	if(chTmp >= '0' && chTmp <= '9')
+		return (chTmp - '0');
+	else if(chTmp >= 'a' && chTmp <= 'f')
+		return (10 + (chTmp - 'a'));
+	else if(chTmp >= 'A' && chTmp <= 'F')
+		return (10 + (chTmp - 'A'));
+	else
+		return 0;
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:	efuse_ParsingMap
+ *
+ * Overview:
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/08/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+#ifdef TO_DO_LIST
+static	bool
+efuse_ParsingMap(char* szStr,u32* pu4bVal,u32* pu4bMove)
+{
+	char* 		szScan = szStr;
+
+	// Check input parameter.
+	if(szStr == NULL || pu4bVal == NULL || pu4bMove == NULL)
+	{
+		//RT_TRACE(COMP_EFUSE,
+		//"eeprom_ParsingMap(): Invalid IN args! szStr: %p, pu4bVal: %p, pu4bMove: %p\n",
+		//szStr, pu4bVal, pu4bMove);
+		return FALSE;
+	}
+
+	// Initialize output.
+	*pu4bMove = 0;
+	*pu4bVal = 0;
+
+	// Skip leading space.
+	while(	*szScan != '\0' &&
+			(*szScan == ' ' || *szScan == '\t') )
+	{
+		szScan++;
+		(*pu4bMove)++;
+	}
+
+	// Check if szScan is now pointer to a character for hex digit,
+	// if not, it means this is not a valid hex number.
+	if(!IsHexDigit(*szScan))
+	{
+		return FALSE;
+	}
+
+	// Parse each digit.
+	do
+	{
+		(*pu4bVal) <<= 4;
+		*pu4bVal += MapCharToHexDigit(*szScan);
+
+		szScan++;
+		(*pu4bMove)++;
+	} while(IsHexDigit(*szScan));
+
+	return TRUE;
+
+}	/* efuse_ParsingMap */
+#endif
+
+//
+// Useless Section Code Now!!!!!!
+//
+// Porting from 8712 SDIO
+int efuse_one_byte_rw(struct net_device* dev, u8 bRead, u16 addr, u8 *data)
+{
+	u32 bResult;
+	//u8 efuse_ctlreg,tmpidx = 0;
+	u8 tmpidx = 0;
+	u8 tmpv8=0;
+
+	// -----------------e-fuse reg ctrl ---------------------------------
+
+	write_nic_byte(dev, EFUSE_CTRL+1, (u8)(addr&0xff));		//address
+	tmpv8 = ((u8)((addr>>8) &0x03) ) | (read_nic_byte(dev, EFUSE_CTRL+2)&0xFC );
+	write_nic_byte(dev, EFUSE_CTRL+2, tmpv8);
+
+	if(TRUE==bRead){
+
+		write_nic_byte(dev, EFUSE_CTRL+3,  0x72);//read cmd
+
+		while(!(0x80 & read_nic_byte(dev, EFUSE_CTRL+3)) && (tmpidx<100) ){
+			tmpidx++;
+		}
+		if(tmpidx<100){
+			*data=read_nic_byte(dev, EFUSE_CTRL);
+			bResult = TRUE;
+		}
+		else
+		{
+			*data = 0;
+			bResult = FALSE;
+		}
+
+	}
+	else{
+		//return	0;
+		write_nic_byte(dev, EFUSE_CTRL, *data);//data
+
+		write_nic_byte(dev, EFUSE_CTRL+3, 0xF2);//write cmd
+
+		while((0x80 & read_nic_byte(dev, EFUSE_CTRL+3)) && (tmpidx<100) ){
+			tmpidx++;
+		}
+		if(tmpidx<100)
+		{
+			*data=read_nic_byte(dev, EFUSE_CTRL);
+			bResult = TRUE;
+		}
+		else
+		{
+			*data = 0;
+			bResult = FALSE;
+		}
+
+	}
+	return bResult;
+}
+//------------------------------------------------------------------------------
+void efuse_access(struct net_device* dev, u8 bRead,u16 start_addr, u8 cnts, u8 *data)
+{
+	u8	efuse_clk_ori,efuse_clk_new;//,tmp8;
+	u32 i = 0;
+
+	if(start_addr>0x200) return;
+	//RT_TRACE(_module_rtl871x_mp_ioctl_c_,_drv_err_,
+	//	("\n ===> efuse_access [start_addr=0x%x cnts:%d dataarray:0x%08x  Query Efuse].\n",start_addr,cnts,data));
+	// -----------------SYS_FUNC_EN Digital Core Vdd enable ---------------------------------
+	efuse_clk_ori = read_nic_byte(dev,SYS_FUNC_EN+1);
+	efuse_clk_new = efuse_clk_ori|0x20;
+
+	if(efuse_clk_new!= efuse_clk_ori){
+		//RT_TRACE(_module_rtl871x_mp_ioctl_c_,_drv_err_,("====write 0x10250003=====\n"));
+		write_nic_byte(dev, SYS_FUNC_EN+1, efuse_clk_new);
+	}
+#ifdef _POWERON_DELAY_
+	mdelay(10);
+#endif
+	// -----------------e-fuse pwr & clk reg ctrl ---------------------------------
+	write_nic_byte(dev, EFUSE_TEST+3, (read_nic_byte(dev, EFUSE_TEST+3)|0x80));
+	write_nic_byte(dev, EFUSE_CLK_CTRL, (read_nic_byte(dev, EFUSE_CLK_CTRL)|0x03));
+
+#ifdef _PRE_EXECUTE_READ_CMD_
+	{
+		unsigned char tmpdata;
+		efuse_OneByteRead(dev, 0,&tmpdata);
+	}
+#endif
+
+	//-----------------e-fuse one byte read / write ------------------------------
+	for(i=0;i<cnts;i++){
+		efuse_one_byte_rw(dev,bRead, start_addr+i , data+i);
+		////RT_TRACE(_module_rtl871x_mp_ioctl_c_,_drv_err_,("==>efuse_access addr:0x%02x value:0x%02x\n",data+i,*(data+i)));
+	}
+	// -----------------e-fuse pwr & clk reg ctrl ---------------------------------
+	write_nic_byte(dev, EFUSE_TEST+3, read_nic_byte(dev, EFUSE_TEST+3)&0x7f);
+	write_nic_byte(dev, EFUSE_CLK_CTRL, read_nic_byte(dev, EFUSE_CLK_CTRL)&0xfd);
+
+	// -----------------SYS_FUNC_EN Digital Core Vdd disable ---------------------------------
+	if(efuse_clk_new != efuse_clk_ori)	write_nic_byte(dev, 0x10250003, efuse_clk_ori);
+
+}
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+
+#ifdef TO_DO_LIST
+static	void efuse_reg_ctrl(struct net_device* dev, u8 bPowerOn)
+{
+	if(TRUE==bPowerOn){
+		// -----------------SYS_FUNC_EN Digital Core Vdd enable ---------------------------------
+		write_nic_byte(dev, SYS_FUNC_EN+1,  read_nic_byte(dev,SYS_FUNC_EN+1)|0x20);
+#ifdef _POWERON_DELAY_
+		mdelay(10);
+#endif
+		// -----------------e-fuse pwr & clk reg ctrl ---------------------------------
+		write_nic_byte(dev, EFUSE_TEST+4, (read_nic_byte(dev, EFUSE_TEST+4)|0x80));
+		write_nic_byte(dev, EFUSE_CLK_CTRL, (read_nic_byte(dev, EFUSE_CLK_CTRL)|0x03));
+#ifdef _PRE_EXECUTE_READ_CMD_
+		{
+			unsigned char tmpdata;
+			efuse_OneByteRead(dev, 0,&tmpdata);
+		}
+
+#endif
+	}
+	else{
+		// -----------------e-fuse pwr & clk reg ctrl ---------------------------------
+		write_nic_byte(dev, EFUSE_TEST+4, read_nic_byte(dev, EFUSE_TEST+4)&0x7f);
+		write_nic_byte(dev, EFUSE_CLK_CTRL, read_nic_byte(dev, EFUSE_CLK_CTRL)&0xfd);
+		// -----------------SYS_FUNC_EN Digital Core Vdd disable ---------------------------------
+
+		//write_nic_byte(pAdapter, SYS_FUNC_EN+1,  read_nic_byte(pAdapter,SYS_FUNC_EN+1)&0xDF);
+	}
+
+
+}
+#endif
+//------------------------------------------------------------------------------
+
+//------------------------------------------------------------------------------
+void efuse_read_data(struct net_device* dev,u8 efuse_read_item,u8 *data,u32 data_size)
+{
+	u8 offset, word_start,byte_start,byte_cnts;
+	u8	efusedata[EFUSE_MAC_LEN];
+	u8 *tmpdata = NULL;
+
+	u8 pg_pkt_cnts ;
+
+	u8 tmpidx;
+	u8 pg_data[8];
+	//u8	temp_value[8] = {0xff};
+
+	if(efuse_read_item>  (sizeof(RTL8712_SDIO_EFUSE_TABLE)/sizeof(EFUSE_MAP))){
+		//error msg
+		return ;
+	}
+
+	offset		= RTL8712_SDIO_EFUSE_TABLE[efuse_read_item].offset ;
+	word_start	= RTL8712_SDIO_EFUSE_TABLE[efuse_read_item].word_start;
+	byte_start 	= RTL8712_SDIO_EFUSE_TABLE[efuse_read_item].byte_start;
+	byte_cnts   	= RTL8712_SDIO_EFUSE_TABLE[efuse_read_item].byte_cnts;
+
+	if(data_size!=byte_cnts){
+		//error msg
+		return;
+	}
+
+	pg_pkt_cnts = (byte_cnts /PGPKT_DATA_SIZE) +1;
+
+	if(pg_pkt_cnts > 1){
+		//tmpdata = _malloc(pg_pkt_cnts*PGPKT_DATA_SIZE);
+		tmpdata = efusedata;
+
+		if(tmpdata!=NULL)
+		{
+			memset(tmpdata,0xff,pg_pkt_cnts*PGPKT_DATA_SIZE);
+			//PlatformFillMemory((PVOID)pg_data, pg_pkt_cnts*PGPKT_DATA_SIZE, 0xff);
+
+			for(tmpidx=0;tmpidx<pg_pkt_cnts;tmpidx++)
+			{
+				memset(pg_data,0xff,PGPKT_DATA_SIZE);
+				//PlatformFillMemory((PVOID)pg_data, PGPKT_DATA_SIZE, 0xff);
+				if(TRUE== efuse_PgPacketRead(dev,offset+tmpidx,pg_data))
+				{
+					memcpy(tmpdata+(PGPKT_DATA_SIZE*tmpidx),pg_data,PGPKT_DATA_SIZE);
+					//PlatformMoveMemory((PVOID)(tmpdata+(PGPKT_DATA_SIZE*tmpidx)), (PVOID)pg_data, PGPKT_DATA_SIZE);
+				}
+			}
+			memcpy(data,(tmpdata+ (2*word_start)+byte_start ),data_size);
+			//PlatformMoveMemory((PVOID)data, (PVOID)(tmpdata+ (2*word_start)+byte_start ), data_size);
+			//_mfree(tmpdata, pg_pkt_cnts*PGPKT_DATA_SIZE);
+		}
+	}
+	else
+	{
+		memset(pg_data,0xff,PGPKT_DATA_SIZE);
+		//PlatformFillMemory((PVOID)pg_data, PGPKT_DATA_SIZE, 0xff);
+		if(TRUE==efuse_PgPacketRead(dev,offset,pg_data)){
+			memcpy(data,pg_data+ (2*word_start)+byte_start ,data_size);
+			//PlatformMoveMemory((PVOID)data, (PVOID)(pg_data+ (2*word_start)+byte_start), data_size);
+		}
+	}
+
+}
+//------------------------------------------------------------------------------
+//per interface doesn't alike
+void efuse_write_data(struct net_device* dev,u8 efuse_write_item,u8 *data,u32 data_size,u32 bWordUnit)
+{
+	u8 offset, word_start,byte_start,byte_cnts;
+	u8 word_en = 0x0f,word_cnts;
+	u8 pg_pkt_cnts ;
+
+	u8 tmpidx,tmpbitmask;
+	u8 pg_data[8],tmpbytes=0;
+
+	if(efuse_write_item>  (sizeof(RTL8712_SDIO_EFUSE_TABLE)/sizeof(EFUSE_MAP))){
+		//error msg
+		return ;
+	}
+
+	offset		= RTL8712_SDIO_EFUSE_TABLE[efuse_write_item].offset ;
+	word_start	= RTL8712_SDIO_EFUSE_TABLE[efuse_write_item].word_start;
+	byte_start 	= RTL8712_SDIO_EFUSE_TABLE[efuse_write_item].byte_start;
+	byte_cnts   	= RTL8712_SDIO_EFUSE_TABLE[efuse_write_item].byte_cnts;
+
+	if(data_size >  byte_cnts){
+		//error msg
+		return;
+	}
+	pg_pkt_cnts = (byte_cnts /PGPKT_DATA_SIZE) +1;
+	word_cnts = byte_cnts /2 ;
+
+	if(byte_cnts %2){
+		word_cnts+=1;
+	}
+	if((byte_start==1)||((byte_cnts%2)==1)){//situation A
+
+		if((efuse_write_item==EFUSE_F0CIS)||(efuse_write_item==EFUSE_F1CIS)){
+			memset(pg_data,0xff,PGPKT_DATA_SIZE);
+			//PlatformFillMemory((PVOID)pg_data, PGPKT_DATA_SIZE, 0xff);
+			efuse_PgPacketRead(dev,offset,pg_data);
+
+			if(efuse_write_item==EFUSE_F0CIS){
+				word_en = 0x07;
+				memcpy(pg_data+word_start*2+byte_start,data,sizeof(u8)*2);
+				//PlatformMoveMemory((PVOID)(pg_data+word_start*2+byte_start), (PVOID)data, sizeof(u8)*2);
+				efuse_PgPacketWrite(dev,offset,word_en,pg_data+(word_start*2));
+
+				word_en = 0x00;
+				efuse_PgPacketWrite(dev,(offset+1),word_en,data+2);
+
+				word_en = 0x00;
+				efuse_PgPacketRead(dev,offset+2,pg_data);
+				memcpy(pg_data,data+2+8,sizeof(u8)*7);
+				//PlatformMoveMemory((PVOID)(pg_data), (PVOID)(data+2+8), sizeof(u8)*7);
+
+				efuse_PgPacketWrite(dev,(offset+2),word_en,pg_data);
+			}
+			else if(efuse_write_item==EFUSE_F1CIS){
+				word_en = 0x07;
+				efuse_PgPacketRead(dev,offset,pg_data);
+				pg_data[7] = data[0];
+				efuse_PgPacketWrite(dev,offset,word_en,pg_data+(word_start*2));
+
+				word_en = 0x00;
+				for(tmpidx = 0 ;tmpidx<(word_cnts/4);tmpidx++){
+					efuse_PgPacketWrite(dev,(offset+1+tmpidx),word_en,data+1+(tmpidx*PGPKT_DATA_SIZE));
+				}
+			}
+
+		}
+		else{
+			memset(pg_data,0xff,PGPKT_DATA_SIZE);
+			//PlatformFillMemory((PVOID)pg_data, PGPKT_DATA_SIZE, 0xff);
+			if((efuse_write_item==EFUSE_SDIO_SETTING)||(efuse_write_item==EFUSE_CCCR)){
+				word_en = 0x0e ;
+				tmpbytes = 2;
+			}
+			else if(efuse_write_item == EFUSE_SDIO_MODE){
+				word_en = 0x0d ;
+				tmpbytes = 2;
+			}
+			else if(efuse_write_item == EFUSE_OCR){
+				word_en = 0x09 ;
+				tmpbytes = 4;
+			}
+			else if((efuse_write_item == EFUSE_EEPROM_VER)||(efuse_write_item==EFUSE_CHAN_PLAN)){
+				word_en = 0x07 ;
+				tmpbytes = 2;
+			}
+			if(bWordUnit==TRUE){
+				memcpy(pg_data+word_start*2 ,data,sizeof(u8)*tmpbytes);
+				//PlatformMoveMemory((PVOID)(pg_data+word_start*2), (PVOID)(data), sizeof(u8)*tmpbytes);
+			}
+			else{
+				efuse_PgPacketRead(dev,offset,pg_data);
+				memcpy(pg_data+(2*word_start)+byte_start,data,sizeof(u8)*byte_cnts);
+				//PlatformMoveMemory((PVOID)(pg_data+(2*word_start)+byte_start), (PVOID)(data), sizeof(u8)*byte_cnts);
+			}
+
+			efuse_PgPacketWrite(dev,offset,word_en,pg_data+(word_start*2));
+
+		}
+
+	}
+	//========================================================================
+	else if(pg_pkt_cnts>1){//situation B
+		if(word_start==0){
+			word_en = 0x00;
+			for(tmpidx = 0 ;tmpidx<(word_cnts/4);tmpidx++)
+			{
+				efuse_PgPacketWrite(dev,(offset+tmpidx),word_en,data+(tmpidx*PGPKT_DATA_SIZE));
+			}
+			word_en = 0x0f;
+			for(tmpidx= 0; tmpidx<(word_cnts%4) ; tmpidx++)
+			{
+				tmpbitmask =tmpidx;
+				word_en &= (~(EFUSE_BIT(tmpbitmask)));
+				//BIT0
+			}
+			efuse_PgPacketWrite(dev,offset+(word_cnts/4),word_en,data+((word_cnts/4)*PGPKT_DATA_SIZE));
+		}else
+		{
+
+		}
+	}
+	//========================================================================
+	else{//situation C
+		word_en = 0x0f;
+		for(tmpidx= 0; tmpidx<word_cnts ; tmpidx++)
+		{
+			tmpbitmask = word_start + tmpidx ;
+			word_en &= (~(EFUSE_BIT(tmpbitmask)));
+		}
+		efuse_PgPacketWrite(dev,offset,word_en,data);
+	}
+
+}
+//------------------------------------------------------------------------------
+
+void efuset_test_func_read(struct net_device* dev)
+{
+	u8 chipid[2];
+	u8 ocr[3];
+	u8 macaddr[6];
+	u8 txpowertable[28];
+
+	memset(chipid,0,sizeof(u8)*2);
+	efuse_read_data(dev,EFUSE_CHIP_ID,chipid,sizeof(chipid));
+
+	memset(ocr,0,sizeof(u8)*3);
+	efuse_read_data(dev,EFUSE_CCCR,ocr,sizeof(ocr));
+
+	memset(macaddr,0,sizeof(u8)*6);
+	efuse_read_data(dev,EFUSE_MAC_ADDR,macaddr,sizeof(macaddr));
+
+	memset(txpowertable,0,sizeof(u8)*28);
+	efuse_read_data(dev,EFUSE_TXPW_TAB,txpowertable,sizeof(txpowertable));
+}
+//------------------------------------------------------------------------------
+
+void efuset_test_func_write(struct net_device* dev)
+{
+	u32 bWordUnit = TRUE;
+	u8 CCCR=0x02,SDIO_SETTING = 0xFF;
+	u8 tmpdata[2];
+
+	u8 macaddr[6] = {0x00,0xe0,0x4c,0x87,0x12,0x66};
+	efuse_write_data(dev,EFUSE_MAC_ADDR,macaddr,sizeof(macaddr),bWordUnit);
+
+	bWordUnit = FALSE;
+	efuse_write_data(dev,EFUSE_CCCR,&CCCR,sizeof(u8),bWordUnit);
+
+	bWordUnit = FALSE;
+	efuse_write_data(dev,EFUSE_SDIO_SETTING,&SDIO_SETTING,sizeof(u8),bWordUnit);
+
+	bWordUnit = TRUE;
+	tmpdata[0] =SDIO_SETTING ;
+	tmpdata[1] =CCCR ;
+	efuse_write_data(dev,EFUSE_SDIO_SETTING,tmpdata,sizeof(tmpdata),bWordUnit);
+
+}
+//------------------------------------------------------------------------------
+
+
+
+
+#endif	// #if (HAL_CODE_BASE == RTL8192_S)
+
+
+
+
+
+
+/* End of Efuse.c */
+
+
+
+
diff --git a/drivers/staging/rtl8192su/r8192S_Efuse.h b/drivers/staging/rtl8192su/r8192S_Efuse.h
new file mode 100644
index 0000000..1e50153
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_Efuse.h
@@ -0,0 +1,101 @@
+/******************************************************************************
+ *
+ *     (c) Copyright  2008, RealTEK Technologies Inc. All Rights Reserved.
+ *
+ * Module:	Efuse.h	( Header File)
+ *
+ * Note:
+ *
+ * Function:
+ *
+ * Export:
+ *
+ * Abbrev:
+ *
+ * History:
+ * Data			Who		Remark
+ *
+ * 09/23/2008	MHC		Porting Efuse R/W API from WMAC.
+ * 11/10/2008	MHC		Porting Efuse.h from 8712 SDIO.
+ *						1. We muse redefine the header file to fit our coding
+ *						   style.
+ *						2. THe API we export to other module, we must redefine
+ *						   for 8192S series.
+ *
+ *
+******************************************************************************/
+/* Check to see if the file has been included already.  */
+
+#ifndef __INC_EFUSE_H
+#define __INC_EFUSE_H
+
+// Roger porting for 8192SU
+#define		EFUSE_FOR_92SU		1
+
+/*--------------------------Define Parameters-------------------------------*/
+#define		EFUSE_MAC_LEN					0x200
+
+#define		EFUSE_INIT_MAP				0
+#define		EFUSE_MODIFY_MAP				1
+
+#define		EFUSE_CLK_CTRL			EFUSE_CTRL
+#define 	EFUSE_BIT(x)  (1 << (x))
+
+// From 8712!!!!!!!!
+#define		PG_STATE_HEADER 	0x01
+#define		PG_STATE_WORD_0		0x02
+#define		PG_STATE_WORD_1		0x04
+#define		PG_STATE_WORD_2		0x08
+#define		PG_STATE_WORD_3		0x10
+#define		PG_STATE_DATA		0x20
+
+#define		PG_SWBYTE_H			0x01
+#define		PG_SWBYTE_L			0x02
+
+/*--------------------------Define Parameters-------------------------------*/
+
+
+/*------------------------------Define structure----------------------------*/
+
+/*------------------------------Define structure----------------------------*/
+
+
+/*------------------------Export global variable----------------------------*/
+/*------------------------Export global variable----------------------------*/
+
+/*------------------------Export Marco Definition---------------------------*/
+
+/*------------------------Export Marco Definition---------------------------*/
+
+
+/*--------------------------Exported Function prototype---------------------*/
+extern	void
+EFUSE_Initialize(struct net_device* dev);
+extern	u8
+EFUSE_Read1Byte(struct net_device* dev,u16 Address);
+extern	void
+EFUSE_Write1Byte(struct net_device* dev,u16 Address,u8 Value);
+
+#ifdef EFUSE_FOR_92SU
+extern 	void
+ReadEFuse(struct net_device* dev,u16 _offset,u16 _size_byte,u8* pbuf);
+extern	void
+ReadEFuseByte(struct net_device* dev,u16  _offset,u8  *pbuf);
+#endif	// #if (EFUSE_FOR_92SU == 1)
+
+extern	void
+EFUSE_ShadowRead(struct net_device* dev,unsigned char Type,unsigned short Offset,u32 *Value);
+extern	void
+EFUSE_ShadowWrite(struct net_device* dev,unsigned char Type,unsigned short Offset,u32 Value);
+extern	void
+EFUSE_ShadowUpdate(struct net_device* dev);
+extern	void
+EFUSE_ShadowMapUpdate(struct net_device* dev);
+
+extern	bool
+EFUSE_ProgramMap(struct net_device* dev,char* pFileName, u8 TableType);		// 0=Shadow 1=Real Efuse
+/*--------------------------Exported Function prototype---------------------*/
+
+/* End of Efuse.h */
+
+#endif //__INC_EFUSE_H
diff --git a/drivers/staging/rtl8192su/r8192S_FwImgDTM.h b/drivers/staging/rtl8192su/r8192S_FwImgDTM.h
new file mode 100644
index 0000000..afced75
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_FwImgDTM.h
@@ -0,0 +1,3797 @@
+#ifndef HAL8192PciE_FW_IMG_DTM_H
+#define HAL8192PciE_FW_IMG_DTM_H
+
+/*Created on  2008/ 3/11,  8:34*/
+#include <linux/types.h>
+
+#define MACPHY_ArrayLengthDTM 18
+#define MACPHY_Array_PGLengthDTM 30
+#define AGCTAB_ArrayLengthDTM 384
+#define AGCTAB_ArrayLength 384
+
+#define BootArrayLengthDTM 344
+u8 Rtl8192PciEFwBootArrayDTM[BootArrayLengthDTM] = {
+0x10,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x3c,0x08,0xbf,0xc0,0x25,0x08,0x00,0x08,
+0x3c,0x09,0xb0,0x03,0xad,0x28,0x00,0x20,0x40,0x80,0x68,0x00,0x00,0x00,0x00,0x00,
+0x3c,0x0a,0xd0,0x00,0x40,0x8a,0x60,0x00,0x00,0x00,0x00,0x00,0x3c,0x08,0x80,0x01,
+0x25,0x08,0xbc,0xf0,0x24,0x09,0x00,0x01,0x3c,0x01,0x7f,0xff,0x34,0x21,0xff,0xff,
+0x01,0x01,0x50,0x24,0x00,0x09,0x48,0x40,0x35,0x29,0x00,0x01,0x01,0x2a,0x10,0x2b,
+0x14,0x40,0xff,0xfc,0x00,0x00,0x00,0x00,0x3c,0x0a,0x00,0x00,0x25,0x4a,0x00,0x00,
+0x4c,0x8a,0x00,0x00,0x4c,0x89,0x08,0x00,0x00,0x00,0x00,0x00,0x3c,0x08,0x80,0x01,
+0x25,0x08,0xbc,0xf0,0x3c,0x01,0x80,0x00,0x01,0x21,0x48,0x25,0x3c,0x0a,0xbf,0xc0,
+0x25,0x4a,0x00,0x7c,0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,0xad,0x00,0x00,0x00,
+0x21,0x08,0x00,0x04,0x01,0x09,0x10,0x2b,0x14,0x40,0xff,0xf8,0x00,0x00,0x00,0x00,
+0x3c,0x08,0x80,0x01,0x25,0x08,0x7f,0xff,0x24,0x09,0x00,0x01,0x3c,0x01,0x7f,0xff,
+0x34,0x21,0xff,0xff,0x01,0x01,0x50,0x24,0x00,0x09,0x48,0x40,0x35,0x29,0x00,0x01,
+0x01,0x2a,0x10,0x2b,0x14,0x40,0xff,0xfc,0x00,0x00,0x00,0x00,0x3c,0x0a,0x80,0x01,
+0x25,0x4a,0x00,0x00,0x3c,0x01,0x7f,0xff,0x34,0x21,0xff,0xff,0x01,0x41,0x50,0x24,
+0x3c,0x09,0x00,0x01,0x35,0x29,0x7f,0xff,0x4c,0x8a,0x20,0x00,0x4c,0x89,0x28,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0x08,0x04,0x10,
+0x00,0x00,0x00,0x00,0x40,0x88,0xa0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x3c,0x08,0xbf,0xc0,0x00,0x00,0x00,0x00,0x8d,0x09,0x00,0x00,0x00,0x00,0x00,0x00,
+0x3c,0x0a,0xbf,0xc0,0x25,0x4a,0x01,0x20,0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,
+0x3c,0x08,0xb0,0x03,0x8d,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x35,0x29,0x00,0x10,
+0xad,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x3c,0x08,0x80,0x00,0x25,0x08,0x5f,0x84,
+0x01,0x00,0x00,0x08,0x00,0x00,0x00,0x00,};
+
+#define MainArrayLengthDTM 48368
+u8 Rtl8192PciEFwMainArrayDTM[MainArrayLengthDTM] = {
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x40,0x04,0x68,0x00,0x40,0x05,0x70,0x00,0x40,0x06,0x40,0x00,0x0c,0x00,0x17,0x50,
+0x00,0x00,0x00,0x00,0x40,0x1a,0x68,0x00,0x33,0x5b,0x00,0x3c,0x17,0x60,0x00,0x09,
+0x00,0x00,0x00,0x00,0x40,0x1b,0x60,0x00,0x00,0x00,0x00,0x00,0x03,0x5b,0xd0,0x24,
+0x40,0x1a,0x70,0x00,0x03,0x40,0x00,0x08,0x42,0x00,0x00,0x10,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xff,0xff,0x34,0x42,0xff,0xff,0x8c,0x43,0x00,0x00,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x00,0xd0,
+0xac,0x62,0x00,0x00,0x00,0x00,0x20,0x21,0x27,0x85,0x91,0x50,0x00,0x85,0x18,0x21,
+0x24,0x84,0x00,0x01,0x28,0x82,0x00,0x0a,0x14,0x40,0xff,0xfc,0xa0,0x60,0x00,0x00,
+0x27,0x82,0x91,0x5a,0x24,0x04,0x00,0x06,0x24,0x84,0xff,0xff,0xa4,0x40,0x00,0x00,
+0x04,0x81,0xff,0xfd,0x24,0x42,0x00,0x02,0x24,0x02,0x00,0x03,0xa3,0x82,0x91,0x50,
+0x24,0x02,0x00,0x0a,0x24,0x03,0x09,0xc4,0xa3,0x82,0x91,0x52,0x24,0x02,0x00,0x04,
+0x24,0x04,0x00,0x01,0x24,0x05,0x00,0x02,0xa7,0x83,0x91,0x66,0xa3,0x82,0x91,0x58,
+0x24,0x03,0x04,0x00,0x24,0x02,0x02,0x00,0xaf,0x83,0x91,0x6c,0xa3,0x85,0x91,0x59,
+0xa7,0x82,0x91,0x5a,0xa7,0x84,0x91,0x5c,0xaf,0x84,0x91,0x68,0xa3,0x84,0x91,0x51,
+0xa3,0x80,0x91,0x53,0xa3,0x80,0x91,0x54,0xa3,0x80,0x91,0x55,0xa3,0x84,0x91,0x56,
+0xa3,0x85,0x91,0x57,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0x24,0x42,0x01,0x7c,0x34,0x63,0x00,0x20,0xac,0x62,0x00,0x00,
+0x27,0x84,0x91,0x78,0x00,0x00,0x10,0x21,0x24,0x42,0x00,0x01,0x00,0x02,0x16,0x00,
+0x00,0x02,0x16,0x03,0x28,0x43,0x00,0x03,0xac,0x80,0xff,0xfc,0xa0,0x80,0x00,0x00,
+0x14,0x60,0xff,0xf9,0x24,0x84,0x00,0x0c,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x01,0xc0,
+0x3c,0x08,0xb0,0x03,0xac,0x62,0x00,0x00,0x35,0x08,0x00,0x70,0x8d,0x02,0x00,0x00,
+0x00,0xa0,0x48,0x21,0x00,0x04,0x26,0x00,0x00,0x02,0x2a,0x43,0x00,0x06,0x36,0x00,
+0x00,0x07,0x3e,0x00,0x00,0x02,0x12,0x03,0x29,0x23,0x00,0x03,0x00,0x04,0x56,0x03,
+0x00,0x06,0x36,0x03,0x00,0x07,0x3e,0x03,0x30,0x48,0x00,0x01,0x10,0x60,0x00,0x11,
+0x30,0xa5,0x00,0x07,0x24,0x02,0x00,0x02,0x00,0x49,0x10,0x23,0x00,0x45,0x10,0x07,
+0x30,0x42,0x00,0x01,0x10,0x40,0x00,0x66,0x00,0x00,0x00,0x00,0x8f,0xa2,0x00,0x10,
+0x00,0x00,0x00,0x00,0x00,0x02,0x21,0x43,0x11,0x00,0x00,0x10,0x00,0x07,0x20,0x0b,
+0x15,0x20,0x00,0x06,0x24,0x02,0x00,0x01,0x3c,0x02,0xb0,0x05,0x34,0x42,0x01,0x20,
+0xa4,0x44,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x11,0x22,0x00,0x04,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x05,0x08,0x00,0x00,0x94,0x34,0x42,0x01,0x24,
+0x3c,0x02,0xb0,0x05,0x08,0x00,0x00,0x94,0x34,0x42,0x01,0x22,0x15,0x20,0x00,0x54,
+0x24,0x02,0x00,0x01,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0x74,0x90,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0xaf,0x83,0x91,0x74,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0x70,
+0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x6b,0x00,0x08,0x11,0x60,0x00,0x18,
+0x00,0x09,0x28,0x40,0x00,0x00,0x40,0x21,0x27,0x85,0x91,0x70,0x8c,0xa3,0x00,0x00,
+0x8c,0xa2,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x62,0x38,0x23,0x00,0x43,0x10,0x2a,
+0x10,0x40,0x00,0x3d,0x00,0x00,0x00,0x00,0xac,0xa7,0x00,0x00,0x25,0x02,0x00,0x01,
+0x00,0x02,0x16,0x00,0x00,0x02,0x46,0x03,0x29,0x03,0x00,0x03,0x14,0x60,0xff,0xf3,
+0x24,0xa5,0x00,0x0c,0x3c,0x03,0xb0,0x03,0x34,0x63,0x00,0x70,0x90,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x4b,0x10,0x23,0xa0,0x62,0x00,0x00,0x00,0x09,0x28,0x40,
+0x00,0xa9,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x83,0x91,0x78,0x00,0x0a,0x20,0x0b,
+0x00,0x43,0x18,0x21,0x10,0xc0,0x00,0x05,0x00,0x00,0x38,0x21,0x80,0x62,0x00,0x01,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x05,0x00,0x00,0x00,0x00,0x80,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x03,0x00,0xa9,0x10,0x21,0x24,0x07,0x00,0x01,
+0x00,0xa9,0x10,0x21,0x00,0x02,0x30,0x80,0x27,0x82,0x91,0x78,0xa0,0x67,0x00,0x01,
+0x00,0xc2,0x38,0x21,0x80,0xe3,0x00,0x01,0x00,0x00,0x00,0x00,0x10,0x60,0x00,0x07,
+0x00,0x00,0x00,0x00,0x27,0x83,0x91,0x70,0x00,0xc3,0x18,0x21,0x8c,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x44,0x10,0x21,0xac,0x62,0x00,0x00,0x27,0x85,0x91,0x74,
+0x27,0x82,0x91,0x70,0x00,0xc5,0x28,0x21,0x00,0xc2,0x10,0x21,0x8c,0x43,0x00,0x00,
+0x8c,0xa4,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x64,0x18,0x2a,0x14,0x60,0x00,0x03,
+0x24,0x02,0x00,0x01,0x03,0xe0,0x00,0x08,0xa0,0xe2,0x00,0x00,0xa0,0xe0,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0xb7,0xac,0xa0,0x00,0x00,
+0x11,0x22,0x00,0x08,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0x7c,
+0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0xaf,0x83,0x91,0x8c,0x08,0x00,0x00,0xa7,
+0x3c,0x02,0xb0,0x03,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0x78,0x90,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0xaf,0x83,0x91,0x80,0x08,0x00,0x00,0xa7,0x3c,0x02,0xb0,0x03,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x04,0x10,
+0x3c,0x05,0xb0,0x03,0xac,0x62,0x00,0x00,0x34,0xa5,0x00,0x70,0x8c,0xa2,0x00,0x00,
+0x90,0x84,0x00,0x08,0x3c,0x06,0xb0,0x03,0x00,0x02,0x16,0x00,0x2c,0x83,0x00,0x03,
+0x34,0xc6,0x00,0x72,0x24,0x07,0x00,0x01,0x10,0x60,0x00,0x11,0x00,0x02,0x2f,0xc2,
+0x90,0xc2,0x00,0x00,0x00,0x00,0x18,0x21,0x00,0x02,0x16,0x00,0x10,0xa7,0x00,0x09,
+0x00,0x02,0x16,0x03,0x14,0x80,0x00,0x0c,0x30,0x43,0x00,0x03,0x83,0x82,0x91,0x78,
+0x00,0x00,0x00,0x00,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x00,0x02,0x16,0x00,
+0x00,0x02,0x1e,0x03,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0x72,0xa0,0x43,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x30,0x45,0x00,0x05,0x10,0x87,0x00,0x04,
+0x30,0x43,0x00,0x06,0x93,0x82,0x91,0x90,0x08,0x00,0x01,0x1f,0x00,0x43,0x10,0x21,
+0x83,0x82,0x91,0x84,0x00,0x00,0x00,0x00,0x00,0x02,0x10,0x40,0x08,0x00,0x01,0x1f,
+0x00,0x45,0x10,0x21,0x10,0x80,0x00,0x05,0x00,0x00,0x18,0x21,0x24,0x63,0x00,0x01,
+0x00,0x64,0x10,0x2b,0x14,0x40,0xff,0xfd,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x24,0x42,0x04,0xe4,
+0x3c,0x04,0xb0,0x02,0x34,0x63,0x00,0x20,0xac,0x62,0x00,0x00,0x34,0x84,0x00,0x08,
+0x24,0x02,0x00,0x01,0xaf,0x84,0x91,0xa0,0xa3,0x82,0x91,0xb0,0xa7,0x80,0x91,0xa4,
+0xa7,0x80,0x91,0xa6,0xaf,0x80,0x91,0xa8,0xaf,0x80,0x91,0xac,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,
+0x24,0x42,0x05,0x24,0x27,0xbd,0xff,0xe0,0xac,0x62,0x00,0x00,0xaf,0xb1,0x00,0x14,
+0xaf,0xb0,0x00,0x10,0x00,0xa0,0x88,0x21,0xaf,0xbf,0x00,0x18,0x0c,0x00,0x01,0xe3,
+0x00,0x80,0x80,0x21,0x02,0x00,0x20,0x21,0x10,0x40,0x00,0x05,0x02,0x20,0x28,0x21,
+0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,
+0x0c,0x00,0x01,0xf9,0x00,0x00,0x00,0x00,0x08,0x00,0x01,0x58,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x00,0x34,0x42,0x00,0x20,0x24,0x63,0x05,0x80,
+0x27,0xbd,0xff,0xe0,0xac,0x43,0x00,0x00,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,
+0xaf,0xbf,0x00,0x18,0x8f,0x90,0x91,0xa0,0x0c,0x00,0x01,0xe3,0x00,0x80,0x88,0x21,
+0x14,0x40,0x00,0x2a,0x3c,0x02,0x00,0x80,0x16,0x20,0x00,0x02,0x34,0x42,0x02,0x01,
+0x24,0x02,0x02,0x01,0xae,0x02,0x00,0x00,0x97,0x84,0x91,0xa4,0x97,0x82,0x91,0xa6,
+0x3c,0x03,0xb0,0x02,0x00,0x83,0x20,0x21,0x24,0x42,0x00,0x04,0xa7,0x82,0x91,0xa6,
+0xa4,0x82,0x00,0x00,0x8f,0x84,0x91,0xa8,0x8f,0x82,0x91,0xa0,0x93,0x85,0x91,0x52,
+0x24,0x84,0x00,0x01,0x24,0x42,0x00,0x04,0x24,0x03,0x8f,0xff,0x3c,0x07,0xb0,0x06,
+0x3c,0x06,0xb0,0x03,0x00,0x43,0x10,0x24,0x00,0x85,0x28,0x2a,0x34,0xe7,0x80,0x18,
+0xaf,0x82,0x91,0xa0,0xaf,0x84,0x91,0xa8,0x10,0xa0,0x00,0x08,0x34,0xc6,0x01,0x08,
+0x8f,0x83,0x91,0xac,0x8f,0x84,0x91,0x6c,0x8c,0xc2,0x00,0x00,0x00,0x64,0x18,0x21,
+0x00,0x43,0x10,0x2b,0x14,0x40,0x00,0x09,0x00,0x00,0x00,0x00,0x8c,0xe2,0x00,0x00,
+0x3c,0x03,0x0f,0x00,0x3c,0x04,0x04,0x00,0x00,0x43,0x10,0x24,0x10,0x44,0x00,0x03,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x03,0x95,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x18,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x27,0xbd,0xff,0xd8,
+0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x00,0x24,0x63,0x06,0x6c,0xaf,0xb0,0x00,0x10,
+0x34,0x42,0x00,0x20,0x8f,0x90,0x91,0xa0,0xac,0x43,0x00,0x00,0xaf,0xb3,0x00,0x1c,
+0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xbf,0x00,0x20,0x00,0x80,0x88,0x21,
+0x00,0xa0,0x90,0x21,0x0c,0x00,0x01,0xe3,0x00,0xc0,0x98,0x21,0x24,0x07,0x8f,0xff,
+0x14,0x40,0x00,0x19,0x26,0x03,0x00,0x04,0x24,0x02,0x0e,0x03,0xae,0x02,0x00,0x00,
+0x00,0x67,0x80,0x24,0x26,0x02,0x00,0x04,0xae,0x11,0x00,0x00,0x00,0x47,0x80,0x24,
+0x97,0x86,0x91,0xa4,0x26,0x03,0x00,0x04,0xae,0x12,0x00,0x00,0x00,0x67,0x80,0x24,
+0xae,0x13,0x00,0x00,0x8f,0x84,0x91,0xa0,0x3c,0x02,0xb0,0x02,0x97,0x85,0x91,0xa6,
+0x00,0xc2,0x30,0x21,0x8f,0x82,0x91,0xa8,0x24,0x84,0x00,0x10,0x24,0xa5,0x00,0x10,
+0x00,0x87,0x20,0x24,0x24,0x42,0x00,0x01,0xa7,0x85,0x91,0xa6,0xaf,0x84,0x91,0xa0,
+0xaf,0x82,0x91,0xa8,0xa4,0xc5,0x00,0x00,0x8f,0xbf,0x00,0x20,0x7b,0xb2,0x00,0xfc,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,0x87,0x83,0x88,0x86,
+0x93,0x82,0x80,0x11,0x00,0x00,0x00,0x00,0x10,0x62,0x00,0x08,0x00,0x00,0x00,0x00,
+0x93,0x83,0x88,0x87,0x24,0x02,0x00,0x01,0xa3,0x82,0x80,0x10,0xa3,0x83,0x80,0x12,
+0xa3,0x83,0x80,0x11,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x93,0x82,0x80,0x12,
+0x00,0x00,0x00,0x00,0x14,0x62,0xff,0xf6,0x00,0x00,0x00,0x00,0x08,0x00,0x01,0xd5,
+0x00,0x00,0x00,0x00,0x30,0x84,0x00,0xff,0x14,0x80,0x00,0x02,0x00,0x00,0x00,0x00,
+0xa3,0x85,0x8b,0x6b,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x93,0x82,0x91,0xb0,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x11,0x24,0x06,0x00,0x01,0x8f,0x82,0x91,0xa8,
+0x3c,0x05,0xb0,0x06,0x3c,0x04,0xb0,0x03,0x34,0xa5,0x80,0x18,0x34,0x84,0x01,0x08,
+0x14,0x40,0x00,0x09,0x00,0x00,0x30,0x21,0x97,0x82,0x91,0xa4,0x8c,0x84,0x00,0x00,
+0x3c,0x03,0xb0,0x02,0x00,0x43,0x10,0x21,0xaf,0x84,0x91,0xac,0xa7,0x80,0x91,0xa6,
+0xac,0x40,0x00,0x00,0xac,0x40,0x00,0x04,0x8c,0xa2,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x00,0xc0,0x10,0x21,0x8f,0x86,0x91,0xa0,0x8f,0x82,0x91,0xa8,0x27,0xbd,0xff,0xe8,
+0xaf,0xbf,0x00,0x10,0x00,0xc0,0x40,0x21,0x14,0x40,0x00,0x0a,0x00,0x40,0x50,0x21,
+0x00,0x00,0x38,0x21,0x27,0x89,0x8b,0x40,0x24,0xe2,0x00,0x01,0x00,0x07,0x18,0x80,
+0x30,0x47,0x00,0xff,0x00,0x69,0x18,0x21,0x2c,0xe2,0x00,0x0a,0x14,0x40,0xff,0xfa,
+0xac,0x60,0x00,0x00,0x3c,0x02,0x00,0x80,0x10,0x82,0x00,0x6d,0x00,0x00,0x00,0x00,
+0x97,0x82,0x8b,0x46,0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x01,0xa7,0x82,0x8b,0x46,
+0x90,0xa3,0x00,0x15,0x97,0x82,0x8b,0x48,0x00,0x03,0x1e,0x00,0x00,0x03,0x1e,0x03,
+0x00,0x43,0x10,0x21,0xa7,0x82,0x8b,0x48,0x8c,0xa4,0x00,0x20,0x3c,0x02,0x00,0x60,
+0x3c,0x03,0x00,0x20,0x00,0x82,0x20,0x24,0x10,0x83,0x00,0x52,0x00,0x00,0x00,0x00,
+0x14,0x80,0x00,0x45,0x00,0x00,0x00,0x00,0x97,0x82,0x8b,0x4c,0x00,0x00,0x00,0x00,
+0x24,0x42,0x00,0x01,0xa7,0x82,0x8b,0x4c,0x84,0xa3,0x00,0x06,0x8f,0x82,0x8b,0x5c,
+0x00,0x00,0x00,0x00,0x00,0x43,0x10,0x21,0xaf,0x82,0x8b,0x5c,0x25,0x42,0x00,0x01,
+0x28,0x43,0x27,0x10,0xaf,0x82,0x91,0xa8,0x10,0x60,0x00,0x09,0x24,0x02,0x00,0x04,
+0x93,0x83,0x80,0x10,0x24,0x02,0x00,0x01,0x10,0x62,0x00,0x05,0x24,0x02,0x00,0x04,
+0x8f,0xbf,0x00,0x10,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,
+0x24,0x03,0x00,0x28,0xa3,0x83,0x8b,0x42,0xa3,0x82,0x8b,0x43,0x90,0xa2,0x00,0x18,
+0x93,0x83,0x8b,0x6b,0x00,0x00,0x38,0x21,0x00,0x02,0x16,0x00,0x00,0x02,0x16,0x03,
+0xa7,0x82,0x8b,0x56,0xa3,0x83,0x8b,0x64,0x27,0x89,0x8b,0x40,0x24,0x05,0x8f,0xff,
+0x00,0x07,0x10,0x80,0x00,0x49,0x10,0x21,0x8c,0x44,0x00,0x00,0x24,0xe3,0x00,0x01,
+0x30,0x67,0x00,0xff,0x25,0x02,0x00,0x04,0x2c,0xe3,0x00,0x0a,0xad,0x04,0x00,0x00,
+0x14,0x60,0xff,0xf7,0x00,0x45,0x40,0x24,0x97,0x83,0x91,0xa6,0x97,0x85,0x91,0xa4,
+0x3c,0x02,0xb0,0x02,0x24,0x63,0x00,0x28,0x00,0xa2,0x28,0x21,0x3c,0x04,0xb0,0x06,
+0xa7,0x83,0x91,0xa6,0x34,0x84,0x80,0x18,0xa4,0xa3,0x00,0x00,0x8c,0x85,0x00,0x00,
+0x24,0x02,0x8f,0xff,0x24,0xc6,0x00,0x28,0x3c,0x03,0x0f,0x00,0x00,0xc2,0x30,0x24,
+0x00,0xa3,0x28,0x24,0x3c,0x02,0x04,0x00,0xaf,0x86,0x91,0xa0,0x10,0xa2,0xff,0xd4,
+0x00,0x00,0x00,0x00,0xa3,0x80,0x80,0x10,0x0c,0x00,0x03,0x95,0x00,0x00,0x00,0x00,
+0x08,0x00,0x02,0x30,0x00,0x00,0x00,0x00,0x97,0x82,0x8b,0x4e,0x00,0x00,0x00,0x00,
+0x24,0x42,0x00,0x01,0xa7,0x82,0x8b,0x4e,0x84,0xa3,0x00,0x06,0x8f,0x82,0x8b,0x60,
+0x00,0x00,0x00,0x00,0x00,0x43,0x10,0x21,0xaf,0x82,0x8b,0x60,0x08,0x00,0x02,0x28,
+0x25,0x42,0x00,0x01,0x97,0x82,0x8b,0x4a,0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x01,
+0xa7,0x82,0x8b,0x4a,0x84,0xa3,0x00,0x06,0x8f,0x82,0x8b,0x58,0x00,0x00,0x00,0x00,
+0x00,0x43,0x10,0x21,0xaf,0x82,0x8b,0x58,0x08,0x00,0x02,0x28,0x25,0x42,0x00,0x01,
+0x97,0x82,0x8b,0x44,0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x01,0xa7,0x82,0x8b,0x44,
+0x08,0x00,0x02,0x10,0x00,0x00,0x00,0x00,0x3c,0x05,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x27,0xbd,0xff,0xc8,0x00,0x04,0x22,0x00,0x34,0xa5,0x00,0x20,0x24,0x42,0x09,0xf8,
+0x3c,0x03,0xb0,0x00,0xaf,0xb5,0x00,0x24,0xaf,0xb4,0x00,0x20,0xaf,0xb2,0x00,0x18,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x30,0x00,0x83,0x80,0x21,0xaf,0xb7,0x00,0x2c,
+0xaf,0xb6,0x00,0x28,0xaf,0xb3,0x00,0x1c,0xaf,0xb1,0x00,0x14,0xac,0xa2,0x00,0x00,
+0x8e,0x09,0x00,0x00,0x00,0x00,0x90,0x21,0x26,0x10,0x00,0x08,0x00,0x09,0xa6,0x02,
+0x12,0x80,0x00,0x13,0x00,0x00,0xa8,0x21,0x24,0x13,0x00,0x02,0x3c,0x16,0x00,0xff,
+0x3c,0x17,0xff,0x00,0x8e,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x09,0x12,0x02,
+0x24,0x42,0x00,0x02,0x31,0x25,0x00,0xff,0x10,0xb3,0x00,0x76,0x30,0x51,0x00,0xff,
+0x24,0x02,0x00,0x03,0x10,0xa2,0x00,0x18,0x00,0x00,0x00,0x00,0x02,0x51,0x10,0x21,
+0x30,0x52,0xff,0xff,0x02,0x54,0x18,0x2b,0x14,0x60,0xff,0xf2,0x02,0x11,0x80,0x21,
+0x12,0xa0,0x00,0x0a,0x3c,0x02,0xb0,0x06,0x34,0x42,0x80,0x18,0x8c,0x43,0x00,0x00,
+0x3c,0x04,0x0f,0x00,0x3c,0x02,0x04,0x00,0x00,0x64,0x18,0x24,0x10,0x62,0x00,0x03,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x03,0x95,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x30,
+0x7b,0xb6,0x01,0x7c,0x7b,0xb4,0x01,0x3c,0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x38,0x8e,0x09,0x00,0x04,0x24,0x15,0x00,0x01,
+0x8e,0x06,0x00,0x0c,0x00,0x09,0x11,0x42,0x00,0x09,0x18,0xc2,0x30,0x48,0x00,0x03,
+0x00,0x09,0x14,0x02,0x30,0x6c,0x00,0x03,0x00,0x09,0x26,0x02,0x11,0x15,0x00,0x45,
+0x30,0x43,0x00,0x0f,0x29,0x02,0x00,0x02,0x14,0x40,0x00,0x26,0x00,0x00,0x00,0x00,
+0x11,0x13,0x00,0x0f,0x00,0x00,0x38,0x21,0x00,0x07,0x22,0x02,0x30,0x84,0xff,0x00,
+0x3c,0x03,0x00,0xff,0x00,0x07,0x2e,0x02,0x00,0x07,0x12,0x00,0x00,0x43,0x10,0x24,
+0x00,0xa4,0x28,0x25,0x00,0xa2,0x28,0x25,0x00,0x07,0x1e,0x00,0x00,0xa3,0x28,0x25,
+0x0c,0x00,0x01,0x9b,0x01,0x20,0x20,0x21,0x08,0x00,0x02,0xa4,0x02,0x51,0x10,0x21,
+0x11,0x95,0x00,0x0f,0x00,0x00,0x00,0x00,0x11,0x88,0x00,0x07,0x00,0x00,0x00,0x00,
+0x00,0x04,0x10,0x80,0x27,0x83,0x91,0x50,0x00,0x43,0x10,0x21,0x8c,0x47,0x00,0x18,
+0x08,0x00,0x02,0xcb,0x00,0x07,0x22,0x02,0x00,0x04,0x10,0x40,0x27,0x83,0x91,0x58,
+0x00,0x43,0x10,0x21,0x94,0x47,0x00,0x02,0x08,0x00,0x02,0xcb,0x00,0x07,0x22,0x02,
+0x27,0x82,0x91,0x50,0x00,0x82,0x10,0x21,0x90,0x47,0x00,0x00,0x08,0x00,0x02,0xcb,
+0x00,0x07,0x22,0x02,0x15,0x00,0xff,0xdc,0x00,0x00,0x38,0x21,0x10,0x75,0x00,0x05,
+0x00,0x80,0x38,0x21,0x00,0x65,0x18,0x26,0x24,0x82,0x01,0x00,0x00,0x00,0x38,0x21,
+0x00,0x43,0x38,0x0a,0x24,0x02,0x00,0x01,0x11,0x82,0x00,0x0e,0x3c,0x02,0xb0,0x03,
+0x24,0x02,0x00,0x02,0x11,0x82,0x00,0x06,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,
+0x00,0xe2,0x10,0x21,0x8c,0x47,0x00,0x00,0x08,0x00,0x02,0xcb,0x00,0x07,0x22,0x02,
+0x3c,0x02,0xb0,0x03,0x00,0xe2,0x10,0x21,0x94,0x43,0x00,0x00,0x08,0x00,0x02,0xca,
+0x30,0x67,0xff,0xff,0x00,0xe2,0x10,0x21,0x90,0x43,0x00,0x00,0x08,0x00,0x02,0xca,
+0x30,0x67,0x00,0xff,0x30,0x62,0x00,0x03,0x00,0x02,0x12,0x00,0x11,0x95,0x00,0x07,
+0x00,0x44,0x38,0x21,0x11,0x93,0x00,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0x02,0xfc,
+0x3c,0x02,0xb0,0x0a,0x08,0x00,0x03,0x01,0x3c,0x02,0xb0,0x0a,0x08,0x00,0x03,0x05,
+0x3c,0x02,0xb0,0x0a,0x8e,0x09,0x00,0x04,0x8e,0x02,0x00,0x08,0x8e,0x03,0x00,0x0c,
+0x00,0x09,0x41,0x42,0x00,0x02,0x22,0x02,0x00,0x03,0x3a,0x02,0x30,0x84,0xff,0x00,
+0x30,0xe7,0xff,0x00,0x00,0x02,0x5e,0x02,0x00,0x02,0x32,0x00,0x00,0x03,0x56,0x02,
+0x00,0x03,0x2a,0x00,0x01,0x64,0x58,0x25,0x00,0xd6,0x30,0x24,0x01,0x47,0x50,0x25,
+0x00,0x02,0x16,0x00,0x00,0xb6,0x28,0x24,0x00,0x03,0x1e,0x00,0x01,0x66,0x58,0x25,
+0x01,0x45,0x50,0x25,0x00,0x57,0x10,0x24,0x00,0x77,0x18,0x24,0x01,0x62,0x38,0x25,
+0x01,0x43,0x30,0x25,0x00,0x09,0x10,0xc2,0x00,0x09,0x1c,0x02,0x31,0x08,0x00,0x03,
+0x30,0x4c,0x00,0x03,0x30,0x63,0x00,0x0f,0x00,0x09,0x26,0x02,0x00,0xe0,0x58,0x21,
+0x15,0x00,0x00,0x28,0x00,0xc0,0x50,0x21,0x24,0x02,0x00,0x01,0x10,0x62,0x00,0x06,
+0x00,0x80,0x28,0x21,0x24,0x02,0x00,0x03,0x14,0x62,0xff,0x69,0x02,0x51,0x10,0x21,
+0x24,0x85,0x01,0x00,0x24,0x02,0x00,0x01,0x11,0x82,0x00,0x15,0x24,0x02,0x00,0x02,
+0x11,0x82,0x00,0x0a,0x3c,0x03,0xb0,0x03,0x00,0xa3,0x18,0x21,0x8c,0x62,0x00,0x00,
+0x00,0x0a,0x20,0x27,0x01,0x6a,0x28,0x24,0x00,0x44,0x10,0x24,0x00,0x45,0x10,0x25,
+0xac,0x62,0x00,0x00,0x08,0x00,0x02,0xa4,0x02,0x51,0x10,0x21,0x00,0xa3,0x18,0x21,
+0x94,0x62,0x00,0x00,0x00,0x0a,0x20,0x27,0x01,0x6a,0x28,0x24,0x00,0x44,0x10,0x24,
+0x00,0x45,0x10,0x25,0xa4,0x62,0x00,0x00,0x08,0x00,0x02,0xa4,0x02,0x51,0x10,0x21,
+0x3c,0x03,0xb0,0x03,0x00,0xa3,0x18,0x21,0x90,0x62,0x00,0x00,0x00,0x0a,0x20,0x27,
+0x01,0x6a,0x28,0x24,0x00,0x44,0x10,0x24,0x00,0x45,0x10,0x25,0x08,0x00,0x02,0xa3,
+0xa0,0x62,0x00,0x00,0x24,0x02,0x00,0x01,0x11,0x02,0x00,0x21,0x00,0x00,0x00,0x00,
+0x15,0x13,0xff,0x42,0x00,0x00,0x00,0x00,0x11,0x82,0x00,0x17,0x00,0x00,0x00,0x00,
+0x11,0x88,0x00,0x0b,0x00,0x00,0x00,0x00,0x27,0x83,0x91,0x50,0x00,0x04,0x20,0x80,
+0x00,0x83,0x20,0x21,0x8c,0x82,0x00,0x18,0x00,0x06,0x18,0x27,0x00,0xe6,0x28,0x24,
+0x00,0x43,0x10,0x24,0x00,0x45,0x10,0x25,0x08,0x00,0x02,0xa3,0xac,0x82,0x00,0x18,
+0x27,0x83,0x91,0x58,0x00,0x04,0x20,0x40,0x00,0x83,0x20,0x21,0x94,0x82,0x00,0x02,
+0x00,0x06,0x18,0x27,0x00,0xe6,0x28,0x24,0x00,0x43,0x10,0x24,0x00,0x45,0x10,0x25,
+0x08,0x00,0x02,0xa3,0xa4,0x82,0x00,0x02,0x27,0x83,0x91,0x50,0x00,0x83,0x18,0x21,
+0x90,0x62,0x00,0x00,0x00,0x06,0x20,0x27,0x08,0x00,0x03,0x59,0x00,0xe6,0x28,0x24,
+0x30,0x62,0x00,0x07,0x00,0x02,0x12,0x00,0x11,0x88,0x00,0x0f,0x00,0x44,0x10,0x21,
+0x11,0x93,0x00,0x07,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x0a,0x00,0x43,0x18,0x21,
+0x8c,0x62,0x00,0x00,0x00,0x06,0x20,0x27,0x08,0x00,0x03,0x46,0x00,0xe6,0x28,0x24,
+0x3c,0x03,0xb0,0x0a,0x00,0x43,0x18,0x21,0x94,0x62,0x00,0x00,0x00,0x06,0x20,0x27,
+0x08,0x00,0x03,0x4f,0x00,0xe6,0x28,0x24,0x3c,0x03,0xb0,0x0a,0x08,0x00,0x03,0x7c,
+0x00,0x43,0x18,0x21,0x97,0x85,0x91,0xa4,0x3c,0x07,0xb0,0x02,0x3c,0x04,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0x00,0xa7,0x28,0x21,0x34,0x84,0x00,0x20,0x24,0x42,0x0e,0x54,
+0x24,0x03,0xff,0x80,0xac,0x82,0x00,0x00,0xa0,0xa3,0x00,0x07,0x97,0x82,0x91,0xa6,
+0x97,0x85,0x91,0xa4,0x3c,0x06,0xb0,0x06,0x30,0x42,0xff,0xf8,0x24,0x42,0x00,0x10,
+0x00,0xa2,0x10,0x21,0x30,0x42,0x0f,0xff,0x24,0x44,0x00,0x08,0x30,0x84,0x0f,0xff,
+0x00,0x05,0x28,0xc2,0x3c,0x03,0x00,0x40,0x00,0xa3,0x28,0x25,0x00,0x87,0x20,0x21,
+0x34,0xc6,0x80,0x18,0xac,0xc5,0x00,0x00,0xaf,0x84,0x91,0xa0,0xa7,0x82,0x91,0xa4,
+0xa7,0x80,0x91,0xa6,0xaf,0x80,0x91,0xa8,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x30,0xa5,0x00,0xff,0x30,0x84,0x00,0xff,0x24,0x02,0x00,0x01,0x00,0xe0,0x48,0x21,
+0x30,0xc6,0x00,0xff,0x8f,0xa7,0x00,0x10,0x10,0x82,0x00,0x07,0x00,0xa0,0x40,0x21,
+0x24,0x02,0x00,0x03,0x10,0x82,0x00,0x03,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x24,0xa8,0x01,0x00,0x3c,0x03,0xb0,0x03,0x24,0x02,0x00,0x01,
+0x00,0x07,0x20,0x27,0x01,0x27,0x28,0x24,0x10,0xc2,0x00,0x14,0x01,0x03,0x18,0x21,
+0x24,0x02,0x00,0x02,0x10,0xc2,0x00,0x09,0x00,0x07,0x50,0x27,0x3c,0x03,0xb0,0x03,
+0x01,0x03,0x18,0x21,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4a,0x10,0x24,
+0x00,0x45,0x10,0x25,0x08,0x00,0x03,0xe0,0xac,0x62,0x00,0x00,0x3c,0x03,0xb0,0x03,
+0x01,0x03,0x18,0x21,0x94,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4a,0x10,0x24,
+0x00,0x45,0x10,0x25,0x03,0xe0,0x00,0x08,0xa4,0x62,0x00,0x00,0x90,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x44,0x10,0x24,0x00,0x45,0x10,0x25,0xa0,0x62,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x30,0x84,0x00,0x07,0x00,0x04,0x22,0x00,
+0x30,0xa5,0x00,0xff,0x00,0x85,0x28,0x21,0x3c,0x02,0xb0,0x0a,0x00,0xa2,0x40,0x21,
+0x30,0xc6,0x00,0xff,0x24,0x02,0x00,0x01,0x8f,0xa4,0x00,0x10,0x10,0xc2,0x00,0x14,
+0x24,0x02,0x00,0x02,0x00,0x04,0x50,0x27,0x10,0xc2,0x00,0x09,0x00,0xe4,0x48,0x24,
+0x3c,0x03,0xb0,0x0a,0x00,0xa3,0x18,0x21,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x4a,0x10,0x24,0x00,0x49,0x10,0x25,0x03,0xe0,0x00,0x08,0xac,0x62,0x00,0x00,
+0x3c,0x03,0xb0,0x0a,0x00,0xa3,0x18,0x21,0x94,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x4a,0x10,0x24,0x00,0x49,0x10,0x25,0x03,0xe0,0x00,0x08,0xa4,0x62,0x00,0x00,
+0x91,0x02,0x00,0x00,0x00,0x04,0x18,0x27,0x00,0xe4,0x20,0x24,0x00,0x43,0x10,0x24,
+0x00,0x44,0x10,0x25,0x03,0xe0,0x00,0x08,0xa1,0x02,0x00,0x00,0x30,0xa9,0x00,0xff,
+0x27,0x83,0x91,0x50,0x30,0x85,0x00,0xff,0x24,0x02,0x00,0x01,0x00,0x07,0x50,0x27,
+0x00,0xc7,0x40,0x24,0x11,0x22,0x00,0x17,0x00,0xa3,0x18,0x21,0x00,0x05,0x20,0x40,
+0x27,0x82,0x91,0x50,0x00,0x05,0x28,0x80,0x27,0x83,0x91,0x58,0x00,0x83,0x50,0x21,
+0x00,0xa2,0x20,0x21,0x24,0x02,0x00,0x02,0x00,0x07,0x40,0x27,0x11,0x22,0x00,0x07,
+0x00,0xc7,0x28,0x24,0x8c,0x82,0x00,0x18,0x00,0x00,0x00,0x00,0x00,0x48,0x10,0x24,
+0x00,0x45,0x10,0x25,0x03,0xe0,0x00,0x08,0xac,0x82,0x00,0x18,0x95,0x42,0x00,0x02,
+0x00,0x00,0x00,0x00,0x00,0x48,0x10,0x24,0x00,0x45,0x10,0x25,0x03,0xe0,0x00,0x08,
+0xa5,0x42,0x00,0x02,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4a,0x10,0x24,
+0x00,0x48,0x10,0x25,0x03,0xe0,0x00,0x08,0xa0,0x62,0x00,0x00,0x00,0x04,0x32,0x02,
+0x30,0xc6,0xff,0x00,0x00,0x04,0x16,0x02,0x00,0x04,0x1a,0x00,0x3c,0x05,0x00,0xff,
+0x00,0x65,0x18,0x24,0x00,0x46,0x10,0x25,0x00,0x43,0x10,0x25,0x00,0x04,0x26,0x00,
+0x03,0xe0,0x00,0x08,0x00,0x44,0x10,0x25,0x3c,0x02,0xb0,0x02,0x34,0x42,0x00,0x08,
+0x3c,0x03,0xb0,0x02,0xaf,0x82,0x8b,0x78,0xaf,0x83,0x8b,0x7c,0xa7,0x80,0x8b,0x80,
+0xa7,0x80,0x8b,0x82,0xaf,0x80,0x8b,0x84,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x27,0xbd,0xff,0xd8,0xaf,0xbf,0x00,0x20,0x94,0x82,0x00,0x04,0x00,0x00,0x00,0x00,
+0x30,0x42,0xe0,0x00,0x10,0x40,0x00,0x05,0x00,0x80,0x18,0x21,0x8f,0xbf,0x00,0x20,
+0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,0x90,0x84,0x00,0x02,
+0x00,0x00,0x00,0x00,0x30,0x84,0x00,0xfc,0x0c,0x00,0x06,0xc9,0x00,0x64,0x20,0x21,
+0x08,0x00,0x04,0x47,0x00,0x00,0x00,0x00,0x27,0xbd,0xff,0xd8,0xaf,0xb2,0x00,0x18,
+0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x20,0xaf,0xb3,0x00,0x1c,
+0x8f,0x90,0x91,0xa0,0x0c,0x00,0x2b,0xd1,0x00,0x80,0x90,0x21,0x00,0x40,0x88,0x21,
+0x93,0x82,0x82,0x20,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x1b,0x24,0x02,0x00,0x01,
+0xa3,0x82,0x82,0x20,0x24,0x03,0x00,0x05,0x24,0x02,0x00,0x04,0xa3,0x83,0x8b,0x73,
+0xa3,0x82,0x8b,0x72,0xa7,0x80,0x82,0x22,0x00,0x00,0x28,0x21,0x27,0x86,0x8b,0x70,
+0x00,0x05,0x10,0x80,0x00,0x46,0x10,0x21,0x8c,0x44,0x00,0x00,0x24,0xa3,0x00,0x01,
+0x30,0x65,0xff,0xff,0xae,0x04,0x00,0x00,0x10,0xa0,0xff,0xfa,0x00,0x05,0x10,0x80,
+0x8f,0x83,0x91,0xa0,0x97,0x82,0x91,0xa6,0x24,0x05,0x8f,0xff,0x24,0x63,0x00,0x04,
+0x00,0x65,0x18,0x24,0x26,0x04,0x00,0x04,0x24,0x42,0x00,0x04,0xaf,0x83,0x91,0xa0,
+0xa7,0x82,0x91,0xa6,0x00,0x85,0x80,0x24,0x97,0x84,0x82,0x22,0x27,0x93,0x80,0x2c,
+0x02,0x40,0x28,0x21,0x00,0x93,0x20,0x21,0x0c,0x00,0x2c,0x55,0x02,0x20,0x30,0x21,
+0x97,0x87,0x82,0x22,0x24,0x02,0x00,0x52,0x00,0xf1,0x18,0x21,0xa7,0x83,0x82,0x22,
+0x82,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x82,0x00,0x06,0x00,0x60,0x38,0x21,
+0x8f,0xbf,0x00,0x20,0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x28,0x82,0x43,0x00,0x01,0x24,0x02,0x00,0x54,0x14,0x62,0xff,0xf8,
+0x24,0x02,0x00,0x4c,0x82,0x43,0x00,0x02,0x00,0x00,0x00,0x00,0x14,0x62,0xff,0xf4,
+0x00,0x00,0x00,0x00,0x30,0xe6,0xff,0xff,0x10,0xc0,0x00,0x0c,0x00,0x00,0x28,0x21,
+0x02,0x60,0x48,0x21,0x24,0x08,0x8f,0xff,0x00,0xa9,0x10,0x21,0x8c,0x44,0x00,0x00,
+0x24,0xa3,0x00,0x04,0x30,0x65,0xff,0xff,0x26,0x02,0x00,0x04,0x00,0xa6,0x18,0x2b,
+0xae,0x04,0x00,0x00,0x14,0x60,0xff,0xf8,0x00,0x48,0x80,0x24,0x97,0x83,0x91,0xa6,
+0x97,0x85,0x91,0xa4,0x3c,0x02,0xb0,0x02,0x00,0x67,0x18,0x21,0x00,0xa2,0x28,0x21,
+0x3c,0x04,0xb0,0x06,0xa7,0x83,0x91,0xa6,0x34,0x84,0x80,0x18,0xa4,0xa3,0x00,0x00,
+0x8f,0x82,0x91,0xa0,0x8c,0x86,0x00,0x00,0x30,0xe5,0xff,0xff,0x24,0x03,0x8f,0xff,
+0x00,0x45,0x10,0x21,0x3c,0x04,0x0f,0x00,0x00,0x43,0x10,0x24,0x00,0xc4,0x30,0x24,
+0x3c,0x03,0x04,0x00,0xaf,0x82,0x91,0xa0,0x10,0xc3,0xff,0xd1,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x03,0x95,0x00,0x00,0x00,0x00,0xa3,0x80,0x82,0x20,0x08,0x00,0x04,0x88,
+0x00,0x00,0x00,0x00,0x8f,0x82,0x8b,0x7c,0x97,0x83,0x8b,0x80,0x8f,0x87,0x8b,0x78,
+0x3c,0x06,0xff,0xff,0xac,0x43,0x00,0x00,0x8f,0x82,0x8b,0x7c,0x3c,0x03,0x80,0x00,
+0x24,0xe5,0x00,0x08,0xac,0x43,0x00,0x04,0x8f,0x82,0x8b,0x7c,0x34,0xc6,0x1f,0xff,
+0x3c,0x03,0x00,0x40,0x30,0x42,0x0f,0xff,0x3c,0x04,0xb0,0x06,0x00,0x02,0x10,0xc2,
+0x00,0x43,0x10,0x25,0x00,0xa6,0x28,0x24,0x34,0x84,0x80,0x18,0x27,0xbd,0xff,0xf8,
+0xac,0x82,0x00,0x00,0xaf,0x85,0x8b,0x78,0xaf,0x87,0x8b,0x7c,0xa7,0x80,0x8b,0x80,
+0xa7,0x80,0x8b,0x82,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x08,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x27,0xbd,0xff,0xe0,
+0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0x8f,0x91,0x8b,0x78,
+0x00,0x80,0x80,0x21,0xaf,0xbf,0x00,0x1c,0x0c,0x00,0x05,0x78,0x00,0xa0,0x90,0x21,
+0x97,0x82,0x8b,0x80,0x36,0x10,0x12,0x00,0x26,0x2a,0x00,0x04,0x24,0x4c,0x00,0x14,
+0x2c,0x42,0x04,0x01,0x14,0x40,0x00,0x0a,0x24,0x09,0x8f,0xff,0x8f,0x82,0x80,0x18,
+0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x01,0xaf,0x82,0x80,0x18,0x8f,0xbf,0x00,0x1c,
+0x8f,0xb2,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,
+0x8e,0x44,0x00,0x1c,0x86,0x47,0x00,0x06,0x97,0x86,0x8b,0x82,0x8c,0x82,0x00,0x08,
+0x00,0x07,0x3c,0x00,0x8f,0x85,0x8b,0x78,0x00,0x02,0x11,0x02,0x30,0x42,0x40,0x00,
+0x02,0x02,0x80,0x25,0xae,0x30,0x00,0x00,0x8c,0x82,0x00,0x04,0x82,0x43,0x00,0x15,
+0x01,0x49,0x88,0x24,0x00,0x02,0x14,0xc2,0x00,0x03,0x1a,0x00,0x00,0x02,0x14,0x00,
+0x00,0x62,0x80,0x25,0xae,0x30,0x00,0x00,0x92,0x43,0x00,0x13,0x92,0x44,0x00,0x10,
+0x96,0x50,0x00,0x1a,0x00,0x03,0x1c,0x00,0x00,0x04,0x26,0x00,0x02,0x03,0x80,0x25,
+0x26,0x22,0x00,0x04,0x00,0x49,0x88,0x24,0x02,0x04,0x80,0x25,0xae,0x30,0x00,0x00,
+0x92,0x42,0x00,0x0f,0x92,0x43,0x00,0x11,0x26,0x24,0x00,0x04,0x00,0x02,0x12,0x00,
+0x00,0x89,0x88,0x24,0x00,0x62,0x80,0x25,0x02,0x07,0x80,0x25,0x26,0x22,0x00,0x04,
+0xae,0x30,0x00,0x00,0x00,0x49,0x88,0x24,0xae,0x20,0x00,0x00,0x8f,0x82,0x80,0x14,
+0x24,0xc6,0x00,0x01,0x24,0xa5,0x00,0x14,0x30,0xc8,0xff,0xff,0x3c,0x0b,0xb0,0x03,
+0x00,0xa9,0x28,0x24,0x24,0x42,0x00,0x01,0x2d,0x08,0x00,0x0a,0xaf,0x85,0x8b,0x78,
+0xa7,0x8c,0x8b,0x80,0xaf,0x82,0x80,0x14,0xa7,0x86,0x8b,0x82,0x11,0x00,0x00,0x07,
+0x35,0x6b,0x01,0x08,0x8f,0x82,0x8b,0x84,0x8d,0x63,0x00,0x00,0x24,0x42,0x04,0x00,
+0x00,0x62,0x18,0x2b,0x14,0x60,0xff,0xc1,0x00,0x00,0x00,0x00,0x0c,0x00,0x04,0xbd,
+0x00,0x00,0x00,0x00,0x08,0x00,0x04,0xf3,0x00,0x00,0x00,0x00,0x27,0xbd,0xff,0xe8,
+0xaf,0xbf,0x00,0x10,0x0c,0x00,0x05,0x78,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x10,
+0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x27,0xbd,0xff,0xe0,
+0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x1c,
+0x8f,0x90,0x8b,0x78,0x0c,0x00,0x05,0x78,0x00,0x80,0x90,0x21,0x97,0x82,0x8b,0x80,
+0x24,0x11,0x8f,0xff,0x2c,0x42,0x04,0x01,0x14,0x40,0x00,0x06,0x26,0x03,0x00,0x04,
+0x8f,0xbf,0x00,0x1c,0x8f,0xb2,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x20,0x24,0x02,0x0e,0x03,0xae,0x02,0x00,0x00,0x00,0x71,0x80,0x24,
+0xae,0x00,0x00,0x00,0x8e,0x44,0x00,0x08,0x26,0x02,0x00,0x04,0x0c,0x00,0x05,0x86,
+0x00,0x51,0x80,0x24,0x97,0x86,0x8b,0x82,0x8f,0x83,0x8b,0x78,0xae,0x02,0x00,0x00,
+0x97,0x82,0x8b,0x80,0x24,0xc6,0x00,0x01,0x8e,0x47,0x00,0x0c,0x24,0x63,0x00,0x10,
+0x30,0xc5,0xff,0xff,0x26,0x04,0x00,0x04,0x3c,0x08,0xb0,0x03,0x00,0x71,0x18,0x24,
+0x00,0x91,0x80,0x24,0x24,0x42,0x00,0x10,0x2c,0xa5,0x00,0x0a,0x35,0x08,0x01,0x08,
+0xae,0x07,0x00,0x00,0xaf,0x83,0x8b,0x78,0xa7,0x82,0x8b,0x80,0xa7,0x86,0x8b,0x82,
+0x10,0xa0,0x00,0x07,0x00,0x00,0x00,0x00,0x8f,0x82,0x8b,0x84,0x8d,0x03,0x00,0x00,
+0x24,0x42,0x04,0x00,0x00,0x62,0x18,0x2b,0x14,0x60,0xff,0xd9,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x04,0xbd,0x00,0x00,0x00,0x00,0x08,0x00,0x05,0x4c,0x00,0x00,0x00,0x00,
+0x97,0x82,0x8b,0x82,0x3c,0x03,0xb0,0x03,0x14,0x40,0x00,0x09,0x34,0x63,0x01,0x08,
+0x8c,0x62,0x00,0x00,0x8f,0x83,0x8b,0x7c,0xa7,0x80,0x8b,0x80,0xaf,0x82,0x8b,0x84,
+0xac,0x60,0x00,0x00,0x8f,0x82,0x8b,0x7c,0x00,0x00,0x00,0x00,0xac,0x40,0x00,0x04,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x04,0x32,0x02,0x30,0xc6,0xff,0x00,
+0x00,0x04,0x16,0x02,0x00,0x04,0x1a,0x00,0x3c,0x05,0x00,0xff,0x00,0x65,0x18,0x24,
+0x00,0x46,0x10,0x25,0x00,0x43,0x10,0x25,0x00,0x04,0x26,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x44,0x10,0x25,0x80,0x82,0x00,0x00,0x90,0x83,0x00,0x00,0x10,0x40,0x00,0x0c,
+0x00,0x80,0x28,0x21,0x24,0x62,0xff,0x9f,0x30,0x42,0x00,0xff,0x2c,0x42,0x00,0x1a,
+0x10,0x40,0x00,0x02,0x24,0x63,0xff,0xe0,0xa0,0xa3,0x00,0x00,0x24,0xa5,0x00,0x01,
+0x90,0xa2,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0xf6,0x00,0x40,0x18,0x21,
+0x03,0xe0,0x00,0x08,0x00,0x80,0x10,0x21,0x80,0x82,0x00,0x00,0x90,0x83,0x00,0x00,
+0x10,0x40,0x00,0x0c,0x00,0x80,0x28,0x21,0x24,0x62,0xff,0xbf,0x30,0x42,0x00,0xff,
+0x2c,0x42,0x00,0x1a,0x10,0x40,0x00,0x02,0x24,0x63,0x00,0x20,0xa0,0xa3,0x00,0x00,
+0x24,0xa5,0x00,0x01,0x90,0xa2,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0xf6,
+0x00,0x40,0x18,0x21,0x03,0xe0,0x00,0x08,0x00,0x80,0x10,0x21,0x27,0xbd,0xff,0xe8,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,0x24,0x10,0xff,0xff,0x0c,0x00,0x29,0x11,
+0x00,0x00,0x00,0x00,0x10,0x50,0xff,0xfd,0x00,0x02,0x16,0x00,0x00,0x02,0x16,0x03,
+0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,
+0x27,0xbd,0xff,0xc8,0xaf,0xb3,0x00,0x1c,0x00,0x00,0x98,0x21,0xaf,0xb1,0x00,0x14,
+0x02,0x65,0x88,0x2b,0xaf,0xb6,0x00,0x28,0xaf,0xb5,0x00,0x24,0xaf,0xb0,0x00,0x10,
+0xaf,0xbf,0x00,0x34,0xaf,0xbe,0x00,0x30,0xaf,0xb7,0x00,0x2c,0xaf,0xb4,0x00,0x20,
+0xaf,0xb2,0x00,0x18,0x00,0xa0,0xb0,0x21,0xaf,0xa4,0x00,0x38,0x00,0xc0,0xa8,0x21,
+0x12,0x20,0x00,0x17,0x00,0x80,0x80,0x21,0x24,0x17,0xff,0xff,0x24,0x1e,0x00,0x0a,
+0x0c,0x00,0x29,0x11,0x00,0x00,0x00,0x00,0x10,0x57,0x00,0x0f,0x00,0x02,0x16,0x00,
+0x00,0x02,0x26,0x03,0x10,0x9e,0x00,0x0e,0x24,0x02,0x00,0x0d,0x10,0x82,0x00,0x34,
+0x24,0x02,0x00,0x08,0x10,0x82,0x00,0x25,0x24,0x02,0x00,0x09,0x10,0x82,0x00,0x13,
+0x00,0x00,0x90,0x21,0xa2,0x04,0x00,0x00,0x26,0x73,0x00,0x01,0x16,0xa0,0x00,0x0b,
+0x26,0x10,0x00,0x01,0x02,0x76,0x88,0x2b,0x16,0x20,0xff,0xed,0x00,0x00,0x00,0x00,
+0x7b,0xbe,0x01,0xbc,0x7b,0xb6,0x01,0x7c,0x7b,0xb4,0x01,0x3c,0x7b,0xb2,0x00,0xfc,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x38,0x0c,0x00,0x29,0x04,
+0x02,0x76,0x88,0x2b,0x08,0x00,0x05,0xe6,0x00,0x00,0x00,0x00,0x24,0x14,0x00,0x20,
+0xa2,0x14,0x00,0x00,0x26,0x52,0x00,0x01,0x24,0x04,0x00,0x20,0x26,0x73,0x00,0x01,
+0x16,0xa0,0x00,0x06,0x26,0x10,0x00,0x01,0x2a,0x42,0x00,0x08,0x10,0x40,0xff,0xea,
+0x02,0x76,0x88,0x2b,0x08,0x00,0x05,0xf5,0xa2,0x14,0x00,0x00,0x0c,0x00,0x29,0x04,
+0x00,0x00,0x00,0x00,0x08,0x00,0x05,0xfb,0x2a,0x42,0x00,0x08,0x8f,0xa2,0x00,0x38,
+0x00,0x00,0x00,0x00,0x12,0x02,0xff,0xe0,0x00,0x00,0x00,0x00,0x26,0x10,0xff,0xff,
+0x12,0xa0,0xff,0xdc,0x26,0x73,0xff,0xff,0x0c,0x00,0x29,0x04,0x24,0x04,0x00,0x08,
+0x0c,0x00,0x29,0x04,0x24,0x04,0x00,0x20,0x08,0x00,0x05,0xef,0x24,0x04,0x00,0x08,
+0x08,0x00,0x05,0xe8,0xa2,0x00,0x00,0x00,0x90,0x82,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x02,0x1e,0x00,0x10,0x60,0x00,0x16,0x00,0x00,0x30,0x21,0x24,0x07,0x00,0x20,
+0x00,0x03,0x1e,0x03,0x10,0x67,0x00,0x17,0x00,0x00,0x00,0x00,0x10,0x60,0x00,0x15,
+0x00,0x00,0x00,0x00,0x10,0x67,0x00,0x0b,0x24,0xc6,0x00,0x01,0x10,0x60,0x00,0x0a,
+0x00,0x02,0x1e,0x00,0x24,0x05,0x00,0x20,0x24,0x84,0x00,0x01,0x80,0x83,0x00,0x00,
+0x90,0x82,0x00,0x00,0x10,0x65,0x00,0x03,0x00,0x00,0x00,0x00,0x14,0x60,0xff,0xfa,
+0x00,0x00,0x00,0x00,0x00,0x02,0x1e,0x00,0x14,0x60,0xff,0xed,0x00,0x00,0x00,0x00,
+0x28,0xc3,0x00,0x08,0x24,0x02,0x00,0x07,0x00,0x43,0x30,0x0a,0x03,0xe0,0x00,0x08,
+0x00,0xc0,0x10,0x21,0x24,0x84,0x00,0x01,0x90,0x82,0x00,0x00,0x08,0x00,0x06,0x2a,
+0x00,0x02,0x1e,0x00,0x27,0xbd,0xff,0xe0,0xaf,0xb1,0x00,0x14,0x27,0x91,0x8b,0x88,
+0xaf,0xb0,0x00,0x10,0x24,0x06,0x00,0x20,0x00,0x80,0x80,0x21,0x00,0x00,0x28,0x21,
+0xaf,0xbf,0x00,0x18,0x0c,0x00,0x2c,0x4b,0x02,0x20,0x20,0x21,0x82,0x02,0x00,0x00,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x1f,0x00,0x00,0x30,0x21,0x02,0x20,0x20,0x21,
+0x24,0x09,0x00,0x20,0x24,0x08,0x00,0x20,0x24,0x07,0x00,0x08,0xac,0x90,0x00,0x00,
+0x82,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x49,0x00,0x0a,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x08,0x24,0x03,0x00,0x20,0x26,0x10,0x00,0x01,0x82,0x02,0x00,0x00,
+0x00,0x00,0x00,0x00,0x10,0x43,0x00,0x03,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0xfa,
+0x00,0x00,0x00,0x00,0xa2,0x00,0x00,0x00,0x26,0x10,0x00,0x01,0x82,0x02,0x00,0x00,
+0x92,0x03,0x00,0x00,0x10,0x48,0x00,0x0c,0x24,0x05,0x00,0x20,0x24,0xc6,0x00,0x01,
+0x10,0xc7,0x00,0x04,0x24,0x84,0x00,0x04,0x00,0x03,0x16,0x00,0x14,0x40,0xff,0xe7,
+0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x27,0x82,0x8b,0x88,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x26,0x10,0x00,0x01,0x82,0x02,0x00,0x00,
+0x92,0x03,0x00,0x00,0x10,0x45,0xff,0xfc,0x00,0x00,0x00,0x00,0x08,0x00,0x06,0x5c,
+0x24,0xc6,0x00,0x01,0x00,0x80,0x30,0x21,0x90,0x84,0x00,0x00,0x00,0x00,0x38,0x21,
+0x10,0x80,0x00,0x19,0x24,0xc6,0x00,0x01,0x24,0x82,0xff,0xd0,0x30,0x42,0x00,0xff,
+0x2c,0x43,0x00,0x0a,0x14,0x60,0x00,0x0c,0x00,0x07,0x19,0x00,0x24,0x83,0xff,0x9f,
+0x24,0x82,0xff,0xa9,0x24,0x88,0xff,0xc9,0x2c,0x63,0x00,0x06,0x24,0x84,0xff,0xbf,
+0x2c,0x84,0x00,0x06,0x14,0x60,0x00,0x03,0x30,0x42,0x00,0xff,0x10,0x80,0x00,0x0e,
+0x31,0x02,0x00,0xff,0x00,0x07,0x19,0x00,0x00,0x62,0x18,0x21,0x00,0x67,0x10,0x2b,
+0x14,0x40,0x00,0x07,0x00,0x00,0x20,0x21,0x90,0xc4,0x00,0x00,0x00,0x60,0x38,0x21,
+0x14,0x80,0xff,0xe9,0x24,0xc6,0x00,0x01,0xac,0xa7,0x00,0x00,0x24,0x04,0x00,0x01,
+0x03,0xe0,0x00,0x08,0x00,0x80,0x10,0x21,0x08,0x00,0x06,0x8c,0x00,0x00,0x20,0x21,
+0x00,0x00,0x20,0x21,0x27,0x85,0x91,0xc0,0x24,0x82,0x00,0x01,0x00,0x04,0x18,0x80,
+0x30,0x44,0x00,0xff,0x00,0x65,0x18,0x21,0x2c,0x82,0x00,0x0b,0x14,0x40,0xff,0xfa,
+0xac,0x60,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0xaf,0x84,0x8c,0x08,
+0xaf,0x85,0x8c,0x0c,0xaf,0x86,0x8c,0x10,0xaf,0x87,0x8c,0x14,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x8f,0x82,0x84,0x90,0x27,0xbd,0xff,0xe8,0xaf,0xbf,0x00,0x10,
+0x2c,0x43,0x00,0x64,0x24,0x42,0x00,0x01,0x27,0x84,0x8b,0xa8,0xaf,0x82,0x84,0x90,
+0x10,0x60,0x00,0x05,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x10,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0xaf,0x80,0x84,0x90,0x0c,0x00,0x06,0xf6,
+0x00,0x00,0x00,0x00,0x00,0x40,0x18,0x21,0x28,0x44,0x00,0x08,0x24,0x02,0x00,0x07,
+0x10,0x62,0x00,0x08,0x00,0x00,0x00,0x00,0x14,0x80,0xff,0xf3,0x24,0x02,0x00,0x08,
+0x27,0x84,0x8b,0xa8,0x14,0x62,0xff,0xf0,0x00,0x00,0x00,0x00,0x0c,0x00,0x17,0xb0,
+0x00,0x00,0x00,0x00,0x27,0x84,0x8b,0xa8,0x0c,0x00,0x07,0x54,0x00,0x00,0x00,0x00,
+0x8f,0x83,0x84,0x94,0x3c,0x04,0x80,0x01,0x00,0x60,0x28,0x21,0x24,0x63,0x00,0x01,
+0xaf,0x83,0x84,0x94,0x0c,0x00,0x17,0x9d,0x24,0x84,0x04,0x88,0x08,0x00,0x06,0xaa,
+0x00,0x00,0x00,0x00,0x27,0xbd,0xff,0xc0,0xaf,0xbf,0x00,0x38,0x8c,0x85,0x00,0x0c,
+0x8c,0x88,0x00,0x08,0x18,0xa0,0x00,0x0e,0x00,0x00,0x30,0x21,0x24,0x87,0x00,0x08,
+0x27,0xa9,0x00,0x10,0x00,0x06,0x10,0x80,0x00,0x06,0x19,0x00,0x00,0x49,0x10,0x21,
+0x14,0xc0,0x00,0x1f,0x00,0x83,0x18,0x21,0xaf,0xa7,0x00,0x10,0x24,0xc2,0x00,0x01,
+0x30,0x46,0x00,0xff,0x00,0xc5,0x18,0x2a,0x14,0x60,0xff,0xf7,0x00,0x06,0x10,0x80,
+0x29,0x02,0x00,0x0a,0x14,0x40,0x00,0x05,0x00,0x08,0x18,0x40,0x8f,0xbf,0x00,0x38,
+0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x40,0x00,0x68,0x18,0x21,
+0x27,0x82,0x83,0x8c,0x00,0x03,0x18,0xc0,0x00,0x62,0x18,0x21,0x8c,0x62,0x00,0x10,
+0x01,0x00,0x20,0x21,0x00,0x40,0xf8,0x09,0x27,0xa6,0x00,0x10,0x8f,0x83,0x84,0xa8,
+0x3c,0x04,0x80,0x01,0x00,0x60,0x28,0x21,0x24,0x63,0x00,0x01,0xaf,0x83,0x84,0xa8,
+0x0c,0x00,0x17,0x9d,0x24,0x84,0x04,0x9c,0x08,0x00,0x06,0xdf,0x00,0x00,0x00,0x00,
+0x08,0x00,0x06,0xd7,0xac,0x43,0x00,0x00,0x27,0xbd,0xff,0xe0,0xaf,0xb1,0x00,0x14,
+0xaf,0xbf,0x00,0x18,0x00,0x80,0x88,0x21,0x0c,0x00,0x17,0xd4,0xaf,0xb0,0x00,0x10,
+0x00,0x40,0x20,0x21,0x24,0x02,0xff,0xff,0x10,0x82,0x00,0x1f,0x24,0x03,0x00,0x06,
+0x8f,0x85,0x84,0xbc,0x00,0x00,0x00,0x00,0x14,0xa0,0x00,0x0a,0x24,0x02,0x00,0x08,
+0x24,0x02,0x00,0x02,0x10,0x82,0x00,0x3b,0x28,0x82,0x00,0x03,0x10,0x40,0x00,0x32,
+0x24,0x02,0x00,0x1b,0x24,0x02,0x00,0x01,0x10,0x82,0x00,0x13,0x24,0x03,0x00,0x08,
+0x24,0x02,0x00,0x08,0x10,0x82,0x00,0x23,0x24,0x02,0x00,0x0d,0x10,0x82,0x00,0x18,
+0x02,0x25,0x10,0x21,0x24,0xa3,0x00,0x01,0xa0,0x44,0x00,0x00,0xaf,0x83,0x84,0xbc,
+0x18,0x60,0x00,0x08,0x24,0x02,0x00,0x43,0x82,0x23,0x00,0x00,0x00,0x00,0x00,0x00,
+0x10,0x62,0x00,0x0a,0x00,0x00,0x00,0x00,0x30,0x84,0xff,0xff,0x0c,0x00,0x17,0xd0,
+0x00,0x00,0x00,0x00,0x24,0x03,0x00,0x06,0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,
+0x00,0x60,0x10,0x21,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x3c,0x04,0x80,0x01,
+0x0c,0x00,0x17,0xb0,0x24,0x84,0x04,0xb0,0x08,0x00,0x07,0x1e,0x24,0x03,0x00,0x06,
+0xa0,0x40,0x00,0x00,0x24,0xa5,0x00,0x01,0xaf,0x85,0x84,0xbc,0x0c,0x00,0x17,0xd0,
+0x24,0x04,0x00,0x0d,0x24,0x03,0x00,0x07,0xaf,0x80,0x84,0xbc,0x08,0x00,0x07,0x1e,
+0x00,0x00,0x00,0x00,0x18,0xa0,0xff,0xeb,0x24,0xa5,0xff,0xff,0xaf,0x85,0x84,0xbc,
+0x0c,0x00,0x17,0xd0,0x24,0x04,0x00,0x08,0x0c,0x00,0x17,0xd0,0x24,0x04,0x00,0x20,
+0x08,0x00,0x07,0x1b,0x24,0x04,0x00,0x08,0x14,0x82,0xff,0xd2,0x24,0x02,0x00,0x08,
+0x0c,0x00,0x06,0x90,0x00,0x00,0x00,0x00,0x8f,0x85,0x84,0xbc,0x08,0x00,0x07,0x0c,
+0x24,0x04,0x00,0x0d,0x0c,0x00,0x2b,0xd1,0x02,0x20,0x20,0x21,0xaf,0x82,0x84,0xbc,
+0x04,0x40,0x00,0x0d,0x00,0x00,0x80,0x21,0x02,0x30,0x10,0x21,0x90,0x44,0x00,0x00,
+0x26,0x10,0x00,0x01,0x00,0x04,0x26,0x00,0x00,0x04,0x26,0x03,0x0c,0x00,0x17,0xd0,
+0x30,0x84,0xff,0xff,0x8f,0x83,0x84,0xbc,0x00,0x00,0x00,0x00,0x00,0x70,0x18,0x2a,
+0x10,0x60,0xff,0xf6,0x02,0x30,0x10,0x21,0x08,0x00,0x07,0x2e,0x24,0x03,0x00,0x06,
+0x27,0xbd,0xff,0xe8,0xaf,0xbf,0x00,0x10,0x27,0x83,0x8b,0xe8,0x24,0x02,0x00,0x07,
+0x24,0x42,0xff,0xff,0xac,0x60,0x00,0x00,0x04,0x41,0xff,0xfd,0x24,0x63,0x00,0x04,
+0x0c,0x00,0x07,0x66,0x00,0x00,0x00,0x00,0x8f,0x84,0x8b,0xe8,0x27,0x86,0x8b,0xe8,
+0x0c,0x00,0x07,0x83,0x00,0x40,0x28,0x21,0x8f,0xbf,0x00,0x10,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x27,0xbd,0xff,0xe0,0x00,0x80,0x28,0x21,
+0x27,0x84,0x8b,0xc8,0xaf,0xb1,0x00,0x14,0xaf,0xbf,0x00,0x18,0x0c,0x00,0x2c,0x62,
+0xaf,0xb0,0x00,0x10,0x8f,0x85,0x83,0x2c,0x27,0x84,0x8b,0xc8,0x0c,0x00,0x2c,0x26,
+0x00,0x00,0x88,0x21,0x10,0x40,0x00,0x0c,0x00,0x00,0x00,0x00,0x27,0x90,0x8b,0xe8,
+0x8f,0x85,0x83,0x2c,0x00,0x00,0x20,0x21,0xae,0x02,0x00,0x00,0x0c,0x00,0x2c,0x26,
+0x26,0x31,0x00,0x01,0x26,0x10,0x00,0x04,0x10,0x40,0x00,0x03,0x2a,0x23,0x00,0x64,
+0x14,0x60,0xff,0xf7,0x00,0x00,0x00,0x00,0x02,0x20,0x10,0x21,0x8f,0xbf,0x00,0x18,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x27,0xbd,0xff,0xd0,
+0xaf,0xb6,0x00,0x28,0xaf,0xb5,0x00,0x24,0xaf,0xb4,0x00,0x20,0xaf,0xbf,0x00,0x2c,
+0xaf,0xb3,0x00,0x1c,0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,
+0x00,0xa0,0xa8,0x21,0x00,0x80,0xa0,0x21,0x00,0xc0,0xb0,0x21,0x10,0xa0,0x00,0x1d,
+0x24,0x02,0x00,0x05,0x3c,0x02,0x80,0x00,0x24,0x43,0x29,0x1c,0x8f,0x82,0x83,0x9c,
+0x00,0x00,0x00,0x00,0x10,0x43,0x00,0x1e,0x00,0x00,0x88,0x21,0x00,0x60,0x98,0x21,
+0x00,0x00,0x90,0x21,0x27,0x90,0x83,0x9c,0x8e,0x05,0xff,0xec,0x02,0x80,0x20,0x21,
+0x0c,0x00,0x2c,0x6a,0x26,0x10,0x00,0x18,0x10,0x40,0x00,0x06,0x02,0x51,0x18,0x21,
+0x8e,0x02,0x00,0x00,0x26,0x31,0x00,0x01,0x14,0x53,0xff,0xf7,0x00,0x11,0x90,0x40,
+0x02,0x51,0x18,0x21,0x27,0x82,0x83,0x8c,0x00,0x03,0x18,0xc0,0x00,0x62,0x18,0x21,
+0x8c,0x62,0x00,0x10,0x02,0x20,0x20,0x21,0x02,0xa0,0x28,0x21,0x00,0x40,0xf8,0x09,
+0x02,0xc0,0x30,0x21,0x8f,0xbf,0x00,0x2c,0x8f,0xb6,0x00,0x28,0x7b,0xb4,0x01,0x3c,
+0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x30,
+0x08,0x00,0x07,0xa4,0x00,0x00,0x90,0x21,0x27,0xbd,0xff,0xc0,0xaf,0xb5,0x00,0x34,
+0xaf,0xb3,0x00,0x2c,0xaf,0xb1,0x00,0x24,0xaf,0xbf,0x00,0x38,0xaf,0xb4,0x00,0x30,
+0xaf,0xb2,0x00,0x28,0xaf,0xb0,0x00,0x20,0x00,0xc0,0x98,0x21,0x30,0xa5,0x00,0xff,
+0xac,0xc0,0x00,0x00,0x24,0x15,0x00,0x0a,0x00,0x00,0x88,0x21,0x27,0xa8,0x00,0x10,
+0x00,0x91,0x18,0x21,0x80,0x62,0x00,0x00,0x26,0x27,0x00,0x01,0x10,0x40,0x00,0x0c,
+0x01,0x11,0x30,0x21,0x90,0x63,0x00,0x00,0x30,0xf1,0x00,0xff,0x2e,0x22,0x00,0x0a,
+0x14,0x40,0xff,0xf7,0xa0,0xc3,0x00,0x00,0x8f,0xbf,0x00,0x38,0x7b,0xb4,0x01,0xbc,
+0x7b,0xb2,0x01,0x7c,0x7b,0xb0,0x01,0x3c,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x40,
+0x24,0x02,0x00,0x01,0x10,0xa2,0x00,0x23,0x24,0x02,0x00,0x02,0x10,0xa2,0x00,0x1f,
+0x24,0x02,0x00,0x03,0x10,0xa2,0x00,0x1a,0x00,0x00,0x00,0x00,0x02,0x20,0x90,0x21,
+0x12,0x40,0xff,0xf1,0x00,0x00,0x88,0x21,0x27,0xb4,0x00,0x10,0x02,0x91,0x10,0x21,
+0x90,0x44,0x00,0x00,0x0c,0x00,0x08,0x0a,0x00,0x00,0x00,0x00,0x02,0x51,0x20,0x23,
+0x24,0x84,0xff,0xff,0x30,0x84,0x00,0xff,0x02,0xa0,0x28,0x21,0x0c,0x00,0x07,0xfb,
+0x00,0x40,0x80,0x21,0x02,0x02,0x00,0x18,0x8e,0x63,0x00,0x00,0x26,0x22,0x00,0x01,
+0x30,0x51,0x00,0xff,0x02,0x32,0x20,0x2b,0x00,0x00,0x80,0x12,0x00,0x70,0x18,0x21,
+0x14,0x80,0xff,0xee,0xae,0x63,0x00,0x00,0x08,0x00,0x07,0xce,0x00,0x00,0x00,0x00,
+0x80,0x82,0x00,0x00,0x08,0x00,0x07,0xce,0xae,0x62,0x00,0x00,0x08,0x00,0x07,0xdb,
+0x24,0x15,0x00,0x10,0x08,0x00,0x07,0xdb,0x24,0x15,0x00,0x0a,0x30,0x84,0x00,0xff,
+0x30,0xa5,0x00,0xff,0x24,0x06,0x00,0x01,0x10,0x80,0x00,0x09,0x00,0x00,0x10,0x21,
+0x00,0xc5,0x00,0x18,0x24,0x42,0x00,0x01,0x30,0x42,0x00,0xff,0x00,0x44,0x18,0x2b,
+0x00,0x00,0x30,0x12,0x00,0x00,0x00,0x00,0x14,0x60,0xff,0xfa,0x00,0xc5,0x00,0x18,
+0x03,0xe0,0x00,0x08,0x00,0xc0,0x10,0x21,0x30,0x84,0x00,0xff,0x24,0x83,0xff,0xd0,
+0x30,0x62,0x00,0xff,0x2c,0x42,0x00,0x0a,0x14,0x40,0x00,0x06,0x00,0x00,0x00,0x00,
+0x24,0x82,0xff,0xbf,0x2c,0x42,0x00,0x06,0x14,0x40,0x00,0x02,0x24,0x83,0xff,0xc9,
+0x24,0x83,0xff,0xa9,0x03,0xe0,0x00,0x08,0x00,0x60,0x10,0x21,0x27,0xbd,0xff,0xc8,
+0x24,0x02,0x00,0x01,0xaf,0xbf,0x00,0x30,0xaf,0xb5,0x00,0x2c,0xaf,0xb4,0x00,0x28,
+0xaf,0xb3,0x00,0x24,0xaf,0xb2,0x00,0x20,0xaf,0xb1,0x00,0x1c,0x10,0xa2,0x00,0x3e,
+0xaf,0xb0,0x00,0x18,0x24,0x02,0x00,0x02,0x10,0xa2,0x00,0x08,0x24,0x05,0x00,0x01,
+0x00,0x00,0x10,0x21,0x8f,0xbf,0x00,0x30,0x7b,0xb4,0x01,0x7c,0x7b,0xb2,0x01,0x3c,
+0x7b,0xb0,0x00,0xfc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x38,0x8c,0xc4,0x00,0x04,
+0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x10,0x8f,0xa2,0x00,0x10,0x00,0x00,0x00,0x00,
+0x28,0x42,0x00,0x65,0x14,0x40,0x00,0x06,0x00,0x00,0x00,0x00,0x3c,0x04,0x80,0x01,
+0x0c,0x00,0x17,0xb0,0x24,0x84,0x04,0xb4,0x08,0x00,0x08,0x25,0x24,0x02,0x00,0x01,
+0x3c,0x04,0x80,0x01,0x0c,0x00,0x17,0xb0,0x24,0x84,0x04,0xc0,0x8f,0x83,0x83,0x9c,
+0x3c,0x02,0x80,0x00,0x24,0x42,0x29,0x1c,0x10,0x62,0xff,0xe5,0x00,0x40,0x90,0x21,
+0x3c,0x13,0x80,0x01,0x27,0x95,0x83,0x88,0x3c,0x14,0x80,0x01,0x27,0x90,0x83,0x8c,
+0x00,0x00,0x88,0x21,0x8e,0x03,0x00,0x08,0x8f,0xa2,0x00,0x10,0x00,0x00,0x00,0x00,
+0x10,0x62,0x00,0x08,0x26,0x64,0x04,0xcc,0x26,0x10,0x00,0x18,0x8e,0x02,0x00,0x10,
+0x00,0x00,0x00,0x00,0x14,0x52,0xff,0xf7,0x26,0x31,0x00,0x18,0x08,0x00,0x08,0x25,
+0x00,0x00,0x10,0x21,0x0c,0x00,0x17,0xb0,0x00,0x00,0x00,0x00,0x02,0x35,0x10,0x21,
+0x8c,0x44,0x00,0x00,0x0c,0x00,0x17,0xb0,0x00,0x00,0x00,0x00,0x0c,0x00,0x17,0xb0,
+0x26,0x84,0x04,0xd0,0x8e,0x04,0x00,0x00,0x0c,0x00,0x17,0xb0,0x26,0x10,0x00,0x18,
+0x08,0x00,0x08,0x4b,0x00,0x00,0x00,0x00,0x3c,0x04,0x80,0x01,0x0c,0x00,0x17,0xb0,
+0x24,0x84,0x04,0xd4,0x3c,0x04,0x80,0x01,0x0c,0x00,0x17,0x9d,0x24,0x84,0x04,0xe4,
+0x24,0x11,0x00,0x05,0x3c,0x12,0x80,0x01,0x27,0x90,0x88,0x8e,0x86,0x05,0x00,0x00,
+0x26,0x44,0x05,0x04,0x0c,0x00,0x17,0x9d,0x26,0x31,0xff,0xff,0x06,0x21,0xff,0xfb,
+0x26,0x10,0xff,0xfe,0x08,0x00,0x08,0x25,0x00,0x00,0x10,0x21,0x27,0xbd,0xff,0xd0,
+0x28,0xa2,0x00,0x02,0xaf,0xb1,0x00,0x1c,0xaf,0xb0,0x00,0x18,0xaf,0xbf,0x00,0x2c,
+0xaf,0xb4,0x00,0x28,0xaf,0xb3,0x00,0x24,0xaf,0xb2,0x00,0x20,0x00,0xa0,0x80,0x21,
+0x14,0x40,0x00,0x51,0x00,0xc0,0x88,0x21,0x8c,0xc4,0x00,0x04,0x24,0x05,0x00,0x02,
+0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x10,0x24,0x02,0x00,0x02,0x12,0x02,0x00,0x48,
+0x24,0x05,0x00,0x01,0x8e,0x24,0x00,0x08,0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x14,
+0x8f,0xa2,0x00,0x14,0x00,0x00,0x00,0x00,0x30,0x42,0x0f,0xff,0xaf,0xa2,0x00,0x14,
+0x7b,0xa4,0x00,0xbc,0x0c,0x00,0x09,0x06,0x24,0x06,0x00,0x04,0x24,0x03,0x00,0x04,
+0x10,0x43,0x00,0x2a,0x24,0x04,0x00,0x04,0x8f,0xa2,0x00,0x10,0x3c,0x04,0x80,0x01,
+0x24,0x84,0x05,0x08,0x00,0x02,0x19,0x02,0x00,0x03,0x81,0x00,0x8f,0xa3,0x00,0x14,
+0x00,0x50,0x10,0x23,0x00,0x02,0x10,0x82,0x00,0x62,0x18,0x21,0x0c,0x00,0x17,0xb0,
+0xaf,0xa3,0x00,0x14,0x3c,0x04,0x80,0x01,0x0c,0x00,0x17,0xb0,0x24,0x84,0x05,0x30,
+0x8f,0xa2,0x00,0x14,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x17,0x00,0x00,0x88,0x21,
+0x3c,0x13,0x80,0x01,0x3c,0x12,0x80,0x01,0x3c,0x14,0x80,0x01,0x0c,0x00,0x29,0xa1,
+0x24,0x04,0x27,0x10,0x32,0x23,0x00,0x03,0x02,0x00,0x28,0x21,0x10,0x60,0x00,0x1c,
+0x26,0x64,0x05,0x5c,0x8f,0xa2,0x00,0x10,0x00,0x00,0x00,0x00,0x02,0x02,0x10,0x23,
+0x28,0x42,0xff,0xfd,0x10,0x40,0x00,0x10,0x26,0x44,0x05,0x68,0x0c,0x00,0x17,0xb0,
+0x26,0x10,0x00,0x04,0x8f,0xa2,0x00,0x14,0x26,0x31,0x00,0x01,0x02,0x22,0x10,0x2b,
+0x14,0x40,0xff,0xee,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x21,0x8f,0xbf,0x00,0x2c,
+0x8f,0xb4,0x00,0x28,0x7b,0xb2,0x01,0x3c,0x7b,0xb0,0x00,0xfc,0x00,0x80,0x10,0x21,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x30,0x8e,0x05,0x00,0x00,0x26,0x84,0x05,0x6c,
+0x0c,0x00,0x17,0x9d,0x26,0x10,0x00,0x04,0x08,0x00,0x08,0xb1,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x17,0x9d,0x00,0x00,0x00,0x00,0x08,0x00,0x08,0xa9,0x00,0x00,0x00,0x00,
+0x08,0x00,0x08,0x87,0x24,0x02,0x00,0x01,0x0c,0x00,0x0a,0x52,0x00,0x00,0x00,0x00,
+0x08,0x00,0x08,0xb7,0x24,0x04,0x00,0x04,0x27,0xbd,0xff,0xd0,0x28,0xa2,0x00,0x03,
+0xaf,0xb1,0x00,0x24,0xaf,0xb0,0x00,0x20,0xaf,0xbf,0x00,0x28,0x00,0xa0,0x88,0x21,
+0x10,0x40,0x00,0x09,0x00,0xc0,0x80,0x21,0x0c,0x00,0x0a,0x52,0x00,0x00,0x00,0x00,
+0x24,0x04,0x00,0x04,0x8f,0xbf,0x00,0x28,0x7b,0xb0,0x01,0x3c,0x00,0x80,0x10,0x21,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x30,0x8c,0xc4,0x00,0x04,0x24,0x05,0x00,0x02,
+0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x10,0x8e,0x04,0x00,0x08,0x24,0x05,0x00,0x02,
+0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x14,0x24,0x02,0x00,0x03,0x12,0x22,0x00,0x1b,
+0x24,0x05,0x00,0x01,0x8e,0x04,0x00,0x0c,0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x18,
+0x8f,0xa4,0x00,0x10,0x8f,0xa5,0x00,0x18,0x0c,0x00,0x09,0x06,0x24,0x06,0x00,0x04,
+0x24,0x03,0x00,0x04,0x10,0x43,0xff,0xe7,0x24,0x04,0x00,0x04,0x8f,0xa2,0x00,0x18,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x0b,0x00,0x00,0x28,0x21,0x8f,0xa2,0x00,0x10,
+0x8f,0xa4,0x00,0x14,0x24,0xa5,0x00,0x01,0xac,0x44,0x00,0x00,0x8f,0xa3,0x00,0x10,
+0x8f,0xa2,0x00,0x18,0x24,0x63,0x00,0x04,0x00,0xa2,0x10,0x2b,0x14,0x40,0xff,0xf7,
+0xaf,0xa3,0x00,0x10,0x08,0x00,0x08,0xd9,0x00,0x00,0x20,0x21,0x24,0x02,0x00,0x01,
+0x08,0x00,0x08,0xec,0xaf,0xa2,0x00,0x18,0x30,0xc6,0x00,0xff,0x00,0xa6,0x00,0x18,
+0x00,0x00,0x28,0x12,0x04,0x81,0x00,0x07,0x00,0x00,0x30,0x21,0x3c,0x02,0x80,0x01,
+0x00,0x85,0x18,0x21,0x34,0x42,0x7f,0xff,0x00,0x43,0x10,0x2b,0x10,0x40,0x00,0x0b,
+0x3c,0x02,0xb0,0x03,0x3c,0x02,0xaf,0xff,0x34,0x42,0xff,0xff,0x00,0x44,0x10,0x2b,
+0x10,0x40,0x00,0x17,0x3c,0x02,0xb0,0x0a,0x00,0x85,0x18,0x21,0x34,0x42,0xff,0xff,
+0x00,0x43,0x10,0x2b,0x14,0x40,0x00,0x12,0x3c,0x02,0xb0,0x03,0x34,0x42,0xff,0xff,
+0x00,0x44,0x10,0x2b,0x10,0x40,0x00,0x06,0x3c,0x02,0xb0,0x07,0x3c,0x02,0xb0,0x04,
+0x34,0x42,0xff,0xff,0x00,0x43,0x10,0x2b,0x10,0x40,0x00,0x09,0x3c,0x02,0xb0,0x07,
+0x34,0x42,0x00,0x3f,0x00,0x44,0x10,0x2b,0x10,0x40,0x00,0x06,0x3c,0x02,0xb0,0x07,
+0x34,0x42,0xff,0xff,0x00,0x43,0x10,0x2b,0x14,0x40,0x00,0x02,0x00,0x00,0x00,0x00,
+0x24,0x06,0x00,0x01,0x14,0xc0,0x00,0x11,0x24,0x02,0x00,0x04,0x3c,0x02,0xb0,0x08,
+0x34,0x42,0x0f,0xff,0x00,0x44,0x10,0x2b,0x14,0x40,0x00,0x08,0x3c,0x02,0x4f,0xf7,
+0x00,0x85,0x20,0x21,0x34,0x42,0xf0,0x00,0x00,0x82,0x20,0x21,0x34,0x03,0xef,0xff,
+0x00,0x64,0x18,0x2b,0x14,0x60,0x00,0x02,0x00,0x00,0x00,0x00,0x24,0x06,0x00,0x02,
+0x10,0xc0,0x00,0x02,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x04,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x27,0xbd,0xff,0xe0,0x24,0x02,0x00,0x02,0xaf,0xb0,0x00,0x18,
+0xaf,0xbf,0x00,0x1c,0x10,0xa2,0x00,0x23,0x00,0xc0,0x80,0x21,0x28,0xa2,0x00,0x03,
+0x10,0x40,0x00,0x0c,0x24,0x02,0x00,0x03,0x24,0x02,0x00,0x01,0x10,0xa2,0x00,0x04,
+0x00,0x00,0x18,0x21,0x0c,0x00,0x0a,0x52,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x21,
+0x8f,0xbf,0x00,0x1c,0x8f,0xb0,0x00,0x18,0x00,0x60,0x10,0x21,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x20,0x14,0xa2,0xff,0xf7,0x24,0x05,0x00,0x01,0x8c,0xc4,0x00,0x04,
+0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x10,0x8e,0x04,0x00,0x08,0x24,0x05,0x00,0x02,
+0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x14,0x8f,0xa4,0x00,0x10,0x00,0x00,0x00,0x00,
+0x2c,0x82,0x00,0x0b,0x10,0x40,0xff,0xee,0x24,0x03,0x00,0x04,0x00,0x04,0x10,0x80,
+0x8f,0xa4,0x00,0x14,0x27,0x83,0x91,0xc0,0x00,0x43,0x10,0x21,0x08,0x00,0x09,0x4f,
+0xac,0x44,0x00,0x00,0x8c,0xc4,0x00,0x04,0x24,0x05,0x00,0x01,0x0c,0x00,0x07,0xb6,
+0x27,0xa6,0x00,0x10,0x8f,0xa5,0x00,0x10,0x27,0x83,0x91,0xc0,0x3c,0x04,0x80,0x01,
+0x00,0x05,0x10,0x80,0x00,0x43,0x10,0x21,0x8c,0x46,0x00,0x00,0x0c,0x00,0x17,0x9d,
+0x24,0x84,0x05,0x74,0x08,0x00,0x09,0x50,0x00,0x00,0x18,0x21,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x8f,0x82,0x92,0x10,0x27,0xbd,0xff,0xe8,0xaf,0xbf,0x00,0x10,
+0x8c,0x45,0x00,0x24,0x3c,0x04,0x80,0x01,0x0c,0x00,0x17,0x9d,0x24,0x84,0x05,0x88,
+0x8f,0x83,0x92,0x10,0x3c,0x04,0x80,0x01,0x8c,0x65,0x00,0x28,0x0c,0x00,0x17,0x9d,
+0x24,0x84,0x05,0x9c,0x8f,0x83,0x92,0x10,0x3c,0x04,0x80,0x01,0x8c,0x65,0x00,0x2c,
+0x0c,0x00,0x17,0x9d,0x24,0x84,0x05,0xb0,0x8f,0x83,0x92,0x10,0x3c,0x04,0x80,0x01,
+0x8c,0x65,0x00,0x30,0x0c,0x00,0x17,0x9d,0x24,0x84,0x05,0xc4,0x8f,0x83,0x92,0x10,
+0x3c,0x04,0x80,0x01,0x8c,0x65,0x00,0x34,0x0c,0x00,0x17,0x9d,0x24,0x84,0x05,0xd8,
+0x8f,0x83,0x92,0x10,0x3c,0x04,0x80,0x01,0x8c,0x65,0x00,0x38,0x0c,0x00,0x17,0x9d,
+0x24,0x84,0x05,0xec,0x8f,0x83,0x92,0x10,0x3c,0x04,0x80,0x01,0x8c,0x65,0x00,0x3c,
+0x0c,0x00,0x17,0x9d,0x24,0x84,0x05,0xfc,0x8f,0xbf,0x00,0x10,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x27,0xbd,0xff,0xb8,0x28,0xa5,0x00,0x04,0xaf,0xb0,0x00,0x20,0xaf,0xbf,0x00,0x40,
+0xaf,0xb7,0x00,0x3c,0xaf,0xb6,0x00,0x38,0xaf,0xb5,0x00,0x34,0xaf,0xb4,0x00,0x30,
+0xaf,0xb3,0x00,0x2c,0xaf,0xb2,0x00,0x28,0xaf,0xb1,0x00,0x24,0x10,0xa0,0x00,0x0b,
+0x00,0xc0,0x80,0x21,0x0c,0x00,0x0a,0x52,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x04,
+0x8f,0xbf,0x00,0x40,0x7b,0xb6,0x01,0xfc,0x7b,0xb4,0x01,0xbc,0x7b,0xb2,0x01,0x7c,
+0x7b,0xb0,0x01,0x3c,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x48,0x8c,0xc4,0x00,0x04,
+0x24,0x05,0x00,0x01,0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x10,0x8e,0x04,0x00,0x08,
+0x24,0x05,0x00,0x01,0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x14,0x8e,0x04,0x00,0x0c,
+0x24,0x05,0x00,0x01,0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x18,0x8f,0xa3,0x00,0x18,
+0x00,0x00,0x00,0x00,0x10,0x60,0x00,0x3a,0x24,0x02,0x00,0x01,0x10,0x62,0x00,0x33,
+0x3c,0x04,0x80,0x01,0x97,0xb0,0x00,0x12,0x8f,0xa2,0x00,0x14,0x00,0x00,0x00,0x00,
+0x02,0x02,0x10,0x2b,0x10,0x40,0xff,0xe2,0x3c,0x15,0x80,0x01,0x3c,0x02,0x80,0x01,
+0x24,0x52,0x06,0x3c,0x3c,0x14,0xb0,0x06,0x24,0x13,0x00,0x01,0x3c,0x17,0xb0,0x08,
+0x3c,0x16,0x80,0x01,0x32,0x02,0x00,0x01,0x02,0x00,0x28,0x21,0x10,0x40,0x00,0x1f,
+0x26,0xa4,0x06,0x30,0x8f,0xa3,0x00,0x18,0x00,0x10,0x10,0xc0,0x00,0x54,0x10,0x21,
+0x10,0x60,0x00,0x14,0x02,0x40,0x20,0x21,0x00,0x10,0x10,0xc0,0x00,0x57,0x10,0x21,
+0x10,0x73,0x00,0x09,0x26,0xc4,0x06,0x44,0x8f,0xa2,0x00,0x14,0x26,0x03,0x00,0x01,
+0x30,0x70,0xff,0xff,0x02,0x02,0x10,0x2b,0x14,0x40,0xff,0xee,0x00,0x00,0x00,0x00,
+0x08,0x00,0x09,0xb4,0x00,0x00,0x00,0x00,0x8c,0x51,0x00,0x00,0x00,0x00,0x00,0x00,
+0x32,0x25,0x00,0xff,0x0c,0x00,0x17,0x9d,0x00,0x00,0x00,0x00,0x08,0x00,0x09,0xe6,
+0x00,0x00,0x00,0x00,0x8c,0x51,0x00,0x00,0x0c,0x00,0x17,0x9d,0x00,0x11,0x2c,0x02,
+0x32,0x25,0x00,0xff,0x08,0x00,0x09,0xf1,0x02,0x40,0x20,0x21,0x0c,0x00,0x17,0x9d,
+0x00,0x00,0x00,0x00,0x08,0x00,0x09,0xdd,0x00,0x00,0x00,0x00,0x24,0x84,0x06,0x10,
+0x0c,0x00,0x17,0xb0,0x00,0x00,0x00,0x00,0x08,0x00,0x09,0xcd,0x00,0x00,0x00,0x00,
+0x3c,0x04,0x80,0x01,0x08,0x00,0x0a,0x00,0x24,0x84,0x06,0x50,0x00,0xa0,0x10,0x21,
+0x27,0xbd,0xff,0xd8,0x28,0x42,0x00,0x04,0xaf,0xb0,0x00,0x20,0xaf,0xbf,0x00,0x24,
+0x00,0xc0,0x80,0x21,0x24,0x05,0x00,0x01,0x10,0x40,0x00,0x08,0x27,0xa6,0x00,0x10,
+0x0c,0x00,0x0a,0x52,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x04,0x8f,0xbf,0x00,0x24,
+0x8f,0xb0,0x00,0x20,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,0x8e,0x04,0x00,0x04,
+0x0c,0x00,0x07,0xb6,0x00,0x00,0x00,0x00,0x8e,0x04,0x00,0x08,0x24,0x05,0x00,0x01,
+0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x14,0x8e,0x04,0x00,0x0c,0x24,0x05,0x00,0x01,
+0x0c,0x00,0x07,0xb6,0x27,0xa6,0x00,0x18,0x08,0x00,0x0a,0x13,0x24,0x02,0x00,0x01,
+0x24,0x03,0x00,0x01,0x00,0x65,0x10,0x2a,0x27,0xbd,0xff,0xd8,0x00,0xa0,0x40,0x21,
+0x10,0x40,0x00,0x0b,0x00,0xc0,0x38,0x21,0x00,0x03,0x20,0x80,0x00,0x87,0x10,0x21,
+0x8c,0x45,0x00,0x00,0x24,0x63,0x00,0x01,0x30,0x63,0x00,0xff,0x8c,0xa6,0x00,0x00,
+0x00,0x9d,0x20,0x21,0x00,0x68,0x10,0x2a,0x14,0x40,0xff,0xf7,0xac,0x86,0xff,0xfc,
+0x8f,0xa3,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x60,0x00,0x0b,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0x62,0x00,0x03,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x28,0x93,0xa2,0x00,0x07,0x00,0x00,0x00,0x00,0xa3,0x82,0x87,0xec,
+0x08,0x00,0x0a,0x3b,0x00,0x00,0x00,0x00,0x93,0xa2,0x00,0x07,0x00,0x00,0x00,0x00,
+0xa3,0x82,0x91,0xb0,0x08,0x00,0x0a,0x3b,0x00,0x00,0x00,0x00,0x27,0xbd,0xff,0xe8,
+0x3c,0x04,0x80,0x01,0xaf,0xbf,0x00,0x10,0x18,0xa0,0x00,0x03,0x24,0x84,0x06,0x78,
+0x0c,0x00,0x17,0xb0,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x10,0x24,0x02,0x00,0x01,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x27,0xbd,0xff,0xe8,0xaf,0xb0,0x00,0x10,
+0x00,0x80,0x80,0x21,0x3c,0x04,0x80,0x01,0xaf,0xbf,0x00,0x14,0x0c,0x00,0x17,0xb0,
+0x24,0x84,0x06,0x8c,0x00,0x10,0x10,0x40,0x00,0x50,0x10,0x21,0x27,0x83,0x83,0x88,
+0x00,0x02,0x10,0xc0,0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x08,0x0c,0x00,0x17,0xb0,
+0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xe8,
+0x34,0x63,0x00,0x20,0x24,0x42,0x29,0x94,0x3c,0x04,0xb0,0x03,0xaf,0xbf,0x00,0x14,
+0xac,0x62,0x00,0x00,0xaf,0xb0,0x00,0x10,0x34,0x84,0x00,0x2c,0x8c,0x83,0x00,0x00,
+0xa7,0x80,0xc2,0x40,0x00,0x03,0x12,0x02,0x00,0x03,0x2d,0x02,0x30,0x42,0x0f,0xff,
+0xa3,0x83,0xc2,0x48,0xa7,0x85,0xc2,0x4c,0xa7,0x82,0xc2,0x4a,0xa7,0x80,0xc2,0x42,
+0xa7,0x80,0xc2,0x44,0xa7,0x80,0xc2,0x46,0x0c,0x00,0x0b,0xfa,0x24,0x04,0x05,0x00,
+0x3c,0x05,0x08,0x00,0x00,0x45,0x28,0x25,0x24,0x04,0x05,0x00,0x0c,0x00,0x0b,0xed,
+0x00,0x40,0x80,0x21,0x3c,0x02,0xf7,0xff,0x34,0x42,0xff,0xff,0x02,0x02,0x80,0x24,
+0x02,0x00,0x28,0x21,0x0c,0x00,0x0b,0xed,0x24,0x04,0x05,0x00,0x3c,0x02,0xb0,0x03,
+0x3c,0x03,0xb0,0x03,0x34,0x42,0x01,0x08,0x34,0x63,0x01,0x18,0x8c,0x45,0x00,0x00,
+0x8c,0x64,0x00,0x00,0x3c,0x02,0x00,0x0f,0x3c,0x03,0x00,0x4c,0x30,0x84,0x02,0x00,
+0x34,0x63,0x4b,0x40,0xaf,0x85,0xc2,0x50,0x10,0x80,0x00,0x06,0x34,0x42,0x42,0x40,
+0xaf,0x83,0xc2,0x54,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0xaf,0x82,0xc2,0x54,0x08,0x00,0x0a,0x95,0x00,0x00,0x00,0x00,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xc8,0x34,0x63,0x00,0x20,
+0x24,0x42,0x2a,0x70,0x30,0x84,0x00,0xff,0xaf,0xbf,0x00,0x30,0xaf,0xb7,0x00,0x2c,
+0xaf,0xb6,0x00,0x28,0xaf,0xb5,0x00,0x24,0xaf,0xb4,0x00,0x20,0xaf,0xb3,0x00,0x1c,
+0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0xac,0x62,0x00,0x00,
+0x10,0x80,0x00,0x1c,0x24,0x02,0x00,0x02,0x10,0x82,0x00,0x08,0x00,0x00,0x00,0x00,
+0x8f,0xbf,0x00,0x30,0x7b,0xb6,0x01,0x7c,0x7b,0xb4,0x01,0x3c,0x7b,0xb2,0x00,0xfc,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x38,0xa7,0x80,0xc2,0x40,
+0xa7,0x80,0xc2,0x42,0xa7,0x80,0xc2,0x44,0xa7,0x80,0xc2,0x46,0x0c,0x00,0x0b,0xfa,
+0x24,0x04,0x05,0x00,0x3c,0x05,0x08,0x00,0x00,0x45,0x28,0x25,0x24,0x04,0x05,0x00,
+0x0c,0x00,0x0b,0xed,0x00,0x40,0x80,0x21,0x3c,0x05,0xf7,0xff,0x34,0xa5,0xff,0xff,
+0x02,0x05,0x28,0x24,0x0c,0x00,0x0b,0xed,0x24,0x04,0x05,0x00,0x08,0x00,0x0a,0xb0,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x0b,0xfa,0x24,0x04,0x05,0xa0,0x24,0x04,0x05,0xa4,
+0x0c,0x00,0x0b,0xfa,0x00,0x02,0xbc,0x02,0x24,0x04,0x05,0xa8,0x00,0x02,0xb4,0x02,
+0x0c,0x00,0x0b,0xfa,0x30,0x55,0xff,0xff,0x00,0x40,0x80,0x21,0x97,0x84,0xc2,0x40,
+0x97,0x82,0xc2,0x42,0x97,0x83,0xc2,0x46,0x02,0xe4,0x20,0x23,0x02,0xa2,0x10,0x23,
+0x00,0x82,0x20,0x21,0x97,0x82,0xc2,0x44,0x32,0x14,0xff,0xff,0x02,0x83,0x18,0x23,
+0x02,0xc2,0x10,0x23,0x00,0x82,0x20,0x21,0x93,0x82,0xc2,0x48,0x00,0x83,0x20,0x21,
+0x30,0x84,0xff,0xff,0x00,0x82,0x10,0x2b,0x14,0x40,0x00,0xaa,0x00,0x00,0x00,0x00,
+0x97,0x82,0xc2,0x4c,0x00,0x00,0x00,0x00,0x00,0x44,0x10,0x2b,0x14,0x40,0x00,0x7f,
+0x00,0x00,0x00,0x00,0x97,0x82,0xc2,0x4a,0x00,0x00,0x00,0x00,0x00,0x44,0x10,0x2b,
+0x10,0x40,0x00,0x3a,0x00,0x00,0x00,0x00,0x0c,0x00,0x0b,0xfa,0x24,0x04,0x04,0x50,
+0x30,0x51,0x00,0x7f,0x00,0x40,0x80,0x21,0x2e,0x22,0x00,0x32,0x10,0x40,0x00,0x13,
+0x24,0x02,0x00,0x20,0x12,0x22,0x00,0x17,0x24,0x02,0xff,0x80,0x02,0x02,0x10,0x24,
+0x26,0x31,0x00,0x01,0x00,0x51,0x80,0x25,0x02,0x00,0x28,0x21,0x0c,0x00,0x0b,0xed,
+0x24,0x04,0x04,0x50,0x02,0x00,0x28,0x21,0x0c,0x00,0x0b,0xed,0x24,0x04,0x04,0x58,
+0x02,0x00,0x28,0x21,0x0c,0x00,0x0b,0xed,0x24,0x04,0x04,0x60,0x02,0x00,0x28,0x21,
+0x24,0x04,0x04,0x68,0x0c,0x00,0x0b,0xed,0x00,0x00,0x00,0x00,0xa7,0x97,0xc2,0x40,
+0xa7,0x95,0xc2,0x42,0xa7,0x96,0xc2,0x44,0xa7,0x94,0xc2,0x46,0x08,0x00,0x0a,0xb0,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x0b,0xfa,0x24,0x04,0x02,0x08,0x3c,0x04,0x00,0xc0,
+0x00,0x40,0x28,0x21,0x00,0x44,0x10,0x24,0x00,0x02,0x15,0x82,0x24,0x03,0x00,0x03,
+0x10,0x43,0x00,0x07,0x00,0x00,0x00,0x00,0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,
+0x00,0xa2,0x10,0x24,0x00,0x44,0x28,0x25,0x0c,0x00,0x0b,0xed,0x24,0x04,0x02,0x08,
+0x0c,0x00,0x0b,0xfa,0x24,0x04,0x02,0x2c,0x00,0x40,0x90,0x21,0x3c,0x02,0xff,0xff,
+0x34,0x42,0x3f,0xff,0x02,0x42,0x90,0x24,0x02,0x40,0x28,0x21,0x0c,0x00,0x0b,0xed,
+0x24,0x04,0x02,0x2c,0x08,0x00,0x0a,0xf7,0x24,0x02,0xff,0x80,0x0c,0x00,0x0b,0xfa,
+0x24,0x04,0x04,0x50,0x30,0x51,0x00,0x7f,0x24,0x02,0x00,0x20,0x16,0x22,0xff,0xdb,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x0b,0xfa,0x24,0x04,0x02,0x2c,0x34,0x52,0x40,0x00,
+0x02,0x40,0x28,0x21,0x0c,0x00,0x0b,0xed,0x24,0x04,0x02,0x2c,0x0c,0x00,0x0b,0xfa,
+0x24,0x04,0x02,0x58,0x24,0x04,0x02,0x5c,0x0c,0x00,0x0b,0xfa,0x00,0x02,0x9e,0x02,
+0x30,0x43,0x00,0xff,0x00,0x13,0x12,0x00,0x00,0x43,0x10,0x25,0x2c,0x43,0x00,0x04,
+0x14,0x60,0x00,0x1d,0x2c,0x42,0x00,0x11,0x10,0x40,0x00,0x0b,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xff,0xff,0x34,0x42,0x3f,0xff,0x02,0x42,0x90,0x24,0x02,0x40,0x28,0x21,
+0x24,0x04,0x02,0x2c,0x0c,0x00,0x0b,0xed,0x36,0x52,0x80,0x00,0x02,0x40,0x28,0x21,
+0x08,0x00,0x0b,0x05,0x24,0x04,0x02,0x2c,0x0c,0x00,0x0b,0xfa,0x24,0x04,0x02,0x08,
+0x3c,0x04,0x00,0xc0,0x00,0x40,0x28,0x21,0x00,0x44,0x10,0x24,0x00,0x02,0x15,0x82,
+0x24,0x03,0x00,0x02,0x14,0x43,0xff,0xee,0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,
+0x00,0xa2,0x10,0x24,0x00,0x44,0x28,0x25,0x0c,0x00,0x0b,0xed,0x24,0x04,0x02,0x08,
+0x08,0x00,0x0b,0x41,0x3c,0x02,0xff,0xff,0x0c,0x00,0x0b,0xfa,0x24,0x04,0x02,0x08,
+0x00,0x40,0x28,0x21,0x00,0x02,0x15,0x82,0x30,0x42,0x00,0x03,0x24,0x03,0x00,0x03,
+0x14,0x43,0xff,0xdf,0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,0x00,0xa2,0x10,0x24,
+0x3c,0x03,0x00,0x80,0x08,0x00,0x0b,0x56,0x00,0x43,0x28,0x25,0x0c,0x00,0x0b,0xfa,
+0x24,0x04,0x04,0x50,0x30,0x51,0x00,0x7f,0x00,0x40,0x80,0x21,0x2e,0x22,0x00,0x32,
+0x10,0x40,0xff,0x9a,0x24,0x02,0x00,0x20,0x12,0x22,0x00,0x04,0x24,0x02,0xff,0x80,
+0x02,0x02,0x10,0x24,0x08,0x00,0x0a,0xf9,0x26,0x31,0x00,0x02,0x0c,0x00,0x0b,0xfa,
+0x24,0x04,0x02,0x08,0x3c,0x04,0x00,0xc0,0x00,0x40,0x28,0x21,0x00,0x44,0x10,0x24,
+0x00,0x02,0x15,0x82,0x24,0x03,0x00,0x03,0x10,0x43,0x00,0x07,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,0x00,0xa2,0x10,0x24,0x00,0x44,0x28,0x25,
+0x0c,0x00,0x0b,0xed,0x24,0x04,0x02,0x08,0x0c,0x00,0x0b,0xfa,0x24,0x04,0x02,0x2c,
+0x00,0x40,0x90,0x21,0x3c,0x02,0xff,0xff,0x34,0x42,0x3f,0xff,0x02,0x42,0x90,0x24,
+0x02,0x40,0x28,0x21,0x0c,0x00,0x0b,0xed,0x24,0x04,0x02,0x2c,0x08,0x00,0x0b,0x70,
+0x24,0x02,0xff,0x80,0x0c,0x00,0x0b,0xfa,0x24,0x04,0x04,0x50,0x00,0x40,0x80,0x21,
+0x30,0x51,0x00,0x7f,0x24,0x02,0x00,0x20,0x12,0x22,0x00,0x1d,0x2e,0x22,0x00,0x21,
+0x14,0x40,0xff,0x72,0x24,0x02,0xff,0x80,0x02,0x02,0x10,0x24,0x26,0x31,0xff,0xff,
+0x00,0x51,0x80,0x25,0x24,0x04,0x04,0x50,0x0c,0x00,0x0b,0xed,0x02,0x00,0x28,0x21,
+0x24,0x04,0x04,0x58,0x0c,0x00,0x0b,0xed,0x02,0x00,0x28,0x21,0x24,0x04,0x04,0x60,
+0x0c,0x00,0x0b,0xed,0x02,0x00,0x28,0x21,0x02,0x00,0x28,0x21,0x0c,0x00,0x0b,0xed,
+0x24,0x04,0x04,0x68,0x24,0x02,0x00,0x20,0x16,0x22,0xff,0x60,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x0b,0xfa,0x24,0x04,0x02,0x2c,0x00,0x40,0x90,0x21,0x3c,0x02,0xff,0xff,
+0x34,0x42,0x3f,0xff,0x02,0x42,0x10,0x24,0x08,0x00,0x0b,0x47,0x34,0x52,0x80,0x00,
+0x0c,0x00,0x0b,0xfa,0x24,0x04,0x02,0x2c,0x34,0x52,0x40,0x00,0x02,0x40,0x28,0x21,
+0x0c,0x00,0x0b,0xed,0x24,0x04,0x02,0x2c,0x0c,0x00,0x0b,0xfa,0x24,0x04,0x02,0x58,
+0x24,0x04,0x02,0x5c,0x0c,0x00,0x0b,0xfa,0x00,0x02,0x9e,0x02,0x30,0x43,0x00,0xff,
+0x00,0x13,0x12,0x00,0x00,0x43,0x10,0x25,0x2c,0x43,0x00,0x04,0x14,0x60,0x00,0x20,
+0x2c,0x42,0x00,0x11,0x10,0x40,0x00,0x0d,0x00,0x00,0x00,0x00,0x3c,0x02,0xff,0xff,
+0x34,0x42,0x3f,0xff,0x02,0x42,0x90,0x24,0x02,0x40,0x28,0x21,0x24,0x04,0x02,0x2c,
+0x0c,0x00,0x0b,0xed,0x36,0x52,0x80,0x00,0x02,0x40,0x28,0x21,0x0c,0x00,0x0b,0xed,
+0x24,0x04,0x02,0x2c,0x08,0x00,0x0b,0x94,0x2e,0x22,0x00,0x21,0x0c,0x00,0x0b,0xfa,
+0x24,0x04,0x02,0x08,0x3c,0x04,0x00,0xc0,0x00,0x40,0x28,0x21,0x00,0x44,0x10,0x24,
+0x00,0x02,0x15,0x82,0x24,0x03,0x00,0x02,0x14,0x43,0xff,0xec,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,0x00,0xa2,0x10,0x24,0x00,0x44,0x28,0x25,
+0x0c,0x00,0x0b,0xed,0x24,0x04,0x02,0x08,0x08,0x00,0x0b,0xc4,0x3c,0x02,0xff,0xff,
+0x0c,0x00,0x0b,0xfa,0x24,0x04,0x02,0x08,0x00,0x40,0x28,0x21,0x00,0x02,0x15,0x82,
+0x30,0x42,0x00,0x03,0x24,0x03,0x00,0x03,0x14,0x43,0xff,0xdc,0x3c,0x03,0x00,0x80,
+0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,0x00,0xa2,0x10,0x24,0x08,0x00,0x0b,0xdc,
+0x00,0x43,0x28,0x25,0x30,0x83,0x00,0x03,0x00,0x04,0x20,0x40,0x00,0x83,0x20,0x23,
+0x3c,0x02,0xb0,0x0a,0x00,0x82,0x20,0x21,0xac,0x85,0x00,0x00,0x00,0x00,0x18,0x21,
+0x24,0x63,0x00,0x01,0x2c,0x62,0x00,0x0a,0x14,0x40,0xff,0xfe,0x24,0x63,0x00,0x01,
+0x03,0xe0,0x00,0x08,0x24,0x63,0xff,0xff,0x30,0x86,0x00,0x03,0x00,0x04,0x28,0x40,
+0x3c,0x03,0xb0,0x0a,0x00,0xa6,0x10,0x23,0x00,0x43,0x10,0x21,0x24,0x04,0xff,0xff,
+0xac,0x44,0x10,0x00,0x00,0x00,0x18,0x21,0x24,0x63,0x00,0x01,0x2c,0x62,0x00,0x0a,
+0x14,0x40,0xff,0xfe,0x24,0x63,0x00,0x01,0x24,0x63,0xff,0xff,0x00,0xa6,0x18,0x23,
+0x3c,0x02,0xb0,0x0a,0x00,0x62,0x18,0x21,0x8c,0x62,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x3c,0x05,0xb0,0x03,0x3c,0x02,0x80,0x00,0x24,0x42,0x30,0x34,
+0x24,0x03,0x00,0x01,0x34,0xa5,0x00,0x20,0x3c,0x06,0xb0,0x03,0xac,0xa2,0x00,0x00,
+0x34,0xc6,0x01,0x04,0xa0,0x83,0x00,0x48,0xa0,0x80,0x00,0x04,0xa0,0x80,0x00,0x05,
+0xa0,0x80,0x00,0x06,0xa0,0x80,0x00,0x07,0xa0,0x80,0x00,0x08,0xa0,0x80,0x00,0x09,
+0xa0,0x80,0x00,0x0a,0xa0,0x80,0x00,0x11,0xa0,0x80,0x00,0x13,0xa0,0x80,0x00,0x49,
+0x94,0xc2,0x00,0x00,0xac,0x80,0x00,0x00,0xac,0x80,0x00,0x24,0x00,0x02,0x14,0x00,
+0x00,0x02,0x14,0x03,0x30,0x43,0x00,0xff,0x30,0x42,0xff,0x00,0xa4,0x83,0x00,0x46,
+0xa4,0x82,0x00,0x44,0xac,0x80,0x00,0x28,0xac,0x80,0x00,0x2c,0xac,0x80,0x00,0x30,
+0xac,0x80,0x00,0x34,0xac,0x80,0x00,0x38,0xac,0x80,0x00,0x3c,0x03,0xe0,0x00,0x08,
+0xac,0x80,0x00,0x40,0x84,0x83,0x00,0x0c,0x3c,0x07,0xb0,0x03,0x34,0xe7,0x00,0x20,
+0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x83,0x96,0x44,
+0x00,0x43,0x10,0x21,0x8c,0x48,0x00,0x18,0x3c,0x02,0x80,0x00,0x24,0x42,0x30,0xc4,
+0xac,0xe2,0x00,0x00,0x8d,0x03,0x00,0x08,0x80,0x82,0x00,0x13,0x00,0x05,0x2c,0x00,
+0x00,0x03,0x1e,0x02,0x00,0x02,0x12,0x00,0x30,0x63,0x00,0x7e,0x00,0x62,0x18,0x21,
+0x00,0x65,0x18,0x21,0x3c,0x02,0xc0,0x00,0x3c,0x05,0xb0,0x05,0x34,0x42,0x04,0x00,
+0x24,0x63,0x00,0x01,0x3c,0x07,0xb0,0x05,0x3c,0x08,0xb0,0x05,0x34,0xa5,0x04,0x20,
+0xac,0xa3,0x00,0x00,0x00,0xc2,0x30,0x21,0x34,0xe7,0x04,0x24,0x35,0x08,0x02,0x28,
+0x24,0x02,0x00,0x01,0x24,0x03,0x00,0x20,0xac,0xe6,0x00,0x00,0xac,0x82,0x00,0x3c,
+0x03,0xe0,0x00,0x08,0xa1,0x03,0x00,0x00,0x27,0xbd,0xff,0xc0,0x00,0x07,0x60,0x80,
+0x27,0x82,0xba,0x40,0xaf,0xb7,0x00,0x34,0xaf,0xb5,0x00,0x2c,0xaf,0xb3,0x00,0x24,
+0xaf,0xbf,0x00,0x3c,0xaf,0xbe,0x00,0x38,0xaf,0xb6,0x00,0x30,0xaf,0xb4,0x00,0x28,
+0xaf,0xb2,0x00,0x20,0xaf,0xb1,0x00,0x1c,0xaf,0xb0,0x00,0x18,0x01,0x82,0x10,0x21,
+0x8c,0x43,0x00,0x00,0x3c,0x07,0xb0,0x03,0x3c,0x02,0x80,0x00,0x94,0x71,0x00,0x14,
+0x34,0xe7,0x00,0x20,0x24,0x42,0x31,0x58,0x3c,0x03,0xb0,0x05,0xac,0xe2,0x00,0x00,
+0x34,0x63,0x01,0x28,0x90,0x67,0x00,0x00,0x00,0x11,0xa8,0xc0,0x02,0xb1,0x18,0x21,
+0x27,0x82,0x96,0x44,0x00,0x03,0x18,0x80,0x00,0x62,0x18,0x21,0x00,0x05,0x2c,0x00,
+0x00,0x07,0x3e,0x00,0x28,0xc2,0x00,0x03,0x00,0xc0,0x98,0x21,0xaf,0xa4,0x00,0x40,
+0x00,0x05,0x6c,0x03,0x8c,0x68,0x00,0x18,0x02,0xa0,0x58,0x21,0x10,0x40,0x01,0x4f,
+0x00,0x07,0xbe,0x03,0x00,0xd7,0x10,0x07,0x30,0x57,0x00,0x01,0x01,0x71,0x10,0x21,
+0x27,0x83,0x96,0x48,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x80,0x4e,0x00,0x06,
+0x8d,0x03,0x00,0x00,0x8d,0x0f,0x00,0x04,0x8d,0x0a,0x00,0x08,0x8d,0x10,0x00,0x0c,
+0x11,0xc0,0x00,0x1c,0x00,0x00,0xa0,0x21,0x27,0x82,0xba,0x40,0x01,0x82,0x10,0x21,
+0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x90,0x83,0x00,0x16,0x00,0x00,0x00,0x00,
+0x30,0x63,0x00,0x04,0x14,0x60,0x00,0x13,0x3c,0x02,0xb0,0x09,0x34,0x42,0x01,0x46,
+0x90,0x43,0x00,0x00,0x2a,0x64,0x00,0x04,0x10,0x80,0x01,0x26,0x30,0x65,0x00,0x01,
+0x8f,0xa3,0x00,0x40,0x00,0x00,0x00,0x00,0x90,0x62,0x00,0x09,0x00,0x00,0x00,0x00,
+0x12,0x62,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x21,0x14,0xa0,0x00,0x03,
+0x00,0x00,0x38,0x21,0x12,0xe0,0x00,0x03,0x38,0xf4,0x00,0x01,0x24,0x07,0x00,0x01,
+0x38,0xf4,0x00,0x01,0x01,0x71,0x10,0x21,0x00,0x02,0x38,0x80,0x27,0x83,0x96,0x50,
+0x00,0xe3,0x48,0x21,0x91,0x25,0x00,0x00,0x00,0x0f,0x11,0xc3,0x2c,0xa3,0x00,0x04,
+0x00,0x03,0xa0,0x0b,0x12,0x80,0x00,0xc7,0x30,0x52,0x00,0x01,0x93,0x88,0xc2,0x2a,
+0x00,0x0a,0x16,0x42,0x30,0x4a,0x00,0x3f,0x2d,0x06,0x00,0x0c,0x10,0xc0,0x00,0xaf,
+0x00,0xa0,0x20,0x21,0x2c,0xa2,0x00,0x10,0x14,0x40,0x00,0x04,0x00,0x88,0x10,0x2b,
+0x30,0xa2,0x00,0x07,0x24,0x44,0x00,0x04,0x00,0x88,0x10,0x2b,0x10,0x40,0x00,0x0b,
+0x01,0x71,0x10,0x21,0x27,0x85,0xc1,0x5c,0x00,0x08,0x10,0x40,0x00,0x48,0x10,0x21,
+0x00,0x45,0x10,0x21,0x90,0x48,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x88,0x18,0x2b,
+0x14,0x60,0xff,0xfa,0x00,0x08,0x10,0x40,0x01,0x71,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x96,0x48,0x00,0x43,0x10,0x21,0x31,0xc4,0x00,0x01,0x10,0x80,0x00,0x94,
+0xa0,0x48,0x00,0x07,0x24,0x0d,0x00,0x0e,0x24,0x11,0x01,0x06,0x27,0x82,0xba,0x40,
+0x01,0x82,0x10,0x21,0x8c,0x43,0x00,0x00,0x24,0x16,0x00,0x01,0x00,0x11,0xa8,0xc0,
+0x90,0x62,0x00,0x16,0x00,0x00,0x00,0x00,0x34,0x42,0x00,0x04,0xa0,0x62,0x00,0x16,
+0x00,0x0f,0x1b,0x43,0x30,0x7e,0x00,0x01,0x00,0x0a,0x10,0x40,0x00,0x12,0x19,0xc0,
+0x00,0x5e,0x10,0x21,0x00,0x08,0x22,0x00,0x00,0x43,0x10,0x21,0x00,0x44,0x10,0x21,
+0x00,0x0d,0x1c,0x00,0x00,0x10,0x82,0x02,0x01,0x00,0x28,0x21,0x00,0x00,0x20,0x21,
+0x00,0x43,0x90,0x21,0x0c,0x00,0x01,0xdd,0x32,0x10,0x07,0xff,0x00,0x16,0x12,0x80,
+0x00,0x10,0x84,0x80,0x02,0x22,0x10,0x21,0x00,0x50,0x10,0x21,0x3c,0x03,0xc0,0x00,
+0x16,0x60,0x00,0x2b,0x00,0x43,0x80,0x21,0x3c,0x02,0xb0,0x05,0x34,0x42,0x04,0x00,
+0x3c,0x03,0xb0,0x05,0x3c,0x04,0xb0,0x05,0xac,0x52,0x00,0x00,0x34,0x63,0x04,0x04,
+0x34,0x84,0x02,0x28,0x24,0x02,0x00,0x01,0xac,0x70,0x00,0x00,0xa0,0x82,0x00,0x00,
+0x3c,0x02,0xb0,0x09,0x34,0x42,0x01,0x46,0x90,0x44,0x00,0x00,0x8f,0xa2,0x00,0x40,
+0x30,0x86,0x00,0x01,0x90,0x43,0x00,0x09,0x00,0x00,0x00,0x00,0x02,0x63,0x18,0x26,
+0x00,0x03,0x30,0x0b,0x14,0xc0,0x00,0x03,0x00,0x00,0x28,0x21,0x12,0xe0,0x00,0x03,
+0x02,0xb1,0x10,0x21,0x24,0x05,0x00,0x01,0x02,0xb1,0x10,0x21,0x27,0x83,0x96,0x48,
+0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x84,0x48,0x00,0x04,0x00,0xa0,0x30,0x21,
+0x03,0xc0,0x20,0x21,0x02,0x60,0x28,0x21,0x02,0x80,0x38,0x21,0x0c,0x00,0x00,0x70,
+0xaf,0xa8,0x00,0x10,0x7b,0xbe,0x01,0xfc,0x7b,0xb6,0x01,0xbc,0x7b,0xb4,0x01,0x7c,
+0x7b,0xb2,0x01,0x3c,0x7b,0xb0,0x00,0xfc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x40,
+0x24,0x02,0x00,0x01,0x12,0x62,0x00,0x3d,0x3c,0x02,0xb0,0x05,0x24,0x02,0x00,0x02,
+0x12,0x62,0x00,0x31,0x3c,0x02,0xb0,0x05,0x24,0x02,0x00,0x03,0x12,0x62,0x00,0x25,
+0x3c,0x02,0xb0,0x05,0x24,0x02,0x00,0x10,0x12,0x62,0x00,0x19,0x3c,0x02,0xb0,0x05,
+0x24,0x02,0x00,0x11,0x12,0x62,0x00,0x0d,0x3c,0x02,0xb0,0x05,0x24,0x02,0x00,0x12,
+0x16,0x62,0xff,0xcf,0x3c,0x02,0xb0,0x05,0x3c,0x03,0xb0,0x05,0x34,0x42,0x04,0x20,
+0x3c,0x04,0xb0,0x05,0x34,0x63,0x04,0x24,0xac,0x52,0x00,0x00,0x34,0x84,0x02,0x28,
+0xac,0x70,0x00,0x00,0x08,0x00,0x0c,0xf7,0x24,0x02,0x00,0x20,0x34,0x42,0x04,0x40,
+0x3c,0x03,0xb0,0x05,0x3c,0x04,0xb0,0x05,0xac,0x52,0x00,0x00,0x34,0x63,0x04,0x44,
+0x34,0x84,0x02,0x28,0x24,0x02,0x00,0x40,0x08,0x00,0x0c,0xf7,0xac,0x70,0x00,0x00,
+0x34,0x42,0x04,0x28,0x3c,0x03,0xb0,0x05,0x3c,0x04,0xb0,0x05,0xac,0x52,0x00,0x00,
+0x34,0x63,0x04,0x2c,0x34,0x84,0x02,0x28,0x24,0x02,0xff,0x80,0x08,0x00,0x0c,0xf7,
+0xac,0x70,0x00,0x00,0x34,0x42,0x04,0x18,0x3c,0x03,0xb0,0x05,0x3c,0x04,0xb0,0x05,
+0xac,0x52,0x00,0x00,0x34,0x63,0x04,0x1c,0x34,0x84,0x02,0x28,0x24,0x02,0x00,0x08,
+0x08,0x00,0x0c,0xf7,0xac,0x70,0x00,0x00,0x34,0x42,0x04,0x10,0x3c,0x03,0xb0,0x05,
+0x3c,0x04,0xb0,0x05,0xac,0x52,0x00,0x00,0x34,0x63,0x04,0x14,0x34,0x84,0x02,0x28,
+0x24,0x02,0x00,0x04,0x08,0x00,0x0c,0xf7,0xac,0x70,0x00,0x00,0x34,0x42,0x04,0x08,
+0x3c,0x03,0xb0,0x05,0x3c,0x04,0xb0,0x05,0xac,0x52,0x00,0x00,0x34,0x63,0x04,0x0c,
+0x34,0x84,0x02,0x28,0x24,0x02,0x00,0x02,0x08,0x00,0x0c,0xf7,0xac,0x70,0x00,0x00,
+0x24,0x0d,0x00,0x14,0x08,0x00,0x0c,0xcf,0x24,0x11,0x01,0x02,0x30,0xa2,0x00,0x07,
+0x24,0x44,0x00,0x0c,0x00,0x88,0x18,0x2b,0x10,0x60,0x00,0x0c,0x25,0x02,0x00,0x04,
+0x27,0x85,0xc1,0x5c,0x00,0x08,0x10,0x40,0x00,0x48,0x10,0x21,0x00,0x45,0x10,0x21,
+0x90,0x48,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x88,0x18,0x2b,0x14,0x60,0xff,0xfa,
+0x00,0x08,0x10,0x40,0x2d,0x06,0x00,0x0c,0x25,0x02,0x00,0x04,0x08,0x00,0x0c,0xc6,
+0x00,0x46,0x40,0x0a,0x27,0x82,0xba,0x40,0x01,0x82,0x20,0x21,0x8c,0x86,0x00,0x00,
+0x00,0x00,0x00,0x00,0x90,0xc2,0x00,0x19,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x07,
+0x00,0x00,0x00,0x00,0x27,0x82,0x96,0x60,0x00,0xe2,0x10,0x21,0x90,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0x10,0x60,0x00,0x12,0x00,0x00,0x00,0x00,0x90,0xc3,0x00,0x16,
+0x27,0x82,0x96,0x48,0x00,0xe2,0x10,0x21,0x34,0x63,0x00,0x20,0x90,0x48,0x00,0x07,
+0xa0,0xc3,0x00,0x16,0x8c,0x84,0x00,0x00,0x00,0x0a,0x16,0x42,0x30,0x4a,0x00,0x3f,
+0x90,0x83,0x00,0x16,0x24,0x0d,0x00,0x18,0x24,0x11,0x01,0x03,0x30,0x63,0x00,0xfb,
+0x24,0x16,0x00,0x01,0x24,0x15,0x08,0x18,0x08,0x00,0x0c,0xd8,0xa0,0x83,0x00,0x16,
+0x8d,0x02,0x00,0x04,0x00,0x0a,0x1c,0x42,0x30,0x42,0x00,0x10,0x14,0x40,0x00,0x15,
+0x30,0x6a,0x00,0x3f,0x81,0x22,0x00,0x05,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x11,
+0x30,0x6a,0x00,0x3e,0x27,0x83,0x96,0x58,0x00,0xe3,0x18,0x21,0x80,0x64,0x00,0x00,
+0x27,0x83,0xbb,0xb8,0x00,0x04,0x11,0x00,0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,
+0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x90,0x44,0x00,0x05,
+0x90,0x43,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x64,0x18,0x24,0x30,0x63,0x00,0x01,
+0x01,0x43,0x50,0x25,0x27,0x85,0xba,0x40,0x01,0x85,0x28,0x21,0x8c,0xa6,0x00,0x00,
+0x01,0x71,0x10,0x21,0x27,0x83,0x96,0x50,0x90,0xc4,0x00,0x16,0x00,0x02,0x10,0x80,
+0x00,0x43,0x10,0x21,0x30,0x84,0x00,0xdf,0x90,0x48,0x00,0x00,0xa0,0xc4,0x00,0x16,
+0x8c,0xa3,0x00,0x00,0x80,0xd6,0x00,0x12,0x90,0x62,0x00,0x16,0x08,0x00,0x0c,0xd7,
+0x30,0x42,0x00,0xfb,0x3c,0x03,0xb0,0x05,0x34,0x63,0x02,0x42,0x90,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x0f,0x14,0x40,0xfe,0xdc,0x00,0x00,0x00,0x00,
+0x8f,0xa3,0x00,0x40,0x00,0x00,0x00,0x00,0x90,0x62,0x00,0x09,0x00,0x00,0x00,0x00,
+0x02,0x62,0x10,0x26,0x08,0x00,0x0c,0x9f,0x00,0x02,0x28,0x0b,0x24,0x02,0x00,0x10,
+0x10,0xc2,0x00,0x08,0x24,0x02,0x00,0x11,0x10,0xc2,0xfe,0xaf,0x00,0x07,0x17,0x83,
+0x24,0x02,0x00,0x12,0x14,0xc2,0xfe,0xad,0x00,0x07,0x17,0x43,0x08,0x00,0x0c,0x7f,
+0x30,0x57,0x00,0x01,0x08,0x00,0x0c,0x7f,0x00,0x07,0xbf,0xc2,0x00,0x04,0x10,0x40,
+0x27,0x83,0x86,0xb0,0x00,0x43,0x10,0x21,0x00,0x80,0x40,0x21,0x94,0x44,0x00,0x00,
+0x2d,0x07,0x00,0x04,0x24,0xc2,0x00,0x03,0x00,0x47,0x30,0x0a,0x00,0x86,0x00,0x18,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x37,0x5c,
+0xac,0x62,0x00,0x00,0x2d,0x06,0x00,0x10,0x00,0x00,0x20,0x12,0x00,0x04,0x22,0x42,
+0x24,0x84,0x00,0x01,0x24,0x83,0x00,0xc0,0x10,0xe0,0x00,0x0b,0x24,0x82,0x00,0x60,
+0x00,0x40,0x20,0x21,0x00,0x65,0x20,0x0a,0x3c,0x03,0xb0,0x03,0x34,0x63,0x01,0x00,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,0x00,0x44,0x20,0x04,
+0x03,0xe0,0x00,0x08,0x00,0x80,0x10,0x21,0x24,0x85,0x00,0x28,0x24,0x83,0x00,0x24,
+0x31,0x02,0x00,0x08,0x14,0xc0,0xff,0xf4,0x24,0x84,0x00,0x14,0x00,0x60,0x20,0x21,
+0x08,0x00,0x0d,0xee,0x00,0xa2,0x20,0x0b,0x27,0xbd,0xff,0xe0,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0xaf,0xb0,0x00,0x10,0x24,0x42,0x37,0xf8,0x00,0x80,0x80,0x21,
+0x34,0x63,0x00,0x20,0x3c,0x04,0xb0,0x03,0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,
+0xaf,0xbf,0x00,0x1c,0x83,0xb1,0x00,0x33,0x83,0xa8,0x00,0x37,0x34,0x84,0x01,0x10,
+0xac,0x62,0x00,0x00,0x2e,0x02,0x00,0x10,0x00,0xe0,0x90,0x21,0x8c,0x87,0x00,0x00,
+0x14,0x40,0x00,0x0c,0x2e,0x02,0x00,0x0c,0x3c,0x02,0x00,0x0f,0x34,0x42,0xf0,0x00,
+0x00,0xe2,0x10,0x24,0x14,0x40,0x00,0x37,0x32,0x02,0x00,0x08,0x32,0x02,0x00,0x07,
+0x27,0x83,0x87,0x60,0x00,0x43,0x10,0x21,0x90,0x50,0x00,0x00,0x00,0x00,0x00,0x00,
+0x2e,0x02,0x00,0x0c,0x14,0x40,0x00,0x03,0x02,0x00,0x20,0x21,0x32,0x02,0x00,0x0f,
+0x24,0x44,0x00,0x0c,0x00,0x87,0x10,0x06,0x30,0x42,0x00,0x01,0x14,0x40,0x00,0x07,
+0x2c,0x82,0x00,0x0c,0x00,0x04,0x10,0x80,0x27,0x83,0xba,0x90,0x00,0x43,0x10,0x21,
+0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x2c,0x82,0x00,0x0c,0x14,0x40,0x00,0x05,
+0x00,0x05,0x10,0x40,0x00,0x46,0x10,0x21,0x00,0x02,0x11,0x00,0x00,0x82,0x10,0x21,
+0x24,0x44,0x00,0x04,0x15,0x00,0x00,0x02,0x24,0x06,0x00,0x20,0x24,0x06,0x00,0x0e,
+0x0c,0x00,0x0d,0xd7,0x00,0x00,0x00,0x00,0x00,0x40,0x30,0x21,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x01,0x00,0x90,0x43,0x00,0x00,0x2e,0x04,0x00,0x04,0x24,0x02,0x00,0x10,
+0x24,0x05,0x00,0x0a,0x00,0x44,0x28,0x0a,0x30,0x63,0x00,0x01,0x14,0x60,0x00,0x02,
+0x00,0x05,0x10,0x40,0x00,0xa0,0x10,0x21,0x30,0x45,0x00,0xff,0x00,0xc5,0x10,0x21,
+0x24,0x46,0x00,0x46,0x02,0x26,0x18,0x04,0xa6,0x43,0x00,0x00,0x8f,0xbf,0x00,0x1c,
+0x8f,0xb2,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x00,0xc0,0x10,0x21,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x20,0x10,0x40,0xff,0xcf,0x2e,0x02,0x00,0x0c,0x32,0x02,0x00,0x07,
+0x27,0x83,0x87,0x58,0x00,0x43,0x10,0x21,0x90,0x44,0x00,0x00,0x08,0x00,0x0e,0x1c,
+0x02,0x04,0x80,0x23,0x27,0xbd,0xff,0xb8,0x00,0x05,0x38,0x80,0x27,0x82,0xba,0x40,
+0xaf,0xbe,0x00,0x40,0xaf,0xb6,0x00,0x38,0xaf,0xb4,0x00,0x30,0xaf,0xbf,0x00,0x44,
+0xaf,0xb7,0x00,0x3c,0xaf,0xb5,0x00,0x34,0xaf,0xb3,0x00,0x2c,0xaf,0xb2,0x00,0x28,
+0xaf,0xb1,0x00,0x24,0xaf,0xb0,0x00,0x20,0x00,0xe2,0x38,0x21,0x8c,0xe6,0x00,0x00,
+0xaf,0xa5,0x00,0x4c,0x3c,0x02,0x80,0x00,0x3c,0x05,0xb0,0x03,0x34,0xa5,0x00,0x20,
+0x24,0x42,0x39,0x54,0x24,0x03,0x00,0x01,0xac,0xa2,0x00,0x00,0xa0,0xc3,0x00,0x12,
+0x8c,0xe5,0x00,0x00,0x94,0xc3,0x00,0x06,0x90,0xa2,0x00,0x16,0xa4,0xc3,0x00,0x14,
+0x27,0x83,0x96,0x40,0x34,0x42,0x00,0x08,0xa0,0xa2,0x00,0x16,0x8c,0xe8,0x00,0x00,
+0xaf,0xa4,0x00,0x48,0x27,0x82,0x96,0x44,0x95,0x11,0x00,0x14,0x00,0x00,0x00,0x00,
+0x00,0x11,0xa0,0xc0,0x02,0x91,0x20,0x21,0x00,0x04,0x20,0x80,0x00,0x82,0x10,0x21,
+0x8c,0x53,0x00,0x18,0x00,0x83,0x18,0x21,0x84,0x75,0x00,0x06,0x8e,0x65,0x00,0x08,
+0x8e,0x66,0x00,0x04,0x8e,0x67,0x00,0x04,0x00,0x05,0x1c,0x82,0x00,0x06,0x31,0x42,
+0x27,0x82,0x96,0x50,0x30,0x63,0x00,0x01,0x30,0xc6,0x00,0x01,0x00,0x82,0x20,0x21,
+0xa5,0x15,0x00,0x1a,0x00,0x05,0x14,0x42,0xaf,0xa3,0x00,0x18,0xaf,0xa6,0x00,0x1c,
+0x30,0xe7,0x00,0x10,0x30,0x56,0x00,0x01,0x80,0x97,0x00,0x06,0x14,0xe0,0x00,0x42,
+0x00,0x05,0xf7,0xc2,0x80,0x82,0x00,0x05,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x3f,
+0x02,0x91,0x10,0x21,0x93,0x90,0xc2,0x29,0x00,0x00,0x00,0x00,0x2e,0x02,0x00,0x0c,
+0x14,0x40,0x00,0x06,0x02,0x00,0x20,0x21,0x00,0x16,0x10,0x40,0x00,0x43,0x10,0x21,
+0x00,0x02,0x11,0x00,0x02,0x02,0x10,0x21,0x24,0x44,0x00,0x04,0x02,0x91,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x96,0x50,0x00,0x43,0x10,0x21,0x00,0x80,0x80,0x21,
+0xa0,0x44,0x00,0x03,0xa0,0x44,0x00,0x00,0x02,0x00,0x20,0x21,0x02,0xc0,0x28,0x21,
+0x0c,0x00,0x0d,0xd7,0x02,0xa0,0x30,0x21,0x02,0x91,0x18,0x21,0x00,0x03,0x88,0x80,
+0x00,0x40,0x90,0x21,0x27,0x82,0x96,0x60,0x02,0x22,0x10,0x21,0x8c,0x44,0x00,0x00,
+0x26,0xe3,0x00,0x02,0x00,0x03,0x17,0xc2,0x00,0x62,0x18,0x21,0x00,0x04,0x25,0xc2,
+0x00,0x03,0x18,0x43,0x30,0x84,0x00,0x01,0x00,0x03,0x18,0x40,0x03,0xc4,0x20,0x24,
+0x14,0x80,0x00,0x10,0x02,0x63,0x38,0x21,0x8f,0xa6,0x00,0x4c,0x8f,0xa4,0x00,0x48,
+0x27,0x82,0x96,0x48,0x02,0x22,0x10,0x21,0x02,0xa0,0x28,0x21,0xa4,0x52,0x00,0x04,
+0x0c,0x00,0x0c,0x56,0x00,0xc0,0x38,0x21,0x7b,0xbe,0x02,0x3c,0x7b,0xb6,0x01,0xfc,
+0x7b,0xb4,0x01,0xbc,0x7b,0xb2,0x01,0x7c,0x7b,0xb0,0x01,0x3c,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x48,0x8f,0xa2,0x00,0x1c,0x8f,0xa6,0x00,0x18,0x02,0x00,0x20,0x21,
+0x02,0xc0,0x28,0x21,0xaf,0xa2,0x00,0x10,0x0c,0x00,0x0d,0xfe,0xaf,0xa0,0x00,0x14,
+0x08,0x00,0x0e,0xba,0x02,0x42,0x90,0x21,0x02,0x91,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x96,0x50,0x00,0x43,0x10,0x21,0x90,0x50,0x00,0x00,0x08,0x00,0x0e,0xa6,
+0xa0,0x50,0x00,0x03,0x27,0xbd,0xff,0xb8,0xaf,0xb1,0x00,0x24,0x8f,0xb1,0x00,0x5c,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x3b,0x64,
+0xaf,0xbe,0x00,0x40,0xaf,0xb7,0x00,0x3c,0xaf,0xb6,0x00,0x38,0xaf,0xb5,0x00,0x34,
+0xaf,0xb4,0x00,0x30,0xaf,0xa5,0x00,0x4c,0x8f,0xb5,0x00,0x58,0xaf,0xbf,0x00,0x44,
+0xaf,0xb3,0x00,0x2c,0xaf,0xb2,0x00,0x28,0xaf,0xb0,0x00,0x20,0x00,0xe0,0xb0,0x21,
+0xac,0x62,0x00,0x00,0x00,0x80,0xf0,0x21,0x00,0x00,0xb8,0x21,0x16,0x20,0x00,0x2b,
+0x00,0x00,0xa0,0x21,0x27,0x85,0xba,0x40,0x00,0x07,0x10,0x80,0x00,0x45,0x10,0x21,
+0x8c,0x53,0x00,0x00,0x00,0x15,0x18,0x80,0x00,0x65,0x18,0x21,0x92,0x62,0x00,0x16,
+0x8c,0x72,0x00,0x00,0x30,0x42,0x00,0x03,0x14,0x40,0x00,0x2d,0x00,0x00,0x00,0x00,
+0x92,0x42,0x00,0x16,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x03,0x14,0x40,0x00,0x28,
+0x00,0x00,0x00,0x00,0x8c,0x82,0x00,0x34,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x18,
+0x02,0x20,0x10,0x21,0x8c,0x82,0x00,0x38,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x14,
+0x02,0x20,0x10,0x21,0x8c,0x82,0x00,0x3c,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x0f,
+0x3c,0x03,0xb0,0x09,0x3c,0x05,0xb0,0x05,0x34,0x63,0x01,0x44,0x34,0xa5,0x02,0x52,
+0x94,0x66,0x00,0x00,0x90,0xa2,0x00,0x00,0x8f,0xa3,0x00,0x4c,0x00,0x00,0x00,0x00,
+0x00,0x62,0x10,0x06,0x30,0x42,0x00,0x01,0x10,0x40,0x00,0x04,0x30,0xc6,0xff,0xff,
+0x2c,0xc2,0x00,0x41,0x10,0x40,0x00,0x09,0x24,0x05,0x00,0x14,0x02,0x20,0x10,0x21,
+0x7b,0xbe,0x02,0x3c,0x7b,0xb6,0x01,0xfc,0x7b,0xb4,0x01,0xbc,0x7b,0xb2,0x01,0x7c,
+0x7b,0xb0,0x01,0x3c,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x48,0x0c,0x00,0x0c,0x31,
+0x24,0x06,0x01,0x07,0x24,0x02,0x00,0x01,0x08,0x00,0x0f,0x1b,0xa3,0xc2,0x00,0x11,
+0x10,0xc0,0x00,0x1c,0x24,0x02,0x00,0x01,0x10,0xc2,0x00,0x17,0x00,0xc0,0x88,0x21,
+0x96,0x54,0x00,0x1a,0x02,0xa0,0xb8,0x21,0x12,0x20,0xff,0xed,0x02,0x20,0x10,0x21,
+0x27,0x83,0xba,0x40,0x00,0x17,0x10,0x80,0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,
+0x3c,0x03,0xb0,0x03,0x34,0x63,0x00,0x28,0x80,0x86,0x00,0x12,0x8c,0x62,0x00,0x00,
+0x00,0x14,0x2c,0x00,0x00,0x05,0x2c,0x03,0x00,0x46,0x10,0x21,0x8f,0xa6,0x00,0x4c,
+0x02,0xe0,0x38,0x21,0x03,0xc0,0x20,0x21,0x0c,0x00,0x0c,0x56,0xac,0x62,0x00,0x00,
+0x08,0x00,0x0f,0x1b,0xaf,0xd1,0x00,0x40,0x96,0x74,0x00,0x1a,0x08,0x00,0x0f,0x2e,
+0x02,0xc0,0xb8,0x21,0x3c,0x02,0xb0,0x03,0x34,0x42,0x01,0x08,0x8c,0x50,0x00,0x00,
+0x02,0x60,0x20,0x21,0x0c,0x00,0x23,0x25,0x02,0x00,0x28,0x21,0x30,0x42,0x00,0xff,
+0x02,0x00,0x28,0x21,0x02,0x40,0x20,0x21,0x0c,0x00,0x23,0x25,0xaf,0xa2,0x00,0x18,
+0x30,0x50,0x00,0xff,0x8f,0xa2,0x00,0x18,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0xc3,
+0x00,0x00,0x00,0x00,0x12,0x00,0x00,0x18,0x24,0x11,0x00,0x01,0x96,0x63,0x00,0x14,
+0x96,0x44,0x00,0x14,0x27,0x85,0x96,0x40,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x45,0x10,0x21,0x00,0x04,0x18,0xc0,0x8c,0x46,0x00,0x08,
+0x00,0x64,0x18,0x21,0x00,0x03,0x18,0x80,0x00,0x65,0x18,0x21,0x00,0x06,0x17,0x02,
+0x24,0x04,0x00,0xff,0x8c,0x63,0x00,0x08,0x10,0x44,0x00,0xac,0x00,0x03,0x17,0x02,
+0x10,0x44,0x00,0xab,0x3c,0x02,0x80,0x00,0x00,0x66,0x18,0x2b,0x24,0x11,0x00,0x02,
+0x24,0x02,0x00,0x01,0x00,0x43,0x88,0x0a,0x24,0x02,0x00,0x01,0x12,0x22,0x00,0x45,
+0x24,0x02,0x00,0x02,0x16,0x22,0xff,0xbc,0x00,0x00,0x00,0x00,0x96,0x49,0x00,0x14,
+0x27,0x82,0x96,0x44,0x02,0xa0,0xb8,0x21,0x00,0x09,0x50,0xc0,0x01,0x49,0x18,0x21,
+0x00,0x03,0x40,0x80,0x01,0x02,0x10,0x21,0x8c,0x43,0x00,0x18,0x00,0x00,0x00,0x00,
+0x8c,0x65,0x00,0x08,0x8c,0x62,0x00,0x0c,0x8c,0x62,0x00,0x04,0x00,0x05,0x24,0x42,
+0x00,0x05,0x1c,0x82,0x30,0x42,0x00,0x10,0x30,0x66,0x00,0x01,0x14,0x40,0x00,0x2c,
+0x30,0x87,0x00,0x01,0x27,0x83,0x96,0x58,0x01,0x03,0x18,0x21,0x80,0x64,0x00,0x00,
+0x27,0x83,0xba,0xe0,0x00,0x04,0x11,0x00,0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,
+0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x90,0x45,0x00,0x00,
+0x00,0x00,0x00,0x00,0x2c,0xa3,0x00,0x0c,0x14,0x60,0x00,0x07,0x01,0x49,0x10,0x21,
+0x00,0x07,0x10,0x40,0x00,0x46,0x10,0x21,0x00,0x02,0x11,0x00,0x00,0xa2,0x10,0x21,
+0x24,0x45,0x00,0x04,0x01,0x49,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x83,0x96,0x50,
+0x00,0x43,0x10,0x21,0xa0,0x45,0x00,0x03,0xa0,0x45,0x00,0x00,0x24,0x02,0x00,0x08,
+0x12,0x02,0x00,0x0a,0x24,0x02,0x00,0x01,0x02,0x40,0x20,0x21,0x0c,0x00,0x23,0xa1,
+0xaf,0xa2,0x00,0x10,0x30,0x54,0xff,0xff,0x92,0x42,0x00,0x16,0x00,0x00,0x00,0x00,
+0x02,0x02,0x10,0x25,0x08,0x00,0x0f,0x2e,0xa2,0x42,0x00,0x16,0x02,0x40,0x20,0x21,
+0x0c,0x00,0x23,0x52,0xaf,0xa0,0x00,0x10,0x08,0x00,0x0f,0xa6,0x30,0x54,0xff,0xff,
+0x27,0x82,0x96,0x50,0x01,0x02,0x10,0x21,0x90,0x45,0x00,0x00,0x08,0x00,0x0f,0x9f,
+0xa0,0x45,0x00,0x03,0x96,0x69,0x00,0x14,0x02,0xc0,0xb8,0x21,0x24,0x0b,0x00,0x01,
+0x00,0x09,0x10,0xc0,0x00,0x49,0x18,0x21,0x00,0x03,0x40,0x80,0x00,0x40,0x50,0x21,
+0x27,0x82,0x96,0x44,0x01,0x02,0x10,0x21,0x8c,0x43,0x00,0x18,0x00,0x00,0x00,0x00,
+0x8c,0x65,0x00,0x08,0x8c,0x62,0x00,0x0c,0x8c,0x62,0x00,0x04,0x00,0x05,0x24,0x42,
+0x00,0x05,0x1c,0x82,0x30,0x42,0x00,0x10,0x30,0x66,0x00,0x01,0x10,0x40,0x00,0x0d,
+0x30,0x87,0x00,0x01,0x27,0x82,0x96,0x58,0x01,0x02,0x10,0x21,0x80,0x43,0x00,0x00,
+0x00,0x00,0x58,0x21,0x00,0x03,0x11,0x00,0x00,0x43,0x10,0x23,0x00,0x02,0x10,0x80,
+0x00,0x43,0x10,0x23,0x00,0x02,0x10,0x80,0x27,0x83,0xbb,0xb0,0x00,0x43,0x10,0x21,
+0xa0,0x40,0x00,0x04,0x11,0x60,0x00,0x3a,0x00,0x00,0x00,0x00,0x01,0x49,0x10,0x21,
+0x00,0x02,0x20,0x80,0x27,0x85,0x96,0x50,0x00,0x85,0x10,0x21,0x80,0x43,0x00,0x05,
+0x00,0x00,0x00,0x00,0x14,0x60,0x00,0x2d,0x01,0x49,0x10,0x21,0x27,0x83,0x96,0x58,
+0x00,0x83,0x18,0x21,0x80,0x64,0x00,0x00,0x27,0x83,0xba,0xe0,0x00,0x04,0x11,0x00,
+0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,
+0x00,0x43,0x10,0x21,0x90,0x45,0x00,0x00,0x00,0x00,0x00,0x00,0x2c,0xa3,0x00,0x0c,
+0x14,0x60,0x00,0x07,0x01,0x49,0x10,0x21,0x00,0x07,0x10,0x40,0x00,0x46,0x10,0x21,
+0x00,0x02,0x11,0x00,0x00,0xa2,0x10,0x21,0x24,0x45,0x00,0x04,0x01,0x49,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x96,0x50,0x00,0x43,0x10,0x21,0xa0,0x45,0x00,0x03,
+0xa0,0x45,0x00,0x00,0x8f,0xa3,0x00,0x18,0x24,0x02,0x00,0x08,0x10,0x62,0x00,0x0b,
+0x02,0x60,0x20,0x21,0x24,0x02,0x00,0x01,0x0c,0x00,0x23,0xa1,0xaf,0xa2,0x00,0x10,
+0x8f,0xa3,0x00,0x18,0x30,0x54,0xff,0xff,0x92,0x62,0x00,0x16,0x00,0x00,0x00,0x00,
+0x00,0x62,0x10,0x25,0x08,0x00,0x0f,0x2e,0xa2,0x62,0x00,0x16,0x0c,0x00,0x23,0x52,
+0xaf,0xa0,0x00,0x10,0x08,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x10,0x80,
+0x00,0x45,0x10,0x21,0x90,0x45,0x00,0x00,0x08,0x00,0x0f,0xf9,0xa0,0x45,0x00,0x03,
+0x27,0x85,0x96,0x50,0x08,0x00,0x10,0x0b,0x01,0x49,0x10,0x21,0x3c,0x02,0x80,0x00,
+0x00,0x62,0x18,0x26,0x08,0x00,0x0f,0x6a,0x00,0xc2,0x30,0x26,0x12,0x00,0xff,0x57,
+0x24,0x02,0x00,0x01,0x08,0x00,0x0f,0x6f,0x24,0x11,0x00,0x02,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xd0,0x24,0x42,0x40,0x6c,0x34,0x63,0x00,0x20,
+0x3c,0x05,0xb0,0x05,0xaf,0xb3,0x00,0x24,0xaf,0xb2,0x00,0x20,0xaf,0xb1,0x00,0x1c,
+0xaf,0xbf,0x00,0x28,0xaf,0xb0,0x00,0x18,0xac,0x62,0x00,0x00,0x34,0xa5,0x02,0x42,
+0x90,0xa2,0x00,0x00,0x00,0x80,0x90,0x21,0x24,0x11,0x00,0x10,0x30,0x53,0x00,0xff,
+0x24,0x02,0x00,0x10,0x12,0x22,0x00,0xcf,0x00,0x00,0x18,0x21,0x24,0x02,0x00,0x11,
+0x12,0x22,0x00,0xc1,0x24,0x02,0x00,0x12,0x12,0x22,0x00,0xb4,0x00,0x00,0x00,0x00,
+0x14,0x60,0x00,0xad,0xae,0x43,0x00,0x40,0x3c,0x02,0xb0,0x05,0x34,0x42,0x02,0x2c,
+0x8c,0x44,0x00,0x00,0x3c,0x03,0x00,0x02,0x34,0x63,0x00,0xff,0x00,0x83,0x80,0x24,
+0x00,0x10,0x14,0x43,0x10,0x40,0x00,0x05,0x00,0x00,0x00,0x00,0x8e,0x42,0x00,0x34,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x92,0x00,0x00,0x00,0x00,0x93,0x83,0x91,0x51,
+0x00,0x00,0x00,0x00,0x30,0x62,0x00,0x02,0x10,0x40,0x00,0x04,0x32,0x10,0x00,0xff,
+0x00,0x10,0x11,0xc3,0x14,0x40,0x00,0x86,0x00,0x00,0x00,0x00,0x16,0x00,0x00,0x15,
+0x02,0x00,0x10,0x21,0x26,0x22,0x00,0x01,0x30,0x51,0x00,0xff,0x2e,0x23,0x00,0x13,
+0x14,0x60,0xff,0xdb,0x24,0x03,0x00,0x02,0x12,0x63,0x00,0x73,0x24,0x02,0x00,0x05,
+0x2a,0x62,0x00,0x03,0x10,0x40,0x00,0x58,0x24,0x02,0x00,0x04,0x24,0x02,0x00,0x01,
+0x12,0x62,0x00,0x4b,0x02,0x40,0x20,0x21,0x3c,0x02,0xb0,0x05,0x34,0x42,0x02,0x2c,
+0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x70,0x00,0xff,0x12,0x00,0x00,0x06,
+0x02,0x00,0x10,0x21,0x8f,0xbf,0x00,0x28,0x7b,0xb2,0x01,0x3c,0x7b,0xb0,0x00,0xfc,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x30,0x92,0x46,0x00,0x04,0x8e,0x43,0x00,0x24,
+0x24,0x02,0x00,0x07,0x02,0x40,0x20,0x21,0x00,0x00,0x28,0x21,0x24,0x07,0x00,0x06,
+0xaf,0xa2,0x00,0x10,0x0c,0x00,0x0e,0xd9,0xaf,0xa3,0x00,0x14,0xae,0x42,0x00,0x24,
+0x3c,0x02,0xb0,0x05,0x8c,0x42,0x02,0x2c,0x00,0x00,0x00,0x00,0x30,0x50,0x00,0xff,
+0x16,0x00,0xff,0xec,0x02,0x00,0x10,0x21,0x92,0x46,0x00,0x05,0x8e,0x43,0x00,0x28,
+0x24,0x02,0x00,0x05,0x02,0x40,0x20,0x21,0x24,0x05,0x00,0x01,0x24,0x07,0x00,0x04,
+0xaf,0xa2,0x00,0x10,0x0c,0x00,0x0e,0xd9,0xaf,0xa3,0x00,0x14,0xae,0x42,0x00,0x28,
+0x3c,0x02,0xb0,0x05,0x8c,0x42,0x02,0x2c,0x00,0x00,0x00,0x00,0x30,0x50,0x00,0xff,
+0x16,0x00,0xff,0xdc,0x02,0x00,0x10,0x21,0x92,0x46,0x00,0x06,0x8e,0x43,0x00,0x2c,
+0x24,0x02,0x00,0x03,0x02,0x40,0x20,0x21,0x24,0x05,0x00,0x02,0x00,0x00,0x38,0x21,
+0xaf,0xa2,0x00,0x10,0x0c,0x00,0x0e,0xd9,0xaf,0xa3,0x00,0x14,0xae,0x42,0x00,0x2c,
+0x3c,0x02,0xb0,0x05,0x8c,0x42,0x02,0x2c,0x00,0x00,0x00,0x00,0x30,0x50,0x00,0xff,
+0x16,0x00,0xff,0xcc,0x02,0x00,0x10,0x21,0x92,0x46,0x00,0x07,0x8e,0x43,0x00,0x30,
+0x24,0x02,0x00,0x02,0x02,0x40,0x20,0x21,0x24,0x05,0x00,0x03,0x24,0x07,0x00,0x01,
+0xaf,0xa2,0x00,0x10,0x0c,0x00,0x0e,0xd9,0xaf,0xa3,0x00,0x14,0xae,0x42,0x00,0x30,
+0x3c,0x02,0xb0,0x05,0x8c,0x42,0x02,0x2c,0x08,0x00,0x10,0x61,0x30,0x42,0x00,0xff,
+0x92,0x46,0x00,0x04,0x8e,0x43,0x00,0x24,0x24,0x02,0x00,0x07,0x00,0x00,0x28,0x21,
+0x24,0x07,0x00,0x06,0xaf,0xa2,0x00,0x10,0x0c,0x00,0x0e,0xd9,0xaf,0xa3,0x00,0x14,
+0x08,0x00,0x10,0x5a,0xae,0x42,0x00,0x24,0x12,0x62,0x00,0x0d,0x24,0x02,0x00,0x03,
+0x24,0x02,0x00,0x08,0x16,0x62,0xff,0xa8,0x02,0x40,0x20,0x21,0x92,0x46,0x00,0x07,
+0x8e,0x42,0x00,0x30,0x24,0x05,0x00,0x03,0x24,0x07,0x00,0x01,0xaf,0xa3,0x00,0x10,
+0x0c,0x00,0x0e,0xd9,0xaf,0xa2,0x00,0x14,0x08,0x00,0x10,0x5a,0xae,0x42,0x00,0x30,
+0x92,0x46,0x00,0x06,0x8e,0x43,0x00,0x2c,0x02,0x40,0x20,0x21,0x24,0x05,0x00,0x02,
+0x00,0x00,0x38,0x21,0xaf,0xa2,0x00,0x10,0x0c,0x00,0x0e,0xd9,0xaf,0xa3,0x00,0x14,
+0x08,0x00,0x10,0x5a,0xae,0x42,0x00,0x2c,0x92,0x46,0x00,0x05,0x8e,0x43,0x00,0x28,
+0x02,0x40,0x20,0x21,0x24,0x05,0x00,0x01,0x24,0x07,0x00,0x04,0xaf,0xa2,0x00,0x10,
+0x0c,0x00,0x0e,0xd9,0xaf,0xa3,0x00,0x14,0x08,0x00,0x10,0x5a,0xae,0x42,0x00,0x28,
+0x0c,0x00,0x01,0x60,0x24,0x04,0x00,0x01,0x08,0x00,0x10,0x4b,0x00,0x00,0x00,0x00,
+0x8f,0x84,0xba,0x80,0xae,0x40,0x00,0x34,0x94,0x85,0x00,0x14,0x0c,0x00,0x1f,0xdd,
+0x00,0x00,0x00,0x00,0x93,0x83,0x91,0x51,0x00,0x00,0x00,0x00,0x30,0x62,0x00,0x02,
+0x10,0x40,0xff,0x69,0x00,0x00,0x00,0x00,0x0c,0x00,0x01,0x60,0x00,0x00,0x20,0x21,
+0x08,0x00,0x10,0x43,0x00,0x00,0x00,0x00,0x02,0x40,0x20,0x21,0x0c,0x00,0x0e,0x55,
+0x02,0x20,0x28,0x21,0x08,0x00,0x10,0x37,0x3c,0x02,0xb0,0x05,0x8e,0x42,0x00,0x3c,
+0x00,0x00,0x00,0x00,0x14,0x40,0xff,0x4a,0x00,0x00,0x00,0x00,0x8f,0x82,0xba,0x88,
+0x00,0x00,0x00,0x00,0x90,0x42,0x00,0x0a,0x00,0x00,0x00,0x00,0x00,0x02,0x18,0x2b,
+0x08,0x00,0x10,0x34,0xae,0x43,0x00,0x3c,0x8e,0x42,0x00,0x38,0x00,0x00,0x00,0x00,
+0x14,0x40,0xff,0x3d,0x24,0x02,0x00,0x12,0x8f,0x82,0xba,0x84,0x00,0x00,0x00,0x00,
+0x90,0x42,0x00,0x0a,0x00,0x00,0x00,0x00,0x00,0x02,0x18,0x2b,0x08,0x00,0x10,0x34,
+0xae,0x43,0x00,0x38,0x8e,0x42,0x00,0x34,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0x30,
+0x24,0x02,0x00,0x11,0x8f,0x82,0xba,0x80,0x00,0x00,0x00,0x00,0x90,0x42,0x00,0x0a,
+0x00,0x00,0x00,0x00,0x00,0x02,0x18,0x2b,0x08,0x00,0x10,0x34,0xae,0x43,0x00,0x34,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xe0,0x34,0x63,0x00,0x20,
+0x24,0x42,0x44,0x20,0x3c,0x08,0xb0,0x03,0xaf,0xb1,0x00,0x14,0xac,0x62,0x00,0x00,
+0x35,0x08,0x01,0x00,0xaf,0xbf,0x00,0x18,0xaf,0xb0,0x00,0x10,0x91,0x03,0x00,0x00,
+0x00,0xa0,0x48,0x21,0x24,0x11,0x00,0x0a,0x2c,0xa5,0x00,0x04,0x24,0x02,0x00,0x10,
+0x00,0x45,0x88,0x0a,0x30,0x63,0x00,0x01,0x00,0xc0,0x28,0x21,0x14,0x60,0x00,0x02,
+0x00,0x11,0x40,0x40,0x02,0x20,0x40,0x21,0x84,0x83,0x00,0x0c,0x31,0x11,0x00,0xff,
+0x01,0x20,0x20,0x21,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x96,0x48,0x00,0x43,0x10,0x21,0x84,0x43,0x00,0x04,0x24,0x06,0x00,0x0e,
+0x10,0xe0,0x00,0x06,0x02,0x23,0x80,0x21,0x02,0x00,0x10,0x21,0x8f,0xbf,0x00,0x18,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x0c,0x00,0x0d,0xd7,
+0x00,0x00,0x00,0x00,0x02,0x11,0x18,0x21,0x08,0x00,0x11,0x2a,0x00,0x62,0x80,0x21,
+0x27,0xbd,0xff,0xd0,0xaf,0xbf,0x00,0x28,0xaf,0xb5,0x00,0x24,0xaf,0xb4,0x00,0x20,
+0xaf,0xb2,0x00,0x18,0xaf,0xb3,0x00,0x1c,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,
+0x84,0x82,0x00,0x0c,0x3c,0x06,0xb0,0x03,0x34,0xc6,0x00,0x20,0x00,0x02,0x18,0xc0,
+0x00,0x62,0x18,0x21,0x00,0x03,0x18,0x80,0x27,0x82,0x96,0x44,0x00,0x62,0x10,0x21,
+0x8c,0x53,0x00,0x18,0x3c,0x02,0x80,0x00,0x24,0x42,0x44,0xd0,0xac,0xc2,0x00,0x00,
+0x8e,0x70,0x00,0x08,0x27,0x82,0x96,0x48,0x00,0x62,0x18,0x21,0x90,0x71,0x00,0x07,
+0x00,0x10,0x86,0x43,0x32,0x10,0x00,0x01,0x00,0xa0,0x38,0x21,0x02,0x00,0x30,0x21,
+0x00,0xa0,0xa0,0x21,0x02,0x20,0x28,0x21,0x0c,0x00,0x11,0x08,0x00,0x80,0xa8,0x21,
+0x02,0x20,0x20,0x21,0x02,0x00,0x28,0x21,0x24,0x06,0x00,0x14,0x0c,0x00,0x0d,0xd7,
+0x00,0x40,0x90,0x21,0x3c,0x03,0xb0,0x05,0x34,0x63,0x02,0x40,0x94,0x64,0x00,0x00,
+0x3c,0x0a,0xb0,0x09,0x3c,0x0b,0xb0,0x09,0x00,0x04,0x21,0x40,0x00,0x82,0x28,0x23,
+0x35,0x4a,0x01,0x10,0x35,0x6b,0x01,0x14,0x3c,0x0c,0xb0,0x09,0x3c,0x08,0xb0,0x09,
+0x3c,0x06,0xb0,0x09,0x00,0x44,0x10,0x2b,0x01,0x40,0x48,0x21,0x35,0x8c,0x01,0x20,
+0x01,0x60,0x38,0x21,0x35,0x08,0x01,0x24,0x34,0xc6,0x01,0x02,0x10,0x40,0x00,0x02,
+0x02,0x45,0x18,0x2b,0x00,0xa3,0x90,0x0b,0x86,0xa3,0x00,0x0c,0x27,0x84,0x96,0x50,
+0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x21,
+0x80,0x43,0x00,0x06,0xa4,0xd2,0x00,0x00,0x24,0x64,0x00,0x03,0x28,0x62,0x00,0x00,
+0x00,0x82,0x18,0x0b,0x00,0x03,0x18,0x83,0x00,0x03,0x18,0x80,0x12,0x80,0x00,0x11,
+0x02,0x63,0x28,0x21,0x8c,0xa2,0x00,0x0c,0x8c,0xa3,0x00,0x08,0x00,0x02,0x14,0x00,
+0x00,0x03,0x1c,0x02,0x00,0x43,0x10,0x21,0xad,0x22,0x00,0x00,0x8c,0xa3,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x00,0x03,0x1c,0x02,0xa4,0xe3,0x00,0x00,0x8f,0xbf,0x00,0x28,
+0x7b,0xb4,0x01,0x3c,0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x30,0x8c,0xa2,0x00,0x04,0x00,0x00,0x00,0x00,0xad,0x42,0x00,0x00,
+0x8c,0xa4,0x00,0x08,0x00,0x00,0x00,0x00,0xa5,0x64,0x00,0x00,0x78,0xa2,0x00,0x7c,
+0x00,0x00,0x00,0x00,0x00,0x03,0x1c,0x00,0x00,0x02,0x14,0x02,0x00,0x62,0x18,0x21,
+0xad,0x83,0x00,0x00,0x8c,0xa2,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x02,0x14,0x02,
+0x08,0x00,0x11,0x87,0xa5,0x02,0x00,0x00,0x27,0xbd,0xff,0xe0,0xaf,0xb2,0x00,0x18,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x1c,0xaf,0xb1,0x00,0x14,0x84,0x82,0x00,0x0c,
+0x00,0x80,0x90,0x21,0x3c,0x05,0xb0,0x03,0x00,0x02,0x20,0xc0,0x00,0x82,0x20,0x21,
+0x00,0x04,0x20,0x80,0x27,0x82,0x96,0x44,0x00,0x82,0x10,0x21,0x8c,0x51,0x00,0x18,
+0x3c,0x02,0x80,0x00,0x34,0xa5,0x00,0x20,0x24,0x42,0x46,0x78,0x27,0x83,0x96,0x48,
+0xac,0xa2,0x00,0x00,0x00,0x83,0x20,0x21,0x3c,0x02,0xb0,0x03,0x90,0x86,0x00,0x07,
+0x34,0x42,0x01,0x00,0x8e,0x23,0x00,0x08,0x90,0x44,0x00,0x00,0x2c,0xc5,0x00,0x04,
+0x24,0x02,0x00,0x10,0x24,0x10,0x00,0x0a,0x00,0x45,0x80,0x0a,0x00,0x03,0x1e,0x43,
+0x30,0x84,0x00,0x01,0x30,0x65,0x00,0x01,0x14,0x80,0x00,0x02,0x00,0x10,0x10,0x40,
+0x02,0x00,0x10,0x21,0x00,0xc0,0x20,0x21,0x24,0x06,0x00,0x20,0x0c,0x00,0x0d,0xd7,
+0x30,0x50,0x00,0xff,0x86,0x44,0x00,0x0c,0x27,0x85,0x96,0x50,0x3c,0x06,0xb0,0x09,
+0x00,0x04,0x18,0xc0,0x00,0x64,0x18,0x21,0x00,0x03,0x18,0x80,0x00,0x65,0x18,0x21,
+0x80,0x64,0x00,0x06,0x00,0x50,0x10,0x21,0x34,0xc6,0x01,0x02,0x24,0x85,0x00,0x03,
+0x28,0x83,0x00,0x00,0x00,0xa3,0x20,0x0b,0x00,0x04,0x20,0x83,0x00,0x04,0x20,0x80,
+0xa4,0xc2,0x00,0x00,0x02,0x24,0x20,0x21,0x8c,0x83,0x00,0x04,0x3c,0x02,0xb0,0x09,
+0x34,0x42,0x01,0x10,0xac,0x43,0x00,0x00,0x8c,0x86,0x00,0x08,0x3c,0x02,0xb0,0x09,
+0x34,0x42,0x01,0x14,0xa4,0x46,0x00,0x00,0x8c,0x85,0x00,0x0c,0x8c,0x82,0x00,0x08,
+0x3c,0x06,0xb0,0x09,0x00,0x05,0x2c,0x00,0x00,0x02,0x14,0x02,0x00,0xa2,0x28,0x21,
+0x34,0xc6,0x01,0x20,0xac,0xc5,0x00,0x00,0x8c,0x83,0x00,0x0c,0x3c,0x05,0xb0,0x09,
+0x34,0xa5,0x01,0x24,0x00,0x03,0x1c,0x02,0xa4,0xa3,0x00,0x00,0x92,0x42,0x00,0x0a,
+0x3c,0x03,0xb0,0x09,0x34,0x63,0x01,0x30,0x00,0x02,0x13,0x00,0x24,0x42,0x00,0x04,
+0x30,0x42,0xff,0xff,0xa4,0x62,0x00,0x00,0x86,0x44,0x00,0x0c,0x27,0x83,0x96,0x58,
+0x8f,0xbf,0x00,0x1c,0x00,0x04,0x10,0xc0,0x00,0x44,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x43,0x10,0x21,0x94,0x44,0x00,0x02,0x8f,0xb2,0x00,0x18,0x7b,0xb0,0x00,0xbc,
+0x3c,0x05,0xb0,0x09,0x34,0xa5,0x01,0x32,0xa4,0xa4,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x20,0x27,0xbd,0xff,0xe0,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x00,
+0xaf,0xb0,0x00,0x10,0x34,0x42,0x00,0x20,0x00,0xa0,0x80,0x21,0x24,0x63,0x48,0x04,
+0x00,0x05,0x2c,0x43,0xaf,0xb1,0x00,0x14,0xaf,0xbf,0x00,0x18,0xac,0x43,0x00,0x00,
+0x10,0xa0,0x00,0x05,0x00,0x80,0x88,0x21,0x8c,0x82,0x00,0x34,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0xaf,0x00,0x00,0x00,0x00,0x32,0x10,0x00,0xff,0x12,0x00,0x00,0x47,
+0x00,0x00,0x10,0x21,0x24,0x02,0x00,0x08,0x12,0x02,0x00,0x9c,0x2a,0x02,0x00,0x09,
+0x10,0x40,0x00,0x84,0x24,0x02,0x00,0x40,0x24,0x04,0x00,0x02,0x12,0x04,0x00,0x74,
+0x2a,0x02,0x00,0x03,0x10,0x40,0x00,0x64,0x24,0x02,0x00,0x04,0x24,0x02,0x00,0x01,
+0x12,0x02,0x00,0x55,0x00,0x00,0x00,0x00,0x82,0x22,0x00,0x11,0x92,0x27,0x00,0x11,
+0x10,0x40,0x00,0x4e,0x00,0x00,0x00,0x00,0x92,0x26,0x00,0x0a,0x24,0x02,0x00,0x12,
+0x10,0x46,0x00,0x09,0x30,0xc2,0x00,0xff,0x27,0x83,0xba,0x40,0x00,0x02,0x10,0x80,
+0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x94,0x83,0x00,0x14,
+0x00,0x00,0x00,0x00,0xa6,0x23,0x00,0x0c,0x3c,0x02,0xb0,0x09,0x34,0x42,0x00,0x40,
+0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x03,0xa2,0x23,0x00,0x10,
+0x14,0x60,0x00,0x2b,0x30,0x65,0x00,0x01,0x30,0xc2,0x00,0xff,0x27,0x83,0xba,0x40,
+0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,0x82,0x23,0x00,0x12,
+0x90,0x82,0x00,0x16,0x00,0x00,0x00,0x00,0x00,0x02,0x11,0x42,0x30,0x42,0x00,0x01,
+0x00,0x62,0x18,0x21,0x00,0x03,0x26,0x00,0x14,0x80,0x00,0x18,0xa2,0x23,0x00,0x12,
+0x00,0x07,0x16,0x00,0x14,0x40,0x00,0x11,0x24,0x02,0x00,0x01,0x96,0x23,0x00,0x0c,
+0x27,0x84,0x96,0x50,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x44,0x10,0x21,0x80,0x45,0x00,0x06,0x00,0x03,0x1a,0x00,0x3c,0x02,0xb0,0x00,
+0x00,0x65,0x18,0x21,0x00,0x62,0x18,0x21,0x90,0x64,0x00,0x00,0x90,0x62,0x00,0x04,
+0xa2,0x20,0x00,0x15,0xa3,0x80,0x92,0x15,0x24,0x02,0x00,0x01,0x8f,0xbf,0x00,0x18,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x0c,0x00,0x11,0x9e,
+0x02,0x20,0x20,0x21,0x92,0x27,0x00,0x11,0x08,0x00,0x12,0x49,0x00,0x07,0x16,0x00,
+0x0c,0x00,0x11,0x34,0x02,0x20,0x20,0x21,0x86,0x23,0x00,0x0c,0x27,0x84,0x96,0x48,
+0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x44,0x20,0x21,
+0x90,0x85,0x00,0x07,0x27,0x83,0x96,0x50,0x00,0x43,0x10,0x21,0xa2,0x25,0x00,0x13,
+0x90,0x83,0x00,0x07,0x08,0x00,0x12,0x61,0xa0,0x43,0x00,0x02,0x92,0x26,0x00,0x0a,
+0x08,0x00,0x12,0x2a,0x30,0xc2,0x00,0xff,0x8e,0x22,0x00,0x24,0x00,0x00,0x00,0x00,
+0x10,0x50,0x00,0x07,0xa2,0x20,0x00,0x08,0x24,0x02,0x00,0x07,0xa2,0x22,0x00,0x0a,
+0x92,0x22,0x00,0x27,0xae,0x20,0x00,0x24,0x08,0x00,0x12,0x22,0xa2,0x22,0x00,0x04,
+0x08,0x00,0x12,0x7b,0x24,0x02,0x00,0x06,0x16,0x02,0xff,0x9f,0x24,0x02,0x00,0x01,
+0x8e,0x23,0x00,0x2c,0x00,0x00,0x00,0x00,0x10,0x62,0x00,0x07,0xa2,0x24,0x00,0x08,
+0x24,0x02,0x00,0x03,0xa2,0x22,0x00,0x0a,0x92,0x22,0x00,0x2f,0xae,0x20,0x00,0x2c,
+0x08,0x00,0x12,0x22,0xa2,0x22,0x00,0x06,0x08,0x00,0x12,0x8a,0xa2,0x20,0x00,0x0a,
+0x8e,0x22,0x00,0x28,0x24,0x03,0x00,0x01,0x24,0x04,0x00,0x01,0x10,0x44,0x00,0x07,
+0xa2,0x23,0x00,0x08,0x24,0x02,0x00,0x05,0xa2,0x22,0x00,0x0a,0x92,0x22,0x00,0x2b,
+0xae,0x20,0x00,0x28,0x08,0x00,0x12,0x22,0xa2,0x22,0x00,0x05,0x08,0x00,0x12,0x96,
+0x24,0x02,0x00,0x04,0x12,0x02,0x00,0x10,0x2a,0x02,0x00,0x41,0x10,0x40,0x00,0x08,
+0x24,0x02,0x00,0x80,0x24,0x02,0x00,0x20,0x16,0x02,0xff,0x7f,0x24,0x02,0x00,0x12,
+0xa2,0x22,0x00,0x0a,0xa2,0x22,0x00,0x08,0x08,0x00,0x12,0x22,0xae,0x20,0x00,0x3c,
+0x16,0x02,0xff,0x79,0x24,0x02,0x00,0x10,0xa2,0x22,0x00,0x0a,0xa2,0x22,0x00,0x08,
+0x08,0x00,0x12,0x22,0xae,0x20,0x00,0x34,0x24,0x02,0x00,0x11,0xa2,0x22,0x00,0x0a,
+0xa2,0x22,0x00,0x08,0x08,0x00,0x12,0x22,0xae,0x20,0x00,0x38,0x8e,0x24,0x00,0x30,
+0x24,0x02,0x00,0x03,0x24,0x03,0x00,0x01,0x10,0x83,0x00,0x07,0xa2,0x22,0x00,0x08,
+0x24,0x02,0x00,0x02,0xa2,0x22,0x00,0x0a,0x92,0x22,0x00,0x33,0xae,0x20,0x00,0x30,
+0x08,0x00,0x12,0x22,0xa2,0x22,0x00,0x07,0x08,0x00,0x12,0xba,0xa2,0x24,0x00,0x0a,
+0x8f,0x84,0xba,0x80,0xae,0x20,0x00,0x34,0x94,0x85,0x00,0x14,0x0c,0x00,0x1f,0xdd,
+0x32,0x10,0x00,0xff,0x08,0x00,0x12,0x13,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0x24,0x42,0x4b,0x1c,0x34,0x63,0x00,0x20,0xac,0x62,0x00,0x00,
+0x80,0xa2,0x00,0x15,0x3c,0x06,0xb0,0x05,0x10,0x40,0x00,0x0a,0x34,0xc6,0x02,0x54,
+0x83,0x83,0x92,0x15,0x00,0x00,0x00,0x00,0xac,0x83,0x00,0x24,0x8c,0xc2,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x02,0x17,0x42,0x30,0x42,0x00,0x01,0x03,0xe0,0x00,0x08,
+0xac,0x82,0x00,0x28,0x8c,0x82,0x00,0x2c,0x3c,0x06,0xb0,0x05,0x34,0xc6,0x04,0x50,
+0x00,0x02,0x18,0x43,0x30,0x63,0x00,0x01,0x10,0x40,0x00,0x04,0x30,0x45,0x00,0x01,
+0xac,0x83,0x00,0x28,0x03,0xe0,0x00,0x08,0xac,0x85,0x00,0x24,0x90,0xc2,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0x30,0x43,0x00,0x02,0x30,0x42,0x00,0x01,
+0xac,0x83,0x00,0x28,0x03,0xe0,0x00,0x08,0xac,0x82,0x00,0x24,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xd8,0x34,0x63,0x00,0x20,0x24,0x42,0x4b,0xac,
+0xac,0x62,0x00,0x00,0xaf,0xb1,0x00,0x1c,0xaf,0xbf,0x00,0x20,0xaf,0xb0,0x00,0x18,
+0x90,0xa6,0x00,0x0a,0x27,0x83,0xba,0x40,0x00,0xa0,0x88,0x21,0x00,0x06,0x10,0x80,
+0x00,0x43,0x10,0x21,0x8c,0x50,0x00,0x00,0x80,0xa5,0x00,0x11,0x92,0x03,0x00,0x12,
+0x10,0xa0,0x00,0x04,0xa2,0x20,0x00,0x15,0x24,0x02,0x00,0x12,0x10,0xc2,0x00,0xd9,
+0x00,0x00,0x00,0x00,0x82,0x22,0x00,0x12,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x67,
+0x00,0x00,0x00,0x00,0xa2,0x20,0x00,0x12,0xa2,0x00,0x00,0x19,0x86,0x23,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x96,0x60,0x00,0x43,0x10,0x21,0xa0,0x40,0x00,0x00,0x92,0x03,0x00,0x16,
+0x00,0x00,0x00,0x00,0x30,0x63,0x00,0xdf,0xa2,0x03,0x00,0x16,0x82,0x02,0x00,0x12,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x20,0x00,0x00,0x00,0x00,0x92,0x23,0x00,0x08,
+0x00,0x00,0x00,0x00,0x14,0x60,0x00,0x45,0x24,0x02,0x00,0x01,0xa2,0x20,0x00,0x04,
+0x92,0x08,0x00,0x04,0x00,0x00,0x00,0x00,0x15,0x00,0x00,0x1e,0x24,0x02,0x00,0x01,
+0x92,0x07,0x00,0x0a,0xa2,0x02,0x00,0x17,0x92,0x02,0x00,0x16,0x30,0xe3,0x00,0xff,
+0x30,0x42,0x00,0xe4,0x10,0x60,0x00,0x03,0xa2,0x02,0x00,0x16,0x34,0x42,0x00,0x01,
+0xa2,0x02,0x00,0x16,0x11,0x00,0x00,0x05,0x00,0x00,0x00,0x00,0x92,0x02,0x00,0x16,
+0x00,0x00,0x00,0x00,0x34,0x42,0x00,0x02,0xa2,0x02,0x00,0x16,0x92,0x02,0x00,0x17,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x08,0x00,0x00,0x00,0x00,0x96,0x02,0x00,0x06,
+0x00,0x00,0x00,0x00,0xa6,0x02,0x00,0x14,0x8f,0xbf,0x00,0x20,0x7b,0xb0,0x00,0xfc,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,0x96,0x02,0x00,0x00,0x08,0x00,0x13,0x36,
+0xa6,0x02,0x00,0x14,0x92,0x07,0x00,0x0a,0x00,0x00,0x00,0x00,0x14,0xe0,0x00,0x03,
+0x00,0x00,0x00,0x00,0x08,0x00,0x13,0x22,0xa2,0x00,0x00,0x17,0x96,0x04,0x00,0x00,
+0x96,0x05,0x00,0x06,0x27,0x86,0x96,0x40,0x00,0x04,0x18,0xc0,0x00,0x64,0x18,0x21,
+0x00,0x05,0x10,0xc0,0x00,0x45,0x10,0x21,0x00,0x03,0x18,0x80,0x00,0x66,0x18,0x21,
+0x00,0x02,0x10,0x80,0x00,0x46,0x10,0x21,0x8c,0x66,0x00,0x08,0x8c,0x45,0x00,0x08,
+0x3c,0x03,0x80,0x00,0x00,0xc3,0x20,0x24,0x10,0x80,0x00,0x08,0x00,0xa3,0x10,0x24,
+0x10,0x40,0x00,0x04,0x00,0x00,0x18,0x21,0x10,0x80,0x00,0x02,0x24,0x03,0x00,0x01,
+0x00,0xa6,0x18,0x2b,0x08,0x00,0x13,0x22,0xa2,0x03,0x00,0x17,0x10,0x40,0xff,0xfd,
+0x00,0xa6,0x18,0x2b,0x08,0x00,0x13,0x56,0x00,0x00,0x00,0x00,0x10,0x62,0x00,0x09,
+0x24,0x02,0x00,0x02,0x10,0x62,0x00,0x05,0x24,0x02,0x00,0x03,0x14,0x62,0xff,0xb8,
+0x00,0x00,0x00,0x00,0x08,0x00,0x13,0x1c,0xa2,0x20,0x00,0x07,0x08,0x00,0x13,0x1c,
+0xa2,0x20,0x00,0x06,0x08,0x00,0x13,0x1c,0xa2,0x20,0x00,0x05,0x82,0x22,0x00,0x10,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x68,0x2c,0x62,0x00,0x02,0x10,0x40,0x00,0x48,
+0x3c,0x02,0xb0,0x09,0x92,0x25,0x00,0x08,0x00,0x00,0x00,0x00,0x30,0xa6,0x00,0xff,
+0x2c,0xc2,0x00,0x04,0x10,0x40,0x00,0x3a,0x2c,0xc2,0x00,0x10,0x3c,0x04,0xb0,0x05,
+0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,0x24,0x02,0x00,0x01,0x00,0xc2,0x10,0x04,
+0x00,0x02,0x10,0x27,0x00,0x62,0x18,0x24,0xa0,0x83,0x00,0x00,0x86,0x23,0x00,0x0c,
+0x96,0x26,0x00,0x0c,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x28,0x80,
+0x27,0x83,0x96,0x44,0x00,0xa3,0x18,0x21,0x8c,0x64,0x00,0x18,0x00,0x00,0x00,0x00,
+0x8c,0x82,0x00,0x04,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x10,0x10,0x40,0x00,0x18,
+0x00,0x00,0x00,0x00,0x93,0x82,0x91,0x51,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,
+0x14,0x40,0x00,0x0a,0x24,0x05,0x00,0x24,0x00,0x06,0x2c,0x00,0x00,0x05,0x2c,0x03,
+0x0c,0x00,0x1f,0xdd,0x02,0x00,0x20,0x21,0x92,0x02,0x00,0x16,0xa2,0x00,0x00,0x12,
+0x30,0x42,0x00,0xe7,0x08,0x00,0x13,0x13,0xa2,0x02,0x00,0x16,0xf0,0xc5,0x00,0x06,
+0x00,0x00,0x28,0x12,0x27,0x82,0x96,0x40,0x00,0xa2,0x28,0x21,0x0c,0x00,0x01,0x49,
+0x3c,0x04,0x00,0x80,0x96,0x26,0x00,0x0c,0x08,0x00,0x13,0x93,0x00,0x06,0x2c,0x00,
+0x27,0x83,0x96,0x50,0x27,0x82,0x96,0x58,0x00,0xa2,0x10,0x21,0x00,0xa3,0x18,0x21,
+0x90,0x44,0x00,0x00,0x90,0x65,0x00,0x05,0x00,0x00,0x30,0x21,0x0c,0x00,0x25,0xc4,
+0x24,0x07,0x00,0x01,0x96,0x26,0x00,0x0c,0x08,0x00,0x13,0x8d,0x00,0x00,0x00,0x00,
+0x14,0x40,0xff,0xce,0x3c,0x04,0xb0,0x05,0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,
+0x30,0xa5,0x00,0x0f,0x24,0x02,0x00,0x80,0x08,0x00,0x13,0x7c,0x00,0xa2,0x10,0x07,
+0x86,0x26,0x00,0x0c,0x3c,0x03,0xb0,0x09,0x34,0x42,0x01,0x72,0x34,0x63,0x01,0x78,
+0x94,0x47,0x00,0x00,0x8c,0x65,0x00,0x00,0x00,0x06,0x10,0xc0,0x00,0x46,0x10,0x21,
+0x3c,0x04,0xb0,0x09,0xae,0x25,0x00,0x1c,0x34,0x84,0x01,0x7c,0x27,0x83,0x96,0x44,
+0x00,0x02,0x10,0x80,0x8c,0x85,0x00,0x00,0x00,0x43,0x10,0x21,0x8c,0x43,0x00,0x18,
+0xae,0x25,0x00,0x20,0xa6,0x27,0x00,0x18,0x8c,0x66,0x00,0x08,0x02,0x20,0x20,0x21,
+0x0c,0x00,0x13,0xe2,0x00,0x00,0x28,0x21,0x86,0x25,0x00,0x18,0x8e,0x26,0x00,0x1c,
+0x8e,0x27,0x00,0x20,0x02,0x20,0x20,0x21,0x0c,0x00,0x20,0xdf,0xaf,0xa2,0x00,0x10,
+0x08,0x00,0x13,0x13,0xa2,0x02,0x00,0x12,0x92,0x22,0x00,0x08,0x08,0x00,0x13,0x13,
+0xa2,0x22,0x00,0x09,0xa2,0x20,0x00,0x11,0x80,0x82,0x00,0x50,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x03,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0xd0,0xac,0x40,0x00,0x00,
+0x08,0x00,0x13,0x13,0xa0,0x80,0x00,0x50,0x94,0x8a,0x00,0x0c,0x24,0x03,0x00,0x24,
+0x00,0x80,0x70,0x21,0x3c,0x02,0x80,0x00,0x3c,0x04,0xb0,0x03,0x24,0x42,0x4f,0x88,
+0xf1,0x43,0x00,0x06,0x34,0x84,0x00,0x20,0x00,0x00,0x18,0x12,0x00,0xa0,0x68,0x21,
+0xac,0x82,0x00,0x00,0x27,0x85,0x96,0x50,0x27,0x82,0x96,0x4f,0x27,0xbd,0xff,0xf8,
+0x00,0x62,0x60,0x21,0x00,0x65,0x58,0x21,0x00,0x00,0xc0,0x21,0x11,0xa0,0x00,0xcc,
+0x00,0x00,0x78,0x21,0x00,0x0a,0x1c,0x00,0x00,0x03,0x1c,0x03,0x00,0x03,0x10,0xc0,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x45,0x10,0x21,0x91,0x87,0x00,0x00,
+0x80,0x48,0x00,0x04,0x03,0xa0,0x60,0x21,0x00,0x0a,0x1c,0x00,0x00,0x03,0x1c,0x03,
+0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x48,0x80,0x27,0x83,0x96,0x44,
+0xa3,0xa7,0x00,0x00,0x01,0x23,0x18,0x21,0x8c,0x64,0x00,0x18,0x25,0x02,0xff,0xff,
+0x00,0x48,0x40,0x0b,0x8c,0x83,0x00,0x04,0x2d,0x05,0x00,0x07,0x24,0x02,0x00,0x06,
+0x30,0x63,0x00,0x08,0x14,0x60,0x00,0x35,0x00,0x45,0x40,0x0a,0x93,0xa7,0x00,0x00,
+0x27,0x82,0x96,0x58,0x01,0x22,0x10,0x21,0x30,0xe3,0x00,0xf0,0x38,0x63,0x00,0x50,
+0x30,0xe5,0x00,0xff,0x00,0x05,0x20,0x2b,0x00,0x03,0x18,0x2b,0x00,0x64,0x18,0x24,
+0x90,0x49,0x00,0x00,0x10,0x60,0x00,0x16,0x30,0xe4,0x00,0x0f,0x24,0x02,0x00,0x04,
+0x10,0xa2,0x00,0x9d,0x00,0x00,0x00,0x00,0x11,0xa0,0x00,0x3a,0x2c,0xa2,0x00,0x0c,
+0x10,0x40,0x00,0x02,0x24,0x84,0x00,0x0c,0x00,0xe0,0x20,0x21,0x30,0x84,0x00,0xff,
+0x00,0x04,0x10,0x40,0x27,0x83,0xc1,0x5c,0x00,0x44,0x10,0x21,0x00,0x43,0x10,0x21,
+0x90,0x47,0x00,0x00,0x00,0x00,0x00,0x00,0x2c,0xe3,0x00,0x0c,0xa3,0xa7,0x00,0x00,
+0x10,0x60,0x00,0x02,0x24,0xe2,0x00,0x04,0x00,0xe0,0x10,0x21,0xa3,0xa2,0x00,0x00,
+0x91,0x65,0x00,0x00,0x91,0x82,0x00,0x00,0x30,0xa3,0x00,0xff,0x00,0x62,0x10,0x2b,
+0x10,0x40,0x00,0x0e,0x2c,0x62,0x00,0x0c,0x14,0x40,0x00,0x03,0x00,0x60,0x20,0x21,
+0x30,0xa2,0x00,0x0f,0x24,0x44,0x00,0x0c,0x00,0x04,0x10,0x40,0x00,0x44,0x20,0x21,
+0x27,0x83,0xc1,0x5c,0x00,0x83,0x18,0x21,0x90,0x62,0x00,0x02,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x05,0x00,0x09,0x11,0x00,0xa1,0x85,0x00,0x00,0x93,0xa2,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x08,0x00,0x49,0x10,0x23,0x00,0x02,0x10,0x80,
+0x00,0x49,0x10,0x23,0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x21,0x27,0x83,0xba,0xe8,
+0x00,0x43,0x10,0x21,0x90,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x2c,0x83,0x00,0x0c,
+0x14,0x60,0x00,0x06,0x00,0x80,0x10,0x21,0x00,0x18,0x10,0x40,0x00,0x4f,0x10,0x21,
+0x00,0x02,0x11,0x00,0x00,0x82,0x10,0x21,0x24,0x42,0x00,0x04,0x08,0x00,0x14,0x43,
+0xa1,0x82,0x00,0x00,0x8f,0x8d,0x87,0xf0,0x00,0x00,0x00,0x00,0x01,0xa8,0x10,0x21,
+0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x60,0xff,0xd1,0x00,0x00,0x28,0x21,
+0x00,0x06,0x74,0x82,0x30,0xe2,0x00,0xff,0x2c,0x42,0x00,0x0c,0x14,0x40,0x00,0x03,
+0x00,0xe0,0x10,0x21,0x30,0xe2,0x00,0x0f,0x24,0x42,0x00,0x0c,0x30,0x44,0x00,0xff,
+0xa3,0xa2,0x00,0x00,0x24,0x02,0x00,0x0c,0x10,0x82,0x00,0x0d,0x00,0x09,0x11,0x00,
+0x00,0x49,0x10,0x23,0x00,0x02,0x10,0x80,0x00,0x04,0x18,0x40,0x00,0x49,0x10,0x23,
+0x00,0x64,0x18,0x21,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x27,0x84,0xba,0xe8,
+0x00,0x44,0x10,0x21,0x90,0x47,0x00,0x00,0x00,0x00,0x00,0x00,0xa3,0xa7,0x00,0x00,
+0x00,0x0a,0x1c,0x00,0x00,0x03,0x1c,0x03,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x96,0x44,0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x18,
+0x00,0x00,0x00,0x00,0x8c,0x83,0x00,0x04,0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x10,
+0x14,0x60,0x00,0x33,0x00,0x06,0x14,0x42,0x00,0x09,0x11,0x00,0x00,0x49,0x10,0x23,
+0x00,0x02,0x10,0x80,0x00,0x49,0x10,0x23,0x27,0x83,0xbb,0xb8,0x00,0x02,0x10,0x80,
+0x00,0x43,0x10,0x21,0x90,0x44,0x00,0x04,0x90,0x43,0x00,0x05,0x00,0x00,0x00,0x00,
+0x00,0x64,0xc0,0x24,0x93,0xa7,0x00,0x00,0x00,0x00,0x00,0x00,0x2c,0xe2,0x00,0x0f,
+0x10,0x40,0x00,0x0f,0x31,0xcf,0x00,0x01,0x00,0x0a,0x1c,0x00,0x00,0x03,0x1c,0x03,
+0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x84,0x96,0x40,
+0x00,0x44,0x10,0x21,0x84,0x43,0x00,0x06,0x00,0x00,0x00,0x00,0x28,0x63,0x06,0x41,
+0x14,0x60,0x00,0x04,0x30,0xe2,0x00,0xff,0x24,0x07,0x00,0x0f,0xa3,0xa7,0x00,0x00,
+0x30,0xe2,0x00,0xff,0x2c,0x42,0x00,0x0c,0x14,0x40,0x00,0x06,0x00,0xe0,0x10,0x21,
+0x00,0x18,0x10,0x40,0x00,0x4f,0x10,0x21,0x00,0x02,0x11,0x00,0x00,0x47,0x10,0x21,
+0x24,0x42,0x00,0x04,0xa3,0xa2,0x00,0x00,0x00,0x40,0x38,0x21,0x01,0xa8,0x10,0x21,
+0x90,0x43,0x00,0x00,0x24,0xa4,0x00,0x01,0x30,0x85,0xff,0xff,0x00,0xa3,0x18,0x2b,
+0x14,0x60,0xff,0xad,0x30,0xe2,0x00,0xff,0x08,0x00,0x14,0x30,0x00,0x00,0x00,0x00,
+0x08,0x00,0x14,0x91,0x30,0x58,0x00,0x01,0x81,0xc2,0x00,0x48,0x00,0x00,0x00,0x00,
+0x10,0x40,0xff,0x73,0x00,0x00,0x00,0x00,0x08,0x00,0x14,0x1e,0x00,0x00,0x00,0x00,
+0x00,0x0a,0x1c,0x00,0x00,0x03,0x1c,0x03,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x45,0x10,0x21,0x80,0x48,0x00,0x05,0x91,0x67,0x00,0x00,
+0x08,0x00,0x13,0xfe,0x03,0xa0,0x58,0x21,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x34,0x63,0x00,0x20,0x24,0x42,0x53,0x28,0x03,0xe0,0x00,0x08,0xac,0x62,0x00,0x00,
+0x27,0xbd,0xff,0xc0,0xaf,0xb7,0x00,0x34,0xaf,0xb6,0x00,0x30,0xaf,0xb5,0x00,0x2c,
+0xaf,0xb4,0x00,0x28,0xaf,0xb3,0x00,0x24,0xaf,0xb2,0x00,0x20,0xaf,0xbf,0x00,0x3c,
+0xaf,0xbe,0x00,0x38,0xaf,0xb1,0x00,0x1c,0xaf,0xb0,0x00,0x18,0x84,0x82,0x00,0x0c,
+0x27,0x93,0x96,0x44,0x3c,0x05,0xb0,0x03,0x00,0x02,0x18,0xc0,0x00,0x62,0x18,0x21,
+0x00,0x03,0x18,0x80,0x00,0x73,0x10,0x21,0x8c,0x5e,0x00,0x18,0x3c,0x02,0x80,0x00,
+0x34,0xa5,0x00,0x20,0x24,0x42,0x53,0x40,0xac,0xa2,0x00,0x00,0x8f,0xd0,0x00,0x08,
+0x27,0x95,0x96,0x50,0x00,0x75,0x18,0x21,0x00,0x00,0x28,0x21,0x02,0x00,0x30,0x21,
+0x90,0x71,0x00,0x00,0x0c,0x00,0x13,0xe2,0x00,0x80,0xb0,0x21,0x00,0x40,0x90,0x21,
+0x00,0x10,0x14,0x42,0x30,0x54,0x00,0x01,0x02,0x40,0x20,0x21,0x00,0x10,0x14,0x82,
+0x02,0x80,0x28,0x21,0x12,0x51,0x00,0x23,0x00,0x10,0xbf,0xc2,0x86,0xc3,0x00,0x0c,
+0x30,0x50,0x00,0x01,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x55,0x10,0x21,0xa0,0x52,0x00,0x00,0x86,0xc3,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x53,0x30,0x21,
+0x8c,0xc7,0x00,0x18,0x27,0x83,0x96,0x40,0x00,0x43,0x10,0x21,0x8c,0xe3,0x00,0x04,
+0x84,0x46,0x00,0x06,0x00,0x03,0x19,0x42,0x0c,0x00,0x0d,0xd7,0x30,0x73,0x00,0x01,
+0x00,0x40,0x88,0x21,0x02,0x40,0x20,0x21,0x02,0x80,0x28,0x21,0x16,0xe0,0x00,0x10,
+0x02,0x00,0x30,0x21,0x86,0xc2,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x02,0x18,0xc0,
+0x00,0x62,0x18,0x21,0x00,0x03,0x18,0x80,0x27,0x82,0x96,0x48,0x00,0x62,0x18,0x21,
+0xa4,0x71,0x00,0x04,0x7b,0xbe,0x01,0xfc,0x7b,0xb6,0x01,0xbc,0x7b,0xb4,0x01,0x7c,
+0x7b,0xb2,0x01,0x3c,0x7b,0xb0,0x00,0xfc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x40,
+0x86,0xc3,0x00,0x0c,0xaf,0xb3,0x00,0x10,0xaf,0xa0,0x00,0x14,0x00,0x03,0x10,0xc0,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x55,0x10,0x21,0x80,0x47,0x00,0x06,
+0x00,0x00,0x00,0x00,0x24,0xe7,0x00,0x02,0x00,0x07,0x17,0xc2,0x00,0xe2,0x38,0x21,
+0x00,0x07,0x38,0x43,0x00,0x07,0x38,0x40,0x0c,0x00,0x0d,0xfe,0x03,0xc7,0x38,0x21,
+0x08,0x00,0x15,0x11,0x02,0x22,0x88,0x21,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x27,0xbd,0xff,0xd0,0x34,0x63,0x00,0x20,0x24,0x42,0x54,0xc8,0xaf,0xb2,0x00,0x20,
+0xac,0x62,0x00,0x00,0xaf,0xbf,0x00,0x28,0xaf,0xb3,0x00,0x24,0xaf,0xb1,0x00,0x1c,
+0xaf,0xb0,0x00,0x18,0x3c,0x02,0xb0,0x03,0x90,0x83,0x00,0x0a,0x34,0x42,0x01,0x04,
+0x94,0x45,0x00,0x00,0x00,0x03,0x18,0x80,0x27,0x82,0xba,0x40,0x00,0x62,0x18,0x21,
+0x30,0xa6,0xff,0xff,0x8c,0x71,0x00,0x00,0x80,0x85,0x00,0x12,0x30,0xc8,0x00,0xff,
+0x00,0x06,0x32,0x02,0xa4,0x86,0x00,0x44,0xa4,0x88,0x00,0x46,0x82,0x22,0x00,0x12,
+0x00,0x80,0x90,0x21,0x10,0xa0,0x00,0x1b,0xa0,0x80,0x00,0x15,0x00,0xc5,0x10,0x2a,
+0x10,0x40,0x00,0x14,0x00,0x00,0x00,0x00,0xa2,0x20,0x00,0x19,0x84,0x83,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x96,0x60,0x00,0x43,0x10,0x21,0xa0,0x40,0x00,0x00,0xa0,0x80,0x00,0x12,
+0x92,0x22,0x00,0x16,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xdf,0xa2,0x22,0x00,0x16,
+0x8f,0xbf,0x00,0x28,0x7b,0xb2,0x01,0x3c,0x7b,0xb0,0x00,0xfc,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x30,0x0c,0x00,0x14,0xca,0x00,0x00,0x00,0x00,0x08,0x00,0x15,0x60,
+0x00,0x00,0x00,0x00,0x28,0x42,0x00,0x02,0x10,0x40,0x01,0x65,0x00,0x00,0x28,0x21,
+0x84,0x83,0x00,0x0c,0x27,0x84,0x96,0x50,0x96,0x47,0x00,0x0c,0x00,0x03,0x10,0xc0,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x83,0x96,0x48,0x00,0x43,0x18,0x21,
+0x80,0x65,0x00,0x06,0x00,0x44,0x10,0x21,0x80,0x49,0x00,0x05,0x38,0xa5,0x00,0x00,
+0x80,0x4a,0x00,0x04,0x15,0x20,0x00,0x27,0x01,0x05,0x30,0x0b,0x15,0x40,0x00,0x11,
+0x30,0xe3,0xff,0xff,0x92,0x45,0x00,0x08,0x00,0x00,0x00,0x00,0x30,0xa8,0x00,0xff,
+0x2d,0x02,0x00,0x04,0x10,0x40,0x01,0x45,0x2d,0x02,0x00,0x10,0x3c,0x04,0xb0,0x05,
+0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,0x24,0x02,0x00,0x01,0x01,0x02,0x10,0x04,
+0x00,0x62,0x18,0x25,0xa0,0x83,0x00,0x00,0x96,0x47,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x30,0xe3,0xff,0xff,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x27,0x84,0x96,0x50,
+0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x21,0x80,0x45,0x00,0x06,0x00,0x03,0x1a,0x00,
+0x3c,0x04,0xb0,0x00,0x00,0x65,0x18,0x21,0x00,0x64,0x28,0x21,0x94,0xa2,0x00,0x00,
+0x82,0x43,0x00,0x10,0x00,0x02,0x14,0x00,0x14,0x60,0x00,0x06,0x00,0x02,0x24,0x03,
+0x30,0x82,0x00,0x04,0x14,0x40,0x00,0x04,0x01,0x49,0x10,0x21,0x34,0x82,0x08,0x00,
+0xa4,0xa2,0x00,0x00,0x01,0x49,0x10,0x21,0x00,0x02,0x16,0x00,0x00,0x02,0x16,0x03,
+0x00,0x46,0x10,0x2a,0x10,0x40,0x00,0x7c,0x00,0x00,0x00,0x00,0x82,0x42,0x00,0x10,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x0e,0x00,0x00,0x00,0x00,0x86,0x43,0x00,0x0c,
+0x25,0x44,0x00,0x01,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x96,0x50,0x00,0x43,0x10,0x21,0xa0,0x44,0x00,0x04,0x92,0x23,0x00,0x16,
+0x02,0x40,0x20,0x21,0x30,0x63,0x00,0xfb,0x08,0x00,0x15,0x65,0xa2,0x23,0x00,0x16,
+0x86,0x43,0x00,0x0c,0x25,0x24,0x00,0x01,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x96,0x50,0x00,0x43,0x10,0x21,0xa0,0x44,0x00,0x05,
+0x86,0x45,0x00,0x0c,0x0c,0x00,0x23,0x1c,0x02,0x20,0x20,0x21,0x10,0x40,0x00,0x5a,
+0x00,0x00,0x00,0x00,0x92,0x45,0x00,0x08,0x00,0x00,0x00,0x00,0x30,0xa6,0x00,0xff,
+0x2c,0xc2,0x00,0x04,0x10,0x40,0x00,0x4c,0x2c,0xc2,0x00,0x10,0x3c,0x04,0xb0,0x05,
+0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,0x24,0x02,0x00,0x01,0x00,0xc2,0x10,0x04,
+0x00,0x02,0x10,0x27,0x00,0x62,0x18,0x24,0xa0,0x83,0x00,0x00,0x92,0x45,0x00,0x08,
+0x00,0x00,0x00,0x00,0x30,0xa5,0x00,0xff,0x14,0xa0,0x00,0x33,0x24,0x02,0x00,0x01,
+0xa2,0x40,0x00,0x04,0x92,0x22,0x00,0x04,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x0c,
+0x24,0x02,0x00,0x01,0xa2,0x22,0x00,0x17,0x92,0x22,0x00,0x17,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x04,0x00,0x00,0x00,0x00,0x96,0x22,0x00,0x06,0x08,0x00,0x15,0x60,
+0xa6,0x22,0x00,0x14,0x96,0x22,0x00,0x00,0x08,0x00,0x15,0x60,0xa6,0x22,0x00,0x14,
+0x92,0x22,0x00,0x0a,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0x15,0xde,0xa2,0x20,0x00,0x17,0x96,0x24,0x00,0x00,0x96,0x25,0x00,0x06,
+0x27,0x86,0x96,0x40,0x00,0x04,0x18,0xc0,0x00,0x64,0x18,0x21,0x00,0x05,0x10,0xc0,
+0x00,0x45,0x10,0x21,0x00,0x03,0x18,0x80,0x00,0x66,0x18,0x21,0x00,0x02,0x10,0x80,
+0x00,0x46,0x10,0x21,0x8c,0x65,0x00,0x08,0x8c,0x44,0x00,0x08,0x3c,0x03,0x80,0x00,
+0x00,0xa3,0x30,0x24,0x10,0xc0,0x00,0x08,0x00,0x83,0x10,0x24,0x10,0x40,0x00,0x04,
+0x00,0x00,0x18,0x21,0x10,0xc0,0x00,0x02,0x24,0x03,0x00,0x01,0x00,0x85,0x18,0x2b,
+0x08,0x00,0x15,0xde,0xa2,0x23,0x00,0x17,0x10,0x40,0xff,0xfd,0x00,0x85,0x18,0x2b,
+0x08,0x00,0x16,0x01,0x00,0x00,0x00,0x00,0x10,0xa2,0x00,0x09,0x24,0x02,0x00,0x02,
+0x10,0xa2,0x00,0x05,0x24,0x02,0x00,0x03,0x14,0xa2,0xff,0xca,0x00,0x00,0x00,0x00,
+0x08,0x00,0x15,0xd9,0xa2,0x40,0x00,0x07,0x08,0x00,0x15,0xd9,0xa2,0x40,0x00,0x06,
+0x08,0x00,0x15,0xd9,0xa2,0x40,0x00,0x05,0x14,0x40,0xff,0xbe,0x3c,0x04,0xb0,0x05,
+0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,0x30,0xa5,0x00,0x0f,0x24,0x02,0x00,0x80,
+0x08,0x00,0x15,0xd0,0x00,0xa2,0x10,0x07,0x0c,0x00,0x14,0xd0,0x02,0x40,0x20,0x21,
+0x08,0x00,0x15,0x60,0x00,0x00,0x00,0x00,0x92,0x45,0x00,0x08,0x00,0x00,0x00,0x00,
+0x30,0xa6,0x00,0xff,0x2c,0xc2,0x00,0x04,0x10,0x40,0x00,0x98,0x2c,0xc2,0x00,0x10,
+0x3c,0x04,0xb0,0x05,0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,0x24,0x02,0x00,0x01,
+0x00,0xc2,0x10,0x04,0x00,0x02,0x10,0x27,0x00,0x62,0x18,0x24,0xa0,0x83,0x00,0x00,
+0x92,0x45,0x00,0x08,0x00,0x00,0x00,0x00,0x30,0xa5,0x00,0xff,0x14,0xa0,0x00,0x7f,
+0x24,0x02,0x00,0x01,0xa2,0x40,0x00,0x04,0x86,0x43,0x00,0x0c,0x27,0x93,0x96,0x44,
+0x96,0x47,0x00,0x0c,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x28,0x80,
+0x00,0xb3,0x18,0x21,0x8c,0x64,0x00,0x18,0x00,0x00,0x00,0x00,0x8c,0x82,0x00,0x04,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x10,0x10,0x40,0x00,0x64,0x00,0x00,0x00,0x00,
+0x00,0x07,0x1c,0x00,0x00,0x03,0x1c,0x03,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x53,0x10,0x21,0x8c,0x43,0x00,0x18,0x93,0x82,0x91,0x51,
+0x8c,0x64,0x00,0x04,0x30,0x42,0x00,0x01,0x00,0x04,0x21,0x42,0x14,0x40,0x00,0x4d,
+0x30,0x90,0x00,0x01,0x00,0x07,0x2c,0x00,0x00,0x05,0x2c,0x03,0x0c,0x00,0x1f,0xdd,
+0x02,0x20,0x20,0x21,0x96,0x26,0x00,0x06,0x12,0x00,0x00,0x14,0x30,0xc5,0xff,0xff,
+0x02,0x60,0x90,0x21,0x00,0x05,0x10,0xc0,0x00,0x45,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x52,0x18,0x21,0x92,0x22,0x00,0x0a,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x0b,
+0x02,0x20,0x20,0x21,0x8c,0x63,0x00,0x18,0x00,0x00,0x00,0x00,0x8c,0x62,0x00,0x04,
+0x00,0x00,0x00,0x00,0x00,0x02,0x11,0x42,0x0c,0x00,0x1f,0xdd,0x30,0x50,0x00,0x01,
+0x96,0x26,0x00,0x06,0x16,0x00,0xff,0xef,0x30,0xc5,0xff,0xff,0x92,0x22,0x00,0x04,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x0d,0x24,0x02,0x00,0x01,0xa2,0x22,0x00,0x17,
+0x92,0x22,0x00,0x17,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x05,0x00,0x00,0x00,0x00,
+0xa6,0x26,0x00,0x14,0x92,0x22,0x00,0x16,0x08,0x00,0x15,0x5f,0x30,0x42,0x00,0xc3,
+0x96,0x22,0x00,0x00,0x08,0x00,0x16,0x75,0xa6,0x22,0x00,0x14,0x92,0x22,0x00,0x0a,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0x16,0x70,
+0xa2,0x20,0x00,0x17,0x96,0x24,0x00,0x00,0x30,0xc5,0xff,0xff,0x00,0x05,0x18,0xc0,
+0x00,0x04,0x10,0xc0,0x00,0x44,0x10,0x21,0x00,0x65,0x18,0x21,0x27,0x84,0x96,0x40,
+0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x21,0x00,0x03,0x18,0x80,0x8c,0x45,0x00,0x08,
+0x00,0x64,0x18,0x21,0x8c,0x64,0x00,0x08,0x3c,0x02,0x80,0x00,0x00,0xa2,0x38,0x24,
+0x10,0xe0,0x00,0x08,0x00,0x82,0x10,0x24,0x10,0x40,0x00,0x04,0x00,0x00,0x18,0x21,
+0x10,0xe0,0x00,0x02,0x24,0x03,0x00,0x01,0x00,0x85,0x18,0x2b,0x08,0x00,0x16,0x70,
+0xa2,0x23,0x00,0x17,0x10,0x40,0xff,0xfd,0x00,0x85,0x18,0x2b,0x08,0x00,0x16,0x94,
+0x00,0x00,0x00,0x00,0x24,0x05,0x00,0x24,0xf0,0xe5,0x00,0x06,0x00,0x00,0x28,0x12,
+0x27,0x82,0x96,0x40,0x00,0xa2,0x28,0x21,0x0c,0x00,0x01,0x49,0x00,0x00,0x20,0x21,
+0x96,0x47,0x00,0x0c,0x08,0x00,0x16,0x52,0x00,0x07,0x2c,0x00,0x27,0x83,0x96,0x50,
+0x27,0x82,0x96,0x58,0x00,0xa2,0x10,0x21,0x00,0xa3,0x18,0x21,0x90,0x44,0x00,0x00,
+0x90,0x65,0x00,0x05,0x24,0x07,0x00,0x01,0x0c,0x00,0x25,0xc4,0x00,0x00,0x30,0x21,
+0x96,0x47,0x00,0x0c,0x08,0x00,0x16,0x45,0x00,0x07,0x1c,0x00,0x10,0xa2,0x00,0x09,
+0x24,0x02,0x00,0x02,0x10,0xa2,0x00,0x05,0x24,0x02,0x00,0x03,0x14,0xa2,0xff,0x7e,
+0x00,0x00,0x00,0x00,0x08,0x00,0x16,0x36,0xa2,0x40,0x00,0x07,0x08,0x00,0x16,0x36,
+0xa2,0x40,0x00,0x06,0x08,0x00,0x16,0x36,0xa2,0x40,0x00,0x05,0x14,0x40,0xff,0x72,
+0x3c,0x04,0xb0,0x05,0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,0x30,0xa5,0x00,0x0f,
+0x24,0x02,0x00,0x80,0x08,0x00,0x16,0x2d,0x00,0xa2,0x10,0x07,0x14,0x40,0xfe,0xc4,
+0x00,0x00,0x00,0x00,0x3c,0x04,0xb0,0x05,0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,
+0x30,0xa5,0x00,0x0f,0x24,0x02,0x00,0x80,0x08,0x00,0x15,0x88,0x00,0xa2,0x10,0x07,
+0x84,0x83,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x96,0x44,0x00,0x43,0x10,0x21,0x8c,0x47,0x00,0x18,
+0x00,0x00,0x00,0x00,0x8c,0xe6,0x00,0x08,0x0c,0x00,0x13,0xe2,0x00,0x00,0x00,0x00,
+0x02,0x40,0x20,0x21,0x00,0x00,0x28,0x21,0x00,0x00,0x30,0x21,0x00,0x00,0x38,0x21,
+0x0c,0x00,0x20,0xdf,0xaf,0xa2,0x00,0x10,0x00,0x02,0x1e,0x00,0x14,0x60,0xfe,0x7c,
+0xa2,0x22,0x00,0x12,0x92,0x43,0x00,0x08,0x00,0x00,0x00,0x00,0x14,0x60,0x00,0x40,
+0x24,0x02,0x00,0x01,0xa2,0x40,0x00,0x04,0x92,0x28,0x00,0x04,0x00,0x00,0x00,0x00,
+0x15,0x00,0x00,0x19,0x24,0x02,0x00,0x01,0x92,0x27,0x00,0x0a,0xa2,0x22,0x00,0x17,
+0x92,0x22,0x00,0x17,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x10,0x00,0x00,0x00,0x00,
+0x96,0x22,0x00,0x06,0x00,0x00,0x00,0x00,0xa6,0x22,0x00,0x14,0x92,0x22,0x00,0x16,
+0x30,0xe3,0x00,0xff,0x30,0x42,0x00,0xc0,0x10,0x60,0x00,0x03,0xa2,0x22,0x00,0x16,
+0x34,0x42,0x00,0x01,0xa2,0x22,0x00,0x16,0x11,0x00,0xfe,0x61,0x00,0x00,0x00,0x00,
+0x92,0x22,0x00,0x16,0x08,0x00,0x15,0x5f,0x34,0x42,0x00,0x02,0x96,0x22,0x00,0x00,
+0x08,0x00,0x16,0xf7,0xa6,0x22,0x00,0x14,0x92,0x27,0x00,0x0a,0x00,0x00,0x00,0x00,
+0x14,0xe0,0x00,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0x16,0xf0,0xa2,0x20,0x00,0x17,
+0x96,0x24,0x00,0x00,0x96,0x25,0x00,0x06,0x27,0x86,0x96,0x40,0x00,0x04,0x18,0xc0,
+0x00,0x64,0x18,0x21,0x00,0x05,0x10,0xc0,0x00,0x45,0x10,0x21,0x00,0x03,0x18,0x80,
+0x00,0x66,0x18,0x21,0x00,0x02,0x10,0x80,0x00,0x46,0x10,0x21,0x8c,0x65,0x00,0x08,
+0x8c,0x44,0x00,0x08,0x3c,0x03,0x80,0x00,0x00,0xa3,0x30,0x24,0x10,0xc0,0x00,0x08,
+0x00,0x83,0x10,0x24,0x10,0x40,0x00,0x04,0x00,0x00,0x18,0x21,0x10,0xc0,0x00,0x02,
+0x24,0x03,0x00,0x01,0x00,0x85,0x18,0x2b,0x08,0x00,0x16,0xf0,0xa2,0x23,0x00,0x17,
+0x10,0x40,0xff,0xfd,0x00,0x85,0x18,0x2b,0x08,0x00,0x17,0x1f,0x00,0x00,0x00,0x00,
+0x10,0x62,0x00,0x09,0x24,0x02,0x00,0x02,0x10,0x62,0x00,0x05,0x24,0x02,0x00,0x03,
+0x14,0x62,0xff,0xbd,0x00,0x00,0x00,0x00,0x08,0x00,0x16,0xea,0xa2,0x40,0x00,0x07,
+0x08,0x00,0x16,0xea,0xa2,0x40,0x00,0x06,0x08,0x00,0x16,0xea,0xa2,0x40,0x00,0x05,
+0x3c,0x02,0x80,0x00,0x00,0x82,0x30,0x24,0x10,0xc0,0x00,0x08,0x00,0xa2,0x18,0x24,
+0x10,0x60,0x00,0x04,0x00,0x00,0x10,0x21,0x10,0xc0,0x00,0x02,0x24,0x02,0x00,0x01,
+0x00,0xa4,0x10,0x2b,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x10,0x60,0xff,0xfd,
+0x00,0xa4,0x10,0x2b,0x08,0x00,0x17,0x3a,0x00,0x00,0x00,0x00,0x30,0x82,0xff,0xff,
+0x00,0x02,0x18,0xc0,0x00,0x62,0x18,0x21,0x27,0x84,0x96,0x50,0x00,0x03,0x18,0x80,
+0x00,0x64,0x18,0x21,0x80,0x66,0x00,0x06,0x00,0x02,0x12,0x00,0x3c,0x03,0xb0,0x00,
+0x00,0x46,0x10,0x21,0x00,0x45,0x10,0x21,0x03,0xe0,0x00,0x08,0x00,0x43,0x10,0x21,
+0x27,0xbd,0xff,0xe0,0x30,0x82,0x00,0x7c,0x30,0x84,0xff,0x00,0xaf,0xbf,0x00,0x1c,
+0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0x14,0x40,0x00,0x41,
+0x00,0x04,0x22,0x03,0x24,0x02,0x00,0x04,0x3c,0x10,0xb0,0x03,0x8e,0x10,0x00,0x00,
+0x10,0x82,0x00,0x32,0x24,0x02,0x00,0x08,0x10,0x82,0x00,0x03,0x32,0x02,0x00,0x20,
+0x08,0x00,0x17,0x60,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x17,0x3c,0x02,0xb0,0x06,
+0x34,0x42,0x80,0x24,0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x67,0x00,0xff,
+0x10,0xe0,0x00,0x23,0x00,0x00,0x88,0x21,0x8f,0x85,0x96,0x20,0x00,0x40,0x30,0x21,
+0x94,0xa2,0x00,0x08,0x8c,0xc3,0x00,0x00,0x26,0x31,0x00,0x01,0x24,0x42,0x00,0x02,
+0x30,0x42,0x01,0xff,0x34,0x63,0x01,0x00,0x02,0x27,0x20,0x2a,0xa4,0xa2,0x00,0x08,
+0x14,0x80,0xff,0xf7,0xac,0xc3,0x00,0x00,0x84,0xa3,0x00,0x08,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x00,0x30,0xac,0x43,0x00,0x00,0x27,0x92,0xba,0x40,0x24,0x11,0x00,0x12,
+0x8e,0x44,0x00,0x00,0x26,0x31,0xff,0xff,0x90,0x82,0x00,0x10,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x03,0x26,0x52,0x00,0x04,0x0c,0x00,0x1d,0x55,0x00,0x00,0x00,0x00,
+0x06,0x21,0xff,0xf7,0x24,0x02,0xff,0xdf,0x02,0x02,0x80,0x24,0x3c,0x01,0xb0,0x03,
+0x0c,0x00,0x18,0x18,0xac,0x30,0x00,0x00,0x08,0x00,0x17,0x60,0x00,0x00,0x00,0x00,
+0x8f,0x85,0x96,0x20,0x08,0x00,0x17,0x76,0x00,0x00,0x00,0x00,0x24,0x02,0xff,0x95,
+0x3c,0x03,0xb0,0x03,0x02,0x02,0x80,0x24,0x34,0x63,0x00,0x30,0x3c,0x01,0xb0,0x03,
+0xac,0x30,0x00,0x00,0x0c,0x00,0x17,0xe1,0xac,0x60,0x00,0x00,0x08,0x00,0x17,0x60,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0x50,0x08,0x00,0x17,0x60,
+0xac,0x46,0x00,0x00,0xaf,0xa7,0x00,0x0c,0xaf,0xa4,0x00,0x00,0xaf,0xa5,0x00,0x04,
+0xaf,0xa6,0x00,0x08,0x27,0xbd,0xfe,0xe8,0x00,0x80,0x28,0x21,0x27,0xa6,0x01,0x1c,
+0x27,0xa4,0x00,0x10,0xaf,0xbf,0x01,0x14,0x0c,0x00,0x29,0xa9,0xaf,0xb0,0x01,0x10,
+0x00,0x40,0x80,0x21,0x0c,0x00,0x17,0xb0,0x27,0xa4,0x00,0x10,0x02,0x00,0x10,0x21,
+0x8f,0xbf,0x01,0x14,0x8f,0xb0,0x01,0x10,0x03,0xe0,0x00,0x08,0x27,0xbd,0x01,0x18,
+0x93,0x83,0x87,0xec,0x27,0xbd,0xff,0xe8,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,
+0x14,0x60,0x00,0x14,0x00,0x80,0x80,0x21,0x80,0x82,0x00,0x00,0x90,0x84,0x00,0x00,
+0x14,0x40,0x00,0x05,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x00,0x04,0x26,0x00,0x00,0x04,0x26,0x03,
+0x30,0x84,0xff,0xff,0x0c,0x00,0x17,0xd0,0x26,0x10,0x00,0x01,0x92,0x03,0x00,0x00,
+0x00,0x00,0x00,0x00,0x14,0x60,0xff,0xf8,0x00,0x60,0x20,0x21,0x08,0x00,0x17,0xba,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x14,0x43,0xff,0xef,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x04,0x52,0x00,0x00,0x00,0x00,0x08,0x00,0x17,0xba,0x00,0x00,0x00,0x00,
+0x30,0x84,0xff,0xff,0x48,0x84,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x27,0xbd,0xff,0xe8,0xaf,0xbf,0x00,0x10,0x0c,0x00,0x29,0x11,0x00,0x00,0x00,0x00,
+0x8f,0xbf,0x00,0x10,0x00,0x02,0x14,0x00,0x00,0x02,0x14,0x03,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x03,0xe0,0x00,0x08,0x24,0x02,0x00,0x01,0x03,0xe0,0x00,0x08,
+0x24,0x02,0x00,0x01,0x3c,0x0a,0x80,0x00,0x25,0x4a,0x5f,0x84,0x3c,0x0b,0xb0,0x03,
+0xad,0x6a,0x00,0x20,0x3c,0x08,0x80,0x01,0x25,0x08,0x00,0x00,0x3c,0x09,0x80,0x01,
+0x25,0x29,0x0b,0x2c,0x11,0x09,0x00,0x10,0x00,0x00,0x00,0x00,0x3c,0x0a,0x80,0x00,
+0x25,0x4a,0x5f,0xac,0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,0x3c,0x08,0xb0,0x06,
+0x35,0x08,0x80,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x8d,0x09,0x00,0x00,
+0x00,0x00,0x00,0x00,0x31,0x29,0x00,0x01,0x00,0x00,0x00,0x00,0x24,0x01,0x00,0x01,
+0x15,0x21,0xff,0xf2,0x00,0x00,0x00,0x00,0x3c,0x0a,0x80,0x00,0x25,0x4a,0x5f,0xe8,
+0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,0x3c,0x02,0xb0,0x03,0x8c,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0x34,0x63,0x00,0x40,0x00,0x00,0x00,0x00,0xac,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0x3c,0x0a,0x80,0x00,0x25,0x4a,0x60,0x14,0x3c,0x0b,0xb0,0x03,
+0xad,0x6a,0x00,0x20,0x3c,0x02,0x80,0x01,0x24,0x42,0x00,0x00,0x3c,0x03,0x80,0x01,
+0x24,0x63,0x0b,0x2c,0x3c,0x04,0xb0,0x00,0x8c,0x85,0x00,0x00,0x00,0x00,0x00,0x00,
+0xac,0x45,0x00,0x00,0x24,0x42,0x00,0x04,0x24,0x84,0x00,0x04,0x00,0x43,0x08,0x2a,
+0x14,0x20,0xff,0xf9,0x00,0x00,0x00,0x00,0x0c,0x00,0x18,0x18,0x00,0x00,0x00,0x00,
+0x3c,0x0a,0x80,0x00,0x25,0x4a,0x60,0x60,0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,
+0x3c,0x02,0x80,0x01,0x24,0x42,0x0b,0x30,0x3c,0x03,0x80,0x01,0x24,0x63,0x42,0x50,
+0xac,0x40,0x00,0x00,0xac,0x40,0x00,0x04,0xac,0x40,0x00,0x08,0xac,0x40,0x00,0x0c,
+0x24,0x42,0x00,0x10,0x00,0x43,0x08,0x2a,0x14,0x20,0xff,0xf9,0x00,0x00,0x00,0x00,
+0x3c,0x0a,0x80,0x00,0x25,0x4a,0x60,0xa0,0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,
+0x3c,0x1c,0x80,0x01,0x27,0x9c,0x7f,0xf0,0x27,0x9d,0x92,0x20,0x00,0x00,0x00,0x00,
+0x27,0x9d,0x96,0x08,0x3c,0x0a,0x80,0x00,0x25,0x4a,0x60,0xc4,0x3c,0x0b,0xb0,0x03,
+0xad,0x6a,0x00,0x20,0x40,0x80,0x68,0x00,0x40,0x08,0x60,0x00,0x00,0x00,0x00,0x00,
+0x35,0x08,0xff,0x01,0x40,0x88,0x60,0x00,0x00,0x00,0x00,0x00,0x0c,0x00,0x1a,0x4d,
+0x00,0x00,0x00,0x00,0x24,0x84,0xf8,0x00,0x30,0x87,0x00,0x03,0x00,0x04,0x30,0x40,
+0x00,0xc7,0x20,0x23,0x3c,0x02,0xb0,0x0a,0x27,0xbd,0xff,0xe0,0x24,0x03,0xff,0xff,
+0x00,0x82,0x20,0x21,0xaf,0xb1,0x00,0x14,0xac,0x83,0x10,0x00,0xaf,0xbf,0x00,0x18,
+0xaf,0xb0,0x00,0x10,0x00,0xa0,0x88,0x21,0x24,0x03,0x00,0x01,0x8c,0x82,0x10,0x00,
+0x00,0x00,0x00,0x00,0x14,0x43,0xff,0xfd,0x00,0xc7,0x10,0x23,0x3c,0x03,0xb0,0x0a,
+0x00,0x43,0x10,0x21,0x8c,0x50,0x00,0x00,0x0c,0x00,0x18,0x95,0x02,0x20,0x20,0x21,
+0x02,0x11,0x80,0x24,0x00,0x50,0x80,0x06,0x02,0x00,0x10,0x21,0x8f,0xbf,0x00,0x18,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x27,0xbd,0xff,0xd8,
+0xaf,0xb2,0x00,0x18,0x00,0xa0,0x90,0x21,0x24,0x05,0xff,0xff,0xaf,0xb3,0x00,0x1c,
+0xaf,0xbf,0x00,0x20,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0x00,0xc0,0x98,0x21,
+0x12,0x45,0x00,0x23,0x24,0x84,0xf8,0x00,0x30,0x83,0x00,0x03,0x00,0x04,0x10,0x40,
+0x00,0x40,0x88,0x21,0x00,0x60,0x20,0x21,0x00,0x43,0x10,0x23,0x3c,0x03,0xb0,0x0a,
+0x00,0x43,0x10,0x21,0xac,0x45,0x10,0x00,0x00,0x40,0x18,0x21,0x24,0x05,0x00,0x01,
+0x8c,0x62,0x10,0x00,0x00,0x00,0x00,0x00,0x14,0x45,0xff,0xfd,0x3c,0x02,0xb0,0x0a,
+0x02,0x24,0x88,0x23,0x02,0x22,0x88,0x21,0x8e,0x30,0x00,0x00,0x0c,0x00,0x18,0x95,
+0x02,0x40,0x20,0x21,0x00,0x12,0x18,0x27,0x02,0x03,0x80,0x24,0x00,0x53,0x10,0x04,
+0x02,0x02,0x80,0x25,0xae,0x30,0x00,0x00,0x24,0x03,0x00,0x01,0x8e,0x22,0x10,0x00,
+0x00,0x00,0x00,0x00,0x14,0x43,0xff,0xfd,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x20,
+0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,
+0x30,0x82,0x00,0x03,0x00,0x04,0x18,0x40,0x00,0x62,0x18,0x23,0x3c,0x04,0xb0,0x0a,
+0x00,0x64,0x18,0x21,0xac,0x66,0x00,0x00,0x24,0x04,0x00,0x01,0x8c,0x62,0x10,0x00,
+0x00,0x00,0x00,0x00,0x14,0x44,0xff,0xfd,0x00,0x00,0x00,0x00,0x08,0x00,0x18,0x83,
+0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x21,0x00,0x64,0x10,0x06,0x30,0x42,0x00,0x01,
+0x14,0x40,0x00,0x05,0x00,0x00,0x00,0x00,0x24,0x63,0x00,0x01,0x2c,0x62,0x00,0x20,
+0x14,0x40,0xff,0xf9,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x60,0x10,0x21,
+0x27,0xbd,0xff,0xe0,0x3c,0x03,0xb0,0x05,0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x1c,0x00,0x80,0x80,0x21,0x00,0xa0,0x88,0x21,
+0x00,0xc0,0x90,0x21,0x34,0x63,0x02,0x2e,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0x01,0x14,0x40,0xff,0xfc,0x24,0x04,0x08,0x24,0x3c,0x05,0x00,0xc0,
+0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x03,0x24,0x04,0x08,0x34,0x3c,0x05,0x00,0xc0,
+0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x03,0x82,0x02,0x00,0x13,0x00,0x11,0x24,0x00,
+0x3c,0x03,0xc0,0x00,0x00,0x02,0x12,0x00,0x00,0x44,0x10,0x21,0x3c,0x04,0xb0,0x05,
+0x24,0x42,0x00,0x09,0x34,0x84,0x04,0x20,0x34,0x63,0x04,0x00,0x3c,0x05,0xb0,0x05,
+0x3c,0x06,0xb0,0x05,0xac,0x82,0x00,0x00,0x24,0x07,0x00,0x01,0x02,0x43,0x18,0x21,
+0x34,0xa5,0x04,0x24,0x34,0xc6,0x02,0x28,0x24,0x02,0x00,0x20,0xac,0xa3,0x00,0x00,
+0xae,0x07,0x00,0x3c,0xa0,0xc2,0x00,0x00,0xa2,0x07,0x00,0x11,0x3c,0x02,0xb0,0x05,
+0x34,0x42,0x02,0x2e,0x90,0x43,0x00,0x00,0x24,0x04,0x08,0x24,0x3c,0x05,0x00,0xc0,
+0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x01,0x24,0x04,0x08,0x34,0x3c,0x05,0x00,0xc0,
+0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x01,0x8f,0xbf,0x00,0x1c,0x8f,0xb2,0x00,0x18,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x24,0x02,0x00,0x06,
+0xac,0x82,0x00,0x0c,0xa0,0x80,0x00,0x50,0xac,0x80,0x00,0x00,0xac,0x80,0x00,0x04,
+0xac,0x80,0x00,0x08,0xac,0x80,0x00,0x14,0xac,0x80,0x00,0x18,0xac,0x80,0x00,0x1c,
+0xa4,0x80,0x00,0x20,0xac,0x80,0x00,0x24,0xac,0x80,0x00,0x28,0xac,0x80,0x00,0x2c,
+0xa0,0x80,0x00,0x30,0xa0,0x80,0x00,0x31,0xac,0x80,0x00,0x34,0xac,0x80,0x00,0x38,
+0xa0,0x80,0x00,0x3c,0xac,0x82,0x00,0x10,0xa0,0x80,0x00,0x44,0xac,0x80,0x00,0x48,
+0x03,0xe0,0x00,0x08,0xac,0x80,0x00,0x4c,0x3c,0x04,0xb0,0x06,0x34,0x84,0x80,0x00,
+0x8c,0x83,0x00,0x00,0x3c,0x02,0x12,0x00,0x3c,0x05,0xb0,0x03,0x00,0x62,0x18,0x25,
+0x34,0xa5,0x00,0x8b,0x24,0x02,0xff,0x80,0xac,0x83,0x00,0x00,0x03,0xe0,0x00,0x08,
+0xa0,0xa2,0x00,0x00,0x3c,0x04,0xb0,0x03,0x34,0x84,0x00,0x0b,0x24,0x02,0x00,0x22,
+0x3c,0x05,0xb0,0x01,0x3c,0x06,0x45,0x67,0x3c,0x0a,0xb0,0x09,0xa0,0x82,0x00,0x00,
+0x34,0xa5,0x00,0x04,0x34,0xc6,0x89,0xaa,0x35,0x4a,0x00,0x04,0x24,0x02,0x01,0x23,
+0x3c,0x0b,0xb0,0x09,0x3c,0x07,0x01,0x23,0x3c,0x0c,0xb0,0x09,0x3c,0x01,0xb0,0x01,
+0xac,0x20,0x00,0x00,0x27,0xbd,0xff,0xe0,0xac,0xa0,0x00,0x00,0x35,0x6b,0x00,0x08,
+0x3c,0x01,0xb0,0x09,0xac,0x26,0x00,0x00,0x34,0xe7,0x45,0x66,0xa5,0x42,0x00,0x00,
+0x35,0x8c,0x00,0x0c,0x24,0x02,0xcd,0xef,0x3c,0x0d,0xb0,0x09,0x3c,0x08,0xcd,0xef,
+0x3c,0x0e,0xb0,0x09,0xad,0x67,0x00,0x00,0xaf,0xb7,0x00,0x1c,0xa5,0x82,0x00,0x00,
+0xaf,0xb6,0x00,0x18,0xaf,0xb5,0x00,0x14,0xaf,0xb4,0x00,0x10,0xaf,0xb3,0x00,0x0c,
+0xaf,0xb2,0x00,0x08,0xaf,0xb1,0x00,0x04,0xaf,0xb0,0x00,0x00,0x35,0xad,0x00,0x10,
+0x35,0x08,0x01,0x22,0x35,0xce,0x00,0x14,0x24,0x02,0x89,0xab,0x3c,0x0f,0xb0,0x09,
+0x3c,0x09,0x89,0xab,0x3c,0x10,0xb0,0x09,0x3c,0x11,0xb0,0x09,0x3c,0x12,0xb0,0x09,
+0x3c,0x13,0xb0,0x09,0x3c,0x14,0xb0,0x09,0x3c,0x15,0xb0,0x09,0x3c,0x16,0xb0,0x09,
+0x3c,0x17,0xb0,0x09,0xad,0xa8,0x00,0x00,0x24,0x03,0xff,0xff,0xa5,0xc2,0x00,0x00,
+0x35,0xef,0x00,0x18,0x35,0x29,0xcd,0xee,0x36,0x10,0x00,0x1c,0x36,0x31,0x00,0x20,
+0x36,0x52,0x00,0x24,0x36,0x73,0x00,0x28,0x36,0x94,0x00,0x2c,0x36,0xb5,0x00,0x30,
+0x36,0xd6,0x00,0x34,0x36,0xf7,0x00,0x38,0x24,0x02,0x45,0x67,0xad,0xe9,0x00,0x00,
+0xa6,0x02,0x00,0x00,0xae,0x23,0x00,0x00,0x8f,0xb0,0x00,0x00,0xa6,0x43,0x00,0x00,
+0x8f,0xb1,0x00,0x04,0xae,0x63,0x00,0x00,0x8f,0xb2,0x00,0x08,0xa6,0x83,0x00,0x00,
+0x8f,0xb3,0x00,0x0c,0xae,0xa3,0x00,0x00,0x8f,0xb4,0x00,0x10,0xa6,0xc3,0x00,0x00,
+0x8f,0xb5,0x00,0x14,0xae,0xe3,0x00,0x00,0x7b,0xb6,0x00,0xfc,0x3c,0x18,0xb0,0x09,
+0x37,0x18,0x00,0x3c,0xa7,0x03,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x65,0x50,
+0xac,0x62,0x00,0x00,0x8c,0x83,0x00,0x34,0x34,0x02,0xff,0xff,0x00,0x43,0x10,0x2a,
+0x14,0x40,0x00,0xed,0x00,0x80,0x28,0x21,0x8c,0x84,0x00,0x08,0x24,0x02,0x00,0x03,
+0x10,0x82,0x00,0xe0,0x00,0x00,0x00,0x00,0x8c,0xa2,0x00,0x2c,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x38,0x24,0x02,0x00,0x06,0x3c,0x03,0xb0,0x05,0x34,0x63,0x04,0x50,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0x14,0x40,0x00,0xc6,
+0xac,0xa2,0x00,0x2c,0x24,0x02,0x00,0x01,0x10,0x82,0x00,0xc5,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0x82,0x00,0xb3,0x00,0x00,0x00,0x00,0x8c,0xa6,0x00,0x04,
+0x24,0x02,0x00,0x02,0x10,0xc2,0x00,0xa9,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x00,0xd0,0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x61,0x00,0x16,
+0x3c,0x03,0xb0,0x05,0x34,0x63,0x02,0x2e,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0x01,0x14,0x40,0x00,0x10,0x3c,0x02,0xb0,0x05,0x34,0x42,0x02,0x42,
+0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x60,0x00,0x0b,0x00,0x00,0x00,0x00,
+0x80,0xa2,0x00,0x50,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x07,0x00,0x00,0x00,0x00,
+0x14,0x80,0x00,0x05,0x24,0x02,0x00,0x0e,0x24,0x03,0x00,0x01,0xac,0xa2,0x00,0x00,
+0x03,0xe0,0x00,0x08,0xa0,0xa3,0x00,0x50,0x80,0xa2,0x00,0x31,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x0a,0x3c,0x02,0xb0,0x06,0x34,0x42,0x80,0x18,0x8c,0x43,0x00,0x00,
+0x3c,0x04,0xf0,0x00,0x3c,0x02,0x80,0x00,0x00,0x64,0x18,0x24,0x10,0x62,0x00,0x03,
+0x24,0x02,0x00,0x09,0x03,0xe0,0x00,0x08,0xac,0xa2,0x00,0x00,0x8c,0xa2,0x00,0x40,
+0x00,0x00,0x00,0x00,0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x60,0x00,0x09,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0xb0,0x05,0x34,0x42,0x02,0x2c,0x8c,0x43,0x00,0x00,
+0x3c,0x04,0x00,0x02,0x00,0x64,0x18,0x24,0x14,0x60,0xff,0xf2,0x24,0x02,0x00,0x10,
+0x3c,0x03,0xb0,0x03,0x34,0x63,0x02,0x01,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0x80,0x10,0x40,0x00,0x0e,0x00,0x00,0x00,0x00,0x8c,0xa3,0x00,0x0c,
+0x00,0x00,0x00,0x00,0xac,0xa3,0x00,0x10,0x3c,0x02,0xb0,0x03,0x90,0x42,0x02,0x01,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x0f,0xac,0xa2,0x00,0x0c,0x90,0xa3,0x00,0x0f,
+0x24,0x02,0x00,0x0d,0x3c,0x01,0xb0,0x03,0x08,0x00,0x19,0x9d,0xa0,0x23,0x02,0x01,
+0x3c,0x02,0xb0,0x09,0x34,0x42,0x01,0x80,0x90,0x44,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x04,0x1e,0x00,0x00,0x03,0x1e,0x03,0x10,0x60,0x00,0x15,0xa0,0xa4,0x00,0x44,
+0x24,0x02,0x00,0x01,0x10,0x62,0x00,0x0b,0x24,0x02,0x00,0x02,0x10,0x62,0x00,0x03,
+0x24,0x03,0x00,0x0d,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x8c,0xa2,0x00,0x0c,
+0xac,0xa3,0x00,0x00,0x24,0x03,0x00,0x04,0xac,0xa2,0x00,0x10,0x03,0xe0,0x00,0x08,
+0xac,0xa3,0x00,0x0c,0x24,0x02,0x00,0x0d,0xac,0xa2,0x00,0x00,0x24,0x03,0x00,0x04,
+0x24,0x02,0x00,0x06,0xac,0xa3,0x00,0x10,0x03,0xe0,0x00,0x08,0xac,0xa2,0x00,0x0c,
+0x8c,0xa2,0x00,0x14,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x09,0x24,0x02,0x00,0x01,
+0x3c,0x03,0xb0,0x09,0x34,0x63,0x01,0x60,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0xff,0x10,0x40,0x00,0x05,0xac,0xa2,0x00,0x14,0x24,0x02,0x00,0x01,
+0xac,0xa2,0x00,0x00,0x03,0xe0,0x00,0x08,0xac,0xa0,0x00,0x14,0x8c,0xa3,0x00,0x38,
+0x24,0x04,0x00,0x01,0x10,0x64,0x00,0x2d,0x24,0x02,0x00,0x02,0x10,0x60,0x00,0x19,
+0x00,0x00,0x00,0x00,0x10,0x62,0x00,0x10,0x24,0x02,0x00,0x04,0x10,0x62,0x00,0x04,
+0x00,0x00,0x00,0x00,0xac,0xa0,0x00,0x38,0x03,0xe0,0x00,0x08,0xac,0xa0,0x00,0x00,
+0x10,0xc4,0x00,0x07,0x24,0x02,0x00,0x03,0x80,0xa2,0x00,0x30,0x00,0x00,0x00,0x00,
+0x00,0x02,0x18,0x0b,0xac,0xa3,0x00,0x00,0x03,0xe0,0x00,0x08,0xac,0xa0,0x00,0x38,
+0x08,0x00,0x19,0xfe,0xac,0xa2,0x00,0x00,0x10,0xc4,0x00,0x02,0x24,0x02,0x00,0x03,
+0x24,0x02,0x00,0x0c,0xac,0xa2,0x00,0x00,0x24,0x02,0x00,0x04,0x03,0xe0,0x00,0x08,
+0xac,0xa2,0x00,0x38,0x10,0xc4,0x00,0x0e,0x3c,0x03,0xb0,0x06,0x34,0x63,0x80,0x24,
+0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0x10,0x40,0x00,0x06,
+0xac,0xa2,0x00,0x18,0x24,0x02,0x00,0x02,0xac,0xa2,0x00,0x00,0xac,0xa0,0x00,0x18,
+0x08,0x00,0x1a,0x07,0x24,0x02,0x00,0x01,0x08,0x00,0x1a,0x14,0xac,0xa0,0x00,0x00,
+0x24,0x02,0x00,0x03,0x08,0x00,0x1a,0x14,0xac,0xa2,0x00,0x00,0x24,0x03,0x00,0x0b,
+0xac,0xa2,0x00,0x38,0x03,0xe0,0x00,0x08,0xac,0xa3,0x00,0x00,0x80,0xa2,0x00,0x30,
+0x00,0x00,0x00,0x00,0x14,0x40,0xff,0x55,0x24,0x02,0x00,0x04,0x08,0x00,0x19,0x9d,
+0x00,0x00,0x00,0x00,0x84,0xa2,0x00,0x20,0x00,0x00,0x00,0x00,0x10,0x40,0xff,0x75,
+0x24,0x02,0x00,0x06,0x3c,0x02,0xb0,0x05,0x34,0x42,0x02,0x2e,0x90,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x01,0x30,0x63,0x00,0xff,0x00,0x60,0x10,0x21,
+0x14,0x40,0xff,0x42,0xa4,0xa3,0x00,0x20,0x08,0x00,0x19,0x9d,0x24,0x02,0x00,0x06,
+0x8c,0xa2,0x00,0x1c,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0x66,0x24,0x02,0x00,0x05,
+0x3c,0x03,0xb0,0x05,0x34,0x63,0x02,0x2c,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0xff,0x10,0x40,0xff,0x32,0xac,0xa2,0x00,0x1c,0x08,0x00,0x19,0x9d,
+0x24,0x02,0x00,0x05,0x3c,0x02,0xb0,0x05,0x8c,0x42,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x02,0x17,0x42,0x30,0x42,0x00,0x01,0x14,0x40,0xff,0x56,0x24,0x02,0x00,0x06,
+0x08,0x00,0x19,0x62,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x0a,0x03,0xe0,0x00,0x08,
+0xac,0x82,0x00,0x00,0x27,0xbd,0xff,0xd8,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,
+0x27,0x91,0x90,0xf8,0x27,0x90,0x8e,0x38,0xaf,0xbf,0x00,0x20,0xaf,0xb3,0x00,0x1c,
+0x0c,0x00,0x28,0x9e,0xaf,0xb2,0x00,0x18,0x0c,0x00,0x06,0x90,0x00,0x00,0x00,0x00,
+0xaf,0x91,0x92,0x10,0xaf,0x90,0x96,0x20,0x48,0x02,0x00,0x00,0x0c,0x00,0x18,0xf2,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x1c,0x9b,0x02,0x00,0x20,0x21,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x00,0x3a,0x94,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0xa3,0x83,0x96,0x24,
+0x0c,0x00,0x00,0x34,0x00,0x00,0x00,0x00,0x0c,0x00,0x18,0xfd,0x00,0x00,0x00,0x00,
+0x27,0x84,0x8c,0x78,0x0c,0x00,0x2c,0x78,0x00,0x00,0x00,0x00,0x0c,0x00,0x25,0x71,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x0c,0x0d,0x02,0x20,0x20,0x21,0x0c,0x00,0x01,0x39,
+0x00,0x00,0x00,0x00,0x27,0x84,0x8c,0x20,0x0c,0x00,0x18,0xdb,0x00,0x00,0x00,0x00,
+0x27,0x82,0x91,0x2c,0xaf,0x82,0x8c,0x60,0x0c,0x00,0x00,0x5f,0x00,0x00,0x00,0x00,
+0x3c,0x03,0xb0,0x03,0x34,0x63,0x01,0x08,0x3c,0x04,0xb0,0x09,0x3c,0x05,0xb0,0x09,
+0x8c,0x66,0x00,0x00,0x34,0x84,0x01,0x68,0x24,0x02,0xd1,0x10,0x34,0xa5,0x01,0x40,
+0x24,0x03,0x00,0x0a,0xa4,0x82,0x00,0x00,0xa4,0xa3,0x00,0x00,0x3c,0x04,0xb0,0x03,
+0x8c,0x82,0x00,0x00,0xaf,0x86,0x8c,0x18,0x34,0x42,0x00,0x20,0xac,0x82,0x00,0x00,
+0x0c,0x00,0x06,0xa1,0x00,0x00,0x00,0x00,0x3c,0x04,0xb0,0x05,0x0c,0x00,0x28,0xb6,
+0x34,0x84,0x00,0x04,0x8f,0x83,0x8c,0x20,0x00,0x00,0x00,0x00,0x2c,0x62,0x00,0x11,
+0x10,0x40,0xff,0xf7,0x00,0x03,0x10,0x80,0x3c,0x03,0x80,0x01,0x24,0x63,0x09,0x08,
+0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x08,
+0x00,0x00,0x00,0x00,0x27,0x84,0x8c,0x20,0x0c,0x00,0x19,0x54,0x00,0x00,0x00,0x00,
+0x8f,0x82,0x8c,0x54,0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x01,0xaf,0x82,0x8c,0x54,
+0x08,0x00,0x1a,0x88,0x00,0x00,0x00,0x00,0x27,0x84,0x8c,0x78,0x0c,0x00,0x2d,0xe5,
+0x00,0x00,0x00,0x00,0xa3,0x82,0x8c,0x51,0xaf,0x80,0x8c,0x20,0x08,0x00,0x1a,0x9c,
+0x00,0x00,0x00,0x00,0x27,0x84,0x8e,0x38,0x0c,0x00,0x1d,0xe0,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0xff,0x14,0x40,0x00,0x05,0x3c,0x03,0xb0,0x05,0xaf,0x80,0x8c,0x20,
+0xaf,0x80,0x8c,0x24,0x08,0x00,0x1a,0x9c,0x00,0x00,0x00,0x00,0x34,0x63,0x04,0x50,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0xaf,0x82,0x8c,0x4c,
+0x14,0x40,0x00,0x1e,0x24,0x02,0x00,0x01,0x8f,0x84,0x8c,0x28,0x00,0x00,0x00,0x00,
+0x10,0x82,0x00,0x1d,0x3c,0x03,0xb0,0x09,0x34,0x63,0x01,0x60,0x90,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0xaf,0x82,0x8c,0x34,0x14,0x40,0x00,0x13,
+0x24,0x02,0x00,0x01,0x24,0x02,0x00,0x02,0x10,0x82,0x00,0x07,0x3c,0x02,0xb0,0x05,
+0x24,0x02,0x00,0x01,0x24,0x03,0x00,0x03,0xaf,0x82,0x8c,0x24,0xaf,0x83,0x8c,0x20,
+0x08,0x00,0x1a,0x9c,0x00,0x00,0x00,0x00,0x34,0x42,0x02,0x2e,0x90,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x01,0x30,0x63,0x00,0xff,0x00,0x60,0x10,0x21,
+0xa7,0x83,0x8c,0x40,0x14,0x40,0xff,0xf3,0x24,0x02,0x00,0x01,0xaf,0x82,0x8c,0x24,
+0x08,0x00,0x1a,0xa6,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x05,0x34,0x63,0x02,0x2c,
+0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0xaf,0x82,0x8c,0x3c,
+0x14,0x40,0xff,0xf6,0x24,0x02,0x00,0x01,0x08,0x00,0x1a,0xbe,0x3c,0x03,0xb0,0x09,
+0x27,0x84,0x8e,0x38,0x0c,0x00,0x1f,0x44,0x00,0x00,0x00,0x00,0x83,0x82,0x8c,0x50,
+0x00,0x00,0x00,0x00,0x14,0x40,0xff,0xed,0x24,0x02,0x00,0x02,0x3c,0x03,0xb0,0x05,
+0x34,0x63,0x04,0x50,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,
+0xaf,0x82,0x8c,0x4c,0x14,0x40,0xff,0xe5,0x24,0x02,0x00,0x02,0x8f,0x84,0x8c,0x28,
+0x24,0x02,0x00,0x01,0x10,0x82,0x00,0x12,0x24,0x02,0x00,0x02,0x10,0x82,0x00,0x05,
+0x3c,0x02,0xb0,0x05,0x24,0x02,0x00,0x02,0xaf,0x82,0x8c,0x24,0x08,0x00,0x1a,0xcb,
+0x24,0x03,0x00,0x04,0x34,0x42,0x02,0x2e,0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x63,0x00,0x01,0x30,0x63,0x00,0xff,0x00,0x60,0x10,0x21,0xa7,0x83,0x8c,0x40,
+0x14,0x40,0xff,0xf4,0x00,0x00,0x00,0x00,0x08,0x00,0x1a,0xd7,0x24,0x02,0x00,0x02,
+0x3c,0x03,0xb0,0x05,0x34,0x63,0x02,0x2c,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0xff,0xaf,0x82,0x8c,0x3c,0x14,0x40,0xff,0xf7,0x00,0x00,0x00,0x00,
+0x08,0x00,0x1a,0xf7,0x24,0x02,0x00,0x02,0x27,0x84,0x90,0xf8,0x0c,0x00,0x10,0x1b,
+0x00,0x00,0x00,0x00,0x8f,0x83,0x8c,0x24,0xaf,0x82,0x8c,0x3c,0x38,0x64,0x00,0x02,
+0x00,0x04,0x18,0x0a,0xaf,0x83,0x8c,0x24,0x14,0x40,0x00,0x08,0x24,0x02,0x00,0x05,
+0x8f,0x82,0x91,0x38,0xaf,0x80,0x8c,0x20,0x10,0x40,0xff,0x7d,0x24,0x04,0x00,0x01,
+0xaf,0x84,0x8c,0x28,0x08,0x00,0x1a,0x9c,0x00,0x00,0x00,0x00,0xaf,0x82,0x8c,0x20,
+0x08,0x00,0x1a,0x9c,0x00,0x00,0x00,0x00,0x83,0x82,0x8c,0x70,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x02,0x24,0x02,0x00,0x20,0xaf,0x82,0x8c,0x3c,0x8f,0x85,0x8c,0x3c,
+0x27,0x84,0x90,0xf8,0x0c,0x00,0x12,0x01,0x00,0x00,0x00,0x00,0x00,0x02,0x1e,0x00,
+0xa3,0x82,0x8c,0x50,0xaf,0x80,0x8c,0x3c,0x10,0x60,0xff,0x73,0x3c,0x02,0xb0,0x05,
+0x34,0x42,0x02,0x2e,0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x01,
+0x30,0x63,0x00,0xff,0x00,0x60,0x10,0x21,0xa7,0x83,0x8c,0x40,0x10,0x40,0xff,0xe7,
+0x24,0x02,0x00,0x06,0x24,0x04,0x00,0x02,0xaf,0x84,0x8c,0x28,0x08,0x00,0x1a,0xa6,
+0x00,0x00,0x00,0x00,0x27,0x84,0x8c,0x20,0x27,0x85,0x90,0xf8,0x0c,0x00,0x12,0xc7,
+0x00,0x00,0x00,0x00,0x8f,0x82,0x8c,0x44,0xaf,0x80,0x8c,0x4c,0x14,0x40,0x00,0x18,
+0x00,0x40,0x18,0x21,0x8f,0x82,0x8c,0x48,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x14,
+0x24,0x02,0x00,0x02,0x8f,0x83,0x8c,0x28,0x00,0x00,0x00,0x00,0x10,0x62,0x00,0x09,
+0x24,0x02,0x00,0x01,0x8f,0x83,0x8c,0x24,0x00,0x00,0x00,0x00,0x10,0x62,0x00,0x02,
+0x24,0x02,0x00,0x03,0x24,0x02,0x00,0x06,0xaf,0x82,0x8c,0x20,0x08,0x00,0x1b,0x20,
+0x24,0x04,0x00,0x03,0x3c,0x02,0x40,0x00,0x34,0x42,0x00,0x14,0x3c,0x01,0xb0,0x05,
+0xac,0x22,0x00,0x00,0xaf,0x80,0x8c,0x20,0x08,0x00,0x1b,0x20,0x24,0x04,0x00,0x03,
+0x10,0x60,0x00,0x10,0x00,0x00,0x00,0x00,0x27,0x84,0x8c,0x20,0x27,0x85,0x90,0xf8,
+0x0c,0x00,0x12,0xeb,0x00,0x00,0x00,0x00,0x8f,0x83,0x8c,0x24,0x24,0x02,0x00,0x01,
+0xa3,0x80,0x8c,0x50,0xaf,0x80,0x8c,0x28,0x10,0x62,0x00,0x02,0x24,0x02,0x00,0x03,
+0x24,0x02,0x00,0x04,0xaf,0x82,0x8c,0x20,0xaf,0x80,0x8c,0x44,0x08,0x00,0x1a,0x9c,
+0x00,0x00,0x00,0x00,0x83,0x82,0x8c,0x70,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x04,
+0x00,0x00,0x00,0x00,0x27,0x84,0x90,0xf8,0x0c,0x00,0x15,0x32,0x00,0x00,0x00,0x00,
+0x8f,0x82,0x8c,0x24,0xa3,0x80,0x8c,0x50,0xaf,0x80,0x8c,0x20,0xaf,0x80,0x8c,0x28,
+0x14,0x40,0x00,0x02,0x24,0x02,0x00,0x02,0xaf,0x82,0x8c,0x24,0xaf,0x80,0x8c,0x48,
+0x08,0x00,0x1a,0x9c,0x00,0x00,0x00,0x00,0x27,0x84,0x8c,0x20,0x27,0x85,0x90,0xf8,
+0x0c,0x00,0x12,0xeb,0x00,0x00,0x00,0x00,0x8f,0x82,0x8c,0x24,0xa3,0x80,0x8c,0x50,
+0xaf,0x80,0x8c,0x20,0xaf,0x80,0x8c,0x28,0x14,0x40,0xff,0x11,0x24,0x02,0x00,0x02,
+0xaf,0x82,0x8c,0x24,0x08,0x00,0x1a,0x9c,0x00,0x00,0x00,0x00,0x27,0x84,0x90,0xf8,
+0x0c,0x00,0x15,0x32,0x00,0x00,0x00,0x00,0x08,0x00,0x1b,0x86,0x00,0x00,0x00,0x00,
+0x27,0x84,0x8c,0x78,0x0c,0x00,0x2e,0x70,0x00,0x00,0x00,0x00,0x08,0x00,0x1a,0xa5,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x27,0x0a,0x00,0x00,0x00,0x00,0x93,0x82,0x92,0x14,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x2b,0x3c,0x02,0xb0,0x03,0x34,0x42,0x01,0x08,
+0x8c,0x44,0x00,0x00,0x8f,0x83,0xc2,0x50,0x8f,0x82,0xc2,0x54,0x00,0x83,0x18,0x23,
+0x00,0x43,0x10,0x2b,0x10,0x40,0x00,0x23,0x3c,0x02,0xb0,0x03,0x24,0x04,0x05,0xa0,
+0x34,0x42,0x01,0x18,0x8c,0x42,0x00,0x00,0x0c,0x00,0x0b,0xfa,0x00,0x00,0x00,0x00,
+0x24,0x04,0x05,0xa4,0x0c,0x00,0x0b,0xfa,0x00,0x02,0x84,0x02,0x30,0x51,0xff,0xff,
+0x24,0x04,0x05,0xa8,0x00,0x02,0x94,0x02,0x0c,0x00,0x0b,0xfa,0x3a,0x10,0xff,0xff,
+0x3a,0x31,0xff,0xff,0x30,0x42,0xff,0xff,0x2e,0x10,0x00,0x01,0x2e,0x31,0x00,0x01,
+0x3a,0x52,0xff,0xff,0x02,0x11,0x80,0x25,0x2e,0x52,0x00,0x01,0x38,0x42,0xff,0xff,
+0x02,0x12,0x80,0x25,0x2c,0x42,0x00,0x01,0x02,0x02,0x80,0x25,0x16,0x00,0x00,0x02,
+0x24,0x04,0x00,0x02,0x00,0x00,0x20,0x21,0x0c,0x00,0x0a,0x9c,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xb0,0x03,0x34,0x42,0x01,0x08,0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,
+0xaf,0x83,0xc2,0x50,0x0c,0x00,0x01,0xcb,0x00,0x00,0x00,0x00,0xaf,0x80,0x8c,0x20,
+0xaf,0x80,0x8c,0x54,0x08,0x00,0x1a,0x88,0x00,0x00,0x00,0x00,0x27,0x90,0xba,0x40,
+0x24,0x11,0x00,0x12,0x8e,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x90,0x82,0x00,0x10,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x03,0x00,0x00,0x00,0x00,0x0c,0x00,0x1d,0x55,
+0x00,0x00,0x00,0x00,0x26,0x31,0xff,0xff,0x06,0x21,0xff,0xf6,0x26,0x10,0x00,0x04,
+0x08,0x00,0x1a,0xa6,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x34,0x42,0x01,0x08,
+0x8c,0x44,0x00,0x00,0x8f,0x82,0x8c,0x18,0x00,0x04,0x19,0xc2,0x00,0x02,0x11,0xc2,
+0x10,0x62,0xfe,0xc1,0x3c,0x02,0xb0,0x03,0x34,0x42,0x01,0x02,0x90,0x43,0x00,0x00,
+0x3c,0x12,0xb0,0x05,0xaf,0x84,0x8c,0x18,0x30,0x63,0x00,0xff,0x00,0x03,0x11,0x40,
+0x00,0x43,0x10,0x23,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x00,0x02,0x99,0x00,
+0x00,0x00,0x88,0x21,0x36,0x52,0x02,0x2c,0x27,0x90,0xba,0x40,0x8e,0x04,0x00,0x00,
+0x00,0x00,0x00,0x00,0x90,0x83,0x00,0x16,0x00,0x00,0x00,0x00,0x30,0x62,0x00,0x03,
+0x10,0x40,0x00,0x06,0x30,0x62,0x00,0x1c,0x14,0x40,0x00,0x04,0x00,0x00,0x00,0x00,
+0x8f,0x85,0x8c,0x18,0x0c,0x00,0x22,0xc6,0x02,0x60,0x30,0x21,0x8e,0x42,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0x14,0x40,0xfe,0xa3,0x00,0x00,0x00,0x00,
+0x26,0x31,0x00,0x01,0x2a,0x22,0x00,0x13,0x14,0x40,0xff,0xec,0x26,0x10,0x00,0x04,
+0x08,0x00,0x1a,0xa6,0x00,0x00,0x00,0x00,0x8f,0x84,0x8c,0x2c,0x27,0x85,0x90,0xf8,
+0x0c,0x00,0x1c,0x2e,0x00,0x00,0x00,0x00,0x8f,0x83,0x8c,0x2c,0x24,0x02,0x00,0x04,
+0x14,0x62,0xfe,0x95,0x24,0x02,0x00,0x05,0x08,0x00,0x1b,0x23,0x00,0x00,0x00,0x00,
+0x27,0x84,0x90,0xf8,0x0c,0x00,0x27,0x2e,0x00,0x00,0x00,0x00,0x08,0x00,0x1a,0xcb,
+0x24,0x03,0x00,0x05,0x8f,0x82,0x91,0x2c,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x0d,
+0x00,0x00,0x00,0x00,0x8f,0x84,0xba,0x80,0xaf,0x80,0x91,0x2c,0x94,0x85,0x00,0x14,
+0x0c,0x00,0x1f,0xdd,0x00,0x00,0x00,0x00,0x93,0x82,0x91,0x51,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0x02,0x10,0x40,0x00,0x03,0x00,0x00,0x00,0x00,0x0c,0x00,0x01,0x60,
+0x00,0x00,0x20,0x21,0x8f,0x84,0xba,0x80,0x0c,0x00,0x1d,0x55,0x00,0x00,0x00,0x00,
+0x08,0x00,0x1a,0xa6,0x00,0x00,0x00,0x00,0x27,0xbd,0xff,0xe0,0x3c,0x06,0xb0,0x03,
+0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0x34,0xc6,0x00,0x5f,0xaf,0xbf,0x00,0x18,
+0x90,0xc3,0x00,0x00,0x3c,0x07,0xb0,0x03,0x34,0xe7,0x00,0x5d,0x34,0x63,0x00,0x01,
+0x3c,0x09,0xb0,0x03,0x24,0x02,0x00,0x01,0xa0,0xc3,0x00,0x00,0x00,0x80,0x80,0x21,
+0xa0,0xe2,0x00,0x00,0x00,0xa0,0x88,0x21,0x35,0x29,0x00,0x5e,0x00,0xe0,0x40,0x21,
+0x24,0x04,0x00,0x01,0x91,0x22,0x00,0x00,0x91,0x03,0x00,0x00,0x30,0x42,0x00,0x01,
+0x14,0x83,0x00,0x03,0x30,0x42,0x00,0x01,0x14,0x40,0xff,0xfa,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x04,0x12,0x02,0x00,0x2c,0x24,0x05,0x0f,0x00,0x24,0x02,0x00,0x06,
+0x12,0x02,0x00,0x08,0x24,0x05,0x00,0x0f,0x3c,0x02,0xb0,0x03,0x34,0x42,0x02,0x00,
+0xa0,0x50,0x00,0x00,0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x20,0x24,0x04,0x0c,0x04,0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x0f,
+0x24,0x04,0x0d,0x04,0x24,0x05,0x00,0x0f,0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x0f,
+0x24,0x04,0x08,0x80,0x24,0x05,0x1e,0x00,0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x0f,
+0x24,0x04,0x08,0x8c,0x24,0x05,0x0f,0x00,0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x0f,
+0x24,0x04,0x08,0x24,0x3c,0x05,0x00,0x30,0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x02,
+0x24,0x04,0x08,0x2c,0x3c,0x05,0x00,0x30,0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x02,
+0x24,0x04,0x08,0x34,0x3c,0x05,0x00,0x30,0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x02,
+0x24,0x04,0x08,0x3c,0x3c,0x05,0x00,0x30,0x0c,0x00,0x18,0x5b,0x24,0x06,0x00,0x02,
+0x08,0x00,0x1c,0x4f,0x3c,0x02,0xb0,0x03,0x24,0x04,0x08,0x8c,0x0c,0x00,0x18,0x5b,
+0x24,0x06,0x00,0x04,0x24,0x04,0x08,0x80,0x24,0x05,0x1e,0x00,0x0c,0x00,0x18,0x5b,
+0x24,0x06,0x00,0x04,0x24,0x04,0x0c,0x04,0x24,0x05,0x00,0x0f,0x0c,0x00,0x18,0x5b,
+0x24,0x06,0x00,0x04,0x24,0x04,0x0d,0x04,0x24,0x05,0x00,0x0f,0x0c,0x00,0x18,0x5b,
+0x24,0x06,0x00,0x04,0x24,0x04,0x08,0x24,0x3c,0x05,0x00,0x30,0x0c,0x00,0x18,0x5b,
+0x24,0x06,0x00,0x03,0x24,0x04,0x08,0x2c,0x3c,0x05,0x00,0x30,0x0c,0x00,0x18,0x5b,
+0x24,0x06,0x00,0x03,0x24,0x04,0x08,0x34,0x3c,0x05,0x00,0x30,0x0c,0x00,0x18,0x5b,
+0x24,0x06,0x00,0x02,0x3c,0x05,0x00,0x30,0x24,0x06,0x00,0x03,0x0c,0x00,0x18,0x5b,
+0x24,0x04,0x08,0x3c,0x02,0x20,0x20,0x21,0x24,0x05,0x00,0x14,0x0c,0x00,0x18,0xa0,
+0x24,0x06,0x01,0x07,0x08,0x00,0x1c,0x4f,0x3c,0x02,0xb0,0x03,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0x00,0x80,0x70,0x21,0x34,0x63,0x00,0x20,0x24,0x42,0x72,0x6c,
+0x3c,0x04,0xb0,0x03,0xac,0x62,0x00,0x00,0x34,0x84,0x00,0x30,0xad,0xc0,0x02,0xb8,
+0x8c,0x83,0x00,0x00,0x24,0x02,0x00,0xff,0xa5,0xc0,0x00,0x0a,0x00,0x00,0x30,0x21,
+0xa7,0x82,0x96,0x30,0x27,0x88,0x96,0x40,0xa5,0xc3,0x00,0x08,0x3c,0x07,0xb0,0x08,
+0x30,0xc2,0xff,0xff,0x00,0x02,0x20,0xc0,0x24,0xc3,0x00,0x01,0x00,0x82,0x10,0x21,
+0x00,0x60,0x30,0x21,0x00,0x02,0x10,0x80,0x30,0x63,0xff,0xff,0x00,0x48,0x10,0x21,
+0x00,0x87,0x20,0x21,0x28,0xc5,0x00,0xff,0xac,0x83,0x00,0x00,0x14,0xa0,0xff,0xf4,
+0xa4,0x43,0x00,0x00,0x3c,0x02,0xb0,0x08,0x34,0x03,0xff,0xff,0x34,0x42,0x07,0xf8,
+0x3c,0x04,0xb0,0x08,0xac,0x43,0x00,0x00,0xa7,0x83,0xba,0x1c,0x24,0x06,0x01,0x00,
+0x34,0x84,0x08,0x00,0x24,0xc2,0x00,0x01,0x28,0x43,0x02,0x00,0xac,0x82,0x00,0x00,
+0x00,0x40,0x30,0x21,0x14,0x60,0xff,0xfb,0x24,0x84,0x00,0x08,0x25,0xc2,0x00,0x0c,
+0x24,0x0a,0x00,0x02,0x3c,0x06,0xb0,0x03,0xaf,0x82,0xba,0x40,0x34,0xc6,0x00,0x64,
+0xa0,0x4a,0x00,0x18,0x94,0xc5,0x00,0x00,0x8f,0x82,0xba,0x40,0x25,0xc4,0x00,0x30,
+0x24,0x08,0x00,0x03,0x3c,0x03,0xb0,0x03,0xa0,0x45,0x00,0x21,0x34,0x63,0x00,0x66,
+0xaf,0x84,0xba,0x44,0xa0,0x88,0x00,0x18,0x94,0x65,0x00,0x00,0x8f,0x82,0xba,0x44,
+0x25,0xc4,0x00,0x54,0x25,0xc7,0x00,0x78,0xa0,0x45,0x00,0x21,0xaf,0x84,0xba,0x48,
+0xa0,0x88,0x00,0x18,0x94,0x65,0x00,0x00,0x8f,0x82,0xba,0x48,0x25,0xc8,0x00,0x9c,
+0x24,0x09,0x00,0x01,0xa0,0x45,0x00,0x21,0xaf,0x87,0xba,0x4c,0xa0,0xea,0x00,0x18,
+0x94,0xc4,0x00,0x00,0x8f,0x82,0xba,0x4c,0x3c,0x03,0xb0,0x03,0x34,0x63,0x00,0x62,
+0xa0,0x44,0x00,0x21,0xaf,0x88,0xba,0x50,0xa1,0x09,0x00,0x18,0x94,0x65,0x00,0x00,
+0x8f,0x82,0xba,0x50,0x25,0xc4,0x00,0xc0,0x25,0xc6,0x00,0xe4,0xa0,0x45,0x00,0x21,
+0xaf,0x84,0xba,0x54,0xa0,0x89,0x00,0x18,0x94,0x65,0x00,0x00,0x8f,0x82,0xba,0x54,
+0x3c,0x04,0xb0,0x03,0x34,0x84,0x00,0x60,0xa0,0x45,0x00,0x21,0xaf,0x86,0xba,0x58,
+0xa0,0xc0,0x00,0x18,0x94,0x85,0x00,0x00,0x8f,0x82,0xba,0x58,0x25,0xc3,0x01,0x08,
+0x25,0xc6,0x01,0x2c,0xa0,0x45,0x00,0x21,0xaf,0x83,0xba,0x5c,0xa0,0x60,0x00,0x18,
+0x94,0x87,0x00,0x00,0x8f,0x82,0xba,0x5c,0x25,0xc5,0x01,0x50,0x25,0xc4,0x01,0x74,
+0xa0,0x47,0x00,0x21,0x25,0xc8,0x01,0x98,0x25,0xc9,0x01,0xbc,0x25,0xca,0x01,0xe0,
+0x25,0xcb,0x02,0x04,0x25,0xcc,0x02,0x28,0x25,0xcd,0x02,0x4c,0x24,0x02,0x00,0x10,
+0x3c,0x03,0xb0,0x03,0xaf,0x86,0xba,0x60,0x34,0x63,0x00,0x38,0xa0,0xc0,0x00,0x18,
+0xaf,0x85,0xba,0x64,0xa0,0xa0,0x00,0x18,0xaf,0x84,0xba,0x68,0xa0,0x80,0x00,0x18,
+0xaf,0x88,0xba,0x6c,0xa1,0x00,0x00,0x18,0xaf,0x89,0xba,0x70,0xa1,0x20,0x00,0x18,
+0xaf,0x8a,0xba,0x74,0xa1,0x40,0x00,0x18,0xaf,0x8b,0xba,0x78,0xa1,0x60,0x00,0x18,
+0xaf,0x8c,0xba,0x7c,0xa1,0x80,0x00,0x18,0xaf,0x8d,0xba,0x80,0xa1,0xa2,0x00,0x18,
+0x94,0x64,0x00,0x00,0x8f,0x82,0xba,0x80,0x25,0xc5,0x02,0x70,0x3c,0x03,0xb0,0x03,
+0xa0,0x44,0x00,0x21,0x24,0x02,0x00,0x11,0xaf,0x85,0xba,0x84,0x34,0x63,0x00,0x6e,
+0xa0,0xa2,0x00,0x18,0x94,0x64,0x00,0x00,0x8f,0x82,0xba,0x84,0x25,0xc5,0x02,0x94,
+0x3c,0x03,0xb0,0x03,0xa0,0x44,0x00,0x21,0x24,0x02,0x00,0x12,0xaf,0x85,0xba,0x88,
+0x34,0x63,0x00,0x6c,0xa0,0xa2,0x00,0x18,0x94,0x64,0x00,0x00,0x8f,0x82,0xba,0x88,
+0x24,0x05,0xff,0xff,0x24,0x07,0x00,0x01,0xa0,0x44,0x00,0x21,0x24,0x06,0x00,0x12,
+0x27,0x84,0xba,0x40,0x8c,0x82,0x00,0x00,0x24,0xc6,0xff,0xff,0xa0,0x40,0x00,0x04,
+0x8c,0x83,0x00,0x00,0xa4,0x45,0x00,0x00,0xa4,0x45,0x00,0x02,0xa0,0x60,0x00,0x0a,
+0x8c,0x82,0x00,0x00,0xa4,0x65,0x00,0x06,0xa4,0x65,0x00,0x08,0xa0,0x40,0x00,0x10,
+0x8c,0x83,0x00,0x00,0xa4,0x45,0x00,0x0c,0xa4,0x45,0x00,0x0e,0xa0,0x60,0x00,0x12,
+0x8c,0x82,0x00,0x00,0x00,0x00,0x00,0x00,0xa0,0x40,0x00,0x16,0x8c,0x83,0x00,0x00,
+0xa4,0x45,0x00,0x14,0xa0,0x67,0x00,0x17,0x8c,0x82,0x00,0x00,0x24,0x84,0x00,0x04,
+0xa0,0x40,0x00,0x20,0x04,0xc1,0xff,0xe7,0xac,0x40,0x00,0x1c,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x00,0x34,0x42,0x00,0x20,
+0x24,0x63,0x75,0x54,0xac,0x43,0x00,0x00,0x90,0x82,0x00,0x10,0x00,0x80,0x60,0x21,
+0x10,0x40,0x00,0x56,0x00,0x00,0x70,0x21,0x97,0x82,0x96,0x30,0x94,0x8a,0x00,0x0c,
+0x27,0x87,0x96,0x40,0x00,0x02,0x40,0xc0,0x01,0x02,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x47,0x10,0x21,0x90,0x8b,0x00,0x18,0xa4,0x4a,0x00,0x00,0x94,0x83,0x00,0x0e,
+0x39,0x64,0x00,0x10,0x2c,0x84,0x00,0x01,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x34,0x85,0x00,0x02,0x39,0x63,0x00,0x11,0x00,0x83,0x28,0x0b,0x34,0xa3,0x00,0x08,
+0x39,0x64,0x00,0x12,0x00,0x02,0x10,0x80,0x00,0xa4,0x18,0x0b,0x00,0x47,0x10,0x21,
+0x94,0x49,0x00,0x04,0x34,0x64,0x00,0x20,0x00,0x6b,0x20,0x0b,0x34,0x83,0x00,0x40,
+0x39,0x62,0x00,0x01,0x00,0x82,0x18,0x0b,0x00,0x09,0x30,0xc0,0x34,0x64,0x00,0x80,
+0x00,0xc9,0x28,0x21,0x39,0x62,0x00,0x02,0x00,0x60,0x68,0x21,0x00,0x82,0x68,0x0a,
+0x00,0x05,0x28,0x80,0x3c,0x02,0xb0,0x08,0x00,0xa7,0x28,0x21,0x00,0xc2,0x30,0x21,
+0x01,0x02,0x40,0x21,0x34,0x03,0xff,0xff,0x35,0xa4,0x01,0x00,0x39,0x62,0x00,0x03,
+0x2d,0x67,0x00,0x13,0xad,0x0a,0x00,0x00,0xa4,0xa3,0x00,0x00,0xac,0xc3,0x00,0x00,
+0xa7,0x89,0x96,0x30,0x10,0xe0,0x00,0x0f,0x00,0x82,0x68,0x0a,0x3c,0x03,0x80,0x01,
+0x00,0x0b,0x10,0x80,0x24,0x63,0x09,0x4c,0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x08,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,
+0x34,0x63,0x00,0x60,0x94,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x14,0x00,
+0x00,0x02,0x74,0x03,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0x3a,0x94,0x44,0x00,0x00,
+0x93,0x83,0x96,0x24,0x91,0x82,0x00,0x21,0x01,0xc4,0x20,0x21,0x91,0x85,0x00,0x10,
+0x00,0x04,0x24,0x00,0x00,0x62,0x18,0x21,0x00,0x04,0x74,0x03,0x00,0x6e,0x18,0x23,
+0x00,0x65,0x10,0x2a,0x00,0xa2,0x18,0x0a,0x00,0x0d,0x24,0x00,0x3c,0x02,0xb0,0x06,
+0x24,0x05,0xff,0xff,0x00,0x64,0x18,0x25,0x34,0x42,0x80,0x20,0xac,0x43,0x00,0x00,
+0xa5,0x85,0x00,0x0e,0xa1,0x80,0x00,0x10,0xa5,0x85,0x00,0x0c,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x08,0x00,0x1d,0x99,0x34,0x63,0x00,0x62,
+0x3c,0x03,0xb0,0x03,0x08,0x00,0x1d,0x99,0x34,0x63,0x00,0x64,0x3c,0x03,0xb0,0x03,
+0x08,0x00,0x1d,0x99,0x34,0x63,0x00,0x66,0x3c,0x03,0xb0,0x03,0x08,0x00,0x1d,0x99,
+0x34,0x63,0x00,0x38,0x3c,0x03,0xb0,0x03,0x08,0x00,0x1d,0x99,0x34,0x63,0x00,0x6e,
+0x3c,0x03,0xb0,0x03,0x08,0x00,0x1d,0x99,0x34,0x63,0x00,0x6c,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x77,0x1c,0x00,0x05,0x28,0x40,
+0xac,0x62,0x00,0x00,0x00,0xa6,0x28,0x21,0x2c,0xe2,0x00,0x10,0x14,0x80,0x00,0x06,
+0x00,0x00,0x18,0x21,0x10,0x40,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0xe0,0x18,0x21,
+0x03,0xe0,0x00,0x08,0x00,0x60,0x10,0x21,0x24,0x02,0x00,0x20,0x10,0xe2,0x00,0x06,
+0x2c,0xe4,0x00,0x10,0x24,0xa2,0x00,0x01,0x10,0x80,0xff,0xf9,0x00,0x02,0x11,0x00,
+0x08,0x00,0x1d,0xd4,0x00,0x47,0x18,0x21,0x08,0x00,0x1d,0xd4,0x24,0xa3,0x00,0x50,
+0x27,0xbd,0xff,0xc0,0xaf,0xb7,0x00,0x34,0xaf,0xb5,0x00,0x2c,0xaf,0xb4,0x00,0x28,
+0xaf,0xb2,0x00,0x20,0xaf,0xb1,0x00,0x1c,0xaf,0xbf,0x00,0x3c,0xaf,0xbe,0x00,0x38,
+0xaf,0xb6,0x00,0x30,0xaf,0xb3,0x00,0x24,0xaf,0xb0,0x00,0x18,0x84,0x85,0x00,0x08,
+0x00,0x80,0x90,0x21,0x3c,0x02,0x80,0x00,0x3c,0x04,0xb0,0x03,0x34,0x84,0x00,0x20,
+0x24,0x42,0x77,0x80,0x3c,0x03,0xb0,0x06,0x00,0x05,0x28,0x80,0xac,0x82,0x00,0x00,
+0x00,0xa3,0x28,0x21,0x3c,0x04,0xb0,0x06,0x8c,0xa3,0x00,0x00,0x34,0x84,0x80,0x24,
+0x8c,0xa6,0x00,0x00,0x8c,0x82,0x00,0x00,0x30,0x71,0xff,0xff,0x00,0x11,0x2a,0x00,
+0x34,0x42,0x01,0x00,0x3c,0x03,0xb0,0x00,0xac,0x82,0x00,0x00,0x00,0xa3,0x40,0x21,
+0x8d,0x1e,0x00,0x00,0x8d,0x13,0x00,0x04,0x96,0x44,0x00,0x08,0x00,0x11,0xa0,0xc0,
+0x02,0x91,0x10,0x21,0x00,0x02,0x38,0x80,0x00,0x13,0x12,0x02,0x30,0x42,0x00,0x1f,
+0x24,0x84,0x00,0x02,0x27,0x83,0x96,0x50,0xa6,0x42,0x00,0x06,0x30,0x84,0x01,0xff,
+0x24,0x02,0x00,0x10,0x00,0xe3,0x18,0x21,0xa6,0x44,0x00,0x08,0x8d,0x10,0x00,0x08,
+0xa0,0x62,0x00,0x06,0x86,0x44,0x00,0x06,0x27,0x82,0x96,0x44,0x00,0xe2,0x10,0x21,
+0xac,0x48,0x00,0x18,0x24,0x02,0x00,0x13,0x00,0x06,0xbc,0x02,0x10,0x82,0x00,0xe6,
+0x00,0x00,0xa8,0x21,0x3c,0x03,0xb0,0x03,0x34,0x63,0x01,0x00,0xa6,0x40,0x00,0x02,
+0x90,0x64,0x00,0x00,0x3c,0x02,0xb0,0x03,0x34,0x42,0x01,0x08,0x8c,0x45,0x00,0x00,
+0x00,0x10,0x1b,0xc2,0x00,0x04,0x20,0x82,0x27,0x82,0x96,0x40,0x00,0xe2,0x10,0x21,
+0x30,0x84,0x00,0x01,0x30,0x63,0x00,0x01,0xac,0x45,0x00,0x08,0x10,0x60,0x00,0xbc,
+0xaf,0xa4,0x00,0x10,0x00,0x10,0x16,0x82,0x30,0x46,0x00,0x01,0x00,0x10,0x12,0x02,
+0x00,0x10,0x19,0xc2,0x00,0x10,0x26,0x02,0x00,0x10,0x2e,0x42,0x30,0x47,0x00,0x7f,
+0x24,0x02,0x00,0x01,0x30,0x76,0x00,0x01,0x30,0x84,0x00,0x01,0x10,0xc2,0x00,0xa7,
+0x30,0xa3,0x00,0x01,0x0c,0x00,0x1d,0xc7,0x00,0x60,0x28,0x21,0x00,0x40,0xa8,0x21,
+0x02,0x91,0x10,0x21,0x00,0x02,0x10,0x80,0x2e,0xa4,0x00,0x54,0x27,0x85,0x96,0x50,
+0x27,0x83,0x96,0x48,0x00,0x04,0xa8,0x0a,0x00,0x45,0x28,0x21,0x26,0xc4,0x00,0x02,
+0x00,0x43,0x10,0x21,0xa0,0x44,0x00,0x06,0xa0,0x55,0x00,0x07,0xa0,0xb5,0x00,0x02,
+0xa0,0xb5,0x00,0x01,0x00,0x10,0x14,0x82,0x00,0x10,0x1d,0xc2,0x30,0x48,0x00,0x01,
+0x00,0x13,0x15,0x82,0x00,0x13,0x21,0x82,0x30,0x63,0x00,0x01,0x00,0x10,0x2c,0x02,
+0x00,0x10,0x34,0x42,0x30,0x49,0x00,0x03,0x24,0x02,0x00,0x01,0xa6,0x5e,0x00,0x04,
+0xa6,0x43,0x00,0x00,0x30,0x8a,0x00,0x01,0x32,0x73,0x00,0x07,0x30,0xa5,0x00,0x01,
+0x30,0xc6,0x00,0x01,0x11,0x02,0x00,0x77,0x32,0x07,0x00,0x7f,0x15,0x40,0x00,0x03,
+0x00,0x00,0x00,0x00,0x15,0x20,0x00,0x68,0x24,0x02,0x00,0x01,0x96,0x42,0x00,0x04,
+0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x04,0xa6,0x42,0x00,0x04,0x00,0xa0,0x20,0x21,
+0x00,0xc0,0x28,0x21,0x0c,0x00,0x1d,0xc7,0x01,0x00,0x30,0x21,0x02,0x91,0x18,0x21,
+0x00,0x03,0x38,0x80,0x2e,0xa5,0x00,0x54,0x27,0x84,0x96,0x50,0x00,0xe4,0x20,0x21,
+0x00,0x05,0x10,0x0a,0xa0,0x82,0x00,0x00,0xa0,0x80,0x00,0x04,0xa0,0x80,0x00,0x05,
+0x96,0x45,0x00,0x04,0x27,0x82,0x96,0x40,0x00,0xe2,0x10,0x21,0xa4,0x45,0x00,0x06,
+0x27,0x83,0x96,0x44,0x00,0xe3,0x18,0x21,0x92,0x45,0x00,0x01,0x8c,0x66,0x00,0x18,
+0x27,0x82,0x96,0x60,0x00,0xe2,0x10,0x21,0xa0,0x40,0x00,0x00,0xa0,0x85,0x00,0x07,
+0x94,0xc3,0x00,0x10,0x24,0x02,0x00,0x04,0x30,0x63,0x00,0x0f,0x10,0x62,0x00,0x42,
+0x24,0xc6,0x00,0x10,0x94,0xc3,0x00,0x16,0x27,0x88,0x96,0x58,0x00,0xe8,0x10,0x21,
+0xa4,0x43,0x00,0x02,0x94,0xc2,0x00,0x04,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,
+0x14,0x40,0x00,0x30,0x02,0x91,0x20,0x21,0x94,0xc2,0x00,0x00,0x24,0x03,0x00,0xa4,
+0x30,0x42,0x00,0xff,0x10,0x43,0x00,0x2b,0x00,0x00,0x00,0x00,0x94,0xc2,0x00,0x00,
+0x24,0x03,0x00,0x88,0x30,0x42,0x00,0x88,0x10,0x43,0x00,0x20,0x02,0x91,0x18,0x21,
+0x27,0x84,0x96,0x60,0x00,0x03,0x18,0x80,0x00,0x64,0x18,0x21,0x8c,0x62,0x00,0x00,
+0x3c,0x04,0x00,0x80,0x00,0x44,0x10,0x25,0xac,0x62,0x00,0x00,0x00,0x17,0x10,0xc0,
+0x00,0x57,0x10,0x21,0x27,0x84,0x96,0x40,0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x21,
+0x94,0x45,0x00,0x00,0x02,0x91,0x18,0x21,0x00,0x03,0x18,0x80,0x00,0x64,0x20,0x21,
+0x24,0x02,0xff,0xff,0x00,0x68,0x18,0x21,0xa0,0x73,0x00,0x00,0xa4,0x82,0x00,0x02,
+0xa4,0x97,0x00,0x04,0xae,0x51,0x02,0xb8,0xa6,0x45,0x00,0x0a,0x7b,0xbe,0x01,0xfc,
+0x7b,0xb6,0x01,0xbc,0x7b,0xb4,0x01,0x7c,0x7b,0xb2,0x01,0x3c,0x7b,0xb0,0x00,0xfc,
+0x24,0x02,0x00,0x01,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x40,0x94,0xc2,0x00,0x18,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x60,0x10,0x40,0xff,0xdd,0x02,0x91,0x18,0x21,
+0x02,0x91,0x20,0x21,0x27,0x82,0x96,0x60,0x00,0x04,0x20,0x80,0x00,0x82,0x20,0x21,
+0x8c,0x83,0x00,0x00,0x3c,0x02,0xff,0x7f,0x34,0x42,0xff,0xff,0x00,0x62,0x18,0x24,
+0x08,0x00,0x1e,0x97,0xac,0x83,0x00,0x00,0x27,0x88,0x96,0x58,0x00,0xe8,0x10,0x21,
+0x08,0x00,0x1e,0x81,0xa4,0x40,0x00,0x02,0x11,0x22,0x00,0x07,0x00,0x00,0x00,0x00,
+0x2d,0x22,0x00,0x02,0x14,0x40,0xff,0x9a,0x00,0xa0,0x20,0x21,0x96,0x42,0x00,0x04,
+0x08,0x00,0x1e,0x5e,0x24,0x42,0x00,0x0c,0x96,0x42,0x00,0x04,0x08,0x00,0x1e,0x5e,
+0x24,0x42,0x00,0x08,0x8f,0xa2,0x00,0x10,0x00,0x00,0x00,0x00,0x14,0x48,0xff,0x87,
+0x02,0x91,0x18,0x21,0x27,0x82,0x96,0x44,0x00,0x03,0x18,0x80,0x00,0x62,0x18,0x21,
+0x8c,0x64,0x00,0x18,0x3c,0x02,0xff,0xfb,0x34,0x42,0xff,0xff,0x02,0x02,0x10,0x24,
+0xac,0x82,0x00,0x08,0x08,0x00,0x1e,0x57,0x00,0x00,0x40,0x21,0x8f,0xa2,0x00,0x10,
+0x00,0x00,0x00,0x00,0x14,0x46,0xff,0x57,0x3c,0x02,0xfb,0xff,0x34,0x42,0xff,0xff,
+0x02,0x02,0x10,0x24,0xad,0x02,0x00,0x08,0x08,0x00,0x1e,0x35,0x00,0x00,0x30,0x21,
+0x93,0x88,0xc1,0x54,0x00,0x10,0x1e,0x42,0x00,0x10,0x26,0x82,0x27,0x82,0x96,0x48,
+0x2d,0x05,0x00,0x0c,0x00,0xe2,0x48,0x21,0x30,0x63,0x00,0x01,0x30,0x86,0x00,0x01,
+0x14,0xa0,0x00,0x06,0x01,0x00,0x38,0x21,0x00,0x03,0x10,0x40,0x00,0x46,0x10,0x21,
+0x00,0x02,0x11,0x00,0x01,0x02,0x10,0x21,0x24,0x47,0x00,0x04,0x02,0x91,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x84,0x96,0x50,0x27,0x83,0x96,0x48,0x00,0x44,0x20,0x21,
+0x00,0x43,0x10,0x21,0xa1,0x27,0x00,0x07,0xa0,0x40,0x00,0x06,0xa0,0x80,0x00,0x02,
+0x08,0x00,0x1e,0x45,0xa0,0x80,0x00,0x01,0x24,0x02,0x00,0x01,0xa6,0x42,0x00,0x02,
+0x0c,0x00,0x04,0x40,0x01,0x00,0x20,0x21,0x08,0x00,0x1e,0xa7,0x00,0x00,0x00,0x00,
+0x30,0xa7,0xff,0xff,0x00,0x07,0x18,0xc0,0x00,0x67,0x18,0x21,0x3c,0x06,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0x24,0x42,0x7c,0x10,0x27,0x85,0x96,0x50,0x00,0x03,0x18,0x80,
+0x34,0xc6,0x00,0x20,0x00,0x65,0x18,0x21,0xac,0xc2,0x00,0x00,0x80,0x62,0x00,0x07,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x29,0x00,0x80,0x28,0x21,0x90,0x82,0x00,0x16,
+0x00,0x00,0x00,0x00,0x34,0x42,0x00,0x02,0x30,0x43,0x00,0x01,0x14,0x60,0x00,0x02,
+0xa0,0x82,0x00,0x16,0xa0,0x80,0x00,0x17,0x90,0xa2,0x00,0x04,0x3c,0x03,0xb0,0x03,
+0x27,0x86,0x96,0x40,0x14,0x40,0x00,0x06,0x34,0x63,0x00,0x20,0x24,0x02,0x00,0x01,
+0xa0,0xa2,0x00,0x04,0xa4,0xa7,0x00,0x02,0x03,0xe0,0x00,0x08,0xa4,0xa7,0x00,0x00,
+0x94,0xa4,0x00,0x02,0x3c,0x02,0x80,0x01,0x24,0x42,0x93,0x34,0xac,0x62,0x00,0x00,
+0x00,0x04,0x18,0xc0,0x00,0x64,0x18,0x21,0x00,0x03,0x18,0x80,0x00,0x66,0x18,0x21,
+0x94,0x62,0x00,0x04,0xa4,0x67,0x00,0x02,0x3c,0x03,0xb0,0x08,0x00,0x02,0x20,0xc0,
+0x00,0x82,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x46,0x10,0x21,0x00,0x83,0x20,0x21,
+0xa4,0x47,0x00,0x00,0xac,0x87,0x00,0x00,0x90,0xa2,0x00,0x04,0xa4,0xa7,0x00,0x02,
+0x24,0x42,0x00,0x01,0x03,0xe0,0x00,0x08,0xa0,0xa2,0x00,0x04,0x90,0x82,0x00,0x16,
+0x24,0x85,0x00,0x06,0x34,0x42,0x00,0x01,0x30,0x43,0x00,0x02,0x14,0x60,0xff,0xda,
+0xa0,0x82,0x00,0x16,0x24,0x02,0x00,0x01,0x08,0x00,0x1f,0x1a,0xa0,0x82,0x00,0x17,
+0x27,0xbd,0xff,0xe8,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,0x00,0x80,0x80,0x21,
+0x84,0x84,0x00,0x02,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,
+0x24,0x42,0x7d,0x10,0x10,0x80,0x00,0x38,0xac,0x62,0x00,0x00,0x8e,0x04,0x02,0xb8,
+0x0c,0x00,0x02,0x7e,0x00,0x00,0x00,0x00,0x97,0x88,0x96,0x30,0x96,0x0c,0x02,0xba,
+0x3c,0x04,0xb0,0x08,0x00,0x08,0x30,0xc0,0x00,0xc4,0x10,0x21,0xac,0x4c,0x00,0x00,
+0x8e,0x03,0x02,0xb8,0x27,0x89,0x96,0x40,0x34,0x0b,0xff,0xff,0x00,0x03,0x10,0xc0,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x49,0x10,0x21,0x94,0x4a,0x00,0x04,
+0x00,0xc8,0x30,0x21,0x00,0x06,0x30,0x80,0x00,0x0a,0x28,0xc0,0x00,0xa4,0x20,0x21,
+0xac,0x8b,0x00,0x00,0x8e,0x02,0x02,0xb8,0x27,0x84,0x96,0x50,0x00,0xaa,0x28,0x21,
+0x00,0x02,0x18,0xc0,0x00,0x62,0x18,0x21,0x00,0x03,0x18,0x80,0x27,0x82,0x96,0x44,
+0x00,0x62,0x10,0x21,0x8c,0x47,0x00,0x18,0x00,0x64,0x18,0x21,0x80,0x68,0x00,0x06,
+0x8c,0xe4,0x00,0x00,0x00,0x05,0x28,0x80,0x3c,0x03,0xb0,0x06,0x30,0x84,0xff,0xff,
+0x00,0x88,0x20,0x21,0x30,0x82,0x00,0xff,0x00,0x02,0x10,0x2b,0x00,0x04,0x22,0x02,
+0x00,0x82,0x20,0x21,0x3c,0x02,0x00,0x04,0x00,0xa9,0x28,0x21,0x00,0x82,0x20,0x25,
+0x00,0xc9,0x30,0x21,0x34,0x63,0x80,0x20,0xa4,0xcc,0x00,0x00,0xac,0x64,0x00,0x00,
+0xa4,0xab,0x00,0x00,0xa7,0x8a,0x96,0x30,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x86,0x03,0x00,0x06,0x27,0x82,0xba,0x40,
+0x96,0x05,0x02,0xba,0x00,0x03,0x18,0x80,0x00,0x62,0x18,0x21,0x8c,0x64,0x00,0x00,
+0x0c,0x00,0x1f,0x04,0x00,0x00,0x00,0x00,0x08,0x00,0x1f,0x82,0x00,0x00,0x00,0x00,
+0x94,0x88,0x00,0x00,0x00,0x80,0x58,0x21,0x27,0x8a,0x96,0x40,0x00,0x08,0x18,0xc0,
+0x00,0x68,0x18,0x21,0x3c,0x04,0xb0,0x03,0x00,0x03,0x18,0x80,0x3c,0x02,0x80,0x00,
+0x00,0x6a,0x18,0x21,0x34,0x84,0x00,0x20,0x24,0x42,0x7e,0x40,0x30,0xa5,0xff,0xff,
+0xac,0x82,0x00,0x00,0x94,0x67,0x00,0x02,0x11,0x05,0x00,0x35,0x24,0x04,0x00,0x01,
+0x91,0x66,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x86,0x10,0x2a,0x10,0x40,0x00,0x10,
+0x00,0xc0,0x48,0x21,0x3c,0x0d,0xb0,0x03,0x01,0x40,0x60,0x21,0x35,0xad,0x00,0x20,
+0x10,0xe5,0x00,0x0d,0x24,0x84,0x00,0x01,0x00,0x07,0x10,0xc0,0x00,0x47,0x10,0x21,
+0x00,0x02,0x10,0x80,0x01,0x20,0x30,0x21,0x00,0x4a,0x10,0x21,0x00,0x86,0x18,0x2a,
+0x00,0xe0,0x40,0x21,0x94,0x47,0x00,0x02,0x14,0x60,0xff,0xf5,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x10,0x21,0x00,0x08,0x20,0xc0,0x00,0x88,0x20,0x21,
+0x24,0xc2,0xff,0xff,0x00,0x04,0x20,0x80,0xa1,0x62,0x00,0x04,0x00,0x8c,0x20,0x21,
+0x94,0x83,0x00,0x04,0x00,0x07,0x10,0xc0,0x00,0x47,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x4c,0x10,0x21,0x00,0x03,0x28,0xc0,0x94,0x46,0x00,0x02,0x00,0xa3,0x18,0x21,
+0x00,0x03,0x18,0x80,0x00,0x6c,0x18,0x21,0xa4,0x66,0x00,0x00,0xa4,0x86,0x00,0x02,
+0x95,0x64,0x00,0x02,0x3c,0x03,0xb0,0x08,0x3c,0x02,0x80,0x01,0x00,0xa3,0x28,0x21,
+0x24,0x42,0x93,0x34,0xad,0xa2,0x00,0x00,0x10,0x87,0x00,0x03,0xac,0xa6,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x24,0x02,0x00,0x01,0x08,0x00,0x1f,0xd0,0xa5,0x68,0x00,0x02,
+0x91,0x62,0x00,0x04,0xa5,0x67,0x00,0x00,0x24,0x42,0xff,0xff,0x30,0x43,0x00,0xff,
+0x14,0x60,0xff,0xf7,0xa1,0x62,0x00,0x04,0x24,0x02,0xff,0xff,0x08,0x00,0x1f,0xd0,
+0xa5,0x62,0x00,0x02,0x00,0x05,0x40,0xc0,0x01,0x05,0x30,0x21,0x27,0xbd,0xff,0xd8,
+0x00,0x06,0x30,0x80,0x27,0x82,0x96,0x44,0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,
+0xaf,0xbf,0x00,0x20,0xaf,0xb3,0x00,0x1c,0xaf,0xb0,0x00,0x10,0x00,0xc2,0x10,0x21,
+0x8c,0x47,0x00,0x18,0x00,0xa0,0x90,0x21,0x3c,0x02,0x80,0x00,0x3c,0x05,0xb0,0x03,
+0x34,0xa5,0x00,0x20,0x24,0x42,0x7f,0x74,0xac,0xa2,0x00,0x00,0x27,0x83,0x96,0x50,
+0x00,0xc3,0x30,0x21,0x8c,0xe2,0x00,0x00,0x80,0xc5,0x00,0x06,0x00,0x80,0x88,0x21,
+0x30,0x42,0xff,0xff,0x00,0x45,0x10,0x21,0x30,0x43,0x00,0xff,0x10,0x60,0x00,0x02,
+0x00,0x02,0x12,0x02,0x24,0x42,0x00,0x01,0x30,0x53,0x00,0xff,0x01,0x12,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x96,0x50,0x00,0x43,0x10,0x21,0x80,0x44,0x00,0x07,
+0x00,0x00,0x00,0x00,0x10,0x80,0x00,0x4b,0x26,0x24,0x00,0x06,0x32,0x50,0xff,0xff,
+0x02,0x20,0x20,0x21,0x0c,0x00,0x1f,0x90,0x02,0x00,0x28,0x21,0x92,0x22,0x00,0x10,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x2e,0x3c,0x03,0xb0,0x08,0x3c,0x09,0x80,0x01,
+0x27,0x88,0x96,0x40,0xa6,0x32,0x00,0x0c,0x00,0x10,0x20,0xc0,0x00,0x90,0x20,0x21,
+0x00,0x04,0x20,0x80,0x00,0x88,0x20,0x21,0x94,0x82,0x00,0x04,0x3c,0x03,0xb0,0x08,
+0x3c,0x07,0xb0,0x03,0x00,0x02,0x28,0xc0,0x00,0xa2,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x48,0x10,0x21,0x00,0xa3,0x28,0x21,0x25,0x26,0x93,0x34,0x34,0x03,0xff,0xff,
+0x34,0xe7,0x00,0x20,0xac,0xe6,0x00,0x00,0xa4,0x83,0x00,0x02,0xa4,0x43,0x00,0x00,
+0xac,0xa3,0x00,0x00,0x92,0x22,0x00,0x10,0x92,0x23,0x00,0x0a,0xa6,0x32,0x00,0x0e,
+0x02,0x62,0x10,0x21,0x14,0x60,0x00,0x05,0xa2,0x22,0x00,0x10,0x92,0x22,0x00,0x16,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xfe,0xa2,0x22,0x00,0x16,0x92,0x22,0x00,0x04,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x05,0x00,0x00,0x00,0x00,0x92,0x22,0x00,0x16,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xfd,0xa2,0x22,0x00,0x16,0x8f,0xbf,0x00,0x20,
+0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,
+0x96,0x22,0x00,0x0e,0x27,0x88,0x96,0x40,0x00,0x02,0x20,0xc0,0x00,0x82,0x20,0x21,
+0x00,0x04,0x20,0x80,0x00,0x88,0x20,0x21,0x94,0x82,0x00,0x04,0x3c,0x06,0xb0,0x03,
+0x3c,0x09,0x80,0x01,0x00,0x02,0x28,0xc0,0x00,0xa2,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0xa3,0x28,0x21,0x00,0x48,0x10,0x21,0x34,0xc6,0x00,0x20,0x25,0x23,0x93,0x34,
+0xac,0xc3,0x00,0x00,0xa4,0x50,0x00,0x00,0xac,0xb0,0x00,0x00,0x08,0x00,0x20,0x0e,
+0xa4,0x90,0x00,0x02,0x08,0x00,0x20,0x05,0x32,0x50,0xff,0xff,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x01,0x24,0x42,0x81,0x3c,0x34,0x63,0x00,0x20,0xac,0x62,0x00,0x00,
+0x90,0x82,0x00,0x04,0x97,0xaa,0x00,0x12,0x00,0x80,0x60,0x21,0x30,0xa8,0xff,0xff,
+0x00,0x4a,0x20,0x23,0x34,0x09,0xff,0xff,0x30,0xcf,0xff,0xff,0x30,0xee,0xff,0xff,
+0x11,0x09,0x00,0x73,0xa1,0x84,0x00,0x04,0x00,0x0e,0xc0,0xc0,0x00,0x08,0x10,0xc0,
+0x00,0x48,0x10,0x21,0x03,0x0e,0x20,0x21,0x27,0x8d,0x96,0x40,0x00,0x04,0x20,0x80,
+0x00,0x02,0x10,0x80,0x00,0x4d,0x10,0x21,0x00,0x8d,0x20,0x21,0x94,0x86,0x00,0x02,
+0x94,0x43,0x00,0x04,0x3c,0x19,0x80,0x01,0xa4,0x46,0x00,0x02,0x00,0x03,0x28,0xc0,
+0x00,0xa3,0x18,0x21,0x94,0x87,0x00,0x02,0x3c,0x02,0xb0,0x08,0x00,0x03,0x18,0x80,
+0x00,0xa2,0x28,0x21,0x00,0x6d,0x18,0x21,0x27,0x22,0x93,0x34,0x3c,0x01,0xb0,0x03,
+0xac,0x22,0x00,0x20,0xa4,0x66,0x00,0x00,0x10,0xe9,0x00,0x57,0xac,0xa6,0x00,0x00,
+0x01,0xe0,0x30,0x21,0x11,0x40,0x00,0x1d,0x00,0x00,0x48,0x21,0x01,0x40,0x38,0x21,
+0x27,0x8b,0x96,0x44,0x27,0x8a,0x96,0x50,0x00,0x06,0x40,0xc0,0x01,0x06,0x18,0x21,
+0x00,0x03,0x18,0x80,0x00,0x6b,0x10,0x21,0x8c,0x44,0x00,0x18,0x00,0x6a,0x18,0x21,
+0x80,0x65,0x00,0x06,0x8c,0x82,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0xff,0xff,
+0x00,0x45,0x10,0x21,0x30,0x44,0x00,0xff,0x00,0x02,0x12,0x02,0x01,0x22,0x18,0x21,
+0x24,0x62,0x00,0x01,0x14,0x80,0x00,0x02,0x30,0x49,0x00,0xff,0x30,0x69,0x00,0xff,
+0x01,0x06,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x4d,0x10,0x21,0x24,0xe7,0xff,0xff,
+0x94,0x46,0x00,0x02,0x14,0xe0,0xff,0xe9,0x00,0x06,0x40,0xc0,0x91,0x82,0x00,0x10,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x20,0x3c,0x06,0xb0,0x03,0xa5,0x8f,0x00,0x0c,
+0x03,0x0e,0x20,0x21,0x00,0x04,0x20,0x80,0x00,0x8d,0x20,0x21,0x94,0x82,0x00,0x04,
+0x3c,0x03,0xb0,0x08,0x3c,0x07,0xb0,0x03,0x00,0x02,0x28,0xc0,0x00,0xa2,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x4d,0x10,0x21,0x00,0xa3,0x28,0x21,0x27,0x26,0x93,0x34,
+0x34,0x03,0xff,0xff,0x34,0xe7,0x00,0x20,0xac,0xe6,0x00,0x00,0xa4,0x83,0x00,0x02,
+0xa4,0x43,0x00,0x00,0xac,0xa3,0x00,0x00,0x91,0x82,0x00,0x10,0x91,0x83,0x00,0x04,
+0xa5,0x8e,0x00,0x0e,0x01,0x22,0x10,0x21,0x14,0x60,0x00,0x05,0xa1,0x82,0x00,0x10,
+0x91,0x82,0x00,0x16,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xfd,0xa1,0x82,0x00,0x16,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x95,0x82,0x00,0x0e,0x3c,0x03,0xb0,0x08,
+0x00,0x02,0x20,0xc0,0x00,0x82,0x20,0x21,0x00,0x04,0x20,0x80,0x00,0x8d,0x20,0x21,
+0x94,0x82,0x00,0x04,0x34,0xc6,0x00,0x20,0x27,0x27,0x93,0x34,0x00,0x02,0x28,0xc0,
+0x00,0xa2,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0xa3,0x28,0x21,0x00,0x4d,0x10,0x21,
+0xac,0xc7,0x00,0x00,0xa4,0x8f,0x00,0x02,0xa4,0x4f,0x00,0x00,0xac,0xaf,0x00,0x00,
+0x08,0x00,0x20,0x9d,0x03,0x0e,0x20,0x21,0x08,0x00,0x20,0x78,0xa5,0x88,0x00,0x02,
+0x00,0x0e,0xc0,0xc0,0x03,0x0e,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x8d,0x96,0x40,
+0x00,0x4d,0x10,0x21,0x94,0x43,0x00,0x02,0x30,0x84,0x00,0xff,0x14,0x80,0x00,0x05,
+0xa5,0x83,0x00,0x00,0x24,0x02,0xff,0xff,0x3c,0x19,0x80,0x01,0x08,0x00,0x20,0x78,
+0xa5,0x82,0x00,0x02,0x08,0x00,0x20,0x78,0x3c,0x19,0x80,0x01,0x3c,0x08,0xb0,0x03,
+0x3c,0x02,0x80,0x01,0x27,0xbd,0xff,0x80,0x24,0x42,0x83,0x7c,0x35,0x08,0x00,0x20,
+0xaf,0xb2,0x00,0x60,0xaf,0xb1,0x00,0x5c,0xaf,0xbf,0x00,0x7c,0xaf,0xbe,0x00,0x78,
+0xaf,0xb7,0x00,0x74,0xaf,0xb6,0x00,0x70,0xaf,0xb5,0x00,0x6c,0xaf,0xb4,0x00,0x68,
+0xaf,0xb3,0x00,0x64,0xaf,0xb0,0x00,0x58,0xad,0x02,0x00,0x00,0xaf,0xa4,0x00,0x80,
+0x90,0x83,0x00,0x0a,0x27,0x82,0xba,0x40,0xaf,0xa6,0x00,0x88,0x00,0x03,0x18,0x80,
+0x00,0x62,0x18,0x21,0x8c,0x7e,0x00,0x00,0xaf,0xa7,0x00,0x8c,0x27,0x86,0x96,0x44,
+0x97,0xc3,0x00,0x14,0x30,0xb1,0xff,0xff,0x00,0x03,0x20,0xc0,0xaf,0xa3,0x00,0x1c,
+0x00,0x83,0x18,0x21,0xaf,0xa4,0x00,0x50,0x00,0x03,0x18,0x80,0x27,0x84,0x96,0x50,
+0x00,0x64,0x20,0x21,0x80,0x82,0x00,0x06,0x00,0x66,0x18,0x21,0x8c,0x66,0x00,0x18,
+0x24,0x42,0x00,0x02,0x00,0x02,0x1f,0xc2,0x8c,0xc4,0x00,0x08,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x43,0x00,0x02,0x10,0x40,0x00,0x04,0x2f,0xc2,0x00,0x04,0x1c,0x82,
+0x00,0x04,0x24,0x42,0x30,0x63,0x00,0x01,0x00,0xc2,0x38,0x21,0x30,0x84,0x00,0x01,
+0x24,0x02,0x00,0x01,0xaf,0xa5,0x00,0x3c,0xaf,0xa3,0x00,0x34,0xaf,0xa4,0x00,0x38,
+0xaf,0xa0,0x00,0x40,0xaf,0xa0,0x00,0x44,0xaf,0xa2,0x00,0x20,0x83,0xc3,0x00,0x12,
+0x8f,0xb2,0x00,0x1c,0x8c,0xd0,0x00,0x0c,0x14,0xa0,0x01,0xa2,0xaf,0xa3,0x00,0x28,
+0x00,0x10,0x10,0x82,0x30,0x45,0x00,0x07,0x10,0xa0,0x00,0x11,0xaf,0xa0,0x00,0x30,
+0x8f,0xa4,0x00,0x90,0x27,0x82,0x86,0xb0,0x00,0x04,0x18,0x40,0x00,0x62,0x18,0x21,
+0x24,0xa2,0x00,0x06,0x8f,0xa5,0x00,0x20,0x94,0x64,0x00,0x00,0x00,0x45,0x10,0x04,
+0x00,0x44,0x00,0x1a,0x14,0x80,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x0d,
+0x00,0x00,0x10,0x12,0x24,0x42,0x00,0x20,0x30,0x42,0xff,0xfc,0xaf,0xa2,0x00,0x30,
+0x8f,0xa3,0x00,0x1c,0x8f,0xa4,0x00,0x28,0x34,0x02,0xff,0xff,0xaf,0xa0,0x00,0x2c,
+0xaf,0xa2,0x00,0x48,0xaf,0xa3,0x00,0x4c,0x00,0x60,0xb0,0x21,0x00,0x00,0xb8,0x21,
+0x18,0x80,0x00,0x3b,0xaf,0xa0,0x00,0x24,0x00,0x11,0x89,0x02,0xaf,0xb1,0x00,0x54,
+0x00,0x80,0xa8,0x21,0x00,0x12,0xa0,0xc0,0x02,0x92,0x10,0x21,0x00,0x02,0x80,0x80,
+0x27,0x85,0x96,0x40,0x02,0x05,0x18,0x21,0x94,0x63,0x00,0x02,0x02,0x40,0x20,0x21,
+0x00,0x00,0x28,0x21,0x0c,0x00,0x17,0x43,0xaf,0xa3,0x00,0x18,0x90,0x42,0x00,0x00,
+0x24,0x03,0x00,0x08,0x30,0x42,0x00,0x0c,0x10,0x43,0x01,0x5c,0x24,0x04,0x00,0x01,
+0x24,0x02,0x00,0x01,0x10,0x82,0x01,0x3b,0x3c,0x03,0xb0,0x03,0x34,0x63,0x01,0x04,
+0x02,0x92,0x20,0x21,0x94,0x66,0x00,0x00,0x00,0x04,0x20,0x80,0x27,0x82,0x96,0x48,
+0x00,0x82,0x10,0x21,0x27,0x83,0x96,0x50,0x80,0x45,0x00,0x06,0x00,0x83,0x20,0x21,
+0x30,0xd0,0xff,0xff,0x80,0x91,0x00,0x05,0x80,0x93,0x00,0x04,0x8f,0xa4,0x00,0x80,
+0x32,0x03,0x00,0xff,0x00,0x10,0x12,0x03,0x38,0xa5,0x00,0x00,0x00,0x60,0x80,0x21,
+0x00,0x45,0x80,0x0a,0xa4,0x82,0x00,0x44,0x12,0x20,0x01,0x1c,0xa4,0x83,0x00,0x46,
+0x02,0x71,0x10,0x21,0x00,0x50,0x10,0x2a,0x14,0x40,0x00,0xbb,0x02,0x92,0x10,0x21,
+0x93,0x82,0x91,0x51,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,0x14,0x40,0x00,0xae,
+0x02,0x92,0x28,0x21,0x26,0xe2,0x00,0x01,0x30,0x57,0xff,0xff,0x02,0x40,0xb0,0x21,
+0x26,0xb5,0xff,0xff,0x8f,0xb2,0x00,0x18,0x16,0xa0,0xff,0xca,0x00,0x00,0x00,0x00,
+0x16,0xe0,0x00,0x9e,0x02,0xc0,0x38,0x21,0x8f,0xa5,0x00,0x90,0x00,0x00,0x00,0x00,
+0x2c,0xa2,0x00,0x10,0x10,0x40,0x00,0x2e,0x00,0x00,0x00,0x00,0x8f,0xa2,0x00,0x24,
+0x00,0x00,0x00,0x00,0x18,0x40,0x00,0x2a,0x24,0x03,0x00,0x01,0x97,0xd2,0x00,0x14,
+0xa3,0xc3,0x00,0x12,0x00,0x12,0x10,0xc0,0x00,0x52,0x10,0x21,0x00,0x02,0x80,0x80,
+0x27,0x82,0x96,0x50,0x02,0x02,0x10,0x21,0x80,0x43,0x00,0x06,0x27,0x84,0x96,0x44,
+0x02,0x04,0x20,0x21,0x24,0x63,0x00,0x02,0x00,0x03,0x17,0xc2,0x00,0x62,0x18,0x21,
+0x8c,0x85,0x00,0x18,0x00,0x03,0x18,0x43,0x00,0x03,0x18,0x40,0x00,0xa3,0x38,0x21,
+0x8f,0xa3,0x00,0x3c,0x00,0x00,0x00,0x00,0x14,0x60,0x00,0x0d,0x00,0x00,0x00,0x00,
+0x27,0x82,0x96,0x40,0x02,0x02,0x10,0x21,0x94,0x43,0x00,0x06,0x24,0x02,0x00,0x01,
+0xa7,0xc3,0x00,0x1a,0x7b,0xbe,0x03,0xfc,0x7b,0xb6,0x03,0xbc,0x7b,0xb4,0x03,0x7c,
+0x7b,0xb2,0x03,0x3c,0x7b,0xb0,0x02,0xfc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x80,
+0x8f,0xa4,0x00,0x90,0x8f,0xa5,0x00,0x38,0x8f,0xa6,0x00,0x34,0xaf,0xa0,0x00,0x10,
+0x0c,0x00,0x0d,0xfe,0xaf,0xa0,0x00,0x14,0x08,0x00,0x21,0x94,0x00,0x00,0x00,0x00,
+0x8f,0xa4,0x00,0x44,0x8f,0xa3,0x00,0x24,0x8f,0xa5,0x00,0x2c,0x30,0x82,0x00,0x03,
+0xa3,0xc3,0x00,0x12,0x00,0x02,0x10,0x23,0x8f,0xa4,0x00,0x80,0x30,0x42,0x00,0x03,
+0x00,0xa2,0x10,0x23,0xa7,0xc2,0x00,0x1a,0x84,0x83,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x83,0x96,0x44,
+0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x18,0x00,0x00,0x00,0x00,0x8c,0x83,0x00,0x04,
+0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x10,0x14,0x60,0x00,0x18,0x00,0x00,0x00,0x00,
+0x8f,0xa5,0x00,0x50,0x8f,0xa2,0x00,0x1c,0x00,0x00,0x00,0x00,0x00,0xa2,0x18,0x21,
+0x00,0x03,0x18,0x80,0x27,0x82,0x96,0x58,0x00,0x62,0x18,0x21,0x90,0x65,0x00,0x00,
+0x27,0x83,0xba,0xe0,0x00,0x05,0x11,0x00,0x00,0x45,0x10,0x23,0x00,0x02,0x10,0x80,
+0x00,0x45,0x10,0x23,0x00,0x02,0x30,0x80,0x00,0xc3,0x38,0x21,0x90,0xe4,0x00,0x00,
+0x24,0x02,0x00,0x1b,0x10,0x82,0x00,0x0e,0x00,0x00,0x00,0x00,0x8f,0xa2,0x00,0x24,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x04,0x00,0xa0,0x20,0x21,0x8f,0xa2,0x00,0x24,
+0x08,0x00,0x21,0x99,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x21,0x00,0x00,0x28,0x21,
+0x0c,0x00,0x25,0xc4,0x00,0x00,0x38,0x21,0x08,0x00,0x21,0xd7,0x00,0x00,0x00,0x00,
+0x27,0x82,0xbb,0xc0,0x00,0xc2,0x20,0x21,0x94,0x83,0x00,0x00,0x24,0x02,0x00,0x05,
+0x10,0x43,0x00,0x25,0x24,0x62,0x00,0x01,0xa4,0x82,0x00,0x00,0x8f,0xa3,0x00,0x24,
+0x8f,0xa4,0x00,0x28,0x00,0x00,0x00,0x00,0x10,0x64,0xff,0xec,0x00,0x00,0x00,0x00,
+0x10,0x60,0xff,0xea,0x00,0x00,0x00,0x00,0x27,0x82,0xbb,0xb8,0x00,0xc2,0x20,0x21,
+0x90,0x83,0x00,0x06,0x00,0x00,0x00,0x00,0x2c,0x62,0x00,0x02,0x10,0x40,0x00,0x03,
+0x24,0x62,0x00,0x01,0xa0,0x82,0x00,0x06,0x00,0x40,0x18,0x21,0x30,0x63,0x00,0xff,
+0x24,0x02,0x00,0x02,0x10,0x62,0x00,0x09,0x00,0x00,0x00,0x00,0x27,0x84,0xba,0xe4,
+0x00,0xc4,0x18,0x21,0x8c,0x62,0x00,0x58,0x00,0x00,0x00,0x00,0x00,0x02,0x10,0x23,
+0x24,0x42,0xff,0xc0,0x08,0x00,0x21,0xd7,0xac,0xe2,0x00,0xd0,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x01,0x08,0x8c,0x43,0x00,0x00,0x27,0x84,0xba,0xe4,0x00,0xc4,0x10,0x21,
+0x08,0x00,0x21,0xfc,0xac,0x43,0x00,0xe0,0x27,0x83,0xbb,0xb8,0x00,0xc3,0x18,0x21,
+0x90,0x62,0x00,0x06,0x00,0x00,0x00,0x00,0x2c,0x42,0x00,0x02,0x10,0x40,0xff,0xc7,
+0xa4,0x80,0x00,0x00,0x08,0x00,0x21,0xd7,0xa0,0x60,0x00,0x06,0x8f,0xa5,0x00,0x48,
+0x8f,0xa6,0x00,0x4c,0x03,0xc0,0x20,0x21,0x0c,0x00,0x20,0x4f,0xaf,0xb7,0x00,0x10,
+0x08,0x00,0x21,0x76,0x00,0x00,0x00,0x00,0x00,0x05,0x28,0x80,0x27,0x82,0x96,0x40,
+0x00,0xa2,0x28,0x21,0x00,0x00,0x20,0x21,0x0c,0x00,0x01,0x49,0x00,0x00,0x00,0x00,
+0x08,0x00,0x21,0x6e,0x26,0xe2,0x00,0x01,0x00,0x02,0x80,0x80,0x27,0x83,0x96,0x50,
+0x02,0x03,0x18,0x21,0x26,0x31,0x00,0x01,0x03,0xc0,0x20,0x21,0x02,0x40,0x28,0x21,
+0x0c,0x00,0x23,0x1c,0xa0,0x71,0x00,0x05,0x14,0x40,0xff,0x45,0x00,0x00,0x00,0x00,
+0x16,0xe0,0x00,0x4b,0x02,0xc0,0x38,0x21,0x8f,0xa5,0x00,0x24,0x8f,0xb6,0x00,0x18,
+0x8f,0xa3,0x00,0x20,0x24,0xa5,0x00,0x01,0x24,0x02,0x00,0x01,0xaf,0xb2,0x00,0x48,
+0xaf,0xb6,0x00,0x4c,0x10,0x62,0x00,0x40,0xaf,0xa5,0x00,0x24,0x27,0x82,0x96,0x40,
+0x02,0x02,0x10,0x21,0x94,0x42,0x00,0x06,0x8f,0xa5,0x00,0x30,0xaf,0xa0,0x00,0x20,
+0xaf,0xa2,0x00,0x44,0x8f,0xa4,0x00,0x44,0x30,0x42,0x00,0x03,0x00,0x02,0x10,0x23,
+0x30,0x42,0x00,0x03,0x00,0x82,0x10,0x21,0x24,0x42,0x00,0x04,0x30,0x42,0xff,0xff,
+0x00,0x45,0x18,0x2b,0x10,0x60,0x00,0x29,0x00,0x00,0x00,0x00,0x8f,0xa4,0x00,0x2c,
+0x00,0xa2,0x10,0x23,0x00,0x85,0x18,0x21,0x30,0x63,0xff,0xff,0x30,0x45,0xff,0xff,
+0xaf,0xa3,0x00,0x2c,0x02,0x92,0x30,0x21,0x00,0x06,0x30,0x80,0x27,0x82,0x96,0x44,
+0x00,0xc2,0x10,0x21,0x8c,0x47,0x00,0x18,0x3c,0x04,0x80,0xff,0x34,0x84,0xff,0xff,
+0x8c,0xe3,0x00,0x04,0x3c,0x02,0x7f,0x00,0x00,0x05,0x2d,0x40,0x00,0xa2,0x28,0x24,
+0x00,0x64,0x18,0x24,0x00,0x65,0x18,0x25,0xac,0xe3,0x00,0x04,0x8f,0xa3,0x00,0x90,
+0x27,0x82,0x96,0x50,0x00,0xc2,0x10,0x21,0xa0,0x43,0x00,0x00,0x8c,0xe4,0x00,0x08,
+0x00,0x00,0x00,0x00,0x00,0x04,0x27,0xc2,0x10,0x80,0xff,0x0d,0xaf,0xa4,0x00,0x3c,
+0x80,0x42,0x00,0x06,0x8f,0xa4,0x00,0x40,0x24,0x42,0x00,0x02,0x00,0x02,0x1f,0xc2,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x43,0x00,0x02,0x10,0x40,0x00,0xe2,0x38,0x21,
+0xa4,0xe4,0x00,0x00,0x08,0x00,0x21,0x71,0x26,0xb5,0xff,0xff,0x8f,0xa5,0x00,0x2c,
+0x00,0x00,0x00,0x00,0x00,0xa2,0x10,0x21,0x30,0x42,0xff,0xff,0xaf,0xa2,0x00,0x2c,
+0x08,0x00,0x22,0x4d,0x00,0x00,0x28,0x21,0x08,0x00,0x22,0x37,0xa7,0xd2,0x00,0x14,
+0x8f,0xa5,0x00,0x48,0x8f,0xa6,0x00,0x4c,0x03,0xc0,0x20,0x21,0x0c,0x00,0x20,0x4f,
+0xaf,0xb7,0x00,0x10,0x08,0x00,0x22,0x2e,0x00,0x00,0xb8,0x21,0x02,0x40,0x20,0x21,
+0x0c,0x00,0x17,0x43,0x00,0x00,0x28,0x21,0x00,0x40,0x18,0x21,0x94,0x42,0x00,0x00,
+0x00,0x00,0x00,0x00,0x34,0x42,0x08,0x00,0xa4,0x62,0x00,0x00,0x08,0x00,0x21,0x65,
+0x02,0x71,0x10,0x21,0x02,0x92,0x18,0x21,0x00,0x03,0x80,0x80,0x27,0x82,0x96,0x44,
+0x02,0x02,0x10,0x21,0x8c,0x44,0x00,0x18,0x00,0x00,0x00,0x00,0x8c,0x83,0x00,0x04,
+0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x10,0x10,0x60,0x00,0x0a,0x24,0x06,0x00,0x01,
+0x93,0x82,0x91,0x51,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,0x10,0x40,0xfe,0xd5,
+0x00,0x00,0x00,0x00,0x27,0x85,0x96,0x40,0x02,0x05,0x28,0x21,0x08,0x00,0x22,0x1e,
+0x3c,0x04,0x00,0x80,0x27,0x83,0x96,0x58,0x27,0x82,0x96,0x50,0x02,0x03,0x18,0x21,
+0x02,0x02,0x10,0x21,0x90,0x64,0x00,0x00,0x90,0x45,0x00,0x05,0x0c,0x00,0x25,0xc4,
+0x00,0x00,0x38,0x21,0x08,0x00,0x22,0x94,0x00,0x00,0x00,0x00,0x27,0x82,0x96,0x58,
+0x02,0x02,0x10,0x21,0x94,0x43,0x00,0x02,0x8f,0xa2,0x00,0x54,0x00,0x03,0x19,0x02,
+0x00,0x62,0x18,0x23,0x30,0x63,0x0f,0xff,0x28,0x62,0x00,0x20,0x10,0x40,0x00,0x06,
+0x28,0x62,0x00,0x40,0x8f,0xa4,0x00,0x88,0x00,0x00,0x00,0x00,0x00,0x64,0x10,0x06,
+0x08,0x00,0x21,0x4c,0x30,0x44,0x00,0x01,0x10,0x40,0x00,0x04,0x00,0x00,0x00,0x00,
+0x8f,0xa5,0x00,0x8c,0x08,0x00,0x22,0xb4,0x00,0x65,0x10,0x06,0x08,0x00,0x21,0x4c,
+0x00,0x00,0x20,0x21,0x8f,0xa4,0x00,0x90,0x8f,0xa5,0x00,0x38,0x8f,0xa6,0x00,0x34,
+0xaf,0xa0,0x00,0x10,0x0c,0x00,0x0d,0xfe,0xaf,0xa2,0x00,0x14,0x30,0x42,0xff,0xff,
+0x08,0x00,0x21,0x1c,0xaf,0xa2,0x00,0x40,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,
+0x27,0xbd,0xff,0xe0,0x34,0x42,0x00,0x20,0x24,0x63,0x8b,0x18,0xaf,0xb1,0x00,0x14,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x18,0xac,0x43,0x00,0x00,0x90,0x82,0x00,0x0a,
+0x00,0x80,0x80,0x21,0x14,0x40,0x00,0x45,0x00,0x00,0x88,0x21,0x92,0x02,0x00,0x04,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x3c,0x00,0x00,0x00,0x00,0x12,0x20,0x00,0x18,
+0x00,0x00,0x00,0x00,0x92,0x02,0x00,0x16,0x92,0x05,0x00,0x0a,0x30,0x42,0x00,0xfc,
+0x10,0xa0,0x00,0x03,0xa2,0x02,0x00,0x16,0x34,0x42,0x00,0x01,0xa2,0x02,0x00,0x16,
+0x92,0x04,0x00,0x04,0x00,0x00,0x00,0x00,0x30,0x83,0x00,0xff,0x10,0x60,0x00,0x05,
+0x00,0x00,0x00,0x00,0x92,0x02,0x00,0x16,0x00,0x00,0x00,0x00,0x34,0x42,0x00,0x02,
+0xa2,0x02,0x00,0x16,0x10,0x60,0x00,0x0a,0x00,0x00,0x00,0x00,0x14,0xa0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x96,0x02,0x00,0x00,0xa2,0x00,0x00,0x17,0xa6,0x02,0x00,0x14,
+0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,
+0x14,0x80,0x00,0x05,0x24,0x02,0x00,0x01,0x96,0x03,0x00,0x06,0xa2,0x02,0x00,0x17,
+0x08,0x00,0x22,0xf0,0xa6,0x03,0x00,0x14,0x96,0x04,0x00,0x00,0x96,0x05,0x00,0x06,
+0x27,0x86,0x96,0x40,0x00,0x04,0x10,0xc0,0x00,0x05,0x18,0xc0,0x00,0x44,0x10,0x21,
+0x00,0x65,0x18,0x21,0x00,0x02,0x10,0x80,0x00,0x03,0x18,0x80,0x00,0x66,0x18,0x21,
+0x00,0x46,0x10,0x21,0x8c,0x65,0x00,0x08,0x8c,0x44,0x00,0x08,0x0c,0x00,0x17,0x34,
+0x00,0x00,0x00,0x00,0x30,0x43,0x00,0xff,0x10,0x60,0x00,0x04,0xa2,0x02,0x00,0x17,
+0x96,0x02,0x00,0x06,0x08,0x00,0x22,0xf0,0xa6,0x02,0x00,0x14,0x96,0x02,0x00,0x00,
+0x08,0x00,0x22,0xf0,0xa6,0x02,0x00,0x14,0x96,0x05,0x00,0x00,0x0c,0x00,0x23,0x1c,
+0x02,0x00,0x20,0x21,0x08,0x00,0x22,0xd7,0x02,0x22,0x88,0x21,0x94,0x85,0x00,0x06,
+0x0c,0x00,0x23,0x1c,0x00,0x00,0x00,0x00,0x08,0x00,0x22,0xd3,0x00,0x40,0x88,0x21,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x01,0x34,0x63,0x00,0x20,0x24,0x42,0x8c,0x70,
+0x27,0xbd,0xff,0xf0,0xac,0x62,0x00,0x00,0x00,0x00,0x10,0x21,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x10,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x01,0x34,0x63,0x00,0x20,
+0x24,0x42,0x8c,0x94,0xac,0x62,0x00,0x00,0x90,0x89,0x00,0x0a,0x00,0x80,0x30,0x21,
+0x11,0x20,0x00,0x05,0x00,0xa0,0x50,0x21,0x90,0x82,0x00,0x17,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x1b,0x00,0x00,0x00,0x00,0x90,0xc7,0x00,0x04,0x00,0x00,0x00,0x00,
+0x10,0xe0,0x00,0x1b,0x00,0x00,0x00,0x00,0x94,0xc8,0x00,0x00,0x27,0x83,0x96,0x40,
+0x93,0x85,0x91,0x50,0x00,0x08,0x10,0xc0,0x00,0x48,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x08,0x00,0xe5,0x28,0x2b,0x10,0xa0,0x00,0x06,
+0x01,0x44,0x18,0x23,0x8f,0x82,0x91,0x68,0x00,0x00,0x00,0x00,0x00,0x43,0x10,0x2b,
+0x10,0x40,0x00,0x05,0x00,0x00,0x00,0x00,0x24,0x03,0x00,0x10,0xa4,0xc8,0x00,0x14,
+0x03,0xe0,0x00,0x08,0x00,0x60,0x10,0x21,0x11,0x20,0x00,0x05,0x00,0x00,0x00,0x00,
+0x94,0xc2,0x00,0x06,0x24,0x03,0x00,0x08,0x08,0x00,0x23,0x48,0xa4,0xc2,0x00,0x14,
+0x08,0x00,0x23,0x48,0x00,0x00,0x18,0x21,0x27,0xbd,0xff,0xc8,0xaf,0xb5,0x00,0x2c,
+0xaf,0xb4,0x00,0x28,0xaf,0xb3,0x00,0x24,0xaf,0xb0,0x00,0x18,0xaf,0xbf,0x00,0x30,
+0xaf,0xb2,0x00,0x20,0xaf,0xb1,0x00,0x1c,0x94,0x91,0x00,0x06,0x00,0x80,0xa0,0x21,
+0x3c,0x02,0x80,0x01,0x3c,0x04,0xb0,0x03,0x00,0x11,0xa8,0xc0,0x34,0x84,0x00,0x20,
+0x24,0x42,0x8d,0x48,0x02,0xb1,0x48,0x21,0xac,0x82,0x00,0x00,0x00,0x09,0x48,0x80,
+0x24,0x03,0x00,0x01,0x27,0x82,0x96,0x50,0xa2,0x83,0x00,0x12,0x01,0x22,0x10,0x21,
+0x27,0x84,0x96,0x44,0x01,0x24,0x20,0x21,0x80,0x48,0x00,0x06,0x8c,0x8a,0x00,0x18,
+0x27,0x83,0x96,0x60,0x01,0x23,0x48,0x21,0x8d,0x24,0x00,0x00,0x25,0x08,0x00,0x02,
+0x8d,0x42,0x00,0x00,0x8d,0x49,0x00,0x04,0x00,0x08,0x17,0xc2,0x8d,0x43,0x00,0x08,
+0x01,0x02,0x40,0x21,0x00,0x04,0x25,0xc2,0x00,0x08,0x40,0x43,0x30,0x84,0x00,0x01,
+0x00,0x03,0x1f,0xc2,0x00,0x08,0x40,0x40,0x00,0xe0,0x80,0x21,0x00,0x64,0x18,0x24,
+0x00,0x09,0x49,0x42,0x01,0x48,0x10,0x21,0x00,0xa0,0x98,0x21,0x00,0xa0,0x20,0x21,
+0x00,0x40,0x38,0x21,0x02,0x00,0x28,0x21,0x14,0x60,0x00,0x19,0x31,0x29,0x00,0x01,
+0x94,0x42,0x00,0x00,0x02,0xb1,0x88,0x21,0x02,0x00,0x28,0x21,0x00,0x11,0x88,0x80,
+0x27,0x90,0x96,0x40,0x02,0x30,0x80,0x21,0x96,0x03,0x00,0x06,0x30,0x52,0xff,0xff,
+0x02,0x60,0x20,0x21,0x00,0x60,0x30,0x21,0xa6,0x83,0x00,0x1a,0x27,0x82,0x96,0x48,
+0x0c,0x00,0x0d,0xd7,0x02,0x22,0x88,0x21,0x00,0x52,0x10,0x21,0x96,0x03,0x00,0x06,
+0xa6,0x22,0x00,0x04,0x8f,0xbf,0x00,0x30,0x7b,0xb4,0x01,0x7c,0x7b,0xb2,0x01,0x3c,
+0x7b,0xb0,0x00,0xfc,0x00,0x60,0x10,0x21,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x38,
+0xaf,0xa9,0x00,0x10,0x0c,0x00,0x0d,0xfe,0xaf,0xa0,0x00,0x14,0x08,0x00,0x23,0x86,
+0x02,0xb1,0x88,0x21,0x27,0xbd,0xff,0xc0,0xaf,0xbe,0x00,0x38,0xaf,0xb7,0x00,0x34,
+0xaf,0xb6,0x00,0x30,0xaf,0xb5,0x00,0x2c,0xaf,0xb3,0x00,0x24,0xaf,0xb1,0x00,0x1c,
+0xaf,0xbf,0x00,0x3c,0xaf,0xb4,0x00,0x28,0xaf,0xb2,0x00,0x20,0xaf,0xb0,0x00,0x18,
+0x94,0x90,0x00,0x00,0x3c,0x08,0xb0,0x03,0x35,0x08,0x00,0x20,0x00,0x10,0x10,0xc0,
+0x00,0x50,0x18,0x21,0x00,0x40,0x88,0x21,0x3c,0x02,0x80,0x01,0x00,0x03,0x48,0x80,
+0x24,0x42,0x8e,0x84,0x00,0x80,0x98,0x21,0x27,0x84,0x96,0x50,0x01,0x24,0x20,0x21,
+0x93,0xb7,0x00,0x53,0xad,0x02,0x00,0x00,0x80,0x83,0x00,0x06,0x27,0x82,0x96,0x44,
+0x01,0x22,0x10,0x21,0x8c,0x44,0x00,0x18,0x24,0x63,0x00,0x02,0x00,0x03,0x17,0xc2,
+0x8c,0x88,0x00,0x08,0x00,0x62,0x18,0x21,0x00,0x03,0x18,0x43,0x00,0x03,0x18,0x40,
+0xaf,0xa7,0x00,0x4c,0x2c,0xa2,0x00,0x10,0x00,0xa0,0xa8,0x21,0x00,0x83,0x50,0x21,
+0x00,0x08,0x47,0xc2,0x00,0xc0,0x58,0x21,0x00,0x00,0xb0,0x21,0x8c,0x92,0x00,0x0c,
+0x14,0x40,0x00,0x13,0x00,0x00,0xf0,0x21,0x92,0x67,0x00,0x04,0x24,0x14,0x00,0x01,
+0x12,0x87,0x00,0x10,0x02,0x30,0x10,0x21,0x27,0x83,0x96,0x58,0x01,0x23,0x18,0x21,
+0x80,0x64,0x00,0x00,0x27,0x83,0xbb,0xb0,0x00,0x04,0x11,0x00,0x00,0x44,0x10,0x23,
+0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,
+0x90,0x44,0x00,0x04,0x00,0x00,0x00,0x00,0x10,0x80,0x00,0x23,0x00,0x00,0x00,0x00,
+0x02,0x30,0x10,0x21,0x00,0x02,0x80,0x80,0x24,0x04,0x00,0x01,0x27,0x83,0x96,0x60,
+0xa2,0x64,0x00,0x12,0x02,0x03,0x18,0x21,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x02,0x15,0xc2,0x30,0x42,0x00,0x01,0x01,0x02,0x10,0x24,0x14,0x40,0x00,0x0e,
+0x02,0xa0,0x20,0x21,0x27,0x82,0x96,0x40,0x02,0x02,0x10,0x21,0x94,0x43,0x00,0x06,
+0x00,0x00,0x00,0x00,0xa6,0x63,0x00,0x1a,0x94,0x42,0x00,0x06,0x7b,0xbe,0x01,0xfc,
+0x7b,0xb6,0x01,0xbc,0x7b,0xb4,0x01,0x7c,0x7b,0xb2,0x01,0x3c,0x7b,0xb0,0x00,0xfc,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x40,0x8f,0xa5,0x00,0x4c,0x01,0x60,0x30,0x21,
+0x01,0x40,0x38,0x21,0xaf,0xa0,0x00,0x10,0x0c,0x00,0x0d,0xfe,0xaf,0xa0,0x00,0x14,
+0x08,0x00,0x23,0xed,0x00,0x00,0x00,0x00,0x27,0x83,0x96,0x60,0x01,0x23,0x18,0x21,
+0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x15,0xc2,0x30,0x42,0x00,0x01,
+0x01,0x02,0x10,0x24,0x14,0x40,0x00,0xaf,0x00,0xa0,0x20,0x21,0x32,0x4f,0x00,0x03,
+0x00,0x12,0x10,0x82,0x25,0xe3,0x00,0x0d,0x30,0x45,0x00,0x07,0x00,0x74,0x78,0x04,
+0x10,0xa0,0x00,0x0e,0x00,0x00,0x90,0x21,0x27,0x82,0x86,0xb0,0x00,0x15,0x18,0x40,
+0x00,0x62,0x18,0x21,0x94,0x64,0x00,0x00,0x24,0xa2,0x00,0x06,0x00,0x54,0x10,0x04,
+0x00,0x44,0x00,0x1a,0x14,0x80,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x0d,
+0x00,0x00,0x10,0x12,0x24,0x42,0x00,0x20,0x30,0x52,0xff,0xfc,0x02,0x30,0x10,0x21,
+0x27,0x83,0x96,0x50,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x90,0x44,0x00,0x03,
+0x00,0x00,0x00,0x00,0x30,0x83,0x00,0xff,0x2c,0x62,0x00,0x0c,0x14,0x40,0x00,0x04,
+0x2c,0x62,0x00,0x19,0x30,0x82,0x00,0x0f,0x24,0x43,0x00,0x0c,0x2c,0x62,0x00,0x19,
+0x10,0x40,0x00,0x19,0x24,0x0e,0x00,0x20,0x24,0x62,0xff,0xe9,0x2c,0x42,0x00,0x02,
+0x14,0x40,0x00,0x15,0x24,0x0e,0x00,0x08,0x24,0x62,0xff,0xeb,0x2c,0x42,0x00,0x02,
+0x14,0x40,0x00,0x11,0x24,0x0e,0x00,0x04,0x24,0x02,0x00,0x14,0x10,0x62,0x00,0x0e,
+0x24,0x0e,0x00,0x02,0x24,0x62,0xff,0xef,0x2c,0x42,0x00,0x03,0x14,0x40,0x00,0x0a,
+0x24,0x0e,0x00,0x10,0x24,0x62,0xff,0xf1,0x2c,0x42,0x00,0x02,0x14,0x40,0x00,0x06,
+0x24,0x0e,0x00,0x04,0x24,0x62,0xff,0xf3,0x2c,0x42,0x00,0x02,0x24,0x0e,0x00,0x02,
+0x24,0x03,0x00,0x01,0x00,0x62,0x70,0x0a,0x30,0xe2,0x00,0xff,0x00,0x00,0x48,0x21,
+0x00,0x00,0x68,0x21,0x10,0x40,0x00,0x6d,0x00,0x00,0x58,0x21,0x3c,0x14,0x80,0xff,
+0x27,0x99,0x96,0x40,0x01,0xf2,0xc0,0x23,0x36,0x94,0xff,0xff,0x01,0xc9,0x10,0x2a,
+0x14,0x40,0x00,0x64,0x24,0x03,0x00,0x04,0x00,0x10,0x28,0xc0,0x00,0xb0,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x59,0x10,0x21,0x94,0x56,0x00,0x06,0x00,0x00,0x00,0x00,
+0x32,0xcc,0x00,0x03,0x00,0x6c,0x10,0x23,0x30,0x42,0x00,0x03,0x02,0xc2,0x10,0x21,
+0x24,0x42,0x00,0x04,0x30,0x51,0xff,0xff,0x02,0x32,0x18,0x2b,0x10,0x60,0x00,0x4d,
+0x01,0xf1,0x10,0x23,0x02,0x51,0x10,0x23,0x01,0x78,0x18,0x2b,0x10,0x60,0x00,0x34,
+0x30,0x44,0xff,0xff,0x29,0x22,0x00,0x40,0x10,0x40,0x00,0x31,0x01,0x72,0x18,0x21,
+0x25,0x22,0x00,0x01,0x00,0x02,0x16,0x00,0x00,0x02,0x4e,0x03,0x00,0xb0,0x10,0x21,
+0x00,0x02,0x30,0x80,0x27,0x82,0x96,0x44,0x30,0x6b,0xff,0xff,0x00,0xc2,0x18,0x21,
+0x8c,0x67,0x00,0x18,0x00,0x04,0x25,0x40,0x3c,0x03,0x7f,0x00,0x8c,0xe2,0x00,0x04,
+0x00,0x83,0x20,0x24,0x27,0x83,0x96,0x50,0x00,0x54,0x10,0x24,0x00,0xc3,0x28,0x21,
+0x00,0x44,0x10,0x25,0xac,0xe2,0x00,0x04,0x16,0xe0,0x00,0x02,0xa0,0xb5,0x00,0x00,
+0xa0,0xb5,0x00,0x03,0x27,0x84,0x96,0x60,0x00,0xc4,0x18,0x21,0x8c,0x62,0x00,0x00,
+0x8c,0xe8,0x00,0x08,0x00,0x02,0x15,0xc2,0x00,0x08,0x47,0xc2,0x30,0x42,0x00,0x01,
+0x01,0x02,0x10,0x24,0x10,0x40,0x00,0x0a,0x00,0x00,0x00,0x00,0x80,0xa2,0x00,0x06,
+0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x02,0x00,0x02,0x1f,0xc2,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x43,0x00,0x02,0x10,0x40,0x00,0xe2,0x50,0x21,0xa5,0x5e,0x00,0x00,
+0x92,0x62,0x00,0x04,0x25,0xad,0x00,0x01,0x27,0x84,0x96,0x40,0x00,0xc4,0x18,0x21,
+0x01,0xa2,0x10,0x2a,0x94,0x70,0x00,0x02,0x14,0x40,0xff,0xb8,0x00,0x00,0x00,0x00,
+0x96,0x63,0x00,0x14,0x00,0x0c,0x10,0x23,0xa2,0x69,0x00,0x12,0x30,0x42,0x00,0x03,
+0x01,0x62,0x10,0x23,0x00,0x03,0x80,0xc0,0x8f,0xa5,0x00,0x4c,0x30,0x4b,0xff,0xff,
+0x02,0x03,0x80,0x21,0x27,0x82,0x96,0x48,0x00,0x10,0x80,0x80,0xa6,0x6b,0x00,0x1a,
+0x02,0xa0,0x20,0x21,0x01,0x60,0x30,0x21,0x01,0x60,0x88,0x21,0x0c,0x00,0x0d,0xd7,
+0x02,0x02,0x80,0x21,0x00,0x5e,0x10,0x21,0xa6,0x02,0x00,0x04,0x08,0x00,0x23,0xf3,
+0x02,0x20,0x10,0x21,0x01,0x62,0x10,0x2b,0x10,0x40,0xff,0xe9,0x00,0x00,0x20,0x21,
+0x29,0x22,0x00,0x40,0x10,0x40,0xff,0xe6,0x01,0x71,0x18,0x21,0x08,0x00,0x24,0x69,
+0x25,0x22,0x00,0x01,0x08,0x00,0x24,0x98,0x32,0xcc,0x00,0x03,0x08,0x00,0x24,0x98,
+0x00,0x00,0x60,0x21,0x8f,0xa5,0x00,0x4c,0x01,0x40,0x38,0x21,0xaf,0xa0,0x00,0x10,
+0x0c,0x00,0x0d,0xfe,0xaf,0xb4,0x00,0x14,0x92,0x67,0x00,0x04,0x08,0x00,0x24,0x0b,
+0x30,0x5e,0xff,0xff,0x30,0x84,0xff,0xff,0x00,0x04,0x30,0xc0,0x00,0xc4,0x20,0x21,
+0x00,0x04,0x20,0x80,0x27,0x82,0x96,0x40,0x3c,0x03,0xb0,0x08,0x30,0xa5,0xff,0xff,
+0x00,0x82,0x20,0x21,0x00,0xc3,0x30,0x21,0xac,0xc5,0x00,0x00,0x03,0xe0,0x00,0x08,
+0xa4,0x85,0x00,0x00,0x30,0x84,0xff,0xff,0x00,0x04,0x30,0xc0,0x00,0xc4,0x30,0x21,
+0x27,0x88,0x96,0x40,0x00,0x06,0x30,0x80,0x00,0xc8,0x30,0x21,0x94,0xc3,0x00,0x04,
+0x3c,0x02,0xb0,0x08,0x3c,0x07,0xb0,0x03,0x00,0x03,0x20,0xc0,0x00,0x83,0x18,0x21,
+0x00,0x03,0x18,0x80,0x00,0x82,0x20,0x21,0x3c,0x02,0x80,0x01,0x30,0xa5,0xff,0xff,
+0x00,0x68,0x18,0x21,0x34,0xe7,0x00,0x20,0x24,0x42,0x93,0x34,0xac,0xe2,0x00,0x00,
+0xa4,0xc5,0x00,0x02,0xa4,0x65,0x00,0x00,0x03,0xe0,0x00,0x08,0xac,0x85,0x00,0x00,
+0x30,0x84,0xff,0xff,0x00,0x04,0x10,0xc0,0x00,0x44,0x10,0x21,0x27,0x89,0x96,0x40,
+0x00,0x02,0x10,0x80,0x00,0x49,0x10,0x21,0x97,0x83,0x96,0x30,0x94,0x4a,0x00,0x04,
+0x3c,0x02,0xb0,0x08,0x00,0x03,0x38,0xc0,0x00,0x0a,0x40,0xc0,0x00,0xe3,0x18,0x21,
+0x01,0x0a,0x28,0x21,0x00,0xe2,0x38,0x21,0x01,0x02,0x40,0x21,0x00,0x03,0x18,0x80,
+0x00,0x05,0x28,0x80,0x3c,0x06,0xb0,0x03,0x3c,0x02,0x80,0x01,0x00,0xa9,0x28,0x21,
+0x00,0x69,0x18,0x21,0x34,0xc6,0x00,0x20,0x34,0x09,0xff,0xff,0x24,0x42,0x93,0x90,
+0xac,0xc2,0x00,0x00,0xa4,0x64,0x00,0x00,0xac,0xe4,0x00,0x00,0xa4,0xa9,0x00,0x00,
+0xad,0x09,0x00,0x00,0xa7,0x8a,0x96,0x30,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x01,0x34,0x63,0x00,0x20,0x24,0x42,0x94,0x10,
+0x3c,0x04,0xb0,0x03,0xac,0x62,0x00,0x00,0x34,0x84,0x01,0x10,0x8c,0x82,0x00,0x00,
+0x97,0x83,0x87,0xf4,0x30,0x42,0xff,0xff,0x10,0x62,0x00,0x16,0x24,0x0a,0x00,0x01,
+0xa7,0x82,0x87,0xf4,0xaf,0x80,0xba,0x90,0x00,0x40,0x28,0x21,0x24,0x06,0x00,0x01,
+0x27,0x84,0xba,0x94,0x25,0x43,0xff,0xff,0x00,0x66,0x10,0x04,0x00,0xa2,0x10,0x24,
+0x14,0x40,0x00,0x07,0x00,0x00,0x00,0x00,0x8c,0x83,0xff,0xfc,0x00,0x00,0x00,0x00,
+0x00,0x66,0x10,0x04,0x00,0xa2,0x10,0x24,0x38,0x42,0x00,0x00,0x01,0x42,0x18,0x0a,
+0x25,0x4a,0x00,0x01,0x2d,0x42,0x00,0x14,0xac,0x83,0x00,0x00,0x14,0x40,0xff,0xf1,
+0x24,0x84,0x00,0x04,0x3c,0x0b,0xb0,0x03,0x00,0x00,0x50,0x21,0x3c,0x0c,0x80,0x00,
+0x27,0x89,0xba,0xe0,0x35,0x6b,0x01,0x20,0x8d,0x68,0x00,0x00,0x8d,0x23,0x00,0x04,
+0x01,0x0c,0x10,0x24,0x00,0x02,0x17,0xc2,0x11,0x03,0x00,0x37,0xa1,0x22,0x00,0xdc,
+0xa1,0x20,0x00,0xd5,0xa1,0x20,0x00,0xd6,0x01,0x20,0x30,0x21,0x00,0x00,0x38,0x21,
+0x00,0x00,0x28,0x21,0x01,0x20,0x20,0x21,0x00,0xa8,0x10,0x06,0x30,0x42,0x00,0x01,
+0x10,0xe0,0x00,0x10,0xa0,0x82,0x00,0x0a,0x90,0x82,0x00,0x07,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x31,0x24,0xa2,0xff,0xff,0xa0,0x82,0x00,0x08,0x90,0x82,0x00,0x0a,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x09,0x00,0x00,0x00,0x00,0x90,0x83,0x00,0x08,
+0x00,0x00,0x00,0x00,0x00,0x03,0x10,0x40,0x00,0x43,0x10,0x21,0x00,0x46,0x10,0x21,
+0xa0,0x45,0x00,0x09,0x90,0x82,0x00,0x0a,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x07,
+0x00,0x00,0x00,0x00,0x14,0xe0,0x00,0x04,0x00,0x00,0x00,0x00,0xa0,0xc5,0x00,0xd5,
+0x24,0x07,0x00,0x01,0xa0,0x85,0x00,0x08,0xa0,0xc5,0x00,0xd6,0x24,0xa5,0x00,0x01,
+0x2c,0xa2,0x00,0x1c,0x14,0x40,0xff,0xe0,0x24,0x84,0x00,0x03,0x90,0xc4,0x00,0xd5,
+0x00,0x00,0x28,0x21,0x00,0xa4,0x10,0x2b,0x10,0x40,0x00,0x0b,0x00,0x00,0x00,0x00,
+0x00,0xc0,0x18,0x21,0xa0,0x64,0x00,0x08,0x90,0xc2,0x00,0xd5,0x24,0xa5,0x00,0x01,
+0xa0,0x62,0x00,0x09,0x90,0xc4,0x00,0xd5,0x00,0x00,0x00,0x00,0x00,0xa4,0x10,0x2b,
+0x14,0x40,0xff,0xf8,0x24,0x63,0x00,0x03,0x25,0x4a,0x00,0x01,0x2d,0x42,0x00,0x08,
+0xad,0x28,0x00,0x04,0x25,0x6b,0x00,0x04,0x14,0x40,0xff,0xbf,0x25,0x29,0x00,0xec,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x90,0x82,0x00,0x05,0x08,0x00,0x25,0x3f,
+0xa0,0x82,0x00,0x08,0x97,0x84,0x91,0x5a,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x01,
+0x27,0xbd,0xff,0xe8,0x34,0x63,0x00,0x20,0x24,0x42,0x95,0xc4,0xaf,0xbf,0x00,0x10,
+0xac,0x62,0x00,0x00,0x00,0x04,0x20,0x42,0x00,0x00,0x40,0x21,0x27,0x8f,0xba,0xe4,
+0x00,0x00,0x50,0x21,0x00,0x00,0x58,0x21,0x27,0x98,0xbb,0xc4,0x27,0x99,0xbb,0xc0,
+0x27,0x8e,0xbb,0xbe,0x27,0x8c,0xba,0xe8,0x27,0x8d,0xbb,0x40,0x27,0x89,0xbb,0xb8,
+0x00,0x0a,0x18,0x80,0x01,0x6f,0x10,0x21,0xac,0x40,0x00,0x00,0xac,0x44,0x00,0x58,
+0x00,0x6e,0x28,0x21,0x00,0x78,0x10,0x21,0xa1,0x20,0xff,0xfc,0xad,0x20,0x00,0x00,
+0xa1,0x20,0x00,0x04,0xa1,0x20,0x00,0x05,0xad,0x20,0xff,0xf8,0x00,0x79,0x18,0x21,
+0x24,0x06,0x00,0x01,0x24,0xc6,0xff,0xff,0xa0,0xa0,0x00,0x00,0xa4,0x60,0x00,0x00,
+0xac,0x40,0x00,0x00,0x24,0x63,0x00,0x02,0x24,0x42,0x00,0x04,0x04,0xc1,0xff,0xf9,
+0x24,0xa5,0x00,0x01,0x00,0x0a,0x10,0x80,0x00,0x4d,0x28,0x21,0x00,0x00,0x30,0x21,
+0x00,0x4c,0x18,0x21,0x27,0x87,0x87,0xf8,0x8c,0xe2,0x00,0x00,0x24,0xe7,0x00,0x04,
+0xac,0xa2,0x00,0x00,0xa0,0x66,0x00,0x00,0xa0,0x66,0x00,0x01,0x24,0xc6,0x00,0x01,
+0x28,0xc2,0x00,0x1c,0xa0,0x60,0x00,0x02,0x24,0xa5,0x00,0x04,0x14,0x40,0xff,0xf6,
+0x24,0x63,0x00,0x03,0x25,0x08,0x00,0x01,0x29,0x02,0x00,0x08,0x25,0x4a,0x00,0x3b,
+0x25,0x29,0x00,0xec,0x14,0x40,0xff,0xd6,0x25,0x6b,0x00,0xec,0xa7,0x80,0x87,0xf4,
+0x00,0x00,0x40,0x21,0x27,0x83,0xba,0x90,0xac,0x68,0x00,0x00,0x25,0x08,0x00,0x01,
+0x29,0x02,0x00,0x0c,0x14,0x40,0xff,0xfc,0x24,0x63,0x00,0x04,0x0c,0x00,0x25,0x04,
+0x00,0x00,0x00,0x00,0x27,0x83,0xba,0xe0,0x24,0x08,0x00,0x07,0x90,0x62,0x00,0xd6,
+0x25,0x08,0xff,0xff,0xa0,0x62,0x00,0x00,0x05,0x01,0xff,0xfc,0x24,0x63,0x00,0xec,
+0x8f,0xbf,0x00,0x10,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,
+0x30,0x84,0x00,0xff,0x00,0x04,0x11,0x00,0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,
+0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,0x27,0x83,0xba,0xe0,0x00,0x43,0x40,0x21,
+0x3c,0x04,0xb0,0x03,0x3c,0x02,0x80,0x01,0x34,0x84,0x00,0x20,0x24,0x42,0x97,0x10,
+0x30,0xc6,0x00,0xff,0xac,0x82,0x00,0x00,0x30,0xa5,0x00,0xff,0x30,0xe7,0x00,0xff,
+0x10,0xc0,0x00,0x41,0x25,0x0f,0x00,0xd0,0x91,0x03,0x00,0x00,0x00,0x00,0x00,0x00,
+0x24,0x62,0xff,0xee,0x2c,0x42,0x00,0x02,0x14,0x40,0x00,0x31,0x30,0x63,0x00,0xff,
+0x24,0x02,0x00,0x1a,0x10,0x62,0x00,0x2e,0x24,0x02,0x00,0x1b,0x10,0x62,0x00,0x2c,
+0x24,0x02,0x00,0x11,0x10,0x62,0x00,0x1e,0x24,0x02,0x00,0x18,0x10,0x62,0x00,0x1c,
+0x24,0x02,0x00,0x19,0x10,0x62,0x00,0x1a,0x00,0x00,0x00,0x00,0x14,0xa0,0x00,0x06,
+0x24,0x02,0x00,0x01,0x8d,0x02,0x00,0xd0,0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x02,
+0x03,0xe0,0x00,0x08,0xad,0x02,0x00,0xd0,0x10,0xa2,0x00,0x0e,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0xa2,0x00,0x09,0x24,0x02,0x00,0x03,0x10,0xa2,0x00,0x04,
+0x00,0x00,0x00,0x00,0x8d,0x02,0x00,0xd0,0x08,0x00,0x25,0xec,0x24,0x42,0xff,0xe0,
+0x8d,0x02,0x00,0xd0,0x08,0x00,0x25,0xec,0x24,0x42,0xff,0xf8,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x8d,0x02,0x00,0xd0,0x08,0x00,0x25,0xec,0x24,0x42,0x00,0x01,
+0x10,0xa0,0xff,0xe8,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xfa,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0xf5,0x24,0x02,0x00,0x03,0x14,0xa2,0xff,0xed,
+0x00,0x00,0x00,0x00,0x8d,0x02,0x00,0xd0,0x08,0x00,0x25,0xec,0x24,0x42,0xff,0xe8,
+0x10,0xa0,0xff,0xf0,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xeb,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0xe6,0x00,0x00,0x00,0x00,0x8d,0x02,0x00,0xd0,
+0x08,0x00,0x25,0xec,0x24,0x42,0xff,0xd0,0x91,0x06,0x00,0x00,0x91,0x03,0x00,0xd4,
+0x25,0x0d,0x00,0x5c,0x30,0xc4,0x00,0xff,0x00,0x04,0x10,0x40,0x00,0x44,0x10,0x21,
+0x00,0x04,0x50,0x80,0x01,0x02,0x58,0x21,0x01,0x0a,0x48,0x21,0x00,0xc0,0x60,0x21,
+0x25,0x78,0x00,0x08,0x10,0x60,0x00,0x36,0x25,0x2e,0x00,0x60,0x10,0xa0,0x00,0x25,
+0x00,0x00,0x00,0x00,0x91,0x02,0x00,0xdd,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x1e,
+0x00,0x00,0x00,0x00,0x27,0x86,0x87,0xf8,0x01,0x46,0x10,0x21,0x8c,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0xad,0x23,0x00,0x60,0x91,0x62,0x00,0x08,0x00,0x00,0x00,0x00,
+0x00,0x40,0x60,0x21,0xa1,0x02,0x00,0x00,0x31,0x82,0x00,0xff,0x00,0x02,0x10,0x80,
+0x00,0x46,0x10,0x21,0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x18,0x42,
+0xad,0xa3,0x00,0x00,0x91,0x04,0x00,0x00,0x8d,0xc5,0x00,0x00,0x00,0x04,0x20,0x80,
+0x00,0x86,0x10,0x21,0x8c,0x43,0x00,0x00,0x00,0x05,0x28,0x40,0x00,0x88,0x20,0x21,
+0x00,0x03,0x32,0x80,0x00,0xa6,0x10,0x2b,0x00,0xc2,0x28,0x0a,0xac,0x85,0x00,0x60,
+0x03,0xe0,0x00,0x08,0xa1,0x00,0x00,0xd4,0x27,0x86,0x87,0xf8,0x08,0x00,0x26,0x32,
+0xa1,0x00,0x00,0xdd,0x27,0x82,0x88,0x68,0x8d,0x03,0x00,0xd8,0x00,0x82,0x10,0x21,
+0x90,0x44,0x00,0x00,0x24,0x63,0x00,0x01,0x00,0x64,0x20,0x2b,0x14,0x80,0xff,0xab,
+0xad,0x03,0x00,0xd8,0x8d,0x22,0x00,0x60,0xa1,0x00,0x00,0xd4,0x00,0x02,0x1f,0xc2,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x43,0x03,0xe0,0x00,0x08,0xad,0x02,0x00,0x5c,
+0x10,0xe0,0x00,0x14,0x24,0xc2,0xff,0xee,0x2c,0x42,0x00,0x02,0x14,0x40,0x00,0xa4,
+0x24,0x02,0x00,0x1a,0x10,0x82,0x00,0xa2,0x24,0x02,0x00,0x1b,0x10,0x82,0x00,0xa0,
+0x24,0x02,0x00,0x11,0x10,0x82,0x00,0x92,0x24,0x02,0x00,0x18,0x10,0x82,0x00,0x90,
+0x24,0x02,0x00,0x19,0x10,0x82,0x00,0x8e,0x00,0x00,0x00,0x00,0x14,0xa0,0x00,0x7c,
+0x24,0x02,0x00,0x01,0x8d,0x02,0x00,0xd0,0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x02,
+0xad,0x02,0x00,0xd0,0x8d,0xe3,0x00,0x00,0x8d,0xa2,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x43,0x10,0x21,0xad,0xa2,0x00,0x00,0xad,0xe0,0x00,0x00,0x8d,0xa3,0x00,0x00,
+0x8d,0xc4,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x83,0x10,0x2a,0x10,0x40,0x00,0x4d,
+0x24,0x02,0x00,0x1b,0x93,0x05,0x00,0x01,0x00,0x00,0x00,0x00,0x10,0x45,0x00,0x21,
+0x00,0x00,0x00,0x00,0x91,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x45,0x00,0x05,
+0x24,0x02,0x00,0x01,0xa1,0x05,0x00,0x00,0xa1,0x02,0x00,0xd4,0x03,0xe0,0x00,0x08,
+0xad,0x00,0x00,0xd8,0x91,0x02,0x00,0xdd,0x24,0x03,0x00,0x01,0x10,0x43,0x00,0x05,
+0x00,0x00,0x00,0x00,0xa1,0x03,0x00,0xd4,0xad,0x00,0x00,0xd8,0x03,0xe0,0x00,0x08,
+0xa1,0x03,0x00,0xdd,0x00,0x04,0x17,0xc2,0x00,0x82,0x10,0x21,0x00,0x02,0x10,0x43,
+0xad,0xa2,0x00,0x00,0x91,0x03,0x00,0x00,0x27,0x82,0x87,0xf8,0x8d,0xc5,0x00,0x00,
+0x00,0x03,0x18,0x80,0x00,0x62,0x18,0x21,0x8c,0x64,0x00,0x00,0x00,0x05,0x28,0x40,
+0x00,0x04,0x32,0x80,0x00,0xa6,0x10,0x2b,0x00,0xc2,0x28,0x0a,0x08,0x00,0x26,0x44,
+0xad,0xc5,0x00,0x00,0x91,0x02,0x00,0xde,0x00,0x00,0x00,0x00,0x2c,0x42,0x00,0x02,
+0x14,0x40,0xff,0xdc,0x00,0x04,0x17,0xc2,0x00,0x82,0x10,0x21,0x00,0x02,0x10,0x43,
+0xad,0xa2,0x00,0x00,0x91,0x03,0x00,0x00,0x27,0x82,0x87,0xf8,0x8d,0xc5,0x00,0x00,
+0x00,0x03,0x18,0x80,0x00,0x62,0x18,0x21,0x8c,0x64,0x00,0x00,0x00,0x05,0x28,0x40,
+0x3c,0x03,0xb0,0x03,0x00,0x04,0x32,0x80,0x00,0xa6,0x10,0x2b,0x00,0xc2,0x28,0x0a,
+0xad,0xc5,0x00,0x00,0x34,0x63,0x01,0x08,0x8c,0x64,0x00,0x00,0x8d,0x03,0x00,0xe4,
+0x00,0x00,0x00,0x00,0x00,0x64,0x10,0x2b,0x14,0x40,0x00,0x03,0x00,0x83,0x28,0x23,
+0x00,0x83,0x10,0x23,0x24,0x45,0xff,0xff,0x3c,0x02,0x00,0x98,0x34,0x42,0x96,0x80,
+0x00,0x45,0x10,0x2b,0x10,0x40,0x00,0x04,0x00,0x00,0x00,0x00,0xa5,0x00,0x00,0xe0,
+0x03,0xe0,0x00,0x08,0xa1,0x00,0x00,0xde,0x24,0x02,0x00,0x03,0x03,0xe0,0x00,0x08,
+0xa1,0x02,0x00,0xde,0x97,0x82,0x91,0x5c,0x00,0x00,0x00,0x00,0x00,0x62,0x10,0x2a,
+0x10,0x40,0xff,0x32,0x00,0x00,0x00,0x00,0x91,0x02,0x00,0xdd,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x15,0x00,0x00,0x00,0x00,0x91,0x03,0x00,0x00,0x27,0x82,0x87,0xf8,
+0x00,0x03,0x18,0x80,0x00,0x62,0x10,0x21,0x8c,0x44,0x00,0x00,0x00,0x68,0x18,0x21,
+0xac,0x64,0x00,0x60,0x93,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x10,0x80,
+0x01,0x02,0x10,0x21,0x24,0x4e,0x00,0x60,0xa1,0x05,0x00,0x00,0x8d,0xc2,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x02,0x1f,0xc2,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x43,
+0x03,0xe0,0x00,0x08,0xad,0xa2,0x00,0x00,0x08,0x00,0x26,0xdb,0xa1,0x00,0x00,0xdd,
+0x10,0xa2,0x00,0x0c,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0x85,
+0x24,0x02,0x00,0x03,0x10,0xa2,0x00,0x04,0x00,0x00,0x00,0x00,0x8d,0x02,0x00,0xd0,
+0x08,0x00,0x26,0x6c,0x24,0x42,0xff,0xe0,0x8d,0x02,0x00,0xd0,0x08,0x00,0x26,0x6c,
+0x24,0x42,0xff,0xf8,0x8d,0x02,0x00,0xd0,0x08,0x00,0x26,0x6c,0x24,0x42,0x00,0x01,
+0x10,0xa0,0xff,0x74,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xfa,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0x73,0x24,0x02,0x00,0x03,0x14,0xa2,0xff,0xef,
+0x00,0x00,0x00,0x00,0x8d,0x02,0x00,0xd0,0x08,0x00,0x26,0x6c,0x24,0x42,0xff,0xe8,
+0x10,0xa0,0xff,0xf0,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x69,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0xe8,0x00,0x00,0x00,0x00,0x8d,0x02,0x00,0xd0,
+0x08,0x00,0x26,0x6c,0x24,0x42,0xff,0xd0,0x27,0xbd,0xff,0xe8,0x3c,0x02,0xb0,0x03,
+0xaf,0xbf,0x00,0x14,0xaf,0xb0,0x00,0x10,0x34,0x42,0x01,0x18,0x8c,0x50,0x00,0x00,
+0x00,0x00,0x00,0x00,0x32,0x03,0x00,0x01,0x14,0x60,0x00,0x14,0x00,0x00,0x00,0x00,
+0x32,0x02,0x01,0x00,0x14,0x40,0x00,0x09,0x00,0x00,0x00,0x00,0x32,0x02,0x08,0x00,
+0x10,0x40,0x00,0x02,0x24,0x02,0x00,0x01,0xa3,0x82,0x92,0x14,0x8f,0xbf,0x00,0x14,
+0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x0c,0x00,0x0a,0x65,
+0x00,0x00,0x00,0x00,0x26,0x02,0xff,0x00,0xa3,0x80,0x92,0x14,0x3c,0x01,0xb0,0x03,
+0xac,0x22,0x01,0x18,0x08,0x00,0x27,0x18,0x32,0x02,0x08,0x00,0x0c,0x00,0x25,0x71,
+0x00,0x00,0x00,0x00,0x26,0x02,0xff,0xff,0x3c,0x01,0xb0,0x03,0xac,0x22,0x01,0x18,
+0x08,0x00,0x27,0x15,0x32,0x02,0x01,0x00,0x27,0xbd,0xff,0xe0,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x00,0xd0,0xaf,0xbf,0x00,0x18,0x8c,0x43,0x00,0x00,0x3c,0x02,0x00,0x40,
+0x24,0x07,0x0f,0xff,0x00,0x03,0x33,0x02,0x00,0x03,0x2d,0x02,0x00,0x03,0x43,0x02,
+0x30,0x69,0x0f,0xff,0x00,0x62,0x18,0x24,0x30,0xa5,0x00,0x03,0x30,0xc6,0x00,0xff,
+0x10,0x60,0x00,0x08,0x31,0x08,0x00,0xff,0x01,0x00,0x30,0x21,0x0c,0x00,0x27,0x4b,
+0xaf,0xa9,0x00,0x10,0x8f,0xbf,0x00,0x18,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x20,0x0c,0x00,0x27,0xae,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,
+0x34,0x63,0x00,0xd4,0x08,0x00,0x27,0x41,0xac,0x62,0x00,0x00,0x27,0xbd,0xff,0xd8,
+0xaf,0xb0,0x00,0x10,0x30,0xd0,0x00,0xff,0x2e,0x02,0x00,0x2e,0xaf,0xb4,0x00,0x20,
+0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xbf,0x00,0x24,0xaf,0xb3,0x00,0x1c,
+0x30,0xb1,0x00,0xff,0x8f,0xb4,0x00,0x38,0x14,0x40,0x00,0x07,0x00,0x80,0x90,0x21,
+0x8f,0xbf,0x00,0x24,0x8f,0xb4,0x00,0x20,0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,0x2e,0x13,0x00,0x10,0x24,0x05,0x00,0x14,
+0x0c,0x00,0x18,0xa0,0x24,0x06,0x01,0x07,0x12,0x60,0x00,0x46,0x02,0x40,0x20,0x21,
+0x02,0x00,0x90,0x21,0x00,0x14,0x1c,0x00,0x32,0x42,0x00,0x3f,0x24,0x04,0x00,0x50,
+0x0c,0x00,0x01,0x31,0x00,0x62,0x80,0x25,0x24,0x03,0x00,0x01,0x12,0x23,0x00,0x3a,
+0x2a,0x22,0x00,0x02,0x14,0x40,0x00,0x34,0x24,0x02,0x00,0x02,0x12,0x22,0x00,0x2f,
+0x24,0x02,0x00,0x03,0x12,0x22,0x00,0x28,0x02,0x00,0x30,0x21,0x16,0x60,0xff,0xe4,
+0x00,0x00,0x00,0x00,0x16,0x40,0x00,0x1f,0x02,0x80,0x80,0x21,0x0c,0x00,0x01,0x31,
+0x24,0x04,0x00,0x50,0x24,0x03,0x00,0x01,0x12,0x23,0x00,0x16,0x2a,0x22,0x00,0x02,
+0x14,0x40,0x00,0x0f,0x24,0x02,0x00,0x02,0x12,0x22,0x00,0x09,0x24,0x02,0x00,0x03,
+0x16,0x22,0xff,0xd7,0x32,0x06,0x0e,0xbf,0x00,0x06,0x34,0x00,0x24,0x04,0x08,0x4c,
+0x0c,0x00,0x18,0x5b,0x24,0x05,0xff,0xff,0x08,0x00,0x27,0x58,0x00,0x00,0x00,0x00,
+0x32,0x06,0x0e,0xbf,0x00,0x06,0x34,0x00,0x08,0x00,0x27,0x84,0x24,0x04,0x08,0x48,
+0x16,0x20,0xff,0xcb,0x32,0x06,0x0e,0xbf,0x00,0x06,0x34,0x00,0x08,0x00,0x27,0x84,
+0x24,0x04,0x08,0x40,0x32,0x06,0x0e,0xbf,0x00,0x06,0x34,0x00,0x08,0x00,0x27,0x84,
+0x24,0x04,0x08,0x44,0x02,0x20,0x20,0x21,0x0c,0x00,0x28,0x46,0x00,0x00,0x28,0x21,
+0x08,0x00,0x27,0x77,0x00,0x40,0x80,0x21,0x24,0x04,0x08,0x4c,0x0c,0x00,0x18,0x5b,
+0x24,0x05,0xff,0xff,0x08,0x00,0x27,0x73,0x00,0x00,0x00,0x00,0x02,0x00,0x30,0x21,
+0x08,0x00,0x27,0x9b,0x24,0x04,0x08,0x48,0x16,0x20,0xff,0xd0,0x02,0x00,0x30,0x21,
+0x08,0x00,0x27,0x9b,0x24,0x04,0x08,0x40,0x02,0x00,0x30,0x21,0x08,0x00,0x27,0x9b,
+0x24,0x04,0x08,0x44,0x02,0x00,0x30,0x21,0x0c,0x00,0x27,0xf5,0x02,0x20,0x28,0x21,
+0x08,0x00,0x27,0x65,0x00,0x40,0x90,0x21,0x27,0xbd,0xff,0xd8,0x2c,0xc2,0x00,0x2e,
+0xaf,0xb3,0x00,0x1c,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x20,
+0xaf,0xb2,0x00,0x18,0x00,0xc0,0x80,0x21,0x30,0xb1,0x00,0xff,0x00,0x80,0x98,0x21,
+0x14,0x40,0x00,0x07,0x00,0x00,0x18,0x21,0x8f,0xbf,0x00,0x20,0x7b,0xb2,0x00,0xfc,
+0x7b,0xb0,0x00,0xbc,0x00,0x60,0x10,0x21,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,
+0x2e,0x12,0x00,0x10,0x24,0x05,0x00,0x14,0x0c,0x00,0x18,0xa0,0x24,0x06,0x01,0x07,
+0x12,0x40,0x00,0x2a,0x02,0x00,0x10,0x21,0x30,0x45,0x00,0x3f,0x0c,0x00,0x28,0x46,
+0x02,0x20,0x20,0x21,0x12,0x40,0x00,0x03,0x00,0x40,0x98,0x21,0x08,0x00,0x27,0xba,
+0x02,0x60,0x18,0x21,0x02,0x20,0x20,0x21,0x0c,0x00,0x28,0x46,0x00,0x00,0x28,0x21,
+0x24,0x04,0x00,0x50,0x0c,0x00,0x01,0x31,0x00,0x40,0x80,0x21,0x24,0x03,0x00,0x01,
+0x12,0x23,0x00,0x16,0x2a,0x22,0x00,0x02,0x14,0x40,0x00,0x0f,0x24,0x02,0x00,0x02,
+0x12,0x22,0x00,0x09,0x24,0x02,0x00,0x03,0x16,0x22,0xff,0xf0,0x32,0x06,0x0e,0xbf,
+0x00,0x06,0x34,0x00,0x24,0x04,0x08,0x4c,0x0c,0x00,0x18,0x5b,0x24,0x05,0xff,0xff,
+0x08,0x00,0x27,0xba,0x02,0x60,0x18,0x21,0x32,0x06,0x0e,0xbf,0x00,0x06,0x34,0x00,
+0x08,0x00,0x27,0xde,0x24,0x04,0x08,0x48,0x16,0x20,0xff,0xe4,0x32,0x06,0x0e,0xbf,
+0x00,0x06,0x34,0x00,0x08,0x00,0x27,0xde,0x24,0x04,0x08,0x40,0x32,0x06,0x0e,0xbf,
+0x00,0x06,0x34,0x00,0x08,0x00,0x27,0xde,0x24,0x04,0x08,0x44,0x02,0x60,0x20,0x21,
+0x02,0x00,0x30,0x21,0x0c,0x00,0x27,0xf5,0x02,0x20,0x28,0x21,0x08,0x00,0x27,0xc7,
+0x30,0x45,0x00,0x3f,0x27,0xbd,0xff,0xe0,0xaf,0xb0,0x00,0x10,0x30,0xb0,0x00,0xff,
+0x02,0x00,0x20,0x21,0x00,0x00,0x28,0x21,0xaf,0xb1,0x00,0x14,0xaf,0xbf,0x00,0x1c,
+0x00,0xc0,0x88,0x21,0x0c,0x00,0x28,0x46,0xaf,0xb2,0x00,0x18,0x00,0x40,0x18,0x21,
+0x2e,0x22,0x00,0x1f,0x10,0x40,0x00,0x26,0x2e,0x22,0x00,0x10,0x10,0x40,0x00,0x07,
+0x34,0x62,0x01,0x00,0x02,0x20,0x10,0x21,0x8f,0xbf,0x00,0x1c,0x8f,0xb2,0x00,0x18,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x24,0x04,0x00,0x50,
+0x0c,0x00,0x01,0x31,0x00,0x02,0x94,0x00,0x24,0x03,0x00,0x01,0x12,0x03,0x00,0x15,
+0x2a,0x02,0x00,0x02,0x14,0x40,0x00,0x0f,0x24,0x02,0x00,0x02,0x12,0x02,0x00,0x0a,
+0x24,0x02,0x00,0x03,0x12,0x02,0x00,0x03,0x02,0x40,0x30,0x21,0x08,0x00,0x28,0x05,
+0x26,0x31,0xff,0xf1,0x24,0x04,0x08,0x4c,0x0c,0x00,0x18,0x5b,0x24,0x05,0xff,0xff,
+0x08,0x00,0x28,0x05,0x26,0x31,0xff,0xf1,0x02,0x40,0x30,0x21,0x08,0x00,0x28,0x1a,
+0x24,0x04,0x08,0x48,0x16,0x00,0xff,0xf5,0x02,0x40,0x30,0x21,0x08,0x00,0x28,0x1a,
+0x24,0x04,0x08,0x40,0x02,0x40,0x30,0x21,0x08,0x00,0x28,0x1a,0x24,0x04,0x08,0x44,
+0x34,0x62,0x01,0x40,0x24,0x04,0x00,0x50,0x0c,0x00,0x01,0x31,0x00,0x02,0x94,0x00,
+0x24,0x03,0x00,0x01,0x12,0x03,0x00,0x15,0x2a,0x02,0x00,0x02,0x14,0x40,0x00,0x0f,
+0x24,0x02,0x00,0x02,0x12,0x02,0x00,0x0a,0x24,0x02,0x00,0x03,0x12,0x02,0x00,0x03,
+0x02,0x40,0x30,0x21,0x08,0x00,0x28,0x05,0x26,0x31,0xff,0xe2,0x24,0x04,0x08,0x4c,
+0x0c,0x00,0x18,0x5b,0x24,0x05,0xff,0xff,0x08,0x00,0x28,0x05,0x26,0x31,0xff,0xe2,
+0x02,0x40,0x30,0x21,0x08,0x00,0x28,0x38,0x24,0x04,0x08,0x48,0x16,0x00,0xff,0xf5,
+0x02,0x40,0x30,0x21,0x08,0x00,0x28,0x38,0x24,0x04,0x08,0x40,0x02,0x40,0x30,0x21,
+0x08,0x00,0x28,0x38,0x24,0x04,0x08,0x44,0x27,0xbd,0xff,0xe0,0x00,0x80,0x10,0x21,
+0x24,0x04,0x00,0x50,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x18,
+0x00,0xa0,0x88,0x21,0x0c,0x00,0x01,0x31,0x30,0x50,0x00,0xff,0x24,0x03,0x00,0x01,
+0x12,0x03,0x00,0x3e,0x02,0x20,0x30,0x21,0x2a,0x02,0x00,0x02,0x14,0x40,0x00,0x2a,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,0x12,0x02,0x00,0x19,0x24,0x04,0x08,0x34,
+0x24,0x02,0x00,0x03,0x12,0x02,0x00,0x05,0x24,0x04,0x08,0x3c,0x8f,0xbf,0x00,0x18,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x0c,0x00,0x18,0x5b,
+0x3c,0x05,0x3f,0x00,0x24,0x04,0x08,0x3c,0x3c,0x05,0x80,0x00,0x0c,0x00,0x18,0x5b,
+0x00,0x00,0x30,0x21,0x3c,0x05,0x80,0x00,0x24,0x06,0x00,0x01,0x0c,0x00,0x18,0x5b,
+0x24,0x04,0x08,0x3c,0x0c,0x00,0x01,0x31,0x24,0x04,0x00,0x28,0x24,0x04,0x08,0xac,
+0x0c,0x00,0x18,0x3d,0x24,0x05,0x0f,0xff,0x08,0x00,0x28,0x5b,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x18,0x5b,0x3c,0x05,0x3f,0x00,0x24,0x04,0x08,0x34,0x3c,0x05,0x80,0x00,
+0x0c,0x00,0x18,0x5b,0x00,0x00,0x30,0x21,0x3c,0x05,0x80,0x00,0x24,0x06,0x00,0x01,
+0x0c,0x00,0x18,0x5b,0x24,0x04,0x08,0x34,0x0c,0x00,0x01,0x31,0x24,0x04,0x00,0x28,
+0x08,0x00,0x28,0x6c,0x24,0x04,0x08,0xa8,0x16,0x00,0xff,0xdc,0x02,0x20,0x30,0x21,
+0x24,0x04,0x08,0x24,0x0c,0x00,0x18,0x5b,0x3c,0x05,0x3f,0x00,0x24,0x04,0x08,0x24,
+0x3c,0x05,0x80,0x00,0x0c,0x00,0x18,0x5b,0x00,0x00,0x30,0x21,0x3c,0x05,0x80,0x00,
+0x24,0x06,0x00,0x01,0x0c,0x00,0x18,0x5b,0x24,0x04,0x08,0x24,0x0c,0x00,0x01,0x31,
+0x24,0x04,0x00,0x28,0x08,0x00,0x28,0x6c,0x24,0x04,0x08,0xa0,0x24,0x04,0x08,0x2c,
+0x0c,0x00,0x18,0x5b,0x3c,0x05,0x3f,0x00,0x24,0x04,0x08,0x2c,0x3c,0x05,0x80,0x00,
+0x0c,0x00,0x18,0x5b,0x00,0x00,0x30,0x21,0x3c,0x05,0x80,0x00,0x24,0x06,0x00,0x01,
+0x0c,0x00,0x18,0x5b,0x24,0x04,0x08,0x2c,0x0c,0x00,0x01,0x31,0x24,0x04,0x00,0x28,
+0x08,0x00,0x28,0x6c,0x24,0x04,0x08,0xa4,0x27,0xbd,0xff,0xe8,0xaf,0xbf,0x00,0x10,
+0x0c,0x00,0x29,0x4c,0x00,0x00,0x00,0x00,0x0c,0x00,0x29,0x4e,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x29,0x75,0x00,0x00,0x00,0x00,0x3c,0x04,0xb0,0x05,0x34,0x84,0x00,0x04,
+0x0c,0x00,0x29,0x55,0x34,0x05,0x9c,0x40,0x8f,0xbf,0x00,0x10,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x24,0x02,0x00,0x01,
+0x03,0xe0,0x00,0x08,0x24,0x02,0x00,0x01,0x97,0x82,0x88,0x90,0x00,0x00,0x00,0x00,
+0x2c,0x43,0x00,0x64,0x24,0x42,0x00,0x01,0xa7,0x82,0x88,0x90,0x14,0x60,0x00,0x28,
+0x00,0x80,0x30,0x21,0x8c,0x82,0x00,0x00,0x3c,0x03,0x20,0x00,0xa7,0x80,0x88,0x90,
+0x00,0x43,0x10,0x24,0x10,0x40,0x00,0x22,0x00,0x00,0x00,0x00,0x8c,0x82,0x00,0x00,
+0x3c,0x03,0x80,0x00,0x00,0x43,0x10,0x25,0x97,0x83,0x88,0x84,0xac,0x82,0x00,0x00,
+0x8c,0x85,0x00,0x00,0x24,0x63,0x00,0x01,0x3c,0x02,0x40,0x64,0x34,0x42,0x64,0x00,
+0x00,0x03,0x24,0x00,0x00,0xa2,0x28,0x25,0x00,0x04,0x24,0x03,0x24,0x02,0x00,0x64,
+0xac,0xc5,0x00,0x00,0xa7,0x83,0x88,0x84,0x10,0x82,0x00,0x2b,0x00,0x00,0x00,0x00,
+0x87,0x82,0x88,0x86,0x24,0x03,0x00,0x3c,0x10,0x43,0x00,0x21,0x00,0x00,0x00,0x00,
+0x87,0x82,0x88,0x88,0x00,0x00,0x00,0x00,0x10,0x43,0x00,0x17,0x00,0x00,0x00,0x00,
+0x87,0x83,0x88,0x8a,0x24,0x02,0x00,0x18,0x10,0x62,0x00,0x0d,0x00,0x00,0x00,0x00,
+0x87,0x83,0x88,0x8c,0x24,0x02,0x01,0x6d,0x10,0x62,0x00,0x03,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x97,0x82,0x88,0x8e,0xa7,0x80,0x88,0x8c,
+0x24,0x42,0x00,0x01,0xa7,0x82,0x88,0x8e,0x08,0x00,0x28,0xe4,0x00,0x00,0x00,0x00,
+0x97,0x82,0x88,0x8c,0xa7,0x80,0x88,0x8a,0x24,0x42,0x00,0x01,0xa7,0x82,0x88,0x8c,
+0x08,0x00,0x28,0xe0,0x00,0x00,0x00,0x00,0x97,0x82,0x88,0x8a,0xa7,0x80,0x88,0x88,
+0x24,0x42,0x00,0x01,0xa7,0x82,0x88,0x8a,0x08,0x00,0x28,0xdc,0x00,0x00,0x00,0x00,
+0x97,0x82,0x88,0x88,0xa7,0x80,0x88,0x86,0x24,0x42,0x00,0x01,0xa7,0x82,0x88,0x88,
+0x08,0x00,0x28,0xd8,0x00,0x00,0x00,0x00,0x97,0x82,0x88,0x86,0xa7,0x80,0x88,0x84,
+0x24,0x42,0x00,0x01,0xa7,0x82,0x88,0x86,0x08,0x00,0x28,0xd4,0x00,0x00,0x00,0x00,
+0x00,0x04,0x24,0x00,0x3c,0x03,0xb0,0x07,0x00,0x04,0x24,0x03,0x34,0x63,0x00,0x28,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x40,0x10,0x40,0xff,0xfc,
+0x00,0x00,0x00,0x00,0x3c,0x01,0xb0,0x07,0xa0,0x24,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x10,0x21,0x3c,0x02,0xb0,0x07,0x34,0x42,0x00,0x28,0x90,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x01,0x10,0x60,0x00,0x06,0x24,0x02,0xff,0xff,
+0x3c,0x02,0xb0,0x07,0x90,0x42,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x16,0x00,
+0x00,0x02,0x16,0x03,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x27,0xbd,0xff,0xe0,
+0xaf,0xb0,0x00,0x10,0x3c,0x10,0x04,0xc4,0x00,0x04,0x11,0x00,0x36,0x10,0xb4,0x00,
+0x02,0x02,0x00,0x1b,0xaf,0xb1,0x00,0x14,0x3c,0x11,0xb0,0x07,0x36,0x31,0x00,0x18,
+0x24,0x04,0x00,0x0a,0xaf,0xbf,0x00,0x18,0x14,0x40,0x00,0x02,0x00,0x00,0x00,0x00,
+0x00,0x07,0x00,0x0d,0x00,0x00,0x80,0x12,0x0c,0x00,0x29,0xa1,0x00,0x00,0x00,0x00,
+0x92,0x22,0x00,0x00,0x24,0x03,0xff,0x80,0x24,0x04,0x00,0x0a,0x00,0x43,0x10,0x25,
+0x0c,0x00,0x29,0xa1,0xa2,0x22,0x00,0x00,0x24,0x04,0x00,0x0a,0x3c,0x01,0xb0,0x07,
+0xa0,0x30,0x00,0x00,0x0c,0x00,0x29,0xa1,0x00,0x10,0x82,0x03,0x3c,0x02,0xb0,0x07,
+0x34,0x42,0x00,0x08,0xa0,0x50,0x00,0x00,0x0c,0x00,0x29,0xa1,0x24,0x04,0x00,0x0a,
+0x92,0x22,0x00,0x00,0x8f,0xbf,0x00,0x18,0x8f,0xb0,0x00,0x10,0x30,0x42,0x00,0x7f,
+0xa2,0x22,0x00,0x00,0x8f,0xb1,0x00,0x14,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x34,0x63,0x00,0x58,
+0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x34,0x42,0x07,0xa4,0x03,0xe0,0x00,0x08,
+0xac,0x62,0x00,0x00,0x27,0xbd,0xff,0xf8,0x00,0x80,0x38,0x21,0x00,0xa0,0x30,0x21,
+0x00,0x00,0x18,0x21,0x00,0x63,0x00,0x18,0x00,0x00,0x10,0x12,0x00,0xc2,0x10,0x2b,
+0x14,0x40,0x00,0x05,0x00,0x00,0x00,0x00,0x24,0x63,0x00,0x01,0x2c,0x62,0x01,0x00,
+0x14,0x40,0xff,0xf9,0x00,0x63,0x00,0x18,0x24,0x63,0xff,0xff,0x00,0x63,0x00,0x18,
+0x30,0x63,0x00,0xff,0x8c,0xe4,0x00,0x00,0x00,0x03,0x2a,0x00,0x00,0x03,0x1c,0x00,
+0x00,0x00,0x10,0x12,0x00,0xc2,0x10,0x23,0x30,0x42,0x00,0xff,0x00,0x45,0x10,0x21,
+0x00,0x43,0x10,0x21,0x00,0x82,0x20,0x25,0xac,0xe4,0x00,0x00,0x8c,0xe2,0x00,0x00,
+0x3c,0x03,0x40,0x00,0x00,0x43,0x10,0x25,0xac,0xe2,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x08,0x27,0xbd,0xff,0xe0,0xaf,0xbf,0x00,0x18,0xaf,0xb1,0x00,0x14,
+0xaf,0xb0,0x00,0x10,0x3c,0x04,0xb0,0x03,0x8c,0x82,0x00,0x00,0x3c,0x06,0xb0,0x03,
+0x34,0xc6,0x00,0x08,0x34,0x42,0x40,0x00,0xac,0x82,0x00,0x00,0x8c,0x83,0x00,0x00,
+0x24,0x02,0xcf,0xff,0x3c,0x11,0xb0,0x07,0x00,0x62,0x18,0x24,0xac,0x83,0x00,0x00,
+0x8c,0xc5,0x00,0x00,0x3c,0x02,0x00,0xff,0x24,0x04,0x00,0x0a,0x00,0xa2,0x28,0x25,
+0xac,0xc5,0x00,0x00,0x0c,0x00,0x29,0xa1,0x36,0x31,0x00,0x18,0x24,0x02,0xff,0x83,
+0x3c,0x04,0x00,0x01,0xa2,0x22,0x00,0x00,0x0c,0x00,0x29,0x1f,0x34,0x84,0xc2,0x00,
+0x0c,0x00,0x29,0xa1,0x24,0x04,0x00,0x0a,0x24,0x02,0x00,0x03,0xa2,0x22,0x00,0x00,
+0x24,0x04,0x00,0x0a,0x0c,0x00,0x29,0xa1,0x3c,0x10,0xb0,0x07,0x36,0x10,0x00,0x10,
+0x24,0x02,0x00,0x06,0xa2,0x02,0x00,0x00,0x0c,0x00,0x29,0xa1,0x24,0x04,0x00,0x0a,
+0xa2,0x00,0x00,0x00,0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x20,0x10,0x80,0x00,0x05,0x00,0x00,0x18,0x21,0x24,0x63,0x00,0x01,
+0x00,0x64,0x10,0x2b,0x14,0x40,0xff,0xfd,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x27,0xbd,0xff,0xc0,0xaf,0xb5,0x00,0x34,0xaf,0xb2,0x00,0x28,
+0xaf,0xb0,0x00,0x20,0xaf,0xbf,0x00,0x38,0xaf,0xb4,0x00,0x30,0xaf,0xb3,0x00,0x2c,
+0xaf,0xb1,0x00,0x24,0xaf,0xa5,0x00,0x44,0x90,0xa7,0x00,0x00,0x00,0x80,0xa8,0x21,
+0x00,0xc0,0x90,0x21,0x00,0x07,0x1e,0x00,0x10,0x60,0x00,0x0f,0x00,0x80,0x80,0x21,
+0x00,0x03,0x1e,0x03,0x24,0x02,0x00,0x25,0x10,0x62,0x00,0x13,0x00,0x00,0x88,0x21,
+0xa2,0x07,0x00,0x00,0x8f,0xa5,0x00,0x44,0x26,0x10,0x00,0x01,0x24,0xa5,0x00,0x01,
+0xaf,0xa5,0x00,0x44,0x90,0xa7,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x1e,0x00,
+0x14,0x60,0xff,0xf3,0x00,0x00,0x00,0x00,0x02,0x15,0x10,0x23,0xa2,0x00,0x00,0x00,
+0x8f,0xbf,0x00,0x38,0x7b,0xb4,0x01,0xbc,0x7b,0xb2,0x01,0x7c,0x7b,0xb0,0x01,0x3c,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x40,0x24,0xa5,0x00,0x01,0xaf,0xa5,0x00,0x44,
+0x80,0xa3,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0x63,0xff,0xe0,0x2c,0x62,0x00,0x11,
+0x10,0x40,0x00,0x11,0x00,0xa0,0x38,0x21,0x00,0x03,0x10,0x80,0x3c,0x03,0x80,0x01,
+0x24,0x63,0x09,0x98,0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x80,0x00,0x08,0x00,0x00,0x00,0x00,0x08,0x00,0x29,0xce,0x36,0x31,0x00,0x10,
+0x08,0x00,0x29,0xce,0x36,0x31,0x00,0x08,0x08,0x00,0x29,0xce,0x36,0x31,0x00,0x20,
+0x08,0x00,0x29,0xce,0x36,0x31,0x00,0x04,0x90,0xe4,0x00,0x00,0x3c,0x02,0x80,0x01,
+0x24,0x42,0x02,0x14,0x00,0x44,0x10,0x21,0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x63,0x00,0x04,0x14,0x60,0x00,0xfd,0x24,0x14,0xff,0xff,0x00,0x04,0x16,0x00,
+0x00,0x02,0x16,0x03,0x24,0x03,0x00,0x2a,0x10,0x43,0x00,0xee,0x26,0x42,0x00,0x03,
+0x80,0xa3,0x00,0x00,0x24,0x02,0x00,0x2e,0x10,0x62,0x00,0xcc,0x24,0x08,0xff,0xff,
+0x80,0xa3,0x00,0x00,0x24,0x02,0x00,0x68,0x10,0x62,0x00,0xc4,0x24,0x06,0xff,0xff,
+0x24,0x02,0x00,0x6c,0x10,0x62,0x00,0xc1,0x24,0x02,0x00,0x4c,0x10,0x62,0x00,0xbf,
+0x24,0x02,0x00,0x5a,0x10,0x62,0x00,0xbd,0x00,0x00,0x00,0x00,0x80,0xa3,0x00,0x00,
+0x00,0x00,0x00,0x00,0x24,0x63,0xff,0xdb,0x2c,0x62,0x00,0x54,0x10,0x40,0x00,0xaa,
+0x24,0x09,0x00,0x0a,0x00,0x03,0x10,0x80,0x3c,0x03,0x80,0x01,0x24,0x63,0x09,0xdc,
+0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x08,
+0x00,0x00,0x00,0x00,0x32,0x22,0x00,0x10,0x14,0x40,0x00,0x09,0x24,0x02,0xff,0xfc,
+0x26,0x94,0xff,0xff,0x1a,0x80,0x00,0x05,0x24,0x02,0x00,0x20,0x26,0x94,0xff,0xff,
+0xa2,0x02,0x00,0x00,0x1e,0x80,0xff,0xfd,0x26,0x10,0x00,0x01,0x24,0x02,0xff,0xfc,
+0x26,0x44,0x00,0x03,0x00,0x82,0x90,0x24,0x92,0x42,0x00,0x03,0x26,0x94,0xff,0xff,
+0x26,0x52,0x00,0x04,0xa2,0x02,0x00,0x00,0x1a,0x80,0x00,0x06,0x26,0x10,0x00,0x01,
+0x24,0x02,0x00,0x20,0x26,0x94,0xff,0xff,0xa2,0x02,0x00,0x00,0x1e,0x80,0xff,0xfd,
+0x26,0x10,0x00,0x01,0x8f,0xa5,0x00,0x44,0x08,0x00,0x29,0xc0,0x24,0xa5,0x00,0x01,
+0x24,0x02,0x00,0x25,0x08,0x00,0x29,0xbd,0xa2,0x02,0x00,0x00,0x36,0x31,0x00,0x40,
+0x24,0x09,0x00,0x10,0x24,0x02,0x00,0x4c,0x10,0xc2,0x00,0x2a,0x24,0x02,0x00,0x6c,
+0x10,0xc2,0x00,0x05,0x24,0x02,0x00,0x5a,0x10,0xc2,0x00,0x1f,0x24,0x02,0x00,0x68,
+0x10,0xc2,0x00,0x13,0x24,0x02,0xff,0xfc,0x24,0x02,0xff,0xfc,0x26,0x43,0x00,0x03,
+0x00,0x62,0x90,0x24,0x32,0x22,0x00,0x02,0x8e,0x47,0x00,0x00,0x00,0x00,0x30,0x21,
+0x10,0x40,0x00,0x03,0x26,0x52,0x00,0x04,0x00,0xe0,0x10,0x21,0x00,0x02,0x37,0xc3,
+0x02,0x00,0x20,0x21,0xaf,0xa9,0x00,0x10,0xaf,0xb4,0x00,0x14,0xaf,0xa8,0x00,0x18,
+0x0c,0x00,0x2b,0x0e,0xaf,0xb1,0x00,0x1c,0x08,0x00,0x2a,0x29,0x00,0x40,0x80,0x21,
+0x26,0x43,0x00,0x03,0x00,0x62,0x90,0x24,0x32,0x22,0x00,0x02,0x96,0x47,0x00,0x02,
+0x00,0x00,0x30,0x21,0x10,0x40,0xff,0xf2,0x26,0x52,0x00,0x04,0x00,0x07,0x14,0x00,
+0x08,0x00,0x2a,0x43,0x00,0x02,0x3c,0x03,0x26,0x42,0x00,0x03,0x24,0x03,0xff,0xfc,
+0x00,0x43,0x90,0x24,0x8e,0x47,0x00,0x00,0x00,0x00,0x30,0x21,0x08,0x00,0x2a,0x44,
+0x26,0x52,0x00,0x04,0x26,0x42,0x00,0x07,0x24,0x03,0xff,0xf8,0x00,0x43,0x90,0x24,
+0x8e,0x46,0x00,0x00,0x8e,0x47,0x00,0x04,0x08,0x00,0x2a,0x44,0x26,0x52,0x00,0x08,
+0x08,0x00,0x2a,0x31,0x36,0x31,0x00,0x02,0x26,0x44,0x00,0x03,0x24,0x02,0xff,0xfc,
+0x00,0x82,0x90,0x24,0x8e,0x44,0x00,0x00,0x02,0x15,0x10,0x23,0x26,0x52,0x00,0x04,
+0x08,0x00,0x29,0xbf,0xac,0x82,0x00,0x00,0x08,0x00,0x2a,0x31,0x24,0x09,0x00,0x08,
+0x24,0x02,0xff,0xff,0x12,0x82,0x00,0x11,0x00,0x00,0x00,0x00,0x26,0x43,0x00,0x03,
+0x24,0x02,0xff,0xfc,0x00,0x62,0x90,0x24,0x8e,0x47,0x00,0x00,0x02,0x00,0x20,0x21,
+0x24,0x02,0x00,0x10,0x00,0x00,0x30,0x21,0xaf,0xa2,0x00,0x10,0xaf,0xb4,0x00,0x14,
+0xaf,0xa8,0x00,0x18,0x0c,0x00,0x2b,0x0e,0xaf,0xb1,0x00,0x1c,0x8f,0xa5,0x00,0x44,
+0x00,0x40,0x80,0x21,0x08,0x00,0x29,0xbf,0x26,0x52,0x00,0x04,0x24,0x14,0x00,0x08,
+0x08,0x00,0x2a,0x73,0x36,0x31,0x00,0x01,0x26,0x42,0x00,0x03,0x24,0x03,0xff,0xfc,
+0x00,0x43,0x90,0x24,0x8e,0x53,0x00,0x00,0x00,0x00,0x00,0x00,0x12,0x60,0x00,0x23,
+0x26,0x52,0x00,0x04,0x02,0x60,0x20,0x21,0x0c,0x00,0x2b,0xdc,0x01,0x00,0x28,0x21,
+0x00,0x40,0x20,0x21,0x32,0x22,0x00,0x10,0x14,0x40,0x00,0x09,0x00,0x94,0x10,0x2a,
+0x10,0x40,0x00,0x07,0x26,0x94,0xff,0xff,0x24,0x03,0x00,0x20,0x00,0x94,0x10,0x2a,
+0xa2,0x03,0x00,0x00,0x26,0x94,0xff,0xff,0x14,0x40,0xff,0xfc,0x26,0x10,0x00,0x01,
+0x18,0x80,0x00,0x07,0x00,0x80,0x18,0x21,0x92,0x62,0x00,0x00,0x24,0x63,0xff,0xff,
+0x26,0x73,0x00,0x01,0xa2,0x02,0x00,0x00,0x14,0x60,0xff,0xfb,0x26,0x10,0x00,0x01,
+0x00,0x94,0x10,0x2a,0x10,0x40,0xff,0x83,0x26,0x94,0xff,0xff,0x24,0x03,0x00,0x20,
+0x00,0x94,0x10,0x2a,0xa2,0x03,0x00,0x00,0x26,0x94,0xff,0xff,0x14,0x40,0xff,0xfc,
+0x26,0x10,0x00,0x01,0x08,0x00,0x2a,0x29,0x00,0x00,0x00,0x00,0x3c,0x02,0x80,0x01,
+0x08,0x00,0x2a,0x8d,0x24,0x53,0x08,0x84,0x24,0x02,0x00,0x25,0xa2,0x02,0x00,0x00,
+0x8f,0xa5,0x00,0x44,0x00,0x00,0x00,0x00,0x80,0xa2,0x00,0x00,0x90,0xa3,0x00,0x00,
+0x10,0x40,0x00,0x03,0x26,0x10,0x00,0x01,0x08,0x00,0x29,0xbd,0xa2,0x03,0x00,0x00,
+0x24,0xa5,0xff,0xff,0x08,0x00,0x29,0xbf,0xaf,0xa5,0x00,0x44,0x80,0xa6,0x00,0x00,
+0x24,0xa5,0x00,0x01,0x08,0x00,0x2a,0x03,0xaf,0xa5,0x00,0x44,0x24,0xa5,0x00,0x01,
+0xaf,0xa5,0x00,0x44,0x90,0xa4,0x00,0x00,0x3c,0x02,0x80,0x01,0x24,0x42,0x02,0x14,
+0x00,0x44,0x10,0x21,0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x04,
+0x14,0x60,0x00,0x0f,0x00,0x04,0x16,0x00,0x00,0x02,0x16,0x03,0x24,0x03,0x00,0x2a,
+0x10,0x43,0x00,0x04,0x26,0x42,0x00,0x03,0x29,0x02,0x00,0x00,0x08,0x00,0x29,0xf8,
+0x00,0x02,0x40,0x0b,0x24,0x03,0xff,0xfc,0x00,0x43,0x90,0x24,0x24,0xa5,0x00,0x01,
+0x8e,0x48,0x00,0x00,0xaf,0xa5,0x00,0x44,0x08,0x00,0x2a,0xd2,0x26,0x52,0x00,0x04,
+0x0c,0x00,0x2a,0xf2,0x27,0xa4,0x00,0x44,0x8f,0xa5,0x00,0x44,0x08,0x00,0x2a,0xd2,
+0x00,0x40,0x40,0x21,0x24,0x03,0xff,0xfc,0x00,0x43,0x90,0x24,0x8e,0x54,0x00,0x00,
+0x24,0xe5,0x00,0x01,0xaf,0xa5,0x00,0x44,0x06,0x81,0xff,0x0d,0x26,0x52,0x00,0x04,
+0x00,0x14,0xa0,0x23,0x08,0x00,0x29,0xf4,0x36,0x31,0x00,0x10,0x0c,0x00,0x2a,0xf2,
+0x27,0xa4,0x00,0x44,0x8f,0xa5,0x00,0x44,0x08,0x00,0x29,0xf4,0x00,0x40,0xa0,0x21,
+0x08,0x00,0x29,0xce,0x36,0x31,0x00,0x01,0x8c,0x86,0x00,0x00,0x3c,0x02,0x80,0x01,
+0x00,0x80,0x48,0x21,0x90,0xc3,0x00,0x00,0x24,0x44,0x02,0x14,0x00,0x64,0x18,0x21,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x04,0x10,0x40,0x00,0x10,
+0x00,0x00,0x38,0x21,0x00,0x80,0x40,0x21,0x24,0xc2,0x00,0x01,0x80,0xc5,0x00,0x00,
+0xad,0x22,0x00,0x00,0x90,0x43,0x00,0x00,0x00,0x40,0x30,0x21,0x00,0x07,0x10,0x80,
+0x00,0x68,0x18,0x21,0x90,0x64,0x00,0x00,0x00,0x47,0x10,0x21,0x00,0x02,0x10,0x40,
+0x00,0x45,0x10,0x21,0x30,0x84,0x00,0x04,0x14,0x80,0xff,0xf3,0x24,0x47,0xff,0xd0,
+0x03,0xe0,0x00,0x08,0x00,0xe0,0x10,0x21,0x27,0xbd,0xff,0x98,0xaf,0xb2,0x00,0x50,
+0x8f,0xb2,0x00,0x84,0x3c,0x02,0x80,0x01,0xaf,0xb4,0x00,0x58,0x32,0x43,0x00,0x40,
+0xaf,0xb1,0x00,0x4c,0xaf,0xb0,0x00,0x48,0xaf,0xb7,0x00,0x64,0xaf,0xb6,0x00,0x60,
+0xaf,0xb5,0x00,0x5c,0xaf,0xb3,0x00,0x54,0x00,0x80,0x68,0x21,0x00,0xc0,0x70,0x21,
+0x00,0xe0,0x78,0x21,0x8f,0xb0,0x00,0x78,0x8f,0xb8,0x00,0x7c,0x8f,0xb1,0x00,0x80,
+0x10,0x60,0x00,0x03,0x24,0x54,0x08,0x8c,0x3c,0x02,0x80,0x01,0x24,0x54,0x08,0xb4,
+0x32,0x42,0x00,0x10,0x10,0x40,0x00,0x04,0x26,0x02,0xff,0xfe,0x24,0x02,0xff,0xfe,
+0x02,0x42,0x90,0x24,0x26,0x02,0xff,0xfe,0x2c,0x42,0x00,0x23,0x10,0x40,0x00,0x5d,
+0x00,0x00,0x18,0x21,0x32,0x42,0x00,0x01,0x24,0x15,0x00,0x30,0x24,0x03,0x00,0x20,
+0x32,0x44,0x00,0x02,0x00,0x62,0xa8,0x0a,0x10,0x80,0x00,0x07,0x00,0x00,0xb8,0x21,
+0x05,0xc0,0x00,0x96,0x32,0x42,0x00,0x04,0x10,0x40,0x00,0x90,0x32,0x42,0x00,0x08,
+0x24,0x17,0x00,0x2b,0x27,0x18,0xff,0xff,0x32,0x56,0x00,0x20,0x12,0xc0,0x00,0x07,
+0x01,0xcf,0x10,0x25,0x24,0x02,0x00,0x10,0x12,0x02,0x00,0x86,0x27,0x03,0xff,0xff,
+0x3a,0x02,0x00,0x08,0x00,0x62,0xc0,0x0a,0x01,0xcf,0x10,0x25,0x14,0x40,0x00,0x55,
+0x00,0x00,0xc8,0x21,0x24,0x02,0x00,0x30,0x24,0x19,0x00,0x01,0xa3,0xa2,0x00,0x00,
+0x02,0x39,0x10,0x2a,0x03,0x22,0x88,0x0b,0x32,0x43,0x00,0x11,0x14,0x60,0x00,0x0a,
+0x03,0x11,0xc0,0x23,0x03,0x00,0x10,0x21,0x18,0x40,0x00,0x07,0x27,0x18,0xff,0xff,
+0x24,0x03,0x00,0x20,0x03,0x00,0x10,0x21,0xa1,0xa3,0x00,0x00,0x27,0x18,0xff,0xff,
+0x1c,0x40,0xff,0xfc,0x25,0xad,0x00,0x01,0x12,0xe0,0x00,0x03,0x00,0x00,0x00,0x00,
+0xa1,0xb7,0x00,0x00,0x25,0xad,0x00,0x01,0x12,0xc0,0x00,0x07,0x32,0x42,0x00,0x10,
+0x24,0x02,0x00,0x08,0x12,0x02,0x00,0x38,0x24,0x02,0x00,0x10,0x12,0x02,0x00,0x30,
+0x24,0x02,0x00,0x30,0x32,0x42,0x00,0x10,0x14,0x40,0x00,0x0a,0x03,0x31,0x10,0x2a,
+0x03,0x00,0x10,0x21,0x18,0x40,0x00,0x06,0x27,0x18,0xff,0xff,0x03,0x00,0x10,0x21,
+0xa1,0xb5,0x00,0x00,0x27,0x18,0xff,0xff,0x1c,0x40,0xff,0xfc,0x25,0xad,0x00,0x01,
+0x03,0x31,0x10,0x2a,0x10,0x40,0x00,0x07,0x26,0x31,0xff,0xff,0x24,0x03,0x00,0x30,
+0x03,0x31,0x10,0x2a,0xa1,0xa3,0x00,0x00,0x26,0x31,0xff,0xff,0x14,0x40,0xff,0xfc,
+0x25,0xad,0x00,0x01,0x03,0x20,0x10,0x21,0x18,0x40,0x00,0x08,0x27,0x39,0xff,0xff,
+0x03,0xb9,0x10,0x21,0x90,0x43,0x00,0x00,0x03,0x20,0x20,0x21,0x27,0x39,0xff,0xff,
+0xa1,0xa3,0x00,0x00,0x1c,0x80,0xff,0xfa,0x25,0xad,0x00,0x01,0x03,0x00,0x10,0x21,
+0x18,0x40,0x00,0x07,0x27,0x18,0xff,0xff,0x24,0x03,0x00,0x20,0x03,0x00,0x10,0x21,
+0xa1,0xa3,0x00,0x00,0x27,0x18,0xff,0xff,0x1c,0x40,0xff,0xfc,0x25,0xad,0x00,0x01,
+0x01,0xa0,0x18,0x21,0x7b,0xb6,0x03,0x3c,0x7b,0xb4,0x02,0xfc,0x7b,0xb2,0x02,0xbc,
+0x7b,0xb0,0x02,0x7c,0x00,0x60,0x10,0x21,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x68,
+0xa1,0xa2,0x00,0x00,0x92,0x83,0x00,0x21,0x25,0xad,0x00,0x01,0xa1,0xa3,0x00,0x00,
+0x08,0x00,0x2b,0x61,0x25,0xad,0x00,0x01,0x24,0x02,0x00,0x30,0x08,0x00,0x2b,0x94,
+0xa1,0xa2,0x00,0x00,0x01,0xcf,0x10,0x25,0x10,0x40,0xff,0xad,0x00,0x00,0x60,0x21,
+0x00,0x0e,0x18,0x02,0x03,0x3d,0x98,0x21,0x00,0x60,0x20,0x21,0x01,0xe0,0x38,0x21,
+0x10,0x60,0x00,0x04,0x27,0x39,0x00,0x01,0x00,0x70,0x00,0x1b,0x00,0x00,0x20,0x12,
+0x00,0x00,0x18,0x10,0x00,0x80,0x48,0x21,0x00,0xe0,0x30,0x21,0x01,0x80,0x70,0x21,
+0x01,0x80,0x28,0x21,0x10,0x00,0x00,0x06,0x24,0x04,0x00,0x21,0x00,0x03,0x08,0x40,
+0x00,0x03,0x2f,0xc2,0x00,0x22,0x18,0x25,0x00,0x06,0x30,0x40,0x00,0x0e,0x70,0x40,
+0x14,0xa0,0x00,0x02,0x00,0x70,0x10,0x2b,0x14,0x40,0x00,0x03,0x24,0x84,0xff,0xff,
+0x00,0x70,0x18,0x23,0x25,0xce,0x00,0x01,0x14,0x80,0xff,0xf4,0x00,0x06,0x17,0xc2,
+0x02,0x83,0x18,0x21,0x01,0xc0,0x38,0x21,0x00,0x00,0x50,0x21,0x00,0x09,0x20,0x00,
+0x00,0x00,0x28,0x21,0x90,0x66,0x00,0x00,0x00,0x8a,0x70,0x25,0x00,0xa7,0x78,0x25,
+0x01,0xcf,0x10,0x25,0x14,0x40,0xff,0xda,0xa2,0x66,0x00,0x00,0x08,0x00,0x2b,0x49,
+0x02,0x39,0x10,0x2a,0x08,0x00,0x2b,0x42,0x27,0x18,0xff,0xfe,0x10,0x40,0xff,0x73,
+0x32,0x56,0x00,0x20,0x08,0x00,0x2b,0x39,0x24,0x17,0x00,0x20,0x00,0x0f,0x78,0x23,
+0x00,0x0e,0x70,0x23,0x00,0x0f,0x10,0x2b,0x01,0xc2,0x70,0x23,0x08,0x00,0x2b,0x39,
+0x24,0x17,0x00,0x2d,0x80,0x82,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x06,
+0x00,0x80,0x18,0x21,0x24,0x63,0x00,0x01,0x80,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x14,0x40,0xff,0xfc,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x64,0x10,0x23,
+0x24,0xa5,0xff,0xff,0x24,0x02,0xff,0xff,0x10,0xa2,0x00,0x0d,0x00,0x80,0x18,0x21,
+0x80,0x82,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x09,0x00,0x00,0x00,0x00,
+0x24,0x06,0xff,0xff,0x24,0xa5,0xff,0xff,0x10,0xa6,0x00,0x05,0x24,0x63,0x00,0x01,
+0x80,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0xfa,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x00,0x64,0x10,0x23,0x80,0x82,0x00,0x00,0x90,0x88,0x00,0x00,
+0x10,0x40,0x00,0x17,0x00,0x00,0x48,0x21,0x90,0xa3,0x00,0x00,0x00,0xa0,0x30,0x21,
+0x10,0x60,0x00,0x0b,0x00,0x60,0x38,0x21,0x00,0x08,0x16,0x00,0x00,0x02,0x46,0x03,
+0x00,0x07,0x16,0x00,0x00,0x02,0x16,0x03,0x11,0x02,0x00,0x05,0x24,0xc6,0x00,0x01,
+0x90,0xc3,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x60,0xff,0xf9,0x00,0x60,0x38,0x21,
+0x00,0x03,0x16,0x00,0x10,0x40,0x00,0x06,0x00,0x00,0x00,0x00,0x24,0x84,0x00,0x01,
+0x90,0x82,0x00,0x00,0x25,0x29,0x00,0x01,0x14,0x40,0xff,0xeb,0x00,0x40,0x40,0x21,
+0x03,0xe0,0x00,0x08,0x01,0x20,0x10,0x21,0x80,0x82,0x00,0x00,0x90,0x87,0x00,0x00,
+0x10,0x40,0x00,0x17,0x00,0x00,0x18,0x21,0x90,0xa2,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x02,0x1e,0x00,0x10,0x60,0x00,0x0c,0x00,0xa0,0x30,0x21,0x00,0x07,0x16,0x00,
+0x00,0x02,0x3e,0x03,0x00,0x03,0x16,0x03,0x10,0xe2,0x00,0x0d,0x00,0x80,0x18,0x21,
+0x24,0xc6,0x00,0x01,0x90,0xc2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x1e,0x00,
+0x14,0x60,0xff,0xf9,0x00,0x03,0x16,0x03,0x24,0x84,0x00,0x01,0x90,0x82,0x00,0x00,
+0x00,0x00,0x00,0x00,0x14,0x40,0xff,0xec,0x00,0x40,0x38,0x21,0x00,0x00,0x18,0x21,
+0x03,0xe0,0x00,0x08,0x00,0x60,0x10,0x21,0x27,0xbd,0xff,0xe0,0xaf,0xb0,0x00,0x10,
+0x8f,0x90,0xc2,0x58,0xaf,0xb1,0x00,0x14,0xaf,0xbf,0x00,0x18,0x00,0x84,0x80,0x0b,
+0x00,0x00,0x30,0x21,0x12,0x00,0x00,0x0a,0x00,0xa0,0x88,0x21,0x0c,0x00,0x2b,0xee,
+0x02,0x00,0x20,0x21,0x02,0x02,0x80,0x21,0x82,0x02,0x00,0x00,0x02,0x20,0x28,0x21,
+0x02,0x00,0x20,0x21,0x14,0x40,0x00,0x07,0x00,0x00,0x30,0x21,0xaf,0x80,0xc2,0x58,
+0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x00,0xc0,0x10,0x21,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x20,0x0c,0x00,0x2c,0x0a,0x00,0x00,0x00,0x00,0x00,0x40,0x18,0x21,
+0x10,0x40,0x00,0x07,0x02,0x00,0x30,0x21,0x80,0x42,0x00,0x00,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x03,0x00,0x00,0x00,0x00,0xa0,0x60,0x00,0x00,0x24,0x63,0x00,0x01,
+0xaf,0x83,0xc2,0x58,0x08,0x00,0x2c,0x38,0x00,0x00,0x00,0x00,0x24,0xc6,0xff,0xff,
+0x24,0x02,0xff,0xff,0x10,0xc2,0x00,0x05,0x00,0x80,0x18,0x21,0x24,0xc6,0xff,0xff,
+0xa0,0x65,0x00,0x00,0x14,0xc2,0xff,0xfd,0x24,0x63,0x00,0x01,0x03,0xe0,0x00,0x08,
+0x00,0x80,0x10,0x21,0x24,0xc6,0xff,0xff,0x24,0x02,0xff,0xff,0x10,0xc2,0x00,0x08,
+0x00,0x80,0x18,0x21,0x24,0x07,0xff,0xff,0x90,0xa2,0x00,0x00,0x24,0xc6,0xff,0xff,
+0x24,0xa5,0x00,0x01,0xa0,0x62,0x00,0x00,0x14,0xc7,0xff,0xfb,0x24,0x63,0x00,0x01,
+0x03,0xe0,0x00,0x08,0x00,0x80,0x10,0x21,0x00,0x80,0x18,0x21,0x90,0xa2,0x00,0x00,
+0x24,0xa5,0x00,0x01,0xa0,0x82,0x00,0x00,0x14,0x40,0xff,0xfc,0x24,0x84,0x00,0x01,
+0x03,0xe0,0x00,0x08,0x00,0x60,0x10,0x21,0x90,0x83,0x00,0x00,0x90,0xa2,0x00,0x00,
+0x24,0x84,0x00,0x01,0x00,0x62,0x10,0x23,0x00,0x02,0x16,0x00,0x00,0x02,0x16,0x03,
+0x14,0x40,0x00,0x03,0x24,0xa5,0x00,0x01,0x14,0x60,0xff,0xf7,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x10,0x21,
+0x3c,0x05,0xb0,0x03,0x3c,0x02,0x80,0x01,0x34,0xa5,0x00,0x20,0x24,0x42,0xb1,0xe0,
+0xac,0xa2,0x00,0x00,0x24,0x02,0x00,0x02,0x24,0x03,0x00,0x20,0xac,0x82,0x00,0x64,
+0x3c,0x02,0x80,0x01,0xac,0x83,0x00,0x60,0xac,0x80,0x00,0x00,0xac,0x80,0x00,0x04,
+0xac,0x80,0x00,0x08,0xac,0x80,0x00,0x4c,0xac,0x80,0x00,0x50,0xac,0x80,0x00,0x54,
+0xac,0x80,0x00,0x0c,0xac,0x80,0x00,0x58,0xa0,0x80,0x00,0x5c,0x24,0x42,0xb2,0xb0,
+0x24,0x83,0x00,0x68,0x24,0x05,0x00,0x0f,0x24,0xa5,0xff,0xff,0xac,0x62,0x00,0x00,
+0x04,0xa1,0xff,0xfd,0x24,0x63,0x00,0x04,0x3c,0x02,0x80,0x01,0x3c,0x03,0x80,0x01,
+0x24,0x42,0xb3,0xe0,0x24,0x63,0xb4,0x44,0xac,0x82,0x00,0x78,0xac,0x83,0x00,0x84,
+0x3c,0x02,0x80,0x01,0x3c,0x03,0x80,0x01,0x24,0x42,0xb5,0x6c,0x24,0x63,0xb4,0xd8,
+0xac,0x82,0x00,0x88,0xac,0x83,0x00,0x98,0x3c,0x02,0x80,0x01,0x3c,0x03,0x80,0x01,
+0x24,0x42,0xb6,0x14,0x24,0x63,0xb6,0xd4,0xac,0x82,0x00,0xa0,0xac,0x83,0x00,0xa4,
+0xa0,0x80,0x01,0xba,0xac,0x80,0x01,0xa8,0xac,0x80,0x01,0xac,0xac,0x80,0x01,0xb0,
+0xac,0x80,0x01,0xb4,0xa0,0x80,0x01,0xb8,0x03,0xe0,0x00,0x08,0xa0,0x80,0x01,0xb9,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x01,0x34,0x63,0x00,0x20,0x24,0x42,0xb2,0xb0,
+0x03,0xe0,0x00,0x08,0xac,0x62,0x00,0x00,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x01,
+0x27,0xbd,0xff,0xe8,0x34,0x63,0x00,0x20,0x24,0x42,0xb2,0xc8,0xaf,0xb0,0x00,0x10,
+0xac,0x62,0x00,0x00,0xaf,0xbf,0x00,0x14,0x8c,0x83,0x00,0x10,0x8f,0x82,0x91,0xe8,
+0x00,0x80,0x80,0x21,0x3c,0x04,0x80,0x01,0x30,0x46,0x00,0x01,0x10,0x60,0x00,0x11,
+0x24,0x84,0x08,0xdc,0x8e,0x02,0x00,0x14,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x0d,
+0x00,0x00,0x00,0x00,0x8e,0x05,0x00,0x10,0x8e,0x03,0x00,0x14,0x8e,0x02,0x00,0x04,
+0x00,0xa3,0x28,0x21,0x00,0x45,0x10,0x21,0x30,0x43,0x00,0xff,0x00,0x03,0x18,0x2b,
+0x00,0x02,0x12,0x02,0x00,0x43,0x10,0x21,0x00,0x02,0x12,0x00,0x30,0x42,0x3f,0xff,
+0xae,0x02,0x00,0x04,0x14,0xc0,0x00,0x0a,0x00,0x00,0x00,0x00,0xae,0x00,0x00,0x00,
+0xae,0x00,0x00,0x4c,0xae,0x00,0x00,0x50,0xae,0x00,0x00,0x54,0xae,0x00,0x00,0x0c,
+0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,
+0x8e,0x05,0x00,0x10,0x8e,0x07,0x00,0x04,0x8e,0x06,0x00,0x14,0x0c,0x00,0x17,0x9d,
+0x00,0x00,0x00,0x00,0x08,0x00,0x2c,0xd4,0xae,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x01,0x34,0x63,0x00,0x20,0x24,0x42,0xb3,0x8c,0xac,0x62,0x00,0x00,
+0x8c,0x86,0x00,0x04,0x3c,0x02,0xb0,0x01,0x24,0x03,0x00,0x01,0x00,0xc2,0x10,0x21,
+0x8c,0x45,0x00,0x00,0xac,0x83,0x00,0x4c,0x00,0x05,0x14,0x02,0x30,0xa3,0x3f,0xff,
+0x30,0x42,0x00,0xff,0xac,0x83,0x00,0x10,0xac,0x82,0x00,0x14,0x8c,0x83,0x00,0x14,
+0xac,0x85,0x00,0x40,0x00,0xc3,0x30,0x21,0x03,0xe0,0x00,0x08,0xac,0x86,0x00,0x08,
+0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,0x27,0xbd,0xff,0xe8,0x34,0x42,0x00,0x20,
+0x24,0x63,0xb3,0xe0,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,0xac,0x43,0x00,0x00,
+0x8c,0x82,0x00,0x4c,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x0a,0x00,0x80,0x80,0x21,
+0xae,0x00,0x00,0x00,0xae,0x00,0x00,0x4c,0xae,0x00,0x00,0x50,0xae,0x00,0x00,0x54,
+0xae,0x00,0x00,0x0c,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x0c,0x00,0x2c,0xe3,0x00,0x00,0x00,0x00,0x08,0x00,0x2d,0x05,
+0xae,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,0x27,0xbd,0xff,0xe8,
+0x34,0x42,0x00,0x20,0x24,0x63,0xb4,0x44,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,
+0xac,0x43,0x00,0x00,0x8c,0x82,0x00,0x4c,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x16,
+0x00,0x80,0x80,0x21,0x8e,0x03,0x00,0x08,0x3c,0x02,0xb0,0x01,0x8e,0x04,0x00,0x44,
+0x00,0x62,0x18,0x21,0x90,0x65,0x00,0x00,0x24,0x02,0x00,0x01,0xae,0x02,0x00,0x50,
+0x30,0xa3,0x00,0xff,0x00,0x03,0x10,0x82,0x00,0x04,0x23,0x02,0x30,0x84,0x00,0x0f,
+0x30,0x42,0x00,0x03,0x00,0x03,0x19,0x02,0xae,0x04,0x00,0x34,0xae,0x02,0x00,0x2c,
+0xae,0x03,0x00,0x30,0xa2,0x05,0x00,0x48,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x0c,0x00,0x2c,0xe3,0x00,0x00,0x00,0x00,
+0x08,0x00,0x2d,0x1d,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,
+0x27,0xbd,0xff,0xe8,0x34,0x42,0x00,0x20,0x24,0x63,0xb4,0xd8,0xaf,0xb0,0x00,0x10,
+0xaf,0xbf,0x00,0x14,0xac,0x43,0x00,0x00,0x8c,0x82,0x00,0x50,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x16,0x00,0x80,0x80,0x21,0x92,0x03,0x00,0x44,0x8e,0x02,0x00,0x40,
+0x83,0x85,0x92,0x15,0x92,0x04,0x00,0x41,0x30,0x63,0x00,0x01,0x00,0x02,0x16,0x02,
+0xae,0x04,0x00,0x14,0x00,0x00,0x30,0x21,0xae,0x02,0x00,0x18,0x10,0xa0,0x00,0x04,
+0xae,0x03,0x00,0x3c,0x10,0x60,0x00,0x03,0x24,0x02,0x00,0x01,0x24,0x06,0x00,0x01,
+0x24,0x02,0x00,0x01,0xa3,0x86,0x92,0x15,0x8f,0xbf,0x00,0x14,0xae,0x02,0x00,0x54,
+0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x0c,0x00,0x2d,0x11,
+0x00,0x00,0x00,0x00,0x08,0x00,0x2d,0x42,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,
+0x3c,0x03,0x80,0x01,0x27,0xbd,0xff,0xe8,0x34,0x42,0x00,0x20,0x24,0x63,0xb5,0x6c,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,0xac,0x43,0x00,0x00,0x8c,0x82,0x00,0x50,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x1b,0x00,0x80,0x80,0x21,0x3c,0x02,0xb0,0x03,
+0x8c,0x42,0x00,0x00,0x92,0x04,0x00,0x44,0x8e,0x03,0x00,0x40,0x83,0x86,0x92,0x15,
+0x92,0x05,0x00,0x41,0x30,0x42,0x08,0x00,0x30,0x84,0x00,0x01,0x00,0x02,0x12,0xc2,
+0x00,0x03,0x1e,0x02,0x00,0x82,0x20,0x25,0xae,0x05,0x00,0x14,0x00,0x00,0x38,0x21,
+0xae,0x03,0x00,0x18,0x10,0xc0,0x00,0x04,0xae,0x04,0x00,0x3c,0x10,0x80,0x00,0x03,
+0x24,0x02,0x00,0x01,0x24,0x07,0x00,0x01,0x24,0x02,0x00,0x01,0xa3,0x87,0x92,0x15,
+0x8f,0xbf,0x00,0x14,0xae,0x02,0x00,0x54,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x0c,0x00,0x2d,0x11,0x00,0x00,0x00,0x00,0x08,0x00,0x2d,0x67,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,0x27,0xbd,0xff,0xe8,
+0x34,0x42,0x00,0x20,0x24,0x63,0xb6,0x14,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,
+0xac,0x43,0x00,0x00,0x8c,0x82,0x00,0x54,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x21,
+0x00,0x80,0x80,0x21,0x8e,0x05,0x00,0x04,0x8e,0x04,0x00,0x44,0x3c,0x03,0x80,0x00,
+0x34,0x63,0x00,0x10,0x3c,0x02,0xb0,0x01,0x00,0xa2,0x28,0x21,0x00,0x83,0x20,0x25,
+0xac,0xa4,0x00,0x04,0x8e,0x03,0x01,0xac,0x8e,0x08,0x00,0x04,0x3c,0x07,0xb0,0x03,
+0x24,0x66,0x00,0x01,0x28,0xc5,0x00,0x00,0x24,0x62,0x00,0x40,0x00,0xc5,0x10,0x0a,
+0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,0x00,0x03,0x18,0x80,0x00,0xc2,0x30,0x23,
+0x00,0x70,0x18,0x21,0xae,0x06,0x01,0xac,0x34,0xe7,0x00,0x30,0xac,0x68,0x00,0xa8,
+0x8c,0xe2,0x00,0x00,0x02,0x00,0x20,0x21,0x24,0x42,0x00,0x01,0x0c,0x00,0x2c,0xb2,
+0xac,0xe2,0x00,0x00,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x0c,0x00,0x2d,0x5b,0x00,0x00,0x00,0x00,0x08,0x00,0x2d,0x91,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,0x27,0xbd,0xff,0xe8,
+0x34,0x42,0x00,0x20,0x24,0x63,0xb6,0xd4,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,
+0xac,0x43,0x00,0x00,0x8c,0x82,0x00,0x54,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x21,
+0x00,0x80,0x80,0x21,0x8e,0x05,0x00,0x04,0x8e,0x04,0x00,0x44,0x3c,0x03,0x80,0x00,
+0x34,0x63,0x00,0x10,0x3c,0x02,0xb0,0x01,0x00,0xa2,0x28,0x21,0x00,0x83,0x20,0x25,
+0xac,0xa4,0x00,0x04,0x8e,0x03,0x01,0xac,0x8e,0x08,0x00,0x04,0x3c,0x07,0xb0,0x03,
+0x24,0x66,0x00,0x01,0x28,0xc5,0x00,0x00,0x24,0x62,0x00,0x40,0x00,0xc5,0x10,0x0a,
+0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,0x00,0x03,0x18,0x80,0x00,0xc2,0x30,0x23,
+0x00,0x70,0x18,0x21,0xae,0x06,0x01,0xac,0x34,0xe7,0x00,0x30,0xac,0x68,0x00,0xa8,
+0x8c,0xe2,0x00,0x00,0x02,0x00,0x20,0x21,0x24,0x42,0x00,0x01,0x0c,0x00,0x2c,0xb2,
+0xac,0xe2,0x00,0x00,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x0c,0x00,0x2d,0x5b,0x00,0x00,0x00,0x00,0x08,0x00,0x2d,0xc1,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,0x34,0x42,0x00,0x20,
+0x24,0x63,0xb7,0x94,0x27,0xbd,0xff,0xe0,0xac,0x43,0x00,0x00,0x3c,0x02,0x80,0x01,
+0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x18,0x00,0x80,0x80,0x21,
+0x24,0x51,0xb2,0xb0,0x3c,0x03,0xb0,0x09,0x34,0x63,0x00,0x06,0x8e,0x07,0x00,0x04,
+0x90,0x62,0x00,0x00,0x00,0x07,0x22,0x02,0x00,0x44,0x10,0x23,0x24,0x44,0x00,0x40,
+0x28,0x83,0x00,0x00,0x24,0x42,0x00,0x7f,0x00,0x83,0x10,0x0a,0x00,0x02,0x11,0x83,
+0x00,0x02,0x11,0x80,0x24,0x84,0xff,0xff,0x10,0x44,0x00,0x5f,0x00,0x00,0x40,0x21,
+0x3c,0x02,0xb0,0x01,0x00,0xe2,0x10,0x21,0x8c,0x44,0x00,0x04,0x3c,0x03,0x7c,0x00,
+0x34,0x63,0x00,0xf0,0x00,0x83,0x18,0x24,0xae,0x04,0x00,0x44,0x8c,0x44,0x00,0x00,
+0x10,0x60,0x00,0x60,0x00,0x00,0x48,0x21,0x24,0xe2,0x01,0x00,0x30,0x45,0x3f,0xff,
+0x3c,0x03,0xb0,0x01,0xae,0x05,0x00,0x04,0x00,0xa3,0x18,0x21,0x8c,0x64,0x00,0x04,
+0x3c,0x02,0x7c,0x00,0x34,0x42,0x00,0xf0,0x00,0x82,0x30,0x24,0xae,0x04,0x00,0x44,
+0x25,0x08,0x00,0x01,0x24,0x02,0x00,0x40,0x00,0xa0,0x38,0x21,0x8c,0x64,0x00,0x00,
+0x11,0x02,0x00,0x30,0x24,0x09,0x00,0x01,0x3c,0x02,0xff,0xff,0x14,0xc0,0xff,0xee,
+0x00,0x82,0x18,0x24,0x3c,0x02,0x28,0x38,0x14,0x62,0xff,0xec,0x24,0xe2,0x01,0x00,
+0x24,0x02,0x00,0x01,0x11,0x22,0x00,0x2e,0x3c,0x03,0xb0,0x09,0x8e,0x02,0x00,0x44,
+0x8e,0x04,0x00,0x60,0x00,0x02,0x1e,0x42,0x00,0x02,0x12,0x02,0x30,0x42,0x00,0x0f,
+0x30,0x63,0x00,0x01,0xae,0x02,0x00,0x00,0x10,0x44,0x00,0x1a,0xae,0x03,0x00,0x58,
+0x8e,0x02,0x00,0x64,0x8e,0x04,0x00,0x58,0x00,0x00,0x00,0x00,0x10,0x82,0x00,0x05,
+0x00,0x00,0x00,0x00,0xae,0x00,0x00,0x4c,0xae,0x00,0x00,0x50,0xae,0x00,0x00,0x54,
+0xae,0x00,0x00,0x0c,0x8e,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x10,0x80,
+0x00,0x50,0x10,0x21,0x8c,0x42,0x00,0x68,0x00,0x00,0x00,0x00,0x10,0x51,0x00,0x06,
+0x00,0x00,0x00,0x00,0x00,0x40,0xf8,0x09,0x02,0x00,0x20,0x21,0x8e,0x04,0x00,0x58,
+0x8e,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0xae,0x03,0x00,0x60,0x08,0x00,0x2d,0xf1,
+0xae,0x04,0x00,0x64,0x8e,0x02,0x00,0x64,0x00,0x00,0x00,0x00,0x14,0x62,0xff,0xe5,
+0x00,0x00,0x00,0x00,0x7a,0x02,0x0d,0x7c,0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,
+0x00,0x43,0x10,0x26,0x00,0x02,0x10,0x2b,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,
+0x34,0x63,0x00,0x06,0x8e,0x04,0x00,0x04,0x90,0x62,0x00,0x00,0x00,0x04,0x22,0x02,
+0x00,0x44,0x10,0x23,0x24,0x44,0x00,0x40,0x28,0x83,0x00,0x00,0x24,0x42,0x00,0x7f,
+0x00,0x83,0x10,0x0a,0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,0x00,0x82,0x20,0x23,
+0x14,0x89,0xff,0xc6,0x00,0x00,0x00,0x00,0x8e,0x03,0x00,0x00,0x00,0x00,0x00,0x00,
+0x2c,0x62,0x00,0x03,0x14,0x40,0x00,0x05,0x24,0x02,0x00,0x0d,0x10,0x62,0x00,0x03,
+0x24,0x02,0x00,0x01,0x08,0x00,0x2e,0x49,0xa2,0x02,0x00,0x5c,0x08,0x00,0x2e,0x49,
+0xa2,0x00,0x00,0x5c,0x3c,0x02,0xff,0xff,0x00,0x82,0x10,0x24,0x3c,0x03,0x28,0x38,
+0x14,0x43,0xff,0x9d,0x24,0x02,0x00,0x01,0x08,0x00,0x2e,0x21,0x00,0x00,0x00,0x00,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x01,0x34,0x63,0x00,0x20,0x24,0x42,0xb9,0xc0,
+0xac,0x62,0x00,0x00,0x8c,0x83,0x01,0xa8,0x3c,0x05,0xb0,0x06,0x34,0xa5,0x80,0x18,
+0x00,0x03,0x18,0x80,0x00,0x64,0x18,0x21,0x8c,0x62,0x00,0xa8,0x3c,0x03,0x00,0x80,
+0x00,0x02,0x10,0xc2,0x00,0x02,0x12,0x00,0x00,0x43,0x10,0x25,0xac,0xa2,0x00,0x00,
+0x8c,0x83,0x01,0xa8,0x8c,0x82,0x01,0xac,0x24,0x66,0x00,0x01,0x28,0xc5,0x00,0x00,
+0x24,0x63,0x00,0x40,0x00,0xc5,0x18,0x0a,0x00,0x03,0x19,0x83,0x00,0x03,0x19,0x80,
+0x00,0xc3,0x30,0x23,0x00,0xc2,0x10,0x26,0x00,0x02,0x10,0x2b,0x03,0xe0,0x00,0x08,
+0xac,0x86,0x01,0xa8,0x90,0x87,0x00,0x00,0x3c,0x02,0x80,0x01,0x27,0xbd,0xff,0xe8,
+0x24,0x48,0x02,0x14,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,0x01,0x07,0x18,0x21,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x20,0x10,0x40,0x00,0x0a,
+0x00,0x00,0x80,0x21,0x24,0x84,0x00,0x01,0x90,0x87,0x00,0x00,0x00,0x00,0x00,0x00,
+0x01,0x07,0x18,0x21,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x20,
+0x14,0x40,0xff,0xf8,0x00,0x00,0x00,0x00,0x00,0x07,0x16,0x00,0x00,0x02,0x16,0x03,
+0x24,0x03,0x00,0x2d,0x10,0x43,0x00,0x0f,0x00,0x00,0x00,0x00,0x0c,0x00,0x2e,0xb8,
+0x00,0x00,0x00,0x00,0x00,0x40,0x18,0x21,0x00,0x02,0x10,0x23,0x04,0x61,0x00,0x05,
+0x00,0x70,0x10,0x0a,0x16,0x00,0x00,0x03,0x3c,0x02,0x80,0x00,0x3c,0x02,0x7f,0xff,
+0x34,0x42,0xff,0xff,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x24,0x10,0xff,0xff,0x08,0x00,0x2e,0xa7,0x24,0x84,0x00,0x01,
+0x00,0x80,0x38,0x21,0x90,0x84,0x00,0x00,0x3c,0x02,0x80,0x01,0x24,0x48,0x02,0x14,
+0x01,0x04,0x18,0x21,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x20,
+0x10,0x40,0x00,0x0a,0x00,0x00,0x50,0x21,0x24,0xe7,0x00,0x01,0x90,0xe4,0x00,0x00,
+0x00,0x00,0x00,0x00,0x01,0x04,0x18,0x21,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0x20,0x14,0x40,0xff,0xf8,0x00,0x00,0x00,0x00,0x00,0x04,0x16,0x00,
+0x00,0x02,0x16,0x03,0x38,0x42,0x00,0x2b,0x24,0xe3,0x00,0x01,0x24,0x04,0x00,0x10,
+0x10,0xc4,0x00,0x38,0x00,0x62,0x38,0x0a,0x90,0xe4,0x00,0x00,0x14,0xc0,0x00,0x07,
+0x00,0x80,0x18,0x21,0x00,0x04,0x16,0x00,0x00,0x02,0x16,0x03,0x24,0x03,0x00,0x30,
+0x10,0x43,0x00,0x25,0x24,0x06,0x00,0x0a,0x00,0x80,0x18,0x21,0x00,0x03,0x16,0x00,
+0x10,0x40,0x00,0x1a,0x30,0x64,0x00,0xff,0x24,0x82,0xff,0xa9,0x2c,0x83,0x00,0x61,
+0x30,0x48,0x00,0xff,0x10,0x60,0x00,0x09,0x2c,0x89,0x00,0x41,0x24,0x82,0xff,0xc9,
+0x30,0x48,0x00,0xff,0x11,0x20,0x00,0x05,0x2c,0x83,0x00,0x3a,0x24,0x82,0xff,0xd0,
+0x14,0x60,0x00,0x02,0x30,0x48,0x00,0xff,0x24,0x08,0x00,0xff,0x01,0x06,0x10,0x2a,
+0x10,0x40,0x00,0x0a,0x01,0x46,0x00,0x18,0x24,0xe7,0x00,0x01,0x00,0x00,0x18,0x12,
+0x00,0x6a,0x10,0x2b,0x14,0x40,0x00,0x0a,0x00,0x68,0x50,0x21,0x80,0xe2,0x00,0x00,
+0x90,0xe3,0x00,0x00,0x14,0x40,0xff,0xe8,0x30,0x64,0x00,0xff,0x10,0xa0,0x00,0x02,
+0x00,0x00,0x00,0x00,0xac,0xa7,0x00,0x00,0x03,0xe0,0x00,0x08,0x01,0x40,0x10,0x21,
+0x03,0xe0,0x00,0x08,0x24,0x02,0xff,0xff,0x24,0x06,0x00,0x08,0x80,0xe3,0x00,0x01,
+0x24,0x02,0x00,0x78,0x10,0x62,0x00,0x03,0x24,0x02,0x00,0x58,0x14,0x62,0xff,0xd7,
+0x00,0x80,0x18,0x21,0x24,0xe7,0x00,0x02,0x90,0xe4,0x00,0x00,0x08,0x00,0x2e,0xda,
+0x24,0x06,0x00,0x10,0x80,0xe3,0x00,0x00,0x24,0x02,0x00,0x30,0x90,0xe4,0x00,0x00,
+0x10,0x62,0xff,0xf2,0x00,0x00,0x00,0x00,0x08,0x00,0x2e,0xd3,0x00,0x00,0x00,0x00,
+0x3c,0x04,0xb0,0x03,0x3c,0x06,0xb0,0x07,0x3c,0x02,0x80,0x01,0x34,0xc6,0x00,0x18,
+0x34,0x84,0x00,0x20,0x24,0x42,0xbc,0x40,0x24,0x03,0xff,0x83,0xac,0x82,0x00,0x00,
+0xa0,0xc3,0x00,0x00,0x90,0xc4,0x00,0x00,0x27,0xbd,0xff,0xf8,0x3c,0x03,0xb0,0x07,
+0x24,0x02,0xff,0x82,0xa3,0xa4,0x00,0x00,0xa0,0x62,0x00,0x00,0x90,0x64,0x00,0x00,
+0x3c,0x02,0xb0,0x07,0x34,0x42,0x00,0x08,0xa3,0xa4,0x00,0x01,0xa0,0x40,0x00,0x00,
+0x90,0x43,0x00,0x00,0x24,0x02,0x00,0x03,0x3c,0x05,0xb0,0x07,0xa3,0xa3,0x00,0x00,
+0xa0,0xc2,0x00,0x00,0x90,0xc4,0x00,0x00,0x34,0xa5,0x00,0x10,0x24,0x02,0x00,0x06,
+0x3c,0x03,0xb0,0x07,0xa3,0xa4,0x00,0x00,0x34,0x63,0x00,0x38,0xa0,0xa2,0x00,0x00,
+0x90,0x64,0x00,0x00,0x3c,0x02,0xb0,0x07,0x34,0x42,0x00,0x20,0xa3,0xa4,0x00,0x00,
+0xa0,0xa0,0x00,0x00,0x90,0xa3,0x00,0x00,0xaf,0x82,0xc2,0x5c,0xa3,0xa3,0x00,0x00,
+0xa0,0x40,0x00,0x00,0x90,0x43,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x08,
+};
+
+#define DataArrayLengthDTM 2860
+u8 Rtl8192PciEFwDataArrayDTM[DataArrayLengthDTM] = {
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0a,0x0d,0x5b,0x43,
+0x4d,0x50,0x4b,0x5d,0x00,0x00,0x00,0x00,0x80,0x01,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x28,0x28,0x28,
+0x28,0x28,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,
+0x08,0x08,0x08,0x08,0xa0,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,
+0x10,0x10,0x10,0x10,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x10,0x10,
+0x10,0x10,0x10,0x10,0x10,0x41,0x41,0x41,0x41,0x41,0x41,0x01,0x01,0x01,0x01,0x01,
+0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x10,
+0x10,0x10,0x10,0x10,0x10,0x42,0x42,0x42,0x42,0x42,0x42,0x02,0x02,0x02,0x02,0x02,
+0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x10,
+0x10,0x10,0x10,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0xa0,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,
+0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,
+0x10,0x10,0x10,0x10,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,
+0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x10,0x01,0x01,0x01,0x01,
+0x01,0x01,0x01,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,
+0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x10,0x02,0x02,0x02,0x02,
+0x02,0x02,0x02,0x02,0x20,0x09,0x0d,0x0a,0x00,0x00,0x00,0x00,0x80,0x01,0x03,0x14,
+0x00,0x00,0x00,0x00,0x43,0x6e,0x73,0x64,0x31,0x00,0x00,0x00,0x68,0x65,0x6c,0x70,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x72,0x34,0x00,0x00,0x77,0x34,0x00,0x00,
+0x64,0x62,0x67,0x00,0x72,0x61,0x63,0x74,0x72,0x6c,0x00,0x00,0x73,0x79,0x73,0x64,
+0x00,0x00,0x00,0x00,0x73,0x79,0x73,0x63,0x74,0x72,0x6c,0x00,0x74,0x78,0x74,0x62,
+0x6c,0x00,0x00,0x00,0x70,0x72,0x61,0x6e,0x67,0x65,0x00,0x00,0x64,0x6d,0x00,0x00,
+0x75,0x6e,0x6b,0x6e,0x6f,0x77,0x00,0x00,0x80,0x01,0x03,0x2c,0x80,0x01,0x03,0x34,
+0x80,0x01,0x03,0x34,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x80,0x00,0x20,0x5c,
+0x80,0x01,0x03,0x38,0x80,0x01,0x03,0x34,0x80,0x01,0x03,0x34,0x00,0x00,0x00,0x01,
+0x00,0x00,0x00,0x00,0x80,0x00,0x21,0xbc,0x80,0x01,0x03,0x3c,0x80,0x01,0x03,0x34,
+0x80,0x01,0x03,0x34,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x80,0x00,0x23,0x38,
+0x80,0x01,0x03,0x40,0x80,0x01,0x03,0x34,0x80,0x01,0x03,0x34,0x00,0x00,0x00,0x01,
+0x00,0x00,0x00,0x00,0x80,0x00,0x25,0x04,0x80,0x01,0x03,0x44,0x80,0x01,0x03,0x34,
+0x80,0x01,0x03,0x34,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x80,0x00,0x25,0xdc,
+0x80,0x01,0x03,0x4c,0x80,0x01,0x03,0x34,0x80,0x01,0x03,0x34,0x00,0x00,0x00,0x01,
+0x00,0x00,0x00,0x00,0x80,0x00,0x25,0xe4,0x80,0x01,0x03,0x54,0x80,0x01,0x03,0x34,
+0x80,0x01,0x03,0x34,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x80,0x00,0x26,0x88,
+0x80,0x01,0x03,0x5c,0x80,0x01,0x03,0x34,0x80,0x01,0x03,0x34,0x00,0x00,0x00,0x01,
+0x00,0x00,0x00,0x00,0x80,0x00,0x26,0x90,0x80,0x01,0x03,0x64,0x80,0x01,0x03,0x34,
+0x80,0x01,0x03,0x34,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x80,0x00,0x28,0x1c,
+0x80,0x01,0x03,0x6c,0x80,0x01,0x03,0x34,0x80,0x01,0x03,0x34,0x00,0x00,0x00,0x01,
+0x00,0x00,0x00,0x00,0x80,0x00,0x28,0x90,0x80,0x01,0x03,0x70,0x80,0x01,0x03,0x34,
+0x80,0x01,0x03,0x34,0x00,0x00,0x00,0x0f,0x00,0x00,0x00,0x01,0x80,0x00,0x29,0x1c,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0a,0x0d,0x52,0x54,0x4c,0x38,0x31,0x39,
+0x58,0x2d,0x25,0x64,0x3e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x52,0x54,0x4c,0x38,
+0x31,0x39,0x58,0x2d,0x25,0x64,0x3e,0x0a,0x0d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x2a,0x00,0x00,0x00,0x0a,0x0d,0x45,0x72,0x72,0x20,0x44,0x49,0x52,0x00,0x00,0x00,
+0x0a,0x0d,0x44,0x42,0x47,0x20,0x43,0x4d,0x44,0x73,0x3a,0x00,0x0a,0x0d,0x5b,0x00,
+0x5d,0x2d,0x00,0x00,0x0a,0x0d,0x3c,0x31,0x2e,0x43,0x4d,0x4e,0x3e,0x20,0x3c,0x32,
+0x2e,0x3f,0x3e,0x00,0x0a,0x0d,0x20,0x79,0x65,0x61,0x72,0x2d,0x64,0x61,0x79,0x2d,
+0x68,0x6f,0x75,0x72,0x2d,0x6d,0x69,0x6e,0x2d,0x73,0x65,0x63,0x2d,0x31,0x30,0x6d,
+0x73,0x3d,0x00,0x00,0x25,0x64,0x2d,0x00,0x0a,0x0d,0x09,0x20,0x20,0x20,0x20,0x20,
+0x30,0x30,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x30,0x34,0x20,0x20,0x20,0x20,0x20,
+0x20,0x20,0x30,0x38,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x30,0x43,0x00,0x00,0x00,
+0x0a,0x0d,0x09,0x20,0x20,0x20,0x20,0x20,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,
+0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,
+0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x3d,0x00,0x0d,0x0a,0x20,0x30,
+0x78,0x25,0x30,0x38,0x58,0x20,0x20,0x00,0x09,0x00,0x00,0x00,0x25,0x30,0x38,0x58,
+0x20,0x00,0x00,0x00,0x0a,0x0d,0x44,0x62,0x67,0x5f,0x46,0x6c,0x61,0x67,0x25,0x64,
+0x3d,0x30,0x78,0x25,0x30,0x38,0x78,0x00,0x0a,0x0d,0x20,0x76,0x6f,0x71,0x74,0x78,
+0x72,0x65,0x71,0x20,0x3d,0x20,0x25,0x64,0x00,0x00,0x00,0x00,0x0a,0x0d,0x20,0x76,
+0x69,0x71,0x74,0x78,0x72,0x65,0x71,0x20,0x3d,0x20,0x25,0x64,0x00,0x00,0x00,0x00,
+0x0a,0x0d,0x20,0x62,0x65,0x71,0x74,0x78,0x72,0x65,0x71,0x20,0x3d,0x20,0x25,0x64,
+0x00,0x00,0x00,0x00,0x0a,0x0d,0x20,0x62,0x6b,0x71,0x74,0x78,0x72,0x65,0x71,0x20,
+0x3d,0x20,0x25,0x64,0x00,0x00,0x00,0x00,0x0a,0x0d,0x20,0x62,0x63,0x6e,0x71,0x74,
+0x78,0x72,0x65,0x71,0x20,0x3d,0x20,0x25,0x64,0x00,0x00,0x00,0x0a,0x0d,0x20,0x68,
+0x71,0x74,0x78,0x72,0x65,0x71,0x20,0x3d,0x20,0x25,0x64,0x00,0x0a,0x0d,0x20,0x6d,
+0x67,0x71,0x74,0x78,0x72,0x65,0x71,0x20,0x3d,0x20,0x25,0x64,0x00,0x00,0x00,0x00,
+0x0a,0x0d,0x54,0x58,0x4c,0x4c,0x54,0x09,0x09,0x4e,0x45,0x58,0x54,0x20,0x20,0x20,
+0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x4e,0x45,0x58,0x54,0x0a,0x0d,0x00,
+0x0a,0x0d,0x20,0x50,0x61,0x67,0x65,0x25,0x33,0x64,0x09,0x00,0x25,0x34,0x64,0x20,
+0x20,0x20,0x20,0x00,0x25,0x34,0x64,0x20,0x20,0x20,0x20,0x09,0x00,0x00,0x00,0x00,
+0x0a,0x0d,0x54,0x58,0x4f,0x51,0x54,0x09,0x09,0x48,0x65,0x61,0x64,0x20,0x20,0x20,
+0x20,0x54,0x61,0x69,0x6c,0x20,0x20,0x20,0x20,0x48,0x65,0x61,0x64,0x20,0x20,0x20,
+0x20,0x54,0x61,0x69,0x6c,0x0a,0x0d,0x00,0x0a,0x0d,0x55,0x6e,0x6b,0x6e,0x6f,0x77,
+0x20,0x63,0x6f,0x6d,0x6d,0x61,0x6e,0x64,0x00,0x00,0x00,0x00,0x0a,0x0d,0x45,0x72,
+0x72,0x20,0x41,0x72,0x67,0x0a,0x0d,0x55,0x53,0x41,0x47,0x45,0x3a,0x00,0x00,0x00,
+0x10,0x00,0x08,0x00,0x02,0xe9,0x01,0x74,0x02,0xab,0x01,0xc7,0x01,0x55,0x00,0xe4,
+0x00,0xab,0x00,0x72,0x00,0x55,0x00,0x4c,0x00,0x4c,0x00,0x4c,0x00,0x4c,0x00,0x4c,
+0x02,0x76,0x01,0x3b,0x00,0xd2,0x00,0x9e,0x00,0x69,0x00,0x4f,0x00,0x46,0x00,0x3f,
+0x01,0x3b,0x00,0x9e,0x00,0x69,0x00,0x4f,0x00,0x35,0x00,0x27,0x00,0x23,0x00,0x20,
+0x01,0x2f,0x00,0x98,0x00,0x65,0x00,0x4c,0x00,0x33,0x00,0x26,0x00,0x22,0x00,0x1e,
+0x00,0x98,0x00,0x4c,0x00,0x33,0x00,0x26,0x00,0x19,0x00,0x13,0x00,0x11,0x00,0x0f,
+0x02,0x39,0x01,0x1c,0x00,0xbd,0x00,0x8e,0x00,0x5f,0x00,0x47,0x00,0x3f,0x00,0x39,
+0x01,0x1c,0x00,0x8e,0x00,0x5f,0x00,0x47,0x00,0x2f,0x00,0x23,0x00,0x20,0x00,0x1c,
+0x01,0x11,0x00,0x89,0x00,0x5b,0x00,0x44,0x00,0x2e,0x00,0x22,0x00,0x1e,0x00,0x1b,
+0x00,0x89,0x00,0x44,0x00,0x2e,0x00,0x22,0x00,0x17,0x00,0x11,0x00,0x0f,0x00,0x0e,
+0x02,0xab,0x02,0xab,0x02,0x66,0x02,0x66,0x07,0x06,0x06,0x06,0x05,0x06,0x07,0x08,
+0x04,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0b,0x49,0x6e,0x74,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x54,0x4c,0x42,0x4d,0x4f,0x44,0x00,0x00,0x00,0x00,0x54,0x4c,0x42,0x4c,
+0x5f,0x64,0x61,0x74,0x61,0x00,0x54,0x4c,0x42,0x53,0x00,0x00,0x00,0x00,0x00,0x00,
+0x41,0x64,0x45,0x4c,0x5f,0x64,0x61,0x74,0x61,0x00,0x41,0x64,0x45,0x53,0x00,0x00,
+0x00,0x00,0x00,0x00,0x45,0x78,0x63,0x43,0x6f,0x64,0x65,0x36,0x00,0x00,0x45,0x78,
+0x63,0x43,0x6f,0x64,0x65,0x37,0x00,0x00,0x53,0x79,0x73,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x42,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x52,0x49,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x43,0x70,0x55,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x4f,0x76,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x80,0x01,0x11,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x10,
+0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x50,
+0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x90,0x00,0x00,0x00,0xc0,0x00,0x00,0x01,0x20,
+0x00,0x00,0x01,0x80,0x00,0x00,0x01,0xb0,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0xd0,
+0x00,0x00,0x01,0x30,0x00,0x00,0x01,0xa0,0x00,0x00,0x02,0x70,0x00,0x00,0x03,0x40,
+0x00,0x00,0x03,0xa0,0x00,0x00,0x04,0x10,0x00,0x00,0x00,0xd0,0x00,0x00,0x01,0xa0,
+0x00,0x00,0x02,0x70,0x00,0x00,0x03,0x40,0x00,0x00,0x04,0xe0,0x00,0x00,0x06,0x80,
+0x00,0x00,0x07,0x50,0x00,0x00,0x07,0xf8,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x02,
+0x02,0x02,0x02,0x02,0x01,0x01,0x02,0x02,0x04,0x05,0x06,0x06,0x02,0x02,0x04,0x06,
+0x07,0x09,0x0a,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x3c,0x4e,0x55,0x4c,0x4c,0x3e,0x00,0x00,0x30,0x31,0x32,0x33,
+0x34,0x35,0x36,0x37,0x38,0x39,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,
+0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,
+0x00,0x00,0x00,0x00,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x41,0x42,
+0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,
+0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x00,0x00,0x00,0x00,0x5b,0x52,0x58,0x5d,
+0x20,0x70,0x6b,0x74,0x5f,0x6c,0x65,0x6e,0x3d,0x25,0x64,0x20,0x6f,0x66,0x66,0x73,
+0x65,0x74,0x3d,0x25,0x64,0x20,0x73,0x74,0x61,0x72,0x74,0x5f,0x61,0x64,0x64,0x72,
+0x3d,0x25,0x30,0x38,0x78,0x0a,0x0d,0x00,0x80,0x00,0x6a,0x64,0x80,0x00,0x6a,0x88,
+0x80,0x00,0x6a,0xa4,0x80,0x00,0x6b,0x90,0x80,0x00,0x6c,0x48,0x80,0x00,0x6c,0x98,
+0x80,0x00,0x6d,0x04,0x80,0x00,0x6e,0x08,0x80,0x00,0x6e,0x3c,0x80,0x00,0x6e,0x50,
+0x80,0x00,0x6e,0x64,0x80,0x00,0x6f,0x3c,0x80,0x00,0x6f,0x78,0x80,0x00,0x70,0x28,
+0x80,0x00,0x70,0x50,0x80,0x00,0x6a,0x20,0x80,0x00,0x70,0x64,0x80,0x00,0x76,0x5c,
+0x80,0x00,0x76,0xd4,0x80,0x00,0x76,0xe0,0x80,0x00,0x76,0xec,0x80,0x00,0x76,0x74,
+0x80,0x00,0x76,0x74,0x80,0x00,0x76,0x74,0x80,0x00,0x76,0x74,0x80,0x00,0x76,0x74,
+0x80,0x00,0x76,0x74,0x80,0x00,0x76,0x74,0x80,0x00,0x76,0x74,0x80,0x00,0x76,0x74,
+0x80,0x00,0x76,0x74,0x80,0x00,0x76,0x74,0x80,0x00,0x76,0x74,0x80,0x00,0x76,0xf8,
+0x80,0x00,0x77,0x04,0x80,0x00,0x77,0x10,0x80,0x00,0xa7,0x80,0x80,0x00,0xa7,0x98,
+0x80,0x00,0xa7,0x98,0x80,0x00,0xa7,0x88,0x80,0x00,0xa7,0x98,0x80,0x00,0xa7,0x98,
+0x80,0x00,0xa7,0x98,0x80,0x00,0xa7,0x98,0x80,0x00,0xa7,0x98,0x80,0x00,0xa7,0x98,
+0x80,0x00,0xa7,0x98,0x80,0x00,0xa7,0x90,0x80,0x00,0xa7,0x98,0x80,0x00,0xa7,0x78,
+0x80,0x00,0xa7,0x98,0x80,0x00,0xa7,0x98,0x80,0x00,0xab,0xc0,0x80,0x00,0xa8,0xb0,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xa8,0xbc,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xa8,0x44,0x80,0x00,0xa9,0x90,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xa9,0x90,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xa9,0x98,0x80,0x00,0xa9,0xb8,0x80,0x00,0xa9,0xc0,0x80,0x00,0xaa,0xc8,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0x18,0x80,0x00,0xaa,0xc8,0x80,0x00,0xa8,0xc4,
+0x80,0x00,0xaa,0xc8,0x80,0x00,0xaa,0xc8,0x80,0x00,0xa8,0xc0,};
+
+#define PHY_REGArrayLengthDTM 1
+u32 Rtl8192PciEPHY_REGArrayDTM[PHY_REGArrayLengthDTM] = {
+0x0, };
+
+#define PHY_REG_1T2RArrayLengthDTM 296
+u32 Rtl8192PciEPHY_REG_1T2RArrayDTM[PHY_REG_1T2RArrayLengthDTM] = {
+0x800,0x00000000,
+0x804,0x00000001,
+0x808,0x0000fc00,
+0x80c,0x0000001c,
+0x810,0x801010aa,
+0x814,0x008514d0,
+0x818,0x00000040,
+0x81c,0x00000000,
+0x820,0x00000004,
+0x824,0x00690000,
+0x828,0x00000004,
+0x82c,0x00e90000,
+0x830,0x00000004,
+0x834,0x00690000,
+0x838,0x00000004,
+0x83c,0x00e90000,
+0x840,0x00000000,
+0x844,0x00000000,
+0x848,0x00000000,
+0x84c,0x00000000,
+0x850,0x00000000,
+0x854,0x00000000,
+0x858,0x65a965a9,
+0x85c,0x65a965a9,
+0x860,0x001f0010,
+0x864,0x007f0010,
+0x868,0x001f0010,
+0x86c,0x007f0010,
+0x870,0x0f100f70,
+0x874,0x0f100f70,
+0x878,0x00000000,
+0x87c,0x00000000,
+0x880,0x6870e36c,
+0x884,0xe3573600,
+0x888,0x4260c340,
+0x88c,0x0000ff00,
+0x890,0x00000000,
+0x894,0xfffffffe,
+0x898,0x40302010,
+0x89c,0x00706050,
+0x8b0,0x00000000,
+0x8e0,0x00000000,
+0x8e4,0x00000000,
+0x900,0x00000000,
+0x904,0x00000023,
+0x908,0x00000000,
+0x90c,0x31121311,
+0xa00,0x00d0c7d8,
+0xa04,0x811f0008,
+0xa08,0x80cd8300,
+0xa0c,0x2e62740f,
+0xa10,0x95009b78,
+0xa14,0x11145008,
+0xa18,0x00881117,
+0xa1c,0x89140fa0,
+0xa20,0x1a1b0000,
+0xa24,0x090e1317,
+0xa28,0x00000204,
+0xa2c,0x00000000,
+0xc00,0x00000040,
+0xc04,0x00005411,
+0xc08,0x000000e4,
+0xc0c,0x6c6c6c6c,
+0xc10,0x08800000,
+0xc14,0x40000100,
+0xc18,0x08000000,
+0xc1c,0x40000100,
+0xc20,0x08000000,
+0xc24,0x40000100,
+0xc28,0x08000000,
+0xc2c,0x40000100,
+0xc30,0x6de98a44,
+0xc34,0x469652cd,
+0xc38,0x49475996,
+0xc3c,0x0a9a9764,
+0xc40,0x1f7c423f,
+0xc44,0x000100b7,
+0xc48,0xec020000,
+0xc4c,0x00000300,
+0xc50,0x69543430,
+0xc54,0x433c0094,
+0xc58,0x69543430,
+0xc5c,0x433c0094,
+0xc60,0x69543430,
+0xc64,0x433c0094,
+0xc68,0x69543430,
+0xc6c,0x433c0094,
+0xc70,0x2c7f000d,
+0xc74,0x0186175b,
+0xc78,0x0000001f,
+0xc7c,0x00b91612,
+0xc80,0x40000100,
+0xc84,0x20000000,
+0xc88,0x40000100,
+0xc8c,0x08000000,
+0xc90,0x40000100,
+0xc94,0x00000000,
+0xc98,0x40000100,
+0xc9c,0x00000000,
+0xca0,0x00492492,
+0xca4,0x00000000,
+0xca8,0x00000000,
+0xcac,0x00000000,
+0xcb0,0x00000000,
+0xcb4,0x00000000,
+0xcb8,0x00000000,
+0xcbc,0x00492492,
+0xcc0,0x00000000,
+0xcc4,0x00000000,
+0xcc8,0x00000000,
+0xccc,0x00000000,
+0xcd0,0x00000000,
+0xcd4,0x00000000,
+0xcd8,0x64b22427,
+0xcdc,0x00766932,
+0xce0,0x00222222,
+0xd00,0x00000740,
+0xd04,0x00000401,
+0xd08,0x0000907f,
+0xd0c,0x00000001,
+0xd10,0xa0633333,
+0xd14,0x33333c63,
+0xd18,0x6a8f5b6b,
+0xd1c,0x00000000,
+0xd20,0x00000000,
+0xd24,0x00000000,
+0xd28,0x00000000,
+0xd2c,0xcc979975,
+0xd30,0x00000000,
+0xd34,0x00000000,
+0xd38,0x00000000,
+0xd3c,0x00027293,
+0xd40,0x00000000,
+0xd44,0x00000000,
+0xd48,0x00000000,
+0xd4c,0x00000000,
+0xd50,0x6437140a,
+0xd54,0x024dbd02,
+0xd58,0x00000000,
+0xd5c,0x2d432064,
+0xe00,0x161a1a1a,
+0xe04,0x12121416,
+0xe08,0x00001800,
+0xe0c,0x00000000,
+0xe10,0x161a1a1a,
+0xe14,0x12121416,
+0xe18,0x161a1a1a,
+0xe1c,0x12121416,
+};
+
+#define RadioA_ArrayLengthDTM 246
+u32 Rtl8192PciERadioA_ArrayDTM[RadioA_ArrayLengthDTM] = {
+0x019,0x00000003,
+0x000,0x000000bf,
+0x001,0x00000ee0,
+0x002,0x0000004c,
+0x003,0x000007f1,
+0x004,0x00000975,
+0x005,0x00000c58,
+0x006,0x00000ae6,
+0x007,0x000000ca,
+0x008,0x00000e1c,
+0x009,0x000007f0,
+0x00a,0x000009d0,
+0x00b,0x000001ba,
+0x00c,0x00000240,
+0x00e,0x00000020,
+0x00f,0x00000ff0,
+0x012,0x00000806,
+0x014,0x000005ab,
+0x015,0x00000f80,
+0x016,0x00000020,
+0x017,0x00000597,
+0x018,0x0000050a,
+0x01a,0x00000e00,
+0x01b,0x00000f5e,
+0x01c,0x00000008,
+0x01d,0x00000607,
+0x01e,0x000006cc,
+0x01f,0x00000000,
+0x020,0x00000096,
+0x01f,0x00000001,
+0x020,0x00000076,
+0x01f,0x00000002,
+0x020,0x00000056,
+0x01f,0x00000003,
+0x020,0x00000036,
+0x01f,0x00000004,
+0x020,0x00000016,
+0x01f,0x00000005,
+0x020,0x000001f6,
+0x01f,0x00000006,
+0x020,0x000001d6,
+0x01f,0x00000007,
+0x020,0x000001b6,
+0x01f,0x00000008,
+0x020,0x00000196,
+0x01f,0x00000009,
+0x020,0x00000176,
+0x01f,0x0000000a,
+0x020,0x000000f7,
+0x01f,0x0000000b,
+0x020,0x000000d7,
+0x01f,0x0000000c,
+0x020,0x000000b7,
+0x01f,0x0000000d,
+0x020,0x00000097,
+0x01f,0x0000000e,
+0x020,0x00000077,
+0x01f,0x0000000f,
+0x020,0x00000057,
+0x01f,0x00000010,
+0x020,0x00000037,
+0x01f,0x00000011,
+0x020,0x000000fb,
+0x01f,0x00000012,
+0x020,0x000000db,
+0x01f,0x00000013,
+0x020,0x000000bb,
+0x01f,0x00000014,
+0x020,0x000000ff,
+0x01f,0x00000015,
+0x020,0x000000e3,
+0x01f,0x00000016,
+0x020,0x000000c3,
+0x01f,0x00000017,
+0x020,0x000000a3,
+0x01f,0x00000018,
+0x020,0x00000083,
+0x01f,0x00000019,
+0x020,0x00000063,
+0x01f,0x0000001a,
+0x020,0x00000043,
+0x01f,0x0000001b,
+0x020,0x00000023,
+0x01f,0x0000001c,
+0x020,0x00000003,
+0x01f,0x0000001d,
+0x020,0x000001e3,
+0x01f,0x0000001e,
+0x020,0x000001c3,
+0x01f,0x0000001f,
+0x020,0x000001a3,
+0x01f,0x00000020,
+0x020,0x00000183,
+0x01f,0x00000021,
+0x020,0x00000163,
+0x01f,0x00000022,
+0x020,0x00000143,
+0x01f,0x00000023,
+0x020,0x00000123,
+0x01f,0x00000024,
+0x020,0x00000103,
+0x023,0x00000203,
+0x024,0x00000200,
+0x00b,0x000001ba,
+0x02c,0x000003d7,
+0x02d,0x00000ff0,
+0x000,0x00000037,
+0x004,0x00000160,
+0x007,0x00000080,
+0x002,0x0000088d,
+0x0fe,0x00000000,
+0x0fe,0x00000000,
+0x016,0x00000200,
+0x016,0x00000380,
+0x016,0x00000020,
+0x016,0x000001a0,
+0x000,0x000000bf,
+0x00d,0x0000001f,
+0x00d,0x00000c9f,
+0x002,0x0000004d,
+0x000,0x00000cbf,
+0x004,0x00000975,
+0x007,0x00000700,
+};
+
+#define RadioB_ArrayLengthDTM 78
+u32 Rtl8192PciERadioB_ArrayDTM[RadioB_ArrayLengthDTM] = {
+0x019,0x00000003,
+0x000,0x000000bf,
+0x001,0x000006e0,
+0x002,0x0000004c,
+0x003,0x000007f1,
+0x004,0x00000975,
+0x005,0x00000c58,
+0x006,0x00000ae6,
+0x007,0x000000ca,
+0x008,0x00000e1c,
+0x000,0x000000b7,
+0x00a,0x00000850,
+0x000,0x000000bf,
+0x00b,0x000001ba,
+0x00c,0x00000240,
+0x00e,0x00000020,
+0x015,0x00000f80,
+0x016,0x00000020,
+0x017,0x00000597,
+0x018,0x0000050a,
+0x01a,0x00000e00,
+0x01b,0x00000f5e,
+0x01d,0x00000607,
+0x01e,0x000006cc,
+0x00b,0x000001ba,
+0x023,0x00000203,
+0x024,0x00000200,
+0x000,0x00000037,
+0x004,0x00000160,
+0x016,0x00000200,
+0x016,0x00000380,
+0x016,0x00000020,
+0x016,0x000001a0,
+0x00d,0x00000ccc,
+0x000,0x000000bf,
+0x002,0x0000004d,
+0x000,0x00000cbf,
+0x004,0x00000975,
+0x007,0x00000700,
+};
+
+#define RadioC_ArrayLengthDTM 1
+u32 Rtl8192PciERadioC_ArrayDTM[RadioC_ArrayLengthDTM] = {
+0x0, };
+
+#define RadioD_ArrayLengthDTM 1
+u32 Rtl8192PciERadioD_ArrayDTM[RadioD_ArrayLengthDTM] = {
+0x0, };
+
+u32 Rtl8192PciEMACPHY_ArrayDTM[] = {
+0x03c,0xffff0000,0x00000f0f,
+0x340,0xffffffff,0x161a1a1a,
+0x344,0xffffffff,0x12121416,
+0x348,0x0000ffff,0x00001818,
+0x12c,0xffffffff,0x04000802,
+0x318,0x00000fff,0x00000100,
+};
+
+u32 Rtl8192PciEMACPHY_Array_PGDTM[] = {
+0x03c,0xffff0000,0x00000f0f,
+0xe00,0xffffffff,0x06090909,
+0xe04,0xffffffff,0x00030306,
+0xe08,0x0000ff00,0x00000000,
+0xe10,0xffffffff,0x050b0b0e,
+0xe14,0xffffffff,0x00030305,
+0xe18,0xffffffff,0x050b0b0e,
+0xe1c,0xffffffff,0x00030305,
+0x12c,0xffffffff,0x04000802,
+0x318,0x00000fff,0x00000800,
+};
+
+u32 Rtl8192PciEAGCTAB_ArrayDTM[AGCTAB_ArrayLength] = {
+0xc78,0x7d000001,
+0xc78,0x7d010001,
+0xc78,0x7d020001,
+0xc78,0x7d030001,
+0xc78,0x7d040001,
+0xc78,0x7d050001,
+0xc78,0x7c060001,
+0xc78,0x7b070001,
+0xc78,0x7a080001,
+0xc78,0x79090001,
+0xc78,0x780a0001,
+0xc78,0x770b0001,
+0xc78,0x760c0001,
+0xc78,0x750d0001,
+0xc78,0x740e0001,
+0xc78,0x730f0001,
+0xc78,0x72100001,
+0xc78,0x71110001,
+0xc78,0x70120001,
+0xc78,0x6f130001,
+0xc78,0x6e140001,
+0xc78,0x6d150001,
+0xc78,0x6c160001,
+0xc78,0x6b170001,
+0xc78,0x6a180001,
+0xc78,0x69190001,
+0xc78,0x681a0001,
+0xc78,0x671b0001,
+0xc78,0x661c0001,
+0xc78,0x651d0001,
+0xc78,0x641e0001,
+0xc78,0x491f0001,
+0xc78,0x48200001,
+0xc78,0x47210001,
+0xc78,0x46220001,
+0xc78,0x45230001,
+0xc78,0x44240001,
+0xc78,0x43250001,
+0xc78,0x28260001,
+0xc78,0x27270001,
+0xc78,0x26280001,
+0xc78,0x25290001,
+0xc78,0x242a0001,
+0xc78,0x232b0001,
+0xc78,0x222c0001,
+0xc78,0x212d0001,
+0xc78,0x202e0001,
+0xc78,0x0a2f0001,
+0xc78,0x08300001,
+0xc78,0x06310001,
+0xc78,0x05320001,
+0xc78,0x04330001,
+0xc78,0x03340001,
+0xc78,0x02350001,
+0xc78,0x01360001,
+0xc78,0x00370001,
+0xc78,0x00380001,
+0xc78,0x00390001,
+0xc78,0x003a0001,
+0xc78,0x003b0001,
+0xc78,0x003c0001,
+0xc78,0x003d0001,
+0xc78,0x003e0001,
+0xc78,0x003f0001,
+0xc78,0x7d400001,
+0xc78,0x7d410001,
+0xc78,0x7d420001,
+0xc78,0x7d430001,
+0xc78,0x7d440001,
+0xc78,0x7d450001,
+0xc78,0x7c460001,
+0xc78,0x7b470001,
+0xc78,0x7a480001,
+0xc78,0x79490001,
+0xc78,0x784a0001,
+0xc78,0x774b0001,
+0xc78,0x764c0001,
+0xc78,0x754d0001,
+0xc78,0x744e0001,
+0xc78,0x734f0001,
+0xc78,0x72500001,
+0xc78,0x71510001,
+0xc78,0x70520001,
+0xc78,0x6f530001,
+0xc78,0x6e540001,
+0xc78,0x6d550001,
+0xc78,0x6c560001,
+0xc78,0x6b570001,
+0xc78,0x6a580001,
+0xc78,0x69590001,
+0xc78,0x685a0001,
+0xc78,0x675b0001,
+0xc78,0x665c0001,
+0xc78,0x655d0001,
+0xc78,0x645e0001,
+0xc78,0x495f0001,
+0xc78,0x48600001,
+0xc78,0x47610001,
+0xc78,0x46620001,
+0xc78,0x45630001,
+0xc78,0x44640001,
+0xc78,0x43650001,
+0xc78,0x28660001,
+0xc78,0x27670001,
+0xc78,0x26680001,
+0xc78,0x25690001,
+0xc78,0x246a0001,
+0xc78,0x236b0001,
+0xc78,0x226c0001,
+0xc78,0x216d0001,
+0xc78,0x206e0001,
+0xc78,0x0a6f0001,
+0xc78,0x08700001,
+0xc78,0x06710001,
+0xc78,0x05720001,
+0xc78,0x04730001,
+0xc78,0x03740001,
+0xc78,0x02750001,
+0xc78,0x01760001,
+0xc78,0x00770001,
+0xc78,0x00780001,
+0xc78,0x00790001,
+0xc78,0x007a0001,
+0xc78,0x007b0001,
+0xc78,0x007c0001,
+0xc78,0x007d0001,
+0xc78,0x007e0001,
+0xc78,0x007f0001,
+0xc78,0x2e00001e,
+0xc78,0x2e01001e,
+0xc78,0x2e02001e,
+0xc78,0x2e03001e,
+0xc78,0x2e04001e,
+0xc78,0x2e05001e,
+0xc78,0x3006001e,
+0xc78,0x3407001e,
+0xc78,0x3908001e,
+0xc78,0x3c09001e,
+0xc78,0x3f0a001e,
+0xc78,0x420b001e,
+0xc78,0x440c001e,
+0xc78,0x450d001e,
+0xc78,0x460e001e,
+0xc78,0x460f001e,
+0xc78,0x4710001e,
+0xc78,0x4811001e,
+0xc78,0x4912001e,
+0xc78,0x4a13001e,
+0xc78,0x4b14001e,
+0xc78,0x4b15001e,
+0xc78,0x4c16001e,
+0xc78,0x4d17001e,
+0xc78,0x4e18001e,
+0xc78,0x4f19001e,
+0xc78,0x4f1a001e,
+0xc78,0x501b001e,
+0xc78,0x511c001e,
+0xc78,0x521d001e,
+0xc78,0x521e001e,
+0xc78,0x531f001e,
+0xc78,0x5320001e,
+0xc78,0x5421001e,
+0xc78,0x5522001e,
+0xc78,0x5523001e,
+0xc78,0x5624001e,
+0xc78,0x5725001e,
+0xc78,0x5726001e,
+0xc78,0x5827001e,
+0xc78,0x5828001e,
+0xc78,0x5929001e,
+0xc78,0x592a001e,
+0xc78,0x5a2b001e,
+0xc78,0x5b2c001e,
+0xc78,0x5c2d001e,
+0xc78,0x5c2e001e,
+0xc78,0x5d2f001e,
+0xc78,0x5e30001e,
+0xc78,0x5f31001e,
+0xc78,0x6032001e,
+0xc78,0x6033001e,
+0xc78,0x6134001e,
+0xc78,0x6235001e,
+0xc78,0x6336001e,
+0xc78,0x6437001e,
+0xc78,0x6438001e,
+0xc78,0x6539001e,
+0xc78,0x663a001e,
+0xc78,0x673b001e,
+0xc78,0x673c001e,
+0xc78,0x683d001e,
+0xc78,0x693e001e,
+0xc78,0x6a3f001e,
+};
+
+#endif //__INC_HAL8192PciE_FW_IMG_DTM_H
diff --git a/drivers/staging/rtl8192su/r8192S_firmware.c b/drivers/staging/rtl8192su/r8192S_firmware.c
new file mode 100644
index 0000000..b3d69b3
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_firmware.c
@@ -0,0 +1,1023 @@
+/**************************************************************************************************
+ * Procedure:    Init boot code/firmware code/data session
+ *
+ * Description: This routine will intialize firmware. If any error occurs during the initialization
+ * 		process, the routine shall terminate immediately and return fail.
+ *		NIC driver should call NdisOpenFile only from MiniportInitialize.
+ *
+ * Arguments:   The pointer of the adapter
+
+ * Returns:
+ *        NDIS_STATUS_FAILURE - the following initialization process should be terminated
+ *        NDIS_STATUS_SUCCESS - if firmware initialization process success
+**************************************************************************************************/
+//#include "ieee80211.h"
+#if defined(RTL8192SE)||defined(RTL8192SU)
+#include "r8192U.h"
+#include "r8192S_firmware.h"
+#include <linux/unistd.h>
+
+#ifdef RTL8192SU
+#include "r8192S_hw.h"
+#include "r8192SU_HWImg.h"
+//#include "r8192S_FwImgDTM.h"
+#else
+//#include "r8192U_hw.h"
+#include "r8192xU_firmware_img.h"
+#endif
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+#include <linux/firmware.h>
+#endif
+
+#define   byte(x,n)  ( (x >> (8 * n)) & 0xff  )
+
+//
+// Description:   This routine will intialize firmware. If any error occurs during the initialization
+//				process, the routine shall terminate immediately and return fail.
+//
+// Arguments:   The pointer of the adapter
+//			   Code address (Virtual address, should fill descriptor with physical address)
+//			   Code size
+// Created by Roger, 2008.04.10.
+//
+bool FirmwareDownloadCode(struct net_device *dev, u8 *	code_virtual_address,u32 buffer_len)
+{
+	struct r8192_priv   *priv = ieee80211_priv(dev);
+	bool 		    rt_status = true;
+	u16		    frag_threshold = MAX_FIRMWARE_CODE_SIZE; //Fragmentation might be required in 90/92 but not in 92S
+	u16		    frag_length, frag_offset = 0;
+	struct sk_buff	    *skb;
+	unsigned char	    *seg_ptr;
+	cb_desc		    *tcb_desc;
+	u8                  	    bLastIniPkt = 0;
+	u16 			    ExtraDescOffset = 0;
+
+#ifdef RTL8192SE
+	fw_SetRQPN(dev);	// For 92SE only
+#endif
+
+	RT_TRACE(COMP_FIRMWARE, "--->FirmwareDownloadCode()\n" );
+
+	//MAX_TRANSMIT_BUFFER_SIZE
+	if(buffer_len >= MAX_FIRMWARE_CODE_SIZE-USB_HWDESC_HEADER_LEN)
+	{
+		RT_TRACE(COMP_ERR, "Size over MAX_FIRMWARE_CODE_SIZE! \n");
+		goto cmdsend_downloadcode_fail;
+	}
+
+	ExtraDescOffset = USB_HWDESC_HEADER_LEN;
+
+	do {
+		if((buffer_len-frag_offset) > frag_threshold)
+		{
+			frag_length = frag_threshold + ExtraDescOffset;
+		}
+		else
+		{
+			frag_length = (u16)(buffer_len - frag_offset + ExtraDescOffset);
+		bLastIniPkt = 1;
+		}
+
+		/* Allocate skb buffer to contain firmware info and tx descriptor info. */
+		skb  = dev_alloc_skb(frag_length);
+		memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
+
+		tcb_desc = (cb_desc*)(skb->cb + MAX_DEV_ADDR_SIZE);
+		tcb_desc->queue_index = TXCMD_QUEUE;
+		tcb_desc->bCmdOrInit = DESC_PACKET_TYPE_INIT;
+		tcb_desc->bLastIniPkt = bLastIniPkt;
+
+		skb_reserve(skb, ExtraDescOffset);
+		seg_ptr = (u8 *)skb_put(skb, (u32)(frag_length-ExtraDescOffset));
+		memcpy(seg_ptr, code_virtual_address+frag_offset, (u32)(frag_length-ExtraDescOffset));
+
+		tcb_desc->txbuf_size= frag_length;
+
+		if(!priv->ieee80211->check_nic_enough_desc(dev,tcb_desc->queue_index)||
+			(!skb_queue_empty(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index]))||\
+			(priv->ieee80211->queue_stop) )
+		{
+			RT_TRACE(COMP_FIRMWARE,"=====================================================> tx full!\n");
+			skb_queue_tail(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index], skb);
+		}
+		else
+		{
+			priv->ieee80211->softmac_hard_start_xmit(skb,dev);
+		}
+
+		frag_offset += (frag_length - ExtraDescOffset);
+
+	}while(frag_offset < buffer_len);
+
+	return rt_status ;
+
+
+cmdsend_downloadcode_fail:
+	rt_status = false;
+	RT_TRACE(COMP_ERR, "CmdSendDownloadCode fail !!\n");
+	return rt_status;
+
+}
+
+#ifdef RTL8192SE
+static void fw_SetRQPN(struct net_device *dev)
+{
+	// Only for 92SE HW bug, we have to set RAPN before every FW download
+	// We can remove the code later.
+	write_nic_dword(dev,  RQPN, 0xffffffff);
+	write_nic_dword(dev,  RQPN+4, 0xffffffff);
+	write_nic_byte(dev,  RQPN+8, 0xff);
+	write_nic_byte(dev,  RQPN+0xB, 0x80);
+	//#if ((HAL_CODE_BASE ==  RTL8192_S) && (PLATFORM != PLATFORM_WINDOWS_USB))
+
+}	/* fw_SetRQPN */
+#endif
+
+RT_STATUS
+FirmwareEnableCPU(struct net_device *dev)
+{
+
+	RT_STATUS	rtStatus = RT_STATUS_SUCCESS;
+	u8		tmpU1b, CPUStatus = 0;
+	u16		tmpU2b;
+	u32		iCheckTime = 200;
+
+	RT_TRACE(COMP_FIRMWARE, "-->FirmwareEnableCPU()\n" );
+#ifdef RTL8192SE
+	fw_SetRQPN(dev);	// For 92SE only
+#endif
+	// Enable CPU.
+	tmpU1b = read_nic_byte(dev, SYS_CLKR);
+	write_nic_byte(dev,  SYS_CLKR, (tmpU1b|SYS_CPU_CLKSEL)); //AFE source
+
+	tmpU2b = read_nic_word(dev, SYS_FUNC_EN);
+	write_nic_word(dev, SYS_FUNC_EN, (tmpU2b|FEN_CPUEN));
+
+	//Polling IMEM Ready after CPU has refilled.
+	do
+	{
+		CPUStatus = read_nic_byte(dev, TCR);
+		if(CPUStatus& IMEM_RDY)
+		{
+			RT_TRACE(COMP_FIRMWARE, "IMEM Ready after CPU has refilled.\n");
+			break;
+		}
+
+		//usleep(100);
+		udelay(100);
+	}while(iCheckTime--);
+
+	if(!(CPUStatus & IMEM_RDY))
+		return RT_STATUS_FAILURE;
+
+	RT_TRACE(COMP_FIRMWARE, "<--FirmwareEnableCPU(): rtStatus(%#x)\n", rtStatus);
+	return rtStatus;
+}
+
+FIRMWARE_8192S_STATUS
+FirmwareGetNextStatus(FIRMWARE_8192S_STATUS FWCurrentStatus)
+{
+	FIRMWARE_8192S_STATUS	NextFWStatus = 0;
+
+	switch(FWCurrentStatus)
+	{
+		case FW_STATUS_INIT:
+			NextFWStatus = FW_STATUS_LOAD_IMEM;
+			break;
+
+		case FW_STATUS_LOAD_IMEM:
+			NextFWStatus = FW_STATUS_LOAD_EMEM;
+			break;
+
+		case FW_STATUS_LOAD_EMEM:
+			NextFWStatus = FW_STATUS_LOAD_DMEM;
+			break;
+
+		case FW_STATUS_LOAD_DMEM:
+			NextFWStatus = FW_STATUS_READY;
+			break;
+
+		default:
+			RT_TRACE(COMP_ERR,"Invalid FW Status(%#x)!!\n", FWCurrentStatus);
+			break;
+	}
+	return	NextFWStatus;
+}
+
+bool
+FirmwareCheckReady(struct net_device *dev,	u8 LoadFWStatus)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	RT_STATUS	rtStatus = RT_STATUS_SUCCESS;
+	rt_firmware	*pFirmware = priv->pFirmware;
+	int			PollingCnt = 1000;
+	//u8	 	tmpU1b, CPUStatus = 0;
+	u8	 	CPUStatus = 0;
+	u32		tmpU4b;
+	//bool		bOrgIMREnable;
+
+	RT_TRACE(COMP_FIRMWARE, "--->FirmwareCheckReady(): LoadStaus(%d),", LoadFWStatus);
+
+	pFirmware->FWStatus = (FIRMWARE_8192S_STATUS)LoadFWStatus;
+	if( LoadFWStatus == FW_STATUS_LOAD_IMEM)
+	{
+		do
+		{//Polling IMEM code done.
+			CPUStatus = read_nic_byte(dev, TCR);
+			if(CPUStatus& IMEM_CODE_DONE)
+				break;
+
+			udelay(5);
+		}while(PollingCnt--);
+		if(!(CPUStatus & IMEM_CHK_RPT) || PollingCnt <= 0)
+		{
+			RT_TRACE(COMP_ERR, "FW_STATUS_LOAD_IMEM FAIL CPU, Status=%x\r\n", CPUStatus);
+			return false;
+		}
+	}
+	else if( LoadFWStatus == FW_STATUS_LOAD_EMEM)
+	{//Check Put Code OK and Turn On CPU
+		do
+		{//Polling EMEM code done.
+			CPUStatus = read_nic_byte(dev, TCR);
+			if(CPUStatus& EMEM_CODE_DONE)
+				break;
+
+			udelay(5);
+		}while(PollingCnt--);
+		if(!(CPUStatus & EMEM_CHK_RPT))
+		{
+			RT_TRACE(COMP_ERR, "FW_STATUS_LOAD_EMEM FAIL CPU, Status=%x\r\n", CPUStatus);
+			return false;
+		}
+
+		// Turn On CPU
+		rtStatus = FirmwareEnableCPU(dev);
+		if(rtStatus != RT_STATUS_SUCCESS)
+		{
+			RT_TRACE(COMP_ERR, "Enable CPU fail ! \n" );
+			return false;
+		}
+	}
+	else if( LoadFWStatus == FW_STATUS_LOAD_DMEM)
+	{
+		do
+		{//Polling DMEM code done
+			CPUStatus = read_nic_byte(dev, TCR);
+			if(CPUStatus& DMEM_CODE_DONE)
+				break;
+
+			udelay(5);
+		}while(PollingCnt--);
+
+		if(!(CPUStatus & DMEM_CODE_DONE))
+		{
+			RT_TRACE(COMP_ERR, "Polling  DMEM code done fail ! CPUStatus(%#x)\n", CPUStatus);
+			return false;
+		}
+
+		RT_TRACE(COMP_FIRMWARE, "DMEM code download success, CPUStatus(%#x)\n", CPUStatus);
+
+//              PollingCnt = 100; // Set polling cycle to 10ms.
+              PollingCnt = 10000; // Set polling cycle to 10ms.
+
+		do
+		{//Polling Load Firmware ready
+			CPUStatus = read_nic_byte(dev, TCR);
+			if(CPUStatus & FWRDY)
+				break;
+
+			udelay(100);
+		}while(PollingCnt--);
+
+		RT_TRACE(COMP_FIRMWARE, "Polling Load Firmware ready, CPUStatus(%x)\n", CPUStatus);
+
+		//if(!(CPUStatus & LOAD_FW_READY))
+		//if((CPUStatus & LOAD_FW_READY) != 0xff)
+		if((CPUStatus & LOAD_FW_READY) != LOAD_FW_READY)
+		{
+			RT_TRACE(COMP_ERR, "Polling Load Firmware ready fail ! CPUStatus(%x)\n", CPUStatus);
+			return false;
+		}
+
+	       //
+              // <Roger_Notes> USB interface will update reserved followings parameters later!!
+              // 2008.08.28.
+              //
+#ifdef RTL8192SE
+		//write_nic_dword(dev, RQPN, 0x10101010);
+		//write_nic_byte(dev,  0xAB, 0x80);
+#endif
+
+	       //
+              // <Roger_Notes> If right here, we can set TCR/RCR to desired value
+              // and config MAC lookback mode to normal mode. 2008.08.28.
+              //
+              tmpU4b = read_nic_dword(dev,TCR);
+		write_nic_dword(dev, TCR, (tmpU4b&(~TCR_ICV)));
+
+		tmpU4b = read_nic_dword(dev, RCR);
+		write_nic_dword(dev, RCR,
+			(tmpU4b|RCR_APPFCS|RCR_APP_ICV|RCR_APP_MIC));
+
+		RT_TRACE(COMP_FIRMWARE, "FirmwareCheckReady(): Current RCR settings(%#x)\n", tmpU4b);
+
+#if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION) ||defined (RTL8192SU_ASIC_VERIFICATION))
+#ifdef NOT_YET   //YJ,TMP
+		priv->TransmitConfig = read_nic_dword(dev, TCR);
+		RT_TRACE(COMP_FIRMWARE, "FirmwareCheckReady(): Current TCR settings(%x)\n", priv->TransmitConfig);
+		pHalData->FwRsvdTxPageCfg = read_nic_byte(dev, FW_RSVD_PG_CRTL);
+#endif
+#endif
+
+		// Set to normal mode.
+		write_nic_byte(dev, LBKMD_SEL, LBK_NORMAL);
+
+	}
+
+	RT_TRACE(COMP_FIRMWARE, "<---FirmwareCheckReady(): LoadFWStatus(%d), rtStatus(%x)\n", LoadFWStatus, rtStatus);
+	return (rtStatus == RT_STATUS_SUCCESS) ? true:false;
+}
+
+//
+// Description:   This routine is to update the RF types in FW header partially.
+//
+// Created by Roger, 2008.12.24.
+//
+u8 FirmwareHeaderMapRfType(struct net_device *dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	switch(priv->rf_type)
+	{
+		case RF_1T1R: 	return 0x11;
+		case RF_1T2R: 	return 0x12;
+		case RF_2T2R: 	return 0x22;
+		case RF_2T2R_GREEN: 	return 0x92;
+		default:
+			RT_TRACE(COMP_INIT, "Unknown RF type(%x)\n",priv->rf_type);
+			break;
+	}
+	return 0x22;
+}
+
+
+//
+// Description:   This routine is to update the private parts in FW header partially.
+//
+// Created by Roger, 2008.12.18.
+//
+void FirmwareHeaderPriveUpdate(struct net_device *dev, PRT_8192S_FIRMWARE_PRIV 	pFwPriv)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+#ifdef RTL8192SU
+	// Update USB endpoint number for RQPN settings.
+	pFwPriv->usb_ep_num = priv->EEPROMUsbEndPointNumber; // endpoint number: 4, 6 and 11.
+	RT_TRACE(COMP_INIT, "FirmwarePriveUpdate(): usb_ep_num(%#x)\n", pFwPriv->usb_ep_num);
+#endif
+
+	// Update RF types for RATR settings.
+	pFwPriv->rf_config = FirmwareHeaderMapRfType(dev);
+}
+
+
+
+bool FirmwareDownload92S(struct net_device *dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	bool				rtStatus = true;
+	const char 		*pFwImageFileName[1] = {"RTL8192SU/rtl8192sfw.bin"};
+	u8				*pucMappedFile = NULL;
+	u32				ulFileLength, ulInitStep = 0;
+	u8				FwHdrSize = RT_8192S_FIRMWARE_HDR_SIZE;
+	rt_firmware		*pFirmware = priv->pFirmware;
+	u8				FwStatus = FW_STATUS_INIT;
+	PRT_8192S_FIRMWARE_HDR		pFwHdr = NULL;
+	PRT_8192S_FIRMWARE_PRIV		pFwPriv = NULL;
+	int 				rc;
+	const struct firmware 	*fw_entry;
+	u32				file_length = 0;
+
+	pFirmware->FWStatus = FW_STATUS_INIT;
+
+	RT_TRACE(COMP_FIRMWARE, " --->FirmwareDownload92S()\n");
+
+	//3//
+	//3 //<1> Open Image file, and map file to contineous memory if open file success.
+	//3  //        or read image file from array. Default load from BIN file
+	//3//
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+	priv->firmware_source = FW_SOURCE_HEADER_FILE;
+#else
+	priv->firmware_source = FW_SOURCE_IMG_FILE;// We should decided by Reg.
+#endif
+
+	switch( priv->firmware_source )
+	{
+		case FW_SOURCE_IMG_FILE:
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+			if(pFirmware->szFwTmpBufferLen == 0)
+			{
+
+				rc = request_firmware(&fw_entry, pFwImageFileName[ulInitStep],&priv->udev->dev);//===>1
+				if(rc < 0 ) {
+					RT_TRACE(COMP_ERR, "request firmware fail!\n");
+					goto DownloadFirmware_Fail;
+				}
+
+				if(fw_entry->size > sizeof(pFirmware->szFwTmpBuffer))
+				{
+					RT_TRACE(COMP_ERR, "img file size exceed the container buffer fail!\n");
+					release_firmware(fw_entry);
+					goto DownloadFirmware_Fail;
+				}
+
+				memcpy(pFirmware->szFwTmpBuffer,fw_entry->data,fw_entry->size);
+				pFirmware->szFwTmpBufferLen = fw_entry->size;
+				release_firmware(fw_entry);
+
+				pucMappedFile = pFirmware->szFwTmpBuffer;
+				file_length = pFirmware->szFwTmpBufferLen;
+
+				//Retrieve FW header.
+				pFirmware->pFwHeader = (PRT_8192S_FIRMWARE_HDR) pucMappedFile;
+				pFwHdr = pFirmware->pFwHeader;
+				RT_TRACE(COMP_FIRMWARE,"signature:%x, version:%x, size:%x, imemsize:%x, sram size:%x\n", \
+						pFwHdr->Signature, pFwHdr->Version, pFwHdr->DMEMSize, \
+						pFwHdr->IMG_IMEM_SIZE, pFwHdr->IMG_SRAM_SIZE);
+				pFirmware->FirmwareVersion =  byte(pFwHdr->Version ,0);
+				if ((pFwHdr->IMG_IMEM_SIZE==0) || (pFwHdr->IMG_IMEM_SIZE > sizeof(pFirmware->FwIMEM)))
+				{
+					RT_TRACE(COMP_ERR, "%s: memory for data image is less than IMEM required\n",\
+							__FUNCTION__);
+					goto DownloadFirmware_Fail;
+				} else {
+					pucMappedFile+=FwHdrSize;
+
+					//Retrieve IMEM image.
+					memcpy(pFirmware->FwIMEM, pucMappedFile, pFwHdr->IMG_IMEM_SIZE);
+					pFirmware->FwIMEMLen = pFwHdr->IMG_IMEM_SIZE;
+				}
+
+				if (pFwHdr->IMG_SRAM_SIZE > sizeof(pFirmware->FwEMEM))
+				{
+					RT_TRACE(COMP_ERR, "%s: memory for data image is less than EMEM required\n",\
+							__FUNCTION__);
+					goto DownloadFirmware_Fail;
+				} else {
+					pucMappedFile += pFirmware->FwIMEMLen;
+
+					/* Retriecve EMEM image */
+					memcpy(pFirmware->FwEMEM, pucMappedFile, pFwHdr->IMG_SRAM_SIZE);//===>6
+					pFirmware->FwEMEMLen = pFwHdr->IMG_SRAM_SIZE;
+				}
+
+
+			}
+#endif
+			break;
+
+		case FW_SOURCE_HEADER_FILE:
+#if 1
+#define Rtl819XFwImageArray Rtl8192SUFwImgArray
+			//2008.11.10 Add by tynli.
+			pucMappedFile = Rtl819XFwImageArray;
+			ulFileLength = ImgArrayLength;
+
+			RT_TRACE(COMP_INIT,"Fw download from header.\n");
+			/* Retrieve FW header*/
+			pFirmware->pFwHeader = (PRT_8192S_FIRMWARE_HDR) pucMappedFile;
+			pFwHdr = pFirmware->pFwHeader;
+			RT_TRACE(COMP_FIRMWARE,"signature:%x, version:%x, size:%x, imemsize:%x, sram size:%x\n", \
+					pFwHdr->Signature, pFwHdr->Version, pFwHdr->DMEMSize, \
+					pFwHdr->IMG_IMEM_SIZE, pFwHdr->IMG_SRAM_SIZE);
+			pFirmware->FirmwareVersion =  byte(pFwHdr->Version ,0);
+
+			if ((pFwHdr->IMG_IMEM_SIZE==0) || (pFwHdr->IMG_IMEM_SIZE > sizeof(pFirmware->FwIMEM)))
+			{
+				printk("FirmwareDownload92S(): memory for data image is less than IMEM required\n");
+				goto DownloadFirmware_Fail;
+			} else {
+				pucMappedFile+=FwHdrSize;
+				//Retrieve IMEM image.
+				memcpy(pFirmware->FwIMEM, pucMappedFile, pFwHdr->IMG_IMEM_SIZE);
+				pFirmware->FwIMEMLen = pFwHdr->IMG_IMEM_SIZE;
+			}
+
+			if (pFwHdr->IMG_SRAM_SIZE > sizeof(pFirmware->FwEMEM))
+			{
+				printk(" FirmwareDownload92S(): memory for data image is less than EMEM required\n");
+				goto DownloadFirmware_Fail;
+			} else {
+				pucMappedFile+= pFirmware->FwIMEMLen;
+
+				//Retriecve EMEM image.
+				memcpy(pFirmware->FwEMEM, pucMappedFile, pFwHdr->IMG_SRAM_SIZE);
+				pFirmware->FwEMEMLen = pFwHdr->IMG_SRAM_SIZE;
+			}
+#endif
+			break;
+		default:
+			break;
+	}
+
+	FwStatus = FirmwareGetNextStatus(pFirmware->FWStatus);
+	while(FwStatus!= FW_STATUS_READY)
+	{
+		// Image buffer redirection.
+		switch(FwStatus)
+		{
+			case FW_STATUS_LOAD_IMEM:
+				pucMappedFile = pFirmware->FwIMEM;
+				ulFileLength = pFirmware->FwIMEMLen;
+				break;
+
+			case FW_STATUS_LOAD_EMEM:
+				pucMappedFile = pFirmware->FwEMEM;
+				ulFileLength = pFirmware->FwEMEMLen;
+				break;
+
+			case FW_STATUS_LOAD_DMEM:
+				/* <Roger_Notes> Partial update the content of header private. 2008.12.18 */
+                                pFwHdr = pFirmware->pFwHeader;
+                                pFwPriv = (PRT_8192S_FIRMWARE_PRIV)&pFwHdr->FWPriv;
+				FirmwareHeaderPriveUpdate(dev, pFwPriv);
+				pucMappedFile = (u8*)(pFirmware->pFwHeader)+RT_8192S_FIRMWARE_HDR_EXCLUDE_PRI_SIZE;
+				ulFileLength = FwHdrSize-RT_8192S_FIRMWARE_HDR_EXCLUDE_PRI_SIZE;
+				break;
+
+			default:
+				RT_TRACE(COMP_ERR, "Unexpected Download step!!\n");
+				goto DownloadFirmware_Fail;
+				break;
+		}
+
+		//3//
+		//3// <2> Download image file
+	//3	//
+		rtStatus = FirmwareDownloadCode(dev, pucMappedFile, ulFileLength);
+
+		if(rtStatus != true)
+		{
+			RT_TRACE(COMP_ERR, "FirmwareDownloadCode() fail ! \n" );
+			goto DownloadFirmware_Fail;
+		}
+
+		//3//
+		//3// <3> Check whether load FW process is ready
+	//3	//
+		rtStatus = FirmwareCheckReady(dev, FwStatus);
+
+		if(rtStatus != true)
+		{
+			RT_TRACE(COMP_ERR, "FirmwareDownloadCode() fail ! \n");
+			goto DownloadFirmware_Fail;
+		}
+
+		FwStatus = FirmwareGetNextStatus(pFirmware->FWStatus);
+	}
+
+	RT_TRACE(COMP_FIRMWARE, "Firmware Download Success!!\n");
+	return rtStatus;
+
+	DownloadFirmware_Fail:
+	RT_TRACE(COMP_ERR, "Firmware Download Fail!!%x\n",read_nic_word(dev, TCR));
+	rtStatus = false;
+	return rtStatus;
+}
+#else
+void firmware_init_param(struct net_device *dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	rt_firmware		*pfirmware = priv->pFirmware;
+
+	pfirmware->cmdpacket_frag_thresold = GET_COMMAND_PACKET_FRAG_THRESHOLD(MAX_TRANSMIT_BUFFER_SIZE);
+}
+
+/*
+ * segment the img and use the ptr and length to remember info on each segment
+ *
+ */
+bool fw_download_code(struct net_device *dev, u8 *code_virtual_address, u32 buffer_len)
+{
+	struct r8192_priv   *priv = ieee80211_priv(dev);
+	bool 		    rt_status = true;
+	//u16		    frag_threshold;
+	u16		    frag_length, frag_offset = 0;
+	//u16		    total_size;
+	int		    i;
+
+	//rt_firmware	    *pfirmware = priv->pFirmware;
+	struct sk_buff	    *skb;
+	unsigned char	    *seg_ptr;
+	cb_desc		    *tcb_desc;
+	u8                  bLastIniPkt;
+#ifdef RTL8192SE
+	fw_SetRQPN(dev);	// For 92SE only
+#endif
+
+#ifndef RTL8192SU
+	if(buffer_len >= 64000-USB_HWDESC_HEADER_LEN)
+	{
+		return rt_status;
+	}
+	firmware_init_param(dev);
+	//Fragmentation might be required
+	frag_threshold = pfirmware->cmdpacket_frag_thresold;
+#endif
+
+	do {
+#ifndef RTL8192SU
+		if((buffer_len - frag_offset) > frag_threshold) {
+			frag_length = frag_threshold ;
+			bLastIniPkt = 0;
+
+		} else
+#endif
+		{
+			frag_length = buffer_len - frag_offset;
+			bLastIniPkt = 1;
+
+		}
+
+		/* Allocate skb buffer to contain firmware info and tx descriptor info
+		 * add 4 to avoid packet appending overflow.
+		 * */
+		#ifdef RTL8192U
+		skb  = dev_alloc_skb(USB_HWDESC_HEADER_LEN + frag_length + 4);
+		#else
+		skb  = dev_alloc_skb(frag_length + 4);
+		#endif
+		memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
+		tcb_desc = (cb_desc*)(skb->cb + MAX_DEV_ADDR_SIZE);
+		tcb_desc->queue_index = TXCMD_QUEUE;
+		tcb_desc->bCmdOrInit = DESC_PACKET_TYPE_INIT;
+		tcb_desc->bLastIniPkt = bLastIniPkt;
+
+		#ifdef RTL8192U
+		skb_reserve(skb, USB_HWDESC_HEADER_LEN);
+		#endif
+		seg_ptr = skb->data;
+		/*
+		 * Transform from little endian to big endian
+                 * and pending  zero
+		 */
+		for(i=0 ; i < frag_length; i+=4) {
+			*seg_ptr++ = ((i+0)<frag_length)?code_virtual_address[i+3]:0;
+			*seg_ptr++ = ((i+1)<frag_length)?code_virtual_address[i+2]:0;
+			*seg_ptr++ = ((i+2)<frag_length)?code_virtual_address[i+1]:0;
+			*seg_ptr++ = ((i+3)<frag_length)?code_virtual_address[i+0]:0;
+		}
+		tcb_desc->txbuf_size= (u16)i;
+		skb_put(skb, i);
+
+		if(!priv->ieee80211->check_nic_enough_desc(dev,tcb_desc->queue_index)||
+			(!skb_queue_empty(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index]))||\
+			(priv->ieee80211->queue_stop) ) {
+			RT_TRACE(COMP_FIRMWARE,"=====================================================> tx full!\n");
+			skb_queue_tail(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index], skb);
+		} else {
+			priv->ieee80211->softmac_hard_start_xmit(skb,dev);
+		}
+
+		code_virtual_address += frag_length;
+		frag_offset += frag_length;
+
+	}while(frag_offset < buffer_len);
+
+	return rt_status;
+
+#if 0
+cmdsend_downloadcode_fail:
+	rt_status = false;
+	RT_TRACE(COMP_ERR, "CmdSendDownloadCode fail !!\n");
+	return rt_status;
+#endif
+}
+
+bool
+fwSendNullPacket(
+	struct net_device *dev,
+	u32			Length
+)
+{
+	bool	rtStatus = true;
+	struct r8192_priv   *priv = ieee80211_priv(dev);
+	struct sk_buff	    *skb;
+	cb_desc		    *tcb_desc;
+	unsigned char	    *ptr_buf;
+	bool	bLastInitPacket = false;
+
+	//PlatformAcquireSpinLock(dev, RT_TX_SPINLOCK);
+
+	//Get TCB and local buffer from common pool. (It is shared by CmdQ, MgntQ, and USB coalesce DataQ)
+	skb  = dev_alloc_skb(Length+ 4);
+	memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
+	tcb_desc = (cb_desc*)(skb->cb + MAX_DEV_ADDR_SIZE);
+	tcb_desc->queue_index = TXCMD_QUEUE;
+	tcb_desc->bCmdOrInit = DESC_PACKET_TYPE_INIT;
+	tcb_desc->bLastIniPkt = bLastInitPacket;
+	ptr_buf = skb_put(skb, Length);
+	memset(ptr_buf,0,Length);
+	tcb_desc->txbuf_size= (u16)Length;
+
+	if(!priv->ieee80211->check_nic_enough_desc(dev,tcb_desc->queue_index)||
+			(!skb_queue_empty(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index]))||\
+			(priv->ieee80211->queue_stop) ) {
+			RT_TRACE(COMP_FIRMWARE,"===================NULL packet==================================> tx full!\n");
+			skb_queue_tail(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index], skb);
+		} else {
+			priv->ieee80211->softmac_hard_start_xmit(skb,dev);
+		}
+
+	//PlatformReleaseSpinLock(dev, RT_TX_SPINLOCK);
+	return rtStatus;
+}
+
+//-----------------------------------------------------------------------------
+// Procedure:    Check whether main code is download OK. If OK, turn on CPU
+//
+// Description:   CPU register locates in different page against general register.
+//			    Switch to CPU register in the begin and switch back before return
+//
+//
+// Arguments:   The pointer of the dev
+//
+// Returns:
+//        NDIS_STATUS_FAILURE - the following initialization process should be terminated
+//        NDIS_STATUS_SUCCESS - if firmware initialization process success
+//-----------------------------------------------------------------------------
+bool CPUcheck_maincodeok_turnonCPU(struct net_device *dev)
+{
+	bool		rt_status = true;
+	int		check_putcodeOK_time = 200000, check_bootOk_time = 200000;
+	u32	 	CPU_status = 0;
+
+	/* Check whether put code OK */
+	do {
+		CPU_status = read_nic_dword(dev, CPU_GEN);
+
+		if(CPU_status&CPU_GEN_PUT_CODE_OK)
+			break;
+
+	}while(check_putcodeOK_time--);
+
+	if(!(CPU_status&CPU_GEN_PUT_CODE_OK)) {
+		RT_TRACE(COMP_ERR, "Download Firmware: Put code fail!\n");
+		goto CPUCheckMainCodeOKAndTurnOnCPU_Fail;
+	} else {
+		RT_TRACE(COMP_FIRMWARE, "Download Firmware: Put code ok!\n");
+	}
+
+	/* Turn On CPU */
+	CPU_status = read_nic_dword(dev, CPU_GEN);
+	write_nic_byte(dev, CPU_GEN, (u8)((CPU_status|CPU_GEN_PWR_STB_CPU)&0xff));
+	mdelay(1000);
+
+	/* Check whether CPU boot OK */
+	do {
+		CPU_status = read_nic_dword(dev, CPU_GEN);
+
+		if(CPU_status&CPU_GEN_BOOT_RDY)
+			break;
+	}while(check_bootOk_time--);
+
+	if(!(CPU_status&CPU_GEN_BOOT_RDY)) {
+		goto CPUCheckMainCodeOKAndTurnOnCPU_Fail;
+	} else {
+		RT_TRACE(COMP_FIRMWARE, "Download Firmware: Boot ready!\n");
+	}
+
+	return rt_status;
+
+CPUCheckMainCodeOKAndTurnOnCPU_Fail:
+	RT_TRACE(COMP_ERR, "ERR in %s()\n", __FUNCTION__);
+	rt_status = FALSE;
+	return rt_status;
+}
+
+bool CPUcheck_firmware_ready(struct net_device *dev)
+{
+
+	bool		rt_status = true;
+	int		check_time = 200000;
+	u32		CPU_status = 0;
+
+	/* Check Firmware Ready */
+	do {
+		CPU_status = read_nic_dword(dev, CPU_GEN);
+
+		if(CPU_status&CPU_GEN_FIRM_RDY)
+			break;
+
+	}while(check_time--);
+
+	if(!(CPU_status&CPU_GEN_FIRM_RDY))
+		goto CPUCheckFirmwareReady_Fail;
+	else
+		RT_TRACE(COMP_FIRMWARE, "Download Firmware: Firmware ready!\n");
+
+	return rt_status;
+
+CPUCheckFirmwareReady_Fail:
+	RT_TRACE(COMP_ERR, "ERR in %s()\n", __FUNCTION__);
+	rt_status = false;
+	return rt_status;
+
+}
+
+bool init_firmware(struct net_device *dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	bool			rt_status = TRUE;
+
+	u8			*firmware_img_buf[3] = { &rtl8190_fwboot_array[0],
+						   	 &rtl8190_fwmain_array[0],
+						   	 &rtl8190_fwdata_array[0]};
+
+	u32			firmware_img_len[3] = { sizeof(rtl8190_fwboot_array),
+						   	sizeof(rtl8190_fwmain_array),
+						   	sizeof(rtl8190_fwdata_array)};
+	u32			file_length = 0;
+	u8			*mapped_file = NULL;
+	u32			init_step = 0;
+	opt_rst_type_e	rst_opt = OPT_SYSTEM_RESET;
+	firmware_init_step_e 	starting_state = FW_INIT_STEP0_BOOT;
+
+	rt_firmware		*pfirmware = priv->pFirmware;
+	const struct firmware 	*fw_entry;
+	const char *fw_name[3] = { "RTL8192U/boot.img",
+                           "RTL8192U/main.img",
+			   "RTL8192U/data.img"};
+	int rc;
+
+	RT_TRACE(COMP_FIRMWARE, " PlatformInitFirmware()==>\n");
+
+	if (pfirmware->firmware_status == FW_STATUS_0_INIT ) {
+		/* it is called by reset */
+		rst_opt = OPT_SYSTEM_RESET;
+		starting_state = FW_INIT_STEP0_BOOT;
+		// TODO: system reset
+
+	}else if(pfirmware->firmware_status == FW_STATUS_5_READY) {
+		/* it is called by Initialize */
+		rst_opt = OPT_FIRMWARE_RESET;
+		starting_state = FW_INIT_STEP2_DATA;
+	}else {
+		 RT_TRACE(COMP_FIRMWARE, "PlatformInitFirmware: undefined firmware state\n");
+	}
+
+	/*
+	 * Download boot, main, and data image for System reset.
+	 * Download data image for firmware reseta
+	 */
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+	priv->firmware_source = FW_SOURCE_HEADER_FILE;
+#else
+	priv->firmware_source = FW_SOURCE_IMG_FILE;
+#endif
+	for(init_step = starting_state; init_step <= FW_INIT_STEP2_DATA; init_step++) {
+		/*
+		 * Open Image file, and map file to contineous memory if open file success.
+		 * or read image file from array. Default load from IMG file
+		 */
+		if(rst_opt == OPT_SYSTEM_RESET) {
+			switch(priv->firmware_source) {
+				case FW_SOURCE_IMG_FILE:
+				#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+					rc = request_firmware(&fw_entry, fw_name[init_step],&priv->udev->dev);
+					if(rc < 0 ) {
+						RT_TRACE(COMP_ERR, "request firmware fail!\n");
+						goto download_firmware_fail;
+					}
+
+					if(fw_entry->size > sizeof(pfirmware->firmware_buf)) {
+						RT_TRACE(COMP_ERR, "img file size exceed the container buffer fail!\n");
+						goto download_firmware_fail;
+					}
+
+					if(init_step != FW_INIT_STEP1_MAIN) {
+						memcpy(pfirmware->firmware_buf,fw_entry->data,fw_entry->size);
+						mapped_file = pfirmware->firmware_buf;
+						file_length = fw_entry->size;
+					} else {
+					#ifdef RTL8190P
+						memcpy(pfirmware->firmware_buf,fw_entry->data,fw_entry->size);
+						mapped_file = pfirmware->firmware_buf;
+						file_length = fw_entry->size;
+					#else
+						memset(pfirmware->firmware_buf,0,128);
+						memcpy(&pfirmware->firmware_buf[128],fw_entry->data,fw_entry->size);
+						mapped_file = pfirmware->firmware_buf;
+						file_length = fw_entry->size + 128;
+					#endif
+					}
+					pfirmware->firmware_buf_size = file_length;
+					#endif
+					break;
+
+				case FW_SOURCE_HEADER_FILE:
+					mapped_file =  firmware_img_buf[init_step];
+					file_length  = firmware_img_len[init_step];
+					if(init_step == FW_INIT_STEP2_DATA) {
+						memcpy(pfirmware->firmware_buf, mapped_file, file_length);
+						pfirmware->firmware_buf_size = file_length;
+					}
+					break;
+
+				default:
+					break;
+			}
+
+
+		}else if(rst_opt == OPT_FIRMWARE_RESET ) {
+			/* we only need to download data.img here */
+			mapped_file = pfirmware->firmware_buf;
+			file_length = pfirmware->firmware_buf_size;
+		}
+
+		/* Download image file */
+		/* The firmware download process is just as following,
+		 * 1. that is each packet will be segmented and inserted to the wait queue.
+		 * 2. each packet segment will be put in the skb_buff packet.
+		 * 3. each skb_buff packet data content will already include the firmware info
+		 *   and Tx descriptor info
+		 * */
+		rt_status = fw_download_code(dev,mapped_file,file_length);
+		#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+		if(rst_opt == OPT_SYSTEM_RESET) {
+			release_firmware(fw_entry);
+		}
+		#endif
+
+		if(rt_status != TRUE) {
+			goto download_firmware_fail;
+		}
+
+		switch(init_step) {
+			case FW_INIT_STEP0_BOOT:
+				/* Download boot
+				 * initialize command descriptor.
+				 * will set polling bit when firmware code is also configured
+				 */
+				pfirmware->firmware_status = FW_STATUS_1_MOVE_BOOT_CODE;
+#ifdef RTL8190P
+				// To initialize IMEM, CPU move code  from 0x80000080, hence, we send 0x80 byte packet
+				rt_status = fwSendNullPacket(dev, RTL8190_CPU_START_OFFSET);
+				if(rt_status != true)
+				{
+					RT_TRACE(COMP_INIT, "fwSendNullPacket() fail ! \n");
+					goto  download_firmware_fail;
+				}
+#endif
+				//mdelay(1000);
+				/*
+				 * To initialize IMEM, CPU move code  from 0x80000080,
+				 * hence, we send 0x80 byte packet
+				 */
+				break;
+
+			case FW_INIT_STEP1_MAIN:
+				/* Download firmware code. Wait until Boot Ready and Turn on CPU */
+				pfirmware->firmware_status = FW_STATUS_2_MOVE_MAIN_CODE;
+
+				/* Check Put Code OK and Turn On CPU */
+				rt_status = CPUcheck_maincodeok_turnonCPU(dev);
+				if(rt_status != TRUE) {
+					RT_TRACE(COMP_ERR, "CPUcheck_maincodeok_turnonCPU fail!\n");
+					goto download_firmware_fail;
+				}
+
+				pfirmware->firmware_status = FW_STATUS_3_TURNON_CPU;
+				break;
+
+			case FW_INIT_STEP2_DATA:
+				/* download initial data code */
+				pfirmware->firmware_status = FW_STATUS_4_MOVE_DATA_CODE;
+				mdelay(1);
+
+				rt_status = CPUcheck_firmware_ready(dev);
+				if(rt_status != TRUE) {
+					RT_TRACE(COMP_ERR, "CPUcheck_firmware_ready fail(%d)!\n",rt_status);
+					goto download_firmware_fail;
+				}
+
+				/* wait until data code is initialized ready.*/
+				pfirmware->firmware_status = FW_STATUS_5_READY;
+				break;
+		}
+	}
+
+	RT_TRACE(COMP_FIRMWARE, "Firmware Download Success\n");
+	//assert(pfirmware->firmware_status == FW_STATUS_5_READY, ("Firmware Download Fail\n"));
+
+	return rt_status;
+
+download_firmware_fail:
+	RT_TRACE(COMP_ERR, "ERR in %s()\n", __FUNCTION__);
+	rt_status = FALSE;
+	return rt_status;
+
+}
+#endif
+
diff --git a/drivers/staging/rtl8192su/r8192S_firmware.h b/drivers/staging/rtl8192su/r8192S_firmware.h
new file mode 100644
index 0000000..047f8ae
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_firmware.h
@@ -0,0 +1,212 @@
+#ifndef __INC_FIRMWARE_H
+#define __INC_FIRMWARE_H
+
+
+//#define RTL8190_CPU_START_OFFSET	0x80
+/* TODO: this definition is TBD */
+//#define USB_HWDESC_HEADER_LEN	0
+
+/* It should be double word alignment */
+//#if DEV_BUS_TYPE==PCI_INTERFACE
+//#define GET_COMMAND_PACKET_FRAG_THRESHOLD(v)	4*(v/4) - 8
+//#else
+//#define GET_COMMAND_PACKET_FRAG_THRESHOLD(v)	(4*(v/4) - 8 - USB_HWDESC_HEADER_LEN)
+//#endif
+
+//typedef enum _firmware_init_step{
+//	FW_INIT_STEP0_BOOT = 0,
+//	FW_INIT_STEP1_MAIN = 1,
+//	FW_INIT_STEP2_DATA = 2,
+//}firmware_init_step_e;
+
+//typedef enum _DESC_PACKET_TYPE{
+//	DESC_PACKET_TYPE_INIT = 0,
+//	DESC_PACKET_TYPE_NORMAL = 1,
+//}DESC_PACKET_TYPE;
+#define	RTL8192S_FW_PKT_FRAG_SIZE		0xFF00	// 64K
+
+
+#define 	RTL8190_MAX_FIRMWARE_CODE_SIZE	64000	//64k
+#define	MAX_FIRMWARE_CODE_SIZE	0xFF00 // Firmware Local buffer size.
+#define 	RTL8190_CPU_START_OFFSET			0x80
+
+#ifdef RTL8192SE
+//It should be double word alignment
+#define GET_COMMAND_PACKET_FRAG_THRESHOLD(v)	4*(v/4) - 8
+#else
+#define GET_COMMAND_PACKET_FRAG_THRESHOLD(v)	(4*(v/4) - 8 - USB_HWDESC_HEADER_LEN)
+#endif
+
+//typedef enum _DESC_PACKET_TYPE{
+//	DESC_PACKET_TYPE_INIT = 0,
+//	DESC_PACKET_TYPE_NORMAL = 1,
+//}DESC_PACKET_TYPE;
+
+// Forward declaration.
+//typedef	struct _ADAPTER	ADAPTER, *PADAPTER;
+#ifdef RTL8192S
+typedef enum _firmware_init_step{
+	FW_INIT_STEP0_IMEM = 0,
+	FW_INIT_STEP1_MAIN = 1,
+	FW_INIT_STEP2_DATA = 2,
+}firmware_init_step_e;
+#else
+typedef enum _firmware_init_step{
+	FW_INIT_STEP0_BOOT = 0,
+	FW_INIT_STEP1_MAIN = 1,
+	FW_INIT_STEP2_DATA = 2,
+}firmware_init_step_e;
+#endif
+
+/* due to rtl8192 firmware */
+typedef enum _desc_packet_type_e{
+	DESC_PACKET_TYPE_INIT = 0,
+	DESC_PACKET_TYPE_NORMAL = 1,
+}desc_packet_type_e;
+
+typedef enum _firmware_source{
+	FW_SOURCE_IMG_FILE = 0,
+	FW_SOURCE_HEADER_FILE = 1,
+}firmware_source_e, *pfirmware_source_e;
+
+
+typedef enum _opt_rst_type{
+	OPT_SYSTEM_RESET = 0,
+	OPT_FIRMWARE_RESET = 1,
+}opt_rst_type_e;
+
+/*typedef enum _FIRMWARE_STATUS{
+	FW_STATUS_0_INIT = 0,
+	FW_STATUS_1_MOVE_BOOT_CODE = 1,
+	FW_STATUS_2_MOVE_MAIN_CODE = 2,
+	FW_STATUS_3_TURNON_CPU = 3,
+	FW_STATUS_4_MOVE_DATA_CODE = 4,
+	FW_STATUS_5_READY = 5,
+}FIRMWARE_STATUS;
+*/
+//--------------------------------------------------------------------------------
+// RTL8192S Firmware related, Revised by Roger, 2008.12.18.
+//--------------------------------------------------------------------------------
+typedef  struct _RT_8192S_FIRMWARE_PRIV { //8-bytes alignment required
+
+	//--- long word 0 ----
+	u8		signature_0;		//0x12: CE product, 0x92: IT product
+	u8		signature_1;		//0x87: CE product, 0x81: IT product
+	u8		hci_sel;			//0x81: PCI-AP, 01:PCIe, 02: 92S-U, 0x82: USB-AP, 0x12: 72S-U, 03:SDIO
+	u8		chip_version;	//the same value as reigster value
+	u8		customer_ID_0;	//customer  ID low byte
+	u8		customer_ID_1;	//customer  ID high byte
+	u8		rf_config;		//0x11:  1T1R, 0x12: 1T2R, 0x92: 1T2R turbo, 0x22: 2T2R
+	u8		usb_ep_num;	// 4: 4EP, 6: 6EP, 11: 11EP
+
+	//--- long word 1 ----
+	u8		regulatory_class_0;	//regulatory class bit map 0
+	u8		regulatory_class_1;	//regulatory class bit map 1
+	u8		regulatory_class_2;	//regulatory class bit map 2
+	u8		regulatory_class_3;	//regulatory class bit map 3
+	u8		rfintfs;				// 0:SWSI, 1:HWSI, 2:HWPI
+	u8		def_nettype;
+	u8		rsvd010;
+	u8		rsvd011;
+
+
+	//--- long word 2 ----
+	u8		lbk_mode;	//0x00: normal, 0x03: MACLBK, 0x01: PHYLBK
+	u8		mp_mode;	// 1: for MP use, 0: for normal driver (to be discussed)
+	u8		rsvd020;
+	u8		rsvd021;
+	u8		rsvd022;
+	u8		rsvd023;
+	u8		rsvd024;
+	u8		rsvd025;
+
+	//--- long word 3 ----
+	u8		qos_en;				// QoS enable
+	u8		bw_40MHz_en;		// 40MHz BW enable
+	u8		AMSDU2AMPDU_en;	// 4181 convert AMSDU to AMPDU, 0: disable
+	u8		AMPDU_en;			// 11n AMPDU enable
+	u8		rate_control_offload;//FW offloads, 0: driver handles
+	u8		aggregation_offload;	// FW offloads, 0: driver handles
+	u8		rsvd030;
+	u8		rsvd031;
+
+
+	//--- long word 4 ----
+	unsigned char		beacon_offload;			// 1. FW offloads, 0: driver handles
+	unsigned char		MLME_offload;			// 2. FW offloads, 0: driver handles
+	unsigned char		hwpc_offload;			// 3. FW offloads, 0: driver handles
+	unsigned char		tcp_checksum_offload;	// 4. FW offloads, 0: driver handles
+	unsigned char		tcp_offload;				// 5. FW offloads, 0: driver handles
+	unsigned char		ps_control_offload;		// 6. FW offloads, 0: driver handles
+	unsigned char		WWLAN_offload;			// 7. FW offloads, 0: driver handles
+	unsigned char		rsvd040;
+
+	//--- long word 5 ----
+	u8		tcp_tx_frame_len_L;		//tcp tx packet length low byte
+	u8		tcp_tx_frame_len_H;		//tcp tx packet length high byte
+	u8		tcp_rx_frame_len_L;		//tcp rx packet length low byte
+	u8		tcp_rx_frame_len_H;		//tcp rx packet length high byte
+	u8		rsvd050;
+	u8		rsvd051;
+	u8		rsvd052;
+	u8		rsvd053;
+}RT_8192S_FIRMWARE_PRIV, *PRT_8192S_FIRMWARE_PRIV;
+
+typedef struct _RT_8192S_FIRMWARE_HDR {//8-byte alinment required
+
+	//--- LONG WORD 0 ----
+	u16		Signature;
+	u16		Version;		  //0x8000 ~ 0x8FFF for FPGA version, 0x0000 ~ 0x7FFF for ASIC version,
+	u32		DMEMSize;    //define the size of boot loader
+
+
+	//--- LONG WORD 1 ----
+	u32		IMG_IMEM_SIZE;    //define the size of FW in IMEM
+	u32		IMG_SRAM_SIZE;    //define the size of FW in SRAM
+
+	//--- LONG WORD 2 ----
+	u32		FW_PRIV_SIZE;       //define the size of DMEM variable
+	u32		Rsvd0;
+
+	//--- LONG WORD 3 ----
+	u32		Rsvd1;
+	u32		Rsvd2;
+
+	RT_8192S_FIRMWARE_PRIV	FWPriv;
+
+}RT_8192S_FIRMWARE_HDR, *PRT_8192S_FIRMWARE_HDR;
+
+#define	RT_8192S_FIRMWARE_HDR_SIZE	80
+#define   RT_8192S_FIRMWARE_HDR_EXCLUDE_PRI_SIZE	32
+
+typedef enum _FIRMWARE_8192S_STATUS{
+	FW_STATUS_INIT = 0,
+	FW_STATUS_LOAD_IMEM = 1,
+	FW_STATUS_LOAD_EMEM = 2,
+	FW_STATUS_LOAD_DMEM = 3,
+	FW_STATUS_READY = 4,
+}FIRMWARE_8192S_STATUS;
+
+#define RTL8190_MAX_FIRMWARE_CODE_SIZE  64000   //64k
+
+typedef struct _rt_firmware{
+	firmware_source_e	eFWSource;
+	PRT_8192S_FIRMWARE_HDR	pFwHeader;
+	FIRMWARE_8192S_STATUS	FWStatus;
+	u16             FirmwareVersion;
+	u8		FwIMEM[RTL8190_MAX_FIRMWARE_CODE_SIZE];
+	u8		FwEMEM[RTL8190_MAX_FIRMWARE_CODE_SIZE];
+	u32		FwIMEMLen;
+	u32		FwEMEMLen;
+	u8		szFwTmpBuffer[164000];
+        u32             szFwTmpBufferLen;
+	u16		CmdPacketFragThresold;
+}rt_firmware, *prt_firmware;
+
+//typedef struct _RT_FIRMWARE_INFO_8192SU{
+//	u8		szInfo[16];
+//}RT_FIRMWARE_INFO_8192SU, *PRT_FIRMWARE_INFO_8192SU;
+bool FirmwareDownload92S(struct net_device *dev);
+
+#endif
+
diff --git a/drivers/staging/rtl8192su/r8192S_hw.h b/drivers/staging/rtl8192su/r8192S_hw.h
new file mode 100644
index 0000000..7a3d850
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_hw.h
@@ -0,0 +1,1677 @@
+/*****************************************************************************
+ *	Copyright(c) 2008,  RealTEK Technology Inc. All Right Reserved.
+ *
+ * Module:	__INC_HAL8192SEREG_H
+ *
+ *
+ * Note:	1. Define Mac register address and corresponding bit mask map
+ *			2. CCX register
+ *			3. Backward compatible register with useless address.
+ *			4. Define 92SU required register address and definition.
+ *
+ *
+ * Export:	Constants, macro, functions(API), global variables(None).
+ *
+ * Abbrev:
+ *
+ * History:
+ *		Data		Who		Remark
+ *      08/07/2007  MHC    	1. Porting from 9x series PHYCFG.h.
+ *							2. Reorganize code architecture.
+ *
+ *****************************************************************************/
+#ifndef R8192S_HW
+#define R8192S_HW
+
+typedef enum _VERSION_8192S{
+	VERSION_8192S_ACUT,
+	VERSION_8192S_BCUT,
+	VERSION_8192S_CCUT
+}VERSION_8192S,*PVERSION_8192S;
+
+//#ifdef RTL8192SU
+typedef enum _VERSION_8192SUsb{
+	VERSION_8192SU_A, //A-Cut
+	VERSION_8192SU_B, //B-Cut
+	VERSION_8192SU_C, //C-Cut
+}VERSION_8192SUsb, *PVERSION_8192SUsb;
+//#else
+typedef enum _VERSION_819xU{
+	VERSION_819xU_A, // A-cut
+	VERSION_819xU_B, // B-cut
+	VERSION_819xU_C,// C-cut
+}VERSION_819xU,*PVERSION_819xU;
+//#endif
+
+/* 2007/11/15 MH Define different RF type. */
+typedef	enum _RT_RF_TYPE_DEFINITION
+{
+	RF_1T2R = 0,
+	RF_2T4R,
+	RF_2T2R,
+#ifdef RTL8192SU
+	RF_1T1R,
+	RF_2T2R_GREEN,
+#endif
+	//RF_3T3R,
+	//RF_3T4R,
+	//RF_4T4R,
+	RF_819X_MAX_TYPE
+}RT_RF_TYPE_DEF_E;
+
+typedef enum _BaseBand_Config_Type{
+	BaseBand_Config_PHY_REG = 0,			//Radio Path A
+	BaseBand_Config_AGC_TAB = 1,			//Radio Path B
+}BaseBand_Config_Type, *PBaseBand_Config_Type;
+
+#if 0
+typedef enum _RT_RF_TYPE_819xU{
+	RF_TYPE_MIN = 0,
+	RF_8225,
+	RF_8256,
+	RF_8258,
+	RF_PSEUDO_11N = 4,
+}RT_RF_TYPE_819xU, *PRT_RF_TYPE_819xU;
+#endif
+
+#define	RTL8187_REQT_READ		0xc0
+#define	RTL8187_REQT_WRITE	0x40
+#define	RTL8187_REQ_GET_REGS	0x05
+#define	RTL8187_REQ_SET_REGS	0x05
+
+#define MAX_TX_URB 5
+#define MAX_RX_URB 16
+
+#define R8180_MAX_RETRY 255
+//#define MAX_RX_NORMAL_URB 3
+//#define MAX_RX_COMMAND_URB 2
+#define RX_URB_SIZE 		9100
+
+#define BB_ANTATTEN_CHAN14	0x0c
+#define BB_ANTENNA_B 		0x40
+
+#define BB_HOST_BANG 		(1<<30)
+#define BB_HOST_BANG_EN 	(1<<2)
+#define BB_HOST_BANG_CLK 	(1<<1)
+#define BB_HOST_BANG_RW 	(1<<3)
+#define BB_HOST_BANG_DATA	1
+
+
+//============================================================
+//       8192S Regsiter bit
+//============================================================
+#define	BB_GLOBAL_RESET_BIT	0x1
+
+#define CR_RST			0x10
+#define CR_RE			0x08
+#define CR_TE			0x04
+#define CR_MulRW			0x01
+
+#define MAC_FILTER_MASK ((1<<0) | (1<<1) | (1<<2) | (1<<3) | (1<<5) | \
+		(1<<12) | (1<<18) | (1<<19) | (1<<20) | (1<<21) | (1<<22) | (1<<23))
+
+#define RX_FIFO_THRESHOLD_MASK 	((1<<13) | (1<<14) | (1<<15))
+#define RX_FIFO_THRESHOLD_SHIFT 	13
+#define RX_FIFO_THRESHOLD_128 		3
+#define RX_FIFO_THRESHOLD_256 		4
+#define RX_FIFO_THRESHOLD_512 		5
+#define RX_FIFO_THRESHOLD_1024 		6
+#define RX_FIFO_THRESHOLD_NONE 	7
+
+#define MAX_RX_DMA_MASK ((1<<8) | (1<<9) | (1<<10))
+
+//----------------------------------------------------------------------------
+//       8190 CPU General Register		(offset 0x100, 4 byte)
+//----------------------------------------------------------------------------
+#define	CPU_CCK_LOOPBACK			0x00030000
+#define	CPU_GEN_SYSTEM_RESET		0x00000001
+#define	CPU_GEN_FIRMWARE_RESET	0x00000008
+#define	CPU_GEN_BOOT_RDY			0x00000010
+#define	CPU_GEN_FIRM_RDY			0x00000020
+#define	CPU_GEN_PUT_CODE_OK		0x00000080
+#define	CPU_GEN_BB_RST				0x00000100
+#define	CPU_GEN_PWR_STB_CPU		0x00000004
+#define 	CPU_GEN_NO_LOOPBACK_MSK	0xFFF8FFFF // Set bit18,17,16 to 0. Set bit19
+#define	CPU_GEN_NO_LOOPBACK_SET	0x00080000 // Set BIT19 to 1
+//----------------------------------------------------------------------------
+////
+////       8190 AcmHwCtrl bits                                    (offset 0x171, 1 byte)
+////----------------------------------------------------------------------------
+#define MSR_LINK_MASK      	((1<<0)|(1<<1))
+#define MSR_LINK_MANAGED   	2
+#define MSR_LINK_NONE      	0
+#define MSR_LINK_SHIFT     	0
+#define MSR_LINK_ADHOC     	1
+#define MSR_LINK_MASTER    	3
+#define MSR_LINK_ENEDCA	   	(1<<4)
+
+
+//#define Cmd9346CR_9356SEL	(1<<4)
+#define EPROM_CMD_RESERVED_MASK 			(1<<5)
+#define EPROM_CMD_OPERATING_MODE_SHIFT 	6
+#define EPROM_CMD_OPERATING_MODE_MASK 	((1<<7)|(1<<6))
+#define EPROM_CMD_CONFIG 		0x3
+#define EPROM_CMD_NORMAL 		0
+#define EPROM_CMD_LOAD 			1
+#define EPROM_CMD_PROGRAM		2
+#define EPROM_CS_SHIFT 			3
+#define EPROM_CK_SHIFT 			2
+#define EPROM_W_SHIFT 			1
+#define EPROM_R_SHIFT 			0
+
+//#define	MAC0 			 0x000,
+//#define	MAC1 			 0x001,
+//#define	MAC2 			 0x002,
+//#define	MAC3 			 0x003,
+//#define	MAC4 			 0x004,
+//#define	MAC5 			 0x005,
+
+//============================================================
+//       8192S Regsiter offset definition
+//============================================================
+
+//
+// MAC register 0x0 - 0x5xx
+// 1. System configuration registers.
+// 2. Command Control Registers
+// 3. MACID Setting Registers
+// 4. Timing Control Registers
+// 5. FIFO Control Registers
+// 6. Adaptive Control Registers
+// 7. EDCA Setting Registers
+// 8. WMAC, BA and CCX related Register.
+// 9. Security Control Registers
+// 10. Power Save Control Registers
+// 11. General Purpose Registers
+// 12. Host Interrupt Status Registers
+// 13. Test Mode and Debug Control Registers
+// 14. PCIE config register
+//
+
+
+//
+// 1. System Configuration Registers	 (Offset: 0x0000 - 0x003F)
+//
+#define		SYS_ISO_CTRL		0x0000	// System Isolation Interface Control.
+#define		SYS_FUNC_EN		0x0002	// System Function Enable.
+#define		PMC_FSM			0x0004	// Power Sequence Control.
+#define		SYS_CLKR			0x0008	// System Clock.
+#define		EPROM_CMD			0x000A	// 93C46/93C56 Command Register. (win CR93C46)
+#define		EE_VPD				0x000C	// EEPROM VPD Data.
+#define		AFE_MISC			0x0010	// AFE Misc.
+#define		SPS0_CTRL			0x0011	// Switching Power Supply 0 Control.
+#define		SPS1_CTRL			0x0018	// Switching Power Supply 1 Control.
+#define		RF_CTRL				0x001F	// RF Block Control.
+#define		LDOA15_CTRL		0x0020	// V15 Digital LDO Control.
+#define		LDOV12D_CTRL		0x0021	// V12 Digital LDO Control.
+#define		LDOHCI12_CTRL		0x0022	// V12 Digital LDO Control.
+#define		LDO_USB_SDIO		0x0023	// LDO USB Control.
+#define		LPLDO_CTRL			0x0024	// Low Power LDO Control.
+#define		AFE_XTAL_CTRL		0x0026	// AFE Crystal Control.
+#define		AFE_PLL_CTRL		0x0028	// System Function Enable.
+#define		EFUSE_CTRL			0x0030	// E-Fuse Control.
+#define		EFUSE_TEST			0x0034	// E-Fuse Test.
+#define		PWR_DATA			0x0038	// Power on date.
+#define		DBG_PORT			0x003A	// MAC debug port select
+#define		DPS_TIMER			0x003C	// Deep Power Save Timer Register.
+#define		RCLK_MON			0x003E	// Retention Clock Monitor.
+
+//
+// 2. Command Control Registers	 (Offset: 0x0040 - 0x004F)
+//
+#define		CMDR				0x0040	// MAC Command Register.
+#define		TXPAUSE				0x0042	// Transmission Pause Register.
+#define		LBKMD_SEL			0x0043	// Loopback Mode Select Register.
+#define		TCR					0x0044	// Transmit Configuration Register
+#define		RCR					0x0048	// Receive Configuration Register
+#define		MSR					0x004C	// Media Status register
+#define		SYSF_CFG			0x004D	// System Function Configuration.
+#define		RX_PKY_LIMIT		0x004E	// RX packet length limit
+#define		MBIDCTRL			0x004F	// MBSSID Control.
+
+//
+// 3. MACID Setting Registers	(Offset: 0x0050 - 0x007F)
+//
+#define		MACIDR				0x0050	// MAC ID Register, Offset 0x0050-0x0055
+#define		MACIDR0				0x0050	// MAC ID Register, Offset 0x0050-0x0053
+#define		MACIDR4				0x0054	// MAC ID Register, Offset 0x0054-0x0055
+#define		BSSIDR				0x0058	// BSSID Register, Offset 0x0058-0x005D
+#define		HWVID				0x005E	// HW Version ID.
+#define		MAR					0x0060	// Multicase Address.
+#define		MBIDCAMCONTENT	0x0068	// MBSSID CAM Content.
+#define		MBIDCAMCFG			0x0070	// MBSSID CAM Configuration.
+#define		BUILDTIME			0x0074	// Build Time Register.
+#define		BUILDUSER			0x0078	// Build User Register.
+
+// Redifine MACID register, to compatible prior ICs.
+#define		IDR0				MACIDR0
+#define		IDR4				MACIDR4
+
+//
+// 4. Timing Control Registers	(Offset: 0x0080 - 0x009F)
+//
+#define		TSFR				0x0080	// Timing Sync Function Timer Register.
+#define		SLOT_TIME			0x0089	// Slot Time Register, in us.
+#define		USTIME				0x008A	// EDCA/TSF clock unit time us unit.
+#define		SIFS_CCK			0x008C	// SIFS for CCK, in us.
+#define		SIFS_OFDM			0x008E	// SIFS for OFDM, in us.
+#define		PIFS_TIME			0x0090	// PIFS time register.
+#define		ACK_TIMEOUT		0x0091	// Ack Timeout Register
+#define		EIFSTR				0x0092	// EIFS time regiser.
+#define		BCN_INTERVAL		0x0094	// Beacon Interval, in TU.
+#define		ATIMWND			0x0096	// ATIM Window width, in TU.
+#define		BCN_DRV_EARLY_INT	0x0098	// Driver Early Interrupt.
+#define		BCN_DMATIME		0x009A	// Beacon DMA and ATIM INT Time.
+#define		BCN_ERR_THRESH		0x009C	// Beacon Error Threshold.
+#define		MLT					0x009D	// MSDU Lifetime.
+#define		RSVD_MAC_TUNE_US	0x009E	// MAC Internal USE.
+
+//
+// 5. FIFO Control Registers	 (Offset: 0x00A0 - 0x015F)
+//
+#define 	RQPN				0x00A0
+#define	RQPN1				0x00A0	// Reserved Queue Page Number for BK
+#define	RQPN2				0x00A1	// Reserved Queue Page Number for BE
+#define	RQPN3				0x00A2	// Reserved Queue Page Number for VI
+#define	RQPN4				0x00A3	// Reserved Queue Page Number for VO
+#define	RQPN5				0x00A4	// Reserved Queue Page Number for HCCA
+#define	RQPN6				0x00A5	// Reserved Queue Page Number for CMD
+#define	RQPN7				0x00A6	// Reserved Queue Page Number for MGNT
+#define	RQPN8				0x00A7	// Reserved Queue Page Number for HIGH
+#define	RQPN9				0x00A8	// Reserved Queue Page Number for Beacon
+#define	RQPN10				0x00A9	// Reserved Queue Page Number for Public
+#define		LD_RQPN				0x00AB  //
+#define		RXFF_BNDY			0x00AC  //
+#define		RXRPT_BNDY			0x00B0  //
+#define		TXPKTBUF_PGBNDY		0x00B4  //
+#define		PBP					0x00B5  //
+#define		RXDRVINFO_SZ		0x00B6  //
+#define		TXFF_STATUS			0x00B7  //
+#define		RXFF_STATUS			0x00B8  //
+#define		TXFF_EMPTY_TH		0x00B9  //
+#define		SDIO_RX_BLKSZ		0x00BC  //
+#define		RXDMA				0x00BD  //
+#define		RXPKT_NUM			0x00BE  //
+#define		C2HCMD_UDT_SIZE		0x00C0  //
+#define		C2HCMD_UDT_ADDR		0x00C2  //
+#define		FIFOPAGE1			0x00C4  // Available public queue page number
+#define		FIFOPAGE2			0x00C8  //
+#define		FIFOPAGE3			0x00CC  //
+#define		FIFOPAGE4			0x00D0  //
+#define		FIFOPAGE5			0x00D4  //
+#define		FW_RSVD_PG_CRTL		0x00D8  //
+#define		RXDMA_AGG_PG_TH		0x00D9  //
+#define		TXRPTFF_RDPTR		0x00E0  //
+#define		TXRPTFF_WTPTR		0x00E4  //
+#define		C2HFF_RDPTR			0x00E8	//FIFO Read pointer register.
+#define		C2HFF_WTPTR			0x00EC	//FIFO Write pointer register.
+#define		RXFF0_RDPTR			0x00F0	//
+#define		RXFF0_WTPTR			0x00F4  //
+#define		RXFF1_RDPTR			0x00F8  //
+#define		RXFF1_WTPTR			0x00FC  //
+#define		RXRPT0_RDPTR		0x0100  //
+#define		RXRPT0_WTPTR		0x0104  //
+#define		RXRPT1_RDPTR		0x0108  //
+#define		RXRPT1_WTPTR		0x010C  //
+#define		RX0_UDT_SIZE		0x0110  //
+#define		RX1PKTNUM			0x0114  //
+#define		RXFILTERMAP			0x0116  //
+#define		RXFILTERMAP_GP1		0x0118  //
+#define		RXFILTERMAP_GP2		0x011A  //
+#define		RXFILTERMAP_GP3		0x011C  //
+#define		BCNQ_CTRL			0x0120  //
+#define		MGTQ_CTRL			0x0124  //
+#define		HIQ_CTRL			0x0128  //
+#define		VOTID7_CTRL			0x012c  //
+#define		VOTID6_CTRL			0x0130  //
+#define		VITID5_CTRL			0x0134  //
+#define		VITID4_CTRL			0x0138  //
+#define		BETID3_CTRL			0x013c  //
+#define		BETID0_CTRL			0x0140  //
+#define		BKTID2_CTRL			0x0144  //
+#define		BKTID1_CTRL			0x0148  //
+#define		CMDQ_CTRL			0x014c  //
+#define		TXPKT_NUM_CTRL		0x0150  //
+#define		TXQ_PGADD			0x0152  //
+#define		TXFF_PG_NUM			0x0154  //
+#define		TRXDMA_STATUS		0x0156  //
+
+//
+// 6. Adaptive Control Registers  (Offset: 0x0160 - 0x01CF)
+//
+#define		INIMCS_SEL			0x0160	// Init MCSrate for 32 MACID 0x160-17f
+#define		TX_RATE_REG		INIMCS_SEL //Current Tx rate register
+#define		INIRTSMCS_SEL		0x0180	// Init RTSMCSrate
+#define		RRSR				0x0181	// Response rate setting.
+#define		ARFR0				0x0184	// Auto Rate Fallback 0 Register.
+#define		ARFR1				0x0188	//
+#define		ARFR2				0x018C  //
+#define		ARFR3				0x0190  //
+#define		ARFR4				0x0194  //
+#define		ARFR5				0x0198  //
+#define		ARFR6				0x019C  //
+#define		ARFR7				0x01A0  //
+#define		AGGLEN_LMT_H		0x01A7	// Aggregation Length Limit for High-MCS
+#define		AGGLEN_LMT_L		0x01A8	// Aggregation Length Limit for Low-MCS.
+#define		DARFRC				0x01B0	// Data Auto Rate Fallback Retry Count.
+#define		RARFRC				0x01B8	// Response Auto Rate Fallback Count.
+#define		MCS_TXAGC			0x01C0
+#define		CCK_TXAGC			0x01C8
+
+//
+// 7. EDCA Setting Registers	 (Offset: 0x01D0 - 0x01FF)
+//
+#define		EDCAPARA_VO 		0x01D0	// EDCA Parameter Register for VO queue.
+#define		EDCAPARA_VI			0x01D4	// EDCA Parameter Register for VI queue.
+#define		EDCAPARA_BE			0x01D8	// EDCA Parameter Register for BE queue.
+#define		EDCAPARA_BK			0x01DC	// EDCA Parameter Register for BK queue.
+#define		BCNTCFG				0x01E0	// Beacon Time Configuration Register.
+#define		CWRR				0x01E2	// Contention Window Report Register.
+#define		ACMAVG				0x01E4	// ACM Average Register.
+#define		AcmHwCtrl			0x01E7
+#define		VO_ADMTM			0x01E8	// Admission Time Register.
+#define		VI_ADMTM			0x01EC
+#define		BE_ADMTM			0x01F0
+#define		RETRY_LIMIT			0x01F4	// Retry Limit Registers[15:8]-short, [7:0]-long
+#define		SG_RATE				0x01F6	// Max MCS Rate Available Register, which we Set the hightst SG rate.
+
+//
+// 8. WMAC, BA and CCX related Register.	 (Offset: 0x0200 - 0x023F)
+//
+#define		NAV_CTRL			0x0200
+#define		BW_OPMODE			0x0203
+#define		BACAMCMD			0x0204
+#define		BACAMCONTENT		0x0208	// Block ACK CAM R/W Register.
+
+// Roger had defined the 0x2xx register WMAC definition
+#define		LBDLY				0x0210	// Loopback Delay Register.
+#define		FWDLY				0x0211	// FW Delay Register.
+#define		HWPC_RX_CTRL		0x0218	// HW Packet Conversion RX Control Reg
+#define		MQIR				0x0220	// Mesh Qos Type Indication Register.
+#define		MAIR				0x0222	// Mesh ACK.
+#define		MSIR				0x0224	// Mesh HW Security Requirement Indication Reg
+#define		CLM_RESULT			0x0227	// CCA Busy Fraction(Channel Load)
+#define		NHM_RPI_CNT			0x0228	// Noise Histogram Measurement (NHM) RPI Report.
+#define		RXERR_RPT			0x0230	// Rx Error Report.
+#define		NAV_PROT_LEN		0x0234	// NAV Protection Length.
+#define		CFEND_TH			0x0236	// CF-End Threshold.
+#define		AMPDU_MIN_SPACE		0x0237	// AMPDU Min Space.
+#define		TXOP_STALL_CTRL		0x0238
+
+//
+// 9. Security Control Registers	(Offset: 0x0240 - 0x025F)
+//
+#define		RWCAM				0x0240	//IN 8190 Data Sheet is called CAMcmd
+#define		WCAMI				0x0244	// Software write CAM input content
+#define		RCAMO				0x0248	// Software read/write CAM config
+#define		CAMDBG				0x024C
+#define		SECR				0x0250	//Security Configuration Register
+
+//
+// 10. Power Save Control Registers	 (Offset: 0x0260 - 0x02DF)
+//
+#define		WOW_CTRL			0x0260	//Wake On WLAN Control.
+#define		PSSTATUS			0x0261	// Power Save Status.
+#define		PSSWITCH			0x0262	// Power Save Switch.
+#define		MIMOPS_WAIT_PERIOD	0x0263
+#define		LPNAV_CTRL			0x0264
+#define		WFM0				0x0270	// Wakeup Frame Mask.
+#define		WFM1				0x0280	//
+#define		WFM2				0x0290  //
+#define		WFM3				0x02A0  //
+#define		WFM4				0x02B0  //
+#define		WFM5				0x02C0  // FW Control register.
+#define		WFCRC				0x02D0	// Wakeup Frame CRC.
+#define		RPWM				0x02DC	// Host Request Power Mode.
+#define		CPWM				0x02DD	// Current Power Mode.
+#define		FW_RPT_REG			0x02c4
+
+//
+// 11. General Purpose Registers	(Offset: 0x02E0 - 0x02FF)
+//
+#define		PSTIME				0x02E0  // Power Save Timer Register
+#define		TIMER0				0x02E4  //
+#define		TIMER1				0x02E8  //
+#define		GPIO_CTRL			0x02EC  // GPIO Control Register
+#define		GPIO_IN				0x02EC	// GPIO pins input value
+#define		GPIO_OUT			0x02ED	// GPIO pins output value
+#define		GPIO_IO_SEL			0x02EE	// GPIO pins output enable when a bit is set to "1"; otherwise, input is configured.
+#define		GPIO_MOD			0x02EF	//
+#define		GPIO_INTCTRL		0x02F0  // GPIO Interrupt Control Register[7:0]
+#define		MAC_PINMUX_CFG		0x02F1  // MAC PINMUX Configuration Reg[7:0]
+#define		LEDCFG				0x02F2  // System PINMUX Configuration Reg[7:0]
+#define		PHY_REG				0x02F3  // RPT: PHY REG Access Report Reg[7:0]
+#define		PHY_REG_DATA		0x02F4  // PHY REG Read DATA Register [31:0]
+#define		EFUSE_CLK			0x02F8  // CTRL: E-FUSE Clock Control Reg[7:0]
+//#define		GPIO_INTCTRL		0x02F9  // GPIO Interrupt Control Register[7:0]
+
+//
+// 12. Host Interrupt Status Registers	 (Offset: 0x0300 - 0x030F)
+//
+#define		IMR					0x0300	// Interrupt Mask Register
+#define		ISR					0x0308	// Interrupt Status Register
+
+//
+// 13. Test Mode and Debug Control Registers	(Offset: 0x0310 - 0x034F)
+//
+#define		DBG_PORT_SWITCH		0x003A
+#define		BIST				0x0310	// Bist reg definition
+#define		DBS					0x0314	// Debug Select ???
+#define		CPUINST				0x0318	// CPU Instruction Read Register
+#define		CPUCAUSE			0x031C	// CPU Cause Register
+#define		LBUS_ERR_ADDR		0x0320	// Lexra Bus Error Address Register
+#define		LBUS_ERR_CMD		0x0324	// Lexra Bus Error Command Register
+#define		LBUS_ERR_DATA_L		0x0328	// Lexra Bus Error Data Low DW Register
+#define		LBUS_ERR_DATA_H		0x032C	//
+#define		LX_EXCEPTION_ADDR	0x0330	// Lexra Bus Exception Address Register
+#define		WDG_CTRL			0x0334	// Watch Dog Control Register
+#define		INTMTU				0x0338	// Interrupt Mitigation Time Unit Reg
+#define		INTM				0x033A	// Interrupt Mitigation Register
+#define		FDLOCKTURN0			0x033C	// FW/DRV Lock Turn 0 Register
+#define		FDLOCKTURN1			0x033D	// FW/DRV Lock Turn 1 Register
+#define		TRXPKTBUF_DBG_DATA	0x0340	// TRX Packet Buffer Debug Data Register
+#define		TRXPKTBUF_DBG_CTRL	0x0348	// TRX Packet Buffer Debug Control Reg
+#define		DPLL				0x034A	// DPLL Monitor Register [15:0]
+#define		CBUS_ERR_ADDR		0x0350	// CPU Bus Error Address Register
+#define		CBUS_ERR_CMD		0x0354	// CPU Bus Error Command Register
+#define		CBUS_ERR_DATA_L		0x0358	// CPU Bus Error Data Low DW Register
+#define		CBUS_ERR_DATA_H 	0x035C	//
+#define		USB_SIE_INTF_ADDR	0x0360	// USB SIE Access Interface Address Reg
+#define		USB_SIE_INTF_WD		0x0361	// USB SIE Access Interface WData Reg
+#define		USB_SIE_INTF_RD		0x0362	// USB SIE Access Interface RData Reg
+#define		USB_SIE_INTF_CTRL	0x0363	// USB SIE Access Interface Control Reg
+
+// Boundary is 0x37F
+
+//
+// 14. PCIE config register	(Offset 0x500-)
+//
+#define		TPPoll				0x0500	// Transmit Polling
+#define		PM_CTRL				0x0502	// PCIE power management control Register
+#define		PCIF				0x0503	// PCI Function Register 0x0009h~0x000bh
+
+#define		THPDA				0x0514	// Transmit High Priority Desc Addr
+#define		TMDA				0x0518	// Transmit Management Desc Addr
+#define		TCDA				0x051C	// Transmit Command Desc Addr
+#define		HDA				0x0520	// HCCA Desc Addr
+#define		TVODA				0x0524	// Transmit VO Desc Addr
+#define		TVIDA				0x0528	// Transmit VI Desc Addr
+#define		TBEDA				0x052C	// Transmit BE Desc Addr
+#define		TBKDA				0x0530	// Transmit BK Desc Addr
+#define		TBDA				0x0534	// Transmit Beacon Desc Addr
+#define		RCDA				0x0538	// Receive Command Desc Addr
+#define		RDSA				0x053C	// Receive Desc Starting Addr
+#define		DBI_WDATA			0x0540	// DBI write data Register
+#define		DBI_RDATA			0x0544	// DBI read data Register
+#define		DBI_CTRL			0x0548	// PCIE DBI control Register
+#define		MDIO_DATA			0x0550	// PCIE MDIO data Register
+#define		MDIO_CTRL			0x0554	// PCIE MDIO control Register
+#define		PCI_RPWM			0x0561	// PCIE RPWM register
+#define		PCI_CPWM				0x0563	// Current Power Mode.
+
+//
+// Config register   (Offset 0x800-)
+//
+#define 	PHY_CCA				0x803   // CCA related register
+
+//============================================================================
+//       8192S USB specific Regsiter Offset and Content definition,
+//       2008.08.28, added by Roger.
+//============================================================================
+// Rx Aggregation time-out reg.
+#define	USB_RX_AGG_TIMEOUT	0xFE5B
+
+// Firware reserved Tx page control.
+#define	FW_OFFLOAD_EN		BIT7
+
+// Min Spacing related settings.
+#define	MAX_MSS_DENSITY 			0x13
+#define	MAX_MSS_DENSITY_2T 		0x13
+#define	MAX_MSS_DENSITY_1T 		0x0A
+
+// Rx DMA Control related settings
+#define	RXDMA_AGG_EN		BIT7
+
+// USB Rx Aggregation TimeOut settings
+#define	RXDMA_AGG_TIMEOUT_DISABLE		0x00
+#define	RXDMA_AGG_TIMEOUT_17MS  			0x01
+#define	RXDMA_AGG_TIMEOUT_17_2_MS  		0x02
+#define	RXDMA_AGG_TIMEOUT_17_4_MS  		0x04
+#define	RXDMA_AGG_TIMEOUT_17_10_MS  		0x0A
+// USB RPWM register
+#define	USB_RPWM			0xFE58
+
+//FIXLZM SVN_BRACH NOT MOD HERE, IF MOD RX IS LITTLE LOW
+//#if ((HAL_CODE_BASE == RTL8192_S) &&  (DEV_BUS_TYPE==PCI_INTERFACE))
+//#define	RPWM		PCI_RPWM
+//#elif ((HAL_CODE_BASE == RTL8192_S) &&  (DEV_BUS_TYPE==USB_INTERFACE))
+//#define	RPWM		USB_RPWM
+//#endif
+
+
+//============================================================================
+//       8190 Regsiter offset definition
+//============================================================================
+#if 1	// Delete the register later
+#define		AFR					0x010	// AutoLoad Function Register
+#define		BCN_TCFG			0x062	// Beacon Time Configuration
+#define		RATR0				0x320	// Rate Adaptive Table register1
+#endif
+// TODO: Remove unused register, We must declare backward compatiable
+//Undefined register set in 8192S. 0x320/350 DW is useless
+#define		UnusedRegister		0x0320
+#define		PSR					UnusedRegister	// Page Select Register
+//Security Related
+#define		DCAM				UnusedRegister	// Debug CAM Interface
+//PHY Configuration related
+#define		BBAddr				UnusedRegister	// Phy register address register
+#define		PhyDataR			UnusedRegister	// Phy register data read
+#define		UFWP				UnusedRegister
+
+
+//============================================================================
+//       8192S Regsiter Bit and Content definition
+//============================================================================
+
+//
+// 1. System Configuration Registers	 (Offset: 0x0000 - 0x003F)
+//
+//----------------------------------------------------------------------------
+//       8192S SYS_ISO_CTRL bits					(Offset 0x0, 16bit)
+//----------------------------------------------------------------------------
+#define		ISO_MD2PP			BIT0	// MACTOP/BB/PCIe Digital to Power On.
+#define		ISO_PA2PCIE			BIT3	// PCIe Analog 1.2V to PCIe 3.3V
+#define		ISO_PLL2MD			BIT4	// AFE PLL to MACTOP/BB/PCIe Digital.
+#define		ISO_PWC_DV2RP		BIT11	// Digital Vdd to Retention Path
+#define		ISO_PWC_RV2RP		BIT12	// LPLDOR12 to Retenrion Path, 1: isolation, 0: attach.
+
+//----------------------------------------------------------------------------
+//       8192S SYS_FUNC_EN bits					(Offset 0x2, 16bit)
+//----------------------------------------------------------------------------
+#define		FEN_MREGEN			BIT15	// MAC I/O Registers Enable.
+#define		FEN_DCORE			BIT11	// Enable Core Digital.
+#define		FEN_CPUEN			BIT10	// Enable CPU Core Digital.
+//       8192S PMC_FSM bits					(Offset 0x4, 32bit)
+//----------------------------------------------------------------------------
+#define		PAD_HWPD_IDN		BIT22	// HWPDN PAD status Indicator
+
+//----------------------------------------------------------------------------
+
+//----------------------------------------------------------------------------
+//       8192S SYS_CLKR bits					(Offset 0x8, 16bit)
+//----------------------------------------------------------------------------
+#define		SYS_CLKSEL_80M		BIT0	// System Clock 80MHz
+#define		SYS_PS_CLKSEL		BIT1	 //System power save clock select.
+#define		SYS_CPU_CLKSEL		BIT2	// System Clock select, 1: AFE source, 0: System clock(L-Bus)
+#define		SYS_MAC_CLK_EN		BIT11	// MAC Clock Enable.
+#define		SYS_SWHW_SEL		BIT14	// Load done, control path seitch.
+#define		SYS_FWHW_SEL		BIT15	// Sleep exit, control path swith.
+
+
+//----------------------------------------------------------------------------
+//       8192S Cmd9346CR bits					(Offset 0xA, 16bit)
+//----------------------------------------------------------------------------
+#define		CmdEEPROM_En						BIT5	 // EEPROM enable when set 1
+#define		CmdEERPOMSEL						BIT4 // System EEPROM select, 0: boot from E-FUSE, 1: The EEPROM used is 9346
+#define		Cmd9346CR_9356SEL					BIT4
+#define		AutoLoadEEPROM						(CmdEEPROM_En|CmdEERPOMSEL)
+#define		AutoLoadEFUSE						CmdEEPROM_En
+
+
+//----------------------------------------------------------------------------
+//       8192S AFE_MISC bits		AFE Misc			(Offset 0x10, 8bits)
+//----------------------------------------------------------------------------
+#define		AFE_MBEN			BIT1	// Enable AFE Macro Block's Mbias.
+#define		AFE_BGEN			BIT0	// Enable AFE Macro Block's Bandgap.
+
+//----------------------------------------------------------------------------
+//       8192S SPS1_CTRL bits					(Offset 0x18-1E, 56bits)
+//----------------------------------------------------------------------------
+#define		SPS1_SWEN			BIT1	// Enable vsps18 SW Macro Block.
+#define		SPS1_LDEN			BIT0	// Enable VSPS12 LDO Macro block.
+
+//----------------------------------------------------------------------------
+//       8192S RF_CTRL bits					(Offset 0x1F, 8bits)
+//----------------------------------------------------------------------------
+#define		RF_EN				BIT0 // Enable RF module.
+#define		RF_RSTB			BIT1 // Reset RF module.
+#define		RF_SDMRSTB			BIT2 // Reset RF SDM module.
+
+//----------------------------------------------------------------------------
+//       8192S LDOA15_CTRL bits					(Offset 0x20, 8bits)
+//----------------------------------------------------------------------------
+#define		LDA15_EN			BIT0	// Enable LDOA15 Macro Block
+
+//----------------------------------------------------------------------------
+//       8192S LDOV12D_CTRL bits					(Offset 0x21, 8bits)
+//----------------------------------------------------------------------------
+#define		LDV12_EN			BIT0	// Enable LDOVD12 Macro Block
+#define		LDV12_SDBY			BIT1	// LDOVD12 standby mode
+
+//----------------------------------------------------------------------------
+//       8192S AFE_XTAL_CTRL bits	AFE Crystal Control.	(Offset 0x26,16bits)
+//----------------------------------------------------------------------------
+#define		XTAL_GATE_AFE		BIT10
+// Gated Control. 1: AFE Clock source gated, 0: Clock enable.
+
+//----------------------------------------------------------------------------
+//       8192S AFE_PLL_CTRL bits	System Function Enable	(Offset 0x28,64bits)
+//----------------------------------------------------------------------------
+#define		APLL_EN				BIT0	// Enable AFE PLL Macro Block.
+
+// Find which card bus type
+#define		AFR_CardBEn			BIT0
+#define		AFR_CLKRUN_SEL		BIT1
+#define		AFR_FuncRegEn		BIT2
+
+//
+// 2. Command Control Registers	 (Offset: 0x0040 - 0x004F)
+//
+//----------------------------------------------------------------------------
+//       8192S (CMD) command register bits		(Offset 0x40, 16 bits)
+//----------------------------------------------------------------------------
+#define		APSDOFF_STATUS		BIT15	//
+#define		APSDOFF				BIT14   //
+#define		BBRSTn				BIT13   //Enable OFDM/CCK
+#define		BB_GLB_RSTn			BIT12   //Enable BB
+#define		SCHEDULE_EN			BIT10   //Enable MAC scheduler
+#define		MACRXEN				BIT9    //
+#define		MACTXEN				BIT8    //
+#define		DDMA_EN				BIT7    //FW off load function enable
+#define		FW2HW_EN			BIT6    //MAC every module reset as below
+#define		RXDMA_EN			BIT5    //
+#define		TXDMA_EN			BIT4    //
+#define		HCI_RXDMA_EN		BIT3    //
+#define		HCI_TXDMA_EN		BIT2    //
+
+//----------------------------------------------------------------------------
+//       8192S (TXPAUSE) transmission pause		(Offset 0x42, 8 bits)
+//----------------------------------------------------------------------------
+#define		StopHCCA			BIT6
+#define		StopHigh			BIT5
+#define		StopMgt				BIT4
+#define		StopVO				BIT3
+#define		StopVI				BIT2
+#define		StopBE				BIT1
+#define		StopBK				BIT0
+
+//----------------------------------------------------------------------------
+//       8192S (LBKMD) LoopBack Mode Select 		(Offset 0x43, 8 bits)
+//----------------------------------------------------------------------------
+//
+//	[3] no buffer, 1: no delay, 0: delay; [2] dmalbk, [1] no_txphy, [0] diglbk.
+//	0000: Normal
+//	1011: MAC loopback (involving CPU)
+//	0011: MAC Delay Loopback
+//	0001: PHY loopback (not yet implemented)
+//	0111: DMA loopback (only uses TxPktBuffer and DMA engine)
+//	All other combinations are reserved.
+//	Default: 0000b.
+//
+#define		LBK_NORMAL		0x00
+#define		LBK_MAC_LB		(BIT0|BIT1|BIT3)
+#define		LBK_MAC_DLB		(BIT0|BIT1)
+#define		LBK_DMA_LB		(BIT0|BIT1|BIT2)
+
+//----------------------------------------------------------------------------
+//       8192S (TCR) transmission Configuration Register (Offset 0x44, 32 bits)
+//----------------------------------------------------------------------------
+#define		TCP_OFDL_EN				BIT25	//For CE packet conversion
+#define		HWPC_TX_EN				BIT24   //""
+#define		TXDMAPRE2FULL			BIT23   //TXDMA enable pre2full sync
+#define		DISCW					BIT20   //CW disable
+#define		TCRICV					BIT19   //Append ICV or not
+#define		CfendForm				BIT17   //AP mode
+#define		TCRCRC					BIT16   //Append CRC32
+#define		FAKE_IMEM_EN			BIT15   //
+#define		TSFRST					BIT9    //
+#define		TSFEN					BIT8    //
+// For TCR FW download ready --> write by FW  Bit0-7 must all one
+#define		FWALLRDY				(BIT0|BIT1|BIT2|BIT3|BIT4|BIT5|BIT6|BIT7)
+#define		FWRDY					BIT7
+#define		BASECHG					BIT6
+#define		IMEM					BIT5
+#define		DMEM_CODE_DONE			BIT4
+#define		EXT_IMEM_CHK_RPT		BIT3
+#define		EXT_IMEM_CODE_DONE		BIT2
+#define		IMEM_CHK_RPT			BIT1
+#define		IMEM_CODE_DONE			BIT0
+// Copy fomr 92SU definition
+#define		IMEM_CODE_DONE		BIT0
+#define		IMEM_CHK_RPT		BIT1
+#define		EMEM_CODE_DONE		BIT2
+#define		EMEM_CHK_RPT		BIT3
+#define		DMEM_CODE_DONE		BIT4
+#define		IMEM_RDY			BIT5
+#define		BASECHG			BIT6
+#define		FWRDY				BIT7
+#define		LOAD_FW_READY		(IMEM_CODE_DONE|IMEM_CHK_RPT|EMEM_CODE_DONE|\
+					EMEM_CHK_RPT|DMEM_CODE_DONE|IMEM_RDY|BASECHG|\
+					FWRDY)
+#define		TCR_TSFEN			BIT8		// TSF function on or off.
+#define		TCR_TSFRST			BIT9		// Reset TSF function to zero.
+#define		TCR_FAKE_IMEM_EN	BIT15
+#define		TCR_CRC				BIT16
+#define		TCR_ICV				BIT19	// Integrity Check Value.
+#define		TCR_DISCW			BIT20	// Disable Contention Windows Backoff.
+#define		TCR_HWPC_TX_EN	BIT24
+#define		TCR_TCP_OFDL_EN	BIT25
+#define		TXDMA_INIT_VALUE	(IMEM_CHK_RPT|EXT_IMEM_CHK_RPT)
+//----------------------------------------------------------------------------
+//       8192S (RCR) Receive Configuration Register	(Offset 0x48, 32 bits)
+//----------------------------------------------------------------------------
+#define		RCR_APPFCS				BIT31		//WMAC append FCS after pauload
+#define		RCR_DIS_ENC_2BYTE		BIT30       //HW encrypt 2 or 1 byte mode
+#define		RCR_DIS_AES_2BYTE		BIT29       //
+#define		RCR_HTC_LOC_CTRL		BIT28       //MFC<--HTC=1 MFC-->HTC=0
+#define		RCR_ENMBID				BIT27		//Enable Multiple BssId.
+#define		RCR_RX_TCPOFDL_EN		BIT26		//
+#define		RCR_APP_PHYST_RXFF	BIT25       //
+#define		RCR_APP_PHYST_STAFF	BIT24       //
+#define		RCR_CBSSID				BIT23		//Accept BSSID match packet
+#define		RCR_APWRMGT			BIT22		//Accept power management packet
+#define		RCR_ADD3				BIT21		//Accept address 3 match packet
+#define		RCR_AMF				BIT20		//Accept management type frame
+#define		RCR_ACF					BIT19		//Accept control type frame
+#define		RCR_ADF					BIT18		//Accept data type frame
+#define		RCR_APP_MIC			BIT17		//
+#define		RCR_APP_ICV			BIT16       //
+#define		RCR_RXFTH				BIT13		//Rx FIFO Threshold Bot 13 - 15
+#define		RCR_AICV				BIT12		//Accept ICV error packet
+#define		RCR_RXDESC_LK_EN		BIT11		//Accept to update rx desc length
+#define		RCR_APP_BA_SSN			BIT6		//Accept BA SSN
+#define		RCR_ACRC32				BIT5		//Accept CRC32 error packet
+#define		RCR_RXSHFT_EN			BIT4		//Accept broadcast packet
+#define		RCR_AB					BIT3		//Accept broadcast packet
+#define		RCR_AM					BIT2		//Accept multicast packet
+#define		RCR_APM				BIT1		//Accept physical match packet
+#define		RCR_AAP					BIT0		//Accept all unicast packet
+#define		RCR_MXDMA_OFFSET		8
+#define		RCR_FIFO_OFFSET		13
+
+//in 92U FIXLZM
+//#ifdef RTL8192U
+#define RCR_ONLYERLPKT		BIT31			// Early Receiving based on Packet Size.
+#define RCR_ENCS2			BIT30			// Enable Carrier Sense Detection Method 2
+#define RCR_ENCS1			BIT29			// Enable Carrier Sense Detection Method 1
+#define RCR_ACKTXBW			(BIT24|BIT25)		// TXBW Setting of ACK frames
+//#endif
+//----------------------------------------------------------------------------
+//       8192S (MSR) Media Status Register	(Offset 0x4C, 8 bits)
+//----------------------------------------------------------------------------
+/*
+Network Type
+00: No link
+01: Link in ad hoc network
+10: Link in infrastructure network
+11: AP mode
+Default: 00b.
+*/
+#define		MSR_NOLINK				0x00
+#define		MSR_ADHOC				0x01
+#define		MSR_INFRA				0x02
+#define		MSR_AP					0x03
+
+//----------------------------------------------------------------------------
+//       8192S (SYSF_CFG) system Fucntion Config Reg	(Offset 0x4D, 8 bits)
+//----------------------------------------------------------------------------
+#define		ENUART					BIT7
+#define		ENJTAG					BIT3
+#define		BTMODE					(BIT2|BIT1)
+#define		ENBT					BIT0
+
+//----------------------------------------------------------------------------
+//       8192S (MBIDCTRL) MBSSID Control Register	(Offset 0x4F, 8 bits)
+//----------------------------------------------------------------------------
+#define		ENMBID					BIT7
+#define		BCNUM					(BIT6|BIT5|BIT4)
+
+//
+// 3. MACID Setting Registers	(Offset: 0x0050 - 0x007F)
+//
+
+//
+// 4. Timing Control Registers	(Offset: 0x0080 - 0x009F)
+//
+//----------------------------------------------------------------------------
+//       8192S (USTIME) US Time Tunning Register	(Offset 0x8A, 16 bits)
+//----------------------------------------------------------------------------
+#define		USTIME_EDCA				0xFF00
+#define		USTIME_TSF				0x00FF
+
+//----------------------------------------------------------------------------
+//       8192S (SIFS_CCK/OFDM) US Time Tunning Register	(Offset 0x8C/8E,16 bits)
+//----------------------------------------------------------------------------
+#define		SIFS_TRX				0xFF00
+#define		SIFS_CTX				0x00FF
+
+//----------------------------------------------------------------------------
+//       8192S (DRVERLYINT)	Driver Early Interrupt Reg		(Offset 0x98, 16bit)
+//----------------------------------------------------------------------------
+#define		ENSWBCN					BIT15
+#define		DRVERLY_TU				0x0FF0
+#define		DRVERLY_US				0x000F
+#define		BCN_TCFG_CW_SHIFT		8
+#define		BCN_TCFG_IFS			0
+
+//
+// 5. FIFO Control Registers	 (Offset: 0x00A0 - 0x015F)
+//
+
+//
+// 6. Adaptive Control Registers  (Offset: 0x0160 - 0x01CF)
+//
+//----------------------------------------------------------------------------
+//       8192S Response Rate Set Register	(offset 0x181, 24bits)
+//----------------------------------------------------------------------------
+#define		RRSR_RSC_OFFSET			21
+#define		RRSR_SHORT_OFFSET		23
+#define		RRSR_RSC_BW_40M		0x600000
+#define		RRSR_RSC_UPSUBCHNL		0x400000
+#define		RRSR_RSC_LOWSUBCHNL		0x200000
+#define		RRSR_SHORT				0x800000
+#define		RRSR_1M					BIT0
+#define		RRSR_2M					BIT1
+#define		RRSR_5_5M				BIT2
+#define		RRSR_11M				BIT3
+#define		RRSR_6M					BIT4
+#define		RRSR_9M					BIT5
+#define		RRSR_12M				BIT6
+#define		RRSR_18M				BIT7
+#define		RRSR_24M				BIT8
+#define		RRSR_36M				BIT9
+#define		RRSR_48M				BIT10
+#define		RRSR_54M				BIT11
+#define		RRSR_MCS0				BIT12
+#define		RRSR_MCS1				BIT13
+#define		RRSR_MCS2				BIT14
+#define		RRSR_MCS3				BIT15
+#define		RRSR_MCS4				BIT16
+#define		RRSR_MCS5				BIT17
+#define		RRSR_MCS6				BIT18
+#define		RRSR_MCS7				BIT19
+#define		BRSR_AckShortPmb		BIT23
+
+#define 		RRSR_RSC_UPSUBCHANL	0x200000
+// CCK ACK: use Short Preamble or not
+
+//----------------------------------------------------------------------------
+//       8192S Rate Definition
+//----------------------------------------------------------------------------
+//CCK
+#define		RATR_1M					0x00000001
+#define		RATR_2M					0x00000002
+#define		RATR_55M				0x00000004
+#define		RATR_11M				0x00000008
+//OFDM
+#define		RATR_6M					0x00000010
+#define		RATR_9M					0x00000020
+#define		RATR_12M				0x00000040
+#define		RATR_18M				0x00000080
+#define		RATR_24M				0x00000100
+#define		RATR_36M				0x00000200
+#define		RATR_48M				0x00000400
+#define		RATR_54M				0x00000800
+//MCS 1 Spatial Stream
+#define		RATR_MCS0				0x00001000
+#define		RATR_MCS1				0x00002000
+#define		RATR_MCS2				0x00004000
+#define		RATR_MCS3				0x00008000
+#define		RATR_MCS4				0x00010000
+#define		RATR_MCS5				0x00020000
+#define		RATR_MCS6				0x00040000
+#define		RATR_MCS7				0x00080000
+//MCS 2 Spatial Stream
+#define		RATR_MCS8				0x00100000
+#define		RATR_MCS9				0x00200000
+#define		RATR_MCS10				0x00400000
+#define		RATR_MCS11				0x00800000
+#define		RATR_MCS12				0x01000000
+#define		RATR_MCS13				0x02000000
+#define		RATR_MCS14				0x04000000
+#define		RATR_MCS15				0x08000000
+// ALL CCK Rate
+#define	RATE_ALL_CCK				RATR_1M|RATR_2M|RATR_55M|RATR_11M
+#define	RATE_ALL_OFDM_AG			RATR_6M|RATR_9M|RATR_12M|RATR_18M|RATR_24M|\
+									RATR_36M|RATR_48M|RATR_54M
+#define	RATE_ALL_OFDM_1SS			RATR_MCS0|RATR_MCS1|RATR_MCS2|RATR_MCS3 |\
+									RATR_MCS4|RATR_MCS5|RATR_MCS6	|RATR_MCS7
+#define	RATE_ALL_OFDM_2SS			RATR_MCS8|RATR_MCS9	|RATR_MCS10|RATR_MCS11|\
+									RATR_MCS12|RATR_MCS13|RATR_MCS14|RATR_MCS15
+
+//
+// 7. EDCA Setting Registers	 (Offset: 0x01D0 - 0x01FF)
+//
+//----------------------------------------------------------------------------
+//       8192S EDCA Setting 	(offset 0x1D0-1DF, 4DW VO/VI/BE/BK)
+//----------------------------------------------------------------------------
+#define		AC_PARAM_TXOP_LIMIT_OFFSET		16
+#define		AC_PARAM_ECW_MAX_OFFSET			12
+#define		AC_PARAM_ECW_MIN_OFFSET			8
+#define		AC_PARAM_AIFS_OFFSET			0
+
+//----------------------------------------------------------------------------
+//       8192S AcmHwCtrl bits 					(offset 0x1E7, 1 byte)
+//----------------------------------------------------------------------------
+#define		AcmHw_HwEn				BIT0
+#define		AcmHw_BeqEn				BIT1
+#define		AcmHw_ViqEn				BIT2
+#define		AcmHw_VoqEn				BIT3
+#define		AcmHw_BeqStatus			BIT4
+#define		AcmHw_ViqStatus			BIT5
+#define		AcmHw_VoqStatus			BIT6
+
+//----------------------------------------------------------------------------
+//       8192S Retry Limit					(Offset 0x1F4, 16bit)
+//----------------------------------------------------------------------------
+#define		RETRY_LIMIT_SHORT_SHIFT	8
+#define		RETRY_LIMIT_LONG_SHIFT	0
+
+//
+// 8. WMAC, BA and CCX related Register.	 (Offset: 0x0200 - 0x023F)
+//
+//----------------------------------------------------------------------------
+//       8192S NAV_CTRL bits					(Offset 0x200, 24bit)
+//----------------------------------------------------------------------------
+#define		NAV_UPPER_EN			BIT16
+#define		NAV_UPPER				0xFF00
+#define		NAV_RTSRST				0xFF
+//----------------------------------------------------------------------------
+//       8192S BW_OPMODE bits					(Offset 0x203, 8bit)
+//----------------------------------------------------------------------------
+#define		BW_OPMODE_20MHZ			BIT2
+#define		BW_OPMODE_5G			BIT1
+#define		BW_OPMODE_11J			BIT0
+//----------------------------------------------------------------------------
+//       8192S BW_OPMODE bits					(Offset 0x230, 4 Byte)
+//----------------------------------------------------------------------------
+#define		RXERR_RPT_RST			BIT27 // Write "one" to set the counter to zero.
+// RXERR_RPT_SEL
+#define		RXERR_OFDM_PPDU			0
+#define		RXERR_OFDM_FALSE_ALARM	1
+#define		RXERR_OFDM_MPDU_OK		2
+#define		RXERR_OFDM_MPDU_FAIL	3
+#define		RXERR_CCK_PPDU			4
+#define		RXERR_CCK_FALSE_ALARM	5
+#define		RXERR_CCK_MPDU_OK		6
+#define		RXERR_CCK_MPDU_FAIL		7
+#define		RXERR_HT_PPDU			8
+#define		RXERR_HT_FALSE_ALARM	9
+#define		RXERR_HT_MPDU_TOTAL		10
+#define		RXERR_HT_MPDU_OK		11
+#define		RXERR_HT_MPDU_FAIL		12
+#define		RXERR_RX_FULL_DROP		15
+
+//
+// 9. Security Control Registers	(Offset: 0x0240 - 0x025F)
+//
+//----------------------------------------------------------------------------
+//       8192S RWCAM CAM Command Register     		(offset 0x240, 4 byte)
+//----------------------------------------------------------------------------
+#define		CAM_CM_SecCAMPolling	BIT31		//Security CAM Polling
+#define		CAM_CM_SecCAMClr		BIT30		//Clear all bits in CAM
+#define		CAM_CM_SecCAMWE			BIT16		//Security CAM enable
+#define		CAM_ADDR				0xFF		//CAM Address Offset
+
+//----------------------------------------------------------------------------
+//       8192S CAMDBG Debug CAM Register	 			(offset 0x24C, 4 byte)
+//----------------------------------------------------------------------------
+#define		Dbg_CAM_TXSecCAMInfo	BIT31		//Retrieve lastest Tx Info
+#define		Dbg_CAM_SecKeyFound		BIT30		//Security KEY Found
+
+
+//----------------------------------------------------------------------------
+//       8192S SECR Security Configuration Register	(offset 0x250, 1 byte)
+//----------------------------------------------------------------------------
+#define		SCR_TxUseDK				BIT0			//Force Tx Use Default Key
+#define		SCR_RxUseDK				BIT1			//Force Rx Use Default Key
+#define		SCR_TxEncEnable			BIT2			//Enable Tx Encryption
+#define		SCR_RxDecEnable			BIT3			//Enable Rx Decryption
+#define		SCR_SKByA2				BIT4			//Search kEY BY A2
+#define		SCR_NoSKMC				BIT5			//No Key Search Multicast
+//----------------------------------------------------------------------------
+//       8192S CAM Config Setting (offset 0x250, 1 byte)
+//----------------------------------------------------------------------------
+#define		CAM_VALID				BIT15
+#define		CAM_NOTVALID			0x0000
+#define		CAM_USEDK				BIT5
+
+#define		CAM_NONE				0x0
+#define		CAM_WEP40				0x01
+#define		CAM_TKIP				0x02
+#define		CAM_AES					0x04
+#define		CAM_WEP104				0x05
+
+#define		TOTAL_CAM_ENTRY			32
+
+#define		CAM_CONFIG_USEDK		TRUE
+#define		CAM_CONFIG_NO_USEDK		FALSE
+
+#define		CAM_WRITE				BIT16
+#define		CAM_READ				0x00000000
+#define		CAM_POLLINIG			BIT31
+
+#define		SCR_UseDK				0x01
+#define		SCR_TxSecEnable		0x02
+#define		SCR_RxSecEnable		0x04
+
+//
+// 10. Power Save Control Registers	 (Offset: 0x0260 - 0x02DF)
+//
+#define		WOW_PMEN				BIT0 // Power management Enable.
+#define		WOW_WOMEN			BIT1 // WoW function on or off.
+#define		WOW_MAGIC				BIT2 // Magic packet
+#define		WOW_UWF				BIT3 // Unicast Wakeup frame.
+
+//
+// 11. General Purpose Registers	(Offset: 0x02E0 - 0x02FF)
+//       8192S GPIO Config Setting (offset 0x2F1, 1 byte)
+//----------------------------------------------------------------------------
+#define		GPIOMUX_EN			BIT3 // When this bit is set to "1", GPIO PINs will switch to MAC GPIO Function
+#define		GPIOSEL_GPIO		0	// UART or JTAG or pure GPIO
+#define		GPIOSEL_PHYDBG		1	// PHYDBG
+#define		GPIOSEL_BT			2	// BT_coex
+#define		GPIOSEL_WLANDBG		3	// WLANDBG
+#define		GPIOSEL_GPIO_MASK	~(BIT0|BIT1)
+
+//----------------------------------------------------------------------------
+
+//----------------------------------------------------------------------------
+// PHY REG Access Report Register definition
+//----------------------------------------------------------------------------
+#define		HST_RDBUSY				BIT0
+#define		CPU_WTBUSY			BIT1
+
+//
+// 12. Host Interrupt Status Registers	 (Offset: 0x0300 - 0x030F)
+//
+//----------------------------------------------------------------------------
+//       8190 IMR/ISR bits						(offset 0xfd,  8bits)
+//----------------------------------------------------------------------------
+#define		IMR8190_DISABLED	0x0
+
+// IMR DW1 Bit 0-31
+#define		IMR_CPUERR			BIT5		// CPU error interrupt
+#define		IMR_ATIMEND			BIT4		// ATIM Window End Interrupt
+#define		IMR_TBDOK			BIT3		// Transmit Beacon OK Interrupt
+#define		IMR_TBDER			BIT2		// Transmit Beacon Error Interrupt
+#define		IMR_BCNDMAINT8		BIT1		// Beacon DMA Interrupt 8
+#define		IMR_BCNDMAINT7		BIT0		// Beacon DMA Interrupt 7
+// IMR DW0 Bit 0-31
+
+#define		IMR_BCNDMAINT6		BIT31		// Beacon DMA Interrupt 6
+#define		IMR_BCNDMAINT5		BIT30		// Beacon DMA Interrupt 5
+#define		IMR_BCNDMAINT4		BIT29		// Beacon DMA Interrupt 4
+#define		IMR_BCNDMAINT3		BIT28		// Beacon DMA Interrupt 3
+#define		IMR_BCNDMAINT2		BIT27		// Beacon DMA Interrupt 2
+#define		IMR_BCNDMAINT1		BIT26		// Beacon DMA Interrupt 1
+#define		IMR_BCNDOK8			BIT25		// Beacon Queue DMA OK Interrup 8
+#define		IMR_BCNDOK7			BIT24		// Beacon Queue DMA OK Interrup 7
+#define		IMR_BCNDOK6			BIT23		// Beacon Queue DMA OK Interrup 6
+#define		IMR_BCNDOK5			BIT22		// Beacon Queue DMA OK Interrup 5
+#define		IMR_BCNDOK4			BIT21		// Beacon Queue DMA OK Interrup 4
+#define		IMR_BCNDOK3			BIT20		// Beacon Queue DMA OK Interrup 3
+#define		IMR_BCNDOK2			BIT19		// Beacon Queue DMA OK Interrup 2
+#define		IMR_BCNDOK1			BIT18		// Beacon Queue DMA OK Interrup 1
+#define		IMR_TIMEOUT2		BIT17		// Timeout interrupt 2
+#define		IMR_TIMEOUT1		BIT16		// Timeout interrupt 1
+#define		IMR_TXFOVW			BIT15		// Transmit FIFO Overflow
+#define		IMR_PSTIMEOUT		BIT14		// Power save time out interrupt
+#define		IMR_BcnInt			BIT13		// Beacon DMA Interrupt 0
+#define		IMR_RXFOVW			BIT12		// Receive FIFO Overflow
+#define		IMR_RDU				BIT11		// Receive Descriptor Unavailable
+#define		IMR_RXCMDOK			BIT10		// Receive Command Packet OK
+#define		IMR_BDOK			BIT9		// Beacon Queue DMA OK Interrup
+#define		IMR_HIGHDOK			BIT8		// High Queue DMA OK Interrupt
+#define		IMR_COMDOK			BIT7		// Command Queue DMA OK Interrupt
+#define		IMR_MGNTDOK			BIT6		// Management Queue DMA OK Interrupt
+#define		IMR_HCCADOK			BIT5		// HCCA Queue DMA OK Interrupt
+#define		IMR_BKDOK			BIT4		// AC_BK DMA OK Interrupt
+#define		IMR_BEDOK			BIT3		// AC_BE DMA OK Interrupt
+#define		IMR_VIDOK			BIT2		// AC_VI DMA OK Interrupt
+#define		IMR_VODOK			BIT1		// AC_VO DMA Interrupt
+#define		IMR_ROK				BIT0		// Receive DMA OK Interrupt
+
+//
+// 13. Test Mode and Debug Control Registers	(Offset: 0x0310 - 0x034F)
+//
+
+//
+// 14. PCIE config register	(Offset 0x500-)
+//
+//----------------------------------------------------------------------------
+//       8190 TPPool bits 					(offset 0xd9, 2 byte)
+//----------------------------------------------------------------------------
+#define		TPPoll_BKQ			BIT0			// BK queue polling
+#define		TPPoll_BEQ			BIT1			// BE queue polling
+#define		TPPoll_VIQ			BIT2			// VI queue polling
+#define		TPPoll_VOQ			BIT3			// VO queue polling
+#define		TPPoll_BQ			BIT4			// Beacon queue polling
+#define		TPPoll_CQ			BIT5			// Command queue polling
+#define		TPPoll_MQ			BIT6			// Management queue polling
+#define		TPPoll_HQ			BIT7			// High queue polling
+#define		TPPoll_HCCAQ		BIT8			// HCCA queue polling
+#define		TPPoll_StopBK		BIT9			// Stop BK queue
+#define		TPPoll_StopBE		BIT10			// Stop BE queue
+#define		TPPoll_StopVI		BIT11			// Stop VI queue
+#define		TPPoll_StopVO		BIT12			// Stop VO queue
+#define		TPPoll_StopMgt		BIT13			// Stop Mgnt queue
+#define		TPPoll_StopHigh		BIT14			// Stop High queue
+#define		TPPoll_StopHCCA		BIT15			// Stop HCCA queue
+#define		TPPoll_SHIFT		8				// Queue ID mapping
+
+//----------------------------------------------------------------------------
+//       8192S PCIF 							(Offset 0x500, 32bit)
+//----------------------------------------------------------------------------
+#define		MXDMA2_16bytes		0x000
+#define		MXDMA2_32bytes		0x001
+#define		MXDMA2_64bytes		0x010
+#define		MXDMA2_128bytes		0x011
+#define		MXDMA2_256bytes		0x100
+#define		MXDMA2_512bytes		0x101
+#define		MXDMA2_1024bytes	0x110
+#define		MXDMA2_NoLimit		0x7
+
+#define		MULRW_SHIFT			3
+#define		MXDMA2_RX_SHIFT		4
+#define		MXDMA2_TX_SHIFT		0
+
+//----------------------------------------------------------------------------
+//       8190 CCX_COMMAND_REG Setting (offset 0x25A, 1 byte)
+//----------------------------------------------------------------------------
+#define		CCX_CMD_CLM_ENABLE				BIT0	// Enable Channel Load
+#define		CCX_CMD_NHM_ENABLE				BIT1	// Enable Noise Histogram
+#define		CCX_CMD_FUNCTION_ENABLE			BIT8
+// CCX function (Channel Load/RPI/Noise Histogram).
+#define		CCX_CMD_IGNORE_CCA				BIT9
+// Treat CCA period as IDLE time for NHM.
+#define		CCX_CMD_IGNORE_TXON				BIT10
+// Treat TXON period as IDLE time for NHM.
+#define		CCX_CLM_RESULT_READY			BIT16
+// 1: Indicate the result of Channel Load is ready.
+#define		CCX_NHM_RESULT_READY			BIT16
+// 1: Indicate the result of Noise histogram is ready.
+#define		CCX_CMD_RESET					0x0
+// Clear all the result of CCX measurement and disable the CCX function.
+
+
+//----------------------------------------------------------------------------
+// 8192S EFUSE
+//----------------------------------------------------------------------------
+//#define		HWSET_MAX_SIZE_92S				128
+
+
+//----------------------------------------------------------------------------
+//       8192S EEPROM/EFUSE share register definition.
+//----------------------------------------------------------------------------
+
+#ifdef RTL8192SE
+//
+// 2008/11/05 MH Redefine EEPROM address for 8192SE
+// 92SE/SU EEPROM definition seems not the same!!!!!!
+// EEPROM MAP REgister Definition!!!! Please refer to 8192SE EEPROM V0.5 2008/10/21
+// Update to 8192SE EEPROM V0.6 2008/11/11
+//
+#define 		RTL8190_EEPROM_ID				0x8129	// 0-1
+#define 		EEPROM_HPON					0x02 // LDO settings.2-5
+#define 		EEPROM_CLK						0x06 // Clock settings.6-7
+#define 		EEPROM_TESTR					0x08 // SE Test mode.8
+
+#define 		EEPROM_VID						0x0A // SE Vendor ID.A-B
+#define 		EEPROM_DID						0x0C // SE Device ID. C-D
+#define 		EEPROM_SVID					0x0E // SE Vendor ID.E-F
+#define 		EEPROM_SMID					0x10 // SE PCI Subsystem ID. 10-11
+
+#define 		EEPROM_MAC_ADDR				0x12 // SEMAC Address. 12-17
+#define 		EEPROM_NODE_ADDRESS_BYTE_0	0x12 // MAC address.
+
+#define 		EEPROM_PwDiff					0x54 // Difference of gain index between legacy and high throughput OFDM.
+
+//
+// 0x20 - 4B EPHY parameter!!!
+//
+//
+#define 		EEPROM_TxPowerBase			0x50 // Tx Power of serving station.
+#define 		EEPROM_TxPwIndex_CCK_24G	0x5D // 0x50~0x5D Range = 0~0x24//FIXLZM
+#define 		EEPROM_TxPwIndex_OFDM_24G	0x6B // 0x5E~0x6B Range = 0~0x24//FIXLZM
+#define		EEPROM_TX_PWR_INDEX_RANGE	28		// CCK and OFDM 14 channel
+
+
+// 2009/01/21 MH Add for SD3 requirement
+#define 		EEPROM_TX_PWR_HT20_DIFF		0x62// HT20 Tx Power Index Difference
+#define 		DEFAULT_HT20_TXPWR_DIFF		2	// HT20<->40 default Tx Power Index Difference
+#define 		EEPROM_TX_PWR_OFDM_DIFF		0x65// OFDM Tx Power Index Difference
+#define 		EEPROM_TX_PWR_BAND_EDGE	0x67// TX Power offset at band-edge channel
+#define 		TX_PWR_BAND_EDGE_CHK		0x6D// Check if band-edge scheme is enabled
+
+// Oly old EEPROM format support the definition=============================
+//
+#define 		EEPROM_TxPwIndex_CCK_24G	0x5D // 0x50~0x5D Range = 0~0x24
+#define 		EEPROM_TxPwIndex_OFDM_24G	0x6B // 0x5E~0x6B Range = 0~0x24
+#define 		EEPROM_HT2T_CH1_A			0x6c //HT 2T path A channel 1 Power Index.
+#define 		EEPROM_HT2T_CH7_A			0x6d //HT 2T path A channel 7 Power Index.
+#define 		EEPROM_HT2T_CH13_A			0x6e //HT 2T path A channel 13 Power Index.
+#define 		EEPROM_HT2T_CH1_B			0x6f //HT 2T path B channel 1 Power Index.
+#define 		EEPROM_HT2T_CH7_B			0x70 //HT 2T path B channel 7 Power Index.
+#define 		EEPROM_HT2T_CH13_B			0x71 //HT 2T path B channel 13 Power Index.
+//
+#define 		EEPROM_TSSI_A					0x74 //TSSI value of path A.
+#define 		EEPROM_TSSI_B					0x75 //TSSI value of path B.
+//
+#define		EEPROM_RFInd_PowerDiff				0x76
+#define		EEPROM_Default_LegacyHTTxPowerDiff	0x3
+//
+#define 		EEPROM_ThermalMeter			0x77 // Thermal meter default value.
+#define 		EEPROM_CrystalCap				0x79 // Crystal Cap.
+#define 		EEPROM_ChannelPlan				0x7B // Map of supported channels.
+#define 		EEPROM_Version					0x7C // The EEPROM content version
+#define		EEPROM_CustomID				0x7A
+#define 		EEPROM_BoardType				0x7E
+// 0: 2x2 Green RTL8192GE miniCard (QFN68)
+// 1: 1x2            RTL8191SE miniCard (QFN64)
+// 2: 2x2            RTL8192SE miniCard (QFN68)
+// 3: 1x2            RTL8191SR minicCard(QFN64)
+
+//
+// Default Value for EEPROM or EFUSE!!!
+//
+#define		EEPROM_Default_TSSI			0x0
+#define 		EEPROM_Default_TxPowerDiff		0x0
+#define 		EEPROM_Default_CrystalCap		0x5
+#define 		EEPROM_Default_BoardType		0x02 // Default: 2X2, RTL8192SE(QFPN68)
+#define 		EEPROM_Default_TxPower		0x1010
+#define		EEPROM_Default_HT2T_TxPwr		0x10
+
+#ifdef EEPROM_OLD_FORMAT_SUPPORT
+#define 		EEPROM_Default_TxPowerBase	0x0
+#define 		EEPROM_Default_ThermalMeter	0x12
+#define 		EEPROM_Default_PwDiff			0x4
+#else
+#define		EEPROM_Default_LegacyHTTxPowerDiff	0x3
+#define		EEPROM_Default_ThermalMeter		0x12
+#define		EEPROM_Default_AntTxPowerDiff		0x0
+#define		EEPROM_Default_TxPwDiff_CrystalCap	0x5
+#define		EEPROM_Default_TxPowerLevel		0x22
+#endif
+
+#define		EEPROM_CHANNEL_PLAN_FCC				0x0
+#define		EEPROM_CHANNEL_PLAN_IC				0x1
+#define		EEPROM_CHANNEL_PLAN_ETSI			0x2
+#define		EEPROM_CHANNEL_PLAN_SPAIN			0x3
+#define		EEPROM_CHANNEL_PLAN_FRANCE			0x4
+#define		EEPROM_CHANNEL_PLAN_MKK				0x5
+#define		EEPROM_CHANNEL_PLAN_MKK1			0x6
+#define		EEPROM_CHANNEL_PLAN_ISRAEL			0x7
+#define		EEPROM_CHANNEL_PLAN_TELEC			0x8
+#define		EEPROM_CHANNEL_PLAN_GLOBAL_DOMAIN	0x9
+#define		EEPROM_CHANNEL_PLAN_WORLD_WIDE_13	0xA
+#define		EEPROM_CHANNEL_PLAN_BY_HW_MASK	0x80
+
+
+#define 		EEPROM_CID_DEFAULT					0x0
+#define 		EEPROM_CID_TOSHIBA			0x4
+#else
+//----------------------------------------------------------------------------
+//       8192S EEROM and Compatible E-Fuse definition. Added by Roger, 2008.10.21.
+//----------------------------------------------------------------------------
+#define 		RTL8190_EEPROM_ID				0x8129
+#define 		EEPROM_HPON					0x02 // LDO settings.
+#define 		EEPROM_VID						0x08 // USB Vendor ID.
+#define 		EEPROM_PID						0x0A // USB Product ID.
+#define 		EEPROM_USB_OPTIONAL			0x0C // For optional function.
+#define 		EEPROM_USB_PHY_PARA1			0x0D // For fine tune USB PHY.
+#define 		EEPROM_NODE_ADDRESS_BYTE_0	0x12 // MAC address.
+#define 		EEPROM_TxPowerDiff				0x1F
+
+#define 		EEPROM_Version					0x50
+#define 		EEPROM_ChannelPlan				0x51 // Map of supported channels.
+#define		EEPROM_CustomID				0x52
+#define 		EEPROM_SubCustomID			0x53 // Reserved  for customer use.
+
+
+	// <Roger_Notes> The followin are for different version of EEPROM contents purpose. 2008.11.22.
+#ifdef EEPROM_OLD_FORMAT_SUPPORT
+#define 		EEPROM_PwDiff					0x54 // Difference of gain index between legacy and high throughput OFDM.
+#define 		EEPROM_ThermalMeter			0x55 // Thermal meter default value.
+#define 		EEPROM_Reserved				0x56 // Reserved.
+#define 		EEPROM_CrystalCap				0x57 // Crystal Cap.
+#define 		EEPROM_TxPowerBase			0x58 // Tx Power of serving station.
+#define 		EEPROM_TxPwIndex_CCK_24G	0x59 // 0x59~0x66
+#define 		EEPROM_TxPwIndex_OFDM_24G	0x67 // 0x67~0x74
+#define 		EEPROM_TSSI_A					0x75 //TSSI value of path A.
+#define 		EEPROM_TSSI_B					0x76 //TSSI value of path B.
+#define 		EEPROM_TxPwTkMode			0x77 //Tx Power tracking mode.
+#define 		EEPROM_HT2T_CH1_A			0x78 //HT 2T path A channel 1 Power Index.
+#define 		EEPROM_HT2T_CH7_A			0x79 //HT 2T path A channel 7 Power Index.
+#define 		EEPROM_HT2T_CH13_A			0x7a //HT 2T path A channel 13 Power Index.
+#define 		EEPROM_HT2T_CH1_B			0x7b //HT 2T path B channel 1 Power Index.
+#define 		EEPROM_HT2T_CH7_B			0x7c //HT 2T path B channel 7 Power Index.
+#define 		EEPROM_HT2T_CH13_B			0x7d //HT 2T path B channel 13 Power Index.
+#define 		EEPROM_BoardType				0x7e //0x0: RTL8188SU, 0x1: RTL8191SU, 0x2: RTL8192SU, 0x3: RTL8191GU
+#else
+#define 		EEPROM_BoardType				0x54 //0x0: RTL8188SU, 0x1: RTL8191SU, 0x2: RTL8192SU, 0x3: RTL8191GU
+#define		EEPROM_TxPwIndex				0x55 //0x55-0x66, Tx Power index.
+#define 		EEPROM_PwDiff					0x67 // Difference of gain index between legacy and high throughput OFDM.
+#define 		EEPROM_ThermalMeter			0x68 // Thermal meter default value.
+#define 		EEPROM_CrystalCap				0x69 // Crystal Cap.
+#define 		EEPROM_TxPowerBase			0x6a // Tx Power of serving station.
+#define 		EEPROM_TSSI_A					0x6b //TSSI value of path A.
+#define 		EEPROM_TSSI_B					0x6c //TSSI value of path B.
+#define 		EEPROM_TxPwTkMode			0x6d //Tx Power tracking mode.
+//#define 		EEPROM_Reserved				0x6e //0x6e-0x7f, reserved.
+
+// 2009/02/09 Cosa Add for SD3 requirement
+#define 		EEPROM_TX_PWR_HT20_DIFF		0x6e// HT20 Tx Power Index Difference
+#define 		DEFAULT_HT20_TXPWR_DIFF		2	// HT20<->40 default Tx Power Index Difference
+#define 		EEPROM_TX_PWR_OFDM_DIFF		0x71// OFDM Tx Power Index Difference
+#define 		EEPROM_TX_PWR_BAND_EDGE	0x73// TX Power offset at band-edge channel
+#define 		TX_PWR_BAND_EDGE_CHK		0x79// Check if band-edge scheme is enabled
+#endif
+#define		EEPROM_Default_LegacyHTTxPowerDiff	0x3
+#define		EEPROM_USB_Default_OPTIONAL_FUNC	0x8
+#define		EEPROM_USB_Default_PHY_PARAM		0x0
+#define		EEPROM_Default_TSSI			0x0
+#define		EEPROM_Default_TxPwrTkMode	0x0
+#define 		EEPROM_Default_TxPowerDiff		0x0
+#define 		EEPROM_Default_TxPowerBase	0x0
+#define 		EEPROM_Default_ThermalMeter	0x7
+#define 		EEPROM_Default_PwDiff			0x4
+#define 		EEPROM_Default_CrystalCap		0x5
+#define 		EEPROM_Default_TxPower		0x1010
+#define 		EEPROM_Default_BoardType		0x02 // Default: 2X2, RTL8192SU(QFPN68)
+#define		EEPROM_Default_HT2T_TxPwr		0x10
+#define		EEPROM_USB_SN					BIT0
+#define		EEPROM_USB_REMOTE_WAKEUP	BIT1
+#define		EEPROM_USB_DEVICE_PWR		BIT2
+#define		EEPROM_EP_NUMBER				(BIT3|BIT4)
+
+#define		EEPROM_CHANNEL_PLAN_FCC				0x0
+#define		EEPROM_CHANNEL_PLAN_IC				0x1
+#define		EEPROM_CHANNEL_PLAN_ETSI			0x2
+#define		EEPROM_CHANNEL_PLAN_SPAIN			0x3
+#define		EEPROM_CHANNEL_PLAN_FRANCE			0x4
+#define		EEPROM_CHANNEL_PLAN_MKK				0x5
+#define		EEPROM_CHANNEL_PLAN_MKK1			0x6
+#define		EEPROM_CHANNEL_PLAN_ISRAEL			0x7
+#define		EEPROM_CHANNEL_PLAN_TELEC			0x8
+#define		EEPROM_CHANNEL_PLAN_GLOBAL_DOMAIN	0x9
+#define		EEPROM_CHANNEL_PLAN_WORLD_WIDE_13	0xA
+#define		EEPROM_CHANNEL_PLAN_BY_HW_MASK	0x80
+
+#define 		EEPROM_CID_DEFAULT				0x0
+#define 		EEPROM_CID_ALPHA				0x1
+#define		EEPROM_CID_CAMEO					0X8
+#define 		EEPROM_CID_SITECOM				0x9
+
+//#define EEPROM_CID_RUNTOP						0x2
+//#define EEPROM_CID_Senao						0x3
+//#define EEPROM_CID_TOSHIBA						0x4
+//#define EEPROM_CID_NetCore						0x5
+#define 		EEPROM_CID_WHQL 				0xFE // added by chiyoko for dtm, 20090108
+#endif
+
+//-----------------------------------------------------------------
+// 0x2c0 FW Command Control register definition, added by Roger, 2008.11.27.
+//-----------------------------------------------------------------
+#define		FW_DIG_DISABLE				0xfd00cc00
+#define		FW_DIG_ENABLE					0xfd000000
+#define		FW_DIG_HALT					0xfd000001
+#define		FW_DIG_RESUME					0xfd000002
+#define		FW_HIGH_PWR_DISABLE			0xfd000008
+#define		FW_HIGH_PWR_ENABLE			0xfd000009
+#define		FW_TXPWR_TRACK_ENABLE		0xfd000017
+#define		FW_TXPWR_TRACK_DISABLE		0xfd000018
+#define		FW_RA_RESET					0xfd0000af
+#define		FW_RA_ACTIVE					0xfd0000a6
+#define		FW_RA_REFRESH					0xfd0000a0
+#define		FW_RA_ENABLE_BG				0xfd0000ac
+#define		FW_IQK_ENABLE					0xf0000020
+#define		FW_IQK_SUCCESS				0x0000dddd
+#define		FW_IQK_FAIL					0x0000ffff
+#define		FW_OP_FAILURE					0xffffffff
+#define		FW_DM_DISABLE					0xfd00aa00
+#define		FW_BB_RESET_ENABLE			0xff00000d
+#define		FW_BB_RESET_DISABLE			0xff00000e
+#if 0
+//----------------------------------------------------------------------------
+//       8190 EEROM
+//----------------------------------------------------------------------------
+#define		RTL8190_EEPROM_ID					0x8129
+//#define		EEPROM_NODE_ADDRESS_BYTE_0			0x0C
+
+#define		EEPROM_RFInd_PowerDiff				0x28
+#define		EEPROM_ThermalMeter					0x29
+#define		EEPROM_TxPwDiff_CrystalCap			0x2A	//0x2A~0x2B
+#define		EEPROM_TxPwIndex_CCK				0x2C	//0x2C~0x39
+#define		EEPROM_TxPwIndex_OFDM_24G			0x3A	//0x3A~0x47
+#define		EEPROM_TxPwIndex_OFDM_5G			0x34	//0x34~0x7B
+
+//The following definition is for eeprom 93c56......modified 20080220
+#define		EEPROM_C56_CrystalCap				0x17	//0x17
+#define		EEPROM_C56_RfA_CCK_Chnl1_TxPwIndex	0x80	//0x80
+#define		EEPROM_C56_RfA_HT_OFDM_TxPwIndex	0x81	//0x81~0x83
+#define		EEPROM_C56_RfC_CCK_Chnl1_TxPwIndex	0xbc	//0xb8
+#define		EEPROM_C56_RfC_HT_OFDM_TxPwIndex	0xb9	//0xb9~0xbb
+#define		EEPROM_Customer_ID					0x7B	//0x7B:CustomerID
+#define		EEPROM_ICVersion_ChannelPlan		0x7C	//0x7C:ChnlPlan,
+														//0x7D:IC_Ver
+#define		EEPROM_CRC							0x7E	//0x7E~0x7F
+
+#define		EEPROM_Default_LegacyHTTxPowerDiff	0x4
+#define		EEPROM_Default_ThermalMeter			0x77
+#define		EEPROM_Default_AntTxPowerDiff		0x0
+#define		EEPROM_Default_TxPwDiff_CrystalCap	0x5
+#define		EEPROM_Default_TxPower				0x1010
+#define		EEPROM_Default_TxPowerLevel			0x10
+
+//
+// Define Different EEPROM type for customer
+//
+#define		EEPROM_CID_DEFAULT					0x0
+#define		EEPROM_CID_CAMEO					0x1
+#define		EEPROM_CID_RUNTOP					0x2
+#define		EEPROM_CID_Senao					0x3
+#define		EEPROM_CID_TOSHIBA					0x4
+#define		EEPROM_CID_NetCore					0x5
+#define		EEPROM_CID_Nettronix				0x6
+#define		EEPROM_CID_Pronet					0x7
+
+#endif
+
+//
+//--------------92SU require delete or move to other place later
+//
+
+
+
+//
+//
+// 2008/08/06 MH For share the same 92S source/header files, we copy some
+// definition to pass 92SU compiler. But we must delete thm later.
+//
+//
+
+//============================================================================
+//       819xUsb Regsiter offset definition
+//============================================================================
+
+//2 define it temp!!!
+#define RFPC					0x5F			// Rx FIFO Packet Count
+#define RCR_9356SEL			BIT6
+#define TCR_LRL_OFFSET		0
+#define TCR_SRL_OFFSET		8
+#define TCR_MXDMA_OFFSET	21
+#define TCR_MXDMA_2048 		7
+#define TCR_SAT				BIT24		// Enable Rate depedent ack timeout timer
+#define RCR_MXDMA_OFFSET	8
+#define RCR_FIFO_OFFSET		13
+#define RCR_OnlyErlPkt		BIT31				// Rx Early mode is performed for packet size greater than 1536
+#define CWR					0xDC			// Contention window register
+#define RetryCTR				0xDE			// Retry Count register
+
+
+// For backward compatible for 9xUSB
+#define		LED1Cfg				UnusedRegister	// LED1 Configuration Register
+#define 	LED0Cfg				UnusedRegister	// LED0 Configuration Register
+#define 	GPI					UnusedRegister	// LED0 Configuration Register
+#define 	BRSR				UnusedRegister	// LED0 Configuration Register
+#define 	CPU_GEN				UnusedRegister	// LED0 Configuration Register
+#define 	SIFS				UnusedRegister	// LED0 Configuration Register
+
+//----------------------------------------------------------------------------
+//       8190 CPU General Register		(offset 0x100, 4 byte)
+//----------------------------------------------------------------------------
+//#define 	CPU_CCK_LOOPBACK			0x00030000
+#define 	CPU_GEN_SYSTEM_RESET		0x00000001
+//#define 	CPU_GEN_FIRMWARE_RESET	0x00000008
+//#define 	CPU_GEN_BOOT_RDY			0x00000010
+//#define 	CPU_GEN_FIRM_RDY			0x00000020
+//#define 	CPU_GEN_PUT_CODE_OK		0x00000080
+//#define 	CPU_GEN_BB_RST			0x00000100
+//#define 	CPU_GEN_PWR_STB_CPU		0x00000004
+//#define 	CPU_GEN_NO_LOOPBACK_MSK	0xFFF8FFFF		// Set bit18,17,16 to 0. Set bit19
+//#define 	CPU_GEN_NO_LOOPBACK_SET	0x00080000		// Set BIT19 to 1
+
+//----------------------------------------------------------------------------
+//       8192S EEROM
+//----------------------------------------------------------------------------
+
+//#define RTL8190_EEPROM_ID				0x8129
+//#define EEPROM_VID						0x08
+//#define EEPROM_PID						0x0A
+//#define EEPROM_USB_OPTIONAL			0x0C
+//#define EEPROM_NODE_ADDRESS_BYTE_0	0x12
+//
+//#define EEPROM_TxPowerDiff				0x1F
+//#define EEPROM_ThermalMeter			0x20
+//#define EEPROM_PwDiff					0x21	//0x21
+//#define EEPROM_CrystalCap				0x22	//0x22
+//
+//#define EEPROM_TxPwIndex_CCK			0x23	//0x23
+//#define EEPROM_TxPwIndex_OFDM_24G	0x24	//0x24~0x26
+#define EEPROM_TxPwIndex_CCK_V1			0x29	//0x29~0x2B
+#define EEPROM_TxPwIndex_OFDM_24G_V1	0x2C	//0x2C~0x2E
+#define EEPROM_TxPwIndex_Ver				0x27	//0x27
+//
+//#define EEPROM_Default_TxPowerDiff		0x0
+//#define EEPROM_Default_ThermalMeter	0x7
+//#define EEPROM_Default_PwDiff			0x4
+//#define EEPROM_Default_CrystalCap		0x5
+//#define EEPROM_Default_TxPower			0x1010
+//#define EEPROM_Customer_ID				0x7B	//0x7B:CustomerID
+//#define EEPROM_Version					0x50	// 0x50
+//#define EEPROM_CustomID				0x52
+//#define EEPROM_ChannelPlan				0x7c	//0x7C
+//#define EEPROM_IC_VER					0x7d	//0x7D
+//#define EEPROM_CRC						0x7e	//0x7E~0x7F
+//
+//
+//#define EEPROM_CID_DEFAULT			0x0
+//#define EEPROM_CID_CAMEO				0x1
+//#define EEPROM_CID_RUNTOP				0x2
+//#define EEPROM_CID_Senao				0x3
+//#define EEPROM_CID_TOSHIBA				0x4	// Toshiba setting, Merge by Jacken, 2008/01/31
+//#define EEPROM_CID_NetCore				0x5
+
+
+//
+//--------------92SU require delete or move to other place later
+//
+
+//============================================================
+// CCX Related Register
+//============================================================
+#define		CCX_COMMAND_REG			0x890
+// CCX Measurement Command Register. 4 Bytes.
+// Bit[0]: R_CLM_En, 1=enable, 0=disable. Enable or disable "Channel Load
+// Measurement (CLM)".
+// Bit[1]: R_NHM_En, 1=enable, 0=disable. Enable or disalbe "Noise Histogram
+// Measurement (NHM)".
+// Bit[2~7]: Reserved
+// Bit[8]: R_CCX_En: 1=enable, 0=disable. Enable or disable CCX function.
+// Note: After clearing this bit, all the result of all NHM_Result and CLM_
+// Result are cleared concurrently.
+// Bit[9]: R_Ignore_CCA: 1=enable, 0=disable. Enable means that treat CCA
+// period as idle time for NHM.
+// Bit[10]: R_Ignore_TXON: 1=enable, 0=disable. Enable means that treat TXON
+// period as idle time for NHM.
+// Bit[11~31]: Reserved.
+#define		CLM_PERIOD_REG			0x894
+// CCX Measurement Period Register, in unit of 4us. 2 Bytes.
+#define		NHM_PERIOD_REG			0x896
+// Noise Histogram Measurement Period Register, in unit of 4us. 2Bytes.
+#define		NHM_THRESHOLD0			0x898	// Noise Histogram Meashorement0
+#define		NHM_THRESHOLD1			0x899	// Noise Histogram Meashorement1
+#define		NHM_THRESHOLD2			0x89A	// Noise Histogram Meashorement2
+#define		NHM_THRESHOLD3			0x89B	// Noise Histogram Meashorement3
+#define		NHM_THRESHOLD4			0x89C	// Noise Histogram Meashorement4
+#define		NHM_THRESHOLD5			0x89D	// Noise Histogram Meashorement5
+#define		NHM_THRESHOLD6			0x89E	// Noise Histogram Meashorement6
+#define		CLM_RESULT_REG			0x8D0
+// Channel Load result register. 4 Bytes.
+// Bit[0~15]: Total measured duration of CLM. The CCA busy fraction is caculate
+// by CLM_RESULT_REG/CLM_PERIOD_REG.
+// Bit[16]: Indicate the CLM result is ready.
+// Bit[17~31]: Reserved.
+#define		NHM_RESULT_REG			0x8D4
+// Noise Histogram result register. 4 Bytes.
+// Bit[0~15]: Total measured duration of NHM. If R_Ignore_CCA=1 or
+// R_Ignore_TXON=1, this value will be less than NHM_PERIOD_REG.
+// Bit[16]: Indicate the NHM result is ready.
+// Bit[17~31]: Reserved.
+#define		NHM_RPI_COUNTER0		0x8D8
+// NHM RPI counter0, the fraction of signal strength < NHM_THRESHOLD0.
+#define		NHM_RPI_COUNTER1		0x8D9
+// NHM RPI counter1, the fraction of signal stren in NHM_THRESH0, NHM_THRESH1
+#define		NHM_RPI_COUNTER2		0x8DA
+// NHM RPI counter2, the fraction of signal stren in NHM_THRESH2, NHM_THRESH3
+#define		NHM_RPI_COUNTER3		0x8DB
+// NHM RPI counter3, the fraction of signal stren in NHM_THRESH4, NHM_THRESH5
+#define		NHM_RPI_COUNTER4		0x8DC
+// NHM RPI counter4, the fraction of signal stren in NHM_THRESH6, NHM_THRESH7
+#define		NHM_RPI_COUNTER5		0x8DD
+// NHM RPI counter5, the fraction of signal stren in NHM_THRESH8, NHM_THRESH9
+#define		NHM_RPI_COUNTER6		0x8DE
+// NHM RPI counter6, the fraction of signal stren in NHM_THRESH10, NHM_THRESH11
+#define		NHM_RPI_COUNTER7		0x8DF
+// NHM RPI counter7, the fraction of signal stren in NHM_THRESH12, NHM_THRESH13
+
+#define HAL_RETRY_LIMIT_INFRA							48
+#define HAL_RETRY_LIMIT_AP_ADHOC						7
+
+// HW Readio OFF switch (GPIO BIT)
+#define		HAL_8192S_HW_GPIO_OFF_BIT	BIT3
+#define		HAL_8192S_HW_GPIO_OFF_MASK	0xF7
+#define		HAL_8192S_HW_GPIO_WPS_BIT	BIT4
+
+#endif  //R8192S_HW
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/drivers/staging/rtl8192su/r8192S_phy.c b/drivers/staging/rtl8192su/r8192S_phy.c
new file mode 100644
index 0000000..99a4051a
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_phy.c
@@ -0,0 +1,5028 @@
+/******************************************************************************
+
+     (c) Copyright 2008, RealTEK Technologies Inc. All Rights Reserved.
+
+ Module:	hal8192sphy.c
+
+ Note:		Merge 92SE/SU PHY config as below
+			1. BB register R/W API
+ 			2. RF register R/W API
+ 			3. Initial BB/RF/MAC config by reading BB/MAC/RF txt.
+ 			3. Power setting API
+ 			4. Channel switch API
+ 			5. Initial gain switch API.
+ 			6. Other BB/MAC/RF API.
+
+ Function:	PHY: Extern function, phy: local function
+
+ Export:	PHY_FunctionName
+
+ Abbrev:	NONE
+
+ History:
+	Data		Who		Remark
+	08/08/2008  MHC    	1. Port from 9x series phycfg.c
+						2. Reorganize code arch and ad description.
+						3. Collect similar function.
+						4. Seperate extern/local API.
+	08/12/2008	MHC		We must merge or move USB PHY relative function later.
+	10/07/2008	MHC		Add IQ calibration for PHY.(Only 1T2R mode now!!!)
+	11/06/2008	MHC		Add TX Power index PG file to config in 0xExx register
+						area to map with EEPROM/EFUSE tx pwr index.
+
+******************************************************************************/
+#include "r8192U.h"
+#include "r8192U_dm.h"
+#include "r8192S_rtl6052.h"
+
+#ifdef RTL8192SU
+#include "r8192S_hw.h"
+#include "r8192S_phy.h"
+#include "r8192S_phyreg.h"
+#include "r8192SU_HWImg.h"
+//#include "r8192S_FwImgDTM.h"
+#else
+#include "r8192U_hw.h"
+#include "r819xU_phy.h"
+#include "r819xU_phyreg.h"
+#endif
+
+#ifdef ENABLE_DOT11D
+#include "dot11d.h"
+#endif
+
+/*---------------------------Define Local Constant---------------------------*/
+/* Channel switch:The size of command tables for switch channel*/
+#define MAX_PRECMD_CNT 16
+#define MAX_RFDEPENDCMD_CNT 16
+#define MAX_POSTCMD_CNT 16
+#define MAX_DOZE_WAITING_TIMES_9x 64
+
+/*------------------------Define local variable------------------------------*/
+// 2004-05-11
+#ifndef RTL8192SU
+static u32	RF_CHANNEL_TABLE_ZEBRA[]={
+		0,
+		0x085c,//2412 1
+		0x08dc,//2417 2
+		0x095c,//2422 3
+		0x09dc,//2427 4
+		0x0a5c,//2432 5
+		0x0adc,//2437 6
+		0x0b5c,//2442 7
+		0x0bdc,//2447 8
+		0x0c5c,//2452 9
+		0x0cdc,//2457 10
+		0x0d5c,//2462 11
+		0x0ddc,//2467 12
+		0x0e5c,//2472 13
+		//0x0f5c,//2484
+		0x0f72,//2484  //20040810
+};
+#endif
+
+static	u32
+phy_CalculateBitShift(u32 BitMask);
+static	RT_STATUS
+phy_ConfigMACWithHeaderFile(struct net_device* dev);
+static void
+phy_InitBBRFRegisterDefinition(struct net_device* dev);
+static	RT_STATUS
+phy_BB8192S_Config_ParaFile(struct net_device* dev);
+static	RT_STATUS
+phy_ConfigBBWithHeaderFile(struct net_device* dev,u8 ConfigType);
+static bool
+phy_SetRFPowerState8192SU(struct net_device* dev,RT_RF_POWER_STATE eRFPowerState);
+void
+SetBWModeCallback8192SUsbWorkItem(struct net_device *dev);
+void
+SetBWModeCallback8192SUsbWorkItem(struct net_device *dev);
+void
+SwChnlCallback8192SUsbWorkItem(struct net_device *dev );
+static void
+phy_FinishSwChnlNow(struct net_device* dev,u8 channel);
+static bool
+phy_SwChnlStepByStep(
+	struct net_device* dev,
+	u8		channel,
+	u8		*stage,
+	u8		*step,
+	u32		*delay
+	);
+static RT_STATUS
+phy_ConfigBBWithPgHeaderFile(struct net_device* dev,u8 ConfigType);
+#ifdef RTL8192SE
+static  u32 phy_FwRFSerialRead( struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 Offset);
+static u32 phy_RFSerialRead(struct net_device* dev,RF90_RADIO_PATH_E eRFPath,u32 Offset);
+static	void phy_FwRFSerialWrite( struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 Offset, u32 Data);
+static void phy_RFSerialWrite( struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 Offset, u32 Data);
+#endif
+static long phy_TxPwrIdxToDbm( struct net_device* dev, WIRELESS_MODE   WirelessMode, u8 TxPwrIdx);
+static u8 phy_DbmToTxPwrIdx( struct net_device* dev, WIRELESS_MODE WirelessMode, long PowerInDbm);
+void phy_SetFwCmdIOCallback(struct net_device* dev);
+
+//#if ((HAL_CODE_BASE == RTL8192_S) && (DEV_BUS_TYPE==USB_INTERFACE))
+#ifdef RTL8192SU
+//
+// Description:
+//	Base Band read by 4181 to make sure that operation could be done in unlimited cycle.
+//
+// Assumption:
+//		-	Only use on RTL8192S USB interface.
+//		-	PASSIVE LEVEL
+//
+// Created by Roger, 2008.09.06.
+//
+//use in phy only
+u32 phy_QueryUsbBBReg(struct net_device* dev, u32	RegAddr)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32	ReturnValue = 0xffffffff;
+	u8	PollingCnt = 50;
+	u8	BBWaitCounter = 0;
+
+
+	//
+	// <Roger_Notes> Due to PASSIVE_LEVEL, so we ONLY simply busy waiting for a while here.
+	// We have to make sure that previous BB I/O has been done.
+	// 2008.08.20.
+	//
+	while(priv->bChangeBBInProgress)
+	{
+		BBWaitCounter ++;
+		RT_TRACE(COMP_RF, "phy_QueryUsbBBReg(): Wait 1 ms (%d times)...\n", BBWaitCounter);
+		msleep(1); // 1 ms
+
+		// Wait too long, return FALSE to avoid to be stuck here.
+		if((BBWaitCounter > 100) )//||RT_USB_CANNOT_IO(Adapter))
+		{
+			RT_TRACE(COMP_RF, "phy_QueryUsbBBReg(): (%d) Wait too logn to query BB!!\n", BBWaitCounter);
+			return ReturnValue;
+		}
+	}
+
+	priv->bChangeBBInProgress = true;
+
+	read_nic_dword(dev, RegAddr);
+
+	do
+	{// Make sure that access could be done.
+		if((read_nic_byte(dev, PHY_REG)&HST_RDBUSY) == 0)
+			break;
+	}while( --PollingCnt );
+
+	if(PollingCnt == 0)
+	{
+		RT_TRACE(COMP_RF, "Fail!!!phy_QueryUsbBBReg(): RegAddr(%#x) = %#x\n", RegAddr, ReturnValue);
+	}
+	else
+	{
+		// Data FW read back.
+		ReturnValue = read_nic_dword(dev, PHY_REG_DATA);
+		RT_TRACE(COMP_RF, "phy_QueryUsbBBReg(): RegAddr(%#x) = %#x, PollingCnt(%d)\n", RegAddr, ReturnValue, PollingCnt);
+	}
+
+	priv->bChangeBBInProgress = false;
+
+	return ReturnValue;
+}
+
+
+
+//
+// Description:
+//	Base Band wrote by 4181 to make sure that operation could be done in unlimited cycle.
+//
+// Assumption:
+//		-	Only use on RTL8192S USB interface.
+//		-	PASSIVE LEVEL
+//
+// Created by Roger, 2008.09.06.
+//
+//use in phy only
+void
+phy_SetUsbBBReg(struct net_device* dev,u32	RegAddr,u32 Data)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8	BBWaitCounter = 0;
+
+	RT_TRACE(COMP_RF, "phy_SetUsbBBReg(): RegAddr(%#x) <= %#x\n", RegAddr, Data);
+
+	//
+	// <Roger_Notes> Due to PASSIVE_LEVEL, so we ONLY simply busy waiting for a while here.
+	// We have to make sure that previous BB I/O has been done.
+	// 2008.08.20.
+	//
+	while(priv->bChangeBBInProgress)
+	{
+		BBWaitCounter ++;
+		RT_TRACE(COMP_RF, "phy_SetUsbBBReg(): Wait 1 ms (%d times)...\n", BBWaitCounter);
+		msleep(1); // 1 ms
+
+		if((BBWaitCounter > 100))// || RT_USB_CANNOT_IO(Adapter))
+		{
+			RT_TRACE(COMP_RF, "phy_SetUsbBBReg(): (%d) Wait too logn to query BB!!\n", BBWaitCounter);
+			return;
+		}
+	}
+
+	priv->bChangeBBInProgress = true;
+	//printk("**************%s: RegAddr:%x Data:%x\n", __FUNCTION__,RegAddr, Data);
+	write_nic_dword(dev, RegAddr, Data);
+
+	priv->bChangeBBInProgress = false;
+}
+
+
+
+//
+// Description:
+//	RF read by 4181 to make sure that operation could be done in unlimited cycle.
+//
+// Assumption:
+//		-	Only use on RTL8192S USB interface.
+//		-	PASSIVE LEVEL
+//		- 	RT_RF_OPERATE_SPINLOCK is acquired and keep on holding to the end.FIXLZM
+//
+// Created by Roger, 2008.09.06.
+//
+//use in phy only
+u32 phy_QueryUsbRFReg(	struct net_device* dev, RF90_RADIO_PATH_E eRFPath,	u32	Offset)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//u32	value  = 0, ReturnValue = 0;
+	u32	ReturnValue = 0;
+	//u32 	tmplong,tmplong2;
+	u8	PollingCnt = 50;
+	u8	RFWaitCounter = 0;
+
+
+	//
+	// <Roger_Notes> Due to PASSIVE_LEVEL, so we ONLY simply busy waiting for a while here.
+	// We have to make sure that previous RF I/O has been done.
+	// 2008.08.20.
+	//
+	while(priv->bChangeRFInProgress)
+	{
+		//PlatformReleaseSpinLock(Adapter, RT_RF_OPERATE_SPINLOCK);
+		//spin_lock_irqsave(&priv->rf_lock, flags);	//LZM,090318
+		down(&priv->rf_sem);
+
+		RFWaitCounter ++;
+		RT_TRACE(COMP_RF, "phy_QueryUsbRFReg(): Wait 1 ms (%d times)...\n", RFWaitCounter);
+		msleep(1); // 1 ms
+
+		if((RFWaitCounter > 100)) //|| RT_USB_CANNOT_IO(Adapter))
+		{
+			RT_TRACE(COMP_RF, "phy_QueryUsbRFReg(): (%d) Wait too logn to query BB!!\n", RFWaitCounter);
+			return 0xffffffff;
+		}
+		else
+		{
+			//PlatformAcquireSpinLock(Adapter, RT_RF_OPERATE_SPINLOCK);
+		}
+	}
+
+	priv->bChangeRFInProgress = true;
+	//PlatformReleaseSpinLock(Adapter, RT_RF_OPERATE_SPINLOCK);
+
+
+	Offset &= 0x3f; //RF_Offset= 0x00~0x3F
+
+	write_nic_dword(dev, RF_BB_CMD_ADDR, 0xF0000002|
+						(Offset<<8)|	//RF_Offset= 0x00~0x3F
+						(eRFPath<<16)); 	//RF_Path = 0(A) or 1(B)
+
+	do
+	{// Make sure that access could be done.
+		if(read_nic_dword(dev, RF_BB_CMD_ADDR) == 0)
+			break;
+	}while( --PollingCnt );
+
+	// Data FW read back.
+	ReturnValue = read_nic_dword(dev, RF_BB_CMD_DATA);
+
+	//PlatformAcquireSpinLock(Adapter, RT_RF_OPERATE_SPINLOCK);
+	//spin_unlock_irqrestore(&priv->rf_lock, flags);   //LZM,090318
+	up(&priv->rf_sem);
+	priv->bChangeRFInProgress = false;
+
+	RT_TRACE(COMP_RF, "phy_QueryUsbRFReg(): eRFPath(%d), Offset(%#x) = %#x\n", eRFPath, Offset, ReturnValue);
+
+	return ReturnValue;
+
+}
+
+
+//
+// Description:
+//	RF wrote by 4181 to make sure that operation could be done in unlimited cycle.
+//
+// Assumption:
+//		-	Only use on RTL8192S USB interface.
+//		-	PASSIVE LEVEL
+//		- 	RT_RF_OPERATE_SPINLOCK is acquired and keep on holding to the end.FIXLZM
+//
+// Created by Roger, 2008.09.06.
+//
+//use in phy only
+void phy_SetUsbRFReg(struct net_device* dev,RF90_RADIO_PATH_E eRFPath,u32	RegAddr,u32 Data)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8	PollingCnt = 50;
+	u8	RFWaitCounter = 0;
+
+
+	//
+	// <Roger_Notes> Due to PASSIVE_LEVEL, so we ONLY simply busy waiting for a while here.
+	// We have to make sure that previous BB I/O has been done.
+	// 2008.08.20.
+	//
+	while(priv->bChangeRFInProgress)
+	{
+		//PlatformReleaseSpinLock(Adapter, RT_RF_OPERATE_SPINLOCK);
+		//spin_lock_irqsave(&priv->rf_lock, flags);	//LZM,090318
+		down(&priv->rf_sem);
+
+		RFWaitCounter ++;
+		RT_TRACE(COMP_RF, "phy_SetUsbRFReg(): Wait 1 ms (%d times)...\n", RFWaitCounter);
+		msleep(1); // 1 ms
+
+		if((RFWaitCounter > 100))// || RT_USB_CANNOT_IO(Adapter))
+		{
+			RT_TRACE(COMP_RF, "phy_SetUsbRFReg(): (%d) Wait too logn to query BB!!\n", RFWaitCounter);
+			return;
+		}
+		else
+		{
+			//PlatformAcquireSpinLock(Adapter, RT_RF_OPERATE_SPINLOCK);
+		}
+	}
+
+	priv->bChangeRFInProgress = true;
+	//PlatformReleaseSpinLock(Adapter, RT_RF_OPERATE_SPINLOCK);
+
+
+	RegAddr &= 0x3f; //RF_Offset= 0x00~0x3F
+
+	write_nic_dword(dev, RF_BB_CMD_DATA, Data);
+	write_nic_dword(dev, RF_BB_CMD_ADDR, 0xF0000003|
+					(RegAddr<<8)| //RF_Offset= 0x00~0x3F
+					(eRFPath<<16));  //RF_Path = 0(A) or 1(B)
+
+	do
+	{// Make sure that access could be done.
+		if(read_nic_dword(dev, RF_BB_CMD_ADDR) == 0)
+				break;
+	}while( --PollingCnt );
+
+	if(PollingCnt == 0)
+	{
+		RT_TRACE(COMP_RF, "phy_SetUsbRFReg(): Set RegAddr(%#x) = %#x Fail!!!\n", RegAddr, Data);
+	}
+
+	//PlatformAcquireSpinLock(Adapter, RT_RF_OPERATE_SPINLOCK);
+	//spin_unlock_irqrestore(&priv->rf_lock, flags);   //LZM,090318
+	up(&priv->rf_sem);
+	priv->bChangeRFInProgress = false;
+
+}
+
+#endif
+
+/*---------------------Define local function prototype-----------------------*/
+
+
+/*----------------------------Function Body----------------------------------*/
+//
+// 1. BB register R/W API
+//
+/**
+* Function:	PHY_QueryBBReg
+*
+* OverView:	Read "sepcific bits" from BB register
+*
+* Input:
+*			PADAPTER		Adapter,
+*			u32			RegAddr,		//The target address to be readback
+*			u32			BitMask		//The target bit position in the target address
+*										//to be readback
+* Output:	None
+* Return:		u32			Data			//The readback register value
+* Note:		This function is equal to "GetRegSetting" in PHY programming guide
+*/
+//use phy dm core 8225 8256 6052
+//u32 PHY_QueryBBReg(struct net_device* dev,u32		RegAddr,	u32		BitMask)
+u32 rtl8192_QueryBBReg(struct net_device* dev, u32 RegAddr, u32 BitMask)
+{
+
+  	u32	ReturnValue = 0, OriginalValue, BitShift;
+
+#if (DISABLE_BB_RF == 1)
+	return 0;
+#endif
+
+	RT_TRACE(COMP_RF, "--->PHY_QueryBBReg(): RegAddr(%#x), BitMask(%#x)\n", RegAddr, BitMask);
+
+	//
+	// <Roger_Notes> Due to 8051 operation cycle (limitation cycle: 6us) and 1-Byte access issue, we should use
+	// 4181 to access Base Band instead of 8051 on USB interface to make sure that access could be done in
+	// infinite cycle.
+	// 2008.09.06.
+	//
+//#if ((HAL_CODE_BASE == RTL8192_S) && (DEV_BUS_TYPE==USB_INTERFACE))
+#ifdef RTL8192SU
+	if(IS_BB_REG_OFFSET_92S(RegAddr))
+	{
+		//if(RT_USB_CANNOT_IO(Adapter))	return	FALSE;
+
+		if((RegAddr & 0x03) != 0)
+		{
+			printk("%s: Not DWORD alignment!!\n", __FUNCTION__);
+			return 0;
+		}
+
+	OriginalValue = phy_QueryUsbBBReg(dev, RegAddr);
+	}
+	else
+#endif
+	{
+	OriginalValue = read_nic_dword(dev, RegAddr);
+	}
+
+	BitShift = phy_CalculateBitShift(BitMask);
+	ReturnValue = (OriginalValue & BitMask) >> BitShift;
+
+	//RTPRINT(FPHY, PHY_BBR, ("BBR MASK=0x%x Addr[0x%x]=0x%x\n", BitMask, RegAddr, OriginalValue));
+	RT_TRACE(COMP_RF, "<---PHY_QueryBBReg(): RegAddr(%#x), BitMask(%#x), OriginalValue(%#x)\n", RegAddr, BitMask, OriginalValue);
+	return (ReturnValue);
+}
+
+/**
+* Function:	PHY_SetBBReg
+*
+* OverView:	Write "Specific bits" to BB register (page 8~)
+*
+* Input:
+*			PADAPTER		Adapter,
+*			u32			RegAddr,		//The target address to be modified
+*			u32			BitMask		//The target bit position in the target address
+*										//to be modified
+*			u32			Data			//The new register value in the target bit position
+*										//of the target address
+*
+* Output:	None
+* Return:		None
+* Note:		This function is equal to "PutRegSetting" in PHY programming guide
+*/
+//use phy dm core 8225 8256
+//void PHY_SetBBReg(struct net_device* dev,u32		RegAddr,	u32		BitMask,	u32		Data	)
+void rtl8192_setBBreg(struct net_device* dev, u32 RegAddr, u32 BitMask, u32 Data)
+{
+	u32	OriginalValue, BitShift, NewValue;
+
+#if (DISABLE_BB_RF == 1)
+	return;
+#endif
+
+	RT_TRACE(COMP_RF, "--->PHY_SetBBReg(): RegAddr(%#x), BitMask(%#x), Data(%#x)\n", RegAddr, BitMask, Data);
+
+	//
+	// <Roger_Notes> Due to 8051 operation cycle (limitation cycle: 6us) and 1-Byte access issue, we should use
+	// 4181 to access Base Band instead of 8051 on USB interface to make sure that access could be done in
+	// infinite cycle.
+	// 2008.09.06.
+	//
+//#if ((HAL_CODE_BASE == RTL8192_S) && (DEV_BUS_TYPE==USB_INTERFACE))
+#ifdef RTL8192SU
+	if(IS_BB_REG_OFFSET_92S(RegAddr))
+	{
+		if((RegAddr & 0x03) != 0)
+		{
+			printk("%s: Not DWORD alignment!!\n", __FUNCTION__);
+			return;
+		}
+
+		if(BitMask!= bMaskDWord)
+		{//if not "double word" write
+			OriginalValue = phy_QueryUsbBBReg(dev, RegAddr);
+			BitShift = phy_CalculateBitShift(BitMask);
+            NewValue = (((OriginalValue) & (~BitMask))|(Data << BitShift));
+			phy_SetUsbBBReg(dev, RegAddr, NewValue);
+		}else
+			phy_SetUsbBBReg(dev, RegAddr, Data);
+	}
+	else
+#endif
+	{
+		if(BitMask!= bMaskDWord)
+		{//if not "double word" write
+			OriginalValue = read_nic_dword(dev, RegAddr);
+			BitShift = phy_CalculateBitShift(BitMask);
+			NewValue = (((OriginalValue) & (~BitMask)) | (Data << BitShift));
+			write_nic_dword(dev, RegAddr, NewValue);
+		}else
+			write_nic_dword(dev, RegAddr, Data);
+	}
+
+	//RT_TRACE(COMP_RF, "<---PHY_SetBBReg(): RegAddr(%#x), BitMask(%#x), Data(%#x)\n", RegAddr, BitMask, Data);
+
+	return;
+}
+
+
+//
+// 2. RF register R/W API
+//
+/**
+* Function:	PHY_QueryRFReg
+*
+* OverView:	Query "Specific bits" to RF register (page 8~)
+*
+* Input:
+*			PADAPTER		Adapter,
+*			RF90_RADIO_PATH_E	eRFPath,	//Radio path of A/B/C/D
+*			u32			RegAddr,		//The target address to be read
+*			u32			BitMask		//The target bit position in the target address
+*										//to be read
+*
+* Output:	None
+* Return:		u32			Readback value
+* Note:		This function is equal to "GetRFRegSetting" in PHY programming guide
+*/
+//in dm 8256 and phy
+//u32 PHY_QueryRFReg(struct net_device* dev,	RF90_RADIO_PATH_E eRFPath, u32 RegAddr, u32 BitMask)
+u32 rtl8192_phy_QueryRFReg(struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 RegAddr, u32 BitMask)
+{
+	u32 Original_Value, Readback_Value, BitShift;//, flags;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+#if (DISABLE_BB_RF == 1)
+	return 0;
+#endif
+
+	RT_TRACE(COMP_RF, "--->PHY_QueryRFReg(): RegAddr(%#x), eRFPath(%#x), BitMask(%#x)\n", RegAddr, eRFPath,BitMask);
+
+	if (!((priv->rf_pathmap >> eRFPath) & 0x1))
+	{
+		printk("EEEEEError: rfpath off! rf_pathmap=%x eRFPath=%x\n", priv->rf_pathmap, eRFPath);
+		return 0;
+	}
+
+	if (!rtl8192_phy_CheckIsLegalRFPath(dev, eRFPath))
+	{
+		printk("EEEEEError: not legal rfpath! eRFPath=%x\n", eRFPath);
+		return 0;
+	}
+
+	/* 2008/01/17 MH We get and release spin lock when reading RF register. */
+	//PlatformAcquireSpinLock(dev, RT_RF_OPERATE_SPINLOCK);FIXLZM
+	//spin_lock_irqsave(&priv->rf_lock, flags);	//YJ,test,090113
+	down(&priv->rf_sem);
+	//
+	// <Roger_Notes> Due to 8051 operation cycle (limitation cycle: 6us) and 1-Byte access issue, we should use
+	// 4181 to access Base Band instead of 8051 on USB interface to make sure that access could be done in
+	// infinite cycle.
+	// 2008.09.06.
+	//
+//#if (HAL_CODE_BASE == RTL8192_S && DEV_BUS_TYPE==USB_INTERFACE)
+#ifdef RTL8192SU
+	//if(RT_USB_CANNOT_IO(Adapter))	return FALSE;
+	Original_Value = phy_QueryUsbRFReg(dev, eRFPath, RegAddr);
+#else
+	if (priv->Rf_Mode == RF_OP_By_FW)
+	{
+		Original_Value = phy_FwRFSerialRead(dev, eRFPath, RegAddr);
+	}
+	else
+	{
+		Original_Value = phy_RFSerialRead(dev, eRFPath, RegAddr);
+	}
+#endif
+
+	BitShift =  phy_CalculateBitShift(BitMask);
+	Readback_Value = (Original_Value & BitMask) >> BitShift;
+	//spin_unlock_irqrestore(&priv->rf_lock, flags);   //YJ,test,090113
+	up(&priv->rf_sem);
+	//PlatformReleaseSpinLock(dev, RT_RF_OPERATE_SPINLOCK);
+
+	//RTPRINT(FPHY, PHY_RFR, ("RFR-%d MASK=0x%x Addr[0x%x]=0x%x\n", eRFPath, BitMask, RegAddr, Original_Value));
+
+	return (Readback_Value);
+}
+
+/**
+* Function:	PHY_SetRFReg
+*
+* OverView:	Write "Specific bits" to RF register (page 8~)
+*
+* Input:
+*			PADAPTER		Adapter,
+*			RF90_RADIO_PATH_E	eRFPath,	//Radio path of A/B/C/D
+*			u32			RegAddr,		//The target address to be modified
+*			u32			BitMask		//The target bit position in the target address
+*										//to be modified
+*			u32			Data			//The new register Data in the target bit position
+*										//of the target address
+*
+* Output:	None
+* Return:		None
+* Note:		This function is equal to "PutRFRegSetting" in PHY programming guide
+*/
+//use phy  8225 8256
+//void PHY_SetRFReg(struct net_device* dev,RF90_RADIO_PATH_E eRFPath, u32	RegAddr,	u32 BitMask,u32	Data	)
+void rtl8192_phy_SetRFReg(struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 RegAddr, u32 BitMask, u32 Data)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 Original_Value, BitShift, New_Value;//, flags;
+#if (DISABLE_BB_RF == 1)
+	return;
+#endif
+
+	RT_TRACE(COMP_RF, "--->PHY_SetRFReg(): RegAddr(%#x), BitMask(%#x), Data(%#x), eRFPath(%#x)\n",
+		RegAddr, BitMask, Data, eRFPath);
+
+	if (!((priv->rf_pathmap >> eRFPath) & 0x1))
+	{
+		printk("EEEEEError: rfpath off! rf_pathmap=%x eRFPath=%x\n", priv->rf_pathmap, eRFPath);
+		return ;
+	}
+	if (!rtl8192_phy_CheckIsLegalRFPath(dev, eRFPath))
+	{
+		printk("EEEEEError: not legal rfpath! eRFPath=%x\n", eRFPath);
+		return;
+	}
+
+	/* 2008/01/17 MH We get and release spin lock when writing RF register. */
+	//PlatformAcquireSpinLock(dev, RT_RF_OPERATE_SPINLOCK);
+	//spin_lock_irqsave(&priv->rf_lock, flags);	//YJ,test,090113
+	down(&priv->rf_sem);
+	//
+	// <Roger_Notes> Due to 8051 operation cycle (limitation cycle: 6us) and 1-Byte access issue, we should use
+	// 4181 to access Base Band instead of 8051 on USB interface to make sure that access could be done in
+	// infinite cycle.
+	// 2008.09.06.
+	//
+//#if (HAL_CODE_BASE == RTL8192_S && DEV_BUS_TYPE==USB_INTERFACE)
+#ifdef RTL8192SU
+		//if(RT_USB_CANNOT_IO(Adapter))	return;
+
+		if (BitMask != bRFRegOffsetMask) // RF data is 12 bits only
+		{
+			Original_Value = phy_QueryUsbRFReg(dev, eRFPath, RegAddr);
+			BitShift =  phy_CalculateBitShift(BitMask);
+			New_Value = (((Original_Value)&(~BitMask))|(Data<< BitShift));
+			phy_SetUsbRFReg(dev, eRFPath, RegAddr, New_Value);
+		}
+		else
+			phy_SetUsbRFReg(dev, eRFPath, RegAddr, Data);
+#else
+	if (priv->Rf_Mode == RF_OP_By_FW)
+	{
+		//DbgPrint("eRFPath-%d Addr[%02x] = %08x\n", eRFPath, RegAddr, Data);
+		if (BitMask != bRFRegOffsetMask) // RF data is 12 bits only
+		{
+			Original_Value = phy_FwRFSerialRead(dev, eRFPath, RegAddr);
+			BitShift =  phy_CalculateBitShift(BitMask);
+			New_Value = (((Original_Value) & (~BitMask)) | (Data<< BitShift));
+
+			phy_FwRFSerialWrite(dev, eRFPath, RegAddr, New_Value);
+		}
+		else
+			phy_FwRFSerialWrite(dev, eRFPath, RegAddr, Data);
+	}
+	else
+	{
+		//DbgPrint("eRFPath-%d Addr[%02x] = %08x\n", eRFPath, RegAddr, Data);
+		if (BitMask != bRFRegOffsetMask) // RF data is 12 bits only
+		{
+			Original_Value = phy_RFSerialRead(dev, eRFPath, RegAddr);
+			BitShift =  phy_CalculateBitShift(BitMask);
+			New_Value = (((Original_Value) & (~BitMask)) | (Data<< BitShift));
+
+			phy_RFSerialWrite(dev, eRFPath, RegAddr, New_Value);
+		}
+		else
+			phy_RFSerialWrite(dev, eRFPath, RegAddr, Data);
+
+	}
+#endif
+	//PlatformReleaseSpinLock(dev, RT_RF_OPERATE_SPINLOCK);
+	//spin_unlock_irqrestore(&priv->rf_lock, flags);   //YJ,test,090113
+	up(&priv->rf_sem);
+	//RTPRINT(FPHY, PHY_RFW, ("RFW-%d MASK=0x%x Addr[0x%x]=0x%x\n", eRFPath, BitMask, RegAddr, Data));
+	RT_TRACE(COMP_RF, "<---PHY_SetRFReg(): RegAddr(%#x), BitMask(%#x), Data(%#x), eRFPath(%#x)\n",
+			RegAddr, BitMask, Data, eRFPath);
+
+}
+
+#ifdef RTL8192SE
+/*-----------------------------------------------------------------------------
+ * Function:	phy_FwRFSerialRead()
+ *
+ * Overview:	We support firmware to execute RF-R/W.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	01/21/2008	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+//use in phy only
+static	u32
+phy_FwRFSerialRead(
+	struct net_device* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32				Offset	)
+{
+	u32		retValue = 0;
+	//u32		Data = 0;
+	//u8		time = 0;
+#if 0
+	//DbgPrint("FW RF CTRL\n\r");
+	/* 2007/11/02 MH Firmware RF Write control. By Francis' suggestion, we can
+	   not execute the scheme in the initial step. Otherwise, RF-R/W will waste
+	   much time. This is only for site survey. */
+	// 1. Read operation need not insert data. bit 0-11
+	//Data &= bMask12Bits;
+	// 2. Write RF register address. Bit 12-19
+	Data |= ((Offset&0xFF)<<12);
+	// 3. Write RF path.  bit 20-21
+	Data |= ((eRFPath&0x3)<<20);
+	// 4. Set RF read indicator. bit 22=0
+	//Data |= 0x00000;
+	// 5. Trigger Fw to operate the command. bit 31
+	Data |= 0x80000000;
+	// 6. We can not execute read operation if bit 31 is 1.
+	while (PlatformIORead4Byte(dev, QPNR)&0x80000000)
+	{
+		// If FW can not finish RF-R/W for more than ?? times. We must reset FW.
+		if (time++ < 100)
+		{
+			//DbgPrint("FW not finish RF-R Time=%d\n\r", time);
+			delay_us(10);
+		}
+		else
+			break;
+	}
+	// 7. Execute read operation.
+	PlatformIOWrite4Byte(dev, QPNR, Data);
+	// 8. Check if firmawre send back RF content.
+	while (PlatformIORead4Byte(dev, QPNR)&0x80000000)
+	{
+		// If FW can not finish RF-R/W for more than ?? times. We must reset FW.
+		if (time++ < 100)
+		{
+			//DbgPrint("FW not finish RF-W Time=%d\n\r", time);
+			delay_us(10);
+		}
+		else
+			return	(0);
+	}
+	retValue = PlatformIORead4Byte(dev, RF_DATA);
+#endif
+	return	(retValue);
+
+}	/* phy_FwRFSerialRead */
+
+/*-----------------------------------------------------------------------------
+ * Function:	phy_FwRFSerialWrite()
+ *
+ * Overview:	We support firmware to execute RF-R/W.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	01/21/2008	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+//use in phy only
+static	void
+phy_FwRFSerialWrite(
+	struct net_device* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32				Offset,
+	u32				Data	)
+{
+#if 0
+	u8	time = 0;
+	DbgPrint("N FW RF CTRL RF-%d OF%02x DATA=%03x\n\r", eRFPath, Offset, Data);
+	/* 2007/11/02 MH Firmware RF Write control. By Francis' suggestion, we can
+	   not execute the scheme in the initial step. Otherwise, RF-R/W will waste
+	   much time. This is only for site survey. */
+
+	// 1. Set driver write bit and 12 bit data. bit 0-11
+	//Data &= bMask12Bits;	// Done by uper layer.
+	// 2. Write RF register address. bit 12-19
+	Data |= ((Offset&0xFF)<<12);
+	// 3. Write RF path.  bit 20-21
+	Data |= ((eRFPath&0x3)<<20);
+	// 4. Set RF write indicator. bit 22=1
+	Data |= 0x400000;
+	// 5. Trigger Fw to operate the command. bit 31=1
+	Data |= 0x80000000;
+
+	// 6. Write operation. We can not write if bit 31 is 1.
+	while (PlatformIORead4Byte(dev, QPNR)&0x80000000)
+	{
+		// If FW can not finish RF-R/W for more than ?? times. We must reset FW.
+		if (time++ < 100)
+		{
+			//DbgPrint("FW not finish RF-W Time=%d\n\r", time);
+			delay_us(10);
+		}
+		else
+			break;
+	}
+	// 7. No matter check bit. We always force the write. Because FW will
+	//    not accept the command.
+	PlatformIOWrite4Byte(dev, QPNR, Data);
+	/* 2007/11/02 MH Acoording to test, we must delay 20us to wait firmware
+	   to finish RF write operation. */
+	/* 2008/01/17 MH We support delay in firmware side now. */
+	//delay_us(20);
+#endif
+}	/* phy_FwRFSerialWrite */
+
+/**
+* Function:	phy_RFSerialRead
+*
+* OverView:	Read regster from RF chips
+*
+* Input:
+*			PADAPTER		Adapter,
+*			RF90_RADIO_PATH_E	eRFPath,	//Radio path of A/B/C/D
+*			u32			Offset,		//The target address to be read
+*
+* Output:	None
+* Return:		u32			reback value
+* Note:		Threre are three types of serial operations:
+*			1. Software serial write
+*			2. Hardware LSSI-Low Speed Serial Interface
+*			3. Hardware HSSI-High speed
+*			serial write. Driver need to implement (1) and (2).
+*			This function is equal to the combination of RF_ReadReg() and  RFLSSIRead()
+*/
+//use in phy only
+static u32 phy_RFSerialRead(struct net_device* dev,RF90_RADIO_PATH_E eRFPath,u32 Offset)
+{
+
+	u32						retValue = 0;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	BB_REGISTER_DEFINITION_T	*pPhyReg = &priv->PHYRegDef[eRFPath];
+	u32						NewOffset;
+	u8						RfPiEnable=0;
+
+
+	//
+	// Make sure RF register offset is correct
+	//
+	Offset &= 0x3f;
+
+	//
+	// Switch page for 8256 RF IC
+	//
+	if(	priv->rf_chip == RF_8256 ||
+		priv->rf_chip == RF_8225 ||
+		priv->rf_chip == RF_6052)
+	{
+		//analog to digital off, for protection
+		rtl8192_setBBreg(dev, rFPGA0_AnalogParameter4, 0xf00, 0x0);// 0x88c[11:8]
+
+		if(Offset>=31)
+		{
+			priv->RFReadPageCnt[2]++;//cosa add for debug
+			priv->RfReg0Value[eRFPath] |= 0x140;
+
+			// Switch to Reg_Mode2 for Reg31~45
+			rtl8192_setBBreg(dev,
+				pPhyReg->rf3wireOffset,
+				bMaskDWord,
+				(priv->RfReg0Value[eRFPath] << 16)	);
+
+			// Modified Offset
+			NewOffset = Offset - 30;
+
+		}else if(Offset>=16)
+		{
+			priv->RFReadPageCnt[1]++;//cosa add for debug
+			priv->RfReg0Value[eRFPath] |= 0x100;
+			priv->RfReg0Value[eRFPath] &= (~0x40);
+
+			// Switch to Reg_Mode1 for Reg16~30
+			rtl8192_setBBreg(dev,
+				pPhyReg->rf3wireOffset,
+				bMaskDWord,
+				(priv->RfReg0Value[eRFPath] << 16)	);
+
+			// Modified Offset
+			NewOffset = Offset - 15;
+		}
+		else
+		{
+			priv->RFReadPageCnt[0]++;//cosa add for debug
+			NewOffset = Offset;
+	}
+	}
+	else
+		NewOffset = Offset;
+
+	//
+	// Put desired read address to LSSI control register
+	//
+	rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2, bLSSIReadAddress, NewOffset);
+
+	//
+	// Issue a posedge trigger
+	//
+	rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2,  bLSSIReadEdge, 0x0);
+	rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2,  bLSSIReadEdge, 0x1);
+
+	// TODO: we should not delay such a  long time. Ask help from SD3
+	mdelay(1);
+
+	retValue = rtl8192_QueryBBReg(dev, pPhyReg->rfLSSIReadBack, bLSSIReadBackData);
+
+	// Switch back to Reg_Mode0;
+	if(	priv->rf_chip == RF_8256 ||
+		priv->rf_chip == RF_8225 ||
+		priv->rf_chip == RF_0222D)
+	{
+		if (Offset >= 0x10)
+		{
+			priv->RfReg0Value[eRFPath] &= 0xebf;
+
+			rtl8192_setBBreg(
+				dev,
+				pPhyReg->rf3wireOffset,
+				bMaskDWord,
+				(priv->RfReg0Value[eRFPath] << 16)	);
+		}
+
+		//analog to digital on
+		rtl8192_setBBreg(dev, rFPGA0_AnalogParameter4, 0xf00, 0xf);// 0x88c[11:8]
+	}
+
+	return retValue;
+}
+
+
+
+/**
+* Function:	phy_RFSerialWrite
+*
+* OverView:	Write data to RF register (page 8~)
+*
+* Input:
+*			PADAPTER		Adapter,
+*			RF90_RADIO_PATH_E	eRFPath,	//Radio path of A/B/C/D
+*			u32			Offset,		//The target address to be read
+*			u32			Data			//The new register Data in the target bit position
+*										//of the target to be read
+*
+* Output:	None
+* Return:		None
+* Note:		Threre are three types of serial operations:
+*			1. Software serial write
+*			2. Hardware LSSI-Low Speed Serial Interface
+*			3. Hardware HSSI-High speed
+*			serial write. Driver need to implement (1) and (2).
+*			This function is equal to the combination of RF_ReadReg() and  RFLSSIRead()
+ *
+ * Note: 		  For RF8256 only
+ *			 The total count of RTL8256(Zebra4) register is around 36 bit it only employs
+ *			 4-bit RF address. RTL8256 uses "register mode control bit" (Reg00[12], Reg00[10])
+ *			 to access register address bigger than 0xf. See "Appendix-4 in PHY Configuration
+ *			 programming guide" for more details.
+ *			 Thus, we define a sub-finction for RTL8526 register address conversion
+ *		       ===========================================================
+ *			 Register Mode		RegCTL[1]		RegCTL[0]		Note
+ *								(Reg00[12])		(Reg00[10])
+ *		       ===========================================================
+ *			 Reg_Mode0				0				x			Reg 0 ~15(0x0 ~ 0xf)
+ *		       ------------------------------------------------------------------
+ *			 Reg_Mode1				1				0			Reg 16 ~30(0x1 ~ 0xf)
+ *		       ------------------------------------------------------------------
+ *			 Reg_Mode2				1				1			Reg 31 ~ 45(0x1 ~ 0xf)
+ *		       ------------------------------------------------------------------
+*/
+////use in phy only
+static void
+phy_RFSerialWrite(
+	struct net_device* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32				Offset,
+	u32				Data
+	)
+{
+	u32					DataAndAddr = 0;
+	struct r8192_priv 			*priv = ieee80211_priv(dev);
+	BB_REGISTER_DEFINITION_T	*pPhyReg = &priv->PHYRegDef[eRFPath];
+	u32					NewOffset;
+
+	Offset &= 0x3f;
+
+	// Shadow Update
+	PHY_RFShadowWrite(dev, eRFPath, Offset, Data);
+
+
+	// Switch page for 8256 RF IC
+	if( 	priv->rf_chip == RF_8256 ||
+		priv->rf_chip == RF_8225 ||
+		priv->rf_chip == RF_0222D)
+	{
+		//analog to digital off, for protection
+		rtl8192_setBBreg(dev, rFPGA0_AnalogParameter4, 0xf00, 0x0);// 0x88c[11:8]
+
+		if(Offset>=31)
+		{
+			priv->RFWritePageCnt[2]++;//cosa add for debug
+			priv->RfReg0Value[eRFPath] |= 0x140;
+
+			rtl8192_setBBreg(dev,
+				pPhyReg->rf3wireOffset,
+				bMaskDWord,
+				(priv->RfReg0Value[eRFPath] << 16)	);
+
+			NewOffset = Offset - 30;
+
+		}else if(Offset>=16)
+		{
+			priv->RFWritePageCnt[1]++;//cosa add for debug
+			priv->RfReg0Value[eRFPath] |= 0x100;
+			priv->RfReg0Value[eRFPath] &= (~0x40);
+
+
+			rtl8192_setBBreg(dev,
+				pPhyReg->rf3wireOffset,
+				bMaskDWord,
+				(priv->RfReg0Value[eRFPath] << 16)	);
+
+			NewOffset = Offset - 15;
+		}
+		else
+		{
+			priv->RFWritePageCnt[0]++;//cosa add for debug
+			NewOffset = Offset;
+	}
+	}
+	else
+		NewOffset = Offset;
+
+	//
+	// Put write addr in [5:0]  and write data in [31:16]
+	//
+	DataAndAddr = (Data<<16) | (NewOffset&0x3f);
+
+	//
+	// Write Operation
+	//
+	rtl8192_setBBreg(dev, pPhyReg->rf3wireOffset, bMaskDWord, DataAndAddr);
+
+
+	if(Offset==0x0)
+		priv->RfReg0Value[eRFPath] = Data;
+
+	// Switch back to Reg_Mode0;
+ 	if(	priv->rf_chip == RF_8256 ||
+		priv->rf_chip == RF_8225 ||
+		priv->rf_chip == RF_0222D)
+	{
+		if (Offset >= 0x10)
+		{
+			if(Offset != 0)
+			{
+				priv->RfReg0Value[eRFPath] &= 0xebf;
+				rtl8192_setBBreg(
+				dev,
+				pPhyReg->rf3wireOffset,
+				bMaskDWord,
+				(priv->RfReg0Value[eRFPath] << 16)	);
+			}
+		}
+		//analog to digital on
+		rtl8192_setBBreg(dev, rFPGA0_AnalogParameter4, 0xf00, 0xf);// 0x88c[11:8]
+	}
+
+}
+#else
+/**
+* Function:	phy_RFSerialRead
+*
+* OverView:	Read regster from RF chips
+*
+* Input:
+*			PADAPTER		Adapter,
+*			RF90_RADIO_PATH_E	eRFPath,	//Radio path of A/B/C/D
+*			u4Byte			Offset,		//The target address to be read
+*
+* Output:	None
+* Return:		u4Byte			reback value
+* Note:		Threre are three types of serial operations:
+*			1. Software serial write
+*			2. Hardware LSSI-Low Speed Serial Interface
+*			3. Hardware HSSI-High speed
+*			serial write. Driver need to implement (1) and (2).
+*			This function is equal to the combination of RF_ReadReg() and  RFLSSIRead()
+*/
+#if 0
+static	u32
+phy_RFSerialRead(struct net_device* dev,RF90_RADIO_PATH_E eRFPath,u32 Offset)
+{
+
+	u32						retValue = 0;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	BB_REGISTER_DEFINITION_T	*pPhyReg = &priv->PHYRegDef[eRFPath];
+	u32						NewOffset;
+	//u32						value  = 0;
+	u32 						tmplong,tmplong2;
+	u32						RfPiEnable=0;
+#if 0
+	if(pHalData->RFChipID == RF_8225 && Offset > 0x24) //36 valid regs
+		return	retValue;
+	if(pHalData->RFChipID == RF_8256 && Offset > 0x2D) //45 valid regs
+		return	retValue;
+#endif
+	//
+	// Make sure RF register offset is correct
+	//
+	Offset &= 0x3f;
+
+	//
+	// Switch page for 8256 RF IC
+	//
+	NewOffset = Offset;
+
+	// For 92S LSSI Read RFLSSIRead
+	// For RF A/B write 0x824/82c(does not work in the future)
+	// We must use 0x824 for RF A and B to execute read trigger
+	tmplong = rtl8192_QueryBBReg(dev, rFPGA0_XA_HSSIParameter2, bMaskDWord);
+	tmplong2 = rtl8192_QueryBBReg(dev, pPhyReg->rfHSSIPara2, bMaskDWord);
+	tmplong2 = (tmplong2 & (~bLSSIReadAddress)) | (NewOffset<<23) | bLSSIReadEdge;	//T65 RF
+
+	rtl8192_setBBreg(dev, rFPGA0_XA_HSSIParameter2, bMaskDWord, tmplong&(~bLSSIReadEdge));
+	mdelay(1);
+
+	rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2, bMaskDWord, tmplong2);
+	mdelay(1);
+
+	rtl8192_setBBreg(dev, rFPGA0_XA_HSSIParameter2, bMaskDWord, tmplong|bLSSIReadEdge);
+	mdelay(1);
+
+	if(eRFPath == RF90_PATH_A)
+		RfPiEnable = (u8)rtl8192_QueryBBReg(dev, rFPGA0_XA_HSSIParameter1, BIT8);
+	else if(eRFPath == RF90_PATH_B)
+		RfPiEnable = (u8)rtl8192_QueryBBReg(dev, rFPGA0_XB_HSSIParameter1, BIT8);
+
+	if(RfPiEnable)
+	{	// Read from BBreg8b8, 12 bits for 8190, 20bits for T65 RF
+		retValue = rtl8192_QueryBBReg(dev, pPhyReg->rfLSSIReadBackPi, bLSSIReadBackData);
+		//DbgPrint("Readback from RF-PI : 0x%x\n", retValue);
+	}
+	else
+	{	//Read from BBreg8a0, 12 bits for 8190, 20 bits for T65 RF
+		retValue = rtl8192_QueryBBReg(dev, pPhyReg->rfLSSIReadBack, bLSSIReadBackData);
+		//DbgPrint("Readback from RF-SI : 0x%x\n", retValue);
+	}
+	//RTPRINT(FPHY, PHY_RFR, ("RFR-%d Addr[0x%x]=0x%x\n", eRFPath, pPhyReg->rfLSSIReadBack, retValue));
+
+	return retValue;
+
+}
+4
+
+
+/**
+* Function:	phy_RFSerialWrite
+*
+* OverView:	Write data to RF register (page 8~)
+*
+* Input:
+*			PADAPTER		Adapter,
+*			RF90_RADIO_PATH_E	eRFPath,	//Radio path of A/B/C/D
+*			u4Byte			Offset,		//The target address to be read
+*			u4Byte			Data			//The new register Data in the target bit position
+*										//of the target to be read
+*
+* Output:	None
+* Return:		None
+* Note:		Threre are three types of serial operations:
+*			1. Software serial write
+*			2. Hardware LSSI-Low Speed Serial Interface
+*			3. Hardware HSSI-High speed
+*			serial write. Driver need to implement (1) and (2).
+*			This function is equal to the combination of RF_ReadReg() and  RFLSSIRead()
+ *
+ * Note: 		  For RF8256 only
+ *			 The total count of RTL8256(Zebra4) register is around 36 bit it only employs
+ *			 4-bit RF address. RTL8256 uses "register mode control bit" (Reg00[12], Reg00[10])
+ *			 to access register address bigger than 0xf. See "Appendix-4 in PHY Configuration
+ *			 programming guide" for more details.
+ *			 Thus, we define a sub-finction for RTL8526 register address conversion
+ *		       ===========================================================
+ *			 Register Mode		RegCTL[1]		RegCTL[0]		Note
+ *								(Reg00[12])		(Reg00[10])
+ *		       ===========================================================
+ *			 Reg_Mode0				0				x			Reg 0 ~15(0x0 ~ 0xf)
+ *		       ------------------------------------------------------------------
+ *			 Reg_Mode1				1				0			Reg 16 ~30(0x1 ~ 0xf)
+ *		       ------------------------------------------------------------------
+ *			 Reg_Mode2				1				1			Reg 31 ~ 45(0x1 ~ 0xf)
+ *		       ------------------------------------------------------------------
+ *
+ *	2008/09/02	MH	Add 92S RF definition
+ *
+ *
+ *
+*/
+static	void
+phy_RFSerialWrite(struct net_device* dev,RF90_RADIO_PATH_E eRFPath,u32 Offset,u32	Data)
+{
+	u32						DataAndAddr = 0;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	BB_REGISTER_DEFINITION_T	*pPhyReg = &priv->PHYRegDef[eRFPath];
+	u32						NewOffset;
+
+#if 0
+	//<Roger_TODO> We should check valid regs for RF_6052 case.
+	if(pHalData->RFChipID == RF_8225 && Offset > 0x24) //36 valid regs
+		return;
+	if(pHalData->RFChipID == RF_8256 && Offset > 0x2D) //45 valid regs
+		return;
+#endif
+
+	Offset &= 0x3f;
+
+	//
+	// Shadow Update
+	//
+	PHY_RFShadowWrite(dev, eRFPath, Offset, Data);
+
+	//
+	// Switch page for 8256 RF IC
+	//
+		NewOffset = Offset;
+
+	//
+	// Put write addr in [5:0]  and write data in [31:16]
+	//
+	//DataAndAddr = (Data<<16) | (NewOffset&0x3f);
+	DataAndAddr = ((NewOffset<<20) | (Data&0x000fffff)) & 0x0fffffff;	// T65 RF
+
+	//
+	// Write Operation
+	//
+	rtl8192_setBBreg(dev, pPhyReg->rf3wireOffset, bMaskDWord, DataAndAddr);
+	//RTPRINT(FPHY, PHY_RFW, ("RFW-%d Addr[0x%x]=0x%x\n", eRFPath, pPhyReg->rf3wireOffset, DataAndAddr));
+
+}
+#endif
+#endif
+
+/**
+* Function:	phy_CalculateBitShift
+*
+* OverView:	Get shifted position of the BitMask
+*
+* Input:
+*			u32		BitMask,
+*
+* Output:	none
+* Return:		u32		Return the shift bit bit position of the mask
+*/
+//use in phy only
+static u32 phy_CalculateBitShift(u32 BitMask)
+{
+	u32 i;
+
+	for(i=0; i<=31; i++)
+	{
+		if ( ((BitMask>>i) &  0x1 ) == 1)
+			break;
+	}
+
+	return (i);
+}
+
+
+//
+// 3. Initial MAC/BB/RF config by reading MAC/BB/RF txt.
+//
+/*-----------------------------------------------------------------------------
+ * Function:    PHY_MACConfig8192S
+ *
+ * Overview:	Condig MAC by header file or parameter file.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ *  When		Who		Remark
+ *  08/12/2008	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+//adapter_start
+extern bool PHY_MACConfig8192S(struct net_device* dev)
+{
+	RT_STATUS		rtStatus = RT_STATUS_SUCCESS;
+
+	//
+	// Config MAC
+	//
+#if RTL8190_Download_Firmware_From_Header
+	rtStatus = phy_ConfigMACWithHeaderFile(dev);
+#else
+	// Not make sure EEPROM, add later
+	RT_TRACE(COMP_INIT, "Read MACREG.txt\n");
+	//rtStatus = phy_ConfigMACWithParaFile(dev, RTL819X_PHY_MACREG);// lzm del it temp
+#endif
+	return (rtStatus == RT_STATUS_SUCCESS) ? true:false;
+
+}
+
+//adapter_start
+extern	bool
+PHY_BBConfig8192S(struct net_device* dev)
+{
+	RT_STATUS	rtStatus = RT_STATUS_SUCCESS;
+
+	u8 PathMap = 0, index = 0, rf_num = 0;
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	phy_InitBBRFRegisterDefinition(dev);
+
+	//
+	// Config BB and AGC
+	//
+	//switch( Adapter->MgntInfo.bRegHwParaFile )
+	//{
+	//	case 0:
+	//		phy_BB8190_Config_HardCode(dev);
+	//		break;
+
+	//	case 1:
+			rtStatus = phy_BB8192S_Config_ParaFile(dev);
+	//		break;
+
+	//	case 2:
+			// Partial Modify.
+	//		phy_BB8190_Config_HardCode(dev);
+	//		phy_BB8192S_Config_ParaFile(dev);
+	//		break;
+
+	//	default:
+	//		phy_BB8190_Config_HardCode(dev);
+	//		break;
+	//}
+	PathMap = (u8)(rtl8192_QueryBBReg(dev, rFPGA0_TxInfo, 0xf) |
+				rtl8192_QueryBBReg(dev, rOFDM0_TRxPathEnable, 0xf));
+	priv->rf_pathmap = PathMap;
+	for(index = 0; index<4; index++)
+	{
+		if((PathMap>>index)&0x1)
+			rf_num++;
+	}
+
+	if((priv->rf_type==RF_1T1R && rf_num!=1) ||
+		(priv->rf_type==RF_1T2R && rf_num!=2) ||
+		(priv->rf_type==RF_2T2R && rf_num!=2) ||
+		(priv->rf_type==RF_2T2R_GREEN && rf_num!=2) ||
+		(priv->rf_type==RF_2T4R && rf_num!=4))
+	{
+		RT_TRACE( COMP_INIT, "PHY_BBConfig8192S: RF_Type(%x) does not match RF_Num(%x)!!\n", priv->rf_type, rf_num);
+	}
+	return (rtStatus == RT_STATUS_SUCCESS) ? 1:0;
+}
+
+//adapter_start
+extern	bool
+PHY_RFConfig8192S(struct net_device* dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	RT_STATUS    		rtStatus = RT_STATUS_SUCCESS;
+
+	//Set priv->rf_chip = RF_8225 to do real PHY FPGA initilization
+
+	//<Roger_EXP> We assign RF type here temporally. 2008.09.12.
+	priv->rf_chip = RF_6052;
+
+	//
+	// RF config
+	//
+	switch(priv->rf_chip)
+	{
+	case RF_8225:
+	case RF_6052:
+		rtStatus = PHY_RF6052_Config(dev);
+		break;
+
+	case RF_8256:
+		//rtStatus = PHY_RF8256_Config(dev);
+		break;
+
+	case RF_8258:
+		break;
+
+	case RF_PSEUDO_11N:
+		//rtStatus = PHY_RF8225_Config(dev);
+		break;
+        default:
+            break;
+	}
+
+	return (rtStatus == RT_STATUS_SUCCESS) ? 1:0;
+}
+
+
+// Joseph test: new initialize order!!
+// Test only!! This part need to be re-organized.
+// Now it is just for 8256.
+//use in phy only
+#ifdef TO_DO_LIST
+static RT_STATUS
+phy_BB8190_Config_HardCode(struct net_device* dev)
+{
+	//RT_ASSERT(FALSE, ("This function is not implement yet!! \n"));
+	return RT_STATUS_SUCCESS;
+}
+#endif
+
+/*-----------------------------------------------------------------------------
+ * Function:    phy_SetBBtoDiffRFWithHeaderFile()
+ *
+ * Overview:    This function
+ *
+ *
+ * Input:      	PADAPTER		Adapter
+ *			u1Byte 			ConfigType     0 => PHY_CONFIG
+ *
+ * Output:      NONE
+ *
+ * Return:      RT_STATUS_SUCCESS: configuration file exist
+ * When			Who		Remark
+ * 2008/11/10	tynli
+ * use in phy only
+ *---------------------------------------------------------------------------*/
+static RT_STATUS
+phy_SetBBtoDiffRFWithHeaderFile(struct net_device* dev, u8 ConfigType)
+{
+	int i;
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	u32* 			Rtl819XPHY_REGArraytoXTXR_Table;
+	u16				PHY_REGArraytoXTXRLen;
+
+//#if (HAL_CODE_BASE != RTL8192_S)
+
+	if(priv->rf_type == RF_1T1R)
+	{
+		Rtl819XPHY_REGArraytoXTXR_Table = Rtl819XPHY_REG_to1T1R_Array;
+		PHY_REGArraytoXTXRLen = PHY_ChangeTo_1T1RArrayLength;
+	}
+	else if(priv->rf_type == RF_1T2R)
+	{
+		Rtl819XPHY_REGArraytoXTXR_Table = Rtl819XPHY_REG_to1T2R_Array;
+		PHY_REGArraytoXTXRLen = PHY_ChangeTo_1T2RArrayLength;
+	}
+	//else if(priv->rf_type == RF_2T2R || priv->rf_type == RF_2T2R_GREEN)
+	//{
+	//	Rtl819XPHY_REGArraytoXTXR_Table = Rtl819XPHY_REG_to2T2R_Array;
+	//	PHY_REGArraytoXTXRLen = PHY_ChangeTo_2T2RArrayLength;
+	//}
+	else
+	{
+		return RT_STATUS_FAILURE;
+	}
+
+	if(ConfigType == BaseBand_Config_PHY_REG)
+	{
+		for(i=0;i<PHY_REGArraytoXTXRLen;i=i+3)
+		{
+			if (Rtl819XPHY_REGArraytoXTXR_Table[i] == 0xfe)
+				mdelay(50);
+			else if (Rtl819XPHY_REGArraytoXTXR_Table[i] == 0xfd)
+				mdelay(5);
+			else if (Rtl819XPHY_REGArraytoXTXR_Table[i] == 0xfc)
+				mdelay(1);
+			else if (Rtl819XPHY_REGArraytoXTXR_Table[i] == 0xfb)
+				udelay(50);
+			else if (Rtl819XPHY_REGArraytoXTXR_Table[i] == 0xfa)
+				udelay(5);
+			else if (Rtl819XPHY_REGArraytoXTXR_Table[i] == 0xf9)
+				udelay(1);
+			rtl8192_setBBreg(dev, Rtl819XPHY_REGArraytoXTXR_Table[i], Rtl819XPHY_REGArraytoXTXR_Table[i+1], Rtl819XPHY_REGArraytoXTXR_Table[i+2]);
+			//RT_TRACE(COMP_SEND,
+			//"The Rtl819XPHY_REGArraytoXTXR_Table[0] is %lx Rtl819XPHY_REGArraytoXTXR_Table[1] is %lx Rtl819XPHY_REGArraytoXTXR_Table[2] is %lx \n",
+			//Rtl819XPHY_REGArraytoXTXR_Table[i],Rtl819XPHY_REGArraytoXTXR_Table[i+1], Rtl819XPHY_REGArraytoXTXR_Table[i+2]);
+		}
+	}
+	else {
+		RT_TRACE(COMP_SEND, "phy_SetBBtoDiffRFWithHeaderFile(): ConfigType != BaseBand_Config_PHY_REG\n");
+	}
+//#endif	// #if (HAL_CODE_BASE != RTL8192_S)
+	return RT_STATUS_SUCCESS;
+}
+
+
+//use in phy only
+static	RT_STATUS
+phy_BB8192S_Config_ParaFile(struct net_device* dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	RT_STATUS			rtStatus = RT_STATUS_SUCCESS;
+	//u8				u2RegValue;
+	//u16				u4RegValue;
+	//char				szBBRegFile[] = RTL819X_PHY_REG;
+	//char				szBBRegFile1T2R[] = RTL819X_PHY_REG_1T2R;
+	//char				szBBRegPgFile[] = RTL819X_PHY_REG_PG;
+	//char				szAGCTableFile[] = RTL819X_AGC_TAB;
+	//char				szBBRegto1T1RFile[] = RTL819X_PHY_REG_to1T1R;
+	//char				szBBRegto1T2RFile[] = RTL819X_PHY_REG_to1T2R;
+
+	RT_TRACE(COMP_INIT, "==>phy_BB8192S_Config_ParaFile\n");
+
+	//
+	// 1. Read PHY_REG.TXT BB INIT!!
+	// We will seperate as 1T1R/1T2R/1T2R_GREEN/2T2R
+	//
+#if RTL8190_Download_Firmware_From_Header
+	if (priv->rf_type == RF_1T2R || priv->rf_type == RF_2T2R ||
+	    priv->rf_type == RF_1T1R ||priv->rf_type == RF_2T2R_GREEN)
+	{
+		rtStatus = phy_ConfigBBWithHeaderFile(dev,BaseBand_Config_PHY_REG);
+		if(priv->rf_type != RF_2T2R && priv->rf_type != RF_2T2R_GREEN)
+		{//2008.11.10 Added by tynli. The default PHY_REG.txt we read is for 2T2R,
+		  //so we should reconfig BB reg with the right PHY parameters.
+			rtStatus = phy_SetBBtoDiffRFWithHeaderFile(dev,BaseBand_Config_PHY_REG);
+		}
+	}else
+		rtStatus = RT_STATUS_FAILURE;
+#else
+	RT_TRACE(COMP_INIT, "RF_Type == %d\n", priv->rf_type);
+	// No matter what kind of RF we always read PHY_REG.txt. We must copy different
+	// type of parameter files to phy_reg.txt at first.
+	if (priv->rf_type == RF_1T2R || priv->rf_type == RF_2T2R ||
+	    priv->rf_type == RF_1T1R ||priv->rf_type == RF_2T2R_GREEN)
+	{
+		rtStatus = phy_ConfigBBWithParaFile(dev, (char* )&szBBRegFile);
+		if(priv->rf_type != RF_2T2R && priv->rf_type != RF_2T2R_GREEN)
+		{//2008.11.10 Added by tynli. The default PHY_REG.txt we read is for 2T2R,
+		  //so we should reconfig BB reg with the right PHY parameters.
+			if(priv->rf_type == RF_1T1R)
+				rtStatus = phy_SetBBtoDiffRFWithParaFile(dev, (char* )&szBBRegto1T1RFile);
+			else if(priv->rf_type == RF_1T2R)
+				rtStatus = phy_SetBBtoDiffRFWithParaFile(dev, (char* )&szBBRegto1T2RFile);
+		}
+
+	}else
+		rtStatus = RT_STATUS_FAILURE;
+#endif
+
+	if(rtStatus != RT_STATUS_SUCCESS){
+		RT_TRACE(COMP_INIT, "phy_BB8192S_Config_ParaFile():Write BB Reg Fail!!");
+		goto phy_BB8190_Config_ParaFile_Fail;
+	}
+
+	//
+	// 2. If EEPROM or EFUSE autoload OK, We must config by PHY_REG_PG.txt
+	//
+	if (priv->AutoloadFailFlag == false)
+	{
+#if	RTL8190_Download_Firmware_From_Header
+		rtStatus = phy_ConfigBBWithPgHeaderFile(dev,BaseBand_Config_PHY_REG);
+#else
+		rtStatus = phy_ConfigBBWithPgParaFile(dev, (char* )&szBBRegPgFile);
+#endif
+	}
+	if(rtStatus != RT_STATUS_SUCCESS){
+		RT_TRACE(COMP_INIT, "phy_BB8192S_Config_ParaFile():BB_PG Reg Fail!!");
+		goto phy_BB8190_Config_ParaFile_Fail;
+	}
+
+	//
+	// 3. BB AGC table Initialization
+	//
+#if RTL8190_Download_Firmware_From_Header
+	rtStatus = phy_ConfigBBWithHeaderFile(dev,BaseBand_Config_AGC_TAB);
+#else
+	RT_TRACE(COMP_INIT, "phy_BB8192S_Config_ParaFile AGC_TAB.txt\n");
+	rtStatus = phy_ConfigBBWithParaFile(Adapter, (char* )&szAGCTableFile);
+#endif
+
+	if(rtStatus != RT_STATUS_SUCCESS){
+		printk( "phy_BB8192S_Config_ParaFile():AGC Table Fail\n");
+		goto phy_BB8190_Config_ParaFile_Fail;
+	}
+
+
+#if 0	// 2008/08/18 MH Disable for 92SE
+	if(pHalData->VersionID > VERSION_8190_BD)
+	{
+		//if(pHalData->RF_Type == RF_2T4R)
+		//{
+		// Antenna gain offset from B/C/D to A
+		u4RegValue = (  pHalData->AntennaTxPwDiff[2]<<8 |
+						pHalData->AntennaTxPwDiff[1]<<4 |
+						pHalData->AntennaTxPwDiff[0]);
+		//}
+		//else
+		//u4RegValue = 0;
+
+		PHY_SetBBReg(dev, rFPGA0_TxGainStage,
+			(bXBTxAGC|bXCTxAGC|bXDTxAGC), u4RegValue);
+
+		// CrystalCap
+		// Simulate 8192???
+		u4RegValue = pHalData->CrystalCap;
+		PHY_SetBBReg(dev, rFPGA0_AnalogParameter1, bXtalCap92x, u4RegValue);
+		// Simulate 8190??
+		//u4RegValue = ((pHalData->CrystalCap & 0xc)>>2);	// bit2~3 of crystal cap
+		//PHY_SetBBReg(Adapter, rFPGA0_AnalogParameter2, bXtalCap23, u4RegValue);
+
+	}
+#endif
+
+	// Check if the CCK HighPower is turned ON.
+	// This is used to calculate PWDB.
+	priv->bCckHighPower = (bool)(rtl8192_QueryBBReg(dev, rFPGA0_XA_HSSIParameter2, 0x200));
+
+
+phy_BB8190_Config_ParaFile_Fail:
+	return rtStatus;
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:    phy_ConfigMACWithHeaderFile()
+ *
+ * Overview:    This function read BB parameters from Header file we gen, and do register
+ *			  Read/Write
+ *
+ * Input:      	PADAPTER		Adapter
+ *			char* 			pFileName
+ *
+ * Output:      NONE
+ *
+ * Return:      RT_STATUS_SUCCESS: configuration file exist
+ *
+ * Note: 		The format of MACPHY_REG.txt is different from PHY and RF.
+ *			[Register][Mask][Value]
+ *---------------------------------------------------------------------------*/
+//use in phy only
+static	RT_STATUS
+phy_ConfigMACWithHeaderFile(struct net_device* dev)
+{
+	u32					i = 0;
+	u32					ArrayLength = 0;
+	u32*					ptrArray;
+	//struct r8192_priv 	*priv = ieee80211_priv(dev);
+
+//#if (HAL_CODE_BASE != RTL8192_S)
+	/*if(Adapter->bInHctTest)
+	{
+		RT_TRACE(COMP_INIT, DBG_LOUD, ("Rtl819XMACPHY_ArrayDTM\n"));
+		ArrayLength = MACPHY_ArrayLengthDTM;
+		ptrArray = Rtl819XMACPHY_ArrayDTM;
+	}
+	else if(pHalData->bTXPowerDataReadFromEEPORM)
+	{
+//		RT_TRACE(COMP_INIT, DBG_LOUD, ("Rtl819XMACPHY_Array_PG\n"));
+//		ArrayLength = MACPHY_Array_PGLength;
+//		ptrArray = Rtl819XMACPHY_Array_PG;
+
+	}else*/
+	{ //2008.11.06 Modified by tynli.
+		RT_TRACE(COMP_INIT, "Read Rtl819XMACPHY_Array\n");
+		ArrayLength = MAC_2T_ArrayLength;
+		ptrArray = Rtl819XMAC_Array;
+	}
+
+	/*for(i = 0 ;i < ArrayLength;i=i+3){
+		RT_TRACE(COMP_SEND, DBG_LOUD, ("The Rtl819XMACPHY_Array[0] is %lx Rtl819XMACPHY_Array[1] is %lx Rtl819XMACPHY_Array[2] is %lx\n",ptrArray[i], ptrArray[i+1], ptrArray[i+2]));
+		if(ptrArray[i] == 0x318)
+		{
+			ptrArray[i+2] = 0x00000800;
+			//DbgPrint("ptrArray[i], ptrArray[i+1], ptrArray[i+2] = %x, %x, %x\n",
+			//	ptrArray[i], ptrArray[i+1], ptrArray[i+2]);
+		}
+		PHY_SetBBReg(Adapter, ptrArray[i], ptrArray[i+1], ptrArray[i+2]);
+	}*/
+	for(i = 0 ;i < ArrayLength;i=i+2){ // Add by tynli for 2 column
+		write_nic_byte(dev, ptrArray[i], (u8)ptrArray[i+1]);
+	}
+//#endif
+	return RT_STATUS_SUCCESS;
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:    phy_ConfigBBWithHeaderFile()
+ *
+ * Overview:    This function read BB parameters from general file format, and do register
+ *			  Read/Write
+ *
+ * Input:      	PADAPTER		Adapter
+ *			u8 			ConfigType     0 => PHY_CONFIG
+ *										 1 =>AGC_TAB
+ *
+ * Output:      NONE
+ *
+ * Return:      RT_STATUS_SUCCESS: configuration file exist
+ *
+ *---------------------------------------------------------------------------*/
+//use in phy only
+static	RT_STATUS
+phy_ConfigBBWithHeaderFile(struct net_device* dev,u8 ConfigType)
+{
+	int 		i;
+	//u8 		ArrayLength;
+	u32*	Rtl819XPHY_REGArray_Table;
+	u32*	Rtl819XAGCTAB_Array_Table;
+	u16		PHY_REGArrayLen, AGCTAB_ArrayLen;
+	//struct r8192_priv *priv = ieee80211_priv(dev);
+//#if (HAL_CODE_BASE != RTL8192_S)
+	/*if(Adapter->bInHctTest)
+	{
+
+		AGCTAB_ArrayLen = AGCTAB_ArrayLengthDTM;
+		Rtl819XAGCTAB_Array_Table = Rtl819XAGCTAB_ArrayDTM;
+
+		if(pHalData->RF_Type == RF_2T4R)
+		{
+			PHY_REGArrayLen = PHY_REGArrayLengthDTM;
+			Rtl819XPHY_REGArray_Table = Rtl819XPHY_REGArrayDTM;
+		}
+		else if (pHalData->RF_Type == RF_1T2R)
+		{
+			PHY_REGArrayLen = PHY_REG_1T2RArrayLengthDTM;
+			Rtl819XPHY_REGArray_Table = Rtl819XPHY_REG_1T2RArrayDTM;
+		}
+
+	}
+	else
+	*/
+	//{
+	//
+	// 2008.11.06 Modified by tynli.
+	//
+	AGCTAB_ArrayLen = AGCTAB_ArrayLength;
+	Rtl819XAGCTAB_Array_Table = Rtl819XAGCTAB_Array;
+	PHY_REGArrayLen = PHY_REG_2T2RArrayLength; // Default RF_type: 2T2R
+	Rtl819XPHY_REGArray_Table = Rtl819XPHY_REG_Array;
+	//}
+
+	if(ConfigType == BaseBand_Config_PHY_REG)
+	{
+		for(i=0;i<PHY_REGArrayLen;i=i+2)
+		{
+			if (Rtl819XPHY_REGArray_Table[i] == 0xfe)
+				mdelay(50);
+			else if (Rtl819XPHY_REGArray_Table[i] == 0xfd)
+				mdelay(5);
+			else if (Rtl819XPHY_REGArray_Table[i] == 0xfc)
+				mdelay(1);
+			else if (Rtl819XPHY_REGArray_Table[i] == 0xfb)
+				udelay(50);
+			else if (Rtl819XPHY_REGArray_Table[i] == 0xfa)
+				udelay(5);
+			else if (Rtl819XPHY_REGArray_Table[i] == 0xf9)
+				udelay(1);
+			rtl8192_setBBreg(dev, Rtl819XPHY_REGArray_Table[i], bMaskDWord, Rtl819XPHY_REGArray_Table[i+1]);
+			//RT_TRACE(COMP_SEND, "The Rtl819XPHY_REGArray_Table[0] is %lx Rtl819XPHY_REGArray[1] is %lx \n",Rtl819XPHY_REGArray_Table[i], Rtl819XPHY_REGArray_Table[i+1]);
+
+		}
+	}
+	else if(ConfigType == BaseBand_Config_AGC_TAB){
+		for(i=0;i<AGCTAB_ArrayLen;i=i+2)
+		{
+			rtl8192_setBBreg(dev, Rtl819XAGCTAB_Array_Table[i], bMaskDWord, Rtl819XAGCTAB_Array_Table[i+1]);
+		}
+	}
+//#endif	// #if (HAL_CODE_BASE != RTL8192_S)
+	return RT_STATUS_SUCCESS;
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:	phy_ConfigBBWithPgHeaderFile
+ *
+ * Overview:	Config PHY_REG_PG array
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/06/2008 	MHC		Add later!!!!!!.. Please modify for new files!!!!
+ * 11/10/2008	tynli		Modify to mew files.
+ //use in phy only
+ *---------------------------------------------------------------------------*/
+static RT_STATUS
+phy_ConfigBBWithPgHeaderFile(struct net_device* dev,u8 ConfigType)
+{
+	int i;
+	//u8 ArrayLength;
+	u32*	Rtl819XPHY_REGArray_Table_PG;
+	u16	PHY_REGArrayPGLen;
+	//struct r8192_priv *priv = ieee80211_priv(dev);
+//#if (HAL_CODE_BASE != RTL8192_S)
+	// Default: pHalData->RF_Type = RF_2T2R.
+
+	PHY_REGArrayPGLen = PHY_REG_Array_PGLength;
+	Rtl819XPHY_REGArray_Table_PG = Rtl819XPHY_REG_Array_PG;
+
+	if(ConfigType == BaseBand_Config_PHY_REG)
+	{
+		for(i=0;i<PHY_REGArrayPGLen;i=i+3)
+		{
+			if (Rtl819XPHY_REGArray_Table_PG[i] == 0xfe)
+				mdelay(50);
+			else if (Rtl819XPHY_REGArray_Table_PG[i] == 0xfd)
+				mdelay(5);
+			else if (Rtl819XPHY_REGArray_Table_PG[i] == 0xfc)
+				mdelay(1);
+			else if (Rtl819XPHY_REGArray_Table_PG[i] == 0xfb)
+				udelay(50);
+			else if (Rtl819XPHY_REGArray_Table_PG[i] == 0xfa)
+				udelay(5);
+			else if (Rtl819XPHY_REGArray_Table_PG[i] == 0xf9)
+				udelay(1);
+			rtl8192_setBBreg(dev, Rtl819XPHY_REGArray_Table_PG[i], Rtl819XPHY_REGArray_Table_PG[i+1], Rtl819XPHY_REGArray_Table_PG[i+2]);
+			//RT_TRACE(COMP_SEND, "The Rtl819XPHY_REGArray_Table_PG[0] is %lx Rtl819XPHY_REGArray_Table_PG[1] is %lx \n",
+			//		Rtl819XPHY_REGArray_Table_PG[i], Rtl819XPHY_REGArray_Table_PG[i+1]);
+		}
+	}else{
+		RT_TRACE(COMP_SEND, "phy_ConfigBBWithPgHeaderFile(): ConfigType != BaseBand_Config_PHY_REG\n");
+	}
+	return RT_STATUS_SUCCESS;
+
+}	/* phy_ConfigBBWithPgHeaderFile */
+
+/*-----------------------------------------------------------------------------
+ * Function:    PHY_ConfigRFWithHeaderFile()
+ *
+ * Overview:    This function read RF parameters from general file format, and do RF 3-wire
+ *
+ * Input:      	PADAPTER			Adapter
+ *			char* 				pFileName
+ *			RF90_RADIO_PATH_E	eRFPath
+ *
+ * Output:      NONE
+ *
+ * Return:      RT_STATUS_SUCCESS: configuration file exist
+ *
+ * Note:		Delay may be required for RF configuration
+ *---------------------------------------------------------------------------*/
+//in 8256 phy_RF8256_Config_ParaFile only
+//RT_STATUS PHY_ConfigRFWithHeaderFile(struct net_device* dev,RF90_RADIO_PATH_E eRFPath)
+u8 rtl8192_phy_ConfigRFWithHeaderFile(struct net_device* dev, RF90_RADIO_PATH_E	eRFPath)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int			i;
+	//u32*	pRFArray;
+	RT_STATUS	rtStatus = RT_STATUS_SUCCESS;
+	u32			*Rtl819XRadioA_Array_Table;
+	u32			*Rtl819XRadioB_Array_Table;
+	//u32*	Rtl819XRadioC_Array_Table;
+	//u32*	Rtl819XRadioD_Array_Table;
+	u16			RadioA_ArrayLen,RadioB_ArrayLen;
+
+	{	//2008.11.06 Modified by tynli
+		RadioA_ArrayLen = RadioA_1T_ArrayLength;
+		Rtl819XRadioA_Array_Table=Rtl819XRadioA_Array;
+		Rtl819XRadioB_Array_Table=Rtl819XRadioB_Array;
+		RadioB_ArrayLen = RadioB_ArrayLength;
+	}
+
+	if( priv->rf_type == RF_2T2R_GREEN )
+	{
+		Rtl819XRadioB_Array_Table = Rtl819XRadioB_GM_Array;
+		RadioB_ArrayLen = RadioB_GM_ArrayLength;
+	}
+	else
+	{
+		Rtl819XRadioB_Array_Table = Rtl819XRadioB_Array;
+		RadioB_ArrayLen = RadioB_ArrayLength;
+	}
+
+	rtStatus = RT_STATUS_SUCCESS;
+
+	// When initialization, we want the delay function(mdelay(), delay_us()
+	// ==> actually we call PlatformStallExecution()) to do NdisStallExecution()
+	// [busy wait] instead of NdisMSleep(). So we acquire RT_INITIAL_SPINLOCK
+	// to run at Dispatch level to achive it.
+	//cosa PlatformAcquireSpinLock(Adapter, RT_INITIAL_SPINLOCK);
+
+	switch(eRFPath){
+		case RF90_PATH_A:
+			for(i = 0;i<RadioA_ArrayLen; i=i+2){
+				if(Rtl819XRadioA_Array_Table[i] == 0xfe)
+					{ // Deay specific ms. Only RF configuration require delay.
+//#if (DEV_BUS_TYPE == USB_INTERFACE)
+#ifdef RTL8192SU
+						mdelay(1000);
+#else
+						mdelay(50);
+#endif
+				}
+					else if (Rtl819XRadioA_Array_Table[i] == 0xfd)
+						mdelay(5);
+					else if (Rtl819XRadioA_Array_Table[i] == 0xfc)
+						mdelay(1);
+					else if (Rtl819XRadioA_Array_Table[i] == 0xfb)
+						udelay(50);
+						//PlatformStallExecution(50);
+					else if (Rtl819XRadioA_Array_Table[i] == 0xfa)
+						udelay(5);
+					else if (Rtl819XRadioA_Array_Table[i] == 0xf9)
+						udelay(1);
+					else
+					{
+					rtl8192_phy_SetRFReg(dev, eRFPath, Rtl819XRadioA_Array_Table[i], bRFRegOffsetMask, Rtl819XRadioA_Array_Table[i+1]);
+					}
+			}
+			break;
+		case RF90_PATH_B:
+			for(i = 0;i<RadioB_ArrayLen; i=i+2){
+				if(Rtl819XRadioB_Array_Table[i] == 0xfe)
+					{ // Deay specific ms. Only RF configuration require delay.
+//#if (DEV_BUS_TYPE == USB_INTERFACE)
+#ifdef RTL8192SU
+						mdelay(1000);
+#else
+						mdelay(50);
+#endif
+				}
+					else if (Rtl819XRadioB_Array_Table[i] == 0xfd)
+						mdelay(5);
+					else if (Rtl819XRadioB_Array_Table[i] == 0xfc)
+						mdelay(1);
+					else if (Rtl819XRadioB_Array_Table[i] == 0xfb)
+						udelay(50);
+					else if (Rtl819XRadioB_Array_Table[i] == 0xfa)
+						udelay(5);
+					else if (Rtl819XRadioB_Array_Table[i] == 0xf9)
+						udelay(1);
+					else
+					{
+					rtl8192_phy_SetRFReg(dev, eRFPath, Rtl819XRadioB_Array_Table[i], bRFRegOffsetMask, Rtl819XRadioB_Array_Table[i+1]);
+					}
+			}
+			break;
+		case RF90_PATH_C:
+			break;
+		case RF90_PATH_D:
+			break;
+		default:
+			break;
+	}
+
+	return rtStatus;
+
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:    PHY_CheckBBAndRFOK()
+ *
+ * Overview:    This function is write register and then readback to make sure whether
+ *			  BB[PHY0, PHY1], RF[Patha, path b, path c, path d] is Ok
+ *
+ * Input:      	PADAPTER			Adapter
+ *			HW90_BLOCK_E		CheckBlock
+ *			RF90_RADIO_PATH_E	eRFPath		// it is used only when CheckBlock is HW90_BLOCK_RF
+ *
+ * Output:      NONE
+ *
+ * Return:      RT_STATUS_SUCCESS: PHY is OK
+ *
+ * Note:		This function may be removed in the ASIC
+ *---------------------------------------------------------------------------*/
+//in 8256 phy_RF8256_Config_HardCode
+//but we don't use it temp
+RT_STATUS
+PHY_CheckBBAndRFOK(
+	struct net_device* dev,
+	HW90_BLOCK_E		CheckBlock,
+	RF90_RADIO_PATH_E	eRFPath
+	)
+{
+	//struct r8192_priv *priv = ieee80211_priv(dev);
+	RT_STATUS			rtStatus = RT_STATUS_SUCCESS;
+	u32				i, CheckTimes = 4,ulRegRead = 0;
+	u32				WriteAddr[4];
+	u32				WriteData[] = {0xfffff027, 0xaa55a02f, 0x00000027, 0x55aa502f};
+
+	// Initialize register address offset to be checked
+	WriteAddr[HW90_BLOCK_MAC] = 0x100;
+	WriteAddr[HW90_BLOCK_PHY0] = 0x900;
+	WriteAddr[HW90_BLOCK_PHY1] = 0x800;
+	WriteAddr[HW90_BLOCK_RF] = 0x3;
+
+	for(i=0 ; i < CheckTimes ; i++)
+	{
+
+		//
+		// Write Data to register and readback
+		//
+		switch(CheckBlock)
+		{
+		case HW90_BLOCK_MAC:
+			//RT_ASSERT(FALSE, ("PHY_CheckBBRFOK(): Never Write 0x100 here!"));
+			RT_TRACE(COMP_INIT, "PHY_CheckBBRFOK(): Never Write 0x100 here!\n");
+			break;
+
+		case HW90_BLOCK_PHY0:
+		case HW90_BLOCK_PHY1:
+			write_nic_dword(dev, WriteAddr[CheckBlock], WriteData[i]);
+			ulRegRead = read_nic_dword(dev, WriteAddr[CheckBlock]);
+			break;
+
+		case HW90_BLOCK_RF:
+			// When initialization, we want the delay function(mdelay(), delay_us()
+			// ==> actually we call PlatformStallExecution()) to do NdisStallExecution()
+			// [busy wait] instead of NdisMSleep(). So we acquire RT_INITIAL_SPINLOCK
+			// to run at Dispatch level to achive it.
+			//cosa PlatformAcquireSpinLock(dev, RT_INITIAL_SPINLOCK);
+			WriteData[i] &= 0xfff;
+			rtl8192_phy_SetRFReg(dev, eRFPath, WriteAddr[HW90_BLOCK_RF], bRFRegOffsetMask, WriteData[i]);
+			// TODO: we should not delay for such a long time. Ask SD3
+			mdelay(10);
+			ulRegRead = rtl8192_phy_QueryRFReg(dev, eRFPath, WriteAddr[HW90_BLOCK_RF], bMaskDWord);
+			mdelay(10);
+			//cosa PlatformReleaseSpinLock(dev, RT_INITIAL_SPINLOCK);
+			break;
+
+		default:
+			rtStatus = RT_STATUS_FAILURE;
+			break;
+		}
+
+
+		//
+		// Check whether readback data is correct
+		//
+		if(ulRegRead != WriteData[i])
+		{
+			//RT_TRACE(COMP_FPGA,  ("ulRegRead: %x, WriteData: %x \n", ulRegRead, WriteData[i]));
+			RT_TRACE(COMP_ERR, "read back error(read:%x, write:%x)\n", ulRegRead, WriteData[i]);
+			rtStatus = RT_STATUS_FAILURE;
+			break;
+		}
+	}
+
+	return rtStatus;
+}
+
+//no use temp in windows driver
+#ifdef TO_DO_LIST
+void
+PHY_SetRFPowerState8192SUsb(
+	struct net_device* dev,
+	RF_POWER_STATE	RFPowerState
+	)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	bool			WaitShutDown = FALSE;
+	u32			DWordContent;
+	//RF90_RADIO_PATH_E	eRFPath;
+	u8				eRFPath;
+	BB_REGISTER_DEFINITION_T	*pPhyReg;
+
+	if(priv->SetRFPowerStateInProgress == TRUE)
+		return;
+
+	priv->SetRFPowerStateInProgress = TRUE;
+
+	// TODO: Emily, 2006.11.21, we should rewrite this function
+
+	if(RFPowerState==RF_SHUT_DOWN)
+	{
+		RFPowerState=RF_OFF;
+		WaitShutDown=TRUE;
+	}
+
+
+	priv->RFPowerState = RFPowerState;
+	switch( priv->rf_chip )
+	{
+	case RF_8225:
+	case RF_6052:
+		switch( RFPowerState )
+		{
+		case RF_ON:
+			break;
+
+		case RF_SLEEP:
+			break;
+
+		case RF_OFF:
+			break;
+		}
+		break;
+
+	case RF_8256:
+		switch( RFPowerState )
+		{
+		case RF_ON:
+			break;
+
+		case RF_SLEEP:
+			break;
+
+		case RF_OFF:
+			for(eRFPath=(RF90_RADIO_PATH_E)RF90_PATH_A; eRFPath < RF90_PATH_MAX; eRFPath++)
+			{
+				if (!rtl8192_phy_CheckIsLegalRFPath(dev, eRFPath))
+					continue;
+
+				pPhyReg = &priv->PHYRegDef[eRFPath];
+				rtl8192_setBBreg(dev, pPhyReg->rfintfs, bRFSI_RFENV, bRFSI_RFENV);
+				rtl8192_setBBreg(dev, pPhyReg->rfintfo, bRFSI_RFENV, 0);
+			}
+			break;
+		}
+		break;
+
+	case RF_8258:
+		break;
+	}// switch( priv->rf_chip )
+
+	priv->SetRFPowerStateInProgress = FALSE;
+}
+#endif
+
+#ifdef RTL8192U
+//no use temp in windows driver
+void
+PHY_UpdateInitialGain(
+	struct net_device* dev
+	)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	//unsigned char			*IGTable;
+	//u8			DIG_CurrentInitialGain = 4;
+
+	switch(priv->rf_chip)
+	{
+	case RF_8225:
+		break;
+	case RF_8256:
+		break;
+	case RF_8258:
+		break;
+	case RF_PSEUDO_11N:
+		break;
+	case RF_6052:
+		break;
+	default:
+		RT_TRACE(COMP_DBG, "PHY_UpdateInitialGain(): unknown rf_chip: %#X\n", priv->rf_chip);
+		break;
+	}
+}
+#endif
+
+//YJ,modified,090107
+void PHY_GetHWRegOriginalValue(struct net_device* dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	// read tx power offset
+	// Simulate 8192
+	priv->MCSTxPowerLevelOriginalOffset[0] =
+		rtl8192_QueryBBReg(dev, rTxAGC_Rate18_06, bMaskDWord);
+	priv->MCSTxPowerLevelOriginalOffset[1] =
+		rtl8192_QueryBBReg(dev, rTxAGC_Rate54_24, bMaskDWord);
+	priv->MCSTxPowerLevelOriginalOffset[2] =
+		rtl8192_QueryBBReg(dev, rTxAGC_Mcs03_Mcs00, bMaskDWord);
+	priv->MCSTxPowerLevelOriginalOffset[3] =
+		rtl8192_QueryBBReg(dev, rTxAGC_Mcs07_Mcs04, bMaskDWord);
+	priv->MCSTxPowerLevelOriginalOffset[4] =
+		rtl8192_QueryBBReg(dev, rTxAGC_Mcs11_Mcs08, bMaskDWord);
+	priv->MCSTxPowerLevelOriginalOffset[5] =
+		rtl8192_QueryBBReg(dev, rTxAGC_Mcs15_Mcs12, bMaskDWord);
+
+	// Read CCK offset
+	priv->MCSTxPowerLevelOriginalOffset[6] =
+		rtl8192_QueryBBReg(dev, rTxAGC_CCK_Mcs32, bMaskDWord);
+	RT_TRACE(COMP_INIT, "Legacy OFDM =%08x/%08x HT_OFDM=%08x/%08x/%08x/%08x\n",
+	priv->MCSTxPowerLevelOriginalOffset[0], priv->MCSTxPowerLevelOriginalOffset[1] ,
+	priv->MCSTxPowerLevelOriginalOffset[2], priv->MCSTxPowerLevelOriginalOffset[3] ,
+	priv->MCSTxPowerLevelOriginalOffset[4], priv->MCSTxPowerLevelOriginalOffset[5] );
+
+	// read rx initial gain
+	priv->DefaultInitialGain[0] = rtl8192_QueryBBReg(dev, rOFDM0_XAAGCCore1, bMaskByte0);
+	priv->DefaultInitialGain[1] = rtl8192_QueryBBReg(dev, rOFDM0_XBAGCCore1, bMaskByte0);
+	priv->DefaultInitialGain[2] = rtl8192_QueryBBReg(dev, rOFDM0_XCAGCCore1, bMaskByte0);
+	priv->DefaultInitialGain[3] = rtl8192_QueryBBReg(dev, rOFDM0_XDAGCCore1, bMaskByte0);
+	RT_TRACE(COMP_INIT, "Default initial gain (c50=0x%x, c58=0x%x, c60=0x%x, c68=0x%x) \n",
+			priv->DefaultInitialGain[0], priv->DefaultInitialGain[1],
+			priv->DefaultInitialGain[2], priv->DefaultInitialGain[3]);
+
+	// read framesync
+	priv->framesync = rtl8192_QueryBBReg(dev, rOFDM0_RxDetector3, bMaskByte0);
+	priv->framesyncC34 = rtl8192_QueryBBReg(dev, rOFDM0_RxDetector2, bMaskDWord);
+	RT_TRACE(COMP_INIT, "Default framesync (0x%x) = 0x%x \n",
+				rOFDM0_RxDetector3, priv->framesync);
+}
+//YJ,modified,090107,end
+
+
+
+/**
+* Function:	phy_InitBBRFRegisterDefinition
+*
+* OverView:	Initialize Register definition offset for Radio Path A/B/C/D
+*
+* Input:
+*			PADAPTER		Adapter,
+*
+* Output:	None
+* Return:		None
+* Note:		The initialization value is constant and it should never be changes
+*/
+//use in phy only
+static void phy_InitBBRFRegisterDefinition(	struct net_device* dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	// RF Interface Sowrtware Control
+	priv->PHYRegDef[RF90_PATH_A].rfintfs = rFPGA0_XAB_RFInterfaceSW; // 16 LSBs if read 32-bit from 0x870
+	priv->PHYRegDef[RF90_PATH_B].rfintfs = rFPGA0_XAB_RFInterfaceSW; // 16 MSBs if read 32-bit from 0x870 (16-bit for 0x872)
+	priv->PHYRegDef[RF90_PATH_C].rfintfs = rFPGA0_XCD_RFInterfaceSW;// 16 LSBs if read 32-bit from 0x874
+	priv->PHYRegDef[RF90_PATH_D].rfintfs = rFPGA0_XCD_RFInterfaceSW;// 16 MSBs if read 32-bit from 0x874 (16-bit for 0x876)
+
+	// RF Interface Readback Value
+	priv->PHYRegDef[RF90_PATH_A].rfintfi = rFPGA0_XAB_RFInterfaceRB; // 16 LSBs if read 32-bit from 0x8E0
+	priv->PHYRegDef[RF90_PATH_B].rfintfi = rFPGA0_XAB_RFInterfaceRB;// 16 MSBs if read 32-bit from 0x8E0 (16-bit for 0x8E2)
+	priv->PHYRegDef[RF90_PATH_C].rfintfi = rFPGA0_XCD_RFInterfaceRB;// 16 LSBs if read 32-bit from 0x8E4
+	priv->PHYRegDef[RF90_PATH_D].rfintfi = rFPGA0_XCD_RFInterfaceRB;// 16 MSBs if read 32-bit from 0x8E4 (16-bit for 0x8E6)
+
+	// RF Interface Output (and Enable)
+	priv->PHYRegDef[RF90_PATH_A].rfintfo = rFPGA0_XA_RFInterfaceOE; // 16 LSBs if read 32-bit from 0x860
+	priv->PHYRegDef[RF90_PATH_B].rfintfo = rFPGA0_XB_RFInterfaceOE; // 16 LSBs if read 32-bit from 0x864
+	priv->PHYRegDef[RF90_PATH_C].rfintfo = rFPGA0_XC_RFInterfaceOE;// 16 LSBs if read 32-bit from 0x868
+	priv->PHYRegDef[RF90_PATH_D].rfintfo = rFPGA0_XD_RFInterfaceOE;// 16 LSBs if read 32-bit from 0x86C
+
+	// RF Interface (Output and)  Enable
+	priv->PHYRegDef[RF90_PATH_A].rfintfe = rFPGA0_XA_RFInterfaceOE; // 16 MSBs if read 32-bit from 0x860 (16-bit for 0x862)
+	priv->PHYRegDef[RF90_PATH_B].rfintfe = rFPGA0_XB_RFInterfaceOE; // 16 MSBs if read 32-bit from 0x864 (16-bit for 0x866)
+	priv->PHYRegDef[RF90_PATH_C].rfintfe = rFPGA0_XC_RFInterfaceOE;// 16 MSBs if read 32-bit from 0x86A (16-bit for 0x86A)
+	priv->PHYRegDef[RF90_PATH_D].rfintfe = rFPGA0_XD_RFInterfaceOE;// 16 MSBs if read 32-bit from 0x86C (16-bit for 0x86E)
+
+	//Addr of LSSI. Wirte RF register by driver
+	priv->PHYRegDef[RF90_PATH_A].rf3wireOffset = rFPGA0_XA_LSSIParameter; //LSSI Parameter
+	priv->PHYRegDef[RF90_PATH_B].rf3wireOffset = rFPGA0_XB_LSSIParameter;
+	priv->PHYRegDef[RF90_PATH_C].rf3wireOffset = rFPGA0_XC_LSSIParameter;
+	priv->PHYRegDef[RF90_PATH_D].rf3wireOffset = rFPGA0_XD_LSSIParameter;
+
+	// RF parameter
+	priv->PHYRegDef[RF90_PATH_A].rfLSSI_Select = rFPGA0_XAB_RFParameter;  //BB Band Select
+	priv->PHYRegDef[RF90_PATH_B].rfLSSI_Select = rFPGA0_XAB_RFParameter;
+	priv->PHYRegDef[RF90_PATH_C].rfLSSI_Select = rFPGA0_XCD_RFParameter;
+	priv->PHYRegDef[RF90_PATH_D].rfLSSI_Select = rFPGA0_XCD_RFParameter;
+
+	// Tx AGC Gain Stage (same for all path. Should we remove this?)
+	priv->PHYRegDef[RF90_PATH_A].rfTxGainStage = rFPGA0_TxGainStage; //Tx gain stage
+	priv->PHYRegDef[RF90_PATH_B].rfTxGainStage = rFPGA0_TxGainStage; //Tx gain stage
+	priv->PHYRegDef[RF90_PATH_C].rfTxGainStage = rFPGA0_TxGainStage; //Tx gain stage
+	priv->PHYRegDef[RF90_PATH_D].rfTxGainStage = rFPGA0_TxGainStage; //Tx gain stage
+
+	// Tranceiver A~D HSSI Parameter-1
+	priv->PHYRegDef[RF90_PATH_A].rfHSSIPara1 = rFPGA0_XA_HSSIParameter1;  //wire control parameter1
+	priv->PHYRegDef[RF90_PATH_B].rfHSSIPara1 = rFPGA0_XB_HSSIParameter1;  //wire control parameter1
+	priv->PHYRegDef[RF90_PATH_C].rfHSSIPara1 = rFPGA0_XC_HSSIParameter1;  //wire control parameter1
+	priv->PHYRegDef[RF90_PATH_D].rfHSSIPara1 = rFPGA0_XD_HSSIParameter1;  //wire control parameter1
+
+	// Tranceiver A~D HSSI Parameter-2
+	priv->PHYRegDef[RF90_PATH_A].rfHSSIPara2 = rFPGA0_XA_HSSIParameter2;  //wire control parameter2
+	priv->PHYRegDef[RF90_PATH_B].rfHSSIPara2 = rFPGA0_XB_HSSIParameter2;  //wire control parameter2
+	priv->PHYRegDef[RF90_PATH_C].rfHSSIPara2 = rFPGA0_XC_HSSIParameter2;  //wire control parameter2
+	priv->PHYRegDef[RF90_PATH_D].rfHSSIPara2 = rFPGA0_XD_HSSIParameter2;  //wire control parameter1
+
+	// RF switch Control
+	priv->PHYRegDef[RF90_PATH_A].rfSwitchControl = rFPGA0_XAB_SwitchControl; //TR/Ant switch control
+	priv->PHYRegDef[RF90_PATH_B].rfSwitchControl = rFPGA0_XAB_SwitchControl;
+	priv->PHYRegDef[RF90_PATH_C].rfSwitchControl = rFPGA0_XCD_SwitchControl;
+	priv->PHYRegDef[RF90_PATH_D].rfSwitchControl = rFPGA0_XCD_SwitchControl;
+
+	// AGC control 1
+	priv->PHYRegDef[RF90_PATH_A].rfAGCControl1 = rOFDM0_XAAGCCore1;
+	priv->PHYRegDef[RF90_PATH_B].rfAGCControl1 = rOFDM0_XBAGCCore1;
+	priv->PHYRegDef[RF90_PATH_C].rfAGCControl1 = rOFDM0_XCAGCCore1;
+	priv->PHYRegDef[RF90_PATH_D].rfAGCControl1 = rOFDM0_XDAGCCore1;
+
+	// AGC control 2
+	priv->PHYRegDef[RF90_PATH_A].rfAGCControl2 = rOFDM0_XAAGCCore2;
+	priv->PHYRegDef[RF90_PATH_B].rfAGCControl2 = rOFDM0_XBAGCCore2;
+	priv->PHYRegDef[RF90_PATH_C].rfAGCControl2 = rOFDM0_XCAGCCore2;
+	priv->PHYRegDef[RF90_PATH_D].rfAGCControl2 = rOFDM0_XDAGCCore2;
+
+	// RX AFE control 1
+	priv->PHYRegDef[RF90_PATH_A].rfRxIQImbalance = rOFDM0_XARxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_B].rfRxIQImbalance = rOFDM0_XBRxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_C].rfRxIQImbalance = rOFDM0_XCRxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_D].rfRxIQImbalance = rOFDM0_XDRxIQImbalance;
+
+	// RX AFE control 1
+	priv->PHYRegDef[RF90_PATH_A].rfRxAFE = rOFDM0_XARxAFE;
+	priv->PHYRegDef[RF90_PATH_B].rfRxAFE = rOFDM0_XBRxAFE;
+	priv->PHYRegDef[RF90_PATH_C].rfRxAFE = rOFDM0_XCRxAFE;
+	priv->PHYRegDef[RF90_PATH_D].rfRxAFE = rOFDM0_XDRxAFE;
+
+	// Tx AFE control 1
+	priv->PHYRegDef[RF90_PATH_A].rfTxIQImbalance = rOFDM0_XATxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_B].rfTxIQImbalance = rOFDM0_XBTxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_C].rfTxIQImbalance = rOFDM0_XCTxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_D].rfTxIQImbalance = rOFDM0_XDTxIQImbalance;
+
+	// Tx AFE control 2
+	priv->PHYRegDef[RF90_PATH_A].rfTxAFE = rOFDM0_XATxAFE;
+	priv->PHYRegDef[RF90_PATH_B].rfTxAFE = rOFDM0_XBTxAFE;
+	priv->PHYRegDef[RF90_PATH_C].rfTxAFE = rOFDM0_XCTxAFE;
+	priv->PHYRegDef[RF90_PATH_D].rfTxAFE = rOFDM0_XDTxAFE;
+
+	// Tranceiver LSSI Readback  SI mode
+	priv->PHYRegDef[RF90_PATH_A].rfLSSIReadBack = rFPGA0_XA_LSSIReadBack;
+	priv->PHYRegDef[RF90_PATH_B].rfLSSIReadBack = rFPGA0_XB_LSSIReadBack;
+	priv->PHYRegDef[RF90_PATH_C].rfLSSIReadBack = rFPGA0_XC_LSSIReadBack;
+	priv->PHYRegDef[RF90_PATH_D].rfLSSIReadBack = rFPGA0_XD_LSSIReadBack;
+
+	// Tranceiver LSSI Readback PI mode
+	priv->PHYRegDef[RF90_PATH_A].rfLSSIReadBackPi = TransceiverA_HSPI_Readback;
+	priv->PHYRegDef[RF90_PATH_B].rfLSSIReadBackPi = TransceiverB_HSPI_Readback;
+	//pHalData->PHYRegDef[RF90_PATH_C].rfLSSIReadBackPi = rFPGA0_XC_LSSIReadBack;
+	//pHalData->PHYRegDef[RF90_PATH_D].rfLSSIReadBackPi = rFPGA0_XD_LSSIReadBack;
+
+}
+
+
+//
+//	Description:  Change RF power state.
+//
+//	Assumption: This function must be executed in re-schdulable context,
+//		ie. PASSIVE_LEVEL.
+//
+//	050823, by rcnjko.
+//not understand it seem's use in init
+//SetHwReg8192SUsb--->HalFunc.SetHwRegHandler
+bool PHY_SetRFPowerState(struct net_device* dev, RT_RF_POWER_STATE eRFPowerState)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	bool			bResult = FALSE;
+
+	RT_TRACE(COMP_RF, "---------> PHY_SetRFPowerState(): eRFPowerState(%d)\n", eRFPowerState);
+
+	if(eRFPowerState == priv->ieee80211->eRFPowerState)
+	{
+		RT_TRACE(COMP_RF, "<--------- PHY_SetRFPowerState(): discard the request for eRFPowerState(%d) is the same.\n", eRFPowerState);
+		return bResult;
+	}
+
+	bResult = phy_SetRFPowerState8192SU(dev, eRFPowerState);
+
+	RT_TRACE(COMP_RF, "<--------- PHY_SetRFPowerState(): bResult(%d)\n", bResult);
+
+	return bResult;
+}
+
+//use in phy only
+static bool phy_SetRFPowerState8192SU(struct net_device* dev,RT_RF_POWER_STATE eRFPowerState)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	bool			bResult = TRUE;
+	//u8		eRFPath;
+	//u8		i, QueueID;
+	u8 		u1bTmp;
+
+	if(priv->SetRFPowerStateInProgress == TRUE)
+		return FALSE;
+
+	priv->SetRFPowerStateInProgress = TRUE;
+
+	switch(priv->rf_chip )
+	{
+		default:
+		switch( eRFPowerState )
+		{
+			case eRfOn:
+				write_nic_dword(dev, WFM5, FW_BB_RESET_ENABLE);
+				write_nic_word(dev, CMDR, 0x37FC);
+				write_nic_byte(dev, PHY_CCA, 0x3);
+				write_nic_byte(dev, TXPAUSE, 0x00);
+				write_nic_byte(dev, SPS1_CTRL, 0x64);
+				break;
+
+			//
+			// In current solution, RFSleep=RFOff in order to save power under 802.11 power save.
+			// By Bruce, 2008-01-16.
+			//
+			case eRfSleep:
+			case eRfOff:
+			  	if (priv->ieee80211->eRFPowerState == eRfSleep || priv->ieee80211->eRFPowerState == eRfOff)
+						break;
+#ifdef NOT_YET
+				// Make sure BusyQueue is empty befor turn off RFE pwoer.
+				for(QueueID = 0, i = 0; QueueID < MAX_TX_QUEUE; )
+				{
+					if(RTIsListEmpty(&Adapter->TcbBusyQueue[QueueID]))
+					{
+						QueueID++;
+						continue;
+					}
+					else
+					{
+						RT_TRACE(COMP_POWER, "eRf Off/Sleep: %d times TcbBusyQueue[%d] !=0 before doze!\n", (i+1), QueueID);
+						udelay(10);
+						i++;
+					}
+
+					if(i >= MAX_DOZE_WAITING_TIMES_9x)
+					{
+						RT_TRACE(COMP_POWER, "\n\n\n SetZebraRFPowerState8185B(): eRfOff: %d times TcbBusyQueue[%d] != 0 !!!\n\n\n", MAX_DOZE_WAITING_TIMES_9x, QueueID);
+						break;
+					}
+				}
+#endif
+				//
+				//RF Off/Sleep sequence. Designed/tested from SD4 Scott, SD1 Grent and Jonbon.
+				// Added by Bruce, 2008-11-22.
+				//
+				//==================================================================
+				// (0) Disable FW BB reset checking
+				write_nic_dword(dev, WFM5, FW_BB_RESET_DISABLE);
+
+				// (1) Switching Power Supply Register : Disable LD12 & SW12 (for IT)
+				u1bTmp = read_nic_byte(dev, LDOV12D_CTRL);
+				u1bTmp |= BIT0;
+				write_nic_byte(dev, LDOV12D_CTRL, u1bTmp);
+
+				write_nic_byte(dev, SPS1_CTRL, 0x0);
+				write_nic_byte(dev, TXPAUSE, 0xFF);
+
+				// (2) MAC Tx/Rx enable, BB enable, CCK/OFDM enable
+				write_nic_word(dev, CMDR, 0x77FC);
+				write_nic_byte(dev, PHY_CCA, 0x0);
+				udelay(100);
+
+				write_nic_word(dev, CMDR, 0x37FC);
+				udelay(10);
+
+				write_nic_word(dev, CMDR, 0x77FC);
+				udelay(10);
+
+				// (3) Reset BB TRX blocks
+				write_nic_word(dev, CMDR, 0x57FC);
+				break;
+
+			default:
+				bResult = FALSE;
+				//RT_ASSERT(FALSE, ("phy_SetRFPowerState8192SU(): unknow state to set: 0x%X!!!\n", eRFPowerState));
+				break;
+		}
+		break;
+
+	}
+	priv->ieee80211->eRFPowerState = eRFPowerState;
+#ifdef TO_DO_LIST
+	if(bResult)
+	{
+		// Update current RF state variable.
+		priv->ieee80211->eRFPowerState = eRFPowerState;
+
+		switch(priv->rf_chip )
+		{
+			case RF_8256:
+			switch(priv->ieee80211->eRFPowerState)
+			{
+				case eRfOff:
+					//
+					//If Rf off reason is from IPS, Led should blink with no link, by Maddest 071015
+					//
+					if(pMgntInfo->RfOffReason==RF_CHANGE_BY_IPS )
+					{
+						dev->HalFunc.LedControlHandler(dev,LED_CTL_NO_LINK);
+					}
+					else
+					{
+						// Turn off LED if RF is not ON.
+						dev->HalFunc.LedControlHandler(dev, LED_CTL_POWER_OFF);
+					}
+					break;
+
+				case eRfOn:
+					// Turn on RF we are still linked, which might happen when
+					// we quickly turn off and on HW RF. 2006.05.12, by rcnjko.
+					if( pMgntInfo->bMediaConnect == TRUE )
+					{
+						dev->HalFunc.LedControlHandler(dev, LED_CTL_LINK);
+					}
+					else
+					{
+						// Turn off LED if RF is not ON.
+						dev->HalFunc.LedControlHandler(dev, LED_CTL_NO_LINK);
+					}
+					break;
+
+				default:
+					// do nothing.
+					break;
+			}// Switch RF state
+
+				break;
+
+			default:
+				RT_TRACE(COMP_RF, "phy_SetRFPowerState8192SU(): Unknown RF type\n");
+				break;
+		}// Switch rf_chip
+	}
+#endif
+	priv->SetRFPowerStateInProgress = FALSE;
+
+	return bResult;
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:    GetTxPowerLevel8190()
+ *
+ * Overview:    This function is export to "common" moudule
+ *
+ * Input:       PADAPTER		Adapter
+ *			psByte			Power Level
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ *---------------------------------------------------------------------------*/
+ // no use temp
+ void
+PHY_GetTxPowerLevel8192S(
+	struct net_device* dev,
+	 long*    		powerlevel
+	)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8			TxPwrLevel = 0;
+	long			TxPwrDbm;
+	//
+	// Because the Tx power indexes are different, we report the maximum of them to
+	// meet the CCX TPC request. By Bruce, 2008-01-31.
+	//
+
+	// CCK
+	TxPwrLevel = priv->CurrentCckTxPwrIdx;
+	TxPwrDbm = phy_TxPwrIdxToDbm(dev, WIRELESS_MODE_B, TxPwrLevel);
+
+	// Legacy OFDM
+	TxPwrLevel = priv->CurrentOfdm24GTxPwrIdx + priv->LegacyHTTxPowerDiff;
+
+	// Compare with Legacy OFDM Tx power.
+	if(phy_TxPwrIdxToDbm(dev, WIRELESS_MODE_G, TxPwrLevel) > TxPwrDbm)
+		TxPwrDbm = phy_TxPwrIdxToDbm(dev, WIRELESS_MODE_G, TxPwrLevel);
+
+	// HT OFDM
+	TxPwrLevel = priv->CurrentOfdm24GTxPwrIdx;
+
+	// Compare with HT OFDM Tx power.
+	if(phy_TxPwrIdxToDbm(dev, WIRELESS_MODE_N_24G, TxPwrLevel) > TxPwrDbm)
+		TxPwrDbm = phy_TxPwrIdxToDbm(dev, WIRELESS_MODE_N_24G, TxPwrLevel);
+
+	*powerlevel = TxPwrDbm;
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:    SetTxPowerLevel8190()
+ *
+ * Overview:    This function is export to "HalCommon" moudule
+ *
+ * Input:       PADAPTER		Adapter
+ *			u1Byte		channel
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *	2008/11/04	MHC		We remove EEPROM_93C56.
+ *						We need to move CCX relative code to independet file.
+*	2009/01/21	MHC		Support new EEPROM format from SD3 requirement.
+  *---------------------------------------------------------------------------*/
+ void PHY_SetTxPowerLevel8192S(struct net_device* dev, u8	channel)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//HAL_DATA_TYPE		*pHalData = GET_HAL_DATA(dev);
+	u8	powerlevel = (u8)EEPROM_Default_TxPower, powerlevelOFDM24G = 0x10;
+	s8 	ant_pwr_diff = 0;
+	u32	u4RegValue;
+	u8	index = (channel -1);
+	// 2009/01/22 MH Add for new EEPROM format from SD3
+	u8	pwrdiff[2] = {0};
+	u8	ht20pwr[2] = {0}, ht40pwr[2] = {0};
+	u8	rfpath = 0, rfpathnum = 2;
+
+	if(priv->bTXPowerDataReadFromEEPORM == FALSE)
+		return;
+
+	//
+	// Read predefined TX power index in EEPROM
+	//
+//	if(priv->epromtype == EPROM_93c46)
+	{
+#ifdef EEPROM_OLD_FORMAT_SUPPORT
+		powerlevel = priv->TxPowerLevelCCK[index];
+		powerlevelOFDM24G = priv->TxPowerLevelOFDM24G[index];
+#else
+		//
+		// Mainly we use RF-A Tx Power to write the Tx Power registers, but the RF-B Tx
+		// Power must be calculated by the antenna diff.
+		// So we have to rewrite Antenna gain offset register here.
+		// Please refer to BB register 0x80c
+		// 1. For CCK.
+		// 2. For OFDM 1T or 2T
+		//
+
+		// 1. CCK
+		powerlevel = priv->RfTxPwrLevelCck[0][index];
+
+		if (priv->rf_type == RF_1T2R || priv->rf_type == RF_1T1R)
+		{
+		// Read HT 40 OFDM TX power
+		powerlevelOFDM24G = priv->RfTxPwrLevelOfdm1T[0][index];
+		// RF B HT OFDM pwr-RFA HT OFDM pwr
+		// Only one RF we need not to decide B <-> A pwr diff
+
+		// Legacy<->HT pwr diff, we only care about path A.
+
+		// We only assume 1T as RF path A
+		rfpathnum = 1;
+		ht20pwr[0] = ht40pwr[0] = priv->RfTxPwrLevelOfdm1T[0][index];
+		}
+		else if (priv->rf_type == RF_2T2R)
+		{
+		// Read HT 40 OFDM TX power
+		powerlevelOFDM24G = priv->RfTxPwrLevelOfdm2T[0][index];
+			// RF B HT OFDM pwr-RFA HT OFDM pwr
+		ant_pwr_diff = 	priv->RfTxPwrLevelOfdm2T[1][index] -
+						priv->RfTxPwrLevelOfdm2T[0][index];
+			// RF B (HT OFDM pwr+legacy-ht-diff) -(RFA HT OFDM pwr+legacy-ht-diff)
+		// We can not handle Path B&A HT/Legacy pwr diff for 92S now.
+
+		//RTPRINT(FPHY, PHY_TXPWR, ("CH-%d HT40 A/B Pwr index = %x/%x(%d/%d)\n",
+		//channel, priv->RfTxPwrLevelOfdm2T[0][index],
+		//priv->RfTxPwrLevelOfdm2T[1][index],
+		//priv->RfTxPwrLevelOfdm2T[0][index],
+		//priv->RfTxPwrLevelOfdm2T[1][index]));
+
+		ht20pwr[0] = ht40pwr[0] = priv->RfTxPwrLevelOfdm2T[0][index];
+		ht20pwr[1] = ht40pwr[1] = priv->RfTxPwrLevelOfdm2T[1][index];
+	}
+
+	//
+	// 2009/01/21 MH Support new EEPROM format from SD3 requirement
+	// 2009/02/10 Cosa, Here is only for reg B/C/D to A gain diff.
+	//
+	if (priv->EEPROMVersion == 2)	// Defined by SD1 Jong
+	{
+		if (priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20)
+		{
+			for (rfpath = 0; rfpath < rfpathnum; rfpath++)
+			{
+				// HT 20<->40 pwr diff
+				pwrdiff[rfpath] = priv->TxPwrHt20Diff[rfpath][index];
+
+				// Calculate Antenna pwr diff
+				if (pwrdiff[rfpath] < 8)	// 0~+7
+				{
+				#if 0//cosa, it doesn't need to add the offset here
+					if (rfpath == 0)
+						powerlevelOFDM24G += pwrdiff[rfpath];
+				#endif
+					ht20pwr[rfpath] += pwrdiff[rfpath];
+				}
+				else				// index8-15=-8~-1
+				{
+				#if 0//cosa, it doesn't need to add the offset here
+					if (rfpath == 0)
+						powerlevelOFDM24G -= (15-pwrdiff[rfpath]);
+				#endif
+					ht20pwr[rfpath] -= (15-pwrdiff[rfpath]);
+				}
+			}
+
+			// RF B HT OFDM pwr-RFA HT OFDM pwr
+			if (priv->rf_type == RF_2T2R)
+				ant_pwr_diff = ht20pwr[1] - ht20pwr[0];
+
+			//RTPRINT(FPHY, PHY_TXPWR,
+			//("HT20 to HT40 pwrdiff[A/B]=%d/%d, ant_pwr_diff=%d(B-A=%d-%d)\n",
+			//pwrdiff[0], pwrdiff[1], ant_pwr_diff, ht20pwr[1], ht20pwr[0]));
+		}
+
+		// Band Edge scheme is enabled for FCC mode
+		if (priv->TxPwrbandEdgeFlag == 1/* && pHalData->ChannelPlan == 0*/)
+		{
+			for (rfpath = 0; rfpath < rfpathnum; rfpath++)
+			{
+				pwrdiff[rfpath] = 0;
+				if (priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
+				{
+					if (channel <= 3)
+						pwrdiff[rfpath] = priv->TxPwrbandEdgeHt40[rfpath][0];
+					else if (channel >= 9)
+						pwrdiff[rfpath] = priv->TxPwrbandEdgeHt40[rfpath][1];
+					else
+						pwrdiff[rfpath] = 0;
+
+					ht40pwr[rfpath] -= pwrdiff[rfpath];
+				}
+				else if (priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20)
+				{
+					if (channel == 1)
+						pwrdiff[rfpath] = priv->TxPwrbandEdgeHt20[rfpath][0];
+					else if (channel >= 11)
+						pwrdiff[rfpath] = priv->TxPwrbandEdgeHt20[rfpath][1];
+					else
+						pwrdiff[rfpath] = 0;
+
+					ht20pwr[rfpath] -= pwrdiff[rfpath];
+				}
+			#if 0//cosa, it doesn't need to add the offset here
+				if (rfpath == 0)
+					powerlevelOFDM24G -= pwrdiff[rfpath];
+			#endif
+			}
+
+			if (priv->rf_type == RF_2T2R)
+			{
+				// HT 20/40 must decide if they need to minus  BD pwr offset
+				if (priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
+					ant_pwr_diff = ht40pwr[1] - ht40pwr[0];
+				else
+					ant_pwr_diff = ht20pwr[1] - ht20pwr[0];
+			}
+			if (priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20)
+			{
+				if (channel <= 1 || channel >= 11)
+				{
+					//RTPRINT(FPHY, PHY_TXPWR,
+					//("HT20 Band-edge pwrdiff[A/B]=%d/%d, ant_pwr_diff=%d(B-A=%d-%d)\n",
+					//pwrdiff[0], pwrdiff[1], ant_pwr_diff, ht20pwr[1], ht20pwr[0]));
+				}
+			}
+			else
+			{
+				if (channel <= 3 || channel >= 9)
+				{
+					//RTPRINT(FPHY, PHY_TXPWR,
+					//("HT40 Band-edge pwrdiff[A/B]=%d/%d, ant_pwr_diff=%d(B-A=%d-%d)\n",
+					//pwrdiff[0], pwrdiff[1], ant_pwr_diff, ht40pwr[1], ht40pwr[0]));
+				}
+			}
+		}
+#if 0//cosa, useless
+		// Read HT/Legacy OFDM diff
+		legacy_ant_pwr_diff= pHalData->TxPwrLegacyHtDiff[RF90_PATH_A][index];
+#endif
+		}
+
+	//Cosa added for protection, the reg rFPGA0_TxGainStage
+	// range is from 7~-8, index = 0x0~0xf
+	if(ant_pwr_diff > 7)
+		ant_pwr_diff = 7;
+	if(ant_pwr_diff < -8)
+		ant_pwr_diff = -8;
+
+		//RTPRINT(FPHY, PHY_TXPWR,
+		//("CCK/HT Power index = %x/%x(%d/%d), ant_pwr_diff=%d\n",
+		//powerlevel, powerlevelOFDM24G, powerlevel, powerlevelOFDM24G, ant_pwr_diff));
+
+		ant_pwr_diff &= 0xf;
+
+		// Antenna TX power difference
+		priv->AntennaTxPwDiff[2] = 0;// RF-D, don't care
+		priv->AntennaTxPwDiff[1] = 0;// RF-C, don't care
+		priv->AntennaTxPwDiff[0] = (u8)(ant_pwr_diff);		// RF-B
+
+		// Antenna gain offset from B/C/D to A
+		u4RegValue = (	priv->AntennaTxPwDiff[2]<<8 |
+						priv->AntennaTxPwDiff[1]<<4 |
+						priv->AntennaTxPwDiff[0]	);
+
+		// Notify Tx power difference for B/C/D to A!!!
+		rtl8192_setBBreg(dev, rFPGA0_TxGainStage, (bXBTxAGC|bXCTxAGC|bXDTxAGC), u4RegValue);
+#endif
+	}
+
+	//
+	// CCX 2 S31, AP control of client transmit power:
+	// 1. We shall not exceed Cell Power Limit as possible as we can.
+	// 2. Tolerance is +/- 5dB.
+	// 3. 802.11h Power Contraint takes higher precedence over CCX Cell Power Limit.
+	//
+	// TODO:
+	// 1. 802.11h power contraint
+	//
+	// 071011, by rcnjko.
+	//
+#ifdef TODO //WB, 11h has not implemented now.
+	if(	priv->ieee80211->iw_mode != IW_MODE_INFRA && priv->bWithCcxCellPwr &&
+		channel == priv->ieee80211->current_network.channel)// & priv->ieee80211->mAssoc )
+	{
+		u8	CckCellPwrIdx = phy_DbmToTxPwrIdx(dev, WIRELESS_MODE_B, priv->CcxCellPwr);
+		u8	LegacyOfdmCellPwrIdx = phy_DbmToTxPwrIdx(dev, WIRELESS_MODE_G, priv->CcxCellPwr);
+		u8	OfdmCellPwrIdx = phy_DbmToTxPwrIdx(dev, WIRELESS_MODE_N_24G, priv->CcxCellPwr);
+
+		RT_TRACE(COMP_TXAGC,
+		("CCX Cell Limit: %d dbm => CCK Tx power index : %d, Legacy OFDM Tx power index : %d, OFDM Tx power index: %d\n",
+		priv->CcxCellPwr, CckCellPwrIdx, LegacyOfdmCellPwrIdx, OfdmCellPwrIdx));
+		RT_TRACE(COMP_TXAGC,
+		("EEPROM channel(%d) => CCK Tx power index: %d, Legacy OFDM Tx power index : %d, OFDM Tx power index: %d\n",
+		channel, powerlevel, powerlevelOFDM24G + priv->LegacyHTTxPowerDiff, powerlevelOFDM24G));
+
+		// CCK
+		if(powerlevel > CckCellPwrIdx)
+			powerlevel = CckCellPwrIdx;
+		// Legacy OFDM, HT OFDM
+		if(powerlevelOFDM24G + priv->LegacyHTTxPowerDiff > LegacyOfdmCellPwrIdx)
+		{
+			if((OfdmCellPwrIdx - priv->LegacyHTTxPowerDiff) > 0)
+			{
+				powerlevelOFDM24G = OfdmCellPwrIdx - priv->LegacyHTTxPowerDiff;
+			}
+			else
+			{
+				powerlevelOFDM24G = 0;
+			}
+		}
+
+		RT_TRACE(COMP_TXAGC,
+		("Altered CCK Tx power index : %d, Legacy OFDM Tx power index: %d, OFDM Tx power index: %d\n",
+		powerlevel, powerlevelOFDM24G + priv->LegacyHTTxPowerDiff, powerlevelOFDM24G));
+	}
+#endif
+
+	priv->CurrentCckTxPwrIdx = powerlevel;
+	priv->CurrentOfdm24GTxPwrIdx = powerlevelOFDM24G;
+
+	switch(priv->rf_chip)
+	{
+		case RF_8225:
+			//PHY_SetRF8225CckTxPower(dev, powerlevel);
+			//PHY_SetRF8225OfdmTxPower(dev, powerlevelOFDM24G);
+		break;
+
+		case RF_8256:
+#if 0
+			PHY_SetRF8256CCKTxPower(dev, powerlevel);
+			PHY_SetRF8256OFDMTxPower(dev, powerlevelOFDM24G);
+#endif
+			break;
+
+		case RF_6052:
+			PHY_RF6052SetCckTxPower(dev, powerlevel);
+			PHY_RF6052SetOFDMTxPower(dev, powerlevelOFDM24G);
+			break;
+
+		case RF_8258:
+			break;
+		default:
+			break;
+	}
+
+}
+
+//
+//	Description:
+//		Update transmit power level of all channel supported.
+//
+//	TODO:
+//		A mode.
+//	By Bruce, 2008-02-04.
+//    no use temp
+bool PHY_UpdateTxPowerDbm8192S(struct net_device* dev, long powerInDbm)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	u8				idx;
+	u8				rf_path;
+
+	// TODO: A mode Tx power.
+	u8	CckTxPwrIdx = phy_DbmToTxPwrIdx(dev, WIRELESS_MODE_B, powerInDbm);
+	u8	OfdmTxPwrIdx = phy_DbmToTxPwrIdx(dev, WIRELESS_MODE_N_24G, powerInDbm);
+
+	if(OfdmTxPwrIdx - priv->LegacyHTTxPowerDiff > 0)
+		OfdmTxPwrIdx -= priv->LegacyHTTxPowerDiff;
+	else
+		OfdmTxPwrIdx = 0;
+
+	for(idx = 0; idx < 14; idx++)
+	{
+		priv->TxPowerLevelCCK[idx] = CckTxPwrIdx;
+		priv->TxPowerLevelCCK_A[idx] = CckTxPwrIdx;
+		priv->TxPowerLevelCCK_C[idx] = CckTxPwrIdx;
+		priv->TxPowerLevelOFDM24G[idx] = OfdmTxPwrIdx;
+		priv->TxPowerLevelOFDM24G_A[idx] = OfdmTxPwrIdx;
+		priv->TxPowerLevelOFDM24G_C[idx] = OfdmTxPwrIdx;
+
+		for (rf_path = 0; rf_path < 2; rf_path++)
+		{
+			priv->RfTxPwrLevelCck[rf_path][idx] = CckTxPwrIdx;
+			priv->RfTxPwrLevelOfdm1T[rf_path][idx] =  \
+			priv->RfTxPwrLevelOfdm2T[rf_path][idx] = OfdmTxPwrIdx;
+		}
+	}
+
+	PHY_SetTxPowerLevel8192S(dev, priv->chan);
+
+	return TRUE;
+}
+
+/*
+	Description:
+		When beacon interval is changed, the values of the
+		hw registers should be modified.
+	By tynli, 2008.10.24.
+
+*/
+
+extern void PHY_SetBeaconHwReg(	struct net_device* dev, u16 BeaconInterval)
+{
+	u32 NewBeaconNum;
+
+	NewBeaconNum = BeaconInterval *32 - 64;
+	//PlatformEFIOWrite4Byte(Adapter, WFM3+4, NewBeaconNum);
+	//PlatformEFIOWrite4Byte(Adapter, WFM3, 0xB026007C);
+	write_nic_dword(dev, WFM3+4, NewBeaconNum);
+	write_nic_dword(dev, WFM3, 0xB026007C);
+}
+
+//
+//	Description:
+//		Map dBm into Tx power index according to
+//		current HW model, for example, RF and PA, and
+//		current wireless mode.
+//	By Bruce, 2008-01-29.
+//    use in phy only
+static u8 phy_DbmToTxPwrIdx(
+	struct net_device* dev,
+	WIRELESS_MODE	WirelessMode,
+	long			PowerInDbm
+	)
+{
+	//struct r8192_priv *priv = ieee80211_priv(dev);
+	u8				TxPwrIdx = 0;
+	long				Offset = 0;
+
+
+	//
+	// Tested by MP, we found that CCK Index 0 equals to -7dbm, OFDM legacy equals to
+	// 3dbm, and OFDM HT equals to 0dbm repectively.
+	// Note:
+	//	The mapping may be different by different NICs. Do not use this formula for what needs accurate result.
+	// By Bruce, 2008-01-29.
+	//
+	switch(WirelessMode)
+	{
+	case WIRELESS_MODE_B:
+		Offset = -7;
+		break;
+
+	case WIRELESS_MODE_G:
+	case WIRELESS_MODE_N_24G:
+		Offset = -8;
+		break;
+	default:
+		break;
+	}
+
+	if((PowerInDbm - Offset) > 0)
+	{
+		TxPwrIdx = (u8)((PowerInDbm - Offset) * 2);
+	}
+	else
+	{
+		TxPwrIdx = 0;
+	}
+
+	// Tx Power Index is too large.
+	if(TxPwrIdx > MAX_TXPWR_IDX_NMODE_92S)
+		TxPwrIdx = MAX_TXPWR_IDX_NMODE_92S;
+
+	return TxPwrIdx;
+}
+//
+//	Description:
+//		Map Tx power index into dBm according to
+//		current HW model, for example, RF and PA, and
+//		current wireless mode.
+//	By Bruce, 2008-01-29.
+//    use in phy only
+static long phy_TxPwrIdxToDbm(
+	struct net_device* dev,
+	WIRELESS_MODE	WirelessMode,
+	u8			TxPwrIdx
+	)
+{
+	//struct r8192_priv *priv = ieee80211_priv(dev);
+	long				Offset = 0;
+	long				PwrOutDbm = 0;
+
+	//
+	// Tested by MP, we found that CCK Index 0 equals to -7dbm, OFDM legacy equals to
+	// 3dbm, and OFDM HT equals to 0dbm repectively.
+	// Note:
+	//	The mapping may be different by different NICs. Do not use this formula for what needs accurate result.
+	// By Bruce, 2008-01-29.
+	//
+	switch(WirelessMode)
+	{
+	case WIRELESS_MODE_B:
+		Offset = -7;
+		break;
+
+	case WIRELESS_MODE_G:
+	case WIRELESS_MODE_N_24G:
+		Offset = -8;
+		break;
+	default:
+		break;
+	}
+
+	PwrOutDbm = TxPwrIdx / 2 + Offset; // Discard the decimal part.
+
+	return PwrOutDbm;
+}
+
+#ifdef TO_DO_LIST
+extern	VOID
+PHY_ScanOperationBackup8192S(
+	IN	PADAPTER	Adapter,
+	IN	u1Byte		Operation
+	)
+{
+
+	HAL_DATA_TYPE			*pHalData = GET_HAL_DATA(Adapter);
+	PMGNT_INFO			pMgntInfo = &(Adapter->MgntInfo);
+	u4Byte				BitMask;
+	u1Byte				initial_gain;
+
+
+
+
+#if(RTL8192S_DISABLE_FW_DM == 0)
+
+	if(!Adapter->bDriverStopped)
+	{
+		switch(Operation)
+		{
+			case SCAN_OPT_BACKUP:
+				//
+				// <Roger_Notes> We halt FW DIG and disable high ppower both two DMs here
+				// and resume both two DMs while scan complete.
+				// 2008.11.27.
+				//
+				Adapter->HalFunc.SetFwCmdHandler(Adapter, FW_CMD_PAUSE_DM_BY_SCAN);
+				break;
+
+			case SCAN_OPT_RESTORE:
+				//
+				// <Roger_Notes> We resume DIG and enable high power both two DMs here and
+				// recover earlier DIG settings.
+				// 2008.11.27.
+				//
+				Adapter->HalFunc.SetFwCmdHandler(Adapter, FW_CMD_RESUME_DM_BY_SCAN);
+				break;
+
+			default:
+				RT_TRACE(COMP_SCAN, DBG_LOUD, ("Unknown Scan Backup Operation. \n"));
+				break;
+		}
+	}
+#endif
+}
+#endif
+
+//nouse temp
+void PHY_InitialGain8192S(struct net_device* dev,u8 Operation	)
+{
+
+	//struct r8192_priv *priv = ieee80211_priv(dev);
+	//u32					BitMask;
+	//u8					initial_gain;
+
+#if 0	// For 8192s test disable
+	if(!dev->bDriverStopped)
+	{
+		switch(Operation)
+		{
+			case IG_Backup:
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("IG_Backup, backup the initial gain.\n"));
+				initial_gain = priv->DefaultInitialGain[0];
+				BitMask = bMaskByte0;
+				if(DM_DigTable.Dig_Algorithm == DIG_ALGO_BY_FALSE_ALARM)
+					PHY_SetMacReg(dev, UFWP, bMaskByte1, 0x8);	// FW DIG OFF
+				pMgntInfo->InitGain_Backup.XAAGCCore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XAAGCCore1, BitMask);
+				pMgntInfo->InitGain_Backup.XBAGCCore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XBAGCCore1, BitMask);
+				pMgntInfo->InitGain_Backup.XCAGCCore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XCAGCCore1, BitMask);
+				pMgntInfo->InitGain_Backup.XDAGCCore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XDAGCCore1, BitMask);
+				BitMask  = bMaskByte2;
+				pMgntInfo->InitGain_Backup.CCA		= (u8)rtl8192_QueryBBReg(dev, rCCK0_CCA, BitMask);
+
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Scan InitialGainBackup 0xc50 is %x\n",pMgntInfo->InitGain_Backup.XAAGCCore1));
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Scan InitialGainBackup 0xc58 is %x\n",pMgntInfo->InitGain_Backup.XBAGCCore1));
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Scan InitialGainBackup 0xc60 is %x\n",pMgntInfo->InitGain_Backup.XCAGCCore1));
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Scan InitialGainBackup 0xc68 is %x\n",pMgntInfo->InitGain_Backup.XDAGCCore1));
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Scan InitialGainBackup 0xa0a is %x\n",pMgntInfo->InitGain_Backup.CCA));
+
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Write scan initial gain = 0x%x \n", initial_gain));
+				write_nic_byte(dev, rOFDM0_XAAGCCore1, initial_gain);
+				write_nic_byte(dev, rOFDM0_XBAGCCore1, initial_gain);
+				write_nic_byte(dev, rOFDM0_XCAGCCore1, initial_gain);
+				write_nic_byte(dev, rOFDM0_XDAGCCore1, initial_gain);
+				break;
+			case IG_Restore:
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("IG_Restore, restore the initial gain.\n"));
+				BitMask = 0x7f; //Bit0~ Bit6
+				if(DM_DigTable.Dig_Algorithm == DIG_ALGO_BY_FALSE_ALARM)
+					PHY_SetMacReg(dev, UFWP, bMaskByte1, 0x8);	// FW DIG OFF
+
+				rtl8192_setBBreg(dev, rOFDM0_XAAGCCore1, BitMask, (u32)pMgntInfo->InitGain_Backup.XAAGCCore1);
+				rtl8192_setBBreg(dev, rOFDM0_XBAGCCore1, BitMask, (u32)pMgntInfo->InitGain_Backup.XBAGCCore1);
+				rtl8192_setBBreg(dev, rOFDM0_XCAGCCore1, BitMask, (u32)pMgntInfo->InitGain_Backup.XCAGCCore1);
+				rtl8192_setBBreg(dev, rOFDM0_XDAGCCore1, BitMask, (u32)pMgntInfo->InitGain_Backup.XDAGCCore1);
+				BitMask  = (BIT22|BIT23);
+				rtl8192_setBBreg(dev, rCCK0_CCA, BitMask, (u32)pMgntInfo->InitGain_Backup.CCA);
+
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Scan BBInitialGainRestore 0xc50 is %x\n",pMgntInfo->InitGain_Backup.XAAGCCore1));
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Scan BBInitialGainRestore 0xc58 is %x\n",pMgntInfo->InitGain_Backup.XBAGCCore1));
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Scan BBInitialGainRestore 0xc60 is %x\n",pMgntInfo->InitGain_Backup.XCAGCCore1));
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Scan BBInitialGainRestore 0xc68 is %x\n",pMgntInfo->InitGain_Backup.XDAGCCore1));
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Scan BBInitialGainRestore 0xa0a is %x\n",pMgntInfo->InitGain_Backup.CCA));
+
+				if(DM_DigTable.Dig_Algorithm == DIG_ALGO_BY_FALSE_ALARM)
+					PHY_SetMacReg(dev, UFWP, bMaskByte1, 0x1);	// FW DIG ON
+				break;
+			default:
+			RT_TRACE(COMP_SCAN, DBG_LOUD, ("Unknown IG Operation. \n"));
+				break;
+		}
+	}
+#endif
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:    SetBWModeCallback8190Pci()
+ *
+ * Overview:    Timer callback function for SetSetBWMode
+ *
+ * Input:       	PRT_TIMER		pTimer
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Note:		(1) We do not take j mode into consideration now
+ *			(2) Will two workitem of "switch channel" and "switch channel bandwidth" run
+ *			     concurrently?
+ *---------------------------------------------------------------------------*/
+//    use in phy only (in win it's timer)
+void PHY_SetBWModeCallback8192S(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8	 			regBwOpMode;
+
+	//return;
+
+	// Added it for 20/40 mhz switch time evaluation by guangan 070531
+	//u32				NowL, NowH;
+	//u8Byte				BeginTime, EndTime;
+	u8				regRRSR_RSC;
+
+	RT_TRACE(COMP_SWBW, "==>SetBWModeCallback8190Pci()  Switch to %s bandwidth\n", \
+					priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20?"20MHz":"40MHz");
+
+	if(priv->rf_chip == RF_PSEUDO_11N)
+	{
+		priv->SetBWModeInProgress= FALSE;
+		return;
+	}
+
+	if(!priv->up)
+		return;
+
+	// Added it for 20/40 mhz switch time evaluation by guangan 070531
+	//NowL = read_nic_dword(dev, TSFR);
+	//NowH = read_nic_dword(dev, TSFR+4);
+	//BeginTime = ((u8Byte)NowH << 32) + NowL;
+
+	//3//
+	//3//<1>Set MAC register
+	//3//
+	regBwOpMode = read_nic_byte(dev, BW_OPMODE);
+	regRRSR_RSC = read_nic_byte(dev, RRSR+2);
+
+	switch(priv->CurrentChannelBW)
+	{
+		case HT_CHANNEL_WIDTH_20:
+			//if(priv->card_8192_version >= VERSION_8192S_BCUT)
+			//	write_nic_byte(dev, rFPGA0_AnalogParameter2, 0x58);
+
+			regBwOpMode |= BW_OPMODE_20MHZ;
+		       	// 2007/02/07 Mark by Emily becasue we have not verify whether this register works
+			write_nic_byte(dev, BW_OPMODE, regBwOpMode);
+			break;
+
+		case HT_CHANNEL_WIDTH_20_40:
+			//if(priv->card_8192_version >= VERSION_8192S_BCUT)
+			//	write_nic_byte(dev, rFPGA0_AnalogParameter2, 0x18);
+
+			regBwOpMode &= ~BW_OPMODE_20MHZ;
+        		// 2007/02/07 Mark by Emily becasue we have not verify whether this register works
+			write_nic_byte(dev, BW_OPMODE, regBwOpMode);
+			regRRSR_RSC = (regRRSR_RSC&0x90) |(priv->nCur40MhzPrimeSC<<5);
+			write_nic_byte(dev, RRSR+2, regRRSR_RSC);
+			break;
+
+		default:
+			RT_TRACE(COMP_DBG, "SetBWModeCallback8190Pci():\
+						unknown Bandwidth: %#X\n",priv->CurrentChannelBW);
+			break;
+	}
+
+	//3//
+	//3//<2>Set PHY related register
+	//3//
+	switch(priv->CurrentChannelBW)
+	{
+		/* 20 MHz channel*/
+		case HT_CHANNEL_WIDTH_20:
+			rtl8192_setBBreg(dev, rFPGA0_RFMOD, bRFMOD, 0x0);
+			rtl8192_setBBreg(dev, rFPGA1_RFMOD, bRFMOD, 0x0);
+
+			// Correct the tx power for CCK rate in 40M. Suggest by YN, 20071207
+			// It is set in Tx descriptor for 8192x series
+			//write_nic_dword(dev, rCCK0_TxFilter1, 0x1a1b0000);
+			//write_nic_dword(dev, rCCK0_TxFilter2, 0x090e1317);
+			//write_nic_dword(dev, rCCK0_DebugPort, 0x00000204);
+			#if 0 //LZM 090219
+			rtl8192_setBBreg(dev, rCCK0_TxFilter1, bMaskDWord, 0x1a1b0000);
+			rtl8192_setBBreg(dev, rCCK0_TxFilter2, bMaskDWord, 0x090e1317);
+			rtl8192_setBBreg(dev, rCCK0_DebugPort, bMaskDWord, 0x00000204);
+			rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x00300000, 3);
+			#endif
+
+			if (priv->card_8192_version >= VERSION_8192S_BCUT)
+				write_nic_byte(dev, rFPGA0_AnalogParameter2, 0x58);
+
+
+			break;
+
+		/* 40 MHz channel*/
+		case HT_CHANNEL_WIDTH_20_40:
+			rtl8192_setBBreg(dev, rFPGA0_RFMOD, bRFMOD, 0x1);
+			rtl8192_setBBreg(dev, rFPGA1_RFMOD, bRFMOD, 0x1);
+
+			// Correct the tx power for CCK rate in 40M. Suggest by YN, 20071207
+			//write_nic_dword(dev, rCCK0_TxFilter1, 0x35360000);
+			//write_nic_dword(dev, rCCK0_TxFilter2, 0x121c252e);
+			//write_nic_dword(dev, rCCK0_DebugPort, 0x00000409);
+			#if 0 //LZM 090219
+			rtl8192_setBBreg(dev, rCCK0_TxFilter1, bMaskDWord, 0x35360000);
+			rtl8192_setBBreg(dev, rCCK0_TxFilter2, bMaskDWord, 0x121c252e);
+			rtl8192_setBBreg(dev, rCCK0_DebugPort, bMaskDWord, 0x00000409);
+			#endif
+
+			// Set Control channel to upper or lower. These settings are required only for 40MHz
+			rtl8192_setBBreg(dev, rCCK0_System, bCCKSideBand, (priv->nCur40MhzPrimeSC>>1));
+			rtl8192_setBBreg(dev, rOFDM1_LSTF, 0xC00, priv->nCur40MhzPrimeSC);
+
+			//rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x00300000, 3);
+			if (priv->card_8192_version >= VERSION_8192S_BCUT)
+				write_nic_byte(dev, rFPGA0_AnalogParameter2, 0x18);
+
+			break;
+
+		default:
+			RT_TRACE(COMP_DBG, "SetBWModeCallback8190Pci(): unknown Bandwidth: %#X\n"\
+						,priv->CurrentChannelBW);
+			break;
+
+	}
+	//Skip over setting of J-mode in BB register here. Default value is "None J mode". Emily 20070315
+
+	// Added it for 20/40 mhz switch time evaluation by guangan 070531
+	//NowL = read_nic_dword(dev, TSFR);
+	//NowH = read_nic_dword(dev, TSFR+4);
+	//EndTime = ((u8Byte)NowH << 32) + NowL;
+	//RT_TRACE(COMP_SCAN, DBG_LOUD, ("SetBWModeCallback8190Pci: time of SetBWMode = %I64d us!\n", (EndTime - BeginTime)));
+
+	//3<3>Set RF related register
+	switch( priv->rf_chip )
+	{
+		case RF_8225:
+			//PHY_SetRF8225Bandwidth(dev, priv->CurrentChannelBW);
+			break;
+
+		case RF_8256:
+			// Please implement this function in Hal8190PciPhy8256.c
+			//PHY_SetRF8256Bandwidth(dev, priv->CurrentChannelBW);
+			break;
+
+		case RF_8258:
+			// Please implement this function in Hal8190PciPhy8258.c
+			// PHY_SetRF8258Bandwidth();
+			break;
+
+		case RF_PSEUDO_11N:
+			// Do Nothing
+			break;
+
+		case RF_6052:
+			PHY_RF6052SetBandwidth(dev, priv->CurrentChannelBW);
+			break;
+		default:
+			printk("Unknown rf_chip: %d\n", priv->rf_chip);
+			break;
+	}
+
+	priv->SetBWModeInProgress= FALSE;
+
+	RT_TRACE(COMP_SWBW, "<==SetBWModeCallback8190Pci() \n" );
+}
+
+
+ /*-----------------------------------------------------------------------------
+ * Function:   SetBWMode8190Pci()
+ *
+ * Overview:  This function is export to "HalCommon" moudule
+ *
+ * Input:       	PADAPTER			Adapter
+ *			HT_CHANNEL_WIDTH	Bandwidth	//20M or 40M
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Note:		We do not take j mode into consideration now
+ *---------------------------------------------------------------------------*/
+//extern void PHY_SetBWMode8192S(	struct net_device* dev,
+//	HT_CHANNEL_WIDTH	Bandwidth,	// 20M or 40M
+//	HT_EXTCHNL_OFFSET	Offset		// Upper, Lower, or Don't care
+void rtl8192_SetBWMode(struct net_device *dev, HT_CHANNEL_WIDTH	Bandwidth, HT_EXTCHNL_OFFSET Offset)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	HT_CHANNEL_WIDTH tmpBW = priv->CurrentChannelBW;
+
+
+	// Modified it for 20/40 mhz switch by guangan 070531
+
+	//return;
+
+	//if(priv->SwChnlInProgress)
+//	if(pMgntInfo->bScanInProgress)
+//	{
+//		RT_TRACE(COMP_SCAN, DBG_LOUD, ("SetBWMode8190Pci() %s Exit because bScanInProgress!\n",
+//					Bandwidth == HT_CHANNEL_WIDTH_20?"20MHz":"40MHz"));
+//		return;
+//	}
+
+//	if(priv->SetBWModeInProgress)
+//	{
+//		// Modified it for 20/40 mhz switch by guangan 070531
+//		RT_TRACE(COMP_SCAN, DBG_LOUD, ("SetBWMode8190Pci() %s cancel last timer because SetBWModeInProgress!\n",
+//					Bandwidth == HT_CHANNEL_WIDTH_20?"20MHz":"40MHz"));
+//		PlatformCancelTimer(dev, &priv->SetBWModeTimer);
+//		//return;
+//	}
+
+	if(priv->SetBWModeInProgress)
+		return;
+
+	priv->SetBWModeInProgress= TRUE;
+
+	priv->CurrentChannelBW = Bandwidth;
+
+	if(Offset==HT_EXTCHNL_OFFSET_LOWER)
+		priv->nCur40MhzPrimeSC = HAL_PRIME_CHNL_OFFSET_UPPER;
+	else if(Offset==HT_EXTCHNL_OFFSET_UPPER)
+		priv->nCur40MhzPrimeSC = HAL_PRIME_CHNL_OFFSET_LOWER;
+	else
+		priv->nCur40MhzPrimeSC = HAL_PRIME_CHNL_OFFSET_DONT_CARE;
+
+#if 0
+	if(!priv->bDriverStopped)
+	{
+#ifdef USE_WORKITEM
+		PlatformScheduleWorkItem(&(priv->SetBWModeWorkItem));//SetBWModeCallback8192SUsbWorkItem
+#else
+		PlatformSetTimer(dev, &(priv->SetBWModeTimer), 0);//PHY_SetBWModeCallback8192S
+#endif
+	}
+#endif
+	if((priv->up) )// && !(RT_CANNOT_IO(Adapter) && Adapter->bInSetPower) )
+	{
+#ifdef RTL8192SE
+	PHY_SetBWModeCallback8192S(dev);
+#elif defined(RTL8192SU)
+	SetBWModeCallback8192SUsbWorkItem(dev);
+#endif
+	}
+	else
+	{
+		RT_TRACE(COMP_SCAN, "PHY_SetBWMode8192S() SetBWModeInProgress FALSE driver sleep or unload\n");
+		priv->SetBWModeInProgress= FALSE;
+		priv->CurrentChannelBW = tmpBW;
+	}
+}
+
+//    use in phy only (in win it's timer)
+void PHY_SwChnlCallback8192S(struct net_device *dev)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32		delay;
+	//bool			ret;
+
+	RT_TRACE(COMP_CH, "==>SwChnlCallback8190Pci(), switch to channel %d\n", priv->chan);
+
+	if(!priv->up)
+		return;
+
+	if(priv->rf_chip == RF_PSEUDO_11N)
+	{
+		priv->SwChnlInProgress=FALSE;
+		return; 								//return immediately if it is peudo-phy
+	}
+
+	do{
+		if(!priv->SwChnlInProgress)
+			break;
+
+		//if(!phy_SwChnlStepByStep(dev, priv->CurrentChannel, &priv->SwChnlStage, &priv->SwChnlStep, &delay))
+		if(!phy_SwChnlStepByStep(dev, priv->chan, &priv->SwChnlStage, &priv->SwChnlStep, &delay))
+		{
+			if(delay>0)
+			{
+				mdelay(delay);
+				//PlatformSetTimer(dev, &priv->SwChnlTimer, delay);
+				//mod_timer(&priv->SwChnlTimer,  jiffies + MSECS(delay));
+				//==>PHY_SwChnlCallback8192S(dev); for 92se
+				//==>SwChnlCallback8192SUsb(dev) for 92su
+			}
+			else
+			continue;
+		}
+		else
+		{
+			priv->SwChnlInProgress=FALSE;
+			break;
+		}
+	}while(true);
+}
+
+// Call after initialization
+//extern void PHY_SwChnl8192S(struct net_device* dev,	u8 channel)
+u8 rtl8192_phy_SwChnl(struct net_device* dev, u8 channel)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//u8 			tmpchannel =channel;
+	//bool			bResult = false;
+
+        if(!priv->up)
+		return false;
+
+	if(priv->SwChnlInProgress)
+		return false;
+
+	if(priv->SetBWModeInProgress)
+		return false;
+
+	//--------------------------------------------
+	switch(priv->ieee80211->mode)
+	{
+	case WIRELESS_MODE_A:
+	case WIRELESS_MODE_N_5G:
+		if (channel<=14){
+			RT_TRACE(COMP_ERR, "WIRELESS_MODE_A but channel<=14");
+			return false;
+		}
+		break;
+
+	case WIRELESS_MODE_B:
+		if (channel>14){
+			RT_TRACE(COMP_ERR, "WIRELESS_MODE_B but channel>14");
+			return false;
+		}
+		break;
+
+	case WIRELESS_MODE_G:
+	case WIRELESS_MODE_N_24G:
+		if (channel>14){
+			RT_TRACE(COMP_ERR, "WIRELESS_MODE_G but channel>14");
+			return false;
+		}
+		break;
+
+	default:
+			;//RT_TRACE(COMP_ERR, "Invalid WirelessMode(%#x)!!\n", priv->ieee80211->mode);
+		break;
+	}
+	//--------------------------------------------
+
+	priv->SwChnlInProgress = TRUE;
+	if( channel == 0)
+		channel = 1;
+
+	priv->chan=channel;
+
+	priv->SwChnlStage=0;
+	priv->SwChnlStep=0;
+
+	if((priv->up))// && !(RT_CANNOT_IO(Adapter) && Adapter->bInSetPower))
+	{
+#ifdef RTL8192SE
+	PHY_SwChnlCallback8192S(dev);
+#elif defined(RTL8192SU)
+	SwChnlCallback8192SUsbWorkItem(dev);
+#endif
+#ifdef TO_DO_LIST
+	if(bResult)
+		{
+			RT_TRACE(COMP_SCAN, "PHY_SwChnl8192S SwChnlInProgress TRUE schdule workitem done\n");
+		}
+		else
+		{
+			RT_TRACE(COMP_SCAN, "PHY_SwChnl8192S SwChnlInProgress FALSE schdule workitem error\n");
+			priv->SwChnlInProgress = false;
+			priv->CurrentChannel = tmpchannel;
+		}
+#endif
+	}
+	else
+	{
+		RT_TRACE(COMP_SCAN, "PHY_SwChnl8192S SwChnlInProgress FALSE driver sleep or unload\n");
+		priv->SwChnlInProgress = false;
+		//priv->CurrentChannel = tmpchannel;
+	}
+        return true;
+}
+
+
+//
+// Description:
+//	Switch channel synchronously. Called by SwChnlByDelayHandler.
+//
+// Implemented by Bruce, 2008-02-14.
+// The following procedure is operted according to SwChanlCallback8190Pci().
+// However, this procedure is performed synchronously  which should be running under
+// passive level.
+//
+//not understant it
+void PHY_SwChnlPhy8192S(	// Only called during initialize
+	struct net_device* dev,
+	u8		channel
+	)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	RT_TRACE(COMP_SCAN, "==>PHY_SwChnlPhy8192S(), switch to channel %d.\n", priv->chan);
+
+#ifdef TO_DO_LIST
+	// Cannot IO.
+	if(RT_CANNOT_IO(dev))
+		return;
+#endif
+
+	// Channel Switching is in progress.
+	if(priv->SwChnlInProgress)
+		return;
+
+	//return immediately if it is peudo-phy
+	if(priv->rf_chip == RF_PSEUDO_11N)
+	{
+		priv->SwChnlInProgress=FALSE;
+		return;
+	}
+
+	priv->SwChnlInProgress = TRUE;
+	if( channel == 0)
+		channel = 1;
+
+	priv->chan=channel;
+
+	priv->SwChnlStage = 0;
+	priv->SwChnlStep = 0;
+
+	phy_FinishSwChnlNow(dev,channel);
+
+	priv->SwChnlInProgress = FALSE;
+}
+
+//    use in phy only
+static bool
+phy_SetSwChnlCmdArray(
+	SwChnlCmd*		CmdTable,
+	u32			CmdTableIdx,
+	u32			CmdTableSz,
+	SwChnlCmdID		CmdID,
+	u32			Para1,
+	u32			Para2,
+	u32			msDelay
+	)
+{
+	SwChnlCmd* pCmd;
+
+	if(CmdTable == NULL)
+	{
+		//RT_ASSERT(FALSE, ("phy_SetSwChnlCmdArray(): CmdTable cannot be NULL.\n"));
+		return FALSE;
+	}
+	if(CmdTableIdx >= CmdTableSz)
+	{
+		//RT_ASSERT(FALSE,
+			//	("phy_SetSwChnlCmdArray(): Access invalid index, please check size of the table, CmdTableIdx:%d, CmdTableSz:%d\n",
+				//CmdTableIdx, CmdTableSz));
+		return FALSE;
+	}
+
+	pCmd = CmdTable + CmdTableIdx;
+	pCmd->CmdID = CmdID;
+	pCmd->Para1 = Para1;
+	pCmd->Para2 = Para2;
+	pCmd->msDelay = msDelay;
+
+	return TRUE;
+}
+
+//    use in phy only
+static bool
+phy_SwChnlStepByStep(
+	struct net_device* dev,
+	u8		channel,
+	u8		*stage,
+	u8		*step,
+	u32		*delay
+	)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//PCHANNEL_ACCESS_SETTING	pChnlAccessSetting;
+	SwChnlCmd				PreCommonCmd[MAX_PRECMD_CNT];
+	u32					PreCommonCmdCnt;
+	SwChnlCmd				PostCommonCmd[MAX_POSTCMD_CNT];
+	u32					PostCommonCmdCnt;
+	SwChnlCmd				RfDependCmd[MAX_RFDEPENDCMD_CNT];
+	u32					RfDependCmdCnt;
+	SwChnlCmd				*CurrentCmd = NULL;
+	u8					eRFPath;
+
+	//RT_ASSERT((dev != NULL), ("Adapter should not be NULL\n"));
+	//RT_ASSERT(IsLegalChannel(dev, channel), ("illegal channel: %d\n", channel));
+	RT_TRACE(COMP_CH, "===========>%s(), channel:%d, stage:%d, step:%d\n", __FUNCTION__, channel, *stage, *step);
+	//RT_ASSERT((pHalData != NULL), ("pHalData should not be NULL\n"));
+#ifdef ENABLE_DOT11D
+	if (!IsLegalChannel(priv->ieee80211, channel))
+	{
+		RT_TRACE(COMP_ERR, "=============>set to illegal channel:%d\n", channel);
+		return true; //return true to tell upper caller function this channel setting is finished! Or it will in while loop.
+	}
+#endif
+
+	//pChnlAccessSetting = &Adapter->MgntInfo.Info8185.ChannelAccessSetting;
+	//RT_ASSERT((pChnlAccessSetting != NULL), ("pChnlAccessSetting should not be NULL\n"));
+
+	//for(eRFPath = RF90_PATH_A; eRFPath <priv->NumTotalRFPath; eRFPath++)
+	//for(eRFPath = 0; eRFPath <priv->NumTotalRFPath; eRFPath++)
+	//{
+		// <1> Fill up pre common command.
+	PreCommonCmdCnt = 0;
+	phy_SetSwChnlCmdArray(PreCommonCmd, PreCommonCmdCnt++, MAX_PRECMD_CNT,
+				CmdID_SetTxPowerLevel, 0, 0, 0);
+	phy_SetSwChnlCmdArray(PreCommonCmd, PreCommonCmdCnt++, MAX_PRECMD_CNT,
+				CmdID_End, 0, 0, 0);
+
+		// <2> Fill up post common command.
+	PostCommonCmdCnt = 0;
+
+	phy_SetSwChnlCmdArray(PostCommonCmd, PostCommonCmdCnt++, MAX_POSTCMD_CNT,
+				CmdID_End, 0, 0, 0);
+
+		// <3> Fill up RF dependent command.
+	RfDependCmdCnt = 0;
+	switch( priv->rf_chip )
+	{
+		case RF_8225:
+		if (channel < 1 || channel > 14)
+			RT_TRACE(COMP_ERR, "illegal channel for zebra:%d\n", channel);
+		//RT_ASSERT((channel >= 1 && channel <= 14), ("illegal channel for Zebra: %d\n", channel));
+		// 2008/09/04 MH Change channel.
+		phy_SetSwChnlCmdArray(RfDependCmd, RfDependCmdCnt++, MAX_RFDEPENDCMD_CNT,
+			CmdID_RF_WriteReg, rRfChannel, channel, 10);
+		phy_SetSwChnlCmdArray(RfDependCmd, RfDependCmdCnt++, MAX_RFDEPENDCMD_CNT,
+		CmdID_End, 0, 0, 0);
+		break;
+
+	case RF_8256:
+		if (channel < 1 || channel > 14)
+			RT_TRACE(COMP_ERR, "illegal channel for zebra:%d\n", channel);
+		// TEST!! This is not the table for 8256!!
+		//RT_ASSERT((channel >= 1 && channel <= 14), ("illegal channel for Zebra: %d\n", channel));
+		phy_SetSwChnlCmdArray(RfDependCmd, RfDependCmdCnt++, MAX_RFDEPENDCMD_CNT,
+			CmdID_RF_WriteReg, rRfChannel, channel, 10);
+		phy_SetSwChnlCmdArray(RfDependCmd, RfDependCmdCnt++, MAX_RFDEPENDCMD_CNT,
+		CmdID_End, 0, 0, 0);
+		break;
+
+	case RF_6052:
+		if (channel < 1 || channel > 14)
+			RT_TRACE(COMP_ERR, "illegal channel for zebra:%d\n", channel);
+		phy_SetSwChnlCmdArray(RfDependCmd, RfDependCmdCnt++, MAX_RFDEPENDCMD_CNT,
+			CmdID_RF_WriteReg, RF_CHNLBW, channel, 10);
+		phy_SetSwChnlCmdArray(RfDependCmd, RfDependCmdCnt++, MAX_RFDEPENDCMD_CNT,
+			CmdID_End, 0, 0, 0);
+		break;
+
+	case RF_8258:
+		break;
+
+	default:
+		//RT_ASSERT(FALSE, ("Unknown rf_chip: %d\n", priv->rf_chip));
+		return FALSE;
+		break;
+	}
+
+
+	do{
+		switch(*stage)
+		{
+		case 0:
+			CurrentCmd=&PreCommonCmd[*step];
+			break;
+		case 1:
+			CurrentCmd=&RfDependCmd[*step];
+			break;
+		case 2:
+			CurrentCmd=&PostCommonCmd[*step];
+			break;
+		}
+
+		if(CurrentCmd->CmdID==CmdID_End)
+		{
+			if((*stage)==2)
+			{
+				return TRUE;
+			}
+			else
+			{
+				(*stage)++;
+				(*step)=0;
+				continue;
+			}
+		}
+
+		switch(CurrentCmd->CmdID)
+		{
+		case CmdID_SetTxPowerLevel:
+			//if(priv->card_8192_version > VERSION_8190_BD)
+				PHY_SetTxPowerLevel8192S(dev,channel);
+			break;
+		case CmdID_WritePortUlong:
+			write_nic_dword(dev, CurrentCmd->Para1, CurrentCmd->Para2);
+			break;
+		case CmdID_WritePortUshort:
+			write_nic_word(dev, CurrentCmd->Para1, (u16)CurrentCmd->Para2);
+			break;
+		case CmdID_WritePortUchar:
+			write_nic_byte(dev, CurrentCmd->Para1, (u8)CurrentCmd->Para2);
+			break;
+		case CmdID_RF_WriteReg:	// Only modify channel for the register now !!!!!
+			for(eRFPath = 0; eRFPath <priv->NumTotalRFPath; eRFPath++)
+			{
+#if (defined RTL8192SE ||defined RTL8192SU )
+			// For new T65 RF 0222d register 0x18 bit 0-9 = channel number.
+				rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, CurrentCmd->Para1, 0x1f, (CurrentCmd->Para2));
+				//printk("====>%x, %x, read_back:%x\n", CurrentCmd->Para2,CurrentCmd->Para1, rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, CurrentCmd->Para1, 0x1f));
+#else
+				rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, CurrentCmd->Para1, bRFRegOffsetMask, ((CurrentCmd->Para2)<<7));
+#endif
+			}
+			break;
+                default:
+                        break;
+		}
+
+		break;
+	}while(TRUE);
+	//cosa }/*for(Number of RF paths)*/
+
+	(*delay)=CurrentCmd->msDelay;
+	(*step)++;
+	RT_TRACE(COMP_CH, "<===========%s(), channel:%d, stage:%d, step:%d\n", __FUNCTION__, channel, *stage, *step);
+	return FALSE;
+}
+
+//called PHY_SwChnlPhy8192S, SwChnlCallback8192SUsbWorkItem
+//    use in phy only
+static void
+phy_FinishSwChnlNow(	// We should not call this function directly
+	struct net_device* dev,
+	u8		channel
+		)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	u32			delay;
+
+	while(!phy_SwChnlStepByStep(dev,channel,&priv->SwChnlStage,&priv->SwChnlStep,&delay))
+	{
+		if(delay>0)
+			mdelay(delay);
+		if(!priv->up)
+			break;
+	}
+}
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	PHYCheckIsLegalRfPath8190Pci()
+ *
+ * Overview:	Check different RF type to execute legal judgement. If RF Path is illegal
+ *			We will return false.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	11/15/2007	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+ //called by rtl8192_phy_QueryRFReg, rtl8192_phy_SetRFReg, PHY_SetRFPowerState8192SUsb
+//extern	bool
+//PHY_CheckIsLegalRfPath8192S(
+//	struct net_device* dev,
+//	u32	eRFPath)
+u8 rtl8192_phy_CheckIsLegalRFPath(struct net_device* dev, u32 eRFPath)
+{
+//	struct r8192_priv *priv = ieee80211_priv(dev);
+	bool				rtValue = TRUE;
+
+	// NOt check RF Path now.!
+#if 0
+	if (priv->rf_type == RF_1T2R && eRFPath != RF90_PATH_A)
+	{
+		rtValue = FALSE;
+	}
+	if (priv->rf_type == RF_1T2R && eRFPath != RF90_PATH_A)
+	{
+
+	}
+#endif
+	return	rtValue;
+
+}	/* PHY_CheckIsLegalRfPath8192S */
+
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	PHY_IQCalibrate8192S()
+ *
+ * Overview:	After all MAC/PHY/RF is configued. We must execute IQ calibration
+ *			to improve RF EVM!!?
+ *
+ * Input:		IN	PADAPTER	pAdapter
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	10/07/2008	MHC		Create. Document from SD3 RFSI Jenyu.
+ *
+ *---------------------------------------------------------------------------*/
+ //called by InitializeAdapter8192SE
+void
+PHY_IQCalibrate(	struct net_device* dev)
+{
+	//struct r8192_priv 	*priv = ieee80211_priv(dev);
+	u32				i, reg;
+	u32				old_value;
+	long				X, Y, TX0[4];
+	u32				TXA[4];
+
+	// 1. Check QFN68 or 64 92S (Read from EEPROM)
+
+	//
+	// 2. QFN 68
+	//
+	// For 1T2R IQK only now !!!
+	for (i = 0; i < 10; i++)
+	{
+		// IQK
+		rtl8192_setBBreg(dev, 0xc04, bMaskDWord, 0x00a05430);
+		//PlatformStallExecution(5);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xc08, bMaskDWord, 0x000800e4);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe28, bMaskDWord, 0x80800000);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe40, bMaskDWord, 0x02140148);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe44, bMaskDWord, 0x681604a2);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe4c, bMaskDWord, 0x000028d1);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe60, bMaskDWord, 0x0214014d);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe64, bMaskDWord, 0x281608ba);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe6c, bMaskDWord, 0x000028d1);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe48, bMaskDWord, 0xfb000001);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe48, bMaskDWord, 0xf8000001);
+		udelay(2000);
+		rtl8192_setBBreg(dev, 0xc04, bMaskDWord, 0x00a05433);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xc08, bMaskDWord, 0x000000e4);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe28, bMaskDWord, 0x0);
+
+
+		reg = rtl8192_QueryBBReg(dev, 0xeac, bMaskDWord);
+
+		// Readback IQK value and rewrite
+		if (!(reg&(BIT27|BIT28|BIT30|BIT31)))
+		{
+			old_value = (rtl8192_QueryBBReg(dev, 0xc80, bMaskDWord) & 0x3FF);
+
+			// Calibrate init gain for A path for TX0
+			X = (rtl8192_QueryBBReg(dev, 0xe94, bMaskDWord) & 0x03FF0000)>>16;
+			TXA[RF90_PATH_A] = (X * old_value)/0x100;
+			reg = rtl8192_QueryBBReg(dev, 0xc80, bMaskDWord);
+			reg = (reg & 0xFFFFFC00) | (u32)TXA[RF90_PATH_A];
+			rtl8192_setBBreg(dev, 0xc80, bMaskDWord, reg);
+			udelay(5);
+
+			// Calibrate init gain for C path for TX0
+			Y = ( rtl8192_QueryBBReg(dev, 0xe9C, bMaskDWord) & 0x03FF0000)>>16;
+			TX0[RF90_PATH_C] = ((Y * old_value)/0x100);
+			reg = rtl8192_QueryBBReg(dev, 0xc80, bMaskDWord);
+			reg = (reg & 0xffc0ffff) |((u32) (TX0[RF90_PATH_C]&0x3F)<<16);
+			rtl8192_setBBreg(dev, 0xc80, bMaskDWord, reg);
+			reg = rtl8192_QueryBBReg(dev, 0xc94, bMaskDWord);
+			reg = (reg & 0x0fffffff) |(((Y&0x3c0)>>6)<<28);
+			rtl8192_setBBreg(dev, 0xc94, bMaskDWord, reg);
+			udelay(5);
+
+			// Calibrate RX A and B for RX0
+			reg = rtl8192_QueryBBReg(dev, 0xc14, bMaskDWord);
+			X = (rtl8192_QueryBBReg(dev, 0xea4, bMaskDWord) & 0x03FF0000)>>16;
+			reg = (reg & 0xFFFFFC00) |X;
+			rtl8192_setBBreg(dev, 0xc14, bMaskDWord, reg);
+			Y = (rtl8192_QueryBBReg(dev, 0xeac, bMaskDWord) & 0x003F0000)>>16;
+			reg = (reg & 0xFFFF03FF) |Y<<10;
+			rtl8192_setBBreg(dev, 0xc14, bMaskDWord, reg);
+			udelay(5);
+			old_value = (rtl8192_QueryBBReg(dev, 0xc88, bMaskDWord) & 0x3FF);
+
+			// Calibrate init gain for A path for TX1 !!!!!!
+			X = (rtl8192_QueryBBReg(dev, 0xeb4, bMaskDWord) & 0x03FF0000)>>16;
+			reg = rtl8192_QueryBBReg(dev, 0xc88, bMaskDWord);
+			TXA[RF90_PATH_A] = (X * old_value) / 0x100;
+			reg = (reg & 0xFFFFFC00) | TXA[RF90_PATH_A];
+			rtl8192_setBBreg(dev, 0xc88, bMaskDWord, reg);
+			udelay(5);
+
+			// Calibrate init gain for C path for TX1
+			Y = (rtl8192_QueryBBReg(dev, 0xebc, bMaskDWord)& 0x03FF0000)>>16;
+			TX0[RF90_PATH_C] = ((Y * old_value)/0x100);
+			reg = rtl8192_QueryBBReg(dev, 0xc88, bMaskDWord);
+			reg = (reg & 0xffc0ffff) |( (TX0[RF90_PATH_C]&0x3F)<<16);
+			rtl8192_setBBreg(dev, 0xc88, bMaskDWord, reg);
+			reg = rtl8192_QueryBBReg(dev, 0xc9c, bMaskDWord);
+			reg = (reg & 0x0fffffff) |(((Y&0x3c0)>>6)<<28);
+			rtl8192_setBBreg(dev, 0xc9c, bMaskDWord, reg);
+			udelay(5);
+
+			// Calibrate RX A and B for RX1
+			reg = rtl8192_QueryBBReg(dev, 0xc1c, bMaskDWord);
+			X = (rtl8192_QueryBBReg(dev, 0xec4, bMaskDWord) & 0x03FF0000)>>16;
+			reg = (reg & 0xFFFFFC00) |X;
+			rtl8192_setBBreg(dev, 0xc1c, bMaskDWord, reg);
+
+			Y = (rtl8192_QueryBBReg(dev, 0xecc, bMaskDWord) & 0x003F0000)>>16;
+			reg = (reg & 0xFFFF03FF) |Y<<10;
+			rtl8192_setBBreg(dev, 0xc1c, bMaskDWord, reg);
+			udelay(5);
+
+			RT_TRACE(COMP_INIT, "PHY_IQCalibrate OK\n");
+			break;
+		}
+
+	}
+
+
+	//
+	// 3. QFN64. Not enabled now !!! We must use different gain table for 1T2R.
+	//
+
+
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:	PHY_IQCalibrateBcut()
+ *
+ * Overview:	After all MAC/PHY/RF is configued. We must execute IQ calibration
+ *			to improve RF EVM!!?
+ *
+ * Input:		IN	PADAPTER	pAdapter
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	11/18/2008	MHC		Create. Document from SD3 RFSI Jenyu.
+ *						92S B-cut QFN 68 pin IQ calibration procedure.doc
+ *
+ *---------------------------------------------------------------------------*/
+extern void PHY_IQCalibrateBcut(struct net_device* dev)
+{
+	//struct r8192_priv 	*priv = ieee80211_priv(dev);
+	//PMGNT_INFO		pMgntInfo = &pAdapter->MgntInfo;
+	u32				i, reg;
+	u32				old_value;
+	long				X, Y, TX0[4];
+	u32				TXA[4];
+	u32				calibrate_set[13] = {0};
+	u32				load_value[13];
+	u8				RfPiEnable=0;
+
+	// 0. Check QFN68 or 64 92S (Read from EEPROM/EFUSE)
+
+	//
+	// 1. Save e70~ee0 register setting, and load calibration setting
+	//
+	/*
+	0xee0[31:0]=0x3fed92fb;
+	0xedc[31:0] =0x3fed92fb;
+	0xe70[31:0] =0x3fed92fb;
+	0xe74[31:0] =0x3fed92fb;
+	0xe78[31:0] =0x3fed92fb;
+	0xe7c[31:0]= 0x3fed92fb;
+	0xe80[31:0]= 0x3fed92fb;
+	0xe84[31:0]= 0x3fed92fb;
+	0xe88[31:0]= 0x3fed92fb;
+	0xe8c[31:0]= 0x3fed92fb;
+	0xed0[31:0]= 0x3fed92fb;
+	0xed4[31:0]= 0x3fed92fb;
+	0xed8[31:0]= 0x3fed92fb;
+	*/
+	calibrate_set [0] = 0xee0;
+	calibrate_set [1] = 0xedc;
+	calibrate_set [2] = 0xe70;
+	calibrate_set [3] = 0xe74;
+	calibrate_set [4] = 0xe78;
+	calibrate_set [5] = 0xe7c;
+	calibrate_set [6] = 0xe80;
+	calibrate_set [7] = 0xe84;
+	calibrate_set [8] = 0xe88;
+	calibrate_set [9] = 0xe8c;
+	calibrate_set [10] = 0xed0;
+	calibrate_set [11] = 0xed4;
+	calibrate_set [12] = 0xed8;
+	//RT_TRACE(COMP_INIT, DBG_LOUD, ("Save e70~ee0 register setting\n"));
+	for (i = 0; i < 13; i++)
+	{
+		load_value[i] = rtl8192_QueryBBReg(dev, calibrate_set[i], bMaskDWord);
+		rtl8192_setBBreg(dev, calibrate_set[i], bMaskDWord, 0x3fed92fb);
+
+	}
+
+	RfPiEnable = (u8)rtl8192_QueryBBReg(dev, rFPGA0_XA_HSSIParameter1, BIT8);
+
+	//
+	// 2. QFN 68
+	//
+	// For 1T2R IQK only now !!!
+	for (i = 0; i < 10; i++)
+	{
+		RT_TRACE(COMP_INIT, "IQK -%d\n", i);
+		//BB switch to PI mode. If default is PI mode, ignoring 2 commands below.
+		if (!RfPiEnable)	//if original is SI mode, then switch to PI mode.
+		{
+			//DbgPrint("IQK Switch to PI mode\n");
+			rtl8192_setBBreg(dev, 0x820, bMaskDWord, 0x01000100);
+			rtl8192_setBBreg(dev, 0x828, bMaskDWord, 0x01000100);
+		}
+
+		// IQK
+		// 2. IQ calibration & LO leakage calibration
+		rtl8192_setBBreg(dev, 0xc04, bMaskDWord, 0x00a05430);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xc08, bMaskDWord, 0x000800e4);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe28, bMaskDWord, 0x80800000);
+		udelay(5);
+		//path-A IQ K and LO K gain setting
+		rtl8192_setBBreg(dev, 0xe40, bMaskDWord, 0x02140102);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe44, bMaskDWord, 0x681604c2);
+		udelay(5);
+		//set LO calibration
+		rtl8192_setBBreg(dev, 0xe4c, bMaskDWord, 0x000028d1);
+		udelay(5);
+		//path-B IQ K and LO K gain setting
+		rtl8192_setBBreg(dev, 0xe60, bMaskDWord, 0x02140102);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe64, bMaskDWord, 0x28160d05);
+		udelay(5);
+		//K idac_I & IQ
+		rtl8192_setBBreg(dev, 0xe48, bMaskDWord, 0xfb000000);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe48, bMaskDWord, 0xf8000000);
+		udelay(5);
+
+		// delay 2ms
+		udelay(2000);
+
+		//idac_Q setting
+		rtl8192_setBBreg(dev, 0xe6c, bMaskDWord, 0x020028d1);
+		udelay(5);
+		//K idac_Q & IQ
+		rtl8192_setBBreg(dev, 0xe48, bMaskDWord, 0xfb000000);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe48, bMaskDWord, 0xf8000000);
+
+		// delay 2ms
+		udelay(2000);
+
+		rtl8192_setBBreg(dev, 0xc04, bMaskDWord, 0x00a05433);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xc08, bMaskDWord, 0x000000e4);
+		udelay(5);
+		rtl8192_setBBreg(dev, 0xe28, bMaskDWord, 0x0);
+
+		if (!RfPiEnable)	//if original is SI mode, then switch to PI mode.
+		{
+			//DbgPrint("IQK Switch back to SI mode\n");
+			rtl8192_setBBreg(dev, 0x820, bMaskDWord, 0x01000000);
+			rtl8192_setBBreg(dev, 0x828, bMaskDWord, 0x01000000);
+		}
+
+
+		reg = rtl8192_QueryBBReg(dev, 0xeac, bMaskDWord);
+
+		// 3.	check fail bit, and fill BB IQ matrix
+		// Readback IQK value and rewrite
+		if (!(reg&(BIT27|BIT28|BIT30|BIT31)))
+		{
+			old_value = (rtl8192_QueryBBReg(dev, 0xc80, bMaskDWord) & 0x3FF);
+
+			// Calibrate init gain for A path for TX0
+			X = (rtl8192_QueryBBReg(dev, 0xe94, bMaskDWord) & 0x03FF0000)>>16;
+			TXA[RF90_PATH_A] = (X * old_value)/0x100;
+			reg = rtl8192_QueryBBReg(dev, 0xc80, bMaskDWord);
+			reg = (reg & 0xFFFFFC00) | (u32)TXA[RF90_PATH_A];
+			rtl8192_setBBreg(dev, 0xc80, bMaskDWord, reg);
+			udelay(5);
+
+			// Calibrate init gain for C path for TX0
+			Y = ( rtl8192_QueryBBReg(dev, 0xe9C, bMaskDWord) & 0x03FF0000)>>16;
+			TX0[RF90_PATH_C] = ((Y * old_value)/0x100);
+			reg = rtl8192_QueryBBReg(dev, 0xc80, bMaskDWord);
+			reg = (reg & 0xffc0ffff) |((u32) (TX0[RF90_PATH_C]&0x3F)<<16);
+			rtl8192_setBBreg(dev, 0xc80, bMaskDWord, reg);
+			reg = rtl8192_QueryBBReg(dev, 0xc94, bMaskDWord);
+			reg = (reg & 0x0fffffff) |(((Y&0x3c0)>>6)<<28);
+			rtl8192_setBBreg(dev, 0xc94, bMaskDWord, reg);
+			udelay(5);
+
+			// Calibrate RX A and B for RX0
+			reg = rtl8192_QueryBBReg(dev, 0xc14, bMaskDWord);
+			X = (rtl8192_QueryBBReg(dev, 0xea4, bMaskDWord) & 0x03FF0000)>>16;
+			reg = (reg & 0xFFFFFC00) |X;
+			rtl8192_setBBreg(dev, 0xc14, bMaskDWord, reg);
+			Y = (rtl8192_QueryBBReg(dev, 0xeac, bMaskDWord) & 0x003F0000)>>16;
+			reg = (reg & 0xFFFF03FF) |Y<<10;
+			rtl8192_setBBreg(dev, 0xc14, bMaskDWord, reg);
+			udelay(5);
+			old_value = (rtl8192_QueryBBReg(dev, 0xc88, bMaskDWord) & 0x3FF);
+
+			// Calibrate init gain for A path for TX1 !!!!!!
+			X = (rtl8192_QueryBBReg(dev, 0xeb4, bMaskDWord) & 0x03FF0000)>>16;
+			reg = rtl8192_QueryBBReg(dev, 0xc88, bMaskDWord);
+			TXA[RF90_PATH_A] = (X * old_value) / 0x100;
+			reg = (reg & 0xFFFFFC00) | TXA[RF90_PATH_A];
+			rtl8192_setBBreg(dev, 0xc88, bMaskDWord, reg);
+			udelay(5);
+
+			// Calibrate init gain for C path for TX1
+			Y = (rtl8192_QueryBBReg(dev, 0xebc, bMaskDWord)& 0x03FF0000)>>16;
+			TX0[RF90_PATH_C] = ((Y * old_value)/0x100);
+			reg = rtl8192_QueryBBReg(dev, 0xc88, bMaskDWord);
+			reg = (reg & 0xffc0ffff) |( (TX0[RF90_PATH_C]&0x3F)<<16);
+			rtl8192_setBBreg(dev, 0xc88, bMaskDWord, reg);
+			reg = rtl8192_QueryBBReg(dev, 0xc9c, bMaskDWord);
+			reg = (reg & 0x0fffffff) |(((Y&0x3c0)>>6)<<28);
+			rtl8192_setBBreg(dev, 0xc9c, bMaskDWord, reg);
+			udelay(5);
+
+			// Calibrate RX A and B for RX1
+			reg = rtl8192_QueryBBReg(dev, 0xc1c, bMaskDWord);
+			X = (rtl8192_QueryBBReg(dev, 0xec4, bMaskDWord) & 0x03FF0000)>>16;
+			reg = (reg & 0xFFFFFC00) |X;
+			rtl8192_setBBreg(dev, 0xc1c, bMaskDWord, reg);
+
+			Y = (rtl8192_QueryBBReg(dev, 0xecc, bMaskDWord) & 0x003F0000)>>16;
+			reg = (reg & 0xFFFF03FF) |Y<<10;
+			rtl8192_setBBreg(dev, 0xc1c, bMaskDWord, reg);
+			udelay(5);
+
+			RT_TRACE(COMP_INIT, "PHY_IQCalibrate OK\n");
+			break;
+		}
+
+	}
+
+	//
+	// 4. Reload e70~ee0 register setting.
+	//
+	//RT_TRACE(COMP_INIT, DBG_LOUD, ("Reload e70~ee0 register setting.\n"));
+	for (i = 0; i < 13; i++)
+		rtl8192_setBBreg(dev, calibrate_set[i], bMaskDWord, load_value[i]);
+
+
+	//
+	// 3. QFN64. Not enabled now !!! We must use different gain table for 1T2R.
+	//
+
+
+
+}	// PHY_IQCalibrateBcut
+
+
+//
+// Move from phycfg.c to gen.c to be code independent later
+//
+//-------------------------Move to other DIR later----------------------------*/
+//#if (DEV_BUS_TYPE == USB_INTERFACE)
+#ifdef RTL8192SU
+
+//    use in phy only (in win it's timer)
+void SwChnlCallback8192SUsb(struct net_device *dev)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32			delay;
+//	bool			ret;
+
+	RT_TRACE(COMP_SCAN, "==>SwChnlCallback8190Pci(), switch to channel\
+				%d\n", priv->chan);
+
+
+	if(!priv->up)
+		return;
+
+	if(priv->rf_chip == RF_PSEUDO_11N)
+	{
+		priv->SwChnlInProgress=FALSE;
+		return; 								//return immediately if it is peudo-phy
+	}
+
+	do{
+		if(!priv->SwChnlInProgress)
+			break;
+
+		if(!phy_SwChnlStepByStep(dev, priv->chan, &priv->SwChnlStage, &priv->SwChnlStep, &delay))
+		{
+			if(delay>0)
+			{
+				//PlatformSetTimer(dev, &priv->SwChnlTimer, delay);
+
+			}
+			else
+			continue;
+		}
+		else
+		{
+			priv->SwChnlInProgress=FALSE;
+		}
+		break;
+	}while(TRUE);
+}
+
+
+//
+// Callback routine of the work item for switch channel.
+//
+//    use in phy only (in win it's work)
+void SwChnlCallback8192SUsbWorkItem(struct net_device *dev )
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	RT_TRACE(COMP_TRACE, "==> SwChnlCallback8192SUsbWorkItem()\n");
+#ifdef TO_DO_LIST
+	if(pAdapter->bInSetPower && RT_USB_CANNOT_IO(pAdapter))
+	{
+		RT_TRACE(COMP_SCAN, DBG_LOUD, ("<== SwChnlCallback8192SUsbWorkItem() SwChnlInProgress FALSE driver sleep or unload\n"));
+
+		pHalData->SwChnlInProgress = FALSE;
+		return;
+	}
+#endif
+	phy_FinishSwChnlNow(dev, priv->chan);
+	priv->SwChnlInProgress = FALSE;
+
+	RT_TRACE(COMP_TRACE, "<== SwChnlCallback8192SUsbWorkItem()\n");
+}
+
+
+/*-----------------------------------------------------------------------------
+ * Function:    SetBWModeCallback8192SUsb()
+ *
+ * Overview:    Timer callback function for SetSetBWMode
+ *
+ * Input:       	PRT_TIMER		pTimer
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Note:		(1) We do not take j mode into consideration now
+ *			(2) Will two workitem of "switch channel" and "switch channel bandwidth" run
+ *			     concurrently?
+ *---------------------------------------------------------------------------*/
+//====>//rtl8192_SetBWMode
+//    use in phy only (in win it's timer)
+void SetBWModeCallback8192SUsb(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8	 			regBwOpMode;
+
+	// Added it for 20/40 mhz switch time evaluation by guangan 070531
+	//u32				NowL, NowH;
+	//u8Byte				BeginTime, EndTime;
+	u8				regRRSR_RSC;
+
+	RT_TRACE(COMP_SCAN, "==>SetBWModeCallback8190Pci()  Switch to %s bandwidth\n", \
+					priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20?"20MHz":"40MHz");
+
+	if(priv->rf_chip == RF_PSEUDO_11N)
+	{
+		priv->SetBWModeInProgress= FALSE;
+		return;
+	}
+
+	if(!priv->up)
+		return;
+
+	// Added it for 20/40 mhz switch time evaluation by guangan 070531
+	//NowL = read_nic_dword(dev, TSFR);
+	//NowH = read_nic_dword(dev, TSFR+4);
+	//BeginTime = ((u8Byte)NowH << 32) + NowL;
+
+	//3<1>Set MAC register
+	regBwOpMode = read_nic_byte(dev, BW_OPMODE);
+	regRRSR_RSC = read_nic_byte(dev, RRSR+2);
+
+	switch(priv->CurrentChannelBW)
+	{
+		case HT_CHANNEL_WIDTH_20:
+			regBwOpMode |= BW_OPMODE_20MHZ;
+		       // 2007/02/07 Mark by Emily becasue we have not verify whether this register works
+			write_nic_byte(dev, BW_OPMODE, regBwOpMode);
+			break;
+
+		case HT_CHANNEL_WIDTH_20_40:
+			regBwOpMode &= ~BW_OPMODE_20MHZ;
+        		// 2007/02/07 Mark by Emily becasue we have not verify whether this register works
+			write_nic_byte(dev, BW_OPMODE, regBwOpMode);
+
+			regRRSR_RSC = (regRRSR_RSC&0x90) |(priv->nCur40MhzPrimeSC<<5);
+			write_nic_byte(dev, RRSR+2, regRRSR_RSC);
+			break;
+
+		default:
+			RT_TRACE(COMP_DBG, "SetChannelBandwidth8190Pci():\
+						unknown Bandwidth: %#X\n",priv->CurrentChannelBW);
+			break;
+	}
+
+	//3 <2>Set PHY related register
+	switch(priv->CurrentChannelBW)
+	{
+		case HT_CHANNEL_WIDTH_20:
+			rtl8192_setBBreg(dev, rFPGA0_RFMOD, bRFMOD, 0x0);
+			rtl8192_setBBreg(dev, rFPGA1_RFMOD, bRFMOD, 0x0);
+			#if 0 //LZM090219
+			rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x00300000, 3);
+
+			// Correct the tx power for CCK rate in 20M. Suggest by YN, 20071207
+			//write_nic_dword(dev, rCCK0_TxFilter1, 0x1a1b0000);
+			//write_nic_dword(dev, rCCK0_TxFilter2, 0x090e1317);
+			//write_nic_dword(dev, rCCK0_DebugPort, 0x00000204);
+			rtl8192_setBBreg(dev, rCCK0_TxFilter1, bMaskDWord, 0x1a1b0000);
+			rtl8192_setBBreg(dev, rCCK0_TxFilter2, bMaskDWord, 0x090e1317);
+			rtl8192_setBBreg(dev, rCCK0_DebugPort, bMaskDWord, 0x00000204);
+			rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x00300000, 3);
+			#endif
+
+			if (priv->card_8192_version >= VERSION_8192S_BCUT)
+				rtl8192_setBBreg(dev, rFPGA0_AnalogParameter2, 0xff, 0x58);
+
+			break;
+		case HT_CHANNEL_WIDTH_20_40:
+			rtl8192_setBBreg(dev, rFPGA0_RFMOD, bRFMOD, 0x1);
+			rtl8192_setBBreg(dev, rFPGA1_RFMOD, bRFMOD, 0x1);
+			rtl8192_setBBreg(dev, rCCK0_System, bCCKSideBand, (priv->nCur40MhzPrimeSC>>1));
+			rtl8192_setBBreg(dev, rOFDM1_LSTF, 0xC00, priv->nCur40MhzPrimeSC);
+
+			// Correct the tx power for CCK rate in 40M. Suggest by YN, 20071207
+			//PHY_SetBBReg(Adapter, rCCK0_TxFilter1, bMaskDWord, 0x35360000);
+			//PHY_SetBBReg(Adapter, rCCK0_TxFilter2, bMaskDWord, 0x121c252e);
+			//PHY_SetBBReg(Adapter, rCCK0_DebugPort, bMaskDWord, 0x00000409);
+			//PHY_SetBBReg(Adapter, rFPGA0_AnalogParameter1, bADClkPhase, 0);
+
+			if (priv->card_8192_version >= VERSION_8192S_BCUT)
+				rtl8192_setBBreg(dev, rFPGA0_AnalogParameter2, 0xff, 0x18);
+
+			break;
+		default:
+			RT_TRACE(COMP_DBG, "SetChannelBandwidth8190Pci(): unknown Bandwidth: %#X\n"\
+						,priv->CurrentChannelBW);
+			break;
+
+	}
+	//Skip over setting of J-mode in BB register here. Default value is "None J mode". Emily 20070315
+
+	// Added it for 20/40 mhz switch time evaluation by guangan 070531
+	//NowL = read_nic_dword(dev, TSFR);
+	//NowH = read_nic_dword(dev, TSFR+4);
+	//EndTime = ((u8Byte)NowH << 32) + NowL;
+	//RT_TRACE(COMP_SCAN, DBG_LOUD, ("SetBWModeCallback8190Pci: time of SetBWMode = %I64d us!\n", (EndTime - BeginTime)));
+
+#if 1
+	//3<3>Set RF related register
+	switch( priv->rf_chip )
+	{
+		case RF_8225:
+			PHY_SetRF8225Bandwidth(dev, priv->CurrentChannelBW);
+			break;
+
+		case RF_8256:
+			// Please implement this function in Hal8190PciPhy8256.c
+			//PHY_SetRF8256Bandwidth(dev, priv->CurrentChannelBW);
+			break;
+
+		case RF_6052:
+			PHY_RF6052SetBandwidth(dev, priv->CurrentChannelBW);
+			break;
+
+		case RF_8258:
+			// Please implement this function in Hal8190PciPhy8258.c
+			// PHY_SetRF8258Bandwidth();
+			break;
+
+		case RF_PSEUDO_11N:
+			// Do Nothing
+			break;
+
+		default:
+			//RT_ASSERT(FALSE, ("Unknown rf_chip: %d\n", priv->rf_chip));
+			break;
+	}
+#endif
+	priv->SetBWModeInProgress= FALSE;
+
+	RT_TRACE(COMP_SCAN, "<==SetBWMode8190Pci()" );
+}
+
+//
+// Callback routine of the work item for set bandwidth mode.
+//
+//    use in phy only (in win it's work)
+void SetBWModeCallback8192SUsbWorkItem(struct net_device *dev)
+{
+	struct r8192_priv 		*priv = ieee80211_priv(dev);
+	u8	 			regBwOpMode;
+
+	// Added it for 20/40 mhz switch time evaluation by guangan 070531
+	//u32				NowL, NowH;
+	//u8Byte				BeginTime, EndTime;
+	u8			regRRSR_RSC;
+
+	RT_TRACE(COMP_SCAN, "==>SetBWModeCallback8192SUsbWorkItem()  Switch to %s bandwidth\n", \
+					priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20?"20MHz":"40MHz");
+
+	if(priv->rf_chip == RF_PSEUDO_11N)
+	{
+		priv->SetBWModeInProgress= FALSE;
+		return;
+	}
+
+	if(!priv->up)
+		return;
+
+	// Added it for 20/40 mhz switch time evaluation by guangan 070531
+	//NowL = read_nic_dword(dev, TSFR);
+	//NowH = read_nic_dword(dev, TSFR+4);
+	//BeginTime = ((u8Byte)NowH << 32) + NowL;
+
+	//3<1>Set MAC register
+	regBwOpMode = read_nic_byte(dev, BW_OPMODE);
+	regRRSR_RSC = read_nic_byte(dev, RRSR+2);
+
+	switch(priv->CurrentChannelBW)
+	{
+		case HT_CHANNEL_WIDTH_20:
+			regBwOpMode |= BW_OPMODE_20MHZ;
+		       // 2007/02/07 Mark by Emily becasue we have not verify whether this register works
+			write_nic_byte(dev, BW_OPMODE, regBwOpMode);
+			break;
+
+		case HT_CHANNEL_WIDTH_20_40:
+			regBwOpMode &= ~BW_OPMODE_20MHZ;
+        		// 2007/02/07 Mark by Emily becasue we have not verify whether this register works
+			write_nic_byte(dev, BW_OPMODE, regBwOpMode);
+			regRRSR_RSC = (regRRSR_RSC&0x90) |(priv->nCur40MhzPrimeSC<<5);
+			write_nic_byte(dev, RRSR+2, regRRSR_RSC);
+
+			break;
+
+		default:
+			RT_TRACE(COMP_DBG, "SetBWModeCallback8192SUsbWorkItem():\
+						unknown Bandwidth: %#X\n",priv->CurrentChannelBW);
+			break;
+	}
+
+	//3 <2>Set PHY related register
+	switch(priv->CurrentChannelBW)
+	{
+		case HT_CHANNEL_WIDTH_20:
+			rtl8192_setBBreg(dev, rFPGA0_RFMOD, bRFMOD, 0x0);
+			rtl8192_setBBreg(dev, rFPGA1_RFMOD, bRFMOD, 0x0);
+
+			#if 0 //LZM 090219
+			rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, bADClkPhase, 1);
+
+			// Correct the tx power for CCK rate in 20M. Suggest by YN, 20071207
+			rtl8192_setBBreg(dev, rCCK0_TxFilter1, bMaskDWord, 0x1a1b0000);
+			rtl8192_setBBreg(dev, rCCK0_TxFilter2, bMaskDWord, 0x090e1317);
+			rtl8192_setBBreg(dev, rCCK0_DebugPort, bMaskDWord, 0x00000204);
+			rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x00100000, 1);
+			#endif
+
+			rtl8192_setBBreg(dev, rFPGA0_AnalogParameter2, 0xff, 0x58);
+
+			break;
+		case HT_CHANNEL_WIDTH_20_40:
+			rtl8192_setBBreg(dev, rFPGA0_RFMOD, bRFMOD, 0x1);
+			rtl8192_setBBreg(dev, rFPGA1_RFMOD, bRFMOD, 0x1);
+			#if 0 //LZM 090219
+			rtl8192_setBBreg(dev, rCCK0_System, bCCKSideBand, (priv->nCur40MhzPrimeSC>>1));
+
+			rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, bADClkPhase, 0);
+
+   			rtl8192_setBBreg(dev, rOFDM1_LSTF, 0xC00, priv->nCur40MhzPrimeSC);
+			// Correct the tx power for CCK rate in 40M. Suggest by YN, 20071207
+			rtl8192_setBBreg(dev, rCCK0_TxFilter1, bMaskDWord, 0x35360000);
+			rtl8192_setBBreg(dev, rCCK0_TxFilter2, bMaskDWord, 0x121c252e);
+			rtl8192_setBBreg(dev, rCCK0_DebugPort, bMaskDWord, 0x00000409);
+			#endif
+
+			// Set Control channel to upper or lower. These settings are required only for 40MHz
+			rtl8192_setBBreg(dev, rCCK0_System, bCCKSideBand, (priv->nCur40MhzPrimeSC>>1));
+			rtl8192_setBBreg(dev, rOFDM1_LSTF, 0xC00, priv->nCur40MhzPrimeSC);
+
+			rtl8192_setBBreg(dev, rFPGA0_AnalogParameter2, 0xff, 0x18);
+
+			break;
+
+
+		default:
+			RT_TRACE(COMP_DBG, "SetBWModeCallback8192SUsbWorkItem(): unknown Bandwidth: %#X\n"\
+						,priv->CurrentChannelBW);
+			break;
+
+	}
+	//Skip over setting of J-mode in BB register here. Default value is "None J mode". Emily 20070315
+
+	//3<3>Set RF related register
+	switch( priv->rf_chip )
+	{
+		case RF_8225:
+			PHY_SetRF8225Bandwidth(dev, priv->CurrentChannelBW);
+			break;
+
+		case RF_8256:
+			// Please implement this function in Hal8190PciPhy8256.c
+			//PHY_SetRF8256Bandwidth(dev, priv->CurrentChannelBW);
+			break;
+
+		case RF_6052:
+			PHY_RF6052SetBandwidth(dev, priv->CurrentChannelBW);
+			break;
+
+		case RF_8258:
+			// Please implement this function in Hal8190PciPhy8258.c
+			// PHY_SetRF8258Bandwidth();
+			break;
+
+		case RF_PSEUDO_11N:
+			// Do Nothing
+			break;
+
+		default:
+			//RT_ASSERT(FALSE, ("Unknown rf_chip: %d\n", priv->rf_chip));
+			break;
+	}
+
+	priv->SetBWModeInProgress= FALSE;
+
+	RT_TRACE(COMP_SCAN, "<==SetBWModeCallback8192SUsbWorkItem()" );
+}
+
+//--------------------------Move to oter DIR later-------------------------------*/
+#ifdef RTL8192SU
+void InitialGain8192S(struct net_device *dev,	u8 Operation)
+{
+#ifdef TO_DO_LIST
+	struct r8192_priv *priv = ieee80211_priv(dev);
+#endif
+
+}
+#endif
+
+void InitialGain819xUsb(struct net_device *dev,	u8 Operation)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	priv->InitialGainOperateType = Operation;
+
+	if(priv->up)
+	{
+	#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+		queue_delayed_work(priv->priv_wq,&priv->initialgain_operate_wq,0);
+	#else
+		#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+		schedule_task(&priv->initialgain_operate_wq);
+		#else
+		queue_work(priv->priv_wq,&priv->initialgain_operate_wq);
+		#endif
+	#endif
+	}
+}
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern void InitialGainOperateWorkItemCallBack(struct work_struct *work)
+{
+	struct delayed_work *dwork = container_of(work,struct delayed_work,work);
+       struct r8192_priv *priv = container_of(dwork,struct r8192_priv,initialgain_operate_wq);
+       struct net_device *dev = priv->ieee80211->dev;
+#else
+extern void InitialGainOperateWorkItemCallBack(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+#endif
+#define SCAN_RX_INITIAL_GAIN	0x17
+#define POWER_DETECTION_TH	0x08
+	u32	BitMask;
+	u8	initial_gain;
+	u8	Operation;
+
+	Operation = priv->InitialGainOperateType;
+
+	switch(Operation)
+	{
+		case IG_Backup:
+			RT_TRACE(COMP_SCAN, "IG_Backup, backup the initial gain.\n");
+			initial_gain = SCAN_RX_INITIAL_GAIN;//priv->DefaultInitialGain[0];//
+			BitMask = bMaskByte0;
+			if(dm_digtable.dig_algorithm == DIG_ALGO_BY_FALSE_ALARM)
+				rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8);	// FW DIG OFF
+			priv->initgain_backup.xaagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XAAGCCore1, BitMask);
+			priv->initgain_backup.xbagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XBAGCCore1, BitMask);
+			priv->initgain_backup.xcagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XCAGCCore1, BitMask);
+			priv->initgain_backup.xdagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XDAGCCore1, BitMask);
+			BitMask  = bMaskByte2;
+			priv->initgain_backup.cca		= (u8)rtl8192_QueryBBReg(dev, rCCK0_CCA, BitMask);
+
+			RT_TRACE(COMP_SCAN, "Scan InitialGainBackup 0xc50 is %x\n",priv->initgain_backup.xaagccore1);
+			RT_TRACE(COMP_SCAN, "Scan InitialGainBackup 0xc58 is %x\n",priv->initgain_backup.xbagccore1);
+			RT_TRACE(COMP_SCAN, "Scan InitialGainBackup 0xc60 is %x\n",priv->initgain_backup.xcagccore1);
+			RT_TRACE(COMP_SCAN, "Scan InitialGainBackup 0xc68 is %x\n",priv->initgain_backup.xdagccore1);
+			RT_TRACE(COMP_SCAN, "Scan InitialGainBackup 0xa0a is %x\n",priv->initgain_backup.cca);
+
+			RT_TRACE(COMP_SCAN, "Write scan initial gain = 0x%x \n", initial_gain);
+			write_nic_byte(dev, rOFDM0_XAAGCCore1, initial_gain);
+			write_nic_byte(dev, rOFDM0_XBAGCCore1, initial_gain);
+			write_nic_byte(dev, rOFDM0_XCAGCCore1, initial_gain);
+			write_nic_byte(dev, rOFDM0_XDAGCCore1, initial_gain);
+			RT_TRACE(COMP_SCAN, "Write scan 0xa0a = 0x%x \n", POWER_DETECTION_TH);
+			write_nic_byte(dev, 0xa0a, POWER_DETECTION_TH);
+			break;
+		case IG_Restore:
+			RT_TRACE(COMP_SCAN, "IG_Restore, restore the initial gain.\n");
+			BitMask = 0x7f; //Bit0~ Bit6
+			if(dm_digtable.dig_algorithm == DIG_ALGO_BY_FALSE_ALARM)
+				rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8);	// FW DIG OFF
+
+			rtl8192_setBBreg(dev, rOFDM0_XAAGCCore1, BitMask, (u32)priv->initgain_backup.xaagccore1);
+			rtl8192_setBBreg(dev, rOFDM0_XBAGCCore1, BitMask, (u32)priv->initgain_backup.xbagccore1);
+			rtl8192_setBBreg(dev, rOFDM0_XCAGCCore1, BitMask, (u32)priv->initgain_backup.xcagccore1);
+			rtl8192_setBBreg(dev, rOFDM0_XDAGCCore1, BitMask, (u32)priv->initgain_backup.xdagccore1);
+			BitMask  = bMaskByte2;
+			rtl8192_setBBreg(dev, rCCK0_CCA, BitMask, (u32)priv->initgain_backup.cca);
+
+			RT_TRACE(COMP_SCAN, "Scan BBInitialGainRestore 0xc50 is %x\n",priv->initgain_backup.xaagccore1);
+			RT_TRACE(COMP_SCAN, "Scan BBInitialGainRestore 0xc58 is %x\n",priv->initgain_backup.xbagccore1);
+			RT_TRACE(COMP_SCAN, "Scan BBInitialGainRestore 0xc60 is %x\n",priv->initgain_backup.xcagccore1);
+			RT_TRACE(COMP_SCAN, "Scan BBInitialGainRestore 0xc68 is %x\n",priv->initgain_backup.xdagccore1);
+			RT_TRACE(COMP_SCAN, "Scan BBInitialGainRestore 0xa0a is %x\n",priv->initgain_backup.cca);
+
+			PHY_SetTxPowerLevel8192S(dev,priv->ieee80211->current_network.channel);
+
+			if(dm_digtable.dig_algorithm == DIG_ALGO_BY_FALSE_ALARM)
+				rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x1);	// FW DIG ON
+			break;
+		default:
+			RT_TRACE(COMP_SCAN, "Unknown IG Operation. \n");
+			break;
+	}
+}
+
+#endif	// #if (DEV_BUS_TYPE == USB_INTERFACE)
+
+//-----------------------------------------------------------------------------
+//	Description:
+//		Schedule workitem to send specific CMD IO to FW.
+//	Added by Roger, 2008.12.03.
+//
+//-----------------------------------------------------------------------------
+bool HalSetFwCmd8192S(struct net_device* dev, FW_CMD_IO_TYPE	FwCmdIO)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u16	FwCmdWaitCounter = 0;
+
+	u16	FwCmdWaitLimit = 1000;
+
+	//if(IS_HARDWARE_TYPE_8192SU(Adapter) && Adapter->bInHctTest)
+	if(priv->bInHctTest)
+		return true;
+
+	RT_TRACE(COMP_CMD, "-->HalSetFwCmd8192S(): Set FW Cmd(%x), SetFwCmdInProgress(%d)\n", (u32)FwCmdIO, priv->SetFwCmdInProgress);
+
+	// Will be done by high power respectively.
+	if(FwCmdIO==FW_CMD_DIG_HALT || FwCmdIO==FW_CMD_DIG_RESUME)
+	{
+		RT_TRACE(COMP_CMD, "<--HalSetFwCmd8192S(): Set FW Cmd(%x)\n", (u32)FwCmdIO);
+		return false;
+	}
+
+#if 1
+	while(priv->SetFwCmdInProgress && FwCmdWaitCounter<FwCmdWaitLimit)
+	{
+		//if(RT_USB_CANNOT_IO(Adapter))
+		//{
+		//	RT_TRACE(COMP_CMD, DBG_WARNING, ("HalSetFwCmd8192S(): USB can NOT IO!!\n"));
+		//	return FALSE;
+		//}
+
+		RT_TRACE(COMP_CMD, "HalSetFwCmd8192S(): previous workitem not finish!!\n");
+		return false;
+		FwCmdWaitCounter ++;
+		RT_TRACE(COMP_CMD, "HalSetFwCmd8192S(): Wait 10 ms (%d times)...\n", FwCmdWaitCounter);
+		udelay(100);
+	}
+
+	if(FwCmdWaitCounter == FwCmdWaitLimit)
+	{
+		//RT_ASSERT(FALSE, ("SetFwCmdIOWorkItemCallback(): Wait too logn to set FW CMD\n"));
+		RT_TRACE(COMP_CMD, "HalSetFwCmd8192S(): Wait too logn to set FW CMD\n");
+		//return false;
+	}
+#endif
+	if (priv->SetFwCmdInProgress)
+	{
+		RT_TRACE(COMP_ERR, "<--HalSetFwCmd8192S(): Set FW Cmd(%#x)\n", FwCmdIO);
+		return false;
+	}
+	priv->SetFwCmdInProgress = TRUE;
+	priv->CurrentFwCmdIO = FwCmdIO; // Update current FW Cmd for callback use.
+
+	phy_SetFwCmdIOCallback(dev);
+	return true;
+}
+void ChkFwCmdIoDone(struct net_device* dev)
+{
+	u16 PollingCnt = 1000;
+	u32 tmpValue;
+
+	do
+	{// Make sure that CMD IO has be accepted by FW.
+#ifdef TO_DO_LIST
+		if(RT_USB_CANNOT_IO(Adapter))
+		{
+			RT_TRACE(COMP_CMD, "ChkFwCmdIoDone(): USB can NOT IO!!\n");
+			return;
+		}
+#endif
+		udelay(10); // sleep 20us
+		tmpValue = read_nic_dword(dev, WFM5);
+		if(tmpValue == 0)
+		{
+			RT_TRACE(COMP_CMD, "[FW CMD] Set FW Cmd success!!\n");
+			break;
+		}
+		else
+		{
+			RT_TRACE(COMP_CMD, "[FW CMD] Polling FW Cmd PollingCnt(%d)!!\n", PollingCnt);
+		}
+	}while( --PollingCnt );
+
+	if(PollingCnt == 0)
+	{
+		RT_TRACE(COMP_ERR, "[FW CMD] Set FW Cmd fail!!\n");
+	}
+}
+// 	Callback routine of the timer callback for FW Cmd IO.
+//
+//	Description:
+//		This routine will send specific CMD IO to FW and check whether it is done.
+//
+void phy_SetFwCmdIOCallback(struct net_device* dev)
+{
+	//struct net_device* dev = (struct net_device*) data;
+	u32 	 	input;
+	static u32 ScanRegister;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	if(!priv->up)
+	{
+		RT_TRACE(COMP_CMD, "SetFwCmdIOTimerCallback(): driver is going to unload\n");
+		return;
+	}
+
+	RT_TRACE(COMP_CMD, "--->SetFwCmdIOTimerCallback(): Cmd(%#x), SetFwCmdInProgress(%d)\n", priv->CurrentFwCmdIO, priv->SetFwCmdInProgress);
+
+	switch(priv->CurrentFwCmdIO)
+	{
+		case FW_CMD_HIGH_PWR_ENABLE:
+			if((priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_HIGH_POWER)==0)
+				write_nic_dword(dev, WFM5, FW_HIGH_PWR_ENABLE);
+			break;
+
+		case FW_CMD_HIGH_PWR_DISABLE:
+			write_nic_dword(dev, WFM5, FW_HIGH_PWR_DISABLE);
+			break;
+
+		case FW_CMD_DIG_RESUME:
+			write_nic_dword(dev, WFM5, FW_DIG_RESUME);
+			break;
+
+		case FW_CMD_DIG_HALT:
+			write_nic_dword(dev, WFM5, FW_DIG_HALT);
+			break;
+
+		//
+		// <Roger_Notes> The following FW CMD IO was combined into single operation
+		// (i.e., to prevent number of system workitem out of resource!!).
+		// 2008.12.04.
+		//
+		case FW_CMD_RESUME_DM_BY_SCAN:
+			RT_TRACE(COMP_CMD, "[FW CMD] Set HIGHPWR enable and DIG resume!!\n");
+			if((priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_HIGH_POWER)==0)
+			{
+				write_nic_dword(dev, WFM5, FW_HIGH_PWR_ENABLE); //break;
+				ChkFwCmdIoDone(dev);
+			}
+			write_nic_dword(dev, WFM5, FW_DIG_RESUME);
+			break;
+
+		case FW_CMD_PAUSE_DM_BY_SCAN:
+			RT_TRACE(COMP_CMD, "[FW CMD] Set HIGHPWR disable and DIG halt!!\n");
+			write_nic_dword(dev, WFM5, FW_HIGH_PWR_DISABLE); //break;
+			ChkFwCmdIoDone(dev);
+			write_nic_dword(dev, WFM5, FW_DIG_HALT);
+			break;
+
+		//
+		// <Roger_Notes> The following FW CMD IO should be checked
+		// (i.e., workitem schedule timing issue!!).
+		// 2008.12.04.
+		//
+		case FW_CMD_DIG_DISABLE:
+			RT_TRACE(COMP_CMD, "[FW CMD] Set DIG disable!!\n");
+			write_nic_dword(dev, WFM5, FW_DIG_DISABLE);
+			break;
+
+		case FW_CMD_DIG_ENABLE:
+			RT_TRACE(COMP_CMD, "[FW CMD] Set DIG enable!!\n");
+			write_nic_dword(dev, WFM5, FW_DIG_ENABLE);
+			break;
+
+		case FW_CMD_RA_RESET:
+			write_nic_dword(dev, WFM5, FW_RA_RESET);
+			break;
+
+		case FW_CMD_RA_ACTIVE:
+			write_nic_dword(dev, WFM5, FW_RA_ACTIVE);
+			break;
+
+		case FW_CMD_RA_REFRESH_N:
+			RT_TRACE(COMP_CMD, "[FW CMD] Set RA refresh!! N\n");
+			if(priv->ieee80211->pHTInfo->IOTRaFunc & HT_IOT_RAFUNC_DISABLE_ALL)
+				input = FW_RA_REFRESH;
+			else
+				input = FW_RA_REFRESH | (priv->ieee80211->pHTInfo->IOTRaFunc << 8);
+			write_nic_dword(dev, WFM5, input);
+			break;
+		case FW_CMD_RA_REFRESH_BG:
+			RT_TRACE(COMP_CMD, "[FW CMD] Set RA refresh!! B/G\n");
+			write_nic_dword(dev, WFM5, FW_RA_REFRESH);
+			ChkFwCmdIoDone(dev);
+			write_nic_dword(dev, WFM5, FW_RA_ENABLE_BG);
+			break;
+
+		case FW_CMD_IQK_ENABLE:
+			write_nic_dword(dev, WFM5, FW_IQK_ENABLE);
+			break;
+
+		case FW_CMD_TXPWR_TRACK_ENABLE:
+			write_nic_dword(dev, WFM5, FW_TXPWR_TRACK_ENABLE);
+			break;
+
+		case FW_CMD_TXPWR_TRACK_DISABLE:
+			write_nic_dword(dev, WFM5, FW_TXPWR_TRACK_DISABLE);
+			break;
+
+		default:
+			RT_TRACE(COMP_CMD,"Unknown FW Cmd IO(%#x)\n", priv->CurrentFwCmdIO);
+			break;
+	}
+
+	ChkFwCmdIoDone(dev);
+
+	switch(priv->CurrentFwCmdIO)
+	{
+		case FW_CMD_HIGH_PWR_DISABLE:
+			//if(pMgntInfo->bTurboScan)
+			{
+				//Lower initial gain
+				rtl8192_setBBreg(dev, rOFDM0_XAAGCCore1, bMaskByte0, 0x17);
+				rtl8192_setBBreg(dev, rOFDM0_XBAGCCore1, bMaskByte0, 0x17);
+				// CCA threshold
+				rtl8192_setBBreg(dev, rCCK0_CCA, bMaskByte2, 0x40);
+				// Disable OFDM Part
+				rtl8192_setBBreg(dev, rOFDM0_TRMuxPar, bMaskByte2, 0x1);
+				ScanRegister = rtl8192_QueryBBReg(dev, rOFDM0_RxDetector1,bMaskDWord);
+				rtl8192_setBBreg(dev, rOFDM0_RxDetector1, 0xf, 0xf);
+				rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0xf, 0x0);
+			}
+			break;
+
+		case FW_CMD_HIGH_PWR_ENABLE:
+			//if(pMgntInfo->bTurboScan)
+			{
+				rtl8192_setBBreg(dev, rOFDM0_XAAGCCore1, bMaskByte0, 0x36);
+				rtl8192_setBBreg(dev, rOFDM0_XBAGCCore1, bMaskByte0, 0x36);
+
+				// CCA threshold
+				rtl8192_setBBreg(dev, rCCK0_CCA, bMaskByte2, 0x83);
+				// Enable OFDM Part
+				rtl8192_setBBreg(dev, rOFDM0_TRMuxPar, bMaskByte2, 0x0);
+
+				//LZM ADD because sometimes there is no FW_CMD_HIGH_PWR_DISABLE, this value will be 0.
+				if(ScanRegister != 0){
+				rtl8192_setBBreg(dev, rOFDM0_RxDetector1, bMaskDWord, ScanRegister);
+				}
+
+				if(priv->rf_type == RF_1T2R || priv->rf_type == RF_2T2R)
+					rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0xf, 0x3);
+				else
+					rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0xf, 0x1);
+			}
+			break;
+	}
+
+	priv->SetFwCmdInProgress = false;// Clear FW CMD operation flag.
+	RT_TRACE(COMP_CMD, "<---SetFwCmdIOWorkItemCallback()\n");
+
+}
+
diff --git a/drivers/staging/rtl8192su/r8192S_phy.h b/drivers/staging/rtl8192su/r8192S_phy.h
new file mode 100644
index 0000000..580a7c6
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_phy.h
@@ -0,0 +1,138 @@
+/*****************************************************************************
+ *	Copyright(c) 2008,  RealTEK Technology Inc. All Right Reserved.
+ *
+ * Module:	__INC_HAL8192SPHYCFG_H
+ *
+ *
+ * Note:
+ *
+ *
+ * Export:	Constants, macro, functions(API), global variables(None).
+ *
+ * Abbrev:
+ *
+ * History:
+ *		Data		Who		Remark
+ *      08/07/2007  MHC    	1. Porting from 9x series PHYCFG.h.
+ *							2. Reorganize code architecture.
+ *
+ *****************************************************************************/
+ /* Check to see if the file has been included already.  */
+#ifndef _R8192S_PHY_H
+#define _R8192S_PHY_H
+
+
+/*--------------------------Define Parameters-------------------------------*/
+#define LOOP_LIMIT				5
+#define MAX_STALL_TIME			50		//us
+#define AntennaDiversityValue		0x80	//(dev->bSoftwareAntennaDiversity ? 0x00:0x80)
+#define MAX_TXPWR_IDX_NMODE_92S	63
+
+//#define delay_ms(_t)			PlatformStallExecution(1000*(_t))
+//#define delay_us(_t)			PlatformStallExecution(_t)
+
+/* Channel switch:The size of command tables for switch channel*/
+#define MAX_PRECMD_CNT 			16
+#define MAX_RFDEPENDCMD_CNT 	16
+#define MAX_POSTCMD_CNT 		16
+
+
+/*------------------------------Define structure----------------------------*/
+typedef enum _SwChnlCmdID{
+	CmdID_End,
+	CmdID_SetTxPowerLevel,
+	CmdID_BBRegWrite10,
+	CmdID_WritePortUlong,
+	CmdID_WritePortUshort,
+	CmdID_WritePortUchar,
+	CmdID_RF_WriteReg,
+}SwChnlCmdID;
+
+
+/* 1. Switch channel related */
+typedef struct _SwChnlCmd{
+	SwChnlCmdID	CmdID;
+	u32			Para1;
+	u32			Para2;
+	u32			msDelay;
+}__attribute__ ((packed)) SwChnlCmd;
+
+extern u32 rtl819XMACPHY_Array_PG[];
+extern u32 rtl819XPHY_REG_1T2RArray[];
+extern u32 rtl819XAGCTAB_Array[];
+extern u32 rtl819XRadioA_Array[];
+extern u32 rtl819XRadioB_Array[];
+extern u32 rtl819XRadioC_Array[];
+extern u32 rtl819XRadioD_Array[];
+
+typedef enum _HW90_BLOCK{
+	HW90_BLOCK_MAC = 0,
+	HW90_BLOCK_PHY0 = 1,
+	HW90_BLOCK_PHY1 = 2,
+	HW90_BLOCK_RF = 3,
+	HW90_BLOCK_MAXIMUM = 4, // Never use this
+}HW90_BLOCK_E, *PHW90_BLOCK_E;
+
+typedef enum _RF90_RADIO_PATH{
+	RF90_PATH_A = 0,			//Radio Path A
+	RF90_PATH_B = 1,			//Radio Path B
+	RF90_PATH_C = 2,			//Radio Path C
+	RF90_PATH_D = 3,			//Radio Path D
+	RF90_PATH_MAX	= 4,			//Max RF number 90 support
+}RF90_RADIO_PATH_E, *PRF90_RADIO_PATH_E;
+
+#define bMaskByte0                0xff
+#define bMaskByte1                0xff00
+#define bMaskByte2                0xff0000
+#define bMaskByte3                0xff000000
+#define bMaskHWord                0xffff0000
+#define bMaskLWord                0x0000ffff
+#define bMaskDWord                0xffffffff
+
+typedef enum _VERSION_8190{
+	// RTL8190
+	VERSION_8190_BD=0x3,
+	VERSION_8190_BE
+}VERSION_8190,*PVERSION_8190;
+
+//
+// BB and RF register read/write
+//
+
+extern	u32	rtl8192_QueryBBReg(struct net_device* dev,u32 RegAddr, u32 BitMask);
+extern	void	rtl8192_setBBreg(struct net_device* dev,u32 RegAddr, u32 BitMask,u32 Data);
+extern	u32	rtl8192_phy_QueryRFReg(struct net_device* dev,RF90_RADIO_PATH_E eRFPath, u32 RegAddr, u32 BitMask);
+extern	void	rtl8192_phy_SetRFReg(struct net_device* dev,RF90_RADIO_PATH_E eRFPath, u32 RegAddr,u32 BitMask,u32 Data);
+
+bool rtl8192_phy_checkBBAndRF(struct net_device* dev, HW90_BLOCK_E CheckBlock, RF90_RADIO_PATH_E eRFPath);
+
+
+/* MAC/BB/RF HAL config */
+extern	bool 	PHY_MACConfig8192S(struct net_device* dev);
+extern	bool 	PHY_BBConfig8192S(struct net_device* dev);
+extern	bool 	PHY_RFConfig8192S(struct net_device* dev);
+
+extern	u8	rtl8192_phy_ConfigRFWithHeaderFile(struct net_device* dev,RF90_RADIO_PATH_E eRFPath);
+extern	void	rtl8192_SetBWMode(struct net_device* dev,HT_CHANNEL_WIDTH ChnlWidth,HT_EXTCHNL_OFFSET Offset	);
+extern	u8	rtl8192_phy_SwChnl(struct net_device* dev,u8 channel);
+extern	u8	rtl8192_phy_CheckIsLegalRFPath(struct net_device* dev,u32 eRFPath	);
+extern	void    rtl8192_BBConfig(struct net_device* dev);
+extern	void 	PHY_IQCalibrateBcut(struct net_device* dev);
+extern	void 	PHY_IQCalibrate(struct net_device* dev);
+extern	void 	PHY_GetHWRegOriginalValue(struct net_device* dev);
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern void 	InitialGainOperateWorkItemCallBack(struct work_struct *work);
+#else
+extern void 	InitialGainOperateWorkItemCallBack(struct net_device *dev);
+#endif
+void PHY_SetTxPowerLevel8192S(struct net_device* dev, u8  channel);
+void PHY_InitialGain8192S(struct net_device* dev,u8 Operation   );
+
+/*--------------------------Exported Function prototype---------------------*/
+bool HalSetFwCmd8192S(struct net_device* dev, FW_CMD_IO_TYPE                FwCmdIO);
+extern void PHY_SetBeaconHwReg( struct net_device* dev, u16 BeaconInterval);
+void ChkFwCmdIoDone(struct net_device* dev);
+
+#endif	// __INC_HAL8192SPHYCFG_H
+
diff --git a/drivers/staging/rtl8192su/r8192S_phyreg.h b/drivers/staging/rtl8192su/r8192S_phyreg.h
new file mode 100644
index 0000000..96c7cfa
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_phyreg.h
@@ -0,0 +1,1033 @@
+/*****************************************************************************
+ *	Copyright(c) 2008,  RealTEK Technology Inc. All Right Reserved.
+ *
+ * Module:	__INC_HAL8192SPHYREG_H
+ *
+ *
+ * Note:	1. Define PMAC/BB register map
+ *			2. Define RF register map
+ *			3. PMAC/BB register bit mask.
+ *			4. RF reg bit mask.
+ *			5. Other BB/RF relative definition.
+ *
+ *
+ * Export:	Constants, macro, functions(API), global variables(None).
+ *
+ * Abbrev:
+ *
+ * History:
+ *		Data		Who		Remark
+ *      08/07/2007  MHC    	1. Porting from 9x series PHYCFG.h.
+ *							2. Reorganize code architecture.
+ *	09/25/2008	MH		1. Add RL6052 register definition
+ *
+ *****************************************************************************/
+#ifndef __INC_HAL8192SPHYREG_H
+#define __INC_HAL8192SPHYREG_H
+
+
+/*--------------------------Define Parameters-------------------------------*/
+
+//============================================================
+//       8192S Regsiter offset definition
+//============================================================
+
+//
+// BB-PHY register PMAC 0x100 PHY 0x800 - 0xEFF
+// 1. PMAC duplicate register due to connection: RF_Mode, TRxRN, NumOf L-STF
+// 2. 0x800/0x900/0xA00/0xC00/0xD00/0xE00
+// 3. RF register 0x00-2E
+// 4. Bit Mask for BB/RF register
+// 5. Other defintion for BB/RF R/W
+//
+
+
+//
+// 1. PMAC duplicate register due to connection: RF_Mode, TRxRN, NumOf L-STF
+// 1. Page1(0x100)
+//
+#define		rPMAC_Reset					0x100
+#define		rPMAC_TxStart				0x104
+#define		rPMAC_TxLegacySIG			0x108
+#define		rPMAC_TxHTSIG1				0x10c
+#define		rPMAC_TxHTSIG2				0x110
+#define		rPMAC_PHYDebug				0x114
+#define		rPMAC_TxPacketNum			0x118
+#define		rPMAC_TxIdle					0x11c
+#define		rPMAC_TxMACHeader0			0x120
+#define		rPMAC_TxMACHeader1			0x124
+#define		rPMAC_TxMACHeader2			0x128
+#define		rPMAC_TxMACHeader3			0x12c
+#define		rPMAC_TxMACHeader4			0x130
+#define		rPMAC_TxMACHeader5			0x134
+#define		rPMAC_TxDataType			0x138
+#define		rPMAC_TxRandomSeed			0x13c
+#define		rPMAC_CCKPLCPPreamble		0x140
+#define		rPMAC_CCKPLCPHeader		0x144
+#define		rPMAC_CCKCRC16				0x148
+#define		rPMAC_OFDMRxCRC32OK		0x170
+#define		rPMAC_OFDMRxCRC32Er		0x174
+#define		rPMAC_OFDMRxParityEr		0x178
+#define		rPMAC_OFDMRxCRC8Er		0x17c
+#define		rPMAC_CCKCRxRC16Er			0x180
+#define		rPMAC_CCKCRxRC32Er			0x184
+#define		rPMAC_CCKCRxRC32OK		0x188
+#define		rPMAC_TxStatus				0x18c
+
+//
+// 2. Page2(0x200)
+//
+// The following two definition are only used for USB interface.
+#define		RF_BB_CMD_ADDR			0x02c0	// RF/BB read/write command address.
+#define		RF_BB_CMD_DATA			0x02c4	// RF/BB read/write command data.
+
+//
+// 3. Page8(0x800)
+//
+#define		rFPGA0_RFMOD				0x800	//RF mode & CCK TxSC // RF BW Setting??
+
+#define		rFPGA0_TxInfo				0x804	// Status report??
+#define		rFPGA0_PSDFunction			0x808
+
+#define		rFPGA0_TxGainStage			0x80c	// Set TX PWR init gain?
+
+#define		rFPGA0_RFTiming1			0x810	// Useless now
+#define		rFPGA0_RFTiming2			0x814
+//#define rFPGA0_XC_RFTiming        		0x818
+//#define rFPGA0_XD_RFTiming        		0x81c
+
+#define		rFPGA0_XA_HSSIParameter1		0x820	// RF 3 wire register
+#define		rFPGA0_XA_HSSIParameter2		0x824
+#define		rFPGA0_XB_HSSIParameter1		0x828
+#define		rFPGA0_XB_HSSIParameter2		0x82c
+#define		rFPGA0_XC_HSSIParameter1		0x830
+#define		rFPGA0_XC_HSSIParameter2		0x834
+#define		rFPGA0_XD_HSSIParameter1		0x838
+#define		rFPGA0_XD_HSSIParameter2		0x83c
+#define		rFPGA0_XA_LSSIParameter		0x840
+#define		rFPGA0_XB_LSSIParameter		0x844
+#define		rFPGA0_XC_LSSIParameter		0x848
+#define		rFPGA0_XD_LSSIParameter		0x84c
+
+#define		rFPGA0_RFWakeUpParameter		0x850	// Useless now
+#define		rFPGA0_RFSleepUpParameter		0x854
+
+#define		rFPGA0_XAB_SwitchControl		0x858	// RF Channel switch
+#define		rFPGA0_XCD_SwitchControl		0x85c
+
+#define		rFPGA0_XA_RFInterfaceOE		0x860	// RF Channel switch
+#define		rFPGA0_XB_RFInterfaceOE		0x864
+#define		rFPGA0_XC_RFInterfaceOE		0x868
+#define		rFPGA0_XD_RFInterfaceOE		0x86c
+
+#define		rFPGA0_XAB_RFInterfaceSW		0x870	// RF Interface Software Control
+#define		rFPGA0_XCD_RFInterfaceSW		0x874
+
+#define		rFPGA0_XAB_RFParameter		0x878	// RF Parameter
+#define		rFPGA0_XCD_RFParameter		0x87c
+
+#define		rFPGA0_AnalogParameter1		0x880	// Crystal cap setting RF-R/W protection for parameter4??
+#define		rFPGA0_AnalogParameter2		0x884
+#define		rFPGA0_AnalogParameter3		0x888	// Useless now
+#define		rFPGA0_AnalogParameter4		0x88c
+
+#define		rFPGA0_XA_LSSIReadBack		0x8a0	// Tranceiver LSSI Readback
+#define		rFPGA0_XB_LSSIReadBack		0x8a4
+#define		rFPGA0_XC_LSSIReadBack		0x8a8
+#define		rFPGA0_XD_LSSIReadBack		0x8ac
+
+#define		rFPGA0_PSDReport			0x8b4	// Useless now
+#define		TransceiverA_HSPI_Readback	0x8b8	// Transceiver A HSPI Readback
+#define		TransceiverB_HSPI_Readback	0x8bc	// Transceiver B HSPI Readback
+#define		rFPGA0_XAB_RFInterfaceRB	0x8e0	// Useless now // RF Interface Readback Value
+#define		rFPGA0_XCD_RFInterfaceRB	0x8e4	// Useless now
+
+//
+// 4. Page9(0x900)
+//
+#define		rFPGA1_RFMOD				0x900	//RF mode & OFDM TxSC // RF BW Setting??
+
+#define		rFPGA1_TxBlock				0x904	// Useless now
+#define		rFPGA1_DebugSelect			0x908	// Useless now
+#define		rFPGA1_TxInfo				0x90c	// Useless now // Status report??
+
+//
+// 5. PageA(0xA00)
+//
+// Set Control channel to upper or lower. These settings are required only for 40MHz
+#define		rCCK0_System				0xa00
+
+#define		rCCK0_AFESetting				0xa04	// Disable init gain now // Select RX path by RSSI
+#define		rCCK0_CCA					0xa08	// Disable init gain now // Init gain
+
+#define		rCCK0_RxAGC1				0xa0c 	//AGC default value, saturation level // Antenna Diversity, RX AGC, LNA Threshold, RX LNA Threshold useless now. Not the same as 90 series
+#define		rCCK0_RxAGC2				0xa10 	//AGC & DAGC
+
+#define		rCCK0_RxHP					0xa14
+
+#define		rCCK0_DSPParameter1			0xa18	//Timing recovery & Channel estimation threshold
+#define		rCCK0_DSPParameter2			0xa1c	//SQ threshold
+
+#define		rCCK0_TxFilter1				0xa20
+#define		rCCK0_TxFilter2				0xa24
+#define		rCCK0_DebugPort				0xa28	//debug port and Tx filter3
+#define		rCCK0_FalseAlarmReport		0xa2c	//0xa2d	useless now 0xa30-a4f channel report
+#define		rCCK0_TRSSIReport         		0xa50
+#define		rCCK0_RxReport            		0xa54  //0xa57
+#define		rCCK0_FACounterLower      		0xa5c  //0xa5b
+#define		rCCK0_FACounterUpper      		0xa58  //0xa5c
+
+//
+// 6. PageC(0xC00)
+//
+#define		rOFDM0_LSTF				0xc00
+
+#define		rOFDM0_TRxPathEnable		0xc04
+#define		rOFDM0_TRMuxPar			0xc08
+#define		rOFDM0_TRSWIsolation		0xc0c
+
+#define		rOFDM0_XARxAFE				0xc10  //RxIQ DC offset, Rx digital filter, DC notch filter
+#define		rOFDM0_XARxIQImbalance    	0xc14  //RxIQ imblance matrix
+#define		rOFDM0_XBRxAFE            		0xc18
+#define		rOFDM0_XBRxIQImbalance    	0xc1c
+#define		rOFDM0_XCRxAFE            		0xc20
+#define		rOFDM0_XCRxIQImbalance    	0xc24
+#define		rOFDM0_XDRxAFE            		0xc28
+#define		rOFDM0_XDRxIQImbalance    	0xc2c
+
+#define		rOFDM0_RxDetector1			0xc30  //PD,BW & SBD	// DM tune init gain
+#define		rOFDM0_RxDetector2			0xc34  //SBD & Fame Sync.
+#define		rOFDM0_RxDetector3			0xc38  //Frame Sync.
+#define		rOFDM0_RxDetector4			0xc3c  //PD, SBD, Frame Sync & Short-GI
+
+#define		rOFDM0_RxDSP				0xc40  //Rx Sync Path
+#define		rOFDM0_CFOandDAGC			0xc44  //CFO & DAGC
+#define		rOFDM0_CCADropThreshold		0xc48 //CCA Drop threshold
+#define		rOFDM0_ECCAThreshold		0xc4c // energy CCA
+
+#define		rOFDM0_XAAGCCore1			0xc50	// DIG
+#define		rOFDM0_XAAGCCore2			0xc54
+#define		rOFDM0_XBAGCCore1			0xc58
+#define		rOFDM0_XBAGCCore2			0xc5c
+#define		rOFDM0_XCAGCCore1			0xc60
+#define		rOFDM0_XCAGCCore2			0xc64
+#define		rOFDM0_XDAGCCore1			0xc68
+#define		rOFDM0_XDAGCCore2			0xc6c
+
+#define		rOFDM0_AGCParameter1		0xc70
+#define		rOFDM0_AGCParameter2		0xc74
+#define		rOFDM0_AGCRSSITable		0xc78
+#define		rOFDM0_HTSTFAGC			0xc7c
+
+#define		rOFDM0_XATxIQImbalance		0xc80	// TX PWR TRACK and DIG
+#define		rOFDM0_XATxAFE				0xc84
+#define		rOFDM0_XBTxIQImbalance		0xc88
+#define		rOFDM0_XBTxAFE				0xc8c
+#define		rOFDM0_XCTxIQImbalance		0xc90
+#define		rOFDM0_XCTxAFE            		0xc94
+#define		rOFDM0_XDTxIQImbalance		0xc98
+#define		rOFDM0_XDTxAFE				0xc9c
+
+#define		rOFDM0_RxHPParameter		0xce0
+#define		rOFDM0_TxPseudoNoiseWgt	0xce4
+#define		rOFDM0_FrameSync			0xcf0
+#define		rOFDM0_DFSReport			0xcf4
+#define		rOFDM0_TxCoeff1				0xca4
+#define		rOFDM0_TxCoeff2				0xca8
+#define		rOFDM0_TxCoeff3				0xcac
+#define		rOFDM0_TxCoeff4				0xcb0
+#define		rOFDM0_TxCoeff5				0xcb4
+#define		rOFDM0_TxCoeff6				0xcb8
+
+
+//
+// 7. PageD(0xD00)
+//
+#define		rOFDM1_LSTF				0xd00
+#define		rOFDM1_TRxPathEnable		0xd04
+#define		rOFDM1_CFO					0xd08	// No setting now
+#define		rOFDM1_CSI1				0xd10
+#define		rOFDM1_SBD					0xd14
+#define		rOFDM1_CSI2				0xd18
+#define		rOFDM1_CFOTracking			0xd2c
+#define		rOFDM1_TRxMesaure1			0xd34
+#define		rOFDM1_IntfDet				0xd3c
+#define		rOFDM1_PseudoNoiseStateAB	0xd50
+#define		rOFDM1_PseudoNoiseStateCD	0xd54
+#define		rOFDM1_RxPseudoNoiseWgt	0xd58
+
+#define		rOFDM_PHYCounter1			0xda0  //cca, parity fail
+#define		rOFDM_PHYCounter2			0xda4  //rate illegal, crc8 fail
+#define		rOFDM_PHYCounter3			0xda8  //MCS not support
+#define		rOFDM_ShortCFOAB			0xdac	// No setting now
+#define		rOFDM_ShortCFOCD			0xdb0
+#define		rOFDM_LongCFOAB			0xdb4
+#define		rOFDM_LongCFOCD			0xdb8
+#define		rOFDM_TailCFOAB				0xdbc
+#define		rOFDM_TailCFOCD				0xdc0
+#define		rOFDM_PWMeasure1          		0xdc4
+#define		rOFDM_PWMeasure2          		0xdc8
+#define		rOFDM_BWReport				0xdcc
+#define		rOFDM_AGCReport				0xdd0
+#define		rOFDM_RxSNR				0xdd4
+#define		rOFDM_RxEVMCSI				0xdd8
+#define		rOFDM_SIGReport				0xddc
+
+
+//
+// 8. PageE(0xE00)
+//
+#define		rTxAGC_Rate18_06			0xe00
+#define		rTxAGC_Rate54_24			0xe04
+#define		rTxAGC_CCK_Mcs32			0xe08
+#define		rTxAGC_Mcs03_Mcs00			0xe10
+#define		rTxAGC_Mcs07_Mcs04			0xe14
+#define		rTxAGC_Mcs11_Mcs08			0xe18
+#define		rTxAGC_Mcs15_Mcs12			0xe1c
+
+//
+// 7. RF Register 0x00-0x2E (RF 8256)
+//    RF-0222D 0x00-3F
+//
+//Zebra1
+#define		rZebra1_HSSIEnable			0x0	// Useless now
+#define		rZebra1_TRxEnable1			0x1
+#define		rZebra1_TRxEnable2			0x2
+#define		rZebra1_AGC					0x4
+#define		rZebra1_ChargePump			0x5
+//#if (RTL92SE_FPGA_VERIFY == 1)
+#define		rZebra1_Channel				0x7	// RF channel switch
+//#else
+
+//#endif
+#define		rZebra1_TxGain				0x8	// Useless now
+#define		rZebra1_TxLPF				0x9
+#define		rZebra1_RxLPF				0xb
+#define		rZebra1_RxHPFCorner			0xc
+
+//Zebra4
+#define		rGlobalCtrl					0	// Useless now
+#define		rRTL8256_TxLPF				19
+#define		rRTL8256_RxLPF				11
+
+//RTL8258
+#define		rRTL8258_TxLPF				0x11	// Useless now
+#define		rRTL8258_RxLPF				0x13
+#define		rRTL8258_RSSILPF			0xa
+
+//
+// RL6052 Register definition
+//
+#define		RF_AC						0x00	//
+
+#define		RF_IQADJ_G1				0x01	//
+#define		RF_IQADJ_G2				0x02	//
+#define		RF_POW_TRSW				0x05	//
+
+#define		RF_GAIN_RX					0x06	//
+#define		RF_GAIN_TX					0x07	//
+
+#define		RF_TXM_IDAC				0x08	//
+#define		RF_BS_IQGEN				0x0F	//
+
+#define		RF_MODE1					0x10	//
+#define		RF_MODE2					0x11	//
+
+#define		RF_RX_AGC_HP				0x12	//
+#define		RF_TX_AGC					0x13	//
+#define		RF_BIAS						0x14	//
+#define		RF_IPA						0x15	//
+#define		RF_POW_ABILITY				0x17	//
+#define		RF_MODE_AG					0x18	//
+#define		rRfChannel					0x18	// RF channel and BW switch
+#define		RF_CHNLBW					0x18	// RF channel and BW switch
+#define		RF_TOP						0x19	//
+
+#define		RF_RX_G1					0x1A	//
+#define		RF_RX_G2					0x1B	//
+
+#define		RF_RX_BB2					0x1C	//
+#define		RF_RX_BB1					0x1D	//
+
+#define		RF_RCK1						0x1E	//
+#define		RF_RCK2						0x1F	//
+
+#define		RF_TX_G1					0x20	//
+#define		RF_TX_G2					0x21	//
+#define		RF_TX_G3					0x22	//
+
+#define		RF_TX_BB1					0x23	//
+
+#define		RF_T_METER					0x24	//
+
+#define		RF_SYN_G1					0x25	// RF TX Power control
+#define		RF_SYN_G2					0x26	// RF TX Power control
+#define		RF_SYN_G3					0x27	// RF TX Power control
+#define		RF_SYN_G4					0x28	// RF TX Power control
+#define		RF_SYN_G5					0x29	// RF TX Power control
+#define		RF_SYN_G6					0x2A	// RF TX Power control
+#define		RF_SYN_G7					0x2B	// RF TX Power control
+#define		RF_SYN_G8					0x2C	// RF TX Power control
+
+#define		RF_RCK_OS					0x30	// RF TX PA control
+
+#define		RF_TXPA_G1					0x31	// RF TX PA control
+#define		RF_TXPA_G2					0x32	// RF TX PA control
+#define		RF_TXPA_G3					0x33	// RF TX PA control
+
+//
+//Bit Mask
+//
+// 1. Page1(0x100)
+#define		bBBResetB					0x100	// Useless now?
+#define		bGlobalResetB				0x200
+#define		bOFDMTxStart				0x4
+#define		bCCKTxStart					0x8
+#define		bCRC32Debug					0x100
+#define		bPMACLoopback				0x10
+#define		bTxLSIG						0xffffff
+#define		bOFDMTxRate					0xf
+#define		bOFDMTxReserved				0x10
+#define		bOFDMTxLength				0x1ffe0
+#define		bOFDMTxParity				0x20000
+#define		bTxHTSIG1					0xffffff
+#define		bTxHTMCSRate				0x7f
+#define		bTxHTBW					0x80
+#define		bTxHTLength					0xffff00
+#define		bTxHTSIG2					0xffffff
+#define		bTxHTSmoothing				0x1
+#define		bTxHTSounding				0x2
+#define		bTxHTReserved				0x4
+#define		bTxHTAggreation				0x8
+#define		bTxHTSTBC					0x30
+#define		bTxHTAdvanceCoding			0x40
+#define		bTxHTShortGI					0x80
+#define		bTxHTNumberHT_LTF			0x300
+#define		bTxHTCRC8					0x3fc00
+#define		bCounterReset				0x10000
+#define		bNumOfOFDMTx				0xffff
+#define		bNumOfCCKTx				0xffff0000
+#define		bTxIdleInterval				0xffff
+#define		bOFDMService				0xffff0000
+#define		bTxMACHeader				0xffffffff
+#define		bTxDataInit					0xff
+#define		bTxHTMode					0x100
+#define		bTxDataType					0x30000
+#define		bTxRandomSeed				0xffffffff
+#define		bCCKTxPreamble				0x1
+#define		bCCKTxSFD					0xffff0000
+#define		bCCKTxSIG					0xff
+#define		bCCKTxService				0xff00
+#define		bCCKLengthExt				0x8000
+#define		bCCKTxLength				0xffff0000
+#define		bCCKTxCRC16				0xffff
+#define		bCCKTxStatus					0x1
+#define		bOFDMTxStatus				0x2
+
+#define 		IS_BB_REG_OFFSET_92S(_Offset)		((_Offset >= 0x800) && (_Offset <= 0xfff))
+
+// 2. Page8(0x800)
+#define		bRFMOD						0x1	// Reg 0x800 rFPGA0_RFMOD
+#define		bJapanMode					0x2
+#define		bCCKTxSC					0x30
+#define		bCCKEn						0x1000000
+#define		bOFDMEn					0x2000000
+
+#define		bOFDMRxADCPhase           		0x10000	// Useless now
+#define		bOFDMTxDACPhase           		0x40000
+#define		bXATxAGC                  			0x3f
+
+#define		bXBTxAGC                  			0xf00	// Reg 80c rFPGA0_TxGainStage
+#define		bXCTxAGC                  			0xf000
+#define		bXDTxAGC                  			0xf0000
+
+#define		bPAStart                  			0xf0000000	// Useless now
+#define		bTRStart                  			0x00f00000
+#define		bRFStart                  			0x0000f000
+#define		bBBStart                  			0x000000f0
+#define		bBBCCKStart               			0x0000000f
+#define		bPAEnd                    			0xf          //Reg0x814
+#define		bTREnd                    			0x0f000000
+#define		bRFEnd                    			0x000f0000
+#define		bCCAMask                  			0x000000f0   //T2R
+#define		bR2RCCAMask               			0x00000f00
+#define		bHSSI_R2TDelay            		0xf8000000
+#define		bHSSI_T2RDelay            		0xf80000
+#define		bContTxHSSI               			0x400     //chane gain at continue Tx
+#define		bIGFromCCK                			0x200
+#define		bAGCAddress               			0x3f
+#define		bRxHPTx                   			0x7000
+#define		bRxHPT2R                  			0x38000
+#define		bRxHPCCKIni               			0xc0000
+#define		bAGCTxCode                			0xc00000
+#define		bAGCRxCode                			0x300000
+
+#define		b3WireDataLength          		0x800	// Reg 0x820~84f rFPGA0_XA_HSSIParameter1
+#define		b3WireAddressLength       		0x400
+
+#define		b3WireRFPowerDown         		0x1	// Useless now
+//#define bHWSISelect               		0x8
+#define		b5GPAPEPolarity           			0x40000000
+#define		b2GPAPEPolarity           			0x80000000
+#define		bRFSW_TxDefaultAnt        		0x3
+#define		bRFSW_TxOptionAnt         		0x30
+#define		bRFSW_RxDefaultAnt        		0x300
+#define		bRFSW_RxOptionAnt         		0x3000
+#define		bRFSI_3WireData           		0x1
+#define		bRFSI_3WireClock          		0x2
+#define		bRFSI_3WireLoad           		0x4
+#define		bRFSI_3WireRW             		0x8
+#define		bRFSI_3Wire               			0xf
+
+#define		bRFSI_RFENV               			0x10	// Reg 0x870 rFPGA0_XAB_RFInterfaceSW
+
+#define		bRFSI_TRSW                			0x20	// Useless now
+#define		bRFSI_TRSWB               			0x40
+#define		bRFSI_ANTSW               			0x100
+#define		bRFSI_ANTSWB              		0x200
+#define		bRFSI_PAPE                			0x400
+#define		bRFSI_PAPE5G              			0x800
+#define		bBandSelect               			0x1
+#define		bHTSIG2_GI                			0x80
+#define		bHTSIG2_Smoothing         		0x01
+#define		bHTSIG2_Sounding          		0x02
+#define		bHTSIG2_Aggreaton         		0x08
+#define		bHTSIG2_STBC              		0x30
+#define		bHTSIG2_AdvCoding         		0x40
+#define		bHTSIG2_NumOfHTLTF        		0x300
+#define		bHTSIG2_CRC8              		0x3fc
+#define		bHTSIG1_MCS               			0x7f
+#define		bHTSIG1_BandWidth         		0x80
+#define		bHTSIG1_HTLength          		0xffff
+#define		bLSIG_Rate                			0xf
+#define		bLSIG_Reserved            		0x10
+#define		bLSIG_Length              			0x1fffe
+#define		bLSIG_Parity              			0x20
+#define		bCCKRxPhase               		0x4
+#define		bLSSIReadAddress          		0x7f800000   // T65 RF
+#define		bLSSIReadEdge             		0x80000000   //LSSI "Read" edge signal
+#define		bLSSIReadBackData         		0xfffff		// T65 RF
+#define		bLSSIReadOKFlag           		0x1000	// Useless now
+#define		bCCKSampleRate            		0x8       //0: 44MHz, 1:88MHz
+#define		bRegulator0Standby        		0x1
+#define		bRegulatorPLLStandby      		0x2
+#define		bRegulator1Standby        		0x4
+#define		bPLLPowerUp               			0x8
+#define		bDPLLPowerUp              		0x10
+#define		bDA10PowerUp              		0x20
+#define		bAD7PowerUp               			0x200
+#define		bDA6PowerUp               			0x2000
+#define		bXtalPowerUp              			0x4000
+#define		b40MDClkPowerUP           		0x8000
+#define		bDA6DebugMode             		0x20000
+#define		bDA6Swing                 			0x380000
+
+#define		bADClkPhase               			0x4000000	// Reg 0x880 rFPGA0_AnalogParameter1 20/40 CCK support switch 40/80 BB MHZ
+
+#define		b80MClkDelay              			0x18000000	// Useless
+#define		bAFEWatchDogEnable        		0x20000000
+
+#define		bXtalCap01                			0xc0000000	// Reg 0x884 rFPGA0_AnalogParameter2 Crystal cap
+#define		bXtalCap23                			0x3
+#define		bXtalCap92x					0x0f000000
+#define 		bXtalCap                				0x0f000000
+
+#define		bIntDifClkEnable          		0x400	// Useless
+#define		bExtSigClkEnable         	 	0x800
+#define		bBandgapMbiasPowerUp      	0x10000
+#define		bAD11SHGain               		0xc0000
+#define		bAD11InputRange           		0x700000
+#define		bAD11OPCurrent            		0x3800000
+#define		bIPathLoopback            		0x4000000
+#define		bQPathLoopback            		0x8000000
+#define		bAFELoopback              		0x10000000
+#define		bDA10Swing                		0x7e0
+#define		bDA10Reverse              		0x800
+#define		bDAClkSource              		0x1000
+#define		bAD7InputRange            		0x6000
+#define		bAD7Gain                  			0x38000
+#define		bAD7OutputCMMode          		0x40000
+#define		bAD7InputCMMode           		0x380000
+#define		bAD7Current               			0xc00000
+#define		bRegulatorAdjust          		0x7000000
+#define		bAD11PowerUpAtTx          		0x1
+#define		bDA10PSAtTx               		0x10
+#define		bAD11PowerUpAtRx          		0x100
+#define		bDA10PSAtRx               		0x1000
+#define		bCCKRxAGCFormat           		0x200
+#define		bPSDFFTSamplepPoint       		0xc000
+#define		bPSDAverageNum            		0x3000
+#define		bIQPathControl            		0xc00
+#define		bPSDFreq                  			0x3ff
+#define		bPSDAntennaPath           		0x30
+#define		bPSDIQSwitch              		0x40
+#define		bPSDRxTrigger             		0x400000
+#define		bPSDTxTrigger             		0x80000000
+#define		bPSDSineToneScale        		0x7f000000
+#define		bPSDReport                			0xffff
+
+// 3. Page9(0x900)
+#define		bOFDMTxSC                 		0x30000000	// Useless
+#define		bCCKTxOn                  			0x1
+#define		bOFDMTxOn                 		0x2
+#define		bDebugPage                		0xfff  //reset debug page and also HWord, LWord
+#define		bDebugItem                		0xff   //reset debug page and LWord
+#define		bAntL              	       		0x10
+#define		bAntNonHT           	      			0x100
+#define		bAntHT1               			0x1000
+#define		bAntHT2                   			0x10000
+#define		bAntHT1S1                 			0x100000
+#define		bAntNonHTS1               		0x1000000
+
+// 4. PageA(0xA00)
+#define		bCCKBBMode                		0x3	// Useless
+#define		bCCKTxPowerSaving         		0x80
+#define		bCCKRxPowerSaving         		0x40
+
+#define		bCCKSideBand              		0x10	// Reg 0xa00 rCCK0_System 20/40 switch
+
+#define		bCCKScramble              		0x8	// Useless
+#define		bCCKAntDiversity    		      	0x8000
+#define		bCCKCarrierRecovery   	    	0x4000
+#define		bCCKTxRate           		     	0x3000
+#define		bCCKDCCancel             	 	0x0800
+#define		bCCKISICancel             		0x0400
+#define		bCCKMatchFilter           		0x0200
+#define		bCCKEqualizer             		0x0100
+#define		bCCKPreambleDetect       	 	0x800000
+#define		bCCKFastFalseCCA          		0x400000
+#define		bCCKChEstStart            		0x300000
+#define		bCCKCCACount              		0x080000
+#define		bCCKcs_lim                			0x070000
+#define		bCCKBistMode              		0x80000000
+#define		bCCKCCAMask             	  	0x40000000
+#define		bCCKTxDACPhase         	   	0x4
+#define		bCCKRxADCPhase         	   	0x20000000   //r_rx_clk
+#define		bCCKr_cp_mode0         	   	0x0100
+#define		bCCKTxDCOffset           	 	0xf0
+#define		bCCKRxDCOffset           	 	0xf
+#define		bCCKCCAMode              	 	0xc000
+#define		bCCKFalseCS_lim           		0x3f00
+#define		bCCKCS_ratio              		0xc00000
+#define		bCCKCorgBit_sel           		0x300000
+#define		bCCKPD_lim                			0x0f0000
+#define		bCCKNewCCA                		0x80000000
+#define		bCCKRxHPofIG              		0x8000
+#define		bCCKRxIG                  			0x7f00
+#define		bCCKLNAPolarity           		0x800000
+#define		bCCKRx1stGain             		0x7f0000
+#define		bCCKRFExtend              		0x20000000 //CCK Rx Iinital gain polarity
+#define		bCCKRxAGCSatLevel        	 	0x1f000000
+#define		bCCKRxAGCSatCount       	  	0xe0
+#define		bCCKRxRFSettle            		0x1f       //AGCsamp_dly
+#define		bCCKFixedRxAGC           	 	0x8000
+//#define bCCKRxAGCFormat         	 	0x4000   //remove to HSSI register 0x824
+#define		bCCKAntennaPolarity      	 	0x2000
+#define		bCCKTxFilterType          		0x0c00
+#define		bCCKRxAGCReportType   	   	0x0300
+#define		bCCKRxDAGCEn              		0x80000000
+#define		bCCKRxDAGCPeriod        	  	0x20000000
+#define		bCCKRxDAGCSatLevel     	   	0x1f000000
+#define		bCCKTimingRecovery       	 	0x800000
+#define		bCCKTxC0                  			0x3f0000
+#define		bCCKTxC1                  			0x3f000000
+#define		bCCKTxC2                  			0x3f
+#define		bCCKTxC3                  			0x3f00
+#define		bCCKTxC4                  			0x3f0000
+#define		bCCKTxC5                  			0x3f000000
+#define		bCCKTxC6                  			0x3f
+#define		bCCKTxC7                  			0x3f00
+#define		bCCKDebugPort             		0xff0000
+#define		bCCKDACDebug              		0x0f000000
+#define		bCCKFalseAlarmEnable      		0x8000
+#define		bCCKFalseAlarmRead        		0x4000
+#define		bCCKTRSSI                 			0x7f
+#define		bCCKRxAGCReport           		0xfe
+#define		bCCKRxReport_AntSel       		0x80000000
+#define		bCCKRxReport_MFOff        		0x40000000
+#define		bCCKRxRxReport_SQLoss     	0x20000000
+#define		bCCKRxReport_Pktloss      		0x10000000
+#define		bCCKRxReport_Lockedbit    	0x08000000
+#define		bCCKRxReport_RateError    	0x04000000
+#define		bCCKRxReport_RxRate       		0x03000000
+#define		bCCKRxFACounterLower      	0xff
+#define		bCCKRxFACounterUpper      	0xff000000
+#define		bCCKRxHPAGCStart          		0xe000
+#define		bCCKRxHPAGCFinal          		0x1c00
+#define		bCCKRxFalseAlarmEnable    	0x8000
+#define		bCCKFACounterFreeze       		0x4000
+#define		bCCKTxPathSel             		0x10000000
+#define		bCCKDefaultRxPath         		0xc000000
+#define		bCCKOptionRxPath          		0x3000000
+
+// 5. PageC(0xC00)
+#define		bNumOfSTF                			0x3	// Useless
+#define		bShift_L                 			0xc0
+#define		bGI_TH                   			0xc
+#define		bRxPathA                 			0x1
+#define		bRxPathB                 			0x2
+#define		bRxPathC                 			0x4
+#define		bRxPathD                 			0x8
+#define		bTxPathA                 			0x1
+#define		bTxPathB                 			0x2
+#define		bTxPathC                 			0x4
+#define		bTxPathD                 			0x8
+#define		bTRSSIFreq               			0x200
+#define		bADCBackoff              			0x3000
+#define		bDFIRBackoff             			0xc000
+#define		bTRSSILatchPhase         		0x10000
+#define		bRxIDCOffset             			0xff
+#define		bRxQDCOffset             			0xff00
+#define		bRxDFIRMode              		0x1800000
+#define		bRxDCNFType              		0xe000000
+#define		bRXIQImb_A               			0x3ff
+#define		bRXIQImb_B               			0xfc00
+#define		bRXIQImb_C               			0x3f0000
+#define		bRXIQImb_D               			0xffc00000
+#define		bDC_dc_Notch             		0x60000
+#define		bRxNBINotch              			0x1f000000
+#define		bPD_TH                   			0xf
+#define		bPD_TH_Opt2              		0xc000
+#define		bPWED_TH                 			0x700
+#define		bIfMF_Win_L              			0x800
+#define		bPD_Option               			0x1000
+#define		bMF_Win_L                			0xe000
+#define		bBW_Search_L             		0x30000
+#define		bwin_enh_L               			0xc0000
+#define		bBW_TH                   			0x700000
+#define		bED_TH2                  			0x3800000
+#define		bBW_option               			0x4000000
+#define		bRatio_TH                			0x18000000
+#define		bWindow_L                			0xe0000000
+#define		bSBD_Option              			0x1
+#define		bFrame_TH                			0x1c
+#define		bFS_Option               			0x60
+#define		bDC_Slope_check          		0x80
+#define		bFGuard_Counter_DC_L     		0xe00
+#define		bFrame_Weight_Short      		0x7000
+#define		bSub_Tune                			0xe00000
+#define		bFrame_DC_Length         		0xe000000
+#define		bSBD_start_offset        		0x30000000
+#define		bFrame_TH_2              		0x7
+#define		bFrame_GI2_TH            		0x38
+#define		bGI2_Sync_en             		0x40
+#define		bSarch_Short_Early       		0x300
+#define		bSarch_Short_Late        		0xc00
+#define		bSarch_GI2_Late          		0x70000
+#define		bCFOAntSum               		0x1
+#define		bCFOAcc                  			0x2
+#define		bCFOStartOffset          		0xc
+#define		bCFOLookBack             		0x70
+#define		bCFOSumWeight            		0x80
+#define		bDAGCEnable              			0x10000
+#define		bTXIQImb_A               			0x3ff
+#define		bTXIQImb_B               			0xfc00
+#define		bTXIQImb_C               			0x3f0000
+#define		bTXIQImb_D               			0xffc00000
+#define		bTxIDCOffset             			0xff
+#define		bTxQDCOffset             			0xff00
+#define		bTxDFIRMode              		0x10000
+#define		bTxPesudoNoiseOn         		0x4000000
+#define		bTxPesudoNoise_A         		0xff
+#define		bTxPesudoNoise_B         		0xff00
+#define		bTxPesudoNoise_C         		0xff0000
+#define		bTxPesudoNoise_D         		0xff000000
+#define		bCCADropOption           		0x20000
+#define		bCCADropThres            		0xfff00000
+#define		bEDCCA_H                 			0xf
+#define		bEDCCA_L                 			0xf0
+#define		bLambda_ED               0x300
+#define		bRxInitialGain           0x7f
+#define		bRxAntDivEn              0x80
+#define		bRxAGCAddressForLNA      0x7f00
+#define		bRxHighPowerFlow         0x8000
+#define		bRxAGCFreezeThres        0xc0000
+#define		bRxFreezeStep_AGC1       0x300000
+#define		bRxFreezeStep_AGC2       0xc00000
+#define		bRxFreezeStep_AGC3       0x3000000
+#define		bRxFreezeStep_AGC0       0xc000000
+#define		bRxRssi_Cmp_En           0x10000000
+#define		bRxQuickAGCEn            0x20000000
+#define		bRxAGCFreezeThresMode    0x40000000
+#define		bRxOverFlowCheckType     0x80000000
+#define		bRxAGCShift              0x7f
+#define		bTRSW_Tri_Only           0x80
+#define		bPowerThres              0x300
+#define		bRxAGCEn                 0x1
+#define		bRxAGCTogetherEn         0x2
+#define		bRxAGCMin                0x4
+#define		bRxHP_Ini                0x7
+#define		bRxHP_TRLNA              0x70
+#define		bRxHP_RSSI               0x700
+#define		bRxHP_BBP1               0x7000
+#define		bRxHP_BBP2               0x70000
+#define		bRxHP_BBP3               0x700000
+#define		bRSSI_H                  0x7f0000     //the threshold for high power
+#define		bRSSI_Gen                0x7f000000   //the threshold for ant diversity
+#define		bRxSettle_TRSW           0x7
+#define		bRxSettle_LNA            0x38
+#define		bRxSettle_RSSI           0x1c0
+#define		bRxSettle_BBP            0xe00
+#define		bRxSettle_RxHP           0x7000
+#define		bRxSettle_AntSW_RSSI     0x38000
+#define		bRxSettle_AntSW          0xc0000
+#define		bRxProcessTime_DAGC      0x300000
+#define		bRxSettle_HSSI           0x400000
+#define		bRxProcessTime_BBPPW     0x800000
+#define		bRxAntennaPowerShift     0x3000000
+#define		bRSSITableSelect         0xc000000
+#define		bRxHP_Final              0x7000000
+#define		bRxHTSettle_BBP          0x7
+#define		bRxHTSettle_HSSI         0x8
+#define		bRxHTSettle_RxHP         0x70
+#define		bRxHTSettle_BBPPW        0x80
+#define		bRxHTSettle_Idle         0x300
+#define		bRxHTSettle_Reserved     0x1c00
+#define		bRxHTRxHPEn              0x8000
+#define		bRxHTAGCFreezeThres      0x30000
+#define		bRxHTAGCTogetherEn       0x40000
+#define		bRxHTAGCMin              0x80000
+#define		bRxHTAGCEn               0x100000
+#define		bRxHTDAGCEn              0x200000
+#define		bRxHTRxHP_BBP            0x1c00000
+#define		bRxHTRxHP_Final          0xe0000000
+#define		bRxPWRatioTH             0x3
+#define		bRxPWRatioEn             0x4
+#define		bRxMFHold                0x3800
+#define		bRxPD_Delay_TH1          0x38
+#define		bRxPD_Delay_TH2          0x1c0
+#define		bRxPD_DC_COUNT_MAX       0x600
+//#define bRxMF_Hold               0x3800
+#define		bRxPD_Delay_TH           0x8000
+#define		bRxProcess_Delay         0xf0000
+#define		bRxSearchrange_GI2_Early 0x700000
+#define		bRxFrame_Guard_Counter_L 0x3800000
+#define		bRxSGI_Guard_L           0xc000000
+#define		bRxSGI_Search_L          0x30000000
+#define		bRxSGI_TH                0xc0000000
+#define		bDFSCnt0                 0xff
+#define		bDFSCnt1                 0xff00
+#define		bDFSFlag                 0xf0000
+#define		bMFWeightSum             0x300000
+#define		bMinIdxTH                0x7f000000
+#define		bDAFormat                0x40000
+#define		bTxChEmuEnable           0x01000000
+#define		bTRSWIsolation_A         0x7f
+#define		bTRSWIsolation_B         0x7f00
+#define		bTRSWIsolation_C         0x7f0000
+#define		bTRSWIsolation_D         0x7f000000
+#define		bExtLNAGain              0x7c00
+
+// 6. PageE(0xE00)
+#define		bSTBCEn                  0x4	// Useless
+#define		bAntennaMapping          0x10
+#define		bNss                     0x20
+#define		bCFOAntSumD              0x200
+#define		bPHYCounterReset         0x8000000
+#define		bCFOReportGet            0x4000000
+#define		bOFDMContinueTx          0x10000000
+#define		bOFDMSingleCarrier       0x20000000
+#define		bOFDMSingleTone          0x40000000
+//#define bRxPath1                 0x01
+//#define bRxPath2                 0x02
+//#define bRxPath3                 0x04
+//#define bRxPath4                 0x08
+//#define bTxPath1                 0x10
+//#define bTxPath2                 0x20
+#define		bHTDetect                0x100
+#define		bCFOEn                   0x10000
+#define		bCFOValue                0xfff00000
+#define		bSigTone_Re              0x3f
+#define		bSigTone_Im              0x7f00
+#define		bCounter_CCA             0xffff
+#define		bCounter_ParityFail      0xffff0000
+#define		bCounter_RateIllegal     0xffff
+#define		bCounter_CRC8Fail        0xffff0000
+#define		bCounter_MCSNoSupport    0xffff
+#define		bCounter_FastSync        0xffff
+#define		bShortCFO                0xfff
+#define		bShortCFOTLength         12   //total
+#define		bShortCFOFLength         11   //fraction
+#define		bLongCFO                 0x7ff
+#define		bLongCFOTLength          11
+#define		bLongCFOFLength          11
+#define		bTailCFO                 0x1fff
+#define		bTailCFOTLength          13
+#define		bTailCFOFLength          12
+#define		bmax_en_pwdB             0xffff
+#define		bCC_power_dB             0xffff0000
+#define		bnoise_pwdB              0xffff
+#define		bPowerMeasTLength        10
+#define		bPowerMeasFLength        3
+#define		bRx_HT_BW                0x1
+#define		bRxSC                    0x6
+#define		bRx_HT                   0x8
+#define		bNB_intf_det_on          0x1
+#define		bIntf_win_len_cfg        0x30
+#define		bNB_Intf_TH_cfg          0x1c0
+#define		bRFGain                  0x3f
+#define		bTableSel                0x40
+#define		bTRSW                    0x80
+#define		bRxSNR_A                 0xff
+#define		bRxSNR_B                 0xff00
+#define		bRxSNR_C                 0xff0000
+#define		bRxSNR_D                 0xff000000
+#define		bSNREVMTLength           8
+#define		bSNREVMFLength           1
+#define		bCSI1st                  0xff
+#define		bCSI2nd                  0xff00
+#define		bRxEVM1st                0xff0000
+#define		bRxEVM2nd                0xff000000
+#define		bSIGEVM                  0xff
+#define		bPWDB                    0xff00
+#define		bSGIEN                   0x10000
+
+#define		bSFactorQAM1             0xf	// Useless
+#define		bSFactorQAM2             0xf0
+#define		bSFactorQAM3             0xf00
+#define		bSFactorQAM4             0xf000
+#define		bSFactorQAM5             0xf0000
+#define		bSFactorQAM6             0xf0000
+#define		bSFactorQAM7             0xf00000
+#define		bSFactorQAM8             0xf000000
+#define		bSFactorQAM9             0xf0000000
+#define		bCSIScheme               0x100000
+
+#define		bNoiseLvlTopSet          0x3	// Useless
+#define		bChSmooth                0x4
+#define		bChSmoothCfg1            0x38
+#define		bChSmoothCfg2            0x1c0
+#define		bChSmoothCfg3            0xe00
+#define		bChSmoothCfg4            0x7000
+#define		bMRCMode                 0x800000
+#define		bTHEVMCfg                0x7000000
+
+#define		bLoopFitType             0x1	// Useless
+#define		bUpdCFO                  0x40
+#define		bUpdCFOOffData           0x80
+#define		bAdvUpdCFO               0x100
+#define		bAdvTimeCtrl             0x800
+#define		bUpdClko                 0x1000
+#define		bFC                      0x6000
+#define		bTrackingMode            0x8000
+#define		bPhCmpEnable             0x10000
+#define		bUpdClkoLTF              0x20000
+#define		bComChCFO                0x40000
+#define		bCSIEstiMode             0x80000
+#define		bAdvUpdEqz               0x100000
+#define		bUChCfg                  0x7000000
+#define		bUpdEqz                  0x8000000
+
+#define		bTxAGCRate18_06			0x7f7f7f7f	// Useless
+#define		bTxAGCRate54_24			0x7f7f7f7f
+#define		bTxAGCRateMCS32			0x7f
+#define		bTxAGCRateCCK			0x7f00
+#define		bTxAGCRateMCS3_MCS0		0x7f7f7f7f
+#define		bTxAGCRateMCS7_MCS4		0x7f7f7f7f
+#define		bTxAGCRateMCS11_MCS8	0x7f7f7f7f
+#define		bTxAGCRateMCS15_MCS12	0x7f7f7f7f
+
+//Rx Pseduo noise
+#define		bRxPesudoNoiseOn         0x20000000	// Useless
+#define		bRxPesudoNoise_A         0xff
+#define		bRxPesudoNoise_B         0xff00
+#define		bRxPesudoNoise_C         0xff0000
+#define		bRxPesudoNoise_D         0xff000000
+#define		bPesudoNoiseState_A      0xffff
+#define		bPesudoNoiseState_B      0xffff0000
+#define		bPesudoNoiseState_C      0xffff
+#define		bPesudoNoiseState_D      0xffff0000
+
+//7. RF Register
+//Zebra1
+#define		bZebra1_HSSIEnable        0x8		// Useless
+#define		bZebra1_TRxControl        0xc00
+#define		bZebra1_TRxGainSetting    0x07f
+#define		bZebra1_RxCorner          0xc00
+#define		bZebra1_TxChargePump      0x38
+#define		bZebra1_RxChargePump      0x7
+#define		bZebra1_ChannelNum        0xf80
+#define		bZebra1_TxLPFBW           0x400
+#define		bZebra1_RxLPFBW           0x600
+
+//Zebra4
+#define		bRTL8256RegModeCtrl1      0x100	// Useless
+#define		bRTL8256RegModeCtrl0      0x40
+#define		bRTL8256_TxLPFBW          0x18
+#define		bRTL8256_RxLPFBW          0x600
+
+//RTL8258
+#define		bRTL8258_TxLPFBW          0xc	// Useless
+#define		bRTL8258_RxLPFBW          0xc00
+#define		bRTL8258_RSSILPFBW        0xc0
+
+
+//
+// Other Definition
+//
+
+//byte endable for sb_write
+#define		bByte0                    0x1	// Useless
+#define		bByte1                    0x2
+#define		bByte2                    0x4
+#define		bByte3                    0x8
+#define		bWord0                    0x3
+#define		bWord1                    0xc
+#define		bDWord                    0xf
+
+//for PutRegsetting & GetRegSetting BitMask
+#define		bMaskByte0                0xff	// Reg 0xc50 rOFDM0_XAAGCCore~0xC6f
+#define		bMaskByte1                0xff00
+#define		bMaskByte2                0xff0000
+#define		bMaskByte3                0xff000000
+#define		bMaskHWord                0xffff0000
+#define		bMaskLWord                0x0000ffff
+#define		bMaskDWord                0xffffffff
+
+//for PutRFRegsetting & GetRFRegSetting BitMask
+#define		bMask12Bits               0xfffff	// RF Reg mask bits
+#define		bMask20Bits               0xfffff	// RF Reg mask bits T65 RF
+#define 		bRFRegOffsetMask		0xfffff
+
+#define		bEnable                   0x1	// Useless
+#define		bDisable                  0x0
+
+#define		LeftAntenna               0x0	// Useless
+#define		RightAntenna              0x1
+
+#define		tCheckTxStatus            500   //500ms // Useless
+#define		tUpdateRxCounter          100   //100ms
+
+#define		rateCCK     0	// Useless
+#define		rateOFDM    1
+#define		rateHT      2
+
+//define Register-End
+#define		bPMAC_End                 0x1ff	// Useless
+#define		bFPGAPHY0_End             0x8ff
+#define		bFPGAPHY1_End             0x9ff
+#define		bCCKPHY0_End              0xaff
+#define		bOFDMPHY0_End             0xcff
+#define		bOFDMPHY1_End             0xdff
+
+//define max debug item in each debug page
+//#define bMaxItem_FPGA_PHY0        0x9
+//#define bMaxItem_FPGA_PHY1        0x3
+//#define bMaxItem_PHY_11B          0x16
+//#define bMaxItem_OFDM_PHY0        0x29
+//#define bMaxItem_OFDM_PHY1        0x0
+
+#define		bPMACControl              0x0		// Useless
+#define		bWMACControl              0x1
+#define		bWNICControl              0x2
+
+#define		PathA                     0x0	// Useless
+#define		PathB                     0x1
+#define		PathC                     0x2
+#define		PathD                     0x3
+
+/*--------------------------Define Parameters-------------------------------*/
+
+
+#endif	//__INC_HAL8192SPHYREG_H
+
diff --git a/drivers/staging/rtl8192su/r8192S_rtl6052.c b/drivers/staging/rtl8192su/r8192S_rtl6052.c
new file mode 100644
index 0000000..71caf81
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_rtl6052.c
@@ -0,0 +1,946 @@
+/******************************************************************************
+ *
+ *     (c) Copyright  2008, RealTEK Technologies Inc. All Rights Reserved.
+ *
+ * Module:	HalRf6052.c	( Source C File)
+ *
+ * Note:	Provide RF 6052 series relative API.
+ *
+ * Function:
+ *
+ * Export:
+ *
+ * Abbrev:
+ *
+ * History:
+ * Data			Who		Remark
+ *
+ * 09/25/2008	MHC		Create initial version.
+ * 11/05/2008 	MHC		Add API for tw power setting.
+ *
+ *
+******************************************************************************/
+#include "r8192U.h"
+#include "r8192S_rtl6052.h"
+
+#ifdef RTL8192SU
+#include "r8192S_hw.h"
+#include "r8192S_phyreg.h"
+#include "r8192S_phy.h"
+#else
+#include "r8192U_hw.h"
+#include "r819xU_phyreg.h"
+#include "r819xU_phy.h"
+#endif
+
+
+/*---------------------------Define Local Constant---------------------------*/
+// Define local structure for debug!!!!!
+typedef struct RF_Shadow_Compare_Map {
+	// Shadow register value
+	u32		Value;
+	// Compare or not flag
+	u8		Compare;
+	// Record If it had ever modified unpredicted
+	u8		ErrorOrNot;
+	// Recorver Flag
+	u8		Recorver;
+	//
+	u8		Driver_Write;
+}RF_SHADOW_T;
+/*---------------------------Define Local Constant---------------------------*/
+
+
+/*------------------------Define global variable-----------------------------*/
+/*------------------------Define global variable-----------------------------*/
+
+
+
+
+/*---------------------Define local function prototype-----------------------*/
+void phy_RF6052_Config_HardCode(struct net_device* dev);
+
+RT_STATUS phy_RF6052_Config_ParaFile(struct net_device* dev);
+/*---------------------Define local function prototype-----------------------*/
+
+/*------------------------Define function prototype--------------------------*/
+extern void RF_ChangeTxPath(struct net_device* dev,  u16 DataRate);
+
+/*------------------------Define function prototype--------------------------*/
+
+/*------------------------Define local variable------------------------------*/
+// 2008/11/20 MH For Debug only, RF
+static	RF_SHADOW_T	RF_Shadow[RF6052_MAX_PATH][RF6052_MAX_REG];// = {{0}};//FIXLZM
+/*------------------------Define local variable------------------------------*/
+
+/*------------------------Define function prototype--------------------------*/
+/*-----------------------------------------------------------------------------
+ * Function:	RF_ChangeTxPath
+ *
+ * Overview:	For RL6052, we must change some RF settign for 1T or 2T.
+ *
+ * Input:		u16 DataRate		// 0x80-8f, 0x90-9f
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 09/25/2008 	MHC		Create Version 0.
+ *						Firmwaer support the utility later.
+ *
+ *---------------------------------------------------------------------------*/
+extern void RF_ChangeTxPath(struct net_device* dev,  u16 DataRate)
+{
+// We do not support gain table change inACUT now !!!! Delete later !!!
+#if 0//(RTL92SE_FPGA_VERIFY == 0)
+	static	u1Byte	RF_Path_Type = 2;	// 1 = 1T 2= 2T
+	static	u4Byte	tx_gain_tbl1[6]
+			= {0x17f50, 0x11f40, 0x0cf30, 0x08720, 0x04310, 0x00100};
+	static	u4Byte	tx_gain_tbl2[6]
+			= {0x15ea0, 0x10e90, 0x0c680, 0x08250, 0x04040, 0x00030};
+	u1Byte	i;
+
+	if (RF_Path_Type == 2 && (DataRate&0xF) <= 0x7)
+	{
+		// Set TX SYNC power G2G3 loop filter
+		PHY_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A,
+					RF_TXPA_G2, bMask20Bits, 0x0f000);
+		PHY_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A,
+					RF_TXPA_G3, bMask20Bits, 0xeacf1);
+
+		// Change TX AGC gain table
+		for (i = 0; i < 6; i++)
+			PHY_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A,
+						RF_TX_AGC, bMask20Bits, tx_gain_tbl1[i]);
+
+		// Set PA to high value
+		PHY_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A,
+					RF_TXPA_G2, bMask20Bits, 0x01e39);
+	}
+	else if (RF_Path_Type == 1 && (DataRate&0xF) >= 0x8)
+	{
+		// Set TX SYNC power G2G3 loop filter
+		PHY_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A,
+					RF_TXPA_G2, bMask20Bits, 0x04440);
+		PHY_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A,
+					RF_TXPA_G3, bMask20Bits, 0xea4f1);
+
+		// Change TX AGC gain table
+		for (i = 0; i < 6; i++)
+			PHY_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A,
+						RF_TX_AGC, bMask20Bits, tx_gain_tbl2[i]);
+
+		// Set PA low gain
+		PHY_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A,
+					RF_TXPA_G2, bMask20Bits, 0x01e19);
+	}
+#endif
+
+}	/* RF_ChangeTxPath */
+
+
+/*-----------------------------------------------------------------------------
+ * Function:    PHY_RF6052SetBandwidth()
+ *
+ * Overview:    This function is called by SetBWModeCallback8190Pci() only
+ *
+ * Input:       PADAPTER				Adapter
+ *			WIRELESS_BANDWIDTH_E	Bandwidth	//20M or 40M
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Note:		For RF type 0222D
+ *---------------------------------------------------------------------------*/
+void PHY_RF6052SetBandwidth(struct net_device* dev, HT_CHANNEL_WIDTH Bandwidth)	//20M or 40M
+{
+	//u8				eRFPath;
+	//struct r8192_priv 	*priv = ieee80211_priv(dev);
+
+
+	//if (priv->card_8192 == NIC_8192SE)
+#ifdef RTL8192SU  //YJ,test,090113
+	{
+		switch(Bandwidth)
+		{
+			case HT_CHANNEL_WIDTH_20:
+				//if (priv->card_8192_version >= VERSION_8192S_BCUT)
+				//	rtl8192_setBBreg(dev, rFPGA0_AnalogParameter2, 0xff, 0x58);
+
+				rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A, RF_CHNLBW, BIT10|BIT11, 0x01);
+				break;
+			case HT_CHANNEL_WIDTH_20_40:
+				//if (priv->card_8192_version >= VERSION_8192S_BCUT)
+				//	rtl8192_setBBreg(dev, rFPGA0_AnalogParameter2, 0xff, 0x18);
+
+				rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A, RF_CHNLBW, BIT10|BIT11, 0x00);
+				break;
+			default:
+				RT_TRACE(COMP_DBG, "PHY_SetRF6052Bandwidth(): unknown Bandwidth: %#X\n",Bandwidth);
+				break;
+		}
+	}
+//	else
+#else
+	{
+	for(eRFPath = 0; eRFPath <priv->NumTotalRFPath; eRFPath++)
+	{
+		switch(Bandwidth)
+		{
+			case HT_CHANNEL_WIDTH_20:
+					//PHY_SetRFReg(Adapter, (RF90_RADIO_PATH_E)RF90_PATH_A, RF_CHNLBW, (BIT10|BIT11), 0x01);
+				break;
+			case HT_CHANNEL_WIDTH_20_40:
+					//PHY_SetRFReg(Adapter, (RF90_RADIO_PATH_E)RF90_PATH_A, RF_CHNLBW, (BIT10|BIT11), 0x00);
+				break;
+			default:
+					RT_TRACE(COMP_DBG, "PHY_SetRF8225Bandwidth(): unknown Bandwidth: %#X\n",Bandwidth );
+				break;
+
+		}
+	}
+	}
+#endif
+}
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	PHY_RF6052SetCckTxPower
+ *
+ * Overview:
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/05/2008 	MHC		Simulate 8192series..
+ *
+ *---------------------------------------------------------------------------*/
+extern void PHY_RF6052SetCckTxPower(struct net_device* dev, u8	powerlevel)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32				TxAGC=0;
+
+	if(priv->ieee80211->scanning == 1)
+		TxAGC = 0x3f;
+	else if(priv->bDynamicTxLowPower == true)//cosa 04282008 for cck long range
+		TxAGC = 0x22;
+	else
+		TxAGC = powerlevel;
+
+	//cosa add for lenovo, to pass the safety spec, don't increase power index for different rates.
+	if(priv->bIgnoreDiffRateTxPowerOffset)
+		TxAGC = powerlevel;
+
+	if(TxAGC > RF6052_MAX_TX_PWR)
+		TxAGC = RF6052_MAX_TX_PWR;
+
+	//printk("CCK PWR= %x\n", TxAGC);
+	rtl8192_setBBreg(dev, rTxAGC_CCK_Mcs32, bTxAGCRateCCK, TxAGC);
+
+}	/* PHY_RF6052SetCckTxPower */
+
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	PHY_RF6052SetOFDMTxPower
+ *
+ * Overview:	For legacy and HY OFDM, we must read EEPROM TX power index for
+ *			different channel and read original value in TX power register area from
+ *			0xe00. We increase offset and original value to be correct tx pwr.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/05/2008 	MHC		Simulate 8192 series method.
+* 01/06/2009	MHC		1. Prevent Path B tx power overflow or underflow dure to
+ *						A/B pwr difference or legacy/HT pwr diff.
+ *						2. We concern with path B legacy/HT OFDM difference.
+ * 01/22/2009	MHC		Support new EPRO format from SD3.
+ *---------------------------------------------------------------------------*/
+ #if 1
+extern void PHY_RF6052SetOFDMTxPower(struct net_device* dev, u8 powerlevel)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 	writeVal, powerBase0, powerBase1;
+	u8 	index = 0;
+	u16 	RegOffset[6] = {0xe00, 0xe04, 0xe10, 0xe14, 0xe18, 0xe1c};
+	//u8 	byte0, byte1, byte2, byte3;
+	u8    Channel = priv->ieee80211->current_network.channel;
+	u8	rfa_pwr[4];
+	u8	rfa_lower_bound = 0, rfa_upper_bound = 0 /*, rfa_htpwr, rfa_legacypwr*/;
+	u8	i;
+	u8	rf_pwr_diff = 0;
+	u8	Legacy_pwrdiff=0, HT20_pwrdiff=0, BandEdge_Pwrdiff=0;
+	u8	ofdm_bandedge_chnl_low=0, ofdm_bandedge_chnl_high=0;
+
+
+	// We only care about the path A for legacy.
+	if (priv->EEPROMVersion != 2)
+	powerBase0 = powerlevel + (priv->LegacyHTTxPowerDiff & 0xf);
+	else if (priv->EEPROMVersion == 2)	// Defined by SD1 Jong
+	{
+		//
+		// 2009/01/21 MH Support new EEPROM format from SD3 requirement
+		//
+		Legacy_pwrdiff = priv->TxPwrLegacyHtDiff[RF90_PATH_A][Channel-1];
+		// For legacy OFDM, tx pwr always > HT OFDM pwr. We do not care Path B
+		// legacy OFDM pwr diff. NO BB register to notify HW.
+		powerBase0 = powerlevel + Legacy_pwrdiff;
+		//RTPRINT(FPHY, PHY_TXPWR, (" [LagacyToHT40 pwr diff = %d]\n", Legacy_pwrdiff));
+
+		// Band Edge scheme is enabled for FCC mode
+		if (priv->TxPwrbandEdgeFlag == 1/* && pHalData->ChannelPlan == 0*/)
+		{
+			ofdm_bandedge_chnl_low = 1;
+			ofdm_bandedge_chnl_high = 11;
+		#if 0//cosa, Todo: check ofdm 40MHz, when lower and duplicate, the bandedge chnl low=3, high=9
+			if (pHalData->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
+			{	// Is it the same with the document?
+				if(pHalData->nCur40MhzPrimeSC == HAL_PRIME_CHNL_OFFSET_UPPER)
+				else if(pHalData->nCur40MhzPrimeSC == HAL_PRIME_CHNL_OFFSET_LOWER;
+				else
+				pHalData->nCur40MhzPrimeSC = HAL_PRIME_CHNL_OFFSET_DONT_CARE;
+			}
+		#endif
+			BandEdge_Pwrdiff = 0;
+			if (Channel <= ofdm_bandedge_chnl_low)
+				BandEdge_Pwrdiff = priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][0];
+			else if (Channel >= ofdm_bandedge_chnl_high)
+			{
+				BandEdge_Pwrdiff = priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][1];
+			}
+			powerBase0 -= BandEdge_Pwrdiff;
+			if (Channel <= ofdm_bandedge_chnl_low || Channel >= ofdm_bandedge_chnl_high)
+			{
+				//RTPRINT(FPHY, PHY_TXPWR, (" [OFDM band-edge channel = %d, pwr diff = %d]\n",
+				//Channel, BandEdge_Pwrdiff));
+			}
+		}
+		//RTPRINT(FPHY, PHY_TXPWR, (" [OFDM power base index = 0x%x]\n", powerBase0));
+	}
+	powerBase0 = (powerBase0<<24) | (powerBase0<<16) |(powerBase0<<8) |powerBase0;
+
+	//MCS rates
+	if(priv->EEPROMVersion == 2)
+	{
+		//Cosa add for new EEPROM content. 02102009
+
+		//Check HT20 to HT40 diff
+		if (priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20)
+		{
+			// HT 20<->40 pwr diff
+			HT20_pwrdiff = priv->TxPwrHt20Diff[RF90_PATH_A][Channel-1];
+
+			// Calculate Antenna pwr diff
+			if (HT20_pwrdiff < 8)	// 0~+7
+				powerlevel += HT20_pwrdiff;
+			else				// index8-15=-8~-1
+				powerlevel -= (16-HT20_pwrdiff);
+
+			//RTPRINT(FPHY, PHY_TXPWR, (" [HT20 to HT40 pwrdiff = %d]\n", HT20_pwrdiff));
+			//RTPRINT(FPHY, PHY_TXPWR, (" [MCS power base index = 0x%x]\n", powerlevel));
+		}
+
+		// Band Edge scheme is enabled for FCC mode
+		if (priv->TxPwrbandEdgeFlag == 1/* && pHalData->ChannelPlan == 0*/)
+		{
+			BandEdge_Pwrdiff = 0;
+			if (priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
+			{
+				if (Channel <= 3)
+					BandEdge_Pwrdiff = priv->TxPwrbandEdgeHt40[RF90_PATH_A][0];
+				else if (Channel >= 9)
+					BandEdge_Pwrdiff = priv->TxPwrbandEdgeHt40[RF90_PATH_A][1];
+				if (Channel <= 3 || Channel >= 9)
+				{
+					//RTPRINT(FPHY, PHY_TXPWR, (" [HT40 band-edge channel = %d, pwr diff = %d]\n",
+					//Channel, BandEdge_Pwrdiff));
+				}
+			}
+			else if (priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20)
+			{
+				if (Channel <= 1)
+					BandEdge_Pwrdiff = priv->TxPwrbandEdgeHt20[RF90_PATH_A][0];
+				else if (Channel >= 11)
+					BandEdge_Pwrdiff = priv->TxPwrbandEdgeHt20[RF90_PATH_A][1];
+				if (Channel <= 1 || Channel >= 11)
+				{
+					//RTPRINT(FPHY, PHY_TXPWR, (" [HT20 band-edge channel = %d, pwr diff = %d]\n",
+					//Channel, BandEdge_Pwrdiff));
+				}
+			}
+			powerlevel -= BandEdge_Pwrdiff;
+			//RTPRINT(FPHY, PHY_TXPWR, (" [MCS power base index = 0x%x]\n", powerlevel));
+		}
+	}
+	powerBase1 = powerlevel;
+	powerBase1 = (powerBase1<<24) | (powerBase1<<16) |(powerBase1<<8) |powerBase1;
+
+	//RTPRINT(FPHY, PHY_TXPWR, (" [Legacy/HT power index= %x/%x]\n", powerBase0, powerBase1));
+
+	for(index=0; index<6; index++)
+	{
+		//
+		// Index 0 & 1= legacy OFDM, 2-5=HT_MCS rate
+		//
+		//cosa add for lenovo, to pass the safety spec, don't increase power index for different rates.
+		if(priv->bIgnoreDiffRateTxPowerOffset)
+			writeVal = ((index<2)?powerBase0:powerBase1);
+		else
+		writeVal = priv->MCSTxPowerLevelOriginalOffset[index] + ((index<2)?powerBase0:powerBase1);
+
+		//RTPRINT(FPHY, PHY_TXPWR, ("Reg 0x%x, Original=%x writeVal=%x\n",
+		//RegOffset[index], priv->MCSTxPowerLevelOriginalOffset[index], writeVal));
+
+		//
+		// If path A and Path B coexist, we must limit Path A tx power.
+		// Protect Path B pwr over or under flow. We need to calculate upper and
+		// lower bound of path A tx power.
+		//
+		if (priv->rf_type == RF_2T2R)
+		{
+		#if 0//cosa, we have only one AntennaTxPwDiff
+			// HT OFDM
+			if (index > 1)
+			{
+				rf_pwr_diff = pHalData->AntennaTxPwDiff[0];
+			}
+			// Legacy OFDM
+			else
+			{
+				rf_pwr_diff = pHalData->AntTxPwDiffLegacy[0];
+			}
+		#endif
+			rf_pwr_diff = priv->AntennaTxPwDiff[0];
+			//RTPRINT(FPHY, PHY_TXPWR, ("2T2R RF-B to RF-A PWR DIFF=%d\n", rf_pwr_diff));
+
+			if (rf_pwr_diff >= 8)		// Diff=-8~-1
+			{	// Prevent underflow!!
+				rfa_lower_bound = 0x10-rf_pwr_diff;
+				//RTPRINT(FPHY, PHY_TXPWR, ("rfa_lower_bound= %d\n", rfa_lower_bound));
+			}
+			else if (rf_pwr_diff >= 0)	// Diff = 0-7
+			{
+				rfa_upper_bound = RF6052_MAX_TX_PWR-rf_pwr_diff;
+				//RTPRINT(FPHY, PHY_TXPWR, ("rfa_upper_bound= %d\n", rfa_upper_bound));
+			}
+		}
+
+		for (i=  0; i <4; i++)
+		{
+			rfa_pwr[i] = (u8)((writeVal & (0x7f<<(i*8)))>>(i*8));
+			if (rfa_pwr[i]  > RF6052_MAX_TX_PWR)
+				rfa_pwr[i]  = RF6052_MAX_TX_PWR;
+
+			//
+			// If path A and Path B coexist, we must limit Path A tx power.
+			// Protect Path B pwr over or under flow. We need to calculate upper and
+			// lower bound of path A tx power.
+			//
+			if (priv->rf_type == RF_2T2R)
+			{
+				if (rf_pwr_diff >= 8)		// Diff=-8~-1
+				{	// Prevent underflow!!
+					if (rfa_pwr[i] <rfa_lower_bound)
+					{
+						//RTPRINT(FPHY, PHY_TXPWR, ("Underflow"));
+						rfa_pwr[i] = rfa_lower_bound;
+					}
+				}
+				else if (rf_pwr_diff >= 1)	// Diff = 0-7
+				{	// Prevent overflow
+					if (rfa_pwr[i] > rfa_upper_bound)
+					{
+						//RTPRINT(FPHY, PHY_TXPWR, ("Overflow"));
+						rfa_pwr[i] = rfa_upper_bound;
+					}
+				}
+				//RTPRINT(FPHY, PHY_TXPWR, ("rfa_pwr[%d]=%x\n", i, rfa_pwr[i]));
+			}
+
+		}
+
+		//
+		// Add description: PWDB > threshold!!!High power issue!!
+		// We must decrease tx power !! Why is the value ???
+		//
+		if(priv->bDynamicTxHighPower == TRUE)
+		{
+			// For MCS rate
+			if(index > 1)
+			{
+				writeVal = 0x03030303;
+			}
+			// For Legacy rate
+			else
+			{
+				writeVal = (rfa_pwr[3]<<24) | (rfa_pwr[2]<<16) |(rfa_pwr[1]<<8) |rfa_pwr[0];
+			}
+			//RTPRINT(FPHY, PHY_TXPWR, ("HighPower=%08x\n", writeVal));
+		}
+		else
+		{
+			writeVal = (rfa_pwr[3]<<24) | (rfa_pwr[2]<<16) |(rfa_pwr[1]<<8) |rfa_pwr[0];
+			//RTPRINT(FPHY, PHY_TXPWR, ("NormalPower=%08x\n", writeVal));
+		}
+
+		//
+		// Write different rate set tx power index.
+		//
+		//if (DCMD_Test_Flag == 0)
+		rtl8192_setBBreg(dev, RegOffset[index], 0x7f7f7f7f, writeVal);
+	}
+
+}	/* PHY_RF6052SetOFDMTxPower */
+#else
+extern void PHY_RF6052SetOFDMTxPower(struct net_device* dev, u8 powerlevel)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 	writeVal, powerBase0, powerBase1;
+	u8 	index = 0;
+	u16 	RegOffset[6] = {0xe00, 0xe04, 0xe10, 0xe14, 0xe18, 0xe1c};
+	u8 	byte0, byte1, byte2, byte3;
+	u8    channel = priv->ieee80211->current_network.channel;
+
+	//Legacy OFDM rates
+	powerBase0 = powerlevel + (priv->LegacyHTTxPowerDiff & 0xf);
+	powerBase0 = (powerBase0<<24) | (powerBase0<<16) |(powerBase0<<8) |powerBase0;
+
+	//MCS rates HT OFDM
+	powerBase1 = powerlevel;
+	powerBase1 = (powerBase1<<24) | (powerBase1<<16) |(powerBase1<<8) |powerBase1;
+
+	//printk("Legacy/HT PWR= %x/%x\n", powerBase0, powerBase1);
+
+	for(index=0; index<6; index++)
+	{
+		//
+		// Index 0 & 1= legacy OFDM, 2-5=HT_MCS rate
+		//
+		writeVal = priv->MCSTxPowerLevelOriginalOffset[index] +  ((index<2)?powerBase0:powerBase1);
+
+		//printk("Index = %d Original=%x writeVal=%x\n", index, priv->MCSTxPowerLevelOriginalOffset[index], writeVal);
+
+		byte0 = (u8)(writeVal & 0x7f);
+		byte1 = (u8)((writeVal & 0x7f00)>>8);
+		byte2 = (u8)((writeVal & 0x7f0000)>>16);
+		byte3 = (u8)((writeVal & 0x7f000000)>>24);
+
+		// Max power index = 0x3F Range = 0-0x3F
+		if(byte0 > RF6052_MAX_TX_PWR)
+			byte0 = RF6052_MAX_TX_PWR;
+		if(byte1 > RF6052_MAX_TX_PWR)
+			byte1 = RF6052_MAX_TX_PWR;
+		if(byte2 > RF6052_MAX_TX_PWR)
+			byte2 = RF6052_MAX_TX_PWR;
+		if(byte3 > RF6052_MAX_TX_PWR)
+			byte3 = RF6052_MAX_TX_PWR;
+
+		//
+		// Add description: PWDB > threshold!!!High power issue!!
+		// We must decrease tx power !! Why is the value ???
+		//
+		if(priv->bDynamicTxHighPower == true)
+		{
+			// For MCS rate
+			if(index > 1)
+			{
+				writeVal = 0x03030303;
+			}
+			// For Legacy rate
+			else
+			{
+				writeVal = (byte3<<24) | (byte2<<16) |(byte1<<8) |byte0;
+			}
+		}
+		else
+		{
+			writeVal = (byte3<<24) | (byte2<<16) |(byte1<<8) |byte0;
+		}
+
+		//
+		// Write different rate set tx power index.
+		//
+		rtl8192_setBBreg(dev, RegOffset[index], 0x7f7f7f7f, writeVal);
+	}
+
+}	/* PHY_RF6052SetOFDMTxPower */
+#endif
+
+RT_STATUS PHY_RF6052_Config(struct net_device* dev)
+{
+	struct r8192_priv 			*priv = ieee80211_priv(dev);
+	RT_STATUS				rtStatus = RT_STATUS_SUCCESS;
+	//RF90_RADIO_PATH_E		eRFPath;
+	//BB_REGISTER_DEFINITION_T	*pPhyReg;
+	//u32						OrgStoreRFIntSW[RF90_PATH_D+1];
+
+	//
+	// Initialize general global value
+	//
+	// TODO: Extend RF_PATH_C and RF_PATH_D in the future
+	if(priv->rf_type == RF_1T1R)
+		priv->NumTotalRFPath = 1;
+	else
+		priv->NumTotalRFPath = 2;
+
+	//
+	// Config BB and RF
+	//
+//	switch( priv->bRegHwParaFile )
+//	{
+//		case 0:
+//			phy_RF6052_Config_HardCode(dev);
+//			break;
+
+//		case 1:
+			rtStatus = phy_RF6052_Config_ParaFile(dev);
+//			break;
+
+//		case 2:
+			// Partial Modify.
+//			phy_RF6052_Config_HardCode(dev);
+//			phy_RF6052_Config_ParaFile(dev);
+//			break;
+
+//		default:
+//			phy_RF6052_Config_HardCode(dev);
+//			break;
+//	}
+	return rtStatus;
+
+}
+
+void phy_RF6052_Config_HardCode(struct net_device* dev)
+{
+
+	// Set Default Bandwidth to 20M
+	//Adapter->HalFunc	.SetBWModeHandler(Adapter, HT_CHANNEL_WIDTH_20);
+
+	// TODO: Set Default Channel to channel one for RTL8225
+
+}
+
+RT_STATUS phy_RF6052_Config_ParaFile(struct net_device* dev)
+{
+	u32			u4RegValue = 0;
+	//static s1Byte		szRadioAFile[] = RTL819X_PHY_RADIO_A;
+	//static s1Byte		szRadioBFile[] = RTL819X_PHY_RADIO_B;
+	//static s1Byte		szRadioBGMFile[] = RTL819X_PHY_RADIO_B_GM;
+	u8			eRFPath;
+	RT_STATUS		rtStatus = RT_STATUS_SUCCESS;
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	BB_REGISTER_DEFINITION_T	*pPhyReg;
+	//u8			eCheckItem;
+
+
+	//3//-----------------------------------------------------------------
+	//3// <2> Initialize RF
+	//3//-----------------------------------------------------------------
+	//for(eRFPath = RF90_PATH_A; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
+	for(eRFPath = 0; eRFPath <priv->NumTotalRFPath; eRFPath++)
+	{
+
+		pPhyReg = &priv->PHYRegDef[eRFPath];
+
+		/*----Store original RFENV control type----*/
+		switch(eRFPath)
+		{
+		case RF90_PATH_A:
+		case RF90_PATH_C:
+			u4RegValue = rtl8192_QueryBBReg(dev, pPhyReg->rfintfs, bRFSI_RFENV);
+			break;
+		case RF90_PATH_B :
+		case RF90_PATH_D:
+			u4RegValue = rtl8192_QueryBBReg(dev, pPhyReg->rfintfs, bRFSI_RFENV<<16);
+			break;
+		}
+
+		/*----Set RF_ENV enable----*/
+		rtl8192_setBBreg(dev, pPhyReg->rfintfe, bRFSI_RFENV<<16, 0x1);
+
+		/*----Set RF_ENV output high----*/
+		rtl8192_setBBreg(dev, pPhyReg->rfintfo, bRFSI_RFENV, 0x1);
+
+		/* Set bit number of Address and Data for RF register */
+		rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2, b3WireAddressLength, 0x0); 	// Set 1 to 4 bits for 8255
+		rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2, b3WireDataLength, 0x0);	// Set 0 to 12  bits for 8255
+
+
+		/*----Initialize RF fom connfiguration file----*/
+		switch(eRFPath)
+		{
+		case RF90_PATH_A:
+#if	RTL8190_Download_Firmware_From_Header
+			rtStatus= rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
+#else
+			rtStatus = PHY_ConfigRFWithParaFile(Adapter, (char* )&szRadioAFile, (RF90_RADIO_PATH_E)eRFPath);
+#endif
+			break;
+		case RF90_PATH_B:
+#if	RTL8190_Download_Firmware_From_Header
+			rtStatus= rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
+#else
+			if(priv->rf_type == RF_2T2R_GREEN)
+				rtStatus = PHY_ConfigRFWithParaFile(Adapter, (ps1Byte)&szRadioBGMFile, (RF90_RADIO_PATH_E)eRFPath);
+			else
+				rtStatus = PHY_ConfigRFWithParaFile(Adapter, (char* )&szRadioBFile, (RF90_RADIO_PATH_E)eRFPath);
+#endif
+			break;
+		case RF90_PATH_C:
+			break;
+		case RF90_PATH_D:
+			break;
+		}
+
+		/*----Restore RFENV control type----*/;
+		switch(eRFPath)
+		{
+		case RF90_PATH_A:
+		case RF90_PATH_C:
+			rtl8192_setBBreg(dev, pPhyReg->rfintfs, bRFSI_RFENV, u4RegValue);
+			break;
+		case RF90_PATH_B :
+		case RF90_PATH_D:
+			rtl8192_setBBreg(dev, pPhyReg->rfintfs, bRFSI_RFENV<<16, u4RegValue);
+			break;
+		}
+
+		if(rtStatus != RT_STATUS_SUCCESS){
+			printk("phy_RF6052_Config_ParaFile():Radio[%d] Fail!!", eRFPath);
+			goto phy_RF6052_Config_ParaFile_Fail;
+		}
+
+	}
+
+	RT_TRACE(COMP_INIT, "<---phy_RF6052_Config_ParaFile()\n");
+	return rtStatus;
+
+phy_RF6052_Config_ParaFile_Fail:
+	return rtStatus;
+}
+
+
+//
+// ==> RF shadow Operation API Code Section!!!
+//
+/*-----------------------------------------------------------------------------
+ * Function:	PHY_RFShadowRead
+ *				PHY_RFShadowWrite
+ *				PHY_RFShadowCompare
+ *				PHY_RFShadowRecorver
+ *				PHY_RFShadowCompareAll
+ *				PHY_RFShadowRecorverAll
+ *				PHY_RFShadowCompareFlagSet
+ *				PHY_RFShadowRecorverFlagSet
+ *
+ * Overview:	When we set RF register, we must write shadow at first.
+ *			When we are running, we must compare shadow abd locate error addr.
+ *			Decide to recorver or not.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 11/20/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+extern u32 PHY_RFShadowRead(
+	struct net_device		* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32					Offset)
+{
+	return	RF_Shadow[eRFPath][Offset].Value;
+
+}	/* PHY_RFShadowRead */
+
+
+extern void PHY_RFShadowWrite(
+	struct net_device		* dev,
+	u32	eRFPath,
+	u32					Offset,
+	u32					Data)
+{
+	//RF_Shadow[eRFPath][Offset].Value = (Data & bMask20Bits);
+	RF_Shadow[eRFPath][Offset].Value = (Data & bRFRegOffsetMask);
+	RF_Shadow[eRFPath][Offset].Driver_Write = true;
+
+}	/* PHY_RFShadowWrite */
+
+
+extern void PHY_RFShadowCompare(
+	struct net_device		* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32					Offset)
+{
+	u32	reg;
+
+	// Check if we need to check the register
+	if (RF_Shadow[eRFPath][Offset].Compare == true)
+	{
+		reg = rtl8192_phy_QueryRFReg(dev, eRFPath, Offset, bRFRegOffsetMask);
+		// Compare shadow and real rf register for 20bits!!
+		if (RF_Shadow[eRFPath][Offset].Value != reg)
+		{
+			// Locate error position.
+			RF_Shadow[eRFPath][Offset].ErrorOrNot = true;
+			RT_TRACE(COMP_INIT, "PHY_RFShadowCompare RF-%d Addr%02xErr = %05x", eRFPath, Offset, reg);
+		}
+	}
+
+}	/* PHY_RFShadowCompare */
+
+extern void PHY_RFShadowRecorver(
+	struct net_device		* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32					Offset)
+{
+	// Check if the address is error
+	if (RF_Shadow[eRFPath][Offset].ErrorOrNot == true)
+	{
+		// Check if we need to recorver the register.
+		if (RF_Shadow[eRFPath][Offset].Recorver == true)
+		{
+			rtl8192_phy_SetRFReg(dev, eRFPath, Offset, bRFRegOffsetMask, RF_Shadow[eRFPath][Offset].Value);
+			RT_TRACE(COMP_INIT, "PHY_RFShadowRecorver RF-%d Addr%02x=%05x",
+			eRFPath, Offset, RF_Shadow[eRFPath][Offset].Value);
+		}
+	}
+
+}	/* PHY_RFShadowRecorver */
+
+
+extern void PHY_RFShadowCompareAll(struct net_device * dev)
+{
+	u32		eRFPath;
+	u32		Offset;
+
+	for (eRFPath = 0; eRFPath < RF6052_MAX_PATH; eRFPath++)
+	{
+		for (Offset = 0; Offset <= RF6052_MAX_REG; Offset++)
+		{
+			PHY_RFShadowCompare(dev, (RF90_RADIO_PATH_E)eRFPath, Offset);
+		}
+	}
+
+}	/* PHY_RFShadowCompareAll */
+
+
+extern void PHY_RFShadowRecorverAll(struct net_device * dev)
+{
+	u32		eRFPath;
+	u32		Offset;
+
+	for (eRFPath = 0; eRFPath < RF6052_MAX_PATH; eRFPath++)
+	{
+		for (Offset = 0; Offset <= RF6052_MAX_REG; Offset++)
+		{
+			PHY_RFShadowRecorver(dev, (RF90_RADIO_PATH_E)eRFPath, Offset);
+		}
+	}
+
+}	/* PHY_RFShadowRecorverAll */
+
+
+extern void PHY_RFShadowCompareFlagSet(
+	struct net_device 		* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32					Offset,
+	u8					Type)
+{
+	// Set True or False!!!
+	RF_Shadow[eRFPath][Offset].Compare = Type;
+
+}	/* PHY_RFShadowCompareFlagSet */
+
+
+extern void PHY_RFShadowRecorverFlagSet(
+	struct net_device 		* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32					Offset,
+	u8					Type)
+{
+	// Set True or False!!!
+	RF_Shadow[eRFPath][Offset].Recorver= Type;
+
+}	/* PHY_RFShadowRecorverFlagSet */
+
+
+extern void PHY_RFShadowCompareFlagSetAll(struct net_device  * dev)
+{
+	u32		eRFPath;
+	u32		Offset;
+
+	for (eRFPath = 0; eRFPath < RF6052_MAX_PATH; eRFPath++)
+	{
+		for (Offset = 0; Offset <= RF6052_MAX_REG; Offset++)
+		{
+			// 2008/11/20 MH For S3S4 test, we only check reg 26/27 now!!!!
+			if (Offset != 0x26 && Offset != 0x27)
+				PHY_RFShadowCompareFlagSet(dev, (RF90_RADIO_PATH_E)eRFPath, Offset, FALSE);
+			else
+				PHY_RFShadowCompareFlagSet(dev, (RF90_RADIO_PATH_E)eRFPath, Offset, TRUE);
+		}
+	}
+
+}	/* PHY_RFShadowCompareFlagSetAll */
+
+
+extern void PHY_RFShadowRecorverFlagSetAll(struct net_device  * dev)
+{
+	u32		eRFPath;
+	u32		Offset;
+
+	for (eRFPath = 0; eRFPath < RF6052_MAX_PATH; eRFPath++)
+	{
+		for (Offset = 0; Offset <= RF6052_MAX_REG; Offset++)
+		{
+			// 2008/11/20 MH For S3S4 test, we only check reg 26/27 now!!!!
+			if (Offset != 0x26 && Offset != 0x27)
+				PHY_RFShadowRecorverFlagSet(dev, (RF90_RADIO_PATH_E)eRFPath, Offset, FALSE);
+			else
+				PHY_RFShadowRecorverFlagSet(dev, (RF90_RADIO_PATH_E)eRFPath, Offset, TRUE);
+		}
+	}
+
+}	/* PHY_RFShadowCompareFlagSetAll */
+
+
+
+extern void PHY_RFShadowRefresh(struct net_device  * dev)
+{
+	u32		eRFPath;
+	u32		Offset;
+
+	for (eRFPath = 0; eRFPath < RF6052_MAX_PATH; eRFPath++)
+	{
+		for (Offset = 0; Offset <= RF6052_MAX_REG; Offset++)
+		{
+			RF_Shadow[eRFPath][Offset].Value = 0;
+			RF_Shadow[eRFPath][Offset].Compare = false;
+			RF_Shadow[eRFPath][Offset].Recorver  = false;
+			RF_Shadow[eRFPath][Offset].ErrorOrNot = false;
+			RF_Shadow[eRFPath][Offset].Driver_Write = false;
+		}
+	}
+
+}	/* PHY_RFShadowRead */
+
+/* End of HalRf6052.c */
diff --git a/drivers/staging/rtl8192su/r8192S_rtl6052.h b/drivers/staging/rtl8192su/r8192S_rtl6052.h
new file mode 100644
index 0000000..916603c
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_rtl6052.h
@@ -0,0 +1,134 @@
+/******************************************************************************
+ *
+ *     (c) Copyright  2008, RealTEK Technologies Inc. All Rights Reserved.
+ *
+ * Module:	HalRf.h	( Header File)
+ *
+ * Note:	Collect every HAL RF type exter API or constant.
+ *
+ * Function:
+ *
+ * Export:
+ *
+ * Abbrev:
+ *
+ * History:
+ * Data			Who		Remark
+ *
+ * 09/25/2008	MHC		Create initial version.
+ *
+ *
+******************************************************************************/
+/* Check to see if the file has been included already.  */
+
+
+/*--------------------------Define Parameters-------------------------------*/
+
+//
+// For RF 6052 Series
+//
+#define	RF6052_MAX_TX_PWR	0x3F
+#define	RF6052_MAX_REG		0x3F
+#define	RF6052_MAX_PATH		4
+/*--------------------------Define Parameters-------------------------------*/
+
+
+/*------------------------------Define structure----------------------------*/
+
+/*------------------------------Define structure----------------------------*/
+
+
+/*------------------------Export global variable----------------------------*/
+/*------------------------Export global variable----------------------------*/
+
+/*------------------------Export Marco Definition---------------------------*/
+
+/*------------------------Export Marco Definition---------------------------*/
+
+
+/*--------------------------Exported Function prototype---------------------*/
+//======================================================
+#if 1
+// Function prototypes for HalPhy8225.c
+//1======================================================
+extern void PHY_SetRF0222DBandwidth(struct net_device* dev , HT_CHANNEL_WIDTH Bandwidth);	//20M or 40M;
+extern void PHY_SetRF8225Bandwidth(	struct net_device* dev ,	HT_CHANNEL_WIDTH Bandwidth);
+extern bool PHY_RF8225_Config(struct net_device* dev );
+extern void phy_RF8225_Config_HardCode(struct net_device*	dev);
+extern bool phy_RF8225_Config_ParaFile(struct net_device* dev);
+extern void PHY_SetRF8225CckTxPower(struct net_device* dev ,u8 powerlevel);
+extern void PHY_SetRF8225OfdmTxPower(struct net_device* dev ,u8        powerlevel);
+extern void PHY_SetRF0222DOfdmTxPower(struct net_device* dev ,u8 powerlevel);
+extern void PHY_SetRF0222DCckTxPower(struct net_device* dev ,u8        powerlevel);
+
+//1======================================================
+// Function prototypes for HalPhy8256.c
+//1======================================================
+extern void PHY_SetRF8256Bandwidth(struct net_device* dev , HT_CHANNEL_WIDTH Bandwidth);
+extern void PHY_RF8256_Config(struct net_device* dev);
+extern void phy_RF8256_Config_ParaFile(struct net_device* dev);
+extern void PHY_SetRF8256CCKTxPower(struct net_device*	dev, u8	powerlevel);
+extern void PHY_SetRF8256OFDMTxPower(struct net_device* dev, u8 powerlevel);
+#endif
+
+//
+// RF RL6052 Series API
+//
+extern	void		RF_ChangeTxPath(struct net_device  * dev, u16 DataRate);
+extern	void		PHY_RF6052SetBandwidth(struct net_device  * dev,HT_CHANNEL_WIDTH	Bandwidth);
+extern	void		PHY_RF6052SetCckTxPower(struct net_device  * dev, u8	powerlevel);
+extern	void		PHY_RF6052SetOFDMTxPower(struct net_device  * dev, u8 powerlevel);
+extern	RT_STATUS	PHY_RF6052_Config(struct net_device  * dev);
+extern void PHY_RFShadowRefresh( struct net_device  		* dev);
+extern void PHY_RFShadowWrite( struct net_device* dev, u32 eRFPath, u32 Offset, u32 Data);
+#if 0
+//
+// RF Shadow operation relative API
+//
+extern	u32
+PHY_RFShadowRead(
+	struct net_device  		* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32					Offset);
+extern void
+PHY_RFShadowCompare(
+	struct net_device  		* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32					Offset);
+extern void
+PHY_RFShadowRecorver(
+	struct net_device  		* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32					Offset);
+extern void
+PHY_RFShadowCompareAll(
+	struct net_device  		* dev);
+extern void
+PHY_RFShadowRecorverAll(
+	struct net_device  		* dev);
+extern void
+PHY_RFShadowCompareFlagSet(
+	struct net_device  		* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32					Offset,
+	u8					Type);
+extern void
+PHY_RFShadowRecorverFlagSet(
+	struct net_device  		* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32					Offset,
+	u8					Type);
+extern void
+PHY_RFShadowCompareFlagSetAll(
+	struct net_device  		* dev);
+extern void
+PHY_RFShadowRecorverFlagSetAll(
+	struct net_device  		* dev);
+extern void
+PHY_RFShadowRefresh(
+	struct net_device  		* dev);
+#endif
+/*--------------------------Exported Function prototype---------------------*/
+
+
+/* End of HalRf.h */
diff --git a/drivers/staging/rtl8192su/r8192S_rtl8225.c b/drivers/staging/rtl8192su/r8192S_rtl8225.c
new file mode 100644
index 0000000..09465df
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_rtl8225.c
@@ -0,0 +1,292 @@
+
+#include "r8192U.h"
+#include "r8192S_hw.h"
+#include "r8192S_phyreg.h"
+#include "r8192S_phy.h"
+#include "r8192S_rtl8225.h"
+
+/*---------------------Define local function prototype-----------------------*/
+void phy_RF8225_Config_HardCode(struct net_device* dev );
+bool phy_RF8225_Config_ParaFile(struct net_device* dev );
+/*---------------------Define local function prototype-----------------------*/
+void PHY_SetRF8225OfdmTxPower(struct net_device* dev ,u8	powerlevel)
+{
+
+}
+
+
+
+void PHY_SetRF8225CckTxPower(	struct net_device* dev ,	u8 powerlevel)
+{
+
+}
+
+
+// TODO: The following RF 022D related function should be removed to HalPhy0222D.c.
+void PHY_SetRF0222DOfdmTxPower(struct net_device* dev ,u8 powerlevel)
+{
+	//TODO: We should set RF TxPower for RF 0222D here!!
+}
+
+
+
+void PHY_SetRF0222DCckTxPower(struct net_device* dev ,u8	powerlevel)
+{
+	//TODO: We should set RF TxPower for RF 0222D here!!
+}
+
+
+/*-----------------------------------------------------------------------------
+ * Function:    PHY_SetRF0222DBandwidth()
+ *
+ * Overview:    This function is called by SetBWModeCallback8190Pci() only
+ *
+ * Input:       PADAPTER				Adapter
+ *			WIRELESS_BANDWIDTH_E	Bandwidth	//20M or 40M
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Note:		For RF type 0222D
+ *---------------------------------------------------------------------------*/
+ //just in phy
+void PHY_SetRF0222DBandwidth(struct net_device* dev , HT_CHANNEL_WIDTH	 Bandwidth)	//20M or 40M
+{
+	u8			eRFPath;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+
+	//if (IS_HARDWARE_TYPE_8192S(dev))
+	if (1)
+	{
+#ifndef RTL92SE_FPGA_VERIFY
+		switch(Bandwidth)
+		{
+			case HT_CHANNEL_WIDTH_20:
+#ifdef FIB_MODIFICATION
+				write_nic_byte(dev, rFPGA0_AnalogParameter2, 0x58);
+#endif
+				rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A, RF_CHNLBW, BIT10|BIT11, 0x01);
+				break;
+			case HT_CHANNEL_WIDTH_20_40:
+#ifdef FIB_MODIFICATION
+				write_nic_byte(dev, rFPGA0_AnalogParameter2, 0x18);
+#endif
+				rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)RF90_PATH_A, RF_CHNLBW, BIT10|BIT11, 0x00);
+				break;
+			default:
+				;//RT_TRACE(COMP_DBG, DBG_LOUD, ("PHY_SetRF8225Bandwidth(): unknown Bandwidth: %#X\n",Bandwidth ));
+				break;
+		}
+#endif
+	}
+	else
+	{
+	for(eRFPath = 0; eRFPath <priv->NumTotalRFPath; eRFPath++)
+	{
+		switch(Bandwidth)
+		{
+			case HT_CHANNEL_WIDTH_20:
+					//rtl8192_phy_SetRFReg(Adapter, (RF90_RADIO_PATH_E)RF90_PATH_A, RF_CHNLBW, (BIT10|BIT11), 0x01);
+				break;
+			case HT_CHANNEL_WIDTH_20_40:
+					//rtl8192_phy_SetRFReg(Adapter, (RF90_RADIO_PATH_E)RF90_PATH_A, RF_CHNLBW, (BIT10|BIT11), 0x00);
+				break;
+			default:
+				;//RT_TRACE(COMP_DBG, DBG_LOUD, ("PHY_SetRF8225Bandwidth(): unknown Bandwidth: %#X\n",Bandwidth ));
+				break;
+
+		}
+	}
+	}
+
+}
+
+// TODO: Aabove RF 022D related function should be removed to HalPhy0222D.c.
+
+/*-----------------------------------------------------------------------------
+ * Function:    PHY_SetRF8225Bandwidth()
+ *
+ * Overview:    This function is called by SetBWModeCallback8190Pci() only
+ *
+ * Input:       PADAPTER				Adapter
+ *			WIRELESS_BANDWIDTH_E	Bandwidth	//20M or 40M
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Note:		8225(zebra1) support 20M only
+ *---------------------------------------------------------------------------*/
+ //just in phy
+void PHY_SetRF8225Bandwidth(struct net_device* dev ,HT_CHANNEL_WIDTH Bandwidth)	//20M or 40M
+{
+	u8			eRFPath;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	//for(eRFPath = RF90_PATH_A; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
+	for(eRFPath = 0; eRFPath <priv->NumTotalRFPath; eRFPath++)
+	{
+		switch(Bandwidth)
+		{
+			case HT_CHANNEL_WIDTH_20:
+				// TODO: Update the parameters here
+				break;
+			case HT_CHANNEL_WIDTH_20_40:
+				RT_TRACE(COMP_DBG, "SetChannelBandwidth8190Pci():8225 does not support 40M mode\n");
+				break;
+			default:
+				RT_TRACE(COMP_DBG, "PHY_SetRF8225Bandwidth(): unknown Bandwidth: %#X\n",Bandwidth );
+				break;
+
+		}
+	}
+
+}
+
+//just in phy
+bool PHY_RF8225_Config(struct net_device* dev )
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	bool	rtStatus = true;
+	//RF90_RADIO_PATH_E			eRFPath;
+	//BB_REGISTER_DEFINITION_T	*pPhyReg;
+	//u32						OrgStoreRFIntSW[RF90_PATH_D+1];
+
+	//
+	// Initialize general global value
+	//
+	// TODO: Extend RF_PATH_C and RF_PATH_D in the future
+	priv->NumTotalRFPath = 2;
+
+	//
+	// Config BB and RF
+	//
+	//switch( Adapter->MgntInfo.bRegHwParaFile )
+	//{
+	//	case 0:
+	//		phy_RF8225_Config_HardCode(dev);
+	//		break;
+
+	//	case 1:
+	//		rtStatus = phy_RF8225_Config_ParaFile(dev);
+	//		break;
+
+	//	case 2:
+			// Partial Modify.
+			phy_RF8225_Config_HardCode(dev);
+			phy_RF8225_Config_ParaFile(dev);
+	//		break;
+
+	//	default:
+	//		phy_RF8225_Config_HardCode(dev);
+	//		break;
+	//}
+	return rtStatus;
+
+}
+
+//just in 8225
+void phy_RF8225_Config_HardCode(struct net_device* dev)
+{
+
+	// Set Default Bandwidth to 20M
+	//Adapter->HalFunc	.SetBWModeHandler(Adapter, HT_CHANNEL_WIDTH_20);
+
+	// TODO: Set Default Channel to channel one for RTL8225
+
+}
+
+//just in 8225
+bool phy_RF8225_Config_ParaFile(struct net_device* dev)
+{
+	u32					u4RegValue = 0;
+	//static char				szRadioAFile[] = RTL819X_PHY_RADIO_A;
+	//static char				szRadioBFile[] = RTL819X_PHY_RADIO_B;
+	u8					eRFPath;
+	bool				rtStatus = true;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	BB_REGISTER_DEFINITION_T	*pPhyReg;
+	//u8						eCheckItem;
+
+#if	1
+	//3//-----------------------------------------------------------------
+	//3// <2> Initialize RF
+	//3//-----------------------------------------------------------------
+	//for(eRFPath = RF90_PATH_A; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
+	for(eRFPath = 0; eRFPath <priv->NumTotalRFPath; eRFPath++)
+	{
+
+		pPhyReg = &priv->PHYRegDef[eRFPath];
+
+		/*----Store original RFENV control type----*/
+		switch(eRFPath)
+		{
+		case RF90_PATH_A:
+		case RF90_PATH_C:
+			u4RegValue = rtl8192_QueryBBReg(dev, pPhyReg->rfintfs, bRFSI_RFENV);
+			break;
+		case RF90_PATH_B :
+		case RF90_PATH_D:
+			u4RegValue = rtl8192_QueryBBReg(dev, pPhyReg->rfintfs, bRFSI_RFENV<<16);
+			break;
+		}
+
+		/*----Set RF_ENV enable----*/
+		rtl8192_setBBreg(dev, pPhyReg->rfintfe, bRFSI_RFENV<<16, 0x1);
+
+		/*----Set RF_ENV output high----*/
+		rtl8192_setBBreg(dev, pPhyReg->rfintfo, bRFSI_RFENV, 0x1);
+
+		/* Set bit number of Address and Data for RF register */
+		rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2, b3WireAddressLength, 0x0); 	// Set 1 to 4 bits for 8255
+		rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2, b3WireDataLength, 0x0);	// Set 0 to 12  bits for 8255
+
+
+		/*----Initialize RF fom connfiguration file----*/
+		switch(eRFPath)
+		{
+		case RF90_PATH_A:
+			//rtStatus = PHY_ConfigRFWithParaFile(dev, (char* )&szRadioAFile, (RF90_RADIO_PATH_E)eRFPath);
+			rtStatus = rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
+			break;
+		case RF90_PATH_B:
+			//rtStatus = PHY_ConfigRFWithParaFile(dev, (char* )&szRadioBFile, (RF90_RADIO_PATH_E)eRFPath);
+			rtStatus = rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
+			break;
+		case RF90_PATH_C:
+			break;
+		case RF90_PATH_D:
+			break;
+		}
+
+		/*----Restore RFENV control type----*/;
+		switch(eRFPath)
+		{
+		case RF90_PATH_A:
+		case RF90_PATH_C:
+			rtl8192_setBBreg(dev, pPhyReg->rfintfs, bRFSI_RFENV, u4RegValue);
+			break;
+		case RF90_PATH_B :
+		case RF90_PATH_D:
+			rtl8192_setBBreg(dev, pPhyReg->rfintfs, bRFSI_RFENV<<16, u4RegValue);
+			break;
+		}
+
+		if(rtStatus == false){
+			//RT_TRACE(COMP_FPGA, DBG_LOUD, ("phy_RF8225_Config_ParaFile():Radio[%d] Fail!!", eRFPath));
+			goto phy_RF8225_Config_ParaFile_Fail;
+		}
+
+	}
+
+	//RT_TRACE(COMP_INIT, DBG_LOUD, ("<---phy_RF8225_Config_ParaFile()\n"));
+	return rtStatus;
+
+phy_RF8225_Config_ParaFile_Fail:
+#endif
+	return rtStatus;
+}
+
+
diff --git a/drivers/staging/rtl8192su/r8192S_rtl8225.h b/drivers/staging/rtl8192su/r8192S_rtl8225.h
new file mode 100644
index 0000000..8a64728
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192S_rtl8225.h
@@ -0,0 +1,30 @@
+/*
+  This is part of the rtl8180-sa2400 driver
+  released under the GPL (See file COPYING for details).
+  Copyright (c) 2005 Andrea Merello <andreamrl@tiscali.it>
+
+  This files contains programming code for the rtl8256
+  radio frontend.
+
+  *Many* thanks to Realtek Corp. for their great support!
+
+*/
+
+#ifndef RTL8225H
+#define RTL8225H
+
+#ifdef RTL8190P
+#define RTL819X_TOTAL_RF_PATH 4 //for 90P
+#else
+#define RTL819X_TOTAL_RF_PATH 2 //for 8192U
+#endif
+extern void PHY_SetRF0222DBandwidth(struct net_device* dev , HT_CHANNEL_WIDTH Bandwidth);	//20M or 40M;
+extern void PHY_SetRF8225Bandwidth(	struct net_device* dev ,	HT_CHANNEL_WIDTH Bandwidth);
+extern bool PHY_RF8225_Config(struct net_device* dev );
+extern void phy_RF8225_Config_HardCode(struct net_device*	dev);
+extern bool phy_RF8225_Config_ParaFile(struct net_device* dev);
+extern void PHY_SetRF8225CckTxPower(struct net_device* dev ,u8 powerlevel);
+extern void PHY_SetRF8225OfdmTxPower(struct net_device* dev ,u8        powerlevel);
+extern void PHY_SetRF0222DOfdmTxPower(struct net_device* dev ,u8 powerlevel);
+extern void PHY_SetRF0222DCckTxPower(struct net_device* dev ,u8        powerlevel);
+#endif
diff --git a/drivers/staging/rtl8192su/r8192U.h b/drivers/staging/rtl8192su/r8192U.h
new file mode 100644
index 0000000..a236558
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192U.h
@@ -0,0 +1,2112 @@
+/*
+   This is part of rtl8187 OpenSource driver.
+   Copyright (C) Andrea Merello 2004-2005  <andreamrl@tiscali.it>
+   Released under the terms of GPL (General Public Licence)
+
+   Parts of this driver are based on the GPL part of the
+   official realtek driver
+
+   Parts of this driver are based on the rtl8192 driver skeleton
+   from Patric Schenke & Andres Salomon
+
+   Parts of this driver are based on the Intel Pro Wireless 2100 GPL driver
+
+   We want to tanks the Authors of those projects and the Ndiswrapper
+   project Authors.
+*/
+
+#ifndef R819xU_H
+#define R819xU_H
+
+#include <linux/module.h>
+#include <linux/kernel.h>
+//#include <linux/config.h>
+#include <linux/init.h>
+#include <linux/ioport.h>
+#include <linux/sched.h>
+#include <linux/types.h>
+#include <linux/slab.h>
+#include <linux/netdevice.h>
+//#include <linux/pci.h>
+#include <linux/usb.h>
+#include <linux/etherdevice.h>
+#include <linux/delay.h>
+#include <linux/rtnetlink.h>	//for rtnl_lock()
+#include <linux/wireless.h>
+#include <linux/timer.h>
+#include <linux/proc_fs.h>	// Necessary because we use the proc fs
+#include <linux/if_arp.h>
+#include <linux/random.h>
+#include <linux/version.h>
+#include <asm/io.h>
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,27))
+#include <asm/semaphore.h>
+#endif
+#include "ieee80211.h"
+
+#ifdef RTL8192SU
+#include "r8192S_firmware.h"
+#else
+#include "r819xU_firmware.h"
+#endif
+
+//#define RTL8192U
+#define RTL819xU_MODULE_NAME "rtl819xU"
+//added for HW security, john.0629
+#define FALSE 0
+#define TRUE 1
+#define MAX_KEY_LEN     61
+#define KEY_BUF_SIZE    5
+
+#define BIT0            0x00000001
+#define BIT1            0x00000002
+#define BIT2            0x00000004
+#define BIT3            0x00000008
+#define BIT4            0x00000010
+#define BIT5            0x00000020
+#define BIT6            0x00000040
+#define BIT7            0x00000080
+#define BIT8            0x00000100
+#define BIT9            0x00000200
+#define BIT10           0x00000400
+#define BIT11           0x00000800
+#define BIT12           0x00001000
+#define BIT13           0x00002000
+#define BIT14           0x00004000
+#define BIT15           0x00008000
+#define BIT16           0x00010000
+#define BIT17           0x00020000
+#define BIT18           0x00040000
+#define BIT19           0x00080000
+#define BIT20           0x00100000
+#define BIT21           0x00200000
+#define BIT22           0x00400000
+#define BIT23           0x00800000
+#define BIT24           0x01000000
+#define BIT25           0x02000000
+#define BIT26           0x04000000
+#define BIT27           0x08000000
+#define BIT28           0x10000000
+#define BIT29           0x20000000
+#define BIT30           0x40000000
+#define BIT31           0x80000000
+
+// Rx smooth factor
+#define	Rx_Smooth_Factor		20
+#if 0 //we need to use RT_TRACE instead DMESG as RT_TRACE will clearly show debug level wb.
+#define DMESG(x,a...) printk(KERN_INFO RTL819xU_MODULE_NAME ": " x "\n", ## a)
+#define DMESGW(x,a...) printk(KERN_WARNING RTL819xU_MODULE_NAME ": WW:" x "\n", ## a)
+#define DMESGE(x,a...) printk(KERN_WARNING RTL819xU_MODULE_NAME ": EE:" x "\n", ## a)
+#else
+#define DMESG(x,a...)
+#define DMESGW(x,a...)
+#define DMESGE(x,a...)
+extern u32 rt_global_debug_component;
+#define RT_TRACE(component, x, args...) \
+do { if(rt_global_debug_component & component) \
+	printk(KERN_DEBUG RTL819xU_MODULE_NAME ":" x "\n" , \
+	       ##args);\
+}while(0);
+//----------------------------------------------------------------------
+//// Get 8192SU  Rx descriptor. Added by Roger, 2008.04.15.
+////----------------------------------------------------------------------
+#define RX_DESC_SIZE 24
+#define RX_DRV_INFO_SIZE_UNIT   8
+
+#define IS_UNDER_11N_AES_MODE(_ieee)  ((_ieee->pHTInfo->bCurrentHTSupport==TRUE) &&\
+									(_ieee->pairwise_key_type==KEY_TYPE_CCMP))
+
+#define COMP_TRACE				BIT0		// For function call tracing.
+#define COMP_DBG				BIT1		// Only for temporary debug message.
+#define COMP_INIT				BIT2		// during driver initialization / halt / reset.
+
+
+#define COMP_RECV				BIT3		// Reveive part data path.
+#define COMP_SEND				BIT4		// Send part path.
+#define COMP_IO					BIT5		// I/O Related. Added by Annie, 2006-03-02.
+#define COMP_POWER				BIT6		// 802.11 Power Save mode or System/Device Power state related.
+#define COMP_EPROM				BIT7		// 802.11 link related: join/start BSS, leave BSS.
+#define COMP_SWBW				BIT8	// For bandwidth switch.
+#define COMP_POWER_TRACKING			BIT9	//FOR 8190 TX POWER TRACKING
+#define COMP_TURBO				BIT10	// For Turbo Mode related. By Annie, 2005-10-21.
+#define COMP_QOS				BIT11	// For QoS.
+#define COMP_RATE				BIT12	// For Rate Adaptive mechanism, 2006.07.02, by rcnjko.
+#define COMP_LPS					BIT13	// For Radio Measurement.
+#define COMP_DIG				BIT14	// For DIG, 2006.09.25, by rcnjko.
+#define COMP_PHY	 			BIT15
+#define COMP_CH					BIT16	//channel setting debug
+#define COMP_TXAGC				BIT17	// For Tx power, 060928, by rcnjko.
+#define COMP_HIPWR				BIT18	// For High Power Mechanism, 060928, by rcnjko.
+#define COMP_HALDM				BIT19	// For HW Dynamic Mechanism, 061010, by rcnjko.
+#define COMP_SEC			        BIT20	// Event handling
+#define COMP_LED				BIT21	// For LED.
+#define COMP_RF					BIT22	// For RF.
+//1!!!!!!!!!!!!!!!!!!!!!!!!!!!
+#define COMP_RXDESC				BIT23	// Show Rx desc information for SD3 debug. Added by Annie, 2006-07-15.
+//1//1Attention Please!!!<11n or 8190 specific code should be put below this line>
+//1!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+#define COMP_FIRMWARE				BIT24	//for firmware downloading
+#define COMP_HT					BIT25	// For 802.11n HT related information. by Emily 2006-8-11
+#define COMP_AMSDU				BIT26	// For A-MSDU Debugging
+
+#define COMP_SCAN				BIT27
+#define COMP_CMD				BIT28
+#define COMP_DOWN				BIT29  //for rm driver module
+#define COMP_RESET				BIT30  //for silent reset
+#define COMP_ERR				BIT31 //for error out, always on
+#endif
+
+#define RTL819x_DEBUG
+#ifdef RTL819x_DEBUG
+#define assert(expr) \
+        if (!(expr)) {                                  \
+                printk( "Assertion failed! %s,%s,%s,line=%d\n", \
+                #expr,__FILE__,__FUNCTION__,__LINE__);          \
+        }
+//wb added to debug out data buf
+//if you want print DATA buffer related BA, please set ieee80211_debug_level to DATA|BA
+#define RT_DEBUG_DATA(level, data, datalen)      \
+        do{ if ((rt_global_debug_component & (level)) == (level))   \
+                {       \
+                        int i;                                  \
+                        u8* pdata = (u8*) data;                 \
+                        printk(KERN_DEBUG RTL819xU_MODULE_NAME ": %s()\n", __FUNCTION__);   \
+                        for(i=0; i<(int)(datalen); i++)                 \
+                        {                                               \
+                                printk("%2x ", pdata[i]);               \
+                                if ((i+1)%16 == 0) printk("\n");        \
+                        }                               \
+                        printk("\n");                   \
+                }                                       \
+        } while (0)
+#else
+#define assert(expr) do {} while (0)
+#define RT_DEBUG_DATA(level, data, datalen) do {} while(0)
+#endif /* RTL8169_DEBUG */
+
+//#ifdef RTL8192SU
+	//2TODO: We should define 8192S firmware related macro settings here!!
+	#define RTL819X_DEFAULT_RF_TYPE				RF_1T2R
+	#define RTL819X_TOTAL_RF_PATH				2
+
+	//#define Rtl819XFwBootArray					Rtl8192UsbFwBootArray
+	//#define Rtl819XFwMainArray					Rtl8192UsbFwMainArray
+	//#define Rtl819XFwDataArray					Rtl8192UsbFwDataArray
+
+	#define Rtl819XMACPHY_Array_PG				Rtl8192UsbMACPHY_Array_PG
+	#define Rtl819XMACPHY_Array					Rtl8192UsbMACPHY_Array
+	#define Rtl819XPHY_REGArray					Rtl8192UsbPHY_REGArray
+	#define Rtl819XPHY_REG_1T2RArray				Rtl8192UsbPHY_REG_1T2RArray
+	//#define Rtl819XRadioA_Array					Rtl8192UsbRadioA_Array
+	//#define Rtl819XRadioB_Array					Rtl8192UsbRadioB_Array
+	#define Rtl819XRadioC_Array					Rtl8192UsbRadioC_Array
+	#define Rtl819XRadioD_Array					Rtl8192UsbRadioD_Array
+
+	//2008.11.06 Add.
+	#define Rtl819XFwImageArray					Rtl8192SUFwImgArray
+	#define Rtl819XMAC_Array						Rtl8192SUMAC_2T_Array
+	#define Rtl819XAGCTAB_Array					Rtl8192SUAGCTAB_Array
+	#define Rtl819XPHY_REG_Array					Rtl8192SUPHY_REG_2T2RArray
+	#define Rtl819XPHY_REG_to1T1R_Array			Rtl8192SUPHY_ChangeTo_1T1RArray
+	#define Rtl819XPHY_REG_to1T2R_Array			Rtl8192SUPHY_ChangeTo_1T2RArray
+	#define Rtl819XPHY_REG_to2T2R_Array			Rtl8192SUPHY_ChangeTo_2T2RArray
+	#define Rtl819XPHY_REG_Array_PG				Rtl8192SUPHY_REG_Array_PG
+	#define Rtl819XRadioA_Array					Rtl8192SURadioA_1T_Array
+	#define Rtl819XRadioB_Array					Rtl8192SURadioB_Array
+	#define Rtl819XRadioB_GM_Array				Rtl8192SURadioB_GM_Array
+	#define Rtl819XRadioA_to1T_Array				Rtl8192SURadioA_to1T_Array
+	#define Rtl819XRadioA_to2T_Array				Rtl8192SURadioA_to2T_Array
+//#endif
+
+//
+// Queue Select Value in TxDesc
+//
+#define QSLT_BK                                 0x1
+#define QSLT_BE                                 0x0
+#define QSLT_VI                                 0x4
+#define QSLT_VO                                 0x6
+#define QSLT_BEACON                             0x10
+#define QSLT_HIGH                               0x11
+#define QSLT_MGNT                               0x12
+#define QSLT_CMD                                0x13
+
+#define DESC90_RATE1M                           0x00
+#define DESC90_RATE2M                           0x01
+#define DESC90_RATE5_5M                         0x02
+#define DESC90_RATE11M                          0x03
+#define DESC90_RATE6M                           0x04
+#define DESC90_RATE9M                           0x05
+#define DESC90_RATE12M                          0x06
+#define DESC90_RATE18M                          0x07
+#define DESC90_RATE24M                          0x08
+#define DESC90_RATE36M                          0x09
+#define DESC90_RATE48M                          0x0a
+#define DESC90_RATE54M                          0x0b
+#define DESC90_RATEMCS0                         0x00
+#define DESC90_RATEMCS1                         0x01
+#define DESC90_RATEMCS2                         0x02
+#define DESC90_RATEMCS3                         0x03
+#define DESC90_RATEMCS4                         0x04
+#define DESC90_RATEMCS5                         0x05
+#define DESC90_RATEMCS6                         0x06
+#define DESC90_RATEMCS7                         0x07
+#define DESC90_RATEMCS8                         0x08
+#define DESC90_RATEMCS9                         0x09
+#define DESC90_RATEMCS10                        0x0a
+#define DESC90_RATEMCS11                        0x0b
+#define DESC90_RATEMCS12                        0x0c
+#define DESC90_RATEMCS13                        0x0d
+#define DESC90_RATEMCS14                        0x0e
+#define DESC90_RATEMCS15                        0x0f
+#define DESC90_RATEMCS32                        0x20
+
+//#ifdef RTL8192SU
+// CCK Rates, TxHT = 0
+#define DESC92S_RATE1M					0x00
+#define DESC92S_RATE2M					0x01
+#define DESC92S_RATE5_5M				0x02
+#define DESC92S_RATE11M					0x03
+
+// OFDM Rates, TxHT = 0
+#define DESC92S_RATE6M					0x04
+#define DESC92S_RATE9M					0x05
+#define DESC92S_RATE12M					0x06
+#define DESC92S_RATE18M					0x07
+#define DESC92S_RATE24M					0x08
+#define DESC92S_RATE36M					0x09
+#define DESC92S_RATE48M					0x0a
+#define DESC92S_RATE54M					0x0b
+
+// MCS Rates, TxHT = 1
+#define DESC92S_RATEMCS0				0x0c
+#define DESC92S_RATEMCS1				0x0d
+#define DESC92S_RATEMCS2				0x0e
+#define DESC92S_RATEMCS3				0x0f
+#define DESC92S_RATEMCS4				0x10
+#define DESC92S_RATEMCS5				0x11
+#define DESC92S_RATEMCS6				0x12
+#define DESC92S_RATEMCS7				0x13
+#define DESC92S_RATEMCS8				0x14
+#define DESC92S_RATEMCS9				0x15
+#define DESC92S_RATEMCS10				0x16
+#define DESC92S_RATEMCS11				0x17
+#define DESC92S_RATEMCS12				0x18
+#define DESC92S_RATEMCS13				0x19
+#define DESC92S_RATEMCS14				0x1a
+#define DESC92S_RATEMCS15				0x1b
+#define DESC92S_RATEMCS15_SG			0x1c
+#define DESC92S_RATEMCS32				0x20
+//#endif
+
+#define RTL819X_DEFAULT_RF_TYPE RF_1T2R
+
+#define IEEE80211_WATCH_DOG_TIME    2000
+#define		PHY_Beacon_RSSI_SLID_WIN_MAX		10
+//for txpowertracking by amy
+#define 	OFDM_Table_Length	19
+#define	CCK_Table_length	12
+
+#ifdef RTL8192SU
+//
+//Tx Descriptor for RLT8192SU(Normal mode)
+//
+typedef struct _tx_desc_819x_usb {
+	// DWORD 0
+	u16		PktSize;//:16;
+	u8		Offset;//:8;
+	u8		Type:2;	// Reserved for MAC header Frame Type subfield.
+	u8		LastSeg:1;
+	u8		FirstSeg:1;
+	u8		LINIP:1;
+	u8		AMSDU:1;
+	u8		GF:1;
+	u8		OWN:1;
+
+	// DWORD 1
+	u8		MacID:5;
+	u8		MoreData:1;
+	u8		MOREFRAG:1;
+	u8		PIFS:1;
+	u8		QueueSelect:5;
+	u8		AckPolicy:2;
+	u8		NoACM:1;
+	u8		NonQos:1;
+	u8		KeyID:2;
+	u8		OUI:1;
+	u8		PktType:1;
+	u8		EnDescID:1;
+	u8		SecType:2;
+	u8		HTC:1;	//padding0
+	u8		WDS:1;	//padding1
+	u8		PktOffset:5;	//padding_len (hw)
+	u8		HWPC:1;
+
+	// DWORD 2
+	u32		DataRetryLmt:6;
+	u32		RetryLmtEn:1;
+	u32		TSFL:5;
+	u32		RTSRC:6;	// Reserved for HW RTS Retry Count.
+	u32		DATARC:6;	// Reserved for HW DATA Retry Count.
+	u32		Rsvd1:5;
+	u32		AllowAggregation:1;
+	u32		BK:1;	//Aggregation break.
+	u32		OwnMAC:1;
+
+	// DWORD 3
+	u8		NextHeadPage;//:8;
+	u8		TailPage;//:8;
+	u16		Seq:12;
+	u16		Frag:4;
+
+	// DWORD 4
+	u32		RTSRate:6;
+	u32		DisRTSFB:1;
+	u32		RTSRateFBLmt:4;
+	u32		CTS2Self:1;
+	u32		RTSEn:1;
+	u32		RaBRSRID:3;	//Rate adaptive BRSR ID.
+	u32		TxHT:1;
+	u32		TxShort:1;//for data
+	u32		TxBandwidth:1;
+	u32		TxSubCarrier:2;
+	u32		STBC:2;
+	u32		RD:1;
+	u32		RTSHT:1;
+	u32		RTSShort:1;
+	u32		RTSBW:1;
+	u32		RTSSubcarrier:2;
+	u32		RTSSTBC:2;
+	u32		USERATE:1;
+	// DWORD 5
+	u32		PktID:9;
+	u32		TxRate:6;
+	u32		DISFB:1;
+	u32		DataRateFBLmt:5;
+	u32		TxAGC:11;
+
+	// DWORD 6
+	u16		IPChkSum;//:16;
+	u16		TCPChkSum;//:16;
+
+	// DWORD 7
+	//u16		TxBuffSize;//:16;//pcie
+        u16     	TxBufferSize;
+	u16		IPHdrOffset:8;
+	u16		Rsvd2:7;
+	u16		TCPEn:1;
+}tx_desc_819x_usb, *ptx_desc_819x_usb;
+typedef struct _tx_status_desc_8192s_usb{
+
+	//DWORD 0
+	u8		TxRate:6;
+	u8		Rsvd1:1;
+	u8		BandWidth:1;
+	u8		RTSRate:6;
+	u8		AGGLS:1;
+	u8		AGG:1;
+	u8		RTSRC:6;
+	u8		DataRC:6;
+	u8		FailCause:2;
+	u8		TxOK:1;
+	u8		Own:1;
+
+	//DWORD 1
+	u16		Seq:12;
+	u8		QueueSel:5;
+	u8		MACID:5;
+	u8		PwrMgt:1;
+	u8		MoreData:1;
+	u8		Rsvd2;
+
+	//DWORD 2
+	u8		RxAGC1;
+	u8		RxAGC2;
+	u8		RxAGC3;
+	u8		RxAGC4;
+}tx_status_desc_8192s_usb, *ptx_status_desc_8192s_usb;
+#else
+/* for rtl819x */
+typedef struct _tx_desc_819x_usb {
+        //DWORD 0
+        u16	PktSize;
+        u8	Offset;
+        u8	Reserved0:3;
+        u8	CmdInit:1;
+        u8	LastSeg:1;
+        u8	FirstSeg:1;
+        u8	LINIP:1;
+        u8	OWN:1;
+
+        //DWORD 1
+        u8	TxFWInfoSize;
+        u8	RATid:3;
+        u8	DISFB:1;
+        u8	USERATE:1;
+        u8	MOREFRAG:1;
+        u8	NoEnc:1;
+        u8	PIFS:1;
+        u8	QueueSelect:5;
+        u8	NoACM:1;
+        u8	Reserved1:2;
+        u8	SecCAMID:5;
+        u8	SecDescAssign:1;
+        u8	SecType:2;
+
+        //DWORD 2
+        u16	TxBufferSize;
+        //u16 Reserved2;
+        u8	ResvForPaddingLen:7;
+        u8	Reserved3:1;
+        u8	Reserved4;
+
+        //DWORD 3, 4, 5
+        u32	Reserved5;
+        u32	Reserved6;
+        u32	Reserved7;
+}tx_desc_819x_usb, *ptx_desc_819x_usb;
+#endif
+
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+typedef struct _tx_desc_819x_usb_aggr_subframe {
+	//DWORD 0
+	u16	PktSize;
+	u8	Offset;
+	u8	TxFWInfoSize;
+
+	//DWORD 1
+	u8	RATid:3;
+	u8	DISFB:1;
+	u8	USERATE:1;
+	u8	MOREFRAG:1;
+	u8	NoEnc:1;
+	u8	PIFS:1;
+	u8	QueueSelect:5;
+	u8	NoACM:1;
+	u8	Reserved1:2;
+	u8	SecCAMID:5;
+	u8	SecDescAssign:1;
+	u8	SecType:2;
+	u8	PacketID:7;
+	u8	OWN:1;
+}tx_desc_819x_usb_aggr_subframe, *ptx_desc_819x_usb_aggr_subframe;
+#endif
+
+
+#ifdef RTL8192SU
+//
+//Tx Descriptor for RLT8192SU(Load FW mode)
+//
+typedef struct _tx_desc_cmd_819x_usb{
+       // DWORD 0
+	u16		PktSize;
+	u8		Offset;
+	u8		Rsvd0:4;
+	u8		LINIP:1;
+	u8		Rsvd1:2;
+	u8		OWN:1;
+
+	// DWORD 1, 2, 3, 4, 5, 6 are all reserved.
+	u32		Rsvd2;
+	u32		Rsvd3;
+	u32		Rsvd4;
+	u32		Rsvd5;
+	u32		Rsvd6;
+	u32		Rsvd7;
+
+	// DWORD 7
+	u16		TxBuffSize;//pcie
+	u16		Rsvd8;
+}tx_desc_cmd_819x_usb, *ptx_desc_cmd_819x_usb;
+//
+//H2C Command for RLT8192SU(Host TxCmd)
+//
+typedef struct _tx_h2c_desc_cmd_8192s_usb{
+       // DWORD 0
+	u32		PktSize:16;
+	u32		Offset:8;
+	u32		Rsvd0:7;
+	u32		OWN:1;
+
+	// DWORD 1
+	u32		Rsvd1:8;
+	u32		QSEL:5;
+	u32		Rsvd2:19;
+
+	// DWORD 2
+	u32		Rsvd3;
+
+	// DWORD 3
+	u32		NextHeadPage:8;
+	u32		TailPage:8;
+	u32		Rsvd4:16;
+
+	// DWORD 4, 5, 6, 7
+	u32		Rsvd5;
+	u32		Rsvd6;
+	u32		Rsvd7;
+	u32		Rsvd8;
+}tx_h2c_desc_cmd_8192s_usb, *ptx_h2c_desc_cmd_8192s_usb;
+
+
+typedef struct _tx_h2c_cmd_hdr_8192s_usb{
+       // DWORD 0
+	u32		CmdLen:16;
+	u32		ElementID:8;
+	u32		CmdSeq:8;
+
+	// DWORD 1
+	u32		Rsvd0;
+}tx_h2c_cmd_hdr_8192s_usb, *ptx_h2c_cmd_hdr_8192s_usb;
+#else
+typedef struct _tx_desc_cmd_819x_usb {
+        //DWORD 0
+	u16	Reserved0;
+	u8	Reserved1;
+	u8	Reserved2:3;
+	u8	CmdInit:1;
+	u8	LastSeg:1;
+	u8	FirstSeg:1;
+	u8	LINIP:1;
+	u8	OWN:1;
+
+        //DOWRD 1
+	//u32	Reserved3;
+	u8	TxFWInfoSize;
+	u8	Reserved3;
+	u8	QueueSelect;
+	u8	Reserved4;
+
+        //DOWRD 2
+	u16 	TxBufferSize;
+	u16	Reserved5;
+
+       //DWORD 3,4,5
+	//u32	TxBufferAddr;
+	//u32	NextDescAddress;
+	u32	Reserved6;
+	u32	Reserved7;
+	u32	Reserved8;
+}tx_desc_cmd_819x_usb, *ptx_desc_cmd_819x_usb;
+#endif
+
+#ifdef RTL8192SU
+typedef struct _tx_fwinfo_819x_usb{
+	//DWORD 0
+	u8			TxRate:7;
+	u8			CtsEnable:1;
+	u8			RtsRate:7;
+	u8			RtsEnable:1;
+	u8			TxHT:1;
+	u8			Short:1;						//Short PLCP for CCK, or short GI for 11n MCS
+	u8			TxBandwidth:1;				// This is used for HT MCS rate only.
+	u8			TxSubCarrier:2;				// This is used for legacy OFDM rate only.
+	u8			STBC:2;
+	u8			AllowAggregation:1;
+	u8			RtsHT:1;						//Interpre RtsRate field as high throughput data rate
+	u8			RtsShort:1;					//Short PLCP for CCK, or short GI for 11n MCS
+	u8			RtsBandwidth:1;				// This is used for HT MCS rate only.
+	u8			RtsSubcarrier:2;				// This is used for legacy OFDM rate only.
+	u8			RtsSTBC:2;
+	u8			EnableCPUDur:1;				//Enable firmware to recalculate and assign packet duration
+
+	//DWORD 1
+	u32			RxMF:2;
+	u32			RxAMD:3;
+        u32			Reserved1:3;
+	u32			TxAGCOffSet:4;//TxAGCOffset:4;
+	u32			TxAGCSign:1;
+	u32			Tx_INFO_RSVD:6;
+	u32			PacketID:13;
+}tx_fwinfo_819x_usb, *ptx_fwinfo_819x_usb;
+#else
+typedef struct _tx_fwinfo_819x_usb {
+        //DOWRD 0
+        u8		TxRate:7;
+        u8		CtsEnable:1;
+        u8		RtsRate:7;
+        u8		RtsEnable:1;
+        u8		TxHT:1;
+        u8		Short:1;                //Short PLCP for CCK, or short GI for 11n MCS
+        u8		TxBandwidth:1;          // This is used for HT MCS rate only.
+        u8		TxSubCarrier:2;         // This is used for legacy OFDM rate only.
+        u8		STBC:2;
+        u8		AllowAggregation:1;
+        u8		RtsHT:1;                //Interpre RtsRate field as high throughput data rate
+        u8		RtsShort:1;             //Short PLCP for CCK, or short GI for 11n MCS
+        u8		RtsBandwidth:1;         // This is used for HT MCS rate only.
+        u8		RtsSubcarrier:2;        // This is used for legacy OFDM rate only.
+        u8		RtsSTBC:2;
+        u8		EnableCPUDur:1;         //Enable firmware to recalculate and assign packet duration
+
+        //DWORD 1
+        u32		RxMF:2;
+        u32		RxAMD:3;
+        u32		TxPerPktInfoFeedback:1;//1 indicate Tx info gathtered by firmware and returned by Rx Cmd
+        u32		Reserved1:2;
+        u32		TxAGCOffSet:4;
+        u32		TxAGCSign:1;
+        u32		Tx_INFO_RSVD:6;
+	u32		PacketID:13;
+        //u32                Reserved;
+}tx_fwinfo_819x_usb, *ptx_fwinfo_819x_usb;
+#endif
+
+typedef struct rtl8192_rx_info {
+	struct urb *urb;
+	struct net_device *dev;
+	u8 out_pipe;
+}rtl8192_rx_info ;
+
+#ifdef RTL8192SU
+//typedef struct _RX_DESC_STATUS_8192SU{
+typedef struct rx_desc_819x_usb{
+	//DWORD 0
+	u16		Length:14;
+	u16		CRC32:1;
+	u16		ICV:1;
+	u8		RxDrvInfoSize:4;
+	u8		Security:3;
+	u8		Qos:1;
+	u8		Shift:2;
+	u8		PHYStatus:1;
+	u8		SWDec:1;
+	u8		LastSeg:1;
+	u8		FirstSeg:1;
+	u8		EOR:1;
+	u8		Own:1;
+
+	//DWORD 1
+	u16		MACID:5;
+	u16		TID:4;
+	u16		HwRsvd:5;
+	u16		PAGGR:1;
+	u16		FAGGR:1;
+	u8		A1_FIT:4;
+	u8		A2_FIT:4;
+	u8		PAM:1;
+	u8		PWR:1;
+	u8		MoreData:1;
+	u8		MoreFrag:1;
+	u8		Type:2;
+	u8		MC:1;
+	u8		BC:1;
+
+	//DWORD 2
+	u16		Seq:12;
+	u16		Frag:4;
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	u8		UsbAggPktNum;//:8;
+#else
+	u8		NextPktLen;//:8;
+#endif
+	u8		Rsvd0:6;
+	u8		NextIND:1;
+	u8		Rsvd1:1;
+
+	//DWORD 3
+	u8		RxMCS:6;
+	u8		RxHT:1;
+	u8		AMSDU:1;
+	u8		SPLCP:1;
+	u8		BW:1;
+	u8		HTC:1;
+	u8		TCPChkRpt:1;
+	u8		IPChkRpt:1;
+	u8		TCPChkValID:1;
+	u8		HwPCErr:1;
+	u8		HwPCInd:1;
+	u16		IV0;//:16;
+
+	//DWORD 4
+	u32		IV1;
+
+	//DWORD 5
+	u32		TSFL;
+//}RX_DESC_STATUS_8192SU, *PRX_DESC_STATUS_8192SU;
+}rx_desc_819x_usb, *prx_desc_819x_usb;
+#else
+typedef struct rx_desc_819x_usb{
+	//DOWRD 0
+	u16                 Length:14;
+	u16                 CRC32:1;
+	u16                 ICV:1;
+	u8                  RxDrvInfoSize;
+	u8                  Shift:2;
+	u8                  PHYStatus:1;
+	u8                  SWDec:1;
+	//u8                LastSeg:1;
+	//u8                FirstSeg:1;
+	//u8                EOR:1;
+	//u8                OWN:1;
+	u8                  Reserved1:4;
+
+	//DWORD 1
+	u32                 Reserved2;
+
+	//DWORD 2
+	//u32               Reserved3;
+
+	//DWORD 3
+	//u32                BufferAddress;
+
+}rx_desc_819x_usb, *prx_desc_819x_usb;
+#endif
+
+#ifdef USB_RX_AGGREGATION_SUPPORT
+typedef struct _rx_desc_819x_usb_aggr_subframe{
+	//DOWRD 0
+	u16			Length:14;
+	u16			CRC32:1;
+	u16			ICV:1;
+	u8			Offset;
+	u8			RxDrvInfoSize;
+	//DOWRD 1
+	u8			Shift:2;
+	u8			PHYStatus:1;
+	u8			SWDec:1;
+	u8			Reserved1:4;
+	u8			Reserved2;
+	u16			Reserved3;
+	//DWORD 2
+	//u4Byte		Reserved3;
+	//DWORD 3
+	//u4Byte           	BufferAddress;
+}rx_desc_819x_usb_aggr_subframe, *prx_desc_819x_usb_aggr_subframe;
+#endif
+
+#ifdef RTL8192SU
+//
+// Driver info are written to the begining of the RxBuffer
+//
+//typedef struct _RX_DRIVER_INFO_8192S{
+typedef struct rx_drvinfo_819x_usb{
+	//
+	// Driver info contain PHY status and other variabel size info
+	// PHY Status content as below
+	//
+
+	//DWORD 0
+	/*u4Byte			gain_0:7;
+	u4Byte			trsw_0:1;
+	u4Byte			gain_1:7;
+	u4Byte			trsw_1:1;
+	u4Byte			gain_2:7;
+	u4Byte			trsw_2:1;
+	u4Byte			gain_3:7;
+	u4Byte			trsw_3:1;	*/
+	u8			gain_trsw[4];
+
+	//DWORD 1
+	/*u4Byte			pwdb_all:8;
+	u4Byte			cfosho_0:8;
+	u4Byte			cfosho_1:8;
+	u4Byte			cfosho_2:8;*/
+	u8			pwdb_all;
+	u8			cfosho[4];
+
+	//DWORD 2
+	/*u4Byte			cfosho_3:8;
+	u4Byte			cfotail_0:8;
+	u4Byte			cfotail_1:8;
+	u4Byte			cfotail_2:8;*/
+	u8			cfotail[4];
+
+	//DWORD 3
+	/*u4Byte			cfotail_3:8;
+	u4Byte			rxevm_0:8;
+	u4Byte			rxevm_1:8;
+	u4Byte			rxsnr_0:8;*/
+	char			        rxevm[2];
+	char			        rxsnr[4];
+
+	//DWORD 4
+	/*u4Byte			rxsnr_1:8;
+	u4Byte			rxsnr_2:8;
+	u4Byte			rxsnr_3:8;
+	u4Byte			pdsnr_0:8;*/
+	u8			pdsnr[2];
+
+	//DWORD 5
+	/*u4Byte			pdsnr_1:8;
+	u4Byte			csi_current_0:8;
+	u4Byte			csi_current_1:8;
+	u4Byte			csi_target_0:8;*/
+	u8			csi_current[2];
+	u8			csi_target[2];
+
+	//DWORD 6
+	/*u4Byte			csi_target_1:8;
+	u4Byte			sigevm:8;
+	u4Byte			max_ex_pwr:8;
+	u4Byte			ex_intf_flag:1;
+	u4Byte			sgi_en:1;
+	u4Byte			rxsc:2;
+	u4Byte			reserve:4;*/
+	u8			sigevm;
+	u8			max_ex_pwr;
+	u8			ex_intf_flag:1;
+	u8			sgi_en:1;
+	u8			rxsc:2;
+	u8			reserve:4;
+
+}rx_drvinfo_819x_usb, *prx_drvinfo_819x_usb;
+#else
+typedef struct rx_drvinfo_819x_usb{
+	//DWORD 0
+	u16                 Reserved1:12;
+	u16                 PartAggr:1;
+	u16                 FirstAGGR:1;
+	u16                 Reserved2:2;
+
+	u8                  RxRate:7;
+	u8                  RxHT:1;
+
+	u8                  BW:1;
+	u8                  SPLCP:1;
+	u8                  Reserved3:2;
+	u8                  PAM:1;
+	u8                  Mcast:1;
+	u8                  Bcast:1;
+	u8                  Reserved4:1;
+
+	//DWORD 1
+	u32                  TSFL;
+
+}rx_drvinfo_819x_usb, *prx_drvinfo_819x_usb;
+#endif
+
+	#define HWSET_MAX_SIZE_92S	128
+#ifdef RTL8192SU
+	#define MAX_802_11_HEADER_LENGTH 40
+	#define MAX_PKT_AGG_NUM		256
+	#define TX_PACKET_SHIFT_BYTES USB_HWDESC_HEADER_LEN
+#else
+	#define MAX_802_11_HEADER_LENGTH        (40 + MAX_FIRMWARE_INFORMATION_SIZE)
+	#define	MAX_PKT_AGG_NUM		64
+	#define TX_PACKET_SHIFT_BYTES (USB_HWDESC_HEADER_LEN + sizeof(tx_fwinfo_819x_usb))
+#endif
+
+#define MAX_DEV_ADDR_SIZE		8  /* support till 64 bit bus width OS */
+#define MAX_FIRMWARE_INFORMATION_SIZE   32 /*2006/04/30 by Emily forRTL8190*/
+//#define MAX_802_11_HEADER_LENGTH        (40 + MAX_FIRMWARE_INFORMATION_SIZE)
+#define ENCRYPTION_MAX_OVERHEAD		128
+#define	USB_HWDESC_HEADER_LEN		sizeof(tx_desc_819x_usb)
+//#define TX_PACKET_SHIFT_BYTES 	  	(USB_HWDESC_HEADER_LEN + sizeof(tx_fwinfo_819x_usb))
+#define MAX_FRAGMENT_COUNT		8
+#ifdef RTL8192U
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+#define MAX_TRANSMIT_BUFFER_SIZE			32000
+#else
+#define MAX_TRANSMIT_BUFFER_SIZE			8000
+#endif
+#else
+#define MAX_TRANSMIT_BUFFER_SIZE  	(1600+(MAX_802_11_HEADER_LENGTH+ENCRYPTION_MAX_OVERHEAD)*MAX_FRAGMENT_COUNT)
+#endif
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+#define TX_PACKET_DRVAGGR_SUBFRAME_SHIFT_BYTES (sizeof(tx_desc_819x_usb_aggr_subframe) + sizeof(tx_fwinfo_819x_usb))
+#endif
+#define scrclng					4		// octets for crc32 (FCS, ICV)
+
+typedef enum rf_optype
+{
+	RF_OP_By_SW_3wire = 0,
+	RF_OP_By_FW,
+	RF_OP_MAX
+}rf_op_type;
+/* 8190 Loopback Mode definition */
+typedef enum _rtl819xUsb_loopback{
+	RTL819xU_NO_LOOPBACK = 0,
+	RTL819xU_MAC_LOOPBACK = 1,
+	RTL819xU_DMA_LOOPBACK = 2,
+	RTL819xU_CCK_LOOPBACK = 3,
+}rtl819xUsb_loopback_e;
+
+/* for rtl819x */
+typedef enum _RT_STATUS{
+	RT_STATUS_SUCCESS = 0,
+	RT_STATUS_FAILURE = 1,
+	RT_STATUS_PENDING = 2,
+	RT_STATUS_RESOURCE = 3
+}RT_STATUS,*PRT_STATUS;
+
+//#ifdef RTL8192SU
+typedef enum _RTL8192SUSB_LOOPBACK{
+	RTL8192SU_NO_LOOPBACK = 0,
+	RTL8192SU_MAC_LOOPBACK = 1,
+	RTL8192SU_DMA_LOOPBACK = 2,
+	RTL8192SU_CCK_LOOPBACK = 3,
+}RTL8192SUSB_LOOPBACK_E;
+//#endif
+
+
+#if 0
+/* due to rtl8192 firmware */
+typedef enum _desc_packet_type_e{
+	DESC_PACKET_TYPE_INIT = 0,
+	DESC_PACKET_TYPE_NORMAL = 1,
+}desc_packet_type_e;
+
+typedef enum _firmware_source{
+	FW_SOURCE_IMG_FILE = 0,
+	FW_SOURCE_HEADER_FILE = 1,		//from header file
+}firmware_source_e, *pfirmware_source_e;
+
+typedef enum _firmware_status{
+	FW_STATUS_0_INIT = 0,
+	FW_STATUS_1_MOVE_BOOT_CODE = 1,
+	FW_STATUS_2_MOVE_MAIN_CODE = 2,
+	FW_STATUS_3_TURNON_CPU = 3,
+	FW_STATUS_4_MOVE_DATA_CODE = 4,
+	FW_STATUS_5_READY = 5,
+}firmware_status_e;
+
+typedef struct _rt_firmare_seg_container {
+	u16	seg_size;
+	u8	*seg_ptr;
+}fw_seg_container, *pfw_seg_container;
+
+#ifdef RTL8192SU
+//--------------------------------------------------------------------------------
+// 8192S Firmware related
+//--------------------------------------------------------------------------------
+typedef  struct _RT_8192S_FIRMWARE_PRIV { //8-bytes alignment required
+
+	//--- LONG WORD 0 ----
+	u32		RegulatoryClass;
+	u32		Rfintfs;
+
+	//--- LONG WORD 1 ----
+	u32		ChipVer;
+	u32		HCISel;
+
+	//--- LONG WORD 2 ----
+	u32		IBKMode;
+	u32		Rsvd00;
+
+	//--- LONG WORD 3 ----
+	u32		Rsvd01;
+	u8		Qos_En;			// QoS enable
+	u8		En40MHz;		// 40MHz BW enable
+	u8		AMSDU2AMPDU_En;	//14181 convert AMSDU to AMPDU, 0: disable
+	u8		AMPDU_En;		//111n AMPDU/AMSDU enable
+
+	//--- LONG WORD 4 ----
+	u8		rate_control_offload;//FW offloads, 0: driver handles
+	u8		aggregation_offload;	// FW offloads, 0: driver handles
+	u8		beacon_offload;	//FW offloads, 0: driver handles
+	u8		MLME_offload;	// FW offloads, 0: driver handles
+	u8		hwpc_offload;	// FW offloads, 0: driver handles
+	u8		tcp_checksum_offload;	//FW offloads, 0: driver handles
+	u8		tcp_offload;			//FW offloads, 0: driver handles
+	u8		ps_control_offload;	//FW offloads, 0: driver handles
+
+	//--- LONG WORD 5 ----
+	u8		WWLAN_Offload;	// FW offloads, 0: driver handles
+	u8		MPMode;	// normal mode, 0: MP mode;
+	u16		Version;		//0x8000 ~ 0x8FFF for FPGA version, 0x0000 ~ 0x7FFF for ASIC version,
+	u16		Signature;	//0x12: 8712, 0x92: 8192S
+	u16		Rsvd11;
+
+//	u32		rsvd1;
+//	u32		wireless_band;	//no A-band exists in 8712
+}RT_8192S_FIRMWARE_PRIV, *PRT_8192S_FIRMWARE_PRIV;
+
+typedef struct _RT_8192S_FIRMWARE_HDR {//8-byte alinment required
+
+	//--- LONG WORD 0 ----
+	u16		Signature;
+	u16		Version;		  //0x8000 ~ 0x8FFF for FPGA version, 0x0000 ~ 0x7FFF for ASIC version,
+	u32		DMEMSize;    //define the size of boot loader
+
+
+	//--- LONG WORD 1 ----
+	u32		IMG_IMEM_SIZE;    //define the size of FW in IMEM
+	u32		IMG_SRAM_SIZE;    //define the size of FW in SRAM
+
+	//--- LONG WORD 2 ----
+	u32		FW_PRIV_SIZE;       //define the size of DMEM variable
+	u32		Rsvd0;
+
+	//--- LONG WORD 3 ----
+	u32		Rsvd1;
+	u32		Rsvd2;
+
+	RT_8192S_FIRMWARE_PRIV	FWPriv;
+
+}RT_8192S_FIRMWARE_HDR, *PRT_8192S_FIRMWARE_HDR;
+
+#define	RT_8192S_FIRMWARE_HDR_SIZE	80
+
+typedef enum _FIRMWARE_8192S_STATUS{
+	FW_STATUS_INIT = 0,
+	FW_STATUS_LOAD_IMEM = 1,
+	FW_STATUS_LOAD_EMEM = 2,
+	FW_STATUS_LOAD_DMEM = 3,
+	FW_STATUS_READY = 4,
+}FIRMWARE_8192S_STATUS;
+
+#define RTL8190_MAX_FIRMWARE_CODE_SIZE  64000   //64k
+
+typedef struct _rt_firmware{
+	firmware_source_e	eFWSource;
+	PRT_8192S_FIRMWARE_HDR		pFwHeader;
+	FIRMWARE_8192S_STATUS	FWStatus;
+	u8		FwIMEM[64000];
+	u8		FwEMEM[64000];
+	u32		FwIMEMLen;
+	u32		FwEMEMLen;
+	u8		szFwTmpBuffer[164000];
+	u16		CmdPacketFragThresold;
+	//firmware_status_e       firmware_status;//in 92u temp FIXLZM
+	//u16               cmdpacket_frag_thresold;//in 92u temp FIXLZM
+	//u8                firmware_buf[RTL8190_MAX_FIRMWARE_CODE_SIZE];//in 92u temp FIXLZM
+	//u16               firmware_buf_size;//in 92u temp FIXLZM
+
+}rt_firmware, *prt_firmware;
+#else
+typedef struct _rt_firmware{
+	firmware_status_e firmware_status;
+	u16               cmdpacket_frag_thresold;
+#define RTL8190_MAX_FIRMWARE_CODE_SIZE  64000   //64k
+#define MAX_FW_INIT_STEP                3
+	u8                firmware_buf[MAX_FW_INIT_STEP][RTL8190_MAX_FIRMWARE_CODE_SIZE];
+	u16               firmware_buf_size[MAX_FW_INIT_STEP];
+}rt_firmware, *prt_firmware;
+#endif
+typedef struct _rt_firmware_info_819xUsb{
+	u8		sz_info[16];
+}rt_firmware_info_819xUsb, *prt_firmware_info_819xUsb;
+#endif
+
+//+by amy 080507
+#define MAX_RECEIVE_BUFFER_SIZE	9100	// Add this to 9100 bytes to receive A-MSDU from RT-AP
+
+
+/* Firmware Queue Layout */
+#define NUM_OF_FIRMWARE_QUEUE		10
+#define NUM_OF_PAGES_IN_FW		0x100
+
+#ifdef USE_ONE_PIPE
+#define NUM_OF_PAGE_IN_FW_QUEUE_BE	0x000
+#define NUM_OF_PAGE_IN_FW_QUEUE_BK	0x000
+#define NUM_OF_PAGE_IN_FW_QUEUE_VI	0x0ff
+#define NUM_OF_PAGE_IN_FW_QUEUE_VO	0x000
+#define NUM_OF_PAGE_IN_FW_QUEUE_HCCA	0
+#define NUM_OF_PAGE_IN_FW_QUEUE_CMD	0x0
+#define NUM_OF_PAGE_IN_FW_QUEUE_MGNT	0x00
+#define NUM_OF_PAGE_IN_FW_QUEUE_HIGH	0
+#define NUM_OF_PAGE_IN_FW_QUEUE_BCN	0x0
+#define NUM_OF_PAGE_IN_FW_QUEUE_PUB	0x00
+#else
+
+#define NUM_OF_PAGE_IN_FW_QUEUE_BE	0x020
+#define NUM_OF_PAGE_IN_FW_QUEUE_BK	0x020
+#define NUM_OF_PAGE_IN_FW_QUEUE_VI	0x040
+#define NUM_OF_PAGE_IN_FW_QUEUE_VO	0x040
+#define NUM_OF_PAGE_IN_FW_QUEUE_HCCA	0
+#define NUM_OF_PAGE_IN_FW_QUEUE_CMD	0x4
+#define NUM_OF_PAGE_IN_FW_QUEUE_MGNT	0x20
+#define NUM_OF_PAGE_IN_FW_QUEUE_HIGH	0
+#define NUM_OF_PAGE_IN_FW_QUEUE_BCN	0x4
+#define NUM_OF_PAGE_IN_FW_QUEUE_PUB	0x18
+
+#endif
+
+#define APPLIED_RESERVED_QUEUE_IN_FW	0x80000000
+#define RSVD_FW_QUEUE_PAGE_BK_SHIFT	0x00
+#define RSVD_FW_QUEUE_PAGE_BE_SHIFT	0x08
+#define RSVD_FW_QUEUE_PAGE_VI_SHIFT	0x10
+#define RSVD_FW_QUEUE_PAGE_VO_SHIFT	0x18
+#define RSVD_FW_QUEUE_PAGE_MGNT_SHIFT	0x10
+#define RSVD_FW_QUEUE_PAGE_CMD_SHIFT	0x08
+#define RSVD_FW_QUEUE_PAGE_BCN_SHIFT	0x00
+#define RSVD_FW_QUEUE_PAGE_PUB_SHIFT	0x08
+//=================================================================
+//=================================================================
+
+#define EPROM_93c46 0
+#define EPROM_93c56 1
+
+#define DEFAULT_FRAG_THRESHOLD 2342U
+#define MIN_FRAG_THRESHOLD     256U
+#define DEFAULT_BEACONINTERVAL 0x64U
+#define DEFAULT_BEACON_ESSID "Rtl819xU"
+
+#define DEFAULT_SSID ""
+#define DEFAULT_RETRY_RTS 7
+#define DEFAULT_RETRY_DATA 7
+#define PRISM_HDR_SIZE 64
+
+#define		PHY_RSSI_SLID_WIN_MAX				100
+
+
+typedef enum _WIRELESS_MODE {
+	WIRELESS_MODE_UNKNOWN = 0x00,
+	WIRELESS_MODE_A = 0x01,
+	WIRELESS_MODE_B = 0x02,
+	WIRELESS_MODE_G = 0x04,
+	WIRELESS_MODE_AUTO = 0x08,
+	WIRELESS_MODE_N_24G = 0x10,
+	WIRELESS_MODE_N_5G = 0x20
+} WIRELESS_MODE;
+
+
+#define RTL_IOCTL_WPA_SUPPLICANT		SIOCIWFIRSTPRIV+30
+
+typedef struct buffer
+{
+	struct buffer *next;
+	u32 *buf;
+
+} buffer;
+
+typedef struct rtl_reg_debug{
+        unsigned int  cmd;
+        struct {
+                unsigned char type;
+                unsigned char addr;
+                unsigned char page;
+                unsigned char length;
+        } head;
+        unsigned char buf[0xff];
+}rtl_reg_debug;
+
+
+
+
+
+#if 0
+
+typedef struct tx_pendingbuf
+{
+	struct ieee80211_txb *txb;
+	short ispending;
+	short descfrag;
+} tx_pendigbuf;
+
+#endif
+
+typedef struct _rt_9x_tx_rate_history {
+	u32             cck[4];
+	u32             ofdm[8];
+	// HT_MCS[0][]: BW=0 SG=0
+	// HT_MCS[1][]: BW=1 SG=0
+	// HT_MCS[2][]: BW=0 SG=1
+	// HT_MCS[3][]: BW=1 SG=1
+	u32             ht_mcs[4][16];
+}rt_tx_rahis_t, *prt_tx_rahis_t;
+typedef struct _RT_SMOOTH_DATA_4RF {
+	char    elements[4][100];//array to store values
+	u32     index;                  //index to current array to store
+	u32     TotalNum;               //num of valid elements
+	u32     TotalVal[4];            //sum of valid elements
+}RT_SMOOTH_DATA_4RF, *PRT_SMOOTH_DATA_4RF;
+
+#define MAX_8192U_RX_SIZE			8192    // This maybe changed for D-cut larger aggregation size
+//stats seems messed up, clean it ASAP
+typedef struct Stats
+{
+	unsigned long txrdu;
+//	unsigned long rxrdu;
+	//unsigned long rxnolast;
+	//unsigned long rxnodata;
+//	unsigned long rxreset;
+//	unsigned long rxnopointer;
+	unsigned long rxok;
+	unsigned long rxframgment;
+	unsigned long rxcmdpkt[4];		//08/05/08 amy rx cmd element txfeedback/bcn report/cfg set/query
+	unsigned long rxurberr;
+	unsigned long rxstaterr;
+	unsigned long received_rate_histogram[4][32];	//0: Total, 1:OK, 2:CRC, 3:ICV, 2007 07 03 cosa
+	unsigned long received_preamble_GI[2][32];		//0: Long preamble/GI, 1:Short preamble/GI
+	unsigned long rx_AMPDUsize_histogram[5]; // level: (<4K), (4K~8K), (8K~16K), (16K~32K), (32K~64K)
+	unsigned long rx_AMPDUnum_histogram[5]; // level: (<5), (5~10), (10~20), (20~40), (>40)
+	unsigned long numpacket_matchbssid;	// debug use only.
+	unsigned long numpacket_toself;		// debug use only.
+	unsigned long num_process_phyinfo;		// debug use only.
+	unsigned long numqry_phystatus;
+	unsigned long numqry_phystatusCCK;
+	unsigned long numqry_phystatusHT;
+	unsigned long received_bwtype[5];              //0: 20M, 1: funn40M, 2: upper20M, 3: lower20M, 4: duplicate
+	unsigned long txnperr;
+	unsigned long txnpdrop;
+	unsigned long txresumed;
+//	unsigned long rxerr;
+//	unsigned long rxoverflow;
+//	unsigned long rxint;
+	unsigned long txnpokint;
+//	unsigned long txhpokint;
+//	unsigned long txhperr;
+//	unsigned long ints;
+//	unsigned long shints;
+	unsigned long txoverflow;
+//	unsigned long rxdmafail;
+//	unsigned long txbeacon;
+//	unsigned long txbeaconerr;
+	unsigned long txlpokint;
+	unsigned long txlpdrop;
+	unsigned long txlperr;
+	unsigned long txbeokint;
+	unsigned long txbedrop;
+	unsigned long txbeerr;
+	unsigned long txbkokint;
+	unsigned long txbkdrop;
+	unsigned long txbkerr;
+	unsigned long txviokint;
+	unsigned long txvidrop;
+	unsigned long txvierr;
+	unsigned long txvookint;
+	unsigned long txvodrop;
+	unsigned long txvoerr;
+	unsigned long txbeaconokint;
+	unsigned long txbeacondrop;
+	unsigned long txbeaconerr;
+	unsigned long txmanageokint;
+	unsigned long txmanagedrop;
+	unsigned long txmanageerr;
+	unsigned long txdatapkt;
+	unsigned long txfeedback;
+	unsigned long txfeedbackok;
+
+	unsigned long txoktotal;
+	unsigned long txokbytestotal;
+	unsigned long txokinperiod;
+	unsigned long txmulticast;
+	unsigned long txbytesmulticast;
+	unsigned long txbroadcast;
+	unsigned long txbytesbroadcast;
+	unsigned long txunicast;
+	unsigned long txbytesunicast;
+
+	unsigned long rxoktotal;
+	unsigned long rxbytesunicast;
+	unsigned long txfeedbackfail;
+	unsigned long txerrtotal;
+	unsigned long txerrbytestotal;
+	unsigned long txerrmulticast;
+	unsigned long txerrbroadcast;
+	unsigned long txerrunicast;
+	unsigned long txretrycount;
+	unsigned long txfeedbackretry;
+	u8	      last_packet_rate;
+	unsigned long slide_signal_strength[100];
+	unsigned long slide_evm[100];
+	unsigned long slide_rssi_total;	// For recording sliding window's RSSI value
+	unsigned long slide_evm_total;	// For recording sliding window's EVM value
+	long signal_strength; // Transformed, in dbm. Beautified signal strength for UI, not correct.
+	long signal_quality;
+	long last_signal_strength_inpercent;
+	long recv_signal_power;	// Correct smoothed ss in Dbm, only used in driver to report real power now.
+	u8 rx_rssi_percentage[4];
+	u8 rx_evm_percentage[2];
+	long rxSNRdB[4];
+	rt_tx_rahis_t txrate;
+	u32 Slide_Beacon_pwdb[100];     //cosa add for beacon rssi
+	u32 Slide_Beacon_Total;         //cosa add for beacon rssi
+	RT_SMOOTH_DATA_4RF              cck_adc_pwdb;
+
+	u32	CurrentShowTxate;
+} Stats;
+
+
+// Bandwidth Offset
+#define HAL_PRIME_CHNL_OFFSET_DONT_CARE		0
+#define HAL_PRIME_CHNL_OFFSET_LOWER			1
+#define HAL_PRIME_CHNL_OFFSET_UPPER			2
+
+//+by amy 080507
+
+typedef struct 	ChnlAccessSetting {
+	u16 SIFS_Timer;
+	u16 DIFS_Timer;
+	u16 SlotTimeTimer;
+	u16 EIFS_Timer;
+	u16 CWminIndex;
+	u16 CWmaxIndex;
+}*PCHANNEL_ACCESS_SETTING,CHANNEL_ACCESS_SETTING;
+
+typedef struct _BB_REGISTER_DEFINITION{
+	u32 rfintfs; 			// set software control: //		0x870~0x877[8 bytes]
+	u32 rfintfi; 			// readback data: //		0x8e0~0x8e7[8 bytes]
+	u32 rfintfo; 			// output data: //		0x860~0x86f [16 bytes]
+	u32 rfintfe; 			// output enable: //		0x860~0x86f [16 bytes]
+	u32 rf3wireOffset; 		// LSSI data: //		0x840~0x84f [16 bytes]
+	u32 rfLSSI_Select; 		// BB Band Select: //		0x878~0x87f [8 bytes]
+	u32 rfTxGainStage;		// Tx gain stage: //		0x80c~0x80f [4 bytes]
+	u32 rfHSSIPara1; 		// wire parameter control1 : //		0x820~0x823,0x828~0x82b, 0x830~0x833, 0x838~0x83b [16 bytes]
+	u32 rfHSSIPara2; 		// wire parameter control2 : //		0x824~0x827,0x82c~0x82f, 0x834~0x837, 0x83c~0x83f [16 bytes]
+	u32 rfSwitchControl; 	//Tx Rx antenna control : //		0x858~0x85f [16 bytes]
+	u32 rfAGCControl1; 	//AGC parameter control1 : //		0xc50~0xc53,0xc58~0xc5b, 0xc60~0xc63, 0xc68~0xc6b [16 bytes]
+	u32 rfAGCControl2; 	//AGC parameter control2 : //		0xc54~0xc57,0xc5c~0xc5f, 0xc64~0xc67, 0xc6c~0xc6f [16 bytes]
+	u32 rfRxIQImbalance; 	//OFDM Rx IQ imbalance matrix : //		0xc14~0xc17,0xc1c~0xc1f, 0xc24~0xc27, 0xc2c~0xc2f [16 bytes]
+	u32 rfRxAFE;  			//Rx IQ DC ofset and Rx digital filter, Rx DC notch filter : //		0xc10~0xc13,0xc18~0xc1b, 0xc20~0xc23, 0xc28~0xc2b [16 bytes]
+	u32 rfTxIQImbalance; 	//OFDM Tx IQ imbalance matrix //		0xc80~0xc83,0xc88~0xc8b, 0xc90~0xc93, 0xc98~0xc9b [16 bytes]
+	u32 rfTxAFE; 			//Tx IQ DC Offset and Tx DFIR type //		0xc84~0xc87,0xc8c~0xc8f, 0xc94~0xc97, 0xc9c~0xc9f [16 bytes]
+	u32 rfLSSIReadBack; 	//LSSI RF readback data //		0x8a0~0x8af [16 bytes]
+	u32 rfLSSIReadBackPi; 	//LSSI RF readback data PI mode 0x8b8-8bc for Path A and B
+}BB_REGISTER_DEFINITION_T, *PBB_REGISTER_DEFINITION_T;
+
+typedef enum _RT_RF_TYPE_819xU{
+        RF_TYPE_MIN = 0,
+        RF_8225,
+        RF_8256,
+        RF_8258,
+	RF_6052=4,		// 4 11b/g/n RF
+        RF_PSEUDO_11N = 5,
+}RT_RF_TYPE_819xU, *PRT_RF_TYPE_819xU;
+
+//#ifdef RTL8192SU
+typedef enum _RF_POWER_STATE{
+	RF_ON,
+	RF_SLEEP,
+	RF_OFF,
+	RF_SHUT_DOWN,
+}RF_POWER_STATE, *PRF_POWER_STATE;
+//#endif
+
+typedef struct _rate_adaptive
+{
+	u8				rate_adaptive_disabled;
+	u8				ratr_state;
+	u16				reserve;
+
+	u32				high_rssi_thresh_for_ra;
+	u32				high2low_rssi_thresh_for_ra;
+	u8				low2high_rssi_thresh_for_ra40M;
+	u32				low_rssi_thresh_for_ra40M;
+	u8				low2high_rssi_thresh_for_ra20M;
+	u32				low_rssi_thresh_for_ra20M;
+	u32				upper_rssi_threshold_ratr;
+	u32				middle_rssi_threshold_ratr;
+	u32				low_rssi_threshold_ratr;
+	u32				low_rssi_threshold_ratr_40M;
+	u32				low_rssi_threshold_ratr_20M;
+	u8				ping_rssi_enable;	//cosa add for test
+	u32				ping_rssi_ratr;	//cosa add for test
+	u32				ping_rssi_thresh_for_ra;//cosa add for test
+	u32				last_ratr;
+
+} rate_adaptive, *prate_adaptive;
+
+#define TxBBGainTableLength 37
+#define	CCKTxBBGainTableLength 23
+
+typedef struct _txbbgain_struct
+{
+	long	txbb_iq_amplifygain;
+	u32	txbbgain_value;
+} txbbgain_struct, *ptxbbgain_struct;
+
+typedef struct _ccktxbbgain_struct
+{
+	//The Value is from a22 to a29 one Byte one time is much Safer
+	u8	ccktxbb_valuearray[8];
+} ccktxbbgain_struct,*pccktxbbgain_struct;
+
+
+typedef struct _init_gain
+{
+	u8				xaagccore1;
+	u8				xbagccore1;
+	u8				xcagccore1;
+	u8				xdagccore1;
+	u8				cca;
+
+} init_gain, *pinit_gain;
+//by amy 0606
+
+typedef struct _phy_ofdm_rx_status_report_819xusb
+{
+	u8	trsw_gain_X[4];
+	u8	pwdb_all;
+	u8	cfosho_X[4];
+	u8	cfotail_X[4];
+	u8	rxevm_X[2];
+	u8	rxsnr_X[4];
+	u8	pdsnr_X[2];
+	u8	csi_current_X[2];
+	u8	csi_target_X[2];
+	u8	sigevm;
+	u8	max_ex_pwr;
+	u8	sgi_en;
+	u8  rxsc_sgien_exflg;
+}phy_sts_ofdm_819xusb_t;
+
+typedef struct _phy_cck_rx_status_report_819xusb
+{
+	/* For CCK rate descriptor. This is a unsigned 8:1 variable. LSB bit presend
+	   0.5. And MSB 7 bts presend a signed value. Range from -64~+63.5. */
+	u8	adc_pwdb_X[4];
+	u8	sq_rpt;
+	u8	cck_agc_rpt;
+}phy_sts_cck_819xusb_t;
+
+
+typedef struct _phy_ofdm_rx_status_rxsc_sgien_exintfflag{
+	u8			reserved:4;
+	u8			rxsc:2;
+	u8			sgi_en:1;
+	u8			ex_intf_flag:1;
+}phy_ofdm_rx_status_rxsc_sgien_exintfflag;
+
+typedef enum _RT_CUSTOMER_ID
+{
+	RT_CID_DEFAULT = 0,
+	RT_CID_8187_ALPHA0 = 1,
+	RT_CID_8187_SERCOMM_PS = 2,
+	RT_CID_8187_HW_LED = 3,
+	RT_CID_8187_NETGEAR = 4,
+	RT_CID_WHQL = 5,
+	RT_CID_819x_CAMEO  = 6,
+	RT_CID_819x_RUNTOP = 7,
+	RT_CID_819x_Senao = 8,
+	RT_CID_TOSHIBA = 9,	// Merge by Jacken, 2008/01/31.
+	RT_CID_819x_Netcore = 10,
+	RT_CID_Nettronix = 11,
+	RT_CID_DLINK = 12,
+	RT_CID_PRONET = 13,
+}RT_CUSTOMER_ID, *PRT_CUSTOMER_ID;
+
+//================================================================================
+// LED customization.
+//================================================================================
+
+typedef	enum _LED_STRATEGY_8190{
+	SW_LED_MODE0, // SW control 1 LED via GPIO0. It is default option.
+	SW_LED_MODE1, // SW control for PCI Express
+	SW_LED_MODE2, // SW control for Cameo.
+	SW_LED_MODE3, // SW contorl for RunTop.
+	SW_LED_MODE4, // SW control for Netcore
+	HW_LED, // HW control 2 LEDs, LED0 and LED1 (there are 4 different control modes)
+}LED_STRATEGY_8190, *PLED_STRATEGY_8190;
+
+typedef enum _RESET_TYPE {
+	RESET_TYPE_NORESET = 0x00,
+	RESET_TYPE_NORMAL = 0x01,
+	RESET_TYPE_SILENT = 0x02
+} RESET_TYPE;
+
+/* The simple tx command OP code. */
+typedef enum _tag_TxCmd_Config_Index{
+	TXCMD_TXRA_HISTORY_CTRL				= 0xFF900000,
+	TXCMD_RESET_TX_PKT_BUFF				= 0xFF900001,
+	TXCMD_RESET_RX_PKT_BUFF				= 0xFF900002,
+	TXCMD_SET_TX_DURATION				= 0xFF900003,
+	TXCMD_SET_RX_RSSI						= 0xFF900004,
+	TXCMD_SET_TX_PWR_TRACKING			= 0xFF900005,
+	TXCMD_XXXX_CTRL,
+}DCMD_TXCMD_OP;
+
+typedef enum{
+	NIC_8192U = 1,
+	NIC_8190P = 2,
+	NIC_8192E = 3,
+	NIC_8192SE = 4,
+	NIC_8192SU = 5,
+	} nic_t;
+
+//definded by WB. Ready to fill handlers for different NIC types.
+//add handle here when necessary.
+struct rtl819x_ops{
+	nic_t nic_type;
+	void (* rtl819x_read_eeprom_info)(struct net_device *dev);
+	short (* rtl819x_tx)(struct net_device *dev, struct sk_buff* skb);
+	short (* rtl819x_tx_cmd)(struct net_device *dev, struct sk_buff *skb);
+	void (* rtl819x_rx_nomal)(struct sk_buff* skb);
+	void (* rtl819x_rx_cmd)(struct sk_buff *skb);
+	bool (*	rtl819x_adapter_start)(struct net_device *dev);
+	void (* rtl819x_link_change)(struct net_device *dev);
+	void (*	rtl819x_initial_gain)(struct net_device *dev,u8 Operation);
+	void (*	rtl819x_query_rxdesc_status)(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe);
+};
+
+typedef struct r8192_priv
+{
+	struct rtl819x_ops* ops;
+	struct usb_device *udev;
+	//added for maintain info from eeprom
+	short epromtype;
+	u16 eeprom_vid;
+	u16 eeprom_pid;
+	u8  eeprom_CustomerID;
+	u8  eeprom_SubCustomerID;
+	u8  eeprom_ChannelPlan;
+	RT_CUSTOMER_ID CustomerID;
+	LED_STRATEGY_8190	LedStrategy;
+	u8  txqueue_to_outpipemap[9];
+	u8  RtOutPipes[16];
+	u8  RtInPipes[16];
+	u8  ep_in_num;
+	u8  ep_out_num;
+	u8  ep_num;
+	int irq;
+	struct ieee80211_device *ieee80211;
+
+	short card_8192; /* O: rtl8192, 1:rtl8185 V B/C, 2:rtl8185 V D */
+	u8 card_8192_version; /* if TCR reports card V B/C this discriminates */
+//	short phy_ver; /* meaningful for rtl8225 1:A 2:B 3:C */
+	short enable_gpio0;
+	enum card_type {PCI,MINIPCI,CARDBUS,USB}card_type;
+	short hw_plcp_len;
+	short plcp_preamble_mode;
+
+	spinlock_t irq_lock;
+//	spinlock_t irq_th_lock;
+	spinlock_t tx_lock;
+	spinlock_t ps_lock;
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16))
+	struct semaphore mutex;
+#else
+        struct mutex mutex;
+#endif
+	spinlock_t rf_lock; //used to lock rf write operation added by wb
+
+	u16 irq_mask;
+//	short irq_enabled;
+//	struct net_device *dev; //comment this out.
+	short chan;
+	short sens;
+	short max_sens;
+
+
+	//	u8 chtxpwr[15]; //channels from 1 to 14, 0 not used
+//	u8 chtxpwr_ofdm[15]; //channels from 1 to 14, 0 not used
+//	u8 cck_txpwr_base;
+//	u8 ofdm_txpwr_base;
+//	u8 challow[15]; //channels from 1 to 14, 0 not used
+	short up;
+	short crcmon; //if 1 allow bad crc frame reception in monitor mode
+//	short prism_hdr;
+
+//	struct timer_list scan_timer;
+	/*short scanpending;
+	short stopscan;*/
+//	spinlock_t scan_lock;
+//	u8 active_probe;
+	//u8 active_scan_num;
+	struct semaphore wx_sem;
+	struct semaphore rf_sem; //used to lock rf write operation added by wb, modified by david
+//	short hw_wep;
+
+//	short digphy;
+//	short antb;
+//	short diversity;
+//	u8 cs_treshold;
+//	short rcr_csense;
+	u8 rf_type; //0 means 1T2R, 1 means 2T4R
+	RT_RF_TYPE_819xU rf_chip;
+
+//	u32 key0[4];
+	short (*rf_set_sens)(struct net_device *dev,short sens);
+	u8 (*rf_set_chan)(struct net_device *dev,u8 ch);
+	void (*rf_close)(struct net_device *dev);
+	void (*rf_init)(struct net_device *dev);
+	//short rate;
+	short promisc;
+	/*stats*/
+	struct Stats stats;
+	struct iw_statistics wstats;
+	struct proc_dir_entry *dir_dev;
+
+	/*RX stuff*/
+//	u32 *rxring;
+//	u32 *rxringtail;
+//	dma_addr_t rxringdma;
+	struct urb **rx_urb;
+	struct urb **rx_cmd_urb;
+
+/* modified by davad for Rx process */
+       struct sk_buff_head rx_queue;
+       struct sk_buff_head skb_queue;
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+	struct tq_struct qos_activate;
+#else
+       struct work_struct qos_activate;
+#endif
+	short  tx_urb_index;
+	atomic_t tx_pending[0x10];//UART_PRIORITY+1
+
+
+	struct tasklet_struct irq_rx_tasklet;
+	struct urb *rxurb_task;
+
+	//2 Tx Related variables
+	u16	ShortRetryLimit;
+	u16	LongRetryLimit;
+	u32	TransmitConfig;
+	u8	RegCWinMin;		// For turbo mode CW adaptive. Added by Annie, 2005-10-27.
+
+	u32     LastRxDescTSFHigh;
+	u32     LastRxDescTSFLow;
+
+
+	//2 Rx Related variables
+	u16	EarlyRxThreshold;
+	u32	ReceiveConfig;
+	u8	AcmControl;
+
+	u8	RFProgType;
+
+	u8 retry_data;
+	u8 retry_rts;
+	u16 rts;
+
+	struct 	ChnlAccessSetting  ChannelAccessSetting;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	struct work_struct reset_wq;
+#else
+	struct tq_struct reset_wq;
+#endif
+
+/**********************************************************/
+	//for rtl819xUsb
+	u16     basic_rate;
+	u8      short_preamble;
+	u8      slot_time;
+	bool 	bDcut;
+	bool bCurrentRxAggrEnable;
+	u8 Rf_Mode; //add for Firmware RF -R/W switch
+	prt_firmware		pFirmware;
+	rtl819xUsb_loopback_e	LoopbackMode;
+	firmware_source_e	firmware_source;
+	bool usb_error;
+
+	u16 EEPROMTxPowerDiff;
+	u8 EEPROMThermalMeter;
+	u8 EEPROMPwDiff;
+	u8 EEPROMCrystalCap;
+	u8 EEPROM_Def_Ver;
+	u8 EEPROMTxPowerLevelCCK;// CCK channel 1~14
+	u8 EEPROMTxPowerLevelCCK_V1[3];
+	u8 EEPROMTxPowerLevelOFDM24G[3]; // OFDM 2.4G channel 1~14
+	u8 EEPROMTxPowerLevelOFDM5G[24];	// OFDM 5G
+
+//RTL8192SU
+	bool	bDmDisableProtect;
+	bool	bIgnoreDiffRateTxPowerOffset;
+
+#ifdef EEPROM_OLD_FORMAT_SUPPORT
+	u8  EEPROMTxPowerLevelCCK24G[14];		// CCK 2.4G channel 1~14
+	//u8  EEPROMTxPowerLevelOFDM24G[14];	// OFDM 2.4G channel 1~14
+	//u8  EEPROMTxPowerLevelOFDM5G[24];	// OFDM 5G
+#else
+	// For EEPROM TX Power Index like 8190 series
+	u8  EEPROMRfACCKChnl1TxPwLevel[3];	//RF-A CCK Tx Power Level at channel 7
+	u8  EEPROMRfAOfdmChnlTxPwLevel[3];//RF-A CCK Tx Power Level at [0],[1],[2] = channel 1,7,13
+	u8  EEPROMRfCCCKChnl1TxPwLevel[3];	//RF-C CCK Tx Power Level at channel 7
+	u8  EEPROMRfCOfdmChnlTxPwLevel[3];//RF-C CCK Tx Power Level at [0],[1],[2] = channel 1,7,13
+
+	// F92S new definition
+	//RF-A&B CCK/OFDM Tx Power Level at three channel are [1-3] [4-9] [10-14]
+	u8  RfCckChnlAreaTxPwr[2][3];
+	u8  RfOfdmChnlAreaTxPwr1T[2][3];
+	u8  RfOfdmChnlAreaTxPwr2T[2][3];
+#endif
+
+	// Add For EEPROM Efuse switch and  Efuse Shadow map Setting
+	bool		EepromOrEfuse;
+	bool		bBootFromEfuse;	// system boot form EFUSE
+	u8  		EfuseMap[2][HWSET_MAX_SIZE_92S];
+
+	u8  		EEPROMUsbOption;
+	u8  		EEPROMUsbPhyParam[5];
+	u8  		EEPROMTxPwrBase;
+	u8  		EEPROMBoardType;
+	bool		bBootFromEEPROM;   // system boot from EEPROM
+	u8  		EEPROMTSSI_A;
+	u8  		EEPROMTSSI_B;
+	u8  		EEPROMHT2T_TxPwr[6];			// For channel 1, 7 and 13 on path A/B.
+	u8  		EEPROMTxPwrTkMode;
+
+	u8  		bTXPowerDataReadFromEEPORM;
+
+	u8		EEPROMVersion;
+	u8		EEPROMUsbEndPointNumber;
+
+	bool		AutoloadFailFlag;
+	u8	RfTxPwrLevelCck[2][14];
+	u8	RfTxPwrLevelOfdm1T[2][14];
+	u8	RfTxPwrLevelOfdm2T[2][14];
+	// 2009/01/20 MH Add for new EEPROM format.
+	u8					TxPwrHt20Diff[2][14];				// HT 20<->40 Pwr diff
+	u8					TxPwrLegacyHtDiff[2][14];		// For HT<->legacy pwr diff
+	u8					TxPwrbandEdgeHt40[2][2];		// Band edge for HY 40MHZlow/up channel
+	u8					TxPwrbandEdgeHt20[2][2];		// Band edge for HY 40MHZ low/up channel
+	u8					TxPwrbandEdgeLegacyOfdm[2][2];	// Band edge for legacy ofdm low/up channel
+	u8					TxPwrbandEdgeFlag;				// Band edge enable flag
+
+	// L1 and L2 high power threshold.
+	u8 				MidHighPwrTHR_L1;
+	u8 				MidHighPwrTHR_L2;
+	u8				TxPwrSafetyFlag;				// for Tx power safety spec
+//RTL8192SU
+
+/*PHY related*/
+	BB_REGISTER_DEFINITION_T	PHYRegDef[4];	//Radio A/B/C/D
+	// Read/write are allow for following hardware information variables
+#ifdef RTL8192SU
+	u32	MCSTxPowerLevelOriginalOffset[7];//FIXLZM
+#else
+	u32	MCSTxPowerLevelOriginalOffset[6];
+#endif
+	u32	CCKTxPowerLevelOriginalOffset;
+	u8	TxPowerLevelCCK[14];			// CCK channel 1~14
+	u8	TxPowerLevelOFDM24G[14];		// OFDM 2.4G channel 1~14
+	u8	TxPowerLevelOFDM5G[14];			// OFDM 5G
+	u32	Pwr_Track;
+	u8	TxPowerDiff;
+	u8	AntennaTxPwDiff[2];				// Antenna gain offset, index 0 for B, 1 for C, and 2 for D
+	u8	CrystalCap;						// CrystalCap.
+	u8	ThermalMeter[2];				// ThermalMeter, index 0 for RFIC0, and 1 for RFIC1
+
+	u8	CckPwEnl;
+	// Use to calculate PWBD.
+	u8	bCckHighPower;
+	long	undecorated_smoothed_pwdb;
+
+	//for set channel
+	u8	SwChnlInProgress;
+	u8 	SwChnlStage;
+	u8	SwChnlStep;
+	u8	SetBWModeInProgress;
+	HT_CHANNEL_WIDTH		CurrentChannelBW;
+	u8      ChannelPlan;
+	u8      pwrGroupCnt;
+	// 8190 40MHz mode
+	//
+	u8	nCur40MhzPrimeSC;	// Control channel sub-carrier
+	// Joseph test for shorten RF configuration time.
+	// We save RF reg0 in this variable to reduce RF reading.
+	//
+	u32					RfReg0Value[4];
+	u8 					NumTotalRFPath;
+	bool 				brfpath_rxenable[4];
+	//RF set related
+	bool				SetRFPowerStateInProgress;
+//+by amy 080507
+	struct timer_list watch_dog_timer;
+
+//+by amy 080515 for dynamic mechenism
+	//Add by amy Tx Power Control for Near/Far Range 2008/05/15
+	bool	bdynamic_txpower;  //bDynamicTxPower
+	bool	bDynamicTxHighPower;  // Tx high power state
+	bool	bDynamicTxLowPower;  // Tx low power state
+	bool	bLastDTPFlag_High;
+	bool	bLastDTPFlag_Low;
+
+	bool	bstore_last_dtpflag;
+	bool	bstart_txctrl_bydtp;   //Define to discriminate on High power State or on sitesuvey to change Tx gain index
+	//Add by amy for Rate Adaptive
+	rate_adaptive rate_adaptive;
+	//Add by amy for TX power tracking
+	//2008/05/15  Mars OPEN/CLOSE TX POWER TRACKING
+       txbbgain_struct txbbgain_table[TxBBGainTableLength];
+       u8	EEPROMTxPowerTrackEnable;
+	u8			   txpower_count;//For 6 sec do tracking again
+	bool			   btxpower_trackingInit;
+	u8			   OFDM_index;
+	u8			   CCK_index;
+	//2007/09/10 Mars Add CCK TX Power Tracking
+	ccktxbbgain_struct	cck_txbbgain_table[CCKTxBBGainTableLength];
+	ccktxbbgain_struct	cck_txbbgain_ch14_table[CCKTxBBGainTableLength];
+	u8 rfa_txpowertrackingindex;
+	u8 rfa_txpowertrackingindex_real;
+	u8 rfa_txpowertracking_default;
+	u8 rfc_txpowertrackingindex;
+	u8 rfc_txpowertrackingindex_real;
+
+	s8 cck_present_attentuation;
+	u8 cck_present_attentuation_20Mdefault;
+	u8 cck_present_attentuation_40Mdefault;
+	char cck_present_attentuation_difference;
+	bool btxpower_tracking;
+	bool bcck_in_ch14;
+	bool btxpowerdata_readfromEEPORM;
+	u16 	TSSI_13dBm;
+	//For Backup Initial Gain
+	init_gain initgain_backup;
+	u8 DefaultInitialGain[4];
+	// For EDCA Turbo mode, Added by amy 080515.
+	bool		bis_any_nonbepkts;
+	bool		bcurrent_turbo_EDCA;
+	bool		bis_cur_rdlstate;
+	struct timer_list fsync_timer;
+	bool bfsync_processing;	// 500ms Fsync timer is active or not
+	u32 	rate_record;
+	u32 	rateCountDiffRecord;
+	u32	ContiuneDiffCount;
+	bool bswitch_fsync;
+
+	u8	framesync;
+	u32 	framesyncC34;
+	u8   	framesyncMonitor;
+        	//Added by amy 080516  for RX related
+	u16 	nrxAMPDU_size;
+	u8 	nrxAMPDU_aggr_num;
+
+	//by amy for gpio
+	 bool bHwRadioOff;
+
+	//by amy for reset_count
+	u32 reset_count;
+	bool bpbc_pressed;
+	//by amy for debug
+	u32 txpower_checkcnt;
+	u32 txpower_tracking_callback_cnt;
+	u8 thermal_read_val[40];
+	u8 thermal_readback_index;
+	u32 ccktxpower_adjustcnt_not_ch14;
+	u32 ccktxpower_adjustcnt_ch14;
+	u8 tx_fwinfo_force_subcarriermode;
+	u8 tx_fwinfo_force_subcarrierval;
+	//by amy for silent reset
+	RESET_TYPE	ResetProgress;
+	bool		bForcedSilentReset;
+	bool		bDisableNormalResetCheck;
+	u16		TxCounter;
+	u16		RxCounter;
+	int		IrpPendingCount;
+	bool		bResetInProgress;
+	bool		force_reset;
+	u8		InitialGainOperateType;
+
+	u16		SifsTime;
+
+	//define work item by amy 080526
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+	struct delayed_work update_beacon_wq;
+	struct delayed_work watch_dog_wq;
+	struct delayed_work txpower_tracking_wq;
+	struct delayed_work rfpath_check_wq;
+	struct delayed_work gpio_change_rf_wq;
+	struct delayed_work initialgain_operate_wq;
+#else
+	struct work_struct update_beacon_wq;
+	struct work_struct watch_dog_wq;
+	struct work_struct txpower_tracking_wq;
+	struct work_struct rfpath_check_wq;
+	struct work_struct gpio_change_rf_wq;
+	struct work_struct initialgain_operate_wq;
+#endif
+	struct workqueue_struct *priv_wq;
+#else
+	/* used for periodly scan */
+	struct tq_struct update_beacon_wq;
+	struct tq_struct txpower_tracking_wq;
+	struct tq_struct rfpath_check_wq;
+	struct tq_struct watch_dog_wq;
+	struct tq_struct gpio_change_rf_wq;
+	struct tq_struct initialgain_operate_wq;
+#endif
+//#ifdef RTL8192SU
+	//lzm add for 8192S
+	 u32 			IntrMask;
+	// RF and BB access related synchronization flags.
+	bool				bChangeBBInProgress; // BaseBand RW is still in progress.
+	bool				bChangeRFInProgress; // RF RW is still in progress.
+
+	u32				CCKTxPowerAdjustCntCh14;		//debug only
+	u32				CCKTxPowerAdjustCntNotCh14;	//debug only
+	u32				TXPowerTrackingCallbackCnt;		//debug only
+	u32				TxPowerCheckCnt;				//debug only
+	u32				RFWritePageCnt[3];				//debug only
+	u32				RFReadPageCnt[3];				//debug only
+	u8				ThermalReadBackIndex;			//debug only
+	u8				ThermalReadVal[40];				//debug only
+
+	// For HCT test, 2005.07.15, by rcnjko.
+	// not realize true, just define it, set it 0 default, because some func use it
+	bool				bInHctTest;
+
+	// The current Tx Power Level
+	u8				CurrentCckTxPwrIdx;
+	u8				CurrentOfdm24GTxPwrIdx;
+
+	// For pass 92S common phycfg.c compiler
+	u8					TxPowerLevelCCK_A[14];			// RF-A, CCK channel 1~14
+	u8					TxPowerLevelOFDM24G_A[14];	// RF-A, OFDM 2.4G channel 1~14
+	u8					TxPowerLevelCCK_C[14];			// RF-C, CCK channel 1~14
+	u8					TxPowerLevelOFDM24G_C[14];	// RF-C, OFDM 2.4G channel 1~14
+	u8					LegacyHTTxPowerDiff;			// Legacy to HT rate power diff
+	char					RF_C_TxPwDiff;					// Antenna gain offset, rf-c to rf-a
+
+	bool	bRFSiOrPi;//0=si, 1=pi.
+	//lzm add for 8192S
+
+	bool SetFwCmdInProgress; //is set FW CMD in Progress? 92S only
+	u8 CurrentFwCmdIO;
+
+	u8 MinSpaceCfg;
+
+	u16 rf_pathmap;
+//#endif
+
+
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	bool		bCurrentRxAggrEnable;
+	bool		bForcedUsbRxAggr;
+	u32		ForcedUsbRxAggrInfo;
+	u32		LastUsbRxAggrInfoSetting;
+	u32		RegUsbRxAggrInfo;
+#endif
+
+
+
+}r8192_priv;
+
+// for rtl8187
+// now mirging to rtl8187B
+/*
+typedef enum{
+	LOW_PRIORITY = 0x02,
+	NORM_PRIORITY
+	} priority_t;
+*/
+//for rtl8187B
+typedef enum{
+	BULK_PRIORITY = 0x01,
+	//RSVD0,
+	//RSVD1,
+	LOW_PRIORITY,
+	NORM_PRIORITY,
+	VO_PRIORITY,
+	VI_PRIORITY, //0x05
+	BE_PRIORITY,
+	BK_PRIORITY,
+	RSVD2,
+	RSVD3,
+	BEACON_PRIORITY, //0x0A
+	HIGH_PRIORITY,
+	MANAGE_PRIORITY,
+	RSVD4,
+	RSVD5,
+	UART_PRIORITY //0x0F
+} priority_t;
+
+#if 0
+typedef enum{
+	NIC_8192U = 1,
+	NIC_8190P = 2,
+	NIC_8192E = 3,
+	NIC_8192SE = 4,
+	NIC_8192SU = 5,
+	} nic_t;
+#endif
+
+#if 0 //defined in Qos.h
+//typedef u32 AC_CODING;
+#define AC0_BE	0		// ACI: 0x00	// Best Effort
+#define AC1_BK	1		// ACI: 0x01	// Background
+#define AC2_VI	2		// ACI: 0x10	// Video
+#define AC3_VO	3		// ACI: 0x11	// Voice
+#define AC_MAX	4		// Max: define total number; Should not to be used as a real enum.
+
+//
+// ECWmin/ECWmax field.
+// Ref: WMM spec 2.2.2: WME Parameter Element, p.13.
+//
+typedef	union _ECW{
+	u8	charData;
+	struct
+	{
+		u8	ECWmin:4;
+		u8	ECWmax:4;
+	}f;	// Field
+}ECW, *PECW;
+
+//
+// ACI/AIFSN Field.
+// Ref: WMM spec 2.2.2: WME Parameter Element, p.12.
+//
+typedef	union _ACI_AIFSN{
+	u8	charData;
+
+	struct
+	{
+		u8	AIFSN:4;
+		u8	ACM:1;
+		u8	ACI:2;
+		u8	Reserved:1;
+	}f;	// Field
+}ACI_AIFSN, *PACI_AIFSN;
+
+//
+// AC Parameters Record Format.
+// Ref: WMM spec 2.2.2: WME Parameter Element, p.12.
+//
+typedef	union _AC_PARAM{
+	u32	longData;
+	u8	charData[4];
+
+	struct
+	{
+		ACI_AIFSN	AciAifsn;
+		ECW		Ecw;
+		u16		TXOPLimit;
+	}f;	// Field
+}AC_PARAM, *PAC_PARAM;
+
+#endif
+#ifdef JOHN_HWSEC
+struct ssid_thread {
+	struct net_device *dev;
+       	u8 name[IW_ESSID_MAX_SIZE + 1];
+};
+#endif
+
+#ifdef RTL8192SU
+short rtl8192SU_tx_cmd(struct net_device *dev, struct sk_buff *skb);
+short rtl8192SU_tx(struct net_device *dev, struct sk_buff* skb);
+bool FirmwareDownload92S(struct net_device *dev);
+#else
+short rtl8192_tx(struct net_device *dev, struct sk_buff* skb);
+bool init_firmware(struct net_device *dev);
+#endif
+
+short rtl819xU_tx_cmd(struct net_device *dev, struct sk_buff *skb);
+short rtl8192_tx(struct net_device *dev, struct sk_buff* skb);
+
+u32 read_cam(struct net_device *dev, u8 addr);
+void write_cam(struct net_device *dev, u8 addr, u32 data);
+
+u8 read_nic_byte(struct net_device *dev, int x);
+u8 read_nic_byte_E(struct net_device *dev, int x);
+u32 read_nic_dword(struct net_device *dev, int x);
+u16 read_nic_word(struct net_device *dev, int x) ;
+void write_nic_byte(struct net_device *dev, int x,u8 y);
+void write_nic_byte_E(struct net_device *dev, int x,u8 y);
+void write_nic_word(struct net_device *dev, int x,u16 y);
+void write_nic_dword(struct net_device *dev, int x,u32 y);
+void force_pci_posting(struct net_device *dev);
+
+void rtl8192_rtx_disable(struct net_device *);
+void rtl8192_rx_enable(struct net_device *);
+void rtl8192_tx_enable(struct net_device *);
+
+void rtl8192_disassociate(struct net_device *dev);
+//void fix_rx_fifo(struct net_device *dev);
+void rtl8185_set_rf_pins_enable(struct net_device *dev,u32 a);
+
+void rtl8192_set_anaparam(struct net_device *dev,u32 a);
+void rtl8185_set_anaparam2(struct net_device *dev,u32 a);
+void rtl8192_update_msr(struct net_device *dev);
+int rtl8192_down(struct net_device *dev);
+int rtl8192_up(struct net_device *dev);
+void rtl8192_commit(struct net_device *dev);
+void rtl8192_set_chan(struct net_device *dev,short ch);
+void write_phy(struct net_device *dev, u8 adr, u8 data);
+void write_phy_cck(struct net_device *dev, u8 adr, u32 data);
+void write_phy_ofdm(struct net_device *dev, u8 adr, u32 data);
+void rtl8185_tx_antenna(struct net_device *dev, u8 ant);
+void rtl8192_set_rxconf(struct net_device *dev);
+//short check_nic_enough_desc(struct net_device *dev, priority_t priority);
+extern void rtl819xusb_beacon_tx(struct net_device *dev,u16  tx_rate);
+void CamResetAllEntry(struct net_device* dev);
+void EnableHWSecurityConfig8192(struct net_device *dev);
+void setKey(struct net_device *dev, u8 EntryNo, u8 KeyIndex, u16 KeyType, u8 *MacAddr, u8 DefaultKey, u32 *KeyContent );
+short rtl8192_is_tx_queue_empty(struct net_device *dev);
+
+#endif
diff --git a/drivers/staging/rtl8192su/r8192U_core.c b/drivers/staging/rtl8192su/r8192U_core.c
new file mode 100644
index 0000000..f1423d7
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192U_core.c
@@ -0,0 +1,12460 @@
+/******************************************************************************
+ * Copyright(c) 2008 - 2010 Realtek Corporation. All rights reserved.
+ * Linux device driver for RTL8192U
+ *
+ * Based on the r8187 driver, which is:
+ * Copyright 2004-2005 Andrea Merello <andreamrl@tiscali.it>, et al.
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
+ *
+ * The full GNU General Public License is included in this distribution in the
+ * file called LICENSE.
+ *
+ * Contact Information:
+ * Jerry chuang <wlanfae@realtek.com>
+ */
+
+#ifndef CONFIG_FORCE_HARD_FLOAT
+double __floatsidf (int i) { return i; }
+unsigned int __fixunsdfsi (double d) { return d; }
+double __adddf3(double a, double b) { return a+b; }
+double __addsf3(float a, float b) { return a+b; }
+double __subdf3(double a, double b) { return a-b; }
+double __extendsfdf2(float a) {return a;}
+#endif
+
+#undef LOOP_TEST
+#undef DUMP_RX
+#undef DUMP_TX
+#undef DEBUG_TX_DESC2
+#undef RX_DONT_PASS_UL
+#undef DEBUG_EPROM
+#undef DEBUG_RX_VERBOSE
+#undef DUMMY_RX
+#undef DEBUG_ZERO_RX
+#undef DEBUG_RX_SKB
+#undef DEBUG_TX_FRAG
+#undef DEBUG_RX_FRAG
+#undef DEBUG_TX_FILLDESC
+#undef DEBUG_TX
+#undef DEBUG_IRQ
+#undef DEBUG_RX
+#undef DEBUG_RXALLOC
+#undef DEBUG_REGISTERS
+#undef DEBUG_RING
+#undef DEBUG_IRQ_TASKLET
+#undef DEBUG_TX_ALLOC
+#undef DEBUG_TX_DESC
+
+#define CONFIG_RTL8192_IO_MAP
+
+#ifdef RTL8192SU
+#include <asm/uaccess.h>
+#include "r8192U.h"
+//#include "r8190_rtl8256.h" /* RTL8225 Radio frontend */
+#include "r8180_93cx6.h"   /* Card EEPROM */
+#include "r8192U_wx.h"
+
+#include "r8192S_rtl8225.h"
+#include "r8192S_hw.h"
+#include "r8192S_phy.h"
+#include "r8192S_phyreg.h"
+#include "r8192S_Efuse.h"
+
+#include "r819xU_cmdpkt.h"
+#include "r8192U_dm.h"
+//#include "r8192xU_phyreg.h"
+#include <linux/usb.h>
+// FIXME: check if 2.6.7 is ok
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,7))
+#define usb_kill_urb usb_unlink_urb
+#endif
+
+#ifdef CONFIG_RTL8192_PM
+#include "r8192U_pm.h"
+#endif
+
+#ifdef ENABLE_DOT11D
+#include "dot11d.h"
+#endif
+
+#else
+
+#include <asm/uaccess.h>
+#include "r8192U_hw.h"
+#include "r8192U.h"
+#include "r8190_rtl8256.h" /* RTL8225 Radio frontend */
+#include "r8180_93cx6.h"   /* Card EEPROM */
+#include "r8192U_wx.h"
+#include "r819xU_phy.h" //added by WB 4.30.2008
+#include "r819xU_phyreg.h"
+#include "r819xU_cmdpkt.h"
+#include "r8192U_dm.h"
+//#include "r8192xU_phyreg.h"
+#include <linux/usb.h>
+// FIXME: check if 2.6.7 is ok
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,7))
+#define usb_kill_urb usb_unlink_urb
+#endif
+
+#ifdef CONFIG_RTL8192_PM
+#include "r8192U_pm.h"
+#endif
+
+#ifdef ENABLE_DOT11D
+#include "dot11d.h"
+#endif
+
+#endif
+
+
+#ifdef RTL8192SU
+u32 rt_global_debug_component = \
+//				COMP_TRACE	|
+//    				COMP_DBG	|
+//				COMP_INIT    	|
+//				COMP_RECV	|
+//				COMP_SEND	|
+//				COMP_IO		|
+				COMP_POWER	|
+//				COMP_EPROM   	|
+				COMP_SWBW	|
+				COMP_POWER_TRACKING |
+				COMP_TURBO	|
+				COMP_QOS	|
+//				COMP_RATE	|
+//				COMP_RM		|
+				COMP_DIG	|
+//				COMP_EFUSE	|
+//				COMP_CH		|
+//				COMP_TXAGC	|
+                              	COMP_HIPWR	|
+//                             	COMP_HALDM	|
+				COMP_SEC	|
+				COMP_LED	|
+//				COMP_RF		|
+//				COMP_RXDESC	|
+				COMP_FIRMWARE	|
+				COMP_HT		|
+				COMP_AMSDU	|
+				COMP_SCAN	|
+//				COMP_CMD	|
+				COMP_DOWN	|
+				COMP_RESET	|
+				COMP_ERR; //always open err flags on
+#else
+//set here to open your trace code. //WB
+u32 rt_global_debug_component = \
+			//	COMP_INIT    	|
+//				COMP_DBG	|
+			//	COMP_EPROM   	|
+//				COMP_PHY	|
+			//	COMP_RF		|
+//				COMP_FIRMWARE	|
+//				COMP_CH		|
+			//	COMP_POWER_TRACKING |
+//				COMP_RATE	|
+			//	COMP_TXAGC	|
+		//		COMP_TRACE	|
+				COMP_DOWN	|
+		//		COMP_RECV	|
+                //              COMP_SWBW	|
+				COMP_SEC	|
+	//			COMP_RESET	|
+		//		COMP_SEND	|
+			//	COMP_EVENTS	|
+				COMP_ERR ; //always open err flags on
+#endif
+
+#define TOTAL_CAM_ENTRY 32
+#define CAM_CONTENT_COUNT 8
+
+static struct usb_device_id rtl8192_usb_id_tbl[] = {
+	/* Realtek */
+	{USB_DEVICE(0x0bda, 0x8192)},
+	{USB_DEVICE(0x0bda, 0x8709)},
+	/* Corega */
+	{USB_DEVICE(0x07aa, 0x0043)},
+	/* Belkin */
+	{USB_DEVICE(0x050d, 0x805E)},
+	/* Sitecom */
+	{USB_DEVICE(0x0df6, 0x0031)},
+	/* EnGenius */
+	{USB_DEVICE(0x1740, 0x9201)},
+	/* Dlink */
+	{USB_DEVICE(0x2001, 0x3301)},
+	/* Zinwell */
+	{USB_DEVICE(0x5a57, 0x0290)},
+	//92SU
+	{USB_DEVICE(0x0bda, 0x8172)},
+	{}
+};
+
+MODULE_LICENSE("GPL");
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+MODULE_VERSION("V 1.1");
+#endif
+MODULE_DEVICE_TABLE(usb, rtl8192_usb_id_tbl);
+MODULE_DESCRIPTION("Linux driver for Realtek RTL8192 USB WiFi cards");
+
+static char* ifname = "wlan%d";
+#if 0
+static int hwseqnum = 0;
+static int hwwep = 0;
+#endif
+static int hwwep = 1;  //default use hw. set 0 to use software security
+static int channels = 0x3fff;
+
+
+
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 9)
+module_param(ifname, charp, S_IRUGO|S_IWUSR );
+//module_param(hwseqnum,int, S_IRUGO|S_IWUSR);
+module_param(hwwep,int, S_IRUGO|S_IWUSR);
+module_param(channels,int, S_IRUGO|S_IWUSR);
+#else
+MODULE_PARM(ifname, "s");
+//MODULE_PARM(hwseqnum,"i");
+MODULE_PARM(hwwep,"i");
+MODULE_PARM(channels,"i");
+#endif
+
+MODULE_PARM_DESC(ifname," Net interface name, wlan%d=default");
+//MODULE_PARM_DESC(hwseqnum," Try to use hardware 802.11 header sequence numbers. Zero=default");
+MODULE_PARM_DESC(hwwep," Try to use hardware security support. ");
+MODULE_PARM_DESC(channels," Channel bitmask for specific locales. NYI");
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+static int __devinit rtl8192_usb_probe(struct usb_interface *intf,
+			 const struct usb_device_id *id);
+static void __devexit rtl8192_usb_disconnect(struct usb_interface *intf);
+#else
+static void *__devinit rtl8192_usb_probe(struct usb_device *udev,unsigned int ifnum,
+			 const struct usb_device_id *id);
+static void __devexit rtl8192_usb_disconnect(struct usb_device *udev, void *ptr);
+#endif
+
+
+static struct usb_driver rtl8192_usb_driver = {
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 15)
+	.owner		= THIS_MODULE,
+#endif
+	.name		= RTL819xU_MODULE_NAME,	          /* Driver name   */
+	.id_table	= rtl8192_usb_id_tbl,	          /* PCI_ID table  */
+	.probe		= rtl8192_usb_probe,	          /* probe fn      */
+	.disconnect	= rtl8192_usb_disconnect,	  /* remove fn     */
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0)
+#ifdef CONFIG_RTL8192_PM
+	.suspend	= rtl8192U_suspend,	          /* PM suspend fn */
+	.resume		= rtl8192U_resume,                 /* PM resume fn  */
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 22)
+	.reset_resume   = rtl8192U_resume,                 /* PM reset resume fn  */
+#endif
+#else
+	.suspend	= NULL,			          /* PM suspend fn */
+	.resume      	= NULL,			          /* PM resume fn  */
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 22)
+	.reset_resume   = NULL,                 /* PM reset resume fn  */
+#endif
+#endif
+#endif
+};
+
+
+#ifdef RTL8192SU
+static void 	rtl8192SU_read_eeprom_info(struct net_device *dev);
+short 	rtl8192SU_tx(struct net_device *dev, struct sk_buff* skb);
+void 	rtl8192SU_rx_nomal(struct sk_buff* skb);
+void 	rtl8192SU_rx_cmd(struct sk_buff *skb);
+bool 	rtl8192SU_adapter_start(struct net_device *dev);
+short	rtl8192SU_tx_cmd(struct net_device *dev, struct sk_buff *skb);
+void 	rtl8192SU_link_change(struct net_device *dev);
+void 	InitialGain8192S(struct net_device *dev,u8 Operation);
+void 	rtl8192SU_query_rxdesc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe);
+
+struct rtl819x_ops rtl8192su_ops = {
+	.nic_type = NIC_8192SU,
+	.rtl819x_read_eeprom_info = rtl8192SU_read_eeprom_info,
+	.rtl819x_tx = rtl8192SU_tx,
+	.rtl819x_tx_cmd = rtl8192SU_tx_cmd,
+	.rtl819x_rx_nomal = rtl8192SU_rx_nomal,
+	.rtl819x_rx_cmd = rtl8192SU_rx_cmd,
+	.rtl819x_adapter_start = rtl8192SU_adapter_start,
+	.rtl819x_link_change = rtl8192SU_link_change,
+	.rtl819x_initial_gain = InitialGain8192S,
+	.rtl819x_query_rxdesc_status = rtl8192SU_query_rxdesc_status,
+};
+#else
+static void 	rtl8192_read_eeprom_info(struct net_device *dev);
+short	rtl8192_tx(struct net_device *dev, struct sk_buff* skb);
+void 	rtl8192_rx_nomal(struct sk_buff* skb);
+void 	rtl8192_rx_cmd(struct sk_buff *skb);
+bool 	rtl8192_adapter_start(struct net_device *dev);
+short	rtl819xU_tx_cmd(struct net_device *dev, struct sk_buff *skb);
+void 	rtl8192_link_change(struct net_device *dev);
+void 	InitialGain819xUsb(struct net_device *dev,u8 Operation);
+void 	query_rxdesc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe);
+
+struct rtl819x_ops rtl8192u_ops = {
+	.nic_type = NIC_8192U,
+	.rtl819x_read_eeprom_info = rtl8192_read_eeprom_info,
+	.rtl819x_tx = rtl8192_tx,
+	.rtl819x_tx_cmd = rtl819xU_tx_cmd,
+	.rtl819x_rx_nomal = rtl8192_rx_nomal,
+	.rtl819x_rx_cmd = rtl8192_rx_cmd,
+	.rtl819x_adapter_start = rtl8192_adapter_start,
+	.rtl819x_link_change = rtl8192_link_change,
+	.rtl819x_initial_gain = InitialGain819xUsb,
+	.rtl819x_query_rxdesc_status = query_rxdesc_status,
+};
+#endif
+
+#ifdef ENABLE_DOT11D
+
+typedef struct _CHANNEL_LIST
+{
+	u8	Channel[32];
+	u8	Len;
+}CHANNEL_LIST, *PCHANNEL_LIST;
+
+static CHANNEL_LIST ChannelPlan[] = {
+	{{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
+	{{1,2,3,4,5,6,7,8,9,10,11},11},                    				//IC
+	{{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},  	//ETSI
+	{{1,2,3,4,5,6,7,8,9,10,11,12,13},13},    //Spain. Change to ETSI.
+	{{1,2,3,4,5,6,7,8,9,10,11,12,13},13},  	//France. Change to ETSI.
+	{{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
+	{{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64},22},//MKK1
+	{{1,2,3,4,5,6,7,8,9,10,11,12,13},13},	//Israel.
+	{{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
+	{{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64}, 22},    //MIC
+	{{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
+};
+
+static void rtl819x_set_channel_map(u8 channel_plan, struct r8192_priv* priv)
+{
+	int i, max_chan=-1, min_chan=-1;
+	struct ieee80211_device* ieee = priv->ieee80211;
+	switch (channel_plan)
+	{
+		case COUNTRY_CODE_FCC:
+		case COUNTRY_CODE_IC:
+		case COUNTRY_CODE_ETSI:
+		case COUNTRY_CODE_SPAIN:
+		case COUNTRY_CODE_FRANCE:
+		case COUNTRY_CODE_MKK:
+		case COUNTRY_CODE_MKK1:
+		case COUNTRY_CODE_ISRAEL:
+		case COUNTRY_CODE_TELEC:
+		case COUNTRY_CODE_MIC:
+		{
+			Dot11d_Init(ieee);
+			ieee->bGlobalDomain = false;
+			//acturally 8225 & 8256 rf chip only support B,G,24N mode
+                        if ((priv->rf_chip == RF_8225) || (priv->rf_chip == RF_8256) || (priv->rf_chip == RF_6052))
+			{
+				min_chan = 1;
+				max_chan = 14;
+			}
+			else
+			{
+				RT_TRACE(COMP_ERR, "unknown rf chip, can't set channel map in function:%s()\n", __FUNCTION__);
+			}
+			if (ChannelPlan[channel_plan].Len != 0){
+				// Clear old channel map
+				memset(GET_DOT11D_INFO(ieee)->channel_map, 0, sizeof(GET_DOT11D_INFO(ieee)->channel_map));
+				// Set new channel map
+				for (i=0;i<ChannelPlan[channel_plan].Len;i++)
+				{
+					if (ChannelPlan[channel_plan].Channel[i] < min_chan || ChannelPlan[channel_plan].Channel[i] > max_chan)
+					break;
+					GET_DOT11D_INFO(ieee)->channel_map[ChannelPlan[channel_plan].Channel[i]] = 1;
+				}
+			}
+			break;
+		}
+		case COUNTRY_CODE_GLOBAL_DOMAIN:
+		{
+			GET_DOT11D_INFO(ieee)->bEnabled = 0;//this flag enabled to follow 11d country IE setting, otherwise, it shall follow global domain settings.
+			Dot11d_Reset(ieee);
+			ieee->bGlobalDomain = true;
+			break;
+		}
+		default:
+			break;
+	}
+	return;
+}
+#endif
+
+#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 )
+
+#ifdef RTL8192SU
+#define		rx_hal_is_cck_rate(_pDesc)\
+			((_pDesc->RxMCS  == DESC92S_RATE1M ||\
+			_pDesc->RxMCS == DESC92S_RATE2M ||\
+			_pDesc->RxMCS == DESC92S_RATE5_5M ||\
+			_pDesc->RxMCS == DESC92S_RATE11M) &&\
+			!_pDesc->RxHT)
+
+#define 	tx_hal_is_cck_rate(_DataRate)\
+			( _DataRate == MGN_1M ||\
+			 _DataRate == MGN_2M ||\
+			 _DataRate == MGN_5_5M ||\
+			 _DataRate == MGN_11M )
+
+#else
+#define 	rx_hal_is_cck_rate(_pdrvinfo)\
+			((_pdrvinfo->RxRate == DESC90_RATE1M ||\
+			_pdrvinfo->RxRate == DESC90_RATE2M ||\
+			_pdrvinfo->RxRate == DESC90_RATE5_5M ||\
+			_pdrvinfo->RxRate == DESC90_RATE11M) &&\
+			!_pdrvinfo->RxHT)
+#endif
+
+
+
+void CamResetAllEntry(struct net_device *dev)
+{
+#if 1
+	u32 ulcommand = 0;
+        //2004/02/11  In static WEP, OID_ADD_KEY or OID_ADD_WEP are set before STA associate to AP.
+        // However, ResetKey is called on OID_802_11_INFRASTRUCTURE_MODE and MlmeAssociateRequest
+        // In this condition, Cam can not be reset because upper layer will not set this static key again.
+        //if(Adapter->EncAlgorithm == WEP_Encryption)
+        //      return;
+//debug
+        //DbgPrint("========================================\n");
+        //DbgPrint("                            Call ResetAllEntry                                              \n");
+        //DbgPrint("========================================\n\n");
+	ulcommand |= BIT31|BIT30;
+	write_nic_dword(dev, RWCAM, ulcommand);
+#else
+        for(ucIndex=0;ucIndex<TOTAL_CAM_ENTRY;ucIndex++)
+                CAM_mark_invalid(dev, ucIndex);
+        for(ucIndex=0;ucIndex<TOTAL_CAM_ENTRY;ucIndex++)
+                CAM_empty_entry(dev, ucIndex);
+#endif
+
+}
+
+
+void write_cam(struct net_device *dev, u8 addr, u32 data)
+{
+        write_nic_dword(dev, WCAMI, data);
+        write_nic_dword(dev, RWCAM, BIT31|BIT16|(addr&0xff) );
+}
+
+u32 read_cam(struct net_device *dev, u8 addr)
+{
+        write_nic_dword(dev, RWCAM, 0x80000000|(addr&0xff) );
+        return read_nic_dword(dev, 0xa8);
+}
+
+void write_nic_byte_E(struct net_device *dev, int indx, u8 data)
+{
+	int status;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct usb_device *udev = priv->udev;
+
+	status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
+			       RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
+			       indx|0xfe00, 0, &data, 1, HZ / 2);
+
+	if (status < 0)
+	{
+		printk("write_nic_byte_E TimeOut! status:%d\n", status);
+	}
+}
+
+u8 read_nic_byte_E(struct net_device *dev, int indx)
+{
+	int status;
+	u8 data;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct usb_device *udev = priv->udev;
+
+	status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
+			       RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
+			       indx|0xfe00, 0, &data, 1, HZ / 2);
+
+        if (status < 0)
+        {
+                printk("read_nic_byte_E TimeOut! status:%d\n", status);
+        }
+
+	return data;
+}
+//as 92U has extend page from 4 to 16, so modify functions below.
+void write_nic_byte(struct net_device *dev, int indx, u8 data)
+{
+	int status;
+
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct usb_device *udev = priv->udev;
+
+	status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
+			       RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
+#ifdef RTL8192SU
+			       indx, 0, &data, 1, HZ / 2);
+#else
+			       (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 1, HZ / 2);
+#endif
+
+        if (status < 0)
+        {
+                printk("write_nic_byte TimeOut! status:%d\n", status);
+        }
+
+
+}
+
+
+void write_nic_word(struct net_device *dev, int indx, u16 data)
+{
+
+	int status;
+
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct usb_device *udev = priv->udev;
+
+	status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
+			       RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
+#ifdef RTL8192SU
+			       indx, 0, &data, 2, HZ / 2);
+#else
+			       (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 2, HZ / 2);
+#endif
+
+        if (status < 0)
+        {
+                printk("write_nic_word TimeOut! status:%d\n", status);
+        }
+
+}
+
+
+void write_nic_dword(struct net_device *dev, int indx, u32 data)
+{
+
+	int status;
+
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct usb_device *udev = priv->udev;
+
+	status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
+			       RTL8187_REQ_SET_REGS, RTL8187_REQT_WRITE,
+#ifdef RTL8192SU
+			       indx, 0, &data, 4, HZ / 2);
+#else
+			       (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 4, HZ / 2);
+#endif
+
+
+        if (status < 0)
+        {
+                printk("write_nic_dword TimeOut! status:%d\n", status);
+        }
+
+}
+
+
+
+u8 read_nic_byte(struct net_device *dev, int indx)
+{
+	u8 data;
+	int status;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct usb_device *udev = priv->udev;
+
+	status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
+			       RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
+#ifdef RTL8192SU
+			       indx, 0, &data, 1, HZ / 2);
+#else
+			       (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 1, HZ / 2);
+#endif
+
+        if (status < 0)
+        {
+                printk("read_nic_byte TimeOut! status:%d\n", status);
+        }
+
+	return data;
+}
+
+
+
+u16 read_nic_word(struct net_device *dev, int indx)
+{
+	u16 data;
+	int status;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct usb_device *udev = priv->udev;
+
+	status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
+			       RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
+#ifdef RTL8192SU
+			       indx, 0, &data, 2, HZ / 2);
+#else
+			       (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 2, HZ / 2);
+#endif
+
+        if (status < 0)
+        {
+                printk("read_nic_word TimeOut! status:%d\n", status);
+        }
+
+
+	return data;
+}
+
+u16 read_nic_word_E(struct net_device *dev, int indx)
+{
+	u16 data;
+	int status;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct usb_device *udev = priv->udev;
+
+	status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
+			       RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
+			       indx|0xfe00, 0, &data, 2, HZ / 2);
+
+        if (status < 0)
+        {
+                printk("read_nic_word TimeOut! status:%d\n", status);
+        }
+
+
+	return data;
+}
+
+u32 read_nic_dword(struct net_device *dev, int indx)
+{
+	u32 data;
+	int status;
+//	int result;
+
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct usb_device *udev = priv->udev;
+
+	status = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
+			       RTL8187_REQ_GET_REGS, RTL8187_REQT_READ,
+#ifdef RTL8192SU
+			       indx, 0, &data, 4, HZ / 2);
+#else
+			       (indx&0xff)|0xff00, (indx>>8)&0x0f, &data, 4, HZ / 2);
+#endif
+//	if(0 != result) {
+//	  printk(KERN_WARNING "read size of data = %d\, date = %d\n", result, data);
+//	}
+
+        if (status < 0)
+        {
+                printk("read_nic_dword TimeOut! status:%d\n", status);
+		if(status == -ENODEV) {
+			priv->usb_error = true;
+		}
+        }
+
+
+
+	return data;
+}
+
+
+//u8 read_phy_cck(struct net_device *dev, u8 adr);
+//u8 read_phy_ofdm(struct net_device *dev, u8 adr);
+/* this might still called in what was the PHY rtl8185/rtl8192 common code
+ * plans are to possibilty turn it again in one common code...
+ */
+inline void force_pci_posting(struct net_device *dev)
+{
+}
+
+
+static struct net_device_stats *rtl8192_stats(struct net_device *dev);
+void rtl8192_commit(struct net_device *dev);
+//void rtl8192_restart(struct net_device *dev);
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+void rtl8192_restart(struct work_struct *work);
+//void rtl8192_rq_tx_ack(struct work_struct *work);
+#else
+ void rtl8192_restart(struct net_device *dev);
+// //void rtl8192_rq_tx_ack(struct net_device *dev);
+ #endif
+
+void watch_dog_timer_callback(unsigned long data);
+
+/****************************************************************************
+   -----------------------------PROCFS STUFF-------------------------
+*****************************************************************************/
+
+static struct proc_dir_entry *rtl8192_proc = NULL;
+
+
+
+static int proc_get_stats_ap(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct ieee80211_device *ieee = priv->ieee80211;
+	struct ieee80211_network *target;
+
+	int len = 0;
+
+        list_for_each_entry(target, &ieee->network_list, list) {
+
+		len += snprintf(page + len, count - len,
+                "%s ", target->ssid);
+
+		if(target->wpa_ie_len>0 || target->rsn_ie_len>0){
+	                len += snprintf(page + len, count - len,
+        	        "WPA\n");
+		}
+		else{
+                        len += snprintf(page + len, count - len,
+                        "non_WPA\n");
+                }
+
+        }
+
+	*eof = 1;
+	return len;
+}
+
+#ifdef RTL8192SU
+static int proc_get_registers(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n,page0,page1,page2;
+
+	int max=0xff;
+	page0 = 0x000;
+	page1 = 0x100;
+	page2 = 0x800;
+
+	/* This dump the current register page */
+	if(!IS_BB_REG_OFFSET_92S(page0)){
+		len += snprintf(page + len, count - len,
+				"\n####################page %x##################\n ", (page0>>8));
+		for(n=0;n<=max;)
+		{
+			len += snprintf(page + len, count - len,
+					"\nD:  %2x > ",n);
+			for(i=0;i<16 && n<=max;i++,n++)
+				len += snprintf(page + len, count - len,
+						"%2.2x ",read_nic_byte(dev,(page0|n)));
+		}
+	}else{
+		len += snprintf(page + len, count - len,
+				"\n####################page %x##################\n ", (page0>>8));
+		for(n=0;n<=max;)
+		{
+			len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
+			for(i=0;i<4 && n<=max;n+=4,i++)
+				len += snprintf(page + len, count - len,
+						"%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
+		}
+	}
+	len += snprintf(page + len, count - len,"\n");
+	*eof = 1;
+	return len;
+
+}
+static int proc_get_registers_1(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n,page0;
+
+	int max=0xff;
+	page0 = 0x100;
+
+	/* This dump the current register page */
+		len += snprintf(page + len, count - len,
+				"\n####################page %x##################\n ", (page0>>8));
+		for(n=0;n<=max;)
+		{
+			len += snprintf(page + len, count - len,
+					"\nD:  %2x > ",n);
+			for(i=0;i<16 && n<=max;i++,n++)
+				len += snprintf(page + len, count - len,
+						"%2.2x ",read_nic_byte(dev,(page0|n)));
+		}
+	len += snprintf(page + len, count - len,"\n");
+	*eof = 1;
+	return len;
+
+}
+static int proc_get_registers_2(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n,page0;
+
+	int max=0xff;
+	page0 = 0x200;
+
+	/* This dump the current register page */
+		len += snprintf(page + len, count - len,
+				"\n####################page %x##################\n ", (page0>>8));
+		for(n=0;n<=max;)
+		{
+			len += snprintf(page + len, count - len,
+					"\nD:  %2x > ",n);
+			for(i=0;i<16 && n<=max;i++,n++)
+				len += snprintf(page + len, count - len,
+						"%2.2x ",read_nic_byte(dev,(page0|n)));
+		}
+	len += snprintf(page + len, count - len,"\n");
+	*eof = 1;
+	return len;
+
+}
+static int proc_get_registers_8(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+
+	int len = 0;
+	int i,n,page0;
+
+	int max=0xff;
+	page0 = 0x800;
+
+	/* This dump the current register page */
+		len += snprintf(page + len, count - len,
+				"\n####################page %x##################\n ", (page0>>8));
+		for(n=0;n<=max;)
+		{
+			len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
+			for(i=0;i<4 && n<=max;n+=4,i++)
+				len += snprintf(page + len, count - len,
+						"%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
+		}
+	len += snprintf(page + len, count - len,"\n");
+	*eof = 1;
+	return len;
+
+	}
+static int proc_get_registers_9(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n,page0;
+
+	int max=0xff;
+	page0 = 0x900;
+
+	/* This dump the current register page */
+		len += snprintf(page + len, count - len,
+				"\n####################page %x##################\n ", (page0>>8));
+		for(n=0;n<=max;)
+		{
+			len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
+			for(i=0;i<4 && n<=max;n+=4,i++)
+			len += snprintf(page + len, count - len,
+						"%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
+		}
+	len += snprintf(page + len, count - len,"\n");
+	*eof = 1;
+	return len;
+}
+static int proc_get_registers_a(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n,page0;
+
+	int max=0xff;
+	page0 = 0xa00;
+
+	/* This dump the current register page */
+				len += snprintf(page + len, count - len,
+				"\n####################page %x##################\n ", (page0>>8));
+		for(n=0;n<=max;)
+		{
+			len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
+			for(i=0;i<4 && n<=max;n+=4,i++)
+				len += snprintf(page + len, count - len,
+						"%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
+		}
+	len += snprintf(page + len, count - len,"\n");
+	*eof = 1;
+	return len;
+}
+static int proc_get_registers_b(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n,page0;
+
+	int max=0xff;
+	page0 = 0xb00;
+
+	/* This dump the current register page */
+		len += snprintf(page + len, count - len,
+				"\n####################page %x##################\n ", (page0>>8));
+		for(n=0;n<=max;)
+		{
+			len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
+			for(i=0;i<4 && n<=max;n+=4,i++)
+				len += snprintf(page + len, count - len,
+						"%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
+		}
+	len += snprintf(page + len, count - len,"\n");
+	*eof = 1;
+	return len;
+	}
+static int proc_get_registers_c(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n,page0;
+
+	int max=0xff;
+	page0 = 0xc00;
+
+	/* This dump the current register page */
+		len += snprintf(page + len, count - len,
+				"\n####################page %x##################\n ", (page0>>8));
+		for(n=0;n<=max;)
+		{
+			len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
+			for(i=0;i<4 && n<=max;n+=4,i++)
+				len += snprintf(page + len, count - len,
+						"%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
+		}
+	len += snprintf(page + len, count - len,"\n");
+	*eof = 1;
+	return len;
+}
+static int proc_get_registers_d(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n,page0;
+
+	int max=0xff;
+	page0 = 0xd00;
+
+	/* This dump the current register page */
+		len += snprintf(page + len, count - len,
+				"\n####################page %x##################\n ", (page0>>8));
+		for(n=0;n<=max;)
+		{
+			len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
+			for(i=0;i<4 && n<=max;n+=4,i++)
+				len += snprintf(page + len, count - len,
+						"%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
+		}
+	len += snprintf(page + len, count - len,"\n");
+	*eof = 1;
+	return len;
+}
+static int proc_get_registers_e(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n,page0;
+
+	int max=0xff;
+	page0 = 0xe00;
+
+	/* This dump the current register page */
+		len += snprintf(page + len, count - len,
+				"\n####################page %x##################\n ", (page0>>8));
+		for(n=0;n<=max;)
+		{
+			len += snprintf(page + len, count - len, "\nD:  %2x > ",n);
+			for(i=0;i<4 && n<=max;n+=4,i++)
+				len += snprintf(page + len, count - len,
+						"%8.8x ",rtl8192_QueryBBReg(dev,(page0|n), bMaskDWord));
+		}
+	len += snprintf(page + len, count - len,"\n");
+	*eof = 1;
+	return len;
+}
+#else
+static int proc_get_registers(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n;
+
+	int max=0xff;
+
+	/* This dump the current register page */
+len += snprintf(page + len, count - len,
+                        "\n####################page 0##################\n ");
+
+	for(n=0;n<=max;)
+	{
+		//printk( "\nD: %2x> ", n);
+		len += snprintf(page + len, count - len,
+			"\nD:  %2x > ",n);
+
+		for(i=0;i<16 && n<=max;i++,n++)
+		len += snprintf(page + len, count - len,
+			"%2x ",read_nic_byte(dev,0x000|n));
+
+		//	printk("%2x ",read_nic_byte(dev,n));
+	}
+#if 1
+len += snprintf(page + len, count - len,
+                        "\n####################page 1##################\n ");
+        for(n=0;n<=max;)
+        {
+                //printk( "\nD: %2x> ", n);
+                len += snprintf(page + len, count - len,
+                        "\nD:  %2x > ",n);
+
+                for(i=0;i<16 && n<=max;i++,n++)
+                len += snprintf(page + len, count - len,
+                        "%2x ",read_nic_byte(dev,0x100|n));
+
+                //      printk("%2x ",read_nic_byte(dev,n));
+        }
+len += snprintf(page + len, count - len,
+                        "\n####################page 3##################\n ");
+        for(n=0;n<=max;)
+        {
+                //printk( "\nD: %2x> ", n);
+                len += snprintf(page + len, count - len,
+                        "\nD:  %2x > ",n);
+
+                for(i=0;i<16 && n<=max;i++,n++)
+                len += snprintf(page + len, count - len,
+                        "%2x ",read_nic_byte(dev,0x300|n));
+
+                //      printk("%2x ",read_nic_byte(dev,n));
+        }
+
+#endif
+
+	len += snprintf(page + len, count - len,"\n");
+	*eof = 1;
+	return len;
+
+}
+#endif
+
+#if 0
+static int proc_get_cck_reg(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n;
+
+	int max = 0x5F;
+
+	/* This dump the current register page */
+	for(n=0;n<=max;)
+	{
+		//printk( "\nD: %2x> ", n);
+		len += snprintf(page + len, count - len,
+			"\nD:  %2x > ",n);
+
+		for(i=0;i<16 && n<=max;i++,n++)
+		len += snprintf(page + len, count - len,
+			"%2x ",read_phy_cck(dev,n));
+
+		//	printk("%2x ",read_nic_byte(dev,n));
+	}
+	len += snprintf(page + len, count - len,"\n");
+
+
+	*eof = 1;
+	return len;
+}
+
+#endif
+
+#if 0
+static int proc_get_ofdm_reg(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+	int i,n;
+
+	//int max=0xff;
+	int max = 0x40;
+
+	/* This dump the current register page */
+	for(n=0;n<=max;)
+	{
+		//printk( "\nD: %2x> ", n);
+		len += snprintf(page + len, count - len,
+			"\nD:  %2x > ",n);
+
+		for(i=0;i<16 && n<=max;i++,n++)
+		len += snprintf(page + len, count - len,
+			"%2x ",read_phy_ofdm(dev,n));
+
+		//	printk("%2x ",read_nic_byte(dev,n));
+	}
+	len += snprintf(page + len, count - len,"\n");
+
+
+
+	*eof = 1;
+	return len;
+}
+
+#endif
+
+#if 0
+static int proc_get_stats_hw(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+
+	len += snprintf(page + len, count - len,
+		"NIC int: %lu\n"
+		"Total int: %lu\n",
+		priv->stats.ints,
+		priv->stats.shints);
+
+	*eof = 1;
+	return len;
+}
+#endif
+
+static int proc_get_stats_tx(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+
+	len += snprintf(page + len, count - len,
+		"TX VI priority ok int: %lu\n"
+		"TX VI priority error int: %lu\n"
+		"TX VO priority ok int: %lu\n"
+		"TX VO priority error int: %lu\n"
+		"TX BE priority ok int: %lu\n"
+		"TX BE priority error int: %lu\n"
+		"TX BK priority ok int: %lu\n"
+		"TX BK priority error int: %lu\n"
+		"TX MANAGE priority ok int: %lu\n"
+		"TX MANAGE priority error int: %lu\n"
+		"TX BEACON priority ok int: %lu\n"
+		"TX BEACON priority error int: %lu\n"
+//		"TX high priority ok int: %lu\n"
+//		"TX high priority failed error int: %lu\n"
+		"TX queue resume: %lu\n"
+		"TX queue stopped?: %d\n"
+		"TX fifo overflow: %lu\n"
+//		"TX beacon: %lu\n"
+		"TX VI queue: %d\n"
+		"TX VO queue: %d\n"
+		"TX BE queue: %d\n"
+		"TX BK queue: %d\n"
+//		"TX HW queue: %d\n"
+		"TX VI dropped: %lu\n"
+		"TX VO dropped: %lu\n"
+		"TX BE dropped: %lu\n"
+		"TX BK dropped: %lu\n"
+		"TX total data packets %lu\n",
+//		"TX beacon aborted: %lu\n",
+		priv->stats.txviokint,
+		priv->stats.txvierr,
+		priv->stats.txvookint,
+		priv->stats.txvoerr,
+		priv->stats.txbeokint,
+		priv->stats.txbeerr,
+		priv->stats.txbkokint,
+		priv->stats.txbkerr,
+		priv->stats.txmanageokint,
+		priv->stats.txmanageerr,
+		priv->stats.txbeaconokint,
+		priv->stats.txbeaconerr,
+//		priv->stats.txhpokint,
+//		priv->stats.txhperr,
+		priv->stats.txresumed,
+		netif_queue_stopped(dev),
+		priv->stats.txoverflow,
+//		priv->stats.txbeacon,
+		atomic_read(&(priv->tx_pending[VI_PRIORITY])),
+		atomic_read(&(priv->tx_pending[VO_PRIORITY])),
+		atomic_read(&(priv->tx_pending[BE_PRIORITY])),
+		atomic_read(&(priv->tx_pending[BK_PRIORITY])),
+//		read_nic_byte(dev, TXFIFOCOUNT),
+		priv->stats.txvidrop,
+		priv->stats.txvodrop,
+		priv->stats.txbedrop,
+		priv->stats.txbkdrop,
+		priv->stats.txdatapkt
+//		priv->stats.txbeaconerr
+		);
+
+	*eof = 1;
+	return len;
+}
+
+
+
+static int proc_get_stats_rx(char *page, char **start,
+			  off_t offset, int count,
+			  int *eof, void *data)
+{
+	struct net_device *dev = data;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	int len = 0;
+
+	len += snprintf(page + len, count - len,
+		"RX packets: %lu\n"
+		"RX urb status error: %lu\n"
+		"RX invalid urb error: %lu\n",
+		priv->stats.rxoktotal,
+		priv->stats.rxstaterr,
+		priv->stats.rxurberr);
+
+	*eof = 1;
+	return len;
+}
+#if 0
+#if WIRELESS_EXT >= 12 && WIRELESS_EXT < 17
+
+static struct iw_statistics *r8192_get_wireless_stats(struct net_device *dev)
+{
+       struct r8192_priv *priv = ieee80211_priv(dev);
+
+       return &priv->wstats;
+}
+#endif
+#endif
+void rtl8192_proc_module_init(void)
+{
+	RT_TRACE(COMP_INIT, "Initializing proc filesystem");
+#if(LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24))
+	rtl8192_proc=create_proc_entry(RTL819xU_MODULE_NAME, S_IFDIR, proc_net);
+#else
+	rtl8192_proc=create_proc_entry(RTL819xU_MODULE_NAME, S_IFDIR, init_net.proc_net);
+#endif
+}
+
+
+void rtl8192_proc_module_remove(void)
+{
+#if(LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24))
+	remove_proc_entry(RTL819xU_MODULE_NAME, proc_net);
+#else
+	remove_proc_entry(RTL819xU_MODULE_NAME, init_net.proc_net);
+#endif
+}
+
+
+void rtl8192_proc_remove_one(struct net_device *dev)
+{
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+
+	if (priv->dir_dev) {
+	//	remove_proc_entry("stats-hw", priv->dir_dev);
+		remove_proc_entry("stats-tx", priv->dir_dev);
+		remove_proc_entry("stats-rx", priv->dir_dev);
+	//	remove_proc_entry("stats-ieee", priv->dir_dev);
+		remove_proc_entry("stats-ap", priv->dir_dev);
+		remove_proc_entry("registers", priv->dir_dev);
+		remove_proc_entry("registers-1", priv->dir_dev);
+		remove_proc_entry("registers-2", priv->dir_dev);
+		remove_proc_entry("registers-8", priv->dir_dev);
+		remove_proc_entry("registers-9", priv->dir_dev);
+		remove_proc_entry("registers-a", priv->dir_dev);
+		remove_proc_entry("registers-b", priv->dir_dev);
+		remove_proc_entry("registers-c", priv->dir_dev);
+		remove_proc_entry("registers-d", priv->dir_dev);
+		remove_proc_entry("registers-e", priv->dir_dev);
+	//	remove_proc_entry("cck-registers",priv->dir_dev);
+	//	remove_proc_entry("ofdm-registers",priv->dir_dev);
+		//remove_proc_entry(dev->name, rtl8192_proc);
+		remove_proc_entry("wlan0", rtl8192_proc);
+		priv->dir_dev = NULL;
+	}
+}
+
+
+void rtl8192_proc_init_one(struct net_device *dev)
+{
+	struct proc_dir_entry *e;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	priv->dir_dev = create_proc_entry(dev->name,
+					  S_IFDIR | S_IRUGO | S_IXUGO,
+					  rtl8192_proc);
+	if (!priv->dir_dev) {
+		RT_TRACE(COMP_ERR, "Unable to initialize /proc/net/rtl8192/%s\n",
+		      dev->name);
+		return;
+	}
+	#if 0
+	e = create_proc_read_entry("stats-hw", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_stats_hw, dev);
+
+	if (!e) {
+		DMESGE("Unable to initialize "
+		      "/proc/net/rtl8192/%s/stats-hw\n",
+		      dev->name);
+	}
+	#endif
+	e = create_proc_read_entry("stats-rx", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_stats_rx, dev);
+
+	if (!e) {
+		RT_TRACE(COMP_ERR,"Unable to initialize "
+		      "/proc/net/rtl8192/%s/stats-rx\n",
+		      dev->name);
+	}
+
+
+	e = create_proc_read_entry("stats-tx", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_stats_tx, dev);
+
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/stats-tx\n",
+		      dev->name);
+	}
+	#if 0
+	e = create_proc_read_entry("stats-ieee", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_stats_ieee, dev);
+
+	if (!e) {
+		DMESGE("Unable to initialize "
+		      "/proc/net/rtl8192/%s/stats-ieee\n",
+		      dev->name);
+	}
+
+	#endif
+
+	e = create_proc_read_entry("stats-ap", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_stats_ap, dev);
+
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/stats-ap\n",
+		      dev->name);
+	}
+
+	e = create_proc_read_entry("registers", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_registers, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/registers\n",
+		      dev->name);
+	}
+#ifdef RTL8192SU
+	e = create_proc_read_entry("registers-1", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_registers_1, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/registers-1\n",
+		      dev->name);
+	}
+	e = create_proc_read_entry("registers-2", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_registers_2, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/registers-2\n",
+		      dev->name);
+	}
+	e = create_proc_read_entry("registers-8", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_registers_8, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/registers-8\n",
+		      dev->name);
+	}
+	e = create_proc_read_entry("registers-9", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_registers_9, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/registers-9\n",
+		      dev->name);
+	}
+	e = create_proc_read_entry("registers-a", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_registers_a, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/registers-a\n",
+		      dev->name);
+	}
+	e = create_proc_read_entry("registers-b", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_registers_b, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/registers-b\n",
+		      dev->name);
+	}
+	e = create_proc_read_entry("registers-c", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_registers_c, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/registers-c\n",
+		      dev->name);
+	}
+	e = create_proc_read_entry("registers-d", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_registers_d, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/registers-d\n",
+		      dev->name);
+	}
+	e = create_proc_read_entry("registers-e", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_registers_e, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/registers-e\n",
+		      dev->name);
+	}
+#endif
+#if 0
+	e = create_proc_read_entry("cck-registers", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_cck_reg, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/cck-registers\n",
+		      dev->name);
+	}
+
+	e = create_proc_read_entry("ofdm-registers", S_IFREG | S_IRUGO,
+				   priv->dir_dev, proc_get_ofdm_reg, dev);
+	if (!e) {
+		RT_TRACE(COMP_ERR, "Unable to initialize "
+		      "/proc/net/rtl8192/%s/ofdm-registers\n",
+		      dev->name);
+	}
+#endif
+}
+/****************************************************************************
+   -----------------------------MISC STUFF-------------------------
+*****************************************************************************/
+
+/* this is only for debugging */
+void print_buffer(u32 *buffer, int len)
+{
+	int i;
+	u8 *buf =(u8*)buffer;
+
+	printk("ASCII BUFFER DUMP (len: %x):\n",len);
+
+	for(i=0;i<len;i++)
+		printk("%c",buf[i]);
+
+	printk("\nBINARY BUFFER DUMP (len: %x):\n",len);
+
+	for(i=0;i<len;i++)
+		printk("%x",buf[i]);
+
+	printk("\n");
+}
+
+//short check_nic_enough_desc(struct net_device *dev, priority_t priority)
+short check_nic_enough_desc(struct net_device *dev,int queue_index)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int used = atomic_read(&priv->tx_pending[queue_index]);
+
+	return (used < MAX_TX_URB);
+}
+
+void tx_timeout(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//rtl8192_commit(dev);
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+	schedule_work(&priv->reset_wq);
+#else
+	schedule_task(&priv->reset_wq);
+#endif
+	//DMESG("TXTIMEOUT");
+}
+
+
+/* this is only for debug */
+void dump_eprom(struct net_device *dev)
+{
+	int i;
+	for(i=0; i<63; i++)
+		RT_TRACE(COMP_EPROM, "EEPROM addr %x : %x", i, eprom_read(dev,i));
+}
+
+/* this is only for debug */
+void rtl8192_dump_reg(struct net_device *dev)
+{
+	int i;
+	int n;
+	int max=0x1ff;
+
+	RT_TRACE(COMP_PHY, "Dumping NIC register map");
+
+	for(n=0;n<=max;)
+	{
+		printk( "\nD: %2x> ", n);
+		for(i=0;i<16 && n<=max;i++,n++)
+			printk("%2x ",read_nic_byte(dev,n));
+	}
+	printk("\n");
+}
+
+/****************************************************************************
+      ------------------------------HW STUFF---------------------------
+*****************************************************************************/
+
+#if 0
+void rtl8192_irq_enable(struct net_device *dev)
+{
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	//priv->irq_enabled = 1;
+/*
+	write_nic_word(dev,INTA_MASK,INTA_RXOK | INTA_RXDESCERR | INTA_RXOVERFLOW |\
+	INTA_TXOVERFLOW | INTA_HIPRIORITYDESCERR | INTA_HIPRIORITYDESCOK |\
+	INTA_NORMPRIORITYDESCERR | INTA_NORMPRIORITYDESCOK |\
+	INTA_LOWPRIORITYDESCERR | INTA_LOWPRIORITYDESCOK | INTA_TIMEOUT);
+*/
+	write_nic_word(dev,INTA_MASK, priv->irq_mask);
+}
+
+
+void rtl8192_irq_disable(struct net_device *dev)
+{
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	write_nic_word(dev,INTA_MASK,0);
+	force_pci_posting(dev);
+//	priv->irq_enabled = 0;
+}
+#endif
+
+void rtl8192_set_mode(struct net_device *dev,int mode)
+{
+	u8 ecmd;
+	ecmd=read_nic_byte(dev, EPROM_CMD);
+	ecmd=ecmd &~ EPROM_CMD_OPERATING_MODE_MASK;
+	ecmd=ecmd | (mode<<EPROM_CMD_OPERATING_MODE_SHIFT);
+	ecmd=ecmd &~ (1<<EPROM_CS_SHIFT);
+	ecmd=ecmd &~ (1<<EPROM_CK_SHIFT);
+	write_nic_byte(dev, EPROM_CMD, ecmd);
+}
+
+
+void rtl8192_update_msr(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8 msr;
+
+	msr  = read_nic_byte(dev, MSR);
+	msr &= ~ MSR_LINK_MASK;
+
+	/* do not change in link_state != WLAN_LINK_ASSOCIATED.
+	 * msr must be updated if the state is ASSOCIATING.
+	 * this is intentional and make sense for ad-hoc and
+	 * master (see the create BSS/IBSS func)
+	 */
+	if (priv->ieee80211->state == IEEE80211_LINKED){
+
+		if (priv->ieee80211->iw_mode == IW_MODE_INFRA)
+			msr |= (MSR_LINK_MANAGED<<MSR_LINK_SHIFT);
+		else if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
+			msr |= (MSR_LINK_ADHOC<<MSR_LINK_SHIFT);
+		else if (priv->ieee80211->iw_mode == IW_MODE_MASTER)
+			msr |= (MSR_LINK_MASTER<<MSR_LINK_SHIFT);
+
+	}else
+		msr |= (MSR_LINK_NONE<<MSR_LINK_SHIFT);
+
+	write_nic_byte(dev, MSR, msr);
+}
+
+void rtl8192_set_chan(struct net_device *dev,short ch)
+{
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+//	u32 tx;
+	RT_TRACE(COMP_CH, "=====>%s()====ch:%d\n", __FUNCTION__, ch);
+	//printk("=====>%s()====ch:%d\n", __FUNCTION__, ch);
+	priv->chan=ch;
+	#if 0
+	if(priv->ieee80211->iw_mode == IW_MODE_ADHOC ||
+		priv->ieee80211->iw_mode == IW_MODE_MASTER){
+
+			priv->ieee80211->link_state = WLAN_LINK_ASSOCIATED;
+			priv->ieee80211->master_chan = ch;
+			rtl8192_update_beacon_ch(dev);
+		}
+	#endif
+
+	/* this hack should avoid frame TX during channel setting*/
+
+
+//	tx = read_nic_dword(dev,TX_CONF);
+//	tx &= ~TX_LOOPBACK_MASK;
+
+#ifndef LOOP_TEST
+//	write_nic_dword(dev,TX_CONF, tx |( TX_LOOPBACK_MAC<<TX_LOOPBACK_SHIFT));
+
+	//need to implement rf set channel here WB
+
+	if (priv->rf_set_chan)
+	priv->rf_set_chan(dev,priv->chan);
+	mdelay(10);
+//	write_nic_dword(dev,TX_CONF,tx | (TX_LOOPBACK_NONE<<TX_LOOPBACK_SHIFT));
+#endif
+}
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20)
+static void rtl8192_rx_isr(struct urb *urb, struct pt_regs *regs);
+#else
+static void rtl8192_rx_isr(struct urb *urb);
+#endif
+//static void rtl8192_rx_isr(struct urb *rx_urb);
+
+u32 get_rxpacket_shiftbytes_819xusb(struct ieee80211_rx_stats *pstats)
+{
+
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	if (pstats->bisrxaggrsubframe)
+		return (sizeof(rx_desc_819x_usb) + pstats->RxDrvInfoSize
+			+ pstats->RxBufShift + 8);
+	else
+#endif
+		return (sizeof(rx_desc_819x_usb) + pstats->RxDrvInfoSize
+				+ pstats->RxBufShift);
+
+}
+static int rtl8192_rx_initiate(struct net_device*dev)
+{
+        struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+        struct urb *entry;
+        struct sk_buff *skb;
+        struct rtl8192_rx_info *info;
+
+	/* nomal packet rx procedure */
+        while (skb_queue_len(&priv->rx_queue) < MAX_RX_URB) {
+                skb = __dev_alloc_skb(RX_URB_SIZE, GFP_KERNEL);
+                if (!skb)
+                        break;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	        entry = usb_alloc_urb(0, GFP_KERNEL);
+#else
+	        entry = usb_alloc_urb(0);
+#endif
+                if (!entry) {
+                        kfree_skb(skb);
+                        break;
+                }
+//		printk("nomal packet IN request!\n");
+                usb_fill_bulk_urb(entry, priv->udev,
+                                  usb_rcvbulkpipe(priv->udev, 3), skb->tail,
+                                  RX_URB_SIZE, rtl8192_rx_isr, skb);
+                info = (struct rtl8192_rx_info *) skb->cb;
+                info->urb = entry;
+                info->dev = dev;
+		info->out_pipe = 3; //denote rx normal packet queue
+                skb_queue_tail(&priv->rx_queue, skb);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+                usb_submit_urb(entry, GFP_KERNEL);
+#else
+                usb_submit_urb(entry);
+#endif
+        }
+
+	/* command packet rx procedure */
+        while (skb_queue_len(&priv->rx_queue) < MAX_RX_URB + 3) {
+//		printk("command packet IN request!\n");
+                skb = __dev_alloc_skb(RX_URB_SIZE ,GFP_KERNEL);
+                if (!skb)
+                        break;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+                entry = usb_alloc_urb(0, GFP_KERNEL);
+#else
+                entry = usb_alloc_urb(0);
+#endif
+                if (!entry) {
+                        kfree_skb(skb);
+                        break;
+                }
+                usb_fill_bulk_urb(entry, priv->udev,
+                                  usb_rcvbulkpipe(priv->udev, 9), skb->tail,
+                                  RX_URB_SIZE, rtl8192_rx_isr, skb);
+                info = (struct rtl8192_rx_info *) skb->cb;
+                info->urb = entry;
+                info->dev = dev;
+		   info->out_pipe = 9; //denote rx cmd packet queue
+                skb_queue_tail(&priv->rx_queue, skb);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+		usb_submit_urb(entry, GFP_KERNEL);
+#else
+		usb_submit_urb(entry);
+#endif
+        }
+
+        return 0;
+}
+
+void rtl8192_set_rxconf(struct net_device *dev)
+{
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	u32 rxconf;
+
+	rxconf=read_nic_dword(dev,RCR);
+	rxconf = rxconf &~ MAC_FILTER_MASK;
+	rxconf = rxconf | RCR_AMF;
+	rxconf = rxconf | RCR_ADF;
+	rxconf = rxconf | RCR_AB;
+	rxconf = rxconf | RCR_AM;
+	//rxconf = rxconf | RCR_ACF;
+
+	if (dev->flags & IFF_PROMISC) {DMESG ("NIC in promisc mode");}
+
+	if(priv->ieee80211->iw_mode == IW_MODE_MONITOR || \
+	   dev->flags & IFF_PROMISC){
+		rxconf = rxconf | RCR_AAP;
+	} /*else if(priv->ieee80211->iw_mode == IW_MODE_MASTER){
+		rxconf = rxconf | (1<<ACCEPT_ALLMAC_FRAME_SHIFT);
+		rxconf = rxconf | (1<<RX_CHECK_BSSID_SHIFT);
+	}*/else{
+		rxconf = rxconf | RCR_APM;
+		rxconf = rxconf | RCR_CBSSID;
+	}
+
+
+	if(priv->ieee80211->iw_mode == IW_MODE_MONITOR){
+		rxconf = rxconf | RCR_AICV;
+		rxconf = rxconf | RCR_APWRMGT;
+	}
+
+	if( priv->crcmon == 1 && priv->ieee80211->iw_mode == IW_MODE_MONITOR)
+		rxconf = rxconf | RCR_ACRC32;
+
+
+	rxconf = rxconf &~ RX_FIFO_THRESHOLD_MASK;
+	rxconf = rxconf | (RX_FIFO_THRESHOLD_NONE<<RX_FIFO_THRESHOLD_SHIFT);
+	rxconf = rxconf &~ MAX_RX_DMA_MASK;
+	rxconf = rxconf | ((u32)7<<RCR_MXDMA_OFFSET);
+
+//	rxconf = rxconf | (1<<RX_AUTORESETPHY_SHIFT);
+	rxconf = rxconf | RCR_ONLYERLPKT;
+
+//	rxconf = rxconf &~ RCR_CS_MASK;
+//	rxconf = rxconf | (1<<RCR_CS_SHIFT);
+
+	write_nic_dword(dev, RCR, rxconf);
+
+	#ifdef DEBUG_RX
+	DMESG("rxconf: %x %x",rxconf ,read_nic_dword(dev,RCR));
+	#endif
+}
+//wait to be removed
+void rtl8192_rx_enable(struct net_device *dev)
+{
+	//u8 cmd;
+
+	//struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	rtl8192_rx_initiate(dev);
+
+//	rtl8192_set_rxconf(dev);
+#if 0
+	if(NIC_8187 == priv->card_8187) {
+		cmd=read_nic_byte(dev,CMD);
+		write_nic_byte(dev,CMD,cmd | (1<<CMD_RX_ENABLE_SHIFT));
+	}
+	else {
+		//write_nic_dword(dev, RX_CONF, priv->ReceiveConfig);
+	}
+#endif
+}
+
+
+void rtl8192_tx_enable(struct net_device *dev)
+{
+#if 0
+	u8 cmd;
+	u8 byte;
+	u32 txconf;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	//test loopback
+	//	priv->TransmitConfig |= (TX_LOOPBACK_BASEBAND<<TX_LOOPBACK_SHIFT);
+	if(NIC_8187B == priv->card_8187){
+		write_nic_dword(dev, TX_CONF, priv->TransmitConfig);
+		byte = read_nic_byte(dev, MSR);
+		byte |= MSR_LINK_ENEDCA;
+		write_nic_byte(dev, MSR, byte);
+	} else {
+		byte = read_nic_byte(dev,CW_CONF);
+		byte &= ~(1<<CW_CONF_PERPACKET_CW_SHIFT);
+		byte &= ~(1<<CW_CONF_PERPACKET_RETRY_SHIFT);
+		write_nic_byte(dev, CW_CONF, byte);
+
+		byte = read_nic_byte(dev, TX_AGC_CTL);
+		byte &= ~(1<<TX_AGC_CTL_PERPACKET_GAIN_SHIFT);
+		byte &= ~(1<<TX_AGC_CTL_PERPACKET_ANTSEL_SHIFT);
+		byte &= ~(1<<TX_AGC_CTL_FEEDBACK_ANT);
+		write_nic_byte(dev, TX_AGC_CTL, byte);
+
+		txconf= read_nic_dword(dev,TX_CONF);
+
+
+		txconf = txconf &~ TX_LOOPBACK_MASK;
+
+#ifndef LOOP_TEST
+		txconf = txconf | (TX_LOOPBACK_NONE<<TX_LOOPBACK_SHIFT);
+#else
+		txconf = txconf | (TX_LOOPBACK_BASEBAND<<TX_LOOPBACK_SHIFT);
+#endif
+		txconf = txconf &~ TCR_SRL_MASK;
+		txconf = txconf &~ TCR_LRL_MASK;
+
+		txconf = txconf | (priv->retry_data<<TX_LRLRETRY_SHIFT); // long
+		txconf = txconf | (priv->retry_rts<<TX_SRLRETRY_SHIFT); // short
+
+		txconf = txconf &~ (1<<TX_NOCRC_SHIFT);
+
+		txconf = txconf &~ TCR_MXDMA_MASK;
+		txconf = txconf | (TCR_MXDMA_2048<<TCR_MXDMA_SHIFT);
+
+		txconf = txconf | TCR_DISReqQsize;
+		txconf = txconf | TCR_DISCW;
+		txconf = txconf &~ TCR_SWPLCPLEN;
+
+		txconf=txconf | (1<<TX_NOICV_SHIFT);
+
+		write_nic_dword(dev,TX_CONF,txconf);
+
+#ifdef DEBUG_TX
+		DMESG("txconf: %x %x",txconf,read_nic_dword(dev,TX_CONF));
+#endif
+
+		cmd=read_nic_byte(dev,CMD);
+		write_nic_byte(dev,CMD,cmd | (1<<CMD_TX_ENABLE_SHIFT));
+	}
+#endif
+}
+
+#if 0
+void rtl8192_beacon_tx_enable(struct net_device *dev)
+{
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	priv->dma_poll_mask &=~(1<<TX_DMA_STOP_BEACON_SHIFT);
+	rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
+	write_nic_byte(dev,TX_DMA_POLLING,priv->dma_poll_mask);
+	rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
+}
+
+
+void rtl8192_
+_disable(struct net_device *dev)
+{
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	priv->dma_poll_mask |= (1<<TX_DMA_STOP_BEACON_SHIFT);
+	rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
+	write_nic_byte(dev,TX_DMA_POLLING,priv->dma_poll_mask);
+	rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
+}
+
+#endif
+
+
+void rtl8192_rtx_disable(struct net_device *dev)
+{
+	u8 cmd;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct sk_buff *skb;
+	struct rtl8192_rx_info *info;
+
+	cmd=read_nic_byte(dev,CMDR);
+	write_nic_byte(dev, CMDR, cmd &~ \
+		(CR_TE|CR_RE));
+	force_pci_posting(dev);
+	mdelay(10);
+
+	while ((skb = __skb_dequeue(&priv->rx_queue))) {
+		info = (struct rtl8192_rx_info *) skb->cb;
+		if (!info->urb)
+			continue;
+
+		usb_kill_urb(info->urb);
+		kfree_skb(skb);
+	}
+
+	if (skb_queue_len(&priv->skb_queue)) {
+		printk(KERN_WARNING "skb_queue not empty\n");
+	}
+
+	skb_queue_purge(&priv->skb_queue);
+	return;
+}
+
+
+int alloc_tx_beacon_desc_ring(struct net_device *dev, int count)
+{
+	#if 0
+	int i;
+	u32 *tmp;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	priv->txbeaconring = (u32*)pci_alloc_consistent(priv->pdev,
+					  sizeof(u32)*8*count,
+					  &priv->txbeaconringdma);
+	if (!priv->txbeaconring) return -1;
+	for (tmp=priv->txbeaconring,i=0;i<count;i++){
+		*tmp = *tmp &~ (1<<31); // descriptor empty, owned by the drv
+		/*
+		*(tmp+2) = (u32)dma_tmp;
+		*(tmp+3) = bufsize;
+		*/
+		if(i+1<count)
+			*(tmp+4) = (u32)priv->txbeaconringdma+((i+1)*8*4);
+		else
+			*(tmp+4) = (u32)priv->txbeaconringdma;
+
+		tmp=tmp+8;
+	}
+	#endif
+	return 0;
+}
+
+#if 0
+void rtl8192_reset(struct net_device *dev)
+{
+
+	//struct r8192_priv *priv = ieee80211_priv(dev);
+	//u8 cr;
+
+
+	/* make sure the analog power is on before
+	 * reset, otherwise reset may fail
+	 */
+#if 0
+	if(NIC_8187 == priv->card_8187) {
+		rtl8192_set_anaparam(dev, RTL8225_ANAPARAM_ON);
+		rtl8185_set_anaparam2(dev, RTL8225_ANAPARAM2_ON);
+		rtl8192_irq_disable(dev);
+		mdelay(200);
+		write_nic_byte_E(dev,0x18,0x10);
+		write_nic_byte_E(dev,0x18,0x11);
+		write_nic_byte_E(dev,0x18,0x00);
+		mdelay(200);
+	}
+#endif
+	printk("=====>reset?\n");
+#if 0
+	cr=read_nic_byte(dev,CMD);
+	cr = cr & 2;
+	cr = cr | (1<<CMD_RST_SHIFT);
+	write_nic_byte(dev,CMD,cr);
+
+	force_pci_posting(dev);
+
+	mdelay(200);
+
+	if(read_nic_byte(dev,CMD) & (1<<CMD_RST_SHIFT))
+		RT_TRACE(COMP_ERR, "Card reset timeout!\n");
+	else
+		RT_TRACE(COMP_DOWN, "Card successfully reset\n");
+#endif
+#if 0
+	if(NIC_8187 == priv->card_8187) {
+
+		printk("This is RTL8187 Reset procedure\n");
+		rtl8192_set_mode(dev,EPROM_CMD_LOAD);
+		force_pci_posting(dev);
+		mdelay(200);
+
+		/* after the eeprom load cycle, make sure we have
+		 * correct anaparams
+		 */
+		rtl8192_set_anaparam(dev, RTL8225_ANAPARAM_ON);
+		rtl8185_set_anaparam2(dev, RTL8225_ANAPARAM2_ON);
+	}
+	else
+#endif
+		printk("This is RTL8187B Reset procedure\n");
+
+}
+#endif
+inline u16 ieeerate2rtlrate(int rate)
+{
+	switch(rate){
+	case 10:
+	return 0;
+	case 20:
+	return 1;
+	case 55:
+	return 2;
+	case 110:
+	return 3;
+	case 60:
+	return 4;
+	case 90:
+	return 5;
+	case 120:
+	return 6;
+	case 180:
+	return 7;
+	case 240:
+	return 8;
+	case 360:
+	return 9;
+	case 480:
+	return 10;
+	case 540:
+	return 11;
+	default:
+	return 3;
+
+	}
+}
+static u16 rtl_rate[] = {10,20,55,110,60,90,120,180,240,360,480,540};
+inline u16 rtl8192_rate2rate(short rate)
+{
+	if (rate >11) return 0;
+	return rtl_rate[rate];
+}
+
+
+/* The protype of rx_isr has changed since one verion of Linux Kernel */
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20)
+static void rtl8192_rx_isr(struct urb *urb, struct pt_regs *regs)
+#else
+static void rtl8192_rx_isr(struct urb *urb)
+#endif
+{
+        struct sk_buff *skb = (struct sk_buff *) urb->context;
+        struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
+        struct net_device *dev = info->dev;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int out_pipe = info->out_pipe;
+	int err;
+	if(!priv->up)
+		return;
+        if (unlikely(urb->status)) {
+                info->urb = NULL;
+                priv->stats.rxstaterr++;
+                priv->ieee80211->stats.rx_errors++;
+                usb_free_urb(urb);
+	//	printk("%s():rx status err\n",__FUNCTION__);
+                return;
+        }
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,14)
+        skb_unlink(skb, &priv->rx_queue);
+#else
+	/*
+	 * __skb_unlink before linux2.6.14 does not use spinlock to protect list head.
+	 * add spinlock function manually. john,2008/12/03
+	 */
+	{
+		unsigned long flags;
+		spin_lock_irqsave(&(priv->rx_queue.lock), flags);
+		__skb_unlink(skb,&priv->rx_queue);
+		spin_unlock_irqrestore(&(priv->rx_queue.lock), flags);
+	}
+#endif
+        skb_put(skb, urb->actual_length);
+
+	skb_queue_tail(&priv->skb_queue, skb);
+	tasklet_schedule(&priv->irq_rx_tasklet);
+
+        skb = dev_alloc_skb(RX_URB_SIZE);
+        if (unlikely(!skb)) {
+                usb_free_urb(urb);
+		printk("%s():can,t alloc skb\n",__FUNCTION__);
+                /* TODO check rx queue length and refill *somewhere* */
+                return;
+        }
+
+	usb_fill_bulk_urb(urb, priv->udev,
+			usb_rcvbulkpipe(priv->udev, out_pipe), skb->tail,
+			RX_URB_SIZE, rtl8192_rx_isr, skb);
+
+        info = (struct rtl8192_rx_info *) skb->cb;
+        info->urb = urb;
+        info->dev = dev;
+	info->out_pipe = out_pipe;
+
+        urb->transfer_buffer = skb->tail;
+        urb->context = skb;
+        skb_queue_tail(&priv->rx_queue, skb);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+        err = usb_submit_urb(urb, GFP_ATOMIC);
+#else
+        err = usb_submit_urb(urb);
+#endif
+	if(err && err != EPERM)
+		printk("can not submit rxurb, err is %x,URB status is %x\n",err,urb->status);
+}
+
+u32
+rtl819xusb_rx_command_packet(
+	struct net_device *dev,
+	struct ieee80211_rx_stats *pstats
+	)
+{
+	u32	status;
+
+	//RT_TRACE(COMP_RECV, DBG_TRACE, ("---> RxCommandPacketHandle819xUsb()\n"));
+
+	status = cmpk_message_handle_rx(dev, pstats);
+	if (status)
+	{
+		DMESG("rxcommandpackethandle819xusb: It is a command packet\n");
+	}
+	else
+	{
+		//RT_TRACE(COMP_RECV, DBG_TRACE, ("RxCommandPacketHandle819xUsb: It is not a command packet\n"));
+	}
+
+	//RT_TRACE(COMP_RECV, DBG_TRACE, ("<--- RxCommandPacketHandle819xUsb()\n"));
+	return status;
+}
+
+#if 0
+void rtl8192_tx_queues_stop(struct net_device *dev)
+{
+	//struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	u8 dma_poll_mask = (1<<TX_DMA_STOP_LOWPRIORITY_SHIFT);
+	dma_poll_mask |= (1<<TX_DMA_STOP_HIPRIORITY_SHIFT);
+	dma_poll_mask |= (1<<TX_DMA_STOP_NORMPRIORITY_SHIFT);
+	dma_poll_mask |= (1<<TX_DMA_STOP_BEACON_SHIFT);
+
+	rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
+	write_nic_byte(dev,TX_DMA_POLLING,dma_poll_mask);
+	rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
+}
+#endif
+
+void rtl8192_data_hard_stop(struct net_device *dev)
+{
+	//FIXME !!
+	#if 0
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	priv->dma_poll_mask |= (1<<TX_DMA_STOP_LOWPRIORITY_SHIFT);
+	rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
+	write_nic_byte(dev,TX_DMA_POLLING,priv->dma_poll_mask);
+	rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
+	#endif
+}
+
+
+void rtl8192_data_hard_resume(struct net_device *dev)
+{
+	// FIXME !!
+	#if 0
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	priv->dma_poll_mask &= ~(1<<TX_DMA_STOP_LOWPRIORITY_SHIFT);
+	rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
+	write_nic_byte(dev,TX_DMA_POLLING,priv->dma_poll_mask);
+	rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
+	#endif
+}
+
+/* this function TX data frames when the ieee80211 stack requires this.
+ * It checks also if we need to stop the ieee tx queue, eventually do it
+ */
+void rtl8192_hard_data_xmit(struct sk_buff *skb, struct net_device *dev, int rate)
+{
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	int ret;
+	unsigned long flags;
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	u8 queue_index = tcb_desc->queue_index;
+
+	/* shall not be referred by command packet */
+	assert(queue_index != TXCMD_QUEUE);
+
+	spin_lock_irqsave(&priv->tx_lock,flags);
+
+        memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
+//	tcb_desc->RATRIndex = 7;
+//	tcb_desc->bTxDisableRateFallBack = 1;
+//	tcb_desc->bTxUseDriverAssingedRate = 1;
+	tcb_desc->bTxEnableFwCalcDur = 1;
+	skb_push(skb, priv->ieee80211->tx_headroom);
+	ret = priv->ops->rtl819x_tx(dev, skb);
+
+	//priv->ieee80211->stats.tx_bytes+=(skb->len - priv->ieee80211->tx_headroom);
+	//priv->ieee80211->stats.tx_packets++;
+
+	spin_unlock_irqrestore(&priv->tx_lock,flags);
+
+//	return ret;
+	return;
+}
+
+/* This is a rough attempt to TX a frame
+ * This is called by the ieee 80211 stack to TX management frames.
+ * If the ring is full packet are dropped (for data frame the queue
+ * is stopped before this can happen).
+ */
+int rtl8192_hard_start_xmit(struct sk_buff *skb,struct net_device *dev)
+{
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	int ret;
+	unsigned long flags;
+        cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+        u8 queue_index = tcb_desc->queue_index;
+
+
+	spin_lock_irqsave(&priv->tx_lock,flags);
+
+        memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
+	if(queue_index == TXCMD_QUEUE) {
+		skb_push(skb, USB_HWDESC_HEADER_LEN);
+		priv->ops->rtl819x_tx_cmd(dev, skb);
+		ret = 1;
+	        spin_unlock_irqrestore(&priv->tx_lock,flags);
+		return ret;
+	} else {
+		skb_push(skb, priv->ieee80211->tx_headroom);
+		ret = priv->ops->rtl819x_tx(dev, skb);
+	}
+
+	spin_unlock_irqrestore(&priv->tx_lock,flags);
+
+	return ret;
+}
+
+
+void rtl8192_try_wake_queue(struct net_device *dev, int pri);
+
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+u16 DrvAggr_PaddingAdd(struct net_device *dev, struct sk_buff *skb)
+{
+	u16     PaddingNum =  256 - ((skb->len + TX_PACKET_DRVAGGR_SUBFRAME_SHIFT_BYTES) % 256);
+	return  (PaddingNum&0xff);
+}
+
+u8 MRateToHwRate8190Pci(u8 rate);
+u8 QueryIsShort(u8 TxHT, u8 TxRate, cb_desc *tcb_desc);
+u8 MapHwQueueToFirmwareQueue(u8 QueueID);
+struct sk_buff *DrvAggr_Aggregation(struct net_device *dev, struct ieee80211_drv_agg_txb *pSendList)
+{
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
+	struct ieee80211_device *ieee = netdev_priv(dev);
+#else
+	struct ieee80211_device *ieee = (struct ieee80211_device *)dev->priv;
+#endif
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	cb_desc 	*tcb_desc = NULL;
+	u8 		i;
+	u32		TotalLength;
+	struct sk_buff	*skb;
+	struct sk_buff  *agg_skb;
+	tx_desc_819x_usb_aggr_subframe *tx_agg_desc = NULL;
+	tx_fwinfo_819x_usb	       *tx_fwinfo = NULL;
+
+	//
+	// Local variable initialization.
+	//
+	/* first skb initialization */
+	skb = pSendList->tx_agg_frames[0];
+	TotalLength = skb->len;
+
+	/* Get the total aggregation length including the padding space and
+	 * sub frame header.
+	 */
+	for(i = 1; i < pSendList->nr_drv_agg_frames; i++) {
+		TotalLength += DrvAggr_PaddingAdd(dev, skb);
+		skb = pSendList->tx_agg_frames[i];
+		TotalLength += (skb->len + TX_PACKET_DRVAGGR_SUBFRAME_SHIFT_BYTES);
+	}
+
+	/* allocate skb to contain the aggregated packets */
+	agg_skb = dev_alloc_skb(TotalLength + ieee->tx_headroom);
+	memset(agg_skb->data, 0, agg_skb->len);
+	skb_reserve(agg_skb, ieee->tx_headroom);
+
+//	RT_DEBUG_DATA(COMP_SEND, skb->cb, sizeof(skb->cb));
+	/* reserve info for first subframe Tx descriptor to be set in the tx function */
+	skb = pSendList->tx_agg_frames[0];
+	tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	tcb_desc->drv_agg_enable = 1;
+	tcb_desc->pkt_size = skb->len;
+ 	tcb_desc->DrvAggrNum = pSendList->nr_drv_agg_frames;
+	printk("DrvAggNum = %d\n", tcb_desc->DrvAggrNum);
+//	RT_DEBUG_DATA(COMP_SEND, skb->cb, sizeof(skb->cb));
+//	printk("========>skb->data ======> \n");
+//	RT_DEBUG_DATA(COMP_SEND, skb->data, skb->len);
+	memcpy(agg_skb->cb, skb->cb, sizeof(skb->cb));
+	memcpy(skb_put(agg_skb,skb->len),skb->data,skb->len);
+
+	for(i = 1; i < pSendList->nr_drv_agg_frames; i++) {
+		/* push the next sub frame to be 256 byte aline */
+		skb_put(agg_skb,DrvAggr_PaddingAdd(dev,skb));
+
+		/* Subframe drv Tx descriptor and firmware info setting */
+		skb = pSendList->tx_agg_frames[i];
+		tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+		tx_agg_desc = (tx_desc_819x_usb_aggr_subframe *)agg_skb->tail;
+		tx_fwinfo = (tx_fwinfo_819x_usb *)(agg_skb->tail + sizeof(tx_desc_819x_usb_aggr_subframe));
+
+		memset(tx_fwinfo,0,sizeof(tx_fwinfo_819x_usb));
+		/* DWORD 0 */
+		tx_fwinfo->TxHT = (tcb_desc->data_rate&0x80)?1:0;
+		tx_fwinfo->TxRate = MRateToHwRate8190Pci(tcb_desc->data_rate);
+		tx_fwinfo->EnableCPUDur = tcb_desc->bTxEnableFwCalcDur;
+		tx_fwinfo->Short = QueryIsShort(tx_fwinfo->TxHT, tx_fwinfo->TxRate, tcb_desc);
+		if(tcb_desc->bAMPDUEnable) {//AMPDU enabled
+			tx_fwinfo->AllowAggregation = 1;
+			/* DWORD 1 */
+			tx_fwinfo->RxMF = tcb_desc->ampdu_factor;
+			tx_fwinfo->RxAMD = tcb_desc->ampdu_density&0x07;//ampdudensity
+		} else {
+			tx_fwinfo->AllowAggregation = 0;
+			/* DWORD 1 */
+			tx_fwinfo->RxMF = 0;
+			tx_fwinfo->RxAMD = 0;
+		}
+
+		/* Protection mode related */
+		tx_fwinfo->RtsEnable = (tcb_desc->bRTSEnable)?1:0;
+		tx_fwinfo->CtsEnable = (tcb_desc->bCTSEnable)?1:0;
+		tx_fwinfo->RtsSTBC = (tcb_desc->bRTSSTBC)?1:0;
+		tx_fwinfo->RtsHT = (tcb_desc->rts_rate&0x80)?1:0;
+		tx_fwinfo->RtsRate =  MRateToHwRate8190Pci((u8)tcb_desc->rts_rate);
+		tx_fwinfo->RtsSubcarrier = (tx_fwinfo->RtsHT==0)?(tcb_desc->RTSSC):0;
+		tx_fwinfo->RtsBandwidth = (tx_fwinfo->RtsHT==1)?((tcb_desc->bRTSBW)?1:0):0;
+		tx_fwinfo->RtsShort = (tx_fwinfo->RtsHT==0)?(tcb_desc->bRTSUseShortPreamble?1:0):\
+				      (tcb_desc->bRTSUseShortGI?1:0);
+
+		/* Set Bandwidth and sub-channel settings. */
+		if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
+		{
+			if(tcb_desc->bPacketBW) {
+				tx_fwinfo->TxBandwidth = 1;
+				tx_fwinfo->TxSubCarrier = 0;    //By SD3's Jerry suggestion, use duplicated mode
+			} else {
+				tx_fwinfo->TxBandwidth = 0;
+				tx_fwinfo->TxSubCarrier = priv->nCur40MhzPrimeSC;
+			}
+		} else {
+			tx_fwinfo->TxBandwidth = 0;
+			tx_fwinfo->TxSubCarrier = 0;
+		}
+
+		/* Fill Tx descriptor */
+		memset(tx_agg_desc, 0, sizeof(tx_desc_819x_usb_aggr_subframe));
+		/* DWORD 0 */
+		//tx_agg_desc->LINIP = 0;
+		//tx_agg_desc->CmdInit = 1;
+		tx_agg_desc->Offset =  sizeof(tx_fwinfo_819x_usb) + 8;
+		/* already raw data, need not to substract header length */
+		tx_agg_desc->PktSize = skb->len & 0xffff;
+
+		/*DWORD 1*/
+		tx_agg_desc->SecCAMID= 0;
+		tx_agg_desc->RATid = tcb_desc->RATRIndex;
+#if 0
+		/* Fill security related */
+		if( pTcb->bEncrypt && !Adapter->MgntInfo.SecurityInfo.SWTxEncryptFlag)
+		{
+			EncAlg = SecGetEncryptionOverhead(
+					Adapter,
+					&EncryptionMPDUHeadOverhead,
+					&EncryptionMPDUTailOverhead,
+					NULL,
+					NULL,
+					FALSE,
+					FALSE);
+			//2004/07/22, kcwu, EncryptionMPDUHeadOverhead has been added in previous code
+			//MPDUOverhead = EncryptionMPDUHeadOverhead + EncryptionMPDUTailOverhead;
+			MPDUOverhead = EncryptionMPDUTailOverhead;
+			tx_agg_desc->NoEnc = 0;
+			RT_TRACE(COMP_SEC, DBG_LOUD, ("******We in the loop SecCAMID is %d SecDescAssign is %d The Sec is %d********\n",tx_agg_desc->SecCAMID,tx_agg_desc->SecDescAssign,EncAlg));
+			//CamDumpAll(Adapter);
+		}
+		else
+#endif
+		{
+			//MPDUOverhead = 0;
+			tx_agg_desc->NoEnc = 1;
+		}
+#if 0
+		switch(EncAlg){
+			case NO_Encryption:
+				tx_agg_desc->SecType = 0x0;
+				break;
+			case WEP40_Encryption:
+			case WEP104_Encryption:
+				tx_agg_desc->SecType = 0x1;
+				break;
+			case TKIP_Encryption:
+				tx_agg_desc->SecType = 0x2;
+				break;
+			case AESCCMP_Encryption:
+				tx_agg_desc->SecType = 0x3;
+				break;
+			default:
+				tx_agg_desc->SecType = 0x0;
+				break;
+		}
+#else
+		tx_agg_desc->SecType = 0x0;
+#endif
+
+		if (tcb_desc->bHwSec) {
+			switch (priv->ieee80211->pairwise_key_type)
+			{
+				case KEY_TYPE_WEP40:
+				case KEY_TYPE_WEP104:
+					tx_agg_desc->SecType = 0x1;
+					tx_agg_desc->NoEnc = 0;
+					break;
+				case KEY_TYPE_TKIP:
+					tx_agg_desc->SecType = 0x2;
+					tx_agg_desc->NoEnc = 0;
+					break;
+				case KEY_TYPE_CCMP:
+					tx_agg_desc->SecType = 0x3;
+					tx_agg_desc->NoEnc = 0;
+					break;
+				case KEY_TYPE_NA:
+					tx_agg_desc->SecType = 0x0;
+					tx_agg_desc->NoEnc = 1;
+					break;
+			}
+		}
+
+		tx_agg_desc->QueueSelect = MapHwQueueToFirmwareQueue(tcb_desc->queue_index);
+		tx_agg_desc->TxFWInfoSize =  sizeof(tx_fwinfo_819x_usb);
+
+		tx_agg_desc->DISFB = tcb_desc->bTxDisableRateFallBack;
+		tx_agg_desc->USERATE = tcb_desc->bTxUseDriverAssingedRate;
+
+		tx_agg_desc->OWN = 1;
+
+		//DWORD 2
+		/* According windows driver, it seems that there no need to fill this field */
+		//tx_agg_desc->TxBufferSize= (u32)(skb->len - USB_HWDESC_HEADER_LEN);
+
+		/* to fill next packet */
+		skb_put(agg_skb,TX_PACKET_DRVAGGR_SUBFRAME_SHIFT_BYTES);
+		memcpy(skb_put(agg_skb,skb->len),skb->data,skb->len);
+	}
+
+	for(i = 0; i < pSendList->nr_drv_agg_frames; i++) {
+		dev_kfree_skb_any(pSendList->tx_agg_frames[i]);
+	}
+
+	return agg_skb;
+}
+
+/* NOTE:
+	This function return a list of PTCB which is proper to be aggregate with the input TCB.
+	If no proper TCB is found to do aggregation, SendList will only contain the input TCB.
+*/
+u8 DrvAggr_GetAggregatibleList(struct net_device *dev, struct sk_buff *skb,
+		struct ieee80211_drv_agg_txb *pSendList)
+{
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
+	struct ieee80211_device *ieee = netdev_priv(dev);
+#else
+	struct ieee80211_device *ieee = (struct ieee80211_device *)dev->priv;
+#endif
+	PRT_HIGH_THROUGHPUT	pHTInfo = ieee->pHTInfo;
+	u16		nMaxAggrNum = pHTInfo->UsbTxAggrNum;
+	cb_desc 	*tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	u8		QueueID = tcb_desc->queue_index;
+
+	do {
+		pSendList->tx_agg_frames[pSendList->nr_drv_agg_frames++] = skb;
+		if(pSendList->nr_drv_agg_frames >= nMaxAggrNum) {
+			break;
+		}
+
+	} while((skb = skb_dequeue(&ieee->skb_drv_aggQ[QueueID])));
+
+	RT_TRACE(COMP_AMSDU, "DrvAggr_GetAggregatibleList, nAggrTcbNum = %d \n", pSendList->nr_drv_agg_frames);
+	return pSendList->nr_drv_agg_frames;
+}
+#endif
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20)
+static void rtl8192_tx_isr(struct urb *tx_urb, struct pt_regs *reg)
+#else
+static void rtl8192_tx_isr(struct urb *tx_urb)
+#endif
+{
+	struct sk_buff *skb = (struct sk_buff*)tx_urb->context;
+	struct net_device *dev = NULL;
+	struct r8192_priv *priv = NULL;
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	u8  queue_index = tcb_desc->queue_index;
+//	bool bToSend0Byte;
+//	u16 BufLen = skb->len;
+
+	memcpy(&dev,(struct net_device*)(skb->cb),sizeof(struct net_device*));
+	priv = ieee80211_priv(dev);
+
+	if(tcb_desc->queue_index != TXCMD_QUEUE) {
+		if(tx_urb->status == 0) {
+		//	dev->trans_start = jiffies;
+			// As act as station mode, destion shall be  unicast address.
+			//priv->ieee80211->stats.tx_bytes+=(skb->len - priv->ieee80211->tx_headroom);
+			//priv->ieee80211->stats.tx_packets++;
+			priv->stats.txoktotal++;
+			priv->ieee80211->LinkDetectInfo.NumTxOkInPeriod++;
+			priv->stats.txbytesunicast += (skb->len - priv->ieee80211->tx_headroom);
+		} else {
+			priv->ieee80211->stats.tx_errors++;
+			//priv->stats.txmanageerr++;
+			/* TODO */
+		}
+	}
+
+	/* free skb and tx_urb */
+	if(skb != NULL) {
+		dev_kfree_skb_any(skb);
+		usb_free_urb(tx_urb);
+		atomic_dec(&priv->tx_pending[queue_index]);
+	}
+
+#if 0  //we need to send zero byte packet just after 512 byte(64 byte)packet is transmitted, or we will halt. It will greatly reduced available page in FW, and ruin our throughput. WB 2008.08.27
+	if(BufLen > 0 && ((BufLen % 512 == 0)||(BufLen % 64 == 0))) {
+		bToSend0Byte = true;
+	}
+
+	bToSend0Byte = false;
+	//
+	// Note that, we at most handle 1 MPDU to send here, either
+	// fragment or MPDU in wait queue.
+	//
+	if(!bToSend0Byte)
+#endif
+	{
+		//
+		// Handle HW Beacon:
+		// We had transfer our beacon frame to host controler at this moment.
+		//
+#if 0
+		if(tcb_desc->tx_queue == BEACON_QUEUE)
+		{
+			priv->bSendingBeacon = FALSE;
+		}
+#endif
+		//
+		// Caution:
+		// Handling the wait queue of command packets.
+		// For Tx command packets, we must not do TCB fragment because it is not handled right now.
+		// We must cut the packets to match the size of TX_CMD_PKT before we send it.
+		//
+	if (queue_index == MGNT_QUEUE){
+        if (priv->ieee80211->ack_tx_to_ieee){
+            if (rtl8192_is_tx_queue_empty(dev)){
+                priv->ieee80211->ack_tx_to_ieee = 0;
+                ieee80211_ps_tx_ack(priv->ieee80211, 1);
+            }
+        }
+    }
+		/* Handle MPDU in wait queue. */
+		if(queue_index != BEACON_QUEUE) {
+			/* Don't send data frame during scanning.*/
+			if((skb_queue_len(&priv->ieee80211->skb_waitQ[queue_index]) != 0)&&\
+					(!(priv->ieee80211->queue_stop))) {
+				if(NULL != (skb = skb_dequeue(&(priv->ieee80211->skb_waitQ[queue_index]))))
+					priv->ieee80211->softmac_hard_start_xmit(skb, dev);
+
+				return; //modified by david to avoid further processing AMSDU
+			}
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+			else if ((skb_queue_len(&priv->ieee80211->skb_drv_aggQ[queue_index])!= 0)&&\
+ 				(!(priv->ieee80211->queue_stop))) {
+				// Tx Driver Aggregation process
+				/* The driver will aggregation the packets according to the following stets
+				 * 1. check whether there's tx irq available, for it's a completion return
+				 *    function, it should contain enough tx irq;
+				 * 2. check pakcet type;
+				 * 3. intialize sendlist, check whether the to-be send packet no greater than 1
+				 * 4. aggregation the packets, and fill firmware info and tx desc to it, etc.
+				 * 5. check whehter the packet could be sent, otherwise just insert to wait head
+				 * */
+				skb = skb_dequeue(&priv->ieee80211->skb_drv_aggQ[queue_index]);
+				if(!check_nic_enough_desc(dev, queue_index)) {
+					skb_queue_head(&(priv->ieee80211->skb_drv_aggQ[queue_index]), skb);
+					return;
+				}
+
+				{
+					/*TODO*/
+					/*
+					u8* pHeader = skb->data;
+
+					if(IsMgntQosData(pHeader) ||
+				            IsMgntQData_Ack(pHeader) ||
+					    IsMgntQData_Poll(pHeader) ||
+					    IsMgntQData_Poll_Ack(pHeader)
+					  )
+					*/
+					{
+						struct ieee80211_drv_agg_txb SendList;
+
+						memset(&SendList, 0, sizeof(struct ieee80211_drv_agg_txb));
+						if(DrvAggr_GetAggregatibleList(dev, skb, &SendList) > 1) {
+							skb = DrvAggr_Aggregation(dev, &SendList);
+
+#if 0
+						printk("=============>to send aggregated packet!\n");
+						RT_DEBUG_DATA(COMP_SEND, skb->cb, sizeof(skb->cb));
+						printk("\n=================skb->len = %d\n", skb->len);
+						RT_DEBUG_DATA(COMP_SEND, skb->data, skb->len);
+#endif
+						}
+					}
+					priv->ieee80211->softmac_hard_start_xmit(skb, dev);
+				}
+			}
+#endif
+		}
+	}
+
+#if 0
+	else
+	{
+		RT_TRACE( COMP_SEND,"HalUsbOutComplete(%d): bToSend0Byte.\n", PipeIndex);
+
+		//
+		// In this case, we don't return skb now.
+		// It will be returned when the 0-byte request completed.
+		//
+
+		//
+		// Bulk out an 0-byte padding transfer.
+		//
+		HalUsbOut0Byte(pAdapter, PipeIndex, skb);
+	}
+
+#endif
+}
+
+void rtl8192_beacon_stop(struct net_device *dev)
+{
+	u8 msr, msrm, msr2;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	msr  = read_nic_byte(dev, MSR);
+	msrm = msr & MSR_LINK_MASK;
+	msr2 = msr & ~MSR_LINK_MASK;
+
+	if(NIC_8192U == priv->card_8192) {
+		usb_kill_urb(priv->rx_urb[MAX_RX_URB]);
+	}
+	if ((msrm == (MSR_LINK_ADHOC<<MSR_LINK_SHIFT) ||
+		(msrm == (MSR_LINK_MASTER<<MSR_LINK_SHIFT)))){
+		write_nic_byte(dev, MSR, msr2 | MSR_LINK_NONE);
+		write_nic_byte(dev, MSR, msr);
+	}
+}
+
+void rtl8192_config_rate(struct net_device* dev, u16* rate_config)
+{
+	 struct r8192_priv *priv = ieee80211_priv(dev);
+	 struct ieee80211_network *net;
+	 u8 i=0, basic_rate = 0;
+	 net = & priv->ieee80211->current_network;
+
+	 for (i=0; i<net->rates_len; i++)
+	 {
+		 basic_rate = net->rates[i]&0x7f;
+		 switch(basic_rate)
+		 {
+			 case MGN_1M:	*rate_config |= RRSR_1M;	break;
+			 case MGN_2M:	*rate_config |= RRSR_2M;	break;
+			 case MGN_5_5M:	*rate_config |= RRSR_5_5M;	break;
+			 case MGN_11M:	*rate_config |= RRSR_11M;	break;
+			 case MGN_6M:	*rate_config |= RRSR_6M;	break;
+			 case MGN_9M:	*rate_config |= RRSR_9M;	break;
+			 case MGN_12M:	*rate_config |= RRSR_12M;	break;
+			 case MGN_18M:	*rate_config |= RRSR_18M;	break;
+			 case MGN_24M:	*rate_config |= RRSR_24M;	break;
+			 case MGN_36M:	*rate_config |= RRSR_36M;	break;
+			 case MGN_48M:	*rate_config |= RRSR_48M;	break;
+			 case MGN_54M:	*rate_config |= RRSR_54M;	break;
+		 }
+	 }
+	 for (i=0; i<net->rates_ex_len; i++)
+	 {
+		 basic_rate = net->rates_ex[i]&0x7f;
+		 switch(basic_rate)
+		 {
+			 case MGN_1M:	*rate_config |= RRSR_1M;	break;
+			 case MGN_2M:	*rate_config |= RRSR_2M;	break;
+			 case MGN_5_5M:	*rate_config |= RRSR_5_5M;	break;
+			 case MGN_11M:	*rate_config |= RRSR_11M;	break;
+			 case MGN_6M:	*rate_config |= RRSR_6M;	break;
+			 case MGN_9M:	*rate_config |= RRSR_9M;	break;
+			 case MGN_12M:	*rate_config |= RRSR_12M;	break;
+			 case MGN_18M:	*rate_config |= RRSR_18M;	break;
+			 case MGN_24M:	*rate_config |= RRSR_24M;	break;
+			 case MGN_36M:	*rate_config |= RRSR_36M;	break;
+			 case MGN_48M:	*rate_config |= RRSR_48M;	break;
+			 case MGN_54M:	*rate_config |= RRSR_54M;	break;
+		 }
+	 }
+}
+
+
+#define SHORT_SLOT_TIME 9
+#define NON_SHORT_SLOT_TIME 20
+
+void rtl8192_update_cap(struct net_device* dev, u16 cap)
+{
+	//u32 tmp = 0;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct ieee80211_network *net = &priv->ieee80211->current_network;
+	priv->short_preamble = cap & WLAN_CAPABILITY_SHORT_PREAMBLE;
+
+	//LZM MOD 090303 HW_VAR_ACK_PREAMBLE
+#ifdef RTL8192SU
+	if(0)
+	{
+		u8 tmp = 0;
+		tmp = ((priv->nCur40MhzPrimeSC) << 5);
+		if (priv->short_preamble)
+			tmp |= 0x80;
+		write_nic_byte(dev, RRSR+2, tmp);
+	}
+#else
+	{
+	u32 tmp = 0;
+	tmp = priv->basic_rate;
+	if (priv->short_preamble)
+		tmp |= BRSR_AckShortPmb;
+	write_nic_dword(dev, RRSR, tmp);
+	}
+#endif
+
+	if (net->mode & (IEEE_G|IEEE_N_24G))
+	{
+		u8 slot_time = 0;
+		if ((cap & WLAN_CAPABILITY_SHORT_SLOT)&&(!priv->ieee80211->pHTInfo->bCurrentRT2RTLongSlotTime))
+		{//short slot time
+			slot_time = SHORT_SLOT_TIME;
+		}
+		else //long slot time
+			slot_time = NON_SHORT_SLOT_TIME;
+		priv->slot_time = slot_time;
+		write_nic_byte(dev, SLOT_TIME, slot_time);
+	}
+
+}
+void rtl8192_net_update(struct net_device *dev)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct ieee80211_network *net;
+	u16 BcnTimeCfg = 0, BcnCW = 6, BcnIFS = 0xf;
+	u16 rate_config = 0;
+	net = & priv->ieee80211->current_network;
+
+	rtl8192_config_rate(dev, &rate_config);
+	priv->basic_rate = rate_config &= 0x15f;
+
+	write_nic_dword(dev,BSSIDR,((u32*)net->bssid)[0]);
+	write_nic_word(dev,BSSIDR+4,((u16*)net->bssid)[2]);
+	//for(i=0;i<ETH_ALEN;i++)
+	//	write_nic_byte(dev,BSSID+i,net->bssid[i]);
+
+	rtl8192_update_msr(dev);
+//	rtl8192_update_cap(dev, net->capability);
+	if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
+	{
+	write_nic_word(dev, ATIMWND, 2);
+	write_nic_word(dev, BCN_DMATIME, 1023);
+	write_nic_word(dev, BCN_INTERVAL, net->beacon_interval);
+//	write_nic_word(dev, BcnIntTime, 100);
+	write_nic_word(dev, BCN_DRV_EARLY_INT, 1);
+	write_nic_byte(dev, BCN_ERR_THRESH, 100);
+		BcnTimeCfg |= (BcnCW<<BCN_TCFG_CW_SHIFT);
+	// TODO: BcnIFS may required to be changed on ASIC
+	 	BcnTimeCfg |= BcnIFS<<BCN_TCFG_IFS;
+
+	write_nic_word(dev, BCN_TCFG, BcnTimeCfg);
+	}
+
+
+
+}
+
+//temporary hw beacon is not used any more.
+//open it when necessary
+#if 1
+void rtl819xusb_beacon_tx(struct net_device *dev,u16  tx_rate)
+{
+
+#if 0
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct sk_buff *skb;
+	int i = 0;
+	//u8 cr;
+
+	rtl8192_net_update(dev);
+
+	skb = ieee80211_get_beacon(priv->ieee80211);
+		if(!skb){
+			DMESG("not enought memory for allocating beacon");
+			return;
+		}
+
+
+		write_nic_byte(dev, BQREQ, read_nic_byte(dev, BQREQ) | (1<<7));
+
+		i=0;
+		//while(!read_nic_byte(dev,BQREQ & (1<<7)))
+		while( (read_nic_byte(dev, BQREQ) & (1<<7)) == 0 )
+		{
+			msleep_interruptible_rtl(HZ/2);
+			if(i++ > 10){
+				DMESGW("get stuck to wait HW beacon to be ready");
+				return ;
+			}
+		}
+	skb->cb[0] = NORM_PRIORITY;
+	skb->cb[1] = 0; //morefragment = 0
+	skb->cb[2] = ieeerate2rtlrate(tx_rate);
+
+	rtl8192_tx(dev,skb);
+
+#endif
+}
+#endif
+inline u8 rtl8192_IsWirelessBMode(u16 rate)
+{
+	if( ((rate <= 110) && (rate != 60) && (rate != 90)) || (rate == 220) )
+		return 1;
+	else return 0;
+}
+
+u16 N_DBPSOfRate(u16 DataRate);
+
+u16 ComputeTxTime(
+	u16		FrameLength,
+	u16		DataRate,
+	u8		bManagementFrame,
+	u8		bShortPreamble
+)
+{
+	u16	FrameTime;
+	u16	N_DBPS;
+	u16	Ceiling;
+
+	if( rtl8192_IsWirelessBMode(DataRate) )
+	{
+		if( bManagementFrame || !bShortPreamble || DataRate == 10 )
+		{	// long preamble
+			FrameTime = (u16)(144+48+(FrameLength*8/(DataRate/10)));
+		}
+		else
+		{	// Short preamble
+			FrameTime = (u16)(72+24+(FrameLength*8/(DataRate/10)));
+		}
+		if( ( FrameLength*8 % (DataRate/10) ) != 0 ) //Get the Ceilling
+				FrameTime ++;
+	} else {	//802.11g DSSS-OFDM PLCP length field calculation.
+		N_DBPS = N_DBPSOfRate(DataRate);
+		Ceiling = (16 + 8*FrameLength + 6) / N_DBPS
+				+ (((16 + 8*FrameLength + 6) % N_DBPS) ? 1 : 0);
+		FrameTime = (u16)(16 + 4 + 4*Ceiling + 6);
+	}
+	return FrameTime;
+}
+
+u16 N_DBPSOfRate(u16 DataRate)
+{
+	 u16 N_DBPS = 24;
+
+	 switch(DataRate)
+	 {
+	 case 60:
+	  N_DBPS = 24;
+	  break;
+
+	 case 90:
+	  N_DBPS = 36;
+	  break;
+
+	 case 120:
+	  N_DBPS = 48;
+	  break;
+
+	 case 180:
+	  N_DBPS = 72;
+	  break;
+
+	 case 240:
+	  N_DBPS = 96;
+	  break;
+
+	 case 360:
+	  N_DBPS = 144;
+	  break;
+
+	 case 480:
+	  N_DBPS = 192;
+	  break;
+
+	 case 540:
+	  N_DBPS = 216;
+	  break;
+
+	 default:
+	  break;
+	 }
+
+	 return N_DBPS;
+}
+
+void rtl819xU_cmd_isr(struct urb *tx_cmd_urb, struct pt_regs *regs)
+{
+#if 0
+	struct net_device *dev = (struct net_device*)tx_cmd_urb->context;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int		   last_init_packet = 0;
+	u8		   *ptr_cmd_buf;
+	u16		    cmd_buf_len;
+
+	if(tx_cmd_urb->status != 0) {
+		priv->pFirmware.firmware_seg_index = 0; //only begin transter, should it can be set to 1
+	}
+
+	/* Free the urb and the corresponding buf for common Tx cmd packet, or
+	 * last segment of each firmware img.
+	 */
+	if((priv->pFirmware.firmware_seg_index == 0) ||(priv->pFirmware.firmware_seg_index == priv->pFirmware.firmware_seg_maxnum)) {
+		priv->pFirmware.firmware_seg_index = 0;//only begin transter, should it can be set to 1
+	} else {
+		/* prepare for last transfer */
+		/* update some infomation for */
+		/* last segment of the firmware img need indicate to device */
+		priv->pFirmware.firmware_seg_index++;
+		if(priv->pFirmware.firmware_seg_index == priv->pFirmware.firmware_seg_maxnum) {
+			last_init_packet = 1;
+		}
+
+		cmd_buf_len = priv->pFirmware.firmware_seg_container[priv->pFirmware.firmware_seg_index-1].seg_size;
+		ptr_cmd_buf = priv->pFfirmware.firmware_seg_container[priv->pFfirmware.firmware_seg_index-1].seg_ptr;
+		rtl819xU_tx_cmd(dev, ptr_cmd_buf, cmd_buf_len, last_init_packet, DESC_PACKET_TYPE_INIT);
+	}
+
+	kfree(tx_cmd_urb->transfer_buffer);
+#endif
+	usb_free_urb(tx_cmd_urb);
+}
+
+unsigned int txqueue2outpipe(struct r8192_priv* priv,unsigned int tx_queue) {
+
+	if(tx_queue >= 9)
+	{
+		RT_TRACE(COMP_ERR,"%s():Unknown queue ID!!!\n",__FUNCTION__);
+		return 0x04;
+	}
+	return priv->txqueue_to_outpipemap[tx_queue];
+}
+
+#ifdef RTL8192SU
+short rtl8192SU_tx_cmd(struct net_device *dev, struct sk_buff *skb)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int			status;
+	struct urb		*tx_urb;
+	unsigned int 		idx_pipe;
+	tx_desc_cmd_819x_usb *pdesc = (tx_desc_cmd_819x_usb *)skb->data;
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	u8 queue_index = tcb_desc->queue_index;
+	u32			PktSize = 0;
+
+	//printk("\n %s::::::::::::::::::::::queue_index = %d\n",__FUNCTION__, queue_index);
+	atomic_inc(&priv->tx_pending[queue_index]);
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
+#else
+	tx_urb = usb_alloc_urb(0);
+#endif
+	if(!tx_urb){
+		dev_kfree_skb(skb);
+		return -ENOMEM;
+	}
+
+	memset(pdesc, 0, USB_HWDESC_HEADER_LEN);
+
+	/* Tx descriptor ought to be set according to the skb->cb */
+	pdesc->LINIP = tcb_desc->bLastIniPkt;
+	PktSize = (u16)(skb->len - USB_HWDESC_HEADER_LEN);
+	pdesc->PktSize = PktSize;
+	//printk("PKTSize = %d %x\n",pdesc->PktSize,pdesc->PktSize);
+	//----------------------------------------------------------------------------
+	// Fill up USB_OUT_CONTEXT.
+	//----------------------------------------------------------------------------
+	// Get index to out pipe from specified QueueID.
+	idx_pipe = txqueue2outpipe(priv,queue_index);
+	//printk("=============>%s queue_index:%d, outpipe:%d\n", __func__,queue_index,priv->RtOutPipes[idx_pipe]);
+
+#ifdef JOHN_DUMP_TXDESC
+	int i;
+	printk("Len = %d\n", skb->len);
+	for (i = 0; i < 8; i++)
+		printk("%2.2x ", *((u8*)skb->data+i));
+	printk("\n");
+#endif
+
+	usb_fill_bulk_urb(tx_urb,
+	                            priv->udev,
+	                            usb_sndbulkpipe(priv->udev,priv->RtOutPipes[idx_pipe]),
+	                            skb->data,
+	                            skb->len,
+	                            rtl8192_tx_isr,
+	                            skb);
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	status = usb_submit_urb(tx_urb, GFP_ATOMIC);
+#else
+	status = usb_submit_urb(tx_urb);
+#endif
+
+	if (!status){
+		return 0;
+	}else{
+		printk("Error TX CMD URB, error %d",
+				status);
+		return -1;
+	}
+}
+#else
+short rtl819xU_tx_cmd(struct net_device *dev, struct sk_buff *skb)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//u8			*tx;
+	int			status;
+	struct urb		*tx_urb;
+	//int			urb_buf_len;
+	unsigned int 		idx_pipe;
+	tx_desc_cmd_819x_usb *pdesc = (tx_desc_cmd_819x_usb *)skb->data;
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	u8 queue_index = tcb_desc->queue_index;
+
+	//printk("\n %s::queue_index = %d\n",__FUNCTION__, queue_index);
+	atomic_inc(&priv->tx_pending[queue_index]);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
+#else
+	tx_urb = usb_alloc_urb(0);
+#endif
+	if(!tx_urb){
+		dev_kfree_skb(skb);
+		return -ENOMEM;
+	}
+
+	memset(pdesc, 0, USB_HWDESC_HEADER_LEN);
+	/* Tx descriptor ought to be set according to the skb->cb */
+	pdesc->FirstSeg = 1;//bFirstSeg;
+	pdesc->LastSeg = 1;//bLastSeg;
+	pdesc->CmdInit = tcb_desc->bCmdOrInit;
+	pdesc->TxBufferSize = tcb_desc->txbuf_size;
+	pdesc->OWN = 1;
+	pdesc->LINIP = tcb_desc->bLastIniPkt;
+
+	//----------------------------------------------------------------------------
+	// Fill up USB_OUT_CONTEXT.
+	//----------------------------------------------------------------------------
+	// Get index to out pipe from specified QueueID.
+#ifndef USE_ONE_PIPE
+	idx_pipe = txqueue2outpipe(priv,queue_index);
+#else
+	idx_pipe = 0x04;
+#endif
+#ifdef JOHN_DUMP_TXDESC
+	int i;
+	printk("<Tx descriptor>--rate %x---",rate);
+	for (i = 0; i < 8; i++)
+		printk("%8x ", tx[i]);
+	printk("\n");
+#endif
+	usb_fill_bulk_urb(tx_urb,priv->udev, usb_sndbulkpipe(priv->udev,idx_pipe), \
+			skb->data, skb->len, rtl8192_tx_isr, skb);
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	status = usb_submit_urb(tx_urb, GFP_ATOMIC);
+#else
+	status = usb_submit_urb(tx_urb);
+#endif
+
+	if (!status){
+		return 0;
+	}else{
+		DMESGE("Error TX CMD URB, error %d",
+				status);
+		return -1;
+	}
+}
+#endif
+
+/*
+ * Mapping Software/Hardware descriptor queue id to "Queue Select Field"
+ * in TxFwInfo data structure
+ * 2006.10.30 by Emily
+ *
+ * \param QUEUEID       Software Queue
+*/
+u8 MapHwQueueToFirmwareQueue(u8 QueueID)
+{
+	u8 QueueSelect = 0x0;       //defualt set to
+
+	switch(QueueID) {
+		case BE_QUEUE:
+			QueueSelect = QSLT_BE;  //or QSelect = pTcb->priority;
+			break;
+
+		case BK_QUEUE:
+			QueueSelect = QSLT_BK;  //or QSelect = pTcb->priority;
+			break;
+
+		case VO_QUEUE:
+			QueueSelect = QSLT_VO;  //or QSelect = pTcb->priority;
+			break;
+
+		case VI_QUEUE:
+			QueueSelect = QSLT_VI;  //or QSelect = pTcb->priority;
+			break;
+		case MGNT_QUEUE:
+			QueueSelect = QSLT_MGNT;
+			break;
+
+		case BEACON_QUEUE:
+			QueueSelect = QSLT_BEACON;
+			break;
+
+			// TODO: 2006.10.30 mark other queue selection until we verify it is OK
+			// TODO: Remove Assertions
+//#if (RTL819X_FPGA_VER & RTL819X_FPGA_GUANGAN_070502)
+		case TXCMD_QUEUE:
+			QueueSelect = QSLT_CMD;
+			break;
+//#endif
+		case HIGH_QUEUE:
+			QueueSelect = QSLT_HIGH;
+			break;
+
+		default:
+			RT_TRACE(COMP_ERR, "TransmitTCB(): Impossible Queue Selection: %d \n", QueueID);
+			break;
+	}
+	return QueueSelect;
+}
+
+#ifdef RTL8192SU
+u8 MRateToHwRate8190Pci(u8 rate)
+{
+	u8	ret = DESC92S_RATE1M;
+
+	switch(rate)
+	{
+		// CCK and OFDM non-HT rates
+	case MGN_1M:		ret = DESC92S_RATE1M;	break;
+	case MGN_2M:		ret = DESC92S_RATE2M;	break;
+	case MGN_5_5M:		ret = DESC92S_RATE5_5M;	break;
+	case MGN_11M:		ret = DESC92S_RATE11M;	break;
+	case MGN_6M:		ret = DESC92S_RATE6M;	break;
+	case MGN_9M:		ret = DESC92S_RATE9M;	break;
+	case MGN_12M:		ret = DESC92S_RATE12M;	break;
+	case MGN_18M:		ret = DESC92S_RATE18M;	break;
+	case MGN_24M:		ret = DESC92S_RATE24M;	break;
+	case MGN_36M:		ret = DESC92S_RATE36M;	break;
+	case MGN_48M:		ret = DESC92S_RATE48M;	break;
+	case MGN_54M:		ret = DESC92S_RATE54M;	break;
+
+		// HT rates since here
+	case MGN_MCS0:		ret = DESC92S_RATEMCS0;	break;
+	case MGN_MCS1:		ret = DESC92S_RATEMCS1;	break;
+	case MGN_MCS2:		ret = DESC92S_RATEMCS2;	break;
+	case MGN_MCS3:		ret = DESC92S_RATEMCS3;	break;
+	case MGN_MCS4:		ret = DESC92S_RATEMCS4;	break;
+	case MGN_MCS5:		ret = DESC92S_RATEMCS5;	break;
+	case MGN_MCS6:		ret = DESC92S_RATEMCS6;	break;
+	case MGN_MCS7:		ret = DESC92S_RATEMCS7;	break;
+	case MGN_MCS8:		ret = DESC92S_RATEMCS8;	break;
+	case MGN_MCS9:		ret = DESC92S_RATEMCS9;	break;
+	case MGN_MCS10:	ret = DESC92S_RATEMCS10;	break;
+	case MGN_MCS11:	ret = DESC92S_RATEMCS11;	break;
+	case MGN_MCS12:	ret = DESC92S_RATEMCS12;	break;
+	case MGN_MCS13:	ret = DESC92S_RATEMCS13;	break;
+	case MGN_MCS14:	ret = DESC92S_RATEMCS14;	break;
+	case MGN_MCS15:	ret = DESC92S_RATEMCS15;	break;
+
+	// Set the highest SG rate
+	case MGN_MCS0_SG:
+	case MGN_MCS1_SG:
+	case MGN_MCS2_SG:
+	case MGN_MCS3_SG:
+	case MGN_MCS4_SG:
+	case MGN_MCS5_SG:
+	case MGN_MCS6_SG:
+	case MGN_MCS7_SG:
+	case MGN_MCS8_SG:
+	case MGN_MCS9_SG:
+	case MGN_MCS10_SG:
+	case MGN_MCS11_SG:
+	case MGN_MCS12_SG:
+	case MGN_MCS13_SG:
+	case MGN_MCS14_SG:
+	case MGN_MCS15_SG:
+	{
+		ret = DESC92S_RATEMCS15_SG;
+		break;
+	}
+
+	default:		break;
+	}
+	return ret;
+}
+#else
+u8 MRateToHwRate8190Pci(u8 rate)
+{
+	u8  ret = DESC90_RATE1M;
+
+	switch(rate) {
+		case MGN_1M:    ret = DESC90_RATE1M;    break;
+		case MGN_2M:    ret = DESC90_RATE2M;    break;
+		case MGN_5_5M:  ret = DESC90_RATE5_5M;  break;
+		case MGN_11M:   ret = DESC90_RATE11M;   break;
+		case MGN_6M:    ret = DESC90_RATE6M;    break;
+		case MGN_9M:    ret = DESC90_RATE9M;    break;
+		case MGN_12M:   ret = DESC90_RATE12M;   break;
+		case MGN_18M:   ret = DESC90_RATE18M;   break;
+		case MGN_24M:   ret = DESC90_RATE24M;   break;
+		case MGN_36M:   ret = DESC90_RATE36M;   break;
+		case MGN_48M:   ret = DESC90_RATE48M;   break;
+		case MGN_54M:   ret = DESC90_RATE54M;   break;
+
+		// HT rate since here
+		case MGN_MCS0:  ret = DESC90_RATEMCS0;  break;
+		case MGN_MCS1:  ret = DESC90_RATEMCS1;  break;
+		case MGN_MCS2:  ret = DESC90_RATEMCS2;  break;
+		case MGN_MCS3:  ret = DESC90_RATEMCS3;  break;
+		case MGN_MCS4:  ret = DESC90_RATEMCS4;  break;
+		case MGN_MCS5:  ret = DESC90_RATEMCS5;  break;
+		case MGN_MCS6:  ret = DESC90_RATEMCS6;  break;
+		case MGN_MCS7:  ret = DESC90_RATEMCS7;  break;
+		case MGN_MCS8:  ret = DESC90_RATEMCS8;  break;
+		case MGN_MCS9:  ret = DESC90_RATEMCS9;  break;
+		case MGN_MCS10: ret = DESC90_RATEMCS10; break;
+		case MGN_MCS11: ret = DESC90_RATEMCS11; break;
+		case MGN_MCS12: ret = DESC90_RATEMCS12; break;
+		case MGN_MCS13: ret = DESC90_RATEMCS13; break;
+		case MGN_MCS14: ret = DESC90_RATEMCS14; break;
+		case MGN_MCS15: ret = DESC90_RATEMCS15; break;
+		case (0x80|0x20): ret = DESC90_RATEMCS32; break;
+
+		default:       break;
+	}
+	return ret;
+}
+#endif
+
+u8 QueryIsShort(u8 TxHT, u8 TxRate, cb_desc *tcb_desc)
+{
+	u8   tmp_Short;
+
+	tmp_Short = (TxHT==1)?((tcb_desc->bUseShortGI)?1:0):((tcb_desc->bUseShortPreamble)?1:0);
+
+	if(TxHT==1 && TxRate != DESC90_RATEMCS15)
+		tmp_Short = 0;
+
+	return tmp_Short;
+}
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20)
+static void tx_zero_isr(struct urb *tx_urb, struct pt_regs *reg)
+#else
+static void tx_zero_isr(struct urb *tx_urb)
+#endif
+{
+	return;
+}
+
+
+#ifdef RTL8192SU
+/*
+ * The tx procedure is just as following,  skb->cb will contain all the following
+ *information: * priority, morefrag, rate, &dev.
+ * */
+ //	<Note> Buffer format for 8192S Usb bulk out:
+//
+//  --------------------------------------------------
+//  | 8192S Usb Tx Desc | 802_11_MAC_header |    data          |
+//  --------------------------------------------------
+//  |  32 bytes           	  |       24 bytes             |0-2318 bytes|
+//  --------------------------------------------------
+//  |<------------ BufferLen ------------------------->|
+
+short rtl8192SU_tx(struct net_device *dev, struct sk_buff* skb)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	tx_desc_819x_usb *tx_desc = (tx_desc_819x_usb *)skb->data;
+	//tx_fwinfo_819x_usb *tx_fwinfo = (tx_fwinfo_819x_usb *)(skb->data + USB_HWDESC_HEADER_LEN);//92su del
+	struct usb_device *udev = priv->udev;
+	int pend;
+	int status;
+	struct urb *tx_urb = NULL, *tx_urb_zero = NULL;
+	//int urb_len;
+	unsigned int idx_pipe;
+	u16		MPDUOverhead = 0;
+ 	//RT_DEBUG_DATA(COMP_SEND, tcb_desc, sizeof(cb_desc));
+
+#if 0
+	/* Added by Annie for filling Len_Adjust field. 2005-12-14. */
+        RT_ENC_ALG  EncAlg = NO_Encryption;
+#endif
+
+
+	pend = atomic_read(&priv->tx_pending[tcb_desc->queue_index]);
+	/* we are locked here so the two atomic_read and inc are executed
+	 * without interleaves  * !!! For debug purpose 	  */
+	if( pend > MAX_TX_URB){
+		switch (tcb_desc->queue_index) {
+			case VO_PRIORITY:
+				priv->stats.txvodrop++;
+				break;
+			case VI_PRIORITY:
+				priv->stats.txvidrop++;
+				break;
+			case BE_PRIORITY:
+				priv->stats.txbedrop++;
+				break;
+			default://BK_PRIORITY
+				priv->stats.txbkdrop++;
+				break;
+		}
+		printk("To discard skb packet!\n");
+		dev_kfree_skb_any(skb);
+		return -1;
+	}
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
+#else
+	tx_urb = usb_alloc_urb(0);
+#endif
+	if(!tx_urb){
+		dev_kfree_skb_any(skb);
+		return -ENOMEM;
+	}
+
+	memset(tx_desc, 0, sizeof(tx_desc_819x_usb));
+
+
+#if RTL8192SU_FPGA_UNSPECIFIED_NETWORK
+		if(IsQoSDataFrame(skb->data))
+		{
+			tcb_desc->bAMPDUEnable = TRUE;
+			tx_desc->NonQos = 0;
+		}
+		else
+			tcb_desc->bAMPDUEnable = FALSE;
+
+		tcb_desc->bPacketBW = TRUE;
+		priv->CurrentChannelBW = HT_CHANNEL_WIDTH_20_40;
+#endif
+
+#if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
+		tx_desc->NonQos = (IsQoSDataFrame(skb->data)==TRUE)? 0:1;
+#endif
+
+	/* Fill Tx descriptor */
+	//memset(tx_fwinfo,0,sizeof(tx_fwinfo_819x_usb));
+
+	// This part can just fill to the first descriptor of the frame.
+	/* DWORD 0 */
+	tx_desc->TxHT = (tcb_desc->data_rate&0x80)?1:0;
+
+#ifdef RTL8192SU_DISABLE_CCK_RATE
+		if(tx_hal_is_cck_rate(tcb_desc->data_rate))
+			tcb_desc->data_rate = MGN_6M;
+#endif
+
+	tx_desc->TxRate = MRateToHwRate8190Pci(tcb_desc->data_rate);
+	//tx_desc->EnableCPUDur = tcb_desc->bTxEnableFwCalcDur;
+	tx_desc->TxShort = QueryIsShort(tx_desc->TxHT, tx_desc->TxRate, tcb_desc);
+
+
+	// Aggregation related
+	if(tcb_desc->bAMPDUEnable) {//AMPDU enabled
+		tx_desc->AllowAggregation = 1;
+		/* DWORD 1 */
+		//tx_fwinfo->RxMF = tcb_desc->ampdu_factor;
+		//tx_fwinfo->RxAMD = tcb_desc->ampdu_density&0x07;//ampdudensity
+	} else {
+		tx_desc->AllowAggregation = 0;
+		/* DWORD 1 */
+		//tx_fwinfo->RxMF = 0;
+		//tx_fwinfo->RxAMD = 0;
+	}
+
+	//
+	// <Roger_Notes> For AMPDU case, we must insert SSN into TX_DESC,
+	// FW according as this SSN to do necessary packet retry.
+	// 2008.06.06.
+	//
+	{
+		u8	*pSeq;
+		u16	Temp;
+		//pSeq = (u8 *)(VirtualAddress+USB_HWDESC_HEADER_LEN + FRAME_OFFSET_SEQUENCE);
+		pSeq = (u8 *)(skb->data+USB_HWDESC_HEADER_LEN + 22);
+		Temp = pSeq[0];
+		Temp <<= 12;
+		Temp |= (*(u16 *)pSeq)>>4;
+		tx_desc->Seq = Temp;
+	}
+
+	/* Protection mode related */
+	tx_desc->RTSEn = (tcb_desc->bRTSEnable)?1:0;
+	tx_desc->CTS2Self = (tcb_desc->bCTSEnable)?1:0;
+	tx_desc->RTSSTBC = (tcb_desc->bRTSSTBC)?1:0;
+	tx_desc->RTSHT = (tcb_desc->rts_rate&0x80)?1:0;
+	tx_desc->RTSRate =  MRateToHwRate8190Pci((u8)tcb_desc->rts_rate);
+	tx_desc->RTSSubcarrier = (tx_desc->RTSHT==0)?(tcb_desc->RTSSC):0;
+	tx_desc->RTSBW = (tx_desc->RTSHT==1)?((tcb_desc->bRTSBW)?1:0):0;
+	tx_desc->RTSShort = (tx_desc->RTSHT==0)?(tcb_desc->bRTSUseShortPreamble?1:0):\
+				(tcb_desc->bRTSUseShortGI?1:0);
+	//LZM 090219
+	tx_desc->DisRTSFB = 0;
+	tx_desc->RTSRateFBLmt = 0xf;
+
+	// <Roger_EXP> 2008.09.22. We disable RTS rate fallback temporarily.
+	//tx_desc->DisRTSFB = 0x01;
+
+	/* Set Bandwidth and sub-channel settings. */
+	if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
+	{
+		if(tcb_desc->bPacketBW) {
+			tx_desc->TxBandwidth = 1;
+			tx_desc->TxSubCarrier = 0;    //By SD3's Jerry suggestion, use duplicated mode
+		} else {
+			tx_desc->TxBandwidth = 0;
+			tx_desc->TxSubCarrier = priv->nCur40MhzPrimeSC;
+		}
+	} else {
+		tx_desc->TxBandwidth = 0;
+		tx_desc->TxSubCarrier = 0;
+	}
+
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+	if (tcb_desc->drv_agg_enable)
+	{
+		//tx_desc->Tx_INFO_RSVD = (tcb_desc->DrvAggrNum & 0x1f) << 1; //92su del
+	}
+#endif
+
+	//memset(tx_desc, 0, sizeof(tx_desc_819x_usb));
+	/* DWORD 0 */
+        tx_desc->LINIP = 0;
+        //tx_desc->CmdInit = 1; //92su del
+        tx_desc->Offset =  USB_HWDESC_HEADER_LEN;
+
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+	if (tcb_desc->drv_agg_enable) {
+		tx_desc->PktSize = tcb_desc->pkt_size;//FIXLZM
+	} else
+#endif
+	{
+		tx_desc->PktSize = (skb->len - USB_HWDESC_HEADER_LEN) & 0xffff;
+	}
+
+	/*DWORD 1*/
+	//tx_desc->SecCAMID= 0;//92su del
+	tx_desc->RaBRSRID= tcb_desc->RATRIndex;
+//#ifdef RTL8192S_PREPARE_FOR_NORMAL_RELEASE
+#if 0//LZM 090219
+	tx_desc->RaBRSRID= 1;
+#endif
+
+#if 0
+	/* Fill security related */
+	if( pTcb->bEncrypt && !Adapter->MgntInfo.SecurityInfo.SWTxEncryptFlag)
+	{
+		EncAlg = SecGetEncryptionOverhead(
+				Adapter,
+				&EncryptionMPDUHeadOverhead,
+				&EncryptionMPDUTailOverhead,
+				NULL,
+				NULL,
+				FALSE,
+				FALSE);
+		//2004/07/22, kcwu, EncryptionMPDUHeadOverhead has been added in previous code
+		//MPDUOverhead = EncryptionMPDUHeadOverhead + EncryptionMPDUTailOverhead;
+		MPDUOverhead = EncryptionMPDUTailOverhead;
+		tx_desc->NoEnc = 0;
+		RT_TRACE(COMP_SEC, DBG_LOUD, ("******We in the loop SecCAMID is %d SecDescAssign is %d The Sec is %d********\n",tx_desc->SecCAMID,tx_desc->SecDescAssign,EncAlg));
+		//CamDumpAll(Adapter);
+	}
+	else
+#endif
+	{
+		MPDUOverhead = 0;
+		//tx_desc->NoEnc = 1;//92su del
+	}
+#if 0
+	switch(EncAlg){
+		case NO_Encryption:
+			tx_desc->SecType = 0x0;
+			break;
+		case WEP40_Encryption:
+		case WEP104_Encryption:
+			tx_desc->SecType = 0x1;
+			break;
+		case TKIP_Encryption:
+			tx_desc->SecType = 0x2;
+			break;
+		case AESCCMP_Encryption:
+			tx_desc->SecType = 0x3;
+			break;
+		default:
+			tx_desc->SecType = 0x0;
+			break;
+	}
+#else
+	tx_desc->SecType = 0x0;
+#endif
+		if (tcb_desc->bHwSec)
+			{
+				switch (priv->ieee80211->pairwise_key_type)
+				{
+					case KEY_TYPE_WEP40:
+					case KEY_TYPE_WEP104:
+						 tx_desc->SecType = 0x1;
+						 //tx_desc->NoEnc = 0;//92su del
+						 break;
+					case KEY_TYPE_TKIP:
+						 tx_desc->SecType = 0x2;
+						 //tx_desc->NoEnc = 0;//92su del
+						 break;
+					case KEY_TYPE_CCMP:
+						 tx_desc->SecType = 0x3;
+						 //tx_desc->NoEnc = 0;//92su del
+						 break;
+					case KEY_TYPE_NA:
+						 tx_desc->SecType = 0x0;
+						 //tx_desc->NoEnc = 1;//92su del
+						 break;
+					default:
+						 tx_desc->SecType = 0x0;
+						 //tx_desc->NoEnc = 1;//92su del
+						 break;
+				}
+			}
+
+	//tx_desc->TxFWInfoSize =  sizeof(tx_fwinfo_819x_usb);//92su del
+
+
+	tx_desc->USERATE = tcb_desc->bTxUseDriverAssingedRate;
+	tx_desc->DISFB = tcb_desc->bTxDisableRateFallBack;
+	tx_desc->DataRateFBLmt = 0x1F;// Alwasy enable all rate fallback range
+
+	tx_desc->QueueSelect = MapHwQueueToFirmwareQueue(tcb_desc->queue_index);
+
+
+        /* Fill fields that are required to be initialized in all of the descriptors */
+        //DWORD 0
+#if 0
+        tx_desc->FirstSeg = (tcb_desc->bFirstSeg)? 1:0;
+        tx_desc->LastSeg = (tcb_desc->bLastSeg)?1:0;
+#else
+        tx_desc->FirstSeg = 1;
+        tx_desc->LastSeg = 1;
+#endif
+        tx_desc->OWN = 1;
+
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+	if (tcb_desc->drv_agg_enable) {
+		tx_desc->TxBufferSize = tcb_desc->pkt_size + sizeof(tx_fwinfo_819x_usb);
+	} else
+#endif
+	{
+		//DWORD 2
+		//tx_desc->TxBufferSize = (u32)(skb->len - USB_HWDESC_HEADER_LEN);
+		tx_desc->TxBufferSize = (u32)(skb->len);//92su mod FIXLZM
+	}
+
+#if 0
+	RT_TRACE(COMP_FPGA, DBG_LOUD, ("(1)TxFillDescriptor8192SUsb(): DataRate(%#x)\n", pTcb->DataRate));
+	RT_TRACE(COMP_FPGA, DBG_LOUD, ("(2)TxFillDescriptor8192SUsb(): bTxUseDriverAssingedRate(%#x)\n", pTcb->bTxUseDriverAssingedRate));
+	RT_TRACE(COMP_FPGA, DBG_LOUD, ("(3)TxFillDescriptor8192SUsb(): bAMPDUEnable(%d)\n", pTcb->bAMPDUEnable));
+	RT_TRACE(COMP_FPGA, DBG_LOUD, ("(4)TxFillDescriptor8192SUsb(): bRTSEnable(%d)\n", pTcb->bRTSEnable));
+	RT_TRACE(COMP_FPGA, DBG_LOUD, ("(5)TxFillDescriptor8192SUsb(): RTSRate(%#x)\n", pTcb->RTSRate));
+	RT_TRACE(COMP_FPGA, DBG_LOUD, ("(6)TxFillDescriptor8192SUsb(): bCTSEnable(%d)\n", pTcb->bCTSEnable));
+	RT_TRACE(COMP_FPGA, DBG_LOUD, ("(7)TxFillDescriptor8192SUsb(): bUseShortGI(%d)\n", pTcb->bUseShortGI));
+	RT_TRACE(COMP_FPGA, DBG_LOUD, ("(8)TxFillDescriptor8192SUsb(): bPacketBW(%d)\n", pTcb->bPacketBW));
+	RT_TRACE(COMP_FPGA, DBG_LOUD, ("(9)TxFillDescriptor8192SUsb(): CurrentChannelBW(%d)\n", pHalData->CurrentChannelBW));
+	RT_TRACE(COMP_FPGA, DBG_LOUD, ("(10)TxFillDescriptor8192SUsb(): bTxDisableRateFallBack(%d)\n", pTcb->bTxDisableRateFallBack));
+	RT_TRACE(COMP_FPGA, DBG_LOUD, ("(11)TxFillDescriptor8192SUsb(): RATRIndex(%d)\n", pTcb->RATRIndex));
+#endif
+
+	/* Get index to out pipe from specified QueueID */
+	idx_pipe = txqueue2outpipe(priv,tcb_desc->queue_index);
+	//printk("=============>%s queue_index:%d, outpipe:%d\n", __func__,tcb_desc->queue_index,priv->RtOutPipes[idx_pipe]);
+
+	//RT_DEBUG_DATA(COMP_SEND,tx_fwinfo,sizeof(tx_fwinfo_819x_usb));
+	//RT_DEBUG_DATA(COMP_SEND,tx_desc,sizeof(tx_desc_819x_usb));
+
+	/* To submit bulk urb */
+	usb_fill_bulk_urb(tx_urb,
+				    udev,
+				    usb_sndbulkpipe(udev,priv->RtOutPipes[idx_pipe]),
+				    skb->data,
+				    skb->len, rtl8192_tx_isr, skb);
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	status = usb_submit_urb(tx_urb, GFP_ATOMIC);
+#else
+	status = usb_submit_urb(tx_urb);
+#endif
+	if (!status){
+//we need to send 0 byte packet whenever 512N bytes/64N(HIGN SPEED/NORMAL SPEED) bytes packet has been transmitted. Otherwise, it will be halt to wait for another packet. WB. 2008.08.27
+		bool bSend0Byte = false;
+		u8 zero = 0;
+		if(udev->speed == USB_SPEED_HIGH)
+		{
+			if (skb->len > 0 && skb->len % 512 == 0)
+				bSend0Byte = true;
+		}
+		else
+		{
+			if (skb->len > 0 && skb->len % 64 == 0)
+				bSend0Byte = true;
+		}
+		if (bSend0Byte)
+		{
+#if 1
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+			tx_urb_zero = usb_alloc_urb(0,GFP_ATOMIC);
+#else
+			tx_urb_zero = usb_alloc_urb(0);
+#endif
+			if(!tx_urb_zero){
+				RT_TRACE(COMP_ERR, "can't alloc urb for zero byte\n");
+				return -ENOMEM;
+			}
+			usb_fill_bulk_urb(tx_urb_zero,udev,
+					usb_sndbulkpipe(udev,idx_pipe), &zero,
+					0, tx_zero_isr, dev);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+			status = usb_submit_urb(tx_urb_zero, GFP_ATOMIC);
+#else
+			status = usb_submit_urb(tx_urb_zero);
+#endif
+			if (status){
+			RT_TRACE(COMP_ERR, "Error TX URB for zero byte %d, error %d", atomic_read(&priv->tx_pending[tcb_desc->queue_index]), status);
+			return -1;
+			}
+#endif
+		}
+		dev->trans_start = jiffies;
+		atomic_inc(&priv->tx_pending[tcb_desc->queue_index]);
+		return 0;
+	}else{
+		RT_TRACE(COMP_ERR, "Error TX URB %d, error %d", atomic_read(&priv->tx_pending[tcb_desc->queue_index]),
+				status);
+		return -1;
+	}
+}
+#else
+
+/*
+ * The tx procedure is just as following,
+ * skb->cb will contain all the following information,
+ * priority, morefrag, rate, &dev.
+ * */
+short rtl8192_tx(struct net_device *dev, struct sk_buff* skb)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
+	tx_desc_819x_usb *tx_desc = (tx_desc_819x_usb *)skb->data;
+	tx_fwinfo_819x_usb *tx_fwinfo = (tx_fwinfo_819x_usb *)(skb->data + USB_HWDESC_HEADER_LEN);
+	struct usb_device *udev = priv->udev;
+	int pend;
+	int status;
+	struct urb *tx_urb = NULL, *tx_urb_zero = NULL;
+	//int urb_len;
+	unsigned int idx_pipe;
+//	RT_DEBUG_DATA(COMP_SEND, tcb_desc, sizeof(cb_desc));
+#if 0
+	/* Added by Annie for filling Len_Adjust field. 2005-12-14. */
+        RT_ENC_ALG  EncAlg = NO_Encryption;
+#endif
+//	printk("=============> %s\n", __FUNCTION__);
+	pend = atomic_read(&priv->tx_pending[tcb_desc->queue_index]);
+	/* we are locked here so the two atomic_read and inc are executed
+	 * without interleaves
+	 * !!! For debug purpose
+	 */
+	if( pend > MAX_TX_URB){
+#if 0
+		switch (tcb_desc->queue_index) {
+			case VO_PRIORITY:
+				priv->stats.txvodrop++;
+				break;
+			case VI_PRIORITY:
+				priv->stats.txvidrop++;
+				break;
+			case BE_PRIORITY:
+				priv->stats.txbedrop++;
+				break;
+			default://BK_PRIORITY
+				priv->stats.txbkdrop++;
+				break;
+		}
+#endif
+		printk("To discard skb packet!\n");
+		dev_kfree_skb_any(skb);
+		return -1;
+	}
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	tx_urb = usb_alloc_urb(0,GFP_ATOMIC);
+#else
+	tx_urb = usb_alloc_urb(0);
+#endif
+	if(!tx_urb){
+		dev_kfree_skb_any(skb);
+		return -ENOMEM;
+	}
+
+	/* Fill Tx firmware info */
+	memset(tx_fwinfo,0,sizeof(tx_fwinfo_819x_usb));
+	/* DWORD 0 */
+	tx_fwinfo->TxHT = (tcb_desc->data_rate&0x80)?1:0;
+	tx_fwinfo->TxRate = MRateToHwRate8190Pci(tcb_desc->data_rate);
+	tx_fwinfo->EnableCPUDur = tcb_desc->bTxEnableFwCalcDur;
+	tx_fwinfo->Short = QueryIsShort(tx_fwinfo->TxHT, tx_fwinfo->TxRate, tcb_desc);
+	if(tcb_desc->bAMPDUEnable) {//AMPDU enabled
+		tx_fwinfo->AllowAggregation = 1;
+		/* DWORD 1 */
+		tx_fwinfo->RxMF = tcb_desc->ampdu_factor;
+		tx_fwinfo->RxAMD = tcb_desc->ampdu_density&0x07;//ampdudensity
+	} else {
+		tx_fwinfo->AllowAggregation = 0;
+		/* DWORD 1 */
+		tx_fwinfo->RxMF = 0;
+		tx_fwinfo->RxAMD = 0;
+	}
+
+	/* Protection mode related */
+	tx_fwinfo->RtsEnable = (tcb_desc->bRTSEnable)?1:0;
+	tx_fwinfo->CtsEnable = (tcb_desc->bCTSEnable)?1:0;
+	tx_fwinfo->RtsSTBC = (tcb_desc->bRTSSTBC)?1:0;
+	tx_fwinfo->RtsHT = (tcb_desc->rts_rate&0x80)?1:0;
+	tx_fwinfo->RtsRate =  MRateToHwRate8190Pci((u8)tcb_desc->rts_rate);
+	tx_fwinfo->RtsSubcarrier = (tx_fwinfo->RtsHT==0)?(tcb_desc->RTSSC):0;
+	tx_fwinfo->RtsBandwidth = (tx_fwinfo->RtsHT==1)?((tcb_desc->bRTSBW)?1:0):0;
+	tx_fwinfo->RtsShort = (tx_fwinfo->RtsHT==0)?(tcb_desc->bRTSUseShortPreamble?1:0):\
+				(tcb_desc->bRTSUseShortGI?1:0);
+
+	/* Set Bandwidth and sub-channel settings. */
+	if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40)
+	{
+		if(tcb_desc->bPacketBW) {
+			tx_fwinfo->TxBandwidth = 1;
+			tx_fwinfo->TxSubCarrier = 0;    //By SD3's Jerry suggestion, use duplicated mode
+		} else {
+			tx_fwinfo->TxBandwidth = 0;
+			tx_fwinfo->TxSubCarrier = priv->nCur40MhzPrimeSC;
+		}
+	} else {
+		tx_fwinfo->TxBandwidth = 0;
+		tx_fwinfo->TxSubCarrier = 0;
+	}
+
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+	if (tcb_desc->drv_agg_enable)
+	{
+		tx_fwinfo->Tx_INFO_RSVD = (tcb_desc->DrvAggrNum & 0x1f) << 1;
+	}
+#endif
+	/* Fill Tx descriptor */
+	memset(tx_desc, 0, sizeof(tx_desc_819x_usb));
+	/* DWORD 0 */
+        tx_desc->LINIP = 0;
+        tx_desc->CmdInit = 1;
+        tx_desc->Offset =  sizeof(tx_fwinfo_819x_usb) + 8;
+
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+	if (tcb_desc->drv_agg_enable) {
+		tx_desc->PktSize = tcb_desc->pkt_size;
+	} else
+#endif
+	{
+		tx_desc->PktSize = (skb->len - TX_PACKET_SHIFT_BYTES) & 0xffff;
+	}
+
+	/*DWORD 1*/
+	tx_desc->SecCAMID= 0;
+	tx_desc->RATid = tcb_desc->RATRIndex;
+#if 0
+	/* Fill security related */
+	if( pTcb->bEncrypt && !Adapter->MgntInfo.SecurityInfo.SWTxEncryptFlag)
+	{
+		EncAlg = SecGetEncryptionOverhead(
+				Adapter,
+				&EncryptionMPDUHeadOverhead,
+				&EncryptionMPDUTailOverhead,
+				NULL,
+				NULL,
+				FALSE,
+				FALSE);
+		//2004/07/22, kcwu, EncryptionMPDUHeadOverhead has been added in previous code
+		//MPDUOverhead = EncryptionMPDUHeadOverhead + EncryptionMPDUTailOverhead;
+		MPDUOverhead = EncryptionMPDUTailOverhead;
+		tx_desc->NoEnc = 0;
+		RT_TRACE(COMP_SEC, DBG_LOUD, ("******We in the loop SecCAMID is %d SecDescAssign is %d The Sec is %d********\n",tx_desc->SecCAMID,tx_desc->SecDescAssign,EncAlg));
+		//CamDumpAll(Adapter);
+	}
+	else
+#endif
+	{
+		//MPDUOverhead = 0;
+		tx_desc->NoEnc = 1;
+	}
+#if 0
+	switch(EncAlg){
+		case NO_Encryption:
+			tx_desc->SecType = 0x0;
+			break;
+		case WEP40_Encryption:
+		case WEP104_Encryption:
+			tx_desc->SecType = 0x1;
+			break;
+		case TKIP_Encryption:
+			tx_desc->SecType = 0x2;
+			break;
+		case AESCCMP_Encryption:
+			tx_desc->SecType = 0x3;
+			break;
+		default:
+			tx_desc->SecType = 0x0;
+			break;
+	}
+#else
+	tx_desc->SecType = 0x0;
+#endif
+		if (tcb_desc->bHwSec)
+			{
+				switch (priv->ieee80211->pairwise_key_type)
+				{
+					case KEY_TYPE_WEP40:
+					case KEY_TYPE_WEP104:
+						 tx_desc->SecType = 0x1;
+						 tx_desc->NoEnc = 0;
+						 break;
+					case KEY_TYPE_TKIP:
+						 tx_desc->SecType = 0x2;
+						 tx_desc->NoEnc = 0;
+						 break;
+					case KEY_TYPE_CCMP:
+						 tx_desc->SecType = 0x3;
+						 tx_desc->NoEnc = 0;
+						 break;
+					case KEY_TYPE_NA:
+						 tx_desc->SecType = 0x0;
+						 tx_desc->NoEnc = 1;
+						 break;
+				}
+			}
+
+	tx_desc->QueueSelect = MapHwQueueToFirmwareQueue(tcb_desc->queue_index);
+	tx_desc->TxFWInfoSize =  sizeof(tx_fwinfo_819x_usb);
+
+	tx_desc->DISFB = tcb_desc->bTxDisableRateFallBack;
+	tx_desc->USERATE = tcb_desc->bTxUseDriverAssingedRate;
+
+        /* Fill fields that are required to be initialized in all of the descriptors */
+        //DWORD 0
+#if 0
+        tx_desc->FirstSeg = (tcb_desc->bFirstSeg)? 1:0;
+        tx_desc->LastSeg = (tcb_desc->bLastSeg)?1:0;
+#else
+        tx_desc->FirstSeg = 1;
+        tx_desc->LastSeg = 1;
+#endif
+        tx_desc->OWN = 1;
+
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+	if (tcb_desc->drv_agg_enable) {
+		tx_desc->TxBufferSize = tcb_desc->pkt_size + sizeof(tx_fwinfo_819x_usb);
+	} else
+#endif
+	{
+		//DWORD 2
+		tx_desc->TxBufferSize = (u32)(skb->len - USB_HWDESC_HEADER_LEN);
+	}
+	/* Get index to out pipe from specified QueueID */
+#ifndef USE_ONE_PIPE
+	idx_pipe = txqueue2outpipe(priv,tcb_desc->queue_index);
+#else
+	idx_pipe = 0x5;
+#endif
+
+	//RT_DEBUG_DATA(COMP_SEND,tx_fwinfo,sizeof(tx_fwinfo_819x_usb));
+	//RT_DEBUG_DATA(COMP_SEND,tx_desc,sizeof(tx_desc_819x_usb));
+
+	/* To submit bulk urb */
+	usb_fill_bulk_urb(tx_urb,udev,
+			usb_sndbulkpipe(udev,idx_pipe), skb->data,
+			skb->len, rtl8192_tx_isr, skb);
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	status = usb_submit_urb(tx_urb, GFP_ATOMIC);
+#else
+	status = usb_submit_urb(tx_urb);
+#endif
+	if (!status){
+//we need to send 0 byte packet whenever 512N bytes/64N(HIGN SPEED/NORMAL SPEED) bytes packet has been transmitted. Otherwise, it will be halt to wait for another packet. WB. 2008.08.27
+		bool bSend0Byte = false;
+		u8 zero = 0;
+		if(udev->speed == USB_SPEED_HIGH)
+		{
+			if (skb->len > 0 && skb->len % 512 == 0)
+				bSend0Byte = true;
+		}
+		else
+		{
+			if (skb->len > 0 && skb->len % 64 == 0)
+				bSend0Byte = true;
+		}
+		if (bSend0Byte)
+		{
+#if 1
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+			tx_urb_zero = usb_alloc_urb(0,GFP_ATOMIC);
+#else
+			tx_urb_zero = usb_alloc_urb(0);
+#endif
+			if(!tx_urb_zero){
+				RT_TRACE(COMP_ERR, "can't alloc urb for zero byte\n");
+				return -ENOMEM;
+			}
+			usb_fill_bulk_urb(tx_urb_zero,udev,
+					usb_sndbulkpipe(udev,idx_pipe), &zero,
+					0, tx_zero_isr, dev);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+			status = usb_submit_urb(tx_urb_zero, GFP_ATOMIC);
+#else
+			status = usb_submit_urb(tx_urb_zero);
+#endif
+			if (status){
+			RT_TRACE(COMP_ERR, "Error TX URB for zero byte %d, error %d", atomic_read(&priv->tx_pending[tcb_desc->queue_index]), status);
+			return -1;
+			}
+#endif
+		}
+		dev->trans_start = jiffies;
+		atomic_inc(&priv->tx_pending[tcb_desc->queue_index]);
+		return 0;
+	}else{
+		RT_TRACE(COMP_ERR, "Error TX URB %d, error %d", atomic_read(&priv->tx_pending[tcb_desc->queue_index]),
+				status);
+		return -1;
+	}
+}
+#endif
+
+#if 0
+void rtl8192_set_rate(struct net_device *dev)
+{
+	int i;
+	u16 word;
+	int basic_rate,min_rr_rate,max_rr_rate;
+
+//	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	//if (ieee80211_is_54g(priv->ieee80211->current_network) &&
+//		priv->ieee80211->state == IEEE80211_LINKED){
+	basic_rate = ieeerate2rtlrate(240);
+	min_rr_rate = ieeerate2rtlrate(60);
+	max_rr_rate = ieeerate2rtlrate(240);
+
+//
+//	}else{
+//		basic_rate = ieeerate2rtlrate(20);
+//		min_rr_rate = ieeerate2rtlrate(10);
+//		max_rr_rate = ieeerate2rtlrate(110);
+//	}
+
+	write_nic_byte(dev, RESP_RATE,
+			max_rr_rate<<MAX_RESP_RATE_SHIFT| min_rr_rate<<MIN_RESP_RATE_SHIFT);
+
+	//word  = read_nic_word(dev, BRSR);
+	word  = read_nic_word(dev, BRSR_8187);
+	word &= ~BRSR_MBR_8185;
+
+
+	for(i=0;i<=basic_rate;i++)
+		word |= (1<<i);
+
+	//write_nic_word(dev, BRSR, word);
+	write_nic_word(dev, BRSR_8187, word);
+	//DMESG("RR:%x BRSR: %x", read_nic_byte(dev,RESP_RATE), read_nic_word(dev,BRSR));
+}
+#endif
+
+
+#ifdef RTL8192SU
+void rtl8192SU_net_update(struct net_device *dev)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+	struct ieee80211_network *net = &priv->ieee80211->current_network;
+	//u16 BcnTimeCfg = 0, BcnCW = 6, BcnIFS = 0xf;
+	u16 rate_config = 0;
+	u32 regTmp = 0;
+	u8 rateIndex = 0;
+	u8	retrylimit = 0x30;
+	u16 cap = net->capability;
+
+	priv->short_preamble = cap & WLAN_CAPABILITY_SHORT_PREAMBLE;
+
+//HW_VAR_BASIC_RATE
+	//update Basic rate: RR, BRSR
+	rtl8192_config_rate(dev, &rate_config);	//HalSetBrateCfg
+
+#ifdef RTL8192SU_DISABLE_CCK_RATE
+	priv->basic_rate = rate_config  = rate_config & 0x150; // Disable CCK 11M, 5.5M, 2M, and 1M rates.
+#else
+	priv->basic_rate = rate_config  = rate_config & 0x15f;
+#endif
+
+	// Set RRSR rate table.
+	write_nic_byte(dev, RRSR, rate_config&0xff);
+	write_nic_byte(dev, RRSR+1, (rate_config>>8)&0xff);
+
+	// Set RTS initial rate
+	while(rate_config > 0x1)
+	{
+		rate_config = (rate_config>> 1);
+		rateIndex++;
+	}
+	write_nic_byte(dev, INIRTSMCS_SEL, rateIndex);
+//HW_VAR_BASIC_RATE
+
+	//set ack preample
+	regTmp = (priv->nCur40MhzPrimeSC) << 5;
+	if (priv->short_preamble)
+		regTmp |= 0x80;
+	write_nic_byte(dev, RRSR+2, regTmp);
+
+	write_nic_dword(dev,BSSIDR,((u32*)net->bssid)[0]);
+	write_nic_word(dev,BSSIDR+4,((u16*)net->bssid)[2]);
+
+	write_nic_word(dev, BCN_INTERVAL, net->beacon_interval);
+	//2008.10.24 added by tynli for beacon changed.
+	PHY_SetBeaconHwReg( dev, net->beacon_interval);
+
+	rtl8192_update_cap(dev, cap);
+
+	if (ieee->iw_mode == IW_MODE_ADHOC){
+		retrylimit = 7;
+		//we should enable ibss interrupt here, but disable it temporarily
+		if (0){
+			priv->irq_mask |= (IMR_BcnInt | IMR_BcnInt | IMR_TBDOK | IMR_TBDER);
+			//rtl8192_irq_disable(dev);
+			//rtl8192_irq_enable(dev);
+		}
+	}
+	else{
+		if (0){
+			priv->irq_mask &= ~(IMR_BcnInt | IMR_BcnInt | IMR_TBDOK | IMR_TBDER);
+			//rtl8192_irq_disable(dev);
+			//rtl8192_irq_enable(dev);
+		}
+	}
+
+	priv->ShortRetryLimit = priv->LongRetryLimit = retrylimit;
+
+	write_nic_word(dev, 	RETRY_LIMIT,
+				retrylimit << RETRY_LIMIT_SHORT_SHIFT | \
+				retrylimit << RETRY_LIMIT_LONG_SHIFT);
+}
+
+void rtl8192SU_update_ratr_table(struct net_device* dev)
+{
+		struct r8192_priv* priv = ieee80211_priv(dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+	u8* pMcsRate = ieee->dot11HTOperationalRateSet;
+	//struct ieee80211_network *net = &ieee->current_network;
+	u32 ratr_value = 0;
+
+	u8 rate_index = 0;
+	int WirelessMode = ieee->mode;
+	u8 MimoPs = ieee->pHTInfo->PeerMimoPs;
+
+	u8 bNMode = 0;
+
+	rtl8192_config_rate(dev, (u16*)(&ratr_value));
+	ratr_value |= (*(u16*)(pMcsRate)) << 12;
+
+	//switch (ieee->mode)
+	switch (WirelessMode)
+	{
+		case IEEE_A:
+			ratr_value &= 0x00000FF0;
+			break;
+		case IEEE_B:
+			ratr_value &= 0x0000000D;
+			break;
+		case IEEE_G:
+			ratr_value &= 0x00000FF5;
+			break;
+		case IEEE_N_24G:
+		case IEEE_N_5G:
+		{
+			bNMode = 1;
+
+			if (MimoPs == 0) //MIMO_PS_STATIC
+					{
+				ratr_value &= 0x0007F005;
+			}
+			else
+			{	// MCS rate only => for 11N mode.
+				u32	ratr_mask;
+
+				// 1T2R or 1T1R, Spatial Stream 2 should be disabled
+				if (	priv->rf_type == RF_1T2R ||
+					priv->rf_type == RF_1T1R ||
+					(ieee->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_TX_2SS) )
+						ratr_mask = 0x000ff005;
+					else
+						ratr_mask = 0x0f0ff005;
+
+				if((ieee->pHTInfo->bCurTxBW40MHz) &&
+				    !(ieee->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_TX_40_MHZ))
+					ratr_mask |= 0x00000010; // Set 6MBps
+
+				// Select rates for rate adaptive mechanism.
+					ratr_value &= ratr_mask;
+					}
+			}
+			break;
+		default:
+			if(0)
+			{
+				if(priv->rf_type == RF_1T2R)	// 1T2R, Spatial Stream 2 should be disabled
+				{
+				ratr_value &= 0x000ff0f5;
+				}
+				else
+				{
+				ratr_value &= 0x0f0ff0f5;
+				}
+			}
+			//printk("====>%s(), mode is not correct:%x\n", __FUNCTION__, ieee->mode);
+			break;
+	}
+
+#ifdef RTL8192SU_DISABLE_CCK_RATE
+	ratr_value &= 0x0FFFFFF0;
+#else
+	ratr_value &= 0x0FFFFFFF;
+#endif
+
+	// Get MAX MCS available.
+	if (   (bNMode && ((ieee->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_SHORT_GI)==0)) &&
+		((ieee->pHTInfo->bCurBW40MHz && ieee->pHTInfo->bCurShortGI40MHz) ||
+	        (!ieee->pHTInfo->bCurBW40MHz && ieee->pHTInfo->bCurShortGI20MHz)))
+	{
+		u8 shortGI_rate = 0;
+		u32 tmp_ratr_value = 0;
+		ratr_value |= 0x10000000;//???
+		tmp_ratr_value = (ratr_value>>12);
+		for(shortGI_rate=15; shortGI_rate>0; shortGI_rate--)
+		{
+			if((1<<shortGI_rate) & tmp_ratr_value)
+				break;
+		}
+		shortGI_rate = (shortGI_rate<<12)|(shortGI_rate<<8)|(shortGI_rate<<4)|(shortGI_rate);
+		write_nic_byte(dev, SG_RATE, shortGI_rate);
+		//printk("==>SG_RATE:%x\n", read_nic_byte(dev, SG_RATE));
+	}
+	write_nic_dword(dev, ARFR0+rate_index*4, ratr_value);
+	printk("=============>ARFR0+rate_index*4:%#x\n", ratr_value);
+
+	//2 UFWP
+	if (ratr_value & 0xfffff000){
+		//printk("===>set to N mode\n");
+		HalSetFwCmd8192S(dev, FW_CMD_RA_REFRESH_N);
+	}
+	else	{
+		//printk("===>set to B/G mode\n");
+		HalSetFwCmd8192S(dev, FW_CMD_RA_REFRESH_BG);
+	}
+}
+
+void rtl8192SU_link_change(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+	//unsigned long flags;
+	u32 reg = 0;
+
+	printk("=====>%s 1\n", __func__);
+	reg = read_nic_dword(dev, RCR);
+
+	if (ieee->state == IEEE80211_LINKED)
+	{
+
+		rtl8192SU_net_update(dev);
+		rtl8192SU_update_ratr_table(dev);
+		ieee->SetFwCmdHandler(dev, FW_CMD_HIGH_PWR_ENABLE);
+		priv->ReceiveConfig = reg |= RCR_CBSSID;
+
+	}else{
+		priv->ReceiveConfig = reg &= ~RCR_CBSSID;
+
+	}
+
+	write_nic_dword(dev, RCR, reg);
+	rtl8192_update_msr(dev);
+
+	printk("<=====%s 2\n", __func__);
+}
+#else
+extern void rtl8192_update_ratr_table(struct net_device* dev);
+void rtl8192_link_change(struct net_device *dev)
+{
+//	int i;
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+	//write_nic_word(dev, BCN_INTR_ITV, net->beacon_interval);
+	if (ieee->state == IEEE80211_LINKED)
+	{
+		rtl8192_net_update(dev);
+		rtl8192_update_ratr_table(dev);
+#if 1
+		//add this as in pure N mode, wep encryption will use software way, but there is no chance to set this as wep will not set group key in wext. WB.2008.07.08
+		if ((KEY_TYPE_WEP40 == ieee->pairwise_key_type) || (KEY_TYPE_WEP104 == ieee->pairwise_key_type))
+		EnableHWSecurityConfig8192(dev);
+#endif
+	}
+	/*update timing params*/
+//	RT_TRACE(COMP_CH, "========>%s(), chan:%d\n", __FUNCTION__, priv->chan);
+//	rtl8192_set_chan(dev, priv->chan);
+	 if (ieee->iw_mode == IW_MODE_INFRA || ieee->iw_mode == IW_MODE_ADHOC)
+        {
+                u32 reg = 0;
+                reg = read_nic_dword(dev, RCR);
+                if (priv->ieee80211->state == IEEE80211_LINKED)
+                        priv->ReceiveConfig = reg |= RCR_CBSSID;
+                else
+                        priv->ReceiveConfig = reg &= ~RCR_CBSSID;
+                write_nic_dword(dev, RCR, reg);
+        }
+
+//	rtl8192_set_rxconf(dev);
+}
+#endif
+
+static struct ieee80211_qos_parameters def_qos_parameters = {
+        {3,3,3,3},/* cw_min */
+        {7,7,7,7},/* cw_max */
+        {2,2,2,2},/* aifs */
+        {0,0,0,0},/* flags */
+        {0,0,0,0} /* tx_op_limit */
+};
+
+
+#if LINUX_VERSION_CODE >=KERNEL_VERSION(2,6,20)
+void rtl8192_update_beacon(struct work_struct * work)
+{
+        struct r8192_priv *priv = container_of(work, struct r8192_priv, update_beacon_wq.work);
+        struct net_device *dev = priv->ieee80211->dev;
+#else
+void rtl8192_update_beacon(struct net_device *dev)
+{
+        struct r8192_priv *priv = ieee80211_priv(dev);
+#endif
+ 	struct ieee80211_device* ieee = priv->ieee80211;
+	struct ieee80211_network* net = &ieee->current_network;
+
+	if (ieee->pHTInfo->bCurrentHTSupport)
+		HTUpdateSelfAndPeerSetting(ieee, net);
+	ieee->pHTInfo->bCurrentRT2RTLongSlotTime = net->bssht.bdRT2RTLongSlotTime;
+	// Joseph test for turbo mode with AP
+	ieee->pHTInfo->RT2RT_HT_Mode = net->bssht.RT2RT_HT_Mode;
+	rtl8192_update_cap(dev, net->capability);
+}
+/*
+* background support to run QoS activate functionality
+*/
+int WDCAPARA_ADD[] = {EDCAPARA_BE,EDCAPARA_BK,EDCAPARA_VI,EDCAPARA_VO};
+#if LINUX_VERSION_CODE >=KERNEL_VERSION(2,6,20)
+void rtl8192_qos_activate(struct work_struct * work)
+{
+        struct r8192_priv *priv = container_of(work, struct r8192_priv, qos_activate);
+        struct net_device *dev = priv->ieee80211->dev;
+#else
+void rtl8192_qos_activate(struct net_device *dev)
+{
+        struct r8192_priv *priv = ieee80211_priv(dev);
+#endif
+        struct ieee80211_qos_parameters *qos_parameters = &priv->ieee80211->current_network.qos_data.parameters;
+        u8 mode = priv->ieee80211->current_network.mode;
+        //u32 size = sizeof(struct ieee80211_qos_parameters);
+	u8  u1bAIFS;
+	u32 u4bAcParam;
+        int i;
+
+        if (priv == NULL)
+                return;
+
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16))
+	down(&priv->mutex);
+#else
+       mutex_lock(&priv->mutex);
+#endif
+        if(priv->ieee80211->state != IEEE80211_LINKED)
+		goto success;
+	RT_TRACE(COMP_QOS,"qos active process with associate response received\n");
+	/* It better set slot time at first */
+	/* For we just support b/g mode at present, let the slot time at 9/20 selection */
+	/* update the ac parameter to related registers */
+	for(i = 0; i <  QOS_QUEUE_NUM; i++) {
+		//Mode G/A: slotTimeTimer = 9; Mode B: 20
+		u1bAIFS = qos_parameters->aifs[i] * ((mode&(IEEE_G|IEEE_N_24G)) ?9:20) + aSifsTime;
+		u4bAcParam = ((((u32)(qos_parameters->tx_op_limit[i]))<< AC_PARAM_TXOP_LIMIT_OFFSET)|
+				(((u32)(qos_parameters->cw_max[i]))<< AC_PARAM_ECW_MAX_OFFSET)|
+				(((u32)(qos_parameters->cw_min[i]))<< AC_PARAM_ECW_MIN_OFFSET)|
+				((u32)u1bAIFS << AC_PARAM_AIFS_OFFSET));
+
+		write_nic_dword(dev, WDCAPARA_ADD[i], u4bAcParam);
+		//write_nic_dword(dev, WDCAPARA_ADD[i], 0x005e4322);
+	}
+
+success:
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16))
+	up(&priv->mutex);
+#else
+       mutex_unlock(&priv->mutex);
+#endif
+}
+
+static int rtl8192_qos_handle_probe_response(struct r8192_priv *priv,
+		int active_network,
+		struct ieee80211_network *network)
+{
+	int ret = 0;
+	u32 size = sizeof(struct ieee80211_qos_parameters);
+
+	if(priv->ieee80211->state !=IEEE80211_LINKED)
+                return ret;
+
+        if ((priv->ieee80211->iw_mode != IW_MODE_INFRA))
+                return ret;
+
+	if (network->flags & NETWORK_HAS_QOS_MASK) {
+		if (active_network &&
+				(network->flags & NETWORK_HAS_QOS_PARAMETERS))
+			network->qos_data.active = network->qos_data.supported;
+
+		if ((network->qos_data.active == 1) && (active_network == 1) &&
+				(network->flags & NETWORK_HAS_QOS_PARAMETERS) &&
+				(network->qos_data.old_param_count !=
+				 network->qos_data.param_count)) {
+			network->qos_data.old_param_count =
+				network->qos_data.param_count;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+			queue_work(priv->priv_wq, &priv->qos_activate);
+#else
+			schedule_task(&priv->qos_activate);
+#endif
+			RT_TRACE (COMP_QOS, "QoS parameters change call "
+					"qos_activate\n");
+		}
+	} else {
+		memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
+		       &def_qos_parameters, size);
+
+		if ((network->qos_data.active == 1) && (active_network == 1)) {
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+			queue_work(priv->priv_wq, &priv->qos_activate);
+#else
+			schedule_task(&priv->qos_activate);
+#endif
+			RT_TRACE(COMP_QOS, "QoS was disabled call qos_activate \n");
+		}
+		network->qos_data.active = 0;
+		network->qos_data.supported = 0;
+	}
+
+	return 0;
+}
+
+/* handle manage frame frame beacon and probe response */
+static int rtl8192_handle_beacon(struct net_device * dev,
+                              struct ieee80211_beacon * beacon,
+                              struct ieee80211_network * network)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	rtl8192_qos_handle_probe_response(priv,1,network);
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+	queue_delayed_work(priv->priv_wq, &priv->update_beacon_wq, 0);
+#else
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+	schedule_task(&priv->update_beacon_wq);
+#else
+	queue_work(priv->priv_wq, &priv->update_beacon_wq);
+#endif
+
+#endif
+	return 0;
+
+}
+
+/*
+* handling the beaconing responses. if we get different QoS setting
+* off the network from the associated setting, adjust the QoS
+* setting
+*/
+static int rtl8192_qos_association_resp(struct r8192_priv *priv,
+                                    struct ieee80211_network *network)
+{
+        int ret = 0;
+        unsigned long flags;
+        u32 size = sizeof(struct ieee80211_qos_parameters);
+        int set_qos_param = 0;
+
+        if ((priv == NULL) || (network == NULL))
+                return ret;
+
+	if(priv->ieee80211->state !=IEEE80211_LINKED)
+                return ret;
+
+        if ((priv->ieee80211->iw_mode != IW_MODE_INFRA))
+                return ret;
+
+        spin_lock_irqsave(&priv->ieee80211->lock, flags);
+	if(network->flags & NETWORK_HAS_QOS_PARAMETERS) {
+		memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
+			 &network->qos_data.parameters,\
+			sizeof(struct ieee80211_qos_parameters));
+		priv->ieee80211->current_network.qos_data.active = 1;
+#if 0
+		if((priv->ieee80211->current_network.qos_data.param_count != \
+					network->qos_data.param_count))
+#endif
+		 {
+                        set_qos_param = 1;
+			/* update qos parameter for current network */
+			priv->ieee80211->current_network.qos_data.old_param_count = \
+				 priv->ieee80211->current_network.qos_data.param_count;
+			priv->ieee80211->current_network.qos_data.param_count = \
+			     	 network->qos_data.param_count;
+		}
+        } else {
+		memcpy(&priv->ieee80211->current_network.qos_data.parameters,\
+		       &def_qos_parameters, size);
+		priv->ieee80211->current_network.qos_data.active = 0;
+		priv->ieee80211->current_network.qos_data.supported = 0;
+                set_qos_param = 1;
+        }
+
+        spin_unlock_irqrestore(&priv->ieee80211->lock, flags);
+
+	RT_TRACE(COMP_QOS, "%s: network->flags = %d,%d\n",__FUNCTION__,network->flags ,priv->ieee80211->current_network.qos_data.active);
+	if (set_qos_param == 1)
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+		queue_work(priv->priv_wq, &priv->qos_activate);
+#else
+		schedule_task(&priv->qos_activate);
+#endif
+
+
+        return ret;
+}
+
+
+static int rtl8192_handle_assoc_response(struct net_device *dev,
+                                     struct ieee80211_assoc_response_frame *resp,
+                                     struct ieee80211_network *network)
+{
+        struct r8192_priv *priv = ieee80211_priv(dev);
+        rtl8192_qos_association_resp(priv, network);
+        return 0;
+}
+
+
+void rtl8192_update_ratr_table(struct net_device* dev)
+	//	POCTET_STRING	posLegacyRate,
+	//	u8*			pMcsRate)
+	//	PRT_WLAN_STA	pEntry)
+{
+	struct r8192_priv* priv = ieee80211_priv(dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+	u8* pMcsRate = ieee->dot11HTOperationalRateSet;
+	//struct ieee80211_network *net = &ieee->current_network;
+	u32 ratr_value = 0;
+	u8 rate_index = 0;
+	rtl8192_config_rate(dev, (u16*)(&ratr_value));
+	ratr_value |= (*(u16*)(pMcsRate)) << 12;
+//	switch (net->mode)
+	switch (ieee->mode)
+	{
+		case IEEE_A:
+			ratr_value &= 0x00000FF0;
+			break;
+		case IEEE_B:
+			ratr_value &= 0x0000000F;
+			break;
+		case IEEE_G:
+			ratr_value &= 0x00000FF7;
+			break;
+		case IEEE_N_24G:
+		case IEEE_N_5G:
+			if (ieee->pHTInfo->PeerMimoPs == 0) //MIMO_PS_STATIC
+				ratr_value &= 0x0007F007;
+			else{
+				if (priv->rf_type == RF_1T2R)
+					ratr_value &= 0x000FF007;
+				else
+					ratr_value &= 0x0F81F007;
+			}
+			break;
+		default:
+			break;
+	}
+	ratr_value &= 0x0FFFFFFF;
+	if(ieee->pHTInfo->bCurTxBW40MHz && ieee->pHTInfo->bCurShortGI40MHz){
+		ratr_value |= 0x80000000;
+	}else if(!ieee->pHTInfo->bCurTxBW40MHz && ieee->pHTInfo->bCurShortGI20MHz){
+		ratr_value |= 0x80000000;
+	}
+	write_nic_dword(dev, RATR0+rate_index*4, ratr_value);
+	write_nic_byte(dev, UFWP, 1);
+}
+
+static u8 ccmp_ie[4] = {0x00,0x50,0xf2,0x04};
+static u8 ccmp_rsn_ie[4] = {0x00, 0x0f, 0xac, 0x04};
+bool GetNmodeSupportBySecCfg8192(struct net_device*dev)
+{
+#if 1
+	struct r8192_priv* priv = ieee80211_priv(dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+	struct ieee80211_network * network = &ieee->current_network;
+        int wpa_ie_len= ieee->wpa_ie_len;
+        struct ieee80211_crypt_data* crypt;
+        int encrypt;
+#if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
+	return TRUE;
+#endif
+
+        crypt = ieee->crypt[ieee->tx_keyidx];
+	//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
+        encrypt = (network->capability & WLAN_CAPABILITY_PRIVACY) || (ieee->host_encrypt && crypt && crypt->ops && (0 == strcmp(crypt->ops->name,"WEP")));
+
+	/* simply judge  */
+	if(encrypt && (wpa_ie_len == 0)) {
+		/* wep encryption, no N mode setting */
+		return false;
+//	} else if((wpa_ie_len != 0)&&(memcmp(&(ieee->wpa_ie[14]),ccmp_ie,4))) {
+	} else if((wpa_ie_len != 0)) {
+		/* parse pairwise key type */
+		//if((pairwisekey = WEP40)||(pairwisekey = WEP104)||(pairwisekey = TKIP))
+		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))))
+			return true;
+		else
+			return false;
+	} else {
+		return true;
+	}
+
+#if 0
+        //In here we discuss with SD4 David. He think we still can send TKIP in broadcast group key in MCS rate.
+        //We can't force in G mode if Pairwie key is AES and group key is TKIP
+        if((pSecInfo->GroupEncAlgorithm == WEP104_Encryption) || (pSecInfo->GroupEncAlgorithm == WEP40_Encryption)  ||
+           (pSecInfo->PairwiseEncAlgorithm == WEP104_Encryption) ||
+           (pSecInfo->PairwiseEncAlgorithm == WEP40_Encryption) || (pSecInfo->PairwiseEncAlgorithm == TKIP_Encryption))
+        {
+                return  false;
+        }
+        else
+                return true;
+#endif
+	return true;
+#endif
+}
+
+bool GetHalfNmodeSupportByAPs819xUsb(struct net_device* dev)
+{
+	bool			Reval;
+	struct r8192_priv* priv = ieee80211_priv(dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+
+// 	Added by Roger, 2008.08.29.
+#ifdef RTL8192SU
+	return false;
+#endif
+
+	if(ieee->bHalfWirelessN24GMode == true)
+		Reval = true;
+	else
+		Reval =  false;
+
+	return Reval;
+}
+
+void rtl8192_refresh_supportrate(struct r8192_priv* priv)
+{
+	struct ieee80211_device* ieee = priv->ieee80211;
+	//we donot consider set support rate for ABG mode, only HT MCS rate is set here.
+	if (ieee->mode == WIRELESS_MODE_N_24G || ieee->mode == WIRELESS_MODE_N_5G)
+	{
+		memcpy(ieee->Regdot11HTOperationalRateSet, ieee->RegHTSuppRateSet, 16);
+		//RT_DEBUG_DATA(COMP_INIT, ieee->RegHTSuppRateSet, 16);
+		//RT_DEBUG_DATA(COMP_INIT, ieee->Regdot11HTOperationalRateSet, 16);
+	}
+	else
+		memset(ieee->Regdot11HTOperationalRateSet, 0, 16);
+	return;
+}
+
+u8 rtl8192_getSupportedWireleeMode(struct net_device*dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8 ret = 0;
+	switch(priv->rf_chip)
+	{
+		case RF_8225:
+		case RF_8256:
+		case RF_PSEUDO_11N:
+		case RF_6052:
+			ret = (WIRELESS_MODE_N_24G|WIRELESS_MODE_G|WIRELESS_MODE_B);
+			break;
+		case RF_8258:
+			ret = (WIRELESS_MODE_A|WIRELESS_MODE_N_5G);
+			break;
+		default:
+			ret = WIRELESS_MODE_B;
+			break;
+	}
+	return ret;
+}
+void rtl8192_SetWirelessMode(struct net_device* dev, u8 wireless_mode)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8 bSupportMode = rtl8192_getSupportedWireleeMode(dev);
+
+#if 1
+	if ((wireless_mode == WIRELESS_MODE_AUTO) || ((wireless_mode&bSupportMode)==0))
+	{
+		if(bSupportMode & WIRELESS_MODE_N_24G)
+		{
+			wireless_mode = WIRELESS_MODE_N_24G;
+		}
+		else if(bSupportMode & WIRELESS_MODE_N_5G)
+		{
+			wireless_mode = WIRELESS_MODE_N_5G;
+		}
+		else if((bSupportMode & WIRELESS_MODE_A))
+		{
+			wireless_mode = WIRELESS_MODE_A;
+		}
+		else if((bSupportMode & WIRELESS_MODE_G))
+		{
+			wireless_mode = WIRELESS_MODE_G;
+		}
+		else if((bSupportMode & WIRELESS_MODE_B))
+		{
+			wireless_mode = WIRELESS_MODE_B;
+		}
+		else{
+			RT_TRACE(COMP_ERR, "%s(), No valid wireless mode supported, SupportedWirelessMode(%x)!!!\n", __FUNCTION__,bSupportMode);
+			wireless_mode = WIRELESS_MODE_B;
+		}
+	}
+#ifdef TO_DO_LIST //// TODO: this function doesn't work well at this time, we shoud wait for FPGA
+	ActUpdateChannelAccessSetting( pAdapter, pHalData->CurrentWirelessMode, &pAdapter->MgntInfo.Info8185.ChannelAccessSetting );
+#endif
+#ifdef RTL8192SU
+	//LZM 090306 usb crash here, mark it temp
+	//write_nic_word(dev, SIFS_OFDM, 0x0e0e);
+#endif
+	priv->ieee80211->mode = wireless_mode;
+
+	if ((wireless_mode == WIRELESS_MODE_N_24G) ||  (wireless_mode == WIRELESS_MODE_N_5G))
+		priv->ieee80211->pHTInfo->bEnableHT = 1;
+	else
+		priv->ieee80211->pHTInfo->bEnableHT = 0;
+	RT_TRACE(COMP_INIT, "Current Wireless Mode is %x\n", wireless_mode);
+	rtl8192_refresh_supportrate(priv);
+#endif
+
+}
+
+
+short rtl8192_is_tx_queue_empty(struct net_device *dev)
+{
+	int i=0;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//struct ieee80211_device* ieee = priv->ieee80211;
+	for (i=0; i<=MGNT_QUEUE; i++)
+	{
+		if ((i== TXCMD_QUEUE) || (i == HCCA_QUEUE) )
+			continue;
+		if (atomic_read(&priv->tx_pending[i]))
+		{
+			printk("===>tx queue is not empty:%d, %d\n", i, atomic_read(&priv->tx_pending[i]));
+			return 0;
+		}
+	}
+	return 1;
+}
+#if 0
+void rtl8192_rq_tx_ack(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	priv->ieee80211->ack_tx_to_ieee = 1;
+}
+#endif
+void rtl8192_hw_sleep_down(struct net_device *dev)
+{
+	RT_TRACE(COMP_POWER, "%s()============>come to sleep down\n", __FUNCTION__);
+#ifdef TODO
+//	MgntActSet_RF_State(dev, eRfSleep, RF_CHANGE_BY_PS);
+#endif
+}
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+void rtl8192_hw_sleep_wq (struct work_struct *work)
+{
+//      struct r8180_priv *priv = container_of(work, struct r8180_priv, watch_dog_wq);
+//      struct ieee80211_device * ieee = (struct ieee80211_device*)
+//                                             container_of(work, struct ieee80211_device, watch_dog_wq);
+        struct delayed_work *dwork = container_of(work,struct delayed_work,work);
+        struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,hw_sleep_wq);
+        struct net_device *dev = ieee->dev;
+#else
+void rtl8192_hw_sleep_wq(struct net_device* dev)
+{
+#endif
+	//printk("=========>%s()\n", __FUNCTION__);
+        rtl8192_hw_sleep_down(dev);
+}
+//	printk("dev is %d\n",dev);
+//	printk("&*&(^*(&(&=========>%s()\n", __FUNCTION__);
+void rtl8192_hw_wakeup(struct net_device* dev)
+{
+//	u32 flags = 0;
+
+//	spin_lock_irqsave(&priv->ps_lock,flags);
+	RT_TRACE(COMP_POWER, "%s()============>come to wake up\n", __FUNCTION__);
+#ifdef TODO
+//	MgntActSet_RF_State(dev, eRfSleep, RF_CHANGE_BY_PS);
+#endif
+	//FIXME: will we send package stored while nic is sleep?
+//	spin_unlock_irqrestore(&priv->ps_lock,flags);
+}
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+void rtl8192_hw_wakeup_wq (struct work_struct *work)
+{
+//	struct r8180_priv *priv = container_of(work, struct r8180_priv, watch_dog_wq);
+//	struct ieee80211_device * ieee = (struct ieee80211_device*)
+//	                                       container_of(work, struct ieee80211_device, watch_dog_wq);
+	struct delayed_work *dwork = container_of(work,struct delayed_work,work);
+	struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,hw_wakeup_wq);
+	struct net_device *dev = ieee->dev;
+#else
+void rtl8192_hw_wakeup_wq(struct net_device* dev)
+{
+#endif
+	rtl8192_hw_wakeup(dev);
+
+}
+
+#define MIN_SLEEP_TIME 50
+#define MAX_SLEEP_TIME 10000
+void rtl8192_hw_to_sleep(struct net_device *dev, u32 th, u32 tl)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	u32 rb = jiffies;
+	unsigned long flags;
+
+	spin_lock_irqsave(&priv->ps_lock,flags);
+
+	/* Writing HW register with 0 equals to disable
+	 * the timer, that is not really what we want
+	 */
+	tl -= MSECS(4+16+7);
+
+	//if(tl == 0) tl = 1;
+
+	/* FIXME HACK FIXME HACK */
+//	force_pci_posting(dev);
+	//mdelay(1);
+
+//	rb = read_nic_dword(dev, TSFTR);
+
+	/* If the interval in witch we are requested to sleep is too
+	 * short then give up and remain awake
+	 */
+	if(((tl>=rb)&& (tl-rb) <= MSECS(MIN_SLEEP_TIME))
+		||((rb>tl)&& (rb-tl) < MSECS(MIN_SLEEP_TIME))) {
+		spin_unlock_irqrestore(&priv->ps_lock,flags);
+		printk("too short to sleep\n");
+		return;
+	}
+
+//	write_nic_dword(dev, TimerInt, tl);
+//	rb = read_nic_dword(dev, TSFTR);
+	{
+		u32 tmp = (tl>rb)?(tl-rb):(rb-tl);
+	//	if (tl<rb)
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+		schedule_task(&priv->ieee80211->hw_wakeup_wq);
+#else
+		queue_delayed_work(priv->ieee80211->wq, &priv->ieee80211->hw_wakeup_wq, tmp); //as tl may be less than rb
+#endif
+	}
+	/* if we suspect the TimerInt is gone beyond tl
+	 * while setting it, then give up
+	 */
+#if 1
+	if(((tl > rb) && ((tl-rb) > MSECS(MAX_SLEEP_TIME)))||
+		((tl < rb) && ((rb-tl) > MSECS(MAX_SLEEP_TIME)))) {
+		printk("========>too long to sleep:%x, %x, %lx\n", tl, rb,  MSECS(MAX_SLEEP_TIME));
+		spin_unlock_irqrestore(&priv->ps_lock,flags);
+		return;
+	}
+#endif
+//	if(priv->rf_sleep)
+//		priv->rf_sleep(dev);
+
+	//printk("<=========%s()\n", __FUNCTION__);
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+	schedule_task(&priv->ieee80211->hw_sleep_wq);
+#else
+	queue_delayed_work(priv->ieee80211->wq, (void *)&priv->ieee80211->hw_sleep_wq,0);
+#endif
+	spin_unlock_irqrestore(&priv->ps_lock,flags);
+}
+//init priv variables here. only non_zero value should be initialized here.
+static void rtl8192_init_priv_variable(struct net_device* dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8 i;
+	priv->card_8192 = NIC_8192U;
+	priv->chan = 1; //set to channel 1
+	priv->ieee80211->mode = WIRELESS_MODE_AUTO; //SET AUTO
+	priv->ieee80211->iw_mode = IW_MODE_INFRA;
+	priv->ieee80211->ieee_up=0;
+	priv->retry_rts = DEFAULT_RETRY_RTS;
+	priv->retry_data = DEFAULT_RETRY_DATA;
+	priv->ieee80211->rts = DEFAULT_RTS_THRESHOLD;
+	priv->ieee80211->rate = 110; //11 mbps
+	priv->ieee80211->short_slot = 1;
+	priv->promisc = (dev->flags & IFF_PROMISC) ? 1:0;
+	priv->CckPwEnl = 6;
+	//for silent reset
+	priv->IrpPendingCount = 1;
+	priv->ResetProgress = RESET_TYPE_NORESET;
+	priv->bForcedSilentReset = 0;
+	priv->bDisableNormalResetCheck = false;
+	priv->force_reset = false;
+
+	priv->ieee80211->FwRWRF = 0; 	//we don't use FW read/write RF until stable firmware is available.
+	priv->ieee80211->current_network.beacon_interval = DEFAULT_BEACONINTERVAL;
+	priv->ieee80211->iw_mode = IW_MODE_INFRA;
+	priv->ieee80211->softmac_features  = IEEE_SOFTMAC_SCAN |
+		IEEE_SOFTMAC_ASSOCIATE | IEEE_SOFTMAC_PROBERQ |
+		IEEE_SOFTMAC_PROBERS | IEEE_SOFTMAC_TX_QUEUE |
+		IEEE_SOFTMAC_BEACONS;//added by amy 080604 //|  //IEEE_SOFTMAC_SINGLE_QUEUE;
+
+	priv->ieee80211->active_scan = 1;
+	priv->ieee80211->modulation = IEEE80211_CCK_MODULATION | IEEE80211_OFDM_MODULATION;
+	priv->ieee80211->host_encrypt = 1;
+	priv->ieee80211->host_decrypt = 1;
+	priv->ieee80211->start_send_beacons = NULL;//rtl819xusb_beacon_tx;//-by amy 080604
+	priv->ieee80211->stop_send_beacons = NULL;//rtl8192_beacon_stop;//-by amy 080604
+	priv->ieee80211->softmac_hard_start_xmit = rtl8192_hard_start_xmit;
+	priv->ieee80211->set_chan = rtl8192_set_chan;
+	priv->ieee80211->link_change = priv->ops->rtl819x_link_change;
+	priv->ieee80211->softmac_data_hard_start_xmit = rtl8192_hard_data_xmit;
+	priv->ieee80211->data_hard_stop = rtl8192_data_hard_stop;
+	priv->ieee80211->data_hard_resume = rtl8192_data_hard_resume;
+	priv->ieee80211->init_wmmparam_flag = 0;
+	priv->ieee80211->fts = DEFAULT_FRAG_THRESHOLD;
+	priv->ieee80211->check_nic_enough_desc = check_nic_enough_desc;
+	priv->ieee80211->tx_headroom = TX_PACKET_SHIFT_BYTES;
+	priv->ieee80211->qos_support = 1;
+
+	//added by WB
+//	priv->ieee80211->SwChnlByTimerHandler = rtl8192_phy_SwChnl;
+	priv->ieee80211->SetBWModeHandler = rtl8192_SetBWMode;
+	priv->ieee80211->handle_assoc_response = rtl8192_handle_assoc_response;
+	priv->ieee80211->handle_beacon = rtl8192_handle_beacon;
+	//for LPS
+	priv->ieee80211->sta_wake_up = rtl8192_hw_wakeup;
+//	priv->ieee80211->ps_request_tx_ack = rtl8192_rq_tx_ack;
+	priv->ieee80211->enter_sleep_state = rtl8192_hw_to_sleep;
+	priv->ieee80211->ps_is_queue_empty = rtl8192_is_tx_queue_empty;
+	//added by david
+	priv->ieee80211->GetNmodeSupportBySecCfg = GetNmodeSupportBySecCfg8192;
+	priv->ieee80211->GetHalfNmodeSupportByAPsHandler = GetHalfNmodeSupportByAPs819xUsb;
+	priv->ieee80211->SetWirelessMode = rtl8192_SetWirelessMode;
+	//added by amy
+	priv->ieee80211->InitialGainHandler = priv->ops->rtl819x_initial_gain;
+	priv->card_type = USB;
+
+#ifdef RTL8192SU
+//1 RTL8192SU/
+	priv->ieee80211->current_network.beacon_interval = DEFAULT_BEACONINTERVAL;
+	priv->ieee80211->SetFwCmdHandler = HalSetFwCmd8192S;
+	priv->bRFSiOrPi = 0;//o=si,1=pi;
+	//lzm add
+	priv->bInHctTest = false;
+
+	priv->MidHighPwrTHR_L1 = 0x3B;
+	priv->MidHighPwrTHR_L2 = 0x40;
+
+	if(priv->bInHctTest)
+  	{
+		priv->ShortRetryLimit = HAL_RETRY_LIMIT_AP_ADHOC;
+		priv->LongRetryLimit = HAL_RETRY_LIMIT_AP_ADHOC;
+  	}
+	else
+	{
+		priv->ShortRetryLimit = HAL_RETRY_LIMIT_INFRA;
+		priv->LongRetryLimit = HAL_RETRY_LIMIT_INFRA;
+	}
+
+	priv->SetFwCmdInProgress = false; //is set FW CMD in Progress? 92S only
+	priv->CurrentFwCmdIO = 0;
+
+	priv->MinSpaceCfg = 0;
+
+	priv->EarlyRxThreshold = 7;
+	priv->enable_gpio0 = 0;
+	priv->TransmitConfig	=
+				((u32)TCR_MXDMA_2048<<TCR_MXDMA_OFFSET) |	// Max DMA Burst Size per Tx DMA Burst, 7: reservied.
+				(priv->ShortRetryLimit<<TCR_SRL_OFFSET) |	// Short retry limit
+				(priv->LongRetryLimit<<TCR_LRL_OFFSET) |	// Long retry limit
+				(false ? TCR_SAT : 0);	// FALSE: HW provies PLCP length and LENGEXT, TURE: SW proiveds them
+	if(priv->bInHctTest)
+		priv->ReceiveConfig	=	//priv->CSMethod |
+								RCR_AMF | RCR_ADF |	//RCR_AAP | 	//accept management/data
+									RCR_ACF |RCR_APPFCS|						//accept control frame for SW AP needs PS-poll, 2005.07.07, by rcnjko.
+								RCR_AB | RCR_AM | RCR_APM |		//accept BC/MC/UC
+								RCR_AICV | RCR_ACRC32 | 		//accept ICV/CRC error packet
+								RCR_APP_PHYST_STAFF | RCR_APP_PHYST_RXFF |	// Accept PHY status
+								((u32)7<<RCR_MXDMA_OFFSET) | // Max DMA Burst Size per Rx DMA Burst, 7: unlimited.
+								(priv->EarlyRxThreshold<<RCR_FIFO_OFFSET) | // Rx FIFO Threshold, 7: No Rx threshold.
+								(priv->EarlyRxThreshold == 7 ? RCR_OnlyErlPkt:0);
+	else
+		priv->ReceiveConfig	=	//priv->CSMethod |
+									RCR_AMF | RCR_ADF | RCR_AB |
+									RCR_AM | RCR_APM |RCR_AAP |RCR_ADD3|RCR_APP_ICV|
+								RCR_APP_PHYST_STAFF | RCR_APP_PHYST_RXFF |	// Accept PHY status
+									RCR_APP_MIC | RCR_APPFCS;
+
+	// <Roger_EXP> 2008.06.16.
+	priv->IntrMask 		= 	(u16)(IMR_ROK | IMR_VODOK | IMR_VIDOK | IMR_BEDOK | IMR_BKDOK |		\
+								IMR_HCCADOK | IMR_MGNTDOK | IMR_COMDOK | IMR_HIGHDOK | 					\
+								IMR_BDOK | IMR_RXCMDOK | /*IMR_TIMEOUT0 |*/ IMR_RDU | IMR_RXFOVW	|			\
+								IMR_TXFOVW | IMR_BcnInt | IMR_TBDOK | IMR_TBDER);
+
+//1 End
+
+#else
+
+#ifdef TO_DO_LIST
+	if(Adapter->bInHctTest)
+  	{
+		pHalData->ShortRetryLimit = 7;
+		pHalData->LongRetryLimit = 7;
+  	}
+#endif
+	{
+		priv->ShortRetryLimit = 0x30;
+		priv->LongRetryLimit = 0x30;
+	}
+	priv->EarlyRxThreshold = 7;
+	priv->enable_gpio0 = 0;
+	priv->TransmitConfig =
+	//	TCR_DurProcMode |	//for RTL8185B, duration setting by HW
+	//?	TCR_DISReqQsize |
+                (TCR_MXDMA_2048<<TCR_MXDMA_OFFSET)|  // Max DMA Burst Size per Tx DMA Burst, 7: reservied.
+		(priv->ShortRetryLimit<<TCR_SRL_OFFSET)|	// Short retry limit
+		(priv->LongRetryLimit<<TCR_LRL_OFFSET) |	// Long retry limit
+		(false ? TCR_SAT: 0);	// FALSE: HW provies PLCP length and LENGEXT, TURE: SW proiveds them
+#ifdef TO_DO_LIST
+	if(Adapter->bInHctTest)
+		pHalData->ReceiveConfig	=	pHalData->CSMethod |
+						RCR_AMF | RCR_ADF |	//RCR_AAP | 	//accept management/data
+						//guangan200710
+						RCR_ACF |	//accept control frame for SW AP needs PS-poll, 2005.07.07, by rcnjko.
+						RCR_AB | RCR_AM | RCR_APM |		//accept BC/MC/UC
+						RCR_AICV | RCR_ACRC32 | 		//accept ICV/CRC error packet
+						((u32)7<<RCR_MXDMA_OFFSET) | // Max DMA Burst Size per Rx DMA Burst, 7: unlimited.
+						(pHalData->EarlyRxThreshold<<RCR_FIFO_OFFSET) | // Rx FIFO Threshold, 7: No Rx threshold.
+						(pHalData->EarlyRxThreshold == 7 ? RCR_OnlyErlPkt:0);
+	else
+
+#endif
+	priv->ReceiveConfig	=
+		RCR_AMF | RCR_ADF |		//accept management/data
+		RCR_ACF |			//accept control frame for SW AP needs PS-poll, 2005.07.07, by rcnjko.
+		RCR_AB | RCR_AM | RCR_APM |	//accept BC/MC/UC
+		//RCR_AICV | RCR_ACRC32 | 	//accept ICV/CRC error packet
+		((u32)7<<RCR_MXDMA_OFFSET)| // Max DMA Burst Size per Rx DMA Burst, 7: unlimited.
+		(priv->EarlyRxThreshold<<RX_FIFO_THRESHOLD_SHIFT) | // Rx FIFO Threshold, 7: No Rx threshold.
+		(priv->EarlyRxThreshold == 7 ? RCR_ONLYERLPKT:0);
+#endif
+
+	priv->AcmControl = 0;
+	priv->pFirmware = (rt_firmware*)vmalloc(sizeof(rt_firmware));
+	if (priv->pFirmware)
+	memset(priv->pFirmware, 0, sizeof(rt_firmware));
+
+	/* rx related queue */
+        skb_queue_head_init(&priv->rx_queue);
+	skb_queue_head_init(&priv->skb_queue);
+
+	/* Tx related queue */
+	for(i = 0; i < MAX_QUEUE_SIZE; i++) {
+		skb_queue_head_init(&priv->ieee80211->skb_waitQ [i]);
+	}
+	for(i = 0; i < MAX_QUEUE_SIZE; i++) {
+		skb_queue_head_init(&priv->ieee80211->skb_aggQ [i]);
+	}
+	for(i = 0; i < MAX_QUEUE_SIZE; i++) {
+		skb_queue_head_init(&priv->ieee80211->skb_drv_aggQ [i]);
+	}
+	priv->rf_set_chan = rtl8192_phy_SwChnl;
+}
+
+//init lock here
+static void rtl8192_init_priv_lock(struct r8192_priv* priv)
+{
+	spin_lock_init(&priv->tx_lock);
+	spin_lock_init(&priv->irq_lock);//added by thomas
+	//spin_lock_init(&priv->rf_lock);//use rf_sem, or will crash in some OS.
+	sema_init(&priv->wx_sem,1);
+	sema_init(&priv->rf_sem,1);
+	spin_lock_init(&priv->ps_lock);
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16))
+	sema_init(&priv->mutex, 1);
+#else
+	mutex_init(&priv->mutex);
+#endif
+}
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern  void    rtl819x_watchdog_wqcallback(struct work_struct *work);
+#else
+extern  void    rtl819x_watchdog_wqcallback(struct net_device *dev);
+#endif
+
+void rtl8192_irq_rx_tasklet(struct r8192_priv *priv);
+//init tasklet and wait_queue here. only 2.6 above kernel is considered
+#define DRV_NAME "wlan0"
+static void rtl8192_init_priv_task(struct net_device* dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+#ifdef PF_SYNCTHREAD
+	priv->priv_wq = create_workqueue(DRV_NAME,0);
+#else
+	priv->priv_wq = create_workqueue(DRV_NAME);
+#endif
+#endif
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+	INIT_WORK(&priv->reset_wq, rtl8192_restart);
+
+	//INIT_DELAYED_WORK(&priv->watch_dog_wq, hal_dm_watchdog);
+	INIT_DELAYED_WORK(&priv->watch_dog_wq, rtl819x_watchdog_wqcallback);
+	INIT_DELAYED_WORK(&priv->txpower_tracking_wq,  dm_txpower_trackingcallback);
+//	INIT_DELAYED_WORK(&priv->gpio_change_rf_wq,  dm_gpio_change_rf_callback);
+	INIT_DELAYED_WORK(&priv->rfpath_check_wq,  dm_rf_pathcheck_workitemcallback);
+	INIT_DELAYED_WORK(&priv->update_beacon_wq, rtl8192_update_beacon);
+	INIT_DELAYED_WORK(&priv->initialgain_operate_wq, InitialGainOperateWorkItemCallBack);
+	//INIT_WORK(&priv->SwChnlWorkItem,  rtl8192_SwChnl_WorkItem);
+	//INIT_WORK(&priv->SetBWModeWorkItem,  rtl8192_SetBWModeWorkItem);
+	INIT_WORK(&priv->qos_activate, rtl8192_qos_activate);
+	INIT_DELAYED_WORK(&priv->ieee80211->hw_wakeup_wq,(void*) rtl8192_hw_wakeup_wq);
+	INIT_DELAYED_WORK(&priv->ieee80211->hw_sleep_wq,(void*) rtl8192_hw_sleep_wq);
+
+#else
+#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
+	tq_init(&priv->reset_wq, (void*)rtl8192_restart, dev);
+	tq_init(&priv->watch_dog_wq, (void*)rtl819x_watchdog_wqcallback, dev);
+	tq_init(&priv->txpower_tracking_wq, (void*)dm_txpower_trackingcallback, dev);
+	tq_init(&priv->rfpath_check_wq, (void*)dm_rf_pathcheck_workitemcallback, dev);
+	tq_init(&priv->update_beacon_wq, (void*)rtl8192_update_beacon, dev);
+	//tq_init(&priv->SwChnlWorkItem, (void*) rtl8192_SwChnl_WorkItem, dev);
+	//tq_init(&priv->SetBWModeWorkItem, (void*)rtl8192_SetBWModeWorkItem, dev);
+	tq_init(&priv->qos_activate, (void *)rtl8192_qos_activate, dev);
+	tq_init(&priv->ieee80211->hw_wakeup_wq,(void*) rtl8192_hw_wakeup_wq, dev);
+	tq_init(&priv->ieee80211->hw_sleep_wq,(void*) rtl8192_hw_sleep_wq, dev);
+
+#else
+	INIT_WORK(&priv->reset_wq,(void(*)(void*)) rtl8192_restart,dev);
+	//INIT_WORK(&priv->watch_dog_wq, (void(*)(void*)) hal_dm_watchdog,dev);
+	INIT_WORK(&priv->watch_dog_wq, (void(*)(void*)) rtl819x_watchdog_wqcallback,dev);
+	INIT_WORK(&priv->txpower_tracking_wq, (void(*)(void*)) dm_txpower_trackingcallback,dev);
+//	INIT_WORK(&priv->gpio_change_rf_wq, (void(*)(void*)) dm_gpio_change_rf_callback,dev);
+	INIT_WORK(&priv->rfpath_check_wq, (void(*)(void*)) dm_rf_pathcheck_workitemcallback,dev);
+	INIT_WORK(&priv->update_beacon_wq, (void(*)(void*))rtl8192_update_beacon,dev);
+	INIT_WORK(&priv->initialgain_operate_wq, (void(*)(void*))InitialGainOperateWorkItemCallBack,dev);
+	//INIT_WORK(&priv->SwChnlWorkItem, (void(*)(void*)) rtl8192_SwChnl_WorkItem, dev);
+	//INIT_WORK(&priv->SetBWModeWorkItem, (void(*)(void*)) rtl8192_SetBWModeWorkItem, dev);
+	INIT_WORK(&priv->qos_activate, (void(*)(void *))rtl8192_qos_activate, dev);
+	INIT_WORK(&priv->ieee80211->hw_wakeup_wq,(void*) rtl8192_hw_wakeup_wq, dev);
+	INIT_WORK(&priv->ieee80211->hw_sleep_wq,(void*) rtl8192_hw_sleep_wq, dev);
+#endif
+#endif
+
+	tasklet_init(&priv->irq_rx_tasklet,
+	     (void(*)(unsigned long))rtl8192_irq_rx_tasklet,
+	     (unsigned long)priv);
+}
+
+static void rtl8192_get_eeprom_size(struct net_device* dev)
+{
+	u16 curCR = 0;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	RT_TRACE(COMP_EPROM, "===========>%s()\n", __FUNCTION__);
+	curCR = read_nic_word_E(dev,EPROM_CMD);
+	RT_TRACE(COMP_EPROM, "read from Reg EPROM_CMD(%x):%x\n", EPROM_CMD, curCR);
+	//whether need I consider BIT5?
+	priv->epromtype = (curCR & Cmd9346CR_9356SEL) ? EPROM_93c56 : EPROM_93c46;
+	RT_TRACE(COMP_EPROM, "<===========%s(), epromtype:%d\n", __FUNCTION__, priv->epromtype);
+}
+
+//used to swap endian. as ntohl & htonl are not neccessary to swap endian, so use this instead.
+static inline u16 endian_swap(u16* data)
+{
+	u16 tmp = *data;
+	*data = (tmp >> 8) | (tmp << 8);
+	return *data;
+}
+
+#ifdef RTL8192SU
+u8 rtl8192SU_UsbOptionToEndPointNumber(u8 UsbOption)
+{
+	u8	nEndPoint = 0;
+	switch(UsbOption)
+	{
+		case 0:
+			nEndPoint = 6;
+			break;
+		case 1:
+			nEndPoint = 11;
+			break;
+		case 2:
+			nEndPoint = 4;
+			break;
+		default:
+			RT_TRACE(COMP_INIT, "UsbOptionToEndPointNumber(): Invalid UsbOption(%#x)\n", UsbOption);
+			break;
+	}
+	return nEndPoint;
+}
+
+u8 rtl8192SU_BoardTypeToRFtype(struct net_device* dev,  u8 Boardtype)
+{
+	u8	RFtype = RF_1T2R;
+
+	switch(Boardtype)
+	{
+		case 0:
+			RFtype = RF_1T1R;
+			break;
+		case 1:
+			RFtype = RF_1T2R;
+			break;
+		case 2:
+			RFtype = RF_2T2R;
+			break;
+		case 3:
+			RFtype = RF_2T2R_GREEN;
+			break;
+		default:
+			break;
+	}
+
+	return RFtype;
+}
+
+//
+//	Description:
+//		Config HW adapter information into initial value.
+//
+//	Assumption:
+//		1. After Auto load fail(i.e, check CR9346 fail)
+//
+//	Created by Roger, 2008.10.21.
+//
+void
+rtl8192SU_ConfigAdapterInfo8192SForAutoLoadFail(struct net_device* dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	//u16			i,usValue;
+	//u8 sMacAddr[6] = {0x00, 0xE0, 0x4C, 0x81, 0x92, 0x00};
+	u8		rf_path, index;	// For EEPROM/EFUSE After V0.6_1117
+	int	i;
+
+	RT_TRACE(COMP_INIT, "====> ConfigAdapterInfo8192SForAutoLoadFail\n");
+
+	write_nic_byte(dev, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
+	//PlatformStallExecution(10000);
+	mdelay(10);
+	write_nic_byte(dev, PMC_FSM, 0x02); // Enable Loader Data Keep
+
+	//RT_ASSERT(priv->AutoloadFailFlag==TRUE, ("ReadAdapterInfo8192SEEPROM(): AutoloadFailFlag !=TRUE\n"));
+
+	// Initialize IC Version && Channel Plan
+	priv->eeprom_vid = 0;
+	priv->eeprom_pid = 0;
+	priv->card_8192_version = 0;
+	priv->eeprom_ChannelPlan = 0;
+	priv->eeprom_CustomerID = 0;
+	priv->eeprom_SubCustomerID = 0;
+	priv->bIgnoreDiffRateTxPowerOffset = false;
+
+	RT_TRACE(COMP_INIT, "EEPROM VID = 0x%4x\n", priv->eeprom_vid);
+	RT_TRACE(COMP_INIT, "EEPROM PID = 0x%4x\n", priv->eeprom_pid);
+	RT_TRACE(COMP_INIT, "EEPROM Customer ID: 0x%2x\n", priv->eeprom_CustomerID);
+	RT_TRACE(COMP_INIT, "EEPROM SubCustomer ID: 0x%2x\n", priv->eeprom_SubCustomerID);
+	RT_TRACE(COMP_INIT, "EEPROM ChannelPlan = 0x%4x\n", priv->eeprom_ChannelPlan);
+	RT_TRACE(COMP_INIT, "IgnoreDiffRateTxPowerOffset = %d\n", priv->bIgnoreDiffRateTxPowerOffset);
+
+
+
+	priv->EEPROMUsbOption = EEPROM_USB_Default_OPTIONAL_FUNC;
+	RT_TRACE(COMP_INIT, "USB Option = %#x\n", priv->EEPROMUsbOption);
+
+	for(i=0; i<5; i++)
+		priv->EEPROMUsbPhyParam[i] = EEPROM_USB_Default_PHY_PARAM;
+
+	//RT_PRINT_DATA(COMP_INIT|COMP_EFUSE, DBG_LOUD, ("EFUSE USB PHY Param: \n"), priv->EEPROMUsbPhyParam, 5);
+
+	{
+	//<Roger_Notes> In this case, we random assigh MAC address here. 2008.10.15.
+		static u8 sMacAddr[6] = {0x00, 0xE0, 0x4C, 0x81, 0x92, 0x00};
+		u8	i;
+
+        	//sMacAddr[5] = (u8)GetRandomNumber(1, 254);
+
+		for(i = 0; i < 6; i++)
+			dev->dev_addr[i] = sMacAddr[i];
+	}
+	//NicIFSetMacAddress(Adapter, Adapter->PermanentAddress);
+	write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
+	write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
+
+	RT_TRACE(COMP_INIT, "ReadAdapterInfo8192SEFuse(), Permanent Address = %02x-%02x-%02x-%02x-%02x-%02x\n",
+			dev->dev_addr[0], dev->dev_addr[1],
+			dev->dev_addr[2], dev->dev_addr[3],
+			dev->dev_addr[4], dev->dev_addr[5]);
+
+	priv->EEPROMBoardType = EEPROM_Default_BoardType;
+	priv->rf_type = RF_1T2R; //RF_2T2R
+	priv->EEPROMTxPowerDiff = EEPROM_Default_PwDiff;
+	priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
+	priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
+	priv->EEPROMTxPwrBase = EEPROM_Default_TxPowerBase;
+	priv->EEPROMTSSI_A = EEPROM_Default_TSSI;
+	priv->EEPROMTSSI_B = EEPROM_Default_TSSI;
+	priv->EEPROMTxPwrTkMode = EEPROM_Default_TxPwrTkMode;
+
+
+#ifdef EEPROM_OLD_FORMAT_SUPPORT
+	for(i=0; i<6; i++)
+		{
+		priv->EEPROMHT2T_TxPwr[i] = EEPROM_Default_HT2T_TxPwr;
+		}
+
+		for(i=0; i<14; i++)
+		{
+		priv->EEPROMTxPowerLevelCCK24G[i] = (u8)(EEPROM_Default_TxPower & 0xff);
+			priv->EEPROMTxPowerLevelOFDM24G[i] = (u8)(EEPROM_Default_TxPower & 0xff);
+		}
+
+	//
+	// Update HAL variables.
+	//
+	memcpy( priv->TxPowerLevelOFDM24G, priv->EEPROMTxPowerLevelOFDM24G, 14);
+	memcpy( priv->TxPowerLevelCCK, priv->EEPROMTxPowerLevelCCK24G, 14);
+	//RT_PRINT_DATA(COMP_INIT|COMP_EFUSE, DBG_LOUD, ("HAL CCK 2.4G TxPwr: \n"), priv->TxPowerLevelCCK, 14);
+	//RT_PRINT_DATA(COMP_INIT|COMP_EFUSE, DBG_LOUD, ("HAL OFDM 2.4G TxPwr: \n"), priv->TxPowerLevelOFDM24G, 14);
+#else
+
+	for (rf_path = 0; rf_path < 2; rf_path++)
+	{
+		for (i = 0; i < 3; i++)
+		{
+			// Read CCK RF A & B Tx power
+			priv->RfCckChnlAreaTxPwr[rf_path][i] =
+			priv->RfOfdmChnlAreaTxPwr1T[rf_path][i] =
+			priv->RfOfdmChnlAreaTxPwr2T[rf_path][i] =
+			(u8)(EEPROM_Default_TxPower & 0xff);
+		}
+	}
+
+	for (i = 0; i < 3; i++)
+	{
+		//RT_TRACE((COMP_EFUSE), "CCK RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i,
+		//priv->RfCckChnlAreaTxPwr[rf_path][i]);
+		//RT_TRACE((COMP_EFUSE), "OFDM-1T RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i,
+		//priv->RfOfdmChnlAreaTxPwr1T[rf_path][i]);
+		//RT_TRACE((COMP_EFUSE), "OFDM-2T RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i,
+		//priv->RfOfdmChnlAreaTxPwr2T[rf_path][i]);
+	}
+
+	// Assign dedicated channel tx power
+	for(i=0; i<14; i++)	// channel 1~3 use the same Tx Power Level.
+		{
+		if (i < 3)			// Cjanel 1-3
+			index = 0;
+		else if (i < 9)		// Channel 4-9
+			index = 1;
+		else				// Channel 10-14
+			index = 2;
+
+		// Record A & B CCK /OFDM - 1T/2T Channel area tx power
+		priv->RfTxPwrLevelCck[rf_path][i]  =
+		priv->RfCckChnlAreaTxPwr[rf_path][index];
+		priv->RfTxPwrLevelOfdm1T[rf_path][i]  =
+		priv->RfOfdmChnlAreaTxPwr1T[rf_path][index];
+		priv->RfTxPwrLevelOfdm2T[rf_path][i]  =
+		priv->RfOfdmChnlAreaTxPwr2T[rf_path][index];
+		}
+
+		for(i=0; i<14; i++)
+		{
+		//RT_TRACE((COMP_EFUSE), "Rf-%d TxPwr CH-%d CCK OFDM_1T OFDM_2T= 0x%x/0x%x/0x%x\n",
+		//rf_path, i, priv->RfTxPwrLevelCck[0][i],
+		//priv->RfTxPwrLevelOfdm1T[0][i] ,
+		//priv->RfTxPwrLevelOfdm2T[0][i] );
+		}
+#endif
+
+	//
+	// Update remained HAL variables.
+	//
+	priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
+	priv->LegacyHTTxPowerDiff = priv->EEPROMTxPowerDiff;//new
+	priv->TxPowerDiff = priv->EEPROMTxPowerDiff;
+	//priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);// Antenna B gain offset to antenna A, bit0~3
+	//priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);// Antenna C gain offset to antenna A, bit4~7
+	priv->CrystalCap = priv->EEPROMCrystalCap;	// CrystalCap, bit12~15
+	priv->ThermalMeter[0] = priv->EEPROMThermalMeter;// ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
+	priv->LedStrategy = SW_LED_MODE0;
+
+	init_rate_adaptive(dev);
+
+	RT_TRACE(COMP_INIT, "<==== ConfigAdapterInfo8192SForAutoLoadFail\n");
+
+}
+
+#if 0
+static void rtl8192SU_ReadAdapterInfo8192SEEPROM(struct net_device* dev)
+{
+	u16 				EEPROMId = 0;
+	u8 				bLoad_From_EEPOM = false;
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	u16 				tmpValue = 0;
+	u8				tmpBuffer[30];
+	int i;
+
+	RT_TRACE(COMP_EPROM, "===========>%s()\n", __FUNCTION__);
+
+
+	write_nic_byte(dev, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
+	udelay(10000);
+	write_nic_byte(dev, PMC_FSM, 0x02); // Enable Loader Data Keep
+
+
+	EEPROMId = eprom_read(dev, 0); //first read EEPROM ID out;
+	RT_TRACE(COMP_EPROM, "EEPROM ID is 0x%x\n", EEPROMId);
+
+	if (EEPROMId != RTL8190_EEPROM_ID)
+	{
+		priv->AutoloadFailFlag = true;
+		RT_TRACE(COMP_ERR, "EEPROM ID is invalid(is 0x%x(should be 0x%x)\n", EEPROMId, RTL8190_EEPROM_ID);
+	}
+	else
+	{
+		priv->AutoloadFailFlag = false;
+		bLoad_From_EEPOM = true;
+	}
+
+	if (bLoad_From_EEPOM)
+	{
+		tmpValue = eprom_read(dev, (EEPROM_VID>>1));
+		priv->eeprom_vid = endian_swap(&tmpValue);
+		priv->eeprom_pid = eprom_read(dev, (EEPROM_PID>>1));
+
+		// Version ID, Channel plan
+		tmpValue = eprom_read(dev, (EEPROM_Version>>1));
+		//pHalData->card_8192_version = (VERSION_8192S)((usValue&0x00ff));
+		priv->eeprom_ChannelPlan =(tmpValue&0xff00)>>8;
+		priv->bTXPowerDataReadFromEEPORM = true;
+
+		// Customer ID, 0x00 and 0xff are reserved for Realtek.
+		tmpValue = eprom_read(dev, (u16)(EEPROM_CustomID>>1)) ;
+		priv->eeprom_CustomerID = (u8)( tmpValue & 0xff);
+		priv->eeprom_SubCustomerID = (u8)((tmpValue & 0xff00)>>8);
+	}
+	else
+	{
+		priv->eeprom_vid = 0;
+		priv->eeprom_pid = 0;
+		//priv->card_8192_version = VERSION_8192SU_A;
+		priv->eeprom_ChannelPlan = 0;
+		priv->eeprom_CustomerID = 0;
+		priv->eeprom_SubCustomerID = 0;
+	}
+	RT_TRACE(COMP_EPROM, "vid:0x%4x, pid:0x%4x, CustomID:0x%2x, ChanPlan:0x%x\n", priv->eeprom_vid, priv->eeprom_pid, priv->eeprom_CustomerID, priv->eeprom_ChannelPlan);
+	//set channelplan from eeprom
+	priv->ChannelPlan = priv->eeprom_ChannelPlan;// FIXLZM
+
+	RT_TRACE(COMP_INIT, "EEPROMId = 0x%4x\n", EEPROMId);
+	RT_TRACE(COMP_INIT, "EEPROM VID = 0x%4x\n", priv->eeprom_vid);
+	RT_TRACE(COMP_INIT, "EEPROM PID = 0x%4x\n", priv->eeprom_pid);
+	//RT_TRACE(COMP_INIT, DBG_LOUD, ("EEPROM Version ID: 0x%2x\n", pHalData->VersionID));
+	RT_TRACE(COMP_INIT, "EEPROM Customer ID: 0x%2x\n", priv->eeprom_CustomerID);
+	RT_TRACE(COMP_INIT, "EEPROM SubCustomer ID: 0x%2x\n", priv->eeprom_SubCustomerID);
+	RT_TRACE(COMP_INIT, "EEPROM ChannelPlan = 0x%4x\n", priv->eeprom_ChannelPlan);
+
+	// Read USB optional function.
+	if(bLoad_From_EEPOM)
+	{
+		tmpValue = eprom_read(dev, (EEPROM_USB_OPTIONAL>>1));
+		priv->EEPROMUsbOption = (u8)(tmpValue&0xff);
+	}
+	else
+	{
+		priv->EEPROMUsbOption = EEPROM_USB_Default_OPTIONAL_FUNC;
+	}
+
+	RT_TRACE(COMP_INIT, "USB Option = %#x\n", priv->EEPROMUsbOption);
+
+
+	if (bLoad_From_EEPOM)
+	{
+		int i;
+		for (i=0; i<6; i+=2)
+		{
+			u16 tmp = 0;
+			tmp = eprom_read(dev, (u16)((EEPROM_NODE_ADDRESS_BYTE_0 + i)>>1));
+			*(u16*)(&dev->dev_addr[i]) = tmp;
+		}
+	}
+	else
+	{
+		//<Roger_Notes> In this case, we random assigh MAC address here. 2008.10.15.
+		static u8 sMacAddr[6] = {0x00, 0xE0, 0x4C, 0x81, 0x92, 0x00};
+		u8	i;
+
+		//sMacAddr[5] = (u8)GetRandomNumber(1, 254);
+
+		for(i = 0; i < 6; i++)
+			dev->dev_addr[i] = sMacAddr[i];
+
+		//memcpy(dev->dev_addr, sMacAddr, 6);
+		//should I set IDR0 here?
+	}
+	write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
+	write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
+	RT_TRACE(COMP_EPROM, "MAC addr:"MAC_FMT"\n", MAC_ARG(dev->dev_addr));
+
+	priv->rf_type = RTL819X_DEFAULT_RF_TYPE; //default 1T2R
+#if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
+	priv->rf_chip = RF_6052;
+	priv->rf_type = RTL819X_DEFAULT_RF_TYPE;
+	//priv->card_8192_version = VERSION_8192SU_A; //Over write for temporally experiment. 2008.10.16. By Roger.
+#else
+	priv->rf_chip = RF_8256;
+#endif
+
+	{
+#if 0
+		if(bLoad_From_EEPOM)
+		{
+			tempval = (ReadEEprom(Adapter, (EEPROM_RFInd_PowerDiff>>1))) & 0xff;
+			if (tempval&0x80)	//RF-indication, bit[7]
+				pHalData->RF_Type = RF_1T2R;
+			else
+				pHalData->RF_Type = RF_2T4R;
+		}
+#endif
+
+		priv->EEPROMTxPowerDiff = EEPROM_Default_TxPowerDiff;
+		RT_TRACE(COMP_INIT, "TxPowerDiff = %#x\n", priv->EEPROMTxPowerDiff);
+
+
+		//
+		// Read antenna tx power offset of B/C/D to A  from EEPROM
+		// and read ThermalMeter from EEPROM
+		//
+		if(bLoad_From_EEPOM)
+		{
+			tmpValue = eprom_read(dev, (EEPROM_PwDiff>>1));
+			priv->EEPROMPwDiff = tmpValue&0x00ff;
+			priv->EEPROMThermalMeter = (tmpValue&0xff00)>>8;
+		}
+		else
+		{
+			priv->EEPROMPwDiff = EEPROM_Default_PwDiff;
+			priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
+		}
+		RT_TRACE(COMP_INIT, "PwDiff = %#x\n", priv->EEPROMPwDiff);
+		RT_TRACE(COMP_INIT, "ThermalMeter = %#x\n", priv->EEPROMThermalMeter);
+
+		priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
+
+
+		// Read CrystalCap from EEPROM
+		if(bLoad_From_EEPOM)
+		{
+			priv->EEPROMCrystalCap =(u8) (((eprom_read(dev, (EEPROM_CrystalCap>>1)))&0xf000)>>12);
+		}
+		else
+		{
+			priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
+		}
+		RT_TRACE(COMP_INIT, "CrystalCap = %#x\n", priv->EEPROMCrystalCap);
+
+
+		//if(pHalData->EEPROM_Def_Ver == 0)	// old eeprom definition
+		{
+
+			//
+			// Get Tx Power Base.//===>
+			//
+			if(bLoad_From_EEPOM)
+			{
+				priv->EEPROMTxPwrBase =(u8) ((eprom_read(dev, (EEPROM_TxPowerBase>>1)))&0xff);
+			}
+			else
+			{
+				priv->EEPROMTxPwrBase = EEPROM_Default_TxPowerBase;
+			}
+
+			RT_TRACE(COMP_INIT, "TxPwrBase = %#x\n", priv->EEPROMTxPwrBase);
+
+			//
+			// Get CustomerID(Boad Type)
+			// i.e., 0x0: RTL8188SU, 0x1: RTL8191SU, 0x2: RTL8192SU, 0x3: RTL8191GU.
+			// Others: Reserved. Default is 0x2: RTL8192SU.
+			//
+			if(bLoad_From_EEPOM)
+			{
+				tmpValue = eprom_read(dev, (u16) (EEPROM_BoardType>>1));
+				priv->EEPROMBoardType = (u8)(tmpValue&0xff);
+			}
+			else
+			{
+				priv->EEPROMBoardType = EEPROM_Default_BoardType;
+			}
+
+			RT_TRACE(COMP_INIT, "BoardType = %#x\n", priv->EEPROMBoardType);
+
+#ifdef EEPROM_OLD_FORMAT_SUPPORT
+
+			//
+			// Buffer TxPwIdx(i.e., from offset 0x58~0x75, total 30Bytes)
+			//
+			if(bLoad_From_EEPOM)
+			{
+				for(i = 0; i < 30; i += 2)
+				{
+					tmpValue = eprom_read(dev, (u16) ((EEPROM_TxPowerBase+i)>>1));
+					*((u16 *)(&tmpBuffer[i])) = tmpValue;
+				}
+			}
+
+			//
+			// Update CCK, OFDM Tx Power Index from above buffer.
+			//
+			if(bLoad_From_EEPOM)
+			{
+				for(i=0; i<14; i++)
+				{
+					priv->EEPROMTxPowerLevelCCK24G[i] = (u8)tmpBuffer[i+1];
+					priv->EEPROMTxPowerLevelOFDM24G[i] = (u8)tmpBuffer[i+15];
+				}
+
+			}
+			else
+			{
+				for(i=0; i<14; i++)
+				{
+					priv->EEPROMTxPowerLevelCCK24G[i] = (u8)(EEPROM_Default_TxPower & 0xff);
+					priv->EEPROMTxPowerLevelOFDM24G[i] = (u8)(EEPROM_Default_TxPower & 0xff);
+				}
+			}
+
+			for(i=0; i<14; i++)
+			{
+				RT_TRACE(COMP_INIT, "CCK 2.4G Tx Power Level, Index %d = 0x%02x\n", i, priv->EEPROMTxPowerLevelCCK24G[i]);
+				RT_TRACE(COMP_INIT, "OFDM 2.4G Tx Power Level, Index %d = 0x%02x\n", i, priv->EEPROMTxPowerLevelOFDM24G[i]);
+			}
+#else
+			// Please add code in the section!!!!
+			// And merge tx power difference section.
+#endif
+
+			//
+			// Get TSSI value for each path.
+			//
+			if(bLoad_From_EEPOM)
+			{
+				tmpValue = eprom_read(dev, (u16) ((EEPROM_TSSI_A)>>1));
+				priv->EEPROMTSSI_A = (u8)((tmpValue&0xff00)>>8);
+			}
+			else
+			{ // Default setting for Empty EEPROM
+				priv->EEPROMTSSI_A = EEPROM_Default_TSSI;
+			}
+
+			if(bLoad_From_EEPOM)
+			{
+				tmpValue = eprom_read(dev, (u16) ((EEPROM_TSSI_B)>>1));
+				priv->EEPROMTSSI_B = (u8)(tmpValue&0xff);
+				priv->EEPROMTxPwrTkMode = (u8)((tmpValue&0xff00)>>8);
+			}
+			else
+			{ // Default setting for Empty EEPROM
+				priv->EEPROMTSSI_B = EEPROM_Default_TSSI;
+				priv->EEPROMTxPwrTkMode = EEPROM_Default_TxPwrTkMode;
+			}
+
+			RT_TRACE(COMP_INIT, "TSSI_A = %#x, TSSI_B = %#x\n", priv->EEPROMTSSI_A, priv->EEPROMTSSI_B);
+			RT_TRACE(COMP_INIT, "TxPwrTkMod = %#x\n", priv->EEPROMTxPwrTkMode);
+
+#ifdef EEPROM_OLD_FORMAT_SUPPORT
+			//
+			// Get HT 2T Path A and B Power Index.
+			//
+			if(bLoad_From_EEPOM)
+			{
+				for(i = 0; i < 6; i += 2)
+				{
+					tmpValue = eprom_read(dev, (u16) ((EEPROM_HT2T_CH1_A+i)>>1));
+					*((u16*)(&priv->EEPROMHT2T_TxPwr[i])) = tmpValue;
+				}
+			}
+			else
+			{ // Default setting for Empty EEPROM
+				for(i=0; i<6; i++)
+				{
+					priv->EEPROMHT2T_TxPwr[i] = EEPROM_Default_HT2T_TxPwr;
+				}
+			}
+
+			for(i=0; i<6; i++)
+			{
+				RT_TRACE(COMP_INIT, "EEPROMHT2T_TxPwr, Index %d = 0x%02x\n", i, priv->EEPROMHT2T_TxPwr[i]);
+			}
+#else
+
+#endif
+		}
+
+#ifdef EEPROM_OLD_FORMAT_SUPPORT
+		//
+		// Update HAL variables.
+		//
+		for(i=0; i<14; i++)
+		{
+			priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[i];
+			priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK24G[i];
+		}
+#else
+
+#endif
+		priv->TxPowerDiff = priv->EEPROMPwDiff;
+		// Antenna B gain offset to antenna A, bit0~3
+		priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);
+		// Antenna C gain offset to antenna A, bit4~7
+		priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);
+		// CrystalCap, bit12~15
+		priv->CrystalCap = priv->EEPROMCrystalCap;
+		// ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
+		// 92U does not enable TX power tracking.
+		priv->ThermalMeter[0] = priv->EEPROMThermalMeter;
+	}
+
+	priv->LedStrategy = SW_LED_MODE0;
+
+	if(priv->rf_type == RF_1T2R)
+	{
+		RT_TRACE(COMP_EPROM, "\n1T2R config\n");
+	}
+	else
+	{
+		RT_TRACE(COMP_EPROM, "\n2T4R config\n");
+	}
+
+	// 2008/01/16 MH We can only know RF type in the function. So we have to init
+	// DIG RATR table again.
+	init_rate_adaptive(dev);
+	//we need init DIG RATR table here again.
+
+	RT_TRACE(COMP_EPROM, "<===========%s()\n", __FUNCTION__);
+	return;
+}
+
+//
+//	Description:
+//		1. Read HW adapter information by E-Fuse.
+//		2. Refered from SD1 Richard.
+//
+//	Assumption:
+//		1. Boot from E-Fuse and CR9346 regiser has verified.
+//		2. PASSIVE_LEVEL (USB interface)
+//
+//	Created by Roger, 2008.10.21.
+//
+void
+rtl8192SU_ReadAdapterInfo8192SEFuse(struct net_device* dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	u16			i,usValue;
+	u16			EEPROMId;
+	u8			readbyte;
+	u8			OFDMTxPwr[14];
+	u8			CCKTxPwr[14];
+	u8			HT2T_TxPwr[6];
+	u8			UsbPhyParam[5];
+	u8			hwinfo[HWSET_MAX_SIZE_92S];
+
+
+	RT_TRACE(COMP_INIT, "====> ReadAdapterInfo8192SEFuse\n");
+
+	//
+	// <Roger_Notes> We set Isolation signals from Loader and reset EEPROM after system resuming
+	// from suspend mode.
+	// 2008.10.21.
+	//
+	write_nic_byte(dev, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
+	//PlatformStallExecution(10000);
+	mdelay(10);
+	write_nic_byte(dev, SYS_FUNC_EN+1, 0x40);
+	write_nic_byte(dev, SYS_FUNC_EN+1, 0x50);
+
+	readbyte = read_nic_byte(dev, EFUSE_TEST+3);
+	write_nic_byte(dev, EFUSE_TEST+3, (readbyte | 0x80));
+	write_nic_byte(dev, EFUSE_TEST+3, 0x72);
+	write_nic_byte(dev, EFUSE_CLK, 0x03);
+
+	//
+	// Dump EFUSe at init time for later use
+	//
+	// Read EFUSE real map to shadow!!
+	EFUSE_ShadowMapUpdate(dev);
+
+	memcpy(hwinfo, (void*)&priv->EfuseMap[EFUSE_INIT_MAP][0], HWSET_MAX_SIZE_92S);
+	//RT_PRINT_DATA(COMP_INIT, DBG_LOUD, ("MAP \n"), hwinfo, HWSET_MAX_SIZE_92S);
+
+	//
+	// <Roger_Notes> Event though CR9346 regiser can verify whether Autoload is success or not, but we still
+	// double check ID codes for 92S here(e.g., due to HW GPIO polling fail issue).
+	// 2008.10.21.
+	//
+	ReadEFuse(dev, 0, 2, (unsigned char*) &EEPROMId);
+
+	if( EEPROMId != RTL8190_EEPROM_ID )
+	{
+		RT_TRACE(COMP_INIT, "EEPROM ID(%#x) is invalid!!\n", EEPROMId);
+		priv->AutoloadFailFlag=true;
+	}
+	else
+	{
+		priv->AutoloadFailFlag=false;
+	}
+
+       // Read IC Version && Channel Plan
+	if(!priv->AutoloadFailFlag)
+	{
+
+        	// VID, PID
+	    	ReadEFuse(dev, EEPROM_VID, 2, (unsigned char*) &priv->eeprom_vid);
+		ReadEFuse(dev, EEPROM_PID, 2, (unsigned char*) &priv->eeprom_pid);
+
+		// Version ID, Channel plan
+		ReadEFuse(dev, EEPROM_Version, 2, (unsigned char*) &usValue);
+		//pHalData->VersionID = (VERSION_8192S)(usValue&0x00ff);
+		priv->eeprom_ChannelPlan = (usValue&0xff00>>8);
+		priv->bTXPowerDataReadFromEEPORM = true;
+
+		// Customer ID, 0x00 and 0xff are reserved for Realtek.
+		ReadEFuse(dev, EEPROM_CustomID, 2, (unsigned char*) &usValue);
+		priv->eeprom_CustomerID = (u8)( usValue & 0xff);
+		priv->eeprom_SubCustomerID = (u8)((usValue & 0xff00)>>8);
+	}
+	else
+	{
+		priv->eeprom_vid = 0;
+		priv->eeprom_pid = 0;
+		priv->eeprom_ChannelPlan = 0;
+		priv->eeprom_CustomerID = 0;
+		priv->eeprom_SubCustomerID = 0;
+	}
+
+	RT_TRACE(COMP_INIT, "EEPROM Id = 0x%4x\n", EEPROMId);
+	RT_TRACE(COMP_INIT, "EEPROM VID = 0x%4x\n", priv->eeprom_vid);
+	RT_TRACE(COMP_INIT, "EEPROM PID = 0x%4x\n", priv->eeprom_pid);
+	//RT_TRACE(COMP_INIT, DBG_LOUD, ("EEPROM Version ID: 0x%2x\n", pHalData->VersionID));
+	RT_TRACE(COMP_INIT, "EEPROM Customer ID: 0x%2x\n", priv->eeprom_CustomerID);
+	RT_TRACE(COMP_INIT, "EEPROM SubCustomer ID: 0x%2x\n", priv->eeprom_SubCustomerID);
+	RT_TRACE(COMP_INIT, "EEPROM ChannelPlan = 0x%4x\n", priv->eeprom_ChannelPlan);
+
+
+	// Read USB optional function.
+	if(!priv->AutoloadFailFlag)
+	{
+		ReadEFuse(dev, EEPROM_USB_OPTIONAL, 1, (unsigned char*) &priv->EEPROMUsbOption);
+	}
+	else
+	{
+		priv->EEPROMUsbOption = EEPROM_USB_Default_OPTIONAL_FUNC;
+	}
+
+	RT_TRACE(COMP_INIT, "USB Option = %#x\n", priv->EEPROMUsbOption);
+
+
+	// Read USB PHY parameters.
+	if(!priv->AutoloadFailFlag)
+	{
+		ReadEFuse(dev, EEPROM_USB_PHY_PARA1, 5, (unsigned char*)UsbPhyParam);
+		for(i=0; i<5; i++)
+		{
+			priv->EEPROMUsbPhyParam[i] = UsbPhyParam[i];
+			RT_TRACE(COMP_INIT, "USB Param = index(%d) = %#x\n", i, priv->EEPROMUsbPhyParam[i]);
+		}
+	}
+	else
+	{
+		for(i=0; i<5; i++)
+		{
+			priv->EEPROMUsbPhyParam[i] = EEPROM_USB_Default_PHY_PARAM;
+			RT_TRACE(COMP_INIT, "USB Param = index(%d) = %#x\n", i, priv->EEPROMUsbPhyParam[i]);
+		}
+	}
+
+
+       //Read Permanent MAC address
+	if(!priv->AutoloadFailFlag)
+	{
+		u8			macaddr[6] = {0x00, 0xe1, 0x86, 0x4c, 0x92, 0x00};
+
+		ReadEFuse(dev, EEPROM_NODE_ADDRESS_BYTE_0, 6, (unsigned char*)macaddr);
+		for(i=0; i<6; i++)
+			dev->dev_addr[i] = macaddr[i];
+	}
+	else
+	{//Auto load fail
+
+		//<Roger_Notes> In this case, we random assigh MAC address here. 2008.10.15.
+		static u8 sMacAddr[6] = {0x00, 0xE0, 0x4C, 0x81, 0x92, 0x00};
+		u8	i;
+
+		//if(!Adapter->bInHctTest)
+                    //sMacAddr[5] = (u8)GetRandomNumber(1, 254);
+
+		for(i = 0; i < 6; i++)
+			dev->dev_addr[i] = sMacAddr[i];
+	}
+
+	//NicIFSetMacAddress(Adapter, Adapter->PermanentAddress);
+	write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
+	write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
+
+	RT_TRACE(COMP_INIT, "ReadAdapterInfo8192SEFuse(), Permanent Address = %02x-%02x-%02x-%02x-%02x-%02x\n",
+			dev->dev_addr[0], dev->dev_addr[1],
+			dev->dev_addr[2], dev->dev_addr[3],
+			dev->dev_addr[4], dev->dev_addr[5]);
+
+	// 2007/11/15 MH For RTL8192USB we assign as 1T2R now.
+	priv->rf_type = RTL819X_DEFAULT_RF_TYPE;	// default : 1T2R
+
+#if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
+	priv->rf_chip = RF_6052;
+	priv->rf_type = RTL819X_DEFAULT_RF_TYPE;
+#else
+	priv->rf_chip = RF_8256;
+#endif
+
+	{
+		//
+		// Read antenna tx power offset of B/C/D to A  from EEPROM
+		// and read ThermalMeter from EEPROM
+		//
+		if(!priv->AutoloadFailFlag)
+		{
+			ReadEFuse(dev, EEPROM_PwDiff, 2, (unsigned char*) &usValue);
+			priv->EEPROMPwDiff = usValue&0x00ff;
+			priv->EEPROMThermalMeter = (usValue&0xff00)>>8;
+		}
+		else
+		{
+			priv->EEPROMPwDiff = EEPROM_Default_PwDiff;
+			priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
+		}
+
+		RT_TRACE(COMP_INIT, "PwDiff = %#x\n", priv->EEPROMPwDiff);
+		RT_TRACE(COMP_INIT, "ThermalMeter = %#x\n", priv->EEPROMThermalMeter);
+
+		priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
+
+		//
+		// Read Tx Power gain offset of legacy OFDM to HT rate.
+		// Read CrystalCap from EEPROM
+		//
+		if(!priv->AutoloadFailFlag)
+		{
+			ReadEFuse(dev, EEPROM_CrystalCap, 1, (unsigned char*) &usValue);
+			priv->EEPROMCrystalCap = (u8)((usValue&0xf0)>>4);
+		}
+		else
+		{
+			priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
+		}
+
+		RT_TRACE(COMP_INIT, "CrystalCap = %#x\n", priv->EEPROMCrystalCap);
+
+		priv->EEPROMTxPowerDiff = EEPROM_Default_TxPowerDiff;
+		RT_TRACE(COMP_INIT, "TxPowerDiff = %d\n", priv->EEPROMTxPowerDiff);
+
+
+		//
+		// Get Tx Power Base.
+		//
+		if(!priv->AutoloadFailFlag)
+		{
+			ReadEFuse(dev, EEPROM_TxPowerBase, 1, (unsigned char*) &priv->EEPROMTxPwrBase );
+		}
+		else
+		{
+			priv->EEPROMTxPwrBase = EEPROM_Default_TxPowerBase;
+		}
+
+		RT_TRACE(COMP_INIT, "TxPwrBase = %#x\n", priv->EEPROMTxPwrBase);
+
+		//
+		// Get CustomerID(Boad Type)
+		// i.e., 0x0: RTL8188SU, 0x1: RTL8191SU, 0x2: RTL8192SU, 0x3: RTL8191GU.
+		// Others: Reserved. Default is 0x2: RTL8192SU.
+		//
+		if(!priv->AutoloadFailFlag)
+		{
+			ReadEFuse(dev, EEPROM_BoardType, 1, (unsigned char*) &priv->EEPROMBoardType );
+		}
+		else
+		{
+			priv->EEPROMBoardType = EEPROM_Default_BoardType;
+		}
+
+		RT_TRACE(COMP_INIT, "BoardType = %#x\n", priv->EEPROMBoardType);
+
+		//if(pHalData->EEPROM_Def_Ver == 0)
+		{
+#ifdef EEPROM_OLD_FORMAT_SUPPORT
+			//
+			// Get CCK Tx Power Index.
+			//
+			if(!priv->AutoloadFailFlag)
+			{
+				ReadEFuse(dev, EEPROM_TxPwIndex_CCK_24G, 14, (unsigned char*)CCKTxPwr);
+				for(i=0; i<14; i++)
+				{
+					RT_TRACE(COMP_INIT, "CCK 2.4G Tx Power Level, Index %d = 0x%02x\n", i, CCKTxPwr[i]);
+					priv->EEPROMTxPowerLevelCCK24G[i] = CCKTxPwr[i];
+				}
+			}
+			else
+			{ // Default setting for Empty EEPROM
+				for(i=0; i<14; i++)
+					priv->EEPROMTxPowerLevelCCK24G[i] = (u8)(EEPROM_Default_TxPower & 0xff);
+			}
+
+			//
+			// Get OFDM Tx Power Index.
+			//
+			if(!priv->AutoloadFailFlag)
+			{
+				ReadEFuse(dev, EEPROM_TxPwIndex_OFDM_24G, 14, (unsigned char*)OFDMTxPwr);
+				for(i=0; i<14; i++)
+				{
+					RT_TRACE(COMP_INIT, "OFDM 2.4G Tx Power Level, Index %d = 0x%02x\n", i, OFDMTxPwr[i]);
+					priv->EEPROMTxPowerLevelOFDM24G[i] = OFDMTxPwr[i];
+				}
+			}
+			else
+			{ // Default setting for Empty EEPROM
+				usValue = 0x10;
+				for(i=0; i<14; i++)
+					priv->EEPROMTxPowerLevelOFDM24G[i] = (u8)usValue;
+			}
+#else
+			// Please add code in the section!!!!
+			// And merge tx power difference section.
+#endif
+
+			//
+			// Get TSSI value for each path.
+			//
+			if(!priv->AutoloadFailFlag)
+			{
+				ReadEFuse(dev, EEPROM_TSSI_A, 2, (unsigned char*)&usValue);
+				priv->EEPROMTSSI_A = (u8)(usValue&0xff);
+				priv->EEPROMTSSI_B = (u8)((usValue&0xff00)>>8);
+			}
+			else
+			{ // Default setting for Empty EEPROM
+				priv->EEPROMTSSI_A = EEPROM_Default_TSSI;
+				priv->EEPROMTSSI_B = EEPROM_Default_TSSI;
+			}
+
+			RT_TRACE(COMP_INIT, "TSSI_A = %#x, TSSI_B = %#x\n",
+					priv->EEPROMTSSI_A, priv->EEPROMTSSI_B);
+
+			//
+			// Get Tx Power tracking mode.
+			//
+			if(!priv->AutoloadFailFlag)
+			{
+				ReadEFuse(dev, EEPROM_TxPwTkMode, 1, (unsigned char*)&priv->EEPROMTxPwrTkMode);
+			}
+			else
+			{ // Default setting for Empty EEPROM
+				priv->EEPROMTxPwrTkMode = EEPROM_Default_TxPwrTkMode;
+			}
+
+			RT_TRACE(COMP_INIT, "TxPwrTkMod = %#x\n", priv->EEPROMTxPwrTkMode);
+
+
+			// TODO: The following HT 2T Path A and B Power Index should be updated.!! Added by Roger, 2008.20.23.
+
+			//
+			// Get HT 2T Path A and B Power Index.
+			//
+			if(!priv->AutoloadFailFlag)
+			{
+				ReadEFuse(dev, EEPROM_HT2T_CH1_A, 6, (unsigned char*)HT2T_TxPwr);
+				for(i=0; i<6; i++)
+				{
+					priv->EEPROMHT2T_TxPwr[i] = HT2T_TxPwr[i];
+				}
+			}
+			else
+			{ // Default setting for Empty EEPROM
+				for(i=0; i<6; i++)
+				{
+					priv->EEPROMHT2T_TxPwr[i] = EEPROM_Default_HT2T_TxPwr;
+				}
+			}
+
+			for(i=0; i<6; i++)
+			{
+				RT_TRACE(COMP_INIT, "EEPROMHT2T_TxPwr, Index %d = 0x%02x\n",
+						i, priv->EEPROMHT2T_TxPwr[i]);
+			}
+		}
+
+#ifdef EEPROM_OLD_FORMAT_SUPPORT
+		//
+		// Update HAL variables.
+		//
+		for(i=0; i<14; i++)
+		{
+			priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[i];
+			priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK24G[i];
+		}
+#else
+
+#endif
+		priv->TxPowerDiff = priv->EEPROMPwDiff;
+		// Antenna B gain offset to antenna A, bit0~3
+		priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);
+		// Antenna C gain offset to antenna A, bit4~7
+		priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);
+		// CrystalCap, bit12~15
+		priv->CrystalCap = priv->EEPROMCrystalCap;
+		// ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
+		// 92U does not enable TX power tracking.
+		priv->ThermalMeter[0] = priv->EEPROMThermalMeter;
+	}
+
+	priv->LedStrategy = SW_LED_MODE0;
+
+	init_rate_adaptive(dev);
+
+	RT_TRACE(COMP_INIT, "<==== ReadAdapterInfo8192SEFuse\n");
+
+}
+#endif
+
+//
+//	Description:
+//		Read HW adapter information by E-Fuse or EEPROM according CR9346 reported.
+//
+//	Assumption:
+//		1. CR9346 regiser has verified.
+//		2. PASSIVE_LEVEL (USB interface)
+//
+//	Created by Roger, 2008.10.21.
+//
+void
+rtl8192SU_ReadAdapterInfo8192SUsb(struct net_device* dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	u16			i,usValue;
+	u8			tmpU1b, tempval;
+	u16			EEPROMId;
+	u8			hwinfo[HWSET_MAX_SIZE_92S];
+	u8			rf_path, index;	// For EEPROM/EFUSE After V0.6_1117
+
+
+	RT_TRACE(COMP_INIT, "====> ReadAdapterInfo8192SUsb\n");
+
+	//
+	// <Roger_Note> The following operation are prevent Efuse leakage by turn on 2.5V.
+	// 2008.11.25.
+	//
+	tmpU1b = read_nic_byte(dev, EFUSE_TEST+3);
+	write_nic_byte(dev, EFUSE_TEST+3, tmpU1b|0x80);
+	//PlatformStallExecution(1000);
+	mdelay(10);
+	write_nic_byte(dev, EFUSE_TEST+3, (tmpU1b&(~BIT7)));
+
+	// Retrieve Chip version.
+	priv->card_8192_version = (VERSION_8192S)((read_nic_dword(dev, PMC_FSM)>>16)&0xF);
+	RT_TRACE(COMP_INIT, "Chip Version ID: 0x%2x\n", priv->card_8192_version);
+
+	switch(priv->card_8192_version)
+	{
+		case 0:
+			RT_TRACE(COMP_INIT, "Chip Version ID: VERSION_8192S_ACUT.\n");
+			break;
+		case 1:
+			RT_TRACE(COMP_INIT, "Chip Version ID: VERSION_8192S_BCUT.\n");
+			break;
+		case 2:
+			RT_TRACE(COMP_INIT, "Chip Version ID: VERSION_8192S_CCUT.\n");
+			break;
+		default:
+			RT_TRACE(COMP_INIT, "Unknown Chip Version!!\n");
+			priv->card_8192_version = VERSION_8192S_BCUT;
+			break;
+	}
+
+	//if (IS_BOOT_FROM_EEPROM(Adapter))
+	if(priv->EepromOrEfuse)
+	{	// Read frin EEPROM
+		write_nic_byte(dev, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
+		//PlatformStallExecution(10000);
+		mdelay(10);
+		write_nic_byte(dev, PMC_FSM, 0x02); // Enable Loader Data Keep
+		// Read all Content from EEPROM or EFUSE.
+		for(i = 0; i < HWSET_MAX_SIZE_92S; i += 2)
+		{
+			usValue = eprom_read(dev, (u16) (i>>1));
+			*((u16*)(&hwinfo[i])) = usValue;
+		}
+	}
+	else if (!(priv->EepromOrEfuse))
+	{	// Read from EFUSE
+
+		//
+		// <Roger_Notes> We set Isolation signals from Loader and reset EEPROM after system resuming
+		// from suspend mode.
+		// 2008.10.21.
+		//
+		//PlatformEFIOWrite1Byte(Adapter, SYS_ISO_CTRL+1, 0xE8); // Isolation signals from Loader
+		//PlatformStallExecution(10000);
+		//PlatformEFIOWrite1Byte(Adapter, SYS_FUNC_EN+1, 0x40);
+		//PlatformEFIOWrite1Byte(Adapter, SYS_FUNC_EN+1, 0x50);
+
+		//tmpU1b = PlatformEFIORead1Byte(Adapter, EFUSE_TEST+3);
+		//PlatformEFIOWrite1Byte(Adapter, EFUSE_TEST+3, (tmpU1b | 0x80));
+		//PlatformEFIOWrite1Byte(Adapter, EFUSE_TEST+3, 0x72);
+		//PlatformEFIOWrite1Byte(Adapter, EFUSE_CLK, 0x03);
+
+		// Read EFUSE real map to shadow.
+		EFUSE_ShadowMapUpdate(dev);
+		memcpy(hwinfo, &priv->EfuseMap[EFUSE_INIT_MAP][0], HWSET_MAX_SIZE_92S);
+	}
+	else
+	{
+		RT_TRACE(COMP_INIT, "ReadAdapterInfo8192SUsb(): Invalid boot type!!\n");
+	}
+
+	//YJ,test,090106
+	//dump_buf(hwinfo,HWSET_MAX_SIZE_92S);
+	//
+	// <Roger_Notes> The following are EFUSE/EEPROM independent operations!!
+	//
+	//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("MAP: \n"), hwinfo, HWSET_MAX_SIZE_92S);
+
+	//
+	// <Roger_Notes> Event though CR9346 regiser can verify whether Autoload is success or not, but we still
+	// double check ID codes for 92S here(e.g., due to HW GPIO polling fail issue).
+	// 2008.10.21.
+	//
+	EEPROMId = *((u16 *)&hwinfo[0]);
+
+	if( EEPROMId != RTL8190_EEPROM_ID )
+	{
+		RT_TRACE(COMP_INIT, "ID(%#x) is invalid!!\n", EEPROMId);
+		priv->bTXPowerDataReadFromEEPORM = FALSE;
+		priv->AutoloadFailFlag=TRUE;
+	}
+	else
+	{
+		priv->AutoloadFailFlag=FALSE;
+#if RTL8192SU_USE_PARAM_TXPWR
+		priv->bTXPowerDataReadFromEEPORM = FALSE;
+#else
+		priv->bTXPowerDataReadFromEEPORM = TRUE;
+#endif
+
+	}
+       // Read IC Version && Channel Plan
+	if(!priv->AutoloadFailFlag)
+	{
+        	// VID, PID
+	    	priv->eeprom_vid = *(u16 *)&hwinfo[EEPROM_VID];
+		priv->eeprom_pid = *(u16 *)&hwinfo[EEPROM_PID];
+		priv->bIgnoreDiffRateTxPowerOffset = false;	//cosa for test
+
+
+		// EEPROM Version ID, Channel plan
+		priv->EEPROMVersion = *(u8 *)&hwinfo[EEPROM_Version];
+		priv->eeprom_ChannelPlan = *(u8 *)&hwinfo[EEPROM_ChannelPlan];
+
+		// Customer ID, 0x00 and 0xff are reserved for Realtek.
+		priv->eeprom_CustomerID = *(u8 *)&hwinfo[EEPROM_CustomID];
+		priv->eeprom_SubCustomerID = *(u8 *)&hwinfo[EEPROM_SubCustomID];
+	}
+	else
+	{
+		//priv->eeprom_vid = 0;
+		//priv->eeprom_pid = 0;
+		//priv->EEPROMVersion = 0;
+		//priv->eeprom_ChannelPlan = 0;
+		//priv->eeprom_CustomerID = 0;
+		//priv->eeprom_SubCustomerID = 0;
+
+		rtl8192SU_ConfigAdapterInfo8192SForAutoLoadFail(dev);
+		return;
+	}
+
+
+	RT_TRACE(COMP_INIT, "EEPROM Id = 0x%4x\n", EEPROMId);
+	RT_TRACE(COMP_INIT, "EEPROM VID = 0x%4x\n", priv->eeprom_vid);
+	RT_TRACE(COMP_INIT, "EEPROM PID = 0x%4x\n", priv->eeprom_pid);
+	RT_TRACE(COMP_INIT, "EEPROM Version ID: 0x%2x\n", priv->EEPROMVersion);
+	RT_TRACE(COMP_INIT, "EEPROM Customer ID: 0x%2x\n", priv->eeprom_CustomerID);
+	RT_TRACE(COMP_INIT, "EEPROM SubCustomer ID: 0x%2x\n", priv->eeprom_SubCustomerID);
+	RT_TRACE(COMP_INIT, "EEPROM ChannelPlan = 0x%4x\n", priv->eeprom_ChannelPlan);
+	RT_TRACE(COMP_INIT, "bIgnoreDiffRateTxPowerOffset = %d\n", priv->bIgnoreDiffRateTxPowerOffset);
+
+
+	// Read USB optional function.
+	if(!priv->AutoloadFailFlag)
+	{
+		priv->EEPROMUsbOption = *(u8 *)&hwinfo[EEPROM_USB_OPTIONAL];
+	}
+	else
+	{
+		priv->EEPROMUsbOption = EEPROM_USB_Default_OPTIONAL_FUNC;
+	}
+
+
+	priv->EEPROMUsbEndPointNumber = rtl8192SU_UsbOptionToEndPointNumber((priv->EEPROMUsbOption&EEPROM_EP_NUMBER)>>3);
+
+	RT_TRACE(COMP_INIT, "USB Option = %#x\n", priv->EEPROMUsbOption);
+	RT_TRACE(COMP_INIT, "EndPoint Number = %#x\n", priv->EEPROMUsbEndPointNumber);
+
+#ifdef TO_DO_LIST
+	//
+	//  Decide CustomerID according to VID/DID or EEPROM
+	//
+	switch(pHalData->EEPROMCustomerID)
+	{
+		case EEPROM_CID_ALPHA:
+			pMgntInfo->CustomerID = RT_CID_819x_ALPHA;
+			break;
+
+		case EEPROM_CID_CAMEO:
+			pMgntInfo->CustomerID = RT_CID_819x_CAMEO;
+			break;
+
+		case EEPROM_CID_SITECOM:
+			pMgntInfo->CustomerID = RT_CID_819x_Sitecom;
+			RT_TRACE(COMP_INIT, DBG_LOUD, ("CustomerID = 0x%4x\n", pMgntInfo->CustomerID));
+
+			break;
+
+		case EEPROM_CID_WHQL:
+			Adapter->bInHctTest = TRUE;
+
+			pMgntInfo->bSupportTurboMode = FALSE;
+			pMgntInfo->bAutoTurboBy8186 = FALSE;
+
+			pMgntInfo->PowerSaveControl.bInactivePs = FALSE;
+			pMgntInfo->PowerSaveControl.bIPSModeBackup = FALSE;
+			pMgntInfo->PowerSaveControl.bLeisurePs = FALSE;
+			pMgntInfo->keepAliveLevel = 0;
+			break;
+
+		default:
+			pMgntInfo->CustomerID = RT_CID_DEFAULT;
+			break;
+
+	}
+
+	//
+	// Led mode
+	//
+	switch(pMgntInfo->CustomerID)
+	{
+		case RT_CID_DEFAULT:
+		case RT_CID_819x_ALPHA:
+			pHalData->LedStrategy = SW_LED_MODE1;
+			pHalData->bRegUseLed = TRUE;
+			pHalData->SwLed1.bLedOn = TRUE;
+			break;
+		case RT_CID_819x_CAMEO:
+			pHalData->LedStrategy = SW_LED_MODE1;
+			pHalData->bRegUseLed = TRUE;
+			break;
+
+		case RT_CID_819x_Sitecom:
+			pHalData->LedStrategy = SW_LED_MODE2;
+			pHalData->bRegUseLed = TRUE;
+			break;
+
+		default:
+			pHalData->LedStrategy = SW_LED_MODE0;
+			break;
+	}
+#endif
+
+	// Read USB PHY parameters.
+	for(i=0; i<5; i++)
+		priv->EEPROMUsbPhyParam[i] = *(u8 *)&hwinfo[EEPROM_USB_PHY_PARA1+i];
+
+	//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("USB PHY Param: \n"), pHalData->EEPROMUsbPhyParam, 5);
+
+
+       //Read Permanent MAC address
+	for(i=0; i<6; i++)
+		dev->dev_addr[i] =  *(u8 *)&hwinfo[EEPROM_NODE_ADDRESS_BYTE_0+i];
+
+	//NicIFSetMacAddress(Adapter, Adapter->PermanentAddress);
+	write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
+	write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
+
+	RT_TRACE(COMP_INIT, "ReadAdapterInfo8192SEFuse(), Permanent Address = %02x-%02x-%02x-%02x-%02x-%02x\n",
+			dev->dev_addr[0], dev->dev_addr[1],
+			dev->dev_addr[2], dev->dev_addr[3],
+			dev->dev_addr[4], dev->dev_addr[5]);
+
+	//
+	// Get CustomerID(Boad Type)
+	// i.e., 0x0: RTL8188SU, 0x1: RTL8191SU, 0x2: RTL8192SU, 0x3: RTL8191GU.
+	// Others: Reserved. Default is 0x2: RTL8192SU.
+	//
+	//if(!priv->AutoloadFailFlag)
+	//{
+		priv->EEPROMBoardType = *(u8 *)&hwinfo[EEPROM_BoardType];
+		priv->rf_type = rtl8192SU_BoardTypeToRFtype(dev, priv->EEPROMBoardType);
+	//}
+	//else
+	//{
+	//	priv->EEPROMBoardType = EEPROM_Default_BoardType;
+	//	priv->rf_type = RF_1T2R;
+	//}
+
+#if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
+	priv->rf_chip = RF_6052;
+#else
+	priv->rf_chip = RF_8256;
+#endif
+
+	priv->rf_chip = RF_6052;//lzm test
+	RT_TRACE(COMP_INIT, "BoardType = 0x%2x\n", priv->EEPROMBoardType);
+	RT_TRACE(COMP_INIT, "RF_Type = 0x%2x\n", priv->rf_type);
+
+	//
+	// Read antenna tx power offset of B/C/D to A  from EEPROM
+	// and read ThermalMeter from EEPROM
+	//
+	//if(!priv->AutoloadFailFlag)
+	{
+		priv->EEPROMTxPowerDiff = *(u8 *)&hwinfo[EEPROM_PwDiff];
+		priv->EEPROMThermalMeter = *(u8 *)&hwinfo[EEPROM_ThermalMeter];
+	}
+	//else
+	//{
+	//	priv->EEPROMTxPowerDiff = EEPROM_Default_PwDiff;
+	//	priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
+	//}
+
+	RT_TRACE(COMP_INIT, "PwDiff = %#x\n", priv->EEPROMTxPowerDiff);
+	RT_TRACE(COMP_INIT, "ThermalMeter = %#x\n", priv->EEPROMThermalMeter);
+
+	//
+	// Read Tx Power gain offset of legacy OFDM to HT rate.
+	// Read CrystalCap from EEPROM
+	//
+	//if(!priv->AutoloadFailFlag)
+	{
+		priv->EEPROMCrystalCap = *(u8 *)&hwinfo[EEPROM_CrystalCap];
+	}
+	//else
+	//{
+	//	priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
+	//}
+
+	RT_TRACE(COMP_INIT, "CrystalCap = %#x\n", priv->EEPROMCrystalCap);
+
+	//
+	// Get Tx Power Base.
+	//
+	//if(!priv->AutoloadFailFlag)
+	{
+		priv->EEPROMTxPwrBase = *(u8 *)&hwinfo[EEPROM_TxPowerBase];
+	}
+	//else
+	//{
+	//	priv->EEPROMTxPwrBase = EEPROM_Default_TxPowerBase;
+	//}
+
+	RT_TRACE(COMP_INIT, "TxPwrBase = %#x\n", priv->EEPROMTxPwrBase);
+
+
+	//
+	// Get TSSI value for each path.
+	//
+	//if(!priv->AutoloadFailFlag)
+	{
+		priv->EEPROMTSSI_A = *(u8 *)&hwinfo[EEPROM_TSSI_A];
+		priv->EEPROMTSSI_B = *(u8 *)&hwinfo[EEPROM_TSSI_B];
+	}
+	//else
+	//{ // Default setting for Empty EEPROM
+	//	priv->EEPROMTSSI_A = EEPROM_Default_TSSI;
+	//	priv->EEPROMTSSI_B = EEPROM_Default_TSSI;
+	//}
+
+	RT_TRACE(COMP_INIT, "TSSI_A = %#x, TSSI_B = %#x\n", priv->EEPROMTSSI_A, priv->EEPROMTSSI_B);
+
+	//
+	// Get Tx Power tracking mode.
+	//
+	//if(!priv->AutoloadFailFlag)
+	{
+		priv->EEPROMTxPwrTkMode = *(u8 *)&hwinfo[EEPROM_TxPwTkMode];
+	}
+
+	RT_TRACE(COMP_INIT, "TxPwrTkMod = %#x\n", priv->EEPROMTxPwrTkMode);
+
+
+#ifdef EEPROM_OLD_FORMAT_SUPPORT
+
+	//
+	// <Roger_Notes> The following settings are EFUSE version dependence.
+	// So we need to adjust reading offset.
+	// 2008.11.22.
+	//
+	{
+			//
+			// Get HT 2T Path A and B Power Index.
+			//
+			//if(!priv->AutoloadFailFlag)
+			{
+				for(i=0; i<6; i++)
+				{
+				priv->EEPROMHT2T_TxPwr[i] = *(u8 *)&hwinfo[EEPROM_HT2T_CH1_A+i];
+				}
+			}
+
+		//RT_PRINT_DATA(COMP_EFUSE, "HT2T TxPwr: \n"), pHalData->EEPROMHT2T_TxPwr, 6);
+
+		//
+		// Get CCK and OFDM Tx Power Index.
+		//
+		//if(!priv->AutoloadFailFlag)
+		{
+			for(i=0; i<14; i++)
+			{
+				priv->EEPROMTxPowerLevelCCK24G[i] = *(u8 *)&hwinfo[EEPROM_TxPwIndex_CCK_24G+i];
+				priv->EEPROMTxPowerLevelOFDM24G[i] = *(u8 *)&hwinfo[EEPROM_TxPwIndex_OFDM_24G+i];
+			}
+		}
+
+		//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("CCK 2.4G TxPwr: \n"), pHalData->EEPROMTxPowerLevelCCK24G, 14);
+		//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("OFDM 2.4G TxPwr: \n"), pHalData->EEPROMTxPowerLevelOFDM24G, 14);
+
+		//
+		// Update HAL variables.
+		//
+		memcpy( priv->TxPowerLevelOFDM24G, priv->EEPROMTxPowerLevelOFDM24G, 14);
+		memcpy( priv->TxPowerLevelCCK, priv->EEPROMTxPowerLevelCCK24G, 14);
+		//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("HAL CCK 2.4G TxPwr: \n"), pHalData->TxPowerLevelCCK, 14);
+		//RT_PRINT_DATA(COMP_EFUSE, DBG_LOUD, ("HAL OFDM 2.4G TxPwr: \n"), pHalData->TxPowerLevelOFDM24G, 14);
+
+	}
+#else // Support new version of EFUSE content, 2008.11.22.
+	{
+		//
+		// Buffer TxPwIdx(i.e., from offset 0x55~0x66, total 18Bytes)
+		// Update CCK, OFDM (1T/2T)Tx Power Index from above buffer.
+		//
+
+		//
+		// Get Tx Power Level by Channel
+		//
+		//if(!priv->AutoloadFailFlag)
+		{
+			// Read Tx power of Channel 1 ~ 14 from EFUSE.
+			// 92S suupport RF A & B
+			for (rf_path = 0; rf_path < 2; rf_path++)
+			{
+				for (i = 0; i < 3; i++)
+				{
+					// Read CCK RF A & B Tx power
+					priv->RfCckChnlAreaTxPwr[rf_path][i] =
+					hwinfo[EEPROM_TxPwIndex+rf_path*3+i];
+
+					// Read OFDM RF A & B Tx power for 1T
+					priv->RfOfdmChnlAreaTxPwr1T[rf_path][i] =
+					hwinfo[EEPROM_TxPwIndex+6+rf_path*3+i];
+
+					// Read OFDM RF A & B Tx power for 2T
+					priv->RfOfdmChnlAreaTxPwr2T[rf_path][i] =
+					hwinfo[EEPROM_TxPwIndex+12+rf_path*3+i];
+				}
+			}
+
+		}
+//
+		// Update Tx Power HAL variables.
+//
+		for (rf_path = 0; rf_path < 2; rf_path++)
+		{
+			for (i = 0; i < 3; i++)
+			{
+				RT_TRACE((COMP_INIT),  "CCK RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i,
+				priv->RfCckChnlAreaTxPwr[rf_path][i]);
+				RT_TRACE((COMP_INIT), "OFDM-1T RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i,
+				priv->RfOfdmChnlAreaTxPwr1T[rf_path][i]);
+				RT_TRACE((COMP_INIT), "OFDM-2T RF-%d CHan_Area-%d = 0x%x\n",  rf_path, i, priv->RfOfdmChnlAreaTxPwr2T[rf_path][i]);
+			}
+
+			// Assign dedicated channel tx power
+			for(i=0; i<14; i++)	// channel 1~3 use the same Tx Power Level.
+			{
+				if (i < 3)			// Cjanel 1-3
+					index = 0;
+				else if (i < 9)		// Channel 4-9
+					index = 1;
+				else				// Channel 10-14
+					index = 2;
+
+				// Record A & B CCK /OFDM - 1T/2T Channel area tx power
+				priv->RfTxPwrLevelCck[rf_path][i]  =
+				priv->RfCckChnlAreaTxPwr[rf_path][index];
+				priv->RfTxPwrLevelOfdm1T[rf_path][i]  =
+				priv->RfOfdmChnlAreaTxPwr1T[rf_path][index];
+				priv->RfTxPwrLevelOfdm2T[rf_path][i]  =
+				priv->RfOfdmChnlAreaTxPwr2T[rf_path][index];
+				if (rf_path == 0)
+				{
+					priv->TxPowerLevelOFDM24G[i] = priv->RfTxPwrLevelOfdm1T[rf_path][i] ;
+					priv->TxPowerLevelCCK[i] = priv->RfTxPwrLevelCck[rf_path][i];
+				}
+			}
+
+			for(i=0; i<14; i++)
+			{
+				RT_TRACE((COMP_INIT),
+				"Rf-%d TxPwr CH-%d CCK OFDM_1T OFDM_2T= 0x%x/0x%x/0x%x\n",
+				rf_path, i, priv->RfTxPwrLevelCck[rf_path][i],
+				priv->RfTxPwrLevelOfdm1T[rf_path][i] ,
+				priv->RfTxPwrLevelOfdm2T[rf_path][i] );
+			}
+		}
+	}
+
+	//
+	// 2009/02/09 Cosa add for new EEPROM format
+	//
+	for(i=0; i<14; i++)	// channel 1~3 use the same Tx Power Level.
+	{
+		// Read tx power difference between HT OFDM 20/40 MHZ
+		if (i < 3)			// Cjanel 1-3
+			index = 0;
+		else if (i < 9)		// Channel 4-9
+			index = 1;
+		else				// Channel 10-14
+			index = 2;
+
+		tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_HT20_DIFF+index])&0xff;
+		priv->TxPwrHt20Diff[RF90_PATH_A][i] = (tempval&0xF);
+		priv->TxPwrHt20Diff[RF90_PATH_B][i] = ((tempval>>4)&0xF);
+
+		// Read OFDM<->HT tx power diff
+		if (i < 3)			// Cjanel 1-3
+			tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_OFDM_DIFF])&0xff;
+		else if (i < 9)		// Channel 4-9
+			tempval = (*(u8 *)&hwinfo[EEPROM_PwDiff])&0xff;
+		else				// Channel 10-14
+			tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_OFDM_DIFF+1])&0xff;
+
+		//cosa tempval = (*(u1Byte *)&hwinfo[EEPROM_TX_PWR_OFDM_DIFF+index])&0xff;
+		priv->TxPwrLegacyHtDiff[RF90_PATH_A][i] = (tempval&0xF);
+		priv->TxPwrLegacyHtDiff[RF90_PATH_B][i] = ((tempval>>4)&0xF);
+
+		//
+		// Read Band Edge tx power offset and check if user enable the ability
+		//
+		// HT 40 band edge channel
+		tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE])&0xff;
+		priv->TxPwrbandEdgeHt40[RF90_PATH_A][0] = (tempval&0xF); 		// Band edge low channel
+		priv->TxPwrbandEdgeHt40[RF90_PATH_A][1] =  ((tempval>>4)&0xF);	// Band edge high channel
+		tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+1])&0xff;
+		priv->TxPwrbandEdgeHt40[RF90_PATH_B][0] = (tempval&0xF); 		// Band edge low channel
+		priv->TxPwrbandEdgeHt40[RF90_PATH_B][1] =  ((tempval>>4)&0xF);	// Band edge high channel
+		// HT 20 band edge channel
+		tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+2])&0xff;
+		priv->TxPwrbandEdgeHt20[RF90_PATH_A][0] = (tempval&0xF); 		// Band edge low channel
+		priv->TxPwrbandEdgeHt20[RF90_PATH_A][1] =  ((tempval>>4)&0xF);	// Band edge high channel
+		tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+3])&0xff;
+		priv->TxPwrbandEdgeHt20[RF90_PATH_B][0] = (tempval&0xF); 		// Band edge low channel
+		priv->TxPwrbandEdgeHt20[RF90_PATH_B][1] =  ((tempval>>4)&0xF);	// Band edge high channel
+		// OFDM band edge channel
+		tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+4])&0xff;
+		priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][0] = (tempval&0xF); 		// Band edge low channel
+		priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][1] =  ((tempval>>4)&0xF);	// Band edge high channel
+		tempval = (*(u8 *)&hwinfo[EEPROM_TX_PWR_BAND_EDGE+5])&0xff;
+		priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][0] = (tempval&0xF); 		// Band edge low channel
+		priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][1] =  ((tempval>>4)&0xF);	// Band edge high channel
+
+		priv->TxPwrbandEdgeFlag = (*(u8 *)&hwinfo[TX_PWR_BAND_EDGE_CHK]);
+	}
+
+	for(i=0; i<14; i++)
+		RT_TRACE(COMP_INIT, "RF-A Ht20 to HT40 Diff[%d] = 0x%x\n", i, priv->TxPwrHt20Diff[RF90_PATH_A][i]);
+	for(i=0; i<14; i++)
+		RT_TRACE(COMP_INIT,  "RF-A Legacy to Ht40 Diff[%d] = 0x%x\n", i, priv->TxPwrLegacyHtDiff[RF90_PATH_A][i]);
+	for(i=0; i<14; i++)
+		RT_TRACE(COMP_INIT,  "RF-B Ht20 to HT40 Diff[%d] = 0x%x\n", i, priv->TxPwrHt20Diff[RF90_PATH_B][i]);
+	for(i=0; i<14; i++)
+		RT_TRACE(COMP_INIT,  "RF-B Legacy to HT40 Diff[%d] = 0x%x\n", i, priv->TxPwrLegacyHtDiff[RF90_PATH_B][i]);
+	RT_TRACE(COMP_INIT, "RF-A HT40 band-edge low/high power diff = 0x%x/0x%x\n",
+		priv->TxPwrbandEdgeHt40[RF90_PATH_A][0],
+		priv->TxPwrbandEdgeHt40[RF90_PATH_A][1]);
+	RT_TRACE((COMP_INIT&COMP_DBG), "RF-B HT40 band-edge low/high power diff = 0x%x/0x%x\n",
+		priv->TxPwrbandEdgeHt40[RF90_PATH_B][0],
+		priv->TxPwrbandEdgeHt40[RF90_PATH_B][1]);
+
+	RT_TRACE((COMP_INIT&COMP_DBG), "RF-A HT20 band-edge low/high power diff = 0x%x/0x%x\n",
+		priv->TxPwrbandEdgeHt20[RF90_PATH_A][0],
+		priv->TxPwrbandEdgeHt20[RF90_PATH_A][1]);
+	RT_TRACE((COMP_INIT&COMP_DBG), "RF-B HT20 band-edge low/high power diff = 0x%x/0x%x\n",
+		priv->TxPwrbandEdgeHt20[RF90_PATH_B][0],
+		priv->TxPwrbandEdgeHt20[RF90_PATH_B][1]);
+
+	RT_TRACE((COMP_INIT&COMP_DBG), "RF-A OFDM band-edge low/high power diff = 0x%x/0x%x\n",
+		priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][0],
+		priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_A][1]);
+	RT_TRACE((COMP_INIT&COMP_DBG), "RF-B OFDM band-edge low/high power diff = 0x%x/0x%x\n",
+		priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][0],
+		priv->TxPwrbandEdgeLegacyOfdm[RF90_PATH_B][1]);
+	RT_TRACE((COMP_INIT&COMP_DBG), "Band-edge enable flag = %d\n", priv->TxPwrbandEdgeFlag);
+#endif
+
+	//
+	// Update remained HAL variables.
+	//
+	priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
+	priv->LegacyHTTxPowerDiff = priv->EEPROMTxPowerDiff;
+	priv->TxPowerDiff = priv->EEPROMTxPowerDiff;
+	//priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);// Antenna B gain offset to antenna A, bit[3:0]
+	//priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);// Antenna C gain offset to antenna A, bit[7:4]
+	priv->CrystalCap = priv->EEPROMCrystalCap;	// CrystalCap, bit[15:12]
+	priv->ThermalMeter[0] = (priv->EEPROMThermalMeter&0x1f);// ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
+	priv->LedStrategy = SW_LED_MODE0;
+
+	init_rate_adaptive(dev);
+
+	RT_TRACE(COMP_INIT, "<==== ReadAdapterInfo8192SUsb\n");
+
+	//return RT_STATUS_SUCCESS;
+}
+
+
+//
+//	Description:
+//		Read HW adapter information by E-Fuse or EEPROM according CR9346 reported.
+//
+//	Assumption:
+//		1. CR9346 regiser has verified.
+//		2. PASSIVE_LEVEL (USB interface)
+//
+//	Created by Roger, 2008.10.21.
+//
+static void rtl8192SU_read_eeprom_info(struct net_device *dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	u8			tmpU1b;
+
+	RT_TRACE(COMP_INIT, "====> ReadAdapterInfo8192SUsb\n");
+
+	// Retrieve Chip version.
+	priv->card_8192_version = (VERSION_8192S)((read_nic_dword(dev, PMC_FSM)>>16)&0xF);
+	RT_TRACE(COMP_INIT, "Chip Version ID: 0x%2x\n", priv->card_8192_version);
+
+	tmpU1b = read_nic_byte(dev, EPROM_CMD);//CR9346
+
+	// To check system boot selection.
+	if (tmpU1b & CmdEERPOMSEL)
+	{
+		RT_TRACE(COMP_INIT, "Boot from EEPROM\n");
+		priv->EepromOrEfuse = TRUE;
+	}
+	else
+	{
+		RT_TRACE(COMP_INIT, "Boot from EFUSE\n");
+		priv->EepromOrEfuse = FALSE;
+	}
+
+	// To check autoload success or not.
+	if (tmpU1b & CmdEEPROM_En)
+	{
+		RT_TRACE(COMP_INIT, "Autoload OK!!\n");
+		priv->AutoloadFailFlag=FALSE;
+		rtl8192SU_ReadAdapterInfo8192SUsb(dev);//eeprom or e-fuse
+	}
+	else
+	{ // Auto load fail.
+		RT_TRACE(COMP_INIT, "AutoLoad Fail reported from CR9346!!\n");
+		priv->AutoloadFailFlag=TRUE;
+		rtl8192SU_ConfigAdapterInfo8192SForAutoLoadFail(dev);
+
+		//if (IS_BOOT_FROM_EFUSE(Adapter))
+		if(!priv->EepromOrEfuse)
+		{
+			RT_TRACE(COMP_INIT, "Update shadow map for EFuse future use!!\n");
+			EFUSE_ShadowMapUpdate(dev);
+		}
+	}
+#ifdef TO_DO_LIST
+	if((priv->RegChannelPlan >= RT_CHANNEL_DOMAIN_MAX) || (pHalData->EEPROMChannelPlan & EEPROM_CHANNEL_PLAN_BY_HW_MASK))
+	{
+		pMgntInfo->ChannelPlan = HalMapChannelPlan8192S(Adapter, (pHalData->EEPROMChannelPlan & (~(EEPROM_CHANNEL_PLAN_BY_HW_MASK))));
+		pMgntInfo->bChnlPlanFromHW = (pHalData->EEPROMChannelPlan & EEPROM_CHANNEL_PLAN_BY_HW_MASK) ? TRUE : FALSE; // User cannot change  channel plan.
+	}
+	else
+	{
+		pMgntInfo->ChannelPlan = (RT_CHANNEL_DOMAIN)pMgntInfo->RegChannelPlan;
+	}
+
+	switch(pMgntInfo->ChannelPlan)
+	{
+		case RT_CHANNEL_DOMAIN_GLOBAL_DOAMIN:
+		{
+			PRT_DOT11D_INFO	pDot11dInfo = GET_DOT11D_INFO(pMgntInfo);
+
+			pDot11dInfo->bEnabled = TRUE;
+		}
+		RT_TRACE(COMP_INIT, DBG_LOUD, ("ReadAdapterInfo8187(): Enable dot11d when RT_CHANNEL_DOMAIN_GLOBAL_DOAMIN!\n"));
+		break;
+	}
+
+	RT_TRACE(COMP_INIT, DBG_LOUD, ("RegChannelPlan(%d) EEPROMChannelPlan(%d)", pMgntInfo->RegChannelPlan, pHalData->EEPROMChannelPlan));
+	RT_TRACE(COMP_INIT, DBG_LOUD, ("ChannelPlan = %d\n" , pMgntInfo->ChannelPlan));
+
+	RT_TRACE(COMP_INIT, DBG_LOUD, ("<==== ReadAdapterInfo8192S\n"));
+#endif
+
+	RT_TRACE(COMP_INIT, "<==== ReadAdapterInfo8192SUsb\n");
+
+	//return RT_STATUS_SUCCESS;
+}
+#else
+static void rtl8192_read_eeprom_info(struct net_device* dev)
+{
+	u16 wEPROM_ID = 0;
+	u8 bMac_Tmp_Addr[6] = {0x00, 0xe0, 0x4c, 0x00, 0x00, 0x02};
+	u8 bLoad_From_EEPOM = false;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u16 tmpValue = 0;
+	RT_TRACE(COMP_EPROM, "===========>%s()\n", __FUNCTION__);
+	wEPROM_ID = eprom_read(dev, 0); //first read EEPROM ID out;
+	RT_TRACE(COMP_EPROM, "EEPROM ID is 0x%x\n", wEPROM_ID);
+
+	if (wEPROM_ID != RTL8190_EEPROM_ID)
+	{
+		RT_TRACE(COMP_ERR, "EEPROM ID is invalid(is 0x%x(should be 0x%x)\n", wEPROM_ID, RTL8190_EEPROM_ID);
+	}
+	else
+		bLoad_From_EEPOM = true;
+
+	if (bLoad_From_EEPOM)
+	{
+		tmpValue = eprom_read(dev, (EEPROM_VID>>1));
+		priv->eeprom_vid = endian_swap(&tmpValue);
+		priv->eeprom_pid = eprom_read(dev, (EEPROM_PID>>1));
+		tmpValue = eprom_read(dev, (EEPROM_ChannelPlan>>1));
+		priv->eeprom_ChannelPlan =((tmpValue&0xff00)>>8);
+		priv->btxpowerdata_readfromEEPORM = true;
+		priv->eeprom_CustomerID = eprom_read(dev, (EEPROM_Customer_ID>>1)) >>8;
+	}
+	else
+	{
+		priv->eeprom_vid = 0;
+		priv->eeprom_pid = 0;
+		priv->card_8192_version = VERSION_819xU_B;
+		priv->eeprom_ChannelPlan = 0;
+		priv->eeprom_CustomerID = 0;
+	}
+	RT_TRACE(COMP_EPROM, "vid:0x%4x, pid:0x%4x, CustomID:0x%2x, ChanPlan:0x%x\n", priv->eeprom_vid, priv->eeprom_pid, priv->eeprom_CustomerID, priv->eeprom_ChannelPlan);
+	//set channelplan from eeprom
+	priv->ChannelPlan = priv->eeprom_ChannelPlan;
+	if (bLoad_From_EEPOM)
+	{
+		int i;
+		for (i=0; i<6; i+=2)
+		{
+			u16 tmp = 0;
+			tmp = eprom_read(dev, (u16)((EEPROM_NODE_ADDRESS_BYTE_0 + i)>>1));
+			*(u16*)(&dev->dev_addr[i]) = tmp;
+		}
+	}
+	else
+	{
+		memcpy(dev->dev_addr, bMac_Tmp_Addr, 6);
+		//should I set IDR0 here?
+	}
+	RT_TRACE(COMP_EPROM, "MAC addr:"MAC_FMT"\n", MAC_ARG(dev->dev_addr));
+	priv->rf_type = RTL819X_DEFAULT_RF_TYPE; //default 1T2R
+	priv->rf_chip = RF_8256;
+
+	if (priv->card_8192_version == (u8)VERSION_819xU_A)
+	{
+		//read Tx power gain offset of legacy OFDM to HT rate
+		if (bLoad_From_EEPOM)
+			priv->EEPROMTxPowerDiff = (eprom_read(dev, (EEPROM_TxPowerDiff>>1))&0xff00) >> 8;
+		else
+			priv->EEPROMTxPowerDiff = EEPROM_Default_TxPower;
+		RT_TRACE(COMP_EPROM, "TxPowerDiff:%d\n", priv->EEPROMTxPowerDiff);
+		//read ThermalMeter from EEPROM
+		if (bLoad_From_EEPOM)
+			priv->EEPROMThermalMeter = (u8)(eprom_read(dev, (EEPROM_ThermalMeter>>1))&0x00ff);
+		else
+			priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
+		RT_TRACE(COMP_EPROM, "ThermalMeter:%d\n", priv->EEPROMThermalMeter);
+		//vivi, for tx power track
+		priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
+		//read antenna tx power offset of B/C/D to A from EEPROM
+		if (bLoad_From_EEPOM)
+			priv->EEPROMPwDiff = (eprom_read(dev, (EEPROM_PwDiff>>1))&0x0f00)>>8;
+		else
+			priv->EEPROMPwDiff = EEPROM_Default_PwDiff;
+		RT_TRACE(COMP_EPROM, "TxPwDiff:%d\n", priv->EEPROMPwDiff);
+		// Read CrystalCap from EEPROM
+		if (bLoad_From_EEPOM)
+			priv->EEPROMCrystalCap = (eprom_read(dev, (EEPROM_CrystalCap>>1))&0x0f);
+		else
+			priv->EEPROMCrystalCap = EEPROM_Default_CrystalCap;
+		RT_TRACE(COMP_EPROM, "CrystalCap = %d\n", priv->EEPROMCrystalCap);
+		//get per-channel Tx power level
+		if (bLoad_From_EEPOM)
+			priv->EEPROM_Def_Ver = (eprom_read(dev, (EEPROM_TxPwIndex_Ver>>1))&0xff00)>>8;
+		else
+			priv->EEPROM_Def_Ver = 1;
+		RT_TRACE(COMP_EPROM, "EEPROM_DEF_VER:%d\n", priv->EEPROM_Def_Ver);
+		if (priv->EEPROM_Def_Ver == 0) //old eeprom definition
+		{
+			int i;
+			if (bLoad_From_EEPOM)
+				priv->EEPROMTxPowerLevelCCK = (eprom_read(dev, (EEPROM_TxPwIndex_CCK>>1))&0xff) >> 8;
+			else
+				priv->EEPROMTxPowerLevelCCK = 0x10;
+			RT_TRACE(COMP_EPROM, "CCK Tx Power Levl: 0x%02x\n", priv->EEPROMTxPowerLevelCCK);
+			for (i=0; i<3; i++)
+			{
+				if (bLoad_From_EEPOM)
+				{
+					tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_OFDM_24G+i)>>1);
+					if (((EEPROM_TxPwIndex_OFDM_24G+i) % 2) == 0)
+						tmpValue = tmpValue & 0x00ff;
+					else
+						tmpValue = (tmpValue & 0xff00) >> 8;
+				}
+				else
+					tmpValue = 0x10;
+				priv->EEPROMTxPowerLevelOFDM24G[i] = (u8) tmpValue;
+				RT_TRACE(COMP_EPROM, "OFDM 2.4G Tx Power Level, Index %d = 0x%02x\n", i, priv->EEPROMTxPowerLevelCCK);
+			}
+		}//end if EEPROM_DEF_VER == 0
+		else if (priv->EEPROM_Def_Ver == 1)
+		{
+			if (bLoad_From_EEPOM)
+			{
+				tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_CCK_V1>>1));
+				tmpValue = (tmpValue & 0xff00) >> 8;
+			}
+			else
+				tmpValue = 0x10;
+			priv->EEPROMTxPowerLevelCCK_V1[0] = (u8)tmpValue;
+
+			if (bLoad_From_EEPOM)
+				tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_CCK_V1 + 2)>>1);
+			else
+				tmpValue = 0x1010;
+			*((u16*)(&priv->EEPROMTxPowerLevelCCK_V1[1])) = tmpValue;
+			if (bLoad_From_EEPOM)
+				tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_OFDM_24G_V1>>1));
+			else
+				tmpValue = 0x1010;
+			*((u16*)(&priv->EEPROMTxPowerLevelOFDM24G[0])) = tmpValue;
+			if (bLoad_From_EEPOM)
+				tmpValue = eprom_read(dev, (EEPROM_TxPwIndex_OFDM_24G_V1+2)>>1);
+			else
+				tmpValue = 0x10;
+			priv->EEPROMTxPowerLevelOFDM24G[2] = (u8)tmpValue;
+		}//endif EEPROM_Def_Ver == 1
+
+		//update HAL variables
+		//
+		{
+			int i;
+			for (i=0; i<14; i++)
+			{
+				if (i<=3)
+					priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[0];
+				else if (i>=4 && i<=9)
+					priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[1];
+				else
+					priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[2];
+			}
+
+			for (i=0; i<14; i++)
+			{
+				if (priv->EEPROM_Def_Ver == 0)
+				{
+					if (i<=3)
+						priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelOFDM24G[0] + (priv->EEPROMTxPowerLevelCCK - priv->EEPROMTxPowerLevelOFDM24G[1]);
+					else if (i>=4 && i<=9)
+						priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK;
+					else
+						priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelOFDM24G[2] + (priv->EEPROMTxPowerLevelCCK - priv->EEPROMTxPowerLevelOFDM24G[1]);
+				}
+				else if (priv->EEPROM_Def_Ver == 1)
+				{
+					if (i<=3)
+						priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[0];
+					else if (i>=4 && i<=9)
+						priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[1];
+					else
+						priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[2];
+				}
+			}
+		}//end update HAL variables
+		priv->TxPowerDiff = priv->EEPROMPwDiff;
+// Antenna B gain offset to antenna A, bit0~3
+		priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);
+		// Antenna C gain offset to antenna A, bit4~7
+		priv->AntennaTxPwDiff[1] = ((priv->EEPROMTxPowerDiff & 0xf0)>>4);
+		// CrystalCap, bit12~15
+		priv->CrystalCap = priv->EEPROMCrystalCap;
+		// ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
+		// 92U does not enable TX power tracking.
+		priv->ThermalMeter[0] = priv->EEPROMThermalMeter;
+	}//end if VersionID == VERSION_819xU_A
+
+//added by vivi, for dlink led, 20080416
+	switch(priv->eeprom_CustomerID)
+	{
+		case EEPROM_CID_RUNTOP:
+			priv->CustomerID = RT_CID_819x_RUNTOP;
+			break;
+
+		case EEPROM_CID_DLINK:
+			priv->CustomerID = RT_CID_DLINK;
+			break;
+
+		default:
+			priv->CustomerID = RT_CID_DEFAULT;
+			break;
+
+	}
+
+	switch(priv->CustomerID)
+	{
+		case RT_CID_819x_RUNTOP:
+			priv->LedStrategy = SW_LED_MODE2;
+			break;
+
+ 		case RT_CID_DLINK:
+			priv->LedStrategy = SW_LED_MODE4;
+			break;
+
+		default:
+			priv->LedStrategy = SW_LED_MODE0;
+			break;
+
+	}
+
+
+	if(priv->rf_type == RF_1T2R)
+	{
+		RT_TRACE(COMP_EPROM, "\n1T2R config\n");
+	}
+	else
+	{
+		RT_TRACE(COMP_EPROM, "\n2T4R config\n");
+	}
+
+	// 2008/01/16 MH We can only know RF type in the function. So we have to init
+	// DIG RATR table again.
+	init_rate_adaptive(dev);
+	//we need init DIG RATR table here again.
+
+	RT_TRACE(COMP_EPROM, "<===========%s()\n", __FUNCTION__);
+	return;
+}
+#endif
+
+short rtl8192_get_channel_map(struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+#ifdef ENABLE_DOT11D
+	if(priv->ChannelPlan > COUNTRY_CODE_GLOBAL_DOMAIN){
+		printk("rtl8180_init:Error channel plan! Set to default.\n");
+		priv->ChannelPlan= 0;
+	}
+	RT_TRACE(COMP_INIT, "Channel plan is %d\n",priv->ChannelPlan);
+
+	rtl819x_set_channel_map(priv->ChannelPlan, priv);
+#else
+	int ch,i;
+	//Set Default Channel Plan
+	if(!channels){
+		DMESG("No channels, aborting");
+		return -1;
+	}
+	ch=channels;
+	priv->ChannelPlan= 0;//hikaru
+	 // set channels 1..14 allowed in given locale
+	for (i=1; i<=14; i++) {
+		(priv->ieee80211->channel_map)[i] = (u8)(ch & 0x01);
+		ch >>= 1;
+	}
+#endif
+	return 0;
+}
+
+short rtl8192_init(struct net_device *dev)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+#ifndef RTL8192SU
+	memset(&(priv->stats),0,sizeof(struct Stats));
+	memset(priv->txqueue_to_outpipemap,0,9);
+#ifdef PIPE12
+	{
+		int i=0;
+		u8 queuetopipe[]={3,2,1,0,4,8,7,6,5};
+		memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
+/*		for(i=0;i<9;i++)
+			printk("%d ",priv->txqueue_to_outpipemap[i]);
+		printk("\n");*/
+	}
+#else
+	{
+		u8 queuetopipe[]={3,2,1,0,4,4,0,4,4};
+		memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
+/*		for(i=0;i<9;i++)
+			printk("%d ",priv->txqueue_to_outpipemap[i]);
+		printk("\n");*/
+	}
+#endif
+#endif
+	rtl8192_init_priv_variable(dev);
+	rtl8192_init_priv_lock(priv);
+	rtl8192_init_priv_task(dev);
+	rtl8192_get_eeprom_size(dev);
+	priv->ops->rtl819x_read_eeprom_info(dev);
+	rtl8192_get_channel_map(dev);
+	init_hal_dm(dev);
+	init_timer(&priv->watch_dog_timer);
+	priv->watch_dog_timer.data = (unsigned long)dev;
+	priv->watch_dog_timer.function = watch_dog_timer_callback;
+
+	//rtl8192_adapter_start(dev);
+#ifdef DEBUG_EPROM
+	dump_eprom(dev);
+#endif
+	return 0;
+}
+
+/******************************************************************************
+ *function:  This function actually only set RRSR, RATR and BW_OPMODE registers
+ *	     not to do all the hw config as its name says
+ *   input:  net_device dev
+ *  output:  none
+ *  return:  none
+ *  notice:  This part need to modified according to the rate set we filtered
+ * ****************************************************************************/
+void rtl8192_hwconfig(struct net_device* dev)
+{
+	u32 regRATR = 0, regRRSR = 0;
+	u8 regBwOpMode = 0, regTmp = 0;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+// Set RRSR, RATR, and BW_OPMODE registers
+	//
+	switch(priv->ieee80211->mode)
+	{
+	case WIRELESS_MODE_B:
+		regBwOpMode = BW_OPMODE_20MHZ;
+		regRATR = RATE_ALL_CCK;
+		regRRSR = RATE_ALL_CCK;
+		break;
+	case WIRELESS_MODE_A:
+		regBwOpMode = BW_OPMODE_5G |BW_OPMODE_20MHZ;
+		regRATR = RATE_ALL_OFDM_AG;
+		regRRSR = RATE_ALL_OFDM_AG;
+		break;
+	case WIRELESS_MODE_G:
+		regBwOpMode = BW_OPMODE_20MHZ;
+		regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		break;
+	case WIRELESS_MODE_AUTO:
+#ifdef TO_DO_LIST
+		if (Adapter->bInHctTest)
+		{
+		    regBwOpMode = BW_OPMODE_20MHZ;
+		    regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		    regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		}
+		else
+#endif
+		{
+		    regBwOpMode = BW_OPMODE_20MHZ;
+		    regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
+		    regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		}
+		break;
+	case WIRELESS_MODE_N_24G:
+		// It support CCK rate by default.
+		// CCK rate will be filtered out only when associated AP does not support it.
+		regBwOpMode = BW_OPMODE_20MHZ;
+			regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
+			regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		break;
+	case WIRELESS_MODE_N_5G:
+		regBwOpMode = BW_OPMODE_5G;
+		regRATR = RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
+		regRRSR = RATE_ALL_OFDM_AG;
+		break;
+	}
+
+	write_nic_byte(dev, BW_OPMODE, regBwOpMode);
+	{
+		u32 ratr_value = 0;
+		ratr_value = regRATR;
+		if (priv->rf_type == RF_1T2R)
+		{
+			ratr_value &= ~(RATE_ALL_OFDM_2SS);
+		}
+		write_nic_dword(dev, RATR0, ratr_value);
+		write_nic_byte(dev, UFWP, 1);
+	}
+	regTmp = read_nic_byte(dev, 0x313);
+	regRRSR = ((regTmp) << 24) | (regRRSR & 0x00ffffff);
+	write_nic_dword(dev, RRSR, regRRSR);
+
+	//
+	// Set Retry Limit here
+	//
+	write_nic_word(dev, RETRY_LIMIT,
+			priv->ShortRetryLimit << RETRY_LIMIT_SHORT_SHIFT | \
+			priv->LongRetryLimit << RETRY_LIMIT_LONG_SHIFT);
+	// Set Contention Window here
+
+	// Set Tx AGC
+
+	// Set Tx Antenna including Feedback control
+
+	// Set Auto Rate fallback control
+
+
+}
+
+#ifdef RTL8192SU
+#ifdef USB_RX_AGGREGATION_SUPPORT
+u8 rtl8192SU_MapRxPageSizeToIdx(u16 RxPktSize	)
+{
+	switch(RxPktSize)
+	{
+		case 64:		return 0; break;
+		case 128	:	return 1; break;
+		case 256:		return 2; break;
+		case 512:		return 3; break;
+		case 1024:	return 4; break;
+		default:		return 0;	// We use 64bytes in defult.
+	}
+}
+#endif
+
+//
+//	Description:
+//		Initial HW relted registers.
+//
+//	Assumption:
+//		Config RTL8192S USB MAC, we should config MAC before download FW.
+//
+//	2008.09.03, Added by Roger.
+//
+static void rtl8192SU_MacConfigBeforeFwDownloadASIC(struct net_device *dev)
+{
+	u8				tmpU1b;// i;
+//	u16				tmpU2b;
+//	u32				tmpU4b;
+	u8				PollingCnt = 20;
+
+	RT_TRACE(COMP_INIT, "--->MacConfigBeforeFwDownloadASIC()\n");
+
+	//2MAC Initialization for power on sequence, Revised by Roger. 2008.09.03.
+
+	//
+	//<Roger_Notes> Set control path switch to HW control and reset Digital Core,  CPU Core and
+	// MAC I/O to solve FW download fail when system from resume sate.
+	// 2008.11.04.
+	//
+       tmpU1b = read_nic_byte(dev, SYS_CLKR+1);
+       if(tmpU1b & 0x80)
+	{
+       	tmpU1b &= 0x3f;
+              write_nic_byte(dev, SYS_CLKR+1, tmpU1b);
+       }
+	// Clear FW RPWM for FW control LPS. by tynli. 2009.02.23
+	write_nic_byte(dev, RPWM, 0x0);
+
+       tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
+       tmpU1b &= 0x73;
+       write_nic_byte(dev, SYS_FUNC_EN+1, tmpU1b);
+       udelay(1000);
+
+	//Revised POS, suggested by SD1 Alex, 2008.09.27.
+	write_nic_byte(dev, SPS0_CTRL+1, 0x53);
+	write_nic_byte(dev, SPS0_CTRL, 0x57);
+
+	//Enable AFE Macro Block's Bandgap adn Enable AFE Macro Block's Mbias
+	tmpU1b = read_nic_byte(dev, AFE_MISC);
+	write_nic_byte(dev, AFE_MISC, (tmpU1b|AFE_BGEN|AFE_MBEN));
+
+	//Enable PLL Power (LDOA15V)
+	tmpU1b = read_nic_byte(dev, LDOA15_CTRL);
+	write_nic_byte(dev, LDOA15_CTRL, (tmpU1b|LDA15_EN));
+
+	//Enable LDOV12D block
+	tmpU1b = read_nic_byte(dev, LDOV12D_CTRL);
+	write_nic_byte(dev, LDOV12D_CTRL, (tmpU1b|LDV12_EN));
+
+	//mpU1b = read_nic_byte(Adapter, SPS1_CTRL);
+	//write_nic_byte(dev, SPS1_CTRL, (tmpU1b|SPS1_LDEN));
+
+	//PlatformSleepUs(2000);
+
+	//Enable Switch Regulator Block
+	//tmpU1b = read_nic_byte(Adapter, SPS1_CTRL);
+	//write_nic_byte(dev, SPS1_CTRL, (tmpU1b|SPS1_SWEN));
+
+	//write_nic_dword(Adapter, SPS1_CTRL, 0x00a7b267);
+
+	tmpU1b = read_nic_byte(dev, SYS_ISO_CTRL+1);
+	write_nic_byte(dev, SYS_ISO_CTRL+1, (tmpU1b|0x08));
+
+	//Engineer Packet CP test Enable
+	tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
+	write_nic_byte(dev, SYS_FUNC_EN+1, (tmpU1b|0x20));
+
+	//Support 64k IMEM, suggested by SD1 Alex.
+	tmpU1b = read_nic_byte(dev, SYS_ISO_CTRL+1);
+	write_nic_byte(dev, SYS_ISO_CTRL+1, (tmpU1b& 0x68));
+
+	//Enable AFE clock
+	tmpU1b = read_nic_byte(dev, AFE_XTAL_CTRL+1);
+	write_nic_byte(dev, AFE_XTAL_CTRL+1, (tmpU1b& 0xfb));
+
+	//Enable AFE PLL Macro Block
+	tmpU1b = read_nic_byte(dev, AFE_PLL_CTRL);
+	write_nic_byte(dev, AFE_PLL_CTRL, (tmpU1b|0x11));
+
+	//Attatch AFE PLL to MACTOP/BB/PCIe Digital
+	tmpU1b = read_nic_byte(dev, SYS_ISO_CTRL);
+	write_nic_byte(dev, SYS_ISO_CTRL, (tmpU1b&0xEE));
+
+	// Switch to 40M clock
+	write_nic_byte(dev, SYS_CLKR, 0x00);
+
+	//SSC Disable
+	tmpU1b = read_nic_byte(dev, SYS_CLKR);
+	//write_nic_byte(dev, SYS_CLKR, (tmpU1b&0x5f));
+	write_nic_byte(dev, SYS_CLKR, (tmpU1b|0xa0));
+
+	//Enable MAC clock
+	tmpU1b = read_nic_byte(dev, SYS_CLKR+1);
+	write_nic_byte(dev, SYS_CLKR+1, (tmpU1b|0x18));
+
+	//Revised POS, suggested by SD1 Alex, 2008.09.27.
+	write_nic_byte(dev, PMC_FSM, 0x02);
+
+	//Enable Core digital and enable IOREG R/W
+	tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
+	write_nic_byte(dev, SYS_FUNC_EN+1, (tmpU1b|0x08));
+
+	//Enable REG_EN
+	tmpU1b = read_nic_byte(dev, SYS_FUNC_EN+1);
+	write_nic_byte(dev, SYS_FUNC_EN+1, (tmpU1b|0x80));
+
+	//Switch the control path to FW
+	tmpU1b = read_nic_byte(dev, SYS_CLKR+1);
+	write_nic_byte(dev, SYS_CLKR+1, (tmpU1b|0x80)& 0xBF);
+
+	write_nic_byte(dev, CMDR, 0xFC);
+	write_nic_byte(dev, CMDR+1, 0x37);
+
+	//Fix the RX FIFO issue(usb error), 970410
+	tmpU1b = read_nic_byte_E(dev, 0x5c);
+	write_nic_byte_E(dev, 0x5c, (tmpU1b|BIT7));
+
+	 //For power save, used this in the bit file after 970621
+	tmpU1b = read_nic_byte(dev, SYS_CLKR);
+	write_nic_byte(dev, SYS_CLKR, tmpU1b&(~SYS_CPU_CLKSEL));
+
+	// Revised for 8051 ROM code wrong operation. Added by Roger. 2008.10.16.
+	write_nic_byte_E(dev, 0x1c, 0x80);
+
+	//
+	// <Roger_EXP> To make sure that TxDMA can ready to download FW.
+	// We should reset TxDMA if IMEM RPT was not ready.
+	// Suggested by SD1 Alex. 2008.10.23.
+	//
+	do
+	{
+		tmpU1b = read_nic_byte(dev, TCR);
+		if((tmpU1b & TXDMA_INIT_VALUE) == TXDMA_INIT_VALUE)
+			break;
+		//PlatformStallExecution(5);
+		udelay(5);
+	}while(PollingCnt--);	// Delay 1ms
+
+	if(PollingCnt <= 0 )
+	{
+		RT_TRACE(COMP_INIT, "MacConfigBeforeFwDownloadASIC(): Polling TXDMA_INIT_VALUE timeout!! Current TCR(%#x)\n", tmpU1b);
+		tmpU1b = read_nic_byte(dev, CMDR);
+		write_nic_byte(dev, CMDR, tmpU1b&(~TXDMA_EN));
+		udelay(2);
+		write_nic_byte(dev, CMDR, tmpU1b|TXDMA_EN);// Reset TxDMA
+	}
+
+
+	RT_TRACE(COMP_INIT, "<---MacConfigBeforeFwDownloadASIC()\n");
+}
+#ifdef USB_RX_AGGREGATION_SUPPORT
+void rtl8192SU_HalUsbRxAggr8192SUsb(struct net_device *dev, bool Value)
+{
+	struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
+	PRT_HIGH_THROUGHPUT	pHTInfo = priv->ieee80211->pHTInfo;;
+
+
+	//
+	// <Roger_Notes> We decrease Rx page aggregated threshold in B/G mode.
+	// 2008.10.29
+	//
+	if(priv->ieee80211->mode == WIRELESS_MODE_B ||  priv->ieee80211->mode == WIRELESS_MODE_G)
+	{// Overwrite current settings to disable Rx Aggregation.
+		Value = false;
+	}
+
+	// Alway set Rx Aggregation to Disable if current platform is Win2K USB 1.1, by Emily
+	//if(PLATFORM_LIMITED_RX_BUF_SIZE(Adapter))
+	//	Value = FALSE;
+
+	// Always set Rx Aggregation to Disable if connected AP is Realtek AP, by Joseph
+	//if(pHTInfo->bCurrentRT2RTAggregation)
+	//	Value = FALSE;
+
+	// The RX aggregation may be enabled/disabled dynamically according current traffic stream.
+	//Enable Rx aggregation if downlink traffic is busier than uplink traffic. by Guangan
+	if(priv->bCurrentRxAggrEnable != Value)
+	{
+		priv->bCurrentRxAggrEnable = Value;
+		//Adapter->HalFunc.SetHwRegHandler(Adapter, HW_VAR_USB_RX_AGGR, (pu1Byte)&pHalData->bCurrentRxAggrEnable);
+		{
+			//u8 	Setting = ((pu1Byte)(val))[0];
+			u8 	Setting = priv->bCurrentRxAggrEnable
+			u32 	ulValue;
+
+			if(Setting==0)
+			{
+				//
+				// <Roger_Notes> Reduce aggregated page threshold to 0x01 and set minimal threshold 0x0a.
+				// i.e., disable Rx aggregation.
+				//
+				ulValue = 0x0001000a;
+			}
+			else
+			{
+				//PRT_HIGH_THROUGHPUT	pHTInfo = priv->ieee80211->pHTInfo;
+				//HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter);
+
+				if (priv->bForcedUsbRxAggr)
+				{// Using forced settings.
+					ulValue = priv->ForcedUsbRxAggrInfo;
+				}
+				else
+				{// Using default settings.
+
+					ulValue = (pHTInfo->UsbRxFwAggrEn<<24) | (pHTInfo->UsbRxFwAggrPageNum<<16) |
+							(pHTInfo->UsbRxFwAggrPacketNum<<8) | (pHTInfo->UsbRxFwAggrTimeout);
+				}
+			}
+
+			write_nic_byte(dev, RXDMA_AGG_PG_TH, (u8)((ulValue&0xff0000)>>16));
+			write_nic_byte_E(dev, USB_RX_AGG_TIMEOUT, (u8)(ulValue&0xff));
+
+			priv->LastUsbRxAggrInfoSetting = ulValue;
+
+			RT_TRACE(COMP_HT|COMP_RECV, "Set HW_VAR_USB_RX_AGGR: ulValue(%#x)\n", ulValue);
+		}
+		RT_TRACE(COMP_RECV, "HalUsbRxAggr8192SUsb() :  Set RxAggregation to %s\n", Value?"ON":"OFF");
+	}
+
+}
+#endif
+
+#ifdef USB_RX_AGGREGATION_SUPPORT
+void rtl8192SU_HalUsbRxAggr8192SUsb(struct net_device *dev, bool Value)
+{
+	struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
+	PRT_HIGH_THROUGHPUT	pHTInfo = priv->ieee80211->pHTInfo;;
+
+
+	//
+	// <Roger_Notes> We decrease Rx page aggregated threshold in B/G mode.
+	// 2008.10.29
+	//
+	if((priv->ieee80211->mode & WIRELESS_MODE_B) || (priv->ieee80211->mode & WIRELESS_MODE_G))
+	{// Overwrite current settings to disable Rx Aggregation.
+		Value = false;
+	}
+
+	// Alway set Rx Aggregation to Disable if current platform is Win2K USB 1.1, by Emily
+	//if(PLATFORM_LIMITED_RX_BUF_SIZE(Adapter))
+	//	Value = FALSE;
+
+	// Always set Rx Aggregation to Disable if connected AP is Realtek AP, by Joseph
+	//if(pHTInfo->bCurrentRT2RTAggregation)
+	//	Value = FALSE;
+
+	// The RX aggregation may be enabled/disabled dynamically according current traffic stream.
+	//Enable Rx aggregation if downlink traffic is busier than uplink traffic. by Guangan
+	if(priv->bCurrentRxAggrEnable != Value)
+	{
+		priv->bCurrentRxAggrEnable = Value;
+		//Adapter->HalFunc.SetHwRegHandler(Adapter, HW_VAR_USB_RX_AGGR, (pu1Byte)&pHalData->bCurrentRxAggrEnable);
+		{
+			//u8 	Setting = ((pu1Byte)(val))[0];
+			u8 	Setting = priv->bCurrentRxAggrEnable
+			u32 	ulValue;
+
+			if(Setting==0)
+			{
+				//
+				// <Roger_Notes> Reduce aggregated page threshold to 0x01 and set minimal threshold 0x0a.
+				// i.e., disable Rx aggregation.
+				//
+				ulValue = 0x0001000a;
+			}
+			else
+			{
+				//PRT_HIGH_THROUGHPUT	pHTInfo = priv->ieee80211->pHTInfo;
+				//HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter);
+
+				if (priv->bForcedUsbRxAggr)
+				{// Using forced settings.
+					ulValue = priv->ForcedUsbRxAggrInfo;
+				}
+				else
+				{// Using default settings.
+
+					ulValue = (pHTInfo->UsbRxFwAggrEn<<24) | (pHTInfo->UsbRxFwAggrPageNum<<16) |
+							(pHTInfo->UsbRxFwAggrPacketNum<<8) | (pHTInfo->UsbRxFwAggrTimeout);
+				}
+			}
+
+			write_nic_byte(dev, RXDMA_AGG_PG_TH, (u8)((ulValue&0xff0000)>>16));
+			write_nic_byte_E(dev, USB_RX_AGG_TIMEOUT, (u8)(ulValue&0xff));
+
+			priv->LastUsbRxAggrInfoSetting = ulValue;
+
+			RT_TRACE(COMP_HT|COMP_RECV, "Set HW_VAR_USB_RX_AGGR: ulValue(%#x)\n", ulValue);
+		}
+		RT_TRACE(COMP_RECV, "HalUsbRxAggr8192SUsb() :  Set RxAggregation to %s\n", Value?"ON":"OFF");
+	}
+
+}
+
+u8 rtl8192SU_MapRxPageSizeToIdx(u16 RxPktSize	)
+{
+	switch(RxPktSize)
+	{
+		case 64:		return 0; break;
+		case 128	:	return 1; break;
+		case 256:		return 2; break;
+		case 512:		return 3; break;
+		case 1024:	return 4; break;
+		default:		return 0;	// We use 64bytes in defult.
+	}
+}
+#endif
+
+#if 0
+static void rtl8192SU_SetHwRegAmpduMinSpace(struct net_device *dev, u8 MinSpaceCfg)
+{
+	struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+	u8	MinSpacingToSet;
+	u8	SecMinSpace;
+
+#ifdef RTL8192S_PREPARE_FOR_NORMAL_RELEASE
+	MinSpacingToSet = MinSpaceCfg;
+	if(MinSpacingToSet <= 7)
+	{
+		switch(ieee->pairwise_key_type)
+		{
+			case	KEY_TYPE_NA:			SecMinSpace = 0;		break;
+			case	KEY_TYPE_CCMP:
+			case	KEY_TYPE_WEP40:
+			case	KEY_TYPE_WEP104:
+			case	KEY_TYPE_TKIP:		SecMinSpace = 6;		break;
+			default:					SecMinSpace = 7;		break;
+		}
+
+		if(MinSpacingToSet < SecMinSpace)
+			MinSpacingToSet = SecMinSpace;
+		priv->MinSpaceCfg = ((priv->MinSpaceCfg&0xf8) |MinSpacingToSet);
+		RT_TRACE(COMP_SEC, "Set AMPDU_MIN_SPACE: %x\n", priv->MinSpaceCfg);
+		write_nic_byte(dev, AMPDU_MIN_SPACE, priv->MinSpaceCfg);
+	}
+
+#else
+	MinSpacingToSet = MinSpaceCfg;
+	MinSpacingToSet &= 0x07; // We only care about bit[2:0]
+	priv->MinSpaceCfg |= MinSpacingToSet;
+	RT_TRACE(COMP_SEC, "Set AMPDU_MIN_SPACE: %x\n", priv->MinSpaceCfg);
+	write_nic_byte(dev, AMPDU_MIN_SPACE, priv->MinSpaceCfg);//FIXLZM
+#endif
+}
+#endif
+
+//
+//	Description:
+//		Initial HW relted registers.
+//
+//	Assumption:
+//		1. This function is only invoked at driver intialization once.
+//		2. PASSIVE LEVEL.
+//
+//	2008.06.10, Added by Roger.
+//
+static void rtl8192SU_MacConfigAfterFwDownload(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
+	//PRT_HIGH_THROUGHPUT	pHTInfo = priv->ieee80211->pHTInfo;
+	//u8	tmpU1b, RxPageCfg, i;
+	u16	tmpU2b;
+	u8	tmpU1b;//, i;
+
+
+	RT_TRACE(COMP_INIT, "--->MacConfigAfterFwDownload()\n");
+
+	// Enable Tx/Rx
+	tmpU2b = (BBRSTn|BB_GLB_RSTn|SCHEDULE_EN|MACRXEN|MACTXEN|DDMA_EN|
+			 FW2HW_EN|RXDMA_EN|TXDMA_EN|HCI_RXDMA_EN|HCI_TXDMA_EN);		//3
+	//Adapter->HalFunc.SetHwRegHandler( Adapter, HW_VAR_COMMAND, &tmpU1b );
+	write_nic_word(dev, CMDR, tmpU2b); //LZM REGISTER COM 090305
+
+	// Loopback mode or not
+	priv->LoopbackMode = RTL8192SU_NO_LOOPBACK; // Set no loopback as default.
+	if(priv->LoopbackMode == RTL8192SU_NO_LOOPBACK)
+		tmpU1b = LBK_NORMAL;
+	else if (priv->LoopbackMode == RTL8192SU_MAC_LOOPBACK )
+		tmpU1b = LBK_MAC_DLB;
+	else
+		RT_TRACE(COMP_INIT, "Serious error: wrong loopback mode setting\n");
+
+	//Adapter->HalFunc.SetHwRegHandler( Adapter, HW_VAR_LBK_MODE, &tmpU1b);
+	write_nic_byte(dev, LBKMD_SEL, tmpU1b);
+
+	// Set RCR
+	write_nic_dword(dev, RCR, priv->ReceiveConfig);
+	RT_TRACE(COMP_INIT, "MacConfigAfterFwDownload(): Current RCR settings(%#x)\n", priv->ReceiveConfig);
+
+
+	// Set RQPN
+	//
+	// <Roger_Notes> 2008.08.18.
+	// 6 endpoints:
+	// (1) Page number on CMDQ is 0x03.
+	// (2) Page number on BCNQ, HQ and MGTQ is 0.
+	// (3) Page number on BKQ, BEQ, VIQ and VOQ are 0x07.
+	// (4) Page number on PUBQ is 0xdd
+	//
+	// 11 endpoints:
+	// (1) Page number on CMDQ is 0x00.
+	// (2) Page number on BCNQ is 0x02, HQ and MGTQ are 0x03.
+	// (3) Page number on BKQ, BEQ, VIQ and VOQ are 0x07.
+	// (4) Page number on PUBQ is 0xd8
+	//
+	//write_nic_dword(Adapter, 0xa0, 0x07070707); //BKQ, BEQ, VIQ and VOQ
+	//write_nic_byte(dev, 0xa4, 0x00); // HCCAQ
+#if 0	 //LZM 090219
+#ifdef USE_SIX_USB_ENDPOINT
+	//write_nic_dword(Adapter, 0xa5, 0x00000003); //CMDQ, MGTQ, HQ and BCNQ
+	//write_nic_byte(dev, 0xa9, 0xdd); // PUBQ
+	tmpU1b = read_nic_byte(dev, 0xab); // RQPN
+	write_nic_byte(dev, 0xab, tmpU1b|BIT7|BIT6);// reduce to 6 endpoints.
+#else
+	write_nic_dword(dev, 0xa5, 0x02030300); //CMDQ, MGTQ, HQ and BCNQ
+	write_nic_byte(dev, 0xa9, 0xd8); // PUBQ
+	tmpU1b = read_nic_byte(dev, 0xab); // RQPN
+	write_nic_byte(dev, 0xab, (tmpU1b&(~BIT6))|BIT7); // Disable reduced endpoint.
+#endif
+#endif
+
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	// Size of Tx/Rx packet buffer.
+	tmpU1b = read_nic_byte(dev, PBP);
+	RxPageCfg = rtl8192SU_MapRxPageSizeToIdx(priv->ieee80211->pHTInfo.UsbRxPageSize);
+	write_nic_byte(dev, PBP, tmpU1b|RxPageCfg); // Set page size of Rx packet buffer to 128 bytes.
+	tmpU1b = read_nic_byte(dev, RXDMA);
+
+	write_nic_byte(dev, RXDMA, tmpU1b|RXDMA_AGG_EN); // Rx aggregation enable.
+	//PlatformIOWrite1Byte(Adapter, RXDMA_AGG_PG_TH, 0x14);	// Set page size of RxDMA aggregation threshold, default: 20.
+	//write_nic_byte(dev, RXDMA_AGG_PG_TH, 0x40); // By Scott's suggestion, 2008.09.30.//92su del
+	//write_nic_byte(dev, USB_RX_AGG_TIMEOUT, RXDMA_AGG_TIMEOUT_17_4_MS); // Set aggregation time-out to 17ms/4.
+	rtl8192SU_HalUsbRxAggr8192SUsb(dev, true);
+#endif
+
+	// Fix the RX FIFO issue(USB error), Rivesed by Roger, 2008-06-14
+	tmpU1b = read_nic_byte_E(dev, 0x5C);
+	write_nic_byte_E(dev, 0x5C, tmpU1b|BIT7);
+
+	//
+	// Revise USB PHY to solve the issue of Rx payload error, Rivesed by Roger,  2008-04-10
+	// Suggest by SD1 Alex.
+	//
+	// <Roger_Notes> The following operation are ONLY for USB PHY test chip.
+	// 2008.10.07.
+	//
+#if RTL8192SU_USB_PHY_TEST
+	write_nic_byte(dev, 0x41,0xf4);
+	write_nic_byte(dev, 0x40,0x00);
+	write_nic_byte(dev, 0x42,0x00);
+	write_nic_byte(dev, 0x42,0x01);
+	write_nic_byte(dev, 0x40,0x0f);
+	write_nic_byte(dev, 0x42,0x00);
+	write_nic_byte(dev, 0x42,0x01);
+#endif
+
+#if 0 //LZM 090219
+	//
+	// Suggested by SD1 Alex, 2008-06-14.
+	//
+	write_nic_byte(dev, TXOP_STALL_CTRL, 0x80);//NAV
+
+
+	//
+	// Set Data Auto Rate Fallback Retry Count register.
+	//
+	write_nic_dword(dev, DARFRC, 0x04010000);
+	write_nic_dword(dev, DARFRC+4, 0x09070605);
+	write_nic_dword(dev, RARFRC, 0x04010000);
+	write_nic_dword(dev, RARFRC+4, 0x09070605);
+
+	// Set Data Auto Rate Fallback Reg. Added by Roger, 2008.09.22.
+	for (i = 0; i < 8; i++)
+#ifdef RTL8192SU_DISABLE_CCK_RATE
+		write_nic_dword(dev, ARFR0+i*4, 0x1f0ff0f0);
+#else
+		write_nic_dword(dev, ARFR0+i*4, 0x1f0ffff0);
+#endif
+
+	//
+	// Set driver info, we only accept PHY status now.
+	//
+	//write_nic_byte(dev, RXDRVINFO_SZ, 4);
+
+	//
+	// Aggregation length limit. Revised by Roger. 2008.09.22.
+	//
+	write_nic_dword(dev, AGGLEN_LMT_L, 0x66666666); // Long GI
+	write_nic_byte(dev, AGGLEN_LMT_H, 0x06);	// Set AMPDU length to 12Kbytes for ShortGI case.
+
+	//
+	// For Min Spacing configuration.
+	//
+	//Adapter->HalFunc.SetHwRegHandler(Adapter, HW_VAR_AMPDU_MIN_SPACE, (u8*)(&Adapter->MgntInfo.MinSpaceCfg));
+	rtl8192SU_SetHwRegAmpduMinSpace(dev,priv->MinSpaceCfg);
+#endif
+
+	// For EFUSE init configuration.
+	//if (IS_BOOT_FROM_EFUSE(Adapter))	// We may R/W EFUSE in EFUSE mode
+	if (priv->bBootFromEfuse)
+	{
+		u8	tempval;
+
+		tempval = read_nic_byte(dev, SYS_ISO_CTRL+1);
+		tempval &= 0xFE;
+		write_nic_byte(dev, SYS_ISO_CTRL+1, tempval);
+
+		// Enable LDO 2.5V for write action
+		//tempval = read_nic_byte(Adapter, EFUSE_TEST+3);
+		//write_nic_byte(Adapter, EFUSE_TEST+3, (tempval | 0x80));
+
+		// Change Efuse Clock for write action
+		//write_nic_byte(Adapter, EFUSE_CLK, 0x03);
+
+		// Change Program timing
+		write_nic_byte(dev, EFUSE_CTRL+3, 0x72);
+		//printk("!!!!!!!!!!!!!!!!!!!!!%s: write 0x33 with 0x72\n",__FUNCTION__);
+		RT_TRACE(COMP_INIT, "EFUSE CONFIG OK\n");
+	}
+
+
+	RT_TRACE(COMP_INIT, "<---MacConfigAfterFwDownload()\n");
+}
+
+void rtl8192SU_HwConfigureRTL8192SUsb(struct net_device *dev)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8			regBwOpMode = 0;
+	u32			regRATR = 0, regRRSR = 0;
+	u8			regTmp = 0;
+	u32 			i = 0;
+
+	//1 This part need to modified according to the rate set we filtered!!
+	//
+	// Set RRSR, RATR, and BW_OPMODE registers
+	//
+	switch(priv->ieee80211->mode)
+	{
+	case WIRELESS_MODE_B:
+		regBwOpMode = BW_OPMODE_20MHZ;
+		regRATR = RATE_ALL_CCK;
+		regRRSR = RATE_ALL_CCK;
+		break;
+	case WIRELESS_MODE_A:
+		regBwOpMode = BW_OPMODE_5G |BW_OPMODE_20MHZ;
+		regRATR = RATE_ALL_OFDM_AG;
+		regRRSR = RATE_ALL_OFDM_AG;
+		break;
+	case WIRELESS_MODE_G:
+		regBwOpMode = BW_OPMODE_20MHZ;
+		regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		break;
+	case WIRELESS_MODE_AUTO:
+		if (priv->bInHctTest)
+		{
+		    regBwOpMode = BW_OPMODE_20MHZ;
+		    regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		    regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		}
+		else
+		{
+		    regBwOpMode = BW_OPMODE_20MHZ;
+		    regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
+		    regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		}
+		break;
+	case WIRELESS_MODE_N_24G:
+		// It support CCK rate by default.
+		// CCK rate will be filtered out only when associated AP does not support it.
+		regBwOpMode = BW_OPMODE_20MHZ;
+			regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
+			regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
+		break;
+	case WIRELESS_MODE_N_5G:
+		regBwOpMode = BW_OPMODE_5G;
+		regRATR = RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
+		regRRSR = RATE_ALL_OFDM_AG;
+		break;
+	}
+
+	//
+	// <Roger_Notes> We disable CCK response rate until FIB CCK rate IC's back.
+	// 2008.09.23.
+	//
+	regTmp = read_nic_byte(dev, INIRTSMCS_SEL);
+#ifdef RTL8192SU_DISABLE_CCK_RATE
+	regRRSR = ((regRRSR & 0x000ffff0)<<8) | regTmp;
+#else
+	regRRSR = ((regRRSR & 0x000fffff)<<8) | regTmp;
+#endif
+
+	//
+	// Update SIFS timing.
+	//
+	//priv->SifsTime = 0x0e0e0a0a;
+	//Adapter->HalFunc.SetHwRegHandler( Adapter, HW_VAR_SIFS,  (pu1Byte)&pHalData->SifsTime);
+	{	u8 val[4] = {0x0e, 0x0e, 0x0a, 0x0a};
+		// SIFS for CCK Data ACK
+		write_nic_byte(dev, SIFS_CCK, val[0]);
+		// SIFS for CCK consecutive tx like CTS data!
+		write_nic_byte(dev, SIFS_CCK+1, val[1]);
+
+		// SIFS for OFDM Data ACK
+		write_nic_byte(dev, SIFS_OFDM, val[2]);
+		// SIFS for OFDM consecutive tx like CTS data!
+		write_nic_byte(dev, SIFS_OFDM+1, val[3]);
+	}
+
+	write_nic_dword(dev, INIRTSMCS_SEL, regRRSR);
+	write_nic_byte(dev, BW_OPMODE, regBwOpMode);
+
+	//
+	// Suggested by SD1 Alex, 2008-06-14.
+	//
+	//PlatformEFIOWrite1Byte(Adapter, TXOP_STALL_CTRL, 0x80);//NAV to protect all TXOP.
+
+	//
+	// Set Data Auto Rate Fallback Retry Count register.
+	//
+	write_nic_dword(dev, DARFRC, 0x02010000);
+	write_nic_dword(dev, DARFRC+4, 0x06050403);
+	write_nic_dword(dev, RARFRC, 0x02010000);
+	write_nic_dword(dev, RARFRC+4, 0x06050403);
+
+	// Set Data Auto Rate Fallback Reg. Added by Roger, 2008.09.22.
+	for (i = 0; i < 8; i++)
+#ifdef RTL8192SU_DISABLE_CCK_RATE
+		write_nic_dword(dev, ARFR0+i*4, 0x1f0ff0f0);
+#else
+		write_nic_dword(dev, ARFR0+i*4, 0x1f0ffff0);
+#endif
+
+	//
+	// Aggregation length limit. Revised by Roger. 2008.09.22.
+	//
+	write_nic_byte(dev, AGGLEN_LMT_H, 0x0f);	// Set AMPDU length to 12Kbytes for ShortGI case.
+	write_nic_dword(dev, AGGLEN_LMT_L, 0xddd77442); // Long GI
+	write_nic_dword(dev, AGGLEN_LMT_L+4, 0xfffdd772);
+
+	// Set NAV protection length
+	write_nic_word(dev, NAV_PROT_LEN, 0x0080);
+
+	// Set TXOP stall control for several queue/HI/BCN/MGT/
+	write_nic_byte(dev, TXOP_STALL_CTRL, 0x00); // NAV Protect next packet.
+
+	// Set MSDU lifetime.
+	write_nic_byte(dev, MLT, 0x8f);
+
+	// Set CCK/OFDM SIFS
+	write_nic_word(dev, SIFS_CCK, 0x0a0a); // CCK SIFS shall always be 10us.
+	write_nic_word(dev, SIFS_OFDM, 0x0e0e);
+
+	write_nic_byte(dev, ACK_TIMEOUT, 0x40);
+
+	// CF-END Threshold
+	write_nic_byte(dev, CFEND_TH, 0xFF);
+
+	//
+	// For Min Spacing configuration.
+	//
+	switch(priv->rf_type)
+	{
+		case RF_1T2R:
+		case RF_1T1R:
+			RT_TRACE(COMP_INIT, "Initializeadapter: RF_Type%s\n", (priv->rf_type==RF_1T1R? "(1T1R)":"(1T2R)"));
+			priv->MinSpaceCfg = (MAX_MSS_DENSITY_1T<<3);
+			break;
+		case RF_2T2R:
+		case RF_2T2R_GREEN:
+			RT_TRACE(COMP_INIT, "Initializeadapter:RF_Type(2T2R)\n");
+			priv->MinSpaceCfg = (MAX_MSS_DENSITY_2T<<3);
+			break;
+	}
+	write_nic_byte(dev, AMPDU_MIN_SPACE, priv->MinSpaceCfg);
+
+	//LZM 090219
+	//
+	// For Min Spacing configuration.
+	//
+	//priv->MinSpaceCfg = 0x00;
+	//rtl8192SU_SetHwRegAmpduMinSpace(dev, priv->MinSpaceCfg);
+}
+
+#endif
+
+#ifdef RTL8192SU
+//	Description:	Initial HW relted registers.
+//
+//	Assumption:	This function is only invoked at driver intialization once.
+//
+//	2008.06.10, Added by Roger.
+bool rtl8192SU_adapter_start(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//u32 					dwRegRead = 0;
+	//bool 					init_status = true;
+	//u32					ulRegRead;
+	bool             				rtStatus = true;
+	//u8					PipeIndex;
+	//u8					eRFPath, tmpU1b;
+	u8 fw_download_times = 1;
+
+
+	RT_TRACE(COMP_INIT, "--->InitializeAdapter8192SUsb()\n");
+
+	//pHalData->bGPIOChangeRF = FALSE;
+
+
+	//
+	// <Roger_Notes> 2008.06.15.
+	//
+	// Initialization Steps on RTL8192SU:
+	// a. MAC initialization prior to sending down firmware code.
+	// b. Download firmware code step by step(i.e., IMEM, EMEM, DMEM).
+	// c. MAC configuration after firmware has been download successfully.
+	// d. Initialize BB related configurations.
+	// e. Initialize RF related configurations.
+	// f.  Start to BulkIn transfer.
+	//
+
+	//
+	//a. MAC initialization prior to send down firmware code.
+	//
+start:
+	rtl8192SU_MacConfigBeforeFwDownloadASIC(dev);
+
+	//
+	//b. Download firmware code step by step(i.e., IMEM, EMEM, DMEM).
+	//
+	rtStatus = FirmwareDownload92S(dev);
+	if(rtStatus != true)
+	{
+		if(fw_download_times == 1){
+			RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Download Firmware failed once, Download again!!\n");
+			fw_download_times = fw_download_times + 1;
+			goto start;
+		}else{
+			RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Download Firmware failed twice, end!!\n");
+		goto end;
+	}
+	}
+	//
+	//c. MAC configuration after firmware has been download successfully.
+	//
+	rtl8192SU_MacConfigAfterFwDownload(dev);
+
+#if (RTL8192S_DISABLE_FW_DM == 1)
+	write_nic_dword(dev, WFM5, FW_DM_DISABLE);
+#endif
+	//priv->bLbusEnable = TRUE;
+	//if(priv->RegRfOff == TRUE)
+	//	priv->eRFPowerState = eRfOff;
+
+	// Save target channel
+	// <Roger_Notes> Current Channel will be updated again later.
+	//priv->CurrentChannel = Channel;
+	rtStatus = PHY_MACConfig8192S(dev);//===>ok
+	if(rtStatus != true)
+	{
+		RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Fail to configure MAC!!\n");
+		goto end;
+	}
+	if (1){
+		int i;
+		for (i=0; i<4; i++)
+			write_nic_dword(dev,WDCAPARA_ADD[i], 0x5e4322);
+		write_nic_byte(dev,AcmHwCtrl, 0x01);
+	}
+
+
+	//
+	//d. Initialize BB related configurations.
+	//
+
+	rtStatus = PHY_BBConfig8192S(dev);//===>ok
+	if(rtStatus != true)
+	{
+		RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Fail to configure BB!!\n");
+		goto end;
+	}
+
+	rtl8192_setBBreg(dev, rFPGA0_AnalogParameter2, 0xff, 0x58);//===>ok
+
+	//
+	// e. Initialize RF related configurations.
+	//
+	// 2007/11/02 MH Before initalizing RF. We can not use FW to do RF-R/W.
+	priv->Rf_Mode = RF_OP_By_SW_3wire;
+
+	// For RF test only from Scott's suggestion
+	//write_nic_byte(dev, 0x27, 0xDB);
+	//write_nic_byte(dev, 0x1B, 0x07);
+
+
+	write_nic_byte(dev, AFE_XTAL_CTRL+1, 0xDB);
+
+	// <Roger_Notes> The following IOs are configured for each RF modules.
+	// Enable RF module and reset RF and SDM module. 2008.11.17.
+	if(priv->card_8192_version == VERSION_8192S_ACUT)
+		write_nic_byte(dev, SPS1_CTRL+3, (u8)(RF_EN|RF_RSTB|RF_SDMRSTB)); // Fix A-Cut bug.
+	else
+		write_nic_byte(dev, RF_CTRL, (u8)(RF_EN|RF_RSTB|RF_SDMRSTB));
+
+	rtStatus = PHY_RFConfig8192S(dev);//===>ok
+	if(rtStatus != true)
+	{
+		RT_TRACE(COMP_INIT, "InitializeAdapter8192SUsb(): Fail to configure RF!!\n");
+		goto end;
+	}
+
+
+	// Set CCK and OFDM Block "ON"
+	rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn, 0x1);
+	rtl8192_setBBreg(dev, rFPGA0_RFMOD, bOFDMEn, 0x1);
+
+	//
+	// Turn off Radio B while RF type is 1T1R by SD3 Wilsion's request.
+	// Revised by Roger, 2008.12.18.
+	//
+	if(priv->rf_type == RF_1T1R)
+	{
+		// This is needed for PHY_REG after 20081219
+		rtl8192_setBBreg(dev, rFPGA0_RFMOD, 0xff000000, 0x03);
+		// This is needed for PHY_REG before 20081219
+		//PHY_SetBBReg(Adapter, rOFDM0_TRxPathEnable, bMaskByte0, 0x11);
+	}
+
+#if (RTL8192SU_DISABLE_IQK==0)
+		// For 1T2R IQK only currently.
+		if (priv->card_8192_version == VERSION_8192S_BCUT)
+		{
+			PHY_IQCalibrateBcut(dev);
+		}
+		else if (priv->card_8192_version == VERSION_8192S_ACUT)
+		{
+			PHY_IQCalibrate(dev);
+		}
+#endif
+
+	//LZM 090219
+	// Set CCK and OFDM Block "ON"
+	//rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn, 0x1);
+	//rtl8192_setBBreg(dev, rFPGA0_RFMOD, bOFDMEn, 0x1);
+
+
+	//3//Get hardware version, do it in read eeprom?
+	//GetHardwareVersion819xUsb(Adapter);
+
+	//3//
+	//3 //Set Hardware
+	//3//
+	rtl8192SU_HwConfigureRTL8192SUsb(dev);//==>ok
+
+	//
+	// <Roger_Notes> We set MAC address here if autoload was failed before,
+	// otherwise IDR0 will NOT contain any value.
+	//
+	write_nic_dword(dev, IDR0, ((u32*)dev->dev_addr)[0]);
+	write_nic_word(dev, IDR4, ((u16*)(dev->dev_addr + 4))[0]);
+	if(!priv->bInHctTest)
+	{
+		if(priv->ResetProgress == RESET_TYPE_NORESET)
+		{
+			//RT_TRACE(COMP_MLME, DBG_LOUD, ("Initializeadapter8192SUsb():RegWirelessMode(%#x) \n", Adapter->RegWirelessMode));
+			//Adapter->HalFunc.SetWirelessModeHandler(Adapter, Adapter->RegWirelessMode);
+			rtl8192_SetWirelessMode(dev, priv->ieee80211->mode);//===>ok
+	        }
+	}
+	else
+	{
+		priv->ieee80211->mode = WIRELESS_MODE_G;
+	 	rtl8192_SetWirelessMode(dev, WIRELESS_MODE_G);
+	}
+
+	//Security related.
+	//-----------------------------------------------------------------------------
+	// Set up security related. 070106, by rcnjko:
+	// 1. Clear all H/W keys.
+	// 2. Enable H/W encryption/decryption.
+	//-----------------------------------------------------------------------------
+	//CamResetAllEntry(Adapter);
+	//Adapter->HalFunc.EnableHWSecCfgHandler(Adapter);
+
+	//SecClearAllKeys(Adapter);
+	CamResetAllEntry(dev);
+	//SecInit(Adapter);
+	{
+		u8 SECR_value = 0x0;
+		SECR_value |= SCR_TxEncEnable;
+		SECR_value |= SCR_RxDecEnable;
+		SECR_value |= SCR_NoSKMC;
+		write_nic_byte(dev, SECR, SECR_value);
+	}
+
+#if 0
+
+	if(pHalData->VersionID == VERSION_8192SU_A)
+	{
+		// cosa add for tx power level initialization.
+		GetTxPowerOriginalOffset(Adapter);
+		SetTxPowerLevel819xUsb(Adapter, Channel);
+	}
+#endif
+
+
+#ifdef TO_DO_LIST
+
+	//PHY_UpdateInitialGain(dev);
+
+	if(priv->RegRfOff == true)
+	{ // User disable RF via registry.
+		u8 eRFPath = 0;
+
+		RT_TRACE((COMP_INIT|COMP_RF), "InitializeAdapter8192SUsb(): Turn off RF for RegRfOff ----------\n");
+		MgntActSet_RF_State(dev, eRfOff, RF_CHANGE_BY_SW);
+		// Those action will be discard in MgntActSet_RF_State because off the same state
+		for(eRFPath = 0; eRFPath <priv->NumTotalRFPath; eRFPath++)
+			rtl8192_setBBreg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x4, 0xC00, 0x0);
+	}
+	else if(priv->RfOffReason > RF_CHANGE_BY_PS)
+	{ // H/W or S/W RF OFF before sleep.
+		RT_TRACE((COMP_INIT|COMP_RF), "InitializeAdapter8192SUsb(): Turn off RF for RfOffReason(%d) ----------\n", priv->RfOffReason);
+		MgntActSet_RF_State(dev, eRfOff, priv->RfOffReason);
+	}
+	else
+	{
+		priv->eRFPowerState = eRfOn;
+		priv->RfOffReason = 0;
+		RT_TRACE((COMP_INIT|COMP_RF), "InitializeAdapter8192SUsb(): RF is on ----------\n");
+	}
+
+#endif
+
+
+//
+// f. Start to BulkIn transfer.
+//
+#ifdef TO_DO_LIST
+
+#ifndef UNDER_VISTA
+	{
+		u8	i;
+		PlatformAcquireSpinLock(Adapter, RT_RX_SPINLOCK);
+
+		for(PipeIndex=0; PipeIndex < MAX_RX_QUEUE; PipeIndex++)
+		{
+			if (PipeIndex == 0)
+			{
+				for(i=0; i<32; i++)
+				HalUsbInMpdu(Adapter, PipeIndex);
+			}
+			else
+			{
+				//HalUsbInMpdu(Adapter, PipeIndex);
+				//HalUsbInMpdu(Adapter, PipeIndex);
+				//HalUsbInMpdu(Adapter, PipeIndex);
+			}
+		}
+		PlatformReleaseSpinLock(Adapter, RT_RX_SPINLOCK);
+	}
+#else
+		// Joseph add to 819X code base for Vista USB platform.
+		// This part may need to be add to Hal819xU code base. too.
+	        PlatformUsbEnableInPipes(Adapter);
+#endif
+
+	RT_TRACE(COMP_INIT, "HighestOperaRate = %x\n", Adapter->MgntInfo.HighestOperaRate);
+
+	PlatformStartWorkItem( &(pHalData->RtUsbCheckForHangWorkItem) );
+
+	//
+	// <Roger_EXP> The following  configurations are for ASIC verification temporally.
+	// 2008.07.10.
+	//
+
+#endif
+
+	//
+	// Read EEPROM TX power index and PHY_REG_PG.txt to capture correct
+	// TX power index for different rate set.
+	//
+	//if(priv->card_8192_version >= VERSION_8192S_ACUT)
+	{
+		// Get original hw reg values
+		PHY_GetHWRegOriginalValue(dev);
+
+		// Write correct tx power index//FIXLZM
+		PHY_SetTxPowerLevel8192S(dev, priv->chan);
+	}
+
+	{
+	u8  tmpU1b = 0;
+	// EEPROM R/W workaround
+	tmpU1b = read_nic_byte(dev, MAC_PINMUX_CFG);
+	write_nic_byte(dev, MAC_PINMUX_CFG, tmpU1b&(~GPIOMUX_EN));
+	}
+
+//
+//<Roger_Notes> 2008.08.19.
+// We return status here for temporal FPGA verification, 2008.08.19.
+
+#ifdef RTL8192SU_FW_IQK
+	write_nic_dword(dev, WFM5, FW_IQK_ENABLE);
+	ChkFwCmdIoDone(dev);
+#endif
+
+	//
+	// <Roger_Notes> We enable high power mechanism after NIC initialized.
+	// 2008.11.27.
+	//
+	write_nic_dword(dev, WFM5, FW_RA_RESET);
+	ChkFwCmdIoDone(dev);
+	write_nic_dword(dev, WFM5, FW_RA_ACTIVE);
+	ChkFwCmdIoDone(dev);
+	write_nic_dword(dev, WFM5, FW_RA_REFRESH);
+	ChkFwCmdIoDone(dev);
+	write_nic_dword(dev, WFM5, FW_BB_RESET_ENABLE);
+
+// <Roger_Notes> We return status here for temporal FPGA verification. 2008.05.12.
+//
+#if RTL8192SU_FPGA_UNSPECIFIED_NETWORK
+	//
+	// To send specific number of packets to verify MAC Lookback mode.
+	//
+	//SendRandomTxPkt(Adapter, 0); // Burst mode for verification.
+	//rtStatus = RT_STATUS_FAILURE;
+	rtStatus = true;
+        goto end;
+#endif
+
+// The following IO was for FPGA verification purpose. Added by Roger, 2008.09.11.
+#if 0
+	// 2008/08/19 MH From SD1 Jong, we must write some register for true PHY/MAC FPGA.
+	write_nic_byte(dev, rOFDM0_XAAGCCore1, 0x30);
+	write_nic_byte(dev, rOFDM0_XBAGCCore1, 0x30);
+
+	write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
+
+	//write_nic_dword(Adapter, RCR, 0x817FF02F);
+
+	write_nic_dword(Adapter, rTxAGC_Mcs15_Mcs12, 0x06060606);
+#endif
+end:
+return rtStatus;
+}
+
+#else
+
+//InitializeAdapter and PhyCfg
+bool rtl8192_adapter_start(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 dwRegRead = 0;
+	bool init_status = true;
+	RT_TRACE(COMP_INIT, "====>%s()\n", __FUNCTION__);
+	priv->Rf_Mode = RF_OP_By_SW_3wire;
+	//for ASIC power on sequence
+	write_nic_byte_E(dev, 0x5f, 0x80);
+	mdelay(50);
+	write_nic_byte_E(dev, 0x5f, 0xf0);
+	write_nic_byte_E(dev, 0x5d, 0x00);
+	write_nic_byte_E(dev, 0x5e, 0x80);
+	write_nic_byte(dev, 0x17, 0x37);
+	mdelay(10);
+//#ifdef TO_DO_LIST
+	priv->pFirmware->firmware_status = FW_STATUS_0_INIT;
+	//config CPUReset Register
+	//Firmware Reset or not?
+	dwRegRead = read_nic_dword(dev, CPU_GEN);
+	if (priv->pFirmware->firmware_status == FW_STATUS_0_INIT)
+		dwRegRead |= CPU_GEN_SYSTEM_RESET; //do nothing here?
+	else if (priv->pFirmware->firmware_status == FW_STATUS_5_READY)
+		dwRegRead |= CPU_GEN_FIRMWARE_RESET;
+	else
+		RT_TRACE(COMP_ERR, "ERROR in %s(): undefined firmware state(%d)\n", __FUNCTION__,   priv->pFirmware->firmware_status);
+
+	write_nic_dword(dev, CPU_GEN, dwRegRead);
+	//mdelay(30);
+	//config BB.
+	rtl8192_BBConfig(dev);
+
+#if 1
+	//Loopback mode or not
+	priv->LoopbackMode = RTL819xU_NO_LOOPBACK;
+//	priv->LoopbackMode = RTL819xU_MAC_LOOPBACK;
+
+	dwRegRead = read_nic_dword(dev, CPU_GEN);
+	if (priv->LoopbackMode == RTL819xU_NO_LOOPBACK)
+		dwRegRead = ((dwRegRead & CPU_GEN_NO_LOOPBACK_MSK) | CPU_GEN_NO_LOOPBACK_SET);
+	else if (priv->LoopbackMode == RTL819xU_MAC_LOOPBACK)
+		dwRegRead |= CPU_CCK_LOOPBACK;
+	else
+		RT_TRACE(COMP_ERR, "Serious error in %s(): wrong loopback mode setting(%d)\n", __FUNCTION__,  priv->LoopbackMode);
+
+	write_nic_dword(dev, CPU_GEN, dwRegRead);
+
+	//after reset cpu, we need wait for a seconds to write in register.
+	udelay(500);
+
+	//xiong add for new bitfile:usb suspend reset pin set to 1. //do we need?
+	write_nic_byte_E(dev, 0x5f, (read_nic_byte_E(dev, 0x5f)|0x20));
+
+	//Set Hardware
+	rtl8192_hwconfig(dev);
+
+	//turn on Tx/Rx
+	write_nic_byte(dev, CMDR, CR_RE|CR_TE);
+
+	//set IDR0 here
+	write_nic_dword(dev, MAC0, ((u32*)dev->dev_addr)[0]);
+	write_nic_word(dev, MAC4, ((u16*)(dev->dev_addr + 4))[0]);
+
+	//set RCR
+	write_nic_dword(dev, RCR, priv->ReceiveConfig);
+
+	//Initialize Number of Reserved Pages in Firmware Queue
+	write_nic_dword(dev, RQPN1,  NUM_OF_PAGE_IN_FW_QUEUE_BK << RSVD_FW_QUEUE_PAGE_BK_SHIFT |\
+						NUM_OF_PAGE_IN_FW_QUEUE_BE << RSVD_FW_QUEUE_PAGE_BE_SHIFT | \
+						NUM_OF_PAGE_IN_FW_QUEUE_VI << RSVD_FW_QUEUE_PAGE_VI_SHIFT | \
+						NUM_OF_PAGE_IN_FW_QUEUE_VO <<RSVD_FW_QUEUE_PAGE_VO_SHIFT);
+	write_nic_dword(dev, RQPN2, NUM_OF_PAGE_IN_FW_QUEUE_MGNT << RSVD_FW_QUEUE_PAGE_MGNT_SHIFT |\
+						NUM_OF_PAGE_IN_FW_QUEUE_CMD << RSVD_FW_QUEUE_PAGE_CMD_SHIFT);
+	write_nic_dword(dev, RQPN3, APPLIED_RESERVED_QUEUE_IN_FW| \
+						NUM_OF_PAGE_IN_FW_QUEUE_BCN<<RSVD_FW_QUEUE_PAGE_BCN_SHIFT
+//						| NUM_OF_PAGE_IN_FW_QUEUE_PUB<<RSVD_FW_QUEUE_PAGE_PUB_SHIFT
+						);
+	write_nic_dword(dev, RATR0+4*7, (RATE_ALL_OFDM_AG | RATE_ALL_CCK));
+
+	//Set AckTimeout
+	// TODO: (it value is only for FPGA version). need to be changed!!2006.12.18, by Emily
+	write_nic_byte(dev, ACK_TIMEOUT, 0x30);
+
+//	RT_TRACE(COMP_INIT, "%s():priv->ResetProgress is %d\n", __FUNCTION__,priv->ResetProgress);
+	if(priv->ResetProgress == RESET_TYPE_NORESET)
+	rtl8192_SetWirelessMode(dev, priv->ieee80211->mode);
+	if(priv->ResetProgress == RESET_TYPE_NORESET){
+	CamResetAllEntry(dev);
+	{
+		u8 SECR_value = 0x0;
+		SECR_value |= SCR_TxEncEnable;
+		SECR_value |= SCR_RxDecEnable;
+		SECR_value |= SCR_NoSKMC;
+		write_nic_byte(dev, SECR, SECR_value);
+	}
+	}
+
+	//Beacon related
+	write_nic_word(dev, ATIMWND, 2);
+	write_nic_word(dev, BCN_INTERVAL, 100);
+
+	{
+#define DEFAULT_EDCA 0x005e4332
+		int i;
+		for (i=0; i<QOS_QUEUE_NUM; i++)
+		write_nic_dword(dev, WDCAPARA_ADD[i], DEFAULT_EDCA);
+	}
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	//3 For usb rx firmware aggregation control
+	if(priv->ResetProgress == RESET_TYPE_NORESET)
+	{
+		u32 ulValue;
+		PRT_HIGH_THROUGHPUT	pHTInfo = priv->ieee80211->pHTInfo;
+		ulValue = (pHTInfo->UsbRxFwAggrEn<<24) | (pHTInfo->UsbRxFwAggrPageNum<<16) |
+					(pHTInfo->UsbRxFwAggrPacketNum<<8) | (pHTInfo->UsbRxFwAggrTimeout);
+		/*
+		 * If usb rx firmware aggregation is enabled,
+		 * when anyone of three threshold conditions above is reached,
+		 * firmware will send aggregated packet to driver.
+		 */
+		write_nic_dword(dev, 0x1a8, ulValue);
+		priv->bCurrentRxAggrEnable = true;
+	}
+#endif
+
+	rtl8192_phy_configmac(dev);
+
+	if (priv->card_8192_version == (u8) VERSION_819xU_A)
+	{
+		rtl8192_phy_getTxPower(dev);
+		rtl8192_phy_setTxPower(dev, priv->chan);
+	}
+
+
+	priv->usb_error = false;
+	//Firmware download
+	init_status = init_firmware(dev);
+	if(!init_status)
+	{
+		RT_TRACE(COMP_ERR,"ERR!!! %s(): Firmware download is failed\n", __FUNCTION__);
+		return init_status;
+	}
+	RT_TRACE(COMP_INIT, "%s():after firmware download\n", __FUNCTION__);
+	//
+#ifdef TO_DO_LIST
+if(Adapter->ResetProgress == RESET_TYPE_NORESET)
+	{
+		if(pMgntInfo->RegRfOff == TRUE)
+		{ // User disable RF via registry.
+			RT_TRACE((COMP_INIT|COMP_RF), DBG_LOUD, ("InitializeAdapter819xUsb(): Turn off RF for RegRfOff ----------\n"));
+			MgntActSet_RF_State(Adapter, eRfOff, RF_CHANGE_BY_SW);
+			// Those action will be discard in MgntActSet_RF_State because off the same state
+			for(eRFPath = 0; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
+				PHY_SetRFReg(Adapter, (RF90_RADIO_PATH_E)eRFPath, 0x4, 0xC00, 0x0);
+		}
+		else if(pMgntInfo->RfOffReason > RF_CHANGE_BY_PS)
+		{ // H/W or S/W RF OFF before sleep.
+			RT_TRACE((COMP_INIT|COMP_RF), DBG_LOUD, ("InitializeAdapter819xUsb(): Turn off RF for RfOffReason(%d) ----------\n", pMgntInfo->RfOffReason));
+			MgntActSet_RF_State(Adapter, eRfOff, pMgntInfo->RfOffReason);
+		}
+		else
+		{
+			pHalData->eRFPowerState = eRfOn;
+			pMgntInfo->RfOffReason = 0;
+			RT_TRACE((COMP_INIT|COMP_RF), DBG_LOUD, ("InitializeAdapter819xUsb(): RF is on ----------\n"));
+		}
+	}
+	else
+	{
+		if(pHalData->eRFPowerState == eRfOff)
+		{
+			MgntActSet_RF_State(Adapter, eRfOff, pMgntInfo->RfOffReason);
+			// Those action will be discard in MgntActSet_RF_State because off the same state
+			for(eRFPath = 0; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
+				PHY_SetRFReg(Adapter, (RF90_RADIO_PATH_E)eRFPath, 0x4, 0xC00, 0x0);
+		}
+	}
+#endif
+	//config RF.
+	if(priv->ResetProgress == RESET_TYPE_NORESET){
+	rtl8192_phy_RFConfig(dev);
+	RT_TRACE(COMP_INIT, "%s():after phy RF config\n", __FUNCTION__);
+	}
+
+
+	if(priv->ieee80211->FwRWRF)
+		// We can force firmware to do RF-R/W
+		priv->Rf_Mode = RF_OP_By_FW;
+	else
+		priv->Rf_Mode = RF_OP_By_SW_3wire;
+
+
+	rtl8192_phy_updateInitGain(dev);
+	/*--set CCK and OFDM Block "ON"--*/
+	rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn, 0x1);
+	rtl8192_setBBreg(dev, rFPGA0_RFMOD, bOFDMEn, 0x1);
+
+	if(priv->ResetProgress == RESET_TYPE_NORESET)
+	{
+		//if D or C cut
+		u8 tmpvalue = read_nic_byte(dev, 0x301);
+		if(tmpvalue ==0x03)
+		{
+			priv->bDcut = TRUE;
+			RT_TRACE(COMP_POWER_TRACKING, "D-cut\n");
+		}
+		else
+		{
+			priv->bDcut = FALSE;
+			RT_TRACE(COMP_POWER_TRACKING, "C-cut\n");
+		}
+		dm_initialize_txpower_tracking(dev);
+
+		if(priv->bDcut == TRUE)
+		{
+			u32 i, TempCCk;
+			u32 tmpRegA= rtl8192_QueryBBReg(dev,rOFDM0_XATxIQImbalance,bMaskDWord);
+		//	u32 tmpRegC= rtl8192_QueryBBReg(dev,rOFDM0_XCTxIQImbalance,bMaskDWord);
+			for(i = 0; i<TxBBGainTableLength; i++)
+			{
+				if(tmpRegA == priv->txbbgain_table[i].txbbgain_value)
+				{
+					priv->rfa_txpowertrackingindex= (u8)i;
+					priv->rfa_txpowertrackingindex_real= (u8)i;
+					priv->rfa_txpowertracking_default= priv->rfa_txpowertrackingindex;
+					break;
+				}
+			}
+
+			TempCCk = rtl8192_QueryBBReg(dev, rCCK0_TxFilter1, bMaskByte2);
+
+			for(i=0 ; i<CCKTxBBGainTableLength ; i++)
+			{
+
+				if(TempCCk == priv->cck_txbbgain_table[i].ccktxbb_valuearray[0])
+				{
+					priv->cck_present_attentuation_20Mdefault=(u8) i;
+					break;
+				}
+			}
+			priv->cck_present_attentuation_40Mdefault= 0;
+			priv->cck_present_attentuation_difference= 0;
+			priv->cck_present_attentuation = priv->cck_present_attentuation_20Mdefault;
+
+	//		pMgntInfo->bTXPowerTracking = FALSE;//TEMPLY DISABLE
+		}
+	}
+	write_nic_byte(dev, 0x87, 0x0);
+
+
+#endif
+	return init_status;
+}
+
+#endif
+/* this configures registers for beacon tx and enables it via
+ * rtl8192_beacon_tx_enable(). rtl8192_beacon_tx_disable() might
+ * be used to stop beacon transmission
+ */
+#if 0
+void rtl8192_start_tx_beacon(struct net_device *dev)
+{
+	int i;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	u16 word;
+	DMESG("Enabling beacon TX");
+	//write_nic_byte(dev, TX_CONF,0xe6);// TX_CONF
+	//rtl8192_init_beacon(dev);
+	//set_nic_txring(dev);
+//	rtl8192_prepare_beacon(dev);
+	rtl8192_irq_disable(dev);
+//	rtl8192_beacon_tx_enable(dev);
+	rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
+	//write_nic_byte(dev,0x9d,0x20); //DMA Poll
+	//write_nic_word(dev,0x7a,0);
+	//write_nic_word(dev,0x7a,0x8000);
+
+
+	word  = read_nic_word(dev, BcnItv);
+	word &= ~BcnItv_BcnItv; // clear Bcn_Itv
+	write_nic_word(dev, BcnItv, word);
+
+	write_nic_word(dev, AtimWnd,
+		       read_nic_word(dev, AtimWnd) &~ AtimWnd_AtimWnd);
+
+	word  = read_nic_word(dev, BCN_INTR_ITV);
+	word &= ~BCN_INTR_ITV_MASK;
+
+	//word |= priv->ieee80211->beacon_interval *
+	//	((priv->txbeaconcount > 1)?(priv->txbeaconcount-1):1);
+	// FIXME:FIXME check if correct ^^ worked with 0x3e8;
+
+	write_nic_word(dev, BCN_INTR_ITV, word);
+
+	//write_nic_word(dev,0x2e,0xe002);
+	//write_nic_dword(dev,0x30,0xb8c7832e);
+	for(i=0; i<ETH_ALEN; i++)
+		write_nic_byte(dev, BSSID+i, priv->ieee80211->beacon_cell_ssid[i]);
+
+//	rtl8192_update_msr(dev);
+
+
+	//write_nic_byte(dev,CONFIG4,3); /* !!!!!!!!!! */
+
+	rtl8192_set_mode(dev, EPROM_CMD_NORMAL);
+
+	rtl8192_irq_enable(dev);
+
+	/* VV !!!!!!!!!! VV*/
+	/*
+	rtl8192_set_mode(dev,EPROM_CMD_CONFIG);
+	write_nic_byte(dev,0x9d,0x00);
+	rtl8192_set_mode(dev,EPROM_CMD_NORMAL);
+*/
+}
+#endif
+/***************************************************************************
+    -------------------------------NET STUFF---------------------------
+***************************************************************************/
+
+static struct net_device_stats *rtl8192_stats(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	return &priv->ieee80211->stats;
+}
+
+bool
+HalTxCheckStuck819xUsb(
+	struct net_device *dev
+	)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u16 		RegTxCounter = read_nic_word(dev, 0x128);
+	bool		bStuck = FALSE;
+	RT_TRACE(COMP_RESET,"%s():RegTxCounter is %d,TxCounter is %d\n",__FUNCTION__,RegTxCounter,priv->TxCounter);
+	if(priv->TxCounter==RegTxCounter)
+		bStuck = TRUE;
+
+	priv->TxCounter = RegTxCounter;
+
+	return bStuck;
+}
+
+/*
+*	<Assumption: RT_TX_SPINLOCK is acquired.>
+*	First added: 2006.11.19 by emily
+*/
+RESET_TYPE
+TxCheckStuck(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8			QueueID;
+//	PRT_TCB			pTcb;
+//	u8			ResetThreshold;
+	bool			bCheckFwTxCnt = false;
+	//unsigned long flags;
+
+	//
+	// Decide Stuch threshold according to current power save mode
+	//
+
+//     RT_TRACE(COMP_RESET, " ==> TxCheckStuck()\n");
+//	     PlatformAcquireSpinLock(Adapter, RT_TX_SPINLOCK);
+//	     spin_lock_irqsave(&priv->ieee80211->lock,flags);
+	     for (QueueID = 0; QueueID<=BEACON_QUEUE;QueueID ++)
+	     {
+	     		if(QueueID == TXCMD_QUEUE)
+		         continue;
+#if 1
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+			if((skb_queue_len(&priv->ieee80211->skb_waitQ[QueueID]) == 0) && (skb_queue_len(&priv->ieee80211->skb_aggQ[QueueID]) == 0) && (skb_queue_len(&priv->ieee80211->skb_drv_aggQ[QueueID]) == 0))
+#else
+		     	if((skb_queue_len(&priv->ieee80211->skb_waitQ[QueueID]) == 0)  && (skb_queue_len(&priv->ieee80211->skb_aggQ[QueueID]) == 0))
+#endif
+			 	continue;
+#endif
+
+	             bCheckFwTxCnt = true;
+	     }
+//	     PlatformReleaseSpinLock(Adapter, RT_TX_SPINLOCK);
+//	spin_unlock_irqrestore(&priv->ieee80211->lock,flags);
+//	RT_TRACE(COMP_RESET,"bCheckFwTxCnt is %d\n",bCheckFwTxCnt);
+#if 1
+	if(bCheckFwTxCnt)
+	{
+		if(HalTxCheckStuck819xUsb(dev))
+		{
+			RT_TRACE(COMP_RESET, "TxCheckStuck(): Fw indicates no Tx condition! \n");
+			return RESET_TYPE_SILENT;
+		}
+	}
+#endif
+	return RESET_TYPE_NORESET;
+}
+
+bool
+HalRxCheckStuck819xUsb(struct net_device *dev)
+{
+	u16 	RegRxCounter = read_nic_word(dev, 0x130);
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	bool bStuck = FALSE;
+//#ifdef RTL8192SU
+
+//#else
+	static u8	rx_chk_cnt = 0;
+	RT_TRACE(COMP_RESET,"%s(): RegRxCounter is %d,RxCounter is %d\n",__FUNCTION__,RegRxCounter,priv->RxCounter);
+	// If rssi is small, we should check rx for long time because of bad rx.
+	// or maybe it will continuous silent reset every 2 seconds.
+	rx_chk_cnt++;
+	if(priv->undecorated_smoothed_pwdb >= (RateAdaptiveTH_High+5))
+	{
+		rx_chk_cnt = 0;	//high rssi, check rx stuck right now.
+	}
+	else if(priv->undecorated_smoothed_pwdb < (RateAdaptiveTH_High+5) &&
+		((priv->CurrentChannelBW!=HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb>=RateAdaptiveTH_Low_40M) ||
+		(priv->CurrentChannelBW==HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb>=RateAdaptiveTH_Low_20M)) )
+	{
+		if(rx_chk_cnt < 2)
+		{
+			return bStuck;
+		}
+		else
+		{
+			rx_chk_cnt = 0;
+		}
+	}
+	else if(((priv->CurrentChannelBW!=HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb<RateAdaptiveTH_Low_40M) ||
+		(priv->CurrentChannelBW==HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb<RateAdaptiveTH_Low_20M)) &&
+		priv->undecorated_smoothed_pwdb >= VeryLowRSSI)
+	{
+		if(rx_chk_cnt < 4)
+		{
+			//DbgPrint("RSSI < %d && RSSI >= %d, no check this time \n", RateAdaptiveTH_Low, VeryLowRSSI);
+			return bStuck;
+		}
+		else
+		{
+			rx_chk_cnt = 0;
+			//DbgPrint("RSSI < %d && RSSI >= %d, check this time \n", RateAdaptiveTH_Low, VeryLowRSSI);
+		}
+	}
+	else
+	{
+		if(rx_chk_cnt < 8)
+		{
+			//DbgPrint("RSSI <= %d, no check this time \n", VeryLowRSSI);
+			return bStuck;
+		}
+		else
+		{
+			rx_chk_cnt = 0;
+			//DbgPrint("RSSI <= %d, check this time \n", VeryLowRSSI);
+		}
+	}
+//#endif
+
+	if(priv->RxCounter==RegRxCounter)
+		bStuck = TRUE;
+
+	priv->RxCounter = RegRxCounter;
+
+	return bStuck;
+}
+
+RESET_TYPE
+RxCheckStuck(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//int                     i;
+	bool        bRxCheck = FALSE;
+
+//       RT_TRACE(COMP_RESET," ==> RxCheckStuck()\n");
+	//PlatformAcquireSpinLock(Adapter, RT_RX_SPINLOCK);
+
+	 if(priv->IrpPendingCount > 1)
+	 	bRxCheck = TRUE;
+       //PlatformReleaseSpinLock(Adapter, RT_RX_SPINLOCK);
+
+//       RT_TRACE(COMP_RESET,"bRxCheck is %d \n",bRxCheck);
+	if(bRxCheck)
+	{
+		if(HalRxCheckStuck819xUsb(dev))
+		{
+			RT_TRACE(COMP_RESET, "RxStuck Condition\n");
+			return RESET_TYPE_SILENT;
+		}
+	}
+	return RESET_TYPE_NORESET;
+}
+
+
+/**
+*	This function is called by Checkforhang to check whether we should ask OS to reset driver
+*
+*	\param pAdapter	The adapter context for this miniport
+*
+*	Note:NIC with USB interface sholud not call this function because we cannot scan descriptor
+*	to judge whether there is tx stuck.
+*	Note: This function may be required to be rewrite for Vista OS.
+*	<<<Assumption: Tx spinlock has been acquired >>>
+*
+*	8185 and 8185b does not implement this function. This is added by Emily at 2006.11.24
+*/
+RESET_TYPE
+rtl819x_ifcheck_resetornot(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	RESET_TYPE	TxResetType = RESET_TYPE_NORESET;
+	RESET_TYPE	RxResetType = RESET_TYPE_NORESET;
+	RT_RF_POWER_STATE 	rfState;
+
+#if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
+	return RESET_TYPE_NORESET;
+#endif
+
+	rfState = priv->ieee80211->eRFPowerState;
+
+	TxResetType = TxCheckStuck(dev);
+#if 1
+	if( rfState != eRfOff ||
+		/*ADAPTER_TEST_STATUS_FLAG(Adapter, ADAPTER_STATUS_FW_DOWNLOAD_FAILURE)) &&*/
+		(priv->ieee80211->iw_mode != IW_MODE_ADHOC))
+	{
+		// If driver is in the status of firmware download failure , driver skips RF initialization and RF is
+		// in turned off state. Driver should check whether Rx stuck and do silent reset. And
+		// if driver is in firmware download failure status, driver should initialize RF in the following
+		// silent reset procedure Emily, 2008.01.21
+
+		// Driver should not check RX stuck in IBSS mode because it is required to
+		// set Check BSSID in order to send beacon, however, if check BSSID is
+		// set, STA cannot hear any packet a all. Emily, 2008.04.12
+		RxResetType = RxCheckStuck(dev);
+	}
+#endif
+	if(TxResetType==RESET_TYPE_NORMAL || RxResetType==RESET_TYPE_NORMAL)
+		return RESET_TYPE_NORMAL;
+	else if(TxResetType==RESET_TYPE_SILENT || RxResetType==RESET_TYPE_SILENT){
+		RT_TRACE(COMP_RESET,"%s():silent reset\n",__FUNCTION__);
+		return RESET_TYPE_SILENT;
+	}
+	else
+		return RESET_TYPE_NORESET;
+
+}
+
+void rtl8192_cancel_deferred_work(struct r8192_priv* priv);
+int _rtl8192_up(struct net_device *dev);
+int rtl8192_close(struct net_device *dev);
+
+
+
+void
+CamRestoreAllEntry(	struct net_device *dev)
+{
+	u8 EntryId = 0;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8*	MacAddr = priv->ieee80211->current_network.bssid;
+
+	static u8	CAM_CONST_ADDR[4][6] = {
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x02},
+		{0x00, 0x00, 0x00, 0x00, 0x00, 0x03}};
+	static u8	CAM_CONST_BROAD[] =
+		{0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
+
+	RT_TRACE(COMP_SEC, "CamRestoreAllEntry: \n");
+
+
+	if ((priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP40)||
+	    (priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP104))
+	{
+
+		for(EntryId=0; EntryId<4; EntryId++)
+		{
+			{
+				MacAddr = CAM_CONST_ADDR[EntryId];
+				setKey(dev,
+						EntryId ,
+						EntryId,
+						priv->ieee80211->pairwise_key_type,
+						MacAddr,
+						0,
+						NULL);
+			}
+		}
+
+	}
+	else if(priv->ieee80211->pairwise_key_type == KEY_TYPE_TKIP)
+	{
+
+		{
+			if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
+				setKey(dev,
+						4,
+						0,
+						priv->ieee80211->pairwise_key_type,
+						(u8*)dev->dev_addr,
+						0,
+						NULL);
+			else
+				setKey(dev,
+						4,
+						0,
+						priv->ieee80211->pairwise_key_type,
+						MacAddr,
+						0,
+						NULL);
+		}
+	}
+	else if(priv->ieee80211->pairwise_key_type == KEY_TYPE_CCMP)
+	{
+
+		{
+			if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
+				setKey(dev,
+						4,
+						0,
+						priv->ieee80211->pairwise_key_type,
+						(u8*)dev->dev_addr,
+						0,
+						NULL);
+			else
+				setKey(dev,
+						4,
+						0,
+						priv->ieee80211->pairwise_key_type,
+						MacAddr,
+						0,
+						NULL);
+		}
+	}
+
+
+
+	if(priv->ieee80211->group_key_type == KEY_TYPE_TKIP)
+	{
+		MacAddr = CAM_CONST_BROAD;
+		for(EntryId=1 ; EntryId<4 ; EntryId++)
+		{
+			{
+				setKey(dev,
+						EntryId,
+						EntryId,
+						priv->ieee80211->group_key_type,
+						MacAddr,
+						0,
+						NULL);
+			}
+		}
+		if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
+				setKey(dev,
+						0,
+						0,
+						priv->ieee80211->group_key_type,
+						CAM_CONST_ADDR[0],
+						0,
+						NULL);
+	}
+	else if(priv->ieee80211->group_key_type == KEY_TYPE_CCMP)
+	{
+		MacAddr = CAM_CONST_BROAD;
+		for(EntryId=1; EntryId<4 ; EntryId++)
+		{
+			{
+				setKey(dev,
+						EntryId ,
+						EntryId,
+						priv->ieee80211->group_key_type,
+						MacAddr,
+						0,
+						NULL);
+			}
+		}
+
+		if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
+				setKey(dev,
+						0 ,
+						0,
+						priv->ieee80211->group_key_type,
+						CAM_CONST_ADDR[0],
+						0,
+						NULL);
+	}
+}
+//////////////////////////////////////////////////////////////
+// This function is used to fix Tx/Rx stop bug temporarily.
+// This function will do "system reset" to NIC when Tx or Rx is stuck.
+// The method checking Tx/Rx stuck of this function is supported by FW,
+// which reports Tx and Rx counter to register 0x128 and 0x130.
+//////////////////////////////////////////////////////////////
+void
+rtl819x_ifsilentreset(struct net_device *dev)
+{
+	//OCTET_STRING asocpdu;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8	reset_times = 0;
+	int reset_status = 0;
+	struct ieee80211_device *ieee = priv->ieee80211;
+
+
+	// 2007.07.20. If we need to check CCK stop, please uncomment this line.
+	//bStuck = Adapter->HalFunc.CheckHWStopHandler(Adapter);
+
+	if(priv->ResetProgress==RESET_TYPE_NORESET)
+	{
+RESET_START:
+
+		RT_TRACE(COMP_RESET,"=========>Reset progress!! \n");
+
+		// Set the variable for reset.
+		priv->ResetProgress = RESET_TYPE_SILENT;
+//		rtl8192_close(dev);
+#if 1
+		down(&priv->wx_sem);
+		if(priv->up == 0)
+		{
+			RT_TRACE(COMP_ERR,"%s():the driver is not up! return\n",__FUNCTION__);
+			up(&priv->wx_sem);
+			return ;
+		}
+		priv->up = 0;
+		RT_TRACE(COMP_RESET,"%s():======>start to down the driver\n",__FUNCTION__);
+//		if(!netif_queue_stopped(dev))
+//			netif_stop_queue(dev);
+
+		rtl8192_rtx_disable(dev);
+		rtl8192_cancel_deferred_work(priv);
+		deinit_hal_dm(dev);
+		del_timer_sync(&priv->watch_dog_timer);
+
+		ieee->sync_scan_hurryup = 1;
+		if(ieee->state == IEEE80211_LINKED)
+		{
+			down(&ieee->wx_sem);
+			printk("ieee->state is IEEE80211_LINKED\n");
+			ieee80211_stop_send_beacons(priv->ieee80211);
+			del_timer_sync(&ieee->associate_timer);
+			#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+			cancel_delayed_work(&ieee->associate_retry_wq);
+			#endif
+			ieee80211_stop_scan(ieee);
+			netif_carrier_off(dev);
+			up(&ieee->wx_sem);
+		}
+		else{
+			printk("ieee->state is NOT LINKED\n");
+			ieee80211_softmac_stop_protocol(priv->ieee80211);			}
+		up(&priv->wx_sem);
+		RT_TRACE(COMP_RESET,"%s():<==========down process is finished\n",__FUNCTION__);
+	//rtl8192_irq_disable(dev);
+		RT_TRACE(COMP_RESET,"%s():===========>start to up the driver\n",__FUNCTION__);
+		reset_status = _rtl8192_up(dev);
+
+		RT_TRACE(COMP_RESET,"%s():<===========up process is finished\n",__FUNCTION__);
+		if(reset_status == -EAGAIN)
+		{
+			if(reset_times < 3)
+			{
+				reset_times++;
+				goto RESET_START;
+			}
+			else
+			{
+				RT_TRACE(COMP_ERR," ERR!!! %s():  Reset Failed!!\n", __FUNCTION__);
+			}
+		}
+#endif
+		ieee->is_silent_reset = 1;
+#if 1
+		EnableHWSecurityConfig8192(dev);
+#if 1
+		if(ieee->state == IEEE80211_LINKED && ieee->iw_mode == IW_MODE_INFRA)
+		{
+			ieee->set_chan(ieee->dev, ieee->current_network.channel);
+
+#if 1
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+			queue_work(ieee->wq, &ieee->associate_complete_wq);
+#else
+			schedule_task(&ieee->associate_complete_wq);
+#endif
+#endif
+
+		}
+		else if(ieee->state == IEEE80211_LINKED && ieee->iw_mode == IW_MODE_ADHOC)
+		{
+			ieee->set_chan(ieee->dev, ieee->current_network.channel);
+			ieee->link_change(ieee->dev);
+
+		//	notify_wx_assoc_event(ieee);
+
+			ieee80211_start_send_beacons(ieee);
+
+			if (ieee->data_hard_resume)
+				ieee->data_hard_resume(ieee->dev);
+			netif_carrier_on(ieee->dev);
+		}
+#endif
+
+		CamRestoreAllEntry(dev);
+
+		priv->ResetProgress = RESET_TYPE_NORESET;
+		priv->reset_count++;
+
+		priv->bForcedSilentReset =false;
+		priv->bResetInProgress = false;
+
+		// For test --> force write UFWP.
+		write_nic_byte(dev, UFWP, 1);
+		RT_TRACE(COMP_RESET, "Reset finished!! ====>[%d]\n", priv->reset_count);
+#endif
+	}
+}
+
+void CAM_read_entry(
+	struct net_device *dev,
+	u32	 		iIndex
+)
+{
+ 	u32 target_command=0;
+	 u32 target_content=0;
+	 u8 entry_i=0;
+	 u32 ulStatus;
+	s32 i=100;
+//	printk("=======>start read CAM\n");
+ 	for(entry_i=0;entry_i<CAM_CONTENT_COUNT;entry_i++)
+ 	{
+   	// polling bit, and No Write enable, and address
+		target_command= entry_i+CAM_CONTENT_COUNT*iIndex;
+		target_command= target_command | BIT31;
+
+	//Check polling bit is clear
+//	mdelay(1);
+#if 1
+		while((i--)>=0)
+		{
+			ulStatus = read_nic_dword(dev, RWCAM);
+			if(ulStatus & BIT31){
+				continue;
+			}
+			else{
+				break;
+			}
+		}
+#endif
+  		write_nic_dword(dev, RWCAM, target_command);
+   	 	RT_TRACE(COMP_SEC,"CAM_read_entry(): WRITE A0: %x \n",target_command);
+   	 //	printk("CAM_read_entry(): WRITE A0: %lx \n",target_command);
+  	 	target_content = read_nic_dword(dev, RCAMO);
+  	 	RT_TRACE(COMP_SEC, "CAM_read_entry(): WRITE A8: %x \n",target_content);
+  	 //	printk("CAM_read_entry(): WRITE A8: %lx \n",target_content);
+ 	}
+	printk("\n");
+}
+
+void rtl819x_update_rxcounts(
+	struct r8192_priv *priv,
+	u32* TotalRxBcnNum,
+	u32* TotalRxDataNum
+)
+{
+	u16 			SlotIndex;
+	u8			i;
+
+	*TotalRxBcnNum = 0;
+	*TotalRxDataNum = 0;
+
+	SlotIndex = (priv->ieee80211->LinkDetectInfo.SlotIndex++)%(priv->ieee80211->LinkDetectInfo.SlotNum);
+	priv->ieee80211->LinkDetectInfo.RxBcnNum[SlotIndex] = priv->ieee80211->LinkDetectInfo.NumRecvBcnInPeriod;
+	priv->ieee80211->LinkDetectInfo.RxDataNum[SlotIndex] = priv->ieee80211->LinkDetectInfo.NumRecvDataInPeriod;
+	for( i=0; i<priv->ieee80211->LinkDetectInfo.SlotNum; i++ ){
+		*TotalRxBcnNum += priv->ieee80211->LinkDetectInfo.RxBcnNum[i];
+		*TotalRxDataNum += priv->ieee80211->LinkDetectInfo.RxDataNum[i];
+	}
+}
+
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern	void	rtl819x_watchdog_wqcallback(struct work_struct *work)
+{
+	struct delayed_work *dwork = container_of(work,struct delayed_work,work);
+       struct r8192_priv *priv = container_of(dwork,struct r8192_priv,watch_dog_wq);
+       struct net_device *dev = priv->ieee80211->dev;
+#else
+extern	void	rtl819x_watchdog_wqcallback(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+#endif
+	struct ieee80211_device* ieee = priv->ieee80211;
+	RESET_TYPE	ResetType = RESET_TYPE_NORESET;
+      	static u8	check_reset_cnt=0;
+	bool bBusyTraffic = false;
+
+	if(!priv->up)
+		return;
+	hal_dm_watchdog(dev);
+
+	{//to get busy traffic condition
+		if(ieee->state == IEEE80211_LINKED)
+		{
+			//windows mod 666 to 100.
+			//if(	ieee->LinkDetectInfo.NumRxOkInPeriod> 666 ||
+			//	ieee->LinkDetectInfo.NumTxOkInPeriod> 666 ) {
+			if(	ieee->LinkDetectInfo.NumRxOkInPeriod> 100 ||
+				ieee->LinkDetectInfo.NumTxOkInPeriod> 100 ) {
+				bBusyTraffic = true;
+			}
+			ieee->LinkDetectInfo.NumRxOkInPeriod = 0;
+			ieee->LinkDetectInfo.NumTxOkInPeriod = 0;
+			ieee->LinkDetectInfo.bBusyTraffic = bBusyTraffic;
+		}
+	}
+	//added by amy for AP roaming
+	{
+		if(priv->ieee80211->state == IEEE80211_LINKED && priv->ieee80211->iw_mode == IW_MODE_INFRA)
+		{
+			u32	TotalRxBcnNum = 0;
+			u32	TotalRxDataNum = 0;
+
+			rtl819x_update_rxcounts(priv, &TotalRxBcnNum, &TotalRxDataNum);
+			if((TotalRxBcnNum+TotalRxDataNum) == 0)
+			{
+				#ifdef TODO
+				if(rfState == eRfOff)
+					RT_TRACE(COMP_ERR,"========>%s()\n",__FUNCTION__);
+				#endif
+				printk("===>%s(): AP is power off,connect another one\n",__FUNCTION__);
+			//	Dot11d_Reset(dev);
+				priv->ieee80211->state = IEEE80211_ASSOCIATING;
+				notify_wx_assoc_event(priv->ieee80211);
+				RemovePeerTS(priv->ieee80211,priv->ieee80211->current_network.bssid);
+				ieee->is_roaming = true;
+				priv->ieee80211->link_change(dev);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+                                queue_work(priv->ieee80211->wq, &priv->ieee80211->associate_procedure_wq);
+#else
+                                schedule_task(&priv->ieee80211->associate_procedure_wq);
+#endif
+
+			}
+		}
+		priv->ieee80211->LinkDetectInfo.NumRecvBcnInPeriod=0;
+		priv->ieee80211->LinkDetectInfo.NumRecvDataInPeriod=0;
+	}
+//	CAM_read_entry(dev,4);
+	//check if reset the driver
+	if(check_reset_cnt++ >= 3 && !ieee->is_roaming)
+	{
+    		ResetType = rtl819x_ifcheck_resetornot(dev);
+		check_reset_cnt = 3;
+		//DbgPrint("Start to check silent reset\n");
+	}
+	//	RT_TRACE(COMP_RESET,"%s():priv->force_reset is %d,priv->ResetProgress is %d, priv->bForcedSilentReset is %d,priv->bDisableNormalResetCheck is %d,ResetType is %d\n",__FUNCTION__,priv->force_reset,priv->ResetProgress,priv->bForcedSilentReset,priv->bDisableNormalResetCheck,ResetType);
+#if 1
+	if( (priv->force_reset) || (priv->ResetProgress==RESET_TYPE_NORESET &&
+		(priv->bForcedSilentReset ||
+		(!priv->bDisableNormalResetCheck && ResetType==RESET_TYPE_SILENT)))) // This is control by OID set in Pomelo
+	{
+		RT_TRACE(COMP_RESET,"%s():priv->force_reset is %d,priv->ResetProgress is %d, priv->bForcedSilentReset is %d,priv->bDisableNormalResetCheck is %d,ResetType is %d\n",__FUNCTION__,priv->force_reset,priv->ResetProgress,priv->bForcedSilentReset,priv->bDisableNormalResetCheck,ResetType);
+		rtl819x_ifsilentreset(dev);
+	}
+#endif
+	priv->force_reset = false;
+	priv->bForcedSilentReset = false;
+	priv->bResetInProgress = false;
+	RT_TRACE(COMP_TRACE, " <==RtUsbCheckForHangWorkItemCallback()\n");
+
+}
+
+void watch_dog_timer_callback(unsigned long data)
+{
+	struct r8192_priv *priv = ieee80211_priv((struct net_device *) data);
+	//printk("===============>watch_dog  timer\n");
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+	queue_delayed_work(priv->priv_wq,&priv->watch_dog_wq, 0);
+#else
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+	schedule_task(&priv->watch_dog_wq);
+#else
+	queue_work(priv->priv_wq,&priv->watch_dog_wq);
+#endif
+#endif
+	mod_timer(&priv->watch_dog_timer, jiffies + MSECS(IEEE80211_WATCH_DOG_TIME));
+#if 0
+	priv->watch_dog_timer.expires = jiffies + MSECS(IEEE80211_WATCH_DOG_TIME);
+	add_timer(&priv->watch_dog_timer);
+#endif
+}
+int _rtl8192_up(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//int i;
+	int init_status = 0;
+	priv->up=1;
+	priv->ieee80211->ieee_up=1;
+	RT_TRACE(COMP_INIT, "Bringing up iface");
+	init_status = priv->ops->rtl819x_adapter_start(dev);
+	if(!init_status)
+	{
+		RT_TRACE(COMP_ERR,"ERR!!! %s(): initialization is failed!\n", __FUNCTION__);
+		priv->up=priv->ieee80211->ieee_up = 0;
+		return -EAGAIN;
+	}
+	RT_TRACE(COMP_INIT, "start adapter finished\n");
+	rtl8192_rx_enable(dev);
+//	rtl8192_tx_enable(dev);
+	if(priv->ieee80211->state != IEEE80211_LINKED)
+	ieee80211_softmac_start_protocol(priv->ieee80211);
+	ieee80211_reset_queue(priv->ieee80211);
+	watch_dog_timer_callback((unsigned long) dev);
+	if(!netif_queue_stopped(dev))
+		netif_start_queue(dev);
+	else
+		netif_wake_queue(dev);
+
+	/*
+	 * Make sure that drop_unencrypted is initialized as "0"
+	 * No packets will be sent in non-security mode if we had set drop_unencrypted.
+	 * ex, After kill wpa_supplicant process, make the driver up again.
+	 * drop_unencrypted remains as "1", which is set by wpa_supplicant. 2008/12/04.john
+	 */
+	priv->ieee80211->drop_unencrypted = 0;
+
+	return 0;
+}
+
+
+int rtl8192_open(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int ret;
+	down(&priv->wx_sem);
+	ret = rtl8192_up(dev);
+	up(&priv->wx_sem);
+	return ret;
+
+}
+
+
+int rtl8192_up(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	if (priv->up == 1) return -1;
+
+	return _rtl8192_up(dev);
+}
+
+
+int rtl8192_close(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int ret;
+
+	down(&priv->wx_sem);
+
+	ret = rtl8192_down(dev);
+
+	up(&priv->wx_sem);
+
+	return ret;
+
+}
+
+int rtl8192_down(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int i;
+
+	if (priv->up == 0) return -1;
+
+	priv->up=0;
+	priv->ieee80211->ieee_up = 0;
+	RT_TRACE(COMP_DOWN, "==========>%s()\n", __FUNCTION__);
+/* FIXME */
+	if (!netif_queue_stopped(dev))
+		netif_stop_queue(dev);
+
+	rtl8192_rtx_disable(dev);
+	//rtl8192_irq_disable(dev);
+
+ /* Tx related queue release */
+        for(i = 0; i < MAX_QUEUE_SIZE; i++) {
+                skb_queue_purge(&priv->ieee80211->skb_waitQ [i]);
+        }
+        for(i = 0; i < MAX_QUEUE_SIZE; i++) {
+                skb_queue_purge(&priv->ieee80211->skb_aggQ [i]);
+        }
+
+        for(i = 0; i < MAX_QUEUE_SIZE; i++) {
+                skb_queue_purge(&priv->ieee80211->skb_drv_aggQ [i]);
+        }
+
+        //as cancel_delayed_work will del work->timer, so if work is not definedas struct delayed_work, it will corrupt
+//	flush_scheduled_work();
+	rtl8192_cancel_deferred_work(priv);
+	deinit_hal_dm(dev);
+	del_timer_sync(&priv->watch_dog_timer);
+
+
+	ieee80211_softmac_stop_protocol(priv->ieee80211);
+	memset(&priv->ieee80211->current_network, 0 , offsetof(struct ieee80211_network, list));
+	RT_TRACE(COMP_DOWN, "<==========%s()\n", __FUNCTION__);
+
+		return 0;
+}
+
+
+void rtl8192_commit(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int reset_status = 0;
+	//u8 reset_times = 0;
+	if (priv->up == 0) return ;
+	priv->up = 0;
+
+	rtl8192_cancel_deferred_work(priv);
+	del_timer_sync(&priv->watch_dog_timer);
+	//cancel_delayed_work(&priv->SwChnlWorkItem);
+
+	ieee80211_softmac_stop_protocol(priv->ieee80211);
+
+	//rtl8192_irq_disable(dev);
+	rtl8192_rtx_disable(dev);
+	reset_status = _rtl8192_up(dev);
+
+}
+
+/*
+void rtl8192_restart(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+*/
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+void rtl8192_restart(struct work_struct *work)
+{
+        struct r8192_priv *priv = container_of(work, struct r8192_priv, reset_wq);
+        struct net_device *dev = priv->ieee80211->dev;
+#else
+void rtl8192_restart(struct net_device *dev)
+{
+
+        struct r8192_priv *priv = ieee80211_priv(dev);
+#endif
+
+	down(&priv->wx_sem);
+
+	rtl8192_commit(dev);
+
+	up(&priv->wx_sem);
+}
+
+static void r8192_set_multicast(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	short promisc;
+
+	//down(&priv->wx_sem);
+
+	/* FIXME FIXME */
+
+	promisc = (dev->flags & IFF_PROMISC) ? 1:0;
+
+	if (promisc != priv->promisc)
+	//	rtl8192_commit(dev);
+
+	priv->promisc = promisc;
+
+	//schedule_work(&priv->reset_wq);
+	//up(&priv->wx_sem);
+}
+
+
+int r8192_set_mac_adr(struct net_device *dev, void *mac)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct sockaddr *addr = mac;
+
+	down(&priv->wx_sem);
+
+	memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
+
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+	schedule_work(&priv->reset_wq);
+#else
+	schedule_task(&priv->reset_wq);
+#endif
+	up(&priv->wx_sem);
+
+	return 0;
+}
+
+/* based on ipw2200 driver */
+int rtl8192_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
+{
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct iwreq *wrq = (struct iwreq *)rq;
+	int ret=-1;
+	struct ieee80211_device *ieee = priv->ieee80211;
+	u32 key[4];
+	u8 broadcast_addr[6] = {0xff,0xff,0xff,0xff,0xff,0xff};
+	u8 zero_addr[6] = {0};
+	struct iw_point *p = &wrq->u.data;
+	struct ieee_param *ipw = NULL;//(struct ieee_param *)wrq->u.data.pointer;
+
+	down(&priv->wx_sem);
+
+
+     if (p->length < sizeof(struct ieee_param) || !p->pointer){
+             ret = -EINVAL;
+             goto out;
+	}
+
+     ipw = (struct ieee_param *)kmalloc(p->length, GFP_KERNEL);
+     if (ipw == NULL){
+             ret = -ENOMEM;
+             goto out;
+     }
+     if (copy_from_user(ipw, p->pointer, p->length)) {
+		kfree(ipw);
+            ret = -EFAULT;
+            goto out;
+	}
+
+	switch (cmd) {
+	    case RTL_IOCTL_WPA_SUPPLICANT:
+	//parse here for HW security
+			if (ipw->cmd == IEEE_CMD_SET_ENCRYPTION)
+			{
+				if (ipw->u.crypt.set_tx)
+				{
+					if (strcmp(ipw->u.crypt.alg, "CCMP") == 0)
+						ieee->pairwise_key_type = KEY_TYPE_CCMP;
+					else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0)
+						ieee->pairwise_key_type = KEY_TYPE_TKIP;
+					else if (strcmp(ipw->u.crypt.alg, "WEP") == 0)
+					{
+						if (ipw->u.crypt.key_len == 13)
+							ieee->pairwise_key_type = KEY_TYPE_WEP104;
+						else if (ipw->u.crypt.key_len == 5)
+							ieee->pairwise_key_type = KEY_TYPE_WEP40;
+					}
+					else
+						ieee->pairwise_key_type = KEY_TYPE_NA;
+
+					if (ieee->pairwise_key_type)
+					{
+				//	FIXME:these two lines below just to fix ipw interface bug, that is, it will never set mode down to driver. So treat it as ADHOC mode, if no association procedure. WB. 2009.02.04
+						if (memcmp(ieee->ap_mac_addr, zero_addr, 6) == 0)
+							ieee->iw_mode = IW_MODE_ADHOC;
+						memcpy((u8*)key, ipw->u.crypt.key, 16);
+						EnableHWSecurityConfig8192(dev);
+					//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!
+					//added by WB.
+						setKey(dev, 4, ipw->u.crypt.idx, ieee->pairwise_key_type, (u8*)ieee->ap_mac_addr, 0, key);
+						if (ieee->iw_mode == IW_MODE_ADHOC)
+						setKey(dev, ipw->u.crypt.idx, ipw->u.crypt.idx, ieee->pairwise_key_type, (u8*)ieee->ap_mac_addr, 0, key);
+					}
+				}
+				else //if (ipw->u.crypt.idx) //group key use idx > 0
+				{
+					memcpy((u8*)key, ipw->u.crypt.key, 16);
+					if (strcmp(ipw->u.crypt.alg, "CCMP") == 0)
+						ieee->group_key_type= KEY_TYPE_CCMP;
+					else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0)
+						ieee->group_key_type = KEY_TYPE_TKIP;
+					else if (strcmp(ipw->u.crypt.alg, "WEP") == 0)
+					{
+						if (ipw->u.crypt.key_len == 13)
+							ieee->group_key_type = KEY_TYPE_WEP104;
+						else if (ipw->u.crypt.key_len == 5)
+							ieee->group_key_type = KEY_TYPE_WEP40;
+					}
+					else
+						ieee->group_key_type = KEY_TYPE_NA;
+
+					if (ieee->group_key_type)
+					{
+							setKey(	dev,
+								ipw->u.crypt.idx,
+								ipw->u.crypt.idx,		//KeyIndex
+						     		ieee->group_key_type,	//KeyType
+						            	broadcast_addr,	//MacAddr
+								0,		//DefaultKey
+							      	key);		//KeyContent
+					}
+				}
+			}
+#ifdef JOHN_HWSEC_DEBUG
+		//john's test 0711
+		printk("@@ wrq->u pointer = ");
+		for(i=0;i<wrq->u.data.length;i++){
+			if(i%10==0) printk("\n");
+			printk( "%8x|", ((u32*)wrq->u.data.pointer)[i] );
+		}
+		printk("\n");
+#endif /*JOHN_HWSEC_DEBUG*/
+		ret = ieee80211_wpa_supplicant_ioctl(priv->ieee80211, &wrq->u.data);
+		break;
+
+	    default:
+		ret = -EOPNOTSUPP;
+		break;
+	}
+	kfree(ipw);
+        ipw = NULL;
+out:
+	up(&priv->wx_sem);
+	return ret;
+}
+
+#ifdef RTL8192SU
+u8 rtl8192SU_HwRateToMRate(bool bIsHT, u8 rate,bool bFirstAMPDU)
+{
+
+	u8	ret_rate = 0x02;
+
+	if( bFirstAMPDU )
+	{
+	if(!bIsHT)
+	{
+		switch(rate)
+		{
+
+			case DESC92S_RATE1M:		ret_rate = MGN_1M;		break;
+			case DESC92S_RATE2M:		ret_rate = MGN_2M;		break;
+			case DESC92S_RATE5_5M:		ret_rate = MGN_5_5M;		break;
+			case DESC92S_RATE11M:		ret_rate = MGN_11M;		break;
+			case DESC92S_RATE6M:		ret_rate = MGN_6M;		break;
+			case DESC92S_RATE9M:		ret_rate = MGN_9M;		break;
+			case DESC92S_RATE12M:		ret_rate = MGN_12M;		break;
+			case DESC92S_RATE18M:		ret_rate = MGN_18M;		break;
+			case DESC92S_RATE24M:		ret_rate = MGN_24M;		break;
+			case DESC92S_RATE36M:		ret_rate = MGN_36M;		break;
+			case DESC92S_RATE48M:		ret_rate = MGN_48M;		break;
+			case DESC92S_RATE54M:		ret_rate = MGN_54M;		break;
+
+			default:
+				RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n", rate, bIsHT);
+					break;
+	}
+		}
+		else
+	{
+		switch(rate)
+		{
+
+			case DESC92S_RATEMCS0:	ret_rate = MGN_MCS0;		break;
+			case DESC92S_RATEMCS1:	ret_rate = MGN_MCS1;		break;
+			case DESC92S_RATEMCS2:	ret_rate = MGN_MCS2;		break;
+			case DESC92S_RATEMCS3:	ret_rate = MGN_MCS3;		break;
+			case DESC92S_RATEMCS4:	ret_rate = MGN_MCS4;		break;
+			case DESC92S_RATEMCS5:	ret_rate = MGN_MCS5;		break;
+			case DESC92S_RATEMCS6:	ret_rate = MGN_MCS6;		break;
+			case DESC92S_RATEMCS7:	ret_rate = MGN_MCS7;		break;
+			case DESC92S_RATEMCS8:	ret_rate = MGN_MCS8;		break;
+			case DESC92S_RATEMCS9:	ret_rate = MGN_MCS9;		break;
+			case DESC92S_RATEMCS10:	ret_rate = MGN_MCS10;	break;
+			case DESC92S_RATEMCS11:	ret_rate = MGN_MCS11;	break;
+			case DESC92S_RATEMCS12:	ret_rate = MGN_MCS12;	break;
+			case DESC92S_RATEMCS13:	ret_rate = MGN_MCS13;	break;
+			case DESC92S_RATEMCS14:	ret_rate = MGN_MCS14;	break;
+			case DESC92S_RATEMCS15:	ret_rate = MGN_MCS15;	break;
+			case DESC92S_RATEMCS32:	ret_rate = (0x80|0x20);	break;
+
+			default:
+					RT_TRACE(COMP_RECV, "HwRateToMRate92S(): Non supported Rate [%x], bIsHT = %d!!!\n",rate, bIsHT );
+				break;
+		}
+
+	}
+	}
+	else
+	{
+		switch(rate)
+		{
+
+			case DESC92S_RATE1M:	ret_rate = MGN_1M;		break;
+			case DESC92S_RATE2M:	ret_rate = MGN_2M;		break;
+			case DESC92S_RATE5_5M:	ret_rate = MGN_5_5M;		break;
+			case DESC92S_RATE11M:	ret_rate = MGN_11M;		break;
+			case DESC92S_RATE6M:	ret_rate = MGN_6M;		break;
+			case DESC92S_RATE9M:	ret_rate = MGN_9M;		break;
+			case DESC92S_RATE12M:	ret_rate = MGN_12M;		break;
+			case DESC92S_RATE18M:	ret_rate = MGN_18M;		break;
+			case DESC92S_RATE24M:	ret_rate = MGN_24M;		break;
+			case DESC92S_RATE36M:	ret_rate = MGN_36M;		break;
+			case DESC92S_RATE48M:	ret_rate = MGN_48M;		break;
+			case DESC92S_RATE54M:	ret_rate = MGN_54M;		break;
+			case DESC92S_RATEMCS0:	ret_rate = MGN_MCS0;		break;
+			case DESC92S_RATEMCS1:	ret_rate = MGN_MCS1;		break;
+			case DESC92S_RATEMCS2:	ret_rate = MGN_MCS2;		break;
+			case DESC92S_RATEMCS3:	ret_rate = MGN_MCS3;		break;
+			case DESC92S_RATEMCS4:	ret_rate = MGN_MCS4;		break;
+			case DESC92S_RATEMCS5:	ret_rate = MGN_MCS5;		break;
+			case DESC92S_RATEMCS6:	ret_rate = MGN_MCS6;		break;
+			case DESC92S_RATEMCS7:	ret_rate = MGN_MCS7;		break;
+			case DESC92S_RATEMCS8:	ret_rate = MGN_MCS8;		break;
+			case DESC92S_RATEMCS9:	ret_rate = MGN_MCS9;		break;
+			case DESC92S_RATEMCS10:	ret_rate = MGN_MCS10;	break;
+			case DESC92S_RATEMCS11:	ret_rate = MGN_MCS11;	break;
+			case DESC92S_RATEMCS12:	ret_rate = MGN_MCS12;	break;
+			case DESC92S_RATEMCS13:	ret_rate = MGN_MCS13;	break;
+			case DESC92S_RATEMCS14:	ret_rate = MGN_MCS14;	break;
+			case DESC92S_RATEMCS15:	ret_rate = MGN_MCS15;	break;
+			case DESC92S_RATEMCS32:	ret_rate = (0x80|0x20);	break;
+
+			default:
+				RT_TRACE(COMP_RECV, "HwRateToMRate92S(): Non supported Rate [%x], bIsHT = %d!!!\n",rate, bIsHT );
+				break;
+			}
+	}
+	return ret_rate;
+}
+#endif
+
+u8 HwRateToMRate90(bool bIsHT, u8 rate)
+{
+	u8  ret_rate = 0xff;
+
+	if(!bIsHT) {
+		switch(rate) {
+			case DESC90_RATE1M:   ret_rate = MGN_1M;         break;
+			case DESC90_RATE2M:   ret_rate = MGN_2M;         break;
+			case DESC90_RATE5_5M: ret_rate = MGN_5_5M;       break;
+			case DESC90_RATE11M:  ret_rate = MGN_11M;        break;
+			case DESC90_RATE6M:   ret_rate = MGN_6M;         break;
+			case DESC90_RATE9M:   ret_rate = MGN_9M;         break;
+			case DESC90_RATE12M:  ret_rate = MGN_12M;        break;
+			case DESC90_RATE18M:  ret_rate = MGN_18M;        break;
+			case DESC90_RATE24M:  ret_rate = MGN_24M;        break;
+			case DESC90_RATE36M:  ret_rate = MGN_36M;        break;
+			case DESC90_RATE48M:  ret_rate = MGN_48M;        break;
+			case DESC90_RATE54M:  ret_rate = MGN_54M;        break;
+
+			default:
+				ret_rate = 0xff;
+				RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n", rate, bIsHT);
+				break;
+		}
+
+	} else {
+		switch(rate) {
+			case DESC90_RATEMCS0:   ret_rate = MGN_MCS0;    break;
+			case DESC90_RATEMCS1:   ret_rate = MGN_MCS1;    break;
+			case DESC90_RATEMCS2:   ret_rate = MGN_MCS2;    break;
+			case DESC90_RATEMCS3:   ret_rate = MGN_MCS3;    break;
+			case DESC90_RATEMCS4:   ret_rate = MGN_MCS4;    break;
+			case DESC90_RATEMCS5:   ret_rate = MGN_MCS5;    break;
+			case DESC90_RATEMCS6:   ret_rate = MGN_MCS6;    break;
+			case DESC90_RATEMCS7:   ret_rate = MGN_MCS7;    break;
+			case DESC90_RATEMCS8:   ret_rate = MGN_MCS8;    break;
+			case DESC90_RATEMCS9:   ret_rate = MGN_MCS9;    break;
+			case DESC90_RATEMCS10:  ret_rate = MGN_MCS10;   break;
+			case DESC90_RATEMCS11:  ret_rate = MGN_MCS11;   break;
+			case DESC90_RATEMCS12:  ret_rate = MGN_MCS12;   break;
+			case DESC90_RATEMCS13:  ret_rate = MGN_MCS13;   break;
+			case DESC90_RATEMCS14:  ret_rate = MGN_MCS14;   break;
+			case DESC90_RATEMCS15:  ret_rate = MGN_MCS15;   break;
+			case DESC90_RATEMCS32:  ret_rate = (0x80|0x20); break;
+
+			default:
+				ret_rate = 0xff;
+				RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n",rate, bIsHT);
+				break;
+		}
+	}
+
+	return ret_rate;
+}
+
+/**
+ * Function:     UpdateRxPktTimeStamp
+ * Overview:     Recored down the TSF time stamp when receiving a packet
+ *
+ * Input:
+ *       PADAPTER        Adapter
+ *       PRT_RFD         pRfd,
+ *
+ * Output:
+ *       PRT_RFD         pRfd
+ *                               (pRfd->Status.TimeStampHigh is updated)
+ *                               (pRfd->Status.TimeStampLow is updated)
+ * Return:
+ *               None
+ */
+void UpdateRxPktTimeStamp8190 (struct net_device *dev, struct ieee80211_rx_stats *stats)
+{
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	if(stats->bIsAMPDU && !stats->bFirstMPDU) {
+		stats->mac_time[0] = priv->LastRxDescTSFLow;
+		stats->mac_time[1] = priv->LastRxDescTSFHigh;
+	} else {
+		priv->LastRxDescTSFLow = stats->mac_time[0];
+		priv->LastRxDescTSFHigh = stats->mac_time[1];
+	}
+}
+
+//by amy 080606
+
+long rtl819x_translate_todbm(u8 signal_strength_index	)// 0-100 index.
+{
+	long	signal_power; // in dBm.
+
+	// Translate to dBm (x=0.5y-95).
+	signal_power = (long)((signal_strength_index + 1) >> 1);
+	signal_power -= 95;
+
+	return signal_power;
+}
+
+
+/* 2008/01/22 MH We can not delcare RSSI/EVM total value of sliding window to
+    be a local static. Otherwise, it may increase when we return from S3/S4. The
+    value will be kept in memory or disk. We must delcare the value in adapter
+    and it will be reinitialized when return from S3/S4. */
+void rtl8192_process_phyinfo(struct r8192_priv * priv,u8* buffer, struct ieee80211_rx_stats * pprevious_stats, struct ieee80211_rx_stats * pcurrent_stats)
+{
+	bool bcheck = false;
+	u8	rfpath;
+	u32	nspatial_stream, tmp_val;
+	//u8	i;
+	static u32 slide_rssi_index=0, slide_rssi_statistics=0;
+	static u32 slide_evm_index=0, slide_evm_statistics=0;
+	static u32 last_rssi=0, last_evm=0;
+
+	static u32 slide_beacon_adc_pwdb_index=0, slide_beacon_adc_pwdb_statistics=0;
+	static u32 last_beacon_adc_pwdb=0;
+
+	struct ieee80211_hdr_3addr *hdr;
+	u16 sc ;
+	unsigned int frag,seq;
+	hdr = (struct ieee80211_hdr_3addr *)buffer;
+	sc = le16_to_cpu(hdr->seq_ctl);
+	frag = WLAN_GET_SEQ_FRAG(sc);
+	seq = WLAN_GET_SEQ_SEQ(sc);
+	//cosa add 04292008 to record the sequence number
+	pcurrent_stats->Seq_Num = seq;
+	//
+	// Check whether we should take the previous packet into accounting
+	//
+	if(!pprevious_stats->bIsAMPDU)
+	{
+		// if previous packet is not aggregated packet
+		bcheck = true;
+	}else
+	{
+	#if 0
+		// if previous packet is aggregated packet, and current packet
+		//  (1) is not AMPDU
+		//  (2) is the first packet of one AMPDU
+		// that means the previous packet is the last one aggregated packet
+		if( !pcurrent_stats->bIsAMPDU || pcurrent_stats->bFirstMPDU)
+			bcheck = true;
+	#endif
+	}
+
+
+	if(slide_rssi_statistics++ >= PHY_RSSI_SLID_WIN_MAX)
+	{
+		slide_rssi_statistics = PHY_RSSI_SLID_WIN_MAX;
+		last_rssi = priv->stats.slide_signal_strength[slide_rssi_index];
+		priv->stats.slide_rssi_total -= last_rssi;
+	}
+	priv->stats.slide_rssi_total += pprevious_stats->SignalStrength;
+
+	priv->stats.slide_signal_strength[slide_rssi_index++] = pprevious_stats->SignalStrength;
+	if(slide_rssi_index >= PHY_RSSI_SLID_WIN_MAX)
+		slide_rssi_index = 0;
+
+	// <1> Showed on UI for user, in dbm
+	tmp_val = priv->stats.slide_rssi_total/slide_rssi_statistics;
+	priv->stats.signal_strength = rtl819x_translate_todbm((u8)tmp_val);
+	pcurrent_stats->rssi = priv->stats.signal_strength;
+	//
+	// If the previous packet does not match the criteria, neglect it
+	//
+	if(!pprevious_stats->bPacketMatchBSSID)
+	{
+		if(!pprevious_stats->bToSelfBA)
+			return;
+	}
+
+	if(!bcheck)
+		return;
+
+
+	//rtl8190_process_cck_rxpathsel(priv,pprevious_stats);//only rtl8190 supported
+
+	//
+	// Check RSSI
+	//
+	priv->stats.num_process_phyinfo++;
+
+	/* record the general signal strength to the sliding window. */
+
+
+	// <2> Showed on UI for engineering
+	// hardware does not provide rssi information for each rf path in CCK
+	if(!pprevious_stats->bIsCCK && (pprevious_stats->bPacketToSelf || pprevious_stats->bToSelfBA))
+	{
+		for (rfpath = RF90_PATH_A; rfpath < priv->NumTotalRFPath; rfpath++)
+		{
+                     if (!rtl8192_phy_CheckIsLegalRFPath(priv->ieee80211->dev, rfpath))
+			         continue;
+
+			//Fixed by Jacken 2008-03-20
+			if(priv->stats.rx_rssi_percentage[rfpath] == 0)
+			{
+				priv->stats.rx_rssi_percentage[rfpath] = pprevious_stats->RxMIMOSignalStrength[rfpath];
+				//DbgPrint("MIMO RSSI initialize \n");
+			}
+			if(pprevious_stats->RxMIMOSignalStrength[rfpath]  > priv->stats.rx_rssi_percentage[rfpath])
+			{
+				priv->stats.rx_rssi_percentage[rfpath] =
+					( (priv->stats.rx_rssi_percentage[rfpath]*(Rx_Smooth_Factor-1)) +
+					(pprevious_stats->RxMIMOSignalStrength[rfpath])) /(Rx_Smooth_Factor);
+				priv->stats.rx_rssi_percentage[rfpath] = priv->stats.rx_rssi_percentage[rfpath]  + 1;
+			}
+			else
+			{
+				priv->stats.rx_rssi_percentage[rfpath] =
+					( (priv->stats.rx_rssi_percentage[rfpath]*(Rx_Smooth_Factor-1)) +
+					(pprevious_stats->RxMIMOSignalStrength[rfpath])) /(Rx_Smooth_Factor);
+			}
+			RT_TRACE(COMP_DBG,"priv->stats.rx_rssi_percentage[rfPath]  = %d \n" ,priv->stats.rx_rssi_percentage[rfpath] );
+		}
+	}
+
+
+	//
+	// Check PWDB.
+	//
+	RT_TRACE(COMP_RXDESC, "Smooth %s PWDB = %d\n",
+				pprevious_stats->bIsCCK? "CCK": "OFDM",
+				pprevious_stats->RxPWDBAll);
+
+	if(pprevious_stats->bPacketBeacon)
+	{
+/* record the beacon pwdb to the sliding window. */
+		if(slide_beacon_adc_pwdb_statistics++ >= PHY_Beacon_RSSI_SLID_WIN_MAX)
+		{
+			slide_beacon_adc_pwdb_statistics = PHY_Beacon_RSSI_SLID_WIN_MAX;
+			last_beacon_adc_pwdb = priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index];
+			priv->stats.Slide_Beacon_Total -= last_beacon_adc_pwdb;
+			//DbgPrint("slide_beacon_adc_pwdb_index = %d, last_beacon_adc_pwdb = %d, Adapter->RxStats.Slide_Beacon_Total = %d\n",
+			//	slide_beacon_adc_pwdb_index, last_beacon_adc_pwdb, Adapter->RxStats.Slide_Beacon_Total);
+		}
+		priv->stats.Slide_Beacon_Total += pprevious_stats->RxPWDBAll;
+		priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index] = pprevious_stats->RxPWDBAll;
+		//DbgPrint("slide_beacon_adc_pwdb_index = %d, pPreviousRfd->Status.RxPWDBAll = %d\n", slide_beacon_adc_pwdb_index, pPreviousRfd->Status.RxPWDBAll);
+		slide_beacon_adc_pwdb_index++;
+		if(slide_beacon_adc_pwdb_index >= PHY_Beacon_RSSI_SLID_WIN_MAX)
+			slide_beacon_adc_pwdb_index = 0;
+		pprevious_stats->RxPWDBAll = priv->stats.Slide_Beacon_Total/slide_beacon_adc_pwdb_statistics;
+		if(pprevious_stats->RxPWDBAll >= 3)
+			pprevious_stats->RxPWDBAll -= 3;
+	}
+
+	RT_TRACE(COMP_RXDESC, "Smooth %s PWDB = %d\n",
+				pprevious_stats->bIsCCK? "CCK": "OFDM",
+				pprevious_stats->RxPWDBAll);
+
+
+	if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA)
+	{
+		if(priv->undecorated_smoothed_pwdb < 0)	// initialize
+		{
+			priv->undecorated_smoothed_pwdb = pprevious_stats->RxPWDBAll;
+			//DbgPrint("First pwdb initialize \n");
+		}
+#if 1
+		if(pprevious_stats->RxPWDBAll > (u32)priv->undecorated_smoothed_pwdb)
+		{
+			priv->undecorated_smoothed_pwdb =
+					( ((priv->undecorated_smoothed_pwdb)*(Rx_Smooth_Factor-1)) +
+					(pprevious_stats->RxPWDBAll)) /(Rx_Smooth_Factor);
+			priv->undecorated_smoothed_pwdb = priv->undecorated_smoothed_pwdb + 1;
+		}
+		else
+		{
+			priv->undecorated_smoothed_pwdb =
+					( ((priv->undecorated_smoothed_pwdb)*(Rx_Smooth_Factor-1)) +
+					(pprevious_stats->RxPWDBAll)) /(Rx_Smooth_Factor);
+		}
+#else
+		//Fixed by Jacken 2008-03-20
+		if(pPreviousRfd->Status.RxPWDBAll > (u32)pHalData->UndecoratedSmoothedPWDB)
+		{
+			pHalData->UndecoratedSmoothedPWDB =
+					( ((pHalData->UndecoratedSmoothedPWDB)* 5) + (pPreviousRfd->Status.RxPWDBAll)) / 6;
+			pHalData->UndecoratedSmoothedPWDB = pHalData->UndecoratedSmoothedPWDB + 1;
+		}
+		else
+		{
+			pHalData->UndecoratedSmoothedPWDB =
+					( ((pHalData->UndecoratedSmoothedPWDB)* 5) + (pPreviousRfd->Status.RxPWDBAll)) / 6;
+		}
+#endif
+
+	}
+
+	//
+	// Check EVM
+	//
+	/* record the general EVM to the sliding window. */
+	if(pprevious_stats->SignalQuality == 0)
+	{
+	}
+	else
+	{
+		if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA){
+			if(slide_evm_statistics++ >= PHY_RSSI_SLID_WIN_MAX){
+				slide_evm_statistics = PHY_RSSI_SLID_WIN_MAX;
+				last_evm = priv->stats.slide_evm[slide_evm_index];
+				priv->stats.slide_evm_total -= last_evm;
+			}
+
+			priv->stats.slide_evm_total += pprevious_stats->SignalQuality;
+
+			priv->stats.slide_evm[slide_evm_index++] = pprevious_stats->SignalQuality;
+			if(slide_evm_index >= PHY_RSSI_SLID_WIN_MAX)
+				slide_evm_index = 0;
+
+			// <1> Showed on UI for user, in percentage.
+			tmp_val = priv->stats.slide_evm_total/slide_evm_statistics;
+			priv->stats.signal_quality = tmp_val;
+			//cosa add 10/11/2007, Showed on UI for user in Windows Vista, for Link quality.
+			priv->stats.last_signal_strength_inpercent = tmp_val;
+		}
+
+		// <2> Showed on UI for engineering
+		if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA)
+		{
+			for(nspatial_stream = 0; nspatial_stream<2 ; nspatial_stream++) // 2 spatial stream
+			{
+				if(pprevious_stats->RxMIMOSignalQuality[nspatial_stream] != -1)
+				{
+					if(priv->stats.rx_evm_percentage[nspatial_stream] == 0)	// initialize
+					{
+						priv->stats.rx_evm_percentage[nspatial_stream] = pprevious_stats->RxMIMOSignalQuality[nspatial_stream];
+					}
+					priv->stats.rx_evm_percentage[nspatial_stream] =
+						( (priv->stats.rx_evm_percentage[nspatial_stream]* (Rx_Smooth_Factor-1)) +
+						(pprevious_stats->RxMIMOSignalQuality[nspatial_stream]* 1)) / (Rx_Smooth_Factor);
+				}
+			}
+		}
+	}
+
+
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:	rtl819x_query_rxpwrpercentage()
+ *
+ * Overview:
+ *
+ * Input:		char		antpower
+ *
+ * Output:		NONE
+ *
+ * Return:		0-100 percentage
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/26/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static u8 rtl819x_query_rxpwrpercentage(
+	char		antpower
+	)
+{
+	if ((antpower <= -100) || (antpower >= 20))
+	{
+		return	0;
+	}
+	else if (antpower >= 0)
+	{
+		return	100;
+	}
+	else
+	{
+		return	(100+antpower);
+	}
+
+}	/* QueryRxPwrPercentage */
+
+static u8
+rtl819x_evm_dbtopercentage(
+    char value
+    )
+{
+    char ret_val;
+
+    ret_val = value;
+
+    if(ret_val >= 0)
+        ret_val = 0;
+    if(ret_val <= -33)
+        ret_val = -33;
+    ret_val = 0 - ret_val;
+    ret_val*=3;
+	if(ret_val == 99)
+		ret_val = 100;
+    return(ret_val);
+}
+//
+//	Description:
+// 	We want good-looking for signal strength/quality
+//	2007/7/19 01:09, by cosa.
+//
+long
+rtl819x_signal_scale_mapping(
+	long currsig
+	)
+{
+	long retsig;
+
+	// Step 1. Scale mapping.
+	if(currsig >= 61 && currsig <= 100)
+	{
+		retsig = 90 + ((currsig - 60) / 4);
+	}
+	else if(currsig >= 41 && currsig <= 60)
+	{
+		retsig = 78 + ((currsig - 40) / 2);
+	}
+	else if(currsig >= 31 && currsig <= 40)
+	{
+		retsig = 66 + (currsig - 30);
+	}
+	else if(currsig >= 21 && currsig <= 30)
+	{
+		retsig = 54 + (currsig - 20);
+	}
+	else if(currsig >= 5 && currsig <= 20)
+	{
+		retsig = 42 + (((currsig - 5) * 2) / 3);
+	}
+	else if(currsig == 4)
+	{
+		retsig = 36;
+	}
+	else if(currsig == 3)
+	{
+		retsig = 27;
+	}
+	else if(currsig == 2)
+	{
+		retsig = 18;
+	}
+	else if(currsig == 1)
+	{
+		retsig = 9;
+	}
+	else
+	{
+		retsig = currsig;
+	}
+
+	return retsig;
+}
+
+#ifdef RTL8192SU
+/*-----------------------------------------------------------------------------
+ * Function:	QueryRxPhyStatus8192S()
+ *
+ * Overview:
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	06/01/2007	MHC		Create Version 0.
+ *	06/05/2007	MHC		Accordign to HW's new data sheet, we add CCK and OFDM
+ *						descriptor definition.
+ *	07/04/2007	MHC		According to Jerry and Bryant's document. We read
+ *						ir_isolation and ext_lna for RF's init value and use
+ *						to compensate RSSI after receiving packets.
+ *	09/10/2008	MHC		Modify name and PHY status field for 92SE.
+ *	09/19/2008	MHC		Add CCK/OFDM SS/SQ for 92S series.
+ *
+ *---------------------------------------------------------------------------*/
+static void rtl8192SU_query_rxphystatus(
+	struct r8192_priv * priv,
+	struct ieee80211_rx_stats * pstats,
+	rx_desc_819x_usb	*pDesc,
+	rx_drvinfo_819x_usb  * pdrvinfo,
+	struct ieee80211_rx_stats * precord_stats,
+	bool bpacket_match_bssid,
+	bool bpacket_toself,
+	bool bPacketBeacon,
+	bool bToSelfBA
+	)
+{
+	//PRT_RFD_STATUS		pRtRfdStatus = &(pRfd->Status);
+	//PHY_STS_CCK_8192S_T	*pCck_buf;
+	phy_sts_cck_819xusb_t	*	pcck_buf;
+	phy_ofdm_rx_status_rxsc_sgien_exintfflag* prxsc;
+	//u8				*prxpkt;
+	//u8				i, max_spatial_stream, tmp_rxsnr, tmp_rxevm, rxsc_sgien_exflg;
+	u8				i, max_spatial_stream, rxsc_sgien_exflg;
+	char				rx_pwr[4], rx_pwr_all=0;
+	//long				rx_avg_pwr = 0;
+	//char				rx_snrX, rx_evmX;
+	u8				evm, pwdb_all;
+	u32				RSSI, total_rssi=0;//, total_evm=0;
+//	long				signal_strength_index = 0;
+	u8				is_cck_rate=0;
+	u8				rf_rx_num = 0;
+
+
+
+	priv->stats.numqry_phystatus++;
+
+	is_cck_rate = rx_hal_is_cck_rate(pDesc);
+
+	// Record it for next packet processing
+	memset(precord_stats, 0, sizeof(struct ieee80211_rx_stats));
+	pstats->bPacketMatchBSSID = precord_stats->bPacketMatchBSSID = bpacket_match_bssid;
+	pstats->bPacketToSelf = precord_stats->bPacketToSelf = bpacket_toself;
+	pstats->bIsCCK = precord_stats->bIsCCK = is_cck_rate;//RX_HAL_IS_CCK_RATE(pDrvInfo);
+	pstats->bPacketBeacon = precord_stats->bPacketBeacon = bPacketBeacon;
+	pstats->bToSelfBA = precord_stats->bToSelfBA = bToSelfBA;
+
+#ifndef RTL8192SU
+	phy_sts_ofdm_819xusb_t*	pofdm_buf = NULL;
+	prxpkt = (u8*)pdrvinfo;
+
+	/* Move pointer to the 16th bytes. Phy status start address. */
+	prxpkt += sizeof(rx_drvinfo_819x_usb);
+
+	/* Initial the cck and ofdm buffer pointer */
+	pcck_buf = (phy_sts_cck_819xusb_t *)prxpkt;
+	pofdm_buf = (phy_sts_ofdm_819xusb_t *)prxpkt;
+#endif
+
+	pstats->RxMIMOSignalQuality[0] = -1;
+	pstats->RxMIMOSignalQuality[1] = -1;
+	precord_stats->RxMIMOSignalQuality[0] = -1;
+	precord_stats->RxMIMOSignalQuality[1] = -1;
+
+	if(is_cck_rate)
+	{
+		u8 report;//, tmp_pwdb;
+		//char cck_adc_pwdb[4];
+
+		// CCK Driver info Structure is not the same as OFDM packet.
+		pcck_buf = (phy_sts_cck_819xusb_t *)pdrvinfo;
+
+		//
+		// (1)Hardware does not provide RSSI for CCK
+		//
+
+		//
+		// (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
+		//
+
+		priv->stats.numqry_phystatusCCK++;
+
+		if(!priv->bCckHighPower)
+		{
+			report = pcck_buf->cck_agc_rpt & 0xc0;
+			report = report>>6;
+			switch(report)
+			{
+				//Fixed by Jacken from Bryant 2008-03-20
+				//Original value is -38 , -26 , -14 , -2
+				//Fixed value is -35 , -23 , -11 , 6
+				case 0x3:
+					rx_pwr_all = -35 - (pcck_buf->cck_agc_rpt & 0x3e);
+					break;
+				case 0x2:
+					rx_pwr_all = -23 - (pcck_buf->cck_agc_rpt & 0x3e);
+					break;
+				case 0x1:
+					rx_pwr_all = -11 - (pcck_buf->cck_agc_rpt & 0x3e);
+					break;
+				case 0x0:
+					rx_pwr_all = 8 - (pcck_buf->cck_agc_rpt & 0x3e);//6->8
+					break;
+			}
+		}
+		else
+		{
+			report = pdrvinfo->cfosho[0] & 0x60;
+			report = report>>5;
+			switch(report)
+			{
+				case 0x3:
+					rx_pwr_all = -35 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
+					break;
+				case 0x2:
+					rx_pwr_all = -23 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1);
+					break;
+				case 0x1:
+					rx_pwr_all = -11 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
+					break;
+				case 0x0:
+					rx_pwr_all = -8 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;//6->-8
+					break;
+			}
+		}
+
+		pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);//check it
+		pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
+		//pstats->RecvSignalPower = pwdb_all;
+		pstats->RecvSignalPower = rx_pwr_all;
+
+		//
+		// (3) Get Signal Quality (EVM)
+		//
+	//if(bpacket_match_bssid)
+	{
+			u8	sq;
+
+			if(pstats->RxPWDBAll > 40)
+			{
+				sq = 100;
+			}else
+			{
+				sq = pcck_buf->sq_rpt;
+
+				if(pcck_buf->sq_rpt > 64)
+					sq = 0;
+				else if (pcck_buf->sq_rpt < 20)
+					sq = 100;
+				else
+					sq = ((64-sq) * 100) / 44;
+			}
+			pstats->SignalQuality = precord_stats->SignalQuality = sq;
+			pstats->RxMIMOSignalQuality[0] = precord_stats->RxMIMOSignalQuality[0] = sq;
+			pstats->RxMIMOSignalQuality[1] = precord_stats->RxMIMOSignalQuality[1] = -1;
+		}
+	}
+	else
+	{
+		priv->stats.numqry_phystatusHT++;
+
+		// 2008/09/19 MH For 92S debug, RX RF path always enable!!
+		priv->brfpath_rxenable[0] = priv->brfpath_rxenable[1] = TRUE;
+
+		//
+		// (1)Get RSSI for HT rate
+		//
+		//for(i=RF90_PATH_A; i<priv->NumTotalRFPath; i++)
+		for(i=RF90_PATH_A; i<RF90_PATH_MAX; i++)
+		{
+			// 2008/01/30 MH we will judge RF RX path now.
+			if (priv->brfpath_rxenable[i])
+				rf_rx_num++;
+			//else
+			//	continue;
+
+		//if (!rtl8192_phy_CheckIsLegalRFPath(priv->ieee80211->dev, i))
+		//		continue;
+
+			//Fixed by Jacken from Bryant 2008-03-20
+			//Original value is 106
+			//rx_pwr[i] = ((pofdm_buf->trsw_gain_X[i]&0x3F)*2) - 106;
+			rx_pwr[i] = ((pdrvinfo->gain_trsw[i]&0x3F)*2) - 110;
+
+			/* Translate DBM to percentage. */
+			RSSI = rtl819x_query_rxpwrpercentage(rx_pwr[i]);	//check ok
+			total_rssi += RSSI;
+			RT_TRACE(COMP_RF, "RF-%d RXPWR=%x RSSI=%d\n", i, rx_pwr[i], RSSI);
+
+			//Get Rx snr value in DB
+			//tmp_rxsnr =	pofdm_buf->rxsnr_X[i];
+			//rx_snrX = (char)(tmp_rxsnr);
+			//rx_snrX /= 2;
+			//priv->stats.rxSNRdB[i] = (long)rx_snrX;
+			priv->stats.rxSNRdB[i] = (long)(pdrvinfo->rxsnr[i]/2);
+
+			/* Translate DBM to percentage. */
+			//RSSI = rtl819x_query_rxpwrpercentage(rx_pwr[i]);
+			//total_rssi += RSSI;
+
+			/* Record Signal Strength for next packet */
+			//if(bpacket_match_bssid)
+			{
+				pstats->RxMIMOSignalStrength[i] =(u8) RSSI;
+				precord_stats->RxMIMOSignalStrength[i] =(u8) RSSI;
+			}
+		}
+
+
+		//
+		// (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
+		//
+		//Fixed by Jacken from Bryant 2008-03-20
+		//Original value is 106
+		//rx_pwr_all = (((pofdm_buf->pwdb_all ) >> 1 )& 0x7f) -106;
+		rx_pwr_all = (((pdrvinfo->pwdb_all ) >> 1 )& 0x7f) -106;
+		pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
+
+		pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
+		pstats->RxPower = precord_stats->RxPower =  rx_pwr_all;
+		pstats->RecvSignalPower = rx_pwr_all;
+
+		//
+		// (3)EVM of HT rate
+		//
+		//if(pdrvinfo->RxHT && pdrvinfo->RxRate>=DESC90_RATEMCS8 &&
+		 //	pdrvinfo->RxRate<=DESC90_RATEMCS15)
+		 if(pDesc->RxHT && pDesc->RxMCS>=DESC92S_RATEMCS8 &&
+		 	pDesc->RxMCS<=DESC92S_RATEMCS15)
+			max_spatial_stream = 2; //both spatial stream make sense
+		else
+			max_spatial_stream = 1; //only spatial stream 1 makes sense
+
+		for(i=0; i<max_spatial_stream; i++)
+		{
+			//tmp_rxevm =	pofdm_buf->rxevm_X[i];
+			//rx_evmX = (char)(tmp_rxevm);
+
+			// Do not use shift operation like "rx_evmX >>= 1" because the compilor of free build environment
+			// fill most significant bit to "zero" when doing shifting operation which may change a negative
+			// value to positive one, then the dbm value (which is supposed to be negative)  is not correct anymore.
+			//rx_evmX /= 2;	//dbm
+
+			//evm = rtl819x_evm_dbtopercentage(rx_evmX);
+			evm = rtl819x_evm_dbtopercentage( (pdrvinfo->rxevm[i] /*/ 2*/));	//dbm
+			RT_TRACE(COMP_RF, "RXRATE=%x RXEVM=%x EVM=%s%d\n", pDesc->RxMCS, pdrvinfo->rxevm[i], "%", evm);
+#if 0
+			EVM = SignalScaleMapping(EVM);//make it good looking, from 0~100//=====>from here
+#endif
+
+			//if(bpacket_match_bssid)
+			{
+				if(i==0) // Fill value in RFD, Get the first spatial stream only
+					pstats->SignalQuality = precord_stats->SignalQuality = (u8)(evm & 0xff);
+				pstats->RxMIMOSignalQuality[i] = precord_stats->RxMIMOSignalQuality[i] = (u8)(evm & 0xff);
+			}
+		}
+
+
+		/* record rx statistics for debug */
+		//rxsc_sgien_exflg = pofdm_buf->rxsc_sgien_exflg;
+		prxsc =	(phy_ofdm_rx_status_rxsc_sgien_exintfflag *)&rxsc_sgien_exflg;
+		//if(pdrvinfo->BW)	//40M channel
+		if(pDesc->BW)	//40M channel
+			priv->stats.received_bwtype[1+pdrvinfo->rxsc]++;
+		else				//20M channel
+			priv->stats.received_bwtype[0]++;
+	}
+
+	//UI BSS List signal strength(in percentage), make it good looking, from 0~100.
+	//It is assigned to the BSS List in GetValueFromBeaconOrProbeRsp().
+	if(is_cck_rate)
+	{
+		pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)pwdb_all));//PWDB_ALL;//check ok
+
+	}
+	else
+	{
+		//pRfd->Status.SignalStrength = pRecordRfd->Status.SignalStrength = (u8)(SignalScaleMapping(total_rssi/=RF90_PATH_MAX));//(u8)(total_rssi/=RF90_PATH_MAX);
+		// We can judge RX path number now.
+		if (rf_rx_num != 0)
+			pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)(total_rssi/=rf_rx_num)));
+	}
+}/* QueryRxPhyStatus8192S */
+#else
+static void rtl8192_query_rxphystatus(
+	struct r8192_priv * priv,
+	struct ieee80211_rx_stats * pstats,
+	rx_drvinfo_819x_usb  * pdrvinfo,
+	struct ieee80211_rx_stats * precord_stats,
+	bool bpacket_match_bssid,
+	bool bpacket_toself,
+	bool bPacketBeacon,
+	bool bToSelfBA
+	)
+{
+	//PRT_RFD_STATUS		pRtRfdStatus = &(pRfd->Status);
+	phy_sts_ofdm_819xusb_t*	pofdm_buf;
+	phy_sts_cck_819xusb_t	*	pcck_buf;
+	phy_ofdm_rx_status_rxsc_sgien_exintfflag* prxsc;
+	u8				*prxpkt;
+	u8				i, max_spatial_stream, tmp_rxsnr, tmp_rxevm, rxsc_sgien_exflg;
+	char				rx_pwr[4], rx_pwr_all=0;
+	//long				rx_avg_pwr = 0;
+	char				rx_snrX, rx_evmX;
+	u8				evm, pwdb_all;
+	u32				RSSI, total_rssi=0;//, total_evm=0;
+//	long				signal_strength_index = 0;
+	u8				is_cck_rate=0;
+	u8				rf_rx_num = 0;
+
+
+	priv->stats.numqry_phystatus++;
+
+	is_cck_rate = rx_hal_is_cck_rate(pdrvinfo);
+
+	// Record it for next packet processing
+	memset(precord_stats, 0, sizeof(struct ieee80211_rx_stats));
+	pstats->bPacketMatchBSSID = precord_stats->bPacketMatchBSSID = bpacket_match_bssid;
+	pstats->bPacketToSelf = precord_stats->bPacketToSelf = bpacket_toself;
+	pstats->bIsCCK = precord_stats->bIsCCK = is_cck_rate;//RX_HAL_IS_CCK_RATE(pDrvInfo);
+	pstats->bPacketBeacon = precord_stats->bPacketBeacon = bPacketBeacon;
+	pstats->bToSelfBA = precord_stats->bToSelfBA = bToSelfBA;
+
+	prxpkt = (u8*)pdrvinfo;
+
+	/* Move pointer to the 16th bytes. Phy status start address. */
+	prxpkt += sizeof(rx_drvinfo_819x_usb);
+
+	/* Initial the cck and ofdm buffer pointer */
+	pcck_buf = (phy_sts_cck_819xusb_t *)prxpkt;
+	pofdm_buf = (phy_sts_ofdm_819xusb_t *)prxpkt;
+
+	pstats->RxMIMOSignalQuality[0] = -1;
+	pstats->RxMIMOSignalQuality[1] = -1;
+	precord_stats->RxMIMOSignalQuality[0] = -1;
+	precord_stats->RxMIMOSignalQuality[1] = -1;
+
+	if(is_cck_rate)
+	{
+		//
+		// (1)Hardware does not provide RSSI for CCK
+		//
+
+		//
+		// (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
+		//
+		u8 report;//, cck_agc_rpt;
+
+		priv->stats.numqry_phystatusCCK++;
+
+		if(!priv->bCckHighPower)
+		{
+			report = pcck_buf->cck_agc_rpt & 0xc0;
+			report = report>>6;
+			switch(report)
+			{
+				//Fixed by Jacken from Bryant 2008-03-20
+				//Original value is -38 , -26 , -14 , -2
+				//Fixed value is -35 , -23 , -11 , 6
+				case 0x3:
+					rx_pwr_all = -35 - (pcck_buf->cck_agc_rpt & 0x3e);
+					break;
+				case 0x2:
+					rx_pwr_all = -23 - (pcck_buf->cck_agc_rpt & 0x3e);
+					break;
+				case 0x1:
+					rx_pwr_all = -11 - (pcck_buf->cck_agc_rpt & 0x3e);
+					break;
+				case 0x0:
+					rx_pwr_all = 6 - (pcck_buf->cck_agc_rpt & 0x3e);
+					break;
+			}
+		}
+		else
+		{
+			report = pcck_buf->cck_agc_rpt & 0x60;
+			report = report>>5;
+			switch(report)
+			{
+				case 0x3:
+					rx_pwr_all = -35 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
+					break;
+				case 0x2:
+					rx_pwr_all = -23 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1);
+					break;
+				case 0x1:
+					rx_pwr_all = -11 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
+					break;
+				case 0x0:
+					rx_pwr_all = 6 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
+					break;
+			}
+		}
+
+		pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
+		pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
+		pstats->RecvSignalPower = pwdb_all;
+
+		//
+		// (3) Get Signal Quality (EVM)
+		//
+		//if(bpacket_match_bssid)
+		{
+			u8	sq;
+
+			if(pstats->RxPWDBAll > 40)
+			{
+				sq = 100;
+			}else
+			{
+				sq = pcck_buf->sq_rpt;
+
+				if(pcck_buf->sq_rpt > 64)
+					sq = 0;
+				else if (pcck_buf->sq_rpt < 20)
+					sq = 100;
+				else
+					sq = ((64-sq) * 100) / 44;
+			}
+			pstats->SignalQuality = precord_stats->SignalQuality = sq;
+			pstats->RxMIMOSignalQuality[0] = precord_stats->RxMIMOSignalQuality[0] = sq;
+			pstats->RxMIMOSignalQuality[1] = precord_stats->RxMIMOSignalQuality[1] = -1;
+		}
+	}
+	else
+	{
+		priv->stats.numqry_phystatusHT++;
+		//
+		// (1)Get RSSI for HT rate
+		//
+		for(i=RF90_PATH_A; i<priv->NumTotalRFPath; i++)
+		{
+			// 2008/01/30 MH we will judge RF RX path now.
+			if (priv->brfpath_rxenable[i])
+				rf_rx_num++;
+			else
+				continue;
+
+		if (!rtl8192_phy_CheckIsLegalRFPath(priv->ieee80211->dev, i))
+				continue;
+
+			//Fixed by Jacken from Bryant 2008-03-20
+			//Original value is 106
+			rx_pwr[i] = ((pofdm_buf->trsw_gain_X[i]&0x3F)*2) - 106;
+
+			//Get Rx snr value in DB
+			tmp_rxsnr =	pofdm_buf->rxsnr_X[i];
+			rx_snrX = (char)(tmp_rxsnr);
+			//rx_snrX >>= 1;;
+			rx_snrX /= 2;
+			priv->stats.rxSNRdB[i] = (long)rx_snrX;
+
+			/* Translate DBM to percentage. */
+			RSSI = rtl819x_query_rxpwrpercentage(rx_pwr[i]);
+			total_rssi += RSSI;
+
+			/* Record Signal Strength for next packet */
+			//if(bpacket_match_bssid)
+			{
+				pstats->RxMIMOSignalStrength[i] =(u8) RSSI;
+				precord_stats->RxMIMOSignalStrength[i] =(u8) RSSI;
+			}
+		}
+
+
+		//
+		// (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
+		//
+		//Fixed by Jacken from Bryant 2008-03-20
+		//Original value is 106
+		rx_pwr_all = (((pofdm_buf->pwdb_all ) >> 1 )& 0x7f) -106;
+		pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
+
+		pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
+		pstats->RxPower = precord_stats->RxPower =  rx_pwr_all;
+
+		//
+		// (3)EVM of HT rate
+		//
+		if(pdrvinfo->RxHT && pdrvinfo->RxRate>=DESC90_RATEMCS8 &&
+		 	pdrvinfo->RxRate<=DESC90_RATEMCS15)
+			max_spatial_stream = 2; //both spatial stream make sense
+		else
+			max_spatial_stream = 1; //only spatial stream 1 makes sense
+
+		for(i=0; i<max_spatial_stream; i++)
+		{
+			tmp_rxevm =	pofdm_buf->rxevm_X[i];
+			rx_evmX = (char)(tmp_rxevm);
+
+			// Do not use shift operation like "rx_evmX >>= 1" because the compilor of free build environment
+			// fill most significant bit to "zero" when doing shifting operation which may change a negative
+			// value to positive one, then the dbm value (which is supposed to be negative)  is not correct anymore.
+			rx_evmX /= 2;	//dbm
+
+			evm = rtl819x_evm_dbtopercentage(rx_evmX);
+#if 0
+			EVM = SignalScaleMapping(EVM);//make it good looking, from 0~100
+#endif
+			//if(bpacket_match_bssid)
+			{
+				if(i==0) // Fill value in RFD, Get the first spatial stream only
+					pstats->SignalQuality = precord_stats->SignalQuality = (u8)(evm & 0xff);
+				pstats->RxMIMOSignalQuality[i] = precord_stats->RxMIMOSignalQuality[i] = (u8)(evm & 0xff);
+			}
+		}
+
+
+		/* record rx statistics for debug */
+		rxsc_sgien_exflg = pofdm_buf->rxsc_sgien_exflg;
+		prxsc =	(phy_ofdm_rx_status_rxsc_sgien_exintfflag *)&rxsc_sgien_exflg;
+		if(pdrvinfo->BW)	//40M channel
+			priv->stats.received_bwtype[1+prxsc->rxsc]++;
+		else				//20M channel
+			priv->stats.received_bwtype[0]++;
+	}
+
+	//UI BSS List signal strength(in percentage), make it good looking, from 0~100.
+	//It is assigned to the BSS List in GetValueFromBeaconOrProbeRsp().
+	if(is_cck_rate)
+	{
+		pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)pwdb_all));//PWDB_ALL;
+
+	}
+	else
+	{
+		//pRfd->Status.SignalStrength = pRecordRfd->Status.SignalStrength = (u8)(SignalScaleMapping(total_rssi/=RF90_PATH_MAX));//(u8)(total_rssi/=RF90_PATH_MAX);
+		// We can judge RX path number now.
+		if (rf_rx_num != 0)
+			pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)(total_rssi/=rf_rx_num)));
+	}
+}	/* QueryRxPhyStatus8190Pci */
+#endif
+
+void
+rtl8192_record_rxdesc_forlateruse(
+	struct ieee80211_rx_stats *	psrc_stats,
+	struct ieee80211_rx_stats *	ptarget_stats
+)
+{
+	ptarget_stats->bIsAMPDU = psrc_stats->bIsAMPDU;
+	ptarget_stats->bFirstMPDU = psrc_stats->bFirstMPDU;
+	ptarget_stats->Seq_Num = psrc_stats->Seq_Num;
+}
+
+#ifdef RTL8192SU
+static void rtl8192SU_query_rxphystatus(
+	struct r8192_priv * priv,
+	struct ieee80211_rx_stats * pstats,
+	rx_desc_819x_usb	*pDesc,
+	rx_drvinfo_819x_usb  * pdrvinfo,
+	struct ieee80211_rx_stats * precord_stats,
+	bool bpacket_match_bssid,
+	bool bpacket_toself,
+	bool bPacketBeacon,
+	bool bToSelfBA
+	);
+void rtl8192SU_TranslateRxSignalStuff(struct sk_buff *skb,
+				   struct ieee80211_rx_stats * pstats,
+				   rx_desc_819x_usb	*pDesc,
+                                   rx_drvinfo_819x_usb  *pdrvinfo)
+{
+	// TODO: We must only check packet for current MAC address. Not finish
+	rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
+	struct net_device *dev=info->dev;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	bool bpacket_match_bssid, bpacket_toself;
+	bool bPacketBeacon=FALSE, bToSelfBA=FALSE;
+	static struct ieee80211_rx_stats  previous_stats;
+	struct ieee80211_hdr_3addr *hdr;//by amy
+       u16 fc,type;
+
+	// Get Signal Quality for only RX data queue (but not command queue)
+
+	u8* tmp_buf;
+	//u16 tmp_buf_len = 0;
+	u8  *praddr;
+
+	/* Get MAC frame start address. */
+	tmp_buf = (u8*)skb->data;// + get_rxpacket_shiftbytes_819xusb(pstats);
+
+	hdr = (struct ieee80211_hdr_3addr *)tmp_buf;
+	fc = le16_to_cpu(hdr->frame_ctl);
+	type = WLAN_FC_GET_TYPE(fc);
+	praddr = hdr->addr1;
+
+	/* Check if the received packet is acceptabe. */
+	bpacket_match_bssid = ((IEEE80211_FTYPE_CTL != type) &&
+                                			(eqMacAddr(priv->ieee80211->current_network.bssid,  (fc & IEEE80211_FCTL_TODS)? hdr->addr1 : (fc & IEEE80211_FCTL_FROMDS )? hdr->addr2 : hdr->addr3))
+                                				 && (!pstats->bHwError) && (!pstats->bCRC)&& (!pstats->bICV));
+	bpacket_toself =  bpacket_match_bssid & (eqMacAddr(praddr, priv->ieee80211->dev->dev_addr));
+
+#if 1//cosa
+		if(WLAN_FC_GET_FRAMETYPE(fc)== IEEE80211_STYPE_BEACON)
+		{
+			bPacketBeacon = true;
+			//DbgPrint("Beacon 2, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
+		}
+		if(WLAN_FC_GET_FRAMETYPE(fc) == IEEE80211_STYPE_BLOCKACK)
+		{
+			if((eqMacAddr(praddr,dev->dev_addr)))
+				bToSelfBA = true;
+				//DbgPrint("BlockAck, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
+		}
+
+#endif
+
+
+	if(bpacket_match_bssid)
+	{
+		priv->stats.numpacket_matchbssid++;
+	}
+	if(bpacket_toself){
+		priv->stats.numpacket_toself++;
+	}
+	//
+	// Process PHY information for previous packet (RSSI/PWDB/EVM)
+	//
+	// Because phy information is contained in the last packet of AMPDU only, so driver
+	// should process phy information of previous packet
+	rtl8192_process_phyinfo(priv, tmp_buf, &previous_stats, pstats);
+	rtl8192SU_query_rxphystatus(priv, pstats, pDesc, pdrvinfo, &previous_stats, bpacket_match_bssid,bpacket_toself,bPacketBeacon,bToSelfBA);
+	rtl8192_record_rxdesc_forlateruse(pstats, &previous_stats);
+
+}
+#else
+void TranslateRxSignalStuff819xUsb(struct sk_buff *skb,
+				   struct ieee80211_rx_stats * pstats,
+                                   rx_drvinfo_819x_usb  *pdrvinfo)
+{
+	// TODO: We must only check packet for current MAC address. Not finish
+	rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
+	struct net_device *dev=info->dev;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	bool bpacket_match_bssid, bpacket_toself;
+	bool bPacketBeacon=FALSE, bToSelfBA=FALSE;
+	static struct ieee80211_rx_stats  previous_stats;
+	struct ieee80211_hdr_3addr *hdr;//by amy
+       u16 fc,type;
+
+	// Get Signal Quality for only RX data queue (but not command queue)
+
+	u8* tmp_buf;
+	//u16 tmp_buf_len = 0;
+	u8  *praddr;
+
+	/* Get MAC frame start address. */
+	tmp_buf = (u8*)skb->data;// + get_rxpacket_shiftbytes_819xusb(pstats);
+
+	hdr = (struct ieee80211_hdr_3addr *)tmp_buf;
+	fc = le16_to_cpu(hdr->frame_ctl);
+	type = WLAN_FC_GET_TYPE(fc);
+	praddr = hdr->addr1;
+
+	/* Check if the received packet is acceptabe. */
+	bpacket_match_bssid = ((IEEE80211_FTYPE_CTL != type) &&
+                                			(eqMacAddr(priv->ieee80211->current_network.bssid,  (fc & IEEE80211_FCTL_TODS)? hdr->addr1 : (fc & IEEE80211_FCTL_FROMDS )? hdr->addr2 : hdr->addr3))
+                                				 && (!pstats->bHwError) && (!pstats->bCRC)&& (!pstats->bICV));
+	bpacket_toself =  bpacket_match_bssid & (eqMacAddr(praddr, priv->ieee80211->dev->dev_addr));
+
+#if 1//cosa
+		if(WLAN_FC_GET_FRAMETYPE(fc)== IEEE80211_STYPE_BEACON)
+		{
+			bPacketBeacon = true;
+			//DbgPrint("Beacon 2, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
+		}
+		if(WLAN_FC_GET_FRAMETYPE(fc) == IEEE80211_STYPE_BLOCKACK)
+		{
+			if((eqMacAddr(praddr,dev->dev_addr)))
+				bToSelfBA = true;
+				//DbgPrint("BlockAck, MatchBSSID = %d, ToSelf = %d \n", bPacketMatchBSSID, bPacketToSelf);
+		}
+
+#endif
+
+
+	if(bpacket_match_bssid)
+	{
+		priv->stats.numpacket_matchbssid++;
+	}
+	if(bpacket_toself){
+		priv->stats.numpacket_toself++;
+	}
+	//
+	// Process PHY information for previous packet (RSSI/PWDB/EVM)
+	//
+	// Because phy information is contained in the last packet of AMPDU only, so driver
+	// should process phy information of previous packet
+	rtl8192_process_phyinfo(priv, tmp_buf, &previous_stats, pstats);
+	rtl8192_query_rxphystatus(priv, pstats, pdrvinfo, &previous_stats, bpacket_match_bssid,bpacket_toself,bPacketBeacon,bToSelfBA);
+	rtl8192_record_rxdesc_forlateruse(pstats, &previous_stats);
+
+}
+#endif
+
+/**
+* Function:	UpdateReceivedRateHistogramStatistics
+* Overview:	Recored down the received data rate
+*
+* Input:
+* 	struct net_device *dev
+*	struct ieee80211_rx_stats *stats
+*
+* Output:
+*
+*			(priv->stats.ReceivedRateHistogram[] is updated)
+* Return:
+*		None
+*/
+void
+UpdateReceivedRateHistogramStatistics8190(
+	struct net_device *dev,
+	struct ieee80211_rx_stats *stats
+	)
+{
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+    	u32 rcvType=1;   //0: Total, 1:OK, 2:CRC, 3:ICV
+    	u32 rateIndex;
+    	u32 preamble_guardinterval;  //1: short preamble/GI, 0: long preamble/GI
+
+
+    	if(stats->bCRC)
+       	rcvType = 2;
+   	else if(stats->bICV)
+       	rcvType = 3;
+
+   	if(stats->bShortPreamble)
+       	preamble_guardinterval = 1;// short
+    	else
+       	preamble_guardinterval = 0;// long
+
+	switch(stats->rate)
+	{
+		//
+		// CCK rate
+		//
+		case MGN_1M:    rateIndex = 0;  break;
+		case MGN_2M:    rateIndex = 1;  break;
+		case MGN_5_5M:  rateIndex = 2;  break;
+		case MGN_11M:   rateIndex = 3;  break;
+		//
+		// Legacy OFDM rate
+		//
+		case MGN_6M:    rateIndex = 4;  break;
+		case MGN_9M:    rateIndex = 5;  break;
+		case MGN_12M:   rateIndex = 6;  break;
+		case MGN_18M:   rateIndex = 7;  break;
+		case MGN_24M:   rateIndex = 8;  break;
+		case MGN_36M:   rateIndex = 9;  break;
+		case MGN_48M:   rateIndex = 10; break;
+		case MGN_54M:   rateIndex = 11; break;
+		//
+		// 11n High throughput rate
+		//
+		case MGN_MCS0:  rateIndex = 12; break;
+		case MGN_MCS1:  rateIndex = 13; break;
+		case MGN_MCS2:  rateIndex = 14; break;
+		case MGN_MCS3:  rateIndex = 15; break;
+		case MGN_MCS4:  rateIndex = 16; break;
+		case MGN_MCS5:  rateIndex = 17; break;
+		case MGN_MCS6:  rateIndex = 18; break;
+		case MGN_MCS7:  rateIndex = 19; break;
+		case MGN_MCS8:  rateIndex = 20; break;
+		case MGN_MCS9:  rateIndex = 21; break;
+		case MGN_MCS10: rateIndex = 22; break;
+		case MGN_MCS11: rateIndex = 23; break;
+		case MGN_MCS12: rateIndex = 24; break;
+		case MGN_MCS13: rateIndex = 25; break;
+		case MGN_MCS14: rateIndex = 26; break;
+		case MGN_MCS15: rateIndex = 27; break;
+		default:        rateIndex = 28; break;
+	}
+    priv->stats.received_preamble_GI[preamble_guardinterval][rateIndex]++;
+    priv->stats.received_rate_histogram[0][rateIndex]++; //total
+    priv->stats.received_rate_histogram[rcvType][rateIndex]++;
+}
+
+#ifdef RTL8192SU
+void rtl8192SU_query_rxdesc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe)
+{
+	rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
+	struct net_device *dev=info->dev;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	//rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
+	rx_drvinfo_819x_usb  *driver_info = NULL;
+
+	//PRT_RFD_STATUS				pRtRfdStatus = &pRfd->Status;
+	//PHAL_DATA_8192SUSB			pHalData = GET_HAL_DATA(Adapter);
+	//pu1Byte		pDesc = (pu1Byte)pDescIn;
+	//PRX_DRIVER_INFO_8192S		pDrvInfo;
+
+#ifdef USB_RX_AGGREGATION_SUPPORT//FIXLZM
+	//if (bIsRxAggrSubframe)
+		rx_desc_819x_usb_aggr_subframe *desc = (rx_desc_819x_usb_aggr_subframe *)skb->data;
+	else
+#endif
+	rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
+
+	if(0)
+	{
+		int m = 0;
+		printk("========================");
+		for(m=0; m<skb->len; m++){
+			if((m%32) == 0)
+				printk("\n");
+			printk("%2x ",((u8*)skb->data)[m]);
+		}
+		printk("\n========================\n");
+
+	}
+
+
+	//
+	//Get Rx Descriptor Raw Information
+	//
+	stats->Length = desc->Length ;
+	stats->RxDrvInfoSize = desc->RxDrvInfoSize*RX_DRV_INFO_SIZE_UNIT;
+	stats->RxBufShift = (desc->Shift)&0x03;
+	stats->bICV = desc->ICV;
+	stats->bCRC = desc->CRC32;
+	stats->bHwError = stats->bCRC|stats->bICV;
+	stats->Decrypted = !desc->SWDec;//RTL8190 set this bit to indicate that Hw does not decrypt packet
+	stats->bIsAMPDU = (desc->AMSDU==1);
+	stats->bFirstMPDU = (desc->PAGGR==1) && (desc->FAGGR==1);
+	stats->bShortPreamble = desc->SPLCP;
+	stats->RxIs40MHzPacket = (desc->BW==1);
+	stats->TimeStampLow = desc->TSFL;
+
+	if((desc->FAGGR==1) || (desc->PAGGR==1))
+	{// Rx A-MPDU
+		RT_TRACE(COMP_RXDESC, "FirstAGGR = %d, PartAggr = %d\n", desc->FAGGR, desc->PAGGR);
+	}
+//YJ,test,090310
+if(stats->bHwError)
+{
+	if(stats->bICV)
+		printk("%s: Receive ICV error!!!!!!!!!!!!!!!!!!!!!!\n", __FUNCTION__);
+	if(stats->bCRC)
+		printk("%s: Receive CRC error!!!!!!!!!!!!!!!!!!!!!!\n", __FUNCTION__);
+}
+
+	if(IS_UNDER_11N_AES_MODE(priv->ieee80211))
+	{
+		// Always received ICV error packets in AES mode.
+		// This fixed HW later MIC write bug.
+		if(stats->bICV && !stats->bCRC)
+		{
+			stats->bICV = FALSE;
+			stats->bHwError = FALSE;
+		}
+	}
+
+	// Transform HwRate to MRate
+	if(!stats->bHwError)
+		//stats->DataRate = HwRateToMRate(
+		//	(BOOLEAN)GET_RX_DESC_RXHT(pDesc),
+		//	(u1Byte)GET_RX_DESC_RXMCS(pDesc),
+		//	(BOOLEAN)GET_RX_DESC_PAGGR(pDesc));
+		stats->rate = rtl8192SU_HwRateToMRate(desc->RxHT, desc->RxMCS, desc->PAGGR);
+	else
+		stats->rate = MGN_1M;
+
+	//
+	// Collect Rx rate/AMPDU/TSFL
+	//
+	//UpdateRxdRateHistogramStatistics8192S(Adapter, pRfd);
+	//UpdateRxAMPDUHistogramStatistics8192S(Adapter, pRfd);
+	//UpdateRxPktTimeStamp8192S(Adapter, pRfd);
+	UpdateReceivedRateHistogramStatistics8190(dev, stats);
+	//UpdateRxAMPDUHistogramStatistics8192S(dev, stats);	//FIXLZM
+	UpdateRxPktTimeStamp8190(dev, stats);
+
+	//
+	// Get PHY Status and RSVD parts.
+	// <Roger_Notes> It only appears on last aggregated packet.
+	//
+	if (desc->PHYStatus)
+	{
+		//driver_info = (rx_drvinfo_819x_usb *)(skb->data + RX_DESC_SIZE + stats->RxBufShift);
+		driver_info = (rx_drvinfo_819x_usb *)(skb->data + sizeof(rx_desc_819x_usb) + \
+				stats->RxBufShift);
+		if(0)
+		{
+			int m = 0;
+			printk("========================\n");
+			printk("RX_DESC_SIZE:%d, RxBufShift:%d, RxDrvInfoSize:%d\n",
+					RX_DESC_SIZE, stats->RxBufShift, stats->RxDrvInfoSize);
+			for(m=0; m<32; m++){
+			       printk("%2x ",((u8*)driver_info)[m]);
+			}
+			printk("\n========================\n");
+
+		}
+
+	}
+
+	//YJ,add,090107
+	skb_pull(skb, sizeof(rx_desc_819x_usb));
+	//YJ,add,090107,end
+
+	//
+	// Get Total offset of MPDU Frame Body
+	//
+	if((stats->RxBufShift + stats->RxDrvInfoSize) > 0)
+	{
+		stats->bShift = 1;
+		//YJ,add,090107
+		skb_pull(skb, stats->RxBufShift + stats->RxDrvInfoSize);
+		//YJ,add,090107,end
+	}
+
+	//
+	// Get PHY Status and RSVD parts.
+	// <Roger_Notes> It only appears on last aggregated packet.
+	//
+	if (desc->PHYStatus)
+	{
+		rtl8192SU_TranslateRxSignalStuff(skb, stats, desc, driver_info);
+	}
+}
+#else
+void query_rxdesc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats, bool bIsRxAggrSubframe)
+{
+	rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
+	struct net_device *dev=info->dev;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	//rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
+	rx_drvinfo_819x_usb  *driver_info = NULL;
+
+	//
+	//Get Rx Descriptor Information
+	//
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	if (bIsRxAggrSubframe)
+	{
+		rx_desc_819x_usb_aggr_subframe *desc = (rx_desc_819x_usb_aggr_subframe *)skb->data;
+		stats->Length = desc->Length ;
+		stats->RxDrvInfoSize = desc->RxDrvInfoSize;
+		stats->RxBufShift = 0; //RxBufShift = 2 in RxDesc, but usb didn't shift bytes in fact.
+		stats->bICV = desc->ICV;
+		stats->bCRC = desc->CRC32;
+		stats->bHwError = stats->bCRC|stats->bICV;
+		stats->Decrypted = !desc->SWDec;//RTL8190 set this bit to indicate that Hw does not decrypt packet
+	} else
+#endif
+	{
+		rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
+
+		stats->Length = desc->Length;
+		stats->RxDrvInfoSize = desc->RxDrvInfoSize;
+		stats->RxBufShift = 0;//desc->Shift&0x03;
+		stats->bICV = desc->ICV;
+		stats->bCRC = desc->CRC32;
+		stats->bHwError = stats->bCRC|stats->bICV;
+		//RTL8190 set this bit to indicate that Hw does not decrypt packet
+		stats->Decrypted = !desc->SWDec;
+	}
+
+	if((priv->ieee80211->pHTInfo->bCurrentHTSupport == true) && (priv->ieee80211->pairwise_key_type == KEY_TYPE_CCMP))
+	{
+		stats->bHwError = false;
+	}
+	else
+	{
+		stats->bHwError = stats->bCRC|stats->bICV;
+	}
+
+	if(stats->Length < 24 || stats->Length > MAX_8192U_RX_SIZE)
+		stats->bHwError |= 1;
+	//
+	//Get Driver Info
+	//
+	// TODO: Need to verify it on FGPA platform
+	//Driver info are written to the RxBuffer following rx desc
+	if (stats->RxDrvInfoSize != 0) {
+		driver_info = (rx_drvinfo_819x_usb *)(skb->data + sizeof(rx_desc_819x_usb) + \
+				stats->RxBufShift);
+		/* unit: 0.5M */
+		/* TODO */
+		if(!stats->bHwError){
+			u8	ret_rate;
+			ret_rate = HwRateToMRate90(driver_info->RxHT, driver_info->RxRate);
+			if(ret_rate == 0xff)
+			{
+				// Abnormal Case: Receive CRC OK packet with Rx descriptor indicating non supported rate.
+				// Special Error Handling here, 2008.05.16, by Emily
+
+				stats->bHwError = 1;
+				stats->rate = MGN_1M;	//Set 1M rate by default
+			}else
+			{
+				stats->rate = ret_rate;
+			}
+		}
+		else
+			stats->rate = 0x02;
+
+		stats->bShortPreamble = driver_info->SPLCP;
+
+
+		UpdateReceivedRateHistogramStatistics8190(dev, stats);
+
+		stats->bIsAMPDU = (driver_info->PartAggr==1);
+		stats->bFirstMPDU = (driver_info->PartAggr==1) && (driver_info->FirstAGGR==1);
+#if 0
+		// TODO: it is debug only. It should be disabled in released driver. 2007.1.12 by Joseph
+		UpdateRxAMPDUHistogramStatistics8190(Adapter, pRfd);
+#endif
+		stats->TimeStampLow = driver_info->TSFL;
+		// xiong mask it, 070514
+		//pRfd->Status.TimeStampHigh = PlatformEFIORead4Byte(Adapter, TSFR+4);
+		// stats->TimeStampHigh = read_nic_dword(dev,  TSFR+4);
+
+		UpdateRxPktTimeStamp8190(dev, stats);
+
+		//
+		// Rx A-MPDU
+		//
+		if(driver_info->FirstAGGR==1 || driver_info->PartAggr == 1)
+			RT_TRACE(COMP_RXDESC, "driver_info->FirstAGGR = %d, driver_info->PartAggr = %d\n",
+					driver_info->FirstAGGR, driver_info->PartAggr);
+
+	}
+
+	skb_pull(skb,sizeof(rx_desc_819x_usb));
+	//
+	// Get Total offset of MPDU Frame Body
+	//
+	if((stats->RxBufShift + stats->RxDrvInfoSize) > 0) {
+		stats->bShift = 1;
+		skb_pull(skb,stats->RxBufShift + stats->RxDrvInfoSize);
+	}
+
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	/* for the rx aggregated sub frame, the redundant space truelly contained in the packet */
+	if(bIsRxAggrSubframe) {
+		skb_pull(skb, 8);
+	}
+#endif
+	/* for debug 2008.5.29 */
+#if 0
+	{
+		int i;
+		printk("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
+		for(i = 0; i < skb->len; i++) {
+			if(i % 10 == 0) printk("\n");
+			printk("%02x ", skb->data[i]);
+		}
+		printk("\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
+	}
+#endif
+
+	//added by vivi, for MP, 20080108
+	stats->RxIs40MHzPacket = driver_info->BW;
+	if(stats->RxDrvInfoSize != 0)
+		TranslateRxSignalStuff819xUsb(skb, stats, driver_info);
+
+}
+#endif
+
+#ifdef RTL8192SU
+#if 0
+/*-----------------------------------------------------------------------------
+ * Function:	UpdateRxAMPDUHistogramStatistics8192S
+ *
+ * Overview:	Recored down the received A-MPDU aggregation size and pkt number
+ *
+ * Input:       Adapter
+ *
+ * Output:      Adapter
+ *				(Adapter->RxStats.RxAMPDUSizeHistogram[] is updated)
+ *				(Adapter->RxStats.RxAMPDUNumHistogram[] is updated)
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ * When			Who		Remark
+ * 09/18/2008 	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+UpdateRxAMPDUHistogramStatistics8192S(
+	struct net_device *dev,
+	struct ieee80211_rx_stats *stats
+	)
+{
+	//HAL_DATA_TYPE			*pHalData = GET_HAL_DATA(Adapter);
+	u8 	size_index;
+	u8	num_index;
+	u16	update_size = 0;
+	u8	update_num = 0;
+
+	if(stats->bIsAMPDU)
+	{
+		if(stats->bFirstMPDU)
+		{
+			if(stats->nRxAMPDU_Size!=0 && stats->nRxAMPDU_AggrNum!=0)
+			{
+				update_size = stats->nRxAMPDU_Size;
+				update_num = stats->nRxAMPDU_AggrNum;
+			}
+			stats->nRxAMPDU_Size = stats->Length;
+			stats->nRxAMPDU_AggrNum = 1;
+		}
+		else
+		{
+			stats->nRxAMPDU_Size += stats->Length;
+			stats->nRxAMPDU_AggrNum++;
+		}
+	}
+	else
+	{
+		if(stats->nRxAMPDU_Size!=0 && stats->nRxAMPDU_AggrNum!=0)
+		{
+			update_size = stats->nRxAMPDU_Size;
+			update_num = stats->nRxAMPDU_AggrNum;
+		}
+		stats->nRxAMPDU_Size = 0;
+		stats->nRxAMPDU_AggrNum = 0;
+	}
+
+	if(update_size!=0 && update_num!= 0)
+	{
+		if(update_size < 4096)
+			size_index = 0;
+		else if(update_size < 8192)
+			size_index = 1;
+		else if(update_size < 16384)
+			size_index = 2;
+		else if(update_size < 32768)
+			size_index = 3;
+		else if(update_size < 65536)
+			size_index = 4;
+		else
+		{
+			RT_TRACE(COMP_RXDESC,
+			("UpdateRxAMPDUHistogramStatistics8192S(): A-MPDU too large\n");
+		}
+
+		Adapter->RxStats.RxAMPDUSizeHistogram[size_index]++;
+
+		if(update_num < 5)
+			num_index = 0;
+		else if(update_num < 10)
+			num_index = 1;
+		else if(update_num < 20)
+			num_index = 2;
+		else if(update_num < 40)
+			num_index = 3;
+		else
+			num_index = 4;
+
+		Adapter->RxStats.RxAMPDUNumHistogram[num_index]++;
+	}
+}	// UpdateRxAMPDUHistogramStatistics8192S
+#endif
+
+#endif
+
+
+#ifdef RTL8192SU
+//
+// Description:
+// 	The strarting address of wireless lan header will shift 1 or 2 or 3 or "more" bytes for the following reason :
+// 	(1) QoS control : shift 2 bytes
+// 	(2) Mesh Network : shift 1 or 3 bytes
+// 	(3) RxDriverInfo occupies  the front parts of Rx Packets buffer(shift units is in 8Bytes)
+//
+//  	It is because Lextra CPU used by 8186 or 865x series assert exception if the statrting address
+//	of IP header is not double word alignment.
+//	This features is supported in 818xb and 8190 only, but not 818x.
+//
+//	parameter: PRT_RFD, Pointer of Reeceive frame descriptor which is initialized according to
+//					     Rx Descriptor
+//	return value: unsigned int,  number of total shifted bytes
+//
+//	Notes: 2008/06/28, created by Roger
+//
+u32 GetRxPacketShiftBytes8192SU(struct ieee80211_rx_stats  *Status, bool bIsRxAggrSubframe)
+{
+	//PRT_RFD_STATUS	pRtRfdStatus = &pRfd->Status;
+
+	return (sizeof(rx_desc_819x_usb) + Status->RxDrvInfoSize + Status->RxBufShift);
+}
+
+void rtl8192SU_rx_nomal(struct sk_buff* skb)
+{
+	rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
+	struct net_device *dev=info->dev;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct ieee80211_rx_stats stats = {
+		.signal = 0,
+		.noise = -98,
+		.rate = 0,
+		//      .mac_time = jiffies,
+		.freq = IEEE80211_24GHZ_BAND,
+	};
+	u32 rx_pkt_len = 0;
+	struct ieee80211_hdr_1addr *ieee80211_hdr = NULL;
+	bool unicast_packet = false;
+
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	struct sk_buff *agg_skb = NULL;
+	u32  TotalLength = 0;//Total packet length for all aggregated packets.
+	u32  TempDWord = 0;
+	u32  PacketLength = 0;// Per-packet length include size of RxDesc.
+	u32  PacketOccupiedLendth = 0;
+	u8   TempByte = 0;
+	u32  PacketShiftBytes = 0;
+	rx_desc_819x_usb_aggr_subframe *RxDescr = NULL;
+	u8  PaddingBytes = 0;
+	//add just for testing
+	u8   testing;
+
+	u8	TotalAggPkt = 0;
+	PRT_HIGH_THROUGHPUT	pHTInfo =priv-> ieee80211->pHTInfo;
+	u16	RxPageSize = pHTInfo->UsbRxPageSize;
+
+	stats->nTotalAggPkt = 0;
+	//stats->bIsRxAggrSubframe = FALSE;
+
+#endif
+	//printk("**********skb->len = %d\n", skb->len);
+	/* 20 is for ps-poll */
+	if((skb->len >=(20 + sizeof(rx_desc_819x_usb))) && (skb->len < RX_URB_SIZE)) {
+
+		/* first packet should not contain Rx aggregation header */
+		rtl8192SU_query_rxdesc_status(skb, &stats, false);
+		/* TODO */
+
+		/* hardware related info */
+#ifdef USB_RX_AGGREGATION_SUPPORT
+		TotalAggPkt = stats->nTotalAggPkt;
+		PacketLength = stats->Length + GetRxPacketShiftBytes8192SU(&stats, false);
+
+		agg_skb = skb;
+		skb = dev_alloc_skb(PacketLength);
+		memcpy(skb_put(skb,PacketLength),agg_skb->data,PacketLength);
+#endif
+		priv->stats.rxoktotal++;  //YJ,test,090108
+
+		/* Process the MPDU recevied */
+		skb_trim(skb, skb->len - 4/*sCrcLng*/);//FIXLZM
+
+		rx_pkt_len = skb->len;
+		ieee80211_hdr = (struct ieee80211_hdr_1addr *)skb->data;
+		unicast_packet = false;
+		if(is_broadcast_ether_addr(ieee80211_hdr->addr1)) {
+			//TODO
+		}else if(is_multicast_ether_addr(ieee80211_hdr->addr1)){
+			//TODO
+		}else {
+			/* unicast packet */
+			unicast_packet = true;
+		}
+
+		if(!ieee80211_rx(priv->ieee80211,skb, &stats)) {
+			dev_kfree_skb_any(skb);
+		} else {
+		//	priv->stats.rxoktotal++;  //YJ,test,090108
+			if(unicast_packet) {
+				priv->stats.rxbytesunicast += rx_pkt_len;
+			}
+		}
+
+		//up is firs pkt, follow is next and next
+#ifdef USB_RX_AGGREGATION_SUPPORT
+		//
+		// The following operations are for processing Rx aggregated packets.
+		//
+		if(TotalAggPkt>0)
+			TotalAggPkt--;
+
+		while ( TotalAggPkt>0 )
+		{// More aggregated packets need to process.
+
+			u8 tmpCRC = 0, tmpICV = 0;
+
+			//Page size must align to multiple of 128-Bytes.
+			if((PacketLength%RxPageSize) != 0)
+				//PacketLength = ((PacketLength/RxPageSize)+1)*RxPageSize;
+				PacketLength = ((PacketLength>>7)+1)*RxPageSize; // RxPageSize is 128bytes as default.
+
+			// Current total packet occupied length in this buffer.
+			PacketOccupiedLendth += PacketLength;
+
+#if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
+			//if(PacketOccupiedLendth>pContext->BufLenUsed)
+			if(PacketOccupiedLendth>skb->len)
+			{
+				RT_TRACE(COMP_RECV, "(1)HalUsbInMpduComplete8192SUsb(): pRtRfdStatus->Length(%#x)!!\n", stats->Length);
+				RT_TRACE(COMP_RECV, "(1)HalUsbInMpduComplete8192SUsb(): Invalid PacketOccupiedLendth(%#x)!!, BufLenUsed(%#x)\n", PacketOccupiedLendth, stats->BufLenUsed);
+				break;
+			}
+#endif
+
+			skb_pull(agg_skb, PacketLength);
+
+			//
+			// Process the MPDU recevied.
+			//
+			//RT_TRACE(COMP_RECV,"%s:aggred pkt,total_len = %d\n",__FUNCTION__,agg_skb->len);
+			RxDescr = (rx_desc_819x_usb_aggr_subframe *)(agg_skb->data);
+
+#if 0//92SU del
+			tmpCRC = RxDescr->CRC32;
+			tmpICV = RxDescr->ICV;
+			memcpy(agg_skb->data, &agg_skb->data[44], 2);
+			RxDescr->CRC32 = tmpCRC;
+			RxDescr->ICV = tmpICV;
+#endif
+			memset(&stats, 0, sizeof(struct ieee80211_rx_stats));
+			stats.signal = 0;
+			stats.noise = -98;
+			stats.rate = 0;
+			stats.freq = IEEE80211_24GHZ_BAND;
+
+			rtl8192SU_query_rxdesc_status(agg_skb, &stats, true);
+			//PacketLength = stats.Length;
+			PacketLength = stats.Length +  GetRxPacketShiftBytes8192SU(&stats, true);
+
+#if (defined (RTL8192SU_FPGA_2MAC_VERIFICATION)||defined (RTL8192SU_ASIC_VERIFICATION))
+			if((PacketOccupiedLendth+PacketLength)>skb->len)
+			{
+				RT_TRACE(COMP_RECV, "(2)HalUsbInMpduComplete8192SUsb(): Invalid PacketOccupiedLendth(%#x)+PacketLength(%#x)!!, BufLenUsed(%#x)\n",
+					PacketOccupiedLendth, PacketLength, pContext->BufLenUsed);
+				break;
+			}
+#endif
+
+			if(PacketLength > agg_skb->len) {
+				break;
+			}
+
+			/* Process the MPDU recevied */
+			skb = dev_alloc_skb(PacketLength);
+			memcpy(skb_put(skb,PacketLength),agg_skb->data, PacketLength);
+			skb_trim(skb, skb->len - 4/*sCrcLng*/);
+
+			rx_pkt_len = skb->len;
+			ieee80211_hdr = (struct ieee80211_hdr_1addr *)skb->data;
+			unicast_packet = false;
+			if(is_broadcast_ether_addr(ieee80211_hdr->addr1)) {
+				//TODO
+			}else if(is_multicast_ether_addr(ieee80211_hdr->addr1)){
+				//TODO
+			}else {
+				/* unicast packet */
+				unicast_packet = true;
+			}
+			if(!ieee80211_rx(priv->ieee80211,skb, &stats)) {
+				dev_kfree_skb_any(skb);
+			} else {
+				priv->stats.rxoktotal++;
+				if(unicast_packet) {
+					priv->stats.rxbytesunicast += rx_pkt_len;
+				}
+			}
+
+			TotalAggPkt--;
+
+			skb_pull(agg_skb, TempDWord);
+		}
+
+		dev_kfree_skb(agg_skb);
+#endif
+	}
+	else
+	{
+		priv->stats.rxurberr++;
+		printk("actual_length:%d\n", skb->len);
+		dev_kfree_skb_any(skb);
+	}
+
+}
+#else
+u32 GetRxPacketShiftBytes819xUsb(struct ieee80211_rx_stats  *Status, bool bIsRxAggrSubframe)
+{
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	if (bIsRxAggrSubframe)
+		return (sizeof(rx_desc_819x_usb) + Status->RxDrvInfoSize
+			+ Status->RxBufShift + 8);
+	else
+#endif
+		return (sizeof(rx_desc_819x_usb) + Status->RxDrvInfoSize
+				+ Status->RxBufShift);
+}
+
+void rtl8192_rx_nomal(struct sk_buff* skb)
+{
+	rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
+	struct net_device *dev=info->dev;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	struct ieee80211_rx_stats stats = {
+		.signal = 0,
+		.noise = -98,
+		.rate = 0,
+		//      .mac_time = jiffies,
+		.freq = IEEE80211_24GHZ_BAND,
+	};
+	u32 rx_pkt_len = 0;
+	struct ieee80211_hdr_1addr *ieee80211_hdr = NULL;
+	bool unicast_packet = false;
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	struct sk_buff *agg_skb = NULL;
+	u32  TotalLength = 0;
+	u32  TempDWord = 0;
+	u32  PacketLength = 0;
+	u32  PacketOccupiedLendth = 0;
+	u8   TempByte = 0;
+	u32  PacketShiftBytes = 0;
+	rx_desc_819x_usb_aggr_subframe *RxDescr = NULL;
+	u8  PaddingBytes = 0;
+	//add just for testing
+	u8   testing;
+
+#endif
+
+	/* 20 is for ps-poll */
+	if((skb->len >=(20 + sizeof(rx_desc_819x_usb))) && (skb->len < RX_URB_SIZE)) {
+#ifdef USB_RX_AGGREGATION_SUPPORT
+		TempByte = *(skb->data + sizeof(rx_desc_819x_usb));
+#endif
+		/* first packet should not contain Rx aggregation header */
+		query_rxdesc_status(skb, &stats, false);
+		/* TODO */
+		/* hardware related info */
+#ifdef USB_RX_AGGREGATION_SUPPORT
+		if (TempByte & BIT0) {
+			agg_skb = skb;
+			//TotalLength = agg_skb->len - 4; /*sCrcLng*/
+			TotalLength = stats.Length - 4; /*sCrcLng*/
+			//RT_TRACE(COMP_RECV, "%s:first aggregated packet!Length=%d\n",__FUNCTION__,TotalLength);
+			/* though the head pointer has passed this position  */
+			TempDWord = *(u32 *)(agg_skb->data - 4);
+			PacketLength = (u16)(TempDWord & 0x3FFF); /*sCrcLng*/
+			skb = dev_alloc_skb(PacketLength);
+			memcpy(skb_put(skb,PacketLength),agg_skb->data,PacketLength);
+			PacketShiftBytes = GetRxPacketShiftBytes819xUsb(&stats, false);
+		}
+#endif
+		/* Process the MPDU recevied */
+		skb_trim(skb, skb->len - 4/*sCrcLng*/);
+
+		rx_pkt_len = skb->len;
+		ieee80211_hdr = (struct ieee80211_hdr_1addr *)skb->data;
+		unicast_packet = false;
+		if(is_broadcast_ether_addr(ieee80211_hdr->addr1)) {
+			//TODO
+		}else if(is_multicast_ether_addr(ieee80211_hdr->addr1)){
+			//TODO
+		}else {
+			/* unicast packet */
+			unicast_packet = true;
+		}
+
+		if(!ieee80211_rx(priv->ieee80211,skb, &stats)) {
+			dev_kfree_skb_any(skb);
+		} else {
+			priv->stats.rxoktotal++;
+			if(unicast_packet) {
+				priv->stats.rxbytesunicast += rx_pkt_len;
+			}
+		}
+#ifdef USB_RX_AGGREGATION_SUPPORT
+		testing = 1;
+		// (PipeIndex == 0) && (TempByte & BIT0) => TotalLength > 0.
+		if (TotalLength > 0) {
+			PacketOccupiedLendth = PacketLength + (PacketShiftBytes + 8);
+			if ((PacketOccupiedLendth & 0xFF) != 0)
+				PacketOccupiedLendth = (PacketOccupiedLendth & 0xFFFFFF00) + 256;
+			PacketOccupiedLendth -= 8;
+			TempDWord = PacketOccupiedLendth - PacketShiftBytes; /*- PacketLength */
+			if (agg_skb->len > TempDWord)
+				skb_pull(agg_skb, TempDWord);
+			else
+				agg_skb->len = 0;
+
+			while (agg_skb->len>=GetRxPacketShiftBytes819xUsb(&stats, true)) {
+				u8 tmpCRC = 0, tmpICV = 0;
+				//RT_TRACE(COMP_RECV,"%s:aggred pkt,total_len = %d\n",__FUNCTION__,agg_skb->len);
+				RxDescr = (rx_desc_819x_usb_aggr_subframe *)(agg_skb->data);
+				tmpCRC = RxDescr->CRC32;
+				tmpICV = RxDescr->ICV;
+				memcpy(agg_skb->data, &agg_skb->data[44], 2);
+				RxDescr->CRC32 = tmpCRC;
+				RxDescr->ICV = tmpICV;
+
+				memset(&stats, 0, sizeof(struct ieee80211_rx_stats));
+				stats.signal = 0;
+				stats.noise = -98;
+				stats.rate = 0;
+				stats.freq = IEEE80211_24GHZ_BAND;
+				query_rxdesc_status(agg_skb, &stats, true);
+				PacketLength = stats.Length;
+
+				if(PacketLength > agg_skb->len) {
+					break;
+				}
+				/* Process the MPDU recevied */
+				skb = dev_alloc_skb(PacketLength);
+				memcpy(skb_put(skb,PacketLength),agg_skb->data, PacketLength);
+				skb_trim(skb, skb->len - 4/*sCrcLng*/);
+
+				rx_pkt_len = skb->len;
+				ieee80211_hdr = (struct ieee80211_hdr_1addr *)skb->data;
+				unicast_packet = false;
+				if(is_broadcast_ether_addr(ieee80211_hdr->addr1)) {
+					//TODO
+				}else if(is_multicast_ether_addr(ieee80211_hdr->addr1)){
+					//TODO
+				}else {
+					/* unicast packet */
+					unicast_packet = true;
+				}
+				if(!ieee80211_rx(priv->ieee80211,skb, &stats)) {
+					dev_kfree_skb_any(skb);
+				} else {
+					priv->stats.rxoktotal++;
+					if(unicast_packet) {
+						priv->stats.rxbytesunicast += rx_pkt_len;
+					}
+				}
+				/* should trim the packet which has been copied to target skb */
+				skb_pull(agg_skb, PacketLength);
+				PacketShiftBytes = GetRxPacketShiftBytes819xUsb(&stats, true);
+				PacketOccupiedLendth = PacketLength + PacketShiftBytes;
+				if ((PacketOccupiedLendth & 0xFF) != 0) {
+					PaddingBytes = 256 - (PacketOccupiedLendth & 0xFF);
+					if (agg_skb->len > PaddingBytes)
+						skb_pull(agg_skb, PaddingBytes);
+					else
+						agg_skb->len = 0;
+				}
+			}
+			dev_kfree_skb(agg_skb);
+		}
+#endif
+	} else {
+		priv->stats.rxurberr++;
+		printk("actual_length:%d\n", skb->len);
+		dev_kfree_skb_any(skb);
+	}
+
+}
+
+#endif
+
+void
+rtl819xusb_process_received_packet(
+	struct net_device *dev,
+	struct ieee80211_rx_stats *pstats
+	)
+{
+//	bool bfreerfd=false, bqueued=false;
+	u8* 	frame;
+	u16     frame_len=0;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+//	u8			index = 0;
+//	u8			TID = 0;
+	//u16			seqnum = 0;
+	//PRX_TS_RECORD	pts = NULL;
+
+	// Get shifted bytes of Starting address of 802.11 header. 2006.09.28, by Emily
+	//porting by amy 080508
+	pstats->virtual_address += get_rxpacket_shiftbytes_819xusb(pstats);
+	frame = pstats->virtual_address;
+	frame_len = pstats->packetlength;
+#ifdef TODO	// by amy about HCT
+	if(!Adapter->bInHctTest)
+		CountRxErrStatistics(Adapter, pRfd);
+#endif
+	{
+	#ifdef ENABLE_PS  //by amy for adding ps function in future
+		RT_RF_POWER_STATE rtState;
+		// When RF is off, we should not count the packet for hw/sw synchronize
+		// reason, ie. there may be a duration while sw switch is changed and hw
+		// switch is being changed. 2006.12.04, by shien chang.
+		Adapter->HalFunc.GetHwRegHandler(Adapter, HW_VAR_RF_STATE, (u8* )(&rtState));
+		if (rtState == eRfOff)
+		{
+			return;
+		}
+	#endif
+	priv->stats.rxframgment++;
+
+	}
+#ifdef TODO
+	RmMonitorSignalStrength(Adapter, pRfd);
+#endif
+	/* 2007/01/16 MH Add RX command packet handle here. */
+	/* 2007/03/01 MH We have to release RFD and return if rx pkt is cmd pkt. */
+	if (rtl819xusb_rx_command_packet(dev, pstats))
+	{
+		return;
+	}
+
+#ifdef SW_CRC_CHECK
+	SwCrcCheck();
+#endif
+
+
+}
+
+void query_rx_cmdpkt_desc_status(struct sk_buff *skb, struct ieee80211_rx_stats *stats)
+{
+//	rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
+//	struct net_device *dev=info->dev;
+//	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	rx_desc_819x_usb *desc = (rx_desc_819x_usb *)skb->data;
+//	rx_drvinfo_819x_usb  *driver_info;
+
+	//
+	//Get Rx Descriptor Information
+	//
+	stats->virtual_address = (u8*)skb->data;
+	stats->Length = desc->Length;
+	stats->RxDrvInfoSize = 0;
+	stats->RxBufShift = 0;
+	stats->packetlength = stats->Length-scrclng;
+	stats->fraglength = stats->packetlength;
+	stats->fragoffset = 0;
+	stats->ntotalfrag = 1;
+}
+
+#ifdef RTL8192SU
+void rtl8192SU_rx_cmd(struct sk_buff *skb)
+{
+	struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
+	struct net_device *dev = info->dev;
+
+	/* TODO */
+	struct ieee80211_rx_stats stats = {
+		.signal = 0,
+		.noise = -98,
+		.rate = 0,
+		//      .mac_time = jiffies,
+		.freq = IEEE80211_24GHZ_BAND,
+	};
+
+	//
+	// Check buffer length to determine if this is a valid MPDU.
+	//
+	if( (skb->len >= sizeof(rx_desc_819x_usb)) && (skb->len <= RX_URB_SIZE) )//&&
+		//(pHalData->SwChnlInProgress == FALSE))
+	{
+		//
+		// Collection information in Rx descriptor.
+		//
+#if 0
+		pRxDesc = pContext->Buffer;
+
+		pRfd->Buffer.VirtualAddress = pContext->Buffer; // 061109, rcnjko, for multi-platform consideration..
+
+		pRtRfdStatus->Length = (u2Byte)GET_RX_DESC_PKT_LEN(pRxDesc);
+		pRtRfdStatus->RxDrvInfoSize = 0;
+		pRtRfdStatus->RxBufShift = 0;
+
+		pRfd->PacketLength	= pRfd->Status.Length - sCrcLng;
+		pRfd->FragLength	= pRfd->PacketLength;
+		pRfd->FragOffset	= 0;
+		pRfd->nTotalFrag	= 1;
+		pRfd->queue_id = PipeIndex;
+#endif
+		query_rx_cmdpkt_desc_status(skb,&stats);
+		// this is to be done by amy 080508     prfd->queue_id = 1;
+
+		//
+		// Process the MPDU recevied.
+		//
+		rtl819xusb_process_received_packet(dev,&stats);
+
+		dev_kfree_skb_any(skb);
+	}
+	else
+	{
+		//RTInsertTailListWithCnt(&pAdapter->RfdIdleQueue, &pRfd->List, &pAdapter->NumIdleRfd);
+		//RT_ASSERT(pAdapter->NumIdleRfd <= pAdapter->NumRfd, ("HalUsbInCommandComplete8192SUsb(): Adapter->NumIdleRfd(%d)\n", pAdapter->NumIdleRfd));
+		//RT_TRACE(COMP_RECV, DBG_LOUD, ("HalUsbInCommandComplete8192SUsb(): NOT enough Resources!! BufLenUsed(%d), NumIdleRfd(%d)\n",
+			//pContext->BufLenUsed, pAdapter->NumIdleRfd));
+	}
+
+	//
+	// Reuse USB_IN_CONTEXT since we had finished processing the
+	// buffer in USB_IN_CONTEXT.
+	//
+	//HalUsbReturnInContext(pAdapter, pContext);
+
+	//
+	// Issue another bulk IN transfer.
+	//
+	//HalUsbInMpdu(pAdapter, PipeIndex);
+
+	RT_TRACE(COMP_RECV, "<--- HalUsbInCommandComplete8192SUsb()\n");
+
+}
+#else
+void rtl8192_rx_cmd(struct sk_buff *skb)
+{
+	struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
+	struct net_device *dev = info->dev;
+	//int ret;
+//	struct urb *rx_urb = info->urb;
+	/* TODO */
+	struct ieee80211_rx_stats stats = {
+		.signal = 0,
+		.noise = -98,
+		.rate = 0,
+		//      .mac_time = jiffies,
+		.freq = IEEE80211_24GHZ_BAND,
+	};
+
+	if((skb->len >=(20 + sizeof(rx_desc_819x_usb))) && (skb->len < RX_URB_SIZE))
+	{
+
+		query_rx_cmdpkt_desc_status(skb,&stats);
+		// this is to be done by amy 080508     prfd->queue_id = 1;
+
+
+		//
+		//  Process the command packet received.
+		//
+
+		rtl819xusb_process_received_packet(dev,&stats);
+
+		dev_kfree_skb_any(skb);
+	}
+	else
+		;
+
+
+#if 0
+	desc = (u32*)(skb->data);
+	cmd = (desc[0] >> 30) & 0x03;
+
+	if(cmd == 0x00) {//beacon interrupt
+		//send beacon packet
+		skb = ieee80211_get_beacon(priv->ieee80211);
+
+		if(!skb){
+			DMESG("not enought memory for allocating beacon");
+			return;
+		}
+		skb->cb[0] = BEACON_PRIORITY;
+		skb->cb[1] = 0;
+		skb->cb[2] = ieeerate2rtlrate(priv->ieee80211->basic_rate);
+		ret = rtl8192_tx(dev, skb);
+
+		if( ret != 0 ){
+			printk(KERN_ALERT "tx beacon packet error : %d !\n", ret);
+		}
+		dev_kfree_skb_any(skb);
+	} else {//0x00
+		//{ log the device information
+		// At present, It is not implemented just now.
+		//}
+	}
+#endif
+}
+#endif
+
+void rtl8192_irq_rx_tasklet(struct r8192_priv *priv)
+{
+        struct sk_buff *skb;
+	struct rtl8192_rx_info *info;
+
+        while (NULL != (skb = skb_dequeue(&priv->skb_queue))) {
+		info = (struct rtl8192_rx_info *)skb->cb;
+                switch (info->out_pipe) {
+		/* Nomal packet pipe */
+			case 3:
+				//RT_TRACE(COMP_RECV, "normal in-pipe index(%d)\n",info->out_pipe);
+				priv->IrpPendingCount--;
+				priv->ops->rtl819x_rx_nomal(skb);
+				break;
+
+				/* Command packet pipe */
+			case 9:
+				RT_TRACE(COMP_RECV, "command in-pipe index(%d)\n",\
+						info->out_pipe);
+				priv->ops->rtl819x_rx_cmd(skb);
+				break;
+
+			default: /* should never get here! */
+				RT_TRACE(COMP_ERR, "Unknown in-pipe index(%d)\n",\
+						info->out_pipe);
+				dev_kfree_skb(skb);
+				break;
+
+		}
+        }
+}
+
+
+
+/****************************************************************************
+     ---------------------------- USB_STUFF---------------------------
+*****************************************************************************/
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+//LZM Merge from windows HalUsbSetQueuePipeMapping8192SUsb 090319
+static void HalUsbSetQueuePipeMapping8192SUsb(struct usb_interface *intf, struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct usb_host_interface *iface_desc;
+	struct usb_endpoint_descriptor *endpoint;
+	u8 i = 0;
+
+	priv->ep_in_num = 0;
+	priv->ep_out_num = 0;
+	memset(priv->RtOutPipes,0,16);
+	memset(priv->RtInPipes,0,16);
+
+#ifndef USE_ONE_PIPE
+	iface_desc = intf->cur_altsetting;
+	priv->ep_num = iface_desc->desc.bNumEndpoints;
+
+	for (i = 0; i < priv->ep_num; ++i) {
+		endpoint = &iface_desc->endpoint[i].desc;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,23)
+		if (usb_endpoint_is_bulk_in(endpoint)) {
+			priv->RtInPipes[priv->ep_in_num] = usb_endpoint_num(endpoint);
+			priv->ep_in_num ++;
+			//printk("in_endpoint_idx = %d\n", usb_endpoint_num(endpoint));
+		} else if (usb_endpoint_is_bulk_out(endpoint)) {
+			priv->RtOutPipes[priv->ep_out_num] = usb_endpoint_num(endpoint);
+			priv->ep_out_num ++;
+			//printk("out_endpoint_idx = %d\n", usb_endpoint_num(endpoint));
+		}
+#else
+		if ((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK) &&
+		     ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)) {
+			/* we found a bulk in endpoint */
+			priv->RtInPipes[priv->ep_in_num] = (endpoint->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
+			priv->ep_in_num ++;
+		} else if (((endpoint->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) &&
+		     ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)) {
+			/* We found bulk out endpoint */
+			priv->RtOutPipes[priv->ep_out_num] = endpoint->bEndpointAddress;
+			priv->ep_out_num ++;
+			}
+#endif
+	}
+	{
+		memset(priv->txqueue_to_outpipemap,0,9);
+		if (priv->ep_num == 6) {
+			// BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
+			u8 queuetopipe[] = {3, 2, 1, 0, 4, 4, 4, 4, 4};
+
+			memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
+		} else if (priv->ep_num == 4) {
+			// BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
+			u8 queuetopipe[] = {1, 1, 0, 0, 2, 2, 2, 2, 2};
+
+			memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
+		} else if (priv->ep_num > 9) {
+			// BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
+			u8 queuetopipe[] = {3, 2, 1, 0, 4, 8, 7, 6, 5};
+
+			memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
+		} else {//use sigle pipe
+			// BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON
+			u8 queuetopipe[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
+			memcpy(priv->txqueue_to_outpipemap,queuetopipe,9);
+		}
+	}
+	printk("==>ep_num:%d, in_ep_num:%d, out_ep_num:%d\n", priv->ep_num, priv->ep_in_num, priv->ep_out_num);
+
+	printk("==>RtInPipes:");
+	for(i=0; i < priv->ep_in_num; i++)
+		printk("%d  ", priv->RtInPipes[i]);
+	printk("\n");
+
+	printk("==>RtOutPipes:");
+	for(i=0; i < priv->ep_out_num; i++)
+		printk("%d  ", priv->RtOutPipes[i]);
+	printk("\n");
+
+	printk("==>txqueue_to_outpipemap for BK, BE, VI, VO, HCCA, TXCMD, MGNT, HIGH, BEACON:\n");
+	for(i=0; i < 9; i++)
+		printk("%d  ", priv->txqueue_to_outpipemap[i]);
+	printk("\n");
+#else
+	{
+		memset(priv->txqueue_to_outpipemap,0,9);
+		memset(priv->RtOutPipes,4,16);//all use endpoint 4 for out
+	}
+#endif
+
+	return;
+}
+#endif
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+static int __devinit rtl8192_usb_probe(struct usb_interface *intf,
+			 const struct usb_device_id *id)
+#else
+static void * __devinit rtl8192_usb_probe(struct usb_device *udev,
+			                unsigned int ifnum,
+			          const struct usb_device_id *id)
+#endif
+{
+//	unsigned long ioaddr = 0;
+	struct net_device *dev = NULL;
+	struct r8192_priv *priv= NULL;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	struct usb_device *udev = interface_to_usbdev(intf);
+#endif
+        RT_TRACE(COMP_INIT, "Oops: i'm coming\n");
+
+	dev = alloc_ieee80211(sizeof(struct r8192_priv));
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24)
+	SET_MODULE_OWNER(dev);
+#endif
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	usb_set_intfdata(intf, dev);
+	SET_NETDEV_DEV(dev, &intf->dev);
+#endif
+	priv = ieee80211_priv(dev);
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	priv->ieee80211 = netdev_priv(dev);
+#else
+	priv->ieee80211 = (struct net_device *)dev->priv;
+#endif
+	priv->udev=udev;
+
+#ifdef RTL8192SU
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	HalUsbSetQueuePipeMapping8192SUsb(intf, dev);
+#else//use one pipe
+	{
+		memset(priv->txqueue_to_outpipemap,0,9);
+		memset(priv->RtOutPipes,4,16);//all use endpoint 4 for out
+	}
+#endif
+#endif
+
+#ifdef RTL8192SU
+	//printk("===============>NIC 8192SU\n");
+	priv->ops = &rtl8192su_ops;
+#else
+	//printk("===============>NIC 8192U\n");
+	priv->ops = &rtl8192u_ops;
+#endif
+
+	dev->open = rtl8192_open;
+	dev->stop = rtl8192_close;
+	//dev->hard_start_xmit = rtl8192_8023_hard_start_xmit;
+	dev->tx_timeout = tx_timeout;
+	//dev->wireless_handlers = &r8192_wx_handlers_def;
+	dev->do_ioctl = rtl8192_ioctl;
+	dev->set_multicast_list = r8192_set_multicast;
+	dev->set_mac_address = r8192_set_mac_adr;
+	dev->get_stats = rtl8192_stats;
+
+         //DMESG("Oops: i'm coming\n");
+#if WIRELESS_EXT >= 12
+#if WIRELESS_EXT < 17
+        dev->get_wireless_stats = r8192_get_wireless_stats;
+#endif
+        dev->wireless_handlers = (struct iw_handler_def *) &r8192_wx_handlers_def;
+#endif
+	dev->type=ARPHRD_ETHER;
+
+	dev->watchdog_timeo = HZ*3;	//modified by john, 0805
+
+	if (dev_alloc_name(dev, ifname) < 0){
+                RT_TRACE(COMP_INIT, "Oops: devname already taken! Trying wlan%%d...\n");
+		ifname = "wlan%d";
+		dev_alloc_name(dev, ifname);
+        }
+
+	RT_TRACE(COMP_INIT, "Driver probe completed1\n");
+#if 1
+	if(rtl8192_init(dev)!=0){
+		RT_TRACE(COMP_ERR, "Initialization failed");
+		goto fail;
+	}
+#endif
+	netif_carrier_off(dev);
+	netif_stop_queue(dev);
+
+	register_netdev(dev);
+	RT_TRACE(COMP_INIT, "dev name=======> %s\n",dev->name);
+	rtl8192_proc_init_one(dev);
+
+
+	RT_TRACE(COMP_INIT, "Driver probe completed\n");
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+	return dev;
+#else
+	return 0;
+#endif
+
+
+fail:
+	free_ieee80211(dev);
+
+	RT_TRACE(COMP_ERR, "wlan driver load failed\n");
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+	return NULL;
+#else
+	return -ENODEV;
+#endif
+
+}
+
+//detach all the work and timer structure declared or inititialize in r8192U_init function.
+void rtl8192_cancel_deferred_work(struct r8192_priv* priv)
+{
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
+	cancel_work_sync(&priv->reset_wq);
+	cancel_work_sync(&priv->qos_activate);
+	cancel_delayed_work(&priv->watch_dog_wq);
+	cancel_delayed_work(&priv->update_beacon_wq);
+	cancel_delayed_work(&priv->ieee80211->hw_wakeup_wq);
+	cancel_delayed_work(&priv->ieee80211->hw_sleep_wq);
+	//cancel_work_sync(&priv->SetBWModeWorkItem);
+	//cancel_work_sync(&priv->SwChnlWorkItem);
+#else
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	cancel_delayed_work(&priv->reset_wq);
+	cancel_delayed_work(&priv->qos_activate);
+	cancel_delayed_work(&priv->watch_dog_wq);
+	cancel_delayed_work(&priv->update_beacon_wq);
+	cancel_delayed_work(&priv->ieee80211->hw_wakeup_wq);
+	cancel_delayed_work(&priv->ieee80211->hw_sleep_wq);
+
+	//cancel_delayed_work(&priv->SetBWModeWorkItem);
+	//cancel_delayed_work(&priv->SwChnlWorkItem);
+#endif
+#endif
+
+}
+
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+static void __devexit rtl8192_usb_disconnect(struct usb_interface *intf)
+#else
+static void __devexit rtl8192_usb_disconnect(struct usb_device *udev, void *ptr)
+#endif
+{
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	struct net_device *dev = usb_get_intfdata(intf);
+#else
+	struct net_device *dev = (struct net_device *)ptr;
+#endif
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+ 	if(dev){
+
+		unregister_netdev(dev);
+
+		RT_TRACE(COMP_DOWN, "=============>wlan driver to be removed\n");
+		rtl8192_proc_remove_one(dev);
+
+			rtl8192_down(dev);
+		if (priv->pFirmware)
+		{
+			vfree(priv->pFirmware);
+			priv->pFirmware = NULL;
+		}
+	//	priv->rf_close(dev);
+//		rtl8192_SetRFPowerState(dev, eRfOff);
+#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
+		destroy_workqueue(priv->priv_wq);
+#endif
+		//rtl8192_irq_disable(dev);
+		//rtl8192_reset(dev);
+		mdelay(10);
+
+	}
+	free_ieee80211(dev);
+	RT_TRACE(COMP_DOWN, "wlan driver removed\n");
+}
+
+static int __init rtl8192_usb_module_init(void)
+{
+	printk(KERN_INFO "\nLinux kernel driver for RTL8192 based WLAN cards\n");
+	printk(KERN_INFO "Copyright (c) 2007-2008, Realsil Wlan\n");
+	RT_TRACE(COMP_INIT, "Initializing module");
+	RT_TRACE(COMP_INIT, "Wireless extensions version %d", WIRELESS_EXT);
+	rtl8192_proc_module_init();
+	return usb_register(&rtl8192_usb_driver);
+}
+
+
+static void __exit rtl8192_usb_module_exit(void)
+{
+	usb_deregister(&rtl8192_usb_driver);
+
+	RT_TRACE(COMP_DOWN, "Exiting");
+	rtl8192_proc_module_remove();
+}
+
+
+void rtl8192_try_wake_queue(struct net_device *dev, int pri)
+{
+	unsigned long flags;
+	short enough_desc;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+
+	spin_lock_irqsave(&priv->tx_lock,flags);
+	enough_desc = check_nic_enough_desc(dev,pri);
+        spin_unlock_irqrestore(&priv->tx_lock,flags);
+
+	if(enough_desc)
+		ieee80211_wake_queue(priv->ieee80211);
+}
+
+#if 0
+void DisableHWSecurityConfig8192SUsb(struct net_device *dev)
+{
+	u8 SECR_value = 0x0;
+	write_nic_byte(dev, SECR,  SECR_value);//SECR_value |  SCR_UseDK );
+}
+#endif
+
+void EnableHWSecurityConfig8192(struct net_device *dev)
+{
+        u8 SECR_value = 0x0;
+	struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
+	 struct ieee80211_device* ieee = priv->ieee80211;
+
+	SECR_value = SCR_TxEncEnable | SCR_RxDecEnable;
+#if 1
+	if (((KEY_TYPE_WEP40 == ieee->pairwise_key_type) || (KEY_TYPE_WEP104 == ieee->pairwise_key_type)) && (priv->ieee80211->auth_mode != 2))
+	{
+		SECR_value |= SCR_RxUseDK;
+		SECR_value |= SCR_TxUseDK;
+	}
+	else if ((ieee->iw_mode == IW_MODE_ADHOC) && (ieee->pairwise_key_type & (KEY_TYPE_CCMP | KEY_TYPE_TKIP)))
+	{
+		SECR_value |= SCR_RxUseDK;
+		SECR_value |= SCR_TxUseDK;
+	}
+#endif
+        //add HWSec active enable here.
+//default using hwsec. when peer AP is in N mode only and pairwise_key_type is none_aes(which HT_IOT_ACT_PURE_N_MODE indicates it), use software security. when peer AP is in b,g,n mode mixed and pairwise_key_type is none_aes, use g mode hw security. WB on 2008.7.4
+
+	ieee->hwsec_active = 1;
+
+	if ((ieee->pHTInfo->IOTAction&HT_IOT_ACT_PURE_N_MODE) || !hwwep)//!ieee->hwsec_support) //add hwsec_support flag to totol control hw_sec on/off
+	{
+		ieee->hwsec_active = 0;
+		SECR_value &= ~SCR_RxDecEnable;
+	}
+
+	RT_TRACE(COMP_SEC,"%s:, hwsec:%d, pairwise_key:%d, SECR_value:%x\n", __FUNCTION__, \
+			ieee->hwsec_active, ieee->pairwise_key_type, SECR_value);
+	{
+                write_nic_byte(dev, SECR,  SECR_value);//SECR_value |  SCR_UseDK );
+        }
+}
+
+
+void setKey(	struct net_device *dev,
+		u8 EntryNo,
+		u8 KeyIndex,
+		u16 KeyType,
+		u8 *MacAddr,
+		u8 DefaultKey,
+		u32 *KeyContent )
+{
+	u32 TargetCommand = 0;
+	u32 TargetContent = 0;
+	u16 usConfig = 0;
+	u8 i;
+	if (EntryNo >= TOTAL_CAM_ENTRY)
+		RT_TRACE(COMP_ERR, "cam entry exceeds in setKey()\n");
+
+	RT_TRACE(COMP_SEC, "====>to setKey(), dev:%p, EntryNo:%d, KeyIndex:%d, KeyType:%d, MacAddr"MAC_FMT"\n", dev,EntryNo, KeyIndex, KeyType, MAC_ARG(MacAddr));
+
+	if (DefaultKey)
+		usConfig |= BIT15 | (KeyType<<2);
+	else
+		usConfig |= BIT15 | (KeyType<<2) | KeyIndex;
+//	usConfig |= BIT15 | (KeyType<<2) | (DefaultKey<<5) | KeyIndex;
+
+
+	for(i=0 ; i<CAM_CONTENT_COUNT; i++){
+		TargetCommand  = i+CAM_CONTENT_COUNT*EntryNo;
+		TargetCommand |= BIT31|BIT16;
+
+		if(i==0){//MAC|Config
+			TargetContent = (u32)(*(MacAddr+0)) << 16|
+					(u32)(*(MacAddr+1)) << 24|
+					(u32)usConfig;
+
+			write_nic_dword(dev, WCAMI, TargetContent);
+			write_nic_dword(dev, RWCAM, TargetCommand);
+	//		printk("setkey cam =%8x\n", read_cam(dev, i+6*EntryNo));
+		}
+		else if(i==1){//MAC
+                        TargetContent = (u32)(*(MacAddr+2)) 	 |
+                                        (u32)(*(MacAddr+3)) <<  8|
+                                        (u32)(*(MacAddr+4)) << 16|
+                                        (u32)(*(MacAddr+5)) << 24;
+			write_nic_dword(dev, WCAMI, TargetContent);
+			write_nic_dword(dev, RWCAM, TargetCommand);
+		}
+		else {
+			//Key Material
+			if(KeyContent !=NULL){
+			write_nic_dword(dev, WCAMI, (u32)(*(KeyContent+i-2)) );
+			write_nic_dword(dev, RWCAM, TargetCommand);
+		}
+	}
+	}
+
+}
+
+/***************************************************************************
+     ------------------- module init / exit stubs ----------------
+****************************************************************************/
+module_init(rtl8192_usb_module_init);
+module_exit(rtl8192_usb_module_exit);
diff --git a/drivers/staging/rtl8192su/r8192U_dm.c b/drivers/staging/rtl8192su/r8192U_dm.c
new file mode 100644
index 0000000..304274b
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192U_dm.c
@@ -0,0 +1,4521 @@
+/*++
+Copyright-c Realtek Semiconductor Corp. All rights reserved.
+
+Module Name:
+	r8192U_dm.c
+
+Abstract:
+	HW dynamic mechanism.
+
+Major Change History:
+	When      	Who				What
+	----------	--------------- -------------------------------
+	2008-05-14	amy                     create version 0 porting from windows code.
+
+--*/
+
+
+#ifdef RTL8192SU
+#include "r8192U.h"
+#include "r8192U_dm.h"
+//#include "r8190_rtl8256.h"
+#include "r819xU_cmdpkt.h"
+#include "r8192S_hw.h"
+#include "r8192S_phy.h"
+#include "r8192S_phyreg.h"
+#else
+#include "r8192U.h"
+#include "r8192U_dm.h"
+#include "r8192U_hw.h"
+#include "r819xU_phy.h"
+#include "r819xU_phyreg.h"
+#include "r8190_rtl8256.h"
+#include "r819xU_cmdpkt.h"
+#endif
+
+/*---------------------------Define Local Constant---------------------------*/
+//
+// Indicate different AP vendor for IOT issue.
+//
+#if 0
+typedef enum _HT_IOT_PEER
+{
+	HT_IOT_PEER_UNKNOWN = 0,
+	HT_IOT_PEER_REALTEK = 1,
+	HT_IOT_PEER_BROADCOM = 2,
+	HT_IOT_PEER_RALINK = 3,
+	HT_IOT_PEER_ATHEROS = 4,
+	HT_IOT_PEER_CISCO = 5,
+	HT_IOT_PEER_MAX = 6
+}HT_IOT_PEER_E, *PHTIOT_PEER_E;
+#endif
+#if 1
+#ifdef RTL8192SU
+		static u32 edca_setting_DL[HT_IOT_PEER_MAX] =
+		// UNKNOWN	REALTEK_90	/*REALTEK_92SE*/	BROADCOM	RALINK		ATHEROS		CISCO		MARVELL		92U_AP		SELF_AP
+		   { 0xa44f, 	0x5ea44f, 	0x5ea44f,		0xa44f,		0xa44f, 		0xa44f, 		0xa630,		0xa42b,		0x5e4322,	0x5e4322};
+		static u32 edca_setting_UL[HT_IOT_PEER_MAX] =
+		// UNKNOWN	REALTEK		/*REALTEK_92SE*/	BROADCOM	RALINK		ATHEROS		CISCO		MARVELL		92U_AP		SELF_AP
+		   { 0x5ea44f, 	0xa44f, 	0x5ea44f,		0x5e4322, 	0x5ea422, 	0x5e4322, 	0x3ea44f,	0x5ea42b,	0x5e4322,	0x5e4322};
+
+#else
+
+static u32 edca_setting_DL[HT_IOT_PEER_MAX] =
+		{ 0x5e4322, 	0x5e4322, 	0x5ea44f,		0x5e4322, 	0x604322, 	0xa44f, 	0x5ea44f};
+static u32 edca_setting_UL[HT_IOT_PEER_MAX] =
+		{ 0x5e4322, 	0xa44f, 	0x5ea44f,	        0x5e4322, 	0x604322, 	0x5ea44f, 	0x5ea44f};
+
+#endif
+#endif
+
+#define RTK_UL_EDCA 0xa44f
+#define RTK_DL_EDCA 0x5e4322
+/*---------------------------Define Local Constant---------------------------*/
+
+
+/*------------------------Define global variable-----------------------------*/
+// Debug variable ?
+dig_t	dm_digtable;
+// Store current shoftware write register content for MAC PHY.
+u8		dm_shadow[16][256] = {{0}};
+// For Dynamic Rx Path Selection by Signal Strength
+DRxPathSel	DM_RxPathSelTable;
+/*------------------------Define global variable-----------------------------*/
+
+
+/*------------------------Define local variable------------------------------*/
+/*------------------------Define local variable------------------------------*/
+
+
+/*--------------------Define export function prototype-----------------------*/
+#ifdef TO_DO_LIST
+static	void dm_CheckProtection(struct net_device *dev);
+#endif
+extern	void	init_hal_dm(struct net_device *dev);
+extern	void deinit_hal_dm(struct net_device *dev);
+
+extern void hal_dm_watchdog(struct net_device *dev);
+
+
+extern	void	init_rate_adaptive(struct net_device *dev);
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern	void	dm_txpower_trackingcallback(struct work_struct *work);
+#else
+extern	void	dm_txpower_trackingcallback(struct net_device *dev);
+#endif
+
+extern	void	dm_cck_txpower_adjust(struct net_device *dev,bool  binch14);
+extern	void	dm_restore_dynamic_mechanism_state(struct net_device *dev);
+extern	void	dm_backup_dynamic_mechanism_state(struct net_device *dev);
+extern	void	dm_change_dynamic_initgain_thresh(struct net_device *dev,
+								u32		dm_type,
+								u32		dm_value);
+extern	void	DM_ChangeFsyncSetting(struct net_device *dev,
+												s32		DM_Type,
+												s32		DM_Value);
+extern	void dm_force_tx_fw_info(struct net_device *dev,
+										u32		force_type,
+										u32		force_value);
+extern	void	dm_init_edca_turbo(struct net_device *dev);
+extern	void	dm_rf_operation_test_callback(unsigned long data);
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern	void	dm_rf_pathcheck_workitemcallback(struct work_struct *work);
+#else
+extern	void	dm_rf_pathcheck_workitemcallback(struct net_device *dev);
+#endif
+extern	void dm_fsync_timer_callback(unsigned long data);
+#if 0
+extern	bool	dm_check_lbus_status(struct net_device *dev);
+#endif
+extern	void dm_check_fsync(struct net_device *dev);
+extern	void	dm_shadow_init(struct net_device *dev);
+
+
+/*--------------------Define export function prototype-----------------------*/
+
+
+/*---------------------Define local function prototype-----------------------*/
+// DM --> Rate Adaptive
+static	void	dm_check_rate_adaptive(struct net_device *dev);
+
+// DM --> Bandwidth switch
+static	void	dm_init_bandwidth_autoswitch(struct net_device *dev);
+static	void	dm_bandwidth_autoswitch(	struct net_device *dev);
+
+// DM --> TX power control
+//static	void	dm_initialize_txpower_tracking(struct net_device *dev);
+
+static	void	dm_check_txpower_tracking(struct net_device *dev);
+
+
+
+//static	void	dm_txpower_reset_recovery(struct net_device *dev);
+
+
+// DM --> BB init gain restore
+#ifndef RTL8192U
+static	void	dm_bb_initialgain_restore(struct net_device *dev);
+
+
+// DM --> BB init gain backup
+static	void	dm_bb_initialgain_backup(struct net_device *dev);
+#endif
+// DM --> Dynamic Init Gain by RSSI
+static	void	dm_dig_init(struct net_device *dev);
+static	void	dm_ctrl_initgain_byrssi(struct net_device *dev);
+static	void	dm_ctrl_initgain_byrssi_highpwr(struct net_device *dev);
+static	void	dm_ctrl_initgain_byrssi_by_driverrssi(	struct net_device *dev);
+static	void	dm_ctrl_initgain_byrssi_by_fwfalse_alarm(struct net_device *dev);
+static	void	dm_initial_gain(struct net_device *dev);
+static	void	dm_pd_th(struct net_device *dev);
+static	void	dm_cs_ratio(struct net_device *dev);
+
+static	void dm_init_ctstoself(struct net_device *dev);
+// DM --> EDCA turboe mode control
+static	void	dm_check_edca_turbo(struct net_device *dev);
+
+// DM --> HW RF control
+static	void	dm_check_rfctrl_gpio(struct net_device *dev);
+
+#ifndef RTL8190P
+//static	void	dm_gpio_change_rf(struct net_device *dev);
+#endif
+// DM --> Check PBC
+static	void dm_check_pbc_gpio(struct net_device *dev);
+
+
+// DM --> Check current RX RF path state
+static	void	dm_check_rx_path_selection(struct net_device *dev);
+static 	void dm_init_rxpath_selection(struct net_device *dev);
+static	void dm_rxpath_sel_byrssi(struct net_device *dev);
+
+
+// DM --> Fsync for broadcom ap
+static void dm_init_fsync(struct net_device *dev);
+static void dm_deInit_fsync(struct net_device *dev);
+
+//Added by vivi, 20080522
+static	void	dm_check_txrateandretrycount(struct net_device *dev);
+
+/*---------------------Define local function prototype-----------------------*/
+
+/*---------------------Define of Tx Power Control For Near/Far Range --------*/   //Add by Jacken 2008/02/18
+static	void	dm_init_dynamic_txpower(struct net_device *dev);
+static	void	dm_dynamic_txpower(struct net_device *dev);
+
+
+// DM --> For rate adaptive and DIG, we must send RSSI to firmware
+static	void dm_send_rssi_tofw(struct net_device *dev);
+static	void	dm_ctstoself(struct net_device *dev);
+/*---------------------------Define function prototype------------------------*/
+//================================================================================
+//	HW Dynamic mechanism interface.
+//================================================================================
+#ifdef RTL8192SU
+static void dm_CheckAggrPolicy(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	PRT_HIGH_THROUGHPUT	pHTInfo = priv->ieee80211->pHTInfo;
+	//u8 			QueueId;
+	//PRT_TCB			pTcb;
+	bool			bAmsduEnable = false;
+
+	static u8		lastTxOkCnt = 0;
+	static u8		lastRxOkCnt = 0;
+	u8			curTxOkCnt = 0;
+	u8			curRxOkCnt = 0;
+
+	// Determine if A-MSDU policy.
+	if(priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_HYBRID_AGGREGATION)
+	{
+		if(read_nic_byte(dev, INIMCS_SEL) > DESC92S_RATE54M)
+			bAmsduEnable = true;
+	}
+	else if(priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_AMSDU_ENABLE)
+	{
+		if(read_nic_byte(dev, INIMCS_SEL) > DESC92S_RATE54M)
+		{
+			curTxOkCnt = priv->stats.txbytesunicast - lastTxOkCnt;
+			curRxOkCnt = priv->stats.rxbytesunicast - lastRxOkCnt;
+
+			if(curRxOkCnt <= 4*curTxOkCnt)
+				bAmsduEnable = true;
+		}
+	}
+	else
+	{
+		// Do not need to switch aggregation policy.
+		return;
+	}
+
+	// Switch A-MSDU
+	if(bAmsduEnable && !pHTInfo->bCurrent_AMSDU_Support)
+	{
+		pHTInfo->bCurrent_AMSDU_Support = true;
+	}
+	else if(!bAmsduEnable && pHTInfo->bCurrent_AMSDU_Support)
+	{
+#ifdef TO_DO_LIST
+		//PlatformAcquireSpinLock(Adapter, RT_TX_SPINLOCK);
+		for(QueueId = 0; QueueId < MAX_TX_QUEUE; QueueId++)
+		{
+			while(!RTIsListEmpty(&dev->TcbAggrQueue[QueueId]))
+			{
+				pTcb = (PRT_TCB)RTRemoveHeadList(&dev->TcbAggrQueue[QueueId]);
+				dev->TcbCountInAggrQueue[QueueId]--;
+				PreTransmitTCB(dev, pTcb);
+			}
+		}
+		//PlatformReleaseSpinLock(Adapter, RT_TX_SPINLOCK);
+		pHTInfo->bCurrent_AMSDU_Support = false;
+#endif
+	}
+
+	// Determine A-MPDU policy
+	if(priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_AMSDU_ENABLE)
+	{
+		if(!bAmsduEnable)
+			pHTInfo->bCurrentAMPDUEnable = true;
+	}
+
+	// Update local static variables.
+	lastTxOkCnt = priv->stats.txbytesunicast;
+	lastRxOkCnt = priv->stats.rxbytesunicast;
+}
+#endif
+//
+//	Description:
+//		Prepare SW resource for HW dynamic mechanism.
+//
+//	Assumption:
+//		This function is only invoked at driver intialization once.
+//
+//
+extern	void
+init_hal_dm(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	// Undecorated Smoothed Signal Strength, it can utilized to dynamic mechanism.
+	priv->undecorated_smoothed_pwdb = -1;
+
+	//Initial TX Power Control for near/far range , add by amy 2008/05/15, porting from windows code.
+	dm_init_dynamic_txpower(dev);
+	init_rate_adaptive(dev);
+#ifdef RTL8192SU
+	dm_initialize_txpower_tracking(dev);
+#else
+	//dm_initialize_txpower_tracking(dev);
+#endif
+	dm_dig_init(dev);
+	dm_init_edca_turbo(dev);
+	dm_init_bandwidth_autoswitch(dev);
+	dm_init_fsync(dev);
+	dm_init_rxpath_selection(dev);
+	dm_init_ctstoself(dev);
+
+}	// InitHalDm
+
+extern void deinit_hal_dm(struct net_device *dev)
+{
+
+	dm_deInit_fsync(dev);
+
+}
+
+
+#ifdef USB_RX_AGGREGATION_SUPPORT
+void dm_CheckRxAggregation(struct net_device *dev) {
+	struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
+	PRT_HIGH_THROUGHPUT	pHTInfo = priv->ieee80211->pHTInfo;
+	static unsigned long	lastTxOkCnt = 0;
+	static unsigned long	lastRxOkCnt = 0;
+	unsigned long		curTxOkCnt = 0;
+	unsigned long		curRxOkCnt = 0;
+
+/*
+	if (pHalData->bForcedUsbRxAggr) {
+		if (pHalData->ForcedUsbRxAggrInfo == 0) {
+			if (pHalData->bCurrentRxAggrEnable) {
+				Adapter->HalFunc.HalUsbRxAggrHandler(Adapter, FALSE);
+			}
+		} else {
+			if (!pHalData->bCurrentRxAggrEnable || (pHalData->ForcedUsbRxAggrInfo != pHalData->LastUsbRxAggrInfoSetting)) {
+				Adapter->HalFunc.HalUsbRxAggrHandler(Adapter, TRUE);
+			}
+		}
+		return;
+	}
+
+*/
+#ifdef RTL8192SU
+	if (priv->bForcedUsbRxAggr) {
+		if (priv->ForcedUsbRxAggrInfo == 0) {
+			if (priv->bCurrentRxAggrEnable) {
+				//Adapter->HalFunc.HalUsbRxAggrHandler(Adapter, FALSE);
+				write_nic_dword(dev, 0x1a8, 0);
+				priv->bCurrentRxAggrEnable = false;
+			}
+		} else {
+			if (!priv->bCurrentRxAggrEnable || (priv->ForcedUsbRxAggrInfo != priv->LastUsbRxAggrInfoSetting)) {
+				u32 ulValue;
+				ulValue = (pHTInfo->UsbRxFwAggrEn<<24) | (pHTInfo->UsbRxFwAggrPageNum<<16) |
+						(pHTInfo->UsbRxFwAggrPacketNum<<8) | (pHTInfo->UsbRxFwAggrTimeout);
+				/*
+				 * If usb rx firmware aggregation is enabled,
+				 * when anyone of three threshold conditions above is reached,
+				 * firmware will send aggregated packet to driver.
+			 	*/
+				write_nic_dword(dev, 0x1a8, ulValue);
+				priv->bCurrentRxAggrEnable = true;
+			}
+		}
+		return;
+	}
+
+	if((priv->ieee80211->mode & WIRELESS_MODE_B) || (priv->ieee80211->mode & WIRELESS_MODE_G))
+	{
+		if (priv->bCurrentRxAggrEnable)
+		{
+			RT_TRACE(COMP_RECV, "dm_CheckRxAggregation() :  Disable Rx Aggregation!!\n");
+			write_nic_dword(dev, 0x1a8, 0);
+			priv->bCurrentRxAggrEnable = false;
+			return;
+		}
+	}
+#endif
+
+	curTxOkCnt = priv->stats.txbytesunicast - lastTxOkCnt;
+	curRxOkCnt = priv->stats.rxbytesunicast - lastRxOkCnt;
+
+	if((curTxOkCnt + curRxOkCnt) < 15000000) {
+		return;
+	}
+
+	if(curTxOkCnt > 4*curRxOkCnt) {
+		if (priv->bCurrentRxAggrEnable) {
+			write_nic_dword(dev, 0x1a8, 0);
+			priv->bCurrentRxAggrEnable = false;
+		}
+	}else{
+		if (!priv->bCurrentRxAggrEnable && !pHTInfo->bCurrentRT2RTAggregation) {
+			u32 ulValue;
+			ulValue = (pHTInfo->UsbRxFwAggrEn<<24) | (pHTInfo->UsbRxFwAggrPageNum<<16) |
+				(pHTInfo->UsbRxFwAggrPacketNum<<8) | (pHTInfo->UsbRxFwAggrTimeout);
+			/*
+			 * If usb rx firmware aggregation is enabled,
+			 * when anyone of three threshold conditions above is reached,
+			 * firmware will send aggregated packet to driver.
+			 */
+			write_nic_dword(dev, 0x1a8, ulValue);
+			priv->bCurrentRxAggrEnable = true;
+		}
+	}
+
+	lastTxOkCnt = priv->stats.txbytesunicast;
+	lastRxOkCnt = priv->stats.rxbytesunicast;
+}	// dm_CheckEdcaTurbo
+#endif
+
+
+#ifdef RTL8192SU
+//#if 0
+extern  void    hal_dm_watchdog(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	if(priv->bInHctTest)
+		return;
+
+
+	dm_check_rfctrl_gpio(dev);
+
+	// Add by hpfan 2008-03-11
+	dm_check_pbc_gpio(dev);
+	dm_check_txrateandretrycount(dev); //moved by tynli
+	dm_check_edca_turbo(dev);
+
+	dm_CheckAggrPolicy(dev);
+
+#ifdef TO_DO_LIST
+	dm_CheckProtection(dev);
+#endif
+
+	// ====================================================
+	// If any dynamic mechanism is ready, put it above this return;
+	// ====================================================
+	//if (IS_HARDWARE_TYPE_8192S(dev))
+	return;
+
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	dm_CheckRxAggregation(dev);
+#endif
+#ifdef TO_DO_LIST
+	if(Adapter->MgntInfo.mActingAsAp)
+	{
+		AP_dm_CheckRateAdaptive(dev);
+		//return;
+	}
+	else
+#endif
+	{
+		dm_check_rate_adaptive(dev);
+	}
+	dm_dynamic_txpower(dev);
+
+	dm_check_txpower_tracking(dev);
+	dm_ctrl_initgain_byrssi(dev);//LZM TMP 090302
+
+	dm_bandwidth_autoswitch(dev);
+
+	dm_check_rx_path_selection(dev);//LZM TMP 090302
+	dm_check_fsync(dev);
+
+	dm_send_rssi_tofw(dev);
+
+	dm_ctstoself(dev);
+
+}	//HalDmWatchDog
+#else
+extern  void    hal_dm_watchdog(struct net_device *dev)
+{
+        //struct r8192_priv *priv = ieee80211_priv(dev);
+
+	//static u8 	previous_bssid[6] ={0};
+
+	/*Add by amy 2008/05/15 ,porting from windows code.*/
+	dm_check_rate_adaptive(dev);
+	dm_dynamic_txpower(dev);
+	dm_check_txrateandretrycount(dev);
+	dm_check_txpower_tracking(dev);
+	dm_ctrl_initgain_byrssi(dev);
+	dm_check_edca_turbo(dev);
+	dm_bandwidth_autoswitch(dev);
+	dm_check_rfctrl_gpio(dev);
+	dm_check_rx_path_selection(dev);
+	dm_check_fsync(dev);
+
+	// Add by amy 2008-05-15 porting from windows code.
+	dm_check_pbc_gpio(dev);
+	dm_send_rssi_tofw(dev);
+	dm_ctstoself(dev);
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	dm_CheckRxAggregation(dev);
+#endif
+}	//HalDmWatchDog
+#endif
+
+/*
+  * Decide Rate Adaptive Set according to distance (signal strength)
+  *	01/11/2008	MHC		Modify input arguments and RATR table level.
+  *	01/16/2008	MHC		RF_Type is assigned in ReadAdapterInfo(). We must call
+  *						the function after making sure RF_Type.
+  */
+extern void init_rate_adaptive(struct net_device * dev)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	prate_adaptive	pra = (prate_adaptive)&priv->rate_adaptive;
+
+	pra->ratr_state = DM_RATR_STA_MAX;
+	pra->high2low_rssi_thresh_for_ra = RateAdaptiveTH_High;
+	pra->low2high_rssi_thresh_for_ra20M = RateAdaptiveTH_Low_20M+5;
+	pra->low2high_rssi_thresh_for_ra40M = RateAdaptiveTH_Low_40M+5;
+
+	pra->high_rssi_thresh_for_ra = RateAdaptiveTH_High+5;
+	pra->low_rssi_thresh_for_ra20M = RateAdaptiveTH_Low_20M;
+	pra->low_rssi_thresh_for_ra40M = RateAdaptiveTH_Low_40M;
+
+	if(priv->CustomerID == RT_CID_819x_Netcore)
+		pra->ping_rssi_enable = 1;
+	else
+		pra->ping_rssi_enable = 0;
+	pra->ping_rssi_thresh_for_ra = 15;
+
+
+	if (priv->rf_type == RF_2T4R)
+	{
+		// 07/10/08 MH Modify for RA smooth scheme.
+		/* 2008/01/11 MH Modify 2T RATR table for different RSSI. 080515 porting by amy from windows code.*/
+		pra->upper_rssi_threshold_ratr		= 	0x8f0f0000;
+		pra->middle_rssi_threshold_ratr		= 	0x8f0ff000;
+		pra->low_rssi_threshold_ratr		= 	0x8f0ff001;
+		pra->low_rssi_threshold_ratr_40M	= 	0x8f0ff005;
+		pra->low_rssi_threshold_ratr_20M	= 	0x8f0ff001;
+		pra->ping_rssi_ratr	= 	0x0000000d;//cosa add for test
+	}
+	else if (priv->rf_type == RF_1T2R)
+	{
+		pra->upper_rssi_threshold_ratr		= 	0x000f0000;
+		pra->middle_rssi_threshold_ratr		= 	0x000ff000;
+		pra->low_rssi_threshold_ratr		= 	0x000ff001;
+		pra->low_rssi_threshold_ratr_40M	= 	0x000ff005;
+		pra->low_rssi_threshold_ratr_20M	= 	0x000ff001;
+		pra->ping_rssi_ratr	= 	0x0000000d;//cosa add for test
+	}
+
+}	// InitRateAdaptive
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	dm_check_rate_adaptive()
+ *
+ * Overview:
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/26/08	amy 	Create version 0 proting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static void dm_check_rate_adaptive(struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	PRT_HIGH_THROUGHPUT	pHTInfo = priv->ieee80211->pHTInfo;
+	prate_adaptive			pra = (prate_adaptive)&priv->rate_adaptive;
+	u32						currentRATR, targetRATR = 0;
+	u32						LowRSSIThreshForRA = 0, HighRSSIThreshForRA = 0;
+	bool						bshort_gi_enabled = false;
+	static u8					ping_rssi_state=0;
+
+
+	if(!priv->up)
+	{
+		RT_TRACE(COMP_RATE, "<---- dm_check_rate_adaptive(): driver is going to unload\n");
+		return;
+	}
+
+	if(pra->rate_adaptive_disabled)//this variable is set by ioctl.
+		return;
+
+	// TODO: Only 11n mode is implemented currently,
+	if( !(priv->ieee80211->mode == WIRELESS_MODE_N_24G ||
+		 priv->ieee80211->mode == WIRELESS_MODE_N_5G))
+		 return;
+
+	if( priv->ieee80211->state == IEEE80211_LINKED )
+	{
+	//	RT_TRACE(COMP_RATE, "dm_CheckRateAdaptive(): \t");
+
+		//
+		// Check whether Short GI is enabled
+		//
+		bshort_gi_enabled = (pHTInfo->bCurTxBW40MHz && pHTInfo->bCurShortGI40MHz) ||
+			(!pHTInfo->bCurTxBW40MHz && pHTInfo->bCurShortGI20MHz);
+
+
+		pra->upper_rssi_threshold_ratr =
+				(pra->upper_rssi_threshold_ratr & (~BIT31)) | ((bshort_gi_enabled)? BIT31:0) ;
+
+		pra->middle_rssi_threshold_ratr =
+				(pra->middle_rssi_threshold_ratr & (~BIT31)) | ((bshort_gi_enabled)? BIT31:0) ;
+
+		if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
+		{
+			pra->low_rssi_threshold_ratr =
+				(pra->low_rssi_threshold_ratr_40M & (~BIT31)) | ((bshort_gi_enabled)? BIT31:0) ;
+		}
+		else
+		{
+			pra->low_rssi_threshold_ratr =
+			(pra->low_rssi_threshold_ratr_20M & (~BIT31)) | ((bshort_gi_enabled)? BIT31:0) ;
+		}
+		//cosa add for test
+		pra->ping_rssi_ratr =
+				(pra->ping_rssi_ratr & (~BIT31)) | ((bshort_gi_enabled)? BIT31:0) ;
+
+		/* 2007/10/08 MH We support RA smooth scheme now. When it is the first
+		   time to link with AP. We will not change upper/lower threshold. If
+		   STA stay in high or low level, we must change two different threshold
+		   to prevent jumping frequently. */
+		if (pra->ratr_state == DM_RATR_STA_HIGH)
+		{
+			HighRSSIThreshForRA 	= pra->high2low_rssi_thresh_for_ra;
+			LowRSSIThreshForRA	= (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)?
+					(pra->low_rssi_thresh_for_ra40M):(pra->low_rssi_thresh_for_ra20M);
+		}
+		else if (pra->ratr_state == DM_RATR_STA_LOW)
+		{
+			HighRSSIThreshForRA	= pra->high_rssi_thresh_for_ra;
+			LowRSSIThreshForRA 	= (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)?
+					(pra->low2high_rssi_thresh_for_ra40M):(pra->low2high_rssi_thresh_for_ra20M);
+		}
+		else
+		{
+			HighRSSIThreshForRA	= pra->high_rssi_thresh_for_ra;
+			LowRSSIThreshForRA	= (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)?
+					(pra->low_rssi_thresh_for_ra40M):(pra->low_rssi_thresh_for_ra20M);
+		}
+
+		//DbgPrint("[DM] THresh H/L=%d/%d\n\r", RATR.HighRSSIThreshForRA, RATR.LowRSSIThreshForRA);
+		if(priv->undecorated_smoothed_pwdb >= (long)HighRSSIThreshForRA)
+		{
+			//DbgPrint("[DM] RSSI=%d STA=HIGH\n\r", pHalData->UndecoratedSmoothedPWDB);
+			pra->ratr_state = DM_RATR_STA_HIGH;
+			targetRATR = pra->upper_rssi_threshold_ratr;
+		}else if(priv->undecorated_smoothed_pwdb >= (long)LowRSSIThreshForRA)
+		{
+			//DbgPrint("[DM] RSSI=%d STA=Middle\n\r", pHalData->UndecoratedSmoothedPWDB);
+			pra->ratr_state = DM_RATR_STA_MIDDLE;
+			targetRATR = pra->middle_rssi_threshold_ratr;
+		}else
+		{
+			//DbgPrint("[DM] RSSI=%d STA=LOW\n\r", pHalData->UndecoratedSmoothedPWDB);
+			pra->ratr_state = DM_RATR_STA_LOW;
+			targetRATR = pra->low_rssi_threshold_ratr;
+		}
+
+			//cosa add for test
+		if(pra->ping_rssi_enable)
+		{
+			//pHalData->UndecoratedSmoothedPWDB = 19;
+			if(priv->undecorated_smoothed_pwdb < (long)(pra->ping_rssi_thresh_for_ra+5))
+			{
+				if( (priv->undecorated_smoothed_pwdb < (long)pra->ping_rssi_thresh_for_ra) ||
+					ping_rssi_state )
+				{
+					//DbgPrint("TestRSSI = %d, set RATR to 0x%x \n", pHalData->UndecoratedSmoothedPWDB, pRA->TestRSSIRATR);
+					pra->ratr_state = DM_RATR_STA_LOW;
+					targetRATR = pra->ping_rssi_ratr;
+					ping_rssi_state = 1;
+				}
+				//else
+				//	DbgPrint("TestRSSI is between the range. \n");
+			}
+			else
+			{
+				//DbgPrint("TestRSSI Recover to 0x%x \n", targetRATR);
+				ping_rssi_state = 0;
+			}
+		}
+
+		// 2008.04.01
+#if 1
+		// For RTL819X, if pairwisekey = wep/tkip, we support only MCS0~7.
+		if(priv->ieee80211->GetHalfNmodeSupportByAPsHandler(dev))
+			targetRATR &=  0xf00fffff;
+#endif
+
+		//
+		// Check whether updating of RATR0 is required
+		//
+		currentRATR = read_nic_dword(dev, RATR0);
+		if( targetRATR !=  currentRATR )
+		{
+			u32 ratr_value;
+			ratr_value = targetRATR;
+			RT_TRACE(COMP_RATE,"currentRATR = %x, targetRATR = %x\n", currentRATR, targetRATR);
+			if(priv->rf_type == RF_1T2R)
+			{
+				ratr_value &= ~(RATE_ALL_OFDM_2SS);
+			}
+			write_nic_dword(dev, RATR0, ratr_value);
+			write_nic_byte(dev, UFWP, 1);
+
+			pra->last_ratr = targetRATR;
+		}
+
+	}
+	else
+	{
+		pra->ratr_state = DM_RATR_STA_MAX;
+	}
+
+}	// dm_CheckRateAdaptive
+
+
+static void dm_init_bandwidth_autoswitch(struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	priv->ieee80211->bandwidth_auto_switch.threshold_20Mhzto40Mhz = BW_AUTO_SWITCH_LOW_HIGH;
+	priv->ieee80211->bandwidth_auto_switch.threshold_40Mhzto20Mhz = BW_AUTO_SWITCH_HIGH_LOW;
+	priv->ieee80211->bandwidth_auto_switch.bforced_tx20Mhz = false;
+	priv->ieee80211->bandwidth_auto_switch.bautoswitch_enable = false;
+
+}	// dm_init_bandwidth_autoswitch
+
+
+static void dm_bandwidth_autoswitch(struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20 ||!priv->ieee80211->bandwidth_auto_switch.bautoswitch_enable){
+		return;
+	}else{
+		if(priv->ieee80211->bandwidth_auto_switch.bforced_tx20Mhz == false){//If send packets in 40 Mhz in 20/40
+			if(priv->undecorated_smoothed_pwdb <= priv->ieee80211->bandwidth_auto_switch.threshold_40Mhzto20Mhz)
+				priv->ieee80211->bandwidth_auto_switch.bforced_tx20Mhz = true;
+		}else{//in force send packets in 20 Mhz in 20/40
+			if(priv->undecorated_smoothed_pwdb >= priv->ieee80211->bandwidth_auto_switch.threshold_20Mhzto40Mhz)
+				priv->ieee80211->bandwidth_auto_switch.bforced_tx20Mhz = false;
+
+		}
+	}
+}	// dm_BandwidthAutoSwitch
+
+//OFDM default at 0db, index=6.
+static u32 OFDMSwingTable[OFDM_Table_Length] = {
+	0x7f8001fe,	// 0, +6db
+	0x71c001c7,	// 1, +5db
+	0x65400195,	// 2, +4db
+	0x5a400169,	// 3, +3db
+	0x50800142,	// 4, +2db
+	0x47c0011f,	// 5, +1db
+	0x40000100,	// 6, +0db ===> default, upper for higher temprature, lower for low temprature
+	0x390000e4,	// 7, -1db
+	0x32c000cb,	// 8, -2db
+	0x2d4000b5,	// 9, -3db
+	0x288000a2,	// 10, -4db
+	0x24000090,	// 11, -5db
+	0x20000080,	// 12, -6db
+	0x1c800072,	// 13, -7db
+	0x19800066,	// 14, -8db
+	0x26c0005b,	// 15, -9db
+	0x24400051,	// 16, -10db
+	0x12000048,	// 17, -11db
+	0x10000040	// 18, -12db
+};
+
+static u8	CCKSwingTable_Ch1_Ch13[CCK_Table_length][8] = {
+	{0x36, 0x35, 0x2e, 0x25, 0x1c, 0x12, 0x09, 0x04},	// 0, +0db ===> CCK40M default
+	{0x30, 0x2f, 0x29, 0x21, 0x19, 0x10, 0x08, 0x03},	// 1, -1db
+	{0x2b, 0x2a, 0x25, 0x1e, 0x16, 0x0e, 0x07, 0x03},	// 2, -2db
+	{0x26, 0x25, 0x21, 0x1b, 0x14, 0x0d, 0x06, 0x03},	// 3, -3db
+	{0x22, 0x21, 0x1d, 0x18, 0x11, 0x0b, 0x06, 0x02},	// 4, -4db
+	{0x1f, 0x1e, 0x1a, 0x15, 0x10, 0x0a, 0x05, 0x02},	// 5, -5db
+	{0x1b, 0x1a, 0x17, 0x13, 0x0e, 0x09, 0x04, 0x02},	// 6, -6db ===> CCK20M default
+	{0x18, 0x17, 0x15, 0x11, 0x0c, 0x08, 0x04, 0x02},	// 7, -7db
+	{0x16, 0x15, 0x12, 0x0f, 0x0b, 0x07, 0x04, 0x01},	// 8, -8db
+	{0x13, 0x13, 0x10, 0x0d, 0x0a, 0x06, 0x03, 0x01},	// 9, -9db
+	{0x11, 0x11, 0x0f, 0x0c, 0x09, 0x06, 0x03, 0x01},	// 10, -10db
+	{0x0f, 0x0f, 0x0d, 0x0b, 0x08, 0x05, 0x03, 0x01}	// 11, -11db
+};
+
+static u8	CCKSwingTable_Ch14[CCK_Table_length][8] = {
+	{0x36, 0x35, 0x2e, 0x1b, 0x00, 0x00, 0x00, 0x00},	// 0, +0db  ===> CCK40M default
+	{0x30, 0x2f, 0x29, 0x18, 0x00, 0x00, 0x00, 0x00},	// 1, -1db
+	{0x2b, 0x2a, 0x25, 0x15, 0x00, 0x00, 0x00, 0x00},	// 2, -2db
+	{0x26, 0x25, 0x21, 0x13, 0x00, 0x00, 0x00, 0x00},	// 3, -3db
+	{0x22, 0x21, 0x1d, 0x11, 0x00, 0x00, 0x00, 0x00},	// 4, -4db
+	{0x1f, 0x1e, 0x1a, 0x0f, 0x00, 0x00, 0x00, 0x00},	// 5, -5db
+	{0x1b, 0x1a, 0x17, 0x0e, 0x00, 0x00, 0x00, 0x00},	// 6, -6db  ===> CCK20M default
+	{0x18, 0x17, 0x15, 0x0c, 0x00, 0x00, 0x00, 0x00},	// 7, -7db
+	{0x16, 0x15, 0x12, 0x0b, 0x00, 0x00, 0x00, 0x00},	// 8, -8db
+	{0x13, 0x13, 0x10, 0x0a, 0x00, 0x00, 0x00, 0x00},	// 9, -9db
+	{0x11, 0x11, 0x0f, 0x09, 0x00, 0x00, 0x00, 0x00},	// 10, -10db
+	{0x0f, 0x0f, 0x0d, 0x08, 0x00, 0x00, 0x00, 0x00}	// 11, -11db
+};
+
+static void dm_TXPowerTrackingCallback_TSSI(struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	bool						bHighpowerstate, viviflag = FALSE;
+	DCMD_TXCMD_T			tx_cmd;
+	u8						powerlevelOFDM24G;
+	int	    					i =0, j = 0, k = 0;
+	u8						RF_Type, tmp_report[5]={0, 0, 0, 0, 0};
+	u32						Value;
+	u8						Pwr_Flag;
+	u16						Avg_TSSI_Meas, TSSI_13dBm, Avg_TSSI_Meas_from_driver=0;
+	//RT_STATUS 				rtStatus = RT_STATUS_SUCCESS;
+#ifdef RTL8192U
+	bool rtStatus = true;
+#endif
+	u32						delta=0;
+
+	write_nic_byte(dev, 0x1ba, 0);
+
+	priv->ieee80211->bdynamic_txpower_enable = false;
+	bHighpowerstate = priv->bDynamicTxHighPower;
+
+	powerlevelOFDM24G = (u8)(priv->Pwr_Track>>24);
+	RF_Type = priv->rf_type;
+	Value = (RF_Type<<8) | powerlevelOFDM24G;
+
+	RT_TRACE(COMP_POWER_TRACKING, "powerlevelOFDM24G = %x\n", powerlevelOFDM24G);
+
+	for(j = 0; j<=30; j++)
+{	//fill tx_cmd
+
+	tx_cmd.Op		= TXCMD_SET_TX_PWR_TRACKING;
+	tx_cmd.Length	= 4;
+	tx_cmd.Value		= Value;
+#ifdef RTL8192U
+	rtStatus = SendTxCommandPacket(dev, &tx_cmd, 12);
+	if (rtStatus == false)
+	{
+		RT_TRACE(COMP_POWER_TRACKING, "Set configuration with tx cmd queue fail!\n");
+	}
+#else
+	cmpk_message_handle_tx(dev, (u8*)&tx_cmd,
+								DESC_PACKET_TYPE_INIT, sizeof(DCMD_TXCMD_T));
+#endif
+	mdelay(1);
+	//DbgPrint("hi, vivi, strange\n");
+	for(i = 0;i <= 30; i++)
+	{
+		Pwr_Flag = read_nic_byte(dev, 0x1ba);
+
+		if (Pwr_Flag == 0)
+		{
+			mdelay(1);
+			continue;
+		}
+#ifdef RTL8190P
+		Avg_TSSI_Meas = read_nic_word(dev, 0x1bc);
+#else
+		Avg_TSSI_Meas = read_nic_word(dev, 0x13c);
+#endif
+		if(Avg_TSSI_Meas == 0)
+		{
+			write_nic_byte(dev, 0x1ba, 0);
+			break;
+		}
+
+		for(k = 0;k < 5; k++)
+		{
+#ifdef RTL8190P
+			tmp_report[k] = read_nic_byte(dev, 0x1d8+k);
+#else
+			if(k !=4)
+				tmp_report[k] = read_nic_byte(dev, 0x134+k);
+			else
+				tmp_report[k] = read_nic_byte(dev, 0x13e);
+#endif
+			RT_TRACE(COMP_POWER_TRACKING, "TSSI_report_value = %d\n", tmp_report[k]);
+		}
+
+		//check if the report value is right
+		for(k = 0;k < 5; k++)
+		{
+			if(tmp_report[k] <= 20)
+			{
+				viviflag =TRUE;
+				break;
+			}
+		}
+		if(viviflag ==TRUE)
+		{
+			write_nic_byte(dev, 0x1ba, 0);
+			viviflag = FALSE;
+			RT_TRACE(COMP_POWER_TRACKING, "we filted this data\n");
+			for(k = 0;k < 5; k++)
+				tmp_report[k] = 0;
+			break;
+		}
+
+		for(k = 0;k < 5; k++)
+		{
+			Avg_TSSI_Meas_from_driver += tmp_report[k];
+		}
+
+		Avg_TSSI_Meas_from_driver = Avg_TSSI_Meas_from_driver*100/5;
+		RT_TRACE(COMP_POWER_TRACKING, "Avg_TSSI_Meas_from_driver = %d\n", Avg_TSSI_Meas_from_driver);
+		TSSI_13dBm = priv->TSSI_13dBm;
+		RT_TRACE(COMP_POWER_TRACKING, "TSSI_13dBm = %d\n", TSSI_13dBm);
+
+		//if(abs(Avg_TSSI_Meas_from_driver - TSSI_13dBm) <= E_FOR_TX_POWER_TRACK)
+		// For MacOS-compatible
+		if(Avg_TSSI_Meas_from_driver > TSSI_13dBm)
+			delta = Avg_TSSI_Meas_from_driver - TSSI_13dBm;
+		else
+			delta = TSSI_13dBm - Avg_TSSI_Meas_from_driver;
+
+		if(delta <= E_FOR_TX_POWER_TRACK)
+		{
+			priv->ieee80211->bdynamic_txpower_enable = TRUE;
+			write_nic_byte(dev, 0x1ba, 0);
+			RT_TRACE(COMP_POWER_TRACKING, "tx power track is done\n");
+			RT_TRACE(COMP_POWER_TRACKING, "priv->rfa_txpowertrackingindex = %d\n", priv->rfa_txpowertrackingindex);
+			RT_TRACE(COMP_POWER_TRACKING, "priv->rfa_txpowertrackingindex_real = %d\n", priv->rfa_txpowertrackingindex_real);
+#ifdef RTL8190P
+			RT_TRACE(COMP_POWER_TRACKING, "priv->rfc_txpowertrackingindex = %d\n", priv->rfc_txpowertrackingindex);
+			RT_TRACE(COMP_POWER_TRACKING, "priv->rfc_txpowertrackingindex_real = %d\n", priv->rfc_txpowertrackingindex_real);
+#endif
+			RT_TRACE(COMP_POWER_TRACKING, "priv->cck_present_attentuation_difference = %d\n", priv->cck_present_attentuation_difference);
+			RT_TRACE(COMP_POWER_TRACKING, "priv->cck_present_attentuation = %d\n", priv->cck_present_attentuation);
+			return;
+		}
+		else
+		{
+			if(Avg_TSSI_Meas_from_driver < TSSI_13dBm - E_FOR_TX_POWER_TRACK)
+			{
+				if((priv->rfa_txpowertrackingindex > 0)
+#ifdef RTL8190P
+					&&(priv->rfc_txpowertrackingindex > 0)
+#endif
+				)
+				{
+					priv->rfa_txpowertrackingindex--;
+					if(priv->rfa_txpowertrackingindex_real > 4)
+					{
+						priv->rfa_txpowertrackingindex_real--;
+						rtl8192_setBBreg(dev, rOFDM0_XATxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfa_txpowertrackingindex_real].txbbgain_value);
+					}
+#ifdef RTL8190P
+					priv->rfc_txpowertrackingindex--;
+					if(priv->rfc_txpowertrackingindex_real > 4)
+					{
+						priv->rfc_txpowertrackingindex_real--;
+						rtl8192_setBBreg(dev, rOFDM0_XCTxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfc_txpowertrackingindex_real].txbbgain_value);
+					}
+#endif
+				}
+			}
+			else
+			{
+				if((priv->rfa_txpowertrackingindex < 36)
+#ifdef RTL8190P
+					&&(priv->rfc_txpowertrackingindex < 36)
+#endif
+					)
+				{
+					priv->rfa_txpowertrackingindex++;
+					priv->rfa_txpowertrackingindex_real++;
+					rtl8192_setBBreg(dev, rOFDM0_XATxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfa_txpowertrackingindex_real].txbbgain_value);
+
+#ifdef RTL8190P
+					priv->rfc_txpowertrackingindex++;
+					priv->rfc_txpowertrackingindex_real++;
+					rtl8192_setBBreg(dev, rOFDM0_XCTxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfc_txpowertrackingindex_real].txbbgain_value);
+#endif
+				}
+			}
+			priv->cck_present_attentuation_difference
+				= priv->rfa_txpowertrackingindex - priv->rfa_txpowertracking_default;
+
+			if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20)
+				priv->cck_present_attentuation
+				= priv->cck_present_attentuation_20Mdefault + priv->cck_present_attentuation_difference;
+			else
+				priv->cck_present_attentuation
+				= priv->cck_present_attentuation_40Mdefault + priv->cck_present_attentuation_difference;
+
+			if(priv->cck_present_attentuation > -1&&priv->cck_present_attentuation <23)
+			{
+				if(priv->ieee80211->current_network.channel == 14 && !priv->bcck_in_ch14)
+				{
+					priv->bcck_in_ch14 = TRUE;
+					dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
+				}
+				else if(priv->ieee80211->current_network.channel != 14 && priv->bcck_in_ch14)
+				{
+					priv->bcck_in_ch14 = FALSE;
+					dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
+				}
+				else
+					dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
+			}
+		RT_TRACE(COMP_POWER_TRACKING, "priv->rfa_txpowertrackingindex = %d\n", priv->rfa_txpowertrackingindex);
+		RT_TRACE(COMP_POWER_TRACKING, "priv->rfa_txpowertrackingindex_real = %d\n", priv->rfa_txpowertrackingindex_real);
+#ifdef RTL8190P
+		RT_TRACE(COMP_POWER_TRACKING, "priv->rfc_txpowertrackingindex = %d\n", priv->rfc_txpowertrackingindex);
+		RT_TRACE(COMP_POWER_TRACKING, "priv->rfc_txpowertrackingindex_real = %d\n", priv->rfc_txpowertrackingindex_real);
+#endif
+		RT_TRACE(COMP_POWER_TRACKING, "priv->cck_present_attentuation_difference = %d\n", priv->cck_present_attentuation_difference);
+		RT_TRACE(COMP_POWER_TRACKING, "priv->cck_present_attentuation = %d\n", priv->cck_present_attentuation);
+
+		if (priv->cck_present_attentuation_difference <= -12||priv->cck_present_attentuation_difference >= 24)
+		{
+			priv->ieee80211->bdynamic_txpower_enable = TRUE;
+			write_nic_byte(dev, 0x1ba, 0);
+			RT_TRACE(COMP_POWER_TRACKING, "tx power track--->limited\n");
+			return;
+		}
+
+
+	}
+		write_nic_byte(dev, 0x1ba, 0);
+		Avg_TSSI_Meas_from_driver = 0;
+		for(k = 0;k < 5; k++)
+			tmp_report[k] = 0;
+		break;
+	}
+}
+		priv->ieee80211->bdynamic_txpower_enable = TRUE;
+		write_nic_byte(dev, 0x1ba, 0);
+}
+
+static void dm_TXPowerTrackingCallback_ThermalMeter(struct net_device * dev)
+{
+#define ThermalMeterVal	9
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 tmpRegA, TempCCk;
+	u8 tmpOFDMindex, tmpCCKindex, tmpCCK20Mindex, tmpCCK40Mindex, tmpval;
+	int i =0, CCKSwingNeedUpdate=0;
+
+	if(!priv->btxpower_trackingInit)
+	{
+		//Query OFDM default setting
+		tmpRegA= rtl8192_QueryBBReg(dev, rOFDM0_XATxIQImbalance, bMaskDWord);
+		for(i=0; i<OFDM_Table_Length; i++)	//find the index
+		{
+			if(tmpRegA == OFDMSwingTable[i])
+			{
+				priv->OFDM_index= (u8)i;
+				RT_TRACE(COMP_POWER_TRACKING, "Initial reg0x%x = 0x%x, OFDM_index=0x%x\n",
+					rOFDM0_XATxIQImbalance, tmpRegA, priv->OFDM_index);
+			}
+		}
+
+		//Query CCK default setting From 0xa22
+		TempCCk = rtl8192_QueryBBReg(dev, rCCK0_TxFilter1, bMaskByte2);
+		for(i=0 ; i<CCK_Table_length ; i++)
+		{
+			if(TempCCk == (u32)CCKSwingTable_Ch1_Ch13[i][0])
+			{
+				priv->CCK_index =(u8) i;
+				RT_TRACE(COMP_POWER_TRACKING, "Initial reg0x%x = 0x%x, CCK_index=0x%x\n",
+					rCCK0_TxFilter1, TempCCk, priv->CCK_index);
+				break;
+			}
+		}
+		priv->btxpower_trackingInit = TRUE;
+		//pHalData->TXPowercount = 0;
+		return;
+	}
+
+	//==========================
+	// this is only for test, should be masked
+#if 0
+{
+	//UINT32	eRFPath;
+	//UINT32	start_rf, end_rf;
+	UINT32	curr_addr;
+	//UINT32	reg_addr;
+	//UINT32	reg_addr_end;
+	UINT32	reg_value;
+	//start_rf 		= RF90_PATH_A;
+	//end_rf 			= RF90_PATH_B;//RF90_PATH_MAX;
+	//reg_addr 		= 0x0;
+	//reg_addr_end 	= 0x2F;
+
+		for (curr_addr = 0; curr_addr < 0x2d; curr_addr++)
+		{
+			reg_value = PHY_QueryRFReg(	Adapter, (RF90_RADIO_PATH_E)RF90_PATH_A,
+										curr_addr, bMaskDWord);
+		}
+
+	pHalData->TXPowercount = 0;
+	return;
+}
+#endif
+	//==========================
+
+	// read and filter out unreasonable value
+	tmpRegA = rtl8192_phy_QueryRFReg(dev, RF90_PATH_A, 0x12, 0x078);	// 0x12: RF Reg[10:7]
+	RT_TRACE(COMP_POWER_TRACKING, "Readback ThermalMeterA = %d \n", tmpRegA);
+	if(tmpRegA < 3 || tmpRegA > 13)
+		return;
+	if(tmpRegA >= 12)	// if over 12, TP will be bad when high temprature
+		tmpRegA = 12;
+	RT_TRACE(COMP_POWER_TRACKING, "Valid ThermalMeterA = %d \n", tmpRegA);
+	priv->ThermalMeter[0] = ThermalMeterVal;	//We use fixed value by Bryant's suggestion
+	priv->ThermalMeter[1] = ThermalMeterVal;	//We use fixed value by Bryant's suggestion
+
+	//Get current RF-A temprature index
+	if(priv->ThermalMeter[0] >= (u8)tmpRegA)	//lower temprature
+	{
+		tmpOFDMindex = tmpCCK20Mindex = 6+(priv->ThermalMeter[0]-(u8)tmpRegA);
+		tmpCCK40Mindex = tmpCCK20Mindex - 6;
+		if(tmpOFDMindex >= OFDM_Table_Length)
+			tmpOFDMindex = OFDM_Table_Length-1;
+		if(tmpCCK20Mindex >= CCK_Table_length)
+			tmpCCK20Mindex = CCK_Table_length-1;
+		if(tmpCCK40Mindex >= CCK_Table_length)
+			tmpCCK40Mindex = CCK_Table_length-1;
+	}
+	else
+	{
+		tmpval = ((u8)tmpRegA - priv->ThermalMeter[0]);
+		if(tmpval >= 6)								// higher temprature
+			tmpOFDMindex = tmpCCK20Mindex = 0;		// max to +6dB
+		else
+			tmpOFDMindex = tmpCCK20Mindex = 6 - tmpval;
+		tmpCCK40Mindex = 0;
+	}
+	//DbgPrint("%ddb, tmpOFDMindex = %d, tmpCCK20Mindex = %d, tmpCCK40Mindex = %d",
+		//((u1Byte)tmpRegA - pHalData->ThermalMeter[0]),
+		//tmpOFDMindex, tmpCCK20Mindex, tmpCCK40Mindex);
+	if(priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)	//40M
+		tmpCCKindex = tmpCCK40Mindex;
+	else
+		tmpCCKindex = tmpCCK20Mindex;
+
+	if(priv->ieee80211->current_network.channel == 14 && !priv->bcck_in_ch14)
+	{
+		priv->bcck_in_ch14 = TRUE;
+		CCKSwingNeedUpdate = 1;
+	}
+	else if(priv->ieee80211->current_network.channel != 14 && priv->bcck_in_ch14)
+	{
+		priv->bcck_in_ch14 = FALSE;
+		CCKSwingNeedUpdate = 1;
+	}
+
+	if(priv->CCK_index != tmpCCKindex)
+	{
+		priv->CCK_index = tmpCCKindex;
+		CCKSwingNeedUpdate = 1;
+	}
+
+	if(CCKSwingNeedUpdate)
+	{
+		//DbgPrint("Update CCK Swing, CCK_index = %d\n", pHalData->CCK_index);
+		dm_cck_txpower_adjust(dev, priv->bcck_in_ch14);
+	}
+	if(priv->OFDM_index != tmpOFDMindex)
+	{
+		priv->OFDM_index = tmpOFDMindex;
+		rtl8192_setBBreg(dev, rOFDM0_XATxIQImbalance, bMaskDWord, OFDMSwingTable[priv->OFDM_index]);
+		RT_TRACE(COMP_POWER_TRACKING, "Update OFDMSwing[%d] = 0x%x\n",
+			priv->OFDM_index, OFDMSwingTable[priv->OFDM_index]);
+	}
+	priv->txpower_count = 0;
+}
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern	void	dm_txpower_trackingcallback(struct work_struct *work)
+{
+	struct delayed_work *dwork = container_of(work,struct delayed_work,work);
+       struct r8192_priv *priv = container_of(dwork,struct r8192_priv,txpower_tracking_wq);
+       struct net_device *dev = priv->ieee80211->dev;
+#else
+extern	void	dm_txpower_trackingcallback(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+#endif
+
+#ifdef RTL8190P
+	dm_TXPowerTrackingCallback_TSSI(dev);
+#else
+	if(priv->bDcut == TRUE)
+		dm_TXPowerTrackingCallback_TSSI(dev);
+	else
+		dm_TXPowerTrackingCallback_ThermalMeter(dev);
+#endif
+}
+
+
+static void dm_InitializeTXPowerTracking_TSSI(struct net_device *dev)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	//Initial the Tx BB index and mapping value
+	priv->txbbgain_table[0].txbb_iq_amplifygain = 	 		12;
+	priv->txbbgain_table[0].txbbgain_value=0x7f8001fe;
+	priv->txbbgain_table[1].txbb_iq_amplifygain = 	 		11;
+	priv->txbbgain_table[1].txbbgain_value=0x788001e2;
+	priv->txbbgain_table[2].txbb_iq_amplifygain = 	 		10;
+	priv->txbbgain_table[2].txbbgain_value=0x71c001c7;
+	priv->txbbgain_table[3].txbb_iq_amplifygain = 	 		9;
+	priv->txbbgain_table[3].txbbgain_value=0x6b8001ae;
+	priv->txbbgain_table[4].txbb_iq_amplifygain = 		       8;
+	priv->txbbgain_table[4].txbbgain_value=0x65400195;
+	priv->txbbgain_table[5].txbb_iq_amplifygain = 		       7;
+	priv->txbbgain_table[5].txbbgain_value=0x5fc0017f;
+	priv->txbbgain_table[6].txbb_iq_amplifygain = 		       6;
+	priv->txbbgain_table[6].txbbgain_value=0x5a400169;
+	priv->txbbgain_table[7].txbb_iq_amplifygain = 		       5;
+	priv->txbbgain_table[7].txbbgain_value=0x55400155;
+	priv->txbbgain_table[8].txbb_iq_amplifygain = 		       4;
+	priv->txbbgain_table[8].txbbgain_value=0x50800142;
+	priv->txbbgain_table[9].txbb_iq_amplifygain = 		       3;
+	priv->txbbgain_table[9].txbbgain_value=0x4c000130;
+	priv->txbbgain_table[10].txbb_iq_amplifygain = 		       2;
+	priv->txbbgain_table[10].txbbgain_value=0x47c0011f;
+	priv->txbbgain_table[11].txbb_iq_amplifygain = 		       1;
+	priv->txbbgain_table[11].txbbgain_value=0x43c0010f;
+	priv->txbbgain_table[12].txbb_iq_amplifygain = 		       0;
+	priv->txbbgain_table[12].txbbgain_value=0x40000100;
+	priv->txbbgain_table[13].txbb_iq_amplifygain = 		       -1;
+	priv->txbbgain_table[13].txbbgain_value=0x3c8000f2;
+	priv->txbbgain_table[14].txbb_iq_amplifygain = 		     -2;
+	priv->txbbgain_table[14].txbbgain_value=0x390000e4;
+	priv->txbbgain_table[15].txbb_iq_amplifygain = 		     -3;
+	priv->txbbgain_table[15].txbbgain_value=0x35c000d7;
+	priv->txbbgain_table[16].txbb_iq_amplifygain = 		     -4;
+	priv->txbbgain_table[16].txbbgain_value=0x32c000cb;
+	priv->txbbgain_table[17].txbb_iq_amplifygain = 		     -5;
+	priv->txbbgain_table[17].txbbgain_value=0x300000c0;
+	priv->txbbgain_table[18].txbb_iq_amplifygain = 		 	    -6;
+	priv->txbbgain_table[18].txbbgain_value=0x2d4000b5;
+	priv->txbbgain_table[19].txbb_iq_amplifygain = 		     -7;
+	priv->txbbgain_table[19].txbbgain_value=0x2ac000ab;
+	priv->txbbgain_table[20].txbb_iq_amplifygain = 		     -8;
+	priv->txbbgain_table[20].txbbgain_value=0x288000a2;
+	priv->txbbgain_table[21].txbb_iq_amplifygain = 		     -9;
+	priv->txbbgain_table[21].txbbgain_value=0x26000098;
+	priv->txbbgain_table[22].txbb_iq_amplifygain = 		     -10;
+	priv->txbbgain_table[22].txbbgain_value=0x24000090;
+	priv->txbbgain_table[23].txbb_iq_amplifygain = 		     -11;
+	priv->txbbgain_table[23].txbbgain_value=0x22000088;
+	priv->txbbgain_table[24].txbb_iq_amplifygain = 		     -12;
+	priv->txbbgain_table[24].txbbgain_value=0x20000080;
+	priv->txbbgain_table[25].txbb_iq_amplifygain = 		     -13;
+	priv->txbbgain_table[25].txbbgain_value=0x1a00006c;
+	priv->txbbgain_table[26].txbb_iq_amplifygain = 		     -14;
+	priv->txbbgain_table[26].txbbgain_value=0x1c800072;
+	priv->txbbgain_table[27].txbb_iq_amplifygain = 		     -15;
+	priv->txbbgain_table[27].txbbgain_value=0x18000060;
+	priv->txbbgain_table[28].txbb_iq_amplifygain = 		     -16;
+	priv->txbbgain_table[28].txbbgain_value=0x19800066;
+	priv->txbbgain_table[29].txbb_iq_amplifygain = 		     -17;
+	priv->txbbgain_table[29].txbbgain_value=0x15800056;
+	priv->txbbgain_table[30].txbb_iq_amplifygain = 		     -18;
+	priv->txbbgain_table[30].txbbgain_value=0x26c0005b;
+	priv->txbbgain_table[31].txbb_iq_amplifygain = 		     -19;
+	priv->txbbgain_table[31].txbbgain_value=0x14400051;
+	priv->txbbgain_table[32].txbb_iq_amplifygain = 		     -20;
+	priv->txbbgain_table[32].txbbgain_value=0x24400051;
+	priv->txbbgain_table[33].txbb_iq_amplifygain = 		     -21;
+	priv->txbbgain_table[33].txbbgain_value=0x1300004c;
+	priv->txbbgain_table[34].txbb_iq_amplifygain = 		     -22;
+	priv->txbbgain_table[34].txbbgain_value=0x12000048;
+	priv->txbbgain_table[35].txbb_iq_amplifygain = 		     -23;
+	priv->txbbgain_table[35].txbbgain_value=0x11000044;
+	priv->txbbgain_table[36].txbb_iq_amplifygain = 		     -24;
+	priv->txbbgain_table[36].txbbgain_value=0x10000040;
+
+	//ccktxbb_valuearray[0] is 0xA22 [1] is 0xA24 ...[7] is 0xA29
+	//This Table is for CH1~CH13
+	priv->cck_txbbgain_table[0].ccktxbb_valuearray[0] = 0x36;
+	priv->cck_txbbgain_table[0].ccktxbb_valuearray[1] = 0x35;
+	priv->cck_txbbgain_table[0].ccktxbb_valuearray[2] = 0x2e;
+	priv->cck_txbbgain_table[0].ccktxbb_valuearray[3] = 0x25;
+	priv->cck_txbbgain_table[0].ccktxbb_valuearray[4] = 0x1c;
+	priv->cck_txbbgain_table[0].ccktxbb_valuearray[5] = 0x12;
+	priv->cck_txbbgain_table[0].ccktxbb_valuearray[6] = 0x09;
+	priv->cck_txbbgain_table[0].ccktxbb_valuearray[7] = 0x04;
+
+	priv->cck_txbbgain_table[1].ccktxbb_valuearray[0] = 0x33;
+	priv->cck_txbbgain_table[1].ccktxbb_valuearray[1] = 0x32;
+	priv->cck_txbbgain_table[1].ccktxbb_valuearray[2] = 0x2b;
+	priv->cck_txbbgain_table[1].ccktxbb_valuearray[3] = 0x23;
+	priv->cck_txbbgain_table[1].ccktxbb_valuearray[4] = 0x1a;
+	priv->cck_txbbgain_table[1].ccktxbb_valuearray[5] = 0x11;
+	priv->cck_txbbgain_table[1].ccktxbb_valuearray[6] = 0x08;
+	priv->cck_txbbgain_table[1].ccktxbb_valuearray[7] = 0x04;
+
+	priv->cck_txbbgain_table[2].ccktxbb_valuearray[0] = 0x30;
+	priv->cck_txbbgain_table[2].ccktxbb_valuearray[1] = 0x2f;
+	priv->cck_txbbgain_table[2].ccktxbb_valuearray[2] = 0x29;
+	priv->cck_txbbgain_table[2].ccktxbb_valuearray[3] = 0x21;
+	priv->cck_txbbgain_table[2].ccktxbb_valuearray[4] = 0x19;
+	priv->cck_txbbgain_table[2].ccktxbb_valuearray[5] = 0x10;
+	priv->cck_txbbgain_table[2].ccktxbb_valuearray[6] = 0x08;
+	priv->cck_txbbgain_table[2].ccktxbb_valuearray[7] = 0x03;
+
+	priv->cck_txbbgain_table[3].ccktxbb_valuearray[0] = 0x2d;
+	priv->cck_txbbgain_table[3].ccktxbb_valuearray[1] = 0x2d;
+	priv->cck_txbbgain_table[3].ccktxbb_valuearray[2] = 0x27;
+	priv->cck_txbbgain_table[3].ccktxbb_valuearray[3] = 0x1f;
+	priv->cck_txbbgain_table[3].ccktxbb_valuearray[4] = 0x18;
+	priv->cck_txbbgain_table[3].ccktxbb_valuearray[5] = 0x0f;
+	priv->cck_txbbgain_table[3].ccktxbb_valuearray[6] = 0x08;
+	priv->cck_txbbgain_table[3].ccktxbb_valuearray[7] = 0x03;
+
+	priv->cck_txbbgain_table[4].ccktxbb_valuearray[0] = 0x2b;
+	priv->cck_txbbgain_table[4].ccktxbb_valuearray[1] = 0x2a;
+	priv->cck_txbbgain_table[4].ccktxbb_valuearray[2] = 0x25;
+	priv->cck_txbbgain_table[4].ccktxbb_valuearray[3] = 0x1e;
+	priv->cck_txbbgain_table[4].ccktxbb_valuearray[4] = 0x16;
+	priv->cck_txbbgain_table[4].ccktxbb_valuearray[5] = 0x0e;
+	priv->cck_txbbgain_table[4].ccktxbb_valuearray[6] = 0x07;
+	priv->cck_txbbgain_table[4].ccktxbb_valuearray[7] = 0x03;
+
+	priv->cck_txbbgain_table[5].ccktxbb_valuearray[0] = 0x28;
+	priv->cck_txbbgain_table[5].ccktxbb_valuearray[1] = 0x28;
+	priv->cck_txbbgain_table[5].ccktxbb_valuearray[2] = 0x22;
+	priv->cck_txbbgain_table[5].ccktxbb_valuearray[3] = 0x1c;
+	priv->cck_txbbgain_table[5].ccktxbb_valuearray[4] = 0x15;
+	priv->cck_txbbgain_table[5].ccktxbb_valuearray[5] = 0x0d;
+	priv->cck_txbbgain_table[5].ccktxbb_valuearray[6] = 0x07;
+	priv->cck_txbbgain_table[5].ccktxbb_valuearray[7] = 0x03;
+
+	priv->cck_txbbgain_table[6].ccktxbb_valuearray[0] = 0x26;
+	priv->cck_txbbgain_table[6].ccktxbb_valuearray[1] = 0x25;
+	priv->cck_txbbgain_table[6].ccktxbb_valuearray[2] = 0x21;
+	priv->cck_txbbgain_table[6].ccktxbb_valuearray[3] = 0x1b;
+	priv->cck_txbbgain_table[6].ccktxbb_valuearray[4] = 0x14;
+	priv->cck_txbbgain_table[6].ccktxbb_valuearray[5] = 0x0d;
+	priv->cck_txbbgain_table[6].ccktxbb_valuearray[6] = 0x06;
+	priv->cck_txbbgain_table[6].ccktxbb_valuearray[7] = 0x03;
+
+	priv->cck_txbbgain_table[7].ccktxbb_valuearray[0] = 0x24;
+	priv->cck_txbbgain_table[7].ccktxbb_valuearray[1] = 0x23;
+	priv->cck_txbbgain_table[7].ccktxbb_valuearray[2] = 0x1f;
+	priv->cck_txbbgain_table[7].ccktxbb_valuearray[3] = 0x19;
+	priv->cck_txbbgain_table[7].ccktxbb_valuearray[4] = 0x13;
+	priv->cck_txbbgain_table[7].ccktxbb_valuearray[5] = 0x0c;
+	priv->cck_txbbgain_table[7].ccktxbb_valuearray[6] = 0x06;
+	priv->cck_txbbgain_table[7].ccktxbb_valuearray[7] = 0x03;
+
+	priv->cck_txbbgain_table[8].ccktxbb_valuearray[0] = 0x22;
+	priv->cck_txbbgain_table[8].ccktxbb_valuearray[1] = 0x21;
+	priv->cck_txbbgain_table[8].ccktxbb_valuearray[2] = 0x1d;
+	priv->cck_txbbgain_table[8].ccktxbb_valuearray[3] = 0x18;
+	priv->cck_txbbgain_table[8].ccktxbb_valuearray[4] = 0x11;
+	priv->cck_txbbgain_table[8].ccktxbb_valuearray[5] = 0x0b;
+	priv->cck_txbbgain_table[8].ccktxbb_valuearray[6] = 0x06;
+	priv->cck_txbbgain_table[8].ccktxbb_valuearray[7] = 0x02;
+
+	priv->cck_txbbgain_table[9].ccktxbb_valuearray[0] = 0x20;
+	priv->cck_txbbgain_table[9].ccktxbb_valuearray[1] = 0x20;
+	priv->cck_txbbgain_table[9].ccktxbb_valuearray[2] = 0x1b;
+	priv->cck_txbbgain_table[9].ccktxbb_valuearray[3] = 0x16;
+	priv->cck_txbbgain_table[9].ccktxbb_valuearray[4] = 0x11;
+	priv->cck_txbbgain_table[9].ccktxbb_valuearray[5] = 0x08;
+	priv->cck_txbbgain_table[9].ccktxbb_valuearray[6] = 0x05;
+	priv->cck_txbbgain_table[9].ccktxbb_valuearray[7] = 0x02;
+
+	priv->cck_txbbgain_table[10].ccktxbb_valuearray[0] = 0x1f;
+	priv->cck_txbbgain_table[10].ccktxbb_valuearray[1] = 0x1e;
+	priv->cck_txbbgain_table[10].ccktxbb_valuearray[2] = 0x1a;
+	priv->cck_txbbgain_table[10].ccktxbb_valuearray[3] = 0x15;
+	priv->cck_txbbgain_table[10].ccktxbb_valuearray[4] = 0x10;
+	priv->cck_txbbgain_table[10].ccktxbb_valuearray[5] = 0x0a;
+	priv->cck_txbbgain_table[10].ccktxbb_valuearray[6] = 0x05;
+	priv->cck_txbbgain_table[10].ccktxbb_valuearray[7] = 0x02;
+
+	priv->cck_txbbgain_table[11].ccktxbb_valuearray[0] = 0x1d;
+	priv->cck_txbbgain_table[11].ccktxbb_valuearray[1] = 0x1c;
+	priv->cck_txbbgain_table[11].ccktxbb_valuearray[2] = 0x18;
+	priv->cck_txbbgain_table[11].ccktxbb_valuearray[3] = 0x14;
+	priv->cck_txbbgain_table[11].ccktxbb_valuearray[4] = 0x0f;
+	priv->cck_txbbgain_table[11].ccktxbb_valuearray[5] = 0x0a;
+	priv->cck_txbbgain_table[11].ccktxbb_valuearray[6] = 0x05;
+	priv->cck_txbbgain_table[11].ccktxbb_valuearray[7] = 0x02;
+
+	priv->cck_txbbgain_table[12].ccktxbb_valuearray[0] = 0x1b;
+	priv->cck_txbbgain_table[12].ccktxbb_valuearray[1] = 0x1a;
+	priv->cck_txbbgain_table[12].ccktxbb_valuearray[2] = 0x17;
+	priv->cck_txbbgain_table[12].ccktxbb_valuearray[3] = 0x13;
+	priv->cck_txbbgain_table[12].ccktxbb_valuearray[4] = 0x0e;
+	priv->cck_txbbgain_table[12].ccktxbb_valuearray[5] = 0x09;
+	priv->cck_txbbgain_table[12].ccktxbb_valuearray[6] = 0x04;
+	priv->cck_txbbgain_table[12].ccktxbb_valuearray[7] = 0x02;
+
+	priv->cck_txbbgain_table[13].ccktxbb_valuearray[0] = 0x1a;
+	priv->cck_txbbgain_table[13].ccktxbb_valuearray[1] = 0x19;
+	priv->cck_txbbgain_table[13].ccktxbb_valuearray[2] = 0x16;
+	priv->cck_txbbgain_table[13].ccktxbb_valuearray[3] = 0x12;
+	priv->cck_txbbgain_table[13].ccktxbb_valuearray[4] = 0x0d;
+	priv->cck_txbbgain_table[13].ccktxbb_valuearray[5] = 0x09;
+	priv->cck_txbbgain_table[13].ccktxbb_valuearray[6] = 0x04;
+	priv->cck_txbbgain_table[13].ccktxbb_valuearray[7] = 0x02;
+
+	priv->cck_txbbgain_table[14].ccktxbb_valuearray[0] = 0x18;
+	priv->cck_txbbgain_table[14].ccktxbb_valuearray[1] = 0x17;
+	priv->cck_txbbgain_table[14].ccktxbb_valuearray[2] = 0x15;
+	priv->cck_txbbgain_table[14].ccktxbb_valuearray[3] = 0x11;
+	priv->cck_txbbgain_table[14].ccktxbb_valuearray[4] = 0x0c;
+	priv->cck_txbbgain_table[14].ccktxbb_valuearray[5] = 0x08;
+	priv->cck_txbbgain_table[14].ccktxbb_valuearray[6] = 0x04;
+	priv->cck_txbbgain_table[14].ccktxbb_valuearray[7] = 0x02;
+
+	priv->cck_txbbgain_table[15].ccktxbb_valuearray[0] = 0x17;
+	priv->cck_txbbgain_table[15].ccktxbb_valuearray[1] = 0x16;
+	priv->cck_txbbgain_table[15].ccktxbb_valuearray[2] = 0x13;
+	priv->cck_txbbgain_table[15].ccktxbb_valuearray[3] = 0x10;
+	priv->cck_txbbgain_table[15].ccktxbb_valuearray[4] = 0x0c;
+	priv->cck_txbbgain_table[15].ccktxbb_valuearray[5] = 0x08;
+	priv->cck_txbbgain_table[15].ccktxbb_valuearray[6] = 0x04;
+	priv->cck_txbbgain_table[15].ccktxbb_valuearray[7] = 0x02;
+
+	priv->cck_txbbgain_table[16].ccktxbb_valuearray[0] = 0x16;
+	priv->cck_txbbgain_table[16].ccktxbb_valuearray[1] = 0x15;
+	priv->cck_txbbgain_table[16].ccktxbb_valuearray[2] = 0x12;
+	priv->cck_txbbgain_table[16].ccktxbb_valuearray[3] = 0x0f;
+	priv->cck_txbbgain_table[16].ccktxbb_valuearray[4] = 0x0b;
+	priv->cck_txbbgain_table[16].ccktxbb_valuearray[5] = 0x07;
+	priv->cck_txbbgain_table[16].ccktxbb_valuearray[6] = 0x04;
+	priv->cck_txbbgain_table[16].ccktxbb_valuearray[7] = 0x01;
+
+	priv->cck_txbbgain_table[17].ccktxbb_valuearray[0] = 0x14;
+	priv->cck_txbbgain_table[17].ccktxbb_valuearray[1] = 0x14;
+	priv->cck_txbbgain_table[17].ccktxbb_valuearray[2] = 0x11;
+	priv->cck_txbbgain_table[17].ccktxbb_valuearray[3] = 0x0e;
+	priv->cck_txbbgain_table[17].ccktxbb_valuearray[4] = 0x0b;
+	priv->cck_txbbgain_table[17].ccktxbb_valuearray[5] = 0x07;
+	priv->cck_txbbgain_table[17].ccktxbb_valuearray[6] = 0x03;
+	priv->cck_txbbgain_table[17].ccktxbb_valuearray[7] = 0x02;
+
+	priv->cck_txbbgain_table[18].ccktxbb_valuearray[0] = 0x13;
+	priv->cck_txbbgain_table[18].ccktxbb_valuearray[1] = 0x13;
+	priv->cck_txbbgain_table[18].ccktxbb_valuearray[2] = 0x10;
+	priv->cck_txbbgain_table[18].ccktxbb_valuearray[3] = 0x0d;
+	priv->cck_txbbgain_table[18].ccktxbb_valuearray[4] = 0x0a;
+	priv->cck_txbbgain_table[18].ccktxbb_valuearray[5] = 0x06;
+	priv->cck_txbbgain_table[18].ccktxbb_valuearray[6] = 0x03;
+	priv->cck_txbbgain_table[18].ccktxbb_valuearray[7] = 0x01;
+
+	priv->cck_txbbgain_table[19].ccktxbb_valuearray[0] = 0x12;
+	priv->cck_txbbgain_table[19].ccktxbb_valuearray[1] = 0x12;
+	priv->cck_txbbgain_table[19].ccktxbb_valuearray[2] = 0x0f;
+	priv->cck_txbbgain_table[19].ccktxbb_valuearray[3] = 0x0c;
+	priv->cck_txbbgain_table[19].ccktxbb_valuearray[4] = 0x09;
+	priv->cck_txbbgain_table[19].ccktxbb_valuearray[5] = 0x06;
+	priv->cck_txbbgain_table[19].ccktxbb_valuearray[6] = 0x03;
+	priv->cck_txbbgain_table[19].ccktxbb_valuearray[7] = 0x01;
+
+	priv->cck_txbbgain_table[20].ccktxbb_valuearray[0] = 0x11;
+	priv->cck_txbbgain_table[20].ccktxbb_valuearray[1] = 0x11;
+	priv->cck_txbbgain_table[20].ccktxbb_valuearray[2] = 0x0f;
+	priv->cck_txbbgain_table[20].ccktxbb_valuearray[3] = 0x0c;
+	priv->cck_txbbgain_table[20].ccktxbb_valuearray[4] = 0x09;
+	priv->cck_txbbgain_table[20].ccktxbb_valuearray[5] = 0x06;
+	priv->cck_txbbgain_table[20].ccktxbb_valuearray[6] = 0x03;
+	priv->cck_txbbgain_table[20].ccktxbb_valuearray[7] = 0x01;
+
+	priv->cck_txbbgain_table[21].ccktxbb_valuearray[0] = 0x10;
+	priv->cck_txbbgain_table[21].ccktxbb_valuearray[1] = 0x10;
+	priv->cck_txbbgain_table[21].ccktxbb_valuearray[2] = 0x0e;
+	priv->cck_txbbgain_table[21].ccktxbb_valuearray[3] = 0x0b;
+	priv->cck_txbbgain_table[21].ccktxbb_valuearray[4] = 0x08;
+	priv->cck_txbbgain_table[21].ccktxbb_valuearray[5] = 0x05;
+	priv->cck_txbbgain_table[21].ccktxbb_valuearray[6] = 0x03;
+	priv->cck_txbbgain_table[21].ccktxbb_valuearray[7] = 0x01;
+
+	priv->cck_txbbgain_table[22].ccktxbb_valuearray[0] = 0x0f;
+	priv->cck_txbbgain_table[22].ccktxbb_valuearray[1] = 0x0f;
+	priv->cck_txbbgain_table[22].ccktxbb_valuearray[2] = 0x0d;
+	priv->cck_txbbgain_table[22].ccktxbb_valuearray[3] = 0x0b;
+	priv->cck_txbbgain_table[22].ccktxbb_valuearray[4] = 0x08;
+	priv->cck_txbbgain_table[22].ccktxbb_valuearray[5] = 0x05;
+	priv->cck_txbbgain_table[22].ccktxbb_valuearray[6] = 0x03;
+	priv->cck_txbbgain_table[22].ccktxbb_valuearray[7] = 0x01;
+
+	//ccktxbb_valuearray[0] is 0xA22 [1] is 0xA24 ...[7] is 0xA29
+	//This Table is for CH14
+	priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[0] = 0x36;
+	priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[1] = 0x35;
+	priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[2] = 0x2e;
+	priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[3] = 0x1b;
+	priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[0] = 0x33;
+	priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[1] = 0x32;
+	priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[2] = 0x2b;
+	priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[3] = 0x19;
+	priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[0] = 0x30;
+	priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[1] = 0x2f;
+	priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[2] = 0x29;
+	priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[3] = 0x18;
+	priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[0] = 0x2d;
+	priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[1] = 0x2d;
+	priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[2] = 0x27;
+	priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[3] = 0x17;
+	priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[0] = 0x2b;
+	priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[1] = 0x2a;
+	priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[2] = 0x25;
+	priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[3] = 0x15;
+	priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[0] = 0x28;
+	priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[1] = 0x28;
+	priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[2] = 0x22;
+	priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[3] = 0x14;
+	priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[0] = 0x26;
+	priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[1] = 0x25;
+	priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[2] = 0x21;
+	priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[3] = 0x13;
+	priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[0] = 0x24;
+	priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[1] = 0x23;
+	priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[2] = 0x1f;
+	priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[3] = 0x12;
+	priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[0] = 0x22;
+	priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[1] = 0x21;
+	priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[2] = 0x1d;
+	priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[3] = 0x11;
+	priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[0] = 0x20;
+	priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[1] = 0x20;
+	priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[2] = 0x1b;
+	priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[3] = 0x10;
+	priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[0] = 0x1f;
+	priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[1] = 0x1e;
+	priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[2] = 0x1a;
+	priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[3] = 0x0f;
+	priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[0] = 0x1d;
+	priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[1] = 0x1c;
+	priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[2] = 0x18;
+	priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[3] = 0x0e;
+	priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[0] = 0x1b;
+	priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[1] = 0x1a;
+	priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[2] = 0x17;
+	priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[3] = 0x0e;
+	priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[0] = 0x1a;
+	priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[1] = 0x19;
+	priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[2] = 0x16;
+	priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[3] = 0x0d;
+	priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[0] = 0x18;
+	priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[1] = 0x17;
+	priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[2] = 0x15;
+	priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[3] = 0x0c;
+	priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[0] = 0x17;
+	priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[1] = 0x16;
+	priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[2] = 0x13;
+	priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[3] = 0x0b;
+	priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[0] = 0x16;
+	priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[1] = 0x15;
+	priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[2] = 0x12;
+	priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[3] = 0x0b;
+	priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[0] = 0x14;
+	priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[1] = 0x14;
+	priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[2] = 0x11;
+	priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[3] = 0x0a;
+	priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[0] = 0x13;
+	priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[1] = 0x13;
+	priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[2] = 0x10;
+	priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[3] = 0x0a;
+	priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[0] = 0x12;
+	priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[1] = 0x12;
+	priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[2] = 0x0f;
+	priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[3] = 0x09;
+	priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[0] = 0x11;
+	priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[1] = 0x11;
+	priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[2] = 0x0f;
+	priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[3] = 0x09;
+	priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[0] = 0x10;
+	priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[1] = 0x10;
+	priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[2] = 0x0e;
+	priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[3] = 0x08;
+	priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[7] = 0x00;
+
+	priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[0] = 0x0f;
+	priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[1] = 0x0f;
+	priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[2] = 0x0d;
+	priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[3] = 0x08;
+	priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[4] = 0x00;
+	priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[5] = 0x00;
+	priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[6] = 0x00;
+	priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[7] = 0x00;
+
+	priv->btxpower_tracking = TRUE;
+	priv->txpower_count       = 0;
+	priv->btxpower_trackingInit = FALSE;
+
+}
+
+#ifndef RTL8192SU
+static void dm_InitializeTXPowerTracking_ThermalMeter(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	// Tx Power tracking by Theremal Meter require Firmware R/W 3-wire. This mechanism
+	// can be enabled only when Firmware R/W 3-wire is enabled. Otherwise, frequent r/w
+	// 3-wire by driver cause RF goes into wrong state.
+	if(priv->ieee80211->FwRWRF)
+		priv->btxpower_tracking = TRUE;
+	else
+		priv->btxpower_tracking = FALSE;
+	priv->txpower_count       = 0;
+	priv->btxpower_trackingInit = FALSE;
+}
+#endif
+
+void dm_initialize_txpower_tracking(struct net_device *dev)
+{
+#if (defined RTL8190P)
+	dm_InitializeTXPowerTracking_TSSI(dev);
+#elif (defined RTL8192SU)
+	// 2009/01/12 MH Enable for 92S series channel 1-14 CCK tx pwer setting for MP.
+	//
+	dm_InitializeTXPowerTracking_TSSI(dev);
+#else
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	if(priv->bDcut == TRUE)
+		dm_InitializeTXPowerTracking_TSSI(dev);
+	else
+		dm_InitializeTXPowerTracking_ThermalMeter(dev);
+#endif
+}// dm_InitializeTXPowerTracking
+
+
+static void dm_CheckTXPowerTracking_TSSI(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	static u32 tx_power_track_counter = 0;
+
+	if(!priv->btxpower_tracking)
+		return;
+	else
+	{
+	 	if((tx_power_track_counter % 30 == 0)&&(tx_power_track_counter != 0))
+	 	{
+	 		#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+				queue_delayed_work(priv->priv_wq,&priv->txpower_tracking_wq,0);
+			#else
+				#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+				schedule_task(&priv->txpower_tracking_wq);
+				#else
+				queue_work(priv->priv_wq,&priv->txpower_tracking_wq);
+				#endif
+			#endif
+	 	}
+		tx_power_track_counter++;
+	}
+
+}
+
+
+static void dm_CheckTXPowerTracking_ThermalMeter(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	static u8 	TM_Trigger=0;
+#if 0
+	u1Byte					i;
+	u4Byte tmpRegA;
+	for(i=0; i<50; i++)
+	{
+		tmpRegA = PHY_QueryRFReg(Adapter, RF90_PATH_A, 0x12, 0x078);	// 0x12: RF Reg[10:7]
+		PHY_SetRFReg(Adapter, RF90_PATH_A, 0x02, bMask12Bits, 0x4d);
+		//delay_us(100);
+		PHY_SetRFReg(Adapter, RF90_PATH_A, 0x02, bMask12Bits, 0x4f);
+		//delay_us(100);
+	}
+	DbgPrint("Trigger and readback ThermalMeter, write RF reg0x2 = 0x4d to 0x4f for 50 times\n");
+#else
+	//DbgPrint("dm_CheckTXPowerTracking() \n");
+	if(!priv->btxpower_tracking)
+		return;
+	else
+	{
+		if(priv->txpower_count  <= 2)
+		{
+			priv->txpower_count++;
+			return;
+		}
+	}
+
+	if(!TM_Trigger)
+	{
+		//Attention!! You have to wirte all 12bits data to RF, or it may cause RF to crash
+		//actually write reg0x02 bit1=0, then bit1=1.
+		//DbgPrint("Trigger ThermalMeter, write RF reg0x2 = 0x4d to 0x4f\n");
+#ifdef RTL8192SU
+		rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bRFRegOffsetMask, 0x4d);
+		rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bRFRegOffsetMask, 0x4f);
+		rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bRFRegOffsetMask, 0x4d);
+		rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bRFRegOffsetMask, 0x4f);
+#else
+		rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bMask12Bits, 0x4d);
+		rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bMask12Bits, 0x4f);
+		rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bMask12Bits, 0x4d);
+		rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bMask12Bits, 0x4f);
+#endif
+		TM_Trigger = 1;
+		return;
+	}
+	else
+	{
+		//DbgPrint("Schedule TxPowerTrackingWorkItem\n");
+		#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+			queue_delayed_work(priv->priv_wq,&priv->txpower_tracking_wq,0);
+		#else
+			#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+			schedule_task(&priv->txpower_tracking_wq);
+			#else
+			queue_work(priv->priv_wq,&priv->txpower_tracking_wq);
+			#endif
+		#endif
+		TM_Trigger = 0;
+	}
+#endif
+}
+
+
+static void dm_check_txpower_tracking(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//static u32 tx_power_track_counter = 0;
+
+#ifdef  RTL8190P
+	dm_CheckTXPowerTracking_TSSI(dev);
+#else
+	if(priv->bDcut == TRUE)
+		dm_CheckTXPowerTracking_TSSI(dev);
+	else
+		dm_CheckTXPowerTracking_ThermalMeter(dev);
+#endif
+
+}	// dm_CheckTXPowerTracking
+
+
+static void dm_CCKTxPowerAdjust_TSSI(struct net_device *dev, bool  bInCH14)
+{
+	u32 TempVal;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//Write 0xa22 0xa23
+	TempVal = 0;
+	if(!bInCH14){
+		//Write 0xa22 0xa23
+		TempVal = 	priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[0] +
+					(priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[1]<<8) ;
+
+		rtl8192_setBBreg(dev, rCCK0_TxFilter1,bMaskHWord, TempVal);
+		//Write 0xa24 ~ 0xa27
+		TempVal = 0;
+		TempVal = 	priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[2] +
+					(priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[3]<<8) +
+					(priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[4]<<16 )+
+					(priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[5]<<24);
+		rtl8192_setBBreg(dev, rCCK0_TxFilter2,bMaskDWord, TempVal);
+		//Write 0xa28  0xa29
+		TempVal = 0;
+		TempVal = 	priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[6] +
+					(priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[7]<<8) ;
+
+		rtl8192_setBBreg(dev, rCCK0_DebugPort,bMaskLWord, TempVal);
+	}
+	else
+	{
+		TempVal = 	priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[0] +
+					(priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[1]<<8) ;
+
+		rtl8192_setBBreg(dev, rCCK0_TxFilter1,bMaskHWord, TempVal);
+		//Write 0xa24 ~ 0xa27
+		TempVal = 0;
+		TempVal = 	priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[2] +
+					(priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[3]<<8) +
+					(priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[4]<<16 )+
+					(priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[5]<<24);
+		rtl8192_setBBreg(dev, rCCK0_TxFilter2,bMaskDWord, TempVal);
+		//Write 0xa28  0xa29
+		TempVal = 0;
+		TempVal = 	priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[6] +
+					(priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[7]<<8) ;
+
+		rtl8192_setBBreg(dev, rCCK0_DebugPort,bMaskLWord, TempVal);
+	}
+
+
+}
+
+static void dm_CCKTxPowerAdjust_ThermalMeter(struct net_device *dev,	bool  bInCH14)
+{
+	u32 TempVal;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	TempVal = 0;
+	if(!bInCH14)
+	{
+		//Write 0xa22 0xa23
+		TempVal = 	CCKSwingTable_Ch1_Ch13[priv->CCK_index][0] +
+					(CCKSwingTable_Ch1_Ch13[priv->CCK_index][1]<<8) ;
+		rtl8192_setBBreg(dev, rCCK0_TxFilter1, bMaskHWord, TempVal);
+		RT_TRACE(COMP_POWER_TRACKING, "CCK not chnl 14, reg 0x%x = 0x%x\n",
+			rCCK0_TxFilter1, TempVal);
+		//Write 0xa24 ~ 0xa27
+		TempVal = 0;
+		TempVal = 	CCKSwingTable_Ch1_Ch13[priv->CCK_index][2] +
+					(CCKSwingTable_Ch1_Ch13[priv->CCK_index][3]<<8) +
+					(CCKSwingTable_Ch1_Ch13[priv->CCK_index][4]<<16 )+
+					(CCKSwingTable_Ch1_Ch13[priv->CCK_index][5]<<24);
+		rtl8192_setBBreg(dev, rCCK0_TxFilter2, bMaskDWord, TempVal);
+		RT_TRACE(COMP_POWER_TRACKING, "CCK not chnl 14, reg 0x%x = 0x%x\n",
+			rCCK0_TxFilter2, TempVal);
+		//Write 0xa28  0xa29
+		TempVal = 0;
+		TempVal = 	CCKSwingTable_Ch1_Ch13[priv->CCK_index][6] +
+					(CCKSwingTable_Ch1_Ch13[priv->CCK_index][7]<<8) ;
+
+		rtl8192_setBBreg(dev, rCCK0_DebugPort, bMaskLWord, TempVal);
+		RT_TRACE(COMP_POWER_TRACKING, "CCK not chnl 14, reg 0x%x = 0x%x\n",
+			rCCK0_DebugPort, TempVal);
+	}
+	else
+	{
+//		priv->CCKTxPowerAdjustCntNotCh14++;	//cosa add for debug.
+		//Write 0xa22 0xa23
+		TempVal = 	CCKSwingTable_Ch14[priv->CCK_index][0] +
+					(CCKSwingTable_Ch14[priv->CCK_index][1]<<8) ;
+
+		rtl8192_setBBreg(dev, rCCK0_TxFilter1, bMaskHWord, TempVal);
+		RT_TRACE(COMP_POWER_TRACKING, "CCK chnl 14, reg 0x%x = 0x%x\n",
+			rCCK0_TxFilter1, TempVal);
+		//Write 0xa24 ~ 0xa27
+		TempVal = 0;
+		TempVal = 	CCKSwingTable_Ch14[priv->CCK_index][2] +
+					(CCKSwingTable_Ch14[priv->CCK_index][3]<<8) +
+					(CCKSwingTable_Ch14[priv->CCK_index][4]<<16 )+
+					(CCKSwingTable_Ch14[priv->CCK_index][5]<<24);
+		rtl8192_setBBreg(dev, rCCK0_TxFilter2, bMaskDWord, TempVal);
+		RT_TRACE(COMP_POWER_TRACKING, "CCK chnl 14, reg 0x%x = 0x%x\n",
+			rCCK0_TxFilter2, TempVal);
+		//Write 0xa28  0xa29
+		TempVal = 0;
+		TempVal = 	CCKSwingTable_Ch14[priv->CCK_index][6] +
+					(CCKSwingTable_Ch14[priv->CCK_index][7]<<8) ;
+
+		rtl8192_setBBreg(dev, rCCK0_DebugPort, bMaskLWord, TempVal);
+		RT_TRACE(COMP_POWER_TRACKING,"CCK chnl 14, reg 0x%x = 0x%x\n",
+			rCCK0_DebugPort, TempVal);
+	}
+}
+
+
+
+extern void dm_cck_txpower_adjust(
+	struct net_device *dev,
+	bool  binch14
+)
+{	// dm_CCKTxPowerAdjust
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+#ifdef RTL8190P
+	dm_CCKTxPowerAdjust_TSSI(dev, binch14);
+#else
+	if(priv->bDcut == TRUE)
+		dm_CCKTxPowerAdjust_TSSI(dev, binch14);
+	else
+		dm_CCKTxPowerAdjust_ThermalMeter(dev, binch14);
+#endif
+}
+
+
+#ifndef  RTL8192U
+static void dm_txpower_reset_recovery(
+	struct net_device *dev
+)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	RT_TRACE(COMP_POWER_TRACKING, "Start Reset Recovery ==>\n");
+	rtl8192_setBBreg(dev, rOFDM0_XATxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfa_txpowertrackingindex].txbbgain_value);
+	RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery: Fill in 0xc80 is %08x\n",priv->txbbgain_table[priv->rfa_txpowertrackingindex].txbbgain_value);
+	RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery: Fill in RFA_txPowerTrackingIndex is %x\n",priv->rfa_txpowertrackingindex);
+	RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery : RF A I/Q Amplify Gain is %ld\n",priv->txbbgain_table[priv->rfa_txpowertrackingindex].txbb_iq_amplifygain);
+	RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery: CCK Attenuation is %d dB\n",priv->cck_present_attentuation);
+	dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
+
+	rtl8192_setBBreg(dev, rOFDM0_XCTxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfc_txpowertrackingindex].txbbgain_value);
+	RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery: Fill in 0xc90 is %08x\n",priv->txbbgain_table[priv->rfc_txpowertrackingindex].txbbgain_value);
+	RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery: Fill in RFC_txPowerTrackingIndex is %x\n",priv->rfc_txpowertrackingindex);
+	RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery : RF C I/Q Amplify Gain is %ld\n",priv->txbbgain_table[priv->rfc_txpowertrackingindex].txbb_iq_amplifygain);
+
+}	// dm_TXPowerResetRecovery
+
+extern void dm_restore_dynamic_mechanism_state(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 	reg_ratr = priv->rate_adaptive.last_ratr;
+
+	if(!priv->up)
+	{
+		RT_TRACE(COMP_RATE, "<---- dm_restore_dynamic_mechanism_state(): driver is going to unload\n");
+		return;
+	}
+
+	//
+	// Restore previous state for rate adaptive
+	//
+	if(priv->rate_adaptive.rate_adaptive_disabled)
+		return;
+	// TODO: Only 11n mode is implemented currently,
+	if( !(priv->ieee80211->mode==WIRELESS_MODE_N_24G ||
+		 priv->ieee80211->mode==WIRELESS_MODE_N_5G))
+		 return;
+	{
+			/* 2007/11/15 MH Copy from 8190PCI. */
+			u32 ratr_value;
+			ratr_value = reg_ratr;
+			if(priv->rf_type == RF_1T2R)	// 1T2R, Spatial Stream 2 should be disabled
+			{
+				ratr_value &=~ (RATE_ALL_OFDM_2SS);
+				//DbgPrint("HW_VAR_TATR_0 from 0x%x ==> 0x%x\n", ((pu4Byte)(val))[0], ratr_value);
+			}
+			//DbgPrint("set HW_VAR_TATR_0 = 0x%x\n", ratr_value);
+			//cosa PlatformEFIOWrite4Byte(Adapter, RATR0, ((pu4Byte)(val))[0]);
+			write_nic_dword(dev, RATR0, ratr_value);
+			write_nic_byte(dev, UFWP, 1);
+#if 0		// Disable old code.
+			u1Byte index;
+			u4Byte input_value;
+			index = (u1Byte)((((pu4Byte)(val))[0]) >> 28);
+			input_value = (((pu4Byte)(val))[0]) & 0x0fffffff;
+			// TODO: Correct it. Emily 2007.01.11
+			PlatformEFIOWrite4Byte(Adapter, RATR0+index*4, input_value);
+#endif
+	}
+	//Resore TX Power Tracking Index
+	if(priv->btxpower_trackingInit && priv->btxpower_tracking){
+		dm_txpower_reset_recovery(dev);
+	}
+
+	//
+	//Restore BB Initial Gain
+	//
+	dm_bb_initialgain_restore(dev);
+
+}	// DM_RestoreDynamicMechanismState
+
+static void dm_bb_initialgain_restore(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 bit_mask = 0x7f; //Bit0~ Bit6
+
+	if(dm_digtable.dig_algorithm == DIG_ALGO_BY_RSSI)
+		return;
+
+	//Disable Initial Gain
+	//PHY_SetBBReg(Adapter, UFWP, bMaskLWord, 0x800);
+	rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8);	// Only clear byte 1 and rewrite.
+	rtl8192_setBBreg(dev, rOFDM0_XAAGCCore1, bit_mask, (u32)priv->initgain_backup.xaagccore1);
+	rtl8192_setBBreg(dev, rOFDM0_XBAGCCore1, bit_mask, (u32)priv->initgain_backup.xbagccore1);
+	rtl8192_setBBreg(dev, rOFDM0_XCAGCCore1, bit_mask, (u32)priv->initgain_backup.xcagccore1);
+	rtl8192_setBBreg(dev, rOFDM0_XDAGCCore1, bit_mask, (u32)priv->initgain_backup.xdagccore1);
+	bit_mask  = bMaskByte2;
+	rtl8192_setBBreg(dev, rCCK0_CCA, bit_mask, (u32)priv->initgain_backup.cca);
+
+	RT_TRACE(COMP_DIG, "dm_BBInitialGainRestore 0xc50 is %x\n",priv->initgain_backup.xaagccore1);
+	RT_TRACE(COMP_DIG, "dm_BBInitialGainRestore 0xc58 is %x\n",priv->initgain_backup.xbagccore1);
+	RT_TRACE(COMP_DIG, "dm_BBInitialGainRestore 0xc60 is %x\n",priv->initgain_backup.xcagccore1);
+	RT_TRACE(COMP_DIG, "dm_BBInitialGainRestore 0xc68 is %x\n",priv->initgain_backup.xdagccore1);
+	RT_TRACE(COMP_DIG, "dm_BBInitialGainRestore 0xa0a is %x\n",priv->initgain_backup.cca);
+	//Enable Initial Gain
+	//PHY_SetBBReg(Adapter, UFWP, bMaskLWord, 0x100);
+	rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x1);	// Only clear byte 1 and rewrite.
+
+}	// dm_BBInitialGainRestore
+
+
+extern void dm_backup_dynamic_mechanism_state(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	// Fsync to avoid reset
+	priv->bswitch_fsync  = false;
+	priv->bfsync_processing = false;
+	//Backup BB InitialGain
+	dm_bb_initialgain_backup(dev);
+
+}	// DM_BackupDynamicMechanismState
+
+
+static void dm_bb_initialgain_backup(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 bit_mask = bMaskByte0; //Bit0~ Bit6
+
+	if(dm_digtable.dig_algorithm == DIG_ALGO_BY_RSSI)
+		return;
+
+	//PHY_SetBBReg(Adapter, UFWP, bMaskLWord, 0x800);
+	rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8);	// Only clear byte 1 and rewrite.
+	priv->initgain_backup.xaagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XAAGCCore1, bit_mask);
+	priv->initgain_backup.xbagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XBAGCCore1, bit_mask);
+	priv->initgain_backup.xcagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XCAGCCore1, bit_mask);
+	priv->initgain_backup.xdagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XDAGCCore1, bit_mask);
+	bit_mask  = bMaskByte2;
+	priv->initgain_backup.cca = (u8)rtl8192_QueryBBReg(dev, rCCK0_CCA, bit_mask);
+
+	RT_TRACE(COMP_DIG, "BBInitialGainBackup 0xc50 is %x\n",priv->initgain_backup.xaagccore1);
+	RT_TRACE(COMP_DIG, "BBInitialGainBackup 0xc58 is %x\n",priv->initgain_backup.xbagccore1);
+	RT_TRACE(COMP_DIG, "BBInitialGainBackup 0xc60 is %x\n",priv->initgain_backup.xcagccore1);
+	RT_TRACE(COMP_DIG, "BBInitialGainBackup 0xc68 is %x\n",priv->initgain_backup.xdagccore1);
+	RT_TRACE(COMP_DIG, "BBInitialGainBackup 0xa0a is %x\n",priv->initgain_backup.cca);
+
+}   // dm_BBInitialGainBakcup
+
+#endif
+/*-----------------------------------------------------------------------------
+ * Function:	dm_change_dynamic_initgain_thresh()
+ *
+ * Overview:
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/29/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+extern void dm_change_dynamic_initgain_thresh(struct net_device *dev,
+								u32		dm_type,
+								u32		dm_value)
+{
+#ifdef RTL8192SU
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	if(dm_type == DIG_TYPE_THRESH_HIGHPWR_HIGH)
+		priv->MidHighPwrTHR_L2 = (u8)dm_value;
+	else if(dm_type == DIG_TYPE_THRESH_HIGHPWR_LOW)
+		priv->MidHighPwrTHR_L1 = (u8)dm_value;
+	return;
+#endif
+	if (dm_type == DIG_TYPE_THRESH_HIGH)
+	{
+		dm_digtable.rssi_high_thresh = dm_value;
+	}
+	else if (dm_type == DIG_TYPE_THRESH_LOW)
+	{
+		dm_digtable.rssi_low_thresh = dm_value;
+	}
+	else if (dm_type == DIG_TYPE_THRESH_HIGHPWR_HIGH)
+	{
+		dm_digtable.rssi_high_power_highthresh = dm_value;
+	}
+	else if (dm_type == DIG_TYPE_THRESH_HIGHPWR_HIGH)
+	{
+		dm_digtable.rssi_high_power_highthresh = dm_value;
+	}
+	else if (dm_type == DIG_TYPE_ENABLE)
+	{
+		dm_digtable.dig_state		= DM_STA_DIG_MAX;
+		dm_digtable.dig_enable_flag	= true;
+	}
+	else if (dm_type == DIG_TYPE_DISABLE)
+	{
+		dm_digtable.dig_state		= DM_STA_DIG_MAX;
+		dm_digtable.dig_enable_flag	= false;
+	}
+	else if (dm_type == DIG_TYPE_DBG_MODE)
+	{
+		if(dm_value >= DM_DBG_MAX)
+			dm_value = DM_DBG_OFF;
+		dm_digtable.dbg_mode		= (u8)dm_value;
+	}
+	else if (dm_type == DIG_TYPE_RSSI)
+	{
+		if(dm_value > 100)
+			dm_value = 30;
+		dm_digtable.rssi_val			= (long)dm_value;
+	}
+	else if (dm_type == DIG_TYPE_ALGORITHM)
+	{
+		if (dm_value >= DIG_ALGO_MAX)
+			dm_value = DIG_ALGO_BY_FALSE_ALARM;
+		if(dm_digtable.dig_algorithm != (u8)dm_value)
+			dm_digtable.dig_algorithm_switch = 1;
+		dm_digtable.dig_algorithm	= (u8)dm_value;
+	}
+	else if (dm_type == DIG_TYPE_BACKOFF)
+	{
+		if(dm_value > 30)
+			dm_value = 30;
+		dm_digtable.backoff_val		= (u8)dm_value;
+	}
+	else if(dm_type == DIG_TYPE_RX_GAIN_MIN)
+	{
+		if(dm_value == 0)
+			dm_value = 0x1;
+		dm_digtable.rx_gain_range_min = (u8)dm_value;
+	}
+	else if(dm_type == DIG_TYPE_RX_GAIN_MAX)
+	{
+		if(dm_value > 0x50)
+			dm_value = 0x50;
+		dm_digtable.rx_gain_range_max = (u8)dm_value;
+	}
+}	/* DM_ChangeDynamicInitGainThresh */
+extern	void
+dm_change_fsync_setting(
+	struct net_device *dev,
+	s32		DM_Type,
+	s32		DM_Value)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	if (DM_Type == 0)	// monitor 0xc38 register
+	{
+		if(DM_Value > 1)
+			DM_Value = 1;
+		priv->framesyncMonitor = (u8)DM_Value;
+		//DbgPrint("pHalData->framesyncMonitor = %d", pHalData->framesyncMonitor);
+	}
+}
+
+extern void
+dm_change_rxpath_selection_setting(
+	struct net_device *dev,
+	s32		DM_Type,
+	s32		DM_Value)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	prate_adaptive 	pRA = (prate_adaptive)&(priv->rate_adaptive);
+
+
+	if(DM_Type == 0)
+	{
+		if(DM_Value > 1)
+			DM_Value = 1;
+		DM_RxPathSelTable.Enable = (u8)DM_Value;
+	}
+	else if(DM_Type == 1)
+	{
+		if(DM_Value > 1)
+			DM_Value = 1;
+		DM_RxPathSelTable.DbgMode = (u8)DM_Value;
+	}
+	else if(DM_Type == 2)
+	{
+		if(DM_Value > 40)
+			DM_Value = 40;
+		DM_RxPathSelTable.SS_TH_low = (u8)DM_Value;
+	}
+	else if(DM_Type == 3)
+	{
+		if(DM_Value > 25)
+			DM_Value = 25;
+		DM_RxPathSelTable.diff_TH = (u8)DM_Value;
+	}
+	else if(DM_Type == 4)
+	{
+		if(DM_Value >= CCK_Rx_Version_MAX)
+			DM_Value = CCK_Rx_Version_1;
+		DM_RxPathSelTable.cck_method= (u8)DM_Value;
+	}
+	else if(DM_Type == 10)
+	{
+		if(DM_Value > 100)
+			DM_Value = 50;
+		DM_RxPathSelTable.rf_rssi[0] = (u8)DM_Value;
+	}
+	else if(DM_Type == 11)
+	{
+		if(DM_Value > 100)
+			DM_Value = 50;
+		DM_RxPathSelTable.rf_rssi[1] = (u8)DM_Value;
+	}
+	else if(DM_Type == 12)
+	{
+		if(DM_Value > 100)
+			DM_Value = 50;
+		DM_RxPathSelTable.rf_rssi[2] = (u8)DM_Value;
+	}
+	else if(DM_Type == 13)
+	{
+		if(DM_Value > 100)
+			DM_Value = 50;
+		DM_RxPathSelTable.rf_rssi[3] = (u8)DM_Value;
+	}
+	else if(DM_Type == 20)
+	{
+		if(DM_Value > 1)
+			DM_Value = 1;
+		pRA->ping_rssi_enable = (u8)DM_Value;
+	}
+	else if(DM_Type == 21)
+	{
+		if(DM_Value > 30)
+			DM_Value = 30;
+		pRA->ping_rssi_thresh_for_ra = DM_Value;
+	}
+}
+
+#if 0
+extern void dm_force_tx_fw_info(struct net_device *dev,
+										u32		force_type,
+										u32		force_value)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	if (force_type == 0)	// don't force TxSC
+	{
+		//DbgPrint("Set Force SubCarrier Off\n");
+		priv->tx_fwinfo_force_subcarriermode = 0;
+	}
+	else if(force_type == 1) //force
+	{
+		//DbgPrint("Set Force SubCarrier On\n");
+		priv->tx_fwinfo_force_subcarriermode = 1;
+		if(force_value > 3)
+			force_value = 3;
+		priv->tx_fwinfo_force_subcarrierval = (u8)force_value;
+	}
+}
+#endif
+
+/*-----------------------------------------------------------------------------
+ * Function:	dm_dig_init()
+ *
+ * Overview:	Set DIG scheme init value.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/15/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static void dm_dig_init(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	/* 2007/10/05 MH Disable DIG scheme now. Not tested. */
+	dm_digtable.dig_enable_flag	= true;
+	dm_digtable.dig_algorithm = DIG_ALGO_BY_RSSI;
+	dm_digtable.dbg_mode = DM_DBG_OFF;	//off=by real rssi value, on=by DM_DigTable.Rssi_val for new dig
+	dm_digtable.dig_algorithm_switch = 0;
+
+	/* 2007/10/04 MH Define init gain threshol. */
+	dm_digtable.dig_state		= DM_STA_DIG_MAX;
+	dm_digtable.dig_highpwr_state	= DM_STA_DIG_MAX;
+	dm_digtable.initialgain_lowerbound_state = false;
+
+	dm_digtable.rssi_low_thresh 	= DM_DIG_THRESH_LOW;
+	dm_digtable.rssi_high_thresh 	= DM_DIG_THRESH_HIGH;
+
+	dm_digtable.rssi_high_power_lowthresh = DM_DIG_HIGH_PWR_THRESH_LOW;
+	dm_digtable.rssi_high_power_highthresh = DM_DIG_HIGH_PWR_THRESH_HIGH;
+
+	dm_digtable.rssi_val = 50;	//for new dig debug rssi value
+	dm_digtable.backoff_val = DM_DIG_BACKOFF;
+	dm_digtable.rx_gain_range_max = DM_DIG_MAX;
+	if(priv->CustomerID == RT_CID_819x_Netcore)
+		dm_digtable.rx_gain_range_min = DM_DIG_MIN_Netcore;
+	else
+		dm_digtable.rx_gain_range_min = DM_DIG_MIN;
+
+}	/* dm_dig_init */
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	dm_ctrl_initgain_byrssi()
+ *
+ * Overview:	Driver must monitor RSSI and notify firmware to change initial
+ *				gain according to different threshold. BB team provide the
+ *				suggested solution.
+ *
+ * Input:			struct net_device *dev
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/27/2008	amy		Create Version 0 porting from windows code.
+ *---------------------------------------------------------------------------*/
+static void dm_ctrl_initgain_byrssi(struct net_device *dev)
+{
+
+	if (dm_digtable.dig_enable_flag == false)
+		return;
+
+	if(dm_digtable.dig_algorithm == DIG_ALGO_BY_FALSE_ALARM)
+		dm_ctrl_initgain_byrssi_by_fwfalse_alarm(dev);
+	else if(dm_digtable.dig_algorithm == DIG_ALGO_BY_RSSI)
+		dm_ctrl_initgain_byrssi_by_driverrssi(dev);
+//		;
+	else
+		return;
+}
+
+
+static void dm_ctrl_initgain_byrssi_by_driverrssi(
+	struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8 i;
+	static u8 	fw_dig=0;
+
+	if (dm_digtable.dig_enable_flag == false)
+		return;
+
+	//DbgPrint("Dig by Sw Rssi \n");
+	if(dm_digtable.dig_algorithm_switch)	// if swithed algorithm, we have to disable FW Dig.
+		fw_dig = 0;
+	if(fw_dig <= 3)	// execute several times to make sure the FW Dig is disabled
+	{// FW DIG Off
+		for(i=0; i<3; i++)
+			rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8);	// Only clear byte 1 and rewrite.
+		fw_dig++;
+		dm_digtable.dig_state = DM_STA_DIG_OFF;	//fw dig off.
+	}
+
+	if(priv->ieee80211->state == IEEE80211_LINKED)
+		dm_digtable.cur_connect_state = DIG_CONNECT;
+	else
+		dm_digtable.cur_connect_state = DIG_DISCONNECT;
+
+	//DbgPrint("DM_DigTable.PreConnectState = %d, DM_DigTable.CurConnectState = %d \n",
+		//DM_DigTable.PreConnectState, DM_DigTable.CurConnectState);
+
+	if(dm_digtable.dbg_mode == DM_DBG_OFF)
+		dm_digtable.rssi_val = priv->undecorated_smoothed_pwdb;
+	//DbgPrint("DM_DigTable.Rssi_val = %d \n", DM_DigTable.Rssi_val);
+	dm_initial_gain(dev);
+	dm_pd_th(dev);
+	dm_cs_ratio(dev);
+	if(dm_digtable.dig_algorithm_switch)
+		dm_digtable.dig_algorithm_switch = 0;
+	dm_digtable.pre_connect_state = dm_digtable.cur_connect_state;
+
+}	/* dm_CtrlInitGainByRssi */
+
+static void dm_ctrl_initgain_byrssi_by_fwfalse_alarm(
+	struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	static u32 reset_cnt = 0;
+	u8 i;
+
+	if (dm_digtable.dig_enable_flag == false)
+		return;
+
+	if(dm_digtable.dig_algorithm_switch)
+	{
+		dm_digtable.dig_state = DM_STA_DIG_MAX;
+		// Fw DIG On.
+		for(i=0; i<3; i++)
+			rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x1);	// Only clear byte 1 and rewrite.
+		dm_digtable.dig_algorithm_switch = 0;
+	}
+
+	if (priv->ieee80211->state != IEEE80211_LINKED)
+		return;
+
+	// For smooth, we can not change DIG state.
+	if ((priv->undecorated_smoothed_pwdb > dm_digtable.rssi_low_thresh) &&
+		(priv->undecorated_smoothed_pwdb < dm_digtable.rssi_high_thresh))
+	{
+		return;
+	}
+	//DbgPrint("Dig by Fw False Alarm\n");
+	//if (DM_DigTable.Dig_State == DM_STA_DIG_OFF)
+	/*DbgPrint("DIG Check\n\r RSSI=%d LOW=%d HIGH=%d STATE=%d",
+	pHalData->UndecoratedSmoothedPWDB, DM_DigTable.RssiLowThresh,
+	DM_DigTable.RssiHighThresh, DM_DigTable.Dig_State);*/
+	/* 1. When RSSI decrease, We have to judge if it is smaller than a treshold
+		  and then execute below step. */
+	if ((priv->undecorated_smoothed_pwdb <= dm_digtable.rssi_low_thresh))
+	{
+		/* 2008/02/05 MH When we execute silent reset, the DIG PHY parameters
+		   will be reset to init value. We must prevent the condition. */
+		if (dm_digtable.dig_state == DM_STA_DIG_OFF &&
+			(priv->reset_count == reset_cnt))
+		{
+			return;
+		}
+		else
+		{
+			reset_cnt = priv->reset_count;
+		}
+
+		// If DIG is off, DIG high power state must reset.
+		dm_digtable.dig_highpwr_state = DM_STA_DIG_MAX;
+		dm_digtable.dig_state = DM_STA_DIG_OFF;
+
+		// 1.1 DIG Off.
+		rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8);	// Only clear byte 1 and rewrite.
+
+		// 1.2 Set initial gain.
+		write_nic_byte(dev, rOFDM0_XAAGCCore1, 0x17);
+		write_nic_byte(dev, rOFDM0_XBAGCCore1, 0x17);
+		write_nic_byte(dev, rOFDM0_XCAGCCore1, 0x17);
+		write_nic_byte(dev, rOFDM0_XDAGCCore1, 0x17);
+
+		// 1.3 Lower PD_TH for OFDM.
+		if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
+		{
+			/* 2008/01/11 MH 40MHZ 90/92 register are not the same. */
+			// 2008/02/05 MH SD3-Jerry 92U/92E PD_TH are the same.
+#ifdef RTL8192SU
+			rtl8192_setBBreg(dev, (rOFDM0_XATxAFE+3), bMaskByte0, 0x00);
+#else
+			#ifdef RTL8190P
+				write_nic_byte(dev, rOFDM0_RxDetector1, 0x40);
+			#else
+				write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x00);
+			#endif
+#endif
+			/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
+				write_nic_byte(pAdapter, rOFDM0_RxDetector1, 0x40);
+			*/
+			//else if (pAdapter->HardwareType == HARDWARE_TYPE_RTL8192E)
+
+
+			//else
+				//PlatformEFIOWrite1Byte(pAdapter, rOFDM0_RxDetector1, 0x40);
+		}
+		else
+			write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
+
+		// 1.4 Lower CS ratio for CCK.
+		write_nic_byte(dev, 0xa0a, 0x08);
+
+		// 1.5 Higher EDCCA.
+		//PlatformEFIOWrite4Byte(pAdapter, rOFDM0_ECCAThreshold, 0x325);
+		return;
+
+	}
+
+	/* 2. When RSSI increase, We have to judge if it is larger than a treshold
+		  and then execute below step.  */
+	if ((priv->undecorated_smoothed_pwdb >= dm_digtable.rssi_high_thresh) )
+	{
+		u8 reset_flag = 0;
+
+		if (dm_digtable.dig_state == DM_STA_DIG_ON &&
+			(priv->reset_count == reset_cnt))
+		{
+			dm_ctrl_initgain_byrssi_highpwr(dev);
+			return;
+		}
+		else
+		{
+			if (priv->reset_count != reset_cnt)
+				reset_flag = 1;
+
+			reset_cnt = priv->reset_count;
+		}
+
+		dm_digtable.dig_state = DM_STA_DIG_ON;
+		//DbgPrint("DIG ON\n\r");
+
+		// 2.1 Set initial gain.
+		// 2008/02/26 MH SD3-Jerry suggest to prevent dirty environment.
+		if (reset_flag == 1)
+		{
+			write_nic_byte(dev, rOFDM0_XAAGCCore1, 0x2c);
+			write_nic_byte(dev, rOFDM0_XBAGCCore1, 0x2c);
+			write_nic_byte(dev, rOFDM0_XCAGCCore1, 0x2c);
+			write_nic_byte(dev, rOFDM0_XDAGCCore1, 0x2c);
+		}
+		else
+		{
+			write_nic_byte(dev, rOFDM0_XAAGCCore1, 0x20);
+			write_nic_byte(dev, rOFDM0_XBAGCCore1, 0x20);
+			write_nic_byte(dev, rOFDM0_XCAGCCore1, 0x20);
+			write_nic_byte(dev, rOFDM0_XDAGCCore1, 0x20);
+		}
+
+		// 2.2 Higher PD_TH for OFDM.
+		if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
+		{
+			/* 2008/01/11 MH 40MHZ 90/92 register are not the same. */
+			// 2008/02/05 MH SD3-Jerry 92U/92E PD_TH are the same.
+			#ifdef RTL8190P
+				write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
+			#else
+				write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x20);
+			#endif
+			/*
+			else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
+				write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
+			*/
+			//else if (pAdapter->HardwareType == HARDWARE_TYPE_RTL8192E)
+
+			//else
+				//PlatformEFIOWrite1Byte(pAdapter, rOFDM0_RxDetector1, 0x42);
+		}
+		else
+			write_nic_byte(dev, rOFDM0_RxDetector1, 0x44);
+
+		// 2.3 Higher CS ratio for CCK.
+		write_nic_byte(dev, 0xa0a, 0xcd);
+
+		// 2.4 Lower EDCCA.
+		/* 2008/01/11 MH 90/92 series are the same. */
+		//PlatformEFIOWrite4Byte(pAdapter, rOFDM0_ECCAThreshold, 0x346);
+
+		// 2.5 DIG On.
+		rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x1);	// Only clear byte 1 and rewrite.
+
+	}
+
+	dm_ctrl_initgain_byrssi_highpwr(dev);
+
+}	/* dm_CtrlInitGainByRssi */
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	dm_ctrl_initgain_byrssi_highpwr()
+ *
+ * Overview:
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/28/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static void dm_ctrl_initgain_byrssi_highpwr(
+	struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	static u32 reset_cnt_highpwr = 0;
+
+	// For smooth, we can not change high power DIG state in the range.
+	if ((priv->undecorated_smoothed_pwdb > dm_digtable.rssi_high_power_lowthresh) &&
+		(priv->undecorated_smoothed_pwdb < dm_digtable.rssi_high_power_highthresh))
+	{
+		return;
+	}
+
+	/* 3. When RSSI >75% or <70%, it is a high power issue. We have to judge if
+		  it is larger than a treshold and then execute below step.  */
+	// 2008/02/05 MH SD3-Jerry Modify PD_TH for high power issue.
+	if (priv->undecorated_smoothed_pwdb >= dm_digtable.rssi_high_power_highthresh)
+	{
+		if (dm_digtable.dig_highpwr_state == DM_STA_DIG_ON &&
+			(priv->reset_count == reset_cnt_highpwr))
+			return;
+		else
+			dm_digtable.dig_highpwr_state = DM_STA_DIG_ON;
+
+		// 3.1 Higher PD_TH for OFDM for high power state.
+		if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
+		{
+#ifdef RTL8192SU
+			rtl8192_setBBreg(dev, (rOFDM0_XATxAFE+3), bMaskByte0, 0x10);
+#else
+			#ifdef RTL8190P
+				write_nic_byte(dev, rOFDM0_RxDetector1, 0x41);
+			#else
+				write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x10);
+			#endif
+#endif
+			/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
+				write_nic_byte(dev, rOFDM0_RxDetector1, 0x41);
+			*/
+
+		}
+		else
+			write_nic_byte(dev, rOFDM0_RxDetector1, 0x43);
+	}
+	else
+	{
+		if (dm_digtable.dig_highpwr_state == DM_STA_DIG_OFF&&
+			(priv->reset_count == reset_cnt_highpwr))
+			return;
+		else
+			dm_digtable.dig_highpwr_state = DM_STA_DIG_OFF;
+
+		if (priv->undecorated_smoothed_pwdb < dm_digtable.rssi_high_power_lowthresh &&
+			 priv->undecorated_smoothed_pwdb >= dm_digtable.rssi_high_thresh)
+		{
+			// 3.2 Recover PD_TH for OFDM for normal power region.
+			if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
+			{
+				#ifdef RTL8190P
+					write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
+				#else
+					write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x20);
+				#endif
+				/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
+					write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
+				*/
+
+			}
+			else
+				write_nic_byte(dev, rOFDM0_RxDetector1, 0x44);
+		}
+	}
+
+	reset_cnt_highpwr = priv->reset_count;
+
+}	/* dm_CtrlInitGainByRssiHighPwr */
+
+
+static void dm_initial_gain(
+	struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8					initial_gain=0;
+	static u8				initialized=0, force_write=0;
+	static u32			reset_cnt=0;
+
+	if(dm_digtable.dig_algorithm_switch)
+	{
+		initialized = 0;
+		reset_cnt = 0;
+	}
+
+	if(dm_digtable.pre_connect_state == dm_digtable.cur_connect_state)
+	{
+		if(dm_digtable.cur_connect_state == DIG_CONNECT)
+		{
+			if((dm_digtable.rssi_val+10-dm_digtable.backoff_val) > dm_digtable.rx_gain_range_max)
+				dm_digtable.cur_ig_value = dm_digtable.rx_gain_range_max;
+			else if((dm_digtable.rssi_val+10-dm_digtable.backoff_val) < dm_digtable.rx_gain_range_min)
+				dm_digtable.cur_ig_value = dm_digtable.rx_gain_range_min;
+			else
+				dm_digtable.cur_ig_value = dm_digtable.rssi_val+10-dm_digtable.backoff_val;
+		}
+		else		//current state is disconnected
+		{
+			if(dm_digtable.cur_ig_value == 0)
+				dm_digtable.cur_ig_value = priv->DefaultInitialGain[0];
+			else
+				dm_digtable.cur_ig_value = dm_digtable.pre_ig_value;
+		}
+	}
+	else	// disconnected -> connected or connected -> disconnected
+	{
+		dm_digtable.cur_ig_value = priv->DefaultInitialGain[0];
+		dm_digtable.pre_ig_value = 0;
+	}
+	//DbgPrint("DM_DigTable.CurIGValue = 0x%x, DM_DigTable.PreIGValue = 0x%x\n", DM_DigTable.CurIGValue, DM_DigTable.PreIGValue);
+
+	// if silent reset happened, we should rewrite the values back
+	if(priv->reset_count != reset_cnt)
+	{
+		force_write = 1;
+		reset_cnt = priv->reset_count;
+	}
+
+	if(dm_digtable.pre_ig_value != read_nic_byte(dev, rOFDM0_XAAGCCore1))
+		force_write = 1;
+
+	{
+		if((dm_digtable.pre_ig_value != dm_digtable.cur_ig_value)
+			|| !initialized || force_write)
+		{
+			initial_gain = (u8)dm_digtable.cur_ig_value;
+			//DbgPrint("Write initial gain = 0x%x\n", initial_gain);
+			// Set initial gain.
+			write_nic_byte(dev, rOFDM0_XAAGCCore1, initial_gain);
+			write_nic_byte(dev, rOFDM0_XBAGCCore1, initial_gain);
+			write_nic_byte(dev, rOFDM0_XCAGCCore1, initial_gain);
+			write_nic_byte(dev, rOFDM0_XDAGCCore1, initial_gain);
+			dm_digtable.pre_ig_value = dm_digtable.cur_ig_value;
+			initialized = 1;
+			force_write = 0;
+		}
+	}
+}
+
+static void dm_pd_th(
+	struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	static u8				initialized=0, force_write=0;
+	static u32			reset_cnt = 0;
+
+	if(dm_digtable.dig_algorithm_switch)
+	{
+		initialized = 0;
+		reset_cnt = 0;
+	}
+
+	if(dm_digtable.pre_connect_state == dm_digtable.cur_connect_state)
+	{
+		if(dm_digtable.cur_connect_state == DIG_CONNECT)
+		{
+			if (dm_digtable.rssi_val >= dm_digtable.rssi_high_power_highthresh)
+				dm_digtable.curpd_thstate = DIG_PD_AT_HIGH_POWER;
+			else if ((dm_digtable.rssi_val <= dm_digtable.rssi_low_thresh))
+				dm_digtable.curpd_thstate = DIG_PD_AT_LOW_POWER;
+			else if ((dm_digtable.rssi_val >= dm_digtable.rssi_high_thresh) &&
+					(dm_digtable.rssi_val < dm_digtable.rssi_high_power_lowthresh))
+				dm_digtable.curpd_thstate = DIG_PD_AT_NORMAL_POWER;
+			else
+				dm_digtable.curpd_thstate = dm_digtable.prepd_thstate;
+		}
+		else
+		{
+			dm_digtable.curpd_thstate = DIG_PD_AT_LOW_POWER;
+		}
+	}
+	else	// disconnected -> connected or connected -> disconnected
+	{
+		dm_digtable.curpd_thstate = DIG_PD_AT_LOW_POWER;
+	}
+
+	// if silent reset happened, we should rewrite the values back
+	if(priv->reset_count != reset_cnt)
+	{
+		force_write = 1;
+		reset_cnt = priv->reset_count;
+	}
+
+	{
+		if((dm_digtable.prepd_thstate != dm_digtable.curpd_thstate) ||
+			(initialized<=3) || force_write)
+		{
+			//DbgPrint("Write PD_TH state = %d\n", DM_DigTable.CurPD_THState);
+			if(dm_digtable.curpd_thstate == DIG_PD_AT_LOW_POWER)
+			{
+				// Lower PD_TH for OFDM.
+				if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
+				{
+					/* 2008/01/11 MH 40MHZ 90/92 register are not the same. */
+					// 2008/02/05 MH SD3-Jerry 92U/92E PD_TH are the same.
+#ifdef RTL8192SU
+					rtl8192_setBBreg(dev, (rOFDM0_XATxAFE+3), bMaskByte0, 0x00);
+#else
+					#ifdef RTL8190P
+						write_nic_byte(dev, rOFDM0_RxDetector1, 0x40);
+					#else
+						write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x00);
+					#endif
+#endif
+					/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
+						write_nic_byte(dev, rOFDM0_RxDetector1, 0x40);
+					*/
+				}
+				else
+					write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
+			}
+			else if(dm_digtable.curpd_thstate == DIG_PD_AT_NORMAL_POWER)
+			{
+				// Higher PD_TH for OFDM.
+				if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
+				{
+					/* 2008/01/11 MH 40MHZ 90/92 register are not the same. */
+					// 2008/02/05 MH SD3-Jerry 92U/92E PD_TH are the same.
+					#ifdef RTL8190P
+						write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
+					#else
+						write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x20);
+					#endif
+					/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
+						write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
+					*/
+				}
+				else
+					write_nic_byte(dev, rOFDM0_RxDetector1, 0x44);
+			}
+			else if(dm_digtable.curpd_thstate == DIG_PD_AT_HIGH_POWER)
+			{
+				// Higher PD_TH for OFDM for high power state.
+				if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
+				{
+					#ifdef RTL8190P
+						write_nic_byte(dev, rOFDM0_RxDetector1, 0x41);
+					#else
+						write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x10);
+					#endif
+					/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
+						write_nic_byte(dev, rOFDM0_RxDetector1, 0x41);
+					*/
+				}
+				else
+					write_nic_byte(dev, rOFDM0_RxDetector1, 0x43);
+			}
+			dm_digtable.prepd_thstate = dm_digtable.curpd_thstate;
+			if(initialized <= 3)
+				initialized++;
+			force_write = 0;
+		}
+	}
+}
+
+static	void dm_cs_ratio(
+	struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	static u8				initialized=0,force_write=0;
+	static u32			reset_cnt = 0;
+
+	if(dm_digtable.dig_algorithm_switch)
+	{
+		initialized = 0;
+		reset_cnt = 0;
+	}
+
+	if(dm_digtable.pre_connect_state == dm_digtable.cur_connect_state)
+	{
+		if(dm_digtable.cur_connect_state == DIG_CONNECT)
+		{
+			if ((dm_digtable.rssi_val <= dm_digtable.rssi_low_thresh))
+				dm_digtable.curcs_ratio_state = DIG_CS_RATIO_LOWER;
+			else if ((dm_digtable.rssi_val >= dm_digtable.rssi_high_thresh) )
+				dm_digtable.curcs_ratio_state = DIG_CS_RATIO_HIGHER;
+			else
+				dm_digtable.curcs_ratio_state = dm_digtable.precs_ratio_state;
+		}
+		else
+		{
+			dm_digtable.curcs_ratio_state = DIG_CS_RATIO_LOWER;
+		}
+	}
+	else	// disconnected -> connected or connected -> disconnected
+	{
+		dm_digtable.curcs_ratio_state = DIG_CS_RATIO_LOWER;
+	}
+
+	// if silent reset happened, we should rewrite the values back
+	if(priv->reset_count != reset_cnt)
+	{
+		force_write = 1;
+		reset_cnt = priv->reset_count;
+	}
+
+
+	{
+		if((dm_digtable.precs_ratio_state != dm_digtable.curcs_ratio_state) ||
+			!initialized || force_write)
+		{
+			//DbgPrint("Write CS_ratio state = %d\n", DM_DigTable.CurCS_ratioState);
+			if(dm_digtable.curcs_ratio_state == DIG_CS_RATIO_LOWER)
+			{
+				// Lower CS ratio for CCK.
+				write_nic_byte(dev, 0xa0a, 0x08);
+			}
+			else if(dm_digtable.curcs_ratio_state == DIG_CS_RATIO_HIGHER)
+			{
+				// Higher CS ratio for CCK.
+				write_nic_byte(dev, 0xa0a, 0xcd);
+			}
+			dm_digtable.precs_ratio_state = dm_digtable.curcs_ratio_state;
+			initialized = 1;
+			force_write = 0;
+		}
+	}
+}
+
+extern void dm_init_edca_turbo(struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	priv->bcurrent_turbo_EDCA = false;
+	priv->ieee80211->bis_any_nonbepkts = false;
+	priv->bis_cur_rdlstate = false;
+}	// dm_init_edca_turbo
+
+#if 1
+static void dm_check_edca_turbo(
+	struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	PRT_HIGH_THROUGHPUT	pHTInfo = priv->ieee80211->pHTInfo;
+	//PSTA_QOS			pStaQos = pMgntInfo->pStaQos;
+
+	// Keep past Tx/Rx packet count for RT-to-RT EDCA turbo.
+	static unsigned long			lastTxOkCnt = 0;
+	static unsigned long			lastRxOkCnt = 0;
+	unsigned long				curTxOkCnt = 0;
+	unsigned long				curRxOkCnt = 0;
+
+	//
+	// Do not be Turbo if it's under WiFi config and Qos Enabled, because the EDCA parameters
+	// should follow the settings from QAP. By Bruce, 2007-12-07.
+	//
+	#if 1
+	if(priv->ieee80211->state != IEEE80211_LINKED)
+		goto dm_CheckEdcaTurbo_EXIT;
+	#endif
+	// We do not turn on EDCA turbo mode for some AP that has IOT issue
+	if(priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_EDCA_TURBO)
+		goto dm_CheckEdcaTurbo_EXIT;
+
+	{
+		u8* peername[11] = {"unknown", "realtek", "realtek_92se", "broadcom", "ralink", "atheros", "cisco", "marvell", "92u_softap", "self_softap"};
+		static int wb_tmp = 0;
+		if (wb_tmp == 0){
+			printk("%s():iot peer is %#x:%s, bssid:"MAC_FMT"\n",__FUNCTION__,pHTInfo->IOTPeer,peername[pHTInfo->IOTPeer], MAC_ARG(priv->ieee80211->current_network.bssid));
+			wb_tmp = 1;
+		}
+	}
+	// Check the status for current condition.
+	if(!priv->ieee80211->bis_any_nonbepkts)
+	{
+		curTxOkCnt = priv->stats.txbytesunicast - lastTxOkCnt;
+		curRxOkCnt = priv->stats.rxbytesunicast - lastRxOkCnt;
+#ifdef RTL8192SU
+		// Modify EDCA parameters selection bias
+		// For some APs, use downlink EDCA parameters for uplink+downlink
+		if(priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_EDCA_BIAS_ON_RX)
+		{
+			if(curTxOkCnt > 4*curRxOkCnt)
+			{
+				if(priv->bis_cur_rdlstate || !priv->bcurrent_turbo_EDCA)
+				{
+					write_nic_dword(dev, EDCAPARA_BE, edca_setting_UL[pHTInfo->IOTPeer]);
+					priv->bis_cur_rdlstate = false;
+				}
+			}
+			else
+			{
+				if(!priv->bis_cur_rdlstate || !priv->bcurrent_turbo_EDCA)
+				{
+					write_nic_dword(dev, EDCAPARA_BE, edca_setting_DL[pHTInfo->IOTPeer]);
+					priv->bis_cur_rdlstate = true;
+				}
+			}
+			priv->bcurrent_turbo_EDCA = true;
+		}
+		else
+		{
+			if(curRxOkCnt > 4*curTxOkCnt)
+			{
+				if(!priv->bis_cur_rdlstate || !priv->bcurrent_turbo_EDCA)
+				{
+					write_nic_dword(dev, EDCAPARA_BE, edca_setting_DL[pHTInfo->IOTPeer]);
+					priv->bis_cur_rdlstate = true;
+				}
+			}
+			else
+			{
+				if(priv->bis_cur_rdlstate || !priv->bcurrent_turbo_EDCA)
+				{
+					write_nic_dword(dev, EDCAPARA_BE, edca_setting_UL[pHTInfo->IOTPeer]);
+					priv->bis_cur_rdlstate = false;
+				}
+			}
+			priv->bcurrent_turbo_EDCA = true;
+		}
+#else
+		// For RT-AP, we needs to turn it on when Rx>Tx
+		if(curRxOkCnt > 4*curTxOkCnt)
+		{
+			//printk("%s():curRxOkCnt > 4*curTxOkCnt\n");
+			if(!priv->bis_cur_rdlstate || !priv->bcurrent_turbo_EDCA)
+			{
+				write_nic_dword(dev, EDCAPARA_BE, edca_setting_DL[pHTInfo->IOTPeer]);
+				priv->bis_cur_rdlstate = true;
+			}
+		}
+		else
+		{
+
+			//printk("%s():curRxOkCnt < 4*curTxOkCnt\n");
+			if(priv->bis_cur_rdlstate || !priv->bcurrent_turbo_EDCA)
+			{
+				write_nic_dword(dev, EDCAPARA_BE, edca_setting_UL[pHTInfo->IOTPeer]);
+				priv->bis_cur_rdlstate = false;
+			}
+
+		}
+
+		priv->bcurrent_turbo_EDCA = true;
+#endif
+	}
+	else
+	{
+		//
+		// Turn Off EDCA turbo here.
+		// Restore original EDCA according to the declaration of AP.
+		//
+		 if(priv->bcurrent_turbo_EDCA)
+		{
+
+			{
+				u8		u1bAIFS;
+				u32		u4bAcParam;
+				struct ieee80211_qos_parameters *qos_parameters = &priv->ieee80211->current_network.qos_data.parameters;
+				u8 mode = priv->ieee80211->mode;
+
+			// For Each time updating EDCA parameter, reset EDCA turbo mode status.
+				dm_init_edca_turbo(dev);
+				u1bAIFS = qos_parameters->aifs[0] * ((mode&(IEEE_G|IEEE_N_24G)) ?9:20) + aSifsTime;
+				u4bAcParam = ((((u32)(qos_parameters->tx_op_limit[0]))<< AC_PARAM_TXOP_LIMIT_OFFSET)|
+					(((u32)(qos_parameters->cw_max[0]))<< AC_PARAM_ECW_MAX_OFFSET)|
+					(((u32)(qos_parameters->cw_min[0]))<< AC_PARAM_ECW_MIN_OFFSET)|
+					((u32)u1bAIFS << AC_PARAM_AIFS_OFFSET));
+			//write_nic_dword(dev, WDCAPARA_ADD[i], u4bAcParam);
+				write_nic_dword(dev, EDCAPARA_BE,  u4bAcParam);
+
+			// Check ACM bit.
+			// If it is set, immediately set ACM control bit to downgrading AC for passing WMM testplan. Annie, 2005-12-13.
+				{
+			// TODO:  Modified this part and try to set acm control in only 1 IO processing!!
+
+					PACI_AIFSN	pAciAifsn = (PACI_AIFSN)&(qos_parameters->aifs[0]);
+					u8		AcmCtrl = read_nic_byte( dev, AcmHwCtrl );
+					if( pAciAifsn->f.ACM )
+					{ // ACM bit is 1.
+						AcmCtrl |= AcmHw_BeqEn;
+					}
+					else
+					{ // ACM bit is 0.
+						AcmCtrl &= (~AcmHw_BeqEn);
+					}
+
+					RT_TRACE( COMP_QOS,"SetHwReg8190pci(): [HW_VAR_ACM_CTRL] Write 0x%X\n", AcmCtrl ) ;
+					write_nic_byte(dev, AcmHwCtrl, AcmCtrl );
+				}
+			}
+			priv->bcurrent_turbo_EDCA = false;
+		}
+	}
+
+
+dm_CheckEdcaTurbo_EXIT:
+	// Set variables for next time.
+	priv->ieee80211->bis_any_nonbepkts = false;
+	lastTxOkCnt = priv->stats.txbytesunicast;
+	lastRxOkCnt = priv->stats.rxbytesunicast;
+}	// dm_CheckEdcaTurbo
+#endif
+
+extern void DM_CTSToSelfSetting(struct net_device * dev,u32 DM_Type, u32 DM_Value)
+{
+	struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
+
+	if (DM_Type == 0)	// CTS to self disable/enable
+	{
+		if(DM_Value > 1)
+			DM_Value = 1;
+		priv->ieee80211->bCTSToSelfEnable = (bool)DM_Value;
+		//DbgPrint("pMgntInfo->bCTSToSelfEnable = %d\n", pMgntInfo->bCTSToSelfEnable);
+	}
+	else if(DM_Type == 1) //CTS to self Th
+	{
+		if(DM_Value >= 50)
+			DM_Value = 50;
+		priv->ieee80211->CTSToSelfTH = (u8)DM_Value;
+		//DbgPrint("pMgntInfo->CTSToSelfTH = %d\n", pMgntInfo->CTSToSelfTH);
+	}
+}
+
+static void dm_init_ctstoself(struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
+
+	priv->ieee80211->bCTSToSelfEnable = TRUE;
+	priv->ieee80211->CTSToSelfTH = CTSToSelfTHVal;
+}
+
+static void dm_ctstoself(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
+	PRT_HIGH_THROUGHPUT	pHTInfo = priv->ieee80211->pHTInfo;
+	static unsigned long				lastTxOkCnt = 0;
+	static unsigned long				lastRxOkCnt = 0;
+	unsigned long						curTxOkCnt = 0;
+	unsigned long						curRxOkCnt = 0;
+
+	if(priv->ieee80211->bCTSToSelfEnable != TRUE)
+	{
+		pHTInfo->IOTAction &= ~HT_IOT_ACT_FORCED_CTS2SELF;
+		return;
+	}
+	/*
+	1. Uplink
+	2. Linksys350/Linksys300N
+	3. <50 disable, >55 enable
+	*/
+
+	if(pHTInfo->IOTPeer == HT_IOT_PEER_BROADCOM)
+	{
+		curTxOkCnt = priv->stats.txbytesunicast - lastTxOkCnt;
+		curRxOkCnt = priv->stats.rxbytesunicast - lastRxOkCnt;
+		if(curRxOkCnt > 4*curTxOkCnt)	//downlink, disable CTS to self
+		{
+			pHTInfo->IOTAction &= ~HT_IOT_ACT_FORCED_CTS2SELF;
+			//DbgPrint("dm_CTSToSelf() ==> CTS to self disabled -- downlink\n");
+		}
+		else	//uplink
+		{
+		#if 1
+			pHTInfo->IOTAction |= HT_IOT_ACT_FORCED_CTS2SELF;
+		#else
+			if(priv->undecorated_smoothed_pwdb < priv->ieee80211->CTSToSelfTH)	// disable CTS to self
+			{
+				pHTInfo->IOTAction &= ~HT_IOT_ACT_FORCED_CTS2SELF;
+				//DbgPrint("dm_CTSToSelf() ==> CTS to self disabled\n");
+			}
+			else if(priv->undecorated_smoothed_pwdb >= (priv->ieee80211->CTSToSelfTH+5))	// enable CTS to self
+			{
+				pHTInfo->IOTAction |= HT_IOT_ACT_FORCED_CTS2SELF;
+				//DbgPrint("dm_CTSToSelf() ==> CTS to self enabled\n");
+			}
+		#endif
+		}
+
+		lastTxOkCnt = priv->stats.txbytesunicast;
+		lastRxOkCnt = priv->stats.rxbytesunicast;
+	}
+}
+
+
+#if 0
+/*-----------------------------------------------------------------------------
+ * Function:	dm_rf_operation_test_callback()
+ *
+ * Overview:	Only for RF operation test now.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/29/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+extern void dm_rf_operation_test_callback(unsigned long dev)
+{
+//	struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
+	u8 erfpath;
+
+
+	for(erfpath=0; erfpath<4; erfpath++)
+	{
+		//DbgPrint("Set RF-%d\n\r", eRFPath);
+		//PHY_SetRFReg(Adapter, (RF90_RADIO_PATH_E)eRFPath, 0x2c, bMask12Bits, 0x3d7);
+		udelay(100);
+	}
+
+	{
+		//PlatformSetPeriodicTimer(Adapter, &pHalData->RfTest1Timer, 500);
+	}
+
+	// For test
+	{
+		//u8 i;
+		//PlatformSetPeriodicTimer(Adapter, &pHalData->RfTest1Timer, 500);
+#if 0
+		for(i=0; i<50; i++)
+		{
+			// Write Test
+			PHY_SetRFReg(Adapter, RF90_PATH_A, 0x02, bMask12Bits, 0x4d);
+			//delay_us(100);
+			PHY_SetRFReg(Adapter, RF90_PATH_A, 0x02, bMask12Bits, 0x4f);
+			//delay_us(100);
+			PHY_SetRFReg(Adapter, RF90_PATH_C, 0x02, bMask12Bits, 0x4d);
+			//delay_us(100);
+			PHY_SetRFReg(Adapter, RF90_PATH_C, 0x02, bMask12Bits, 0x4f);
+			//delay_us(100);
+
+#if 0
+			// Read test
+			PHY_QueryRFReg(Adapter, RF90_PATH_A, 0x02, bMask12Bits);
+			//delay_us(100);
+			PHY_QueryRFReg(Adapter, RF90_PATH_A, 0x02, bMask12Bits);
+			//delay_us(100);
+			PHY_QueryRFReg(Adapter, RF90_PATH_A, 0x12, bMask12Bits);
+			//delay_us(100);
+			PHY_QueryRFReg(Adapter, RF90_PATH_A, 0x12, bMask12Bits);
+			//delay_us(100);
+			PHY_QueryRFReg(Adapter, RF90_PATH_A, 0x21, bMask12Bits);
+			//delay_us(100);
+			PHY_QueryRFReg(Adapter, RF90_PATH_A, 0x21, bMask12Bits);
+			//delay_us(100);
+#endif
+		}
+#endif
+	}
+
+}	/* DM_RfOperationTestCallBack */
+#endif
+
+/*-----------------------------------------------------------------------------
+ * Function:	dm_check_rfctrl_gpio()
+ *
+ * Overview:	Copy 8187B template for 9xseries.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/28/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+#if 1
+static void dm_check_rfctrl_gpio(struct net_device * dev)
+{
+	//struct r8192_priv *priv = ieee80211_priv(dev);
+
+	// Walk around for DTM test, we will not enable HW - radio on/off because r/w
+	// page 1 register before Lextra bus is enabled cause system fails when resuming
+	// from S4. 20080218, Emily
+
+	// Stop to execute workitem to prevent S3/S4 bug.
+#ifdef RTL8190P
+	return;
+#endif
+#ifdef RTL8192U
+	return;
+#endif
+#ifdef RTL8192SU
+	return;
+#endif
+#ifdef RTL8192E
+	#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+		queue_delayed_work(priv->priv_wq,&priv->gpio_change_rf_wq,0);
+	#else
+		#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+		schedule_task(&priv->gpio_change_rf_wq);
+             #else
+		queue_work(priv->priv_wq,&priv->gpio_change_rf_wq);
+		#endif
+	#endif
+#endif
+
+}	/* dm_CheckRfCtrlGPIO */
+
+#endif
+/*-----------------------------------------------------------------------------
+ * Function:	dm_check_pbc_gpio()
+ *
+ * Overview:	Check if PBC button is pressed.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/28/2008	amy 	Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static	void	dm_check_pbc_gpio(struct net_device *dev)
+{
+#ifdef RTL8192U
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8 tmp1byte;
+
+
+	tmp1byte = read_nic_byte(dev,GPI);
+	if(tmp1byte == 0xff)
+		return;
+
+	if (tmp1byte&BIT6 || tmp1byte&BIT0)
+	{
+		// Here we only set bPbcPressed to TRUE
+		// After trigger PBC, the variable will be set to FALSE
+		RT_TRACE(COMP_IO, "CheckPbcGPIO - PBC is pressed\n");
+		priv->bpbc_pressed = true;
+	}
+#endif
+#ifdef RTL8192SU
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8	tmp1byte;
+
+	write_nic_byte(dev, MAC_PINMUX_CFG, (GPIOMUX_EN | GPIOSEL_GPIO));
+
+	tmp1byte = read_nic_byte(dev, GPIO_IO_SEL);
+	tmp1byte &= ~(HAL_8192S_HW_GPIO_WPS_BIT);
+	write_nic_byte(dev, GPIO_IO_SEL, tmp1byte);
+
+	tmp1byte = read_nic_byte(dev, GPIO_IN);
+
+	RT_TRACE(COMP_IO, "CheckPbcGPIO - %x\n", tmp1byte);
+
+	// Add by hpfan 2008.07.07 to fix read GPIO error from S3
+	if (tmp1byte == 0xff)
+		return ;
+
+	if (tmp1byte&HAL_8192S_HW_GPIO_WPS_BIT)
+	{
+		// Here we only set bPbcPressed to TRUE
+		// After trigger PBC, the variable will be set to FALSE
+		RT_TRACE(COMP_IO, "CheckPbcGPIO - PBC is pressed\n");
+		priv->bpbc_pressed = true;
+	}
+
+#endif
+
+
+}
+
+#ifdef RTL8192E
+
+/*-----------------------------------------------------------------------------
+ * Function:	dm_GPIOChangeRF
+ * Overview:	PCI will not support workitem call back HW radio on-off control.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	02/21/2008	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+ #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern	void	dm_gpio_change_rf_callback(struct work_struct *work)
+{
+	struct delayed_work *dwork = container_of(work,struct delayed_work,work);
+       struct r8192_priv *priv = container_of(dwork,struct r8192_priv,gpio_change_rf_wq);
+       struct net_device *dev = priv->ieee80211->dev;
+#else
+extern	void	dm_gpio_change_rf_callback(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+#endif
+	u8 tmp1byte;
+	RT_RF_POWER_STATE	eRfPowerStateToSet;
+	bool bActuallySet = false;
+
+	do{
+		bActuallySet=false;
+
+		if(!priv->up)
+		{
+			RT_TRACE((COMP_INIT | COMP_POWER | COMP_RF),"dm_gpio_change_rf_callback(): Callback function breaks out!!\n");
+		}
+		else
+		{
+			// 0x108 GPIO input register is read only
+			//set 0x108 B1= 1: RF-ON; 0: RF-OFF.
+			tmp1byte = read_nic_byte(dev,GPI);
+
+			eRfPowerStateToSet = (tmp1byte&BIT1) ?  eRfOn : eRfOff;
+
+			if( (priv->bHwRadioOff == true) && (eRfPowerStateToSet == eRfOn))
+			{
+				RT_TRACE(COMP_RF, "gpiochangeRF  - HW Radio ON\n");
+
+				priv->bHwRadioOff = false;
+				bActuallySet = true;
+			}
+			else if ( (priv->bHwRadioOff == false) && (eRfPowerStateToSet == eRfOff))
+			{
+				RT_TRACE(COMP_RF, "gpiochangeRF  - HW Radio OFF\n");
+				priv->bHwRadioOff = true;
+				bActuallySet = true;
+			}
+
+			if(bActuallySet)
+			{
+				#ifdef TO_DO
+				MgntActSet_RF_State(dev, eRfPowerStateToSet, RF_CHANGE_BY_HW);
+				//DrvIFIndicateCurrentPhyStatus(pAdapter);
+				#endif
+			}
+			else
+			{
+				msleep(2000);
+			}
+
+		}
+	}while(TRUE)
+
+}	/* dm_GPIOChangeRF */
+
+#endif
+/*-----------------------------------------------------------------------------
+ * Function:	DM_RFPathCheckWorkItemCallBack()
+ *
+ * Overview:	Check if Current RF RX path is enabled
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	01/30/2008	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern	void	dm_rf_pathcheck_workitemcallback(struct work_struct *work)
+{
+	struct delayed_work *dwork = container_of(work,struct delayed_work,work);
+       struct r8192_priv *priv = container_of(dwork,struct r8192_priv,rfpath_check_wq);
+       struct net_device *dev =priv->ieee80211->dev;
+#else
+extern	void	dm_rf_pathcheck_workitemcallback(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+#endif
+	//bool bactually_set = false;
+	u8 rfpath = 0, i;
+
+
+	/* 2008/01/30 MH After discussing with SD3 Jerry, 0xc04/0xd04 register will
+	   always be the same. We only read 0xc04 now. */
+	rfpath = read_nic_byte(dev, 0xc04);
+
+	// Check Bit 0-3, it means if RF A-D is enabled.
+	for (i = 0; i < RF90_PATH_MAX; i++)
+	{
+		if (rfpath & (0x01<<i))
+			priv->brfpath_rxenable[i] = 1;
+		else
+			priv->brfpath_rxenable[i] = 0;
+	}
+	if(!DM_RxPathSelTable.Enable)
+		return;
+
+	dm_rxpath_sel_byrssi(dev);
+}	/* DM_RFPathCheckWorkItemCallBack */
+
+static void dm_init_rxpath_selection(struct net_device * dev)
+{
+	u8 i;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	DM_RxPathSelTable.Enable = 1;	//default enabled
+	DM_RxPathSelTable.SS_TH_low = RxPathSelection_SS_TH_low;
+	DM_RxPathSelTable.diff_TH = RxPathSelection_diff_TH;
+	if(priv->CustomerID == RT_CID_819x_Netcore)
+		DM_RxPathSelTable.cck_method = CCK_Rx_Version_2;
+	else
+		DM_RxPathSelTable.cck_method = CCK_Rx_Version_1;
+	DM_RxPathSelTable.DbgMode = DM_DBG_OFF;
+	DM_RxPathSelTable.disabledRF = 0;
+	for(i=0; i<4; i++)
+	{
+		DM_RxPathSelTable.rf_rssi[i] = 50;
+		DM_RxPathSelTable.cck_pwdb_sta[i] = -64;
+		DM_RxPathSelTable.rf_enable_rssi_th[i] = 100;
+	}
+}
+
+static void dm_rxpath_sel_byrssi(struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8				i, max_rssi_index=0, min_rssi_index=0, sec_rssi_index=0, rf_num=0;
+	u8				tmp_max_rssi=0, tmp_min_rssi=0, tmp_sec_rssi=0;
+	u8				cck_default_Rx=0x2;	//RF-C
+	u8				cck_optional_Rx=0x3;//RF-D
+	long				tmp_cck_max_pwdb=0, tmp_cck_min_pwdb=0, tmp_cck_sec_pwdb=0;
+	u8				cck_rx_ver2_max_index=0, cck_rx_ver2_min_index=0, cck_rx_ver2_sec_index=0;
+	u8				cur_rf_rssi;
+	long				cur_cck_pwdb;
+	static u8			disabled_rf_cnt=0, cck_Rx_Path_initialized=0;
+	u8				update_cck_rx_path;
+
+	if(priv->rf_type != RF_2T4R)
+		return;
+
+	if(!cck_Rx_Path_initialized)
+	{
+		DM_RxPathSelTable.cck_Rx_path = (read_nic_byte(dev, 0xa07)&0xf);
+		cck_Rx_Path_initialized = 1;
+	}
+
+	DM_RxPathSelTable.disabledRF = 0xf;
+	DM_RxPathSelTable.disabledRF &=~ (read_nic_byte(dev, 0xc04));
+
+	if(priv->ieee80211->mode == WIRELESS_MODE_B)
+	{
+		DM_RxPathSelTable.cck_method = CCK_Rx_Version_2;	//pure B mode, fixed cck version2
+		//DbgPrint("Pure B mode, use cck rx version2 \n");
+	}
+
+	//decide max/sec/min rssi index
+	for (i=0; i<RF90_PATH_MAX; i++)
+	{
+		if(!DM_RxPathSelTable.DbgMode)
+			DM_RxPathSelTable.rf_rssi[i] = priv->stats.rx_rssi_percentage[i];
+
+		if(priv->brfpath_rxenable[i])
+		{
+			rf_num++;
+			cur_rf_rssi = DM_RxPathSelTable.rf_rssi[i];
+
+			if(rf_num == 1)	// find first enabled rf path and the rssi values
+			{	//initialize, set all rssi index to the same one
+				max_rssi_index = min_rssi_index = sec_rssi_index = i;
+				tmp_max_rssi = tmp_min_rssi = tmp_sec_rssi = cur_rf_rssi;
+			}
+			else if(rf_num == 2)
+			{	// we pick up the max index first, and let sec and min to be the same one
+				if(cur_rf_rssi >= tmp_max_rssi)
+				{
+					tmp_max_rssi = cur_rf_rssi;
+					max_rssi_index = i;
+				}
+				else
+				{
+					tmp_sec_rssi = tmp_min_rssi = cur_rf_rssi;
+					sec_rssi_index = min_rssi_index = i;
+				}
+			}
+			else
+			{
+				if(cur_rf_rssi > tmp_max_rssi)
+				{
+					tmp_sec_rssi = tmp_max_rssi;
+					sec_rssi_index = max_rssi_index;
+					tmp_max_rssi = cur_rf_rssi;
+					max_rssi_index = i;
+				}
+				else if(cur_rf_rssi == tmp_max_rssi)
+				{	// let sec and min point to the different index
+					tmp_sec_rssi = cur_rf_rssi;
+					sec_rssi_index = i;
+				}
+				else if((cur_rf_rssi < tmp_max_rssi) &&(cur_rf_rssi > tmp_sec_rssi))
+				{
+					tmp_sec_rssi = cur_rf_rssi;
+					sec_rssi_index = i;
+				}
+				else if(cur_rf_rssi == tmp_sec_rssi)
+				{
+					if(tmp_sec_rssi == tmp_min_rssi)
+					{	// let sec and min point to the different index
+						tmp_sec_rssi = cur_rf_rssi;
+						sec_rssi_index = i;
+					}
+					else
+					{
+						// This case we don't need to set any index
+					}
+				}
+				else if((cur_rf_rssi < tmp_sec_rssi) && (cur_rf_rssi > tmp_min_rssi))
+				{
+					// This case we don't need to set any index
+				}
+				else if(cur_rf_rssi == tmp_min_rssi)
+				{
+					if(tmp_sec_rssi == tmp_min_rssi)
+					{	// let sec and min point to the different index
+						tmp_min_rssi = cur_rf_rssi;
+						min_rssi_index = i;
+					}
+					else
+					{
+						// This case we don't need to set any index
+					}
+				}
+				else if(cur_rf_rssi < tmp_min_rssi)
+				{
+					tmp_min_rssi = cur_rf_rssi;
+					min_rssi_index = i;
+				}
+			}
+		}
+	}
+
+	rf_num = 0;
+	// decide max/sec/min cck pwdb index
+	if(DM_RxPathSelTable.cck_method == CCK_Rx_Version_2)
+	{
+		for (i=0; i<RF90_PATH_MAX; i++)
+		{
+			if(priv->brfpath_rxenable[i])
+			{
+				rf_num++;
+				cur_cck_pwdb =  DM_RxPathSelTable.cck_pwdb_sta[i];
+
+				if(rf_num == 1)	// find first enabled rf path and the rssi values
+				{	//initialize, set all rssi index to the same one
+					cck_rx_ver2_max_index = cck_rx_ver2_min_index = cck_rx_ver2_sec_index = i;
+					tmp_cck_max_pwdb = tmp_cck_min_pwdb = tmp_cck_sec_pwdb = cur_cck_pwdb;
+				}
+				else if(rf_num == 2)
+				{	// we pick up the max index first, and let sec and min to be the same one
+					if(cur_cck_pwdb >= tmp_cck_max_pwdb)
+					{
+						tmp_cck_max_pwdb = cur_cck_pwdb;
+						cck_rx_ver2_max_index = i;
+					}
+					else
+					{
+						tmp_cck_sec_pwdb = tmp_cck_min_pwdb = cur_cck_pwdb;
+						cck_rx_ver2_sec_index = cck_rx_ver2_min_index = i;
+					}
+				}
+				else
+				{
+					if(cur_cck_pwdb > tmp_cck_max_pwdb)
+					{
+						tmp_cck_sec_pwdb = tmp_cck_max_pwdb;
+						cck_rx_ver2_sec_index = cck_rx_ver2_max_index;
+						tmp_cck_max_pwdb = cur_cck_pwdb;
+						cck_rx_ver2_max_index = i;
+					}
+					else if(cur_cck_pwdb == tmp_cck_max_pwdb)
+					{	// let sec and min point to the different index
+						tmp_cck_sec_pwdb = cur_cck_pwdb;
+						cck_rx_ver2_sec_index = i;
+					}
+					else if((cur_cck_pwdb < tmp_cck_max_pwdb) &&(cur_cck_pwdb > tmp_cck_sec_pwdb))
+					{
+						tmp_cck_sec_pwdb = cur_cck_pwdb;
+						cck_rx_ver2_sec_index = i;
+					}
+					else if(cur_cck_pwdb == tmp_cck_sec_pwdb)
+					{
+						if(tmp_cck_sec_pwdb == tmp_cck_min_pwdb)
+						{	// let sec and min point to the different index
+							tmp_cck_sec_pwdb = cur_cck_pwdb;
+							cck_rx_ver2_sec_index = i;
+						}
+						else
+						{
+							// This case we don't need to set any index
+						}
+					}
+					else if((cur_cck_pwdb < tmp_cck_sec_pwdb) && (cur_cck_pwdb > tmp_cck_min_pwdb))
+					{
+						// This case we don't need to set any index
+					}
+					else if(cur_cck_pwdb == tmp_cck_min_pwdb)
+					{
+						if(tmp_cck_sec_pwdb == tmp_cck_min_pwdb)
+						{	// let sec and min point to the different index
+							tmp_cck_min_pwdb = cur_cck_pwdb;
+							cck_rx_ver2_min_index = i;
+						}
+						else
+						{
+							// This case we don't need to set any index
+						}
+					}
+					else if(cur_cck_pwdb < tmp_cck_min_pwdb)
+					{
+						tmp_cck_min_pwdb = cur_cck_pwdb;
+						cck_rx_ver2_min_index = i;
+					}
+				}
+
+			}
+		}
+	}
+
+
+	// Set CCK Rx path
+	// reg0xA07[3:2]=cck default rx path, reg0xa07[1:0]=cck optional rx path.
+	update_cck_rx_path = 0;
+	if(DM_RxPathSelTable.cck_method == CCK_Rx_Version_2)
+	{
+		cck_default_Rx = cck_rx_ver2_max_index;
+		cck_optional_Rx = cck_rx_ver2_sec_index;
+		if(tmp_cck_max_pwdb != -64)
+			update_cck_rx_path = 1;
+	}
+
+	if(tmp_min_rssi < DM_RxPathSelTable.SS_TH_low && disabled_rf_cnt < 2)
+	{
+		if((tmp_max_rssi - tmp_min_rssi) >= DM_RxPathSelTable.diff_TH)
+		{
+			//record the enabled rssi threshold
+			DM_RxPathSelTable.rf_enable_rssi_th[min_rssi_index] = tmp_max_rssi+5;
+			//disable the BB Rx path, OFDM
+			rtl8192_setBBreg(dev, rOFDM0_TRxPathEnable, 0x1<<min_rssi_index, 0x0);	// 0xc04[3:0]
+			rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0x1<<min_rssi_index, 0x0);	// 0xd04[3:0]
+			disabled_rf_cnt++;
+		}
+		if(DM_RxPathSelTable.cck_method == CCK_Rx_Version_1)
+		{
+			cck_default_Rx = max_rssi_index;
+			cck_optional_Rx = sec_rssi_index;
+			if(tmp_max_rssi)
+				update_cck_rx_path = 1;
+		}
+	}
+
+	if(update_cck_rx_path)
+	{
+		DM_RxPathSelTable.cck_Rx_path = (cck_default_Rx<<2)|(cck_optional_Rx);
+		rtl8192_setBBreg(dev, rCCK0_AFESetting, 0x0f000000, DM_RxPathSelTable.cck_Rx_path);
+	}
+
+	if(DM_RxPathSelTable.disabledRF)
+	{
+		for(i=0; i<4; i++)
+		{
+			if((DM_RxPathSelTable.disabledRF>>i) & 0x1)	//disabled rf
+			{
+				if(tmp_max_rssi >= DM_RxPathSelTable.rf_enable_rssi_th[i])
+				{
+					//enable the BB Rx path
+					//DbgPrint("RF-%d is enabled. \n", 0x1<<i);
+					rtl8192_setBBreg(dev, rOFDM0_TRxPathEnable, 0x1<<i, 0x1);	// 0xc04[3:0]
+					rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0x1<<i, 0x1);	// 0xd04[3:0]
+					DM_RxPathSelTable.rf_enable_rssi_th[i] = 100;
+					disabled_rf_cnt--;
+				}
+			}
+		}
+	}
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:	dm_check_rx_path_selection()
+ *
+ * Overview:	Call a workitem to check current RXRF path and Rx Path selection by RSSI.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/28/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static	void	dm_check_rx_path_selection(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+	queue_delayed_work(priv->priv_wq,&priv->rfpath_check_wq,0);
+#else
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+	schedule_task(&priv->rfpath_check_wq);
+#else
+	queue_work(priv->priv_wq,&priv->rfpath_check_wq);
+#endif
+#endif
+}	/* dm_CheckRxRFPath */
+
+
+static void dm_init_fsync (struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	priv->ieee80211->fsync_time_interval = 500;
+	priv->ieee80211->fsync_rate_bitmap = 0x0f000800;
+	priv->ieee80211->fsync_rssi_threshold = 30;
+#ifdef RTL8190P
+	priv->ieee80211->bfsync_enable = true;
+#else
+	priv->ieee80211->bfsync_enable = false;
+#endif
+	priv->ieee80211->fsync_multiple_timeinterval = 3;
+	priv->ieee80211->fsync_firstdiff_ratethreshold= 100;
+	priv->ieee80211->fsync_seconddiff_ratethreshold= 200;
+	priv->ieee80211->fsync_state = Default_Fsync;
+	priv->framesyncMonitor = 1;	// current default 0xc38 monitor on
+
+	init_timer(&priv->fsync_timer);
+	priv->fsync_timer.data = (unsigned long)dev;
+	priv->fsync_timer.function = dm_fsync_timer_callback;
+}
+
+
+static void dm_deInit_fsync(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	del_timer_sync(&priv->fsync_timer);
+}
+
+extern void dm_fsync_timer_callback(unsigned long data)
+{
+	struct net_device *dev = (struct net_device *)data;
+	struct r8192_priv *priv = ieee80211_priv((struct net_device *)data);
+	u32 rate_index, rate_count = 0, rate_count_diff=0;
+	bool		bSwitchFromCountDiff = false;
+	bool		bDoubleTimeInterval = false;
+
+	if(	priv->ieee80211->state == IEEE80211_LINKED &&
+		priv->ieee80211->bfsync_enable &&
+		(priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_CDD_FSYNC))
+	{
+		 // Count rate 54, MCS [7], [12, 13, 14, 15]
+		u32 rate_bitmap;
+		for(rate_index = 0; rate_index <= 27; rate_index++)
+		{
+			rate_bitmap  = 1 << rate_index;
+			if(priv->ieee80211->fsync_rate_bitmap &  rate_bitmap)
+		 		rate_count+= priv->stats.received_rate_histogram[1][rate_index];
+		}
+
+		if(rate_count < priv->rate_record)
+			rate_count_diff = 0xffffffff - rate_count + priv->rate_record;
+		else
+			rate_count_diff = rate_count - priv->rate_record;
+		if(rate_count_diff < priv->rateCountDiffRecord)
+		{
+
+			u32 DiffNum = priv->rateCountDiffRecord - rate_count_diff;
+			// Contiune count
+			if(DiffNum >= priv->ieee80211->fsync_seconddiff_ratethreshold)
+				priv->ContiuneDiffCount++;
+			else
+				priv->ContiuneDiffCount = 0;
+
+			// Contiune count over
+			if(priv->ContiuneDiffCount >=2)
+			{
+				bSwitchFromCountDiff = true;
+				priv->ContiuneDiffCount = 0;
+			}
+		}
+		else
+		{
+			// Stop contiune count
+			priv->ContiuneDiffCount = 0;
+		}
+
+		//If Count diff <= FsyncRateCountThreshold
+		if(rate_count_diff <= priv->ieee80211->fsync_firstdiff_ratethreshold)
+		{
+			bSwitchFromCountDiff = true;
+			priv->ContiuneDiffCount = 0;
+		}
+		priv->rate_record = rate_count;
+		priv->rateCountDiffRecord = rate_count_diff;
+		RT_TRACE(COMP_HALDM, "rateRecord %d rateCount %d, rateCountdiff %d bSwitchFsync %d\n", priv->rate_record, rate_count, rate_count_diff , priv->bswitch_fsync);
+		// if we never receive those mcs rate and rssi > 30 % then switch fsyn
+		if(priv->undecorated_smoothed_pwdb > priv->ieee80211->fsync_rssi_threshold && bSwitchFromCountDiff)
+		{
+			bDoubleTimeInterval = true;
+			priv->bswitch_fsync = !priv->bswitch_fsync;
+			if(priv->bswitch_fsync)
+			{
+			#ifdef RTL8190P
+				write_nic_byte(dev, 0xC36, 0x00);
+			#else
+				write_nic_byte(dev,0xC36, 0x1c);
+			#endif
+				write_nic_byte(dev, 0xC3e, 0x90);
+			}
+			else
+			{
+			#ifdef RTL8190P
+				write_nic_byte(dev, 0xC36, 0x40);
+			#else
+				write_nic_byte(dev, 0xC36, 0x5c);
+			#endif
+				write_nic_byte(dev, 0xC3e, 0x96);
+			}
+		}
+		else if(priv->undecorated_smoothed_pwdb <= priv->ieee80211->fsync_rssi_threshold)
+		{
+			if(priv->bswitch_fsync)
+			{
+				priv->bswitch_fsync  = false;
+			#ifdef RTL8190P
+				write_nic_byte(dev, 0xC36, 0x40);
+			#else
+				write_nic_byte(dev, 0xC36, 0x5c);
+			#endif
+				write_nic_byte(dev, 0xC3e, 0x96);
+			}
+		}
+		if(bDoubleTimeInterval){
+			if(timer_pending(&priv->fsync_timer))
+				del_timer_sync(&priv->fsync_timer);
+			priv->fsync_timer.expires = jiffies + MSECS(priv->ieee80211->fsync_time_interval*priv->ieee80211->fsync_multiple_timeinterval);
+			add_timer(&priv->fsync_timer);
+		}
+		else{
+			if(timer_pending(&priv->fsync_timer))
+				del_timer_sync(&priv->fsync_timer);
+			priv->fsync_timer.expires = jiffies + MSECS(priv->ieee80211->fsync_time_interval);
+			add_timer(&priv->fsync_timer);
+		}
+	}
+	else
+	{
+		// Let Register return to default value;
+		if(priv->bswitch_fsync)
+		{
+			priv->bswitch_fsync  = false;
+		#ifdef RTL8190P
+			write_nic_byte(dev, 0xC36, 0x40);
+		#else
+			write_nic_byte(dev, 0xC36, 0x5c);
+		#endif
+			write_nic_byte(dev, 0xC3e, 0x96);
+		}
+		priv->ContiuneDiffCount = 0;
+#ifdef RTL8192SU
+	rtl8192_setBBreg(dev, rOFDM0_RxDetector2, bMaskDWord, 0x164052cd);
+#else
+	#ifdef RTL8190P
+		write_nic_dword(dev, rOFDM0_RxDetector2, 0x164052cd);
+	#else
+		write_nic_dword(dev, rOFDM0_RxDetector2, 0x465c52cd);
+	#endif
+#endif
+	}
+	RT_TRACE(COMP_HALDM, "ContiuneDiffCount %d\n", priv->ContiuneDiffCount);
+	RT_TRACE(COMP_HALDM, "rateRecord %d rateCount %d, rateCountdiff %d bSwitchFsync %d\n", priv->rate_record, rate_count, rate_count_diff , priv->bswitch_fsync);
+}
+
+static void dm_StartHWFsync(struct net_device *dev)
+{
+	RT_TRACE(COMP_HALDM, "%s\n", __FUNCTION__);
+	write_nic_dword(dev, rOFDM0_RxDetector2, 0x465c12cf);
+	write_nic_byte(dev, 0xc3b, 0x41);
+}
+
+static void dm_EndSWFsync(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	RT_TRACE(COMP_HALDM, "%s\n", __FUNCTION__);
+	del_timer_sync(&(priv->fsync_timer));
+
+	// Let Register return to default value;
+	if(priv->bswitch_fsync)
+	{
+		priv->bswitch_fsync  = false;
+
+		#ifdef RTL8190P
+			write_nic_byte(dev, 0xC36, 0x40);
+		#else
+			write_nic_byte(dev, 0xC36, 0x5c);
+		#endif
+
+		write_nic_byte(dev, 0xC3e, 0x96);
+	}
+
+	priv->ContiuneDiffCount = 0;
+#ifndef RTL8190P
+	write_nic_dword(dev, rOFDM0_RxDetector2, 0x465c52cd);
+#endif
+
+}
+
+static void dm_StartSWFsync(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 			rateIndex;
+	u32 			rateBitmap;
+
+	RT_TRACE(COMP_HALDM,"%s\n", __FUNCTION__);
+	// Initial rate record to zero, start to record.
+	priv->rate_record = 0;
+	// Initial contiune diff count to zero, start to record.
+	priv->ContiuneDiffCount = 0;
+	priv->rateCountDiffRecord = 0;
+	priv->bswitch_fsync  = false;
+
+	if(priv->ieee80211->mode == WIRELESS_MODE_N_24G)
+	{
+		priv->ieee80211->fsync_firstdiff_ratethreshold= 600;
+		priv->ieee80211->fsync_seconddiff_ratethreshold = 0xffff;
+	}
+	else
+	{
+		priv->ieee80211->fsync_firstdiff_ratethreshold= 200;
+		priv->ieee80211->fsync_seconddiff_ratethreshold = 200;
+	}
+	for(rateIndex = 0; rateIndex <= 27; rateIndex++)
+	{
+		rateBitmap  = 1 << rateIndex;
+		if(priv->ieee80211->fsync_rate_bitmap &  rateBitmap)
+			priv->rate_record += priv->stats.received_rate_histogram[1][rateIndex];
+	}
+	if(timer_pending(&priv->fsync_timer))
+		del_timer_sync(&priv->fsync_timer);
+	priv->fsync_timer.expires = jiffies + MSECS(priv->ieee80211->fsync_time_interval);
+	add_timer(&priv->fsync_timer);
+
+#ifndef RTL8190P
+	write_nic_dword(dev, rOFDM0_RxDetector2, 0x465c12cd);
+#endif
+
+}
+
+static void dm_EndHWFsync(struct net_device *dev)
+{
+	RT_TRACE(COMP_HALDM,"%s\n", __FUNCTION__);
+	write_nic_dword(dev, rOFDM0_RxDetector2, 0x465c52cd);
+	write_nic_byte(dev, 0xc3b, 0x49);
+
+}
+
+void dm_check_fsync(struct net_device *dev)
+{
+#define	RegC38_Default				0
+#define	RegC38_NonFsync_Other_AP	1
+#define	RegC38_Fsync_AP_BCM		2
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//u32 			framesyncC34;
+	static u8		reg_c38_State=RegC38_Default;
+	static u32	reset_cnt=0;
+
+	RT_TRACE(COMP_HALDM, "RSSI %d TimeInterval %d MultipleTimeInterval %d\n", priv->ieee80211->fsync_rssi_threshold, priv->ieee80211->fsync_time_interval, priv->ieee80211->fsync_multiple_timeinterval);
+	RT_TRACE(COMP_HALDM, "RateBitmap 0x%x FirstDiffRateThreshold %d SecondDiffRateThreshold %d\n", priv->ieee80211->fsync_rate_bitmap, priv->ieee80211->fsync_firstdiff_ratethreshold, priv->ieee80211->fsync_seconddiff_ratethreshold);
+
+	if(	priv->ieee80211->state == IEEE80211_LINKED &&
+		(priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_CDD_FSYNC))
+	{
+		if(priv->ieee80211->bfsync_enable == 0)
+		{
+			switch(priv->ieee80211->fsync_state)
+			{
+				case Default_Fsync:
+					dm_StartHWFsync(dev);
+					priv->ieee80211->fsync_state = HW_Fsync;
+					break;
+				case SW_Fsync:
+					dm_EndSWFsync(dev);
+					dm_StartHWFsync(dev);
+					priv->ieee80211->fsync_state = HW_Fsync;
+					break;
+				case HW_Fsync:
+				default:
+					break;
+			}
+		}
+		else
+		{
+			switch(priv->ieee80211->fsync_state)
+			{
+				case Default_Fsync:
+					dm_StartSWFsync(dev);
+					priv->ieee80211->fsync_state = SW_Fsync;
+					break;
+				case HW_Fsync:
+					dm_EndHWFsync(dev);
+					dm_StartSWFsync(dev);
+					priv->ieee80211->fsync_state = SW_Fsync;
+					break;
+				case SW_Fsync:
+				default:
+					break;
+
+			}
+		}
+		if(priv->framesyncMonitor)
+		{
+			if(reg_c38_State != RegC38_Fsync_AP_BCM)
+			{	//For broadcom AP we write different default value
+				#ifdef RTL8190P
+					write_nic_byte(dev, rOFDM0_RxDetector3, 0x15);
+				#else
+					write_nic_byte(dev, rOFDM0_RxDetector3, 0x95);
+				#endif
+
+				reg_c38_State = RegC38_Fsync_AP_BCM;
+			}
+		}
+	}
+	else
+	{
+		switch(priv->ieee80211->fsync_state)
+		{
+			case HW_Fsync:
+				dm_EndHWFsync(dev);
+				priv->ieee80211->fsync_state = Default_Fsync;
+				break;
+			case SW_Fsync:
+				dm_EndSWFsync(dev);
+				priv->ieee80211->fsync_state = Default_Fsync;
+				break;
+			case Default_Fsync:
+			default:
+				break;
+		}
+
+		if(priv->framesyncMonitor)
+		{
+			if(priv->ieee80211->state == IEEE80211_LINKED)
+			{
+				if(priv->undecorated_smoothed_pwdb <= RegC38_TH)
+				{
+					if(reg_c38_State != RegC38_NonFsync_Other_AP)
+					{
+						#ifdef RTL8190P
+							write_nic_byte(dev, rOFDM0_RxDetector3, 0x10);
+						#else
+							write_nic_byte(dev, rOFDM0_RxDetector3, 0x90);
+						#endif
+
+						reg_c38_State = RegC38_NonFsync_Other_AP;
+					#if 0//cosa
+						if (Adapter->HardwareType == HARDWARE_TYPE_RTL8190P)
+							DbgPrint("Fsync is idle, rssi<=35, write 0xc38 = 0x%x \n", 0x10);
+						else
+							DbgPrint("Fsync is idle, rssi<=35, write 0xc38 = 0x%x \n", 0x90);
+					#endif
+					}
+				}
+				else if(priv->undecorated_smoothed_pwdb >= (RegC38_TH+5))
+				{
+					if(reg_c38_State)
+					{
+						write_nic_byte(dev, rOFDM0_RxDetector3, priv->framesync);
+						reg_c38_State = RegC38_Default;
+						//DbgPrint("Fsync is idle, rssi>=40, write 0xc38 = 0x%x \n", pHalData->framesync);
+					}
+				}
+			}
+			else
+			{
+				if(reg_c38_State)
+				{
+					write_nic_byte(dev, rOFDM0_RxDetector3, priv->framesync);
+					reg_c38_State = RegC38_Default;
+					//DbgPrint("Fsync is idle, not connected, write 0xc38 = 0x%x \n", pHalData->framesync);
+				}
+			}
+		}
+	}
+	if(priv->framesyncMonitor)
+	{
+		if(priv->reset_count != reset_cnt)
+		{	//After silent reset, the reg_c38_State will be returned to default value
+			write_nic_byte(dev, rOFDM0_RxDetector3, priv->framesync);
+			reg_c38_State = RegC38_Default;
+			reset_cnt = priv->reset_count;
+			//DbgPrint("reg_c38_State = 0 for silent reset. \n");
+		}
+	}
+	else
+	{
+		if(reg_c38_State)
+		{
+			write_nic_byte(dev, rOFDM0_RxDetector3, priv->framesync);
+			reg_c38_State = RegC38_Default;
+			//DbgPrint("framesync no monitor, write 0xc38 = 0x%x \n", pHalData->framesync);
+		}
+	}
+}
+
+#if 0
+/*-----------------------------------------------------------------------------
+ * Function:	DM_CheckLBusStatus()
+ *
+ * Overview:	For 9x series, we must make sure LBUS is active for IO.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	02/22/2008	MHC		Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+extern	s1Byte	DM_CheckLBusStatus(IN	PADAPTER	Adapter)
+{
+	PMGNT_INFO	pMgntInfo=&Adapter->MgntInfo;
+
+#if (HAL_CODE_BASE & RTL819X)
+
+#if (HAL_CODE_BASE == RTL8192)
+
+#if( DEV_BUS_TYPE==PCI_INTERFACE)
+	//return (pMgntInfo->bLbusEnable);	// For debug only
+	return TRUE;
+#endif
+
+#if( DEV_BUS_TYPE==USB_INTERFACE)
+	return TRUE;
+#endif
+
+#endif	// #if (HAL_CODE_BASE == RTL8192)
+
+#if (HAL_CODE_BASE == RTL8190)
+	return TRUE;
+#endif	// #if (HAL_CODE_BASE == RTL8190)
+
+#endif	// #if (HAL_CODE_BASE & RTL819X)
+}	/* DM_CheckLBusStatus */
+
+#endif
+
+/*-----------------------------------------------------------------------------
+ * Function:	dm_shadow_init()
+ *
+ * Overview:	Store all NIC MAC/BB register content.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/29/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+extern void dm_shadow_init(struct net_device *dev)
+{
+	u8	page;
+	u16	offset;
+
+	for (page = 0; page < 5; page++)
+		for (offset = 0; offset < 256; offset++)
+		{
+			dm_shadow[page][offset] = read_nic_byte(dev, offset+page*256);
+			//DbgPrint("P-%d/O-%02x=%02x\r\n", page, offset, DM_Shadow[page][offset]);
+		}
+
+	for (page = 8; page < 11; page++)
+		for (offset = 0; offset < 256; offset++)
+			dm_shadow[page][offset] = read_nic_byte(dev, offset+page*256);
+
+	for (page = 12; page < 15; page++)
+		for (offset = 0; offset < 256; offset++)
+			dm_shadow[page][offset] = read_nic_byte(dev, offset+page*256);
+
+}   /* dm_shadow_init */
+
+/*---------------------------Define function prototype------------------------*/
+/*-----------------------------------------------------------------------------
+ * Function:	DM_DynamicTxPower()
+ *
+ * Overview:	Detect Signal strength to control TX Registry
+ 			Tx Power Control For Near/Far Range
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	03/06/2008	Jacken	Create Version 0.
+ *
+ *---------------------------------------------------------------------------*/
+static void dm_init_dynamic_txpower(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	//Initial TX Power Control for near/far range , add by amy 2008/05/15, porting from windows code.
+	priv->ieee80211->bdynamic_txpower_enable = true;    //Default to enable Tx Power Control
+	priv->bLastDTPFlag_High = false;
+	priv->bLastDTPFlag_Low = false;
+	priv->bDynamicTxHighPower = false;
+	priv->bDynamicTxLowPower = false;
+}
+
+static void dm_dynamic_txpower(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	unsigned int txhipower_threshhold=0;
+	unsigned int txlowpower_threshold=0;
+	if(priv->ieee80211->bdynamic_txpower_enable != true)
+	{
+		priv->bDynamicTxHighPower = false;
+		priv->bDynamicTxLowPower = false;
+		return;
+	}
+	//printk("priv->ieee80211->current_network.unknown_cap_exist is %d ,priv->ieee80211->current_network.broadcom_cap_exist is %d\n",priv->ieee80211->current_network.unknown_cap_exist,priv->ieee80211->current_network.broadcom_cap_exist);
+	if((priv->ieee80211->current_network.atheros_cap_exist ) && (priv->ieee80211->mode == IEEE_G)){
+		txhipower_threshhold = TX_POWER_ATHEROAP_THRESH_HIGH;
+		txlowpower_threshold = TX_POWER_ATHEROAP_THRESH_LOW;
+	}
+	else
+	{
+		txhipower_threshhold = TX_POWER_NEAR_FIELD_THRESH_HIGH;
+		txlowpower_threshold = TX_POWER_NEAR_FIELD_THRESH_LOW;
+	}
+
+//	printk("=======>%s(): txhipower_threshhold is %d,txlowpower_threshold is %d\n",__FUNCTION__,txhipower_threshhold,txlowpower_threshold);
+	RT_TRACE(COMP_TXAGC,"priv->undecorated_smoothed_pwdb = %ld \n" , priv->undecorated_smoothed_pwdb);
+
+	if(priv->ieee80211->state == IEEE80211_LINKED)
+	{
+		if(priv->undecorated_smoothed_pwdb >= txhipower_threshhold)
+		{
+			priv->bDynamicTxHighPower = true;
+			priv->bDynamicTxLowPower = false;
+		}
+		else
+		{
+			// high power state check
+			if(priv->undecorated_smoothed_pwdb < txlowpower_threshold && priv->bDynamicTxHighPower == true)
+			{
+				priv->bDynamicTxHighPower = false;
+			}
+			// low power state check
+			if(priv->undecorated_smoothed_pwdb < 35)
+			{
+				priv->bDynamicTxLowPower = true;
+			}
+			else if(priv->undecorated_smoothed_pwdb >= 40)
+			{
+				priv->bDynamicTxLowPower = false;
+			}
+		}
+	}
+	else
+	{
+		//pHalData->bTXPowerCtrlforNearFarRange = !pHalData->bTXPowerCtrlforNearFarRange;
+		priv->bDynamicTxHighPower = false;
+		priv->bDynamicTxLowPower = false;
+	}
+
+	if( (priv->bDynamicTxHighPower != priv->bLastDTPFlag_High ) ||
+		(priv->bDynamicTxLowPower != priv->bLastDTPFlag_Low ) )
+	{
+		RT_TRACE(COMP_TXAGC,"SetTxPowerLevel8190()  channel = %d \n" , priv->ieee80211->current_network.channel);
+#ifndef RTL8192SU
+#if  defined(RTL8190P) || defined(RTL8192E)
+		SetTxPowerLevel8190(Adapter,pHalData->CurrentChannel);
+#endif
+
+#ifdef RTL8192U
+		rtl8192_phy_setTxPower(dev,priv->ieee80211->current_network.channel);
+		//pHalData->bStartTxCtrlByTPCNFR = FALSE;    //Clear th flag of Set TX Power from Sitesurvey
+#endif
+#endif
+	}
+	priv->bLastDTPFlag_High = priv->bDynamicTxHighPower;
+	priv->bLastDTPFlag_Low = priv->bDynamicTxLowPower;
+
+}	/* dm_dynamic_txpower */
+
+//added by vivi, for read tx rate and retrycount
+static void dm_check_txrateandretrycount(struct net_device * dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+	//for 11n tx rate
+//	priv->stats.CurrentShowTxate = read_nic_byte(dev, Current_Tx_Rate_Reg);
+#ifdef RTL8192SU
+	ieee->softmac_stats.CurrentShowTxate = read_nic_byte(dev, TX_RATE_REG);
+#else
+	ieee->softmac_stats.CurrentShowTxate = read_nic_byte(dev, Current_Tx_Rate_Reg);
+#endif
+	//printk("=============>tx_rate_reg:%x\n", ieee->softmac_stats.CurrentShowTxate);
+	//for initial tx rate
+//	priv->stats.last_packet_rate = read_nic_byte(dev, Initial_Tx_Rate_Reg);
+	ieee->softmac_stats.last_packet_rate = read_nic_byte(dev ,Initial_Tx_Rate_Reg);
+	//for tx tx retry count
+//	priv->stats.txretrycount = read_nic_dword(dev, Tx_Retry_Count_Reg);
+	ieee->softmac_stats.txretrycount = read_nic_dword(dev, Tx_Retry_Count_Reg);
+}
+
+static void dm_send_rssi_tofw(struct net_device *dev)
+{
+#ifndef RTL8192SU
+	DCMD_TXCMD_T			tx_cmd;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	// If we test chariot, we should stop the TX command ?
+	// Because 92E will always silent reset when we send tx command. We use register
+	// 0x1e0(byte) to botify driver.
+	write_nic_byte(dev, DRIVER_RSSI, (u8)priv->undecorated_smoothed_pwdb);
+	return;
+#if 1
+	tx_cmd.Op		= TXCMD_SET_RX_RSSI;
+	tx_cmd.Length	= 4;
+	tx_cmd.Value		= priv->undecorated_smoothed_pwdb;
+
+	cmpk_message_handle_tx(dev, (u8*)&tx_cmd,
+								DESC_PACKET_TYPE_INIT, sizeof(DCMD_TXCMD_T));
+#endif
+#endif
+}
+
+#ifdef TO_DO_LIST
+static	void
+dm_CheckProtection(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	//PMGNT_INFO		pMgntInfo = &(Adapter->MgntInfo);
+	u8			CurRate;
+
+	if(priv->ieee80211->pHTInfo->IOTAction & (HT_IOT_ACT_FORCED_RTS|HT_IOT_ACT_FORCED_CTS2SELF))
+	{
+		CurRate = read_nic_byte(dev, INIMCS_SEL);
+		if(CurRate <= DESC92S_RATE11M)
+			priv->bDmDisableProtect = true;
+		else
+			priv->bDmDisableProtect = fasle;
+	}
+}
+#endif
+
+/*---------------------------Define function prototype------------------------*/
+
diff --git a/drivers/staging/rtl8192su/r8192U_dm.h b/drivers/staging/rtl8192su/r8192U_dm.h
new file mode 100644
index 0000000..1e05d75
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192U_dm.h
@@ -0,0 +1,309 @@
+/*****************************************************************************
+ *	Copyright(c) 2007,  RealTEK Technology Inc. All Right Reserved.
+ *
+ * Module:		Hal819xUsbDM.h	(RTL8192  Header H File)
+ *
+ *
+ * Note:		For dynamic control definition constant structure.
+ *
+ *
+ * Export:
+ *
+ * Abbrev:
+ *
+ * History:
+ *	Data		Who		Remark
+ *	10/04/2007  MHC    	Create initial version.
+ *
+ *****************************************************************************/
+ /* Check to see if the file has been included already.  */
+#ifndef	__R8192UDM_H__
+#define __R8192UDM_H__
+
+
+/*--------------------------Define Parameters-------------------------------*/
+#define		DM_DIG_THRESH_HIGH					40
+#define		DM_DIG_THRESH_LOW					35
+
+#define		DM_DIG_HIGH_PWR_THRESH_HIGH		75
+#define		DM_DIG_HIGH_PWR_THRESH_LOW		70
+
+#define		BW_AUTO_SWITCH_HIGH_LOW			25
+#define		BW_AUTO_SWITCH_LOW_HIGH			30
+
+#define		DM_check_fsync_time_interval				500
+
+
+#define		DM_DIG_BACKOFF				12
+#define		DM_DIG_MAX					0x36
+#define		DM_DIG_MIN					0x1c
+#define		DM_DIG_MIN_Netcore			0x12
+
+#define		RxPathSelection_SS_TH_low		30
+#define		RxPathSelection_diff_TH			18
+
+#define		RateAdaptiveTH_High			50
+#define		RateAdaptiveTH_Low_20M		30
+#define		RateAdaptiveTH_Low_40M		10
+#define		VeryLowRSSI					15
+#define		CTSToSelfTHVal					30
+
+//defined by vivi, for tx power track
+#define		E_FOR_TX_POWER_TRACK               300
+//Dynamic Tx Power Control Threshold
+#define		TX_POWER_NEAR_FIELD_THRESH_HIGH		68
+#define		TX_POWER_NEAR_FIELD_THRESH_LOW		62
+//added by amy for atheros AP
+#define         TX_POWER_ATHEROAP_THRESH_HIGH           78
+#define 	TX_POWER_ATHEROAP_THRESH_LOW		72
+
+//defined by vivi, for showing on UI
+#define 		Current_Tx_Rate_Reg         0x1b8
+#define 		Initial_Tx_Rate_Reg         	  0x1b9
+#define 		Tx_Retry_Count_Reg         0x1ac
+#define		RegC38_TH				 20
+#if 0
+//----------------------------------------------------------------------------
+//       8190 Rate Adaptive Table Register	(offset 0x320, 4 byte)
+//----------------------------------------------------------------------------
+
+//CCK
+#define	RATR_1M					0x00000001
+#define	RATR_2M					0x00000002
+#define	RATR_55M					0x00000004
+#define	RATR_11M					0x00000008
+//OFDM
+#define	RATR_6M					0x00000010
+#define	RATR_9M					0x00000020
+#define	RATR_12M					0x00000040
+#define	RATR_18M					0x00000080
+#define	RATR_24M					0x00000100
+#define	RATR_36M					0x00000200
+#define	RATR_48M					0x00000400
+#define	RATR_54M					0x00000800
+//MCS 1 Spatial Stream
+#define	RATR_MCS0					0x00001000
+#define	RATR_MCS1					0x00002000
+#define	RATR_MCS2					0x00004000
+#define	RATR_MCS3					0x00008000
+#define	RATR_MCS4					0x00010000
+#define	RATR_MCS5					0x00020000
+#define	RATR_MCS6					0x00040000
+#define	RATR_MCS7					0x00080000
+//MCS 2 Spatial Stream
+#define	RATR_MCS8					0x00100000
+#define	RATR_MCS9					0x00200000
+#define	RATR_MCS10					0x00400000
+#define	RATR_MCS11					0x00800000
+#define	RATR_MCS12					0x01000000
+#define	RATR_MCS13					0x02000000
+#define	RATR_MCS14					0x04000000
+#define	RATR_MCS15					0x08000000
+// ALL CCK Rate
+#define RATE_ALL_CCK				RATR_1M|RATR_2M|RATR_55M|RATR_11M
+#define RATE_ALL_OFDM_AG			RATR_6M|RATR_9M|RATR_12M|RATR_18M|RATR_24M\
+									|RATR_36M|RATR_48M|RATR_54M
+#define RATE_ALL_OFDM_2SS			RATR_MCS8|RATR_MCS9	|RATR_MCS10|RATR_MCS11| \
+									RATR_MCS12|RATR_MCS13|RATR_MCS14|RATR_MCS15
+#endif
+/*--------------------------Define Parameters-------------------------------*/
+
+
+/*------------------------------Define structure----------------------------*/
+/* 2007/10/04 MH Define upper and lower threshold of DIG enable or disable. */
+typedef struct _dynamic_initial_gain_threshold_
+{
+	u8		dig_enable_flag;
+	u8		dig_algorithm;
+	u8		dbg_mode;
+	u8		dig_algorithm_switch;
+
+	long		rssi_low_thresh;
+	long		rssi_high_thresh;
+
+	long		rssi_high_power_lowthresh;
+	long		rssi_high_power_highthresh;
+
+	u8		dig_state;
+	u8		dig_highpwr_state;
+	u8		cur_connect_state;
+	u8		pre_connect_state;
+
+	u8		curpd_thstate;
+	u8		prepd_thstate;
+	u8		curcs_ratio_state;
+	u8		precs_ratio_state;
+
+	u32		pre_ig_value;
+	u32		cur_ig_value;
+
+	u8		backoff_val;
+	u8		rx_gain_range_max;
+	u8		rx_gain_range_min;
+	bool		initialgain_lowerbound_state;
+
+	long		rssi_val;
+}dig_t;
+
+typedef enum tag_dynamic_init_gain_state_definition
+{
+	DM_STA_DIG_OFF = 0,
+	DM_STA_DIG_ON,
+	DM_STA_DIG_MAX
+}dm_dig_sta_e;
+
+
+/* 2007/10/08 MH Define RATR state. */
+typedef enum tag_dynamic_ratr_state_definition
+{
+	DM_RATR_STA_HIGH = 0,
+	DM_RATR_STA_MIDDLE = 1,
+	DM_RATR_STA_LOW = 2,
+	DM_RATR_STA_MAX
+}dm_ratr_sta_e;
+
+/* 2007/10/11 MH Define DIG operation type. */
+typedef enum tag_dynamic_init_gain_operation_type_definition
+{
+	DIG_TYPE_THRESH_HIGH	= 0,
+	DIG_TYPE_THRESH_LOW	= 1,
+	DIG_TYPE_THRESH_HIGHPWR_HIGH	= 2,
+	DIG_TYPE_THRESH_HIGHPWR_LOW	= 3,
+	DIG_TYPE_DBG_MODE				= 4,
+	DIG_TYPE_RSSI						= 5,
+	DIG_TYPE_ALGORITHM				= 6,
+	DIG_TYPE_BACKOFF					= 7,
+	DIG_TYPE_PWDB_FACTOR			= 8,
+	DIG_TYPE_RX_GAIN_MIN				= 9,
+	DIG_TYPE_RX_GAIN_MAX				= 10,
+	DIG_TYPE_ENABLE 		= 20,
+	DIG_TYPE_DISABLE 		= 30,
+	DIG_OP_TYPE_MAX
+}dm_dig_op_e;
+
+typedef enum tag_dig_algorithm_definition
+{
+	DIG_ALGO_BY_FALSE_ALARM = 0,
+	DIG_ALGO_BY_RSSI	= 1,
+	DIG_ALGO_MAX
+}dm_dig_alg_e;
+
+typedef enum tag_dig_dbgmode_definition
+{
+	DIG_DBG_OFF = 0,
+	DIG_DBG_ON = 1,
+	DIG_DBG_MAX
+}dm_dig_dbg_e;
+
+typedef enum tag_dig_connect_definition
+{
+	DIG_DISCONNECT = 0,
+	DIG_CONNECT = 1,
+	DIG_CONNECT_MAX
+}dm_dig_connect_e;
+
+typedef enum tag_dig_packetdetection_threshold_definition
+{
+	DIG_PD_AT_LOW_POWER = 0,
+	DIG_PD_AT_NORMAL_POWER = 1,
+	DIG_PD_AT_HIGH_POWER = 2,
+	DIG_PD_MAX
+}dm_dig_pd_th_e;
+
+typedef enum tag_dig_cck_cs_ratio_state_definition
+{
+	DIG_CS_RATIO_LOWER = 0,
+	DIG_CS_RATIO_HIGHER = 1,
+	DIG_CS_MAX
+}dm_dig_cs_ratio_e;
+typedef struct _Dynamic_Rx_Path_Selection_
+{
+	u8		Enable;
+	u8		DbgMode;
+	u8		cck_method;
+	u8		cck_Rx_path;
+
+	u8		SS_TH_low;
+	u8		diff_TH;
+	u8		disabledRF;
+	u8		reserved;
+
+	u8		rf_rssi[4];
+	u8		rf_enable_rssi_th[4];
+	long		cck_pwdb_sta[4];
+}DRxPathSel;
+
+typedef enum tag_CCK_Rx_Path_Method_Definition
+{
+	CCK_Rx_Version_1 = 0,
+	CCK_Rx_Version_2= 1,
+	CCK_Rx_Version_MAX
+}DM_CCK_Rx_Path_Method;
+
+typedef enum tag_DM_DbgMode_Definition
+{
+	DM_DBG_OFF = 0,
+	DM_DBG_ON = 1,
+	DM_DBG_MAX
+}DM_DBG_E;
+
+typedef struct tag_Tx_Config_Cmd_Format
+{
+	u32	Op;										/* Command packet type. */
+	u32	Length;									/* Command packet length. */
+	u32	Value;
+}DCMD_TXCMD_T, *PDCMD_TXCMD_T;
+/*------------------------------Define structure----------------------------*/
+
+
+/*------------------------Export global variable----------------------------*/
+extern	dig_t	dm_digtable;
+extern	u8		dm_shadow[16][256];
+extern DRxPathSel      DM_RxPathSelTable;
+/*------------------------Export global variable----------------------------*/
+
+
+/*------------------------Export Marco Definition---------------------------*/
+
+/*------------------------Export Marco Definition---------------------------*/
+
+
+/*--------------------------Exported Function prototype---------------------*/
+extern  void    init_hal_dm(struct net_device *dev);
+extern  void deinit_hal_dm(struct net_device *dev);
+
+extern void hal_dm_watchdog(struct net_device *dev);
+
+extern  void    init_rate_adaptive(struct net_device *dev);
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern  void    dm_txpower_trackingcallback(struct work_struct *work);
+#else
+extern  void    dm_txpower_trackingcallback(struct net_device *dev);
+#endif
+extern  void    dm_restore_dynamic_mechanism_state(struct net_device *dev);
+extern  void    dm_backup_dynamic_mechanism_state(struct net_device *dev);
+extern  void    dm_change_dynamic_initgain_thresh(struct net_device *dev,
+                                                                u32 dm_type, u32 dm_value);
+extern  void    dm_force_tx_fw_info(struct net_device *dev,u32 force_type, u32 force_value);
+extern  void    dm_init_edca_turbo(struct net_device *dev);
+extern  void    dm_rf_operation_test_callback(unsigned long data);
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern  void    dm_rf_pathcheck_workitemcallback(struct work_struct *work);
+#else
+extern  void    dm_rf_pathcheck_workitemcallback(struct net_device *dev);
+#endif
+extern  void dm_fsync_timer_callback(unsigned long data);
+extern	void	dm_cck_txpower_adjust(struct net_device *dev,bool  binch14);
+#if 0
+extern  char    dm_check_lbus_status(IN PADAPTER        Adapter);
+#endif
+extern  void    dm_shadow_init(struct net_device *dev);
+extern void dm_initialize_txpower_tracking(struct net_device *dev);
+/*--------------------------Exported Function prototype---------------------*/
+
+
+#endif	/*__R8192UDM_H__ */
+
+
+/* End of r8192U_dm.h */
+
diff --git a/drivers/staging/rtl8192su/r8192U_hw.h b/drivers/staging/rtl8192su/r8192U_hw.h
new file mode 100644
index 0000000..f2500e6
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192U_hw.h
@@ -0,0 +1,746 @@
+/*
+	This is part of rtl8187 OpenSource driver.
+	Copyright (C) Andrea Merello 2004-2005  <andreamrl@tiscali.it>
+	Released under the terms of GPL (General Public Licence)
+
+	Parts of this driver are based on the GPL part of the
+	official Realtek driver.
+	Parts of this driver are based on the rtl8180 driver skeleton
+	from Patric Schenke & Andres Salomon.
+	Parts of this driver are based on the Intel Pro Wireless
+	2100 GPL driver.
+
+	We want to tanks the Authors of those projects
+	and the Ndiswrapper project Authors.
+*/
+
+/* Mariusz Matuszek added full registers definition with Realtek's name */
+
+/* this file contains register definitions for the rtl8187 MAC controller */
+#ifndef R8192_HW
+#define R8192_HW
+
+typedef enum _VERSION_819xU{
+	VERSION_819xU_A, // A-cut
+	VERSION_819xU_B, // B-cut
+	VERSION_819xU_C,// C-cut
+}VERSION_819xU,*PVERSION_819xU;
+//added for different RF type
+typedef enum _RT_RF_TYPE_DEF
+{
+	RF_1T2R = 0,
+	RF_2T4R,
+
+	RF_819X_MAX_TYPE
+}RT_RF_TYPE_DEF;
+
+
+typedef enum _BaseBand_Config_Type{
+	BaseBand_Config_PHY_REG = 0,			//Radio Path A
+	BaseBand_Config_AGC_TAB = 1,			//Radio Path B
+}BaseBand_Config_Type, *PBaseBand_Config_Type;
+#if 0
+typedef enum _RT_RF_TYPE_819xU{
+	RF_TYPE_MIN = 0,
+	RF_8225,
+	RF_8256,
+	RF_8258,
+	RF_PSEUDO_11N = 4,
+}RT_RF_TYPE_819xU, *PRT_RF_TYPE_819xU;
+#endif
+#define	RTL8187_REQT_READ	0xc0
+#define	RTL8187_REQT_WRITE	0x40
+#define	RTL8187_REQ_GET_REGS	0x05
+#define	RTL8187_REQ_SET_REGS	0x05
+
+#define MAX_TX_URB 16  //less URB will cause 2.4.31 crash, need to fix it further
+#define MAX_RX_URB 16
+
+#define R8180_MAX_RETRY 255
+//#define MAX_RX_NORMAL_URB 3
+//#define MAX_RX_COMMAND_URB 2
+#define RX_URB_SIZE 9100
+
+#define BB_ANTATTEN_CHAN14	0x0c
+#define BB_ANTENNA_B 0x40
+
+#define BB_HOST_BANG (1<<30)
+#define BB_HOST_BANG_EN (1<<2)
+#define BB_HOST_BANG_CLK (1<<1)
+#define BB_HOST_BANG_RW (1<<3)
+#define BB_HOST_BANG_DATA	 1
+
+//#if (RTL819X_FPGA_VER & RTL819X_FPGA_VIVI_070920)
+#define AFR			0x010
+#define AFR_CardBEn		(1<<0)
+#define AFR_CLKRUN_SEL		(1<<1)
+#define AFR_FuncRegEn		(1<<2)
+#define RTL8190_EEPROM_ID	0x8129
+#define EEPROM_VID		0x02
+#define EEPROM_PID		0x04
+#define EEPROM_NODE_ADDRESS_BYTE_0	0x0C
+
+#define EEPROM_TxPowerDiff	0x1F
+#define EEPROM_ThermalMeter	0x20
+#define EEPROM_PwDiff		0x21	//0x21
+#define EEPROM_CrystalCap	0x22	//0x22
+
+#define EEPROM_TxPwIndex_CCK	0x23	//0x23
+#define EEPROM_TxPwIndex_OFDM_24G	0x24	//0x24~0x26
+#define EEPROM_TxPwIndex_CCK_V1		0x29	//0x29~0x2B
+#define EEPROM_TxPwIndex_OFDM_24G_V1	0x2C	//0x2C~0x2E
+#define EEPROM_TxPwIndex_Ver		0x27	//0x27
+
+#define EEPROM_Default_TxPowerDiff		0x0
+#define EEPROM_Default_ThermalMeter		0x7
+#define EEPROM_Default_PwDiff			0x4
+#define EEPROM_Default_CrystalCap		0x5
+#define EEPROM_Default_TxPower			0x1010
+#define EEPROM_Customer_ID			0x7B	//0x7B:CustomerID
+#define EEPROM_ChannelPlan			0x16	//0x7C
+#define EEPROM_IC_VER				0x7d	//0x7D
+#define EEPROM_CRC				0x7e	//0x7E~0x7F
+
+#define EEPROM_CID_DEFAULT			0x0
+#define EEPROM_CID_CAMEO				0x1
+#define EEPROM_CID_RUNTOP				0x2
+#define EEPROM_CID_Senao				0x3
+#define EEPROM_CID_TOSHIBA				0x4	// Toshiba setting, Merge by Jacken, 2008/01/31
+#define EEPROM_CID_NetCore				0x5
+#define EEPROM_CID_Nettronix			0x6
+#define EEPROM_CID_Pronet				0x7
+#define EEPROM_CID_DLINK				0x8
+
+#define AC_PARAM_TXOP_LIMIT_OFFSET	16
+#define AC_PARAM_ECW_MAX_OFFSET		12
+#define AC_PARAM_ECW_MIN_OFFSET		8
+#define AC_PARAM_AIFS_OFFSET		0
+
+//#endif
+enum _RTL8192Usb_HW {
+
+	PCIF			= 0x009, // PCI Function Register 0x0009h~0x000bh
+#define	BB_GLOBAL_RESET_BIT	0x1
+	BB_GLOBAL_RESET		= 0x020, // BasebandGlobal Reset Register
+	BSSIDR			= 0x02E, // BSSID Register
+	CMDR			= 0x037, // Command register
+#define CR_RST			0x10
+#define CR_RE			0x08
+#define CR_TE			0x04
+#define CR_MulRW		0x01
+	SIFS			= 0x03E, // SIFS register
+	TCR			= 0x040, // Transmit Configuration Register
+
+#define TCR_MXDMA_2048 		7
+#define TCR_LRL_OFFSET		0
+#define TCR_SRL_OFFSET		8
+#define TCR_MXDMA_OFFSET	21
+#define TCR_SAT			BIT24		// Enable Rate depedent ack timeout timer
+	RCR			= 0x044, // Receive Configuration Register
+#define MAC_FILTER_MASK ((1<<0) | (1<<1) | (1<<2) | (1<<3) | (1<<5) | \
+		(1<<12) | (1<<18) | (1<<19) | (1<<20) | (1<<21) | (1<<22) | (1<<23))
+#define RX_FIFO_THRESHOLD_MASK ((1<<13) | (1<<14) | (1<<15))
+#define RX_FIFO_THRESHOLD_SHIFT 13
+#define RX_FIFO_THRESHOLD_128 3
+#define RX_FIFO_THRESHOLD_256 4
+#define RX_FIFO_THRESHOLD_512 5
+#define RX_FIFO_THRESHOLD_1024 6
+#define RX_FIFO_THRESHOLD_NONE 7
+#define MAX_RX_DMA_MASK ((1<<8) | (1<<9) | (1<<10))
+#define RCR_MXDMA_OFFSET	8
+#define RCR_FIFO_OFFSET		13
+#define RCR_ONLYERLPKT		BIT31			// Early Receiving based on Packet Size.
+#define RCR_ENCS2		BIT30			// Enable Carrier Sense Detection Method 2
+#define RCR_ENCS1		BIT29			// Enable Carrier Sense Detection Method 1
+#define RCR_ENMBID		BIT27			// Enable Multiple BssId.
+#define RCR_ACKTXBW		(BIT24|BIT25)		// TXBW Setting of ACK frames
+#define RCR_CBSSID		BIT23			// Accept BSSID match packet
+#define RCR_APWRMGT		BIT22			// Accept power management packet
+#define	RCR_ADD3		BIT21			// Accept address 3 match packet
+#define RCR_AMF			BIT20			// Accept management type frame
+#define RCR_ACF			BIT19			// Accept control type frame
+#define RCR_ADF			BIT18			// Accept data type frame
+#define RCR_RXFTH		BIT13			// Rx FIFO Threshold
+#define RCR_AICV		BIT12			// Accept ICV error packet
+#define	RCR_ACRC32		BIT5			// Accept CRC32 error packet
+#define	RCR_AB			BIT3			// Accept broadcast packet
+#define	RCR_AM			BIT2			// Accept multicast packet
+#define	RCR_APM			BIT1			// Accept physical match packet
+#define	RCR_AAP			BIT0			// Accept all unicast packet
+	SLOT_TIME		= 0x049, // Slot Time Register
+	ACK_TIMEOUT		= 0x04c, // Ack Timeout Register
+	PIFS_TIME		= 0x04d, // PIFS time
+	USTIME			= 0x04e, // Microsecond Tuning Register, Sets the microsecond time unit used by MAC clock.
+	EDCAPARA_BE		= 0x050, // EDCA Parameter of AC BE
+	EDCAPARA_BK		= 0x054, // EDCA Parameter of AC BK
+	EDCAPARA_VO		= 0x058, // EDCA Parameter of AC VO
+	EDCAPARA_VI		= 0x05C, // EDCA Parameter of AC VI
+	RFPC			= 0x05F, // Rx FIFO Packet Count
+	CWRR			= 0x060, // Contention Window Report Register
+	BCN_TCFG		= 0x062, // Beacon Time Configuration
+#define BCN_TCFG_CW_SHIFT		8
+#define BCN_TCFG_IFS			0
+	BCN_INTERVAL		= 0x070, // Beacon Interval (TU)
+	ATIMWND			= 0x072, // ATIM Window Size (TU)
+	BCN_DRV_EARLY_INT	= 0x074, // Driver Early Interrupt Time (TU). Time to send interrupt to notify to change beacon content before TBTT
+	BCN_DMATIME		= 0x076, // Beacon DMA and ATIM interrupt time (US). Indicates the time before TBTT to perform beacon queue DMA
+	BCN_ERR_THRESH		= 0x078, // Beacon Error Threshold
+	RWCAM			= 0x0A0, //IN 8190 Data Sheet is called CAMcmd
+	WCAMI			= 0x0A4, // Software write CAM input content
+	RCAMO			= 0x0A8, // Software read/write CAM config
+	SECR			= 0x0B0, //Security Configuration Register
+#define	SCR_TxUseDK		BIT0			//Force Tx Use Default Key
+#define SCR_RxUseDK		BIT1			//Force Rx Use Default Key
+#define SCR_TxEncEnable		BIT2			//Enable Tx Encryption
+#define SCR_RxDecEnable		BIT3			//Enable Rx Decryption
+#define SCR_SKByA2		BIT4			//Search kEY BY A2
+#define SCR_NoSKMC		BIT5			//No Key Search for Multicast
+#define SCR_UseDK		0x01
+#define SCR_TxSecEnable		0x02
+#define SCR_RxSecEnable		0x04
+	TPPoll			= 0x0fd, // Transmit priority polling register
+	PSR			= 0x0ff, // Page Select Register
+#define CPU_CCK_LOOPBACK	0x00030000
+#define CPU_GEN_SYSTEM_RESET	0x00000001
+#define CPU_GEN_FIRMWARE_RESET	0x00000008
+#define CPU_GEN_BOOT_RDY	0x00000010
+#define CPU_GEN_FIRM_RDY	0x00000020
+#define CPU_GEN_PUT_CODE_OK	0x00000080
+#define CPU_GEN_BB_RST		0x00000100
+#define CPU_GEN_PWR_STB_CPU	0x00000004
+#define CPU_GEN_NO_LOOPBACK_MSK	0xFFF8FFFF		// Set bit18,17,16 to 0. Set bit19
+#define CPU_GEN_NO_LOOPBACK_SET	0x00080000		// Set BIT19 to 1
+
+//----------------------------------------------------------------------------
+//       8190 CPU General Register		(offset 0x100, 4 byte)
+//----------------------------------------------------------------------------
+#define	CPU_CCK_LOOPBACK	0x00030000
+#define	CPU_GEN_SYSTEM_RESET	0x00000001
+#define	CPU_GEN_FIRMWARE_RESET	0x00000008
+#define	CPU_GEN_BOOT_RDY	0x00000010
+#define	CPU_GEN_FIRM_RDY	0x00000020
+#define	CPU_GEN_PUT_CODE_OK	0x00000080
+#define	CPU_GEN_BB_RST		0x00000100
+#define	CPU_GEN_PWR_STB_CPU	0x00000004
+#define CPU_GEN_NO_LOOPBACK_MSK	0xFFF8FFFF // Set bit18,17,16 to 0. Set bit19
+#define CPU_GEN_NO_LOOPBACK_SET	0x00080000 // Set BIT19 to 1
+	CPU_GEN			= 0x100, // CPU Reset Register
+	LED1Cfg			=		0x154,// LED1 Configuration Register
+ 	LED0Cfg			=		0x155,// LED0 Configuration Register
+
+	AcmAvg			= 0x170, // ACM Average Period Register
+	AcmHwCtrl		= 0x171, // ACM Hardware Control Register
+//----------------------------------------------------------------------------
+////
+////       8190 AcmHwCtrl bits                                    (offset 0x171, 1 byte)
+////----------------------------------------------------------------------------
+//
+#define AcmHw_HwEn              BIT0
+#define AcmHw_BeqEn             BIT1
+#define AcmHw_ViqEn             BIT2
+#define AcmHw_VoqEn             BIT3
+#define AcmHw_BeqStatus         BIT4
+#define AcmHw_ViqStatus         BIT5
+#define AcmHw_VoqStatus         BIT6
+
+	AcmFwCtrl		= 0x172, // ACM Firmware Control Register
+	AES_11N_FIX		= 0x173,
+	VOAdmTime		= 0x174, // VO Queue Admitted Time Register
+	VIAdmTime		= 0x178, // VI Queue Admitted Time Register
+	BEAdmTime		= 0x17C, // BE Queue Admitted Time Register
+	RQPN1			= 0x180, // Reserved Queue Page Number , Vo Vi, Be, Bk
+	RQPN2			= 0x184, // Reserved Queue Page Number, HCCA, Cmd, Mgnt, High
+	RQPN3			= 0x188, // Reserved Queue Page Number, Bcn, Public,
+//	QPRR			= 0x1E0, // Queue Page Report per TID
+	QPNR			= 0x1D0, //0x1F0, // Queue Packet Number report per TID
+	BQDA			= 0x200, // Beacon Queue Descriptor Address
+	HQDA			= 0x204, // High Priority Queue Descriptor Address
+	CQDA			= 0x208, // Command Queue Descriptor Address
+	MQDA			= 0x20C, // Management Queue Descriptor Address
+	HCCAQDA			= 0x210, // HCCA Queue Descriptor Address
+	VOQDA			= 0x214, // VO Queue Descriptor Address
+	VIQDA			= 0x218, // VI Queue Descriptor Address
+	BEQDA			= 0x21C, // BE Queue Descriptor Address
+	BKQDA			= 0x220, // BK Queue Descriptor Address
+	RCQDA			= 0x224, // Receive command Queue Descriptor Address
+	RDQDA			= 0x228, // Receive Queue Descriptor Start Address
+
+	MAR0			= 0x240, // Multicast filter.
+	MAR4			= 0x244,
+
+	CCX_PERIOD		= 0x250, // CCX Measurement Period Register, in unit of TU.
+	CLM_RESULT		= 0x251, // CCA Busy fraction register.
+	NHM_PERIOD		= 0x252, // NHM Measurement Period register, in unit of TU.
+
+	NHM_THRESHOLD0		= 0x253, // Noise Histogram Meashorement0.
+	NHM_THRESHOLD1		= 0x254, // Noise Histogram Meashorement1.
+	NHM_THRESHOLD2		= 0x255, // Noise Histogram Meashorement2.
+	NHM_THRESHOLD3		= 0x256, // Noise Histogram Meashorement3.
+	NHM_THRESHOLD4		= 0x257, // Noise Histogram Meashorement4.
+	NHM_THRESHOLD5		= 0x258, // Noise Histogram Meashorement5.
+	NHM_THRESHOLD6		= 0x259, // Noise Histogram Meashorement6
+
+	MCTRL			= 0x25A, // Measurement Control
+
+	NHM_RPI_COUNTER0	= 0x264, // Noise Histogram RPI counter0, the fraction of signal strength < NHM_THRESHOLD0.
+	NHM_RPI_COUNTER1	= 0x265, // Noise Histogram RPI counter1, the fraction of signal strength in (NHM_THRESHOLD0, NHM_THRESHOLD1].
+	NHM_RPI_COUNTER2	= 0x266, // Noise Histogram RPI counter2, the fraction of signal strength in (NHM_THRESHOLD1, NHM_THRESHOLD2].
+	NHM_RPI_COUNTER3	= 0x267, // Noise Histogram RPI counter3, the fraction of signal strength in (NHM_THRESHOLD2, NHM_THRESHOLD3].
+	NHM_RPI_COUNTER4	= 0x268, // Noise Histogram RPI counter4, the fraction of signal strength in (NHM_THRESHOLD3, NHM_THRESHOLD4].
+	NHM_RPI_COUNTER5	= 0x269, // Noise Histogram RPI counter5, the fraction of signal strength in (NHM_THRESHOLD4, NHM_THRESHOLD5].
+	NHM_RPI_COUNTER6	= 0x26A, // Noise Histogram RPI counter6, the fraction of signal strength in (NHM_THRESHOLD5, NHM_THRESHOLD6].
+	NHM_RPI_COUNTER7	= 0x26B, // Noise Histogram RPI counter7, the fraction of signal strength in (NHM_THRESHOLD6, NHM_THRESHOLD7].
+#define	BW_OPMODE_11J			BIT0
+#define	BW_OPMODE_5G			BIT1
+#define	BW_OPMODE_20MHZ			BIT2
+	BW_OPMODE		= 0x300, // Bandwidth operation mode
+	MSR			= 0x303, // Media Status register
+#define MSR_LINK_MASK      ((1<<0)|(1<<1))
+#define MSR_LINK_MANAGED   2
+#define MSR_LINK_NONE      0
+#define MSR_LINK_SHIFT     0
+#define MSR_LINK_ADHOC     1
+#define MSR_LINK_MASTER    3
+#define MSR_LINK_ENEDCA	   (1<<4)
+	RETRY_LIMIT		= 0x304, // Retry Limit [15:8]-short, [7:0]-long
+#define RETRY_LIMIT_SHORT_SHIFT 8
+#define RETRY_LIMIT_LONG_SHIFT 0
+	TSFR			= 0x308,
+	RRSR			= 0x310, // Response Rate Set
+#define RRSR_RSC_OFFSET			21
+#define RRSR_SHORT_OFFSET			23
+#define RRSR_RSC_DUPLICATE			0x600000
+#define RRSR_RSC_LOWSUBCHNL		0x400000
+#define RRSR_RSC_UPSUBCHANL		0x200000
+#define RRSR_SHORT					0x800000
+#define RRSR_1M						BIT0
+#define RRSR_2M						BIT1
+#define RRSR_5_5M					BIT2
+#define RRSR_11M					BIT3
+#define RRSR_6M						BIT4
+#define RRSR_9M						BIT5
+#define RRSR_12M					BIT6
+#define RRSR_18M					BIT7
+#define RRSR_24M					BIT8
+#define RRSR_36M					BIT9
+#define RRSR_48M					BIT10
+#define RRSR_54M					BIT11
+#define RRSR_MCS0					BIT12
+#define RRSR_MCS1					BIT13
+#define RRSR_MCS2					BIT14
+#define RRSR_MCS3					BIT15
+#define RRSR_MCS4					BIT16
+#define RRSR_MCS5					BIT17
+#define RRSR_MCS6					BIT18
+#define RRSR_MCS7					BIT19
+#define BRSR_AckShortPmb			BIT23		// CCK ACK: use Short Preamble or not.
+	RATR0			= 0x320, // Rate Adaptive Table register1
+	UFWP			= 0x318,
+	DRIVER_RSSI		= 0x32c,					// Driver tell Firmware current RSSI
+//----------------------------------------------------------------------------
+//       8190 Rate Adaptive Table Register	(offset 0x320, 4 byte)
+//----------------------------------------------------------------------------
+//CCK
+#define	RATR_1M			0x00000001
+#define	RATR_2M			0x00000002
+#define	RATR_55M		0x00000004
+#define	RATR_11M		0x00000008
+//OFDM
+#define	RATR_6M			0x00000010
+#define	RATR_9M			0x00000020
+#define	RATR_12M		0x00000040
+#define	RATR_18M		0x00000080
+#define	RATR_24M		0x00000100
+#define	RATR_36M		0x00000200
+#define	RATR_48M		0x00000400
+#define	RATR_54M		0x00000800
+//MCS 1 Spatial Stream
+#define	RATR_MCS0		0x00001000
+#define	RATR_MCS1		0x00002000
+#define	RATR_MCS2		0x00004000
+#define	RATR_MCS3		0x00008000
+#define	RATR_MCS4		0x00010000
+#define	RATR_MCS5		0x00020000
+#define	RATR_MCS6		0x00040000
+#define	RATR_MCS7		0x00080000
+//MCS 2 Spatial Stream
+#define	RATR_MCS8		0x00100000
+#define	RATR_MCS9		0x00200000
+#define	RATR_MCS10		0x00400000
+#define	RATR_MCS11		0x00800000
+#define	RATR_MCS12		0x01000000
+#define	RATR_MCS13		0x02000000
+#define	RATR_MCS14		0x04000000
+#define	RATR_MCS15		0x08000000
+// ALL CCK Rate
+#define RATE_ALL_CCK		RATR_1M|RATR_2M|RATR_55M|RATR_11M
+#define RATE_ALL_OFDM_AG	RATR_6M|RATR_9M|RATR_12M|RATR_18M|RATR_24M\
+							|RATR_36M|RATR_48M|RATR_54M
+#define RATE_ALL_OFDM_1SS	RATR_MCS0|RATR_MCS1|RATR_MCS2|RATR_MCS3 | \
+							RATR_MCS4|RATR_MCS5|RATR_MCS6|RATR_MCS7
+#define RATE_ALL_OFDM_2SS	RATR_MCS8|RATR_MCS9	|RATR_MCS10|RATR_MCS11| \
+							RATR_MCS12|RATR_MCS13|RATR_MCS14|RATR_MCS15
+
+	MCS_TXAGC		= 0x340, // MCS AGC
+	CCK_TXAGC		= 0x348, // CCK AGC
+//	ISR			= 0x350, // Interrupt Status Register
+//	IMR			= 0x354, // Interrupt Mask Register
+//	IMR_POLL		= 0x360,
+	MacBlkCtrl		= 0x403, // Mac block on/off control register
+
+	EPROM_CMD 		= 0xfe58,
+#define Cmd9346CR_9356SEL	(1<<4)
+#define EPROM_CMD_RESERVED_MASK (1<<5)
+#define EPROM_CMD_OPERATING_MODE_SHIFT 6
+#define EPROM_CMD_OPERATING_MODE_MASK ((1<<7)|(1<<6))
+#define EPROM_CMD_CONFIG 0x3
+#define EPROM_CMD_NORMAL 0
+#define EPROM_CMD_LOAD 1
+#define EPROM_CMD_PROGRAM 2
+#define EPROM_CS_SHIFT 3
+#define EPROM_CK_SHIFT 2
+#define EPROM_W_SHIFT 1
+#define EPROM_R_SHIFT 0
+	MAC0 			= 0x000,
+	MAC1 			= 0x001,
+	MAC2 			= 0x002,
+	MAC3 			= 0x003,
+	MAC4 			= 0x004,
+	MAC5 			= 0x005,
+
+#if 0
+/* 0x0006 - 0x0007 - reserved */
+	RXFIFOCOUNT 		= 0x010,
+	TXFIFOCOUNT 		= 0x012,
+	BQREQ 			= 0x013,
+/* 0x0010 - 0x0017 - reserved */
+	TSFTR 			= 0x018,
+	TLPDA 			= 0x020,
+	TNPDA 			= 0x024,
+	THPDA 			= 0x028,
+	BSSID 			= 0x02E,
+	RESP_RATE 		= 0x034,
+	CMD 			= 0x037,
+#define CMD_RST_SHIFT 4
+#define CMD_RESERVED_MASK ((1<<1) | (1<<5) | (1<<6) | (1<<7))
+#define CMD_RX_ENABLE_SHIFT 3
+#define CMD_TX_ENABLE_SHIFT 2
+#define CR_RST      ((1<< 4))
+#define CR_RE       ((1<< 3))
+#define CR_TE       ((1<< 2))
+#define CR_MulRW    ((1<< 0))
+
+	INTA_MASK 		= 0x03c,
+	INTA 			= 0x03e,
+#define INTA_TXOVERFLOW (1<<15)
+#define INTA_TIMEOUT (1<<14)
+#define INTA_BEACONTIMEOUT (1<<13)
+#define INTA_ATIM (1<<12)
+#define INTA_BEACONDESCERR (1<<11)
+#define INTA_BEACONDESCOK (1<<10)
+#define INTA_HIPRIORITYDESCERR (1<<9)
+#define INTA_HIPRIORITYDESCOK (1<<8)
+#define INTA_NORMPRIORITYDESCERR (1<<7)
+#define INTA_NORMPRIORITYDESCOK (1<<6)
+#define INTA_RXOVERFLOW (1<<5)
+#define INTA_RXDESCERR (1<<4)
+#define INTA_LOWPRIORITYDESCERR (1<<3)
+#define INTA_LOWPRIORITYDESCOK (1<<2)
+#define INTA_RXCRCERR (1<<1)
+#define INTA_RXOK (1)
+	TX_CONF 		= 0x040,
+#define TX_CONF_HEADER_AUTOICREMENT_SHIFT 30
+#define TX_LOOPBACK_SHIFT 17
+#define TX_LOOPBACK_MAC 1
+#define TX_LOOPBACK_BASEBAND 2
+#define TX_LOOPBACK_NONE 0
+#define TX_LOOPBACK_CONTINUE 3
+#define TX_LOOPBACK_MASK ((1<<17)|(1<<18))
+#define TX_LRLRETRY_SHIFT 0
+#define TX_SRLRETRY_SHIFT 8
+#define TX_NOICV_SHIFT 19
+#define TX_NOCRC_SHIFT 16
+#define TCR_DurProcMode  ((1<<30))
+#define TCR_DISReqQsize  ((1<<28))
+#define TCR_HWVERID_MASK ((1<<27)|(1<<26)|(1<<25))
+#define TCR_HWVERID_SHIFT 25
+#define TCR_SWPLCPLEN     ((1<<24))
+#define TCR_PLCP_LEN TCR_SAT // rtl8180
+#define TCR_MXDMA_MASK   ((1<<23)|(1<<22)|(1<<21))
+#define TCR_MXDMA_1024 6
+#define TCR_MXDMA_2048 7
+#define TCR_MXDMA_SHIFT  21
+#define TCR_DISCW   ((1<<20))
+#define TCR_ICV     ((1<<19))
+#define TCR_LBK     ((1<<18)|(1<<17))
+#define TCR_LBK1    ((1<<18))
+#define TCR_LBK0    ((1<<17))
+#define TCR_CRC     ((1<<16))
+#define TCR_SRL_MASK   ((1<<15)|(1<<14)|(1<<13)|(1<<12)|(1<<11)|(1<<10)|(1<<9)|(1<<8))
+#define TCR_LRL_MASK   ((1<<0)|(1<<1)|(1<<2)|(1<<3)|(1<<4)|(1<<5)|(1<<6)|(1<<7))
+#define TCR_PROBE_NOTIMESTAMP_SHIFT 29 //rtl8185
+	RX_CONF 		= 0x044,
+#define MAC_FILTER_MASK ((1<<0) | (1<<1) | (1<<2) | (1<<3) | (1<<5) | \
+(1<<12) | (1<<18) | (1<<19) | (1<<20) | (1<<21) | (1<<22) | (1<<23))
+#define RX_CHECK_BSSID_SHIFT 23
+#define ACCEPT_PWR_FRAME_SHIFT 22
+#define ACCEPT_MNG_FRAME_SHIFT 20
+#define ACCEPT_CTL_FRAME_SHIFT 19
+#define ACCEPT_DATA_FRAME_SHIFT 18
+#define ACCEPT_ICVERR_FRAME_SHIFT 12
+#define ACCEPT_CRCERR_FRAME_SHIFT 5
+#define ACCEPT_BCAST_FRAME_SHIFT 3
+#define ACCEPT_MCAST_FRAME_SHIFT 2
+#define ACCEPT_ALLMAC_FRAME_SHIFT 0
+#define ACCEPT_NICMAC_FRAME_SHIFT 1
+#define RX_FIFO_THRESHOLD_MASK ((1<<13) | (1<<14) | (1<<15))
+#define RX_FIFO_THRESHOLD_SHIFT 13
+#define RX_FIFO_THRESHOLD_128 3
+#define RX_FIFO_THRESHOLD_256 4
+#define RX_FIFO_THRESHOLD_512 5
+#define RX_FIFO_THRESHOLD_1024 6
+#define RX_FIFO_THRESHOLD_NONE 7
+#define RX_AUTORESETPHY_SHIFT 28
+#define MAX_RX_DMA_MASK ((1<<8) | (1<<9) | (1<<10))
+#define MAX_RX_DMA_2048 7
+#define MAX_RX_DMA_1024	6
+#define MAX_RX_DMA_SHIFT 10
+#define RCR_ONLYERLPKT ((1<<31))
+#define RCR_CS_SHIFT   29
+#define RCR_CS_MASK    ((1<<30) | (1<<29))
+#define RCR_ENMARP     ((1<<28))
+#define RCR_CBSSID     ((1<<23))
+#define RCR_APWRMGT    ((1<<22))
+#define RCR_ADD3       ((1<<21))
+#define RCR_AMF        ((1<<20))
+#define RCR_ACF        ((1<<19))
+#define RCR_ADF        ((1<<18))
+#define RCR_RXFTH      ((1<<15)|(1<<14)|(1<<13))
+#define RCR_RXFTH2     ((1<<15))
+#define RCR_RXFTH1     ((1<<14))
+#define RCR_RXFTH0     ((1<<13))
+#define RCR_AICV       ((1<<12))
+#define RCR_MXDMA      ((1<<10)|(1<< 9)|(1<< 8))
+#define RCR_MXDMA2     ((1<<10))
+#define RCR_MXDMA1     ((1<< 9))
+#define RCR_MXDMA0     ((1<< 8))
+#define RCR_9356SEL    ((1<< 6))
+#define RCR_ACRC32     ((1<< 5))
+#define RCR_AB         ((1<< 3))
+#define RCR_AM         ((1<< 2))
+#define RCR_APM        ((1<< 1))
+#define RCR_AAP        ((1<< 0))
+	INT_TIMEOUT 		= 0x048,
+	TX_BEACON_RING_ADDR 	= 0x04c,
+	EPROM_CMD 		= 0x58,
+#define EPROM_CMD_RESERVED_MASK ((1<<5)|(1<<4))
+#define EPROM_CMD_OPERATING_MODE_SHIFT 6
+#define EPROM_CMD_OPERATING_MODE_MASK ((1<<7)|(1<<6))
+#define EPROM_CMD_CONFIG 0x3
+#define EPROM_CMD_NORMAL 0
+#define EPROM_CMD_LOAD 1
+#define EPROM_CMD_PROGRAM 2
+#define EPROM_CS_SHIFT 3
+#define EPROM_CK_SHIFT 2
+#define EPROM_W_SHIFT 1
+#define EPROM_R_SHIFT 0
+	CONFIG0 		= 0x051,
+#define CONFIG0_WEP104     ((1<<6))
+#define CONFIG0_LEDGPO_En  ((1<<4))
+#define CONFIG0_Aux_Status ((1<<3))
+#define CONFIG0_GL         ((1<<1)|(1<<0))
+#define CONFIG0_GL1        ((1<<1))
+#define CONFIG0_GL0        ((1<<0))
+	CONFIG1 		= 0x052,
+#define CONFIG1_LEDS       ((1<<7)|(1<<6))
+#define CONFIG1_LEDS1      ((1<<7))
+#define CONFIG1_LEDS0      ((1<<6))
+#define CONFIG1_LWACT      ((1<<4))
+#define CONFIG1_MEMMAP     ((1<<3))
+#define CONFIG1_IOMAP      ((1<<2))
+#define CONFIG1_VPD        ((1<<1))
+#define CONFIG1_PMEn       ((1<<0))
+	CONFIG2 		= 0x053,
+#define CONFIG2_LCK        ((1<<7))
+#define CONFIG2_ANT        ((1<<6))
+#define CONFIG2_DPS        ((1<<3))
+#define CONFIG2_PAPE_sign  ((1<<2))
+#define CONFIG2_PAPE_time  ((1<<1)|(1<<0))
+#define CONFIG2_PAPE_time1 ((1<<1))
+#define CONFIG2_PAPE_time0 ((1<<0))
+	ANA_PARAM 		= 0x054,
+	CONFIG3 		= 0x059,
+#define CONFIG3_GNTSel     ((1<<7))
+#define CONFIG3_PARM_En    ((1<<6))
+#define CONFIG3_Magic      ((1<<5))
+#define CONFIG3_CardB_En   ((1<<3))
+#define CONFIG3_CLKRUN_En  ((1<<2))
+#define CONFIG3_FuncRegEn  ((1<<1))
+#define CONFIG3_FBtbEn     ((1<<0))
+#define CONFIG3_CLKRUN_SHIFT 2
+#define CONFIG3_ANAPARAM_W_SHIFT 6
+	CONFIG4 		= 0x05a,
+#define CONFIG4_VCOPDN     ((1<<7))
+#define CONFIG4_PWROFF     ((1<<6))
+#define CONFIG4_PWRMGT     ((1<<5))
+#define CONFIG4_LWPME      ((1<<4))
+#define CONFIG4_LWPTN      ((1<<2))
+#define CONFIG4_RFTYPE     ((1<<1)|(1<<0))
+#define CONFIG4_RFTYPE1    ((1<<1))
+#define CONFIG4_RFTYPE0    ((1<<0))
+	TESTR 			= 0x05b,
+#define TFPC_AC  0x05C
+
+#define SCR 0x05F
+	PGSELECT 		= 0x05e,
+#define PGSELECT_PG_SHIFT 0
+	SECURITY 		= 0x05f,
+#define SECURITY_WEP_TX_ENABLE_SHIFT 1
+#define SECURITY_WEP_RX_ENABLE_SHIFT 0
+#define SECURITY_ENCRYP_104 1
+#define SECURITY_ENCRYP_SHIFT 4
+#define SECURITY_ENCRYP_MASK ((1<<4)|(1<<5))
+	ANA_PARAM2 		= 0x060,
+	BEACON_INTERVAL 	= 0x070,
+#define BEACON_INTERVAL_MASK ((1<<0)|(1<<1)|(1<<2)|(1<<3)|(1<<4)|(1<<5)| \
+(1<<6)|(1<<7)|(1<<8)|(1<<9))
+	ATIM_WND 		= 0x072,
+#define ATIM_WND_MASK      (0x01FF)
+	BCN_INTR_ITV 		= 0x074,
+#define BCN_INTR_ITV_MASK  (0x01FF)
+	ATIM_INTR_ITV		= 0x076,
+#define ATIM_INTR_ITV_MASK  (0x01FF)
+	AckTimeOutReg      	= 0x079, //ACK timeout register, in unit of 4 us.
+	PHY_ADR 		= 0x07c,
+	PHY_READ 		= 0x07e,
+	RFPinsOutput 		= 0x080,
+	RFPinsEnable 		= 0x082,
+
+//Page 0
+	RFPinsSelect 		= 0x084,
+#define SW_CONTROL_GPIO 0x400
+	RFPinsInput 		= 0x086,
+	RF_PARA 		= 0x088,
+	RF_TIMING 		= 0x08c,
+	GP_ENABLE 		= 0x090,
+	GPIO 			= 0x091,
+	TX_AGC_CTL 		= 0x09c,
+#define TX_AGC_CTL_PER_PACKET_TXAGC	0x01
+#define TX_AGC_CTL_PERPACKET_GAIN_SHIFT 0
+#define TX_AGC_CTL_PERPACKET_ANTSEL_SHIFT 1
+#define TX_AGC_CTL_FEEDBACK_ANT 2
+#define TXAGC_CTL_PER_PACKET_ANT_SEL 0x02
+	OFDM_TXAGC 		= 0x09e,
+	ANTSEL 			= 0x09f,
+	WPA_CONFIG 		= 0x0b0,
+	SIFS 			= 0x0b4,
+	DIFS 			= 0x0b5,
+	SLOT 			= 0x0b6,
+	CW_CONF 		= 0x0bc,
+#define CW_CONF_PERPACKET_RETRY_LIMIT 0x02
+#define CW_CONF_PERPACKET_CW 0x01
+#define CW_CONF_PERPACKET_RETRY_SHIFT 1
+#define CW_CONF_PERPACKET_CW_SHIFT 0
+	CW_VAL 			= 0x0bd,
+	RATE_FALLBACK 		= 0x0be,
+#define MAX_RESP_RATE_SHIFT 4
+#define MIN_RESP_RATE_SHIFT 0
+#define RATE_FALLBACK_CTL_ENABLE  0x80
+#define RATE_FALLBACK_CTL_AUTO_STEP0 0x00
+	ACM_CONTROL             = 0x0BF,      // ACM Control Registe
+//----------------------------------------------------------------------------
+//       8187B ACM_CONTROL bits						(Offset 0xBF, 1 Byte)
+//----------------------------------------------------------------------------
+#define VOQ_ACM_EN				(0x01 << 7) //BIT7
+#define VIQ_ACM_EN				(0x01 << 6) //BIT6
+#define BEQ_ACM_EN				(0x01 << 5) //BIT5
+#define ACM_HW_EN				(0x01 << 4) //BIT4
+#define TXOPSEL					(0x01 << 3) //BIT3
+#define VOQ_ACM_CTL				(0x01 << 2) //BIT2 // Set to 1 when AC_VO used time reaches or exceeds the admitted time
+#define VIQ_ACM_CTL				(0x01 << 1) //BIT1 // Set to 1 when AC_VI used time reaches or exceeds the admitted time
+#define BEQ_ACM_CTL				(0x01 << 0) //BIT0 // Set to 1 when AC_BE used time reaches or exceeds the admitted time
+	CONFIG5 		= 0x0D8,
+#define CONFIG5_TX_FIFO_OK ((1<<7))
+#define CONFIG5_RX_FIFO_OK ((1<<6))
+#define CONFIG5_CALON      ((1<<5))
+#define CONFIG5_EACPI      ((1<<2))
+#define CONFIG5_LANWake    ((1<<1))
+#define CONFIG5_PME_STS    ((1<<0))
+	TX_DMA_POLLING 		= 0x0d9,
+#define TX_DMA_POLLING_BEACON_SHIFT 7
+#define TX_DMA_POLLING_HIPRIORITY_SHIFT 6
+#define TX_DMA_POLLING_NORMPRIORITY_SHIFT 5
+#define TX_DMA_POLLING_LOWPRIORITY_SHIFT 4
+#define TX_DMA_STOP_BEACON_SHIFT 3
+#define TX_DMA_STOP_HIPRIORITY_SHIFT 2
+#define TX_DMA_STOP_NORMPRIORITY_SHIFT 1
+#define TX_DMA_STOP_LOWPRIORITY_SHIFT 0
+	CWR 			= 0x0DC,
+	RetryCTR 		= 0x0DE,
+	INT_MIG                 = 0x0E2,      // Interrupt Migration (0xE2 ~ 0xE3)
+	TID_AC_MAP         	= 0x0E8,     // TID to AC Mapping Register
+	ANA_PARAM3 		= 0x0EE,
+
+
+//page 1
+	Wakeup0 		= 0x084,
+	Wakeup1 		= 0x08C,
+	Wakeup2LD 		= 0x094,
+	Wakeup2HD 		= 0x09C,
+	Wakeup3LD 		= 0x0A4,
+	Wakeup3HD 		= 0x0AC,
+	Wakeup4LD 		= 0x0B4,
+	Wakeup4HD 		= 0x0BC,
+	CRC0 			= 0x0C4,
+	CRC1 			= 0x0C6,
+	CRC2 			= 0x0C8,
+	CRC3 			= 0x0CA,
+	CRC4 			= 0x0CC,
+/* 0x00CE - 0x00D3 - reserved */
+
+	RFSW_CTRL               = 0x272,   // 0x272-0x273.
+
+//Reg Diff between rtl8187 and rtl8187B
+/**************************************************************************/
+	BRSR_8187 		= 0x02C,
+	BRSR_8187B 		= 0x034,
+#define BRSR_BPLCP  ((1<< 8))
+#define BRSR_MBR    ((1<< 1)|(1<< 0))
+#define BRSR_MBR_8185 ((1<< 11)|(1<< 10)|(1<< 9)|(1<< 8)|(1<< 7)|(1<< 6)|(1<< 5)|(1<< 4)|(1<< 3)|(1<< 2)|(1<< 1)|(1<< 0))
+#define BRSR_MBR0   ((1<< 0))
+#define BRSR_MBR1   ((1<< 1))
+
+/**************************************************************************/
+	EIFS_8187  		= 0x035,
+	EIFS_8187B 		= 0x02D,
+
+/**************************************************************************/
+	FER 			= 0x0F0,
+	FEMR 			= 0x0F4,
+	FPSR 			= 0x0F8,
+	FFER 			= 0x0FC,
+
+	AC_VO_PARAM             = 0x0F0,      // AC_VO Parameters Record
+	AC_VI_PARAM             = 0x0F4,      // AC_VI Parameters Record
+	AC_BE_PARAM             = 0x0F8,      // AC_BE Parameters Record
+	AC_BK_PARAM             = 0x0FC,      // AC_BK Parameters Record
+	TALLY_SEL 		= 0x0fc,
+//----------------------------------------------------------------------------
+//       8187B AC_XX_PARAM bits
+//----------------------------------------------------------------------------
+#define AC_PARAM_TXOP_LIMIT_OFFSET		16
+#define AC_PARAM_ECW_MAX_OFFSET			12
+#define AC_PARAM_ECW_MIN_OFFSET			8
+#define AC_PARAM_AIFS_OFFSET			0
+
+#endif
+};
+//----------------------------------------------------------------------------
+//       818xB AnaParm & AnaParm2 Register
+//----------------------------------------------------------------------------
+//#define ANAPARM_ASIC_ON    0x45090658
+//#define ANAPARM2_ASIC_ON   0x727f3f52
+#define GPI 0x108
+#define GPO 0x109
+#define GPE 0x10a
+#endif
diff --git a/drivers/staging/rtl8192su/r8192U_pm.c b/drivers/staging/rtl8192su/r8192U_pm.c
new file mode 100644
index 0000000..92c95aa
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192U_pm.c
@@ -0,0 +1,77 @@
+/*
+   Power management interface routines.
+   Written by Mariusz Matuszek.
+   This code is currently just a placeholder for later work and
+   does not do anything useful.
+
+   This is part of rtl8180 OpenSource driver.
+   Copyright (C) Andrea Merello 2004  <andreamrl@tiscali.it>
+   Released under the terms of GPL (General Public Licence)
+*/
+
+#ifdef CONFIG_RTL8192_PM
+#include "r8192U.h"
+#include "r8192U_pm.h"
+
+/*****************************************************************************/
+int rtl8192U_save_state (struct pci_dev *dev, u32 state)
+{
+	printk(KERN_NOTICE "r8192U save state call (state %u).\n", state);
+	return(-EAGAIN);
+}
+
+int rtl8192U_suspend(struct usb_interface *intf, pm_message_t state)
+{
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	struct net_device *dev = usb_get_intfdata(intf);
+#else
+	//struct net_device *dev = (struct net_device *)ptr;
+#endif
+	RT_TRACE(COMP_POWER, "============> r8192U suspend call.\n");
+
+	if(dev) {
+		 if (!netif_running(dev)) {
+		      printk(KERN_WARNING "netif not running, go out suspend function\n");
+		      return 0;
+		 }
+
+		dev->stop(dev);
+		mdelay(10);
+
+		netif_device_detach(dev);
+	}
+
+	return 0;
+}
+
+int rtl8192U_resume (struct usb_interface *intf)
+{
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	struct net_device *dev = usb_get_intfdata(intf);
+#else
+	//struct net_device *dev = (struct net_device *)ptr;
+#endif
+
+	RT_TRACE(COMP_POWER, "================>r8192U resume call.");
+
+	if(dev) {
+		if (!netif_running(dev)){
+			printk(KERN_WARNING "netif not running, go out resume function\n");
+			return 0;
+		}
+
+		netif_device_attach(dev);
+		dev->open(dev);
+	}
+
+        return 0;
+}
+
+int rtl8192U_enable_wake (struct pci_dev *dev, u32 state, int enable)
+{
+	printk(KERN_NOTICE "r8192U enable wake call (state %u, enable %d).\n",
+			state, enable);
+	return(-EAGAIN);
+}
+
+#endif //CONFIG_RTL8192_PM
diff --git a/drivers/staging/rtl8192su/r8192U_pm.h b/drivers/staging/rtl8192su/r8192U_pm.h
new file mode 100644
index 0000000..ab025d6
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192U_pm.h
@@ -0,0 +1,27 @@
+/*
+        Power management interface routines.
+	Written by Mariusz Matuszek.
+	This code is currently just a placeholder for later work and
+	does not do anything useful.
+
+	This is part of rtl8180 OpenSource driver.
+	Copyright (C) Andrea Merello 2004  <andreamrl@tiscali.it>
+	Released under the terms of GPL (General Public Licence)
+
+*/
+
+#ifdef CONFIG_RTL8192_PM
+
+#ifndef R8192_PM_H
+#define R8192_PM_H
+
+#include <linux/types.h>
+#include <linux/usb.h>
+
+int rtl8192U_save_tate (struct pci_dev *dev, u32 state);
+int rtl8192U_suspend(struct usb_interface *intf, pm_message_t state);
+int rtl8192U_resume (struct usb_interface *intf);
+int rtl8192U_enable_wake (struct pci_dev *dev, u32 state, int enable);
+
+#endif //R8192U_PM_H
+#endif // CONFIG_RTL8192_PM
diff --git a/drivers/staging/rtl8192su/r8192U_wx.c b/drivers/staging/rtl8192su/r8192U_wx.c
new file mode 100644
index 0000000..f9eafb1
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192U_wx.c
@@ -0,0 +1,1350 @@
+/*
+   This file contains wireless extension handlers.
+
+   This is part of rtl8180 OpenSource driver.
+   Copyright (C) Andrea Merello 2004-2005  <andreamrl@tiscali.it>
+   Released under the terms of GPL (General Public Licence)
+
+   Parts of this driver are based on the GPL part
+   of the official realtek driver.
+
+   Parts of this driver are based on the rtl8180 driver skeleton
+   from Patric Schenke & Andres Salomon.
+
+   Parts of this driver are based on the Intel Pro Wireless 2100 GPL driver.
+
+   We want to tanks the Authors of those projects and the Ndiswrapper
+   project Authors.
+*/
+
+#ifdef RTL8192SU
+#include <linux/string.h>
+#include "r8192U.h"
+#include "r8192S_hw.h"
+#else
+#include <linux/string.h>
+#include "r8192U.h"
+#include "r8192U_hw.h"
+#endif
+
+#ifdef ENABLE_DOT11D
+#include "dot11d.h"
+#endif
+
+#define RATE_COUNT 12
+u32 rtl8180_rates[] = {1000000,2000000,5500000,11000000,
+	6000000,9000000,12000000,18000000,24000000,36000000,48000000,54000000};
+
+
+#ifndef ENETDOWN
+#define ENETDOWN 1
+#endif
+
+static int r8192_wx_get_freq(struct net_device *dev,
+			     struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	return ieee80211_wx_get_freq(priv->ieee80211,a,wrqu,b);
+}
+
+
+#if 0
+
+static int r8192_wx_set_beaconinterval(struct net_device *dev, struct iw_request_info *aa,
+			  union iwreq_data *wrqu, char *b)
+{
+	int *parms = (int *)b;
+	int bi = parms[0];
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	down(&priv->wx_sem);
+	DMESG("setting beacon interval to %x",bi);
+
+	priv->ieee80211->beacon_interval=bi;
+	rtl8180_commit(dev);
+	up(&priv->wx_sem);
+
+	return 0;
+}
+
+
+static int r8192_wx_set_forceassociate(struct net_device *dev, struct iw_request_info *aa,
+			  union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv=ieee80211_priv(dev);
+	int *parms = (int *)extra;
+
+	priv->ieee80211->force_associate = (parms[0] > 0);
+
+
+	return 0;
+}
+
+#endif
+static int r8192_wx_get_mode(struct net_device *dev, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b)
+{
+	struct r8192_priv *priv=ieee80211_priv(dev);
+
+	return ieee80211_wx_get_mode(priv->ieee80211,a,wrqu,b);
+}
+
+
+
+static int r8192_wx_get_rate(struct net_device *dev,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	return ieee80211_wx_get_rate(priv->ieee80211,info,wrqu,extra);
+}
+
+
+
+static int r8192_wx_set_rate(struct net_device *dev,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	int ret;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	down(&priv->wx_sem);
+
+	ret = ieee80211_wx_set_rate(priv->ieee80211,info,wrqu,extra);
+
+	up(&priv->wx_sem);
+
+	return ret;
+}
+
+
+static int r8192_wx_set_rts(struct net_device *dev,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	int ret;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	down(&priv->wx_sem);
+
+	ret = ieee80211_wx_set_rts(priv->ieee80211,info,wrqu,extra);
+
+	up(&priv->wx_sem);
+
+	return ret;
+}
+
+static int r8192_wx_get_rts(struct net_device *dev,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	return ieee80211_wx_get_rts(priv->ieee80211,info,wrqu,extra);
+}
+
+static int r8192_wx_set_power(struct net_device *dev,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	int ret;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	down(&priv->wx_sem);
+
+	ret = ieee80211_wx_set_power(priv->ieee80211,info,wrqu,extra);
+
+	up(&priv->wx_sem);
+
+	return ret;
+}
+
+static int r8192_wx_get_power(struct net_device *dev,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	return ieee80211_wx_get_power(priv->ieee80211,info,wrqu,extra);
+}
+
+#ifdef JOHN_IOCTL
+u16 read_rtl8225(struct net_device *dev, u8 addr);
+void write_rtl8225(struct net_device *dev, u8 adr, u16 data);
+u32 john_read_rtl8225(struct net_device *dev, u8 adr);
+void _write_rtl8225(struct net_device *dev, u8 adr, u16 data);
+
+static int r8192_wx_read_regs(struct net_device *dev,
+			       struct iw_request_info *info,
+			       union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8 addr;
+	u16 data1;
+
+	down(&priv->wx_sem);
+
+
+	get_user(addr,(u8*)wrqu->data.pointer);
+	data1 = read_rtl8225(dev, addr);
+	wrqu->data.length = data1;
+
+	up(&priv->wx_sem);
+	return 0;
+
+}
+
+static int r8192_wx_write_regs(struct net_device *dev,
+			       struct iw_request_info *info,
+			       union iwreq_data *wrqu, char *extra)
+{
+        struct r8192_priv *priv = ieee80211_priv(dev);
+        u8 addr;
+
+        down(&priv->wx_sem);
+
+        get_user(addr, (u8*)wrqu->data.pointer);
+	write_rtl8225(dev, addr, wrqu->data.length);
+
+        up(&priv->wx_sem);
+	return 0;
+
+}
+
+void rtl8187_write_phy(struct net_device *dev, u8 adr, u32 data);
+u8 rtl8187_read_phy(struct net_device *dev,u8 adr, u32 data);
+
+static int r8192_wx_read_bb(struct net_device *dev,
+			       struct iw_request_info *info,
+			       union iwreq_data *wrqu, char *extra)
+{
+        struct r8192_priv *priv = ieee80211_priv(dev);
+	u8 databb;
+#if 0
+	int i;
+	for(i=0;i<12;i++) printk("%8x\n", read_cam(dev, i) );
+#endif
+
+        down(&priv->wx_sem);
+
+	databb = rtl8187_read_phy(dev, (u8)wrqu->data.length, 0x00000000);
+	wrqu->data.length = databb;
+
+	up(&priv->wx_sem);
+	return 0;
+}
+
+void rtl8187_write_phy(struct net_device *dev, u8 adr, u32 data);
+static int r8192_wx_write_bb(struct net_device *dev,
+                               struct iw_request_info *info,
+                               union iwreq_data *wrqu, char *extra)
+{
+        struct r8192_priv *priv = ieee80211_priv(dev);
+        u8 databb;
+
+        down(&priv->wx_sem);
+
+        get_user(databb, (u8*)wrqu->data.pointer);
+        rtl8187_write_phy(dev, wrqu->data.length, databb);
+
+        up(&priv->wx_sem);
+        return 0;
+
+}
+
+
+static int r8192_wx_write_nicb(struct net_device *dev,
+                               struct iw_request_info *info,
+                               union iwreq_data *wrqu, char *extra)
+{
+        struct r8192_priv *priv = ieee80211_priv(dev);
+        u32 addr;
+
+        down(&priv->wx_sem);
+
+        get_user(addr, (u32*)wrqu->data.pointer);
+        write_nic_byte(dev, addr, wrqu->data.length);
+
+        up(&priv->wx_sem);
+        return 0;
+
+}
+static int r8192_wx_read_nicb(struct net_device *dev,
+                               struct iw_request_info *info,
+                               union iwreq_data *wrqu, char *extra)
+{
+        struct r8192_priv *priv = ieee80211_priv(dev);
+        u32 addr;
+        u16 data1;
+
+        down(&priv->wx_sem);
+
+        get_user(addr,(u32*)wrqu->data.pointer);
+        data1 = read_nic_byte(dev, addr);
+        wrqu->data.length = data1;
+
+        up(&priv->wx_sem);
+        return 0;
+}
+
+static int r8192_wx_get_ap_status(struct net_device *dev,
+                               struct iw_request_info *info,
+                               union iwreq_data *wrqu, char *extra)
+{
+        struct r8192_priv *priv = ieee80211_priv(dev);
+        struct ieee80211_device *ieee = priv->ieee80211;
+        struct ieee80211_network *target;
+	int name_len;
+
+        down(&priv->wx_sem);
+
+	//count the length of input ssid
+	for(name_len=0 ; ((char*)wrqu->data.pointer)[name_len]!='\0' ; name_len++);
+
+	//search for the correspoding info which is received
+        list_for_each_entry(target, &ieee->network_list, list) {
+                if ( (target->ssid_len == name_len) &&
+		     (strncmp(target->ssid, (char*)wrqu->data.pointer, name_len)==0)){
+			if(target->wpa_ie_len>0 || target->rsn_ie_len>0 )
+				//set flags=1 to indicate this ap is WPA
+				wrqu->data.flags = 1;
+			else wrqu->data.flags = 0;
+
+
+		break;
+                }
+        }
+
+        up(&priv->wx_sem);
+        return 0;
+}
+
+
+
+#endif
+#if 0
+static int r8192_wx_null(struct net_device *dev,
+		struct iw_request_info *info,
+		union iwreq_data *wrqu, char *extra)
+{
+	return 0;
+}
+#endif
+static int r8192_wx_force_reset(struct net_device *dev,
+		struct iw_request_info *info,
+		union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	down(&priv->wx_sem);
+
+	printk("%s(): force reset ! extra is %d\n",__FUNCTION__, *extra);
+	priv->force_reset = *extra;
+	up(&priv->wx_sem);
+	return 0;
+
+}
+
+#ifdef RTL8192SU
+static int r8191su_wx_get_firm_version(struct net_device *dev,
+		struct iw_request_info *info,
+		struct iw_param *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u16 firmware_version;
+
+	down(&priv->wx_sem);
+	firmware_version = priv->pFirmware->FirmwareVersion;
+	wrqu->value = firmware_version;
+	wrqu->fixed = 1;
+
+	up(&priv->wx_sem);
+	return 0;
+}
+#endif
+
+
+
+static int r8192_wx_set_rawtx(struct net_device *dev,
+			       struct iw_request_info *info,
+			       union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int ret;
+
+	down(&priv->wx_sem);
+
+	ret = ieee80211_wx_set_rawtx(priv->ieee80211, info, wrqu, extra);
+
+	up(&priv->wx_sem);
+
+	return ret;
+
+}
+
+static int r8192_wx_set_crcmon(struct net_device *dev,
+			       struct iw_request_info *info,
+			       union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int *parms = (int *)extra;
+	int enable = (parms[0] > 0);
+	short prev = priv->crcmon;
+
+	down(&priv->wx_sem);
+
+	if(enable)
+		priv->crcmon=1;
+	else
+		priv->crcmon=0;
+
+	DMESG("bad CRC in monitor mode are %s",
+	      priv->crcmon ? "accepted" : "rejected");
+
+	if(prev != priv->crcmon && priv->up){
+		//rtl8180_down(dev);
+		//rtl8180_up(dev);
+	}
+
+	up(&priv->wx_sem);
+
+	return 0;
+}
+
+static int r8192_wx_set_mode(struct net_device *dev, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int ret;
+	down(&priv->wx_sem);
+
+	ret = ieee80211_wx_set_mode(priv->ieee80211,a,wrqu,b);
+
+	rtl8192_set_rxconf(dev);
+
+	up(&priv->wx_sem);
+	return ret;
+}
+
+struct  iw_range_with_scan_capa
+{
+        /* Informative stuff (to choose between different interface) */
+        __u32           throughput;     /* To give an idea... */
+        /* In theory this value should be the maximum benchmarked
+         * TCP/IP throughput, because with most of these devices the
+         * bit rate is meaningless (overhead an co) to estimate how
+         * fast the connection will go and pick the fastest one.
+         * I suggest people to play with Netperf or any benchmark...
+         */
+
+        /* NWID (or domain id) */
+        __u32           min_nwid;       /* Minimal NWID we are able to set */
+        __u32           max_nwid;       /* Maximal NWID we are able to set */
+
+        /* Old Frequency (backward compat - moved lower ) */
+        __u16           old_num_channels;
+        __u8            old_num_frequency;
+
+        /* Scan capabilities */
+        __u8            scan_capa;
+};
+static int rtl8180_wx_get_range(struct net_device *dev,
+				struct iw_request_info *info,
+				union iwreq_data *wrqu, char *extra)
+{
+	struct iw_range *range = (struct iw_range *)extra;
+	struct iw_range_with_scan_capa* tmp = (struct iw_range_with_scan_capa*)range;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u16 val;
+	int i;
+
+	wrqu->data.length = sizeof(*range);
+	memset(range, 0, sizeof(*range));
+
+	/* Let's try to keep this struct in the same order as in
+	 * linux/include/wireless.h
+	 */
+
+	/* TODO: See what values we can set, and remove the ones we can't
+	 * set, or fill them with some default data.
+	 */
+
+	/* ~5 Mb/s real (802.11b) */
+	range->throughput = 5 * 1000 * 1000;
+
+	// TODO: Not used in 802.11b?
+//	range->min_nwid;	/* Minimal NWID we are able to set */
+	// TODO: Not used in 802.11b?
+//	range->max_nwid;	/* Maximal NWID we are able to set */
+
+        /* Old Frequency (backward compat - moved lower ) */
+//	range->old_num_channels;
+//	range->old_num_frequency;
+//	range->old_freq[6]; /* Filler to keep "version" at the same offset */
+	if(priv->rf_set_sens != NULL)
+		range->sensitivity = priv->max_sens;	/* signal level threshold range */
+
+	range->max_qual.qual = 100;
+	/* TODO: Find real max RSSI and stick here */
+	range->max_qual.level = 0;
+	range->max_qual.noise = -98;
+	range->max_qual.updated = 7; /* Updated all three */
+
+	range->avg_qual.qual = 92; /* > 8% missed beacons is 'bad' */
+	/* TODO: Find real 'good' to 'bad' threshol value for RSSI */
+	range->avg_qual.level = 20 + -98;
+	range->avg_qual.noise = 0;
+	range->avg_qual.updated = 7; /* Updated all three */
+
+	range->num_bitrates = RATE_COUNT;
+
+	for (i = 0; i < RATE_COUNT && i < IW_MAX_BITRATES; i++) {
+		range->bitrate[i] = rtl8180_rates[i];
+	}
+
+	range->min_frag = MIN_FRAG_THRESHOLD;
+	range->max_frag = MAX_FRAG_THRESHOLD;
+
+	range->min_pmp=0;
+	range->max_pmp = 5000000;
+	range->min_pmt = 0;
+	range->max_pmt = 65535*1000;
+	range->pmp_flags = IW_POWER_PERIOD;
+	range->pmt_flags = IW_POWER_TIMEOUT;
+	range->pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT | IW_POWER_ALL_R;
+
+	range->we_version_compiled = WIRELESS_EXT;
+	range->we_version_source = 16;
+
+//	range->retry_capa;	/* What retry options are supported */
+//	range->retry_flags;	/* How to decode max/min retry limit */
+//	range->r_time_flags;	/* How to decode max/min retry life */
+//	range->min_retry;	/* Minimal number of retries */
+//	range->max_retry;	/* Maximal number of retries */
+//	range->min_r_time;	/* Minimal retry lifetime */
+//	range->max_r_time;	/* Maximal retry lifetime */
+
+
+	for (i = 0, val = 0; i < 14; i++) {
+
+		// Include only legal frequencies for some countries
+#ifdef ENABLE_DOT11D
+		if ((GET_DOT11D_INFO(priv->ieee80211)->channel_map)[i+1]) {
+#else
+		if ((priv->ieee80211->channel_map)[i+1]) {
+#endif
+		        range->freq[val].i = i + 1;
+			range->freq[val].m = ieee80211_wlan_frequencies[i] * 100000;
+			range->freq[val].e = 1;
+			val++;
+		} else {
+			// FIXME: do we need to set anything for channels
+			// we don't use ?
+		}
+
+		if (val == IW_MAX_FREQUENCIES)
+		break;
+	}
+	range->num_frequency = val;
+        range->num_channels = val;
+#if WIRELESS_EXT > 17
+	range->enc_capa = IW_ENC_CAPA_WPA|IW_ENC_CAPA_WPA2|
+			  IW_ENC_CAPA_CIPHER_TKIP|IW_ENC_CAPA_CIPHER_CCMP;
+#endif
+	tmp->scan_capa = 0x01;
+	return 0;
+}
+
+
+static int r8192_wx_set_scan(struct net_device *dev, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+	int ret = 0;
+
+	if(!priv->up) return -ENETDOWN;
+
+	if (priv->ieee80211->LinkDetectInfo.bBusyTraffic == true)
+		return -EAGAIN;
+#if WIRELESS_EXT > 17
+	if (wrqu->data.flags & IW_SCAN_THIS_ESSID)
+	{
+		struct iw_scan_req* req = (struct iw_scan_req*)b;
+		if (req->essid_len)
+		{
+			//printk("==**&*&*&**===>scan set ssid:%s\n", req->essid);
+			ieee->current_network.ssid_len = req->essid_len;
+			memcpy(ieee->current_network.ssid, req->essid, req->essid_len);
+			//printk("=====>network ssid:%s\n", ieee->current_network.ssid);
+		}
+	}
+#endif
+
+	down(&priv->wx_sem);
+	if(priv->ieee80211->state != IEEE80211_LINKED){
+                priv->ieee80211->scanning = 0;
+                ieee80211_softmac_scan_syncro(priv->ieee80211);
+                ret = 0;
+        }
+	else
+	ret = ieee80211_wx_set_scan(priv->ieee80211,a,wrqu,b);
+	up(&priv->wx_sem);
+	return ret;
+}
+
+
+static int r8192_wx_get_scan(struct net_device *dev, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b)
+{
+
+	int ret;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	if(!priv->up) return -ENETDOWN;
+
+	down(&priv->wx_sem);
+
+	ret = ieee80211_wx_get_scan(priv->ieee80211,a,wrqu,b);
+
+	up(&priv->wx_sem);
+
+	return ret;
+}
+
+static int r8192_wx_set_essid(struct net_device *dev,
+			      struct iw_request_info *a,
+			      union iwreq_data *wrqu, char *b)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int ret;
+	down(&priv->wx_sem);
+
+	ret = ieee80211_wx_set_essid(priv->ieee80211,a,wrqu,b);
+
+	up(&priv->wx_sem);
+
+	return ret;
+}
+
+
+
+
+static int r8192_wx_get_essid(struct net_device *dev,
+			      struct iw_request_info *a,
+			      union iwreq_data *wrqu, char *b)
+{
+	int ret;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	down(&priv->wx_sem);
+
+	ret = ieee80211_wx_get_essid(priv->ieee80211, a, wrqu, b);
+
+	up(&priv->wx_sem);
+
+	return ret;
+}
+
+
+static int r8192_wx_set_freq(struct net_device *dev, struct iw_request_info *a,
+			     union iwreq_data *wrqu, char *b)
+{
+	int ret;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	down(&priv->wx_sem);
+
+	ret = ieee80211_wx_set_freq(priv->ieee80211, a, wrqu, b);
+
+	up(&priv->wx_sem);
+	return ret;
+}
+
+static int r8192_wx_get_name(struct net_device *dev,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	return ieee80211_wx_get_name(priv->ieee80211, info, wrqu, extra);
+}
+
+
+static int r8192_wx_set_frag(struct net_device *dev,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	if (wrqu->frag.disabled)
+		priv->ieee80211->fts = DEFAULT_FRAG_THRESHOLD;
+	else {
+		if (wrqu->frag.value < MIN_FRAG_THRESHOLD ||
+		    wrqu->frag.value > MAX_FRAG_THRESHOLD)
+			return -EINVAL;
+
+		priv->ieee80211->fts = wrqu->frag.value & ~0x1;
+	}
+
+	return 0;
+}
+
+
+static int r8192_wx_get_frag(struct net_device *dev,
+			     struct iw_request_info *info,
+			     union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	wrqu->frag.value = priv->ieee80211->fts;
+	wrqu->frag.fixed = 0;	/* no auto select */
+	wrqu->frag.disabled = (wrqu->frag.value == DEFAULT_FRAG_THRESHOLD);
+
+	return 0;
+}
+
+
+static int r8192_wx_set_wap(struct net_device *dev,
+			 struct iw_request_info *info,
+			 union iwreq_data *awrq,
+			 char *extra)
+{
+
+	int ret;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+//        struct sockaddr *temp = (struct sockaddr *)awrq;
+	down(&priv->wx_sem);
+
+	ret = ieee80211_wx_set_wap(priv->ieee80211,info,awrq,extra);
+
+	up(&priv->wx_sem);
+
+	return ret;
+
+}
+
+
+static int r8192_wx_get_wap(struct net_device *dev,
+			    struct iw_request_info *info,
+			    union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	return ieee80211_wx_get_wap(priv->ieee80211,info,wrqu,extra);
+}
+
+
+static int r8192_wx_get_enc(struct net_device *dev,
+			    struct iw_request_info *info,
+			    union iwreq_data *wrqu, char *key)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	return ieee80211_wx_get_encode(priv->ieee80211, info, wrqu, key);
+}
+
+static int r8192_wx_set_enc(struct net_device *dev,
+			    struct iw_request_info *info,
+			    union iwreq_data *wrqu, char *key)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct ieee80211_device *ieee = priv->ieee80211;
+	int ret;
+
+	//u32 TargetContent;
+	u32 hwkey[4]={0,0,0,0};
+	u8 mask=0xff;
+	u32 key_idx=0;
+	//u8 broadcast_addr[6] ={	0xff,0xff,0xff,0xff,0xff,0xff};
+	u8 zero_addr[4][6] ={	{0x00,0x00,0x00,0x00,0x00,0x00},
+				{0x00,0x00,0x00,0x00,0x00,0x01},
+				{0x00,0x00,0x00,0x00,0x00,0x02},
+				{0x00,0x00,0x00,0x00,0x00,0x03} };
+	int i;
+
+       if(!priv->up) return -ENETDOWN;
+
+	down(&priv->wx_sem);
+
+	RT_TRACE(COMP_SEC, "Setting SW wep key");
+	ret = ieee80211_wx_set_encode(priv->ieee80211,info,wrqu,key);
+
+	up(&priv->wx_sem);
+
+
+
+	//sometimes, the length is zero while we do not type key value
+	if(wrqu->encoding.length!=0){
+
+		for(i=0 ; i<4 ; i++){
+			hwkey[i] |=  key[4*i+0]&mask;
+			if(i==1&&(4*i+1)==wrqu->encoding.length) mask=0x00;
+			if(i==3&&(4*i+1)==wrqu->encoding.length) mask=0x00;
+			hwkey[i] |= (key[4*i+1]&mask)<<8;
+			hwkey[i] |= (key[4*i+2]&mask)<<16;
+			hwkey[i] |= (key[4*i+3]&mask)<<24;
+		}
+
+		#define CONF_WEP40  0x4
+		#define CONF_WEP104 0x14
+
+		switch(wrqu->encoding.flags & IW_ENCODE_INDEX){
+			case 0: key_idx = ieee->tx_keyidx; break;
+			case 1:	key_idx = 0; break;
+			case 2:	key_idx = 1; break;
+			case 3:	key_idx = 2; break;
+			case 4:	key_idx	= 3; break;
+			default: break;
+		}
+
+		if(wrqu->encoding.length==0x5){
+				ieee->pairwise_key_type = KEY_TYPE_WEP40;
+			EnableHWSecurityConfig8192(dev);
+
+			setKey( dev,
+				key_idx,                //EntryNo
+				key_idx,                //KeyIndex
+				KEY_TYPE_WEP40,         //KeyType
+				zero_addr[key_idx],
+				0,                      //DefaultKey
+				hwkey);                 //KeyContent
+
+		}
+
+		else if(wrqu->encoding.length==0xd){
+				ieee->pairwise_key_type = KEY_TYPE_WEP104;
+				EnableHWSecurityConfig8192(dev);
+
+			setKey( dev,
+				key_idx,                //EntryNo
+				key_idx,                //KeyIndex
+				KEY_TYPE_WEP104,        //KeyType
+				zero_addr[key_idx],
+				0,                      //DefaultKey
+				hwkey);                 //KeyContent
+
+		}
+		else printk("wrong type in WEP, not WEP40 and WEP104\n");
+
+	}
+
+	return ret;
+}
+
+
+static int r8192_wx_set_scan_type(struct net_device *dev, struct iw_request_info *aa, union
+ iwreq_data *wrqu, char *p){
+
+ 	struct r8192_priv *priv = ieee80211_priv(dev);
+	int *parms=(int*)p;
+	int mode=parms[0];
+
+	priv->ieee80211->active_scan = mode;
+
+	return 1;
+}
+
+
+
+static int r8192_wx_set_retry(struct net_device *dev,
+				struct iw_request_info *info,
+				union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int err = 0;
+
+	down(&priv->wx_sem);
+
+	if (wrqu->retry.flags & IW_RETRY_LIFETIME ||
+	    wrqu->retry.disabled){
+		err = -EINVAL;
+		goto exit;
+	}
+	if (!(wrqu->retry.flags & IW_RETRY_LIMIT)){
+		err = -EINVAL;
+		goto exit;
+	}
+
+	if(wrqu->retry.value > R8180_MAX_RETRY){
+		err= -EINVAL;
+		goto exit;
+	}
+	if (wrqu->retry.flags & IW_RETRY_MAX) {
+		priv->retry_rts = wrqu->retry.value;
+		DMESG("Setting retry for RTS/CTS data to %d", wrqu->retry.value);
+
+	}else {
+		priv->retry_data = wrqu->retry.value;
+		DMESG("Setting retry for non RTS/CTS data to %d", wrqu->retry.value);
+	}
+
+	/* FIXME !
+	 * We might try to write directly the TX config register
+	 * or to restart just the (R)TX process.
+	 * I'm unsure if whole reset is really needed
+	 */
+
+ 	rtl8192_commit(dev);
+	/*
+	if(priv->up){
+		rtl8180_rtx_disable(dev);
+		rtl8180_rx_enable(dev);
+		rtl8180_tx_enable(dev);
+
+	}
+	*/
+exit:
+	up(&priv->wx_sem);
+
+	return err;
+}
+
+static int r8192_wx_get_retry(struct net_device *dev,
+				struct iw_request_info *info,
+				union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+
+	wrqu->retry.disabled = 0; /* can't be disabled */
+
+	if ((wrqu->retry.flags & IW_RETRY_TYPE) ==
+	    IW_RETRY_LIFETIME)
+		return -EINVAL;
+
+	if (wrqu->retry.flags & IW_RETRY_MAX) {
+		wrqu->retry.flags = IW_RETRY_LIMIT | IW_RETRY_MAX;
+		wrqu->retry.value = priv->retry_rts;
+	} else {
+		wrqu->retry.flags = IW_RETRY_LIMIT | IW_RETRY_MIN;
+		wrqu->retry.value = priv->retry_data;
+	}
+	//printk("returning %d",wrqu->retry.value);
+
+
+	return 0;
+}
+
+static int r8192_wx_get_sens(struct net_device *dev,
+				struct iw_request_info *info,
+				union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	if(priv->rf_set_sens == NULL)
+		return -1; /* we have not this support for this radio */
+	wrqu->sens.value = priv->sens;
+	return 0;
+}
+
+
+static int r8192_wx_set_sens(struct net_device *dev,
+				struct iw_request_info *info,
+				union iwreq_data *wrqu, char *extra)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	short err = 0;
+	down(&priv->wx_sem);
+	//DMESG("attempt to set sensivity to %ddb",wrqu->sens.value);
+	if(priv->rf_set_sens == NULL) {
+		err= -1; /* we have not this support for this radio */
+		goto exit;
+	}
+	if(priv->rf_set_sens(dev, wrqu->sens.value) == 0)
+		priv->sens = wrqu->sens.value;
+	else
+		err= -EINVAL;
+
+exit:
+	up(&priv->wx_sem);
+
+	return err;
+}
+
+#if (WIRELESS_EXT >= 18)
+#if 0
+static int r8192_wx_get_enc_ext(struct net_device *dev,
+                                        struct iw_request_info *info,
+                                        union iwreq_data *wrqu, char *extra)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int ret = 0;
+	ret = ieee80211_wx_get_encode_ext(priv->ieee80211, info, wrqu, extra);
+	return ret;
+}
+#endif
+//hw security need to reorganized.
+static int r8192_wx_set_enc_ext(struct net_device *dev,
+                                        struct iw_request_info *info,
+                                        union iwreq_data *wrqu, char *extra)
+{
+	int ret=0;
+	#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+	//printk("===>%s()\n", __FUNCTION__);
+
+
+	down(&priv->wx_sem);
+	ret = ieee80211_wx_set_encode_ext(priv->ieee80211, info, wrqu, extra);
+
+	{
+		u8 broadcast_addr[6] = {0xff,0xff,0xff,0xff,0xff,0xff};
+		u8 zero[6] = {0};
+		u32 key[4] = {0};
+		struct iw_encode_ext *ext = (struct iw_encode_ext *)extra;
+		struct iw_point *encoding = &wrqu->encoding;
+#if 0
+		static u8 CAM_CONST_ADDR[4][6] = {
+			{0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+			{0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
+			{0x00, 0x00, 0x00, 0x00, 0x00, 0x02},
+			{0x00, 0x00, 0x00, 0x00, 0x00, 0x03}};
+#endif
+		u8 idx = 0, alg = 0, group = 0;
+		if ((encoding->flags & IW_ENCODE_DISABLED) ||
+		ext->alg == IW_ENCODE_ALG_NONE) //none is not allowed to use hwsec WB 2008.07.01
+		{
+			ieee->pairwise_key_type = ieee->group_key_type = KEY_TYPE_NA;
+			CamResetAllEntry(dev);
+			goto end_hw_sec;
+		}
+		alg =  (ext->alg == IW_ENCODE_ALG_CCMP)?KEY_TYPE_CCMP:ext->alg; // as IW_ENCODE_ALG_CCMP is defined to be 3 and KEY_TYPE_CCMP is defined to 4;
+		idx = encoding->flags & IW_ENCODE_INDEX;
+		if (idx)
+			idx --;
+		group = ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY;
+
+		if ((!group) || (IW_MODE_ADHOC == ieee->iw_mode) || (alg ==  KEY_TYPE_WEP40))
+		{
+			if ((ext->key_len == 13) && (alg == KEY_TYPE_WEP40) )
+				alg = KEY_TYPE_WEP104;
+			ieee->pairwise_key_type = alg;
+			EnableHWSecurityConfig8192(dev);
+		}
+		memcpy((u8*)key, ext->key, 16); //we only get 16 bytes key.why? WB 2008.7.1
+
+		if ((alg & KEY_TYPE_WEP40) && (ieee->auth_mode !=2) )
+		{
+
+			setKey( dev,
+					idx,//EntryNo
+					idx, //KeyIndex
+					alg,  //KeyType
+					zero, //MacAddr
+					0,              //DefaultKey
+					key);           //KeyContent
+		}
+		else if (group)
+		{
+			ieee->group_key_type = alg;
+			setKey( dev,
+					idx,//EntryNo
+					idx, //KeyIndex
+					alg,  //KeyType
+					broadcast_addr, //MacAddr
+					0,              //DefaultKey
+					key);           //KeyContent
+		}
+		else //pairwise key
+		{
+			setKey( dev,
+					4,//EntryNo
+					idx, //KeyIndex
+					alg,  //KeyType
+					(u8*)ieee->ap_mac_addr, //MacAddr
+					0,              //DefaultKey
+					key);           //KeyContent
+		}
+
+
+	}
+
+end_hw_sec:
+
+	up(&priv->wx_sem);
+#endif
+	return ret;
+
+}
+static int r8192_wx_set_auth(struct net_device *dev,
+                                        struct iw_request_info *info,
+                                        union iwreq_data *data, char *extra)
+{
+	int ret=0;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	//printk("====>%s()\n", __FUNCTION__);
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	down(&priv->wx_sem);
+	ret = ieee80211_wx_set_auth(priv->ieee80211, info, &(data->param), extra);
+	up(&priv->wx_sem);
+#endif
+	return ret;
+}
+
+static int r8192_wx_set_mlme(struct net_device *dev,
+                                        struct iw_request_info *info,
+                                        union iwreq_data *wrqu, char *extra)
+{
+	//printk("====>%s()\n", __FUNCTION__);
+
+	int ret=0;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	down(&priv->wx_sem);
+	ret = ieee80211_wx_set_mlme(priv->ieee80211, info, wrqu, extra);
+
+	up(&priv->wx_sem);
+#endif
+	return ret;
+}
+#endif
+static int r8192_wx_set_gen_ie(struct net_device *dev,
+                                        struct iw_request_info *info,
+                                        union iwreq_data *data, char *extra)
+{
+	   //printk("====>%s(), len:%d\n", __FUNCTION__, data->length);
+	int ret=0;
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+        struct r8192_priv *priv = ieee80211_priv(dev);
+        down(&priv->wx_sem);
+#if 1
+        ret = ieee80211_wx_set_gen_ie(priv->ieee80211, extra, data->data.length);
+#endif
+        up(&priv->wx_sem);
+	//printk("<======%s(), ret:%d\n", __FUNCTION__, ret);
+#endif
+        return ret;
+
+
+}
+
+static int dummy(struct net_device *dev, struct iw_request_info *a,
+		 union iwreq_data *wrqu,char *b)
+{
+	return -1;
+}
+
+
+static iw_handler r8192_wx_handlers[] =
+{
+        NULL,                     /* SIOCSIWCOMMIT */
+        r8192_wx_get_name,   	  /* SIOCGIWNAME */
+        dummy,                    /* SIOCSIWNWID */
+        dummy,                    /* SIOCGIWNWID */
+        r8192_wx_set_freq,        /* SIOCSIWFREQ */
+        r8192_wx_get_freq,        /* SIOCGIWFREQ */
+        r8192_wx_set_mode,        /* SIOCSIWMODE */
+        r8192_wx_get_mode,        /* SIOCGIWMODE */
+        r8192_wx_set_sens,        /* SIOCSIWSENS */
+        r8192_wx_get_sens,        /* SIOCGIWSENS */
+        NULL,                     /* SIOCSIWRANGE */
+        rtl8180_wx_get_range,	  /* SIOCGIWRANGE */
+        NULL,                     /* SIOCSIWPRIV */
+        NULL,                     /* SIOCGIWPRIV */
+        NULL,                     /* SIOCSIWSTATS */
+        NULL,                     /* SIOCGIWSTATS */
+        dummy,                    /* SIOCSIWSPY */
+        dummy,                    /* SIOCGIWSPY */
+        NULL,                     /* SIOCGIWTHRSPY */
+        NULL,                     /* SIOCWIWTHRSPY */
+        r8192_wx_set_wap,      	  /* SIOCSIWAP */
+        r8192_wx_get_wap,         /* SIOCGIWAP */
+#if (WIRELESS_EXT >= 18)
+        r8192_wx_set_mlme,                     /* MLME-- */
+#else
+	 NULL,
+#endif
+        dummy,                     /* SIOCGIWAPLIST -- depricated */
+        r8192_wx_set_scan,        /* SIOCSIWSCAN */
+        r8192_wx_get_scan,        /* SIOCGIWSCAN */
+        r8192_wx_set_essid,       /* SIOCSIWESSID */
+        r8192_wx_get_essid,       /* SIOCGIWESSID */
+        dummy,                    /* SIOCSIWNICKN */
+        dummy,                    /* SIOCGIWNICKN */
+        NULL,                     /* -- hole -- */
+        NULL,                     /* -- hole -- */
+        r8192_wx_set_rate,        /* SIOCSIWRATE */
+        r8192_wx_get_rate,        /* SIOCGIWRATE */
+        r8192_wx_set_rts,                    /* SIOCSIWRTS */
+        r8192_wx_get_rts,                    /* SIOCGIWRTS */
+        r8192_wx_set_frag,        /* SIOCSIWFRAG */
+        r8192_wx_get_frag,        /* SIOCGIWFRAG */
+        dummy,                    /* SIOCSIWTXPOW */
+        dummy,                    /* SIOCGIWTXPOW */
+        r8192_wx_set_retry,       /* SIOCSIWRETRY */
+        r8192_wx_get_retry,       /* SIOCGIWRETRY */
+        r8192_wx_set_enc,         /* SIOCSIWENCODE */
+        r8192_wx_get_enc,         /* SIOCGIWENCODE */
+        r8192_wx_set_power,                    /* SIOCSIWPOWER */
+        r8192_wx_get_power,                    /* SIOCGIWPOWER */
+	NULL,			/*---hole---*/
+	NULL, 			/*---hole---*/
+	r8192_wx_set_gen_ie,//NULL, 			/* SIOCSIWGENIE */
+	NULL, 			/* SIOCSIWGENIE */
+
+#if (WIRELESS_EXT >= 18)
+	r8192_wx_set_auth,//NULL, 			/* SIOCSIWAUTH */
+	NULL,//r8192_wx_get_auth,//NULL, 			/* SIOCSIWAUTH */
+	r8192_wx_set_enc_ext, 			/* SIOCSIWENCODEEXT */
+	NULL,//r8192_wx_get_enc_ext,//NULL, 			/* SIOCSIWENCODEEXT */
+#else
+	NULL,
+	NULL,
+	NULL,
+	NULL,
+#endif
+	NULL, 			/* SIOCSIWPMKSA */
+	NULL, 			 /*---hole---*/
+
+};
+
+
+static const struct iw_priv_args r8192_private_args[] = {
+
+	{
+		SIOCIWFIRSTPRIV + 0x0,
+		IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "badcrc"
+	},
+
+	{
+		SIOCIWFIRSTPRIV + 0x1,
+		IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "activescan"
+
+	},
+	{
+		SIOCIWFIRSTPRIV + 0x2,
+		IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "rawtx"
+	}
+#ifdef JOHN_IOCTL
+	,
+	{
+		SIOCIWFIRSTPRIV + 0x3,
+                IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "readRF"
+	}
+	,
+	{
+		SIOCIWFIRSTPRIV + 0x4,
+                IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "writeRF"
+	}
+	,
+	{
+		SIOCIWFIRSTPRIV + 0x5,
+                IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "readBB"
+	}
+	,
+	{
+		SIOCIWFIRSTPRIV + 0x6,
+                IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "writeBB"
+	}
+        ,
+        {
+                SIOCIWFIRSTPRIV + 0x7,
+                IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "readnicb"
+        }
+        ,
+        {
+                SIOCIWFIRSTPRIV + 0x8,
+                IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "writenicb"
+        }
+        ,
+        {
+                SIOCIWFIRSTPRIV + 0x9,
+                IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "apinfo"
+        }
+
+#endif
+	,
+	{
+		SIOCIWFIRSTPRIV + 0x3,
+		IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "forcereset"
+	}
+
+#ifdef RTL8192SU
+	,
+	{
+		SIOCIWFIRSTPRIV + 0x5,
+		IW_PRIV_TYPE_NONE, IW_PRIV_TYPE_INT|IW_PRIV_SIZE_FIXED|1,
+		"firm_ver"
+	}
+#endif
+};
+
+
+static iw_handler r8192_private_handler[] = {
+//	r8192_wx_set_monitor,  /* SIOCIWFIRSTPRIV */
+	r8192_wx_set_crcmon,   /*SIOCIWSECONDPRIV*/
+//	r8192_wx_set_forceassociate,
+//	r8192_wx_set_beaconinterval,
+//	r8192_wx_set_monitor_type,
+	r8192_wx_set_scan_type,
+	r8192_wx_set_rawtx,
+#ifdef JOHN_IOCTL
+	r8192_wx_read_regs,
+	r8192_wx_write_regs,
+	r8192_wx_read_bb,
+	r8192_wx_write_bb,
+        r8192_wx_read_nicb,
+        r8192_wx_write_nicb,
+	r8192_wx_get_ap_status,
+#endif
+	r8192_wx_force_reset,
+        (iw_handler)NULL,
+#ifdef RTL8192SU
+        (iw_handler)r8191su_wx_get_firm_version,
+#endif
+};
+
+//#if WIRELESS_EXT >= 17
+struct iw_statistics *r8192_get_wireless_stats(struct net_device *dev)
+{
+       struct r8192_priv *priv = ieee80211_priv(dev);
+	struct ieee80211_device* ieee = priv->ieee80211;
+	struct iw_statistics* wstats = &priv->wstats;
+	int tmp_level = 0;
+	int tmp_qual = 0;
+	int tmp_noise = 0;
+	if(ieee->state < IEEE80211_LINKED)
+	{
+		wstats->qual.qual = 0;
+		wstats->qual.level = 0;
+		wstats->qual.noise = 0;
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,14))
+		wstats->qual.updated = IW_QUAL_ALL_UPDATED | IW_QUAL_DBM;
+#else
+		wstats->qual.updated = 0x0f;
+#endif
+		return wstats;
+	}
+
+       tmp_level = (&ieee->current_network)->stats.rssi;
+	tmp_qual = (&ieee->current_network)->stats.signal;
+	tmp_noise = (&ieee->current_network)->stats.noise;
+	//printk("level:%d, qual:%d, noise:%d\n", tmp_level, tmp_qual, tmp_noise);
+
+	wstats->qual.level = tmp_level;
+	wstats->qual.qual = tmp_qual;
+	wstats->qual.noise = tmp_noise;
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,14))
+	wstats->qual.updated = IW_QUAL_ALL_UPDATED| IW_QUAL_DBM;
+#else
+        wstats->qual.updated = 0x0f;
+#endif
+	return wstats;
+}
+//#endif
+
+
+struct iw_handler_def  r8192_wx_handlers_def={
+	.standard = r8192_wx_handlers,
+	.num_standard = sizeof(r8192_wx_handlers) / sizeof(iw_handler),
+	.private = r8192_private_handler,
+	.num_private = sizeof(r8192_private_handler) / sizeof(iw_handler),
+ 	.num_private_args = sizeof(r8192_private_args) / sizeof(struct iw_priv_args),
+#if WIRELESS_EXT >= 17
+	.get_wireless_stats = r8192_get_wireless_stats,
+#endif
+	.private_args = (struct iw_priv_args *)r8192_private_args,
+};
diff --git a/drivers/staging/rtl8192su/r8192U_wx.h b/drivers/staging/rtl8192su/r8192U_wx.h
new file mode 100644
index 0000000..b2f7a57
--- /dev/null
+++ b/drivers/staging/rtl8192su/r8192U_wx.h
@@ -0,0 +1,23 @@
+/*
+	This is part of rtl8180 OpenSource driver - v 0.3
+	Copyright (C) Andrea Merello 2004  <andreamrl@tiscali.it>
+	Released under the terms of GPL (General Public Licence)
+
+	Parts of this driver are based on the GPL part of the official realtek driver
+	Parts of this driver are based on the rtl8180 driver skeleton from Patric Schenke & Andres Salomon
+	Parts of this driver are based on the Intel Pro Wireless 2100 GPL driver
+
+	We want to tanks the Authors of such projects and the Ndiswrapper project Authors.
+*/
+
+/* this file (will) contains wireless extension handlers*/
+
+#ifndef R8180_WX_H
+#define R8180_WX_H
+//#include <linux/wireless.h>
+//#include "ieee80211.h"
+extern struct iw_handler_def r8192_wx_handlers_def;
+/* Enable  the rtl819x_core.c to share this function, david 2008.9.22 */
+extern struct iw_statistics *r8192_get_wireless_stats(struct net_device *dev);
+
+#endif
diff --git a/drivers/staging/rtl8192su/r819xU_HTGen.h b/drivers/staging/rtl8192su/r819xU_HTGen.h
new file mode 100644
index 0000000..7a60480
--- /dev/null
+++ b/drivers/staging/rtl8192su/r819xU_HTGen.h
@@ -0,0 +1,22 @@
+//
+// IOT Action for different AP
+//
+typedef enum _HT_IOT_ACTION{
+	HT_IOT_ACT_TX_USE_AMSDU_4K = 0x00000001,
+	HT_IOT_ACT_TX_USE_AMSDU_8K = 0x00000002,
+	HT_IOT_ACT_DECLARE_MCS13 = 0x00000004,
+	HT_IOT_ACT_DISABLE_EDCA_TURBO = 0x00000008,
+	HT_IOT_ACT_MGNT_USE_CCK_6M = 0x00000010,
+	HT_IOT_ACT_CDD_FSYNC = 0x00000020,
+	HT_IOT_ACT_PURE_N_MODE = 0x00000040,
+
+	//LZM ADD 090224
+	HT_IOT_ACT_EDCA_BIAS_ON_RX = 0x00004000,
+	HT_IOT_ACT_HYBRID_AGGREGATION = 0x00010000,
+	HT_IOT_ACT_AMSDU_ENABLE = 0x00000800,
+	HT_IOT_ACT_DISABLE_SHORT_GI = 0x00020000,
+	HT_IOT_ACT_DISABLE_HIGH_POWER = 0x00040000,
+	HT_IOT_ACT_DISABLE_TX_2SS = 0x00200000,
+	HT_IOT_ACT_DISABLE_TX_40_MHZ = 0x00080000,
+}HT_IOT_ACTION_E, *PHT_IOT_ACTION_E;
+
diff --git a/drivers/staging/rtl8192su/r819xU_HTType.h b/drivers/staging/rtl8192su/r819xU_HTType.h
new file mode 100644
index 0000000..2994aa0
--- /dev/null
+++ b/drivers/staging/rtl8192su/r819xU_HTType.h
@@ -0,0 +1,392 @@
+#ifndef _R819XU_HTTYPE_H_
+#define _R819XU_HTTYPE_H_
+
+
+//------------------------------------------------------------
+// The HT Capability element is present in beacons, association request,
+//	reassociation request and probe response frames
+//------------------------------------------------------------
+
+//
+// Operation mode value
+//
+#define HT_OPMODE_NO_PROTECT		0
+#define HT_OPMODE_OPTIONAL		1
+#define HT_OPMODE_40MHZ_PROTECT	2
+#define HT_OPMODE_MIXED			3
+
+//
+// MIMO Power Save Setings
+//
+#define MIMO_PS_STATIC				0
+#define MIMO_PS_DYNAMIC			1
+#define MIMO_PS_NOLIMIT			3
+
+
+//
+//	There should be 128 bits to cover all of the MCS rates. However, since
+//	8190 does not support too much rates, one integer is quite enough.
+//
+
+#define sHTCLng	4
+
+
+#define HT_SUPPORTED_MCS_1SS_BITMAP					0x000000ff
+#define HT_SUPPORTED_MCS_2SS_BITMAP					0x0000ff00
+#define HT_SUPPORTED_MCS_1SS_2SS_BITMAP			HT_MCS_1SS_BITMAP|HT_MCS_1SS_2SS_BITMAP
+
+
+typedef enum _HT_MCS_RATE{
+	HT_MCS0   = 0x00000001,
+	HT_MCS1   = 0x00000002,
+	HT_MCS2   = 0x00000004,
+	HT_MCS3   = 0x00000008,
+	HT_MCS4   = 0x00000010,
+	HT_MCS5   = 0x00000020,
+	HT_MCS6   = 0x00000040,
+	HT_MCS7   = 0x00000080,
+	HT_MCS8   = 0x00000100,
+	HT_MCS9   = 0x00000200,
+	HT_MCS10 = 0x00000400,
+	HT_MCS11 = 0x00000800,
+	HT_MCS12 = 0x00001000,
+	HT_MCS13 = 0x00002000,
+	HT_MCS14 = 0x00004000,
+	HT_MCS15 = 0x00008000,
+	// Do not define MCS32 here although 8190 support MCS32
+}HT_MCS_RATE,*PHT_MCS_RATE;
+
+//
+// Represent Channel Width in HT Capabilities
+//
+typedef enum _HT_CHANNEL_WIDTH{
+	HT_CHANNEL_WIDTH_20 = 0,
+	HT_CHANNEL_WIDTH_20_40 = 1,
+}HT_CHANNEL_WIDTH, *PHT_CHANNEL_WIDTH;
+
+//
+// Represent Extention Channel Offset in HT Capabilities
+// This is available only in 40Mhz mode.
+//
+typedef enum _HT_EXTCHNL_OFFSET{
+	HT_EXTCHNL_OFFSET_NO_EXT = 0,
+	HT_EXTCHNL_OFFSET_UPPER = 1,
+	HT_EXTCHNL_OFFSET_NO_DEF = 2,
+	HT_EXTCHNL_OFFSET_LOWER = 3,
+}HT_EXTCHNL_OFFSET, *PHT_EXTCHNL_OFFSET;
+
+typedef enum _CHNLOP{
+	CHNLOP_NONE = 0, // No Action now
+	CHNLOP_SCAN = 1, // Scan in progress
+	CHNLOP_SWBW = 2, // Bandwidth switching in progress
+	CHNLOP_SWCHNL = 3, // Software Channel switching in progress
+} CHNLOP, *PCHNLOP;
+
+// Determine if the Channel Operation is in progress
+#define CHHLOP_IN_PROGRESS(_pHTInfo)	\
+		((_pHTInfo)->ChnlOp > CHNLOP_NONE) ? TRUE : FALSE
+
+
+typedef enum _HT_ACTION{
+	ACT_RECOMMAND_WIDTH		= 0,
+	ACT_MIMO_PWR_SAVE 		= 1,
+	ACT_PSMP					= 2,
+	ACT_SET_PCO_PHASE		= 3,
+	ACT_MIMO_CHL_MEASURE	= 4,
+	ACT_RECIPROCITY_CORRECT	= 5,
+	ACT_MIMO_CSI_MATRICS		= 6,
+	ACT_MIMO_NOCOMPR_STEER	= 7,
+	ACT_MIMO_COMPR_STEER		= 8,
+	ACT_ANTENNA_SELECT		= 9,
+} HT_ACTION, *PHT_ACTION;
+
+
+/* 2007/06/07 MH Define sub-carrier mode for 40MHZ. */
+typedef enum _HT_Bandwidth_40MHZ_Sub_Carrier{
+	SC_MODE_DUPLICATE = 0,
+	SC_MODE_LOWER = 1,
+	SC_MODE_UPPER = 2,
+	SC_MODE_FULL40MHZ = 3,
+}HT_BW40_SC_E;
+
+typedef	struct _HT_CAPABILITY_ELE{
+
+	//HT capability info
+	u8	AdvCoding:1;
+	u8	ChlWidth:1;
+	u8	MimoPwrSave:2;
+	u8	GreenField:1;
+	u8	ShortGI20Mhz:1;
+	u8	ShortGI40Mhz:1;
+	u8	TxSTBC:1;
+	u8	RxSTBC:2;
+	u8	DelayBA:1;
+	u8	MaxAMSDUSize:1;
+	u8	DssCCk:1;
+	u8	PSMP:1;
+	u8	Rsvd1:1;
+	u8	LSigTxopProtect:1;
+
+	//MAC HT parameters info
+	u8	MaxRxAMPDUFactor:2;
+	u8	MPDUDensity:3;
+	u8	Rsvd2:3;
+
+	//Supported MCS set
+	u8	MCS[16];
+
+
+	//Extended HT Capability Info
+	u16	ExtHTCapInfo;
+
+	//TXBF Capabilities
+	u8	TxBFCap[4];
+
+	//Antenna Selection Capabilities
+	u8	ASCap;
+
+}__attribute__((packed)) HT_CAPABILITY_ELE, *PHT_CAPABILITY_ELE;
+
+//------------------------------------------------------------
+// The HT Information element is present in beacons
+// Only AP is required to include this element
+//------------------------------------------------------------
+
+typedef struct _HT_INFORMATION_ELE{
+	u8	ControlChl;
+
+	u8	ExtChlOffset:2;
+	u8	RecommemdedTxWidth:1;
+	u8	RIFS:1;
+	u8	PSMPAccessOnly:1;
+	u8	SrvIntGranularity:3;
+
+	u8	OptMode:2;
+	u8	NonGFDevPresent:1;
+	u8	Revd1:5;
+	u8	Revd2:8;
+
+	u8	Rsvd3:6;
+	u8	DualBeacon:1;
+	u8	DualCTSProtect:1;
+
+	u8	SecondaryBeacon:1;
+	u8	LSigTxopProtectFull:1;
+	u8	PcoActive:1;
+	u8	PcoPhase:1;
+	u8	Rsvd4:4;
+
+	u8	BasicMSC[16];
+}__attribute__((packed)) HT_INFORMATION_ELE, *PHT_INFORMATION_ELE;
+
+//
+// MIMO Power Save control field.
+// This is appear in MIMO Power Save Action Frame
+//
+typedef struct _MIMOPS_CTRL{
+	u8	MimoPsEnable:1;
+	u8	MimoPsMode:1;
+	u8	Reserved:6;
+} MIMOPS_CTRL, *PMIMOPS_CTRL;
+
+typedef enum _HT_SPEC_VER{
+	HT_SPEC_VER_IEEE = 0,
+	HT_SPEC_VER_EWC = 1,
+}HT_SPEC_VER, *PHT_SPEC_VER;
+
+typedef enum _HT_AGGRE_MODE_E{
+	HT_AGG_AUTO = 0,
+	HT_AGG_FORCE_ENABLE = 1,
+	HT_AGG_FORCE_DISABLE = 2,
+}HT_AGGRE_MODE_E, *PHT_AGGRE_MODE_E;
+
+//------------------------------------------------------------
+//  The Data structure is used to keep HT related variables when card is
+//  configured as non-AP STA mode.  **Note**  Current_xxx should be set
+//	to default value in HTInitializeHTInfo()
+//------------------------------------------------------------
+
+typedef struct _RT_HIGH_THROUGHPUT{
+//	DECLARE_RT_OBJECT(_RT_HIGH_THROUGHPUT);
+	u8				bEnableHT;
+	u8				bCurrentHTSupport;
+
+	u8				bRegBW40MHz;				// Tx 40MHz channel capablity
+	u8				bCurBW40MHz;				// Tx 40MHz channel capability
+
+	u8				bRegShortGI40MHz;			// Tx Short GI for 40Mhz
+	u8				bCurShortGI40MHz;			// Tx Short GI for 40MHz
+
+	u8				bRegShortGI20MHz;			// Tx Short GI for 20MHz
+	u8				bCurShortGI20MHz;			// Tx Short GI for 20MHz
+
+	u8				bRegSuppCCK;				// Tx CCK rate capability
+	u8				bCurSuppCCK;				// Tx CCK rate capability
+
+	// 802.11n spec version for "peer"
+	HT_SPEC_VER			ePeerHTSpecVer;
+
+
+	// HT related information for "Self"
+	HT_CAPABILITY_ELE	SelfHTCap;					// This is HT cap element sent to peer STA, which also indicate HT Rx capabilities.
+	HT_INFORMATION_ELE	SelfHTInfo;					// This is HT info element sent to peer STA, which also indicate HT Rx capabilities.
+
+	// HT related information for "Peer"
+	u8				PeerHTCapBuf[32];
+	u8				PeerHTInfoBuf[32];
+
+
+	// A-MSDU related
+	u8				bAMSDU_Support;			// This indicates Tx A-MSDU capability
+	u16				nAMSDU_MaxSize;			// This indicates Tx A-MSDU capability
+	u8				bCurrent_AMSDU_Support;	// This indicates Tx A-MSDU capability
+	u16				nCurrent_AMSDU_MaxSize;	// This indicates Tx A-MSDU capability
+
+
+	// AMPDU  related <2006.08.10 Emily>
+	u8				bAMPDUEnable;				// This indicate Tx A-MPDU capability
+	u8				bCurrentAMPDUEnable;		// This indicate Tx A-MPDU capability
+	u8				AMPDU_Factor;				// This indicate Tx A-MPDU capability
+	u8				CurrentAMPDUFactor;		// This indicate Tx A-MPDU capability
+	u8				MPDU_Density;				// This indicate Tx A-MPDU capability
+	u8				CurrentMPDUDensity;			// This indicate Tx A-MPDU capability
+
+	// Forced A-MPDU enable
+	HT_AGGRE_MODE_E	ForcedAMPDUMode;
+	u8				ForcedAMPDUFactor;
+	u8				ForcedMPDUDensity;
+
+	// Forced A-MSDU enable
+	HT_AGGRE_MODE_E	ForcedAMSDUMode;
+	u16				ForcedAMSDUMaxSize;
+
+	u8				bForcedShortGI;
+
+	u8				CurrentOpMode;
+
+	// MIMO PS related
+	u8				SelfMimoPs;
+	u8				PeerMimoPs;
+
+	// 40MHz Channel Offset settings.
+	HT_EXTCHNL_OFFSET	CurSTAExtChnlOffset;
+	u8				bCurTxBW40MHz;	// If we use 40 MHz to Tx
+	u8				PeerBandwidth;
+
+	// For Bandwidth Switching
+	u8				bSwBwInProgress;
+	CHNLOP				ChnlOp; // software switching channel in progress. By Bruce, 2008-02-15.
+	u8				SwBwStep;
+	//RT_TIMER			SwBwTimer;
+	struct timer_list		SwBwTimer;
+
+	// For Realtek proprietary A-MPDU factor for aggregation
+	u8				bRegRT2RTAggregation;
+	u8				bCurrentRT2RTAggregation;
+	u8				bCurrentRT2RTLongSlotTime;
+	u8				szRT2RTAggBuffer[10];
+
+	// Rx Reorder control
+	u8				bRegRxReorderEnable;
+	u8				bCurRxReorderEnable;
+	u8				RxReorderWinSize;
+	u8				RxReorderPendingTime;
+	u16				RxReorderDropCounter;
+
+#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
+	u8				UsbTxAggrNum;
+#endif
+#ifdef USB_RX_AGGREGATION_SUPPORT
+	u8				UsbRxFwAggrEn;
+	u8				UsbRxFwAggrPageNum;
+	u8				UsbRxFwAggrPacketNum;
+	u8				UsbRxFwAggrTimeout;
+#endif
+
+	// Add for Broadcom(Linksys) IOT. Joseph
+	u8				bIsPeerBcm;
+
+	// For IOT issue.
+	u32					IOTAction;
+}RT_HIGH_THROUGHPUT, *PRT_HIGH_THROUGHPUT;
+
+
+//------------------------------------------------------------
+// The Data structure is used to keep HT related variable for "each Sta"
+// when card is configured as "AP mode"
+//------------------------------------------------------------
+
+typedef struct _RT_HTINFO_STA_ENTRY{
+	u8			bEnableHT;
+
+	u8			bSupportCck;
+
+	u16			AMSDU_MaxSize;
+
+	u8			AMPDU_Factor;
+	u8			MPDU_Density;
+
+	u8			HTHighestOperaRate;
+
+	u8			bBw40MHz;
+
+	u8			MimoPs;
+
+	u8			McsRateSet[16];
+
+
+}RT_HTINFO_STA_ENTRY, *PRT_HTINFO_STA_ENTRY;
+
+
+
+
+
+//------------------------------------------------------------
+// The Data structure is used to keep HT related variable for "each AP"
+// when card is configured as "STA mode"
+//------------------------------------------------------------
+
+typedef struct _BSS_HT{
+
+	u8				bdSupportHT;
+
+	// HT related elements
+	u8					bdHTCapBuf[32];
+	u16					bdHTCapLen;
+	u8					bdHTInfoBuf[32];
+	u16					bdHTInfoLen;
+
+	HT_SPEC_VER				bdHTSpecVer;
+	//HT_CAPABILITY_ELE			bdHTCapEle;
+	//HT_INFORMATION_ELE		bdHTInfoEle;
+
+	u8					bdRT2RTAggregation;
+	u8					bdRT2RTLongSlotTime;
+	bool					bdHT1R;
+}BSS_HT, *PBSS_HT;
+
+typedef struct _MIMO_RSSI{
+	u32	EnableAntenna;
+	u32	AntennaA;
+	u32 	AntennaB;
+	u32 	AntennaC;
+	u32 	AntennaD;
+	u32	Average;
+}MIMO_RSSI, *PMIMO_RSSI;
+
+typedef struct _MIMO_EVM{
+	u32	EVM1;
+	u32    EVM2;
+}MIMO_EVM, *PMIMO_EVM;
+
+typedef struct _FALSE_ALARM_STATISTICS{
+	u32	Cnt_Parity_Fail;
+	u32    Cnt_Rate_Illegal;
+	u32	Cnt_Crc8_fail;
+	u32	Cnt_all;
+}FALSE_ALARM_STATISTICS, *PFALSE_ALARM_STATISTICS;
+
+
+
+#endif //__INC_HTTYPE_H
+
diff --git a/drivers/staging/rtl8192su/r819xU_cmdpkt.c b/drivers/staging/rtl8192su/r819xU_cmdpkt.c
new file mode 100644
index 0000000..c1149c6
--- /dev/null
+++ b/drivers/staging/rtl8192su/r819xU_cmdpkt.c
@@ -0,0 +1,826 @@
+/******************************************************************************
+
+     (c) Copyright 2008, RealTEK Technologies Inc. All Rights Reserved.
+
+ Module:	r819xusb_cmdpkt.c	(RTL8190 TX/RX command packet handler Source C File)
+
+ Note:      The module is responsible for handling TX and RX command packet.
+ 			1. TX : Send set and query configuration command packet.
+ 			2. RX : Receive tx feedback, beacon state, query configuration
+ 			        command packet.
+
+ Function:
+
+ Export:
+
+ Abbrev:
+
+ History:
+	Data		Who		Remark
+
+	05/06/2008  amy    	Create initial version porting from windows driver.
+
+******************************************************************************/
+#include "r8192U.h"
+#include "r819xU_cmdpkt.h"
+/*---------------------------Define Local Constant---------------------------*/
+/* Debug constant*/
+#define		CMPK_DEBOUNCE_CNT			1
+/* 2007/10/24 MH Add for printing a range of data. */
+#define		CMPK_PRINT(Address)\
+{\
+	unsigned char	i;\
+	u32	temp[10];\
+	\
+	memcpy(temp, Address, 40);\
+	for (i = 0; i <40; i+=4)\
+		printk("\r\n %08x", temp[i]);\
+}\
+/*---------------------------Define functions---------------------------------*/
+
+bool
+SendTxCommandPacket(
+	struct net_device *dev,
+	void* 			pData,
+	u32				DataLen
+	)
+{
+	bool	rtStatus = true;
+	struct r8192_priv   *priv = ieee80211_priv(dev);
+	struct sk_buff	    *skb;
+	cb_desc		    *tcb_desc;
+	unsigned char	    *ptr_buf;
+	//bool	bLastInitPacket = false;
+
+	//PlatformAcquireSpinLock(Adapter, RT_TX_SPINLOCK);
+
+	//Get TCB and local buffer from common pool. (It is shared by CmdQ, MgntQ, and USB coalesce DataQ)
+	skb  = dev_alloc_skb(USB_HWDESC_HEADER_LEN + DataLen + 4);
+	memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
+	tcb_desc = (cb_desc*)(skb->cb + MAX_DEV_ADDR_SIZE);
+	tcb_desc->queue_index = TXCMD_QUEUE;
+	tcb_desc->bCmdOrInit = DESC_PACKET_TYPE_NORMAL;
+	tcb_desc->bLastIniPkt = 0;
+	skb_reserve(skb, USB_HWDESC_HEADER_LEN);
+	ptr_buf = skb_put(skb, DataLen);
+	memset(ptr_buf,0,DataLen);
+	memcpy(ptr_buf,pData,DataLen);
+	tcb_desc->txbuf_size= (u16)DataLen;
+
+	if(!priv->ieee80211->check_nic_enough_desc(dev,tcb_desc->queue_index)||
+			(!skb_queue_empty(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index]))||\
+			(priv->ieee80211->queue_stop) ) {
+			RT_TRACE(COMP_FIRMWARE,"===================NULL packet==================================> tx full!\n");
+			skb_queue_tail(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index], skb);
+		} else {
+			priv->ieee80211->softmac_hard_start_xmit(skb,dev);
+		}
+
+	//PlatformReleaseSpinLock(Adapter, RT_TX_SPINLOCK);
+	return rtStatus;
+}
+
+/*-----------------------------------------------------------------------------
+ * Function:	cmpk_message_handle_tx()
+ *
+ * Overview:	Driver internal module can call the API to send message to
+ *				firmware side. For example, you can send a debug command packet.
+ *				Or you can send a request for FW to modify RLX4181 LBUS HW bank.
+ *				Otherwise, you can change MAC/PHT/RF register by firmware at
+ *				run time. We do not support message more than one segment now.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/06/2008	amy		porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+ extern	bool	cmpk_message_handle_tx(
+	struct net_device *dev,
+	u8*	codevirtualaddress,
+	u32	packettype,
+	u32	buffer_len)
+{
+
+	bool 	    rt_status = true;
+#ifdef RTL8192SU
+	return rt_status;
+#else
+#ifdef RTL8192U
+	return rt_status;
+#else
+	struct r8192_priv   *priv = ieee80211_priv(dev);
+	u16		    frag_threshold;
+	u16		    frag_length, frag_offset = 0;
+	//u16		    total_size;
+	//int		    i;
+
+	rt_firmware	    *pfirmware = priv->pFirmware;
+	struct sk_buff	    *skb;
+	unsigned char	    *seg_ptr;
+	cb_desc		    *tcb_desc;
+	u8                  bLastIniPkt;
+
+	firmware_init_param(dev);
+	//Fragmentation might be required
+	frag_threshold = pfirmware->cmdpacket_frag_thresold;
+	do {
+		if((buffer_len - frag_offset) > frag_threshold) {
+			frag_length = frag_threshold ;
+			bLastIniPkt = 0;
+
+		} else {
+			frag_length = buffer_len - frag_offset;
+			bLastIniPkt = 1;
+
+		}
+
+		/* Allocate skb buffer to contain firmware info and tx descriptor info
+		 * add 4 to avoid packet appending overflow.
+		 * */
+		#ifdef RTL8192U
+		skb  = dev_alloc_skb(USB_HWDESC_HEADER_LEN + frag_length + 4);
+		#else
+		skb  = dev_alloc_skb(frag_length + 4);
+		#endif
+		memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
+		tcb_desc = (cb_desc*)(skb->cb + MAX_DEV_ADDR_SIZE);
+		tcb_desc->queue_index = TXCMD_QUEUE;
+		tcb_desc->bCmdOrInit = packettype;
+		tcb_desc->bLastIniPkt = bLastIniPkt;
+
+		#ifdef RTL8192U
+		skb_reserve(skb, USB_HWDESC_HEADER_LEN);
+		#endif
+
+		seg_ptr = skb_put(skb, buffer_len);
+		/*
+		 * Transform from little endian to big endian
+                 * and pending  zero
+		 */
+		memcpy(seg_ptr,codevirtualaddress,buffer_len);
+		tcb_desc->txbuf_size= (u16)buffer_len;
+
+
+		if(!priv->ieee80211->check_nic_enough_desc(dev,tcb_desc->queue_index)||
+			(!skb_queue_empty(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index]))||\
+			(priv->ieee80211->queue_stop) ) {
+			RT_TRACE(COMP_FIRMWARE,"=====================================================> tx full!\n");
+			skb_queue_tail(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index], skb);
+		} else {
+			priv->ieee80211->softmac_hard_start_xmit(skb,dev);
+		}
+
+		codevirtualaddress += frag_length;
+		frag_offset += frag_length;
+
+	}while(frag_offset < buffer_len);
+
+	return rt_status;
+
+
+#endif
+#endif
+}	/* CMPK_Message_Handle_Tx */
+
+/*-----------------------------------------------------------------------------
+ * Function:    cmpk_counttxstatistic()
+ *
+ * Overview:
+ *
+ * Input:       PADAPTER 	pAdapter		-	.
+ *				CMPK_TXFB_T *psTx_FB	-	.
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ *  When		Who		Remark
+ *  05/12/2008	amy 	Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+cmpk_count_txstatistic(
+	struct net_device *dev,
+	cmpk_txfb_t	*pstx_fb)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+#ifdef ENABLE_PS
+	RT_RF_POWER_STATE	rtState;
+
+	pAdapter->HalFunc.GetHwRegHandler(pAdapter, HW_VAR_RF_STATE, (pu1Byte)(&rtState));
+
+	// When RF is off, we should not count the packet for hw/sw synchronize
+	// reason, ie. there may be a duration while sw switch is changed and hw
+	// switch is being changed. 2006.12.04, by shien chang.
+	if (rtState == eRfOff)
+	{
+		return;
+	}
+#endif
+
+#ifdef TODO
+	if(pAdapter->bInHctTest)
+		return;
+#endif
+	/* We can not know the packet length and transmit type: broadcast or uni
+	   or multicast. So the relative statistics must be collected in tx
+	   feedback info. */
+	if (pstx_fb->tok)
+	{
+		priv->stats.txfeedbackok++;
+		priv->stats.txoktotal++;
+		priv->stats.txokbytestotal += pstx_fb->pkt_length;
+		priv->stats.txokinperiod++;
+
+		/* We can not make sure broadcast/multicast or unicast mode. */
+		if (pstx_fb->pkt_type == PACKET_MULTICAST)
+		{
+			priv->stats.txmulticast++;
+			priv->stats.txbytesmulticast += pstx_fb->pkt_length;
+		}
+		else if (pstx_fb->pkt_type == PACKET_BROADCAST)
+		{
+			priv->stats.txbroadcast++;
+			priv->stats.txbytesbroadcast += pstx_fb->pkt_length;
+		}
+		else
+		{
+			priv->stats.txunicast++;
+			priv->stats.txbytesunicast += pstx_fb->pkt_length;
+		}
+	}
+	else
+	{
+		priv->stats.txfeedbackfail++;
+		priv->stats.txerrtotal++;
+		priv->stats.txerrbytestotal += pstx_fb->pkt_length;
+
+		/* We can not make sure broadcast/multicast or unicast mode. */
+		if (pstx_fb->pkt_type == PACKET_MULTICAST)
+		{
+			priv->stats.txerrmulticast++;
+		}
+		else if (pstx_fb->pkt_type == PACKET_BROADCAST)
+		{
+			priv->stats.txerrbroadcast++;
+		}
+		else
+		{
+			priv->stats.txerrunicast++;
+		}
+	}
+
+	priv->stats.txretrycount += pstx_fb->retry_cnt;
+	priv->stats.txfeedbackretry += pstx_fb->retry_cnt;
+
+}	/* cmpk_CountTxStatistic */
+
+
+
+/*-----------------------------------------------------------------------------
+ * Function:    cmpk_handle_tx_feedback()
+ *
+ * Overview:	The function is responsible for extract the message inside TX
+ *				feedbck message from firmware. It will contain dedicated info in
+ *				ws-06-0063-rtl8190-command-packet-specification. Please
+ *				refer to chapter "TX Feedback Element". We have to read 20 bytes
+ *				in the command packet.
+ *
+ * Input:       struct net_device *    dev
+ *				u8 	*	pmsg		-	Msg Ptr of the command packet.
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ *  When		Who		Remark
+ *  05/08/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+cmpk_handle_tx_feedback(
+	struct net_device *dev,
+	u8	*	pmsg)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	cmpk_txfb_t		rx_tx_fb;	/* */
+
+	priv->stats.txfeedback++;
+
+	/* 0. Display received message. */
+	//cmpk_Display_Message(CMPK_RX_TX_FB_SIZE, pMsg);
+
+	/* 1. Extract TX feedback info from RFD to temp structure buffer. */
+	/* It seems that FW use big endian(MIPS) and DRV use little endian in
+	   windows OS. So we have to read the content byte by byte or transfer
+	   endian type before copy the message copy. */
+#if 0		// The TX FEEDBACK packet element address
+	//rx_tx_fb.Element_ID 	= pMsg[0];
+	//rx_tx_fb.Length 		= pMsg[1];
+	rx_tx_fb.TOK 			= pMsg[2]>>7;
+	rx_tx_fb.Fail_Reason 	= (pMsg[2] & 0x70) >> 4;
+	rx_tx_fb.TID 			= (pMsg[2] & 0x0F);
+	rx_tx_fb.Qos_Pkt 		= pMsg[3] >> 7;
+	rx_tx_fb.Bandwidth 		= (pMsg[3] & 0x40) >> 6;
+	rx_tx_fb.Retry_Cnt 		= pMsg[5];
+	rx_tx_fb.Pkt_ID 		= (pMsg[6] << 8) | pMsg[7];
+	rx_tx_fb.Seq_Num 		= (pMsg[8] << 8) | pMsg[9];
+	rx_tx_fb.S_Rate 		= pMsg[10];
+	rx_tx_fb.F_Rate 		= pMsg[11];
+	rx_tx_fb.S_RTS_Rate 	= pMsg[12];
+	rx_tx_fb.F_RTS_Rate 	= pMsg[13];
+	rx_tx_fb.pkt_length	= (pMsg[14] << 8) | pMsg[15];
+#endif
+	/* 2007/07/05 MH Use pointer to transfer structure memory. */
+	//memcpy((UINT8 *)&rx_tx_fb, pMsg, sizeof(CMPK_TXFB_T));
+	memcpy((u8*)&rx_tx_fb, pmsg, sizeof(cmpk_txfb_t));
+	/* 2. Use tx feedback info to count TX statistics. */
+	cmpk_count_txstatistic(dev, &rx_tx_fb);
+#if 0
+	/* 2007/07/11 MH Assign current operate rate.  */
+	if (pAdapter->RegWirelessMode == WIRELESS_MODE_A ||
+		pAdapter->RegWirelessMode == WIRELESS_MODE_B ||
+		pAdapter->RegWirelessMode == WIRELESS_MODE_G)
+	{
+		pMgntInfo->CurrentOperaRate = (rx_tx_fb.F_Rate & 0x7F);
+	}
+	else if (pAdapter->RegWirelessMode == WIRELESS_MODE_N_24G ||
+		 	 pAdapter->RegWirelessMode == WIRELESS_MODE_N_5G)
+	{
+		pMgntInfo->HTCurrentOperaRate = (rx_tx_fb.F_Rate & 0x8F);
+	}
+#endif
+	/* 2007/01/17 MH Comment previous method for TX statistic function. */
+	/* Collect info TX feedback packet to fill TCB. */
+	/* We can not know the packet length and transmit type: broadcast or uni
+	   or multicast. */
+	//CountTxStatistics( pAdapter, &tcb );
+
+}	/* cmpk_Handle_Tx_Feedback */
+
+void
+cmdpkt_beacontimerinterrupt_819xusb(
+	struct net_device *dev
+)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u16 tx_rate;
+	{
+		//
+		// 070117, rcnjko: 87B have to S/W beacon for DTM encryption_cmn.
+		//
+		if(priv->ieee80211->current_network.mode == IEEE_A  ||
+			priv->ieee80211->current_network.mode == IEEE_N_5G ||
+			(priv->ieee80211->current_network.mode == IEEE_N_24G  && (!priv->ieee80211->pHTInfo->bCurSuppCCK)))
+		{
+			tx_rate = 60;
+			DMESG("send beacon frame  tx rate is 6Mbpm\n");
+		}
+		else
+		{
+			tx_rate =10;
+			DMESG("send beacon frame  tx rate is 1Mbpm\n");
+		}
+
+		rtl819xusb_beacon_tx(dev,tx_rate); // HW Beacon
+
+	}
+
+}
+
+
+
+
+/*-----------------------------------------------------------------------------
+ * Function:    cmpk_handle_interrupt_status()
+ *
+ * Overview:    The function is responsible for extract the message from
+ *				firmware. It will contain dedicated info in
+ *				ws-07-0063-v06-rtl819x-command-packet-specification-070315.doc.
+ * 				Please refer to chapter "Interrupt Status Element".
+ *
+ * Input:       struct net_device *dev,
+ *			u8*	pmsg		-	Message Pointer of the command packet.
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ *  When			Who			Remark
+ *  05/12/2008	amy		Add this for rtl8192 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+cmpk_handle_interrupt_status(
+	struct net_device *dev,
+	u8*	pmsg)
+{
+	cmpk_intr_sta_t		rx_intr_status;	/* */
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	DMESG("---> cmpk_Handle_Interrupt_Status()\n");
+
+	/* 0. Display received message. */
+	//cmpk_Display_Message(CMPK_RX_BEACON_STATE_SIZE, pMsg);
+
+	/* 1. Extract TX feedback info from RFD to temp structure buffer. */
+	/* It seems that FW use big endian(MIPS) and DRV use little endian in
+	   windows OS. So we have to read the content byte by byte or transfer
+	   endian type before copy the message copy. */
+	//rx_bcn_state.Element_ID 	= pMsg[0];
+	//rx_bcn_state.Length 		= pMsg[1];
+	rx_intr_status.length = pmsg[1];
+	if (rx_intr_status.length != (sizeof(cmpk_intr_sta_t) - 2))
+	{
+		DMESG("cmpk_Handle_Interrupt_Status: wrong length!\n");
+		return;
+	}
+
+
+	// Statistics of beacon for ad-hoc mode.
+	if(	priv->ieee80211->iw_mode == IW_MODE_ADHOC)
+	{
+		//2 maybe need endian transform?
+		rx_intr_status.interrupt_status = *((u32 *)(pmsg + 4));
+		//rx_intr_status.InterruptStatus = N2H4BYTE(*((UINT32 *)(pMsg + 4)));
+
+		DMESG("interrupt status = 0x%x\n", rx_intr_status.interrupt_status);
+
+		if (rx_intr_status.interrupt_status & ISR_TxBcnOk)
+		{
+			priv->ieee80211->bibsscoordinator = true;
+			priv->stats.txbeaconokint++;
+		}
+		else if (rx_intr_status.interrupt_status & ISR_TxBcnErr)
+		{
+			priv->ieee80211->bibsscoordinator = false;
+			priv->stats.txbeaconerr++;
+		}
+
+		if (rx_intr_status.interrupt_status & ISR_BcnTimerIntr)
+		{
+			cmdpkt_beacontimerinterrupt_819xusb(dev);
+		}
+
+	}
+
+	 // Other informations in interrupt status we need?
+
+
+	DMESG("<---- cmpk_handle_interrupt_status()\n");
+
+}	/* cmpk_handle_interrupt_status */
+
+
+/*-----------------------------------------------------------------------------
+ * Function:    cmpk_handle_query_config_rx()
+ *
+ * Overview:    The function is responsible for extract the message from
+ *				firmware. It will contain dedicated info in
+ *				ws-06-0063-rtl8190-command-packet-specification. Please
+ *				refer to chapter "Beacon State Element".
+ *
+ * Input:       u8 *  pmsg	-	Message Pointer of the command packet.
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ *  When		Who		Remark
+ *  05/12/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+cmpk_handle_query_config_rx(
+	struct net_device *dev,
+	u8*	   pmsg)
+{
+	cmpk_query_cfg_t	rx_query_cfg;	/* */
+
+	/* 0. Display received message. */
+	//cmpk_Display_Message(CMPK_RX_BEACON_STATE_SIZE, pMsg);
+
+	/* 1. Extract TX feedback info from RFD to temp structure buffer. */
+	/* It seems that FW use big endian(MIPS) and DRV use little endian in
+	   windows OS. So we have to read the content byte by byte or transfer
+	   endian type before copy the message copy. */
+	//rx_query_cfg.Element_ID 	= pMsg[0];
+	//rx_query_cfg.Length 		= pMsg[1];
+	rx_query_cfg.cfg_action 	= (pmsg[4] & 0x80000000)>>31;
+	rx_query_cfg.cfg_type 		= (pmsg[4] & 0x60) >> 5;
+	rx_query_cfg.cfg_size 		= (pmsg[4] & 0x18) >> 3;
+	rx_query_cfg.cfg_page 		= (pmsg[6] & 0x0F) >> 0;
+	rx_query_cfg.cfg_offset 		= pmsg[7];
+	rx_query_cfg.value 			= (pmsg[8] << 24) | (pmsg[9] << 16) |
+								  (pmsg[10] << 8) | (pmsg[11] << 0);
+	rx_query_cfg.mask 			= (pmsg[12] << 24) | (pmsg[13] << 16) |
+								  (pmsg[14] << 8) | (pmsg[15] << 0);
+
+}	/* cmpk_Handle_Query_Config_Rx */
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	cmpk_count_tx_status()
+ *
+ * Overview:	Count aggregated tx status from firmwar of one type rx command
+ *				packet element id = RX_TX_STATUS.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/12/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static	void	cmpk_count_tx_status(	struct net_device *dev,
+									cmpk_tx_status_t 	*pstx_status)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+#ifdef ENABLE_PS
+
+	RT_RF_POWER_STATE	rtstate;
+
+	pAdapter->HalFunc.GetHwRegHandler(pAdapter, HW_VAR_RF_STATE, (pu1Byte)(&rtState));
+
+	// When RF is off, we should not count the packet for hw/sw synchronize
+	// reason, ie. there may be a duration while sw switch is changed and hw
+	// switch is being changed. 2006.12.04, by shien chang.
+	if (rtState == eRfOff)
+	{
+		return;
+	}
+#endif
+
+	priv->stats.txfeedbackok	+= pstx_status->txok;
+	priv->stats.txoktotal		+= pstx_status->txok;
+
+	priv->stats.txfeedbackfail	+= pstx_status->txfail;
+	priv->stats.txerrtotal		+= pstx_status->txfail;
+
+	priv->stats.txretrycount		+= pstx_status->txretry;
+	priv->stats.txfeedbackretry	+= pstx_status->txretry;
+
+	//pAdapter->TxStats.NumTxOkBytesTotal += psTx_FB->pkt_length;
+	//pAdapter->TxStats.NumTxErrBytesTotal += psTx_FB->pkt_length;
+	//pAdapter->MgntInfo.LinkDetectInfo.NumTxOkInPeriod++;
+
+	priv->stats.txmulticast	+= pstx_status->txmcok;
+	priv->stats.txbroadcast	+= pstx_status->txbcok;
+	priv->stats.txunicast		+= pstx_status->txucok;
+
+	priv->stats.txerrmulticast	+= pstx_status->txmcfail;
+	priv->stats.txerrbroadcast	+= pstx_status->txbcfail;
+	priv->stats.txerrunicast	+= pstx_status->txucfail;
+
+	priv->stats.txbytesmulticast	+= pstx_status->txmclength;
+	priv->stats.txbytesbroadcast	+= pstx_status->txbclength;
+	priv->stats.txbytesunicast		+= pstx_status->txuclength;
+
+	priv->stats.last_packet_rate		= pstx_status->rate;
+}	/* cmpk_CountTxStatus */
+
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	cmpk_handle_tx_status()
+ *
+ * Overview:	Firmware add a new tx feedback status to reduce rx command
+ *				packet buffer operation load.
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/12/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+cmpk_handle_tx_status(
+	struct net_device *dev,
+	u8*	   pmsg)
+{
+	cmpk_tx_status_t	rx_tx_sts;	/* */
+
+	memcpy((void*)&rx_tx_sts, (void*)pmsg, sizeof(cmpk_tx_status_t));
+	/* 2. Use tx feedback info to count TX statistics. */
+	cmpk_count_tx_status(dev, &rx_tx_sts);
+
+}	/* cmpk_Handle_Tx_Status */
+
+
+/*-----------------------------------------------------------------------------
+ * Function:	cmpk_handle_tx_rate_history()
+ *
+ * Overview:	Firmware add a new tx rate history
+ *
+ * Input:		NONE
+ *
+ * Output:		NONE
+ *
+ * Return:		NONE
+ *
+ * Revised History:
+ *	When		Who		Remark
+ *	05/12/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+static	void
+cmpk_handle_tx_rate_history(
+	struct net_device *dev,
+	u8*	   pmsg)
+{
+	cmpk_tx_rahis_t	*ptxrate;
+//	RT_RF_POWER_STATE	rtState;
+	u8				i, j;
+	u16				length = sizeof(cmpk_tx_rahis_t);
+	u32				*ptemp;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+
+#ifdef ENABLE_PS
+	pAdapter->HalFunc.GetHwRegHandler(pAdapter, HW_VAR_RF_STATE, (pu1Byte)(&rtState));
+
+	// When RF is off, we should not count the packet for hw/sw synchronize
+	// reason, ie. there may be a duration while sw switch is changed and hw
+	// switch is being changed. 2006.12.04, by shien chang.
+	if (rtState == eRfOff)
+	{
+		return;
+	}
+#endif
+
+	ptemp = (u32 *)pmsg;
+
+	//
+	// Do endian transfer to word alignment(16 bits) for windows system.
+	// You must do different endian transfer for linux and MAC OS
+	//
+	for (i = 0; i < (length/4); i++)
+	{
+		u16	 temp1, temp2;
+
+		temp1 = ptemp[i]&0x0000FFFF;
+		temp2 = ptemp[i]>>16;
+		ptemp[i] = (temp1<<16)|temp2;
+	}
+
+	ptxrate = (cmpk_tx_rahis_t *)pmsg;
+
+	if (ptxrate == NULL )
+	{
+		return;
+	}
+
+	for (i = 0; i < 16; i++)
+	{
+		// Collect CCK rate packet num
+		if (i < 4)
+			priv->stats.txrate.cck[i] += ptxrate->cck[i];
+
+		// Collect OFDM rate packet num
+		if (i< 8)
+			priv->stats.txrate.ofdm[i] += ptxrate->ofdm[i];
+
+		for (j = 0; j < 4; j++)
+			priv->stats.txrate.ht_mcs[j][i] += ptxrate->ht_mcs[j][i];
+	}
+
+}	/* cmpk_Handle_Tx_Rate_History */
+
+
+/*-----------------------------------------------------------------------------
+ * Function:    cmpk_message_handle_rx()
+ *
+ * Overview:    In the function, we will capture different RX command packet
+ *				info. Every RX command packet element has different message
+ *				length and meaning in content. We only support three type of RX
+ *				command packet now. Please refer to document
+ *				ws-06-0063-rtl8190-command-packet-specification.
+ *
+ * Input:       NONE
+ *
+ * Output:      NONE
+ *
+ * Return:      NONE
+ *
+ * Revised History:
+ *  When		Who		Remark
+ *  05/06/2008	amy		Create Version 0 porting from windows code.
+ *
+ *---------------------------------------------------------------------------*/
+extern	u32
+cmpk_message_handle_rx(
+	struct net_device *dev,
+	struct ieee80211_rx_stats *pstats)
+{
+//	u32			debug_level = DBG_LOUD;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	int			total_length;
+	u8			cmd_length, exe_cnt = 0;
+	u8			element_id;
+	u8			*pcmd_buff;
+
+	/* 0. Check inpt arguments. If is is a command queue message or pointer is
+	      null. */
+	if (/*(prfd->queue_id != CMPK_RX_QUEUE_ID) || */(pstats== NULL))
+	{
+		/* Print error message. */
+		/*RT_TRACE(COMP_SEND, DebugLevel,
+				("\n\r[CMPK]-->Err queue id or pointer"));*/
+		return 0;	/* This is not a command packet. */
+	}
+
+	/* 1. Read received command packet message length from RFD. */
+	total_length = pstats->Length;
+
+	/* 2. Read virtual address from RFD. */
+	pcmd_buff = pstats->virtual_address;
+
+	/* 3. Read command pakcet element id and length. */
+	element_id = pcmd_buff[0];
+	/*RT_TRACE(COMP_SEND, DebugLevel,
+			("\n\r[CMPK]-->element ID=%d Len=%d", element_id, total_length));*/
+
+	/* 4. Check every received command packet conent according to different
+	      element type. Because FW may aggregate RX command packet to minimize
+	      transmit time between DRV and FW.*/
+	// Add a counter to prevent to locked in the loop too long
+	while (total_length > 0 || exe_cnt++ >100)
+	{
+		/* 2007/01/17 MH We support aggregation of different cmd in the same packet. */
+		element_id = pcmd_buff[0];
+
+		switch(element_id)
+		{
+			case RX_TX_FEEDBACK:
+				cmpk_handle_tx_feedback (dev, pcmd_buff);
+				cmd_length = CMPK_RX_TX_FB_SIZE;
+				break;
+
+			case RX_INTERRUPT_STATUS:
+				cmpk_handle_interrupt_status(dev, pcmd_buff);
+				cmd_length = sizeof(cmpk_intr_sta_t);
+				break;
+
+			case BOTH_QUERY_CONFIG:
+				cmpk_handle_query_config_rx(dev, pcmd_buff);
+				cmd_length = CMPK_BOTH_QUERY_CONFIG_SIZE;
+				break;
+
+			case RX_TX_STATUS:
+				cmpk_handle_tx_status(dev, pcmd_buff);
+				cmd_length = CMPK_RX_TX_STS_SIZE;
+				break;
+
+			case RX_TX_PER_PKT_FEEDBACK:
+				// You must at lease add a switch case element here,
+				// Otherwise, we will jump to default case.
+				//DbgPrint("CCX Test\r\n");
+				cmd_length = CMPK_RX_TX_FB_SIZE;
+				break;
+
+			case RX_TX_RATE_HISTORY:
+				//DbgPrint(" rx tx rate history\r\n");
+				cmpk_handle_tx_rate_history(dev, pcmd_buff);
+				cmd_length = CMPK_TX_RAHIS_SIZE;
+				break;
+
+			default:
+
+			        RT_TRACE(COMP_ERR, "---->cmpk_message_handle_rx():unknow CMD Element\n");
+				return 1;	/* This is a command packet. */
+		}
+		// 2007/01/22 MH Display received rx command packet info.
+		//cmpk_Display_Message(cmd_length, pcmd_buff);
+
+		// 2007/01/22 MH Add to display tx statistic.
+		//cmpk_DisplayTxStatistic(pAdapter);
+
+		/* 2007/03/09 MH Collect sidderent cmd element pkt num. */
+		priv->stats.rxcmdpkt[element_id]++;
+
+		total_length -= cmd_length;
+		pcmd_buff    += cmd_length;
+	}	/* while (total_length > 0) */
+	return	1;	/* This is a command packet. */
+
+}	/* CMPK_Message_Handle_Rx */
diff --git a/drivers/staging/rtl8192su/r819xU_cmdpkt.h b/drivers/staging/rtl8192su/r819xU_cmdpkt.h
new file mode 100644
index 0000000..f67af6c
--- /dev/null
+++ b/drivers/staging/rtl8192su/r819xU_cmdpkt.h
@@ -0,0 +1,219 @@
+#ifndef R819XUSB_CMDPKT_H
+#define R819XUSB_CMDPKT_H
+/* Different command packet have dedicated message length and definition. */
+#define		CMPK_RX_TX_FB_SIZE					sizeof(cmpk_txfb_t)		//20
+#define		CMPK_TX_SET_CONFIG_SIZE				sizeof(cmpk_set_cfg_t)	//16
+#define		CMPK_BOTH_QUERY_CONFIG_SIZE			sizeof(cmpk_set_cfg_t)	//16
+#define		CMPK_RX_TX_STS_SIZE					sizeof(cmpk_tx_status_t)//
+#define		CMPK_RX_DBG_MSG_SIZE			sizeof(cmpk_rx_dbginfo_t)//
+#define		CMPK_TX_RAHIS_SIZE			sizeof(cmpk_tx_rahis_t)
+
+/* 2008/05/08 amy For USB constant. */
+#define ISR_TxBcnOk					BIT27			// Transmit Beacon OK
+#define ISR_TxBcnErr				BIT26			// Transmit Beacon Error
+#define ISR_BcnTimerIntr			BIT13			// Beacon Timer Interrupt
+
+#if 0
+/* Define packet type. */
+typedef enum tag_packet_type
+{
+    PACKET_BROADCAST,
+    PACKET_MULTICAST,
+    PACKET_UNICAST,
+    PACKET_TYPE_MAX
+}cmpk_pkt_type_e;
+#endif
+
+/* Define element ID of command packet. */
+
+/*------------------------------Define structure----------------------------*/
+/* Define different command packet structure. */
+/* 1. RX side: TX feedback packet. */
+typedef struct tag_cmd_pkt_tx_feedback
+{
+	// DWORD 0
+	u8	element_id;			/* Command packet type. */
+	u8	length;				/* Command packet length. */
+	/* 2007/07/05 MH Change tx feedback info field. */
+	/*------TX Feedback Info Field */
+	u8	TID:4;				/* */
+	u8	fail_reason:3;		/* */
+	u8	tok:1;				/* Transmit ok. */
+	u8	reserve1:4;			/* */
+	u8	pkt_type:2;		/* */
+	u8	bandwidth:1;		/* */
+	u8	qos_pkt:1;			/* */
+
+	// DWORD 1
+	u8	reserve2;			/* */
+	/*------TX Feedback Info Field */
+	u8	retry_cnt;			/* */
+	u16	pkt_id;				/* */
+
+	// DWORD 3
+	u16	seq_num;			/* */
+	u8	s_rate;				/* Start rate. */
+	u8	f_rate;				/* Final rate. */
+
+	// DWORD 4
+	u8	s_rts_rate;			/* */
+	u8	f_rts_rate;			/* */
+	u16	pkt_length;			/* */
+
+	// DWORD 5
+	u16	reserve3;			/* */
+	u16	duration;			/* */
+}cmpk_txfb_t;
+
+/* 2. RX side: Interrupt status packet. It includes Beacon State,
+	  Beacon Timer Interrupt and other useful informations in MAC ISR Reg. */
+typedef struct tag_cmd_pkt_interrupt_status
+{
+	u8	element_id;			/* Command packet type. */
+	u8	length;				/* Command packet length. */
+	u16	reserve;
+	u32	interrupt_status;				/* Interrupt Status. */
+}cmpk_intr_sta_t;
+
+
+/* 3. TX side: Set configuration packet. */
+typedef struct tag_cmd_pkt_set_configuration
+{
+	u8	element_id;			/* Command packet type. */
+	u8	length;				/* Command packet length. */
+	u16	reserve1;			/* */
+	u8 	cfg_reserve1:3;
+	u8	cfg_size:2;			/* Configuration info. */
+	u8	cfg_type:2;			/* Configuration info. */
+	u8	cfg_action:1;		/* Configuration info. */
+	u8	cfg_reserve2;		/* Configuration info. */
+	u8	cfg_page:4;			/* Configuration info. */
+	u8	cfg_reserve3:4;		/* Configuration info. */
+	u8	cfg_offset;			/* Configuration info. */
+	u32	value;				/* */
+	u32	mask;				/* */
+}cmpk_set_cfg_t;
+
+/* 4. Both side : TX/RX query configuraton packet. The query structure is the
+      same as set configuration. */
+#define		cmpk_query_cfg_t	cmpk_set_cfg_t
+
+/* 5. Multi packet feedback status. */
+typedef struct tag_tx_stats_feedback // PJ quick rxcmd 09042007
+{
+	// For endian transfer --> Driver will not the same as firmware structure.
+	// DW 0
+	u16	reserve1;
+	u8 	length;				// Command packet length
+	u8 	element_id;			// Command packet type
+
+	// DW 1
+	u16	txfail;				// Tx Fail count
+	u16 	txok;				// Tx ok count
+
+	// DW 2
+	u16	txmcok;  			// tx multicast
+	u16 	txretry;			// Tx Retry count
+
+	// DW 3
+	u16  txucok;				// tx unicast
+	u16	txbcok;  			// tx broadcast
+
+	// DW 4
+	u16	txbcfail;			//
+	u16	txmcfail;			//
+
+	// DW 5
+	u16	reserve2;			//
+	u16	txucfail;			//
+
+	// DW 6-8
+	u32	txmclength;
+	u32	txbclength;
+	u32	txuclength;
+
+	// DW 9
+	u16	reserve3_23;
+	u8	reserve3_1;
+	u8	rate;
+}__attribute__((packed)) cmpk_tx_status_t;
+
+/* 6. Debug feedback message. */
+/* 2007/10/23 MH Define RX debug message  */
+typedef struct tag_rx_debug_message_feedback
+{
+	// For endian transfer --> for driver
+	// DW 0
+	u16	reserve1;
+	u8 	length;				// Command packet length
+	u8 	element_id;			// Command packet type
+
+	// DW 1-??
+	// Variable debug message.
+
+}cmpk_rx_dbginfo_t;
+
+/* 2008/03/20 MH Define transmit rate history. For big endian format. */
+typedef struct tag_tx_rate_history
+{
+	// For endian transfer --> for driver
+	// DW 0
+	u8 	element_id;			// Command packet type
+	u8 	length;				// Command packet length
+	u16	reserved1;
+
+	// DW 1-2	CCK rate counter
+	u16 	cck[4];
+
+	// DW 3-6
+	u16 	ofdm[8];
+
+	// DW 7-14
+	//UINT16	MCS_BW0_SG0[16];
+
+	// DW 15-22
+	//UINT16	MCS_BW1_SG0[16];
+
+	// DW 23-30
+	//UINT16	MCS_BW0_SG1[16];
+
+	// DW 31-38
+	//UINT16	MCS_BW1_SG1[16];
+
+	// DW 7-14	BW=0 SG=0
+	// DW 15-22	BW=1 SG=0
+	// DW 23-30	BW=0 SG=1
+	// DW 31-38	BW=1 SG=1
+	u16	ht_mcs[4][16];
+
+}__attribute__((packed)) cmpk_tx_rahis_t;
+
+typedef enum tag_command_packet_directories
+{
+    RX_TX_FEEDBACK = 0,
+    RX_INTERRUPT_STATUS		= 1,
+    TX_SET_CONFIG				= 2,
+    BOTH_QUERY_CONFIG			= 3,
+    RX_TX_STATUS				= 4,
+    RX_DBGINFO_FEEDBACK		= 5,
+    RX_TX_PER_PKT_FEEDBACK		= 6,
+    RX_TX_RATE_HISTORY		= 7,
+    RX_CMD_ELE_MAX
+}cmpk_element_e;
+
+#if 0
+typedef enum _rt_status{
+        RT_STATUS_SUCCESS,
+        RT_STATUS_FAILURE,
+        RT_STATUS_PENDING,
+        RT_STATUS_RESOURCE
+}rt_status,*prt_status;
+#endif
+
+extern bool cmpk_message_handle_tx(struct net_device *dev, u8* codevirtualaddress, u32 packettype, u32 buffer_len);
+
+extern  u32 cmpk_message_handle_rx(struct net_device *dev, struct ieee80211_rx_stats * pstats);
+extern bool SendTxCommandPacket( struct net_device *dev, void* pData, u32 DataLen);
+
+
+#endif
diff --git a/drivers/staging/rtl8192su/r819xU_firmware.c b/drivers/staging/rtl8192su/r819xU_firmware.c
new file mode 100644
index 0000000..219f71e
--- /dev/null
+++ b/drivers/staging/rtl8192su/r819xU_firmware.c
@@ -0,0 +1,707 @@
+/**************************************************************************************************
+ * Procedure:    Init boot code/firmware code/data session
+ *
+ * Description: This routine will intialize firmware. If any error occurs during the initialization
+ * 		process, the routine shall terminate immediately and return fail.
+ *		NIC driver should call NdisOpenFile only from MiniportInitialize.
+ *
+ * Arguments:   The pointer of the adapter
+
+ * Returns:
+ *        NDIS_STATUS_FAILURE - the following initialization process should be terminated
+ *        NDIS_STATUS_SUCCESS - if firmware initialization process success
+**************************************************************************************************/
+//#include "ieee80211.h"
+#include "r8192U.h"
+#include "r8192U_hw.h"
+#include "r819xU_firmware_img.h"
+#include "r819xU_firmware.h"
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+#include <linux/firmware.h>
+#endif
+void firmware_init_param(struct net_device *dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	rt_firmware		*pfirmware = priv->pFirmware;
+
+	pfirmware->cmdpacket_frag_thresold = GET_COMMAND_PACKET_FRAG_THRESHOLD(MAX_TRANSMIT_BUFFER_SIZE);
+}
+
+/*
+ * segment the img and use the ptr and length to remember info on each segment
+ *
+ */
+bool fw_download_code(struct net_device *dev, u8 *code_virtual_address, u32 buffer_len)
+{
+	struct r8192_priv   *priv = ieee80211_priv(dev);
+	bool 		    rt_status = true;
+	u16		    frag_threshold;
+	u16		    frag_length, frag_offset = 0;
+	//u16		    total_size;
+	int		    i;
+
+	rt_firmware	    *pfirmware = priv->pFirmware;
+	struct sk_buff	    *skb;
+	unsigned char	    *seg_ptr;
+	cb_desc		    *tcb_desc;
+	u8                  bLastIniPkt;
+
+	firmware_init_param(dev);
+	//Fragmentation might be required
+	frag_threshold = pfirmware->cmdpacket_frag_thresold;
+	do {
+		if((buffer_len - frag_offset) > frag_threshold) {
+			frag_length = frag_threshold ;
+			bLastIniPkt = 0;
+
+		} else {
+			frag_length = buffer_len - frag_offset;
+			bLastIniPkt = 1;
+
+		}
+
+		/* Allocate skb buffer to contain firmware info and tx descriptor info
+		 * add 4 to avoid packet appending overflow.
+		 * */
+		#ifdef RTL8192U
+		skb  = dev_alloc_skb(USB_HWDESC_HEADER_LEN + frag_length + 4);
+		#else
+		skb  = dev_alloc_skb(frag_length + 4);
+		#endif
+		memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
+		tcb_desc = (cb_desc*)(skb->cb + MAX_DEV_ADDR_SIZE);
+		tcb_desc->queue_index = TXCMD_QUEUE;
+		tcb_desc->bCmdOrInit = DESC_PACKET_TYPE_INIT;
+		tcb_desc->bLastIniPkt = bLastIniPkt;
+
+		#ifdef RTL8192U
+		skb_reserve(skb, USB_HWDESC_HEADER_LEN);
+		#endif
+		seg_ptr = skb->data;
+		/*
+		 * Transform from little endian to big endian
+                 * and pending  zero
+		 */
+		for(i=0 ; i < frag_length; i+=4) {
+			*seg_ptr++ = ((i+0)<frag_length)?code_virtual_address[i+3]:0;
+			*seg_ptr++ = ((i+1)<frag_length)?code_virtual_address[i+2]:0;
+			*seg_ptr++ = ((i+2)<frag_length)?code_virtual_address[i+1]:0;
+			*seg_ptr++ = ((i+3)<frag_length)?code_virtual_address[i+0]:0;
+		}
+		tcb_desc->txbuf_size= (u16)i;
+		skb_put(skb, i);
+
+		if(!priv->ieee80211->check_nic_enough_desc(dev,tcb_desc->queue_index)||
+			(!skb_queue_empty(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index]))||\
+			(priv->ieee80211->queue_stop) ) {
+			RT_TRACE(COMP_FIRMWARE,"=====================================================> tx full!\n");
+			skb_queue_tail(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index], skb);
+		} else {
+			priv->ieee80211->softmac_hard_start_xmit(skb,dev);
+		}
+
+		code_virtual_address += frag_length;
+		frag_offset += frag_length;
+
+	}while(frag_offset < buffer_len);
+
+	return rt_status;
+
+#if 0
+cmdsend_downloadcode_fail:
+	rt_status = false;
+	RT_TRACE(COMP_ERR, "CmdSendDownloadCode fail !!\n");
+	return rt_status;
+#endif
+}
+
+bool
+fwSendNullPacket(
+	struct net_device *dev,
+	u32			Length
+)
+{
+	bool	rtStatus = true;
+	struct r8192_priv   *priv = ieee80211_priv(dev);
+	struct sk_buff	    *skb;
+	cb_desc		    *tcb_desc;
+	unsigned char	    *ptr_buf;
+	bool	bLastInitPacket = false;
+
+	//PlatformAcquireSpinLock(Adapter, RT_TX_SPINLOCK);
+
+	//Get TCB and local buffer from common pool. (It is shared by CmdQ, MgntQ, and USB coalesce DataQ)
+	skb  = dev_alloc_skb(Length+ 4);
+	memcpy((unsigned char *)(skb->cb),&dev,sizeof(dev));
+	tcb_desc = (cb_desc*)(skb->cb + MAX_DEV_ADDR_SIZE);
+	tcb_desc->queue_index = TXCMD_QUEUE;
+	tcb_desc->bCmdOrInit = DESC_PACKET_TYPE_INIT;
+	tcb_desc->bLastIniPkt = bLastInitPacket;
+	ptr_buf = skb_put(skb, Length);
+	memset(ptr_buf,0,Length);
+	tcb_desc->txbuf_size= (u16)Length;
+
+	if(!priv->ieee80211->check_nic_enough_desc(dev,tcb_desc->queue_index)||
+			(!skb_queue_empty(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index]))||\
+			(priv->ieee80211->queue_stop) ) {
+			RT_TRACE(COMP_FIRMWARE,"===================NULL packet==================================> tx full!\n");
+			skb_queue_tail(&priv->ieee80211->skb_waitQ[tcb_desc->queue_index], skb);
+		} else {
+			priv->ieee80211->softmac_hard_start_xmit(skb,dev);
+		}
+
+	//PlatformReleaseSpinLock(Adapter, RT_TX_SPINLOCK);
+	return rtStatus;
+}
+
+#if 0
+/*
+ * Procedure  :   Download code into IMEM or DMEM
+ * Description:   This routine will intialize firmware. If any error occurs during the initialization
+ *				process, the routine shall terminate immediately and return fail.
+ *				The routine copy virtual address get from opening of file into shared memory
+ *				allocated during initialization. If code size larger than a conitneous shared
+ *				memory may contain, the code should be divided into several section.
+ *				!!!NOTES This finction should only be called during MPInitialization because
+ *				A NIC driver should call NdisOpenFile only from MiniportInitialize.
+ * Arguments :    The pointer of the adapter
+ *			   Code address (Virtual address, should fill descriptor with physical address)
+ *			   Code size
+ * Returns  :
+ *        RT_STATUS_FAILURE - the following initialization process should be terminated
+ *        RT_STATUS_SUCCESS - if firmware initialization process success
+ */
+bool fwsend_download_code(struct net_device *dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	rt_firmware		*pfirmware = (rt_firmware*)(&priv->firmware);
+
+	bool			rt_status = true;
+	u16			length = 0;
+	u16			offset = 0;
+	u16			frag_threhold;
+	bool			last_init_packet = false;
+	u32			check_txcmdwait_queueemptytime = 100000;
+	u16			cmd_buf_len;
+	u8			*ptr_cmd_buf;
+
+	/* reset to 0 for first segment of img download */
+	pfirmware->firmware_seg_index = 1;
+
+	if(pfirmware->firmware_seg_index == pfirmware->firmware_seg_maxnum) {
+		last_init_packet = 1;
+	}
+
+	cmd_buf_len = pfirmware->firmware_seg_container[pfirmware->firmware_seg_index-1].seg_size;
+	ptr_cmd_buf = pfirmware->firmware_seg_container[pfirmware->firmware_seg_index-1].seg_ptr;
+	rtl819xU_tx_cmd(dev, ptr_cmd_buf, cmd_buf_len, last_init_packet, DESC_PACKET_TYPE_INIT);
+
+	rt_status = true;
+	return rt_status;
+}
+#endif
+
+//-----------------------------------------------------------------------------
+// Procedure:    Check whether main code is download OK. If OK, turn on CPU
+//
+// Description:   CPU register locates in different page against general register.
+//			    Switch to CPU register in the begin and switch back before return
+//
+//
+// Arguments:   The pointer of the adapter
+//
+// Returns:
+//        NDIS_STATUS_FAILURE - the following initialization process should be terminated
+//        NDIS_STATUS_SUCCESS - if firmware initialization process success
+//-----------------------------------------------------------------------------
+bool CPUcheck_maincodeok_turnonCPU(struct net_device *dev)
+{
+	struct r8192_priv  *priv = ieee80211_priv(dev);
+	bool rt_status = true;
+	int  check_putcodeOK_time = 200000, check_bootOk_time = 200000;
+	u32  CPU_status = 0;
+
+	/* Check whether put code OK */
+	do {
+		CPU_status = read_nic_dword(dev, CPU_GEN);
+
+		if((CPU_status&CPU_GEN_PUT_CODE_OK) || (priv->usb_error==true))
+			break;
+
+	}while(check_putcodeOK_time--);
+
+	if(!(CPU_status&CPU_GEN_PUT_CODE_OK)) {
+		RT_TRACE(COMP_ERR, "Download Firmware: Put code fail!\n");
+		goto CPUCheckMainCodeOKAndTurnOnCPU_Fail;
+	} else {
+		RT_TRACE(COMP_FIRMWARE, "Download Firmware: Put code ok!\n");
+	}
+
+	/* Turn On CPU */
+	CPU_status = read_nic_dword(dev, CPU_GEN);
+	write_nic_byte(dev, CPU_GEN, (u8)((CPU_status|CPU_GEN_PWR_STB_CPU)&0xff));
+	mdelay(1000);
+
+	/* Check whether CPU boot OK */
+	do {
+		CPU_status = read_nic_dword(dev, CPU_GEN);
+
+		if((CPU_status&CPU_GEN_BOOT_RDY)||(priv->usb_error == true))
+			break;
+	}while(check_bootOk_time--);
+
+	if(!(CPU_status&CPU_GEN_BOOT_RDY)) {
+		goto CPUCheckMainCodeOKAndTurnOnCPU_Fail;
+	} else {
+		RT_TRACE(COMP_FIRMWARE, "Download Firmware: Boot ready!\n");
+	}
+
+	return rt_status;
+
+CPUCheckMainCodeOKAndTurnOnCPU_Fail:
+	RT_TRACE(COMP_ERR, "ERR in %s()\n", __FUNCTION__);
+	rt_status = FALSE;
+	return rt_status;
+}
+
+bool CPUcheck_firmware_ready(struct net_device *dev)
+{
+	struct r8192_priv  *priv = ieee80211_priv(dev);
+	bool		rt_status = true;
+	int		check_time = 200000;
+	u32		CPU_status = 0;
+
+	/* Check Firmware Ready */
+	do {
+		CPU_status = read_nic_dword(dev, CPU_GEN);
+
+		if((CPU_status&CPU_GEN_FIRM_RDY)||(priv->usb_error == true))
+			break;
+
+	}while(check_time--);
+
+	if(!(CPU_status&CPU_GEN_FIRM_RDY))
+		goto CPUCheckFirmwareReady_Fail;
+	else
+		RT_TRACE(COMP_FIRMWARE, "Download Firmware: Firmware ready!\n");
+
+	return rt_status;
+
+CPUCheckFirmwareReady_Fail:
+	RT_TRACE(COMP_ERR, "ERR in %s()\n", __FUNCTION__);
+	rt_status = false;
+	return rt_status;
+
+}
+
+bool init_firmware(struct net_device *dev)
+{
+	struct r8192_priv 	*priv = ieee80211_priv(dev);
+	bool			rt_status = TRUE;
+
+	u8			*firmware_img_buf[3] = { &rtl8190_fwboot_array[0],
+						   	 &rtl8190_fwmain_array[0],
+						   	 &rtl8190_fwdata_array[0]};
+
+	u32			firmware_img_len[3] = { sizeof(rtl8190_fwboot_array),
+						   	sizeof(rtl8190_fwmain_array),
+						   	sizeof(rtl8190_fwdata_array)};
+	u32			file_length = 0;
+	u8			*mapped_file = NULL;
+	u32			init_step = 0;
+	opt_rst_type_e	rst_opt = OPT_SYSTEM_RESET;
+	firmware_init_step_e 	starting_state = FW_INIT_STEP0_BOOT;
+
+	rt_firmware		*pfirmware = priv->pFirmware;
+	const struct firmware 	*fw_entry;
+	const char *fw_name[3] = { "RTL8192U/boot.img",
+                           "RTL8192U/main.img",
+			   "RTL8192U/data.img"};
+	int rc;
+
+	RT_TRACE(COMP_FIRMWARE, " PlatformInitFirmware()==>\n");
+
+	if (pfirmware->firmware_status == FW_STATUS_0_INIT ) {
+		/* it is called by reset */
+		rst_opt = OPT_SYSTEM_RESET;
+		starting_state = FW_INIT_STEP0_BOOT;
+		// TODO: system reset
+
+	}else if(pfirmware->firmware_status == FW_STATUS_5_READY) {
+		/* it is called by Initialize */
+		rst_opt = OPT_FIRMWARE_RESET;
+		starting_state = FW_INIT_STEP2_DATA;
+	}else {
+		 RT_TRACE(COMP_FIRMWARE, "PlatformInitFirmware: undefined firmware state\n");
+	}
+
+	/*
+	 * Download boot, main, and data image for System reset.
+	 * Download data image for firmware reseta
+	 */
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+	priv->firmware_source = FW_SOURCE_HEADER_FILE;
+#else
+	priv->firmware_source = FW_SOURCE_IMG_FILE;
+#endif
+	for(init_step = starting_state; init_step <= FW_INIT_STEP2_DATA; init_step++) {
+		/*
+		 * Open Image file, and map file to contineous memory if open file success.
+		 * or read image file from array. Default load from IMG file
+		 */
+		if(rst_opt == OPT_SYSTEM_RESET) {
+			switch(priv->firmware_source) {
+				case FW_SOURCE_IMG_FILE:
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+					if(pfirmware->firmware_buf_size[init_step] == 0) {
+						rc = request_firmware(&fw_entry, fw_name[init_step],&priv->udev->dev);
+						if(rc < 0 ) {
+							RT_TRACE(COMP_ERR, "request firmware fail!\n");
+							goto download_firmware_fail;
+						}
+
+						if(fw_entry->size > sizeof(pfirmware->firmware_buf[init_step])) {
+							//RT_TRACE(COMP_ERR, "img file size exceed the container buffer fail!\n");
+							 RT_TRACE(COMP_FIRMWARE, "img file size exceed the container buffer fail!, entry_size = %d, buf_size = %d\n",fw_entry->size,sizeof(pfirmware->firmware_buf[init_step]));
+
+							goto download_firmware_fail;
+						}
+
+						if(init_step != FW_INIT_STEP1_MAIN) {
+							memcpy(pfirmware->firmware_buf[init_step],fw_entry->data,fw_entry->size);
+							pfirmware->firmware_buf_size[init_step] = fw_entry->size;
+						} else {
+#ifdef RTL8190P
+							memcpy(pfirmware->firmware_buf[init_step],fw_entry->data,fw_entry->size);
+							pfirmware->firmware_buf_size[init_step] = fw_entry->size;
+#else
+							memset(pfirmware->firmware_buf[init_step],0,128);
+							memcpy(&pfirmware->firmware_buf[init_step][128],fw_entry->data,fw_entry->size);
+							mapped_file = pfirmware->firmware_buf[init_step];
+							pfirmware->firmware_buf_size[init_step] = fw_entry->size+128;
+#endif
+						}
+						//pfirmware->firmware_buf_size = file_length;
+
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)
+						if(rst_opt == OPT_SYSTEM_RESET) {
+							release_firmware(fw_entry);
+						}
+#endif
+					}
+					mapped_file = pfirmware->firmware_buf[init_step];
+					file_length = pfirmware->firmware_buf_size[init_step];
+#endif
+
+					break;
+
+				case FW_SOURCE_HEADER_FILE:
+					mapped_file =  firmware_img_buf[init_step];
+					file_length  = firmware_img_len[init_step];
+					if(init_step == FW_INIT_STEP2_DATA) {
+						memcpy(pfirmware->firmware_buf[init_step], mapped_file, file_length);
+						pfirmware->firmware_buf_size[init_step] = file_length;
+					}
+					break;
+
+				default:
+					break;
+			}
+
+
+		}else if(rst_opt == OPT_FIRMWARE_RESET ) {
+			/* we only need to download data.img here */
+			mapped_file = pfirmware->firmware_buf[init_step];
+			file_length = pfirmware->firmware_buf_size[init_step];
+		}
+
+		/* Download image file */
+		/* The firmware download process is just as following,
+		 * 1. that is each packet will be segmented and inserted to the wait queue.
+		 * 2. each packet segment will be put in the skb_buff packet.
+		 * 3. each skb_buff packet data content will already include the firmware info
+		 *   and Tx descriptor info
+		 * */
+		rt_status = fw_download_code(dev,mapped_file,file_length);
+
+		if(rt_status != TRUE) {
+			goto download_firmware_fail;
+		}
+
+		switch(init_step) {
+			case FW_INIT_STEP0_BOOT:
+				/* Download boot
+				 * initialize command descriptor.
+				 * will set polling bit when firmware code is also configured
+				 */
+				pfirmware->firmware_status = FW_STATUS_1_MOVE_BOOT_CODE;
+#ifdef RTL8190P
+				// To initialize IMEM, CPU move code  from 0x80000080, hence, we send 0x80 byte packet
+				rt_status = fwSendNullPacket(dev, RTL8190_CPU_START_OFFSET);
+				if(rt_status != true)
+				{
+					RT_TRACE(COMP_INIT, "fwSendNullPacket() fail ! \n");
+					goto  download_firmware_fail;
+				}
+#endif
+				//mdelay(1000);
+				/*
+				 * To initialize IMEM, CPU move code  from 0x80000080,
+				 * hence, we send 0x80 byte packet
+				 */
+				break;
+
+			case FW_INIT_STEP1_MAIN:
+				/* Download firmware code. Wait until Boot Ready and Turn on CPU */
+				pfirmware->firmware_status = FW_STATUS_2_MOVE_MAIN_CODE;
+
+				/* Check Put Code OK and Turn On CPU */
+				rt_status = CPUcheck_maincodeok_turnonCPU(dev);
+				if(rt_status != TRUE) {
+					RT_TRACE(COMP_ERR, "CPUcheck_maincodeok_turnonCPU fail!\n");
+					goto download_firmware_fail;
+				}
+
+				pfirmware->firmware_status = FW_STATUS_3_TURNON_CPU;
+				break;
+
+			case FW_INIT_STEP2_DATA:
+				/* download initial data code */
+				pfirmware->firmware_status = FW_STATUS_4_MOVE_DATA_CODE;
+				mdelay(1);
+
+				rt_status = CPUcheck_firmware_ready(dev);
+				if(rt_status != TRUE) {
+					RT_TRACE(COMP_ERR, "CPUcheck_firmware_ready fail(%d)!\n",rt_status);
+					goto download_firmware_fail;
+				}
+
+				/* wait until data code is initialized ready.*/
+				pfirmware->firmware_status = FW_STATUS_5_READY;
+				break;
+		}
+	}
+
+	RT_TRACE(COMP_FIRMWARE, "Firmware Download Success\n");
+	//assert(pfirmware->firmware_status == FW_STATUS_5_READY, ("Firmware Download Fail\n"));
+
+	return rt_status;
+
+download_firmware_fail:
+	RT_TRACE(COMP_ERR, "ERR in %s()\n", __FUNCTION__);
+	rt_status = FALSE;
+	return rt_status;
+
+}
+
+#if 0
+/*
+ * Procedure:   (1)  Transform firmware code from little endian to big endian if required.
+ *	        (2)  Number of bytes in Firmware downloading should be multiple
+ *	   	     of 4 bytes. If length is not multiple of 4 bytes, appending of zeros is required
+ *
+ */
+void CmdAppendZeroAndEndianTransform(
+	u1Byte	*pDst,
+	u1Byte	*pSrc,
+	u2Byte   	*pLength)
+{
+
+	u2Byte	ulAppendBytes = 0, i;
+	u2Byte	ulLength = *pLength;
+
+//test only
+	//memset(pDst, 0xcc, 12);
+
+
+	/* Transform from little endian to big endian */
+//#if DEV_BUS_TYPE==PCI_INTERFACE
+#if 0
+	for( i=0 ; i<(*pLength) ; i+=4)
+	{
+		if((i+3) < (*pLength))	pDst[i+0] = pSrc[i+3];
+		if((i+2) < (*pLength))	pDst[i+1] = pSrc[i+2];
+		if((i+1) < (*pLength))	pDst[i+2] = pSrc[i+1];
+		if((i+0) < (*pLength))	pDst[i+3] = pSrc[i+0];
+	}
+#else
+	pDst += USB_HWDESC_HEADER_LEN;
+	ulLength -= USB_HWDESC_HEADER_LEN;
+
+	for( i=0 ; i<ulLength ; i+=4) {
+		if((i+3) < ulLength)	pDst[i+0] = pSrc[i+3];
+		if((i+2) < ulLength)	pDst[i+1] = pSrc[i+2];
+		if((i+1) < ulLength)	pDst[i+2] = pSrc[i+1];
+		if((i+0) < ulLength)	pDst[i+3] = pSrc[i+0];
+
+	}
+#endif
+
+	//1(2) Append Zero
+	if(  ((*pLength) % 4)  >0)
+	{
+		ulAppendBytes = 4-((*pLength) % 4);
+
+		for(i=0 ; i<ulAppendBytes; i++)
+			pDst[  4*((*pLength)/4)  + i ] = 0x0;
+
+		*pLength += ulAppendBytes;
+	}
+}
+#endif
+
+#if 0
+RT_STATUS
+CmdSendPacket(
+	PADAPTER				Adapter,
+	PRT_TCB					pTcb,
+	PRT_TX_LOCAL_BUFFER 			pBuf,
+	u4Byte					BufferLen,
+	u4Byte					PacketType,
+	BOOLEAN					bLastInitPacket
+	)
+{
+	s2Byte		i;
+	u1Byte		QueueID;
+	u2Byte		firstDesc,curDesc = 0;
+	u2Byte		FragIndex=0, FragBufferIndex=0;
+
+	RT_STATUS	rtStatus = RT_STATUS_SUCCESS;
+
+	CmdInitTCB(Adapter, pTcb, pBuf, BufferLen);
+
+
+	if(CmdCheckFragment(Adapter, pTcb, pBuf))
+		CmdFragmentTCB(Adapter, pTcb);
+	else
+		pTcb->FragLength[0] = (u2Byte)pTcb->BufferList[0].Length;
+
+	QueueID=pTcb->SpecifiedQueueID;
+#if DEV_BUS_TYPE!=USB_INTERFACE
+	firstDesc=curDesc=Adapter->NextTxDescToFill[QueueID];
+#endif
+
+#if DEV_BUS_TYPE!=USB_INTERFACE
+	if(VacancyTxDescNum(Adapter, QueueID) > pTcb->BufferCount)
+#else
+	if(PlatformIsTxQueueAvailable(Adapter, QueueID, pTcb->BufferCount) &&
+		RTIsListEmpty(&Adapter->TcbWaitQueue[QueueID]))
+#endif
+	{
+		pTcb->nDescUsed=0;
+
+		for(i=0 ; i<pTcb->BufferCount ; i++)
+		{
+			Adapter->HalFunc.TxFillCmdDescHandler(
+				Adapter,
+				pTcb,
+				QueueID,							//QueueIndex
+				curDesc,							//index
+				FragBufferIndex==0,						//bFirstSeg
+				FragBufferIndex==(pTcb->FragBufCount[FragIndex]-1),		//bLastSeg
+				pTcb->BufferList[i].VirtualAddress,				//VirtualAddress
+				pTcb->BufferList[i].PhysicalAddressLow,				//PhyAddressLow
+				pTcb->BufferList[i].Length,					//BufferLen
+				i!=0,								//bSetOwnBit
+				(i==(pTcb->BufferCount-1)) && bLastInitPacket,			//bLastInitPacket
+				PacketType,							//DescPacketType
+				pTcb->FragLength[FragIndex]					//PktLen
+				);
+
+			if(FragBufferIndex==(pTcb->FragBufCount[FragIndex]-1))
+			{ // Last segment of the fragment.
+				pTcb->nFragSent++;
+			}
+
+			FragBufferIndex++;
+			if(FragBufferIndex==pTcb->FragBufCount[FragIndex])
+			{
+				FragIndex++;
+				FragBufferIndex=0;
+			}
+
+#if DEV_BUS_TYPE!=USB_INTERFACE
+			curDesc=(curDesc+1)%Adapter->NumTxDesc[QueueID];
+#endif
+			pTcb->nDescUsed++;
+		}
+
+#if DEV_BUS_TYPE!=USB_INTERFACE
+		RTInsertTailList(&Adapter->TcbBusyQueue[QueueID], &pTcb->List);
+		IncrementTxDescToFill(Adapter, QueueID, pTcb->nDescUsed);
+		Adapter->HalFunc.SetTxDescOWNHandler(Adapter, QueueID, firstDesc);
+		// TODO: should call poll use QueueID
+		Adapter->HalFunc.TxPollingHandler(Adapter, TXCMD_QUEUE);
+#endif
+	}
+	else
+#if DEV_BUS_TYPE!=USB_INTERFACE
+		goto CmdSendPacket_Fail;
+#else
+	{
+		pTcb->bLastInitPacket = bLastInitPacket;
+		RTInsertTailList(&Adapter->TcbWaitQueue[pTcb->SpecifiedQueueID], &pTcb->List);
+	}
+#endif
+
+	return rtStatus;
+
+#if DEV_BUS_TYPE!=USB_INTERFACE
+CmdSendPacket_Fail:
+	rtStatus = RT_STATUS_FAILURE;
+	return rtStatus;
+#endif
+
+}
+#endif
+
+
+
+
+#if 0
+RT_STATUS
+FWSendNullPacket(
+	IN	PADAPTER		Adapter,
+	IN	u4Byte			Length
+)
+{
+	RT_STATUS	rtStatus = RT_STATUS_SUCCESS;
+
+
+	PRT_TCB					pTcb;
+	PRT_TX_LOCAL_BUFFER 	pBuf;
+	BOOLEAN					bLastInitPacket = FALSE;
+
+	PlatformAcquireSpinLock(Adapter, RT_TX_SPINLOCK);
+
+#if DEV_BUS_TYPE==USB_INTERFACE
+	Length += USB_HWDESC_HEADER_LEN;
+#endif
+
+	//Get TCB and local buffer from common pool. (It is shared by CmdQ, MgntQ, and USB coalesce DataQ)
+	if(MgntGetBuffer(Adapter, &pTcb, &pBuf))
+	{
+		PlatformZeroMemory(pBuf->Buffer.VirtualAddress, Length);
+		rtStatus = CmdSendPacket(Adapter, pTcb, pBuf, Length, DESC_PACKET_TYPE_INIT, bLastInitPacket);	//0 : always set LastInitPacket to zero
+//#if HAL_CODE_BASE != RTL8190HW
+//		// TODO: for test only
+//		ReturnTCB(Adapter, pTcb, RT_STATUS_SUCCESS);
+//#endif
+		if(rtStatus == RT_STATUS_FAILURE)
+			goto CmdSendNullPacket_Fail;
+	}else
+		goto CmdSendNullPacket_Fail;
+
+	PlatformReleaseSpinLock(Adapter, RT_TX_SPINLOCK);
+	return rtStatus;
+
+
+CmdSendNullPacket_Fail:
+	PlatformReleaseSpinLock(Adapter, RT_TX_SPINLOCK);
+	rtStatus = RT_STATUS_FAILURE;
+	RT_ASSERT(rtStatus == RT_STATUS_SUCCESS, ("CmdSendDownloadCode fail !!\n"));
+	return rtStatus;
+}
+#endif
+
+
diff --git a/drivers/staging/rtl8192su/r819xU_firmware.h b/drivers/staging/rtl8192su/r819xU_firmware.h
new file mode 100644
index 0000000..10801be
--- /dev/null
+++ b/drivers/staging/rtl8192su/r819xU_firmware.h
@@ -0,0 +1,106 @@
+#ifndef __INC_FIRMWARE_H
+#define __INC_FIRMWARE_H
+
+#define RTL8190_CPU_START_OFFSET	0x80
+/* TODO: this definition is TBD */
+//#define USB_HWDESC_HEADER_LEN	0
+
+/* It should be double word alignment */
+//#if DEV_BUS_TYPE==PCI_INTERFACE
+//#define GET_COMMAND_PACKET_FRAG_THRESHOLD(v)	4*(v/4) - 8
+//#else
+#define GET_COMMAND_PACKET_FRAG_THRESHOLD(v)	(4*(v/4) - 8 - USB_HWDESC_HEADER_LEN)
+//#endif
+
+typedef enum _firmware_init_step{
+	FW_INIT_STEP0_BOOT = 0,
+	FW_INIT_STEP1_MAIN = 1,
+	FW_INIT_STEP2_DATA = 2,
+}firmware_init_step_e;
+
+typedef enum _opt_rst_type{
+	OPT_SYSTEM_RESET = 0,
+	OPT_FIRMWARE_RESET = 1,
+}opt_rst_type_e;
+
+/* due to rtl8192 firmware */
+typedef enum _desc_packet_type_e{
+	DESC_PACKET_TYPE_INIT = 0,
+	DESC_PACKET_TYPE_NORMAL = 1,
+}desc_packet_type_e;
+
+typedef enum _firmware_source{
+	FW_SOURCE_IMG_FILE = 0,
+	FW_SOURCE_HEADER_FILE = 1,              //from header file
+}firmware_source_e, *pfirmware_source_e;
+
+typedef enum _firmware_status{
+	FW_STATUS_0_INIT = 0,
+	FW_STATUS_1_MOVE_BOOT_CODE = 1,
+	FW_STATUS_2_MOVE_MAIN_CODE = 2,
+	FW_STATUS_3_TURNON_CPU = 3,
+	FW_STATUS_4_MOVE_DATA_CODE = 4,
+	FW_STATUS_5_READY = 5,
+}firmware_status_e;
+
+typedef struct _rt_firmare_seg_container {
+	u16     seg_size;
+	u8      *seg_ptr;
+}fw_seg_container, *pfw_seg_container;
+
+#define RTL8190_MAX_FIRMWARE_CODE_SIZE  64000   //64k
+#define MAX_FW_INIT_STEP                3
+typedef struct _rt_firmware{
+	firmware_status_e firmware_status;
+	u16               cmdpacket_frag_thresold;
+	u8                firmware_buf[MAX_FW_INIT_STEP][RTL8190_MAX_FIRMWARE_CODE_SIZE];
+	u16               firmware_buf_size[MAX_FW_INIT_STEP];
+}rt_firmware, *prt_firmware;
+
+typedef struct _rt_firmware_info_819xUsb{
+	u8		sz_info[16];
+}rt_firmware_info_819xUsb, *prt_firmware_info_819xUsb;
+
+#if 0
+/* CPU related */
+RT_STATUS
+CPUCheckMainCodeOKAndTurnOnCPU(
+	IN	PADAPTER			Adapter
+	);
+
+RT_STATUS
+CPUCheckFirmwareReady(
+	IN	PADAPTER			Adapter
+	);
+
+/* Firmware related */
+VOID
+FWInitializeParameters(
+	IN	PADAPTER		Adapter
+	);
+
+RT_STATUS
+FWSendDownloadCode(
+	IN	PADAPTER		Adapter,
+	IN	pu1Byte			CodeVirtualAddrress,
+	IN	u4Byte			BufferLen
+	);
+
+RT_STATUS
+FWSendNullPacket(
+	IN	PADAPTER		Adapter,
+	IN	u4Byte			Length
+	);
+
+RT_STATUS
+CmdSendPacket(
+	PADAPTER				Adapter,
+	PRT_TCB					pTcb,
+	PRT_TX_LOCAL_BUFFER 	pBuf,
+	u4Byte					BufferLen,
+	u4Byte					PacketType,
+	BOOLEAN					bLastInitPacket
+	);
+#endif
+#endif
+
diff --git a/drivers/staging/rtl8192su/r819xU_firmware_img.c b/drivers/staging/rtl8192su/r819xU_firmware_img.c
new file mode 100644
index 0000000..29b656d
--- /dev/null
+++ b/drivers/staging/rtl8192su/r819xU_firmware_img.c
@@ -0,0 +1,3447 @@
+/*Created on  2008/ 7/16,  5:31*/
+#include <linux/types.h>
+
+u8 rtl8190_fwboot_array[] = {
+0x10,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x3c,0x08,0xbf,0xc0,0x25,0x08,0x00,0x08,
+0x3c,0x09,0xb0,0x03,0xad,0x28,0x00,0x20,0x40,0x80,0x68,0x00,0x00,0x00,0x00,0x00,
+0x3c,0x0a,0xd0,0x00,0x40,0x8a,0x60,0x00,0x00,0x00,0x00,0x00,0x3c,0x08,0x80,0x01,
+0x25,0x08,0xb0,0x50,0x24,0x09,0x00,0x01,0x3c,0x01,0x7f,0xff,0x34,0x21,0xff,0xff,
+0x01,0x01,0x50,0x24,0x00,0x09,0x48,0x40,0x35,0x29,0x00,0x01,0x01,0x2a,0x10,0x2b,
+0x14,0x40,0xff,0xfc,0x00,0x00,0x00,0x00,0x3c,0x0a,0x00,0x00,0x25,0x4a,0x00,0x00,
+0x4c,0x8a,0x00,0x00,0x4c,0x89,0x08,0x00,0x00,0x00,0x00,0x00,0x3c,0x08,0x80,0x01,
+0x25,0x08,0xb0,0x50,0x3c,0x01,0x80,0x00,0x01,0x21,0x48,0x25,0x3c,0x0a,0xbf,0xc0,
+0x25,0x4a,0x00,0x7c,0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,0xad,0x00,0x00,0x00,
+0x21,0x08,0x00,0x04,0x01,0x09,0x10,0x2b,0x14,0x40,0xff,0xf8,0x00,0x00,0x00,0x00,
+0x3c,0x08,0x80,0x01,0x25,0x08,0x7f,0xff,0x24,0x09,0x00,0x01,0x3c,0x01,0x7f,0xff,
+0x34,0x21,0xff,0xff,0x01,0x01,0x50,0x24,0x00,0x09,0x48,0x40,0x35,0x29,0x00,0x01,
+0x01,0x2a,0x10,0x2b,0x14,0x40,0xff,0xfc,0x00,0x00,0x00,0x00,0x3c,0x0a,0x80,0x01,
+0x25,0x4a,0x00,0x00,0x3c,0x01,0x7f,0xff,0x34,0x21,0xff,0xff,0x01,0x41,0x50,0x24,
+0x3c,0x09,0x00,0x01,0x35,0x29,0x7f,0xff,0x4c,0x8a,0x20,0x00,0x4c,0x89,0x28,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0x08,0x04,0x10,
+0x00,0x00,0x00,0x00,0x40,0x88,0xa0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x3c,0x08,0xbf,0xc0,0x00,0x00,0x00,0x00,0x8d,0x09,0x00,0x00,0x00,0x00,0x00,0x00,
+0x3c,0x0a,0xbf,0xc0,0x25,0x4a,0x01,0x20,0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,
+0x3c,0x08,0xb0,0x03,0x8d,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x35,0x29,0x00,0x10,
+0xad,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x3c,0x08,0x80,0x00,0x25,0x08,0x4b,0x84,
+0x01,0x00,0x00,0x08,0x00,0x00,0x00,0x00,};
+
+u8 rtl8190_fwmain_array[] = {
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+0x40,0x04,0x68,0x00,0x40,0x05,0x70,0x00,0x40,0x06,0x40,0x00,0x0c,0x00,0x12,0x94,
+0x00,0x00,0x00,0x00,0x40,0x1a,0x68,0x00,0x33,0x5b,0x00,0x3c,0x17,0x60,0x00,0x09,
+0x00,0x00,0x00,0x00,0x40,0x1b,0x60,0x00,0x00,0x00,0x00,0x00,0x03,0x5b,0xd0,0x24,
+0x40,0x1a,0x70,0x00,0x03,0x40,0x00,0x08,0x42,0x00,0x00,0x10,0x00,0x00,0x00,0x00,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xff,0xff,0x34,0x42,0xff,0xff,0x8c,0x43,0x00,0x00,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x00,0xd0,
+0xac,0x62,0x00,0x00,0x00,0x00,0x20,0x21,0x27,0x85,0x8b,0x60,0x00,0x85,0x18,0x21,
+0x24,0x84,0x00,0x01,0x28,0x82,0x00,0x0a,0x14,0x40,0xff,0xfc,0xa0,0x60,0x00,0x00,
+0x27,0x82,0x8b,0x6a,0x24,0x04,0x00,0x06,0x24,0x84,0xff,0xff,0xa4,0x40,0x00,0x00,
+0x04,0x81,0xff,0xfd,0x24,0x42,0x00,0x02,0x24,0x02,0x00,0x03,0xa3,0x82,0x8b,0x60,
+0x24,0x02,0x09,0xc4,0x24,0x03,0x01,0x00,0xa7,0x82,0x8b,0x76,0x24,0x02,0x04,0x00,
+0xaf,0x83,0x8b,0x78,0xaf,0x82,0x8b,0x7c,0x24,0x03,0x00,0x0a,0x24,0x02,0x00,0x04,
+0x24,0x05,0x00,0x02,0x24,0x04,0x00,0x01,0xa3,0x83,0x8b,0x62,0xa3,0x82,0x8b,0x68,
+0x24,0x03,0x00,0x01,0x24,0x02,0x02,0x00,0xa3,0x84,0x8b,0x66,0xa3,0x85,0x8b,0x69,
+0xa7,0x82,0x8b,0x6a,0xa7,0x83,0x8b,0x6c,0xa3,0x84,0x8b,0x61,0xa3,0x80,0x8b,0x63,
+0xa3,0x80,0x8b,0x64,0xa3,0x80,0x8b,0x65,0xa3,0x85,0x8b,0x67,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x24,0x42,0x01,0x84,
+0x34,0x63,0x00,0x20,0xac,0x62,0x00,0x00,0x27,0x84,0x8b,0x88,0x00,0x00,0x10,0x21,
+0x24,0x42,0x00,0x01,0x00,0x02,0x16,0x00,0x00,0x02,0x16,0x03,0x28,0x43,0x00,0x03,
+0xac,0x80,0xff,0xfc,0xa0,0x80,0x00,0x00,0x14,0x60,0xff,0xf9,0x24,0x84,0x00,0x0c,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x34,0x63,0x00,0x20,0x24,0x42,0x01,0xc8,0x3c,0x08,0xb0,0x03,0xac,0x62,0x00,0x00,
+0x35,0x08,0x00,0x70,0x8d,0x02,0x00,0x00,0x00,0xa0,0x48,0x21,0x00,0x04,0x26,0x00,
+0x00,0x02,0x2a,0x43,0x00,0x06,0x36,0x00,0x00,0x07,0x3e,0x00,0x00,0x02,0x12,0x03,
+0x29,0x23,0x00,0x03,0x00,0x04,0x56,0x03,0x00,0x06,0x36,0x03,0x00,0x07,0x3e,0x03,
+0x30,0x48,0x00,0x01,0x10,0x60,0x00,0x11,0x30,0xa5,0x00,0x07,0x24,0x02,0x00,0x02,
+0x00,0x49,0x10,0x23,0x00,0x45,0x10,0x07,0x30,0x42,0x00,0x01,0x10,0x40,0x00,0x66,
+0x00,0x00,0x00,0x00,0x8f,0xa2,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x02,0x21,0x43,
+0x11,0x00,0x00,0x10,0x00,0x07,0x20,0x0b,0x15,0x20,0x00,0x06,0x24,0x02,0x00,0x01,
+0x3c,0x02,0xb0,0x05,0x34,0x42,0x01,0x20,0xa4,0x44,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x11,0x22,0x00,0x04,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x05,
+0x08,0x00,0x00,0x96,0x34,0x42,0x01,0x24,0x3c,0x02,0xb0,0x05,0x08,0x00,0x00,0x96,
+0x34,0x42,0x01,0x22,0x15,0x20,0x00,0x54,0x24,0x02,0x00,0x01,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x00,0x74,0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0xaf,0x83,0x8b,0x84,
+0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0x70,0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x6b,0x00,0x08,0x11,0x60,0x00,0x18,0x00,0x09,0x28,0x40,0x00,0x00,0x40,0x21,
+0x27,0x85,0x8b,0x80,0x8c,0xa3,0x00,0x00,0x8c,0xa2,0x00,0x04,0x00,0x00,0x00,0x00,
+0x00,0x62,0x38,0x23,0x00,0x43,0x10,0x2a,0x10,0x40,0x00,0x3d,0x00,0x00,0x00,0x00,
+0xac,0xa7,0x00,0x00,0x25,0x02,0x00,0x01,0x00,0x02,0x16,0x00,0x00,0x02,0x46,0x03,
+0x29,0x03,0x00,0x03,0x14,0x60,0xff,0xf3,0x24,0xa5,0x00,0x0c,0x3c,0x03,0xb0,0x03,
+0x34,0x63,0x00,0x70,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4b,0x10,0x23,
+0xa0,0x62,0x00,0x00,0x00,0x09,0x28,0x40,0x00,0xa9,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x8b,0x88,0x00,0x0a,0x20,0x0b,0x00,0x43,0x18,0x21,0x10,0xc0,0x00,0x05,
+0x00,0x00,0x38,0x21,0x80,0x62,0x00,0x01,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x05,
+0x00,0x00,0x00,0x00,0x80,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x03,
+0x00,0xa9,0x10,0x21,0x24,0x07,0x00,0x01,0x00,0xa9,0x10,0x21,0x00,0x02,0x30,0x80,
+0x27,0x82,0x8b,0x88,0xa0,0x67,0x00,0x01,0x00,0xc2,0x38,0x21,0x80,0xe3,0x00,0x01,
+0x00,0x00,0x00,0x00,0x10,0x60,0x00,0x07,0x00,0x00,0x00,0x00,0x27,0x83,0x8b,0x80,
+0x00,0xc3,0x18,0x21,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x44,0x10,0x21,
+0xac,0x62,0x00,0x00,0x27,0x85,0x8b,0x84,0x27,0x82,0x8b,0x80,0x00,0xc5,0x28,0x21,
+0x00,0xc2,0x10,0x21,0x8c,0x43,0x00,0x00,0x8c,0xa4,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x64,0x18,0x2a,0x14,0x60,0x00,0x03,0x24,0x02,0x00,0x01,0x03,0xe0,0x00,0x08,
+0xa0,0xe2,0x00,0x00,0xa0,0xe0,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x08,0x00,0x00,0xb9,0xac,0xa0,0x00,0x00,0x11,0x22,0x00,0x08,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0x7c,0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,
+0xaf,0x83,0x8b,0x9c,0x08,0x00,0x00,0xa9,0x3c,0x02,0xb0,0x03,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x00,0x78,0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0xaf,0x83,0x8b,0x90,
+0x08,0x00,0x00,0xa9,0x3c,0x02,0xb0,0x03,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x34,0x63,0x00,0x20,0x24,0x42,0x04,0x18,0x3c,0x05,0xb0,0x03,0xac,0x62,0x00,0x00,
+0x34,0xa5,0x00,0x70,0x8c,0xa2,0x00,0x00,0x90,0x84,0x00,0x08,0x3c,0x06,0xb0,0x03,
+0x00,0x02,0x16,0x00,0x2c,0x83,0x00,0x03,0x34,0xc6,0x00,0x72,0x24,0x07,0x00,0x01,
+0x10,0x60,0x00,0x11,0x00,0x02,0x2f,0xc2,0x90,0xc2,0x00,0x00,0x00,0x00,0x18,0x21,
+0x00,0x02,0x16,0x00,0x10,0xa7,0x00,0x09,0x00,0x02,0x16,0x03,0x14,0x80,0x00,0x0c,
+0x30,0x43,0x00,0x03,0x83,0x82,0x8b,0x88,0x00,0x00,0x00,0x00,0x00,0x02,0x10,0x80,
+0x00,0x43,0x10,0x21,0x00,0x02,0x16,0x00,0x00,0x02,0x1e,0x03,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x00,0x72,0xa0,0x43,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x30,0x45,0x00,0x05,0x10,0x87,0x00,0x04,0x30,0x43,0x00,0x06,0x93,0x82,0x8b,0xa0,
+0x08,0x00,0x01,0x21,0x00,0x43,0x10,0x21,0x83,0x82,0x8b,0x94,0x00,0x00,0x00,0x00,
+0x00,0x02,0x10,0x40,0x08,0x00,0x01,0x21,0x00,0x45,0x10,0x21,0x10,0x80,0x00,0x05,
+0x00,0x00,0x18,0x21,0x24,0x63,0x00,0x01,0x00,0x64,0x10,0x2b,0x14,0x40,0xff,0xfd,
+0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0x24,0x42,0x04,0xec,0x3c,0x04,0xb0,0x02,0x34,0x63,0x00,0x20,
+0xac,0x62,0x00,0x00,0x34,0x84,0x00,0x08,0x24,0x02,0x00,0x01,0xaf,0x84,0x8b,0xb0,
+0xa3,0x82,0x8b,0xc0,0xa7,0x80,0x8b,0xb4,0xa7,0x80,0x8b,0xb6,0xaf,0x80,0x8b,0xb8,
+0xaf,0x80,0x8b,0xbc,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x05,0x2c,0x3c,0x04,0xb0,0x03,
+0xac,0x62,0x00,0x00,0x34,0x84,0x00,0xac,0x80,0xa2,0x00,0x15,0x8c,0x83,0x00,0x00,
+0x27,0xbd,0xff,0xf0,0x00,0x43,0x10,0x21,0xac,0x82,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x10,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x00,0x34,0x42,0x00,0x20,
+0x24,0x63,0x05,0x64,0x27,0xbd,0xff,0xe0,0xac,0x43,0x00,0x00,0xaf,0xb1,0x00,0x14,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x18,0x8f,0x90,0x8b,0xb0,0x0c,0x00,0x02,0x9a,
+0x00,0x80,0x88,0x21,0x14,0x40,0x00,0x2a,0x3c,0x02,0x00,0x80,0x16,0x20,0x00,0x02,
+0x34,0x42,0x02,0x01,0x24,0x02,0x02,0x01,0xae,0x02,0x00,0x00,0x97,0x84,0x8b,0xb4,
+0x97,0x82,0x8b,0xb6,0x3c,0x03,0xb0,0x02,0x00,0x83,0x20,0x21,0x24,0x42,0x00,0x04,
+0xa7,0x82,0x8b,0xb6,0xa4,0x82,0x00,0x00,0x8f,0x84,0x8b,0xb8,0x8f,0x82,0x8b,0xb0,
+0x93,0x85,0x8b,0x62,0x24,0x84,0x00,0x01,0x24,0x42,0x00,0x04,0x24,0x03,0x8f,0xff,
+0x3c,0x07,0xb0,0x06,0x3c,0x06,0xb0,0x03,0x00,0x43,0x10,0x24,0x00,0x85,0x28,0x2a,
+0x34,0xe7,0x80,0x18,0xaf,0x82,0x8b,0xb0,0xaf,0x84,0x8b,0xb8,0x10,0xa0,0x00,0x08,
+0x34,0xc6,0x01,0x08,0x8f,0x83,0x8b,0xbc,0x8f,0x84,0x8b,0x7c,0x8c,0xc2,0x00,0x00,
+0x00,0x64,0x18,0x21,0x00,0x43,0x10,0x2b,0x14,0x40,0x00,0x09,0x00,0x00,0x00,0x00,
+0x8c,0xe2,0x00,0x00,0x3c,0x03,0x0f,0x00,0x3c,0x04,0x04,0x00,0x00,0x43,0x10,0x24,
+0x10,0x44,0x00,0x03,0x00,0x00,0x00,0x00,0x0c,0x00,0x04,0x98,0x00,0x00,0x00,0x00,
+0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,
+0x27,0xbd,0xff,0xd8,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x00,0x24,0x63,0x06,0x50,
+0xaf,0xb0,0x00,0x10,0x34,0x42,0x00,0x20,0x8f,0x90,0x8b,0xb0,0xac,0x43,0x00,0x00,
+0xaf,0xb3,0x00,0x1c,0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xbf,0x00,0x20,
+0x00,0x80,0x88,0x21,0x00,0xa0,0x90,0x21,0x0c,0x00,0x02,0x9a,0x00,0xc0,0x98,0x21,
+0x24,0x07,0x8f,0xff,0x14,0x40,0x00,0x19,0x26,0x03,0x00,0x04,0x24,0x02,0x0e,0x03,
+0xae,0x02,0x00,0x00,0x00,0x67,0x80,0x24,0x26,0x02,0x00,0x04,0xae,0x11,0x00,0x00,
+0x00,0x47,0x80,0x24,0x97,0x86,0x8b,0xb4,0x26,0x03,0x00,0x04,0xae,0x12,0x00,0x00,
+0x00,0x67,0x80,0x24,0xae,0x13,0x00,0x00,0x8f,0x84,0x8b,0xb0,0x3c,0x02,0xb0,0x02,
+0x97,0x85,0x8b,0xb6,0x00,0xc2,0x30,0x21,0x8f,0x82,0x8b,0xb8,0x24,0x84,0x00,0x10,
+0x24,0xa5,0x00,0x10,0x00,0x87,0x20,0x24,0x24,0x42,0x00,0x01,0xa7,0x85,0x8b,0xb6,
+0xaf,0x84,0x8b,0xb0,0xaf,0x82,0x8b,0xb8,0xa4,0xc5,0x00,0x00,0x8f,0xbf,0x00,0x20,
+0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,
+0x27,0xbd,0xff,0xe8,0xaf,0xbf,0x00,0x10,0x94,0x82,0x00,0x04,0x00,0x00,0x00,0x00,
+0x30,0x42,0xe0,0x00,0x14,0x40,0x00,0x14,0x00,0x00,0x00,0x00,0x90,0x82,0x00,0x02,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xfc,0x00,0x82,0x28,0x21,0x8c,0xa4,0x00,0x00,
+0x3c,0x02,0x00,0x70,0x8c,0xa6,0x00,0x08,0x00,0x82,0x10,0x21,0x2c,0x43,0x00,0x06,
+0x10,0x60,0x00,0x09,0x3c,0x03,0x80,0x01,0x00,0x02,0x10,0x80,0x24,0x63,0x01,0xe8,
+0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x08,
+0x00,0x00,0x00,0x00,0xaf,0x86,0x80,0x14,0x8f,0xbf,0x00,0x10,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x8c,0xa4,0x00,0x00,0x0c,0x00,0x17,0xb3,
+0x00,0x00,0x00,0x00,0x08,0x00,0x01,0xde,0x00,0x00,0x00,0x00,0x0c,0x00,0x24,0xaa,
+0x00,0xc0,0x20,0x21,0x08,0x00,0x01,0xde,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x01,0x08,0x8c,0x44,0x00,0x00,0x8f,0x82,0x80,0x18,0x3c,0x03,0x00,0x0f,
+0x34,0x63,0x42,0x40,0x00,0x43,0x10,0x21,0x00,0x82,0x20,0x2b,0x10,0x80,0x00,0x09,
+0x24,0x03,0x00,0x05,0x8f,0x82,0x83,0x30,0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x01,
+0xaf,0x82,0x83,0x30,0x10,0x43,0x00,0x03,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x8c,0x63,0x01,0x08,0x24,0x02,0x00,0x01,
+0xa3,0x82,0x80,0x11,0xaf,0x80,0x83,0x30,0xaf,0x83,0x80,0x18,0x08,0x00,0x01,0xfb,
+0x00,0x00,0x00,0x00,0x30,0x84,0x00,0xff,0x14,0x80,0x00,0x2f,0x00,0x00,0x00,0x00,
+0x8f,0x82,0x80,0x14,0xa3,0x85,0x83,0x63,0x10,0x40,0x00,0x2b,0x2c,0xa2,0x00,0x04,
+0x14,0x40,0x00,0x06,0x00,0x05,0x10,0x40,0x24,0xa2,0xff,0xfc,0x2c,0x42,0x00,0x08,
+0x10,0x40,0x00,0x09,0x24,0xa2,0xff,0xf0,0x00,0x05,0x10,0x40,0x27,0x84,0x83,0x6c,
+0x00,0x44,0x10,0x21,0x94,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0x63,0x00,0x01,
+0x03,0xe0,0x00,0x08,0xa4,0x43,0x00,0x00,0x2c,0x42,0x00,0x10,0x14,0x40,0x00,0x0a,
+0x00,0x05,0x10,0x40,0x24,0xa2,0xff,0xe0,0x2c,0x42,0x00,0x10,0x14,0x40,0x00,0x06,
+0x00,0x05,0x10,0x40,0x24,0xa2,0xff,0xd0,0x2c,0x42,0x00,0x10,0x10,0x40,0x00,0x09,
+0x24,0xa2,0xff,0xc0,0x00,0x05,0x10,0x40,0x27,0x84,0x83,0x6c,0x00,0x44,0x10,0x21,
+0x94,0x43,0xff,0xf8,0x00,0x00,0x00,0x00,0x24,0x63,0x00,0x01,0x03,0xe0,0x00,0x08,
+0xa4,0x43,0xff,0xf8,0x2c,0x42,0x00,0x10,0x10,0x40,0x00,0x07,0x00,0x05,0x10,0x40,
+0x27,0x84,0x83,0x6c,0x00,0x44,0x10,0x21,0x94,0x43,0xff,0xf8,0x00,0x00,0x00,0x00,
+0x24,0x63,0x00,0x01,0xa4,0x43,0xff,0xf8,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x8f,0x86,0x8b,0xb0,0x8f,0x82,0x80,0x14,0x27,0xbd,0xff,0xe8,0xaf,0xbf,0x00,0x10,
+0x10,0x40,0x00,0x2a,0x00,0xc0,0x38,0x21,0x24,0x02,0x00,0x07,0x24,0x03,0xff,0x9c,
+0xa3,0x82,0x83,0x6b,0xa3,0x83,0x83,0x6a,0x27,0x8a,0x83,0x68,0x00,0x00,0x20,0x21,
+0x24,0x09,0x8f,0xff,0x00,0x04,0x10,0x80,0x00,0x4a,0x28,0x21,0x8c,0xa2,0x00,0x00,
+0x24,0xe3,0x00,0x04,0x24,0x88,0x00,0x01,0xac,0xe2,0x00,0x00,0x10,0x80,0x00,0x02,
+0x00,0x69,0x38,0x24,0xac,0xa0,0x00,0x00,0x31,0x04,0x00,0xff,0x2c,0x82,0x00,0x27,
+0x14,0x40,0xff,0xf5,0x00,0x04,0x10,0x80,0x97,0x83,0x8b,0xb6,0x97,0x85,0x8b,0xb4,
+0x3c,0x02,0xb0,0x02,0x24,0x63,0x00,0x9c,0x00,0xa2,0x28,0x21,0x3c,0x04,0xb0,0x06,
+0xa7,0x83,0x8b,0xb6,0x34,0x84,0x80,0x18,0xa4,0xa3,0x00,0x00,0x8c,0x85,0x00,0x00,
+0x24,0x02,0x8f,0xff,0x24,0xc6,0x00,0x9c,0x3c,0x03,0x0f,0x00,0x00,0xc2,0x30,0x24,
+0x00,0xa3,0x28,0x24,0x3c,0x02,0x04,0x00,0xaf,0x86,0x8b,0xb0,0x10,0xa2,0x00,0x03,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x04,0x98,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x10,
+0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x8f,0x86,0x8b,0xb0,
+0x27,0xbd,0xff,0xc8,0x24,0x02,0x00,0x08,0x24,0x03,0x00,0x20,0xaf,0xbf,0x00,0x30,
+0xa3,0xa2,0x00,0x13,0xa3,0xa3,0x00,0x12,0xa7,0xa4,0x00,0x10,0x00,0xc0,0x28,0x21,
+0x27,0xa9,0x00,0x10,0x00,0x00,0x38,0x21,0x24,0x08,0x8f,0xff,0x00,0x07,0x10,0x80,
+0x00,0x49,0x10,0x21,0x8c,0x44,0x00,0x00,0x24,0xe3,0x00,0x01,0x30,0x67,0x00,0xff,
+0x24,0xa2,0x00,0x04,0x2c,0xe3,0x00,0x08,0xac,0xa4,0x00,0x00,0x14,0x60,0xff,0xf7,
+0x00,0x48,0x28,0x24,0x97,0x83,0x8b,0xb6,0x97,0x85,0x8b,0xb4,0x3c,0x02,0xb0,0x02,
+0x24,0x63,0x00,0x20,0x00,0xa2,0x28,0x21,0x3c,0x04,0xb0,0x06,0xa7,0x83,0x8b,0xb6,
+0x34,0x84,0x80,0x18,0xa4,0xa3,0x00,0x00,0x8c,0x85,0x00,0x00,0x24,0x02,0x8f,0xff,
+0x24,0xc6,0x00,0x20,0x3c,0x03,0x0f,0x00,0x00,0xc2,0x30,0x24,0x00,0xa3,0x28,0x24,
+0x3c,0x02,0x04,0x00,0xaf,0x86,0x8b,0xb0,0x10,0xa2,0x00,0x03,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x04,0x98,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x30,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x38,0x93,0x82,0x8b,0xc0,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x11,0x24,0x06,0x00,0x01,0x8f,0x82,0x8b,0xb8,0x3c,0x05,0xb0,0x06,
+0x3c,0x04,0xb0,0x03,0x34,0xa5,0x80,0x18,0x34,0x84,0x01,0x08,0x14,0x40,0x00,0x09,
+0x00,0x00,0x30,0x21,0x97,0x82,0x8b,0xb4,0x8c,0x84,0x00,0x00,0x3c,0x03,0xb0,0x02,
+0x00,0x43,0x10,0x21,0xaf,0x84,0x8b,0xbc,0xa7,0x80,0x8b,0xb6,0xac,0x40,0x00,0x00,
+0xac,0x40,0x00,0x04,0x8c,0xa2,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0xc0,0x10,0x21,
+0x8f,0x86,0x8b,0xb0,0x8f,0x82,0x8b,0xb8,0x27,0xbd,0xff,0xe8,0xaf,0xbf,0x00,0x10,
+0x00,0xc0,0x40,0x21,0x14,0x40,0x00,0x0a,0x00,0x40,0x50,0x21,0x00,0x00,0x38,0x21,
+0x27,0x89,0x83,0x38,0x24,0xe2,0x00,0x01,0x00,0x07,0x18,0x80,0x30,0x47,0x00,0xff,
+0x00,0x69,0x18,0x21,0x2c,0xe2,0x00,0x0a,0x14,0x40,0xff,0xfa,0xac,0x60,0x00,0x00,
+0x3c,0x02,0x00,0x80,0x10,0x82,0x00,0x6f,0x00,0x00,0x00,0x00,0x97,0x82,0x83,0x3e,
+0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x01,0xa7,0x82,0x83,0x3e,0x90,0xa3,0x00,0x15,
+0x97,0x82,0x83,0x40,0x00,0x03,0x1e,0x00,0x00,0x03,0x1e,0x03,0x00,0x43,0x10,0x21,
+0xa7,0x82,0x83,0x40,0x8c,0xa4,0x00,0x20,0x3c,0x02,0x00,0x60,0x3c,0x03,0x00,0x20,
+0x00,0x82,0x20,0x24,0x10,0x83,0x00,0x54,0x00,0x00,0x00,0x00,0x14,0x80,0x00,0x47,
+0x00,0x00,0x00,0x00,0x97,0x82,0x83,0x44,0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x01,
+0xa7,0x82,0x83,0x44,0x84,0xa3,0x00,0x06,0x8f,0x82,0x83,0x54,0x00,0x00,0x00,0x00,
+0x00,0x43,0x10,0x21,0xaf,0x82,0x83,0x54,0x25,0x42,0x00,0x01,0x28,0x43,0x27,0x10,
+0xaf,0x82,0x8b,0xb8,0x10,0x60,0x00,0x09,0x24,0x02,0x00,0x04,0x93,0x83,0x80,0x11,
+0x24,0x02,0x00,0x01,0x10,0x62,0x00,0x05,0x24,0x02,0x00,0x04,0x8f,0xbf,0x00,0x10,
+0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x24,0x03,0x00,0x28,
+0xa3,0x83,0x83,0x3a,0xa3,0x82,0x83,0x3b,0x90,0xa2,0x00,0x18,0x93,0x83,0x83,0x63,
+0x00,0x00,0x38,0x21,0x00,0x02,0x16,0x00,0x00,0x02,0x16,0x03,0xa7,0x82,0x83,0x4e,
+0xa3,0x83,0x83,0x5c,0x27,0x89,0x83,0x38,0x24,0x05,0x8f,0xff,0x00,0x07,0x10,0x80,
+0x00,0x49,0x10,0x21,0x8c,0x44,0x00,0x00,0x24,0xe3,0x00,0x01,0x30,0x67,0x00,0xff,
+0x25,0x02,0x00,0x04,0x2c,0xe3,0x00,0x0a,0xad,0x04,0x00,0x00,0x14,0x60,0xff,0xf7,
+0x00,0x45,0x40,0x24,0x97,0x83,0x8b,0xb6,0x97,0x85,0x8b,0xb4,0x3c,0x02,0xb0,0x02,
+0x24,0x63,0x00,0x28,0x00,0xa2,0x28,0x21,0x3c,0x04,0xb0,0x06,0xa7,0x83,0x8b,0xb6,
+0x34,0x84,0x80,0x18,0xa4,0xa3,0x00,0x00,0x8c,0x85,0x00,0x00,0x24,0x02,0x8f,0xff,
+0x24,0xc6,0x00,0x28,0x3c,0x03,0x0f,0x00,0x00,0xc2,0x30,0x24,0x00,0xa3,0x28,0x24,
+0x3c,0x02,0x04,0x00,0xaf,0x86,0x8b,0xb0,0x10,0xa2,0x00,0x03,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x04,0x98,0x00,0x00,0x00,0x00,0x0c,0x00,0x02,0x38,0x00,0x00,0x00,0x00,
+0xa3,0x80,0x80,0x11,0x08,0x00,0x02,0xe7,0x00,0x00,0x00,0x00,0x97,0x82,0x83,0x46,
+0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x01,0xa7,0x82,0x83,0x46,0x84,0xa3,0x00,0x06,
+0x8f,0x82,0x83,0x58,0x00,0x00,0x00,0x00,0x00,0x43,0x10,0x21,0xaf,0x82,0x83,0x58,
+0x08,0x00,0x02,0xdf,0x25,0x42,0x00,0x01,0x97,0x82,0x83,0x42,0x00,0x00,0x00,0x00,
+0x24,0x42,0x00,0x01,0xa7,0x82,0x83,0x42,0x84,0xa3,0x00,0x06,0x8f,0x82,0x83,0x50,
+0x00,0x00,0x00,0x00,0x00,0x43,0x10,0x21,0xaf,0x82,0x83,0x50,0x08,0x00,0x02,0xdf,
+0x25,0x42,0x00,0x01,0x97,0x82,0x83,0x3c,0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x01,
+0xa7,0x82,0x83,0x3c,0x08,0x00,0x02,0xc7,0x00,0x00,0x00,0x00,0x27,0xbd,0xff,0xd0,
+0xaf,0xbf,0x00,0x28,0x8c,0xa3,0x00,0x20,0x8f,0x8a,0x8b,0xb0,0x3c,0x02,0x00,0x10,
+0x00,0x62,0x10,0x24,0x00,0xa0,0x38,0x21,0x01,0x40,0x48,0x21,0x10,0x40,0x00,0x3d,
+0x00,0x80,0x28,0x21,0x8c,0xe4,0x00,0x1c,0x34,0xa5,0x12,0x06,0xaf,0xa5,0x00,0x10,
+0x8c,0x82,0x00,0x08,0x00,0x03,0x1c,0x42,0x30,0x63,0x00,0x30,0x00,0x02,0x13,0x02,
+0x30,0x42,0x00,0x40,0x00,0x43,0x10,0x25,0x90,0xe6,0x00,0x10,0x90,0xe4,0x00,0x13,
+0x94,0xe8,0x00,0x0c,0x94,0xe3,0x00,0x1a,0x00,0x02,0x16,0x00,0x90,0xe7,0x00,0x12,
+0x00,0xa2,0x28,0x25,0x24,0x02,0x12,0x34,0xa7,0xa2,0x00,0x1c,0x24,0x02,0x56,0x78,
+0xaf,0xa5,0x00,0x10,0xa3,0xa6,0x00,0x18,0xa3,0xa7,0x00,0x1f,0xa7,0xa3,0x00,0x1a,
+0xa3,0xa4,0x00,0x19,0xa7,0xa8,0x00,0x20,0xa7,0xa2,0x00,0x22,0x00,0x00,0x28,0x21,
+0x27,0xa7,0x00,0x10,0x24,0x06,0x8f,0xff,0x00,0x05,0x10,0x80,0x00,0x47,0x10,0x21,
+0x8c,0x44,0x00,0x00,0x24,0xa3,0x00,0x01,0x30,0x65,0x00,0xff,0x25,0x22,0x00,0x04,
+0x2c,0xa3,0x00,0x05,0xad,0x24,0x00,0x00,0x14,0x60,0xff,0xf7,0x00,0x46,0x48,0x24,
+0x97,0x83,0x8b,0xb6,0x97,0x85,0x8b,0xb4,0x3c,0x02,0xb0,0x02,0x24,0x63,0x00,0x14,
+0x00,0xa2,0x28,0x21,0x3c,0x04,0xb0,0x06,0xa7,0x83,0x8b,0xb6,0x34,0x84,0x80,0x18,
+0xa4,0xa3,0x00,0x00,0x8c,0x85,0x00,0x00,0x24,0x02,0x8f,0xff,0x25,0x46,0x00,0x14,
+0x3c,0x03,0x0f,0x00,0x00,0xc2,0x50,0x24,0x00,0xa3,0x28,0x24,0x3c,0x02,0x04,0x00,
+0xaf,0x8a,0x8b,0xb0,0x10,0xa2,0x00,0x03,0x00,0x00,0x00,0x00,0x0c,0x00,0x04,0x98,
+0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x28,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x30,0x3c,0x05,0xb0,0x03,0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xc8,
+0x00,0x04,0x22,0x00,0x34,0xa5,0x00,0x20,0x24,0x42,0x0e,0x04,0x3c,0x03,0xb0,0x00,
+0xaf,0xb5,0x00,0x24,0xaf,0xb4,0x00,0x20,0xaf,0xb2,0x00,0x18,0xaf,0xb0,0x00,0x10,
+0xaf,0xbf,0x00,0x30,0x00,0x83,0x80,0x21,0xaf,0xb7,0x00,0x2c,0xaf,0xb6,0x00,0x28,
+0xaf,0xb3,0x00,0x1c,0xaf,0xb1,0x00,0x14,0xac,0xa2,0x00,0x00,0x8e,0x09,0x00,0x00,
+0x00,0x00,0x90,0x21,0x26,0x10,0x00,0x08,0x00,0x09,0xa6,0x02,0x12,0x80,0x00,0x13,
+0x00,0x00,0xa8,0x21,0x24,0x13,0x00,0x02,0x3c,0x16,0x00,0xff,0x3c,0x17,0xff,0x00,
+0x8e,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x09,0x12,0x02,0x24,0x42,0x00,0x02,
+0x31,0x25,0x00,0xff,0x10,0xb3,0x00,0x76,0x30,0x51,0x00,0xff,0x24,0x02,0x00,0x03,
+0x10,0xa2,0x00,0x18,0x00,0x00,0x00,0x00,0x02,0x51,0x10,0x21,0x30,0x52,0xff,0xff,
+0x02,0x54,0x18,0x2b,0x14,0x60,0xff,0xf2,0x02,0x11,0x80,0x21,0x12,0xa0,0x00,0x0a,
+0x3c,0x02,0xb0,0x06,0x34,0x42,0x80,0x18,0x8c,0x43,0x00,0x00,0x3c,0x04,0x0f,0x00,
+0x3c,0x02,0x04,0x00,0x00,0x64,0x18,0x24,0x10,0x62,0x00,0x03,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x04,0x98,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x30,0x7b,0xb6,0x01,0x7c,
+0x7b,0xb4,0x01,0x3c,0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x38,0x8e,0x09,0x00,0x04,0x24,0x15,0x00,0x01,0x8e,0x06,0x00,0x0c,
+0x00,0x09,0x11,0x42,0x00,0x09,0x18,0xc2,0x30,0x48,0x00,0x03,0x00,0x09,0x14,0x02,
+0x30,0x6c,0x00,0x03,0x00,0x09,0x26,0x02,0x11,0x15,0x00,0x45,0x30,0x43,0x00,0x0f,
+0x29,0x02,0x00,0x02,0x14,0x40,0x00,0x26,0x00,0x00,0x00,0x00,0x11,0x13,0x00,0x0f,
+0x00,0x00,0x38,0x21,0x00,0x07,0x22,0x02,0x30,0x84,0xff,0x00,0x3c,0x03,0x00,0xff,
+0x00,0x07,0x2e,0x02,0x00,0x07,0x12,0x00,0x00,0x43,0x10,0x24,0x00,0xa4,0x28,0x25,
+0x00,0xa2,0x28,0x25,0x00,0x07,0x1e,0x00,0x00,0xa3,0x28,0x25,0x0c,0x00,0x01,0x94,
+0x01,0x20,0x20,0x21,0x08,0x00,0x03,0xa7,0x02,0x51,0x10,0x21,0x11,0x95,0x00,0x0f,
+0x00,0x00,0x00,0x00,0x11,0x88,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x04,0x10,0x80,
+0x27,0x83,0x8b,0x60,0x00,0x43,0x10,0x21,0x8c,0x47,0x00,0x18,0x08,0x00,0x03,0xce,
+0x00,0x07,0x22,0x02,0x00,0x04,0x10,0x40,0x27,0x83,0x8b,0x68,0x00,0x43,0x10,0x21,
+0x94,0x47,0x00,0x02,0x08,0x00,0x03,0xce,0x00,0x07,0x22,0x02,0x27,0x82,0x8b,0x60,
+0x00,0x82,0x10,0x21,0x90,0x47,0x00,0x00,0x08,0x00,0x03,0xce,0x00,0x07,0x22,0x02,
+0x15,0x00,0xff,0xdc,0x00,0x00,0x38,0x21,0x10,0x75,0x00,0x05,0x00,0x80,0x38,0x21,
+0x00,0x65,0x18,0x26,0x24,0x82,0x01,0x00,0x00,0x00,0x38,0x21,0x00,0x43,0x38,0x0a,
+0x24,0x02,0x00,0x01,0x11,0x82,0x00,0x0e,0x3c,0x02,0xb0,0x03,0x24,0x02,0x00,0x02,
+0x11,0x82,0x00,0x06,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x00,0xe2,0x10,0x21,
+0x8c,0x47,0x00,0x00,0x08,0x00,0x03,0xce,0x00,0x07,0x22,0x02,0x3c,0x02,0xb0,0x03,
+0x00,0xe2,0x10,0x21,0x94,0x43,0x00,0x00,0x08,0x00,0x03,0xcd,0x30,0x67,0xff,0xff,
+0x00,0xe2,0x10,0x21,0x90,0x43,0x00,0x00,0x08,0x00,0x03,0xcd,0x30,0x67,0x00,0xff,
+0x30,0x62,0x00,0x03,0x00,0x02,0x12,0x00,0x11,0x95,0x00,0x07,0x00,0x44,0x38,0x21,
+0x11,0x93,0x00,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0x03,0xff,0x3c,0x02,0xb0,0x0a,
+0x08,0x00,0x04,0x04,0x3c,0x02,0xb0,0x0a,0x08,0x00,0x04,0x08,0x3c,0x02,0xb0,0x0a,
+0x8e,0x09,0x00,0x04,0x8e,0x02,0x00,0x08,0x8e,0x03,0x00,0x0c,0x00,0x09,0x41,0x42,
+0x00,0x02,0x22,0x02,0x00,0x03,0x3a,0x02,0x30,0x84,0xff,0x00,0x30,0xe7,0xff,0x00,
+0x00,0x02,0x5e,0x02,0x00,0x02,0x32,0x00,0x00,0x03,0x56,0x02,0x00,0x03,0x2a,0x00,
+0x01,0x64,0x58,0x25,0x00,0xd6,0x30,0x24,0x01,0x47,0x50,0x25,0x00,0x02,0x16,0x00,
+0x00,0xb6,0x28,0x24,0x00,0x03,0x1e,0x00,0x01,0x66,0x58,0x25,0x01,0x45,0x50,0x25,
+0x00,0x57,0x10,0x24,0x00,0x77,0x18,0x24,0x01,0x62,0x38,0x25,0x01,0x43,0x30,0x25,
+0x00,0x09,0x10,0xc2,0x00,0x09,0x1c,0x02,0x31,0x08,0x00,0x03,0x30,0x4c,0x00,0x03,
+0x30,0x63,0x00,0x0f,0x00,0x09,0x26,0x02,0x00,0xe0,0x58,0x21,0x15,0x00,0x00,0x28,
+0x00,0xc0,0x50,0x21,0x24,0x02,0x00,0x01,0x10,0x62,0x00,0x06,0x00,0x80,0x28,0x21,
+0x24,0x02,0x00,0x03,0x14,0x62,0xff,0x69,0x02,0x51,0x10,0x21,0x24,0x85,0x01,0x00,
+0x24,0x02,0x00,0x01,0x11,0x82,0x00,0x15,0x24,0x02,0x00,0x02,0x11,0x82,0x00,0x0a,
+0x3c,0x03,0xb0,0x03,0x00,0xa3,0x18,0x21,0x8c,0x62,0x00,0x00,0x00,0x0a,0x20,0x27,
+0x01,0x6a,0x28,0x24,0x00,0x44,0x10,0x24,0x00,0x45,0x10,0x25,0xac,0x62,0x00,0x00,
+0x08,0x00,0x03,0xa7,0x02,0x51,0x10,0x21,0x00,0xa3,0x18,0x21,0x94,0x62,0x00,0x00,
+0x00,0x0a,0x20,0x27,0x01,0x6a,0x28,0x24,0x00,0x44,0x10,0x24,0x00,0x45,0x10,0x25,
+0xa4,0x62,0x00,0x00,0x08,0x00,0x03,0xa7,0x02,0x51,0x10,0x21,0x3c,0x03,0xb0,0x03,
+0x00,0xa3,0x18,0x21,0x90,0x62,0x00,0x00,0x00,0x0a,0x20,0x27,0x01,0x6a,0x28,0x24,
+0x00,0x44,0x10,0x24,0x00,0x45,0x10,0x25,0x08,0x00,0x03,0xa6,0xa0,0x62,0x00,0x00,
+0x24,0x02,0x00,0x01,0x11,0x02,0x00,0x21,0x00,0x00,0x00,0x00,0x15,0x13,0xff,0x42,
+0x00,0x00,0x00,0x00,0x11,0x82,0x00,0x17,0x00,0x00,0x00,0x00,0x11,0x88,0x00,0x0b,
+0x00,0x00,0x00,0x00,0x27,0x83,0x8b,0x60,0x00,0x04,0x20,0x80,0x00,0x83,0x20,0x21,
+0x8c,0x82,0x00,0x18,0x00,0x06,0x18,0x27,0x00,0xe6,0x28,0x24,0x00,0x43,0x10,0x24,
+0x00,0x45,0x10,0x25,0x08,0x00,0x03,0xa6,0xac,0x82,0x00,0x18,0x27,0x83,0x8b,0x68,
+0x00,0x04,0x20,0x40,0x00,0x83,0x20,0x21,0x94,0x82,0x00,0x02,0x00,0x06,0x18,0x27,
+0x00,0xe6,0x28,0x24,0x00,0x43,0x10,0x24,0x00,0x45,0x10,0x25,0x08,0x00,0x03,0xa6,
+0xa4,0x82,0x00,0x02,0x27,0x83,0x8b,0x60,0x00,0x83,0x18,0x21,0x90,0x62,0x00,0x00,
+0x00,0x06,0x20,0x27,0x08,0x00,0x04,0x5c,0x00,0xe6,0x28,0x24,0x30,0x62,0x00,0x07,
+0x00,0x02,0x12,0x00,0x11,0x88,0x00,0x0f,0x00,0x44,0x10,0x21,0x11,0x93,0x00,0x07,
+0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x0a,0x00,0x43,0x18,0x21,0x8c,0x62,0x00,0x00,
+0x00,0x06,0x20,0x27,0x08,0x00,0x04,0x49,0x00,0xe6,0x28,0x24,0x3c,0x03,0xb0,0x0a,
+0x00,0x43,0x18,0x21,0x94,0x62,0x00,0x00,0x00,0x06,0x20,0x27,0x08,0x00,0x04,0x52,
+0x00,0xe6,0x28,0x24,0x3c,0x03,0xb0,0x0a,0x08,0x00,0x04,0x7f,0x00,0x43,0x18,0x21,
+0x97,0x85,0x8b,0xb4,0x3c,0x07,0xb0,0x02,0x3c,0x04,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x00,0xa7,0x28,0x21,0x34,0x84,0x00,0x20,0x24,0x42,0x12,0x60,0x24,0x03,0xff,0x80,
+0xac,0x82,0x00,0x00,0xa0,0xa3,0x00,0x07,0x97,0x82,0x8b,0xb6,0x97,0x85,0x8b,0xb4,
+0x3c,0x06,0xb0,0x06,0x30,0x42,0xff,0xf8,0x24,0x42,0x00,0x10,0x00,0xa2,0x10,0x21,
+0x30,0x42,0x0f,0xff,0x24,0x44,0x00,0x08,0x30,0x84,0x0f,0xff,0x00,0x05,0x28,0xc2,
+0x3c,0x03,0x00,0x40,0x00,0xa3,0x28,0x25,0x00,0x87,0x20,0x21,0x34,0xc6,0x80,0x18,
+0xac,0xc5,0x00,0x00,0xaf,0x84,0x8b,0xb0,0xa7,0x82,0x8b,0xb4,0xa7,0x80,0x8b,0xb6,
+0xaf,0x80,0x8b,0xb8,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x30,0xa5,0x00,0xff,
+0x30,0x84,0x00,0xff,0x24,0x02,0x00,0x01,0x00,0xe0,0x48,0x21,0x30,0xc6,0x00,0xff,
+0x8f,0xa7,0x00,0x10,0x10,0x82,0x00,0x07,0x00,0xa0,0x40,0x21,0x24,0x02,0x00,0x03,
+0x10,0x82,0x00,0x03,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x24,0xa8,0x01,0x00,0x3c,0x03,0xb0,0x03,0x24,0x02,0x00,0x01,0x00,0x07,0x20,0x27,
+0x01,0x27,0x28,0x24,0x10,0xc2,0x00,0x14,0x01,0x03,0x18,0x21,0x24,0x02,0x00,0x02,
+0x10,0xc2,0x00,0x09,0x00,0x07,0x50,0x27,0x3c,0x03,0xb0,0x03,0x01,0x03,0x18,0x21,
+0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4a,0x10,0x24,0x00,0x45,0x10,0x25,
+0x08,0x00,0x04,0xe3,0xac,0x62,0x00,0x00,0x3c,0x03,0xb0,0x03,0x01,0x03,0x18,0x21,
+0x94,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4a,0x10,0x24,0x00,0x45,0x10,0x25,
+0x03,0xe0,0x00,0x08,0xa4,0x62,0x00,0x00,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x44,0x10,0x24,0x00,0x45,0x10,0x25,0xa0,0x62,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x30,0x84,0x00,0x07,0x00,0x04,0x22,0x00,0x30,0xa5,0x00,0xff,
+0x00,0x85,0x28,0x21,0x3c,0x02,0xb0,0x0a,0x00,0xa2,0x40,0x21,0x30,0xc6,0x00,0xff,
+0x24,0x02,0x00,0x01,0x8f,0xa4,0x00,0x10,0x10,0xc2,0x00,0x14,0x24,0x02,0x00,0x02,
+0x00,0x04,0x50,0x27,0x10,0xc2,0x00,0x09,0x00,0xe4,0x48,0x24,0x3c,0x03,0xb0,0x0a,
+0x00,0xa3,0x18,0x21,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4a,0x10,0x24,
+0x00,0x49,0x10,0x25,0x03,0xe0,0x00,0x08,0xac,0x62,0x00,0x00,0x3c,0x03,0xb0,0x0a,
+0x00,0xa3,0x18,0x21,0x94,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4a,0x10,0x24,
+0x00,0x49,0x10,0x25,0x03,0xe0,0x00,0x08,0xa4,0x62,0x00,0x00,0x91,0x02,0x00,0x00,
+0x00,0x04,0x18,0x27,0x00,0xe4,0x20,0x24,0x00,0x43,0x10,0x24,0x00,0x44,0x10,0x25,
+0x03,0xe0,0x00,0x08,0xa1,0x02,0x00,0x00,0x30,0xa9,0x00,0xff,0x27,0x83,0x8b,0x60,
+0x30,0x85,0x00,0xff,0x24,0x02,0x00,0x01,0x00,0x07,0x50,0x27,0x00,0xc7,0x40,0x24,
+0x11,0x22,0x00,0x17,0x00,0xa3,0x18,0x21,0x00,0x05,0x20,0x40,0x27,0x82,0x8b,0x60,
+0x00,0x05,0x28,0x80,0x27,0x83,0x8b,0x68,0x00,0x83,0x50,0x21,0x00,0xa2,0x20,0x21,
+0x24,0x02,0x00,0x02,0x00,0x07,0x40,0x27,0x11,0x22,0x00,0x07,0x00,0xc7,0x28,0x24,
+0x8c,0x82,0x00,0x18,0x00,0x00,0x00,0x00,0x00,0x48,0x10,0x24,0x00,0x45,0x10,0x25,
+0x03,0xe0,0x00,0x08,0xac,0x82,0x00,0x18,0x95,0x42,0x00,0x02,0x00,0x00,0x00,0x00,
+0x00,0x48,0x10,0x24,0x00,0x45,0x10,0x25,0x03,0xe0,0x00,0x08,0xa5,0x42,0x00,0x02,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4a,0x10,0x24,0x00,0x48,0x10,0x25,
+0x03,0xe0,0x00,0x08,0xa0,0x62,0x00,0x00,0x00,0x04,0x32,0x02,0x30,0xc6,0xff,0x00,
+0x00,0x04,0x16,0x02,0x00,0x04,0x1a,0x00,0x3c,0x05,0x00,0xff,0x00,0x65,0x18,0x24,
+0x00,0x46,0x10,0x25,0x00,0x43,0x10,0x25,0x00,0x04,0x26,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x44,0x10,0x25,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xe8,
+0x34,0x63,0x00,0x20,0x24,0x42,0x14,0xe4,0x3c,0x04,0xb0,0x03,0xaf,0xbf,0x00,0x14,
+0xac,0x62,0x00,0x00,0xaf,0xb0,0x00,0x10,0x34,0x84,0x00,0x2c,0x8c,0x83,0x00,0x00,
+0xa7,0x80,0xbb,0xf0,0x00,0x03,0x12,0x02,0x00,0x03,0x2d,0x02,0x30,0x42,0x0f,0xff,
+0xa3,0x83,0xbb,0xf8,0xa7,0x85,0xbb,0xfc,0xa7,0x82,0xbb,0xfa,0xa7,0x80,0xbb,0xf2,
+0xa7,0x80,0xbb,0xf4,0xa7,0x80,0xbb,0xf6,0x0c,0x00,0x06,0xce,0x24,0x04,0x05,0x00,
+0x3c,0x05,0x08,0x00,0x00,0x45,0x28,0x25,0x24,0x04,0x05,0x00,0x0c,0x00,0x06,0xc1,
+0x00,0x40,0x80,0x21,0x3c,0x02,0xf7,0xff,0x34,0x42,0xff,0xff,0x02,0x02,0x80,0x24,
+0x02,0x00,0x28,0x21,0x0c,0x00,0x06,0xc1,0x24,0x04,0x05,0x00,0x3c,0x02,0xb0,0x03,
+0x3c,0x03,0xb0,0x03,0x34,0x42,0x01,0x08,0x34,0x63,0x01,0x18,0x8c,0x45,0x00,0x00,
+0x8c,0x64,0x00,0x00,0x3c,0x02,0x00,0x0f,0x3c,0x03,0x00,0x4c,0x30,0x84,0x02,0x00,
+0x34,0x63,0x4b,0x40,0xaf,0x85,0xbc,0x00,0x10,0x80,0x00,0x06,0x34,0x42,0x42,0x40,
+0xaf,0x83,0xbc,0x04,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0xaf,0x82,0xbc,0x04,0x08,0x00,0x05,0x69,0x00,0x00,0x00,0x00,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xc8,0x34,0x63,0x00,0x20,
+0x24,0x42,0x15,0xc0,0x30,0x84,0x00,0xff,0xaf,0xbf,0x00,0x30,0xaf,0xb7,0x00,0x2c,
+0xaf,0xb6,0x00,0x28,0xaf,0xb5,0x00,0x24,0xaf,0xb4,0x00,0x20,0xaf,0xb3,0x00,0x1c,
+0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0xac,0x62,0x00,0x00,
+0x10,0x80,0x00,0x1c,0x24,0x02,0x00,0x02,0x10,0x82,0x00,0x08,0x00,0x00,0x00,0x00,
+0x8f,0xbf,0x00,0x30,0x7b,0xb6,0x01,0x7c,0x7b,0xb4,0x01,0x3c,0x7b,0xb2,0x00,0xfc,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x38,0xa7,0x80,0xbb,0xf0,
+0xa7,0x80,0xbb,0xf2,0xa7,0x80,0xbb,0xf4,0xa7,0x80,0xbb,0xf6,0x0c,0x00,0x06,0xce,
+0x24,0x04,0x05,0x00,0x3c,0x05,0x08,0x00,0x00,0x45,0x28,0x25,0x24,0x04,0x05,0x00,
+0x0c,0x00,0x06,0xc1,0x00,0x40,0x80,0x21,0x3c,0x05,0xf7,0xff,0x34,0xa5,0xff,0xff,
+0x02,0x05,0x28,0x24,0x0c,0x00,0x06,0xc1,0x24,0x04,0x05,0x00,0x08,0x00,0x05,0x84,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x06,0xce,0x24,0x04,0x05,0xa0,0x24,0x04,0x05,0xa4,
+0x0c,0x00,0x06,0xce,0x00,0x02,0xbc,0x02,0x24,0x04,0x05,0xa8,0x00,0x02,0xb4,0x02,
+0x0c,0x00,0x06,0xce,0x30,0x55,0xff,0xff,0x00,0x40,0x80,0x21,0x97,0x84,0xbb,0xf0,
+0x97,0x82,0xbb,0xf2,0x97,0x83,0xbb,0xf6,0x02,0xe4,0x20,0x23,0x02,0xa2,0x10,0x23,
+0x00,0x82,0x20,0x21,0x97,0x82,0xbb,0xf4,0x32,0x14,0xff,0xff,0x02,0x83,0x18,0x23,
+0x02,0xc2,0x10,0x23,0x00,0x82,0x20,0x21,0x93,0x82,0xbb,0xf8,0x00,0x83,0x20,0x21,
+0x30,0x84,0xff,0xff,0x00,0x82,0x10,0x2b,0x14,0x40,0x00,0xaa,0x00,0x00,0x00,0x00,
+0x97,0x82,0xbb,0xfc,0x00,0x00,0x00,0x00,0x00,0x44,0x10,0x2b,0x14,0x40,0x00,0x7f,
+0x00,0x00,0x00,0x00,0x97,0x82,0xbb,0xfa,0x00,0x00,0x00,0x00,0x00,0x44,0x10,0x2b,
+0x10,0x40,0x00,0x3a,0x00,0x00,0x00,0x00,0x0c,0x00,0x06,0xce,0x24,0x04,0x04,0x50,
+0x30,0x51,0x00,0x7f,0x00,0x40,0x80,0x21,0x2e,0x22,0x00,0x32,0x10,0x40,0x00,0x13,
+0x24,0x02,0x00,0x20,0x12,0x22,0x00,0x17,0x24,0x02,0xff,0x80,0x02,0x02,0x10,0x24,
+0x26,0x31,0x00,0x01,0x00,0x51,0x80,0x25,0x02,0x00,0x28,0x21,0x0c,0x00,0x06,0xc1,
+0x24,0x04,0x04,0x50,0x02,0x00,0x28,0x21,0x0c,0x00,0x06,0xc1,0x24,0x04,0x04,0x58,
+0x02,0x00,0x28,0x21,0x0c,0x00,0x06,0xc1,0x24,0x04,0x04,0x60,0x02,0x00,0x28,0x21,
+0x24,0x04,0x04,0x68,0x0c,0x00,0x06,0xc1,0x00,0x00,0x00,0x00,0xa7,0x97,0xbb,0xf0,
+0xa7,0x95,0xbb,0xf2,0xa7,0x96,0xbb,0xf4,0xa7,0x94,0xbb,0xf6,0x08,0x00,0x05,0x84,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x06,0xce,0x24,0x04,0x02,0x08,0x3c,0x04,0x00,0xc0,
+0x00,0x40,0x28,0x21,0x00,0x44,0x10,0x24,0x00,0x02,0x15,0x82,0x24,0x03,0x00,0x03,
+0x10,0x43,0x00,0x07,0x00,0x00,0x00,0x00,0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,
+0x00,0xa2,0x10,0x24,0x00,0x44,0x28,0x25,0x0c,0x00,0x06,0xc1,0x24,0x04,0x02,0x08,
+0x0c,0x00,0x06,0xce,0x24,0x04,0x02,0x2c,0x00,0x40,0x90,0x21,0x3c,0x02,0xff,0xff,
+0x34,0x42,0x3f,0xff,0x02,0x42,0x90,0x24,0x02,0x40,0x28,0x21,0x0c,0x00,0x06,0xc1,
+0x24,0x04,0x02,0x2c,0x08,0x00,0x05,0xcb,0x24,0x02,0xff,0x80,0x0c,0x00,0x06,0xce,
+0x24,0x04,0x04,0x50,0x30,0x51,0x00,0x7f,0x24,0x02,0x00,0x20,0x16,0x22,0xff,0xdb,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x06,0xce,0x24,0x04,0x02,0x2c,0x34,0x52,0x40,0x00,
+0x02,0x40,0x28,0x21,0x0c,0x00,0x06,0xc1,0x24,0x04,0x02,0x2c,0x0c,0x00,0x06,0xce,
+0x24,0x04,0x02,0x58,0x24,0x04,0x02,0x5c,0x0c,0x00,0x06,0xce,0x00,0x02,0x9e,0x02,
+0x30,0x43,0x00,0xff,0x00,0x13,0x12,0x00,0x00,0x43,0x10,0x25,0x2c,0x43,0x00,0x04,
+0x14,0x60,0x00,0x1d,0x2c,0x42,0x00,0x11,0x10,0x40,0x00,0x0b,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xff,0xff,0x34,0x42,0x3f,0xff,0x02,0x42,0x90,0x24,0x02,0x40,0x28,0x21,
+0x24,0x04,0x02,0x2c,0x0c,0x00,0x06,0xc1,0x36,0x52,0x80,0x00,0x02,0x40,0x28,0x21,
+0x08,0x00,0x05,0xd9,0x24,0x04,0x02,0x2c,0x0c,0x00,0x06,0xce,0x24,0x04,0x02,0x08,
+0x3c,0x04,0x00,0xc0,0x00,0x40,0x28,0x21,0x00,0x44,0x10,0x24,0x00,0x02,0x15,0x82,
+0x24,0x03,0x00,0x02,0x14,0x43,0xff,0xee,0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,
+0x00,0xa2,0x10,0x24,0x00,0x44,0x28,0x25,0x0c,0x00,0x06,0xc1,0x24,0x04,0x02,0x08,
+0x08,0x00,0x06,0x15,0x3c,0x02,0xff,0xff,0x0c,0x00,0x06,0xce,0x24,0x04,0x02,0x08,
+0x00,0x40,0x28,0x21,0x00,0x02,0x15,0x82,0x30,0x42,0x00,0x03,0x24,0x03,0x00,0x03,
+0x14,0x43,0xff,0xdf,0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,0x00,0xa2,0x10,0x24,
+0x3c,0x03,0x00,0x80,0x08,0x00,0x06,0x2a,0x00,0x43,0x28,0x25,0x0c,0x00,0x06,0xce,
+0x24,0x04,0x04,0x50,0x30,0x51,0x00,0x7f,0x00,0x40,0x80,0x21,0x2e,0x22,0x00,0x32,
+0x10,0x40,0xff,0x9a,0x24,0x02,0x00,0x20,0x12,0x22,0x00,0x04,0x24,0x02,0xff,0x80,
+0x02,0x02,0x10,0x24,0x08,0x00,0x05,0xcd,0x26,0x31,0x00,0x02,0x0c,0x00,0x06,0xce,
+0x24,0x04,0x02,0x08,0x3c,0x04,0x00,0xc0,0x00,0x40,0x28,0x21,0x00,0x44,0x10,0x24,
+0x00,0x02,0x15,0x82,0x24,0x03,0x00,0x03,0x10,0x43,0x00,0x07,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,0x00,0xa2,0x10,0x24,0x00,0x44,0x28,0x25,
+0x0c,0x00,0x06,0xc1,0x24,0x04,0x02,0x08,0x0c,0x00,0x06,0xce,0x24,0x04,0x02,0x2c,
+0x00,0x40,0x90,0x21,0x3c,0x02,0xff,0xff,0x34,0x42,0x3f,0xff,0x02,0x42,0x90,0x24,
+0x02,0x40,0x28,0x21,0x0c,0x00,0x06,0xc1,0x24,0x04,0x02,0x2c,0x08,0x00,0x06,0x44,
+0x24,0x02,0xff,0x80,0x0c,0x00,0x06,0xce,0x24,0x04,0x04,0x50,0x00,0x40,0x80,0x21,
+0x30,0x51,0x00,0x7f,0x24,0x02,0x00,0x20,0x12,0x22,0x00,0x1d,0x2e,0x22,0x00,0x21,
+0x14,0x40,0xff,0x72,0x24,0x02,0xff,0x80,0x02,0x02,0x10,0x24,0x26,0x31,0xff,0xff,
+0x00,0x51,0x80,0x25,0x24,0x04,0x04,0x50,0x0c,0x00,0x06,0xc1,0x02,0x00,0x28,0x21,
+0x24,0x04,0x04,0x58,0x0c,0x00,0x06,0xc1,0x02,0x00,0x28,0x21,0x24,0x04,0x04,0x60,
+0x0c,0x00,0x06,0xc1,0x02,0x00,0x28,0x21,0x02,0x00,0x28,0x21,0x0c,0x00,0x06,0xc1,
+0x24,0x04,0x04,0x68,0x24,0x02,0x00,0x20,0x16,0x22,0xff,0x60,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x06,0xce,0x24,0x04,0x02,0x2c,0x00,0x40,0x90,0x21,0x3c,0x02,0xff,0xff,
+0x34,0x42,0x3f,0xff,0x02,0x42,0x10,0x24,0x08,0x00,0x06,0x1b,0x34,0x52,0x80,0x00,
+0x0c,0x00,0x06,0xce,0x24,0x04,0x02,0x2c,0x34,0x52,0x40,0x00,0x02,0x40,0x28,0x21,
+0x0c,0x00,0x06,0xc1,0x24,0x04,0x02,0x2c,0x0c,0x00,0x06,0xce,0x24,0x04,0x02,0x58,
+0x24,0x04,0x02,0x5c,0x0c,0x00,0x06,0xce,0x00,0x02,0x9e,0x02,0x30,0x43,0x00,0xff,
+0x00,0x13,0x12,0x00,0x00,0x43,0x10,0x25,0x2c,0x43,0x00,0x04,0x14,0x60,0x00,0x20,
+0x2c,0x42,0x00,0x11,0x10,0x40,0x00,0x0d,0x00,0x00,0x00,0x00,0x3c,0x02,0xff,0xff,
+0x34,0x42,0x3f,0xff,0x02,0x42,0x90,0x24,0x02,0x40,0x28,0x21,0x24,0x04,0x02,0x2c,
+0x0c,0x00,0x06,0xc1,0x36,0x52,0x80,0x00,0x02,0x40,0x28,0x21,0x0c,0x00,0x06,0xc1,
+0x24,0x04,0x02,0x2c,0x08,0x00,0x06,0x68,0x2e,0x22,0x00,0x21,0x0c,0x00,0x06,0xce,
+0x24,0x04,0x02,0x08,0x3c,0x04,0x00,0xc0,0x00,0x40,0x28,0x21,0x00,0x44,0x10,0x24,
+0x00,0x02,0x15,0x82,0x24,0x03,0x00,0x02,0x14,0x43,0xff,0xec,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,0x00,0xa2,0x10,0x24,0x00,0x44,0x28,0x25,
+0x0c,0x00,0x06,0xc1,0x24,0x04,0x02,0x08,0x08,0x00,0x06,0x98,0x3c,0x02,0xff,0xff,
+0x0c,0x00,0x06,0xce,0x24,0x04,0x02,0x08,0x00,0x40,0x28,0x21,0x00,0x02,0x15,0x82,
+0x30,0x42,0x00,0x03,0x24,0x03,0x00,0x03,0x14,0x43,0xff,0xdc,0x3c,0x03,0x00,0x80,
+0x3c,0x02,0xff,0x3f,0x34,0x42,0xff,0xff,0x00,0xa2,0x10,0x24,0x08,0x00,0x06,0xb0,
+0x00,0x43,0x28,0x25,0x30,0x83,0x00,0x03,0x00,0x04,0x20,0x40,0x00,0x83,0x20,0x23,
+0x3c,0x02,0xb0,0x0a,0x00,0x82,0x20,0x21,0xac,0x85,0x00,0x00,0x00,0x00,0x18,0x21,
+0x24,0x63,0x00,0x01,0x2c,0x62,0x00,0x0a,0x14,0x40,0xff,0xfe,0x24,0x63,0x00,0x01,
+0x03,0xe0,0x00,0x08,0x24,0x63,0xff,0xff,0x30,0x86,0x00,0x03,0x00,0x04,0x28,0x40,
+0x3c,0x03,0xb0,0x0a,0x00,0xa6,0x10,0x23,0x00,0x43,0x10,0x21,0x24,0x04,0xff,0xff,
+0xac,0x44,0x10,0x00,0x00,0x00,0x18,0x21,0x24,0x63,0x00,0x01,0x2c,0x62,0x00,0x0a,
+0x14,0x40,0xff,0xfe,0x24,0x63,0x00,0x01,0x24,0x63,0xff,0xff,0x00,0xa6,0x18,0x23,
+0x3c,0x02,0xb0,0x0a,0x00,0x62,0x18,0x21,0x8c,0x62,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x3c,0x05,0xb0,0x03,0x3c,0x02,0x80,0x00,0x24,0x42,0x1b,0x84,
+0x24,0x03,0x00,0x01,0x34,0xa5,0x00,0x20,0x3c,0x06,0xb0,0x03,0xac,0xa2,0x00,0x00,
+0x34,0xc6,0x01,0x04,0xa0,0x83,0x00,0x48,0xa0,0x80,0x00,0x04,0xa0,0x80,0x00,0x05,
+0xa0,0x80,0x00,0x06,0xa0,0x80,0x00,0x07,0xa0,0x80,0x00,0x08,0xa0,0x80,0x00,0x09,
+0xa0,0x80,0x00,0x0a,0xa0,0x80,0x00,0x11,0xa0,0x80,0x00,0x13,0xa0,0x80,0x00,0x49,
+0x94,0xc2,0x00,0x00,0xac,0x80,0x00,0x00,0xa0,0x80,0x00,0x4e,0x00,0x02,0x14,0x00,
+0x00,0x02,0x14,0x03,0x30,0x43,0x00,0xff,0x30,0x42,0xff,0x00,0xa4,0x82,0x00,0x44,
+0xa4,0x83,0x00,0x46,0xac,0x80,0x00,0x24,0xac,0x80,0x00,0x28,0xac,0x80,0x00,0x2c,
+0xac,0x80,0x00,0x30,0xac,0x80,0x00,0x34,0xac,0x80,0x00,0x38,0xac,0x80,0x00,0x3c,
+0x03,0xe0,0x00,0x08,0xac,0x80,0x00,0x40,0x84,0x83,0x00,0x0c,0x3c,0x07,0xb0,0x03,
+0x34,0xe7,0x00,0x20,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x8f,0xf4,0x00,0x43,0x10,0x21,0x8c,0x48,0x00,0x18,0x3c,0x02,0x80,0x00,
+0x24,0x42,0x1c,0x18,0xac,0xe2,0x00,0x00,0x8d,0x03,0x00,0x08,0x80,0x82,0x00,0x13,
+0x00,0x05,0x2c,0x00,0x00,0x03,0x1e,0x02,0x00,0x02,0x12,0x00,0x30,0x63,0x00,0x7e,
+0x00,0x62,0x18,0x21,0x00,0x65,0x18,0x21,0x3c,0x02,0xc0,0x00,0x3c,0x05,0xb0,0x05,
+0x34,0x42,0x04,0x00,0x24,0x63,0x00,0x01,0x3c,0x07,0xb0,0x05,0x3c,0x08,0xb0,0x05,
+0x34,0xa5,0x04,0x20,0xac,0xa3,0x00,0x00,0x00,0xc2,0x30,0x21,0x34,0xe7,0x04,0x24,
+0x35,0x08,0x02,0x28,0x24,0x02,0x00,0x01,0x24,0x03,0x00,0x20,0xac,0xe6,0x00,0x00,
+0xac,0x82,0x00,0x3c,0x03,0xe0,0x00,0x08,0xa1,0x03,0x00,0x00,0x27,0xbd,0xff,0xa8,
+0x00,0x07,0x60,0x80,0x27,0x82,0xb3,0xf0,0xaf,0xbe,0x00,0x50,0xaf,0xb7,0x00,0x4c,
+0xaf,0xb5,0x00,0x44,0xaf,0xb4,0x00,0x40,0xaf,0xbf,0x00,0x54,0xaf,0xb6,0x00,0x48,
+0xaf,0xb3,0x00,0x3c,0xaf,0xb2,0x00,0x38,0xaf,0xb1,0x00,0x34,0xaf,0xb0,0x00,0x30,
+0x01,0x82,0x10,0x21,0x8c,0x43,0x00,0x00,0x00,0xe0,0x70,0x21,0x3c,0x02,0x80,0x00,
+0x94,0x73,0x00,0x14,0x3c,0x07,0xb0,0x03,0x34,0xe7,0x00,0x20,0x24,0x42,0x1c,0xac,
+0x3c,0x03,0xb0,0x05,0xac,0xe2,0x00,0x00,0x34,0x63,0x01,0x28,0x90,0x67,0x00,0x00,
+0x00,0x13,0xa8,0xc0,0x02,0xb3,0x18,0x21,0x27,0x82,0x8f,0xf4,0x00,0x03,0x18,0x80,
+0x00,0x62,0x18,0x21,0x00,0x05,0x2c,0x00,0x00,0x07,0x3e,0x00,0x28,0xc2,0x00,0x03,
+0x00,0xc0,0xa0,0x21,0x00,0x80,0x78,0x21,0x00,0x05,0xbc,0x03,0x8c,0x68,0x00,0x18,
+0x02,0xa0,0x58,0x21,0x10,0x40,0x01,0x81,0x00,0x07,0xf6,0x03,0x00,0xde,0x10,0x07,
+0x30,0x5e,0x00,0x01,0x01,0x73,0x10,0x21,0x27,0x83,0x8f,0xf8,0x00,0x02,0x10,0x80,
+0x00,0x43,0x10,0x21,0x80,0x4d,0x00,0x06,0x8d,0x03,0x00,0x00,0x8d,0x02,0x00,0x04,
+0x8d,0x0a,0x00,0x08,0x8d,0x03,0x00,0x0c,0xaf,0xa2,0x00,0x20,0x11,0xa0,0x01,0x71,
+0xaf,0xa3,0x00,0x18,0x27,0x82,0xb3,0xf0,0x01,0x82,0x10,0x21,0x8c,0x44,0x00,0x00,
+0x00,0x00,0x00,0x00,0x90,0x83,0x00,0x16,0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x04,
+0x14,0x60,0x00,0x12,0x00,0x00,0xb0,0x21,0x3c,0x02,0xb0,0x09,0x34,0x42,0x01,0x46,
+0x90,0x43,0x00,0x00,0x2a,0x84,0x00,0x04,0x10,0x80,0x01,0x56,0x30,0x65,0x00,0x01,
+0x91,0xe2,0x00,0x09,0x00,0x00,0x00,0x00,0x12,0x82,0x00,0x02,0x00,0x00,0x00,0x00,
+0x00,0x00,0x28,0x21,0x14,0xa0,0x00,0x03,0x00,0x00,0x38,0x21,0x13,0xc0,0x00,0x03,
+0x38,0xf6,0x00,0x01,0x24,0x07,0x00,0x01,0x38,0xf6,0x00,0x01,0x01,0x73,0x10,0x21,
+0x00,0x02,0x30,0x80,0x27,0x83,0x90,0x00,0x00,0xc3,0x48,0x21,0x91,0x25,0x00,0x00,
+0x8f,0xa4,0x00,0x20,0x2c,0xa3,0x00,0x04,0x00,0x04,0x11,0xc3,0x30,0x42,0x00,0x01,
+0x00,0x03,0xb0,0x0b,0x12,0xc0,0x00,0xd8,0xaf,0xa2,0x00,0x24,0x93,0x90,0xbb,0xda,
+0x00,0x0a,0x16,0x42,0x30,0x52,0x00,0x3f,0x2e,0x06,0x00,0x0c,0x10,0xc0,0x00,0xc0,
+0x00,0xa0,0x20,0x21,0x2c,0xa2,0x00,0x10,0x14,0x40,0x00,0x04,0x00,0x90,0x10,0x2b,
+0x30,0xa2,0x00,0x07,0x24,0x44,0x00,0x04,0x00,0x90,0x10,0x2b,0x10,0x40,0x00,0x0b,
+0x01,0x73,0x10,0x21,0x27,0x85,0xbb,0x0c,0x00,0x10,0x10,0x40,0x00,0x50,0x10,0x21,
+0x00,0x45,0x10,0x21,0x90,0x50,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x90,0x18,0x2b,
+0x14,0x60,0xff,0xfa,0x00,0x10,0x10,0x40,0x01,0x73,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x8f,0xf8,0x00,0x43,0x10,0x21,0x31,0xa4,0x00,0x01,0x10,0x80,0x00,0xa5,
+0xa0,0x50,0x00,0x07,0x3c,0x04,0xb0,0x05,0x34,0x84,0x00,0x08,0x24,0x02,0x00,0x01,
+0x3c,0x03,0x80,0x00,0xa1,0xe2,0x00,0x4e,0xac,0x83,0x00,0x00,0x8c,0x85,0x00,0x00,
+0x3c,0x02,0x00,0xf0,0x3c,0x03,0x40,0xf0,0x34,0x42,0xf0,0x00,0x34,0x63,0xf0,0x00,
+0x24,0x17,0x00,0x0e,0x24,0x13,0x01,0x06,0xac,0x82,0x00,0x00,0xac,0x83,0x00,0x00,
+0x27,0x82,0xb3,0xf0,0x01,0x82,0x10,0x21,0x8c,0x43,0x00,0x00,0x24,0x05,0x00,0x01,
+0xaf,0xa5,0x00,0x1c,0x90,0x62,0x00,0x16,0x00,0x13,0xa8,0xc0,0x32,0x51,0x00,0x02,
+0x34,0x42,0x00,0x04,0xa0,0x62,0x00,0x16,0x8f,0xa3,0x00,0x20,0x8f,0xa4,0x00,0x18,
+0x00,0x03,0x13,0x43,0x00,0x04,0x1a,0x02,0x30,0x47,0x00,0x01,0x12,0x20,0x00,0x04,
+0x30,0x64,0x07,0xff,0x2e,0x03,0x00,0x04,0x32,0x42,0x00,0x33,0x00,0x43,0x90,0x0b,
+0x8f,0xa5,0x00,0x24,0x8f,0xa6,0x00,0x1c,0x00,0x12,0x10,0x40,0x00,0x05,0x19,0xc0,
+0x00,0x47,0x10,0x21,0x00,0x06,0x2a,0x80,0x00,0x43,0x10,0x21,0x00,0x10,0x32,0x00,
+0x00,0x04,0x24,0x80,0x02,0x65,0x28,0x21,0x00,0xa4,0x28,0x21,0x00,0x46,0x10,0x21,
+0x00,0x17,0x1c,0x00,0x3c,0x04,0xc0,0x00,0x00,0x43,0x30,0x21,0x16,0x80,0x00,0x29,
+0x00,0xa4,0x28,0x21,0x3c,0x02,0xb0,0x05,0x34,0x42,0x04,0x00,0x3c,0x03,0xb0,0x05,
+0x3c,0x04,0xb0,0x05,0xac,0x46,0x00,0x00,0x34,0x63,0x04,0x04,0x34,0x84,0x02,0x28,
+0x24,0x02,0x00,0x01,0xac,0x65,0x00,0x00,0xa0,0x82,0x00,0x00,0x3c,0x02,0xb0,0x09,
+0x34,0x42,0x01,0x46,0x90,0x44,0x00,0x00,0x91,0xe3,0x00,0x09,0x30,0x86,0x00,0x01,
+0x02,0x83,0x18,0x26,0x00,0x03,0x30,0x0b,0x14,0xc0,0x00,0x03,0x00,0x00,0x28,0x21,
+0x13,0xc0,0x00,0x03,0x02,0xb3,0x10,0x21,0x24,0x05,0x00,0x01,0x02,0xb3,0x10,0x21,
+0x27,0x83,0x8f,0xf8,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x84,0x48,0x00,0x04,
+0x00,0xa0,0x30,0x21,0x00,0xe0,0x20,0x21,0x02,0x80,0x28,0x21,0x02,0xc0,0x38,0x21,
+0x0c,0x00,0x00,0x72,0xaf,0xa8,0x00,0x10,0x7b,0xbe,0x02,0xbc,0x7b,0xb6,0x02,0x7c,
+0x7b,0xb4,0x02,0x3c,0x7b,0xb2,0x01,0xfc,0x7b,0xb0,0x01,0xbc,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x58,0x24,0x02,0x00,0x01,0x12,0x82,0x00,0x3d,0x3c,0x02,0xb0,0x05,
+0x24,0x02,0x00,0x02,0x12,0x82,0x00,0x31,0x3c,0x02,0xb0,0x05,0x24,0x02,0x00,0x03,
+0x12,0x82,0x00,0x25,0x3c,0x02,0xb0,0x05,0x24,0x02,0x00,0x10,0x12,0x82,0x00,0x19,
+0x3c,0x02,0xb0,0x05,0x24,0x02,0x00,0x11,0x12,0x82,0x00,0x0d,0x3c,0x02,0xb0,0x05,
+0x24,0x02,0x00,0x12,0x16,0x82,0xff,0xd1,0x3c,0x02,0xb0,0x05,0x3c,0x03,0xb0,0x05,
+0x34,0x42,0x04,0x20,0x3c,0x04,0xb0,0x05,0x34,0x63,0x04,0x24,0xac,0x46,0x00,0x00,
+0x34,0x84,0x02,0x28,0xac,0x65,0x00,0x00,0x08,0x00,0x07,0xe2,0x24,0x02,0x00,0x20,
+0x34,0x42,0x04,0x40,0x3c,0x03,0xb0,0x05,0x3c,0x04,0xb0,0x05,0xac,0x46,0x00,0x00,
+0x34,0x63,0x04,0x44,0x34,0x84,0x02,0x28,0x24,0x02,0x00,0x40,0x08,0x00,0x07,0xe2,
+0xac,0x65,0x00,0x00,0x34,0x42,0x04,0x28,0x3c,0x03,0xb0,0x05,0x3c,0x04,0xb0,0x05,
+0xac,0x46,0x00,0x00,0x34,0x63,0x04,0x2c,0x34,0x84,0x02,0x28,0x24,0x02,0xff,0x80,
+0x08,0x00,0x07,0xe2,0xac,0x65,0x00,0x00,0x34,0x42,0x04,0x18,0x3c,0x03,0xb0,0x05,
+0x3c,0x04,0xb0,0x05,0xac,0x46,0x00,0x00,0x34,0x63,0x04,0x1c,0x34,0x84,0x02,0x28,
+0x24,0x02,0x00,0x08,0x08,0x00,0x07,0xe2,0xac,0x65,0x00,0x00,0x34,0x42,0x04,0x10,
+0x3c,0x03,0xb0,0x05,0x3c,0x04,0xb0,0x05,0xac,0x46,0x00,0x00,0x34,0x63,0x04,0x14,
+0x34,0x84,0x02,0x28,0x24,0x02,0x00,0x04,0x08,0x00,0x07,0xe2,0xac,0x65,0x00,0x00,
+0x34,0x42,0x04,0x08,0x3c,0x03,0xb0,0x05,0x3c,0x04,0xb0,0x05,0xac,0x46,0x00,0x00,
+0x34,0x63,0x04,0x0c,0x34,0x84,0x02,0x28,0x24,0x02,0x00,0x02,0x08,0x00,0x07,0xe2,
+0xac,0x65,0x00,0x00,0x24,0x17,0x00,0x14,0x08,0x00,0x07,0xb4,0x24,0x13,0x01,0x02,
+0x30,0xa2,0x00,0x07,0x24,0x44,0x00,0x0c,0x00,0x90,0x18,0x2b,0x10,0x60,0x00,0x0c,
+0x26,0x02,0x00,0x04,0x27,0x85,0xbb,0x0c,0x00,0x10,0x10,0x40,0x00,0x50,0x10,0x21,
+0x00,0x45,0x10,0x21,0x90,0x50,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x90,0x18,0x2b,
+0x14,0x60,0xff,0xfa,0x00,0x10,0x10,0x40,0x2e,0x06,0x00,0x0c,0x26,0x02,0x00,0x04,
+0x08,0x00,0x07,0x9e,0x00,0x46,0x80,0x0a,0x27,0x82,0xb3,0xf0,0x01,0x82,0x20,0x21,
+0x8c,0x87,0x00,0x00,0x00,0x00,0x00,0x00,0x90,0xe2,0x00,0x19,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x07,0x00,0x00,0x00,0x00,0x27,0x82,0x90,0x10,0x00,0xc2,0x10,0x21,
+0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x60,0x00,0x14,0x00,0x00,0x00,0x00,
+0x90,0xe3,0x00,0x16,0x27,0x82,0x8f,0xf8,0x00,0xc2,0x10,0x21,0x34,0x63,0x00,0x20,
+0x90,0x50,0x00,0x07,0xa0,0xe3,0x00,0x16,0x8c,0x84,0x00,0x00,0x00,0x0a,0x1e,0x42,
+0x24,0x06,0x00,0x01,0x90,0x82,0x00,0x16,0x30,0x71,0x00,0x02,0x30,0x72,0x00,0x3f,
+0x30,0x42,0x00,0xfb,0x24,0x17,0x00,0x18,0x24,0x13,0x01,0x03,0x24,0x15,0x08,0x18,
+0xaf,0xa6,0x00,0x1c,0x08,0x00,0x07,0xbe,0xa0,0x82,0x00,0x16,0x8d,0x02,0x00,0x04,
+0x00,0x0a,0x1c,0x42,0x30,0x42,0x00,0x10,0x14,0x40,0x00,0x15,0x30,0x72,0x00,0x3f,
+0x81,0x22,0x00,0x05,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x11,0x30,0x72,0x00,0x3e,
+0x27,0x83,0x90,0x08,0x00,0xc3,0x18,0x21,0x80,0x64,0x00,0x00,0x27,0x83,0xb5,0x68,
+0x00,0x04,0x11,0x00,0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x23,
+0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x90,0x44,0x00,0x05,0x90,0x43,0x00,0x04,
+0x00,0x00,0x00,0x00,0x00,0x64,0x18,0x24,0x30,0x63,0x00,0x01,0x02,0x43,0x90,0x25,
+0x27,0x85,0xb3,0xf0,0x01,0x85,0x28,0x21,0x8c,0xa6,0x00,0x00,0x01,0x73,0x10,0x21,
+0x27,0x83,0x90,0x00,0x90,0xc4,0x00,0x16,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,
+0x30,0x84,0x00,0xdf,0x90,0x50,0x00,0x00,0xa0,0xc4,0x00,0x16,0x80,0xc6,0x00,0x12,
+0x8c,0xa3,0x00,0x00,0x2d,0xc4,0x00,0x02,0xaf,0xa6,0x00,0x1c,0x90,0x62,0x00,0x16,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xfb,0x14,0x80,0x00,0x06,0xa0,0x62,0x00,0x16,
+0x24,0x02,0x00,0x06,0x11,0xc2,0x00,0x03,0x24,0x02,0x00,0x04,0x15,0xc2,0xff,0x0e,
+0x32,0x51,0x00,0x02,0x32,0x51,0x00,0x02,0x2e,0x02,0x00,0x0c,0x14,0x40,0x00,0x0f,
+0x00,0x11,0x18,0x2b,0x32,0x02,0x00,0x0f,0x34,0x42,0x00,0x10,0x00,0x03,0x19,0x00,
+0x00,0x43,0x18,0x21,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0xb8,0xa0,0x43,0x00,0x00,
+0x00,0x00,0x20,0x21,0x02,0x00,0x28,0x21,0x0c,0x00,0x02,0x05,0xaf,0xaf,0x00,0x28,
+0x8f,0xaf,0x00,0x28,0x08,0x00,0x07,0xbe,0x00,0x00,0x00,0x00,0x08,0x00,0x08,0xb9,
+0x32,0x03,0x00,0xff,0x3c,0x03,0xb0,0x05,0x34,0x63,0x02,0x42,0x90,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x0f,0x14,0x40,0xfe,0xaa,0x00,0x00,0x00,0x00,
+0x91,0xe2,0x00,0x09,0x00,0x00,0x00,0x00,0x02,0x82,0x10,0x26,0x08,0x00,0x07,0x75,
+0x00,0x02,0x28,0x0b,0x08,0x00,0x07,0x7b,0x00,0x00,0xb0,0x21,0x24,0x02,0x00,0x10,
+0x10,0xc2,0x00,0x08,0x24,0x02,0x00,0x11,0x10,0xc2,0xfe,0x7d,0x00,0x07,0x17,0x83,
+0x24,0x02,0x00,0x12,0x14,0xc2,0xfe,0x7b,0x00,0x07,0x17,0x43,0x08,0x00,0x07,0x55,
+0x30,0x5e,0x00,0x01,0x08,0x00,0x07,0x55,0x00,0x07,0xf7,0xc2,0x00,0x04,0x10,0x40,
+0x27,0x83,0x80,0x1c,0x00,0x43,0x10,0x21,0x00,0x80,0x40,0x21,0x94,0x44,0x00,0x00,
+0x2d,0x07,0x00,0x04,0x24,0xc2,0x00,0x03,0x00,0x47,0x30,0x0a,0x00,0x86,0x00,0x18,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x23,0x7c,
+0xac,0x62,0x00,0x00,0x2d,0x06,0x00,0x10,0x00,0x00,0x20,0x12,0x00,0x04,0x22,0x42,
+0x24,0x84,0x00,0x01,0x24,0x83,0x00,0xc0,0x10,0xe0,0x00,0x0b,0x24,0x82,0x00,0x60,
+0x00,0x40,0x20,0x21,0x00,0x65,0x20,0x0a,0x3c,0x03,0xb0,0x03,0x34,0x63,0x01,0x00,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,0x00,0x44,0x20,0x04,
+0x03,0xe0,0x00,0x08,0x00,0x80,0x10,0x21,0x24,0x85,0x00,0x28,0x24,0x83,0x00,0x24,
+0x31,0x02,0x00,0x08,0x14,0xc0,0xff,0xf4,0x24,0x84,0x00,0x14,0x00,0x60,0x20,0x21,
+0x08,0x00,0x08,0xf6,0x00,0xa2,0x20,0x0b,0x27,0xbd,0xff,0xe0,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x00,0xaf,0xb0,0x00,0x10,0x24,0x42,0x24,0x18,0x00,0x80,0x80,0x21,
+0x34,0x63,0x00,0x20,0x3c,0x04,0xb0,0x03,0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,
+0xaf,0xbf,0x00,0x1c,0x83,0xb1,0x00,0x33,0x83,0xa8,0x00,0x37,0x34,0x84,0x01,0x10,
+0xac,0x62,0x00,0x00,0x2e,0x02,0x00,0x10,0x00,0xe0,0x90,0x21,0x8c,0x87,0x00,0x00,
+0x14,0x40,0x00,0x0c,0x2e,0x02,0x00,0x0c,0x3c,0x02,0x00,0x0f,0x34,0x42,0xf0,0x00,
+0x00,0xe2,0x10,0x24,0x14,0x40,0x00,0x37,0x32,0x02,0x00,0x08,0x32,0x02,0x00,0x07,
+0x27,0x83,0x80,0xcc,0x00,0x43,0x10,0x21,0x90,0x50,0x00,0x00,0x00,0x00,0x00,0x00,
+0x2e,0x02,0x00,0x0c,0x14,0x40,0x00,0x03,0x02,0x00,0x20,0x21,0x32,0x02,0x00,0x0f,
+0x24,0x44,0x00,0x0c,0x00,0x87,0x10,0x06,0x30,0x42,0x00,0x01,0x14,0x40,0x00,0x07,
+0x2c,0x82,0x00,0x0c,0x00,0x04,0x10,0x80,0x27,0x83,0xb4,0x40,0x00,0x43,0x10,0x21,
+0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x2c,0x82,0x00,0x0c,0x14,0x40,0x00,0x05,
+0x00,0x05,0x10,0x40,0x00,0x46,0x10,0x21,0x00,0x02,0x11,0x00,0x00,0x82,0x10,0x21,
+0x24,0x44,0x00,0x04,0x15,0x00,0x00,0x02,0x24,0x06,0x00,0x20,0x24,0x06,0x00,0x0e,
+0x0c,0x00,0x08,0xdf,0x00,0x00,0x00,0x00,0x00,0x40,0x30,0x21,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x01,0x00,0x90,0x43,0x00,0x00,0x2e,0x04,0x00,0x04,0x24,0x02,0x00,0x10,
+0x24,0x05,0x00,0x0a,0x00,0x44,0x28,0x0a,0x30,0x63,0x00,0x01,0x14,0x60,0x00,0x02,
+0x00,0x05,0x10,0x40,0x00,0xa0,0x10,0x21,0x30,0x45,0x00,0xff,0x00,0xc5,0x10,0x21,
+0x24,0x46,0x00,0x46,0x02,0x26,0x18,0x04,0xa6,0x43,0x00,0x00,0x8f,0xbf,0x00,0x1c,
+0x8f,0xb2,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x00,0xc0,0x10,0x21,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x20,0x10,0x40,0xff,0xcf,0x2e,0x02,0x00,0x0c,0x32,0x02,0x00,0x07,
+0x27,0x83,0x80,0xc4,0x00,0x43,0x10,0x21,0x90,0x44,0x00,0x00,0x08,0x00,0x09,0x24,
+0x02,0x04,0x80,0x23,0x27,0xbd,0xff,0xb8,0x00,0x05,0x38,0x80,0x27,0x82,0xb3,0xf0,
+0xaf,0xbe,0x00,0x40,0xaf,0xb6,0x00,0x38,0xaf,0xb3,0x00,0x2c,0xaf,0xbf,0x00,0x44,
+0xaf,0xb7,0x00,0x3c,0xaf,0xb5,0x00,0x34,0xaf,0xb4,0x00,0x30,0xaf,0xb2,0x00,0x28,
+0xaf,0xb1,0x00,0x24,0xaf,0xb0,0x00,0x20,0x00,0xe2,0x38,0x21,0x8c,0xe6,0x00,0x00,
+0xaf,0xa5,0x00,0x4c,0x3c,0x02,0x80,0x00,0x3c,0x05,0xb0,0x03,0x34,0xa5,0x00,0x20,
+0x24,0x42,0x25,0x74,0x24,0x03,0x00,0x01,0xac,0xa2,0x00,0x00,0xa0,0xc3,0x00,0x12,
+0x8c,0xe5,0x00,0x00,0x94,0xc3,0x00,0x06,0x90,0xa2,0x00,0x16,0xa4,0xc3,0x00,0x14,
+0x27,0x83,0x8f,0xf0,0x34,0x42,0x00,0x08,0xa0,0xa2,0x00,0x16,0x8c,0xe8,0x00,0x00,
+0xaf,0xa4,0x00,0x48,0x27,0x82,0x8f,0xf4,0x95,0x11,0x00,0x14,0x00,0x00,0x00,0x00,
+0x00,0x11,0x98,0xc0,0x02,0x71,0x20,0x21,0x00,0x04,0x20,0x80,0x00,0x82,0x10,0x21,
+0x8c,0x52,0x00,0x18,0x00,0x83,0x18,0x21,0x84,0x75,0x00,0x06,0x8e,0x45,0x00,0x08,
+0x8e,0x46,0x00,0x04,0x8e,0x47,0x00,0x04,0x00,0x05,0x1c,0x82,0x00,0x06,0x31,0x42,
+0x27,0x82,0x90,0x00,0x30,0x63,0x00,0x01,0x30,0xc6,0x00,0x01,0x00,0x82,0x20,0x21,
+0xa5,0x15,0x00,0x1a,0x00,0x05,0x14,0x42,0xaf,0xa3,0x00,0x18,0xaf,0xa6,0x00,0x1c,
+0x30,0xe7,0x00,0x10,0x30,0x56,0x00,0x01,0x80,0x97,0x00,0x06,0x14,0xe0,0x00,0x47,
+0x00,0x05,0xf7,0xc2,0x80,0x82,0x00,0x05,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x44,
+0x02,0x71,0x10,0x21,0x93,0x90,0xbb,0xd9,0x00,0x00,0x00,0x00,0x2e,0x02,0x00,0x0c,
+0x14,0x40,0x00,0x06,0x02,0x00,0x20,0x21,0x00,0x16,0x10,0x40,0x00,0x43,0x10,0x21,
+0x00,0x02,0x11,0x00,0x02,0x02,0x10,0x21,0x24,0x44,0x00,0x04,0x02,0x71,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x90,0x00,0x00,0x43,0x10,0x21,0x00,0x80,0x80,0x21,
+0xa0,0x44,0x00,0x03,0xa0,0x44,0x00,0x00,0x02,0x00,0x20,0x21,0x02,0xc0,0x28,0x21,
+0x0c,0x00,0x08,0xdf,0x02,0xa0,0x30,0x21,0x02,0x71,0x18,0x21,0x00,0x03,0x88,0x80,
+0x00,0x40,0xa0,0x21,0x27,0x82,0x90,0x10,0x02,0x22,0x10,0x21,0x8c,0x44,0x00,0x00,
+0x26,0xe3,0x00,0x02,0x00,0x03,0x17,0xc2,0x00,0x62,0x18,0x21,0x00,0x04,0x25,0xc2,
+0x00,0x03,0x18,0x43,0x30,0x84,0x00,0x01,0x00,0x03,0x18,0x40,0x03,0xc4,0x20,0x24,
+0x14,0x80,0x00,0x15,0x02,0x43,0x38,0x21,0x3c,0x08,0xb0,0x03,0x35,0x08,0x00,0x28,
+0x8d,0x03,0x00,0x00,0x8f,0xa6,0x00,0x4c,0x8f,0xa4,0x00,0x48,0x27,0x82,0x8f,0xf8,
+0x02,0x22,0x10,0x21,0x24,0x63,0x00,0x01,0x02,0xa0,0x28,0x21,0xa4,0x54,0x00,0x04,
+0x00,0xc0,0x38,0x21,0x0c,0x00,0x07,0x2b,0xad,0x03,0x00,0x00,0x7b,0xbe,0x02,0x3c,
+0x7b,0xb6,0x01,0xfc,0x7b,0xb4,0x01,0xbc,0x7b,0xb2,0x01,0x7c,0x7b,0xb0,0x01,0x3c,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x48,0x8f,0xa2,0x00,0x1c,0x8f,0xa6,0x00,0x18,
+0x02,0x00,0x20,0x21,0x02,0xc0,0x28,0x21,0xaf,0xa2,0x00,0x10,0x0c,0x00,0x09,0x06,
+0xaf,0xa0,0x00,0x14,0x08,0x00,0x09,0xc2,0x02,0x82,0xa0,0x21,0x02,0x71,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x90,0x00,0x00,0x43,0x10,0x21,0x90,0x50,0x00,0x00,
+0x08,0x00,0x09,0xae,0xa0,0x50,0x00,0x03,0x27,0xbd,0xff,0xb8,0xaf,0xb1,0x00,0x24,
+0x8f,0xb1,0x00,0x5c,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,
+0x24,0x42,0x27,0x98,0xaf,0xbe,0x00,0x40,0xaf,0xb7,0x00,0x3c,0xaf,0xb6,0x00,0x38,
+0xaf,0xb5,0x00,0x34,0xaf,0xb4,0x00,0x30,0xaf,0xa5,0x00,0x4c,0x8f,0xb5,0x00,0x58,
+0xaf,0xbf,0x00,0x44,0xaf,0xb3,0x00,0x2c,0xaf,0xb2,0x00,0x28,0xaf,0xb0,0x00,0x20,
+0x00,0xe0,0xb0,0x21,0xac,0x62,0x00,0x00,0x00,0x80,0xf0,0x21,0x00,0x00,0xb8,0x21,
+0x16,0x20,0x00,0x2b,0x00,0x00,0xa0,0x21,0x27,0x85,0xb3,0xf0,0x00,0x07,0x10,0x80,
+0x00,0x45,0x10,0x21,0x8c,0x53,0x00,0x00,0x00,0x15,0x18,0x80,0x00,0x65,0x18,0x21,
+0x92,0x62,0x00,0x16,0x8c,0x72,0x00,0x00,0x30,0x42,0x00,0x03,0x14,0x40,0x00,0x2d,
+0x00,0x00,0x00,0x00,0x92,0x42,0x00,0x16,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x03,
+0x14,0x40,0x00,0x28,0x00,0x00,0x00,0x00,0x8c,0x82,0x00,0x34,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x18,0x02,0x20,0x10,0x21,0x8c,0x82,0x00,0x38,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x14,0x02,0x20,0x10,0x21,0x8c,0x82,0x00,0x3c,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x0f,0x3c,0x03,0xb0,0x09,0x3c,0x05,0xb0,0x05,0x34,0x63,0x01,0x44,
+0x34,0xa5,0x02,0x52,0x94,0x66,0x00,0x00,0x90,0xa2,0x00,0x00,0x8f,0xa3,0x00,0x4c,
+0x00,0x00,0x00,0x00,0x00,0x62,0x10,0x06,0x30,0x42,0x00,0x01,0x10,0x40,0x00,0x04,
+0x30,0xc6,0xff,0xff,0x2c,0xc2,0x00,0x41,0x10,0x40,0x00,0x09,0x24,0x05,0x00,0x14,
+0x02,0x20,0x10,0x21,0x7b,0xbe,0x02,0x3c,0x7b,0xb6,0x01,0xfc,0x7b,0xb4,0x01,0xbc,
+0x7b,0xb2,0x01,0x7c,0x7b,0xb0,0x01,0x3c,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x48,
+0x0c,0x00,0x07,0x06,0x24,0x06,0x01,0x07,0x24,0x02,0x00,0x01,0x08,0x00,0x0a,0x28,
+0xa3,0xc2,0x00,0x11,0x10,0xc0,0x00,0x1c,0x24,0x02,0x00,0x01,0x10,0xc2,0x00,0x17,
+0x00,0xc0,0x88,0x21,0x96,0x54,0x00,0x1a,0x02,0xa0,0xb8,0x21,0x12,0x20,0xff,0xed,
+0x02,0x20,0x10,0x21,0x27,0x83,0xb3,0xf0,0x00,0x17,0x10,0x80,0x00,0x43,0x10,0x21,
+0x8c,0x44,0x00,0x00,0x3c,0x03,0xb0,0x03,0x34,0x63,0x00,0x28,0x80,0x86,0x00,0x12,
+0x8c,0x62,0x00,0x00,0x00,0x14,0x2c,0x00,0x00,0x05,0x2c,0x03,0x00,0x46,0x10,0x21,
+0x8f,0xa6,0x00,0x4c,0x02,0xe0,0x38,0x21,0x03,0xc0,0x20,0x21,0x0c,0x00,0x07,0x2b,
+0xac,0x62,0x00,0x00,0x08,0x00,0x0a,0x28,0xaf,0xd1,0x00,0x40,0x96,0x74,0x00,0x1a,
+0x08,0x00,0x0a,0x3b,0x02,0xc0,0xb8,0x21,0x3c,0x02,0xb0,0x03,0x34,0x42,0x01,0x08,
+0x8c,0x50,0x00,0x00,0x02,0x60,0x20,0x21,0x0c,0x00,0x1f,0x11,0x02,0x00,0x28,0x21,
+0x30,0x42,0x00,0xff,0x02,0x00,0x28,0x21,0x02,0x40,0x20,0x21,0x0c,0x00,0x1f,0x11,
+0xaf,0xa2,0x00,0x18,0x8f,0xa4,0x00,0x18,0x00,0x00,0x00,0x00,0x10,0x80,0x00,0xed,
+0x30,0x50,0x00,0xff,0x12,0x00,0x00,0x18,0x24,0x11,0x00,0x01,0x96,0x63,0x00,0x14,
+0x96,0x44,0x00,0x14,0x27,0x85,0x8f,0xf0,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x45,0x10,0x21,0x00,0x04,0x18,0xc0,0x8c,0x46,0x00,0x08,
+0x00,0x64,0x18,0x21,0x00,0x03,0x18,0x80,0x00,0x65,0x18,0x21,0x00,0x06,0x17,0x02,
+0x24,0x04,0x00,0xff,0x8c,0x63,0x00,0x08,0x10,0x44,0x00,0xd6,0x00,0x03,0x17,0x02,
+0x10,0x44,0x00,0xd5,0x3c,0x02,0x80,0x00,0x00,0x66,0x18,0x2b,0x24,0x11,0x00,0x02,
+0x24,0x02,0x00,0x01,0x00,0x43,0x88,0x0a,0x24,0x02,0x00,0x01,0x12,0x22,0x00,0x5a,
+0x24,0x02,0x00,0x02,0x16,0x22,0xff,0xbd,0x00,0x00,0x00,0x00,0x96,0x49,0x00,0x14,
+0x27,0x82,0x8f,0xf4,0x02,0xa0,0xb8,0x21,0x00,0x09,0x50,0xc0,0x01,0x49,0x18,0x21,
+0x00,0x03,0x40,0x80,0x01,0x02,0x10,0x21,0x8c,0x43,0x00,0x18,0x00,0x00,0x00,0x00,
+0x8c,0x65,0x00,0x08,0x8c,0x62,0x00,0x0c,0x8c,0x62,0x00,0x04,0x00,0x05,0x24,0x42,
+0x00,0x05,0x1c,0x82,0x30,0x42,0x00,0x10,0x30,0x66,0x00,0x01,0x14,0x40,0x00,0x41,
+0x30,0x87,0x00,0x01,0x27,0x82,0x90,0x08,0x01,0x02,0x10,0x21,0x80,0x44,0x00,0x00,
+0x27,0x82,0xb5,0x68,0x00,0x04,0x19,0x00,0x00,0x64,0x18,0x23,0x00,0x03,0x18,0x80,
+0x00,0x64,0x18,0x23,0x00,0x03,0x18,0x80,0x00,0x62,0x10,0x21,0x90,0x45,0x00,0x05,
+0x27,0x84,0xb4,0x90,0x00,0x64,0x18,0x21,0x90,0x63,0x00,0x00,0x10,0xa0,0x00,0x2b,
+0x2c,0x64,0x00,0x0c,0x14,0x80,0x00,0x04,0x00,0x60,0x10,0x21,0x00,0x06,0x11,0x00,
+0x00,0x62,0x10,0x21,0x24,0x42,0x00,0x24,0x3c,0x01,0xb0,0x03,0xa0,0x22,0x00,0xb9,
+0x14,0x80,0x00,0x06,0x00,0x60,0x28,0x21,0x00,0x07,0x10,0x40,0x00,0x46,0x10,0x21,
+0x00,0x02,0x11,0x00,0x00,0x62,0x10,0x21,0x24,0x45,0x00,0x04,0x01,0x49,0x10,0x21,
+0x27,0x83,0x90,0x00,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x00,0xa0,0x18,0x21,
+0xa0,0x45,0x00,0x03,0xa0,0x45,0x00,0x00,0x24,0x02,0x00,0x08,0x12,0x02,0x00,0x0b,
+0x24,0x02,0x00,0x01,0x00,0x60,0x28,0x21,0x02,0x40,0x20,0x21,0x0c,0x00,0x1f,0x8d,
+0xaf,0xa2,0x00,0x10,0x30,0x54,0xff,0xff,0x92,0x42,0x00,0x16,0x00,0x00,0x00,0x00,
+0x02,0x02,0x10,0x25,0x08,0x00,0x0a,0x3b,0xa2,0x42,0x00,0x16,0x00,0x60,0x28,0x21,
+0x02,0x40,0x20,0x21,0x0c,0x00,0x1f,0x3e,0xaf,0xa0,0x00,0x10,0x08,0x00,0x0a,0xbe,
+0x30,0x54,0xff,0xff,0x08,0x00,0x0a,0xa6,0x00,0x60,0x10,0x21,0x14,0x80,0xff,0xfd,
+0x00,0x00,0x00,0x00,0x00,0x06,0x11,0x00,0x00,0x62,0x10,0x21,0x08,0x00,0x0a,0xa6,
+0x24,0x42,0x00,0x04,0x27,0x82,0x90,0x00,0x01,0x02,0x10,0x21,0x90,0x43,0x00,0x00,
+0x08,0x00,0x0a,0xb6,0xa0,0x43,0x00,0x03,0x96,0x69,0x00,0x14,0x02,0xc0,0xb8,0x21,
+0x24,0x0b,0x00,0x01,0x00,0x09,0x10,0xc0,0x00,0x49,0x18,0x21,0x00,0x03,0x40,0x80,
+0x00,0x40,0x50,0x21,0x27,0x82,0x8f,0xf4,0x01,0x02,0x10,0x21,0x8c,0x43,0x00,0x18,
+0x00,0x00,0x00,0x00,0x8c,0x65,0x00,0x08,0x8c,0x62,0x00,0x0c,0x8c,0x62,0x00,0x04,
+0x00,0x05,0x24,0x42,0x00,0x05,0x1c,0x82,0x30,0x42,0x00,0x10,0x30,0x66,0x00,0x01,
+0x10,0x40,0x00,0x0d,0x30,0x87,0x00,0x01,0x27,0x82,0x90,0x08,0x01,0x02,0x10,0x21,
+0x80,0x43,0x00,0x00,0x00,0x00,0x58,0x21,0x00,0x03,0x11,0x00,0x00,0x43,0x10,0x23,
+0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x23,0x00,0x02,0x10,0x80,0x27,0x83,0xb5,0x60,
+0x00,0x43,0x10,0x21,0xa0,0x40,0x00,0x04,0x11,0x60,0x00,0x4f,0x00,0x00,0x00,0x00,
+0x01,0x49,0x10,0x21,0x00,0x02,0x20,0x80,0x27,0x85,0x90,0x00,0x00,0x85,0x10,0x21,
+0x80,0x43,0x00,0x05,0x00,0x00,0x00,0x00,0x14,0x60,0x00,0x42,0x01,0x49,0x10,0x21,
+0x27,0x82,0x90,0x08,0x00,0x82,0x10,0x21,0x80,0x44,0x00,0x00,0x27,0x82,0xb5,0x68,
+0x00,0x04,0x19,0x00,0x00,0x64,0x18,0x23,0x00,0x03,0x18,0x80,0x00,0x64,0x18,0x23,
+0x00,0x03,0x18,0x80,0x00,0x62,0x10,0x21,0x90,0x45,0x00,0x05,0x27,0x84,0xb4,0x90,
+0x00,0x64,0x18,0x21,0x90,0x63,0x00,0x00,0x10,0xa0,0x00,0x2c,0x2c,0x64,0x00,0x0c,
+0x14,0x80,0x00,0x04,0x00,0x60,0x10,0x21,0x00,0x06,0x11,0x00,0x00,0x62,0x10,0x21,
+0x24,0x42,0x00,0x24,0x3c,0x01,0xb0,0x03,0xa0,0x22,0x00,0xb9,0x14,0x80,0x00,0x06,
+0x00,0x60,0x28,0x21,0x00,0x07,0x10,0x40,0x00,0x46,0x10,0x21,0x00,0x02,0x11,0x00,
+0x00,0x62,0x10,0x21,0x24,0x45,0x00,0x04,0x01,0x49,0x10,0x21,0x27,0x83,0x90,0x00,
+0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x00,0xa0,0x18,0x21,0xa0,0x45,0x00,0x03,
+0xa0,0x45,0x00,0x00,0x8f,0xa4,0x00,0x18,0x24,0x02,0x00,0x08,0x10,0x82,0x00,0x0c,
+0x00,0x60,0x28,0x21,0x24,0x02,0x00,0x01,0x02,0x60,0x20,0x21,0x0c,0x00,0x1f,0x8d,
+0xaf,0xa2,0x00,0x10,0x8f,0xa3,0x00,0x18,0x30,0x54,0xff,0xff,0x92,0x62,0x00,0x16,
+0x00,0x00,0x00,0x00,0x00,0x62,0x10,0x25,0x08,0x00,0x0a,0x3b,0xa2,0x62,0x00,0x16,
+0x02,0x60,0x20,0x21,0x0c,0x00,0x1f,0x3e,0xaf,0xa0,0x00,0x10,0x08,0x00,0x0b,0x2d,
+0x00,0x00,0x00,0x00,0x08,0x00,0x0b,0x15,0x00,0x60,0x10,0x21,0x14,0x80,0xff,0xfd,
+0x00,0x00,0x00,0x00,0x00,0x06,0x11,0x00,0x00,0x62,0x10,0x21,0x08,0x00,0x0b,0x15,
+0x24,0x42,0x00,0x04,0x00,0x02,0x10,0x80,0x00,0x45,0x10,0x21,0x90,0x43,0x00,0x00,
+0x08,0x00,0x0b,0x25,0xa0,0x43,0x00,0x03,0x27,0x85,0x90,0x00,0x08,0x00,0x0b,0x41,
+0x01,0x49,0x10,0x21,0x3c,0x02,0x80,0x00,0x00,0x62,0x18,0x26,0x08,0x00,0x0a,0x76,
+0x00,0xc2,0x30,0x26,0x12,0x00,0xff,0x2d,0x24,0x02,0x00,0x01,0x08,0x00,0x0a,0x7b,
+0x24,0x11,0x00,0x02,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xd0,
+0x24,0x42,0x2d,0x44,0x34,0x63,0x00,0x20,0x3c,0x05,0xb0,0x05,0xaf,0xb3,0x00,0x24,
+0xaf,0xb2,0x00,0x20,0xaf,0xb1,0x00,0x1c,0xaf,0xbf,0x00,0x28,0xaf,0xb0,0x00,0x18,
+0xac,0x62,0x00,0x00,0x34,0xa5,0x02,0x42,0x90,0xa2,0x00,0x00,0x00,0x80,0x90,0x21,
+0x24,0x11,0x00,0x10,0x30,0x53,0x00,0xff,0x24,0x02,0x00,0x10,0x12,0x22,0x00,0xcf,
+0x00,0x00,0x18,0x21,0x24,0x02,0x00,0x11,0x12,0x22,0x00,0xc1,0x24,0x02,0x00,0x12,
+0x12,0x22,0x00,0xb4,0x00,0x00,0x00,0x00,0x14,0x60,0x00,0xad,0xae,0x43,0x00,0x40,
+0x3c,0x02,0xb0,0x05,0x34,0x42,0x02,0x2c,0x8c,0x44,0x00,0x00,0x3c,0x03,0x00,0x02,
+0x34,0x63,0x00,0xff,0x00,0x83,0x80,0x24,0x00,0x10,0x14,0x43,0x10,0x40,0x00,0x05,
+0x00,0x00,0x00,0x00,0x8e,0x42,0x00,0x34,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x92,
+0x00,0x00,0x00,0x00,0x93,0x83,0x8b,0x61,0x00,0x00,0x00,0x00,0x30,0x62,0x00,0x02,
+0x10,0x40,0x00,0x04,0x32,0x10,0x00,0xff,0x00,0x10,0x11,0xc3,0x14,0x40,0x00,0x86,
+0x00,0x00,0x00,0x00,0x16,0x00,0x00,0x15,0x02,0x00,0x10,0x21,0x26,0x22,0x00,0x01,
+0x30,0x51,0x00,0xff,0x2e,0x23,0x00,0x13,0x14,0x60,0xff,0xdb,0x24,0x03,0x00,0x02,
+0x12,0x63,0x00,0x73,0x24,0x02,0x00,0x05,0x2a,0x62,0x00,0x03,0x10,0x40,0x00,0x58,
+0x24,0x02,0x00,0x04,0x24,0x02,0x00,0x01,0x12,0x62,0x00,0x4b,0x02,0x40,0x20,0x21,
+0x3c,0x02,0xb0,0x05,0x34,0x42,0x02,0x2c,0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x70,0x00,0xff,0x12,0x00,0x00,0x06,0x02,0x00,0x10,0x21,0x8f,0xbf,0x00,0x28,
+0x7b,0xb2,0x01,0x3c,0x7b,0xb0,0x00,0xfc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x30,
+0x92,0x46,0x00,0x04,0x8e,0x43,0x00,0x24,0x24,0x02,0x00,0x07,0x02,0x40,0x20,0x21,
+0x00,0x00,0x28,0x21,0x24,0x07,0x00,0x06,0xaf,0xa2,0x00,0x10,0x0c,0x00,0x09,0xe6,
+0xaf,0xa3,0x00,0x14,0xae,0x42,0x00,0x24,0x3c,0x02,0xb0,0x05,0x8c,0x42,0x02,0x2c,
+0x00,0x00,0x00,0x00,0x30,0x50,0x00,0xff,0x16,0x00,0xff,0xec,0x02,0x00,0x10,0x21,
+0x92,0x46,0x00,0x05,0x8e,0x43,0x00,0x28,0x24,0x02,0x00,0x05,0x02,0x40,0x20,0x21,
+0x24,0x05,0x00,0x01,0x24,0x07,0x00,0x04,0xaf,0xa2,0x00,0x10,0x0c,0x00,0x09,0xe6,
+0xaf,0xa3,0x00,0x14,0xae,0x42,0x00,0x28,0x3c,0x02,0xb0,0x05,0x8c,0x42,0x02,0x2c,
+0x00,0x00,0x00,0x00,0x30,0x50,0x00,0xff,0x16,0x00,0xff,0xdc,0x02,0x00,0x10,0x21,
+0x92,0x46,0x00,0x06,0x8e,0x43,0x00,0x2c,0x24,0x02,0x00,0x03,0x02,0x40,0x20,0x21,
+0x24,0x05,0x00,0x02,0x00,0x00,0x38,0x21,0xaf,0xa2,0x00,0x10,0x0c,0x00,0x09,0xe6,
+0xaf,0xa3,0x00,0x14,0xae,0x42,0x00,0x2c,0x3c,0x02,0xb0,0x05,0x8c,0x42,0x02,0x2c,
+0x00,0x00,0x00,0x00,0x30,0x50,0x00,0xff,0x16,0x00,0xff,0xcc,0x02,0x00,0x10,0x21,
+0x92,0x46,0x00,0x07,0x8e,0x43,0x00,0x30,0x24,0x02,0x00,0x02,0x02,0x40,0x20,0x21,
+0x24,0x05,0x00,0x03,0x24,0x07,0x00,0x01,0xaf,0xa2,0x00,0x10,0x0c,0x00,0x09,0xe6,
+0xaf,0xa3,0x00,0x14,0xae,0x42,0x00,0x30,0x3c,0x02,0xb0,0x05,0x8c,0x42,0x02,0x2c,
+0x08,0x00,0x0b,0x97,0x30,0x42,0x00,0xff,0x92,0x46,0x00,0x04,0x8e,0x43,0x00,0x24,
+0x24,0x02,0x00,0x07,0x00,0x00,0x28,0x21,0x24,0x07,0x00,0x06,0xaf,0xa2,0x00,0x10,
+0x0c,0x00,0x09,0xe6,0xaf,0xa3,0x00,0x14,0x08,0x00,0x0b,0x90,0xae,0x42,0x00,0x24,
+0x12,0x62,0x00,0x0d,0x24,0x02,0x00,0x03,0x24,0x02,0x00,0x08,0x16,0x62,0xff,0xa8,
+0x02,0x40,0x20,0x21,0x92,0x46,0x00,0x07,0x8e,0x42,0x00,0x30,0x24,0x05,0x00,0x03,
+0x24,0x07,0x00,0x01,0xaf,0xa3,0x00,0x10,0x0c,0x00,0x09,0xe6,0xaf,0xa2,0x00,0x14,
+0x08,0x00,0x0b,0x90,0xae,0x42,0x00,0x30,0x92,0x46,0x00,0x06,0x8e,0x43,0x00,0x2c,
+0x02,0x40,0x20,0x21,0x24,0x05,0x00,0x02,0x00,0x00,0x38,0x21,0xaf,0xa2,0x00,0x10,
+0x0c,0x00,0x09,0xe6,0xaf,0xa3,0x00,0x14,0x08,0x00,0x0b,0x90,0xae,0x42,0x00,0x2c,
+0x92,0x46,0x00,0x05,0x8e,0x43,0x00,0x28,0x02,0x40,0x20,0x21,0x24,0x05,0x00,0x01,
+0x24,0x07,0x00,0x04,0xaf,0xa2,0x00,0x10,0x0c,0x00,0x09,0xe6,0xaf,0xa3,0x00,0x14,
+0x08,0x00,0x0b,0x90,0xae,0x42,0x00,0x28,0x0c,0x00,0x01,0x59,0x24,0x04,0x00,0x01,
+0x08,0x00,0x0b,0x81,0x00,0x00,0x00,0x00,0x8f,0x84,0xb4,0x30,0xae,0x40,0x00,0x34,
+0x94,0x85,0x00,0x14,0x0c,0x00,0x1b,0x84,0x00,0x00,0x00,0x00,0x93,0x83,0x8b,0x61,
+0x00,0x00,0x00,0x00,0x30,0x62,0x00,0x02,0x10,0x40,0xff,0x69,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x01,0x59,0x00,0x00,0x20,0x21,0x08,0x00,0x0b,0x79,0x00,0x00,0x00,0x00,
+0x02,0x40,0x20,0x21,0x0c,0x00,0x09,0x5d,0x02,0x20,0x28,0x21,0x08,0x00,0x0b,0x6d,
+0x3c,0x02,0xb0,0x05,0x8e,0x42,0x00,0x3c,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0x4a,
+0x00,0x00,0x00,0x00,0x8f,0x82,0xb4,0x38,0x00,0x00,0x00,0x00,0x90,0x42,0x00,0x0a,
+0x00,0x00,0x00,0x00,0x00,0x02,0x18,0x2b,0x08,0x00,0x0b,0x6a,0xae,0x43,0x00,0x3c,
+0x8e,0x42,0x00,0x38,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0x3d,0x24,0x02,0x00,0x12,
+0x8f,0x82,0xb4,0x34,0x00,0x00,0x00,0x00,0x90,0x42,0x00,0x0a,0x00,0x00,0x00,0x00,
+0x00,0x02,0x18,0x2b,0x08,0x00,0x0b,0x6a,0xae,0x43,0x00,0x38,0x8e,0x42,0x00,0x34,
+0x00,0x00,0x00,0x00,0x14,0x40,0xff,0x30,0x24,0x02,0x00,0x11,0x8f,0x82,0xb4,0x30,
+0x00,0x00,0x00,0x00,0x90,0x42,0x00,0x0a,0x00,0x00,0x00,0x00,0x00,0x02,0x18,0x2b,
+0x08,0x00,0x0b,0x6a,0xae,0x43,0x00,0x34,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x27,0xbd,0xff,0xe0,0x34,0x63,0x00,0x20,0x24,0x42,0x30,0xf8,0x3c,0x08,0xb0,0x03,
+0xaf,0xb1,0x00,0x14,0xac,0x62,0x00,0x00,0x35,0x08,0x01,0x00,0xaf,0xbf,0x00,0x18,
+0xaf,0xb0,0x00,0x10,0x91,0x03,0x00,0x00,0x00,0xa0,0x48,0x21,0x24,0x11,0x00,0x0a,
+0x2c,0xa5,0x00,0x04,0x24,0x02,0x00,0x10,0x00,0x45,0x88,0x0a,0x30,0x63,0x00,0x01,
+0x00,0xc0,0x28,0x21,0x14,0x60,0x00,0x02,0x00,0x11,0x40,0x40,0x02,0x20,0x40,0x21,
+0x84,0x83,0x00,0x0c,0x31,0x11,0x00,0xff,0x01,0x20,0x20,0x21,0x00,0x03,0x10,0xc0,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x83,0x8f,0xf8,0x00,0x43,0x10,0x21,
+0x84,0x43,0x00,0x04,0x24,0x06,0x00,0x0e,0x10,0xe0,0x00,0x06,0x02,0x23,0x80,0x21,
+0x02,0x00,0x10,0x21,0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x20,0x0c,0x00,0x08,0xdf,0x00,0x00,0x00,0x00,0x02,0x11,0x18,0x21,
+0x08,0x00,0x0c,0x60,0x00,0x62,0x80,0x21,0x27,0xbd,0xff,0xd0,0xaf,0xbf,0x00,0x28,
+0xaf,0xb4,0x00,0x20,0xaf,0xb3,0x00,0x1c,0xaf,0xb2,0x00,0x18,0xaf,0xb5,0x00,0x24,
+0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0x84,0x82,0x00,0x0c,0x3c,0x06,0xb0,0x03,
+0x34,0xc6,0x00,0x20,0x00,0x02,0x18,0xc0,0x00,0x62,0x18,0x21,0x00,0x03,0x18,0x80,
+0x27,0x82,0x8f,0xf4,0x00,0x62,0x10,0x21,0x8c,0x55,0x00,0x18,0x3c,0x02,0x80,0x00,
+0x24,0x42,0x31,0xa8,0xac,0xc2,0x00,0x00,0x8e,0xb0,0x00,0x08,0x27,0x82,0x8f,0xf8,
+0x00,0x62,0x18,0x21,0x90,0x71,0x00,0x07,0x00,0x10,0x86,0x43,0x32,0x10,0x00,0x01,
+0x00,0xa0,0x38,0x21,0x02,0x00,0x30,0x21,0x00,0xa0,0x98,0x21,0x02,0x20,0x28,0x21,
+0x0c,0x00,0x0c,0x3e,0x00,0x80,0x90,0x21,0x02,0x20,0x20,0x21,0x02,0x00,0x28,0x21,
+0x24,0x06,0x00,0x14,0x0c,0x00,0x08,0xdf,0x00,0x40,0xa0,0x21,0x86,0x43,0x00,0x0c,
+0x3c,0x09,0xb0,0x09,0x3c,0x08,0xb0,0x09,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x90,0x00,0x00,0x43,0x10,0x21,0x80,0x43,0x00,0x06,
+0x3c,0x07,0xb0,0x09,0x3c,0x05,0xb0,0x09,0x28,0x62,0x00,0x00,0x24,0x64,0x00,0x03,
+0x00,0x82,0x18,0x0b,0x00,0x03,0x18,0x83,0x3c,0x02,0xb0,0x09,0x00,0x03,0x18,0x80,
+0x34,0x42,0x01,0x02,0x35,0x29,0x01,0x10,0x35,0x08,0x01,0x14,0x34,0xe7,0x01,0x20,
+0x34,0xa5,0x01,0x24,0xa4,0x54,0x00,0x00,0x12,0x60,0x00,0x11,0x02,0xa3,0xa8,0x21,
+0x8e,0xa2,0x00,0x0c,0x8e,0xa3,0x00,0x08,0x00,0x02,0x14,0x00,0x00,0x03,0x1c,0x02,
+0x00,0x43,0x10,0x21,0xad,0x22,0x00,0x00,0x8e,0xa3,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x00,0x03,0x1c,0x02,0xa5,0x03,0x00,0x00,0x8f,0xbf,0x00,0x28,0x7b,0xb4,0x01,0x3c,
+0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x30,
+0x8e,0xa2,0x00,0x04,0x00,0x00,0x00,0x00,0xad,0x22,0x00,0x00,0x8e,0xa4,0x00,0x08,
+0x00,0x00,0x00,0x00,0xa5,0x04,0x00,0x00,0x7a,0xa2,0x00,0x7c,0x00,0x00,0x00,0x00,
+0x00,0x03,0x1c,0x00,0x00,0x02,0x14,0x02,0x00,0x62,0x18,0x21,0xac,0xe3,0x00,0x00,
+0x8e,0xa2,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x02,0x14,0x02,0x08,0x00,0x0c,0xb2,
+0xa4,0xa2,0x00,0x00,0x27,0xbd,0xff,0xe0,0xaf,0xb2,0x00,0x18,0xaf,0xb0,0x00,0x10,
+0xaf,0xbf,0x00,0x1c,0xaf,0xb1,0x00,0x14,0x84,0x82,0x00,0x0c,0x00,0x80,0x90,0x21,
+0x3c,0x05,0xb0,0x03,0x00,0x02,0x20,0xc0,0x00,0x82,0x20,0x21,0x00,0x04,0x20,0x80,
+0x27,0x82,0x8f,0xf4,0x00,0x82,0x10,0x21,0x8c,0x51,0x00,0x18,0x3c,0x02,0x80,0x00,
+0x34,0xa5,0x00,0x20,0x24,0x42,0x33,0x24,0x27,0x83,0x8f,0xf8,0xac,0xa2,0x00,0x00,
+0x00,0x83,0x20,0x21,0x3c,0x02,0xb0,0x03,0x90,0x86,0x00,0x07,0x34,0x42,0x01,0x00,
+0x8e,0x23,0x00,0x08,0x90,0x44,0x00,0x00,0x2c,0xc5,0x00,0x04,0x24,0x02,0x00,0x10,
+0x24,0x10,0x00,0x0a,0x00,0x45,0x80,0x0a,0x00,0x03,0x1e,0x43,0x30,0x84,0x00,0x01,
+0x30,0x65,0x00,0x01,0x14,0x80,0x00,0x02,0x00,0x10,0x10,0x40,0x02,0x00,0x10,0x21,
+0x00,0xc0,0x20,0x21,0x24,0x06,0x00,0x20,0x0c,0x00,0x08,0xdf,0x30,0x50,0x00,0xff,
+0x86,0x44,0x00,0x0c,0x27,0x85,0x90,0x00,0x3c,0x06,0xb0,0x09,0x00,0x04,0x18,0xc0,
+0x00,0x64,0x18,0x21,0x00,0x03,0x18,0x80,0x00,0x65,0x18,0x21,0x80,0x64,0x00,0x06,
+0x00,0x50,0x10,0x21,0x34,0xc6,0x01,0x02,0x24,0x85,0x00,0x03,0x28,0x83,0x00,0x00,
+0x00,0xa3,0x20,0x0b,0x00,0x04,0x20,0x83,0x00,0x04,0x20,0x80,0xa4,0xc2,0x00,0x00,
+0x02,0x24,0x20,0x21,0x8c,0x83,0x00,0x04,0x3c,0x02,0xb0,0x09,0x34,0x42,0x01,0x10,
+0xac,0x43,0x00,0x00,0x8c,0x86,0x00,0x08,0x3c,0x02,0xb0,0x09,0x34,0x42,0x01,0x14,
+0xa4,0x46,0x00,0x00,0x8c,0x85,0x00,0x0c,0x8c,0x82,0x00,0x08,0x3c,0x06,0xb0,0x09,
+0x00,0x05,0x2c,0x00,0x00,0x02,0x14,0x02,0x00,0xa2,0x28,0x21,0x34,0xc6,0x01,0x20,
+0xac,0xc5,0x00,0x00,0x8c,0x83,0x00,0x0c,0x3c,0x05,0xb0,0x09,0x34,0xa5,0x01,0x24,
+0x00,0x03,0x1c,0x02,0xa4,0xa3,0x00,0x00,0x92,0x42,0x00,0x0a,0x3c,0x03,0xb0,0x09,
+0x34,0x63,0x01,0x30,0x00,0x02,0x13,0x00,0x24,0x42,0x00,0x04,0x30,0x42,0xff,0xff,
+0xa4,0x62,0x00,0x00,0x86,0x44,0x00,0x0c,0x27,0x83,0x90,0x08,0x8f,0xbf,0x00,0x1c,
+0x00,0x04,0x10,0xc0,0x00,0x44,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,
+0x94,0x44,0x00,0x02,0x8f,0xb2,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x3c,0x05,0xb0,0x09,
+0x34,0xa5,0x01,0x32,0xa4,0xa4,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,
+0x27,0xbd,0xff,0xe0,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x00,0xaf,0xb0,0x00,0x10,
+0x34,0x42,0x00,0x20,0x00,0xa0,0x80,0x21,0x24,0x63,0x34,0xb0,0x00,0x05,0x2c,0x43,
+0xaf,0xb1,0x00,0x14,0xaf,0xbf,0x00,0x18,0xac,0x43,0x00,0x00,0x10,0xa0,0x00,0x05,
+0x00,0x80,0x88,0x21,0x8c,0x82,0x00,0x34,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0xb6,
+0x00,0x00,0x00,0x00,0x32,0x10,0x00,0xff,0x12,0x00,0x00,0x4c,0x00,0x00,0x10,0x21,
+0x24,0x02,0x00,0x08,0x12,0x02,0x00,0xa3,0x2a,0x02,0x00,0x09,0x10,0x40,0x00,0x89,
+0x24,0x02,0x00,0x40,0x24,0x04,0x00,0x02,0x12,0x04,0x00,0x79,0x2a,0x02,0x00,0x03,
+0x10,0x40,0x00,0x69,0x24,0x02,0x00,0x04,0x24,0x02,0x00,0x01,0x12,0x02,0x00,0x5a,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x05,0x34,0x42,0x00,0x08,0x3c,0x03,0x80,0x00,
+0xa2,0x20,0x00,0x4e,0xac,0x43,0x00,0x00,0x82,0x24,0x00,0x11,0x92,0x27,0x00,0x11,
+0x10,0x80,0x00,0x4e,0x00,0x00,0x00,0x00,0x92,0x26,0x00,0x0a,0x24,0x02,0x00,0x12,
+0x10,0x46,0x00,0x09,0x30,0xc2,0x00,0xff,0x27,0x83,0xb3,0xf0,0x00,0x02,0x10,0x80,
+0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x94,0x83,0x00,0x14,
+0x00,0x00,0x00,0x00,0xa6,0x23,0x00,0x0c,0x3c,0x02,0xb0,0x09,0x34,0x42,0x00,0x40,
+0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x03,0xa2,0x23,0x00,0x10,
+0x14,0x60,0x00,0x2b,0x30,0x65,0x00,0x01,0x30,0xc2,0x00,0xff,0x27,0x83,0xb3,0xf0,
+0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,0x82,0x23,0x00,0x12,
+0x90,0x82,0x00,0x16,0x00,0x00,0x00,0x00,0x00,0x02,0x11,0x42,0x30,0x42,0x00,0x01,
+0x00,0x62,0x18,0x21,0x00,0x03,0x26,0x00,0x14,0x80,0x00,0x18,0xa2,0x23,0x00,0x12,
+0x00,0x07,0x16,0x00,0x14,0x40,0x00,0x11,0x24,0x02,0x00,0x01,0x96,0x23,0x00,0x0c,
+0x27,0x84,0x90,0x00,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x44,0x10,0x21,0x80,0x45,0x00,0x06,0x00,0x03,0x1a,0x00,0x3c,0x02,0xb0,0x00,
+0x00,0x65,0x18,0x21,0x00,0x62,0x18,0x21,0x90,0x64,0x00,0x00,0x90,0x62,0x00,0x04,
+0xa2,0x20,0x00,0x15,0xa3,0x80,0x8b,0xc4,0x24,0x02,0x00,0x01,0x8f,0xbf,0x00,0x18,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x0c,0x00,0x0c,0xc9,
+0x02,0x20,0x20,0x21,0x92,0x27,0x00,0x11,0x08,0x00,0x0d,0x79,0x00,0x07,0x16,0x00,
+0x0c,0x00,0x0c,0x6a,0x02,0x20,0x20,0x21,0x86,0x23,0x00,0x0c,0x27,0x84,0x8f,0xf8,
+0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x44,0x20,0x21,
+0x90,0x85,0x00,0x07,0x27,0x83,0x90,0x00,0x00,0x43,0x10,0x21,0xa2,0x25,0x00,0x13,
+0x90,0x83,0x00,0x07,0x08,0x00,0x0d,0x91,0xa0,0x43,0x00,0x02,0x92,0x26,0x00,0x0a,
+0x08,0x00,0x0d,0x5a,0x30,0xc2,0x00,0xff,0x8e,0x22,0x00,0x24,0x00,0x00,0x00,0x00,
+0x10,0x50,0x00,0x07,0xa2,0x20,0x00,0x08,0x24,0x02,0x00,0x07,0xa2,0x22,0x00,0x0a,
+0x92,0x22,0x00,0x27,0xae,0x20,0x00,0x24,0x08,0x00,0x0d,0x4d,0xa2,0x22,0x00,0x04,
+0x08,0x00,0x0d,0xab,0x24,0x02,0x00,0x06,0x16,0x02,0xff,0x9b,0x3c,0x02,0xb0,0x05,
+0x8e,0x23,0x00,0x2c,0x24,0x02,0x00,0x01,0x10,0x62,0x00,0x07,0xa2,0x24,0x00,0x08,
+0x24,0x02,0x00,0x03,0xa2,0x22,0x00,0x0a,0x92,0x22,0x00,0x2f,0xae,0x20,0x00,0x2c,
+0x08,0x00,0x0d,0x4d,0xa2,0x22,0x00,0x06,0x08,0x00,0x0d,0xba,0xa2,0x20,0x00,0x0a,
+0x8e,0x22,0x00,0x28,0x24,0x03,0x00,0x01,0x24,0x04,0x00,0x01,0x10,0x44,0x00,0x07,
+0xa2,0x23,0x00,0x08,0x24,0x02,0x00,0x05,0xa2,0x22,0x00,0x0a,0x92,0x22,0x00,0x2b,
+0xae,0x20,0x00,0x28,0x08,0x00,0x0d,0x4d,0xa2,0x22,0x00,0x05,0x08,0x00,0x0d,0xc6,
+0x24,0x02,0x00,0x04,0x12,0x02,0x00,0x12,0x2a,0x02,0x00,0x41,0x10,0x40,0x00,0x09,
+0x24,0x02,0x00,0x80,0x24,0x02,0x00,0x20,0x16,0x02,0xff,0x7b,0x3c,0x02,0xb0,0x05,
+0x24,0x02,0x00,0x12,0xa2,0x22,0x00,0x0a,0xa2,0x22,0x00,0x08,0x08,0x00,0x0d,0x4d,
+0xae,0x20,0x00,0x3c,0x16,0x02,0xff,0x74,0x3c,0x02,0xb0,0x05,0x24,0x02,0x00,0x10,
+0xa2,0x22,0x00,0x0a,0xa2,0x22,0x00,0x08,0x08,0x00,0x0d,0x4d,0xae,0x20,0x00,0x34,
+0x24,0x02,0x00,0x11,0xa2,0x22,0x00,0x0a,0xa2,0x22,0x00,0x08,0x08,0x00,0x0d,0x4d,
+0xae,0x20,0x00,0x38,0x8e,0x24,0x00,0x30,0x24,0x02,0x00,0x03,0x24,0x03,0x00,0x01,
+0x10,0x83,0x00,0x07,0xa2,0x22,0x00,0x08,0x24,0x02,0x00,0x02,0xa2,0x22,0x00,0x0a,
+0x92,0x22,0x00,0x33,0xae,0x20,0x00,0x30,0x08,0x00,0x0d,0x4d,0xa2,0x22,0x00,0x07,
+0x08,0x00,0x0d,0xec,0xa2,0x24,0x00,0x0a,0x8f,0x84,0xb4,0x30,0xae,0x20,0x00,0x34,
+0x94,0x85,0x00,0x14,0x0c,0x00,0x1b,0x84,0x32,0x10,0x00,0xff,0x08,0x00,0x0d,0x3e,
+0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x24,0x42,0x37,0xe4,
+0x34,0x63,0x00,0x20,0xac,0x62,0x00,0x00,0x80,0xa2,0x00,0x15,0x3c,0x06,0xb0,0x05,
+0x10,0x40,0x00,0x0a,0x34,0xc6,0x02,0x54,0x83,0x83,0x8b,0xc4,0x00,0x00,0x00,0x00,
+0xac,0x83,0x00,0x24,0x8c,0xc2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x17,0x42,
+0x30,0x42,0x00,0x01,0x03,0xe0,0x00,0x08,0xac,0x82,0x00,0x28,0x8c,0x82,0x00,0x2c,
+0x3c,0x06,0xb0,0x05,0x34,0xc6,0x04,0x50,0x00,0x02,0x18,0x43,0x30,0x63,0x00,0x01,
+0x10,0x40,0x00,0x04,0x30,0x45,0x00,0x01,0xac,0x83,0x00,0x28,0x03,0xe0,0x00,0x08,
+0xac,0x85,0x00,0x24,0x90,0xc2,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,
+0x30,0x43,0x00,0x02,0x30,0x42,0x00,0x01,0xac,0x83,0x00,0x28,0x03,0xe0,0x00,0x08,
+0xac,0x82,0x00,0x24,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xd8,
+0x34,0x63,0x00,0x20,0x24,0x42,0x38,0x74,0xac,0x62,0x00,0x00,0xaf,0xb1,0x00,0x1c,
+0xaf,0xbf,0x00,0x20,0xaf,0xb0,0x00,0x18,0x90,0xa6,0x00,0x0a,0x27,0x83,0xb3,0xf0,
+0x00,0xa0,0x88,0x21,0x00,0x06,0x10,0x80,0x00,0x43,0x10,0x21,0x8c,0x50,0x00,0x00,
+0x80,0xa5,0x00,0x11,0x92,0x03,0x00,0x12,0x10,0xa0,0x00,0x04,0xa2,0x20,0x00,0x15,
+0x24,0x02,0x00,0x12,0x10,0xc2,0x00,0xda,0x00,0x00,0x00,0x00,0x82,0x22,0x00,0x12,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x67,0x00,0x00,0x00,0x00,0xa2,0x20,0x00,0x12,
+0xa2,0x00,0x00,0x19,0x86,0x23,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x03,0x10,0xc0,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x83,0x90,0x10,0x00,0x43,0x10,0x21,
+0xa0,0x40,0x00,0x00,0x92,0x03,0x00,0x16,0x00,0x00,0x00,0x00,0x30,0x63,0x00,0xdf,
+0xa2,0x03,0x00,0x16,0x82,0x02,0x00,0x12,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x20,
+0x00,0x00,0x00,0x00,0x92,0x23,0x00,0x08,0x00,0x00,0x00,0x00,0x14,0x60,0x00,0x45,
+0x24,0x02,0x00,0x01,0xa2,0x20,0x00,0x04,0x92,0x08,0x00,0x04,0x00,0x00,0x00,0x00,
+0x15,0x00,0x00,0x1e,0x24,0x02,0x00,0x01,0x92,0x07,0x00,0x0a,0xa2,0x02,0x00,0x17,
+0x92,0x02,0x00,0x16,0x30,0xe3,0x00,0xff,0x30,0x42,0x00,0xe4,0x10,0x60,0x00,0x03,
+0xa2,0x02,0x00,0x16,0x34,0x42,0x00,0x01,0xa2,0x02,0x00,0x16,0x11,0x00,0x00,0x05,
+0x00,0x00,0x00,0x00,0x92,0x02,0x00,0x16,0x00,0x00,0x00,0x00,0x34,0x42,0x00,0x02,
+0xa2,0x02,0x00,0x16,0x92,0x02,0x00,0x17,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x08,
+0x00,0x00,0x00,0x00,0x96,0x02,0x00,0x06,0x00,0x00,0x00,0x00,0xa6,0x02,0x00,0x14,
+0x8f,0xbf,0x00,0x20,0x7b,0xb0,0x00,0xfc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,
+0x96,0x02,0x00,0x00,0x08,0x00,0x0e,0x68,0xa6,0x02,0x00,0x14,0x92,0x07,0x00,0x0a,
+0x00,0x00,0x00,0x00,0x14,0xe0,0x00,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0x0e,0x54,
+0xa2,0x00,0x00,0x17,0x96,0x04,0x00,0x00,0x96,0x05,0x00,0x06,0x27,0x86,0x8f,0xf0,
+0x00,0x04,0x18,0xc0,0x00,0x64,0x18,0x21,0x00,0x05,0x10,0xc0,0x00,0x45,0x10,0x21,
+0x00,0x03,0x18,0x80,0x00,0x66,0x18,0x21,0x00,0x02,0x10,0x80,0x00,0x46,0x10,0x21,
+0x8c,0x66,0x00,0x08,0x8c,0x45,0x00,0x08,0x3c,0x03,0x80,0x00,0x00,0xc3,0x20,0x24,
+0x10,0x80,0x00,0x08,0x00,0xa3,0x10,0x24,0x10,0x40,0x00,0x04,0x00,0x00,0x18,0x21,
+0x10,0x80,0x00,0x02,0x24,0x03,0x00,0x01,0x00,0xa6,0x18,0x2b,0x08,0x00,0x0e,0x54,
+0xa2,0x03,0x00,0x17,0x10,0x40,0xff,0xfd,0x00,0xa6,0x18,0x2b,0x08,0x00,0x0e,0x88,
+0x00,0x00,0x00,0x00,0x10,0x62,0x00,0x09,0x24,0x02,0x00,0x02,0x10,0x62,0x00,0x05,
+0x24,0x02,0x00,0x03,0x14,0x62,0xff,0xb8,0x00,0x00,0x00,0x00,0x08,0x00,0x0e,0x4e,
+0xa2,0x20,0x00,0x07,0x08,0x00,0x0e,0x4e,0xa2,0x20,0x00,0x06,0x08,0x00,0x0e,0x4e,
+0xa2,0x20,0x00,0x05,0x82,0x22,0x00,0x10,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x69,
+0x2c,0x62,0x00,0x02,0x10,0x40,0x00,0x49,0x3c,0x02,0xb0,0x09,0x92,0x25,0x00,0x08,
+0x00,0x00,0x00,0x00,0x30,0xa6,0x00,0xff,0x2c,0xc2,0x00,0x04,0x10,0x40,0x00,0x3b,
+0x2c,0xc2,0x00,0x10,0x3c,0x04,0xb0,0x05,0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,
+0x24,0x02,0x00,0x01,0x00,0xc2,0x10,0x04,0x00,0x02,0x10,0x27,0x00,0x62,0x18,0x24,
+0xa0,0x83,0x00,0x00,0x86,0x23,0x00,0x0c,0x96,0x26,0x00,0x0c,0x00,0x03,0x10,0xc0,
+0x00,0x43,0x10,0x21,0x00,0x02,0x28,0x80,0x27,0x83,0x8f,0xf4,0x00,0xa3,0x18,0x21,
+0x8c,0x64,0x00,0x18,0x00,0x00,0x00,0x00,0x8c,0x82,0x00,0x04,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0x10,0x10,0x40,0x00,0x18,0x24,0x07,0x00,0x01,0x93,0x82,0x8b,0x61,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,0x14,0x40,0x00,0x0a,0x24,0x05,0x00,0x24,
+0x00,0x06,0x2c,0x00,0x00,0x05,0x2c,0x03,0x0c,0x00,0x1b,0x84,0x02,0x00,0x20,0x21,
+0x92,0x02,0x00,0x16,0xa2,0x00,0x00,0x12,0x30,0x42,0x00,0xe7,0x08,0x00,0x0e,0x45,
+0xa2,0x02,0x00,0x16,0xf0,0xc5,0x00,0x06,0x00,0x00,0x28,0x12,0x27,0x82,0x8f,0xf0,
+0x00,0xa2,0x28,0x21,0x0c,0x00,0x01,0x4b,0x3c,0x04,0x00,0x80,0x96,0x26,0x00,0x0c,
+0x08,0x00,0x0e,0xc5,0x00,0x06,0x2c,0x00,0x27,0x83,0x90,0x00,0x27,0x82,0x90,0x08,
+0x00,0xa2,0x10,0x21,0x00,0xa3,0x18,0x21,0x90,0x44,0x00,0x00,0x90,0x65,0x00,0x05,
+0x93,0x82,0x80,0x10,0x00,0x00,0x30,0x21,0x0c,0x00,0x21,0xf5,0xaf,0xa2,0x00,0x10,
+0x96,0x26,0x00,0x0c,0x08,0x00,0x0e,0xbf,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0xcd,
+0x3c,0x04,0xb0,0x05,0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,0x30,0xa5,0x00,0x0f,
+0x24,0x02,0x00,0x80,0x08,0x00,0x0e,0xae,0x00,0xa2,0x10,0x07,0x86,0x26,0x00,0x0c,
+0x3c,0x03,0xb0,0x09,0x34,0x42,0x01,0x72,0x34,0x63,0x01,0x78,0x94,0x47,0x00,0x00,
+0x8c,0x65,0x00,0x00,0x00,0x06,0x10,0xc0,0x00,0x46,0x10,0x21,0x3c,0x04,0xb0,0x09,
+0xae,0x25,0x00,0x1c,0x34,0x84,0x01,0x7c,0x27,0x83,0x8f,0xf4,0x00,0x02,0x10,0x80,
+0x8c,0x85,0x00,0x00,0x00,0x43,0x10,0x21,0x8c,0x43,0x00,0x18,0xae,0x25,0x00,0x20,
+0xa6,0x27,0x00,0x18,0x8c,0x66,0x00,0x08,0x02,0x20,0x20,0x21,0x0c,0x00,0x0f,0x15,
+0x00,0x00,0x28,0x21,0x86,0x25,0x00,0x18,0x8e,0x26,0x00,0x1c,0x8e,0x27,0x00,0x20,
+0x02,0x20,0x20,0x21,0x0c,0x00,0x1c,0x86,0xaf,0xa2,0x00,0x10,0x08,0x00,0x0e,0x45,
+0xa2,0x02,0x00,0x12,0x92,0x22,0x00,0x08,0x08,0x00,0x0e,0x45,0xa2,0x22,0x00,0x09,
+0xa2,0x20,0x00,0x11,0x80,0x82,0x00,0x50,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x03,
+0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0xd0,0xac,0x40,0x00,0x00,0x08,0x00,0x0e,0x45,
+0xa0,0x80,0x00,0x50,0x94,0x8a,0x00,0x0c,0x24,0x03,0x00,0x24,0x00,0x80,0x70,0x21,
+0x3c,0x02,0x80,0x00,0x3c,0x04,0xb0,0x03,0x24,0x42,0x3c,0x54,0xf1,0x43,0x00,0x06,
+0x34,0x84,0x00,0x20,0x00,0x00,0x18,0x12,0x00,0xa0,0x68,0x21,0xac,0x82,0x00,0x00,
+0x27,0x85,0x90,0x00,0x27,0x82,0x8f,0xff,0x27,0xbd,0xff,0xf8,0x00,0x62,0x60,0x21,
+0x00,0x65,0x58,0x21,0x00,0x00,0xc0,0x21,0x11,0xa0,0x00,0xcc,0x00,0x00,0x78,0x21,
+0x00,0x0a,0x1c,0x00,0x00,0x03,0x1c,0x03,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x45,0x10,0x21,0x91,0x87,0x00,0x00,0x80,0x48,0x00,0x04,
+0x03,0xa0,0x60,0x21,0x00,0x0a,0x1c,0x00,0x00,0x03,0x1c,0x03,0x00,0x03,0x10,0xc0,
+0x00,0x43,0x10,0x21,0x00,0x02,0x48,0x80,0x27,0x83,0x8f,0xf4,0xa3,0xa7,0x00,0x00,
+0x01,0x23,0x18,0x21,0x8c,0x64,0x00,0x18,0x25,0x02,0xff,0xff,0x00,0x48,0x40,0x0b,
+0x8c,0x83,0x00,0x04,0x2d,0x05,0x00,0x07,0x24,0x02,0x00,0x06,0x30,0x63,0x00,0x08,
+0x14,0x60,0x00,0x35,0x00,0x45,0x40,0x0a,0x93,0xa7,0x00,0x00,0x27,0x82,0x90,0x08,
+0x01,0x22,0x10,0x21,0x30,0xe3,0x00,0xf0,0x38,0x63,0x00,0x50,0x30,0xe5,0x00,0xff,
+0x00,0x05,0x20,0x2b,0x00,0x03,0x18,0x2b,0x00,0x64,0x18,0x24,0x90,0x49,0x00,0x00,
+0x10,0x60,0x00,0x16,0x30,0xe4,0x00,0x0f,0x24,0x02,0x00,0x04,0x10,0xa2,0x00,0x9d,
+0x00,0x00,0x00,0x00,0x11,0xa0,0x00,0x3a,0x2c,0xa2,0x00,0x0c,0x10,0x40,0x00,0x02,
+0x24,0x84,0x00,0x0c,0x00,0xe0,0x20,0x21,0x30,0x84,0x00,0xff,0x00,0x04,0x10,0x40,
+0x27,0x83,0xbb,0x0c,0x00,0x44,0x10,0x21,0x00,0x43,0x10,0x21,0x90,0x47,0x00,0x00,
+0x00,0x00,0x00,0x00,0x2c,0xe3,0x00,0x0c,0xa3,0xa7,0x00,0x00,0x10,0x60,0x00,0x02,
+0x24,0xe2,0x00,0x04,0x00,0xe0,0x10,0x21,0xa3,0xa2,0x00,0x00,0x91,0x65,0x00,0x00,
+0x91,0x82,0x00,0x00,0x30,0xa3,0x00,0xff,0x00,0x62,0x10,0x2b,0x10,0x40,0x00,0x0e,
+0x2c,0x62,0x00,0x0c,0x14,0x40,0x00,0x03,0x00,0x60,0x20,0x21,0x30,0xa2,0x00,0x0f,
+0x24,0x44,0x00,0x0c,0x00,0x04,0x10,0x40,0x00,0x44,0x20,0x21,0x27,0x83,0xbb,0x0c,
+0x00,0x83,0x18,0x21,0x90,0x62,0x00,0x02,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x05,
+0x00,0x09,0x11,0x00,0xa1,0x85,0x00,0x00,0x93,0xa2,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x08,0x00,0x49,0x10,0x23,0x00,0x02,0x10,0x80,0x00,0x49,0x10,0x23,
+0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x21,0x27,0x83,0xb4,0x98,0x00,0x43,0x10,0x21,
+0x90,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x2c,0x83,0x00,0x0c,0x14,0x60,0x00,0x06,
+0x00,0x80,0x10,0x21,0x00,0x18,0x10,0x40,0x00,0x4f,0x10,0x21,0x00,0x02,0x11,0x00,
+0x00,0x82,0x10,0x21,0x24,0x42,0x00,0x04,0x08,0x00,0x0f,0x76,0xa1,0x82,0x00,0x00,
+0x8f,0x8d,0x81,0x5c,0x00,0x00,0x00,0x00,0x01,0xa8,0x10,0x21,0x90,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0x10,0x60,0xff,0xd1,0x00,0x00,0x28,0x21,0x00,0x06,0x74,0x82,
+0x30,0xe2,0x00,0xff,0x2c,0x42,0x00,0x0c,0x14,0x40,0x00,0x03,0x00,0xe0,0x10,0x21,
+0x30,0xe2,0x00,0x0f,0x24,0x42,0x00,0x0c,0x30,0x44,0x00,0xff,0xa3,0xa2,0x00,0x00,
+0x24,0x02,0x00,0x0c,0x10,0x82,0x00,0x0d,0x00,0x09,0x11,0x00,0x00,0x49,0x10,0x23,
+0x00,0x02,0x10,0x80,0x00,0x04,0x18,0x40,0x00,0x49,0x10,0x23,0x00,0x64,0x18,0x21,
+0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x27,0x84,0xb4,0x98,0x00,0x44,0x10,0x21,
+0x90,0x47,0x00,0x00,0x00,0x00,0x00,0x00,0xa3,0xa7,0x00,0x00,0x00,0x0a,0x1c,0x00,
+0x00,0x03,0x1c,0x03,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x8f,0xf4,0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x18,0x00,0x00,0x00,0x00,
+0x8c,0x83,0x00,0x04,0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x10,0x14,0x60,0x00,0x33,
+0x00,0x06,0x14,0x42,0x00,0x09,0x11,0x00,0x00,0x49,0x10,0x23,0x00,0x02,0x10,0x80,
+0x00,0x49,0x10,0x23,0x27,0x83,0xb5,0x68,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,
+0x90,0x44,0x00,0x04,0x90,0x43,0x00,0x05,0x00,0x00,0x00,0x00,0x00,0x64,0xc0,0x24,
+0x93,0xa7,0x00,0x00,0x00,0x00,0x00,0x00,0x2c,0xe2,0x00,0x0f,0x10,0x40,0x00,0x0f,
+0x31,0xcf,0x00,0x01,0x00,0x0a,0x1c,0x00,0x00,0x03,0x1c,0x03,0x00,0x03,0x10,0xc0,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x84,0x8f,0xf0,0x00,0x44,0x10,0x21,
+0x84,0x43,0x00,0x06,0x00,0x00,0x00,0x00,0x28,0x63,0x06,0x41,0x14,0x60,0x00,0x04,
+0x30,0xe2,0x00,0xff,0x24,0x07,0x00,0x0f,0xa3,0xa7,0x00,0x00,0x30,0xe2,0x00,0xff,
+0x2c,0x42,0x00,0x0c,0x14,0x40,0x00,0x06,0x00,0xe0,0x10,0x21,0x00,0x18,0x10,0x40,
+0x00,0x4f,0x10,0x21,0x00,0x02,0x11,0x00,0x00,0x47,0x10,0x21,0x24,0x42,0x00,0x04,
+0xa3,0xa2,0x00,0x00,0x00,0x40,0x38,0x21,0x01,0xa8,0x10,0x21,0x90,0x43,0x00,0x00,
+0x24,0xa4,0x00,0x01,0x30,0x85,0xff,0xff,0x00,0xa3,0x18,0x2b,0x14,0x60,0xff,0xad,
+0x30,0xe2,0x00,0xff,0x08,0x00,0x0f,0x63,0x00,0x00,0x00,0x00,0x08,0x00,0x0f,0xc4,
+0x30,0x58,0x00,0x01,0x81,0xc2,0x00,0x48,0x00,0x00,0x00,0x00,0x10,0x40,0xff,0x73,
+0x00,0x00,0x00,0x00,0x08,0x00,0x0f,0x51,0x00,0x00,0x00,0x00,0x00,0x0a,0x1c,0x00,
+0x00,0x03,0x1c,0x03,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x45,0x10,0x21,0x80,0x48,0x00,0x05,0x91,0x67,0x00,0x00,0x08,0x00,0x0f,0x31,
+0x03,0xa0,0x58,0x21,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,
+0x24,0x42,0x3f,0xf4,0x03,0xe0,0x00,0x08,0xac,0x62,0x00,0x00,0x27,0xbd,0xff,0xc0,
+0xaf,0xb7,0x00,0x34,0xaf,0xb6,0x00,0x30,0xaf,0xb5,0x00,0x2c,0xaf,0xb4,0x00,0x28,
+0xaf,0xb3,0x00,0x24,0xaf,0xb2,0x00,0x20,0xaf,0xbf,0x00,0x3c,0xaf,0xbe,0x00,0x38,
+0xaf,0xb1,0x00,0x1c,0xaf,0xb0,0x00,0x18,0x84,0x82,0x00,0x0c,0x27,0x93,0x8f,0xf4,
+0x3c,0x05,0xb0,0x03,0x00,0x02,0x18,0xc0,0x00,0x62,0x18,0x21,0x00,0x03,0x18,0x80,
+0x00,0x73,0x10,0x21,0x8c,0x5e,0x00,0x18,0x3c,0x02,0x80,0x00,0x34,0xa5,0x00,0x20,
+0x24,0x42,0x40,0x0c,0xac,0xa2,0x00,0x00,0x8f,0xd0,0x00,0x08,0x27,0x95,0x90,0x00,
+0x00,0x75,0x18,0x21,0x00,0x00,0x28,0x21,0x02,0x00,0x30,0x21,0x90,0x71,0x00,0x00,
+0x0c,0x00,0x0f,0x15,0x00,0x80,0xb0,0x21,0x00,0x40,0x90,0x21,0x00,0x10,0x14,0x42,
+0x30,0x54,0x00,0x01,0x02,0x40,0x20,0x21,0x00,0x10,0x14,0x82,0x02,0x80,0x28,0x21,
+0x12,0x51,0x00,0x23,0x00,0x10,0xbf,0xc2,0x86,0xc3,0x00,0x0c,0x30,0x50,0x00,0x01,
+0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x55,0x10,0x21,
+0xa0,0x52,0x00,0x00,0x86,0xc3,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x03,0x10,0xc0,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x53,0x30,0x21,0x8c,0xc7,0x00,0x18,
+0x27,0x83,0x8f,0xf0,0x00,0x43,0x10,0x21,0x8c,0xe3,0x00,0x04,0x84,0x46,0x00,0x06,
+0x00,0x03,0x19,0x42,0x0c,0x00,0x08,0xdf,0x30,0x73,0x00,0x01,0x00,0x40,0x88,0x21,
+0x02,0x40,0x20,0x21,0x02,0x80,0x28,0x21,0x16,0xe0,0x00,0x10,0x02,0x00,0x30,0x21,
+0x86,0xc2,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x02,0x18,0xc0,0x00,0x62,0x18,0x21,
+0x00,0x03,0x18,0x80,0x27,0x82,0x8f,0xf8,0x00,0x62,0x18,0x21,0xa4,0x71,0x00,0x04,
+0x7b,0xbe,0x01,0xfc,0x7b,0xb6,0x01,0xbc,0x7b,0xb4,0x01,0x7c,0x7b,0xb2,0x01,0x3c,
+0x7b,0xb0,0x00,0xfc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x40,0x86,0xc3,0x00,0x0c,
+0xaf,0xb3,0x00,0x10,0xaf,0xa0,0x00,0x14,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x55,0x10,0x21,0x80,0x47,0x00,0x06,0x00,0x00,0x00,0x00,
+0x24,0xe7,0x00,0x02,0x00,0x07,0x17,0xc2,0x00,0xe2,0x38,0x21,0x00,0x07,0x38,0x43,
+0x00,0x07,0x38,0x40,0x0c,0x00,0x09,0x06,0x03,0xc7,0x38,0x21,0x08,0x00,0x10,0x44,
+0x02,0x22,0x88,0x21,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xd0,
+0x34,0x63,0x00,0x20,0x24,0x42,0x41,0x94,0xaf,0xb2,0x00,0x20,0xac,0x62,0x00,0x00,
+0xaf,0xbf,0x00,0x28,0xaf,0xb3,0x00,0x24,0xaf,0xb1,0x00,0x1c,0xaf,0xb0,0x00,0x18,
+0x3c,0x02,0xb0,0x03,0x90,0x83,0x00,0x0a,0x34,0x42,0x01,0x04,0x94,0x45,0x00,0x00,
+0x00,0x03,0x18,0x80,0x27,0x82,0xb3,0xf0,0x00,0x62,0x18,0x21,0x30,0xa6,0xff,0xff,
+0x8c,0x71,0x00,0x00,0x80,0x85,0x00,0x12,0x30,0xc9,0x00,0xff,0x00,0x06,0x32,0x02,
+0xa4,0x86,0x00,0x44,0xa4,0x89,0x00,0x46,0x82,0x22,0x00,0x12,0x00,0x80,0x90,0x21,
+0x10,0xa0,0x00,0x1b,0xa0,0x80,0x00,0x15,0x00,0xc5,0x10,0x2a,0x10,0x40,0x00,0x14,
+0x00,0x00,0x00,0x00,0xa2,0x20,0x00,0x19,0x84,0x83,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x83,0x90,0x10,
+0x00,0x43,0x10,0x21,0xa0,0x40,0x00,0x00,0xa0,0x80,0x00,0x12,0x92,0x22,0x00,0x16,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xdf,0xa2,0x22,0x00,0x16,0x8f,0xbf,0x00,0x28,
+0x7b,0xb2,0x01,0x3c,0x7b,0xb0,0x00,0xfc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x30,
+0x0c,0x00,0x0f,0xfd,0x00,0x00,0x00,0x00,0x08,0x00,0x10,0x93,0x00,0x00,0x00,0x00,
+0x28,0x42,0x00,0x02,0x10,0x40,0x01,0x76,0x00,0x00,0x28,0x21,0x94,0x87,0x00,0x0c,
+0x00,0x00,0x00,0x00,0x00,0xe0,0x10,0x21,0x00,0x02,0x14,0x00,0x00,0x02,0x14,0x03,
+0x00,0x07,0x24,0x00,0x00,0x04,0x24,0x03,0x00,0x02,0x18,0xc0,0x00,0x62,0x18,0x21,
+0x00,0x04,0x28,0xc0,0x00,0xa4,0x28,0x21,0x27,0x82,0x90,0x10,0x00,0x03,0x18,0x80,
+0x00,0x62,0x18,0x21,0x00,0x05,0x28,0x80,0x27,0x82,0x8f,0xf8,0x00,0xa2,0x10,0x21,
+0x8c,0x68,0x00,0x00,0x80,0x44,0x00,0x06,0x27,0x82,0x90,0x00,0x00,0x08,0x1d,0x02,
+0x00,0xa2,0x28,0x21,0x38,0x84,0x00,0x00,0x30,0x63,0x00,0x01,0x01,0x24,0x30,0x0b,
+0x80,0xaa,0x00,0x04,0x80,0xa9,0x00,0x05,0x10,0x60,0x00,0x02,0x00,0x08,0x14,0x02,
+0x30,0x46,0x00,0x0f,0x15,0x20,0x00,0x28,0x01,0x49,0x10,0x21,0x15,0x40,0x00,0x11,
+0x30,0xe3,0xff,0xff,0x92,0x45,0x00,0x08,0x00,0x00,0x00,0x00,0x30,0xa8,0x00,0xff,
+0x2d,0x02,0x00,0x04,0x10,0x40,0x01,0x46,0x2d,0x02,0x00,0x10,0x3c,0x04,0xb0,0x05,
+0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,0x24,0x02,0x00,0x01,0x01,0x02,0x10,0x04,
+0x00,0x62,0x18,0x25,0xa0,0x83,0x00,0x00,0x96,0x47,0x00,0x0c,0x00,0x00,0x00,0x00,
+0x30,0xe3,0xff,0xff,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x27,0x84,0x90,0x00,
+0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x21,0x80,0x45,0x00,0x06,0x00,0x03,0x1a,0x00,
+0x3c,0x04,0xb0,0x00,0x00,0x65,0x18,0x21,0x00,0x64,0x20,0x21,0x94,0x82,0x00,0x00,
+0x82,0x43,0x00,0x10,0x00,0x02,0x14,0x00,0x14,0x60,0x00,0x06,0x00,0x02,0x3c,0x03,
+0x30,0xe2,0x00,0x04,0x14,0x40,0x00,0x04,0x01,0x49,0x10,0x21,0x34,0xe2,0x08,0x00,
+0xa4,0x82,0x00,0x00,0x01,0x49,0x10,0x21,0x00,0x02,0x16,0x00,0x00,0x02,0x16,0x03,
+0x00,0x46,0x10,0x2a,0x10,0x40,0x00,0x7c,0x00,0x00,0x00,0x00,0x82,0x42,0x00,0x10,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x0e,0x00,0x00,0x00,0x00,0x86,0x43,0x00,0x0c,
+0x25,0x44,0x00,0x01,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x90,0x00,0x00,0x43,0x10,0x21,0xa0,0x44,0x00,0x04,0x92,0x23,0x00,0x16,
+0x02,0x40,0x20,0x21,0x30,0x63,0x00,0xfb,0x08,0x00,0x10,0x98,0xa2,0x23,0x00,0x16,
+0x86,0x43,0x00,0x0c,0x25,0x24,0x00,0x01,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x90,0x00,0x00,0x43,0x10,0x21,0xa0,0x44,0x00,0x05,
+0x86,0x45,0x00,0x0c,0x0c,0x00,0x1f,0x08,0x02,0x20,0x20,0x21,0x10,0x40,0x00,0x5a,
+0x00,0x00,0x00,0x00,0x92,0x45,0x00,0x08,0x00,0x00,0x00,0x00,0x30,0xa6,0x00,0xff,
+0x2c,0xc2,0x00,0x04,0x10,0x40,0x00,0x4c,0x2c,0xc2,0x00,0x10,0x3c,0x04,0xb0,0x05,
+0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,0x24,0x02,0x00,0x01,0x00,0xc2,0x10,0x04,
+0x00,0x02,0x10,0x27,0x00,0x62,0x18,0x24,0xa0,0x83,0x00,0x00,0x92,0x45,0x00,0x08,
+0x00,0x00,0x00,0x00,0x30,0xa5,0x00,0xff,0x14,0xa0,0x00,0x33,0x24,0x02,0x00,0x01,
+0xa2,0x40,0x00,0x04,0x92,0x22,0x00,0x04,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x0c,
+0x24,0x02,0x00,0x01,0xa2,0x22,0x00,0x17,0x92,0x22,0x00,0x17,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x04,0x00,0x00,0x00,0x00,0x96,0x22,0x00,0x06,0x08,0x00,0x10,0x93,
+0xa6,0x22,0x00,0x14,0x96,0x22,0x00,0x00,0x08,0x00,0x10,0x93,0xa6,0x22,0x00,0x14,
+0x92,0x22,0x00,0x0a,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x03,0x00,0x00,0x00,0x00,
+0x08,0x00,0x11,0x22,0xa2,0x20,0x00,0x17,0x96,0x24,0x00,0x00,0x96,0x25,0x00,0x06,
+0x27,0x86,0x8f,0xf0,0x00,0x04,0x18,0xc0,0x00,0x64,0x18,0x21,0x00,0x05,0x10,0xc0,
+0x00,0x45,0x10,0x21,0x00,0x03,0x18,0x80,0x00,0x66,0x18,0x21,0x00,0x02,0x10,0x80,
+0x00,0x46,0x10,0x21,0x8c,0x65,0x00,0x08,0x8c,0x44,0x00,0x08,0x3c,0x03,0x80,0x00,
+0x00,0xa3,0x30,0x24,0x10,0xc0,0x00,0x08,0x00,0x83,0x10,0x24,0x10,0x40,0x00,0x04,
+0x00,0x00,0x18,0x21,0x10,0xc0,0x00,0x02,0x24,0x03,0x00,0x01,0x00,0x85,0x18,0x2b,
+0x08,0x00,0x11,0x22,0xa2,0x23,0x00,0x17,0x10,0x40,0xff,0xfd,0x00,0x85,0x18,0x2b,
+0x08,0x00,0x11,0x45,0x00,0x00,0x00,0x00,0x10,0xa2,0x00,0x09,0x24,0x02,0x00,0x02,
+0x10,0xa2,0x00,0x05,0x24,0x02,0x00,0x03,0x14,0xa2,0xff,0xca,0x00,0x00,0x00,0x00,
+0x08,0x00,0x11,0x1d,0xa2,0x40,0x00,0x07,0x08,0x00,0x11,0x1d,0xa2,0x40,0x00,0x06,
+0x08,0x00,0x11,0x1d,0xa2,0x40,0x00,0x05,0x14,0x40,0xff,0xbe,0x3c,0x04,0xb0,0x05,
+0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,0x30,0xa5,0x00,0x0f,0x24,0x02,0x00,0x80,
+0x08,0x00,0x11,0x14,0x00,0xa2,0x10,0x07,0x0c,0x00,0x10,0x03,0x02,0x40,0x20,0x21,
+0x08,0x00,0x10,0x93,0x00,0x00,0x00,0x00,0x92,0x45,0x00,0x08,0x00,0x00,0x00,0x00,
+0x30,0xa6,0x00,0xff,0x2c,0xc2,0x00,0x04,0x10,0x40,0x00,0x99,0x2c,0xc2,0x00,0x10,
+0x3c,0x04,0xb0,0x05,0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,0x24,0x02,0x00,0x01,
+0x00,0xc2,0x10,0x04,0x00,0x02,0x10,0x27,0x00,0x62,0x18,0x24,0xa0,0x83,0x00,0x00,
+0x92,0x45,0x00,0x08,0x00,0x00,0x00,0x00,0x30,0xa5,0x00,0xff,0x14,0xa0,0x00,0x80,
+0x24,0x02,0x00,0x01,0xa2,0x40,0x00,0x04,0x86,0x43,0x00,0x0c,0x27,0x93,0x8f,0xf4,
+0x96,0x47,0x00,0x0c,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,0x00,0x02,0x28,0x80,
+0x00,0xb3,0x18,0x21,0x8c,0x64,0x00,0x18,0x00,0x00,0x00,0x00,0x8c,0x82,0x00,0x04,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x10,0x10,0x40,0x00,0x64,0x00,0x00,0x30,0x21,
+0x00,0x07,0x1c,0x00,0x00,0x03,0x1c,0x03,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x53,0x10,0x21,0x8c,0x43,0x00,0x18,0x93,0x82,0x8b,0x61,
+0x8c,0x64,0x00,0x04,0x30,0x42,0x00,0x01,0x00,0x04,0x21,0x42,0x14,0x40,0x00,0x4d,
+0x30,0x90,0x00,0x01,0x00,0x07,0x2c,0x00,0x00,0x05,0x2c,0x03,0x0c,0x00,0x1b,0x84,
+0x02,0x20,0x20,0x21,0x96,0x26,0x00,0x06,0x12,0x00,0x00,0x14,0x30,0xc5,0xff,0xff,
+0x02,0x60,0x90,0x21,0x00,0x05,0x10,0xc0,0x00,0x45,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x52,0x18,0x21,0x92,0x22,0x00,0x0a,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x0b,
+0x02,0x20,0x20,0x21,0x8c,0x63,0x00,0x18,0x00,0x00,0x00,0x00,0x8c,0x62,0x00,0x04,
+0x00,0x00,0x00,0x00,0x00,0x02,0x11,0x42,0x0c,0x00,0x1b,0x84,0x30,0x50,0x00,0x01,
+0x96,0x26,0x00,0x06,0x16,0x00,0xff,0xef,0x30,0xc5,0xff,0xff,0x92,0x22,0x00,0x04,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x0d,0x24,0x02,0x00,0x01,0xa2,0x22,0x00,0x17,
+0x92,0x22,0x00,0x17,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x05,0x00,0x00,0x00,0x00,
+0xa6,0x26,0x00,0x14,0x92,0x22,0x00,0x16,0x08,0x00,0x10,0x92,0x30,0x42,0x00,0xc3,
+0x96,0x22,0x00,0x00,0x08,0x00,0x11,0xb9,0xa6,0x22,0x00,0x14,0x92,0x22,0x00,0x0a,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0x11,0xb4,
+0xa2,0x20,0x00,0x17,0x96,0x24,0x00,0x00,0x30,0xc5,0xff,0xff,0x00,0x05,0x18,0xc0,
+0x00,0x04,0x10,0xc0,0x00,0x44,0x10,0x21,0x00,0x65,0x18,0x21,0x27,0x84,0x8f,0xf0,
+0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x21,0x00,0x03,0x18,0x80,0x8c,0x45,0x00,0x08,
+0x00,0x64,0x18,0x21,0x8c,0x64,0x00,0x08,0x3c,0x02,0x80,0x00,0x00,0xa2,0x38,0x24,
+0x10,0xe0,0x00,0x08,0x00,0x82,0x10,0x24,0x10,0x40,0x00,0x04,0x00,0x00,0x18,0x21,
+0x10,0xe0,0x00,0x02,0x24,0x03,0x00,0x01,0x00,0x85,0x18,0x2b,0x08,0x00,0x11,0xb4,
+0xa2,0x23,0x00,0x17,0x10,0x40,0xff,0xfd,0x00,0x85,0x18,0x2b,0x08,0x00,0x11,0xd8,
+0x00,0x00,0x00,0x00,0x24,0x05,0x00,0x24,0xf0,0xe5,0x00,0x06,0x00,0x00,0x28,0x12,
+0x27,0x82,0x8f,0xf0,0x00,0xa2,0x28,0x21,0x0c,0x00,0x01,0x4b,0x00,0x00,0x20,0x21,
+0x96,0x47,0x00,0x0c,0x08,0x00,0x11,0x96,0x00,0x07,0x2c,0x00,0x27,0x83,0x90,0x00,
+0x27,0x82,0x90,0x08,0x00,0xa2,0x10,0x21,0x00,0xa3,0x18,0x21,0x90,0x44,0x00,0x00,
+0x90,0x65,0x00,0x05,0x93,0x82,0x80,0x10,0x24,0x07,0x00,0x01,0x0c,0x00,0x21,0xf5,
+0xaf,0xa2,0x00,0x10,0x96,0x47,0x00,0x0c,0x08,0x00,0x11,0x89,0x00,0x07,0x1c,0x00,
+0x10,0xa2,0x00,0x09,0x24,0x02,0x00,0x02,0x10,0xa2,0x00,0x05,0x24,0x02,0x00,0x03,
+0x14,0xa2,0xff,0x7d,0x00,0x00,0x00,0x00,0x08,0x00,0x11,0x7a,0xa2,0x40,0x00,0x07,
+0x08,0x00,0x11,0x7a,0xa2,0x40,0x00,0x06,0x08,0x00,0x11,0x7a,0xa2,0x40,0x00,0x05,
+0x14,0x40,0xff,0x71,0x3c,0x04,0xb0,0x05,0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,
+0x30,0xa5,0x00,0x0f,0x24,0x02,0x00,0x80,0x08,0x00,0x11,0x71,0x00,0xa2,0x10,0x07,
+0x14,0x40,0xfe,0xc3,0x3c,0x04,0xb0,0x05,0x34,0x84,0x02,0x29,0x90,0x83,0x00,0x00,
+0x30,0xa5,0x00,0x0f,0x24,0x02,0x00,0x80,0x08,0x00,0x10,0xcc,0x00,0xa2,0x10,0x07,
+0x84,0x83,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x8f,0xf4,0x00,0x43,0x10,0x21,0x8c,0x47,0x00,0x18,
+0x00,0x00,0x00,0x00,0x8c,0xe6,0x00,0x08,0x0c,0x00,0x0f,0x15,0x00,0x00,0x00,0x00,
+0x02,0x40,0x20,0x21,0x00,0x00,0x28,0x21,0x00,0x00,0x30,0x21,0x00,0x00,0x38,0x21,
+0x0c,0x00,0x1c,0x86,0xaf,0xa2,0x00,0x10,0x00,0x02,0x1e,0x00,0x14,0x60,0xfe,0x6b,
+0xa2,0x22,0x00,0x12,0x92,0x43,0x00,0x08,0x00,0x00,0x00,0x00,0x14,0x60,0x00,0x40,
+0x24,0x02,0x00,0x01,0xa2,0x40,0x00,0x04,0x92,0x28,0x00,0x04,0x00,0x00,0x00,0x00,
+0x15,0x00,0x00,0x19,0x24,0x02,0x00,0x01,0x92,0x27,0x00,0x0a,0xa2,0x22,0x00,0x17,
+0x92,0x22,0x00,0x17,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x10,0x00,0x00,0x00,0x00,
+0x96,0x22,0x00,0x06,0x00,0x00,0x00,0x00,0xa6,0x22,0x00,0x14,0x92,0x22,0x00,0x16,
+0x30,0xe3,0x00,0xff,0x30,0x42,0x00,0xc0,0x10,0x60,0x00,0x03,0xa2,0x22,0x00,0x16,
+0x34,0x42,0x00,0x01,0xa2,0x22,0x00,0x16,0x11,0x00,0xfe,0x50,0x00,0x00,0x00,0x00,
+0x92,0x22,0x00,0x16,0x08,0x00,0x10,0x92,0x34,0x42,0x00,0x02,0x96,0x22,0x00,0x00,
+0x08,0x00,0x12,0x3b,0xa6,0x22,0x00,0x14,0x92,0x27,0x00,0x0a,0x00,0x00,0x00,0x00,
+0x14,0xe0,0x00,0x03,0x00,0x00,0x00,0x00,0x08,0x00,0x12,0x34,0xa2,0x20,0x00,0x17,
+0x96,0x24,0x00,0x00,0x96,0x25,0x00,0x06,0x27,0x86,0x8f,0xf0,0x00,0x04,0x18,0xc0,
+0x00,0x64,0x18,0x21,0x00,0x05,0x10,0xc0,0x00,0x45,0x10,0x21,0x00,0x03,0x18,0x80,
+0x00,0x66,0x18,0x21,0x00,0x02,0x10,0x80,0x00,0x46,0x10,0x21,0x8c,0x65,0x00,0x08,
+0x8c,0x44,0x00,0x08,0x3c,0x03,0x80,0x00,0x00,0xa3,0x30,0x24,0x10,0xc0,0x00,0x08,
+0x00,0x83,0x10,0x24,0x10,0x40,0x00,0x04,0x00,0x00,0x18,0x21,0x10,0xc0,0x00,0x02,
+0x24,0x03,0x00,0x01,0x00,0x85,0x18,0x2b,0x08,0x00,0x12,0x34,0xa2,0x23,0x00,0x17,
+0x10,0x40,0xff,0xfd,0x00,0x85,0x18,0x2b,0x08,0x00,0x12,0x63,0x00,0x00,0x00,0x00,
+0x10,0x62,0x00,0x09,0x24,0x02,0x00,0x02,0x10,0x62,0x00,0x05,0x24,0x02,0x00,0x03,
+0x14,0x62,0xff,0xbd,0x00,0x00,0x00,0x00,0x08,0x00,0x12,0x2e,0xa2,0x40,0x00,0x07,
+0x08,0x00,0x12,0x2e,0xa2,0x40,0x00,0x06,0x08,0x00,0x12,0x2e,0xa2,0x40,0x00,0x05,
+0x3c,0x02,0x80,0x00,0x00,0x82,0x30,0x24,0x10,0xc0,0x00,0x08,0x00,0xa2,0x18,0x24,
+0x10,0x60,0x00,0x04,0x00,0x00,0x10,0x21,0x10,0xc0,0x00,0x02,0x24,0x02,0x00,0x01,
+0x00,0xa4,0x10,0x2b,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x10,0x60,0xff,0xfd,
+0x00,0xa4,0x10,0x2b,0x08,0x00,0x12,0x7e,0x00,0x00,0x00,0x00,0x30,0x82,0xff,0xff,
+0x00,0x02,0x18,0xc0,0x00,0x62,0x18,0x21,0x27,0x84,0x90,0x00,0x00,0x03,0x18,0x80,
+0x00,0x64,0x18,0x21,0x80,0x66,0x00,0x06,0x00,0x02,0x12,0x00,0x3c,0x03,0xb0,0x00,
+0x00,0x46,0x10,0x21,0x00,0x45,0x10,0x21,0x03,0xe0,0x00,0x08,0x00,0x43,0x10,0x21,
+0x27,0xbd,0xff,0xe0,0x30,0x82,0x00,0x7c,0x30,0x84,0xff,0x00,0xaf,0xbf,0x00,0x1c,
+0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0x14,0x40,0x00,0x41,
+0x00,0x04,0x22,0x03,0x24,0x02,0x00,0x04,0x3c,0x10,0xb0,0x03,0x8e,0x10,0x00,0x00,
+0x10,0x82,0x00,0x32,0x24,0x02,0x00,0x08,0x10,0x82,0x00,0x03,0x32,0x02,0x00,0x20,
+0x08,0x00,0x12,0xa4,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x17,0x3c,0x02,0xb0,0x06,
+0x34,0x42,0x80,0x24,0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x67,0x00,0xff,
+0x10,0xe0,0x00,0x23,0x00,0x00,0x88,0x21,0x8f,0x85,0x8f,0xd0,0x00,0x40,0x30,0x21,
+0x94,0xa2,0x00,0x08,0x8c,0xc3,0x00,0x00,0x26,0x31,0x00,0x01,0x24,0x42,0x00,0x02,
+0x30,0x42,0x01,0xff,0x34,0x63,0x01,0x00,0x02,0x27,0x20,0x2a,0xa4,0xa2,0x00,0x08,
+0x14,0x80,0xff,0xf7,0xac,0xc3,0x00,0x00,0x84,0xa3,0x00,0x08,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x00,0x30,0xac,0x43,0x00,0x00,0x27,0x92,0xb3,0xf0,0x24,0x11,0x00,0x12,
+0x8e,0x44,0x00,0x00,0x26,0x31,0xff,0xff,0x90,0x82,0x00,0x10,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x03,0x26,0x52,0x00,0x04,0x0c,0x00,0x20,0xd0,0x00,0x00,0x00,0x00,
+0x06,0x21,0xff,0xf7,0x24,0x02,0xff,0xdf,0x02,0x02,0x80,0x24,0x3c,0x01,0xb0,0x03,
+0x0c,0x00,0x13,0x18,0xac,0x30,0x00,0x00,0x08,0x00,0x12,0xa4,0x00,0x00,0x00,0x00,
+0x8f,0x85,0x8f,0xd0,0x08,0x00,0x12,0xba,0x00,0x00,0x00,0x00,0x24,0x02,0xff,0x95,
+0x3c,0x03,0xb0,0x03,0x02,0x02,0x80,0x24,0x34,0x63,0x00,0x30,0x3c,0x01,0xb0,0x03,
+0xac,0x30,0x00,0x00,0x0c,0x00,0x12,0xe1,0xac,0x60,0x00,0x00,0x08,0x00,0x12,0xa4,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0x50,0x08,0x00,0x12,0xa4,
+0xac,0x46,0x00,0x00,0x3c,0x0a,0x80,0x00,0x25,0x4a,0x4b,0x84,0x3c,0x0b,0xb0,0x03,
+0xad,0x6a,0x00,0x20,0x3c,0x08,0x80,0x01,0x25,0x08,0x00,0x00,0x3c,0x09,0x80,0x01,
+0x25,0x29,0x03,0x1c,0x11,0x09,0x00,0x10,0x00,0x00,0x00,0x00,0x3c,0x0a,0x80,0x00,
+0x25,0x4a,0x4b,0xac,0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,0x3c,0x08,0xb0,0x06,
+0x35,0x08,0x80,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x8d,0x09,0x00,0x00,
+0x00,0x00,0x00,0x00,0x31,0x29,0x00,0x01,0x00,0x00,0x00,0x00,0x24,0x01,0x00,0x01,
+0x15,0x21,0xff,0xf2,0x00,0x00,0x00,0x00,0x3c,0x0a,0x80,0x00,0x25,0x4a,0x4b,0xe8,
+0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,0x3c,0x02,0xb0,0x03,0x8c,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0x34,0x63,0x00,0x40,0x00,0x00,0x00,0x00,0xac,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0x3c,0x0a,0x80,0x00,0x25,0x4a,0x4c,0x14,0x3c,0x0b,0xb0,0x03,
+0xad,0x6a,0x00,0x20,0x3c,0x02,0x80,0x01,0x24,0x42,0x00,0x00,0x3c,0x03,0x80,0x01,
+0x24,0x63,0x03,0x1c,0x3c,0x04,0xb0,0x00,0x8c,0x85,0x00,0x00,0x00,0x00,0x00,0x00,
+0xac,0x45,0x00,0x00,0x24,0x42,0x00,0x04,0x24,0x84,0x00,0x04,0x00,0x43,0x08,0x2a,
+0x14,0x20,0xff,0xf9,0x00,0x00,0x00,0x00,0x0c,0x00,0x13,0x18,0x00,0x00,0x00,0x00,
+0x3c,0x0a,0x80,0x00,0x25,0x4a,0x4c,0x60,0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,
+0x3c,0x02,0x80,0x01,0x24,0x42,0x03,0x20,0x3c,0x03,0x80,0x01,0x24,0x63,0x3f,0x14,
+0xac,0x40,0x00,0x00,0xac,0x40,0x00,0x04,0xac,0x40,0x00,0x08,0xac,0x40,0x00,0x0c,
+0x24,0x42,0x00,0x10,0x00,0x43,0x08,0x2a,0x14,0x20,0xff,0xf9,0x00,0x00,0x00,0x00,
+0x3c,0x0a,0x80,0x00,0x25,0x4a,0x4c,0xa0,0x3c,0x0b,0xb0,0x03,0xad,0x6a,0x00,0x20,
+0x3c,0x1c,0x80,0x01,0x27,0x9c,0x7f,0xf0,0x27,0x9d,0x8b,0xd0,0x00,0x00,0x00,0x00,
+0x27,0x9d,0x8f,0xb8,0x3c,0x0a,0x80,0x00,0x25,0x4a,0x4c,0xc4,0x3c,0x0b,0xb0,0x03,
+0xad,0x6a,0x00,0x20,0x40,0x80,0x68,0x00,0x40,0x08,0x60,0x00,0x00,0x00,0x00,0x00,
+0x35,0x08,0xff,0x01,0x40,0x88,0x60,0x00,0x00,0x00,0x00,0x00,0x0c,0x00,0x15,0x65,
+0x00,0x00,0x00,0x00,0x24,0x84,0xf8,0x00,0x30,0x87,0x00,0x03,0x00,0x04,0x30,0x40,
+0x00,0xc7,0x20,0x23,0x3c,0x02,0xb0,0x0a,0x27,0xbd,0xff,0xe0,0x24,0x03,0xff,0xff,
+0x00,0x82,0x20,0x21,0xaf,0xb1,0x00,0x14,0xac,0x83,0x10,0x00,0xaf,0xbf,0x00,0x18,
+0xaf,0xb0,0x00,0x10,0x00,0xa0,0x88,0x21,0x24,0x03,0x00,0x01,0x8c,0x82,0x10,0x00,
+0x00,0x00,0x00,0x00,0x14,0x43,0xff,0xfd,0x00,0xc7,0x10,0x23,0x3c,0x03,0xb0,0x0a,
+0x00,0x43,0x10,0x21,0x8c,0x50,0x00,0x00,0x0c,0x00,0x13,0x95,0x02,0x20,0x20,0x21,
+0x02,0x11,0x80,0x24,0x00,0x50,0x80,0x06,0x02,0x00,0x10,0x21,0x8f,0xbf,0x00,0x18,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x27,0xbd,0xff,0xd8,
+0xaf,0xb2,0x00,0x18,0x00,0xa0,0x90,0x21,0x24,0x05,0xff,0xff,0xaf,0xb3,0x00,0x1c,
+0xaf,0xbf,0x00,0x20,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0x00,0xc0,0x98,0x21,
+0x12,0x45,0x00,0x23,0x24,0x84,0xf8,0x00,0x30,0x83,0x00,0x03,0x00,0x04,0x10,0x40,
+0x00,0x40,0x88,0x21,0x00,0x60,0x20,0x21,0x00,0x43,0x10,0x23,0x3c,0x03,0xb0,0x0a,
+0x00,0x43,0x10,0x21,0xac,0x45,0x10,0x00,0x00,0x40,0x18,0x21,0x24,0x05,0x00,0x01,
+0x8c,0x62,0x10,0x00,0x00,0x00,0x00,0x00,0x14,0x45,0xff,0xfd,0x3c,0x02,0xb0,0x0a,
+0x02,0x24,0x88,0x23,0x02,0x22,0x88,0x21,0x8e,0x30,0x00,0x00,0x0c,0x00,0x13,0x95,
+0x02,0x40,0x20,0x21,0x00,0x12,0x18,0x27,0x02,0x03,0x80,0x24,0x00,0x53,0x10,0x04,
+0x02,0x02,0x80,0x25,0xae,0x30,0x00,0x00,0x24,0x03,0x00,0x01,0x8e,0x22,0x10,0x00,
+0x00,0x00,0x00,0x00,0x14,0x43,0xff,0xfd,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x20,
+0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,
+0x30,0x82,0x00,0x03,0x00,0x04,0x18,0x40,0x00,0x62,0x18,0x23,0x3c,0x04,0xb0,0x0a,
+0x00,0x64,0x18,0x21,0xac,0x66,0x00,0x00,0x24,0x04,0x00,0x01,0x8c,0x62,0x10,0x00,
+0x00,0x00,0x00,0x00,0x14,0x44,0xff,0xfd,0x00,0x00,0x00,0x00,0x08,0x00,0x13,0x83,
+0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x21,0x00,0x64,0x10,0x06,0x30,0x42,0x00,0x01,
+0x14,0x40,0x00,0x05,0x00,0x00,0x00,0x00,0x24,0x63,0x00,0x01,0x2c,0x62,0x00,0x20,
+0x14,0x40,0xff,0xf9,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x60,0x10,0x21,
+0x27,0xbd,0xff,0xe0,0x3c,0x03,0xb0,0x05,0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x1c,0x00,0x80,0x90,0x21,0x00,0xa0,0x80,0x21,
+0x00,0xc0,0x88,0x21,0x34,0x63,0x02,0x2e,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0x01,0x14,0x40,0xff,0xfc,0x24,0x04,0x08,0x24,0x3c,0x05,0x00,0xc0,
+0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x03,0x24,0x04,0x08,0x34,0x3c,0x05,0x00,0xc0,
+0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x03,0x3c,0x02,0xc0,0x00,0x00,0x10,0x1c,0x00,
+0x34,0x42,0x04,0x00,0x3c,0x04,0xb0,0x05,0x3c,0x05,0xb0,0x05,0x24,0x63,0x16,0x09,
+0x02,0x22,0x10,0x21,0x34,0x84,0x04,0x20,0x34,0xa5,0x04,0x24,0x3c,0x06,0xb0,0x05,
+0xac,0x83,0x00,0x00,0x24,0x07,0x00,0x01,0xac,0xa2,0x00,0x00,0x34,0xc6,0x02,0x28,
+0x24,0x02,0x00,0x20,0xae,0x47,0x00,0x3c,0x24,0x04,0x08,0x24,0xa0,0xc2,0x00,0x00,
+0x3c,0x05,0x00,0xc0,0xa2,0x47,0x00,0x11,0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x01,
+0x24,0x04,0x08,0x34,0x3c,0x05,0x00,0xc0,0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x01,
+0x8f,0xbf,0x00,0x1c,0x8f,0xb2,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x20,0x24,0x02,0x00,0x06,0xac,0x82,0x00,0x0c,0xa0,0x80,0x00,0x50,
+0xac,0x80,0x00,0x00,0xac,0x80,0x00,0x04,0xac,0x80,0x00,0x08,0xac,0x80,0x00,0x14,
+0xac,0x80,0x00,0x18,0xac,0x80,0x00,0x1c,0xa4,0x80,0x00,0x20,0xac,0x80,0x00,0x24,
+0xac,0x80,0x00,0x28,0xac,0x80,0x00,0x2c,0xa0,0x80,0x00,0x30,0xa0,0x80,0x00,0x31,
+0xac,0x80,0x00,0x34,0xac,0x80,0x00,0x38,0xa0,0x80,0x00,0x3c,0xac,0x82,0x00,0x10,
+0xa0,0x80,0x00,0x44,0xac,0x80,0x00,0x48,0x03,0xe0,0x00,0x08,0xac,0x80,0x00,0x4c,
+0x3c,0x04,0xb0,0x06,0x34,0x84,0x80,0x00,0x8c,0x83,0x00,0x00,0x3c,0x02,0x12,0x00,
+0x3c,0x05,0xb0,0x03,0x00,0x62,0x18,0x25,0x34,0xa5,0x00,0x8b,0x24,0x02,0xff,0x80,
+0xac,0x83,0x00,0x00,0x03,0xe0,0x00,0x08,0xa0,0xa2,0x00,0x00,0x3c,0x04,0xb0,0x03,
+0x34,0x84,0x00,0x0b,0x24,0x02,0x00,0x22,0x3c,0x05,0xb0,0x01,0x3c,0x06,0x45,0x67,
+0x3c,0x0a,0xb0,0x09,0xa0,0x82,0x00,0x00,0x34,0xa5,0x00,0x04,0x34,0xc6,0x89,0xaa,
+0x35,0x4a,0x00,0x04,0x24,0x02,0x01,0x23,0x3c,0x0b,0xb0,0x09,0x3c,0x07,0x01,0x23,
+0x3c,0x0c,0xb0,0x09,0x3c,0x01,0xb0,0x01,0xac,0x20,0x00,0x00,0x27,0xbd,0xff,0xe0,
+0xac,0xa0,0x00,0x00,0x35,0x6b,0x00,0x08,0x3c,0x01,0xb0,0x09,0xac,0x26,0x00,0x00,
+0x34,0xe7,0x45,0x66,0xa5,0x42,0x00,0x00,0x35,0x8c,0x00,0x0c,0x24,0x02,0xcd,0xef,
+0x3c,0x0d,0xb0,0x09,0x3c,0x08,0xcd,0xef,0x3c,0x0e,0xb0,0x09,0xad,0x67,0x00,0x00,
+0xaf,0xb7,0x00,0x1c,0xa5,0x82,0x00,0x00,0xaf,0xb6,0x00,0x18,0xaf,0xb5,0x00,0x14,
+0xaf,0xb4,0x00,0x10,0xaf,0xb3,0x00,0x0c,0xaf,0xb2,0x00,0x08,0xaf,0xb1,0x00,0x04,
+0xaf,0xb0,0x00,0x00,0x35,0xad,0x00,0x10,0x35,0x08,0x01,0x22,0x35,0xce,0x00,0x14,
+0x24,0x02,0x89,0xab,0x3c,0x0f,0xb0,0x09,0x3c,0x09,0x89,0xab,0x3c,0x10,0xb0,0x09,
+0x3c,0x11,0xb0,0x09,0x3c,0x12,0xb0,0x09,0x3c,0x13,0xb0,0x09,0x3c,0x14,0xb0,0x09,
+0x3c,0x15,0xb0,0x09,0x3c,0x16,0xb0,0x09,0x3c,0x17,0xb0,0x09,0xad,0xa8,0x00,0x00,
+0x24,0x03,0xff,0xff,0xa5,0xc2,0x00,0x00,0x35,0xef,0x00,0x18,0x35,0x29,0xcd,0xee,
+0x36,0x10,0x00,0x1c,0x36,0x31,0x00,0x20,0x36,0x52,0x00,0x24,0x36,0x73,0x00,0x28,
+0x36,0x94,0x00,0x2c,0x36,0xb5,0x00,0x30,0x36,0xd6,0x00,0x34,0x36,0xf7,0x00,0x38,
+0x24,0x02,0x45,0x67,0xad,0xe9,0x00,0x00,0xa6,0x02,0x00,0x00,0xae,0x23,0x00,0x00,
+0x8f,0xb0,0x00,0x00,0xa6,0x43,0x00,0x00,0x8f,0xb1,0x00,0x04,0xae,0x63,0x00,0x00,
+0x8f,0xb2,0x00,0x08,0xa6,0x83,0x00,0x00,0x8f,0xb3,0x00,0x0c,0xae,0xa3,0x00,0x00,
+0x8f,0xb4,0x00,0x10,0xa6,0xc3,0x00,0x00,0x8f,0xb5,0x00,0x14,0xae,0xe3,0x00,0x00,
+0x7b,0xb6,0x00,0xfc,0x3c,0x18,0xb0,0x09,0x37,0x18,0x00,0x3c,0xa7,0x03,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x34,0x63,0x00,0x20,0x24,0x42,0x51,0x38,0xac,0x62,0x00,0x00,0x8c,0x83,0x00,0x34,
+0x34,0x02,0xff,0xff,0x00,0x43,0x10,0x2a,0x14,0x40,0x01,0x0b,0x00,0x80,0x30,0x21,
+0x8c,0x84,0x00,0x08,0x24,0x02,0x00,0x03,0x10,0x82,0x00,0xfe,0x00,0x00,0x00,0x00,
+0x8c,0xc2,0x00,0x2c,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x47,0x24,0x02,0x00,0x06,
+0x3c,0x03,0xb0,0x05,0x34,0x63,0x04,0x50,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0xff,0x14,0x40,0x00,0xe4,0xac,0xc2,0x00,0x2c,0x24,0x02,0x00,0x01,
+0x10,0x82,0x00,0xe3,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,0x10,0x82,0x00,0xd1,
+0x00,0x00,0x00,0x00,0x8c,0xc7,0x00,0x04,0x24,0x02,0x00,0x02,0x10,0xe2,0x00,0xc7,
+0x00,0x00,0x00,0x00,0x8c,0xc2,0x00,0x14,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x09,
+0x24,0x02,0x00,0x01,0x3c,0x03,0xb0,0x09,0x34,0x63,0x01,0x60,0x90,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0x10,0x40,0x00,0x05,0xac,0xc2,0x00,0x14,
+0x24,0x02,0x00,0x01,0xac,0xc2,0x00,0x00,0x03,0xe0,0x00,0x08,0xac,0xc0,0x00,0x14,
+0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0xd0,0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,
+0x04,0x61,0x00,0x16,0x3c,0x03,0xb0,0x05,0x34,0x63,0x02,0x2e,0x90,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,0x14,0x40,0x00,0x10,0x3c,0x02,0xb0,0x05,
+0x34,0x42,0x02,0x42,0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x60,0x00,0x0b,
+0x00,0x00,0x00,0x00,0x80,0xc2,0x00,0x50,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x07,
+0x00,0x00,0x00,0x00,0x14,0x80,0x00,0x05,0x24,0x02,0x00,0x0e,0x24,0x03,0x00,0x01,
+0xac,0xc2,0x00,0x00,0x03,0xe0,0x00,0x08,0xa0,0xc3,0x00,0x50,0x80,0xc2,0x00,0x31,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x0a,0x3c,0x02,0xb0,0x06,0x34,0x42,0x80,0x18,
+0x8c,0x43,0x00,0x00,0x3c,0x04,0xf0,0x00,0x3c,0x02,0x80,0x00,0x00,0x64,0x18,0x24,
+0x10,0x62,0x00,0x03,0x24,0x02,0x00,0x09,0x03,0xe0,0x00,0x08,0xac,0xc2,0x00,0x00,
+0x8c,0xc2,0x00,0x40,0x00,0x00,0x00,0x00,0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,
+0x10,0x60,0x00,0x09,0x3c,0x03,0xb0,0x03,0x3c,0x02,0xb0,0x05,0x34,0x42,0x02,0x2c,
+0x8c,0x43,0x00,0x00,0x3c,0x04,0x00,0x02,0x00,0x64,0x18,0x24,0x14,0x60,0xff,0xf2,
+0x24,0x02,0x00,0x10,0x3c,0x03,0xb0,0x03,0x34,0x63,0x02,0x01,0x90,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x80,0x10,0x40,0x00,0x0e,0x00,0x00,0x00,0x00,
+0x8c,0xc3,0x00,0x0c,0x00,0x00,0x00,0x00,0xac,0xc3,0x00,0x10,0x3c,0x02,0xb0,0x03,
+0x90,0x42,0x02,0x01,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x0f,0xac,0xc2,0x00,0x0c,
+0x90,0xc3,0x00,0x0f,0x24,0x02,0x00,0x0d,0x3c,0x01,0xb0,0x03,0x08,0x00,0x14,0xa6,
+0xa0,0x23,0x02,0x01,0x3c,0x02,0xb0,0x09,0x34,0x42,0x01,0x80,0x90,0x44,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x04,0x1e,0x00,0x00,0x03,0x1e,0x03,0x10,0x60,0x00,0x15,
+0xa0,0xc4,0x00,0x44,0x24,0x02,0x00,0x01,0x10,0x62,0x00,0x0b,0x24,0x02,0x00,0x02,
+0x10,0x62,0x00,0x03,0x24,0x03,0x00,0x0d,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x8c,0xc2,0x00,0x0c,0xac,0xc3,0x00,0x00,0x24,0x03,0x00,0x04,0xac,0xc2,0x00,0x10,
+0x03,0xe0,0x00,0x08,0xac,0xc3,0x00,0x0c,0x24,0x02,0x00,0x0d,0xac,0xc2,0x00,0x00,
+0x24,0x03,0x00,0x04,0x24,0x02,0x00,0x06,0xac,0xc3,0x00,0x10,0x03,0xe0,0x00,0x08,
+0xac,0xc2,0x00,0x0c,0x8c,0xc3,0x00,0x38,0x00,0x00,0x00,0x00,0x2c,0x62,0x00,0x06,
+0x10,0x40,0x00,0x2e,0x00,0x03,0x10,0x80,0x3c,0x03,0x80,0x01,0x24,0x63,0x02,0x00,
+0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x08,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xe2,0x00,0x06,0x24,0x02,0x00,0x03,
+0x8c,0xa2,0x02,0xbc,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x06,0x3c,0x03,0xb0,0x06,
+0x24,0x02,0x00,0x02,0xac,0xc2,0x00,0x00,0x24,0x02,0x00,0x01,0x03,0xe0,0x00,0x08,
+0xac,0xc2,0x00,0x38,0x34,0x63,0x80,0x24,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0xff,0x10,0x40,0x00,0x05,0xac,0xc2,0x00,0x18,0x24,0x02,0x00,0x02,
+0xac,0xc2,0x00,0x00,0x08,0x00,0x14,0xfa,0xac,0xc0,0x00,0x18,0x08,0x00,0x14,0xfa,
+0xac,0xc0,0x00,0x00,0x24,0x02,0x00,0x02,0x24,0x03,0x00,0x0b,0xac,0xc2,0x00,0x38,
+0x03,0xe0,0x00,0x08,0xac,0xc3,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xe2,0x00,0x05,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x0c,0xac,0xc2,0x00,0x00,0x08,0x00,0x14,0xfb,
+0x24,0x02,0x00,0x04,0x08,0x00,0x15,0x12,0x24,0x02,0x00,0x03,0xac,0xc0,0x00,0x38,
+0x03,0xe0,0x00,0x08,0xac,0xc0,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xe2,0x00,0x05,
+0x24,0x02,0x00,0x03,0x80,0xc2,0x00,0x30,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x08,
+0x24,0x02,0x00,0x04,0xac,0xc2,0x00,0x00,0x93,0x82,0x86,0x3c,0x00,0x00,0x00,0x00,
+0x14,0x40,0xff,0xd6,0x24,0x02,0x00,0x05,0x03,0xe0,0x00,0x08,0xac,0xc0,0x00,0x38,
+0x08,0x00,0x15,0x22,0xac,0xc0,0x00,0x00,0x3c,0x02,0xb0,0x06,0x34,0x42,0x80,0x18,
+0x8c,0x43,0x00,0x00,0x3c,0x04,0xf0,0x00,0x3c,0x02,0x80,0x00,0x00,0x64,0x18,0x24,
+0x10,0x62,0x00,0x03,0x24,0x02,0x00,0x09,0x08,0x00,0x15,0x26,0xac,0xc2,0x00,0x00,
+0x24,0x02,0x00,0x05,0x08,0x00,0x15,0x18,0xac,0xc2,0x00,0x38,0x80,0xc2,0x00,0x30,
+0x00,0x00,0x00,0x00,0x14,0x40,0xff,0x37,0x24,0x02,0x00,0x04,0x08,0x00,0x14,0xa6,
+0x00,0x00,0x00,0x00,0x84,0xc2,0x00,0x20,0x00,0x00,0x00,0x00,0x10,0x40,0xff,0x66,
+0x24,0x02,0x00,0x06,0x3c,0x02,0xb0,0x05,0x34,0x42,0x02,0x2e,0x90,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x01,0x30,0x63,0x00,0xff,0x00,0x60,0x10,0x21,
+0x14,0x40,0xff,0x24,0xa4,0xc3,0x00,0x20,0x08,0x00,0x14,0xa6,0x24,0x02,0x00,0x06,
+0x8c,0xc2,0x00,0x1c,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0x57,0x24,0x02,0x00,0x05,
+0x3c,0x03,0xb0,0x05,0x34,0x63,0x02,0x2c,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0xff,0x10,0x40,0xff,0x14,0xac,0xc2,0x00,0x1c,0x08,0x00,0x14,0xa6,
+0x24,0x02,0x00,0x05,0x3c,0x02,0xb0,0x05,0x8c,0x42,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x02,0x17,0x42,0x30,0x42,0x00,0x01,0x14,0x40,0xff,0x47,0x24,0x02,0x00,0x06,
+0x08,0x00,0x14,0x5c,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x0a,0x03,0xe0,0x00,0x08,
+0xac,0x82,0x00,0x00,0x27,0xbd,0xff,0xd8,0xaf,0xb0,0x00,0x10,0x27,0x90,0x86,0x48,
+0xaf,0xbf,0x00,0x20,0xaf,0xb3,0x00,0x1c,0xaf,0xb2,0x00,0x18,0x0c,0x00,0x2b,0xe8,
+0xaf,0xb1,0x00,0x14,0xaf,0x90,0x8f,0xd0,0x48,0x02,0x00,0x00,0x0c,0x00,0x13,0xec,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x18,0x4e,0x02,0x00,0x20,0x21,0x0c,0x00,0x00,0x34,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x13,0xf7,0x00,0x00,0x00,0x00,0x27,0x84,0x84,0x68,
+0x0c,0x00,0x27,0xc1,0x00,0x00,0x00,0x00,0x93,0x84,0x80,0x10,0x0c,0x00,0x21,0x9a,
+0x00,0x00,0x00,0x00,0x27,0x84,0x89,0x08,0x0c,0x00,0x06,0xe1,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x01,0x3b,0x00,0x00,0x00,0x00,0x27,0x84,0x84,0x10,0x0c,0x00,0x13,0xd5,
+0x00,0x00,0x00,0x00,0x27,0x82,0x89,0x3c,0xaf,0x82,0x84,0x50,0x0c,0x00,0x00,0x61,
+0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x34,0x63,0x01,0x08,0x3c,0x04,0xb0,0x09,
+0x3c,0x05,0xb0,0x09,0x8c,0x66,0x00,0x00,0x34,0x84,0x01,0x68,0x24,0x02,0xc8,0x80,
+0x34,0xa5,0x01,0x40,0x24,0x03,0x00,0x0a,0xa4,0x82,0x00,0x00,0xa4,0xa3,0x00,0x00,
+0x3c,0x04,0xb0,0x03,0x8c,0x82,0x00,0x00,0x8f,0x87,0x84,0x10,0xaf,0x86,0x84,0x08,
+0x34,0x42,0x00,0x20,0xac,0x82,0x00,0x00,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0x58,
+0x8c,0x43,0x00,0x00,0x2c,0xe4,0x00,0x11,0x34,0x63,0x01,0x00,0xac,0x43,0x00,0x00,
+0x10,0x80,0xff,0xfa,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,0x00,0x07,0x10,0x80,
+0x24,0x63,0x02,0x18,0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x80,0x00,0x08,0x00,0x00,0x00,0x00,0x27,0x84,0x84,0x68,0x0c,0x00,0x26,0xe5,
+0x00,0x00,0x00,0x00,0x27,0x84,0x84,0x10,0x27,0x85,0x86,0x48,0x0c,0x00,0x14,0x4e,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x09,0x34,0x42,0x00,0x07,0x3c,0x03,0xb0,0x06,
+0x90,0x44,0x00,0x00,0x34,0x63,0x80,0x18,0x8c,0x65,0x00,0x00,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x00,0xec,0x3c,0x03,0xb0,0x03,0x30,0x86,0x00,0xff,0xa0,0x46,0x00,0x00,
+0x00,0x05,0x2f,0x02,0x34,0x63,0x00,0xed,0x24,0x02,0x00,0x01,0x10,0xc2,0x00,0x2c,
+0xa0,0x65,0x00,0x00,0xa3,0x80,0x81,0x58,0x93,0x83,0x81,0xf1,0x24,0x02,0x00,0x01,
+0x10,0x62,0x00,0x08,0x00,0x00,0x00,0x00,0x8f,0x87,0x84,0x10,0x8f,0x82,0x84,0x44,
+0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x01,0xaf,0x82,0x84,0x44,0x08,0x00,0x15,0x9b,
+0x3c,0x02,0xb0,0x03,0x8f,0x87,0x84,0x10,0x00,0x00,0x00,0x00,0x24,0xe2,0xff,0xfc,
+0x2c,0x42,0x00,0x03,0x14,0x40,0x00,0x0a,0x3c,0x03,0xb0,0x06,0x93,0x82,0x86,0x3c,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x07,0x34,0x63,0x80,0x18,0x27,0x84,0x84,0x68,
+0x0c,0x00,0x27,0x75,0x00,0x00,0x00,0x00,0x8f,0x87,0x84,0x10,0x3c,0x03,0xb0,0x06,
+0x34,0x63,0x80,0x18,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x17,0x02,
+0x10,0x40,0xff,0xe6,0x00,0x00,0x00,0x00,0x8f,0x82,0xbc,0x10,0x8f,0x84,0xbc,0x18,
+0x3c,0x05,0xb0,0x01,0x00,0x45,0x10,0x21,0xac,0x44,0x00,0x00,0x8f,0x83,0xbc,0x10,
+0x8f,0x82,0xbc,0x14,0x00,0x65,0x18,0x21,0x08,0x00,0x15,0xc7,0xac,0x62,0x00,0x04,
+0x14,0xa0,0xff,0xd4,0x3c,0x02,0xb0,0x03,0x93,0x83,0x81,0x58,0x34,0x42,0x00,0xee,
+0x24,0x63,0x00,0x01,0x30,0x64,0x00,0xff,0x2c,0x84,0x00,0xf1,0xa0,0x43,0x00,0x00,
+0xa3,0x83,0x81,0x58,0x14,0x80,0xff,0xcc,0x00,0x00,0x00,0x00,0xaf,0x86,0x84,0x24,
+0xa3,0x86,0x86,0x23,0x08,0x00,0x15,0xc1,0x00,0x00,0x00,0x00,0x27,0x84,0x84,0x68,
+0x0c,0x00,0x29,0x6e,0x00,0x00,0x00,0x00,0xa3,0x82,0x84,0x41,0x8f,0x82,0x84,0x44,
+0xaf,0x80,0x84,0x10,0x24,0x42,0x00,0x01,0xaf,0x82,0x84,0x44,0x08,0x00,0x15,0x9a,
+0x00,0x00,0x38,0x21,0x27,0x84,0x86,0x48,0x0c,0x00,0x19,0x19,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0xff,0x14,0x40,0x00,0x05,0x3c,0x03,0xb0,0x05,0xaf,0x80,0x84,0x10,
+0xaf,0x80,0x84,0x14,0x08,0x00,0x15,0xc6,0x00,0x00,0x00,0x00,0x34,0x63,0x04,0x50,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0xaf,0x82,0x84,0x3c,
+0x14,0x40,0x00,0x20,0x24,0x02,0x00,0x01,0x8f,0x84,0x84,0x18,0x00,0x00,0x00,0x00,
+0x10,0x82,0x00,0x20,0x3c,0x03,0xb0,0x09,0x34,0x63,0x01,0x60,0x90,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0xaf,0x82,0x84,0x24,0x14,0x40,0x00,0x15,
+0x24,0x02,0x00,0x01,0x24,0x02,0x00,0x02,0x10,0x82,0x00,0x07,0x00,0x00,0x00,0x00,
+0x24,0x07,0x00,0x03,0x24,0x02,0x00,0x01,0xaf,0x82,0x84,0x14,0xaf,0x87,0x84,0x10,
+0x08,0x00,0x15,0xc6,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x05,0x34,0x42,0x02,0x2e,
+0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x01,0x30,0x63,0x00,0xff,
+0x00,0x60,0x10,0x21,0xa7,0x83,0x84,0x30,0x14,0x40,0xff,0xf1,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x01,0xaf,0x82,0x84,0x14,0xaf,0x80,0x84,0x10,0x08,0x00,0x15,0xc6,
+0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x05,0x34,0x63,0x02,0x2c,0x8c,0x62,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0xaf,0x82,0x84,0x2c,0x14,0x40,0xff,0xf5,
+0x24,0x02,0x00,0x01,0x08,0x00,0x16,0x1a,0x3c,0x03,0xb0,0x09,0x27,0x84,0x86,0x48,
+0x0c,0x00,0x1a,0xde,0x00,0x00,0x00,0x00,0x83,0x82,0x84,0x40,0x00,0x00,0x00,0x00,
+0x14,0x40,0xff,0xec,0x24,0x02,0x00,0x02,0x3c,0x03,0xb0,0x05,0x34,0x63,0x04,0x50,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,0xaf,0x82,0x84,0x3c,
+0x14,0x40,0xff,0xe4,0x24,0x02,0x00,0x02,0x8f,0x84,0x84,0x18,0x24,0x02,0x00,0x01,
+0x10,0x82,0x00,0x12,0x24,0x02,0x00,0x02,0x10,0x82,0x00,0x04,0x00,0x00,0x00,0x00,
+0x24,0x07,0x00,0x04,0x08,0x00,0x16,0x26,0x24,0x02,0x00,0x02,0x3c,0x02,0xb0,0x05,
+0x34,0x42,0x02,0x2e,0x90,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x01,
+0x30,0x63,0x00,0xff,0x00,0x60,0x10,0x21,0xa7,0x83,0x84,0x30,0x14,0x40,0xff,0xf4,
+0x00,0x00,0x00,0x00,0x08,0x00,0x16,0x35,0x24,0x02,0x00,0x02,0x3c,0x03,0xb0,0x05,
+0x34,0x63,0x02,0x2c,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xff,
+0xaf,0x82,0x84,0x2c,0x14,0x40,0xff,0xf7,0x00,0x00,0x00,0x00,0x08,0x00,0x16,0x56,
+0x24,0x02,0x00,0x02,0x27,0x84,0x89,0x08,0x0c,0x00,0x0b,0x51,0x00,0x00,0x00,0x00,
+0x8f,0x83,0x84,0x14,0xaf,0x82,0x84,0x2c,0x38,0x64,0x00,0x02,0x00,0x04,0x18,0x0a,
+0xaf,0x83,0x84,0x14,0x14,0x40,0xff,0xad,0x24,0x07,0x00,0x05,0x8f,0x82,0x89,0x48,
+0xaf,0x80,0x84,0x10,0x10,0x40,0x00,0x02,0x24,0x04,0x00,0x01,0xaf,0x84,0x84,0x18,
+0x93,0x82,0x89,0x56,0x00,0x00,0x00,0x00,0x10,0x40,0xff,0x43,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xb0,0x05,0x34,0x42,0x00,0x08,0x8c,0x43,0x00,0x00,0x3c,0x04,0x20,0x00,
+0x00,0x64,0x18,0x24,0x10,0x60,0xff,0x3c,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x00,0xa0,0x8c,0x43,0x00,0x00,0x3c,0x04,0x80,0x00,0xaf,0x80,0x89,0x30,
+0x24,0x63,0x00,0x01,0xac,0x43,0x00,0x00,0x3c,0x01,0xb0,0x05,0xac,0x24,0x00,0x08,
+0xaf,0x80,0x89,0x2c,0xaf,0x80,0x89,0x34,0xaf,0x80,0x89,0x38,0xaf,0x80,0x89,0x44,
+0xaf,0x80,0x89,0x3c,0x08,0x00,0x15,0xc6,0x00,0x00,0x00,0x00,0x83,0x82,0x84,0x60,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x02,0x24,0x02,0x00,0x20,0xaf,0x82,0x84,0x2c,
+0x8f,0x85,0x84,0x2c,0x27,0x84,0x89,0x08,0x0c,0x00,0x0d,0x2c,0x00,0x00,0x00,0x00,
+0x00,0x02,0x1e,0x00,0xa3,0x82,0x84,0x40,0xaf,0x80,0x84,0x2c,0x10,0x60,0xff,0x8e,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x05,0x34,0x42,0x02,0x2e,0x90,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x01,0x30,0x63,0x00,0xff,0x00,0x60,0x10,0x21,
+0xa7,0x83,0x84,0x30,0x10,0x40,0x00,0x04,0x24,0x04,0x00,0x02,0xaf,0x84,0x84,0x18,
+0x08,0x00,0x16,0x36,0x00,0x00,0x00,0x00,0x08,0x00,0x16,0x27,0x24,0x07,0x00,0x06,
+0x27,0x84,0x84,0x10,0x27,0x85,0x89,0x08,0x0c,0x00,0x0d,0xf9,0x00,0x00,0x00,0x00,
+0x8f,0x82,0x84,0x34,0xaf,0x80,0x84,0x3c,0x14,0x40,0x00,0x19,0x00,0x40,0x18,0x21,
+0x8f,0x82,0x84,0x38,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x15,0x24,0x02,0x00,0x02,
+0x8f,0x83,0x84,0x18,0x00,0x00,0x00,0x00,0x10,0x62,0x00,0x0b,0x3c,0x02,0x40,0x00,
+0x8f,0x83,0x84,0x14,0x24,0x02,0x00,0x01,0x10,0x62,0x00,0x02,0x24,0x07,0x00,0x03,
+0x24,0x07,0x00,0x06,0xaf,0x87,0x84,0x10,0x24,0x04,0x00,0x03,0xaf,0x84,0x84,0x18,
+0x08,0x00,0x15,0xc6,0x00,0x00,0x00,0x00,0x34,0x42,0x00,0x14,0x3c,0x01,0xb0,0x05,
+0xac,0x22,0x00,0x00,0xaf,0x80,0x84,0x10,0x08,0x00,0x16,0xcf,0x24,0x04,0x00,0x03,
+0x10,0x60,0x00,0x10,0x00,0x00,0x00,0x00,0x27,0x84,0x84,0x10,0x27,0x85,0x89,0x08,
+0x0c,0x00,0x0e,0x1d,0x00,0x00,0x00,0x00,0x8f,0x83,0x84,0x14,0x24,0x02,0x00,0x01,
+0xa3,0x80,0x84,0x40,0xaf,0x80,0x84,0x18,0x10,0x62,0x00,0x02,0x24,0x07,0x00,0x03,
+0x24,0x07,0x00,0x04,0xaf,0x87,0x84,0x10,0xaf,0x80,0x84,0x34,0x08,0x00,0x15,0xc6,
+0x00,0x00,0x00,0x00,0x83,0x82,0x84,0x60,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x04,
+0x00,0x00,0x00,0x00,0x27,0x84,0x89,0x08,0x0c,0x00,0x10,0x65,0x00,0x00,0x00,0x00,
+0x8f,0x82,0x84,0x14,0xa3,0x80,0x84,0x40,0xaf,0x80,0x84,0x10,0xaf,0x80,0x84,0x18,
+0x14,0x40,0x00,0x03,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,0xaf,0x82,0x84,0x14,
+0xaf,0x80,0x84,0x38,0x08,0x00,0x15,0xc6,0x00,0x00,0x00,0x00,0x27,0x84,0x84,0x10,
+0x27,0x85,0x89,0x08,0x0c,0x00,0x0e,0x1d,0x00,0x00,0x00,0x00,0x8f,0x82,0x84,0x14,
+0xa3,0x80,0x84,0x40,0xaf,0x80,0x84,0x10,0xaf,0x80,0x84,0x18,0x14,0x40,0xfe,0xc2,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,0xaf,0x82,0x84,0x14,0x08,0x00,0x15,0xc6,
+0x00,0x00,0x00,0x00,0x27,0x84,0x89,0x08,0x0c,0x00,0x10,0x65,0x00,0x00,0x00,0x00,
+0x08,0x00,0x16,0xff,0x00,0x00,0x00,0x00,0x27,0x84,0x84,0x68,0x0c,0x00,0x2a,0x96,
+0x00,0x00,0x00,0x00,0x08,0x00,0x15,0xfe,0x00,0x00,0x00,0x00,0x0c,0x00,0x24,0x66,
+0x00,0x00,0x00,0x00,0x0c,0x00,0x27,0x56,0x00,0x00,0x00,0x00,0x0c,0x00,0x18,0x40,
+0x00,0x00,0x00,0x00,0x27,0x84,0x84,0x68,0x0c,0x00,0x27,0x64,0x00,0x00,0x00,0x00,
+0x93,0x83,0xbc,0x08,0x00,0x00,0x00,0x00,0x14,0x60,0x00,0x2b,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x01,0x08,0x8c,0x44,0x00,0x00,0x8f,0x83,0xbc,0x00,0x8f,0x82,0xbc,0x04,
+0x00,0x83,0x18,0x23,0x00,0x43,0x10,0x2b,0x10,0x40,0x00,0x23,0x3c,0x02,0xb0,0x03,
+0x24,0x04,0x05,0xa0,0x34,0x42,0x01,0x18,0x8c,0x42,0x00,0x00,0x0c,0x00,0x06,0xce,
+0x00,0x00,0x00,0x00,0x24,0x04,0x05,0xa4,0x0c,0x00,0x06,0xce,0x00,0x02,0x84,0x02,
+0x30,0x51,0xff,0xff,0x24,0x04,0x05,0xa8,0x00,0x02,0x94,0x02,0x0c,0x00,0x06,0xce,
+0x3a,0x10,0xff,0xff,0x3a,0x31,0xff,0xff,0x30,0x42,0xff,0xff,0x2e,0x10,0x00,0x01,
+0x2e,0x31,0x00,0x01,0x3a,0x52,0xff,0xff,0x02,0x11,0x80,0x25,0x2e,0x52,0x00,0x01,
+0x38,0x42,0xff,0xff,0x02,0x12,0x80,0x25,0x2c,0x42,0x00,0x01,0x02,0x02,0x80,0x25,
+0x16,0x00,0x00,0x02,0x24,0x04,0x00,0x02,0x00,0x00,0x20,0x21,0x0c,0x00,0x05,0x70,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x34,0x42,0x01,0x08,0x8c,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0xaf,0x83,0xbc,0x00,0x0c,0x00,0x01,0xeb,0x00,0x00,0x00,0x00,
+0xaf,0x80,0x84,0x10,0xaf,0x80,0x84,0x44,0x08,0x00,0x15,0x9a,0x00,0x00,0x38,0x21,
+0x27,0x90,0xb3,0xf0,0x24,0x11,0x00,0x12,0x8e,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
+0x90,0x82,0x00,0x10,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x03,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x20,0xd0,0x00,0x00,0x00,0x00,0x26,0x31,0xff,0xff,0x06,0x21,0xff,0xf6,
+0x26,0x10,0x00,0x04,0xaf,0x80,0x84,0x10,0x08,0x00,0x15,0xc7,0x00,0x00,0x38,0x21,
+0x3c,0x02,0xb0,0x03,0x34,0x42,0x01,0x08,0x8c,0x44,0x00,0x00,0x8f,0x82,0x84,0x08,
+0x00,0x04,0x19,0xc2,0x00,0x02,0x11,0xc2,0x10,0x62,0xff,0xf6,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xb0,0x03,0x34,0x42,0x01,0x02,0x90,0x43,0x00,0x00,0x3c,0x12,0xb0,0x05,
+0xaf,0x84,0x84,0x08,0x30,0x63,0x00,0xff,0x00,0x03,0x11,0x40,0x00,0x43,0x10,0x23,
+0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x00,0x02,0x99,0x00,0x00,0x00,0x88,0x21,
+0x36,0x52,0x02,0x2c,0x27,0x90,0xb3,0xf0,0x8e,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
+0x90,0x83,0x00,0x16,0x00,0x00,0x00,0x00,0x30,0x62,0x00,0x03,0x10,0x40,0x00,0x06,
+0x30,0x62,0x00,0x1c,0x14,0x40,0x00,0x04,0x00,0x00,0x00,0x00,0x8f,0x85,0x84,0x08,
+0x0c,0x00,0x1e,0xb2,0x02,0x60,0x30,0x21,0x8e,0x42,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0xff,0x14,0x40,0xff,0xd7,0x00,0x00,0x00,0x00,0x26,0x31,0x00,0x01,
+0x2a,0x22,0x00,0x13,0x14,0x40,0xff,0xec,0x26,0x10,0x00,0x04,0x08,0x00,0x17,0x5d,
+0x00,0x00,0x00,0x00,0x8f,0x84,0x84,0x1c,0x27,0x85,0x89,0x08,0x0c,0x00,0x17,0xd3,
+0x00,0x00,0x00,0x00,0x8f,0x83,0x84,0x1c,0x24,0x02,0x00,0x04,0x14,0x62,0xfe,0xa2,
+0x00,0x00,0x00,0x00,0x08,0x00,0x16,0x27,0x24,0x07,0x00,0x05,0x27,0x84,0x89,0x08,
+0x0c,0x00,0x24,0x8d,0x00,0x00,0x00,0x00,0x24,0x07,0x00,0x05,0xaf,0x87,0x84,0x10,
+0x08,0x00,0x15,0xc7,0x00,0x00,0x00,0x00,0x8f,0x82,0x89,0x3c,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x0d,0x00,0x00,0x00,0x00,0x8f,0x84,0xb4,0x30,0xaf,0x80,0x89,0x3c,
+0x94,0x85,0x00,0x14,0x0c,0x00,0x1b,0x84,0x00,0x00,0x00,0x00,0x93,0x82,0x8b,0x61,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x02,0x10,0x40,0x00,0x03,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x01,0x59,0x00,0x00,0x20,0x21,0x8f,0x84,0xb4,0x30,0x0c,0x00,0x20,0xd0,
+0x00,0x00,0x00,0x00,0x08,0x00,0x17,0x5d,0x00,0x00,0x00,0x00,0x3c,0x02,0xff,0x90,
+0x27,0xbd,0xff,0xe8,0x00,0x80,0x18,0x21,0x34,0x42,0x00,0x01,0x27,0x84,0x89,0x08,
+0x10,0x62,0x00,0x05,0xaf,0xbf,0x00,0x10,0x8f,0xbf,0x00,0x10,0x00,0x00,0x00,0x00,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x0c,0x00,0x06,0xe1,0x00,0x00,0x00,0x00,
+0x27,0x84,0x86,0x48,0x0c,0x00,0x18,0x4e,0x00,0x00,0x00,0x00,0x27,0x84,0x84,0x10,
+0x0c,0x00,0x13,0xd5,0x00,0x00,0x00,0x00,0x08,0x00,0x17,0xba,0x00,0x00,0x00,0x00,
+0x8f,0x82,0x89,0x48,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x05,0x00,0x00,0x18,0x21,
+0x8f,0x82,0x84,0x18,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x02,0x00,0x00,0x00,0x00,
+0x24,0x03,0x00,0x01,0x03,0xe0,0x00,0x08,0x00,0x60,0x10,0x21,0x27,0xbd,0xff,0xe0,
+0x3c,0x06,0xb0,0x03,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0x34,0xc6,0x00,0x5f,
+0xaf,0xbf,0x00,0x18,0x90,0xc3,0x00,0x00,0x3c,0x07,0xb0,0x03,0x34,0xe7,0x00,0x5d,
+0x34,0x63,0x00,0x01,0x3c,0x09,0xb0,0x03,0x24,0x02,0x00,0x01,0xa0,0xc3,0x00,0x00,
+0x00,0x80,0x80,0x21,0xa0,0xe2,0x00,0x00,0x00,0xa0,0x88,0x21,0x35,0x29,0x00,0x5e,
+0x00,0xe0,0x40,0x21,0x24,0x04,0x00,0x01,0x91,0x22,0x00,0x00,0x91,0x03,0x00,0x00,
+0x30,0x42,0x00,0x01,0x14,0x83,0x00,0x03,0x30,0x42,0x00,0x01,0x14,0x40,0xff,0xfa,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x04,0x12,0x02,0x00,0x2c,0x24,0x05,0x0f,0x00,
+0x24,0x02,0x00,0x06,0x12,0x02,0x00,0x08,0x24,0x05,0x00,0x0f,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x02,0x00,0xa0,0x50,0x00,0x00,0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,0x24,0x04,0x0c,0x04,0x0c,0x00,0x13,0x5b,
+0x24,0x06,0x00,0x0f,0x24,0x04,0x0d,0x04,0x24,0x05,0x00,0x0f,0x0c,0x00,0x13,0x5b,
+0x24,0x06,0x00,0x0f,0x24,0x04,0x08,0x80,0x24,0x05,0x1e,0x00,0x0c,0x00,0x13,0x5b,
+0x24,0x06,0x00,0x0f,0x24,0x04,0x08,0x8c,0x24,0x05,0x0f,0x00,0x0c,0x00,0x13,0x5b,
+0x24,0x06,0x00,0x0f,0x24,0x04,0x08,0x24,0x3c,0x05,0x00,0x30,0x0c,0x00,0x13,0x5b,
+0x24,0x06,0x00,0x02,0x24,0x04,0x08,0x2c,0x3c,0x05,0x00,0x30,0x0c,0x00,0x13,0x5b,
+0x24,0x06,0x00,0x02,0x24,0x04,0x08,0x34,0x3c,0x05,0x00,0x30,0x0c,0x00,0x13,0x5b,
+0x24,0x06,0x00,0x02,0x24,0x04,0x08,0x3c,0x3c,0x05,0x00,0x30,0x0c,0x00,0x13,0x5b,
+0x24,0x06,0x00,0x02,0x08,0x00,0x17,0xf4,0x3c,0x02,0xb0,0x03,0x24,0x04,0x08,0x8c,
+0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x04,0x24,0x04,0x08,0x80,0x24,0x05,0x1e,0x00,
+0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x04,0x24,0x04,0x0c,0x04,0x24,0x05,0x00,0x0f,
+0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x04,0x24,0x04,0x0d,0x04,0x24,0x05,0x00,0x0f,
+0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x04,0x24,0x04,0x08,0x24,0x3c,0x05,0x00,0x30,
+0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x03,0x24,0x04,0x08,0x2c,0x3c,0x05,0x00,0x30,
+0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x03,0x24,0x04,0x08,0x34,0x3c,0x05,0x00,0x30,
+0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x02,0x3c,0x05,0x00,0x30,0x24,0x06,0x00,0x03,
+0x0c,0x00,0x13,0x5b,0x24,0x04,0x08,0x3c,0x02,0x20,0x20,0x21,0x24,0x05,0x00,0x14,
+0x0c,0x00,0x13,0xa0,0x24,0x06,0x01,0x07,0x08,0x00,0x17,0xf4,0x3c,0x02,0xb0,0x03,
+0x3c,0x03,0xb0,0x03,0x34,0x63,0x00,0x73,0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0x02,0x14,0x40,0x00,0x04,0x00,0x00,0x00,0x00,0xa3,0x80,0x81,0x59,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0xa3,0x82,0x81,0x59,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x00,0x80,0x70,0x21,0x34,0x63,0x00,0x20,0x24,0x42,0x61,0x38,0x3c,0x04,0xb0,0x03,
+0xac,0x62,0x00,0x00,0x34,0x84,0x00,0x30,0xad,0xc0,0x02,0xbc,0xad,0xc0,0x02,0xb8,
+0x8c,0x83,0x00,0x00,0x24,0x02,0x00,0xff,0xa5,0xc0,0x00,0x0a,0x00,0x00,0x30,0x21,
+0xa7,0x82,0x8f,0xe0,0x27,0x88,0x8f,0xf0,0xa5,0xc3,0x00,0x08,0x3c,0x07,0xb0,0x08,
+0x30,0xc2,0xff,0xff,0x00,0x02,0x20,0xc0,0x24,0xc3,0x00,0x01,0x00,0x82,0x10,0x21,
+0x00,0x60,0x30,0x21,0x00,0x02,0x10,0x80,0x30,0x63,0xff,0xff,0x00,0x48,0x10,0x21,
+0x00,0x87,0x20,0x21,0x28,0xc5,0x00,0xff,0xac,0x83,0x00,0x00,0x14,0xa0,0xff,0xf4,
+0xa4,0x43,0x00,0x00,0x3c,0x02,0xb0,0x08,0x34,0x03,0xff,0xff,0x25,0xc4,0x00,0x0c,
+0x24,0x0a,0x00,0x02,0x34,0x42,0x07,0xf8,0x3c,0x06,0xb0,0x03,0xa7,0x83,0xb3,0xcc,
+0xac,0x43,0x00,0x00,0xaf,0x84,0xb3,0xf0,0x34,0xc6,0x00,0x64,0xa0,0x8a,0x00,0x18,
+0x94,0xc5,0x00,0x00,0x8f,0x82,0xb3,0xf0,0x25,0xc4,0x00,0x30,0x24,0x08,0x00,0x03,
+0x3c,0x03,0xb0,0x03,0xa0,0x45,0x00,0x21,0x34,0x63,0x00,0x66,0xaf,0x84,0xb3,0xf4,
+0xa0,0x88,0x00,0x18,0x94,0x65,0x00,0x00,0x8f,0x82,0xb3,0xf4,0x25,0xc4,0x00,0x54,
+0x25,0xc7,0x00,0x78,0xa0,0x45,0x00,0x21,0xaf,0x84,0xb3,0xf8,0xa0,0x88,0x00,0x18,
+0x94,0x65,0x00,0x00,0x8f,0x82,0xb3,0xf8,0x25,0xc8,0x00,0x9c,0x24,0x09,0x00,0x01,
+0xa0,0x45,0x00,0x21,0xaf,0x87,0xb3,0xfc,0xa0,0xea,0x00,0x18,0x94,0xc4,0x00,0x00,
+0x8f,0x82,0xb3,0xfc,0x3c,0x03,0xb0,0x03,0x34,0x63,0x00,0x62,0xa0,0x44,0x00,0x21,
+0xaf,0x88,0xb4,0x00,0xa1,0x09,0x00,0x18,0x94,0x65,0x00,0x00,0x8f,0x82,0xb4,0x00,
+0x25,0xc4,0x00,0xc0,0x3c,0x06,0xb0,0x03,0xa0,0x45,0x00,0x21,0xaf,0x84,0xb4,0x04,
+0xa0,0x89,0x00,0x18,0x94,0x65,0x00,0x00,0x8f,0x82,0xb4,0x04,0x25,0xc4,0x00,0xe4,
+0x34,0xc6,0x00,0x60,0xa0,0x45,0x00,0x21,0xaf,0x84,0xb4,0x08,0xa0,0x80,0x00,0x18,
+0x94,0xc5,0x00,0x00,0x8f,0x82,0xb4,0x08,0x25,0xc3,0x01,0x08,0x25,0xc7,0x01,0x2c,
+0xa0,0x45,0x00,0x21,0xaf,0x83,0xb4,0x0c,0xa0,0x60,0x00,0x18,0x94,0xc8,0x00,0x00,
+0x8f,0x82,0xb4,0x0c,0x25,0xc4,0x01,0x50,0x25,0xc5,0x01,0x74,0xa0,0x48,0x00,0x21,
+0x25,0xc6,0x01,0x98,0x25,0xc9,0x01,0xbc,0x25,0xca,0x01,0xe0,0x25,0xcb,0x02,0x04,
+0x25,0xcc,0x02,0x28,0x25,0xcd,0x02,0x4c,0x24,0x02,0x00,0x10,0x3c,0x03,0xb0,0x03,
+0xaf,0x87,0xb4,0x10,0x34,0x63,0x00,0x38,0xa0,0xe0,0x00,0x18,0xaf,0x84,0xb4,0x14,
+0xa0,0x80,0x00,0x18,0xaf,0x85,0xb4,0x18,0xa0,0xa0,0x00,0x18,0xaf,0x86,0xb4,0x1c,
+0xa0,0xc0,0x00,0x18,0xaf,0x89,0xb4,0x20,0xa1,0x20,0x00,0x18,0xaf,0x8a,0xb4,0x24,
+0xa1,0x40,0x00,0x18,0xaf,0x8b,0xb4,0x28,0xa1,0x60,0x00,0x18,0xaf,0x8c,0xb4,0x2c,
+0xa1,0x80,0x00,0x18,0xaf,0x8d,0xb4,0x30,0xa1,0xa2,0x00,0x18,0x94,0x64,0x00,0x00,
+0x8f,0x82,0xb4,0x30,0x25,0xc5,0x02,0x70,0x3c,0x03,0xb0,0x03,0xa0,0x44,0x00,0x21,
+0x24,0x02,0x00,0x11,0xaf,0x85,0xb4,0x34,0x34,0x63,0x00,0x6e,0xa0,0xa2,0x00,0x18,
+0x94,0x64,0x00,0x00,0x8f,0x82,0xb4,0x34,0x25,0xc5,0x02,0x94,0x3c,0x03,0xb0,0x03,
+0xa0,0x44,0x00,0x21,0x24,0x02,0x00,0x12,0xaf,0x85,0xb4,0x38,0x34,0x63,0x00,0x6c,
+0xa0,0xa2,0x00,0x18,0x94,0x64,0x00,0x00,0x8f,0x82,0xb4,0x38,0x24,0x05,0xff,0xff,
+0x24,0x07,0x00,0x01,0xa0,0x44,0x00,0x21,0x24,0x06,0x00,0x12,0x27,0x84,0xb3,0xf0,
+0x8c,0x82,0x00,0x00,0x24,0xc6,0xff,0xff,0xa0,0x40,0x00,0x04,0x8c,0x83,0x00,0x00,
+0xa4,0x45,0x00,0x00,0xa4,0x45,0x00,0x02,0xa0,0x60,0x00,0x0a,0x8c,0x82,0x00,0x00,
+0xa4,0x65,0x00,0x06,0xa4,0x65,0x00,0x08,0xa0,0x40,0x00,0x10,0x8c,0x83,0x00,0x00,
+0xa4,0x45,0x00,0x0c,0xa4,0x45,0x00,0x0e,0xa0,0x60,0x00,0x12,0x8c,0x82,0x00,0x00,
+0x00,0x00,0x00,0x00,0xa0,0x40,0x00,0x16,0x8c,0x83,0x00,0x00,0xa4,0x45,0x00,0x14,
+0xa0,0x67,0x00,0x17,0x8c,0x82,0x00,0x00,0x24,0x84,0x00,0x04,0xa0,0x40,0x00,0x20,
+0x04,0xc1,0xff,0xe7,0xac,0x40,0x00,0x1c,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x64,0x00,
+0x00,0x05,0x28,0x40,0xac,0x62,0x00,0x00,0x00,0xa6,0x28,0x21,0x2c,0xe2,0x00,0x10,
+0x14,0x80,0x00,0x06,0x00,0x00,0x18,0x21,0x10,0x40,0x00,0x02,0x00,0x00,0x00,0x00,
+0x00,0xe0,0x18,0x21,0x03,0xe0,0x00,0x08,0x00,0x60,0x10,0x21,0x24,0x02,0x00,0x20,
+0x10,0xe2,0x00,0x06,0x2c,0xe4,0x00,0x10,0x24,0xa2,0x00,0x01,0x10,0x80,0xff,0xf9,
+0x00,0x02,0x11,0x00,0x08,0x00,0x19,0x0d,0x00,0x47,0x18,0x21,0x08,0x00,0x19,0x0d,
+0x24,0xa3,0x00,0x50,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x27,0xbd,0xff,0xc8,
+0x34,0x63,0x00,0x20,0x24,0x42,0x64,0x64,0xaf,0xb2,0x00,0x18,0xaf,0xbf,0x00,0x34,
+0xaf,0xbe,0x00,0x30,0xaf,0xb7,0x00,0x2c,0xaf,0xb6,0x00,0x28,0xaf,0xb5,0x00,0x24,
+0xaf,0xb4,0x00,0x20,0xaf,0xb3,0x00,0x1c,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,
+0xac,0x62,0x00,0x00,0x8c,0x86,0x02,0xbc,0x00,0x80,0x90,0x21,0x14,0xc0,0x01,0x66,
+0x00,0xc0,0x38,0x21,0x84,0x82,0x00,0x08,0x3c,0x03,0xb0,0x06,0x94,0x84,0x00,0x08,
+0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x8c,0x45,0x00,0x00,0x8c,0x43,0x00,0x00,
+0x24,0x84,0x00,0x02,0x30,0x84,0x01,0xff,0x30,0xb1,0xff,0xff,0x00,0x03,0x44,0x02,
+0xa6,0x44,0x00,0x08,0x14,0xe0,0x00,0x08,0x3c,0x03,0xb0,0x06,0x34,0x63,0x80,0x24,
+0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x34,0x42,0x01,0x00,0xac,0x62,0x00,0x00,
+0x8e,0x46,0x02,0xbc,0x00,0x00,0x00,0x00,0x14,0xc0,0x01,0x4c,0x00,0x11,0x98,0xc0,
+0x00,0x11,0x3a,0x00,0x3c,0x04,0xb0,0x00,0x00,0xe4,0x20,0x21,0x8c,0x83,0x00,0x0c,
+0x00,0x11,0x98,0xc0,0x02,0x71,0x10,0x21,0x00,0x03,0x1b,0x82,0x30,0x63,0x00,0x1f,
+0x00,0x02,0x10,0x80,0x27,0x9e,0x8f,0xf4,0x00,0x5e,0x10,0x21,0x00,0x60,0x30,0x21,
+0xac,0x44,0x00,0x18,0xae,0x43,0x02,0xbc,0x14,0xc0,0x00,0x10,0x3c,0x02,0xb0,0x00,
+0x00,0x08,0x10,0xc0,0x00,0x48,0x10,0x21,0x27,0x84,0x8f,0xf0,0x00,0x02,0x10,0x80,
+0x00,0x44,0x10,0x21,0x94,0x45,0x00,0x00,0x02,0x71,0x18,0x21,0x00,0x03,0x18,0x80,
+0x00,0x64,0x18,0x21,0x24,0x02,0xff,0xff,0xa4,0x62,0x00,0x02,0xa4,0x68,0x00,0x04,
+0xae,0x51,0x02,0xb8,0xa6,0x45,0x00,0x0a,0x3c,0x02,0xb0,0x00,0x00,0xe2,0x40,0x21,
+0x8d,0x16,0x00,0x00,0x8d,0x14,0x00,0x04,0x02,0x71,0x10,0x21,0x00,0x02,0x38,0x80,
+0x00,0x14,0x1a,0x02,0x27,0x84,0x90,0x00,0x30,0x63,0x00,0x1f,0x24,0x02,0x00,0x10,
+0x00,0xe4,0x20,0x21,0xa6,0x43,0x00,0x06,0x8d,0x10,0x00,0x08,0xa0,0x82,0x00,0x06,
+0x86,0x45,0x00,0x06,0x00,0xfe,0x10,0x21,0x24,0x03,0x00,0x13,0x10,0xa3,0x01,0x15,
+0xac,0x48,0x00,0x18,0x3c,0x03,0xb0,0x03,0x34,0x63,0x01,0x00,0xa6,0x40,0x00,0x02,
+0x3c,0x02,0xb0,0x03,0x90,0x64,0x00,0x00,0x34,0x42,0x01,0x08,0x8c,0x45,0x00,0x00,
+0x00,0x10,0x1b,0xc2,0x27,0x82,0x8f,0xf0,0x00,0x04,0x20,0x82,0x00,0xe2,0x10,0x21,
+0x30,0x63,0x00,0x01,0xac,0x45,0x00,0x08,0x10,0x60,0x00,0xec,0x30,0x97,0x00,0x01,
+0x00,0x10,0x16,0x82,0x30,0x46,0x00,0x01,0x00,0x10,0x12,0x02,0x00,0x10,0x19,0xc2,
+0x00,0x10,0x26,0x02,0x00,0x10,0x2e,0x42,0x30,0x47,0x00,0x7f,0x24,0x02,0x00,0x01,
+0x30,0x75,0x00,0x01,0x30,0x84,0x00,0x01,0x10,0xc2,0x00,0xd9,0x30,0xa3,0x00,0x01,
+0x0c,0x00,0x19,0x00,0x00,0x60,0x28,0x21,0x02,0x71,0x18,0x21,0x00,0x03,0x18,0x80,
+0x2c,0x46,0x00,0x54,0x27,0x85,0x90,0x00,0x27,0x84,0x8f,0xf8,0x00,0x06,0x10,0x0a,
+0x00,0x65,0x28,0x21,0x26,0xa6,0x00,0x02,0x00,0x64,0x18,0x21,0xa0,0xa2,0x00,0x02,
+0xa0,0x66,0x00,0x06,0xa0,0x62,0x00,0x07,0xa0,0xa2,0x00,0x01,0x02,0x71,0x20,0x21,
+0x00,0x04,0x20,0x80,0x00,0x9e,0x60,0x21,0x8d,0x85,0x00,0x18,0x00,0x10,0x15,0xc2,
+0x30,0x42,0x00,0x01,0x8c,0xa3,0x00,0x0c,0xa6,0x42,0x00,0x00,0x27,0x82,0x90,0x10,
+0x00,0x82,0x50,0x21,0xa6,0x56,0x00,0x04,0x8d,0x45,0x00,0x00,0x00,0x03,0x19,0x42,
+0x3c,0x02,0xff,0xef,0x34,0x42,0xff,0xff,0x30,0x63,0x00,0x01,0x00,0xa2,0x48,0x24,
+0x00,0x03,0x1d,0x00,0x01,0x23,0x48,0x25,0x00,0x09,0x15,0x02,0x26,0xc5,0x00,0x10,
+0x00,0x14,0x19,0x82,0x00,0x14,0x25,0x82,0x00,0x10,0x34,0x02,0x00,0x10,0x3c,0x42,
+0x00,0x10,0x44,0x82,0x30,0x42,0x00,0x01,0x30,0xb5,0xff,0xff,0x30,0xce,0x00,0x01,
+0x30,0xe5,0x00,0x01,0x30,0x6d,0x00,0x01,0x30,0x8b,0x00,0x03,0x32,0x94,0x00,0x07,
+0x31,0x06,0x00,0x01,0xad,0x49,0x00,0x00,0x10,0x40,0x00,0x0b,0x32,0x07,0x00,0x7f,
+0x8d,0x84,0x00,0x18,0x3c,0x03,0xff,0xf0,0x34,0x63,0xff,0xff,0x8c,0x82,0x00,0x0c,
+0x01,0x23,0x18,0x24,0x00,0x02,0x13,0x82,0x30,0x42,0x00,0x0f,0x00,0x02,0x14,0x00,
+0x00,0x62,0x18,0x25,0xad,0x43,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xc2,0x00,0x90,
+0x00,0x00,0x00,0x00,0x15,0xa0,0x00,0x03,0x00,0x00,0x00,0x00,0x15,0x60,0x00,0x81,
+0x24,0x02,0x00,0x01,0x96,0x42,0x00,0x04,0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x04,
+0xa6,0x42,0x00,0x04,0x0c,0x00,0x19,0x00,0x01,0xc0,0x20,0x21,0x02,0x71,0x18,0x21,
+0x00,0x03,0x38,0x80,0x2c,0x45,0x00,0x54,0x27,0x84,0x90,0x00,0x00,0xe4,0x20,0x21,
+0x00,0x05,0x10,0x0a,0xa0,0x82,0x00,0x00,0xa0,0x80,0x00,0x04,0xa0,0x80,0x00,0x05,
+0x96,0x45,0x00,0x04,0x27,0x82,0x8f,0xf0,0x00,0xe2,0x10,0x21,0xa4,0x45,0x00,0x06,
+0x00,0xfe,0x18,0x21,0x92,0x45,0x00,0x01,0x8c,0x66,0x00,0x18,0x27,0x82,0x90,0x10,
+0x00,0xe2,0x10,0x21,0xa0,0x40,0x00,0x00,0xa0,0x85,0x00,0x07,0x94,0xc3,0x00,0x10,
+0x24,0x02,0x00,0x04,0x30,0x63,0x00,0x0f,0x10,0x62,0x00,0x5e,0x24,0xc6,0x00,0x10,
+0x94,0xc3,0x00,0x16,0x27,0x85,0x90,0x08,0x00,0xe5,0x10,0x21,0xa4,0x43,0x00,0x02,
+0x94,0xc2,0x00,0x04,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,0x14,0x40,0x00,0x4c,
+0x02,0x71,0x20,0x21,0x94,0xc2,0x00,0x00,0x24,0x03,0x00,0xa4,0x30,0x42,0x00,0xff,
+0x10,0x43,0x00,0x47,0x00,0x00,0x00,0x00,0x94,0xc2,0x00,0x00,0x24,0x03,0x00,0x88,
+0x30,0x42,0x00,0x88,0x10,0x43,0x00,0x3c,0x02,0x71,0x18,0x21,0x27,0x84,0x90,0x10,
+0x00,0x03,0x18,0x80,0x00,0x64,0x18,0x21,0x8c,0x62,0x00,0x00,0x3c,0x04,0x00,0x80,
+0x00,0x44,0x10,0x25,0xac,0x62,0x00,0x00,0x02,0x71,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x45,0x10,0x21,0xa0,0x54,0x00,0x00,0x92,0x43,0x02,0xbf,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x00,0xc3,0xa0,0x43,0x00,0x00,0x8e,0x4b,0x02,0xbc,0x00,0x00,0x00,0x00,
+0x11,0x60,0x00,0x1c,0x32,0xa2,0x00,0xff,0x00,0x15,0x1a,0x02,0x30,0x64,0xff,0xff,
+0x38,0x42,0x00,0x00,0x24,0x65,0x00,0x01,0x00,0x82,0x28,0x0a,0x02,0x20,0x30,0x21,
+0x10,0xa0,0x00,0x12,0x00,0x00,0x38,0x21,0x02,0x71,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x8f,0xf0,0x00,0x43,0x20,0x21,0x24,0xa9,0xff,0xff,0x3c,0x0a,0xb0,0x08,
+0x24,0x0c,0xff,0xff,0x00,0x06,0x10,0xc0,0x00,0x4a,0x10,0x21,0x8c,0x43,0x00,0x00,
+0x24,0xe8,0x00,0x01,0x10,0xe9,0x00,0x0f,0x30,0x63,0x00,0xff,0x31,0x07,0xff,0xff,
+0x00,0xe5,0x10,0x2b,0x14,0x40,0xff,0xf7,0x00,0x60,0x30,0x21,0x25,0x62,0xff,0xff,
+0xae,0x42,0x02,0xbc,0x7b,0xbe,0x01,0xbc,0x7b,0xb6,0x01,0x7c,0x7b,0xb4,0x01,0x3c,
+0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,0x24,0x02,0x00,0x01,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x38,0xa4,0x86,0x00,0x04,0xa4,0x8c,0x00,0x02,0xae,0x51,0x02,0xb8,
+0x08,0x00,0x1a,0x2f,0xa6,0x43,0x00,0x0a,0x94,0xc2,0x00,0x18,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0x60,0x10,0x40,0xff,0xc1,0x02,0x71,0x18,0x21,0x02,0x71,0x20,0x21,
+0x27,0x82,0x90,0x10,0x00,0x04,0x20,0x80,0x00,0x82,0x20,0x21,0x8c,0x83,0x00,0x00,
+0x3c,0x02,0xff,0x7f,0x34,0x42,0xff,0xff,0x00,0x62,0x18,0x24,0x08,0x00,0x1a,0x0e,
+0xac,0x83,0x00,0x00,0x27,0x85,0x90,0x08,0x00,0xe5,0x10,0x21,0x08,0x00,0x19,0xf8,
+0xa4,0x40,0x00,0x02,0x11,0x62,0x00,0x07,0x00,0x00,0x00,0x00,0x2d,0x62,0x00,0x02,
+0x14,0x40,0xff,0x80,0x00,0x00,0x00,0x00,0x96,0x42,0x00,0x04,0x08,0x00,0x19,0xd8,
+0x24,0x42,0x00,0x0c,0x96,0x42,0x00,0x04,0x08,0x00,0x19,0xd8,0x24,0x42,0x00,0x08,
+0x16,0xe6,0xff,0x70,0x3c,0x02,0xff,0xfb,0x8d,0x83,0x00,0x18,0x34,0x42,0xff,0xff,
+0x02,0x02,0x10,0x24,0xac,0x62,0x00,0x08,0x08,0x00,0x19,0xd1,0x00,0x00,0x30,0x21,
+0x16,0xe6,0xff,0x27,0x3c,0x02,0xfb,0xff,0x34,0x42,0xff,0xff,0x02,0x02,0x10,0x24,
+0xad,0x02,0x00,0x08,0x08,0x00,0x19,0x90,0x00,0x00,0x30,0x21,0x93,0x88,0xbb,0x04,
+0x00,0x10,0x1e,0x42,0x00,0x10,0x26,0x82,0x27,0x82,0x8f,0xf8,0x2d,0x05,0x00,0x0c,
+0x00,0xe2,0x48,0x21,0x30,0x63,0x00,0x01,0x30,0x86,0x00,0x01,0x14,0xa0,0x00,0x06,
+0x01,0x00,0x38,0x21,0x00,0x03,0x10,0x40,0x00,0x46,0x10,0x21,0x00,0x02,0x11,0x00,
+0x01,0x02,0x10,0x21,0x24,0x47,0x00,0x04,0x02,0x71,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x84,0x90,0x00,0x27,0x83,0x8f,0xf8,0x00,0x44,0x20,0x21,0x00,0x43,0x10,0x21,
+0xa1,0x27,0x00,0x07,0xa0,0x40,0x00,0x06,0xa0,0x80,0x00,0x02,0x08,0x00,0x19,0x9f,
+0xa0,0x80,0x00,0x01,0x24,0x02,0x00,0x01,0xa6,0x42,0x00,0x02,0x0c,0x00,0x01,0xc4,
+0x01,0x00,0x20,0x21,0x08,0x00,0x1a,0x35,0x00,0x00,0x00,0x00,0x27,0x9e,0x8f,0xf4,
+0x08,0x00,0x19,0x52,0x00,0x11,0x3a,0x00,0x94,0x91,0x00,0x0a,0x08,0x00,0x19,0x39,
+0x00,0x00,0x00,0x00,0x30,0xa9,0xff,0xff,0x00,0x09,0x18,0xc0,0x00,0x69,0x18,0x21,
+0x3c,0x06,0xb0,0x03,0x3c,0x02,0x80,0x00,0x24,0x42,0x6a,0x54,0x00,0x03,0x18,0x80,
+0x34,0xc6,0x00,0x20,0x27,0x85,0x90,0x00,0xac,0xc2,0x00,0x00,0x00,0x65,0x18,0x21,
+0x80,0x62,0x00,0x07,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x32,0x24,0x88,0x00,0x06,
+0x90,0x82,0x00,0x16,0x00,0x80,0x40,0x21,0x34,0x42,0x00,0x02,0x30,0x43,0x00,0x01,
+0x14,0x60,0x00,0x02,0xa0,0x82,0x00,0x16,0xa0,0x80,0x00,0x17,0x95,0x03,0x00,0x02,
+0x00,0x00,0x00,0x00,0x10,0x69,0x00,0x22,0x3c,0x02,0x34,0x34,0x91,0x02,0x00,0x04,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x06,0x00,0x03,0x20,0xc0,0x24,0x02,0x00,0x01,
+0xa1,0x02,0x00,0x04,0xa5,0x09,0x00,0x02,0x03,0xe0,0x00,0x08,0xa5,0x09,0x00,0x00,
+0x00,0x83,0x20,0x21,0x27,0x87,0x8f,0xf0,0x00,0x04,0x20,0x80,0x00,0x87,0x20,0x21,
+0x94,0x83,0x00,0x04,0x3c,0x02,0xb0,0x08,0x3c,0x06,0xb0,0x03,0x00,0x03,0x28,0xc0,
+0x00,0xa3,0x18,0x21,0x00,0x03,0x18,0x80,0x00,0xa2,0x28,0x21,0x3c,0x02,0x80,0x01,
+0x24,0x42,0x82,0xe4,0x00,0x67,0x18,0x21,0x34,0xc6,0x00,0x20,0xac,0xc2,0x00,0x00,
+0xa4,0x69,0x00,0x00,0xa4,0x89,0x00,0x02,0xac,0xa9,0x00,0x00,0x91,0x02,0x00,0x04,
+0xa5,0x09,0x00,0x02,0x24,0x42,0x00,0x01,0x03,0xe0,0x00,0x08,0xa1,0x02,0x00,0x04,
+0x3c,0x03,0xb0,0x03,0x34,0x63,0x00,0xb0,0x34,0x42,0x34,0x34,0x03,0xe0,0x00,0x08,
+0xac,0x62,0x00,0x00,0x90,0x82,0x00,0x16,0x00,0x00,0x00,0x00,0x34,0x42,0x00,0x01,
+0x30,0x43,0x00,0x02,0x14,0x60,0xff,0xd1,0xa0,0x82,0x00,0x16,0x24,0x02,0x00,0x01,
+0x08,0x00,0x1a,0xab,0xa0,0x82,0x00,0x17,0x27,0xbd,0xff,0xe8,0xaf,0xbf,0x00,0x10,
+0x00,0x80,0x38,0x21,0x84,0x84,0x00,0x02,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x3c,0x0a,0xb0,0x06,0x34,0x63,0x00,0x20,0x24,0x42,0x6b,0x78,0x3c,0x0b,0xb0,0x08,
+0x27,0x89,0x8f,0xf0,0x34,0x0c,0xff,0xff,0x35,0x4a,0x80,0x20,0x10,0x80,0x00,0x30,
+0xac,0x62,0x00,0x00,0x97,0x82,0x8f,0xe0,0x94,0xe6,0x02,0xba,0x00,0x02,0x18,0xc0,
+0x00,0x6b,0x28,0x21,0xac,0xa6,0x00,0x00,0x8c,0xe4,0x02,0xb8,0x00,0x62,0x18,0x21,
+0x00,0x03,0x18,0x80,0x00,0x04,0x10,0xc0,0x00,0x44,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x49,0x10,0x21,0x94,0x48,0x00,0x04,0x00,0x69,0x18,0x21,0xa4,0x66,0x00,0x00,
+0x00,0x08,0x28,0xc0,0x00,0xab,0x10,0x21,0xac,0x4c,0x00,0x00,0x8c,0xe4,0x02,0xb8,
+0x27,0x82,0x8f,0xf4,0x00,0xa8,0x28,0x21,0x00,0x04,0x18,0xc0,0x00,0x64,0x18,0x21,
+0x00,0x03,0x18,0x80,0x00,0x62,0x10,0x21,0x8c,0x46,0x00,0x18,0x27,0x84,0x90,0x00,
+0x00,0x64,0x18,0x21,0x8c,0xc2,0x00,0x00,0x80,0x67,0x00,0x06,0x00,0x05,0x28,0x80,
+0x30,0x42,0xff,0xff,0x00,0x47,0x10,0x21,0x30,0x43,0x00,0xff,0x00,0x03,0x18,0x2b,
+0x00,0x02,0x12,0x02,0x00,0x43,0x10,0x21,0x3c,0x04,0x00,0x04,0x00,0xa9,0x28,0x21,
+0x00,0x44,0x10,0x25,0xa4,0xac,0x00,0x00,0xad,0x42,0x00,0x00,0xa7,0x88,0x8f,0xe0,
+0x8f,0xbf,0x00,0x10,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,
+0x84,0xe3,0x00,0x06,0x27,0x82,0xb3,0xf0,0x94,0xe5,0x02,0xba,0x00,0x03,0x18,0x80,
+0x00,0x62,0x18,0x21,0x8c,0x64,0x00,0x00,0x0c,0x00,0x1a,0x95,0x00,0x00,0x00,0x00,
+0x08,0x00,0x1b,0x18,0x00,0x00,0x00,0x00,0x94,0x88,0x00,0x00,0x00,0x80,0x58,0x21,
+0x27,0x8a,0x8f,0xf0,0x00,0x08,0x18,0xc0,0x00,0x68,0x18,0x21,0x3c,0x04,0xb0,0x03,
+0x00,0x03,0x18,0x80,0x3c,0x02,0x80,0x00,0x00,0x6a,0x18,0x21,0x34,0x84,0x00,0x20,
+0x24,0x42,0x6c,0x98,0x30,0xa5,0xff,0xff,0xac,0x82,0x00,0x00,0x94,0x67,0x00,0x02,
+0x11,0x05,0x00,0x35,0x24,0x04,0x00,0x01,0x91,0x66,0x00,0x04,0x00,0x00,0x00,0x00,
+0x00,0x86,0x10,0x2a,0x10,0x40,0x00,0x10,0x00,0xc0,0x48,0x21,0x3c,0x0d,0xb0,0x03,
+0x01,0x40,0x60,0x21,0x35,0xad,0x00,0x20,0x10,0xe5,0x00,0x0d,0x24,0x84,0x00,0x01,
+0x00,0x07,0x10,0xc0,0x00,0x47,0x10,0x21,0x00,0x02,0x10,0x80,0x01,0x20,0x30,0x21,
+0x00,0x4a,0x10,0x21,0x00,0x86,0x18,0x2a,0x00,0xe0,0x40,0x21,0x94,0x47,0x00,0x02,
+0x14,0x60,0xff,0xf5,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x10,0x21,
+0x00,0x08,0x20,0xc0,0x00,0x88,0x20,0x21,0x24,0xc2,0xff,0xff,0x00,0x04,0x20,0x80,
+0xa1,0x62,0x00,0x04,0x00,0x8c,0x20,0x21,0x94,0x83,0x00,0x04,0x00,0x07,0x10,0xc0,
+0x00,0x47,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x4c,0x10,0x21,0x00,0x03,0x28,0xc0,
+0x94,0x46,0x00,0x02,0x00,0xa3,0x18,0x21,0x00,0x03,0x18,0x80,0x00,0x6c,0x18,0x21,
+0xa4,0x66,0x00,0x00,0xa4,0x86,0x00,0x02,0x95,0x64,0x00,0x02,0x3c,0x03,0xb0,0x08,
+0x3c,0x02,0x80,0x01,0x00,0xa3,0x28,0x21,0x24,0x42,0x82,0xe4,0xad,0xa2,0x00,0x00,
+0x10,0x87,0x00,0x03,0xac,0xa6,0x00,0x00,0x03,0xe0,0x00,0x08,0x24,0x02,0x00,0x01,
+0x08,0x00,0x1b,0x66,0xa5,0x68,0x00,0x02,0x91,0x62,0x00,0x04,0xa5,0x67,0x00,0x00,
+0x24,0x42,0xff,0xff,0x30,0x43,0x00,0xff,0x14,0x60,0x00,0x03,0xa1,0x62,0x00,0x04,
+0x24,0x02,0xff,0xff,0xa5,0x62,0x00,0x02,0x91,0x65,0x00,0x04,0x00,0x00,0x00,0x00,
+0x10,0xa0,0xff,0xf1,0x00,0x00,0x00,0x00,0x95,0x66,0x00,0x00,0x34,0x02,0xff,0xff,
+0x14,0xc2,0xff,0xed,0x3c,0x03,0xb0,0x03,0x95,0x64,0x00,0x02,0x3c,0x02,0xee,0xee,
+0x00,0xa2,0x10,0x25,0x34,0x63,0x00,0xbc,0xac,0x62,0x00,0x00,0x10,0x86,0xff,0xe6,
+0xa1,0x60,0x00,0x04,0x24,0x02,0xff,0xff,0x08,0x00,0x1b,0x66,0xa5,0x62,0x00,0x02,
+0x00,0x05,0x40,0xc0,0x01,0x05,0x30,0x21,0x27,0xbd,0xff,0xd8,0x00,0x06,0x30,0x80,
+0x27,0x82,0x8f,0xf4,0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xbf,0x00,0x20,
+0xaf,0xb3,0x00,0x1c,0xaf,0xb0,0x00,0x10,0x00,0xc2,0x10,0x21,0x8c,0x47,0x00,0x18,
+0x00,0xa0,0x90,0x21,0x3c,0x02,0x80,0x00,0x3c,0x05,0xb0,0x03,0x34,0xa5,0x00,0x20,
+0x24,0x42,0x6e,0x10,0xac,0xa2,0x00,0x00,0x27,0x83,0x90,0x00,0x00,0xc3,0x30,0x21,
+0x8c,0xe2,0x00,0x00,0x80,0xc5,0x00,0x06,0x00,0x80,0x88,0x21,0x30,0x42,0xff,0xff,
+0x00,0x45,0x10,0x21,0x30,0x43,0x00,0xff,0x10,0x60,0x00,0x02,0x00,0x02,0x12,0x02,
+0x24,0x42,0x00,0x01,0x30,0x53,0x00,0xff,0x01,0x12,0x10,0x21,0x00,0x02,0x10,0x80,
+0x27,0x83,0x90,0x00,0x00,0x43,0x10,0x21,0x80,0x44,0x00,0x07,0x00,0x00,0x00,0x00,
+0x10,0x80,0x00,0x4b,0x26,0x24,0x00,0x06,0x32,0x50,0xff,0xff,0x02,0x20,0x20,0x21,
+0x0c,0x00,0x1b,0x26,0x02,0x00,0x28,0x21,0x92,0x22,0x00,0x10,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x2e,0x3c,0x03,0xb0,0x08,0x3c,0x09,0x80,0x01,0x27,0x88,0x8f,0xf0,
+0xa6,0x32,0x00,0x0c,0x00,0x10,0x20,0xc0,0x00,0x90,0x20,0x21,0x00,0x04,0x20,0x80,
+0x00,0x88,0x20,0x21,0x94,0x82,0x00,0x04,0x3c,0x03,0xb0,0x08,0x3c,0x07,0xb0,0x03,
+0x00,0x02,0x28,0xc0,0x00,0xa2,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x48,0x10,0x21,
+0x00,0xa3,0x28,0x21,0x25,0x26,0x82,0xe4,0x34,0x03,0xff,0xff,0x34,0xe7,0x00,0x20,
+0xac,0xe6,0x00,0x00,0xa4,0x83,0x00,0x02,0xa4,0x43,0x00,0x00,0xac,0xa3,0x00,0x00,
+0x92,0x22,0x00,0x10,0x92,0x23,0x00,0x0a,0xa6,0x32,0x00,0x0e,0x02,0x62,0x10,0x21,
+0x14,0x60,0x00,0x05,0xa2,0x22,0x00,0x10,0x92,0x22,0x00,0x16,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0xfe,0xa2,0x22,0x00,0x16,0x92,0x22,0x00,0x04,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x05,0x00,0x00,0x00,0x00,0x92,0x22,0x00,0x16,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0xfd,0xa2,0x22,0x00,0x16,0x8f,0xbf,0x00,0x20,0x7b,0xb2,0x00,0xfc,
+0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,0x96,0x22,0x00,0x0e,
+0x27,0x88,0x8f,0xf0,0x00,0x02,0x20,0xc0,0x00,0x82,0x20,0x21,0x00,0x04,0x20,0x80,
+0x00,0x88,0x20,0x21,0x94,0x82,0x00,0x04,0x3c,0x06,0xb0,0x03,0x3c,0x09,0x80,0x01,
+0x00,0x02,0x28,0xc0,0x00,0xa2,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0xa3,0x28,0x21,
+0x00,0x48,0x10,0x21,0x34,0xc6,0x00,0x20,0x25,0x23,0x82,0xe4,0xac,0xc3,0x00,0x00,
+0xa4,0x50,0x00,0x00,0xac,0xb0,0x00,0x00,0x08,0x00,0x1b,0xb5,0xa4,0x90,0x00,0x02,
+0x08,0x00,0x1b,0xac,0x32,0x50,0xff,0xff,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x24,0x42,0x6f,0xd8,0x34,0x63,0x00,0x20,0xac,0x62,0x00,0x00,0x90,0x82,0x00,0x04,
+0x97,0xaa,0x00,0x12,0x00,0x80,0x60,0x21,0x30,0xa8,0xff,0xff,0x00,0x4a,0x20,0x23,
+0x34,0x09,0xff,0xff,0x30,0xcf,0xff,0xff,0x30,0xee,0xff,0xff,0x11,0x09,0x00,0x73,
+0xa1,0x84,0x00,0x04,0x00,0x0e,0xc0,0xc0,0x00,0x08,0x10,0xc0,0x00,0x48,0x10,0x21,
+0x03,0x0e,0x20,0x21,0x27,0x8d,0x8f,0xf0,0x00,0x04,0x20,0x80,0x00,0x02,0x10,0x80,
+0x00,0x4d,0x10,0x21,0x00,0x8d,0x20,0x21,0x94,0x86,0x00,0x02,0x94,0x43,0x00,0x04,
+0x3c,0x19,0x80,0x01,0xa4,0x46,0x00,0x02,0x00,0x03,0x28,0xc0,0x00,0xa3,0x18,0x21,
+0x94,0x87,0x00,0x02,0x3c,0x02,0xb0,0x08,0x00,0x03,0x18,0x80,0x00,0xa2,0x28,0x21,
+0x00,0x6d,0x18,0x21,0x27,0x22,0x82,0xe4,0x3c,0x01,0xb0,0x03,0xac,0x22,0x00,0x20,
+0xa4,0x66,0x00,0x00,0x10,0xe9,0x00,0x57,0xac,0xa6,0x00,0x00,0x01,0xe0,0x30,0x21,
+0x11,0x40,0x00,0x1d,0x00,0x00,0x48,0x21,0x01,0x40,0x38,0x21,0x27,0x8b,0x8f,0xf4,
+0x27,0x8a,0x90,0x00,0x00,0x06,0x40,0xc0,0x01,0x06,0x18,0x21,0x00,0x03,0x18,0x80,
+0x00,0x6b,0x10,0x21,0x8c,0x44,0x00,0x18,0x00,0x6a,0x18,0x21,0x80,0x65,0x00,0x06,
+0x8c,0x82,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0xff,0xff,0x00,0x45,0x10,0x21,
+0x30,0x44,0x00,0xff,0x00,0x02,0x12,0x02,0x01,0x22,0x18,0x21,0x24,0x62,0x00,0x01,
+0x14,0x80,0x00,0x02,0x30,0x49,0x00,0xff,0x30,0x69,0x00,0xff,0x01,0x06,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x4d,0x10,0x21,0x24,0xe7,0xff,0xff,0x94,0x46,0x00,0x02,
+0x14,0xe0,0xff,0xe9,0x00,0x06,0x40,0xc0,0x91,0x82,0x00,0x10,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x20,0x3c,0x06,0xb0,0x03,0xa5,0x8f,0x00,0x0c,0x03,0x0e,0x20,0x21,
+0x00,0x04,0x20,0x80,0x00,0x8d,0x20,0x21,0x94,0x82,0x00,0x04,0x3c,0x03,0xb0,0x08,
+0x3c,0x07,0xb0,0x03,0x00,0x02,0x28,0xc0,0x00,0xa2,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x4d,0x10,0x21,0x00,0xa3,0x28,0x21,0x27,0x26,0x82,0xe4,0x34,0x03,0xff,0xff,
+0x34,0xe7,0x00,0x20,0xac,0xe6,0x00,0x00,0xa4,0x83,0x00,0x02,0xa4,0x43,0x00,0x00,
+0xac,0xa3,0x00,0x00,0x91,0x82,0x00,0x10,0x91,0x83,0x00,0x04,0xa5,0x8e,0x00,0x0e,
+0x01,0x22,0x10,0x21,0x14,0x60,0x00,0x05,0xa1,0x82,0x00,0x10,0x91,0x82,0x00,0x16,
+0x00,0x00,0x00,0x00,0x30,0x42,0x00,0xfd,0xa1,0x82,0x00,0x16,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x95,0x82,0x00,0x0e,0x3c,0x03,0xb0,0x08,0x00,0x02,0x20,0xc0,
+0x00,0x82,0x20,0x21,0x00,0x04,0x20,0x80,0x00,0x8d,0x20,0x21,0x94,0x82,0x00,0x04,
+0x34,0xc6,0x00,0x20,0x27,0x27,0x82,0xe4,0x00,0x02,0x28,0xc0,0x00,0xa2,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0xa3,0x28,0x21,0x00,0x4d,0x10,0x21,0xac,0xc7,0x00,0x00,
+0xa4,0x8f,0x00,0x02,0xa4,0x4f,0x00,0x00,0xac,0xaf,0x00,0x00,0x08,0x00,0x1c,0x44,
+0x03,0x0e,0x20,0x21,0x08,0x00,0x1c,0x1f,0xa5,0x88,0x00,0x02,0x00,0x0e,0xc0,0xc0,
+0x03,0x0e,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x8d,0x8f,0xf0,0x00,0x4d,0x10,0x21,
+0x94,0x43,0x00,0x02,0x30,0x84,0x00,0xff,0x14,0x80,0x00,0x05,0xa5,0x83,0x00,0x00,
+0x24,0x02,0xff,0xff,0x3c,0x19,0x80,0x01,0x08,0x00,0x1c,0x1f,0xa5,0x82,0x00,0x02,
+0x08,0x00,0x1c,0x1f,0x3c,0x19,0x80,0x01,0x3c,0x08,0xb0,0x03,0x3c,0x02,0x80,0x00,
+0x27,0xbd,0xff,0x78,0x35,0x08,0x00,0x20,0x24,0x42,0x72,0x18,0xaf,0xb2,0x00,0x68,
+0xaf,0xb1,0x00,0x64,0xaf,0xb0,0x00,0x60,0xad,0x02,0x00,0x00,0xaf,0xbf,0x00,0x84,
+0xaf,0xbe,0x00,0x80,0xaf,0xb7,0x00,0x7c,0xaf,0xb6,0x00,0x78,0xaf,0xb5,0x00,0x74,
+0xaf,0xb4,0x00,0x70,0xaf,0xb3,0x00,0x6c,0xaf,0xa4,0x00,0x88,0x90,0x83,0x00,0x0a,
+0x27,0x82,0xb3,0xf0,0xaf,0xa6,0x00,0x90,0x00,0x03,0x18,0x80,0x00,0x62,0x18,0x21,
+0x8c,0x63,0x00,0x00,0xaf,0xa7,0x00,0x94,0x27,0x86,0x8f,0xf4,0xaf,0xa3,0x00,0x1c,
+0x94,0x63,0x00,0x14,0x30,0xb1,0xff,0xff,0x24,0x08,0x00,0x01,0x00,0x03,0x20,0xc0,
+0xaf,0xa3,0x00,0x18,0x00,0x83,0x18,0x21,0xaf,0xa4,0x00,0x54,0x00,0x03,0x18,0x80,
+0x27,0x84,0x90,0x00,0x00,0x64,0x20,0x21,0x80,0x82,0x00,0x06,0x00,0x66,0x18,0x21,
+0x8c,0x66,0x00,0x18,0x24,0x42,0x00,0x02,0x00,0x02,0x1f,0xc2,0x8c,0xc4,0x00,0x08,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x43,0x00,0x02,0x10,0x40,0x00,0x04,0x2f,0xc2,
+0x00,0x04,0x1c,0x82,0x00,0xc2,0x38,0x21,0x00,0x04,0x24,0x42,0x8f,0xa2,0x00,0x1c,
+0x30,0x63,0x00,0x01,0x30,0x84,0x00,0x01,0xaf,0xa5,0x00,0x3c,0xaf,0xa3,0x00,0x34,
+0xaf,0xa4,0x00,0x38,0xaf,0xa0,0x00,0x40,0xaf,0xa0,0x00,0x44,0xaf,0xa0,0x00,0x50,
+0xaf,0xa8,0x00,0x20,0x80,0x42,0x00,0x12,0x8f,0xb2,0x00,0x18,0xaf,0xa2,0x00,0x28,
+0x8c,0xd0,0x00,0x0c,0x14,0xa0,0x01,0xe4,0x00,0x60,0x30,0x21,0x00,0x10,0x10,0x82,
+0x30,0x45,0x00,0x07,0x10,0xa0,0x00,0x11,0xaf,0xa0,0x00,0x30,0x8f,0xa4,0x00,0x98,
+0x27,0x82,0x80,0x1c,0x00,0x04,0x18,0x40,0x00,0x62,0x18,0x21,0x24,0xa2,0x00,0x06,
+0x8f,0xa5,0x00,0x20,0x94,0x64,0x00,0x00,0x00,0x45,0x10,0x04,0x00,0x44,0x00,0x1a,
+0x14,0x80,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x0d,0x00,0x00,0x10,0x12,
+0x24,0x42,0x00,0x20,0x30,0x42,0xff,0xfc,0xaf,0xa2,0x00,0x30,0x8f,0xa3,0x00,0x18,
+0x8f,0xa4,0x00,0x28,0x34,0x02,0xff,0xff,0xaf,0xa0,0x00,0x2c,0xaf,0xa2,0x00,0x48,
+0xaf,0xa3,0x00,0x4c,0x00,0x60,0xf0,0x21,0x00,0x00,0xb8,0x21,0x18,0x80,0x00,0x48,
+0xaf,0xa0,0x00,0x24,0x00,0x11,0x89,0x02,0xaf,0xb1,0x00,0x58,0x00,0x80,0xa8,0x21,
+0x00,0x12,0x10,0xc0,0x00,0x52,0x18,0x21,0x00,0x03,0x80,0x80,0x27,0x85,0x8f,0xf0,
+0x02,0x40,0x20,0x21,0x00,0x40,0xa0,0x21,0x02,0x05,0x10,0x21,0x94,0x56,0x00,0x02,
+0x0c,0x00,0x12,0x87,0x00,0x00,0x28,0x21,0x90,0x42,0x00,0x00,0x24,0x03,0x00,0x08,
+0x30,0x42,0x00,0x0c,0x10,0x43,0x01,0x9e,0x24,0x04,0x00,0x01,0x24,0x02,0x00,0x01,
+0x10,0x82,0x01,0x7c,0x3c,0x02,0xb0,0x03,0x8f,0xa6,0x00,0x88,0x34,0x42,0x01,0x04,
+0x84,0xc5,0x00,0x0c,0x02,0x92,0x18,0x21,0x94,0x46,0x00,0x00,0x00,0x05,0x20,0xc0,
+0x00,0x85,0x20,0x21,0x00,0x03,0x18,0x80,0x27,0x82,0x90,0x00,0x27,0x85,0x8f,0xf8,
+0x00,0x65,0x28,0x21,0x00,0x62,0x18,0x21,0x80,0x71,0x00,0x05,0x80,0x73,0x00,0x04,
+0x8f,0xa3,0x00,0x88,0x30,0xd0,0xff,0xff,0x00,0x10,0x3a,0x03,0x32,0x08,0x00,0xff,
+0x27,0x82,0x90,0x10,0x00,0x04,0x20,0x80,0x80,0xa6,0x00,0x06,0x00,0x82,0x20,0x21,
+0xa4,0x67,0x00,0x44,0xa4,0x68,0x00,0x46,0x8c,0x84,0x00,0x00,0x38,0xc6,0x00,0x00,
+0x01,0x00,0x80,0x21,0x00,0x04,0x15,0x02,0x30,0x42,0x00,0x01,0x10,0x40,0x00,0x03,
+0x00,0xe6,0x80,0x0a,0x00,0x04,0x14,0x02,0x30,0x50,0x00,0x0f,0x12,0x20,0x01,0x50,
+0x02,0x40,0x20,0x21,0x02,0x71,0x10,0x21,0x00,0x50,0x10,0x2a,0x14,0x40,0x00,0xed,
+0x02,0x92,0x10,0x21,0x93,0x82,0x8b,0x61,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,
+0x14,0x40,0x00,0xe0,0x02,0x92,0x28,0x21,0x26,0xe2,0x00,0x01,0x30,0x57,0xff,0xff,
+0x02,0x40,0xf0,0x21,0x26,0xb5,0xff,0xff,0x16,0xa0,0xff,0xbd,0x02,0xc0,0x90,0x21,
+0x16,0xe0,0x00,0xd0,0x00,0x00,0x00,0x00,0x8f,0xa3,0x00,0x98,0x00,0x00,0x00,0x00,
+0x2c,0x62,0x00,0x10,0x10,0x40,0x00,0x2e,0x00,0x00,0x00,0x00,0x8f,0xa4,0x00,0x24,
+0x00,0x00,0x00,0x00,0x18,0x80,0x00,0x2a,0x24,0x03,0x00,0x01,0x8f,0xa5,0x00,0x1c,
+0x27,0x84,0x8f,0xf4,0x94,0xb2,0x00,0x14,0xa0,0xa3,0x00,0x12,0x8f,0xa6,0x00,0x3c,
+0x00,0x12,0x10,0xc0,0x00,0x52,0x10,0x21,0x00,0x02,0x80,0x80,0x27,0x82,0x90,0x00,
+0x02,0x02,0x10,0x21,0x80,0x43,0x00,0x06,0x02,0x04,0x20,0x21,0x8c,0x85,0x00,0x18,
+0x24,0x63,0x00,0x02,0x00,0x03,0x17,0xc2,0x00,0x62,0x18,0x21,0x00,0x03,0x18,0x43,
+0x00,0x03,0x18,0x40,0x14,0xc0,0x00,0x0e,0x00,0xa3,0x38,0x21,0x27,0x82,0x8f,0xf0,
+0x02,0x02,0x10,0x21,0x94,0x43,0x00,0x06,0x8f,0xa8,0x00,0x1c,0x24,0x02,0x00,0x01,
+0xa5,0x03,0x00,0x1a,0x7b,0xbe,0x04,0x3c,0x7b,0xb6,0x03,0xfc,0x7b,0xb4,0x03,0xbc,
+0x7b,0xb2,0x03,0x7c,0x7b,0xb0,0x03,0x3c,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x88,
+0x8f,0xa4,0x00,0x98,0x8f,0xa5,0x00,0x38,0x8f,0xa6,0x00,0x34,0xaf,0xa0,0x00,0x10,
+0x0c,0x00,0x09,0x06,0xaf,0xa0,0x00,0x14,0x08,0x00,0x1d,0x4b,0x00,0x00,0x00,0x00,
+0x8f,0xa3,0x00,0x44,0x93,0x82,0x81,0x59,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x61,
+0x30,0x69,0x00,0x03,0x8f,0xa4,0x00,0x24,0x8f,0xa5,0x00,0x28,0x00,0x00,0x00,0x00,
+0x00,0x85,0x10,0x2a,0x10,0x40,0x00,0x8f,0x00,0x00,0x00,0x00,0x8f,0xa6,0x00,0x1c,
+0x00,0x00,0x00,0x00,0x90,0xc4,0x00,0x04,0x00,0x00,0x00,0x00,0x30,0x83,0x00,0xff,
+0x00,0xa3,0x10,0x2a,0x10,0x40,0x00,0x87,0x00,0x00,0x00,0x00,0x8f,0xa8,0x00,0x24,
+0x00,0x00,0x00,0x00,0x11,0x00,0x00,0x83,0x00,0x65,0x10,0x23,0x00,0xa8,0x18,0x23,
+0x00,0x62,0x10,0x2a,0x14,0x40,0x00,0x7d,0x30,0x63,0x00,0xff,0x00,0x85,0x10,0x23,
+0x30,0x42,0x00,0xff,0xaf,0xa2,0x00,0x50,0x8f,0xa2,0x00,0x50,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x73,0x00,0x00,0xa8,0x21,0x27,0x8c,0x8f,0xf0,0x3c,0x0b,0x80,0xff,
+0x24,0x10,0x00,0x04,0x27,0x91,0x8f,0xf4,0x35,0x6b,0xff,0xff,0x3c,0x0d,0x7f,0x00,
+0x27,0x8e,0x90,0x00,0x01,0x80,0x78,0x21,0x00,0x12,0x30,0xc0,0x00,0xd2,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x4c,0x10,0x21,0x94,0x42,0x00,0x06,0x8f,0xa3,0x00,0x2c,
+0x8f,0xa4,0x00,0x30,0xaf,0xa2,0x00,0x44,0x8f,0xa5,0x00,0x44,0x30,0x49,0x00,0x03,
+0x02,0x09,0x10,0x23,0x30,0x42,0x00,0x03,0x00,0xa2,0x10,0x21,0x8f,0xa8,0x00,0x30,
+0x24,0x42,0x00,0x04,0x30,0x42,0xff,0xff,0x00,0x64,0x38,0x21,0x01,0x02,0x28,0x23,
+0x00,0x62,0x18,0x21,0x00,0x48,0x10,0x2b,0x10,0x40,0x00,0x52,0x00,0x00,0x20,0x21,
+0x30,0xe7,0xff,0xff,0x30,0xa4,0xff,0xff,0xaf,0xa7,0x00,0x2c,0x00,0xd2,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x51,0x18,0x21,0x8c,0x65,0x00,0x18,0x00,0x04,0x25,0x40,
+0x00,0x8d,0x20,0x24,0x8c,0xa8,0x00,0x04,0x00,0x4e,0x18,0x21,0x00,0x4f,0x50,0x21,
+0x01,0x0b,0x40,0x24,0x01,0x04,0x40,0x25,0xac,0xa8,0x00,0x04,0x8f,0xa4,0x00,0x98,
+0x8f,0xa2,0x00,0x50,0x26,0xb5,0x00,0x01,0xa0,0x64,0x00,0x00,0x8c,0xa4,0x00,0x08,
+0x00,0x00,0x00,0x00,0x04,0x81,0x00,0x0c,0x02,0xa2,0x30,0x2a,0x80,0x62,0x00,0x06,
+0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x02,0x00,0x02,0x1f,0xc2,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x43,0x00,0x02,0x10,0x40,0x00,0xa2,0x38,0x21,0x8f,0xa5,0x00,0x40,
+0x00,0x00,0x00,0x00,0xa4,0xe5,0x00,0x00,0x95,0x52,0x00,0x02,0x14,0xc0,0xff,0xc7,
+0x00,0x12,0x30,0xc0,0x8f,0xa4,0x00,0x24,0x8f,0xa5,0x00,0x50,0x8f,0xa6,0x00,0x1c,
+0x8f,0xa3,0x00,0x2c,0x00,0x85,0x80,0x21,0xa0,0xd0,0x00,0x12,0x00,0x09,0x10,0x23,
+0x30,0x42,0x00,0x03,0x8f,0xa8,0x00,0x88,0x00,0x62,0x10,0x23,0xa4,0xc2,0x00,0x1a,
+0x85,0x03,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x03,0x10,0xc0,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x80,0x27,0x83,0x8f,0xf4,0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x18,
+0x00,0x00,0x00,0x00,0x8c,0x83,0x00,0x04,0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x10,
+0x14,0x60,0xff,0x74,0x02,0x00,0x10,0x21,0x8f,0xa3,0x00,0x54,0x8f,0xa4,0x00,0x18,
+0x8f,0xa5,0x00,0x24,0x00,0x64,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x83,0x90,0x08,
+0x00,0x43,0x10,0x21,0x90,0x44,0x00,0x00,0x10,0xa0,0x00,0x03,0x00,0x00,0x30,0x21,
+0x08,0x00,0x1d,0x51,0x02,0x00,0x10,0x21,0x93,0x82,0x80,0x10,0x00,0x00,0x28,0x21,
+0x00,0x00,0x38,0x21,0x0c,0x00,0x21,0xf5,0xaf,0xa2,0x00,0x10,0x08,0x00,0x1d,0x51,
+0x02,0x00,0x10,0x21,0x30,0x63,0xff,0xff,0x08,0x00,0x1d,0xa3,0xaf,0xa3,0x00,0x2c,
+0x8f,0xa8,0x00,0x44,0x08,0x00,0x1d,0xc5,0x31,0x09,0x00,0x03,0x08,0x00,0x1d,0x7e,
+0xaf,0xa3,0x00,0x50,0x8f,0xa6,0x00,0x44,0xaf,0xa0,0x00,0x50,0x08,0x00,0x1d,0xc5,
+0x30,0xc9,0x00,0x03,0x8f,0xa5,0x00,0x48,0x8f,0xa6,0x00,0x4c,0x8f,0xa4,0x00,0x1c,
+0x03,0xc0,0x38,0x21,0x0c,0x00,0x1b,0xf6,0xaf,0xb7,0x00,0x10,0x08,0x00,0x1d,0x2e,
+0x00,0x00,0x00,0x00,0x00,0x05,0x28,0x80,0x27,0x82,0x8f,0xf0,0x00,0xa2,0x28,0x21,
+0x00,0x00,0x20,0x21,0x0c,0x00,0x01,0x4b,0x00,0x00,0x00,0x00,0x08,0x00,0x1d,0x27,
+0x26,0xe2,0x00,0x01,0x00,0x02,0x80,0x80,0x27,0x83,0x90,0x00,0x8f,0xa4,0x00,0x1c,
+0x02,0x03,0x18,0x21,0x26,0x31,0x00,0x01,0x02,0x40,0x28,0x21,0x0c,0x00,0x1f,0x08,
+0xa0,0x71,0x00,0x05,0x14,0x40,0xff,0x13,0x00,0x00,0x00,0x00,0x16,0xe0,0x00,0x4d,
+0x03,0xc0,0x38,0x21,0x8f,0xa4,0x00,0x24,0x8f,0xa5,0x00,0x20,0x24,0x02,0x00,0x01,
+0x24,0x84,0x00,0x01,0xaf,0xb2,0x00,0x48,0xaf,0xb6,0x00,0x4c,0x02,0xc0,0xf0,0x21,
+0x10,0xa2,0x00,0x41,0xaf,0xa4,0x00,0x24,0x27,0x82,0x8f,0xf0,0x02,0x02,0x10,0x21,
+0x94,0x42,0x00,0x06,0x8f,0xa4,0x00,0x30,0xaf,0xa0,0x00,0x20,0xaf,0xa2,0x00,0x44,
+0x30,0x49,0x00,0x03,0x8f,0xa8,0x00,0x44,0x00,0x09,0x10,0x23,0x30,0x42,0x00,0x03,
+0x01,0x02,0x10,0x21,0x24,0x42,0x00,0x04,0x30,0x42,0xff,0xff,0x00,0x44,0x18,0x2b,
+0x10,0x60,0x00,0x2b,0x00,0x00,0x00,0x00,0x8f,0xa5,0x00,0x2c,0x00,0x82,0x10,0x23,
+0x00,0xa4,0x18,0x21,0x30,0x63,0xff,0xff,0x30,0x44,0xff,0xff,0xaf,0xa3,0x00,0x2c,
+0x02,0x92,0x28,0x21,0x00,0x05,0x28,0x80,0x27,0x82,0x8f,0xf4,0x00,0xa2,0x10,0x21,
+0x8c,0x46,0x00,0x18,0x3c,0x03,0x80,0xff,0x3c,0x02,0x7f,0x00,0x8c,0xc8,0x00,0x04,
+0x00,0x04,0x25,0x40,0x34,0x63,0xff,0xff,0x00,0x82,0x20,0x24,0x01,0x03,0x40,0x24,
+0x01,0x04,0x40,0x25,0xac,0xc8,0x00,0x04,0x8f,0xa8,0x00,0x98,0x27,0x82,0x90,0x00,
+0x00,0xa2,0x10,0x21,0xa0,0x48,0x00,0x00,0x8c,0xc4,0x00,0x08,0x00,0x00,0x00,0x00,
+0x00,0x04,0x27,0xc2,0x10,0x80,0xfe,0xdb,0xaf,0xa4,0x00,0x3c,0x80,0x42,0x00,0x06,
+0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x02,0x00,0x02,0x1f,0xc2,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x43,0x00,0x02,0x10,0x40,0x00,0xc2,0x38,0x21,0x8f,0xa2,0x00,0x40,
+0x00,0x00,0x00,0x00,0xa4,0xe2,0x00,0x00,0x08,0x00,0x1d,0x2a,0x26,0xb5,0xff,0xff,
+0x8f,0xa6,0x00,0x2c,0x00,0x00,0x20,0x21,0x00,0xc2,0x10,0x21,0x30,0x42,0xff,0xff,
+0x08,0x00,0x1e,0x38,0xaf,0xa2,0x00,0x2c,0x8f,0xa6,0x00,0x1c,0x08,0x00,0x1e,0x22,
+0xa4,0xd2,0x00,0x14,0x8f,0xa5,0x00,0x48,0x8f,0xa6,0x00,0x4c,0x8f,0xa4,0x00,0x1c,
+0x0c,0x00,0x1b,0xf6,0xaf,0xb7,0x00,0x10,0x08,0x00,0x1e,0x19,0x00,0x00,0xb8,0x21,
+0x0c,0x00,0x12,0x87,0x00,0x00,0x28,0x21,0x00,0x40,0x18,0x21,0x94,0x42,0x00,0x00,
+0x00,0x00,0x00,0x00,0x34,0x42,0x08,0x00,0xa4,0x62,0x00,0x00,0x08,0x00,0x1d,0x1e,
+0x02,0x71,0x10,0x21,0x02,0x92,0x18,0x21,0x00,0x03,0x80,0x80,0x27,0x82,0x8f,0xf4,
+0x02,0x02,0x10,0x21,0x8c,0x44,0x00,0x18,0x00,0x00,0x00,0x00,0x8c,0x83,0x00,0x04,
+0x00,0x00,0x00,0x00,0x30,0x63,0x00,0x10,0x10,0x60,0x00,0x09,0x24,0x06,0x00,0x01,
+0x93,0x82,0x8b,0x61,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,0x10,0x40,0xfe,0xa2,
+0x3c,0x04,0x00,0x80,0x27,0x85,0x8f,0xf0,0x08,0x00,0x1e,0x09,0x02,0x05,0x28,0x21,
+0x27,0x83,0x90,0x08,0x27,0x82,0x90,0x00,0x02,0x03,0x18,0x21,0x02,0x02,0x10,0x21,
+0x90,0x64,0x00,0x00,0x90,0x45,0x00,0x05,0x93,0x83,0x80,0x10,0x00,0x00,0x38,0x21,
+0x0c,0x00,0x21,0xf5,0xaf,0xa3,0x00,0x10,0x08,0x00,0x1e,0x80,0x00,0x00,0x00,0x00,
+0x27,0x82,0x90,0x08,0x02,0x02,0x10,0x21,0x94,0x43,0x00,0x02,0x8f,0xa6,0x00,0x58,
+0x00,0x03,0x19,0x02,0x00,0x66,0x18,0x23,0x30,0x63,0x0f,0xff,0x28,0x62,0x00,0x20,
+0x10,0x40,0x00,0x06,0x28,0x62,0x00,0x40,0x8f,0xa8,0x00,0x90,0x00,0x00,0x00,0x00,
+0x00,0x68,0x10,0x06,0x08,0x00,0x1c,0xf7,0x30,0x44,0x00,0x01,0x10,0x40,0x00,0x04,
+0x00,0x00,0x00,0x00,0x8f,0xa4,0x00,0x94,0x08,0x00,0x1e,0xa1,0x00,0x64,0x10,0x06,
+0x08,0x00,0x1c,0xf7,0x00,0x00,0x20,0x21,0x8f,0xa4,0x00,0x98,0x8f,0xa5,0x00,0x38,
+0xaf,0xa0,0x00,0x10,0x0c,0x00,0x09,0x06,0xaf,0xa8,0x00,0x14,0x30,0x42,0xff,0xff,
+0x08,0x00,0x1c,0xc7,0xaf,0xa2,0x00,0x40,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x00,
+0x27,0xbd,0xff,0xe0,0x34,0x42,0x00,0x20,0x24,0x63,0x7a,0xc8,0xaf,0xb1,0x00,0x14,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x18,0xac,0x43,0x00,0x00,0x90,0x82,0x00,0x0a,
+0x00,0x80,0x80,0x21,0x14,0x40,0x00,0x45,0x00,0x00,0x88,0x21,0x92,0x02,0x00,0x04,
+0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x3c,0x00,0x00,0x00,0x00,0x12,0x20,0x00,0x18,
+0x00,0x00,0x00,0x00,0x92,0x02,0x00,0x16,0x92,0x05,0x00,0x0a,0x30,0x42,0x00,0xfc,
+0x10,0xa0,0x00,0x03,0xa2,0x02,0x00,0x16,0x34,0x42,0x00,0x01,0xa2,0x02,0x00,0x16,
+0x92,0x04,0x00,0x04,0x00,0x00,0x00,0x00,0x30,0x83,0x00,0xff,0x10,0x60,0x00,0x05,
+0x00,0x00,0x00,0x00,0x92,0x02,0x00,0x16,0x00,0x00,0x00,0x00,0x34,0x42,0x00,0x02,
+0xa2,0x02,0x00,0x16,0x10,0x60,0x00,0x0a,0x00,0x00,0x00,0x00,0x14,0xa0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x96,0x02,0x00,0x00,0xa2,0x00,0x00,0x17,0xa6,0x02,0x00,0x14,
+0x8f,0xbf,0x00,0x18,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,
+0x14,0x80,0x00,0x05,0x24,0x02,0x00,0x01,0x96,0x03,0x00,0x06,0xa2,0x02,0x00,0x17,
+0x08,0x00,0x1e,0xdc,0xa6,0x03,0x00,0x14,0x96,0x04,0x00,0x00,0x96,0x05,0x00,0x06,
+0x27,0x86,0x8f,0xf0,0x00,0x04,0x10,0xc0,0x00,0x05,0x18,0xc0,0x00,0x44,0x10,0x21,
+0x00,0x65,0x18,0x21,0x00,0x02,0x10,0x80,0x00,0x03,0x18,0x80,0x00,0x66,0x18,0x21,
+0x00,0x46,0x10,0x21,0x8c,0x65,0x00,0x08,0x8c,0x44,0x00,0x08,0x0c,0x00,0x12,0x78,
+0x00,0x00,0x00,0x00,0x30,0x43,0x00,0xff,0x10,0x60,0x00,0x04,0xa2,0x02,0x00,0x17,
+0x96,0x02,0x00,0x06,0x08,0x00,0x1e,0xdc,0xa6,0x02,0x00,0x14,0x96,0x02,0x00,0x00,
+0x08,0x00,0x1e,0xdc,0xa6,0x02,0x00,0x14,0x96,0x05,0x00,0x00,0x0c,0x00,0x1f,0x08,
+0x02,0x00,0x20,0x21,0x08,0x00,0x1e,0xc3,0x02,0x22,0x88,0x21,0x94,0x85,0x00,0x06,
+0x0c,0x00,0x1f,0x08,0x00,0x00,0x00,0x00,0x08,0x00,0x1e,0xbf,0x00,0x40,0x88,0x21,
+0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,0x24,0x42,0x7c,0x20,
+0x27,0xbd,0xff,0xf0,0xac,0x62,0x00,0x00,0x00,0x00,0x10,0x21,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x10,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x00,0x34,0x63,0x00,0x20,
+0x24,0x42,0x7c,0x44,0xac,0x62,0x00,0x00,0x90,0x89,0x00,0x0a,0x00,0x80,0x30,0x21,
+0x11,0x20,0x00,0x05,0x00,0xa0,0x50,0x21,0x90,0x82,0x00,0x17,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x1b,0x00,0x00,0x00,0x00,0x90,0xc7,0x00,0x04,0x00,0x00,0x00,0x00,
+0x10,0xe0,0x00,0x1b,0x00,0x00,0x00,0x00,0x94,0xc8,0x00,0x00,0x27,0x83,0x8f,0xf0,
+0x93,0x85,0x8b,0x60,0x00,0x08,0x10,0xc0,0x00,0x48,0x10,0x21,0x00,0x02,0x10,0x80,
+0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x08,0x00,0xe5,0x28,0x2b,0x10,0xa0,0x00,0x06,
+0x01,0x44,0x18,0x23,0x8f,0x82,0x8b,0x78,0x00,0x00,0x00,0x00,0x00,0x43,0x10,0x2b,
+0x10,0x40,0x00,0x05,0x00,0x00,0x00,0x00,0x24,0x03,0x00,0x10,0xa4,0xc8,0x00,0x14,
+0x03,0xe0,0x00,0x08,0x00,0x60,0x10,0x21,0x11,0x20,0x00,0x05,0x00,0x00,0x00,0x00,
+0x94,0xc2,0x00,0x06,0x24,0x03,0x00,0x08,0x08,0x00,0x1f,0x34,0xa4,0xc2,0x00,0x14,
+0x08,0x00,0x1f,0x34,0x00,0x00,0x18,0x21,0x27,0xbd,0xff,0xc8,0xaf,0xb5,0x00,0x2c,
+0xaf,0xb4,0x00,0x28,0xaf,0xb3,0x00,0x24,0xaf,0xb0,0x00,0x18,0xaf,0xbf,0x00,0x30,
+0xaf,0xb2,0x00,0x20,0xaf,0xb1,0x00,0x1c,0x94,0x91,0x00,0x06,0x00,0x80,0xa0,0x21,
+0x3c,0x02,0x80,0x00,0x3c,0x04,0xb0,0x03,0x00,0x11,0xa8,0xc0,0x34,0x84,0x00,0x20,
+0x24,0x42,0x7c,0xf8,0x02,0xb1,0x48,0x21,0xac,0x82,0x00,0x00,0x00,0x09,0x48,0x80,
+0x24,0x03,0x00,0x01,0x27,0x82,0x90,0x00,0xa2,0x83,0x00,0x12,0x01,0x22,0x10,0x21,
+0x27,0x84,0x8f,0xf4,0x01,0x24,0x20,0x21,0x80,0x48,0x00,0x06,0x8c,0x8a,0x00,0x18,
+0x27,0x83,0x90,0x10,0x01,0x23,0x48,0x21,0x8d,0x24,0x00,0x00,0x25,0x08,0x00,0x02,
+0x8d,0x42,0x00,0x00,0x8d,0x49,0x00,0x04,0x00,0x08,0x17,0xc2,0x8d,0x43,0x00,0x08,
+0x01,0x02,0x40,0x21,0x00,0x04,0x25,0xc2,0x00,0x08,0x40,0x43,0x30,0x84,0x00,0x01,
+0x00,0x03,0x1f,0xc2,0x00,0x08,0x40,0x40,0x00,0xe0,0x80,0x21,0x00,0x64,0x18,0x24,
+0x00,0x09,0x49,0x42,0x01,0x48,0x10,0x21,0x00,0xa0,0x98,0x21,0x00,0xa0,0x20,0x21,
+0x00,0x40,0x38,0x21,0x02,0x00,0x28,0x21,0x14,0x60,0x00,0x19,0x31,0x29,0x00,0x01,
+0x94,0x42,0x00,0x00,0x02,0xb1,0x88,0x21,0x02,0x00,0x28,0x21,0x00,0x11,0x88,0x80,
+0x27,0x90,0x8f,0xf0,0x02,0x30,0x80,0x21,0x96,0x03,0x00,0x06,0x30,0x52,0xff,0xff,
+0x02,0x60,0x20,0x21,0x00,0x60,0x30,0x21,0xa6,0x83,0x00,0x1a,0x27,0x82,0x8f,0xf8,
+0x0c,0x00,0x08,0xdf,0x02,0x22,0x88,0x21,0x00,0x52,0x10,0x21,0x96,0x03,0x00,0x06,
+0xa6,0x22,0x00,0x04,0x8f,0xbf,0x00,0x30,0x7b,0xb4,0x01,0x7c,0x7b,0xb2,0x01,0x3c,
+0x7b,0xb0,0x00,0xfc,0x00,0x60,0x10,0x21,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x38,
+0xaf,0xa9,0x00,0x10,0x0c,0x00,0x09,0x06,0xaf,0xa0,0x00,0x14,0x08,0x00,0x1f,0x72,
+0x02,0xb1,0x88,0x21,0x27,0xbd,0xff,0xc0,0xaf,0xbe,0x00,0x38,0xaf,0xb7,0x00,0x34,
+0xaf,0xb6,0x00,0x30,0xaf,0xb5,0x00,0x2c,0xaf,0xb3,0x00,0x24,0xaf,0xb1,0x00,0x1c,
+0xaf,0xbf,0x00,0x3c,0xaf,0xb4,0x00,0x28,0xaf,0xb2,0x00,0x20,0xaf,0xb0,0x00,0x18,
+0x94,0x90,0x00,0x00,0x3c,0x08,0xb0,0x03,0x35,0x08,0x00,0x20,0x00,0x10,0x10,0xc0,
+0x00,0x50,0x18,0x21,0x00,0x40,0x88,0x21,0x3c,0x02,0x80,0x00,0x00,0x03,0x48,0x80,
+0x24,0x42,0x7e,0x34,0x00,0x80,0x98,0x21,0x27,0x84,0x90,0x00,0x01,0x24,0x20,0x21,
+0x93,0xb7,0x00,0x53,0xad,0x02,0x00,0x00,0x80,0x83,0x00,0x06,0x27,0x82,0x8f,0xf4,
+0x01,0x22,0x10,0x21,0x8c,0x44,0x00,0x18,0x24,0x63,0x00,0x02,0x00,0x03,0x17,0xc2,
+0x8c,0x88,0x00,0x08,0x00,0x62,0x18,0x21,0x00,0x03,0x18,0x43,0x00,0x03,0x18,0x40,
+0xaf,0xa7,0x00,0x4c,0x2c,0xa2,0x00,0x10,0x00,0xa0,0xa8,0x21,0x00,0x83,0x50,0x21,
+0x00,0x08,0x47,0xc2,0x00,0xc0,0x58,0x21,0x00,0x00,0xb0,0x21,0x8c,0x92,0x00,0x0c,
+0x14,0x40,0x00,0x13,0x00,0x00,0xf0,0x21,0x92,0x67,0x00,0x04,0x24,0x14,0x00,0x01,
+0x12,0x87,0x00,0x10,0x02,0x30,0x10,0x21,0x27,0x83,0x90,0x08,0x01,0x23,0x18,0x21,
+0x80,0x64,0x00,0x00,0x27,0x83,0xb5,0x60,0x00,0x04,0x11,0x00,0x00,0x44,0x10,0x23,
+0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,
+0x90,0x44,0x00,0x04,0x00,0x00,0x00,0x00,0x10,0x80,0x00,0x23,0x00,0x00,0x00,0x00,
+0x02,0x30,0x10,0x21,0x00,0x02,0x80,0x80,0x24,0x04,0x00,0x01,0x27,0x83,0x90,0x10,
+0xa2,0x64,0x00,0x12,0x02,0x03,0x18,0x21,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x02,0x15,0xc2,0x30,0x42,0x00,0x01,0x01,0x02,0x10,0x24,0x14,0x40,0x00,0x0e,
+0x02,0xa0,0x20,0x21,0x27,0x82,0x8f,0xf0,0x02,0x02,0x10,0x21,0x94,0x43,0x00,0x06,
+0x00,0x00,0x00,0x00,0xa6,0x63,0x00,0x1a,0x94,0x42,0x00,0x06,0x7b,0xbe,0x01,0xfc,
+0x7b,0xb6,0x01,0xbc,0x7b,0xb4,0x01,0x7c,0x7b,0xb2,0x01,0x3c,0x7b,0xb0,0x00,0xfc,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x40,0x8f,0xa5,0x00,0x4c,0x01,0x60,0x30,0x21,
+0x01,0x40,0x38,0x21,0xaf,0xa0,0x00,0x10,0x0c,0x00,0x09,0x06,0xaf,0xa0,0x00,0x14,
+0x08,0x00,0x1f,0xd9,0x00,0x00,0x00,0x00,0x27,0x83,0x90,0x10,0x01,0x23,0x18,0x21,
+0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x15,0xc2,0x30,0x42,0x00,0x01,
+0x01,0x02,0x10,0x24,0x14,0x40,0x00,0xaf,0x00,0xa0,0x20,0x21,0x32,0x4f,0x00,0x03,
+0x00,0x12,0x10,0x82,0x25,0xe3,0x00,0x0d,0x30,0x45,0x00,0x07,0x00,0x74,0x78,0x04,
+0x10,0xa0,0x00,0x0e,0x00,0x00,0x90,0x21,0x27,0x82,0x80,0x1c,0x00,0x15,0x18,0x40,
+0x00,0x62,0x18,0x21,0x94,0x64,0x00,0x00,0x24,0xa2,0x00,0x06,0x00,0x54,0x10,0x04,
+0x00,0x44,0x00,0x1a,0x14,0x80,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x0d,
+0x00,0x00,0x10,0x12,0x24,0x42,0x00,0x20,0x30,0x52,0xff,0xfc,0x02,0x30,0x10,0x21,
+0x27,0x83,0x90,0x00,0x00,0x02,0x10,0x80,0x00,0x43,0x10,0x21,0x90,0x44,0x00,0x03,
+0x00,0x00,0x00,0x00,0x30,0x83,0x00,0xff,0x2c,0x62,0x00,0x0c,0x14,0x40,0x00,0x04,
+0x2c,0x62,0x00,0x19,0x30,0x82,0x00,0x0f,0x24,0x43,0x00,0x0c,0x2c,0x62,0x00,0x19,
+0x10,0x40,0x00,0x19,0x24,0x0e,0x00,0x20,0x24,0x62,0xff,0xe9,0x2c,0x42,0x00,0x02,
+0x14,0x40,0x00,0x15,0x24,0x0e,0x00,0x10,0x24,0x62,0xff,0xeb,0x2c,0x42,0x00,0x02,
+0x14,0x40,0x00,0x11,0x24,0x0e,0x00,0x08,0x24,0x02,0x00,0x14,0x10,0x62,0x00,0x0e,
+0x24,0x0e,0x00,0x02,0x24,0x62,0xff,0xef,0x2c,0x42,0x00,0x03,0x14,0x40,0x00,0x0a,
+0x24,0x0e,0x00,0x10,0x24,0x62,0xff,0xf1,0x2c,0x42,0x00,0x02,0x14,0x40,0x00,0x06,
+0x24,0x0e,0x00,0x08,0x24,0x62,0xff,0xf3,0x2c,0x42,0x00,0x02,0x24,0x0e,0x00,0x04,
+0x24,0x03,0x00,0x02,0x00,0x62,0x70,0x0a,0x30,0xe2,0x00,0xff,0x00,0x00,0x48,0x21,
+0x00,0x00,0x68,0x21,0x10,0x40,0x00,0x6d,0x00,0x00,0x58,0x21,0x3c,0x14,0x80,0xff,
+0x27,0x99,0x8f,0xf0,0x01,0xf2,0xc0,0x23,0x36,0x94,0xff,0xff,0x01,0xc9,0x10,0x2a,
+0x14,0x40,0x00,0x64,0x24,0x03,0x00,0x04,0x00,0x10,0x28,0xc0,0x00,0xb0,0x10,0x21,
+0x00,0x02,0x10,0x80,0x00,0x59,0x10,0x21,0x94,0x56,0x00,0x06,0x00,0x00,0x00,0x00,
+0x32,0xcc,0x00,0x03,0x00,0x6c,0x10,0x23,0x30,0x42,0x00,0x03,0x02,0xc2,0x10,0x21,
+0x24,0x42,0x00,0x04,0x30,0x51,0xff,0xff,0x02,0x32,0x18,0x2b,0x10,0x60,0x00,0x4d,
+0x01,0xf1,0x10,0x23,0x02,0x51,0x10,0x23,0x01,0x78,0x18,0x2b,0x10,0x60,0x00,0x34,
+0x30,0x44,0xff,0xff,0x29,0x22,0x00,0x40,0x10,0x40,0x00,0x31,0x01,0x72,0x18,0x21,
+0x25,0x22,0x00,0x01,0x00,0x02,0x16,0x00,0x00,0x02,0x4e,0x03,0x00,0xb0,0x10,0x21,
+0x00,0x02,0x30,0x80,0x27,0x82,0x8f,0xf4,0x30,0x6b,0xff,0xff,0x00,0xc2,0x18,0x21,
+0x8c,0x67,0x00,0x18,0x00,0x04,0x25,0x40,0x3c,0x03,0x7f,0x00,0x8c,0xe2,0x00,0x04,
+0x00,0x83,0x20,0x24,0x27,0x83,0x90,0x00,0x00,0x54,0x10,0x24,0x00,0xc3,0x28,0x21,
+0x00,0x44,0x10,0x25,0xac,0xe2,0x00,0x04,0x16,0xe0,0x00,0x02,0xa0,0xb5,0x00,0x00,
+0xa0,0xb5,0x00,0x03,0x27,0x84,0x90,0x10,0x00,0xc4,0x18,0x21,0x8c,0x62,0x00,0x00,
+0x8c,0xe8,0x00,0x08,0x00,0x02,0x15,0xc2,0x00,0x08,0x47,0xc2,0x30,0x42,0x00,0x01,
+0x01,0x02,0x10,0x24,0x10,0x40,0x00,0x0a,0x00,0x00,0x00,0x00,0x80,0xa2,0x00,0x06,
+0x00,0x00,0x00,0x00,0x24,0x42,0x00,0x02,0x00,0x02,0x1f,0xc2,0x00,0x43,0x10,0x21,
+0x00,0x02,0x10,0x43,0x00,0x02,0x10,0x40,0x00,0xe2,0x50,0x21,0xa5,0x5e,0x00,0x00,
+0x92,0x62,0x00,0x04,0x25,0xad,0x00,0x01,0x27,0x84,0x8f,0xf0,0x00,0xc4,0x18,0x21,
+0x01,0xa2,0x10,0x2a,0x94,0x70,0x00,0x02,0x14,0x40,0xff,0xb8,0x00,0x00,0x00,0x00,
+0x96,0x63,0x00,0x14,0x00,0x0c,0x10,0x23,0xa2,0x69,0x00,0x12,0x30,0x42,0x00,0x03,
+0x01,0x62,0x10,0x23,0x00,0x03,0x80,0xc0,0x8f,0xa5,0x00,0x4c,0x30,0x4b,0xff,0xff,
+0x02,0x03,0x80,0x21,0x27,0x82,0x8f,0xf8,0x00,0x10,0x80,0x80,0xa6,0x6b,0x00,0x1a,
+0x02,0xa0,0x20,0x21,0x01,0x60,0x30,0x21,0x01,0x60,0x88,0x21,0x0c,0x00,0x08,0xdf,
+0x02,0x02,0x80,0x21,0x00,0x5e,0x10,0x21,0xa6,0x02,0x00,0x04,0x08,0x00,0x1f,0xdf,
+0x02,0x20,0x10,0x21,0x01,0x62,0x10,0x2b,0x10,0x40,0xff,0xe9,0x00,0x00,0x20,0x21,
+0x29,0x22,0x00,0x40,0x10,0x40,0xff,0xe6,0x01,0x71,0x18,0x21,0x08,0x00,0x20,0x55,
+0x25,0x22,0x00,0x01,0x08,0x00,0x20,0x84,0x32,0xcc,0x00,0x03,0x08,0x00,0x20,0x84,
+0x00,0x00,0x60,0x21,0x8f,0xa5,0x00,0x4c,0x01,0x40,0x38,0x21,0xaf,0xa0,0x00,0x10,
+0x0c,0x00,0x09,0x06,0xaf,0xb4,0x00,0x14,0x92,0x67,0x00,0x04,0x08,0x00,0x1f,0xf7,
+0x30,0x5e,0xff,0xff,0x30,0x84,0xff,0xff,0x00,0x04,0x30,0xc0,0x00,0xc4,0x20,0x21,
+0x00,0x04,0x20,0x80,0x27,0x82,0x8f,0xf0,0x3c,0x03,0xb0,0x08,0x30,0xa5,0xff,0xff,
+0x00,0x82,0x20,0x21,0x00,0xc3,0x30,0x21,0xac,0xc5,0x00,0x00,0x03,0xe0,0x00,0x08,
+0xa4,0x85,0x00,0x00,0x30,0x84,0xff,0xff,0x00,0x04,0x30,0xc0,0x00,0xc4,0x30,0x21,
+0x27,0x88,0x8f,0xf0,0x00,0x06,0x30,0x80,0x00,0xc8,0x30,0x21,0x94,0xc3,0x00,0x04,
+0x3c,0x02,0xb0,0x08,0x3c,0x07,0xb0,0x03,0x00,0x03,0x20,0xc0,0x00,0x83,0x18,0x21,
+0x00,0x03,0x18,0x80,0x00,0x82,0x20,0x21,0x3c,0x02,0x80,0x01,0x30,0xa5,0xff,0xff,
+0x00,0x68,0x18,0x21,0x34,0xe7,0x00,0x20,0x24,0x42,0x82,0xe4,0xac,0xe2,0x00,0x00,
+0xa4,0xc5,0x00,0x02,0xa4,0x65,0x00,0x00,0x03,0xe0,0x00,0x08,0xac,0x85,0x00,0x00,
+0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,0x34,0x42,0x00,0x20,0x24,0x63,0x83,0x40,
+0xac,0x43,0x00,0x00,0x90,0x82,0x00,0x10,0x3c,0x08,0xb0,0x03,0x3c,0x09,0xb0,0x06,
+0x27,0x87,0x8f,0xf0,0x3c,0x0d,0xb0,0x08,0x34,0x0e,0xff,0xff,0x35,0x08,0x00,0x62,
+0x00,0x80,0x30,0x21,0x24,0x0c,0xff,0xff,0x10,0x40,0x00,0x2c,0x35,0x29,0x80,0x20,
+0x97,0x82,0x8f,0xe0,0x94,0x85,0x00,0x0c,0x3c,0x0b,0xb0,0x03,0x00,0x02,0x18,0xc0,
+0x00,0x62,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x47,0x10,0x21,0xa4,0x45,0x00,0x00,
+0x94,0x84,0x00,0x0e,0x00,0x6d,0x18,0x21,0xac,0x65,0x00,0x00,0x00,0x04,0x10,0xc0,
+0x00,0x44,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x47,0x10,0x21,0x94,0x45,0x00,0x04,
+0x3c,0x0a,0x77,0x77,0x35,0x6b,0x00,0xb4,0x00,0x05,0x10,0xc0,0x00,0x45,0x18,0x21,
+0x00,0x03,0x18,0x80,0x00,0x67,0x18,0x21,0x00,0x4d,0x10,0x21,0xac,0x4e,0x00,0x00,
+0xa4,0x6e,0x00,0x00,0x95,0x04,0x00,0x00,0x90,0xc3,0x00,0x10,0x24,0x02,0x00,0xff,
+0x00,0x44,0x10,0x23,0x00,0x43,0x10,0x2a,0xa7,0x85,0x8f,0xe0,0x10,0x40,0x00,0x04,
+0x35,0x4a,0x88,0x88,0xad,0x6a,0x00,0x00,0x90,0xc3,0x00,0x10,0x00,0x00,0x00,0x00,
+0x30,0x63,0x00,0xff,0x3c,0x02,0x00,0x40,0x00,0x62,0x18,0x25,0xad,0x23,0x00,0x00,
+0xa4,0xcc,0x00,0x0e,0xa4,0xcc,0x00,0x0c,0xa0,0xc0,0x00,0x10,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x30,0x84,0xff,0xff,0x00,0x04,0x10,0xc0,0x00,0x44,0x10,0x21,
+0x27,0x89,0x8f,0xf0,0x00,0x02,0x10,0x80,0x00,0x49,0x10,0x21,0x97,0x83,0x8f,0xe0,
+0x94,0x4a,0x00,0x04,0x3c,0x02,0xb0,0x08,0x00,0x03,0x38,0xc0,0x00,0x0a,0x40,0xc0,
+0x00,0xe3,0x18,0x21,0x01,0x0a,0x28,0x21,0x00,0xe2,0x38,0x21,0x01,0x02,0x40,0x21,
+0x00,0x03,0x18,0x80,0x00,0x05,0x28,0x80,0x3c,0x06,0xb0,0x03,0x3c,0x02,0x80,0x01,
+0x00,0xa9,0x28,0x21,0x00,0x69,0x18,0x21,0x34,0xc6,0x00,0x20,0x34,0x09,0xff,0xff,
+0x24,0x42,0x84,0x34,0xac,0xc2,0x00,0x00,0xa4,0x64,0x00,0x00,0xac,0xe4,0x00,0x00,
+0xa4,0xa9,0x00,0x00,0xad,0x09,0x00,0x00,0xa7,0x8a,0x8f,0xe0,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x01,0x34,0x63,0x00,0x20,
+0x24,0x42,0x84,0xb4,0x3c,0x04,0xb0,0x03,0xac,0x62,0x00,0x00,0x34,0x84,0x01,0x10,
+0x8c,0x82,0x00,0x00,0x97,0x83,0x81,0x60,0x30,0x42,0xff,0xff,0x10,0x62,0x00,0x16,
+0x24,0x0a,0x00,0x01,0xa7,0x82,0x81,0x60,0xaf,0x80,0xb4,0x40,0x00,0x40,0x28,0x21,
+0x24,0x06,0x00,0x01,0x27,0x84,0xb4,0x44,0x25,0x43,0xff,0xff,0x00,0x66,0x10,0x04,
+0x00,0xa2,0x10,0x24,0x14,0x40,0x00,0x07,0x00,0x00,0x00,0x00,0x8c,0x83,0xff,0xfc,
+0x00,0x00,0x00,0x00,0x00,0x66,0x10,0x04,0x00,0xa2,0x10,0x24,0x38,0x42,0x00,0x00,
+0x01,0x42,0x18,0x0a,0x25,0x4a,0x00,0x01,0x2d,0x42,0x00,0x14,0xac,0x83,0x00,0x00,
+0x14,0x40,0xff,0xf1,0x24,0x84,0x00,0x04,0x3c,0x0b,0xb0,0x03,0x00,0x00,0x50,0x21,
+0x3c,0x0c,0x80,0x00,0x27,0x89,0xb4,0x90,0x35,0x6b,0x01,0x20,0x8d,0x68,0x00,0x00,
+0x8d,0x23,0x00,0x04,0x01,0x0c,0x10,0x24,0x00,0x02,0x17,0xc2,0x11,0x03,0x00,0x37,
+0xa1,0x22,0x00,0xdc,0xa1,0x20,0x00,0xd5,0xa1,0x20,0x00,0xd6,0x01,0x20,0x30,0x21,
+0x00,0x00,0x38,0x21,0x00,0x00,0x28,0x21,0x01,0x20,0x20,0x21,0x00,0xa8,0x10,0x06,
+0x30,0x42,0x00,0x01,0x10,0xe0,0x00,0x10,0xa0,0x82,0x00,0x0a,0x90,0x82,0x00,0x07,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x31,0x24,0xa2,0xff,0xff,0xa0,0x82,0x00,0x08,
+0x90,0x82,0x00,0x0a,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x09,0x00,0x00,0x00,0x00,
+0x90,0x83,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x03,0x10,0x40,0x00,0x43,0x10,0x21,
+0x00,0x46,0x10,0x21,0xa0,0x45,0x00,0x09,0x90,0x82,0x00,0x0a,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x07,0x00,0x00,0x00,0x00,0x14,0xe0,0x00,0x04,0x00,0x00,0x00,0x00,
+0xa0,0xc5,0x00,0xd5,0x24,0x07,0x00,0x01,0xa0,0x85,0x00,0x08,0xa0,0xc5,0x00,0xd6,
+0x24,0xa5,0x00,0x01,0x2c,0xa2,0x00,0x1c,0x14,0x40,0xff,0xe0,0x24,0x84,0x00,0x03,
+0x90,0xc4,0x00,0xd5,0x00,0x00,0x28,0x21,0x00,0xa4,0x10,0x2b,0x10,0x40,0x00,0x0b,
+0x00,0x00,0x00,0x00,0x00,0xc0,0x18,0x21,0xa0,0x64,0x00,0x08,0x90,0xc2,0x00,0xd5,
+0x24,0xa5,0x00,0x01,0xa0,0x62,0x00,0x09,0x90,0xc4,0x00,0xd5,0x00,0x00,0x00,0x00,
+0x00,0xa4,0x10,0x2b,0x14,0x40,0xff,0xf8,0x24,0x63,0x00,0x03,0x25,0x4a,0x00,0x01,
+0x2d,0x42,0x00,0x08,0xad,0x28,0x00,0x04,0x25,0x6b,0x00,0x04,0x14,0x40,0xff,0xbf,
+0x25,0x29,0x00,0xec,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x90,0x82,0x00,0x05,
+0x08,0x00,0x21,0x68,0xa0,0x82,0x00,0x08,0x97,0x85,0x8b,0x6a,0x3c,0x03,0xb0,0x03,
+0x3c,0x02,0x80,0x01,0x27,0xbd,0xff,0xe8,0x34,0x63,0x00,0x20,0x24,0x42,0x86,0x68,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,0xac,0x62,0x00,0x00,0x30,0x90,0x00,0xff,
+0x00,0x05,0x28,0x42,0x00,0x00,0x48,0x21,0x27,0x8f,0xb4,0x94,0x00,0x00,0x50,0x21,
+0x00,0x00,0x58,0x21,0x27,0x98,0xb5,0x74,0x27,0x99,0xb5,0x70,0x27,0x8e,0xb5,0x6e,
+0x27,0x8c,0xb4,0x98,0x27,0x8d,0xb4,0xf0,0x27,0x88,0xb5,0x68,0x00,0x0a,0x18,0x80,
+0x01,0x6f,0x10,0x21,0xac,0x40,0x00,0x00,0xac,0x45,0x00,0x58,0x00,0x6e,0x20,0x21,
+0x00,0x78,0x10,0x21,0xa1,0x00,0xff,0xfc,0xad,0x00,0x00,0x00,0xa1,0x00,0x00,0x04,
+0xa1,0x00,0x00,0x05,0xad,0x00,0xff,0xf8,0x00,0x79,0x18,0x21,0x24,0x06,0x00,0x01,
+0x24,0xc6,0xff,0xff,0xa0,0x80,0x00,0x00,0xa4,0x60,0x00,0x00,0xac,0x40,0x00,0x00,
+0x24,0x63,0x00,0x02,0x24,0x42,0x00,0x04,0x04,0xc1,0xff,0xf9,0x24,0x84,0x00,0x01,
+0x00,0x0a,0x10,0x80,0x00,0x4d,0x20,0x21,0x00,0x00,0x30,0x21,0x00,0x4c,0x18,0x21,
+0x27,0x87,0x81,0x64,0x8c,0xe2,0x00,0x00,0x24,0xe7,0x00,0x04,0xac,0x82,0x00,0x00,
+0xa0,0x66,0x00,0x00,0xa0,0x66,0x00,0x01,0x24,0xc6,0x00,0x01,0x28,0xc2,0x00,0x1c,
+0xa0,0x60,0x00,0x02,0x24,0x84,0x00,0x04,0x14,0x40,0xff,0xf6,0x24,0x63,0x00,0x03,
+0x25,0x29,0x00,0x01,0x29,0x22,0x00,0x08,0x25,0x4a,0x00,0x3b,0x25,0x08,0x00,0xec,
+0x14,0x40,0xff,0xd6,0x25,0x6b,0x00,0xec,0xa7,0x80,0x81,0x60,0x00,0x00,0x48,0x21,
+0x27,0x83,0xb4,0x40,0xac,0x69,0x00,0x00,0x25,0x29,0x00,0x01,0x29,0x22,0x00,0x0c,
+0x14,0x40,0xff,0xfc,0x24,0x63,0x00,0x04,0x0c,0x00,0x21,0x2d,0x00,0x00,0x00,0x00,
+0x2e,0x04,0x00,0x14,0x27,0x83,0xb4,0x90,0x24,0x09,0x00,0x07,0x10,0x80,0x00,0x0a,
+0x00,0x00,0x00,0x00,0x90,0x62,0x00,0xd5,0x25,0x29,0xff,0xff,0xa0,0x62,0x00,0x00,
+0x05,0x21,0xff,0xfa,0x24,0x63,0x00,0xec,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x90,0x62,0x00,0xd6,0x08,0x00,0x21,0xeb,
+0x25,0x29,0xff,0xff,0x30,0x84,0x00,0xff,0x00,0x04,0x11,0x00,0x00,0x44,0x10,0x23,
+0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x23,0x00,0x02,0x10,0x80,0x27,0x83,0xb4,0x90,
+0x00,0x43,0x60,0x21,0x3c,0x04,0xb0,0x03,0x3c,0x02,0x80,0x01,0x34,0x84,0x00,0x20,
+0x24,0x42,0x87,0xd4,0x30,0xc6,0x00,0xff,0x93,0xa9,0x00,0x13,0x30,0xa5,0x00,0xff,
+0x30,0xe7,0x00,0xff,0xac,0x82,0x00,0x00,0x10,0xc0,0x00,0xeb,0x25,0x8f,0x00,0xd0,
+0x91,0x82,0x00,0x00,0x00,0x00,0x00,0x00,0x24,0x42,0xff,0xfc,0x2c,0x43,0x00,0x18,
+0x10,0x60,0x00,0xcf,0x3c,0x03,0x80,0x01,0x00,0x02,0x10,0x80,0x24,0x63,0x02,0x5c,
+0x00,0x43,0x10,0x21,0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x08,
+0x00,0x00,0x00,0x00,0x2d,0x22,0x00,0x2d,0x10,0x40,0x00,0x14,0x00,0x00,0x00,0x00,
+0x10,0xa0,0x00,0x0f,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0x00,0x09,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,0x10,0xa2,0x00,0x06,0x00,0x00,0x00,0x00,
+0x8d,0x82,0x00,0xd0,0x00,0x00,0x00,0x00,0x24,0x42,0xff,0xd0,0x03,0xe0,0x00,0x08,
+0xad,0x82,0x00,0xd0,0x8d,0x82,0x00,0xd0,0x08,0x00,0x22,0x23,0x24,0x42,0xff,0xe0,
+0x8d,0x82,0x00,0xd0,0x08,0x00,0x22,0x23,0x24,0x42,0x00,0x01,0x10,0xa0,0x00,0x0f,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xf9,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0xa2,0x00,0x07,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x03,
+0x14,0xa2,0xff,0xf0,0x00,0x00,0x00,0x00,0x8d,0x82,0x00,0xd0,0x08,0x00,0x22,0x23,
+0x24,0x42,0xff,0xe8,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x8d,0x82,0x00,0xd0,
+0x08,0x00,0x22,0x23,0x24,0x42,0x00,0x02,0x10,0xa0,0xff,0xfc,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xe6,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,
+0x10,0xa2,0xff,0xf4,0x24,0x02,0x00,0x03,0x14,0xa2,0xff,0xef,0x00,0x00,0x00,0x00,
+0x8d,0x82,0x00,0xd0,0x08,0x00,0x22,0x23,0x24,0x42,0xff,0xf8,0x2d,0x22,0x00,0x19,
+0x14,0x40,0xff,0xde,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0xec,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xd6,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,
+0x10,0xa2,0xff,0xe4,0x24,0x02,0x00,0x03,0x10,0xa2,0xff,0xf1,0x00,0x00,0x00,0x00,
+0x8d,0x82,0x00,0xd0,0x08,0x00,0x22,0x23,0x24,0x42,0xff,0xf0,0x2d,0x22,0x00,0x1b,
+0x10,0x40,0xff,0xf1,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0xdc,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xc6,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,
+0x14,0xa2,0xff,0xce,0x00,0x00,0x00,0x00,0x8d,0x82,0x00,0xd0,0x08,0x00,0x22,0x23,
+0x24,0x42,0xff,0xf4,0x2d,0x22,0x00,0x1e,0x10,0x40,0xff,0xe3,0x00,0x00,0x00,0x00,
+0x10,0xa0,0xff,0xce,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xc9,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0xd6,0x00,0x00,0x00,0x00,0x08,0x00,0x22,0x34,
+0x24,0x02,0x00,0x03,0x2d,0x22,0x00,0x23,0x10,0x40,0xff,0xd7,0x00,0x00,0x00,0x00,
+0x10,0xa0,0xff,0xaf,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xbd,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0xda,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x03,
+0x14,0xa2,0xff,0x9f,0x00,0x00,0x00,0x00,0x08,0x00,0x22,0x25,0x00,0x00,0x00,0x00,
+0x2d,0x22,0x00,0x25,0x10,0x40,0xff,0xc8,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0xa0,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0x00,0x06,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0x97,0x00,0x00,0x00,0x00,0x08,0x00,0x22,0x80,
+0x24,0x02,0x00,0x03,0x8d,0x82,0x00,0xd0,0x08,0x00,0x22,0x23,0x24,0x42,0xff,0xfc,
+0x2d,0x22,0x00,0x16,0x14,0x40,0x00,0x0e,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0xa3,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x8d,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0x9b,0x24,0x02,0x00,0x03,0x14,0xa2,0xff,0xa8,
+0x00,0x00,0x00,0x00,0x8d,0x82,0x00,0xd0,0x08,0x00,0x22,0x23,0x24,0x42,0xff,0xfa,
+0x10,0xa0,0xff,0x96,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x80,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0x8e,0x00,0x00,0x00,0x00,
+0x08,0x00,0x22,0x48,0x00,0x00,0x00,0x00,0x2d,0x22,0x00,0x17,0x14,0x40,0xff,0x9e,
+0x00,0x00,0x00,0x00,0x08,0x00,0x22,0x97,0x00,0x00,0x00,0x00,0x2d,0x22,0x00,0x19,
+0x10,0x40,0xff,0xe2,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0x84,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x6e,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,
+0x10,0xa2,0xff,0x7c,0x24,0x02,0x00,0x03,0x10,0xa2,0xff,0x89,0x00,0x00,0x00,0x00,
+0x08,0x00,0x22,0x25,0x00,0x00,0x00,0x00,0x08,0x00,0x22,0xb4,0x2d,0x22,0x00,0x1b,
+0x2d,0x22,0x00,0x1e,0x10,0x40,0xff,0xde,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0x73,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x5d,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0x6b,0x24,0x02,0x00,0x03,0x10,0xa2,0xff,0x88,
+0x00,0x00,0x00,0x00,0x08,0x00,0x22,0x25,0x00,0x00,0x00,0x00,0x2d,0x22,0x00,0x23,
+0x14,0x40,0xff,0xf2,0x00,0x00,0x00,0x00,0x08,0x00,0x22,0x4e,0x00,0x00,0x00,0x00,
+0x08,0x00,0x22,0x4c,0x2d,0x22,0x00,0x25,0x08,0x00,0x22,0x85,0x2d,0x22,0x00,0x27,
+0x10,0xa0,0xff,0x5e,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x48,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0x56,0x24,0x02,0x00,0x03,
+0x14,0xa2,0xff,0x63,0x00,0x00,0x00,0x00,0x08,0x00,0x22,0x91,0x00,0x00,0x00,0x00,
+0x2d,0x22,0x00,0x27,0x14,0x40,0xff,0x8e,0x00,0x00,0x00,0x00,0x08,0x00,0x22,0x3e,
+0x00,0x00,0x00,0x00,0x2d,0x22,0x00,0x29,0x14,0x40,0xff,0x89,0x00,0x00,0x00,0x00,
+0x08,0x00,0x22,0x2b,0x00,0x00,0x00,0x00,0x91,0x86,0x00,0x00,0x91,0x83,0x00,0xd4,
+0x25,0x8d,0x00,0x5c,0x30,0xc4,0x00,0xff,0x00,0x04,0x10,0x40,0x00,0x44,0x10,0x21,
+0x00,0x04,0x50,0x80,0x01,0x82,0x58,0x21,0x01,0x8a,0x40,0x21,0x25,0x78,0x00,0x08,
+0x10,0x60,0x00,0x37,0x25,0x0e,0x00,0x60,0x2c,0xa2,0x00,0x03,0x14,0x40,0x00,0x25,
+0x00,0x00,0x00,0x00,0x91,0x82,0x00,0xdd,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x1e,
+0x00,0x00,0x00,0x00,0x27,0x87,0x81,0x64,0x01,0x47,0x10,0x21,0x8c,0x43,0x00,0x00,
+0x00,0x00,0x00,0x00,0xad,0x03,0x00,0x60,0x91,0x62,0x00,0x08,0x00,0x00,0x00,0x00,
+0x00,0x40,0x30,0x21,0xa1,0x82,0x00,0x00,0x30,0xc2,0x00,0xff,0x00,0x02,0x10,0x80,
+0x00,0x47,0x10,0x21,0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x18,0x42,
+0xad,0xa3,0x00,0x00,0x91,0x84,0x00,0x00,0x8d,0xc5,0x00,0x00,0x00,0x04,0x20,0x80,
+0x00,0x87,0x10,0x21,0x8c,0x43,0x00,0x00,0x00,0x05,0x28,0x40,0x00,0x8c,0x20,0x21,
+0x00,0x03,0x18,0x80,0x00,0xa3,0x10,0x2b,0x00,0x62,0x28,0x0a,0xac,0x85,0x00,0x60,
+0x03,0xe0,0x00,0x08,0xa1,0x80,0x00,0xd4,0x27,0x87,0x81,0x64,0x08,0x00,0x23,0x0e,
+0xa1,0x80,0x00,0xdd,0x27,0x82,0x81,0xd4,0x8d,0x83,0x00,0xd8,0x00,0x82,0x10,0x21,
+0x90,0x44,0x00,0x00,0x24,0x63,0x00,0x01,0x00,0x64,0x20,0x2b,0x14,0x80,0xff,0x0d,
+0xad,0x83,0x00,0xd8,0x8d,0x02,0x00,0x60,0xa1,0x80,0x00,0xd4,0x00,0x02,0x1f,0xc2,
+0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x43,0x03,0xe0,0x00,0x08,0xad,0x82,0x00,0x5c,
+0x10,0xe0,0x00,0x1a,0x24,0x83,0xff,0xfc,0x2c,0x62,0x00,0x18,0x10,0x40,0x01,0x18,
+0x00,0x03,0x10,0x80,0x3c,0x03,0x80,0x01,0x24,0x63,0x02,0xbc,0x00,0x43,0x10,0x21,
+0x8c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x08,0x00,0x00,0x00,0x00,
+0x2d,0x22,0x00,0x2d,0x10,0x40,0x00,0x5f,0x00,0x00,0x00,0x00,0x10,0xa0,0x00,0x5a,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0x00,0x54,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0xa2,0x00,0x51,0x00,0x00,0x00,0x00,0x8d,0x82,0x00,0xd0,
+0x00,0x00,0x00,0x00,0x24,0x42,0xff,0xd0,0xad,0x82,0x00,0xd0,0x8d,0xe3,0x00,0x00,
+0x8d,0xa2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x43,0x10,0x21,0xad,0xa2,0x00,0x00,
+0xad,0xe0,0x00,0x00,0x8d,0xa3,0x00,0x00,0x8d,0xc4,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x83,0x10,0x2a,0x10,0x40,0x00,0x22,0x00,0x00,0x00,0x00,0x93,0x05,0x00,0x01,
+0x91,0x82,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x45,0x00,0x05,0x24,0x02,0x00,0x01,
+0xa1,0x85,0x00,0x00,0xa1,0x82,0x00,0xd4,0x03,0xe0,0x00,0x08,0xad,0x80,0x00,0xd8,
+0x91,0x82,0x00,0xdd,0x24,0x03,0x00,0x01,0x10,0x43,0x00,0x05,0x00,0x00,0x00,0x00,
+0xa1,0x83,0x00,0xd4,0xad,0x80,0x00,0xd8,0x03,0xe0,0x00,0x08,0xa1,0x83,0x00,0xdd,
+0x00,0x04,0x17,0xc2,0x00,0x82,0x10,0x21,0x00,0x02,0x10,0x43,0xad,0xa2,0x00,0x00,
+0x91,0x83,0x00,0x00,0x27,0x82,0x81,0x64,0x8d,0xc5,0x00,0x00,0x00,0x03,0x18,0x80,
+0x00,0x62,0x18,0x21,0x8c,0x64,0x00,0x00,0x00,0x05,0x28,0x40,0x00,0x04,0x18,0x80,
+0x00,0xa3,0x10,0x2b,0x00,0x62,0x28,0x0a,0x08,0x00,0x23,0x20,0xad,0xc5,0x00,0x00,
+0x97,0x82,0x8b,0x6c,0x00,0x00,0x00,0x00,0x00,0x62,0x10,0x2a,0x10,0x40,0xfe,0xb9,
+0x00,0x00,0x00,0x00,0x91,0x82,0x00,0xdd,0x00,0x00,0x00,0x00,0x14,0x40,0x00,0x15,
+0x00,0x00,0x00,0x00,0x91,0x83,0x00,0x00,0x27,0x82,0x81,0x64,0x00,0x03,0x18,0x80,
+0x00,0x62,0x10,0x21,0x8c,0x44,0x00,0x00,0x00,0x6c,0x18,0x21,0xac,0x64,0x00,0x60,
+0x93,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x10,0x80,0x01,0x82,0x10,0x21,
+0x24,0x4e,0x00,0x60,0xa1,0x85,0x00,0x00,0x8d,0xc2,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x02,0x1f,0xc2,0x00,0x43,0x10,0x21,0x00,0x02,0x10,0x43,0x03,0xe0,0x00,0x08,
+0xad,0xa2,0x00,0x00,0x08,0x00,0x23,0x92,0xa1,0x80,0x00,0xdd,0x8d,0x82,0x00,0xd0,
+0x08,0x00,0x23,0x4e,0x24,0x42,0xff,0xe0,0x8d,0x82,0x00,0xd0,0x08,0x00,0x23,0x4e,
+0x24,0x42,0x00,0x01,0x10,0xa0,0x00,0x0d,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,
+0x10,0xa2,0xff,0xf9,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0xa7,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x03,0x14,0xa2,0xff,0xf0,0x00,0x00,0x00,0x00,
+0x8d,0x82,0x00,0xd0,0x08,0x00,0x23,0x4e,0x24,0x42,0xff,0xe8,0x8d,0x82,0x00,0xd0,
+0x08,0x00,0x23,0x4e,0x24,0x42,0x00,0x02,0x10,0xa0,0xff,0xfc,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xe8,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,
+0x10,0xa2,0xff,0x96,0x24,0x02,0x00,0x03,0x14,0xa2,0xff,0xf1,0x00,0x00,0x00,0x00,
+0x8d,0x82,0x00,0xd0,0x08,0x00,0x23,0x4e,0x24,0x42,0xff,0xf8,0x2d,0x22,0x00,0x19,
+0x14,0x40,0xff,0xe0,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0xec,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xd8,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,
+0x10,0xa2,0xff,0x86,0x24,0x02,0x00,0x03,0x10,0xa2,0xff,0xf1,0x00,0x00,0x00,0x00,
+0x8d,0x82,0x00,0xd0,0x08,0x00,0x23,0x4e,0x24,0x42,0xff,0xf0,0x2d,0x22,0x00,0x1b,
+0x10,0x40,0xff,0xf1,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0xdc,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0xc8,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,
+0x14,0xa2,0xff,0xd0,0x00,0x00,0x00,0x00,0x8d,0x82,0x00,0xd0,0x08,0x00,0x23,0x4e,
+0x24,0x42,0xff,0xf4,0x2d,0x22,0x00,0x1e,0x10,0x40,0xff,0xe3,0x00,0x00,0x00,0x00,
+0x10,0xa0,0xff,0xce,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x6b,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0xd6,0x00,0x00,0x00,0x00,0x08,0x00,0x23,0xaa,
+0x24,0x02,0x00,0x03,0x2d,0x22,0x00,0x23,0x10,0x40,0xff,0xd7,0x00,0x00,0x00,0x00,
+0x10,0xa0,0xff,0xb1,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x5f,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0xda,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x03,
+0x14,0xa2,0xff,0x56,0x00,0x00,0x00,0x00,0x08,0x00,0x23,0x9b,0x00,0x00,0x00,0x00,
+0x2d,0x22,0x00,0x25,0x10,0x40,0xff,0xc8,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0xa2,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0x00,0x06,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0x99,0x00,0x00,0x00,0x00,0x08,0x00,0x23,0xf4,
+0x24,0x02,0x00,0x03,0x8d,0x82,0x00,0xd0,0x08,0x00,0x23,0x4e,0x24,0x42,0xff,0xfc,
+0x2d,0x22,0x00,0x16,0x14,0x40,0x00,0x0e,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0xa3,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x8f,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0x3d,0x24,0x02,0x00,0x03,0x14,0xa2,0xff,0xa8,
+0x00,0x00,0x00,0x00,0x8d,0x82,0x00,0xd0,0x08,0x00,0x23,0x4e,0x24,0x42,0xff,0xfa,
+0x10,0xa0,0xff,0x96,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x82,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0x30,0x00,0x00,0x00,0x00,
+0x08,0x00,0x23,0xbc,0x00,0x00,0x00,0x00,0x2d,0x22,0x00,0x17,0x14,0x40,0xff,0x9e,
+0x00,0x00,0x00,0x00,0x08,0x00,0x24,0x0b,0x00,0x00,0x00,0x00,0x2d,0x22,0x00,0x19,
+0x10,0x40,0xff,0xe2,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0x84,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x70,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,
+0x10,0xa2,0xff,0x1e,0x24,0x02,0x00,0x03,0x10,0xa2,0xff,0x89,0x00,0x00,0x00,0x00,
+0x08,0x00,0x23,0x9b,0x00,0x00,0x00,0x00,0x08,0x00,0x24,0x28,0x2d,0x22,0x00,0x1b,
+0x2d,0x22,0x00,0x1e,0x10,0x40,0xff,0xde,0x00,0x00,0x00,0x00,0x10,0xa0,0xff,0x73,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x5f,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x02,0x10,0xa2,0xff,0x0d,0x24,0x02,0x00,0x03,0x10,0xa2,0xff,0x88,
+0x00,0x00,0x00,0x00,0x08,0x00,0x23,0x9b,0x00,0x00,0x00,0x00,0x2d,0x22,0x00,0x23,
+0x14,0x40,0xff,0xf2,0x00,0x00,0x00,0x00,0x08,0x00,0x23,0xc2,0x00,0x00,0x00,0x00,
+0x08,0x00,0x23,0xc0,0x2d,0x22,0x00,0x25,0x08,0x00,0x23,0xf9,0x2d,0x22,0x00,0x27,
+0x10,0xa0,0xff,0x5e,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x01,0x10,0xa2,0xff,0x4a,
+0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,0x10,0xa2,0xfe,0xf8,0x24,0x02,0x00,0x03,
+0x14,0xa2,0xff,0x63,0x00,0x00,0x00,0x00,0x08,0x00,0x24,0x05,0x00,0x00,0x00,0x00,
+0x2d,0x22,0x00,0x27,0x14,0x40,0xff,0x8e,0x00,0x00,0x00,0x00,0x08,0x00,0x23,0xb2,
+0x00,0x00,0x00,0x00,0x2d,0x22,0x00,0x29,0x14,0x40,0xff,0x89,0x00,0x00,0x00,0x00,
+0x08,0x00,0x23,0xa1,0x00,0x00,0x00,0x00,0x27,0xbd,0xff,0xe8,0x3c,0x02,0xb0,0x03,
+0xaf,0xbf,0x00,0x14,0xaf,0xb0,0x00,0x10,0x34,0x42,0x01,0x18,0x3c,0x03,0xb0,0x03,
+0x8c,0x50,0x00,0x00,0x34,0x63,0x01,0x2c,0x90,0x62,0x00,0x00,0x32,0x05,0x00,0x01,
+0xa3,0x82,0x80,0x10,0x14,0xa0,0x00,0x14,0x30,0x44,0x00,0xff,0x32,0x02,0x01,0x00,
+0x14,0x40,0x00,0x09,0x00,0x00,0x00,0x00,0x32,0x02,0x08,0x00,0x10,0x40,0x00,0x02,
+0x24,0x02,0x00,0x01,0xa3,0x82,0xbc,0x08,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x0c,0x00,0x05,0x39,0x00,0x00,0x00,0x00,
+0x26,0x02,0xff,0x00,0xa3,0x80,0xbc,0x08,0x3c,0x01,0xb0,0x03,0xac,0x22,0x01,0x18,
+0x08,0x00,0x24,0x77,0x32,0x02,0x08,0x00,0x0c,0x00,0x21,0x9a,0x00,0x00,0x00,0x00,
+0x26,0x02,0xff,0xff,0x3c,0x01,0xb0,0x03,0xac,0x22,0x01,0x18,0x08,0x00,0x24,0x74,
+0x32,0x02,0x01,0x00,0x27,0xbd,0xff,0xe0,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0xd0,
+0xaf,0xbf,0x00,0x18,0x8c,0x43,0x00,0x00,0x3c,0x02,0x00,0x40,0x24,0x07,0x0f,0xff,
+0x00,0x03,0x33,0x02,0x00,0x03,0x2d,0x02,0x00,0x03,0x43,0x02,0x30,0x69,0x0f,0xff,
+0x00,0x62,0x18,0x24,0x30,0xa5,0x00,0x03,0x30,0xc6,0x00,0xff,0x10,0x60,0x00,0x08,
+0x31,0x08,0x00,0xff,0x01,0x00,0x30,0x21,0x0c,0x00,0x25,0x38,0xaf,0xa9,0x00,0x10,
+0x8f,0xbf,0x00,0x18,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x20,
+0x0c,0x00,0x25,0x8a,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x34,0x63,0x00,0xd4,
+0x08,0x00,0x24,0xa0,0xac,0x62,0x00,0x00,0x27,0xbd,0xff,0xc0,0xaf,0xb6,0x00,0x30,
+0xaf,0xb3,0x00,0x24,0xaf,0xb1,0x00,0x1c,0xaf,0xb0,0x00,0x18,0xaf,0xbf,0x00,0x3c,
+0xaf,0xbe,0x00,0x38,0xaf,0xb7,0x00,0x34,0xaf,0xb5,0x00,0x2c,0xaf,0xb4,0x00,0x28,
+0xaf,0xb2,0x00,0x20,0x0c,0x00,0x17,0xc8,0x00,0x80,0x80,0x21,0x00,0x00,0xb0,0x21,
+0x00,0x00,0x88,0x21,0x10,0x40,0x00,0x12,0x00,0x00,0x98,0x21,0x3c,0x02,0xb0,0x03,
+0x3c,0x03,0xb0,0x03,0x3c,0x04,0xb0,0x03,0x24,0x05,0x00,0x01,0x34,0x42,0x00,0xbc,
+0x34,0x63,0x00,0xbb,0x34,0x84,0x00,0xba,0xa4,0x40,0x00,0x00,0xa0,0x65,0x00,0x00,
+0xa0,0x85,0x00,0x00,0x7b,0xbe,0x01,0xfc,0x7b,0xb6,0x01,0xbc,0x7b,0xb4,0x01,0x7c,
+0x7b,0xb2,0x01,0x3c,0x7b,0xb0,0x00,0xfc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x40,
+0x3c,0x02,0xb0,0x03,0x34,0x42,0x01,0x47,0x90,0x44,0x00,0x00,0x00,0x10,0x1a,0x02,
+0x3c,0x15,0xfd,0xff,0x30,0x84,0x00,0xff,0xa0,0x50,0x00,0x00,0x30,0x74,0x00,0x0f,
+0xaf,0xa4,0x00,0x10,0x00,0x00,0x90,0x21,0x3c,0x17,0x02,0x00,0x36,0xb5,0xff,0xff,
+0x3c,0x1e,0xb0,0x03,0x0c,0x00,0x06,0xce,0x24,0x04,0x04,0x00,0x00,0x57,0x10,0x25,
+0x00,0x40,0x28,0x21,0x0c,0x00,0x06,0xc1,0x24,0x04,0x04,0x00,0x00,0x00,0x80,0x21,
+0x0c,0x00,0x26,0x52,0x00,0x00,0x00,0x00,0x26,0x03,0x00,0x01,0x30,0x70,0x00,0xff,
+0x10,0x40,0x00,0x47,0x2e,0x03,0x00,0x02,0x14,0x60,0xff,0xf9,0x00,0x00,0x00,0x00,
+0x0c,0x00,0x06,0xce,0x24,0x04,0x04,0x00,0x00,0x55,0x10,0x24,0x00,0x40,0x28,0x21,
+0x0c,0x00,0x06,0xc1,0x24,0x04,0x04,0x00,0x24,0x02,0x00,0x01,0x12,0x82,0x00,0x38,
+0x00,0x00,0x00,0x00,0x12,0x80,0x00,0x36,0x00,0x00,0x00,0x00,0x32,0x22,0x00,0x60,
+0x32,0x23,0x0c,0x00,0x00,0x03,0x1a,0x02,0x3c,0x05,0x00,0x60,0x00,0x02,0x11,0x42,
+0x02,0x25,0x20,0x24,0x00,0x43,0x10,0x25,0x3c,0x03,0x04,0x00,0x02,0x23,0x28,0x24,
+0x00,0x04,0x24,0x42,0x00,0x44,0x10,0x25,0x00,0x05,0x2d,0x02,0x00,0x45,0x88,0x25,
+0x12,0x20,0x00,0x05,0x26,0x42,0x00,0x01,0x26,0xc2,0x00,0x01,0x30,0x56,0x00,0xff,
+0x02,0x71,0x98,0x21,0x26,0x42,0x00,0x01,0x02,0x5e,0x20,0x21,0x30,0x52,0x00,0xff,
+0x2e,0x43,0x00,0x05,0xa0,0x91,0x00,0xd8,0x14,0x60,0xff,0xce,0x3c,0x02,0xb0,0x03,
+0x8f,0xa5,0x00,0x10,0x34,0x42,0x01,0x47,0xa0,0x45,0x00,0x00,0x12,0x60,0x00,0x0e,
+0x3c,0x02,0xb0,0x03,0x12,0xc0,0x00,0x0d,0x34,0x42,0x00,0xbc,0x00,0x13,0x10,0x40,
+0x00,0x53,0x10,0x21,0x00,0x02,0x10,0xc0,0x00,0x53,0x10,0x21,0x00,0x02,0x98,0x80,
+0x02,0x76,0x00,0x1b,0x16,0xc0,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x0d,
+0x00,0x00,0x98,0x12,0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0xbc,0x3c,0x03,0xb0,0x03,
+0x3c,0x04,0xb0,0x03,0xa4,0x53,0x00,0x00,0x34,0x63,0x00,0xbb,0x34,0x84,0x00,0xba,
+0x24,0x02,0x00,0x01,0xa0,0x60,0x00,0x00,0x08,0x00,0x24,0xc5,0xa0,0x82,0x00,0x00,
+0x0c,0x00,0x06,0xce,0x24,0x04,0x04,0xfc,0x08,0x00,0x24,0xf3,0x00,0x40,0x88,0x21,
+0x3c,0x03,0xb0,0x03,0x34,0x63,0x00,0xbc,0x3c,0x04,0xb0,0x03,0x3c,0x05,0xb0,0x03,
+0xa4,0x60,0x00,0x00,0x34,0x84,0x00,0xbb,0x34,0xa5,0x00,0xba,0x24,0x02,0x00,0x02,
+0x24,0x03,0x00,0x01,0xa0,0x82,0x00,0x00,0x08,0x00,0x24,0xc5,0xa0,0xa3,0x00,0x00,
+0x27,0xbd,0xff,0xd8,0xaf,0xb0,0x00,0x10,0x30,0xd0,0x00,0xff,0x2e,0x02,0x00,0x2e,
+0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xbf,0x00,0x20,0xaf,0xb3,0x00,0x1c,
+0x30,0xb1,0x00,0xff,0x14,0x40,0x00,0x06,0x00,0x80,0x90,0x21,0x8f,0xbf,0x00,0x20,
+0x7b,0xb2,0x00,0xfc,0x7b,0xb0,0x00,0xbc,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,
+0x2e,0x13,0x00,0x10,0x24,0x05,0x00,0x14,0x0c,0x00,0x13,0xa0,0x24,0x06,0x01,0x07,
+0x12,0x60,0x00,0x38,0x02,0x00,0x30,0x21,0x8f,0xa2,0x00,0x38,0x30,0xc3,0x00,0x3f,
+0x3c,0x04,0xb0,0x09,0x00,0x02,0x14,0x00,0x00,0x43,0x30,0x25,0x34,0x84,0x01,0x60,
+0x90,0x82,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0xfd,0x24,0x02,0x00,0x01,
+0x12,0x22,0x00,0x2a,0x2a,0x22,0x00,0x02,0x14,0x40,0x00,0x24,0x24,0x02,0x00,0x02,
+0x12,0x22,0x00,0x20,0x24,0x02,0x00,0x03,0x12,0x22,0x00,0x19,0x00,0x00,0x00,0x00,
+0x16,0x60,0xff,0xe2,0x24,0x02,0x00,0x01,0x12,0x22,0x00,0x13,0x2a,0x22,0x00,0x02,
+0x14,0x40,0x00,0x0d,0x24,0x02,0x00,0x02,0x12,0x22,0x00,0x09,0x24,0x02,0x00,0x03,
+0x16,0x22,0xff,0xda,0x00,0x00,0x00,0x00,0x24,0x04,0x08,0x4c,0x24,0x05,0xff,0xff,
+0x0c,0x00,0x13,0x5b,0x3c,0x06,0x0c,0xb8,0x08,0x00,0x25,0x43,0x00,0x00,0x00,0x00,
+0x08,0x00,0x25,0x6b,0x24,0x04,0x08,0x48,0x16,0x20,0xff,0xd0,0x00,0x00,0x00,0x00,
+0x08,0x00,0x25,0x6b,0x24,0x04,0x08,0x40,0x08,0x00,0x25,0x6b,0x24,0x04,0x08,0x44,
+0x24,0x04,0x08,0x4c,0x0c,0x00,0x13,0x5b,0x24,0x05,0xff,0xff,0x08,0x00,0x25,0x60,
+0x00,0x00,0x00,0x00,0x08,0x00,0x25,0x79,0x24,0x04,0x08,0x48,0x16,0x20,0xff,0xe0,
+0x00,0x00,0x00,0x00,0x08,0x00,0x25,0x79,0x24,0x04,0x08,0x40,0x08,0x00,0x25,0x79,
+0x24,0x04,0x08,0x44,0x02,0x40,0x20,0x21,0x0c,0x00,0x25,0xca,0x02,0x20,0x28,0x21,
+0x08,0x00,0x25,0x4e,0x00,0x40,0x30,0x21,0x27,0xbd,0xff,0xd8,0x2c,0xc2,0x00,0x2e,
+0xaf,0xb2,0x00,0x18,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x20,
+0xaf,0xb3,0x00,0x1c,0x00,0xc0,0x80,0x21,0x30,0xb1,0x00,0xff,0x00,0x80,0x90,0x21,
+0x14,0x40,0x00,0x07,0x00,0x00,0x18,0x21,0x8f,0xbf,0x00,0x20,0x7b,0xb2,0x00,0xfc,
+0x7b,0xb0,0x00,0xbc,0x00,0x60,0x10,0x21,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x28,
+0x2e,0x13,0x00,0x10,0x24,0x05,0x00,0x14,0x0c,0x00,0x13,0xa0,0x24,0x06,0x01,0x07,
+0x12,0x60,0x00,0x24,0x02,0x00,0x30,0x21,0x3c,0x03,0xb0,0x09,0x34,0x63,0x01,0x60,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x40,0xff,0xfd,0x30,0xc5,0x00,0x3f,
+0x0c,0x00,0x26,0x07,0x02,0x20,0x20,0x21,0x16,0x60,0x00,0x0a,0x00,0x40,0x80,0x21,
+0x24,0x02,0x00,0x01,0x12,0x22,0x00,0x15,0x2a,0x22,0x00,0x02,0x14,0x40,0x00,0x0f,
+0x24,0x02,0x00,0x02,0x12,0x22,0x00,0x0b,0x24,0x02,0x00,0x03,0x12,0x22,0x00,0x03,
+0x00,0x00,0x00,0x00,0x08,0x00,0x25,0x96,0x02,0x00,0x18,0x21,0x24,0x04,0x08,0x4c,
+0x24,0x05,0xff,0xff,0x0c,0x00,0x13,0x5b,0x3c,0x06,0x0c,0xb8,0x08,0x00,0x25,0x96,
+0x02,0x00,0x18,0x21,0x08,0x00,0x25,0xb8,0x24,0x04,0x08,0x48,0x16,0x20,0xff,0xf5,
+0x00,0x00,0x00,0x00,0x08,0x00,0x25,0xb8,0x24,0x04,0x08,0x40,0x08,0x00,0x25,0xb8,
+0x24,0x04,0x08,0x44,0x02,0x40,0x20,0x21,0x0c,0x00,0x25,0xca,0x02,0x20,0x28,0x21,
+0x08,0x00,0x25,0xa2,0x00,0x40,0x30,0x21,0x27,0xbd,0xff,0xe8,0x2c,0xc2,0x00,0x1f,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,0x00,0xc0,0x80,0x21,0x14,0x40,0x00,0x1d,
+0x30,0xa5,0x00,0xff,0x24,0x02,0x00,0x01,0x10,0xa2,0x00,0x18,0x28,0xa2,0x00,0x02,
+0x14,0x40,0x00,0x12,0x24,0x02,0x00,0x02,0x10,0xa2,0x00,0x0e,0x24,0x02,0x00,0x03,
+0x10,0xa2,0x00,0x07,0x24,0x04,0x08,0x4c,0x26,0x10,0xff,0xe2,0x02,0x00,0x10,0x21,
+0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,
+0x24,0x05,0xff,0xff,0x0c,0x00,0x13,0x5b,0x3c,0x06,0x0d,0xf8,0x08,0x00,0x25,0xdb,
+0x26,0x10,0xff,0xe2,0x08,0x00,0x25,0xe0,0x24,0x04,0x08,0x48,0x14,0xa0,0xff,0xf2,
+0x24,0x04,0x08,0x40,0x08,0x00,0x25,0xe1,0x24,0x05,0xff,0xff,0x08,0x00,0x25,0xe0,
+0x24,0x04,0x08,0x44,0x2c,0xc2,0x00,0x10,0x14,0x40,0xff,0xec,0x24,0x02,0x00,0x01,
+0x10,0xa2,0x00,0x14,0x28,0xa2,0x00,0x02,0x14,0x40,0x00,0x0e,0x24,0x02,0x00,0x02,
+0x10,0xa2,0x00,0x0a,0x24,0x02,0x00,0x03,0x10,0xa2,0x00,0x03,0x24,0x04,0x08,0x4c,
+0x08,0x00,0x25,0xdb,0x26,0x10,0xff,0xf1,0x24,0x05,0xff,0xff,0x0c,0x00,0x13,0x5b,
+0x3c,0x06,0x0d,0xb8,0x08,0x00,0x25,0xdb,0x26,0x10,0xff,0xf1,0x08,0x00,0x25,0xfa,
+0x24,0x04,0x08,0x48,0x14,0xa0,0xff,0xf6,0x24,0x04,0x08,0x40,0x08,0x00,0x25,0xfb,
+0x24,0x05,0xff,0xff,0x08,0x00,0x25,0xfa,0x24,0x04,0x08,0x44,0x27,0xbd,0xff,0xe8,
+0x30,0x84,0x00,0xff,0x24,0x02,0x00,0x01,0x10,0x82,0x00,0x39,0xaf,0xbf,0x00,0x10,
+0x28,0x82,0x00,0x02,0x14,0x40,0x00,0x27,0x00,0x00,0x00,0x00,0x24,0x02,0x00,0x02,
+0x10,0x82,0x00,0x17,0x00,0xa0,0x30,0x21,0x24,0x02,0x00,0x03,0x10,0x82,0x00,0x05,
+0x24,0x04,0x08,0x3c,0x8f,0xbf,0x00,0x10,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x0c,0x00,0x13,0x5b,0x3c,0x05,0x3f,0x00,0x24,0x04,0x08,0x3c,
+0x3c,0x05,0x80,0x00,0x0c,0x00,0x13,0x5b,0x00,0x00,0x30,0x21,0x24,0x04,0x08,0x3c,
+0x3c,0x05,0x80,0x00,0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x01,0x24,0x04,0x08,0xac,
+0x0c,0x00,0x13,0x3d,0x24,0x05,0x0f,0xff,0x08,0x00,0x26,0x15,0x00,0x00,0x00,0x00,
+0x24,0x04,0x08,0x34,0x0c,0x00,0x13,0x5b,0x3c,0x05,0x3f,0x00,0x24,0x04,0x08,0x34,
+0x3c,0x05,0x80,0x00,0x0c,0x00,0x13,0x5b,0x00,0x00,0x30,0x21,0x24,0x04,0x08,0x34,
+0x3c,0x05,0x80,0x00,0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x01,0x08,0x00,0x26,0x24,
+0x24,0x04,0x08,0xa8,0x14,0x80,0xff,0xdf,0x00,0xa0,0x30,0x21,0x24,0x04,0x08,0x24,
+0x0c,0x00,0x13,0x5b,0x3c,0x05,0x3f,0x00,0x24,0x04,0x08,0x24,0x3c,0x05,0x80,0x00,
+0x0c,0x00,0x13,0x5b,0x00,0x00,0x30,0x21,0x24,0x04,0x08,0x24,0x3c,0x05,0x80,0x00,
+0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x01,0x08,0x00,0x26,0x24,0x24,0x04,0x08,0xa0,
+0x00,0xa0,0x30,0x21,0x24,0x04,0x08,0x2c,0x0c,0x00,0x13,0x5b,0x3c,0x05,0x3f,0x00,
+0x24,0x04,0x08,0x2c,0x3c,0x05,0x80,0x00,0x0c,0x00,0x13,0x5b,0x00,0x00,0x30,0x21,
+0x24,0x04,0x08,0x2c,0x3c,0x05,0x80,0x00,0x0c,0x00,0x13,0x5b,0x24,0x06,0x00,0x01,
+0x08,0x00,0x26,0x24,0x24,0x04,0x08,0xa4,0x3c,0x05,0x00,0x14,0x3c,0x02,0xb0,0x05,
+0x34,0x42,0x04,0x20,0x3c,0x06,0xc0,0x00,0x3c,0x03,0xb0,0x05,0x3c,0x04,0xb0,0x05,
+0x34,0xa5,0x17,0x09,0xac,0x45,0x00,0x00,0x34,0xc6,0x05,0x07,0x34,0x63,0x04,0x24,
+0x34,0x84,0x02,0x28,0x3c,0x07,0xb0,0x05,0x24,0x02,0x00,0x20,0xac,0x66,0x00,0x00,
+0x34,0xe7,0x04,0x50,0xa0,0x82,0x00,0x00,0x90,0xe2,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x42,0x00,0x03,0x10,0x40,0xff,0xfc,0x24,0x02,0x00,0x01,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x93,0x85,0x81,0xf1,0x24,0x02,0x00,0x01,0x14,0xa2,0x00,0x51,
+0x00,0x80,0x40,0x21,0x8c,0x89,0x00,0x04,0x3c,0x03,0xb0,0x01,0x01,0x23,0x30,0x21,
+0x8c,0xc2,0x00,0x04,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x08,0x10,0x45,0x00,0x59,
+0x00,0x00,0x00,0x00,0x94,0xc2,0x00,0x38,0x24,0x03,0x00,0xb4,0x30,0x44,0x00,0xff,
+0x10,0x83,0x00,0x61,0x24,0x02,0x00,0xc4,0x10,0x82,0x00,0x54,0x24,0x02,0x00,0x94,
+0x10,0x82,0x00,0x45,0x00,0x00,0x00,0x00,0x94,0xc2,0x00,0x38,0x00,0x00,0x00,0x00,
+0x30,0x47,0xff,0xff,0x30,0xe3,0x40,0xff,0x24,0x02,0x40,0x88,0x14,0x62,0x00,0x39,
+0x30,0xe3,0x03,0x00,0x24,0x02,0x03,0x00,0x10,0x62,0x00,0x38,0x00,0x00,0x00,0x00,
+0x94,0xc2,0x00,0x56,0x00,0x00,0x00,0x00,0x30,0x47,0xff,0xff,0x30,0xe2,0x00,0x80,
+0x14,0x40,0x00,0x30,0x3c,0x02,0xb0,0x01,0x01,0x22,0x30,0x21,0x94,0xc3,0x00,0x60,
+0x24,0x02,0x00,0x08,0x14,0x43,0x00,0x3b,0x00,0x00,0x00,0x00,0x90,0xc2,0x00,0x62,
+0x24,0x03,0x00,0x04,0x00,0x02,0x39,0x02,0x10,0xe3,0x00,0x15,0x24,0x02,0x00,0x06,
+0x14,0xe2,0x00,0x34,0x00,0x00,0x00,0x00,0x8d,0x05,0x01,0xac,0x94,0xc4,0x00,0x66,
+0x27,0x82,0x89,0x58,0x00,0x05,0x28,0x80,0x30,0x87,0xff,0xff,0x00,0xa2,0x28,0x21,
+0x00,0x07,0x1a,0x00,0x8c,0xa4,0x00,0x00,0x00,0x07,0x12,0x02,0x00,0x43,0x10,0x25,
+0x24,0x42,0x00,0x5e,0x24,0x03,0xc0,0x00,0x30,0x47,0xff,0xff,0x00,0x83,0x20,0x24,
+0x00,0x87,0x20,0x25,0xac,0xa4,0x00,0x00,0x08,0x00,0x26,0xcd,0xad,0x07,0x00,0x10,
+0x8d,0x05,0x01,0xac,0x94,0xc4,0x00,0x64,0x27,0x82,0x89,0x58,0x00,0x05,0x28,0x80,
+0x30,0x87,0xff,0xff,0x00,0xa2,0x28,0x21,0x00,0x07,0x1a,0x00,0x8c,0xa4,0x00,0x00,
+0x00,0x07,0x12,0x02,0x00,0x43,0x10,0x25,0x24,0x42,0x00,0x36,0x3c,0x03,0xff,0xff,
+0x30,0x47,0xff,0xff,0x00,0x83,0x20,0x24,0x00,0x87,0x20,0x25,0xac,0xa4,0x00,0x00,
+0xad,0x07,0x00,0x10,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x94,0xc2,0x00,0x50,
+0x08,0x00,0x26,0x8b,0x30,0x47,0xff,0xff,0x8d,0x04,0x01,0xac,0x27,0x83,0x89,0x58,
+0x00,0x04,0x20,0x80,0x00,0x83,0x20,0x21,0x8c,0x82,0x00,0x00,0x3c,0x03,0xff,0xff,
+0x00,0x43,0x10,0x24,0x34,0x42,0x00,0x2e,0xac,0x82,0x00,0x00,0x24,0x03,0x00,0x2e,
+0xad,0x03,0x00,0x10,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x8d,0x04,0x01,0xac,
+0x27,0x83,0x89,0x58,0x00,0x04,0x20,0x80,0x00,0x83,0x20,0x21,0x8c,0x82,0x00,0x00,
+0x3c,0x03,0xff,0xff,0x00,0x43,0x10,0x24,0x34,0x42,0x00,0x0e,0x24,0x03,0x00,0x0e,
+0x08,0x00,0x26,0xcc,0xac,0x82,0x00,0x00,0x8d,0x04,0x01,0xac,0x27,0x83,0x89,0x58,
+0x00,0x04,0x20,0x80,0x00,0x83,0x20,0x21,0x8c,0x82,0x00,0x00,0x3c,0x03,0xff,0xff,
+0x00,0x43,0x10,0x24,0x34,0x42,0x00,0x14,0x24,0x03,0x00,0x14,0x08,0x00,0x26,0xcc,
+0xac,0x82,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x30,0xc6,0x00,0xff,
+0x00,0x06,0x48,0x40,0x01,0x26,0x10,0x21,0x00,0x02,0x10,0x80,0x27,0x8b,0xbc,0x20,
+0x27,0x83,0xbc,0x26,0x00,0x4b,0x40,0x21,0x00,0x43,0x10,0x21,0x94,0x47,0x00,0x00,
+0x30,0xa2,0x3f,0xff,0x10,0xe2,0x00,0x29,0x30,0x8a,0xff,0xff,0x95,0x02,0x00,0x02,
+0x24,0x03,0x00,0x01,0x00,0x02,0x11,0x82,0x30,0x42,0x00,0x01,0x10,0x43,0x00,0x18,
+0x00,0x00,0x00,0x00,0x01,0x26,0x10,0x21,0x00,0x02,0x10,0x80,0x00,0x4b,0x30,0x21,
+0x94,0xc4,0x00,0x02,0x27,0x83,0xbc,0x26,0x27,0x85,0xbc,0x24,0x00,0x45,0x28,0x21,
+0x30,0x84,0xff,0xdf,0x00,0x43,0x10,0x21,0xa4,0xc4,0x00,0x02,0xa4,0x40,0x00,0x00,
+0xa4,0xa0,0x00,0x00,0x94,0xc3,0x00,0x02,0x3c,0x04,0xb0,0x01,0x01,0x44,0x20,0x21,
+0x30,0x63,0xff,0xbf,0xa4,0xc3,0x00,0x02,0xa0,0xc0,0x00,0x00,0x8c,0x82,0x00,0x04,
+0x24,0x03,0xf0,0xff,0x00,0x43,0x10,0x24,0x03,0xe0,0x00,0x08,0xac,0x82,0x00,0x04,
+0x24,0x02,0xc0,0x00,0x91,0x04,0x00,0x01,0x00,0xa2,0x10,0x24,0x00,0x47,0x28,0x25,
+0x3c,0x03,0xb0,0x01,0x24,0x02,0x00,0x02,0x14,0x82,0xff,0xe2,0x01,0x43,0x18,0x21,
+0xac,0x65,0x00,0x00,0x08,0x00,0x26,0xfa,0x01,0x26,0x10,0x21,0x08,0x00,0x26,0xfa,
+0x01,0x26,0x10,0x21,0x93,0x83,0x81,0xf1,0x24,0x02,0x00,0x01,0x14,0x62,0x00,0x0d,
+0x3c,0x02,0xb0,0x01,0x8c,0x84,0x00,0x04,0x3c,0x06,0xb0,0x09,0x00,0x82,0x20,0x21,
+0x8c,0x85,0x00,0x08,0x8c,0x83,0x00,0x04,0x3c,0x02,0x01,0x00,0x34,0xc6,0x01,0x00,
+0x00,0x62,0x18,0x24,0x14,0x60,0x00,0x05,0x30,0xa5,0x20,0x00,0x24,0x02,0x00,0x06,
+0xa0,0xc2,0x00,0x00,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x09,
+0x10,0xa0,0xff,0xfc,0x34,0x63,0x01,0x00,0x24,0x02,0x00,0x0e,0x08,0x00,0x27,0x2d,
+0xa0,0x62,0x00,0x00,0x3c,0x02,0xb0,0x01,0x30,0xa5,0xff,0xff,0x00,0xa2,0x28,0x21,
+0x8c,0xa3,0x00,0x00,0x3c,0x02,0x10,0x00,0x00,0x80,0x30,0x21,0x00,0x62,0x18,0x24,
+0x8c,0xa2,0x00,0x04,0x10,0x60,0x00,0x04,0x00,0x00,0x00,0x00,0x30,0x42,0x80,0x00,
+0x10,0x40,0x00,0x13,0x00,0x00,0x00,0x00,0x8c,0xc2,0x01,0xa8,0x00,0x00,0x00,0x00,
+0x24,0x44,0x00,0x01,0x28,0x83,0x00,0x00,0x24,0x42,0x00,0x40,0x00,0x83,0x10,0x0a,
+0x93,0x83,0x81,0xf0,0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,0x00,0x82,0x20,0x23,
+0x24,0x63,0xff,0xff,0xac,0xc4,0x01,0xa8,0xa3,0x83,0x81,0xf0,0x8c,0xc4,0x01,0xac,
+0x8c,0xc2,0x01,0xa8,0x00,0x00,0x00,0x00,0x00,0x44,0x10,0x26,0x00,0x02,0x10,0x2b,
+0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x3c,0x03,0xb0,0x03,0x34,0x63,0x00,0x73,
+0x90,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x42,0x00,0x01,0x14,0x40,0x00,0x04,
+0x00,0x00,0x00,0x00,0xa3,0x80,0x81,0xf1,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x01,0xa3,0x82,0x81,0xf1,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0xa8,0x8c,0x43,0x00,0x00,0x00,0x00,0x00,0x00,
+0x30,0x62,0x00,0xff,0x00,0x03,0x2e,0x02,0x00,0x02,0x39,0x80,0x2c,0xa2,0x00,0x02,
+0x00,0x03,0x34,0x02,0x10,0x40,0x00,0x05,0x00,0x03,0x1a,0x02,0xa4,0x87,0x01,0xd8,
+0xa0,0x85,0x01,0xd4,0xa0,0x86,0x01,0xd5,0xa0,0x83,0x01,0xd6,0x03,0xe0,0x00,0x08,
+0x00,0x00,0x00,0x00,0x8c,0x82,0x00,0x04,0x3c,0x05,0xb0,0x01,0x00,0x80,0x50,0x21,
+0x00,0x45,0x10,0x21,0x8c,0x43,0x00,0x04,0x24,0x02,0x00,0x05,0x00,0x03,0x1a,0x02,
+0x30,0x69,0x00,0x0f,0x11,0x22,0x00,0x0b,0x24,0x02,0x00,0x07,0x11,0x22,0x00,0x09,
+0x24,0x02,0x00,0x0a,0x11,0x22,0x00,0x07,0x24,0x02,0x00,0x0b,0x11,0x22,0x00,0x05,
+0x24,0x02,0x00,0x01,0x93,0x83,0x81,0xf0,0x3c,0x04,0xb0,0x06,0x10,0x62,0x00,0x03,
+0x34,0x84,0x80,0x18,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,0x8c,0x82,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x02,0x17,0x02,0x14,0x40,0xff,0xfa,0x00,0x00,0x00,0x00,
+0x8d,0x43,0x01,0xa8,0x27,0x82,0x89,0x58,0x00,0x03,0x18,0x80,0x00,0x6a,0x20,0x21,
+0x8c,0x87,0x00,0xa8,0x00,0x62,0x18,0x21,0x8c,0x68,0x00,0x00,0x00,0xe5,0x28,0x21,
+0x8c,0xa9,0x00,0x00,0x3c,0x02,0xff,0xff,0x27,0x83,0x8a,0x58,0x01,0x22,0x10,0x24,
+0x00,0x48,0x10,0x25,0xac,0xa2,0x00,0x00,0x8d,0x44,0x01,0xa8,0x00,0x07,0x30,0xc2,
+0x3c,0x02,0x00,0x80,0x00,0x04,0x20,0x80,0x00,0x83,0x20,0x21,0x00,0x06,0x32,0x00,
+0x8c,0xa9,0x00,0x04,0x00,0xc2,0x30,0x25,0x8c,0x82,0x00,0x00,0x3c,0x03,0x80,0x00,
+0x01,0x22,0x10,0x25,0x00,0x43,0x10,0x25,0xac,0xa2,0x00,0x04,0xaf,0x87,0xbc,0x10,
+0x8c,0xa2,0x00,0x00,0x00,0x00,0x00,0x00,0xaf,0x82,0xbc,0x18,0x8c,0xa3,0x00,0x04,
+0x3c,0x01,0xb0,0x07,0xac,0x26,0x80,0x18,0x8d,0x42,0x01,0xa8,0xaf,0x83,0xbc,0x14,
+0x93,0x85,0x81,0xf0,0x24,0x44,0x00,0x01,0x28,0x83,0x00,0x00,0x24,0x42,0x00,0x40,
+0x00,0x83,0x10,0x0a,0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,0x24,0xa5,0xff,0xff,
+0x00,0x82,0x20,0x23,0xad,0x44,0x01,0xa8,0xa3,0x85,0x81,0xf0,0x08,0x00,0x27,0x89,
+0x00,0x00,0x00,0x00,0x3c,0x05,0xb0,0x03,0x3c,0x02,0x80,0x01,0x24,0x42,0x9f,0x04,
+0x34,0xa5,0x00,0x20,0xac,0xa2,0x00,0x00,0x24,0x02,0x00,0x02,0x24,0x03,0x00,0x20,
+0xac,0x82,0x00,0x64,0x3c,0x02,0x80,0x01,0xac,0x83,0x00,0x60,0x00,0x80,0x38,0x21,
+0xac,0x80,0x00,0x00,0xac,0x80,0x00,0x04,0xac,0x80,0x00,0x08,0xac,0x80,0x00,0x4c,
+0xac,0x80,0x00,0x50,0xac,0x80,0x00,0x54,0xac,0x80,0x00,0x0c,0xac,0x80,0x00,0x58,
+0xa0,0x80,0x00,0x5c,0x24,0x83,0x00,0x68,0x24,0x42,0xa0,0x14,0x24,0x04,0x00,0x0f,
+0x24,0x84,0xff,0xff,0xac,0x62,0x00,0x00,0x04,0x81,0xff,0xfd,0x24,0x63,0x00,0x04,
+0x3c,0x02,0xb0,0x03,0x34,0x42,0x00,0xa8,0xac,0xe0,0x01,0xa8,0xac,0xe0,0x01,0xac,
+0xac,0xe0,0x01,0xb0,0xac,0xe0,0x01,0xb4,0xa0,0xe0,0x01,0xb8,0xa0,0xe0,0x01,0xb9,
+0xa0,0xe0,0x01,0xba,0xa0,0xe0,0x01,0xc0,0xa0,0xe0,0x01,0xc1,0xac,0xe0,0x01,0xc4,
+0xac,0xe0,0x01,0xc8,0xac,0xe0,0x01,0xcc,0xac,0xe0,0x01,0xd0,0x8c,0x44,0x00,0x00,
+0x3c,0x02,0x80,0x01,0x24,0x42,0xa0,0xfc,0x30,0x83,0x00,0xff,0x00,0x03,0x19,0x80,
+0xa4,0xe3,0x01,0xd8,0xac,0xe2,0x00,0x78,0x3c,0x03,0x80,0x01,0x3c,0x02,0x80,0x01,
+0x24,0x63,0xa2,0x88,0x24,0x42,0xa1,0xf4,0xac,0xe3,0x00,0x88,0xac,0xe2,0x00,0x98,
+0x3c,0x03,0x80,0x01,0x3c,0x02,0x80,0x01,0x00,0x04,0x2e,0x03,0x00,0x04,0x34,0x03,
+0x24,0x63,0xa3,0x30,0x00,0x04,0x22,0x03,0x24,0x42,0xa4,0x74,0xac,0xe3,0x00,0xa0,
+0xac,0xe2,0x00,0xa4,0xa0,0xe5,0x01,0xd4,0xa0,0xe6,0x01,0xd5,0x03,0xe0,0x00,0x08,
+0xa0,0xe4,0x01,0xd6,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x01,0x34,0x63,0x00,0x20,
+0x24,0x42,0xa0,0x14,0x03,0xe0,0x00,0x08,0xac,0x62,0x00,0x00,0x3c,0x02,0xb0,0x03,
+0x3c,0x03,0x80,0x01,0x34,0x42,0x00,0x20,0x24,0x63,0xa0,0x2c,0xac,0x43,0x00,0x00,
+0x8c,0x82,0x00,0x10,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x11,0x00,0x80,0x28,0x21,
+0x8c,0x82,0x00,0x14,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x0d,0x00,0x00,0x00,0x00,
+0x8c,0x84,0x00,0x10,0x8c,0xa3,0x00,0x14,0x8c,0xa2,0x00,0x04,0x00,0x83,0x20,0x21,
+0x00,0x44,0x10,0x21,0x30,0x43,0x00,0xff,0x00,0x03,0x18,0x2b,0x00,0x02,0x12,0x02,
+0x00,0x43,0x10,0x21,0x00,0x02,0x12,0x00,0x30,0x42,0x3f,0xff,0xac,0xa2,0x00,0x04,
+0xac,0xa0,0x00,0x00,0xac,0xa0,0x00,0x4c,0xac,0xa0,0x00,0x50,0xac,0xa0,0x00,0x54,
+0x03,0xe0,0x00,0x08,0xac,0xa0,0x00,0x0c,0x3c,0x03,0xb0,0x03,0x3c,0x02,0x80,0x01,
+0x34,0x63,0x00,0x20,0x24,0x42,0xa0,0xa8,0xac,0x62,0x00,0x00,0x8c,0x86,0x00,0x04,
+0x3c,0x02,0xb0,0x01,0x24,0x03,0x00,0x01,0x00,0xc2,0x10,0x21,0x8c,0x45,0x00,0x00,
+0xac,0x83,0x00,0x4c,0x00,0x05,0x14,0x02,0x30,0xa3,0x3f,0xff,0x30,0x42,0x00,0xff,
+0xac,0x83,0x00,0x10,0xac,0x82,0x00,0x14,0x8c,0x83,0x00,0x14,0xac,0x85,0x00,0x40,
+0x00,0xc3,0x30,0x21,0x03,0xe0,0x00,0x08,0xac,0x86,0x00,0x08,0x3c,0x02,0xb0,0x03,
+0x3c,0x03,0x80,0x01,0x27,0xbd,0xff,0xe8,0x34,0x42,0x00,0x20,0x24,0x63,0xa0,0xfc,
+0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,0xac,0x43,0x00,0x00,0x8c,0x82,0x00,0x4c,
+0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x0a,0x00,0x80,0x80,0x21,0xae,0x00,0x00,0x00,
+0xae,0x00,0x00,0x4c,0xae,0x00,0x00,0x50,0xae,0x00,0x00,0x54,0xae,0x00,0x00,0x0c,
+0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,
+0x0c,0x00,0x28,0x2a,0x00,0x00,0x00,0x00,0x08,0x00,0x28,0x4c,0xae,0x00,0x00,0x00,
+0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,0x27,0xbd,0xff,0xe8,0x34,0x42,0x00,0x20,
+0x24,0x63,0xa1,0x60,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,0xac,0x43,0x00,0x00,
+0x8c,0x82,0x00,0x4c,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x16,0x00,0x80,0x80,0x21,
+0x8e,0x03,0x00,0x08,0x3c,0x02,0xb0,0x01,0x8e,0x04,0x00,0x44,0x00,0x62,0x18,0x21,
+0x90,0x65,0x00,0x00,0x24,0x02,0x00,0x01,0xae,0x02,0x00,0x50,0x30,0xa3,0x00,0xff,
+0x00,0x03,0x10,0x82,0x00,0x04,0x23,0x02,0x30,0x84,0x00,0x0f,0x30,0x42,0x00,0x03,
+0x00,0x03,0x19,0x02,0xae,0x04,0x00,0x34,0xae,0x02,0x00,0x2c,0xae,0x03,0x00,0x30,
+0xa2,0x05,0x00,0x48,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x0c,0x00,0x28,0x2a,0x00,0x00,0x00,0x00,0x08,0x00,0x28,0x64,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,0x27,0xbd,0xff,0xe8,
+0x34,0x42,0x00,0x20,0x24,0x63,0xa1,0xf4,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,
+0xac,0x43,0x00,0x00,0x8c,0x82,0x00,0x50,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x16,
+0x00,0x80,0x80,0x21,0x92,0x03,0x00,0x44,0x8e,0x02,0x00,0x40,0x83,0x85,0x8b,0xc4,
+0x92,0x04,0x00,0x41,0x30,0x63,0x00,0x01,0x00,0x02,0x16,0x02,0xae,0x04,0x00,0x14,
+0x00,0x00,0x30,0x21,0xae,0x02,0x00,0x18,0x10,0xa0,0x00,0x04,0xae,0x03,0x00,0x3c,
+0x10,0x60,0x00,0x03,0x24,0x02,0x00,0x01,0x24,0x06,0x00,0x01,0x24,0x02,0x00,0x01,
+0xa3,0x86,0x8b,0xc4,0x8f,0xbf,0x00,0x14,0xae,0x02,0x00,0x54,0x8f,0xb0,0x00,0x10,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x0c,0x00,0x28,0x58,0x00,0x00,0x00,0x00,
+0x08,0x00,0x28,0x89,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,
+0x27,0xbd,0xff,0xe8,0x34,0x42,0x00,0x20,0x24,0x63,0xa2,0x88,0xaf,0xb0,0x00,0x10,
+0xaf,0xbf,0x00,0x14,0xac,0x43,0x00,0x00,0x8c,0x82,0x00,0x50,0x00,0x00,0x00,0x00,
+0x10,0x40,0x00,0x1b,0x00,0x80,0x80,0x21,0x3c,0x02,0xb0,0x03,0x8c,0x42,0x00,0x00,
+0x92,0x04,0x00,0x44,0x8e,0x03,0x00,0x40,0x83,0x86,0x8b,0xc4,0x92,0x05,0x00,0x41,
+0x30,0x42,0x08,0x00,0x30,0x84,0x00,0x01,0x00,0x02,0x12,0xc2,0x00,0x03,0x1e,0x02,
+0x00,0x82,0x20,0x25,0xae,0x05,0x00,0x14,0x00,0x00,0x38,0x21,0xae,0x03,0x00,0x18,
+0x10,0xc0,0x00,0x04,0xae,0x04,0x00,0x3c,0x10,0x80,0x00,0x03,0x24,0x02,0x00,0x01,
+0x24,0x07,0x00,0x01,0x24,0x02,0x00,0x01,0xa3,0x87,0x8b,0xc4,0x8f,0xbf,0x00,0x14,
+0xae,0x02,0x00,0x54,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,
+0x0c,0x00,0x28,0x58,0x00,0x00,0x00,0x00,0x08,0x00,0x28,0xae,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,0x27,0xbd,0xff,0xe8,0x34,0x42,0x00,0x20,
+0x24,0x63,0xa3,0x30,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,0xac,0x43,0x00,0x00,
+0x8c,0x82,0x00,0x54,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x42,0x00,0x80,0x80,0x21,
+0x8e,0x04,0x00,0x04,0x8e,0x03,0x00,0x44,0x3c,0x02,0x80,0x00,0x3c,0x08,0xb0,0x01,
+0x34,0x42,0x00,0x10,0x00,0x88,0x20,0x21,0x00,0x62,0x18,0x25,0xac,0x83,0x00,0x04,
+0x8e,0x02,0x00,0x04,0x8e,0x03,0x01,0xac,0x27,0x89,0x89,0x58,0x00,0x48,0x10,0x21,
+0x8c,0x45,0x00,0x00,0x00,0x03,0x18,0x80,0x00,0x69,0x18,0x21,0xac,0x65,0x00,0x00,
+0x8e,0x02,0x00,0x04,0x8e,0x03,0x01,0xac,0x27,0x87,0x8a,0x58,0x00,0x48,0x10,0x21,
+0x8c,0x45,0x00,0x04,0x00,0x03,0x18,0x80,0x00,0x67,0x18,0x21,0xac,0x65,0x00,0x00,
+0x8e,0x02,0x01,0xac,0x8e,0x06,0x00,0x04,0x02,0x00,0x20,0x21,0x00,0x02,0x10,0x80,
+0x00,0x47,0x38,0x21,0x94,0xe3,0x00,0x02,0x00,0x49,0x10,0x21,0x90,0x45,0x00,0x00,
+0x00,0x03,0x1a,0x00,0x00,0xc8,0x30,0x21,0x00,0xa3,0x28,0x25,0x0c,0x00,0x26,0x69,
+0xa4,0xc5,0x00,0x2e,0x8e,0x03,0x01,0xac,0x8e,0x07,0x00,0x04,0x3c,0x06,0xb0,0x03,
+0x24,0x65,0x00,0x01,0x28,0xa4,0x00,0x00,0x24,0x62,0x00,0x40,0x00,0xa4,0x10,0x0a,
+0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,0x00,0x03,0x18,0x80,0x00,0xa2,0x28,0x23,
+0x00,0x70,0x18,0x21,0xae,0x05,0x01,0xac,0xac,0x67,0x00,0xa8,0x34,0xc6,0x00,0x30,
+0x8c,0xc3,0x00,0x00,0x93,0x82,0x81,0xf0,0x02,0x00,0x20,0x21,0x24,0x63,0x00,0x01,
+0x24,0x42,0x00,0x01,0xac,0xc3,0x00,0x00,0xa3,0x82,0x81,0xf0,0x0c,0x00,0x28,0x0b,
+0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x0c,0x00,0x28,0xa2,0x00,0x00,0x00,0x00,0x08,0x00,0x28,0xd8,
+0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,0x27,0xbd,0xff,0xe8,
+0x34,0x42,0x00,0x20,0x24,0x63,0xa4,0x74,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x14,
+0xac,0x43,0x00,0x00,0x8c,0x82,0x00,0x54,0x00,0x00,0x00,0x00,0x10,0x40,0x00,0x42,
+0x00,0x80,0x80,0x21,0x8e,0x04,0x00,0x04,0x8e,0x03,0x00,0x44,0x3c,0x02,0x80,0x00,
+0x3c,0x08,0xb0,0x01,0x34,0x42,0x00,0x10,0x00,0x88,0x20,0x21,0x00,0x62,0x18,0x25,
+0xac,0x83,0x00,0x04,0x8e,0x02,0x00,0x04,0x8e,0x03,0x01,0xac,0x27,0x89,0x89,0x58,
+0x00,0x48,0x10,0x21,0x8c,0x45,0x00,0x00,0x00,0x03,0x18,0x80,0x00,0x69,0x18,0x21,
+0xac,0x65,0x00,0x00,0x8e,0x02,0x00,0x04,0x8e,0x03,0x01,0xac,0x27,0x87,0x8a,0x58,
+0x00,0x48,0x10,0x21,0x8c,0x45,0x00,0x04,0x00,0x03,0x18,0x80,0x00,0x67,0x18,0x21,
+0xac,0x65,0x00,0x00,0x8e,0x02,0x01,0xac,0x8e,0x06,0x00,0x04,0x02,0x00,0x20,0x21,
+0x00,0x02,0x10,0x80,0x00,0x47,0x38,0x21,0x94,0xe3,0x00,0x02,0x00,0x49,0x10,0x21,
+0x90,0x45,0x00,0x00,0x00,0x03,0x1a,0x00,0x00,0xc8,0x30,0x21,0x00,0xa3,0x28,0x25,
+0x0c,0x00,0x26,0x69,0xa4,0xc5,0x00,0x2e,0x8e,0x03,0x01,0xac,0x8e,0x07,0x00,0x04,
+0x3c,0x06,0xb0,0x03,0x24,0x65,0x00,0x01,0x28,0xa4,0x00,0x00,0x24,0x62,0x00,0x40,
+0x00,0xa4,0x10,0x0a,0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,0x00,0x03,0x18,0x80,
+0x00,0xa2,0x28,0x23,0x00,0x70,0x18,0x21,0xae,0x05,0x01,0xac,0xac,0x67,0x00,0xa8,
+0x34,0xc6,0x00,0x30,0x8c,0xc3,0x00,0x00,0x93,0x82,0x81,0xf0,0x02,0x00,0x20,0x21,
+0x24,0x63,0x00,0x01,0x24,0x42,0x00,0x01,0xac,0xc3,0x00,0x00,0xa3,0x82,0x81,0xf0,
+0x0c,0x00,0x28,0x0b,0x00,0x00,0x00,0x00,0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x0c,0x00,0x28,0xa2,0x00,0x00,0x00,0x00,
+0x08,0x00,0x29,0x29,0x00,0x00,0x00,0x00,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,
+0x27,0xbd,0xff,0xd8,0x34,0x42,0x00,0x20,0x24,0x63,0xa5,0xb8,0xaf,0xb2,0x00,0x18,
+0xac,0x43,0x00,0x00,0x3c,0x12,0xb0,0x03,0x3c,0x02,0x80,0x01,0xaf,0xb4,0x00,0x20,
+0xaf,0xb3,0x00,0x1c,0xaf,0xb1,0x00,0x14,0xaf,0xb0,0x00,0x10,0xaf,0xbf,0x00,0x24,
+0x00,0x80,0x80,0x21,0x24,0x54,0xa0,0x14,0x00,0x00,0x88,0x21,0x3c,0x13,0xb0,0x01,
+0x36,0x52,0x00,0xef,0x3c,0x02,0xb0,0x09,0x34,0x42,0x00,0x06,0x90,0x43,0x00,0x00,
+0x8e,0x04,0x00,0x04,0x92,0x02,0x01,0xbb,0x30,0x69,0x00,0xff,0x00,0x04,0x42,0x02,
+0x10,0x40,0x00,0x1e,0x00,0x00,0x38,0x21,0x8e,0x03,0x01,0xa8,0x3c,0x06,0x28,0x38,
+0x34,0xc6,0x00,0x20,0x24,0x64,0x00,0x3d,0x28,0x82,0x00,0x00,0x24,0x63,0x00,0x7c,
+0x00,0x82,0x18,0x0a,0x00,0x03,0x19,0x83,0x00,0x03,0x19,0x80,0x00,0x83,0x20,0x23,
+0x00,0x04,0x10,0x80,0x00,0x50,0x10,0x21,0x8c,0x45,0x00,0xa8,0xae,0x04,0x01,0xac,
+0xae,0x04,0x01,0xa8,0x00,0xb3,0x18,0x21,0xae,0x05,0x00,0x04,0xac,0x66,0x00,0x00,
+0x8e,0x02,0x00,0x04,0x3c,0x03,0x80,0x00,0x34,0x63,0x4e,0x00,0x00,0x53,0x10,0x21,
+0xac,0x43,0x00,0x04,0xa2,0x00,0x01,0xbb,0x93,0x83,0x81,0xf7,0x00,0x00,0x00,0x00,
+0x24,0x62,0x00,0x01,0xa3,0x82,0x81,0xf7,0xa2,0x43,0x00,0x00,0x01,0x28,0x10,0x23,
+0x24,0x44,0x00,0x40,0x28,0x83,0x00,0x00,0x24,0x42,0x00,0x7f,0x00,0x83,0x10,0x0a,
+0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,0x24,0x84,0xff,0xff,0x10,0x44,0x00,0x6b,
+0x3c,0x02,0xb0,0x01,0x8e,0x03,0x00,0x04,0x3c,0x04,0x7c,0x00,0x00,0x62,0x18,0x21,
+0x8c,0x65,0x00,0x04,0x34,0x84,0x00,0xf0,0x00,0x00,0x30,0x21,0xae,0x05,0x00,0x44,
+0x00,0xa4,0x20,0x24,0x8c,0x63,0x00,0x00,0x10,0x80,0x00,0x6b,0x3c,0x02,0xff,0xff,
+0x3c,0x09,0xb0,0x03,0x3c,0x05,0x7c,0x00,0x35,0x29,0x00,0x99,0x3c,0x0a,0xb0,0x01,
+0x24,0x08,0x00,0x40,0x34,0xa5,0x00,0xf0,0x3c,0x0b,0xff,0xff,0x3c,0x0c,0x28,0x38,
+0x16,0x20,0x00,0x06,0x24,0xe7,0x00,0x01,0x93,0x82,0x81,0xf6,0x24,0x11,0x00,0x01,
+0x24,0x42,0x00,0x01,0xa1,0x22,0x00,0x00,0xa3,0x82,0x81,0xf6,0x8e,0x02,0x00,0x04,
+0x24,0x06,0x00,0x01,0x24,0x42,0x01,0x00,0x30,0x42,0x3f,0xff,0xae,0x02,0x00,0x04,
+0x00,0x4a,0x10,0x21,0x8c,0x43,0x00,0x04,0x00,0x00,0x00,0x00,0xae,0x03,0x00,0x44,
+0x00,0x65,0x20,0x24,0x8c,0x43,0x00,0x00,0x10,0xe8,0x00,0x2d,0x00,0x00,0x00,0x00,
+0x14,0x80,0xff,0xeb,0x00,0x6b,0x10,0x24,0x14,0x4c,0xff,0xe9,0x24,0x02,0x00,0x01,
+0x10,0xc2,0x00,0x30,0x3c,0x03,0xb0,0x09,0x8e,0x02,0x00,0x44,0x8e,0x04,0x00,0x60,
+0x00,0x02,0x1e,0x42,0x00,0x02,0x12,0x02,0x30,0x42,0x00,0x0f,0x30,0x63,0x00,0x01,
+0xae,0x02,0x00,0x00,0x10,0x44,0x00,0x1a,0xae,0x03,0x00,0x58,0x8e,0x02,0x00,0x64,
+0x8e,0x04,0x00,0x58,0x00,0x00,0x00,0x00,0x10,0x82,0x00,0x05,0x00,0x00,0x00,0x00,
+0xae,0x00,0x00,0x4c,0xae,0x00,0x00,0x50,0xae,0x00,0x00,0x54,0xae,0x00,0x00,0x0c,
+0x8e,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x10,0x80,0x00,0x50,0x10,0x21,
+0x8c,0x42,0x00,0x68,0x00,0x00,0x00,0x00,0x10,0x54,0x00,0x06,0x00,0x00,0x00,0x00,
+0x00,0x40,0xf8,0x09,0x02,0x00,0x20,0x21,0x8e,0x04,0x00,0x58,0x8e,0x03,0x00,0x00,
+0x00,0x00,0x00,0x00,0xae,0x03,0x00,0x60,0x08,0x00,0x29,0x81,0xae,0x04,0x00,0x64,
+0x8e,0x02,0x00,0x64,0x00,0x00,0x00,0x00,0x14,0x62,0xff,0xe5,0x00,0x00,0x00,0x00,
+0x7a,0x02,0x0d,0x7c,0x8f,0xbf,0x00,0x24,0x8f,0xb4,0x00,0x20,0x7b,0xb2,0x00,0xfc,
+0x7b,0xb0,0x00,0xbc,0x00,0x43,0x10,0x26,0x00,0x02,0x10,0x2b,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x28,0x8e,0x04,0x00,0x04,0x34,0x63,0x00,0x06,0x90,0x62,0x00,0x00,
+0x00,0x04,0x42,0x02,0x00,0x48,0x10,0x23,0x24,0x44,0x00,0x40,0x28,0x83,0x00,0x00,
+0x24,0x42,0x00,0x7f,0x00,0x83,0x10,0x0a,0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,
+0x00,0x82,0x20,0x23,0x14,0x86,0xff,0xc4,0x00,0x00,0x00,0x00,0x8e,0x03,0x00,0x00,
+0x00,0x00,0x00,0x00,0x2c,0x62,0x00,0x03,0x14,0x40,0x00,0x05,0x24,0x02,0x00,0x0d,
+0x10,0x62,0x00,0x03,0x24,0x02,0x00,0x01,0x08,0x00,0x2a,0x04,0xa2,0x02,0x00,0x5c,
+0x08,0x00,0x2a,0x04,0xa2,0x00,0x00,0x5c,0x00,0x62,0x10,0x24,0x3c,0x03,0x28,0x38,
+0x14,0x43,0xff,0x93,0x24,0x02,0x00,0x01,0x08,0x00,0x29,0xdc,0x00,0x00,0x00,0x00,
+0x3c,0x02,0xb0,0x01,0x00,0xa2,0x40,0x21,0x00,0xa0,0x48,0x21,0x8d,0x05,0x00,0x00,
+0x24,0x02,0xc0,0x00,0x00,0x09,0x38,0xc2,0x00,0xa2,0x28,0x24,0x24,0xc2,0xff,0xff,
+0x00,0x07,0x3a,0x00,0x3c,0x0a,0xb0,0x06,0x3c,0x03,0x00,0x80,0x00,0xa6,0x28,0x25,
+0x2c,0x42,0x1f,0xff,0x00,0xe3,0x38,0x25,0x35,0x4a,0x80,0x18,0x10,0x40,0x00,0x0e,
+0xad,0x05,0x00,0x00,0xaf,0x89,0xbc,0x10,0x8d,0x02,0x00,0x00,0x00,0x00,0x00,0x00,
+0xaf,0x82,0xbc,0x18,0x8d,0x03,0x00,0x04,0xad,0x47,0x00,0x00,0xaf,0x83,0xbc,0x14,
+0xac,0x80,0x01,0xd0,0xac,0x80,0x01,0xc4,0xa0,0x80,0x01,0xc0,0xa0,0x80,0x01,0xc1,
+0xac,0x80,0x01,0xc8,0xac,0x80,0x01,0xcc,0x03,0xe0,0x00,0x08,0x00,0x00,0x00,0x00,
+0x27,0xbd,0xff,0xe8,0xaf,0xbf,0x00,0x10,0x8c,0x83,0x01,0xc4,0x00,0x80,0x38,0x21,
+0x90,0x84,0x01,0xc0,0x00,0x03,0x18,0x80,0x00,0x67,0x18,0x21,0x8c,0x65,0x00,0xa8,
+0x3c,0x02,0xb0,0x01,0x24,0x03,0x00,0x01,0x00,0xa2,0x10,0x21,0x8c,0x42,0x00,0x00,
+0x10,0x83,0x00,0x18,0x00,0x02,0x14,0x02,0x8c,0xe9,0x01,0xcc,0x8c,0xea,0x01,0xc8,
+0x30,0x46,0x00,0xff,0x01,0x2a,0x18,0x21,0x30,0x64,0x00,0xff,0x00,0x03,0x1a,0x02,
+0x24,0x62,0x00,0x01,0x14,0x80,0x00,0x02,0x30,0x48,0x00,0xff,0x30,0x68,0x00,0xff,
+0x90,0xe2,0x01,0xc1,0x00,0x00,0x00,0x00,0x00,0x48,0x10,0x23,0x00,0x02,0x12,0x00,
+0x00,0x49,0x10,0x21,0x00,0x4a,0x10,0x21,0x00,0x46,0x30,0x23,0x0c,0x00,0x2a,0x2c,
+0x00,0xe0,0x20,0x21,0x8f,0xbf,0x00,0x10,0x00,0x00,0x00,0x00,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x8c,0xe6,0x01,0xc8,0x08,0x00,0x2a,0x6b,0x00,0x00,0x00,0x00,
+0x27,0xbd,0xff,0xe8,0xaf,0xbf,0x00,0x14,0xaf,0xb0,0x00,0x10,0x8c,0x82,0x01,0xc4,
+0x90,0x87,0x01,0xc1,0x00,0x80,0x80,0x21,0x00,0x02,0x10,0x80,0x00,0x44,0x10,0x21,
+0x8c,0x48,0x00,0xa8,0x3c,0x02,0xb0,0x01,0x00,0x07,0x3a,0x00,0x01,0x02,0x10,0x21,
+0x8c,0x43,0x00,0x00,0x00,0xe5,0x38,0x21,0x00,0xe6,0x38,0x21,0x00,0x03,0x1c,0x02,
+0x30,0x63,0x00,0xff,0x00,0xe3,0x38,0x23,0x01,0x00,0x28,0x21,0x0c,0x00,0x2a,0x2c,
+0x00,0xe0,0x30,0x21,0x8e,0x02,0x01,0xa8,0x8f,0xbf,0x00,0x14,0x24,0x44,0x00,0x01,
+0x28,0x83,0x00,0x00,0x24,0x42,0x00,0x40,0x00,0x83,0x10,0x0a,0x00,0x02,0x11,0x83,
+0x00,0x02,0x11,0x80,0x00,0x82,0x20,0x23,0xae,0x04,0x01,0xa8,0x8f,0xb0,0x00,0x10,
+0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x18,0x3c,0x02,0xb0,0x03,0x3c,0x03,0x80,0x01,
+0x27,0xbd,0xff,0xe8,0x34,0x42,0x00,0x20,0x24,0x63,0xaa,0x58,0xaf,0xb0,0x00,0x10,
+0xaf,0xbf,0x00,0x14,0xac,0x43,0x00,0x00,0x90,0x82,0x01,0xd4,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x6a,0x00,0x80,0x80,0x21,0x90,0x82,0x01,0xc0,0x00,0x00,0x00,0x00,
+0x14,0x40,0x00,0x61,0x00,0x00,0x00,0x00,0x8c,0x83,0x01,0xa8,0x8c,0x82,0x01,0xac,
+0x00,0x00,0x00,0x00,0x10,0x62,0x00,0x22,0x00,0x00,0x28,0x21,0x93,0x82,0x81,0xf1,
+0x00,0x03,0x30,0x80,0x00,0xc4,0x18,0x21,0x24,0x04,0x00,0x01,0x8c,0x67,0x00,0xa8,
+0x10,0x44,0x00,0x20,0x3c,0x04,0xb0,0x01,0xaf,0x87,0xbc,0x10,0x00,0xe4,0x20,0x21,
+0x8c,0x86,0x00,0x00,0x00,0x07,0x18,0xc2,0x3c,0x02,0x00,0x80,0xaf,0x86,0xbc,0x18,
+0x8c,0x86,0x00,0x04,0x00,0x03,0x1a,0x00,0x3c,0x05,0xb0,0x06,0x00,0x62,0x18,0x25,
+0x34,0xa5,0x80,0x18,0xac,0xa3,0x00,0x00,0x8e,0x02,0x01,0xa8,0x8e,0x09,0x01,0xac,
+0xaf,0x86,0xbc,0x14,0x24,0x44,0x00,0x01,0x28,0x83,0x00,0x00,0x24,0x42,0x00,0x40,
+0x00,0x83,0x10,0x0a,0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,0x00,0x82,0x20,0x23,
+0x00,0x80,0x30,0x21,0xae,0x04,0x01,0xa8,0x00,0xc9,0x10,0x26,0x00,0x02,0x28,0x2b,
+0x8f,0xbf,0x00,0x14,0x8f,0xb0,0x00,0x10,0x00,0xa0,0x10,0x21,0x03,0xe0,0x00,0x08,
+0x27,0xbd,0x00,0x18,0x93,0x82,0x81,0xf0,0x00,0x00,0x00,0x00,0x2c,0x42,0x00,0x02,
+0x14,0x40,0xff,0xf7,0x00,0x00,0x28,0x21,0x3c,0x05,0xb0,0x01,0x00,0xe5,0x28,0x21,
+0x27,0x83,0x89,0x58,0x00,0xc3,0x18,0x21,0x8c,0xa6,0x00,0x00,0x8c,0x64,0x00,0x00,
+0x24,0x02,0xc0,0x00,0x00,0xc2,0x10,0x24,0x00,0x44,0x10,0x25,0xac,0xa2,0x00,0x00,
+0x8e,0x03,0x01,0xa8,0x27,0x84,0x8a,0x58,0x8c,0xa6,0x00,0x04,0x00,0x03,0x18,0x80,
+0x00,0x64,0x18,0x21,0x8c,0x62,0x00,0x00,0x3c,0x03,0x80,0x00,0x00,0x07,0x20,0xc2,
+0x00,0xc2,0x10,0x25,0x00,0x43,0x10,0x25,0xac,0xa2,0x00,0x04,0xaf,0x87,0xbc,0x10,
+0x8c,0xa6,0x00,0x00,0x3c,0x02,0x00,0x80,0x00,0x04,0x22,0x00,0x3c,0x03,0xb0,0x06,
+0xaf,0x86,0xbc,0x18,0x00,0x82,0x20,0x25,0x34,0x63,0x80,0x18,0x8c,0xa6,0x00,0x04,
+0xac,0x64,0x00,0x00,0x8e,0x02,0x01,0xa8,0xaf,0x86,0xbc,0x14,0x24,0x44,0x00,0x01,
+0x28,0x83,0x00,0x00,0x24,0x42,0x00,0x40,0x00,0x83,0x10,0x0a,0x93,0x83,0x81,0xf0,
+0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,0x00,0x82,0x20,0x23,0x24,0x63,0xff,0xff,
+0xae,0x04,0x01,0xa8,0xa3,0x83,0x81,0xf0,0x8e,0x04,0x01,0xac,0x8e,0x02,0x01,0xa8,
+0x08,0x00,0x2a,0xcb,0x00,0x44,0x10,0x26,0x0c,0x00,0x2a,0x4c,0x00,0x00,0x00,0x00,
+0x7a,0x02,0x0d,0x7c,0x08,0x00,0x2a,0xcb,0x00,0x43,0x10,0x26,0x8c,0x86,0x01,0xa8,
+0x8c,0x89,0x01,0xac,0x00,0x00,0x00,0x00,0x10,0xc9,0x00,0xb4,0x00,0xc0,0x68,0x21,
+0x00,0x06,0x10,0x80,0x27,0x83,0x89,0x58,0x00,0x43,0x18,0x21,0x00,0x44,0x10,0x21,
+0x8c,0x47,0x00,0xa8,0x94,0x65,0x00,0x02,0x3c,0x02,0xb0,0x01,0x00,0xe2,0x10,0x21,
+0x30,0xa5,0x3f,0xff,0xa4,0x45,0x00,0x2c,0x90,0x8a,0x01,0xc0,0x00,0x00,0x00,0x00,
+0x11,0x40,0x00,0x0c,0x00,0x07,0x32,0x02,0x8c,0x83,0x01,0xc4,0x90,0x85,0x01,0xc1,
+0x00,0x03,0x18,0x80,0x00,0x64,0x18,0x21,0x8c,0x62,0x00,0xa8,0x00,0x00,0x00,0x00,
+0x00,0x02,0x12,0x02,0x00,0x45,0x10,0x21,0x30,0x42,0x00,0x3f,0x14,0xc2,0xff,0xde,
+0x00,0x00,0x00,0x00,0x3c,0x04,0xb0,0x01,0x00,0xe4,0x40,0x21,0x8d,0x06,0x00,0x00,
+0x00,0x0d,0x28,0x80,0x00,0x06,0x14,0x02,0x30,0x4b,0x00,0xff,0x00,0xeb,0x70,0x21,
+0x01,0xc4,0x20,0x21,0x90,0x83,0x00,0x00,0x27,0x82,0x89,0x58,0x00,0xa2,0x28,0x21,
+0x8c,0xa4,0x00,0x00,0x00,0x03,0x18,0x82,0x30,0x63,0x00,0x03,0x2c,0x62,0x00,0x02,
+0x14,0x40,0x00,0x66,0x30,0x8c,0x3f,0xff,0x24,0x02,0x00,0x02,0x10,0x62,0x00,0x61,
+0x2d,0x82,0x08,0x00,0x15,0x40,0x00,0x36,0x01,0x6c,0x10,0x21,0x01,0x6c,0x18,0x21,
+0x30,0x62,0x00,0xff,0x00,0x02,0x10,0x2b,0x00,0x03,0x1a,0x02,0x3c,0x04,0xb0,0x01,
+0x00,0x62,0x18,0x21,0x00,0xe4,0x20,0x21,0x24,0x02,0x00,0x01,0xa2,0x03,0x01,0xc1,
+0xa0,0x82,0x00,0x08,0x8e,0x06,0x01,0xa8,0x3c,0x03,0xb0,0x00,0x34,0x63,0xff,0xf4,
+0x24,0xc5,0x00,0x01,0x28,0xa4,0x00,0x00,0x24,0xc2,0x00,0x40,0x00,0xa4,0x10,0x0a,
+0x01,0xc3,0x18,0x21,0xa4,0x6c,0x00,0x00,0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,
+0x92,0x04,0x01,0xc0,0x00,0xa2,0x38,0x23,0x3c,0x03,0xb0,0x03,0xae,0x0b,0x01,0xcc,
+0xae,0x0c,0x01,0xc8,0xae,0x06,0x01,0xc4,0xae,0x07,0x01,0xa8,0x34,0x63,0x01,0x08,
+0x92,0x05,0x01,0xd6,0x8c,0x66,0x00,0x00,0x24,0x84,0x00,0x01,0x30,0x82,0x00,0xff,
+0x00,0x45,0x10,0x2b,0xae,0x06,0x01,0xd0,0x10,0x40,0x00,0x07,0xa2,0x04,0x01,0xc0,
+0x92,0x02,0x01,0xd5,0x92,0x03,0x01,0xc1,0x24,0x42,0xff,0xfc,0x00,0x62,0x18,0x2a,
+0x14,0x60,0x00,0x08,0x00,0x00,0x00,0x00,0x02,0x00,0x20,0x21,0x0c,0x00,0x2a,0x4c,
+0x00,0x00,0x00,0x00,0x8e,0x09,0x01,0xac,0x8e,0x06,0x01,0xa8,0x08,0x00,0x2a,0xcb,
+0x00,0xc9,0x10,0x26,0x8e,0x09,0x01,0xac,0x08,0x00,0x2a,0xca,0x00,0xe0,0x30,0x21,
+0x30,0x43,0x00,0xff,0x92,0x07,0x01,0xc1,0x00,0x02,0x12,0x02,0x30,0x44,0x00,0xff,
+0x38,0x63,0x00,0x00,0x24,0x46,0x00,0x01,0x92,0x05,0x01,0xd5,0x00,0x83,0x30,0x0a,
+0x00,0xc7,0x18,0x21,0x00,0xa3,0x10,0x2a,0x14,0x40,0xff,0xeb,0x00,0x00,0x00,0x00,
+0x24,0xa2,0xff,0xfc,0x00,0x62,0x10,0x2a,0x10,0x40,0x00,0x07,0x01,0x80,0x28,0x21,
+0x92,0x03,0x01,0xd6,0x25,0x42,0x00,0x01,0x00,0x43,0x10,0x2a,0x14,0x40,0x00,0x07,
+0x25,0xa4,0x00,0x01,0x01,0x80,0x28,0x21,0x01,0x60,0x30,0x21,0x0c,0x00,0x2a,0x74,
+0x02,0x00,0x20,0x21,0x08,0x00,0x2b,0x6d,0x00,0x00,0x00,0x00,0x28,0x83,0x00,0x00,
+0x25,0xa2,0x00,0x40,0x00,0x83,0x10,0x0a,0x00,0x02,0x11,0x83,0x00,0x02,0x11,0x80,
+0x00,0x82,0x20,0x23,0x00,0xc7,0x18,0x21,0x25,0x42,0x00,0x01,0x00,0x80,0x30,0x21,
+0xa2,0x03,0x01,0xc1,0xae,0x0b,0x01,0xcc,0xae,0x0c,0x01,0xc8,0x08,0x00,0x2a,0xc9,
+0xa2,0x02,0x01,0xc0,0x14,0x40,0xff,0x9f,0x00,0x00,0x00,0x00,0x15,0x40,0x00,0x14,
+0x24,0x02,0xc0,0x00,0x00,0xc2,0x10,0x24,0x00,0x4c,0x10,0x25,0xad,0x02,0x00,0x00,
+0xaf,0x87,0xbc,0x10,0x8d,0x05,0x00,0x00,0x00,0x07,0x18,0xc2,0x3c,0x02,0x00,0x80,
+0x00,0x03,0x1a,0x00,0x3c,0x04,0xb0,0x06,0xaf,0x85,0xbc,0x18,0x00,0x62,0x18,0x25,
+0x34,0x84,0x80,0x18,0x8d,0x05,0x00,0x04,0xac,0x83,0x00,0x00,0x8e,0x02,0x01,0xa8,
+0x8e,0x09,0x01,0xac,0xaf,0x85,0xbc,0x14,0x08,0x00,0x2a,0xc2,0x24,0x44,0x00,0x01,
+0x01,0x6c,0x10,0x21,0x30,0x45,0x00,0xff,0x92,0x04,0x01,0xc1,0x00,0x02,0x12,0x02,
+0x30,0x46,0x00,0xff,0x38,0xa5,0x00,0x00,0x24,0x42,0x00,0x01,0x92,0x03,0x01,0xd5,
+0x00,0xc5,0x10,0x0a,0x00,0x82,0x20,0x21,0x00,0x64,0x18,0x2a,0x10,0x60,0xff,0xca,
+0x01,0x80,0x28,0x21,0x08,0x00,0x2b,0x6b,0x02,0x00,0x20,0x21,0x90,0x87,0x01,0xc0,
+0x00,0x00,0x00,0x00,0x10,0xe0,0xff,0x06,0x00,0x00,0x28,0x21,0x3c,0x02,0xb0,0x03,
+0x34,0x42,0x01,0x08,0x94,0x83,0x01,0xd8,0x8c,0x88,0x01,0xd0,0x8c,0x45,0x00,0x00,
+0x01,0x03,0x18,0x21,0x00,0xa3,0x10,0x2b,0x10,0x40,0x00,0x0b,0x2c,0xe2,0x00,0x02,
+0x00,0xa8,0x10,0x2b,0x10,0x40,0xfe,0xf9,0x00,0xc9,0x10,0x26,0x3c,0x02,0x80,0x00,
+0x00,0x62,0x18,0x21,0x00,0xa2,0x10,0x21,0x00,0x43,0x10,0x2b,0x14,0x40,0xfe,0xf3,
+0x00,0xc9,0x10,0x26,0x2c,0xe2,0x00,0x02,0x10,0x40,0xff,0x90,0x00,0x00,0x00,0x00,
+0x24,0x02,0x00,0x01,0x14,0xe2,0xfe,0xed,0x00,0xc9,0x10,0x26,0x3c,0x03,0xb0,0x06,
+0x34,0x63,0x80,0x18,0x8c,0x62,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x17,0x02,
+0x14,0x40,0xfe,0xe5,0x00,0x00,0x00,0x00,0x08,0x00,0x2b,0x6b,0x00,0x00,0x00,0x00,
+0x3c,0x04,0xb0,0x03,0x3c,0x06,0xb0,0x07,0x3c,0x02,0x80,0x01,0x34,0xc6,0x00,0x18,
+0x34,0x84,0x00,0x20,0x24,0x42,0xaf,0xa0,0x24,0x03,0xff,0x83,0xac,0x82,0x00,0x00,
+0xa0,0xc3,0x00,0x00,0x90,0xc4,0x00,0x00,0x27,0xbd,0xff,0xf8,0x3c,0x03,0xb0,0x07,
+0x24,0x02,0xff,0x82,0xa3,0xa4,0x00,0x00,0xa0,0x62,0x00,0x00,0x90,0x64,0x00,0x00,
+0x3c,0x02,0xb0,0x07,0x34,0x42,0x00,0x08,0xa3,0xa4,0x00,0x01,0xa0,0x40,0x00,0x00,
+0x90,0x43,0x00,0x00,0x24,0x02,0x00,0x03,0x3c,0x05,0xb0,0x07,0xa3,0xa3,0x00,0x00,
+0xa0,0xc2,0x00,0x00,0x90,0xc4,0x00,0x00,0x34,0xa5,0x00,0x10,0x24,0x02,0x00,0x06,
+0x3c,0x03,0xb0,0x07,0xa3,0xa4,0x00,0x00,0x34,0x63,0x00,0x38,0xa0,0xa2,0x00,0x00,
+0x90,0x64,0x00,0x00,0x3c,0x02,0xb0,0x07,0x34,0x42,0x00,0x20,0xa3,0xa4,0x00,0x00,
+0xa0,0xa0,0x00,0x00,0x90,0xa3,0x00,0x00,0xaf,0x82,0xbf,0x20,0xa3,0xa3,0x00,0x00,
+0xa0,0x40,0x00,0x00,0x90,0x43,0x00,0x00,0x03,0xe0,0x00,0x08,0x27,0xbd,0x00,0x08,
+};
+
+u8 rtl8190_fwdata_array[] ={
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x10,0x00,0x08,0x00,
+0x02,0xe9,0x01,0x74,0x02,0xab,0x01,0xc7,0x01,0x55,0x00,0xe4,0x00,0xab,0x00,0x72,
+0x00,0x55,0x00,0x4c,0x00,0x4c,0x00,0x4c,0x00,0x4c,0x00,0x4c,0x02,0x76,0x01,0x3b,
+0x00,0xd2,0x00,0x9e,0x00,0x69,0x00,0x4f,0x00,0x46,0x00,0x3f,0x01,0x3b,0x00,0x9e,
+0x00,0x69,0x00,0x4f,0x00,0x35,0x00,0x27,0x00,0x23,0x00,0x20,0x01,0x2f,0x00,0x98,
+0x00,0x65,0x00,0x4c,0x00,0x33,0x00,0x26,0x00,0x22,0x00,0x1e,0x00,0x98,0x00,0x4c,
+0x00,0x33,0x00,0x26,0x00,0x19,0x00,0x13,0x00,0x11,0x00,0x0f,0x02,0x39,0x01,0x1c,
+0x00,0xbd,0x00,0x8e,0x00,0x5f,0x00,0x47,0x00,0x3f,0x00,0x39,0x01,0x1c,0x00,0x8e,
+0x00,0x5f,0x00,0x47,0x00,0x2f,0x00,0x23,0x00,0x20,0x00,0x1c,0x01,0x11,0x00,0x89,
+0x00,0x5b,0x00,0x44,0x00,0x2e,0x00,0x22,0x00,0x1e,0x00,0x1b,0x00,0x89,0x00,0x44,
+0x00,0x2e,0x00,0x22,0x00,0x17,0x00,0x11,0x00,0x0f,0x00,0x0e,0x02,0xab,0x02,0xab,
+0x02,0x66,0x02,0x66,0x07,0x06,0x06,0x06,0x05,0x06,0x07,0x08,0x04,0x06,0x07,0x08,
+0x09,0x0a,0x0b,0x0b,0x49,0x6e,0x74,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x54,0x4c,
+0x42,0x4d,0x4f,0x44,0x00,0x00,0x00,0x00,0x54,0x4c,0x42,0x4c,0x5f,0x64,0x61,0x74,
+0x61,0x00,0x54,0x4c,0x42,0x53,0x00,0x00,0x00,0x00,0x00,0x00,0x41,0x64,0x45,0x4c,
+0x5f,0x64,0x61,0x74,0x61,0x00,0x41,0x64,0x45,0x53,0x00,0x00,0x00,0x00,0x00,0x00,
+0x45,0x78,0x63,0x43,0x6f,0x64,0x65,0x36,0x00,0x00,0x45,0x78,0x63,0x43,0x6f,0x64,
+0x65,0x37,0x00,0x00,0x53,0x79,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x42,0x70,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x52,0x49,0x00,0x00,0x00,0x00,0x00,0x00,
+0x00,0x00,0x43,0x70,0x55,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4f,0x76,0x00,0x00,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x01,0x0b,0x53,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x2c,
+0x00,0x00,0x00,0x58,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x48,0x00,0x00,0x00,0x60,
+0x00,0x00,0x00,0x90,0x00,0x00,0x00,0xc0,0x00,0x00,0x01,0x20,0x00,0x00,0x01,0x80,
+0x00,0x00,0x01,0xb0,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x68,0x00,0x00,0x00,0x9c,
+0x00,0x00,0x00,0xd0,0x00,0x00,0x01,0x38,0x00,0x00,0x01,0xa0,0x00,0x00,0x01,0xd4,
+0x00,0x00,0x02,0x08,0x00,0x00,0x00,0x68,0x00,0x00,0x00,0xd0,0x00,0x00,0x01,0x38,
+0x00,0x00,0x01,0xa0,0x00,0x00,0x02,0x6f,0x00,0x00,0x03,0x40,0x00,0x00,0x03,0xa8,
+0x00,0x00,0x04,0x10,0x01,0x01,0x01,0x02,0x01,0x01,0x02,0x02,0x03,0x03,0x04,0x04,
+0x01,0x01,0x02,0x02,0x03,0x03,0x04,0x04,0x02,0x03,0x03,0x04,0x05,0x06,0x07,0x08,
+0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x07,0x74,0x80,0x00,0x07,0x88,
+0x80,0x00,0x07,0x88,0x80,0x00,0x07,0x78,0x80,0x00,0x07,0x78,0x80,0x00,0x07,0x9c,
+0x80,0x00,0x53,0xc4,0x80,0x00,0x54,0x24,0x80,0x00,0x54,0x38,0x80,0x00,0x54,0x5c,
+0x80,0x00,0x54,0x68,0x80,0x00,0x54,0xa8,0x80,0x00,0x56,0xa8,0x80,0x00,0x57,0xec,
+0x80,0x00,0x58,0x14,0x80,0x00,0x59,0x0c,0x80,0x00,0x59,0xc4,0x80,0x00,0x5a,0x6c,
+0x80,0x00,0x5a,0xe0,0x80,0x00,0x5b,0xec,0x80,0x00,0x5c,0x24,0x80,0x00,0x5c,0x38,
+0x80,0x00,0x5c,0x4c,0x80,0x00,0x5d,0x40,0x80,0x00,0x5d,0x80,0x80,0x00,0x5e,0x34,
+0x80,0x00,0x5e,0x5c,0x80,0x00,0x56,0x68,0x80,0x00,0x5e,0x78,0x80,0x00,0x88,0xf8,
+0x80,0x00,0x88,0xf8,0x80,0x00,0x88,0xf8,0x80,0x00,0x89,0x2c,0x80,0x00,0x89,0x6c,
+0x80,0x00,0x89,0xa4,0x80,0x00,0x89,0xd4,0x80,0x00,0x8a,0x10,0x80,0x00,0x8a,0x50,
+0x80,0x00,0x8a,0xb8,0x80,0x00,0x8a,0xcc,0x80,0x00,0x8b,0x08,0x80,0x00,0x8b,0x10,
+0x80,0x00,0x8b,0x4c,0x80,0x00,0x8b,0x60,0x80,0x00,0x8b,0x68,0x80,0x00,0x8b,0x70,
+0x80,0x00,0x8b,0x70,0x80,0x00,0x8b,0x70,0x80,0x00,0x8b,0x70,0x80,0x00,0x8a,0x90,
+0x80,0x00,0x8b,0xa0,0x80,0x00,0x8b,0xb4,0x80,0x00,0x88,0x54,0x80,0x00,0x8e,0xc8,
+0x80,0x00,0x8e,0xc8,0x80,0x00,0x8e,0xc8,0x80,0x00,0x8e,0xfc,0x80,0x00,0x8f,0x3c,
+0x80,0x00,0x8f,0x74,0x80,0x00,0x8f,0xa4,0x80,0x00,0x8f,0xe0,0x80,0x00,0x90,0x20,
+0x80,0x00,0x90,0x88,0x80,0x00,0x90,0x9c,0x80,0x00,0x90,0xd8,0x80,0x00,0x90,0xe0,
+0x80,0x00,0x91,0x1c,0x80,0x00,0x91,0x30,0x80,0x00,0x91,0x38,0x80,0x00,0x91,0x40,
+0x80,0x00,0x91,0x40,0x80,0x00,0x91,0x40,0x80,0x00,0x91,0x40,0x80,0x00,0x90,0x60,
+0x80,0x00,0x91,0x70,0x80,0x00,0x91,0x84,0x80,0x00,0x8d,0x00,};
+
+u32 Rtl8192UsbPHY_REGArray[] = {
+0x0, };
+
+u32 Rtl8192UsbPHY_REG_1T2RArray[] = {
+0x800,0x00000000,
+0x804,0x00000001,
+0x808,0x0000fc00,
+0x80c,0x0000001c,
+0x810,0x801010aa,
+0x814,0x008514d0,
+0x818,0x00000040,
+0x81c,0x00000000,
+0x820,0x00000004,
+0x824,0x00690000,
+0x828,0x00000004,
+0x82c,0x00e90000,
+0x830,0x00000004,
+0x834,0x00690000,
+0x838,0x00000004,
+0x83c,0x00e90000,
+0x840,0x00000000,
+0x844,0x00000000,
+0x848,0x00000000,
+0x84c,0x00000000,
+0x850,0x00000000,
+0x854,0x00000000,
+0x858,0x65a965a9,
+0x85c,0x65a965a9,
+0x860,0x001f0010,
+0x864,0x007f0010,
+0x868,0x001f0010,
+0x86c,0x007f0010,
+0x870,0x0f100f70,
+0x874,0x0f100f70,
+0x878,0x00000000,
+0x87c,0x00000000,
+0x880,0x6870e36c,
+0x884,0xe3573600,
+0x888,0x4260c340,
+0x88c,0x0000ff00,
+0x890,0x00000000,
+0x894,0xfffffffe,
+0x898,0x4c42382f,
+0x89c,0x00656056,
+0x8b0,0x00000000,
+0x8e0,0x00000000,
+0x8e4,0x00000000,
+0x900,0x00000000,
+0x904,0x00000023,
+0x908,0x00000000,
+0x90c,0x31121311,
+0xa00,0x00d0c7d8,
+0xa04,0x811f0008,
+0xa08,0x80cd8300,
+0xa0c,0x2e62740f,
+0xa10,0x95009b78,
+0xa14,0x11145008,
+0xa18,0x00881117,
+0xa1c,0x89140fa0,
+0xa20,0x1a1b0000,
+0xa24,0x090e1317,
+0xa28,0x00000204,
+0xa2c,0x00000000,
+0xc00,0x00000040,
+0xc04,0x00005433,
+0xc08,0x000000e4,
+0xc0c,0x6c6c6c6c,
+0xc10,0x08800000,
+0xc14,0x40000100,
+0xc18,0x08000000,
+0xc1c,0x40000100,
+0xc20,0x08000000,
+0xc24,0x40000100,
+0xc28,0x08000000,
+0xc2c,0x40000100,
+0xc30,0x6de9ac44,
+0xc34,0x465c52cd,
+0xc38,0x497f5994,
+0xc3c,0x0a969764,
+0xc40,0x1f7c403f,
+0xc44,0x000100b7,
+0xc48,0xec020000,
+0xc4c,0x00000300,
+0xc50,0x69543420,
+0xc54,0x433c0094,
+0xc58,0x69543420,
+0xc5c,0x433c0094,
+0xc60,0x69543420,
+0xc64,0x433c0094,
+0xc68,0x69543420,
+0xc6c,0x433c0094,
+0xc70,0x2c7f000d,
+0xc74,0x0186175b,
+0xc78,0x0000001f,
+0xc7c,0x00b91612,
+0xc80,0x40000100,
+0xc84,0x20000000,
+0xc88,0x40000100,
+0xc8c,0x20200000,
+0xc90,0x40000100,
+0xc94,0x00000000,
+0xc98,0x40000100,
+0xc9c,0x00000000,
+0xca0,0x00492492,
+0xca4,0x00000000,
+0xca8,0x00000000,
+0xcac,0x00000000,
+0xcb0,0x00000000,
+0xcb4,0x00000000,
+0xcb8,0x00000000,
+0xcbc,0x00492492,
+0xcc0,0x00000000,
+0xcc4,0x00000000,
+0xcc8,0x00000000,
+0xccc,0x00000000,
+0xcd0,0x00000000,
+0xcd4,0x00000000,
+0xcd8,0x64b22427,
+0xcdc,0x00766932,
+0xce0,0x00222222,
+0xd00,0x00000750,
+0xd04,0x00000403,
+0xd08,0x0000907f,
+0xd0c,0x00000001,
+0xd10,0xa0633333,
+0xd14,0x33333c63,
+0xd18,0x6a8f5b6b,
+0xd1c,0x00000000,
+0xd20,0x00000000,
+0xd24,0x00000000,
+0xd28,0x00000000,
+0xd2c,0xcc979975,
+0xd30,0x00000000,
+0xd34,0x00000000,
+0xd38,0x00000000,
+0xd3c,0x00027293,
+0xd40,0x00000000,
+0xd44,0x00000000,
+0xd48,0x00000000,
+0xd4c,0x00000000,
+0xd50,0x6437140a,
+0xd54,0x024dbd02,
+0xd58,0x00000000,
+0xd5c,0x04032064,
+0xe00,0x161a1a1a,
+0xe04,0x12121416,
+0xe08,0x00001800,
+0xe0c,0x00000000,
+0xe10,0x161a1a1a,
+0xe14,0x12121416,
+0xe18,0x161a1a1a,
+0xe1c,0x12121416,
+};
+
+u32 Rtl8192UsbRadioA_Array[] = {
+0x019,0x00000003,
+0x000,0x000000bf,
+0x001,0x00000ee0,
+0x002,0x0000004c,
+0x003,0x000007f1,
+0x004,0x00000975,
+0x005,0x00000c58,
+0x006,0x00000ae6,
+0x007,0x000000ca,
+0x008,0x00000e1c,
+0x009,0x000007f0,
+0x00a,0x000009d0,
+0x00b,0x000001ba,
+0x00c,0x00000240,
+0x00e,0x00000020,
+0x00f,0x00000990,
+0x012,0x00000806,
+0x014,0x000005ab,
+0x015,0x00000f80,
+0x016,0x00000020,
+0x017,0x00000597,
+0x018,0x0000050a,
+0x01a,0x00000f80,
+0x01b,0x00000f5e,
+0x01c,0x00000008,
+0x01d,0x00000607,
+0x01e,0x000006cc,
+0x01f,0x00000000,
+0x020,0x000001a5,
+0x01f,0x00000001,
+0x020,0x00000165,
+0x01f,0x00000002,
+0x020,0x000000c6,
+0x01f,0x00000003,
+0x020,0x00000086,
+0x01f,0x00000004,
+0x020,0x00000046,
+0x01f,0x00000005,
+0x020,0x000001e6,
+0x01f,0x00000006,
+0x020,0x000001a6,
+0x01f,0x00000007,
+0x020,0x00000166,
+0x01f,0x00000008,
+0x020,0x000000c7,
+0x01f,0x00000009,
+0x020,0x00000087,
+0x01f,0x0000000a,
+0x020,0x000000f7,
+0x01f,0x0000000b,
+0x020,0x000000d7,
+0x01f,0x0000000c,
+0x020,0x000000b7,
+0x01f,0x0000000d,
+0x020,0x00000097,
+0x01f,0x0000000e,
+0x020,0x00000077,
+0x01f,0x0000000f,
+0x020,0x00000057,
+0x01f,0x00000010,
+0x020,0x00000037,
+0x01f,0x00000011,
+0x020,0x000000fb,
+0x01f,0x00000012,
+0x020,0x000000db,
+0x01f,0x00000013,
+0x020,0x000000bb,
+0x01f,0x00000014,
+0x020,0x000000ff,
+0x01f,0x00000015,
+0x020,0x000000e3,
+0x01f,0x00000016,
+0x020,0x000000c3,
+0x01f,0x00000017,
+0x020,0x000000a3,
+0x01f,0x00000018,
+0x020,0x00000083,
+0x01f,0x00000019,
+0x020,0x00000063,
+0x01f,0x0000001a,
+0x020,0x00000043,
+0x01f,0x0000001b,
+0x020,0x00000023,
+0x01f,0x0000001c,
+0x020,0x00000003,
+0x01f,0x0000001d,
+0x020,0x000001e3,
+0x01f,0x0000001e,
+0x020,0x000001c3,
+0x01f,0x0000001f,
+0x020,0x000001a3,
+0x01f,0x00000020,
+0x020,0x00000183,
+0x01f,0x00000021,
+0x020,0x00000163,
+0x01f,0x00000022,
+0x020,0x00000143,
+0x01f,0x00000023,
+0x020,0x00000123,
+0x01f,0x00000024,
+0x020,0x00000103,
+0x023,0x00000203,
+0x024,0x00000200,
+0x00b,0x000001ba,
+0x02c,0x000003d7,
+0x02d,0x00000ff0,
+0x000,0x00000037,
+0x004,0x00000160,
+0x007,0x00000080,
+0x002,0x0000088d,
+0x0fe,0x00000000,
+0x0fe,0x00000000,
+0x016,0x00000200,
+0x016,0x00000380,
+0x016,0x00000020,
+0x016,0x000001a0,
+0x000,0x000000bf,
+0x00d,0x0000001f,
+0x00d,0x00000c9f,
+0x002,0x0000004d,
+0x000,0x00000cbf,
+0x004,0x00000975,
+0x007,0x00000700,
+};
+
+u32 Rtl8192UsbRadioB_Array[] = {
+0x019,0x00000003,
+0x000,0x000000bf,
+0x001,0x000006e0,
+0x002,0x0000004c,
+0x003,0x000007f1,
+0x004,0x00000975,
+0x005,0x00000c58,
+0x006,0x00000ae6,
+0x007,0x000000ca,
+0x008,0x00000e1c,
+0x000,0x000000b7,
+0x00a,0x00000850,
+0x000,0x000000bf,
+0x00b,0x000001ba,
+0x00c,0x00000240,
+0x00e,0x00000020,
+0x015,0x00000f80,
+0x016,0x00000020,
+0x017,0x00000597,
+0x018,0x0000050a,
+0x01a,0x00000e00,
+0x01b,0x00000f5e,
+0x01d,0x00000607,
+0x01e,0x000006cc,
+0x00b,0x000001ba,
+0x023,0x00000203,
+0x024,0x00000200,
+0x000,0x00000037,
+0x004,0x00000160,
+0x016,0x00000200,
+0x016,0x00000380,
+0x016,0x00000020,
+0x016,0x000001a0,
+0x00d,0x00000ccc,
+0x000,0x000000bf,
+0x002,0x0000004d,
+0x000,0x00000cbf,
+0x004,0x00000975,
+0x007,0x00000700,
+};
+
+u32 Rtl8192UsbRadioC_Array[] = {
+0x0, };
+
+u32 Rtl8192UsbRadioD_Array[] = {
+0x0, };
+
+u32 Rtl8192UsbMACPHY_Array[] = {
+0x03c,0xffff0000,0x00000f0f,
+0x340,0xffffffff,0x161a1a1a,
+0x344,0xffffffff,0x12121416,
+0x348,0x0000ffff,0x00001818,
+0x12c,0xffffffff,0x04000802,
+0x318,0x00000fff,0x00000100,
+};
+
+u32 Rtl8192UsbMACPHY_Array_PG[] = {
+0x03c,0xffff0000,0x00000f0f,
+0xe00,0xffffffff,0x06090909,
+0xe04,0xffffffff,0x00030306,
+0xe08,0x0000ff00,0x00000000,
+0xe10,0xffffffff,0x0a0c0d0f,
+0xe14,0xffffffff,0x06070809,
+0xe18,0xffffffff,0x0a0c0d0f,
+0xe1c,0xffffffff,0x06070809,
+0x12c,0xffffffff,0x04000802,
+0x318,0x00000fff,0x00000800,
+};
+
+u32 Rtl8192UsbAGCTAB_Array[] = {
+0xc78,0x7d000001,
+0xc78,0x7d010001,
+0xc78,0x7d020001,
+0xc78,0x7d030001,
+0xc78,0x7d040001,
+0xc78,0x7d050001,
+0xc78,0x7c060001,
+0xc78,0x7b070001,
+0xc78,0x7a080001,
+0xc78,0x79090001,
+0xc78,0x780a0001,
+0xc78,0x770b0001,
+0xc78,0x760c0001,
+0xc78,0x750d0001,
+0xc78,0x740e0001,
+0xc78,0x730f0001,
+0xc78,0x72100001,
+0xc78,0x71110001,
+0xc78,0x70120001,
+0xc78,0x6f130001,
+0xc78,0x6e140001,
+0xc78,0x6d150001,
+0xc78,0x6c160001,
+0xc78,0x6b170001,
+0xc78,0x6a180001,
+0xc78,0x69190001,
+0xc78,0x681a0001,
+0xc78,0x671b0001,
+0xc78,0x661c0001,
+0xc78,0x651d0001,
+0xc78,0x641e0001,
+0xc78,0x491f0001,
+0xc78,0x48200001,
+0xc78,0x47210001,
+0xc78,0x46220001,
+0xc78,0x45230001,
+0xc78,0x44240001,
+0xc78,0x43250001,
+0xc78,0x28260001,
+0xc78,0x27270001,
+0xc78,0x26280001,
+0xc78,0x25290001,
+0xc78,0x242a0001,
+0xc78,0x232b0001,
+0xc78,0x222c0001,
+0xc78,0x212d0001,
+0xc78,0x202e0001,
+0xc78,0x0a2f0001,
+0xc78,0x08300001,
+0xc78,0x06310001,
+0xc78,0x05320001,
+0xc78,0x04330001,
+0xc78,0x03340001,
+0xc78,0x02350001,
+0xc78,0x01360001,
+0xc78,0x00370001,
+0xc78,0x00380001,
+0xc78,0x00390001,
+0xc78,0x003a0001,
+0xc78,0x003b0001,
+0xc78,0x003c0001,
+0xc78,0x003d0001,
+0xc78,0x003e0001,
+0xc78,0x003f0001,
+0xc78,0x7d400001,
+0xc78,0x7d410001,
+0xc78,0x7d420001,
+0xc78,0x7d430001,
+0xc78,0x7d440001,
+0xc78,0x7d450001,
+0xc78,0x7c460001,
+0xc78,0x7b470001,
+0xc78,0x7a480001,
+0xc78,0x79490001,
+0xc78,0x784a0001,
+0xc78,0x774b0001,
+0xc78,0x764c0001,
+0xc78,0x754d0001,
+0xc78,0x744e0001,
+0xc78,0x734f0001,
+0xc78,0x72500001,
+0xc78,0x71510001,
+0xc78,0x70520001,
+0xc78,0x6f530001,
+0xc78,0x6e540001,
+0xc78,0x6d550001,
+0xc78,0x6c560001,
+0xc78,0x6b570001,
+0xc78,0x6a580001,
+0xc78,0x69590001,
+0xc78,0x685a0001,
+0xc78,0x675b0001,
+0xc78,0x665c0001,
+0xc78,0x655d0001,
+0xc78,0x645e0001,
+0xc78,0x495f0001,
+0xc78,0x48600001,
+0xc78,0x47610001,
+0xc78,0x46620001,
+0xc78,0x45630001,
+0xc78,0x44640001,
+0xc78,0x43650001,
+0xc78,0x28660001,
+0xc78,0x27670001,
+0xc78,0x26680001,
+0xc78,0x25690001,
+0xc78,0x246a0001,
+0xc78,0x236b0001,
+0xc78,0x226c0001,
+0xc78,0x216d0001,
+0xc78,0x206e0001,
+0xc78,0x0a6f0001,
+0xc78,0x08700001,
+0xc78,0x06710001,
+0xc78,0x05720001,
+0xc78,0x04730001,
+0xc78,0x03740001,
+0xc78,0x02750001,
+0xc78,0x01760001,
+0xc78,0x00770001,
+0xc78,0x00780001,
+0xc78,0x00790001,
+0xc78,0x007a0001,
+0xc78,0x007b0001,
+0xc78,0x007c0001,
+0xc78,0x007d0001,
+0xc78,0x007e0001,
+0xc78,0x007f0001,
+0xc78,0x2e00001e,
+0xc78,0x2e01001e,
+0xc78,0x2e02001e,
+0xc78,0x2e03001e,
+0xc78,0x2e04001e,
+0xc78,0x2e05001e,
+0xc78,0x3006001e,
+0xc78,0x3407001e,
+0xc78,0x3908001e,
+0xc78,0x3c09001e,
+0xc78,0x3f0a001e,
+0xc78,0x420b001e,
+0xc78,0x440c001e,
+0xc78,0x450d001e,
+0xc78,0x460e001e,
+0xc78,0x460f001e,
+0xc78,0x4710001e,
+0xc78,0x4811001e,
+0xc78,0x4912001e,
+0xc78,0x4a13001e,
+0xc78,0x4b14001e,
+0xc78,0x4b15001e,
+0xc78,0x4c16001e,
+0xc78,0x4d17001e,
+0xc78,0x4e18001e,
+0xc78,0x4f19001e,
+0xc78,0x4f1a001e,
+0xc78,0x501b001e,
+0xc78,0x511c001e,
+0xc78,0x521d001e,
+0xc78,0x521e001e,
+0xc78,0x531f001e,
+0xc78,0x5320001e,
+0xc78,0x5421001e,
+0xc78,0x5522001e,
+0xc78,0x5523001e,
+0xc78,0x5624001e,
+0xc78,0x5725001e,
+0xc78,0x5726001e,
+0xc78,0x5827001e,
+0xc78,0x5828001e,
+0xc78,0x5929001e,
+0xc78,0x592a001e,
+0xc78,0x5a2b001e,
+0xc78,0x5b2c001e,
+0xc78,0x5c2d001e,
+0xc78,0x5c2e001e,
+0xc78,0x5d2f001e,
+0xc78,0x5e30001e,
+0xc78,0x5f31001e,
+0xc78,0x6032001e,
+0xc78,0x6033001e,
+0xc78,0x6134001e,
+0xc78,0x6235001e,
+0xc78,0x6336001e,
+0xc78,0x6437001e,
+0xc78,0x6438001e,
+0xc78,0x6539001e,
+0xc78,0x663a001e,
+0xc78,0x673b001e,
+0xc78,0x673c001e,
+0xc78,0x683d001e,
+0xc78,0x693e001e,
+0xc78,0x6a3f001e,
+};
diff --git a/drivers/staging/rtl8192su/r819xU_firmware_img.h b/drivers/staging/rtl8192su/r819xU_firmware_img.h
new file mode 100644
index 0000000..d9d9515
--- /dev/null
+++ b/drivers/staging/rtl8192su/r819xU_firmware_img.h
@@ -0,0 +1,35 @@
+#ifndef IMG_H
+#define IMG_H
+
+#define BOOT_ARR_LEN 344
+#define MAIN_ARR_LEN 45136
+#define DATA_ARR_LEN 796
+#define MACPHY_Array_PGLength 30
+#define PHY_REG_1T2RArrayLength 296
+#define AGCTAB_ArrayLength 384
+#define MACPHY_ArrayLength 18
+
+#define RadioA_ArrayLength 246
+#define RadioB_ArrayLength 78
+#define RadioC_ArrayLength 1
+#define RadioD_ArrayLength 1
+#define PHY_REGArrayLength 1
+
+
+extern u8 rtl8190_fwboot_array[BOOT_ARR_LEN];
+extern u8 rtl8190_fwmain_array[MAIN_ARR_LEN];
+extern u8 rtl8190_fwdata_array[DATA_ARR_LEN];
+
+extern u32 Rtl8192UsbPHY_REGArray[];
+extern u32 Rtl8192UsbPHY_REG_1T2RArray[];
+extern u32 Rtl8192UsbRadioA_Array[];
+extern u32 Rtl8192UsbRadioB_Array[];
+extern u32 Rtl8192UsbRadioC_Array[];
+extern u32 Rtl8192UsbRadioD_Array[];
+extern u32 Rtl8192UsbMACPHY_Array[];
+extern u32 Rtl8192UsbMACPHY_Array_PG[];
+extern u32 Rtl8192UsbAGCTAB_Array[];
+
+
+
+#endif
diff --git a/drivers/staging/rtl8192su/r819xU_phy.c b/drivers/staging/rtl8192su/r819xU_phy.c
new file mode 100644
index 0000000..00497d3
--- /dev/null
+++ b/drivers/staging/rtl8192su/r819xU_phy.c
@@ -0,0 +1,1826 @@
+#include "r8192U.h"
+#include "r8192U_hw.h"
+#include "r819xU_phy.h"
+#include "r819xU_phyreg.h"
+#include "r8190_rtl8256.h"
+#include "r8192U_dm.h"
+#include "r819xU_firmware_img.h"
+
+#ifdef ENABLE_DOT11D
+#include "dot11d.h"
+#endif
+static u32 RF_CHANNEL_TABLE_ZEBRA[] = {
+	0,
+	0x085c, //2412 1
+	0x08dc, //2417 2
+	0x095c, //2422 3
+	0x09dc, //2427 4
+	0x0a5c, //2432 5
+	0x0adc, //2437 6
+	0x0b5c, //2442 7
+	0x0bdc, //2447 8
+	0x0c5c, //2452 9
+	0x0cdc, //2457 10
+	0x0d5c, //2462 11
+	0x0ddc, //2467 12
+	0x0e5c, //2472 13
+	0x0f72, //2484
+};
+
+
+#define rtl819XPHY_REG_1T2RArray Rtl8192UsbPHY_REG_1T2RArray
+#define rtl819XMACPHY_Array_PG Rtl8192UsbMACPHY_Array_PG
+#define rtl819XMACPHY_Array Rtl8192UsbMACPHY_Array
+#define rtl819XRadioA_Array  Rtl8192UsbRadioA_Array
+#define rtl819XRadioB_Array Rtl8192UsbRadioB_Array
+#define rtl819XRadioC_Array Rtl8192UsbRadioC_Array
+#define rtl819XRadioD_Array Rtl8192UsbRadioD_Array
+#define rtl819XAGCTAB_Array Rtl8192UsbAGCTAB_Array
+
+/******************************************************************************
+ *function:  This function read BB parameters from Header file we gen,
+ *	     and do register read/write
+ *   input:  u32	dwBitMask  //taget bit pos in the addr to be modified
+ *  output:  none
+ *  return:  u32	return the shift bit bit position of the mask
+ * ****************************************************************************/
+u32 rtl8192_CalculateBitShift(u32 dwBitMask)
+{
+	u32 i;
+	for (i=0; i<=31; i++)
+	{
+		if (((dwBitMask>>i)&0x1) == 1)
+			break;
+	}
+	return i;
+}
+/******************************************************************************
+ *function:  This function check different RF type to execute legal judgement. If RF Path is illegal, we will return false.
+ *   input:  none
+ *  output:  none
+ *  return:  0(illegal, false), 1(legal,true)
+ * ***************************************************************************/
+u8 rtl8192_phy_CheckIsLegalRFPath(struct net_device* dev, u32 eRFPath)
+{
+	u8 ret = 1;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	if (priv->rf_type == RF_2T4R)
+		ret = 0;
+	else if (priv->rf_type == RF_1T2R)
+	{
+		if (eRFPath == RF90_PATH_A || eRFPath == RF90_PATH_B)
+			ret = 1;
+		else if (eRFPath == RF90_PATH_C || eRFPath == RF90_PATH_D)
+			ret = 0;
+	}
+	return ret;
+}
+/******************************************************************************
+ *function:  This function set specific bits to BB register
+ *   input:  net_device dev
+ *           u32	dwRegAddr  //target addr to be modified
+ *           u32	dwBitMask  //taget bit pos in the addr to be modified
+ *           u32	dwData     //value to be write
+ *  output:  none
+ *  return:  none
+ *  notice:
+ * ****************************************************************************/
+void rtl8192_setBBreg(struct net_device* dev, u32 dwRegAddr, u32 dwBitMask, u32 dwData)
+{
+
+	u32 OriginalValue, BitShift, NewValue;
+
+	if(dwBitMask!= bMaskDWord)
+	{//if not "double word" write
+		OriginalValue = read_nic_dword(dev, dwRegAddr);
+		BitShift = rtl8192_CalculateBitShift(dwBitMask);
+            	NewValue = (((OriginalValue) & (~dwBitMask)) | (dwData << BitShift));
+		write_nic_dword(dev, dwRegAddr, NewValue);
+	}else
+		write_nic_dword(dev, dwRegAddr, dwData);
+	return;
+}
+/******************************************************************************
+ *function:  This function reads specific bits from BB register
+ *   input:  net_device dev
+ *           u32	dwRegAddr  //target addr to be readback
+ *           u32	dwBitMask  //taget bit pos in the addr to be readback
+ *  output:  none
+ *  return:  u32	Data	//the readback register value
+ *  notice:
+ * ****************************************************************************/
+u32 rtl8192_QueryBBReg(struct net_device* dev, u32 dwRegAddr, u32 dwBitMask)
+{
+	u32 Ret = 0, OriginalValue, BitShift;
+
+	OriginalValue = read_nic_dword(dev, dwRegAddr);
+	BitShift = rtl8192_CalculateBitShift(dwBitMask);
+	Ret =(OriginalValue & dwBitMask) >> BitShift;
+
+	return (Ret);
+}
+static  u32 phy_FwRFSerialRead( struct net_device* dev, RF90_RADIO_PATH_E       eRFPath, u32 Offset  );
+
+static void phy_FwRFSerialWrite( struct net_device* dev, RF90_RADIO_PATH_E       eRFPath, u32  Offset, u32  Data);
+
+/******************************************************************************
+ *function:  This function read register from RF chip
+ *   input:  net_device dev
+ *   	     RF90_RADIO_PATH_E eRFPath //radio path of A/B/C/D
+ *           u32	Offset     //target address to be read
+ *  output:  none
+ *  return:  u32 	readback value
+ *  notice:  There are three types of serial operations:(1) Software serial write.(2)Hardware LSSI-Low Speed Serial Interface.(3)Hardware HSSI-High speed serial write. Driver here need to implement (1) and (2)---need more spec for this information.
+ * ****************************************************************************/
+u32 rtl8192_phy_RFSerialRead(struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 Offset)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 ret = 0;
+	u32 NewOffset = 0;
+	BB_REGISTER_DEFINITION_T* pPhyReg = &priv->PHYRegDef[eRFPath];
+	rtl8192_setBBreg(dev, pPhyReg->rfLSSIReadBack, bLSSIReadBackData, 0);
+	//make sure RF register offset is correct
+	Offset &= 0x3f;
+
+	//switch page for 8256 RF IC
+	if (priv->rf_chip == RF_8256)
+	{
+		if (Offset >= 31)
+		{
+			priv->RfReg0Value[eRFPath] |= 0x140;
+			//Switch to Reg_Mode2 for Reg 31-45
+			rtl8192_setBBreg(dev, pPhyReg->rf3wireOffset, bMaskDWord, (priv->RfReg0Value[eRFPath]<<16) );
+			//modify offset
+			NewOffset = Offset -30;
+		}
+		else if (Offset >= 16)
+		{
+			priv->RfReg0Value[eRFPath] |= 0x100;
+			priv->RfReg0Value[eRFPath] &= (~0x40);
+			//Switch to Reg_Mode 1 for Reg16-30
+			rtl8192_setBBreg(dev, pPhyReg->rf3wireOffset, bMaskDWord, (priv->RfReg0Value[eRFPath]<<16) );
+
+			NewOffset = Offset - 15;
+		}
+		else
+			NewOffset = Offset;
+	}
+	else
+	{
+		RT_TRACE((COMP_PHY|COMP_ERR), "check RF type here, need to be 8256\n");
+		NewOffset = Offset;
+	}
+	//put desired read addr to LSSI control Register
+	rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2, bLSSIReadAddress, NewOffset);
+	//Issue a posedge trigger
+	//
+	rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2,  bLSSIReadEdge, 0x0);
+	rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2,  bLSSIReadEdge, 0x1);
+
+
+	// TODO: we should not delay such a  long time. Ask help from SD3
+	msleep(1);
+
+	ret = rtl8192_QueryBBReg(dev, pPhyReg->rfLSSIReadBack, bLSSIReadBackData);
+
+
+	// Switch back to Reg_Mode0;
+	if(priv->rf_chip == RF_8256)
+	{
+		priv->RfReg0Value[eRFPath] &= 0xebf;
+
+		rtl8192_setBBreg(
+			dev,
+			pPhyReg->rf3wireOffset,
+			bMaskDWord,
+			(priv->RfReg0Value[eRFPath] << 16));
+	}
+
+	return ret;
+
+}
+
+/******************************************************************************
+ *function:  This function write data to RF register
+ *   input:  net_device dev
+ *   	     RF90_RADIO_PATH_E eRFPath //radio path of A/B/C/D
+ *           u32	Offset     //target address to be written
+ *           u32	Data	//The new register data to be written
+ *  output:  none
+ *  return:  none
+ *  notice:  For RF8256 only.
+  ===========================================================
+ *Reg Mode	RegCTL[1]	RegCTL[0]		Note
+ *		(Reg00[12])	(Reg00[10])
+ *===========================================================
+ *Reg_Mode0	0		x			Reg 0 ~15(0x0 ~ 0xf)
+ *------------------------------------------------------------------
+ *Reg_Mode1	1		0			Reg 16 ~30(0x1 ~ 0xf)
+ *------------------------------------------------------------------
+ * Reg_Mode2	1		1			Reg 31 ~ 45(0x1 ~ 0xf)
+ *------------------------------------------------------------------
+ * ****************************************************************************/
+void rtl8192_phy_RFSerialWrite(struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 Offset, u32 Data)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 DataAndAddr = 0, NewOffset = 0;
+	BB_REGISTER_DEFINITION_T	*pPhyReg = &priv->PHYRegDef[eRFPath];
+
+	Offset &= 0x3f;
+	//spin_lock_irqsave(&priv->rf_lock, flags);
+//	down(&priv->rf_sem);
+	if (priv->rf_chip == RF_8256)
+	{
+
+		if (Offset >= 31)
+		{
+			priv->RfReg0Value[eRFPath] |= 0x140;
+			rtl8192_setBBreg(dev, pPhyReg->rf3wireOffset, bMaskDWord, (priv->RfReg0Value[eRFPath] << 16));
+			NewOffset = Offset - 30;
+		}
+		else if (Offset >= 16)
+		{
+			priv->RfReg0Value[eRFPath] |= 0x100;
+			priv->RfReg0Value[eRFPath] &= (~0x40);
+			rtl8192_setBBreg(dev, pPhyReg->rf3wireOffset, bMaskDWord, (priv->RfReg0Value[eRFPath]<<16));
+			NewOffset = Offset - 15;
+		}
+		else
+			NewOffset = Offset;
+	}
+	else
+	{
+		RT_TRACE((COMP_PHY|COMP_ERR), "check RF type here, need to be 8256\n");
+		NewOffset = Offset;
+	}
+
+	// Put write addr in [5:0]  and write data in [31:16]
+	DataAndAddr = (Data<<16) | (NewOffset&0x3f);
+
+	// Write Operation
+	rtl8192_setBBreg(dev, pPhyReg->rf3wireOffset, bMaskDWord, DataAndAddr);
+
+
+	if(Offset==0x0)
+		priv->RfReg0Value[eRFPath] = Data;
+
+	// Switch back to Reg_Mode0;
+ 	if(priv->rf_chip == RF_8256)
+	{
+		if(Offset != 0)
+		{
+			priv->RfReg0Value[eRFPath] &= 0xebf;
+			rtl8192_setBBreg(
+				dev,
+				pPhyReg->rf3wireOffset,
+				bMaskDWord,
+				(priv->RfReg0Value[eRFPath] << 16));
+		}
+	}
+	//spin_unlock_irqrestore(&priv->rf_lock, flags);
+//	up(&priv->rf_sem);
+	return;
+}
+
+/******************************************************************************
+ *function:  This function set specific bits to RF register
+ *   input:  net_device dev
+ *   	     RF90_RADIO_PATH_E eRFPath //radio path of A/B/C/D
+ *           u32	RegAddr  //target addr to be modified
+ *           u32	BitMask  //taget bit pos in the addr to be modified
+ *           u32	Data     //value to be write
+ *  output:  none
+ *  return:  none
+ *  notice:
+ * ****************************************************************************/
+void rtl8192_phy_SetRFReg(struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 RegAddr, u32 BitMask, u32 Data)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32 Original_Value, BitShift, New_Value;
+//	u8	time = 0;
+
+	if (!rtl8192_phy_CheckIsLegalRFPath(dev, eRFPath))
+		return;
+
+	if (priv->Rf_Mode == RF_OP_By_FW)
+	{
+		if (BitMask != bMask12Bits) // RF data is 12 bits only
+		{
+			Original_Value = phy_FwRFSerialRead(dev, eRFPath, RegAddr);
+			BitShift =  rtl8192_CalculateBitShift(BitMask);
+			New_Value = ((Original_Value) & (~BitMask)) | (Data<< BitShift);
+
+			phy_FwRFSerialWrite(dev, eRFPath, RegAddr, New_Value);
+		}else
+			phy_FwRFSerialWrite(dev, eRFPath, RegAddr, Data);
+
+		udelay(200);
+
+	}
+	else
+	{
+		if (BitMask != bMask12Bits) // RF data is 12 bits only
+   	        {
+			Original_Value = rtl8192_phy_RFSerialRead(dev, eRFPath, RegAddr);
+      			BitShift =  rtl8192_CalculateBitShift(BitMask);
+      			New_Value = (((Original_Value) & (~BitMask)) | (Data<< BitShift));
+
+			rtl8192_phy_RFSerialWrite(dev, eRFPath, RegAddr, New_Value);
+	        }else
+			rtl8192_phy_RFSerialWrite(dev, eRFPath, RegAddr, Data);
+	}
+	return;
+}
+
+/******************************************************************************
+ *function:  This function reads specific bits from RF register
+ *   input:  net_device dev
+ *           u32	RegAddr  //target addr to be readback
+ *           u32	BitMask  //taget bit pos in the addr to be readback
+ *  output:  none
+ *  return:  u32	Data	//the readback register value
+ *  notice:
+ * ****************************************************************************/
+u32 rtl8192_phy_QueryRFReg(struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 RegAddr, u32 BitMask)
+{
+	u32 Original_Value, Readback_Value, BitShift;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+
+	if (!rtl8192_phy_CheckIsLegalRFPath(dev, eRFPath))
+		return 0;
+	if (priv->Rf_Mode == RF_OP_By_FW)
+	{
+		Original_Value = phy_FwRFSerialRead(dev, eRFPath, RegAddr);
+		BitShift =  rtl8192_CalculateBitShift(BitMask);
+		Readback_Value = (Original_Value & BitMask) >> BitShift;
+		udelay(200);
+		return (Readback_Value);
+	}
+	else
+	{
+		Original_Value = rtl8192_phy_RFSerialRead(dev, eRFPath, RegAddr);
+   		BitShift =  rtl8192_CalculateBitShift(BitMask);
+   		Readback_Value = (Original_Value & BitMask) >> BitShift;
+		return (Readback_Value);
+	}
+}
+/******************************************************************************
+ *function:  We support firmware to execute RF-R/W.
+ *   input:  dev
+ *  output:  none
+ *  return:  none
+ *  notice:
+ * ***************************************************************************/
+static	u32
+phy_FwRFSerialRead(
+	struct net_device* dev,
+	RF90_RADIO_PATH_E	eRFPath,
+	u32				Offset	)
+{
+	u32		retValue = 0;
+	u32		Data = 0;
+	u8		time = 0;
+	//DbgPrint("FW RF CTRL\n\r");
+	/* 2007/11/02 MH Firmware RF Write control. By Francis' suggestion, we can
+	   not execute the scheme in the initial step. Otherwise, RF-R/W will waste
+	   much time. This is only for site survey. */
+	// 1. Read operation need not insert data. bit 0-11
+	//Data &= bMask12Bits;
+	// 2. Write RF register address. Bit 12-19
+	Data |= ((Offset&0xFF)<<12);
+	// 3. Write RF path.  bit 20-21
+	Data |= ((eRFPath&0x3)<<20);
+	// 4. Set RF read indicator. bit 22=0
+	//Data |= 0x00000;
+	// 5. Trigger Fw to operate the command. bit 31
+	Data |= 0x80000000;
+	// 6. We can not execute read operation if bit 31 is 1.
+	while (read_nic_dword(dev, QPNR)&0x80000000)
+	{
+		// If FW can not finish RF-R/W for more than ?? times. We must reset FW.
+		if (time++ < 100)
+		{
+			//DbgPrint("FW not finish RF-R Time=%d\n\r", time);
+			udelay(10);
+		}
+		else
+			break;
+	}
+	// 7. Execute read operation.
+	write_nic_dword(dev, QPNR, Data);
+	// 8. Check if firmawre send back RF content.
+	while (read_nic_dword(dev, QPNR)&0x80000000)
+	{
+		// If FW can not finish RF-R/W for more than ?? times. We must reset FW.
+		if (time++ < 100)
+		{
+			//DbgPrint("FW not finish RF-W Time=%d\n\r", time);
+			udelay(10);
+		}
+		else
+			return	(0);
+	}
+	retValue = read_nic_dword(dev, RF_DATA);
+
+	return	(retValue);
+
+}	/* phy_FwRFSerialRead */
+
+/******************************************************************************
+ *function:  We support firmware to execute RF-R/W.
+ *   input:  dev
+ *  output:  none
+ *  return:  none
+ *  notice:
+ * ***************************************************************************/
+static void
+phy_FwRFSerialWrite(
+		struct net_device* dev,
+		RF90_RADIO_PATH_E	eRFPath,
+		u32				Offset,
+		u32				Data	)
+{
+	u8	time = 0;
+
+	//DbgPrint("N FW RF CTRL RF-%d OF%02x DATA=%03x\n\r", eRFPath, Offset, Data);
+	/* 2007/11/02 MH Firmware RF Write control. By Francis' suggestion, we can
+	   not execute the scheme in the initial step. Otherwise, RF-R/W will waste
+	   much time. This is only for site survey. */
+
+	// 1. Set driver write bit and 12 bit data. bit 0-11
+	//Data &= bMask12Bits;	// Done by uper layer.
+	// 2. Write RF register address. bit 12-19
+	Data |= ((Offset&0xFF)<<12);
+	// 3. Write RF path.  bit 20-21
+	Data |= ((eRFPath&0x3)<<20);
+	// 4. Set RF write indicator. bit 22=1
+	Data |= 0x400000;
+	// 5. Trigger Fw to operate the command. bit 31=1
+	Data |= 0x80000000;
+
+	// 6. Write operation. We can not write if bit 31 is 1.
+	while (read_nic_dword(dev, QPNR)&0x80000000)
+	{
+		// If FW can not finish RF-R/W for more than ?? times. We must reset FW.
+		if (time++ < 100)
+		{
+			//DbgPrint("FW not finish RF-W Time=%d\n\r", time);
+			udelay(10);
+		}
+		else
+			break;
+	}
+	// 7. No matter check bit. We always force the write. Because FW will
+	//    not accept the command.
+	write_nic_dword(dev, QPNR, Data);
+	/* 2007/11/02 MH Acoording to test, we must delay 20us to wait firmware
+	   to finish RF write operation. */
+	/* 2008/01/17 MH We support delay in firmware side now. */
+	//delay_us(20);
+
+}	/* phy_FwRFSerialWrite */
+
+
+/******************************************************************************
+ *function:  This function read BB parameters from Header file we gen,
+ *	     and do register read/write
+ *   input:  dev
+ *  output:  none
+ *  return:  none
+ *  notice:  BB parameters may change all the time, so please make
+ *           sure it has been synced with the newest.
+ * ***************************************************************************/
+void rtl8192_phy_configmac(struct net_device* dev)
+{
+	u32 dwArrayLen = 0, i;
+	u32* pdwArray = NULL;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	if(priv->btxpowerdata_readfromEEPORM)
+	{
+		RT_TRACE(COMP_PHY, "Rtl819XMACPHY_Array_PG\n");
+		dwArrayLen = MACPHY_Array_PGLength;
+		pdwArray = rtl819XMACPHY_Array_PG;
+
+	}
+	else
+	{
+		RT_TRACE(COMP_PHY, "Rtl819XMACPHY_Array\n");
+		dwArrayLen = MACPHY_ArrayLength;
+		pdwArray = rtl819XMACPHY_Array;
+	}
+	for(i = 0; i<dwArrayLen; i=i+3){
+		if(pdwArray[i] == 0x318)
+		{
+			pdwArray[i+2] = 0x00000800;
+			//DbgPrint("ptrArray[i], ptrArray[i+1], ptrArray[i+2] = %x, %x, %x\n",
+			//	ptrArray[i], ptrArray[i+1], ptrArray[i+2]);
+		}
+
+		RT_TRACE(COMP_DBG, "The Rtl8190MACPHY_Array[0] is %x Rtl8190MACPHY_Array[1] is %x Rtl8190MACPHY_Array[2] is %x\n",
+				pdwArray[i], pdwArray[i+1], pdwArray[i+2]);
+		rtl8192_setBBreg(dev, pdwArray[i], pdwArray[i+1], pdwArray[i+2]);
+	}
+	return;
+
+}
+
+/******************************************************************************
+ *function:  This function do dirty work
+ *   input:  dev
+ *  output:  none
+ *  return:  none
+ *  notice:  BB parameters may change all the time, so please make
+ *           sure it has been synced with the newest.
+ * ***************************************************************************/
+
+void rtl8192_phyConfigBB(struct net_device* dev, u8 ConfigType)
+{
+	u32 i;
+
+#ifdef TO_DO_LIST
+	u32 *rtl8192PhyRegArrayTable = NULL, *rtl8192AgcTabArrayTable = NULL;
+	if(Adapter->bInHctTest)
+	{
+		PHY_REGArrayLen = PHY_REGArrayLengthDTM;
+		AGCTAB_ArrayLen = AGCTAB_ArrayLengthDTM;
+		Rtl8190PHY_REGArray_Table = Rtl819XPHY_REGArrayDTM;
+		Rtl8190AGCTAB_Array_Table = Rtl819XAGCTAB_ArrayDTM;
+	}
+#endif
+	if (ConfigType == BaseBand_Config_PHY_REG)
+	{
+		for (i=0; i<PHY_REG_1T2RArrayLength; i+=2)
+		{
+			rtl8192_setBBreg(dev, rtl819XPHY_REG_1T2RArray[i], bMaskDWord, rtl819XPHY_REG_1T2RArray[i+1]);
+			RT_TRACE(COMP_DBG, "i: %x, The Rtl819xUsbPHY_REGArray[0] is %x Rtl819xUsbPHY_REGArray[1] is %x \n",i, rtl819XPHY_REG_1T2RArray[i], rtl819XPHY_REG_1T2RArray[i+1]);
+		}
+	}
+	else if (ConfigType == BaseBand_Config_AGC_TAB)
+	{
+		for (i=0; i<AGCTAB_ArrayLength; i+=2)
+		{
+			rtl8192_setBBreg(dev, rtl819XAGCTAB_Array[i], bMaskDWord, rtl819XAGCTAB_Array[i+1]);
+			RT_TRACE(COMP_DBG, "i:%x, The rtl819XAGCTAB_Array[0] is %x rtl819XAGCTAB_Array[1] is %x \n",i, rtl819XAGCTAB_Array[i], rtl819XAGCTAB_Array[i+1]);
+		}
+	}
+	return;
+
+
+}
+/******************************************************************************
+ *function:  This function initialize Register definition offset for Radio Path
+ *	     A/B/C/D
+ *   input:  net_device dev
+ *  output:  none
+ *  return:  none
+ *  notice:  Initialization value here is constant and it should never be changed
+ * ***************************************************************************/
+void rtl8192_InitBBRFRegDef(struct net_device* dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+// RF Interface Sowrtware Control
+	priv->PHYRegDef[RF90_PATH_A].rfintfs = rFPGA0_XAB_RFInterfaceSW; // 16 LSBs if read 32-bit from 0x870
+	priv->PHYRegDef[RF90_PATH_B].rfintfs = rFPGA0_XAB_RFInterfaceSW; // 16 MSBs if read 32-bit from 0x870 (16-bit for 0x872)
+	priv->PHYRegDef[RF90_PATH_C].rfintfs = rFPGA0_XCD_RFInterfaceSW;// 16 LSBs if read 32-bit from 0x874
+	priv->PHYRegDef[RF90_PATH_D].rfintfs = rFPGA0_XCD_RFInterfaceSW;// 16 MSBs if read 32-bit from 0x874 (16-bit for 0x876)
+
+	// RF Interface Readback Value
+	priv->PHYRegDef[RF90_PATH_A].rfintfi = rFPGA0_XAB_RFInterfaceRB; // 16 LSBs if read 32-bit from 0x8E0
+	priv->PHYRegDef[RF90_PATH_B].rfintfi = rFPGA0_XAB_RFInterfaceRB;// 16 MSBs if read 32-bit from 0x8E0 (16-bit for 0x8E2)
+	priv->PHYRegDef[RF90_PATH_C].rfintfi = rFPGA0_XCD_RFInterfaceRB;// 16 LSBs if read 32-bit from 0x8E4
+	priv->PHYRegDef[RF90_PATH_D].rfintfi = rFPGA0_XCD_RFInterfaceRB;// 16 MSBs if read 32-bit from 0x8E4 (16-bit for 0x8E6)
+
+	// RF Interface Output (and Enable)
+	priv->PHYRegDef[RF90_PATH_A].rfintfo = rFPGA0_XA_RFInterfaceOE; // 16 LSBs if read 32-bit from 0x860
+	priv->PHYRegDef[RF90_PATH_B].rfintfo = rFPGA0_XB_RFInterfaceOE; // 16 LSBs if read 32-bit from 0x864
+	priv->PHYRegDef[RF90_PATH_C].rfintfo = rFPGA0_XC_RFInterfaceOE;// 16 LSBs if read 32-bit from 0x868
+	priv->PHYRegDef[RF90_PATH_D].rfintfo = rFPGA0_XD_RFInterfaceOE;// 16 LSBs if read 32-bit from 0x86C
+
+	// RF Interface (Output and)  Enable
+	priv->PHYRegDef[RF90_PATH_A].rfintfe = rFPGA0_XA_RFInterfaceOE; // 16 MSBs if read 32-bit from 0x860 (16-bit for 0x862)
+	priv->PHYRegDef[RF90_PATH_B].rfintfe = rFPGA0_XB_RFInterfaceOE; // 16 MSBs if read 32-bit from 0x864 (16-bit for 0x866)
+	priv->PHYRegDef[RF90_PATH_C].rfintfe = rFPGA0_XC_RFInterfaceOE;// 16 MSBs if read 32-bit from 0x86A (16-bit for 0x86A)
+	priv->PHYRegDef[RF90_PATH_D].rfintfe = rFPGA0_XD_RFInterfaceOE;// 16 MSBs if read 32-bit from 0x86C (16-bit for 0x86E)
+
+	//Addr of LSSI. Wirte RF register by driver
+	priv->PHYRegDef[RF90_PATH_A].rf3wireOffset = rFPGA0_XA_LSSIParameter; //LSSI Parameter
+	priv->PHYRegDef[RF90_PATH_B].rf3wireOffset = rFPGA0_XB_LSSIParameter;
+	priv->PHYRegDef[RF90_PATH_C].rf3wireOffset = rFPGA0_XC_LSSIParameter;
+	priv->PHYRegDef[RF90_PATH_D].rf3wireOffset = rFPGA0_XD_LSSIParameter;
+
+	// RF parameter
+	priv->PHYRegDef[RF90_PATH_A].rfLSSI_Select = rFPGA0_XAB_RFParameter;  //BB Band Select
+	priv->PHYRegDef[RF90_PATH_B].rfLSSI_Select = rFPGA0_XAB_RFParameter;
+	priv->PHYRegDef[RF90_PATH_C].rfLSSI_Select = rFPGA0_XCD_RFParameter;
+	priv->PHYRegDef[RF90_PATH_D].rfLSSI_Select = rFPGA0_XCD_RFParameter;
+
+	// Tx AGC Gain Stage (same for all path. Should we remove this?)
+	priv->PHYRegDef[RF90_PATH_A].rfTxGainStage = rFPGA0_TxGainStage; //Tx gain stage
+	priv->PHYRegDef[RF90_PATH_B].rfTxGainStage = rFPGA0_TxGainStage; //Tx gain stage
+	priv->PHYRegDef[RF90_PATH_C].rfTxGainStage = rFPGA0_TxGainStage; //Tx gain stage
+	priv->PHYRegDef[RF90_PATH_D].rfTxGainStage = rFPGA0_TxGainStage; //Tx gain stage
+
+	// Tranceiver A~D HSSI Parameter-1
+	priv->PHYRegDef[RF90_PATH_A].rfHSSIPara1 = rFPGA0_XA_HSSIParameter1;  //wire control parameter1
+	priv->PHYRegDef[RF90_PATH_B].rfHSSIPara1 = rFPGA0_XB_HSSIParameter1;  //wire control parameter1
+	priv->PHYRegDef[RF90_PATH_C].rfHSSIPara1 = rFPGA0_XC_HSSIParameter1;  //wire control parameter1
+	priv->PHYRegDef[RF90_PATH_D].rfHSSIPara1 = rFPGA0_XD_HSSIParameter1;  //wire control parameter1
+
+	// Tranceiver A~D HSSI Parameter-2
+	priv->PHYRegDef[RF90_PATH_A].rfHSSIPara2 = rFPGA0_XA_HSSIParameter2;  //wire control parameter2
+	priv->PHYRegDef[RF90_PATH_B].rfHSSIPara2 = rFPGA0_XB_HSSIParameter2;  //wire control parameter2
+	priv->PHYRegDef[RF90_PATH_C].rfHSSIPara2 = rFPGA0_XC_HSSIParameter2;  //wire control parameter2
+	priv->PHYRegDef[RF90_PATH_D].rfHSSIPara2 = rFPGA0_XD_HSSIParameter2;  //wire control parameter1
+
+	// RF switch Control
+	priv->PHYRegDef[RF90_PATH_A].rfSwitchControl = rFPGA0_XAB_SwitchControl; //TR/Ant switch control
+	priv->PHYRegDef[RF90_PATH_B].rfSwitchControl = rFPGA0_XAB_SwitchControl;
+	priv->PHYRegDef[RF90_PATH_C].rfSwitchControl = rFPGA0_XCD_SwitchControl;
+	priv->PHYRegDef[RF90_PATH_D].rfSwitchControl = rFPGA0_XCD_SwitchControl;
+
+	// AGC control 1
+	priv->PHYRegDef[RF90_PATH_A].rfAGCControl1 = rOFDM0_XAAGCCore1;
+	priv->PHYRegDef[RF90_PATH_B].rfAGCControl1 = rOFDM0_XBAGCCore1;
+	priv->PHYRegDef[RF90_PATH_C].rfAGCControl1 = rOFDM0_XCAGCCore1;
+	priv->PHYRegDef[RF90_PATH_D].rfAGCControl1 = rOFDM0_XDAGCCore1;
+
+	// AGC control 2
+	priv->PHYRegDef[RF90_PATH_A].rfAGCControl2 = rOFDM0_XAAGCCore2;
+	priv->PHYRegDef[RF90_PATH_B].rfAGCControl2 = rOFDM0_XBAGCCore2;
+	priv->PHYRegDef[RF90_PATH_C].rfAGCControl2 = rOFDM0_XCAGCCore2;
+	priv->PHYRegDef[RF90_PATH_D].rfAGCControl2 = rOFDM0_XDAGCCore2;
+
+	// RX AFE control 1
+	priv->PHYRegDef[RF90_PATH_A].rfRxIQImbalance = rOFDM0_XARxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_B].rfRxIQImbalance = rOFDM0_XBRxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_C].rfRxIQImbalance = rOFDM0_XCRxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_D].rfRxIQImbalance = rOFDM0_XDRxIQImbalance;
+
+	// RX AFE control 1
+	priv->PHYRegDef[RF90_PATH_A].rfRxAFE = rOFDM0_XARxAFE;
+	priv->PHYRegDef[RF90_PATH_B].rfRxAFE = rOFDM0_XBRxAFE;
+	priv->PHYRegDef[RF90_PATH_C].rfRxAFE = rOFDM0_XCRxAFE;
+	priv->PHYRegDef[RF90_PATH_D].rfRxAFE = rOFDM0_XDRxAFE;
+
+	// Tx AFE control 1
+	priv->PHYRegDef[RF90_PATH_A].rfTxIQImbalance = rOFDM0_XATxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_B].rfTxIQImbalance = rOFDM0_XBTxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_C].rfTxIQImbalance = rOFDM0_XCTxIQImbalance;
+	priv->PHYRegDef[RF90_PATH_D].rfTxIQImbalance = rOFDM0_XDTxIQImbalance;
+
+	// Tx AFE control 2
+	priv->PHYRegDef[RF90_PATH_A].rfTxAFE = rOFDM0_XATxAFE;
+	priv->PHYRegDef[RF90_PATH_B].rfTxAFE = rOFDM0_XBTxAFE;
+	priv->PHYRegDef[RF90_PATH_C].rfTxAFE = rOFDM0_XCTxAFE;
+	priv->PHYRegDef[RF90_PATH_D].rfTxAFE = rOFDM0_XDTxAFE;
+
+	// Tranceiver LSSI Readback
+	priv->PHYRegDef[RF90_PATH_A].rfLSSIReadBack = rFPGA0_XA_LSSIReadBack;
+	priv->PHYRegDef[RF90_PATH_B].rfLSSIReadBack = rFPGA0_XB_LSSIReadBack;
+	priv->PHYRegDef[RF90_PATH_C].rfLSSIReadBack = rFPGA0_XC_LSSIReadBack;
+	priv->PHYRegDef[RF90_PATH_D].rfLSSIReadBack = rFPGA0_XD_LSSIReadBack;
+
+}
+/******************************************************************************
+ *function:  This function is to write register and then readback to make sure whether BB and RF is OK
+ *   input:  net_device dev
+ *   	     HW90_BLOCK_E CheckBlock
+ *   	     RF90_RADIO_PATH_E eRFPath  //only used when checkblock is HW90_BLOCK_RF
+ *  output:  none
+ *  return:  return whether BB and RF is ok(0:OK; 1:Fail)
+ *  notice:  This function may be removed in the ASIC
+ * ***************************************************************************/
+u8 rtl8192_phy_checkBBAndRF(struct net_device* dev, HW90_BLOCK_E CheckBlock, RF90_RADIO_PATH_E eRFPath)
+{
+//	struct r8192_priv *priv = ieee80211_priv(dev);
+//	BB_REGISTER_DEFINITION_T *pPhyReg = &priv->PHYRegDef[eRFPath];
+	u8 ret = 0;
+	u32 i, CheckTimes = 4, dwRegRead = 0;
+	u32 WriteAddr[4];
+	u32 WriteData[] = {0xfffff027, 0xaa55a02f, 0x00000027, 0x55aa502f};
+	// Initialize register address offset to be checked
+	WriteAddr[HW90_BLOCK_MAC] = 0x100;
+	WriteAddr[HW90_BLOCK_PHY0] = 0x900;
+	WriteAddr[HW90_BLOCK_PHY1] = 0x800;
+	WriteAddr[HW90_BLOCK_RF] = 0x3;
+	RT_TRACE(COMP_PHY, "=======>%s(), CheckBlock:%d\n", __FUNCTION__, CheckBlock);
+	for(i=0 ; i < CheckTimes ; i++)
+	{
+
+		//
+		// Write Data to register and readback
+		//
+		switch(CheckBlock)
+		{
+		case HW90_BLOCK_MAC:
+			RT_TRACE(COMP_ERR, "PHY_CheckBBRFOK(): Never Write 0x100 here!");
+			break;
+
+		case HW90_BLOCK_PHY0:
+		case HW90_BLOCK_PHY1:
+			write_nic_dword(dev, WriteAddr[CheckBlock], WriteData[i]);
+			dwRegRead = read_nic_dword(dev, WriteAddr[CheckBlock]);
+			break;
+
+		case HW90_BLOCK_RF:
+			WriteData[i] &= 0xfff;
+			rtl8192_phy_SetRFReg(dev, eRFPath, WriteAddr[HW90_BLOCK_RF], bMask12Bits, WriteData[i]);
+			// TODO: we should not delay for such a long time. Ask SD3
+			msleep(1);
+			dwRegRead = rtl8192_phy_QueryRFReg(dev, eRFPath, WriteAddr[HW90_BLOCK_RF], bMask12Bits);
+			msleep(1);
+			break;
+
+		default:
+			ret = 1;
+			break;
+		}
+
+
+		//
+		// Check whether readback data is correct
+		//
+		if(dwRegRead != WriteData[i])
+		{
+			RT_TRACE((COMP_PHY|COMP_ERR), "====>error=====dwRegRead: %x, WriteData: %x \n", dwRegRead, WriteData[i]);
+			ret = 1;
+			break;
+		}
+	}
+
+	return ret;
+}
+
+
+/******************************************************************************
+ *function:  This function initialize BB&RF
+ *   input:  net_device dev
+ *  output:  none
+ *  return:  none
+ *  notice:  Initialization value may change all the time, so please make
+ *           sure it has been synced with the newest.
+ * ***************************************************************************/
+void rtl8192_BB_Config_ParaFile(struct net_device* dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8 bRegValue = 0, eCheckItem = 0, rtStatus = 0;
+	u32 dwRegValue = 0;
+	/**************************************
+	//<1>Initialize BaseBand
+	**************************************/
+
+	/*--set BB Global Reset--*/
+	bRegValue = read_nic_byte(dev, BB_GLOBAL_RESET);
+	write_nic_byte(dev, BB_GLOBAL_RESET,(bRegValue|BB_GLOBAL_RESET_BIT));
+	mdelay(50);
+	/*---set BB reset Active---*/
+	dwRegValue = read_nic_dword(dev, CPU_GEN);
+	write_nic_dword(dev, CPU_GEN, (dwRegValue&(~CPU_GEN_BB_RST)));
+
+	/*----Ckeck FPGAPHY0 and PHY1 board is OK----*/
+	// TODO: this function should be removed on ASIC , Emily 2007.2.2
+	for(eCheckItem=(HW90_BLOCK_E)HW90_BLOCK_PHY0; eCheckItem<=HW90_BLOCK_PHY1; eCheckItem++)
+	{
+		rtStatus  = rtl8192_phy_checkBBAndRF(dev, (HW90_BLOCK_E)eCheckItem, (RF90_RADIO_PATH_E)0); //don't care RF path
+		if(rtStatus != 0)
+		{
+			RT_TRACE((COMP_ERR | COMP_PHY), "PHY_RF8256_Config():Check PHY%d Fail!!\n", eCheckItem-1);
+			return ;
+		}
+	}
+	/*---- Set CCK and OFDM Block "OFF"----*/
+	rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn|bOFDMEn, 0x0);
+	/*----BB Register Initilazation----*/
+	//==m==>Set PHY REG From Header<==m==
+	rtl8192_phyConfigBB(dev, BaseBand_Config_PHY_REG);
+
+	/*----Set BB reset de-Active----*/
+	dwRegValue = read_nic_dword(dev, CPU_GEN);
+	write_nic_dword(dev, CPU_GEN, (dwRegValue|CPU_GEN_BB_RST));
+
+ 	/*----BB AGC table Initialization----*/
+	//==m==>Set PHY REG From Header<==m==
+	rtl8192_phyConfigBB(dev, BaseBand_Config_AGC_TAB);
+
+	/*----Enable XSTAL ----*/
+	write_nic_byte_E(dev, 0x5e, 0x00);
+	if (priv->card_8192_version == (u8)VERSION_819xU_A)
+	{
+		//Antenna gain offset from B/C/D to A
+		dwRegValue = (priv->AntennaTxPwDiff[1]<<4 | priv->AntennaTxPwDiff[0]);
+		rtl8192_setBBreg(dev, rFPGA0_TxGainStage, (bXBTxAGC|bXCTxAGC), dwRegValue);
+
+		//XSTALLCap
+		dwRegValue = priv->CrystalCap & 0xf;
+		rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, bXtalCap, dwRegValue);
+	}
+
+	// Check if the CCK HighPower is turned ON.
+	// This is used to calculate PWDB.
+	priv->bCckHighPower = (u8)(rtl8192_QueryBBReg(dev, rFPGA0_XA_HSSIParameter2, 0x200));
+	return;
+}
+/******************************************************************************
+ *function:  This function initialize BB&RF
+ *   input:  net_device dev
+ *  output:  none
+ *  return:  none
+ *  notice:  Initialization value may change all the time, so please make
+ *           sure it has been synced with the newest.
+ * ***************************************************************************/
+void rtl8192_BBConfig(struct net_device* dev)
+{
+	rtl8192_InitBBRFRegDef(dev);
+	//config BB&RF. As hardCode based initialization has not been well
+	//implemented, so use file first.FIXME:should implement it for hardcode?
+	rtl8192_BB_Config_ParaFile(dev);
+	return;
+}
+
+/******************************************************************************
+ *function:  This function obtains the initialization value of Tx power Level offset
+ *   input:  net_device dev
+ *  output:  none
+ *  return:  none
+ * ***************************************************************************/
+void rtl8192_phy_getTxPower(struct net_device* dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	priv->MCSTxPowerLevelOriginalOffset[0] =
+		read_nic_dword(dev, rTxAGC_Rate18_06);
+	priv->MCSTxPowerLevelOriginalOffset[1] =
+		read_nic_dword(dev, rTxAGC_Rate54_24);
+	priv->MCSTxPowerLevelOriginalOffset[2] =
+		read_nic_dword(dev, rTxAGC_Mcs03_Mcs00);
+	priv->MCSTxPowerLevelOriginalOffset[3] =
+		read_nic_dword(dev, rTxAGC_Mcs07_Mcs04);
+	priv->MCSTxPowerLevelOriginalOffset[4] =
+		read_nic_dword(dev, rTxAGC_Mcs11_Mcs08);
+	priv->MCSTxPowerLevelOriginalOffset[5] =
+		read_nic_dword(dev, rTxAGC_Mcs15_Mcs12);
+
+	// read rx initial gain
+	priv->DefaultInitialGain[0] = read_nic_byte(dev, rOFDM0_XAAGCCore1);
+	priv->DefaultInitialGain[1] = read_nic_byte(dev, rOFDM0_XBAGCCore1);
+	priv->DefaultInitialGain[2] = read_nic_byte(dev, rOFDM0_XCAGCCore1);
+	priv->DefaultInitialGain[3] = read_nic_byte(dev, rOFDM0_XDAGCCore1);
+	RT_TRACE(COMP_INIT, "Default initial gain (c50=0x%x, c58=0x%x, c60=0x%x, c68=0x%x) \n",
+		priv->DefaultInitialGain[0], priv->DefaultInitialGain[1],
+		priv->DefaultInitialGain[2], priv->DefaultInitialGain[3]);
+
+	// read framesync
+	priv->framesync = read_nic_byte(dev, rOFDM0_RxDetector3);
+	priv->framesyncC34 = read_nic_byte(dev, rOFDM0_RxDetector2);
+	RT_TRACE(COMP_INIT, "Default framesync (0x%x) = 0x%x \n",
+		rOFDM0_RxDetector3, priv->framesync);
+
+	// read SIFS (save the value read fome MACPHY_REG.txt)
+	priv->SifsTime = read_nic_word(dev, SIFS);
+
+	return;
+}
+
+/******************************************************************************
+ *function:  This function obtains the initialization value of Tx power Level offset
+ *   input:  net_device dev
+ *  output:  none
+ *  return:  none
+ * ***************************************************************************/
+void rtl8192_phy_setTxPower(struct net_device* dev, u8 channel)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8	powerlevel = priv->TxPowerLevelCCK[channel-1];
+	u8	powerlevelOFDM24G = priv->TxPowerLevelOFDM24G[channel-1];
+
+	switch(priv->rf_chip)
+	{
+	case RF_8256:
+		PHY_SetRF8256CCKTxPower(dev, powerlevel); //need further implement
+		PHY_SetRF8256OFDMTxPower(dev, powerlevelOFDM24G);
+		break;
+	default:
+//	case RF_8225:
+//	case RF_8258:
+		RT_TRACE((COMP_PHY|COMP_ERR), "error RF chipID(8225 or 8258) in function %s()\n", __FUNCTION__);
+		break;
+	}
+	return;
+}
+
+/******************************************************************************
+ *function:  This function check Rf chip to do RF config
+ *   input:  net_device dev
+ *  output:  none
+ *  return:  only 8256 is supported
+ * ***************************************************************************/
+void rtl8192_phy_RFConfig(struct net_device* dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	switch(priv->rf_chip)
+	{
+		case RF_8256:
+			PHY_RF8256_Config(dev);
+			break;
+	//	case RF_8225:
+	//	case RF_8258:
+		default:
+			RT_TRACE(COMP_ERR, "error chip id\n");
+			break;
+	}
+	return;
+}
+
+/******************************************************************************
+ *function:  This function update Initial gain
+ *   input:  net_device dev
+ *  output:  none
+ *  return:  As Windows has not implemented this, wait for complement
+ * ***************************************************************************/
+void rtl8192_phy_updateInitGain(struct net_device* dev)
+{
+	return;
+}
+
+/******************************************************************************
+ *function:  This function read RF parameters from general head file, and do RF 3-wire
+ *   input:  net_device dev
+ *  output:  none
+ *  return:  return code show if RF configuration is successful(0:pass, 1:fail)
+ *    Note:  Delay may be required for RF configuration
+ * ***************************************************************************/
+u8 rtl8192_phy_ConfigRFWithHeaderFile(struct net_device* dev, RF90_RADIO_PATH_E	eRFPath)
+{
+
+	int i;
+	//u32* pRFArray;
+	u8 ret = 0;
+
+	switch(eRFPath){
+		case RF90_PATH_A:
+			for(i = 0;i<RadioA_ArrayLength; i=i+2){
+
+				if(rtl819XRadioA_Array[i] == 0xfe){
+						mdelay(100);
+						continue;
+				}
+				rtl8192_phy_SetRFReg(dev, eRFPath, rtl819XRadioA_Array[i], bMask12Bits, rtl819XRadioA_Array[i+1]);
+				mdelay(1);
+
+			}
+			break;
+		case RF90_PATH_B:
+			for(i = 0;i<RadioB_ArrayLength; i=i+2){
+
+				if(rtl819XRadioB_Array[i] == 0xfe){
+						mdelay(100);
+						continue;
+				}
+				rtl8192_phy_SetRFReg(dev, eRFPath, rtl819XRadioB_Array[i], bMask12Bits, rtl819XRadioB_Array[i+1]);
+				mdelay(1);
+
+			}
+			break;
+		case RF90_PATH_C:
+			for(i = 0;i<RadioC_ArrayLength; i=i+2){
+
+				if(rtl819XRadioC_Array[i] == 0xfe){
+						mdelay(100);
+						continue;
+				}
+				rtl8192_phy_SetRFReg(dev, eRFPath, rtl819XRadioC_Array[i], bMask12Bits, rtl819XRadioC_Array[i+1]);
+				mdelay(1);
+
+			}
+			break;
+		case RF90_PATH_D:
+			for(i = 0;i<RadioD_ArrayLength; i=i+2){
+
+				if(rtl819XRadioD_Array[i] == 0xfe){
+						mdelay(100);
+						continue;
+				}
+				rtl8192_phy_SetRFReg(dev, eRFPath, rtl819XRadioD_Array[i], bMask12Bits, rtl819XRadioD_Array[i+1]);
+				mdelay(1);
+
+			}
+			break;
+		default:
+			break;
+	}
+
+	return ret;;
+
+}
+/******************************************************************************
+ *function:  This function set Tx Power of the channel
+ *   input:  struct net_device *dev
+ *   	     u8 		channel
+ *  output:  none
+ *  return:  none
+ *    Note:
+ * ***************************************************************************/
+void rtl8192_SetTxPowerLevel(struct net_device *dev, u8 channel)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8	powerlevel = priv->TxPowerLevelCCK[channel-1];
+	u8	powerlevelOFDM24G = priv->TxPowerLevelOFDM24G[channel-1];
+
+	switch(priv->rf_chip)
+	{
+	case RF_8225:
+#ifdef TO_DO_LIST
+		PHY_SetRF8225CckTxPower(Adapter, powerlevel);
+		PHY_SetRF8225OfdmTxPower(Adapter, powerlevelOFDM24G);
+#endif
+		break;
+
+	case RF_8256:
+		PHY_SetRF8256CCKTxPower(dev, powerlevel);
+		PHY_SetRF8256OFDMTxPower(dev, powerlevelOFDM24G);
+		break;
+
+	case RF_8258:
+		break;
+	default:
+		RT_TRACE(COMP_ERR, "unknown rf chip ID in rtl8192_SetTxPowerLevel()\n");
+		break;
+	}
+	return;
+}
+
+/******************************************************************************
+ *function:  This function set RF state on or off
+ *   input:  struct net_device *dev
+ *   	     RT_RF_POWER_STATE eRFPowerState  //Power State to set
+ *  output:  none
+ *  return:  none
+ *    Note:
+ * ***************************************************************************/
+bool rtl8192_SetRFPowerState(struct net_device *dev, RT_RF_POWER_STATE eRFPowerState)
+{
+	bool				bResult = true;
+//	u8					eRFPath;
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	if(eRFPowerState == priv->ieee80211->eRFPowerState)
+		return false;
+
+	if(priv->SetRFPowerStateInProgress == true)
+		return false;
+
+	priv->SetRFPowerStateInProgress = true;
+
+	switch(priv->rf_chip)
+	{
+		case RF_8256:
+		switch( eRFPowerState )
+		{
+			case eRfOn:
+#if 0
+						rtl8192_setBBreg(dev, rFPGA0_XA_RFInterfaceOE, BIT4, 0x1);		// 0x860[4]
+						rtl8192_setBBreg(dev, rFPGA0_AnalogParameter4, 0x300, 0x3);		// 0x88c[4]
+						rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x60, 0x3); 		// 0x880[6:5]
+						rtl8192_setBBreg(dev, rOFDM0_TRxPathEnable, 0xf, 0x3);			// 0xc04[3:0]
+						rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0xf, 0x3);			// 0xd04[3:0]
+						rtl8192_setBBreg(dev, rFPGA0_AnalogParameter2, 0x7000, 0x3);	// 0x884[14:12]
+	//					for(eRFPath = 0; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
+		//					PHY_SetRFReg(Adapter, (RF90_RADIO_PATH_E)eRFPath, 0x4, 0xC00, 0x2);
+
+						//SwChnl(Adapter->ChannelID);
+#endif
+	//RF-A, RF-B
+					//enable RF-Chip A/B
+					rtl8192_setBBreg(dev, rFPGA0_XA_RFInterfaceOE, BIT4, 0x1);	// 0x860[4]
+					//analog to digital on
+					rtl8192_setBBreg(dev, rFPGA0_AnalogParameter4, 0x300, 0x3);// 0x88c[9:8]
+					//digital to analog on
+					rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x18, 0x3); // 0x880[4:3]
+					//rx antenna on
+					rtl8192_setBBreg(dev, rOFDM0_TRxPathEnable, 0x3, 0x3);// 0xc04[1:0]
+					//rx antenna on
+					rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0x3, 0x3);// 0xd04[1:0]
+					//analog to digital part2 on
+					rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x60, 0x3); // 0x880[6:5]
+
+				break;
+
+			case eRfSleep:
+
+				break;
+
+			case eRfOff:
+#if 0
+						rtl8192_setBBreg(dev, rFPGA0_XA_RFInterfaceOE, BIT4, 0x0);		// 0x860[4]
+						rtl8192_setBBreg(dev, rFPGA0_AnalogParameter4, 0x300, 0x0);		// 0x88c[4]
+						rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x60, 0x0); 		// 0x880[6:5]
+						rtl8192_setBBreg(dev, rOFDM0_TRxPathEnable, 0xf, 0);			// 0xc04[3:0]
+						rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0xf, 0);			// 0xd04[3:0]
+						rtl8192_setBBreg(dev, rFPGA0_AnalogParameter2, 0x7000, 0x0);	// 0x884[14:12]
+	//					for(eRFPath = 0; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
+		//					PHY_SetRFReg(Adapter, (RF90_RADIO_PATH_E)eRFPath, 0x4, 0xC00, 0x0);
+#endif
+					//RF-A, RF-B
+					//disable RF-Chip A/B
+					rtl8192_setBBreg(dev, rFPGA0_XA_RFInterfaceOE, BIT4, 0x0);	// 0x860[4]
+					//analog to digital off, for power save
+					rtl8192_setBBreg(dev, rFPGA0_AnalogParameter4, 0xf00, 0x0);// 0x88c[11:8]
+					//digital to analog off, for power save
+					rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x18, 0x0); // 0x880[4:3]
+					//rx antenna off
+					rtl8192_setBBreg(dev, rOFDM0_TRxPathEnable, 0xf, 0x0);// 0xc04[3:0]
+					//rx antenna off
+					rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0xf, 0x0);// 0xd04[3:0]
+					//analog to digital part2 off, for power save
+					rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x60, 0x0); // 0x880[6:5]
+
+				break;
+
+			default:
+				bResult = false;
+				RT_TRACE(COMP_ERR, "SetRFPowerState819xUsb(): unknow state to set: 0x%X!!!\n", eRFPowerState);
+				break;
+		}
+			break;
+		default:
+			RT_TRACE(COMP_ERR, "Not support rf_chip(%x)\n", priv->rf_chip);
+			break;
+	}
+#ifdef TO_DO_LIST
+	if(bResult)
+	{
+		// Update current RF state variable.
+		pHalData->eRFPowerState = eRFPowerState;
+		switch(pHalData->RFChipID )
+		{
+			case RF_8256:
+		switch(pHalData->eRFPowerState)
+				{
+				case eRfOff:
+					//
+					//If Rf off reason is from IPS, Led should blink with no link, by Maddest 071015
+					//
+					if(pMgntInfo->RfOffReason==RF_CHANGE_BY_IPS )
+					{
+						Adapter->HalFunc.LedControlHandler(Adapter,LED_CTL_NO_LINK);
+					}
+					else
+					{
+						// Turn off LED if RF is not ON.
+						Adapter->HalFunc.LedControlHandler(Adapter, LED_CTL_POWER_OFF);
+					}
+					break;
+
+				case eRfOn:
+					// Turn on RF we are still linked, which might happen when
+					// we quickly turn off and on HW RF. 2006.05.12, by rcnjko.
+					if( pMgntInfo->bMediaConnect == TRUE )
+					{
+						Adapter->HalFunc.LedControlHandler(Adapter, LED_CTL_LINK);
+					}
+					else
+					{
+						// Turn off LED if RF is not ON.
+						Adapter->HalFunc.LedControlHandler(Adapter, LED_CTL_NO_LINK);
+					}
+					break;
+
+				default:
+					// do nothing.
+					break;
+				}// Switch RF state
+				break;
+
+				default:
+					RT_TRACE(COMP_RF, DBG_LOUD, ("SetRFPowerState8190(): Unknown RF type\n"));
+					break;
+			}
+
+	}
+#endif
+	priv->SetRFPowerStateInProgress = false;
+
+	return bResult;
+}
+
+/****************************************************************************************
+ *function:  This function set command table variable(struct SwChnlCmd).
+ *   input:  SwChnlCmd*		CmdTable 	//table to be set.
+ *   	     u32		CmdTableIdx 	//variable index in table to be set
+ *   	     u32		CmdTableSz	//table size.
+ *   	     SwChnlCmdID	CmdID		//command ID to set.
+ *	     u32		Para1
+ *	     u32		Para2
+ *	     u32		msDelay
+ *  output:
+ *  return:  true if finished, false otherwise
+ *    Note:
+ * ************************************************************************************/
+u8 rtl8192_phy_SetSwChnlCmdArray(
+	SwChnlCmd*		CmdTable,
+	u32			CmdTableIdx,
+	u32			CmdTableSz,
+	SwChnlCmdID		CmdID,
+	u32			Para1,
+	u32			Para2,
+	u32			msDelay
+	)
+{
+	SwChnlCmd* pCmd;
+
+	if(CmdTable == NULL)
+	{
+		RT_TRACE(COMP_ERR, "phy_SetSwChnlCmdArray(): CmdTable cannot be NULL.\n");
+		return false;
+	}
+	if(CmdTableIdx >= CmdTableSz)
+	{
+		RT_TRACE(COMP_ERR, "phy_SetSwChnlCmdArray(): Access invalid index, please check size of the table, CmdTableIdx:%d, CmdTableSz:%d\n",
+				CmdTableIdx, CmdTableSz);
+		return false;
+	}
+
+	pCmd = CmdTable + CmdTableIdx;
+	pCmd->CmdID = CmdID;
+	pCmd->Para1 = Para1;
+	pCmd->Para2 = Para2;
+	pCmd->msDelay = msDelay;
+
+	return true;
+}
+/******************************************************************************
+ *function:  This function set channel step by step
+ *   input:  struct net_device *dev
+ *   	     u8 		channel
+ *   	     u8* 		stage //3 stages
+ *   	     u8* 		step  //
+ *   	     u32* 		delay //whether need to delay
+ *  output:  store new stage, step and delay for next step(combine with function above)
+ *  return:  true if finished, false otherwise
+ *    Note:  Wait for simpler function to replace it //wb
+ * ***************************************************************************/
+u8 rtl8192_phy_SwChnlStepByStep(struct net_device *dev, u8 channel, u8* stage, u8* step, u32* delay)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+//	PCHANNEL_ACCESS_SETTING	pChnlAccessSetting;
+	SwChnlCmd				PreCommonCmd[MAX_PRECMD_CNT];
+	u32					PreCommonCmdCnt;
+	SwChnlCmd				PostCommonCmd[MAX_POSTCMD_CNT];
+	u32					PostCommonCmdCnt;
+	SwChnlCmd				RfDependCmd[MAX_RFDEPENDCMD_CNT];
+	u32					RfDependCmdCnt;
+	SwChnlCmd				*CurrentCmd = NULL;
+	//RF90_RADIO_PATH_E		eRFPath;
+	u8		eRFPath;
+//	u32		RfRetVal;
+//	u8		RetryCnt;
+
+	RT_TRACE(COMP_CH, "====>%s()====stage:%d, step:%d, channel:%d\n", __FUNCTION__, *stage, *step, channel);
+//	RT_ASSERT(IsLegalChannel(Adapter, channel), ("illegal channel: %d\n", channel));
+#ifdef ENABLE_DOT11D
+	if (!IsLegalChannel(priv->ieee80211, channel))
+	{
+		RT_TRACE(COMP_ERR, "=============>set to illegal channel:%d\n", channel);
+		return true; //return true to tell upper caller function this channel setting is finished! Or it will in while loop.
+	}
+#endif
+//FIXME:need to check whether channel is legal or not here.WB
+
+
+	//for(eRFPath = RF90_PATH_A; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
+//	for(eRFPath = 0; eRFPath <RF90_PATH_MAX; eRFPath++)
+//	{
+//		if (!rtl8192_phy_CheckIsLegalRFPath(dev, eRFPath))
+//			continue;
+		// <1> Fill up pre common command.
+		PreCommonCmdCnt = 0;
+		rtl8192_phy_SetSwChnlCmdArray(PreCommonCmd, PreCommonCmdCnt++, MAX_PRECMD_CNT,
+					CmdID_SetTxPowerLevel, 0, 0, 0);
+		rtl8192_phy_SetSwChnlCmdArray(PreCommonCmd, PreCommonCmdCnt++, MAX_PRECMD_CNT,
+					CmdID_End, 0, 0, 0);
+
+		// <2> Fill up post common command.
+		PostCommonCmdCnt = 0;
+
+		rtl8192_phy_SetSwChnlCmdArray(PostCommonCmd, PostCommonCmdCnt++, MAX_POSTCMD_CNT,
+					CmdID_End, 0, 0, 0);
+
+		// <3> Fill up RF dependent command.
+		RfDependCmdCnt = 0;
+		switch( priv->rf_chip )
+		{
+		case RF_8225:
+			if (!(channel >= 1 && channel <= 14))
+			{
+				RT_TRACE(COMP_ERR, "illegal channel for Zebra 8225: %d\n", channel);
+				return true;
+			}
+			rtl8192_phy_SetSwChnlCmdArray(RfDependCmd, RfDependCmdCnt++, MAX_RFDEPENDCMD_CNT,
+				CmdID_RF_WriteReg, rZebra1_Channel, RF_CHANNEL_TABLE_ZEBRA[channel], 10);
+			rtl8192_phy_SetSwChnlCmdArray(RfDependCmd, RfDependCmdCnt++, MAX_RFDEPENDCMD_CNT,
+				CmdID_End, 0, 0, 0);
+			break;
+
+		case RF_8256:
+			// TEST!! This is not the table for 8256!!
+			if (!(channel >= 1 && channel <= 14))
+			{
+				RT_TRACE(COMP_ERR, "illegal channel for Zebra 8256: %d\n", channel);
+				return true;
+			}
+			rtl8192_phy_SetSwChnlCmdArray(RfDependCmd, RfDependCmdCnt++, MAX_RFDEPENDCMD_CNT,
+				CmdID_RF_WriteReg, rZebra1_Channel, channel, 10);
+			rtl8192_phy_SetSwChnlCmdArray(RfDependCmd, RfDependCmdCnt++, MAX_RFDEPENDCMD_CNT,
+			CmdID_End, 0, 0, 0);
+			break;
+
+		case RF_8258:
+			break;
+
+		default:
+			RT_TRACE(COMP_ERR, "Unknown RFChipID: %d\n", priv->rf_chip);
+			return true;
+			break;
+		}
+
+
+		do{
+			switch(*stage)
+			{
+			case 0:
+				CurrentCmd=&PreCommonCmd[*step];
+				break;
+			case 1:
+				CurrentCmd=&RfDependCmd[*step];
+				break;
+			case 2:
+				CurrentCmd=&PostCommonCmd[*step];
+				break;
+			}
+
+			if(CurrentCmd->CmdID==CmdID_End)
+			{
+				if((*stage)==2)
+				{
+					(*delay)=CurrentCmd->msDelay;
+					return true;
+				}
+				else
+				{
+					(*stage)++;
+					(*step)=0;
+					continue;
+				}
+			}
+
+			switch(CurrentCmd->CmdID)
+			{
+			case CmdID_SetTxPowerLevel:
+				if(priv->card_8192_version == (u8)VERSION_819xU_A) //xiong: consider it later!
+					rtl8192_SetTxPowerLevel(dev,channel);
+				break;
+			case CmdID_WritePortUlong:
+				write_nic_dword(dev, CurrentCmd->Para1, CurrentCmd->Para2);
+				break;
+			case CmdID_WritePortUshort:
+				write_nic_word(dev, CurrentCmd->Para1, (u16)CurrentCmd->Para2);
+				break;
+			case CmdID_WritePortUchar:
+				write_nic_byte(dev, CurrentCmd->Para1, (u8)CurrentCmd->Para2);
+				break;
+			case CmdID_RF_WriteReg:
+				for(eRFPath = 0; eRFPath < RF90_PATH_MAX; eRFPath++)
+				{
+				rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, CurrentCmd->Para1, bZebra1_ChannelNum, CurrentCmd->Para2);
+				}
+				break;
+			default:
+				break;
+			}
+
+			break;
+		}while(true);
+//	}/*for(Number of RF paths)*/
+
+	(*delay)=CurrentCmd->msDelay;
+	(*step)++;
+	return false;
+}
+
+/******************************************************************************
+ *function:  This function does acturally set channel work
+ *   input:  struct net_device *dev
+ *   	     u8 		channel
+ *  output:  none
+ *  return:  noin
+ *    Note:  We should not call this function directly
+ * ***************************************************************************/
+void rtl8192_phy_FinishSwChnlNow(struct net_device *dev, u8 channel)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u32	delay = 0;
+
+	while(!rtl8192_phy_SwChnlStepByStep(dev,channel,&priv->SwChnlStage,&priv->SwChnlStep,&delay))
+	{
+	//	if(delay>0)
+	//		msleep(delay);//or mdelay? need further consideration
+		if(!priv->up)
+			break;
+	}
+}
+/******************************************************************************
+ *function:  Callback routine of the work item for switch channel.
+ *   input:
+ *
+ *  output:  none
+ *  return:  noin
+ * ***************************************************************************/
+void rtl8192_SwChnl_WorkItem(struct net_device *dev)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	RT_TRACE(COMP_CH, "==> SwChnlCallback819xUsbWorkItem(), chan:%d\n", priv->chan);
+
+
+	rtl8192_phy_FinishSwChnlNow(dev , priv->chan);
+
+	RT_TRACE(COMP_CH, "<== SwChnlCallback819xUsbWorkItem()\n");
+}
+
+/******************************************************************************
+ *function:  This function scheduled actural workitem to set channel
+ *   input:  net_device dev
+ *   	     u8		channel //channel to set
+ *  output:  none
+ *  return:  return code show if workitem is scheduled(1:pass, 0:fail)
+ *    Note:  Delay may be required for RF configuration
+ * ***************************************************************************/
+u8 rtl8192_phy_SwChnl(struct net_device* dev, u8 channel)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	RT_TRACE(COMP_CH, "=====>%s(), SwChnlInProgress:%d\n", __FUNCTION__, priv->SwChnlInProgress);
+	if(!priv->up)
+		return false;
+	if(priv->SwChnlInProgress)
+		return false;
+
+//	if(pHalData->SetBWModeInProgress)
+//		return;
+if (0) //to test current channel from RF reg 0x7.
+{
+	u8		eRFPath;
+	for(eRFPath = 0; eRFPath < 2; eRFPath++){
+	printk("====>set channel:%x\n",rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x7, bZebra1_ChannelNum));
+	udelay(10);
+	}
+}
+	//--------------------------------------------
+	switch(priv->ieee80211->mode)
+	{
+	case WIRELESS_MODE_A:
+	case WIRELESS_MODE_N_5G:
+		if (channel<=14){
+			RT_TRACE(COMP_ERR, "WIRELESS_MODE_A but channel<=14");
+			return false;
+		}
+		break;
+	case WIRELESS_MODE_B:
+		if (channel>14){
+			RT_TRACE(COMP_ERR, "WIRELESS_MODE_B but channel>14");
+			return false;
+		}
+		break;
+	case WIRELESS_MODE_G:
+	case WIRELESS_MODE_N_24G:
+		if (channel>14){
+			RT_TRACE(COMP_ERR, "WIRELESS_MODE_G but channel>14");
+			return false;
+		}
+		break;
+	}
+	//--------------------------------------------
+
+	priv->SwChnlInProgress = true;
+	if(channel == 0)
+		channel = 1;
+
+	priv->chan=channel;
+
+	priv->SwChnlStage=0;
+	priv->SwChnlStep=0;
+//	schedule_work(&(priv->SwChnlWorkItem));
+//	rtl8192_SwChnl_WorkItem(dev);
+	if(priv->up) {
+//		queue_work(priv->priv_wq,&(priv->SwChnlWorkItem));
+	rtl8192_SwChnl_WorkItem(dev);
+	}
+
+	priv->SwChnlInProgress = false;
+	return true;
+}
+
+
+//
+/******************************************************************************
+ *function:  Callback routine of the work item for set bandwidth mode.
+ *   input:  struct net_device *dev
+ *   	     HT_CHANNEL_WIDTH	Bandwidth  //20M or 40M
+ *   	     HT_EXTCHNL_OFFSET Offset 	   //Upper, Lower, or Don't care
+ *  output:  none
+ *  return:  none
+ *    Note:  I doubt whether SetBWModeInProgress flag is necessary as we can
+ *    	     test whether current work in the queue or not.//do I?
+ * ***************************************************************************/
+void rtl8192_SetBWModeWorkItem(struct net_device *dev)
+{
+
+	struct r8192_priv *priv = ieee80211_priv(dev);
+	u8 regBwOpMode;
+
+	RT_TRACE(COMP_SWBW, "==>rtl8192_SetBWModeWorkItem()  Switch to %s bandwidth\n", \
+					priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20?"20MHz":"40MHz")
+
+
+	if(priv->rf_chip == RF_PSEUDO_11N)
+	{
+		priv->SetBWModeInProgress= false;
+		return;
+	}
+
+	//<1>Set MAC register
+	regBwOpMode = read_nic_byte(dev, BW_OPMODE);
+
+	switch(priv->CurrentChannelBW)
+	{
+		case HT_CHANNEL_WIDTH_20:
+			regBwOpMode |= BW_OPMODE_20MHZ;
+		       // 2007/02/07 Mark by Emily becasue we have not verify whether this register works
+			write_nic_byte(dev, BW_OPMODE, regBwOpMode);
+			break;
+
+		case HT_CHANNEL_WIDTH_20_40:
+			regBwOpMode &= ~BW_OPMODE_20MHZ;
+        		// 2007/02/07 Mark by Emily becasue we have not verify whether this register works
+			write_nic_byte(dev, BW_OPMODE, regBwOpMode);
+			break;
+
+		default:
+			RT_TRACE(COMP_ERR, "SetChannelBandwidth819xUsb(): unknown Bandwidth: %#X\n",priv->CurrentChannelBW);
+			break;
+	}
+
+	//<2>Set PHY related register
+	switch(priv->CurrentChannelBW)
+	{
+		case HT_CHANNEL_WIDTH_20:
+			// Add by Vivi 20071119
+			rtl8192_setBBreg(dev, rFPGA0_RFMOD, bRFMOD, 0x0);
+			rtl8192_setBBreg(dev, rFPGA1_RFMOD, bRFMOD, 0x0);
+			rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x00100000, 1);
+
+			// Correct the tx power for CCK rate in 20M. Suggest by YN, 20071207
+#if 0
+			write_nic_dword(dev, rCCK0_TxFilter1, 0x1a1b0000);
+			write_nic_dword(dev, rCCK0_TxFilter2, 0x090e1317);
+			write_nic_dword(dev, rCCK0_DebugPort, 0x00000204);
+#endif
+			priv->cck_present_attentuation =
+				priv->cck_present_attentuation_20Mdefault + priv->cck_present_attentuation_difference;
+
+			if(priv->cck_present_attentuation > 22)
+				priv->cck_present_attentuation= 22;
+			if(priv->cck_present_attentuation< 0)
+				priv->cck_present_attentuation = 0;
+			RT_TRACE(COMP_INIT, "20M, pHalData->CCKPresentAttentuation = %d\n", priv->cck_present_attentuation);
+
+			if(priv->chan == 14 && !priv->bcck_in_ch14)
+			{
+				priv->bcck_in_ch14 = TRUE;
+				dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
+			}
+			else if(priv->chan != 14 && priv->bcck_in_ch14)
+			{
+				priv->bcck_in_ch14 = FALSE;
+				dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
+			}
+			else
+				dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
+
+			break;
+		case HT_CHANNEL_WIDTH_20_40:
+			// Add by Vivi 20071119
+			rtl8192_setBBreg(dev, rFPGA0_RFMOD, bRFMOD, 0x1);
+			rtl8192_setBBreg(dev, rFPGA1_RFMOD, bRFMOD, 0x1);
+			rtl8192_setBBreg(dev, rCCK0_System, bCCKSideBand, (priv->nCur40MhzPrimeSC>>1));
+                   	rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x00100000, 0);
+			rtl8192_setBBreg(dev, rOFDM1_LSTF, 0xC00, priv->nCur40MhzPrimeSC);
+#if 0
+			// Correct the tx power for CCK rate in 40M. Suggest by YN, 20071207
+			write_nic_dword(dev, rCCK0_TxFilter1, 0x35360000);
+			write_nic_dword(dev, rCCK0_TxFilter2, 0x121c252e);
+			write_nic_dword(dev, rCCK0_DebugPort, 0x00000409);
+#endif
+			priv->cck_present_attentuation =
+				priv->cck_present_attentuation_40Mdefault + priv->cck_present_attentuation_difference;
+
+			if(priv->cck_present_attentuation > 22)
+				priv->cck_present_attentuation = 22;
+			if(priv->cck_present_attentuation < 0)
+				priv->cck_present_attentuation = 0;
+
+			RT_TRACE(COMP_INIT, "40M, pHalData->CCKPresentAttentuation = %d\n", priv->cck_present_attentuation);
+			if(priv->chan == 14 && !priv->bcck_in_ch14)
+			{
+				priv->bcck_in_ch14 = true;
+				dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
+			}
+			else if(priv->chan!= 14 && priv->bcck_in_ch14)
+			{
+				priv->bcck_in_ch14 = false;
+				dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
+			}
+			else
+				dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
+
+			break;
+		default:
+			RT_TRACE(COMP_ERR, "SetChannelBandwidth819xUsb(): unknown Bandwidth: %#X\n" ,priv->CurrentChannelBW);
+			break;
+
+	}
+	//Skip over setting of J-mode in BB register here. Default value is "None J mode". Emily 20070315
+
+#if 1
+	//<3>Set RF related register
+	switch( priv->rf_chip )
+	{
+		case RF_8225:
+#ifdef TO_DO_LIST
+			PHY_SetRF8225Bandwidth(Adapter, pHalData->CurrentChannelBW);
+#endif
+			break;
+
+		case RF_8256:
+			PHY_SetRF8256Bandwidth(dev, priv->CurrentChannelBW);
+			break;
+
+		case RF_8258:
+			// PHY_SetRF8258Bandwidth();
+			break;
+
+		case RF_PSEUDO_11N:
+			// Do Nothing
+			break;
+
+		default:
+			RT_TRACE(COMP_ERR, "Unknown RFChipID: %d\n", priv->rf_chip);
+			break;
+	}
+#endif
+	priv->SetBWModeInProgress= false;
+
+	RT_TRACE(COMP_SWBW, "<==SetBWMode819xUsb(), %d", atomic_read(&(priv->ieee80211->atm_swbw)) );
+}
+
+/******************************************************************************
+ *function:  This function schedules bandwith switch work.
+ *   input:  struct net_device *dev
+ *   	     HT_CHANNEL_WIDTH	Bandwidth  //20M or 40M
+ *   	     HT_EXTCHNL_OFFSET Offset 	   //Upper, Lower, or Don't care
+ *  output:  none
+ *  return:  none
+ *    Note:  I doubt whether SetBWModeInProgress flag is necessary as we can
+ *    	     test whether current work in the queue or not.//do I?
+ * ***************************************************************************/
+void rtl8192_SetBWMode(struct net_device *dev, HT_CHANNEL_WIDTH	Bandwidth, HT_EXTCHNL_OFFSET Offset)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	if(priv->SetBWModeInProgress)
+		return;
+	priv->SetBWModeInProgress= true;
+
+	priv->CurrentChannelBW = Bandwidth;
+
+	if(Offset==HT_EXTCHNL_OFFSET_LOWER)
+		priv->nCur40MhzPrimeSC = HAL_PRIME_CHNL_OFFSET_UPPER;
+	else if(Offset==HT_EXTCHNL_OFFSET_UPPER)
+		priv->nCur40MhzPrimeSC = HAL_PRIME_CHNL_OFFSET_LOWER;
+	else
+		priv->nCur40MhzPrimeSC = HAL_PRIME_CHNL_OFFSET_DONT_CARE;
+
+	//queue_work(priv->priv_wq, &(priv->SetBWModeWorkItem));
+	//	schedule_work(&(priv->SetBWModeWorkItem));
+	rtl8192_SetBWModeWorkItem(dev);
+
+}
+
+void InitialGain819xUsb(struct net_device *dev,	u8 Operation)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+
+	priv->InitialGainOperateType = Operation;
+
+	if(priv->up)
+	{
+	#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
+		queue_delayed_work(priv->priv_wq,&priv->initialgain_operate_wq,0);
+	#else
+		#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+		schedule_task(&priv->initialgain_operate_wq);
+		#else
+		queue_work(priv->priv_wq,&priv->initialgain_operate_wq);
+		#endif
+	#endif
+	}
+}
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern void InitialGainOperateWorkItemCallBack(struct work_struct *work)
+{
+	struct delayed_work *dwork = container_of(work,struct delayed_work,work);
+       struct r8192_priv *priv = container_of(dwork,struct r8192_priv,initialgain_operate_wq);
+       struct net_device *dev = priv->ieee80211->dev;
+#else
+extern void InitialGainOperateWorkItemCallBack(struct net_device *dev)
+{
+	struct r8192_priv *priv = ieee80211_priv(dev);
+#endif
+#define SCAN_RX_INITIAL_GAIN	0x17
+#define POWER_DETECTION_TH	0x08
+	u32	BitMask;
+	u8	initial_gain;
+	u8	Operation;
+
+	Operation = priv->InitialGainOperateType;
+
+	switch(Operation)
+	{
+		case IG_Backup:
+			RT_TRACE(COMP_SCAN, "IG_Backup, backup the initial gain.\n");
+			initial_gain = SCAN_RX_INITIAL_GAIN;//priv->DefaultInitialGain[0];//
+			BitMask = bMaskByte0;
+			if(dm_digtable.dig_algorithm == DIG_ALGO_BY_FALSE_ALARM)
+				rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8);	// FW DIG OFF
+			priv->initgain_backup.xaagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XAAGCCore1, BitMask);
+			priv->initgain_backup.xbagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XBAGCCore1, BitMask);
+			priv->initgain_backup.xcagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XCAGCCore1, BitMask);
+			priv->initgain_backup.xdagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XDAGCCore1, BitMask);
+			BitMask  = bMaskByte2;
+			priv->initgain_backup.cca		= (u8)rtl8192_QueryBBReg(dev, rCCK0_CCA, BitMask);
+
+			RT_TRACE(COMP_SCAN, "Scan InitialGainBackup 0xc50 is %x\n",priv->initgain_backup.xaagccore1);
+			RT_TRACE(COMP_SCAN, "Scan InitialGainBackup 0xc58 is %x\n",priv->initgain_backup.xbagccore1);
+			RT_TRACE(COMP_SCAN, "Scan InitialGainBackup 0xc60 is %x\n",priv->initgain_backup.xcagccore1);
+			RT_TRACE(COMP_SCAN, "Scan InitialGainBackup 0xc68 is %x\n",priv->initgain_backup.xdagccore1);
+			RT_TRACE(COMP_SCAN, "Scan InitialGainBackup 0xa0a is %x\n",priv->initgain_backup.cca);
+
+			RT_TRACE(COMP_SCAN, "Write scan initial gain = 0x%x \n", initial_gain);
+			write_nic_byte(dev, rOFDM0_XAAGCCore1, initial_gain);
+			write_nic_byte(dev, rOFDM0_XBAGCCore1, initial_gain);
+			write_nic_byte(dev, rOFDM0_XCAGCCore1, initial_gain);
+			write_nic_byte(dev, rOFDM0_XDAGCCore1, initial_gain);
+			RT_TRACE(COMP_SCAN, "Write scan 0xa0a = 0x%x \n", POWER_DETECTION_TH);
+			write_nic_byte(dev, 0xa0a, POWER_DETECTION_TH);
+			break;
+		case IG_Restore:
+			RT_TRACE(COMP_SCAN, "IG_Restore, restore the initial gain.\n");
+			BitMask = 0x7f; //Bit0~ Bit6
+			if(dm_digtable.dig_algorithm == DIG_ALGO_BY_FALSE_ALARM)
+				rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8);	// FW DIG OFF
+
+			rtl8192_setBBreg(dev, rOFDM0_XAAGCCore1, BitMask, (u32)priv->initgain_backup.xaagccore1);
+			rtl8192_setBBreg(dev, rOFDM0_XBAGCCore1, BitMask, (u32)priv->initgain_backup.xbagccore1);
+			rtl8192_setBBreg(dev, rOFDM0_XCAGCCore1, BitMask, (u32)priv->initgain_backup.xcagccore1);
+			rtl8192_setBBreg(dev, rOFDM0_XDAGCCore1, BitMask, (u32)priv->initgain_backup.xdagccore1);
+			BitMask  = bMaskByte2;
+			rtl8192_setBBreg(dev, rCCK0_CCA, BitMask, (u32)priv->initgain_backup.cca);
+
+			RT_TRACE(COMP_SCAN, "Scan BBInitialGainRestore 0xc50 is %x\n",priv->initgain_backup.xaagccore1);
+			RT_TRACE(COMP_SCAN, "Scan BBInitialGainRestore 0xc58 is %x\n",priv->initgain_backup.xbagccore1);
+			RT_TRACE(COMP_SCAN, "Scan BBInitialGainRestore 0xc60 is %x\n",priv->initgain_backup.xcagccore1);
+			RT_TRACE(COMP_SCAN, "Scan BBInitialGainRestore 0xc68 is %x\n",priv->initgain_backup.xdagccore1);
+			RT_TRACE(COMP_SCAN, "Scan BBInitialGainRestore 0xa0a is %x\n",priv->initgain_backup.cca);
+
+#ifdef RTL8190P
+			SetTxPowerLevel8190(Adapter,priv->CurrentChannel);
+#endif
+#ifdef RTL8192E
+			SetTxPowerLevel8190(Adapter,priv->CurrentChannel);
+#endif
+//#ifdef RTL8192U
+			rtl8192_phy_setTxPower(dev,priv->ieee80211->current_network.channel);
+//#endif
+
+			if(dm_digtable.dig_algorithm == DIG_ALGO_BY_FALSE_ALARM)
+				rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x1);	// FW DIG ON
+			break;
+		default:
+			RT_TRACE(COMP_SCAN, "Unknown IG Operation. \n");
+			break;
+	}
+}
+
diff --git a/drivers/staging/rtl8192su/r819xU_phy.h b/drivers/staging/rtl8192su/r819xU_phy.h
new file mode 100644
index 0000000..c165ac1
--- /dev/null
+++ b/drivers/staging/rtl8192su/r819xU_phy.h
@@ -0,0 +1,94 @@
+#ifndef _R819XU_PHY_H
+#define _R819XU_PHY_H
+
+/* Channel switch:The size of command tables for switch channel*/
+#define MAX_PRECMD_CNT 16
+#define MAX_RFDEPENDCMD_CNT 16
+#define MAX_POSTCMD_CNT 16
+
+typedef enum _SwChnlCmdID{
+	CmdID_End,
+	CmdID_SetTxPowerLevel,
+	CmdID_BBRegWrite10,
+	CmdID_WritePortUlong,
+	CmdID_WritePortUshort,
+	CmdID_WritePortUchar,
+	CmdID_RF_WriteReg,
+}SwChnlCmdID;
+
+/*--------------------------------Define structure--------------------------------*/
+/* 1. Switch channel related */
+typedef struct _SwChnlCmd{
+	SwChnlCmdID	CmdID;
+	u32			Para1;
+	u32			Para2;
+	u32			msDelay;
+}__attribute__ ((packed)) SwChnlCmd;
+
+extern u32 rtl819XMACPHY_Array_PG[];
+extern u32 rtl819XPHY_REG_1T2RArray[];
+extern u32 rtl819XAGCTAB_Array[];
+extern u32 rtl819XRadioA_Array[];
+extern u32 rtl819XRadioB_Array[];
+extern u32 rtl819XRadioC_Array[];
+extern u32 rtl819XRadioD_Array[];
+
+typedef enum _HW90_BLOCK{
+	HW90_BLOCK_MAC = 0,
+	HW90_BLOCK_PHY0 = 1,
+	HW90_BLOCK_PHY1 = 2,
+	HW90_BLOCK_RF = 3,
+	HW90_BLOCK_MAXIMUM = 4, // Never use this
+}HW90_BLOCK_E, *PHW90_BLOCK_E;
+
+typedef enum _RF90_RADIO_PATH{
+	RF90_PATH_A = 0,			//Radio Path A
+	RF90_PATH_B = 1,			//Radio Path B
+	RF90_PATH_C = 2,			//Radio Path C
+	RF90_PATH_D = 3,			//Radio Path D
+	RF90_PATH_MAX				//Max RF number 92 support
+}RF90_RADIO_PATH_E, *PRF90_RADIO_PATH_E;
+
+#define bMaskByte0                0xff
+#define bMaskByte1                0xff00
+#define bMaskByte2                0xff0000
+#define bMaskByte3                0xff000000
+#define bMaskHWord                0xffff0000
+#define bMaskLWord                0x0000ffff
+#define bMaskDWord                0xffffffff
+
+//extern u32 rtl8192_CalculateBitShift(u32 dwBitMask);
+extern u8 rtl8192_phy_CheckIsLegalRFPath(struct net_device* dev, u32 eRFPath);
+extern void rtl8192_setBBreg(struct net_device* dev, u32 dwRegAddr, u32 dwBitMask, u32 dwData);
+extern u32 rtl8192_QueryBBReg(struct net_device* dev, u32 dwRegAddr, u32 dwBitMask);
+//extern u32 rtl8192_phy_RFSerialRead(struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 Offset);
+//extern void rtl8192_phy_RFSerialWrite(struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 Offset, u32 Data);
+extern void rtl8192_phy_SetRFReg(struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 RegAddr, u32 BitMask, u32 Data);
+extern u32 rtl8192_phy_QueryRFReg(struct net_device* dev, RF90_RADIO_PATH_E eRFPath, u32 RegAddr, u32 BitMask);
+extern void rtl8192_phy_configmac(struct net_device* dev);
+extern void rtl8192_phyConfigBB(struct net_device* dev, u8 ConfigType);
+//extern void rtl8192_InitBBRFRegDef(struct net_device* dev);
+extern u8 rtl8192_phy_checkBBAndRF(struct net_device* dev, HW90_BLOCK_E CheckBlock, RF90_RADIO_PATH_E eRFPath);
+//extern void rtl8192_BB_Config_ParaFile(struct net_device* dev);
+extern void rtl8192_BBConfig(struct net_device* dev);
+extern void rtl8192_phy_getTxPower(struct net_device* dev);
+extern void rtl8192_phy_setTxPower(struct net_device* dev, u8 channel);
+extern void rtl8192_phy_RFConfig(struct net_device* dev);
+extern void rtl8192_phy_updateInitGain(struct net_device* dev);
+extern u8 rtl8192_phy_ConfigRFWithHeaderFile(struct net_device* dev, RF90_RADIO_PATH_E	eRFPath);
+
+extern u8 rtl8192_phy_SwChnl(struct net_device* dev, u8 channel);
+extern void rtl8192_SetBWMode(struct net_device *dev, HT_CHANNEL_WIDTH	Bandwidth, HT_EXTCHNL_OFFSET Offset);
+extern void rtl8192_SwChnl_WorkItem(struct net_device *dev);
+void rtl8192_SetBWModeWorkItem(struct net_device *dev);
+extern bool rtl8192_SetRFPowerState(struct net_device *dev, RT_RF_POWER_STATE eRFPowerState);
+//added by amy
+extern void InitialGain819xUsb(struct net_device *dev,	u8 Operation);
+
+#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20))
+extern void InitialGainOperateWorkItemCallBack(struct work_struct *work);
+#else
+extern void InitialGainOperateWorkItemCallBack(struct net_device *dev);
+#endif
+
+#endif
diff --git a/drivers/staging/rtl8192su/r819xU_phyreg.h b/drivers/staging/rtl8192su/r819xU_phyreg.h
new file mode 100644
index 0000000..b62f1a6
--- /dev/null
+++ b/drivers/staging/rtl8192su/r819xU_phyreg.h
@@ -0,0 +1,871 @@
+#ifndef _R819XU_PHYREG_H
+#define _R819XU_PHYREG_H
+
+
+#define   RF_DATA				0x1d4					// FW will write RF data in the register.
+
+//Register   //duplicate register due to connection: RF_Mode, TRxRN, NumOf L-STF
+//page 1
+#define rPMAC_Reset               		0x100
+#define rPMAC_TxStart             		0x104
+#define rPMAC_TxLegacySIG         		0x108
+#define rPMAC_TxHTSIG1            		0x10c
+#define rPMAC_TxHTSIG2            		0x110
+#define rPMAC_PHYDebug            		0x114
+#define rPMAC_TxPacketNum         		0x118
+#define rPMAC_TxIdle              		0x11c
+#define rPMAC_TxMACHeader0       	0x120
+#define rPMAC_TxMACHeader1       	0x124
+#define rPMAC_TxMACHeader2       	0x128
+#define rPMAC_TxMACHeader3       	0x12c
+#define rPMAC_TxMACHeader4       	0x130
+#define rPMAC_TxMACHeader5       	0x134
+#define rPMAC_TxDataType          		0x138
+#define rPMAC_TxRandomSeed      		0x13c
+#define rPMAC_CCKPLCPPreamble  		0x140
+#define rPMAC_CCKPLCPHeader     		0x144
+#define rPMAC_CCKCRC16            		0x148
+#define rPMAC_OFDMRxCRC32OK  		0x170
+#define rPMAC_OFDMRxCRC32Er   		0x174
+#define rPMAC_OFDMRxParityEr    		0x178
+#define rPMAC_OFDMRxCRC8Er     		0x17c
+#define rPMAC_CCKCRxRC16Er       		0x180
+#define rPMAC_CCKCRxRC32Er       		0x184
+#define rPMAC_CCKCRxRC32OK      		0x188
+#define rPMAC_TxStatus            		0x18c
+
+//page8
+#define rFPGA0_RFMOD              		0x800  //RF mode & CCK TxSC
+#define rFPGA0_TxInfo             		0x804
+#define rFPGA0_PSDFunction        		0x808
+#define rFPGA0_TxGainStage        		0x80c
+#define rFPGA0_RFTiming1          		0x810
+#define rFPGA0_RFTiming2          		0x814
+//#define rFPGA0_XC_RFTiming        		0x818
+//#define rFPGA0_XD_RFTiming        		0x81c
+#define rFPGA0_XA_HSSIParameter1  	0x820
+#define rFPGA0_XA_HSSIParameter2  	0x824
+#define rFPGA0_XB_HSSIParameter1  	0x828
+#define rFPGA0_XB_HSSIParameter2  	0x82c
+#define rFPGA0_XC_HSSIParameter1  	0x830
+#define rFPGA0_XC_HSSIParameter2  	0x834
+#define rFPGA0_XD_HSSIParameter1  	0x838
+#define rFPGA0_XD_HSSIParameter2  	0x83c
+#define rFPGA0_XA_LSSIParameter   	0x840
+#define rFPGA0_XB_LSSIParameter   	0x844
+#define rFPGA0_XC_LSSIParameter   	0x848
+#define rFPGA0_XD_LSSIParameter   	0x84c
+#define rFPGA0_RFWakeUpParameter  	0x850
+#define rFPGA0_RFSleepUpParameter 	0x854
+#define rFPGA0_XAB_SwitchControl  	0x858
+#define rFPGA0_XCD_SwitchControl  	0x85c
+#define rFPGA0_XA_RFInterfaceOE   	0x860
+#define rFPGA0_XB_RFInterfaceOE   	0x864
+#define rFPGA0_XC_RFInterfaceOE   	0x868
+#define rFPGA0_XD_RFInterfaceOE   	0x86c
+#define rFPGA0_XAB_RFInterfaceSW  	0x870
+#define rFPGA0_XCD_RFInterfaceSW  	0x874
+#define rFPGA0_XAB_RFParameter    	0x878
+#define rFPGA0_XCD_RFParameter    	0x87c
+#define rFPGA0_AnalogParameter1   	0x880
+#define rFPGA0_AnalogParameter2   	0x884
+#define rFPGA0_AnalogParameter3   	0x888
+#define rFPGA0_AnalogParameter4   	0x88c
+#define rFPGA0_XA_LSSIReadBack    	0x8a0
+#define rFPGA0_XB_LSSIReadBack    	0x8a4
+#define rFPGA0_XC_LSSIReadBack    	0x8a8
+#define rFPGA0_XD_LSSIReadBack    	0x8ac
+#define rFPGA0_PSDReport          		0x8b4
+#define rFPGA0_XAB_RFInterfaceRB  	0x8e0
+#define rFPGA0_XCD_RFInterfaceRB  	0x8e4
+
+//page 9
+#define rFPGA1_RFMOD              		0x900  //RF mode & OFDM TxSC
+#define rFPGA1_TxBlock            		0x904
+#define rFPGA1_DebugSelect        		0x908
+#define rFPGA1_TxInfo             		0x90c
+
+//page a
+#define rCCK0_System              		0xa00
+#define rCCK0_AFESetting          		0xa04
+#define rCCK0_CCA                 			0xa08
+#define rCCK0_RxAGC1              		0xa0c  //AGC default value, saturation level
+#define rCCK0_RxAGC2              		0xa10  //AGC & DAGC
+#define rCCK0_RxHP                		0xa14
+#define rCCK0_DSPParameter1       	0xa18  //Timing recovery & Channel estimation threshold
+#define rCCK0_DSPParameter2       	0xa1c  //SQ threshold
+#define rCCK0_TxFilter1           		0xa20
+#define rCCK0_TxFilter2           		0xa24
+#define rCCK0_DebugPort           		0xa28  //debug port and Tx filter3
+#define rCCK0_FalseAlarmReport    	0xa2c  //0xa2d
+#define rCCK0_TRSSIReport         		0xa50
+#define rCCK0_RxReport            		0xa54  //0xa57
+#define rCCK0_FACounterLower      	0xa5c  //0xa5b
+#define rCCK0_FACounterUpper      	0xa58  //0xa5c
+
+//page c
+#define rOFDM0_LSTF               		0xc00
+#define rOFDM0_TRxPathEnable      	0xc04
+#define rOFDM0_TRMuxPar           		0xc08
+#define rOFDM0_TRSWIsolation      		0xc0c
+#define rOFDM0_XARxAFE            		0xc10  //RxIQ DC offset, Rx digital filter, DC notch filter
+#define rOFDM0_XARxIQImbalance    	0xc14  //RxIQ imblance matrix
+#define rOFDM0_XBRxAFE            		0xc18
+#define rOFDM0_XBRxIQImbalance    	0xc1c
+#define rOFDM0_XCRxAFE            		0xc20
+#define rOFDM0_XCRxIQImbalance    	0xc24
+#define rOFDM0_XDRxAFE            		0xc28
+#define rOFDM0_XDRxIQImbalance    	0xc2c
+#define rOFDM0_RxDetector1        		0xc30  //PD,BW & SBD
+#define rOFDM0_RxDetector2        		0xc34  //SBD & Fame Sync.
+#define rOFDM0_RxDetector3        		0xc38  //Frame Sync.
+#define rOFDM0_RxDetector4        		0xc3c  //PD, SBD, Frame Sync & Short-GI
+#define rOFDM0_RxDSP              		0xc40  //Rx Sync Path
+#define rOFDM0_CFOandDAGC         	0xc44  //CFO & DAGC
+#define rOFDM0_CCADropThreshold   	0xc48 //CCA Drop threshold
+#define rOFDM0_ECCAThreshold      	0xc4c // energy CCA
+#define rOFDM0_XAAGCCore1         	0xc50
+#define rOFDM0_XAAGCCore2         	0xc54
+#define rOFDM0_XBAGCCore1         	0xc58
+#define rOFDM0_XBAGCCore2         	0xc5c
+#define rOFDM0_XCAGCCore1         	0xc60
+#define rOFDM0_XCAGCCore2         	0xc64
+#define rOFDM0_XDAGCCore1         	0xc68
+#define rOFDM0_XDAGCCore2         	0xc6c
+#define rOFDM0_AGCParameter1      	0xc70
+#define rOFDM0_AGCParameter2      	0xc74
+#define rOFDM0_AGCRSSITable       	0xc78
+#define rOFDM0_HTSTFAGC           		0xc7c
+#define rOFDM0_XATxIQImbalance   	0xc80
+#define rOFDM0_XATxAFE            		0xc84
+#define rOFDM0_XBTxIQImbalance    	0xc88
+#define rOFDM0_XBTxAFE            		0xc8c
+#define rOFDM0_XCTxIQImbalance    	0xc90
+#define rOFDM0_XCTxAFE            		0xc94
+#define rOFDM0_XDTxIQImbalance    	0xc98
+#define rOFDM0_XDTxAFE            		0xc9c
+#define rOFDM0_RxHPParameter      	0xce0
+#define rOFDM0_TxPseudoNoiseWgt   	0xce4
+#define rOFDM0_FrameSync          		0xcf0
+#define rOFDM0_DFSReport          		0xcf4
+#define rOFDM0_TxCoeff1           		0xca4
+#define rOFDM0_TxCoeff2           		0xca8
+#define rOFDM0_TxCoeff3           		0xcac
+#define rOFDM0_TxCoeff4           		0xcb0
+#define rOFDM0_TxCoeff5           		0xcb4
+#define rOFDM0_TxCoeff6           		0xcb8
+
+
+//page d
+#define rOFDM1_LSTF               		0xd00
+#define rOFDM1_TRxPathEnable      	0xd04
+#define rOFDM1_CFO                		0xd08
+#define rOFDM1_CSI1               		0xd10
+#define rOFDM1_SBD                		0xd14
+#define rOFDM1_CSI2               		0xd18
+#define rOFDM1_CFOTracking        		0xd2c
+#define rOFDM1_TRxMesaure1        	0xd34
+#define rOFDM1_IntfDet            		0xd3c
+#define rOFDM1_PseudoNoiseStateAB 0xd50
+#define rOFDM1_PseudoNoiseStateCD 0xd54
+#define rOFDM1_RxPseudoNoiseWgt   0xd58
+#define rOFDM_PHYCounter1         		0xda0  //cca, parity fail
+#define rOFDM_PHYCounter2         		0xda4  //rate illegal, crc8 fail
+#define rOFDM_PHYCounter3         		0xda8  //MCS not support
+#define rOFDM_ShortCFOAB          		0xdac
+#define rOFDM_ShortCFOCD          		0xdb0
+#define rOFDM_LongCFOAB           		0xdb4
+#define rOFDM_LongCFOCD           		0xdb8
+#define rOFDM_TailCFOAB           		0xdbc
+#define rOFDM_TailCFOCD           		0xdc0
+#define rOFDM_PWMeasure1          	0xdc4
+#define rOFDM_PWMeasure2          	0xdc8
+#define rOFDM_BWReport            		0xdcc
+#define rOFDM_AGCReport           		0xdd0
+#define rOFDM_RxSNR               		0xdd4
+#define rOFDM_RxEVMCSI            		0xdd8
+#define rOFDM_SIGReport           		0xddc
+
+//page e
+#define rTxAGC_Rate18_06			0xe00
+#define rTxAGC_Rate54_24			0xe04
+#define rTxAGC_CCK_Mcs32			0xe08
+#define rTxAGC_Mcs03_Mcs00			0xe10
+#define rTxAGC_Mcs07_Mcs04			0xe14
+#define rTxAGC_Mcs11_Mcs08			0xe18
+#define rTxAGC_Mcs15_Mcs12			0xe1c
+
+
+//RF
+//Zebra1
+#define rZebra1_HSSIEnable            	0x0
+#define rZebra1_TRxEnable1            	0x1
+#define rZebra1_TRxEnable2           	0x2
+#define rZebra1_AGC                   		0x4
+#define rZebra1_ChargePump            	0x5
+#define rZebra1_Channel               		0x7
+#define rZebra1_TxGain               	 	0x8
+#define rZebra1_TxLPF                 		0x9
+#define rZebra1_RxLPF                 		0xb
+#define rZebra1_RxHPFCorner           	0xc
+
+//Zebra4
+#define rGlobalCtrl                   		0
+#define rRTL8256_TxLPF                		19
+#define rRTL8256_RxLPF                		11
+
+//RTL8258
+#define rRTL8258_TxLPF                		0x11
+#define rRTL8258_RxLPF                		0x13
+#define rRTL8258_RSSILPF              	0xa
+
+//Bit Mask
+//page-1
+#define bBBResetB                 			0x100
+#define bGlobalResetB             		0x200
+#define bOFDMTxStart              		0x4
+#define bCCKTxStart               			0x8
+#define bCRC32Debug               		0x100
+#define bPMACLoopback             		0x10
+#define bTxLSIG                   			0xffffff
+#define bOFDMTxRate               		0xf
+#define bOFDMTxReserved           		0x10
+#define bOFDMTxLength             		0x1ffe0
+#define bOFDMTxParity             		0x20000
+#define bTxHTSIG1                 			0xffffff
+#define bTxHTMCSRate              		0x7f
+#define bTxHTBW                   			0x80
+#define bTxHTLength               		0xffff00
+#define bTxHTSIG2                 			0xffffff
+#define bTxHTSmoothing            		0x1
+#define bTxHTSounding             		0x2
+#define bTxHTReserved             		0x4
+#define bTxHTAggreation           		0x8
+#define bTxHTSTBC                 			0x30
+#define bTxHTAdvanceCoding        		0x40
+#define bTxHTShortGI              		0x80
+#define bTxHTNumberHT_LTF         		0x300
+#define bTxHTCRC8                 			0x3fc00
+#define bCounterReset             		0x10000
+#define bNumOfOFDMTx              		0xffff
+#define bNumOfCCKTx               		0xffff0000
+#define bTxIdleInterval           			0xffff
+#define bOFDMService              		0xffff0000
+#define bTxMACHeader              		0xffffffff
+#define bTxDataInit               			0xff
+#define bTxHTMode                 		0x100
+#define bTxDataType               		0x30000
+#define bTxRandomSeed             		0xffffffff
+#define bCCKTxPreamble           		0x1
+#define bCCKTxSFD                 			0xffff0000
+#define bCCKTxSIG                 			0xff
+#define bCCKTxService             		0xff00
+#define bCCKLengthExt             		0x8000
+#define bCCKTxLength              		0xffff0000
+#define bCCKTxCRC16               		0xffff
+#define bCCKTxStatus              		0x1
+#define bOFDMTxStatus             		0x2
+
+//page-8
+#define bRFMOD                    			0x1
+#define bJapanMode                		0x2
+#define bCCKTxSC                  			0x30
+#define bCCKEn                    			0x1000000
+#define bOFDMEn                   			0x2000000
+#define bOFDMRxADCPhase           		0x10000
+#define bOFDMTxDACPhase           		0x40000
+#define bXATxAGC                  			0x3f
+#define bXBTxAGC                  			0xf00
+#define bXCTxAGC                  			0xf000
+#define bXDTxAGC                  			0xf0000
+#define bPAStart                  			0xf0000000
+#define bTRStart                  			0x00f00000
+#define bRFStart                  			0x0000f000
+#define bBBStart                  			0x000000f0
+#define bBBCCKStart               		0x0000000f
+#define bPAEnd                    			0xf          //Reg0x814
+#define bTREnd                    			0x0f000000
+#define bRFEnd                    			0x000f0000
+#define bCCAMask                  			0x000000f0   //T2R
+#define bR2RCCAMask               		0x00000f00
+#define bHSSI_R2TDelay            		0xf8000000
+#define bHSSI_T2RDelay            		0xf80000
+#define bContTxHSSI               		0x400     //chane gain at continue Tx
+#define bIGFromCCK                		0x200
+#define bAGCAddress               		0x3f
+#define bRxHPTx                   			0x7000
+#define bRxHPT2R                  			0x38000
+#define bRxHPCCKIni               		0xc0000
+#define bAGCTxCode                		0xc00000
+#define bAGCRxCode                		0x300000
+#define b3WireDataLength          		0x800
+#define b3WireAddressLength       		0x400
+#define b3WireRFPowerDown         		0x1
+//#define bHWSISelect               		0x8
+#define b5GPAPEPolarity           		0x40000000
+#define b2GPAPEPolarity           		0x80000000
+#define bRFSW_TxDefaultAnt        		0x3
+#define bRFSW_TxOptionAnt         		0x30
+#define bRFSW_RxDefaultAnt        		0x300
+#define bRFSW_RxOptionAnt         		0x3000
+#define bRFSI_3WireData           		0x1
+#define bRFSI_3WireClock          		0x2
+#define bRFSI_3WireLoad           		0x4
+#define bRFSI_3WireRW             		0x8
+#define bRFSI_3Wire               			0xf  //3-wire total control
+#define bRFSI_RFENV               		0x10
+#define bRFSI_TRSW                		0x20
+#define bRFSI_TRSWB               		0x40
+#define bRFSI_ANTSW               		0x100
+#define bRFSI_ANTSWB              		0x200
+#define bRFSI_PAPE                			0x400
+#define bRFSI_PAPE5G              		0x800
+#define bBandSelect               			0x1
+#define bHTSIG2_GI                			0x80
+#define bHTSIG2_Smoothing         		0x01
+#define bHTSIG2_Sounding          		0x02
+#define bHTSIG2_Aggreaton         		0x08
+#define bHTSIG2_STBC              		0x30
+#define bHTSIG2_AdvCoding         		0x40
+#define bHTSIG2_NumOfHTLTF        	0x300
+#define bHTSIG2_CRC8              		0x3fc
+#define bHTSIG1_MCS               		0x7f
+#define bHTSIG1_BandWidth         		0x80
+#define bHTSIG1_HTLength          		0xffff
+#define bLSIG_Rate                			0xf
+#define bLSIG_Reserved            		0x10
+#define bLSIG_Length              		0x1fffe
+#define bLSIG_Parity              			0x20
+#define bCCKRxPhase               		0x4
+#define bLSSIReadAddress          		0x3f000000   //LSSI "Read" Address
+#define bLSSIReadEdge             		0x80000000   //LSSI "Read" edge signal
+#define bLSSIReadBackData         		0xfff
+#define bLSSIReadOKFlag           		0x1000
+#define bCCKSampleRate            		0x8       //0: 44MHz, 1:88MHz
+
+#define bRegulator0Standby        		0x1
+#define bRegulatorPLLStandby      		0x2
+#define bRegulator1Standby        		0x4
+#define bPLLPowerUp               		0x8
+#define bDPLLPowerUp              		0x10
+#define bDA10PowerUp              		0x20
+#define bAD7PowerUp               		0x200
+#define bDA6PowerUp               		0x2000
+#define bXtalPowerUp              		0x4000
+#define b40MDClkPowerUP           		0x8000
+#define bDA6DebugMode             		0x20000
+#define bDA6Swing                 			0x380000
+#define bADClkPhase               		0x4000000
+#define b80MClkDelay              		0x18000000
+#define bAFEWatchDogEnable        		0x20000000
+#define bXtalCap                			0x0f000000
+#define bIntDifClkEnable          		0x400
+#define bExtSigClkEnable         	 	0x800
+#define bBandgapMbiasPowerUp      	0x10000
+#define bAD11SHGain               		0xc0000
+#define bAD11InputRange           		0x700000
+#define bAD11OPCurrent            		0x3800000
+#define bIPathLoopback            		0x4000000
+#define bQPathLoopback            		0x8000000
+#define bAFELoopback              		0x10000000
+#define bDA10Swing                		0x7e0
+#define bDA10Reverse              		0x800
+#define bDAClkSource              		0x1000
+#define bAD7InputRange            		0x6000
+#define bAD7Gain                  			0x38000
+#define bAD7OutputCMMode          		0x40000
+#define bAD7InputCMMode           		0x380000
+#define bAD7Current               			0xc00000
+#define bRegulatorAdjust          		0x7000000
+#define bAD11PowerUpAtTx          		0x1
+#define bDA10PSAtTx               		0x10
+#define bAD11PowerUpAtRx          		0x100
+#define bDA10PSAtRx               		0x1000
+
+#define bCCKRxAGCFormat           		0x200
+
+#define bPSDFFTSamplepPoint       		0xc000
+#define bPSDAverageNum            		0x3000
+#define bIQPathControl            		0xc00
+#define bPSDFreq                  			0x3ff
+#define bPSDAntennaPath           		0x30
+#define bPSDIQSwitch              		0x40
+#define bPSDRxTrigger             		0x400000
+#define bPSDTxTrigger             		0x80000000
+#define bPSDSineToneScale        		0x7f000000
+#define bPSDReport                			0xffff
+
+//page-9
+#define bOFDMTxSC                 		0x30000000
+#define bCCKTxOn                  			0x1
+#define bOFDMTxOn                 		0x2
+#define bDebugPage                		0xfff  //reset debug page and also HWord, LWord
+#define bDebugItem                		0xff   //reset debug page and LWord
+#define bAntL              	       		0x10
+#define bAntNonHT           	      			0x100
+#define bAntHT1               			0x1000
+#define bAntHT2                   			0x10000
+#define bAntHT1S1                 			0x100000
+#define bAntNonHTS1               		0x1000000
+
+//page-a
+#define bCCKBBMode                		0x3
+#define bCCKTxPowerSaving         		0x80
+#define bCCKRxPowerSaving         		0x40
+#define bCCKSideBand              		0x10
+#define bCCKScramble              		0x8
+#define bCCKAntDiversity    		      	0x8000
+#define bCCKCarrierRecovery   	    	0x4000
+#define bCCKTxRate           		     	0x3000
+#define bCCKDCCancel             	 	0x0800
+#define bCCKISICancel             		0x0400
+#define bCCKMatchFilter           		0x0200
+#define bCCKEqualizer             		0x0100
+#define bCCKPreambleDetect       	 	0x800000
+#define bCCKFastFalseCCA          		0x400000
+#define bCCKChEstStart            		0x300000
+#define bCCKCCACount              		0x080000
+#define bCCKcs_lim                			0x070000
+#define bCCKBistMode              		0x80000000
+#define bCCKCCAMask             	  	0x40000000
+#define bCCKTxDACPhase         	   	0x4
+#define bCCKRxADCPhase         	   	0x20000000   //r_rx_clk
+#define bCCKr_cp_mode0         	   	0x0100
+#define bCCKTxDCOffset           	 	0xf0
+#define bCCKRxDCOffset           	 	0xf
+#define bCCKCCAMode              	 	0xc000
+#define bCCKFalseCS_lim           		0x3f00
+#define bCCKCS_ratio              		0xc00000
+#define bCCKCorgBit_sel           		0x300000
+#define bCCKPD_lim                			0x0f0000
+#define bCCKNewCCA                		0x80000000
+#define bCCKRxHPofIG              		0x8000
+#define bCCKRxIG                  			0x7f00
+#define bCCKLNAPolarity           		0x800000
+#define bCCKRx1stGain             		0x7f0000
+#define bCCKRFExtend              		0x20000000 //CCK Rx Iinital gain polarity
+#define bCCKRxAGCSatLevel        	 	0x1f000000
+#define bCCKRxAGCSatCount       	  	0xe0
+#define bCCKRxRFSettle            		0x1f       //AGCsamp_dly
+#define bCCKFixedRxAGC           	 	0x8000
+//#define bCCKRxAGCFormat         	 	0x4000   //remove to HSSI register 0x824
+#define bCCKAntennaPolarity      	 	0x2000
+#define bCCKTxFilterType          		0x0c00
+#define bCCKRxAGCReportType   	   	0x0300
+#define bCCKRxDAGCEn              		0x80000000
+#define bCCKRxDAGCPeriod        	  	0x20000000
+#define bCCKRxDAGCSatLevel     	   	0x1f000000
+#define bCCKTimingRecovery       	 	0x800000
+#define bCCKTxC0                  			0x3f0000
+#define bCCKTxC1                  			0x3f000000
+#define bCCKTxC2                  			0x3f
+#define bCCKTxC3                  			0x3f00
+#define bCCKTxC4                  			0x3f0000
+#define bCCKTxC5                  			0x3f000000
+#define bCCKTxC6                  			0x3f
+#define bCCKTxC7                  			0x3f00
+#define bCCKDebugPort             		0xff0000
+#define bCCKDACDebug              		0x0f000000
+#define bCCKFalseAlarmEnable      		0x8000
+#define bCCKFalseAlarmRead        		0x4000
+#define bCCKTRSSI                 			0x7f
+#define bCCKRxAGCReport           		0xfe
+#define bCCKRxReport_AntSel       		0x80000000
+#define bCCKRxReport_MFOff        		0x40000000
+#define bCCKRxRxReport_SQLoss     	0x20000000
+#define bCCKRxReport_Pktloss      		0x10000000
+#define bCCKRxReport_Lockedbit    	0x08000000
+#define bCCKRxReport_RateError    	0x04000000
+#define bCCKRxReport_RxRate       		0x03000000
+#define bCCKRxFACounterLower      	0xff
+#define bCCKRxFACounterUpper      	0xff000000
+#define bCCKRxHPAGCStart          		0xe000
+#define bCCKRxHPAGCFinal          		0x1c00
+
+#define bCCKRxFalseAlarmEnable    	0x8000
+#define bCCKFACounterFreeze       		0x4000
+
+#define bCCKTxPathSel             		0x10000000
+#define bCCKDefaultRxPath         		0xc000000
+#define bCCKOptionRxPath          		0x3000000
+
+//page c
+#define bNumOfSTF                			0x3
+#define bShift_L                 			0xc0
+#define bGI_TH                   			0xc
+#define bRxPathA                 			0x1
+#define bRxPathB                 			0x2
+#define bRxPathC                 			0x4
+#define bRxPathD                 			0x8
+#define bTxPathA                 			0x1
+#define bTxPathB                 			0x2
+#define bTxPathC                 			0x4
+#define bTxPathD                 			0x8
+#define bTRSSIFreq               			0x200
+#define bADCBackoff              			0x3000
+#define bDFIRBackoff             			0xc000
+#define bTRSSILatchPhase         		0x10000
+#define bRxIDCOffset             			0xff
+#define bRxQDCOffset             			0xff00
+#define bRxDFIRMode              		0x1800000
+#define bRxDCNFType              		0xe000000
+#define bRXIQImb_A               			0x3ff
+#define bRXIQImb_B               			0xfc00
+#define bRXIQImb_C               			0x3f0000
+#define bRXIQImb_D               			0xffc00000
+#define bDC_dc_Notch             		0x60000
+#define bRxNBINotch              			0x1f000000
+#define bPD_TH                   			0xf
+#define bPD_TH_Opt2              		0xc000
+#define bPWED_TH                 			0x700
+#define bIfMF_Win_L              			0x800
+#define bPD_Option               			0x1000
+#define bMF_Win_L                			0xe000
+#define bBW_Search_L             		0x30000
+#define bwin_enh_L               			0xc0000
+#define bBW_TH                   			0x700000
+#define bED_TH2                  			0x3800000
+#define bBW_option               			0x4000000
+#define bRatio_TH                			0x18000000
+#define bWindow_L                			0xe0000000
+#define bSBD_Option              			0x1
+#define bFrame_TH                			0x1c
+#define bFS_Option               			0x60
+#define bDC_Slope_check          		0x80
+#define bFGuard_Counter_DC_L     		0xe00
+#define bFrame_Weight_Short      		0x7000
+#define bSub_Tune                			0xe00000
+#define bFrame_DC_Length         		0xe000000
+#define bSBD_start_offset        		0x30000000
+#define bFrame_TH_2              		0x7
+#define bFrame_GI2_TH            		0x38
+#define bGI2_Sync_en             		0x40
+#define bSarch_Short_Early       		0x300
+#define bSarch_Short_Late        		0xc00
+#define bSarch_GI2_Late          		0x70000
+#define bCFOAntSum               		0x1
+#define bCFOAcc                  			0x2
+#define bCFOStartOffset          		0xc
+#define bCFOLookBack             		0x70
+#define bCFOSumWeight            		0x80
+#define bDAGCEnable              			0x10000
+#define bTXIQImb_A               			0x3ff
+#define bTXIQImb_B               			0xfc00
+#define bTXIQImb_C               			0x3f0000
+#define bTXIQImb_D               			0xffc00000
+#define bTxIDCOffset             			0xff
+#define bTxQDCOffset             			0xff00
+#define bTxDFIRMode              		0x10000
+#define bTxPesudoNoiseOn         		0x4000000
+#define bTxPesudoNoise_A         		0xff
+#define bTxPesudoNoise_B         		0xff00
+#define bTxPesudoNoise_C         		0xff0000
+#define bTxPesudoNoise_D         		0xff000000
+#define bCCADropOption           		0x20000
+#define bCCADropThres            		0xfff00000
+#define bEDCCA_H                 			0xf
+#define bEDCCA_L                 			0xf0
+#define bLambda_ED               0x300
+#define bRxInitialGain           0x7f
+#define bRxAntDivEn              0x80
+#define bRxAGCAddressForLNA      0x7f00
+#define bRxHighPowerFlow         0x8000
+#define bRxAGCFreezeThres        0xc0000
+#define bRxFreezeStep_AGC1       0x300000
+#define bRxFreezeStep_AGC2       0xc00000
+#define bRxFreezeStep_AGC3       0x3000000
+#define bRxFreezeStep_AGC0       0xc000000
+#define bRxRssi_Cmp_En           0x10000000
+#define bRxQuickAGCEn            0x20000000
+#define bRxAGCFreezeThresMode    0x40000000
+#define bRxOverFlowCheckType     0x80000000
+#define bRxAGCShift              0x7f
+#define bTRSW_Tri_Only           0x80
+#define bPowerThres              0x300
+#define bRxAGCEn                 0x1
+#define bRxAGCTogetherEn         0x2
+#define bRxAGCMin                0x4
+#define bRxHP_Ini                0x7
+#define bRxHP_TRLNA              0x70
+#define bRxHP_RSSI               0x700
+#define bRxHP_BBP1               0x7000
+#define bRxHP_BBP2               0x70000
+#define bRxHP_BBP3               0x700000
+#define bRSSI_H                  0x7f0000     //the threshold for high power
+#define bRSSI_Gen                0x7f000000   //the threshold for ant diversity
+#define bRxSettle_TRSW           0x7
+#define bRxSettle_LNA            0x38
+#define bRxSettle_RSSI           0x1c0
+#define bRxSettle_BBP            0xe00
+#define bRxSettle_RxHP           0x7000
+#define bRxSettle_AntSW_RSSI     0x38000
+#define bRxSettle_AntSW          0xc0000
+#define bRxProcessTime_DAGC      0x300000
+#define bRxSettle_HSSI           0x400000
+#define bRxProcessTime_BBPPW     0x800000
+#define bRxAntennaPowerShift     0x3000000
+#define bRSSITableSelect         0xc000000
+#define bRxHP_Final              0x7000000
+#define bRxHTSettle_BBP          0x7
+#define bRxHTSettle_HSSI         0x8
+#define bRxHTSettle_RxHP         0x70
+#define bRxHTSettle_BBPPW        0x80
+#define bRxHTSettle_Idle         0x300
+#define bRxHTSettle_Reserved     0x1c00
+#define bRxHTRxHPEn              0x8000
+#define bRxHTAGCFreezeThres      0x30000
+#define bRxHTAGCTogetherEn       0x40000
+#define bRxHTAGCMin              0x80000
+#define bRxHTAGCEn               0x100000
+#define bRxHTDAGCEn              0x200000
+#define bRxHTRxHP_BBP            0x1c00000
+#define bRxHTRxHP_Final          0xe0000000
+#define bRxPWRatioTH             0x3
+#define bRxPWRatioEn             0x4
+#define bRxMFHold                0x3800
+#define bRxPD_Delay_TH1          0x38
+#define bRxPD_Delay_TH2          0x1c0
+#define bRxPD_DC_COUNT_MAX       0x600
+//#define bRxMF_Hold               0x3800
+#define bRxPD_Delay_TH           0x8000
+#define bRxProcess_Delay         0xf0000
+#define bRxSearchrange_GI2_Early 0x700000
+#define bRxFrame_Guard_Counter_L 0x3800000
+#define bRxSGI_Guard_L           0xc000000
+#define bRxSGI_Search_L          0x30000000
+#define bRxSGI_TH                0xc0000000
+#define bDFSCnt0                 0xff
+#define bDFSCnt1                 0xff00
+#define bDFSFlag                 0xf0000
+
+#define bMFWeightSum             0x300000
+#define bMinIdxTH                0x7f000000
+
+#define bDAFormat                0x40000
+
+#define bTxChEmuEnable           0x01000000
+
+#define bTRSWIsolation_A         0x7f
+#define bTRSWIsolation_B         0x7f00
+#define bTRSWIsolation_C         0x7f0000
+#define bTRSWIsolation_D         0x7f000000
+
+#define bExtLNAGain              0x7c00
+
+//page d
+#define bSTBCEn                  0x4
+#define bAntennaMapping          0x10
+#define bNss                     0x20
+#define bCFOAntSumD              0x200
+#define bPHYCounterReset         0x8000000
+#define bCFOReportGet            0x4000000
+#define bOFDMContinueTx          0x10000000
+#define bOFDMSingleCarrier       0x20000000
+#define bOFDMSingleTone          0x40000000
+//#define bRxPath1                 0x01
+//#define bRxPath2                 0x02
+//#define bRxPath3                 0x04
+//#define bRxPath4                 0x08
+//#define bTxPath1                 0x10
+//#define bTxPath2                 0x20
+#define bHTDetect                0x100
+#define bCFOEn                   0x10000
+#define bCFOValue                0xfff00000
+#define bSigTone_Re              0x3f
+#define bSigTone_Im              0x7f00
+#define bCounter_CCA             0xffff
+#define bCounter_ParityFail      0xffff0000
+#define bCounter_RateIllegal     0xffff
+#define bCounter_CRC8Fail        0xffff0000
+#define bCounter_MCSNoSupport    0xffff
+#define bCounter_FastSync        0xffff
+#define bShortCFO                0xfff
+#define bShortCFOTLength         12   //total
+#define bShortCFOFLength         11   //fraction
+#define bLongCFO                 0x7ff
+#define bLongCFOTLength          11
+#define bLongCFOFLength          11
+#define bTailCFO                 0x1fff
+#define bTailCFOTLength          13
+#define bTailCFOFLength          12
+
+#define bmax_en_pwdB             0xffff
+#define bCC_power_dB             0xffff0000
+#define bnoise_pwdB              0xffff
+#define bPowerMeasTLength        10
+#define bPowerMeasFLength        3
+#define bRx_HT_BW                0x1
+#define bRxSC                    0x6
+#define bRx_HT                   0x8
+
+#define bNB_intf_det_on          0x1
+#define bIntf_win_len_cfg        0x30
+#define bNB_Intf_TH_cfg          0x1c0
+
+#define bRFGain                  0x3f
+#define bTableSel                0x40
+#define bTRSW                    0x80
+
+#define bRxSNR_A                 0xff
+#define bRxSNR_B                 0xff00
+#define bRxSNR_C                 0xff0000
+#define bRxSNR_D                 0xff000000
+#define bSNREVMTLength           8
+#define bSNREVMFLength           1
+
+#define bCSI1st                  0xff
+#define bCSI2nd                  0xff00
+#define bRxEVM1st                0xff0000
+#define bRxEVM2nd                0xff000000
+
+#define bSIGEVM                  0xff
+#define bPWDB                    0xff00
+#define bSGIEN                   0x10000
+
+#define bSFactorQAM1             0xf
+#define bSFactorQAM2             0xf0
+#define bSFactorQAM3             0xf00
+#define bSFactorQAM4             0xf000
+#define bSFactorQAM5             0xf0000
+#define bSFactorQAM6             0xf0000
+#define bSFactorQAM7             0xf00000
+#define bSFactorQAM8             0xf000000
+#define bSFactorQAM9             0xf0000000
+#define bCSIScheme               0x100000
+
+#define bNoiseLvlTopSet          0x3
+#define bChSmooth                0x4
+#define bChSmoothCfg1            0x38
+#define bChSmoothCfg2            0x1c0
+#define bChSmoothCfg3            0xe00
+#define bChSmoothCfg4            0x7000
+#define bMRCMode                 0x800000
+#define bTHEVMCfg                0x7000000
+
+#define bLoopFitType             0x1
+#define bUpdCFO                  0x40
+#define bUpdCFOOffData           0x80
+#define bAdvUpdCFO               0x100
+#define bAdvTimeCtrl             0x800
+#define bUpdClko                 0x1000
+#define bFC                      0x6000
+#define bTrackingMode            0x8000
+#define bPhCmpEnable             0x10000
+#define bUpdClkoLTF              0x20000
+#define bComChCFO                0x40000
+#define bCSIEstiMode             0x80000
+#define bAdvUpdEqz               0x100000
+#define bUChCfg                  0x7000000
+#define bUpdEqz                  0x8000000
+
+//page e
+#define bTxAGCRate18_06			0x7f7f7f7f
+#define bTxAGCRate54_24			0x7f7f7f7f
+#define bTxAGCRateMCS32		0x7f
+#define bTxAGCRateCCK			0x7f00
+#define bTxAGCRateMCS3_MCS0	0x7f7f7f7f
+#define bTxAGCRateMCS7_MCS4	0x7f7f7f7f
+#define bTxAGCRateMCS11_MCS8	0x7f7f7f7f
+#define bTxAGCRateMCS15_MCS12	0x7f7f7f7f
+
+
+//Rx Pseduo noise
+#define bRxPesudoNoiseOn         0x20000000
+#define bRxPesudoNoise_A         0xff
+#define bRxPesudoNoise_B         0xff00
+#define bRxPesudoNoise_C         0xff0000
+#define bRxPesudoNoise_D         0xff000000
+#define bPesudoNoiseState_A      0xffff
+#define bPesudoNoiseState_B      0xffff0000
+#define bPesudoNoiseState_C      0xffff
+#define bPesudoNoiseState_D      0xffff0000
+
+//RF
+//Zebra1
+#define bZebra1_HSSIEnable        0x8
+#define bZebra1_TRxControl        0xc00
+#define bZebra1_TRxGainSetting    0x07f
+#define bZebra1_RxCorner          0xc00
+#define bZebra1_TxChargePump      0x38
+#define bZebra1_RxChargePump      0x7
+#define bZebra1_ChannelNum        0xf80
+#define bZebra1_TxLPFBW           0x400
+#define bZebra1_RxLPFBW           0x600
+
+//Zebra4
+#define bRTL8256RegModeCtrl1      0x100
+#define bRTL8256RegModeCtrl0      0x40
+#define bRTL8256_TxLPFBW          0x18
+#define bRTL8256_RxLPFBW          0x600
+
+//RTL8258
+#define bRTL8258_TxLPFBW          0xc
+#define bRTL8258_RxLPFBW          0xc00
+#define bRTL8258_RSSILPFBW        0xc0
+
+//byte endable for sb_write
+#define bByte0                    0x1
+#define bByte1                    0x2
+#define bByte2                    0x4
+#define bByte3                    0x8
+#define bWord0                    0x3
+#define bWord1                    0xc
+#define bDWord                    0xf
+
+//for PutRegsetting & GetRegSetting BitMask
+#define bMaskByte0                0xff
+#define bMaskByte1                0xff00
+#define bMaskByte2                0xff0000
+#define bMaskByte3                0xff000000
+#define bMaskHWord                0xffff0000
+#define bMaskLWord                0x0000ffff
+#define bMaskDWord                0xffffffff
+
+//for PutRFRegsetting & GetRFRegSetting BitMask
+#define bMask12Bits               0xfff
+
+#define bEnable                   0x1
+#define bDisable                  0x0
+
+#define LeftAntenna               0x0
+#define RightAntenna              0x1
+
+#define tCheckTxStatus            500   //500ms
+#define tUpdateRxCounter          100   //100ms
+
+#define rateCCK     0
+#define rateOFDM    1
+#define rateHT      2
+
+//define Register-End
+#define bPMAC_End                 0x1ff
+#define bFPGAPHY0_End             0x8ff
+#define bFPGAPHY1_End             0x9ff
+#define bCCKPHY0_End              0xaff
+#define bOFDMPHY0_End             0xcff
+#define bOFDMPHY1_End             0xdff
+
+//define max debug item in each debug page
+//#define bMaxItem_FPGA_PHY0        0x9
+//#define bMaxItem_FPGA_PHY1        0x3
+//#define bMaxItem_PHY_11B          0x16
+//#define bMaxItem_OFDM_PHY0        0x29
+//#define bMaxItem_OFDM_PHY1        0x0
+
+#define bPMACControl              0x0
+#define bWMACControl              0x1
+#define bWNICControl              0x2
+
+#define PathA                     0x0
+#define PathB                     0x1
+#define PathC                     0x2
+#define PathD                     0x3
+
+#define	rRTL8256RxMixerPole		0xb
+#define 	bZebraRxMixerPole		0x6
+#define 	rRTL8256TxBBOPBias        0x9
+#define 	bRTL8256TxBBOPBias       0x400
+#define 	rRTL8256TxBBBW             19
+#define 	bRTL8256TxBBBW            	0x18
+
+#endif	//__INC_HAL8190PCIPHYREG_H
diff --git a/drivers/staging/serqt_usb/Makefile b/drivers/staging/serqt_usb/Makefile
deleted file mode 100644
index 4fd1da2..0000000
--- a/drivers/staging/serqt_usb/Makefile
+++ /dev/null
@@ -1 +0,0 @@
-obj-$(CONFIG_USB_SERIAL_QUATECH_ESU100)		+= serqt_usb.o
diff --git a/drivers/staging/serqt_usb/serqt_usb.c b/drivers/staging/serqt_usb/serqt_usb.c
deleted file mode 100644
index 234f332..0000000
--- a/drivers/staging/serqt_usb/serqt_usb.c
+++ /dev/null
@@ -1,2656 +0,0 @@
-/*
- * This code was developed for the Quatech USB line for linux, it used
- * much of the code developed by Greg Kroah-Hartman for USB serial devices
- *
- */
-
-#include <linux/sched.h>
-#include <linux/slab.h>
-#include <linux/tty.h>
-#include <linux/tty_flip.h>
-#include <linux/module.h>
-#include <linux/usb.h>
-#include <linux/wait.h>
-#include <linux/types.h>
-#include <linux/version.h>
-#include <linux/uaccess.h>
-
-/* Use our own dbg macro */
-/* #define DEBUG_ON */
-/* #undef dbg */
-#ifdef DEBUG_ON
-#define  mydbg(const...)    printk(const)
-#else
-#define  mydbg(const...)
-#endif
-
-/* parity check flag */
-#define RELEVANT_IFLAG(iflag)	(iflag & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))
-
-#define SERIAL_TTY_MAJOR	        0	/* Nice legal number now */
-#define SERIAL_TTY_MINORS	        255	/* loads of devices :) */
-#define MAX_NUM_PORTS		        8	/* The maximum number of ports one device can grab at once */
-#define PREFUFF_LEVEL_CONSERVATIVE  128
-#define ATC_DISABLED                0x00
-
-#define RR_BITS             0x03	/* for clearing clock bits */
-#define DUPMODE_BITS        0xc0
-
-#define RS232_MODE          0x00
-#define RTSCTS_TO_CONNECTOR 0x40
-#define CLKS_X4             0x02
-
-#define LOOPMODE_BITS       0x41	/* LOOP1 = b6, LOOP0 = b0 (PORT B) */
-#define ALL_LOOPBACK        0x01
-#define MODEM_CTRL          0x40
-
-#define THISCHAR                    data[i]
-#define NEXTCHAR                    data[i + 1]
-#define THIRDCHAR                  data[i + 2]
-#define FOURTHCHAR                  data[i + 3]
-
-/*
- * Useful defintions for port A, Port B and Port C
- */
-#define FULLPWRBIT          0x00000080
-#define NEXT_BOARD_POWER_BIT        0x00000004
-
-#define SERIAL_LSR_OE       0x02
-#define SERIAL_LSR_PE       0x04
-#define SERIAL_LSR_FE       0x08
-#define SERIAL_LSR_BI       0x10
-
-#define SERIAL_LSR_TEMT     0x40
-
-#define  DIV_LATCH_LS               0x00
-#define  XMT_HOLD_REGISTER          0x00
-#define  XVR_BUFFER_REGISTER        0x00
-#define  DIV_LATCH_MS               0x01
-#define  FIFO_CONTROL_REGISTER      0x02
-#define  LINE_CONTROL_REGISTER      0x03
-#define  MODEM_CONTROL_REGISTER     0x04
-#define  LINE_STATUS_REGISTER       0x05
-#define  MODEM_STATUS_REGISTER      0x06
-
-#define  SERIAL_MCR_DTR             0x01
-#define  SERIAL_MCR_RTS             0x02
-#define  SERIAL_MCR_LOOP            0x10
-
-#define  SERIAL_MSR_CTS             0x10
-#define  SERIAL_MSR_CD              0x80
-#define  SERIAL_MSR_RI              0x40
-#define  SERIAL_MSR_DSR             0x20
-#define  SERIAL_MSR_MASK            0xf0
-
-#define  SERIAL_8_DATA              0x03
-#define  SERIAL_7_DATA              0x02
-#define  SERIAL_6_DATA              0x01
-#define  SERIAL_5_DATA              0x00
-
-#define  SERIAL_ODD_PARITY          0X08
-#define  SERIAL_EVEN_PARITY         0X18
-#define  SERIAL_TWO_STOPB           0x04
-#define  SERIAL_ONE_STOPB           0x00
-
-#define  MAX_BAUD_RATE              460800
-#define  MAX_BAUD_REMAINDER         4608
-
-#define QT_SET_GET_DEVICE           0xc2
-#define QT_OPEN_CLOSE_CHANNEL       0xca
-#define QT_GET_SET_PREBUF_TRIG_LVL  0xcc
-#define QT_SET_ATF                  0xcd
-#define QT_GET_SET_REGISTER         0xc0
-#define QT_GET_SET_UART             0xc1
-#define QT_HW_FLOW_CONTROL_MASK     0xc5
-#define QT_SW_FLOW_CONTROL_MASK     0xc6
-#define QT_SW_FLOW_CONTROL_DISABLE  0xc7
-#define QT_BREAK_CONTROL            0xc8
-
-#define SERIALQT_PCI_IOC_MAGIC 'k'
-#define SERIALQT_WRITE_QOPR _IOW(SERIALQT_PCI_IOC_MAGIC, 0, int)
-#define SERIALQT_WRITE_QMCR _IOW(SERIALQT_PCI_IOC_MAGIC, 1, int)
-#define SERIALQT_GET_NUMOF_UNITS _IOR(SERIALQT_PCI_IOC_MAGIC, 2, void *)
-#define SERIALQT_GET_THIS_UNIT _IOR(SERIALQT_PCI_IOC_MAGIC, 3, void *)
-#define SERIALQT_READ_QOPR _IOR(SERIALQT_PCI_IOC_MAGIC, 4, int)
-#define SERIALQT_READ_QMCR _IOR(SERIALQT_PCI_IOC_MAGIC, 5, int)
-#define SERIALQT_IS422_EXTENDED _IOR(SERIALQT_PCI_IOC_MAGIC, 6, int)	/* returns successful if 422 extended */
-
-#define USBD_TRANSFER_DIRECTION_IN    0xc0
-#define USBD_TRANSFER_DIRECTION_OUT   0x40
-
-#define ATC_DISABLED                0x00
-#define ATC_RTS_ENABLED                 0x02
-#define ATC_DTR_ENABLED                 0x01
-
-#define RR_BITS             0x03	/* for clearing clock bits */
-#define DUPMODE_BITS        0xc0
-
-#define FULL_DUPLEX         0x00
-#define HALF_DUPLEX_RTS     0x40
-#define HALF_DUPLEX_DTR     0x80
-
-#define QMCR_FULL_DUPLEX  0x00
-#define QMCR_HALF_DUPLEX_RTS 0x02
-#define QMCR_HALF_DUPLEX_DTR 0x01
-#define QMCR_HALF_DUPLEX_MASK 0x03
-#define QMCR_CONNECTOR_MASK 0x1C
-
-#define QMCR_RX_EN_MASK 0x20
-
-#define QMCR_ALL_LOOPBACK    0x10
-#define QMCR_MODEM_CONTROL   0X00
-
-#define SERIALQT_IOC_MAXNR 6
-
-struct usb_serial_port {
-	struct usb_serial *serial;	/* pointer back to the owner of this port */
-	struct tty_struct *tty;	/* the coresponding tty for this port */
-	unsigned char number;
-	char active;		/* someone has this device open */
-
-	unsigned char *interrupt_in_buffer;
-	struct urb *interrupt_in_urb;
-	__u8 interrupt_in_endpointAddress;
-
-	unsigned char *bulk_in_buffer;
-	unsigned char *xfer_to_tty_buffer;
-	struct urb *read_urb;
-	__u8 bulk_in_endpointAddress;
-
-	unsigned char *bulk_out_buffer;
-	int bulk_out_size;
-	struct urb *write_urb;
-	__u8 bulk_out_endpointAddress;
-
-	wait_queue_head_t write_wait;
-	wait_queue_head_t wait;
-	struct work_struct work;
-
-	int open_count;		/* number of times this port has been opened */
-	struct semaphore sem;	/* locks this structure */
-
-	__u8 shadowLCR;		/* last LCR value received */
-	__u8 shadowMCR;		/* last MCR value received */
-	__u8 shadowMSR;		/* last MSR value received */
-	__u8 shadowLSR;		/* last LSR value received */
-	int RxHolding;
-	char closePending;
-	int ReadBulkStopped;
-
-	void *private;		/* data private to the specific port */
-};
-
-struct identity {
-	int index;
-	int n_identity;
-};
-
-struct usb_serial {
-	struct usb_device *dev;
-	struct usb_interface *interface;	/* the interface for this device */
-	struct tty_driver *tty_driver;	/* the tty_driver for this device */
-	unsigned char minor;	/* the starting minor number for this device */
-	unsigned char num_ports;	/* the number of ports this device has */
-	char num_interrupt_in;	/* number of interrupt in endpoints we have */
-	char num_bulk_in;	/* number of bulk in endpoints we have */
-	char num_bulk_out;	/* number of bulk out endpoints we have */
-	unsigned char num_OpenCount;	/* the number of ports this device has */
-
-	__u16 vendor;		/* vendor id of this device */
-	__u16 product;		/* product id of this device */
-	struct usb_serial_port port[MAX_NUM_PORTS];
-
-	void *private;		/* data private to the specific driver */
-};
-
-static inline int port_paranoia_check(struct usb_serial_port *port,
-				      const char *function)
-{
-	if (!port) {
-		dbg("%s - port == NULL", function);
-		return -1;
-	}
-	if (!port->serial) {
-		dbg("%s - port->serial == NULL\n", function);
-		return -1;
-	}
-	if (!port->tty) {
-		dbg("%s - port->tty == NULL\n", function);
-		return -1;
-	}
-
-	return 0;
-}
-
-/* Inline functions to check the sanity of a pointer that is passed to us */
-static inline int serial_paranoia_check(struct usb_serial *serial,
-					const char *function)
-{
-	if (!serial) {
-		dbg("%s - serial == NULL\n", function);
-		return -1;
-	}
-
-	return 0;
-}
-
-static inline struct usb_serial *get_usb_serial(struct usb_serial_port *port,
-						const char *function)
-{
-	/* if no port was specified, or it fails a paranoia check */
-	if (!port ||
-	    port_paranoia_check(port, function) ||
-	    serial_paranoia_check(port->serial, function)) {
-		/* then say that we dont have a valid usb_serial thing, which will
-		 * end up genrating -ENODEV return values */
-		return NULL;
-	}
-
-	return port->serial;
-}
-
-struct qt_get_device_data {
-	__u8 porta;
-	__u8 portb;
-	__u8 portc;
-};
-
-struct qt_open_channel_data {
-	__u8 line_status;
-	__u8 modem_status;
-};
-
-static void ProcessLineStatus(struct usb_serial_port *port,
-			      unsigned char line_status);
-static void ProcessModemStatus(struct usb_serial_port *port,
-			       unsigned char modem_status);
-static void ProcessRxChar(struct usb_serial_port *port, unsigned char Data);
-static struct usb_serial *get_free_serial(int num_ports, int *minor);
-
-static int serqt_probe(struct usb_interface *interface,
-		       const struct usb_device_id *id);
-
-static void serqt_usb_disconnect(struct usb_interface *interface);
-static int box_set_device(struct usb_serial *serial,
-			  struct qt_get_device_data *pDeviceData);
-static int box_get_device(struct usb_serial *serial,
-			  struct qt_get_device_data *pDeviceData);
-static int serial_open(struct tty_struct *tty, struct file *filp);
-static void serial_close(struct tty_struct *tty, struct file *filp);
-static int serial_write_room(struct tty_struct *tty);
-static int serial_ioctl(struct tty_struct *tty, struct file *file,
-			unsigned int cmd, unsigned long arg);
-static void serial_set_termios(struct tty_struct *tty, struct ktermios *old);
-static int serial_write(struct tty_struct *tty, const unsigned char *buf,
-			int count);
-
-static void serial_throttle(struct tty_struct *tty);
-static void serial_unthrottle(struct tty_struct *tty);
-static int serial_break(struct tty_struct *tty, int break_state);
-static int serial_chars_in_buffer(struct tty_struct *tty);
-
-static int qt_open(struct tty_struct *tty, struct usb_serial_port *port,
-				struct file *filp);
-static int BoxSetPrebufferLevel(struct usb_serial *serial);
-
-static int BoxSetATC(struct usb_serial *serial, __u16 n_Mode);
-static int BoxSetUart(struct usb_serial *serial, unsigned short Uart_Number,
-		      unsigned short default_divisor,
-		      unsigned char default_LCR);
-
-static int BoxOPenCloseChannel(struct usb_serial *serial, __u16 Uart_Number,
-			       __u16 OpenClose,
-			       struct qt_open_channel_data *pDeviceData);
-static void qt_close(struct tty_struct *tty, struct usb_serial_port *port,
-					struct file *filp);
-static int BoxGetRegister(struct usb_serial *serial, unsigned short Uart_Number,
-			  unsigned short Register_Num, __u8 *pValue);
-static int BoxSetRegister(struct usb_serial *serial, unsigned short Uart_Number,
-			  unsigned short Register_Num, unsigned short Value);
-static void qt_write_bulk_callback(struct urb *urb);
-static int qt_write(struct tty_struct *tty, struct usb_serial_port *port,
-		    const unsigned char *buf, int count);
-static void port_softint(struct work_struct *work);
-static int qt_write_room(struct usb_serial_port *port);
-static int qt_chars_in_buffer(struct usb_serial_port *port);
-static int qt_ioctl(struct tty_struct *tty, struct usb_serial_port *port,
-		struct file *file, unsigned int cmd, unsigned long arg);
-static void qt_set_termios(struct tty_struct *tty,
-			   struct usb_serial_port *port,
-			   struct ktermios *old_termios);
-static int BoxSetHW_FlowCtrl(struct usb_serial *serial, unsigned int index,
-			     int bSet);
-static int BoxDisable_SW_FlowCtrl(struct usb_serial *serial, __u16 index);
-static int EmulateWriteQMCR_Reg(int index, unsigned uc_value);
-static int EmulateReadQMCR_Reg(int index, unsigned *uc_value);
-static struct usb_serial *find_the_box(unsigned int index);
-static int ioctl_serial_usb(struct inode *innod, struct file *filp, unsigned int cmd,
-		     unsigned long arg);
-
-static int BoxSetSW_FlowCtrl(struct usb_serial *serial, __u16 Uart,
-			     unsigned char stop_char, unsigned char start_char);
-static void qt_read_bulk_callback(struct urb *urb);
-
-static void port_sofrint(void *private);
-
-static void return_serial(struct usb_serial *serial);
-
-static int serial_tiocmset(struct tty_struct *tty, struct file *file,
-			   unsigned int set, unsigned int clear);
-static int serial_tiocmget(struct tty_struct *tty, struct file *file);
-
-static int qt_tiocmset(struct tty_struct *tty, struct usb_serial_port *port,
-		       struct file *file, unsigned int value);
-
-static int qt_tiocmget(struct tty_struct *tty, struct usb_serial_port *port,
-							struct file *file);
-
-/* Version Information */
-#define DRIVER_VERSION "v2.14"
-#define DRIVER_AUTHOR "Tim Gobeli, Quatech, Inc"
-#define DRIVER_DESC "Quatech USB to Serial Driver"
-
-#define	USB_VENDOR_ID_QUATECH			0x061d	/* Quatech VID */
-#define DEVICE_ID_QUATECH_RS232_SINGLE_PORT	0xC020	/* SSU100 */
-#define DEVICE_ID_QUATECH_RS422_SINGLE_PORT	0xC030	/* SSU200 */
-#define DEVICE_ID_QUATECH_RS232_DUAL_PORT	0xC040	/* DSU100 */
-#define DEVICE_ID_QUATECH_RS422_DUAL_PORT	0xC050	/* DSU200 */
-#define DEVICE_ID_QUATECH_RS232_FOUR_PORT	0xC060	/* QSU100 */
-#define DEVICE_ID_QUATECH_RS422_FOUR_PORT	0xC070	/* QSU200 */
-#define DEVICE_ID_QUATECH_RS232_EIGHT_PORT_A	0xC080	/* ESU100A */
-#define DEVICE_ID_QUATECH_RS232_EIGHT_PORT_B	0xC081	/* ESU100B */
-#define DEVICE_ID_QUATECH_RS422_EIGHT_PORT_A	0xC0A0	/* ESU200A */
-#define DEVICE_ID_QUATECH_RS422_EIGHT_PORT_B	0xC0A1	/* ESU200B */
-#define DEVICE_ID_QUATECH_RS232_16_PORT_A	0xC090	/* HSU100A */
-#define DEVICE_ID_QUATECH_RS232_16_PORT_B	0xC091	/* HSU100B */
-#define DEVICE_ID_QUATECH_RS232_16_PORT_C	0xC092	/* HSU100C */
-#define DEVICE_ID_QUATECH_RS232_16_PORT_D	0xC093	/* HSU100D */
-#define DEVICE_ID_QUATECH_RS422_16_PORT_A	0xC0B0	/* HSU200A */
-#define DEVICE_ID_QUATECH_RS422_16_PORT_B	0xC0B1	/* HSU200B */
-#define DEVICE_ID_QUATECH_RS422_16_PORT_C	0xC0B2	/* HSU200C */
-#define DEVICE_ID_QUATECH_RS422_16_PORT_D	0xC0B3	/* HSU200D */
-
-/* table of Quatech devices  */
-static struct usb_device_id serqt_table[] = {
-	{USB_DEVICE
-	 (USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS232_SINGLE_PORT)},
-	{USB_DEVICE
-	 (USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS422_SINGLE_PORT)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS232_DUAL_PORT)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS422_DUAL_PORT)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS232_FOUR_PORT)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS422_FOUR_PORT)},
-	{USB_DEVICE
-	 (USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS232_EIGHT_PORT_A)},
-	{USB_DEVICE
-	 (USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS232_EIGHT_PORT_B)},
-	{USB_DEVICE
-	 (USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS422_EIGHT_PORT_A)},
-	{USB_DEVICE
-	 (USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS422_EIGHT_PORT_B)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS232_16_PORT_A)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS232_16_PORT_B)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS232_16_PORT_C)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS232_16_PORT_D)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS422_16_PORT_A)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS422_16_PORT_B)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS422_16_PORT_C)},
-	{USB_DEVICE(USB_VENDOR_ID_QUATECH, DEVICE_ID_QUATECH_RS422_16_PORT_D)},
-	{}			/* Terminating entry */
-};
-
-MODULE_DEVICE_TABLE(usb, serqt_table);
-
-static int major_number;
-static struct usb_serial *serial_table[SERIAL_TTY_MINORS];	/* initially all NULL */
-
-/* table of Quatech 422devices  */
-static unsigned int serqt_422_table[] = {
-	DEVICE_ID_QUATECH_RS422_SINGLE_PORT,
-	DEVICE_ID_QUATECH_RS422_DUAL_PORT,
-	DEVICE_ID_QUATECH_RS422_FOUR_PORT,
-	DEVICE_ID_QUATECH_RS422_EIGHT_PORT_A,
-	DEVICE_ID_QUATECH_RS422_EIGHT_PORT_B,
-	DEVICE_ID_QUATECH_RS422_16_PORT_A,
-	DEVICE_ID_QUATECH_RS422_16_PORT_B,
-	DEVICE_ID_QUATECH_RS422_16_PORT_C,
-	DEVICE_ID_QUATECH_RS422_16_PORT_D,
-	0			/* terminate with zero */
-};
-
-/* usb specific object needed to register this driver with the usb subsystem */
-static struct usb_driver serqt_usb_driver = {
-	.name = "quatech-usb-serial",
-	.probe = serqt_probe,
-	.disconnect = serqt_usb_disconnect,
-	.id_table = serqt_table,
-};
-
-static struct ktermios *serial_termios[SERIAL_TTY_MINORS];
-static struct ktermios *serial_termios_locked[SERIAL_TTY_MINORS];
-
-static const struct tty_operations serial_ops = {
-	.open = serial_open,
-	.close = serial_close,
-	.write = serial_write,
-	.write_room = serial_write_room,
-	.ioctl = serial_ioctl,
-	.set_termios = serial_set_termios,
-	.throttle = serial_throttle,
-	.unthrottle = serial_unthrottle,
-	.break_ctl = serial_break,
-	.chars_in_buffer = serial_chars_in_buffer,
-	.tiocmset = serial_tiocmset,
-	.tiocmget = serial_tiocmget,
-};
-
-static struct tty_driver serial_tty_driver = {
-	.magic = TTY_DRIVER_MAGIC,
-	.driver_name = "Quatech usb-serial",
-	.name = "ttyQT_USB",
-	.major = SERIAL_TTY_MAJOR,
-	.minor_start = 0,
-	.num = SERIAL_TTY_MINORS,
-	.type = TTY_DRIVER_TYPE_SERIAL,
-	.subtype = SERIAL_TYPE_NORMAL,
-	.flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV,
-
-	.termios = serial_termios,
-	.termios_locked = serial_termios_locked,
-	.init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL,
-
-	.init_termios.c_iflag = ICRNL | IXON,
-	.init_termios.c_oflag = OPOST,
-
-	.init_termios.c_lflag =
-	    ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN,
-};
-
-/* fops for parent device */
-static const struct file_operations serialqt_usb_fops = {
-	.ioctl = ioctl_serial_usb,
-};
-
- /**
- *	  serqt_probe
- *
- *	Called by the usb core when a new device is connected that it thinks
- *	this driver might be interested in.
- *
- */
-static int serqt_probe(struct usb_interface *interface,
-		       const struct usb_device_id *id)
-{
-	struct usb_device *dev = interface_to_usbdev(interface);
-	struct usb_serial *serial = NULL;
-	struct usb_serial_port *port;
-	struct usb_endpoint_descriptor *endpoint;
-	struct usb_endpoint_descriptor *interrupt_in_endpoint[MAX_NUM_PORTS];
-	struct usb_endpoint_descriptor *bulk_in_endpoint[MAX_NUM_PORTS];
-	struct usb_endpoint_descriptor *bulk_out_endpoint[MAX_NUM_PORTS];
-	int minor;
-	int buffer_size;
-	int i;
-	struct usb_host_interface *iface_desc;
-	int num_interrupt_in = 0;
-	int num_bulk_in = 0;
-	int num_bulk_out = 0;
-	int num_ports;
-	struct qt_get_device_data DeviceData;
-	int status;
-
-	mydbg("In %s\n", __func__);
-
-	/* let's find the endpoints needed */
-	/* check out the endpoints */
-	iface_desc = interface->cur_altsetting;;
-	for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
-		endpoint = &iface_desc->endpoint[i].desc;
-
-		if ((endpoint->bEndpointAddress & 0x80) &&
-		    ((endpoint->bmAttributes & 3) == 0x02)) {
-			/* we found a bulk in endpoint */
-			mydbg("found bulk in");
-			bulk_in_endpoint[num_bulk_in] = endpoint;
-			++num_bulk_in;
-		}
-
-		if (((endpoint->bEndpointAddress & 0x80) == 0x00) &&
-		    ((endpoint->bmAttributes & 3) == 0x02)) {
-			/* we found a bulk out endpoint */
-			mydbg("found bulk out\n");
-			bulk_out_endpoint[num_bulk_out] = endpoint;
-			++num_bulk_out;
-		}
-
-		if ((endpoint->bEndpointAddress & 0x80) &&
-		    ((endpoint->bmAttributes & 3) == 0x03)) {
-			/* we found a interrupt in endpoint */
-			mydbg("found interrupt in\n");
-			interrupt_in_endpoint[num_interrupt_in] = endpoint;
-			++num_interrupt_in;
-		}
-	}
-
-	/* found all that we need */
-	dev_info(&interface->dev, "Quatech converter detected\n");
-	num_ports = num_bulk_out;
-	if (num_ports == 0) {
-		err("Quatech device with no bulk out, not allowed.");
-		return -ENODEV;
-
-	}
-
-	serial = get_free_serial(num_ports, &minor);
-	if (serial == NULL) {
-		err("No more free serial devices");
-		return -ENODEV;
-	}
-
-	serial->dev = dev;
-	serial->interface = interface;
-	serial->minor = minor;
-	serial->num_ports = num_ports;
-	serial->num_bulk_in = num_bulk_in;
-	serial->num_bulk_out = num_bulk_out;
-	serial->num_interrupt_in = num_interrupt_in;
-	serial->vendor = dev->descriptor.idVendor;
-	serial->product = dev->descriptor.idProduct;
-
-	/* set up the endpoint information */
-	for (i = 0; i < num_bulk_in; ++i) {
-		endpoint = bulk_in_endpoint[i];
-		port = &serial->port[i];
-		port->read_urb = usb_alloc_urb(0, GFP_KERNEL);
-		if (!port->read_urb) {
-			err("No free urbs available");
-			goto probe_error;
-		}
-		buffer_size = endpoint->wMaxPacketSize;
-		port->bulk_in_endpointAddress = endpoint->bEndpointAddress;
-		port->bulk_in_buffer = kmalloc(buffer_size, GFP_KERNEL);
-		port->xfer_to_tty_buffer = kmalloc(buffer_size, GFP_KERNEL);
-		if (!port->bulk_in_buffer) {
-			err("Couldn't allocate bulk_in_buffer");
-			goto probe_error;
-		}
-		usb_fill_bulk_urb(port->read_urb, dev,
-				  usb_rcvbulkpipe(dev,
-						  endpoint->bEndpointAddress),
-				  port->bulk_in_buffer, buffer_size,
-				  qt_read_bulk_callback, port);
-	}
-
-	for (i = 0; i < num_bulk_out; ++i) {
-		endpoint = bulk_out_endpoint[i];
-		port = &serial->port[i];
-		port->write_urb = usb_alloc_urb(0, GFP_KERNEL);
-		if (!port->write_urb) {
-			err("No free urbs available");
-			goto probe_error;
-		}
-		buffer_size = endpoint->wMaxPacketSize;
-		port->bulk_out_size = buffer_size;
-		port->bulk_out_endpointAddress = endpoint->bEndpointAddress;
-		port->bulk_out_buffer = kmalloc(buffer_size, GFP_KERNEL);
-		if (!port->bulk_out_buffer) {
-			err("Couldn't allocate bulk_out_buffer");
-			goto probe_error;
-		}
-		usb_fill_bulk_urb(port->write_urb, dev,
-				  usb_sndbulkpipe(dev,
-						  endpoint->bEndpointAddress),
-				  port->bulk_out_buffer, buffer_size,
-				  qt_write_bulk_callback, port);
-
-	}
-
-	/* For us numb of bulkin  or out = number of ports */
-	mydbg("%s - setting up %d port structures for this device\n",
-	      __func__, num_bulk_in);
-	for (i = 0; i < num_bulk_in; ++i) {
-		port = &serial->port[i];
-		port->number = i + serial->minor;
-		port->serial = serial;
-
-		INIT_WORK(&port->work, port_softint);
-
-		init_MUTEX(&port->sem);
-
-	}
-	status = box_get_device(serial, &DeviceData);
-	if (status < 0) {
-		mydbg(__FILE__ "box_get_device failed");
-		goto probe_error;
-	}
-
-	mydbg(__FILE__ "DeviceData.portb = 0x%x", DeviceData.portb);
-
-	DeviceData.portb &= ~FULLPWRBIT;
-	mydbg(__FILE__ "Changing DeviceData.portb to 0x%x", DeviceData.portb);
-
-	status = box_set_device(serial, &DeviceData);
-	if (status < 0) {
-		mydbg(__FILE__ "box_set_device failed\n");
-		goto probe_error;
-	}
-
-	/* initialize the devfs nodes for this device and let the user know what ports we are bound to */
-	for (i = 0; i < serial->num_ports; ++i) {
-		dev_info(&interface->dev,
-			 "Converter now attached to ttyUSB%d (or usb/tts/%d for devfs)",
-			 serial->port[i].number, serial->port[i].number);
-	}
-
-	/* usb_serial_console_init (debug, minor); */
-
-	/***********TAG add start next board here ****/
-	status = box_get_device(serial, &DeviceData);
-	if (status < 0) {
-		mydbg(__FILE__ "box_get_device failed");
-		goto probe_error;
-	}
-	/*
-	 * and before we power up lets initialiaze parnent device stuff here before
-	 * we set thmem via any other method such as the property pages
-	 */
-	switch (serial->product) {
-	case DEVICE_ID_QUATECH_RS232_SINGLE_PORT:
-	case DEVICE_ID_QUATECH_RS232_DUAL_PORT:
-	case DEVICE_ID_QUATECH_RS232_FOUR_PORT:
-	case DEVICE_ID_QUATECH_RS232_EIGHT_PORT_A:
-	case DEVICE_ID_QUATECH_RS232_EIGHT_PORT_B:
-	case DEVICE_ID_QUATECH_RS232_16_PORT_A:
-	case DEVICE_ID_QUATECH_RS232_16_PORT_B:
-	case DEVICE_ID_QUATECH_RS232_16_PORT_C:
-	case DEVICE_ID_QUATECH_RS232_16_PORT_D:
-		DeviceData.porta &= ~(RR_BITS | DUPMODE_BITS);
-		DeviceData.porta |= CLKS_X4;
-		DeviceData.portb &= ~(LOOPMODE_BITS);
-		DeviceData.portb |= RS232_MODE;
-		break;
-
-	case DEVICE_ID_QUATECH_RS422_SINGLE_PORT:
-	case DEVICE_ID_QUATECH_RS422_DUAL_PORT:
-	case DEVICE_ID_QUATECH_RS422_FOUR_PORT:
-	case DEVICE_ID_QUATECH_RS422_EIGHT_PORT_A:
-	case DEVICE_ID_QUATECH_RS422_EIGHT_PORT_B:
-	case DEVICE_ID_QUATECH_RS422_16_PORT_A:
-	case DEVICE_ID_QUATECH_RS422_16_PORT_B:
-	case DEVICE_ID_QUATECH_RS422_16_PORT_C:
-	case DEVICE_ID_QUATECH_RS422_16_PORT_D:
-		DeviceData.porta &= ~(RR_BITS | DUPMODE_BITS);
-		DeviceData.porta |= CLKS_X4;
-		DeviceData.portb &= ~(LOOPMODE_BITS);
-		DeviceData.portb |= ALL_LOOPBACK;
-		break;
-	default:
-		DeviceData.porta &= ~(RR_BITS | DUPMODE_BITS);
-		DeviceData.porta |= CLKS_X4;
-		DeviceData.portb &= ~(LOOPMODE_BITS);
-		DeviceData.portb |= RS232_MODE;
-		break;
-
-	}
-	status = BoxSetPrebufferLevel(serial);	/* sets to default vaue */
-	if (status < 0) {
-		mydbg(__FILE__ "BoxSetPrebufferLevel failed\n");
-		goto probe_error;
-	}
-
-	status = BoxSetATC(serial, ATC_DISABLED);
-	if (status < 0) {
-		mydbg(__FILE__ "BoxSetATC failed\n");
-		goto probe_error;
-	}
-	/**********************************************************/
-	mydbg(__FILE__ "DeviceData.portb = 0x%x", DeviceData.portb);
-
-	DeviceData.portb |= NEXT_BOARD_POWER_BIT;
-	mydbg(__FILE__ "Changing DeviceData.portb to 0x%x", DeviceData.portb);
-
-	status = box_set_device(serial, &DeviceData);
-	if (status < 0) {
-		mydbg(__FILE__ "box_set_device failed\n");
-		goto probe_error;
-	}
-
-	mydbg("Exit Success %s\n", __func__);
-
-	usb_set_intfdata(interface, serial);
-	return 0;
-
-probe_error:
-
-	for (i = 0; i < num_bulk_in; ++i) {
-		port = &serial->port[i];
-		usb_free_urb(port->read_urb);
-		kfree(port->bulk_in_buffer);
-	}
-	for (i = 0; i < num_bulk_out; ++i) {
-		port = &serial->port[i];
-		usb_free_urb(port->write_urb);
-		kfree(port->bulk_out_buffer);
-		kfree(port->xfer_to_tty_buffer);
-	}
-	for (i = 0; i < num_interrupt_in; ++i) {
-		port = &serial->port[i];
-		usb_free_urb(port->interrupt_in_urb);
-		kfree(port->interrupt_in_buffer);
-	}
-
-	/* return the minor range that this device had */
-	return_serial(serial);
-	mydbg("Exit fail %s\n", __func__);
-
-	/* free up any memory that we allocated */
-	kfree(serial);
-	return -EIO;
-}
-
-/*
- * returns the serial_table array pointers that are taken
- * up in consecutive positions for each port to a common usb_serial structure
- * back to NULL
- */
-static void return_serial(struct usb_serial *serial)
-{
-	int i;
-
-	mydbg("%s\n", __func__);
-
-	if (serial == NULL)
-		return;
-
-	for (i = 0; i < serial->num_ports; ++i)
-		serial_table[serial->minor + i] = NULL;
-
-	return;
-}
-
-/*
- * Finds the first locatio int the serial_table array where it can fit
- * num_ports number of consecutive points to a common usb_serial
- * structure,allocates a stucture points to it in all the structures, and
- * returns the index to the first location in the array in the "minor"
- * variable.
- */
-static struct usb_serial *get_free_serial(int num_ports, int *minor)
-{
-	struct usb_serial *serial = NULL;
-	int i, j;
-	int good_spot;
-
-	mydbg("%s %d\n", __func__, num_ports);
-
-	*minor = 0;
-	for (i = 0; i < SERIAL_TTY_MINORS; ++i) {
-		if (serial_table[i])
-			continue;
-
-		good_spot = 1;
-		/*
-		 * find a spot in the array where you can fit consecutive
-		 * positions to put the pointers to the usb_serail allocated
-		 * structure for all the minor numbers (ie. ports)
-		 */
-		for (j = 1; j <= num_ports - 1; ++j)
-			if (serial_table[i + j])
-				good_spot = 0;
-		if (good_spot == 0)
-			continue;
-
-		serial = kmalloc(sizeof(struct usb_serial), GFP_KERNEL);
-		if (!serial) {
-			err("%s - Out of memory", __func__);
-			return NULL;
-		}
-		memset(serial, 0, sizeof(struct usb_serial));
-		serial_table[i] = serial;
-		*minor = i;
-		mydbg("%s - minor base = %d\n", __func__, *minor);
-
-		/*
-		 * copy in the pointer into the array starting a the *minor
-		 * position minor is the index into the array.
-		 */
-		for (i = *minor + 1;
-		     (i < (*minor + num_ports)) && (i < SERIAL_TTY_MINORS); ++i)
-			serial_table[i] = serial;
-		return serial;
-	}
-	return NULL;
-}
-
-static int flip_that(struct tty_struct *tty, __u16 index,
-		     struct usb_serial *serial)
-{
-	tty_flip_buffer_push(tty);
-	tty_schedule_flip(tty);
-	return 0;
-}
-
-/* Handles processing and moving data to the tty layer */
-static void port_sofrint(void *private)
-{
-	struct usb_serial_port *port = private;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	struct tty_struct *tty = port->tty;
-	unsigned char *data = port->read_urb->transfer_buffer;
-	unsigned int index;
-	struct urb *urb = port->read_urb;
-	unsigned int RxCount = urb->actual_length;
-	int i, result;
-	int flag, flag_data;
-
-	/* index = MINOR(port->tty->device) - serial->minor; */
-	index = tty->index - serial->minor;
-
-	mydbg("%s - port %d\n", __func__, port->number);
-	mydbg("%s - port->RxHolding = %d\n", __func__, port->RxHolding);
-
-	if (port_paranoia_check(port, __func__) != 0) {
-		mydbg("%s - port_paranoia_check, exiting\n", __func__);
-		port->ReadBulkStopped = 1;
-		return;
-	}
-
-	if (!serial) {
-		mydbg("%s - bad serial pointer, exiting\n", __func__);
-		return;
-	}
-	if (port->closePending == 1) {
-		/* Were closing , stop reading */
-		mydbg("%s - (port->closepending == 1\n", __func__);
-		port->ReadBulkStopped = 1;
-		return;
-	}
-
-	/*
-	 * RxHolding is asserted by throttle, if we assert it, we're not
-	 * receiving any more characters and let the box handle the flow
-	 * control
-	 */
-	if (port->RxHolding == 1) {
-		port->ReadBulkStopped = 1;
-		return;
-	}
-
-	if (urb->status) {
-		port->ReadBulkStopped = 1;
-
-		mydbg("%s - nonzero read bulk status received: %d\n",
-		      __func__, urb->status);
-		return;
-	}
-
-	tty = port->tty;
-	mydbg("%s - port %d, tty =0x%p\n", __func__, port->number, tty);
-
-	if (tty && RxCount) {
-		flag_data = 0;
-		for (i = 0; i < RxCount; ++i) {
-			/* Look ahead code here */
-			if ((i <= (RxCount - 3)) && (THISCHAR == 0x1b)
-			    && (NEXTCHAR == 0x1b)) {
-				flag = 0;
-				switch (THIRDCHAR) {
-				case 0x00:
-					/* Line status change 4th byte must follow */
-					if (i > (RxCount - 4)) {
-						mydbg("Illegal escape sequences in received data\n");
-						break;
-					}
-					ProcessLineStatus(port, FOURTHCHAR);
-					i += 3;
-					flag = 1;
-					break;
-
-				case 0x01:
-					/* Modem status status change 4th byte must follow */
-					mydbg("Modem status status. \n");
-					if (i > (RxCount - 4)) {
-						mydbg
-						    ("Illegal escape sequences in received data\n");
-						break;
-					}
-					ProcessModemStatus(port, FOURTHCHAR);
-					i += 3;
-					flag = 1;
-					break;
-				case 0xff:
-					mydbg("No status sequence. \n");
-
-					ProcessRxChar(port, THISCHAR);
-					ProcessRxChar(port, NEXTCHAR);
-					i += 2;
-					break;
-				}
-				if (flag == 1)
-					continue;
-			}
-
-			if (tty && urb->actual_length) {
-				tty_buffer_request_room(tty, 1);
-				tty_insert_flip_string(tty, (data + i), 1);
-			}
-
-		}
-		tty_flip_buffer_push(tty);
-	}
-
-	/* Continue trying to always read  */
-	usb_fill_bulk_urb(port->read_urb, serial->dev,
-			  usb_rcvbulkpipe(serial->dev,
-					  port->bulk_in_endpointAddress),
-			  port->read_urb->transfer_buffer,
-			  port->read_urb->transfer_buffer_length,
-			  qt_read_bulk_callback, port);
-	result = usb_submit_urb(port->read_urb, GFP_ATOMIC);
-	if (result)
-		mydbg("%s - failed resubmitting read urb, error %d",
-		      __func__, result);
-	else {
-		if (tty && RxCount)
-			flip_that(tty, index, serial);
-	}
-
-	return;
-
-}
-
-static void qt_read_bulk_callback(struct urb *urb)
-{
-
-	struct usb_serial_port *port = (struct usb_serial_port *)urb->context;
-
-	if (urb->status) {
-		port->ReadBulkStopped = 1;
-		mydbg("%s - nonzero write bulk status received: %d\n",
-		      __func__, urb->status);
-		return;
-	}
-
-	port_sofrint((void *)port);
-	schedule_work(&port->work);
-}
-
-static void ProcessRxChar(struct usb_serial_port *port, unsigned char Data)
-{
-	struct tty_struct *tty;
-	struct urb *urb = port->read_urb;
-	tty = port->tty;
-	/* if we insert more than TTY_FLIPBUF_SIZE characters, we drop them. */
-
-	if (tty && urb->actual_length) {
-		tty_buffer_request_room(tty, 1);
-		tty_insert_flip_string(tty, &Data, 1);
-		/* tty_flip_buffer_push(tty); */
-	}
-
-	return;
-}
-
-static void ProcessLineStatus(struct usb_serial_port *port,
-			      unsigned char line_status)
-{
-
-	port->shadowLSR =
-	    line_status & (SERIAL_LSR_OE | SERIAL_LSR_PE | SERIAL_LSR_FE |
-			   SERIAL_LSR_BI);
-	return;
-}
-
-static void ProcessModemStatus(struct usb_serial_port *port,
-			       unsigned char modem_status)
-{
-
-	port->shadowMSR = modem_status;
-	wake_up_interruptible(&port->wait);
-	return;
-}
-
-static void serqt_usb_disconnect(struct usb_interface *interface)
-{
-	struct usb_serial *serial = usb_get_intfdata(interface);
-	/* struct device *dev = &interface->dev; */
-	struct usb_serial_port *port;
-	int i;
-
-	mydbg("%s\n", __func__);
-	if (serial) {
-
-		serial->dev = NULL;
-
-		for (i = 0; i < serial->num_ports; ++i)
-			serial->port[i].open_count = 0;
-
-		for (i = 0; i < serial->num_bulk_in; ++i) {
-			port = &serial->port[i];
-			usb_unlink_urb(port->read_urb);
-			usb_free_urb(port->read_urb);
-			kfree(port->bulk_in_buffer);
-		}
-		for (i = 0; i < serial->num_bulk_out; ++i) {
-			port = &serial->port[i];
-			usb_unlink_urb(port->write_urb);
-			usb_free_urb(port->write_urb);
-			kfree(port->bulk_out_buffer);
-		}
-		for (i = 0; i < serial->num_interrupt_in; ++i) {
-			port = &serial->port[i];
-			usb_unlink_urb(port->interrupt_in_urb);
-			usb_free_urb(port->interrupt_in_urb);
-			kfree(port->interrupt_in_buffer);
-	}
-
-		/* return the minor range that this device had */
-		return_serial(serial);
-
-		/* free up any memory that we allocated */
-		kfree(serial);
-
-	} else {
-		dev_info(&interface->dev, "device disconnected");
-	}
-
-}
-
-static struct usb_serial *get_serial_by_minor(unsigned int minor)
-{
-	return serial_table[minor];
-}
-
-/*****************************************************************************
- * Driver tty interface functions
- *****************************************************************************/
-static int serial_open(struct tty_struct *tty, struct file *filp)
-{
-	struct usb_serial *serial;
-	struct usb_serial_port *port;
-	unsigned int portNumber;
-	int retval = 0;
-
-	mydbg("%s\n", __func__);
-
-	/* initialize the pointer incase something fails */
-	tty->driver_data = NULL;
-
-	/* get the serial object associated with this tty pointer */
-	/* serial = get_serial_by_minor (MINOR(tty->device)); */
-
-	/* get the serial object associated with this tty pointer */
-	serial = get_serial_by_minor(tty->index);
-
-	if (serial_paranoia_check(serial, __func__))
-		return -ENODEV;
-
-	/* set up our port structure making the tty driver remember our port object, and us it */
-	portNumber = tty->index - serial->minor;
-	port = &serial->port[portNumber];
-	tty->driver_data = port;
-
-	down(&port->sem);
-	port->tty = tty;
-
-	++port->open_count;
-	if (port->open_count == 1) {
-		port->closePending = 0;
-		mydbg("%s port->closepending = 0\n", __func__);
-
-		port->RxHolding = 0;
-		mydbg("%s port->RxHolding = 0\n", __func__);
-
-		retval = qt_open(tty, port, filp);
-	}
-
-	if (retval)
-		port->open_count = 0;
-	mydbg("%s returning port->closePending  = %d\n", __func__,
-	      port->closePending);
-
-	up(&port->sem);
-	return retval;
-}
-
-/*****************************************************************************
- *device's specific driver functions
- *****************************************************************************/
-static int qt_open(struct tty_struct *tty, struct usb_serial_port *port,
-					struct file *filp)
-{
-	struct usb_serial *serial = port->serial;
-	int result = 0;
-	unsigned int index;
-	struct qt_get_device_data DeviceData;
-	struct qt_open_channel_data ChannelData;
-	unsigned short default_divisor = 0x30;		/* gives 9600 baud rate */
-	unsigned char default_LCR = SERIAL_8_DATA;	/* 8, none , 1 */
-	int status = 0;
-
-	if (port_paranoia_check(port, __func__))
-		return -ENODEV;
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	index = tty->index - serial->minor;
-
-	status = box_get_device(serial, &DeviceData);
-	if (status < 0) {
-		mydbg(__FILE__ "box_get_device failed\n");
-		return status;
-	}
-	serial->num_OpenCount++;
-	mydbg("%s serial->num_OpenCount  = %d\n", __func__,
-	      serial->num_OpenCount);
-	/* Open uart channel */
-
-	/* Port specific setups */
-	status = BoxOPenCloseChannel(serial, index, 1, &ChannelData);
-	if (status < 0) {
-		mydbg(__FILE__ "BoxOPenCloseChannel failed\n");
-		return status;
-	}
-	mydbg(__FILE__ "BoxOPenCloseChannel completed.\n");
-
-	port->shadowLSR = ChannelData.line_status &
-	    (SERIAL_LSR_OE | SERIAL_LSR_PE | SERIAL_LSR_FE | SERIAL_LSR_BI);
-
-	port->shadowMSR = ChannelData.modem_status &
-	    (SERIAL_MSR_CTS | SERIAL_MSR_DSR | SERIAL_MSR_RI | SERIAL_MSR_CD);
-
-	/* Set Baud rate to default and turn off (default)flow control here */
-	status = BoxSetUart(serial, index, default_divisor, default_LCR);
-	if (status < 0) {
-		mydbg(__FILE__ "BoxSetUart failed\n");
-		return status;
-	}
-	mydbg(__FILE__ "BoxSetUart completed.\n");
-
-	/* Put this here to make it responsive to stty and defauls set by the tty layer */
-	qt_set_termios(tty, port, NULL);
-
-	/* Initialize the wait que head */
-	init_waitqueue_head(&(port->wait));
-
-	/* if we have a bulk endpoint, start reading from it */
-	if (serial->num_bulk_in) {
-		/* Start reading from the device */
-		usb_fill_bulk_urb(port->read_urb, serial->dev,
-				  usb_rcvbulkpipe(serial->dev,
-						  port->
-						  bulk_in_endpointAddress),
-				  port->read_urb->transfer_buffer,
-				  port->read_urb->transfer_buffer_length,
-				  qt_read_bulk_callback, port);
-
-		port->ReadBulkStopped = 0;
-
-		result = usb_submit_urb(port->read_urb, GFP_ATOMIC);
-
-		if (result) {
-			err("%s - failed resubmitting read urb, error %d\n",
-			    __func__, result);
-			port->ReadBulkStopped = 1;
-		}
-
-	}
-
-	return result;
-}
-
-static void serial_close(struct tty_struct *tty, struct file *filp)
-{
-	struct usb_serial_port *port =
-	    tty->driver_data;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-
-	if (!serial)
-		return;
-
-	down(&port->sem);
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	/* if disconnect beat us to the punch here, there's nothing to do */
-	if (tty->driver_data) {
-		if (!port->open_count) {
-			mydbg("%s - port not opened\n", __func__);
-			goto exit;
-		}
-
-		--port->open_count;
-		if (port->open_count <= 0) {
-			port->closePending = 1;
-			mydbg("%s - port->closePending = 1\n", __func__);
-
-			if (serial->dev) {
-				qt_close(tty, port, filp);
-				port->open_count = 0;
-			}
-		}
-
-	}
-
-exit:
-	up(&port->sem);
-
-	mydbg("%s - %d return\n", __func__, port->number);
-
-}
-
-static void qt_close(struct tty_struct *tty, struct usb_serial_port *port,
-							struct file *filp)
-{
-	unsigned long jift = jiffies + 10 * HZ;
-	u8 lsr, mcr;
-	struct usb_serial *serial = port->serial;
-	int status;
-	unsigned int index;
-
-	struct qt_open_channel_data ChannelData;
-	status = 0;
-	lsr = 0;
-
-	mydbg("%s - port %d\n", __func__, port->number);
-	index = tty->index - serial->minor;
-
-	/* shutdown any bulk reads that might be going on */
-	if (serial->num_bulk_out)
-		usb_unlink_urb(port->write_urb);
-	if (serial->num_bulk_in)
-		usb_unlink_urb(port->read_urb);
-
-	/* wait up to 30 seconds for transmitter to empty */
-	do {
-		status = BoxGetRegister(serial, index, LINE_STATUS_REGISTER, &lsr);
-		if (status < 0) {
-			mydbg(__FILE__ "box_get_device failed\n");
-			break;
-		}
-
-		if ((lsr & SERIAL_LSR_TEMT)
-		    && (port->ReadBulkStopped == 1))
-			break;
-		schedule();
-
-	}
-	while (jiffies <= jift);
-
-	if (jiffies > jift)
-		mydbg("%s - port %d timout of checking transmitter empty\n",
-		      __func__, port->number);
-	else
-		mydbg("%s - port %d checking transmitter empty succeded\n",
-		      __func__, port->number);
-
-	status =
-	    BoxGetRegister(serial, index, MODEM_CONTROL_REGISTER,
-			   &mcr);
-	mydbg(__FILE__ "BoxGetRegister MCR = 0x%x.\n", mcr);
-
-	if (status >= 0) {
-		mcr &= ~(SERIAL_MCR_DTR | SERIAL_MCR_RTS);
-		/* status = BoxSetRegister(serial, index, MODEM_CONTROL_REGISTER, mcr); */
-	}
-
-	/* Close uart channel */
-	status = BoxOPenCloseChannel(serial, index, 0, &ChannelData);
-	if (status < 0)
-		mydbg("%s - port %d BoxOPenCloseChannel failed.\n",
-		      __func__, port->number);
-
-	serial->num_OpenCount--;
-
-}
-
-static int serial_write(struct tty_struct *tty, const unsigned char *buf,
-			int count)
-{
-	struct usb_serial_port *port = tty->driver_data;
-	struct usb_serial *serial;
-	int retval = -EINVAL;
-	unsigned int index;
-
-	serial = get_usb_serial(port, __func__);
-	if (serial == NULL)
-		return -ENODEV;
-	/* This can happen if we get disconnected a */
-	if (port->open_count == 0)
-		return -ENODEV;
-	index = tty->index - serial->minor;
-
-	mydbg("%s - port %d, %d byte(s)\n", __func__, port->number, count);
-	mydbg("%s - port->RxHolding =  %d\n", __func__, port->RxHolding);
-
-	if (!port->open_count) {
-		mydbg("%s - port not opened\n", __func__);
-		goto exit;
-	}
-
-	retval = qt_write(tty, port, buf, count);
-
-exit:
-	return retval;
-}
-
-static int qt_write(struct tty_struct *tty, struct usb_serial_port *port,
-				const unsigned char *buf, int count)
-{
-	int result;
-	unsigned int index;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-
-	if (serial == NULL)
-		return -ENODEV;
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	if (count == 0) {
-		mydbg("%s - write request of 0 bytes\n", __func__);
-		return 0;
-	}
-
-	index = tty->index - serial->minor;
-	/* only do something if we have a bulk out endpoint */
-	if (serial->num_bulk_out) {
-		if (port->write_urb->status == -EINPROGRESS) {
-			mydbg("%s - already writing\n", __func__);
-			return 0;
-		}
-
-		count =
-		    (count > port->bulk_out_size) ? port->bulk_out_size : count;
-		memcpy(port->write_urb->transfer_buffer, buf, count);
-
-		/* usb_serial_debug_data(__FILE__, __func__, count, port->write_urb->transfer_buffer); */
-
-		/* set up our urb */
-
-		usb_fill_bulk_urb(port->write_urb, serial->dev,
-				  usb_sndbulkpipe(serial->dev,
-						  port->
-						  bulk_out_endpointAddress),
-				  port->write_urb->transfer_buffer, count,
-				  qt_write_bulk_callback, port);
-
-		/* send the data out the bulk port */
-		result = usb_submit_urb(port->write_urb, GFP_ATOMIC);
-		if (result)
-			mydbg("%s - failed submitting write urb, error %d\n",
-			      __func__, result);
-		else
-			result = count;
-
-		return result;
-	}
-
-	/* no bulk out, so return 0 bytes written */
-	return 0;
-}
-
-static void qt_write_bulk_callback(struct urb *urb)
-{
-	struct usb_serial_port *port = (struct usb_serial_port *)urb->context;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	if (!serial) {
-		mydbg("%s - bad serial pointer, exiting\n", __func__);
-		return;
-	}
-
-	if (urb->status) {
-		mydbg("%s - nonzero write bulk status received: %d\n",
-		      __func__, urb->status);
-		return;
-	}
-	port_softint(&port->work);
-	schedule_work(&port->work);
-
-	return;
-}
-
-static void port_softint(struct work_struct *work)
-{
-	struct usb_serial_port *port =
-	    container_of(work, struct usb_serial_port, work);
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	struct tty_struct *tty;
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	if (!serial)
-		return;
-
-	tty = port->tty;
-	if (!tty)
-		return;
-#if 0
-	if ((tty->flags & (1 << TTY_DO_WRITE_WAKEUP))
-	    && tty->ldisc.write_wakeup) {
-		mydbg("%s - write wakeup call.\n", __func__);
-		(tty->ldisc.write_wakeup) (tty);
-	}
-#endif
-
-	wake_up_interruptible(&tty->write_wait);
-}
-static int serial_write_room(struct tty_struct *tty)
-{
-	struct usb_serial_port *port = tty->driver_data;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	int retval = -EINVAL;
-
-	if (!serial)
-		return -ENODEV;
-
-	down(&port->sem);
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	if (!port->open_count) {
-		mydbg("%s - port not open\n", __func__);
-		goto exit;
-	}
-
-	retval = qt_write_room(port);
-
-exit:
-	up(&port->sem);
-	return retval;
-}
-static int qt_write_room(struct usb_serial_port *port)
-{
-	struct usb_serial *serial = port->serial;
-	int room = 0;
-	if (port->closePending == 1) {
-		mydbg("%s - port->closePending == 1\n", __func__);
-		return -ENODEV;
-	}
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	if (serial->num_bulk_out) {
-		if (port->write_urb->status != -EINPROGRESS)
-			room = port->bulk_out_size;
-	}
-
-	mydbg("%s - returns %d\n", __func__, room);
-	return room;
-}
-static int serial_chars_in_buffer(struct tty_struct *tty)
-{
-	struct usb_serial_port *port = tty->driver_data;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	int retval = -EINVAL;
-
-	if (!serial)
-		return -ENODEV;
-
-	down(&port->sem);
-
-	mydbg("%s = port %d\n", __func__, port->number);
-
-	if (!port->open_count) {
-		mydbg("%s - port not open\n", __func__);
-		goto exit;
-	}
-
-	retval = qt_chars_in_buffer(port);
-
-exit:
-	up(&port->sem);
-	return retval;
-}
-
-static int qt_chars_in_buffer(struct usb_serial_port *port)
-{
-	struct usb_serial *serial = port->serial;
-	int chars = 0;
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	if (serial->num_bulk_out) {
-		if (port->write_urb->status == -EINPROGRESS)
-			chars = port->write_urb->transfer_buffer_length;
-	}
-
-	mydbg("%s - returns %d\n", __func__, chars);
-	return chars;
-}
-
-static int serial_tiocmset(struct tty_struct *tty, struct file *file,
-			   unsigned int set, unsigned int clear)
-{
-
-	struct usb_serial_port *port = tty->driver_data;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	int retval = -ENODEV;
-	unsigned int index;
-	mydbg("In %s \n", __func__);
-
-	if (!serial)
-		return -ENODEV;
-
-	index = tty->index - serial->minor;
-
-	down(&port->sem);
-
-	mydbg("%s - port %d \n", __func__, port->number);
-	mydbg("%s - port->RxHolding = %d\n", __func__, port->RxHolding);
-
-	if (!port->open_count) {
-		mydbg("%s - port not open\n", __func__);
-		goto exit;
-	}
-
-	retval = qt_tiocmset(tty, port, file, set);
-
-exit:
-	up(&port->sem);
-	return retval;
-}
-
-static int qt_tiocmset(struct tty_struct *tty, struct usb_serial_port *port,
-		       struct file *file, unsigned int value)
-{
-
-	u8 mcr;
-	int status;
-	unsigned int index;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-
-	if (serial == NULL)
-		return -ENODEV;
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-    /**************************************************************************************/
-    /**  TIOCMGET
-     */
-	index = tty->index - serial->minor;
-	status =
-	    BoxGetRegister(port->serial, index, MODEM_CONTROL_REGISTER,
-			   &mcr);
-	if (status < 0)
-		return -ESPIPE;
-
-	/*
-	 * Turn off the RTS and DTR and loopbcck and then only turn on what was
-	 * asked for
-	 */
-	mcr &= ~(SERIAL_MCR_RTS | SERIAL_MCR_DTR | SERIAL_MCR_LOOP);
-	if (value & TIOCM_RTS)
-		mcr |= SERIAL_MCR_RTS;
-	if (value & TIOCM_DTR)
-		mcr |= SERIAL_MCR_DTR;
-	if (value & TIOCM_LOOP)
-		mcr |= SERIAL_MCR_LOOP;
-
-	status =
-	    BoxSetRegister(port->serial, index, MODEM_CONTROL_REGISTER,
-			   mcr);
-	if (status < 0)
-		return -ESPIPE;
-	else
-		return 0;
-}
-
-static int serial_tiocmget(struct tty_struct *tty, struct file *file)
-{
-
-	struct usb_serial_port *port = tty->driver_data;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	int retval = -ENODEV;
-	unsigned int index;
-	mydbg("In %s \n", __func__);
-
-	if (!serial)
-		return -ENODEV;
-
-	index = tty->index - serial->minor;
-
-	down(&port->sem);
-
-	mydbg("%s - port %d\n", __func__, port->number);
-	mydbg("%s - port->RxHolding = %d\n", __func__, port->RxHolding);
-
-	if (!port->open_count) {
-		mydbg("%s - port not open\n", __func__);
-		goto exit;
-	}
-
-	retval = qt_tiocmget(tty, port, file);
-
-exit:
-	up(&port->sem);
-	return retval;
-}
-
-static int qt_tiocmget(struct tty_struct *tty,
-			struct usb_serial_port *port, struct file *file)
-{
-
-	u8 mcr;
-	u8 msr;
-	unsigned int result = 0;
-	int status;
-	unsigned int index;
-
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	if (serial == NULL)
-		return -ENODEV;
-
-	mydbg("%s - port %d, tty =0x%p\n", __func__, port->number, tty);
-
-    /**************************************************************************************/
-    /**  TIOCMGET
-     */
-	index = tty->index - serial->minor;
-	status =
-	    BoxGetRegister(port->serial, index, MODEM_CONTROL_REGISTER,
-			   &mcr);
-	if (status >= 0) {
-		status =
-		    BoxGetRegister(port->serial, index,
-				   MODEM_STATUS_REGISTER, &msr);
-
-	}
-
-	if (status >= 0) {
-		result = ((mcr & SERIAL_MCR_DTR) ? TIOCM_DTR : 0)
-		    /* DTR IS SET */
-		    | ((mcr & SERIAL_MCR_RTS) ? TIOCM_RTS : 0)
-		    /* RTS IS SET */
-		    | ((msr & SERIAL_MSR_CTS) ? TIOCM_CTS : 0)
-		    /* CTS is set */
-		    | ((msr & SERIAL_MSR_CD) ? TIOCM_CAR : 0)
-		    /* Carrier detect is set */
-		    | ((msr & SERIAL_MSR_RI) ? TIOCM_RI : 0)
-		    /* Ring indicator set */
-		    | ((msr & SERIAL_MSR_DSR) ? TIOCM_DSR : 0);
-		/* DSR is set */
-		return result;
-
-	} else
-		return -ESPIPE;
-}
-
-static int serial_ioctl(struct tty_struct *tty, struct file *file,
-			unsigned int cmd, unsigned long arg)
-{
-
-	struct usb_serial_port *port = tty->driver_data;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	int retval = -ENODEV;
-	unsigned int index;
-	mydbg("In %s \n", __func__);
-
-	if (!serial)
-		return -ENODEV;
-
-	index = tty->index - serial->minor;
-
-	down(&port->sem);
-
-	mydbg("%s - port %d, cmd 0x%.4x\n", __func__, port->number, cmd);
-	mydbg("%s - port->RxHolding = %d\n", __func__, port->RxHolding);
-
-	if (!port->open_count) {
-		mydbg("%s - port not open\n", __func__);
-		goto exit;
-	}
-
-	retval = qt_ioctl(tty, port, file, cmd, arg);
-
-exit:
-	up(&port->sem);
-	return retval;
-}
-static int qt_ioctl(struct tty_struct *tty, struct usb_serial_port *port,
-			struct file *file, unsigned int cmd, unsigned long arg)
-{
-	__u8 mcr;
-	__u8 msr;
-	unsigned short prev_msr;
-	unsigned int value, result = 0;
-	int status;
-	unsigned int index;
-
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	if (serial == NULL)
-		return -ENODEV;
-
-	mydbg("%s - port %d, tty =0x%p\n", __func__, port->number, tty);
-
-	/* TIOCMGET */
-	index = tty->index - serial->minor;
-
-	if (cmd == TIOCMIWAIT) {
-		DECLARE_WAITQUEUE(wait, current);
-		prev_msr = port->shadowMSR & SERIAL_MSR_MASK;
-		while (1) {
-			add_wait_queue(&port->wait, &wait);
-			set_current_state(TASK_INTERRUPTIBLE);
-			schedule();
-			remove_wait_queue(&port->wait, &wait);
-			/* see if a signal woke us up */
-			if (signal_pending(current))
-				return -ERESTARTSYS;
-			msr = port->shadowMSR & SERIAL_MSR_MASK;
-			if (msr == prev_msr)
-				return -EIO;	/* no change error */
-
-			if ((arg & TIOCM_RNG
-			     && ((prev_msr & SERIAL_MSR_RI) ==
-				 (msr & SERIAL_MSR_RI)))
-			    || (arg & TIOCM_DSR
-				&& ((prev_msr & SERIAL_MSR_DSR) ==
-				    (msr & SERIAL_MSR_DSR)))
-			    || (arg & TIOCM_CD
-				&& ((prev_msr & SERIAL_MSR_CD) ==
-				    (msr & SERIAL_MSR_CD)))
-			    || (arg & TIOCM_CTS
-				&& ((prev_msr & SERIAL_MSR_CTS) ==
-				    (msr & SERIAL_MSR_CTS)))) {
-				return 0;
-			}
-
-		}
-
-	}
-	mydbg("%s -No ioctl for that one.  port = %d\n", __func__,
-	      port->number);
-
-	return -ENOIOCTLCMD;
-}
-
-static void serial_set_termios(struct tty_struct *tty, struct ktermios *old)
-{
-	struct usb_serial_port *port =
-	    tty->driver_data;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-
-	if (!serial)
-		return;
-
-	down(&port->sem);
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	if (!port->open_count) {
-		mydbg("%s - port not open\n", __func__);
-		goto exit;
-	}
-
-	/* pass on to the driver specific version of this function if it is available */
-	qt_set_termios(tty, port, old);
-
-exit:
-	up(&port->sem);
-}
-
-static void qt_set_termios(struct tty_struct *tty,
-			   struct usb_serial_port *port,
-			   struct ktermios *old_termios)
-{
-	unsigned int cflag;
-	int baud, divisor, remainder;
-	unsigned char new_LCR = 0;
-	int status;
-	struct usb_serial *serial;
-	__u16 index;
-	__u16 tmp, tmp2;
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	tmp = port->tty->index;
-	mydbg("%s - MINOR(port->tty->index) =  %d\n", __func__, tmp);
-
-	serial = port->serial;
-	tmp2 = serial->minor;
-	mydbg("%s - serial->minor =  %d\n", __func__, tmp2);
-
-	index = port->tty->index - serial->minor;
-
-	cflag = tty->termios->c_cflag;
-
-	mydbg("%s - 3\n", __func__);
-
-	switch (cflag) {
-	case CS5:
-		new_LCR |= SERIAL_5_DATA;
-		break;
-	case CS6:
-		new_LCR |= SERIAL_6_DATA;
-		break;
-	case CS7:
-		new_LCR |= SERIAL_7_DATA;
-		break;
-	default:
-	case CS8:
-		new_LCR |= SERIAL_8_DATA;
-		break;
-	}
-
-	/* Parity stuff */
-	if (cflag & PARENB) {
-		if (cflag & PARODD)
-			new_LCR |= SERIAL_ODD_PARITY;
-		else
-			new_LCR |= SERIAL_EVEN_PARITY;
-	}
-	if (cflag & CSTOPB)
-		new_LCR |= SERIAL_TWO_STOPB;
-	else
-		new_LCR |= SERIAL_TWO_STOPB;
-
-	mydbg("%s - 4\n", __func__);
-	/* Thats the LCR stuff, go ahead and set it */
-	baud = tty_get_baud_rate(tty);
-	if (!baud)
-		/* pick a default, any default... */
-		baud = 9600;
-
-	mydbg("%s - got baud = %d\n", __func__, baud);
-
-	divisor = MAX_BAUD_RATE / baud;
-	remainder = MAX_BAUD_RATE % baud;
-	/* Round to nearest divisor */
-	if (((remainder * 2) >= baud) && (baud != 110))
-		divisor++;
-
-	/*
-	 * Set Baud rate to default and turn off (default)flow control here
-	 */
-	status = BoxSetUart(serial, index, (unsigned short)divisor, new_LCR);
-	if (status < 0) {
-		mydbg(__FILE__ "BoxSetUart failed\n");
-		return;
-	}
-
-	/* Now determine flow control */
-	if (cflag & CRTSCTS) {
-		mydbg("%s - Enabling HW flow control port %d\n", __func__,
-		      port->number);
-
-		/* Enable RTS/CTS flow control */
-		status = BoxSetHW_FlowCtrl(serial, index, 1);
-
-		if (status < 0) {
-			mydbg(__FILE__ "BoxSetHW_FlowCtrl failed\n");
-			return;
-		}
-	} else {
-		/* Disable RTS/CTS flow control */
-		mydbg("%s - disabling HW flow control port %d\n", __func__,
-		      port->number);
-
-		status = BoxSetHW_FlowCtrl(serial, index, 0);
-		if (status < 0) {
-			mydbg(__FILE__ "BoxSetHW_FlowCtrl failed\n");
-			return;
-		}
-
-	}
-
-	/* if we are implementing XON/XOFF, set the start and stop character in
-	 * the device */
-	if (I_IXOFF(tty) || I_IXON(tty)) {
-		unsigned char stop_char = STOP_CHAR(tty);
-		unsigned char start_char = START_CHAR(tty);
-		status =
-		    BoxSetSW_FlowCtrl(serial, index, stop_char,
-				      start_char);
-		if (status < 0)
-			mydbg(__FILE__ "BoxSetSW_FlowCtrl (enabled) failed\n");
-
-	} else {
-		/* disable SW flow control */
-		status = BoxDisable_SW_FlowCtrl(serial, index);
-		if (status < 0)
-			mydbg(__FILE__ "BoxSetSW_FlowCtrl (diabling) failed\n");
-
-	}
-	tty->termios->c_cflag &= ~CMSPAR;
-	/* FIXME: Error cases should be returning the actual bits changed only */
-}
-
-/****************************************************************************
-* BoxGetRegister
-*	issuse a GET_REGISTER vendor-spcific request on the default control pipe
-*	If successful, fills in the  pValue with the register value asked for
-****************************************************************************/
-static int BoxGetRegister(struct usb_serial *serial, unsigned short Uart_Number,
-			  unsigned short Register_Num, __u8 *pValue)
-{
-	int result;
-	__u16 current_length;
-
-	current_length = sizeof(struct qt_get_device_data);
-
-	result =
-	    usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
-			    QT_GET_SET_REGISTER, 0xC0, Register_Num,
-			    Uart_Number, (void *)pValue, sizeof(*pValue), 300);
-
-	return result;
-}
-
-/****************************************************************************
-* BoxSetRegister
-*	issuse a GET_REGISTER vendor-spcific request on the default control pipe
-*	If successful, fills in the  pValue with the register value asked for
-****************************************************************************/
-static int BoxSetRegister(struct usb_serial *serial, unsigned short Uart_Number,
-			  unsigned short Register_Num, unsigned short Value)
-{
-	int result;
-	unsigned short RegAndByte;
-
-	RegAndByte = Value;
-	RegAndByte = RegAndByte << 8;
-	RegAndByte = RegAndByte + Register_Num;
-
-/*
-	result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
-				 QT_GET_SET_REGISTER, 0xC0, Register_Num,
-				 Uart_Number, NULL, 0, 300);
-*/
-
-	result =
-	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
-			    QT_GET_SET_REGISTER, 0x40, RegAndByte, Uart_Number,
-			    NULL, 0, 300);
-
-	return result;
-}
-
-/**
- * box_get_device
- *   Issue a GET_DEVICE vendor-specific request on the default control pipe If
- *   successful, fills in the qt_get_device_data structure pointed to by
- *   device_data, otherwise return a negative error number of the problem.
- */
-static int box_get_device(struct usb_serial *serial,
-			  struct qt_get_device_data *device_data)
-{
-	int result;
-	__u16 current_length;
-	unsigned char *transfer_buffer;
-
-	current_length = sizeof(struct qt_get_device_data);
-	transfer_buffer = kmalloc(current_length, GFP_KERNEL);
-	if (!transfer_buffer)
-		return -ENOMEM;
-
-	result = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
-				 QT_SET_GET_DEVICE, 0xc0, 0, 0,
-				 transfer_buffer, current_length, 300);
-	if (result > 0)
-		memcpy(device_data, transfer_buffer, current_length);
-	kfree(transfer_buffer);
-
-	return result;
-}
-
-/**
- * box_set_device
- *   Issue a SET_DEVICE vendor-specific request on the default control pipe If
- *   successful returns the number of bytes written, otherwise it returns a
- *   negative error number of the problem.
- */
-static int box_set_device(struct usb_serial *serial,
-			  struct qt_get_device_data *device_data)
-{
-	int result;
-	__u16 length;
-	__u16 PortSettings;
-
-	PortSettings = ((__u16) (device_data->portb));
-	PortSettings = (PortSettings << 8);
-	PortSettings += ((__u16) (device_data->porta));
-
-	length = sizeof(struct qt_get_device_data);
-	mydbg("%s - PortSettings = 0x%x\n", __func__, PortSettings);
-
-	result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
-				 QT_SET_GET_DEVICE, 0x40, PortSettings,
-				 0, NULL, 0, 300);
-	return result;
-}
-
-/****************************************************************************
- * BoxOPenCloseChannel
- * This funciotn notifies the device that the device driver wishes to open a particular UART channel. its
- * purpose is to allow the device driver and the device to synchronize state information.
- * OpenClose = 1 for open , 0 for close
-  ****************************************************************************/
-static int BoxOPenCloseChannel(struct usb_serial *serial, __u16 Uart_Number,
-			       __u16 OpenClose,
-			       struct qt_open_channel_data *pDeviceData)
-{
-	int result;
-	__u16 length;
-	__u8 Direcion;
-	unsigned int pipe;
-	length = sizeof(struct qt_open_channel_data);
-
-	/* if opening... */
-	if (OpenClose == 1) {
-		Direcion = USBD_TRANSFER_DIRECTION_IN;
-		pipe = usb_rcvctrlpipe(serial->dev, 0);
-		result =
-		    usb_control_msg(serial->dev, pipe, QT_OPEN_CLOSE_CHANNEL,
-				    Direcion, OpenClose, Uart_Number,
-				    pDeviceData, length, 300);
-
-	} else {
-		Direcion = USBD_TRANSFER_DIRECTION_OUT;
-		pipe = usb_sndctrlpipe(serial->dev, 0);
-		result =
-		    usb_control_msg(serial->dev, pipe, QT_OPEN_CLOSE_CHANNEL,
-				    Direcion, OpenClose, Uart_Number, NULL, 0,
-				    300);
-
-	}
-
-	return result;
-}
-
-/****************************************************************************
- *  BoxSetPrebufferLevel
-   TELLS BOX WHEN TO ASSERT FLOW CONTROL
- ****************************************************************************/
-static int BoxSetPrebufferLevel(struct usb_serial *serial)
-{
-	int result;
-	__u16 buffer_length;
-
-	buffer_length = PREFUFF_LEVEL_CONSERVATIVE;
-	result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
-				 QT_GET_SET_PREBUF_TRIG_LVL, 0x40,
-				 buffer_length, 0, NULL, 0, 300);
-	return result;
-}
-
-/****************************************************************************
- *  BoxSetATC
-   TELLS BOX WHEN TO ASSERT automatic transmitter control
-   ****************************************************************************/
-static int BoxSetATC(struct usb_serial *serial, __u16 n_Mode)
-{
-	int result;
-	__u16 buffer_length;
-
-	buffer_length = PREFUFF_LEVEL_CONSERVATIVE;
-
-	result =
-	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
-			    QT_SET_ATF, 0x40, n_Mode, 0, NULL, 0, 300);
-
-	return result;
-}
-
-/****************************************************************************
-* BoxSetUart
-*	issuse a SET_UART vendor-spcific request on the default control pipe
-*	If successful sets baud rate divisor and LCR value
-****************************************************************************/
-static int BoxSetUart(struct usb_serial *serial, unsigned short Uart_Number,
-		      unsigned short default_divisor, unsigned char default_LCR)
-{
-	int result;
-	unsigned short UartNumandLCR;
-
-	UartNumandLCR = (default_LCR << 8) + Uart_Number;
-
-	result =
-	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
-			    QT_GET_SET_UART, 0x40, default_divisor,
-			    UartNumandLCR, NULL, 0, 300);
-
-	return result;
-}
-
-static int BoxSetHW_FlowCtrl(struct usb_serial *serial, unsigned int index,
-			     int bSet)
-{
-	__u8 mcr = 0;
-	__u8 msr = 0, MOUT_Value = 0;
-	struct usb_serial_port *port;
-	unsigned int status;
-
-	port = serial->port;
-
-	if (bSet == 1) {
-		/* flow control, box will clear RTS line to prevent remote */
-		mcr = SERIAL_MCR_RTS;
-	}			/* device from xmitting more chars */
-	else {
-		/* no flow control to remote device */
-		mcr = 0;
-
-	}
-	MOUT_Value = mcr << 8;
-
-	if (bSet == 1) {
-		/* flow control, box will inhibit xmit data if CTS line is
-		 * asserted */
-		msr = SERIAL_MSR_CTS;
-	} else {
-		/* Box will not inhimbe xmit data due to CTS line */
-		msr = 0;
-	}
-	MOUT_Value |= msr;
-
-	status =
-	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
-			    QT_HW_FLOW_CONTROL_MASK, 0x40, MOUT_Value,
-			    index, NULL, 0, 300);
-	return status;
-
-}
-
-static int BoxSetSW_FlowCtrl(struct usb_serial *serial, __u16 index,
-			     unsigned char stop_char, unsigned char start_char)
-{
-	__u16 nSWflowout;
-	int result;
-
-	nSWflowout = start_char << 8;
-	nSWflowout = (unsigned short)stop_char;
-
-	result =
-	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
-			    QT_SW_FLOW_CONTROL_MASK, 0x40, nSWflowout,
-			    index, NULL, 0, 300);
-	return result;
-
-}
-static int BoxDisable_SW_FlowCtrl(struct usb_serial *serial, __u16 index)
-{
-	int result;
-
-	result =
-	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
-			    QT_SW_FLOW_CONTROL_DISABLE, 0x40, 0, index,
-			    NULL, 0, 300);
-	return result;
-
-}
-
-static void serial_throttle(struct tty_struct *tty)
-{
-	struct usb_serial_port *port =
-	    tty->driver_data;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	if (!serial)
-		return;
-
-	down(&port->sem);
-
-	if (!port->open_count) {
-		mydbg("%s - port not open\n", __func__);
-		goto exit;
-	}
-	/* shut down any bulk reads that may be going on */
-/*	usb_unlink_urb (port->read_urb); */
-	/* pass on to the driver specific version of this function */
-	port->RxHolding = 1;
-	mydbg("%s - port->RxHolding = 1\n", __func__);
-
-exit:
-	up(&port->sem);
-	return;
-}
-
-static void serial_unthrottle(struct tty_struct *tty)
-{
-	struct usb_serial_port *port =
-	    tty->driver_data;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	unsigned int result;
-
-	if (!serial)
-		return;
-	down(&port->sem);
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	if (!port->open_count) {
-		mydbg("%s - port not open\n", __func__);
-		goto exit;
-	}
-
-	if (port->RxHolding == 1) {
-		mydbg("%s -port->RxHolding == 1\n", __func__);
-
-		port->RxHolding = 0;
-		mydbg("%s - port->RxHolding = 0\n", __func__);
-
-		/* if we have a bulk endpoint, start it up */
-		if ((serial->num_bulk_in) && (port->ReadBulkStopped == 1)) {
-			/* Start reading from the device */
-			usb_fill_bulk_urb(port->read_urb, serial->dev,
-					  usb_rcvbulkpipe(serial->dev,
-							  port->
-							  bulk_in_endpointAddress),
-					  port->read_urb->transfer_buffer,
-					  port->read_urb->
-					  transfer_buffer_length,
-					  qt_read_bulk_callback, port);
-			result = usb_submit_urb(port->read_urb, GFP_ATOMIC);
-			if (result)
-				err("%s - failed restarting read urb, error %d",
-				    __func__, result);
-		}
-	}
-exit:
-	up(&port->sem);
-	return;
-
-}
-
-static int serial_break(struct tty_struct *tty, int break_state)
-{
-	struct usb_serial_port *port = tty->driver_data;
-	struct usb_serial *serial = get_usb_serial(port, __func__);
-	u16 index, onoff;
-	unsigned int result;
-
-	index = tty->index - serial->minor;
-	if (!serial)
-		return -ENODEV;
-
-	if (break_state == -1)
-		onoff = 1;
-	else
-		onoff = 0;
-
-	down(&port->sem);
-
-	mydbg("%s - port %d\n", __func__, port->number);
-
-	if (!port->open_count) {
-		mydbg("%s - port not open\n", __func__);
-		goto exit;
-	}
-
-	result =
-	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
-			    QT_BREAK_CONTROL, 0x40, onoff, index,
-			    NULL, 0, 300);
-
-exit:
-	up(&port->sem);
-	return 0;
-}
-
-static int ioctl_serial_usb(struct inode *innod, struct file *filp, unsigned int cmd,
-		     unsigned long arg)
-{
-
-	unsigned err;
-	unsigned ucOPR_NewValue, uc_Value;
-	int *p_Num_of_adapters, counts, index, *p_QMCR_Value;
-	struct identity *p_Identity_of;
-	struct identity Identity_of;
-	struct usb_serial *lastserial, *serial;
-
-	mydbg(KERN_DEBUG "ioctl_serial_usb  cmd =\n");
-	if (_IOC_TYPE(cmd) != SERIALQT_PCI_IOC_MAGIC)
-		return -ENOTTY;
-	if (_IOC_NR(cmd) > SERIALQT_IOC_MAXNR)
-		return -ENOTTY;
-	mydbg(KERN_DEBUG "ioctl_serial_usb  cmd = 0x%x\n", cmd);
-	err = 0;
-	switch (cmd) {
-
-	case SERIALQT_WRITE_QMCR:
-		err = -ENOTTY;
-		index = arg >> 16;
-		counts = 0;
-
-		ucOPR_NewValue = arg;
-
-		err = EmulateWriteQMCR_Reg(index, ucOPR_NewValue);
-		break;
-
-	case SERIALQT_READ_QMCR:
-		err = -ENOTTY;
-		p_QMCR_Value = (int *)arg;
-		index = arg >> 16;
-		counts = 0;
-
-		err = EmulateReadQMCR_Reg(index, &uc_Value);
-		if (err == 0)
-			err = put_user(uc_Value, p_QMCR_Value);
-		break;
-
-	case SERIALQT_GET_NUMOF_UNITS:
-		p_Num_of_adapters = (int *)arg;
-		counts = 0;	/* Initialize counts to zero */
-		/* struct usb_serial *lastserial = serial_table[0], *serial; */
-		lastserial = serial_table[0];
-
-		mydbg(KERN_DEBUG "SERIALQT_GET_NUMOF_UNITS \n");
-		/* if first pointer is nonull, we at least have one box */
-		if (lastserial)
-			counts = 1;	/* we at least have one box */
-
-		for (index = 1; index < SERIAL_TTY_MINORS; index++) {
-			serial = serial_table[index];
-			if (serial) {
-				if (serial != lastserial) {
-					/* we had a change in the array, hence
-					 * another box is there */
-					lastserial = serial;
-					counts++;
-				}
-			} else
-				break;
-		}
-
-		mydbg(KERN_DEBUG "ioctl_serial_usb writting counts = %d",
-		      counts);
-
-		err = put_user(counts, p_Num_of_adapters);
-
-		break;
-	case SERIALQT_GET_THIS_UNIT:
-		counts = 0;
-		p_Identity_of = (struct identity *)arg;
-		/* copy user structure to local variable */
-		get_user(Identity_of.index, &p_Identity_of->index);
-		mydbg(KERN_DEBUG "SERIALQT_GET_THIS_UNIT Identity_of.index\n");
-		mydbg(KERN_DEBUG
-		      "SERIALQT_GET_THIS_UNIT Identity_of.index= 0x%x\n",
-		      Identity_of.index);
-
-		err = -ENOTTY;
-		serial = find_the_box(Identity_of.index);
-		if (serial) {
-			err =
-			    put_user(serial->product,
-				     &p_Identity_of->n_identity);
-
-		}
-		break;
-
-	case SERIALQT_IS422_EXTENDED:
-		err = -ENOTTY;
-		mydbg(KERN_DEBUG "SERIALQT_IS422_EXTENDED \n");
-		index = arg >> 16;
-
-		counts = 0;
-
-		mydbg(KERN_DEBUG
-		      "SERIALQT_IS422_EXTENDED, looking Identity_of.indext = 0x%x\n",
-		      index);
-		serial = find_the_box(index);
-		if (serial) {
-			mydbg("%s index = 0x%x, serial = 0x%p\n", __func__,
-			      index, serial);
-			for (counts = 0; serqt_422_table[counts] != 0; counts++) {
-
-				mydbg
-				    ("%s serial->product = = 0x%x, serqt_422_table[counts] = 0x%x\n",
-				     __func__, serial->product,
-				     serqt_422_table[counts]);
-				if (serial->product == serqt_422_table[counts]) {
-					err = 0;
-
-					mydbg
-					    ("%s found match for 422extended\n",
-					     __func__);
-					break;
-				}
-			}
-		}
-		break;
-
-	default:
-		err = -ENOTTY;
-	}
-
-	mydbg("%s returning err = 0x%x\n", __func__, err);
-	return err;
-}
-
-static struct usb_serial *find_the_box(unsigned int index)
-{
-	struct usb_serial *lastserial, *foundserial, *serial;
-	int counts = 0, index2;
-	lastserial = serial_table[0];
-	foundserial = NULL;
-	for (index2 = 0; index2 < SERIAL_TTY_MINORS; index2++) {
-		serial = serial_table[index2];
-
-		mydbg("%s index = 0x%x, index2 = 0x%x, serial = 0x%p\n",
-		      __func__, index, index2, serial);
-
-		if (serial) {
-			/* first see if this is the unit we'er looking for */
-			mydbg
-			    ("%s inside if(serial) counts = 0x%x , index = 0x%x\n",
-			     __func__, counts, index);
-			if (counts == index) {
-				/* we found the one we're looking for, copythe
-				 * product Id to user */
-				mydbg("%s we found the one we're looking for serial = 0x%p\n",
-				     __func__, serial);
-				foundserial = serial;
-				break;
-			}
-
-			if (serial != lastserial) {
-				/* when we have a change in the pointer */
-				lastserial = serial;
-				counts++;
-			}
-		} else
-			break;	/* no matches */
-	}
-
-	mydbg("%s returning foundserial = 0x%p\n", __func__, foundserial);
-	return foundserial;
-}
-
-static int EmulateWriteQMCR_Reg(int index, unsigned uc_value)
-{
-
-	__u16 ATC_Mode = 0;
-	struct usb_serial *serial;
-	int status;
-	struct qt_get_device_data DeviceData;
-	unsigned uc_temp = 0;
-	mydbg("Inside %s, uc_value = 0x%x\n", __func__, uc_value);
-
-	DeviceData.porta = 0;
-	DeviceData.portb = 0;
-	serial = find_the_box(index);
-	/* Determine Duplex mode */
-	if (!(serial))
-		return -ENOTTY;
-	status = box_get_device(serial, &DeviceData);
-	if (status < 0) {
-		mydbg(__FILE__ "box_set_device failed\n");
-		return status;
-	}
-
-	uc_temp = uc_value & QMCR_HALF_DUPLEX_MASK;
-	switch (uc_temp) {
-	case QMCR_FULL_DUPLEX:
-		DeviceData.porta &= ~DUPMODE_BITS;
-		DeviceData.porta |= FULL_DUPLEX;
-		ATC_Mode = ATC_DISABLED;
-		break;
-	case QMCR_HALF_DUPLEX_RTS:
-		DeviceData.porta &= ~DUPMODE_BITS;
-		DeviceData.porta |= HALF_DUPLEX_RTS;
-		ATC_Mode = ATC_RTS_ENABLED;
-		break;
-	case QMCR_HALF_DUPLEX_DTR:
-		DeviceData.porta &= ~DUPMODE_BITS;
-		DeviceData.porta |= HALF_DUPLEX_DTR;
-		ATC_Mode = ATC_DTR_ENABLED;
-		break;
-	default:
-		break;
-	}
-
-	uc_temp = uc_value & QMCR_CONNECTOR_MASK;
-	switch (uc_temp) {
-	case QMCR_MODEM_CONTROL:
-		DeviceData.portb &= ~LOOPMODE_BITS;	/* reset connection bits */
-		DeviceData.portb |= MODEM_CTRL;
-		break;
-	case QMCR_ALL_LOOPBACK:
-		DeviceData.portb &= ~LOOPMODE_BITS;	/* reset connection bits */
-		DeviceData.portb |= ALL_LOOPBACK;
-		break;
-	}
-
-	mydbg(__FILE__ "Calling box_set_device with failed\n");
-	status = box_set_device(serial, &DeviceData);
-	if (status < 0) {
-		mydbg(__FILE__ "box_set_device failed\n");
-		return status;
-	}
-
-	/* This bit (otherwise unused) i'll used  to detect whether ATC is
-	 * selected */
-	if (uc_value & QMCR_RX_EN_MASK) {
-
-		mydbg(__FILE__
-		      "calling BoxsetATC with DeviceData.porta = 0x%x and DeviceData.portb = 0x%x\n",
-		      DeviceData.porta, DeviceData.portb);
-		status = BoxSetATC(serial, ATC_Mode);
-		if (status < 0) {
-			mydbg(__FILE__ "BoxSetATC failed\n");
-			return status;
-		}
-	} else {
-
-		mydbg(__FILE__
-		      "calling BoxsetATC with DeviceData.porta = 0x%x and DeviceData.portb = 0x%x\n",
-		      DeviceData.porta, DeviceData.portb);
-		status = BoxSetATC(serial, ATC_DISABLED);
-		if (status < 0) {
-			mydbg(__FILE__ "BoxSetATC failed\n");
-			return status;
-		}
-	}
-
-	return 0;
-
-}
-
-static int EmulateReadQMCR_Reg(int index, unsigned *uc_value)
-{
-	struct usb_serial *serial;
-	int status;
-	struct qt_get_device_data DeviceData;
-	__u8 uc_temp;
-
-	*uc_value = 0;
-
-	serial = find_the_box(index);
-	if (!(serial))
-		return -ENOTTY;
-
-	status = box_get_device(serial, &DeviceData);
-	if (status < 0) {
-		mydbg(__FILE__ "box_get_device failed\n");
-		return status;
-	}
-	uc_temp = DeviceData.porta & DUPMODE_BITS;
-	switch (uc_temp) {
-	case FULL_DUPLEX:
-		*uc_value |= QMCR_FULL_DUPLEX;
-		break;
-	case HALF_DUPLEX_RTS:
-		*uc_value |= QMCR_HALF_DUPLEX_RTS;
-		break;
-	case HALF_DUPLEX_DTR:
-		*uc_value |= QMCR_HALF_DUPLEX_DTR;
-		break;
-	default:
-		break;
-	}
-
-	/* I use this for ATC control se */
-	uc_temp = DeviceData.portb & LOOPMODE_BITS;
-
-	switch (uc_temp) {
-	case ALL_LOOPBACK:
-		*uc_value |= QMCR_ALL_LOOPBACK;
-		break;
-	case MODEM_CTRL:
-		*uc_value |= QMCR_MODEM_CONTROL;
-		break;
-	default:
-		break;
-
-	}
-	return 0;
-
-}
-
-static int __init serqt_usb_init(void)
-{
-	int i, result;
-	int status = 0;
-
-	mydbg("%s\n", __func__);
-	tty_set_operations(&serial_tty_driver, &serial_ops);
-	result = tty_register_driver(&serial_tty_driver);
-	if (result) {
-		mydbg("tty_register_driver failed error = 0x%x", result);
-		return result;
-	}
-
-	/* Initalize our global data */
-	for (i = 0; i < SERIAL_TTY_MINORS; ++i)
-		serial_table[i] = NULL;
-
-	/* register this driver with the USB subsystem */
-	result = usb_register(&serqt_usb_driver);
-	if (result < 0) {
-		err("usb_register failed for the " __FILE__
-		    " driver. Error number %d", result);
-		return result;
-	}
-	status = 0;		/* Dynamic assignment of major number */
-	major_number =
-	    register_chrdev(status, "SerialQT_USB", &serialqt_usb_fops);
-	if (major_number < 0) {
-		mydbg(KERN_DEBUG "No devices found \n\n");
-		return -EBUSY;
-	} else
-		mydbg(KERN_DEBUG "SerQT_USB major number assignment = %d \n\n",
-		      major_number);
-
-	printk(KERN_INFO DRIVER_DESC " " DRIVER_VERSION);
-	return 0;
-}
-
-static void __exit serqt_usb_exit(void)
-{
-	/* deregister this driver with the USB subsystem */
-	usb_deregister(&serqt_usb_driver);
-	tty_unregister_driver(&serial_tty_driver);
-	unregister_chrdev(major_number, "SerialQT_USB");
-}
-
-module_init(serqt_usb_init);
-module_exit(serqt_usb_exit);
-
-MODULE_AUTHOR(DRIVER_AUTHOR);
-MODULE_DESCRIPTION(DRIVER_DESC);
-MODULE_LICENSE("GPL");
diff --git a/drivers/staging/serqt_usb/Kconfig b/drivers/staging/serqt_usb2/Kconfig
similarity index 76%
rename from drivers/staging/serqt_usb/Kconfig
rename to drivers/staging/serqt_usb2/Kconfig
index cc1af5d..f4fed40 100644
--- a/drivers/staging/serqt_usb/Kconfig
+++ b/drivers/staging/serqt_usb2/Kconfig
@@ -1,4 +1,4 @@
-config USB_SERIAL_QUATECH_ESU100
+config USB_SERIAL_QUATECH2
 	tristate "USB Quatech ESU-100 8 Port Serial Driver"
 	depends on USB_SERIAL
 	help
@@ -6,4 +6,4 @@
 	  serial adapter.
 
 	  To compile this driver as a module, choose M here: the
-	  module will be called serqt_usb.
+	  module will be called serqt_usb2.
diff --git a/drivers/staging/serqt_usb2/Makefile b/drivers/staging/serqt_usb2/Makefile
new file mode 100644
index 0000000..2157861
--- /dev/null
+++ b/drivers/staging/serqt_usb2/Makefile
@@ -0,0 +1 @@
+obj-$(CONFIG_USB_SERIAL_QUATECH2)		+= serqt_usb2.o
diff --git a/drivers/staging/serqt_usb2/serqt_usb2.c b/drivers/staging/serqt_usb2/serqt_usb2.c
new file mode 100644
index 0000000..581232b
--- /dev/null
+++ b/drivers/staging/serqt_usb2/serqt_usb2.c
@@ -0,0 +1,1664 @@
+/*
+ * This code was developed for the Quatech USB line for linux, it used
+ * much of the code developed by Greg Kroah-Hartman for USB serial devices
+ *
+ */
+
+#include <linux/errno.h>
+#include <linux/init.h>
+#include <linux/slab.h>
+#include <linux/tty.h>
+#include <linux/tty_driver.h>
+#include <linux/tty_flip.h>
+#include <linux/module.h>
+#include <linux/serial.h>
+#include <linux/usb.h>
+#include <linux/usb/serial.h>
+#include <linux/uaccess.h>
+
+static int debug;
+
+/* Version Information */
+#define DRIVER_VERSION "v2.14"
+#define DRIVER_AUTHOR "Tim Gobeli, Quatech, Inc"
+#define DRIVER_DESC "Quatech USB to Serial Driver"
+
+#define	USB_VENDOR_ID_QUATECH			0x061d	/* Quatech VID */
+#define QUATECH_SSU100	0xC020	/* SSU100 */
+#define QUATECH_SSU200	0xC030	/* SSU200 */
+#define QUATECH_DSU100	0xC040	/* DSU100 */
+#define QUATECH_DSU200	0xC050	/* DSU200 */
+#define QUATECH_QSU100	0xC060	/* QSU100 */
+#define QUATECH_QSU200	0xC070	/* QSU200 */
+#define QUATECH_ESU100A	0xC080	/* ESU100A */
+#define QUATECH_ESU100B	0xC081	/* ESU100B */
+#define QUATECH_ESU200A	0xC0A0	/* ESU200A */
+#define QUATECH_ESU200B	0xC0A1	/* ESU200B */
+#define QUATECH_HSU100A	0xC090	/* HSU100A */
+#define QUATECH_HSU100B	0xC091	/* HSU100B */
+#define QUATECH_HSU100C	0xC092	/* HSU100C */
+#define QUATECH_HSU100D	0xC093	/* HSU100D */
+#define QUATECH_HSU200A	0xC0B0	/* HSU200A */
+#define QUATECH_HSU200B	0xC0B1	/* HSU200B */
+#define QUATECH_HSU200C	0xC0B2	/* HSU200C */
+#define QUATECH_HSU200D	0xC0B3	/* HSU200D */
+#define QUATECH_SSU100_2  0xC120	/* SSU100_2 */
+#define QUATECH_DSU100_2  0xC140	/* DSU100_2 */
+#define QUATECH_DSU400_2  0xC150	/* DSU400_2 */
+#define QUATECH_QSU100_2  0xC160	/* QSU100_2 */
+#define QUATECH_QSU400_2  0xC170	/* QSU400_2 */
+#define QUATECH_ESU400_2  0xC180	/* ESU400_2 */
+#define QUATECH_ESU100_2  0xC1A0	/* ESU100_2 */
+
+#define QT_SET_GET_DEVICE           0xc2
+#define QT_OPEN_CLOSE_CHANNEL       0xca
+#define QT_GET_SET_PREBUF_TRIG_LVL  0xcc
+#define QT_SET_ATF                  0xcd
+#define QT_GET_SET_REGISTER         0xc0
+#define QT_GET_SET_UART             0xc1
+#define QT_HW_FLOW_CONTROL_MASK     0xc5
+#define QT_SW_FLOW_CONTROL_MASK     0xc6
+#define QT_SW_FLOW_CONTROL_DISABLE  0xc7
+#define QT_BREAK_CONTROL            0xc8
+
+#define USBD_TRANSFER_DIRECTION_IN    0xc0
+#define USBD_TRANSFER_DIRECTION_OUT   0x40
+
+#define  MAX_BAUD_RATE              460800
+#define  MAX_BAUD_REMAINDER         4608
+
+#define  DIV_LATCH_LS               0x00
+#define  XMT_HOLD_REGISTER          0x00
+#define  XVR_BUFFER_REGISTER        0x00
+#define  DIV_LATCH_MS               0x01
+#define  FIFO_CONTROL_REGISTER      0x02
+#define  LINE_CONTROL_REGISTER      0x03
+#define  MODEM_CONTROL_REGISTER     0x04
+#define  LINE_STATUS_REGISTER       0x05
+#define  MODEM_STATUS_REGISTER      0x06
+
+#define  SERIAL_MCR_DTR             0x01
+#define  SERIAL_MCR_RTS             0x02
+#define  SERIAL_MCR_LOOP            0x10
+
+#define  SERIAL_MSR_CTS             0x10
+#define  SERIAL_MSR_CD              0x80
+#define  SERIAL_MSR_RI              0x40
+#define  SERIAL_MSR_DSR             0x20
+#define  SERIAL_MSR_MASK            0xf0
+
+#define  SERIAL_8_DATA              0x03
+#define  SERIAL_7_DATA              0x02
+#define  SERIAL_6_DATA              0x01
+#define  SERIAL_5_DATA              0x00
+
+#define  SERIAL_ODD_PARITY          0X08
+#define  SERIAL_EVEN_PARITY         0X18
+#define  SERIAL_TWO_STOPB           0x04
+#define  SERIAL_ONE_STOPB           0x00
+
+#define DEFAULT_DIVISOR  0x30	/* gives 9600 baud rate */
+#define DEFAULT_LCR SERIAL_8_DATA	/* 8, none , 1 */
+
+#define FULLPWRBIT          0x00000080
+#define NEXT_BOARD_POWER_BIT        0x00000004
+
+#define SERIAL_LSR_OE       0x02
+#define SERIAL_LSR_PE       0x04
+#define SERIAL_LSR_FE       0x08
+#define SERIAL_LSR_BI       0x10
+
+#define  SERIAL_MSR_CTS             0x10
+#define  SERIAL_MSR_CD              0x80
+#define  SERIAL_MSR_RI              0x40
+#define  SERIAL_MSR_DSR             0x20
+#define  SERIAL_MSR_MASK            0xf0
+
+#define PREFUFF_LEVEL_CONSERVATIVE  128
+#define ATC_DISABLED                0x0
+
+#define RR_BITS             0x03	/* for clearing clock bits */
+#define DUPMODE_BITS        0xc0
+#define CLKS_X4             0x02
+
+#define LOOPMODE_BITS       0x41	/* LOOP1 = b6, LOOP0 = b0 (PORT B) */
+#define ALL_LOOPBACK        0x01
+#define MODEM_CTRL          0x40
+#define RS232_MODE          0x00
+
+static struct usb_device_id serqt_id_table[] = {
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_SSU100)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_SSU200)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU100)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU200)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU100)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU200)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU100A)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU100B)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU200A)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU200B)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_HSU100A)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_HSU100B)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_HSU100C)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_HSU100D)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_HSU200A)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_HSU200B)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_HSU200C)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_HSU200D)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_SSU100_2)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU100_2)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU400_2)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU100_2)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU400_2)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU400_2)},
+	{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU100_2)},
+	{}			/* Terminating entry */
+};
+
+MODULE_DEVICE_TABLE(usb, serqt_id_table);
+
+struct qt_get_device_data {
+	__u8 porta;
+	__u8 portb;
+	__u8 portc;
+};
+
+struct qt_open_channel_data {
+	__u8 line_status;
+	__u8 modem_status;
+};
+
+struct quatech_port {
+	int port_num;		/* number of the port */
+	struct urb *write_urb;	/* write URB for this port */
+	struct urb *read_urb;	/* read URB for this port */
+	struct urb *int_urb;
+
+	__u8 shadowLCR;		/* last LCR value received */
+	__u8 shadowMCR;		/* last MCR value received */
+	__u8 shadowMSR;		/* last MSR value received */
+	__u8 shadowLSR;		/* last LSR value received */
+	char open_ports;
+
+	/* Used for TIOCMIWAIT */
+	wait_queue_head_t msr_wait;
+	char prev_status, diff_status;
+
+	wait_queue_head_t wait;
+
+	struct async_icount icount;
+
+	struct usb_serial_port *port;	/* owner of this object */
+	struct qt_get_device_data DeviceData;
+	spinlock_t lock;
+	bool read_urb_busy;
+	int RxHolding;
+	int ReadBulkStopped;
+	char closePending;
+};
+
+static struct usb_driver serqt_usb_driver = {
+	.name = "quatech-usb-serial",
+	.probe = usb_serial_probe,
+	.disconnect = usb_serial_disconnect,
+	.id_table = serqt_id_table,
+	.no_dynamic_id = 1,
+};
+
+static int port_paranoia_check(struct usb_serial_port *port,
+			       const char *function)
+{
+	if (!port) {
+		dbg("%s - port == NULL", function);
+		return -1;
+	}
+	if (!port->serial) {
+		dbg("%s - port->serial == NULL\n", function);
+		return -1;
+	}
+
+	return 0;
+}
+
+static int serial_paranoia_check(struct usb_serial *serial,
+				 const char *function)
+{
+	if (!serial) {
+		dbg("%s - serial == NULL\n", function);
+		return -1;
+	}
+
+	if (!serial->type) {
+		dbg("%s - serial->type == NULL!", function);
+		return -1;
+	}
+
+	return 0;
+}
+
+static inline struct quatech_port *qt_get_port_private(struct usb_serial_port
+						       *port)
+{
+	return (struct quatech_port *)usb_get_serial_port_data(port);
+}
+
+static inline void qt_set_port_private(struct usb_serial_port *port,
+				       struct quatech_port *data)
+{
+	usb_set_serial_port_data(port, (void *)data);
+}
+
+static struct usb_serial *get_usb_serial(struct usb_serial_port *port,
+					 const char *function)
+{
+	/* if no port was specified, or it fails a paranoia check */
+	if (!port ||
+	    port_paranoia_check(port, function) ||
+	    serial_paranoia_check(port->serial, function)) {
+		/*
+		 * then say that we dont have a valid usb_serial thing,
+		 * which will end up genrating -ENODEV return values
+		 */
+		return NULL;
+	}
+
+	return port->serial;
+}
+
+static void ProcessLineStatus(struct quatech_port *qt_port,
+			      unsigned char line_status)
+{
+
+	qt_port->shadowLSR =
+	    line_status & (SERIAL_LSR_OE | SERIAL_LSR_PE | SERIAL_LSR_FE |
+			   SERIAL_LSR_BI);
+	return;
+}
+
+static void ProcessModemStatus(struct quatech_port *qt_port,
+			       unsigned char modem_status)
+{
+
+	qt_port->shadowMSR = modem_status;
+	wake_up_interruptible(&qt_port->wait);
+	return;
+}
+
+static void ProcessRxChar(struct usb_serial_port *port, unsigned char Data)
+{
+	struct tty_struct *tty;
+	struct urb *urb = port->read_urb;
+	tty = tty_port_tty_get(&port->port);
+
+	/* if we insert more than TTY_FLIPBUF_SIZE characters, we drop them. */
+
+	if (tty && urb->actual_length) {
+		tty_buffer_request_room(tty, 1);
+		tty_insert_flip_string(tty, &Data, 1);
+		/* tty_flip_buffer_push(tty); */
+	}
+
+	return;
+}
+
+static void qt_write_bulk_callback(struct urb *urb)
+{
+	struct tty_struct *tty;
+	int status;
+	struct quatech_port *quatech_port;
+
+	status = urb->status;
+
+	if (status) {
+		dbg("nonzero write bulk status received:%d\n", status);
+		return;
+	}
+
+	quatech_port = urb->context;
+
+	dbg("%s - port %d\n", __func__, quatech_port->port_num);
+
+	tty = tty_port_tty_get(&quatech_port->port->port);
+
+	if (tty)
+		tty_wakeup(tty);
+	tty_kref_put(tty);
+}
+
+static void qt_interrupt_callback(struct urb *urb)
+{
+	/* FIXME */
+}
+
+static void qt_read_bulk_callback(struct urb *urb)
+{
+
+	struct usb_serial_port *port = urb->context;
+	struct usb_serial *serial = get_usb_serial(port, __func__);
+	struct quatech_port *qt_port = qt_get_port_private(port);
+	unsigned char *data;
+	struct tty_struct *tty;
+	unsigned int index;
+	unsigned int RxCount;
+	int i, result;
+	int flag, flag_data;
+
+	if (urb->status) {
+		qt_port->ReadBulkStopped = 1;
+		dbg("%s - nonzero write bulk status received: %d\n",
+		    __func__, urb->status);
+		return;
+	}
+
+	tty = tty_port_tty_get(&port->port);
+	if (!tty) {
+		dbg("%s - bad tty pointer - exiting", __func__);
+		return;
+	}
+
+	data = urb->transfer_buffer;
+
+	RxCount = urb->actual_length;
+
+	/* index = MINOR(port->tty->device) - serial->minor; */
+	index = tty->index - serial->minor;
+
+	dbg("%s - port %d\n", __func__, port->number);
+	dbg("%s - port->RxHolding = %d\n", __func__, qt_port->RxHolding);
+
+	if (port_paranoia_check(port, __func__) != 0) {
+		dbg("%s - port_paranoia_check, exiting\n", __func__);
+		qt_port->ReadBulkStopped = 1;
+		return;
+	}
+
+	if (!serial) {
+		dbg("%s - bad serial pointer, exiting\n", __func__);
+		return;
+	}
+	if (qt_port->closePending == 1) {
+		/* Were closing , stop reading */
+		dbg("%s - (qt_port->closepending == 1\n", __func__);
+		qt_port->ReadBulkStopped = 1;
+		return;
+	}
+
+	/*
+	 * RxHolding is asserted by throttle, if we assert it, we're not
+	 * receiving any more characters and let the box handle the flow
+	 * control
+	 */
+	if (qt_port->RxHolding == 1) {
+		qt_port->ReadBulkStopped = 1;
+		return;
+	}
+
+	if (urb->status) {
+		qt_port->ReadBulkStopped = 1;
+
+		dbg("%s - nonzero read bulk status received: %d\n",
+		    __func__, urb->status);
+		return;
+	}
+
+	if (tty && RxCount) {
+		flag_data = 0;
+		for (i = 0; i < RxCount; ++i) {
+			/* Look ahead code here */
+			if ((i <= (RxCount - 3)) && (data[i] == 0x1b)
+			    && (data[i + 1] == 0x1b)) {
+				flag = 0;
+				switch (data[i + 2]) {
+				case 0x00:
+					/* line status change 4th byte must follow */
+					if (i > (RxCount - 4)) {
+						dbg("Illegal escape seuences in received data\n");
+						break;
+					}
+					ProcessLineStatus(qt_port, data[i + 3]);
+					i += 3;
+					flag = 1;
+					break;
+
+				case 0x01:
+					/* Modem status status change 4th byte must follow */
+					dbg("Modem status status. \n");
+					if (i > (RxCount - 4)) {
+						dbg("Illegal escape sequences in received data\n");
+						break;
+					}
+					ProcessModemStatus(qt_port,
+							   data[i + 3]);
+					i += 3;
+					flag = 1;
+					break;
+				case 0xff:
+					dbg("No status sequence. \n");
+
+					ProcessRxChar(port, data[i]);
+					ProcessRxChar(port, data[i + 1]);
+					i += 2;
+					break;
+				}
+				if (flag == 1)
+					continue;
+			}
+
+			if (tty && urb->actual_length) {
+				tty_buffer_request_room(tty, 1);
+				tty_insert_flip_string(tty, (data + i), 1);
+			}
+
+		}
+		tty_flip_buffer_push(tty);
+	}
+
+	/* Continue trying to always read  */
+	usb_fill_bulk_urb(port->read_urb, serial->dev,
+			  usb_rcvbulkpipe(serial->dev,
+					  port->bulk_in_endpointAddress),
+			  port->read_urb->transfer_buffer,
+			  port->read_urb->transfer_buffer_length,
+			  qt_read_bulk_callback, port);
+	result = usb_submit_urb(port->read_urb, GFP_ATOMIC);
+	if (result)
+		dbg("%s - failed resubmitting read urb, error %d",
+		    __func__, result);
+	else {
+		if (tty && RxCount) {
+			tty_flip_buffer_push(tty);
+			tty_schedule_flip(tty);
+		}
+	}
+
+	schedule_work(&port->work);
+}
+
+/*
+ * qt_get_device
+ *   Issue a GET_DEVICE vendor-specific request on the default control pipe If
+ *   successful, fills in the qt_get_device_data structure pointed to by
+ *   device_data, otherwise return a negative error number of the problem.
+ */
+
+static int qt_get_device(struct usb_serial *serial,
+			 struct qt_get_device_data *device_data)
+{
+	int result;
+	unsigned char *transfer_buffer;
+
+	transfer_buffer =
+	    kmalloc(sizeof(struct qt_get_device_data), GFP_KERNEL);
+	if (!transfer_buffer)
+		return -ENOMEM;
+
+	result = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
+				 QT_SET_GET_DEVICE, 0xc0, 0, 0,
+				 transfer_buffer,
+				 sizeof(struct qt_get_device_data), 300);
+	if (result > 0)
+		memcpy(device_data, transfer_buffer,
+		       sizeof(struct qt_get_device_data));
+	kfree(transfer_buffer);
+
+	return result;
+}
+
+/****************************************************************************
+ *  BoxSetPrebufferLevel
+   TELLS BOX WHEN TO ASSERT FLOW CONTROL
+ ****************************************************************************/
+static int BoxSetPrebufferLevel(struct usb_serial *serial)
+{
+	int result;
+	__u16 buffer_length;
+
+	buffer_length = PREFUFF_LEVEL_CONSERVATIVE;
+	result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
+				 QT_GET_SET_PREBUF_TRIG_LVL, 0x40,
+				 buffer_length, 0, NULL, 0, 300);
+	return result;
+}
+
+/****************************************************************************
+ *  BoxSetATC
+   TELLS BOX WHEN TO ASSERT automatic transmitter control
+   ****************************************************************************/
+static int BoxSetATC(struct usb_serial *serial, __u16 n_Mode)
+{
+	int result;
+	__u16 buffer_length;
+
+	buffer_length = PREFUFF_LEVEL_CONSERVATIVE;
+
+	result =
+	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
+			    QT_SET_ATF, 0x40, n_Mode, 0, NULL, 0, 300);
+
+	return result;
+}
+
+/**
+ * qt_set_device
+ *   Issue a SET_DEVICE vendor-specific request on the default control pipe If
+ *   successful returns the number of bytes written, otherwise it returns a
+ *   negative error number of the problem.
+ */
+static int qt_set_device(struct usb_serial *serial,
+			 struct qt_get_device_data *device_data)
+{
+	int result;
+	__u16 length;
+	__u16 PortSettings;
+
+	PortSettings = ((__u16) (device_data->portb));
+	PortSettings = (PortSettings << 8);
+	PortSettings += ((__u16) (device_data->porta));
+
+	length = sizeof(struct qt_get_device_data);
+	dbg("%s - PortSettings = 0x%x\n", __func__, PortSettings);
+
+	result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
+				 QT_SET_GET_DEVICE, 0x40, PortSettings,
+				 0, NULL, 0, 300);
+	return result;
+}
+
+static int qt_open_channel(struct usb_serial *serial, __u16 Uart_Number,
+			   struct qt_open_channel_data *pDeviceData)
+{
+	int result;
+
+	result = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
+				 QT_OPEN_CLOSE_CHANNEL,
+				 USBD_TRANSFER_DIRECTION_IN, 1, Uart_Number,
+				 pDeviceData,
+				 sizeof(struct qt_open_channel_data), 300);
+
+	return result;
+
+}
+
+static int qt_close_channel(struct usb_serial *serial, __u16 Uart_Number)
+{
+	int result;
+
+	result = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
+				 QT_OPEN_CLOSE_CHANNEL,
+				 USBD_TRANSFER_DIRECTION_OUT, 0, Uart_Number,
+				 NULL, 0, 300);
+
+	return result;
+
+}
+
+/****************************************************************************
+* BoxGetRegister
+*	issuse a GET_REGISTER vendor-spcific request on the default control pipe
+*	If successful, fills in the  pValue with the register value asked for
+****************************************************************************/
+static int BoxGetRegister(struct usb_serial *serial, unsigned short Uart_Number,
+			  unsigned short Register_Num, __u8 *pValue)
+{
+	int result;
+	__u16 current_length;
+
+	current_length = sizeof(struct qt_get_device_data);
+
+	result =
+	    usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
+			    QT_GET_SET_REGISTER, 0xC0, Register_Num,
+			    Uart_Number, (void *)pValue, sizeof(*pValue), 300);
+
+	return result;
+}
+
+/****************************************************************************
+* BoxSetRegister
+*	issuse a GET_REGISTER vendor-spcific request on the default control pipe
+*	If successful, fills in the  pValue with the register value asked for
+****************************************************************************/
+static int BoxSetRegister(struct usb_serial *serial, unsigned short Uart_Number,
+			  unsigned short Register_Num, unsigned short Value)
+{
+	int result;
+	unsigned short RegAndByte;
+
+	RegAndByte = Value;
+	RegAndByte = RegAndByte << 8;
+	RegAndByte = RegAndByte + Register_Num;
+
+/*
+	result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
+				 QT_GET_SET_REGISTER, 0xC0, Register_Num,
+				 Uart_Number, NULL, 0, 300);
+*/
+
+	result =
+	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
+			    QT_GET_SET_REGISTER, 0x40, RegAndByte, Uart_Number,
+			    NULL, 0, 300);
+
+	return result;
+}
+
+/*
+ * qt_setuart
+ * issuse a SET_UART vendor-spcific request on the default control pipe
+ * If successful sets baud rate divisor and LCR value
+ */
+static int qt_setuart(struct usb_serial *serial, unsigned short Uart_Number,
+		      unsigned short default_divisor, unsigned char default_LCR)
+{
+	int result;
+	unsigned short UartNumandLCR;
+
+	UartNumandLCR = (default_LCR << 8) + Uart_Number;
+
+	result =
+	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
+			    QT_GET_SET_UART, 0x40, default_divisor,
+			    UartNumandLCR, NULL, 0, 300);
+
+	return result;
+}
+
+static int BoxSetHW_FlowCtrl(struct usb_serial *serial, unsigned int index,
+			     int bSet)
+{
+	__u8 mcr = 0;
+	__u8 msr = 0, MOUT_Value = 0;
+	unsigned int status;
+
+	if (bSet == 1) {
+		/* flow control, box will clear RTS line to prevent remote */
+		mcr = SERIAL_MCR_RTS;
+	} /* device from xmitting more chars */
+	else {
+		/* no flow control to remote device */
+		mcr = 0;
+
+	}
+	MOUT_Value = mcr << 8;
+
+	if (bSet == 1) {
+		/* flow control, box will inhibit xmit data if CTS line is
+		 * asserted */
+		msr = SERIAL_MSR_CTS;
+	} else {
+		/* Box will not inhimbe xmit data due to CTS line */
+		msr = 0;
+	}
+	MOUT_Value |= msr;
+
+	status =
+	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
+			    QT_HW_FLOW_CONTROL_MASK, 0x40, MOUT_Value,
+			    index, NULL, 0, 300);
+	return status;
+
+}
+
+static int BoxSetSW_FlowCtrl(struct usb_serial *serial, __u16 index,
+			     unsigned char stop_char, unsigned char start_char)
+{
+	__u16 nSWflowout;
+	int result;
+
+	nSWflowout = start_char << 8;
+	nSWflowout = (unsigned short)stop_char;
+
+	result =
+	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
+			    QT_SW_FLOW_CONTROL_MASK, 0x40, nSWflowout,
+			    index, NULL, 0, 300);
+	return result;
+
+}
+
+static int BoxDisable_SW_FlowCtrl(struct usb_serial *serial, __u16 index)
+{
+	int result;
+
+	result =
+	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
+			    QT_SW_FLOW_CONTROL_DISABLE, 0x40, 0, index,
+			    NULL, 0, 300);
+	return result;
+
+}
+
+static int qt_startup(struct usb_serial *serial)
+{
+	struct usb_serial_port *port;
+	struct quatech_port *qt_port;
+	struct qt_get_device_data DeviceData;
+	int i;
+	int status;
+
+	dbg("enterting %s", __func__);
+
+	/* Now setup per port private data */
+	for (i = 0; i < serial->num_ports; i++) {
+		port = serial->port[i];
+		qt_port = kzalloc(sizeof(*qt_port), GFP_KERNEL);
+		if (!qt_port) {
+			dbg("%s: kmalloc for quatech_port (%d) failed!.",
+			    __func__, i);
+			return -ENOMEM;
+		}
+		spin_lock_init(&qt_port->lock);
+
+		usb_set_serial_port_data(port, qt_port);
+
+	}
+
+	status = qt_get_device(serial, &DeviceData);
+	if (status < 0) {
+		dbg(__FILE__ "box_get_device failed");
+		goto startup_error;
+	}
+
+	dbg(__FILE__ "DeviceData.portb = 0x%x", DeviceData.portb);
+
+	DeviceData.portb &= ~FULLPWRBIT;
+	dbg(__FILE__ "Changing DeviceData.portb to 0x%x", DeviceData.portb);
+
+	status = qt_set_device(serial, &DeviceData);
+	if (status < 0) {
+		dbg(__FILE__ "qt_set_device failed\n");
+		goto startup_error;
+	}
+
+	status = qt_get_device(serial, &DeviceData);
+	if (status < 0) {
+		dbg(__FILE__ "qt_get_device failed");
+		goto startup_error;
+	}
+
+	switch (serial->dev->descriptor.idProduct) {
+	case QUATECH_SSU100:
+	case QUATECH_DSU100:
+	case QUATECH_QSU100:
+	case QUATECH_ESU100A:
+	case QUATECH_ESU100B:
+	case QUATECH_HSU100A:
+	case QUATECH_HSU100B:
+	case QUATECH_HSU100C:
+	case QUATECH_HSU100D:
+		DeviceData.porta &= ~(RR_BITS | DUPMODE_BITS);
+		DeviceData.porta |= CLKS_X4;
+		DeviceData.portb &= ~(LOOPMODE_BITS);
+		DeviceData.portb |= RS232_MODE;
+		break;
+
+	case QUATECH_SSU200:
+	case QUATECH_DSU200:
+	case QUATECH_QSU200:
+	case QUATECH_ESU200A:
+	case QUATECH_ESU200B:
+	case QUATECH_HSU200A:
+	case QUATECH_HSU200B:
+	case QUATECH_HSU200C:
+	case QUATECH_HSU200D:
+		DeviceData.porta &= ~(RR_BITS | DUPMODE_BITS);
+		DeviceData.porta |= CLKS_X4;
+		DeviceData.portb &= ~(LOOPMODE_BITS);
+		DeviceData.portb |= ALL_LOOPBACK;
+		break;
+	default:
+		DeviceData.porta &= ~(RR_BITS | DUPMODE_BITS);
+		DeviceData.porta |= CLKS_X4;
+		DeviceData.portb &= ~(LOOPMODE_BITS);
+		DeviceData.portb |= RS232_MODE;
+		break;
+
+	}
+
+	status = BoxSetPrebufferLevel(serial);	/* sets to default value */
+	if (status < 0) {
+		dbg(__FILE__ "BoxSetPrebufferLevel failed\n");
+		goto startup_error;
+	}
+
+	status = BoxSetATC(serial, ATC_DISABLED);
+	if (status < 0) {
+		dbg(__FILE__ "BoxSetATC failed\n");
+		goto startup_error;
+	}
+
+	dbg(__FILE__ "DeviceData.portb = 0x%x", DeviceData.portb);
+
+	DeviceData.portb |= NEXT_BOARD_POWER_BIT;
+	dbg(__FILE__ "Changing DeviceData.portb to 0x%x", DeviceData.portb);
+
+	status = qt_set_device(serial, &DeviceData);
+	if (status < 0) {
+		dbg(__FILE__ "qt_set_device failed\n");
+		goto startup_error;
+	}
+
+	dbg("Exit Success %s\n", __func__);
+
+	return 0;
+
+startup_error:
+	for (i = 0; i < serial->num_ports; i++) {
+		port = serial->port[i];
+		qt_port = qt_get_port_private(port);
+		kfree(qt_port);
+		usb_set_serial_port_data(port, NULL);
+	}
+
+	dbg("Exit fail %s\n", __func__);
+
+	return -EIO;
+}
+
+static void qt_release(struct usb_serial *serial)
+{
+	struct usb_serial_port *port;
+	struct quatech_port *qt_port;
+	int i;
+
+	dbg("enterting %s", __func__);
+
+	for (i = 0; i < serial->num_ports; i++) {
+		port = serial->port[i];
+		if (!port)
+			continue;
+
+		qt_port = usb_get_serial_port_data(port);
+		kfree(qt_port);
+		usb_set_serial_port_data(port, NULL);
+	}
+
+}
+
+int qt_open(struct tty_struct *tty,
+	    struct usb_serial_port *port, struct file *filp)
+{
+	struct usb_serial *serial;
+	struct quatech_port *quatech_port;
+	struct quatech_port *port0;
+	struct qt_open_channel_data ChannelData;
+
+	int result;
+
+	if (port_paranoia_check(port, __func__))
+		return -ENODEV;
+
+	dbg("%s - port %d\n", __func__, port->number);
+
+	serial = port->serial;
+
+	if (serial_paranoia_check(serial, __func__))
+		return -ENODEV;
+
+	quatech_port = qt_get_port_private(port);
+	port0 = qt_get_port_private(serial->port[0]);
+
+	if (quatech_port == NULL || port0 == NULL)
+		return -ENODEV;
+
+	usb_clear_halt(serial->dev, port->write_urb->pipe);
+	usb_clear_halt(serial->dev, port->read_urb->pipe);
+	port0->open_ports++;
+
+	result = qt_get_device(serial, &port0->DeviceData);
+
+	/* Port specific setups */
+	result = qt_open_channel(serial, port->number, &ChannelData);
+	if (result < 0) {
+		dbg(__FILE__ "qt_open_channel failed\n");
+		return result;
+	}
+	dbg(__FILE__ "qt_open_channel completed.\n");
+
+/* FIXME: are these needed?  Does it even do anything useful? */
+	quatech_port->shadowLSR = ChannelData.line_status &
+	    (SERIAL_LSR_OE | SERIAL_LSR_PE | SERIAL_LSR_FE | SERIAL_LSR_BI);
+
+	quatech_port->shadowMSR = ChannelData.modem_status &
+	    (SERIAL_MSR_CTS | SERIAL_MSR_DSR | SERIAL_MSR_RI | SERIAL_MSR_CD);
+
+	/* Set Baud rate to default and turn off (default)flow control here */
+	result = qt_setuart(serial, port->number, DEFAULT_DIVISOR, DEFAULT_LCR);
+	if (result < 0) {
+		dbg(__FILE__ "qt_setuart failed\n");
+		return result;
+	}
+	dbg(__FILE__ "qt_setuart completed.\n");
+
+	/*
+	 * Put this here to make it responsive to stty and defauls set by
+	 * the tty layer
+	 */
+	/* FIXME: is this needed? */
+	/* qt_set_termios(tty, port, NULL); */
+
+	/*  Check to see if we've set up our endpoint info yet */
+	if (port0->open_ports == 1) {
+		if (serial->port[0]->interrupt_in_buffer == NULL) {
+			/* set up interrupt urb */
+			usb_fill_int_urb(serial->port[0]->interrupt_in_urb,
+					 serial->dev,
+					 usb_rcvintpipe(serial->dev,
+							serial->port[0]->interrupt_in_endpointAddress),
+					 serial->port[0]->interrupt_in_buffer,
+					 serial->port[0]->
+					 interrupt_in_urb->transfer_buffer_length,
+					 qt_interrupt_callback, serial,
+					 serial->port[0]->
+					 interrupt_in_urb->interval);
+
+			result =
+			    usb_submit_urb(serial->port[0]->interrupt_in_urb,
+					   GFP_KERNEL);
+			if (result) {
+				dev_err(&port->dev,
+					"%s - Error %d submitting "
+					"interrupt urb\n", __func__, result);
+			}
+
+		}
+
+	}
+
+	dbg("port number is %d \n", port->number);
+	dbg("serial number is %d \n", port->serial->minor);
+	dbg("Bulkin endpoint is %d \n", port->bulk_in_endpointAddress);
+	dbg("BulkOut endpoint is %d \n", port->bulk_out_endpointAddress);
+	dbg("Interrupt endpoint is %d \n", port->interrupt_in_endpointAddress);
+	dbg("port's number in the device is %d\n", quatech_port->port_num);
+	quatech_port->read_urb = port->read_urb;
+
+	/* set up our bulk in urb */
+
+	usb_fill_bulk_urb(quatech_port->read_urb,
+			  serial->dev,
+			  usb_rcvbulkpipe(serial->dev,
+					  port->bulk_in_endpointAddress),
+			  port->bulk_in_buffer,
+			  quatech_port->read_urb->transfer_buffer_length,
+			  qt_read_bulk_callback, quatech_port);
+
+	dbg("qt_open: bulkin endpoint is %d\n", port->bulk_in_endpointAddress);
+	quatech_port->read_urb_busy = true;
+	result = usb_submit_urb(quatech_port->read_urb, GFP_KERNEL);
+	if (result) {
+		dev_err(&port->dev,
+			"%s - Error %d submitting control urb\n",
+			__func__, result);
+		quatech_port->read_urb_busy = false;
+	}
+
+	/* initialize our wait queues */
+	init_waitqueue_head(&quatech_port->wait);
+	init_waitqueue_head(&quatech_port->msr_wait);
+
+	/* initialize our icount structure */
+	memset(&(quatech_port->icount), 0x00, sizeof(quatech_port->icount));
+
+	return 0;
+
+}
+
+static int qt_chars_in_buffer(struct tty_struct *tty)
+{
+	struct usb_serial_port *port = tty->driver_data;
+	struct usb_serial *serial;
+	int chars = 0;
+
+	serial = get_usb_serial(port, __func__);
+
+	dbg("%s - port %d\n", __func__, port->number);
+
+	if (serial->num_bulk_out) {
+		if (port->write_urb->status == -EINPROGRESS)
+			chars = port->write_urb->transfer_buffer_length;
+	}
+
+	dbg("%s - returns %d\n", __func__, chars);
+
+	return chars;
+}
+
+static void qt_block_until_empty(struct tty_struct *tty,
+				 struct quatech_port *qt_port)
+{
+	int timeout = HZ / 10;
+	int wait = 30;
+	int count;
+
+	while (1) {
+
+		count = qt_chars_in_buffer(tty);
+
+		if (count <= 0)
+			return;
+
+		interruptible_sleep_on_timeout(&qt_port->wait, timeout);
+
+		wait--;
+		if (wait == 0) {
+			dbg("%s - TIMEOUT", __func__);
+			return;
+		} else {
+			wait = 30;
+		}
+	}
+}
+
+static void qt_close(struct tty_struct *tty, struct usb_serial_port *port,
+		     struct file *filp)
+{
+	struct usb_serial *serial = port->serial;
+	struct quatech_port *qt_port;
+	struct quatech_port *port0;
+	int status;
+	unsigned int index;
+	status = 0;
+
+	dbg("%s - port %d\n", __func__, port->number);
+	index = tty->index - serial->minor;
+
+	qt_port = qt_get_port_private(port);
+	port0 = qt_get_port_private(serial->port[0]);
+
+	/* shutdown any bulk reads that might be going on */
+	if (serial->num_bulk_out)
+		usb_unlink_urb(port->write_urb);
+	if (serial->num_bulk_in)
+		usb_unlink_urb(port->read_urb);
+
+	/* wait up to for transmitter to empty */
+	if (serial->dev)
+		qt_block_until_empty(tty, qt_port);
+
+	/* Close uart channel */
+	status = qt_close_channel(serial, index);
+	if (status < 0)
+		dbg("%s - port %d qt_close_channel failed.\n",
+		    __func__, port->number);
+
+	port0->open_ports--;
+
+	dbg("qt_num_open_ports in close%d:in port%d\n",
+	    port0->open_ports, port->number);
+
+	if (port0->open_ports == 0) {
+		if (serial->port[0]->interrupt_in_urb) {
+			dbg("%s", "Shutdown interrupt_in_urb\n");
+			usb_kill_urb(serial->port[0]->interrupt_in_urb);
+		}
+
+	}
+
+	if (qt_port->write_urb) {
+		/* if this urb had a transfer buffer already (old tx) free it */
+		if (qt_port->write_urb->transfer_buffer != NULL)
+			kfree(qt_port->write_urb->transfer_buffer);
+		usb_free_urb(qt_port->write_urb);
+	}
+
+}
+
+static int qt_write(struct tty_struct *tty, struct usb_serial_port *port,
+		    const unsigned char *buf, int count)
+{
+	int result;
+	struct usb_serial *serial = get_usb_serial(port, __func__);
+
+	if (serial == NULL)
+		return -ENODEV;
+
+	dbg("%s - port %d\n", __func__, port->number);
+
+	if (count == 0) {
+		dbg("%s - write request of 0 bytes\n", __func__);
+		return 0;
+	}
+
+	/* only do something if we have a bulk out endpoint */
+	if (serial->num_bulk_out) {
+		if (port->write_urb->status == -EINPROGRESS) {
+			dbg("%s - already writing\n", __func__);
+			return 0;
+		}
+
+		count =
+		    (count > port->bulk_out_size) ? port->bulk_out_size : count;
+		memcpy(port->write_urb->transfer_buffer, buf, count);
+
+		/* set up our urb */
+
+		usb_fill_bulk_urb(port->write_urb, serial->dev,
+				  usb_sndbulkpipe(serial->dev,
+						  port->
+						  bulk_out_endpointAddress),
+				  port->write_urb->transfer_buffer, count,
+				  qt_write_bulk_callback, port);
+
+		/* send the data out the bulk port */
+		result = usb_submit_urb(port->write_urb, GFP_ATOMIC);
+		if (result)
+			dbg("%s - failed submitting write urb, error %d\n",
+			    __func__, result);
+		else
+			result = count;
+
+		return result;
+	}
+
+	/* no bulk out, so return 0 bytes written */
+	return 0;
+}
+
+static int qt_write_room(struct tty_struct *tty)
+{
+	struct usb_serial_port *port = tty->driver_data;
+	struct usb_serial *serial;
+	struct quatech_port *qt_port;
+	unsigned long flags;
+
+	int retval = -EINVAL;
+
+	if (port_paranoia_check(port, __func__)) {
+		dbg("%s", "Invalid port\n");
+		return -1;
+	}
+
+	serial = get_usb_serial(port, __func__);
+
+	if (!serial)
+		return -ENODEV;
+
+	qt_port = qt_get_port_private(port);
+
+	spin_lock_irqsave(&qt_port->lock, flags);
+
+	dbg("%s - port %d\n", __func__, port->number);
+
+	if (serial->num_bulk_out) {
+		if (port->write_urb->status != -EINPROGRESS)
+			retval = port->bulk_out_size;
+	}
+
+	spin_unlock_irqrestore(&qt_port->lock, flags);
+	return retval;
+
+}
+
+static int qt_ioctl(struct tty_struct *tty, struct file *file,
+		    unsigned int cmd, unsigned long arg)
+{
+	struct usb_serial_port *port = tty->driver_data;
+	struct quatech_port *qt_port = qt_get_port_private(port);
+	struct usb_serial *serial = get_usb_serial(port, __func__);
+	unsigned int index;
+
+	dbg("%s cmd 0x%04x", __func__, cmd);
+
+	index = tty->index - serial->minor;
+
+	if (cmd == TIOCMIWAIT) {
+		while (qt_port != NULL) {
+			interruptible_sleep_on(&qt_port->msr_wait);
+			if (signal_pending(current))
+				return -ERESTARTSYS;
+			else {
+				char diff = qt_port->diff_status;
+
+				if (diff == 0)
+					return -EIO;	/* no change => error */
+
+				/* Consume all events */
+				qt_port->diff_status = 0;
+
+				if (((arg & TIOCM_RNG)
+				     && (diff & SERIAL_MSR_RI))
+				    || ((arg & TIOCM_DSR)
+					&& (diff & SERIAL_MSR_DSR))
+				    || ((arg & TIOCM_CD)
+					&& (diff & SERIAL_MSR_CD))
+				    || ((arg & TIOCM_CTS)
+					&& (diff & SERIAL_MSR_CTS))) {
+					return 0;
+				}
+			}
+		}
+		return 0;
+	}
+
+	dbg("%s -No ioctl for that one.  port = %d\n", __func__, port->number);
+	return -ENOIOCTLCMD;
+}
+
+static void qt_set_termios(struct tty_struct *tty,
+			   struct usb_serial_port *port,
+			   struct ktermios *old_termios)
+{
+	struct ktermios *termios = tty->termios;
+	unsigned char new_LCR = 0;
+	unsigned int cflag = termios->c_cflag;
+	unsigned int index;
+	int baud, divisor, remainder;
+	int status;
+
+	dbg("%s", __func__);
+
+	index = tty->index - port->serial->minor;
+
+	switch (cflag) {
+	case CS5:
+		new_LCR |= SERIAL_5_DATA;
+		break;
+	case CS6:
+		new_LCR |= SERIAL_6_DATA;
+		break;
+	case CS7:
+		new_LCR |= SERIAL_7_DATA;
+		break;
+	default:
+	case CS8:
+		new_LCR |= SERIAL_8_DATA;
+		break;
+	}
+
+	/* Parity stuff */
+	if (cflag & PARENB) {
+		if (cflag & PARODD)
+			new_LCR |= SERIAL_ODD_PARITY;
+		else
+			new_LCR |= SERIAL_EVEN_PARITY;
+	}
+	if (cflag & CSTOPB)
+		new_LCR |= SERIAL_TWO_STOPB;
+	else
+		new_LCR |= SERIAL_TWO_STOPB;
+
+	dbg("%s - 4\n", __func__);
+
+	/* Thats the LCR stuff, go ahead and set it */
+	baud = tty_get_baud_rate(tty);
+	if (!baud)
+		/* pick a default, any default... */
+		baud = 9600;
+
+	dbg("%s - got baud = %d\n", __func__, baud);
+
+	divisor = MAX_BAUD_RATE / baud;
+	remainder = MAX_BAUD_RATE % baud;
+	/* Round to nearest divisor */
+	if (((remainder * 2) >= baud) && (baud != 110))
+		divisor++;
+
+	/*
+	 * Set Baud rate to default and turn off (default)flow control here
+	 */
+	status =
+	    qt_setuart(port->serial, index, (unsigned short)divisor, new_LCR);
+	if (status < 0) {
+		dbg(__FILE__ "qt_setuart failed\n");
+		return;
+	}
+
+	/* Now determine flow control */
+	if (cflag & CRTSCTS) {
+		dbg("%s - Enabling HW flow control port %d\n", __func__,
+		    port->number);
+
+		/* Enable RTS/CTS flow control */
+		status = BoxSetHW_FlowCtrl(port->serial, index, 1);
+
+		if (status < 0) {
+			dbg(__FILE__ "BoxSetHW_FlowCtrl failed\n");
+			return;
+		}
+	} else {
+		/* Disable RTS/CTS flow control */
+		dbg("%s - disabling HW flow control port %d\n", __func__,
+		    port->number);
+
+		status = BoxSetHW_FlowCtrl(port->serial, index, 0);
+		if (status < 0) {
+			dbg(__FILE__ "BoxSetHW_FlowCtrl failed\n");
+			return;
+		}
+
+	}
+
+	/* if we are implementing XON/XOFF, set the start and stop character in
+	 * the device */
+	if (I_IXOFF(tty) || I_IXON(tty)) {
+		unsigned char stop_char = STOP_CHAR(tty);
+		unsigned char start_char = START_CHAR(tty);
+		status =
+		    BoxSetSW_FlowCtrl(port->serial, index, stop_char,
+				      start_char);
+		if (status < 0)
+			dbg(__FILE__ "BoxSetSW_FlowCtrl (enabled) failed\n");
+
+	} else {
+		/* disable SW flow control */
+		status = BoxDisable_SW_FlowCtrl(port->serial, index);
+		if (status < 0)
+			dbg(__FILE__ "BoxSetSW_FlowCtrl (diabling) failed\n");
+
+	}
+	tty->termios->c_cflag &= ~CMSPAR;
+	/* FIXME: Error cases should be returning the actual bits changed only */
+}
+
+static void qt_break(struct tty_struct *tty, int break_state)
+{
+	struct usb_serial_port *port = tty->driver_data;
+	struct usb_serial *serial = get_usb_serial(port, __func__);
+	struct quatech_port *qt_port;
+	u16 index, onoff;
+	unsigned int result;
+	unsigned long flags;
+
+	index = tty->index - serial->minor;
+
+	qt_port = qt_get_port_private(port);
+
+	if (break_state == -1)
+		onoff = 1;
+	else
+		onoff = 0;
+
+	spin_lock_irqsave(&qt_port->lock, flags);
+
+	dbg("%s - port %d\n", __func__, port->number);
+
+	result =
+	    usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
+			    QT_BREAK_CONTROL, 0x40, onoff, index, NULL, 0, 300);
+
+	spin_unlock_irqrestore(&qt_port->lock, flags);
+}
+
+static inline int qt_real_tiocmget(struct tty_struct *tty,
+				   struct usb_serial_port *port,
+				   struct file *file, struct usb_serial *serial)
+{
+
+	u8 mcr;
+	u8 msr;
+	unsigned int result = 0;
+	int status;
+	unsigned int index;
+
+	dbg("%s - port %d, tty =0x%p\n", __func__, port->number, tty);
+
+	index = tty->index - serial->minor;
+	status =
+	    BoxGetRegister(port->serial, index, MODEM_CONTROL_REGISTER, &mcr);
+	if (status >= 0) {
+		status =
+		    BoxGetRegister(port->serial, index,
+				   MODEM_STATUS_REGISTER, &msr);
+
+	}
+
+	if (status >= 0) {
+		result = ((mcr & SERIAL_MCR_DTR) ? TIOCM_DTR : 0)
+		    /* DTR IS SET */
+		    | ((mcr & SERIAL_MCR_RTS) ? TIOCM_RTS : 0)
+		    /* RTS IS SET */
+		    | ((msr & SERIAL_MSR_CTS) ? TIOCM_CTS : 0)
+		    /* CTS is set */
+		    | ((msr & SERIAL_MSR_CD) ? TIOCM_CAR : 0)
+		    /* Carrier detect is set */
+		    | ((msr & SERIAL_MSR_RI) ? TIOCM_RI : 0)
+		    /* Ring indicator set */
+		    | ((msr & SERIAL_MSR_DSR) ? TIOCM_DSR : 0);
+		/* DSR is set */
+		return result;
+
+	} else
+		return -ESPIPE;
+}
+
+static inline int qt_real_tiocmset(struct tty_struct *tty,
+				   struct usb_serial_port *port,
+				   struct file *file,
+				   struct usb_serial *serial,
+				   unsigned int value)
+{
+
+	u8 mcr;
+	int status;
+	unsigned int index;
+
+	dbg("%s - port %d\n", __func__, port->number);
+
+	index = tty->index - serial->minor;
+	status =
+	    BoxGetRegister(port->serial, index, MODEM_CONTROL_REGISTER, &mcr);
+	if (status < 0)
+		return -ESPIPE;
+
+	/*
+	 * Turn off the RTS and DTR and loopbcck and then only turn on what was
+	 * asked for
+	 */
+	mcr &= ~(SERIAL_MCR_RTS | SERIAL_MCR_DTR | SERIAL_MCR_LOOP);
+	if (value & TIOCM_RTS)
+		mcr |= SERIAL_MCR_RTS;
+	if (value & TIOCM_DTR)
+		mcr |= SERIAL_MCR_DTR;
+	if (value & TIOCM_LOOP)
+		mcr |= SERIAL_MCR_LOOP;
+
+	status =
+	    BoxSetRegister(port->serial, index, MODEM_CONTROL_REGISTER, mcr);
+	if (status < 0)
+		return -ESPIPE;
+	else
+		return 0;
+}
+
+static int qt_tiocmget(struct tty_struct *tty, struct file *file)
+{
+	struct usb_serial_port *port = tty->driver_data;
+	struct usb_serial *serial = get_usb_serial(port, __func__);
+	struct quatech_port *qt_port = qt_get_port_private(port);
+	int retval = -ENODEV;
+	unsigned long flags;
+
+	dbg("In %s \n", __func__);
+
+	if (!serial)
+		return -ENODEV;
+
+	spin_lock_irqsave(&qt_port->lock, flags);
+
+	dbg("%s - port %d\n", __func__, port->number);
+	dbg("%s - port->RxHolding = %d\n", __func__, qt_port->RxHolding);
+
+	retval = qt_real_tiocmget(tty, port, file, serial);
+
+	spin_unlock_irqrestore(&qt_port->lock, flags);
+	return retval;
+}
+
+static int qt_tiocmset(struct tty_struct *tty, struct file *file,
+		       unsigned int set, unsigned int clear)
+{
+
+	struct usb_serial_port *port = tty->driver_data;
+	struct usb_serial *serial = get_usb_serial(port, __func__);
+	struct quatech_port *qt_port = qt_get_port_private(port);
+	unsigned long flags;
+	int retval = -ENODEV;
+
+	dbg("In %s \n", __func__);
+
+	if (!serial)
+		return -ENODEV;
+
+	spin_lock_irqsave(&qt_port->lock, flags);
+
+	dbg("%s - port %d \n", __func__, port->number);
+	dbg("%s - qt_port->RxHolding = %d\n", __func__, qt_port->RxHolding);
+
+	retval = qt_real_tiocmset(tty, port, file, serial, set);
+
+	spin_unlock_irqrestore(&qt_port->lock, flags);
+	return retval;
+}
+
+static void qt_throttle(struct tty_struct *tty)
+{
+	struct usb_serial_port *port = tty->driver_data;
+	struct usb_serial *serial = get_usb_serial(port, __func__);
+	struct quatech_port *qt_port;
+	unsigned long flags;
+
+	dbg("%s - port %d\n", __func__, port->number);
+
+	if (!serial)
+		return;
+
+	qt_port = qt_get_port_private(port);
+
+	spin_lock_irqsave(&qt_port->lock, flags);
+
+	/* pass on to the driver specific version of this function */
+	qt_port->RxHolding = 1;
+	dbg("%s - port->RxHolding = 1\n", __func__);
+
+	spin_unlock_irqrestore(&qt_port->lock, flags);
+	return;
+}
+
+static void qt_unthrottle(struct tty_struct *tty)
+{
+	struct usb_serial_port *port = tty->driver_data;
+	struct usb_serial *serial = get_usb_serial(port, __func__);
+	struct quatech_port *qt_port;
+	unsigned long flags;
+	unsigned int result;
+
+	if (!serial)
+		return;
+
+	qt_port = qt_get_port_private(port);
+
+	spin_lock_irqsave(&qt_port->lock, flags);
+
+	dbg("%s - port %d\n", __func__, port->number);
+
+	if (qt_port->RxHolding == 1) {
+		dbg("%s -qt_port->RxHolding == 1\n", __func__);
+
+		qt_port->RxHolding = 0;
+		dbg("%s - qt_port->RxHolding = 0\n", __func__);
+
+		/* if we have a bulk endpoint, start it up */
+		if ((serial->num_bulk_in) && (qt_port->ReadBulkStopped == 1)) {
+			/* Start reading from the device */
+			usb_fill_bulk_urb(port->read_urb, serial->dev,
+					  usb_rcvbulkpipe(serial->dev,
+							  port->bulk_in_endpointAddress),
+					  port->read_urb->transfer_buffer,
+					  port->read_urb->
+					  transfer_buffer_length,
+					  qt_read_bulk_callback, port);
+			result = usb_submit_urb(port->read_urb, GFP_ATOMIC);
+			if (result)
+				err("%s - failed restarting read urb, error %d",
+				    __func__, result);
+		}
+	}
+	spin_unlock_irqrestore(&qt_port->lock, flags);
+	return;
+
+}
+
+static int qt_calc_num_ports(struct usb_serial *serial)
+{
+	int num_ports;
+
+	dbg("numberofendpoints: %d \n",
+	    (int)serial->interface->cur_altsetting->desc.bNumEndpoints);
+	dbg("numberofendpoints: %d \n",
+	    (int)serial->interface->altsetting->desc.bNumEndpoints);
+
+	num_ports =
+	    (serial->interface->cur_altsetting->desc.bNumEndpoints - 1) / 2;
+
+	return num_ports;
+}
+
+static struct usb_serial_driver quatech_device = {
+	.driver = {
+		   .owner = THIS_MODULE,
+		   .name = "serqt",
+		   },
+	.description = DRIVER_DESC,
+	.usb_driver = &serqt_usb_driver,
+	.id_table = serqt_id_table,
+	.num_ports = 8,
+	.open = qt_open,
+	.close = qt_close,
+	.write = qt_write,
+	.write_room = qt_write_room,
+	.chars_in_buffer = qt_chars_in_buffer,
+	.throttle = qt_throttle,
+	.unthrottle = qt_unthrottle,
+	.calc_num_ports = qt_calc_num_ports,
+	.ioctl = qt_ioctl,
+	.set_termios = qt_set_termios,
+	.break_ctl = qt_break,
+	.tiocmget = qt_tiocmget,
+	.tiocmset = qt_tiocmset,
+	.attach = qt_startup,
+	.release = qt_release,
+};
+
+static int __init serqt_usb_init(void)
+{
+	int retval;
+
+	dbg("%s\n", __func__);
+
+	/* register with usb-serial */
+	retval = usb_serial_register(&quatech_device);
+
+	if (retval)
+		goto failed_usb_serial_register;
+
+	printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
+	       DRIVER_DESC "\n");
+
+	/* register with usb */
+
+	retval = usb_register(&serqt_usb_driver);
+	if (retval == 0)
+		return 0;
+
+	/* if we're here, usb_register() failed */
+	usb_serial_deregister(&quatech_device);
+failed_usb_serial_register:
+	return retval;
+}
+
+static void __exit serqt_usb_exit(void)
+{
+	usb_deregister(&serqt_usb_driver);
+	usb_serial_deregister(&quatech_device);
+}
+
+module_init(serqt_usb_init);
+module_exit(serqt_usb_exit);
+
+MODULE_AUTHOR(DRIVER_AUTHOR);
+MODULE_DESCRIPTION(DRIVER_DESC);
+MODULE_LICENSE("GPL");
+
+module_param(debug, bool, S_IRUGO | S_IWUSR);
+MODULE_PARM_DESC(debug, "Debug enabled or not");
diff --git a/drivers/staging/slicoss/slicoss.c b/drivers/staging/slicoss/slicoss.c
index 6f5d0bf..ed47db5 100644
--- a/drivers/staging/slicoss/slicoss.c
+++ b/drivers/staging/slicoss/slicoss.c
@@ -1872,7 +1872,6 @@
 	__iomem struct slic_regs *slic_regs = adapter->slic_regs;
 	u32 instruction;
 	u32 baseaddress;
-	u32 failure;
 	u32 i;
 	u32 numsects = 0;
 	u32 sectsize[3];
@@ -4049,7 +4048,7 @@
 	.name = DRV_NAME,
 	.id_table = slic_pci_tbl,
 	.probe = slic_entry_probe,
-	.remove = slic_entry_remove,
+	.remove = __devexit_p(slic_entry_remove),
 };
 
 static int __init slic_module_init(void)
diff --git a/drivers/staging/stlc45xx/stlc45xx.c b/drivers/staging/stlc45xx/stlc45xx.c
index 3eced55..cfdaac9 100644
--- a/drivers/staging/stlc45xx/stlc45xx.c
+++ b/drivers/staging/stlc45xx/stlc45xx.c
@@ -1787,7 +1787,6 @@
 	int payload_len, padding, i;
 	struct s_lm_data_out *data;
 	struct txbuffer *entry;
-	DECLARE_MAC_BUF(mac);
 	struct sk_buff *skb;
 	char *payload;
 	u16 fc;
@@ -1813,8 +1812,8 @@
 	memcpy(pspoll->addr1, stlc->bssid, ETH_ALEN);
 	memcpy(pspoll->addr2, stlc->mac_addr, ETH_ALEN);
 
-	stlc45xx_debug(DEBUG_PSM, "sending PS-Poll frame to %s (powersave %d, "
-		       "fc 0x%x, aid %d)", print_mac(mac, pspoll->addr1),
+	stlc45xx_debug(DEBUG_PSM, "sending PS-Poll frame to %pM (powersave %d, "
+		       "fc 0x%x, aid %d)", pspoll->addr1,
 		       powersave, fc, stlc->aid);
 
 	spin_lock_bh(&stlc->tx_lock);
@@ -1903,7 +1902,6 @@
 	int payload_len, padding, i;
 	struct s_lm_data_out *data;
 	struct txbuffer *entry;
-	DECLARE_MAC_BUF(mac);
 	struct sk_buff *skb;
 	char *payload;
 	u16 fc;
@@ -1928,9 +1926,8 @@
 	memcpy(nullfunc->addr2, stlc->mac_addr, ETH_ALEN);
 	memcpy(nullfunc->addr3, stlc->bssid, ETH_ALEN);
 
-	stlc45xx_debug(DEBUG_PSM, "sending Null frame to %s (powersave %d, "
-		       "fc 0x%x)",
-		       print_mac(mac, nullfunc->addr1), powersave, fc);
+	stlc45xx_debug(DEBUG_PSM, "sending Null frame to %pM (powersave %d, "
+		       "fc 0x%x)", nullfunc->addr1, powersave, fc);
 
 	spin_lock_bh(&stlc->tx_lock);
 
diff --git a/drivers/staging/sxg/sxg.c b/drivers/staging/sxg/sxg.c
index 076b3f7..3a0dac9 100644
--- a/drivers/staging/sxg/sxg.c
+++ b/drivers/staging/sxg/sxg.c
@@ -355,7 +355,7 @@
 	for(i=0; i< adapter->nr_msix_entries;i++)
 	{
 		vector = adapter->msi_entries[i].vector;
-		DBG_ERROR("%s : Freeing IRQ vector#%d\n",__FUNCTION__,vector);
+		DBG_ERROR("%s : Freeing IRQ vector#%d\n",__func__,vector);
 		free_irq(vector,netdev);
 	}
 }
@@ -852,7 +852,7 @@
  		 * Get out of here
  		 */
 		printk(KERN_ERR"%s : Could not allocate memory for reading \
-				 EEPROM\n", __FUNCTION__);
+				 EEPROM\n", __func__);
 		return -ENOMEM;
 	}
 
@@ -887,7 +887,7 @@
 	case SXG_CFG_LOAD_ERROR:
 	default:	/* Fix default handler later */
 		printk(KERN_WARNING"%s  : We could not read the config \
-			word. Status = %ld\n", __FUNCTION__, status);
+			word. Status = %ld\n", __func__, status);
 		break;
 	}
 	pci_free_consistent(adapter->pcidev, sizeof(struct sw_cfg_data), data,
@@ -996,7 +996,7 @@
 		adapter->asictype = SAHARA_REV_B;
 	} else {
 		ASSERT(0);
-		DBG_ERROR("%s Unexpected revision ID %x\n", __FUNCTION__, revision_id);
+		DBG_ERROR("%s Unexpected revision ID %x\n", __func__, revision_id);
 		goto err_out_exit_sxg_probe;
 	}
 	adapter->netdev = netdev;
@@ -1176,9 +1176,9 @@
 		  smp_processor_id());
 
 	pci_disable_device(pcidev);
-        DBG_ERROR("sxg: %s deallocate device\n", __FUNCTION__);
+        DBG_ERROR("sxg: %s deallocate device\n", __func__);
         kfree(netdev);
-	printk("Exit %s, Sxg driver loading failed..\n", __FUNCTION__);
+	printk("Exit %s, Sxg driver loading failed..\n", __func__);
 
 	return -ENODEV;
 }
@@ -2191,10 +2191,10 @@
 	/*
 	 * The microcode expects it to be downloaded on every open.
 	 */
-	DBG_ERROR("sxg: %s ENTER sxg_download_microcode\n", __FUNCTION__);
+	DBG_ERROR("sxg: %s ENTER sxg_download_microcode\n", __func__);
 	if (sxg_download_microcode(adapter, SXG_UCODE_SYSTEM)) {
 		DBG_ERROR("sxg: %s ENTER sxg_adapter_set_hwaddr\n",
-				__FUNCTION__);
+				__func__);
 		sxg_read_config(adapter);
 	} else {
 		adapter->state = ADAPT_FAIL;
@@ -2307,14 +2307,14 @@
         mmio_start = pci_resource_start(pcidev, 0);
         mmio_len = pci_resource_len(pcidev, 0);
 
-        DBG_ERROR("sxg: %s rel_region(0) start[%x] len[%x]\n", __FUNCTION__,
+        DBG_ERROR("sxg: %s rel_region(0) start[%x] len[%x]\n", __func__,
                   mmio_start, mmio_len);
         release_mem_region(mmio_start, mmio_len);
 
         mmio_start = pci_resource_start(pcidev, 2);
         mmio_len = pci_resource_len(pcidev, 2);
 
-        DBG_ERROR("sxg: %s rel_region(2) start[%x] len[%x]\n", __FUNCTION__,
+        DBG_ERROR("sxg: %s rel_region(2) start[%x] len[%x]\n", __func__,
                   mmio_start, mmio_len);
         release_mem_region(mmio_start, mmio_len);
 
@@ -2400,7 +2400,7 @@
 	atomic_set(&adapter->pending_allocations, 0);
 	adapter->intrregistered = 0;
 	sxg_remove_isr(adapter);
-	DBG_ERROR("sxg: %s (%s) EXIT\n", __FUNCTION__, dev->name);
+	DBG_ERROR("sxg: %s (%s) EXIT\n", __func__, dev->name);
 	return (STATUS_SUCCESS);
 }
 
@@ -2454,7 +2454,7 @@
 	u32 status = STATUS_SUCCESS;
 
 	/*
-	 * DBG_ERROR("sxg: %s ENTER sxg_send_packets skb[%p]\n", __FUNCTION__,
+	 * DBG_ERROR("sxg: %s ENTER sxg_send_packets skb[%p]\n", __func__,
 	 *	  skb);
 	 */
 
@@ -3405,7 +3405,7 @@
 
 	SXG_TRACE(TRACE_SXG, SxgTraceBuffer, TRACE_NOISY, "WrtMDIO",
 		  adapter, 0, 0, 0);
-	DBG_ERROR("ENTER %s\n", __FUNCTION__);
+	DBG_ERROR("ENTER %s\n", __func__);
 
 	/* Ensure values don't exceed field width */
 	DevAddr &= 0x001F;	/* 5-bit field */
@@ -3441,7 +3441,7 @@
 		udelay(100);	/* Timeout in 100us units */
 		READ_REG(HwRegs->MacAmiimIndicator, ValueRead);
 		if (--Timeout == 0) {
-            DBG_ERROR("EXIT %s with STATUS_FAILURE 1\n", __FUNCTION__);
+            DBG_ERROR("EXIT %s with STATUS_FAILURE 1\n", __func__);
 
 			return (STATUS_FAILURE);
 		}
@@ -3462,7 +3462,7 @@
 		udelay(100);	/* Timeout in 100us units */
 		READ_REG(HwRegs->MacAmiimIndicator, ValueRead);
 		if (--Timeout == 0) {
-            DBG_ERROR("EXIT %s with STATUS_FAILURE 2\n", __FUNCTION__);
+            DBG_ERROR("EXIT %s with STATUS_FAILURE 2\n", __func__);
 
 			return (STATUS_FAILURE);
 		}
@@ -3472,7 +3472,7 @@
 	READ_REG(HwRegs->MacAmiimField, *pValue);
 	*pValue &= 0xFFFF;	/* data is in the lower 16 bits */
 
-	DBG_ERROR("EXIT %s\n", __FUNCTION__);
+	DBG_ERROR("EXIT %s\n", __func__);
 
 	return (STATUS_SUCCESS);
 }
@@ -3545,7 +3545,7 @@
 {
 	struct sxg_ucode_regs *sxg_regs = adapter->UcodeRegs;
 
-	DBG_ERROR("%s ENTER (%s) MacFilter[%x] mask[%llx]\n", __FUNCTION__,
+	DBG_ERROR("%s ENTER (%s) MacFilter[%x] mask[%llx]\n", __func__,
 		  adapter->netdev->name, (unsigned int)adapter->MacFilter,
 		  adapter->MulticastMask);
 
@@ -4055,7 +4055,7 @@
 	 *  sxg_dbg_macaddrs(adapter);
 	 */
 	/* DBG_ERROR ("%s AFTER copying from config.macinfo into currmacaddr\n",
-	 *	   		__FUNCTION__);
+	 *	   		__func__);
 	 */
 
 	/* sxg_dbg_macaddrs(adapter); */
@@ -4066,7 +4066,7 @@
 		printk("sxg: Dev is Null\n");
 	}
 
-        DBG_ERROR("%s ENTER (%s)\n", __FUNCTION__, adapter->netdev->name);
+        DBG_ERROR("%s ENTER (%s)\n", __func__, adapter->netdev->name);
 
         if (netif_running(dev)) {
                 return -EBUSY;
@@ -4516,7 +4516,7 @@
 	.name = sxg_driver_name,
 	.id_table = sxg_pci_tbl,
 	.probe = sxg_entry_probe,
-	.remove = sxg_entry_remove,
+	.remove = __devexit_p(sxg_entry_remove),
 #if SXG_POWER_MANAGEMENT_ENABLED
 	.suspend = sxgpm_suspend,
 	.resume = sxgpm_resume,
diff --git a/drivers/staging/sxg/sxg_ethtool.c b/drivers/staging/sxg/sxg_ethtool.c
index 97f765d..ad89cb8 100644
--- a/drivers/staging/sxg/sxg_ethtool.c
+++ b/drivers/staging/sxg/sxg_ethtool.c
@@ -278,7 +278,7 @@
                  * Get out of here
                  */
                 printk(KERN_ERR"%s : Could not allocate memory for reading \
-                                EEPROM\n", __FUNCTION__);
+                                EEPROM\n", __func__);
                 return -ENOMEM;
         }
 
diff --git a/drivers/staging/udlfb/Kconfig b/drivers/staging/udlfb/Kconfig
new file mode 100644
index 0000000..641692d
--- /dev/null
+++ b/drivers/staging/udlfb/Kconfig
@@ -0,0 +1,8 @@
+config FB_UDL
+	tristate "Displaylink USB Framebuffer support"
+	depends on FB && USB
+	---help---
+	  This is an experimental driver for DisplayLink USB devices
+	  that provides a framebuffer device.  A normal framebuffer can
+	  be used with this driver, or xorg can be run on the device
+	  using it.
diff --git a/drivers/staging/udlfb/Makefile b/drivers/staging/udlfb/Makefile
new file mode 100644
index 0000000..30d9e67
--- /dev/null
+++ b/drivers/staging/udlfb/Makefile
@@ -0,0 +1 @@
+obj-$(CONFIG_FB_UDL)		+= udlfb.o
diff --git a/drivers/staging/udlfb/udlfb.c b/drivers/staging/udlfb/udlfb.c
new file mode 100644
index 0000000..0ab9d15
--- /dev/null
+++ b/drivers/staging/udlfb/udlfb.c
@@ -0,0 +1,937 @@
+/*****************************************************************************
+ *                          DLFB Kernel Driver                               *
+ *                            Version 0.2 (udlfb)                            *
+ *             (C) 2009 Roberto De Ioris <roberto@unbit.it>                  *
+ *                                                                           *
+ *     This file is licensed under the GPLv2. See COPYING in the package.    *
+ * Based on the amazing work of Florian Echtler and libdlo 0.1               *
+ *                                                                           *
+ *                                                                           *
+ * 10.06.09 release 0.2.3 (edid ioctl, fallback for unsupported modes)       *
+ * 05.06.09 release 0.2.2 (real screen blanking, rle compression, double buffer) *
+ * 31.05.09 release 0.2                                                      *
+ * 22.05.09 First public (ugly) release                                      *
+ *****************************************************************************/
+
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/init.h>
+#include <linux/usb.h>
+#include <linux/uaccess.h>
+#include <linux/mm.h>
+#include <linux/fb.h>
+#include <linux/mutex.h>
+
+#include "udlfb.h"
+
+#define DRIVER_VERSION "DLFB 0.2"
+
+/* memory functions taken from vfb */
+
+static void *rvmalloc(unsigned long size)
+{
+	void *mem;
+	unsigned long adr;
+
+	size = PAGE_ALIGN(size);
+	mem = vmalloc_32(size);
+	if (!mem)
+		return NULL;
+
+	memset(mem, 0, size);	/* Clear the ram out, no junk to the user */
+	adr = (unsigned long)mem;
+	while (size > 0) {
+		SetPageReserved(vmalloc_to_page((void *)adr));
+		adr += PAGE_SIZE;
+		size -= PAGE_SIZE;
+	}
+
+	return mem;
+}
+
+static void rvfree(void *mem, unsigned long size)
+{
+	unsigned long adr;
+
+	if (!mem)
+		return;
+
+	adr = (unsigned long)mem;
+	while ((long)size > 0) {
+		ClearPageReserved(vmalloc_to_page((void *)adr));
+		adr += PAGE_SIZE;
+		size -= PAGE_SIZE;
+	}
+	vfree(mem);
+}
+
+static int dlfb_mmap(struct fb_info *info, struct vm_area_struct *vma)
+{
+	unsigned long start = vma->vm_start;
+	unsigned long size = vma->vm_end - vma->vm_start;
+	unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
+	unsigned long page, pos;
+
+	printk("MMAP: %lu %u\n", offset + size, info->fix.smem_len);
+
+	if (offset + size > info->fix.smem_len)
+		return -EINVAL;
+
+	pos = (unsigned long)info->fix.smem_start + offset;
+
+	while (size > 0) {
+		page = vmalloc_to_pfn((void *)pos);
+		if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED))
+			return -EAGAIN;
+
+		start += PAGE_SIZE;
+		pos += PAGE_SIZE;
+		if (size > PAGE_SIZE)
+			size -= PAGE_SIZE;
+		else
+			size = 0;
+	}
+
+	vma->vm_flags |= VM_RESERVED;	/* avoid to swap out this VMA */
+	return 0;
+
+}
+
+/* ioctl structure */
+struct dloarea {
+	int x, y;
+	int w, h;
+	int x2, y2;
+};
+
+/*
+static struct usb_device_id id_table [] = {
+	{ USB_DEVICE(0x17e9, 0x023d) },
+	{ }
+};
+*/
+
+static struct usb_device_id id_table[] = {
+	{.idVendor = 0x17e9, .match_flags = USB_DEVICE_ID_MATCH_VENDOR,},
+	{},
+};
+MODULE_DEVICE_TABLE(usb, id_table);
+
+static struct usb_driver dlfb_driver;
+
+// thanks to Henrik Bjerregaard Pedersen for this function
+static char *rle_compress16(uint16_t * src, char *dst, int rem)
+{
+
+	int rl;
+	uint16_t pix0;
+	char *end_if_raw = dst + 6 + 2 * rem;
+
+	dst += 6;		// header will be filled in if RLE is worth it
+
+	while (rem && dst < end_if_raw) {
+		char *start = (char *)src;
+
+		pix0 = *src++;
+		rl = 1;
+		rem--;
+		while (rem && *src == pix0)
+			rem--, rl++, src++;
+		*dst++ = rl;
+		*dst++ = start[1];
+		*dst++ = start[0];
+	}
+
+	return dst;
+}
+
+/*
+Thanks to Henrik Bjerregaard Pedersen for rle implementation and code refactoring.
+Next step is huffman compression.
+*/
+
+static int
+image_blit(struct dlfb_data *dev_info, int x, int y, int width, int height,
+	   char *data)
+{
+
+	int i, j, base;
+	int rem = width;
+	int ret;
+
+	int firstdiff, thistime;
+
+	char *bufptr;
+
+	if (x + width > dev_info->info->var.xres)
+		return -EINVAL;
+
+	if (y + height > dev_info->info->var.yres)
+		return -EINVAL;
+
+	mutex_lock(&dev_info->bulk_mutex);
+
+	base =
+	    dev_info->base16 + ((dev_info->info->var.xres * 2 * y) + (x * 2));
+
+	data += (dev_info->info->var.xres * 2 * y) + (x * 2);
+
+	/* printk("IMAGE_BLIT\n"); */
+
+	bufptr = dev_info->buf;
+
+	for (i = y; i < y + height; i++) {
+
+		if (dev_info->bufend - bufptr < BUF_HIGH_WATER_MARK) {
+			ret = dlfb_bulk_msg(dev_info, bufptr - dev_info->buf);
+			bufptr = dev_info->buf;
+		}
+
+		rem = width;
+
+		/* printk("WRITING LINE %d\n", i); */
+
+		while (rem) {
+
+			if (dev_info->bufend - bufptr < BUF_HIGH_WATER_MARK) {
+				ret =
+				    dlfb_bulk_msg(dev_info,
+						  bufptr - dev_info->buf);
+				bufptr = dev_info->buf;
+			}
+			// number of pixels to consider this time
+			thistime = rem;
+			if (thistime > 255)
+				thistime = 255;
+
+			// find position of first pixel that has changed
+			firstdiff = -1;
+			for (j = 0; j < thistime * 2; j++) {
+				if (dev_info->backing_buffer
+				    [base - dev_info->base16 + j] != data[j]) {
+					firstdiff = j / 2;
+					break;
+				}
+			}
+
+			if (firstdiff >= 0) {
+				char *end_of_rle;
+
+				end_of_rle =
+				    rle_compress16((uint16_t *) (data +
+								 firstdiff * 2),
+						   bufptr,
+						   thistime - firstdiff);
+
+				if (end_of_rle <
+				    bufptr + 6 + 2 * (thistime - firstdiff)) {
+					bufptr[0] = 0xAF;
+					bufptr[1] = 0x69;
+
+					bufptr[2] =
+					    (char)((base +
+						    firstdiff * 2) >> 16);
+					bufptr[3] =
+					    (char)((base + firstdiff * 2) >> 8);
+					bufptr[4] =
+					    (char)(base + firstdiff * 2);
+					bufptr[5] = thistime - firstdiff;
+
+					bufptr = end_of_rle;
+
+				} else {
+					// fallback to raw (or some other encoding?)
+					*bufptr++ = 0xAF;
+					*bufptr++ = 0x68;
+
+					*bufptr++ =
+					    (char)((base +
+						    firstdiff * 2) >> 16);
+					*bufptr++ =
+					    (char)((base + firstdiff * 2) >> 8);
+					*bufptr++ =
+					    (char)(base + firstdiff * 2);
+					*bufptr++ = thistime - firstdiff;
+					// PUT COMPRESSION HERE
+					for (j = firstdiff * 2;
+					     j < thistime * 2; j += 2) {
+						*bufptr++ = data[j + 1];
+						*bufptr++ = data[j];
+					}
+				}
+			}
+
+			base += thistime * 2;
+			data += thistime * 2;
+			rem -= thistime;
+		}
+
+		memcpy(dev_info->backing_buffer + (base - dev_info->base16) -
+		       (width * 2), data - (width * 2), width * 2);
+
+		base += (dev_info->info->var.xres * 2) - (width * 2);
+		data += (dev_info->info->var.xres * 2) - (width * 2);
+
+	}
+
+	if (bufptr > dev_info->buf) {
+		ret = dlfb_bulk_msg(dev_info, bufptr - dev_info->buf);
+	}
+
+	mutex_unlock(&dev_info->bulk_mutex);
+
+	return base;
+
+}
+
+static int
+draw_rect(struct dlfb_data *dev_info, int x, int y, int width, int height,
+	  unsigned char red, unsigned char green, unsigned char blue)
+{
+
+	int i, j, base;
+	int ret;
+	unsigned short col =
+	    (((((red) & 0xF8) | ((green) >> 5)) & 0xFF) << 8) +
+	    (((((green) & 0x1C) << 3) | ((blue) >> 3)) & 0xFF);
+	int rem = width;
+
+	char *bufptr;
+
+	if (x + width > dev_info->info->var.xres)
+		return -EINVAL;
+
+	if (y + height > dev_info->info->var.yres)
+		return -EINVAL;
+
+	mutex_lock(&dev_info->bulk_mutex);
+
+	base = dev_info->base16 + (dev_info->info->var.xres * 2 * y) + (x * 2);
+
+	bufptr = dev_info->buf;
+
+	for (i = y; i < y + height; i++) {
+
+		for (j = 0; j < width * 2; j += 2) {
+			dev_info->backing_buffer[base - dev_info->base16 + j] =
+			    (char)(col >> 8);
+			dev_info->backing_buffer[base - dev_info->base16 + j +
+						 1] = (char)(col);
+		}
+		if (dev_info->bufend - bufptr < BUF_HIGH_WATER_MARK) {
+			ret = dlfb_bulk_msg(dev_info, bufptr - dev_info->buf);
+			bufptr = dev_info->buf;
+		}
+
+		rem = width;
+
+		while (rem) {
+
+			if (dev_info->bufend - bufptr < BUF_HIGH_WATER_MARK) {
+				ret =
+				    dlfb_bulk_msg(dev_info,
+						  bufptr - dev_info->buf);
+				bufptr = dev_info->buf;
+			}
+
+			*bufptr++ = 0xAF;
+			*bufptr++ = 0x69;
+
+			*bufptr++ = (char)(base >> 16);
+			*bufptr++ = (char)(base >> 8);
+			*bufptr++ = (char)(base);
+
+			if (rem > 255) {
+				*bufptr++ = 255;
+				*bufptr++ = 255;
+				rem -= 255;
+				base += 255 * 2;
+			} else {
+				*bufptr++ = rem;
+				*bufptr++ = rem;
+				base += rem * 2;
+				rem = 0;
+			}
+
+			*bufptr++ = (char)(col >> 8);
+			*bufptr++ = (char)(col);
+
+		}
+
+		base += (dev_info->info->var.xres * 2) - (width * 2);
+
+	}
+
+	if (bufptr > dev_info->buf)
+		ret = dlfb_bulk_msg(dev_info, bufptr - dev_info->buf);
+
+	mutex_unlock(&dev_info->bulk_mutex);
+
+	return 1;
+}
+
+static void swapfb(struct dlfb_data *dev_info)
+{
+
+	int tmpbase;
+	char *bufptr;
+
+	mutex_lock(&dev_info->bulk_mutex);
+
+	tmpbase = dev_info->base16;
+
+	dev_info->base16 = dev_info->base16d;
+	dev_info->base16d = tmpbase;
+
+	bufptr = dev_info->buf;
+
+	bufptr = dlfb_set_register(bufptr, 0xFF, 0x00);
+
+	// set addresses
+	bufptr =
+	    dlfb_set_register(bufptr, 0x20, (char)(dev_info->base16 >> 16));
+	bufptr = dlfb_set_register(bufptr, 0x21, (char)(dev_info->base16 >> 8));
+	bufptr = dlfb_set_register(bufptr, 0x22, (char)(dev_info->base16));
+
+	bufptr = dlfb_set_register(bufptr, 0xFF, 0x00);
+
+	dlfb_bulk_msg(dev_info, bufptr - dev_info->buf);
+
+	mutex_unlock(&dev_info->bulk_mutex);
+}
+
+static int copyfb(struct dlfb_data *dev_info)
+{
+	int base;
+	int source;
+	int rem;
+	int i, ret;
+
+	char *bufptr;
+
+	base = dev_info->base16d;
+
+	mutex_lock(&dev_info->bulk_mutex);
+
+	source = dev_info->base16;
+
+	bufptr = dev_info->buf;
+
+	for (i = 0; i < dev_info->info->var.yres; i++) {
+
+		if (dev_info->bufend - bufptr < BUF_HIGH_WATER_MARK) {
+			ret = dlfb_bulk_msg(dev_info, bufptr - dev_info->buf);
+			bufptr = dev_info->buf;
+		}
+
+		rem = dev_info->info->var.xres;
+
+		while (rem) {
+
+			if (dev_info->bufend - bufptr < BUF_HIGH_WATER_MARK) {
+				ret =
+				    dlfb_bulk_msg(dev_info,
+						  bufptr - dev_info->buf);
+				bufptr = dev_info->buf;
+
+			}
+
+			*bufptr++ = 0xAF;
+			*bufptr++ = 0x6A;
+
+			*bufptr++ = (char)(base >> 16);
+			*bufptr++ = (char)(base >> 8);
+			*bufptr++ = (char)(base);
+
+			if (rem > 255) {
+				*bufptr++ = 255;
+				*bufptr++ = (char)(source >> 16);
+				*bufptr++ = (char)(source >> 8);
+				*bufptr++ = (char)(source);
+
+				rem -= 255;
+				base += 255 * 2;
+				source += 255 * 2;
+
+			} else {
+				*bufptr++ = rem;
+				*bufptr++ = (char)(source >> 16);
+				*bufptr++ = (char)(source >> 8);
+				*bufptr++ = (char)(source);
+
+				base += rem * 2;
+				source += rem * 2;
+				rem = 0;
+			}
+		}
+	}
+
+	if (bufptr > dev_info->buf)
+		ret = dlfb_bulk_msg(dev_info, bufptr - dev_info->buf);
+
+	mutex_unlock(&dev_info->bulk_mutex);
+
+	return 1;
+
+}
+
+static int
+copyarea(struct dlfb_data *dev_info, int dx, int dy, int sx, int sy,
+	 int width, int height)
+{
+	int base;
+	int source;
+	int rem;
+	int i, ret;
+
+	char *bufptr;
+
+	if (dx + width > dev_info->info->var.xres)
+		return -EINVAL;
+
+	if (dy + height > dev_info->info->var.yres)
+		return -EINVAL;
+
+	mutex_lock(&dev_info->bulk_mutex);
+
+	base =
+	    dev_info->base16 + (dev_info->info->var.xres * 2 * dy) + (dx * 2);
+	source = (dev_info->info->var.xres * 2 * sy) + (sx * 2);
+
+	bufptr = dev_info->buf;
+
+	for (i = sy; i < sy + height; i++) {
+
+		memcpy(dev_info->backing_buffer + base - dev_info->base16,
+		       dev_info->backing_buffer + source, width * 2);
+
+		if (dev_info->bufend - bufptr < BUF_HIGH_WATER_MARK) {
+			ret = dlfb_bulk_msg(dev_info, bufptr - dev_info->buf);
+			bufptr = dev_info->buf;
+		}
+
+		rem = width;
+
+		while (rem) {
+
+			if (dev_info->bufend - bufptr < BUF_HIGH_WATER_MARK) {
+				ret =
+				    dlfb_bulk_msg(dev_info,
+						  bufptr - dev_info->buf);
+				bufptr = dev_info->buf;
+			}
+
+			*bufptr++ = 0xAF;
+			*bufptr++ = 0x6A;
+
+			*bufptr++ = (char)(base >> 16);
+			*bufptr++ = (char)(base >> 8);
+			*bufptr++ = (char)(base);
+
+			if (rem > 255) {
+				*bufptr++ = 255;
+				*bufptr++ = (char)(source >> 16);
+				*bufptr++ = (char)(source >> 8);
+				*bufptr++ = (char)(source);
+
+				rem -= 255;
+				base += 255 * 2;
+				source += 255 * 2;
+
+			} else {
+				*bufptr++ = rem;
+				*bufptr++ = (char)(source >> 16);
+				*bufptr++ = (char)(source >> 8);
+				*bufptr++ = (char)(source);
+
+				base += rem * 2;
+				source += rem * 2;
+				rem = 0;
+			}
+		}
+
+		base += (dev_info->info->var.xres * 2) - (width * 2);
+		source += (dev_info->info->var.xres * 2) - (width * 2);
+	}
+
+	if (bufptr > dev_info->buf)
+		ret = dlfb_bulk_msg(dev_info, bufptr - dev_info->buf);
+
+	mutex_unlock(&dev_info->bulk_mutex);
+
+	return 1;
+}
+
+static void dlfb_copyarea(struct fb_info *info, const struct fb_copyarea *area)
+{
+
+	struct dlfb_data *dev = info->par;
+
+	copyarea(dev, area->dx, area->dy, area->sx, area->sy, area->width,
+		 area->height);
+
+	/* printk("COPY AREA %d %d %d %d %d %d !!!\n", area->dx, area->dy, area->sx, area->sy, area->width, area->height); */
+
+}
+
+static void dlfb_imageblit(struct fb_info *info, const struct fb_image *image)
+{
+
+	int ret;
+	struct dlfb_data *dev = info->par;
+	/* printk("IMAGE BLIT (1) %d %d %d %d DEPTH %d {%p}!!!\n", image->dx, image->dy, image->width, image->height, image->depth, dev->udev); */
+	cfb_imageblit(info, image);
+	ret =
+	    image_blit(dev, image->dx, image->dy, image->width, image->height,
+		       info->screen_base);
+	/* printk("IMAGE BLIT (2) %d %d %d %d DEPTH %d {%p} %d!!!\n", image->dx, image->dy, image->width, image->height, image->depth, dev->udev, ret); */
+}
+
+static void dlfb_fillrect(struct fb_info *info,
+			  const struct fb_fillrect *region)
+{
+
+	unsigned char red, green, blue;
+	struct dlfb_data *dev = info->par;
+
+	memcpy(&red, &region->color, 1);
+	memcpy(&green, &region->color + 1, 1);
+	memcpy(&blue, &region->color + 2, 1);
+	draw_rect(dev, region->dx, region->dy, region->width, region->height,
+		  red, green, blue);
+	/* printk("FILL RECT %d %d !!!\n", region->dx, region->dy); */
+
+}
+
+static int dlfb_ioctl(struct fb_info *info, unsigned int cmd, unsigned long arg)
+{
+
+	struct dlfb_data *dev_info = info->par;
+	struct dloarea *area = NULL;
+
+	if (cmd == 0xAD) {
+		char *edid = (char *)arg;
+		dlfb_edid(dev_info);
+		if (copy_to_user(edid, dev_info->edid, 128)) {
+			return -EFAULT;
+		}
+		return 0;
+	}
+
+	if (cmd == 0xAA || cmd == 0xAB || cmd == 0xAC) {
+
+		area = (struct dloarea *)arg;
+
+		if (area->x < 0)
+			area->x = 0;
+
+		if (area->x > info->var.xres)
+			area->x = info->var.xres;
+
+		if (area->y < 0)
+			area->y = 0;
+
+		if (area->y > info->var.yres)
+			area->y = info->var.yres;
+	}
+
+	if (cmd == 0xAA) {
+		image_blit(dev_info, area->x, area->y, area->w, area->h,
+			   info->screen_base);
+	}
+	if (cmd == 0xAC) {
+		copyfb(dev_info);
+		image_blit(dev_info, area->x, area->y, area->w, area->h,
+			   info->screen_base);
+		swapfb(dev_info);
+	} else if (cmd == 0xAB) {
+
+		if (area->x2 < 0)
+			area->x2 = 0;
+
+		if (area->y2 < 0)
+			area->y2 = 0;
+
+		copyarea(dev_info,
+			 area->x2, area->y2, area->x, area->y, area->w,
+			 area->h);
+	}
+	return 0;
+}
+
+/* taken from vesafb */
+
+static int
+dlfb_setcolreg(unsigned regno, unsigned red, unsigned green,
+	       unsigned blue, unsigned transp, struct fb_info *info)
+{
+	int err = 0;
+
+	if (regno >= info->cmap.len)
+		return 1;
+
+	if (regno < 16) {
+		if (info->var.red.offset == 10) {
+			/* 1:5:5:5 */
+			((u32 *) (info->pseudo_palette))[regno] =
+			    ((red & 0xf800) >> 1) |
+			    ((green & 0xf800) >> 6) | ((blue & 0xf800) >> 11);
+		} else {
+			/* 0:5:6:5 */
+			((u32 *) (info->pseudo_palette))[regno] =
+			    ((red & 0xf800)) |
+			    ((green & 0xfc00) >> 5) | ((blue & 0xf800) >> 11);
+		}
+	}
+
+	return err;
+}
+
+static int dlfb_release(struct fb_info *info, int user)
+{
+	struct dlfb_data *dev_info = info->par;
+	image_blit(dev_info, 0, 0, info->var.xres, info->var.yres,
+		   info->screen_base);
+	return 0;
+}
+
+static int dlfb_blank(int blank_mode, struct fb_info *info)
+{
+	struct dlfb_data *dev_info = info->par;
+	char *bufptr = dev_info->buf;
+
+	bufptr = dlfb_set_register(bufptr, 0xFF, 0x00);
+	if (blank_mode != FB_BLANK_UNBLANK) {
+		bufptr = dlfb_set_register(bufptr, 0x1F, 0x01);
+	} else {
+		bufptr = dlfb_set_register(bufptr, 0x1F, 0x00);
+	}
+	bufptr = dlfb_set_register(bufptr, 0xFF, 0xFF);
+
+	dlfb_bulk_msg(dev_info, bufptr - dev_info->buf);
+
+	return 0;
+}
+
+static struct fb_ops dlfb_ops = {
+	.fb_setcolreg = dlfb_setcolreg,
+	.fb_fillrect = dlfb_fillrect,
+	.fb_copyarea = dlfb_copyarea,
+	.fb_imageblit = dlfb_imageblit,
+	.fb_mmap = dlfb_mmap,
+	.fb_ioctl = dlfb_ioctl,
+	.fb_release = dlfb_release,
+	.fb_blank = dlfb_blank,
+};
+
+static int
+dlfb_probe(struct usb_interface *interface, const struct usb_device_id *id)
+{
+	struct dlfb_data *dev_info;
+	struct fb_info *info;
+
+	int ret;
+	char rbuf[4];
+
+	dev_info = kzalloc(sizeof(*dev_info), GFP_KERNEL);
+	if (dev_info == NULL) {
+		printk("cannot allocate dev_info structure.\n");
+		return -ENOMEM;
+	}
+
+	mutex_init(&dev_info->bulk_mutex);
+
+	dev_info->udev = usb_get_dev(interface_to_usbdev(interface));
+	dev_info->interface = interface;
+
+	printk("DisplayLink device attached\n");
+
+	/* add framebuffer info to usb interface */
+	usb_set_intfdata(interface, dev_info);
+
+	dev_info->buf = kmalloc(BUF_SIZE, GFP_KERNEL);
+	/* usb_buffer_alloc(dev_info->udev, BUF_SIZE , GFP_KERNEL, &dev_info->tx_urb->transfer_dma); */
+
+	if (dev_info->buf == NULL) {
+		printk("unable to allocate memory for dlfb commands\n");
+		goto out;
+	}
+	dev_info->bufend = dev_info->buf + BUF_SIZE;
+
+	dev_info->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
+	usb_fill_bulk_urb(dev_info->tx_urb, dev_info->udev,
+			  usb_sndbulkpipe(dev_info->udev, 1), dev_info->buf, 0,
+			  dlfb_bulk_callback, dev_info);
+
+	ret =
+	    usb_control_msg(dev_info->udev, usb_rcvctrlpipe(dev_info->udev, 0),
+			    (0x06), (0x80 | (0x02 << 5)), 0, 0, rbuf, 4, 0);
+	printk("ret control msg 0: %d %x%x%x%x\n", ret, rbuf[0], rbuf[1],
+	       rbuf[2], rbuf[3]);
+
+	dlfb_edid(dev_info);
+
+	info = framebuffer_alloc(sizeof(u32) * 256, &dev_info->udev->dev);
+
+	if (!info) {
+		printk("non posso allocare il framebuffer displaylink");
+		goto out;
+	}
+
+	fb_parse_edid(dev_info->edid, &info->var);
+
+	printk("EDID XRES %d YRES %d\n", info->var.xres, info->var.yres);
+
+	if (dlfb_set_video_mode(dev_info, info->var.xres, info->var.yres) != 0) {
+		info->var.xres = 1280;
+		info->var.yres = 1024;
+		if (dlfb_set_video_mode
+		    (dev_info, info->var.xres, info->var.yres) != 0) {
+			goto out;
+		}
+	}
+
+	printk("found valid mode...%d\n", info->var.pixclock);
+
+	info->pseudo_palette = info->par;
+	info->par = dev_info;
+
+	dev_info->info = info;
+
+	info->flags =
+	    FBINFO_DEFAULT | FBINFO_READS_FAST | FBINFO_HWACCEL_IMAGEBLIT |
+	    FBINFO_HWACCEL_COPYAREA | FBINFO_HWACCEL_FILLRECT;
+	info->fbops = &dlfb_ops;
+	info->screen_base = rvmalloc(dev_info->screen_size);
+
+	if (info->screen_base == NULL) {
+		printk
+		    ("cannot allocate framebuffer virtual memory of %d bytes\n",
+		     dev_info->screen_size);
+		goto out0;
+	}
+
+	printk("screen base allocated !!!\n");
+
+	dev_info->backing_buffer = kzalloc(dev_info->screen_size, GFP_KERNEL);
+
+	if (!dev_info->backing_buffer)
+		printk("non posso allocare il backing buffer\n");
+
+	/* info->var = dev_info->si; */
+
+	info->var.bits_per_pixel = 16;
+	info->var.activate = FB_ACTIVATE_TEST;
+	info->var.vmode = FB_VMODE_NONINTERLACED;
+
+	info->var.red.offset = 11;
+	info->var.red.length = 5;
+	info->var.red.msb_right = 0;
+
+	info->var.green.offset = 5;
+	info->var.green.length = 6;
+	info->var.green.msb_right = 0;
+
+	info->var.blue.offset = 0;
+	info->var.blue.length = 5;
+	info->var.blue.msb_right = 0;
+
+	/* info->var.pixclock =  (10000000 / FB_W * 1000 / FB_H)/2 ; */
+
+	info->fix.smem_start = (unsigned long)info->screen_base;
+	info->fix.smem_len = PAGE_ALIGN(dev_info->screen_size);
+	if (strlen(dev_info->udev->product) > 15) {
+		memcpy(info->fix.id, dev_info->udev->product, 15);
+	} else {
+		memcpy(info->fix.id, dev_info->udev->product,
+		       strlen(dev_info->udev->product));
+	}
+	info->fix.type = FB_TYPE_PACKED_PIXELS;
+	info->fix.visual = FB_VISUAL_TRUECOLOR;
+	info->fix.accel = info->flags;
+	info->fix.line_length = dev_info->line_length;
+
+	if (fb_alloc_cmap(&info->cmap, 256, 0) < 0)
+		goto out1;
+
+	printk("colormap allocated\n");
+	if (register_framebuffer(info) < 0)
+		goto out2;
+
+	draw_rect(dev_info, 0, 0, dev_info->info->var.xres,
+		  dev_info->info->var.yres, 0x30, 0xff, 0x30);
+
+	return 0;
+
+out2:
+	fb_dealloc_cmap(&info->cmap);
+out1:
+	rvfree(info->screen_base, dev_info->screen_size);
+out0:
+	framebuffer_release(info);
+out:
+	usb_set_intfdata(interface, NULL);
+	usb_put_dev(dev_info->udev);
+	kfree(dev_info);
+	return -ENOMEM;
+
+}
+
+static void dlfb_disconnect(struct usb_interface *interface)
+{
+	struct dlfb_data *dev_info = usb_get_intfdata(interface);
+
+	mutex_unlock(&dev_info->bulk_mutex);
+
+	usb_kill_urb(dev_info->tx_urb);
+	usb_free_urb(dev_info->tx_urb);
+	usb_set_intfdata(interface, NULL);
+	usb_put_dev(dev_info->udev);
+
+	if (dev_info->info) {
+		unregister_framebuffer(dev_info->info);
+		fb_dealloc_cmap(&dev_info->info->cmap);
+		rvfree(dev_info->info->screen_base, dev_info->screen_size);
+		kfree(dev_info->backing_buffer);
+		framebuffer_release(dev_info->info);
+
+	}
+
+	kfree(dev_info);
+
+	printk("DisplayLink device disconnected\n");
+}
+
+static struct usb_driver dlfb_driver = {
+	.name = "udlfb",
+	.probe = dlfb_probe,
+	.disconnect = dlfb_disconnect,
+	.id_table = id_table,
+};
+
+static int __init dlfb_init(void)
+{
+	int res;
+
+	dlfb_init_modes();
+
+	res = usb_register(&dlfb_driver);
+	if (res)
+		err("usb_register failed. Error number %d", res);
+
+	printk("VMODES initialized\n");
+
+	return res;
+}
+
+static void __exit dlfb_exit(void)
+{
+	usb_deregister(&dlfb_driver);
+}
+
+module_init(dlfb_init);
+module_exit(dlfb_exit);
+
+MODULE_AUTHOR("Roberto De Ioris <roberto@unbit.it>");
+MODULE_DESCRIPTION(DRIVER_VERSION);
+MODULE_LICENSE("GPL");
diff --git a/drivers/staging/udlfb/udlfb.h b/drivers/staging/udlfb/udlfb.h
new file mode 100644
index 0000000..08bd671
--- /dev/null
+++ b/drivers/staging/udlfb/udlfb.h
@@ -0,0 +1,225 @@
+#ifndef UDLFB_H
+#define UDLFB_H
+
+#define MAX_VMODES	4
+#define FB_BPP		16
+
+#define STD_CHANNEL	"\x57\xCD\xDC\xA7\x1C\x88\x5E\x15"	\
+			"\x60\xFE\xC6\x97\x16\x3D\x47\xF2"
+
+/* as libdlo */
+#define BUF_HIGH_WATER_MARK	1024
+#define BUF_SIZE		(64*1024)
+
+struct dlfb_data {
+	struct usb_device *udev;
+	struct usb_interface *interface;
+	struct urb *tx_urb, *ctrl_urb;
+	struct usb_ctrlrequest dr;
+	struct fb_info *info;
+	char *buf;
+	char *bufend;
+	char *backing_buffer;
+	struct mutex bulk_mutex;
+	char edid[128];
+	int screen_size;
+	int line_length;
+	struct completion done;
+	int base16;
+	int base16d;
+	int base8;
+	int base8d;
+};
+
+struct dlfb_video_mode {
+	uint8_t col;
+	uint32_t hclock;
+	uint32_t vclock;
+	uint8_t unknown1[6];
+	uint16_t xres;
+	uint8_t unknown2[6];
+	uint16_t yres;
+	uint8_t unknown3[4];
+} __attribute__ ((__packed__));
+
+static struct dlfb_video_mode dlfb_video_modes[MAX_VMODES];
+
+static void dlfb_bulk_callback(struct urb *urb)
+{
+	struct dlfb_data *dev_info = urb->context;
+	complete(&dev_info->done);
+}
+
+static void dlfb_edid(struct dlfb_data *dev_info)
+{
+	int i;
+	int ret;
+	char rbuf[2];
+
+	for (i = 0; i < 128; i++) {
+		ret =
+		    usb_control_msg(dev_info->udev,
+				    usb_rcvctrlpipe(dev_info->udev, 0), (0x02),
+				    (0x80 | (0x02 << 5)), i << 8, 0xA1, rbuf, 2,
+				    0);
+		/*printk("ret control msg edid %d: %d [%d]\n",i, ret, rbuf[1]); */
+		dev_info->edid[i] = rbuf[1];
+	}
+
+}
+
+static int dlfb_bulk_msg(struct dlfb_data *dev_info, int len)
+{
+	int ret;
+
+	init_completion(&dev_info->done);
+
+	dev_info->tx_urb->actual_length = 0;
+	dev_info->tx_urb->transfer_buffer_length = len;
+
+	ret = usb_submit_urb(dev_info->tx_urb, GFP_KERNEL);
+	if (!wait_for_completion_timeout(&dev_info->done, 1000)) {
+		usb_kill_urb(dev_info->tx_urb);
+		printk("usb timeout !!!\n");
+	}
+
+	return dev_info->tx_urb->actual_length;
+}
+
+static void dlfb_init_modes(void)
+{
+	dlfb_video_modes[0].col = 0;
+	memcpy(&dlfb_video_modes[0].hclock, "\x20\x3C\x7A\xC9", 4);
+	memcpy(&dlfb_video_modes[0].vclock, "\xF2\x6C\x48\xF9", 4);
+	memcpy(&dlfb_video_modes[0].unknown1, "\x70\x53\xFF\xFF\x21\x27", 6);
+	dlfb_video_modes[0].xres = 800;
+	memcpy(&dlfb_video_modes[0].unknown2, "\x91\xF3\xFF\xFF\xFF\xF9", 6);
+	dlfb_video_modes[0].yres = 480;
+	memcpy(&dlfb_video_modes[0].unknown3, "\x01\x02\xC8\x19", 4);
+
+	dlfb_video_modes[1].col = 0;
+	memcpy(&dlfb_video_modes[1].hclock, "\x36\x18\xD5\x10", 4);
+	memcpy(&dlfb_video_modes[1].vclock, "\x60\xA9\x7B\x33", 4);
+	memcpy(&dlfb_video_modes[1].unknown1, "\xA1\x2B\x27\x32\xFF\xFF", 6);
+	dlfb_video_modes[1].xres = 1024;
+	memcpy(&dlfb_video_modes[1].unknown2, "\xD9\x9A\xFF\xCA\xFF\xFF", 6);
+	dlfb_video_modes[1].yres = 768;
+	memcpy(&dlfb_video_modes[1].unknown3, "\x04\x03\xC8\x32", 4);
+
+	dlfb_video_modes[2].col = 0;
+	memcpy(&dlfb_video_modes[2].hclock, "\x98\xF8\x0D\x57", 4);
+	memcpy(&dlfb_video_modes[2].vclock, "\x2A\x55\x4D\x54", 4);
+	memcpy(&dlfb_video_modes[2].unknown1, "\xCA\x0D\xFF\xFF\x94\x43", 6);
+	dlfb_video_modes[2].xres = 1280;
+	memcpy(&dlfb_video_modes[2].unknown2, "\x9A\xA8\xFF\xFF\xFF\xF9", 6);
+	dlfb_video_modes[2].yres = 1024;
+	memcpy(&dlfb_video_modes[2].unknown3, "\x04\x02\x60\x54", 4);
+
+	dlfb_video_modes[3].col = 0;
+	memcpy(&dlfb_video_modes[3].hclock, "\x42\x24\x38\x36", 4);
+	memcpy(&dlfb_video_modes[3].vclock, "\xC1\x52\xD9\x29", 4);
+	memcpy(&dlfb_video_modes[3].unknown1, "\xEA\xB8\x32\x60\xFF\xFF", 6);
+	dlfb_video_modes[3].xres = 1400;
+	memcpy(&dlfb_video_modes[3].unknown2, "\xC9\x4E\xFF\xFF\xFF\xF2", 6);
+	dlfb_video_modes[3].yres = 1050;
+	memcpy(&dlfb_video_modes[3].unknown3, "\x04\x02\x1E\x5F", 4);
+}
+
+static char *dlfb_set_register(char *bufptr, uint8_t reg, uint8_t val)
+{
+	*bufptr++ = 0xAF;
+	*bufptr++ = 0x20;
+	*bufptr++ = reg;
+	*bufptr++ = val;
+
+	return bufptr;
+}
+
+static int dlfb_set_video_mode(struct dlfb_data *dev_info, int width, int height)
+{
+	int i, ret;
+	unsigned char j;
+	char *bufptr = dev_info->buf;
+	uint8_t *vdata;
+
+	for (i = 0; i < MAX_VMODES; i++) {
+		printk("INIT VIDEO %d %d %d\n", i, dlfb_video_modes[i].xres,
+		       dlfb_video_modes[i].yres);
+		if (dlfb_video_modes[i].xres == width
+		    && dlfb_video_modes[i].yres == height) {
+
+			dev_info->base16 = 0;
+			dev_info->base16d = width * height * (FB_BPP / 8);
+
+			//dev_info->base8 = width * height * (FB_BPP / 8);
+
+			dev_info->base8 = dev_info->base16;
+			dev_info->base8d = dev_info->base16d;
+
+			/* set encryption key (null) */
+			memcpy(dev_info->buf, STD_CHANNEL, 16);
+			ret =
+			    usb_control_msg(dev_info->udev,
+					    usb_sndctrlpipe(dev_info->udev, 0),
+					    0x12, (0x02 << 5), 0, 0,
+					    dev_info->buf, 16, 0);
+			printk("ret control msg 1 (STD_CHANNEL): %d\n", ret);
+
+			/* set registers */
+			bufptr = dlfb_set_register(bufptr, 0xFF, 0x00);
+
+			/* set color depth */
+			bufptr = dlfb_set_register(bufptr, 0x00, 0x00);
+
+			/* set addresses */
+			bufptr =
+			    dlfb_set_register(bufptr, 0x20,
+					      (char)(dev_info->base16 >> 16));
+			bufptr =
+			    dlfb_set_register(bufptr, 0x21,
+					      (char)(dev_info->base16 >> 8));
+			bufptr =
+			    dlfb_set_register(bufptr, 0x22,
+					      (char)(dev_info->base16));
+
+			bufptr =
+			    dlfb_set_register(bufptr, 0x26,
+					      (char)(dev_info->base8 >> 16));
+			bufptr =
+			    dlfb_set_register(bufptr, 0x27,
+					      (char)(dev_info->base8 >> 8));
+			bufptr =
+			    dlfb_set_register(bufptr, 0x28,
+					      (char)(dev_info->base8));
+
+			/* set video mode */
+			vdata = (uint8_t *)&dlfb_video_modes[i];
+			for (j = 0; j < 29; j++)
+				bufptr = dlfb_set_register(bufptr, j, vdata[j]);
+
+			/* blank */
+			bufptr = dlfb_set_register(bufptr, 0x1F, 0x00);
+
+			/* end registers */
+			bufptr = dlfb_set_register(bufptr, 0xFF, 0xFF);
+
+			/* send */
+			ret = dlfb_bulk_msg(dev_info, bufptr - dev_info->buf);
+			printk("ret bulk 2: %d %d\n", ret,
+			       bufptr - dev_info->buf);
+
+			/* flush */
+			ret = dlfb_bulk_msg(dev_info, 0);
+			printk("ret bulk 3: %d\n", ret);
+
+			dev_info->screen_size = width * height * (FB_BPP / 8);
+			dev_info->line_length = width * (FB_BPP / 8);
+
+			return 0;
+		}
+	}
+
+	return -1;
+}
+
+#endif
diff --git a/drivers/staging/vt6655/80211hdr.h b/drivers/staging/vt6655/80211hdr.h
new file mode 100644
index 0000000..b4bbb8d
--- /dev/null
+++ b/drivers/staging/vt6655/80211hdr.h
@@ -0,0 +1,357 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: 80211hdr.h
+ *
+ * Purpose: Defines the macros, types, and functions for dealing
+ *          with 802.11 MAC headers.
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: Apr 8, 2002
+ *
+ */
+
+
+
+#ifndef __80211HDR_H__
+#define __80211HDR_H__
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+/*---------------------  Export Definitions -------------------------*/
+// bit type
+#define BIT0	0x00000001
+#define BIT1	0x00000002
+#define BIT2	0x00000004
+#define BIT3	0x00000008
+#define BIT4	0x00000010
+#define BIT5	0x00000020
+#define BIT6	0x00000040
+#define BIT7	0x00000080
+#define BIT8	0x00000100
+#define BIT9	0x00000200
+#define BIT10	0x00000400
+#define BIT11	0x00000800
+#define BIT12	0x00001000
+#define BIT13	0x00002000
+#define BIT14	0x00004000
+#define BIT15	0x00008000
+#define BIT16	0x00010000
+#define BIT17	0x00020000
+#define BIT18	0x00040000
+#define BIT19	0x00080000
+#define BIT20	0x00100000
+#define BIT21	0x00200000
+#define BIT22	0x00400000
+#define BIT23	0x00800000
+#define BIT24	0x01000000
+#define BIT25	0x02000000
+#define BIT26	0x04000000
+#define BIT27	0x08000000
+#define BIT28	0x10000000
+#define BIT29	0x20000000
+#define BIT30	0x40000000
+#define BIT31	0x80000000
+
+// 802.11 frame related, defined as 802.11 spec
+#define WLAN_ADDR_LEN               6
+#define WLAN_CRC_LEN                4
+#define WLAN_CRC32_LEN              4
+#define WLAN_FCS_LEN                4
+#define WLAN_BSSID_LEN              6
+#define WLAN_BSS_TS_LEN             8
+#define WLAN_HDR_ADDR2_LEN          16
+#define WLAN_HDR_ADDR3_LEN          24
+#define WLAN_HDR_ADDR4_LEN          30
+#define WLAN_IEHDR_LEN              2
+#define WLAN_SSID_MAXLEN            32
+//#define WLAN_RATES_MAXLEN           255
+#define WLAN_RATES_MAXLEN           16
+#define WLAN_RATES_MAXLEN_11B       4
+#define WLAN_RSN_MAXLEN             32
+#define WLAN_DATA_MAXLEN            2312
+#define WLAN_A3FR_MAXLEN            (WLAN_HDR_ADDR3_LEN + WLAN_DATA_MAXLEN + WLAN_CRC_LEN)
+
+
+#define WLAN_BEACON_FR_MAXLEN       WLAN_A3FR_MAXLEN
+#define WLAN_ATIM_FR_MAXLEN         (WLAN_HDR_ADDR3_LEN + 0)
+#define WLAN_NULLDATA_FR_MAXLEN     (WLAN_HDR_ADDR3_LEN + 0)
+#define WLAN_DISASSOC_FR_MAXLEN     (WLAN_HDR_ADDR3_LEN + 2)
+#define WLAN_ASSOCREQ_FR_MAXLEN     WLAN_A3FR_MAXLEN
+#define WLAN_ASSOCRESP_FR_MAXLEN    WLAN_A3FR_MAXLEN
+#define WLAN_REASSOCREQ_FR_MAXLEN   WLAN_A3FR_MAXLEN
+#define WLAN_REASSOCRESP_FR_MAXLEN  WLAN_A3FR_MAXLEN
+#define WLAN_PROBEREQ_FR_MAXLEN     WLAN_A3FR_MAXLEN
+#define WLAN_PROBERESP_FR_MAXLEN    WLAN_A3FR_MAXLEN
+#define WLAN_AUTHEN_FR_MAXLEN       WLAN_A3FR_MAXLEN
+#define WLAN_DEAUTHEN_FR_MAXLEN     (WLAN_HDR_ADDR3_LEN + 2)
+
+
+#define WLAN_WEP_NKEYS              4
+#define WLAN_WEP40_KEYLEN           5
+#define WLAN_WEP104_KEYLEN          13
+#define WLAN_WEP232_KEYLEN          29
+//#define WLAN_WEPMAX_KEYLEN          29
+#define WLAN_WEPMAX_KEYLEN          32
+#define WLAN_CHALLENGE_IE_MAXLEN    255
+#define WLAN_CHALLENGE_IE_LEN       130
+#define WLAN_CHALLENGE_LEN          128
+#define WLAN_WEP_IV_LEN             4
+#define WLAN_WEP_ICV_LEN            4
+#define WLAN_FRAGS_MAX              16
+
+// Frame Type
+#define WLAN_TYPE_MGR 0x00
+#define WLAN_TYPE_CTL  0x01
+#define WLAN_TYPE_DATA 0x02
+
+#define WLAN_FTYPE_MGMT 0x00
+#define WLAN_FTYPE_CTL  0x01
+#define WLAN_FTYPE_DATA 0x02
+
+
+// Frame Subtypes
+#define WLAN_FSTYPE_ASSOCREQ        0x00
+#define WLAN_FSTYPE_ASSOCRESP       0x01
+#define WLAN_FSTYPE_REASSOCREQ      0x02
+#define WLAN_FSTYPE_REASSOCRESP     0x03
+#define WLAN_FSTYPE_PROBEREQ        0x04
+#define WLAN_FSTYPE_PROBERESP       0x05
+#define WLAN_FSTYPE_BEACON          0x08
+#define WLAN_FSTYPE_ATIM            0x09
+#define WLAN_FSTYPE_DISASSOC        0x0a
+#define WLAN_FSTYPE_AUTHEN          0x0b
+#define WLAN_FSTYPE_DEAUTHEN        0x0c
+#define WLAN_FSTYPE_ACTION          0x0d
+
+// Control
+#define WLAN_FSTYPE_PSPOLL          0x0a
+#define WLAN_FSTYPE_RTS             0x0b
+#define WLAN_FSTYPE_CTS             0x0c
+#define WLAN_FSTYPE_ACK             0x0d
+#define WLAN_FSTYPE_CFEND           0x0e
+#define WLAN_FSTYPE_CFENDCFACK      0x0f
+
+// Data
+#define WLAN_FSTYPE_DATAONLY        0x00
+#define WLAN_FSTYPE_DATA_CFACK      0x01
+#define WLAN_FSTYPE_DATA_CFPOLL     0x02
+#define WLAN_FSTYPE_DATA_CFACK_CFPOLL   0x03
+#define WLAN_FSTYPE_NULL            0x04
+#define WLAN_FSTYPE_CFACK           0x05
+#define WLAN_FSTYPE_CFPOLL          0x06
+#define WLAN_FSTYPE_CFACK_CFPOLL    0x07
+
+
+#ifdef __BIG_ENDIAN
+
+// GET & SET Frame Control bit
+#define WLAN_GET_FC_PRVER(n)    ((((WORD)(n) >> 8) & (BIT0 | BIT1))
+#define WLAN_GET_FC_FTYPE(n)    ((((WORD)(n) >> 8) & (BIT2 | BIT3)) >> 2)
+#define WLAN_GET_FC_FSTYPE(n)   ((((WORD)(n) >> 8) & (BIT4|BIT5|BIT6|BIT7)) >> 4)
+#define WLAN_GET_FC_TODS(n)     ((((WORD)(n) << 8) & (BIT8)) >> 8)
+#define WLAN_GET_FC_FROMDS(n)   ((((WORD)(n) << 8) & (BIT9)) >> 9)
+#define WLAN_GET_FC_MOREFRAG(n) ((((WORD)(n) << 8) & (BIT10)) >> 10)
+#define WLAN_GET_FC_RETRY(n)    ((((WORD)(n) << 8) & (BIT11)) >> 11)
+#define WLAN_GET_FC_PWRMGT(n)   ((((WORD)(n) << 8) & (BIT12)) >> 12)
+#define WLAN_GET_FC_MOREDATA(n) ((((WORD)(n) << 8) & (BIT13)) >> 13)
+#define WLAN_GET_FC_ISWEP(n)    ((((WORD)(n) << 8) & (BIT14)) >> 14)
+#define WLAN_GET_FC_ORDER(n)    ((((WORD)(n) << 8) & (BIT15)) >> 15)
+
+// Sequence Field bit
+#define WLAN_GET_SEQ_FRGNUM(n) (((WORD)(n) >> 8) & (BIT0|BIT1|BIT2|BIT3))
+#define WLAN_GET_SEQ_SEQNUM(n) ((((WORD)(n) >> 8) & (~(BIT0|BIT1|BIT2|BIT3))) >> 4)
+
+
+// Capability Field bit
+#define WLAN_GET_CAP_INFO_ESS(n)           (((n) >> 8) & BIT0)
+#define WLAN_GET_CAP_INFO_IBSS(n)          ((((n) >> 8) & BIT1) >> 1)
+#define WLAN_GET_CAP_INFO_CFPOLLABLE(n)    ((((n) >> 8) & BIT2) >> 2)
+#define WLAN_GET_CAP_INFO_CFPOLLREQ(n)     ((((n) >> 8) & BIT3) >> 3)
+#define WLAN_GET_CAP_INFO_PRIVACY(n)       ((((n) >> 8) & BIT4) >> 4)
+#define WLAN_GET_CAP_INFO_SHORTPREAMBLE(n) ((((n) >> 8) & BIT5) >> 5)
+#define WLAN_GET_CAP_INFO_PBCC(n)          ((((n) >> 8) & BIT6) >> 6)
+#define WLAN_GET_CAP_INFO_AGILITY(n)       ((((n) >> 8) & BIT7) >> 7)
+#define WLAN_GET_CAP_INFO_SPECTRUMMNG(n)   ((((n))      & BIT8) >> 10)
+#define WLAN_GET_CAP_INFO_SHORTSLOTTIME(n) ((((n))      & BIT10) >> 10)
+#define WLAN_GET_CAP_INFO_DSSSOFDM(n)      ((((n))      & BIT13) >> 13)
+#define WLAN_GET_CAP_INFO_GRPACK(n)        ((((n))      & BIT14) >> 14)
+
+
+#else
+
+// GET & SET Frame Control bit
+#define WLAN_GET_FC_PRVER(n)    (((WORD)(n)) & (BIT0 | BIT1))
+#define WLAN_GET_FC_FTYPE(n)    ((((WORD)(n)) & (BIT2 | BIT3)) >> 2)
+#define WLAN_GET_FC_FSTYPE(n)   ((((WORD)(n)) & (BIT4|BIT5|BIT6|BIT7)) >> 4)
+#define WLAN_GET_FC_TODS(n)     ((((WORD)(n)) & (BIT8)) >> 8)
+#define WLAN_GET_FC_FROMDS(n)   ((((WORD)(n)) & (BIT9)) >> 9)
+#define WLAN_GET_FC_MOREFRAG(n) ((((WORD)(n)) & (BIT10)) >> 10)
+#define WLAN_GET_FC_RETRY(n)    ((((WORD)(n)) & (BIT11)) >> 11)
+#define WLAN_GET_FC_PWRMGT(n)   ((((WORD)(n)) & (BIT12)) >> 12)
+#define WLAN_GET_FC_MOREDATA(n) ((((WORD)(n)) & (BIT13)) >> 13)
+#define WLAN_GET_FC_ISWEP(n)    ((((WORD)(n)) & (BIT14)) >> 14)
+#define WLAN_GET_FC_ORDER(n)    ((((WORD)(n)) & (BIT15)) >> 15)
+
+
+// Sequence Field bit
+#define WLAN_GET_SEQ_FRGNUM(n) (((WORD)(n)) & (BIT0|BIT1|BIT2|BIT3))
+#define WLAN_GET_SEQ_SEQNUM(n) ((((WORD)(n)) & (~(BIT0|BIT1|BIT2|BIT3))) >> 4)
+
+
+// Capability Field bit
+#define WLAN_GET_CAP_INFO_ESS(n)           ((n) & BIT0)
+#define WLAN_GET_CAP_INFO_IBSS(n)          (((n) & BIT1) >> 1)
+#define WLAN_GET_CAP_INFO_CFPOLLABLE(n)    (((n) & BIT2) >> 2)
+#define WLAN_GET_CAP_INFO_CFPOLLREQ(n)     (((n) & BIT3) >> 3)
+#define WLAN_GET_CAP_INFO_PRIVACY(n)       (((n) & BIT4) >> 4)
+#define WLAN_GET_CAP_INFO_SHORTPREAMBLE(n) (((n) & BIT5) >> 5)
+#define WLAN_GET_CAP_INFO_PBCC(n)          (((n) & BIT6) >> 6)
+#define WLAN_GET_CAP_INFO_AGILITY(n)       (((n) & BIT7) >> 7)
+#define WLAN_GET_CAP_INFO_SPECTRUMMNG(n)   (((n) & BIT8) >> 10)
+#define WLAN_GET_CAP_INFO_SHORTSLOTTIME(n) (((n) & BIT10) >> 10)
+#define WLAN_GET_CAP_INFO_DSSSOFDM(n)      (((n) & BIT13) >> 13)
+#define WLAN_GET_CAP_INFO_GRPACK(n)        (((n) & BIT14) >> 14)
+
+
+#endif //#ifdef __BIG_ENDIAN
+
+
+#define WLAN_SET_CAP_INFO_ESS(n)           (n)
+#define WLAN_SET_CAP_INFO_IBSS(n)          ((n) << 1)
+#define WLAN_SET_CAP_INFO_CFPOLLABLE(n)    ((n) << 2)
+#define WLAN_SET_CAP_INFO_CFPOLLREQ(n)     ((n) << 3)
+#define WLAN_SET_CAP_INFO_PRIVACY(n)       ((n) << 4)
+#define WLAN_SET_CAP_INFO_SHORTPREAMBLE(n) ((n) << 5)
+#define WLAN_SET_CAP_INFO_SPECTRUMMNG(n)   ((n) << 8)
+#define WLAN_SET_CAP_INFO_PBCC(n)          ((n) << 6)
+#define WLAN_SET_CAP_INFO_AGILITY(n)       ((n) << 7)
+#define WLAN_SET_CAP_INFO_SHORTSLOTTIME(n) ((n) << 10)
+#define WLAN_SET_CAP_INFO_DSSSOFDM(n)      ((n) << 13)
+#define WLAN_SET_CAP_INFO_GRPACK(n)        ((n) << 14)
+
+
+#define WLAN_SET_FC_PRVER(n)    ((WORD)(n))
+#define WLAN_SET_FC_FTYPE(n)    (((WORD)(n)) << 2)
+#define WLAN_SET_FC_FSTYPE(n)   (((WORD)(n)) << 4)
+#define WLAN_SET_FC_TODS(n)     (((WORD)(n)) << 8)
+#define WLAN_SET_FC_FROMDS(n)   (((WORD)(n)) << 9)
+#define WLAN_SET_FC_MOREFRAG(n) (((WORD)(n)) << 10)
+#define WLAN_SET_FC_RETRY(n)    (((WORD)(n)) << 11)
+#define WLAN_SET_FC_PWRMGT(n)   (((WORD)(n)) << 12)
+#define WLAN_SET_FC_MOREDATA(n) (((WORD)(n)) << 13)
+#define WLAN_SET_FC_ISWEP(n)    (((WORD)(n)) << 14)
+#define WLAN_SET_FC_ORDER(n)    (((WORD)(n)) << 15)
+
+#define WLAN_SET_SEQ_FRGNUM(n) ((WORD)(n))
+#define WLAN_SET_SEQ_SEQNUM(n) (((WORD)(n)) << 4)
+
+// ERP Field bit
+
+#define WLAN_GET_ERP_NONERP_PRESENT(n)     ((n) & BIT0)
+#define WLAN_GET_ERP_USE_PROTECTION(n)     (((n) & BIT1) >> 1)
+#define WLAN_GET_ERP_BARKER_MODE(n)        (((n) & BIT2) >> 2)
+
+#define WLAN_SET_ERP_NONERP_PRESENT(n)     (n)
+#define WLAN_SET_ERP_USE_PROTECTION(n)     ((n) << 1)
+#define WLAN_SET_ERP_BARKER_MODE(n)        ((n) << 2)
+
+
+
+// Support & Basic Rates field
+#define WLAN_MGMT_IS_BASICRATE(b)    ((b) & BIT7)
+#define WLAN_MGMT_GET_RATE(b)        ((b) & ~BIT7)
+
+// TIM field
+#define WLAN_MGMT_IS_MULTICAST_TIM(b)   ((b) & BIT0)
+#define WLAN_MGMT_GET_TIM_OFFSET(b)     (((b) & ~BIT0) >> 1)
+
+// 3-Addr & 4-Addr
+#define WLAN_HDR_A3_DATA_PTR(p) (((PBYTE)(p)) + WLAN_HDR_ADDR3_LEN)
+#define WLAN_HDR_A4_DATA_PTR(p) (((PBYTE)(p)) + WLAN_HDR_ADDR4_LEN)
+
+// IEEE ADDR
+#define IEEE_ADDR_UNIVERSAL         0x02
+#define IEEE_ADDR_GROUP             0x01
+
+typedef struct {
+    BYTE            abyAddr[6];
+} IEEE_ADDR, *PIEEE_ADDR;
+
+// 802.11 Header Format
+
+typedef struct tagWLAN_80211HDR_A2 {
+
+    WORD    wFrameCtl;
+    WORD    wDurationID;
+    BYTE    abyAddr1[WLAN_ADDR_LEN];
+    BYTE    abyAddr2[WLAN_ADDR_LEN];
+
+}__attribute__ ((__packed__))
+WLAN_80211HDR_A2, *PWLAN_80211HDR_A2;
+
+typedef struct tagWLAN_80211HDR_A3 {
+
+    WORD    wFrameCtl;
+    WORD    wDurationID;
+    BYTE    abyAddr1[WLAN_ADDR_LEN];
+    BYTE    abyAddr2[WLAN_ADDR_LEN];
+    BYTE    abyAddr3[WLAN_ADDR_LEN];
+    WORD    wSeqCtl;
+
+}__attribute__ ((__packed__))
+WLAN_80211HDR_A3, *PWLAN_80211HDR_A3;
+
+typedef struct tagWLAN_80211HDR_A4 {
+
+    WORD    wFrameCtl;
+    WORD    wDurationID;
+    BYTE    abyAddr1[WLAN_ADDR_LEN];
+    BYTE    abyAddr2[WLAN_ADDR_LEN];
+    BYTE    abyAddr3[WLAN_ADDR_LEN];
+    WORD    wSeqCtl;
+    BYTE    abyAddr4[WLAN_ADDR_LEN];
+
+}__attribute__ ((__packed__))
+WLAN_80211HDR_A4, *PWLAN_80211HDR_A4;
+
+
+typedef union tagUWLAN_80211HDR {
+
+    WLAN_80211HDR_A2        sA2;
+    WLAN_80211HDR_A3        sA3;
+    WLAN_80211HDR_A4        sA4;
+
+} UWLAN_80211HDR, *PUWLAN_80211HDR;
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+#endif // __80211HDR_H__
+
+
diff --git a/drivers/staging/vt6655/80211mgr.c b/drivers/staging/vt6655/80211mgr.c
new file mode 100644
index 0000000..84745fb6
--- /dev/null
+++ b/drivers/staging/vt6655/80211mgr.c
@@ -0,0 +1,1050 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: 80211mgr.c
+ *
+ * Purpose: Handles the 802.11 managment support functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 8, 2002
+ *
+ * Functions:
+ *      vMgrEncodeBeacon - Encode the Beacon frame
+ *      vMgrDecodeBeacon - Decode the Beacon frame
+ *      vMgrEncodeIBSSATIM - Encode the IBSS ATIM frame
+ *      vMgrDecodeIBSSATIM - Decode the IBSS ATIM frame
+ *      vMgrEncodeDisassociation - Encode the Disassociation frame
+ *      vMgrDecodeDisassociation - Decode the Disassociation frame
+ *      vMgrEncodeAssocRequest - Encode the Association request frame
+ *      vMgrDecodeAssocRequest - Decode the Association request frame
+ *      vMgrEncodeAssocResponse - Encode the Association response frame
+ *      vMgrDecodeAssocResponse - Decode the Association response frame
+ *      vMgrEncodeReAssocRequest - Encode the ReAssociation request frame
+ *      vMgrDecodeReAssocRequest - Decode the ReAssociation request frame
+ *      vMgrEncodeProbeRequest - Encode the Probe request frame
+ *      vMgrDecodeProbeRequest - Decode the Probe request frame
+ *      vMgrEncodeProbeResponse - Encode the Probe response frame
+ *      vMgrDecodeProbeResponse - Decode the Probe response frame
+ *      vMgrEncodeAuthen - Encode the Authentication frame
+ *      vMgrDecodeAuthen - Decode the Authentication frame
+ *      vMgrEncodeDeauthen - Encode the DeAuthentication frame
+ *      vMgrDecodeDeauthen - Decode the DeAuthentication frame
+ *      vMgrEncodeReassocResponse - Encode the Reassociation response frame
+ *      vMgrDecodeReassocResponse - Decode the Reassociation response frame
+ *
+ * Revision History:
+ *
+ */
+
+
+
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__80211MGR_H__)
+#include "80211mgr.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__WPA_H__)
+#include "wpa.h"
+#endif
+
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+static int          msglevel                =MSG_LEVEL_INFO;
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+/*---------------------  Static Functions  --------------------------*/
+
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+/*+
+ *
+ * Routine Description:
+ * Encode Beacon frame body offset
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrEncodeBeacon(
+    IN  PWLAN_FR_BEACON  pFrame
+     )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pqwTimestamp = (PQWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                    + WLAN_BEACON_OFF_TS);
+    pFrame->pwBeaconInterval = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                       + WLAN_BEACON_OFF_BCN_INT);
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_BEACON_OFF_CAPINFO);
+
+    pFrame->len = WLAN_HDR_ADDR3_LEN + WLAN_BEACON_OFF_SSID;
+
+    return;
+}
+
+/*+
+ *
+ * Routine Description:
+ * Decode Beacon frame body offset
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+VOID
+vMgrDecodeBeacon(
+    IN  PWLAN_FR_BEACON  pFrame
+    )
+{
+    PWLAN_IE        pItem;
+
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pqwTimestamp = (PQWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                    + WLAN_BEACON_OFF_TS);
+    pFrame->pwBeaconInterval = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                       + WLAN_BEACON_OFF_BCN_INT);
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_BEACON_OFF_CAPINFO);
+
+    // Information elements
+    pItem = (PWLAN_IE)((PBYTE)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3)))
+                       + WLAN_BEACON_OFF_SSID);
+    while( ((PBYTE)pItem) < (pFrame->pBuf + pFrame->len) ){
+
+        switch (pItem->byElementID) {
+            case WLAN_EID_SSID:
+                if (pFrame->pSSID == NULL)
+                    pFrame->pSSID = (PWLAN_IE_SSID)pItem;
+                break;
+            case WLAN_EID_SUPP_RATES:
+                if (pFrame->pSuppRates == NULL)
+                    pFrame->pSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+                break;
+            case WLAN_EID_FH_PARMS:
+                //pFrame->pFHParms = (PWLAN_IE_FH_PARMS)pItem;
+                break;
+            case WLAN_EID_DS_PARMS:
+                if (pFrame->pDSParms == NULL)
+                    pFrame->pDSParms = (PWLAN_IE_DS_PARMS)pItem;
+                break;
+            case WLAN_EID_CF_PARMS:
+                if (pFrame->pCFParms == NULL)
+                    pFrame->pCFParms = (PWLAN_IE_CF_PARMS)pItem;
+                break;
+            case WLAN_EID_IBSS_PARMS:
+                if (pFrame->pIBSSParms == NULL)
+                    pFrame->pIBSSParms = (PWLAN_IE_IBSS_PARMS)pItem;
+                break;
+            case WLAN_EID_TIM:
+                if (pFrame->pTIM == NULL)
+                    pFrame->pTIM = (PWLAN_IE_TIM)pItem;
+                break;
+
+            case WLAN_EID_RSN:
+                if (pFrame->pRSN == NULL) {
+                    pFrame->pRSN = (PWLAN_IE_RSN)pItem;
+                }
+                break;
+            case WLAN_EID_RSN_WPA:
+                if (pFrame->pRSNWPA == NULL) {
+                    if (WPAb_Is_RSN((PWLAN_IE_RSN_EXT)pItem) == TRUE)
+                        pFrame->pRSNWPA = (PWLAN_IE_RSN_EXT)pItem;
+                }
+                break;
+
+            case WLAN_EID_ERP:
+                if (pFrame->pERP == NULL)
+                    pFrame->pERP = (PWLAN_IE_ERP)pItem;
+                break;
+            case WLAN_EID_EXTSUPP_RATES:
+                if (pFrame->pExtSuppRates == NULL)
+                    pFrame->pExtSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+                break;
+
+            case WLAN_EID_COUNTRY:      //7
+                if (pFrame->pIE_Country == NULL)
+                    pFrame->pIE_Country = (PWLAN_IE_COUNTRY)pItem;
+                break;
+
+            case WLAN_EID_PWR_CONSTRAINT:   //32
+                if (pFrame->pIE_PowerConstraint == NULL)
+                    pFrame->pIE_PowerConstraint = (PWLAN_IE_PW_CONST)pItem;
+                break;
+
+            case WLAN_EID_CH_SWITCH:    //37
+                if (pFrame->pIE_CHSW == NULL)
+                    pFrame->pIE_CHSW = (PWLAN_IE_CH_SW)pItem;
+                break;
+
+            case WLAN_EID_QUIET:        //40
+                if (pFrame->pIE_Quiet == NULL)
+                    pFrame->pIE_Quiet = (PWLAN_IE_QUIET)pItem;
+                break;
+
+            case WLAN_EID_IBSS_DFS:
+                if (pFrame->pIE_IBSSDFS == NULL)
+                    pFrame->pIE_IBSSDFS = (PWLAN_IE_IBSS_DFS)pItem;
+                break;
+
+            default:
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Unrecognized EID=%dd in beacon decode.\n", pItem->byElementID);
+                break;
+
+        }
+        pItem = (PWLAN_IE)(((PBYTE)pItem) + 2 + pItem->len);
+    }
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *  Encode IBSS ATIM
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+VOID
+vMgrEncodeIBSSATIM(
+    IN  PWLAN_FR_IBSSATIM   pFrame
+    )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+    pFrame->len = WLAN_HDR_ADDR3_LEN;
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *  Decode IBSS ATIM
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrDecodeIBSSATIM(
+    IN  PWLAN_FR_IBSSATIM   pFrame
+    )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *  Encode Disassociation
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrEncodeDisassociation(
+    IN  PWLAN_FR_DISASSOC  pFrame
+    )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+
+    // Fixed Fields
+    pFrame->pwReason = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                               + WLAN_DISASSOC_OFF_REASON);
+    pFrame->len = WLAN_HDR_ADDR3_LEN + WLAN_DISASSOC_OFF_REASON + sizeof(*(pFrame->pwReason));
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *  Decode Disassociation
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrDecodeDisassociation(
+    IN  PWLAN_FR_DISASSOC  pFrame
+    )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pwReason = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                               + WLAN_DISASSOC_OFF_REASON);
+
+    return;
+}
+
+/*+
+ *
+ * Routine Description:
+ *  Encode Association Request
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+VOID
+vMgrEncodeAssocRequest(
+    IN  PWLAN_FR_ASSOCREQ  pFrame
+    )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+    // Fixed Fields
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_ASSOCREQ_OFF_CAP_INFO);
+    pFrame->pwListenInterval = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                       + WLAN_ASSOCREQ_OFF_LISTEN_INT);
+    pFrame->len = WLAN_HDR_ADDR3_LEN + WLAN_ASSOCREQ_OFF_LISTEN_INT + sizeof(*(pFrame->pwListenInterval));
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description: (AP)
+ *  Decode Association Request
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrDecodeAssocRequest(
+    IN  PWLAN_FR_ASSOCREQ  pFrame
+    )
+{
+    PWLAN_IE   pItem;
+
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+    // Fixed Fields
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_ASSOCREQ_OFF_CAP_INFO);
+    pFrame->pwListenInterval = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_ASSOCREQ_OFF_LISTEN_INT);
+
+    // Information elements
+    pItem = (PWLAN_IE)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                            + WLAN_ASSOCREQ_OFF_SSID);
+
+    while (((PBYTE)pItem) < (pFrame->pBuf + pFrame->len)) {
+        switch (pItem->byElementID){
+            case WLAN_EID_SSID:
+                if (pFrame->pSSID == NULL)
+                    pFrame->pSSID = (PWLAN_IE_SSID)pItem;
+                break;
+            case WLAN_EID_SUPP_RATES:
+                if (pFrame->pSuppRates == NULL)
+                    pFrame->pSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+                break;
+
+            case WLAN_EID_RSN:
+                if (pFrame->pRSN == NULL) {
+                    pFrame->pRSN = (PWLAN_IE_RSN)pItem;
+                }
+                break;
+            case WLAN_EID_RSN_WPA:
+                if (pFrame->pRSNWPA == NULL) {
+                    if (WPAb_Is_RSN((PWLAN_IE_RSN_EXT)pItem) == TRUE)
+                        pFrame->pRSNWPA = (PWLAN_IE_RSN_EXT)pItem;
+                }
+                break;
+            case WLAN_EID_EXTSUPP_RATES:
+                if (pFrame->pExtSuppRates == NULL)
+                    pFrame->pExtSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+                break;
+
+            default:
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Unrecognized EID=%dd in assocreq decode.\n",
+                        pItem->byElementID);
+                break;
+        }
+        pItem = (PWLAN_IE)(((PBYTE)pItem) + 2 + pItem->len);
+    }
+    return;
+}
+
+/*+
+ *
+ * Routine Description: (AP)
+ *  Encode Association Response
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrEncodeAssocResponse(
+    IN  PWLAN_FR_ASSOCRESP  pFrame
+     )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_ASSOCRESP_OFF_CAP_INFO);
+    pFrame->pwStatus = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                               + WLAN_ASSOCRESP_OFF_STATUS);
+    pFrame->pwAid = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                            + WLAN_ASSOCRESP_OFF_AID);
+    pFrame->len = WLAN_HDR_ADDR3_LEN + WLAN_ASSOCRESP_OFF_AID
+                  + sizeof(*(pFrame->pwAid));
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *  Decode Association Response
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrDecodeAssocResponse(
+    IN PWLAN_FR_ASSOCRESP  pFrame
+     )
+{
+    PWLAN_IE   pItem;
+
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_ASSOCRESP_OFF_CAP_INFO);
+    pFrame->pwStatus = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                               + WLAN_ASSOCRESP_OFF_STATUS);
+    pFrame->pwAid = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                            + WLAN_ASSOCRESP_OFF_AID);
+
+    // Information elements
+    pFrame->pSuppRates  = (PWLAN_IE_SUPP_RATES)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                           + WLAN_ASSOCRESP_OFF_SUPP_RATES);
+
+    pItem = (PWLAN_IE)(pFrame->pSuppRates);
+    pItem = (PWLAN_IE)(((PBYTE)pItem) + 2 + pItem->len);
+
+    if ((((PBYTE)pItem) < (pFrame->pBuf + pFrame->len)) && (pItem->byElementID == WLAN_EID_EXTSUPP_RATES)) {
+        pFrame->pExtSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pFrame->pExtSuppRates=[%p].\n", pItem);
+    }
+    else {
+        pFrame->pExtSuppRates = NULL;
+    }
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *  Encode Reassociation Request
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrEncodeReassocRequest(
+    IN  PWLAN_FR_REASSOCREQ  pFrame
+     )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_REASSOCREQ_OFF_CAP_INFO);
+    pFrame->pwListenInterval = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                      + WLAN_REASSOCREQ_OFF_LISTEN_INT);
+    pFrame->pAddrCurrAP = (PIEEE_ADDR)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                       + WLAN_REASSOCREQ_OFF_CURR_AP);
+    pFrame->len = WLAN_HDR_ADDR3_LEN + WLAN_REASSOCREQ_OFF_CURR_AP + sizeof(*(pFrame->pAddrCurrAP));
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description: (AP)
+ *  Decode Reassociation Request
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+VOID
+vMgrDecodeReassocRequest(
+    IN  PWLAN_FR_REASSOCREQ  pFrame
+     )
+{
+    PWLAN_IE   pItem;
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_REASSOCREQ_OFF_CAP_INFO);
+    pFrame->pwListenInterval = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                      + WLAN_REASSOCREQ_OFF_LISTEN_INT);
+    pFrame->pAddrCurrAP = (PIEEE_ADDR)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                       + WLAN_REASSOCREQ_OFF_CURR_AP);
+
+    // Information elements
+    pItem = (PWLAN_IE)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                       + WLAN_REASSOCREQ_OFF_SSID);
+
+    while(((PBYTE)pItem) < (pFrame->pBuf + pFrame->len)) {
+
+        switch (pItem->byElementID){
+            case WLAN_EID_SSID:
+                if (pFrame->pSSID == NULL)
+                    pFrame->pSSID = (PWLAN_IE_SSID)pItem;
+                break;
+            case WLAN_EID_SUPP_RATES:
+                if (pFrame->pSuppRates == NULL)
+                    pFrame->pSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+                break;
+
+            case WLAN_EID_RSN:
+                if (pFrame->pRSN == NULL) {
+                    pFrame->pRSN = (PWLAN_IE_RSN)pItem;
+                }
+                break;
+            case WLAN_EID_RSN_WPA:
+                if (pFrame->pRSNWPA == NULL) {
+                    if (WPAb_Is_RSN((PWLAN_IE_RSN_EXT)pItem) == TRUE)
+                        pFrame->pRSNWPA = (PWLAN_IE_RSN_EXT)pItem;
+                }
+                break;
+
+            case WLAN_EID_EXTSUPP_RATES:
+                if (pFrame->pExtSuppRates == NULL)
+                    pFrame->pExtSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+                break;
+            default:
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Unrecognized EID=%dd in reassocreq decode.\n",
+                            pItem->byElementID);
+                break;
+        }
+        pItem = (PWLAN_IE)(((PBYTE)pItem) + 2 + pItem->len);
+    }
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *  Encode Probe Request
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+VOID
+vMgrEncodeProbeRequest(
+    IN PWLAN_FR_PROBEREQ  pFrame
+     )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+    pFrame->len = WLAN_HDR_ADDR3_LEN;
+    return;
+}
+
+/*+
+ *
+ * Routine Description:
+ *  Decode Probe Request
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrDecodeProbeRequest(
+    IN PWLAN_FR_PROBEREQ  pFrame
+     )
+{
+    PWLAN_IE   pItem;
+
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Information elements
+    pItem = (PWLAN_IE)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3)));
+
+    while( ((PBYTE)pItem) < (pFrame->pBuf + pFrame->len) ) {
+
+        switch (pItem->byElementID) {
+            case WLAN_EID_SSID:
+                if (pFrame->pSSID == NULL)
+                    pFrame->pSSID = (PWLAN_IE_SSID)pItem;
+                break;
+
+            case WLAN_EID_SUPP_RATES:
+                if (pFrame->pSuppRates == NULL)
+                    pFrame->pSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+                break;
+
+            case WLAN_EID_EXTSUPP_RATES:
+                if (pFrame->pExtSuppRates == NULL)
+                    pFrame->pExtSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+                break;
+
+            default:
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Bad EID=%dd in probereq\n", pItem->byElementID);
+                break;
+        }
+
+        pItem = (PWLAN_IE)(((PBYTE)pItem) + 2 +  pItem->len);
+    }
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *  Encode Probe Response
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+VOID
+vMgrEncodeProbeResponse(
+    IN PWLAN_FR_PROBERESP  pFrame
+    )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pqwTimestamp = (PQWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                    + WLAN_PROBERESP_OFF_TS);
+    pFrame->pwBeaconInterval = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                       + WLAN_PROBERESP_OFF_BCN_INT);
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_PROBERESP_OFF_CAP_INFO);
+
+    pFrame->len = WLAN_HDR_ADDR3_LEN + WLAN_PROBERESP_OFF_CAP_INFO +
+                  sizeof(*(pFrame->pwCapInfo));
+
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *  Decode Probe Response
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrDecodeProbeResponse(
+    IN PWLAN_FR_PROBERESP  pFrame
+    )
+{
+    PWLAN_IE    pItem;
+//    BYTE        byCheckEID = 0;
+
+
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pqwTimestamp = (PQWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                    + WLAN_PROBERESP_OFF_TS);
+    pFrame->pwBeaconInterval = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                       + WLAN_PROBERESP_OFF_BCN_INT);
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_PROBERESP_OFF_CAP_INFO);
+
+    // Information elements
+    pItem = (PWLAN_IE)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                       + WLAN_PROBERESP_OFF_SSID);
+
+    while( ((PBYTE)pItem) < (pFrame->pBuf + pFrame->len) ) {
+		/*
+        if (pItem->byElementID < byCheckEID)
+            break;
+        else
+            byCheckEID = pItem->byElementID;
+*/
+        switch (pItem->byElementID) {
+            case WLAN_EID_SSID:
+                if (pFrame->pSSID == NULL)
+                pFrame->pSSID = (PWLAN_IE_SSID)pItem;
+                break;
+            case WLAN_EID_SUPP_RATES:
+                if (pFrame->pSuppRates == NULL)
+                pFrame->pSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+                break;
+            case WLAN_EID_FH_PARMS:
+                break;
+            case WLAN_EID_DS_PARMS:
+                if (pFrame->pDSParms == NULL)
+                    pFrame->pDSParms = (PWLAN_IE_DS_PARMS)pItem;
+                break;
+            case WLAN_EID_CF_PARMS:
+                if (pFrame->pCFParms == NULL)
+                    pFrame->pCFParms = (PWLAN_IE_CF_PARMS)pItem;
+                break;
+            case WLAN_EID_IBSS_PARMS:
+                if (pFrame->pIBSSParms == NULL)
+                    pFrame->pIBSSParms = (PWLAN_IE_IBSS_PARMS)pItem;
+                break;
+
+            case WLAN_EID_RSN:
+                if (pFrame->pRSN == NULL) {
+                    pFrame->pRSN = (PWLAN_IE_RSN)pItem;
+                }
+                break;
+            case WLAN_EID_RSN_WPA:
+                if (pFrame->pRSNWPA == NULL) {
+                    if (WPAb_Is_RSN((PWLAN_IE_RSN_EXT)pItem) == TRUE)
+                        pFrame->pRSNWPA = (PWLAN_IE_RSN_EXT)pItem;
+                }
+                break;
+            case WLAN_EID_ERP:
+                if (pFrame->pERP == NULL)
+                    pFrame->pERP = (PWLAN_IE_ERP)pItem;
+                break;
+            case WLAN_EID_EXTSUPP_RATES:
+                if (pFrame->pExtSuppRates == NULL)
+                    pFrame->pExtSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+                break;
+
+            case WLAN_EID_COUNTRY:      //7
+                if (pFrame->pIE_Country == NULL)
+                    pFrame->pIE_Country = (PWLAN_IE_COUNTRY)pItem;
+                break;
+
+            case WLAN_EID_PWR_CONSTRAINT:   //32
+                if (pFrame->pIE_PowerConstraint == NULL)
+                    pFrame->pIE_PowerConstraint = (PWLAN_IE_PW_CONST)pItem;
+                break;
+
+            case WLAN_EID_CH_SWITCH:    //37
+                if (pFrame->pIE_CHSW == NULL)
+                    pFrame->pIE_CHSW = (PWLAN_IE_CH_SW)pItem;
+                break;
+
+            case WLAN_EID_QUIET:        //40
+                if (pFrame->pIE_Quiet == NULL)
+                    pFrame->pIE_Quiet = (PWLAN_IE_QUIET)pItem;
+                break;
+
+            case WLAN_EID_IBSS_DFS:
+                if (pFrame->pIE_IBSSDFS == NULL)
+                    pFrame->pIE_IBSSDFS = (PWLAN_IE_IBSS_DFS)pItem;
+                break;
+
+            default:
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Bad EID=%dd in proberesp\n", pItem->byElementID);
+                break;
+        }
+
+        pItem = (PWLAN_IE)(((PBYTE)pItem) + 2 +  pItem->len);
+    }
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *     Encode Authentication frame
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrEncodeAuthen(
+    IN  PWLAN_FR_AUTHEN  pFrame
+    )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pwAuthAlgorithm = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                      + WLAN_AUTHEN_OFF_AUTH_ALG);
+    pFrame->pwAuthSequence = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                     + WLAN_AUTHEN_OFF_AUTH_SEQ);
+    pFrame->pwStatus = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                               + WLAN_AUTHEN_OFF_STATUS);
+    pFrame->len = WLAN_HDR_ADDR3_LEN + WLAN_AUTHEN_OFF_STATUS + sizeof(*(pFrame->pwStatus));
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *   Decode Authentication
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrDecodeAuthen(
+    IN  PWLAN_FR_AUTHEN  pFrame
+    )
+{
+    PWLAN_IE    pItem;
+
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pwAuthAlgorithm = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                      + WLAN_AUTHEN_OFF_AUTH_ALG);
+    pFrame->pwAuthSequence = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                     + WLAN_AUTHEN_OFF_AUTH_SEQ);
+    pFrame->pwStatus = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                               + WLAN_AUTHEN_OFF_STATUS);
+
+    // Information elements
+    pItem = (PWLAN_IE)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                       + WLAN_AUTHEN_OFF_CHALLENGE);
+
+    if ((((PBYTE)pItem) < (pFrame->pBuf + pFrame->len)) && (pItem->byElementID == WLAN_EID_CHALLENGE)) {
+        pFrame->pChallenge = (PWLAN_IE_CHALLENGE)pItem;
+    }
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *   Encode Authentication
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrEncodeDeauthen(
+    IN  PWLAN_FR_DEAUTHEN  pFrame
+    )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pwReason = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                               + WLAN_DEAUTHEN_OFF_REASON);
+    pFrame->len = WLAN_HDR_ADDR3_LEN + WLAN_DEAUTHEN_OFF_REASON + sizeof(*(pFrame->pwReason));
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *   Decode Deauthentication
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrDecodeDeauthen(
+    IN  PWLAN_FR_DEAUTHEN  pFrame
+    )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pwReason = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                               + WLAN_DEAUTHEN_OFF_REASON);
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description: (AP)
+ *   Encode Reassociation Response
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrEncodeReassocResponse(
+    IN  PWLAN_FR_REASSOCRESP  pFrame
+     )
+{
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_REASSOCRESP_OFF_CAP_INFO);
+    pFrame->pwStatus = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                               + WLAN_REASSOCRESP_OFF_STATUS);
+    pFrame->pwAid = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                            + WLAN_REASSOCRESP_OFF_AID);
+
+    pFrame->len = WLAN_HDR_ADDR3_LEN + WLAN_REASSOCRESP_OFF_AID + sizeof(*(pFrame->pwAid));
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *   Decode Reassociation Response
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+VOID
+vMgrDecodeReassocResponse(
+    IN  PWLAN_FR_REASSOCRESP  pFrame
+     )
+{
+    PWLAN_IE   pItem;
+
+    pFrame->pHdr = (PUWLAN_80211HDR)pFrame->pBuf;
+
+    // Fixed Fields
+    pFrame->pwCapInfo = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                + WLAN_REASSOCRESP_OFF_CAP_INFO);
+    pFrame->pwStatus = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                               + WLAN_REASSOCRESP_OFF_STATUS);
+    pFrame->pwAid = (PWORD)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                            + WLAN_REASSOCRESP_OFF_AID);
+
+    //Information elements
+    pFrame->pSuppRates = (PWLAN_IE_SUPP_RATES)(WLAN_HDR_A3_DATA_PTR(&(pFrame->pHdr->sA3))
+                                               + WLAN_REASSOCRESP_OFF_SUPP_RATES);
+
+    pItem = (PWLAN_IE)(pFrame->pSuppRates);
+    pItem = (PWLAN_IE)(((PBYTE)pItem) + 2 + pItem->len);
+
+    if ((((PBYTE)pItem) < (pFrame->pBuf + pFrame->len)) && (pItem->byElementID == WLAN_EID_EXTSUPP_RATES)) {
+        pFrame->pExtSuppRates = (PWLAN_IE_SUPP_RATES)pItem;
+    }
+    return;
+}
diff --git a/drivers/staging/vt6655/80211mgr.h b/drivers/staging/vt6655/80211mgr.h
new file mode 100644
index 0000000..dc54a65
--- /dev/null
+++ b/drivers/staging/vt6655/80211mgr.h
@@ -0,0 +1,832 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: 80211mgr.h
+ *
+ * Purpose: Defines the macros, types, and functions for dealing
+ *          with 802.11 managment frames.
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 8, 2002
+ *
+ */
+
+
+#ifndef __80211MGR_H__
+#define __80211MGR_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+#define WLAN_MIN_ARRAY          1
+
+// Information Element ID value
+#define WLAN_EID_SSID           0
+#define WLAN_EID_SUPP_RATES     1
+#define WLAN_EID_FH_PARMS       2
+#define WLAN_EID_DS_PARMS       3
+#define WLAN_EID_CF_PARMS       4
+#define WLAN_EID_TIM            5
+#define WLAN_EID_IBSS_PARMS     6
+#define WLAN_EID_COUNTRY        7
+#define WLAN_EID_CHALLENGE      16
+#define WLAN_EID_PWR_CONSTRAINT 32
+#define WLAN_EID_PWR_CAPABILITY 33
+#define WLAN_EID_TPC_REQ        34
+#define WLAN_EID_TPC_REP        35
+#define WLAN_EID_SUPP_CH        36
+#define WLAN_EID_CH_SWITCH      37
+#define WLAN_EID_MEASURE_REQ    38
+#define WLAN_EID_MEASURE_REP    39
+#define WLAN_EID_QUIET          40
+#define WLAN_EID_IBSS_DFS       41
+#define WLAN_EID_ERP            42
+// reference 802.11i 7.3.2 table 20
+#define WLAN_EID_RSN            48
+#define WLAN_EID_EXTSUPP_RATES  50
+// reference WiFi WPA spec.
+#define WLAN_EID_RSN_WPA        221
+
+
+#define WLAN_EID_ERP_NONERP_PRESENT             0x01
+#define WLAN_EID_ERP_USE_PROTECTION             0x02
+#define WLAN_EID_ERP_BARKER_MODE                0x04
+
+// Reason Codes
+#define WLAN_MGMT_REASON_RSVD                       0
+#define WLAN_MGMT_REASON_UNSPEC                     1
+#define WLAN_MGMT_REASON_PRIOR_AUTH_INVALID         2
+#define WLAN_MGMT_REASON_DEAUTH_LEAVING             3
+#define WLAN_MGMT_REASON_DISASSOC_INACTIVE          4
+#define WLAN_MGMT_REASON_DISASSOC_AP_BUSY           5
+#define WLAN_MGMT_REASON_CLASS2_NONAUTH             6
+#define WLAN_MGMT_REASON_CLASS3_NONASSOC            7
+#define WLAN_MGMT_REASON_DISASSOC_STA_HASLEFT       8
+#define WLAN_MGMT_REASON_CANT_ASSOC_NONAUTH         9
+#define WLAN_MGMT_REASON_DISASSOC_PWR_CAP_UNACCEPT      10
+#define WLAN_MGMT_REASON_DISASSOC_SUPP_CH_UNACCEPT      11
+#define WLAN_MGMT_REASON_INVALID_IE                 13
+#define WLAN_MGMT_REASON_MIC_FAILURE                14
+#define WLAN_MGMT_REASON_4WAY_HANDSHAKE_TIMEOUT     15
+#define WLAN_MGMT_REASON_GRPKEY_UPDATE_TIMEOUT      16
+#define WLAN_MGMT_REASON_4WAY_INFO_DIFFERENT        17
+#define WLAN_MGMT_REASON_MULTCAST_CIPHER_INVALID    18
+#define WLAN_MGMT_REASON_UNCAST_CIPHER_INVALID      19
+#define WLAN_MGMT_REASON_AKMP_INVALID               20
+#define WLAN_MGMT_REASON_RSNE_UNSUPPORTED           21
+#define WLAN_MGMT_REASON_RSNE_CAP_INVALID           22
+#define WLAN_MGMT_REASON_80211X_AUTH_FAILED         23
+
+// Status Codes
+#define WLAN_MGMT_STATUS_SUCCESS                        0
+#define WLAN_MGMT_STATUS_UNSPEC_FAILURE                 1
+#define WLAN_MGMT_STATUS_CAPS_UNSUPPORTED               10
+#define WLAN_MGMT_STATUS_REASSOC_NO_ASSOC               11
+#define WLAN_MGMT_STATUS_ASSOC_DENIED_UNSPEC            12
+#define WLAN_MGMT_STATUS_UNSUPPORTED_AUTHALG            13
+#define WLAN_MGMT_STATUS_RX_AUTH_NOSEQ                  14
+#define WLAN_MGMT_STATUS_CHALLENGE_FAIL                 15
+#define WLAN_MGMT_STATUS_AUTH_TIMEOUT                   16
+#define WLAN_MGMT_STATUS_ASSOC_DENIED_BUSY              17
+#define WLAN_MGMT_STATUS_ASSOC_DENIED_RATES             18
+#define WLAN_MGMT_STATUS_ASSOC_DENIED_SHORTPREAMBLE     19
+#define WLAN_MGMT_STATUS_ASSOC_DENIED_PBCC              20
+#define WLAN_MGMT_STATUS_ASSOC_DENIED_AGILITY           21
+
+// reference 802.11h 7.3.1.9
+//
+#define WLAN_MGMT_STATUS_ASSOC_REJECT_BCS_SPECTRUM_MNG  22
+#define WLAN_MGMT_STATUS_ASSOC_REJECT_BCS_PWR_CAP       23
+#define WLAN_MGMT_STATUS_ASSOC_REJECT_BCS_SUPP_CH       24
+//
+// reference 802.11g 7.3.1.9
+//
+#define WLAN_MGMT_STATUS_SHORTSLOTTIME_UNSUPPORTED      25
+#define WLAN_MGMT_STATUS_DSSSOFDM_UNSUPPORTED           26
+//
+// reference 802.11i 7.3.1.9 table 19
+//
+#define WLAN_MGMT_STATUS_INVALID_IE                     40
+#define WLAN_MGMT_STATUS_GROUP_CIPHER_INVALID           41
+#define WLAN_MGMT_STATUS_PAIRWISE_CIPHER_INVALID        42
+#define WLAN_MGMT_STATUS_AKMP_INVALID                   43
+#define WLAN_MGMT_STATUS_UNSUPPORT_RSN_IE_VER           44
+#define WLAN_MGMT_STATUS_INVALID_RSN_IE_CAP             45
+#define WLAN_MGMT_STATUS_CIPHER_REJECT                  46
+
+
+
+// Auth Algorithm
+#define WLAN_AUTH_ALG_OPENSYSTEM                0
+#define WLAN_AUTH_ALG_SHAREDKEY                 1
+
+
+
+// Management Frame Field Offsets
+// Note: Not all fields are listed because of variable lengths.
+// Note: These offsets are from the start of the frame data
+
+#define WLAN_BEACON_OFF_TS                  0
+#define WLAN_BEACON_OFF_BCN_INT             8
+#define WLAN_BEACON_OFF_CAPINFO             10
+#define WLAN_BEACON_OFF_SSID                12
+
+#define WLAN_DISASSOC_OFF_REASON            0
+
+#define WLAN_ASSOCREQ_OFF_CAP_INFO          0
+#define WLAN_ASSOCREQ_OFF_LISTEN_INT        2
+#define WLAN_ASSOCREQ_OFF_SSID              4
+
+#define WLAN_ASSOCRESP_OFF_CAP_INFO         0
+#define WLAN_ASSOCRESP_OFF_STATUS           2
+#define WLAN_ASSOCRESP_OFF_AID              4
+#define WLAN_ASSOCRESP_OFF_SUPP_RATES       6
+
+#define WLAN_REASSOCREQ_OFF_CAP_INFO        0
+#define WLAN_REASSOCREQ_OFF_LISTEN_INT      2
+#define WLAN_REASSOCREQ_OFF_CURR_AP         4
+#define WLAN_REASSOCREQ_OFF_SSID            10
+
+#define WLAN_REASSOCRESP_OFF_CAP_INFO       0
+#define WLAN_REASSOCRESP_OFF_STATUS         2
+#define WLAN_REASSOCRESP_OFF_AID            4
+#define WLAN_REASSOCRESP_OFF_SUPP_RATES     6
+
+#define WLAN_PROBEREQ_OFF_SSID              0
+
+#define WLAN_PROBERESP_OFF_TS               0
+#define WLAN_PROBERESP_OFF_BCN_INT          8
+#define WLAN_PROBERESP_OFF_CAP_INFO         10
+#define WLAN_PROBERESP_OFF_SSID             12
+
+#define WLAN_AUTHEN_OFF_AUTH_ALG            0
+#define WLAN_AUTHEN_OFF_AUTH_SEQ            2
+#define WLAN_AUTHEN_OFF_STATUS              4
+#define WLAN_AUTHEN_OFF_CHALLENGE           6
+
+#define WLAN_DEAUTHEN_OFF_REASON            0
+
+
+//
+// Cipher Suite Selectors defiened in 802.11i
+//
+#define WLAN_11i_CSS_USE_GROUP              0
+#define WLAN_11i_CSS_WEP40                  1
+#define WLAN_11i_CSS_TKIP                   2
+#define WLAN_11i_CSS_CCMP                   4
+#define WLAN_11i_CSS_WEP104                 5
+#define WLAN_11i_CSS_UNKNOWN                255
+
+//
+// Authentication and Key Management Suite Selectors defined in 802.11i
+//
+#define WLAN_11i_AKMSS_802_1X               1
+#define WLAN_11i_AKMSS_PSK                  2
+#define WLAN_11i_AKMSS_UNKNOWN              255
+
+// Measurement type definitions reference ieee 802.11h Table 20b
+#define MEASURE_TYPE_BASIC      0
+#define MEASURE_TYPE_CCA        1
+#define MEASURE_TYPE_RPI        2
+
+// Measurement request mode definitions reference ieee 802.11h Figure 46h
+#define MEASURE_MODE_ENABLE     0x02
+#define MEASURE_MODE_REQ        0x04
+#define MEASURE_MODE_REP        0x08
+
+// Measurement report mode definitions reference ieee 802.11h Figure 46m
+#define MEASURE_MODE_LATE       0x01
+#define MEASURE_MODE_INCAPABLE  0x02
+#define MEASURE_MODE_REFUSED    0x04
+
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Types  ------------------------------*/
+
+
+// Information Element Types
+
+#pragma pack(1)
+typedef struct tagWLAN_IE {
+    BYTE   byElementID;
+    BYTE   len;
+}__attribute__ ((__packed__))
+WLAN_IE, *PWLAN_IE;
+
+
+// Service Set Identity (SSID)
+#pragma pack(1)
+typedef struct tagWLAN_IE_SSID {
+    BYTE   byElementID;
+    BYTE   len;
+    BYTE   abySSID[1];
+}__attribute__ ((__packed__))
+WLAN_IE_SSID, *PWLAN_IE_SSID;
+
+
+// Supported Rates
+#pragma pack(1)
+typedef struct tagWLAN_IE_SUPP_RATES {
+    BYTE   byElementID;
+    BYTE   len;
+    BYTE   abyRates[1];
+}__attribute__ ((__packed__))
+WLAN_IE_SUPP_RATES,  *PWLAN_IE_SUPP_RATES;
+
+
+
+// FH Parameter Set
+#pragma pack(1)
+typedef struct _WLAN_IE_FH_PARMS {
+    BYTE    byElementID;
+    BYTE    len;
+    WORD    wDwellTime;
+    BYTE    byHopSet;
+    BYTE    byHopPattern;
+    BYTE    byHopIndex;
+} WLAN_IE_FH_PARMS,  *PWLAN_IE_FH_PARMS;
+
+
+// DS Parameter Set
+#pragma pack(1)
+typedef struct tagWLAN_IE_DS_PARMS {
+    BYTE   byElementID;
+    BYTE   len;
+    BYTE   byCurrChannel;
+}__attribute__ ((__packed__))
+WLAN_IE_DS_PARMS,  *PWLAN_IE_DS_PARMS;
+
+
+// CF Parameter Set
+#pragma pack(1)
+typedef struct tagWLAN_IE_CF_PARMS {
+    BYTE   byElementID;
+    BYTE   len;
+    BYTE   byCFPCount;
+    BYTE   byCFPPeriod;
+    WORD   wCFPMaxDuration;
+    WORD   wCFPDurRemaining;
+}__attribute__ ((__packed__))
+WLAN_IE_CF_PARMS,  *PWLAN_IE_CF_PARMS;
+
+
+// TIM
+#pragma pack(1)
+typedef struct tagWLAN_IE_TIM {
+    BYTE   byElementID;
+    BYTE   len;
+    BYTE   byDTIMCount;
+    BYTE   byDTIMPeriod;
+    BYTE   byBitMapCtl;
+    BYTE   byVirtBitMap[1];
+}__attribute__ ((__packed__))
+WLAN_IE_TIM,  *PWLAN_IE_TIM;
+
+
+// IBSS Parameter Set
+#pragma pack(1)
+typedef struct tagWLAN_IE_IBSS_PARMS {
+    BYTE   byElementID;
+    BYTE   len;
+    WORD   wATIMWindow;
+}__attribute__ ((__packed__))
+WLAN_IE_IBSS_PARMS, *PWLAN_IE_IBSS_PARMS;
+
+
+// Challenge Text
+#pragma pack(1)
+typedef struct tagWLAN_IE_CHALLENGE {
+    BYTE   byElementID;
+    BYTE   len;
+    BYTE   abyChallenge[1];
+}__attribute__ ((__packed__))
+WLAN_IE_CHALLENGE,  *PWLAN_IE_CHALLENGE;
+
+
+#pragma pack(1)
+typedef struct tagWLAN_IE_RSN_EXT {
+    BYTE byElementID;
+    BYTE len;
+    BYTE abyOUI[4];
+    WORD wVersion;
+    BYTE abyMulticast[4];
+    WORD wPKCount;
+    struct {
+        BYTE abyOUI[4];
+    } PKSList[1]; // the rest is variable so need to
+    // overlay ieauth structure
+} WLAN_IE_RSN_EXT, *PWLAN_IE_RSN_EXT;
+
+#pragma pack(1)
+typedef struct tagWLAN_IE_RSN_AUTH {
+    WORD wAuthCount;
+    struct {
+        BYTE abyOUI[4];
+    } AuthKSList[1];
+} WLAN_IE_RSN_AUTH, *PWLAN_IE_RSN_AUTH;
+
+// RSN Identity
+#pragma pack(1)
+typedef struct tagWLAN_IE_RSN {
+    BYTE   byElementID;
+    BYTE   len;
+    WORD   wVersion;
+    BYTE   abyRSN[WLAN_MIN_ARRAY];
+} WLAN_IE_RSN, *PWLAN_IE_RSN;
+
+
+// ERP
+#pragma pack(1)
+typedef struct tagWLAN_IE_ERP {
+    BYTE   byElementID;
+    BYTE   len;
+    BYTE   byContext;
+}__attribute__ ((__packed__))
+WLAN_IE_ERP,  *PWLAN_IE_ERP;
+
+
+#pragma pack(1)
+typedef struct _MEASEURE_REQ {
+    BYTE                byChannel;
+    BYTE                abyStartTime[8];
+    BYTE                abyDuration[2];
+} MEASEURE_REQ, *PMEASEURE_REQ,
+  MEASEURE_REQ_BASIC, *PMEASEURE_REQ_BASIC,
+  MEASEURE_REQ_CCA, *PMEASEURE_REQ_CCA,
+  MEASEURE_REQ_RPI, *PMEASEURE_REQ_RPI;
+
+typedef struct _MEASEURE_REP_BASIC {
+    BYTE                byChannel;
+    BYTE                abyStartTime[8];
+    BYTE                abyDuration[2];
+    BYTE                byMap;
+} MEASEURE_REP_BASIC, *PMEASEURE_REP_BASIC;
+
+typedef struct _MEASEURE_REP_CCA {
+    BYTE                byChannel;
+    BYTE                abyStartTime[8];
+    BYTE                abyDuration[2];
+    BYTE                byCCABusyFraction;
+} MEASEURE_REP_CCA, *PMEASEURE_REP_CCA;
+
+typedef struct _MEASEURE_REP_RPI {
+    BYTE                byChannel;
+    BYTE                abyStartTime[8];
+    BYTE                abyDuration[2];
+    BYTE                abyRPIdensity[8];
+} MEASEURE_REP_RPI, *PMEASEURE_REP_RPI;
+
+typedef union _MEASEURE_REP {
+
+    MEASEURE_REP_BASIC  sBasic;
+    MEASEURE_REP_CCA    sCCA;
+    MEASEURE_REP_RPI    sRPI;
+
+} MEASEURE_REP, *PMEASEURE_REP;
+
+typedef struct _WLAN_IE_MEASURE_REQ {
+    BYTE                byElementID;
+    BYTE                len;
+    BYTE                byToken;
+    BYTE                byMode;
+    BYTE                byType;
+    MEASEURE_REQ        sReq;
+} WLAN_IE_MEASURE_REQ, *PWLAN_IE_MEASURE_REQ;
+
+typedef struct _WLAN_IE_MEASURE_REP {
+    BYTE                byElementID;
+    BYTE                len;
+    BYTE                byToken;
+    BYTE                byMode;
+    BYTE                byType;
+    MEASEURE_REP        sRep;
+} WLAN_IE_MEASURE_REP, *PWLAN_IE_MEASURE_REP;
+
+typedef struct _WLAN_IE_CH_SW {
+    BYTE                byElementID;
+    BYTE                len;
+    BYTE                byMode;
+    BYTE                byChannel;
+    BYTE                byCount;
+} WLAN_IE_CH_SW, *PWLAN_IE_CH_SW;
+
+typedef struct _WLAN_IE_QUIET {
+    BYTE                byElementID;
+    BYTE                len;
+    BYTE                byQuietCount;
+    BYTE                byQuietPeriod;
+    BYTE                abyQuietDuration[2];
+    BYTE                abyQuietOffset[2];
+} WLAN_IE_QUIET, *PWLAN_IE_QUIET;
+
+typedef struct _WLAN_IE_COUNTRY {
+    BYTE                byElementID;
+    BYTE                len;
+    BYTE                abyCountryString[3];
+    BYTE                abyCountryInfo[3];
+} WLAN_IE_COUNTRY, *PWLAN_IE_COUNTRY;
+
+typedef struct _WLAN_IE_PW_CONST {
+    BYTE                byElementID;
+    BYTE                len;
+    BYTE                byPower;
+} WLAN_IE_PW_CONST, *PWLAN_IE_PW_CONST;
+
+typedef struct _WLAN_IE_PW_CAP {
+    BYTE                byElementID;
+    BYTE                len;
+    BYTE                byMinPower;
+    BYTE                byMaxPower;
+} WLAN_IE_PW_CAP, *PWLAN_IE_PW_CAP;
+
+typedef struct _WLAN_IE_SUPP_CH {
+    BYTE                byElementID;
+    BYTE                len;
+    BYTE                abyChannelTuple[2];
+} WLAN_IE_SUPP_CH, *PWLAN_IE_SUPP_CH;
+
+typedef struct _WLAN_IE_TPC_REQ {
+    BYTE                byElementID;
+    BYTE                len;
+} WLAN_IE_TPC_REQ, *PWLAN_IE_TPC_REQ;
+
+typedef struct _WLAN_IE_TPC_REP {
+    BYTE                byElementID;
+    BYTE                len;
+    BYTE                byTxPower;
+    BYTE                byLinkMargin;
+} WLAN_IE_TPC_REP, *PWLAN_IE_TPC_REP;
+
+
+typedef struct _WLAN_IE_IBSS_DFS {
+    BYTE                byElementID;
+    BYTE                len;
+    BYTE                abyDFSOwner[6];
+    BYTE                byDFSRecovery;
+    BYTE                abyChannelMap[2];
+} WLAN_IE_IBSS_DFS, *PWLAN_IE_IBSS_DFS;
+
+#pragma pack()
+
+
+
+// Frame Types
+// prototype structure, all mgmt frame types will start with these members
+typedef struct tagWLAN_FR_MGMT {
+
+    UINT                  uType;
+    UINT                  len;
+    PBYTE                 pBuf;
+    PUWLAN_80211HDR       pHdr;
+
+} WLAN_FR_MGMT,  *PWLAN_FR_MGMT;
+
+// Beacon frame
+typedef struct tagWLAN_FR_BEACON {
+
+    UINT                    uType;
+    UINT                    len;
+    PBYTE                   pBuf;
+    PUWLAN_80211HDR         pHdr;
+    // fixed fields
+    PQWORD                  pqwTimestamp;
+    PWORD                   pwBeaconInterval;
+    PWORD                   pwCapInfo;
+    /*-- info elements ----------*/
+    PWLAN_IE_SSID           pSSID;
+    PWLAN_IE_SUPP_RATES     pSuppRates;
+//  PWLAN_IE_FH_PARMS       pFHParms;
+    PWLAN_IE_DS_PARMS       pDSParms;
+    PWLAN_IE_CF_PARMS       pCFParms;
+    PWLAN_IE_TIM            pTIM;
+    PWLAN_IE_IBSS_PARMS     pIBSSParms;
+    PWLAN_IE_RSN            pRSN;
+    PWLAN_IE_RSN_EXT        pRSNWPA;
+    PWLAN_IE_ERP            pERP;
+    PWLAN_IE_SUPP_RATES     pExtSuppRates;
+    PWLAN_IE_COUNTRY        pIE_Country;
+    PWLAN_IE_PW_CONST       pIE_PowerConstraint;
+    PWLAN_IE_CH_SW          pIE_CHSW;
+    PWLAN_IE_IBSS_DFS       pIE_IBSSDFS;
+    PWLAN_IE_QUIET          pIE_Quiet;
+
+} WLAN_FR_BEACON, *PWLAN_FR_BEACON;
+
+
+// IBSS ATIM frame
+typedef struct tagWLAN_FR_IBSSATIM {
+
+    UINT                    uType;
+    UINT                    len;
+    PBYTE                   pBuf;
+    PUWLAN_80211HDR         pHdr;
+
+    // fixed fields
+    // info elements
+    // this frame type has a null body
+
+} WLAN_FR_IBSSATIM, *PWLAN_FR_IBSSATIM;
+
+// Disassociation
+typedef struct tagWLAN_FR_DISASSOC {
+
+    UINT                    uType;
+    UINT                    len;
+    PBYTE                   pBuf;
+    PUWLAN_80211HDR         pHdr;
+    /*-- fixed fields -----------*/
+    PWORD                   pwReason;
+    /*-- info elements ----------*/
+
+} WLAN_FR_DISASSOC, *PWLAN_FR_DISASSOC;
+
+// Association Request
+typedef struct tagWLAN_FR_ASSOCREQ {
+
+    UINT                    uType;
+    UINT                    len;
+    PBYTE                   pBuf;
+    PUWLAN_80211HDR         pHdr;
+    /*-- fixed fields -----------*/
+    PWORD                   pwCapInfo;
+    PWORD                   pwListenInterval;
+    /*-- info elements ----------*/
+    PWLAN_IE_SSID           pSSID;
+    PWLAN_IE_SUPP_RATES     pSuppRates;
+    PWLAN_IE_RSN            pRSN;
+    PWLAN_IE_RSN_EXT        pRSNWPA;
+    PWLAN_IE_SUPP_RATES     pExtSuppRates;
+    PWLAN_IE_PW_CAP         pCurrPowerCap;
+    PWLAN_IE_SUPP_CH        pCurrSuppCh;
+
+} WLAN_FR_ASSOCREQ, *PWLAN_FR_ASSOCREQ;
+
+// Association Response
+typedef struct tagWLAN_FR_ASSOCRESP {
+
+    UINT                    uType;
+    UINT                    len;
+    PBYTE                   pBuf;
+    PUWLAN_80211HDR         pHdr;
+    /*-- fixed fields -----------*/
+    PWORD                   pwCapInfo;
+    PWORD                   pwStatus;
+    PWORD                   pwAid;
+    /*-- info elements ----------*/
+    PWLAN_IE_SUPP_RATES     pSuppRates;
+    PWLAN_IE_SUPP_RATES     pExtSuppRates;
+
+} WLAN_FR_ASSOCRESP, *PWLAN_FR_ASSOCRESP;
+
+// Reassociation Request
+typedef struct tagWLAN_FR_REASSOCREQ {
+
+    UINT                    uType;
+    UINT                    len;
+    PBYTE                   pBuf;
+    PUWLAN_80211HDR         pHdr;
+
+    /*-- fixed fields -----------*/
+    PWORD                   pwCapInfo;
+    PWORD                   pwListenInterval;
+    PIEEE_ADDR              pAddrCurrAP;
+
+    /*-- info elements ----------*/
+    PWLAN_IE_SSID           pSSID;
+    PWLAN_IE_SUPP_RATES     pSuppRates;
+    PWLAN_IE_RSN            pRSN;
+    PWLAN_IE_RSN_EXT        pRSNWPA;
+    PWLAN_IE_SUPP_RATES     pExtSuppRates;
+
+} WLAN_FR_REASSOCREQ, *PWLAN_FR_REASSOCREQ;
+
+// Reassociation Response
+typedef struct tagWLAN_FR_REASSOCRESP {
+
+    UINT                    uType;
+    UINT                    len;
+    PBYTE                   pBuf;
+    PUWLAN_80211HDR         pHdr;
+    /*-- fixed fields -----------*/
+    PWORD                   pwCapInfo;
+    PWORD                   pwStatus;
+    PWORD                   pwAid;
+    /*-- info elements ----------*/
+    PWLAN_IE_SUPP_RATES     pSuppRates;
+    PWLAN_IE_SUPP_RATES     pExtSuppRates;
+
+} WLAN_FR_REASSOCRESP, *PWLAN_FR_REASSOCRESP;
+
+// Probe Request
+typedef struct tagWLAN_FR_PROBEREQ {
+
+    UINT                    uType;
+    UINT                    len;
+    PBYTE                   pBuf;
+    PUWLAN_80211HDR         pHdr;
+    /*-- fixed fields -----------*/
+    /*-- info elements ----------*/
+    PWLAN_IE_SSID           pSSID;
+    PWLAN_IE_SUPP_RATES     pSuppRates;
+    PWLAN_IE_SUPP_RATES     pExtSuppRates;
+
+} WLAN_FR_PROBEREQ, *PWLAN_FR_PROBEREQ;
+
+// Probe Response
+typedef struct tagWLAN_FR_PROBERESP {
+
+    UINT                    uType;
+    UINT                    len;
+    PBYTE                   pBuf;
+    PUWLAN_80211HDR         pHdr;
+    /*-- fixed fields -----------*/
+    PQWORD                  pqwTimestamp;
+    PWORD                   pwBeaconInterval;
+    PWORD                   pwCapInfo;
+    /*-- info elements ----------*/
+    PWLAN_IE_SSID           pSSID;
+    PWLAN_IE_SUPP_RATES     pSuppRates;
+    PWLAN_IE_DS_PARMS       pDSParms;
+    PWLAN_IE_CF_PARMS       pCFParms;
+    PWLAN_IE_IBSS_PARMS     pIBSSParms;
+    PWLAN_IE_RSN            pRSN;
+    PWLAN_IE_RSN_EXT        pRSNWPA;
+    PWLAN_IE_ERP            pERP;
+    PWLAN_IE_SUPP_RATES     pExtSuppRates;
+    PWLAN_IE_COUNTRY        pIE_Country;
+    PWLAN_IE_PW_CONST       pIE_PowerConstraint;
+    PWLAN_IE_CH_SW          pIE_CHSW;
+    PWLAN_IE_IBSS_DFS       pIE_IBSSDFS;
+    PWLAN_IE_QUIET          pIE_Quiet;
+
+} WLAN_FR_PROBERESP, *PWLAN_FR_PROBERESP;
+
+// Authentication
+typedef struct tagWLAN_FR_AUTHEN {
+
+    UINT                    uType;
+    UINT                    len;
+    PBYTE                   pBuf;
+    PUWLAN_80211HDR         pHdr;
+    /*-- fixed fields -----------*/
+    PWORD                   pwAuthAlgorithm;
+    PWORD                   pwAuthSequence;
+    PWORD                   pwStatus;
+    /*-- info elements ----------*/
+    PWLAN_IE_CHALLENGE      pChallenge;
+
+} WLAN_FR_AUTHEN, *PWLAN_FR_AUTHEN;
+
+// Deauthenication
+typedef struct tagWLAN_FR_DEAUTHEN {
+
+    UINT                    uType;
+    UINT                    len;
+    PBYTE                   pBuf;
+    PUWLAN_80211HDR         pHdr;
+    /*-- fixed fields -----------*/
+    PWORD                   pwReason;
+
+    /*-- info elements ----------*/
+
+} WLAN_FR_DEAUTHEN, *PWLAN_FR_DEAUTHEN;
+
+/*---------------------  Export Functions  --------------------------*/
+VOID
+vMgrEncodeBeacon(
+    IN  PWLAN_FR_BEACON  pFrame
+     );
+
+VOID
+vMgrDecodeBeacon(
+    IN  PWLAN_FR_BEACON  pFrame
+    );
+
+VOID
+vMgrEncodeIBSSATIM(
+    IN  PWLAN_FR_IBSSATIM   pFrame
+    );
+
+VOID
+vMgrDecodeIBSSATIM(
+    IN  PWLAN_FR_IBSSATIM   pFrame
+    );
+
+VOID
+vMgrEncodeDisassociation(
+    IN  PWLAN_FR_DISASSOC  pFrame
+    );
+
+VOID
+vMgrDecodeDisassociation(
+    IN  PWLAN_FR_DISASSOC  pFrame
+    );
+
+VOID
+vMgrEncodeAssocRequest(
+    IN  PWLAN_FR_ASSOCREQ  pFrame
+    );
+
+VOID
+vMgrDecodeAssocRequest(
+    IN  PWLAN_FR_ASSOCREQ  pFrame
+    );
+
+VOID
+vMgrEncodeAssocResponse(
+    IN  PWLAN_FR_ASSOCRESP  pFrame
+    );
+
+VOID
+vMgrDecodeAssocResponse(
+    IN PWLAN_FR_ASSOCRESP  pFrame
+    );
+
+VOID
+vMgrEncodeReassocRequest(
+    IN  PWLAN_FR_REASSOCREQ  pFrame
+    );
+
+VOID
+vMgrDecodeReassocRequest(
+    IN  PWLAN_FR_REASSOCREQ  pFrame
+    );
+
+VOID
+vMgrEncodeProbeRequest(
+    IN PWLAN_FR_PROBEREQ  pFrame
+    );
+
+VOID
+vMgrDecodeProbeRequest(
+    IN PWLAN_FR_PROBEREQ  pFrame
+    );
+
+VOID
+vMgrEncodeProbeResponse(
+    IN PWLAN_FR_PROBERESP  pFrame
+    );
+
+VOID
+vMgrDecodeProbeResponse(
+    IN PWLAN_FR_PROBERESP  pFrame
+    );
+
+VOID
+vMgrEncodeAuthen(
+    IN  PWLAN_FR_AUTHEN  pFrame
+    );
+
+VOID
+vMgrDecodeAuthen(
+    IN  PWLAN_FR_AUTHEN  pFrame
+    );
+
+VOID
+vMgrEncodeDeauthen(
+    IN  PWLAN_FR_DEAUTHEN  pFrame
+    );
+
+VOID
+vMgrDecodeDeauthen(
+    IN  PWLAN_FR_DEAUTHEN  pFrame
+    );
+
+VOID
+vMgrEncodeReassocResponse(
+    IN  PWLAN_FR_REASSOCRESP  pFrame
+    );
+
+VOID
+vMgrDecodeReassocResponse(
+    IN  PWLAN_FR_REASSOCRESP  pFrame
+    );
+
+#endif// __80211MGR_H__
diff --git a/drivers/staging/vt6655/IEEE11h.c b/drivers/staging/vt6655/IEEE11h.c
new file mode 100644
index 0000000..5f25b8e
--- /dev/null
+++ b/drivers/staging/vt6655/IEEE11h.c
@@ -0,0 +1,324 @@
+/*
+ * Copyright (c) 1996, 2005 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: IEEE11h.c
+ *
+ * Purpose:
+ *
+ * Functions:
+ *
+ * Revision History:
+ *
+ * Author: Yiching Chen
+ *
+ * Date: Mar. 31, 2005
+ *
+ */
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__IEEE11h_H__)
+#include "IEEE11h.h"
+#endif
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__WMGR_H__)
+#include "wmgr.h"
+#endif
+#if !defined(__RXTX_H__)
+#include "rxtx.h"
+#endif
+
+
+
+/*---------------------  Static Definitions -------------------------*/
+static int          msglevel                =MSG_LEVEL_INFO;
+
+#pragma pack(1)
+
+typedef struct _WLAN_FRAME_ACTION {
+    WLAN_80211HDR_A3    Header;
+    BYTE                byCategory;
+    BYTE                byAction;
+    BYTE                abyVars[1];
+} WLAN_FRAME_ACTION, *PWLAN_FRAME_ACTION;
+
+typedef struct _WLAN_FRAME_MSRREQ {
+    WLAN_80211HDR_A3    Header;
+    BYTE                byCategory;
+    BYTE                byAction;
+    BYTE                byDialogToken;
+    WLAN_IE_MEASURE_REQ sMSRReqEIDs[1];
+} WLAN_FRAME_MSRREQ, *PWLAN_FRAME_MSRREQ;
+
+typedef struct _WLAN_FRAME_MSRREP {
+    WLAN_80211HDR_A3    Header;
+    BYTE                byCategory;
+    BYTE                byAction;
+    BYTE                byDialogToken;
+    WLAN_IE_MEASURE_REP sMSRRepEIDs[1];
+} WLAN_FRAME_MSRREP, *PWLAN_FRAME_MSRREP;
+
+typedef struct _WLAN_FRAME_TPCREQ {
+    WLAN_80211HDR_A3    Header;
+    BYTE                byCategory;
+    BYTE                byAction;
+    BYTE                byDialogToken;
+    WLAN_IE_TPC_REQ     sTPCReqEIDs;
+} WLAN_FRAME_TPCREQ, *PWLAN_FRAME_TPCREQ;
+
+typedef struct _WLAN_FRAME_TPCREP {
+    WLAN_80211HDR_A3    Header;
+    BYTE                byCategory;
+    BYTE                byAction;
+    BYTE                byDialogToken;
+    WLAN_IE_TPC_REP     sTPCRepEIDs;
+} WLAN_FRAME_TPCREP, *PWLAN_FRAME_TPCREP;
+
+#pragma pack()
+
+// action field reference ieee 802.11h Table 20e
+#define ACTION_MSRREQ       0
+#define ACTION_MSRREP       1
+#define ACTION_TPCREQ       2
+#define ACTION_TPCREP       3
+#define ACTION_CHSW         4
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+/*---------------------  Static Functions  --------------------------*/
+static BOOL s_bRxMSRReq(PSMgmtObject pMgmt, PWLAN_FRAME_MSRREQ pMSRReq, UINT uLength)
+{
+    UINT    uNumOfEIDs = 0;
+    BOOL    bResult = TRUE;
+
+    if (uLength <= WLAN_A3FR_MAXLEN) {
+        MEMvCopy(pMgmt->abyCurrentMSRReq, pMSRReq, uLength);
+    }
+    uNumOfEIDs = ((uLength - OFFSET(WLAN_FRAME_MSRREQ, sMSRReqEIDs))/ (sizeof(WLAN_IE_MEASURE_REQ)));
+    pMgmt->pCurrMeasureEIDRep = &(((PWLAN_FRAME_MSRREP) (pMgmt->abyCurrentMSRRep))->sMSRRepEIDs[0]);
+    pMgmt->uLengthOfRepEIDs = 0;
+    bResult = CARDbStartMeasure(pMgmt->pAdapter,
+                                ((PWLAN_FRAME_MSRREQ) (pMgmt->abyCurrentMSRReq))->sMSRReqEIDs,
+                                uNumOfEIDs
+                                );
+    return (bResult);
+}
+
+
+static BOOL s_bRxTPCReq(PSMgmtObject pMgmt, PWLAN_FRAME_TPCREQ pTPCReq, BYTE byRate, BYTE byRSSI)
+{
+    PWLAN_FRAME_TPCREP  pFrame;
+    PSTxMgmtPacket      pTxPacket = NULL;
+
+
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_A3FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+
+    pFrame = (PWLAN_FRAME_TPCREP)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+
+    pFrame->Header.wFrameCtl = (   WLAN_SET_FC_FTYPE(WLAN_FTYPE_MGMT) |
+                                    WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_ACTION)
+                                );
+
+    MEMvCopy( pFrame->Header.abyAddr1, pTPCReq->Header.abyAddr2, WLAN_ADDR_LEN);
+    MEMvCopy( pFrame->Header.abyAddr2, CARDpGetCurrentAddress(pMgmt->pAdapter), WLAN_ADDR_LEN);
+    MEMvCopy( pFrame->Header.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+
+    pFrame->byCategory = 0;
+    pFrame->byAction = 3;
+    pFrame->byDialogToken = ((PWLAN_FRAME_MSRREQ) (pMgmt->abyCurrentMSRReq))->byDialogToken;
+
+    pFrame->sTPCRepEIDs.byElementID = WLAN_EID_TPC_REP;
+    pFrame->sTPCRepEIDs.len = 2;
+    pFrame->sTPCRepEIDs.byTxPower = CARDbyGetTransmitPower(pMgmt->pAdapter);
+    switch (byRate) {
+        case RATE_54M:
+            pFrame->sTPCRepEIDs.byLinkMargin = 65 - byRSSI;
+            break;
+        case RATE_48M:
+            pFrame->sTPCRepEIDs.byLinkMargin = 66 - byRSSI;
+            break;
+        case RATE_36M:
+            pFrame->sTPCRepEIDs.byLinkMargin = 70 - byRSSI;
+            break;
+        case RATE_24M:
+            pFrame->sTPCRepEIDs.byLinkMargin = 74 - byRSSI;
+            break;
+        case RATE_18M:
+            pFrame->sTPCRepEIDs.byLinkMargin = 77 - byRSSI;
+            break;
+        case RATE_12M:
+            pFrame->sTPCRepEIDs.byLinkMargin = 79 - byRSSI;
+            break;
+        case RATE_9M:
+            pFrame->sTPCRepEIDs.byLinkMargin = 81 - byRSSI;
+            break;
+        case RATE_6M:
+        default:
+            pFrame->sTPCRepEIDs.byLinkMargin = 82 - byRSSI;
+            break;
+    }
+
+    pTxPacket->cbMPDULen = sizeof(WLAN_FRAME_TPCREP);
+    pTxPacket->cbPayloadLen = sizeof(WLAN_FRAME_TPCREP) - WLAN_HDR_ADDR3_LEN;
+    if (csMgmt_xmit(pMgmt->pAdapter, pTxPacket) != CMD_STATUS_PENDING)
+        return (FALSE);
+    return (TRUE);
+//    return (CARDbSendPacket(pMgmt->pAdapter, pFrame, PKT_TYPE_802_11_MNG, sizeof(WLAN_FRAME_TPCREP)));
+
+}
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+/*+
+ *
+ * Description:
+ *      Handles action management frames.
+ *
+ * Parameters:
+ *  In:
+ *      pMgmt           - Management Object structure
+ *      pRxPacket       - Received packet
+ *  Out:
+ *      none
+ *
+ * Return Value: None.
+ *
+-*/
+BOOL
+IEEE11hbMgrRxAction (
+    IN PVOID pMgmtHandle,
+    IN PVOID pRxPacket
+    )
+{
+    PSMgmtObject            pMgmt = (PSMgmtObject) pMgmtHandle;
+    PWLAN_FRAME_ACTION      pAction = NULL;
+    UINT                    uLength = 0;
+    PWLAN_IE_CH_SW          pChannelSwitch = NULL;
+
+
+    // decode the frame
+    uLength = ((PSRxMgmtPacket)pRxPacket)->cbMPDULen;
+    if (uLength > WLAN_A3FR_MAXLEN) {
+        return (FALSE);
+    }
+
+
+    pAction = (PWLAN_FRAME_ACTION) (((PSRxMgmtPacket)pRxPacket)->p80211Header);
+
+    if (pAction->byCategory == 0) {
+        switch (pAction->byAction) {
+            case ACTION_MSRREQ:
+                return (s_bRxMSRReq(pMgmt, (PWLAN_FRAME_MSRREQ) pAction, uLength));
+                break;
+            case ACTION_MSRREP:
+                break;
+            case ACTION_TPCREQ:
+                return (s_bRxTPCReq(pMgmt,
+                                    (PWLAN_FRAME_TPCREQ) pAction,
+                                    ((PSRxMgmtPacket)pRxPacket)->byRxRate,
+                                    (BYTE) ((PSRxMgmtPacket)pRxPacket)->uRSSI));
+                break;
+            case ACTION_TPCREP:
+                break;
+            case ACTION_CHSW:
+                pChannelSwitch = (PWLAN_IE_CH_SW) (pAction->abyVars);
+                if ((pChannelSwitch->byElementID == WLAN_EID_CH_SWITCH) &&
+                    (pChannelSwitch->len == 3)) {
+                    // valid element id
+                    CARDbChannelSwitch( pMgmt->pAdapter,
+                                        pChannelSwitch->byMode,
+                                        CARDbyGetChannelMapping(pMgmt->pAdapter, pChannelSwitch->byChannel, pMgmt->eCurrentPHYMode),
+                                        pChannelSwitch->byCount
+                                        );
+                }
+                break;
+            default:
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Unknown Action = %d\n", pAction->byAction);
+                break;
+        }
+    } else {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Unknown Category = %d\n", pAction->byCategory);
+        pAction->byCategory |= 0x80;
+
+       //return (CARDbSendPacket(pMgmt->pAdapter, pAction, PKT_TYPE_802_11_MNG, uLength));
+        return (TRUE);
+    }
+    return (TRUE);
+}
+
+
+BOOL IEEE11hbMSRRepTx (
+    IN PVOID pMgmtHandle
+    )
+{
+    PSMgmtObject            pMgmt = (PSMgmtObject) pMgmtHandle;
+    PWLAN_FRAME_MSRREP      pMSRRep = (PWLAN_FRAME_MSRREP) (pMgmt->abyCurrentMSRRep + sizeof(STxMgmtPacket));
+    UINT                    uLength = 0;
+    PSTxMgmtPacket          pTxPacket = NULL;
+
+    pTxPacket = (PSTxMgmtPacket)pMgmt->abyCurrentMSRRep;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_A3FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+
+
+    pMSRRep->Header.wFrameCtl = (   WLAN_SET_FC_FTYPE(WLAN_FTYPE_MGMT) |
+                                    WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_ACTION)
+                                );
+
+    MEMvCopy( pMSRRep->Header.abyAddr1, ((PWLAN_FRAME_MSRREQ) (pMgmt->abyCurrentMSRReq))->Header.abyAddr2, WLAN_ADDR_LEN);
+    MEMvCopy( pMSRRep->Header.abyAddr2, CARDpGetCurrentAddress(pMgmt->pAdapter), WLAN_ADDR_LEN);
+    MEMvCopy( pMSRRep->Header.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+
+    pMSRRep->byCategory = 0;
+    pMSRRep->byAction = 1;
+    pMSRRep->byDialogToken = ((PWLAN_FRAME_MSRREQ) (pMgmt->abyCurrentMSRReq))->byDialogToken;
+
+    uLength = pMgmt->uLengthOfRepEIDs + OFFSET(WLAN_FRAME_MSRREP, sMSRRepEIDs);
+
+    pTxPacket->cbMPDULen = uLength;
+    pTxPacket->cbPayloadLen = uLength - WLAN_HDR_ADDR3_LEN;
+    if (csMgmt_xmit(pMgmt->pAdapter, pTxPacket) != CMD_STATUS_PENDING)
+        return (FALSE);
+    return (TRUE);
+//    return (CARDbSendPacket(pMgmt->pAdapter, pMSRRep, PKT_TYPE_802_11_MNG, uLength));
+
+}
+
diff --git a/drivers/staging/vt6655/IEEE11h.h b/drivers/staging/vt6655/IEEE11h.h
new file mode 100644
index 0000000..22bcaf1
--- /dev/null
+++ b/drivers/staging/vt6655/IEEE11h.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 1996, 2005 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: IEEE11h.h
+ *
+ * Purpose: Defines the macros, types, and functions for dealing
+ *          with IEEE 802.11h.
+ *
+ * Author: Yiching Chen
+ *
+ * Date: Mar. 31, 2005
+ *
+ */
+
+#ifndef __IEEE11h_H__
+#define __IEEE11h_H__
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+#if !defined(__80211MGR_H__)
+#include "80211mgr.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Types  ------------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+BOOL IEEE11hbMSRRepTx (
+    IN PVOID pMgmtHandle
+    );
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+#endif // __IEEE11h_H__
diff --git a/drivers/staging/vt6655/Kconfig b/drivers/staging/vt6655/Kconfig
new file mode 100644
index 0000000..a01b1e4
--- /dev/null
+++ b/drivers/staging/vt6655/Kconfig
@@ -0,0 +1,6 @@
+config VT6655
+   tristate "VIA Technologies VT6655 support"
+   depends on PCI
+   ---help---
+   This is a vendor-written driver for VIA VT6655.
+
diff --git a/drivers/staging/vt6655/Makefile b/drivers/staging/vt6655/Makefile
new file mode 100644
index 0000000..7d76e7e
--- /dev/null
+++ b/drivers/staging/vt6655/Makefile
@@ -0,0 +1,38 @@
+# TODO: all of these should be removed
+EXTRA_CFLAGS += -DLINUX -D__KERNEL__ -DMODULE  -DEXPORT_SYMTAB -D__NO_VERSION__
+EXTRA_CFLAGS += -DHOSTAP
+
+vt6655-y +=	device_main.o \
+	card.o \
+	mac.o \
+	baseband.o \
+	wctl.o \
+	80211mgr.o \
+	wcmd.o \
+	wmgr.o \
+	bssdb.o \
+	rxtx.o \
+	dpc.o \
+	power.o \
+	datarate.o \
+	srom.o \
+	mib.o \
+	rc4.o \
+	tether.o \
+	tcrc.o \
+	ioctl.o \
+	hostap.o \
+	wpa.o \
+	key.o \
+	tkip.o \
+	michael.o \
+	wroute.o \
+	rf.o \
+	iwctl.o \
+	wpactl.o \
+	wpa2.o \
+	aes_ccmp.o \
+	vntwifi.o \
+	IEEE11h.o
+
+obj-$(CONFIG_VT6655) +=	vt6655.o
diff --git a/drivers/staging/vt6655/Makefile.arm b/drivers/staging/vt6655/Makefile.arm
new file mode 100644
index 0000000..2d2ccad
--- /dev/null
+++ b/drivers/staging/vt6655/Makefile.arm
@@ -0,0 +1,181 @@
+#
+#
+# Build options:
+#   PRIV_OBJ   := 1 for object version
+#   BIG_ENDIAN := 1 for big-endian mode
+#
+#   arm-linux-tools chain are located at:
+#     /usr/local/bin/arm-linux-gcc
+#     /usr/local/bin/arm-linux-ld
+#
+
+IO_MAP := 0
+HOSTAP := 1
+PRIV_OBJ := 1
+BIG_ENDIAN := 1
+
+test_dir = $(shell [ -e $(dir)/include/linux ] && echo $(dir))
+KSP := $(foreach dir, $(KSP), $(test_dir))
+
+KSRC := $(firstword $(KSP))
+
+#ifeq (,$(KSRC))
+#  $(error Linux kernel source not found)
+#endif
+
+# check kernel version
+KVER := $(shell uname -r | cut -c1-3 | sed 's/2\.[56]/2\.6/')
+KERVER2=$(shell uname -r | cut -d. -f2)
+
+ifeq ($(KVER), 2.6)
+# 2.6 kernel
+TARGET = viawget.ko
+
+else
+TARGET = viawget.o
+
+endif
+
+INSTDIR	:= $(shell find /lib/modules/$(shell uname -r) -name $(TARGET) -printf "%h\n" | sort | head -1)
+ifeq (,$(INSTDIR))
+	ifeq (,$(KERVER2))
+		ifneq (,$(wildcard /lib/modules/$(shell uname -r)/kernel))
+			INSTDIR := /lib/modules/$(shell uname -r)/kernel/drivers/net
+		else
+			INSTDIR := /lib/modules/$(shell uname -r)/net
+		endif
+	else
+		ifneq ($(KERVER2),2)
+			INSTDIR := /lib/modules/$(shell uname -r)/kernel/drivers/net
+		else
+			INSTDIR := /lib/modules/$(shell uname -r)/net
+		endif
+	endif
+endif
+
+
+SRC = device_main.c card.c mac.c baseband.c wctl.c 80211mgr.c \
+      wcmd.c wmgr.c bssdb.c rxtx.c dpc.c power.c datarate.c srom.c \
+      mib.c rc4.c tether.c tcrc.c ioctl.c hostap.c wpa.c key.c tkip.c \
+      michael.c wroute.c rf.c iwctl.c wpactl.c wpa2.c aes_ccmp.c
+
+ifeq ($(IO_MAP), 1)
+  CFLAGS += -DIO_MAP
+endif
+
+ifeq ($(HOSTAP), 1)
+  CFLAGS += -DHOSTAP
+endif
+
+ifeq ($(PRIV_OBJ), 1)
+  CFLAGS += -DPRIVATE_OBJ
+endif
+
+ifeq ($(BIG_ENDIAN), 1)
+  CFLAGS += -D__BIG_ENDIAN
+  CFLAGS += -mbig-endian
+  LDOPTS += -EB
+else
+  CFLAGS += -mlittle-endian
+  LDOPTS += -EL
+endif
+
+CFLAGS += -I$(PWD) -I$(PWD)/../include -I$(PWD)/../solomon
+
+
+# build rule
+ifeq ($(KVER), 2.6)
+# 2.6 kernel
+
+ifndef KERNEL_CONF
+KERNEL_CONF=	$(KSRC)/.config
+endif
+
+include ${KERNEL_CONF}
+
+obj-m += viawget.o
+
+viawget-objs :=	device_main.o card.o mac.o baseband.o wctl.o 80211mgr.o \
+	wcmd.o wmgr.o bssdb.o rxtx.o dpc.o power.o datarate.o srom.o \
+	mib.o rc4.o tether.o tcrc.o ioctl.o hostap.o wpa.o key.o tkip.o \
+	michael.o wroute.o rf.o iwctl.o wpactl.o wpa2.o aes_ccmp.o
+
+.c.o:
+	$(CC) $(CFLAGS) -o $@ $<
+
+default:
+	make -C $(KSRC) SUBDIRS=$(shell pwd) modules
+
+else
+
+# 2.2/2.4 kernel
+OBJS :=	device_main.o card.o mac.o baseband.o wctl.o 80211mgr.o \
+	wcmd.o wmgr.o bssdb.o rxtx.o dpc.o power.o datarate.o srom.o \
+	mib.o rc4.o tether.o tcrc.o ioctl.o hostap.o wpa.o key.o tkip.o \
+	michael.o wroute.o rf.o iwctl.o wpactl.o wpa2.o
+
+
+CC := /usr/local/bin/arm-linux-gcc
+LD := /usr/local/bin/arm-linux-ld
+
+CFLAGS += -Wall -DLINUX -D__KERNEL__ -DMODULE  -DEXPORT_SYMTAB -D__NO_VERSION__ -O2 -pipe
+#CFLAGS += -Wstrict-prototypes -fomit-frame-pointer
+COPTS+= -march=armv4 -fno-strict-aliasing -fno-common
+#COPTS+= -mapcs-32 -mtune=xscale  -mshort-load-bytes -msoft-float -mfp=2
+#COPTS+= -mthumb  -mcpu=arm9 -ffunction-sections -fdata-sections
+
+
+.SILENT: $(TARGET) clean
+
+
+
+ifeq ($(PRIV_OBJ), 1)
+
+ifeq ($(BIG_ENDIAN), 1)
+  TARGET = arm_be_g.o
+else
+  TARGET = arm_le_g.o
+endif
+
+endif
+
+
+
+$(TARGET): $(filter-out $(TARGET), $(SRC:.c=.o))
+	$(LD) $(LDOPTS) -r $^ -o $@
+	echo
+	echo "***********************************"
+	echo "Build options:"
+	echo "   VERSION    $(KVER)"
+	echo -n "   SMP             "
+	if [ "$(SMP)" = "1" ]; \
+		then echo "Enabled"; else echo "Disabled"; fi
+
+
+endif # ifeq ($(KVER),2.6)
+
+
+ifeq ($(KVER), 2.6)
+install: default
+else
+install: clean $(TARGET)
+endif
+	mkdir -p $(MOD_ROOT)$(INSTDIR)
+	install -m 644 -o root $(TARGET) $(MOD_ROOT)$(INSTDIR)
+
+ifeq (,$(MOD_ROOT))
+	/sbin/depmod -a || true
+else
+	/sbin/depmod -b $(MOD_ROOT) -a || true
+endif
+
+
+uninstall:
+	rm -f $(INSTDIR)/$(TARGET)
+	/sbin/depmod -a
+
+clean:
+	rm -f $(TARGET) $(SRC:.c=.o) *~
+	rm -f .*.o.d .*.o.cmd .*.ko.cmd *.mod.c *.mod.o
+
+-include .depend.mak
diff --git a/drivers/staging/vt6655/Makefile.x86 b/drivers/staging/vt6655/Makefile.x86
new file mode 100644
index 0000000..69082f0
--- /dev/null
+++ b/drivers/staging/vt6655/Makefile.x86
@@ -0,0 +1,209 @@
+#
+# Build options:
+#   PRIV_OBJ := 1 for object version
+#
+
+IO_MAP := 0
+HOSTAP := 1
+PRIV_OBJ := 1
+
+KSP :=  /lib/modules/$(shell uname -r)/build \
+	/usr/src/linux-$(shell uname -r) \
+	/usr/src/linux-$(shell uname -r | sed 's/-.*//') \
+	/usr/src/kernel-headers-$(shell uname -r) \
+	/usr/src/kernel-source-$(shell uname -r) \
+	/usr/src/linux-$(shell uname -r | sed 's/\([0-9]*\.[0-9]*\)\..*/\1/') \
+	/usr/src/linux
+
+test_dir = $(shell [ -e $(dir)/include/linux ] && echo $(dir))
+KSP := $(foreach dir, $(KSP), $(test_dir))
+
+KSRC := $(firstword $(KSP))
+
+ifeq (,$(KSRC))
+  $(error Linux kernel source not found)
+endif
+
+# check kernel version
+KVER := $(shell uname -r | cut -c1-3 | sed 's/2\.[56]/2\.6/')
+KERVER2=$(shell uname -r | cut -d. -f2)
+
+ifeq ($(KVER), 2.6)
+# 2.6 kernel
+TARGET = viawget.ko
+
+else
+TARGET = viawget.o
+
+endif
+
+INSTDIR	:= $(shell find /lib/modules/$(shell uname -r) -name $(TARGET) -printf "%h\n" | sort | head -1)
+ifeq (,$(INSTDIR))
+	ifeq (,$(KERVER2))
+		ifneq (,$(wildcard /lib/modules/$(shell uname -r)/kernel))
+			INSTDIR := /lib/modules/$(shell uname -r)/kernel/drivers/net
+		else
+			INSTDIR := /lib/modules/$(shell uname -r)/net
+		endif
+	else
+		ifneq ($(KERVER2),2)
+			INSTDIR := /lib/modules/$(shell uname -r)/kernel/drivers/net
+		else
+			INSTDIR := /lib/modules/$(shell uname -r)/net
+		endif
+	endif
+endif
+
+
+SRC = device_main.c card.c mac.c baseband.c wctl.c 80211mgr.c \
+      wcmd.c wmgr.c bssdb.c  wpa2.c rxtx.c dpc.c power.c datarate.c \
+      srom.c mib.c rc4.c tether.c tcrc.c ioctl.c hostap.c wpa.c key.c \
+      tkip.c michael.c wroute.c rf.c iwctl.c wpactl.c aes_ccmp.c
+
+ifeq ($(IO_MAP), 1)
+  CFLAGS += -DIO_MAP
+endif
+
+ifeq ($(HOSTAP), 1)
+  CFLAGS += -DHOSTAP
+endif
+
+ifeq ($(PRIV_OBJ), 1)
+  CFLAGS += -DPRIVATE_OBJ
+endif
+
+CFLAGS += -I$(PWD) -I$(PWD)/../include -I$(PWD)/../solomon
+
+
+# build rule
+ifeq ($(KVER), 2.6)
+# 2.6 kernel
+
+ifndef KERNEL_CONF
+KERNEL_CONF=	$(KSRC)/.config
+endif
+
+include ${KERNEL_CONF}
+
+obj-m += viawget.o
+
+viawget-objs :=	device_main.o card.o mac.o baseband.o wctl.o 80211mgr.o \
+	wcmd.o wmgr.o bssdb.o rxtx.o dpc.o power.o datarate.o srom.o \
+	mib.o rc4.o tether.o tcrc.o ioctl.o hostap.o wpa.o key.o tkip.o \
+	michael.o wroute.o rf.o iwctl.o wpactl.o wpa2.o aes_ccmp.o
+
+.c.o:
+	$(CC) $(CFLAGS) -o $@ $<
+
+default:
+	make -C $(KSRC) SUBDIRS=$(shell pwd) modules
+
+else
+
+# 2.2/2.4 kernel
+OBJS :=	device_main.o card.o mac.o baseband.o wctl.o 80211mgr.o \
+	wcmd.o wmgr.o bssdb.o rxtx.o dpc.o power.o datarate.o srom.o \
+	mib.o rc4.o tether.o tcrc.o ioctl.o hostap.o wpa.o key.o tkip.o \
+	michael.o wroute.o rf.o iwctl.o wpactl.o wpa2.o aes_ccmp.o
+
+VERSION_FILE := $(KSRC)/include/linux/version.h
+CONFIG_FILE  := $(KSRC)/include/linux/config.h
+
+
+ifeq (,$(wildcard $(VERSION_FILE)))
+  $(error Linux kernel source not configured - missing version.h)
+endif
+
+ifeq (,$(wildcard $(CONFIG_FILE)))
+  $(error Linux kernel source not configured - missing config.h)
+endif
+
+ifneq (,$(findstring egcs-2.91.66, $(shell cat /proc/version)))
+  CC := kgcc gcc cc
+else
+  CC := gcc cc
+endif
+
+test_cc = $(shell which $(cc) > /dev/null 2>&1 && echo $(cc))
+CC := $(foreach cc, $(CC), $(test_cc))
+CC := $(firstword $(CC))
+
+CFLAGS += -Wall -DLINUX -D__KERNEL__ -DMODULE  -DEXPORT_SYMTAB -D__NO_VERSION__ -O2 -pipe
+CFLAGS += -I$(KSRC)/include -Wstrict-prototypes -fomit-frame-pointer
+CFLAGS += $(shell [ -f $(KSRC)/include/linux/modversions.h ] && \
+            echo "-DMODVERSIONS -include $(KSRC)/include/linux/modversions.h")
+
+.SILENT: $(TARGET) clean
+
+
+# look for SMP in config.h
+SMP := $(shell $(CC) $(CFLAGS) -E -dM $(CONFIG_FILE) | \
+         grep CONFIG_SMP | awk '{ print $$3 }')
+
+ifneq ($(SMP),1)
+  SMP := 0
+endif
+
+
+ifeq ($(SMP), 1)
+  CFLAGS += -D__SMP__
+endif
+
+
+ifeq ($(PRIV_OBJ), 1)
+  CFLAGS += -DPRIVATE_OBJ
+  TARGET = x86g_up.o
+
+ifeq ($(SMP), 1)
+  TARGET = x86g_smp.o
+endif
+
+endif
+
+
+# check x86_64
+SUBARCH := $(shell uname -m)
+ifeq ($(SUBARCH),x86_64)
+    CFLAGS += -mcmodel=kernel -mno-red-zone
+endif
+
+
+$(TARGET): $(filter-out $(TARGET), $(SRC:.c=.o))
+	$(LD) -r $^ -o $@
+	echo; echo
+	echo "**************************************************"
+	echo "Build options:"
+	echo "   VERSION    $(KVER)"
+	echo -n "   SMP             "
+	if [ "$(SMP)" = "1" ]; \
+		then echo "Enabled"; else echo "Disabled"; fi
+
+
+
+endif # ifeq ($(KVER),2.6)
+
+
+ifeq ($(KVER), 2.6)
+install: default
+else
+install: clean $(TARGET)
+endif
+	mkdir -p $(MOD_ROOT)$(INSTDIR)
+	install -m 644 -o root $(TARGET) $(MOD_ROOT)$(INSTDIR)
+
+ifeq (,$(MOD_ROOT))
+	/sbin/depmod -a || true
+else
+	/sbin/depmod -b $(MOD_ROOT) -a || true
+endif
+
+
+uninstall:
+	rm -f $(INSTDIR)/$(TARGET)
+	/sbin/depmod -a
+
+clean:
+	rm -f $(TARGET) $(SRC:.c=.o) *~
+	rm -f .*.o.d .*.o.cmd .*.ko.cmd *.mod.c *.mod.o
+
+-include .depend.mak
diff --git a/drivers/staging/vt6655/aes_ccmp.c b/drivers/staging/vt6655/aes_ccmp.c
new file mode 100644
index 0000000..59cc018
--- /dev/null
+++ b/drivers/staging/vt6655/aes_ccmp.c
@@ -0,0 +1,410 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: aes_ccmp.c
+ *
+ * Purpose: AES_CCMP decryption
+ *
+ * Author: Warren Hsu
+ *
+ * Date: Feb 15, 2005
+ *
+ * Functions:
+ *      AESbGenCCMP - Parsing RX-packet
+ *
+ *
+ * Revision History:
+ *
+ */
+
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+/*
+ * SBOX Table
+ */
+
+BYTE sbox_table[256] =
+{
+0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
+0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
+0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
+0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
+0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
+0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
+0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
+0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
+0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
+0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
+0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
+0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
+0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
+0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
+0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
+0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
+};
+
+BYTE dot2_table[256] = {
+0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e,
+0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e,
+0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e,
+0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e,
+0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e,
+0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe,
+0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde,
+0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe,
+0x1b, 0x19, 0x1f, 0x1d, 0x13, 0x11, 0x17, 0x15, 0x0b, 0x09, 0x0f, 0x0d, 0x03, 0x01, 0x07, 0x05,
+0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31, 0x37, 0x35, 0x2b, 0x29, 0x2f, 0x2d, 0x23, 0x21, 0x27, 0x25,
+0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51, 0x57, 0x55, 0x4b, 0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, 0x45,
+0x7b, 0x79, 0x7f, 0x7d, 0x73, 0x71, 0x77, 0x75, 0x6b, 0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65,
+0x9b, 0x99, 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85,
+0xbb, 0xb9, 0xbf, 0xbd, 0xb3, 0xb1, 0xb7, 0xb5, 0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5,
+0xdb, 0xd9, 0xdf, 0xdd, 0xd3, 0xd1, 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5,
+0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5, 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5
+};
+
+BYTE dot3_table[256] = {
+0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17, 0x12, 0x11,
+0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39, 0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, 0x21,
+0x60, 0x63, 0x66, 0x65, 0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71,
+0x50, 0x53, 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d, 0x44, 0x47, 0x42, 0x41,
+0xc0, 0xc3, 0xc6, 0xc5, 0xcc, 0xcf, 0xca, 0xc9, 0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1,
+0xf0, 0xf3, 0xf6, 0xf5, 0xfc, 0xff, 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1,
+0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, 0xa9, 0xb8, 0xbb, 0xbe, 0xbd, 0xb4, 0xb7, 0xb2, 0xb1,
+0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99, 0x88, 0x8b, 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81,
+0x9b, 0x98, 0x9d, 0x9e, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86, 0x8f, 0x8c, 0x89, 0x8a,
+0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6, 0xbf, 0xbc, 0xb9, 0xba,
+0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2, 0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, 0xea,
+0xcb, 0xc8, 0xcd, 0xce, 0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda,
+0x5b, 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a,
+0x6b, 0x68, 0x6d, 0x6e, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a,
+0x3b, 0x38, 0x3d, 0x3e, 0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a,
+0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a
+};
+
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+void xor_128(BYTE *a, BYTE *b, BYTE *out)
+{
+PDWORD dwPtrA = (PDWORD) a;
+PDWORD dwPtrB = (PDWORD) b;
+PDWORD dwPtrOut =(PDWORD) out;
+
+    (*dwPtrOut++) = (*dwPtrA++) ^ (*dwPtrB++);
+    (*dwPtrOut++) = (*dwPtrA++) ^ (*dwPtrB++);
+    (*dwPtrOut++) = (*dwPtrA++) ^ (*dwPtrB++);
+    (*dwPtrOut++) = (*dwPtrA++) ^ (*dwPtrB++);
+}
+
+
+void xor_32(BYTE *a, BYTE *b, BYTE *out)
+{
+PDWORD dwPtrA = (PDWORD) a;
+PDWORD dwPtrB = (PDWORD) b;
+PDWORD dwPtrOut =(PDWORD) out;
+
+    (*dwPtrOut++) = (*dwPtrA++) ^ (*dwPtrB++);
+}
+
+void AddRoundKey(BYTE *key, int round)
+{
+BYTE sbox_key[4];
+BYTE rcon_table[10] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36};
+
+    sbox_key[0] = sbox_table[key[13]];
+    sbox_key[1] = sbox_table[key[14]];
+    sbox_key[2] = sbox_table[key[15]];
+    sbox_key[3] = sbox_table[key[12]];
+
+    key[0] = key[0] ^ rcon_table[round];
+    xor_32(&key[0], sbox_key, &key[0]);
+
+    xor_32(&key[4], &key[0], &key[4]);
+    xor_32(&key[8], &key[4], &key[8]);
+    xor_32(&key[12], &key[8], &key[12]);
+}
+
+void SubBytes(BYTE *in, BYTE *out)
+{
+int i;
+
+    for (i=0; i< 16; i++)
+    {
+        out[i] = sbox_table[in[i]];
+    }
+}
+
+void ShiftRows(BYTE *in, BYTE *out)
+{
+    out[0]  = in[0];
+    out[1]  = in[5];
+    out[2]  = in[10];
+    out[3]  = in[15];
+    out[4]  = in[4];
+    out[5]  = in[9];
+    out[6]  = in[14];
+    out[7]  = in[3];
+    out[8]  = in[8];
+    out[9]  = in[13];
+    out[10] = in[2];
+    out[11] = in[7];
+    out[12] = in[12];
+    out[13] = in[1];
+    out[14] = in[6];
+    out[15] = in[11];
+}
+
+void MixColumns(BYTE *in, BYTE *out)
+{
+
+    out[0] = dot2_table[in[0]] ^ dot3_table[in[1]] ^ in[2] ^ in[3];
+    out[1] = in[0] ^ dot2_table[in[1]] ^ dot3_table[in[2]] ^ in[3];
+    out[2] = in[0] ^ in[1] ^ dot2_table[in[2]] ^ dot3_table[in[3]];
+    out[3] = dot3_table[in[0]] ^ in[1] ^ in[2] ^ dot2_table[in[3]];
+}
+
+
+void AESv128(BYTE *key, BYTE *data, BYTE *ciphertext)
+{
+int  i;
+int  round;
+BYTE TmpdataA[16];
+BYTE TmpdataB[16];
+BYTE abyRoundKey[16];
+
+    for(i=0; i<16; i++)
+        abyRoundKey[i] = key[i];
+
+    for (round = 0; round < 11; round++)
+    {
+        if (round == 0)
+        {
+            xor_128(abyRoundKey, data, ciphertext);
+            AddRoundKey(abyRoundKey, round);
+        }
+        else if (round == 10)
+        {
+            SubBytes(ciphertext, TmpdataA);
+            ShiftRows(TmpdataA, TmpdataB);
+            xor_128(TmpdataB, abyRoundKey, ciphertext);
+        }
+        else // round 1 ~ 9
+        {
+            SubBytes(ciphertext, TmpdataA);
+            ShiftRows(TmpdataA, TmpdataB);
+            MixColumns(&TmpdataB[0], &TmpdataA[0]);
+            MixColumns(&TmpdataB[4], &TmpdataA[4]);
+            MixColumns(&TmpdataB[8], &TmpdataA[8]);
+            MixColumns(&TmpdataB[12], &TmpdataA[12]);
+            xor_128(TmpdataA, abyRoundKey, ciphertext);
+            AddRoundKey(abyRoundKey, round);
+        }
+    }
+
+}
+
+/*
+ * Description: AES decryption
+ *
+ * Parameters:
+ *  In:
+ *      pbyRxKey            - The key used to decrypt
+ *      pbyFrame            - Starting address of packet header
+ *      wFrameSize          - Total packet size including CRC
+ *  Out:
+ *      none
+ *
+ * Return Value: MIC compare result
+ *
+ */
+BOOL AESbGenCCMP(PBYTE pbyRxKey, PBYTE pbyFrame, WORD wFrameSize)
+{
+BYTE            abyNonce[13];
+BYTE            MIC_IV[16];
+BYTE            MIC_HDR1[16];
+BYTE            MIC_HDR2[16];
+BYTE            abyMIC[16];
+BYTE            abyCTRPLD[16];
+BYTE            abyTmp[16];
+BYTE            abyPlainText[16];
+BYTE            abyLastCipher[16];
+
+PS802_11Header  pMACHeader = (PS802_11Header) pbyFrame;
+PBYTE           pbyIV;
+PBYTE           pbyPayload;
+WORD            wHLen = 22;
+WORD            wPayloadSize = wFrameSize - 8 - 8 - 4 - WLAN_HDR_ADDR3_LEN;//8 is IV, 8 is MIC, 4 is CRC
+BOOL            bA4 = FALSE;
+BYTE            byTmp;
+WORD            wCnt;
+int             ii,jj,kk;
+
+
+    pbyIV = pbyFrame + WLAN_HDR_ADDR3_LEN;
+    if ( WLAN_GET_FC_TODS(*(PWORD)pbyFrame) &&
+         WLAN_GET_FC_FROMDS(*(PWORD)pbyFrame) ) {
+         bA4 = TRUE;
+         pbyIV += 6;             // 6 is 802.11 address4
+         wHLen += 6;
+         wPayloadSize -= 6;
+    }
+    pbyPayload = pbyIV + 8; //IV-length
+
+    abyNonce[0]  = 0x00; //now is 0, if Qos here will be priority
+    MEMvCopy(&(abyNonce[1]), pMACHeader->abyAddr2, U_ETHER_ADDR_LEN);
+    abyNonce[7]  = pbyIV[7];
+    abyNonce[8]  = pbyIV[6];
+    abyNonce[9]  = pbyIV[5];
+    abyNonce[10] = pbyIV[4];
+    abyNonce[11] = pbyIV[1];
+    abyNonce[12] = pbyIV[0];
+
+    //MIC_IV
+    MIC_IV[0] = 0x59;
+    MEMvCopy(&(MIC_IV[1]), &(abyNonce[0]), 13);
+    MIC_IV[14] = (BYTE)(wPayloadSize >> 8);
+    MIC_IV[15] = (BYTE)(wPayloadSize & 0xff);
+
+    //MIC_HDR1
+    MIC_HDR1[0] = (BYTE)(wHLen >> 8);
+    MIC_HDR1[1] = (BYTE)(wHLen & 0xff);
+    byTmp = (BYTE)(pMACHeader->wFrameCtl & 0xff);
+    MIC_HDR1[2] = byTmp & 0x8f;
+    byTmp = (BYTE)(pMACHeader->wFrameCtl >> 8);
+    byTmp &= 0x87;
+    MIC_HDR1[3] = byTmp | 0x40;
+    MEMvCopy(&(MIC_HDR1[4]), pMACHeader->abyAddr1, U_ETHER_ADDR_LEN);
+    MEMvCopy(&(MIC_HDR1[10]), pMACHeader->abyAddr2, U_ETHER_ADDR_LEN);
+
+    //MIC_HDR2
+    MEMvCopy(&(MIC_HDR2[0]), pMACHeader->abyAddr3, U_ETHER_ADDR_LEN);
+    byTmp = (BYTE)(pMACHeader->wSeqCtl & 0xff);
+    MIC_HDR2[6] = byTmp & 0x0f;
+    MIC_HDR2[7] = 0;
+    if ( bA4 ) {
+        MEMvCopy(&(MIC_HDR2[8]), pMACHeader->abyAddr4, U_ETHER_ADDR_LEN);
+    } else {
+        MIC_HDR2[8]  = 0x00;
+        MIC_HDR2[9]  = 0x00;
+        MIC_HDR2[10] = 0x00;
+        MIC_HDR2[11] = 0x00;
+        MIC_HDR2[12] = 0x00;
+        MIC_HDR2[13] = 0x00;
+    }
+    MIC_HDR2[14] = 0x00;
+    MIC_HDR2[15] = 0x00;
+
+    //CCMP
+    AESv128(pbyRxKey,MIC_IV,abyMIC);
+    for ( kk=0; kk<16; kk++ ) {
+        abyTmp[kk] = MIC_HDR1[kk] ^ abyMIC[kk];
+    }
+    AESv128(pbyRxKey,abyTmp,abyMIC);
+    for ( kk=0; kk<16; kk++ ) {
+        abyTmp[kk] = MIC_HDR2[kk] ^ abyMIC[kk];
+    }
+    AESv128(pbyRxKey,abyTmp,abyMIC);
+
+    wCnt = 1;
+    abyCTRPLD[0] = 0x01;
+    MEMvCopy(&(abyCTRPLD[1]), &(abyNonce[0]), 13);
+
+    for(jj=wPayloadSize; jj>16; jj=jj-16) {
+
+        abyCTRPLD[14] = (BYTE) (wCnt >> 8);
+        abyCTRPLD[15] = (BYTE) (wCnt & 0xff);
+
+        AESv128(pbyRxKey,abyCTRPLD,abyTmp);
+
+        for ( kk=0; kk<16; kk++ ) {
+            abyPlainText[kk] = abyTmp[kk] ^ pbyPayload[kk];
+        }
+        for ( kk=0; kk<16; kk++ ) {
+            abyTmp[kk] = abyMIC[kk] ^ abyPlainText[kk];
+        }
+        AESv128(pbyRxKey,abyTmp,abyMIC);
+
+        MEMvCopy(pbyPayload, abyPlainText, 16);
+        wCnt++;
+        pbyPayload += 16;
+    } //for wPayloadSize
+
+    //last payload
+    MEMvCopy(&(abyLastCipher[0]), pbyPayload, jj);
+    for ( ii=jj; ii<16; ii++ ) {
+        abyLastCipher[ii] = 0x00;
+    }
+
+    abyCTRPLD[14] = (BYTE) (wCnt >> 8);
+    abyCTRPLD[15] = (BYTE) (wCnt & 0xff);
+
+    AESv128(pbyRxKey,abyCTRPLD,abyTmp);
+    for ( kk=0; kk<16; kk++ ) {
+        abyPlainText[kk] = abyTmp[kk] ^ abyLastCipher[kk];
+    }
+    MEMvCopy(pbyPayload, abyPlainText, jj);
+    pbyPayload += jj;
+
+    //for MIC calculation
+    for ( ii=jj; ii<16; ii++ ) {
+        abyPlainText[ii] = 0x00;
+    }
+    for ( kk=0; kk<16; kk++ ) {
+        abyTmp[kk] = abyMIC[kk] ^ abyPlainText[kk];
+    }
+    AESv128(pbyRxKey,abyTmp,abyMIC);
+
+    //=>above is the calculate MIC
+    //--------------------------------------------
+
+    wCnt = 0;
+    abyCTRPLD[14] = (BYTE) (wCnt >> 8);
+    abyCTRPLD[15] = (BYTE) (wCnt & 0xff);
+    AESv128(pbyRxKey,abyCTRPLD,abyTmp);
+    for ( kk=0; kk<8; kk++ ) {
+        abyTmp[kk] = abyTmp[kk] ^ pbyPayload[kk];
+    }
+    //=>above is the dec-MIC from packet
+    //--------------------------------------------
+
+    if ( MEMEqualMemory(abyMIC,abyTmp,8) ) {
+        return TRUE;
+    } else {
+        return FALSE;
+    }
+
+}
diff --git a/drivers/staging/vt6655/aes_ccmp.h b/drivers/staging/vt6655/aes_ccmp.h
new file mode 100644
index 0000000..2b1920f
--- /dev/null
+++ b/drivers/staging/vt6655/aes_ccmp.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: aes_ccmp.h
+ *
+ * Purpose: AES_CCMP Decryption
+ *
+ * Author: Warren Hsu
+ *
+ * Date: Feb 15, 2005
+ *
+ */
+
+#ifndef __AES_H__
+#define __AES_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+/*---------------------  Export Definitions -------------------------*/
+
+/*---------------------  Export Types  ------------------------------*/
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+BOOL AESbGenCCMP(PBYTE pbyRxKey, PBYTE pbyFrame, WORD wFrameSize);
+
+#endif //__AES_H__
diff --git a/drivers/staging/vt6655/baseband.c b/drivers/staging/vt6655/baseband.c
new file mode 100644
index 0000000..bc6db86
--- /dev/null
+++ b/drivers/staging/vt6655/baseband.c
@@ -0,0 +1,2990 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: baseband.c
+ *
+ * Purpose: Implement functions to access baseband
+ *
+ * Author: Kyle Hsu
+ *
+ * Date: Aug.22, 2002
+ *
+ * Functions:
+ *      BBuGetFrameTime        - Calculate data frame transmitting time
+ *      BBvCaculateParameter   - Caculate PhyLength, PhyService and Phy Signal parameter for baseband Tx
+ *      BBbReadEmbeded         - Embeded read baseband register via MAC
+ *      BBbWriteEmbeded        - Embeded write baseband register via MAC
+ *      BBbIsRegBitsOn         - Test if baseband register bits on
+ *      BBbIsRegBitsOff        - Test if baseband register bits off
+ *      BBbVT3253Init          - VIA VT3253 baseband chip init code
+ *      BBvReadAllRegs         - Read All Baseband Registers
+ *      BBvLoopbackOn          - Turn on BaseBand Loopback mode
+ *      BBvLoopbackOff         - Turn off BaseBand Loopback mode
+ *
+ * Revision History:
+ *      06-10-2003 Bryan YC Fan:  Re-write codes to support VT3253 spec.
+ *      08-07-2003 Bryan YC Fan:  Add MAXIM2827/2825 and RFMD2959 support.
+ *      08-26-2003 Kyle Hsu    :  Modify BBuGetFrameTime() and BBvCaculateParameter().
+ *                                cancel the setting of MAC_REG_SOFTPWRCTL on BBbVT3253Init().
+ *                                Add the comments.
+ *      09-01-2003 Bryan YC Fan:  RF & BB tables updated.
+ *                                Modified BBvLoopbackOn & BBvLoopbackOff().
+ */
+
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+#if !defined(__SROM_H__)
+#include "srom.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+
+/*---------------------  Static Definitions -------------------------*/
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+static int          msglevel                =MSG_LEVEL_INFO;
+
+//#define	PLICE_DEBUG
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+
+
+#define CB_VT3253_INIT_FOR_RFMD 446
+BYTE byVT3253InitTab_RFMD[CB_VT3253_INIT_FOR_RFMD][2] = {
+    {0x00, 0x30},
+    {0x01, 0x00},
+    {0x02, 0x00},
+    {0x03, 0x00},
+    {0x04, 0x00},
+    {0x05, 0x00},
+    {0x06, 0x00},
+    {0x07, 0x00},
+    {0x08, 0x70},
+    {0x09, 0x45},
+    {0x0a, 0x2a},
+    {0x0b, 0x76},
+    {0x0c, 0x00},
+    {0x0d, 0x01},
+    {0x0e, 0x80},
+    {0x0f, 0x00},
+    {0x10, 0x00},
+    {0x11, 0x00},
+    {0x12, 0x00},
+    {0x13, 0x00},
+    {0x14, 0x00},
+    {0x15, 0x00},
+    {0x16, 0x00},
+    {0x17, 0x00},
+    {0x18, 0x00},
+    {0x19, 0x00},
+    {0x1a, 0x00},
+    {0x1b, 0x9d},
+    {0x1c, 0x05},
+    {0x1d, 0x00},
+    {0x1e, 0x00},
+    {0x1f, 0x00},
+    {0x20, 0x00},
+    {0x21, 0x00},
+    {0x22, 0x00},
+    {0x23, 0x00},
+    {0x24, 0x00},
+    {0x25, 0x4a},
+    {0x26, 0x00},
+    {0x27, 0x00},
+    {0x28, 0x00},
+    {0x29, 0x00},
+    {0x2a, 0x00},
+    {0x2b, 0x00},
+    {0x2c, 0x00},
+    {0x2d, 0xa8},
+    {0x2e, 0x1a},
+    {0x2f, 0x0c},
+    {0x30, 0x26},
+    {0x31, 0x5b},
+    {0x32, 0x00},
+    {0x33, 0x00},
+    {0x34, 0x00},
+    {0x35, 0x00},
+    {0x36, 0xaa},
+    {0x37, 0xaa},
+    {0x38, 0xff},
+    {0x39, 0xff},
+    {0x3a, 0x00},
+    {0x3b, 0x00},
+    {0x3c, 0x00},
+    {0x3d, 0x0d},
+    {0x3e, 0x51},
+    {0x3f, 0x04},
+    {0x40, 0x00},
+    {0x41, 0x08},
+    {0x42, 0x00},
+    {0x43, 0x08},
+    {0x44, 0x06},
+    {0x45, 0x14},
+    {0x46, 0x05},
+    {0x47, 0x08},
+    {0x48, 0x00},
+    {0x49, 0x00},
+    {0x4a, 0x00},
+    {0x4b, 0x00},
+    {0x4c, 0x09},
+    {0x4d, 0x80},
+    {0x4e, 0x00},
+    {0x4f, 0xc5},
+    {0x50, 0x14},
+    {0x51, 0x19},
+    {0x52, 0x00},
+    {0x53, 0x00},
+    {0x54, 0x00},
+    {0x55, 0x00},
+    {0x56, 0x00},
+    {0x57, 0x00},
+    {0x58, 0x00},
+    {0x59, 0xb0},
+    {0x5a, 0x00},
+    {0x5b, 0x00},
+    {0x5c, 0x00},
+    {0x5d, 0x00},
+    {0x5e, 0x00},
+    {0x5f, 0x00},
+    {0x60, 0x44},
+    {0x61, 0x04},
+    {0x62, 0x00},
+    {0x63, 0x00},
+    {0x64, 0x00},
+    {0x65, 0x00},
+    {0x66, 0x04},
+    {0x67, 0xb7},
+    {0x68, 0x00},
+    {0x69, 0x00},
+    {0x6a, 0x00},
+    {0x6b, 0x00},
+    {0x6c, 0x00},
+    {0x6d, 0x03},
+    {0x6e, 0x01},
+    {0x6f, 0x00},
+    {0x70, 0x00},
+    {0x71, 0x00},
+    {0x72, 0x00},
+    {0x73, 0x00},
+    {0x74, 0x00},
+    {0x75, 0x00},
+    {0x76, 0x00},
+    {0x77, 0x00},
+    {0x78, 0x00},
+    {0x79, 0x00},
+    {0x7a, 0x00},
+    {0x7b, 0x00},
+    {0x7c, 0x00},
+    {0x7d, 0x00},
+    {0x7e, 0x00},
+    {0x7f, 0x00},
+    {0x80, 0x0b},
+    {0x81, 0x00},
+    {0x82, 0x3c},
+    {0x83, 0x00},
+    {0x84, 0x00},
+    {0x85, 0x00},
+    {0x86, 0x00},
+    {0x87, 0x00},
+    {0x88, 0x08},
+    {0x89, 0x00},
+    {0x8a, 0x08},
+    {0x8b, 0xa6},
+    {0x8c, 0x84},
+    {0x8d, 0x47},
+    {0x8e, 0xbb},
+    {0x8f, 0x02},
+    {0x90, 0x21},
+    {0x91, 0x0c},
+    {0x92, 0x04},
+    {0x93, 0x22},
+    {0x94, 0x00},
+    {0x95, 0x00},
+    {0x96, 0x00},
+    {0x97, 0xeb},
+    {0x98, 0x00},
+    {0x99, 0x00},
+    {0x9a, 0x00},
+    {0x9b, 0x00},
+    {0x9c, 0x00},
+    {0x9d, 0x00},
+    {0x9e, 0x00},
+    {0x9f, 0x00},
+    {0xa0, 0x00},
+    {0xa1, 0x00},
+    {0xa2, 0x00},
+    {0xa3, 0x00},
+    {0xa4, 0x00},
+    {0xa5, 0x00},
+    {0xa6, 0x10},
+    {0xa7, 0x04},
+    {0xa8, 0x10},
+    {0xa9, 0x00},
+    {0xaa, 0x8f},
+    {0xab, 0x00},
+    {0xac, 0x00},
+    {0xad, 0x00},
+    {0xae, 0x00},
+    {0xaf, 0x80},
+    {0xb0, 0x38},
+    {0xb1, 0x00},
+    {0xb2, 0x00},
+    {0xb3, 0x00},
+    {0xb4, 0xee},
+    {0xb5, 0xff},
+    {0xb6, 0x10},
+    {0xb7, 0x00},
+    {0xb8, 0x00},
+    {0xb9, 0x00},
+    {0xba, 0x00},
+    {0xbb, 0x03},
+    {0xbc, 0x00},
+    {0xbd, 0x00},
+    {0xbe, 0x00},
+    {0xbf, 0x00},
+    {0xc0, 0x10},
+    {0xc1, 0x10},
+    {0xc2, 0x18},
+    {0xc3, 0x20},
+    {0xc4, 0x10},
+    {0xc5, 0x00},
+    {0xc6, 0x22},
+    {0xc7, 0x14},
+    {0xc8, 0x0f},
+    {0xc9, 0x08},
+    {0xca, 0xa4},
+    {0xcb, 0xa7},
+    {0xcc, 0x3c},
+    {0xcd, 0x10},
+    {0xce, 0x20},
+    {0xcf, 0x00},
+    {0xd0, 0x00},
+    {0xd1, 0x10},
+    {0xd2, 0x00},
+    {0xd3, 0x00},
+    {0xd4, 0x10},
+    {0xd5, 0x33},
+    {0xd6, 0x70},
+    {0xd7, 0x01},
+    {0xd8, 0x00},
+    {0xd9, 0x00},
+    {0xda, 0x00},
+    {0xdb, 0x00},
+    {0xdc, 0x00},
+    {0xdd, 0x00},
+    {0xde, 0x00},
+    {0xdf, 0x00},
+    {0xe0, 0x00},
+    {0xe1, 0x00},
+    {0xe2, 0xcc},
+    {0xe3, 0x04},
+    {0xe4, 0x08},
+    {0xe5, 0x10},
+    {0xe6, 0x00},
+    {0xe7, 0x0e},
+    {0xe8, 0x88},
+    {0xe9, 0xd4},
+    {0xea, 0x05},
+    {0xeb, 0xf0},
+    {0xec, 0x79},
+    {0xed, 0x0f},
+    {0xee, 0x04},
+    {0xef, 0x04},
+    {0xf0, 0x00},
+    {0xf1, 0x00},
+    {0xf2, 0x00},
+    {0xf3, 0x00},
+    {0xf4, 0x00},
+    {0xf5, 0x00},
+    {0xf6, 0x00},
+    {0xf7, 0x00},
+    {0xf8, 0x00},
+    {0xf9, 0x00},
+    {0xF0, 0x00},
+    {0xF1, 0xF8},
+    {0xF0, 0x80},
+    {0xF0, 0x00},
+    {0xF1, 0xF4},
+    {0xF0, 0x81},
+    {0xF0, 0x01},
+    {0xF1, 0xF0},
+    {0xF0, 0x82},
+    {0xF0, 0x02},
+    {0xF1, 0xEC},
+    {0xF0, 0x83},
+    {0xF0, 0x03},
+    {0xF1, 0xE8},
+    {0xF0, 0x84},
+    {0xF0, 0x04},
+    {0xF1, 0xE4},
+    {0xF0, 0x85},
+    {0xF0, 0x05},
+    {0xF1, 0xE0},
+    {0xF0, 0x86},
+    {0xF0, 0x06},
+    {0xF1, 0xDC},
+    {0xF0, 0x87},
+    {0xF0, 0x07},
+    {0xF1, 0xD8},
+    {0xF0, 0x88},
+    {0xF0, 0x08},
+    {0xF1, 0xD4},
+    {0xF0, 0x89},
+    {0xF0, 0x09},
+    {0xF1, 0xD0},
+    {0xF0, 0x8A},
+    {0xF0, 0x0A},
+    {0xF1, 0xCC},
+    {0xF0, 0x8B},
+    {0xF0, 0x0B},
+    {0xF1, 0xC8},
+    {0xF0, 0x8C},
+    {0xF0, 0x0C},
+    {0xF1, 0xC4},
+    {0xF0, 0x8D},
+    {0xF0, 0x0D},
+    {0xF1, 0xC0},
+    {0xF0, 0x8E},
+    {0xF0, 0x0E},
+    {0xF1, 0xBC},
+    {0xF0, 0x8F},
+    {0xF0, 0x0F},
+    {0xF1, 0xB8},
+    {0xF0, 0x90},
+    {0xF0, 0x10},
+    {0xF1, 0xB4},
+    {0xF0, 0x91},
+    {0xF0, 0x11},
+    {0xF1, 0xB0},
+    {0xF0, 0x92},
+    {0xF0, 0x12},
+    {0xF1, 0xAC},
+    {0xF0, 0x93},
+    {0xF0, 0x13},
+    {0xF1, 0xA8},
+    {0xF0, 0x94},
+    {0xF0, 0x14},
+    {0xF1, 0xA4},
+    {0xF0, 0x95},
+    {0xF0, 0x15},
+    {0xF1, 0xA0},
+    {0xF0, 0x96},
+    {0xF0, 0x16},
+    {0xF1, 0x9C},
+    {0xF0, 0x97},
+    {0xF0, 0x17},
+    {0xF1, 0x98},
+    {0xF0, 0x98},
+    {0xF0, 0x18},
+    {0xF1, 0x94},
+    {0xF0, 0x99},
+    {0xF0, 0x19},
+    {0xF1, 0x90},
+    {0xF0, 0x9A},
+    {0xF0, 0x1A},
+    {0xF1, 0x8C},
+    {0xF0, 0x9B},
+    {0xF0, 0x1B},
+    {0xF1, 0x88},
+    {0xF0, 0x9C},
+    {0xF0, 0x1C},
+    {0xF1, 0x84},
+    {0xF0, 0x9D},
+    {0xF0, 0x1D},
+    {0xF1, 0x80},
+    {0xF0, 0x9E},
+    {0xF0, 0x1E},
+    {0xF1, 0x7C},
+    {0xF0, 0x9F},
+    {0xF0, 0x1F},
+    {0xF1, 0x78},
+    {0xF0, 0xA0},
+    {0xF0, 0x20},
+    {0xF1, 0x74},
+    {0xF0, 0xA1},
+    {0xF0, 0x21},
+    {0xF1, 0x70},
+    {0xF0, 0xA2},
+    {0xF0, 0x22},
+    {0xF1, 0x6C},
+    {0xF0, 0xA3},
+    {0xF0, 0x23},
+    {0xF1, 0x68},
+    {0xF0, 0xA4},
+    {0xF0, 0x24},
+    {0xF1, 0x64},
+    {0xF0, 0xA5},
+    {0xF0, 0x25},
+    {0xF1, 0x60},
+    {0xF0, 0xA6},
+    {0xF0, 0x26},
+    {0xF1, 0x5C},
+    {0xF0, 0xA7},
+    {0xF0, 0x27},
+    {0xF1, 0x58},
+    {0xF0, 0xA8},
+    {0xF0, 0x28},
+    {0xF1, 0x54},
+    {0xF0, 0xA9},
+    {0xF0, 0x29},
+    {0xF1, 0x50},
+    {0xF0, 0xAA},
+    {0xF0, 0x2A},
+    {0xF1, 0x4C},
+    {0xF0, 0xAB},
+    {0xF0, 0x2B},
+    {0xF1, 0x48},
+    {0xF0, 0xAC},
+    {0xF0, 0x2C},
+    {0xF1, 0x44},
+    {0xF0, 0xAD},
+    {0xF0, 0x2D},
+    {0xF1, 0x40},
+    {0xF0, 0xAE},
+    {0xF0, 0x2E},
+    {0xF1, 0x3C},
+    {0xF0, 0xAF},
+    {0xF0, 0x2F},
+    {0xF1, 0x38},
+    {0xF0, 0xB0},
+    {0xF0, 0x30},
+    {0xF1, 0x34},
+    {0xF0, 0xB1},
+    {0xF0, 0x31},
+    {0xF1, 0x30},
+    {0xF0, 0xB2},
+    {0xF0, 0x32},
+    {0xF1, 0x2C},
+    {0xF0, 0xB3},
+    {0xF0, 0x33},
+    {0xF1, 0x28},
+    {0xF0, 0xB4},
+    {0xF0, 0x34},
+    {0xF1, 0x24},
+    {0xF0, 0xB5},
+    {0xF0, 0x35},
+    {0xF1, 0x20},
+    {0xF0, 0xB6},
+    {0xF0, 0x36},
+    {0xF1, 0x1C},
+    {0xF0, 0xB7},
+    {0xF0, 0x37},
+    {0xF1, 0x18},
+    {0xF0, 0xB8},
+    {0xF0, 0x38},
+    {0xF1, 0x14},
+    {0xF0, 0xB9},
+    {0xF0, 0x39},
+    {0xF1, 0x10},
+    {0xF0, 0xBA},
+    {0xF0, 0x3A},
+    {0xF1, 0x0C},
+    {0xF0, 0xBB},
+    {0xF0, 0x3B},
+    {0xF1, 0x08},
+    {0xF0, 0x00},
+    {0xF0, 0x3C},
+    {0xF1, 0x04},
+    {0xF0, 0xBD},
+    {0xF0, 0x3D},
+    {0xF1, 0x00},
+    {0xF0, 0xBE},
+    {0xF0, 0x3E},
+    {0xF1, 0x00},
+    {0xF0, 0xBF},
+    {0xF0, 0x3F},
+    {0xF1, 0x00},
+    {0xF0, 0xC0},
+    {0xF0, 0x00},
+};
+
+#define CB_VT3253B0_INIT_FOR_RFMD 256
+BYTE byVT3253B0_RFMD[CB_VT3253B0_INIT_FOR_RFMD][2] = {
+    {0x00, 0x31},
+    {0x01, 0x00},
+    {0x02, 0x00},
+    {0x03, 0x00},
+    {0x04, 0x00},
+    {0x05, 0x81},
+    {0x06, 0x00},
+    {0x07, 0x00},
+    {0x08, 0x38},
+    {0x09, 0x45},
+    {0x0a, 0x2a},
+    {0x0b, 0x76},
+    {0x0c, 0x00},
+    {0x0d, 0x00},
+    {0x0e, 0x80},
+    {0x0f, 0x00},
+    {0x10, 0x00},
+    {0x11, 0x00},
+    {0x12, 0x00},
+    {0x13, 0x00},
+    {0x14, 0x00},
+    {0x15, 0x00},
+    {0x16, 0x00},
+    {0x17, 0x00},
+    {0x18, 0x00},
+    {0x19, 0x00},
+    {0x1a, 0x00},
+    {0x1b, 0x8e},
+    {0x1c, 0x06},
+    {0x1d, 0x00},
+    {0x1e, 0x00},
+    {0x1f, 0x00},
+    {0x20, 0x00},
+    {0x21, 0x00},
+    {0x22, 0x00},
+    {0x23, 0x00},
+    {0x24, 0x00},
+    {0x25, 0x4a},
+    {0x26, 0x00},
+    {0x27, 0x00},
+    {0x28, 0x00},
+    {0x29, 0x00},
+    {0x2a, 0x00},
+    {0x2b, 0x00},
+    {0x2c, 0x00},
+    {0x2d, 0x34},
+    {0x2e, 0x18},
+    {0x2f, 0x0c},
+    {0x30, 0x26},
+    {0x31, 0x5b},
+    {0x32, 0x00},
+    {0x33, 0x00},
+    {0x34, 0x00},
+    {0x35, 0x00},
+    {0x36, 0xaa},
+    {0x37, 0xaa},
+    {0x38, 0xff},
+    {0x39, 0xff},
+    {0x3a, 0xf8},
+    {0x3b, 0x00},
+    {0x3c, 0x00},
+    {0x3d, 0x09},
+    {0x3e, 0x0d},
+    {0x3f, 0x04},
+    {0x40, 0x00},
+    {0x41, 0x08},
+    {0x42, 0x00},
+    {0x43, 0x08},
+    {0x44, 0x08},
+    {0x45, 0x14},
+    {0x46, 0x05},
+    {0x47, 0x08},
+    {0x48, 0x00},
+    {0x49, 0x00},
+    {0x4a, 0x00},
+    {0x4b, 0x00},
+    {0x4c, 0x09},
+    {0x4d, 0x80},
+    {0x4e, 0x00},
+    {0x4f, 0xc5},
+    {0x50, 0x14},
+    {0x51, 0x19},
+    {0x52, 0x00},
+    {0x53, 0x00},
+    {0x54, 0x00},
+    {0x55, 0x00},
+    {0x56, 0x00},
+    {0x57, 0x00},
+    {0x58, 0x00},
+    {0x59, 0xb0},
+    {0x5a, 0x00},
+    {0x5b, 0x00},
+    {0x5c, 0x00},
+    {0x5d, 0x00},
+    {0x5e, 0x00},
+    {0x5f, 0x00},
+    {0x60, 0x39},
+    {0x61, 0x83},
+    {0x62, 0x00},
+    {0x63, 0x00},
+    {0x64, 0x00},
+    {0x65, 0x00},
+    {0x66, 0xc0},
+    {0x67, 0x49},
+    {0x68, 0x00},
+    {0x69, 0x00},
+    {0x6a, 0x00},
+    {0x6b, 0x00},
+    {0x6c, 0x00},
+    {0x6d, 0x03},
+    {0x6e, 0x01},
+    {0x6f, 0x00},
+    {0x70, 0x00},
+    {0x71, 0x00},
+    {0x72, 0x00},
+    {0x73, 0x00},
+    {0x74, 0x00},
+    {0x75, 0x00},
+    {0x76, 0x00},
+    {0x77, 0x00},
+    {0x78, 0x00},
+    {0x79, 0x00},
+    {0x7a, 0x00},
+    {0x7b, 0x00},
+    {0x7c, 0x00},
+    {0x7d, 0x00},
+    {0x7e, 0x00},
+    {0x7f, 0x00},
+    {0x80, 0x89},
+    {0x81, 0x00},
+    {0x82, 0x0e},
+    {0x83, 0x00},
+    {0x84, 0x00},
+    {0x85, 0x00},
+    {0x86, 0x00},
+    {0x87, 0x00},
+    {0x88, 0x08},
+    {0x89, 0x00},
+    {0x8a, 0x0e},
+    {0x8b, 0xa7},
+    {0x8c, 0x88},
+    {0x8d, 0x47},
+    {0x8e, 0xaa},
+    {0x8f, 0x02},
+    {0x90, 0x23},
+    {0x91, 0x0c},
+    {0x92, 0x06},
+    {0x93, 0x08},
+    {0x94, 0x00},
+    {0x95, 0x00},
+    {0x96, 0x00},
+    {0x97, 0xeb},
+    {0x98, 0x00},
+    {0x99, 0x00},
+    {0x9a, 0x00},
+    {0x9b, 0x00},
+    {0x9c, 0x00},
+    {0x9d, 0x00},
+    {0x9e, 0x00},
+    {0x9f, 0x00},
+    {0xa0, 0x00},
+    {0xa1, 0x00},
+    {0xa2, 0x00},
+    {0xa3, 0xcd},
+    {0xa4, 0x07},
+    {0xa5, 0x33},
+    {0xa6, 0x18},
+    {0xa7, 0x00},
+    {0xa8, 0x18},
+    {0xa9, 0x00},
+    {0xaa, 0x28},
+    {0xab, 0x00},
+    {0xac, 0x00},
+    {0xad, 0x00},
+    {0xae, 0x00},
+    {0xaf, 0x18},
+    {0xb0, 0x38},
+    {0xb1, 0x30},
+    {0xb2, 0x00},
+    {0xb3, 0x00},
+    {0xb4, 0x00},
+    {0xb5, 0x00},
+    {0xb6, 0x84},
+    {0xb7, 0xfd},
+    {0xb8, 0x00},
+    {0xb9, 0x00},
+    {0xba, 0x00},
+    {0xbb, 0x03},
+    {0xbc, 0x00},
+    {0xbd, 0x00},
+    {0xbe, 0x00},
+    {0xbf, 0x00},
+    {0xc0, 0x10},
+    {0xc1, 0x20},
+    {0xc2, 0x18},
+    {0xc3, 0x20},
+    {0xc4, 0x10},
+    {0xc5, 0x2c},
+    {0xc6, 0x1e},
+    {0xc7, 0x10},
+    {0xc8, 0x12},
+    {0xc9, 0x01},
+    {0xca, 0x6f},
+    {0xcb, 0xa7},
+    {0xcc, 0x3c},
+    {0xcd, 0x10},
+    {0xce, 0x00},
+    {0xcf, 0x22},
+    {0xd0, 0x00},
+    {0xd1, 0x10},
+    {0xd2, 0x00},
+    {0xd3, 0x00},
+    {0xd4, 0x10},
+    {0xd5, 0x33},
+    {0xd6, 0x80},
+    {0xd7, 0x21},
+    {0xd8, 0x00},
+    {0xd9, 0x00},
+    {0xda, 0x00},
+    {0xdb, 0x00},
+    {0xdc, 0x00},
+    {0xdd, 0x00},
+    {0xde, 0x00},
+    {0xdf, 0x00},
+    {0xe0, 0x00},
+    {0xe1, 0xB3},
+    {0xe2, 0x00},
+    {0xe3, 0x00},
+    {0xe4, 0x00},
+    {0xe5, 0x10},
+    {0xe6, 0x00},
+    {0xe7, 0x18},
+    {0xe8, 0x08},
+    {0xe9, 0xd4},
+    {0xea, 0x00},
+    {0xeb, 0xff},
+    {0xec, 0x79},
+    {0xed, 0x10},
+    {0xee, 0x30},
+    {0xef, 0x02},
+    {0xf0, 0x00},
+    {0xf1, 0x09},
+    {0xf2, 0x00},
+    {0xf3, 0x00},
+    {0xf4, 0x00},
+    {0xf5, 0x00},
+    {0xf6, 0x00},
+    {0xf7, 0x00},
+    {0xf8, 0x00},
+    {0xf9, 0x00},
+    {0xfa, 0x00},
+    {0xfb, 0x00},
+    {0xfc, 0x00},
+    {0xfd, 0x00},
+    {0xfe, 0x00},
+    {0xff, 0x00},
+};
+
+#define CB_VT3253B0_AGC_FOR_RFMD2959 195
+// For RFMD2959
+BYTE byVT3253B0_AGC4_RFMD2959[CB_VT3253B0_AGC_FOR_RFMD2959][2] = {
+    {0xF0, 0x00},
+    {0xF1, 0x3E},
+    {0xF0, 0x80},
+    {0xF0, 0x00},
+    {0xF1, 0x3E},
+    {0xF0, 0x81},
+    {0xF0, 0x01},
+    {0xF1, 0x3E},
+    {0xF0, 0x82},
+    {0xF0, 0x02},
+    {0xF1, 0x3E},
+    {0xF0, 0x83},
+    {0xF0, 0x03},
+    {0xF1, 0x3B},
+    {0xF0, 0x84},
+    {0xF0, 0x04},
+    {0xF1, 0x39},
+    {0xF0, 0x85},
+    {0xF0, 0x05},
+    {0xF1, 0x38},
+    {0xF0, 0x86},
+    {0xF0, 0x06},
+    {0xF1, 0x37},
+    {0xF0, 0x87},
+    {0xF0, 0x07},
+    {0xF1, 0x36},
+    {0xF0, 0x88},
+    {0xF0, 0x08},
+    {0xF1, 0x35},
+    {0xF0, 0x89},
+    {0xF0, 0x09},
+    {0xF1, 0x35},
+    {0xF0, 0x8A},
+    {0xF0, 0x0A},
+    {0xF1, 0x34},
+    {0xF0, 0x8B},
+    {0xF0, 0x0B},
+    {0xF1, 0x34},
+    {0xF0, 0x8C},
+    {0xF0, 0x0C},
+    {0xF1, 0x33},
+    {0xF0, 0x8D},
+    {0xF0, 0x0D},
+    {0xF1, 0x32},
+    {0xF0, 0x8E},
+    {0xF0, 0x0E},
+    {0xF1, 0x31},
+    {0xF0, 0x8F},
+    {0xF0, 0x0F},
+    {0xF1, 0x30},
+    {0xF0, 0x90},
+    {0xF0, 0x10},
+    {0xF1, 0x2F},
+    {0xF0, 0x91},
+    {0xF0, 0x11},
+    {0xF1, 0x2F},
+    {0xF0, 0x92},
+    {0xF0, 0x12},
+    {0xF1, 0x2E},
+    {0xF0, 0x93},
+    {0xF0, 0x13},
+    {0xF1, 0x2D},
+    {0xF0, 0x94},
+    {0xF0, 0x14},
+    {0xF1, 0x2C},
+    {0xF0, 0x95},
+    {0xF0, 0x15},
+    {0xF1, 0x2B},
+    {0xF0, 0x96},
+    {0xF0, 0x16},
+    {0xF1, 0x2B},
+    {0xF0, 0x97},
+    {0xF0, 0x17},
+    {0xF1, 0x2A},
+    {0xF0, 0x98},
+    {0xF0, 0x18},
+    {0xF1, 0x29},
+    {0xF0, 0x99},
+    {0xF0, 0x19},
+    {0xF1, 0x28},
+    {0xF0, 0x9A},
+    {0xF0, 0x1A},
+    {0xF1, 0x27},
+    {0xF0, 0x9B},
+    {0xF0, 0x1B},
+    {0xF1, 0x26},
+    {0xF0, 0x9C},
+    {0xF0, 0x1C},
+    {0xF1, 0x25},
+    {0xF0, 0x9D},
+    {0xF0, 0x1D},
+    {0xF1, 0x24},
+    {0xF0, 0x9E},
+    {0xF0, 0x1E},
+    {0xF1, 0x24},
+    {0xF0, 0x9F},
+    {0xF0, 0x1F},
+    {0xF1, 0x23},
+    {0xF0, 0xA0},
+    {0xF0, 0x20},
+    {0xF1, 0x22},
+    {0xF0, 0xA1},
+    {0xF0, 0x21},
+    {0xF1, 0x21},
+    {0xF0, 0xA2},
+    {0xF0, 0x22},
+    {0xF1, 0x20},
+    {0xF0, 0xA3},
+    {0xF0, 0x23},
+    {0xF1, 0x20},
+    {0xF0, 0xA4},
+    {0xF0, 0x24},
+    {0xF1, 0x1F},
+    {0xF0, 0xA5},
+    {0xF0, 0x25},
+    {0xF1, 0x1E},
+    {0xF0, 0xA6},
+    {0xF0, 0x26},
+    {0xF1, 0x1D},
+    {0xF0, 0xA7},
+    {0xF0, 0x27},
+    {0xF1, 0x1C},
+    {0xF0, 0xA8},
+    {0xF0, 0x28},
+    {0xF1, 0x1B},
+    {0xF0, 0xA9},
+    {0xF0, 0x29},
+    {0xF1, 0x1B},
+    {0xF0, 0xAA},
+    {0xF0, 0x2A},
+    {0xF1, 0x1A},
+    {0xF0, 0xAB},
+    {0xF0, 0x2B},
+    {0xF1, 0x1A},
+    {0xF0, 0xAC},
+    {0xF0, 0x2C},
+    {0xF1, 0x19},
+    {0xF0, 0xAD},
+    {0xF0, 0x2D},
+    {0xF1, 0x18},
+    {0xF0, 0xAE},
+    {0xF0, 0x2E},
+    {0xF1, 0x17},
+    {0xF0, 0xAF},
+    {0xF0, 0x2F},
+    {0xF1, 0x16},
+    {0xF0, 0xB0},
+    {0xF0, 0x30},
+    {0xF1, 0x15},
+    {0xF0, 0xB1},
+    {0xF0, 0x31},
+    {0xF1, 0x15},
+    {0xF0, 0xB2},
+    {0xF0, 0x32},
+    {0xF1, 0x15},
+    {0xF0, 0xB3},
+    {0xF0, 0x33},
+    {0xF1, 0x14},
+    {0xF0, 0xB4},
+    {0xF0, 0x34},
+    {0xF1, 0x13},
+    {0xF0, 0xB5},
+    {0xF0, 0x35},
+    {0xF1, 0x12},
+    {0xF0, 0xB6},
+    {0xF0, 0x36},
+    {0xF1, 0x11},
+    {0xF0, 0xB7},
+    {0xF0, 0x37},
+    {0xF1, 0x10},
+    {0xF0, 0xB8},
+    {0xF0, 0x38},
+    {0xF1, 0x0F},
+    {0xF0, 0xB9},
+    {0xF0, 0x39},
+    {0xF1, 0x0E},
+    {0xF0, 0xBA},
+    {0xF0, 0x3A},
+    {0xF1, 0x0D},
+    {0xF0, 0xBB},
+    {0xF0, 0x3B},
+    {0xF1, 0x0C},
+    {0xF0, 0xBC},
+    {0xF0, 0x3C},
+    {0xF1, 0x0B},
+    {0xF0, 0xBD},
+    {0xF0, 0x3D},
+    {0xF1, 0x0B},
+    {0xF0, 0xBE},
+    {0xF0, 0x3E},
+    {0xF1, 0x0A},
+    {0xF0, 0xBF},
+    {0xF0, 0x3F},
+    {0xF1, 0x09},
+    {0xF0, 0x00},
+};
+
+#define CB_VT3253B0_INIT_FOR_AIROHA2230 256
+// For AIROHA
+BYTE byVT3253B0_AIROHA2230[CB_VT3253B0_INIT_FOR_AIROHA2230][2] = {
+    {0x00, 0x31},
+    {0x01, 0x00},
+    {0x02, 0x00},
+    {0x03, 0x00},
+    {0x04, 0x00},
+    {0x05, 0x80},
+    {0x06, 0x00},
+    {0x07, 0x00},
+    {0x08, 0x70},
+    {0x09, 0x41},
+    {0x0a, 0x2A},
+    {0x0b, 0x76},
+    {0x0c, 0x00},
+    {0x0d, 0x00},
+    {0x0e, 0x80},
+    {0x0f, 0x00},
+    {0x10, 0x00},
+    {0x11, 0x00},
+    {0x12, 0x00},
+    {0x13, 0x00},
+    {0x14, 0x00},
+    {0x15, 0x00},
+    {0x16, 0x00},
+    {0x17, 0x00},
+    {0x18, 0x00},
+    {0x19, 0x00},
+    {0x1a, 0x00},
+    {0x1b, 0x8f},
+    {0x1c, 0x09},
+    {0x1d, 0x00},
+    {0x1e, 0x00},
+    {0x1f, 0x00},
+    {0x20, 0x00},
+    {0x21, 0x00},
+    {0x22, 0x00},
+    {0x23, 0x00},
+    {0x24, 0x00},
+    {0x25, 0x4a},
+    {0x26, 0x00},
+    {0x27, 0x00},
+    {0x28, 0x00},
+    {0x29, 0x00},
+    {0x2a, 0x00},
+    {0x2b, 0x00},
+    {0x2c, 0x00},
+    {0x2d, 0x4a},
+    {0x2e, 0x00},
+    {0x2f, 0x0a},
+    {0x30, 0x26},
+    {0x31, 0x5b},
+    {0x32, 0x00},
+    {0x33, 0x00},
+    {0x34, 0x00},
+    {0x35, 0x00},
+    {0x36, 0xaa},
+    {0x37, 0xaa},
+    {0x38, 0xff},
+    {0x39, 0xff},
+    {0x3a, 0x79},
+    {0x3b, 0x00},
+    {0x3c, 0x00},
+    {0x3d, 0x0b},
+    {0x3e, 0x48},
+    {0x3f, 0x04},
+    {0x40, 0x00},
+    {0x41, 0x08},
+    {0x42, 0x00},
+    {0x43, 0x08},
+    {0x44, 0x08},
+    {0x45, 0x14},
+    {0x46, 0x05},
+    {0x47, 0x09},
+    {0x48, 0x00},
+    {0x49, 0x00},
+    {0x4a, 0x00},
+    {0x4b, 0x00},
+    {0x4c, 0x09},
+    {0x4d, 0x73},
+    {0x4e, 0x00},
+    {0x4f, 0xc5},
+    {0x50, 0x15},
+    {0x51, 0x19},
+    {0x52, 0x00},
+    {0x53, 0x00},
+    {0x54, 0x00},
+    {0x55, 0x00},
+    {0x56, 0x00},
+    {0x57, 0x00},
+    {0x58, 0x00},
+    {0x59, 0xb0},
+    {0x5a, 0x00},
+    {0x5b, 0x00},
+    {0x5c, 0x00},
+    {0x5d, 0x00},
+    {0x5e, 0x00},
+    {0x5f, 0x00},
+    {0x60, 0xe4},
+    {0x61, 0x80},
+    {0x62, 0x00},
+    {0x63, 0x00},
+    {0x64, 0x00},
+    {0x65, 0x00},
+    {0x66, 0x98},
+    {0x67, 0x0a},
+    {0x68, 0x00},
+    {0x69, 0x00},
+    {0x6a, 0x00},
+    {0x6b, 0x00},
+    //{0x6c, 0x80},
+    {0x6c, 0x00}, //RobertYu:20050125, request by JJSue
+    {0x6d, 0x03},
+    {0x6e, 0x01},
+    {0x6f, 0x00},
+    {0x70, 0x00},
+    {0x71, 0x00},
+    {0x72, 0x00},
+    {0x73, 0x00},
+    {0x74, 0x00},
+    {0x75, 0x00},
+    {0x76, 0x00},
+    {0x77, 0x00},
+    {0x78, 0x00},
+    {0x79, 0x00},
+    {0x7a, 0x00},
+    {0x7b, 0x00},
+    {0x7c, 0x00},
+    {0x7d, 0x00},
+    {0x7e, 0x00},
+    {0x7f, 0x00},
+    {0x80, 0x8c},
+    {0x81, 0x01},
+    {0x82, 0x09},
+    {0x83, 0x00},
+    {0x84, 0x00},
+    {0x85, 0x00},
+    {0x86, 0x00},
+    {0x87, 0x00},
+    {0x88, 0x08},
+    {0x89, 0x00},
+    {0x8a, 0x0f},
+    {0x8b, 0xb7},
+    {0x8c, 0x88},
+    {0x8d, 0x47},
+    {0x8e, 0xaa},
+    {0x8f, 0x02},
+    {0x90, 0x22},
+    {0x91, 0x00},
+    {0x92, 0x00},
+    {0x93, 0x00},
+    {0x94, 0x00},
+    {0x95, 0x00},
+    {0x96, 0x00},
+    {0x97, 0xeb},
+    {0x98, 0x00},
+    {0x99, 0x00},
+    {0x9a, 0x00},
+    {0x9b, 0x00},
+    {0x9c, 0x00},
+    {0x9d, 0x00},
+    {0x9e, 0x00},
+    {0x9f, 0x01},
+    {0xa0, 0x00},
+    {0xa1, 0x00},
+    {0xa2, 0x00},
+    {0xa3, 0x00},
+    {0xa4, 0x00},
+    {0xa5, 0x00},
+    {0xa6, 0x10},
+    {0xa7, 0x00},
+    {0xa8, 0x18},
+    {0xa9, 0x00},
+    {0xaa, 0x00},
+    {0xab, 0x00},
+    {0xac, 0x00},
+    {0xad, 0x00},
+    {0xae, 0x00},
+    {0xaf, 0x18},
+    {0xb0, 0x38},
+    {0xb1, 0x30},
+    {0xb2, 0x00},
+    {0xb3, 0x00},
+    {0xb4, 0xff},
+    {0xb5, 0x0f},
+    {0xb6, 0xe4},
+    {0xb7, 0xe2},
+    {0xb8, 0x00},
+    {0xb9, 0x00},
+    {0xba, 0x00},
+    {0xbb, 0x03},
+    {0xbc, 0x01},
+    {0xbd, 0x00},
+    {0xbe, 0x00},
+    {0xbf, 0x00},
+    {0xc0, 0x18},
+    {0xc1, 0x20},
+    {0xc2, 0x07},
+    {0xc3, 0x18},
+    {0xc4, 0xff},
+    {0xc5, 0x2c},
+    {0xc6, 0x0c},
+    {0xc7, 0x0a},
+    {0xc8, 0x0e},
+    {0xc9, 0x01},
+    {0xca, 0x68},
+    {0xcb, 0xa7},
+    {0xcc, 0x3c},
+    {0xcd, 0x10},
+    {0xce, 0x00},
+    {0xcf, 0x25},
+    {0xd0, 0x40},
+    {0xd1, 0x12},
+    {0xd2, 0x00},
+    {0xd3, 0x00},
+    {0xd4, 0x10},
+    {0xd5, 0x28},
+    {0xd6, 0x80},
+    {0xd7, 0x2A},
+    {0xd8, 0x00},
+    {0xd9, 0x00},
+    {0xda, 0x00},
+    {0xdb, 0x00},
+    {0xdc, 0x00},
+    {0xdd, 0x00},
+    {0xde, 0x00},
+    {0xdf, 0x00},
+    {0xe0, 0x00},
+    {0xe1, 0xB3},
+    {0xe2, 0x00},
+    {0xe3, 0x00},
+    {0xe4, 0x00},
+    {0xe5, 0x10},
+    {0xe6, 0x00},
+    {0xe7, 0x1C},
+    {0xe8, 0x00},
+    {0xe9, 0xf4},
+    {0xea, 0x00},
+    {0xeb, 0xff},
+    {0xec, 0x79},
+    {0xed, 0x20},
+    {0xee, 0x30},
+    {0xef, 0x01},
+    {0xf0, 0x00},
+    {0xf1, 0x3e},
+    {0xf2, 0x00},
+    {0xf3, 0x00},
+    {0xf4, 0x00},
+    {0xf5, 0x00},
+    {0xf6, 0x00},
+    {0xf7, 0x00},
+    {0xf8, 0x00},
+    {0xf9, 0x00},
+    {0xfa, 0x00},
+    {0xfb, 0x00},
+    {0xfc, 0x00},
+    {0xfd, 0x00},
+    {0xfe, 0x00},
+    {0xff, 0x00},
+};
+
+
+
+#define CB_VT3253B0_INIT_FOR_UW2451 256
+//For UW2451
+BYTE byVT3253B0_UW2451[CB_VT3253B0_INIT_FOR_UW2451][2] = {
+    {0x00, 0x31},
+    {0x01, 0x00},
+    {0x02, 0x00},
+    {0x03, 0x00},
+    {0x04, 0x00},
+    {0x05, 0x81},
+    {0x06, 0x00},
+    {0x07, 0x00},
+    {0x08, 0x38},
+    {0x09, 0x45},
+    {0x0a, 0x28},
+    {0x0b, 0x76},
+    {0x0c, 0x00},
+    {0x0d, 0x00},
+    {0x0e, 0x80},
+    {0x0f, 0x00},
+    {0x10, 0x00},
+    {0x11, 0x00},
+    {0x12, 0x00},
+    {0x13, 0x00},
+    {0x14, 0x00},
+    {0x15, 0x00},
+    {0x16, 0x00},
+    {0x17, 0x00},
+    {0x18, 0x00},
+    {0x19, 0x00},
+    {0x1a, 0x00},
+    {0x1b, 0x8f},
+    {0x1c, 0x0f},
+    {0x1d, 0x00},
+    {0x1e, 0x00},
+    {0x1f, 0x00},
+    {0x20, 0x00},
+    {0x21, 0x00},
+    {0x22, 0x00},
+    {0x23, 0x00},
+    {0x24, 0x00},
+    {0x25, 0x4a},
+    {0x26, 0x00},
+    {0x27, 0x00},
+    {0x28, 0x00},
+    {0x29, 0x00},
+    {0x2a, 0x00},
+    {0x2b, 0x00},
+    {0x2c, 0x00},
+    {0x2d, 0x18},
+    {0x2e, 0x00},
+    {0x2f, 0x0a},
+    {0x30, 0x26},
+    {0x31, 0x5b},
+    {0x32, 0x00},
+    {0x33, 0x00},
+    {0x34, 0x00},
+    {0x35, 0x00},
+    {0x36, 0xaa},
+    {0x37, 0xaa},
+    {0x38, 0xff},
+    {0x39, 0xff},
+    {0x3a, 0x00},
+    {0x3b, 0x00},
+    {0x3c, 0x00},
+    {0x3d, 0x03},
+    {0x3e, 0x1d},
+    {0x3f, 0x04},
+    {0x40, 0x00},
+    {0x41, 0x08},
+    {0x42, 0x00},
+    {0x43, 0x08},
+    {0x44, 0x08},
+    {0x45, 0x14},
+    {0x46, 0x05},
+    {0x47, 0x09},
+    {0x48, 0x00},
+    {0x49, 0x00},
+    {0x4a, 0x00},
+    {0x4b, 0x00},
+    {0x4c, 0x09},
+    {0x4d, 0x90},
+    {0x4e, 0x00},
+    {0x4f, 0xc5},
+    {0x50, 0x15},
+    {0x51, 0x19},
+    {0x52, 0x00},
+    {0x53, 0x00},
+    {0x54, 0x00},
+    {0x55, 0x00},
+    {0x56, 0x00},
+    {0x57, 0x00},
+    {0x58, 0x00},
+    {0x59, 0xb0},
+    {0x5a, 0x00},
+    {0x5b, 0x00},
+    {0x5c, 0x00},
+    {0x5d, 0x00},
+    {0x5e, 0x00},
+    {0x5f, 0x00},
+    {0x60, 0xb3},
+    {0x61, 0x81},
+    {0x62, 0x00},
+    {0x63, 0x00},
+    {0x64, 0x00},
+    {0x65, 0x00},
+    {0x66, 0x57},
+    {0x67, 0x6c},
+    {0x68, 0x00},
+    {0x69, 0x00},
+    {0x6a, 0x00},
+    {0x6b, 0x00},
+    //{0x6c, 0x80},
+    {0x6c, 0x00}, //RobertYu:20050125, request by JJSue
+    {0x6d, 0x03},
+    {0x6e, 0x01},
+    {0x6f, 0x00},
+    {0x70, 0x00},
+    {0x71, 0x00},
+    {0x72, 0x00},
+    {0x73, 0x00},
+    {0x74, 0x00},
+    {0x75, 0x00},
+    {0x76, 0x00},
+    {0x77, 0x00},
+    {0x78, 0x00},
+    {0x79, 0x00},
+    {0x7a, 0x00},
+    {0x7b, 0x00},
+    {0x7c, 0x00},
+    {0x7d, 0x00},
+    {0x7e, 0x00},
+    {0x7f, 0x00},
+    {0x80, 0x8c},
+    {0x81, 0x00},
+    {0x82, 0x0e},
+    {0x83, 0x00},
+    {0x84, 0x00},
+    {0x85, 0x00},
+    {0x86, 0x00},
+    {0x87, 0x00},
+    {0x88, 0x08},
+    {0x89, 0x00},
+    {0x8a, 0x0e},
+    {0x8b, 0xa7},
+    {0x8c, 0x88},
+    {0x8d, 0x47},
+    {0x8e, 0xaa},
+    {0x8f, 0x02},
+    {0x90, 0x00},
+    {0x91, 0x00},
+    {0x92, 0x00},
+    {0x93, 0x00},
+    {0x94, 0x00},
+    {0x95, 0x00},
+    {0x96, 0x00},
+    {0x97, 0xe3},
+    {0x98, 0x00},
+    {0x99, 0x00},
+    {0x9a, 0x00},
+    {0x9b, 0x00},
+    {0x9c, 0x00},
+    {0x9d, 0x00},
+    {0x9e, 0x00},
+    {0x9f, 0x00},
+    {0xa0, 0x00},
+    {0xa1, 0x00},
+    {0xa2, 0x00},
+    {0xa3, 0x00},
+    {0xa4, 0x00},
+    {0xa5, 0x00},
+    {0xa6, 0x10},
+    {0xa7, 0x00},
+    {0xa8, 0x18},
+    {0xa9, 0x00},
+    {0xaa, 0x00},
+    {0xab, 0x00},
+    {0xac, 0x00},
+    {0xad, 0x00},
+    {0xae, 0x00},
+    {0xaf, 0x18},
+    {0xb0, 0x18},
+    {0xb1, 0x30},
+    {0xb2, 0x00},
+    {0xb3, 0x00},
+    {0xb4, 0x00},
+    {0xb5, 0x00},
+    {0xb6, 0x00},
+    {0xb7, 0x00},
+    {0xb8, 0x00},
+    {0xb9, 0x00},
+    {0xba, 0x00},
+    {0xbb, 0x03},
+    {0xbc, 0x01},
+    {0xbd, 0x00},
+    {0xbe, 0x00},
+    {0xbf, 0x00},
+    {0xc0, 0x10},
+    {0xc1, 0x20},
+    {0xc2, 0x00},
+    {0xc3, 0x20},
+    {0xc4, 0x00},
+    {0xc5, 0x2c},
+    {0xc6, 0x1c},
+    {0xc7, 0x10},
+    {0xc8, 0x10},
+    {0xc9, 0x01},
+    {0xca, 0x68},
+    {0xcb, 0xa7},
+    {0xcc, 0x3c},
+    {0xcd, 0x09},
+    {0xce, 0x00},
+    {0xcf, 0x20},
+    {0xd0, 0x40},
+    {0xd1, 0x10},
+    {0xd2, 0x00},
+    {0xd3, 0x00},
+    {0xd4, 0x20},
+    {0xd5, 0x28},
+    {0xd6, 0xa0},
+    {0xd7, 0x2a},
+    {0xd8, 0x00},
+    {0xd9, 0x00},
+    {0xda, 0x00},
+    {0xdb, 0x00},
+    {0xdc, 0x00},
+    {0xdd, 0x00},
+    {0xde, 0x00},
+    {0xdf, 0x00},
+    {0xe0, 0x00},
+    {0xe1, 0xd3},
+    {0xe2, 0xc0},
+    {0xe3, 0x00},
+    {0xe4, 0x00},
+    {0xe5, 0x10},
+    {0xe6, 0x00},
+    {0xe7, 0x12},
+    {0xe8, 0x12},
+    {0xe9, 0x34},
+    {0xea, 0x00},
+    {0xeb, 0xff},
+    {0xec, 0x79},
+    {0xed, 0x20},
+    {0xee, 0x30},
+    {0xef, 0x01},
+    {0xf0, 0x00},
+    {0xf1, 0x3e},
+    {0xf2, 0x00},
+    {0xf3, 0x00},
+    {0xf4, 0x00},
+    {0xf5, 0x00},
+    {0xf6, 0x00},
+    {0xf7, 0x00},
+    {0xf8, 0x00},
+    {0xf9, 0x00},
+    {0xfa, 0x00},
+    {0xfb, 0x00},
+    {0xfc, 0x00},
+    {0xfd, 0x00},
+    {0xfe, 0x00},
+    {0xff, 0x00},
+};
+
+#define CB_VT3253B0_AGC 193
+// For AIROHA
+BYTE byVT3253B0_AGC[CB_VT3253B0_AGC][2] = {
+    {0xF0, 0x00},
+    {0xF1, 0x00},
+    {0xF0, 0x80},
+    {0xF0, 0x01},
+    {0xF1, 0x00},
+    {0xF0, 0x81},
+    {0xF0, 0x02},
+    {0xF1, 0x02},
+    {0xF0, 0x82},
+    {0xF0, 0x03},
+    {0xF1, 0x04},
+    {0xF0, 0x83},
+    {0xF0, 0x03},
+    {0xF1, 0x04},
+    {0xF0, 0x84},
+    {0xF0, 0x04},
+    {0xF1, 0x06},
+    {0xF0, 0x85},
+    {0xF0, 0x05},
+    {0xF1, 0x06},
+    {0xF0, 0x86},
+    {0xF0, 0x06},
+    {0xF1, 0x06},
+    {0xF0, 0x87},
+    {0xF0, 0x07},
+    {0xF1, 0x08},
+    {0xF0, 0x88},
+    {0xF0, 0x08},
+    {0xF1, 0x08},
+    {0xF0, 0x89},
+    {0xF0, 0x09},
+    {0xF1, 0x0A},
+    {0xF0, 0x8A},
+    {0xF0, 0x0A},
+    {0xF1, 0x0A},
+    {0xF0, 0x8B},
+    {0xF0, 0x0B},
+    {0xF1, 0x0C},
+    {0xF0, 0x8C},
+    {0xF0, 0x0C},
+    {0xF1, 0x0C},
+    {0xF0, 0x8D},
+    {0xF0, 0x0D},
+    {0xF1, 0x0E},
+    {0xF0, 0x8E},
+    {0xF0, 0x0E},
+    {0xF1, 0x0E},
+    {0xF0, 0x8F},
+    {0xF0, 0x0F},
+    {0xF1, 0x10},
+    {0xF0, 0x90},
+    {0xF0, 0x10},
+    {0xF1, 0x10},
+    {0xF0, 0x91},
+    {0xF0, 0x11},
+    {0xF1, 0x12},
+    {0xF0, 0x92},
+    {0xF0, 0x12},
+    {0xF1, 0x12},
+    {0xF0, 0x93},
+    {0xF0, 0x13},
+    {0xF1, 0x14},
+    {0xF0, 0x94},
+    {0xF0, 0x14},
+    {0xF1, 0x14},
+    {0xF0, 0x95},
+    {0xF0, 0x15},
+    {0xF1, 0x16},
+    {0xF0, 0x96},
+    {0xF0, 0x16},
+    {0xF1, 0x16},
+    {0xF0, 0x97},
+    {0xF0, 0x17},
+    {0xF1, 0x18},
+    {0xF0, 0x98},
+    {0xF0, 0x18},
+    {0xF1, 0x18},
+    {0xF0, 0x99},
+    {0xF0, 0x19},
+    {0xF1, 0x1A},
+    {0xF0, 0x9A},
+    {0xF0, 0x1A},
+    {0xF1, 0x1A},
+    {0xF0, 0x9B},
+    {0xF0, 0x1B},
+    {0xF1, 0x1C},
+    {0xF0, 0x9C},
+    {0xF0, 0x1C},
+    {0xF1, 0x1C},
+    {0xF0, 0x9D},
+    {0xF0, 0x1D},
+    {0xF1, 0x1E},
+    {0xF0, 0x9E},
+    {0xF0, 0x1E},
+    {0xF1, 0x1E},
+    {0xF0, 0x9F},
+    {0xF0, 0x1F},
+    {0xF1, 0x20},
+    {0xF0, 0xA0},
+    {0xF0, 0x20},
+    {0xF1, 0x20},
+    {0xF0, 0xA1},
+    {0xF0, 0x21},
+    {0xF1, 0x22},
+    {0xF0, 0xA2},
+    {0xF0, 0x22},
+    {0xF1, 0x22},
+    {0xF0, 0xA3},
+    {0xF0, 0x23},
+    {0xF1, 0x24},
+    {0xF0, 0xA4},
+    {0xF0, 0x24},
+    {0xF1, 0x24},
+    {0xF0, 0xA5},
+    {0xF0, 0x25},
+    {0xF1, 0x26},
+    {0xF0, 0xA6},
+    {0xF0, 0x26},
+    {0xF1, 0x26},
+    {0xF0, 0xA7},
+    {0xF0, 0x27},
+    {0xF1, 0x28},
+    {0xF0, 0xA8},
+    {0xF0, 0x28},
+    {0xF1, 0x28},
+    {0xF0, 0xA9},
+    {0xF0, 0x29},
+    {0xF1, 0x2A},
+    {0xF0, 0xAA},
+    {0xF0, 0x2A},
+    {0xF1, 0x2A},
+    {0xF0, 0xAB},
+    {0xF0, 0x2B},
+    {0xF1, 0x2C},
+    {0xF0, 0xAC},
+    {0xF0, 0x2C},
+    {0xF1, 0x2C},
+    {0xF0, 0xAD},
+    {0xF0, 0x2D},
+    {0xF1, 0x2E},
+    {0xF0, 0xAE},
+    {0xF0, 0x2E},
+    {0xF1, 0x2E},
+    {0xF0, 0xAF},
+    {0xF0, 0x2F},
+    {0xF1, 0x30},
+    {0xF0, 0xB0},
+    {0xF0, 0x30},
+    {0xF1, 0x30},
+    {0xF0, 0xB1},
+    {0xF0, 0x31},
+    {0xF1, 0x32},
+    {0xF0, 0xB2},
+    {0xF0, 0x32},
+    {0xF1, 0x32},
+    {0xF0, 0xB3},
+    {0xF0, 0x33},
+    {0xF1, 0x34},
+    {0xF0, 0xB4},
+    {0xF0, 0x34},
+    {0xF1, 0x34},
+    {0xF0, 0xB5},
+    {0xF0, 0x35},
+    {0xF1, 0x36},
+    {0xF0, 0xB6},
+    {0xF0, 0x36},
+    {0xF1, 0x36},
+    {0xF0, 0xB7},
+    {0xF0, 0x37},
+    {0xF1, 0x38},
+    {0xF0, 0xB8},
+    {0xF0, 0x38},
+    {0xF1, 0x38},
+    {0xF0, 0xB9},
+    {0xF0, 0x39},
+    {0xF1, 0x3A},
+    {0xF0, 0xBA},
+    {0xF0, 0x3A},
+    {0xF1, 0x3A},
+    {0xF0, 0xBB},
+    {0xF0, 0x3B},
+    {0xF1, 0x3C},
+    {0xF0, 0xBC},
+    {0xF0, 0x3C},
+    {0xF1, 0x3C},
+    {0xF0, 0xBD},
+    {0xF0, 0x3D},
+    {0xF1, 0x3E},
+    {0xF0, 0xBE},
+    {0xF0, 0x3E},
+    {0xF1, 0x3E},
+    {0xF0, 0xBF},
+    {0xF0, 0x00},
+};
+
+const WORD awcFrameTime[MAX_RATE] =
+{10, 20, 55, 110, 24, 36, 48, 72, 96, 144, 192, 216};
+
+
+/*---------------------  Static Functions  --------------------------*/
+
+static
+ULONG
+s_ulGetRatio(PSDevice pDevice);
+
+static
+VOID
+s_vChangeAntenna(
+    IN PSDevice pDevice
+    );
+
+static
+VOID
+s_vChangeAntenna (
+    IN PSDevice pDevice
+    )
+{
+
+#ifdef	PLICE_DEBUG
+	//printk("Enter s_vChangeAntenna:original RxMode is %d,TxMode is %d\n",pDevice->byRxAntennaMode,pDevice->byTxAntennaMode);
+#endif
+    if ( pDevice->dwRxAntennaSel == 0) {
+        pDevice->dwRxAntennaSel=1;
+        if (pDevice->bTxRxAntInv == TRUE)
+            BBvSetRxAntennaMode(pDevice->PortOffset, ANT_A);
+        else
+            BBvSetRxAntennaMode(pDevice->PortOffset, ANT_B);
+    } else {
+        pDevice->dwRxAntennaSel=0;
+        if (pDevice->bTxRxAntInv == TRUE)
+            BBvSetRxAntennaMode(pDevice->PortOffset, ANT_B);
+        else
+            BBvSetRxAntennaMode(pDevice->PortOffset, ANT_A);
+    }
+    if ( pDevice->dwTxAntennaSel == 0) {
+        pDevice->dwTxAntennaSel=1;
+        BBvSetTxAntennaMode(pDevice->PortOffset, ANT_B);
+    } else {
+        pDevice->dwTxAntennaSel=0;
+        BBvSetTxAntennaMode(pDevice->PortOffset, ANT_A);
+    }
+}
+
+
+/*---------------------  Export Variables  --------------------------*/
+/*
+ * Description: Calculate data frame transmitting time
+ *
+ * Parameters:
+ *  In:
+ *      byPreambleType  - Preamble Type
+ *      byPktType        - PK_TYPE_11A, PK_TYPE_11B, PK_TYPE_11GB, PK_TYPE_11GA
+ *      cbFrameLength   - Baseband Type
+ *      wRate           - Tx Rate
+ *  Out:
+ *
+ * Return Value: FrameTime
+ *
+ */
+UINT
+BBuGetFrameTime (
+    IN BYTE byPreambleType,
+    IN BYTE byPktType,
+    IN UINT cbFrameLength,
+    IN WORD wRate
+    )
+{
+    UINT uFrameTime;
+    UINT uPreamble;
+    UINT uTmp;
+    UINT uRateIdx = (UINT)wRate;
+    UINT uRate = 0;
+
+
+    if (uRateIdx > RATE_54M) {
+        return 0;
+    }
+
+    uRate = (UINT)awcFrameTime[uRateIdx];
+
+    if (uRateIdx <= 3) {          //CCK mode
+
+        if (byPreambleType == 1) {//Short
+            uPreamble = 96;
+        } else {
+            uPreamble = 192;
+        }
+        uFrameTime = (cbFrameLength * 80) / uRate;  //?????
+        uTmp = (uFrameTime * uRate) / 80;
+        if (cbFrameLength != uTmp) {
+            uFrameTime ++;
+        }
+
+        return (uPreamble + uFrameTime);
+    }
+    else {
+        uFrameTime = (cbFrameLength * 8 + 22) / uRate;   //????????
+        uTmp = ((uFrameTime * uRate) - 22) / 8;
+        if(cbFrameLength != uTmp) {
+            uFrameTime ++;
+        }
+        uFrameTime = uFrameTime * 4;    //???????
+        if(byPktType != PK_TYPE_11A) {
+            uFrameTime += 6;     //??????
+        }
+        return (20 + uFrameTime); //??????
+    }
+}
+
+/*
+ * Description: Caculate Length, Service, and Signal fields of Phy for Tx
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - Device Structure
+ *      cbFrameLength   - Tx Frame Length
+ *      wRate           - Tx Rate
+ *  Out:
+ *      pwPhyLen        - pointer to Phy Length field
+ *      pbyPhySrv       - pointer to Phy Service field
+ *      pbyPhySgn       - pointer to Phy Signal field
+ *
+ * Return Value: none
+ *
+ */
+VOID
+BBvCaculateParameter (
+    IN  PSDevice pDevice,
+    IN  UINT cbFrameLength,
+    IN  WORD wRate,
+    IN  BYTE byPacketType,
+    OUT PWORD pwPhyLen,
+    OUT PBYTE pbyPhySrv,
+    OUT PBYTE pbyPhySgn
+    )
+{
+    UINT cbBitCount;
+    UINT cbUsCount = 0;
+    UINT cbTmp;
+    BOOL bExtBit;
+    BYTE byPreambleType = pDevice->byPreambleType;
+    BOOL bCCK = pDevice->bCCK;
+
+    cbBitCount = cbFrameLength * 8;
+    bExtBit = FALSE;
+
+    switch (wRate) {
+    case RATE_1M :
+        cbUsCount = cbBitCount;
+        *pbyPhySgn = 0x00;
+        break;
+
+    case RATE_2M :
+        cbUsCount = cbBitCount / 2;
+        if (byPreambleType == 1)
+            *pbyPhySgn = 0x09;
+        else // long preamble
+            *pbyPhySgn = 0x01;
+        break;
+
+    case RATE_5M :
+        if (bCCK == FALSE)
+            cbBitCount ++;
+        cbUsCount = (cbBitCount * 10) / 55;
+        cbTmp = (cbUsCount * 55) / 10;
+        if (cbTmp != cbBitCount)
+            cbUsCount ++;
+        if (byPreambleType == 1)
+            *pbyPhySgn = 0x0a;
+        else // long preamble
+            *pbyPhySgn = 0x02;
+        break;
+
+    case RATE_11M :
+
+        if (bCCK == FALSE)
+            cbBitCount ++;
+        cbUsCount = cbBitCount / 11;
+        cbTmp = cbUsCount * 11;
+        if (cbTmp != cbBitCount) {
+            cbUsCount ++;
+            if ((cbBitCount - cbTmp) <= 3)
+                bExtBit = TRUE;
+        }
+        if (byPreambleType == 1)
+            *pbyPhySgn = 0x0b;
+        else // long preamble
+            *pbyPhySgn = 0x03;
+        break;
+
+    case RATE_6M :
+        if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
+            *pbyPhySgn = 0x9B; //1001 1011
+        }
+        else {//11g, 2.4GHZ
+            *pbyPhySgn = 0x8B; //1000 1011
+        }
+        break;
+
+    case RATE_9M :
+        if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
+            *pbyPhySgn = 0x9F; //1001 1111
+        }
+        else {//11g, 2.4GHZ
+            *pbyPhySgn = 0x8F; //1000 1111
+        }
+        break;
+
+    case RATE_12M :
+        if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
+            *pbyPhySgn = 0x9A; //1001 1010
+        }
+        else {//11g, 2.4GHZ
+            *pbyPhySgn = 0x8A; //1000 1010
+        }
+        break;
+
+    case RATE_18M :
+        if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
+            *pbyPhySgn = 0x9E; //1001 1110
+        }
+        else {//11g, 2.4GHZ
+            *pbyPhySgn = 0x8E; //1000 1110
+        }
+        break;
+
+    case RATE_24M :
+        if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
+            *pbyPhySgn = 0x99; //1001 1001
+        }
+        else {//11g, 2.4GHZ
+            *pbyPhySgn = 0x89; //1000 1001
+        }
+        break;
+
+    case RATE_36M :
+        if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
+            *pbyPhySgn = 0x9D; //1001 1101
+        }
+        else {//11g, 2.4GHZ
+            *pbyPhySgn = 0x8D; //1000 1101
+        }
+        break;
+
+    case RATE_48M :
+        if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
+            *pbyPhySgn = 0x98; //1001 1000
+        }
+        else {//11g, 2.4GHZ
+            *pbyPhySgn = 0x88; //1000 1000
+        }
+        break;
+
+    case RATE_54M :
+        if (byPacketType == PK_TYPE_11A) {//11a, 5GHZ
+            *pbyPhySgn = 0x9C; //1001 1100
+        }
+        else {//11g, 2.4GHZ
+            *pbyPhySgn = 0x8C; //1000 1100
+        }
+        break;
+
+    default :
+        if (byPacketType == PK_TYPE_11A) {//11a, 5GHZ
+            *pbyPhySgn = 0x9C; //1001 1100
+        }
+        else {//11g, 2.4GHZ
+            *pbyPhySgn = 0x8C; //1000 1100
+        }
+        break;
+    }
+
+    if (byPacketType == PK_TYPE_11B) {
+        *pbyPhySrv = 0x00;
+        if (bExtBit)
+            *pbyPhySrv = *pbyPhySrv | 0x80;
+        *pwPhyLen = (WORD)cbUsCount;
+    }
+    else {
+        *pbyPhySrv = 0x00;
+        *pwPhyLen = (WORD)cbFrameLength;
+    }
+}
+
+/*
+ * Description: Read a byte from BASEBAND, by embeded programming
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      byBBAddr    - address of register in Baseband
+ *  Out:
+ *      pbyData     - data read
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL BBbReadEmbeded (DWORD_PTR dwIoBase, BYTE byBBAddr, PBYTE pbyData)
+{
+    WORD    ww;
+    BYTE    byValue;
+
+    // BB reg offset
+    VNSvOutPortB(dwIoBase + MAC_REG_BBREGADR, byBBAddr);
+
+    // turn on REGR
+    MACvRegBitsOn(dwIoBase, MAC_REG_BBREGCTL, BBREGCTL_REGR);
+    // W_MAX_TIMEOUT is the timeout period
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_BBREGCTL, &byValue);
+        if (BITbIsBitOn(byValue, BBREGCTL_DONE))
+            break;
+    }
+
+    // get BB data
+    VNSvInPortB(dwIoBase + MAC_REG_BBREGDATA, pbyData);
+
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x30);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x30)\n");
+        return FALSE;
+    }
+    return TRUE;
+}
+
+
+/*
+ * Description: Write a Byte to BASEBAND, by embeded programming
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      byBBAddr    - address of register in Baseband
+ *      byData      - data to write
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL BBbWriteEmbeded (DWORD_PTR dwIoBase, BYTE byBBAddr, BYTE byData)
+{
+    WORD    ww;
+    BYTE    byValue;
+
+    // BB reg offset
+    VNSvOutPortB(dwIoBase + MAC_REG_BBREGADR, byBBAddr);
+    // set BB data
+    VNSvOutPortB(dwIoBase + MAC_REG_BBREGDATA, byData);
+
+    // turn on BBREGCTL_REGW
+    MACvRegBitsOn(dwIoBase, MAC_REG_BBREGCTL, BBREGCTL_REGW);
+    // W_MAX_TIMEOUT is the timeout period
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_BBREGCTL, &byValue);
+        if (BITbIsBitOn(byValue, BBREGCTL_DONE))
+            break;
+    }
+
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x31);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x31)\n");
+        return FALSE;
+    }
+    return TRUE;
+}
+
+
+/*
+ * Description: Test if all bits are set for the Baseband register
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      byBBAddr    - address of register in Baseband
+ *      byTestBits  - TestBits
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if all TestBits are set; FALSE otherwise.
+ *
+ */
+BOOL BBbIsRegBitsOn (DWORD_PTR dwIoBase, BYTE byBBAddr, BYTE byTestBits)
+{
+    BYTE byOrgData;
+
+    BBbReadEmbeded(dwIoBase, byBBAddr, &byOrgData);
+    return BITbIsAllBitsOn(byOrgData, byTestBits);
+}
+
+
+/*
+ * Description: Test if all bits are clear for the Baseband register
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      byBBAddr    - address of register in Baseband
+ *      byTestBits  - TestBits
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if all TestBits are clear; FALSE otherwise.
+ *
+ */
+BOOL BBbIsRegBitsOff (DWORD_PTR dwIoBase, BYTE byBBAddr, BYTE byTestBits)
+{
+    BYTE byOrgData;
+
+    BBbReadEmbeded(dwIoBase, byBBAddr, &byOrgData);
+    return BITbIsAllBitsOff(byOrgData, byTestBits);
+}
+
+/*
+ * Description: VIA VT3253 Baseband chip init function
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      byRevId     - Revision ID
+ *      byRFType    - RF type
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+
+BOOL BBbVT3253Init (PSDevice pDevice)
+{
+    BOOL       bResult = TRUE;
+    int        ii;
+    DWORD_PTR  dwIoBase = pDevice->PortOffset;
+    BYTE       byRFType = pDevice->byRFType;
+    BYTE       byLocalID = pDevice->byLocalID;
+
+    if (byRFType == RF_RFMD2959) {
+        if (byLocalID <= REV_ID_VT3253_A1) {
+            for (ii = 0; ii < CB_VT3253_INIT_FOR_RFMD; ii++) {
+                bResult &= BBbWriteEmbeded(dwIoBase,byVT3253InitTab_RFMD[ii][0],byVT3253InitTab_RFMD[ii][1]);
+            }
+        } else {
+            for (ii = 0; ii < CB_VT3253B0_INIT_FOR_RFMD; ii++) {
+                bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_RFMD[ii][0],byVT3253B0_RFMD[ii][1]);
+            }
+            for (ii = 0; ii < CB_VT3253B0_AGC_FOR_RFMD2959; ii++) {
+        	    bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_AGC4_RFMD2959[ii][0],byVT3253B0_AGC4_RFMD2959[ii][1]);
+            }
+            VNSvOutPortD(dwIoBase + MAC_REG_ITRTMSET, 0x23);
+            MACvRegBitsOn(dwIoBase, MAC_REG_PAPEDELAY, BIT0);
+        }
+        pDevice->abyBBVGA[0] = 0x18;
+        pDevice->abyBBVGA[1] = 0x0A;
+        pDevice->abyBBVGA[2] = 0x0;
+        pDevice->abyBBVGA[3] = 0x0;
+        pDevice->ldBmThreshold[0] = -70;
+        pDevice->ldBmThreshold[1] = -50;
+        pDevice->ldBmThreshold[2] = 0;
+        pDevice->ldBmThreshold[3] = 0;
+    } else if ((byRFType == RF_AIROHA) || (byRFType == RF_AL2230S) ) {
+        for (ii = 0; ii < CB_VT3253B0_INIT_FOR_AIROHA2230; ii++) {
+    	    bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_AIROHA2230[ii][0],byVT3253B0_AIROHA2230[ii][1]);
+    	}
+        for (ii = 0; ii < CB_VT3253B0_AGC; ii++) {
+    	    bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_AGC[ii][0],byVT3253B0_AGC[ii][1]);
+    	}
+        pDevice->abyBBVGA[0] = 0x1C;
+        pDevice->abyBBVGA[1] = 0x10;
+        pDevice->abyBBVGA[2] = 0x0;
+        pDevice->abyBBVGA[3] = 0x0;
+        pDevice->ldBmThreshold[0] = -70;
+        pDevice->ldBmThreshold[1] = -48;
+        pDevice->ldBmThreshold[2] = 0;
+        pDevice->ldBmThreshold[3] = 0;
+    } else if (byRFType == RF_UW2451) {
+        for (ii = 0; ii < CB_VT3253B0_INIT_FOR_UW2451; ii++) {
+    	        bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_UW2451[ii][0],byVT3253B0_UW2451[ii][1]);
+    	}
+        for (ii = 0; ii < CB_VT3253B0_AGC; ii++) {
+    	    bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_AGC[ii][0],byVT3253B0_AGC[ii][1]);
+    	}
+        VNSvOutPortB(dwIoBase + MAC_REG_ITRTMSET, 0x23);
+        MACvRegBitsOn(dwIoBase, MAC_REG_PAPEDELAY, BIT0);
+
+        pDevice->abyBBVGA[0] = 0x14;
+        pDevice->abyBBVGA[1] = 0x0A;
+        pDevice->abyBBVGA[2] = 0x0;
+        pDevice->abyBBVGA[3] = 0x0;
+        pDevice->ldBmThreshold[0] = -60;
+        pDevice->ldBmThreshold[1] = -50;
+        pDevice->ldBmThreshold[2] = 0;
+        pDevice->ldBmThreshold[3] = 0;
+    } else if (byRFType == RF_UW2452) {
+        for (ii = 0; ii < CB_VT3253B0_INIT_FOR_UW2451; ii++) {
+            bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_UW2451[ii][0],byVT3253B0_UW2451[ii][1]);
+    	}
+        // Init ANT B select,TX Config CR09 = 0x61->0x45, 0x45->0x41(VC1/VC2 define, make the ANT_A, ANT_B inverted)
+        //bResult &= BBbWriteEmbeded(dwIoBase,0x09,0x41);
+        // Init ANT B select,RX Config CR10 = 0x28->0x2A, 0x2A->0x28(VC1/VC2 define, make the ANT_A, ANT_B inverted)
+        //bResult &= BBbWriteEmbeded(dwIoBase,0x0a,0x28);
+        // Select VC1/VC2, CR215 = 0x02->0x06
+        bResult &= BBbWriteEmbeded(dwIoBase,0xd7,0x06);
+
+        //{{RobertYu:20050125, request by Jack
+        bResult &= BBbWriteEmbeded(dwIoBase,0x90,0x20);
+        bResult &= BBbWriteEmbeded(dwIoBase,0x97,0xeb);
+        //}}
+
+        //{{RobertYu:20050221, request by Jack
+        bResult &= BBbWriteEmbeded(dwIoBase,0xa6,0x00);
+        bResult &= BBbWriteEmbeded(dwIoBase,0xa8,0x30);
+        //}}
+        bResult &= BBbWriteEmbeded(dwIoBase,0xb0,0x58);
+
+        for (ii = 0; ii < CB_VT3253B0_AGC; ii++) {
+    	    bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_AGC[ii][0],byVT3253B0_AGC[ii][1]);
+    	}
+        //VNSvOutPortB(dwIoBase + MAC_REG_ITRTMSET, 0x23); // RobertYu: 20050104, 20050131 disable PA_Delay
+        //MACvRegBitsOn(dwIoBase, MAC_REG_PAPEDELAY, BIT0); // RobertYu: 20050104, 20050131 disable PA_Delay
+
+        pDevice->abyBBVGA[0] = 0x14;
+        pDevice->abyBBVGA[1] = 0x0A;
+        pDevice->abyBBVGA[2] = 0x0;
+        pDevice->abyBBVGA[3] = 0x0;
+        pDevice->ldBmThreshold[0] = -60;
+        pDevice->ldBmThreshold[1] = -50;
+        pDevice->ldBmThreshold[2] = 0;
+        pDevice->ldBmThreshold[3] = 0;
+    //}} RobertYu
+
+    } else if (byRFType == RF_VT3226) {
+        for (ii = 0; ii < CB_VT3253B0_INIT_FOR_AIROHA2230; ii++) {
+    	    bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_AIROHA2230[ii][0],byVT3253B0_AIROHA2230[ii][1]);
+    	}
+        for (ii = 0; ii < CB_VT3253B0_AGC; ii++) {
+    	    bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_AGC[ii][0],byVT3253B0_AGC[ii][1]);
+    	}
+        pDevice->abyBBVGA[0] = 0x1C;
+        pDevice->abyBBVGA[1] = 0x10;
+        pDevice->abyBBVGA[2] = 0x0;
+        pDevice->abyBBVGA[3] = 0x0;
+        pDevice->ldBmThreshold[0] = -70;
+        pDevice->ldBmThreshold[1] = -48;
+        pDevice->ldBmThreshold[2] = 0;
+        pDevice->ldBmThreshold[3] = 0;
+        // Fix VT3226 DFC system timing issue
+        MACvSetRFLE_LatchBase(dwIoBase);
+         //{{ RobertYu: 20050104
+    } else if (byRFType == RF_AIROHA7230) {
+        for (ii = 0; ii < CB_VT3253B0_INIT_FOR_AIROHA2230; ii++) {
+    	    bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_AIROHA2230[ii][0],byVT3253B0_AIROHA2230[ii][1]);
+    	}
+
+        //{{ RobertYu:20050223, request by JerryChung
+        // Init ANT B select,TX Config CR09 = 0x61->0x45, 0x45->0x41(VC1/VC2 define, make the ANT_A, ANT_B inverted)
+        //bResult &= BBbWriteEmbeded(dwIoBase,0x09,0x41);
+        // Init ANT B select,RX Config CR10 = 0x28->0x2A, 0x2A->0x28(VC1/VC2 define, make the ANT_A, ANT_B inverted)
+        //bResult &= BBbWriteEmbeded(dwIoBase,0x0a,0x28);
+        // Select VC1/VC2, CR215 = 0x02->0x06
+        bResult &= BBbWriteEmbeded(dwIoBase,0xd7,0x06);
+        //}}
+
+        for (ii = 0; ii < CB_VT3253B0_AGC; ii++) {
+    	    bResult &= BBbWriteEmbeded(dwIoBase,byVT3253B0_AGC[ii][0],byVT3253B0_AGC[ii][1]);
+    	}
+        pDevice->abyBBVGA[0] = 0x1C;
+        pDevice->abyBBVGA[1] = 0x10;
+        pDevice->abyBBVGA[2] = 0x0;
+        pDevice->abyBBVGA[3] = 0x0;
+        pDevice->ldBmThreshold[0] = -70;
+        pDevice->ldBmThreshold[1] = -48;
+        pDevice->ldBmThreshold[2] = 0;
+        pDevice->ldBmThreshold[3] = 0;
+    //}} RobertYu
+    } else {
+    	// No VGA Table now
+    	pDevice->bUpdateBBVGA = FALSE;
+        pDevice->abyBBVGA[0] = 0x1C;
+    }
+
+    if (byLocalID > REV_ID_VT3253_A1) {
+        BBbWriteEmbeded(dwIoBase, 0x04, 0x7F);
+        BBbWriteEmbeded(dwIoBase, 0x0D, 0x01);
+    }
+
+    return bResult;
+}
+
+
+
+/*
+ * Description: Read All Baseband Registers
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      pbyBBRegs   - Point to struct that stores Baseband Registers
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+VOID BBvReadAllRegs (DWORD_PTR dwIoBase, PBYTE pbyBBRegs)
+{
+    int  ii;
+    BYTE byBase = 1;
+    for (ii = 0; ii < BB_MAX_CONTEXT_SIZE; ii++) {
+        BBbReadEmbeded(dwIoBase, (BYTE)(ii*byBase), pbyBBRegs);
+        pbyBBRegs += byBase;
+    }
+}
+
+/*
+ * Description: Turn on BaseBand Loopback mode
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      bCCK        - If CCK is set
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+
+
+void BBvLoopbackOn (PSDevice pDevice)
+{
+    BYTE      byData;
+    DWORD_PTR dwIoBase = pDevice->PortOffset;
+
+    //CR C9 = 0x00
+    BBbReadEmbeded(dwIoBase, 0xC9, &pDevice->byBBCRc9);//CR201
+    BBbWriteEmbeded(dwIoBase, 0xC9, 0);
+    BBbReadEmbeded(dwIoBase, 0x4D, &pDevice->byBBCR4d);//CR77
+    BBbWriteEmbeded(dwIoBase, 0x4D, 0x90);
+
+    //CR 88 = 0x02(CCK), 0x03(OFDM)
+    BBbReadEmbeded(dwIoBase, 0x88, &pDevice->byBBCR88);//CR136
+
+    if (pDevice->uConnectionRate <= RATE_11M) { //CCK
+        // Enable internal digital loopback: CR33 |= 0000 0001
+        BBbReadEmbeded(dwIoBase, 0x21, &byData);//CR33
+        BBbWriteEmbeded(dwIoBase, 0x21, (BYTE)(byData | 0x01));//CR33
+        // CR154 = 0x00
+        BBbWriteEmbeded(dwIoBase, 0x9A, 0);   //CR154
+
+        BBbWriteEmbeded(dwIoBase, 0x88, 0x02);//CR239
+    }
+    else { //OFDM
+        // Enable internal digital loopback:CR154 |= 0000 0001
+        BBbReadEmbeded(dwIoBase, 0x9A, &byData);//CR154
+        BBbWriteEmbeded(dwIoBase, 0x9A, (BYTE)(byData | 0x01));//CR154
+        // CR33 = 0x00
+        BBbWriteEmbeded(dwIoBase, 0x21, 0);   //CR33
+
+        BBbWriteEmbeded(dwIoBase, 0x88, 0x03);//CR239
+    }
+
+    //CR14 = 0x00
+    BBbWriteEmbeded(dwIoBase, 0x0E, 0);//CR14
+
+    // Disable TX_IQUN
+    BBbReadEmbeded(pDevice->PortOffset, 0x09, &pDevice->byBBCR09);
+    BBbWriteEmbeded(pDevice->PortOffset, 0x09, (BYTE)(pDevice->byBBCR09 & 0xDE));
+}
+
+/*
+ * Description: Turn off BaseBand Loopback mode
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - Device Structure
+ *
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void BBvLoopbackOff (PSDevice pDevice)
+{
+    BYTE      byData;
+    DWORD_PTR dwIoBase = pDevice->PortOffset;
+
+    BBbWriteEmbeded(dwIoBase, 0xC9, pDevice->byBBCRc9);//CR201
+    BBbWriteEmbeded(dwIoBase, 0x88, pDevice->byBBCR88);//CR136
+    BBbWriteEmbeded(dwIoBase, 0x09, pDevice->byBBCR09);//CR136
+    BBbWriteEmbeded(dwIoBase, 0x4D, pDevice->byBBCR4d);//CR77
+
+    if (pDevice->uConnectionRate <= RATE_11M) { // CCK
+        // Set the CR33 Bit2 to disable internal Loopback.
+        BBbReadEmbeded(dwIoBase, 0x21, &byData);//CR33
+        BBbWriteEmbeded(dwIoBase, 0x21, (BYTE)(byData & 0xFE));//CR33
+    }
+    else { // OFDM
+        BBbReadEmbeded(dwIoBase, 0x9A, &byData);//CR154
+        BBbWriteEmbeded(dwIoBase, 0x9A, (BYTE)(byData & 0xFE));//CR154
+    }
+    BBbReadEmbeded(dwIoBase, 0x0E, &byData);//CR14
+    BBbWriteEmbeded(dwIoBase, 0x0E, (BYTE)(byData | 0x80));//CR14
+
+}
+
+
+
+/*
+ * Description: Set ShortSlotTime mode
+ *
+ * Parameters:
+ *  In:
+ *      pDevice     - Device Structure
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+VOID
+BBvSetShortSlotTime (PSDevice pDevice)
+{
+    BYTE byBBRxConf=0;
+    BYTE byBBVGA=0;
+
+    BBbReadEmbeded(pDevice->PortOffset, 0x0A, &byBBRxConf);//CR10
+
+    if (pDevice->bShortSlotTime) {
+        byBBRxConf &= 0xDF;//1101 1111
+    } else {
+        byBBRxConf |= 0x20;//0010 0000
+    }
+
+    // patch for 3253B0 Baseband with Cardbus module
+    BBbReadEmbeded(pDevice->PortOffset, 0xE7, &byBBVGA);
+    if (byBBVGA == pDevice->abyBBVGA[0]) {
+        byBBRxConf |= 0x20;//0010 0000
+    }
+
+    BBbWriteEmbeded(pDevice->PortOffset, 0x0A, byBBRxConf);//CR10
+
+}
+
+VOID BBvSetVGAGainOffset(PSDevice pDevice, BYTE byData)
+{
+    BYTE byBBRxConf=0;
+
+    BBbWriteEmbeded(pDevice->PortOffset, 0xE7, byData);
+
+    BBbReadEmbeded(pDevice->PortOffset, 0x0A, &byBBRxConf);//CR10
+    // patch for 3253B0 Baseband with Cardbus module
+    if (byData == pDevice->abyBBVGA[0]) {
+        byBBRxConf |= 0x20;//0010 0000
+    } else if (pDevice->bShortSlotTime) {
+        byBBRxConf &= 0xDF;//1101 1111
+    } else {
+        byBBRxConf |= 0x20;//0010 0000
+    }
+    pDevice->byBBVGACurrent = byData;
+    BBbWriteEmbeded(pDevice->PortOffset, 0x0A, byBBRxConf);//CR10
+}
+
+
+/*
+ * Description: Baseband SoftwareReset
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+VOID
+BBvSoftwareReset (DWORD_PTR dwIoBase)
+{
+    BBbWriteEmbeded(dwIoBase, 0x50, 0x40);
+    BBbWriteEmbeded(dwIoBase, 0x50, 0);
+    BBbWriteEmbeded(dwIoBase, 0x9C, 0x01);
+    BBbWriteEmbeded(dwIoBase, 0x9C, 0);
+}
+
+/*
+ * Description: Baseband Power Save Mode ON
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+VOID
+BBvPowerSaveModeON (DWORD_PTR dwIoBase)
+{
+    BYTE byOrgData;
+
+    BBbReadEmbeded(dwIoBase, 0x0D, &byOrgData);
+    byOrgData |= BIT0;
+    BBbWriteEmbeded(dwIoBase, 0x0D, byOrgData);
+}
+
+/*
+ * Description: Baseband Power Save Mode OFF
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+VOID
+BBvPowerSaveModeOFF (DWORD_PTR dwIoBase)
+{
+    BYTE byOrgData;
+
+    BBbReadEmbeded(dwIoBase, 0x0D, &byOrgData);
+    byOrgData &= ~(BIT0);
+    BBbWriteEmbeded(dwIoBase, 0x0D, byOrgData);
+}
+
+/*
+ * Description: Set Tx Antenna mode
+ *
+ * Parameters:
+ *  In:
+ *      pDevice          - Device Structure
+ *      byAntennaMode    - Antenna Mode
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+
+VOID
+BBvSetTxAntennaMode (DWORD_PTR dwIoBase, BYTE byAntennaMode)
+{
+    BYTE byBBTxConf;
+
+#ifdef	PLICE_DEBUG
+	//printk("Enter BBvSetTxAntennaMode\n");
+#endif
+    BBbReadEmbeded(dwIoBase, 0x09, &byBBTxConf);//CR09
+    if (byAntennaMode == ANT_DIVERSITY) {
+        // bit 1 is diversity
+        byBBTxConf |= 0x02;
+    } else if (byAntennaMode == ANT_A) {
+        // bit 2 is ANTSEL
+        byBBTxConf &= 0xF9; // 1111 1001
+    } else if (byAntennaMode == ANT_B) {
+#ifdef	PLICE_DEBUG
+	//printk("BBvSetTxAntennaMode:ANT_B\n");
+#endif
+        byBBTxConf &= 0xFD; // 1111 1101
+        byBBTxConf |= 0x04;
+    }
+    BBbWriteEmbeded(dwIoBase, 0x09, byBBTxConf);//CR09
+}
+
+
+
+
+/*
+ * Description: Set Rx Antenna mode
+ *
+ * Parameters:
+ *  In:
+ *      pDevice          - Device Structure
+ *      byAntennaMode    - Antenna Mode
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+
+VOID
+BBvSetRxAntennaMode (DWORD_PTR dwIoBase, BYTE byAntennaMode)
+{
+    BYTE byBBRxConf;
+
+    BBbReadEmbeded(dwIoBase, 0x0A, &byBBRxConf);//CR10
+    if (byAntennaMode == ANT_DIVERSITY) {
+        byBBRxConf |= 0x01;
+
+    } else if (byAntennaMode == ANT_A) {
+        byBBRxConf &= 0xFC; // 1111 1100
+    } else if (byAntennaMode == ANT_B) {
+        byBBRxConf &= 0xFE; // 1111 1110
+        byBBRxConf |= 0x02;
+    }
+    BBbWriteEmbeded(dwIoBase, 0x0A, byBBRxConf);//CR10
+}
+
+
+/*
+ * Description: BBvSetDeepSleep
+ *
+ * Parameters:
+ *  In:
+ *      pDevice          - Device Structure
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+VOID
+BBvSetDeepSleep (DWORD_PTR dwIoBase, BYTE byLocalID)
+{
+    BBbWriteEmbeded(dwIoBase, 0x0C, 0x17);//CR12
+    BBbWriteEmbeded(dwIoBase, 0x0D, 0xB9);//CR13
+}
+
+VOID
+BBvExitDeepSleep (DWORD_PTR dwIoBase, BYTE byLocalID)
+{
+    BBbWriteEmbeded(dwIoBase, 0x0C, 0x00);//CR12
+    BBbWriteEmbeded(dwIoBase, 0x0D, 0x01);//CR13
+}
+
+
+
+static
+ULONG
+s_ulGetRatio (PSDevice pDevice)
+{
+ULONG   ulRatio = 0;
+ULONG   ulMaxPacket;
+ULONG   ulPacketNum;
+
+    //This is a thousand-ratio
+    ulMaxPacket = pDevice->uNumSQ3[RATE_54M];
+    if ( pDevice->uNumSQ3[RATE_54M] != 0 ) {
+        ulPacketNum = pDevice->uNumSQ3[RATE_54M];
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_54M] * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_54M;
+    }
+    if ( pDevice->uNumSQ3[RATE_48M] > ulMaxPacket ) {
+        ulPacketNum = pDevice->uNumSQ3[RATE_54M] + pDevice->uNumSQ3[RATE_48M];
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_48M] * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_48M;
+        ulMaxPacket = pDevice->uNumSQ3[RATE_48M];
+    }
+    if ( pDevice->uNumSQ3[RATE_36M] > ulMaxPacket ) {
+        ulPacketNum = pDevice->uNumSQ3[RATE_54M] + pDevice->uNumSQ3[RATE_48M] +
+                      pDevice->uNumSQ3[RATE_36M];
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_36M] * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_36M;
+        ulMaxPacket = pDevice->uNumSQ3[RATE_36M];
+    }
+    if ( pDevice->uNumSQ3[RATE_24M] > ulMaxPacket ) {
+        ulPacketNum = pDevice->uNumSQ3[RATE_54M] + pDevice->uNumSQ3[RATE_48M] +
+                      pDevice->uNumSQ3[RATE_36M] + pDevice->uNumSQ3[RATE_24M];
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_24M] * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_24M;
+        ulMaxPacket = pDevice->uNumSQ3[RATE_24M];
+    }
+    if ( pDevice->uNumSQ3[RATE_18M] > ulMaxPacket ) {
+        ulPacketNum = pDevice->uNumSQ3[RATE_54M] + pDevice->uNumSQ3[RATE_48M] +
+                      pDevice->uNumSQ3[RATE_36M] + pDevice->uNumSQ3[RATE_24M] +
+                      pDevice->uNumSQ3[RATE_18M];
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_18M] * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_18M;
+        ulMaxPacket = pDevice->uNumSQ3[RATE_18M];
+    }
+    if ( pDevice->uNumSQ3[RATE_12M] > ulMaxPacket ) {
+        ulPacketNum = pDevice->uNumSQ3[RATE_54M] + pDevice->uNumSQ3[RATE_48M] +
+                      pDevice->uNumSQ3[RATE_36M] + pDevice->uNumSQ3[RATE_24M] +
+                      pDevice->uNumSQ3[RATE_18M] + pDevice->uNumSQ3[RATE_12M];
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_12M] * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_12M;
+        ulMaxPacket = pDevice->uNumSQ3[RATE_12M];
+    }
+    if ( pDevice->uNumSQ3[RATE_11M] > ulMaxPacket ) {
+        ulPacketNum = pDevice->uDiversityCnt - pDevice->uNumSQ3[RATE_1M] -
+                      pDevice->uNumSQ3[RATE_2M] - pDevice->uNumSQ3[RATE_5M] -
+                      pDevice->uNumSQ3[RATE_6M] - pDevice->uNumSQ3[RATE_9M];
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_11M] * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_11M;
+        ulMaxPacket = pDevice->uNumSQ3[RATE_11M];
+    }
+    if ( pDevice->uNumSQ3[RATE_9M] > ulMaxPacket ) {
+        ulPacketNum = pDevice->uDiversityCnt - pDevice->uNumSQ3[RATE_1M] -
+                      pDevice->uNumSQ3[RATE_2M] - pDevice->uNumSQ3[RATE_5M] -
+                      pDevice->uNumSQ3[RATE_6M];
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_9M] * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_9M;
+        ulMaxPacket = pDevice->uNumSQ3[RATE_9M];
+    }
+    if ( pDevice->uNumSQ3[RATE_6M] > ulMaxPacket ) {
+        ulPacketNum = pDevice->uDiversityCnt - pDevice->uNumSQ3[RATE_1M] -
+                      pDevice->uNumSQ3[RATE_2M] - pDevice->uNumSQ3[RATE_5M];
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_6M] * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_6M;
+        ulMaxPacket = pDevice->uNumSQ3[RATE_6M];
+    }
+    if ( pDevice->uNumSQ3[RATE_5M] > ulMaxPacket ) {
+        ulPacketNum = pDevice->uDiversityCnt - pDevice->uNumSQ3[RATE_1M] -
+                      pDevice->uNumSQ3[RATE_2M];
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_5M] * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_55M;
+        ulMaxPacket = pDevice->uNumSQ3[RATE_5M];
+    }
+    if ( pDevice->uNumSQ3[RATE_2M] > ulMaxPacket ) {
+        ulPacketNum = pDevice->uDiversityCnt - pDevice->uNumSQ3[RATE_1M];
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_2M]  * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_2M;
+        ulMaxPacket = pDevice->uNumSQ3[RATE_2M];
+    }
+    if ( pDevice->uNumSQ3[RATE_1M] > ulMaxPacket ) {
+        ulPacketNum = pDevice->uDiversityCnt;
+        ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
+        //ulRatio = (pDevice->uNumSQ3[RATE_1M]  * 1000 / pDevice->uDiversityCnt);
+        ulRatio += TOP_RATE_1M;
+    }
+
+    return ulRatio;
+}
+
+
+VOID
+BBvClearAntDivSQ3Value (PSDevice pDevice)
+{
+    UINT    ii;
+
+    pDevice->uDiversityCnt = 0;
+    for (ii = 0; ii < MAX_RATE; ii++) {
+        pDevice->uNumSQ3[ii] = 0;
+    }
+}
+
+
+/*
+ * Description: Antenna Diversity
+ *
+ * Parameters:
+ *  In:
+ *      pDevice          - Device Structure
+ *      byRSR            - RSR from received packet
+ *      bySQ3            - SQ3 value from received packet
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+
+VOID
+BBvAntennaDiversity (PSDevice pDevice, BYTE byRxRate, BYTE bySQ3)
+{
+
+    if ((byRxRate >= MAX_RATE) || (pDevice->wAntDiversityMaxRate >= MAX_RATE)) {
+        return;
+    }
+    pDevice->uDiversityCnt++;
+   // DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->uDiversityCnt = %d\n", (int)pDevice->uDiversityCnt);
+
+    pDevice->uNumSQ3[byRxRate]++;
+
+    if (pDevice->byAntennaState == 0) {
+
+        if (pDevice->uDiversityCnt > pDevice->ulDiversityNValue) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ulDiversityNValue=[%d],54M-[%d]\n",
+                          (int)pDevice->ulDiversityNValue, (int)pDevice->uNumSQ3[(int)pDevice->wAntDiversityMaxRate]);
+
+            if (pDevice->uNumSQ3[pDevice->wAntDiversityMaxRate] < pDevice->uDiversityCnt/2) {
+
+                pDevice->ulRatio_State0 = s_ulGetRatio(pDevice);
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"SQ3_State0, rate = [%08x]\n", (int)pDevice->ulRatio_State0);
+
+                if ( pDevice->byTMax == 0 )
+                    return;
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"1.[%08x], uNumSQ3[%d]=%d, %d\n",
+                              (int)pDevice->ulRatio_State0, (int)pDevice->wAntDiversityMaxRate,
+                              (int)pDevice->uNumSQ3[(int)pDevice->wAntDiversityMaxRate], (int)pDevice->uDiversityCnt);
+#ifdef	PLICE_DEBUG
+		//printk("BBvAntennaDiversity1:call s_vChangeAntenna\n");
+#endif
+		s_vChangeAntenna(pDevice);
+                pDevice->byAntennaState = 1;
+                del_timer(&pDevice->TimerSQ3Tmax3);
+                del_timer(&pDevice->TimerSQ3Tmax2);
+                pDevice->TimerSQ3Tmax1.expires =  RUN_AT(pDevice->byTMax * HZ);
+                add_timer(&pDevice->TimerSQ3Tmax1);
+
+            } else {
+
+                pDevice->TimerSQ3Tmax3.expires =  RUN_AT(pDevice->byTMax3 * HZ);
+                add_timer(&pDevice->TimerSQ3Tmax3);
+            }
+            BBvClearAntDivSQ3Value(pDevice);
+
+        }
+    } else { //byAntennaState == 1
+
+        if (pDevice->uDiversityCnt > pDevice->ulDiversityMValue) {
+
+            del_timer(&pDevice->TimerSQ3Tmax1);
+
+            pDevice->ulRatio_State1 = s_ulGetRatio(pDevice);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"RX:SQ3_State1, rate0 = %08x,rate1 = %08x\n",
+                          (int)pDevice->ulRatio_State0,(int)pDevice->ulRatio_State1);
+
+            if (pDevice->ulRatio_State1 < pDevice->ulRatio_State0) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"2.[%08x][%08x], uNumSQ3[%d]=%d, %d\n",
+                              (int)pDevice->ulRatio_State0, (int)pDevice->ulRatio_State1,
+                              (int)pDevice->wAntDiversityMaxRate,
+                              (int)pDevice->uNumSQ3[(int)pDevice->wAntDiversityMaxRate], (int)pDevice->uDiversityCnt);
+#ifdef	PLICE_DEBUG
+		//printk("BBvAntennaDiversity2:call s_vChangeAntenna\n");
+#endif
+				s_vChangeAntenna(pDevice);
+                pDevice->TimerSQ3Tmax3.expires =  RUN_AT(pDevice->byTMax3 * HZ);
+                pDevice->TimerSQ3Tmax2.expires =  RUN_AT(pDevice->byTMax2 * HZ);
+                add_timer(&pDevice->TimerSQ3Tmax3);
+                add_timer(&pDevice->TimerSQ3Tmax2);
+            }
+            pDevice->byAntennaState = 0;
+            BBvClearAntDivSQ3Value(pDevice);
+        }
+    } //byAntennaState
+}
+
+/*+
+ *
+ * Description:
+ *  Timer for SQ3 antenna diversity
+ *
+ * Parameters:
+ *  In:
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+-*/
+
+VOID
+TimerSQ3CallBack (
+    IN  HANDLE      hDeviceContext
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"TimerSQ3CallBack...");
+
+
+    spin_lock_irq(&pDevice->lock);
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"3.[%08x][%08x], %d\n",(int)pDevice->ulRatio_State0, (int)pDevice->ulRatio_State1, (int)pDevice->uDiversityCnt);
+#ifdef	PLICE_DEBUG
+		//printk("TimerSQ3CallBack1:call s_vChangeAntenna\n");
+#endif
+
+    s_vChangeAntenna(pDevice);
+    pDevice->byAntennaState = 0;
+    BBvClearAntDivSQ3Value(pDevice);
+
+    pDevice->TimerSQ3Tmax3.expires =  RUN_AT(pDevice->byTMax3 * HZ);
+    pDevice->TimerSQ3Tmax2.expires =  RUN_AT(pDevice->byTMax2 * HZ);
+    add_timer(&pDevice->TimerSQ3Tmax3);
+    add_timer(&pDevice->TimerSQ3Tmax2);
+
+    spin_unlock_irq(&pDevice->lock);
+
+    return;
+}
+
+
+/*+
+ *
+ * Description:
+ *  Timer for SQ3 antenna diversity
+ *
+ * Parameters:
+ *  In:
+ *      pvSysSpec1
+ *      hDeviceContext - Pointer to the adapter
+ *      pvSysSpec2
+ *      pvSysSpec3
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+-*/
+
+VOID
+TimerState1CallBack (
+    IN  HANDLE      hDeviceContext
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"TimerState1CallBack...");
+
+    spin_lock_irq(&pDevice->lock);
+    if (pDevice->uDiversityCnt < pDevice->ulDiversityMValue/100) {
+#ifdef	PLICE_DEBUG
+		//printk("TimerSQ3CallBack2:call s_vChangeAntenna\n");
+#endif
+
+		s_vChangeAntenna(pDevice);
+        pDevice->TimerSQ3Tmax3.expires =  RUN_AT(pDevice->byTMax3 * HZ);
+        pDevice->TimerSQ3Tmax2.expires =  RUN_AT(pDevice->byTMax2 * HZ);
+        add_timer(&pDevice->TimerSQ3Tmax3);
+        add_timer(&pDevice->TimerSQ3Tmax2);
+    } else {
+        pDevice->ulRatio_State1 = s_ulGetRatio(pDevice);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"SQ3_State1, rate0 = %08x,rate1 = %08x\n",
+                      (int)pDevice->ulRatio_State0,(int)pDevice->ulRatio_State1);
+
+        if ( pDevice->ulRatio_State1 < pDevice->ulRatio_State0 ) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"2.[%08x][%08x], uNumSQ3[%d]=%d, %d\n",
+                          (int)pDevice->ulRatio_State0, (int)pDevice->ulRatio_State1,
+                          (int)pDevice->wAntDiversityMaxRate,
+                          (int)pDevice->uNumSQ3[(int)pDevice->wAntDiversityMaxRate], (int)pDevice->uDiversityCnt);
+#ifdef	PLICE_DEBUG
+		//printk("TimerSQ3CallBack3:call s_vChangeAntenna\n");
+#endif
+
+			s_vChangeAntenna(pDevice);
+
+            pDevice->TimerSQ3Tmax3.expires =  RUN_AT(pDevice->byTMax3 * HZ);
+            pDevice->TimerSQ3Tmax2.expires =  RUN_AT(pDevice->byTMax2 * HZ);
+            add_timer(&pDevice->TimerSQ3Tmax3);
+            add_timer(&pDevice->TimerSQ3Tmax2);
+        }
+    }
+    pDevice->byAntennaState = 0;
+    BBvClearAntDivSQ3Value(pDevice);
+    spin_unlock_irq(&pDevice->lock);
+
+    return;
+}
+
diff --git a/drivers/staging/vt6655/baseband.h b/drivers/staging/vt6655/baseband.h
new file mode 100644
index 0000000..09cf4f9
--- /dev/null
+++ b/drivers/staging/vt6655/baseband.h
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: baseband.h
+ *
+ * Purpose: Implement functions to access baseband
+ *
+ * Author: Jerry Chen
+ *
+ * Date: Jun. 5, 2002
+ *
+ */
+
+
+#ifndef __BASEBAND_H__
+#define __BASEBAND_H__
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+//
+// Registers in the BASEBAND
+//
+#define BB_MAX_CONTEXT_SIZE 256
+
+
+//
+// Baseband RF pair definition in eeprom (Bits 6..0)
+//
+
+/*
+#define RATE_1M         0
+#define RATE_2M         1
+#define RATE_5M         2
+#define RATE_11M        3
+#define RATE_6M         4
+#define RATE_9M         5
+#define RATE_12M        6
+#define RATE_18M        7
+#define RATE_24M        8
+#define RATE_36M        9
+#define RATE_48M       10
+#define RATE_54M       11
+#define RATE_AUTO      12
+#define MAX_RATE       12
+
+
+//0:11A 1:11B 2:11G
+#define BB_TYPE_11A    0
+#define BB_TYPE_11B    1
+#define BB_TYPE_11G    2
+
+//0:11a,1:11b,2:11gb(only CCK in BasicRate),3:11ga(OFDM in Basic Rate)
+#define PK_TYPE_11A     0
+#define PK_TYPE_11B     1
+#define PK_TYPE_11GB    2
+#define PK_TYPE_11GA    3
+*/
+
+
+#define PREAMBLE_LONG   0
+#define PREAMBLE_SHORT  1
+
+
+#define F5G             0
+#define F2_4G           1
+
+#define TOP_RATE_54M        0x80000000
+#define TOP_RATE_48M        0x40000000
+#define TOP_RATE_36M        0x20000000
+#define TOP_RATE_24M        0x10000000
+#define TOP_RATE_18M        0x08000000
+#define TOP_RATE_12M        0x04000000
+#define TOP_RATE_11M        0x02000000
+#define TOP_RATE_9M         0x01000000
+#define TOP_RATE_6M         0x00800000
+#define TOP_RATE_55M        0x00400000
+#define TOP_RATE_2M         0x00200000
+#define TOP_RATE_1M         0x00100000
+
+/*---------------------  Export Types  ------------------------------*/
+
+/*---------------------  Export Macros ------------------------------*/
+
+
+
+#define BBvClearFOE(dwIoBase)                               \
+{                                                           \
+    BBbWriteEmbeded(dwIoBase, 0xB1, 0);                     \
+}
+
+#define BBvSetFOE(dwIoBase)                                 \
+{                                                           \
+    BBbWriteEmbeded(dwIoBase, 0xB1, 0x0C);                  \
+}
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+UINT
+BBuGetFrameTime(
+    IN BYTE byPreambleType,
+    IN BYTE byPktType,
+    IN UINT cbFrameLength,
+    IN WORD wRate
+    );
+
+VOID
+BBvCaculateParameter (
+    IN  PSDevice pDevice,
+    IN  UINT cbFrameLength,
+    IN  WORD wRate,
+    IN  BYTE byPacketType,
+    OUT PWORD pwPhyLen,
+    OUT PBYTE pbyPhySrv,
+    OUT PBYTE pbyPhySgn
+    );
+
+BOOL BBbReadEmbeded(DWORD_PTR dwIoBase, BYTE byBBAddr, PBYTE pbyData);
+BOOL BBbWriteEmbeded(DWORD_PTR dwIoBase, BYTE byBBAddr, BYTE byData);
+
+VOID BBvReadAllRegs(DWORD_PTR dwIoBase, PBYTE pbyBBRegs);
+void BBvLoopbackOn(PSDevice pDevice);
+void BBvLoopbackOff(PSDevice pDevice);
+void BBvSetShortSlotTime(PSDevice pDevice);
+BOOL BBbIsRegBitsOn(DWORD_PTR dwIoBase, BYTE byBBAddr, BYTE byTestBits);
+BOOL BBbIsRegBitsOff(DWORD_PTR dwIoBase, BYTE byBBAddr, BYTE byTestBits);
+VOID BBvSetVGAGainOffset(PSDevice pDevice, BYTE byData);
+
+// VT3253 Baseband
+BOOL BBbVT3253Init(PSDevice pDevice);
+VOID BBvSoftwareReset(DWORD_PTR dwIoBase);
+VOID BBvPowerSaveModeON(DWORD_PTR dwIoBase);
+VOID BBvPowerSaveModeOFF(DWORD_PTR dwIoBase);
+VOID BBvSetTxAntennaMode(DWORD_PTR dwIoBase, BYTE byAntennaMode);
+VOID BBvSetRxAntennaMode(DWORD_PTR dwIoBase, BYTE byAntennaMode);
+VOID BBvSetDeepSleep(DWORD_PTR dwIoBase, BYTE byLocalID);
+VOID BBvExitDeepSleep(DWORD_PTR dwIoBase, BYTE byLocalID);
+
+// timer for antenna diversity
+VOID
+TimerSQ3CallBack(
+    IN  HANDLE hDeviceContext
+    );
+VOID
+TimerState1CallBack(
+    IN  HANDLE hDeviceContext
+    );
+
+void BBvAntennaDiversity(PSDevice pDevice, BYTE byRxRate, BYTE bySQ3);
+VOID
+BBvClearAntDivSQ3Value (PSDevice pDevice);
+
+
+#ifdef __cplusplus
+}                /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+#endif // __BASEBAND_H__
+
+
+
diff --git a/drivers/staging/vt6655/bssdb.c b/drivers/staging/vt6655/bssdb.c
new file mode 100644
index 0000000..746fadc
--- /dev/null
+++ b/drivers/staging/vt6655/bssdb.c
@@ -0,0 +1,1786 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: bssdb.c
+ *
+ * Purpose: Handles the Basic Service Set & Node Database functions
+ *
+ * Functions:
+ *      BSSpSearchBSSList - Search known BSS list for Desire SSID or BSSID
+ *      BSSvClearBSSList - Clear BSS List
+ *      BSSbInsertToBSSList - Insert a BSS set into known BSS list
+ *      BSSbUpdateToBSSList - Update BSS set in known BSS list
+ *      BSSDBbIsSTAInNodeDB - Search Node DB table to find the index of matched DstAddr
+ *      BSSvCreateOneNode - Allocate an Node for Node DB
+ *      BSSvUpdateAPNode - Update AP Node content in Index 0 of KnownNodeDB
+ *      BSSvSecondCallBack - One second timer callback function to update Node DB info & AP link status
+ *      BSSvUpdateNodeTxCounter - Update Tx attemps, Tx failure counter in Node DB for auto-fall back rate control
+ *
+ * Revision History:
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: July 17, 2002
+ *
+ */
+
+
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif//chester
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+#if !defined(__BSSDB_H__)
+#include "bssdb.h"
+#endif
+#if !defined(__WMGR_H__)
+#include "wmgr.h"
+#endif
+#if !defined(__DATARATE_H__)
+#include "datarate.h"
+#endif
+#if !defined(__DESC_H__)
+#include "desc.h"
+#endif
+#if !defined(__WCMD_H__)
+#include "wcmd.h"
+#endif
+#if !defined(__WPA_H__)
+#include "wpa.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__WPA2_H__)
+#include "wpa2.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+//DavidWang
+#if !defined(__IOWPA_H__)
+#include "iowpa.h"
+#endif
+
+//#define	PLICE_DEBUG
+/*---------------------  Static Definitions -------------------------*/
+
+
+
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+static int          msglevel                =MSG_LEVEL_INFO;
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+
+
+
+const WORD             awHWRetry0[5][5] = {
+                                            {RATE_18M, RATE_18M, RATE_12M, RATE_12M, RATE_12M},
+                                            {RATE_24M, RATE_24M, RATE_18M, RATE_12M, RATE_12M},
+                                            {RATE_36M, RATE_36M, RATE_24M, RATE_18M, RATE_18M},
+                                            {RATE_48M, RATE_48M, RATE_36M, RATE_24M, RATE_24M},
+                                            {RATE_54M, RATE_54M, RATE_48M, RATE_36M, RATE_36M}
+                                           };
+const WORD             awHWRetry1[5][5] = {
+                                            {RATE_18M, RATE_18M, RATE_12M, RATE_6M, RATE_6M},
+                                            {RATE_24M, RATE_24M, RATE_18M, RATE_6M, RATE_6M},
+                                            {RATE_36M, RATE_36M, RATE_24M, RATE_12M, RATE_12M},
+                                            {RATE_48M, RATE_48M, RATE_24M, RATE_12M, RATE_12M},
+                                            {RATE_54M, RATE_54M, RATE_36M, RATE_18M, RATE_18M}
+                                           };
+
+
+
+/*---------------------  Static Functions  --------------------------*/
+
+VOID s_vCheckSensitivity(
+    IN HANDLE hDeviceContext
+    );
+
+#ifdef Calcu_LinkQual
+VOID s_uCalculateLinkQual(
+    IN HANDLE hDeviceContext
+    );
+#endif
+
+
+VOID s_vCheckPreEDThreshold(
+    IN HANDLE hDeviceContext
+    );
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *    Search known BSS list for Desire SSID or BSSID.
+ *
+ * Return Value:
+ *    PTR to KnownBSS or NULL
+ *
+-*/
+
+PKnownBSS
+BSSpSearchBSSList(
+    IN HANDLE hDeviceContext,
+    IN PBYTE pbyDesireBSSID,
+    IN PBYTE pbyDesireSSID,
+    IN CARD_PHY_TYPE ePhyType
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PBYTE           pbyBSSID = NULL;
+    PWLAN_IE_SSID   pSSID = NULL;
+    PKnownBSS       pCurrBSS = NULL;
+    PKnownBSS       pSelect = NULL;
+BYTE                 ZeroBSSID[WLAN_BSSID_LEN]={0x00,0x00,0x00,0x00,0x00,0x00};
+    UINT            ii = 0;
+//    UINT            jj = 0;   //DavidWang
+    if (pbyDesireBSSID != NULL) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"BSSpSearchBSSList BSSID[%02X %02X %02X-%02X %02X %02X]\n",
+                            *pbyDesireBSSID,*(pbyDesireBSSID+1),*(pbyDesireBSSID+2),
+                            *(pbyDesireBSSID+3),*(pbyDesireBSSID+4),*(pbyDesireBSSID+5));
+        if ((!IS_BROADCAST_ADDRESS(pbyDesireBSSID)) &&
+	     (memcmp(pbyDesireBSSID, ZeroBSSID, 6)!= 0)) {
+            pbyBSSID = pbyDesireBSSID;
+        }
+    }
+    if (pbyDesireSSID != NULL) {
+        if (((PWLAN_IE_SSID)pbyDesireSSID)->len != 0) {
+            pSSID = (PWLAN_IE_SSID) pbyDesireSSID;
+        }
+    }
+
+    if (pbyBSSID != NULL) {
+        // match BSSID first
+        for (ii = 0; ii <MAX_BSS_NUM; ii++) {
+            pCurrBSS = &(pMgmt->sBSSList[ii]);
+if(pDevice->bLinkPass==FALSE) pCurrBSS->bSelected = FALSE;
+            if ((pCurrBSS->bActive) &&
+                (pCurrBSS->bSelected == FALSE)) {
+                if (IS_ETH_ADDRESS_EQUAL(pCurrBSS->abyBSSID, pbyBSSID)) {
+                    if (pSSID != NULL) {
+                        // compare ssid
+                        if (MEMEqualMemory(pSSID->abySSID,
+                            ((PWLAN_IE_SSID)pCurrBSS->abySSID)->abySSID,
+                            pSSID->len)) {
+                            if ((pMgmt->eConfigMode == WMAC_CONFIG_AUTO) ||
+                                ((pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA) && WLAN_GET_CAP_INFO_IBSS(pCurrBSS->wCapInfo)) ||
+                                ((pMgmt->eConfigMode == WMAC_CONFIG_ESS_STA) && WLAN_GET_CAP_INFO_ESS(pCurrBSS->wCapInfo))
+                                ) {
+                                pCurrBSS->bSelected = TRUE;
+                                return(pCurrBSS);
+                            }
+                        }
+                    } else {
+                        if ((pMgmt->eConfigMode == WMAC_CONFIG_AUTO) ||
+                            ((pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA) && WLAN_GET_CAP_INFO_IBSS(pCurrBSS->wCapInfo)) ||
+                            ((pMgmt->eConfigMode == WMAC_CONFIG_ESS_STA) && WLAN_GET_CAP_INFO_ESS(pCurrBSS->wCapInfo))
+                            ) {
+                            pCurrBSS->bSelected = TRUE;
+                            return(pCurrBSS);
+                        }
+                    }
+                }
+            }
+        }
+    } else {
+        // ignore BSSID
+        for (ii = 0; ii <MAX_BSS_NUM; ii++) {
+            pCurrBSS = &(pMgmt->sBSSList[ii]);
+	//2007-0721-01<Add>by MikeLiu
+	  pCurrBSS->bSelected = FALSE;
+          if (pCurrBSS->bActive) {
+
+                if (pSSID != NULL) {
+                    // matched SSID
+                    if (!MEMEqualMemory(pSSID->abySSID,
+                        ((PWLAN_IE_SSID)pCurrBSS->abySSID)->abySSID,
+                        pSSID->len) ||
+                        (pSSID->len != ((PWLAN_IE_SSID)pCurrBSS->abySSID)->len)) {
+                        // SSID not match skip this BSS
+                        continue;
+                    }
+                }
+                if (((pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA) && WLAN_GET_CAP_INFO_ESS(pCurrBSS->wCapInfo)) ||
+                    ((pMgmt->eConfigMode == WMAC_CONFIG_ESS_STA) && WLAN_GET_CAP_INFO_IBSS(pCurrBSS->wCapInfo))
+                    ) {
+                    // Type not match skip this BSS
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"BSS type mismatch.... Config[%d] BSS[0x%04x]\n", pMgmt->eConfigMode, pCurrBSS->wCapInfo);
+                    continue;
+                }
+
+                if (ePhyType != PHY_TYPE_AUTO) {
+                    if (((ePhyType == PHY_TYPE_11A) && (PHY_TYPE_11A != pCurrBSS->eNetworkTypeInUse)) ||
+                        ((ePhyType != PHY_TYPE_11A) && (PHY_TYPE_11A == pCurrBSS->eNetworkTypeInUse))) {
+                        // PhyType not match skip this BSS
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Physical type mismatch.... ePhyType[%d] BSS[%d]\n", ePhyType, pCurrBSS->eNetworkTypeInUse);
+                        continue;
+                    }
+                }
+/*
+                if (pMgmt->eAuthenMode < WMAC_AUTH_WPA) {
+                    if (pCurrBSS->bWPAValid == TRUE) {
+                        // WPA AP will reject connection of station without WPA enable.
+                        continue;
+                    }
+                } else if ((pMgmt->eAuthenMode == WMAC_AUTH_WPA) ||
+                           (pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK)) {
+                    if (pCurrBSS->bWPAValid == FALSE) {
+                        // station with WPA enable can't join NonWPA AP.
+                        continue;
+                    }
+                } else if ((pMgmt->eAuthenMode == WMAC_AUTH_WPA2) ||
+                           (pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK)) {
+                    if (pCurrBSS->bWPA2Valid == FALSE) {
+                        // station with WPA2 enable can't join NonWPA2 AP.
+                        continue;
+                    }
+                }
+*/
+                if (pSelect == NULL) {
+                    pSelect = pCurrBSS;
+                } else {
+                    // compare RSSI, select signal strong one
+                    if (pCurrBSS->uRSSI < pSelect->uRSSI) {
+                        pSelect = pCurrBSS;
+                    }
+                }
+            }
+        }
+        if (pSelect != NULL) {
+            pSelect->bSelected = TRUE;
+/*
+                        if (pDevice->bRoaming == FALSE)  {
+	//       Einsn Add @20070907
+			ZERO_MEMORY(pbyDesireSSID, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+			MEMvCopy(pbyDesireSSID,pCurrBSS->abySSID,WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1) ;
+                                                }*/
+
+            return(pSelect);
+        }
+    }
+    return(NULL);
+
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *    Clear BSS List
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+VOID
+BSSvClearBSSList(
+    IN HANDLE hDeviceContext,
+    IN BOOL bKeepCurrBSSID
+    )
+{
+    PSDevice     pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    UINT            ii;
+
+    for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+        if (bKeepCurrBSSID) {
+            if (pMgmt->sBSSList[ii].bActive &&
+                IS_ETH_ADDRESS_EQUAL(pMgmt->sBSSList[ii].abyBSSID, pMgmt->abyCurrBSSID)) {
+               // bKeepCurrBSSID = FALSE;
+                continue;
+            }
+        }
+
+        if ((pMgmt->sBSSList[ii].bActive) && (pMgmt->sBSSList[ii].uClearCount < BSS_CLEAR_COUNT)) {
+             pMgmt->sBSSList[ii].uClearCount ++;
+             continue;
+        }
+
+        pMgmt->sBSSList[ii].bActive = FALSE;
+        memset(&pMgmt->sBSSList[ii], 0, sizeof(KnownBSS));
+    }
+    BSSvClearAnyBSSJoinRecord(pDevice);
+
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *    search BSS list by BSSID & SSID if matched
+ *
+ * Return Value:
+ *    TRUE if found.
+ *
+-*/
+PKnownBSS
+BSSpAddrIsInBSSList(
+    IN HANDLE hDeviceContext,
+    IN PBYTE abyBSSID,
+    IN PWLAN_IE_SSID pSSID
+    )
+{
+    PSDevice     pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PKnownBSS       pBSSList = NULL;
+    UINT            ii;
+
+    for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+        pBSSList = &(pMgmt->sBSSList[ii]);
+        if (pBSSList->bActive) {
+            if (IS_ETH_ADDRESS_EQUAL(pBSSList->abyBSSID, abyBSSID)) {
+//                if (pSSID == NULL)
+//                    return pBSSList;
+                if (pSSID->len == ((PWLAN_IE_SSID)pBSSList->abySSID)->len){
+                    if (memcmp(pSSID->abySSID,
+                            ((PWLAN_IE_SSID)pBSSList->abySSID)->abySSID,
+                            pSSID->len) == 0)
+                        return pBSSList;
+                }
+            }
+        }
+    }
+
+    return NULL;
+};
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *    Insert a BSS set into known BSS list
+ *
+ * Return Value:
+ *    TRUE if success.
+ *
+-*/
+
+BOOL
+BSSbInsertToBSSList (
+    IN HANDLE hDeviceContext,
+    IN PBYTE abyBSSIDAddr,
+    IN QWORD qwTimestamp,
+    IN WORD wBeaconInterval,
+    IN WORD wCapInfo,
+    IN BYTE byCurrChannel,
+    IN PWLAN_IE_SSID pSSID,
+    IN PWLAN_IE_SUPP_RATES pSuppRates,
+    IN PWLAN_IE_SUPP_RATES pExtSuppRates,
+    IN PERPObject psERP,
+    IN PWLAN_IE_RSN pRSN,
+    IN PWLAN_IE_RSN_EXT pRSNWPA,
+    IN PWLAN_IE_COUNTRY pIE_Country,
+    IN PWLAN_IE_QUIET pIE_Quiet,
+    IN UINT uIELength,
+    IN PBYTE pbyIEs,
+    IN HANDLE pRxPacketContext
+    )
+{
+
+    PSDevice     pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PSRxMgmtPacket  pRxPacket = (PSRxMgmtPacket)pRxPacketContext;
+    PKnownBSS       pBSSList = NULL;
+    UINT            ii;
+    BOOL            bParsingQuiet = FALSE;
+    PWLAN_IE_QUIET  pQuiet = NULL;
+
+
+
+    pBSSList = (PKnownBSS)&(pMgmt->sBSSList[0]);
+
+    for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+        pBSSList = (PKnownBSS)&(pMgmt->sBSSList[ii]);
+        if (!pBSSList->bActive)
+                break;
+    }
+
+    if (ii == MAX_BSS_NUM){
+        DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Get free KnowBSS node failed.\n");
+        return FALSE;
+    }
+    // save the BSS info
+    pBSSList->bActive = TRUE;
+    memcpy( pBSSList->abyBSSID, abyBSSIDAddr, WLAN_BSSID_LEN);
+    HIDWORD(pBSSList->qwBSSTimestamp) = cpu_to_le32(HIDWORD(qwTimestamp));
+    LODWORD(pBSSList->qwBSSTimestamp) = cpu_to_le32(LODWORD(qwTimestamp));
+    pBSSList->wBeaconInterval = cpu_to_le16(wBeaconInterval);
+    pBSSList->wCapInfo = cpu_to_le16(wCapInfo);
+    pBSSList->uClearCount = 0;
+
+    if (pSSID->len > WLAN_SSID_MAXLEN)
+        pSSID->len = WLAN_SSID_MAXLEN;
+    memcpy( pBSSList->abySSID, pSSID, pSSID->len + WLAN_IEHDR_LEN);
+
+    pBSSList->uChannel = byCurrChannel;
+
+    if (pSuppRates->len > WLAN_RATES_MAXLEN)
+        pSuppRates->len = WLAN_RATES_MAXLEN;
+    memcpy( pBSSList->abySuppRates, pSuppRates, pSuppRates->len + WLAN_IEHDR_LEN);
+
+    if (pExtSuppRates != NULL) {
+        if (pExtSuppRates->len > WLAN_RATES_MAXLEN)
+            pExtSuppRates->len = WLAN_RATES_MAXLEN;
+        memcpy(pBSSList->abyExtSuppRates, pExtSuppRates, pExtSuppRates->len + WLAN_IEHDR_LEN);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"BSSbInsertToBSSList: pExtSuppRates->len = %d\n", pExtSuppRates->len);
+
+    } else {
+        memset(pBSSList->abyExtSuppRates, 0, WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1);
+    }
+    pBSSList->sERP.byERP = psERP->byERP;
+    pBSSList->sERP.bERPExist = psERP->bERPExist;
+
+    // Check if BSS is 802.11a/b/g
+    if (pBSSList->uChannel > CB_MAX_CHANNEL_24G) {
+        pBSSList->eNetworkTypeInUse = PHY_TYPE_11A;
+    } else {
+        if (pBSSList->sERP.bERPExist == TRUE) {
+            pBSSList->eNetworkTypeInUse = PHY_TYPE_11G;
+        } else {
+            pBSSList->eNetworkTypeInUse = PHY_TYPE_11B;
+        }
+    }
+
+    pBSSList->byRxRate = pRxPacket->byRxRate;
+    pBSSList->qwLocalTSF = pRxPacket->qwLocalTSF;
+    pBSSList->uRSSI = pRxPacket->uRSSI;
+    pBSSList->bySQ = pRxPacket->bySQ;
+
+   if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
+        (pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
+        // assoc with BSS
+        if (pBSSList == pMgmt->pCurrBSS) {
+            bParsingQuiet = TRUE;
+        }
+    }
+
+    WPA_ClearRSN(pBSSList);
+
+    if (pRSNWPA != NULL) {
+        UINT uLen = pRSNWPA->len + 2;
+
+        if (uLen <= (uIELength - (UINT)(ULONG_PTR)((PBYTE)pRSNWPA - pbyIEs))) {
+            pBSSList->wWPALen = uLen;
+            memcpy(pBSSList->byWPAIE, pRSNWPA, uLen);
+            WPA_ParseRSN(pBSSList, pRSNWPA);
+        }
+    }
+
+    WPA2_ClearRSN(pBSSList);
+
+    if (pRSN != NULL) {
+        UINT uLen = pRSN->len + 2;
+        if (uLen <= (uIELength - (UINT)(ULONG_PTR)((PBYTE)pRSN - pbyIEs))) {
+            pBSSList->wRSNLen = uLen;
+            memcpy(pBSSList->byRSNIE, pRSN, uLen);
+            WPA2vParseRSN(pBSSList, pRSN);
+        }
+    }
+
+    if ((pMgmt->eAuthenMode == WMAC_AUTH_WPA2) || (pBSSList->bWPA2Valid == TRUE)) {
+
+        PSKeyItem  pTransmitKey = NULL;
+        BOOL       bIs802_1x = FALSE;
+
+        for (ii = 0; ii < pBSSList->wAKMSSAuthCount; ii ++) {
+            if (pBSSList->abyAKMSSAuthType[ii] == WLAN_11i_AKMSS_802_1X) {
+                bIs802_1x = TRUE;
+                break;
+            }
+        }
+        if ((bIs802_1x == TRUE) && (pSSID->len == ((PWLAN_IE_SSID)pMgmt->abyDesireSSID)->len) &&
+            (MEMEqualMemory(pSSID->abySSID, ((PWLAN_IE_SSID)pMgmt->abyDesireSSID)->abySSID, pSSID->len))) {
+
+            bAdd_PMKID_Candidate((HANDLE)pDevice, pBSSList->abyBSSID, &pBSSList->sRSNCapObj);
+
+            if ((pDevice->bLinkPass == TRUE) && (pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
+                if ((KeybGetTransmitKey(&(pDevice->sKey), pDevice->abyBSSID, PAIRWISE_KEY, &pTransmitKey) == TRUE) ||
+                    (KeybGetTransmitKey(&(pDevice->sKey), pDevice->abyBSSID, GROUP_KEY, &pTransmitKey) == TRUE)) {
+                    pDevice->gsPMKIDCandidate.StatusType = Ndis802_11StatusType_PMKID_CandidateList;
+                    pDevice->gsPMKIDCandidate.Version = 1;
+
+                }
+
+            }
+        }
+    }
+
+    if (pDevice->bUpdateBBVGA) {
+        // Moniter if RSSI is too strong.
+        pBSSList->byRSSIStatCnt = 0;
+        RFvRSSITodBm(pDevice, (BYTE)(pRxPacket->uRSSI), &pBSSList->ldBmMAX);
+        pBSSList->ldBmAverage[0] = pBSSList->ldBmMAX;
+        for (ii = 1; ii < RSSI_STAT_COUNT; ii++)
+            pBSSList->ldBmAverage[ii] = 0;
+    }
+
+    if ((pIE_Country != NULL) &&
+        (pMgmt->b11hEnable == TRUE)) {
+        CARDvSetCountryInfo(pMgmt->pAdapter,
+                            pBSSList->eNetworkTypeInUse,
+                            pIE_Country);
+    }
+
+
+
+    if ((bParsingQuiet == TRUE) && (pIE_Quiet != NULL)) {
+        if ((((PWLAN_IE_QUIET)pIE_Quiet)->len == 8) &&
+            (((PWLAN_IE_QUIET)pIE_Quiet)->byQuietCount != 0)) {
+            // valid EID
+            if (pQuiet == NULL) {
+                pQuiet = (PWLAN_IE_QUIET)pIE_Quiet;
+                CARDbSetQuiet(  pMgmt->pAdapter,
+                                TRUE,
+                                pQuiet->byQuietCount,
+                                pQuiet->byQuietPeriod,
+                                *((PWORD)pQuiet->abyQuietDuration),
+                                *((PWORD)pQuiet->abyQuietOffset)
+                                );
+            } else {
+                pQuiet = (PWLAN_IE_QUIET)pIE_Quiet;
+                CARDbSetQuiet(  pMgmt->pAdapter,
+                                FALSE,
+                                pQuiet->byQuietCount,
+                                pQuiet->byQuietPeriod,
+                                *((PWORD)pQuiet->abyQuietDuration),
+                                *((PWORD)pQuiet->abyQuietOffset)
+                                );
+            }
+        }
+    }
+
+    if ((bParsingQuiet == TRUE) &&
+        (pQuiet != NULL)) {
+        CARDbStartQuiet(pMgmt->pAdapter);
+    }
+
+    pBSSList->uIELength = uIELength;
+    if (pBSSList->uIELength > WLAN_BEACON_FR_MAXLEN)
+        pBSSList->uIELength = WLAN_BEACON_FR_MAXLEN;
+    MEMvCopy(pBSSList->abyIEs, pbyIEs, pBSSList->uIELength);
+
+    return TRUE;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *    Update BSS set in known BSS list
+ *
+ * Return Value:
+ *    TRUE if success.
+ *
+-*/
+// TODO: input structure modify
+
+BOOL
+BSSbUpdateToBSSList (
+    IN HANDLE hDeviceContext,
+    IN QWORD qwTimestamp,
+    IN WORD wBeaconInterval,
+    IN WORD wCapInfo,
+    IN BYTE byCurrChannel,
+    IN BOOL bChannelHit,
+    IN PWLAN_IE_SSID pSSID,
+    IN PWLAN_IE_SUPP_RATES pSuppRates,
+    IN PWLAN_IE_SUPP_RATES pExtSuppRates,
+    IN PERPObject psERP,
+    IN PWLAN_IE_RSN pRSN,
+    IN PWLAN_IE_RSN_EXT pRSNWPA,
+    IN PWLAN_IE_COUNTRY pIE_Country,
+    IN PWLAN_IE_QUIET pIE_Quiet,
+    IN PKnownBSS pBSSList,
+    IN UINT uIELength,
+    IN PBYTE pbyIEs,
+    IN HANDLE pRxPacketContext
+    )
+{
+    int             ii;
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PSRxMgmtPacket  pRxPacket = (PSRxMgmtPacket)pRxPacketContext;
+    LONG            ldBm;
+    BOOL            bParsingQuiet = FALSE;
+    PWLAN_IE_QUIET  pQuiet = NULL;
+
+
+
+    if (pBSSList == NULL)
+        return FALSE;
+
+    HIDWORD(pBSSList->qwBSSTimestamp) = cpu_to_le32(HIDWORD(qwTimestamp));
+    LODWORD(pBSSList->qwBSSTimestamp) = cpu_to_le32(LODWORD(qwTimestamp));
+    pBSSList->wBeaconInterval = cpu_to_le16(wBeaconInterval);
+    pBSSList->wCapInfo = cpu_to_le16(wCapInfo);
+    pBSSList->uClearCount = 0;
+    pBSSList->uChannel = byCurrChannel;
+//    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"BSSbUpdateToBSSList: pBSSList->uChannel: %d\n", pBSSList->uChannel);
+
+    if (pSSID->len > WLAN_SSID_MAXLEN)
+        pSSID->len = WLAN_SSID_MAXLEN;
+
+    if ((pSSID->len != 0) && (pSSID->abySSID[0] != 0))
+        memcpy(pBSSList->abySSID, pSSID, pSSID->len + WLAN_IEHDR_LEN);
+    memcpy(pBSSList->abySuppRates, pSuppRates,pSuppRates->len + WLAN_IEHDR_LEN);
+
+    if (pExtSuppRates != NULL) {
+        memcpy(pBSSList->abyExtSuppRates, pExtSuppRates,pExtSuppRates->len + WLAN_IEHDR_LEN);
+    } else {
+        memset(pBSSList->abyExtSuppRates, 0, WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1);
+    }
+    pBSSList->sERP.byERP = psERP->byERP;
+    pBSSList->sERP.bERPExist = psERP->bERPExist;
+
+    // Check if BSS is 802.11a/b/g
+    if (pBSSList->uChannel > CB_MAX_CHANNEL_24G) {
+        pBSSList->eNetworkTypeInUse = PHY_TYPE_11A;
+    } else {
+        if (pBSSList->sERP.bERPExist == TRUE) {
+            pBSSList->eNetworkTypeInUse = PHY_TYPE_11G;
+        } else {
+            pBSSList->eNetworkTypeInUse = PHY_TYPE_11B;
+        }
+    }
+
+    pBSSList->byRxRate = pRxPacket->byRxRate;
+    pBSSList->qwLocalTSF = pRxPacket->qwLocalTSF;
+    if(bChannelHit)
+        pBSSList->uRSSI = pRxPacket->uRSSI;
+    pBSSList->bySQ = pRxPacket->bySQ;
+
+   if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
+        (pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
+        // assoc with BSS
+        if (pBSSList == pMgmt->pCurrBSS) {
+            bParsingQuiet = TRUE;
+        }
+    }
+
+    WPA_ClearRSN(pBSSList);         //mike update
+
+    if (pRSNWPA != NULL) {
+        UINT uLen = pRSNWPA->len + 2;
+        if (uLen <= (uIELength - (UINT)(ULONG_PTR)((PBYTE)pRSNWPA - pbyIEs))) {
+            pBSSList->wWPALen = uLen;
+            memcpy(pBSSList->byWPAIE, pRSNWPA, uLen);
+            WPA_ParseRSN(pBSSList, pRSNWPA);
+        }
+    }
+
+  WPA2_ClearRSN(pBSSList);  //mike update
+
+    if (pRSN != NULL) {
+        UINT uLen = pRSN->len + 2;
+        if (uLen <= (uIELength - (UINT)(ULONG_PTR)((PBYTE)pRSN - pbyIEs))) {
+            pBSSList->wRSNLen = uLen;
+            memcpy(pBSSList->byRSNIE, pRSN, uLen);
+            WPA2vParseRSN(pBSSList, pRSN);
+        }
+    }
+
+    if (pRxPacket->uRSSI != 0) {
+        RFvRSSITodBm(pDevice, (BYTE)(pRxPacket->uRSSI), &ldBm);
+        // Moniter if RSSI is too strong.
+        pBSSList->byRSSIStatCnt++;
+        pBSSList->byRSSIStatCnt %= RSSI_STAT_COUNT;
+        pBSSList->ldBmAverage[pBSSList->byRSSIStatCnt] = ldBm;
+        for(ii=0;ii<RSSI_STAT_COUNT;ii++) {
+            if (pBSSList->ldBmAverage[ii] != 0) {
+                pBSSList->ldBmMAX = max(pBSSList->ldBmAverage[ii], ldBm);
+            }
+        }
+    }
+
+    if ((pIE_Country != NULL) &&
+        (pMgmt->b11hEnable == TRUE)) {
+        CARDvSetCountryInfo(pMgmt->pAdapter,
+                            pBSSList->eNetworkTypeInUse,
+                            pIE_Country);
+    }
+
+    if ((bParsingQuiet == TRUE) && (pIE_Quiet != NULL)) {
+        if ((((PWLAN_IE_QUIET)pIE_Quiet)->len == 8) &&
+            (((PWLAN_IE_QUIET)pIE_Quiet)->byQuietCount != 0)) {
+            // valid EID
+            if (pQuiet == NULL) {
+                pQuiet = (PWLAN_IE_QUIET)pIE_Quiet;
+                CARDbSetQuiet(  pMgmt->pAdapter,
+                                TRUE,
+                                pQuiet->byQuietCount,
+                                pQuiet->byQuietPeriod,
+                                *((PWORD)pQuiet->abyQuietDuration),
+                                *((PWORD)pQuiet->abyQuietOffset)
+                                );
+            } else {
+                pQuiet = (PWLAN_IE_QUIET)pIE_Quiet;
+                CARDbSetQuiet(  pMgmt->pAdapter,
+                                FALSE,
+                                pQuiet->byQuietCount,
+                                pQuiet->byQuietPeriod,
+                                *((PWORD)pQuiet->abyQuietDuration),
+                                *((PWORD)pQuiet->abyQuietOffset)
+                                );
+            }
+        }
+    }
+
+    if ((bParsingQuiet == TRUE) &&
+        (pQuiet != NULL)) {
+        CARDbStartQuiet(pMgmt->pAdapter);
+    }
+
+    pBSSList->uIELength = uIELength;
+    if (pBSSList->uIELength > WLAN_BEACON_FR_MAXLEN)
+        pBSSList->uIELength = WLAN_BEACON_FR_MAXLEN;
+    memcpy(pBSSList->abyIEs, pbyIEs, pBSSList->uIELength);
+
+    return TRUE;
+}
+
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *    Search Node DB table to find the index of matched DstAddr
+ *
+ * Return Value:
+ *    None
+ *
+-*/
+
+BOOL
+BSSDBbIsSTAInNodeDB(
+    IN PVOID pMgmtObject,
+    IN PBYTE abyDstAddr,
+    OUT PUINT puNodeIndex
+    )
+{
+    PSMgmtObject    pMgmt = (PSMgmtObject) pMgmtObject;
+    UINT            ii;
+
+    // Index = 0 reserved for AP Node
+    for (ii = 1; ii < (MAX_NODE_NUM + 1); ii++) {
+        if (pMgmt->sNodeDBTable[ii].bActive) {
+            if (IS_ETH_ADDRESS_EQUAL(abyDstAddr, pMgmt->sNodeDBTable[ii].abyMACAddr)) {
+                *puNodeIndex = ii;
+                return TRUE;
+            }
+        }
+    }
+
+   return FALSE;
+};
+
+
+
+/*+
+ *
+ * Routine Description:
+ *    Find an empty node and allocated; if no empty found,
+ *    instand used of most inactive one.
+ *
+ * Return Value:
+ *    None
+ *
+-*/
+VOID
+BSSvCreateOneNode(
+    IN HANDLE hDeviceContext,
+    OUT PUINT puNodeIndex
+    )
+{
+
+    PSDevice     pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    UINT            ii;
+    UINT            BigestCount = 0;
+    UINT            SelectIndex;
+    struct sk_buff  *skb;
+    // Index = 0 reserved for AP Node (In STA mode)
+    // Index = 0 reserved for Broadcast/MultiCast (In AP mode)
+    SelectIndex = 1;
+    for (ii = 1; ii < (MAX_NODE_NUM + 1); ii++) {
+        if (pMgmt->sNodeDBTable[ii].bActive) {
+            if (pMgmt->sNodeDBTable[ii].uInActiveCount > BigestCount) {
+                BigestCount = pMgmt->sNodeDBTable[ii].uInActiveCount;
+                SelectIndex = ii;
+            }
+        }
+        else {
+            break;
+        }
+    }
+
+    // if not found replace uInActiveCount is largest one.
+    if ( ii == (MAX_NODE_NUM + 1)) {
+        *puNodeIndex = SelectIndex;
+        DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Replace inactive node = %d\n", SelectIndex);
+        // clear ps buffer
+        if (pMgmt->sNodeDBTable[*puNodeIndex].sTxPSQueue.next != NULL) {
+      	    while ((skb = skb_dequeue(&pMgmt->sNodeDBTable[*puNodeIndex].sTxPSQueue)) != NULL)
+            dev_kfree_skb(skb);
+        }
+    }
+    else {
+        *puNodeIndex = ii;
+    }
+
+    memset(&pMgmt->sNodeDBTable[*puNodeIndex], 0, sizeof(KnownNodeDB));
+    pMgmt->sNodeDBTable[*puNodeIndex].bActive = TRUE;
+    pMgmt->sNodeDBTable[*puNodeIndex].uRatePollTimeout = FALLBACK_POLL_SECOND;
+    // for AP mode PS queue
+    skb_queue_head_init(&pMgmt->sNodeDBTable[*puNodeIndex].sTxPSQueue);
+    pMgmt->sNodeDBTable[*puNodeIndex].byAuthSequence = 0;
+    pMgmt->sNodeDBTable[*puNodeIndex].wEnQueueCnt = 0;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Create node index = %d\n", ii);
+    return;
+};
+
+
+
+/*+
+ *
+ * Routine Description:
+ *    Remove Node by NodeIndex
+ *
+ *
+ * Return Value:
+ *    None
+ *
+-*/
+VOID
+BSSvRemoveOneNode(
+    IN HANDLE hDeviceContext,
+    IN UINT uNodeIndex
+    )
+{
+
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    BYTE            byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80};
+    struct sk_buff  *skb;
+
+
+    while ((skb = skb_dequeue(&pMgmt->sNodeDBTable[uNodeIndex].sTxPSQueue)) != NULL)
+            dev_kfree_skb(skb);
+    // clear context
+    memset(&pMgmt->sNodeDBTable[uNodeIndex], 0, sizeof(KnownNodeDB));
+    // clear tx bit map
+    pMgmt->abyPSTxMap[pMgmt->sNodeDBTable[uNodeIndex].wAID >> 3] &=  ~byMask[pMgmt->sNodeDBTable[uNodeIndex].wAID & 7];
+
+    return;
+};
+/*+
+ *
+ * Routine Description:
+ *    Update AP Node content in Index 0 of KnownNodeDB
+ *
+ *
+ * Return Value:
+ *    None
+ *
+-*/
+
+VOID
+BSSvUpdateAPNode(
+    IN HANDLE hDeviceContext,
+    IN PWORD pwCapInfo,
+    IN PWLAN_IE_SUPP_RATES pSuppRates,
+    IN PWLAN_IE_SUPP_RATES pExtSuppRates
+    )
+{
+    PSDevice     pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    UINT            uRateLen = WLAN_RATES_MAXLEN;
+
+    memset(&pMgmt->sNodeDBTable[0], 0, sizeof(KnownNodeDB));
+
+    pMgmt->sNodeDBTable[0].bActive = TRUE;
+    if (pDevice->eCurrentPHYType == PHY_TYPE_11B) {
+        uRateLen = WLAN_RATES_MAXLEN_11B;
+    }
+    pMgmt->abyCurrSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)pSuppRates,
+                                            (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                                            uRateLen);
+    pMgmt->abyCurrExtSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)pExtSuppRates,
+                                            (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates,
+                                            uRateLen);
+    RATEvParseMaxRate((PVOID) pDevice,
+                       (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                       (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates,
+                       TRUE,
+                       &(pMgmt->sNodeDBTable[0].wMaxBasicRate),
+                       &(pMgmt->sNodeDBTable[0].wMaxSuppRate),
+                       &(pMgmt->sNodeDBTable[0].wSuppRate),
+                       &(pMgmt->sNodeDBTable[0].byTopCCKBasicRate),
+                       &(pMgmt->sNodeDBTable[0].byTopOFDMBasicRate)
+                      );
+    memcpy(pMgmt->sNodeDBTable[0].abyMACAddr, pMgmt->abyCurrBSSID, WLAN_ADDR_LEN);
+    pMgmt->sNodeDBTable[0].wTxDataRate = pMgmt->sNodeDBTable[0].wMaxSuppRate;
+    pMgmt->sNodeDBTable[0].bShortPreamble = WLAN_GET_CAP_INFO_SHORTPREAMBLE(*pwCapInfo);
+    pMgmt->sNodeDBTable[0].uRatePollTimeout = FALLBACK_POLL_SECOND;
+#ifdef	PLICE_DEBUG
+	printk("BSSvUpdateAPNode:MaxSuppRate is %d\n",pMgmt->sNodeDBTable[0].wMaxSuppRate);
+#endif
+    // Auto rate fallback function initiation.
+    // RATEbInit(pDevice);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pMgmt->sNodeDBTable[0].wTxDataRate = %d \n", pMgmt->sNodeDBTable[0].wTxDataRate);
+
+};
+
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *    Add Multicast Node content in Index 0 of KnownNodeDB
+ *
+ *
+ * Return Value:
+ *    None
+ *
+-*/
+
+
+VOID
+BSSvAddMulticastNode(
+    IN HANDLE hDeviceContext
+    )
+{
+    PSDevice     pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+
+    if (!pDevice->bEnableHostWEP)
+        memset(&pMgmt->sNodeDBTable[0], 0, sizeof(KnownNodeDB));
+    memset(pMgmt->sNodeDBTable[0].abyMACAddr, 0xff, WLAN_ADDR_LEN);
+    pMgmt->sNodeDBTable[0].bActive = TRUE;
+    pMgmt->sNodeDBTable[0].bPSEnable = FALSE;
+    skb_queue_head_init(&pMgmt->sNodeDBTable[0].sTxPSQueue);
+    RATEvParseMaxRate((PVOID) pDevice,
+                      (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                      (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates,
+                      TRUE,
+                      &(pMgmt->sNodeDBTable[0].wMaxBasicRate),
+                      &(pMgmt->sNodeDBTable[0].wMaxSuppRate),
+                       &(pMgmt->sNodeDBTable[0].wSuppRate),
+                      &(pMgmt->sNodeDBTable[0].byTopCCKBasicRate),
+                      &(pMgmt->sNodeDBTable[0].byTopOFDMBasicRate)
+                     );
+    pMgmt->sNodeDBTable[0].wTxDataRate = pMgmt->sNodeDBTable[0].wMaxBasicRate;
+#ifdef	PLICE_DEBUG
+	printk("BSSvAddMultiCastNode:pMgmt->sNodeDBTable[0].wTxDataRate is %d\n",pMgmt->sNodeDBTable[0].wTxDataRate);
+#endif
+    pMgmt->sNodeDBTable[0].uRatePollTimeout = FALLBACK_POLL_SECOND;
+
+};
+
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *
+ *
+ *  Second call back function to update Node DB info & AP link status
+ *
+ *
+ * Return Value:
+ *    none.
+ *
+-*/
+ //2008-4-14 <add> by chester for led issue
+ #ifdef FOR_LED_ON_NOTEBOOK
+BOOL cc=FALSE;
+UINT status;
+#endif
+VOID
+BSSvSecondCallBack(
+    IN  HANDLE hDeviceContext
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    UINT            ii;
+    PWLAN_IE_SSID   pItemSSID, pCurrSSID;
+    UINT            uSleepySTACnt = 0;
+    UINT            uNonShortSlotSTACnt = 0;
+    UINT            uLongPreambleSTACnt = 0;
+viawget_wpa_header* wpahdr;
+
+    spin_lock_irq(&pDevice->lock);
+
+    pDevice->uAssocCount = 0;
+
+    pDevice->byERPFlag &=
+        ~(WLAN_SET_ERP_BARKER_MODE(1) | WLAN_SET_ERP_NONERP_PRESENT(1));
+ //2008-4-14 <add> by chester for led issue
+#ifdef FOR_LED_ON_NOTEBOOK
+MACvGPIOIn(pDevice->PortOffset, &pDevice->byGPIO);
+if (((BITbIsBitOff(pDevice->byGPIO,GPIO0_DATA)&&(pDevice->bHWRadioOff == FALSE))||(BITbIsBitOn(pDevice->byGPIO,GPIO0_DATA)&&(pDevice->bHWRadioOff == TRUE)))&&(cc==FALSE)){
+cc=TRUE;
+}
+else if(cc==TRUE){
+
+if(pDevice->bHWRadioOff == TRUE){
+            if (BITbIsBitOff(pDevice->byGPIO,GPIO0_DATA))
+//||(BITbIsBitOff(pDevice->byGPIO,GPIO0_DATA) && BITbIsBitOn(pDevice->byRadioCtl, EEP_RADIOCTL_INV)))
+{if(status==1) goto start;
+status=1;
+CARDbRadioPowerOff(pDevice);
+                pMgmt->sNodeDBTable[0].bActive = FALSE;
+                pMgmt->eCurrMode = WMAC_MODE_STANDBY;
+                pMgmt->eCurrState = WMAC_STATE_IDLE;
+                //netif_stop_queue(pDevice->dev);
+                pDevice->bLinkPass = FALSE;
+
+}
+  if (BITbIsBitOn(pDevice->byGPIO,GPIO0_DATA))
+//||(BITbIsBitOff(pDevice->byGPIO,GPIO0_DATA) && BITbIsBitOn(pDevice->byRadioCtl, EEP_RADIOCTL_INV)))
+{if(status==2) goto start;
+status=2;
+CARDbRadioPowerOn(pDevice);
+} }
+else{
+            if (BITbIsBitOn(pDevice->byGPIO,GPIO0_DATA))
+//||(BITbIsBitOff(pDevice->byGPIO,GPIO0_DATA) && BITbIsBitOn(pDevice->byRadioCtl, EEP_RADIOCTL_INV)))
+{if(status==3) goto start;
+status=3;
+CARDbRadioPowerOff(pDevice);
+                pMgmt->sNodeDBTable[0].bActive = FALSE;
+                pMgmt->eCurrMode = WMAC_MODE_STANDBY;
+                pMgmt->eCurrState = WMAC_STATE_IDLE;
+                //netif_stop_queue(pDevice->dev);
+                pDevice->bLinkPass = FALSE;
+
+}
+  if (BITbIsBitOff(pDevice->byGPIO,GPIO0_DATA))
+//||(BITbIsBitOff(pDevice->byGPIO,GPIO0_DATA) && BITbIsBitOn(pDevice->byRadioCtl, EEP_RADIOCTL_INV)))
+{if(status==4) goto start;
+status=4;
+CARDbRadioPowerOn(pDevice);
+} }
+}
+start:
+#endif
+
+
+    if (pDevice->wUseProtectCntDown > 0) {
+        pDevice->wUseProtectCntDown --;
+    }
+    else {
+        // disable protect mode
+        pDevice->byERPFlag &= ~(WLAN_SET_ERP_USE_PROTECTION(1));
+    }
+
+{
+       pDevice->byReAssocCount++;
+   if((pDevice->byReAssocCount > 10) && (pDevice->bLinkPass != TRUE)) {  //10 sec timeout
+                     printk("Re-association timeout!!!\n");
+		   pDevice->byReAssocCount = 0;
+                     #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+                    // if(pDevice->bWPASuppWextEnabled == TRUE)
+                        {
+                  	union iwreq_data  wrqu;
+                  	memset(&wrqu, 0, sizeof (wrqu));
+                          wrqu.ap_addr.sa_family = ARPHRD_ETHER;
+                  	printk("wireless_send_event--->SIOCGIWAP(disassociated)\n");
+                  	wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL);
+                       }
+                    #endif
+     }
+   else if(pDevice->bLinkPass == TRUE)
+   	pDevice->byReAssocCount = 0;
+}
+
+#ifdef Calcu_LinkQual
+   s_uCalculateLinkQual((HANDLE)pDevice);
+#endif
+
+    for (ii = 0; ii < (MAX_NODE_NUM + 1); ii++) {
+
+        if (pMgmt->sNodeDBTable[ii].bActive) {
+
+            // Increase in-activity counter
+            pMgmt->sNodeDBTable[ii].uInActiveCount++;
+
+            if (ii > 0) {
+                if (pMgmt->sNodeDBTable[ii].uInActiveCount > MAX_INACTIVE_COUNT) {
+                    BSSvRemoveOneNode(pDevice, ii);
+                    DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO
+                        "Inactive timeout [%d] sec, STA index = [%d] remove\n", MAX_INACTIVE_COUNT, ii);
+                    continue;
+                }
+
+                if (pMgmt->sNodeDBTable[ii].eNodeState >= NODE_ASSOC) {
+
+                    pDevice->uAssocCount++;
+
+                    // check if Non ERP exist
+                    if (pMgmt->sNodeDBTable[ii].uInActiveCount < ERP_RECOVER_COUNT) {
+                        if (!pMgmt->sNodeDBTable[ii].bShortPreamble) {
+                            pDevice->byERPFlag |= WLAN_SET_ERP_BARKER_MODE(1);
+                            uLongPreambleSTACnt ++;
+                        }
+                        if (!pMgmt->sNodeDBTable[ii].bERPExist) {
+                            pDevice->byERPFlag |= WLAN_SET_ERP_NONERP_PRESENT(1);
+                            pDevice->byERPFlag |= WLAN_SET_ERP_USE_PROTECTION(1);
+                        }
+                        if (!pMgmt->sNodeDBTable[ii].bShortSlotTime)
+                            uNonShortSlotSTACnt++;
+                    }
+                }
+
+                // check if any STA in PS mode
+                if (pMgmt->sNodeDBTable[ii].bPSEnable)
+                    uSleepySTACnt++;
+
+
+            }
+
+            // Rate fallback check
+
+            if (!pDevice->bFixRate) {
+/*
+                if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) && (ii == 0))
+                    RATEvTxRateFallBack(pDevice, &(pMgmt->sNodeDBTable[ii]));
+*/
+                if (ii > 0) {
+                    // ii = 0 for multicast node (AP & Adhoc)
+                    RATEvTxRateFallBack((PVOID)pDevice, &(pMgmt->sNodeDBTable[ii]));
+                }
+                else {
+                    // ii = 0 reserved for unicast AP node (Infra STA)
+                    if (pMgmt->eCurrMode == WMAC_MODE_ESS_STA)
+#ifdef	PLICE_DEBUG
+		printk("SecondCallback:Before:TxDataRate is %d\n",pMgmt->sNodeDBTable[0].wTxDataRate);
+#endif
+                        RATEvTxRateFallBack((PVOID)pDevice, &(pMgmt->sNodeDBTable[ii]));
+#ifdef	PLICE_DEBUG
+		printk("SecondCallback:After:TxDataRate is %d\n",pMgmt->sNodeDBTable[0].wTxDataRate);
+#endif
+
+		}
+
+            }
+
+            // check if pending PS queue
+            if (pMgmt->sNodeDBTable[ii].wEnQueueCnt != 0) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Index= %d, Queue = %d pending \n",
+                           ii, pMgmt->sNodeDBTable[ii].wEnQueueCnt);
+                if ((ii >0) && (pMgmt->sNodeDBTable[ii].wEnQueueCnt > 15)) {
+                    BSSvRemoveOneNode(pDevice, ii);
+                    DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Pending many queues PS STA Index = %d remove \n", ii);
+                    continue;
+                }
+            }
+        }
+
+    }
+
+
+    if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) && (pDevice->eCurrentPHYType == PHY_TYPE_11G)) {
+
+        // on/off protect mode
+        if (WLAN_GET_ERP_USE_PROTECTION(pDevice->byERPFlag)) {
+            if (!pDevice->bProtectMode) {
+                MACvEnableProtectMD(pDevice->PortOffset);
+                pDevice->bProtectMode = TRUE;
+            }
+        }
+        else {
+            if (pDevice->bProtectMode) {
+                MACvDisableProtectMD(pDevice->PortOffset);
+                pDevice->bProtectMode = FALSE;
+            }
+        }
+        // on/off short slot time
+
+        if (uNonShortSlotSTACnt > 0) {
+            if (pDevice->bShortSlotTime) {
+                pDevice->bShortSlotTime = FALSE;
+                BBvSetShortSlotTime(pDevice);
+                vUpdateIFS((PVOID)pDevice);
+            }
+        }
+        else {
+            if (!pDevice->bShortSlotTime) {
+                pDevice->bShortSlotTime = TRUE;
+                BBvSetShortSlotTime(pDevice);
+                vUpdateIFS((PVOID)pDevice);
+            }
+        }
+
+        // on/off barker long preamble mode
+
+        if (uLongPreambleSTACnt > 0) {
+            if (!pDevice->bBarkerPreambleMd) {
+                MACvEnableBarkerPreambleMd(pDevice->PortOffset);
+                pDevice->bBarkerPreambleMd = TRUE;
+            }
+        }
+        else {
+            if (pDevice->bBarkerPreambleMd) {
+                MACvDisableBarkerPreambleMd(pDevice->PortOffset);
+                pDevice->bBarkerPreambleMd = FALSE;
+            }
+        }
+
+    }
+
+
+    // Check if any STA in PS mode, enable DTIM multicast deliver
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+        if (uSleepySTACnt > 0)
+            pMgmt->sNodeDBTable[0].bPSEnable = TRUE;
+        else
+            pMgmt->sNodeDBTable[0].bPSEnable = FALSE;
+    }
+
+    pItemSSID = (PWLAN_IE_SSID)pMgmt->abyDesireSSID;
+    pCurrSSID = (PWLAN_IE_SSID)pMgmt->abyCurrSSID;
+//printk("pCurrSSID=%s\n",pCurrSSID->abySSID);
+    if ((pMgmt->eCurrMode == WMAC_MODE_STANDBY) ||
+        (pMgmt->eCurrMode == WMAC_MODE_ESS_STA)) {
+
+        if (pMgmt->sNodeDBTable[0].bActive) { // Assoc with BSS
+           // DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "Callback inactive Count = [%d]\n", pMgmt->sNodeDBTable[0].uInActiveCount);
+            //if (pDevice->bUpdateBBVGA) {
+            //  s_vCheckSensitivity((HANDLE) pDevice);
+            //}
+            if (pDevice->bUpdateBBVGA) {
+               // s_vCheckSensitivity((HANDLE) pDevice);
+               s_vCheckPreEDThreshold((HANDLE)pDevice);
+            }
+    	    if ((pMgmt->sNodeDBTable[0].uInActiveCount >= (LOST_BEACON_COUNT/2)) &&
+    	        (pDevice->byBBVGACurrent != pDevice->abyBBVGA[0]) ) {
+    	        pDevice->byBBVGANew = pDevice->abyBBVGA[0];
+                bScheduleCommand((HANDLE) pDevice, WLAN_CMD_CHANGE_BBSENSITIVITY, NULL);
+    	    }
+
+
+        	if (pMgmt->sNodeDBTable[0].uInActiveCount >= LOST_BEACON_COUNT) {
+                pMgmt->sNodeDBTable[0].bActive = FALSE;
+                pMgmt->eCurrMode = WMAC_MODE_STANDBY;
+                pMgmt->eCurrState = WMAC_STATE_IDLE;
+                netif_stop_queue(pDevice->dev);
+                pDevice->bLinkPass = FALSE;
+                pDevice->bRoaming = TRUE;
+                DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Lost AP beacon [%d] sec, disconnected !\n", pMgmt->sNodeDBTable[0].uInActiveCount);
+        if ((pDevice->bWPADEVUp) && (pDevice->skb != NULL)) {
+             wpahdr = (viawget_wpa_header *)pDevice->skb->data;
+             wpahdr->type = VIAWGET_DISASSOC_MSG;
+             wpahdr->resp_ie_len = 0;
+             wpahdr->req_ie_len = 0;
+             skb_put(pDevice->skb, sizeof(viawget_wpa_header));
+             pDevice->skb->dev = pDevice->wpadev;
+             pDevice->skb->mac_header = pDevice->skb->data;
+             pDevice->skb->pkt_type = PACKET_HOST;
+             pDevice->skb->protocol = htons(ETH_P_802_2);
+             memset(pDevice->skb->cb, 0, sizeof(pDevice->skb->cb));
+             netif_rx(pDevice->skb);
+             pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
+         };
+   #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+  // if(pDevice->bWPASuppWextEnabled == TRUE)
+      {
+	union iwreq_data  wrqu;
+	memset(&wrqu, 0, sizeof (wrqu));
+        wrqu.ap_addr.sa_family = ARPHRD_ETHER;
+	printk("wireless_send_event--->SIOCGIWAP(disassociated)\n");
+	wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL);
+     }
+  #endif
+			}
+        }
+        else if (pItemSSID->len != 0) {
+            if (pDevice->uAutoReConnectTime < 10) {
+                pDevice->uAutoReConnectTime++;
+	#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+                //network manager support need not do Roaming scan???
+                if(pDevice->bWPASuppWextEnabled ==TRUE)
+		 pDevice->uAutoReConnectTime = 0;
+	     #endif
+
+            }
+            else {
+		    //mike use old encryption status for wpa reauthen
+	      if(pDevice->bWPADEVUp)
+	          pDevice->eEncryptionStatus = pDevice->eOldEncryptionStatus;
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Roaming ...\n");
+                BSSvClearBSSList((HANDLE)pDevice, pDevice->bLinkPass);
+	pMgmt->eScanType = WMAC_SCAN_ACTIVE;
+                bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, pMgmt->abyDesireSSID);
+                bScheduleCommand((HANDLE) pDevice, WLAN_CMD_SSID, pMgmt->abyDesireSSID);
+                pDevice->uAutoReConnectTime = 0;
+            }
+        }
+    }
+
+    if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+        // if adhoc started which essid is NULL string, rescaning.
+        if ((pMgmt->eCurrState == WMAC_STATE_STARTED) && (pCurrSSID->len == 0)) {
+            if (pDevice->uAutoReConnectTime < 10) {
+                pDevice->uAutoReConnectTime++;
+            }
+            else {
+                DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Adhoc re-scaning ...\n");
+	pMgmt->eScanType = WMAC_SCAN_ACTIVE;
+                bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, NULL);
+                bScheduleCommand((HANDLE) pDevice, WLAN_CMD_SSID, NULL);
+                pDevice->uAutoReConnectTime = 0;
+            };
+        }
+        if (pMgmt->eCurrState == WMAC_STATE_JOINTED) {
+            if (pDevice->bUpdateBBVGA) {
+               //s_vCheckSensitivity((HANDLE) pDevice);
+               s_vCheckPreEDThreshold((HANDLE)pDevice);
+            }
+        	if (pMgmt->sNodeDBTable[0].uInActiveCount >=ADHOC_LOST_BEACON_COUNT) {
+        	    DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Lost other STA beacon [%d] sec, started !\n", pMgmt->sNodeDBTable[0].uInActiveCount);
+                pMgmt->sNodeDBTable[0].uInActiveCount = 0;
+                pMgmt->eCurrState = WMAC_STATE_STARTED;
+                netif_stop_queue(pDevice->dev);
+                pDevice->bLinkPass = FALSE;
+            }
+        }
+    }
+
+    spin_unlock_irq(&pDevice->lock);
+
+    pMgmt->sTimerSecondCallback.expires = RUN_AT(HZ);
+    add_timer(&pMgmt->sTimerSecondCallback);
+    return;
+}
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *
+ *
+ *  Update Tx attemps, Tx failure counter in Node DB
+ *
+ *
+ * Return Value:
+ *    none.
+ *
+-*/
+
+
+
+VOID
+BSSvUpdateNodeTxCounter(
+    IN HANDLE      hDeviceContext,
+    IN BYTE        byTsr0,
+    IN BYTE        byTsr1,
+    IN PBYTE       pbyBuffer,
+    IN UINT        uFIFOHeaderSize
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    UINT            uNodeIndex = 0;
+    BYTE            byTxRetry = (byTsr0 & TSR0_NCR);
+    PSTxBufHead     pTxBufHead;
+    PS802_11Header  pMACHeader;
+    WORD            wRate;
+    WORD            wFallBackRate = RATE_1M;
+    BYTE            byFallBack;
+    UINT            ii;
+//	UINT		txRetryTemp;
+//PLICE_DEBUG->
+	//txRetryTemp = byTxRetry;
+	//if (txRetryTemp== 8)
+	//txRetryTemp -=3;
+//PLICE_DEBUG <-
+    pTxBufHead = (PSTxBufHead) pbyBuffer;
+    if (pTxBufHead->wFIFOCtl & FIFOCTL_AUTO_FB_0) {
+        byFallBack = AUTO_FB_0;
+    } else if (pTxBufHead->wFIFOCtl & FIFOCTL_AUTO_FB_1) {
+        byFallBack = AUTO_FB_1;
+    } else {
+        byFallBack = AUTO_FB_NONE;
+    }
+    wRate = pTxBufHead->wReserved; //?wRate
+    //printk("BSSvUpdateNodeTxCounter:byTxRetry is %d\n",byTxRetry);
+
+//printk("BSSvUpdateNodeTx:wRate is %d,byFallback is %d\n",wRate,byFallBack);
+//#ifdef	PLICE_DEBUG
+	//printk("BSSvUpdateNodeTx: wRate is %d\n",wRate);
+////#endif
+    // Only Unicast using support rates
+    if (pTxBufHead->wFIFOCtl & FIFOCTL_NEEDACK) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wRate %04X, byTsr0 %02X, byTsr1 %02X\n", wRate, byTsr0, byTsr1);
+        if (pMgmt->eCurrMode == WMAC_MODE_ESS_STA) {
+            pMgmt->sNodeDBTable[0].uTxAttempts += 1;
+            if ((byTsr1 & TSR1_TERR) == 0) {
+                // transmit success, TxAttempts at least plus one
+                pMgmt->sNodeDBTable[0].uTxOk[MAX_RATE]++;
+                if ( (byFallBack == AUTO_FB_NONE) ||
+                     (wRate < RATE_18M) ) {
+                    wFallBackRate = wRate;
+                } else if (byFallBack == AUTO_FB_0) {
+//PLICE_DEBUG
+				  if (byTxRetry < 5)
+				//if (txRetryTemp < 5)
+					wFallBackRate = awHWRetry0[wRate-RATE_18M][byTxRetry];
+			//wFallBackRate = awHWRetry0[wRate-RATE_12M][byTxRetry];
+			//wFallBackRate = awHWRetry0[wRate-RATE_18M][txRetryTemp] +1;
+		else
+                        wFallBackRate = awHWRetry0[wRate-RATE_18M][4];
+			//wFallBackRate = awHWRetry0[wRate-RATE_12M][4];
+		} else if (byFallBack == AUTO_FB_1) {
+                    if (byTxRetry < 5)
+                        wFallBackRate = awHWRetry1[wRate-RATE_18M][byTxRetry];
+                    else
+                        wFallBackRate = awHWRetry1[wRate-RATE_18M][4];
+                }
+                pMgmt->sNodeDBTable[0].uTxOk[wFallBackRate]++;
+            } else {
+                pMgmt->sNodeDBTable[0].uTxFailures ++;
+            }
+            pMgmt->sNodeDBTable[0].uTxRetry += byTxRetry;
+            if (byTxRetry != 0) {
+                pMgmt->sNodeDBTable[0].uTxFail[MAX_RATE]+=byTxRetry;
+                if ( (byFallBack == AUTO_FB_NONE) ||
+                     (wRate < RATE_18M) ) {
+                    pMgmt->sNodeDBTable[0].uTxFail[wRate]+=byTxRetry;
+                } else if (byFallBack == AUTO_FB_0) {
+//PLICE_DEBUG
+				   for(ii=0;ii<byTxRetry;ii++)
+		//for (ii=0;ii<txRetryTemp;ii++)
+		{
+                        if (ii < 5)
+                        	{
+
+//PLICE_DEBUG
+						wFallBackRate = awHWRetry0[wRate-RATE_18M][ii];
+					//printk(" II is %d:BSSvUpdateNodeTx:wFallBackRate is %d\n",ii,wFallBackRate);
+				//wFallBackRate = awHWRetry0[wRate-RATE_12M][ii];
+                        	}
+			else
+				{
+			wFallBackRate = awHWRetry0[wRate-RATE_18M][4];
+			//printk("ii is %d BSSvUpdateNodeTx:wFallBackRate is %d\n",ii,wFallBackRate);
+				//wFallBackRate = awHWRetry0[wRate-RATE_12M][4];
+				}
+						pMgmt->sNodeDBTable[0].uTxFail[wFallBackRate]++;
+                    }
+                } else if (byFallBack == AUTO_FB_1) {
+                    for(ii=0;ii<byTxRetry;ii++) {
+                        if (ii < 5)
+                            wFallBackRate = awHWRetry1[wRate-RATE_18M][ii];
+                        else
+                            wFallBackRate = awHWRetry1[wRate-RATE_18M][4];
+                        pMgmt->sNodeDBTable[0].uTxFail[wFallBackRate]++;
+                    }
+                }
+            }
+        };
+
+        if ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) ||
+            (pMgmt->eCurrMode == WMAC_MODE_ESS_AP)) {
+
+            pMACHeader = (PS802_11Header)(pbyBuffer + uFIFOHeaderSize);
+
+            if (BSSDBbIsSTAInNodeDB((HANDLE)pMgmt, &(pMACHeader->abyAddr1[0]), &uNodeIndex)){
+                pMgmt->sNodeDBTable[uNodeIndex].uTxAttempts += 1;
+                if ((byTsr1 & TSR1_TERR) == 0) {
+                    // transmit success, TxAttempts at least plus one
+                    pMgmt->sNodeDBTable[uNodeIndex].uTxOk[MAX_RATE]++;
+                    if ( (byFallBack == AUTO_FB_NONE) ||
+                         (wRate < RATE_18M) ) {
+                        wFallBackRate = wRate;
+                    } else if (byFallBack == AUTO_FB_0) {
+                        if (byTxRetry < 5)
+                            wFallBackRate = awHWRetry0[wRate-RATE_18M][byTxRetry];
+                        else
+                            wFallBackRate = awHWRetry0[wRate-RATE_18M][4];
+                    } else if (byFallBack == AUTO_FB_1) {
+                        if (byTxRetry < 5)
+                            wFallBackRate = awHWRetry1[wRate-RATE_18M][byTxRetry];
+                        else
+                            wFallBackRate = awHWRetry1[wRate-RATE_18M][4];
+                    }
+                    pMgmt->sNodeDBTable[uNodeIndex].uTxOk[wFallBackRate]++;
+                } else {
+                    pMgmt->sNodeDBTable[uNodeIndex].uTxFailures ++;
+                }
+                pMgmt->sNodeDBTable[uNodeIndex].uTxRetry += byTxRetry;
+                if (byTxRetry != 0) {
+                    pMgmt->sNodeDBTable[uNodeIndex].uTxFail[MAX_RATE]+=byTxRetry;
+                    if ( (byFallBack == AUTO_FB_NONE) ||
+                         (wRate < RATE_18M) ) {
+                        pMgmt->sNodeDBTable[uNodeIndex].uTxFail[wRate]+=byTxRetry;
+                    } else if (byFallBack == AUTO_FB_0) {
+                        for(ii=0;ii<byTxRetry;ii++) {
+                            if (ii < 5)
+                                wFallBackRate = awHWRetry0[wRate-RATE_18M][ii];
+                            else
+                                wFallBackRate = awHWRetry0[wRate-RATE_18M][4];
+                            pMgmt->sNodeDBTable[uNodeIndex].uTxFail[wFallBackRate]++;
+                        }
+                    } else if (byFallBack == AUTO_FB_1) {
+                        for(ii=0;ii<byTxRetry;ii++) {
+                            if (ii < 5)
+                                wFallBackRate = awHWRetry1[wRate-RATE_18M][ii];
+                            else
+                                wFallBackRate = awHWRetry1[wRate-RATE_18M][4];
+                            pMgmt->sNodeDBTable[uNodeIndex].uTxFail[wFallBackRate]++;
+                        }
+                    }
+                }
+            };
+        }
+    };
+
+    return;
+
+}
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *    Clear Nodes & skb in DB Table
+ *
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext        - The adapter context.
+ *      uStartIndex           - starting index
+ *  Out:
+ *      none
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+VOID
+BSSvClearNodeDBTable(
+    IN HANDLE hDeviceContext,
+    IN UINT uStartIndex
+    )
+
+{
+    PSDevice     pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    struct sk_buff  *skb;
+    UINT            ii;
+
+    for (ii = uStartIndex; ii < (MAX_NODE_NUM + 1); ii++) {
+        if (pMgmt->sNodeDBTable[ii].bActive) {
+            // check if sTxPSQueue has been initial
+            if (pMgmt->sNodeDBTable[ii].sTxPSQueue.next != NULL) {
+                while ((skb = skb_dequeue(&pMgmt->sNodeDBTable[ii].sTxPSQueue)) != NULL){
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "PS skb != NULL %d\n", ii);
+                        dev_kfree_skb(skb);
+                }
+            }
+            memset(&pMgmt->sNodeDBTable[ii], 0, sizeof(KnownNodeDB));
+        }
+    }
+
+    return;
+};
+
+
+VOID s_vCheckSensitivity(
+    IN HANDLE hDeviceContext
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    PKnownBSS       pBSSList = NULL;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    int             ii;
+
+    if ((pDevice->byLocalID <= REV_ID_VT3253_A1) && (pDevice->byRFType == RF_RFMD2959) &&
+        (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA)) {
+        return;
+    }
+
+    if ((pMgmt->eCurrState == WMAC_STATE_ASSOC) ||
+        ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) && (pMgmt->eCurrState == WMAC_STATE_JOINTED))) {
+        pBSSList = BSSpAddrIsInBSSList(pDevice, pMgmt->abyCurrBSSID, (PWLAN_IE_SSID)pMgmt->abyCurrSSID);
+        if (pBSSList != NULL) {
+            // Updata BB Reg if RSSI is too strong.
+            LONG    LocalldBmAverage = 0;
+            LONG    uNumofdBm = 0;
+            for (ii = 0; ii < RSSI_STAT_COUNT; ii++) {
+                if (pBSSList->ldBmAverage[ii] != 0) {
+                    uNumofdBm ++;
+                    LocalldBmAverage += pBSSList->ldBmAverage[ii];
+                }
+            }
+            if (uNumofdBm > 0) {
+                LocalldBmAverage = LocalldBmAverage/uNumofdBm;
+                for (ii=0;ii<BB_VGA_LEVEL;ii++) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"LocalldBmAverage:%ld, %ld %02x\n", LocalldBmAverage, pDevice->ldBmThreshold[ii], pDevice->abyBBVGA[ii]);
+                    if (LocalldBmAverage < pDevice->ldBmThreshold[ii]) {
+                	    pDevice->byBBVGANew = pDevice->abyBBVGA[ii];
+                        break;
+                    }
+                }
+                if (pDevice->byBBVGANew != pDevice->byBBVGACurrent) {
+                    pDevice->uBBVGADiffCount++;
+                    if (pDevice->uBBVGADiffCount >= BB_VGA_CHANGE_THRESHOLD)
+                        bScheduleCommand((HANDLE) pDevice, WLAN_CMD_CHANGE_BBSENSITIVITY, NULL);
+                } else {
+                    pDevice->uBBVGADiffCount = 0;
+                }
+            }
+        }
+    }
+}
+
+
+VOID
+BSSvClearAnyBSSJoinRecord (
+    IN HANDLE hDeviceContext
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    UINT            ii;
+
+    for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+        pMgmt->sBSSList[ii].bSelected = FALSE;
+    }
+    return;
+}
+
+#ifdef Calcu_LinkQual
+VOID s_uCalculateLinkQual(
+    IN HANDLE hDeviceContext
+    )
+{
+   PSDevice        pDevice = (PSDevice)hDeviceContext;
+   ULONG TxOkRatio, TxCnt;
+   ULONG RxOkRatio,RxCnt;
+   ULONG RssiRatio;
+   long ldBm;
+
+TxCnt = pDevice->scStatistic.TxNoRetryOkCount +
+	      pDevice->scStatistic.TxRetryOkCount +
+	      pDevice->scStatistic.TxFailCount;
+RxCnt = pDevice->scStatistic.RxFcsErrCnt +
+	      pDevice->scStatistic.RxOkCnt;
+TxOkRatio = (TxCnt < 6) ? 4000:((pDevice->scStatistic.TxNoRetryOkCount * 4000) / TxCnt);
+RxOkRatio = (RxCnt < 6) ? 2000:((pDevice->scStatistic.RxOkCnt * 2000) / RxCnt);
+//decide link quality
+if(pDevice->bLinkPass !=TRUE)
+{
+ //  printk("s_uCalculateLinkQual-->Link disconnect and Poor quality**\n");
+   pDevice->scStatistic.LinkQuality = 0;
+   pDevice->scStatistic.SignalStren = 0;
+}
+else
+{
+   RFvRSSITodBm(pDevice, (BYTE)(pDevice->uCurrRSSI), &ldBm);
+   if(-ldBm < 50)  {
+   	RssiRatio = 4000;
+     }
+   else if(-ldBm > 90) {
+   	RssiRatio = 0;
+     }
+   else {
+   	RssiRatio = (40-(-ldBm-50))*4000/40;
+     }
+   pDevice->scStatistic.SignalStren = RssiRatio/40;
+   pDevice->scStatistic.LinkQuality = (RssiRatio+TxOkRatio+RxOkRatio)/100;
+}
+   pDevice->scStatistic.RxFcsErrCnt = 0;
+   pDevice->scStatistic.RxOkCnt = 0;
+   pDevice->scStatistic.TxFailCount = 0;
+   pDevice->scStatistic.TxNoRetryOkCount = 0;
+   pDevice->scStatistic.TxRetryOkCount = 0;
+   return;
+}
+#endif
+
+VOID s_vCheckPreEDThreshold(
+    IN HANDLE hDeviceContext
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    PKnownBSS       pBSSList = NULL;
+    PSMgmtObject    pMgmt = &(pDevice->sMgmtObj);
+
+    if ((pMgmt->eCurrState == WMAC_STATE_ASSOC) ||
+        ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) && (pMgmt->eCurrState == WMAC_STATE_JOINTED))) {
+        pBSSList = BSSpAddrIsInBSSList(pDevice, pMgmt->abyCurrBSSID, (PWLAN_IE_SSID)pMgmt->abyCurrSSID);
+        if (pBSSList != NULL) {
+            pDevice->byBBPreEDRSSI = (BYTE) (~(pBSSList->ldBmAverRange) + 1);
+            //BBvUpdatePreEDThreshold(pDevice, FALSE);
+        }
+    }
+    return;
+}
diff --git a/drivers/staging/vt6655/bssdb.h b/drivers/staging/vt6655/bssdb.h
new file mode 100644
index 0000000..d35616d
--- /dev/null
+++ b/drivers/staging/vt6655/bssdb.h
@@ -0,0 +1,380 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: bssdb.h
+ *
+ * Purpose: Handles the Basic Service Set & Node Database functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: July 16, 2002
+ *
+ */
+
+#ifndef __BSSDB_H__
+#define __BSSDB_H__
+
+//#if !defined(__DEVICE_H__)
+//#include "device.h"
+//#endif
+#include <linux/skbuff.h>
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+#if !defined(__80211MGR_H__)
+#include "80211mgr.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+#define MAX_NODE_NUM             64
+#define MAX_BSS_NUM              42
+#define LOST_BEACON_COUNT      	 10   // 10 sec, XP defined
+#define MAX_PS_TX_BUF            32   // sta max power saving tx buf
+#define ADHOC_LOST_BEACON_COUNT  30   // 30 sec, beacon lost for adhoc only
+#define MAX_INACTIVE_COUNT       300  // 300 sec, inactive STA node refresh
+
+#define USE_PROTECT_PERIOD       10   // 10 sec, Use protect mode check period
+#define ERP_RECOVER_COUNT        30   // 30 sec, ERP support callback check
+#define BSS_CLEAR_COUNT           1
+
+#define RSSI_STAT_COUNT          10
+#define MAX_CHECK_RSSI_COUNT     8
+
+// STA dwflags
+#define WLAN_STA_AUTH            BIT0
+#define WLAN_STA_ASSOC           BIT1
+#define WLAN_STA_PS              BIT2
+#define WLAN_STA_TIM             BIT3
+// permanent; do not remove entry on expiration
+#define WLAN_STA_PERM            BIT4
+// If 802.1X is used, this flag is
+// controlling whether STA is authorized to
+// send and receive non-IEEE 802.1X frames
+#define WLAN_STA_AUTHORIZED      BIT5
+
+#define MAX_RATE            12
+
+#define MAX_WPA_IE_LEN      64
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Types  ------------------------------*/
+
+//
+// IEEE 802.11 Structures and definitions
+//
+
+typedef enum _NDIS_802_11_NETWORK_TYPE
+{
+    Ndis802_11FH,
+    Ndis802_11DS,
+    Ndis802_11OFDM5,
+    Ndis802_11OFDM24,
+    Ndis802_11NetworkTypeMax    // not a real type, defined as an upper bound
+} NDIS_802_11_NETWORK_TYPE, *PNDIS_802_11_NETWORK_TYPE;
+
+
+typedef struct tagSERPObject {
+    BOOL    bERPExist;
+    BYTE    byERP;
+} ERPObject, DEF* PERPObject;
+
+
+typedef struct tagSRSNCapObject {
+    BOOL    bRSNCapExist;
+    WORD    wRSNCap;
+} SRSNCapObject, DEF* PSRSNCapObject;
+
+// BSS info(AP)
+#pragma pack(1)
+typedef struct tagKnownBSS {
+    // BSS info
+    BOOL            bActive;
+    BYTE            abyBSSID[WLAN_BSSID_LEN];
+    UINT            uChannel;
+    BYTE            abySuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1];
+    BYTE            abyExtSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1];
+    UINT            uRSSI;
+    BYTE            bySQ;
+    WORD            wBeaconInterval;
+    WORD            wCapInfo;
+    BYTE            abySSID[WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1];
+    BYTE            byRxRate;
+//    WORD            wATIMWindow;
+    BYTE            byRSSIStatCnt;
+    LONG            ldBmMAX;
+    LONG            ldBmAverage[RSSI_STAT_COUNT];
+     LONG            ldBmAverRange;
+    //For any BSSID selection improvment
+    BOOL            bSelected;
+
+    //++ WPA informations
+    BOOL            bWPAValid;
+    BYTE            byGKType;
+    BYTE            abyPKType[4];
+    WORD            wPKCount;
+    BYTE            abyAuthType[4];
+    WORD            wAuthCount;
+    BYTE            byDefaultK_as_PK;
+    BYTE            byReplayIdx;
+    //--
+
+    //++ WPA2 informations
+    BOOL            bWPA2Valid;
+    BYTE            byCSSGK;
+    WORD            wCSSPKCount;
+    BYTE            abyCSSPK[4];
+    WORD            wAKMSSAuthCount;
+    BYTE            abyAKMSSAuthType[4];
+
+    //++  wpactl
+    BYTE            byWPAIE[MAX_WPA_IE_LEN];
+    BYTE            byRSNIE[MAX_WPA_IE_LEN];
+    WORD            wWPALen;
+    WORD            wRSNLen;
+
+    // Clear count
+    UINT            uClearCount;
+//    BYTE            abyIEs[WLAN_BEACON_FR_MAXLEN];
+    UINT            uIELength;
+    QWORD           qwBSSTimestamp;
+    QWORD           qwLocalTSF;     // local TSF timer
+
+//    NDIS_802_11_NETWORK_TYPE    NetworkTypeInUse;
+    CARD_PHY_TYPE   eNetworkTypeInUse;
+
+    ERPObject       sERP;
+    SRSNCapObject   sRSNCapObj;
+    BYTE            abyIEs[1024];   // don't move this field !!
+
+}__attribute__ ((__packed__))
+KnownBSS , DEF* PKnownBSS;
+
+//2006-1116-01,<Add> by NomadZhao
+#pragma pack()
+
+typedef enum tagNODE_STATE {
+    NODE_FREE,
+    NODE_AGED,
+    NODE_KNOWN,
+    NODE_AUTH,
+    NODE_ASSOC
+} NODE_STATE, *PNODE_STATE;
+
+
+// STA node info
+typedef struct tagKnownNodeDB {
+    // STA info
+    BOOL            bActive;
+    BYTE            abyMACAddr[WLAN_ADDR_LEN];
+    BYTE            abyCurrSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN];
+    BYTE            abyCurrExtSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN];
+    WORD            wTxDataRate;
+    BOOL            bShortPreamble;
+    BOOL            bERPExist;
+    BOOL            bShortSlotTime;
+    UINT            uInActiveCount;
+    WORD            wMaxBasicRate;     //Get from byTopOFDMBasicRate or byTopCCKBasicRate which depends on packetTyp.
+    WORD            wMaxSuppRate;      //Records the highest supported rate getting from SuppRates IE and ExtSuppRates IE in Beacon.
+    WORD            wSuppRate;
+    BYTE            byTopOFDMBasicRate;//Records the highest basic rate in OFDM mode
+    BYTE            byTopCCKBasicRate; //Records the highest basic rate in CCK mode
+
+    // For AP mode
+    struct sk_buff_head sTxPSQueue;
+    WORD            wCapInfo;
+    WORD            wListenInterval;
+    WORD            wAID;
+    NODE_STATE      eNodeState;
+    BOOL            bPSEnable;
+    BOOL            bRxPSPoll;
+    BYTE            byAuthSequence;
+    ULONG           ulLastRxJiffer;
+    BYTE            bySuppRate;
+    DWORD           dwFlags;
+    WORD            wEnQueueCnt;
+
+    BOOL            bOnFly;
+    ULONGLONG       KeyRSC;
+    BYTE            byKeyIndex;
+    DWORD           dwKeyIndex;
+    BYTE            byCipherSuite;
+    DWORD           dwTSC47_16;
+    WORD            wTSC15_0;
+    UINT            uWepKeyLength;
+    BYTE            abyWepKey[WLAN_WEPMAX_KEYLEN];
+    //
+    // Auto rate fallback vars
+    BOOL            bIsInFallback;
+    UINT            uAverageRSSI;
+    UINT            uRateRecoveryTimeout;
+    UINT            uRatePollTimeout;
+    UINT            uTxFailures;
+    UINT            uTxAttempts;
+
+    UINT            uTxRetry;
+    UINT            uFailureRatio;
+    UINT            uRetryRatio;
+    UINT            uTxOk[MAX_RATE+1];
+    UINT            uTxFail[MAX_RATE+1];
+    UINT            uTimeCount;
+
+} KnownNodeDB, DEF* PKnownNodeDB;
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+PKnownBSS
+BSSpSearchBSSList(
+    IN HANDLE hDeviceContext,
+    IN PBYTE pbyDesireBSSID,
+    IN PBYTE pbyDesireSSID,
+    IN CARD_PHY_TYPE ePhyType
+    );
+
+PKnownBSS
+BSSpAddrIsInBSSList(
+    IN HANDLE hDeviceContext,
+    IN PBYTE abyBSSID,
+    IN PWLAN_IE_SSID pSSID
+    );
+
+VOID
+BSSvClearBSSList(
+    IN HANDLE hDeviceContext,
+    IN BOOL bKeepCurrBSSID
+    );
+
+BOOL
+BSSbInsertToBSSList(
+    IN HANDLE hDeviceContext,
+    IN PBYTE abyBSSIDAddr,
+    IN QWORD qwTimestamp,
+    IN WORD wBeaconInterval,
+    IN WORD wCapInfo,
+    IN BYTE byCurrChannel,
+    IN PWLAN_IE_SSID pSSID,
+    IN PWLAN_IE_SUPP_RATES pSuppRates,
+    IN PWLAN_IE_SUPP_RATES pExtSuppRates,
+    IN PERPObject psERP,
+    IN PWLAN_IE_RSN pRSN,
+    IN PWLAN_IE_RSN_EXT pRSNWPA,
+    IN PWLAN_IE_COUNTRY pIE_Country,
+    IN PWLAN_IE_QUIET pIE_Quiet,
+    IN UINT uIELength,
+    IN PBYTE pbyIEs,
+    IN HANDLE pRxPacketContext
+    );
+
+
+BOOL
+BSSbUpdateToBSSList(
+    IN HANDLE hDeviceContext,
+    IN QWORD qwTimestamp,
+    IN WORD wBeaconInterval,
+    IN WORD wCapInfo,
+    IN BYTE byCurrChannel,
+    IN BOOL bChannelHit,
+    IN PWLAN_IE_SSID pSSID,
+    IN PWLAN_IE_SUPP_RATES pSuppRates,
+    IN PWLAN_IE_SUPP_RATES pExtSuppRates,
+    IN PERPObject psERP,
+    IN PWLAN_IE_RSN pRSN,
+    IN PWLAN_IE_RSN_EXT pRSNWPA,
+    IN PWLAN_IE_COUNTRY pIE_Country,
+    IN PWLAN_IE_QUIET pIE_Quiet,
+    IN PKnownBSS pBSSList,
+    IN UINT uIELength,
+    IN PBYTE pbyIEs,
+    IN HANDLE pRxPacketContext
+    );
+
+
+BOOL
+BSSDBbIsSTAInNodeDB(
+    IN HANDLE hDeviceContext,
+    IN PBYTE abyDstAddr,
+    OUT PUINT puNodeIndex
+    );
+
+VOID
+BSSvCreateOneNode(
+    IN HANDLE hDeviceContext,
+    OUT PUINT puNodeIndex
+    );
+
+VOID
+BSSvUpdateAPNode(
+    IN HANDLE hDeviceContext,
+    IN PWORD pwCapInfo,
+    IN PWLAN_IE_SUPP_RATES pItemRates,
+    IN PWLAN_IE_SUPP_RATES pExtSuppRates
+    );
+
+
+VOID
+BSSvSecondCallBack(
+    IN HANDLE hDeviceContext
+    );
+
+VOID
+BSSvUpdateNodeTxCounter(
+    IN HANDLE hDeviceContext,
+    IN BYTE        byTsr0,
+    IN BYTE        byTsr1,
+    IN PBYTE       pbyBuffer,
+    IN UINT        uFIFOHeaderSize
+    );
+
+VOID
+BSSvRemoveOneNode(
+    IN HANDLE hDeviceContext,
+    IN UINT uNodeIndex
+    );
+
+VOID
+BSSvAddMulticastNode(
+    IN HANDLE hDeviceContext
+    );
+
+
+VOID
+BSSvClearNodeDBTable(
+    IN HANDLE hDeviceContext,
+    IN UINT uStartIndex
+    );
+
+VOID
+BSSvClearAnyBSSJoinRecord(
+    IN HANDLE hDeviceContext
+    );
+
+#endif //__BSSDB_H__
diff --git a/drivers/staging/vt6655/card.c b/drivers/staging/vt6655/card.c
new file mode 100644
index 0000000..723f44e
--- /dev/null
+++ b/drivers/staging/vt6655/card.c
@@ -0,0 +1,3126 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: card.c
+ * Purpose: Provide functions to setup NIC operation mode
+ * Functions:
+ *      s_vSafeResetTx - Rest Tx
+ *      CARDvSetRSPINF - Set RSPINF
+ *      vUpdateIFS - Update slotTime,SIFS,DIFS, and EIFS
+ *      CARDvUpdateBasicTopRate - Update BasicTopRate
+ *      CARDbAddBasicRate - Add to BasicRateSet
+ *      CARDbSetBasicRate - Set Basic Tx Rate
+ *      CARDbIsOFDMinBasicRate - Check if any OFDM rate is in BasicRateSet
+ *      CARDvSetLoopbackMode - Set Loopback mode
+ *      CARDbSoftwareReset - Sortware reset NIC
+ *      CARDqGetTSFOffset - Caculate TSFOffset
+ *      CARDbGetCurrentTSF - Read Current NIC TSF counter
+ *      CARDqGetNextTBTT - Caculate Next Beacon TSF counter
+ *      CARDvSetFirstNextTBTT - Set NIC Beacon time
+ *      CARDvUpdateNextTBTT - Sync. NIC Beacon time
+ *      CARDbRadioPowerOff - Turn Off NIC Radio Power
+ *      CARDbRadioPowerOn - Turn On NIC Radio Power
+ *      CARDbSetWEPMode - Set NIC Wep mode
+ *      CARDbSetTxPower - Set NIC tx power
+ *
+ * Revision History:
+ *      06-10-2003 Bryan YC Fan:  Re-write codes to support VT3253 spec.
+ *      08-26-2003 Kyle Hsu:      Modify the defination type of dwIoBase.
+ *      09-01-2003 Bryan YC Fan:  Add vUpdateIFS().
+ *
+ */
+
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__DESC_H__)
+#include "desc.h"
+#endif
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+#if !defined(__VNTWIFI_H__)
+#include "vntwifi.h"
+#endif
+#if !defined(__POWER_H__)
+#include "power.h"
+#endif
+#if !defined(__KEY_H__)
+#include "key.h"
+#endif
+#if !defined(__RC4_H__)
+#include "rc4.h"
+#endif
+#if !defined(__COUNTRY_H__)
+#include "country.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+static int          msglevel                =MSG_LEVEL_INFO;
+
+#define C_SIFS_A        16      // micro sec.
+#define C_SIFS_BG       10
+
+#define C_EIFS          80      // micro sec.
+
+
+#define C_SLOT_SHORT    9       // micro sec.
+#define C_SLOT_LONG     20
+
+#define C_CWMIN_A       15      // slot time
+#define C_CWMIN_B       31
+
+#define C_CWMAX         1023    // slot time
+
+#define CARD_MAX_CHANNEL_TBL    56
+
+#define WAIT_BEACON_TX_DOWN_TMO         3    // Times
+
+typedef struct tagSChannelTblElement {
+    BYTE    byChannelNumber;
+    UINT    uFrequency;
+    BOOL    bValid;
+    BYTE    byMAP;
+}SChannelTblElement, DEF* PSChannelTblElement;
+
+                                                              //1M,   2M,   5M,  11M,  18M,  24M,  36M,  54M
+static BYTE abyDefaultSuppRatesG[] = {WLAN_EID_SUPP_RATES, 8, 0x02, 0x04, 0x0B, 0x16, 0x24, 0x30, 0x48, 0x6C};
+                                                                    //6M,   9M,  12M,  48M
+static BYTE abyDefaultExtSuppRatesG[] = {WLAN_EID_EXTSUPP_RATES, 4, 0x0C, 0x12, 0x18, 0x60};
+                                                              //6M,   9M,  12M,  18M,  24M,  36M,  48M,  54M
+static BYTE abyDefaultSuppRatesA[] = {WLAN_EID_SUPP_RATES, 8, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x48, 0x60, 0x6C};
+                                                              //1M,   2M,   5M,  11M,
+static BYTE abyDefaultSuppRatesB[] = {WLAN_EID_SUPP_RATES, 4, 0x02, 0x04, 0x0B, 0x16};
+
+
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+
+const WORD cwRXBCNTSFOff[MAX_RATE] =
+{17, 17, 17, 17, 34, 23, 17, 11, 8, 5, 4, 3};
+
+static SChannelTblElement sChannelTbl[CARD_MAX_CHANNEL_TBL+1] =
+{
+  {0,   0,    FALSE,    0},
+  {1,   2412, TRUE,     0},
+  {2,   2417, TRUE,     0},
+  {3,   2422, TRUE,     0},
+  {4,   2427, TRUE,     0},
+  {5,   2432, TRUE,     0},
+  {6,   2437, TRUE,     0},
+  {7,   2442, TRUE,     0},
+  {8,   2447, TRUE,     0},
+  {9,   2452, TRUE,     0},
+  {10,  2457, TRUE,     0},
+  {11,  2462, TRUE,     0},
+  {12,  2467, TRUE,     0},
+  {13,  2472, TRUE,     0},
+  {14,  2484, TRUE,     0},
+  {183, 4915, TRUE,     0},
+  {184, 4920, TRUE,     0},
+  {185, 4925, TRUE,     0},
+  {187, 4935, TRUE,     0},
+  {188, 4940, TRUE,     0},
+  {189, 4945, TRUE,     0},
+  {192, 4960, TRUE,     0},
+  {196, 4980, TRUE,     0},
+  {7,   5035, TRUE,     0},
+  {8,   5040, TRUE,     0},
+  {9,   5045, TRUE,     0},
+  {11,  5055, TRUE,     0},
+  {12,  5060, TRUE,     0},
+  {16,  5080, TRUE,     0},
+  {34,  5170, TRUE,     0},
+  {36,  5180, TRUE,     0},
+  {38,  5190, TRUE,     0},
+  {40,  5200, TRUE,     0},
+  {42,  5210, TRUE,     0},
+  {44,  5220, TRUE,     0},
+  {46,  5230, TRUE,     0},
+  {48,  5240, TRUE,     0},
+  {52,  5260, TRUE,     0},
+  {56,  5280, TRUE,     0},
+  {60,  5300, TRUE,     0},
+  {64,  5320, TRUE,     0},
+  {100, 5500, TRUE,     0},
+  {104, 5520, TRUE,     0},
+  {108, 5540, TRUE,     0},
+  {112, 5560, TRUE,     0},
+  {116, 5580, TRUE,     0},
+  {120, 5600, TRUE,     0},
+  {124, 5620, TRUE,     0},
+  {128, 5640, TRUE,     0},
+  {132, 5660, TRUE,     0},
+  {136, 5680, TRUE,     0},
+  {140, 5700, TRUE,     0},
+  {149, 5745, TRUE,     0},
+  {153, 5765, TRUE,     0},
+  {157, 5785, TRUE,     0},
+  {161, 5805, TRUE,     0},
+  {165, 5825, TRUE,     0}
+};
+
+
+/************************************************************************
+ * The Radar regulation rules for each country
+ ************************************************************************/
+SCountryTable ChannelRuleTab[CCODE_MAX+1] =
+{
+/************************************************************************
+ * This table is based on Athero driver rules
+ ************************************************************************/
+/* Country          Available channels, ended with 0                    */
+/*                                              1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  */
+{CCODE_FCC,                     {'U','S'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,  0, 17,  0, 17,  0, 17, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_TELEC,                   {'J','P'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  0,  0,  1,  0,  1,  1,  0,  1,  0,  0,  1,  1,  1,  0,  1,  0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0, 23,  0,  0, 23,  0, 23, 23,  0, 23,  0,  0, 23, 23, 23,  0, 23,  0, 23,  0, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_ETSI,                    {'E','U'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_RESV3,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RESV4,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RESV5,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RESV6,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RESV7,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RESV8,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RESV9,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RESVa,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RESVb,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RESVc,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RESVd,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RESVe,                   {' ',' '},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_ALLBAND,                 {' ',' '},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_ALBANIA,                 {'A','L'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_ALGERIA,                 {'D','Z'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_ARGENTINA,               {'A','R'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17, 17, 17,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30,  0}  },
+{CCODE_ARMENIA,                 {'A','M'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 18,  0, 18,  0, 18,  0, 18, 18, 18, 18, 18,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_AUSTRALIA,               {'A','U'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 23,  0, 23,  0, 23,  0, 23, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_AUSTRIA,                 {'A','T'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 15,  0, 15,  0, 15,  0, 15,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_AZERBAIJAN,              {'A','Z'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 18,  0, 18,  0, 18,  0, 18, 18, 18, 18, 18,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_BAHRAIN,                 {'B','H'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_BELARUS,                 {'B','Y'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_BELGIUM,                 {'B','E'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 18,  0, 18,  0, 18,  0, 18,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_BELIZE,                  {'B','Z'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_BOLIVIA,                 {'B','O'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_BRAZIL,                  {'B','R'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_BRUNEI_DARUSSALAM,       {'B','N'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_BULGARIA,                {'B','G'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 23,  0, 23,  0, 23,  0, 23, 23, 23,  0,  0, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,  0,  0,  0,  0,  0}  },
+{CCODE_CANADA,                  {'C','A'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,  0, 17,  0, 17,  0, 17, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_CHILE,                   {'C','L'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17, 17, 17, 17, 17}  },
+{CCODE_CHINA,                   {'C','N'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_COLOMBIA,                {'C','O'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,  0, 17,  0, 17,  0, 17, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_COSTA_RICA,              {'C','R'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_CROATIA,                 {'H','R'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_CYPRUS,                  {'C','Y'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_CZECH,                   {'C','Z'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_DENMARK,                 {'D','K'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_DOMINICAN_REPUBLIC,      {'D','O'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,  0, 17,  0, 17,  0, 17, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_ECUADOR,                 {'E','C'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_EGYPT,                   {'E','G'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_EL_SALVADOR,             {'S','V'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_ESTONIA,                 {'E','E'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_FINLAND,                 {'F','I'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_FRANCE,                  {'F','R'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_GERMANY,                 {'D','E'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_GREECE,                  {'G','R'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_GEORGIA,                 {'G','E'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 18,  0, 18,  0, 18,  0, 18, 18, 18, 18, 18,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_GUATEMALA,               {'G','T'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,  0, 17,  0, 17,  0, 17, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_HONDURAS,                {'H','N'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_HONG_KONG,               {'H','K'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 23,  0, 23,  0, 23,  0, 23, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_HUNGARY,                 {'H','U'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 18,  0, 18,  0, 18,  0, 18,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_ICELAND,                 {'I','S'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_INDIA,                   {'I','N'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_INDONESIA,               {'I','D'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_IRAN,                    {'I','R'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_IRELAND,                 {'I','E'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_ITALY,                   {'I','T'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_ISRAEL,                  {'I','L'},  {   0,  0,  0,  0,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_JAPAN,                   {'J','P'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 23,  0, 23,  0, 23,  0, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_JORDAN,                  {'J','O'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_KAZAKHSTAN,              {'K','Z'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_KUWAIT,                  {'K','W'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_LATVIA,                  {'L','V'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_LEBANON,                 {'L','B'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_LEICHTENSTEIN,           {'L','I'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 18,  0, 18,  0, 18,  0, 18,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_LITHUANIA,               {'L','T'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_LUXEMBURG,               {'L','U'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_MACAU,                   {'M','O'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 23,  0, 23,  0, 23,  0, 23, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_MACEDONIA,               {'M','K'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_MALTA,                   {'M','T'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0}
+                                         ,  {  23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16,  0, 16,  0, 16,  0, 16, 16, 16, 16, 16,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 16, 16, 16,  0}  },
+{CCODE_MALAYSIA,                {'M','Y'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_MEXICO,                  {'M','X'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,  0, 17,  0, 17,  0, 17, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_MONACO,                  {'M','C'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 18,  0, 18,  0, 18,  0, 18, 18, 18, 18, 18,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_MOROCCO,                 {'M','A'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_NETHERLANDS,             {'N','L'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_NEW_ZEALAND,             {'N','Z'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 23,  0, 23,  0, 23,  0, 23, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_NORTH_KOREA,             {'K','P'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 23, 23, 23, 23,  0}  },
+{CCODE_NORWAY,                  {'N','O'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_OMAN,                    {'O','M'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_PAKISTAN,                {'P','K'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_PANAMA,                  {'P','A'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,  0, 17,  0, 17,  0, 17, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_PERU,                    {'P','E'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_PHILIPPINES,             {'P','H'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,  0, 17,  0, 17,  0, 17, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_POLAND,                  {'P','L'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_PORTUGAL,                {'P','T'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_PUERTO_RICO,             {'P','R'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,  0, 17,  0, 17,  0, 17, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_QATAR,                   {'Q','A'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_ROMANIA,                 {'R','O'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_RUSSIA,                  {'R','U'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_SAUDI_ARABIA,            {'S','A'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_SINGAPORE,               {'S','G'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20, 20, 20, 20, 20}  },
+{CCODE_SLOVAKIA,                {'S','K'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0}
+                                         ,  {  23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16,  0, 16,  0, 16,  0, 16, 16, 16, 16, 16,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 16, 16, 16,  0}  },
+{CCODE_SLOVENIA,                {'S','I'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_SOUTH_AFRICA,            {'Z','A'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_SOUTH_KOREA,             {'K','R'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 23, 23, 23, 23,  0}  },
+{CCODE_SPAIN,                   {'E','S'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0}
+                                         ,  {  23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16,  0, 16,  0, 16,  0, 16, 16, 16, 16, 16,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 16, 16, 16,  0}  },
+{CCODE_SWEDEN,                  {'S','E'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_SWITZERLAND,             {'C','H'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 18,  0, 18,  0, 18,  0, 18,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_SYRIA,                   {'S','Y'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_TAIWAN,                  {'T','W'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17, 17, 17,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30,  0}  },
+{CCODE_THAILAND,                {'T','H'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 23, 23, 23, 23,  0}  },
+{CCODE_TRINIDAD_TOBAGO,         {'T','T'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 18,  0, 18,  0, 18,  0, 18, 18, 18, 18, 18,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_TUNISIA,                 {'T','N'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_TURKEY,                  {'T','R'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_UK,                      {'G','B'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 20,  0, 20,  0, 20,  0, 20, 20, 20, 20, 20, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0}  },
+{CCODE_UKRAINE,                 {'U','A'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_UNITED_ARAB_EMIRATES,    {'A','E'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_UNITED_STATES,           {'U','S'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1}
+                                         ,  {  27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 17,  0, 17,  0, 17,  0, 17, 23, 23, 23, 23,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 30, 30, 30, 30, 30}  },
+{CCODE_URUGUAY,                 {'U','Y'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 23, 23, 23, 23,  0}  },
+{CCODE_UZBEKISTAN,              {'U','Z'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_VENEZUELA,               {'V','E'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  0}
+                                         ,  {  20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 23, 23, 23, 23,  0}  },
+{CCODE_VIETNAM,                 {'V','N'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_YEMEN,                   {'Y','E'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_ZIMBABWE,                {'Z','W'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_JAPAN_W52_W53,           {'J','J'},  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  1,  0,  1,  0,  1,  1,  1,  1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  },
+{CCODE_MAX,                     {'U','N'},  {   1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1}
+                                         ,  {   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0}  }
+/*                                              1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  */
+};
+
+
+/*---------------------  Static Functions  --------------------------*/
+
+static
+VOID
+s_vCaculateOFDMRParameter(
+    IN  BYTE byRate,
+    IN  CARD_PHY_TYPE ePHYType,
+    OUT PBYTE pbyTxRate,
+    OUT PBYTE pbyRsvTime
+    );
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+/*---------------------  Export function  -------------------------*/
+/************************************************************************
+ * Country Channel Valid
+ *  Input:  CountryCode, ChannelNum
+ *          ChanneIndex is defined as VT3253 MAC channel:
+ *              1   = 2.4G channel 1
+ *              2   = 2.4G channel 2
+ *              ...
+ *              14  = 2.4G channel 14
+ *              15  = 4.9G channel 183
+ *              16  = 4.9G channel 184
+ *              .....
+ *  Output: TRUE if the specified 5GHz band is allowed to be used.
+            False otherwise.
+// 4.9G => Ch 183, 184, 185, 187, 188, 189, 192, 196 (Value:15 ~ 22)
+
+// 5G => Ch 7, 8, 9, 11, 12, 16, 34, 36, 38, 40, 42, 44, 46, 48, 52, 56, 60, 64,
+// 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 149, 153, 157, 161, 165 (Value 23 ~ 56)
+ ************************************************************************/
+//2008-8-4 <add> by chester
+BOOL
+ChannelValid(UINT CountryCode, UINT ChannelIndex)
+{
+    BOOL    bValid;
+
+    bValid = FALSE;
+    /*
+     * If Channel Index is invalid, return invalid
+     */
+    if ((ChannelIndex > CB_MAX_CHANNEL) ||
+        (ChannelIndex == 0))
+    {
+        bValid = FALSE;
+        goto exit;
+    }
+
+    bValid = sChannelTbl[ChannelIndex].bValid;
+
+exit:
+    return (bValid);
+
+} /* end ChannelValid */
+
+
+/*
+ * Description: Caculate TxRate and RsvTime fields for RSPINF in OFDM mode.
+ *
+ * Parameters:
+ *  In:
+ *      wRate           - Tx Rate
+ *      byPktType       - Tx Packet type
+ *  Out:
+ *      pbyTxRate       - pointer to RSPINF TxRate field
+ *      pbyRsvTime      - pointer to RSPINF RsvTime field
+ *
+ * Return Value: none
+ *
+ */
+static
+VOID
+s_vCaculateOFDMRParameter (
+    IN  BYTE byRate,
+    IN  CARD_PHY_TYPE ePHYType,
+    OUT PBYTE pbyTxRate,
+    OUT PBYTE pbyRsvTime
+    )
+{
+    switch (byRate) {
+    case RATE_6M :
+        if (ePHYType == PHY_TYPE_11A) {//5GHZ
+            *pbyTxRate = 0x9B;
+            *pbyRsvTime = 44;
+        }
+        else {
+            *pbyTxRate = 0x8B;
+            *pbyRsvTime = 50;
+        }
+        break;
+
+    case RATE_9M :
+        if (ePHYType == PHY_TYPE_11A) {//5GHZ
+            *pbyTxRate = 0x9F;
+            *pbyRsvTime = 36;
+        }
+        else {
+            *pbyTxRate = 0x8F;
+            *pbyRsvTime = 42;
+        }
+        break;
+
+   case RATE_12M :
+        if (ePHYType == PHY_TYPE_11A) {//5GHZ
+            *pbyTxRate = 0x9A;
+            *pbyRsvTime = 32;
+        }
+        else {
+            *pbyTxRate = 0x8A;
+            *pbyRsvTime = 38;
+        }
+        break;
+
+   case RATE_18M :
+        if (ePHYType == PHY_TYPE_11A) {//5GHZ
+            *pbyTxRate = 0x9E;
+            *pbyRsvTime = 28;
+        }
+        else {
+            *pbyTxRate = 0x8E;
+            *pbyRsvTime = 34;
+        }
+        break;
+
+    case RATE_36M :
+        if (ePHYType == PHY_TYPE_11A) {//5GHZ
+            *pbyTxRate = 0x9D;
+            *pbyRsvTime = 24;
+        }
+        else {
+            *pbyTxRate = 0x8D;
+            *pbyRsvTime = 30;
+        }
+        break;
+
+    case RATE_48M :
+        if (ePHYType == PHY_TYPE_11A) {//5GHZ
+            *pbyTxRate = 0x98;
+            *pbyRsvTime = 24;
+        }
+        else {
+            *pbyTxRate = 0x88;
+            *pbyRsvTime = 30;
+        }
+        break;
+
+    case RATE_54M :
+        if (ePHYType == PHY_TYPE_11A) {//5GHZ
+            *pbyTxRate = 0x9C;
+            *pbyRsvTime = 24;
+        }
+        else {
+            *pbyTxRate = 0x8C;
+            *pbyRsvTime = 30;
+        }
+        break;
+
+    case RATE_24M :
+    default :
+        if (ePHYType == PHY_TYPE_11A) {//5GHZ
+            *pbyTxRate = 0x99;
+            *pbyRsvTime = 28;
+        }
+        else {
+            *pbyTxRate = 0x89;
+            *pbyRsvTime = 34;
+        }
+        break;
+    }
+}
+
+
+
+/*
+ * Description: Set RSPINF
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             - The adapter to be set
+ *  Out:
+ *      none
+ *
+ * Return Value: None.
+ *
+ */
+static
+VOID
+s_vSetRSPINF (PSDevice pDevice, CARD_PHY_TYPE ePHYType, PVOID pvSupportRateIEs, PVOID pvExtSupportRateIEs)
+{
+    BYTE  byServ = 0, bySignal = 0; // For CCK
+    WORD  wLen = 0;
+    BYTE  byTxRate = 0, byRsvTime = 0;    // For OFDM
+
+    //Set to Page1
+    MACvSelectPage1(pDevice->PortOffset);
+
+    //RSPINF_b_1
+    BBvCaculateParameter(pDevice,
+                         14,
+                         VNTWIFIbyGetACKTxRate(RATE_1M, pvSupportRateIEs, pvExtSupportRateIEs),
+                         PK_TYPE_11B,
+                         &wLen,
+                         &byServ,
+                         &bySignal
+    );
+
+    VNSvOutPortD(pDevice->PortOffset + MAC_REG_RSPINF_B_1, MAKEDWORD(wLen,MAKEWORD(bySignal,byServ)));
+    ///RSPINF_b_2
+    BBvCaculateParameter(pDevice,
+                         14,
+                         VNTWIFIbyGetACKTxRate(RATE_2M, pvSupportRateIEs, pvExtSupportRateIEs),
+                         PK_TYPE_11B,
+                         &wLen,
+                         &byServ,
+                         &bySignal
+    );
+
+    VNSvOutPortD(pDevice->PortOffset + MAC_REG_RSPINF_B_2, MAKEDWORD(wLen,MAKEWORD(bySignal,byServ)));
+    //RSPINF_b_5
+    BBvCaculateParameter(pDevice,
+                         14,
+                         VNTWIFIbyGetACKTxRate(RATE_5M, pvSupportRateIEs, pvExtSupportRateIEs),
+                         PK_TYPE_11B,
+                         &wLen,
+                         &byServ,
+                         &bySignal
+    );
+
+    VNSvOutPortD(pDevice->PortOffset + MAC_REG_RSPINF_B_5, MAKEDWORD(wLen,MAKEWORD(bySignal,byServ)));
+    //RSPINF_b_11
+    BBvCaculateParameter(pDevice,
+                         14,
+                         VNTWIFIbyGetACKTxRate(RATE_11M, pvSupportRateIEs, pvExtSupportRateIEs),
+                         PK_TYPE_11B,
+                         &wLen,
+                         &byServ,
+                         &bySignal
+    );
+
+    VNSvOutPortD(pDevice->PortOffset + MAC_REG_RSPINF_B_11, MAKEDWORD(wLen,MAKEWORD(bySignal,byServ)));
+    //RSPINF_a_6
+    s_vCaculateOFDMRParameter(RATE_6M,
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_6, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_9
+    s_vCaculateOFDMRParameter(RATE_9M,
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_9, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_12
+    s_vCaculateOFDMRParameter(RATE_12M,
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_12, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_18
+    s_vCaculateOFDMRParameter(RATE_18M,
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_18, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_24
+    s_vCaculateOFDMRParameter(RATE_24M,
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_24, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_36
+    s_vCaculateOFDMRParameter(
+                              VNTWIFIbyGetACKTxRate(RATE_36M, pvSupportRateIEs, pvExtSupportRateIEs),
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_36, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_48
+    s_vCaculateOFDMRParameter(
+                              VNTWIFIbyGetACKTxRate(RATE_48M, pvSupportRateIEs, pvExtSupportRateIEs),
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_48, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_54
+    s_vCaculateOFDMRParameter(
+                              VNTWIFIbyGetACKTxRate(RATE_54M, pvSupportRateIEs, pvExtSupportRateIEs),
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_54, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_72
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_72, MAKEWORD(byTxRate,byRsvTime));
+    //Set to Page0
+    MACvSelectPage0(pDevice->PortOffset);
+}
+
+
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+BYTE CARDbyGetChannelMapping (PVOID pDeviceHandler, BYTE byChannelNumber, CARD_PHY_TYPE ePhyType)
+{
+    UINT        ii;
+
+    if ((ePhyType == PHY_TYPE_11B) || (ePhyType == PHY_TYPE_11G)) {
+        return (byChannelNumber);
+    }
+
+    for(ii = (CB_MAX_CHANNEL_24G + 1); ii <= CB_MAX_CHANNEL; ) {
+        if (sChannelTbl[ii].byChannelNumber == byChannelNumber) {
+            return ((BYTE) ii);
+        }
+        ii++;
+    }
+    return (0);
+}
+
+
+BYTE CARDbyGetChannelNumber (PVOID pDeviceHandler, BYTE byChannelIndex)
+{
+//    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    return(sChannelTbl[byChannelIndex].byChannelNumber);
+}
+
+/*
+ * Description: Set NIC media channel
+ *
+ * Parameters:
+ *  In:
+ *      pDeviceHandler      - The adapter to be set
+ *      uConnectionChannel  - Channel to be set
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL CARDbSetChannel (PVOID pDeviceHandler, UINT uConnectionChannel)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    BOOL        bResult = TRUE;
+
+
+    if (pDevice->byCurrentCh == uConnectionChannel) {
+        return bResult;
+    }
+
+    if (sChannelTbl[uConnectionChannel].bValid == FALSE) {
+        return (FALSE);
+    }
+
+    if ((uConnectionChannel > CB_MAX_CHANNEL_24G) &&
+        (pDevice->eCurrentPHYType != PHY_TYPE_11A)) {
+        CARDbSetPhyParameter(pDevice, PHY_TYPE_11A, 0, 0, NULL, NULL);
+    } else if ((uConnectionChannel <= CB_MAX_CHANNEL_24G) &&
+        (pDevice->eCurrentPHYType == PHY_TYPE_11A)) {
+        CARDbSetPhyParameter(pDevice, PHY_TYPE_11G, 0, 0, NULL, NULL);
+    }
+    // clear NAV
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MACCR, MACCR_CLRNAV);
+
+    //{{ RobertYu: 20041202
+    //// TX_PE will reserve 3 us for MAX2829 A mode only, it is for better TX throughput
+
+    if ( pDevice->byRFType == RF_AIROHA7230 )
+    {
+        RFbAL7230SelectChannelPostProcess(pDevice->PortOffset, pDevice->byCurrentCh, (BYTE)uConnectionChannel);
+    }
+    //}} RobertYu
+
+
+    pDevice->byCurrentCh = (BYTE)uConnectionChannel;
+    bResult &= RFbSelectChannel(pDevice->PortOffset, pDevice->byRFType, (BYTE)uConnectionChannel);
+
+    // Init Synthesizer Table
+    if (pDevice->bEnablePSMode == TRUE)
+        RFvWriteWakeProgSyn(pDevice->PortOffset, pDevice->byRFType, uConnectionChannel);
+
+
+    //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"CARDbSetMediaChannel: %d\n", (BYTE)uConnectionChannel);
+    BBvSoftwareReset(pDevice->PortOffset);
+
+    if (pDevice->byLocalID > REV_ID_VT3253_B1) {
+        // set HW default power register
+        MACvSelectPage1(pDevice->PortOffset);
+        RFbSetPower(pDevice, RATE_1M, pDevice->byCurrentCh);
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_PWRCCK, pDevice->byCurPwr);
+        RFbSetPower(pDevice, RATE_6M, pDevice->byCurrentCh);
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_PWROFDM, pDevice->byCurPwr);
+        MACvSelectPage0(pDevice->PortOffset);
+    }
+
+    if (pDevice->eCurrentPHYType == PHY_TYPE_11B) {
+#ifdef	PLICE_DEBUG
+	//printk("Func:CARDbSetChannel:call RFbSetPower:11B\n");
+#endif
+        RFbSetPower(pDevice, RATE_1M, pDevice->byCurrentCh);
+    } else {
+#ifdef	PLICE_DEBUG
+	//printk("Func:CARDbSetChannel:call RFbSetPower\n");
+#endif
+		RFbSetPower(pDevice, RATE_6M, pDevice->byCurrentCh);
+    }
+
+    return(bResult);
+}
+
+
+
+/*
+ * Description: Card Send packet function
+ *
+ * Parameters:
+ *  In:
+ *      pDeviceHandler      - The adapter to be set
+ *      pPacket             - Packet buffer pointer
+ *      ePktType            - Packet type
+ *      uLength             - Packet length
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+/*
+BOOL CARDbSendPacket (PVOID pDeviceHandler, PVOID pPacket, CARD_PKT_TYPE ePktType, UINT uLength)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    if (ePktType == PKT_TYPE_802_11_MNG) {
+        return TXbTD0Send(pDevice, pPacket, uLength);
+    } else if (ePktType == PKT_TYPE_802_11_BCN) {
+        return TXbBeaconSend(pDevice, pPacket, uLength);
+    } if (ePktType == PKT_TYPE_802_11_DATA) {
+        return TXbTD1Send(pDevice, pPacket, uLength);
+    }
+
+    return (TRUE);
+}
+*/
+
+
+/*
+ * Description: Get Card short preamble option value
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             - The adapter to be set
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if short preamble; otherwise FALSE
+ *
+ */
+BOOL CARDbIsShortPreamble (PVOID pDeviceHandler)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    if (pDevice->byPreambleType == 0) {
+        return(FALSE);
+    }
+    return(TRUE);
+}
+
+/*
+ * Description: Get Card short slot time option value
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             - The adapter to be set
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if short slot time; otherwise FALSE
+ *
+ */
+BOOL CARDbIsShorSlotTime (PVOID pDeviceHandler)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    return(pDevice->bShortSlotTime);
+}
+
+
+/*
+ * Description: Update IFS
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             - The adapter to be set
+ *  Out:
+ *      none
+ *
+ * Return Value: None.
+ *
+ */
+BOOL CARDbSetPhyParameter (PVOID pDeviceHandler, CARD_PHY_TYPE ePHYType, WORD wCapInfo, BYTE byERPField, PVOID pvSupportRateIEs, PVOID pvExtSupportRateIEs)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    BYTE        byCWMaxMin = 0;
+    BYTE        bySlot = 0;
+    BYTE        bySIFS = 0;
+    BYTE        byDIFS = 0;
+    BYTE        byData;
+//    PWLAN_IE_SUPP_RATES pRates = NULL;
+    PWLAN_IE_SUPP_RATES pSupportRates = (PWLAN_IE_SUPP_RATES) pvSupportRateIEs;
+    PWLAN_IE_SUPP_RATES pExtSupportRates = (PWLAN_IE_SUPP_RATES) pvExtSupportRateIEs;
+
+
+    //Set SIFS, DIFS, EIFS, SlotTime, CwMin
+    if (ePHYType == PHY_TYPE_11A) {
+        if (pSupportRates == NULL) {
+            pSupportRates = (PWLAN_IE_SUPP_RATES) abyDefaultSuppRatesA;
+        }
+        if (pDevice->byRFType == RF_AIROHA7230) {
+            // AL7230 use single PAPE and connect to PAPE_2.4G
+            MACvSetBBType(pDevice->PortOffset, BB_TYPE_11G);
+            pDevice->abyBBVGA[0] = 0x20;
+            pDevice->abyBBVGA[2] = 0x10;
+            pDevice->abyBBVGA[3] = 0x10;
+            BBbReadEmbeded(pDevice->PortOffset, 0xE7, &byData);
+            if (byData == 0x1C) {
+                BBbWriteEmbeded(pDevice->PortOffset, 0xE7, pDevice->abyBBVGA[0]);
+            }
+        } else if (pDevice->byRFType == RF_UW2452) {
+            MACvSetBBType(pDevice->PortOffset, BB_TYPE_11A);
+            pDevice->abyBBVGA[0] = 0x18;
+            BBbReadEmbeded(pDevice->PortOffset, 0xE7, &byData);
+            if (byData == 0x14) {
+                BBbWriteEmbeded(pDevice->PortOffset, 0xE7, pDevice->abyBBVGA[0]);
+                BBbWriteEmbeded(pDevice->PortOffset, 0xE1, 0x57);
+            }
+        } else {
+            MACvSetBBType(pDevice->PortOffset, BB_TYPE_11A);
+        }
+        BBbWriteEmbeded(pDevice->PortOffset, 0x88, 0x03);
+        bySlot = C_SLOT_SHORT;
+        bySIFS = C_SIFS_A;
+        byDIFS = C_SIFS_A + 2*C_SLOT_SHORT;
+        byCWMaxMin = 0xA4;
+    } else if (ePHYType == PHY_TYPE_11B) {
+        if (pSupportRates == NULL) {
+            pSupportRates = (PWLAN_IE_SUPP_RATES) abyDefaultSuppRatesB;
+        }
+        MACvSetBBType(pDevice->PortOffset, BB_TYPE_11B);
+        if (pDevice->byRFType == RF_AIROHA7230) {
+            pDevice->abyBBVGA[0] = 0x1C;
+            pDevice->abyBBVGA[2] = 0x00;
+            pDevice->abyBBVGA[3] = 0x00;
+            BBbReadEmbeded(pDevice->PortOffset, 0xE7, &byData);
+            if (byData == 0x20) {
+                BBbWriteEmbeded(pDevice->PortOffset, 0xE7, pDevice->abyBBVGA[0]);
+            }
+        } else if (pDevice->byRFType == RF_UW2452) {
+            pDevice->abyBBVGA[0] = 0x14;
+            BBbReadEmbeded(pDevice->PortOffset, 0xE7, &byData);
+            if (byData == 0x18) {
+                BBbWriteEmbeded(pDevice->PortOffset, 0xE7, pDevice->abyBBVGA[0]);
+                BBbWriteEmbeded(pDevice->PortOffset, 0xE1, 0xD3);
+            }
+        }
+        BBbWriteEmbeded(pDevice->PortOffset, 0x88, 0x02);
+        bySlot = C_SLOT_LONG;
+        bySIFS = C_SIFS_BG;
+        byDIFS = C_SIFS_BG + 2*C_SLOT_LONG;
+        byCWMaxMin = 0xA5;
+    } else {// PK_TYPE_11GA & PK_TYPE_11GB
+        if (pSupportRates == NULL) {
+            pSupportRates = (PWLAN_IE_SUPP_RATES) abyDefaultSuppRatesG;
+            pExtSupportRates = (PWLAN_IE_SUPP_RATES) abyDefaultExtSuppRatesG;
+        }
+        MACvSetBBType(pDevice->PortOffset, BB_TYPE_11G);
+        if (pDevice->byRFType == RF_AIROHA7230) {
+            pDevice->abyBBVGA[0] = 0x1C;
+            pDevice->abyBBVGA[2] = 0x00;
+            pDevice->abyBBVGA[3] = 0x00;
+            BBbReadEmbeded(pDevice->PortOffset, 0xE7, &byData);
+            if (byData == 0x20) {
+                BBbWriteEmbeded(pDevice->PortOffset, 0xE7, pDevice->abyBBVGA[0]);
+            }
+        } else if (pDevice->byRFType == RF_UW2452) {
+            pDevice->abyBBVGA[0] = 0x14;
+            BBbReadEmbeded(pDevice->PortOffset, 0xE7, &byData);
+            if (byData == 0x18) {
+                BBbWriteEmbeded(pDevice->PortOffset, 0xE7, pDevice->abyBBVGA[0]);
+                BBbWriteEmbeded(pDevice->PortOffset, 0xE1, 0xD3);
+            }
+        }
+        BBbWriteEmbeded(pDevice->PortOffset, 0x88, 0x08);
+        bySIFS = C_SIFS_BG;
+        if(VNTWIFIbIsShortSlotTime(wCapInfo)) {
+            bySlot = C_SLOT_SHORT;
+            byDIFS = C_SIFS_BG + 2*C_SLOT_SHORT;
+        } else {
+            bySlot = C_SLOT_LONG;
+            byDIFS = C_SIFS_BG + 2*C_SLOT_LONG;
+	    }
+        if (VNTWIFIbyGetMaxSupportRate(pSupportRates, pExtSupportRates) > RATE_11M) {
+            byCWMaxMin = 0xA4;
+        } else {
+            byCWMaxMin = 0xA5;
+        }
+        if (pDevice->bProtectMode != VNTWIFIbIsProtectMode(byERPField)) {
+            pDevice->bProtectMode = VNTWIFIbIsProtectMode(byERPField);
+            if (pDevice->bProtectMode) {
+                MACvEnableProtectMD(pDevice->PortOffset);
+            } else {
+                MACvDisableProtectMD(pDevice->PortOffset);
+            }
+        }
+        if (pDevice->bBarkerPreambleMd != VNTWIFIbIsBarkerMode(byERPField)) {
+            pDevice->bBarkerPreambleMd = VNTWIFIbIsBarkerMode(byERPField);
+            if (pDevice->bBarkerPreambleMd) {
+                MACvEnableBarkerPreambleMd(pDevice->PortOffset);
+            } else {
+                MACvDisableBarkerPreambleMd(pDevice->PortOffset);
+            }
+        }
+    }
+
+    if (pDevice->byRFType == RF_RFMD2959) {
+        // bcs TX_PE will reserve 3 us
+        // hardware's processing time here is 2 us.
+        bySIFS -= 3;
+        byDIFS -= 3;
+    //{{ RobertYu: 20041202
+    //// TX_PE will reserve 3 us for MAX2829 A mode only, it is for better TX throughput
+    //// MAC will need 2 us to process, so the SIFS, DIFS can be shorter by 2 us.
+    }
+
+    if (pDevice->bySIFS != bySIFS) {
+        pDevice->bySIFS = bySIFS;
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_SIFS, pDevice->bySIFS);
+    }
+    if (pDevice->byDIFS != byDIFS) {
+        pDevice->byDIFS = byDIFS;
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_DIFS, pDevice->byDIFS);
+    }
+    if (pDevice->byEIFS != C_EIFS) {
+        pDevice->byEIFS = C_EIFS;
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_EIFS, pDevice->byEIFS);
+    }
+    if (pDevice->bySlot != bySlot) {
+        pDevice->bySlot = bySlot;
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_SLOT, pDevice->bySlot);
+        if (pDevice->bySlot == C_SLOT_SHORT) {
+            pDevice->bShortSlotTime = TRUE;
+        } else {
+            pDevice->bShortSlotTime = FALSE;
+        }
+        BBvSetShortSlotTime(pDevice);
+    }
+    if (pDevice->byCWMaxMin != byCWMaxMin) {
+        pDevice->byCWMaxMin = byCWMaxMin;
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_CWMAXMIN0, pDevice->byCWMaxMin);
+    }
+    if (VNTWIFIbIsShortPreamble(wCapInfo)) {
+        pDevice->byPreambleType = pDevice->byShortPreamble;
+    } else {
+        pDevice->byPreambleType = 0;
+    }
+    s_vSetRSPINF(pDevice, ePHYType, pSupportRates, pExtSupportRates);
+    pDevice->eCurrentPHYType = ePHYType;
+    // set for NDIS OID_802_11SUPPORTED_RATES
+    return (TRUE);
+}
+
+/*
+ * Description: Sync. TSF counter to BSS
+ *              Get TSF offset and write to HW
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - The adapter to be sync.
+ *      byRxRate        - data rate of receive beacon
+ *      qwBSSTimestamp  - Rx BCN's TSF
+ *      qwLocalTSF      - Local TSF
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+BOOL CARDbUpdateTSF (PVOID pDeviceHandler, BYTE byRxRate, QWORD qwBSSTimestamp, QWORD qwLocalTSF)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    QWORD       qwTSFOffset;
+
+    HIDWORD(qwTSFOffset) = 0;
+    LODWORD(qwTSFOffset) = 0;
+
+    if ((HIDWORD(qwBSSTimestamp) != HIDWORD(qwLocalTSF)) ||
+        (LODWORD(qwBSSTimestamp) != LODWORD(qwLocalTSF))) {
+        qwTSFOffset = CARDqGetTSFOffset(byRxRate, qwBSSTimestamp, qwLocalTSF);
+        // adjust TSF
+        // HW's TSF add TSF Offset reg
+        VNSvOutPortD(pDevice->PortOffset + MAC_REG_TSFOFST, LODWORD(qwTSFOffset));
+        VNSvOutPortD(pDevice->PortOffset + MAC_REG_TSFOFST + 4, HIDWORD(qwTSFOffset));
+        MACvRegBitsOn(pDevice->PortOffset, MAC_REG_TFTCTL, TFTCTL_TSFSYNCEN);
+    }
+    return(TRUE);
+}
+
+
+/*
+ * Description: Set NIC TSF counter for first Beacon time
+ *              Get NEXTTBTT from adjusted TSF and Beacon Interval
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - The adapter to be set.
+ *      wBeaconInterval - Beacon Interval
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeed; otherwise FALSE
+ *
+ */
+BOOL CARDbSetBeaconPeriod (PVOID pDeviceHandler, WORD wBeaconInterval)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    UINT        uBeaconInterval = 0;
+    UINT        uLowNextTBTT = 0;
+    UINT        uHighRemain = 0;
+    UINT        uLowRemain = 0;
+    QWORD       qwNextTBTT;
+
+    HIDWORD(qwNextTBTT) = 0;
+    LODWORD(qwNextTBTT) = 0;
+    CARDbGetCurrentTSF(pDevice->PortOffset, &qwNextTBTT); //Get Local TSF counter
+    uBeaconInterval = wBeaconInterval * 1024;
+    // Next TBTT = ((local_current_TSF / beacon_interval) + 1 ) * beacon_interval
+    uLowNextTBTT = (LODWORD(qwNextTBTT) >> 10) << 10;
+    uLowRemain = (uLowNextTBTT) % uBeaconInterval;
+    // high dword (mod) bcn
+    uHighRemain = (((0xffffffff % uBeaconInterval) + 1) * HIDWORD(qwNextTBTT))
+                  % uBeaconInterval;
+    uLowRemain = (uHighRemain + uLowRemain) % uBeaconInterval;
+    uLowRemain = uBeaconInterval - uLowRemain;
+
+    // check if carry when add one beacon interval
+    if ((~uLowNextTBTT) < uLowRemain) {
+        HIDWORD(qwNextTBTT) ++ ;
+    }
+    LODWORD(qwNextTBTT) = uLowNextTBTT + uLowRemain;
+
+    // set HW beacon interval
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_BI, wBeaconInterval);
+    pDevice->wBeaconInterval = wBeaconInterval;
+    // Set NextTBTT
+    VNSvOutPortD(pDevice->PortOffset + MAC_REG_NEXTTBTT, LODWORD(qwNextTBTT));
+    VNSvOutPortD(pDevice->PortOffset + MAC_REG_NEXTTBTT + 4, HIDWORD(qwNextTBTT));
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_TFTCTL, TFTCTL_TBTTSYNCEN);
+
+    return(TRUE);
+}
+
+
+
+/*
+ * Description: Card Stop Hardware Tx
+ *
+ * Parameters:
+ *  In:
+ *      pDeviceHandler      - The adapter to be set
+ *      ePktType            - Packet type to stop
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if all data packet complete; otherwise FALSE.
+ *
+ */
+BOOL CARDbStopTxPacket (PVOID pDeviceHandler, CARD_PKT_TYPE ePktType)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+
+
+    if (ePktType == PKT_TYPE_802_11_ALL) {
+        pDevice->bStopBeacon = TRUE;
+        pDevice->bStopTx0Pkt = TRUE;
+        pDevice->bStopDataPkt = TRUE;
+    } else if (ePktType == PKT_TYPE_802_11_BCN) {
+        pDevice->bStopBeacon = TRUE;
+    } else if (ePktType == PKT_TYPE_802_11_MNG) {
+        pDevice->bStopTx0Pkt = TRUE;
+    } else if (ePktType == PKT_TYPE_802_11_DATA) {
+        pDevice->bStopDataPkt = TRUE;
+    }
+
+    if (pDevice->bStopBeacon == TRUE) {
+        if (pDevice->bIsBeaconBufReadySet == TRUE) {
+            if (pDevice->cbBeaconBufReadySetCnt < WAIT_BEACON_TX_DOWN_TMO) {
+                pDevice->cbBeaconBufReadySetCnt ++;
+                return(FALSE);
+            }
+        }
+        pDevice->bIsBeaconBufReadySet = FALSE;
+        pDevice->cbBeaconBufReadySetCnt = 0;
+        MACvRegBitsOff(pDevice->PortOffset, MAC_REG_TCR, TCR_AUTOBCNTX);
+    }
+    // wait all TD0 complete
+    if (pDevice->bStopTx0Pkt == TRUE) {
+         if (pDevice->iTDUsed[TYPE_TXDMA0] != 0){
+            return(FALSE);
+        }
+    }
+    // wait all Data TD complete
+    if (pDevice->bStopDataPkt == TRUE) {
+        if (pDevice->iTDUsed[TYPE_AC0DMA] != 0){
+            return(FALSE);
+        }
+    }
+
+    return(TRUE);
+}
+
+
+/*
+ * Description: Card Start Hardware Tx
+ *
+ * Parameters:
+ *  In:
+ *      pDeviceHandler      - The adapter to be set
+ *      ePktType            - Packet type to start
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; FALSE if failed.
+ *
+ */
+BOOL CARDbStartTxPacket (PVOID pDeviceHandler, CARD_PKT_TYPE ePktType)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+
+
+    if (ePktType == PKT_TYPE_802_11_ALL) {
+        pDevice->bStopBeacon = FALSE;
+        pDevice->bStopTx0Pkt = FALSE;
+        pDevice->bStopDataPkt = FALSE;
+    } else if (ePktType == PKT_TYPE_802_11_BCN) {
+        pDevice->bStopBeacon = FALSE;
+    } else if (ePktType == PKT_TYPE_802_11_MNG) {
+        pDevice->bStopTx0Pkt = FALSE;
+    } else if (ePktType == PKT_TYPE_802_11_DATA) {
+        pDevice->bStopDataPkt = FALSE;
+    }
+
+    if ((pDevice->bStopBeacon == FALSE) &&
+        (pDevice->bBeaconBufReady == TRUE) &&
+        (pDevice->eOPMode == OP_MODE_ADHOC)) {
+        MACvRegBitsOn(pDevice->PortOffset, MAC_REG_TCR, TCR_AUTOBCNTX);
+    }
+
+    return(TRUE);
+}
+
+
+
+/*
+ * Description: Card Set BSSID value
+ *
+ * Parameters:
+ *  In:
+ *      pDeviceHandler      - The adapter to be set
+ *      pbyBSSID            - pointer to BSSID field
+ *      bAdhoc              - flag to indicate IBSS
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; FALSE if failed.
+ *
+ */
+BOOL CARDbSetBSSID(PVOID pDeviceHandler, PBYTE pbyBSSID, CARD_OP_MODE eOPMode)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+
+    MACvWriteBSSIDAddress(pDevice->PortOffset, pbyBSSID);
+    MEMvCopy(pDevice->abyBSSID, pbyBSSID, WLAN_BSSID_LEN);
+    if (eOPMode == OP_MODE_ADHOC) {
+        MACvRegBitsOn(pDevice->PortOffset, MAC_REG_HOSTCR, HOSTCR_ADHOC);
+    } else {
+        MACvRegBitsOff(pDevice->PortOffset, MAC_REG_HOSTCR, HOSTCR_ADHOC);
+    }
+    if (eOPMode == OP_MODE_AP) {
+        MACvRegBitsOn(pDevice->PortOffset, MAC_REG_HOSTCR, HOSTCR_AP);
+    } else {
+        MACvRegBitsOff(pDevice->PortOffset, MAC_REG_HOSTCR, HOSTCR_AP);
+    }
+    if (eOPMode == OP_MODE_UNKNOWN) {
+        MACvRegBitsOff(pDevice->PortOffset, MAC_REG_RCR, RCR_BSSID);
+        pDevice->bBSSIDFilter = FALSE;
+        pDevice->byRxMode &= ~RCR_BSSID;
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wcmd: rx_mode = %x\n", pDevice->byRxMode );
+    } else {
+        if (IS_NULL_ADDRESS(pDevice->abyBSSID) == FALSE) {
+            MACvRegBitsOn(pDevice->PortOffset, MAC_REG_RCR, RCR_BSSID);
+            pDevice->bBSSIDFilter = TRUE;
+            pDevice->byRxMode |= RCR_BSSID;
+	    }
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wmgr: rx_mode = %x\n", pDevice->byRxMode );
+    }
+    // Adopt BSS state in Adapter Device Object
+    pDevice->eOPMode = eOPMode;
+    return(TRUE);
+}
+
+
+/*
+ * Description: Card indicate status
+ *
+ * Parameters:
+ *  In:
+ *      pDeviceHandler      - The adapter to be set
+ *      eStatus             - Status
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; FALSE if failed.
+ *
+ */
+
+
+
+
+/*
+ * Description: Save Assoc info. contain in assoc. response frame
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             - The adapter to be set
+ *      wCapabilityInfo     - Capability information
+ *      wStatus             - Status code
+ *      wAID                - Assoc. ID
+ *      uLen                - Length of IEs
+ *      pbyIEs              - pointer to IEs
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeed; otherwise FALSE
+ *
+ */
+BOOL CARDbSetTxDataRate(
+    PVOID   pDeviceHandler,
+    WORD    wDataRate
+    )
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+
+    pDevice->wCurrentRate = wDataRate;
+    return(TRUE);
+}
+
+/*+
+ *
+ * Routine Description:
+ *      Consider to power down when no more packets to tx or rx.
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             - The adapter to be set
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if power down success; otherwise FALSE
+ *
+-*/
+BOOL
+CARDbPowerDown(
+    PVOID   pDeviceHandler
+    )
+{
+    PSDevice        pDevice = (PSDevice)pDeviceHandler;
+    UINT            uIdx;
+
+    // check if already in Doze mode
+    if (MACbIsRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PS))
+        return TRUE;
+
+    // Froce PSEN on
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PSEN);
+
+    // check if all TD are empty,
+
+    for (uIdx = 0; uIdx < TYPE_MAXTD; uIdx ++) {
+        if (pDevice->iTDUsed[uIdx] != 0)
+            return FALSE;
+    }
+
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_GO2DOZE);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Go to Doze ZZZZZZZZZZZZZZZ\n");
+    return TRUE;
+}
+
+/*
+ * Description: Turn off Radio power
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - The adapter to be turned off
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; otherwise FALSE
+ *
+ */
+BOOL CARDbRadioPowerOff (PVOID pDeviceHandler)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    BOOL        bResult = TRUE;
+
+    if (pDevice->bRadioOff == TRUE)
+        return TRUE;
+
+
+    switch (pDevice->byRFType) {
+
+        case RF_RFMD2959:
+            MACvWordRegBitsOff(pDevice->PortOffset, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_TXPEINV);
+            MACvWordRegBitsOn(pDevice->PortOffset, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_SWPE1);
+            break;
+
+        case RF_AIROHA:
+        case RF_AL2230S:
+        case RF_AIROHA7230: //RobertYu:20050104
+            MACvWordRegBitsOff(pDevice->PortOffset, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_SWPE2);
+            MACvWordRegBitsOff(pDevice->PortOffset, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_SWPE3);
+            break;
+
+    }
+
+    MACvRegBitsOff(pDevice->PortOffset, MAC_REG_HOSTCR, HOSTCR_RXON);
+
+    BBvSetDeepSleep(pDevice->PortOffset, pDevice->byLocalID);
+
+    pDevice->bRadioOff = TRUE;
+     //2007-0409-03,<Add> by chester
+printk("chester power off\n");
+MACvRegBitsOn(pDevice->PortOffset, MAC_REG_GPIOCTL0, LED_ACTSET);  //LED issue
+    return bResult;
+}
+
+
+/*
+ * Description: Turn on Radio power
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - The adapter to be turned on
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; otherwise FALSE
+ *
+ */
+BOOL CARDbRadioPowerOn (PVOID pDeviceHandler)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    BOOL        bResult = TRUE;
+printk("chester power on\n");
+    if (pDevice->bRadioControlOff == TRUE){
+if (pDevice->bHWRadioOff == TRUE) printk("chester bHWRadioOff\n");
+if (pDevice->bRadioControlOff == TRUE) printk("chester bRadioControlOff\n");
+        return FALSE;}
+
+    if (pDevice->bRadioOff == FALSE)
+       {
+printk("chester pbRadioOff\n");
+return TRUE;}
+
+    BBvExitDeepSleep(pDevice->PortOffset, pDevice->byLocalID);
+
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_HOSTCR, HOSTCR_RXON);
+
+    switch (pDevice->byRFType) {
+
+        case RF_RFMD2959:
+            MACvWordRegBitsOn(pDevice->PortOffset, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_TXPEINV);
+            MACvWordRegBitsOff(pDevice->PortOffset, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_SWPE1);
+            break;
+
+        case RF_AIROHA:
+        case RF_AL2230S:
+        case RF_AIROHA7230: //RobertYu:20050104
+            MACvWordRegBitsOn(pDevice->PortOffset, MAC_REG_SOFTPWRCTL, (SOFTPWRCTL_SWPE2 |
+                                                                        SOFTPWRCTL_SWPE3));
+            break;
+
+    }
+
+    pDevice->bRadioOff = FALSE;
+//  2007-0409-03,<Add> by chester
+printk("chester power on\n");
+MACvRegBitsOff(pDevice->PortOffset, MAC_REG_GPIOCTL0, LED_ACTSET); //LED issue
+    return bResult;
+}
+
+
+
+BOOL CARDbRemoveKey (PVOID pDeviceHandler, PBYTE pbyBSSID)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+
+    KeybRemoveAllKey(&(pDevice->sKey), pbyBSSID, pDevice->PortOffset);
+    return (TRUE);
+}
+
+
+/*
+ *
+ * Description:
+ *    Add BSSID in PMKID Candidate list.
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *      pbyBSSID - BSSID address for adding
+ *      wRSNCap - BSS's RSN capability
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+BOOL
+CARDbAdd_PMKID_Candidate (
+    IN PVOID            pDeviceHandler,
+    IN PBYTE            pbyBSSID,
+    IN BOOL             bRSNCapExist,
+    IN WORD             wRSNCap
+    )
+{
+    PSDevice            pDevice = (PSDevice) pDeviceHandler;
+    PPMKID_CANDIDATE    pCandidateList;
+    UINT                ii = 0;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"bAdd_PMKID_Candidate START: (%d)\n", (int)pDevice->gsPMKIDCandidate.NumCandidates);
+
+    if (pDevice->gsPMKIDCandidate.NumCandidates >= MAX_PMKIDLIST) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"vFlush_PMKID_Candidate: 3\n");
+        ZERO_MEMORY(&pDevice->gsPMKIDCandidate, sizeof(SPMKIDCandidateEvent));
+    }
+
+    for (ii = 0; ii < 6; ii++) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%02X ", *(pbyBSSID + ii));
+    }
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n");
+
+
+    // Update Old Candidate
+    for (ii = 0; ii < pDevice->gsPMKIDCandidate.NumCandidates; ii++) {
+        pCandidateList = &pDevice->gsPMKIDCandidate.CandidateList[ii];
+        if (MEMEqualMemory(pCandidateList->BSSID, pbyBSSID, U_ETHER_ADDR_LEN)) {
+            if ((bRSNCapExist == TRUE) && (wRSNCap & BIT0)) {
+                pCandidateList->Flags |= NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED;
+            } else {
+                pCandidateList->Flags &= ~(NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED);
+            }
+            return TRUE;
+        }
+    }
+
+    // New Candidate
+    pCandidateList = &pDevice->gsPMKIDCandidate.CandidateList[pDevice->gsPMKIDCandidate.NumCandidates];
+    if ((bRSNCapExist == TRUE) && (wRSNCap & BIT0)) {
+        pCandidateList->Flags |= NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED;
+    } else {
+        pCandidateList->Flags &= ~(NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED);
+    }
+    MEMvCopy(pCandidateList->BSSID, pbyBSSID, U_ETHER_ADDR_LEN);
+    pDevice->gsPMKIDCandidate.NumCandidates++;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"NumCandidates:%d\n", (int)pDevice->gsPMKIDCandidate.NumCandidates);
+    return TRUE;
+}
+
+PVOID
+CARDpGetCurrentAddress (
+    IN PVOID            pDeviceHandler
+    )
+{
+    PSDevice            pDevice = (PSDevice) pDeviceHandler;
+
+    return (pDevice->abyCurrentNetAddr);
+}
+
+
+
+VOID CARDvInitChannelTable (PVOID pDeviceHandler)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    BOOL        bMultiBand = FALSE;
+    UINT        ii;
+
+    for(ii=1;ii<=CARD_MAX_CHANNEL_TBL;ii++) {
+        sChannelTbl[ii].bValid = FALSE;
+    }
+
+    switch (pDevice->byRFType) {
+        case RF_RFMD2959 :
+        case RF_AIROHA :
+        case RF_AL2230S:
+        case RF_UW2451 :
+        case RF_VT3226 :
+	//		printk("chester-false\n");
+            bMultiBand = FALSE;
+            break;
+        case RF_AIROHA7230 :
+        case RF_UW2452 :
+        case RF_NOTHING :
+        default :
+            bMultiBand = TRUE;
+            break;
+    }
+
+    if ((pDevice->dwDiagRefCount != 0) ||
+        (pDevice->b11hEnable == TRUE)) {
+        if (bMultiBand == TRUE) {
+            for(ii=0;ii<CARD_MAX_CHANNEL_TBL;ii++) {
+                sChannelTbl[ii+1].bValid = TRUE;
+                pDevice->abyRegPwr[ii+1] = pDevice->abyOFDMDefaultPwr[ii+1];
+                pDevice->abyLocalPwr[ii+1] = pDevice->abyOFDMDefaultPwr[ii+1];
+            }
+            for(ii=0;ii<CHANNEL_MAX_24G;ii++) {
+                pDevice->abyRegPwr[ii+1] = pDevice->abyCCKDefaultPwr[ii+1];
+                pDevice->abyLocalPwr[ii+1] = pDevice->abyCCKDefaultPwr[ii+1];
+            }
+        } else {
+            for(ii=0;ii<CHANNEL_MAX_24G;ii++) {
+//2008-8-4 <add> by chester
+ if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[ii] != 0) {
+                sChannelTbl[ii+1].bValid = TRUE;
+                pDevice->abyRegPwr[ii+1] = pDevice->abyCCKDefaultPwr[ii+1];
+                pDevice->abyLocalPwr[ii+1] = pDevice->abyCCKDefaultPwr[ii+1];
+ 	}
+            }
+        }
+    } else if (pDevice->byZoneType <= CCODE_MAX) {
+        if (bMultiBand == TRUE) {
+            for(ii=0;ii<CARD_MAX_CHANNEL_TBL;ii++) {
+                if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[ii] != 0) {
+                    sChannelTbl[ii+1].bValid = TRUE;
+                    pDevice->abyRegPwr[ii+1] = ChannelRuleTab[pDevice->byZoneType].byPower[ii];
+                    pDevice->abyLocalPwr[ii+1] = ChannelRuleTab[pDevice->byZoneType].byPower[ii];
+                }
+            }
+        } else {
+            for(ii=0;ii<CHANNEL_MAX_24G;ii++) {
+                if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[ii] != 0) {
+                    sChannelTbl[ii+1].bValid = TRUE;
+                    pDevice->abyRegPwr[ii+1] = ChannelRuleTab[pDevice->byZoneType].byPower[ii];
+                    pDevice->abyLocalPwr[ii+1] = ChannelRuleTab[pDevice->byZoneType].byPower[ii];
+                }
+            }
+        }
+    }
+ DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO"Zone=[%d][%c][%c]!!\n",pDevice->byZoneType,ChannelRuleTab[pDevice->byZoneType].chCountryCode[0],ChannelRuleTab[pDevice->byZoneType].chCountryCode[1]);
+    for(ii=0;ii<CARD_MAX_CHANNEL_TBL;ii++) {
+        if (pDevice->abyRegPwr[ii+1] == 0) {
+            pDevice->abyRegPwr[ii+1] = pDevice->abyOFDMDefaultPwr[ii+1];
+        }
+        if (pDevice->abyLocalPwr[ii+1] == 0) {
+            pDevice->abyLocalPwr[ii+1] = pDevice->abyOFDMDefaultPwr[ii+1];
+        }
+    }
+}
+
+
+
+/*
+ *
+ * Description:
+ *    Start Spectrum Measure defined in 802.11h
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+BOOL
+CARDbStartMeasure (
+    IN PVOID            pDeviceHandler,
+    IN PVOID            pvMeasureEIDs,
+    IN UINT             uNumOfMeasureEIDs
+    )
+{
+    PSDevice                pDevice = (PSDevice) pDeviceHandler;
+    PWLAN_IE_MEASURE_REQ    pEID = (PWLAN_IE_MEASURE_REQ) pvMeasureEIDs;
+    QWORD                   qwCurrTSF;
+    QWORD                   qwStartTSF;
+    BOOL                    bExpired = TRUE;
+    WORD                    wDuration = 0;
+
+    if ((pEID == NULL) ||
+        (uNumOfMeasureEIDs == 0)) {
+        return (TRUE);
+    }
+    CARDbGetCurrentTSF(pDevice->PortOffset, &qwCurrTSF);
+    if (pDevice->bMeasureInProgress == TRUE) {
+        pDevice->bMeasureInProgress = FALSE;
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_RCR, pDevice->byOrgRCR);
+        MACvSelectPage1(pDevice->PortOffset);
+        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR0, pDevice->dwOrgMAR0);
+        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR4, pDevice->dwOrgMAR4);
+        // clear measure control
+        MACvRegBitsOff(pDevice->PortOffset, MAC_REG_MSRCTL, MSRCTL_EN);
+        MACvSelectPage0(pDevice->PortOffset);
+        CARDbSetChannel(pDevice, pDevice->byOrgChannel);
+        MACvSelectPage1(pDevice->PortOffset);
+        MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL+1, MSRCTL1_TXPAUSE);
+        MACvSelectPage0(pDevice->PortOffset);
+    }
+    pDevice->uNumOfMeasureEIDs = uNumOfMeasureEIDs;
+
+    do {
+        pDevice->pCurrMeasureEID = pEID;
+        pEID++;
+        pDevice->uNumOfMeasureEIDs--;
+
+        if (pDevice->byLocalID > REV_ID_VT3253_B1) {
+            HIDWORD(qwStartTSF) = HIDWORD(*((PQWORD) (pDevice->pCurrMeasureEID->sReq.abyStartTime)));
+            LODWORD(qwStartTSF) = LODWORD(*((PQWORD) (pDevice->pCurrMeasureEID->sReq.abyStartTime)));
+            wDuration = *((PWORD) (pDevice->pCurrMeasureEID->sReq.abyDuration));
+            wDuration += 1; // 1 TU for channel switching
+
+            if ((LODWORD(qwStartTSF) == 0) && (HIDWORD(qwStartTSF) == 0)) {
+                // start imediately by setting start TSF == current TSF + 2 TU
+                LODWORD(qwStartTSF) = LODWORD(qwCurrTSF) + 2048;
+                HIDWORD(qwStartTSF) = HIDWORD(qwCurrTSF);
+                if (LODWORD(qwCurrTSF) > LODWORD(qwStartTSF)) {
+                    HIDWORD(qwStartTSF)++;
+                }
+                bExpired = FALSE;
+                break;
+            } else {
+                // start at setting start TSF - 1TU(for channel switching)
+                if (LODWORD(qwStartTSF) < 1024) {
+                    HIDWORD(qwStartTSF)--;
+                }
+                LODWORD(qwStartTSF) -= 1024;
+            }
+
+            if ((HIDWORD(qwCurrTSF) < HIDWORD(qwStartTSF)) ||
+                ((HIDWORD(qwCurrTSF) == HIDWORD(qwStartTSF)) &&
+                (LODWORD(qwCurrTSF) < LODWORD(qwStartTSF)))
+                ) {
+                bExpired = FALSE;
+                break;
+            }
+            VNTWIFIbMeasureReport(  pDevice->pMgmt,
+                                    FALSE,
+                                    pDevice->pCurrMeasureEID,
+                                    MEASURE_MODE_LATE,
+                                    pDevice->byBasicMap,
+                                    pDevice->byCCAFraction,
+                                    pDevice->abyRPIs
+                                    );
+        } else {
+            // hardware do not support measure
+            VNTWIFIbMeasureReport(  pDevice->pMgmt,
+                                    FALSE,
+                                    pDevice->pCurrMeasureEID,
+                                    MEASURE_MODE_INCAPABLE,
+                                    pDevice->byBasicMap,
+                                    pDevice->byCCAFraction,
+                                    pDevice->abyRPIs
+                                    );
+        }
+    } while (pDevice->uNumOfMeasureEIDs != 0);
+
+    if (bExpired == FALSE) {
+        MACvSelectPage1(pDevice->PortOffset);
+        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MSRSTART, LODWORD(qwStartTSF));
+        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MSRSTART + 4, HIDWORD(qwStartTSF));
+        VNSvOutPortW(pDevice->PortOffset + MAC_REG_MSRDURATION, wDuration);
+        MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL, MSRCTL_EN);
+        MACvSelectPage0(pDevice->PortOffset);
+    } else {
+        // all measure start time expired we should complete action
+        VNTWIFIbMeasureReport(  pDevice->pMgmt,
+                                TRUE,
+                                NULL,
+                                0,
+                                pDevice->byBasicMap,
+                                pDevice->byCCAFraction,
+                                pDevice->abyRPIs
+                                );
+    }
+    return (TRUE);
+}
+
+
+/*
+ *
+ * Description:
+ *    Do Channel Switch defined in 802.11h
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+BOOL
+CARDbChannelSwitch (
+    IN PVOID            pDeviceHandler,
+    IN BYTE             byMode,
+    IN BYTE             byNewChannel,
+    IN BYTE             byCount
+    )
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    BOOL        bResult = TRUE;
+
+    if (byCount == 0) {
+        bResult = CARDbSetChannel(pDevice, byNewChannel);
+        VNTWIFIbChannelSwitch(pDevice->pMgmt, byNewChannel);
+        MACvSelectPage1(pDevice->PortOffset);
+        MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL+1, MSRCTL1_TXPAUSE);
+        MACvSelectPage0(pDevice->PortOffset);
+        return(bResult);
+    }
+    pDevice->byChannelSwitchCount = byCount;
+    pDevice->byNewChannel = byNewChannel;
+    pDevice->bChannelSwitch = TRUE;
+    if (byMode == 1) {
+        bResult=CARDbStopTxPacket(pDevice, PKT_TYPE_802_11_ALL);
+    }
+    return (bResult);
+}
+
+
+/*
+ *
+ * Description:
+ *    Handle Quiet EID defined in 802.11h
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+BOOL
+CARDbSetQuiet (
+    IN PVOID            pDeviceHandler,
+    IN BOOL             bResetQuiet,
+    IN BYTE             byQuietCount,
+    IN BYTE             byQuietPeriod,
+    IN WORD             wQuietDuration,
+    IN WORD             wQuietOffset
+    )
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    UINT        ii = 0;
+
+    if (bResetQuiet == TRUE) {
+        MACvRegBitsOff(pDevice->PortOffset, MAC_REG_MSRCTL, (MSRCTL_QUIETTXCHK | MSRCTL_QUIETEN));
+        for(ii=0;ii<MAX_QUIET_COUNT;ii++) {
+            pDevice->sQuiet[ii].bEnable = FALSE;
+        }
+        pDevice->uQuietEnqueue = 0;
+        pDevice->bEnableFirstQuiet = FALSE;
+        pDevice->bQuietEnable = FALSE;
+        pDevice->byQuietStartCount = byQuietCount;
+    }
+    if (pDevice->sQuiet[pDevice->uQuietEnqueue].bEnable == FALSE) {
+        pDevice->sQuiet[pDevice->uQuietEnqueue].bEnable = TRUE;
+        pDevice->sQuiet[pDevice->uQuietEnqueue].byPeriod = byQuietPeriod;
+        pDevice->sQuiet[pDevice->uQuietEnqueue].wDuration = wQuietDuration;
+        pDevice->sQuiet[pDevice->uQuietEnqueue].dwStartTime = (DWORD) byQuietCount;
+        pDevice->sQuiet[pDevice->uQuietEnqueue].dwStartTime *= pDevice->wBeaconInterval;
+        pDevice->sQuiet[pDevice->uQuietEnqueue].dwStartTime += wQuietOffset;
+        pDevice->uQuietEnqueue++;
+        pDevice->uQuietEnqueue %= MAX_QUIET_COUNT;
+        if (pDevice->byQuietStartCount < byQuietCount) {
+            pDevice->byQuietStartCount = byQuietCount;
+        }
+    } else {
+        // we can not handle Quiet EID more
+    }
+    return (TRUE);
+}
+
+
+/*
+ *
+ * Description:
+ *    Do Quiet, It will called by either ISR (after start) or VNTWIFI (before start) so do not need SPINLOCK
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+BOOL
+CARDbStartQuiet (
+    IN PVOID            pDeviceHandler
+    )
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    UINT        ii = 0;
+    DWORD       dwStartTime = 0xFFFFFFFF;
+    UINT        uCurrentQuietIndex = 0;
+    DWORD       dwNextTime = 0;
+    DWORD       dwGap = 0;
+    DWORD       dwDuration = 0;
+
+    for(ii=0;ii<MAX_QUIET_COUNT;ii++) {
+        if ((pDevice->sQuiet[ii].bEnable == TRUE) &&
+            (dwStartTime > pDevice->sQuiet[ii].dwStartTime)) {
+            dwStartTime = pDevice->sQuiet[ii].dwStartTime;
+            uCurrentQuietIndex = ii;
+        }
+    }
+    if (dwStartTime == 0xFFFFFFFF) {
+        // no more quiet
+        pDevice->bQuietEnable = FALSE;
+        MACvRegBitsOff(pDevice->PortOffset, MAC_REG_MSRCTL, (MSRCTL_QUIETTXCHK | MSRCTL_QUIETEN));
+    } else {
+        if (pDevice->bQuietEnable == FALSE) {
+            // first quiet
+            pDevice->byQuietStartCount--;
+            dwNextTime = pDevice->sQuiet[uCurrentQuietIndex].dwStartTime;
+            dwNextTime %= pDevice->wBeaconInterval;
+            MACvSelectPage1(pDevice->PortOffset);
+            VNSvOutPortW(pDevice->PortOffset + MAC_REG_QUIETINIT, (WORD) dwNextTime);
+            VNSvOutPortW(pDevice->PortOffset + MAC_REG_QUIETDUR, (WORD) pDevice->sQuiet[uCurrentQuietIndex].wDuration);
+            if (pDevice->byQuietStartCount == 0) {
+                pDevice->bEnableFirstQuiet = FALSE;
+                MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL, (MSRCTL_QUIETTXCHK | MSRCTL_QUIETEN));
+            } else {
+                pDevice->bEnableFirstQuiet = TRUE;
+            }
+            MACvSelectPage0(pDevice->PortOffset);
+        } else {
+            if (pDevice->dwCurrentQuietEndTime > pDevice->sQuiet[uCurrentQuietIndex].dwStartTime) {
+                // overlap with previous Quiet
+                dwGap =  pDevice->dwCurrentQuietEndTime - pDevice->sQuiet[uCurrentQuietIndex].dwStartTime;
+                if (dwGap >= pDevice->sQuiet[uCurrentQuietIndex].wDuration) {
+                    // return FALSE to indicate next quiet expired, should call this function again
+                    return (FALSE);
+                }
+                dwDuration = pDevice->sQuiet[uCurrentQuietIndex].wDuration - dwGap;
+                dwGap = 0;
+            } else {
+                dwGap = pDevice->sQuiet[uCurrentQuietIndex].dwStartTime - pDevice->dwCurrentQuietEndTime;
+                dwDuration = pDevice->sQuiet[uCurrentQuietIndex].wDuration;
+            }
+            // set GAP and Next duration
+            MACvSelectPage1(pDevice->PortOffset);
+            VNSvOutPortW(pDevice->PortOffset + MAC_REG_QUIETGAP, (WORD) dwGap);
+            VNSvOutPortW(pDevice->PortOffset + MAC_REG_QUIETDUR, (WORD) dwDuration);
+            MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL, MSRCTL_QUIETRPT);
+            MACvSelectPage0(pDevice->PortOffset);
+        }
+        pDevice->bQuietEnable = TRUE;
+        pDevice->dwCurrentQuietEndTime = pDevice->sQuiet[uCurrentQuietIndex].dwStartTime;
+        pDevice->dwCurrentQuietEndTime += pDevice->sQuiet[uCurrentQuietIndex].wDuration;
+        if (pDevice->sQuiet[uCurrentQuietIndex].byPeriod == 0) {
+            // not period disable current quiet element
+            pDevice->sQuiet[uCurrentQuietIndex].bEnable = FALSE;
+        } else {
+            // set next period start time
+            dwNextTime = (DWORD) pDevice->sQuiet[uCurrentQuietIndex].byPeriod;
+            dwNextTime *= pDevice->wBeaconInterval;
+            pDevice->sQuiet[uCurrentQuietIndex].dwStartTime = dwNextTime;
+        }
+        if (pDevice->dwCurrentQuietEndTime > 0x80010000) {
+            // decreament all time to avoid wrap around
+            for(ii=0;ii<MAX_QUIET_COUNT;ii++) {
+                if (pDevice->sQuiet[ii].bEnable == TRUE) {
+                    pDevice->sQuiet[ii].dwStartTime -= 0x80000000;
+                }
+            }
+            pDevice->dwCurrentQuietEndTime -= 0x80000000;
+        }
+    }
+    return (TRUE);
+}
+
+
+/*
+ *
+ * Description:
+ *    Set Channel Info of Country
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+VOID
+CARDvSetCountryInfo (
+    IN PVOID            pDeviceHandler,
+    IN CARD_PHY_TYPE    ePHYType,
+    IN PVOID            pIE
+    )
+{
+    PSDevice            pDevice = (PSDevice) pDeviceHandler;
+    UINT                ii = 0;
+    UINT                uu = 0;
+    UINT                step = 0;
+    UINT                uNumOfCountryInfo = 0;
+    BYTE                byCh = 0;
+    PWLAN_IE_COUNTRY    pIE_Country = (PWLAN_IE_COUNTRY) pIE;
+
+
+    uNumOfCountryInfo = (pIE_Country->len - 3);
+    uNumOfCountryInfo /= 3;
+
+    if (ePHYType == PHY_TYPE_11A) {
+        pDevice->bCountryInfo5G = TRUE;
+        for(ii=CB_MAX_CHANNEL_24G+1;ii<=CARD_MAX_CHANNEL_TBL;ii++) {
+            sChannelTbl[ii].bValid = FALSE;
+        }
+        step = 4;
+    } else {
+        pDevice->bCountryInfo24G = TRUE;
+        for(ii=1;ii<=CB_MAX_CHANNEL_24G;ii++) {
+            sChannelTbl[ii].bValid = FALSE;
+        }
+        step = 1;
+    }
+    pDevice->abyCountryCode[0] = pIE_Country->abyCountryString[0];
+    pDevice->abyCountryCode[1] = pIE_Country->abyCountryString[1];
+    pDevice->abyCountryCode[2] = pIE_Country->abyCountryString[2];
+
+    for(ii=0;ii<uNumOfCountryInfo;ii++) {
+        for(uu=0;uu<pIE_Country->abyCountryInfo[ii*3+1];uu++) {
+            byCh = CARDbyGetChannelMapping(pDevice, (BYTE)(pIE_Country->abyCountryInfo[ii*3]+step*uu), ePHYType);
+            sChannelTbl[byCh].bValid = TRUE;
+            pDevice->abyRegPwr[byCh] = pIE_Country->abyCountryInfo[ii*3+2];
+        }
+    }
+}
+
+/*
+ *
+ * Description:
+ *    Set Local Power Constraint
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+VOID
+CARDvSetPowerConstraint (
+    IN PVOID            pDeviceHandler,
+    IN BYTE             byChannel,
+    IN I8               byPower
+    )
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+
+    if (byChannel > CB_MAX_CHANNEL_24G) {
+        if (pDevice->bCountryInfo5G == TRUE) {
+            pDevice->abyLocalPwr[byChannel] = pDevice->abyRegPwr[byChannel] - byPower;
+        }
+    } else {
+        if (pDevice->bCountryInfo24G == TRUE) {
+            pDevice->abyLocalPwr[byChannel] = pDevice->abyRegPwr[byChannel] - byPower;
+        }
+    }
+}
+
+
+/*
+ *
+ * Description:
+ *    Set Local Power Constraint
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+VOID
+CARDvGetPowerCapability (
+    IN PVOID            pDeviceHandler,
+    OUT PBYTE           pbyMinPower,
+    OUT PBYTE           pbyMaxPower
+    )
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    BYTE        byDec = 0;
+
+    *pbyMaxPower = pDevice->abyOFDMDefaultPwr[pDevice->byCurrentCh];
+    byDec = pDevice->abyOFDMPwrTbl[pDevice->byCurrentCh];
+    if (pDevice->byRFType == RF_UW2452) {
+        byDec *= 3;
+        byDec >>= 1;
+    } else {
+        byDec <<= 1;
+    }
+    *pbyMinPower = pDevice->abyOFDMDefaultPwr[pDevice->byCurrentCh] - byDec;
+}
+
+
+/*
+ *
+ * Description:
+ *    Set Support Channels IE defined in 802.11h
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+BYTE
+CARDbySetSupportChannels (
+    IN PVOID            pDeviceHandler,
+    IN OUT PBYTE        pbyIEs
+    )
+{
+    PSDevice            pDevice = (PSDevice) pDeviceHandler;
+    UINT                ii;
+    BYTE                byCount;
+    PWLAN_IE_SUPP_CH    pIE = (PWLAN_IE_SUPP_CH) pbyIEs;
+    PBYTE               pbyChTupple;
+    BYTE                byLen = 0;
+
+
+    pIE->byElementID = WLAN_EID_SUPP_CH;
+    pIE->len = 0;
+    pbyChTupple = pIE->abyChannelTuple;
+    byLen = 2;
+    // lower band
+    byCount = 0;
+    if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[28] == TRUE) {
+        for (ii=28;ii<36;ii+=2) {
+            if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[ii] == TRUE) {
+                byCount++;
+            }
+        }
+        *pbyChTupple++ = 34;
+        *pbyChTupple++ = byCount;
+        byLen += 2;
+    } else if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[29] == TRUE) {
+        for (ii=29;ii<36;ii+=2) {
+            if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[ii] == TRUE) {
+                byCount++;
+            }
+        }
+        *pbyChTupple++ = 36;
+        *pbyChTupple++ = byCount;
+        byLen += 2;
+    }
+    // middle band
+    byCount = 0;
+    if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[36] == TRUE) {
+        for (ii=36;ii<40;ii++) {
+            if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[ii] == TRUE) {
+                byCount++;
+            }
+        }
+        *pbyChTupple++ = 52;
+        *pbyChTupple++ = byCount;
+        byLen += 2;
+    }
+    // higher band
+    byCount = 0;
+    if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[40] == TRUE) {
+        for (ii=40;ii<51;ii++) {
+            if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[ii] == TRUE) {
+                byCount++;
+            }
+        }
+        *pbyChTupple++ = 100;
+        *pbyChTupple++ = byCount;
+        byLen += 2;
+    } else if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[51] == TRUE) {
+        for (ii=51;ii<56;ii++) {
+            if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[ii] == TRUE) {
+                byCount++;
+            }
+        }
+        *pbyChTupple++ = 149;
+        *pbyChTupple++ = byCount;
+        byLen += 2;
+    }
+    pIE->len += (byLen - 2);
+    return (byLen);
+}
+
+
+/*
+ *
+ * Description:
+ *    Get Current Tx Power
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+I8
+CARDbyGetTransmitPower (
+    IN PVOID            pDeviceHandler
+    )
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+
+    return (pDevice->byCurPwrdBm);
+}
+
+
+BOOL
+CARDbChannelGetList (
+    IN  UINT       uCountryCodeIdx,
+    OUT PBYTE      pbyChannelTable
+    )
+{
+    if (uCountryCodeIdx >= CCODE_MAX) {
+        return (FALSE);
+    }
+    MEMvCopy(pbyChannelTable, ChannelRuleTab[uCountryCodeIdx].bChannelIdxList, CB_MAX_CHANNEL);
+    return (TRUE);
+}
+
+
+VOID
+CARDvSetCountryIE(
+    IN PVOID        pDeviceHandler,
+    IN PVOID        pIE
+    )
+{
+    PSDevice            pDevice = (PSDevice) pDeviceHandler;
+    UINT                ii;
+    PWLAN_IE_COUNTRY    pIECountry = (PWLAN_IE_COUNTRY) pIE;
+
+    pIECountry->byElementID = WLAN_EID_COUNTRY;
+    pIECountry->len = 0;
+    pIECountry->abyCountryString[0] = ChannelRuleTab[pDevice->byZoneType].chCountryCode[0];
+    pIECountry->abyCountryString[1] = ChannelRuleTab[pDevice->byZoneType].chCountryCode[1];
+    pIECountry->abyCountryString[2] = ' ';
+    for (ii = CB_MAX_CHANNEL_24G; ii < CB_MAX_CHANNEL; ii++ ) {
+        if (ChannelRuleTab[pDevice->byZoneType].bChannelIdxList[ii] != 0) {
+            pIECountry->abyCountryInfo[pIECountry->len++] = sChannelTbl[ii+1].byChannelNumber;
+            pIECountry->abyCountryInfo[pIECountry->len++] = 1;
+            pIECountry->abyCountryInfo[pIECountry->len++] = ChannelRuleTab[pDevice->byZoneType].byPower[ii];
+        }
+    }
+    pIECountry->len += 3;
+}
+
+
+BOOL
+CARDbGetChannelMapInfo(
+    IN PVOID        pDeviceHandler,
+    IN UINT         uChannelIndex,
+    OUT PBYTE       pbyChannelNumber,
+    OUT PBYTE       pbyMap
+    )
+{
+//    PSDevice            pDevice = (PSDevice) pDeviceHandler;
+
+    if (uChannelIndex > CB_MAX_CHANNEL) {
+        return FALSE;
+    }
+    *pbyChannelNumber = sChannelTbl[uChannelIndex].byChannelNumber;
+    *pbyMap = sChannelTbl[uChannelIndex].byMAP;
+    return sChannelTbl[uChannelIndex].bValid;
+}
+
+
+VOID
+CARDvSetChannelMapInfo(
+    IN PVOID        pDeviceHandler,
+    IN UINT         uChannelIndex,
+    IN BYTE         byMap
+    )
+{
+//    PSDevice            pDevice = (PSDevice) pDeviceHandler;
+
+    if (uChannelIndex > CB_MAX_CHANNEL) {
+        return;
+    }
+    sChannelTbl[uChannelIndex].byMAP |= byMap;
+}
+
+
+VOID
+CARDvClearChannelMapInfo(
+    IN PVOID        pDeviceHandler
+    )
+{
+//    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    UINT        ii = 0;
+
+    for (ii = 1; ii <=  CB_MAX_CHANNEL; ii++) {
+        sChannelTbl[ii].byMAP = 0;
+    }
+}
+
+
+BYTE
+CARDbyAutoChannelSelect(
+    IN PVOID        pDeviceHandler,
+    CARD_PHY_TYPE   ePHYType
+    )
+{
+//    PSDevice        pDevice = (PSDevice) pDeviceHandler;
+    UINT            ii = 0;
+    BYTE            byOptionChannel = 0;
+    INT             aiWeight[CB_MAX_CHANNEL_24G+1] = {-1000,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
+
+    if (ePHYType == PHY_TYPE_11A) {
+        for(ii=CB_MAX_CHANNEL_24G+1;ii<=CB_MAX_CHANNEL;ii++) {
+            if (sChannelTbl[ii].bValid == TRUE) {
+                if (byOptionChannel == 0) {
+                    byOptionChannel = (BYTE) ii;
+                }
+                if (sChannelTbl[ii].byMAP == 0) {
+                    return ((BYTE) ii);
+                } else if (BITbIsBitOff(sChannelTbl[ii].byMAP, 0x08)) {
+                    byOptionChannel = (BYTE) ii;
+                }
+            }
+        }
+    } else {
+        byOptionChannel = 0;
+        for(ii=1;ii<=CB_MAX_CHANNEL_24G;ii++) {
+            if (sChannelTbl[ii].bValid == TRUE) {
+                if (sChannelTbl[ii].byMAP == 0) {
+                    aiWeight[ii] += 100;
+                } else if (BITbIsBitOn(sChannelTbl[ii].byMAP, 0x01)) {
+                    if (ii > 3) {
+                        aiWeight[ii-3] -= 10;
+                    }
+                    if (ii > 2) {
+                        aiWeight[ii-2] -= 20;
+                    }
+                    if (ii > 1) {
+                        aiWeight[ii-1] -= 40;
+                    }
+                    aiWeight[ii] -= 80;
+                    if (ii < CB_MAX_CHANNEL_24G) {
+                        aiWeight[ii+1] -= 40;
+                    }
+                    if (ii < (CB_MAX_CHANNEL_24G - 1)) {
+                        aiWeight[ii+2] -= 20;
+                    }
+                    if (ii < (CB_MAX_CHANNEL_24G - 2)) {
+                        aiWeight[ii+3] -= 10;
+                    }
+                }
+            }
+        }
+        for(ii=1;ii<=CB_MAX_CHANNEL_24G;ii++) {
+            if ((sChannelTbl[ii].bValid == TRUE) &&
+                (aiWeight[ii] > aiWeight[byOptionChannel])) {
+                byOptionChannel = (BYTE) ii;
+            }
+        }
+    }
+    return (byOptionChannel);
+}
+
+
+
+//xxx
+VOID
+CARDvSafeResetTx (
+    IN PVOID    pDeviceHandler
+    )
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    UINT        uu;
+    PSTxDesc    pCurrTD;
+
+    // initialize TD index
+    pDevice->apTailTD[0] = pDevice->apCurrTD[0] = &(pDevice->apTD0Rings[0]);
+    pDevice->apTailTD[1] = pDevice->apCurrTD[1] = &(pDevice->apTD1Rings[0]);
+
+    for (uu = 0; uu < TYPE_MAXTD; uu ++)
+        pDevice->iTDUsed[uu] = 0;
+
+    for (uu = 0; uu < pDevice->sOpts.nTxDescs[0]; uu++) {
+        pCurrTD = &(pDevice->apTD0Rings[uu]);
+        pCurrTD->m_td0TD0.f1Owner = OWNED_BY_HOST;
+        // init all Tx Packet pointer to NULL
+    }
+    for (uu = 0; uu < pDevice->sOpts.nTxDescs[1]; uu++) {
+        pCurrTD = &(pDevice->apTD1Rings[uu]);
+        pCurrTD->m_td0TD0.f1Owner = OWNED_BY_HOST;
+        // init all Tx Packet pointer to NULL
+    }
+
+    // set MAC TD pointer
+    MACvSetCurrTXDescAddr(TYPE_TXDMA0, pDevice->PortOffset,
+                        (pDevice->td0_pool_dma));
+
+    MACvSetCurrTXDescAddr(TYPE_AC0DMA, pDevice->PortOffset,
+                        (pDevice->td1_pool_dma));
+
+    // set MAC Beacon TX pointer
+    MACvSetCurrBCNTxDescAddr(pDevice->PortOffset,
+                        (pDevice->tx_beacon_dma));
+
+}
+
+
+
+/*+
+ *
+ * Description:
+ *      Reset Rx
+ *
+ * Parameters:
+ *  In:
+ *      pDevice     - Pointer to the adapter
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+-*/
+VOID
+CARDvSafeResetRx (
+    IN PVOID    pDeviceHandler
+    )
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    UINT        uu;
+    PSRxDesc    pDesc;
+
+
+
+    // initialize RD index
+    pDevice->pCurrRD[0]=&(pDevice->aRD0Ring[0]);
+    pDevice->pCurrRD[1]=&(pDevice->aRD1Ring[0]);
+
+    // init state, all RD is chip's
+    for (uu = 0; uu < pDevice->sOpts.nRxDescs0; uu++) {
+        pDesc =&(pDevice->aRD0Ring[uu]);
+        pDesc->m_rd0RD0.wResCount = (WORD)(pDevice->rx_buf_sz);
+        pDesc->m_rd0RD0.f1Owner=OWNED_BY_NIC;
+        pDesc->m_rd1RD1.wReqCount = (WORD)(pDevice->rx_buf_sz);
+    }
+
+    // init state, all RD is chip's
+    for (uu = 0; uu < pDevice->sOpts.nRxDescs1; uu++) {
+        pDesc =&(pDevice->aRD1Ring[uu]);
+        pDesc->m_rd0RD0.wResCount = (WORD)(pDevice->rx_buf_sz);
+        pDesc->m_rd0RD0.f1Owner=OWNED_BY_NIC;
+        pDesc->m_rd1RD1.wReqCount = (WORD)(pDevice->rx_buf_sz);
+    }
+
+    pDevice->cbDFCB = CB_MAX_RX_FRAG;
+    pDevice->cbFreeDFCB = pDevice->cbDFCB;
+
+    // set perPkt mode
+    MACvRx0PerPktMode(pDevice->PortOffset);
+    MACvRx1PerPktMode(pDevice->PortOffset);
+    // set MAC RD pointer
+    MACvSetCurrRx0DescAddr(pDevice->PortOffset,
+                            pDevice->rd0_pool_dma);
+
+    MACvSetCurrRx1DescAddr(pDevice->PortOffset,
+                            pDevice->rd1_pool_dma);
+}
+
+
+
+
+/*
+ * Description: Get response Control frame rate in CCK mode
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             - The adapter to be set
+ *      wRateIdx            - Receiving data rate
+ *  Out:
+ *      none
+ *
+ * Return Value: response Control frame rate
+ *
+ */
+WORD CARDwGetCCKControlRate(PVOID pDeviceHandler, WORD wRateIdx)
+{
+    PSDevice    pDevice = (PSDevice) pDeviceHandler;
+    UINT ui = (UINT)wRateIdx;
+
+    while (ui > RATE_1M) {
+        if (pDevice->wBasicRate & ((WORD)1 << ui)) {
+            return (WORD)ui;
+        }
+        ui --;
+    }
+    return (WORD)RATE_1M;
+}
+
+/*
+ * Description: Get response Control frame rate in OFDM mode
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             - The adapter to be set
+ *      wRateIdx            - Receiving data rate
+ *  Out:
+ *      none
+ *
+ * Return Value: response Control frame rate
+ *
+ */
+WORD CARDwGetOFDMControlRate (PVOID pDeviceHandler, WORD wRateIdx)
+{
+    PSDevice pDevice = (PSDevice) pDeviceHandler;
+    UINT ui = (UINT)wRateIdx;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"BASIC RATE: %X\n", pDevice->wBasicRate);
+
+    if (!CARDbIsOFDMinBasicRate((PVOID)pDevice)) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"CARDwGetOFDMControlRate:(NO OFDM) %d\n", wRateIdx);
+        if (wRateIdx > RATE_24M)
+            wRateIdx = RATE_24M;
+        return wRateIdx;
+    }
+    while (ui > RATE_11M) {
+        if (pDevice->wBasicRate & ((WORD)1 << ui)) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"CARDwGetOFDMControlRate : %d\n", ui);
+            return (WORD)ui;
+        }
+        ui --;
+    }
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"CARDwGetOFDMControlRate: 6M\n");
+    return (WORD)RATE_24M;
+}
+
+
+/*
+ * Description: Set RSPINF
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             - The adapter to be set
+ *  Out:
+ *      none
+ *
+ * Return Value: None.
+ *
+ */
+void CARDvSetRSPINF (PVOID pDeviceHandler, CARD_PHY_TYPE ePHYType)
+{
+    PSDevice pDevice = (PSDevice) pDeviceHandler;
+    BYTE  byServ = 0x00, bySignal = 0x00; //For CCK
+    WORD  wLen = 0x0000;
+    BYTE  byTxRate, byRsvTime;             //For OFDM
+
+    //Set to Page1
+    MACvSelectPage1(pDevice->PortOffset);
+
+    //RSPINF_b_1
+    BBvCaculateParameter(pDevice,
+                         14,
+                         CARDwGetCCKControlRate((PVOID)pDevice, RATE_1M),
+                         PK_TYPE_11B,
+                         &wLen,
+                         &byServ,
+                         &bySignal
+    );
+
+    VNSvOutPortD(pDevice->PortOffset + MAC_REG_RSPINF_B_1, MAKEDWORD(wLen,MAKEWORD(bySignal,byServ)));
+    ///RSPINF_b_2
+    BBvCaculateParameter(pDevice,
+                         14,
+                         CARDwGetCCKControlRate((PVOID)pDevice, RATE_2M),
+                         PK_TYPE_11B,
+                         &wLen,
+                         &byServ,
+                         &bySignal
+    );
+
+    VNSvOutPortD(pDevice->PortOffset + MAC_REG_RSPINF_B_2, MAKEDWORD(wLen,MAKEWORD(bySignal,byServ)));
+    //RSPINF_b_5
+    BBvCaculateParameter(pDevice,
+                         14,
+                         CARDwGetCCKControlRate((PVOID)pDevice, RATE_5M),
+                         PK_TYPE_11B,
+                         &wLen,
+                         &byServ,
+                         &bySignal
+    );
+
+    VNSvOutPortD(pDevice->PortOffset + MAC_REG_RSPINF_B_5, MAKEDWORD(wLen,MAKEWORD(bySignal,byServ)));
+    //RSPINF_b_11
+    BBvCaculateParameter(pDevice,
+                         14,
+                         CARDwGetCCKControlRate((PVOID)pDevice, RATE_11M),
+                         PK_TYPE_11B,
+                         &wLen,
+                         &byServ,
+                         &bySignal
+    );
+
+    VNSvOutPortD(pDevice->PortOffset + MAC_REG_RSPINF_B_11, MAKEDWORD(wLen,MAKEWORD(bySignal,byServ)));
+    //RSPINF_a_6
+    s_vCaculateOFDMRParameter(RATE_6M,
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_6, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_9
+    s_vCaculateOFDMRParameter(RATE_9M,
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_9, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_12
+    s_vCaculateOFDMRParameter(RATE_12M,
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_12, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_18
+    s_vCaculateOFDMRParameter(RATE_18M,
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+   VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_18, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_24
+    s_vCaculateOFDMRParameter(RATE_24M,
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_24, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_36
+    s_vCaculateOFDMRParameter(CARDwGetOFDMControlRate((PVOID)pDevice, RATE_36M),
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_36, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_48
+    s_vCaculateOFDMRParameter(CARDwGetOFDMControlRate((PVOID)pDevice, RATE_48M),
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_48, MAKEWORD(byTxRate,byRsvTime));
+    //RSPINF_a_54
+    s_vCaculateOFDMRParameter(CARDwGetOFDMControlRate((PVOID)pDevice, RATE_54M),
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_54, MAKEWORD(byTxRate,byRsvTime));
+
+    //RSPINF_a_72
+    s_vCaculateOFDMRParameter(CARDwGetOFDMControlRate((PVOID)pDevice, RATE_54M),
+                              ePHYType,
+                              &byTxRate,
+                              &byRsvTime);
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_RSPINF_A_72, MAKEWORD(byTxRate,byRsvTime));
+    //Set to Page0
+    MACvSelectPage0(pDevice->PortOffset);
+}
+
+/*
+ * Description: Update IFS
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             - The adapter to be set
+ *  Out:
+ *      none
+ *
+ * Return Value: None.
+ *
+ */
+void vUpdateIFS (PVOID pDeviceHandler)
+{
+    //Set SIFS, DIFS, EIFS, SlotTime, CwMin
+    PSDevice pDevice = (PSDevice) pDeviceHandler;
+
+    BYTE byMaxMin = 0;
+    if (pDevice->byPacketType==PK_TYPE_11A) {//0000 0000 0000 0000,11a
+        pDevice->uSlot = C_SLOT_SHORT;
+        pDevice->uSIFS = C_SIFS_A;
+        pDevice->uDIFS = C_SIFS_A + 2*C_SLOT_SHORT;
+        pDevice->uCwMin = C_CWMIN_A;
+        byMaxMin = 4;
+    }
+    else if (pDevice->byPacketType==PK_TYPE_11B) {//0000 0001 0000 0000,11b
+        pDevice->uSlot = C_SLOT_LONG;
+        pDevice->uSIFS = C_SIFS_BG;
+        pDevice->uDIFS = C_SIFS_BG + 2*C_SLOT_LONG;
+	    pDevice->uCwMin = C_CWMIN_B;
+        byMaxMin = 5;
+    }
+    else { // PK_TYPE_11GA & PK_TYPE_11GB
+        pDevice->uSIFS = C_SIFS_BG;
+        if (pDevice->bShortSlotTime) {
+            pDevice->uSlot = C_SLOT_SHORT;
+        } else {
+	        pDevice->uSlot = C_SLOT_LONG;
+	    }
+	    pDevice->uDIFS = C_SIFS_BG + 2*pDevice->uSlot;
+        if (pDevice->wBasicRate & 0x0150) { //0000 0001 0101 0000,24M,12M,6M
+            pDevice->uCwMin = C_CWMIN_A;
+            byMaxMin = 4;
+        }
+        else {
+            pDevice->uCwMin = C_CWMIN_B;
+            byMaxMin = 5;
+        }
+    }
+
+    pDevice->uCwMax = C_CWMAX;
+    pDevice->uEIFS = C_EIFS;
+    if (pDevice->byRFType == RF_RFMD2959) {
+        // bcs TX_PE will reserve 3 us
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_SIFS, (BYTE)(pDevice->uSIFS - 3));
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_DIFS, (BYTE)(pDevice->uDIFS - 3));
+    } else {
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_SIFS, (BYTE)pDevice->uSIFS);
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_DIFS, (BYTE)pDevice->uDIFS);
+    }
+    VNSvOutPortB(pDevice->PortOffset + MAC_REG_EIFS, (BYTE)pDevice->uEIFS);
+    VNSvOutPortB(pDevice->PortOffset + MAC_REG_SLOT, (BYTE)pDevice->uSlot);
+    byMaxMin |= 0xA0;//1010 1111,C_CWMAX = 1023
+    VNSvOutPortB(pDevice->PortOffset + MAC_REG_CWMAXMIN0, (BYTE)byMaxMin);
+}
+
+void CARDvUpdateBasicTopRate (PVOID pDeviceHandler)
+{
+    PSDevice pDevice = (PSDevice) pDeviceHandler;
+    BYTE byTopOFDM = RATE_24M, byTopCCK = RATE_1M;
+    BYTE ii;
+
+     //Determines the highest basic rate.
+     for (ii = RATE_54M; ii >= RATE_6M; ii --) {
+         if ( (pDevice->wBasicRate) & ((WORD)(1<<ii)) )
+             byTopOFDM = ii;
+             break;
+     }
+     pDevice->byTopOFDMBasicRate = byTopOFDM;
+
+     for (ii = RATE_11M;; ii --) {
+         if ( (pDevice->wBasicRate) & ((WORD)(1<<ii)) )
+             byTopCCK = ii;
+             break;
+         if (ii == RATE_1M)
+            break;
+     }
+     pDevice->byTopCCKBasicRate = byTopCCK;
+}
+
+
+/*
+ * Description: Set NIC Tx Basic Rate
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - The adapter to be set
+ *      wBasicRate      - Basic Rate to be set
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL CARDbAddBasicRate (PVOID pDeviceHandler, WORD wRateIdx)
+{
+    PSDevice pDevice = (PSDevice) pDeviceHandler;
+    WORD wRate = (WORD)(1<<wRateIdx);
+
+    pDevice->wBasicRate |= wRate;
+
+    //Determines the highest basic rate.
+    CARDvUpdateBasicTopRate((PVOID)pDevice);
+
+    return(TRUE);
+}
+
+BOOL CARDbIsOFDMinBasicRate (PVOID pDeviceHandler)
+{
+    PSDevice pDevice = (PSDevice) pDeviceHandler;
+    int ii;
+
+    for (ii = RATE_54M; ii >= RATE_6M; ii --) {
+        if ((pDevice->wBasicRate) & ((WORD)(1<<ii)))
+            return TRUE;
+    }
+    return FALSE;
+}
+
+BYTE CARDbyGetPktType (PVOID pDeviceHandler)
+{
+    PSDevice pDevice = (PSDevice) pDeviceHandler;
+
+    if (pDevice->byBBType == BB_TYPE_11A || pDevice->byBBType == BB_TYPE_11B) {
+        return (BYTE)pDevice->byBBType;
+    }
+    else if (CARDbIsOFDMinBasicRate((PVOID)pDevice)) {
+        return PK_TYPE_11GA;
+    }
+    else {
+    	return PK_TYPE_11GB;
+    }
+}
+
+/*
+ * Description: Set NIC Loopback mode
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - The adapter to be set
+ *      wLoopbackMode   - Loopback mode to be set
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void CARDvSetLoopbackMode (DWORD_PTR dwIoBase, WORD wLoopbackMode)
+{
+    switch(wLoopbackMode) {
+    case CARD_LB_NONE:
+    case CARD_LB_MAC:
+    case CARD_LB_PHY:
+        break;
+    default:
+        ASSERT(FALSE);
+        break;
+    }
+    // set MAC loopback
+    MACvSetLoopbackMode(dwIoBase, LOBYTE(wLoopbackMode));
+    // set Baseband loopback
+}
+
+
+/*
+ * Description: Software Reset NIC
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - The adapter to be reset
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+BOOL CARDbSoftwareReset (PVOID pDeviceHandler)
+{
+    PSDevice pDevice = (PSDevice) pDeviceHandler;
+
+    // reset MAC
+    if (!MACbSafeSoftwareReset(pDevice->PortOffset))
+        return FALSE;
+
+    return TRUE;
+}
+
+
+/*
+ * Description: Caculate TSF offset of two TSF input
+ *              Get TSF Offset from RxBCN's TSF and local TSF
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - The adapter to be sync.
+ *      qwTSF1          - Rx BCN's TSF
+ *      qwTSF2          - Local TSF
+ *  Out:
+ *      none
+ *
+ * Return Value: TSF Offset value
+ *
+ */
+QWORD CARDqGetTSFOffset (BYTE byRxRate, QWORD qwTSF1, QWORD qwTSF2)
+{
+    QWORD   qwTSFOffset;
+    WORD    wRxBcnTSFOffst= 0;;
+
+    HIDWORD(qwTSFOffset) = 0;
+    LODWORD(qwTSFOffset) = 0;
+    wRxBcnTSFOffst = cwRXBCNTSFOff[byRxRate%MAX_RATE];
+    (qwTSF2).u.dwLowDword += (DWORD)(wRxBcnTSFOffst);
+    if ((qwTSF2).u.dwLowDword < (DWORD)(wRxBcnTSFOffst)) {
+        (qwTSF2).u.dwHighDword++;
+    }
+    LODWORD(qwTSFOffset) = LODWORD(qwTSF1) - LODWORD(qwTSF2);
+    if (LODWORD(qwTSF1) < LODWORD(qwTSF2)) {
+        // if borrow needed
+        HIDWORD(qwTSFOffset) = HIDWORD(qwTSF1) - HIDWORD(qwTSF2) - 1 ;
+    }
+    else {
+        HIDWORD(qwTSFOffset) = HIDWORD(qwTSF1) - HIDWORD(qwTSF2);
+    };
+    return (qwTSFOffset);
+}
+
+
+/*
+ * Description: Read NIC TSF counter
+ *              Get local TSF counter
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - The adapter to be read
+ *  Out:
+ *      qwCurrTSF       - Current TSF counter
+ *
+ * Return Value: TRUE if success; otherwise FALSE
+ *
+ */
+BOOL CARDbGetCurrentTSF (DWORD_PTR dwIoBase, PQWORD pqwCurrTSF)
+{
+    WORD    ww;
+    BYTE    byData;
+
+    MACvRegBitsOn(dwIoBase, MAC_REG_TFTCTL, TFTCTL_TSFCNTRRD);
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_TFTCTL, &byData);
+        if (BITbIsBitOff(byData, TFTCTL_TSFCNTRRD))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT)
+        return(FALSE);
+    VNSvInPortD(dwIoBase + MAC_REG_TSFCNTR, &LODWORD(*pqwCurrTSF));
+    VNSvInPortD(dwIoBase + MAC_REG_TSFCNTR + 4, &HIDWORD(*pqwCurrTSF));
+
+    return(TRUE);
+}
+
+
+/*
+ * Description: Read NIC TSF counter
+ *              Get NEXTTBTT from adjusted TSF and Beacon Interval
+ *
+ * Parameters:
+ *  In:
+ *      qwTSF           - Current TSF counter
+ *      wbeaconInterval - Beacon Interval
+ *  Out:
+ *      qwCurrTSF       - Current TSF counter
+ *
+ * Return Value: TSF value of next Beacon
+ *
+ */
+QWORD CARDqGetNextTBTT (QWORD qwTSF, WORD wBeaconInterval)
+{
+
+    UINT    uLowNextTBTT;
+    UINT    uHighRemain, uLowRemain;
+    UINT    uBeaconInterval;
+
+    uBeaconInterval = wBeaconInterval * 1024;
+    // Next TBTT = ((local_current_TSF / beacon_interval) + 1 ) * beacon_interval
+    uLowNextTBTT = (LODWORD(qwTSF) >> 10) << 10;
+    // low dword (mod) bcn
+    uLowRemain = (uLowNextTBTT) % uBeaconInterval;
+//    uHighRemain = ((0x80000000 % uBeaconInterval)* 2 * HIDWORD(qwTSF))
+//                  % uBeaconInterval;
+    // high dword (mod) bcn
+    uHighRemain = (((0xffffffff % uBeaconInterval) + 1) * HIDWORD(qwTSF))
+                  % uBeaconInterval;
+    uLowRemain = (uHighRemain + uLowRemain) % uBeaconInterval;
+    uLowRemain = uBeaconInterval - uLowRemain;
+
+    // check if carry when add one beacon interval
+    if ((~uLowNextTBTT) < uLowRemain)
+        HIDWORD(qwTSF) ++ ;
+
+    LODWORD(qwTSF) = uLowNextTBTT + uLowRemain;
+
+    return (qwTSF);
+}
+
+
+/*
+ * Description: Set NIC TSF counter for first Beacon time
+ *              Get NEXTTBTT from adjusted TSF and Beacon Interval
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - IO Base
+ *      wBeaconInterval - Beacon Interval
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void CARDvSetFirstNextTBTT (DWORD_PTR dwIoBase, WORD wBeaconInterval)
+{
+
+    QWORD   qwNextTBTT;
+
+    HIDWORD(qwNextTBTT) = 0;
+    LODWORD(qwNextTBTT) = 0;
+    CARDbGetCurrentTSF(dwIoBase, &qwNextTBTT); //Get Local TSF counter
+    qwNextTBTT = CARDqGetNextTBTT(qwNextTBTT, wBeaconInterval);
+    // Set NextTBTT
+    VNSvOutPortD(dwIoBase + MAC_REG_NEXTTBTT, LODWORD(qwNextTBTT));
+    VNSvOutPortD(dwIoBase + MAC_REG_NEXTTBTT + 4, HIDWORD(qwNextTBTT));
+    MACvRegBitsOn(dwIoBase, MAC_REG_TFTCTL, TFTCTL_TBTTSYNCEN);
+    //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Card:First Next TBTT[%8xh:%8xh] \n", HIDWORD(qwNextTBTT), LODWORD(qwNextTBTT));
+    return;
+}
+
+
+/*
+ * Description: Sync NIC TSF counter for Beacon time
+ *              Get NEXTTBTT and write to HW
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - The adapter to be set
+ *      qwTSF           - Current TSF counter
+ *      wBeaconInterval - Beacon Interval
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void CARDvUpdateNextTBTT (DWORD_PTR dwIoBase, QWORD qwTSF, WORD wBeaconInterval)
+{
+
+    qwTSF = CARDqGetNextTBTT(qwTSF, wBeaconInterval);
+    // Set NextTBTT
+    VNSvOutPortD(dwIoBase + MAC_REG_NEXTTBTT, LODWORD(qwTSF));
+    VNSvOutPortD(dwIoBase + MAC_REG_NEXTTBTT + 4, HIDWORD(qwTSF));
+    MACvRegBitsOn(dwIoBase, MAC_REG_TFTCTL, TFTCTL_TBTTSYNCEN);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Card:Update Next TBTT[%8xh:%8xh] \n",(UINT)HIDWORD(qwTSF), (UINT)LODWORD(qwTSF));
+
+    return;
+}
+
+
+
+
+
+
+
diff --git a/drivers/staging/vt6655/card.h b/drivers/staging/vt6655/card.h
new file mode 100644
index 0000000..bb292e1
--- /dev/null
+++ b/drivers/staging/vt6655/card.h
@@ -0,0 +1,273 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: card.h
+ *
+ * Purpose: Provide functions to setup NIC operation mode
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ *
+ */
+
+
+#ifndef __CARD_H__
+#define __CARD_H__
+
+//#if !defined(__DEVICE_H__)
+//#include "device.h"
+//#endif
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+//
+// Loopback mode
+//
+// LOBYTE is MAC LB mode, HIBYTE is MII LB mode
+#define CARD_LB_NONE            MAKEWORD(MAC_LB_NONE, 0)
+#define CARD_LB_MAC             MAKEWORD(MAC_LB_INTERNAL, 0)   // PHY must ISO, avoid MAC loopback packet go out
+#define CARD_LB_PHY             MAKEWORD(MAC_LB_EXT, 0)
+
+
+#define DEFAULT_MSDU_LIFETIME           512  // ms
+#define DEFAULT_MSDU_LIFETIME_RES_64us  8000 // 64us
+
+#define DEFAULT_MGN_LIFETIME            8    // ms
+#define DEFAULT_MGN_LIFETIME_RES_64us   125  // 64us
+
+#define CB_MAX_CHANNEL_24G      14
+#define CB_MAX_CHANNEL_5G       42 //[20050104] add channel9(5045MHz), 41==>42
+#define CB_MAX_CHANNEL          (CB_MAX_CHANNEL_24G+CB_MAX_CHANNEL_5G)
+
+typedef enum _CARD_PHY_TYPE {
+    PHY_TYPE_AUTO,
+    PHY_TYPE_11B,
+    PHY_TYPE_11G,
+    PHY_TYPE_11A
+} CARD_PHY_TYPE, *PCARD_PHY_TYPE;
+
+typedef enum _CARD_PKT_TYPE {
+    PKT_TYPE_802_11_BCN,
+    PKT_TYPE_802_11_MNG,
+    PKT_TYPE_802_11_DATA,
+    PKT_TYPE_802_11_ALL
+} CARD_PKT_TYPE, *PCARD_PKT_TYPE;
+
+typedef enum _CARD_STATUS_TYPE {
+    CARD_STATUS_MEDIA_CONNECT,
+    CARD_STATUS_MEDIA_DISCONNECT,
+    CARD_STATUS_PMKID
+} CARD_STATUS_TYPE, *PCARD_STATUS_TYPE;
+
+typedef enum _CARD_OP_MODE {
+    OP_MODE_INFRASTRUCTURE,
+    OP_MODE_ADHOC,
+    OP_MODE_AP,
+    OP_MODE_UNKNOWN
+} CARD_OP_MODE, *PCARD_OP_MODE;
+
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+BOOL ChannelValid(UINT CountryCode, UINT ChannelIndex);
+void CARDvSetRSPINF(PVOID pDeviceHandler, CARD_PHY_TYPE ePHYType);
+void vUpdateIFS(PVOID pDeviceHandler);
+void CARDvUpdateBasicTopRate(PVOID pDeviceHandler);
+BOOL CARDbAddBasicRate(PVOID pDeviceHandler, WORD wRateIdx);
+BOOL CARDbIsOFDMinBasicRate(PVOID pDeviceHandler);
+void CARDvSetLoopbackMode(DWORD_PTR dwIoBase, WORD wLoopbackMode);
+BOOL CARDbSoftwareReset(PVOID pDeviceHandler);
+void CARDvSetFirstNextTBTT(DWORD_PTR dwIoBase, WORD wBeaconInterval);
+void CARDvUpdateNextTBTT(DWORD_PTR dwIoBase, QWORD qwTSF, WORD wBeaconInterval);
+BOOL CARDbGetCurrentTSF(DWORD_PTR dwIoBase, PQWORD pqwCurrTSF);
+QWORD CARDqGetNextTBTT(QWORD qwTSF, WORD wBeaconInterval);
+QWORD CARDqGetTSFOffset(BYTE byRxRate, QWORD qwTSF1, QWORD qwTSF2);
+BOOL CARDbSetTxPower(PVOID pDeviceHandler, ULONG ulTxPower);
+BYTE CARDbyGetPktType(PVOID pDeviceHandler);
+VOID CARDvSafeResetTx(PVOID pDeviceHandler);
+VOID CARDvSafeResetRx(PVOID pDeviceHandler);
+
+//xxx
+BOOL CARDbRadioPowerOff(PVOID pDeviceHandler);
+BOOL CARDbRadioPowerOn(PVOID pDeviceHandler);
+BOOL CARDbSetChannel(PVOID pDeviceHandler, UINT uConnectionChannel);
+//BOOL CARDbSendPacket(PVOID pDeviceHandler, PVOID pPacket, CARD_PKT_TYPE ePktType, UINT uLength);
+BOOL CARDbIsShortPreamble(PVOID pDeviceHandler);
+BOOL CARDbIsShorSlotTime(PVOID pDeviceHandler);
+BOOL CARDbSetPhyParameter(PVOID pDeviceHandler, CARD_PHY_TYPE ePHYType, WORD wCapInfo, BYTE byERPField, PVOID pvSupportRateIEs, PVOID pvExtSupportRateIEs);
+BOOL CARDbUpdateTSF(PVOID pDeviceHandler, BYTE byRxRate, QWORD qwBSSTimestamp, QWORD qwLocalTSF);
+BOOL CARDbStopTxPacket(PVOID pDeviceHandler, CARD_PKT_TYPE ePktType);
+BOOL CARDbStartTxPacket(PVOID pDeviceHandler, CARD_PKT_TYPE ePktType);
+BOOL CARDbSetBeaconPeriod(PVOID pDeviceHandler, WORD wBeaconInterval);
+BOOL CARDbSetBSSID(PVOID pDeviceHandler, PBYTE pbyBSSID, CARD_OP_MODE eOPMode);
+
+BOOL
+CARDbPowerDown(
+    PVOID   pDeviceHandler
+    );
+
+BOOL CARDbSetTxDataRate(
+    PVOID   pDeviceHandler,
+    WORD    wDataRate
+    );
+
+
+BOOL CARDbRemoveKey (PVOID pDeviceHandler, PBYTE pbyBSSID);
+
+BOOL
+CARDbAdd_PMKID_Candidate (
+    IN PVOID            pDeviceHandler,
+    IN PBYTE            pbyBSSID,
+    IN BOOL             bRSNCapExist,
+    IN WORD             wRSNCap
+    );
+
+PVOID
+CARDpGetCurrentAddress (
+    IN PVOID            pDeviceHandler
+    );
+
+
+VOID CARDvInitChannelTable(PVOID pDeviceHandler);
+BYTE CARDbyGetChannelMapping(PVOID pDeviceHandler, BYTE byChannelNumber, CARD_PHY_TYPE ePhyType);
+
+BOOL
+CARDbStartMeasure (
+    IN PVOID            pDeviceHandler,
+    IN PVOID            pvMeasureEIDs,
+    IN UINT             uNumOfMeasureEIDs
+    );
+
+BOOL
+CARDbChannelSwitch (
+    IN PVOID            pDeviceHandler,
+    IN BYTE             byMode,
+    IN BYTE             byNewChannel,
+    IN BYTE             byCount
+    );
+
+BOOL
+CARDbSetQuiet (
+    IN PVOID            pDeviceHandler,
+    IN BOOL             bResetQuiet,
+    IN BYTE             byQuietCount,
+    IN BYTE             byQuietPeriod,
+    IN WORD             wQuietDuration,
+    IN WORD             wQuietOffset
+    );
+
+BOOL
+CARDbStartQuiet (
+    IN PVOID            pDeviceHandler
+    );
+
+VOID
+CARDvSetCountryInfo (
+    IN PVOID            pDeviceHandler,
+    IN CARD_PHY_TYPE    ePHYType,
+    IN PVOID            pIE
+    );
+
+VOID
+CARDvSetPowerConstraint (
+    IN PVOID            pDeviceHandler,
+    IN BYTE             byChannel,
+    IN I8               byPower
+    );
+
+VOID
+CARDvGetPowerCapability (
+    IN PVOID            pDeviceHandler,
+    OUT PBYTE           pbyMinPower,
+    OUT PBYTE           pbyMaxPower
+    );
+
+BYTE
+CARDbySetSupportChannels (
+    IN PVOID            pDeviceHandler,
+    IN OUT PBYTE        pbyIEs
+    );
+
+I8
+CARDbyGetTransmitPower (
+    IN PVOID            pDeviceHandler
+    );
+
+BOOL
+CARDbChannelGetList (
+    IN  UINT       uCountryCodeIdx,
+    OUT PBYTE      pbyChannelTable
+    );
+
+VOID
+CARDvSetCountryIE(
+    IN PVOID        pDeviceHandler,
+    IN PVOID        pIE
+    );
+
+BOOL
+CARDbGetChannelMapInfo(
+    IN PVOID        pDeviceHandler,
+    IN UINT         uChannelIndex,
+    OUT PBYTE       pbyChannelNumber,
+    OUT PBYTE       pbyMap
+    );
+
+VOID
+CARDvSetChannelMapInfo(
+    IN PVOID        pDeviceHandler,
+    IN UINT         uChannelIndex,
+    IN BYTE         byMap
+    );
+
+VOID
+CARDvClearChannelMapInfo(
+    IN PVOID        pDeviceHandler
+    );
+
+BYTE
+CARDbyAutoChannelSelect(
+    IN PVOID        pDeviceHandler,
+    CARD_PHY_TYPE   ePHYType
+    );
+
+BYTE CARDbyGetChannelNumber(PVOID pDeviceHandler, BYTE byChannelIndex);
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+#endif // __CARD_H__
+
+
+
diff --git a/drivers/staging/vt6655/country.h b/drivers/staging/vt6655/country.h
new file mode 100644
index 0000000..65d1e52
--- /dev/null
+++ b/drivers/staging/vt6655/country.h
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: country.h
+ *
+ * Purpose: Country Code information
+ *
+ * Author: Lucas Lin
+ *
+ * Date: Dec 23, 2004
+ *
+ */
+
+#ifndef __COUNTRY_H__
+#define __COUNTRY_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+/************************************************************************
+ * The definition here should be complied with the INF country order
+ * Please check with VNWL.inf/VNWL64.inf/VNWL*.inf
+ ************************************************************************/
+typedef enum _COUNTRY_CODE {
+    CCODE_FCC = 0,
+    CCODE_TELEC,
+    CCODE_ETSI,
+    CCODE_RESV3,
+    CCODE_RESV4,
+    CCODE_RESV5,
+    CCODE_RESV6,
+    CCODE_RESV7,
+    CCODE_RESV8,
+    CCODE_RESV9,
+    CCODE_RESVa,
+    CCODE_RESVb,
+    CCODE_RESVc,
+    CCODE_RESVd,
+    CCODE_RESVe,
+    CCODE_ALLBAND,
+    CCODE_ALBANIA,
+    CCODE_ALGERIA,
+    CCODE_ARGENTINA,
+    CCODE_ARMENIA,
+    CCODE_AUSTRALIA,
+    CCODE_AUSTRIA,
+    CCODE_AZERBAIJAN,
+    CCODE_BAHRAIN,
+    CCODE_BELARUS,
+    CCODE_BELGIUM,
+    CCODE_BELIZE,
+    CCODE_BOLIVIA,
+    CCODE_BRAZIL,
+    CCODE_BRUNEI_DARUSSALAM,
+    CCODE_BULGARIA,
+    CCODE_CANADA,
+    CCODE_CHILE,
+    CCODE_CHINA,
+    CCODE_COLOMBIA,
+    CCODE_COSTA_RICA,
+    CCODE_CROATIA,
+    CCODE_CYPRUS,
+    CCODE_CZECH,
+    CCODE_DENMARK,
+    CCODE_DOMINICAN_REPUBLIC,
+    CCODE_ECUADOR,
+    CCODE_EGYPT,
+    CCODE_EL_SALVADOR,
+    CCODE_ESTONIA,
+    CCODE_FINLAND,
+    CCODE_FRANCE,
+    CCODE_GERMANY,
+    CCODE_GREECE,
+    CCODE_GEORGIA,
+    CCODE_GUATEMALA,
+    CCODE_HONDURAS,
+    CCODE_HONG_KONG,
+    CCODE_HUNGARY,
+    CCODE_ICELAND,
+    CCODE_INDIA,
+    CCODE_INDONESIA,
+    CCODE_IRAN,
+    CCODE_IRELAND,
+    CCODE_ITALY,
+    CCODE_ISRAEL,
+    CCODE_JAPAN,
+    CCODE_JORDAN,
+    CCODE_KAZAKHSTAN,
+    CCODE_KUWAIT,
+    CCODE_LATVIA,
+    CCODE_LEBANON,
+    CCODE_LEICHTENSTEIN,
+    CCODE_LITHUANIA,
+    CCODE_LUXEMBURG,
+    CCODE_MACAU,
+    CCODE_MACEDONIA,
+    CCODE_MALTA,
+    CCODE_MALAYSIA,
+    CCODE_MEXICO,
+    CCODE_MONACO,
+    CCODE_MOROCCO,
+    CCODE_NETHERLANDS,
+    CCODE_NEW_ZEALAND,
+    CCODE_NORTH_KOREA,
+    CCODE_NORWAY,
+    CCODE_OMAN,
+    CCODE_PAKISTAN,
+    CCODE_PANAMA,
+    CCODE_PERU,
+    CCODE_PHILIPPINES,
+    CCODE_POLAND,
+    CCODE_PORTUGAL,
+    CCODE_PUERTO_RICO,
+    CCODE_QATAR,
+    CCODE_ROMANIA,
+    CCODE_RUSSIA,
+    CCODE_SAUDI_ARABIA,
+    CCODE_SINGAPORE,
+    CCODE_SLOVAKIA,
+    CCODE_SLOVENIA,
+    CCODE_SOUTH_AFRICA,
+    CCODE_SOUTH_KOREA,
+    CCODE_SPAIN,
+    CCODE_SWEDEN,
+    CCODE_SWITZERLAND,
+    CCODE_SYRIA,
+    CCODE_TAIWAN,
+    CCODE_THAILAND,
+    CCODE_TRINIDAD_TOBAGO,
+    CCODE_TUNISIA,
+    CCODE_TURKEY,
+    CCODE_UK,
+    CCODE_UKRAINE,
+    CCODE_UNITED_ARAB_EMIRATES,
+    CCODE_UNITED_STATES,
+    CCODE_URUGUAY,
+    CCODE_UZBEKISTAN,
+    CCODE_VENEZUELA,
+    CCODE_VIETNAM,
+    CCODE_YEMEN,
+    CCODE_ZIMBABWE,
+    CCODE_JAPAN_W52_W53,
+    CCODE_MAX
+} COUNTRY_CODE;
+
+typedef struct tagSCountryTable
+{
+    BYTE    byChannelCountryCode;             /* The country code         */
+    CHAR    chCountryCode[2];
+    BYTE    bChannelIdxList[CB_MAX_CHANNEL];  /* Available channels Index */
+    BYTE    byPower[CB_MAX_CHANNEL];
+}   SCountryTable, DEF* PSCountryTable;
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+extern SCountryTable ChannelRuleTab[CCODE_MAX+1];
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+/************************************************************************
+ * Function prototype
+ ************************************************************************/
+#endif  /* __COUNTRY_H__ */
diff --git a/drivers/staging/vt6655/datarate.c b/drivers/staging/vt6655/datarate.c
new file mode 100644
index 0000000..f58f963
--- /dev/null
+++ b/drivers/staging/vt6655/datarate.c
@@ -0,0 +1,455 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: datarate.c
+ *
+ * Purpose: Handles the auto fallback & data rates functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: July 17, 2002
+ *
+ * Functions:
+ *      RATEvParseMaxRate - Parsing the highest basic & support rate in rate field of frame
+ *      RATEvTxRateFallBack - Rate fallback Algorithm Implementaion
+ *      RATEuSetIE- Set rate IE field.
+ *
+ * Revision History:
+ *
+ */
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__80211MGR_H__)
+#include "80211mgr.h"
+#endif
+#if !defined(__BSSDB_H__)
+#include "bssdb.h"
+#endif
+#if !defined(__DATARATE_H__)
+#include "datarate.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+#if !defined(__SROM_H__)
+#include "srom.h"
+#endif
+
+/*---------------------  Static Definitions -------------------------*/
+
+
+
+
+/*---------------------  Static Classes  ----------------------------*/
+
+
+ extern WORD TxRate_iwconfig; //2008-5-8 <add> by chester
+/*---------------------  Static Variables  --------------------------*/
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+static int          msglevel                =MSG_LEVEL_INFO;
+const BYTE acbyIERate[MAX_RATE] =
+{0x02, 0x04, 0x0B, 0x16, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x48, 0x60, 0x6C};
+
+#define AUTORATE_TXOK_CNT       0x0400
+#define AUTORATE_TXFAIL_CNT     0x0064
+#define AUTORATE_TIMEOUT        10
+
+/*---------------------  Static Functions  --------------------------*/
+
+VOID s_vResetCounter (
+    IN PKnownNodeDB psNodeDBTable
+    );
+
+
+
+VOID
+s_vResetCounter (
+    IN PKnownNodeDB psNodeDBTable
+    )
+{
+    BYTE            ii;
+
+    // clear statistic counter for auto_rate
+    for(ii=0;ii<=MAX_RATE;ii++) {
+        psNodeDBTable->uTxOk[ii] = 0;
+        psNodeDBTable->uTxFail[ii] = 0;
+    }
+}
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+/*+
+ *
+ * Description:
+ *      Get RateIdx from the value in SuppRates IE or ExtSuppRates IE
+ *
+ * Parameters:
+ *  In:
+ *      BYTE    - Rate value in SuppRates IE or ExtSuppRates IE
+ *  Out:
+ *      none
+ *
+ * Return Value: RateIdx
+ *
+-*/
+BYTE
+DATARATEbyGetRateIdx (
+    IN BYTE byRate
+    )
+{
+    BYTE    ii;
+
+    //Erase basicRate flag.
+    byRate = byRate & 0x7F;//0111 1111
+
+    for (ii = 0; ii < MAX_RATE; ii ++) {
+        if (acbyIERate[ii] == byRate)
+            return ii;
+    }
+    return 0;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *      Rate fallback Algorithm Implementaion
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - Pointer to the adapter
+ *      psNodeDBTable   - Pointer to Node Data Base
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+-*/
+#define AUTORATE_TXCNT_THRESHOLD        20
+#define AUTORATE_INC_THRESHOLD          30
+
+
+
+
+/*+
+ *
+ * Description:
+ *      Get RateIdx from the value in SuppRates IE or ExtSuppRates IE
+ *
+ * Parameters:
+ *  In:
+ *      BYTE    - Rate value in SuppRates IE or ExtSuppRates IE
+ *  Out:
+ *      none
+ *
+ * Return Value: RateIdx
+ *
+-*/
+WORD
+wGetRateIdx(
+    IN BYTE byRate
+    )
+{
+    WORD    ii;
+
+    //Erase basicRate flag.
+    byRate = byRate & 0x7F;//0111 1111
+
+    for (ii = 0; ii < MAX_RATE; ii ++) {
+        if (acbyIERate[ii] == byRate)
+            return ii;
+    }
+    return 0;
+}
+
+/*+
+ *
+ * Description:
+ *      Parsing the highest basic & support rate in rate field of frame.
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - Pointer to the adapter
+ *      pItemRates      - Pointer to Rate field defined in 802.11 spec.
+ *      pItemExtRates      - Pointer to Extended Rate field defined in 802.11 spec.
+ *  Out:
+ *      pwMaxBasicRate  - Maximum Basic Rate
+ *      pwMaxSuppRate   - Maximum Supported Rate
+ *      pbyTopCCKRate   - Maximum Basic Rate in CCK mode
+ *      pbyTopOFDMRate  - Maximum Basic Rate in OFDM mode
+ *
+ * Return Value: none
+ *
+-*/
+VOID
+RATEvParseMaxRate (
+    IN PVOID pDeviceHandler,
+    IN PWLAN_IE_SUPP_RATES pItemRates,
+    IN PWLAN_IE_SUPP_RATES pItemExtRates,
+    IN BOOL bUpdateBasicRate,
+    OUT PWORD pwMaxBasicRate,
+    OUT PWORD pwMaxSuppRate,
+    OUT PWORD pwSuppRate,
+    OUT PBYTE pbyTopCCKRate,
+    OUT PBYTE pbyTopOFDMRate
+    )
+{
+PSDevice  pDevice = (PSDevice) pDeviceHandler;
+UINT  ii;
+BYTE  byHighSuppRate = 0;
+BYTE  byRate = 0;
+WORD  wOldBasicRate = pDevice->wBasicRate;
+UINT  uRateLen;
+
+
+    if (pItemRates == NULL)
+        return;
+
+    *pwSuppRate = 0;
+    uRateLen = pItemRates->len;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ParseMaxRate Len: %d\n", uRateLen);
+    if (pDevice->eCurrentPHYType != PHY_TYPE_11B) {
+        if (uRateLen > WLAN_RATES_MAXLEN)
+            uRateLen = WLAN_RATES_MAXLEN;
+    } else {
+        if (uRateLen > WLAN_RATES_MAXLEN_11B)
+            uRateLen = WLAN_RATES_MAXLEN_11B;
+    }
+
+    for (ii = 0; ii < uRateLen; ii++) {
+    	byRate = (BYTE)(pItemRates->abyRates[ii]);
+        if (WLAN_MGMT_IS_BASICRATE(byRate) &&
+            (bUpdateBasicRate == TRUE))  {
+            // Add to basic rate set, update pDevice->byTopCCKBasicRate and pDevice->byTopOFDMBasicRate
+            CARDbAddBasicRate((PVOID)pDevice, wGetRateIdx(byRate));
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ParseMaxRate AddBasicRate: %d\n", wGetRateIdx(byRate));
+        }
+        byRate = (BYTE)(pItemRates->abyRates[ii]&0x7F);
+        if (byHighSuppRate == 0)
+            byHighSuppRate = byRate;
+        if (byRate > byHighSuppRate)
+            byHighSuppRate = byRate;
+        *pwSuppRate |= (1<<wGetRateIdx(byRate));
+    }
+    if ((pItemExtRates != NULL) && (pItemExtRates->byElementID == WLAN_EID_EXTSUPP_RATES) &&
+        (pDevice->eCurrentPHYType != PHY_TYPE_11B)) {
+
+        UINT  uExtRateLen = pItemExtRates->len;
+
+        if (uExtRateLen > WLAN_RATES_MAXLEN)
+            uExtRateLen = WLAN_RATES_MAXLEN;
+
+        for (ii = 0; ii < uExtRateLen ; ii++) {
+            byRate = (BYTE)(pItemExtRates->abyRates[ii]);
+            // select highest basic rate
+            if (WLAN_MGMT_IS_BASICRATE(pItemExtRates->abyRates[ii])) {
+            	// Add to basic rate set, update pDevice->byTopCCKBasicRate and pDevice->byTopOFDMBasicRate
+                CARDbAddBasicRate((PVOID)pDevice, wGetRateIdx(byRate));
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ParseMaxRate AddBasicRate: %d\n", wGetRateIdx(byRate));
+            }
+            byRate = (BYTE)(pItemExtRates->abyRates[ii]&0x7F);
+            if (byHighSuppRate == 0)
+                byHighSuppRate = byRate;
+            if (byRate > byHighSuppRate)
+                byHighSuppRate = byRate;
+            *pwSuppRate |= (1<<wGetRateIdx(byRate));
+            //DBG_PRN_GRP09(("ParseMaxRate : HighSuppRate: %d, %X\n", wGetRateIdx(byRate), byRate));
+        }
+    } //if(pItemExtRates != NULL)
+
+    if ((pDevice->byPacketType == PK_TYPE_11GB) && CARDbIsOFDMinBasicRate((PVOID)pDevice)) {
+        pDevice->byPacketType = PK_TYPE_11GA;
+    }
+
+    *pbyTopCCKRate = pDevice->byTopCCKBasicRate;
+    *pbyTopOFDMRate = pDevice->byTopOFDMBasicRate;
+    *pwMaxSuppRate = wGetRateIdx(byHighSuppRate);
+    if ((pDevice->byPacketType==PK_TYPE_11B) || (pDevice->byPacketType==PK_TYPE_11GB))
+       *pwMaxBasicRate = pDevice->byTopCCKBasicRate;
+    else
+       *pwMaxBasicRate = pDevice->byTopOFDMBasicRate;
+    if (wOldBasicRate != pDevice->wBasicRate)
+        CARDvSetRSPINF((PVOID)pDevice, pDevice->eCurrentPHYType);
+
+     DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Exit ParseMaxRate\n");
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *      Rate fallback Algorithm Implementaion
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - Pointer to the adapter
+ *      psNodeDBTable   - Pointer to Node Data Base
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+-*/
+#define AUTORATE_TXCNT_THRESHOLD        20
+#define AUTORATE_INC_THRESHOLD          30
+
+VOID
+RATEvTxRateFallBack (
+    IN PVOID pDeviceHandler,
+    IN PKnownNodeDB psNodeDBTable
+    )
+{
+PSDevice        pDevice = (PSDevice) pDeviceHandler;
+WORD            wIdxDownRate = 0;
+UINT            ii;
+//DWORD           dwRateTable[MAX_RATE]  = {1,   2,   5,   11,  6,    9,    12,   18,  24,  36,  48,  54};
+BOOL            bAutoRate[MAX_RATE]    = {TRUE,TRUE,TRUE,TRUE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE};
+DWORD           dwThroughputTbl[MAX_RATE] = {10, 20, 55, 110, 60, 90, 120, 180, 240, 360, 480, 540};
+DWORD           dwThroughput = 0;
+WORD            wIdxUpRate = 0;
+DWORD           dwTxDiff = 0;
+
+    if (pDevice->pMgmt->eScanState != WMAC_NO_SCANNING) {
+        // Don't do Fallback when scanning Channel
+        return;
+    }
+
+    psNodeDBTable->uTimeCount ++;
+
+    if (psNodeDBTable->uTxFail[MAX_RATE] > psNodeDBTable->uTxOk[MAX_RATE])
+        dwTxDiff = psNodeDBTable->uTxFail[MAX_RATE] - psNodeDBTable->uTxOk[MAX_RATE];
+
+    if ((psNodeDBTable->uTxOk[MAX_RATE] < AUTORATE_TXOK_CNT) &&
+        (dwTxDiff < AUTORATE_TXFAIL_CNT) &&
+        (psNodeDBTable->uTimeCount < AUTORATE_TIMEOUT)) {
+        return;
+    }
+
+    if (psNodeDBTable->uTimeCount >= AUTORATE_TIMEOUT) {
+        psNodeDBTable->uTimeCount = 0;
+    }
+
+
+    for(ii=0;ii<MAX_RATE;ii++) {
+        if (psNodeDBTable->wSuppRate & (0x0001<<ii)) {
+            if (bAutoRate[ii] == TRUE) {
+                wIdxUpRate = (WORD) ii;
+            }
+        } else {
+            bAutoRate[ii] = FALSE;
+        }
+    }
+
+    for(ii=0;ii<=psNodeDBTable->wTxDataRate;ii++) {
+        if ( (psNodeDBTable->uTxOk[ii] != 0) ||
+             (psNodeDBTable->uTxFail[ii] != 0) ) {
+            dwThroughputTbl[ii] *= psNodeDBTable->uTxOk[ii];
+            if (ii < RATE_11M) {
+                psNodeDBTable->uTxFail[ii] *= 4;
+            }
+            dwThroughputTbl[ii] /= (psNodeDBTable->uTxOk[ii] + psNodeDBTable->uTxFail[ii]);
+        }
+//        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Rate %d,Ok: %d, Fail:%d, Throughput:%d\n",
+//                       ii, psNodeDBTable->uTxOk[ii], psNodeDBTable->uTxFail[ii], dwThroughputTbl[ii]);
+    }
+    dwThroughput = dwThroughputTbl[psNodeDBTable->wTxDataRate];
+
+    wIdxDownRate = psNodeDBTable->wTxDataRate;
+    for(ii = psNodeDBTable->wTxDataRate; ii > 0;) {
+        ii--;
+        if ( (dwThroughputTbl[ii] > dwThroughput) &&
+             (bAutoRate[ii]==TRUE) ) {
+            dwThroughput = dwThroughputTbl[ii];
+            wIdxDownRate = (WORD) ii;
+        }
+    }
+    psNodeDBTable->wTxDataRate = wIdxDownRate;
+    if (psNodeDBTable->uTxOk[MAX_RATE]) {
+        if (psNodeDBTable->uTxOk[MAX_RATE] >
+           (psNodeDBTable->uTxFail[MAX_RATE] * 4) ) {
+            psNodeDBTable->wTxDataRate = wIdxUpRate;
+        }
+    }else { // adhoc, if uTxOk =0 & uTxFail = 0
+        if (psNodeDBTable->uTxFail[MAX_RATE] == 0)
+            psNodeDBTable->wTxDataRate = wIdxUpRate;
+    }
+//2008-5-8 <add> by chester
+TxRate_iwconfig=psNodeDBTable->wTxDataRate;
+    s_vResetCounter(psNodeDBTable);
+//    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Rate: %d, U:%d, D:%d\n", psNodeDBTable->wTxDataRate, wIdxUpRate, wIdxDownRate);
+
+    return;
+
+}
+
+/*+
+ *
+ * Description:
+ *    This routine is used to assemble available Rate IE.
+ *
+ * Parameters:
+ *  In:
+ *    pDevice
+ *  Out:
+ *
+ * Return Value: None
+ *
+-*/
+BYTE
+RATEuSetIE (
+    IN PWLAN_IE_SUPP_RATES pSrcRates,
+    IN PWLAN_IE_SUPP_RATES pDstRates,
+    IN UINT                uRateLen
+    )
+{
+    UINT ii, uu, uRateCnt = 0;
+
+    if ((pSrcRates == NULL) || (pDstRates == NULL))
+        return 0;
+
+    if (pSrcRates->len == 0)
+        return 0;
+
+    for (ii = 0; ii < uRateLen; ii++) {
+        for (uu = 0; uu < pSrcRates->len; uu++) {
+            if ((pSrcRates->abyRates[uu] & 0x7F) == acbyIERate[ii]) {
+                pDstRates->abyRates[uRateCnt ++] = pSrcRates->abyRates[uu];
+                break;
+            }
+        }
+    }
+    return (BYTE)uRateCnt;
+}
+
diff --git a/drivers/staging/vt6655/datarate.h b/drivers/staging/vt6655/datarate.h
new file mode 100644
index 0000000..5096f3d
--- /dev/null
+++ b/drivers/staging/vt6655/datarate.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: datarate.h
+ *
+ * Purpose: Handles the auto fallback & data rates functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: July 16, 2002
+ *
+ */
+#ifndef __DATARATE_H__
+#define __DATARATE_H__
+
+/*---------------------  Export Definitions -------------------------*/
+
+#define FALLBACK_PKT_COLLECT_TR_H  50   // pkts
+#define FALLBACK_PKT_COLLECT_TR_L  10   // pkts
+#define FALLBACK_POLL_SECOND       5    // 5 sec
+#define FALLBACK_RECOVER_SECOND    30   // 30 sec
+#define FALLBACK_THRESHOLD         15   // percent
+#define UPGRADE_THRESHOLD          5    // percent
+#define UPGRADE_CNT_THRD           3    // times
+#define RETRY_TIMES_THRD_H         2    // times
+#define RETRY_TIMES_THRD_L         1    // times
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Types  ------------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+VOID
+RATEvParseMaxRate(
+    IN PVOID pDeviceHandler,
+    IN PWLAN_IE_SUPP_RATES pItemRates,
+    IN PWLAN_IE_SUPP_RATES pItemExtRates,
+    IN BOOL bUpdateBasicRate,
+    OUT PWORD pwMaxBasicRate,
+    OUT PWORD pwMaxSuppRate,
+    OUT PWORD pwSuppRate,
+    OUT PBYTE pbyTopCCKRate,
+    OUT PBYTE pbyTopOFDMRate
+    );
+
+VOID
+RATEvTxRateFallBack(
+    IN PVOID pDeviceHandler,
+    IN PKnownNodeDB psNodeDBTable
+    );
+
+BYTE
+RATEuSetIE(
+    IN PWLAN_IE_SUPP_RATES pSrcRates,
+    IN PWLAN_IE_SUPP_RATES pDstRates,
+    IN UINT                uRateLen
+    );
+
+WORD
+wGetRateIdx(
+    IN BYTE byRate
+    );
+
+
+BYTE
+DATARATEbyGetRateIdx(
+    IN BYTE byRate
+    );
+
+
+#endif //__DATARATE_H__
diff --git a/drivers/staging/vt6655/desc.h b/drivers/staging/vt6655/desc.h
new file mode 100644
index 0000000..c0fc1d3
--- /dev/null
+++ b/drivers/staging/vt6655/desc.h
@@ -0,0 +1,697 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: desc.h
+ *
+ * Purpose:The header file of descriptor
+ *
+ * Revision History:
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ *
+ */
+
+
+#ifndef __DESC_H__
+#define __DESC_H__
+
+#include <linux/types.h>
+#include <linux/mm.h>
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+// #ifdef PRIVATE_OBJ
+//#if !defined(__DEVICE_MODULE_H)
+//#include "device_module.h"
+//#endif
+
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+#define B_OWNED_BY_CHIP     1           //
+#define B_OWNED_BY_HOST     0           //
+
+//
+// Bits in the RSR register
+//
+#define RSR_ADDRBROAD       0x80        // 1000 0000
+#define RSR_ADDRMULTI       0x40        // 0100 0000
+#define RSR_ADDRUNI         0x00        // 0000 0000
+#define RSR_IVLDTYP         0x20        // 0010 0000 , invalid packet type
+#define RSR_IVLDLEN         0x10        // 0001 0000 , invalid len (> 2312 byte)
+#define RSR_BSSIDOK         0x08        // 0000 1000
+#define RSR_CRCOK           0x04        // 0000 0100
+#define RSR_BCNSSIDOK       0x02        // 0000 0010
+#define RSR_ADDROK          0x01        // 0000 0001
+
+//
+// Bits in the new RSR register
+//
+#define NEWRSR_DECRYPTOK    0x10        // 0001 0000
+#define NEWRSR_CFPIND       0x08        // 0000 1000
+#define NEWRSR_HWUTSF       0x04        // 0000 0100
+#define NEWRSR_BCNHITAID    0x02        // 0000 0010
+#define NEWRSR_BCNHITAID0   0x01        // 0000 0001
+
+//
+// Bits in the TSR0 register
+//
+#define TSR0_PWRSTS1_2      0xC0        // 1100 0000
+#define TSR0_PWRSTS7        0x20        // 0010 0000
+#define TSR0_NCR            0x1F        // 0001 1111
+
+//
+// Bits in the TSR1 register
+//
+#define TSR1_TERR           0x80        // 1000 0000
+#define TSR1_PWRSTS4_6      0x70        // 0111 0000
+#define TSR1_RETRYTMO       0x08        // 0000 1000
+#define TSR1_TMO            0x04        // 0000 0100
+#define TSR1_PWRSTS3        0x02        // 0000 0010
+#define ACK_DATA            0x01        // 0000 0000
+
+//
+// Bits in the TCR register
+//
+#define EDMSDU              0x04        // 0000 0100 end of sdu
+#define TCR_EDP             0x02        // 0000 0010 end of packet
+#define TCR_STP             0x01        // 0000 0001 start of packet
+
+// max transmit or receive buffer size
+#define CB_MAX_BUF_SIZE     2900U       // max buffer size
+                                        // NOTE: must be multiple of 4
+#define CB_MAX_TX_BUF_SIZE          CB_MAX_BUF_SIZE // max Tx buffer size
+#define CB_MAX_RX_BUF_SIZE_NORMAL   CB_MAX_BUF_SIZE // max Rx buffer size when not use Multi-RD
+
+#define CB_BEACON_BUF_SIZE  512U        // default beacon buffer size
+
+#define CB_MAX_RX_DESC      128         // max # of descriptor
+#define CB_MIN_RX_DESC      16          // min # of rx descriptor
+#define CB_MAX_TX_DESC      64          // max # of descriptor
+#define CB_MIN_TX_DESC      16          // min # of tx descriptor
+
+#define CB_MAX_RECEIVED_PACKETS     16  // max # of received packets at one time
+                                        // limit our receive routine to indicating
+                                        // this many at a time for 2 reasons:
+                                        // 1. driver flow control to protocol layer
+                                        // 2. limit the time used in ISR routine
+
+#define CB_EXTRA_RD_NUM     32          // default # of Extra RD
+#define CB_RD_NUM           32          // default # of RD
+#define CB_TD_NUM           32          // default # of TD
+
+
+// max number of physical segments
+// in a single NDIS packet. Above this threshold, the packet
+// is copied into a single physically contiguous buffer
+#define CB_MAX_SEGMENT      4
+
+#define CB_MIN_MAP_REG_NUM  4
+#define CB_MAX_MAP_REG_NUM  CB_MAX_TX_DESC
+
+#define CB_PROTOCOL_RESERVED_SECTION    16
+
+
+// if retrys excess 15 times , tx will abort, and
+// if tx fifo underflow, tx will fail
+// we should try to resend it
+#define CB_MAX_TX_ABORT_RETRY   3
+
+#ifdef __BIG_ENDIAN
+
+// WMAC definition FIFO Control
+#define FIFOCTL_AUTO_FB_1   0x0010 // 0001 0000 0000 0000
+#define FIFOCTL_AUTO_FB_0   0x0008 // 0000 1000 0000 0000
+#define FIFOCTL_GRPACK      0x0004 // 0000 0100 0000 0000
+#define FIFOCTL_11GA        0x0003 // 0000 0011 0000 0000
+#define FIFOCTL_11GB        0x0002 // 0000 0010 0000 0000
+#define FIFOCTL_11B         0x0001 // 0000 0001 0000 0000
+#define FIFOCTL_11A         0x0000 // 0000 0000 0000 0000
+#define FIFOCTL_RTS         0x8000 // 0000 0000 1000 0000
+#define FIFOCTL_ISDMA0      0x4000 // 0000 0000 0100 0000
+#define FIFOCTL_GENINT      0x2000 // 0000 0000 0010 0000
+#define FIFOCTL_TMOEN       0x1000 // 0000 0000 0001 0000
+#define FIFOCTL_LRETRY      0x0800 // 0000 0000 0000 1000
+#define FIFOCTL_CRCDIS      0x0400 // 0000 0000 0000 0100
+#define FIFOCTL_NEEDACK     0x0200 // 0000 0000 0000 0010
+#define FIFOCTL_LHEAD       0x0100 // 0000 0000 0000 0001
+
+//WMAC definition Frag Control
+#define FRAGCTL_AES         0x0003 // 0000 0011 0000 0000
+#define FRAGCTL_TKIP        0x0002 // 0000 0010 0000 0000
+#define FRAGCTL_LEGACY      0x0001 // 0000 0001 0000 0000
+#define FRAGCTL_NONENCRYPT  0x0000 // 0000 0000 0000 0000
+//#define FRAGCTL_AC3         0x0C00 // 0000 0000 0000 1100
+//#define FRAGCTL_AC2         0x0800 // 0000 0000 0000 1000
+//#define FRAGCTL_AC1         0x0400 // 0000 0000 0000 0100
+//#define FRAGCTL_AC0         0x0000 // 0000 0000 0000 0000
+#define FRAGCTL_ENDFRAG     0x0300 // 0000 0000 0000 0011
+#define FRAGCTL_MIDFRAG     0x0200 // 0000 0000 0000 0010
+#define FRAGCTL_STAFRAG     0x0100 // 0000 0000 0000 0001
+#define FRAGCTL_NONFRAG     0x0000 // 0000 0000 0000 0000
+
+#else
+
+#define FIFOCTL_AUTO_FB_1   0x1000 // 0001 0000 0000 0000
+#define FIFOCTL_AUTO_FB_0   0x0800 // 0000 1000 0000 0000
+#define FIFOCTL_GRPACK      0x0400 // 0000 0100 0000 0000
+#define FIFOCTL_11GA        0x0300 // 0000 0011 0000 0000
+#define FIFOCTL_11GB        0x0200 // 0000 0010 0000 0000
+#define FIFOCTL_11B         0x0100 // 0000 0001 0000 0000
+#define FIFOCTL_11A         0x0000 // 0000 0000 0000 0000
+#define FIFOCTL_RTS         0x0080 // 0000 0000 1000 0000
+#define FIFOCTL_ISDMA0      0x0040 // 0000 0000 0100 0000
+#define FIFOCTL_GENINT      0x0020 // 0000 0000 0010 0000
+#define FIFOCTL_TMOEN       0x0010 // 0000 0000 0001 0000
+#define FIFOCTL_LRETRY      0x0008 // 0000 0000 0000 1000
+#define FIFOCTL_CRCDIS      0x0004 // 0000 0000 0000 0100
+#define FIFOCTL_NEEDACK     0x0002 // 0000 0000 0000 0010
+#define FIFOCTL_LHEAD       0x0001 // 0000 0000 0000 0001
+
+//WMAC definition Frag Control
+#define FRAGCTL_AES         0x0300 // 0000 0011 0000 0000
+#define FRAGCTL_TKIP        0x0200 // 0000 0010 0000 0000
+#define FRAGCTL_LEGACY      0x0100 // 0000 0001 0000 0000
+#define FRAGCTL_NONENCRYPT  0x0000 // 0000 0000 0000 0000
+//#define FRAGCTL_AC3         0x000C // 0000 0000 0000 1100
+//#define FRAGCTL_AC2         0x0008 // 0000 0000 0000 1000
+//#define FRAGCTL_AC1         0x0004 // 0000 0000 0000 0100
+//#define FRAGCTL_AC0         0x0000 // 0000 0000 0000 0000
+#define FRAGCTL_ENDFRAG     0x0003 // 0000 0000 0000 0011
+#define FRAGCTL_MIDFRAG     0x0002 // 0000 0000 0000 0010
+#define FRAGCTL_STAFRAG     0x0001 // 0000 0000 0000 0001
+#define FRAGCTL_NONFRAG     0x0000 // 0000 0000 0000 0000
+
+#endif // #ifdef __BIG_ENDIAN
+
+//#define TYPE_AC0DMA     0
+//#define TYPE_TXDMA0     1
+#define TYPE_TXDMA0     0
+#define TYPE_AC0DMA     1
+#define TYPE_ATIMDMA    2
+#define TYPE_SYNCDMA    3
+#define TYPE_MAXTD      2
+
+#define TYPE_BEACONDMA  4
+
+#define TYPE_RXDMA0     0
+#define TYPE_RXDMA1     1
+#define TYPE_MAXRD      2
+
+
+
+// TD_INFO flags control bit
+#define TD_FLAGS_NETIF_SKB               0x01       // check if need release skb
+#define TD_FLAGS_PRIV_SKB                0x02       // check if called from private skb(hostap)
+#define TD_FLAGS_PS_RETRY                0x04       // check if PS STA frame re-transmit
+//#define TD_FLAGS_NETIF_SKB                0x04
+
+/*---------------------  Export Types  ------------------------------*/
+
+// ref_sk_buff is used for mapping the skb structure between pre-built driver-obj & running kernel.
+// Since different kernel version (2.4x) may change skb structure, i.e. pre-built driver-obj
+// may link to older skb that leads error.
+
+typedef struct tagDEVICE_RD_INFO {
+    struct sk_buff* skb;
+#ifdef PRIVATE_OBJ
+    ref_sk_buff ref_skb;
+#endif
+    dma_addr_t  skb_dma;
+    dma_addr_t  curr_desc;
+} DEVICE_RD_INFO,   *PDEVICE_RD_INFO;
+
+/*
+static inline PDEVICE_RD_INFO alloc_rd_info(void) {
+    PDEVICE_RD_INFO  ptr;
+    if ((ptr = kmalloc(sizeof(DEVICE_RD_INFO), GFP_ATOMIC)) == NULL)
+        return NULL;
+    else {
+        memset(ptr,0,sizeof(DEVICE_RD_INFO));
+        return ptr;
+    }
+}
+*/
+
+/*
+typedef struct tagRDES0 {
+    WORD    wResCount;
+    WORD    wf1Owner ;
+//    WORD    f15Reserved : 15;
+//    WORD    f1Owner : 1;
+} __attribute__ ((__packed__))
+SRDES0;
+*/
+
+#ifdef __BIG_ENDIAN
+
+typedef struct tagRDES0 {
+   volatile WORD    wResCount;
+	union {
+		volatile U16    f15Reserved;
+		struct {
+            volatile U8 f8Reserved1;
+			volatile U8 f1Owner:1;
+			volatile U8 f7Reserved:7;
+		} __attribute__ ((__packed__));
+	} __attribute__ ((__packed__));
+} __attribute__ ((__packed__))
+SRDES0, *PSRDES0;
+
+#else
+
+typedef struct tagRDES0 {
+    WORD    wResCount;
+    WORD    f15Reserved : 15;
+    WORD    f1Owner : 1;
+} __attribute__ ((__packed__))
+SRDES0;
+
+
+#endif
+
+typedef struct tagRDES1 {
+    WORD   wReqCount;
+    WORD   wReserved;
+} __attribute__ ((__packed__))
+SRDES1;
+
+//
+// Rx descriptor
+//
+typedef struct tagSRxDesc {
+    volatile SRDES0 m_rd0RD0;
+    volatile SRDES1 m_rd1RD1;
+    volatile U32    buff_addr;
+    volatile U32    next_desc;
+    struct tagSRxDesc   *next;//4 bytes
+    volatile PDEVICE_RD_INFO    pRDInfo;//4 bytes
+    volatile U32    Reserved[2];//8 bytes
+} __attribute__ ((__packed__))
+SRxDesc, DEF* PSRxDesc;
+typedef const SRxDesc DEF*      PCSRxDesc;
+
+#ifdef __BIG_ENDIAN
+
+/*
+typedef struct tagTDES0 {
+    volatile    BYTE    byTSR0;
+    volatile    BYTE    byTSR1;
+    volatile    WORD    wOwner_Txtime;
+//    volatile    WORD    f15Txtime : 15;
+//    volatile    WORD    f1Owner:1;
+} __attribute__ ((__packed__))
+STDES0;
+*/
+
+typedef struct tagTDES0 {
+    volatile    BYTE    byTSR0;
+    volatile    BYTE    byTSR1;
+	union {
+		volatile U16    f15Txtime;
+		struct {
+            volatile U8 f8Reserved1;
+			volatile U8 f1Owner:1;
+			volatile U8 f7Reserved:7;
+		} __attribute__ ((__packed__));
+	} __attribute__ ((__packed__));
+} __attribute__ ((__packed__))
+STDES0, PSTDES0;
+
+#else
+
+typedef struct tagTDES0 {
+    volatile    BYTE    byTSR0;
+    volatile    BYTE    byTSR1;
+    volatile    WORD    f15Txtime : 15;
+    volatile    WORD    f1Owner:1;
+} __attribute__ ((__packed__))
+STDES0;
+
+#endif
+
+
+typedef struct tagTDES1 {
+    volatile    WORD    wReqCount;
+    volatile    BYTE    byTCR;
+    volatile    BYTE    byReserved;
+} __attribute__ ((__packed__))
+STDES1;
+
+
+typedef struct tagDEVICE_TD_INFO{
+    struct sk_buff*     skb;
+    PBYTE               buf;
+    dma_addr_t          skb_dma;
+    dma_addr_t          buf_dma;
+    dma_addr_t          curr_desc;
+    DWORD               dwReqCount;
+    DWORD               dwHeaderLength;
+    BYTE                byFlags;
+} DEVICE_TD_INFO,    *PDEVICE_TD_INFO;
+
+/*
+static inline PDEVICE_TD_INFO alloc_td_info(void) {
+    PDEVICE_TD_INFO  ptr;
+    if ((ptr = kmalloc(sizeof(DEVICE_TD_INFO),GFP_ATOMIC))==NULL)
+        return NULL;
+    else {
+        memset(ptr,0,sizeof(DEVICE_TD_INFO));
+        return ptr;
+    }
+}
+*/
+
+//
+// transmit descriptor
+//
+typedef struct tagSTxDesc {
+    volatile    STDES0  m_td0TD0;
+    volatile    STDES1  m_td1TD1;
+    volatile    U32    buff_addr;
+    volatile    U32    next_desc;
+    struct tagSTxDesc*  next; //4 bytes
+    volatile    PDEVICE_TD_INFO pTDInfo;//4 bytes
+    volatile    U32    Reserved[2];//8 bytes
+} __attribute__ ((__packed__))
+STxDesc, DEF* PSTxDesc;
+typedef const STxDesc DEF*      PCSTxDesc;
+
+
+typedef struct tagSTxSyncDesc {
+    volatile    STDES0  m_td0TD0;
+    volatile    STDES1  m_td1TD1;
+    volatile    DWORD   buff_addr; // pointer to logical buffer
+    volatile    DWORD   next_desc; // pointer to next logical descriptor
+    volatile    WORD    m_wFIFOCtl;
+    volatile    WORD    m_wTimeStamp;
+    struct tagSTxSyncDesc*  next; //4 bytes
+    volatile    PDEVICE_TD_INFO pTDInfo;//4 bytes
+    volatile    DWORD   m_dwReserved2;
+} __attribute__ ((__packed__))
+STxSyncDesc, DEF* PSTxSyncDesc;
+typedef const STxSyncDesc DEF*      PCSTxSyncDesc;
+
+
+//
+// RsvTime buffer header
+//
+typedef struct tagSRrvTime_gRTS {
+    WORD        wRTSTxRrvTime_ba;
+    WORD        wRTSTxRrvTime_aa;
+    WORD        wRTSTxRrvTime_bb;
+    WORD        wReserved;
+    WORD        wTxRrvTime_b;
+    WORD        wTxRrvTime_a;
+}__attribute__ ((__packed__))
+SRrvTime_gRTS, DEF* PSRrvTime_gRTS;
+typedef const SRrvTime_gRTS DEF*     PCSRrvTime_gRTS;
+
+typedef struct tagSRrvTime_gCTS {
+    WORD        wCTSTxRrvTime_ba;
+    WORD        wReserved;
+    WORD        wTxRrvTime_b;
+    WORD        wTxRrvTime_a;
+}__attribute__ ((__packed__))
+SRrvTime_gCTS, DEF* PSRrvTime_gCTS;
+typedef const SRrvTime_gCTS DEF*     PCSRrvTime_gCTS;
+
+typedef struct tagSRrvTime_ab {
+    WORD        wRTSTxRrvTime;
+    WORD        wTxRrvTime;
+}__attribute__ ((__packed__))
+SRrvTime_ab, DEF* PSRrvTime_ab;
+typedef const SRrvTime_ab DEF*     PCSRrvTime_ab;
+
+typedef struct tagSRrvTime_atim {
+    WORD        wCTSTxRrvTime_ba;
+    WORD        wTxRrvTime_a;
+}__attribute__ ((__packed__))
+SRrvTime_atim, DEF* PSRrvTime_atim;
+typedef const SRrvTime_atim DEF*     PCSRrvTime_atim;
+
+//
+// RTS buffer header
+//
+typedef struct tagSRTSData {
+    WORD    wFrameControl;
+    WORD    wDurationID;
+    BYTE    abyRA[U_ETHER_ADDR_LEN];
+    BYTE    abyTA[U_ETHER_ADDR_LEN];
+}__attribute__ ((__packed__))
+SRTSData, DEF* PSRTSData;
+typedef const SRTSData DEF*      PCSRTSData;
+
+typedef struct tagSRTS_g {
+    BYTE        bySignalField_b;
+    BYTE        byServiceField_b;
+    WORD        wTransmitLength_b;
+    BYTE        bySignalField_a;
+    BYTE        byServiceField_a;
+    WORD        wTransmitLength_a;
+    WORD        wDuration_ba;
+    WORD        wDuration_aa;
+    WORD        wDuration_bb;
+    WORD        wReserved;
+    SRTSData    Data;
+}__attribute__ ((__packed__))
+SRTS_g, DEF* PSRTS_g;
+typedef const SRTS_g DEF*     PCSRTS_g;
+
+
+typedef struct tagSRTS_g_FB {
+    BYTE        bySignalField_b;
+    BYTE        byServiceField_b;
+    WORD        wTransmitLength_b;
+    BYTE        bySignalField_a;
+    BYTE        byServiceField_a;
+    WORD        wTransmitLength_a;
+    WORD        wDuration_ba;
+    WORD        wDuration_aa;
+    WORD        wDuration_bb;
+    WORD        wReserved;
+    WORD        wRTSDuration_ba_f0;
+    WORD        wRTSDuration_aa_f0;
+    WORD        wRTSDuration_ba_f1;
+    WORD        wRTSDuration_aa_f1;
+    SRTSData    Data;
+}__attribute__ ((__packed__))
+SRTS_g_FB, DEF* PSRTS_g_FB;
+typedef const SRTS_g_FB DEF*     PCSRTS_g_FB;
+
+
+typedef struct tagSRTS_ab {
+    BYTE        bySignalField;
+    BYTE        byServiceField;
+    WORD        wTransmitLength;
+    WORD        wDuration;
+    WORD        wReserved;
+    SRTSData    Data;
+}__attribute__ ((__packed__))
+SRTS_ab, DEF* PSRTS_ab;
+typedef const SRTS_ab DEF*     PCSRTS_ab;
+
+
+typedef struct tagSRTS_a_FB {
+    BYTE        bySignalField;
+    BYTE        byServiceField;
+    WORD        wTransmitLength;
+    WORD        wDuration;
+    WORD        wReserved;
+    WORD        wRTSDuration_f0;
+    WORD        wRTSDuration_f1;
+    SRTSData    Data;
+}__attribute__ ((__packed__))
+SRTS_a_FB, DEF* PSRTS_a_FB;
+typedef const SRTS_a_FB DEF*     PCSRTS_a_FB;
+
+
+//
+// CTS buffer header
+//
+typedef struct tagSCTSData {
+    WORD    wFrameControl;
+    WORD    wDurationID;
+    BYTE    abyRA[U_ETHER_ADDR_LEN];
+    WORD    wReserved;
+}__attribute__ ((__packed__))
+SCTSData, DEF* PSCTSData;
+
+typedef struct tagSCTS {
+    BYTE        bySignalField_b;
+    BYTE        byServiceField_b;
+    WORD        wTransmitLength_b;
+    WORD        wDuration_ba;
+    WORD        wReserved;
+    SCTSData    Data;
+}__attribute__ ((__packed__))
+SCTS, DEF* PSCTS;
+typedef const SCTS DEF*     PCSCTS;
+
+typedef struct tagSCTS_FB {
+    BYTE        bySignalField_b;
+    BYTE        byServiceField_b;
+    WORD        wTransmitLength_b;
+    WORD        wDuration_ba;
+    WORD        wReserved;
+    WORD        wCTSDuration_ba_f0;
+    WORD        wCTSDuration_ba_f1;
+    SCTSData    Data;
+}__attribute__ ((__packed__))
+SCTS_FB, DEF* PSCTS_FB;
+typedef const SCTS_FB DEF*     PCSCTS_FB;
+
+
+//
+// Tx FIFO header
+//
+typedef struct tagSTxBufHead {
+    DWORD   adwTxKey[4];
+    WORD    wFIFOCtl;
+    WORD    wTimeStamp;
+    WORD    wFragCtl;
+    BYTE    byTxPower;
+    BYTE    wReserved;
+}__attribute__ ((__packed__))
+STxBufHead, DEF* PSTxBufHead;
+typedef const STxBufHead DEF*   PCSTxBufHead;
+
+typedef struct tagSTxShortBufHead {
+    WORD    wFIFOCtl;
+    WORD    wTimeStamp;
+}__attribute__ ((__packed__))
+STxShortBufHead, DEF* PSTxShortBufHead;
+typedef const STxShortBufHead DEF*   PCSTxShortBufHead;
+
+//
+// Tx data header
+//
+typedef struct tagSTxDataHead_g {
+    BYTE    bySignalField_b;
+    BYTE    byServiceField_b;
+    WORD    wTransmitLength_b;
+    BYTE    bySignalField_a;
+    BYTE    byServiceField_a;
+    WORD    wTransmitLength_a;
+    WORD    wDuration_b;
+    WORD    wDuration_a;
+    WORD    wTimeStampOff_b;
+    WORD    wTimeStampOff_a;
+}__attribute__ ((__packed__))
+STxDataHead_g, DEF* PSTxDataHead_g;
+typedef const STxDataHead_g DEF*  PCSTxDataHead_g;
+
+typedef struct tagSTxDataHead_g_FB {
+    BYTE    bySignalField_b;
+    BYTE    byServiceField_b;
+    WORD    wTransmitLength_b;
+    BYTE    bySignalField_a;
+    BYTE    byServiceField_a;
+    WORD    wTransmitLength_a;
+    WORD    wDuration_b;
+    WORD    wDuration_a;
+    WORD    wDuration_a_f0;
+    WORD    wDuration_a_f1;
+    WORD    wTimeStampOff_b;
+    WORD    wTimeStampOff_a;
+}__attribute__ ((__packed__))
+STxDataHead_g_FB, DEF* PSTxDataHead_g_FB;
+typedef const STxDataHead_g_FB DEF*  PCSTxDataHead_g_FB;
+
+
+typedef struct tagSTxDataHead_ab {
+    BYTE    bySignalField;
+    BYTE    byServiceField;
+    WORD    wTransmitLength;
+    WORD    wDuration;
+    WORD    wTimeStampOff;
+}__attribute__ ((__packed__))
+STxDataHead_ab, DEF* PSTxDataHead_ab;
+typedef const STxDataHead_ab DEF*  PCSTxDataHead_ab;
+
+
+typedef struct tagSTxDataHead_a_FB {
+    BYTE    bySignalField;
+    BYTE    byServiceField;
+    WORD    wTransmitLength;
+    WORD    wDuration;
+    WORD    wTimeStampOff;
+    WORD    wDuration_f0;
+    WORD    wDuration_f1;
+}__attribute__ ((__packed__))
+STxDataHead_a_FB, DEF* PSTxDataHead_a_FB;
+typedef const STxDataHead_a_FB DEF*  PCSTxDataHead_a_FB;
+
+//
+// MICHDR data header
+//
+typedef struct tagSMICHDRHead {
+    DWORD   adwHDR0[4];
+    DWORD   adwHDR1[4];
+    DWORD   adwHDR2[4];
+}__attribute__ ((__packed__))
+SMICHDRHead, DEF* PSMICHDRHead;
+typedef const SMICHDRHead DEF*   PCSMICHDRHead;
+
+typedef struct tagSBEACONCtl {
+    DWORD   BufReady : 1;
+    DWORD   TSF      : 15;
+    DWORD   BufLen   : 11;
+    DWORD   Reserved : 5;
+}__attribute__ ((__packed__))
+SBEACONCtl;
+
+
+typedef struct tagSSecretKey {
+    DWORD   dwLowDword;
+    BYTE    byHighByte;
+}__attribute__ ((__packed__))
+SSecretKey;
+
+typedef struct tagSKeyEntry {
+    BYTE  abyAddrHi[2];
+    WORD  wKCTL;
+    BYTE  abyAddrLo[4];
+    DWORD dwKey0[4];
+    DWORD dwKey1[4];
+    DWORD dwKey2[4];
+    DWORD dwKey3[4];
+    DWORD dwKey4[4];
+}__attribute__ ((__packed__))
+SKeyEntry;
+/*---------------------  Export Macros ------------------------------*/
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+
+#endif // __DESC_H__
+
diff --git a/drivers/staging/vt6655/device.h b/drivers/staging/vt6655/device.h
new file mode 100644
index 0000000..264d1bb
--- /dev/null
+++ b/drivers/staging/vt6655/device.h
@@ -0,0 +1,1063 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: device.h
+ *
+ * Purpose: MAC Data structure
+ *
+ * Author: Tevin Chen
+ *
+ * Date: Mar 17, 1997
+ *
+ */
+
+#ifndef __DEVICE_H__
+#define __DEVICE_H__
+
+#ifdef MODULE
+#ifdef MODVERSIONS
+#include <linux/modversions.h>
+#endif /* MODVERSIONS */
+#include <linux/module.h>
+#endif /* MODULE */
+
+#include <linux/types.h>
+#include <linux/init.h>
+#include <linux/mm.h>
+#include <linux/errno.h>
+#include <linux/ioport.h>
+#include <linux/pci.h>
+#include <linux/kernel.h>
+#include <linux/netdevice.h>
+#include <linux/etherdevice.h>
+#include <linux/skbuff.h>
+#include <linux/delay.h>
+#include <linux/timer.h>
+#include <linux/slab.h>
+#include <linux/interrupt.h>
+#include <linux/version.h>
+#include <linux/string.h>
+#include <linux/wait.h>
+#include <linux/if_arp.h>
+#include <linux/sched.h>
+#include <asm/io.h>
+#include <linux/if.h>
+//#include <linux/config.h>
+#include <asm/uaccess.h>
+#include <linux/proc_fs.h>
+#include <linux/inetdevice.h>
+#include <linux/reboot.h>
+#ifdef SIOCETHTOOL
+#define DEVICE_ETHTOOL_IOCTL_SUPPORT
+#include <linux/ethtool.h>
+#else
+#undef DEVICE_ETHTOOL_IOCTL_SUPPORT
+#endif
+/* Include Wireless Extension definition and check version - Jean II */
+#include <linux/wireless.h>
+#if WIRELESS_EXT > 12
+#include <net/iw_handler.h>	// New driver API
+#endif	/* WIRELESS_EXT > 12 */
+
+//2008-0409-07, <Add> by Einsn Liu
+#if WIRELESS_EXT > 17
+#ifndef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+#define WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+#endif
+#endif
+//2008-4-14<add> by chester for led issue
+//#define FOR_LED_ON_NOTEBOOK
+//
+
+
+
+//  device specific
+//
+#if !defined(_KCOMPAT_H)
+#include "kcompat.h"
+#endif
+
+#if !defined(__DEVICE_CONFIG_H)
+#include "device_cfg.h"
+#endif
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__WMGR_H__)
+#include "wmgr.h"
+#endif
+#if !defined(__WCMD_H__)
+#include "wcmd.h"
+#endif
+#if !defined(__MIB_H__)
+#include "mib.h"
+#endif
+#if !defined(__SROM_H__)
+#include "srom.h"
+#endif
+#if !defined(__RC4_H__)
+#include "rc4.h"
+#endif
+#if !defined(__TPCI_H__)
+#include "tpci.h"
+#endif
+#if !defined(__DESC_H__)
+#include "desc.h"
+#endif
+
+#if !defined(__KEY_H__)
+#include "key.h"
+#endif
+
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+
+//PLICE_DEBUG->
+//#define		THREAD
+
+//#define	TASK_LET
+//PLICE_DEBUG<-
+
+// #ifdef PRIVATE_OBJ
+//#if !defined(__DEVICE_MODULE_H)
+//#include "device_module.h"
+//#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+#define MAC_MAX_CONTEXT_REG     (256+128)
+
+#define MAX_MULTICAST_ADDRESS_NUM       32
+#define MULTICAST_ADDRESS_LIST_SIZE     (MAX_MULTICAST_ADDRESS_NUM * U_ETHER_ADDR_LEN)
+
+
+//#define OP_MODE_INFRASTRUCTURE  0
+//#define OP_MODE_ADHOC           1
+//#define OP_MODE_AP              2
+
+#define DUPLICATE_RX_CACHE_LENGTH       5
+
+#define NUM_KEY_ENTRY                   11
+
+#define TX_WEP_NONE                     0
+#define TX_WEP_OTF                      1
+#define TX_WEP_SW                       2
+#define TX_WEP_SWOTP                    3
+#define TX_WEP_OTPSW                    4
+#define TX_WEP_SW232                    5
+
+#define KEYSEL_WEP40                    0
+#define KEYSEL_WEP104                   1
+#define KEYSEL_TKIP                     2
+#define KEYSEL_CCMP                     3
+
+
+
+#define AUTO_FB_NONE            0
+#define AUTO_FB_0               1
+#define AUTO_FB_1               2
+
+#define FB_RATE0                0
+#define FB_RATE1                1
+
+// Antenna Mode
+#define ANT_A                   0
+#define ANT_B                   1
+#define ANT_DIVERSITY           2
+#define ANT_RXD_TXA             3
+#define ANT_RXD_TXB             4
+#define ANT_UNKNOWN             0xFF
+
+#define MAXCHECKHANGCNT         4
+
+#define BB_VGA_LEVEL            4
+#define BB_VGA_CHANGE_THRESHOLD 16
+
+
+#ifndef RUN_AT
+#define RUN_AT(x)                       (jiffies+(x))
+#endif
+
+// DMA related
+#define RESERV_AC0DMA                   4
+
+
+// BUILD OBJ mode
+#ifdef PRIVATE_OBJ
+
+#undef dev_kfree_skb
+#undef dev_kfree_skb_irq
+#undef dev_alloc_skb
+#undef kfree
+#undef del_timer
+#undef init_timer
+#undef add_timer
+#undef kmalloc
+#undef netif_stop_queue
+#undef netif_start_queue
+#undef netif_wake_queue
+#undef netif_queue_stopped
+#undef netif_rx
+#undef netif_running
+#undef udelay
+#undef mdelay
+#undef eth_type_trans
+#undef skb_put
+#undef HZ
+#undef RUN_AT
+#undef pci_alloc_consistent
+#undef pci_free_consistent
+#undef register_netdevice
+#undef register_netdev
+#undef unregister_netdevice
+#undef unregister_netdev
+#undef skb_queue_head_init
+#undef skb_queue_tail
+#undef skb_queue_empty
+#undef free_irq
+#undef copy_from_user
+#undef copy_to_user
+#undef spin_lock_init
+#undef pci_map_single
+#undef pci_unmap_single
+
+// redefine kernel dependent fucntion
+#define dev_kfree_skb       ref_dev_kfree_skb
+#define dev_kfree_skb_irq   ref_dev_kfree_skb_irq
+#define dev_alloc_skb       ref_dev_alloc_skb
+#define kfree               ref_kfree
+#define del_timer           ref_del_timer
+#define init_timer          ref_init_timer
+#define add_timer           ref_add_timer
+#define kmalloc             ref_kmalloc
+#define netif_stop_queue    ref_netif_stop_queue
+#define netif_start_queue   ref_netif_start_queue
+#define netif_wake_queue    ref_netif_wake_queue
+#define netif_queue_stopped ref_netif_queue_stopped
+#define netif_rx            ref_netif_rx
+#define netif_running       ref_netif_running
+#define udelay              ref_udelay
+#define mdelay              ref_mdelay
+#define get_jiffies()       ref_get_jiffies()
+#define RUN_AT(x)           (get_jiffies()+(x))
+#define HZ                  ref_HZ_tick()
+#define eth_type_trans      ref_eth_type_trans
+#define skb_put             ref_skb_put
+#define skb_queue_head_init ref_skb_queue_head_init
+#define skb_queue_tail      ref_skb_queue_tail
+#define skb_queue_empty     ref_skb_queue_empty
+
+#define pci_alloc_consistent    ref_pci_alloc_consistent
+#define pci_free_consistent     ref_pci_free_consistent
+#define register_netdevice      ref_register_netdevice
+#define register_netdev         ref_register_netdev
+#define unregister_netdevice    ref_unregister_netdevice
+#define unregister_netdev       ref_unregister_netdev
+
+#define free_irq                ref_free_irq
+#define copy_from_user          ref_copy_from_user
+#define copy_to_user            ref_copy_to_user
+#define spin_lock_init          ref_spin_lock_init
+#define pci_map_single          ref_pci_map_single
+#define pci_unmap_single        ref_pci_unmap_single
+#endif
+
+
+#ifdef PRIVATE_OBJ
+#undef  printk
+#define DEVICE_PRT(l, p, args...) {if (l<=msglevel) do {} while (0);}
+//#define DEVICE_PRT(l, p, args...) {if (l<=msglevel) printk( p ,##args);}
+#else
+#define DEVICE_PRT(l, p, args...) {if (l<=msglevel) printk( p ,##args);}
+#endif
+
+
+#define	AVAIL_TD(p,q)	((p)->sOpts.nTxDescs[(q)]-((p)->iTDUsed[(q)]))
+
+//PLICE_DEBUG ->
+#define	NUM				64
+//PLICE_DEUBG <-
+
+
+
+/*---------------------  Export Types  ------------------------------*/
+
+
+//0:11A 1:11B 2:11G
+typedef enum _VIA_BB_TYPE
+{
+    BB_TYPE_11A=0,
+    BB_TYPE_11B,
+    BB_TYPE_11G
+} VIA_BB_TYPE, *PVIA_BB_TYPE;
+
+//0:11a,1:11b,2:11gb(only CCK in BasicRate),3:11ga(OFDM in Basic Rate)
+typedef enum _VIA_PKT_TYPE
+{
+    PK_TYPE_11A=0,
+    PK_TYPE_11B,
+    PK_TYPE_11GB,
+    PK_TYPE_11GA
+} VIA_PKT_TYPE, *PVIA_PKT_TYPE;
+
+
+typedef enum __device_msg_level {
+    MSG_LEVEL_ERR=0,            //Errors that will cause abnormal operation.
+    MSG_LEVEL_NOTICE=1,         //Some errors need users to be notified.
+    MSG_LEVEL_INFO=2,           //Normal message.
+    MSG_LEVEL_VERBOSE=3,        //Will report all trival errors.
+    MSG_LEVEL_DEBUG=4           //Only for debug purpose.
+} DEVICE_MSG_LEVEL, *PDEVICE_MSG_LEVEL;
+
+typedef enum __device_init_type {
+    DEVICE_INIT_COLD=0,         // cold init
+    DEVICE_INIT_RESET,          // reset init or Dx to D0 power remain init
+    DEVICE_INIT_DXPL            // Dx to D0 power lost init
+} DEVICE_INIT_TYPE, *PDEVICE_INIT_TYPE;
+
+
+//++ NDIS related
+
+#define MAX_BSSIDINFO_4_PMKID   16
+#define MAX_PMKIDLIST           5
+//Flags for PMKID Candidate list structure
+#define NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED	0x01
+
+// PMKID Structures
+typedef UCHAR   NDIS_802_11_PMKID_VALUE[16];
+
+
+typedef enum _NDIS_802_11_WEP_STATUS
+{
+    Ndis802_11WEPEnabled,
+    Ndis802_11Encryption1Enabled = Ndis802_11WEPEnabled,
+    Ndis802_11WEPDisabled,
+    Ndis802_11EncryptionDisabled = Ndis802_11WEPDisabled,
+    Ndis802_11WEPKeyAbsent,
+    Ndis802_11Encryption1KeyAbsent = Ndis802_11WEPKeyAbsent,
+    Ndis802_11WEPNotSupported,
+    Ndis802_11EncryptionNotSupported = Ndis802_11WEPNotSupported,
+    Ndis802_11Encryption2Enabled,
+    Ndis802_11Encryption2KeyAbsent,
+    Ndis802_11Encryption3Enabled,
+    Ndis802_11Encryption3KeyAbsent
+} NDIS_802_11_WEP_STATUS, *PNDIS_802_11_WEP_STATUS,
+  NDIS_802_11_ENCRYPTION_STATUS, *PNDIS_802_11_ENCRYPTION_STATUS;
+
+
+typedef enum _NDIS_802_11_STATUS_TYPE
+{
+    Ndis802_11StatusType_Authentication,
+    Ndis802_11StatusType_MediaStreamMode,
+    Ndis802_11StatusType_PMKID_CandidateList,
+    Ndis802_11StatusTypeMax    // not a real type, defined as an upper bound
+} NDIS_802_11_STATUS_TYPE, *PNDIS_802_11_STATUS_TYPE;
+
+//Added new types for PMKID Candidate lists.
+typedef struct _PMKID_CANDIDATE {
+    NDIS_802_11_MAC_ADDRESS BSSID;
+    ULONG Flags;
+} PMKID_CANDIDATE, *PPMKID_CANDIDATE;
+
+
+typedef struct _BSSID_INFO
+{
+    NDIS_802_11_MAC_ADDRESS BSSID;
+    NDIS_802_11_PMKID_VALUE PMKID;
+} BSSID_INFO, *PBSSID_INFO;
+
+typedef struct tagSPMKID {
+    ULONG Length;
+    ULONG BSSIDInfoCount;
+    BSSID_INFO BSSIDInfo[MAX_BSSIDINFO_4_PMKID];
+} SPMKID, *PSPMKID;
+
+typedef struct tagSPMKIDCandidateEvent {
+    NDIS_802_11_STATUS_TYPE     StatusType;
+    ULONG Version;       // Version of the structure
+    ULONG NumCandidates; // No. of pmkid candidates
+    PMKID_CANDIDATE CandidateList[MAX_PMKIDLIST];
+} SPMKIDCandidateEvent, DEF* PSPMKIDCandidateEvent;
+
+
+//--
+
+//++ 802.11h related
+#define MAX_QUIET_COUNT     8
+
+typedef struct tagSQuietControl {
+    BOOL        bEnable;
+    DWORD       dwStartTime;
+    BYTE        byPeriod;
+    WORD        wDuration;
+} SQuietControl, DEF* PSQuietControl;
+
+//--
+typedef struct __chip_info_tbl{
+    CHIP_TYPE   chip_id;
+    char*       name;
+    int         io_size;
+    int         nTxQueue;
+    U32         flags;
+} CHIP_INFO, *PCHIP_INFO;
+
+
+typedef enum {
+    OWNED_BY_HOST=0,
+    OWNED_BY_NIC=1
+} DEVICE_OWNER_TYPE, *PDEVICE_OWNER_TYPE;
+
+
+// The receive duplicate detection cache entry
+typedef struct tagSCacheEntry{
+    WORD        wFmSequence;
+    BYTE        abyAddr2[U_ETHER_ADDR_LEN];
+} SCacheEntry, *PSCacheEntry;
+
+
+typedef struct tagSCache{
+/* The receive cache is updated circularly.  The next entry to be written is
+ * indexed by the "InPtr".
+*/
+    UINT            uInPtr;         // Place to use next
+    SCacheEntry     asCacheEntry[DUPLICATE_RX_CACHE_LENGTH];
+} SCache, *PSCache;
+
+#define CB_MAX_RX_FRAG                 64
+// DeFragment Control Block, used for collecting fragments prior to reassembly
+typedef struct tagSDeFragControlBlock
+{
+    WORD            wSequence;
+    WORD            wFragNum;
+    BYTE            abyAddr2[U_ETHER_ADDR_LEN];
+	UINT            uLifetime;
+    struct sk_buff* skb;
+#ifdef PRIVATE_OBJ
+    ref_sk_buff     ref_skb;
+#endif
+    PBYTE           pbyRxBuffer;
+    UINT            cbFrameLength;
+    BOOL            bInUse;
+} SDeFragControlBlock, DEF* PSDeFragControlBlock;
+
+
+
+
+//flags for options
+#define     DEVICE_FLAGS_IP_ALIGN        0x00000001UL
+#define     DEVICE_FLAGS_PREAMBLE_TYPE   0x00000002UL
+#define     DEVICE_FLAGS_OP_MODE         0x00000004UL
+#define     DEVICE_FLAGS_PS_MODE         0x00000008UL
+#define		DEVICE_FLAGS_80211h_MODE	 0x00000010UL
+#define		DEVICE_FLAGS_DiversityANT	 0x00000020UL
+
+//flags for driver status
+#define     DEVICE_FLAGS_OPENED          0x00010000UL
+#define     DEVICE_FLAGS_WOL_ENABLED     0x00080000UL
+//flags for capbilities
+#define     DEVICE_FLAGS_TX_ALIGN        0x01000000UL
+#define     DEVICE_FLAGS_HAVE_CAM        0x02000000UL
+#define     DEVICE_FLAGS_FLOW_CTRL       0x04000000UL
+
+//flags for MII status
+#define     DEVICE_LINK_FAIL             0x00000001UL
+#define     DEVICE_SPEED_10              0x00000002UL
+#define     DEVICE_SPEED_100             0x00000004UL
+#define     DEVICE_SPEED_1000            0x00000008UL
+#define     DEVICE_DUPLEX_FULL           0x00000010UL
+#define     DEVICE_AUTONEG_ENABLE        0x00000020UL
+#define     DEVICE_FORCED_BY_EEPROM      0x00000040UL
+//for device_set_media_duplex
+#define     DEVICE_LINK_CHANGE           0x00000001UL
+
+
+//PLICE_DEBUG->
+
+
+typedef	struct _RxManagementQueue
+{
+	int	packet_num;
+	int	head,tail;
+	PSRxMgmtPacket	Q[NUM];
+} RxManagementQueue,*PSRxManagementQueue;
+
+
+
+//PLICE_DEBUG<-
+
+
+typedef struct __device_opt {
+    int         nRxDescs0;      //Number of RX descriptors0
+    int         nRxDescs1;      //Number of RX descriptors1
+    int         nTxDescs[2];    //Number of TX descriptors 0, 1
+    int         int_works;      //interrupt limits
+    int         rts_thresh;     //rts threshold
+    int         frag_thresh;
+    int         data_rate;
+    int         channel_num;
+    int         short_retry;
+    int         long_retry;
+    int         bbp_type;
+    U32         flags;
+} OPTIONS, *POPTIONS;
+
+
+typedef struct __device_info {
+    struct __device_info*        next;
+    struct __device_info*        prev;
+
+    struct pci_dev*             pcid;
+
+#if CONFIG_PM
+    u32                         pci_state[16];
+#endif
+
+// netdev
+    struct net_device*          dev;
+    struct net_device*          next_module;
+    struct net_device_stats     stats;
+
+//dma addr, rx/tx pool
+    dma_addr_t                  pool_dma;
+    dma_addr_t                  rd0_pool_dma;
+    dma_addr_t                  rd1_pool_dma;
+
+    dma_addr_t                  td0_pool_dma;
+    dma_addr_t                  td1_pool_dma;
+
+    dma_addr_t                  tx_bufs_dma0;
+    dma_addr_t                  tx_bufs_dma1;
+    dma_addr_t                  tx_beacon_dma;
+
+    PBYTE                       tx0_bufs;
+    PBYTE                       tx1_bufs;
+    PBYTE                       tx_beacon_bufs;
+
+    CHIP_TYPE                   chip_id;
+
+    U32                         PortOffset;
+    DWORD                       dwIsr;
+    U32                         memaddr;
+    U32                         ioaddr;
+    U32                         io_size;
+
+    BYTE                        byRevId;
+    WORD                        SubSystemID;
+    WORD                        SubVendorID;
+
+    int                         nTxQueues;
+    volatile int                iTDUsed[TYPE_MAXTD];
+
+    volatile PSTxDesc           apCurrTD[TYPE_MAXTD];
+    volatile PSTxDesc           apTailTD[TYPE_MAXTD];
+
+    volatile PSTxDesc           apTD0Rings;
+    volatile PSTxDesc           apTD1Rings;
+
+    volatile PSRxDesc           aRD0Ring;
+    volatile PSRxDesc           aRD1Ring;
+    volatile PSRxDesc           pCurrRD[TYPE_MAXRD];
+    SCache                      sDupRxCache;
+
+    SDeFragControlBlock         sRxDFCB[CB_MAX_RX_FRAG];
+    UINT                        cbDFCB;
+    UINT                        cbFreeDFCB;
+    UINT                        uCurrentDFCBIdx;
+
+    OPTIONS                     sOpts;
+
+    U32                         flags;
+
+    U32                         rx_buf_sz;
+    int                         multicast_limit;
+    BYTE                        byRxMode;
+
+    spinlock_t                  lock;
+//PLICE_DEBUG->
+	struct	tasklet_struct 		RxMngWorkItem;
+	RxManagementQueue	rxManeQueue;
+//PLICE_DEBUG<-
+//PLICE_DEBUG ->
+	pid_t				MLMEThr_pid;
+	struct 	completion	notify;
+	struct 	semaphore	mlme_semaphore;
+//PLICE_DEBUG <-
+
+
+    U32                         rx_bytes;
+
+    // Version control
+    BYTE                        byLocalID;
+    BYTE                        byRFType;
+
+    BYTE                        byMaxPwrLevel;
+    BYTE                        byZoneType;
+    BOOL                        bZoneRegExist;
+   BYTE                        byOriginalZonetype;
+    BYTE                        abyMacContext[MAC_MAX_CONTEXT_REG];
+    BOOL                        bLinkPass;          // link status: OK or fail
+    BYTE                        abyCurrentNetAddr[U_ETHER_ADDR_LEN];
+
+    // Adapter statistics
+    SStatCounter                scStatistic;
+    // 802.11 counter
+    SDot11Counters              s802_11Counter;
+
+
+    // 802.11 management
+    PSMgmtObject                pMgmt;
+    SMgmtObject                 sMgmtObj;
+
+    // 802.11 MAC specific
+    UINT                        uCurrRSSI;
+    BYTE                        byCurrSQ;
+
+    DWORD                       dwTxAntennaSel;
+    DWORD                       dwRxAntennaSel;
+    BYTE                        byAntennaCount;
+    BYTE                        byRxAntennaMode;
+    BYTE                        byTxAntennaMode;
+    BOOL                        bTxRxAntInv;
+
+    PBYTE                       pbyTmpBuff;
+    UINT                        uSIFS;    //Current SIFS
+    UINT                        uDIFS;    //Current DIFS
+    UINT                        uEIFS;    //Current EIFS
+    UINT                        uSlot;    //Current SlotTime
+    UINT                        uCwMin;   //Current CwMin
+    UINT                        uCwMax;   //CwMax is fixed on 1023.
+    // PHY parameter
+    BYTE                        bySIFS;
+    BYTE                        byDIFS;
+    BYTE                        byEIFS;
+    BYTE                        bySlot;
+    BYTE                        byCWMaxMin;
+    CARD_PHY_TYPE               eCurrentPHYType;
+
+
+    VIA_BB_TYPE                 byBBType; //0: 11A, 1:11B, 2:11G
+    VIA_PKT_TYPE                byPacketType; //0:11a,1:11b,2:11gb(only CCK in BasicRate),3:11ga(OFDM in Basic Rate)
+    WORD                        wBasicRate;
+    BYTE                        byACKRate;
+    BYTE                        byTopOFDMBasicRate;
+    BYTE                        byTopCCKBasicRate;
+
+    BYTE                        byMinChannel;
+    BYTE                        byMaxChannel;
+    UINT                        uConnectionRate;
+
+    BYTE                        byPreambleType;
+    BYTE                        byShortPreamble;
+
+    WORD                        wCurrentRate;
+    WORD                        wRTSThreshold;
+    WORD                        wFragmentationThreshold;
+    BYTE                        byShortRetryLimit;
+    BYTE                        byLongRetryLimit;
+    CARD_OP_MODE                eOPMode;
+    BYTE                        byOpMode;
+    BOOL                        bBSSIDFilter;
+    WORD                        wMaxTransmitMSDULifetime;
+    BYTE                        abyBSSID[U_ETHER_ADDR_LEN];
+    BYTE                        abyDesireBSSID[U_ETHER_ADDR_LEN];
+    WORD                        wCTSDuration;       // update while speed change
+    WORD                        wACKDuration;       // update while speed change
+    WORD                        wRTSTransmitLen;    // update while speed change
+    BYTE                        byRTSServiceField;  // update while speed change
+    BYTE                        byRTSSignalField;   // update while speed change
+
+    DWORD                       dwMaxReceiveLifetime;       // dot11MaxReceiveLifetime
+
+    BOOL                        bCCK;
+    BOOL                        bEncryptionEnable;
+    BOOL                        bLongHeader;
+    BOOL                        bShortSlotTime;
+    BOOL                        bProtectMode;
+    BOOL                        bNonERPPresent;
+    BOOL                        bBarkerPreambleMd;
+
+    BYTE                        byERPFlag;
+    WORD                        wUseProtectCntDown;
+
+    BOOL                    bRadioControlOff;
+    BOOL                    bRadioOff;
+    BOOL                    bEnablePSMode;
+    WORD                    wListenInterval;
+    BOOL                    bPWBitOn;
+    WMAC_POWER_MODE         ePSMode;
+
+
+    // GPIO Radio Control
+    BYTE                    byRadioCtl;
+    BYTE                    byGPIO;
+    BOOL                    bHWRadioOff;
+    BOOL                    bPrvActive4RadioOFF;
+    BOOL                    bGPIOBlockRead;
+
+    // Beacon releated
+    WORD                    wSeqCounter;
+    WORD                    wBCNBufLen;
+    BOOL                    bBeaconBufReady;
+    BOOL                    bBeaconSent;
+    BOOL                    bIsBeaconBufReadySet;
+    UINT                    cbBeaconBufReadySetCnt;
+    BOOL                    bFixRate;
+    BYTE                    byCurrentCh;
+    UINT                    uScanTime;
+
+    CMD_STATE               eCommandState;
+
+    CMD_CODE                eCommand;
+    BOOL                    bBeaconTx;
+
+    BOOL                    bStopBeacon;
+    BOOL                    bStopDataPkt;
+    BOOL                    bStopTx0Pkt;
+    UINT                    uAutoReConnectTime;
+
+    // 802.11 counter
+
+    CMD_ITEM                eCmdQueue[CMD_Q_SIZE];
+    UINT                    uCmdDequeueIdx;
+    UINT                    uCmdEnqueueIdx;
+    UINT                    cbFreeCmdQueue;
+    BOOL                    bCmdRunning;
+    BOOL                    bCmdClear;
+
+
+
+    BOOL                    bRoaming;
+    //WOW
+    BYTE                    abyIPAddr[4];
+
+    ULONG                   ulTxPower;
+    NDIS_802_11_WEP_STATUS  eEncryptionStatus;
+    BOOL                    bTransmitKey;
+//2007-0925-01<Add>by MikeLiu
+//mike add :save old Encryption
+    NDIS_802_11_WEP_STATUS  eOldEncryptionStatus;
+    SKeyManagement          sKey;
+    DWORD                   dwIVCounter;
+
+    QWORD                   qwPacketNumber; //For CCMP and TKIP as TSC(6 bytes)
+    UINT                    uCurrentWEPMode;
+
+    RC4Ext                  SBox;
+    BYTE                    abyPRNG[WLAN_WEPMAX_KEYLEN+3];
+
+    BYTE                    byKeyIndex;
+    UINT                    uKeyLength;
+    BYTE                    abyKey[WLAN_WEP232_KEYLEN];
+
+    BOOL                    bAES;
+    BYTE                    byCntMeasure;
+
+    // for AP mode
+    UINT                    uAssocCount;
+    BOOL                    bMoreData;
+
+    // QoS
+    BOOL                    bGrpAckPolicy;
+
+    // for OID_802_11_ASSOCIATION_INFORMATION
+    BOOL                    bAssocInfoSet;
+
+
+    BYTE                    byAutoFBCtrl;
+
+    BOOL                    bTxMICFail;
+    BOOL                    bRxMICFail;
+
+
+    UINT                    uRATEIdx;
+
+
+    // For Update BaseBand VGA Gain Offset
+    BOOL                    bUpdateBBVGA;
+    UINT                    uBBVGADiffCount;
+    BYTE                    byBBVGANew;
+    BYTE                    byBBVGACurrent;
+    BYTE                    abyBBVGA[BB_VGA_LEVEL];
+    LONG                    ldBmThreshold[BB_VGA_LEVEL];
+
+    BYTE                    byBBPreEDRSSI;
+    BYTE                    byBBPreEDIndex;
+
+    BOOL                    bRadioCmd;
+    DWORD                   dwDiagRefCount;
+
+    // For FOE Tuning
+    BYTE                    byFOETuning;
+
+    // For Auto Power Tunning
+
+    BYTE                    byAutoPwrTunning;
+    SHORT                   sPSetPointCCK;
+    SHORT                   sPSetPointOFDMG;
+    SHORT                   sPSetPointOFDMA;
+    LONG                    lPFormulaOffset;
+    SHORT                   sPThreshold;
+    CHAR                    cAdjustStep;
+    CHAR                    cMinTxAGC;
+
+    // For RF Power table
+    BYTE                    byCCKPwr;
+    BYTE                    byOFDMPwrG;
+    BYTE                    byCurPwr;
+    I8                      byCurPwrdBm;
+    BYTE                    abyCCKPwrTbl[CB_MAX_CHANNEL_24G+1];
+    BYTE                    abyOFDMPwrTbl[CB_MAX_CHANNEL+1];
+    I8                      abyCCKDefaultPwr[CB_MAX_CHANNEL_24G+1];
+    I8                      abyOFDMDefaultPwr[CB_MAX_CHANNEL+1];
+    I8                      abyRegPwr[CB_MAX_CHANNEL+1];
+    I8                      abyLocalPwr[CB_MAX_CHANNEL+1];
+
+
+    // BaseBand Loopback Use
+    BYTE                    byBBCR4d;
+    BYTE                    byBBCRc9;
+    BYTE                    byBBCR88;
+    BYTE                    byBBCR09;
+
+    // command timer
+    struct timer_list       sTimerCommand;
+#ifdef TxInSleep
+     struct timer_list       sTimerTxData;
+     ULONG                       nTxDataTimeCout;
+     BOOL  fTxDataInSleep;
+     BOOL  IsTxDataTrigger;
+#endif
+
+#ifdef WPA_SM_Transtatus
+    BOOL  fWPA_Authened;           //is WPA/WPA-PSK or WPA2/WPA2-PSK authen??
+#endif
+    BYTE            byReAssocCount;   //mike add:re-association retry times!
+    BYTE            byLinkWaitCount;
+
+
+    BYTE                    abyNodeName[17];
+
+    BOOL                    bDiversityRegCtlON;
+    BOOL                    bDiversityEnable;
+    ULONG                   ulDiversityNValue;
+    ULONG                   ulDiversityMValue;
+    BYTE                    byTMax;
+    BYTE                    byTMax2;
+    BYTE                    byTMax3;
+    ULONG                   ulSQ3TH;
+
+// ANT diversity
+    ULONG                   uDiversityCnt;
+    BYTE                    byAntennaState;
+    ULONG                   ulRatio_State0;
+    ULONG                   ulRatio_State1;
+
+    //SQ3 functions for antenna diversity
+    struct timer_list           TimerSQ3Tmax1;
+    struct timer_list           TimerSQ3Tmax2;
+    struct timer_list           TimerSQ3Tmax3;
+
+
+    ULONG                   uNumSQ3[MAX_RATE];
+    WORD                    wAntDiversityMaxRate;
+
+
+    SEthernetHeader         sTxEthHeader;
+    SEthernetHeader         sRxEthHeader;
+    BYTE                    abyBroadcastAddr[U_ETHER_ADDR_LEN];
+    BYTE                    abySNAP_RFC1042[U_ETHER_ADDR_LEN];
+    BYTE                    abySNAP_Bridgetunnel[U_ETHER_ADDR_LEN];
+     BYTE                        abyEEPROM[EEP_MAX_CONTEXT_SIZE];  //DWORD alignment
+    // Pre-Authentication & PMK cache
+    SPMKID                  gsPMKID;
+    SPMKIDCandidateEvent    gsPMKIDCandidate;
+
+
+    // for 802.11h
+    BOOL                    b11hEnable;
+    BYTE                    abyCountryCode[3];
+    // for 802.11h DFS
+    UINT                    uNumOfMeasureEIDs;
+    PWLAN_IE_MEASURE_REQ    pCurrMeasureEID;
+    BOOL                    bMeasureInProgress;
+    BYTE                    byOrgChannel;
+    BYTE                    byOrgRCR;
+    DWORD                   dwOrgMAR0;
+    DWORD                   dwOrgMAR4;
+    BYTE                    byBasicMap;
+    BYTE                    byCCAFraction;
+    BYTE                    abyRPIs[8];
+    DWORD                   dwRPIs[8];
+    BOOL                    bChannelSwitch;
+    BYTE                    byNewChannel;
+    BYTE                    byChannelSwitchCount;
+    BOOL                    bQuietEnable;
+    BOOL                    bEnableFirstQuiet;
+    BYTE                    byQuietStartCount;
+    UINT                    uQuietEnqueue;
+    DWORD                   dwCurrentQuietEndTime;
+    SQuietControl           sQuiet[MAX_QUIET_COUNT];
+    // for 802.11h TPC
+    BOOL                    bCountryInfo5G;
+    BOOL                    bCountryInfo24G;
+
+    WORD                    wBeaconInterval;
+
+    //WPA supplicant deamon
+	struct net_device       *wpadev;
+	BOOL                    bWPADEVUp;
+    struct sk_buff          *skb;
+#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+/*
+        BOOL                 bwextstep0;
+        BOOL                 bwextstep1;
+        BOOL                 bwextstep2;
+        BOOL                 bwextstep3;
+        */
+        UINT                   bwextcount;
+        BOOL                 bWPASuppWextEnabled;
+#endif
+
+    //--
+#ifdef HOSTAP
+    // user space daemon: hostapd, is used for HOSTAP
+	BOOL                    bEnableHostapd;
+	BOOL                    bEnable8021x;
+	BOOL                    bEnableHostWEP;
+	struct net_device       *apdev;
+	int (*tx_80211)(struct sk_buff *skb, struct net_device *dev);
+#endif
+    UINT                    uChannel;
+    BOOL                    bMACSuspend;
+
+#ifdef WIRELESS_EXT
+	struct iw_statistics	wstats;		// wireless stats
+#endif /* WIRELESS_EXT */
+    BOOL                    bCommit;
+
+} DEVICE_INFO, *PSDevice;
+
+
+//PLICE_DEBUG->
+
+
+ inline  static	VOID   EnQueue (PSDevice pDevice,PSRxMgmtPacket  pRxMgmtPacket)
+{
+	//printk("Enter EnQueue:tail is %d\n",pDevice->rxManeQueue.tail);
+	if ((pDevice->rxManeQueue.tail+1) % NUM == pDevice->rxManeQueue.head)
+	{
+		//printk("Queue is Full,tail is %d\n",pDevice->rxManeQueue.tail);
+		return ;
+	}
+	else
+	{
+		pDevice->rxManeQueue.tail = (pDevice->rxManeQueue.tail+1)% NUM;
+		pDevice->rxManeQueue.Q[pDevice->rxManeQueue.tail] = pRxMgmtPacket;
+		pDevice->rxManeQueue.packet_num++;
+		//printk("packet num is %d\n",pDevice->rxManeQueue.packet_num);
+	}
+}
+
+
+
+
+	inline  static  PSRxMgmtPacket DeQueue (PSDevice pDevice)
+{
+	PSRxMgmtPacket  pRxMgmtPacket;
+	if (pDevice->rxManeQueue.tail == pDevice->rxManeQueue.head)
+	{
+		printk("Queue is Empty\n");
+		return NULL;
+	}
+	else
+	{
+		int	x;
+		//x=pDevice->rxManeQueue.head = (pDevice->rxManeQueue.head+1)%NUM;
+		pDevice->rxManeQueue.head = (pDevice->rxManeQueue.head+1)%NUM;
+		x = pDevice->rxManeQueue.head;
+		//printk("Enter DeQueue:head is %d\n",x);
+		pRxMgmtPacket = pDevice->rxManeQueue.Q[x];
+		pDevice->rxManeQueue.packet_num--;
+		return pRxMgmtPacket;
+	}
+}
+
+VOID	InitRxManagementQueue(PSDevice   pDevice);
+
+
+
+//PLICE_DEBUG<-
+
+
+
+
+
+
+inline static BOOL device_get_ip(PSDevice pInfo) {
+    struct in_device* in_dev=(struct in_device*) pInfo->dev->ip_ptr;
+    struct in_ifaddr* ifa;
+
+    if (in_dev!=NULL) {
+        ifa=(struct in_ifaddr*) in_dev->ifa_list;
+        if (ifa!=NULL) {
+            memcpy(pInfo->abyIPAddr,&ifa->ifa_address,4);
+            return TRUE;
+        }
+    }
+    return FALSE;
+}
+
+
+
+static inline PDEVICE_RD_INFO alloc_rd_info(void) {
+    PDEVICE_RD_INFO  ptr;
+    if ((ptr = (PDEVICE_RD_INFO)kmalloc((int)sizeof(DEVICE_RD_INFO), (int)GFP_ATOMIC)) == NULL)
+        return NULL;
+    else {
+        memset(ptr,0,sizeof(DEVICE_RD_INFO));
+        return ptr;
+    }
+}
+
+static inline PDEVICE_TD_INFO alloc_td_info(void) {
+    PDEVICE_TD_INFO  ptr;
+    if ((ptr = (PDEVICE_TD_INFO)kmalloc((int)sizeof(DEVICE_TD_INFO), (int)GFP_ATOMIC))==NULL)
+        return NULL;
+    else {
+        memset(ptr,0,sizeof(DEVICE_TD_INFO));
+        return ptr;
+    }
+}
+
+/*---------------------  Export Functions  --------------------------*/
+
+BOOL device_dma0_xmit(PSDevice pDevice, struct sk_buff *skb, UINT uNodeIndex);
+BOOL device_alloc_frag_buf(PSDevice pDevice, PSDeFragControlBlock pDeF);
+int Config_FileOperation(PSDevice pDevice,BOOL fwrite,unsigned char *Parameter);
+#endif
+
+
diff --git a/drivers/staging/vt6655/device_cfg.h b/drivers/staging/vt6655/device_cfg.h
new file mode 100644
index 0000000..1cbb444
--- /dev/null
+++ b/drivers/staging/vt6655/device_cfg.h
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: device_cfg.h
+ *
+ * Purpose: Driver configuration header
+ * Author: Lyndon Chen
+ *
+ * Date: Dec 17, 2002
+ *
+ */
+#ifndef __DEVICE_CONFIG_H
+#define __DEVICE_CONFIG_H
+
+//#include <linux/config.h>
+#include <linux/types.h>
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+
+typedef __u8    UINT8,   *PUINT8;
+typedef __u16   UINT16,  *PUINT16;
+typedef __u32   UINT32,  *PUINT32;
+
+
+#ifndef VOID
+#define VOID            void
+#endif
+
+#ifndef CONST
+#define CONST           const
+#endif
+
+#ifndef STATIC
+#define STATIC          static
+#endif
+
+#ifndef DEF
+#define DEF
+#endif
+
+#ifndef IN
+#define IN
+#endif
+
+#ifndef OUT
+#define OUT
+#endif
+
+typedef
+struct _version {
+    UINT8   major;
+    UINT8   minor;
+    UINT8   build;
+} version_t, *pversion_t;
+
+#ifndef FALSE
+#define FALSE   (0)
+#endif
+
+#ifndef TRUE
+#define TRUE    (!(FALSE))
+#endif
+
+#define VID_TABLE_SIZE      64
+#define MCAST_TABLE_SIZE    64
+#define MCAM_SIZE           32
+#define VCAM_SIZE           32
+#define TX_QUEUE_NO         8
+
+#define DEVICE_NAME         "vt6655"
+#define DEVICE_FULL_DRV_NAM "VIA Networking Solomon-A/B/G Wireless LAN Adapter Driver"
+
+#ifndef MAJOR_VERSION
+#define MAJOR_VERSION       1
+#endif
+
+#ifndef MINOR_VERSION
+#define MINOR_VERSION       17
+#endif
+
+#ifndef DEVICE_VERSION
+#define DEVICE_VERSION       "1.19.12"
+#endif
+//config file
+#include <linux/fs.h>
+#include <linux/fcntl.h>
+#ifndef CONFIG_PATH
+#define CONFIG_PATH            "/etc/vntconfiguration.dat"
+#endif
+
+//Max: 2378=2312Payload + 30HD +4CRC + 2Padding + 4Len + 8TSF + 4RSR
+#define PKT_BUF_SZ          2390
+
+
+#define MALLOC(x,y)         kmalloc((x),(y))
+#define FREE(x)             kfree((x))
+#define MAX_UINTS           8
+#define OPTION_DEFAULT      { [0 ... MAX_UINTS-1] = -1}
+
+
+
+typedef enum  _chip_type{
+    VT3253=1
+} CHIP_TYPE, *PCHIP_TYPE;
+
+
+
+#ifdef VIAWET_DEBUG
+#define ASSERT(x) { \
+    if (!(x)) { \
+        printk(KERN_ERR "assertion %s failed: file %s line %d\n", #x,\
+        __FUNCTION__, __LINE__);\
+        *(int*) 0=0;\
+    }\
+}
+#define DBG_PORT80(value)                   outb(value, 0x80)
+#else
+#define ASSERT(x)
+#define DBG_PORT80(value)
+#endif
+
+
+#endif
diff --git a/drivers/staging/vt6655/device_main.c b/drivers/staging/vt6655/device_main.c
new file mode 100644
index 0000000..a10ed27
--- /dev/null
+++ b/drivers/staging/vt6655/device_main.c
@@ -0,0 +1,4074 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: device_main.c
+ *
+ * Purpose: driver entry for initial, open, close, tx and rx.
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: Jan 8, 2003
+ *
+ * Functions:
+ *
+ *   device_found1 - module initial (insmod) driver entry
+ *   device_remove1 - module remove entry
+ *   device_init_info - device structure resource allocation function
+ *   device_free_info - device structure resource free function
+ *   device_get_pci_info - get allocated pci io/mem resource
+ *   device_print_info - print out resource
+ *   device_open - allocate dma/descripter resource & initial mac/bbp function
+ *   device_xmit - asynchrous data tx function
+ *   device_intr - interrupt handle function
+ *   device_set_multi - set mac filter
+ *   device_ioctl - ioctl entry
+ *   device_close - shutdown mac/bbp & free dma/descripter resource
+ *   device_rx_srv - rx service function
+ *   device_receive_frame - rx data function
+ *   device_alloc_rx_buf - rx buffer pre-allocated function
+ *   device_alloc_frag_buf - rx fragement pre-allocated function
+ *   device_free_tx_buf - free tx buffer function
+ *   device_free_frag_buf- free de-fragement buffer
+ *   device_dma0_tx_80211- tx 802.11 frame via dma0
+ *   device_dma0_xmit- tx PS bufferred frame via dma0
+ *   device_init_rd0_ring- initial rd dma0 ring
+ *   device_init_rd1_ring- initial rd dma1 ring
+ *   device_init_td0_ring- initial tx dma0 ring buffer
+ *   device_init_td1_ring- initial tx dma1 ring buffer
+ *   device_init_registers- initial MAC & BBP & RF internal registers.
+ *   device_init_rings- initial tx/rx ring buffer
+ *   device_init_defrag_cb- initial & allocate de-fragement buffer.
+ *   device_free_rings- free all allocated ring buffer
+ *   device_tx_srv- tx interrupt service function
+ *
+ * Revision History:
+ */
+#undef __NO_VERSION__
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__WMGR_H__)
+#include "wmgr.h"
+#endif
+#if !defined(__WCTL_H__)
+#include "wctl.h"
+#endif
+#if !defined(__POWER_H__)
+#include "power.h"
+#endif
+#if !defined(__WCMD_H__)
+#include "wcmd.h"
+#endif
+#if !defined(__IOCMD_H__)
+#include "iocmd.h"
+#endif
+#if !defined(__TCRC_H__)
+#include "tcrc.h"
+#endif
+#if !defined(__RXTX_H__)
+#include "rxtx.h"
+#endif
+#if !defined(__WROUTE_H__)
+#include "wroute.h"
+#endif
+#if !defined(__BSSDB_H__)
+#include "bssdb.h"
+#endif
+#if !defined(__HOSTAP_H__)
+#include "hostap.h"
+#endif
+#if !defined(__WPACTL_H__)
+#include "wpactl.h"
+#endif
+#if !defined(__IOCTL_H__)
+#include "ioctl.h"
+#endif
+#if !defined(__IWCTL_H__)
+#include "iwctl.h"
+#endif
+#if !defined(__DPC_H__)
+#include "dpc.h"
+#endif
+#if !defined(__DATARATE_H__)
+#include "datarate.h"
+#endif
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+#if !defined(__IOWPA_H__)
+#include "iowpa.h"
+#endif
+
+#include <linux/delay.h>
+#include <linux/kthread.h>
+// #ifdef PRIVATE_OBJ
+//#if !defined(__DEVICE_EXP_H)
+//#include "device_exp.h"
+//#endif
+//#if !defined(__DEVICE_MODULE_H)
+//#include "device_module.h"
+//#endif
+
+
+// #endif
+//#define	DEBUG
+/*---------------------  Static Definitions -------------------------*/
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+static int          msglevel                =   MSG_LEVEL_INFO;
+
+//#define	PLICE_DEBUG
+//
+// Define module options
+//
+#ifndef PRIVATE_OBJ
+MODULE_AUTHOR("VIA Networking Technologies, Inc., <lyndonchen@vntek.com.tw>");
+MODULE_LICENSE("GPL");
+MODULE_DESCRIPTION("VIA Networking Solomon-A/B/G Wireless LAN Adapter Driver");
+#endif
+
+//PLICE_DEBUG ->
+	static int mlme_kill;
+	//static  struct task_struct * mlme_task;
+//PLICE_DEBUG <-
+
+#define DEVICE_PARAM(N,D)
+/*
+        static const int N[MAX_UINTS]=OPTION_DEFAULT;\
+        MODULE_PARM(N, "1-" __MODULE_STRING(MAX_UINTS) "i");\
+        MODULE_PARM_DESC(N, D);
+*/
+
+#define RX_DESC_MIN0     16
+#define RX_DESC_MAX0     128
+#define RX_DESC_DEF0     32
+DEVICE_PARAM(RxDescriptors0,"Number of receive descriptors0");
+
+#define RX_DESC_MIN1     16
+#define RX_DESC_MAX1     128
+#define RX_DESC_DEF1     32
+DEVICE_PARAM(RxDescriptors1,"Number of receive descriptors1");
+
+#define TX_DESC_MIN0     16
+#define TX_DESC_MAX0     128
+#define TX_DESC_DEF0     32
+DEVICE_PARAM(TxDescriptors0,"Number of transmit descriptors0");
+
+#define TX_DESC_MIN1     16
+#define TX_DESC_MAX1     128
+#define TX_DESC_DEF1     64
+DEVICE_PARAM(TxDescriptors1,"Number of transmit descriptors1");
+
+
+#define IP_ALIG_DEF     0
+/* IP_byte_align[] is used for IP header DWORD byte aligned
+   0: indicate the IP header won't be DWORD byte aligned.(Default) .
+   1: indicate the IP header will be DWORD byte aligned.
+      In some enviroment, the IP header should be DWORD byte aligned,
+      or the packet will be droped when we receive it. (eg: IPVS)
+*/
+DEVICE_PARAM(IP_byte_align,"Enable IP header dword aligned");
+
+
+#define INT_WORKS_DEF   20
+#define INT_WORKS_MIN   10
+#define INT_WORKS_MAX   64
+
+DEVICE_PARAM(int_works,"Number of packets per interrupt services");
+
+#define CHANNEL_MIN     1
+#define CHANNEL_MAX     14
+#define CHANNEL_DEF     6
+
+DEVICE_PARAM(Channel, "Channel number");
+
+
+/* PreambleType[] is the preamble length used for transmit.
+   0: indicate allows long preamble type
+   1: indicate allows short preamble type
+*/
+
+#define PREAMBLE_TYPE_DEF     1
+
+DEVICE_PARAM(PreambleType, "Preamble Type");
+
+
+#define RTS_THRESH_MIN     512
+#define RTS_THRESH_MAX     2347
+#define RTS_THRESH_DEF     2347
+
+DEVICE_PARAM(RTSThreshold, "RTS threshold");
+
+
+#define FRAG_THRESH_MIN     256
+#define FRAG_THRESH_MAX     2346
+#define FRAG_THRESH_DEF     2346
+
+DEVICE_PARAM(FragThreshold, "Fragmentation threshold");
+
+
+#define DATA_RATE_MIN     0
+#define DATA_RATE_MAX     13
+#define DATA_RATE_DEF     13
+/* datarate[] index
+   0: indicate 1 Mbps   0x02
+   1: indicate 2 Mbps   0x04
+   2: indicate 5.5 Mbps 0x0B
+   3: indicate 11 Mbps  0x16
+   4: indicate 6 Mbps   0x0c
+   5: indicate 9 Mbps   0x12
+   6: indicate 12 Mbps  0x18
+   7: indicate 18 Mbps  0x24
+   8: indicate 24 Mbps  0x30
+   9: indicate 36 Mbps  0x48
+  10: indicate 48 Mbps  0x60
+  11: indicate 54 Mbps  0x6c
+  12: indicate 72 Mbps  0x90
+  13: indicate auto rate
+*/
+
+DEVICE_PARAM(ConnectionRate, "Connection data rate");
+
+#define OP_MODE_DEF     0
+
+DEVICE_PARAM(OPMode, "Infrastruct, adhoc, AP mode ");
+
+/* OpMode[] is used for transmit.
+   0: indicate infrastruct mode used
+   1: indicate adhoc mode used
+   2: indicate AP mode used
+*/
+
+
+/* PSMode[]
+   0: indicate disable power saving mode
+   1: indicate enable power saving mode
+*/
+
+#define PS_MODE_DEF     0
+
+DEVICE_PARAM(PSMode, "Power saving mode");
+
+
+#define SHORT_RETRY_MIN     0
+#define SHORT_RETRY_MAX     31
+#define SHORT_RETRY_DEF     8
+
+
+DEVICE_PARAM(ShortRetryLimit, "Short frame retry limits");
+
+#define LONG_RETRY_MIN     0
+#define LONG_RETRY_MAX     15
+#define LONG_RETRY_DEF     4
+
+
+DEVICE_PARAM(LongRetryLimit, "long frame retry limits");
+
+
+/* BasebandType[] baseband type selected
+   0: indicate 802.11a type
+   1: indicate 802.11b type
+   2: indicate 802.11g type
+*/
+#define BBP_TYPE_MIN     0
+#define BBP_TYPE_MAX     2
+#define BBP_TYPE_DEF     2
+
+DEVICE_PARAM(BasebandType, "baseband type");
+
+
+
+/* 80211hEnable[]
+   0: indicate disable 802.11h
+   1: indicate enable 802.11h
+*/
+
+#define X80211h_MODE_DEF     0
+
+DEVICE_PARAM(b80211hEnable, "802.11h mode");
+
+/* 80211hEnable[]
+   0: indicate disable 802.11h
+   1: indicate enable 802.11h
+*/
+
+#define DIVERSITY_ANT_DEF     0
+
+DEVICE_PARAM(bDiversityANTEnable, "ANT diversity mode");
+
+
+//
+// Static vars definitions
+//
+
+
+#ifndef PRIVATE_OBJ
+static int          device_nics             =0;
+static PSDevice     pDevice_Infos           =NULL;
+static struct net_device *root_device_dev = NULL;
+
+static CHIP_INFO chip_info_table[]= {
+    { VT3253,       "VIA Networking Solomon-A/B/G Wireless LAN Adapter ",
+        256, 1,     DEVICE_FLAGS_IP_ALIGN|DEVICE_FLAGS_TX_ALIGN },
+    {0,NULL}
+};
+
+static struct pci_device_id device_id_table[] __devinitdata = {
+{ 0x1106, 0x3253, PCI_ANY_ID, PCI_ANY_ID, 0, 0, (int)&chip_info_table[0]},
+{ 0, }
+};
+#endif
+
+/*---------------------  Static Functions  --------------------------*/
+
+#ifndef PRIVATE_OBJ
+
+static int  device_found1(struct pci_dev *pcid, const struct pci_device_id *ent);
+static BOOL device_init_info(struct pci_dev* pcid, PSDevice* ppDevice, PCHIP_INFO);
+static void device_free_info(PSDevice pDevice);
+static BOOL device_get_pci_info(PSDevice, struct pci_dev* pcid);
+static void device_print_info(PSDevice pDevice);
+static struct net_device_stats *device_get_stats(struct net_device *dev);
+static void device_init_diversity_timer(PSDevice pDevice);
+static int  device_open(struct net_device *dev);
+static int  device_xmit(struct sk_buff *skb, struct net_device *dev);
+static  irqreturn_t  device_intr(int irq,  void*dev_instance);
+static void device_set_multi(struct net_device *dev);
+static int  device_close(struct net_device *dev);
+static int  device_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
+
+#ifdef CONFIG_PM
+static int device_notify_reboot(struct notifier_block *, unsigned long event, void *ptr);
+static int viawget_suspend(struct pci_dev *pcid, u32 state);
+static int viawget_resume(struct pci_dev *pcid);
+struct notifier_block device_notifier = {
+        notifier_call:  device_notify_reboot,
+        next:           NULL,
+        priority:       0
+};
+#endif
+
+#endif // #ifndef PRIVATE_OBJ
+
+static void device_init_rd0_ring(PSDevice pDevice);
+static void device_init_rd1_ring(PSDevice pDevice);
+static void device_init_defrag_cb(PSDevice pDevice);
+static void device_init_td0_ring(PSDevice pDevice);
+static void device_init_td1_ring(PSDevice pDevice);
+
+#ifndef PRIVATE_OBJ
+static int  device_dma0_tx_80211(struct sk_buff *skb, struct net_device *dev);
+#endif
+//2008-0714<Add>by Mike Liu
+static BOOL device_release_WPADEV(PSDevice pDevice);
+
+static int  ethtool_ioctl(struct net_device *dev, void *useraddr);
+static int  device_rx_srv(PSDevice pDevice, UINT uIdx);
+static int  device_tx_srv(PSDevice pDevice, UINT uIdx);
+static BOOL device_alloc_rx_buf(PSDevice pDevice, PSRxDesc pDesc);
+static void device_init_registers(PSDevice pDevice, DEVICE_INIT_TYPE InitType);
+static void device_free_tx_buf(PSDevice pDevice, PSTxDesc pDesc);
+static void device_free_td0_ring(PSDevice pDevice);
+static void device_free_td1_ring(PSDevice pDevice);
+static void device_free_rd0_ring(PSDevice pDevice);
+static void device_free_rd1_ring(PSDevice pDevice);
+static void device_free_rings(PSDevice pDevice);
+static void device_free_frag_buf(PSDevice pDevice);
+static int Config_FileGetParameter(UCHAR *string, UCHAR *dest,UCHAR *source);
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+#ifndef PRIVATE_OBJ
+
+static char* get_chip_name(int chip_id) {
+    int i;
+    for (i=0;chip_info_table[i].name!=NULL;i++)
+        if (chip_info_table[i].chip_id==chip_id)
+            break;
+    return chip_info_table[i].name;
+}
+
+static void __devexit device_remove1(struct pci_dev *pcid)
+{
+    PSDevice pDevice=pci_get_drvdata(pcid);
+
+    if (pDevice==NULL)
+        return;
+    device_free_info(pDevice);
+
+}
+
+#endif
+/*
+static void
+device_set_int_opt(int *opt, int val, int min, int max, int def,char* name,char* devname) {
+    if (val==-1)
+        *opt=def;
+    else if (val<min || val>max) {
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_NOTICE "%s: the value of parameter %s is invalid, the valid range is (%d-%d)\n" ,
+            devname,name, min,max);
+        *opt=def;
+    } else {
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "%s: set value of parameter %s to %d\n",
+            devname, name, val);
+        *opt=val;
+    }
+}
+
+static void
+device_set_bool_opt(PU32 opt, int val,BOOL def,U32 flag, char* name,char* devname) {
+    (*opt)&=(~flag);
+    if (val==-1)
+        *opt|=(def ? flag : 0);
+    else if (val<0 || val>1) {
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_NOTICE
+            "%s: the value of parameter %s is invalid, the valid range is (0-1)\n",devname,name);
+        *opt|=(def ? flag : 0);
+    } else {
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_NOTICE "%s: set parameter %s to %s\n",
+            devname,name , val ? "TRUE" : "FALSE");
+        *opt|=(val ? flag : 0);
+    }
+}
+*/
+static void
+device_get_options(PSDevice pDevice, int index, char* devname) {
+
+    POPTIONS pOpts = &(pDevice->sOpts);
+  pOpts->nRxDescs0=RX_DESC_DEF0;
+  pOpts->nRxDescs1=RX_DESC_DEF1;
+  pOpts->nTxDescs[0]=TX_DESC_DEF0;
+  pOpts->nTxDescs[1]=TX_DESC_DEF1;
+pOpts->flags|=DEVICE_FLAGS_IP_ALIGN;
+  pOpts->int_works=INT_WORKS_DEF;
+  pOpts->rts_thresh=RTS_THRESH_DEF;
+  pOpts->frag_thresh=FRAG_THRESH_DEF;
+  pOpts->data_rate=DATA_RATE_DEF;
+  pOpts->channel_num=CHANNEL_DEF;
+
+pOpts->flags|=DEVICE_FLAGS_PREAMBLE_TYPE;
+pOpts->flags|=DEVICE_FLAGS_OP_MODE;
+//pOpts->flags|=DEVICE_FLAGS_PS_MODE;
+  pOpts->short_retry=SHORT_RETRY_DEF;
+  pOpts->long_retry=LONG_RETRY_DEF;
+  pOpts->bbp_type=BBP_TYPE_DEF;
+pOpts->flags|=DEVICE_FLAGS_80211h_MODE;
+pOpts->flags|=DEVICE_FLAGS_DiversityANT;
+
+
+}
+
+static void
+device_set_options(PSDevice pDevice) {
+
+    BYTE    abyBroadcastAddr[U_ETHER_ADDR_LEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
+    BYTE    abySNAP_RFC1042[U_ETHER_ADDR_LEN] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00};
+    BYTE    abySNAP_Bridgetunnel[U_ETHER_ADDR_LEN] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0xF8};
+
+
+    memcpy(pDevice->abyBroadcastAddr, abyBroadcastAddr, U_ETHER_ADDR_LEN);
+    memcpy(pDevice->abySNAP_RFC1042, abySNAP_RFC1042, U_ETHER_ADDR_LEN);
+    memcpy(pDevice->abySNAP_Bridgetunnel, abySNAP_Bridgetunnel, U_ETHER_ADDR_LEN);
+
+    pDevice->uChannel = pDevice->sOpts.channel_num;
+    pDevice->wRTSThreshold = pDevice->sOpts.rts_thresh;
+    pDevice->wFragmentationThreshold = pDevice->sOpts.frag_thresh;
+    pDevice->byShortRetryLimit = pDevice->sOpts.short_retry;
+    pDevice->byLongRetryLimit = pDevice->sOpts.long_retry;
+    pDevice->wMaxTransmitMSDULifetime = DEFAULT_MSDU_LIFETIME;
+    pDevice->byShortPreamble = (pDevice->sOpts.flags & DEVICE_FLAGS_PREAMBLE_TYPE) ? 1 : 0;
+    pDevice->byOpMode = (pDevice->sOpts.flags & DEVICE_FLAGS_OP_MODE) ? 1 : 0;
+    pDevice->ePSMode = (pDevice->sOpts.flags & DEVICE_FLAGS_PS_MODE) ? 1 : 0;
+    pDevice->b11hEnable = (pDevice->sOpts.flags & DEVICE_FLAGS_80211h_MODE) ? 1 : 0;
+    pDevice->bDiversityRegCtlON = (pDevice->sOpts.flags & DEVICE_FLAGS_DiversityANT) ? 1 : 0;
+    pDevice->uConnectionRate = pDevice->sOpts.data_rate;
+    if (pDevice->uConnectionRate < RATE_AUTO) pDevice->bFixRate = TRUE;
+    pDevice->byBBType = pDevice->sOpts.bbp_type;
+    pDevice->byPacketType = pDevice->byBBType;
+
+//PLICE_DEBUG->
+	pDevice->byAutoFBCtrl = AUTO_FB_0;
+	//pDevice->byAutoFBCtrl = AUTO_FB_1;
+//PLICE_DEBUG<-
+pDevice->bUpdateBBVGA = TRUE;
+    pDevice->byFOETuning = 0;
+    pDevice->wCTSDuration = 0;
+    pDevice->byPreambleType = 0;
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" uChannel= %d\n",(INT)pDevice->uChannel);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byOpMode= %d\n",(INT)pDevice->byOpMode);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" ePSMode= %d\n",(INT)pDevice->ePSMode);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" wRTSThreshold= %d\n",(INT)pDevice->wRTSThreshold);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byShortRetryLimit= %d\n",(INT)pDevice->byShortRetryLimit);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byLongRetryLimit= %d\n",(INT)pDevice->byLongRetryLimit);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byPreambleType= %d\n",(INT)pDevice->byPreambleType);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byShortPreamble= %d\n",(INT)pDevice->byShortPreamble);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" uConnectionRate= %d\n",(INT)pDevice->uConnectionRate);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byBBType= %d\n",(INT)pDevice->byBBType);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->b11hEnable= %d\n",(INT)pDevice->b11hEnable);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->bDiversityRegCtlON= %d\n",(INT)pDevice->bDiversityRegCtlON);
+}
+
+static VOID s_vCompleteCurrentMeasure (IN PSDevice pDevice, IN BYTE byResult)
+{
+    UINT    ii;
+    DWORD   dwDuration = 0;
+    BYTE    byRPI0 = 0;
+
+    for(ii=1;ii<8;ii++) {
+        pDevice->dwRPIs[ii] *= 255;
+        dwDuration |= *((PWORD) (pDevice->pCurrMeasureEID->sReq.abyDuration));
+        dwDuration <<= 10;
+        pDevice->dwRPIs[ii] /= dwDuration;
+        pDevice->abyRPIs[ii] = (BYTE) pDevice->dwRPIs[ii];
+        byRPI0 += pDevice->abyRPIs[ii];
+    }
+    pDevice->abyRPIs[0] = (0xFF - byRPI0);
+
+     if (pDevice->uNumOfMeasureEIDs == 0) {
+        VNTWIFIbMeasureReport(  pDevice->pMgmt,
+                                TRUE,
+                                pDevice->pCurrMeasureEID,
+                                byResult,
+                                pDevice->byBasicMap,
+                                pDevice->byCCAFraction,
+                                pDevice->abyRPIs
+                                );
+    } else {
+        VNTWIFIbMeasureReport(  pDevice->pMgmt,
+                                FALSE,
+                                pDevice->pCurrMeasureEID,
+                                byResult,
+                                pDevice->byBasicMap,
+                                pDevice->byCCAFraction,
+                                pDevice->abyRPIs
+                                );
+        CARDbStartMeasure (pDevice, pDevice->pCurrMeasureEID++, pDevice->uNumOfMeasureEIDs);
+    }
+
+}
+
+
+
+//
+// Initialiation of MAC & BBP registers
+//
+
+static void device_init_registers(PSDevice pDevice, DEVICE_INIT_TYPE InitType)
+{
+    UINT    ii;
+    BYTE    byValue;
+	BYTE    byValue1;
+    BYTE    byCCKPwrdBm = 0;
+    BYTE    byOFDMPwrdBm = 0;
+    INT zonetype=0;
+     PSMgmtObject    pMgmt = &(pDevice->sMgmtObj);
+    MACbShutdown(pDevice->PortOffset);
+    BBvSoftwareReset(pDevice->PortOffset);
+
+    if ((InitType == DEVICE_INIT_COLD) ||
+        (InitType == DEVICE_INIT_DXPL)) {
+        // Do MACbSoftwareReset in MACvInitialize
+        MACbSoftwareReset(pDevice->PortOffset);
+        // force CCK
+        pDevice->bCCK = TRUE;
+        pDevice->bAES = FALSE;
+        pDevice->bProtectMode = FALSE;      //Only used in 11g type, sync with ERP IE
+        pDevice->bNonERPPresent = FALSE;
+        pDevice->bBarkerPreambleMd = FALSE;
+        pDevice->wCurrentRate = RATE_1M;
+        pDevice->byTopOFDMBasicRate = RATE_24M;
+        pDevice->byTopCCKBasicRate = RATE_1M;
+
+        pDevice->byRevId = 0;                   //Target to IF pin while programming to RF chip.
+
+        // init MAC
+        MACvInitialize(pDevice->PortOffset);
+
+        // Get Local ID
+        VNSvInPortB(pDevice->PortOffset + MAC_REG_LOCALID, &(pDevice->byLocalID));
+
+           spin_lock_irq(&pDevice->lock);
+	 SROMvReadAllContents(pDevice->PortOffset,pDevice->abyEEPROM);
+
+           spin_unlock_irq(&pDevice->lock);
+
+        // Get Channel range
+
+        pDevice->byMinChannel = 1;
+        pDevice->byMaxChannel = CB_MAX_CHANNEL;
+
+        // Get Antena
+        byValue = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_ANTENNA);
+        if (byValue & EEP_ANTINV)
+            pDevice->bTxRxAntInv = TRUE;
+        else
+            pDevice->bTxRxAntInv = FALSE;
+#ifdef	PLICE_DEBUG
+	//printk("init_register:TxRxAntInv is %d,byValue is %d\n",pDevice->bTxRxAntInv,byValue);
+#endif
+
+        byValue &= (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN);
+        if (byValue == 0) // if not set default is All
+            byValue = (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN);
+#ifdef	PLICE_DEBUG
+	//printk("init_register:byValue is %d\n",byValue);
+#endif
+        pDevice->ulDiversityNValue = 100*260;//100*SROMbyReadEmbedded(pDevice->PortOffset, 0x51);
+        pDevice->ulDiversityMValue = 100*16;//SROMbyReadEmbedded(pDevice->PortOffset, 0x52);
+        pDevice->byTMax = 1;//SROMbyReadEmbedded(pDevice->PortOffset, 0x53);
+        pDevice->byTMax2 = 4;//SROMbyReadEmbedded(pDevice->PortOffset, 0x54);
+        pDevice->ulSQ3TH = 0;//(ULONG) SROMbyReadEmbedded(pDevice->PortOffset, 0x55);
+        pDevice->byTMax3 = 64;//SROMbyReadEmbedded(pDevice->PortOffset, 0x56);
+
+        if (byValue == (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN)) {
+            pDevice->byAntennaCount = 2;
+            pDevice->byTxAntennaMode = ANT_B;
+            pDevice->dwTxAntennaSel = 1;
+            pDevice->dwRxAntennaSel = 1;
+            if (pDevice->bTxRxAntInv == TRUE)
+                pDevice->byRxAntennaMode = ANT_A;
+            else
+                pDevice->byRxAntennaMode = ANT_B;
+                // chester for antenna
+byValue1 = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_ANTENNA);
+          //  if (pDevice->bDiversityRegCtlON)
+          if((byValue1&0x08)==0)
+                pDevice->bDiversityEnable = FALSE;//SROMbyReadEmbedded(pDevice->PortOffset, 0x50);
+            else
+                pDevice->bDiversityEnable = TRUE;
+#ifdef	PLICE_DEBUG
+		//printk("aux |main antenna: RxAntennaMode is %d\n",pDevice->byRxAntennaMode);
+#endif
+	} else  {
+            pDevice->bDiversityEnable = FALSE;
+            pDevice->byAntennaCount = 1;
+            pDevice->dwTxAntennaSel = 0;
+            pDevice->dwRxAntennaSel = 0;
+            if (byValue & EEP_ANTENNA_AUX) {
+                pDevice->byTxAntennaMode = ANT_A;
+                if (pDevice->bTxRxAntInv == TRUE)
+                    pDevice->byRxAntennaMode = ANT_B;
+                else
+                    pDevice->byRxAntennaMode = ANT_A;
+            } else {
+                pDevice->byTxAntennaMode = ANT_B;
+                if (pDevice->bTxRxAntInv == TRUE)
+                    pDevice->byRxAntennaMode = ANT_A;
+                else
+                    pDevice->byRxAntennaMode = ANT_B;
+            }
+        }
+#ifdef	PLICE_DEBUG
+	//printk("init registers: TxAntennaMode is %d\n",pDevice->byTxAntennaMode);
+#endif
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "bDiversityEnable=[%d],NValue=[%d],MValue=[%d],TMax=[%d],TMax2=[%d]\n",
+            pDevice->bDiversityEnable,(int)pDevice->ulDiversityNValue,(int)pDevice->ulDiversityMValue,pDevice->byTMax,pDevice->byTMax2);
+
+//#ifdef ZoneType_DefaultSetting
+//2008-8-4 <add> by chester
+//zonetype initial
+ pDevice->byOriginalZonetype = pDevice->abyEEPROM[EEP_OFS_ZONETYPE];
+ if((zonetype=Config_FileOperation(pDevice,FALSE,NULL)) >= 0) {         //read zonetype file ok!
+  if ((zonetype == 0)&&
+        (pDevice->abyEEPROM[EEP_OFS_ZONETYPE] !=0x00)){          //for USA
+    pDevice->abyEEPROM[EEP_OFS_ZONETYPE] = 0;
+    pDevice->abyEEPROM[EEP_OFS_MAXCHANNEL] = 0x0B;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Init Zone Type :USA\n");
+  }
+ else if((zonetype == 1)&&
+ 	     (pDevice->abyEEPROM[EEP_OFS_ZONETYPE]!=0x01)){   //for Japan
+    pDevice->abyEEPROM[EEP_OFS_ZONETYPE] = 0x01;
+    pDevice->abyEEPROM[EEP_OFS_MAXCHANNEL] = 0x0D;
+  }
+ else if((zonetype == 2)&&
+ 	     (pDevice->abyEEPROM[EEP_OFS_ZONETYPE]!=0x02)){   //for Europe
+    pDevice->abyEEPROM[EEP_OFS_ZONETYPE] = 0x02;
+    pDevice->abyEEPROM[EEP_OFS_MAXCHANNEL] = 0x0D;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Init Zone Type :Europe\n");
+  }
+
+else
+{
+   if(zonetype!=pDevice->abyEEPROM[EEP_OFS_ZONETYPE])
+      printk("zonetype in file[%02x] mismatch with in EEPROM[%02x]\n",zonetype,pDevice->abyEEPROM[EEP_OFS_ZONETYPE]);
+   else
+      printk("Read Zonetype file sucess,use default zonetype setting[%02x]\n",zonetype);
+ }
+ 	}
+  else
+    printk("Read Zonetype file fail,use default zonetype setting[%02x]\n",SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_ZONETYPE));
+
+        // Get RFType
+        pDevice->byRFType = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_RFTYPE);
+
+        if ((pDevice->byRFType & RF_EMU) != 0) {
+            // force change RevID for VT3253 emu
+            pDevice->byRevId = 0x80;
+        }
+
+        pDevice->byRFType &= RF_MASK;
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->byRFType = %x\n", pDevice->byRFType);
+
+        if (pDevice->bZoneRegExist == FALSE) {
+            pDevice->byZoneType = pDevice->abyEEPROM[EEP_OFS_ZONETYPE];
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->byZoneType = %x\n", pDevice->byZoneType);
+
+        //Init RF module
+        RFbInit(pDevice);
+
+        //Get Desire Power Value
+        pDevice->byCurPwr = 0xFF;
+        pDevice->byCCKPwr = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_PWR_CCK);
+        pDevice->byOFDMPwrG = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_PWR_OFDMG);
+        //byCCKPwrdBm = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_CCK_PWR_dBm);
+
+	//byOFDMPwrdBm = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_OFDM_PWR_dBm);
+//printk("CCKPwrdBm is 0x%x,byOFDMPwrdBm is 0x%x\n",byCCKPwrdBm,byOFDMPwrdBm);
+		// Load power Table
+
+
+        for (ii=0;ii<CB_MAX_CHANNEL_24G;ii++) {
+            pDevice->abyCCKPwrTbl[ii+1] = SROMbyReadEmbedded(pDevice->PortOffset, (BYTE)(ii + EEP_OFS_CCK_PWR_TBL));
+            if (pDevice->abyCCKPwrTbl[ii+1] == 0) {
+                pDevice->abyCCKPwrTbl[ii+1] = pDevice->byCCKPwr;
+            }
+            pDevice->abyOFDMPwrTbl[ii+1] = SROMbyReadEmbedded(pDevice->PortOffset, (BYTE)(ii + EEP_OFS_OFDM_PWR_TBL));
+            if (pDevice->abyOFDMPwrTbl[ii+1] == 0) {
+                pDevice->abyOFDMPwrTbl[ii+1] = pDevice->byOFDMPwrG;
+            }
+            pDevice->abyCCKDefaultPwr[ii+1] = byCCKPwrdBm;
+            pDevice->abyOFDMDefaultPwr[ii+1] = byOFDMPwrdBm;
+        }
+		//2008-8-4 <add> by chester
+	  //recover 12,13 ,14channel for EUROPE by 11 channel
+          if(((pDevice->abyEEPROM[EEP_OFS_ZONETYPE] == ZoneType_Japan) ||
+	        (pDevice->abyEEPROM[EEP_OFS_ZONETYPE] == ZoneType_Europe))&&
+	     (pDevice->byOriginalZonetype == ZoneType_USA)) {
+	    for(ii=11;ii<14;ii++) {
+                pDevice->abyCCKPwrTbl[ii] = pDevice->abyCCKPwrTbl[10];
+	       pDevice->abyOFDMPwrTbl[ii] = pDevice->abyOFDMPwrTbl[10];
+
+	    }
+	  }
+
+
+        // Load OFDM A Power Table
+        for (ii=0;ii<CB_MAX_CHANNEL_5G;ii++) { //RobertYu:20041224, bug using CB_MAX_CHANNEL
+            pDevice->abyOFDMPwrTbl[ii+CB_MAX_CHANNEL_24G+1] = SROMbyReadEmbedded(pDevice->PortOffset, (BYTE)(ii + EEP_OFS_OFDMA_PWR_TBL));
+            pDevice->abyOFDMDefaultPwr[ii+CB_MAX_CHANNEL_24G+1] = SROMbyReadEmbedded(pDevice->PortOffset, (BYTE)(ii + EEP_OFS_OFDMA_PWR_dBm));
+        }
+        CARDvInitChannelTable((PVOID)pDevice);
+
+
+        if (pDevice->byLocalID > REV_ID_VT3253_B1) {
+            MACvSelectPage1(pDevice->PortOffset);
+            VNSvOutPortB(pDevice->PortOffset + MAC_REG_MSRCTL + 1, (MSRCTL1_TXPWR | MSRCTL1_CSAPAREN));
+            MACvSelectPage0(pDevice->PortOffset);
+        }
+
+
+         // use relative tx timeout and 802.11i D4
+        MACvWordRegBitsOn(pDevice->PortOffset, MAC_REG_CFG, (CFG_TKIPOPT | CFG_NOTXTIMEOUT));
+
+        // set performance parameter by registry
+        MACvSetShortRetryLimit(pDevice->PortOffset, pDevice->byShortRetryLimit);
+        MACvSetLongRetryLimit(pDevice->PortOffset, pDevice->byLongRetryLimit);
+
+        // reset TSF counter
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_TFTCTL, TFTCTL_TSFCNTRST);
+        // enable TSF counter
+        VNSvOutPortB(pDevice->PortOffset + MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
+
+        // initialize BBP registers
+        BBbVT3253Init(pDevice);
+
+        if (pDevice->bUpdateBBVGA) {
+            pDevice->byBBVGACurrent = pDevice->abyBBVGA[0];
+            pDevice->byBBVGANew = pDevice->byBBVGACurrent;
+            BBvSetVGAGainOffset(pDevice, pDevice->abyBBVGA[0]);
+        }
+#ifdef	PLICE_DEBUG
+	//printk("init registers:RxAntennaMode is %x,TxAntennaMode is %x\n",pDevice->byRxAntennaMode,pDevice->byTxAntennaMode);
+#endif
+        BBvSetRxAntennaMode(pDevice->PortOffset, pDevice->byRxAntennaMode);
+        BBvSetTxAntennaMode(pDevice->PortOffset, pDevice->byTxAntennaMode);
+
+        pDevice->byCurrentCh = 0;
+
+        //pDevice->NetworkType = Ndis802_11Automode;
+        // Set BB and packet type at the same time.
+        // Set Short Slot Time, xIFS, and RSPINF.
+        if (pDevice->uConnectionRate == RATE_AUTO) {
+            pDevice->wCurrentRate = RATE_54M;
+        } else {
+            pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
+        }
+
+        // default G Mode
+        VNTWIFIbConfigPhyMode(pDevice->pMgmt, PHY_TYPE_11G);
+        VNTWIFIbConfigPhyMode(pDevice->pMgmt, PHY_TYPE_AUTO);
+
+        pDevice->bRadioOff = FALSE;
+
+        pDevice->byRadioCtl = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_RADIOCTL);
+        pDevice->bHWRadioOff = FALSE;
+
+        if (pDevice->byRadioCtl & EEP_RADIOCTL_ENABLE) {
+            // Get GPIO
+            MACvGPIOIn(pDevice->PortOffset, &pDevice->byGPIO);
+//2008-4-14 <add> by chester for led issue
+ #ifdef FOR_LED_ON_NOTEBOOK
+if (BITbIsBitOn(pDevice->byGPIO,GPIO0_DATA)){pDevice->bHWRadioOff = TRUE;}
+if (BITbIsBitOff(pDevice->byGPIO,GPIO0_DATA)){pDevice->bHWRadioOff = FALSE;}
+
+            }
+        if ( (pDevice->bRadioControlOff == TRUE)) {
+            CARDbRadioPowerOff(pDevice);
+        }
+else  CARDbRadioPowerOn(pDevice);
+#else
+            if ((BITbIsBitOn(pDevice->byGPIO,GPIO0_DATA) && BITbIsBitOff(pDevice->byRadioCtl, EEP_RADIOCTL_INV)) ||
+                (BITbIsBitOff(pDevice->byGPIO,GPIO0_DATA) && BITbIsBitOn(pDevice->byRadioCtl, EEP_RADIOCTL_INV))) {
+                pDevice->bHWRadioOff = TRUE;
+            }
+        }
+        if ((pDevice->bHWRadioOff == TRUE) || (pDevice->bRadioControlOff == TRUE)) {
+            CARDbRadioPowerOff(pDevice);
+        }
+
+#endif
+    }
+            pMgmt->eScanType = WMAC_SCAN_PASSIVE;
+    // get Permanent network address
+    SROMvReadEtherAddress(pDevice->PortOffset, pDevice->abyCurrentNetAddr);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Network address = %02x-%02x-%02x=%02x-%02x-%02x\n",
+        pDevice->abyCurrentNetAddr[0],
+        pDevice->abyCurrentNetAddr[1],
+        pDevice->abyCurrentNetAddr[2],
+        pDevice->abyCurrentNetAddr[3],
+        pDevice->abyCurrentNetAddr[4],
+        pDevice->abyCurrentNetAddr[5]);
+
+
+    // reset Tx pointer
+    CARDvSafeResetRx(pDevice);
+    // reset Rx pointer
+    CARDvSafeResetTx(pDevice);
+
+    if (pDevice->byLocalID <= REV_ID_VT3253_A1) {
+        MACvRegBitsOn(pDevice->PortOffset, MAC_REG_RCR, RCR_WPAERR);
+    }
+
+    pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
+
+    // Turn On Rx DMA
+    MACvReceive0(pDevice->PortOffset);
+    MACvReceive1(pDevice->PortOffset);
+
+    // start the adapter
+    MACvStart(pDevice->PortOffset);
+
+    netif_stop_queue(pDevice->dev);
+
+
+}
+
+
+
+static VOID device_init_diversity_timer(PSDevice pDevice) {
+
+    init_timer(&pDevice->TimerSQ3Tmax1);
+    pDevice->TimerSQ3Tmax1.data = (ULONG)pDevice;
+    pDevice->TimerSQ3Tmax1.function = (TimerFunction)TimerSQ3CallBack;
+    pDevice->TimerSQ3Tmax1.expires = RUN_AT(HZ);
+
+    init_timer(&pDevice->TimerSQ3Tmax2);
+    pDevice->TimerSQ3Tmax2.data = (ULONG)pDevice;
+    pDevice->TimerSQ3Tmax2.function = (TimerFunction)TimerSQ3CallBack;
+    pDevice->TimerSQ3Tmax2.expires = RUN_AT(HZ);
+
+    init_timer(&pDevice->TimerSQ3Tmax3);
+    pDevice->TimerSQ3Tmax3.data = (ULONG)pDevice;
+    pDevice->TimerSQ3Tmax3.function = (TimerFunction)TimerState1CallBack;
+    pDevice->TimerSQ3Tmax3.expires = RUN_AT(HZ);
+
+    return;
+}
+
+
+static BOOL device_release_WPADEV(PSDevice pDevice)
+{
+  viawget_wpa_header *wpahdr;
+  int ii=0;
+ // wait_queue_head_t	Set_wait;
+  //send device close to wpa_supplicnat layer
+    if (pDevice->bWPADEVUp==TRUE) {
+                 wpahdr = (viawget_wpa_header *)pDevice->skb->data;
+                 wpahdr->type = VIAWGET_DEVICECLOSE_MSG;
+                 wpahdr->resp_ie_len = 0;
+                 wpahdr->req_ie_len = 0;
+                 skb_put(pDevice->skb, sizeof(viawget_wpa_header));
+                 pDevice->skb->dev = pDevice->wpadev;
+                 pDevice->skb->mac_header = pDevice->skb->data;
+                 pDevice->skb->pkt_type = PACKET_HOST;
+                 pDevice->skb->protocol = htons(ETH_P_802_2);
+                 memset(pDevice->skb->cb, 0, sizeof(pDevice->skb->cb));
+                 netif_rx(pDevice->skb);
+                 pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
+
+ //wait release WPADEV
+              //    init_waitqueue_head(&Set_wait);
+              //    wait_event_timeout(Set_wait, ((pDevice->wpadev==NULL)&&(pDevice->skb == NULL)),5*HZ);    //1s wait
+              while((pDevice->bWPADEVUp==TRUE)) {
+	        set_current_state(TASK_UNINTERRUPTIBLE);
+                 schedule_timeout (HZ/20);          //wait 50ms
+                 ii++;
+	        if(ii>20)
+		  break;
+              }
+           };
+    return TRUE;
+}
+
+
+static const struct net_device_ops device_netdev_ops = {
+    .ndo_open               = device_open,
+    .ndo_stop               = device_close,
+    .ndo_do_ioctl           = device_ioctl,
+    .ndo_get_stats          = device_get_stats,
+    .ndo_start_xmit         = device_xmit,
+    .ndo_set_multicast_list = device_set_multi,
+};
+
+
+#ifndef PRIVATE_OBJ
+
+static int
+device_found1(struct pci_dev *pcid, const struct pci_device_id *ent)
+{
+    static BOOL bFirst = TRUE;
+    struct net_device*  dev = NULL;
+    PCHIP_INFO  pChip_info = (PCHIP_INFO)ent->driver_data;
+    PSDevice    pDevice;
+    int         rc;
+    if (device_nics ++>= MAX_UINTS) {
+        printk(KERN_NOTICE DEVICE_NAME ": already found %d NICs\n", device_nics);
+        return -ENODEV;
+    }
+
+
+    dev = alloc_etherdev(sizeof(DEVICE_INFO));
+
+    pDevice = (PSDevice) netdev_priv(dev);
+
+    if (dev == NULL) {
+        printk(KERN_ERR DEVICE_NAME ": allocate net device failed \n");
+        return -ENODEV;
+    }
+
+    // Chain it all together
+   // SET_MODULE_OWNER(dev);
+    SET_NETDEV_DEV(dev, &pcid->dev);
+
+    if (bFirst) {
+        printk(KERN_NOTICE "%s Ver. %s\n",DEVICE_FULL_DRV_NAM, DEVICE_VERSION);
+        printk(KERN_NOTICE "Copyright (c) 2003 VIA Networking Technologies, Inc.\n");
+        bFirst=FALSE;
+    }
+
+    if (!device_init_info(pcid, &pDevice, pChip_info)) {
+        return -ENOMEM;
+    }
+    pDevice->dev = dev;
+    pDevice->next_module = root_device_dev;
+    root_device_dev = dev;
+    dev->irq = pcid->irq;
+
+    if (pci_enable_device(pcid)) {
+        device_free_info(pDevice);
+        return -ENODEV;
+    }
+#ifdef	DEBUG
+	printk("Before get pci_info memaddr is %x\n",pDevice->memaddr);
+#endif
+    if (device_get_pci_info(pDevice,pcid) == FALSE) {
+        printk(KERN_ERR DEVICE_NAME ": Failed to find PCI device.\n");
+        device_free_info(pDevice);
+        return -ENODEV;
+    }
+
+#if 1
+
+#ifdef	DEBUG
+
+	//pci_read_config_byte(pcid, PCI_BASE_ADDRESS_0, &pDevice->byRevId);
+	printk("after get pci_info memaddr is %x, io addr is %x,io_size is %d\n",pDevice->memaddr,pDevice->ioaddr,pDevice->io_size);
+	{
+		int i;
+		U32			bar,len;
+		u32 address[] = {
+		PCI_BASE_ADDRESS_0,
+		PCI_BASE_ADDRESS_1,
+		PCI_BASE_ADDRESS_2,
+		PCI_BASE_ADDRESS_3,
+		PCI_BASE_ADDRESS_4,
+		PCI_BASE_ADDRESS_5,
+		0};
+		for (i=0;address[i];i++)
+		{
+			//pci_write_config_dword(pcid,address[i], 0xFFFFFFFF);
+			pci_read_config_dword(pcid, address[i], &bar);
+			printk("bar %d is %x\n",i,bar);
+			if (!bar)
+			{
+				printk("bar %d not implemented\n",i);
+				continue;
+			}
+			if (bar & PCI_BASE_ADDRESS_SPACE_IO) {
+			/* This is IO */
+
+			len = bar & (PCI_BASE_ADDRESS_IO_MASK & 0xFFFF);
+			len = len & ~(len - 1);
+
+			printk("IO space:  len in IO %x, BAR %d\n", len, i);
+			}
+			else
+			{
+				len = bar & 0xFFFFFFF0;
+				len = ~len + 1;
+
+				printk("len in MEM %x, BAR %d\n", len, i);
+			}
+		}
+	}
+#endif
+
+
+#endif
+
+#ifdef	DEBUG
+	//return  0  ;
+#endif
+    pDevice->PortOffset = (DWORD)ioremap(pDevice->memaddr & PCI_BASE_ADDRESS_MEM_MASK, pDevice->io_size);
+	//pDevice->PortOffset = (DWORD)ioremap(pDevice->ioaddr & PCI_BASE_ADDRESS_IO_MASK, pDevice->io_size);
+
+	if(pDevice->PortOffset == 0) {
+       printk(KERN_ERR DEVICE_NAME ": Failed to IO remapping ..\n");
+       device_free_info(pDevice);
+        return -ENODEV;
+    }
+
+
+
+
+    rc = pci_request_regions(pcid, DEVICE_NAME);
+    if (rc) {
+        printk(KERN_ERR DEVICE_NAME ": Failed to find PCI device\n");
+        device_free_info(pDevice);
+        return -ENODEV;
+    }
+
+    dev->base_addr = pDevice->ioaddr;
+#ifdef	PLICE_DEBUG
+	BYTE	value;
+
+	VNSvInPortB(pDevice->PortOffset+0x4F, &value);
+	printk("Before write: value is %x\n",value);
+	//VNSvInPortB(pDevice->PortOffset+0x3F, 0x00);
+	VNSvOutPortB(pDevice->PortOffset,value);
+	VNSvInPortB(pDevice->PortOffset+0x4F, &value);
+	printk("After write: value is %x\n",value);
+#endif
+
+
+
+#ifdef IO_MAP
+    pDevice->PortOffset = pDevice->ioaddr;
+#endif
+    // do reset
+    if (!MACbSoftwareReset(pDevice->PortOffset)) {
+        printk(KERN_ERR DEVICE_NAME ": Failed to access MAC hardware..\n");
+        device_free_info(pDevice);
+        return -ENODEV;
+    }
+    // initial to reload eeprom
+    MACvInitialize(pDevice->PortOffset);
+    MACvReadEtherAddress(pDevice->PortOffset, dev->dev_addr);
+
+    device_get_options(pDevice, device_nics-1, dev->name);
+    device_set_options(pDevice);
+    //Mask out the options cannot be set to the chip
+    pDevice->sOpts.flags &= pChip_info->flags;
+
+    //Enable the chip specified capbilities
+    pDevice->flags = pDevice->sOpts.flags | (pChip_info->flags & 0xFF000000UL);
+    pDevice->tx_80211 = device_dma0_tx_80211;
+    pDevice->sMgmtObj.pAdapter = (PVOID)pDevice;
+    pDevice->pMgmt = &(pDevice->sMgmtObj);
+
+    dev->irq                = pcid->irq;
+    dev->netdev_ops         = &device_netdev_ops;
+
+#ifdef WIRELESS_EXT
+//Einsn Modify for ubuntu-7.04
+//	dev->wireless_handlers->get_wireless_stats = iwctl_get_wireless_stats;
+#if WIRELESS_EXT > 12
+	dev->wireless_handlers = (struct iw_handler_def *)&iwctl_handler_def;
+//	netdev->wireless_handlers = NULL;
+#endif /* WIRELESS_EXT > 12 */
+#endif /* WIRELESS_EXT */
+
+    rc = register_netdev(dev);
+    if (rc)
+    {
+        printk(KERN_ERR DEVICE_NAME " Failed to register netdev\n");
+        device_free_info(pDevice);
+        return -ENODEV;
+    }
+//2008-07-21-01<Add>by MikeLiu
+//register wpadev
+   if(wpa_set_wpadev(pDevice, 1)!=0) {
+     printk("Fail to Register WPADEV?\n");
+        unregister_netdev(pDevice->dev);
+        free_netdev(dev);
+   }
+    device_print_info(pDevice);
+    pci_set_drvdata(pcid, pDevice);
+    return 0;
+
+}
+
+static void device_print_info(PSDevice pDevice)
+{
+    struct net_device* dev=pDevice->dev;
+
+    DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "%s: %s\n",dev->name, get_chip_name(pDevice->chip_id));
+    DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "%s: MAC=%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X",
+        dev->name,
+        dev->dev_addr[0],dev->dev_addr[1],dev->dev_addr[2],
+        dev->dev_addr[3],dev->dev_addr[4],dev->dev_addr[5]);
+#ifdef IO_MAP
+    DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO" IO=0x%lx  ",(ULONG) pDevice->ioaddr);
+    DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO" IRQ=%d \n", pDevice->dev->irq);
+#else
+    DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO" IO=0x%lx Mem=0x%lx ",(ULONG) pDevice->ioaddr,(ULONG) pDevice->PortOffset);
+    DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO" IRQ=%d \n", pDevice->dev->irq);
+#endif
+
+}
+
+static BOOL device_init_info(struct pci_dev* pcid, PSDevice* ppDevice,
+    PCHIP_INFO pChip_info) {
+
+    PSDevice p;
+
+    memset(*ppDevice,0,sizeof(DEVICE_INFO));
+
+    if (pDevice_Infos == NULL) {
+        pDevice_Infos =*ppDevice;
+    }
+    else {
+        for (p=pDevice_Infos;p->next!=NULL;p=p->next)
+            do {} while (0);
+        p->next = *ppDevice;
+        (*ppDevice)->prev = p;
+    }
+
+    (*ppDevice)->pcid = pcid;
+    (*ppDevice)->chip_id = pChip_info->chip_id;
+    (*ppDevice)->io_size = pChip_info->io_size;
+    (*ppDevice)->nTxQueues = pChip_info->nTxQueue;
+    (*ppDevice)->multicast_limit =32;
+
+    spin_lock_init(&((*ppDevice)->lock));
+
+    return TRUE;
+}
+
+static BOOL device_get_pci_info(PSDevice pDevice, struct pci_dev* pcid) {
+
+    U16 pci_cmd;
+    U8  b;
+    UINT cis_addr;
+#ifdef	PLICE_DEBUG
+	BYTE       pci_config[256];
+	BYTE	value =0x00;
+	int		ii,j;
+	U16	max_lat=0x0000;
+	memset(pci_config,0x00,256);
+#endif
+
+    pci_read_config_byte(pcid, PCI_REVISION_ID, &pDevice->byRevId);
+    pci_read_config_word(pcid, PCI_SUBSYSTEM_ID,&pDevice->SubSystemID);
+    pci_read_config_word(pcid, PCI_SUBSYSTEM_VENDOR_ID, &pDevice->SubVendorID);
+    pci_read_config_word(pcid, PCI_COMMAND, (u16 *) & (pci_cmd));
+
+    pci_set_master(pcid);
+
+    pDevice->memaddr = pci_resource_start(pcid,0);
+    pDevice->ioaddr = pci_resource_start(pcid,1);
+
+#ifdef	DEBUG
+//	pDevice->ioaddr = pci_resource_start(pcid, 0);
+//	pDevice->memaddr = pci_resource_start(pcid,1);
+#endif
+
+    cis_addr = pci_resource_start(pcid,2);
+
+    pDevice->pcid = pcid;
+
+    pci_read_config_byte(pcid, PCI_REG_COMMAND, &b);
+    pci_write_config_byte(pcid, PCI_REG_COMMAND, (b|COMMAND_BUSM));
+
+#ifdef	PLICE_DEBUG
+   	//pci_read_config_word(pcid,PCI_REG_MAX_LAT,&max_lat);
+	//printk("max lat is %x,SubSystemID is %x\n",max_lat,pDevice->SubSystemID);
+	//for (ii=0;ii<0xFF;ii++)
+	//pci_read_config_word(pcid,PCI_REG_MAX_LAT,&max_lat);
+	//max_lat  = 0x20;
+	//pci_write_config_word(pcid,PCI_REG_MAX_LAT,max_lat);
+	//pci_read_config_word(pcid,PCI_REG_MAX_LAT,&max_lat);
+	//printk("max lat is %x\n",max_lat);
+
+	for (ii=0;ii<0xFF;ii++)
+	{
+		pci_read_config_byte(pcid,ii,&value);
+		pci_config[ii] = value;
+	}
+	for (ii=0,j=1;ii<0x100;ii++,j++)
+	{
+		if (j %16 == 0)
+		{
+			printk("%x:",pci_config[ii]);
+			printk("\n");
+		}
+		else
+		{
+			printk("%x:",pci_config[ii]);
+		}
+	}
+#endif
+    return TRUE;
+}
+
+static void device_free_info(PSDevice pDevice) {
+    PSDevice         ptr;
+    struct net_device*  dev=pDevice->dev;
+
+    ASSERT(pDevice);
+//2008-0714-01<Add>by chester
+device_release_WPADEV(pDevice);
+
+//2008-07-21-01<Add>by MikeLiu
+//unregister wpadev
+   if(wpa_set_wpadev(pDevice, 0)!=0)
+     printk("unregister wpadev fail?\n");
+
+    if (pDevice_Infos==NULL)
+        return;
+
+    for (ptr=pDevice_Infos;ptr && (ptr!=pDevice);ptr=ptr->next)
+            do {} while (0);
+
+    if (ptr==pDevice) {
+        if (ptr==pDevice_Infos)
+            pDevice_Infos=ptr->next;
+        else
+            ptr->prev->next=ptr->next;
+    }
+    else {
+        DEVICE_PRT(MSG_LEVEL_ERR, KERN_ERR "info struct not found\n");
+        return;
+    }
+#ifdef HOSTAP
+    if (dev)
+        hostap_set_hostapd(pDevice, 0, 0);
+#endif
+    if (dev)
+        unregister_netdev(dev);
+
+    if (pDevice->PortOffset)
+        iounmap((PVOID)pDevice->PortOffset);
+
+    if (pDevice->pcid)
+        pci_release_regions(pDevice->pcid);
+    if (dev)
+        free_netdev(dev);
+
+    if (pDevice->pcid) {
+        pci_set_drvdata(pDevice->pcid,NULL);
+    }
+}
+#endif// ifndef PRIVATE_OBJ
+
+static BOOL device_init_rings(PSDevice pDevice) {
+    void*   vir_pool;
+
+
+    /*allocate all RD/TD rings a single pool*/
+    vir_pool = pci_alloc_consistent(pDevice->pcid,
+                    pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc) +
+                    pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc) +
+                    pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc) +
+                    pDevice->sOpts.nTxDescs[1] * sizeof(STxDesc),
+                    &pDevice->pool_dma);
+
+    if (vir_pool == NULL) {
+        DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s : allocate desc dma memory failed\n", pDevice->dev->name);
+        return FALSE;
+    }
+
+    memset(vir_pool, 0,
+            pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc) +
+            pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc) +
+            pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc) +
+            pDevice->sOpts.nTxDescs[1] * sizeof(STxDesc)
+          );
+
+    pDevice->aRD0Ring = vir_pool;
+    pDevice->aRD1Ring = vir_pool +
+                        pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc);
+
+
+    pDevice->rd0_pool_dma = pDevice->pool_dma;
+    pDevice->rd1_pool_dma = pDevice->rd0_pool_dma +
+                            pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc);
+
+    pDevice->tx0_bufs = pci_alloc_consistent(pDevice->pcid,
+                    pDevice->sOpts.nTxDescs[0] * PKT_BUF_SZ +
+                    pDevice->sOpts.nTxDescs[1] * PKT_BUF_SZ +
+                    CB_BEACON_BUF_SIZE +
+                    CB_MAX_BUF_SIZE,
+                    &pDevice->tx_bufs_dma0);
+
+    if (pDevice->tx0_bufs == NULL) {
+        DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: allocate buf dma memory failed\n", pDevice->dev->name);
+        pci_free_consistent(pDevice->pcid,
+            pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc) +
+            pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc) +
+            pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc) +
+            pDevice->sOpts.nTxDescs[1] * sizeof(STxDesc),
+            vir_pool, pDevice->pool_dma
+            );
+        return FALSE;
+    }
+
+    memset(pDevice->tx0_bufs, 0,
+           pDevice->sOpts.nTxDescs[0] * PKT_BUF_SZ +
+           pDevice->sOpts.nTxDescs[1] * PKT_BUF_SZ +
+           CB_BEACON_BUF_SIZE +
+           CB_MAX_BUF_SIZE
+          );
+
+    pDevice->td0_pool_dma = pDevice->rd1_pool_dma +
+            pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc);
+
+    pDevice->td1_pool_dma = pDevice->td0_pool_dma +
+            pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc);
+
+
+    // vir_pool: pvoid type
+    pDevice->apTD0Rings = vir_pool
+                          + pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc)
+                          + pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc);
+
+    pDevice->apTD1Rings = vir_pool
+            + pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc)
+            + pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc)
+            + pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc);
+
+
+    pDevice->tx1_bufs = pDevice->tx0_bufs +
+            pDevice->sOpts.nTxDescs[0] * PKT_BUF_SZ;
+
+
+    pDevice->tx_beacon_bufs = pDevice->tx1_bufs +
+            pDevice->sOpts.nTxDescs[1] * PKT_BUF_SZ;
+
+    pDevice->pbyTmpBuff = pDevice->tx_beacon_bufs +
+            CB_BEACON_BUF_SIZE;
+
+    pDevice->tx_bufs_dma1 = pDevice->tx_bufs_dma0 +
+            pDevice->sOpts.nTxDescs[0] * PKT_BUF_SZ;
+
+
+    pDevice->tx_beacon_dma = pDevice->tx_bufs_dma1 +
+            pDevice->sOpts.nTxDescs[1] * PKT_BUF_SZ;
+
+
+    return TRUE;
+}
+
+static void device_free_rings(PSDevice pDevice) {
+
+    pci_free_consistent(pDevice->pcid,
+            pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc) +
+            pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc) +
+            pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc) +
+            pDevice->sOpts.nTxDescs[1] * sizeof(STxDesc)
+            ,
+            pDevice->aRD0Ring, pDevice->pool_dma
+        );
+
+    if (pDevice->tx0_bufs)
+        pci_free_consistent(pDevice->pcid,
+           pDevice->sOpts.nTxDescs[0] * PKT_BUF_SZ +
+           pDevice->sOpts.nTxDescs[1] * PKT_BUF_SZ +
+           CB_BEACON_BUF_SIZE +
+           CB_MAX_BUF_SIZE,
+           pDevice->tx0_bufs, pDevice->tx_bufs_dma0
+        );
+}
+
+static void device_init_rd0_ring(PSDevice pDevice) {
+    int i;
+    dma_addr_t      curr = pDevice->rd0_pool_dma;
+    PSRxDesc        pDesc;
+
+    /* Init the RD0 ring entries */
+    for (i = 0; i < pDevice->sOpts.nRxDescs0; i ++, curr += sizeof(SRxDesc)) {
+        pDesc = &(pDevice->aRD0Ring[i]);
+        pDesc->pRDInfo = alloc_rd_info();
+        ASSERT(pDesc->pRDInfo);
+        if (!device_alloc_rx_buf(pDevice, pDesc)) {
+            DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc rx bufs\n",
+            pDevice->dev->name);
+        }
+        pDesc->next = &(pDevice->aRD0Ring[(i+1) % pDevice->sOpts.nRxDescs0]);
+        pDesc->pRDInfo->curr_desc = cpu_to_le32(curr);
+        pDesc->next_desc = cpu_to_le32(curr + sizeof(SRxDesc));
+    }
+
+    pDevice->aRD0Ring[i-1].next_desc = cpu_to_le32(pDevice->rd0_pool_dma);
+    pDevice->pCurrRD[0] = &(pDevice->aRD0Ring[0]);
+}
+
+
+static void device_init_rd1_ring(PSDevice pDevice) {
+    int i;
+    dma_addr_t      curr = pDevice->rd1_pool_dma;
+    PSRxDesc        pDesc;
+
+    /* Init the RD1 ring entries */
+    for (i = 0; i < pDevice->sOpts.nRxDescs1; i ++, curr += sizeof(SRxDesc)) {
+        pDesc = &(pDevice->aRD1Ring[i]);
+        pDesc->pRDInfo = alloc_rd_info();
+        ASSERT(pDesc->pRDInfo);
+        if (!device_alloc_rx_buf(pDevice, pDesc)) {
+            DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc rx bufs\n",
+            pDevice->dev->name);
+        }
+        pDesc->next = &(pDevice->aRD1Ring[(i+1) % pDevice->sOpts.nRxDescs1]);
+        pDesc->pRDInfo->curr_desc = cpu_to_le32(curr);
+        pDesc->next_desc = cpu_to_le32(curr + sizeof(SRxDesc));
+    }
+
+    pDevice->aRD1Ring[i-1].next_desc = cpu_to_le32(pDevice->rd1_pool_dma);
+    pDevice->pCurrRD[1] = &(pDevice->aRD1Ring[0]);
+}
+
+
+static void device_init_defrag_cb(PSDevice pDevice) {
+    int i;
+    PSDeFragControlBlock pDeF;
+
+    /* Init the fragment ctl entries */
+    for (i = 0; i < CB_MAX_RX_FRAG; i++) {
+        pDeF = &(pDevice->sRxDFCB[i]);
+        if (!device_alloc_frag_buf(pDevice, pDeF)) {
+            DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc frag bufs\n",
+                pDevice->dev->name);
+        };
+    }
+    pDevice->cbDFCB = CB_MAX_RX_FRAG;
+    pDevice->cbFreeDFCB = pDevice->cbDFCB;
+}
+
+
+
+
+static void device_free_rd0_ring(PSDevice pDevice) {
+    int i;
+
+    for (i = 0; i < pDevice->sOpts.nRxDescs0; i++) {
+        PSRxDesc        pDesc =&(pDevice->aRD0Ring[i]);
+        PDEVICE_RD_INFO  pRDInfo =pDesc->pRDInfo;
+
+        pci_unmap_single(pDevice->pcid,pRDInfo->skb_dma,
+           pDevice->rx_buf_sz, PCI_DMA_FROMDEVICE);
+
+        dev_kfree_skb(pRDInfo->skb);
+
+        kfree((PVOID)pDesc->pRDInfo);
+    }
+
+}
+
+static void device_free_rd1_ring(PSDevice pDevice) {
+    int i;
+
+
+    for (i = 0; i < pDevice->sOpts.nRxDescs1; i++) {
+        PSRxDesc        pDesc=&(pDevice->aRD1Ring[i]);
+        PDEVICE_RD_INFO  pRDInfo=pDesc->pRDInfo;
+
+        pci_unmap_single(pDevice->pcid,pRDInfo->skb_dma,
+           pDevice->rx_buf_sz, PCI_DMA_FROMDEVICE);
+
+        dev_kfree_skb(pRDInfo->skb);
+
+        kfree((PVOID)pDesc->pRDInfo);
+    }
+
+}
+
+static void device_free_frag_buf(PSDevice pDevice) {
+    PSDeFragControlBlock pDeF;
+    int i;
+
+    for (i = 0; i < CB_MAX_RX_FRAG; i++) {
+
+        pDeF = &(pDevice->sRxDFCB[i]);
+
+        if (pDeF->skb)
+            dev_kfree_skb(pDeF->skb);
+
+    }
+
+}
+
+static void device_init_td0_ring(PSDevice pDevice) {
+    int i;
+    dma_addr_t  curr;
+    PSTxDesc        pDesc;
+
+    curr = pDevice->td0_pool_dma;
+    for (i = 0; i < pDevice->sOpts.nTxDescs[0]; i++, curr += sizeof(STxDesc)) {
+        pDesc = &(pDevice->apTD0Rings[i]);
+        pDesc->pTDInfo = alloc_td_info();
+        ASSERT(pDesc->pTDInfo);
+        if (pDevice->flags & DEVICE_FLAGS_TX_ALIGN) {
+            pDesc->pTDInfo->buf = pDevice->tx0_bufs + (i)*PKT_BUF_SZ;
+            pDesc->pTDInfo->buf_dma = pDevice->tx_bufs_dma0 + (i)*PKT_BUF_SZ;
+        }
+        pDesc->next =&(pDevice->apTD0Rings[(i+1) % pDevice->sOpts.nTxDescs[0]]);
+        pDesc->pTDInfo->curr_desc = cpu_to_le32(curr);
+        pDesc->next_desc = cpu_to_le32(curr+sizeof(STxDesc));
+    }
+
+    pDevice->apTD0Rings[i-1].next_desc = cpu_to_le32(pDevice->td0_pool_dma);
+    pDevice->apTailTD[0] = pDevice->apCurrTD[0] =&(pDevice->apTD0Rings[0]);
+
+}
+
+static void device_init_td1_ring(PSDevice pDevice) {
+    int i;
+    dma_addr_t  curr;
+    PSTxDesc    pDesc;
+
+    /* Init the TD ring entries */
+    curr=pDevice->td1_pool_dma;
+    for (i = 0; i < pDevice->sOpts.nTxDescs[1]; i++, curr+=sizeof(STxDesc)) {
+        pDesc=&(pDevice->apTD1Rings[i]);
+        pDesc->pTDInfo = alloc_td_info();
+        ASSERT(pDesc->pTDInfo);
+        if (pDevice->flags & DEVICE_FLAGS_TX_ALIGN) {
+            pDesc->pTDInfo->buf=pDevice->tx1_bufs+(i)*PKT_BUF_SZ;
+            pDesc->pTDInfo->buf_dma=pDevice->tx_bufs_dma1+(i)*PKT_BUF_SZ;
+        }
+        pDesc->next=&(pDevice->apTD1Rings[(i+1) % pDevice->sOpts.nTxDescs[1]]);
+        pDesc->pTDInfo->curr_desc = cpu_to_le32(curr);
+        pDesc->next_desc = cpu_to_le32(curr+sizeof(STxDesc));
+    }
+
+    pDevice->apTD1Rings[i-1].next_desc = cpu_to_le32(pDevice->td1_pool_dma);
+    pDevice->apTailTD[1] = pDevice->apCurrTD[1] = &(pDevice->apTD1Rings[0]);
+}
+
+
+
+static void device_free_td0_ring(PSDevice pDevice) {
+    int i;
+    for (i = 0; i < pDevice->sOpts.nTxDescs[0]; i++) {
+        PSTxDesc        pDesc=&(pDevice->apTD0Rings[i]);
+        PDEVICE_TD_INFO  pTDInfo=pDesc->pTDInfo;
+
+        if (pTDInfo->skb_dma && (pTDInfo->skb_dma != pTDInfo->buf_dma))
+            pci_unmap_single(pDevice->pcid,pTDInfo->skb_dma,
+               pTDInfo->skb->len, PCI_DMA_TODEVICE);
+
+        if (pTDInfo->skb)
+            dev_kfree_skb(pTDInfo->skb);
+
+        kfree((PVOID)pDesc->pTDInfo);
+    }
+}
+
+static void device_free_td1_ring(PSDevice pDevice) {
+    int i;
+
+    for (i = 0; i < pDevice->sOpts.nTxDescs[1]; i++) {
+        PSTxDesc        pDesc=&(pDevice->apTD1Rings[i]);
+        PDEVICE_TD_INFO  pTDInfo=pDesc->pTDInfo;
+
+        if (pTDInfo->skb_dma && (pTDInfo->skb_dma != pTDInfo->buf_dma))
+            pci_unmap_single(pDevice->pcid, pTDInfo->skb_dma,
+               pTDInfo->skb->len, PCI_DMA_TODEVICE);
+
+        if (pTDInfo->skb)
+            dev_kfree_skb(pTDInfo->skb);
+
+        kfree((PVOID)pDesc->pTDInfo);
+    }
+
+}
+
+
+
+/*-----------------------------------------------------------------*/
+
+static int device_rx_srv(PSDevice pDevice, UINT uIdx) {
+    PSRxDesc    pRD;
+    int works = 0;
+
+
+    for (pRD = pDevice->pCurrRD[uIdx];
+         pRD->m_rd0RD0.f1Owner == OWNED_BY_HOST;
+         pRD = pRD->next) {
+//        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->pCurrRD = %x, works = %d\n", pRD, works);
+        if (works++>15)
+            break;
+        if (device_receive_frame(pDevice, pRD)) {
+            if (!device_alloc_rx_buf(pDevice,pRD)) {
+                    DEVICE_PRT(MSG_LEVEL_ERR, KERN_ERR
+                    "%s: can not allocate rx buf\n", pDevice->dev->name);
+                    break;
+            }
+        }
+        pRD->m_rd0RD0.f1Owner = OWNED_BY_NIC;
+#ifdef PRIVATE_OBJ
+        ref_set_rx_jiffies(pDevice->dev);
+#else
+        pDevice->dev->last_rx = jiffies;
+#endif
+    }
+
+    pDevice->pCurrRD[uIdx]=pRD;
+
+    return works;
+}
+
+
+static BOOL device_alloc_rx_buf(PSDevice pDevice, PSRxDesc pRD) {
+
+    PDEVICE_RD_INFO pRDInfo=pRD->pRDInfo;
+
+#ifdef PRIVATE_OBJ
+
+    pRDInfo->skb=dev_alloc_skb(pDevice->rx_buf_sz);
+    if (pRDInfo->skb==NULL)
+        return FALSE;
+    ref_skb_remap(pDevice->dev, &(pRDInfo->ref_skb), pRDInfo->skb);
+    pRDInfo->skb_dma = pci_map_single(pDevice->pcid, pRDInfo->ref_skb.tail, pDevice->rx_buf_sz,
+                        PCI_DMA_FROMDEVICE);
+#else
+
+    pRDInfo->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
+#ifdef	PLICE_DEBUG
+	//printk("device_alloc_rx_buf:skb is %x\n",pRDInfo->skb);
+#endif
+    if (pRDInfo->skb==NULL)
+        return FALSE;
+    ASSERT(pRDInfo->skb);
+    pRDInfo->skb->dev = pDevice->dev;
+    pRDInfo->skb_dma = pci_map_single(pDevice->pcid, pRDInfo->skb->tail, pDevice->rx_buf_sz,
+                        PCI_DMA_FROMDEVICE);
+#endif
+    *((PU32) &(pRD->m_rd0RD0)) = 0;
+
+    pRD->m_rd0RD0.wResCount = cpu_to_le16(pDevice->rx_buf_sz);
+    pRD->m_rd0RD0.f1Owner = OWNED_BY_NIC;
+    pRD->m_rd1RD1.wReqCount = cpu_to_le16(pDevice->rx_buf_sz);
+    pRD->buff_addr = cpu_to_le32(pRDInfo->skb_dma);
+
+    return TRUE;
+}
+
+
+
+BOOL device_alloc_frag_buf(PSDevice pDevice, PSDeFragControlBlock pDeF) {
+
+#ifdef PRIVATE_OBJ
+
+    pDeF->skb=dev_alloc_skb(pDevice->rx_buf_sz);
+    if (pDeF->skb==NULL)
+        return FALSE;
+    ref_skb_remap(pDevice->dev, &(pDeF->ref_skb), pDeF->skb);
+
+#else
+    pDeF->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
+    if (pDeF->skb == NULL)
+        return FALSE;
+    ASSERT(pDeF->skb);
+    pDeF->skb->dev = pDevice->dev;
+#endif
+
+    return TRUE;
+}
+
+
+
+static int device_tx_srv(PSDevice pDevice, UINT uIdx) {
+    PSTxDesc                 pTD;
+    BOOL                     bFull=FALSE;
+    int                      works = 0;
+    BYTE                     byTsr0;
+    BYTE                     byTsr1;
+    UINT                     uFrameSize, uFIFOHeaderSize;
+    PSTxBufHead              pTxBufHead;
+    struct net_device_stats* pStats = &pDevice->stats;
+    struct sk_buff*          skb;
+    UINT                     uNodeIndex;
+    PSMgmtObject             pMgmt = pDevice->pMgmt;
+#ifdef PRIVATE_OBJ
+    ref_sk_buff              ref_skb;
+#endif
+
+
+    for (pTD = pDevice->apTailTD[uIdx]; pDevice->iTDUsed[uIdx] >0; pTD = pTD->next) {
+
+        if (pTD->m_td0TD0.f1Owner == OWNED_BY_NIC)
+            break;
+        if (works++>15)
+            break;
+
+        byTsr0 = pTD->m_td0TD0.byTSR0;
+        byTsr1 = pTD->m_td0TD0.byTSR1;
+
+        //Only the status of first TD in the chain is correct
+        if (pTD->m_td1TD1.byTCR & TCR_STP) {
+
+            if ((pTD->pTDInfo->byFlags & TD_FLAGS_NETIF_SKB) != 0) {
+                uFIFOHeaderSize = pTD->pTDInfo->dwHeaderLength;
+                uFrameSize = pTD->pTDInfo->dwReqCount - uFIFOHeaderSize;
+                pTxBufHead = (PSTxBufHead) (pTD->pTDInfo->buf);
+#ifdef PRIVATE_OBJ
+                ref_skb_remap(pDevice->dev, &ref_skb, pTD->pTDInfo->skb);
+#endif
+                // Update the statistics based on the Transmit status
+                // now, we DO'NT check TSR0_CDH
+
+                STAvUpdateTDStatCounter(&pDevice->scStatistic,
+                        byTsr0, byTsr1,
+                        (PBYTE)(pTD->pTDInfo->buf + uFIFOHeaderSize),
+                        uFrameSize, uIdx);
+
+
+                BSSvUpdateNodeTxCounter(pDevice,
+                         byTsr0, byTsr1,
+                         (PBYTE)(pTD->pTDInfo->buf),
+                         uFIFOHeaderSize
+                         );
+
+                if (BITbIsBitOff(byTsr1, TSR1_TERR)) {
+                    if (byTsr0 != 0) {
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Tx[%d] OK but has error. tsr1[%02X] tsr0[%02X].\n",
+                           (INT)uIdx, byTsr1, byTsr0);
+                    }
+                    if ((pTxBufHead->wFragCtl & FRAGCTL_ENDFRAG) != FRAGCTL_NONFRAG) {
+                        pDevice->s802_11Counter.TransmittedFragmentCount ++;
+                    }
+                    pStats->tx_packets++;
+#ifdef PRIVATE_OBJ
+                    pStats->tx_bytes += *(ref_skb.len);
+#else
+                    pStats->tx_bytes += pTD->pTDInfo->skb->len;
+#endif
+                }
+                else {
+                     DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Tx[%d] dropped & tsr1[%02X] tsr0[%02X].\n",
+                           (INT)uIdx, byTsr1, byTsr0);
+                    pStats->tx_errors++;
+                    pStats->tx_dropped++;
+                }
+            }
+
+            if ((pTD->pTDInfo->byFlags & TD_FLAGS_PRIV_SKB) != 0) {
+                if (pDevice->bEnableHostapd) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "tx call back netif.. \n");
+#ifdef PRIVATE_OBJ
+                    ref_skb_remap(pDevice->apdev, &(ref_skb), pTD->pTDInfo->skb);
+	                ref_skb.mac.raw = ref_skb.data;
+	                *(ref_skb.pkt_type) = PACKET_OTHERHOST;
+    	            //*(ref_skb.protocol) = htons(ETH_P_802_2);
+	                memset(ref_skb.cb, 0, sizeof(ref_skb.cb));
+	                netif_rx(ref_skb.skb);
+#else
+                    skb = pTD->pTDInfo->skb;
+	                skb->dev = pDevice->apdev;
+			        skb->mac_header = skb->data;
+	                skb->pkt_type = PACKET_OTHERHOST;
+    	            //skb->protocol = htons(ETH_P_802_2);
+	                memset(skb->cb, 0, sizeof(skb->cb));
+	                netif_rx(skb);
+#endif
+	            }
+            }
+
+            if (BITbIsBitOn(byTsr1, TSR1_TERR)) {
+            if ((pTD->pTDInfo->byFlags & TD_FLAGS_PRIV_SKB) != 0) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Tx[%d] fail has error. tsr1[%02X] tsr0[%02X].\n",
+                          (INT)uIdx, byTsr1, byTsr0);
+            }
+
+//                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Tx[%d] fail has error. tsr1[%02X] tsr0[%02X].\n",
+//                          (INT)uIdx, byTsr1, byTsr0);
+
+                if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) &&
+                    (pTD->pTDInfo->byFlags & TD_FLAGS_NETIF_SKB)) {
+                    WORD    wAID;
+                    BYTE    byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80};
+
+                    skb = pTD->pTDInfo->skb;
+                    if (BSSDBbIsSTAInNodeDB(pMgmt, (PBYTE)(skb->data), &uNodeIndex)) {
+                        if (pMgmt->sNodeDBTable[uNodeIndex].bPSEnable) {
+                            skb_queue_tail(&pMgmt->sNodeDBTable[uNodeIndex].sTxPSQueue, skb);
+                            pMgmt->sNodeDBTable[uNodeIndex].wEnQueueCnt++;
+                            // set tx map
+                            wAID = pMgmt->sNodeDBTable[uNodeIndex].wAID;
+                            pMgmt->abyPSTxMap[wAID >> 3] |=  byMask[wAID & 7];
+                            pTD->pTDInfo->byFlags &= ~(TD_FLAGS_NETIF_SKB);
+                            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "tx_srv:tx fail re-queue sta index= %d, QueCnt= %d\n"
+                                    ,(INT)uNodeIndex, pMgmt->sNodeDBTable[uNodeIndex].wEnQueueCnt);
+                            pStats->tx_errors--;
+                            pStats->tx_dropped--;
+                        }
+                    }
+                }
+            }
+            device_free_tx_buf(pDevice,pTD);
+            pDevice->iTDUsed[uIdx]--;
+        }
+    }
+
+
+    if (uIdx == TYPE_AC0DMA) {
+        // RESERV_AC0DMA reserved for relay
+
+        if (AVAIL_TD(pDevice, uIdx) < RESERV_AC0DMA) {
+            bFull = TRUE;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " AC0DMA is Full = %d\n", pDevice->iTDUsed[uIdx]);
+        }
+        if (netif_queue_stopped(pDevice->dev) && (bFull==FALSE)){
+            netif_wake_queue(pDevice->dev);
+        }
+    }
+
+
+    pDevice->apTailTD[uIdx] = pTD;
+
+    return works;
+}
+
+
+static void device_error(PSDevice pDevice, WORD status) {
+
+    if (status & ISR_FETALERR) {
+        DEVICE_PRT(MSG_LEVEL_ERR, KERN_ERR
+            "%s: Hardware fatal error.\n",
+            pDevice->dev->name);
+        netif_stop_queue(pDevice->dev);
+        del_timer(&pDevice->sTimerCommand);
+        del_timer(&(pDevice->pMgmt->sTimerSecondCallback));
+        pDevice->bCmdRunning = FALSE;
+        MACbShutdown(pDevice->PortOffset);
+        return;
+    }
+
+}
+
+static void device_free_tx_buf(PSDevice pDevice, PSTxDesc pDesc) {
+    PDEVICE_TD_INFO  pTDInfo=pDesc->pTDInfo;
+    struct sk_buff* skb=pTDInfo->skb;
+
+    // pre-allocated buf_dma can't be unmapped.
+    if (pTDInfo->skb_dma && (pTDInfo->skb_dma != pTDInfo->buf_dma)) {
+        pci_unmap_single(pDevice->pcid,pTDInfo->skb_dma,skb->len,
+              PCI_DMA_TODEVICE);
+    }
+
+    if ((pTDInfo->byFlags & TD_FLAGS_NETIF_SKB) != 0)
+        dev_kfree_skb_irq(skb);
+
+    pTDInfo->skb_dma = 0;
+    pTDInfo->skb = 0;
+    pTDInfo->byFlags = 0;
+}
+
+
+
+//PLICE_DEBUG ->
+VOID	InitRxManagementQueue(PSDevice  pDevice)
+{
+	pDevice->rxManeQueue.packet_num = 0;
+	pDevice->rxManeQueue.head = pDevice->rxManeQueue.tail = 0;
+}
+//PLICE_DEBUG<-
+
+
+
+
+
+//PLICE_DEBUG ->
+INT MlmeThread(
+     void * Context)
+{
+	PSDevice	pDevice =  (PSDevice) Context;
+	PSRxMgmtPacket			pRxMgmtPacket;
+	// int i ;
+	//complete(&pDevice->notify);
+//printk("Enter MngWorkItem,Queue packet num is %d\n",pDevice->rxManeQueue.packet_num);
+
+	//printk("Enter MlmeThread,packet _num is %d\n",pDevice->rxManeQueue.packet_num);
+	//i = 0;
+#if 1
+	while (1)
+	{
+
+	//printk("DDDD\n");
+	//down(&pDevice->mlme_semaphore);
+        // pRxMgmtPacket =  DeQueue(pDevice);
+#if 1
+		spin_lock_irq(&pDevice->lock);
+		 while(pDevice->rxManeQueue.packet_num != 0)
+	 	{
+			 pRxMgmtPacket =  DeQueue(pDevice);
+        			//pDevice;
+        			//DequeueManageObject(pDevice->FirstRecvMngList, pDevice->LastRecvMngList);
+			vMgrRxManagePacket(pDevice, pDevice->pMgmt, pRxMgmtPacket);
+			//printk("packet_num is %d\n",pDevice->rxManeQueue.packet_num);
+
+		 }
+		spin_unlock_irq(&pDevice->lock);
+		if (mlme_kill == 0)
+		break;
+		//udelay(200);
+#endif
+	//printk("Before schedule thread jiffies is %x\n",jiffies);
+	schedule();
+	//printk("after schedule thread jiffies is %x\n",jiffies);
+	if (mlme_kill == 0)
+		break;
+	//printk("i is %d\n",i);
+	}
+
+#endif
+	return 0;
+
+}
+
+
+#ifdef PRIVATE_OBJ
+
+int __device_open(HANDLE pExDevice) {
+    PSDevice_info pDevice_info = (PSDevice_info)pExDevice;
+    PSDevice    pDevice = (PSDevice)(pDevice_info->pWDevice);
+
+#else
+
+static int  device_open(struct net_device *dev) {
+    PSDevice    pDevice=(PSDevice) netdev_priv(dev);
+    int i;
+#endif
+    pDevice->rx_buf_sz = PKT_BUF_SZ;
+    if (!device_init_rings(pDevice)) {
+        return -ENOMEM;
+    }
+//2008-5-13 <add> by chester
+#ifndef PRIVATE_OBJ
+    i=request_irq(pDevice->pcid->irq, &device_intr, IRQF_SHARED, dev->name, dev);
+    if (i)
+        return i;
+#endif
+	//printk("DEBUG1\n");
+#ifdef WPA_SM_Transtatus
+     extern SWPAResult wpa_Result;
+     memset(wpa_Result.ifname,0,sizeof(wpa_Result.ifname));
+     wpa_Result.proto = 0;
+     wpa_Result.key_mgmt = 0;
+     wpa_Result.eap_type = 0;
+     wpa_Result.authenticated = FALSE;
+     pDevice->fWPA_Authened = FALSE;
+#endif
+DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "call device init rd0 ring\n");
+device_init_rd0_ring(pDevice);
+    device_init_rd1_ring(pDevice);
+    device_init_defrag_cb(pDevice);
+    device_init_td0_ring(pDevice);
+    device_init_td1_ring(pDevice);
+//    VNTWIFIvSet11h(pDevice->pMgmt, pDevice->b11hEnable);
+
+
+    if (pDevice->bDiversityRegCtlON) {
+        device_init_diversity_timer(pDevice);
+    }
+    vMgrObjectInit(pDevice);
+    vMgrTimerInit(pDevice);
+
+//PLICE_DEBUG->
+#ifdef	TASK_LET
+	tasklet_init (&pDevice->RxMngWorkItem,(void *)MngWorkItem,(unsigned long )pDevice);
+#endif
+#ifdef	THREAD
+	InitRxManagementQueue(pDevice);
+	mlme_kill = 0;
+	mlme_task = kthread_run(MlmeThread,(void *) pDevice, "MLME");
+	if (IS_ERR(mlme_task)) {
+		printk("thread create fail\n");
+		return -1;
+	}
+
+	mlme_kill = 1;
+#endif
+
+
+
+#if 0
+	pDevice->MLMEThr_pid = kernel_thread(MlmeThread, pDevice, CLONE_VM);
+	if (pDevice->MLMEThr_pid <0 )
+	{
+		printk("unable start thread MlmeThread\n");
+		return -1;
+	}
+#endif
+
+	//printk("thread id is %d\n",pDevice->MLMEThr_pid);
+	//printk("Create thread time is %x\n",jiffies);
+	//wait_for_completion(&pDevice->notify);
+
+
+
+
+  // if (( SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_RADIOCTL)&0x06)==0x04)
+    //    return -ENOMEM;
+DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "call device_init_registers\n");
+	device_init_registers(pDevice, DEVICE_INIT_COLD);
+    MACvReadEtherAddress(pDevice->PortOffset, pDevice->abyCurrentNetAddr);
+    memcpy(pDevice->pMgmt->abyMACAddr, pDevice->abyCurrentNetAddr, U_ETHER_ADDR_LEN);
+#ifdef PRIVATE_OBJ
+    __device_set_multi(pExDevice);
+#else
+    device_set_multi(pDevice->dev);
+#endif
+
+    // Init for Key Management
+    KeyvInitTable(&pDevice->sKey, pDevice->PortOffset);
+    add_timer(&(pDevice->pMgmt->sTimerSecondCallback));
+
+	#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+	/*
+     pDevice->bwextstep0 = FALSE;
+     pDevice->bwextstep1 = FALSE;
+     pDevice->bwextstep2 = FALSE;
+     pDevice->bwextstep3 = FALSE;
+     */
+       pDevice->bwextcount=0;
+     pDevice->bWPASuppWextEnabled = FALSE;
+#endif
+    pDevice->byReAssocCount = 0;
+   pDevice->bWPADEVUp = FALSE;
+    // Patch: if WEP key already set by iwconfig but device not yet open
+    if ((pDevice->bEncryptionEnable == TRUE) && (pDevice->bTransmitKey == TRUE)) {
+        KeybSetDefaultKey(&(pDevice->sKey),
+                            (DWORD)(pDevice->byKeyIndex | (1 << 31)),
+                            pDevice->uKeyLength,
+                            NULL,
+                            pDevice->abyKey,
+                            KEY_CTL_WEP,
+                            pDevice->PortOffset,
+                            pDevice->byLocalID
+                          );
+         pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
+    }
+
+//printk("DEBUG2\n");
+
+
+DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "call MACvIntEnable\n");
+	MACvIntEnable(pDevice->PortOffset, IMR_MASK_VALUE);
+
+    if (pDevice->pMgmt->eConfigMode == WMAC_CONFIG_AP) {
+        bScheduleCommand((HANDLE)pDevice, WLAN_CMD_RUN_AP, NULL);
+	}
+	else {
+        bScheduleCommand((HANDLE)pDevice, WLAN_CMD_BSSID_SCAN, NULL);
+        bScheduleCommand((HANDLE)pDevice, WLAN_CMD_SSID, NULL);
+    }
+    pDevice->flags |=DEVICE_FLAGS_OPENED;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_open success.. \n");
+    return 0;
+}
+
+
+#ifdef PRIVATE_OBJ
+
+int  __device_close(HANDLE pExDevice) {
+    PSDevice_info pDevice_info = (PSDevice_info)pExDevice;
+    struct net_device *dev = pDevice_info->dev;
+    PSDevice    pDevice = (PSDevice)(pDevice_info->pWDevice);
+
+#else
+static int  device_close(struct net_device *dev) {
+    PSDevice  pDevice=(PSDevice) netdev_priv(dev);
+#endif
+    PSMgmtObject     pMgmt = pDevice->pMgmt;
+ //PLICE_DEBUG->
+#ifdef	THREAD
+	mlme_kill = 0;
+#endif
+//PLICE_DEBUG<-
+//2007-1121-02<Add>by EinsnLiu
+    if (pDevice->bLinkPass) {
+	bScheduleCommand((HANDLE)pDevice, WLAN_CMD_DISASSOCIATE, NULL);
+        mdelay(30);
+    }
+#ifdef TxInSleep
+    del_timer(&pDevice->sTimerTxData);
+#endif
+    del_timer(&pDevice->sTimerCommand);
+    del_timer(&pMgmt->sTimerSecondCallback);
+    if (pDevice->bDiversityRegCtlON) {
+        del_timer(&pDevice->TimerSQ3Tmax1);
+        del_timer(&pDevice->TimerSQ3Tmax2);
+        del_timer(&pDevice->TimerSQ3Tmax3);
+    }
+
+#ifdef	TASK_LET
+	tasklet_kill(&pDevice->RxMngWorkItem);
+#endif
+     netif_stop_queue(dev);
+    pDevice->bCmdRunning = FALSE;
+    MACbShutdown(pDevice->PortOffset);
+    MACbSoftwareReset(pDevice->PortOffset);
+    CARDbRadioPowerOff(pDevice);
+
+    pDevice->bLinkPass = FALSE;
+    memset(pMgmt->abyCurrBSSID, 0, 6);
+    pMgmt->eCurrState = WMAC_STATE_IDLE;
+    device_free_td0_ring(pDevice);
+    device_free_td1_ring(pDevice);
+    device_free_rd0_ring(pDevice);
+    device_free_rd1_ring(pDevice);
+    device_free_frag_buf(pDevice);
+    device_free_rings(pDevice);
+    BSSvClearNodeDBTable(pDevice, 0);
+    free_irq(dev->irq, dev);
+    pDevice->flags &=(~DEVICE_FLAGS_OPENED);
+	//2008-0714-01<Add>by chester
+device_release_WPADEV(pDevice);
+//PLICE_DEBUG->
+	//tasklet_kill(&pDevice->RxMngWorkItem);
+//PLICE_DEBUG<-
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_close.. \n");
+    return 0;
+}
+
+#ifdef PRIVATE_OBJ
+
+int  __device_dma0_tx_80211(HANDLE pExDevice, struct sk_buff *skb) {
+    PSDevice_info pDevice_info = (PSDevice_info)pExDevice;
+    PSDevice    pDevice = (PSDevice)(pDevice_info->pWDevice);
+    ref_sk_buff     ref_skb;
+
+#else
+
+
+static int device_dma0_tx_80211(struct sk_buff *skb, struct net_device *dev) {
+    PSDevice        pDevice=netdev_priv(dev);
+#endif
+    PBYTE           pbMPDU;
+    UINT            cbMPDULen = 0;
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_dma0_tx_80211\n");
+    spin_lock_irq(&pDevice->lock);
+
+    if (AVAIL_TD(pDevice, TYPE_TXDMA0) <= 0) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_dma0_tx_80211, td0 <=0\n");
+        dev_kfree_skb_irq(skb);
+        spin_unlock_irq(&pDevice->lock);
+        return 0;
+    }
+
+    if (pDevice->bStopTx0Pkt == TRUE) {
+        dev_kfree_skb_irq(skb);
+        spin_unlock_irq(&pDevice->lock);
+        return 0;
+    };
+
+#ifdef PRIVATE_OBJ
+    ref_skb_remap(pDevice->dev, &ref_skb, skb);
+    cbMPDULen = *(ref_skb.len);
+    pbMPDU = ref_skb.data;
+#else
+    cbMPDULen = skb->len;
+    pbMPDU = skb->data;
+#endif
+
+    vDMA0_tx_80211(pDevice, skb, pbMPDU, cbMPDULen);
+
+    spin_unlock_irq(&pDevice->lock);
+
+    return 0;
+
+}
+
+
+
+BOOL device_dma0_xmit(PSDevice pDevice, struct sk_buff *skb, UINT uNodeIndex) {
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PSTxDesc        pHeadTD, pLastTD;
+    UINT            cbFrameBodySize;
+    UINT            uMACfragNum;
+    BYTE            byPktTyp;
+    BOOL            bNeedEncryption = FALSE;
+    PSKeyItem       pTransmitKey = NULL;
+    UINT            cbHeaderSize;
+    UINT            ii;
+    SKeyItem        STempKey;
+//    BYTE            byKeyIndex = 0;
+#ifdef PRIVATE_OBJ
+    ref_sk_buff     ref_skb;
+#endif
+
+
+    if (pDevice->bStopTx0Pkt == TRUE) {
+        dev_kfree_skb_irq(skb);
+        return FALSE;
+    };
+
+    if (AVAIL_TD(pDevice, TYPE_TXDMA0) <= 0) {
+        dev_kfree_skb_irq(skb);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_dma0_xmit, td0 <=0\n");
+        return FALSE;
+    }
+
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+        if (pDevice->uAssocCount == 0) {
+            dev_kfree_skb_irq(skb);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_dma0_xmit, assocCount = 0\n");
+            return FALSE;
+        }
+    }
+
+#ifdef PRIVATE_OBJ
+    ref_skb_remap(pDevice->dev, &(ref_skb), skb);
+#endif
+    pHeadTD = pDevice->apCurrTD[TYPE_TXDMA0];
+
+    pHeadTD->m_td1TD1.byTCR = (TCR_EDP|TCR_STP);
+
+#ifdef PRIVATE_OBJ
+    memcpy(pDevice->sTxEthHeader.abyDstAddr, (PBYTE)(ref_skb.data), U_HEADER_LEN);
+    cbFrameBodySize = *(ref_skb.len) - U_HEADER_LEN;
+
+#else
+    memcpy(pDevice->sTxEthHeader.abyDstAddr, (PBYTE)(skb->data), U_HEADER_LEN);
+    cbFrameBodySize = skb->len - U_HEADER_LEN;
+#endif
+
+    // 802.1H
+    if (ntohs(pDevice->sTxEthHeader.wType) > MAX_DATA_LEN) {
+        cbFrameBodySize += 8;
+    }
+    uMACfragNum = cbGetFragCount(pDevice, pTransmitKey, cbFrameBodySize, &pDevice->sTxEthHeader);
+
+    if ( uMACfragNum > AVAIL_TD(pDevice, TYPE_TXDMA0)) {
+        dev_kfree_skb_irq(skb);
+        return FALSE;
+    }
+    byPktTyp = (BYTE)pDevice->byPacketType;
+
+
+    if (pDevice->bFixRate) {
+        if (pDevice->eCurrentPHYType == PHY_TYPE_11B) {
+            if (pDevice->uConnectionRate >= RATE_11M) {
+                pDevice->wCurrentRate = RATE_11M;
+            } else {
+                pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
+            }
+        } else {
+            if (pDevice->uConnectionRate >= RATE_54M)
+                pDevice->wCurrentRate = RATE_54M;
+            else
+                pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
+        }
+    }
+    else {
+        pDevice->wCurrentRate = pDevice->pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate;
+    }
+
+    //preamble type
+    if (pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble) {
+        pDevice->byPreambleType = pDevice->byShortPreamble;
+    }
+    else {
+        pDevice->byPreambleType = PREAMBLE_LONG;
+    }
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dma0: pDevice->wCurrentRate = %d \n", pDevice->wCurrentRate);
+
+
+    if (pDevice->wCurrentRate <= RATE_11M) {
+        byPktTyp = PK_TYPE_11B;
+    } else if (pDevice->eCurrentPHYType == PHY_TYPE_11A) {
+        byPktTyp = PK_TYPE_11A;
+    } else {
+        if (pDevice->bProtectMode == TRUE) {
+            byPktTyp = PK_TYPE_11GB;
+        } else {
+            byPktTyp = PK_TYPE_11GA;
+        }
+    }
+
+    if (pDevice->bEncryptionEnable == TRUE)
+        bNeedEncryption = TRUE;
+
+    if (pDevice->bEnableHostWEP) {
+        pTransmitKey = &STempKey;
+        pTransmitKey->byCipherSuite = pMgmt->sNodeDBTable[uNodeIndex].byCipherSuite;
+        pTransmitKey->dwKeyIndex = pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex;
+        pTransmitKey->uKeyLength = pMgmt->sNodeDBTable[uNodeIndex].uWepKeyLength;
+        pTransmitKey->dwTSC47_16 = pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16;
+        pTransmitKey->wTSC15_0 = pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0;
+        memcpy(pTransmitKey->abyKey,
+            &pMgmt->sNodeDBTable[uNodeIndex].abyWepKey[0],
+            pTransmitKey->uKeyLength
+            );
+    }
+    vGenerateFIFOHeader(pDevice, byPktTyp, pDevice->pbyTmpBuff, bNeedEncryption,
+                        cbFrameBodySize, TYPE_TXDMA0, pHeadTD,
+                        &pDevice->sTxEthHeader, (PBYTE)skb->data, pTransmitKey, uNodeIndex,
+                        &uMACfragNum,
+                        &cbHeaderSize
+                        );
+
+    if (MACbIsRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PS)) {
+        // Disable PS
+        MACbPSWakeup(pDevice->PortOffset);
+    }
+
+    pDevice->bPWBitOn = FALSE;
+
+    pLastTD = pHeadTD;
+    for (ii = 0; ii < uMACfragNum; ii++) {
+        // Poll Transmit the adapter
+        wmb();
+        pHeadTD->m_td0TD0.f1Owner=OWNED_BY_NIC;
+        wmb();
+        if (ii == (uMACfragNum - 1))
+            pLastTD = pHeadTD;
+        pHeadTD = pHeadTD->next;
+    }
+
+    // Save the information needed by the tx interrupt handler
+    // to complete the Send request
+    pLastTD->pTDInfo->skb = skb;
+    pLastTD->pTDInfo->byFlags = 0;
+    pLastTD->pTDInfo->byFlags |= TD_FLAGS_NETIF_SKB;
+
+    pDevice->apCurrTD[TYPE_TXDMA0] = pHeadTD;
+
+    MACvTransmit0(pDevice->PortOffset);
+
+
+    return TRUE;
+}
+
+//TYPE_AC0DMA data tx
+#ifdef PRIVATE_OBJ
+
+int  __device_xmit(HANDLE pExDevice, struct sk_buff *skb) {
+    PSDevice_info pDevice_info = (PSDevice_info)pExDevice;
+    PSDevice    pDevice = (PSDevice)(pDevice_info->pWDevice);
+    struct net_device *dev = pDevice_info->dev;
+    ref_sk_buff     ref_skb;
+
+#else
+static int  device_xmit(struct sk_buff *skb, struct net_device *dev) {
+    PSDevice pDevice=netdev_priv(dev);
+
+#endif
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PSTxDesc        pHeadTD, pLastTD;
+    UINT            uNodeIndex = 0;
+    BYTE            byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80};
+    WORD            wAID;
+    UINT            uMACfragNum = 1;
+    UINT            cbFrameBodySize;
+    BYTE            byPktTyp;
+    UINT            cbHeaderSize;
+    BOOL            bNeedEncryption = FALSE;
+    PSKeyItem       pTransmitKey = NULL;
+    SKeyItem        STempKey;
+    UINT            ii;
+    BOOL            bTKIP_UseGTK = FALSE;
+    BOOL            bNeedDeAuth = FALSE;
+    PBYTE           pbyBSSID;
+    BOOL            bNodeExist = FALSE;
+
+
+
+    spin_lock_irq(&pDevice->lock);
+    if (pDevice->bLinkPass == FALSE) {
+        dev_kfree_skb_irq(skb);
+        spin_unlock_irq(&pDevice->lock);
+        return 0;
+    }
+
+    if (pDevice->bStopDataPkt) {
+        dev_kfree_skb_irq(skb);
+        spin_unlock_irq(&pDevice->lock);
+        return 0;
+    }
+
+#ifdef PRIVATE_OBJ
+    ref_skb_remap(pDevice->dev, &ref_skb, skb);
+#endif
+
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+        if (pDevice->uAssocCount == 0) {
+            dev_kfree_skb_irq(skb);
+            spin_unlock_irq(&pDevice->lock);
+            return 0;
+        }
+#ifdef PRIVATE_OBJ
+        if (IS_MULTICAST_ADDRESS((PBYTE)(ref_skb.data))) {
+#else
+        if (IS_MULTICAST_ADDRESS((PBYTE)(skb->data))) {
+#endif
+            uNodeIndex = 0;
+            bNodeExist = TRUE;
+            if (pMgmt->sNodeDBTable[0].bPSEnable) {
+#ifdef PRIVATE_OBJ
+                skb_queue_tail(&(pMgmt->sNodeDBTable[0].sTxPSQueue), ref_skb.skb);
+#else
+                skb_queue_tail(&(pMgmt->sNodeDBTable[0].sTxPSQueue), skb);
+#endif
+                pMgmt->sNodeDBTable[0].wEnQueueCnt++;
+                // set tx map
+                pMgmt->abyPSTxMap[0] |= byMask[0];
+                spin_unlock_irq(&pDevice->lock);
+                return 0;
+            }
+}else {
+#ifdef PRIVATE_OBJ
+            if (BSSDBbIsSTAInNodeDB(pMgmt, (PBYTE)(ref_skb.data), &uNodeIndex)) {
+#else
+            if (BSSDBbIsSTAInNodeDB(pMgmt, (PBYTE)(skb->data), &uNodeIndex)) {
+#endif
+                if (pMgmt->sNodeDBTable[uNodeIndex].bPSEnable) {
+#ifdef PRIVATE_OBJ
+                    skb_queue_tail(&pMgmt->sNodeDBTable[uNodeIndex].sTxPSQueue, ref_skb.skb);
+#else
+                    skb_queue_tail(&pMgmt->sNodeDBTable[uNodeIndex].sTxPSQueue, skb);
+#endif
+                    pMgmt->sNodeDBTable[uNodeIndex].wEnQueueCnt++;
+                    // set tx map
+                    wAID = pMgmt->sNodeDBTable[uNodeIndex].wAID;
+                    pMgmt->abyPSTxMap[wAID >> 3] |=  byMask[wAID & 7];
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Set:pMgmt->abyPSTxMap[%d]= %d\n",
+                             (wAID >> 3), pMgmt->abyPSTxMap[wAID >> 3]);
+                    spin_unlock_irq(&pDevice->lock);
+                    return 0;
+                }
+
+                if (pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble) {
+                    pDevice->byPreambleType = pDevice->byShortPreamble;
+
+                }else {
+                    pDevice->byPreambleType = PREAMBLE_LONG;
+                }
+                bNodeExist = TRUE;
+
+            }
+        }
+
+        if (bNodeExist == FALSE) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Unknown STA not found in node DB \n");
+            dev_kfree_skb_irq(skb);
+            spin_unlock_irq(&pDevice->lock);
+            return 0;
+        }
+    }
+
+    pHeadTD = pDevice->apCurrTD[TYPE_AC0DMA];
+
+    pHeadTD->m_td1TD1.byTCR = (TCR_EDP|TCR_STP);
+
+
+#ifdef PRIVATE_OBJ
+    memcpy(pDevice->sTxEthHeader.abyDstAddr, (PBYTE)(ref_skb.data), U_HEADER_LEN);
+    cbFrameBodySize = *(ref_skb.len) - U_HEADER_LEN;
+#else
+    memcpy(pDevice->sTxEthHeader.abyDstAddr, (PBYTE)(skb->data), U_HEADER_LEN);
+    cbFrameBodySize = skb->len - U_HEADER_LEN;
+#endif
+    // 802.1H
+    if (ntohs(pDevice->sTxEthHeader.wType) > MAX_DATA_LEN) {
+        cbFrameBodySize += 8;
+    }
+
+
+    if (pDevice->bEncryptionEnable == TRUE) {
+        bNeedEncryption = TRUE;
+        // get Transmit key
+        do {
+            if ((pDevice->pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
+                (pDevice->pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
+                pbyBSSID = pDevice->abyBSSID;
+                // get pairwise key
+                if (KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, PAIRWISE_KEY, &pTransmitKey) == FALSE) {
+                    // get group key
+                    if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == TRUE) {
+                        bTKIP_UseGTK = TRUE;
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Get GTK.\n");
+                        break;
+                    }
+                } else {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Get PTK.\n");
+                    break;
+                }
+            }else if (pDevice->pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+
+                pbyBSSID = pDevice->sTxEthHeader.abyDstAddr;  //TO_DS = 0 and FROM_DS = 0 --> 802.11 MAC Address1
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"IBSS Serach Key: \n");
+                for (ii = 0; ii< 6; ii++)
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"%x \n", *(pbyBSSID+ii));
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"\n");
+
+                // get pairwise key
+                if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, PAIRWISE_KEY, &pTransmitKey) == TRUE)
+                    break;
+            }
+            // get group key
+            pbyBSSID = pDevice->abyBroadcastAddr;
+            if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == FALSE) {
+                pTransmitKey = NULL;
+                if (pDevice->pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"IBSS and KEY is NULL. [%d]\n", pDevice->pMgmt->eCurrMode);
+                }
+                else
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"NOT IBSS and KEY is NULL. [%d]\n", pDevice->pMgmt->eCurrMode);
+            } else {
+                bTKIP_UseGTK = TRUE;
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Get GTK.\n");
+            }
+        } while(FALSE);
+    }
+
+    if (pDevice->bEnableHostWEP) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"acdma0: STA index %d\n", uNodeIndex);
+        if (pDevice->bEncryptionEnable == TRUE) {
+            pTransmitKey = &STempKey;
+            pTransmitKey->byCipherSuite = pMgmt->sNodeDBTable[uNodeIndex].byCipherSuite;
+            pTransmitKey->dwKeyIndex = pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex;
+            pTransmitKey->uKeyLength = pMgmt->sNodeDBTable[uNodeIndex].uWepKeyLength;
+            pTransmitKey->dwTSC47_16 = pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16;
+            pTransmitKey->wTSC15_0 = pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0;
+            memcpy(pTransmitKey->abyKey,
+                &pMgmt->sNodeDBTable[uNodeIndex].abyWepKey[0],
+                pTransmitKey->uKeyLength
+                );
+         }
+    }
+
+    uMACfragNum = cbGetFragCount(pDevice, pTransmitKey, cbFrameBodySize, &pDevice->sTxEthHeader);
+
+    if (uMACfragNum > AVAIL_TD(pDevice, TYPE_AC0DMA)) {
+        DEVICE_PRT(MSG_LEVEL_ERR, KERN_DEBUG "uMACfragNum > AVAIL_TD(TYPE_AC0DMA) = %d\n", uMACfragNum);
+        dev_kfree_skb_irq(skb);
+        spin_unlock_irq(&pDevice->lock);
+        return 0;
+    }
+
+    if (pTransmitKey != NULL) {
+        if ((pTransmitKey->byCipherSuite == KEY_CTL_WEP) &&
+            (pTransmitKey->uKeyLength == WLAN_WEP232_KEYLEN)) {
+            uMACfragNum = 1; //WEP256 doesn't support fragment
+        }
+    }
+
+    byPktTyp = (BYTE)pDevice->byPacketType;
+
+    if (pDevice->bFixRate) {
+#ifdef	PLICE_DEBUG
+	printk("Fix Rate: PhyType is %d,ConnectionRate is %d\n",pDevice->eCurrentPHYType,pDevice->uConnectionRate);
+#endif
+
+        if (pDevice->eCurrentPHYType == PHY_TYPE_11B) {
+            if (pDevice->uConnectionRate >= RATE_11M) {
+                pDevice->wCurrentRate = RATE_11M;
+            } else {
+                pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
+            }
+        } else {
+            if ((pDevice->eCurrentPHYType == PHY_TYPE_11A) &&
+                (pDevice->uConnectionRate <= RATE_6M)) {
+                pDevice->wCurrentRate = RATE_6M;
+            } else {
+                if (pDevice->uConnectionRate >= RATE_54M)
+                    pDevice->wCurrentRate = RATE_54M;
+                else
+                    pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
+
+            }
+        }
+        pDevice->byACKRate = (BYTE) pDevice->wCurrentRate;
+        pDevice->byTopCCKBasicRate = RATE_1M;
+        pDevice->byTopOFDMBasicRate = RATE_6M;
+    }
+    else {
+        //auto rate
+    if (pDevice->sTxEthHeader.wType == TYPE_PKT_802_1x) {
+            if (pDevice->eCurrentPHYType != PHY_TYPE_11A) {
+                pDevice->wCurrentRate = RATE_1M;
+                pDevice->byACKRate = RATE_1M;
+                pDevice->byTopCCKBasicRate = RATE_1M;
+                pDevice->byTopOFDMBasicRate = RATE_6M;
+            } else {
+                pDevice->wCurrentRate = RATE_6M;
+                pDevice->byACKRate = RATE_6M;
+                pDevice->byTopCCKBasicRate = RATE_1M;
+                pDevice->byTopOFDMBasicRate = RATE_6M;
+            }
+        }
+        else {
+		VNTWIFIvGetTxRate(  pDevice->pMgmt,
+                                pDevice->sTxEthHeader.abyDstAddr,
+                                &(pDevice->wCurrentRate),
+                                &(pDevice->byACKRate),
+                                &(pDevice->byTopCCKBasicRate),
+                                &(pDevice->byTopOFDMBasicRate));
+
+#if 0
+printk("auto rate:Rate : %d,AckRate:%d,TopCCKRate:%d,TopOFDMRate:%d\n",
+pDevice->wCurrentRate,pDevice->byACKRate,
+pDevice->byTopCCKBasicRate,pDevice->byTopOFDMBasicRate);
+
+#endif
+
+#if 0
+
+	pDevice->wCurrentRate = 11;
+	pDevice->byACKRate = 8;
+	pDevice->byTopCCKBasicRate = 3;
+	pDevice->byTopOFDMBasicRate = 8;
+#endif
+
+
+		}
+    }
+
+//    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "acdma0: pDevice->wCurrentRate = %d \n", pDevice->wCurrentRate);
+
+    if (pDevice->wCurrentRate <= RATE_11M) {
+        byPktTyp = PK_TYPE_11B;
+    } else if (pDevice->eCurrentPHYType == PHY_TYPE_11A) {
+        byPktTyp = PK_TYPE_11A;
+    } else {
+        if (pDevice->bProtectMode == TRUE) {
+            byPktTyp = PK_TYPE_11GB;
+        } else {
+            byPktTyp = PK_TYPE_11GA;
+        }
+    }
+
+//#ifdef	PLICE_DEBUG
+//	printk("FIX RATE:CurrentRate is %d");
+//#endif
+
+    if (bNeedEncryption == TRUE) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ntohs Pkt Type=%04x\n", ntohs(pDevice->sTxEthHeader.wType));
+        if ((pDevice->sTxEthHeader.wType) == TYPE_PKT_802_1x) {
+            bNeedEncryption = FALSE;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Pkt Type=%04x\n", (pDevice->sTxEthHeader.wType));
+            if ((pDevice->pMgmt->eCurrMode == WMAC_MODE_ESS_STA) && (pDevice->pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
+                if (pTransmitKey == NULL) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Don't Find TX KEY\n");
+                }
+                else {
+                    if (bTKIP_UseGTK == TRUE) {
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"error: KEY is GTK!!~~\n");
+                    }
+                    else {
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Find PTK [%lX]\n", pTransmitKey->dwKeyIndex);
+                        bNeedEncryption = TRUE;
+                    }
+                }
+            }
+
+            if (pDevice->byCntMeasure == 2) {
+                bNeedDeAuth = TRUE;
+                pDevice->s802_11Counter.TKIPCounterMeasuresInvoked++;
+            }
+
+            if (pDevice->bEnableHostWEP) {
+                if ((uNodeIndex != 0) &&
+                    (pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex & PAIRWISE_KEY)) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Find PTK [%lX]\n", pTransmitKey->dwKeyIndex);
+                    bNeedEncryption = TRUE;
+                 }
+             }
+        }
+        else {
+            if (pTransmitKey == NULL) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"return no tx key\n");
+                dev_kfree_skb_irq(skb);
+                spin_unlock_irq(&pDevice->lock);
+                return 0;
+            }
+        }
+    }
+
+
+#ifdef PRIVATE_OBJ
+    vGenerateFIFOHeader(pDevice, byPktTyp, pDevice->pbyTmpBuff, bNeedEncryption,
+                        cbFrameBodySize, TYPE_AC0DMA, pHeadTD,
+                        &pDevice->sTxEthHeader, (PBYTE)ref_skb.data, pTransmitKey, uNodeIndex,
+                        &uMACfragNum,
+                        &cbHeaderSize
+                        );
+#else
+#ifdef	PLICE_DEBUG
+	//if (skb->len == 98)
+	//{
+	//	printk("ping:len is %d\n");
+	//}
+#endif
+    vGenerateFIFOHeader(pDevice, byPktTyp, pDevice->pbyTmpBuff, bNeedEncryption,
+                        cbFrameBodySize, TYPE_AC0DMA, pHeadTD,
+                        &pDevice->sTxEthHeader, (PBYTE)skb->data, pTransmitKey, uNodeIndex,
+                        &uMACfragNum,
+                        &cbHeaderSize
+                        );
+#endif
+
+    if (MACbIsRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PS)) {
+        // Disable PS
+        MACbPSWakeup(pDevice->PortOffset);
+    }
+    pDevice->bPWBitOn = FALSE;
+
+    pLastTD = pHeadTD;
+    for (ii = 0; ii < uMACfragNum; ii++) {
+        // Poll Transmit the adapter
+        wmb();
+        pHeadTD->m_td0TD0.f1Owner=OWNED_BY_NIC;
+        wmb();
+        if (ii == uMACfragNum - 1)
+            pLastTD = pHeadTD;
+        pHeadTD = pHeadTD->next;
+    }
+
+    // Save the information needed by the tx interrupt handler
+    // to complete the Send request
+#ifdef PRIVATE_OBJ
+    pLastTD->pTDInfo->skb = ref_skb.skb;
+#else
+    pLastTD->pTDInfo->skb = skb;
+#endif
+    pLastTD->pTDInfo->byFlags = 0;
+    pLastTD->pTDInfo->byFlags |= TD_FLAGS_NETIF_SKB;
+#ifdef TxInSleep
+  pDevice->nTxDataTimeCout=0; //2008-8-21 chester <add> for send null packet
+  #endif
+    if (AVAIL_TD(pDevice, TYPE_AC0DMA) <= 1) {
+        netif_stop_queue(dev);
+    }
+
+    pDevice->apCurrTD[TYPE_AC0DMA] = pHeadTD;
+//#ifdef	PLICE_DEBUG
+	if (pDevice->bFixRate)
+	{
+		printk("FixRate:Rate is %d,TxPower is %d\n",pDevice->wCurrentRate,pDevice->byCurPwr);
+	}
+	else
+	{
+		//printk("Auto Rate:Rate is %d,TxPower is %d\n",pDevice->wCurrentRate,pDevice->byCurPwr);
+	}
+//#endif
+
+{
+    BYTE  Protocol_Version;    //802.1x Authentication
+    BYTE  Packet_Type;           //802.1x Authentication
+    BYTE  Descriptor_type;
+    WORD Key_info;
+BOOL            bTxeapol_key = FALSE;
+    Protocol_Version = skb->data[U_HEADER_LEN];
+    Packet_Type = skb->data[U_HEADER_LEN+1];
+    Descriptor_type = skb->data[U_HEADER_LEN+1+1+2];
+    Key_info = (skb->data[U_HEADER_LEN+1+1+2+1] << 8)|(skb->data[U_HEADER_LEN+1+1+2+2]);
+   if (pDevice->sTxEthHeader.wType == TYPE_PKT_802_1x) {
+           if(((Protocol_Version==1) ||(Protocol_Version==2)) &&
+	        (Packet_Type==3)) {  //802.1x OR eapol-key challenge frame transfer
+                        bTxeapol_key = TRUE;
+		if((Descriptor_type==254)||(Descriptor_type==2)) {       //WPA or RSN
+                       if(!(Key_info & BIT3) &&   //group-key challenge
+			   (Key_info & BIT8) && (Key_info & BIT9)) {    //send 2/2 key
+			  pDevice->fWPA_Authened = TRUE;
+			  if(Descriptor_type==254)
+			      printk("WPA ");
+			  else
+			      printk("WPA2 ");
+			  printk("Authentication completed!!\n");
+                        }
+		 }
+             }
+   }
+}
+
+    MACvTransmitAC0(pDevice->PortOffset);
+//    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "acdma0:pDevice->apCurrTD= %p\n", pHeadTD);
+
+#ifdef PRIVATE_OBJ
+    ref_set_tx_jiffies(pDevice->dev);
+#else
+    dev->trans_start = jiffies;
+#endif
+
+    spin_unlock_irq(&pDevice->lock);
+    return 0;
+
+}
+
+#ifdef PRIVATE_OBJ
+
+int __device_intr(int irq, HANDLE pExDevice, struct pt_regs *regs) {
+    PSDevice_info pDevice_info = (PSDevice_info)pExDevice;
+    PSDevice    pDevice = (PSDevice)(pDevice_info->pWDevice);
+
+
+#else
+static  irqreturn_t  device_intr(int irq,  void *dev_instance) {
+    struct net_device* dev=dev_instance;
+    PSDevice     pDevice=(PSDevice) netdev_priv(dev);
+#endif
+
+    int             max_count=0;
+    DWORD           dwMIBCounter=0;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    BYTE            byOrgPageSel=0;
+    int             handled = 0;
+    BYTE            byData = 0;
+    int             ii= 0;
+//    BYTE            byRSSI;
+
+
+    MACvReadISR(pDevice->PortOffset, &pDevice->dwIsr);
+
+    if (pDevice->dwIsr == 0)
+        return IRQ_RETVAL(handled);
+
+    if (pDevice->dwIsr == 0xffffffff) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dwIsr = 0xffff\n");
+        return IRQ_RETVAL(handled);
+    }
+    /*
+      // 2008-05-21 <mark> by Richardtai, we can't read RSSI here, because no packet bound with RSSI
+
+    	if ((BITbIsBitOn(pDevice->dwIsr, ISR_RXDMA0)) &&
+        (pDevice->byLocalID != REV_ID_VT3253_B0) &&
+        (pDevice->bBSSIDFilter == TRUE)) {
+        // update RSSI
+        //BBbReadEmbeded(pDevice->PortOffset, 0x3E, &byRSSI);
+        //pDevice->uCurrRSSI = byRSSI;
+    }
+    */
+
+    handled = 1;
+    MACvIntDisable(pDevice->PortOffset);
+    spin_lock_irq(&pDevice->lock);
+
+    //Make sure current page is 0
+    VNSvInPortB(pDevice->PortOffset + MAC_REG_PAGE1SEL, &byOrgPageSel);
+    if (byOrgPageSel == 1) {
+        MACvSelectPage0(pDevice->PortOffset);
+    }
+    else
+        byOrgPageSel = 0;
+
+    MACvReadMIBCounter(pDevice->PortOffset, &dwMIBCounter);
+    // TBD....
+    // Must do this after doing rx/tx, cause ISR bit is slow
+    // than RD/TD write back
+    // update ISR counter
+    STAvUpdate802_11Counter(&pDevice->s802_11Counter, &pDevice->scStatistic , dwMIBCounter);
+    while (pDevice->dwIsr != 0) {
+
+        STAvUpdateIsrStatCounter(&pDevice->scStatistic, pDevice->dwIsr);
+        MACvWriteISR(pDevice->PortOffset, pDevice->dwIsr);
+
+        if (pDevice->dwIsr & ISR_FETALERR){
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " ISR_FETALERR \n");
+            VNSvOutPortB(pDevice->PortOffset + MAC_REG_SOFTPWRCTL, 0);
+            VNSvOutPortW(pDevice->PortOffset + MAC_REG_SOFTPWRCTL, SOFTPWRCTL_SWPECTI);
+            device_error(pDevice, pDevice->dwIsr);
+        }
+
+        if (pDevice->byLocalID > REV_ID_VT3253_B1) {
+
+            if (BITbIsBitOn(pDevice->dwIsr, ISR_MEASURESTART)) {
+                // 802.11h measure start
+                pDevice->byOrgChannel = pDevice->byCurrentCh;
+                VNSvInPortB(pDevice->PortOffset + MAC_REG_RCR, &(pDevice->byOrgRCR));
+                VNSvOutPortB(pDevice->PortOffset + MAC_REG_RCR, (RCR_RXALLTYPE | RCR_UNICAST | RCR_BROADCAST | RCR_MULTICAST | RCR_WPAERR));
+                MACvSelectPage1(pDevice->PortOffset);
+                VNSvInPortD(pDevice->PortOffset + MAC_REG_MAR0, &(pDevice->dwOrgMAR0));
+                VNSvInPortD(pDevice->PortOffset + MAC_REG_MAR4, &(pDevice->dwOrgMAR4));
+                MACvSelectPage0(pDevice->PortOffset);
+               //xxxx
+               // WCMDbFlushCommandQueue(pDevice->pMgmt, TRUE);
+                if (CARDbSetChannel(pDevice, pDevice->pCurrMeasureEID->sReq.byChannel) == TRUE) {
+                    pDevice->bMeasureInProgress = TRUE;
+                    MACvSelectPage1(pDevice->PortOffset);
+                    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL, MSRCTL_READY);
+                    MACvSelectPage0(pDevice->PortOffset);
+                    pDevice->byBasicMap = 0;
+                    pDevice->byCCAFraction = 0;
+                    for(ii=0;ii<8;ii++) {
+                        pDevice->dwRPIs[ii] = 0;
+                    }
+                } else {
+                    // can not measure because set channel fail
+                   // WCMDbResetCommandQueue(pDevice->pMgmt);
+                    // clear measure control
+                    MACvRegBitsOff(pDevice->PortOffset, MAC_REG_MSRCTL, MSRCTL_EN);
+                    s_vCompleteCurrentMeasure(pDevice, MEASURE_MODE_INCAPABLE);
+                    MACvSelectPage1(pDevice->PortOffset);
+                    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL+1, MSRCTL1_TXPAUSE);
+                    MACvSelectPage0(pDevice->PortOffset);
+                }
+            }
+            if (BITbIsBitOn(pDevice->dwIsr, ISR_MEASUREEND)) {
+                // 802.11h measure end
+                pDevice->bMeasureInProgress = FALSE;
+                VNSvOutPortB(pDevice->PortOffset + MAC_REG_RCR, pDevice->byOrgRCR);
+                MACvSelectPage1(pDevice->PortOffset);
+                VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR0, pDevice->dwOrgMAR0);
+                VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR4, pDevice->dwOrgMAR4);
+                VNSvInPortB(pDevice->PortOffset + MAC_REG_MSRBBSTS, &byData);
+                pDevice->byBasicMap |= (byData >> 4);
+                VNSvInPortB(pDevice->PortOffset + MAC_REG_CCAFRACTION, &pDevice->byCCAFraction);
+                VNSvInPortB(pDevice->PortOffset + MAC_REG_MSRCTL, &byData);
+                // clear measure control
+                MACvRegBitsOff(pDevice->PortOffset, MAC_REG_MSRCTL, MSRCTL_EN);
+                MACvSelectPage0(pDevice->PortOffset);
+                CARDbSetChannel(pDevice, pDevice->byOrgChannel);
+                // WCMDbResetCommandQueue(pDevice->pMgmt);
+                MACvSelectPage1(pDevice->PortOffset);
+                MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL+1, MSRCTL1_TXPAUSE);
+                MACvSelectPage0(pDevice->PortOffset);
+                if (BITbIsBitOn(byData, MSRCTL_FINISH)) {
+                    // measure success
+                    s_vCompleteCurrentMeasure(pDevice, 0);
+                } else {
+                    // can not measure because not ready before end of measure time
+                    s_vCompleteCurrentMeasure(pDevice, MEASURE_MODE_LATE);
+                }
+            }
+            if (BITbIsBitOn(pDevice->dwIsr, ISR_QUIETSTART)) {
+                do {
+                    ;
+                } while (CARDbStartQuiet(pDevice) == FALSE);
+            }
+        }
+
+        if (pDevice->dwIsr & ISR_TBTT) {
+            if (pDevice->bEnableFirstQuiet == TRUE) {
+                pDevice->byQuietStartCount--;
+                if (pDevice->byQuietStartCount == 0) {
+                    pDevice->bEnableFirstQuiet = FALSE;
+                    MACvSelectPage1(pDevice->PortOffset);
+                    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL, (MSRCTL_QUIETTXCHK | MSRCTL_QUIETEN));
+                    MACvSelectPage0(pDevice->PortOffset);
+                }
+            }
+            if ((pDevice->bChannelSwitch == TRUE) &&
+                (pDevice->eOPMode == OP_MODE_INFRASTRUCTURE)) {
+                pDevice->byChannelSwitchCount--;
+                if (pDevice->byChannelSwitchCount == 0) {
+                    pDevice->bChannelSwitch = FALSE;
+                    CARDbSetChannel(pDevice, pDevice->byNewChannel);
+                    VNTWIFIbChannelSwitch(pDevice->pMgmt, pDevice->byNewChannel);
+                    MACvSelectPage1(pDevice->PortOffset);
+                    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL+1, MSRCTL1_TXPAUSE);
+                    MACvSelectPage0(pDevice->PortOffset);
+                    CARDbStartTxPacket(pDevice, PKT_TYPE_802_11_ALL);
+
+                }
+            }
+            if (pDevice->eOPMode == OP_MODE_ADHOC) {
+                //pDevice->bBeaconSent = FALSE;
+            } else {
+                if ((pDevice->bUpdateBBVGA) && (pDevice->bLinkPass == TRUE) && (pDevice->uCurrRSSI != 0)) {
+                    LONG            ldBm;
+
+                    RFvRSSITodBm(pDevice, (BYTE) pDevice->uCurrRSSI, &ldBm);
+                    for (ii=0;ii<BB_VGA_LEVEL;ii++) {
+                        if (ldBm < pDevice->ldBmThreshold[ii]) {
+                            pDevice->byBBVGANew = pDevice->abyBBVGA[ii];
+                            break;
+                        }
+                    }
+                    if (pDevice->byBBVGANew != pDevice->byBBVGACurrent) {
+                        pDevice->uBBVGADiffCount++;
+                        if (pDevice->uBBVGADiffCount == 1) {
+                            // first VGA diff gain
+                            BBvSetVGAGainOffset(pDevice, pDevice->byBBVGANew);
+                            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"First RSSI[%d] NewGain[%d] OldGain[%d] Count[%d]\n",
+                                            (int)ldBm, pDevice->byBBVGANew, pDevice->byBBVGACurrent, (int)pDevice->uBBVGADiffCount);
+                        }
+                        if (pDevice->uBBVGADiffCount >= BB_VGA_CHANGE_THRESHOLD) {
+                            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"RSSI[%d] NewGain[%d] OldGain[%d] Count[%d]\n",
+                                            (int)ldBm, pDevice->byBBVGANew, pDevice->byBBVGACurrent, (int)pDevice->uBBVGADiffCount);
+                            BBvSetVGAGainOffset(pDevice, pDevice->byBBVGANew);
+                        }
+                    } else {
+                        pDevice->uBBVGADiffCount = 1;
+                    }
+                }
+            }
+
+            pDevice->bBeaconSent = FALSE;
+            if (pDevice->bEnablePSMode) {
+                PSbIsNextTBTTWakeUp((HANDLE)pDevice);
+            };
+
+            if ((pDevice->eOPMode == OP_MODE_AP) ||
+                (pDevice->eOPMode == OP_MODE_ADHOC)) {
+
+                MACvOneShotTimer1MicroSec(pDevice->PortOffset,
+                        (pMgmt->wIBSSBeaconPeriod - MAKE_BEACON_RESERVED) << 10);
+            }
+
+            if (pDevice->eOPMode == OP_MODE_ADHOC && pDevice->pMgmt->wCurrATIMWindow > 0) {
+                // todo adhoc PS mode
+            };
+
+        }
+
+        if (pDevice->dwIsr & ISR_BNTX) {
+
+            if (pDevice->eOPMode == OP_MODE_ADHOC) {
+                pDevice->bIsBeaconBufReadySet = FALSE;
+                pDevice->cbBeaconBufReadySetCnt = 0;
+            };
+
+            if (pDevice->eOPMode == OP_MODE_AP) {
+                if(pMgmt->byDTIMCount > 0) {
+                   pMgmt->byDTIMCount --;
+                   pMgmt->sNodeDBTable[0].bRxPSPoll = FALSE;
+                }
+                else {
+                    if(pMgmt->byDTIMCount == 0) {
+                        // check if mutltcast tx bufferring
+                        pMgmt->byDTIMCount = pMgmt->byDTIMPeriod - 1;
+                        pMgmt->sNodeDBTable[0].bRxPSPoll = TRUE;
+                        bScheduleCommand((HANDLE)pDevice, WLAN_CMD_RX_PSPOLL, NULL);
+                    }
+                }
+            }
+            pDevice->bBeaconSent = TRUE;
+
+            if (pDevice->bChannelSwitch == TRUE) {
+                pDevice->byChannelSwitchCount--;
+                if (pDevice->byChannelSwitchCount == 0) {
+                    pDevice->bChannelSwitch = FALSE;
+                    CARDbSetChannel(pDevice, pDevice->byNewChannel);
+                    VNTWIFIbChannelSwitch(pDevice->pMgmt, pDevice->byNewChannel);
+                    MACvSelectPage1(pDevice->PortOffset);
+                    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL+1, MSRCTL1_TXPAUSE);
+                    MACvSelectPage0(pDevice->PortOffset);
+                    //VNTWIFIbSendBeacon(pDevice->pMgmt);
+                    CARDbStartTxPacket(pDevice, PKT_TYPE_802_11_ALL);
+                }
+            }
+
+        }
+
+        if (pDevice->dwIsr & ISR_RXDMA0) {
+            max_count += device_rx_srv(pDevice, TYPE_RXDMA0);
+        }
+        if (pDevice->dwIsr & ISR_RXDMA1) {
+            max_count += device_rx_srv(pDevice, TYPE_RXDMA1);
+        }
+        if (pDevice->dwIsr & ISR_TXDMA0){
+            max_count += device_tx_srv(pDevice, TYPE_TXDMA0);
+        }
+        if (pDevice->dwIsr & ISR_AC0DMA){
+            max_count += device_tx_srv(pDevice, TYPE_AC0DMA);
+        }
+        if (pDevice->dwIsr & ISR_SOFTTIMER) {
+
+        }
+        if (pDevice->dwIsr & ISR_SOFTTIMER1) {
+            if (pDevice->eOPMode == OP_MODE_AP) {
+               if (pDevice->bShortSlotTime)
+                   pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTSLOTTIME(1);
+               else
+                   pMgmt->wCurrCapInfo &= ~(WLAN_SET_CAP_INFO_SHORTSLOTTIME(1));
+            }
+            bMgrPrepareBeaconToSend(pDevice, pMgmt);
+            pDevice->byCntMeasure = 0;
+        }
+
+        MACvReadISR(pDevice->PortOffset, &pDevice->dwIsr);
+
+        MACvReceive0(pDevice->PortOffset);
+        MACvReceive1(pDevice->PortOffset);
+
+        if (max_count>pDevice->sOpts.int_works)
+            break;
+    }
+
+    if (byOrgPageSel == 1) {
+        MACvSelectPage1(pDevice->PortOffset);
+    }
+
+    spin_unlock_irq(&pDevice->lock);
+    MACvIntEnable(pDevice->PortOffset, IMR_MASK_VALUE);
+
+    return IRQ_RETVAL(handled);
+}
+
+
+static unsigned const ethernet_polynomial = 0x04c11db7U;
+static inline u32 ether_crc(int length, unsigned char *data)
+{
+    int crc = -1;
+
+    while(--length >= 0) {
+        unsigned char current_octet = *data++;
+        int bit;
+        for (bit = 0; bit < 8; bit++, current_octet >>= 1) {
+            crc = (crc << 1) ^
+                ((crc < 0) ^ (current_octet & 1) ? ethernet_polynomial : 0);
+        }
+    }
+    return crc;
+}
+
+//2008-8-4 <add> by chester
+static int Config_FileGetParameter(UCHAR *string, UCHAR *dest,UCHAR *source)
+{
+  UCHAR buf1[100];
+  int source_len = strlen(source);
+
+    memset(buf1,0,100);
+    strcat(buf1, string);
+    strcat(buf1, "=");
+    source+=strlen(buf1);
+
+   memcpy(dest,source,source_len-strlen(buf1));
+ return TRUE;
+}
+
+int Config_FileOperation(PSDevice pDevice,BOOL fwrite,unsigned char *Parameter) {
+    UCHAR    *config_path=CONFIG_PATH;
+    UCHAR    *buffer=NULL;
+    UCHAR      tmpbuffer[20];
+    struct file   *filp=NULL;
+    mm_segment_t old_fs = get_fs();
+    //int oldfsuid=0,oldfsgid=0;
+    int result=0;
+
+    set_fs (KERNEL_DS);
+
+    /* Can't do this anymore, so we rely on correct filesystem permissions:
+    //Make sure a caller can read or write power as root
+    oldfsuid=current->cred->fsuid;
+    oldfsgid=current->cred->fsgid;
+    current->cred->fsuid = 0;
+    current->cred->fsgid = 0;
+    */
+
+    //open file
+      filp = filp_open(config_path, O_RDWR, 0);
+        if (IS_ERR(filp)) {
+	     printk("Config_FileOperation:open file fail?\n");
+	     result=-1;
+             goto error2;
+	  }
+
+     if(!(filp->f_op) || !(filp->f_op->read) ||!(filp->f_op->write)) {
+           printk("file %s cann't readable or writable?\n",config_path);
+	  result = -1;
+	  goto error1;
+     	}
+
+buffer = (UCHAR *)kmalloc(1024, GFP_KERNEL);
+if(buffer==NULL) {
+  printk("alllocate mem for file fail?\n");
+  result = -1;
+  goto error1;
+}
+
+if(filp->f_op->read(filp, buffer, 1024, &filp->f_pos)<0) {
+ printk("read file error?\n");
+ result = -1;
+ goto error1;
+}
+
+if(Config_FileGetParameter("ZONETYPE",tmpbuffer,buffer)!=TRUE) {
+  printk("get parameter error?\n");
+  result = -1;
+  goto error1;
+}
+
+if(memcmp(tmpbuffer,"USA",3)==0) {
+  result=ZoneType_USA;
+}
+else if(memcmp(tmpbuffer,"JAPAN",5)==0) {
+  result=ZoneType_Japan;
+}
+else if(memcmp(tmpbuffer,"EUROPE",5)==0) {
+ result=ZoneType_Europe;
+}
+else {
+  result = -1;
+  printk("Unknown Zonetype[%s]?\n",tmpbuffer);
+}
+
+error1:
+  if(buffer)
+  	 kfree(buffer);
+
+  if(filp_close(filp,NULL))
+       printk("Config_FileOperation:close file fail\n");
+
+error2:
+  set_fs (old_fs);
+
+  /*
+  current->cred->fsuid=oldfsuid;
+  current->cred->fsgid=oldfsgid;
+  */
+
+  return result;
+}
+
+
+#ifdef PRIVATE_OBJ
+
+void __device_set_multi(HANDLE pExDevice) {
+    PSDevice_info pDevice_info = (PSDevice_info)pExDevice;
+    ref_net_device  *dev = &(pDevice_info->ref_dev);
+    PSDevice    pDevice = (PSDevice)(pDevice_info->pWDevice);
+
+#else
+
+static void device_set_multi(struct net_device *dev) {
+    PSDevice         pDevice = (PSDevice) netdev_priv(dev);
+#endif
+
+    PSMgmtObject     pMgmt = pDevice->pMgmt;
+    u32              mc_filter[2];
+    int              i;
+    struct dev_mc_list  *mclist;
+
+
+    VNSvInPortB(pDevice->PortOffset + MAC_REG_RCR, &(pDevice->byRxMode));
+
+#ifdef PRIVATE_OBJ
+    if (*(dev->flags) & IFF_PROMISC) {         /* Set promiscuous. */
+        DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: Promiscuous mode enabled.\n", pDevice->dev->name);
+
+#else
+    if (dev->flags & IFF_PROMISC) {         /* Set promiscuous. */
+        DEVICE_PRT(MSG_LEVEL_ERR,KERN_NOTICE "%s: Promiscuous mode enabled.\n", dev->name);
+#endif
+        /* Unconditionally log net taps. */
+        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST|RCR_UNICAST);
+    }
+#ifdef PRIVATE_OBJ
+    else if ((*(dev->mc_count) > pDevice->multicast_limit)
+        ||  (*(dev->flags) & IFF_ALLMULTI)) {
+#else
+    else if ((dev->mc_count > pDevice->multicast_limit)
+        ||  (dev->flags & IFF_ALLMULTI)) {
+#endif
+        MACvSelectPage1(pDevice->PortOffset);
+        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR0, 0xffffffff);
+        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR0 + 4, 0xffffffff);
+        MACvSelectPage0(pDevice->PortOffset);
+        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST);
+    }
+    else {
+        memset(mc_filter, 0, sizeof(mc_filter));
+#ifdef PRIVATE_OBJ
+        for (i = 0, mclist = dev->mc_list; mclist && i < *(dev->mc_count);
+             i++, mclist = mclist->next) {
+#else
+        for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
+             i++, mclist = mclist->next) {
+#endif
+            int bit_nr = ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26;
+            mc_filter[bit_nr >> 5] |= cpu_to_le32(1 << (bit_nr & 31));
+        }
+        MACvSelectPage1(pDevice->PortOffset);
+        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR0, mc_filter[0]);
+        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR0 + 4, mc_filter[1]);
+        MACvSelectPage0(pDevice->PortOffset);
+        pDevice->byRxMode &= ~(RCR_UNICAST);
+        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST);
+    }
+
+    if (pMgmt->eConfigMode == WMAC_CONFIG_AP) {
+        // If AP mode, don't enable RCR_UNICAST. Since hw only compare addr1 with local mac.
+        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST);
+        pDevice->byRxMode &= ~(RCR_UNICAST);
+    }
+
+    VNSvOutPortB(pDevice->PortOffset + MAC_REG_RCR, pDevice->byRxMode);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->byRxMode = %x\n", pDevice->byRxMode );
+}
+
+
+#ifdef PRIVATE_OBJ
+
+struct net_device_stats *__device_get_stats(HANDLE pExDevice) {
+    PSDevice_info pDevice_info = (PSDevice_info)pExDevice;
+    PSDevice    pDevice = (PSDevice)(pDevice_info->pWDevice);
+
+#else
+static struct net_device_stats *device_get_stats(struct net_device *dev) {
+    PSDevice pDevice=(PSDevice) netdev_priv(dev);
+#endif
+
+    return &pDevice->stats;
+}
+
+
+#ifdef PRIVATE_OBJ
+
+int __device_ioctl(HANDLE pExDevice, struct ifreq *rq, int cmd) {
+    PSDevice_info pDevice_info = (PSDevice_info)pExDevice;
+    struct net_device *dev = pDevice_info->dev;
+    PSDevice    pDevice = (PSDevice)(pDevice_info->pWDevice);
+
+#else
+
+static int  device_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) {
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+#endif
+
+#ifdef WIRELESS_EXT
+	struct iwreq *wrq = (struct iwreq *) rq;
+	int                 rc =0;
+#endif
+    PSMgmtObject        pMgmt = pDevice->pMgmt;
+    PSCmdRequest        pReq;
+
+
+    if (pMgmt == NULL) {
+        rc = -EFAULT;
+        return rc;
+    }
+
+    switch(cmd) {
+
+#ifdef WIRELESS_EXT
+//#if WIRELESS_EXT < 13
+
+	case SIOCGIWNAME:
+		rc = iwctl_giwname(dev, NULL, (char *)&(wrq->u.name), NULL);
+		break;
+
+	case SIOCGIWNWID:     //0x8b03  support
+	#ifdef  WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+          rc = iwctl_giwnwid(dev, NULL, &(wrq->u.nwid), NULL);
+	#else
+        rc = -EOPNOTSUPP;
+	#endif
+		break;
+
+		// Set frequency/channel
+	case SIOCSIWFREQ:
+	    rc = iwctl_siwfreq(dev, NULL, &(wrq->u.freq), NULL);
+		break;
+
+		// Get frequency/channel
+	case SIOCGIWFREQ:
+		rc = iwctl_giwfreq(dev, NULL, &(wrq->u.freq), NULL);
+		break;
+
+		// Set desired network name (ESSID)
+	case SIOCSIWESSID:
+
+		{
+			char essid[IW_ESSID_MAX_SIZE+1];
+			if (wrq->u.essid.length > IW_ESSID_MAX_SIZE) {
+				rc = -E2BIG;
+				break;
+			}
+			if (copy_from_user(essid, wrq->u.essid.pointer,
+					   wrq->u.essid.length)) {
+				rc = -EFAULT;
+				break;
+			}
+			rc = iwctl_siwessid(dev, NULL,
+					    &(wrq->u.essid), essid);
+		}
+		break;
+
+
+		// Get current network name (ESSID)
+	case SIOCGIWESSID:
+
+		{
+			char essid[IW_ESSID_MAX_SIZE+1];
+			if (wrq->u.essid.pointer)
+				rc = iwctl_giwessid(dev, NULL,
+						    &(wrq->u.essid), essid);
+				if (copy_to_user(wrq->u.essid.pointer,
+						         essid,
+						         wrq->u.essid.length) )
+					rc = -EFAULT;
+		}
+		break;
+
+	case SIOCSIWAP:
+
+		rc = iwctl_siwap(dev, NULL, &(wrq->u.ap_addr), NULL);
+		break;
+
+
+		// Get current Access Point (BSSID)
+	case SIOCGIWAP:
+		rc = iwctl_giwap(dev, NULL, &(wrq->u.ap_addr), NULL);
+		break;
+
+
+		// Set desired station name
+	case SIOCSIWNICKN:
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWNICKN \n");
+        rc = -EOPNOTSUPP;
+		break;
+
+		// Get current station name
+	case SIOCGIWNICKN:
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWNICKN \n");
+        rc = -EOPNOTSUPP;
+		break;
+
+		// Set the desired bit-rate
+	case SIOCSIWRATE:
+		rc = iwctl_siwrate(dev, NULL, &(wrq->u.bitrate), NULL);
+		break;
+
+	// Get the current bit-rate
+	case SIOCGIWRATE:
+
+		rc = iwctl_giwrate(dev, NULL, &(wrq->u.bitrate), NULL);
+		break;
+
+	// Set the desired RTS threshold
+	case SIOCSIWRTS:
+
+		rc = iwctl_siwrts(dev, NULL, &(wrq->u.rts), NULL);
+		break;
+
+	// Get the current RTS threshold
+	case SIOCGIWRTS:
+
+		rc = iwctl_giwrts(dev, NULL, &(wrq->u.rts), NULL);
+		break;
+
+		// Set the desired fragmentation threshold
+	case SIOCSIWFRAG:
+
+		rc = iwctl_siwfrag(dev, NULL, &(wrq->u.frag), NULL);
+	    break;
+
+	// Get the current fragmentation threshold
+	case SIOCGIWFRAG:
+
+		rc = iwctl_giwfrag(dev, NULL, &(wrq->u.frag), NULL);
+		break;
+
+		// Set mode of operation
+	case SIOCSIWMODE:
+    	rc = iwctl_siwmode(dev, NULL, &(wrq->u.mode), NULL);
+		break;
+
+		// Get mode of operation
+	case SIOCGIWMODE:
+		rc = iwctl_giwmode(dev, NULL, &(wrq->u.mode), NULL);
+		break;
+
+		// Set WEP keys and mode
+	case SIOCSIWENCODE:
+		{
+            char abyKey[WLAN_WEP232_KEYLEN];
+
+			if (wrq->u.encoding.pointer) {
+
+
+				if (wrq->u.encoding.length > WLAN_WEP232_KEYLEN) {
+					rc = -E2BIG;
+					break;
+				}
+				memset(abyKey, 0, WLAN_WEP232_KEYLEN);
+				if (copy_from_user(abyKey,
+				                  wrq->u.encoding.pointer,
+				                  wrq->u.encoding.length)) {
+					rc = -EFAULT;
+					break;
+				}
+			} else if (wrq->u.encoding.length != 0) {
+				rc = -EINVAL;
+				break;
+			}
+			rc = iwctl_siwencode(dev, NULL, &(wrq->u.encoding), abyKey);
+		}
+		break;
+
+		// Get the WEP keys and mode
+	case SIOCGIWENCODE:
+
+		if (!capable(CAP_NET_ADMIN)) {
+			rc = -EPERM;
+			break;
+		}
+		{
+		    char abyKey[WLAN_WEP232_KEYLEN];
+
+		    rc = iwctl_giwencode(dev, NULL, &(wrq->u.encoding), abyKey);
+		    if (rc != 0) break;
+			if (wrq->u.encoding.pointer) {
+				if (copy_to_user(wrq->u.encoding.pointer,
+						        abyKey,
+						        wrq->u.encoding.length))
+					rc = -EFAULT;
+			}
+		}
+		break;
+
+#if WIRELESS_EXT > 9
+		// Get the current Tx-Power
+	case SIOCGIWTXPOW:
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWTXPOW \n");
+        rc = -EOPNOTSUPP;
+		break;
+
+	case SIOCSIWTXPOW:
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWTXPOW \n");
+        rc = -EOPNOTSUPP;
+		break;
+
+#endif // WIRELESS_EXT > 9
+
+#if WIRELESS_EXT > 10
+	case SIOCSIWRETRY:
+
+		rc = iwctl_siwretry(dev, NULL, &(wrq->u.retry), NULL);
+		break;
+
+	case SIOCGIWRETRY:
+
+		rc = iwctl_giwretry(dev, NULL, &(wrq->u.retry), NULL);
+		break;
+
+#endif // WIRELESS_EXT > 10
+
+		// Get range of parameters
+	case SIOCGIWRANGE:
+
+		{
+			struct iw_range range;
+
+			rc = iwctl_giwrange(dev, NULL, &(wrq->u.data), (char *) &range);
+			if (copy_to_user(wrq->u.data.pointer, &range, sizeof(struct iw_range)))
+				rc = -EFAULT;
+		}
+
+		break;
+
+	case SIOCGIWPOWER:
+
+		rc = iwctl_giwpower(dev, NULL, &(wrq->u.power), NULL);
+		break;
+
+
+	case SIOCSIWPOWER:
+
+		rc = iwctl_siwpower(dev, NULL, &(wrq->u.power), NULL);
+		break;
+
+
+	case SIOCGIWSENS:
+
+	    rc = iwctl_giwsens(dev, NULL, &(wrq->u.sens), NULL);
+		break;
+
+	case SIOCSIWSENS:
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWSENS \n");
+		rc = -EOPNOTSUPP;
+		break;
+
+	case SIOCGIWAPLIST:
+	    {
+            char buffer[IW_MAX_AP * (sizeof(struct sockaddr) + sizeof(struct iw_quality))];
+
+		    if (wrq->u.data.pointer) {
+		        rc = iwctl_giwaplist(dev, NULL, &(wrq->u.data), buffer);
+		        if (rc == 0) {
+                    if (copy_to_user(wrq->u.data.pointer,
+					                buffer,
+					               (wrq->u.data.length * (sizeof(struct sockaddr) +  sizeof(struct iw_quality)))
+				        ))
+				    rc = -EFAULT;
+		        }
+            }
+        }
+		break;
+
+
+#ifdef WIRELESS_SPY
+		// Set the spy list
+	case SIOCSIWSPY:
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWSPY \n");
+		rc = -EOPNOTSUPP;
+		break;
+
+		// Get the spy list
+	case SIOCGIWSPY:
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWSPY \n");
+		rc = -EOPNOTSUPP;
+		break;
+
+#endif // WIRELESS_SPY
+
+	case SIOCGIWPRIV:
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWPRIV \n");
+		rc = -EOPNOTSUPP;
+/*
+		if(wrq->u.data.pointer) {
+			wrq->u.data.length = sizeof(iwctl_private_args) / sizeof( iwctl_private_args[0]);
+
+			if(copy_to_user(wrq->u.data.pointer,
+					(u_char *) iwctl_private_args,
+					sizeof(iwctl_private_args)))
+				rc = -EFAULT;
+		}
+*/
+		break;
+
+
+//#endif // WIRELESS_EXT < 13
+//2008-0409-07, <Add> by Einsn Liu
+#ifdef  WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+	case SIOCSIWAUTH:
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWAUTH \n");
+		rc = iwctl_siwauth(dev, NULL, &(wrq->u.param), NULL);
+		break;
+
+	case SIOCGIWAUTH:
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWAUTH \n");
+		rc = iwctl_giwauth(dev, NULL, &(wrq->u.param), NULL);
+		break;
+
+	case SIOCSIWGENIE:
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWGENIE \n");
+		rc = iwctl_siwgenie(dev, NULL, &(wrq->u.data), wrq->u.data.pointer);
+		break;
+
+	case SIOCGIWGENIE:
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWGENIE \n");
+		rc = iwctl_giwgenie(dev, NULL, &(wrq->u.data), wrq->u.data.pointer);
+		break;
+
+	case SIOCSIWENCODEEXT:
+		{
+			char extra[sizeof(struct iw_encode_ext)+MAX_KEY_LEN+1];
+			DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWENCODEEXT \n");
+			if(wrq->u.encoding.pointer){
+				memset(extra, 0, sizeof(struct iw_encode_ext)+MAX_KEY_LEN+1);
+				if(wrq->u.encoding.length > (sizeof(struct iw_encode_ext)+ MAX_KEY_LEN)){
+					rc = -E2BIG;
+					break;
+				}
+				if(copy_from_user(extra, wrq->u.encoding.pointer,wrq->u.encoding.length)){
+					rc = -EFAULT;
+					break;
+				}
+			}else if(wrq->u.encoding.length != 0){
+				rc = -EINVAL;
+				break;
+			}
+			rc = iwctl_siwencodeext(dev, NULL, &(wrq->u.encoding), extra);
+		}
+		break;
+
+	case SIOCGIWENCODEEXT:
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWENCODEEXT \n");
+		rc = iwctl_giwencodeext(dev, NULL, &(wrq->u.encoding), NULL);
+		break;
+
+	case SIOCSIWMLME:
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWMLME \n");
+		rc = iwctl_siwmlme(dev, NULL, &(wrq->u.data), wrq->u.data.pointer);
+		break;
+
+#endif // #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+//End Add -- //2008-0409-07, <Add> by Einsn Liu
+
+#endif // WIRELESS_EXT
+
+    case IOCTL_CMD_TEST:
+
+		if (!(pDevice->flags & DEVICE_FLAGS_OPENED)) {
+		    rc = -EFAULT;
+		    break;
+		} else {
+		    rc = 0;
+		}
+        pReq = (PSCmdRequest)rq;
+        pReq->wResult = MAGIC_CODE;
+        break;
+
+    case IOCTL_CMD_SET:
+
+               #ifdef SndEvt_ToAPI
+                  if((((PSCmdRequest)rq)->wCmdCode !=WLAN_CMD_SET_EVT) &&
+		       !(pDevice->flags & DEVICE_FLAGS_OPENED))
+	      #else
+		if (!(pDevice->flags & DEVICE_FLAGS_OPENED) &&
+		       (((PSCmdRequest)rq)->wCmdCode !=WLAN_CMD_SET_WPA))
+	      #endif
+		{
+		    rc = -EFAULT;
+		    break;
+		} else {
+		    rc = 0;
+		}
+
+	    if (test_and_set_bit( 0, (void*)&(pMgmt->uCmdBusy))) {
+		    return -EBUSY;
+	    }
+        rc = private_ioctl(pDevice, rq);
+        clear_bit( 0, (void*)&(pMgmt->uCmdBusy));
+        break;
+
+    case IOCTL_CMD_HOSTAPD:
+
+
+#if WIRELESS_EXT > 8
+		rc = hostap_ioctl(pDevice, &wrq->u.data);
+#else // WIRELESS_EXT > 8
+		rc = hostap_ioctl(pDevice, (struct iw_point *) &wrq->u.data);
+#endif // WIRELESS_EXT > 8
+        break;
+
+    case IOCTL_CMD_WPA:
+
+#if WIRELESS_EXT > 8
+		rc = wpa_ioctl(pDevice, &wrq->u.data);
+#else // WIRELESS_EXT > 8
+		rc = wpa_ioctl(pDevice, (struct iw_point *) &wrq->u.data);
+#endif // WIRELESS_EXT > 8
+        break;
+
+	case SIOCETHTOOL:
+        return ethtool_ioctl(dev, (void *) rq->ifr_data);
+	// All other calls are currently unsupported
+
+	default:
+		rc = -EOPNOTSUPP;
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Ioctl command not support..%x\n", cmd);
+
+
+    }
+
+    if (pDevice->bCommit) {
+       if (pMgmt->eConfigMode == WMAC_CONFIG_AP) {
+           netif_stop_queue(pDevice->dev);
+           spin_lock_irq(&pDevice->lock);
+           bScheduleCommand((HANDLE)pDevice, WLAN_CMD_RUN_AP, NULL);
+           spin_unlock_irq(&pDevice->lock);
+       }
+       else {
+           DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Commit the settings\n");
+           spin_lock_irq(&pDevice->lock);
+           pDevice->bLinkPass = FALSE;
+           memset(pMgmt->abyCurrBSSID, 0, 6);
+           pMgmt->eCurrState = WMAC_STATE_IDLE;
+           netif_stop_queue(pDevice->dev);
+	#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+	      pMgmt->eScanType = WMAC_SCAN_ACTIVE;
+	 if(pDevice->bWPASuppWextEnabled !=TRUE)
+	 #endif
+           bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, pMgmt->abyDesireSSID);
+           bScheduleCommand((HANDLE) pDevice, WLAN_CMD_SSID, NULL);
+           spin_unlock_irq(&pDevice->lock);
+      }
+      pDevice->bCommit = FALSE;
+    }
+
+    return rc;
+}
+
+
+static int ethtool_ioctl(struct net_device *dev, void *useraddr)
+{
+	u32 ethcmd;
+
+	if (copy_from_user(&ethcmd, useraddr, sizeof(ethcmd)))
+		return -EFAULT;
+
+        switch (ethcmd) {
+	case ETHTOOL_GDRVINFO: {
+		struct ethtool_drvinfo info = {ETHTOOL_GDRVINFO};
+		strncpy(info.driver, DEVICE_NAME, sizeof(info.driver)-1);
+		strncpy(info.version, DEVICE_VERSION, sizeof(info.version)-1);
+		if (copy_to_user(useraddr, &info, sizeof(info)))
+			return -EFAULT;
+		return 0;
+	}
+
+        }
+
+	return -EOPNOTSUPP;
+}
+
+/*------------------------------------------------------------------*/
+#ifndef PRIVATE_OBJ
+
+MODULE_DEVICE_TABLE(pci, device_id_table);
+
+static struct pci_driver device_driver = {
+        name:       DEVICE_NAME,
+        id_table:   device_id_table,
+        probe:      device_found1,
+        remove:     device_remove1,
+#ifdef CONFIG_PM
+        suspend:    viawget_suspend,
+        resume:     viawget_resume,
+#endif
+};
+
+static int __init device_init_module(void)
+{
+    int ret;
+
+
+//    ret=pci_module_init(&device_driver);
+	//ret = pcie_port_service_register(&device_driver);
+	ret = pci_register_driver(&device_driver);
+#ifdef CONFIG_PM
+    if(ret >= 0)
+        register_reboot_notifier(&device_notifier);
+#endif
+
+    return ret;
+}
+
+static void __exit device_cleanup_module(void)
+{
+
+
+#ifdef CONFIG_PM
+    unregister_reboot_notifier(&device_notifier);
+#endif
+    pci_unregister_driver(&device_driver);
+
+}
+
+module_init(device_init_module);
+module_exit(device_cleanup_module);
+
+
+#ifdef CONFIG_PM
+static int
+device_notify_reboot(struct notifier_block *nb, unsigned long event, void *p)
+{
+    struct pci_dev *pdev = NULL;
+    switch(event) {
+    case SYS_DOWN:
+    case SYS_HALT:
+    case SYS_POWER_OFF:
+        while ((pdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pdev)) != NULL) {
+            if(pci_dev_driver(pdev) == &device_driver) {
+                if (pci_get_drvdata(pdev))
+                    viawget_suspend(pdev, 3);
+            }
+        }
+    }
+    return NOTIFY_DONE;
+}
+
+static int
+viawget_suspend(struct pci_dev *pcid, u32 state)
+{
+    int power_status;   // to silence the compiler
+
+    PSDevice pDevice=pci_get_drvdata(pcid);
+    PSMgmtObject  pMgmt = pDevice->pMgmt;
+
+    netif_stop_queue(pDevice->dev);
+    spin_lock_irq(&pDevice->lock);
+    pci_save_state(pcid);
+    del_timer(&pDevice->sTimerCommand);
+    del_timer(&pMgmt->sTimerSecondCallback);
+    pDevice->cbFreeCmdQueue = CMD_Q_SIZE;
+    pDevice->uCmdDequeueIdx = 0;
+    pDevice->uCmdEnqueueIdx = 0;
+    pDevice->bCmdRunning = FALSE;
+    MACbShutdown(pDevice->PortOffset);
+    MACvSaveContext(pDevice->PortOffset, pDevice->abyMacContext);
+    pDevice->bLinkPass = FALSE;
+    memset(pMgmt->abyCurrBSSID, 0, 6);
+    pMgmt->eCurrState = WMAC_STATE_IDLE;
+    pci_disable_device(pcid);
+    power_status = pci_set_power_state(pcid, state);
+    spin_unlock_irq(&pDevice->lock);
+    return 0;
+}
+
+static int
+viawget_resume(struct pci_dev *pcid)
+{
+    PSDevice  pDevice=pci_get_drvdata(pcid);
+    PSMgmtObject  pMgmt = pDevice->pMgmt;
+    int power_status;   // to silence the compiler
+
+
+    power_status = pci_set_power_state(pcid, 0);
+    power_status = pci_enable_wake(pcid, 0, 0);
+    pci_restore_state(pcid);
+    if (netif_running(pDevice->dev)) {
+        spin_lock_irq(&pDevice->lock);
+        MACvRestoreContext(pDevice->PortOffset, pDevice->abyMacContext);
+        device_init_registers(pDevice, DEVICE_INIT_DXPL);
+        if (pMgmt->sNodeDBTable[0].bActive == TRUE) { // Assoc with BSS
+            pMgmt->sNodeDBTable[0].bActive = FALSE;
+            pDevice->bLinkPass = FALSE;
+            if(pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+                // In Adhoc, BSS state set back to started.
+                pMgmt->eCurrState = WMAC_STATE_STARTED;
+           }
+            else {
+                pMgmt->eCurrMode = WMAC_MODE_STANDBY;
+                pMgmt->eCurrState = WMAC_STATE_IDLE;
+            }
+        }
+        init_timer(&pMgmt->sTimerSecondCallback);
+        init_timer(&pDevice->sTimerCommand);
+        MACvIntEnable(pDevice->PortOffset, IMR_MASK_VALUE);
+        BSSvClearBSSList((HANDLE)pDevice, pDevice->bLinkPass);
+        bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, NULL);
+        bScheduleCommand((HANDLE) pDevice, WLAN_CMD_SSID, NULL);
+        spin_unlock_irq(&pDevice->lock);
+    }
+    return 0;
+}
+
+#endif
+
+#endif //#ifndef PRIVATE_OBJ
+
+#ifdef PRIVATE_OBJ
+
+
+int __device_hw_reset(HANDLE pExDevice){
+     PSDevice_info pDevice_info = (PSDevice_info)pExDevice;
+
+     return MACbSoftwareReset(pDevice_info->port_offset);
+}
+
+
+int __device_hw_init(HANDLE pExDevice){
+    PSDevice_info pDevice_info = (PSDevice_info)pExDevice;
+    PSDevice    pDevice;
+
+    pDevice = (PSDevice)kmalloc(sizeof(DEVICE_INFO), (int)GFP_ATOMIC);
+    if (pDevice == NULL)
+        return FALSE;
+
+    memset(pDevice, 0, sizeof(DEVICE_INFO));
+    pDevice_info->pWDevice = pDevice;
+    pDevice->PortOffset = pDevice_info->port_offset;
+    pDevice->dev = pDevice_info->dev;
+    pDevice->pcid = pDevice_info->pcid;
+    pDevice->chip_id = pDevice_info->chip_id;
+    pDevice->memaddr = pDevice_info->mem_addr;
+    pDevice->ioaddr = pDevice_info->io_addr;
+    pDevice->io_size = pDevice_info->io_size;
+    pDevice->nTxQueues = pDevice_info->nTxQueues;
+    pDevice->multicast_limit = pDevice_info->multicast_limit;
+    pDevice->sMgmtObj.pAdapter = (PVOID)pDevice;
+    pDevice->pMgmt = &(pDevice->sMgmtObj);
+    MACvInitialize(pDevice->PortOffset);
+    device_get_options(pDevice, 0 , pDevice_info->dev->name);
+    device_set_options(pDevice);
+    pDevice->sOpts.flags &= pDevice_info->flags;
+    pDevice->flags = pDevice->sOpts.flags | (pDevice_info->flags & 0xFF000000UL);
+    spin_lock_init(&(pDevice->lock));
+
+    return TRUE;
+}
+
+
+void __device_read_mac(HANDLE pExDevice, PBYTE dev_addr){
+    PSDevice_info pDevice_info = (PSDevice_info)pExDevice;
+    PSDevice    pDevice = (PSDevice)(pDevice_info->pWDevice);
+
+    MACvReadEtherAddress(pDevice->PortOffset, dev_addr);
+    return;
+}
+
+
+#endif
+
+
diff --git a/drivers/staging/vt6655/dpc.c b/drivers/staging/vt6655/dpc.c
new file mode 100644
index 0000000..acc6d82
--- /dev/null
+++ b/drivers/staging/vt6655/dpc.c
@@ -0,0 +1,1668 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: dpc.c
+ *
+ * Purpose: handle dpc rx functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 20, 2003
+ *
+ * Functions:
+ *      device_receive_frame - Rcv 802.11 frame function
+ *      s_bAPModeRxCtl- AP Rcv frame filer Ctl.
+ *      s_bAPModeRxData- AP Rcv data frame handle
+ *      s_bHandleRxEncryption- Rcv decrypted data via on-fly
+ *      s_bHostWepRxEncryption- Rcv encrypted data via host
+ *      s_byGetRateIdx- get rate index
+ *      s_vGetDASA- get data offset
+ *      s_vProcessRxMACHeader- Rcv 802.11 and translate to 802.3
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__RXTX_H__)
+#include "rxtx.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__BSSDB_H__)
+#include "bssdb.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__MICHAEL_H__)
+#include "michael.h"
+#endif
+#if !defined(__TKIP_H__)
+#include "tkip.h"
+#endif
+#if !defined(__TCRC_H__)
+#include "tcrc.h"
+#endif
+#if !defined(__WCTL_H__)
+#include "wctl.h"
+#endif
+#if !defined(__WROUTE_H__)
+#include "wroute.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__HOSTAP_H__)
+#include "hostap.h"
+#endif
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+#if !defined(__IOWPA_H__)
+#include "iowpa.h"
+#endif
+#if !defined(__AES_H__)
+#include "aes_ccmp.h"
+#endif
+
+//#define	PLICE_DEBUG
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+static int          msglevel                =MSG_LEVEL_INFO;
+
+const BYTE acbyRxRate[MAX_RATE] =
+{2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108};
+
+
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Functions  --------------------------*/
+
+static BYTE s_byGetRateIdx(IN BYTE byRate);
+
+
+static
+VOID
+s_vGetDASA(
+    IN  PBYTE pbyRxBufferAddr,
+    OUT PUINT pcbHeaderSize,
+    OUT PSEthernetHeader psEthHeader
+    );
+
+static
+VOID
+s_vProcessRxMACHeader (
+    IN  PSDevice pDevice,
+    IN  PBYTE pbyRxBufferAddr,
+    IN  UINT cbPacketSize,
+    IN  BOOL bIsWEP,
+    IN  BOOL bExtIV,
+    OUT PUINT pcbHeadSize
+    );
+
+static BOOL s_bAPModeRxCtl(
+    IN PSDevice pDevice,
+    IN PBYTE    pbyFrame,
+    IN INT      iSANodeIndex
+    );
+
+#ifdef PRIVATE_OBJ
+
+static BOOL s_bAPModeRxData (
+    IN PSDevice pDevice,
+    IN ref_sk_buff* skb,
+    IN UINT     FrameSize,
+    IN UINT     cbHeaderOffset,
+    IN INT      iSANodeIndex,
+    IN INT      iDANodeIndex
+    );
+#else
+
+static BOOL s_bAPModeRxData (
+    IN PSDevice pDevice,
+    IN struct sk_buff* skb,
+    IN UINT     FrameSize,
+    IN UINT     cbHeaderOffset,
+    IN INT      iSANodeIndex,
+    IN INT      iDANodeIndex
+    );
+#endif
+
+
+static BOOL s_bHandleRxEncryption(
+    IN PSDevice     pDevice,
+    IN PBYTE        pbyFrame,
+    IN UINT         FrameSize,
+    IN PBYTE        pbyRsr,
+    OUT PBYTE       pbyNewRsr,
+    OUT PSKeyItem   *pKeyOut,
+    OUT PBOOL       pbExtIV,
+    OUT PWORD       pwRxTSC15_0,
+    OUT PDWORD      pdwRxTSC47_16
+    );
+
+static BOOL s_bHostWepRxEncryption(
+
+    IN PSDevice     pDevice,
+    IN PBYTE        pbyFrame,
+    IN UINT         FrameSize,
+    IN PBYTE        pbyRsr,
+    IN BOOL         bOnFly,
+    IN PSKeyItem    pKey,
+    OUT PBYTE       pbyNewRsr,
+    OUT PBOOL       pbExtIV,
+    OUT PWORD       pwRxTSC15_0,
+    OUT PDWORD      pdwRxTSC47_16
+
+    );
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*+
+ *
+ * Description:
+ *    Translate Rcv 802.11 header to 802.3 header with Rx buffer
+ *
+ * Parameters:
+ *  In:
+ *      pDevice
+ *      dwRxBufferAddr  - Address of Rcv Buffer
+ *      cbPacketSize    - Rcv Packet size
+ *      bIsWEP          - If Rcv with WEP
+ *  Out:
+ *      pcbHeaderSize   - 802.11 header size
+ *
+ * Return Value: None
+ *
+-*/
+static
+VOID
+s_vProcessRxMACHeader (
+    IN  PSDevice pDevice,
+    IN  PBYTE pbyRxBufferAddr,
+    IN  UINT cbPacketSize,
+    IN  BOOL bIsWEP,
+    IN  BOOL bExtIV,
+    OUT PUINT pcbHeadSize
+    )
+{
+    PBYTE           pbyRxBuffer;
+    UINT            cbHeaderSize = 0;
+    PWORD           pwType;
+    PS802_11Header  pMACHeader;
+    int             ii;
+
+
+    pMACHeader = (PS802_11Header) (pbyRxBufferAddr + cbHeaderSize);
+
+    s_vGetDASA((PBYTE)pMACHeader, &cbHeaderSize, &pDevice->sRxEthHeader);
+
+    if (bIsWEP) {
+        if (bExtIV) {
+            // strip IV&ExtIV , add 8 byte
+            cbHeaderSize += (WLAN_HDR_ADDR3_LEN + 8);
+        } else {
+            // strip IV , add 4 byte
+            cbHeaderSize += (WLAN_HDR_ADDR3_LEN + 4);
+        }
+    }
+    else {
+        cbHeaderSize += WLAN_HDR_ADDR3_LEN;
+    };
+
+    pbyRxBuffer = (PBYTE) (pbyRxBufferAddr + cbHeaderSize);
+    if (IS_ETH_ADDRESS_EQUAL(pbyRxBuffer, &pDevice->abySNAP_Bridgetunnel[0])) {
+        cbHeaderSize += 6;
+    }
+    else if (IS_ETH_ADDRESS_EQUAL(pbyRxBuffer, &pDevice->abySNAP_RFC1042[0])) {
+        cbHeaderSize += 6;
+        pwType = (PWORD) (pbyRxBufferAddr + cbHeaderSize);
+        if ((*pwType!= TYPE_PKT_IPX) && (*pwType != cpu_to_le16(0xF380))) {
+        }
+        else {
+            cbHeaderSize -= 8;
+            pwType = (PWORD) (pbyRxBufferAddr + cbHeaderSize);
+            if (bIsWEP) {
+                if (bExtIV) {
+                    *pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN - 8);    // 8 is IV&ExtIV
+                } else {
+                    *pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN - 4);    // 4 is IV
+                }
+            }
+            else {
+                *pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN);
+            }
+        }
+    }
+    else {
+        cbHeaderSize -= 2;
+        pwType = (PWORD) (pbyRxBufferAddr + cbHeaderSize);
+        if (bIsWEP) {
+            if (bExtIV) {
+                *pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN - 8);    // 8 is IV&ExtIV
+            } else {
+                *pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN - 4);    // 4 is IV
+            }
+        }
+        else {
+            *pwType = htons(cbPacketSize - WLAN_HDR_ADDR3_LEN);
+        }
+    }
+
+    cbHeaderSize -= (U_ETHER_ADDR_LEN * 2);
+    pbyRxBuffer = (PBYTE) (pbyRxBufferAddr + cbHeaderSize);
+    for(ii=0;ii<U_ETHER_ADDR_LEN;ii++)
+        *pbyRxBuffer++ = pDevice->sRxEthHeader.abyDstAddr[ii];
+    for(ii=0;ii<U_ETHER_ADDR_LEN;ii++)
+        *pbyRxBuffer++ = pDevice->sRxEthHeader.abySrcAddr[ii];
+
+    *pcbHeadSize = cbHeaderSize;
+}
+
+
+
+
+static BYTE s_byGetRateIdx (IN BYTE byRate)
+{
+    BYTE    byRateIdx;
+
+    for (byRateIdx = 0; byRateIdx <MAX_RATE ; byRateIdx++) {
+        if (acbyRxRate[byRateIdx%MAX_RATE] == byRate)
+            return byRateIdx;
+    }
+    return 0;
+}
+
+
+static
+VOID
+s_vGetDASA (
+    IN  PBYTE pbyRxBufferAddr,
+    OUT PUINT pcbHeaderSize,
+    OUT PSEthernetHeader psEthHeader
+    )
+{
+    UINT            cbHeaderSize = 0;
+    PS802_11Header  pMACHeader;
+    int             ii;
+
+    pMACHeader = (PS802_11Header) (pbyRxBufferAddr + cbHeaderSize);
+
+    if ((pMACHeader->wFrameCtl & FC_TODS) == 0) {
+        if (pMACHeader->wFrameCtl & FC_FROMDS) {
+            for(ii=0;ii<U_ETHER_ADDR_LEN;ii++) {
+                psEthHeader->abyDstAddr[ii] = pMACHeader->abyAddr1[ii];
+                psEthHeader->abySrcAddr[ii] = pMACHeader->abyAddr3[ii];
+            }
+        }
+        else {
+            // IBSS mode
+            for(ii=0;ii<U_ETHER_ADDR_LEN;ii++) {
+                psEthHeader->abyDstAddr[ii] = pMACHeader->abyAddr1[ii];
+                psEthHeader->abySrcAddr[ii] = pMACHeader->abyAddr2[ii];
+            }
+        }
+    }
+    else {
+        // Is AP mode..
+        if (pMACHeader->wFrameCtl & FC_FROMDS) {
+            for(ii=0;ii<U_ETHER_ADDR_LEN;ii++) {
+                psEthHeader->abyDstAddr[ii] = pMACHeader->abyAddr3[ii];
+                psEthHeader->abySrcAddr[ii] = pMACHeader->abyAddr4[ii];
+                cbHeaderSize += 6;
+            }
+        }
+        else {
+            for(ii=0;ii<U_ETHER_ADDR_LEN;ii++) {
+                psEthHeader->abyDstAddr[ii] = pMACHeader->abyAddr3[ii];
+                psEthHeader->abySrcAddr[ii] = pMACHeader->abyAddr2[ii];
+            }
+        }
+    };
+    *pcbHeaderSize = cbHeaderSize;
+}
+
+
+
+
+//PLICE_DEBUG ->
+
+VOID	MngWorkItem(PVOID Context)
+{
+	PSRxMgmtPacket			pRxMgmtPacket;
+	PSDevice	pDevice =  (PSDevice) Context;
+	//printk("Enter MngWorkItem,Queue packet num is %d\n",pDevice->rxManeQueue.packet_num);
+	spin_lock_irq(&pDevice->lock);
+	 while(pDevice->rxManeQueue.packet_num != 0)
+	 {
+		 pRxMgmtPacket =  DeQueue(pDevice);
+        		vMgrRxManagePacket(pDevice, pDevice->pMgmt, pRxMgmtPacket);
+	}
+	spin_unlock_irq(&pDevice->lock);
+}
+
+
+//PLICE_DEBUG<-
+
+
+
+BOOL
+device_receive_frame (
+    IN  PSDevice pDevice,
+    IN  PSRxDesc pCurrRD
+    )
+{
+
+    PDEVICE_RD_INFO  pRDInfo = pCurrRD->pRDInfo;
+#ifdef	PLICE_DEBUG
+	//printk("device_receive_frame:pCurrRD is %x,pRDInfo is %x\n",pCurrRD,pCurrRD->pRDInfo);
+#endif
+    struct net_device_stats* pStats=&pDevice->stats;
+#ifdef PRIVATE_OBJ
+    ref_sk_buff*    skb;
+#else
+    struct sk_buff* skb;
+#endif
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PSRxMgmtPacket  pRxPacket = &(pDevice->pMgmt->sRxPacket);
+    PS802_11Header  p802_11Header;
+    PBYTE           pbyRsr;
+    PBYTE           pbyNewRsr;
+    PBYTE           pbyRSSI;
+    PQWORD          pqwTSFTime;
+    PWORD           pwFrameSize;
+    PBYTE           pbyFrame;
+    BOOL            bDeFragRx = FALSE;
+    BOOL            bIsWEP = FALSE;
+    UINT            cbHeaderOffset;
+    UINT            FrameSize;
+    WORD            wEtherType = 0;
+    INT             iSANodeIndex = -1;
+    INT             iDANodeIndex = -1;
+    UINT            ii;
+    UINT            cbIVOffset;
+    BOOL            bExtIV = FALSE;
+    PBYTE           pbyRxSts;
+    PBYTE           pbyRxRate;
+    PBYTE           pbySQ;
+    UINT            cbHeaderSize;
+    PSKeyItem       pKey = NULL;
+    WORD            wRxTSC15_0 = 0;
+    DWORD           dwRxTSC47_16 = 0;
+    SKeyItem        STempKey;
+    // 802.11h RPI
+    DWORD           dwDuration = 0;
+    LONG            ldBm = 0;
+    LONG            ldBmThreshold = 0;
+    PS802_11Header pMACHeader;
+ BOOL            bRxeapol_key = FALSE;
+
+//    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"---------- device_receive_frame---\n");
+#ifdef PRIVATE_OBJ
+    skb = &(pRDInfo->ref_skb);
+#else
+
+    skb = pRDInfo->skb;
+#endif
+
+
+//PLICE_DEBUG->
+#if 1
+	pci_unmap_single(pDevice->pcid, pRDInfo->skb_dma,
+                     pDevice->rx_buf_sz, PCI_DMA_FROMDEVICE);
+#endif
+//PLICE_DEBUG<-
+    pwFrameSize = (PWORD)(skb->data + 2);
+    FrameSize = cpu_to_le16(pCurrRD->m_rd1RD1.wReqCount) - cpu_to_le16(pCurrRD->m_rd0RD0.wResCount);
+
+    // Max: 2312Payload + 30HD +4CRC + 2Padding + 4Len + 8TSF + 4RSR
+    // Min (ACK): 10HD +4CRC + 2Padding + 4Len + 8TSF + 4RSR
+    if ((FrameSize > 2364)||(FrameSize <= 32)) {
+        // Frame Size error drop this packet.
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"---------- WRONG Length 1 \n");
+        return FALSE;
+    }
+
+    pbyRxSts = (PBYTE) (skb->data);
+    pbyRxRate = (PBYTE) (skb->data + 1);
+    pbyRsr = (PBYTE) (skb->data + FrameSize - 1);
+    pbyRSSI = (PBYTE) (skb->data + FrameSize - 2);
+    pbyNewRsr = (PBYTE) (skb->data + FrameSize - 3);
+    pbySQ = (PBYTE) (skb->data + FrameSize - 4);
+    pqwTSFTime = (PQWORD) (skb->data + FrameSize - 12);
+    pbyFrame = (PBYTE)(skb->data + 4);
+
+    // get packet size
+    FrameSize = cpu_to_le16(*pwFrameSize);
+
+    if ((FrameSize > 2346)|(FrameSize < 14)) { // Max: 2312Payload + 30HD +4CRC
+                                               // Min: 14 bytes ACK
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"---------- WRONG Length 2 \n");
+        return FALSE;
+    }
+//PLICE_DEBUG->
+#if 1
+	// update receive statistic counter
+    STAvUpdateRDStatCounter(&pDevice->scStatistic,
+                            *pbyRsr,
+                            *pbyNewRsr,
+                            *pbyRxRate,
+                            pbyFrame,
+                            FrameSize);
+
+#endif
+
+  pMACHeader=(PS802_11Header)((PBYTE) (skb->data)+8);
+//PLICE_DEBUG<-
+	if (pDevice->bMeasureInProgress == TRUE) {
+        if ((*pbyRsr & RSR_CRCOK) != 0) {
+            pDevice->byBasicMap |= 0x01;
+        }
+        dwDuration = (FrameSize << 4);
+        dwDuration /= acbyRxRate[*pbyRxRate%MAX_RATE];
+        if (*pbyRxRate <= RATE_11M) {
+            if (BITbIsBitOn(*pbyRxSts, 0x01)) {
+                // long preamble
+                dwDuration += 192;
+            } else {
+                // short preamble
+                dwDuration += 96;
+            }
+        } else {
+            dwDuration += 16;
+        }
+        RFvRSSITodBm(pDevice, *pbyRSSI, &ldBm);
+        ldBmThreshold = -57;
+        for (ii = 7; ii > 0;) {
+            if (ldBm > ldBmThreshold) {
+                break;
+            }
+            ldBmThreshold -= 5;
+            ii--;
+        }
+        pDevice->dwRPIs[ii] += dwDuration;
+        return FALSE;
+    }
+
+    if (!IS_MULTICAST_ADDRESS(pbyFrame) && !IS_BROADCAST_ADDRESS(pbyFrame)) {
+        if (WCTLbIsDuplicate(&(pDevice->sDupRxCache), (PS802_11Header) (skb->data + 4))) {
+            pDevice->s802_11Counter.FrameDuplicateCount++;
+            return FALSE;
+        }
+    }
+
+
+    // Use for TKIP MIC
+    s_vGetDASA(skb->data+4, &cbHeaderSize, &pDevice->sRxEthHeader);
+
+    // filter packet send from myself
+    if (IS_ETH_ADDRESS_EQUAL((PBYTE)&(pDevice->sRxEthHeader.abySrcAddr[0]), pDevice->abyCurrentNetAddr))
+        return FALSE;
+
+    if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) || (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA)) {
+        if (IS_CTL_PSPOLL(pbyFrame) || !IS_TYPE_CONTROL(pbyFrame)) {
+            p802_11Header = (PS802_11Header) (pbyFrame);
+            // get SA NodeIndex
+            if (BSSDBbIsSTAInNodeDB(pMgmt, (PBYTE)(p802_11Header->abyAddr2), &iSANodeIndex)) {
+#ifdef PRIVATE_OBJ
+                pMgmt->sNodeDBTable[iSANodeIndex].ulLastRxJiffer = get_jiffies();
+#else
+                pMgmt->sNodeDBTable[iSANodeIndex].ulLastRxJiffer = jiffies;
+#endif
+                pMgmt->sNodeDBTable[iSANodeIndex].uInActiveCount = 0;
+            }
+        }
+    }
+
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+        if (s_bAPModeRxCtl(pDevice, pbyFrame, iSANodeIndex) == TRUE) {
+            return FALSE;
+        }
+    }
+    if (IS_FC_WEP(pbyFrame)) {
+        BOOL     bRxDecryOK = FALSE;
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"rx WEP pkt\n");
+        bIsWEP = TRUE;
+        if ((pDevice->bEnableHostWEP) && (iSANodeIndex >= 0)) {
+            pKey = &STempKey;
+            pKey->byCipherSuite = pMgmt->sNodeDBTable[iSANodeIndex].byCipherSuite;
+            pKey->dwKeyIndex = pMgmt->sNodeDBTable[iSANodeIndex].dwKeyIndex;
+            pKey->uKeyLength = pMgmt->sNodeDBTable[iSANodeIndex].uWepKeyLength;
+            pKey->dwTSC47_16 = pMgmt->sNodeDBTable[iSANodeIndex].dwTSC47_16;
+            pKey->wTSC15_0 = pMgmt->sNodeDBTable[iSANodeIndex].wTSC15_0;
+            memcpy(pKey->abyKey,
+                &pMgmt->sNodeDBTable[iSANodeIndex].abyWepKey[0],
+                pKey->uKeyLength
+                );
+
+            bRxDecryOK = s_bHostWepRxEncryption(pDevice,
+                                                pbyFrame,
+                                                FrameSize,
+                                                pbyRsr,
+                                                pMgmt->sNodeDBTable[iSANodeIndex].bOnFly,
+                                                pKey,
+                                                pbyNewRsr,
+                                                &bExtIV,
+                                                &wRxTSC15_0,
+                                                &dwRxTSC47_16);
+        } else {
+            bRxDecryOK = s_bHandleRxEncryption(pDevice,
+                                                pbyFrame,
+                                                FrameSize,
+                                                pbyRsr,
+                                                pbyNewRsr,
+                                                &pKey,
+                                                &bExtIV,
+                                                &wRxTSC15_0,
+                                                &dwRxTSC47_16);
+        }
+
+        if (bRxDecryOK) {
+            if ((*pbyNewRsr & NEWRSR_DECRYPTOK) == 0) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ICV Fail\n");
+                if ( (pDevice->pMgmt->eAuthenMode == WMAC_AUTH_WPA) ||
+                    (pDevice->pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK) ||
+                    (pDevice->pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) ||
+                    (pDevice->pMgmt->eAuthenMode == WMAC_AUTH_WPA2) ||
+                    (pDevice->pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK)) {
+
+                    if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_TKIP)) {
+                        pDevice->s802_11Counter.TKIPICVErrors++;
+                    } else if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_CCMP)) {
+                        pDevice->s802_11Counter.CCMPDecryptErrors++;
+                    } else if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_WEP)) {
+//                      pDevice->s802_11Counter.WEPICVErrorCount.QuadPart++;
+                    }
+                }
+                return FALSE;
+            }
+        } else {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"WEP Func Fail\n");
+            return FALSE;
+        }
+        if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_CCMP))
+            FrameSize -= 8;         // Message Integrity Code
+        else
+            FrameSize -= 4;         // 4 is ICV
+    }
+
+
+    //
+    // RX OK
+    //
+    //remove the CRC length
+    FrameSize -= U_CRC_LEN;
+
+    if ((BITbIsAllBitsOff(*pbyRsr, (RSR_ADDRBROAD | RSR_ADDRMULTI))) && // unicast address
+        (IS_FRAGMENT_PKT((skb->data+4)))
+        ) {
+        // defragment
+        bDeFragRx = WCTLbHandleFragment(pDevice, (PS802_11Header) (skb->data+4), FrameSize, bIsWEP, bExtIV);
+        pDevice->s802_11Counter.ReceivedFragmentCount++;
+        if (bDeFragRx) {
+            // defrag complete
+#ifdef PRIVATE_OBJ
+            skb = &(pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].ref_skb);
+#else
+            skb = pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].skb;
+#endif
+            FrameSize = pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].cbFrameLength;
+
+        }
+        else {
+            return FALSE;
+        }
+    }
+
+
+// Management & Control frame Handle
+    if ((IS_TYPE_DATA((skb->data+4))) == FALSE) {
+        // Handle Control & Manage Frame
+
+        if (IS_TYPE_MGMT((skb->data+4))) {
+            PBYTE pbyData1;
+            PBYTE pbyData2;
+
+            pRxPacket->p80211Header = (PUWLAN_80211HDR)(skb->data+4);
+            pRxPacket->cbMPDULen = FrameSize;
+            pRxPacket->uRSSI = *pbyRSSI;
+            pRxPacket->bySQ = *pbySQ;
+            HIDWORD(pRxPacket->qwLocalTSF) = cpu_to_le32(HIDWORD(*pqwTSFTime));
+            LODWORD(pRxPacket->qwLocalTSF) = cpu_to_le32(LODWORD(*pqwTSFTime));
+            if (bIsWEP) {
+                // strip IV
+                pbyData1 = WLAN_HDR_A3_DATA_PTR(skb->data+4);
+                pbyData2 = WLAN_HDR_A3_DATA_PTR(skb->data+4) + 4;
+                for (ii = 0; ii < (FrameSize - 4); ii++) {
+                    *pbyData1 = *pbyData2;
+                     pbyData1++;
+                     pbyData2++;
+                }
+            }
+            pRxPacket->byRxRate = s_byGetRateIdx(*pbyRxRate);
+            pRxPacket->byRxChannel = (*pbyRxSts) >> 2;
+//PLICE_DEBUG->
+//EnQueue(pDevice,pRxPacket);
+
+#ifdef	THREAD
+		EnQueue(pDevice,pRxPacket);
+
+		//printk("enque time is %x\n",jiffies);
+		//up(&pDevice->mlme_semaphore);
+			//Enque (pDevice->FirstRecvMngList,pDevice->LastRecvMngList,pMgmt);
+#else
+
+#ifdef	TASK_LET
+		EnQueue(pDevice,pRxPacket);
+		tasklet_schedule(&pDevice->RxMngWorkItem);
+#else
+//printk("RxMan\n");
+	vMgrRxManagePacket((HANDLE)pDevice, pDevice->pMgmt, pRxPacket);
+           //tasklet_schedule(&pDevice->RxMngWorkItem);
+#endif
+
+#endif
+//PLICE_DEBUG<-
+			//vMgrRxManagePacket((HANDLE)pDevice, pDevice->pMgmt, pRxPacket);
+            // hostap Deamon handle 802.11 management
+            if (pDevice->bEnableHostapd) {
+	            skb->dev = pDevice->apdev;
+#ifdef PRIVATE_OBJ
+                ref_skb_add_offset(skb->skb, 4);
+                ref_skb_set_dev(pDevice->apdev, skb->skb);
+                skb_put(skb->skb, FrameSize);
+	            skb->mac_header = skb->data;
+	            *(skb->pkt_type) = PACKET_OTHERHOST;
+    	        *(skb->protocol) = htons(ETH_P_802_2);
+	            memset(skb->cb, 0, sizeof(skb->cb));
+	            netif_rx(skb->skb);
+#else
+	            skb->data += 4;
+	            skb->tail += 4;
+                     skb_put(skb, FrameSize);
+	            skb->mac_header = skb->data;
+	            skb->pkt_type = PACKET_OTHERHOST;
+    	        skb->protocol = htons(ETH_P_802_2);
+	            memset(skb->cb, 0, sizeof(skb->cb));
+	            netif_rx(skb);
+#endif
+                return TRUE;
+	        }
+        }
+        else {
+            // Control Frame
+        };
+        return FALSE;
+    }
+    else {
+        if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+            //In AP mode, hw only check addr1(BSSID or RA) if equal to local MAC.
+            if (BITbIsBitOff(*pbyRsr, RSR_BSSIDOK)) {
+                if (bDeFragRx) {
+                    if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
+                        DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
+                        pDevice->dev->name);
+                    }
+                }
+                return FALSE;
+            }
+        }
+        else {
+            // discard DATA packet while not associate || BSSID error
+            if ((pDevice->bLinkPass == FALSE) ||
+                BITbIsBitOff(*pbyRsr, RSR_BSSIDOK)) {
+                if (bDeFragRx) {
+                    if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
+                        DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
+                        pDevice->dev->name);
+                    }
+                }
+                return FALSE;
+            }
+
+   //mike add:station mode check eapol-key challenge--->
+   	  {
+   	    BYTE  Protocol_Version;    //802.1x Authentication
+	    BYTE  Packet_Type;           //802.1x Authentication
+              if (bIsWEP)
+                  cbIVOffset = 8;
+              else
+                  cbIVOffset = 0;
+              wEtherType = (skb->data[cbIVOffset + 8 + 24 + 6] << 8) |
+                          skb->data[cbIVOffset + 8 + 24 + 6 + 1];
+	      Protocol_Version = skb->data[cbIVOffset + 8 + 24 + 6 + 1 +1];
+	      Packet_Type = skb->data[cbIVOffset + 8 + 24 + 6 + 1 +1+1];
+	     if (wEtherType == ETH_P_PAE) {         //Protocol Type in LLC-Header
+                  if(((Protocol_Version==1) ||(Protocol_Version==2)) &&
+		     (Packet_Type==3)) {  //802.1x OR eapol-key challenge frame receive
+                        bRxeapol_key = TRUE;
+                  }
+	      }
+   	  }
+    //mike add:station mode check eapol-key challenge<---
+        }
+    }
+
+// Data frame Handle
+
+    if (pDevice->bEnablePSMode) {
+        if (IS_FC_MOREDATA((skb->data+4))) {
+            if (BITbIsBitOn(*pbyRsr, RSR_ADDROK)) {
+                //PSbSendPSPOLL((PSDevice)pDevice);
+            }
+        }
+        else {
+            if (pDevice->pMgmt->bInTIMWake == TRUE) {
+                pDevice->pMgmt->bInTIMWake = FALSE;
+            }
+        }
+    };
+
+    // Now it only supports 802.11g Infrastructure Mode, and support rate must up to 54 Mbps
+    if (pDevice->bDiversityEnable && (FrameSize>50) &&
+        (pDevice->eOPMode == OP_MODE_INFRASTRUCTURE) &&
+        (pDevice->bLinkPass == TRUE)) {
+	//printk("device_receive_frame: RxRate is %d\n",*pbyRxRate);
+		BBvAntennaDiversity(pDevice, s_byGetRateIdx(*pbyRxRate), 0);
+    }
+
+
+    if (pDevice->byLocalID != REV_ID_VT3253_B1) {
+        pDevice->uCurrRSSI = *pbyRSSI;
+    }
+    pDevice->byCurrSQ = *pbySQ;
+
+    if ((*pbyRSSI != 0) &&
+        (pMgmt->pCurrBSS!=NULL)) {
+        RFvRSSITodBm(pDevice, *pbyRSSI, &ldBm);
+        // Moniter if RSSI is too strong.
+        pMgmt->pCurrBSS->byRSSIStatCnt++;
+        pMgmt->pCurrBSS->byRSSIStatCnt %= RSSI_STAT_COUNT;
+        pMgmt->pCurrBSS->ldBmAverage[pMgmt->pCurrBSS->byRSSIStatCnt] = ldBm;
+        for(ii=0;ii<RSSI_STAT_COUNT;ii++) {
+            if (pMgmt->pCurrBSS->ldBmAverage[ii] != 0) {
+            pMgmt->pCurrBSS->ldBmMAX = max(pMgmt->pCurrBSS->ldBmAverage[ii], ldBm);
+            }
+        }
+    }
+
+    // -----------------------------------------------
+
+    if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) && (pDevice->bEnable8021x == TRUE)){
+        BYTE    abyMacHdr[24];
+
+        // Only 802.1x packet incoming allowed
+        if (bIsWEP)
+            cbIVOffset = 8;
+        else
+            cbIVOffset = 0;
+        wEtherType = (skb->data[cbIVOffset + 4 + 24 + 6] << 8) |
+                    skb->data[cbIVOffset + 4 + 24 + 6 + 1];
+
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wEtherType = %04x \n", wEtherType);
+        if (wEtherType == ETH_P_PAE) {
+            skb->dev = pDevice->apdev;
+
+            if (bIsWEP == TRUE) {
+                // strip IV header(8)
+                memcpy(&abyMacHdr[0], (skb->data + 4), 24);
+                memcpy((skb->data + 4 + cbIVOffset), &abyMacHdr[0], 24);
+            }
+#ifdef PRIVATE_OBJ
+            ref_skb_add_offset(skb->skb, (cbIVOffset + 4));
+            ref_skb_set_dev(pDevice->apdev, skb->skb);
+            skb_put(skb->skb, FrameSize);
+			skb->mac_header = skb->data;
+            *(skb->pkt_type) = PACKET_OTHERHOST;
+	        *(skb->protocol) = htons(ETH_P_802_2);
+            memset(skb->cb, 0, sizeof(skb->cb));
+            netif_rx(skb->skb);
+#else
+            skb->data +=  (cbIVOffset + 4);
+            skb->tail +=  (cbIVOffset + 4);
+            skb_put(skb, FrameSize);
+           skb->mac_header = skb->data;
+
+	skb->pkt_type = PACKET_OTHERHOST;
+            skb->protocol = htons(ETH_P_802_2);
+            memset(skb->cb, 0, sizeof(skb->cb));
+            netif_rx(skb);
+#endif
+            return TRUE;
+
+}
+        // check if 802.1x authorized
+        if (!(pMgmt->sNodeDBTable[iSANodeIndex].dwFlags & WLAN_STA_AUTHORIZED))
+            return FALSE;
+    }
+
+
+    if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_TKIP)) {
+        if (bIsWEP) {
+            FrameSize -= 8;  //MIC
+        }
+    }
+
+    //--------------------------------------------------------------------------------
+    // Soft MIC
+    if ((pKey != NULL) && (pKey->byCipherSuite == KEY_CTL_TKIP)) {
+        if (bIsWEP) {
+            PDWORD          pdwMIC_L;
+            PDWORD          pdwMIC_R;
+            DWORD           dwMIC_Priority;
+            DWORD           dwMICKey0 = 0, dwMICKey1 = 0;
+            DWORD           dwLocalMIC_L = 0;
+            DWORD           dwLocalMIC_R = 0;
+            viawget_wpa_header *wpahdr;
+
+
+            if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+                dwMICKey0 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[24]));
+                dwMICKey1 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[28]));
+            }
+            else {
+                if (pDevice->pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) {
+                    dwMICKey0 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[16]));
+                    dwMICKey1 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[20]));
+                } else if ((pKey->dwKeyIndex & BIT28) == 0) {
+                    dwMICKey0 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[16]));
+                    dwMICKey1 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[20]));
+                } else {
+                    dwMICKey0 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[24]));
+                    dwMICKey1 = cpu_to_le32(*(PDWORD)(&pKey->abyKey[28]));
+                }
+            }
+
+            MIC_vInit(dwMICKey0, dwMICKey1);
+            MIC_vAppend((PBYTE)&(pDevice->sRxEthHeader.abyDstAddr[0]), 12);
+            dwMIC_Priority = 0;
+            MIC_vAppend((PBYTE)&dwMIC_Priority, 4);
+            // 4 is Rcv buffer header, 24 is MAC Header, and 8 is IV and Ext IV.
+            MIC_vAppend((PBYTE)(skb->data + 4 + WLAN_HDR_ADDR3_LEN + 8),
+                        FrameSize - WLAN_HDR_ADDR3_LEN - 8);
+            MIC_vGetMIC(&dwLocalMIC_L, &dwLocalMIC_R);
+            MIC_vUnInit();
+
+            pdwMIC_L = (PDWORD)(skb->data + 4 + FrameSize);
+            pdwMIC_R = (PDWORD)(skb->data + 4 + FrameSize + 4);
+            //DBG_PRN_GRP12(("RxL: %lx, RxR: %lx\n", *pdwMIC_L, *pdwMIC_R));
+            //DBG_PRN_GRP12(("LocalL: %lx, LocalR: %lx\n", dwLocalMIC_L, dwLocalMIC_R));
+            //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"dwMICKey0= %lx,dwMICKey1= %lx \n", dwMICKey0, dwMICKey1);
+
+
+            if ((cpu_to_le32(*pdwMIC_L) != dwLocalMIC_L) || (cpu_to_le32(*pdwMIC_R) != dwLocalMIC_R) ||
+                (pDevice->bRxMICFail == TRUE)) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MIC comparison is fail!\n");
+                pDevice->bRxMICFail = FALSE;
+                //pDevice->s802_11Counter.TKIPLocalMICFailures.QuadPart++;
+                pDevice->s802_11Counter.TKIPLocalMICFailures++;
+                if (bDeFragRx) {
+                    if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
+                        DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
+                            pDevice->dev->name);
+                    }
+                }
+
+//2008-0409-07, <Add> by Einsn Liu
+       #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+				//send event to wpa_supplicant
+				//if(pDevice->bWPADevEnable == TRUE)
+					{
+					union iwreq_data wrqu;
+					struct iw_michaelmicfailure ev;
+					int keyidx = pbyFrame[cbHeaderSize+3] >> 6; //top two-bits
+					memset(&ev, 0, sizeof(ev));
+					ev.flags = keyidx & IW_MICFAILURE_KEY_ID;
+					if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
+							(pMgmt->eCurrState == WMAC_STATE_ASSOC) &&
+								(*pbyRsr & (RSR_ADDRBROAD | RSR_ADDRMULTI)) == 0) {
+						ev.flags |= IW_MICFAILURE_PAIRWISE;
+					} else {
+						ev.flags |= IW_MICFAILURE_GROUP;
+					}
+
+					ev.src_addr.sa_family = ARPHRD_ETHER;
+					memcpy(ev.src_addr.sa_data, pMACHeader->abyAddr2, ETH_ALEN);
+					memset(&wrqu, 0, sizeof(wrqu));
+					wrqu.data.length = sizeof(ev);
+					wireless_send_event(pDevice->dev, IWEVMICHAELMICFAILURE, &wrqu, (char *)&ev);
+
+				}
+         #endif
+                if ((pDevice->bWPADEVUp) && (pDevice->skb != NULL)) {
+                     wpahdr = (viawget_wpa_header *)pDevice->skb->data;
+                     if ((pDevice->pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
+                         (pDevice->pMgmt->eCurrState == WMAC_STATE_ASSOC) &&
+                         (*pbyRsr & (RSR_ADDRBROAD | RSR_ADDRMULTI)) == 0) {
+                         //s802_11_Status.Flags = NDIS_802_11_AUTH_REQUEST_PAIRWISE_ERROR;
+                         wpahdr->type = VIAWGET_PTK_MIC_MSG;
+                     } else {
+                         //s802_11_Status.Flags = NDIS_802_11_AUTH_REQUEST_GROUP_ERROR;
+                         wpahdr->type = VIAWGET_GTK_MIC_MSG;
+                     }
+                     wpahdr->resp_ie_len = 0;
+                     wpahdr->req_ie_len = 0;
+                     skb_put(pDevice->skb, sizeof(viawget_wpa_header));
+                     pDevice->skb->dev = pDevice->wpadev;
+                     pDevice->skb->mac_header = pDevice->skb->data;
+                     pDevice->skb->pkt_type = PACKET_HOST;
+                     pDevice->skb->protocol = htons(ETH_P_802_2);
+                     memset(pDevice->skb->cb, 0, sizeof(pDevice->skb->cb));
+                     netif_rx(pDevice->skb);
+                     pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
+                 };
+
+                return FALSE;
+
+            }
+        }
+    } //---end of SOFT MIC-----------------------------------------------------------------------
+
+    // ++++++++++ Reply Counter Check +++++++++++++
+
+    if ((pKey != NULL) && ((pKey->byCipherSuite == KEY_CTL_TKIP) ||
+                           (pKey->byCipherSuite == KEY_CTL_CCMP))) {
+        if (bIsWEP) {
+            WORD        wLocalTSC15_0 = 0;
+            DWORD       dwLocalTSC47_16 = 0;
+            ULONGLONG       RSC = 0;
+            // endian issues
+            RSC = *((ULONGLONG *) &(pKey->KeyRSC));
+            wLocalTSC15_0 = (WORD) RSC;
+            dwLocalTSC47_16 = (DWORD) (RSC>>16);
+
+            RSC = dwRxTSC47_16;
+            RSC <<= 16;
+            RSC += wRxTSC15_0;
+            MEMvCopy(&(pKey->KeyRSC), &RSC,  sizeof(QWORD));
+
+            if ( (pDevice->sMgmtObj.eCurrMode == WMAC_MODE_ESS_STA) &&
+                 (pDevice->sMgmtObj.eCurrState == WMAC_STATE_ASSOC)) {
+                // check RSC
+                if ( (wRxTSC15_0 < wLocalTSC15_0) &&
+                     (dwRxTSC47_16 <= dwLocalTSC47_16) &&
+                     !((dwRxTSC47_16 == 0) && (dwLocalTSC47_16 == 0xFFFFFFFF))) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"TSC is illegal~~!\n ");
+                    if (pKey->byCipherSuite == KEY_CTL_TKIP)
+                        //pDevice->s802_11Counter.TKIPReplays.QuadPart++;
+                        pDevice->s802_11Counter.TKIPReplays++;
+                    else
+                        //pDevice->s802_11Counter.CCMPReplays.QuadPart++;
+                        pDevice->s802_11Counter.CCMPReplays++;
+
+                    if (bDeFragRx) {
+                        if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
+                            DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
+                                pDevice->dev->name);
+                        }
+                    }
+                    return FALSE;
+                }
+            }
+        }
+    } // ----- End of Reply Counter Check --------------------------
+
+
+
+    if ((pKey != NULL) && (bIsWEP)) {
+//      pDevice->s802_11Counter.DecryptSuccessCount.QuadPart++;
+    }
+
+
+    s_vProcessRxMACHeader(pDevice, (PBYTE)(skb->data+4), FrameSize, bIsWEP, bExtIV, &cbHeaderOffset);
+    FrameSize -= cbHeaderOffset;
+    cbHeaderOffset += 4;        // 4 is Rcv buffer header
+
+    // Null data, framesize = 14
+    if (FrameSize < 15)
+        return FALSE;
+
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+        if (s_bAPModeRxData(pDevice,
+                            skb,
+                            FrameSize,
+                            cbHeaderOffset,
+                            iSANodeIndex,
+                            iDANodeIndex
+                            ) == FALSE) {
+
+            if (bDeFragRx) {
+                if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
+                    DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
+                    pDevice->dev->name);
+                }
+            }
+            return FALSE;
+        }
+
+//        if(pDevice->bRxMICFail == FALSE) {
+//           for (ii =0; ii < 100; ii++)
+//                printk(" %02x", *(skb->data + ii));
+//           printk("\n");
+//	    }
+
+    }
+
+#ifdef PRIVATE_OBJ
+    ref_skb_add_offset(skb->skb, cbHeaderOffset);
+    skb_put(skb->skb, FrameSize);
+    *(skb->protocol)=eth_type_trans(skb->skb, skb->dev);
+
+#else
+	skb->data += cbHeaderOffset;
+	skb->tail += cbHeaderOffset;
+    skb_put(skb, FrameSize);
+    skb->protocol=eth_type_trans(skb, skb->dev);
+#endif
+
+
+	//drop frame not met IEEE 802.3
+/*
+	if (pDevice->flags & DEVICE_FLAGS_VAL_PKT_LEN) {
+#ifdef PRIVATE_OBJ
+		if ((*(skb->protocol)==htons(ETH_P_802_3)) &&
+			(*(skb->len)!=htons(skb->mac.ethernet->h_proto))) {
+#else
+		if ((skb->protocol==htons(ETH_P_802_3)) &&
+			(skb->len!=htons(skb->mac.ethernet->h_proto))) {
+#endif
+			pStats->rx_length_errors++;
+			pStats->rx_dropped++;
+            if (bDeFragRx) {
+                if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
+                    DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
+                    pDevice->dev->name);
+                }
+            }
+			return FALSE;
+		}
+	}
+*/
+
+#ifdef PRIVATE_OBJ
+    *(skb->ip_summed)=CHECKSUM_NONE;
+    pStats->rx_bytes +=*(skb->len);
+    pStats->rx_packets++;
+    netif_rx(skb->skb);
+#else
+    skb->ip_summed=CHECKSUM_NONE;
+    pStats->rx_bytes +=skb->len;
+    pStats->rx_packets++;
+    netif_rx(skb);
+#endif
+
+    if (bDeFragRx) {
+        if (!device_alloc_frag_buf(pDevice, &pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx])) {
+            DEVICE_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc more frag bufs\n",
+                pDevice->dev->name);
+        }
+        return FALSE;
+    }
+    return TRUE;
+}
+
+
+static BOOL s_bAPModeRxCtl (
+    IN PSDevice pDevice,
+    IN PBYTE    pbyFrame,
+    IN INT      iSANodeIndex
+    )
+{
+    PS802_11Header      p802_11Header;
+    CMD_STATUS          Status;
+    PSMgmtObject        pMgmt = pDevice->pMgmt;
+
+
+    if (IS_CTL_PSPOLL(pbyFrame) || !IS_TYPE_CONTROL(pbyFrame)) {
+
+        p802_11Header = (PS802_11Header) (pbyFrame);
+        if (!IS_TYPE_MGMT(pbyFrame)) {
+
+            // Data & PS-Poll packet
+            // check frame class
+            if (iSANodeIndex > 0) {
+                // frame class 3 fliter & checking
+                if (pMgmt->sNodeDBTable[iSANodeIndex].eNodeState < NODE_AUTH) {
+                    // send deauth notification
+                    // reason = (6) class 2 received from nonauth sta
+                    vMgrDeAuthenBeginSta(pDevice,
+                                         pMgmt,
+                                         (PBYTE)(p802_11Header->abyAddr2),
+                                         (WLAN_MGMT_REASON_CLASS2_NONAUTH),
+                                         &Status
+                                         );
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: send vMgrDeAuthenBeginSta 1\n");
+                    return TRUE;
+                };
+                if (pMgmt->sNodeDBTable[iSANodeIndex].eNodeState < NODE_ASSOC) {
+                    // send deassoc notification
+                    // reason = (7) class 3 received from nonassoc sta
+                    vMgrDisassocBeginSta(pDevice,
+                                         pMgmt,
+                                         (PBYTE)(p802_11Header->abyAddr2),
+                                         (WLAN_MGMT_REASON_CLASS3_NONASSOC),
+                                         &Status
+                                         );
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: send vMgrDisassocBeginSta 2\n");
+                    return TRUE;
+                };
+
+                if (pMgmt->sNodeDBTable[iSANodeIndex].bPSEnable) {
+                    // delcare received ps-poll event
+                    if (IS_CTL_PSPOLL(pbyFrame)) {
+                        pMgmt->sNodeDBTable[iSANodeIndex].bRxPSPoll = TRUE;
+                        bScheduleCommand((HANDLE)pDevice, WLAN_CMD_RX_PSPOLL, NULL);
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: WLAN_CMD_RX_PSPOLL 1\n");
+                    }
+                    else {
+                        // check Data PS state
+                        // if PW bit off, send out all PS bufferring packets.
+                        if (!IS_FC_POWERMGT(pbyFrame)) {
+                            pMgmt->sNodeDBTable[iSANodeIndex].bPSEnable = FALSE;
+                            pMgmt->sNodeDBTable[iSANodeIndex].bRxPSPoll = TRUE;
+                            bScheduleCommand((HANDLE)pDevice, WLAN_CMD_RX_PSPOLL, NULL);
+                            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: WLAN_CMD_RX_PSPOLL 2\n");
+                        }
+                    }
+                }
+                else {
+                   if (IS_FC_POWERMGT(pbyFrame)) {
+                       pMgmt->sNodeDBTable[iSANodeIndex].bPSEnable = TRUE;
+                       // Once if STA in PS state, enable multicast bufferring
+                       pMgmt->sNodeDBTable[0].bPSEnable = TRUE;
+                   }
+                   else {
+                      // clear all pending PS frame.
+                      if (pMgmt->sNodeDBTable[iSANodeIndex].wEnQueueCnt > 0) {
+                          pMgmt->sNodeDBTable[iSANodeIndex].bPSEnable = FALSE;
+                          pMgmt->sNodeDBTable[iSANodeIndex].bRxPSPoll = TRUE;
+                          bScheduleCommand((HANDLE)pDevice, WLAN_CMD_RX_PSPOLL, NULL);
+                         DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: WLAN_CMD_RX_PSPOLL 3\n");
+
+                      }
+                   }
+                }
+            }
+            else {
+                  vMgrDeAuthenBeginSta(pDevice,
+                                       pMgmt,
+                                       (PBYTE)(p802_11Header->abyAddr2),
+                                       (WLAN_MGMT_REASON_CLASS2_NONAUTH),
+                                       &Status
+                                       );
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: send vMgrDeAuthenBeginSta 3\n");
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "BSSID:%02x-%02x-%02x=%02x-%02x-%02x \n",
+                                p802_11Header->abyAddr3[0],
+                                p802_11Header->abyAddr3[1],
+                                p802_11Header->abyAddr3[2],
+                                p802_11Header->abyAddr3[3],
+                                p802_11Header->abyAddr3[4],
+                                p802_11Header->abyAddr3[5]
+                               );
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "ADDR2:%02x-%02x-%02x=%02x-%02x-%02x \n",
+                                p802_11Header->abyAddr2[0],
+                                p802_11Header->abyAddr2[1],
+                                p802_11Header->abyAddr2[2],
+                                p802_11Header->abyAddr2[3],
+                                p802_11Header->abyAddr2[4],
+                                p802_11Header->abyAddr2[5]
+                               );
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "ADDR1:%02x-%02x-%02x=%02x-%02x-%02x \n",
+                                p802_11Header->abyAddr1[0],
+                                p802_11Header->abyAddr1[1],
+                                p802_11Header->abyAddr1[2],
+                                p802_11Header->abyAddr1[3],
+                                p802_11Header->abyAddr1[4],
+                                p802_11Header->abyAddr1[5]
+                               );
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc: wFrameCtl= %x\n", p802_11Header->wFrameCtl );
+                    VNSvInPortB(pDevice->PortOffset + MAC_REG_RCR, &(pDevice->byRxMode));
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dpc:pDevice->byRxMode = %x\n", pDevice->byRxMode );
+                    return TRUE;
+            }
+        }
+    }
+    return FALSE;
+
+}
+
+static BOOL s_bHandleRxEncryption (
+    IN PSDevice     pDevice,
+    IN PBYTE        pbyFrame,
+    IN UINT         FrameSize,
+    IN PBYTE        pbyRsr,
+    OUT PBYTE       pbyNewRsr,
+    OUT PSKeyItem   *pKeyOut,
+    OUT PBOOL       pbExtIV,
+    OUT PWORD       pwRxTSC15_0,
+    OUT PDWORD      pdwRxTSC47_16
+    )
+{
+    UINT            PayloadLen = FrameSize;
+    PBYTE           pbyIV;
+    BYTE            byKeyIdx;
+    PSKeyItem       pKey = NULL;
+    BYTE            byDecMode = KEY_CTL_WEP;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+
+
+    *pwRxTSC15_0 = 0;
+    *pdwRxTSC47_16 = 0;
+
+    pbyIV = pbyFrame + WLAN_HDR_ADDR3_LEN;
+    if ( WLAN_GET_FC_TODS(*(PWORD)pbyFrame) &&
+         WLAN_GET_FC_FROMDS(*(PWORD)pbyFrame) ) {
+         pbyIV += 6;             // 6 is 802.11 address4
+         PayloadLen -= 6;
+    }
+    byKeyIdx = (*(pbyIV+3) & 0xc0);
+    byKeyIdx >>= 6;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\nKeyIdx: %d\n", byKeyIdx);
+
+    if ((pMgmt->eAuthenMode == WMAC_AUTH_WPA) ||
+        (pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK) ||
+        (pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) ||
+        (pMgmt->eAuthenMode == WMAC_AUTH_WPA2) ||
+        (pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK)) {
+        if (((*pbyRsr & (RSR_ADDRBROAD | RSR_ADDRMULTI)) == 0) &&
+            (pDevice->pMgmt->byCSSPK != KEY_CTL_NONE)) {
+            // unicast pkt use pairwise key
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"unicast pkt\n");
+            if (KeybGetKey(&(pDevice->sKey), pDevice->abyBSSID, 0xFFFFFFFF, &pKey) == TRUE) {
+                if (pDevice->pMgmt->byCSSPK == KEY_CTL_TKIP)
+                    byDecMode = KEY_CTL_TKIP;
+                else if (pDevice->pMgmt->byCSSPK == KEY_CTL_CCMP)
+                    byDecMode = KEY_CTL_CCMP;
+            }
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"unicast pkt: %d, %p\n", byDecMode, pKey);
+        } else {
+            // use group key
+            KeybGetKey(&(pDevice->sKey), pDevice->abyBSSID, byKeyIdx, &pKey);
+            if (pDevice->pMgmt->byCSSGK == KEY_CTL_TKIP)
+                byDecMode = KEY_CTL_TKIP;
+            else if (pDevice->pMgmt->byCSSGK == KEY_CTL_CCMP)
+                byDecMode = KEY_CTL_CCMP;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"group pkt: %d, %d, %p\n", byKeyIdx, byDecMode, pKey);
+        }
+    }
+    // our WEP only support Default Key
+    if (pKey == NULL) {
+        // use default group key
+        KeybGetKey(&(pDevice->sKey), pDevice->abyBroadcastAddr, byKeyIdx, &pKey);
+        if (pDevice->pMgmt->byCSSGK == KEY_CTL_TKIP)
+            byDecMode = KEY_CTL_TKIP;
+        else if (pDevice->pMgmt->byCSSGK == KEY_CTL_CCMP)
+            byDecMode = KEY_CTL_CCMP;
+    }
+    *pKeyOut = pKey;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"AES:%d %d %d\n", pDevice->pMgmt->byCSSPK, pDevice->pMgmt->byCSSGK, byDecMode);
+
+    if (pKey == NULL) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey == NULL\n");
+        if (byDecMode == KEY_CTL_WEP) {
+//            pDevice->s802_11Counter.WEPUndecryptableCount.QuadPart++;
+        } else if (pDevice->bLinkPass == TRUE) {
+//            pDevice->s802_11Counter.DecryptFailureCount.QuadPart++;
+        }
+        return FALSE;
+    }
+    if (byDecMode != pKey->byCipherSuite) {
+        if (byDecMode == KEY_CTL_WEP) {
+//            pDevice->s802_11Counter.WEPUndecryptableCount.QuadPart++;
+        } else if (pDevice->bLinkPass == TRUE) {
+//            pDevice->s802_11Counter.DecryptFailureCount.QuadPart++;
+        }
+        *pKeyOut = NULL;
+        return FALSE;
+    }
+    if (byDecMode == KEY_CTL_WEP) {
+        // handle WEP
+        if ((pDevice->byLocalID <= REV_ID_VT3253_A1) ||
+            (((PSKeyTable)(pKey->pvKeyTable))->bSoftWEP == TRUE)) {
+            // Software WEP
+            // 1. 3253A
+            // 2. WEP 256
+
+            PayloadLen -= (WLAN_HDR_ADDR3_LEN + 4 + 4); // 24 is 802.11 header,4 is IV, 4 is crc
+            MEMvCopy(pDevice->abyPRNG, pbyIV, 3);
+            MEMvCopy(pDevice->abyPRNG + 3, pKey->abyKey, pKey->uKeyLength);
+            rc4_init(&pDevice->SBox, pDevice->abyPRNG, pKey->uKeyLength + 3);
+            rc4_encrypt(&pDevice->SBox, pbyIV+4, pbyIV+4, PayloadLen);
+
+            if (ETHbIsBufferCrc32Ok(pbyIV+4, PayloadLen)) {
+                *pbyNewRsr |= NEWRSR_DECRYPTOK;
+            }
+        }
+    } else if ((byDecMode == KEY_CTL_TKIP) ||
+               (byDecMode == KEY_CTL_CCMP)) {
+        // TKIP/AES
+
+        PayloadLen -= (WLAN_HDR_ADDR3_LEN + 8 + 4); // 24 is 802.11 header, 8 is IV&ExtIV, 4 is crc
+        *pdwRxTSC47_16 = cpu_to_le32(*(PDWORD)(pbyIV + 4));
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ExtIV: %lx\n",*pdwRxTSC47_16);
+        if (byDecMode == KEY_CTL_TKIP) {
+            *pwRxTSC15_0 = cpu_to_le16(MAKEWORD(*(pbyIV+2), *pbyIV));
+        } else {
+            *pwRxTSC15_0 = cpu_to_le16(*(PWORD)pbyIV);
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"TSC0_15: %x\n", *pwRxTSC15_0);
+
+        if ((byDecMode == KEY_CTL_TKIP) &&
+            (pDevice->byLocalID <= REV_ID_VT3253_A1)) {
+            // Software TKIP
+            // 1. 3253 A
+            PS802_11Header  pMACHeader = (PS802_11Header) (pbyFrame);
+            TKIPvMixKey(pKey->abyKey, pMACHeader->abyAddr2, *pwRxTSC15_0, *pdwRxTSC47_16, pDevice->abyPRNG);
+            rc4_init(&pDevice->SBox, pDevice->abyPRNG, TKIP_KEY_LEN);
+            rc4_encrypt(&pDevice->SBox, pbyIV+8, pbyIV+8, PayloadLen);
+            if (ETHbIsBufferCrc32Ok(pbyIV+8, PayloadLen)) {
+                *pbyNewRsr |= NEWRSR_DECRYPTOK;
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ICV OK!\n");
+            } else {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ICV FAIL!!!\n");
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"PayloadLen = %d\n", PayloadLen);
+            }
+        }
+    }// end of TKIP/AES
+
+    if ((*(pbyIV+3) & 0x20) != 0)
+        *pbExtIV = TRUE;
+    return TRUE;
+}
+
+
+static BOOL s_bHostWepRxEncryption (
+    IN PSDevice     pDevice,
+    IN PBYTE        pbyFrame,
+    IN UINT         FrameSize,
+    IN PBYTE        pbyRsr,
+    IN BOOL         bOnFly,
+    IN PSKeyItem    pKey,
+    OUT PBYTE       pbyNewRsr,
+    OUT PBOOL       pbExtIV,
+    OUT PWORD       pwRxTSC15_0,
+    OUT PDWORD      pdwRxTSC47_16
+    )
+{
+    UINT            PayloadLen = FrameSize;
+    PBYTE           pbyIV;
+    BYTE            byKeyIdx;
+    BYTE            byDecMode = KEY_CTL_WEP;
+    PS802_11Header  pMACHeader;
+
+
+
+    *pwRxTSC15_0 = 0;
+    *pdwRxTSC47_16 = 0;
+
+    pbyIV = pbyFrame + WLAN_HDR_ADDR3_LEN;
+    if ( WLAN_GET_FC_TODS(*(PWORD)pbyFrame) &&
+         WLAN_GET_FC_FROMDS(*(PWORD)pbyFrame) ) {
+         pbyIV += 6;             // 6 is 802.11 address4
+         PayloadLen -= 6;
+    }
+    byKeyIdx = (*(pbyIV+3) & 0xc0);
+    byKeyIdx >>= 6;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\nKeyIdx: %d\n", byKeyIdx);
+
+
+    if (pDevice->pMgmt->byCSSGK == KEY_CTL_TKIP)
+        byDecMode = KEY_CTL_TKIP;
+    else if (pDevice->pMgmt->byCSSGK == KEY_CTL_CCMP)
+        byDecMode = KEY_CTL_CCMP;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"AES:%d %d %d\n", pDevice->pMgmt->byCSSPK, pDevice->pMgmt->byCSSGK, byDecMode);
+
+    if (byDecMode != pKey->byCipherSuite) {
+        if (byDecMode == KEY_CTL_WEP) {
+//            pDevice->s802_11Counter.WEPUndecryptableCount.QuadPart++;
+        } else if (pDevice->bLinkPass == TRUE) {
+//            pDevice->s802_11Counter.DecryptFailureCount.QuadPart++;
+        }
+        return FALSE;
+    }
+
+    if (byDecMode == KEY_CTL_WEP) {
+        // handle WEP
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"byDecMode == KEY_CTL_WEP \n");
+        if ((pDevice->byLocalID <= REV_ID_VT3253_A1) ||
+            (((PSKeyTable)(pKey->pvKeyTable))->bSoftWEP == TRUE) ||
+            (bOnFly == FALSE)) {
+            // Software WEP
+            // 1. 3253A
+            // 2. WEP 256
+            // 3. NotOnFly
+
+            PayloadLen -= (WLAN_HDR_ADDR3_LEN + 4 + 4); // 24 is 802.11 header,4 is IV, 4 is crc
+            MEMvCopy(pDevice->abyPRNG, pbyIV, 3);
+            MEMvCopy(pDevice->abyPRNG + 3, pKey->abyKey, pKey->uKeyLength);
+            rc4_init(&pDevice->SBox, pDevice->abyPRNG, pKey->uKeyLength + 3);
+            rc4_encrypt(&pDevice->SBox, pbyIV+4, pbyIV+4, PayloadLen);
+
+            if (ETHbIsBufferCrc32Ok(pbyIV+4, PayloadLen)) {
+                *pbyNewRsr |= NEWRSR_DECRYPTOK;
+            }
+        }
+    } else if ((byDecMode == KEY_CTL_TKIP) ||
+               (byDecMode == KEY_CTL_CCMP)) {
+        // TKIP/AES
+
+        PayloadLen -= (WLAN_HDR_ADDR3_LEN + 8 + 4); // 24 is 802.11 header, 8 is IV&ExtIV, 4 is crc
+        *pdwRxTSC47_16 = cpu_to_le32(*(PDWORD)(pbyIV + 4));
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ExtIV: %lx\n",*pdwRxTSC47_16);
+
+        if (byDecMode == KEY_CTL_TKIP) {
+            *pwRxTSC15_0 = cpu_to_le16(MAKEWORD(*(pbyIV+2), *pbyIV));
+        } else {
+            *pwRxTSC15_0 = cpu_to_le16(*(PWORD)pbyIV);
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"TSC0_15: %x\n", *pwRxTSC15_0);
+
+        if (byDecMode == KEY_CTL_TKIP) {
+            if ((pDevice->byLocalID <= REV_ID_VT3253_A1) || (bOnFly == FALSE)) {
+                // Software TKIP
+                // 1. 3253 A
+                // 2. NotOnFly
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"soft KEY_CTL_TKIP \n");
+                pMACHeader = (PS802_11Header) (pbyFrame);
+                TKIPvMixKey(pKey->abyKey, pMACHeader->abyAddr2, *pwRxTSC15_0, *pdwRxTSC47_16, pDevice->abyPRNG);
+                rc4_init(&pDevice->SBox, pDevice->abyPRNG, TKIP_KEY_LEN);
+                rc4_encrypt(&pDevice->SBox, pbyIV+8, pbyIV+8, PayloadLen);
+                if (ETHbIsBufferCrc32Ok(pbyIV+8, PayloadLen)) {
+                    *pbyNewRsr |= NEWRSR_DECRYPTOK;
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ICV OK!\n");
+                } else {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ICV FAIL!!!\n");
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"PayloadLen = %d\n", PayloadLen);
+                }
+            }
+        }
+
+        if (byDecMode == KEY_CTL_CCMP) {
+            if (bOnFly == FALSE) {
+                // Software CCMP
+                // NotOnFly
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"soft KEY_CTL_CCMP\n");
+                if (AESbGenCCMP(pKey->abyKey, pbyFrame, FrameSize)) {
+                    *pbyNewRsr |= NEWRSR_DECRYPTOK;
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"CCMP MIC compare OK!\n");
+                } else {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"CCMP MIC fail!\n");
+                }
+            }
+        }
+
+    }// end of TKIP/AES
+
+    if ((*(pbyIV+3) & 0x20) != 0)
+        *pbExtIV = TRUE;
+    return TRUE;
+}
+
+
+
+
+#ifdef PRIVATE_OBJ
+
+static BOOL s_bAPModeRxData (
+    IN PSDevice pDevice,
+    IN ref_sk_buff* skb,
+    IN UINT     FrameSize,
+    IN UINT     cbHeaderOffset,
+    IN INT      iSANodeIndex,
+    IN INT      iDANodeIndex
+    )
+
+#else
+
+static BOOL s_bAPModeRxData (
+    IN PSDevice pDevice,
+    IN struct sk_buff* skb,
+    IN UINT     FrameSize,
+    IN UINT     cbHeaderOffset,
+    IN INT      iSANodeIndex,
+    IN INT      iDANodeIndex
+    )
+#endif
+{
+    PSMgmtObject        pMgmt = pDevice->pMgmt;
+    BOOL                bRelayAndForward = FALSE;
+    BOOL                bRelayOnly = FALSE;
+    BYTE                byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80};
+    WORD                wAID;
+#ifdef PRIVATE_OBJ
+    struct sk_buff* tmp_skb;
+    ref_sk_buff     s_ref_skb;
+    ref_sk_buff*    skbcpy = &s_ref_skb;
+#else
+    struct sk_buff* skbcpy = NULL;
+#endif
+
+
+
+    if (FrameSize > CB_MAX_BUF_SIZE)
+        return FALSE;
+    // check DA
+    if(IS_MULTICAST_ADDRESS((PBYTE)(skb->data+cbHeaderOffset))) {
+       if (pMgmt->sNodeDBTable[0].bPSEnable) {
+
+#ifdef PRIVATE_OBJ
+           tmp_skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
+           skbcpy = &s_ref_skb;
+           ref_skb_remap(pDevice->dev, skbcpy, tmp_skb);
+#else
+           skbcpy = dev_alloc_skb((int)pDevice->rx_buf_sz);
+#endif
+        // if any node in PS mode, buffer packet until DTIM.
+           if (skbcpy == NULL) {
+               DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "relay multicast no skb available \n");
+           }
+           else {
+               skbcpy->dev = pDevice->dev;
+#ifdef PRIVATE_OBJ
+               *(skbcpy->len) = FrameSize;
+               memcpy(skbcpy->data, skb->data+cbHeaderOffset, FrameSize);
+               skb_queue_tail(&(pMgmt->sNodeDBTable[0].sTxPSQueue), skbcpy->skb);
+#else
+               skbcpy->len = FrameSize;
+               memcpy(skbcpy->data, skb->data+cbHeaderOffset, FrameSize);
+               skb_queue_tail(&(pMgmt->sNodeDBTable[0].sTxPSQueue), skbcpy);
+#endif
+               pMgmt->sNodeDBTable[0].wEnQueueCnt++;
+               // set tx map
+               pMgmt->abyPSTxMap[0] |= byMask[0];
+           }
+       }
+       else {
+           bRelayAndForward = TRUE;
+       }
+    }
+    else {
+        // check if relay
+        if (BSSDBbIsSTAInNodeDB(pMgmt, (PBYTE)(skb->data+cbHeaderOffset), &iDANodeIndex)) {
+            if (pMgmt->sNodeDBTable[iDANodeIndex].eNodeState >= NODE_ASSOC) {
+                if (pMgmt->sNodeDBTable[iDANodeIndex].bPSEnable) {
+                    // queue this skb until next PS tx, and then release.
+
+#ifdef PRIVATE_OBJ
+                    ref_skb_add_offset(skb->skb, cbHeaderOffset);
+                    skb_put(skb->skb, FrameSize);
+                    skb_queue_tail(&pMgmt->sNodeDBTable[iDANodeIndex].sTxPSQueue, skb->skb);
+#else
+	                skb->data += cbHeaderOffset;
+	                skb->tail += cbHeaderOffset;
+                    skb_put(skb, FrameSize);
+                    skb_queue_tail(&pMgmt->sNodeDBTable[iDANodeIndex].sTxPSQueue, skb);
+#endif
+                    pMgmt->sNodeDBTable[iDANodeIndex].wEnQueueCnt++;
+                    wAID = pMgmt->sNodeDBTable[iDANodeIndex].wAID;
+                    pMgmt->abyPSTxMap[wAID >> 3] |=  byMask[wAID & 7];
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "relay: index= %d, pMgmt->abyPSTxMap[%d]= %d\n",
+                               iDANodeIndex, (wAID >> 3), pMgmt->abyPSTxMap[wAID >> 3]);
+                    return TRUE;
+                }
+                else {
+                    bRelayOnly = TRUE;
+                }
+            }
+        };
+    }
+
+    if (bRelayOnly || bRelayAndForward) {
+        // relay this packet right now
+        if (bRelayAndForward)
+            iDANodeIndex = 0;
+
+        if ((pDevice->uAssocCount > 1) && (iDANodeIndex >= 0)) {
+            ROUTEbRelay(pDevice, (PBYTE)(skb->data + cbHeaderOffset), FrameSize, (UINT)iDANodeIndex);
+        }
+
+        if (bRelayOnly)
+            return FALSE;
+    }
+    // none associate, don't forward
+    if (pDevice->uAssocCount == 0)
+        return FALSE;
+
+    return TRUE;
+}
+
diff --git a/drivers/staging/vt6655/dpc.h b/drivers/staging/vt6655/dpc.h
new file mode 100644
index 0000000..68447c4
--- /dev/null
+++ b/drivers/staging/vt6655/dpc.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: whdr.h
+ *
+ * Purpose:
+ *
+ * Author: Jerry Chen
+ *
+ * Date: Jun. 27, 2002
+ *
+ */
+
+
+#ifndef __DPC_H__
+#define __DPC_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__WCMD_H__)
+#include "wcmd.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+
+BOOL
+device_receive_frame (
+    IN  PSDevice pDevice,
+    IN  PSRxDesc pCurrRD
+    );
+
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+VOID	MngWorkItem(PVOID Context);
+#endif // __RXTX_H__
+
+
+
diff --git a/drivers/staging/vt6655/hostap.c b/drivers/staging/vt6655/hostap.c
new file mode 100644
index 0000000..91f189dd
--- /dev/null
+++ b/drivers/staging/vt6655/hostap.c
@@ -0,0 +1,914 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: hostap.c
+ *
+ * Purpose: handle hostap deamon ioctl input/out functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: Oct. 20, 2003
+ *
+ * Functions:
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__HOSTAP_H__)
+#include "hostap.h"
+#endif
+#if !defined(__IOCMD_H__)
+#include "iocmd.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+#if !defined(__WPACTL_H__)
+#include "wpactl.h"
+#endif
+#if !defined(__KEY_H__)
+#include "key.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+
+
+#define VIAWGET_HOSTAPD_MAX_BUF_SIZE 1024
+#define HOSTAP_CRYPT_FLAG_SET_TX_KEY BIT0
+#define HOSTAP_CRYPT_FLAG_PERMANENT BIT1
+#define HOSTAP_CRYPT_ERR_UNKNOWN_ALG 2
+#define HOSTAP_CRYPT_ERR_UNKNOWN_ADDR 3
+#define HOSTAP_CRYPT_ERR_CRYPT_INIT_FAILED 4
+#define HOSTAP_CRYPT_ERR_KEY_SET_FAILED 5
+#define HOSTAP_CRYPT_ERR_TX_KEY_SET_FAILED 6
+#define HOSTAP_CRYPT_ERR_CARD_CONF_FAILED 7
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+static int          msglevel                =MSG_LEVEL_INFO;
+
+/*---------------------  Static Functions  --------------------------*/
+
+
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*
+ * Description:
+ *      register net_device (AP) for hostap deamon
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             -
+ *      rtnl_locked         -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int hostap_enable_hostapd(PSDevice pDevice, int rtnl_locked)
+{
+    PSDevice apdev_priv;
+	struct net_device *dev = pDevice->dev;
+	int ret;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: Enabling hostapd mode\n", dev->name);
+
+#ifdef PRIVATE_OBJ
+    pDevice->apdev = ref_init_apdev(dev);
+
+    if (pDevice->apdev == NULL)
+		return -ENOMEM;
+
+	if (rtnl_locked)
+		ret = register_netdevice(pDevice->apdev);
+	else
+		ret = register_netdev(pDevice->apdev);
+	if (ret) {
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: register_netdevice(AP) failed!\n",
+		       dev->name);
+		return -1;
+	}
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: Registered netdevice %s for AP management\n",
+	       dev->name, pDevice->apdev->name);
+
+#else
+    pDevice->apdev = (struct net_device *)kmalloc(sizeof(struct net_device), GFP_KERNEL);
+	if (pDevice->apdev == NULL)
+		return -ENOMEM;
+	memset(pDevice->apdev, 0, sizeof(struct net_device));
+
+    apdev_priv = netdev_priv(pDevice->apdev);
+    *apdev_priv = *pDevice;
+	memcpy(pDevice->apdev->dev_addr, dev->dev_addr, ETH_ALEN);
+
+    const struct net_device_ops apdev_netdev_ops = {
+        .ndo_start_xmit         = pDevice->tx_80211,
+    };
+    pDevice->apdev->netdev_ops = &apdev_netdev_ops;
+
+	pDevice->apdev->type = ARPHRD_IEEE80211;
+
+	pDevice->apdev->base_addr = dev->base_addr;
+	pDevice->apdev->irq = dev->irq;
+	pDevice->apdev->mem_start = dev->mem_start;
+	pDevice->apdev->mem_end = dev->mem_end;
+	sprintf(pDevice->apdev->name, "%sap", dev->name);
+	if (rtnl_locked)
+		ret = register_netdevice(pDevice->apdev);
+	else
+		ret = register_netdev(pDevice->apdev);
+	if (ret) {
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: register_netdevice(AP) failed!\n",
+		       dev->name);
+		return -1;
+	}
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: Registered netdevice %s for AP management\n",
+	       dev->name, pDevice->apdev->name);
+
+    KeyvInitTable(&pDevice->sKey, pDevice->PortOffset);
+#endif
+
+	return 0;
+}
+
+/*
+ * Description:
+ *      unregister net_device(AP)
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             -
+ *      rtnl_locked         -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int hostap_disable_hostapd(PSDevice pDevice, int rtnl_locked)
+{
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: disabling hostapd mode\n", pDevice->dev->name);
+
+    if (pDevice->apdev && pDevice->apdev->name && pDevice->apdev->name[0]) {
+		if (rtnl_locked)
+			unregister_netdevice(pDevice->apdev);
+		else
+			unregister_netdev(pDevice->apdev);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: Netdevice %s unregistered\n",
+		       pDevice->dev->name, pDevice->apdev->name);
+	}
+	kfree(pDevice->apdev);
+	pDevice->apdev = NULL;
+    pDevice->bEnable8021x = FALSE;
+    pDevice->bEnableHostWEP = FALSE;
+    pDevice->bEncryptionEnable = FALSE;
+
+//4.2007-0118-03,<Add> by EinsnLiu
+//execute some clear work
+pDevice->pMgmt->byCSSPK=KEY_CTL_NONE;
+pDevice->pMgmt->byCSSGK=KEY_CTL_NONE;
+KeyvInitTable(&pDevice->sKey,pDevice->PortOffset);
+
+	return 0;
+}
+
+
+/*
+ * Description:
+ *      Set enable/disable hostapd mode
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             -
+ *      rtnl_locked         -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+int hostap_set_hostapd(PSDevice pDevice, int val, int rtnl_locked)
+{
+	if (val < 0 || val > 1)
+		return -EINVAL;
+
+	if (pDevice->bEnableHostapd == val)
+		return 0;
+
+	pDevice->bEnableHostapd = val;
+
+	if (val)
+		return hostap_enable_hostapd(pDevice, rtnl_locked);
+	else
+		return hostap_disable_hostapd(pDevice, rtnl_locked);
+}
+
+
+/*
+ * Description:
+ *      remove station function supported for hostap deamon
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+static int hostap_remove_sta(PSDevice pDevice,
+				     struct viawget_hostapd_param *param)
+{
+	UINT uNodeIndex;
+
+
+    if (BSSDBbIsSTAInNodeDB(pDevice->pMgmt, param->sta_addr, &uNodeIndex)) {
+        BSSvRemoveOneNode(pDevice, uNodeIndex);
+    }
+    else {
+        return -ENOENT;
+    }
+	return 0;
+}
+
+/*
+ * Description:
+ *      add a station from hostap deamon
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+static int hostap_add_sta(PSDevice pDevice,
+				  struct viawget_hostapd_param *param)
+{
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+	UINT uNodeIndex;
+
+
+    if (!BSSDBbIsSTAInNodeDB(pMgmt, param->sta_addr, &uNodeIndex)) {
+        BSSvCreateOneNode((PSDevice)pDevice, &uNodeIndex);
+    }
+    memcpy(pMgmt->sNodeDBTable[uNodeIndex].abyMACAddr, param->sta_addr, WLAN_ADDR_LEN);
+    pMgmt->sNodeDBTable[uNodeIndex].eNodeState = NODE_ASSOC;
+    pMgmt->sNodeDBTable[uNodeIndex].wCapInfo = param->u.add_sta.capability;
+// TODO listenInterval
+//    pMgmt->sNodeDBTable[uNodeIndex].wListenInterval = 1;
+    pMgmt->sNodeDBTable[uNodeIndex].bPSEnable = FALSE;
+    pMgmt->sNodeDBTable[uNodeIndex].bySuppRate = param->u.add_sta.tx_supp_rates;
+
+    // set max tx rate
+    pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate =
+           pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate;
+    // set max basic rate
+    pMgmt->sNodeDBTable[uNodeIndex].wMaxBasicRate = RATE_2M;
+    // Todo: check sta preamble, if ap can't support, set status code
+    pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble =
+            WLAN_GET_CAP_INFO_SHORTPREAMBLE(pMgmt->sNodeDBTable[uNodeIndex].wCapInfo);
+
+    pMgmt->sNodeDBTable[uNodeIndex].wAID = (WORD)param->u.add_sta.aid;
+#ifdef PRIVATE_OBJ
+    pMgmt->sNodeDBTable[uNodeIndex].ulLastRxJiffer = get_jiffies();
+#else
+    pMgmt->sNodeDBTable[uNodeIndex].ulLastRxJiffer = jiffies;
+#endif
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Add STA AID= %d \n", pMgmt->sNodeDBTable[uNodeIndex].wAID);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "MAC=%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X \n",
+               param->sta_addr[0],
+               param->sta_addr[1],
+               param->sta_addr[2],
+               param->sta_addr[3],
+               param->sta_addr[4],
+               param->sta_addr[5]
+              ) ;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Max Support rate = %d \n",
+               pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate);
+
+	return 0;
+}
+
+/*
+ * Description:
+ *      get station info
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int hostap_get_info_sta(PSDevice pDevice,
+				       struct viawget_hostapd_param *param)
+{
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+	UINT uNodeIndex;
+
+    if (BSSDBbIsSTAInNodeDB(pMgmt, param->sta_addr, &uNodeIndex)) {
+#ifdef PRIVATE_OBJ
+	    param->u.get_info_sta.inactive_sec =
+	        (get_jiffies() - pMgmt->sNodeDBTable[uNodeIndex].ulLastRxJiffer) / HZ;
+#else
+	    param->u.get_info_sta.inactive_sec =
+	        (jiffies - pMgmt->sNodeDBTable[uNodeIndex].ulLastRxJiffer) / HZ;
+#endif
+	    //param->u.get_info_sta.txexc = pMgmt->sNodeDBTable[uNodeIndex].uTxAttempts;
+	}
+	else {
+	    return -ENOENT;
+	}
+
+	return 0;
+}
+
+/*
+ * Description:
+ *      reset txexec
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *      TURE, FALSE
+ *
+ * Return Value:
+ *
+ */
+/*
+static int hostap_reset_txexc_sta(PSDevice pDevice,
+					  struct viawget_hostapd_param *param)
+{
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+	UINT uNodeIndex;
+
+    if (BSSDBbIsSTAInNodeDB(pMgmt, param->sta_addr, &uNodeIndex)) {
+        pMgmt->sNodeDBTable[uNodeIndex].uTxAttempts = 0;
+	}
+	else {
+	    return -ENOENT;
+	}
+
+	return 0;
+}
+*/
+
+/*
+ * Description:
+ *      set station flag
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+static int hostap_set_flags_sta(PSDevice pDevice,
+					struct viawget_hostapd_param *param)
+{
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+	UINT uNodeIndex;
+
+    if (BSSDBbIsSTAInNodeDB(pMgmt, param->sta_addr, &uNodeIndex)) {
+		pMgmt->sNodeDBTable[uNodeIndex].dwFlags |= param->u.set_flags_sta.flags_or;
+		pMgmt->sNodeDBTable[uNodeIndex].dwFlags &= param->u.set_flags_sta.flags_and;
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " dwFlags = %x \n",
+		            (UINT)pMgmt->sNodeDBTable[uNodeIndex].dwFlags);
+	}
+	else {
+	    return -ENOENT;
+	}
+
+	return 0;
+}
+
+
+
+/*
+ * Description:
+ *      set generic element (wpa ie)
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+static int hostap_set_generic_element(PSDevice pDevice,
+					struct viawget_hostapd_param *param)
+{
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+
+
+
+    memcpy( pMgmt->abyWPAIE,
+            param->u.generic_elem.data,
+            param->u.generic_elem.len
+           );
+
+    pMgmt->wWPAIELen = 	param->u.generic_elem.len;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pMgmt->wWPAIELen = %d\n",  pMgmt->wWPAIELen);
+
+    // disable wpa
+    if (pMgmt->wWPAIELen == 0) {
+        pMgmt->eAuthenMode = WMAC_AUTH_OPEN;
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " No WPAIE, Disable WPA \n");
+    } else  {
+        // enable wpa
+        if ((pMgmt->abyWPAIE[0] == WLAN_EID_RSN_WPA) ||
+             (pMgmt->abyWPAIE[0] == WLAN_EID_RSN)) {
+              pMgmt->eAuthenMode = WMAC_AUTH_WPANONE;
+               DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Set WPAIE enable WPA\n");
+        } else
+            return -EINVAL;
+    }
+
+	return 0;
+}
+
+/*
+ * Description:
+ *      flush station nodes table.
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static void hostap_flush_sta(PSDevice pDevice)
+{
+    // reserved node index =0 for multicast node.
+    BSSvClearNodeDBTable(pDevice, 1);
+    pDevice->uAssocCount = 0;
+
+    return;
+}
+
+/*
+ * Description:
+ *      set each stations encryption key
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+static int hostap_set_encryption(PSDevice pDevice,
+				       struct viawget_hostapd_param *param,
+				       int param_len)
+{
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    DWORD   dwKeyIndex = 0;
+    BYTE    abyKey[MAX_KEY_LEN];
+    BYTE    abySeq[MAX_KEY_LEN];
+    NDIS_802_11_KEY_RSC   KeyRSC;
+    BYTE    byKeyDecMode = KEY_CTL_WEP;
+	int     ret = 0;
+	int     iNodeIndex = -1;
+	int     ii;
+	BOOL    bKeyTableFull = FALSE;
+	WORD    wKeyCtl = 0;
+
+
+	param->u.crypt.err = 0;
+/*
+	if (param_len !=
+	    (int) ((char *) param->u.crypt.key - (char *) param) +
+	    param->u.crypt.key_len)
+		return -EINVAL;
+*/
+
+	if (param->u.crypt.alg > WPA_ALG_CCMP)
+		return -EINVAL;
+
+
+	if ((param->u.crypt.idx > 3) || (param->u.crypt.key_len > MAX_KEY_LEN)) {
+		param->u.crypt.err = HOSTAP_CRYPT_ERR_KEY_SET_FAILED;
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " HOSTAP_CRYPT_ERR_KEY_SET_FAILED\n");
+		return -EINVAL;
+	}
+
+	if (param->sta_addr[0] == 0xff && param->sta_addr[1] == 0xff &&
+	    param->sta_addr[2] == 0xff && param->sta_addr[3] == 0xff &&
+	    param->sta_addr[4] == 0xff && param->sta_addr[5] == 0xff) {
+		if (param->u.crypt.idx >= MAX_GROUP_KEY)
+			return -EINVAL;
+        iNodeIndex = 0;
+
+	} else {
+	    if (BSSDBbIsSTAInNodeDB(pMgmt, param->sta_addr, &iNodeIndex) == FALSE) {
+	        param->u.crypt.err = HOSTAP_CRYPT_ERR_UNKNOWN_ADDR;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " HOSTAP_CRYPT_ERR_UNKNOWN_ADDR\n");
+	        return -EINVAL;
+	    }
+	}
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " hostap_set_encryption: sta_index %d \n", iNodeIndex);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " hostap_set_encryption: alg %d \n", param->u.crypt.alg);
+
+	if (param->u.crypt.alg == WPA_ALG_NONE) {
+
+        if (pMgmt->sNodeDBTable[iNodeIndex].bOnFly == TRUE) {
+            if (KeybRemoveKey(&(pDevice->sKey),
+                                param->sta_addr,
+                                pMgmt->sNodeDBTable[iNodeIndex].dwKeyIndex,
+                                pDevice->PortOffset) == FALSE) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "KeybRemoveKey fail \n");
+            }
+            pMgmt->sNodeDBTable[iNodeIndex].bOnFly = FALSE;
+        }
+        pMgmt->sNodeDBTable[iNodeIndex].byKeyIndex = 0;
+        pMgmt->sNodeDBTable[iNodeIndex].dwKeyIndex = 0;
+        pMgmt->sNodeDBTable[iNodeIndex].uWepKeyLength = 0;
+        pMgmt->sNodeDBTable[iNodeIndex].KeyRSC = 0;
+        pMgmt->sNodeDBTable[iNodeIndex].dwTSC47_16 = 0;
+        pMgmt->sNodeDBTable[iNodeIndex].wTSC15_0 = 0;
+        pMgmt->sNodeDBTable[iNodeIndex].byCipherSuite = 0;
+        memset(&pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[0],
+                0,
+                MAX_KEY_LEN
+               );
+
+        return ret;
+	}
+
+    memcpy(abyKey, param->u.crypt.key, param->u.crypt.key_len);
+    // copy to node key tbl
+    pMgmt->sNodeDBTable[iNodeIndex].byKeyIndex = param->u.crypt.idx;
+    pMgmt->sNodeDBTable[iNodeIndex].uWepKeyLength = param->u.crypt.key_len;
+    memcpy(&pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[0],
+            param->u.crypt.key,
+            param->u.crypt.key_len
+           );
+
+    dwKeyIndex = (DWORD)(param->u.crypt.idx);
+    if (param->u.crypt.flags & HOSTAP_CRYPT_FLAG_SET_TX_KEY) {
+        pDevice->byKeyIndex = (BYTE)dwKeyIndex;
+        pDevice->bTransmitKey = TRUE;
+        dwKeyIndex |= (1 << 31);
+    }
+
+	if (param->u.crypt.alg == WPA_ALG_WEP) {
+
+        if ((pDevice->bEnable8021x == FALSE) || (iNodeIndex == 0)) {
+            KeybSetDefaultKey(&(pDevice->sKey),
+                                dwKeyIndex & ~(BIT30 | USE_KEYRSC),
+                                param->u.crypt.key_len,
+                                NULL,
+                                abyKey,
+                                KEY_CTL_WEP,
+                                pDevice->PortOffset,
+                                pDevice->byLocalID);
+
+        } else {
+            // 8021x enable, individual key
+            dwKeyIndex |= (1 << 30); // set pairwise key
+            if (KeybSetKey(&(pDevice->sKey),
+                           &param->sta_addr[0],
+                           dwKeyIndex & ~(USE_KEYRSC),
+                           param->u.crypt.key_len,
+                           (PQWORD) &(KeyRSC),
+                           (PBYTE)abyKey,
+                            KEY_CTL_WEP,
+                            pDevice->PortOffset,
+                            pDevice->byLocalID) == TRUE) {
+
+                pMgmt->sNodeDBTable[iNodeIndex].bOnFly = TRUE;
+
+            } else {
+                // Key Table Full
+                pMgmt->sNodeDBTable[iNodeIndex].bOnFly = FALSE;
+                bKeyTableFull = TRUE;
+            }
+        }
+        pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
+        pDevice->bEncryptionEnable = TRUE;
+        pMgmt->byCSSPK = KEY_CTL_WEP;
+        pMgmt->byCSSGK = KEY_CTL_WEP;
+        pMgmt->sNodeDBTable[iNodeIndex].byCipherSuite = KEY_CTL_WEP;
+        pMgmt->sNodeDBTable[iNodeIndex].dwKeyIndex = dwKeyIndex;
+        return ret;
+	}
+
+	if (param->u.crypt.seq) {
+	    memcpy(&abySeq, param->u.crypt.seq, 8);
+		for (ii = 0 ; ii < 8 ; ii++) {
+	         KeyRSC |= (abySeq[ii] << (ii * 8));
+		}
+		dwKeyIndex |= 1 << 29;
+		pMgmt->sNodeDBTable[iNodeIndex].KeyRSC = KeyRSC;
+	}
+
+	if (param->u.crypt.alg == WPA_ALG_TKIP) {
+	    if (param->u.crypt.key_len != MAX_KEY_LEN)
+	        return -EINVAL;
+	    pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;
+        byKeyDecMode = KEY_CTL_TKIP;
+        pMgmt->byCSSPK = KEY_CTL_TKIP;
+        pMgmt->byCSSGK = KEY_CTL_TKIP;
+	}
+
+	if (param->u.crypt.alg == WPA_ALG_CCMP) {
+	    if ((param->u.crypt.key_len != AES_KEY_LEN) ||
+	        (pDevice->byLocalID <= REV_ID_VT3253_A1))
+	        return -EINVAL;
+        pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;
+        byKeyDecMode = KEY_CTL_CCMP;
+        pMgmt->byCSSPK = KEY_CTL_CCMP;
+        pMgmt->byCSSGK = KEY_CTL_CCMP;
+    }
+
+
+    if (iNodeIndex == 0) {
+       KeybSetDefaultKey(&(pDevice->sKey),
+                           dwKeyIndex,
+                           param->u.crypt.key_len,
+                           (PQWORD) &(KeyRSC),
+                           abyKey,
+                           byKeyDecMode,
+                           pDevice->PortOffset,
+                           pDevice->byLocalID);
+       pMgmt->sNodeDBTable[iNodeIndex].bOnFly = TRUE;
+
+    } else {
+        dwKeyIndex |= (1 << 30); // set pairwise key
+        if (KeybSetKey(&(pDevice->sKey),
+                       &param->sta_addr[0],
+                       dwKeyIndex,
+                       param->u.crypt.key_len,
+                       (PQWORD) &(KeyRSC),
+                       (PBYTE)abyKey,
+                        byKeyDecMode,
+                        pDevice->PortOffset,
+                        pDevice->byLocalID) == TRUE) {
+
+            pMgmt->sNodeDBTable[iNodeIndex].bOnFly = TRUE;
+
+        } else {
+            // Key Table Full
+            pMgmt->sNodeDBTable[iNodeIndex].bOnFly = FALSE;
+            bKeyTableFull = TRUE;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " Key Table Full\n");
+        }
+
+    }
+
+    if (bKeyTableFull == TRUE) {
+        wKeyCtl &= 0x7F00;              // clear all key control filed
+        wKeyCtl |= (byKeyDecMode << 4);
+        wKeyCtl |= (byKeyDecMode);
+        wKeyCtl |= 0x0044;              // use group key for all address
+        wKeyCtl |= 0x4000;              // disable KeyTable[MAX_KEY_TABLE-1] on-fly to genernate rx int
+        MACvSetDefaultKeyCtl(pDevice->PortOffset, wKeyCtl, MAX_KEY_TABLE-1, pDevice->byLocalID);
+    }
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " Set key sta_index= %d \n", iNodeIndex);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " tx_index=%d len=%d \n", param->u.crypt.idx,
+               param->u.crypt.key_len );
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " key=%x-%x-%x-%x-%x-xxxxx \n",
+               pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[0],
+               pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[1],
+               pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[2],
+               pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[3],
+               pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[4]
+              );
+
+	// set wep key
+    pDevice->bEncryptionEnable = TRUE;
+    pMgmt->sNodeDBTable[iNodeIndex].byCipherSuite = byKeyDecMode;
+    pMgmt->sNodeDBTable[iNodeIndex].dwKeyIndex = dwKeyIndex;
+    pMgmt->sNodeDBTable[iNodeIndex].dwTSC47_16 = 0;
+    pMgmt->sNodeDBTable[iNodeIndex].wTSC15_0 = 0;
+
+	return ret;
+}
+
+
+
+/*
+ * Description:
+ *      get each stations encryption key
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+static int hostap_get_encryption(PSDevice pDevice,
+				       struct viawget_hostapd_param *param,
+				       int param_len)
+{
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+	int     ret = 0;
+	int     ii;
+	int     iNodeIndex =0;
+
+
+	param->u.crypt.err = 0;
+
+	if (param->sta_addr[0] == 0xff && param->sta_addr[1] == 0xff &&
+	    param->sta_addr[2] == 0xff && param->sta_addr[3] == 0xff &&
+	    param->sta_addr[4] == 0xff && param->sta_addr[5] == 0xff) {
+        iNodeIndex = 0;
+	} else {
+	    if (BSSDBbIsSTAInNodeDB(pMgmt, param->sta_addr, &iNodeIndex) == FALSE) {
+	        param->u.crypt.err = HOSTAP_CRYPT_ERR_UNKNOWN_ADDR;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "hostap_get_encryption: HOSTAP_CRYPT_ERR_UNKNOWN_ADDR\n");
+	        return -EINVAL;
+	    }
+	}
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "hostap_get_encryption: %d\n", iNodeIndex);
+    memset(param->u.crypt.seq, 0, 8);
+    for (ii = 0 ; ii < 8 ; ii++) {
+        param->u.crypt.seq[ii] = (BYTE)pMgmt->sNodeDBTable[iNodeIndex].KeyRSC >> (ii * 8);
+    }
+
+	return ret;
+}
+
+
+/*
+ * Description:
+ *      hostap_ioctl main function supported for hostap deamon.
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      iw_point  -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+int hostap_ioctl(PSDevice pDevice, struct iw_point *p)
+{
+	struct viawget_hostapd_param *param;
+	int ret = 0;
+	int ap_ioctl = 0;
+
+	if (p->length < sizeof(struct viawget_hostapd_param) ||
+	    p->length > VIAWGET_HOSTAPD_MAX_BUF_SIZE || !p->pointer)
+		return -EINVAL;
+
+	param = (struct viawget_hostapd_param *) kmalloc((int)p->length, (int)GFP_KERNEL);
+	if (param == NULL)
+		return -ENOMEM;
+
+	if (copy_from_user(param, p->pointer, p->length)) {
+		ret = -EFAULT;
+		goto out;
+	}
+
+	switch (param->cmd) {
+	case VIAWGET_HOSTAPD_SET_ENCRYPTION:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_SET_ENCRYPTION \n");
+        spin_lock_irq(&pDevice->lock);
+		ret = hostap_set_encryption(pDevice, param, p->length);
+        spin_unlock_irq(&pDevice->lock);
+		break;
+	case VIAWGET_HOSTAPD_GET_ENCRYPTION:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_GET_ENCRYPTION \n");
+        spin_lock_irq(&pDevice->lock);
+		ret = hostap_get_encryption(pDevice, param, p->length);
+        spin_unlock_irq(&pDevice->lock);
+		break;
+	case VIAWGET_HOSTAPD_SET_ASSOC_AP_ADDR:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_SET_ASSOC_AP_ADDR \n");
+		return -EOPNOTSUPP;
+		break;
+	case VIAWGET_HOSTAPD_FLUSH:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_FLUSH \n");
+        spin_lock_irq(&pDevice->lock);
+    	hostap_flush_sta(pDevice);
+        spin_unlock_irq(&pDevice->lock);
+		break;
+	case VIAWGET_HOSTAPD_ADD_STA:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_ADD_STA \n");
+         spin_lock_irq(&pDevice->lock);
+		 ret = hostap_add_sta(pDevice, param);
+         spin_unlock_irq(&pDevice->lock);
+		break;
+	case VIAWGET_HOSTAPD_REMOVE_STA:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_REMOVE_STA \n");
+         spin_lock_irq(&pDevice->lock);
+		 ret = hostap_remove_sta(pDevice, param);
+         spin_unlock_irq(&pDevice->lock);
+		break;
+	case VIAWGET_HOSTAPD_GET_INFO_STA:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_GET_INFO_STA \n");
+		 ret = hostap_get_info_sta(pDevice, param);
+		 ap_ioctl = 1;
+		break;
+/*
+	case VIAWGET_HOSTAPD_RESET_TXEXC_STA:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_RESET_TXEXC_STA \n");
+		 ret = hostap_reset_txexc_sta(pDevice, param);
+		break;
+*/
+	case VIAWGET_HOSTAPD_SET_FLAGS_STA:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_SET_FLAGS_STA \n");
+		 ret = hostap_set_flags_sta(pDevice, param);
+		break;
+
+	case VIAWGET_HOSTAPD_MLME:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_MLME \n");
+	    return -EOPNOTSUPP;
+
+	case VIAWGET_HOSTAPD_SET_GENERIC_ELEMENT:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_SET_GENERIC_ELEMENT \n");
+		ret = hostap_set_generic_element(pDevice, param);
+		break;
+
+	case VIAWGET_HOSTAPD_SCAN_REQ:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_SCAN_REQ \n");
+	    return -EOPNOTSUPP;
+
+	case VIAWGET_HOSTAPD_STA_CLEAR_STATS:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_HOSTAPD_STA_CLEAR_STATS \n");
+	    return -EOPNOTSUPP;
+
+	default:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "hostap_ioctl: unknown cmd=%d\n",
+		       (int)param->cmd);
+		return -EOPNOTSUPP;
+		break;
+	}
+
+
+	if ((ret == 0) && ap_ioctl) {
+		if (copy_to_user(p->pointer, param, p->length)) {
+			ret = -EFAULT;
+			goto out;
+		}
+	}
+
+ out:
+	if (param != NULL)
+		kfree(param);
+
+	return ret;
+}
+
diff --git a/drivers/staging/vt6655/hostap.h b/drivers/staging/vt6655/hostap.h
new file mode 100644
index 0000000..1fcb2f0
--- /dev/null
+++ b/drivers/staging/vt6655/hostap.h
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: hostap.h
+ *
+ * Purpose:
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 21, 2003
+ *
+ */
+
+
+#ifndef __HOSTAP_H__
+#define __HOSTAP_H__
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+#if WIRELESS_EXT < 9
+struct iw_point {
+	caddr_t pointer;
+	__u16 length;
+	__u16 flags;
+};
+#endif /* WIRELESS_EXT < 9 */
+
+#define WLAN_RATE_1M    BIT0
+#define WLAN_RATE_2M    BIT1
+#define WLAN_RATE_5M5   BIT2
+#define WLAN_RATE_11M   BIT3
+#define WLAN_RATE_6M    BIT4
+#define WLAN_RATE_9M    BIT5
+#define WLAN_RATE_12M   BIT6
+#define WLAN_RATE_18M   BIT7
+#define WLAN_RATE_24M   BIT8
+#define WLAN_RATE_36M   BIT9
+#define WLAN_RATE_48M   BIT10
+#define WLAN_RATE_54M   BIT11
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+#ifndef ETH_P_PAE
+#define ETH_P_PAE 0x888E /* Port Access Entity (IEEE 802.1X) */
+#endif /* ETH_P_PAE */
+
+#ifndef ARPHRD_IEEE80211
+#define ARPHRD_IEEE80211 801
+#endif
+
+int hostap_set_hostapd(PSDevice pDevice, int val, int rtnl_locked);
+int hostap_ioctl(PSDevice pDevice, struct iw_point *p);
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+
+#endif // __HOSTAP_H__
+
+
+
diff --git a/drivers/staging/vt6655/iocmd.h b/drivers/staging/vt6655/iocmd.h
new file mode 100644
index 0000000..ada9ee9
--- /dev/null
+++ b/drivers/staging/vt6655/iocmd.h
@@ -0,0 +1,481 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: iocmd.h
+ *
+ * Purpose: Handles the viawget ioctl private interface functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 8, 2002
+ *
+ */
+
+#ifndef __IOCMD_H__
+#define __IOCMD_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+#if !defined(DEF)
+#define DEF
+#endif
+
+//typedef int BOOL;
+//typedef uint32_t u32;
+//typedef uint16_t u16;
+//typedef uint8_t u8;
+
+
+// ioctl Command code
+#define MAGIC_CODE	                 0x3142
+#define IOCTL_CMD_TEST	            (SIOCDEVPRIVATE + 0)
+#define IOCTL_CMD_SET			    (SIOCDEVPRIVATE + 1)
+#define IOCTL_CMD_HOSTAPD           (SIOCDEVPRIVATE + 2)
+#define IOCTL_CMD_WPA               (SIOCDEVPRIVATE + 3)
+
+
+typedef enum tagWMAC_CMD {
+
+    WLAN_CMD_BSS_SCAN,
+    WLAN_CMD_BSS_JOIN,
+    WLAN_CMD_DISASSOC,
+    WLAN_CMD_SET_WEP,
+    WLAN_CMD_GET_LINK,
+    WLAN_CMD_GET_LISTLEN,
+    WLAN_CMD_GET_LIST,
+    WLAN_CMD_GET_MIB,
+    WLAN_CMD_GET_STAT,
+    WLAN_CMD_STOP_MAC,
+    WLAN_CMD_START_MAC,
+    WLAN_CMD_AP_START,
+    WLAN_CMD_SET_HOSTAPD,
+    WLAN_CMD_SET_HOSTAPD_STA,
+    WLAN_CMD_SET_802_1X,
+    WLAN_CMD_SET_HOST_WEP,
+    WLAN_CMD_SET_WPA,
+    WLAN_CMD_GET_NODE_CNT,
+     WLAN_CMD_ZONETYPE_SET,
+    WLAN_CMD_GET_NODE_LIST
+
+} WMAC_CMD, DEF* PWMAC_CMD;
+
+	typedef enum tagWZONETYPE {
+  ZoneType_USA=0,
+  ZoneType_Japan=1,
+  ZoneType_Europe=2
+}WZONETYPE;
+
+#define ADHOC	0
+#define INFRA	1
+#define BOTH	2
+#define AP	    3
+
+#define ADHOC_STARTED	   1
+#define ADHOC_JOINTED	   2
+
+
+#define PHY80211a 	    0
+#define PHY80211b       1
+#define PHY80211g       2
+
+#define SSID_ID                0
+#define SSID_MAXLEN            32
+#define BSSID_LEN              6
+#define WEP_NKEYS              4
+#define WEP_KEYMAXLEN          29
+#define WEP_40BIT_LEN          5
+#define WEP_104BIT_LEN         13
+#define WEP_232BIT_LEN         16
+
+
+// Ioctl interface structure
+// Command structure
+//
+#pragma pack(1)
+typedef struct tagSCmdRequest {
+	U8 	    name[16];
+	void	*data;
+	U16	    wResult;
+	U16     wCmdCode;
+} SCmdRequest, *PSCmdRequest;
+
+
+//
+// Scan
+//
+
+typedef struct tagSCmdScan {
+
+    U8	    ssid[SSID_MAXLEN + 2];
+
+} SCmdScan, *PSCmdScan;
+
+
+//
+// BSS Join
+//
+
+typedef struct tagSCmdBSSJoin {
+
+    U16	    wBSSType;
+    U16     wBBPType;
+    U8	    ssid[SSID_MAXLEN + 2];
+    U32	    uChannel;
+    BOOL    bPSEnable;
+    BOOL    bShareKeyAuth;
+
+} SCmdBSSJoin, *PSCmdBSSJoin;
+
+typedef struct tagSCmdZoneTypeSet {
+
+ BOOL       bWrite;
+ WZONETYPE  ZoneType;
+
+} SCmdZoneTypeSet, *PSCmdZoneTypeSet;
+
+#ifdef WPA_SM_Transtatus
+typedef struct tagSWPAResult {
+         char	ifname[100];
+         U8		proto;
+         U8   key_mgmt;
+         U8   eap_type;
+         BOOL authenticated;
+} SWPAResult, *PSWPAResult;
+#endif
+
+
+typedef struct tagSCmdStartAP {
+
+    U16	    wBSSType;
+    U16     wBBPType;
+    U8	    ssid[SSID_MAXLEN + 2];
+    U32 	uChannel;
+    U32     uBeaconInt;
+    BOOL    bShareKeyAuth;
+    U8      byBasicRate;
+
+} SCmdStartAP, *PSCmdStartAP;
+
+
+typedef struct tagSCmdSetWEP {
+
+    BOOL    bEnableWep;
+    U8      byKeyIndex;
+    U8      abyWepKey[WEP_NKEYS][WEP_KEYMAXLEN];
+    BOOL    bWepKeyAvailable[WEP_NKEYS];
+    U32     auWepKeyLength[WEP_NKEYS];
+
+} SCmdSetWEP, *PSCmdSetWEP;
+
+
+
+typedef struct tagSBSSIDItem {
+
+	U32	    uChannel;
+    U8      abyBSSID[BSSID_LEN];
+    U8      abySSID[SSID_MAXLEN + 1];
+    //2006-1116-01,<Modify> by NomadZhao
+    //U16	    wBeaconInterval;
+    //U16	    wCapInfo;
+    //U8      byNetType;
+    U8      byNetType;
+    U16	    wBeaconInterval;
+    U16	    wCapInfo;        // for address of byNetType at align 4
+
+    BOOL    bWEPOn;
+    U32     uRSSI;
+
+} SBSSIDItem;
+
+
+typedef struct tagSBSSIDList {
+
+	U32		    uItem;
+	SBSSIDItem	sBSSIDList[0];
+} SBSSIDList, *PSBSSIDList;
+
+
+typedef struct tagSCmdLinkStatus {
+
+    BOOL    bLink;
+	U16	    wBSSType;
+	U8      byState;
+    U8      abyBSSID[BSSID_LEN];
+    U8      abySSID[SSID_MAXLEN + 2];
+    U32     uChannel;
+    U32     uLinkRate;
+
+} SCmdLinkStatus, *PSCmdLinkStatus;
+
+//
+// 802.11 counter
+//
+typedef struct tagSDot11MIBCount {
+    U32 TransmittedFragmentCount;
+    U32 MulticastTransmittedFrameCount;
+    U32 FailedCount;
+    U32 RetryCount;
+    U32 MultipleRetryCount;
+    U32 RTSSuccessCount;
+    U32 RTSFailureCount;
+    U32 ACKFailureCount;
+    U32 FrameDuplicateCount;
+    U32 ReceivedFragmentCount;
+    U32 MulticastReceivedFrameCount;
+    U32 FCSErrorCount;
+} SDot11MIBCount, DEF* PSDot11MIBCount;
+
+
+
+//
+// statistic counter
+//
+typedef struct tagSStatMIBCount {
+    //
+    // ISR status count
+    //
+    U32   dwIsrTx0OK;
+    U32   dwIsrTx1OK;
+    U32   dwIsrBeaconTxOK;
+    U32   dwIsrRxOK;
+    U32   dwIsrTBTTInt;
+    U32   dwIsrSTIMERInt;
+    U32   dwIsrUnrecoverableError;
+    U32   dwIsrSoftInterrupt;
+    U32   dwIsrRxNoBuf;
+    /////////////////////////////////////
+
+    U32   dwIsrUnknown;               // unknown interrupt count
+
+    // RSR status count
+    //
+    U32   dwRsrFrmAlgnErr;
+    U32   dwRsrErr;
+    U32   dwRsrCRCErr;
+    U32   dwRsrCRCOk;
+    U32   dwRsrBSSIDOk;
+    U32   dwRsrADDROk;
+    U32   dwRsrICVOk;
+    U32   dwNewRsrShortPreamble;
+    U32   dwRsrLong;
+    U32   dwRsrRunt;
+
+    U32   dwRsrRxControl;
+    U32   dwRsrRxData;
+    U32   dwRsrRxManage;
+
+    U32   dwRsrRxPacket;
+    U32   dwRsrRxOctet;
+    U32   dwRsrBroadcast;
+    U32   dwRsrMulticast;
+    U32   dwRsrDirected;
+    // 64-bit OID
+    U32   ullRsrOK;
+
+    // for some optional OIDs (64 bits) and DMI support
+    U32   ullRxBroadcastBytes;
+    U32   ullRxMulticastBytes;
+    U32   ullRxDirectedBytes;
+    U32   ullRxBroadcastFrames;
+    U32   ullRxMulticastFrames;
+    U32   ullRxDirectedFrames;
+
+    U32   dwRsrRxFragment;
+    U32   dwRsrRxFrmLen64;
+    U32   dwRsrRxFrmLen65_127;
+    U32   dwRsrRxFrmLen128_255;
+    U32   dwRsrRxFrmLen256_511;
+    U32   dwRsrRxFrmLen512_1023;
+    U32   dwRsrRxFrmLen1024_1518;
+
+    // TSR0,1 status count
+    //
+    U32   dwTsrTotalRetry[2];        // total collision retry count
+    U32   dwTsrOnceRetry[2];         // this packet only occur one collision
+    U32   dwTsrMoreThanOnceRetry[2]; // this packet occur more than one collision
+    U32   dwTsrRetry[2];             // this packet has ever occur collision,
+                                       // that is (dwTsrOnceCollision0 + dwTsrMoreThanOnceCollision0)
+    U32   dwTsrACKData[2];
+    U32   dwTsrErr[2];
+    U32   dwAllTsrOK[2];
+    U32   dwTsrRetryTimeout[2];
+    U32   dwTsrTransmitTimeout[2];
+
+    U32   dwTsrTxPacket[2];
+    U32   dwTsrTxOctet[2];
+    U32   dwTsrBroadcast[2];
+    U32   dwTsrMulticast[2];
+    U32   dwTsrDirected[2];
+
+    // RD/TD count
+    U32   dwCntRxFrmLength;
+    U32   dwCntTxBufLength;
+
+    U8    abyCntRxPattern[16];
+    U8    abyCntTxPattern[16];
+
+    // Software check....
+    U32   dwCntRxDataErr;             // rx buffer data software compare CRC err count
+    U32   dwCntDecryptErr;            // rx buffer data software compare CRC err count
+    U32   dwCntRxICVErr;              // rx buffer data software compare CRC err count
+    U32    idxRxErrorDesc;             // index for rx data error RD
+
+    // 64-bit OID
+    U32   ullTsrOK[2];
+
+    // for some optional OIDs (64 bits) and DMI support
+    U32   ullTxBroadcastFrames[2];
+    U32   ullTxMulticastFrames[2];
+    U32   ullTxDirectedFrames[2];
+    U32   ullTxBroadcastBytes[2];
+    U32   ullTxMulticastBytes[2];
+    U32   ullTxDirectedBytes[2];
+} SStatMIBCount, DEF* PSStatMIBCount;
+
+
+typedef struct tagSNodeItem {
+    // STA info
+    U16            wAID;
+    U8             abyMACAddr[6];
+    U16            wTxDataRate;
+    U16            wInActiveCount;
+    U16            wEnQueueCnt;
+    U16            wFlags;
+    BOOL           bPWBitOn;
+    U8             byKeyIndex;
+    U16            wWepKeyLength;
+    U8            abyWepKey[WEP_KEYMAXLEN];
+    // Auto rate fallback vars
+    BOOL           bIsInFallback;
+    U32            uTxFailures;
+    U32            uTxAttempts;
+    U16            wFailureRatio;
+
+} SNodeItem;
+
+
+typedef struct tagSNodeList {
+
+	U32		    uItem;
+	SNodeItem	sNodeList[0];
+
+} SNodeList, *PSNodeList;
+
+
+
+typedef struct tagSCmdValue {
+
+    U32     dwValue;
+
+} SCmdValue,  *PSCmdValue;
+
+
+//
+// hostapd & viawget ioctl related
+//
+
+
+// VIAGWET_IOCTL_HOSTAPD ioctl() cmd:
+enum {
+	VIAWGET_HOSTAPD_FLUSH = 1,
+	VIAWGET_HOSTAPD_ADD_STA = 2,
+	VIAWGET_HOSTAPD_REMOVE_STA = 3,
+	VIAWGET_HOSTAPD_GET_INFO_STA = 4,
+	VIAWGET_HOSTAPD_SET_ENCRYPTION = 5,
+	VIAWGET_HOSTAPD_GET_ENCRYPTION = 6,
+	VIAWGET_HOSTAPD_SET_FLAGS_STA = 7,
+	VIAWGET_HOSTAPD_SET_ASSOC_AP_ADDR = 8,
+	VIAWGET_HOSTAPD_SET_GENERIC_ELEMENT = 9,
+	VIAWGET_HOSTAPD_MLME = 10,
+	VIAWGET_HOSTAPD_SCAN_REQ = 11,
+	VIAWGET_HOSTAPD_STA_CLEAR_STATS = 12,
+};
+
+
+#define VIAWGET_HOSTAPD_GENERIC_ELEMENT_HDR_LEN \
+((int) (&((struct viawget_hostapd_param *) 0)->u.generic_elem.data))
+
+// Maximum length for algorithm names (-1 for nul termination) used in ioctl()
+
+
+
+struct viawget_hostapd_param {
+	U32 cmd;
+	U8 sta_addr[6];
+	union {
+		struct {
+			U16 aid;
+			U16 capability;
+			U8 tx_supp_rates;
+		} add_sta;
+		struct {
+			U32 inactive_sec;
+		} get_info_sta;
+		struct {
+			U8 alg;
+			U32 flags;
+			U32 err;
+			U8 idx;
+			U8 seq[8];
+			U16 key_len;
+			U8 key[0];
+		} crypt;
+		struct {
+			U32 flags_and;
+			U32 flags_or;
+		} set_flags_sta;
+		struct {
+			U16 rid;
+			U16 len;
+			U8 data[0];
+		} rid;
+		struct {
+			U8 len;
+			U8 data[0];
+		} generic_elem;
+		struct {
+			U16 cmd;
+			U16 reason_code;
+		} mlme;
+		struct {
+			U8 ssid_len;
+			U8 ssid[32];
+		} scan_req;
+	} u;
+};
+
+//2006-1116-01,<Add> by NomadZhao
+#pragma pack()
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Types  ------------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+#endif //__IOCMD_H__
diff --git a/drivers/staging/vt6655/ioctl.c b/drivers/staging/vt6655/ioctl.c
new file mode 100644
index 0000000..4869107
--- /dev/null
+++ b/drivers/staging/vt6655/ioctl.c
@@ -0,0 +1,775 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: ioctl.c
+ *
+ * Purpose:  private ioctl functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: Auguest 20, 2003
+ *
+ * Functions:
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__IOCTL_H__)
+#include "ioctl.h"
+#endif
+#if !defined(__IOCMD_H__)
+#include "iocmd.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__HOSTAP_H__)
+#include "hostap.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__WPACTL_H__)
+#include "wpactl.h"
+#endif
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+static int          msglevel                =MSG_LEVEL_INFO;
+
+/*---------------------  Static Functions  --------------------------*/
+
+#ifdef WPA_SM_Transtatus
+    SWPAResult wpa_Result;
+#endif
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+int private_ioctl(PSDevice pDevice, struct ifreq *rq) {
+
+	PSCmdRequest        pReq = (PSCmdRequest)rq;
+    PSMgmtObject        pMgmt = pDevice->pMgmt;
+	int 		        result = 0;
+    PWLAN_IE_SSID       pItemSSID;
+    SCmdBSSJoin         sJoinCmd;
+    SCmdZoneTypeSet  sZoneTypeCmd;
+    SCmdScan            sScanCmd;
+    SCmdStartAP         sStartAPCmd;
+    SCmdSetWEP          sWEPCmd;
+    SCmdValue           sValue;
+    SBSSIDList          sList;
+    SNodeList           sNodeList;
+    PSBSSIDList         pList;
+    PSNodeList          pNodeList;
+    UINT                cbListCount;
+    PKnownBSS           pBSS;
+    PKnownNodeDB        pNode;
+    UINT                ii, jj;
+    SCmdLinkStatus      sLinkStatus;
+    BYTE                abySuppRates[] = {WLAN_EID_SUPP_RATES, 4, 0x02, 0x04, 0x0B, 0x16};
+    BYTE                abyNullAddr[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+    DWORD               dwKeyIndex= 0;
+    BYTE                abyScanSSID[WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1];
+    LONG                ldBm;
+
+
+    pReq->wResult = 0;
+
+    switch(pReq->wCmdCode) {
+
+    case WLAN_CMD_BSS_SCAN:
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WLAN_CMD_BSS_SCAN..begin \n");
+        if (copy_from_user(&sScanCmd, pReq->data, sizeof(SCmdScan))) {
+			result = -EFAULT;
+			break;
+		};
+
+        pItemSSID = (PWLAN_IE_SSID)sScanCmd.ssid;
+        if (pItemSSID->len != 0) {
+            memset(abyScanSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+            memcpy(abyScanSSID, pItemSSID, pItemSSID->len + WLAN_IEHDR_LEN);
+        }
+
+        if (pDevice->bMACSuspend == TRUE) {
+            if (pDevice->bRadioOff == TRUE)
+                CARDbRadioPowerOn(pDevice);
+            vMgrTimerInit(pDevice);
+            MACvIntEnable(pDevice->PortOffset, IMR_MASK_VALUE);
+            add_timer(&pMgmt->sTimerSecondCallback);
+            pDevice->bMACSuspend = FALSE;
+        }
+        spin_lock_irq(&pDevice->lock);
+        if (memcmp(pMgmt->abyCurrBSSID, &abyNullAddr[0], 6) == 0)
+            BSSvClearBSSList((HANDLE)pDevice, FALSE);
+        else
+            BSSvClearBSSList((HANDLE)pDevice, pDevice->bLinkPass);
+
+        if (pItemSSID->len != 0)
+            bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, abyScanSSID);
+        else
+            bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, NULL);
+        spin_unlock_irq(&pDevice->lock);
+        break;
+
+    case WLAN_CMD_ZONETYPE_SET:
+	//mike add :cann't support.
+           result=-EOPNOTSUPP;
+	  break;
+
+        if (copy_from_user(&sZoneTypeCmd, pReq->data, sizeof(SCmdZoneTypeSet))) {
+			result = -EFAULT;
+			break;
+		};
+
+          if(sZoneTypeCmd.bWrite==TRUE) {
+	  //////write zonetype
+                if(sZoneTypeCmd.ZoneType == ZoneType_USA) {
+                  //set to USA
+                   printk("set_ZoneType:USA\n");
+		}
+                else if(sZoneTypeCmd.ZoneType == ZoneType_Japan) {
+                  //set to Japan
+                  printk("set_ZoneType:Japan\n");
+		}
+	       else if(sZoneTypeCmd.ZoneType == ZoneType_Europe) {
+                  //set to Europe
+                  printk("set_ZoneType:Europe\n");
+		}
+            }
+	else {
+          ///////read zonetype
+	  BYTE                       zonetype=0;
+
+
+           if(zonetype == 0x00)  { //USA
+             sZoneTypeCmd.ZoneType = ZoneType_USA;
+           }
+	 else if(zonetype == 0x01) { //Japan
+             sZoneTypeCmd.ZoneType = ZoneType_Japan;
+	  }
+	 else if(zonetype == 0x02) { //Europe
+             sZoneTypeCmd.ZoneType = ZoneType_Europe;
+	 }
+	 else { //Unknow ZoneType
+	        printk("Error:ZoneType[%x] Unknown ???\n",zonetype);
+	         result = -EFAULT;
+		break;
+	 }
+	   if (copy_to_user(pReq->data, &sZoneTypeCmd, sizeof(SCmdZoneTypeSet))) {
+			result = -EFAULT;
+			break;
+		};
+	}
+
+	     break;
+
+    case WLAN_CMD_BSS_JOIN:
+
+        if (pDevice->bMACSuspend == TRUE) {
+            if (pDevice->bRadioOff == TRUE)
+                CARDbRadioPowerOn(pDevice);
+            vMgrTimerInit(pDevice);
+            MACvIntEnable(pDevice->PortOffset, IMR_MASK_VALUE);
+            add_timer(&pMgmt->sTimerSecondCallback);
+            pDevice->bMACSuspend = FALSE;
+        }
+
+        if (copy_from_user(&sJoinCmd, pReq->data, sizeof(SCmdBSSJoin))) {
+			result = -EFAULT;
+			break;
+		};
+
+        pItemSSID = (PWLAN_IE_SSID)sJoinCmd.ssid;
+        memset(pMgmt->abyDesireSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+		memcpy(pMgmt->abyDesireSSID, pItemSSID, pItemSSID->len + WLAN_IEHDR_LEN);
+	    if (sJoinCmd.wBSSType == ADHOC) {
+	        pMgmt->eConfigMode = WMAC_CONFIG_IBSS_STA;
+	        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "ioct set to adhoc mode\n");
+	    }
+	    else {
+	        pMgmt->eConfigMode = WMAC_CONFIG_ESS_STA;
+	        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "ioct set to STA mode\n");
+	    }
+	    if (sJoinCmd.bPSEnable == TRUE) {
+            pDevice->ePSMode = WMAC_POWER_FAST;
+//            pDevice->ePSMode = WMAC_POWER_MAX;
+            pMgmt->wListenInterval = 2;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Power Saving On\n");
+        }
+        else {
+            pDevice->ePSMode = WMAC_POWER_CAM;
+            pMgmt->wListenInterval = 1;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Power Saving Off \n");
+        }
+
+        if (sJoinCmd.bShareKeyAuth == TRUE){
+            pMgmt->bShareKeyAlgorithm = TRUE;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Share Key \n");
+        }
+        else {
+            pMgmt->bShareKeyAlgorithm = FALSE;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Open System \n");
+        }
+	    pDevice->uChannel = sJoinCmd.uChannel;
+        netif_stop_queue(pDevice->dev);
+        spin_lock_irq(&pDevice->lock);
+        pMgmt->eCurrState = WMAC_STATE_IDLE;
+        bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, pMgmt->abyDesireSSID);
+        bScheduleCommand((HANDLE) pDevice, WLAN_CMD_SSID, NULL);
+        spin_unlock_irq(&pDevice->lock);
+        break;
+
+    case WLAN_CMD_SET_WEP:
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WLAN_CMD_SET_WEP Key. \n");
+        memset(&sWEPCmd, 0 ,sizeof(SCmdSetWEP));
+        if (copy_from_user(&sWEPCmd, pReq->data, sizeof(SCmdSetWEP))) {
+			result = -EFAULT;
+			break;
+		};
+	    if (sWEPCmd.bEnableWep != TRUE) {
+            pDevice->bEncryptionEnable = FALSE;
+            pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
+            MACvDisableDefaultKey(pDevice->PortOffset);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WEP function disable. \n");
+            break;
+        }
+
+        for (ii = 0; ii < WLAN_WEP_NKEYS; ii ++) {
+            if (sWEPCmd.bWepKeyAvailable[ii]) {
+                if (ii == sWEPCmd.byKeyIndex)
+	//2006-1123-02,<Modify> by EinsnLiu
+	//Evaluate the "dwKeyIndex" error
+	//  dwKeyIndex |= (1 << 31);
+	  dwKeyIndex =ii|(1 << 31);
+                else
+                    dwKeyIndex = ii;
+
+                KeybSetDefaultKey(&(pDevice->sKey),
+                                    dwKeyIndex,
+                                    sWEPCmd.auWepKeyLength[ii],
+                                    NULL,
+                                    (PBYTE)&sWEPCmd.abyWepKey[ii][0],
+                                    KEY_CTL_WEP,
+                                    pDevice->PortOffset,
+                                    pDevice->byLocalID);
+            }
+        }
+        pDevice->byKeyIndex = sWEPCmd.byKeyIndex;
+        pDevice->bTransmitKey = TRUE;
+        pDevice->bEncryptionEnable = TRUE;
+        pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
+
+        break;
+
+    case WLAN_CMD_GET_LINK:
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WLAN_CMD_GET_LINK status. \n");
+
+        memset(sLinkStatus.abySSID, 0 , WLAN_SSID_MAXLEN + 1);
+
+        if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA)
+            sLinkStatus.wBSSType = ADHOC;
+        else
+            sLinkStatus.wBSSType = INFRA;
+
+        if (pMgmt->eCurrState == WMAC_STATE_JOINTED)
+            sLinkStatus.byState = ADHOC_JOINTED;
+        else
+            sLinkStatus.byState = ADHOC_STARTED;
+
+        sLinkStatus.uChannel = pMgmt->uCurrChannel;
+        if (pDevice->bLinkPass == TRUE) {
+            sLinkStatus.bLink = TRUE;
+ 		    pItemSSID = (PWLAN_IE_SSID)pMgmt->abyCurrSSID;
+		    memcpy(sLinkStatus.abySSID, pItemSSID->abySSID, pItemSSID->len);
+		    memcpy(sLinkStatus.abyBSSID, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+		    sLinkStatus.uLinkRate = pMgmt->sNodeDBTable[0].wTxDataRate;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Link Success ! \n");
+        }
+        else {
+            sLinkStatus.bLink = FALSE;
+        }
+        if (copy_to_user(pReq->data, &sLinkStatus, sizeof(SCmdLinkStatus))) {
+			result = -EFAULT;
+			break;
+		};
+
+        break;
+
+    case WLAN_CMD_GET_LISTLEN:
+		cbListCount = 0;
+		pBSS = &(pMgmt->sBSSList[0]);
+        for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+            pBSS = &(pMgmt->sBSSList[ii]);
+            if (!pBSS->bActive)
+                continue;
+            cbListCount++;
+        };
+        sList.uItem = cbListCount;
+        if (copy_to_user(pReq->data, &sList, sizeof(SBSSIDList))) {
+			result = -EFAULT;
+			break;
+		};
+        pReq->wResult = 0;
+        break;
+
+    case WLAN_CMD_GET_LIST:
+        if (copy_from_user(&sList, pReq->data, sizeof(SBSSIDList))) {
+			result = -EFAULT;
+			break;
+		};
+        pList = (PSBSSIDList)kmalloc(sizeof(SBSSIDList) + (sList.uItem * sizeof(SBSSIDItem)), (int)GFP_ATOMIC);
+        if (pList == NULL) {
+            result = -ENOMEM;
+            break;
+        }
+		pList->uItem = sList.uItem;
+		pBSS = &(pMgmt->sBSSList[0]);
+        for (ii = 0, jj = 0; jj < MAX_BSS_NUM ; jj++) {
+            pBSS = &(pMgmt->sBSSList[jj]);
+            if (pBSS->bActive) {
+    		    pList->sBSSIDList[ii].uChannel = pBSS->uChannel;
+    		    pList->sBSSIDList[ii].wBeaconInterval = pBSS->wBeaconInterval;
+    		    pList->sBSSIDList[ii].wCapInfo = pBSS->wCapInfo;
+//    		    pList->sBSSIDList[ii].uRSSI = pBSS->uRSSI;
+    		    RFvRSSITodBm(pDevice, (BYTE)(pBSS->uRSSI), &ldBm);
+    		    pList->sBSSIDList[ii].uRSSI = (UINT)ldBm;
+    		    memcpy(pList->sBSSIDList[ii].abyBSSID, pBSS->abyBSSID, WLAN_BSSID_LEN);
+    		    pItemSSID = (PWLAN_IE_SSID)pBSS->abySSID;
+    		    memset(pList->sBSSIDList[ii].abySSID, 0, WLAN_SSID_MAXLEN + 1);
+    		    memcpy(pList->sBSSIDList[ii].abySSID, pItemSSID->abySSID, pItemSSID->len);
+                if (WLAN_GET_CAP_INFO_ESS(pBSS->wCapInfo)) {
+    		        pList->sBSSIDList[ii].byNetType = INFRA;
+                }
+                else {
+    		        pList->sBSSIDList[ii].byNetType = ADHOC;
+    		    }
+    		    if (WLAN_GET_CAP_INFO_PRIVACY(pBSS->wCapInfo)) {
+    		        pList->sBSSIDList[ii].bWEPOn = TRUE;
+                }
+                else {
+    		        pList->sBSSIDList[ii].bWEPOn = FALSE;
+    		    }
+    		    ii ++;
+    		    if (ii >= pList->uItem)
+    		        break;
+            }
+        }
+
+        if (copy_to_user(pReq->data, pList, sizeof(SBSSIDList) + (sList.uItem * sizeof(SBSSIDItem)))) {
+			result = -EFAULT;
+			break;
+		};
+        kfree(pList);
+        pReq->wResult = 0;
+        break;
+
+    case WLAN_CMD_GET_MIB:
+        if (copy_to_user(pReq->data, &(pDevice->s802_11Counter), sizeof(SDot11MIBCount))) {
+			result = -EFAULT;
+			break;
+		};
+        break;
+
+    case WLAN_CMD_GET_STAT:
+        if (copy_to_user(pReq->data, &(pDevice->scStatistic), sizeof(SStatCounter))) {
+			result = -EFAULT;
+			break;
+		};
+        break;
+    case WLAN_CMD_STOP_MAC:
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WLAN_CMD_STOP_MAC\n");
+        netif_stop_queue(pDevice->dev);
+
+        spin_lock_irq(&pDevice->lock);
+        if (pDevice->bRadioOff == FALSE) {
+            CARDbRadioPowerOff(pDevice);
+        }
+        pDevice->bLinkPass = FALSE;
+        memset(pMgmt->abyCurrBSSID, 0, 6);
+        pMgmt->eCurrState = WMAC_STATE_IDLE;
+        del_timer(&pDevice->sTimerCommand);
+        del_timer(&pMgmt->sTimerSecondCallback);
+        pDevice->bCmdRunning = FALSE;
+        pDevice->bMACSuspend = TRUE;
+        MACvIntDisable(pDevice->PortOffset);
+        spin_unlock_irq(&pDevice->lock);
+
+        break;
+
+    case WLAN_CMD_START_MAC:
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WLAN_CMD_START_MAC\n");
+
+        if (pDevice->bMACSuspend == TRUE) {
+            if (pDevice->bRadioOff == TRUE)
+                CARDbRadioPowerOn(pDevice);
+            vMgrTimerInit(pDevice);
+            MACvIntEnable(pDevice->PortOffset, IMR_MASK_VALUE);
+            add_timer(&pMgmt->sTimerSecondCallback);
+            pDevice->bMACSuspend = FALSE;
+        }
+        break;
+
+    case WLAN_CMD_SET_HOSTAPD:
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WLAN_CMD_SET_HOSTAPD\n");
+
+        if (copy_from_user(&sValue, pReq->data, sizeof(SCmdValue))) {
+			result = -EFAULT;
+			break;
+		};
+		if (sValue.dwValue == 1) {
+            if (hostap_set_hostapd(pDevice, 1, 1) == 0){
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Enable HOSTAP\n");
+            }
+            else {
+			    result = -EFAULT;
+			    break;
+			}
+        }
+        else {
+            hostap_set_hostapd(pDevice, 0, 1);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Disable HOSTAP\n");
+        }
+
+        break;
+
+    case WLAN_CMD_SET_HOSTAPD_STA:
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WLAN_CMD_SET_HOSTAPD_STA\n");
+
+        break;
+    case WLAN_CMD_SET_802_1X:
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WLAN_CMD_SET_802_1X\n");
+        if (copy_from_user(&sValue, pReq->data, sizeof(SCmdValue))) {
+			result = -EFAULT;
+			break;
+		};
+
+		if (sValue.dwValue == 1) {
+            pDevice->bEnable8021x = TRUE;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Enable 802.1x\n");
+        }
+        else {
+            pDevice->bEnable8021x = FALSE;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Disable 802.1x\n");
+        }
+
+        break;
+
+
+    case WLAN_CMD_SET_HOST_WEP:
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WLAN_CMD_SET_HOST_WEP\n");
+        if (copy_from_user(&sValue, pReq->data, sizeof(SCmdValue))) {
+			result = -EFAULT;
+			break;
+		};
+
+		if (sValue.dwValue == 1) {
+            pDevice->bEnableHostWEP = TRUE;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Enable HostWEP\n");
+        }
+        else {
+            pDevice->bEnableHostWEP = FALSE;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Disable HostWEP\n");
+        }
+
+        break;
+
+    case WLAN_CMD_SET_WPA:
+         DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WLAN_CMD_SET_WPA\n");
+
+        if (copy_from_user(&sValue, pReq->data, sizeof(SCmdValue))) {
+			result = -EFAULT;
+			break;
+		};
+		if (sValue.dwValue == 1) {
+                     DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "up wpadev\n");
+		   memcpy(pDevice->wpadev->dev_addr, pDevice->dev->dev_addr, U_ETHER_ADDR_LEN);
+		   pDevice->bWPADEVUp = TRUE;
+        }
+        else {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "close wpadev\n");
+	   pDevice->bWPADEVUp = FALSE;
+        }
+
+        break;
+
+    case WLAN_CMD_AP_START:
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "WLAN_CMD_AP_START\n");
+        if (pDevice->bRadioOff == TRUE) {
+            CARDbRadioPowerOn(pDevice);
+            vMgrTimerInit(pDevice);
+            MACvIntEnable(pDevice->PortOffset, IMR_MASK_VALUE);
+            add_timer(&pMgmt->sTimerSecondCallback);
+        }
+        if (copy_from_user(&sStartAPCmd, pReq->data, sizeof(SCmdStartAP))) {
+			result = -EFAULT;
+			break;
+		};
+
+	    if (sStartAPCmd.wBSSType == AP) {
+	        pMgmt->eConfigMode = WMAC_CONFIG_AP;
+	        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "ioct set to AP mode\n");
+	    }
+	    else {
+	        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "ioct BSS type not set to AP mode\n");
+			result = -EFAULT;
+			break;
+	    }
+
+
+	    if (sStartAPCmd.wBBPType == PHY80211g) {
+            pMgmt->byAPBBType = PHY_TYPE_11G;
+        }
+        else if (sStartAPCmd.wBBPType == PHY80211a) {
+                 pMgmt->byAPBBType = PHY_TYPE_11A;
+        }
+        else {
+            pMgmt->byAPBBType = PHY_TYPE_11B;
+        }
+
+        pItemSSID = (PWLAN_IE_SSID)sStartAPCmd.ssid;
+        memset(pMgmt->abyDesireSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+		memcpy(pMgmt->abyDesireSSID, pItemSSID, pItemSSID->len + WLAN_IEHDR_LEN);
+
+	    if ((sStartAPCmd.uChannel > 0)&&(sStartAPCmd.uChannel <= 14))
+	        pDevice->uChannel = sStartAPCmd.uChannel;
+
+	    if ((sStartAPCmd.uBeaconInt >= 20) && (sStartAPCmd.uBeaconInt <= 1000))
+            pMgmt->wIBSSBeaconPeriod = sStartAPCmd.uBeaconInt;
+        else
+            pMgmt->wIBSSBeaconPeriod = 100;
+
+        if (sStartAPCmd.bShareKeyAuth == TRUE){
+            pMgmt->bShareKeyAlgorithm = TRUE;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Share Key \n");
+        }
+        else {
+            pMgmt->bShareKeyAlgorithm = FALSE;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Open System \n");
+        }
+        memcpy(pMgmt->abyIBSSSuppRates, abySuppRates, 6);
+
+        if (sStartAPCmd.byBasicRate & BIT3) {
+            pMgmt->abyIBSSSuppRates[2] |= BIT7;
+            pMgmt->abyIBSSSuppRates[3] |= BIT7;
+            pMgmt->abyIBSSSuppRates[4] |= BIT7;
+            pMgmt->abyIBSSSuppRates[5] |= BIT7;
+        }else if (sStartAPCmd.byBasicRate & BIT2) {
+             pMgmt->abyIBSSSuppRates[2] |= BIT7;
+             pMgmt->abyIBSSSuppRates[3] |= BIT7;
+             pMgmt->abyIBSSSuppRates[4] |= BIT7;
+        }else if (sStartAPCmd.byBasicRate & BIT1) {
+             pMgmt->abyIBSSSuppRates[2] |= BIT7;
+             pMgmt->abyIBSSSuppRates[3] |= BIT7;
+        }else if (sStartAPCmd.byBasicRate & BIT1) {
+             pMgmt->abyIBSSSuppRates[2] |= BIT7;
+        }else {
+            //default 1,2M
+             pMgmt->abyIBSSSuppRates[2] |= BIT7;
+             pMgmt->abyIBSSSuppRates[3] |= BIT7;
+        }
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Support Rate= %x %x %x %x\n",
+                pMgmt->abyIBSSSuppRates[2],
+                pMgmt->abyIBSSSuppRates[3],
+                pMgmt->abyIBSSSuppRates[4],
+                pMgmt->abyIBSSSuppRates[5]
+                );
+
+        netif_stop_queue(pDevice->dev);
+        spin_lock_irq(&pDevice->lock);
+        bScheduleCommand((HANDLE)pDevice, WLAN_CMD_RUN_AP, NULL);
+        spin_unlock_irq(&pDevice->lock);
+        break;
+
+    case WLAN_CMD_GET_NODE_CNT:
+
+		cbListCount = 0;
+		pNode = &(pMgmt->sNodeDBTable[0]);
+        for (ii = 0; ii < (MAX_NODE_NUM + 1); ii++) {
+            pNode = &(pMgmt->sNodeDBTable[ii]);
+            if (!pNode->bActive)
+                continue;
+            cbListCount++;
+        };
+
+        sNodeList.uItem = cbListCount;
+        if (copy_to_user(pReq->data, &sNodeList, sizeof(SNodeList))) {
+			result = -EFAULT;
+			break;
+		};
+        pReq->wResult = 0;
+        break;
+
+    case WLAN_CMD_GET_NODE_LIST:
+
+        if (copy_from_user(&sNodeList, pReq->data, sizeof(SNodeList))) {
+			result = -EFAULT;
+			break;
+		};
+        pNodeList = (PSNodeList)kmalloc(sizeof(SNodeList) + (sNodeList.uItem * sizeof(SNodeItem)), (int)GFP_ATOMIC);
+        if (pNodeList == NULL) {
+            result = -ENOMEM;
+            break;
+        }
+		pNodeList->uItem = sNodeList.uItem;
+		pNode = &(pMgmt->sNodeDBTable[0]);
+        for (ii = 0, jj = 0; ii < (MAX_NODE_NUM + 1); ii++) {
+            pNode = &(pMgmt->sNodeDBTable[ii]);
+            if (pNode->bActive) {
+    		    pNodeList->sNodeList[jj].wAID = pNode->wAID;
+    		    memcpy(pNodeList->sNodeList[jj].abyMACAddr, pNode->abyMACAddr, WLAN_ADDR_LEN);
+    		    pNodeList->sNodeList[jj].wTxDataRate = pNode->wTxDataRate;
+    		    pNodeList->sNodeList[jj].wInActiveCount = (WORD)pNode->uInActiveCount;
+    		    pNodeList->sNodeList[jj].wEnQueueCnt = (WORD)pNode->wEnQueueCnt;
+    		    pNodeList->sNodeList[jj].wFlags = (WORD)pNode->dwFlags;
+    		    pNodeList->sNodeList[jj].bPWBitOn = pNode->bPSEnable;
+    		    pNodeList->sNodeList[jj].byKeyIndex = pNode->byKeyIndex;
+    		    pNodeList->sNodeList[jj].wWepKeyLength = pNode->uWepKeyLength;
+    		    memcpy(&(pNodeList->sNodeList[jj].abyWepKey[0]), &(pNode->abyWepKey[0]), WEP_KEYMAXLEN);
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "key= %2.2X:%2.2X:%2.2X:%2.2X:%2.2X\n",
+                            pNodeList->sNodeList[jj].abyWepKey[0],
+                            pNodeList->sNodeList[jj].abyWepKey[1],
+                            pNodeList->sNodeList[jj].abyWepKey[2],
+                            pNodeList->sNodeList[jj].abyWepKey[3],
+                            pNodeList->sNodeList[jj].abyWepKey[4]
+                           );
+    		    pNodeList->sNodeList[jj].bIsInFallback = pNode->bIsInFallback;
+    		    pNodeList->sNodeList[jj].uTxFailures = pNode->uTxFailures;
+    		    pNodeList->sNodeList[jj].uTxAttempts = pNode->uTxAttempts;
+    		    pNodeList->sNodeList[jj].wFailureRatio = (WORD)pNode->uFailureRatio;
+    		    jj ++;
+    		    if (jj >= pNodeList->uItem)
+    		        break;
+    		}
+		};
+        if (copy_to_user(pReq->data, pNodeList, sizeof(SNodeList) + (sNodeList.uItem * sizeof(SNodeItem)))) {
+			result = -EFAULT;
+			break;
+		};
+        kfree(pNodeList);
+        pReq->wResult = 0;
+        break;
+
+#ifdef WPA_SM_Transtatus
+    case 0xFF:
+        memset(wpa_Result.ifname,0,sizeof(wpa_Result.ifname));
+	    wpa_Result.proto = 0;
+	    wpa_Result.key_mgmt = 0;
+	    wpa_Result.eap_type = 0;
+	    wpa_Result.authenticated = FALSE;
+		  pDevice->fWPA_Authened = FALSE;
+        if (copy_from_user(&wpa_Result, pReq->data, sizeof(wpa_Result))) {
+            result = -EFAULT;
+			break;
+		}
+
+	if(wpa_Result.authenticated==TRUE) {
+   #ifdef SndEvt_ToAPI
+   {
+     union iwreq_data      wrqu;
+
+     pItemSSID = (PWLAN_IE_SSID)pMgmt->abyCurrSSID;
+
+     memset(&wrqu, 0, sizeof(wrqu));
+     wrqu.data.flags = RT_WPACONNECTED_EVENT_FLAG;
+     wrqu.data.length =pItemSSID->len;
+     wireless_send_event(pDevice->dev, IWEVCUSTOM, &wrqu, pItemSSID->abySSID);
+   }
+   #endif
+         pDevice->fWPA_Authened = TRUE;           //is sucessful peer to wpa_Result.authenticated?
+}
+
+        //printk("get private wpa_supplicant announce WPA SM\n");
+	//printk("wpa-->ifname=%s\n",wpa_Result.ifname);
+	//printk("wpa-->proto=%d\n",wpa_Result.proto);
+	//printk("wpa-->key-mgmt=%d\n",wpa_Result.key_mgmt);
+	//printk("wpa-->eap_type=%d\n",wpa_Result.eap_type);
+	//printk("wpa-->authenticated is %s\n",(wpa_Result.authenticated==TRUE)?"TRUE":"FALSE");
+
+	pReq->wResult = 0;
+        break;
+#endif
+
+
+    default:
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Private command not support..\n");
+    }
+
+    return result;
+}
+
+/*
+VOID
+vConfigWEPKey (
+    IN PSDevice pDevice,
+    IN DWORD    dwKeyIndex,
+    IN PBYTE    pbyKey,
+    IN ULONG    uKeyLength
+    )
+{
+    int ii;
+
+
+    ZERO_MEMORY(&pDevice->abyWepKey[dwKeyIndex][0], WLAN_WEPMAX_KEYLEN);
+    MEMvCopy(&pDevice->abyWepKey[dwKeyIndex][0], pbyKey, uKeyLength);
+
+    pDevice->bWepKeyAvailable[dwKeyIndex] = TRUE;
+    pDevice->auWepKeyLength[dwKeyIndex] = uKeyLength;
+
+    MACvSetDefaultKeyEntry(pDevice->PortOffset, uKeyLength, dwKeyIndex,
+                           (PDWORD) &(pDevice->abyWepKey[dwKeyIndex][0]), pDevice->byLocalID);
+
+    if (pDevice->eEncryptionStatus < Ndis802_11EncryptionNotSupported) {
+        for(ii=0; ii<MAX_GROUP_KEY; ii++) {
+            if ((pDevice->bWepKeyAvailable[ii] == TRUE) &&
+                (pDevice->auWepKeyLength[ii] == WLAN_WEP232_KEYLEN)) {
+                pDevice->uCurrentWEPMode = TX_WEP_SW232;
+                MACvDisableDefaultKey(pDevice->PortOffset);
+                break;
+            }
+        }
+        if ((ii == MAX_GROUP_KEY) &&
+            (pDevice->eEncryptionStatus < Ndis802_11EncryptionNotSupported)) {
+            MACvEnableDefaultKey(pDevice->PortOffset, pDevice->byLocalID);
+        }
+    }
+}
+*/
diff --git a/drivers/staging/vt6655/ioctl.h b/drivers/staging/vt6655/ioctl.h
new file mode 100644
index 0000000..9c6816e
--- /dev/null
+++ b/drivers/staging/vt6655/ioctl.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: hostap.h
+ *
+ * Purpose:
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 21, 2003
+ *
+ */
+
+
+#ifndef __IOCTL_H__
+#define __IOCTL_H__
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+
+int private_ioctl(PSDevice pDevice, struct ifreq *rq);
+
+/*
+VOID vConfigWEPKey (
+    IN PSDevice pDevice,
+    IN DWORD    dwKeyIndex,
+    IN PBYTE    pbyKey,
+    IN ULONG    uKeyLength
+    );
+*/
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+
+#endif // __IOCTL_H__
+
+
+
diff --git a/drivers/staging/vt6655/iowpa.h b/drivers/staging/vt6655/iowpa.h
new file mode 100644
index 0000000..451e2ef
--- /dev/null
+++ b/drivers/staging/vt6655/iowpa.h
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: iowpa.h
+ *
+ * Purpose: Handles wpa supplicant ioctl interface
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 8, 2002
+ *
+ */
+
+#ifndef __IOWPA_H__
+#define __IOWPA_H__
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+
+#define WPA_IE_LEN 64
+
+
+//WPA related
+/*
+typedef enum { WPA_ALG_NONE, WPA_ALG_WEP, WPA_ALG_TKIP, WPA_ALG_CCMP } wpa_alg;
+typedef enum { CIPHER_NONE, CIPHER_WEP40, CIPHER_TKIP, CIPHER_CCMP,
+	       CIPHER_WEP104 } wpa_cipher;
+typedef enum { KEY_MGMT_802_1X, KEY_MGMT_PSK, KEY_MGMT_NONE,
+	       KEY_MGMT_802_1X_NO_WPA, KEY_MGMT_WPA_NONE } wpa_key_mgmt;
+*/
+
+enum {
+	VIAWGET_SET_WPA = 1,
+	VIAWGET_SET_KEY = 2,
+	VIAWGET_SET_SCAN = 3,
+	VIAWGET_GET_SCAN = 4,
+	VIAWGET_GET_SSID = 5,
+	VIAWGET_GET_BSSID = 6,
+	VIAWGET_SET_DROP_UNENCRYPT = 7,
+	VIAWGET_SET_DEAUTHENTICATE = 8,
+	VIAWGET_SET_ASSOCIATE = 9,
+	VIAWGET_SET_DISASSOCIATE= 10
+};
+
+
+enum {
+	VIAWGET_ASSOC_MSG = 1,
+	VIAWGET_DISASSOC_MSG = 2,
+	VIAWGET_PTK_MIC_MSG = 3,
+	VIAWGET_GTK_MIC_MSG = 4,
+	VIAWGET_CCKM_ROAM_MSG = 5,
+	VIAWGET_DEVICECLOSE_MSG = 6
+};
+
+
+
+#pragma pack(1)
+typedef struct viawget_wpa_header {
+	u8 type;
+	u16 req_ie_len;
+	u16 resp_ie_len;
+} viawget_wpa_header;
+
+
+
+struct viawget_wpa_param {
+	u32 cmd;
+	u8 addr[6];
+	union {
+		struct {
+			u8 len;
+			u8 data[0];
+		} generic_elem;
+
+		struct {
+        	u8 bssid[6];
+			u8 ssid[32];
+			u8 ssid_len;
+        	u8 *wpa_ie;
+        	u16 wpa_ie_len;
+        	int pairwise_suite;
+        	int group_suite;
+        	int key_mgmt_suite;
+        	int auth_alg;
+        	int mode;
+
+		} wpa_associate;
+
+		struct {
+	        int alg_name;
+	        u16 key_index;
+	        u16 set_tx;
+	        u8 *seq;
+	        u16 seq_len;
+	        u8 *key;
+	        u16 key_len;
+		} wpa_key;
+
+		struct {
+			u8 ssid_len;
+			u8 ssid[32];
+		} scan_req;
+
+		struct {
+			u16 scan_count;
+			u8 *buf;
+		} scan_results;
+
+	} u;
+
+};
+
+#pragma pack(1)
+struct viawget_scan_result {
+	u8 bssid[6];
+	u8 ssid[32];
+	u16 ssid_len;
+	u8 wpa_ie[WPA_IE_LEN];
+	u16 wpa_ie_len;
+	u8 rsn_ie[WPA_IE_LEN];
+	u16 rsn_ie_len;
+	int freq; // MHz
+	int caps; // e.g. privacy
+	int qual; // signal quality
+	int noise;
+	int level;
+	int maxrate;
+};
+
+//2006-1116-01,<Add> by NomadZhao
+#pragma pack()
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Types  ------------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+#endif //__IOWPA_H__
diff --git a/drivers/staging/vt6655/iwctl.c b/drivers/staging/vt6655/iwctl.c
new file mode 100644
index 0000000..4d5a1da
--- /dev/null
+++ b/drivers/staging/vt6655/iwctl.c
@@ -0,0 +1,2397 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: iwctl.c
+ *
+ * Purpose:  wireless ext & ioctl functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: July 5, 2006
+ *
+ * Functions:
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__IOCTL_H__)
+#include "ioctl.h"
+#endif
+#if !defined(__IOCMD_H__)
+#include "iocmd.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__HOSTAP_H__)
+#include "hostap.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__POWER_H__)
+#include "power.h"
+#endif
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+
+#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+#if !defined(__IOWPA_H__)
+#include "iowpa.h"
+#endif
+#if !defined(__WPACTL_H__)
+#include "wpactl.h"
+#endif
+#endif
+
+#if WIRELESS_EXT > 12
+#include <net/iw_handler.h>
+#endif
+extern WORD TxRate_iwconfig;//2008-5-8 <add> by chester
+
+/*---------------------  Static Definitions -------------------------*/
+
+//2008-0409-07, <Add> by Einsn Liu
+#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+#define SUPPORTED_WIRELESS_EXT                  18
+#else
+#define SUPPORTED_WIRELESS_EXT                  17
+#endif
+
+#ifdef WIRELESS_EXT
+
+static const long frequency_list[] = {
+    2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447, 2452, 2457, 2462, 2467, 2472, 2484,
+    4915, 4920, 4925, 4935, 4940, 4945, 4960, 4980,
+    5035, 5040, 5045, 5055, 5060, 5080, 5170, 5180, 5190, 5200, 5210, 5220, 5230, 5240,
+    5260, 5280, 5300, 5320, 5500, 5520, 5540, 5560, 5580, 5600, 5620, 5640, 5660, 5680,
+    5700, 5745, 5765, 5785, 5805, 5825
+	};
+
+#endif
+
+
+/*---------------------  Static Classes  ----------------------------*/
+
+
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+static int          msglevel                =MSG_LEVEL_INFO;
+
+
+/*---------------------  Static Variables  --------------------------*/
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+#ifdef WIRELESS_EXT
+
+#if WIRELESS_EXT > 12
+
+struct iw_statistics *iwctl_get_wireless_stats(struct net_device *dev)
+{
+	PSDevice pDevice = netdev_priv(dev);
+	long ldBm;
+	pDevice->wstats.status = pDevice->eOPMode;
+	#ifdef Calcu_LinkQual
+	 #if 0
+	  if(pDevice->byBBType == BB_TYPE_11B) {
+	     if(pDevice->byCurrSQ > 120)
+                  pDevice->scStatistic.LinkQuality = 100;
+	     else
+		 pDevice->scStatistic.LinkQuality = pDevice->byCurrSQ*100/120;
+	    }
+	  else if(pDevice->byBBType == BB_TYPE_11G) {
+                if(pDevice->byCurrSQ < 20)
+		   pDevice->scStatistic.LinkQuality = 100;
+	       else if(pDevice->byCurrSQ >96)
+		   pDevice->scStatistic.LinkQuality  = 0;
+	       else
+		   pDevice->scStatistic.LinkQuality = (96-pDevice->byCurrSQ)*100/76;
+	   }
+	   if(pDevice->bLinkPass !=TRUE)
+	       pDevice->scStatistic.LinkQuality = 0;
+	  #endif
+	   if(pDevice->scStatistic.LinkQuality > 100)
+   	       pDevice->scStatistic.LinkQuality = 100;
+               pDevice->wstats.qual.qual =(BYTE) pDevice->scStatistic.LinkQuality;
+	#else
+	pDevice->wstats.qual.qual = pDevice->byCurrSQ;
+	#endif
+	RFvRSSITodBm(pDevice, (BYTE)(pDevice->uCurrRSSI), &ldBm);
+	pDevice->wstats.qual.level = ldBm;
+	//pDevice->wstats.qual.level = 0x100 - pDevice->uCurrRSSI;
+	pDevice->wstats.qual.noise = 0;
+	pDevice->wstats.qual.updated = 1;
+	pDevice->wstats.discard.nwid = 0;
+	pDevice->wstats.discard.code = 0;
+	pDevice->wstats.discard.fragment = 0;
+	pDevice->wstats.discard.retries = (U32)pDevice->scStatistic.dwTsrErr;
+	pDevice->wstats.discard.misc = 0;
+	pDevice->wstats.miss.beacon = 0;
+
+	return &pDevice->wstats;
+}
+
+#endif
+
+
+
+/*------------------------------------------------------------------*/
+
+
+static int iwctl_commit(struct net_device *dev,
+			      struct iw_request_info *info,
+			      void *wrq,
+			      char *extra)
+{
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWCOMMIT \n");
+
+	return 0;
+
+}
+
+/*
+ * Wireless Handler : get protocol name
+ */
+
+int iwctl_giwname(struct net_device *dev,
+			 struct iw_request_info *info,
+			 char *wrq,
+			 char *extra)
+{
+	strcpy(wrq, "802.11-a/b/g");
+	return 0;
+}
+
+int iwctl_giwnwid(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+                   char *extra)
+{
+ 	//wrq->value = 0x100;
+	//wrq->disabled = 0;
+	//wrq->fixed = 1;
+	//return 0;
+  return -EOPNOTSUPP;
+}
+#if WIRELESS_EXT > 13
+
+/*
+ * Wireless Handler : set scan
+ */
+
+int iwctl_siwscan(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_point *wrq,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+		struct iw_scan_req  *req = (struct iw_scan_req *)extra;
+		 PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+	BYTE                abyScanSSID[WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1];
+	PWLAN_IE_SSID       pItemSSID=NULL;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWSCAN \n");
+
+
+if(pDevice->byReAssocCount > 0) {   //reject scan when re-associating!
+//send scan event to wpa_Supplicant
+  union iwreq_data wrqu;
+ printk("wireless_send_event--->SIOCGIWSCAN(scan done)\n");
+ memset(&wrqu, 0, sizeof(wrqu));
+ wireless_send_event(pDevice->dev, SIOCGIWSCAN, &wrqu, NULL);
+  return 0;
+}
+
+	spin_lock_irq(&pDevice->lock);
+	   BSSvClearBSSList((HANDLE)pDevice, pDevice->bLinkPass);
+
+//mike add: active scan OR passive scan OR desire_ssid scan
+ if(wrq->length == sizeof(struct iw_scan_req)) {
+   if (wrq->flags & IW_SCAN_THIS_ESSID)  {                               //desire_ssid scan
+       memset(abyScanSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+       pItemSSID = (PWLAN_IE_SSID)abyScanSSID;
+       pItemSSID->byElementID = WLAN_EID_SSID;
+       memcpy(pItemSSID->abySSID, req->essid, (int)req->essid_len);
+         if (pItemSSID->abySSID[req->essid_len - 1] == '\0') {
+           if(req->essid_len>0)
+		pItemSSID->len = req->essid_len - 1;
+         }
+	else
+	  pItemSSID->len = req->essid_len;
+	  pMgmt->eScanType = WMAC_SCAN_PASSIVE;
+         printk("SIOCSIWSCAN:[desired_ssid=%s,len=%d]\n",((PWLAN_IE_SSID)abyScanSSID)->abySSID,
+		 	                                                                                ((PWLAN_IE_SSID)abyScanSSID)->len);
+	bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, abyScanSSID);
+	spin_unlock_irq(&pDevice->lock);
+
+	return 0;
+   }
+   else if(req->scan_type == IW_SCAN_TYPE_PASSIVE) {          //passive scan
+       pMgmt->eScanType = WMAC_SCAN_PASSIVE;
+   }
+ }
+ else {           //active scan
+     pMgmt->eScanType = WMAC_SCAN_ACTIVE;
+ }
+
+	 pMgmt->eScanType = WMAC_SCAN_PASSIVE;
+	bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, NULL);
+	spin_unlock_irq(&pDevice->lock);
+
+	return 0;
+}
+
+
+/*
+ * Wireless Handler : get scan results
+ */
+
+int iwctl_giwscan(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_point *wrq,
+             char *extra)
+{
+    int ii, jj, kk;
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+    PKnownBSS           pBSS;
+    PWLAN_IE_SSID       pItemSSID;
+    PWLAN_IE_SUPP_RATES pSuppRates, pExtSuppRates;
+	char *current_ev = extra;
+	char *end_buf = extra + IW_SCAN_MAX_DATA;
+	char *current_val = NULL;
+	struct iw_event iwe;
+	long ldBm;
+#if WIRELESS_EXT > 14
+	char buf[MAX_WPA_IE_LEN * 2 + 30];
+#endif /* WIRELESS_EXT > 14 */
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWSCAN \n");
+
+    if (pMgmt->eScanState ==  WMAC_IS_SCANNING) {
+        // In scanning..
+		return -EAGAIN;
+	}
+	pBSS = &(pMgmt->sBSSList[0]);
+    for (ii = 0, jj = 0; jj < MAX_BSS_NUM ; jj++) {
+		if (current_ev >= end_buf)
+			break;
+        pBSS = &(pMgmt->sBSSList[jj]);
+        if (pBSS->bActive) {
+		    memset(&iwe, 0, sizeof(iwe));
+		    iwe.cmd = SIOCGIWAP;
+		    iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
+			memcpy(iwe.u.ap_addr.sa_data, pBSS->abyBSSID, WLAN_BSSID_LEN);
+            current_ev = iwe_stream_add_event(info,current_ev,end_buf, &iwe, IW_EV_ADDR_LEN);
+                 //ADD ssid
+	             memset(&iwe, 0, sizeof(iwe));
+                      iwe.cmd = SIOCGIWESSID;
+                      pItemSSID = (PWLAN_IE_SSID)pBSS->abySSID;
+                       iwe.u.data.length = pItemSSID->len;
+                       iwe.u.data.flags = 1;
+            current_ev = iwe_stream_add_point(info,current_ev,end_buf, &iwe, pItemSSID->abySSID);
+		//ADD mode
+		    memset(&iwe, 0, sizeof(iwe));
+		    iwe.cmd = SIOCGIWMODE;
+            if (WLAN_GET_CAP_INFO_ESS(pBSS->wCapInfo)) {
+		        iwe.u.mode = IW_MODE_INFRA;
+            }
+            else {
+                iwe.u.mode = IW_MODE_ADHOC;
+		    }
+	        iwe.len = IW_EV_UINT_LEN;
+            current_ev = iwe_stream_add_event(info,current_ev, end_buf, &iwe,  IW_EV_UINT_LEN);
+           //ADD frequency
+            pSuppRates = (PWLAN_IE_SUPP_RATES)pBSS->abySuppRates;
+            pExtSuppRates = (PWLAN_IE_SUPP_RATES)pBSS->abyExtSuppRates;
+            memset(&iwe, 0, sizeof(iwe));
+           	iwe.cmd = SIOCGIWFREQ;
+           	iwe.u.freq.m = pBSS->uChannel;
+           	iwe.u.freq.e = 0;
+           	iwe.u.freq.i = 0;
+            current_ev = iwe_stream_add_event(info,current_ev,end_buf, &iwe, IW_EV_FREQ_LEN);
+
+
+            //2008-0409-04, <Add> by Einsn Liu
+			{
+			int f = (int)pBSS->uChannel - 1;
+			if(f < 0)f = 0;
+			iwe.u.freq.m = frequency_list[f] * 100000;
+			iwe.u.freq.e = 1;
+			}
+            current_ev = iwe_stream_add_event(info,current_ev,end_buf, &iwe, IW_EV_FREQ_LEN);
+       		//ADD quality
+            memset(&iwe, 0, sizeof(iwe));
+	        iwe.cmd = IWEVQUAL;
+	        RFvRSSITodBm(pDevice, (BYTE)(pBSS->uRSSI), &ldBm);
+		    iwe.u.qual.level = ldBm;
+	        iwe.u.qual.noise = 0;
+//2008-0409-01, <Add> by Einsn Liu
+			if(-ldBm<50){
+				iwe.u.qual.qual = 100;
+			}else  if(-ldBm > 90) {
+				 iwe.u.qual.qual = 0;
+			}else {
+				iwe.u.qual.qual=(40-(-ldBm-50))*100/40;
+			}
+			iwe.u.qual.updated=7;
+
+	      //  iwe.u.qual.qual = 0;
+            current_ev = iwe_stream_add_event(info,current_ev, end_buf, &iwe, IW_EV_QUAL_LEN);
+
+            memset(&iwe, 0, sizeof(iwe));
+            iwe.cmd = SIOCGIWENCODE;
+            iwe.u.data.length = 0;
+            if (WLAN_GET_CAP_INFO_PRIVACY(pBSS->wCapInfo)) {
+                iwe.u.data.flags =IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
+            }else {
+                iwe.u.data.flags = IW_ENCODE_DISABLED;
+            }
+            current_ev = iwe_stream_add_point(info,current_ev,end_buf, &iwe, pItemSSID->abySSID);
+
+            memset(&iwe, 0, sizeof(iwe));
+            iwe.cmd = SIOCGIWRATE;
+           	iwe.u.bitrate.fixed = iwe.u.bitrate.disabled = 0;
+      		current_val = current_ev + IW_EV_LCP_LEN;
+
+       		for (kk = 0 ; kk < 12 ; kk++) {
+		        if (pSuppRates->abyRates[kk] == 0)
+			        break;
+		        // Bit rate given in 500 kb/s units (+ 0x80)
+		        iwe.u.bitrate.value = ((pSuppRates->abyRates[kk] & 0x7f) * 500000);
+                current_val = iwe_stream_add_value(info,current_ev, current_val, end_buf, &iwe, IW_EV_PARAM_LEN);
+			}
+       		for (kk = 0 ; kk < 8 ; kk++) {
+		        if (pExtSuppRates->abyRates[kk] == 0)
+			        break;
+		        // Bit rate given in 500 kb/s units (+ 0x80)
+		        iwe.u.bitrate.value = ((pExtSuppRates->abyRates[kk] & 0x7f) * 500000);
+                current_val = iwe_stream_add_value(info,current_ev, current_val, end_buf, &iwe, IW_EV_PARAM_LEN);
+	        }
+
+	        if((current_val - current_ev) > IW_EV_LCP_LEN)
+		        current_ev = current_val;
+
+#if WIRELESS_EXT > 14
+            memset(&iwe, 0, sizeof(iwe));
+            iwe.cmd = IWEVCUSTOM;
+            sprintf(buf, "bcn_int=%d", pBSS->wBeaconInterval);
+            iwe.u.data.length = strlen(buf);
+            current_ev = iwe_stream_add_point(info,current_ev, end_buf, &iwe, buf);
+
+#if WIRELESS_EXT > 17
+            if ((pBSS->wWPALen > 0) && (pBSS->wWPALen <= MAX_WPA_IE_LEN)) {
+                memset(&iwe, 0, sizeof(iwe));
+                iwe.cmd = IWEVGENIE;
+                iwe.u.data.length = pBSS->wWPALen;
+                current_ev = iwe_stream_add_point(info,current_ev, end_buf, &iwe, pBSS->byWPAIE);
+            }
+
+            if ((pBSS->wRSNLen > 0) && (pBSS->wRSNLen <= MAX_WPA_IE_LEN)) {
+                memset(&iwe, 0, sizeof(iwe));
+                iwe.cmd = IWEVGENIE;
+                iwe.u.data.length = pBSS->wRSNLen;
+                current_ev = iwe_stream_add_point(info,current_ev, end_buf, &iwe, pBSS->byRSNIE);
+            }
+
+#else // WIRELESS_EXT > 17
+            if ((pBSS->wWPALen > 0) && (pBSS->wWPALen <= MAX_WPA_IE_LEN)) {
+                u8 *p = buf;
+                memset(&iwe, 0, sizeof(iwe));
+                iwe.cmd = IWEVCUSTOM;
+		        p += sprintf(p, "wpa_ie=");
+		        for (ii = 0; ii < pBSS->wWPALen; ii++) {
+			        p += sprintf(p, "%02x", pBSS->byWPAIE[ii]);
+		        }
+		        iwe.u.data.length = strlen(buf);
+                current_ev = iwe_stream_add_point(info,current_ev, end_buf, &iwe, buf);
+		    }
+
+
+            if ((pBSS->wRSNLen > 0) && (pBSS->wRSNLen <= MAX_WPA_IE_LEN)) {
+                u8 *p = buf;
+                memset(&iwe, 0, sizeof(iwe));
+                iwe.cmd = IWEVCUSTOM;
+		        p += sprintf(p, "rsn_ie=");
+		        for (ii = 0; ii < pBSS->wRSNLen; ii++) {
+			        p += sprintf(p, "%02x", pBSS->byRSNIE[ii]);
+		        }
+		        iwe.u.data.length = strlen(buf);
+                current_ev = iwe_stream_add_point(info,current_ev, end_buf, &iwe, buf);
+		    }
+#endif
+#endif
+        }
+    }// for
+
+	wrq->length = current_ev - extra;
+	return 0;
+
+}
+
+#endif	/* WIRELESS_EXT > 13 */
+
+
+/*
+ * Wireless Handler : set frequence or channel
+ */
+
+int iwctl_siwfreq(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_freq *wrq,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+	int rc = 0;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWFREQ \n");
+
+	// If setting by frequency, convert to a channel
+	if((wrq->e == 1) &&
+	   (wrq->m >= (int) 2.412e8) &&
+	   (wrq->m <= (int) 2.487e8)) {
+		int f = wrq->m / 100000;
+		int c = 0;
+		while((c < 14) && (f != frequency_list[c]))
+			c++;
+		wrq->e = 0;
+		wrq->m = c + 1;
+	}
+	// Setting by channel number
+	if((wrq->m > 14) || (wrq->e > 0))
+		rc = -EOPNOTSUPP;
+	else {
+		int channel = wrq->m;
+		if((channel < 1) || (channel > 14)) {
+			DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: New channel value of %d is invalid!\n", dev->name, wrq->m);
+			rc = -EINVAL;
+		} else {
+			  // Yes ! We can set it !!!
+              DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " Set to channel = %d\n", channel);
+			  pDevice->uChannel = channel;
+ 			 //2007-0207-04,<Add> by EinsnLiu
+			 //Make change effect at once
+			  pDevice->bCommit = TRUE;
+		}
+	}
+
+	return rc;
+}
+
+/*
+ * Wireless Handler : get frequence or channel
+ */
+
+int iwctl_giwfreq(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_freq *wrq,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWFREQ \n");
+
+#ifdef WEXT_USECHANNELS
+	wrq->m = (int)pMgmt->uCurrChannel;
+	wrq->e = 0;
+#else
+	{
+		int f = (int)pMgmt->uCurrChannel - 1;
+		if(f < 0)
+		   f = 0;
+		wrq->m = frequency_list[f] * 100000;
+		wrq->e = 1;
+	}
+#endif
+
+	return 0;
+}
+
+/*
+ * Wireless Handler : set operation mode
+ */
+
+int iwctl_siwmode(struct net_device *dev,
+             struct iw_request_info *info,
+             __u32 *wmode,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+    int rc = 0;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWMODE \n");
+
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP && pDevice->bEnableHostapd) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Can't set operation mode, hostapd is running \n");
+        return rc;
+    }
+
+	switch(*wmode) {
+
+	case IW_MODE_ADHOC:
+	    if (pMgmt->eConfigMode != WMAC_CONFIG_IBSS_STA) {
+            pMgmt->eConfigMode = WMAC_CONFIG_IBSS_STA;
+            if (pDevice->flags & DEVICE_FLAGS_OPENED) {
+		        pDevice->bCommit = TRUE;
+   		    }
+		}
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "set mode to ad-hoc \n");
+		break;
+	case IW_MODE_AUTO:
+	case IW_MODE_INFRA:
+	    if (pMgmt->eConfigMode != WMAC_CONFIG_ESS_STA) {
+            pMgmt->eConfigMode = WMAC_CONFIG_ESS_STA;
+            if (pDevice->flags & DEVICE_FLAGS_OPENED) {
+		        pDevice->bCommit = TRUE;
+   		    }
+		}
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "set mode to infrastructure \n");
+		break;
+	case IW_MODE_MASTER:
+
+        pMgmt->eConfigMode = WMAC_CONFIG_ESS_STA;
+		rc = -EOPNOTSUPP;
+		break;
+
+	    if (pMgmt->eConfigMode != WMAC_CONFIG_AP) {
+            pMgmt->eConfigMode = WMAC_CONFIG_AP;
+            if (pDevice->flags & DEVICE_FLAGS_OPENED) {
+		        pDevice->bCommit = TRUE;
+   		    }
+		}
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "set mode to Access Point \n");
+		break;
+
+	case IW_MODE_REPEAT:
+        pMgmt->eConfigMode = WMAC_CONFIG_ESS_STA;
+		rc = -EOPNOTSUPP;
+		break;
+	default:
+		rc = -EINVAL;
+	}
+
+	return rc;
+}
+
+/*
+ * Wireless Handler : get operation mode
+ */
+
+int iwctl_giwmode(struct net_device *dev,
+             struct iw_request_info *info,
+             __u32 *wmode,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWMODE \n");
+	// If not managed, assume it's ad-hoc
+	switch (pMgmt->eConfigMode) {
+	case WMAC_CONFIG_ESS_STA:
+		*wmode = IW_MODE_INFRA;
+		break;
+	case WMAC_CONFIG_IBSS_STA:
+        *wmode = IW_MODE_ADHOC;
+		break;
+	case WMAC_CONFIG_AUTO:
+		*wmode = IW_MODE_INFRA;
+		break;
+	case WMAC_CONFIG_AP:
+		*wmode = IW_MODE_MASTER;
+		break;
+	default:
+		*wmode = IW_MODE_ADHOC;
+	}
+
+	return 0;
+}
+
+
+/*
+ * Wireless Handler : get capability range
+ */
+
+int iwctl_giwrange(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra)
+{
+	struct iw_range *range = (struct iw_range *) extra;
+	int		i,k;
+    BYTE abySupportedRates[13]= {0x02, 0x04, 0x0B, 0x16, 0x0c, 0x12, 0x18, 0x24, 0x30, 0x48, 0x60, 0x6C, 0x90};
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWRANGE \n");
+	if (wrq->pointer) {
+		wrq->length = sizeof(struct iw_range);
+		memset(range, 0, sizeof(struct iw_range));
+		range->min_nwid = 0x0000;
+		range->max_nwid = 0x0000;
+		range->num_channels = 14;
+		// Should be based on cap_rid.country to give only
+		//  what the current card support
+		k = 0;
+		for(i = 0; i < 14; i++) {
+			range->freq[k].i = i + 1; // List index
+			range->freq[k].m = frequency_list[i] * 100000;
+			range->freq[k++].e = 1;	// Values in table in MHz -> * 10^5 * 10
+		}
+		range->num_frequency = k;
+		// Hum... Should put the right values there
+	     #ifdef Calcu_LinkQual
+                 range->max_qual.qual = 100;
+	     #else
+		range->max_qual.qual = 255;
+	     #endif
+		range->max_qual.level = 0;
+		range->max_qual.noise = 0;
+		range->sensitivity = 255;
+
+		for(i = 0 ; i < 13 ; i++) {
+			range->bitrate[i] = abySupportedRates[i] * 500000;
+			if(range->bitrate[i] == 0)
+				break;
+		}
+		range->num_bitrates = i;
+
+		// Set an indication of the max TCP throughput
+		// in bit/s that we can expect using this interface.
+		//  May be use for QoS stuff... Jean II
+		if(i > 2)
+			range->throughput = 5 * 1000 * 1000;
+		else
+			range->throughput = 1.5 * 1000 * 1000;
+
+		range->min_rts = 0;
+		range->max_rts = 2312;
+		range->min_frag = 256;
+		range->max_frag = 2312;
+
+
+	    // the encoding capabilities
+	    range->num_encoding_sizes = 3;
+	    // 64(40) bits WEP
+	    range->encoding_size[0] = 5;
+	    // 128(104) bits WEP
+	    range->encoding_size[1] = 13;
+	    // 256 bits for WPA-PSK
+	    range->encoding_size[2] = 32;
+	    // 4 keys are allowed
+	    range->max_encoding_tokens = 4;
+
+#if WIRELESS_EXT > 17
+	    range->enc_capa = IW_ENC_CAPA_WPA | IW_ENC_CAPA_WPA2 |
+		    IW_ENC_CAPA_CIPHER_TKIP | IW_ENC_CAPA_CIPHER_CCMP;
+#endif
+
+#if WIRELESS_EXT > 9
+		range->min_pmp = 0;
+		range->max_pmp = 1000000;// 1 secs
+		range->min_pmt = 0;
+		range->max_pmt = 1000000;// 1 secs
+		range->pmp_flags = IW_POWER_PERIOD;
+		range->pmt_flags = IW_POWER_TIMEOUT;
+		range->pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT | IW_POWER_ALL_R;
+
+		// Transmit Power - values are in mW
+
+        range->txpower[0] = 100;
+		range->num_txpower = 1;
+		range->txpower_capa = IW_TXPOW_MWATT;
+#endif // WIRELESS_EXT > 9
+#if WIRELESS_EXT > 10
+		range->we_version_source = SUPPORTED_WIRELESS_EXT;
+		range->we_version_compiled = WIRELESS_EXT;
+		range->retry_capa = IW_RETRY_LIMIT | IW_RETRY_LIFETIME;
+		range->retry_flags = IW_RETRY_LIMIT;
+		range->r_time_flags = IW_RETRY_LIFETIME;
+		range->min_retry = 1;
+		range->max_retry = 65535;
+		range->min_r_time = 1024;
+		range->max_r_time = 65535 * 1024;
+#endif // WIRELESS_EXT > 10
+#if WIRELESS_EXT > 11
+		// Experimental measurements - boundary 11/5.5 Mb/s
+		// Note : with or without the (local->rssi), results
+		//  are somewhat different. - Jean II
+		range->avg_qual.qual = 6;
+		range->avg_qual.level = 176;	// -80 dBm
+		range->avg_qual.noise = 0;
+#endif // WIRELESS_EXT > 11
+	}
+
+
+	return 0;
+}
+
+
+/*
+ * Wireless Handler : set ap mac address
+ */
+
+int iwctl_siwap(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct sockaddr *wrq,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+    int rc = 0;
+        BYTE                 ZeroBSSID[WLAN_BSSID_LEN]={0x00,0x00,0x00,0x00,0x00,0x00};
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWAP \n");
+if (pMgmt->eScanState ==  WMAC_IS_SCANNING) {
+        // In scanning..
+     printk("SIOCSIWAP(??)-->In scanning...\n");
+   //  return -EAGAIN;
+  }
+	if (wrq->sa_family != ARPHRD_ETHER)
+		rc = -EINVAL;
+	else {
+		memset(pMgmt->abyDesireBSSID, 0xFF, 6);
+		memcpy(pMgmt->abyDesireBSSID, wrq->sa_data, 6);
+		                //2008-0409-05, <Add> by Einsn Liu
+		if((pDevice->bLinkPass == TRUE) &&
+                     (memcmp(pMgmt->abyDesireBSSID, pMgmt->abyCurrBSSID, 6)== 0)){
+			return rc;
+			}
+	//mike :add
+	 if ((IS_BROADCAST_ADDRESS(pMgmt->abyDesireBSSID)) ||
+	     (memcmp(pMgmt->abyDesireBSSID, ZeroBSSID, 6) == 0)){
+	      printk("SIOCSIWAP:invalid desired BSSID return!\n");
+               return rc;
+         }
+       //mike add: if desired AP is hidden ssid(there are two same BSSID in list),
+       //                  then ignore,because you don't known which one to be connect with??
+       	{
+           UINT            ii , uSameBssidNum=0;
+                  for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+                     if (pMgmt->sBSSList[ii].bActive &&
+                        IS_ETH_ADDRESS_EQUAL(pMgmt->sBSSList[ii].abyBSSID,pMgmt->abyDesireBSSID)) {
+                        uSameBssidNum++;
+                     }
+                  }
+	     if(uSameBssidNum >= 2) {  //hit: desired AP is in hidden ssid mode!!!
+                 printk("SIOCSIWAP:ignore for desired AP in hidden mode\n");
+	        return rc;
+	     }
+       	}
+        if (pDevice->flags & DEVICE_FLAGS_OPENED) {
+		    pDevice->bCommit = TRUE;
+   		}
+	}
+	return rc;
+}
+
+/*
+ * Wireless Handler : get ap mac address
+ */
+
+int iwctl_giwap(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct sockaddr *wrq,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWAP \n");
+
+    memcpy(wrq->sa_data, pMgmt->abyCurrBSSID, 6);
+   //2008-0410,<Modify> by Einsn Liu
+    if ((pDevice->bLinkPass == FALSE) && (pMgmt->eCurrMode != WMAC_MODE_ESS_AP))
+        memset(wrq->sa_data, 0, 6);
+
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+        memcpy(wrq->sa_data, pMgmt->abyCurrBSSID, 6);
+    }
+
+	wrq->sa_family = ARPHRD_ETHER;
+
+	return 0;
+
+}
+
+
+/*
+ * Wireless Handler : get ap list
+ */
+
+int iwctl_giwaplist(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra)
+{
+	int ii,jj, rc = 0;
+	struct sockaddr sock[IW_MAX_AP];
+	struct iw_quality qual[IW_MAX_AP];
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWAPLIST \n");
+	// Only super-user can see AP list
+
+	if (!capable(CAP_NET_ADMIN)) {
+		rc = -EPERM;
+		return rc;
+	}
+
+	if (wrq->pointer) {
+
+		PKnownBSS pBSS = &(pMgmt->sBSSList[0]);
+
+		for (ii = 0, jj= 0; ii < MAX_BSS_NUM; ii++) {
+		    pBSS = &(pMgmt->sBSSList[ii]);
+            if (!pBSS->bActive)
+                continue;
+            if ( jj >= IW_MAX_AP)
+                break;
+			memcpy(sock[jj].sa_data, pBSS->abyBSSID, 6);
+			sock[jj].sa_family = ARPHRD_ETHER;
+			qual[jj].level = pBSS->uRSSI;
+			qual[jj].qual = qual[jj].noise = 0;
+			qual[jj].updated = 2;
+			jj++;
+		}
+
+		wrq->flags = 1; // Should be define'd
+		wrq->length = jj;
+		memcpy(extra, sock, sizeof(struct sockaddr)*jj);
+		memcpy(extra + sizeof(struct sockaddr)*jj, qual, sizeof(struct iw_quality)*jj);
+	}
+
+	return rc;
+}
+
+
+/*
+ * Wireless Handler : set essid
+ */
+
+int iwctl_siwessid(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+    PWLAN_IE_SSID       pItemSSID;
+  //2008-0409-05, <Add> by Einsn Liu
+    BYTE  len;
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWESSID \n");
+ pDevice->fWPA_Authened = FALSE;
+if (pMgmt->eScanState ==  WMAC_IS_SCANNING) {
+        // In scanning..
+     printk("SIOCSIWESSID(??)-->In scanning...\n");
+   //  return -EAGAIN;
+  }
+	// Check if we asked for `any'
+	if(wrq->flags == 0) {
+		// Just send an empty SSID list
+		// Just send an empty SSID list
+		memset(pMgmt->abyDesireSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+                  memset(pMgmt->abyDesireBSSID, 0xFF,6);
+	    printk("set essid to 'any' \n");
+           #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+             //Unknown desired AP,so here need not associate??
+            //if(pDevice->bWPASuppWextEnabled == TRUE)  {
+                  return 0;
+            // }
+            #endif
+	} else {
+		// Set the SSID
+		memset(pMgmt->abyDesireSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+        pItemSSID = (PWLAN_IE_SSID)pMgmt->abyDesireSSID;
+        pItemSSID->byElementID = WLAN_EID_SSID;
+		memcpy(pItemSSID->abySSID, extra, wrq->length);
+		         if (pItemSSID->abySSID[wrq->length - 1] == '\0') {
+           if(wrq->length>0)
+		pItemSSID->len = wrq->length - 1;
+         }
+	else
+	  pItemSSID->len = wrq->length;
+	printk("set essid to %s \n",pItemSSID->abySSID);
+		//2008-0409-05, <Add> by Einsn Liu
+       len=(pItemSSID->len > ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->len)?pItemSSID->len:((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->len;
+   if((pDevice->bLinkPass == TRUE) &&
+  	(memcmp(pItemSSID->abySSID,((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->abySSID,len)==0))
+         return 0;
+
+        //mike:need clear desiredBSSID
+     if(pItemSSID->len==0) {
+        memset(pMgmt->abyDesireBSSID, 0xFF,6);
+        return 0;
+     }
+
+#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+ //Wext wil order another command of siwap to link with desired AP,
+ //so here need not associate??
+  if(pDevice->bWPASuppWextEnabled == TRUE)  {
+        /*******search if  in hidden ssid mode ****/
+        {
+           PKnownBSS       pCurr = NULL;
+           BYTE                   abyTmpDesireSSID[WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1];
+	  UINT            ii , uSameBssidNum=0;
+
+	  memset(abyTmpDesireSSID,0,sizeof(abyTmpDesireSSID));
+	  memcpy(abyTmpDesireSSID,pMgmt->abyDesireSSID,sizeof(abyTmpDesireSSID));
+            pCurr = BSSpSearchBSSList(pDevice,
+                                      NULL,
+                                      abyTmpDesireSSID,
+                                      pMgmt->eConfigPHYMode
+                                      );
+
+            if (pCurr == NULL){
+               printk("SIOCSIWESSID:hidden ssid site survey before associate.......\n");
+	      vResetCommandTimer((HANDLE) pDevice);
+	      pMgmt->eScanType = WMAC_SCAN_ACTIVE;
+               bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, pMgmt->abyDesireSSID);
+	      bScheduleCommand((HANDLE) pDevice, WLAN_CMD_SSID, pMgmt->abyDesireSSID);
+          }
+	 else {  //mike:to find out if that desired SSID is a hidden-ssid AP ,
+                     //         by means of judging if there are two same BSSID exist in list ?
+                  for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+                     if (pMgmt->sBSSList[ii].bActive &&
+                        IS_ETH_ADDRESS_EQUAL(pMgmt->sBSSList[ii].abyBSSID, pCurr->abyBSSID)) {
+                        uSameBssidNum++;
+                     }
+                  }
+	     if(uSameBssidNum >= 2) {  //hit: desired AP is in hidden ssid mode!!!
+                 printk("SIOCSIWESSID:hidden ssid directly associate.......\n");
+	        vResetCommandTimer((HANDLE) pDevice);
+	        pMgmt->eScanType = WMAC_SCAN_PASSIVE;          //this scan type,you'll submit scan result!
+	        bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, pMgmt->abyDesireSSID);
+	        bScheduleCommand((HANDLE) pDevice, WLAN_CMD_SSID, pMgmt->abyDesireSSID);
+	     }
+	 }
+        }
+     return 0;
+  }
+	     #endif
+
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "set essid = %s \n", pItemSSID->abySSID);
+/*
+	             #if WIRELESS_EXT < 21
+ DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO " SIOCSIWESSID1 \n");
+		pItemSSID->len = wrq->length - 1;
+	     #else
+ DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO " SIOCSIWESSID2 \n");
+		pItemSSID->len = wrq->length;
+	     #endif
+	     */
+	}
+
+    if (pDevice->flags & DEVICE_FLAGS_OPENED) {
+	    pDevice->bCommit = TRUE;
+	}
+
+
+	return 0;
+}
+
+
+/*
+ * Wireless Handler : get essid
+ */
+
+int iwctl_giwessid(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra)
+{
+
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+	PWLAN_IE_SSID       pItemSSID;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWESSID \n");
+
+	// Note : if wrq->u.data.flags != 0, we should
+	// get the relevant SSID from the SSID list...
+
+	// Get the current SSID
+    pItemSSID = (PWLAN_IE_SSID)pMgmt->abyCurrSSID;
+	//pItemSSID = (PWLAN_IE_SSID)pMgmt->abyDesireSSID;
+	memcpy(extra, pItemSSID->abySSID , pItemSSID->len);
+	extra[pItemSSID->len] = '\0';
+	wrq->length = pItemSSID->len + 1;
+	        //2008-0409-03, <Add> by Einsn Liu
+        #if WIRELESS_EXT < 21
+	wrq->length = pItemSSID->len + 1;
+        #else
+        wrq->length = pItemSSID->len;
+        #endif
+	wrq->flags = 1; // active
+
+
+	return 0;
+}
+
+/*
+ * Wireless Handler : set data rate
+ */
+
+int iwctl_siwrate(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    int rc = 0;
+	u8	brate = 0;
+	int	i;
+	BYTE abySupportedRates[13]= {0x02, 0x04, 0x0B, 0x16, 0x0c, 0x12, 0x18, 0x24, 0x30, 0x48, 0x60, 0x6C, 0x90};
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWRATE \n");
+    if (!(pDevice->flags & DEVICE_FLAGS_OPENED)) {
+        rc = -EINVAL;
+        return rc;
+    }
+
+	// First : get a valid bit rate value
+
+	// Which type of value
+	if((wrq->value < 13) &&
+	   (wrq->value >= 0)) {
+		// Setting by rate index
+		// Find value in the magic rate table
+		brate = wrq->value;
+	} else {
+		// Setting by frequency value
+		u8	normvalue = (u8) (wrq->value/500000);
+
+		// Check if rate is valid
+		for(i = 0 ; i < 13 ; i++) {
+			if(normvalue == abySupportedRates[i]) {
+				brate = i;
+				break;
+			}
+		}
+	}
+	// -1 designed the max rate (mostly auto mode)
+	if(wrq->value == -1) {
+		// Get the highest available rate
+		for(i = 0 ; i < 13 ; i++) {
+			if(abySupportedRates[i] == 0)
+				break;
+		}
+		if(i != 0)
+			brate = i - 1;
+
+	}
+	// Check that it is valid
+	// brate is index of abySupportedRates[]
+	if(brate > 13 ) {
+		rc = -EINVAL;
+		return rc;
+	}
+
+	// Now, check if we want a fixed or auto value
+	if(wrq->fixed != 0) {
+		// Fixed mode
+		// One rate, fixed
+	printk("Rate Fix\n");
+		pDevice->bFixRate = TRUE;
+        if ((pDevice->byBBType == BB_TYPE_11B)&& (brate > 3)) {
+
+			pDevice->uConnectionRate = 3;
+        }
+        else {
+            pDevice->uConnectionRate = brate;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Fixed to Rate %d \n", pDevice->uConnectionRate);
+        }
+
+	}
+	else {
+        pDevice->bFixRate = FALSE;
+        pDevice->uConnectionRate = 13;
+	printk("auto rate:connection_rate is 13\n");
+}
+
+	return rc;
+}
+
+/*
+ * Wireless Handler : get data rate
+ */
+
+int iwctl_giwrate(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_param *wrq,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+//2007-0118-05,<Mark> by EinsnLiu
+//Mark the unnecessary sentences.
+//    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWRATE \n");
+    {
+        BYTE abySupportedRates[13]= {0x02, 0x04, 0x0B, 0x16, 0x0c, 0x12, 0x18, 0x24, 0x30, 0x48, 0x60, 0x6C, 0x90};
+	    int brate = 0;
+//2008-5-8 <modify> by chester
+if(pDevice->bLinkPass){
+if(pDevice->bFixRate == TRUE){
+		if (pDevice->uConnectionRate < 13) {
+	        brate = abySupportedRates[pDevice->uConnectionRate];
+	    }else {
+            if (pDevice->byBBType == BB_TYPE_11B)
+	            brate = 0x16;
+            if (pDevice->byBBType == BB_TYPE_11G)
+	            brate = 0x6C;
+            if (pDevice->byBBType == BB_TYPE_11A)
+	            brate = 0x6C;
+	    }
+}
+else
+{
+
+ brate = abySupportedRates[TxRate_iwconfig];
+}
+}
+else brate =0;
+//2007-0118-05,<Mark> by EinsnLiu
+//Mark the unnecessary sentences.
+/*
+	    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+            if (pDevice->byBBType == BB_TYPE_11B)
+	            brate = 0x16;
+            if (pDevice->byBBType == BB_TYPE_11G)
+	            brate = 0x6C;
+            if (pDevice->byBBType == BB_TYPE_11A)
+	            brate = 0x6C;
+	    }
+*/
+
+//    		if (pDevice->uConnectionRate == 13)
+//                brate = abySupportedRates[pDevice->wCurrentRate];
+	    wrq->value = brate * 500000;
+	    // If more than one rate, set auto
+	    if (pDevice->bFixRate == TRUE)
+	        wrq->fixed = TRUE;
+    }
+
+
+	return 0;
+}
+
+
+
+/*
+ * Wireless Handler : set rts threshold
+ */
+
+int iwctl_siwrts(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+	int rc = 0;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWRTS \n");
+
+	{
+	    int rthr = wrq->value;
+	    if(wrq->disabled)
+			rthr = 2312;
+	    if((rthr < 0) || (rthr > 2312)) {
+			rc = -EINVAL;
+    	}else {
+		    pDevice->wRTSThreshold = rthr;
+	    }
+    }
+
+	return 0;
+}
+
+/*
+ * Wireless Handler : get rts
+ */
+
+int iwctl_giwrts(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra)
+{
+	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWRTS \n");
+	wrq->value = pDevice->wRTSThreshold;
+	wrq->disabled = (wrq->value >= 2312);
+	wrq->fixed = 1;
+
+	return 0;
+}
+
+/*
+ * Wireless Handler : set fragment threshold
+ */
+
+int iwctl_siwfrag(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra)
+{
+    PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    int rc = 0;
+    int fthr = wrq->value;
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWFRAG \n");
+
+
+    if (wrq->disabled)
+		fthr = 2312;
+    if((fthr < 256) || (fthr > 2312)) {
+		rc = -EINVAL;
+    }else {
+		 fthr &= ~0x1;	// Get an even value
+	     pDevice->wFragmentationThreshold = (u16)fthr;
+    }
+
+	return rc;
+}
+
+/*
+ * Wireless Handler : get fragment threshold
+ */
+
+int iwctl_giwfrag(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra)
+{
+    PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWFRAG \n");
+	wrq->value = pDevice->wFragmentationThreshold;
+	wrq->disabled = (wrq->value >= 2312);
+	wrq->fixed = 1;
+
+	return 0;
+}
+
+
+
+/*
+ * Wireless Handler : set retry threshold
+ */
+int iwctl_siwretry(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra)
+{
+    PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    int rc = 0;
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWRETRY \n");
+
+	if (wrq->disabled) {
+		rc = -EINVAL;
+		return rc;
+	}
+
+	if (wrq->flags & IW_RETRY_LIMIT) {
+		if(wrq->flags & IW_RETRY_MAX)
+			pDevice->byLongRetryLimit = wrq->value;
+		else if (wrq->flags & IW_RETRY_MIN)
+			pDevice->byShortRetryLimit = wrq->value;
+		else {
+			// No modifier : set both
+			pDevice->byShortRetryLimit = wrq->value;
+			pDevice->byLongRetryLimit = wrq->value;
+		}
+	}
+	if (wrq->flags & IW_RETRY_LIFETIME) {
+		pDevice->wMaxTransmitMSDULifetime = wrq->value;
+	}
+
+
+	return rc;
+}
+
+/*
+ * Wireless Handler : get retry threshold
+ */
+int iwctl_giwretry(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra)
+{
+    PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWRETRY \n");
+	wrq->disabled = 0;      // Can't be disabled
+
+	// Note : by default, display the min retry number
+	if((wrq->flags & IW_RETRY_TYPE) == IW_RETRY_LIFETIME) {
+		wrq->flags = IW_RETRY_LIFETIME;
+		wrq->value = (int)pDevice->wMaxTransmitMSDULifetime; //ms
+	} else if((wrq->flags & IW_RETRY_MAX)) {
+		wrq->flags = IW_RETRY_LIMIT | IW_RETRY_MAX;
+		wrq->value = (int)pDevice->byLongRetryLimit;
+	} else {
+		wrq->flags = IW_RETRY_LIMIT;
+		wrq->value = (int)pDevice->byShortRetryLimit;
+		if((int)pDevice->byShortRetryLimit != (int)pDevice->byLongRetryLimit)
+			wrq->flags |= IW_RETRY_MIN;
+	}
+
+
+	return 0;
+}
+
+
+/*
+ * Wireless Handler : set encode mode
+ */
+int iwctl_siwencode(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra)
+{
+    PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+	DWORD dwKeyIndex = (DWORD)(wrq->flags & IW_ENCODE_INDEX);
+	int ii,uu, rc = 0;
+	int index = (wrq->flags & IW_ENCODE_INDEX);
+
+//2007-0207-07,<Modify> by EinsnLiu
+//There are some problems when using iwconfig encode/key command to set the WEP key.
+//I almost rewrite this function.
+//now it support:(assume the wireless interface's name is eth0)
+//iwconfig eth0 key [1] 1122334455 open  /*set key stirng to index 1,and driver using key index is set to 1*/
+//iwconfig eth0 key [3]    /*set driver using  key index to 3,the key string no change */
+//iwconfig eth0 key 1122334455  /*set key string to driver using index*/
+//iwconfig eth0 key restricted  /*enable share key*/
+
+	PSKeyTable pkeytab;
+
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWENCODE \n");
+
+if((wrq->flags & IW_ENCODE_DISABLED)==0){
+	//Not disable encryption
+
+	if (dwKeyIndex > WLAN_WEP_NKEYS) {
+		rc = -EINVAL;
+        return rc;
+    	}
+
+	if(dwKeyIndex<1&&((wrq->flags&IW_ENCODE_NOKEY)==0)){//set default key
+		if(pDevice->byKeyIndex<WLAN_WEP_NKEYS){
+			dwKeyIndex=pDevice->byKeyIndex;
+			}
+		else dwKeyIndex=0;
+		}else dwKeyIndex--;
+
+
+	// Check the size of the key
+	if (wrq->length > WLAN_WEP232_KEYLEN) {
+		rc = -EINVAL;
+        return rc;
+	}
+
+	if(wrq->length>0){//have key
+
+        if (wrq->length ==  WLAN_WEP232_KEYLEN) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Set 232 bit wep key\n");
+        }
+        else if (wrq->length ==  WLAN_WEP104_KEYLEN) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Set 104 bit wep key\n");
+        }
+        else if (wrq->length == WLAN_WEP40_KEYLEN) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Set 40 bit wep key, index= %d\n", (int)dwKeyIndex);
+        }else {//no support length
+		rc = -EINVAL;
+        return rc;
+		}
+        memset(pDevice->abyKey, 0, WLAN_WEP232_KEYLEN);
+        memcpy(pDevice->abyKey, extra, wrq->length);
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"abyKey: ");
+        for (ii = 0; ii < wrq->length; ii++) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%02x ", pDevice->abyKey[ii]);
+        }
+
+        if (pDevice->flags & DEVICE_FLAGS_OPENED) {
+            spin_lock_irq(&pDevice->lock);
+            KeybSetDefaultKey(&(pDevice->sKey),
+                            (DWORD)(dwKeyIndex | (1 << 31)),
+                           	wrq->length,
+                            NULL,
+                            pDevice->abyKey,
+                            KEY_CTL_WEP,
+                            pDevice->PortOffset,
+                            pDevice->byLocalID
+                          );
+            spin_unlock_irq(&pDevice->lock);
+        }
+        pDevice->byKeyIndex = (BYTE)dwKeyIndex;
+        pDevice->uKeyLength = wrq->length;
+        pDevice->bTransmitKey = TRUE;
+        pDevice->bEncryptionEnable = TRUE;
+        pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
+
+		}else if(index>0){
+	//when the length is 0 the request only changes the default transmit key index
+	//check the new key has a non zero lenget
+	if(pDevice->bEncryptionEnable==FALSE)
+	{
+		rc = -EINVAL;
+        	return rc;
+	}
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Just set Default key Index:\n");
+	pkeytab=&(pDevice->sKey.KeyTable[MAX_KEY_TABLE-1]);
+	if(pkeytab->GroupKey[(BYTE)dwKeyIndex].uKeyLength==0){
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Default key len is 0\n");
+		rc = -EINVAL;
+      	  	return rc;
+		}
+	 pDevice->byKeyIndex =(BYTE)dwKeyIndex;
+	 pkeytab->dwGTKeyIndex =dwKeyIndex | (1 << 31);
+	 pkeytab->GroupKey[(BYTE)dwKeyIndex].dwKeyIndex=dwKeyIndex | (1 << 31);
+	}
+
+}else {//disable the key
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Disable WEP function\n");
+	if(pDevice->bEncryptionEnable==FALSE)
+		return 0;
+	pMgmt->bShareKeyAlgorithm = FALSE;
+        pDevice->bEncryptionEnable = FALSE;
+        pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
+        if (pDevice->flags & DEVICE_FLAGS_OPENED) {
+            spin_lock_irq(&pDevice->lock);
+            for(uu=0;uu<MAX_KEY_TABLE;uu++)
+                MACvDisableKeyEntry(pDevice->PortOffset, uu);
+            spin_unlock_irq(&pDevice->lock);
+        }
+}
+//End Modify,Einsn
+
+/*
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWENCODE \n");
+
+	// Check the size of the key
+	if (wrq->length > WLAN_WEP232_KEYLEN) {
+		rc = -EINVAL;
+        return rc;
+	}
+
+	if (dwKeyIndex > WLAN_WEP_NKEYS) {
+		rc = -EINVAL;
+        return rc;
+    }
+
+    if (dwKeyIndex > 0)
+		dwKeyIndex--;
+
+	// Send the key to the card
+	if (wrq->length > 0) {
+
+        if (wrq->length ==  WLAN_WEP232_KEYLEN) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Set 232 bit wep key\n");
+        }
+        else if (wrq->length ==  WLAN_WEP104_KEYLEN) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Set 104 bit wep key\n");
+        }
+        else if (wrq->length == WLAN_WEP40_KEYLEN) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Set 40 bit wep key, index= %d\n", (int)dwKeyIndex);
+        }
+        memset(pDevice->abyKey, 0, WLAN_WEP232_KEYLEN);
+        memcpy(pDevice->abyKey, extra, wrq->length);
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"abyKey: ");
+        for (ii = 0; ii < wrq->length; ii++) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%02x ", pDevice->abyKey[ii]);
+        }
+
+        if (pDevice->flags & DEVICE_FLAGS_OPENED) {
+            spin_lock_irq(&pDevice->lock);
+            KeybSetDefaultKey(&(pDevice->sKey),
+                            (DWORD)(pDevice->byKeyIndex | (1 << 31)),
+                            pDevice->uKeyLength,
+                            NULL,
+                            pDevice->abyKey,
+                            KEY_CTL_WEP,
+                            pDevice->PortOffset,
+                            pDevice->byLocalID
+                          );
+            spin_unlock_irq(&pDevice->lock);
+        }
+        pDevice->byKeyIndex = (BYTE)dwKeyIndex;
+        pDevice->uKeyLength = wrq->length;
+        pDevice->bTransmitKey = TRUE;
+        pDevice->bEncryptionEnable = TRUE;
+        pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
+
+		// Do we want to just set the transmit key index ?
+		if ( index < 4 ) {
+		    pDevice->byKeyIndex = index;
+		}
+		else if(!wrq->flags & IW_ENCODE_MODE) {
+				rc = -EINVAL;
+				return rc;
+	    }
+	}
+	// Read the flags
+	if(wrq->flags & IW_ENCODE_DISABLED){
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Disable WEP function\n");
+		pMgmt->bShareKeyAlgorithm = FALSE;
+        pDevice->bEncryptionEnable = FALSE;
+        pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
+        if (pDevice->flags & DEVICE_FLAGS_OPENED) {
+            spin_lock_irq(&pDevice->lock);
+            for(uu=0;uu<MAX_KEY_TABLE;uu++)
+                MACvDisableKeyEntry(pDevice->PortOffset, uu);
+            spin_unlock_irq(&pDevice->lock);
+        }
+	}
+*/
+
+	if(wrq->flags & IW_ENCODE_RESTRICTED) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Enable WEP & ShareKey System\n");
+		pMgmt->bShareKeyAlgorithm = TRUE;
+	}
+	if(wrq->flags & IW_ENCODE_OPEN) {
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Enable WEP & Open System\n");
+		pMgmt->bShareKeyAlgorithm = FALSE;
+	}
+	return rc;
+}
+
+/*
+ * Wireless Handler : get encode mode
+ */
+ /*
+int iwctl_giwencode(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra)
+{
+    PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+    int rc = 0;
+    char abyKey[WLAN_WEP232_KEYLEN];
+	UINT index = (UINT)(wrq->flags & IW_ENCODE_INDEX);
+	PSKeyItem   pKey = NULL;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWENCODE\n");
+//2007-0207-06,<Add> by EinsnLiu
+//the key index in iwconfig is 1-4 when our driver is 0-3
+//so it can't be used directly.
+//if the index is 0,we should used the index set by driver.
+	if (index > WLAN_WEP_NKEYS) {
+		rc = -EINVAL;
+        return rc;
+    	}
+	if(index<1){//set default key
+		if(pDevice->byKeyIndex<WLAN_WEP_NKEYS){
+			index=pDevice->byKeyIndex;
+			}
+		else index=0;
+		}else index--;
+//End Add,Einsn
+
+	memset(abyKey, 0, sizeof(abyKey));
+	// Check encryption mode
+	wrq->flags = IW_ENCODE_NOKEY;
+	// Is WEP enabled ???
+	if (pDevice->bEncryptionEnable)
+		wrq->flags |=  IW_ENCODE_ENABLED;
+    else
+		wrq->flags |=  IW_ENCODE_DISABLED;
+
+    if (pMgmt->bShareKeyAlgorithm)
+		wrq->flags |=  IW_ENCODE_RESTRICTED;
+	else
+		wrq->flags |=  IW_ENCODE_OPEN;
+
+	if (KeybGetKey(&(pDevice->sKey), pDevice->abyBroadcastAddr, (BYTE)index , &pKey)){
+        wrq->length = pKey->uKeyLength;
+        memcpy(abyKey, pKey->abyKey,  pKey->uKeyLength);
+//2007-0207-06,<Modify> by EinsnLiu
+//only get key success need to  copy data
+//index should +1.
+//there is not necessary to return -EINVAL when get key failed
+//if return -EINVAL,the encryption item can't be display by the command "iwconfig".
+	wrq->flags |= index+1;
+	memcpy(extra,  abyKey, WLAN_WEP232_KEYLEN);
+    }
+
+    //else {
+    //    rc = -EINVAL;
+   //     return rc;
+  //  }
+
+
+//End Modify,Einsn
+
+	return 0;
+}
+*/
+
+//2008-0409-06, <Add> by Einsn Liu
+
+int iwctl_giwencode(struct net_device *dev,
+			struct iw_request_info *info,
+			struct iw_point *wrq,
+			char *extra)
+{
+	PSDevice			pDevice = (PSDevice)netdev_priv(dev);
+	PSMgmtObject		pMgmt = &(pDevice->sMgmtObj);
+	char abyKey[WLAN_WEP232_KEYLEN];
+
+	UINT index = (UINT)(wrq->flags & IW_ENCODE_INDEX);
+	PSKeyItem	pKey = NULL;
+
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWENCODE\n");
+
+	if (index > WLAN_WEP_NKEYS) {
+		return	-EINVAL;
+	}
+	if(index<1){//get default key
+		if(pDevice->byKeyIndex<WLAN_WEP_NKEYS){
+			index=pDevice->byKeyIndex;
+         	} else
+                      index=0;
+	}else
+             index--;
+
+	memset(abyKey, 0, WLAN_WEP232_KEYLEN);
+	// Check encryption mode
+	wrq->flags = IW_ENCODE_NOKEY;
+	// Is WEP enabled ???
+	if (pDevice->bEncryptionEnable)
+		wrq->flags |=  IW_ENCODE_ENABLED;
+	else
+		wrq->flags |=  IW_ENCODE_DISABLED;
+
+	if (pMgmt->bShareKeyAlgorithm)
+		wrq->flags |=  IW_ENCODE_RESTRICTED;
+	else
+		wrq->flags |=  IW_ENCODE_OPEN;
+		wrq->length=0;
+
+	if((index==0)&&(pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled||
+		pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled)){//get wpa pairwise  key
+			if (KeybGetKey(&(pDevice->sKey),pMgmt->abyCurrBSSID, 0xffffffff, &pKey)){
+			   wrq->length = pKey->uKeyLength;
+				  memcpy(abyKey, pKey->abyKey,	pKey->uKeyLength);
+				  memcpy(extra,  abyKey, WLAN_WEP232_KEYLEN);
+			   }
+	}else if (KeybGetKey(&(pDevice->sKey), pDevice->abyBroadcastAddr, (BYTE)index , &pKey)){
+			wrq->length = pKey->uKeyLength;
+			memcpy(abyKey, pKey->abyKey,  pKey->uKeyLength);
+		memcpy(extra,  abyKey, WLAN_WEP232_KEYLEN);
+	}
+
+	wrq->flags |= index+1;
+
+	return 0;
+}
+
+/*
+ * Wireless Handler : set power mode
+ */
+int iwctl_siwpower(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra)
+{
+    PSDevice            pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+    int rc = 0;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWPOWER \n");
+
+    if (!(pDevice->flags & DEVICE_FLAGS_OPENED)) {
+		 rc = -EINVAL;
+		 return rc;
+	}
+
+	if (wrq->disabled) {
+		pDevice->ePSMode = WMAC_POWER_CAM;
+		PSvDisablePowerSaving(pDevice);
+		return rc;
+	}
+	if ((wrq->flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {
+         pDevice->ePSMode = WMAC_POWER_FAST;
+         PSvEnablePowerSaving((HANDLE)pDevice, pMgmt->wListenInterval);
+
+	} else if ((wrq->flags & IW_POWER_TYPE) == IW_POWER_PERIOD) {
+	     pDevice->ePSMode = WMAC_POWER_FAST;
+         PSvEnablePowerSaving((HANDLE)pDevice, pMgmt->wListenInterval);
+	}
+	switch (wrq->flags & IW_POWER_MODE) {
+	case IW_POWER_UNICAST_R:
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWPOWER: IW_POWER_UNICAST_R \n");
+		rc = -EINVAL;
+		break;
+	case IW_POWER_ALL_R:
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWPOWER: IW_POWER_ALL_R \n");
+		rc = -EINVAL;
+	case IW_POWER_ON:
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWPOWER: IW_POWER_ON \n");
+		break;
+	default:
+		rc = -EINVAL;
+	}
+
+	return rc;
+}
+
+/*
+ * Wireless Handler : get power mode
+ */
+int iwctl_giwpower(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra)
+{
+    PSDevice            pDevice = (PSDevice)netdev_priv(dev);
+    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
+    int mode = pDevice->ePSMode;
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWPOWER \n");
+
+
+	if ((wrq->disabled = (mode == WMAC_POWER_CAM)))
+	    return 0;
+
+	if ((wrq->flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {
+		wrq->value = (int)((pMgmt->wListenInterval * pMgmt->wCurrBeaconPeriod) << 10);
+		wrq->flags = IW_POWER_TIMEOUT;
+	} else {
+		wrq->value = (int)((pMgmt->wListenInterval * pMgmt->wCurrBeaconPeriod) << 10);
+		wrq->flags = IW_POWER_PERIOD;
+	}
+	wrq->flags |= IW_POWER_ALL_R;
+
+	return 0;
+}
+
+
+/*
+ * Wireless Handler : get Sensitivity
+ */
+int iwctl_giwsens(struct net_device *dev,
+			 struct iw_request_info *info,
+			 struct iw_param *wrq,
+			 char *extra)
+{
+    PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+    long ldBm;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWSENS \n");
+    if (pDevice->bLinkPass == TRUE) {
+        RFvRSSITodBm(pDevice, (BYTE)(pDevice->uCurrRSSI), &ldBm);
+	    wrq->value = ldBm;
+	}
+	else {
+	    wrq->value = 0;
+    };
+	wrq->disabled = (wrq->value == 0);
+	wrq->fixed = 1;
+
+
+	return 0;
+}
+
+//2008-0409-07, <Add> by Einsn Liu
+#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+
+int iwctl_siwauth(struct net_device *dev,
+			  struct iw_request_info *info,
+			  struct iw_param *wrq,
+			  char *extra)
+{
+	PSDevice			pDevice = (PSDevice)netdev_priv(dev);
+	PSMgmtObject	pMgmt = &(pDevice->sMgmtObj);
+	int ret=0;
+	static int wpa_version=0;  //must be static to save the last value,einsn liu
+	static int pairwise=0;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWAUTH \n");
+	switch (wrq->flags & IW_AUTH_INDEX) {
+	case IW_AUTH_WPA_VERSION:
+		wpa_version = wrq->value;
+		if(wrq->value == IW_AUTH_WPA_VERSION_DISABLED) {
+		       printk("iwctl_siwauth:set WPADEV to disable at 1??????\n");
+			//pDevice->bWPADevEnable = FALSE;
+		}
+		else if(wrq->value == IW_AUTH_WPA_VERSION_WPA) {
+                          printk("iwctl_siwauth:set WPADEV to WPA1******\n");
+		}
+		else {
+                          printk("iwctl_siwauth:set WPADEV to WPA2******\n");
+		}
+		//pDevice->bWPASuppWextEnabled =TRUE;
+		break;
+	case IW_AUTH_CIPHER_PAIRWISE:
+		pairwise = wrq->value;
+
+		if(pairwise == IW_AUTH_CIPHER_CCMP){
+			pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;
+		}else if(pairwise == IW_AUTH_CIPHER_TKIP){
+			pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;
+		}else if(pairwise == IW_AUTH_CIPHER_WEP40||pairwise == IW_AUTH_CIPHER_WEP104){
+			pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
+		}else if(pairwise == IW_AUTH_CIPHER_NONE){
+			//do nothing,einsn liu
+		}else pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
+
+		break;
+	case IW_AUTH_CIPHER_GROUP:
+		if(wpa_version == IW_AUTH_WPA_VERSION_DISABLED)
+			break;
+		if(pairwise == IW_AUTH_CIPHER_NONE){
+			if(wrq->value == IW_AUTH_CIPHER_CCMP){
+				pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;
+			}else {
+				pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;
+			}
+		}
+		break;
+	case IW_AUTH_KEY_MGMT:
+
+		if(wpa_version == IW_AUTH_WPA_VERSION_WPA2){
+			if(wrq->value == IW_AUTH_KEY_MGMT_PSK)
+				pMgmt->eAuthenMode = WMAC_AUTH_WPA2PSK;
+			else pMgmt->eAuthenMode = WMAC_AUTH_WPA2;
+		}else if(wpa_version == IW_AUTH_WPA_VERSION_WPA){
+			if(wrq->value == 0){
+				pMgmt->eAuthenMode = WMAC_AUTH_WPANONE;
+			}else if(wrq->value == IW_AUTH_KEY_MGMT_PSK)
+				pMgmt->eAuthenMode = WMAC_AUTH_WPAPSK;
+			else pMgmt->eAuthenMode = WMAC_AUTH_WPA;
+		}
+
+		break;
+	case IW_AUTH_TKIP_COUNTERMEASURES:
+		break;		/* FIXME */
+	case IW_AUTH_DROP_UNENCRYPTED:
+		break;
+	case IW_AUTH_80211_AUTH_ALG:
+		if(wrq->value==IW_AUTH_ALG_OPEN_SYSTEM){
+			pMgmt->bShareKeyAlgorithm=FALSE;
+		}else if(wrq->value==IW_AUTH_ALG_SHARED_KEY){
+			pMgmt->bShareKeyAlgorithm=TRUE;
+		}
+		break;
+	case IW_AUTH_WPA_ENABLED:
+		//pDevice->bWPADevEnable = !! wrq->value;
+		break;
+	case IW_AUTH_RX_UNENCRYPTED_EAPOL:
+		break;
+	case IW_AUTH_ROAMING_CONTROL:
+		ret = -EOPNOTSUPP;
+		break;
+	case IW_AUTH_PRIVACY_INVOKED:
+		pDevice->bEncryptionEnable = !!wrq->value;
+		if(pDevice->bEncryptionEnable == FALSE){
+			wpa_version = 0;
+			pairwise = 0;
+			pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
+			pMgmt->bShareKeyAlgorithm = FALSE;
+			pMgmt->eAuthenMode = FALSE;
+			//pDevice->bWPADevEnable = FALSE;
+		}
+
+		break;
+	default:
+		ret = -EOPNOTSUPP;
+		break;
+	}
+/*
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wpa_version = %d\n",wpa_version);
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pairwise = %d\n",pairwise);
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->eEncryptionStatus = %d\n",pDevice->eEncryptionStatus);
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pMgmt->eAuthenMode  = %d\n",pMgmt->eAuthenMode);
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pMgmt->bShareKeyAlgorithm = %s\n",pMgmt->bShareKeyAlgorithm?"TRUE":"FALSE");
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->bEncryptionEnable = %s\n",pDevice->bEncryptionEnable?"TRUE":"FALSE");
+	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->bWPADevEnable = %s\n",pDevice->bWPADevEnable?"TRUE":"FALSE");
+*/
+   return ret;
+}
+
+
+int iwctl_giwauth(struct net_device *dev,
+			  struct iw_request_info *info,
+			  struct iw_param *wrq,
+			  char *extra)
+{
+	return -EOPNOTSUPP;
+}
+
+
+
+int iwctl_siwgenie(struct net_device *dev,
+			  struct iw_request_info *info,
+			  struct iw_point *wrq,
+			  char *extra)
+{
+	PSDevice			pDevice = (PSDevice)netdev_priv(dev);
+	PSMgmtObject	pMgmt = &(pDevice->sMgmtObj);
+	int ret=0;
+
+	if(wrq->length){
+		if ((wrq->length < 2) || (extra[1]+2 != wrq->length)) {
+			ret = -EINVAL;
+			goto out;
+		}
+		if(wrq->length > MAX_WPA_IE_LEN){
+			ret = -ENOMEM;
+			goto out;
+		}
+		memset(pMgmt->abyWPAIE, 0, MAX_WPA_IE_LEN);
+		if(copy_from_user(pMgmt->abyWPAIE, extra, wrq->length)){
+			ret = -EFAULT;
+			goto out;
+		}
+		pMgmt->wWPAIELen = wrq->length;
+	}else {
+		memset(pMgmt->abyWPAIE, 0, MAX_WPA_IE_LEN);
+		pMgmt->wWPAIELen = 0;
+	}
+
+	out://not completely ...not necessary in wpa_supplicant 0.5.8
+	return 0;
+}
+
+int iwctl_giwgenie(struct net_device *dev,
+			  struct iw_request_info *info,
+			  struct iw_point *wrq,
+			  char *extra)
+{
+	PSDevice			pDevice = (PSDevice)netdev_priv(dev);
+	PSMgmtObject	pMgmt = &(pDevice->sMgmtObj);
+	int ret=0;
+	int space = wrq->length;
+
+	wrq->length = 0;
+	if(pMgmt->wWPAIELen > 0){
+		wrq->length = pMgmt->wWPAIELen;
+		if(pMgmt->wWPAIELen <= space){
+			if(copy_to_user(extra, pMgmt->abyWPAIE, pMgmt->wWPAIELen)){
+				ret = -EFAULT;
+			}
+		}else
+			ret = -E2BIG;
+	}
+
+	return ret;
+}
+
+
+int iwctl_siwencodeext(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra)
+{
+    PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
+	struct iw_encode_ext *ext = (struct iw_encode_ext*)extra;
+    struct viawget_wpa_param *param=NULL;
+//original member
+    wpa_alg alg_name;
+    u8  addr[6];
+    int key_idx, set_tx;
+    u8  seq[IW_ENCODE_SEQ_MAX_SIZE];
+    u8 key[64];
+    size_t seq_len,key_len=0;
+//
+   // int ii;
+    u8 *buf;
+    size_t blen;
+    u8 key_array[64];
+    int ret=0;
+
+printk("SIOCSIWENCODEEXT...... \n");
+
+blen = sizeof(*param);
+buf = kmalloc((int)blen, (int)GFP_KERNEL);
+if (buf == NULL)
+    return -ENOMEM;
+memset(buf, 0, blen);
+param = (struct viawget_wpa_param *) buf;
+
+//recover alg_name
+switch (ext->alg) {
+    case IW_ENCODE_ALG_NONE:
+                  alg_name = WPA_ALG_NONE;
+		break;
+    case IW_ENCODE_ALG_WEP:
+                  alg_name = WPA_ALG_WEP;
+		break;
+    case IW_ENCODE_ALG_TKIP:
+                  alg_name = WPA_ALG_TKIP;
+		break;
+    case IW_ENCODE_ALG_CCMP:
+                  alg_name = WPA_ALG_CCMP;
+		break;
+    default:
+		printk("Unknown alg = %d\n",ext->alg);
+		ret= -ENOMEM;
+		goto error;
+		}
+//recover addr
+ memcpy(addr, ext->addr.sa_data, ETH_ALEN);
+//recover key_idx
+  key_idx = (wrq->flags&IW_ENCODE_INDEX) - 1;
+//recover set_tx
+if(ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
+   set_tx = 1;
+//recover seq,seq_len
+	if(ext->ext_flags & IW_ENCODE_EXT_RX_SEQ_VALID) {
+   seq_len=IW_ENCODE_SEQ_MAX_SIZE;
+   memcpy(seq, ext->rx_seq, seq_len);
+		}
+//recover key,key_len
+if(ext->key_len) {
+  key_len=ext->key_len;
+  memcpy(key, &ext->key[0], key_len);
+	}
+
+memset(key_array, 0, 64);
+if ( key_len > 0) {
+     memcpy(key_array, key, key_len);
+    if (key_len == 32) {
+          // notice ! the oder
+	  memcpy(&key_array[16], &key[24], 8);
+	  memcpy(&key_array[24], &key[16], 8);
+	}
+	}
+
+/**************Translate iw_encode_ext to viawget_wpa_param****************/
+memcpy(param->addr, addr, ETH_ALEN);
+param->u.wpa_key.alg_name = (int)alg_name;
+param->u.wpa_key.set_tx = set_tx;
+param->u.wpa_key.key_index = key_idx;
+param->u.wpa_key.key_len = key_len;
+param->u.wpa_key.key = (u8 *)key_array;
+param->u.wpa_key.seq = (u8 *)seq;
+param->u.wpa_key.seq_len = seq_len;
+
+#if 0
+int ii;
+printk("param->u.wpa_key.alg_name =%d\n",param->u.wpa_key.alg_name);
+printk("param->addr=%02x:%02x:%02x:%02x:%02x:%02x\n",
+	      param->addr[0],param->addr[1],param->addr[2],
+	      param->addr[3],param->addr[4],param->addr[5]);
+printk("param->u.wpa_key.set_tx =%d\n",param->u.wpa_key.set_tx);
+printk("param->u.wpa_key.key_index =%d\n",param->u.wpa_key.key_index);
+printk("param->u.wpa_key.key_len =%d\n",param->u.wpa_key.key_len);
+printk("param->u.wpa_key.key =");
+for(ii=0;ii<param->u.wpa_key.key_len;ii++)
+	printk("%02x:",param->u.wpa_key.key[ii]);
+         printk("\n");
+printk("param->u.wpa_key.seq_len =%d\n",param->u.wpa_key.seq_len);
+printk("param->u.wpa_key.seq =");
+for(ii=0;ii<param->u.wpa_key.seq_len;ii++)
+	printk("%02x:",param->u.wpa_key.seq[ii]);
+         printk("\n");
+
+printk("...........\n");
+#endif
+//****set if current action is Network Manager count??
+//****this method is so foolish,but there is no other way???
+if(param->u.wpa_key.alg_name == WPA_ALG_NONE) {
+   if(param->u.wpa_key.key_index ==0) {
+     pDevice->bwextcount++;
+    }
+   if((pDevice->bwextcount == 1)&&(param->u.wpa_key.key_index ==1)) {
+ pDevice->bwextcount++;
+    }
+   if((pDevice->bwextcount ==2)&&(param->u.wpa_key.key_index ==2)) {
+ pDevice->bwextcount++;
+	}
+   if((pDevice->bwextcount ==3)&&(param->u.wpa_key.key_index ==3)) {
+ pDevice->bwextcount++;
+        }
+		 }
+if( pDevice->bwextcount == 4) {
+    printk("SIOCSIWENCODEEXT:Enable WPA WEXT SUPPORT!!!!!\n");
+ pDevice->bwextcount=0;
+   pDevice->bWPASuppWextEnabled = TRUE;
+		 }
+//******
+
+		spin_lock_irq(&pDevice->lock);
+ ret = wpa_set_keys(pDevice, param, TRUE);
+		spin_unlock_irq(&pDevice->lock);
+
+error:
+kfree(param);
+	return ret;
+}
+
+
+
+int iwctl_giwencodeext(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra)
+{
+		return -EOPNOTSUPP;;
+}
+
+int iwctl_siwmlme(struct net_device *dev,
+				struct iw_request_info * info,
+				struct iw_point *wrq,
+				char *extra)
+{
+	PSDevice			pDevice = (PSDevice)netdev_priv(dev);
+	PSMgmtObject	pMgmt = &(pDevice->sMgmtObj);
+	struct iw_mlme *mlme = (struct iw_mlme *)extra;
+	//u16 reason = cpu_to_le16(mlme->reason_code);
+	int ret = 0;
+
+	if(memcmp(pMgmt->abyCurrBSSID, mlme->addr.sa_data, ETH_ALEN)){
+		ret = -EINVAL;
+		return ret;
+	}
+	switch(mlme->cmd){
+	case IW_MLME_DEAUTH:
+		//this command seems to be not complete,please test it --einsnliu
+		//bScheduleCommand((HANDLE) pDevice, WLAN_CMD_DEAUTH, (PBYTE)&reason);
+		break;
+	case IW_MLME_DISASSOC:
+		if(pDevice->bLinkPass == TRUE){
+					  printk("iwctl_siwmlme--->send DISASSOCIATE\n");
+		  //clear related flags
+		   memset(pMgmt->abyDesireBSSID, 0xFF,6);
+		KeyvInitTable(&pDevice->sKey, pDevice->PortOffset);
+			bScheduleCommand((HANDLE)pDevice, WLAN_CMD_DISASSOCIATE, NULL);
+		}
+		break;
+	default:
+		ret = -EOPNOTSUPP;
+	}
+
+	return ret;
+
+}
+
+#endif
+
+
+/*------------------------------------------------------------------*/
+/*
+ * Structures to export the Wireless Handlers
+ */
+
+
+#if WIRELESS_EXT > 12
+
+/*
+static const iw_handler		iwctl_handler[] =
+{
+	(iw_handler) iwctl_commit,      // SIOCSIWCOMMIT
+	(iw_handler) iwctl_giwname,     // SIOCGIWNAME
+	(iw_handler) NULL,				// SIOCSIWNWID
+	(iw_handler) NULL,				// SIOCGIWNWID
+	(iw_handler) iwctl_siwfreq,		// SIOCSIWFREQ
+	(iw_handler) iwctl_giwfreq,		// SIOCGIWFREQ
+	(iw_handler) iwctl_siwmode,		// SIOCSIWMODE
+	(iw_handler) iwctl_giwmode,		// SIOCGIWMODE
+	(iw_handler) NULL,		        // SIOCSIWSENS
+	(iw_handler) iwctl_giwsens,		        // SIOCGIWSENS
+	(iw_handler) NULL, 		        // SIOCSIWRANGE
+	(iw_handler) iwctl_giwrange,		// SIOCGIWRANGE
+	(iw_handler) NULL,         		    // SIOCSIWPRIV
+	(iw_handler) NULL,             		// SIOCGIWPRIV
+	(iw_handler) NULL,             		// SIOCSIWSTATS
+	(iw_handler) NULL,                  // SIOCGIWSTATS
+    (iw_handler) NULL,                  // SIOCSIWSPY
+	(iw_handler) NULL,		            // SIOCGIWSPY
+	(iw_handler) NULL,				    // -- hole --
+	(iw_handler) NULL,				    // -- hole --
+	(iw_handler) iwctl_siwap,		    // SIOCSIWAP
+	(iw_handler) iwctl_giwap,		    // SIOCGIWAP
+	(iw_handler) NULL,				    // -- hole -- 0x16
+	(iw_handler) iwctl_giwaplist,       // SIOCGIWAPLIST
+#if WIRELESS_EXT > 13
+	(iw_handler) iwctl_siwscan,         // SIOCSIWSCAN
+	(iw_handler) iwctl_giwscan,         // SIOCGIWSCAN
+#else
+	(iw_handler) NULL,
+	(iw_handler) NULL,
+#endif
+	(iw_handler) iwctl_siwessid,		// SIOCSIWESSID
+	(iw_handler) iwctl_giwessid,		// SIOCGIWESSID
+	(iw_handler) NULL,		// SIOCSIWNICKN
+	(iw_handler) NULL,		// SIOCGIWNICKN
+	(iw_handler) NULL,				    // -- hole --
+	(iw_handler) NULL,				    // -- hole --
+	(iw_handler) iwctl_siwrate,		// SIOCSIWRATE 0x20
+	(iw_handler) iwctl_giwrate,		// SIOCGIWRATE
+	(iw_handler) iwctl_siwrts,		// SIOCSIWRTS
+	(iw_handler) iwctl_giwrts,		// SIOCGIWRTS
+	(iw_handler) iwctl_siwfrag,		// SIOCSIWFRAG
+	(iw_handler) iwctl_giwfrag,		// SIOCGIWFRAG
+	(iw_handler) NULL,		// SIOCSIWTXPOW
+	(iw_handler) NULL,		// SIOCGIWTXPOW
+	(iw_handler) iwctl_siwretry,		// SIOCSIWRETRY
+	(iw_handler) iwctl_giwretry,		// SIOCGIWRETRY
+	(iw_handler) iwctl_siwencode,		// SIOCSIWENCODE
+	(iw_handler) iwctl_giwencode,		// SIOCGIWENCODE
+	(iw_handler) iwctl_siwpower,		// SIOCSIWPOWER
+	(iw_handler) iwctl_giwpower,		// SIOCGIWPOWER
+#if WIRELESS_EXT > 17
+	(iw_handler) NULL,			// -- hole --
+	(iw_handler) NULL,			// -- hole --
+	(iw_handler) iwctl_siwgenie,    // SIOCSIWGENIE
+	(iw_handler) iwctl_giwgenie,    // SIOCGIWGENIE
+	(iw_handler) iwctl_siwauth,		// SIOCSIWAUTH
+	(iw_handler) iwctl_giwauth,		// SIOCGIWAUTH
+	(iw_handler) iwctl_siwencodeext,		// SIOCSIWENCODEEXT
+	(iw_handler) iwctl_giwencodeext,		// SIOCGIWENCODEEXT
+	(iw_handler) NULL,				// SIOCSIWPMKSA
+	(iw_handler) NULL,				// -- hole --
+#endif // WIRELESS_EXT > 17
+
+};
+*/
+
+static const iw_handler		iwctl_handler[] =
+{
+	(iw_handler) iwctl_commit,      // SIOCSIWCOMMIT
+	(iw_handler) NULL,      // SIOCGIWNAME
+	(iw_handler) NULL,				// SIOCSIWNWID
+	(iw_handler) NULL,				// SIOCGIWNWID
+	(iw_handler) NULL,		// SIOCSIWFREQ
+	(iw_handler) NULL,		// SIOCGIWFREQ
+	(iw_handler) NULL,		// SIOCSIWMODE
+	(iw_handler) NULL,		// SIOCGIWMODE
+	(iw_handler) NULL,		        // SIOCSIWSENS
+	(iw_handler) NULL,		        // SIOCGIWSENS
+	(iw_handler) NULL, 		        // SIOCSIWRANGE
+	(iw_handler) iwctl_giwrange,		// SIOCGIWRANGE
+	(iw_handler) NULL,         		    // SIOCSIWPRIV
+	(iw_handler) NULL,             		// SIOCGIWPRIV
+	(iw_handler) NULL,             		// SIOCSIWSTATS
+	(iw_handler) NULL,                  // SIOCGIWSTATS
+    (iw_handler) NULL,                  // SIOCSIWSPY
+	(iw_handler) NULL,		            // SIOCGIWSPY
+	(iw_handler) NULL,				    // -- hole --
+	(iw_handler) NULL,				    // -- hole --
+	(iw_handler) NULL,		    // SIOCSIWAP
+	(iw_handler) NULL,		    // SIOCGIWAP
+	(iw_handler) NULL,				    // -- hole -- 0x16
+	(iw_handler) NULL,       // SIOCGIWAPLIST
+#if WIRELESS_EXT > 13
+	(iw_handler) iwctl_siwscan,         // SIOCSIWSCAN
+	(iw_handler) iwctl_giwscan,         // SIOCGIWSCAN
+#else
+	(iw_handler) NULL,
+	(iw_handler) NULL,
+#endif
+	(iw_handler) NULL,		// SIOCSIWESSID
+	(iw_handler) NULL,		// SIOCGIWESSID
+	(iw_handler) NULL,		// SIOCSIWNICKN
+	(iw_handler) NULL,		// SIOCGIWNICKN
+	(iw_handler) NULL,		// -- hole --
+	(iw_handler) NULL,		// -- hole --
+	(iw_handler) NULL,		// SIOCSIWRATE 0x20
+	(iw_handler) NULL,		// SIOCGIWRATE
+	(iw_handler) NULL,		// SIOCSIWRTS
+	(iw_handler) NULL,		// SIOCGIWRTS
+	(iw_handler) NULL,		// SIOCSIWFRAG
+	(iw_handler) NULL,		// SIOCGIWFRAG
+	(iw_handler) NULL,		// SIOCSIWTXPOW
+	(iw_handler) NULL,		// SIOCGIWTXPOW
+	(iw_handler) NULL,		// SIOCSIWRETRY
+	(iw_handler) NULL,		// SIOCGIWRETRY
+	(iw_handler) NULL,		// SIOCSIWENCODE
+	(iw_handler) NULL,		// SIOCGIWENCODE
+	(iw_handler) NULL,		// SIOCSIWPOWER
+	(iw_handler) NULL,		// SIOCGIWPOWER
+
+//2008-0409-07, <Add> by Einsn Liu
+#if WIRELESS_EXT > 17
+	(iw_handler) NULL,			// -- hole --
+	(iw_handler) NULL,			// -- hole --
+	(iw_handler) NULL,    // SIOCSIWGENIE
+	(iw_handler) NULL,    // SIOCGIWGENIE
+	(iw_handler) NULL,		// SIOCSIWAUTH
+	(iw_handler) NULL,		// SIOCGIWAUTH
+	(iw_handler) NULL,		// SIOCSIWENCODEEXT
+	(iw_handler) NULL,		// SIOCGIWENCODEEXT
+	(iw_handler) NULL,				// SIOCSIWPMKSA
+	(iw_handler) NULL,				// -- hole --
+#endif // WIRELESS_EXT > 17
+};
+
+
+static const iw_handler		iwctl_private_handler[] =
+{
+	NULL,				// SIOCIWFIRSTPRIV
+};
+
+
+struct iw_priv_args iwctl_private_args[] = {
+{ IOCTL_CMD_SET,
+  IW_PRIV_TYPE_CHAR | 1024, 0,
+  "set"},
+};
+
+
+
+const struct iw_handler_def	iwctl_handler_def =
+{
+#if WIRELESS_EXT > 16
+	.get_wireless_stats = &iwctl_get_wireless_stats,
+#endif
+	.num_standard	= sizeof(iwctl_handler)/sizeof(iw_handler),
+//	.num_private	= sizeof(iwctl_private_handler)/sizeof(iw_handler),
+//	.num_private_args = sizeof(iwctl_private_args)/sizeof(struct iw_priv_args),
+	.num_private	= 0,
+	.num_private_args = 0,
+	.standard	= (iw_handler *) iwctl_handler,
+//	.private	= (iw_handler *) iwctl_private_handler,
+//	.private_args	= (struct iw_priv_args *)iwctl_private_args,
+	.private	= NULL,
+	.private_args	= NULL,
+};
+
+
+#endif // WIRELESS_EXT > 12
+
+
+#endif // WIRELESS_EXT
diff --git a/drivers/staging/vt6655/iwctl.h b/drivers/staging/vt6655/iwctl.h
new file mode 100644
index 0000000..07554e1
--- /dev/null
+++ b/drivers/staging/vt6655/iwctl.h
@@ -0,0 +1,332 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: iwctl.h
+ *
+ * Purpose:
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 21, 2004
+ *
+ */
+
+
+#ifndef __IWCTL_H__
+#define __IWCTL_H__
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+
+#if WIRELESS_EXT < 18
+
+
+#define SIOCSIWMLME	        0x8B16
+#define SIOCSIWGENIE	    0x8B30
+
+// WPA : Authentication mode parameters
+#define SIOCSIWAUTH	        0x8B32
+#define SIOCGIWAUTH	        0x8B33
+
+// WPA : Extended version of encoding configuration
+#define SIOCSIWENCODEEXT    0x8B34
+#define SIOCGIWENCODEEXT    0x8B35
+
+#define IW_AUTH_WPA_VERSION		0
+#define IW_AUTH_CIPHER_PAIRWISE		1
+#define IW_AUTH_CIPHER_GROUP		2
+#define IW_AUTH_KEY_MGMT		3
+#define IW_AUTH_TKIP_COUNTERMEASURES	4
+#define IW_AUTH_DROP_UNENCRYPTED	5
+#define IW_AUTH_80211_AUTH_ALG		6
+#define IW_AUTH_WPA_ENABLED		7
+#define IW_AUTH_RX_UNENCRYPTED_EAPOL	8
+#define IW_AUTH_ROAMING_CONTROL		9
+#define IW_AUTH_PRIVACY_INVOKED		10
+
+#define IW_AUTH_WPA_VERSION_DISABLED	0x00000001
+#define IW_AUTH_WPA_VERSION_WPA		0x00000002
+#define IW_AUTH_WPA_VERSION_WPA2	0x00000004
+
+#define IW_AUTH_CIPHER_NONE	    0x00000001
+#define IW_AUTH_CIPHER_WEP40	0x00000002
+#define IW_AUTH_CIPHER_TKIP	    0x00000004
+#define IW_AUTH_CIPHER_CCMP	    0x00000008
+#define IW_AUTH_CIPHER_WEP104	0x00000010
+
+#define IW_AUTH_KEY_MGMT_802_1X	1
+#define IW_AUTH_KEY_MGMT_PSK	2
+
+#define IW_AUTH_ALG_OPEN_SYSTEM	0x00000001
+#define IW_AUTH_ALG_SHARED_KEY	0x00000002
+#define IW_AUTH_ALG_LEAP	0x00000004
+
+#define IW_AUTH_ROAMING_ENABLE	0
+#define IW_AUTH_ROAMING_DISABLE	1
+
+#define IW_ENCODE_SEQ_MAX_SIZE	8
+
+#define IW_ENCODE_ALG_NONE	0
+#define IW_ENCODE_ALG_WEP	1
+#define IW_ENCODE_ALG_TKIP	2
+#define IW_ENCODE_ALG_CCMP	3
+
+
+struct	iw_encode_ext
+{
+	__u32		ext_flags; // IW_ENCODE_EXT_*
+	__u8		tx_seq[IW_ENCODE_SEQ_MAX_SIZE]; // LSB first
+	__u8		rx_seq[IW_ENCODE_SEQ_MAX_SIZE]; // LSB first
+	struct sockaddr	addr; // ff:ff:ff:ff:ff:ff for broadcast/multicast
+			              // (group) keys or unicast address for
+			              // individual keys
+	__u16		alg; // IW_ENCODE_ALG_*
+	__u16		key_len;
+	__u8		key[0];
+};
+
+
+struct	iw_mlme
+{
+	__u16		cmd; /* IW_MLME_* */
+	__u16		reason_code;
+	struct sockaddr	addr;
+};
+
+#endif // WIRELESS_EXT < 18
+
+
+
+#ifdef WIRELESS_EXT
+
+struct iw_statistics *iwctl_get_wireless_stats (struct net_device *dev);
+
+
+int iwctl_siwap(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct sockaddr *wrq,
+             char *extra);
+
+int iwctl_giwrange(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra);
+
+
+int iwctl_giwmode(struct net_device *dev,
+             struct iw_request_info *info,
+             __u32 *wmode,
+             char *extra);
+
+int iwctl_siwmode(struct net_device *dev,
+             struct iw_request_info *info,
+             __u32 *wmode,
+             char *extra);
+
+int iwctl_giwfreq(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_freq *wrq,
+             char *extra);
+
+int iwctl_siwfreq(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_freq *wrq,
+             char *extra);
+
+int iwctl_giwname(struct net_device *dev,
+			 struct iw_request_info *info,
+			 char *wrq,
+			 char *extra);
+
+int iwctl_giwnwid(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+                   char *extra) ;
+
+int iwctl_giwsens(struct net_device *dev,
+			 struct iw_request_info *info,
+			 struct iw_param *wrq,
+			 char *extra);
+
+int iwctl_giwap(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct sockaddr *wrq,
+             char *extra);
+
+int iwctl_giwaplist(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra);
+
+int iwctl_siwessid(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra);
+
+int iwctl_giwessid(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra);
+
+int iwctl_siwrate(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra);
+
+int iwctl_giwrate(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_param *wrq,
+             char *extra);
+
+int iwctl_siwrts(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra);
+
+
+int iwctl_giwrts(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra);
+
+int iwctl_siwfrag(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra);
+
+int iwctl_giwfrag(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra);
+
+int iwctl_siwretry(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra);
+
+int iwctl_giwretry(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra);
+
+int iwctl_siwencode(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra);
+
+int iwctl_giwencode(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra);
+
+int iwctl_siwpower(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra);
+
+int iwctl_giwpower(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra);
+
+int iwctl_giwscan(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_point *wrq,
+             char *extra);
+
+int iwctl_siwscan(struct net_device *dev,
+             struct iw_request_info *info,
+			 struct iw_param *wrq,
+             char *extra);
+
+//2008-0409-07, <Add> by Einsn Liu
+#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+int iwctl_siwauth(struct net_device *dev,
+			  struct iw_request_info *info,
+			  struct iw_param *wrq,
+			  char *extra);
+
+int iwctl_giwauth(struct net_device *dev,
+			  struct iw_request_info *info,
+			  struct iw_param *wrq,
+			  char *extra);
+
+int iwctl_siwgenie(struct net_device *dev,
+			  struct iw_request_info *info,
+			  struct iw_point *wrq,
+			  char *extra);
+
+int iwctl_giwgenie(struct net_device *dev,
+			  struct iw_request_info *info,
+			  struct iw_point *wrq,
+			  char *extra);
+
+int iwctl_siwencodeext(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra);
+
+int iwctl_giwencodeext(struct net_device *dev,
+             struct iw_request_info *info,
+             struct iw_point *wrq,
+             char *extra);
+
+int iwctl_siwmlme(struct net_device *dev,
+			struct iw_request_info * info,
+			struct iw_point *wrq,
+			char *extra);
+#endif // #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+
+
+#endif
+
+#if WIRELESS_EXT > 12
+extern const struct iw_handler_def	iwctl_handler_def;
+extern const struct iw_priv_args	iwctl_private_args;
+#else
+struct iw_request_info {};
+#endif	//WIRELESS_EXT > 12
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+
+#endif // __IWCTL_H__
+
+
+
diff --git a/drivers/staging/vt6655/kcompat.h b/drivers/staging/vt6655/kcompat.h
new file mode 100644
index 0000000..652c2c7
--- /dev/null
+++ b/drivers/staging/vt6655/kcompat.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: kcompat.h
+ *
+ * Purpose: define kernel compatibility header
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: Apr 8, 2002
+ *
+ */
+#ifndef _KCOMPAT_H
+#define _KCOMPAT_H
+
+#include <linux/version.h>
+
+#ifndef __init
+#define __init
+#endif
+
+#ifndef __exit
+#define __exit
+#endif
+
+#ifndef __devexit
+#define __devexit
+#endif
+
+#ifndef __devinitdata
+#define __devinitdata
+#endif
+
+#ifndef MODULE_LICENSE
+#define MODULE_LICENSE(license)
+#endif
+
+#ifndef MOD_INC_USE_COUNT
+#define MOD_INC_USE_COUNT do {} while (0)
+#endif
+
+#ifndef MOD_DEC_USE_COUNT
+#define MOD_DEC_USE_COUNT do {} while (0)
+#endif
+
+#ifndef HAVE_NETDEV_PRIV
+#define netdev_priv(dev) (dev->priv)
+#endif
+
+#ifndef IRQ_RETVAL
+typedef void irqreturn_t;
+
+#ifdef PRIVATE_OBJ
+#define IRQ_RETVAL(x)   (int)x
+#else
+#define IRQ_RETVAL(x)
+#endif
+
+#endif
+
+
+#ifndef MODULE_LICESEN
+#define MODULE_LICESEN(x)
+#endif
+
+
+#endif
+
diff --git a/drivers/staging/vt6655/key.c b/drivers/staging/vt6655/key.c
new file mode 100644
index 0000000..168ebd3
--- /dev/null
+++ b/drivers/staging/vt6655/key.c
@@ -0,0 +1,836 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: key.c
+ *
+ * Purpose: Implement functions for 802.11i Key management
+ *
+ * Author: Jerry Chen
+ *
+ * Date: May 29, 2003
+ *
+ * Functions:
+ *      KeyvInitTable - Init Key management table
+ *      KeybGetKey - Get Key from table
+ *      KeybSetKey - Set Key to table
+ *      KeybRemoveKey - Remove Key from table
+ *      KeybGetTransmitKey - Get Transmit Key from table
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__KEY_H__)
+#include "key.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+static int          msglevel                =MSG_LEVEL_INFO;
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+/*---------------------  Static Functions  --------------------------*/
+static VOID
+s_vCheckKeyTableValid (PSKeyManagement pTable, DWORD_PTR dwIoBase)
+{
+    int i;
+
+    for (i=0;i<MAX_KEY_TABLE;i++) {
+        if ((pTable->KeyTable[i].bInUse == TRUE) &&
+            (pTable->KeyTable[i].PairwiseKey.bKeyValid == FALSE) &&
+            (pTable->KeyTable[i].GroupKey[0].bKeyValid == FALSE) &&
+            (pTable->KeyTable[i].GroupKey[1].bKeyValid == FALSE) &&
+            (pTable->KeyTable[i].GroupKey[2].bKeyValid == FALSE) &&
+            (pTable->KeyTable[i].GroupKey[3].bKeyValid == FALSE)
+            ) {
+            pTable->KeyTable[i].bInUse = FALSE;
+            pTable->KeyTable[i].wKeyCtl = 0;
+            pTable->KeyTable[i].bSoftWEP = FALSE;
+            MACvDisableKeyEntry(dwIoBase, i);
+        }
+    }
+}
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+/*
+ * Description: Init Key management table
+ *
+ * Parameters:
+ *  In:
+ *      pTable          - Pointer to Key table
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+VOID KeyvInitTable (PSKeyManagement pTable, DWORD_PTR dwIoBase)
+{
+    int i;
+    int jj;
+
+    for (i=0;i<MAX_KEY_TABLE;i++) {
+        pTable->KeyTable[i].bInUse = FALSE;
+        pTable->KeyTable[i].PairwiseKey.bKeyValid = FALSE;
+        pTable->KeyTable[i].PairwiseKey.pvKeyTable = (PVOID)&pTable->KeyTable[i];
+        for (jj=0; jj < MAX_GROUP_KEY; jj++) {
+            pTable->KeyTable[i].GroupKey[jj].bKeyValid = FALSE;
+            pTable->KeyTable[i].GroupKey[jj].pvKeyTable = (PVOID)&pTable->KeyTable[i];
+        }
+        pTable->KeyTable[i].wKeyCtl = 0;
+        pTable->KeyTable[i].dwGTKeyIndex = 0;
+        pTable->KeyTable[i].bSoftWEP = FALSE;
+        MACvDisableKeyEntry(dwIoBase, i);
+    }
+}
+
+
+/*
+ * Description: Get Key from table
+ *
+ * Parameters:
+ *  In:
+ *      pTable          - Pointer to Key table
+ *      pbyBSSID        - BSSID of Key
+ *      dwKeyIndex      - Key Index (0xFFFFFFFF means pairwise key)
+ *  Out:
+ *      pKey            - Key return
+ *
+ * Return Value: TRUE if found otherwise FALSE
+ *
+ */
+BOOL KeybGetKey (
+    IN  PSKeyManagement pTable,
+    IN  PBYTE           pbyBSSID,
+    IN  DWORD           dwKeyIndex,
+    OUT PSKeyItem       *pKey
+    )
+{
+    int i;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"KeybGetKey() \n");
+
+    *pKey = NULL;
+    for (i=0;i<MAX_KEY_TABLE;i++) {
+        if ((pTable->KeyTable[i].bInUse == TRUE) &&
+            IS_ETH_ADDRESS_EQUAL(pTable->KeyTable[i].abyBSSID,pbyBSSID)) {
+            if (dwKeyIndex == 0xFFFFFFFF) {
+                if (pTable->KeyTable[i].PairwiseKey.bKeyValid == TRUE) {
+                    *pKey = &(pTable->KeyTable[i].PairwiseKey);
+                    return (TRUE);
+                }
+                else {
+                    return (FALSE);
+                }
+            } else if (dwKeyIndex < MAX_GROUP_KEY) {
+                if (pTable->KeyTable[i].GroupKey[dwKeyIndex].bKeyValid == TRUE) {
+                    *pKey = &(pTable->KeyTable[i].GroupKey[dwKeyIndex]);
+                    return (TRUE);
+                }
+                else {
+                    return (FALSE);
+                }
+            }
+            else {
+                return (FALSE);
+            }
+        }
+    }
+    return (FALSE);
+}
+
+
+/*
+ * Description: Set Key to table
+ *
+ * Parameters:
+ *  In:
+ *      pTable          - Pointer to Key table
+ *      pbyBSSID        - BSSID of Key
+ *      dwKeyIndex      - Key index (reference to NDIS DDK)
+ *      uKeyLength      - Key length
+ *      KeyRSC          - Key RSC
+ *      pbyKey          - Pointer to key
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success otherwise FALSE
+ *
+ */
+BOOL KeybSetKey (
+    PSKeyManagement pTable,
+    PBYTE           pbyBSSID,
+    DWORD           dwKeyIndex,
+    ULONG           uKeyLength,
+    PQWORD          pKeyRSC,
+    PBYTE           pbyKey,
+    BYTE            byKeyDecMode,
+    DWORD_PTR       dwIoBase,
+    BYTE            byLocalID
+    )
+{
+    int         i,j;
+    UINT        ii;
+    PSKeyItem   pKey;
+    UINT        uKeyIdx;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Enter KeybSetKey: %lX\n", dwKeyIndex);
+
+    j = (MAX_KEY_TABLE-1);
+    for (i=0;i<(MAX_KEY_TABLE-1);i++) {
+        if ((pTable->KeyTable[i].bInUse == FALSE) &&
+            (j == (MAX_KEY_TABLE-1))) {
+            // found empty table
+            j = i;
+        }
+        if ((pTable->KeyTable[i].bInUse == TRUE) &&
+            IS_ETH_ADDRESS_EQUAL(pTable->KeyTable[i].abyBSSID,pbyBSSID)) {
+            // found table already exist
+            if ((dwKeyIndex & PAIRWISE_KEY) != 0) {
+                // Pairwise key
+                pKey = &(pTable->KeyTable[i].PairwiseKey);
+                pTable->KeyTable[i].wKeyCtl &= 0xFFF0;          // clear pairwise key control filed
+                pTable->KeyTable[i].wKeyCtl |= byKeyDecMode;
+                uKeyIdx = 4;                                    // use HW key entry 4 for pairwise key
+            } else {
+                // Group key
+                if ((dwKeyIndex & 0x000000FF) >= MAX_GROUP_KEY)
+                    return (FALSE);
+                pKey = &(pTable->KeyTable[i].GroupKey[dwKeyIndex & 0x000000FF]);
+                if ((dwKeyIndex & TRANSMIT_KEY) != 0)  {
+                    // Group transmit key
+                    pTable->KeyTable[i].dwGTKeyIndex = dwKeyIndex;
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Group transmit key(R)[%lX]: %d\n", pTable->KeyTable[i].dwGTKeyIndex, i);
+                }
+                pTable->KeyTable[i].wKeyCtl &= 0xFF0F;          // clear group key control filed
+                pTable->KeyTable[i].wKeyCtl |= (byKeyDecMode << 4);
+                pTable->KeyTable[i].wKeyCtl |= 0x0040;          // use group key for group address
+                uKeyIdx = (dwKeyIndex & 0x000000FF);
+            }
+            pTable->KeyTable[i].wKeyCtl |= 0x8000;              // enable on-fly
+
+            pKey->bKeyValid = TRUE;
+            pKey->uKeyLength = uKeyLength;
+            pKey->dwKeyIndex = dwKeyIndex;
+            pKey->byCipherSuite = byKeyDecMode;
+            MEMvCopy(pKey->abyKey, pbyKey, uKeyLength);
+            if (byKeyDecMode == KEY_CTL_WEP) {
+                if (uKeyLength == WLAN_WEP40_KEYLEN)
+                    pKey->abyKey[15] &= 0x7F;
+                if (uKeyLength == WLAN_WEP104_KEYLEN)
+                    pKey->abyKey[15] |= 0x80;
+            }
+            MACvSetKeyEntry(dwIoBase, pTable->KeyTable[i].wKeyCtl, i, uKeyIdx, pbyBSSID, (PDWORD)pKey->abyKey, byLocalID);
+
+            if ((dwKeyIndex & USE_KEYRSC) == 0) {
+                // RSC set by NIC
+                ZERO_MEMORY(&(pKey->KeyRSC), sizeof(QWORD));
+            }
+            else {
+                MEMvCopy(&(pKey->KeyRSC), pKeyRSC,  sizeof(QWORD));
+            }
+            pKey->dwTSC47_16 = 0;
+            pKey->wTSC15_0 = 0;
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"KeybSetKey(R): \n");
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->bKeyValid: %d\n ", pKey->bKeyValid);
+            //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->uKeyLength: %d\n ", pKey->uKeyLength);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->abyKey: ");
+            for (ii = 0; ii < pKey->uKeyLength; ii++) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%02x ", pKey->abyKey[ii]);
+            }
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n");
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->dwTSC47_16: %lx\n ", pKey->dwTSC47_16);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->wTSC15_0: %x\n ", pKey->wTSC15_0);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->dwKeyIndex: %lx\n ", pKey->dwKeyIndex);
+
+            return (TRUE);
+        }
+    }
+    if (j < (MAX_KEY_TABLE-1)) {
+        MEMvCopy(pTable->KeyTable[j].abyBSSID,pbyBSSID,U_ETHER_ADDR_LEN);
+        pTable->KeyTable[j].bInUse = TRUE;
+        if ((dwKeyIndex & PAIRWISE_KEY) != 0)  {
+            // Pairwise key
+            pKey = &(pTable->KeyTable[j].PairwiseKey);
+            pTable->KeyTable[j].wKeyCtl &= 0xFFF0;          // clear pairwise key control filed
+            pTable->KeyTable[j].wKeyCtl |= byKeyDecMode;
+            uKeyIdx = 4;                                    // use HW key entry 4 for pairwise key
+        } else {
+            // Group key
+            if ((dwKeyIndex & 0x000000FF) >= MAX_GROUP_KEY)
+                return (FALSE);
+            pKey = &(pTable->KeyTable[j].GroupKey[dwKeyIndex & 0x000000FF]);
+            if ((dwKeyIndex & TRANSMIT_KEY) != 0)  {
+                // Group transmit key
+                pTable->KeyTable[j].dwGTKeyIndex = dwKeyIndex;
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Group transmit key(N)[%lX]: %d\n", pTable->KeyTable[j].dwGTKeyIndex, j);
+            }
+            pTable->KeyTable[j].wKeyCtl &= 0xFF0F;          // clear group key control filed
+            pTable->KeyTable[j].wKeyCtl |= (byKeyDecMode << 4);
+            pTable->KeyTable[j].wKeyCtl |= 0x0040;          // use group key for group address
+            uKeyIdx = (dwKeyIndex & 0x000000FF);
+        }
+        pTable->KeyTable[j].wKeyCtl |= 0x8000;              // enable on-fly
+
+        pKey->bKeyValid = TRUE;
+        pKey->uKeyLength = uKeyLength;
+        pKey->dwKeyIndex = dwKeyIndex;
+        pKey->byCipherSuite = byKeyDecMode;
+        MEMvCopy(pKey->abyKey, pbyKey, uKeyLength);
+        if (byKeyDecMode == KEY_CTL_WEP) {
+            if (uKeyLength == WLAN_WEP40_KEYLEN)
+                pKey->abyKey[15] &= 0x7F;
+            if (uKeyLength == WLAN_WEP104_KEYLEN)
+                pKey->abyKey[15] |= 0x80;
+        }
+        MACvSetKeyEntry(dwIoBase, pTable->KeyTable[j].wKeyCtl, j, uKeyIdx, pbyBSSID, (PDWORD)pKey->abyKey, byLocalID);
+
+        if ((dwKeyIndex & USE_KEYRSC) == 0) {
+            // RSC set by NIC
+            ZERO_MEMORY(&(pKey->KeyRSC), sizeof(QWORD));
+        }
+        else {
+            MEMvCopy(&(pKey->KeyRSC), pKeyRSC,  sizeof(QWORD));
+        }
+        pKey->dwTSC47_16 = 0;
+        pKey->wTSC15_0 = 0;
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"KeybSetKey(N): \n");
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->bKeyValid: %d\n ", pKey->bKeyValid);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->uKeyLength: %d\n ", (int)pKey->uKeyLength);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->abyKey: ");
+        for (ii = 0; ii < pKey->uKeyLength; ii++) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%02x ", pKey->abyKey[ii]);
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n");
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->dwTSC47_16: %lx\n ", pKey->dwTSC47_16);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->wTSC15_0: %x\n ", pKey->wTSC15_0);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->dwKeyIndex: %lx\n ", pKey->dwKeyIndex);
+
+        return (TRUE);
+    }
+    return (FALSE);
+}
+
+
+/*
+ * Description: Remove Key from table
+ *
+ * Parameters:
+ *  In:
+ *      pTable          - Pointer to Key table
+ *      pbyBSSID        - BSSID of Key
+ *      dwKeyIndex      - Key Index (reference to NDIS DDK)
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success otherwise FALSE
+ *
+ */
+BOOL KeybRemoveKey (
+    PSKeyManagement pTable,
+    PBYTE           pbyBSSID,
+    DWORD           dwKeyIndex,
+    DWORD_PTR       dwIoBase
+    )
+{
+    int  i;
+
+    if (IS_BROADCAST_ADDRESS(pbyBSSID)) {
+        // dealte all key
+        if ((dwKeyIndex & PAIRWISE_KEY) != 0) {
+            for (i=0;i<MAX_KEY_TABLE;i++) {
+                pTable->KeyTable[i].PairwiseKey.bKeyValid = FALSE;
+            }
+            s_vCheckKeyTableValid(pTable, dwIoBase);
+            return TRUE;
+        }
+        else if ((dwKeyIndex & 0x000000FF) < MAX_GROUP_KEY) {
+            for (i=0;i<MAX_KEY_TABLE;i++) {
+                pTable->KeyTable[i].GroupKey[dwKeyIndex & 0x000000FF].bKeyValid = FALSE;
+                if ((dwKeyIndex & 0x7FFFFFFF) == (pTable->KeyTable[i].dwGTKeyIndex & 0x7FFFFFFF)) {
+                    // remove Group transmit key
+                    pTable->KeyTable[i].dwGTKeyIndex = 0;
+                }
+            }
+            s_vCheckKeyTableValid(pTable, dwIoBase);
+            return TRUE;
+        }
+        else {
+            return FALSE;
+        }
+    }
+
+    for (i=0;i<MAX_KEY_TABLE;i++) {
+        if ((pTable->KeyTable[i].bInUse == TRUE) &&
+            IS_ETH_ADDRESS_EQUAL(pTable->KeyTable[i].abyBSSID,pbyBSSID)) {
+            if ((dwKeyIndex & PAIRWISE_KEY) != 0) {
+                pTable->KeyTable[i].PairwiseKey.bKeyValid = FALSE;
+                s_vCheckKeyTableValid(pTable, dwIoBase);
+                return (TRUE);
+            }
+            else if ((dwKeyIndex & 0x000000FF) < MAX_GROUP_KEY) {
+                pTable->KeyTable[i].GroupKey[dwKeyIndex & 0x000000FF].bKeyValid = FALSE;
+                if ((dwKeyIndex & 0x7FFFFFFF) == (pTable->KeyTable[i].dwGTKeyIndex & 0x7FFFFFFF)) {
+                    // remove Group transmit key
+                    pTable->KeyTable[i].dwGTKeyIndex = 0;
+                }
+                s_vCheckKeyTableValid(pTable, dwIoBase);
+                return (TRUE);
+            }
+            else {
+                return (FALSE);
+            }
+        }
+    }
+    return (FALSE);
+}
+
+
+/*
+ * Description: Remove Key from table
+ *
+ * Parameters:
+ *  In:
+ *      pTable          - Pointer to Key table
+ *      pbyBSSID        - BSSID of Key
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success otherwise FALSE
+ *
+ */
+BOOL KeybRemoveAllKey (
+    PSKeyManagement pTable,
+    PBYTE           pbyBSSID,
+    DWORD_PTR       dwIoBase
+    )
+{
+    int  i,u;
+
+    for (i=0;i<MAX_KEY_TABLE;i++) {
+        if ((pTable->KeyTable[i].bInUse == TRUE) &&
+            IS_ETH_ADDRESS_EQUAL(pTable->KeyTable[i].abyBSSID,pbyBSSID)) {
+            pTable->KeyTable[i].PairwiseKey.bKeyValid = FALSE;
+            for(u=0;u<MAX_GROUP_KEY;u++) {
+                pTable->KeyTable[i].GroupKey[u].bKeyValid = FALSE;
+            }
+            pTable->KeyTable[i].dwGTKeyIndex = 0;
+            s_vCheckKeyTableValid(pTable, dwIoBase);
+            return (TRUE);
+        }
+    }
+    return (FALSE);
+}
+
+/*
+ * Description: Remove WEP Key from table
+ *
+ * Parameters:
+ *  In:
+ *      pTable          - Pointer to Key table
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success otherwise FALSE
+ *
+ */
+VOID KeyvRemoveWEPKey (
+    PSKeyManagement pTable,
+    DWORD           dwKeyIndex,
+    DWORD_PTR       dwIoBase
+    )
+{
+
+   if ((dwKeyIndex & 0x000000FF) < MAX_GROUP_KEY) {
+        if (pTable->KeyTable[MAX_KEY_TABLE-1].bInUse == TRUE) {
+            if (pTable->KeyTable[MAX_KEY_TABLE-1].GroupKey[dwKeyIndex & 0x000000FF].byCipherSuite == KEY_CTL_WEP) {
+                pTable->KeyTable[MAX_KEY_TABLE-1].GroupKey[dwKeyIndex & 0x000000FF].bKeyValid = FALSE;
+                if ((dwKeyIndex & 0x7FFFFFFF) == (pTable->KeyTable[MAX_KEY_TABLE-1].dwGTKeyIndex & 0x7FFFFFFF)) {
+                    // remove Group transmit key
+                    pTable->KeyTable[MAX_KEY_TABLE-1].dwGTKeyIndex = 0;
+                }
+            }
+        }
+        s_vCheckKeyTableValid(pTable, dwIoBase);
+    }
+    return;
+}
+
+VOID KeyvRemoveAllWEPKey (
+    PSKeyManagement pTable,
+    DWORD_PTR       dwIoBase
+    )
+{
+    int i;
+
+    for(i=0;i<MAX_GROUP_KEY;i++) {
+        KeyvRemoveWEPKey(pTable, i, dwIoBase);
+    }
+}
+
+/*
+ * Description: Get Transmit Key from table
+ *
+ * Parameters:
+ *  In:
+ *      pTable          - Pointer to Key table
+ *      pbyBSSID        - BSSID of Key
+ *  Out:
+ *      pKey            - Key return
+ *
+ * Return Value: TRUE if found otherwise FALSE
+ *
+ */
+BOOL KeybGetTransmitKey (
+    IN  PSKeyManagement pTable,
+    IN  PBYTE           pbyBSSID,
+    IN  DWORD           dwKeyType,
+    OUT PSKeyItem       *pKey
+    )
+{
+    int i, ii;
+
+    *pKey = NULL;
+    for (i=0;i<MAX_KEY_TABLE;i++) {
+        if ((pTable->KeyTable[i].bInUse == TRUE) &&
+            IS_ETH_ADDRESS_EQUAL(pTable->KeyTable[i].abyBSSID,pbyBSSID)) {
+
+            if (dwKeyType == PAIRWISE_KEY) {
+
+                if (pTable->KeyTable[i].PairwiseKey.bKeyValid == TRUE) {
+                    *pKey = &(pTable->KeyTable[i].PairwiseKey);
+
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"KeybGetTransmitKey:");
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"PAIRWISE_KEY: KeyTable.abyBSSID: ");
+                    for (ii = 0; ii < 6; ii++) {
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%x ", pTable->KeyTable[i].abyBSSID[ii]);
+                    }
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n");
+
+
+                    return (TRUE);
+                }
+                else {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"PairwiseKey.bKeyValid == FALSE\n");
+                    return (FALSE);
+                }
+            } // End of Type == PAIRWISE
+            else {
+                if (pTable->KeyTable[i].dwGTKeyIndex == 0) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ERROR: dwGTKeyIndex == 0 !!!\n");
+                    return FALSE;
+                }
+                if (pTable->KeyTable[i].GroupKey[(pTable->KeyTable[i].dwGTKeyIndex&0x000000FF)].bKeyValid == TRUE) {
+                    *pKey = &(pTable->KeyTable[i].GroupKey[(pTable->KeyTable[i].dwGTKeyIndex&0x000000FF)]);
+
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"KeybGetTransmitKey:");
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"GROUP_KEY: KeyTable.abyBSSID\n");
+                        for (ii = 0; ii < 6; ii++) {
+                            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%x ", pTable->KeyTable[i].abyBSSID[ii]);
+                        }
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n");
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"dwGTKeyIndex: %lX\n", pTable->KeyTable[i].dwGTKeyIndex);
+
+                    return (TRUE);
+                }
+                else {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"GroupKey.bKeyValid == FALSE\n");
+                    return (FALSE);
+                }
+            } // End of Type = GROUP
+        } // BSSID match
+    }
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ERROR: NO Match BSSID !!! ");
+    for (ii = 0; ii < 6; ii++) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%02x ", *(pbyBSSID+ii));
+    }
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n");
+    return (FALSE);
+}
+
+
+/*
+ * Description: Check Pairewise Key
+ *
+ * Parameters:
+ *  In:
+ *      pTable          - Pointer to Key table
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if found otherwise FALSE
+ *
+ */
+BOOL KeybCheckPairewiseKey (
+    IN  PSKeyManagement pTable,
+    OUT PSKeyItem       *pKey
+    )
+{
+    int i;
+
+    *pKey = NULL;
+    for (i=0;i<MAX_KEY_TABLE;i++) {
+        if ((pTable->KeyTable[i].bInUse == TRUE) &&
+            (pTable->KeyTable[i].PairwiseKey.bKeyValid == TRUE)) {
+            *pKey = &(pTable->KeyTable[i].PairwiseKey);
+            return (TRUE);
+        }
+    }
+    return (FALSE);
+}
+
+/*
+ * Description: Set Key to table
+ *
+ * Parameters:
+ *  In:
+ *      pTable          - Pointer to Key table
+ *      dwKeyIndex      - Key index (reference to NDIS DDK)
+ *      uKeyLength      - Key length
+ *      KeyRSC          - Key RSC
+ *      pbyKey          - Pointer to key
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success otherwise FALSE
+ *
+ */
+BOOL KeybSetDefaultKey (
+    PSKeyManagement pTable,
+    DWORD           dwKeyIndex,
+    ULONG           uKeyLength,
+    PQWORD          pKeyRSC,
+    PBYTE           pbyKey,
+    BYTE            byKeyDecMode,
+    DWORD_PTR       dwIoBase,
+    BYTE            byLocalID
+    )
+{
+    UINT        ii;
+    PSKeyItem   pKey;
+    UINT        uKeyIdx;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Enter KeybSetDefaultKey: %1x, %d \n", (int)dwKeyIndex, (int)uKeyLength);
+
+
+    if ((dwKeyIndex & PAIRWISE_KEY) != 0) {                  // Pairwise key
+        return (FALSE);
+    } else if ((dwKeyIndex & 0x000000FF) >= MAX_GROUP_KEY) {
+        return (FALSE);
+    }
+
+    pTable->KeyTable[MAX_KEY_TABLE-1].bInUse = TRUE;
+    for(ii=0;ii<U_ETHER_ADDR_LEN;ii++)
+        pTable->KeyTable[MAX_KEY_TABLE-1].abyBSSID[ii] = 0xFF;
+
+    // Group key
+    pKey = &(pTable->KeyTable[MAX_KEY_TABLE-1].GroupKey[dwKeyIndex & 0x000000FF]);
+    if ((dwKeyIndex & TRANSMIT_KEY) != 0)  {
+        // Group transmit key
+        pTable->KeyTable[MAX_KEY_TABLE-1].dwGTKeyIndex = dwKeyIndex;
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Group transmit key(R)[%lX]: %d\n", pTable->KeyTable[MAX_KEY_TABLE-1].dwGTKeyIndex, MAX_KEY_TABLE-1);
+
+    }
+    pTable->KeyTable[MAX_KEY_TABLE-1].wKeyCtl &= 0x7F00;          // clear all key control filed
+    pTable->KeyTable[MAX_KEY_TABLE-1].wKeyCtl |= (byKeyDecMode << 4);
+    pTable->KeyTable[MAX_KEY_TABLE-1].wKeyCtl |= (byKeyDecMode);
+    pTable->KeyTable[MAX_KEY_TABLE-1].wKeyCtl |= 0x0044;          // use group key for all address
+    uKeyIdx = (dwKeyIndex & 0x000000FF);
+
+    if ((uKeyLength == WLAN_WEP232_KEYLEN) &&
+        (byKeyDecMode == KEY_CTL_WEP)) {
+        pTable->KeyTable[MAX_KEY_TABLE-1].wKeyCtl |= 0x4000;              // disable on-fly disable address match
+        pTable->KeyTable[MAX_KEY_TABLE-1].bSoftWEP = TRUE;
+    } else {
+        if (pTable->KeyTable[MAX_KEY_TABLE-1].bSoftWEP == FALSE)
+            pTable->KeyTable[MAX_KEY_TABLE-1].wKeyCtl |= 0xC000;          // enable on-fly disable address match
+    }
+
+    pKey->bKeyValid = TRUE;
+    pKey->uKeyLength = uKeyLength;
+    pKey->dwKeyIndex = dwKeyIndex;
+    pKey->byCipherSuite = byKeyDecMode;
+    MEMvCopy(pKey->abyKey, pbyKey, uKeyLength);
+    if (byKeyDecMode == KEY_CTL_WEP) {
+        if (uKeyLength == WLAN_WEP40_KEYLEN)
+            pKey->abyKey[15] &= 0x7F;
+        if (uKeyLength == WLAN_WEP104_KEYLEN)
+            pKey->abyKey[15] |= 0x80;
+    }
+    MACvSetKeyEntry(dwIoBase, pTable->KeyTable[MAX_KEY_TABLE-1].wKeyCtl, MAX_KEY_TABLE-1, uKeyIdx, pTable->KeyTable[MAX_KEY_TABLE-1].abyBSSID, (PDWORD)pKey->abyKey, byLocalID);
+
+    if ((dwKeyIndex & USE_KEYRSC) == 0) {
+        // RSC set by NIC
+        ZERO_MEMORY(&(pKey->KeyRSC), sizeof(QWORD));
+    } else {
+        MEMvCopy(&(pKey->KeyRSC), pKeyRSC,  sizeof(QWORD));
+    }
+    pKey->dwTSC47_16 = 0;
+    pKey->wTSC15_0 = 0;
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"KeybSetKey(R): \n");
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->bKeyValid: %d\n", pKey->bKeyValid);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->uKeyLength: %d\n", (int)pKey->uKeyLength);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->abyKey: \n");
+    for (ii = 0; ii < pKey->uKeyLength; ii++) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%x", pKey->abyKey[ii]);
+    }
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n");
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->dwTSC47_16: %lx\n", pKey->dwTSC47_16);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->wTSC15_0: %x\n", pKey->wTSC15_0);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->dwKeyIndex: %lx\n", pKey->dwKeyIndex);
+
+    return (TRUE);
+}
+
+
+/*
+ * Description: Set Key to table
+ *
+ * Parameters:
+ *  In:
+ *      pTable          - Pointer to Key table
+ *      dwKeyIndex      - Key index (reference to NDIS DDK)
+ *      uKeyLength      - Key length
+ *      KeyRSC          - Key RSC
+ *      pbyKey          - Pointer to key
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success otherwise FALSE
+ *
+ */
+BOOL KeybSetAllGroupKey (
+    PSKeyManagement pTable,
+    DWORD           dwKeyIndex,
+    ULONG           uKeyLength,
+    PQWORD          pKeyRSC,
+    PBYTE           pbyKey,
+    BYTE            byKeyDecMode,
+    DWORD_PTR       dwIoBase,
+    BYTE            byLocalID
+    )
+{
+    int         i;
+    UINT        ii;
+    PSKeyItem   pKey;
+    UINT        uKeyIdx;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Enter KeybSetAllGroupKey: %lX\n", dwKeyIndex);
+
+
+    if ((dwKeyIndex & PAIRWISE_KEY) != 0) {                  // Pairwise key
+        return (FALSE);
+    } else if ((dwKeyIndex & 0x000000FF) >= MAX_GROUP_KEY) {
+        return (FALSE);
+    }
+
+    for (i=0; i < MAX_KEY_TABLE-1; i++) {
+        if (pTable->KeyTable[i].bInUse == TRUE) {
+            // found table already exist
+            // Group key
+            pKey = &(pTable->KeyTable[i].GroupKey[dwKeyIndex & 0x000000FF]);
+            if ((dwKeyIndex & TRANSMIT_KEY) != 0)  {
+                // Group transmit key
+                pTable->KeyTable[i].dwGTKeyIndex = dwKeyIndex;
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Group transmit key(R)[%lX]: %d\n", pTable->KeyTable[i].dwGTKeyIndex, i);
+
+            }
+            pTable->KeyTable[i].wKeyCtl &= 0xFF0F;          // clear group key control filed
+            pTable->KeyTable[i].wKeyCtl |= (byKeyDecMode << 4);
+            pTable->KeyTable[i].wKeyCtl |= 0x0040;          // use group key for group address
+            uKeyIdx = (dwKeyIndex & 0x000000FF);
+
+            pTable->KeyTable[i].wKeyCtl |= 0x8000;              // enable on-fly
+
+            pKey->bKeyValid = TRUE;
+            pKey->uKeyLength = uKeyLength;
+            pKey->dwKeyIndex = dwKeyIndex;
+            pKey->byCipherSuite = byKeyDecMode;
+            MEMvCopy(pKey->abyKey, pbyKey, uKeyLength);
+            if (byKeyDecMode == KEY_CTL_WEP) {
+                if (uKeyLength == WLAN_WEP40_KEYLEN)
+                    pKey->abyKey[15] &= 0x7F;
+                if (uKeyLength == WLAN_WEP104_KEYLEN)
+                    pKey->abyKey[15] |= 0x80;
+            }
+            MACvSetKeyEntry(dwIoBase, pTable->KeyTable[i].wKeyCtl, i, uKeyIdx, pTable->KeyTable[i].abyBSSID, (PDWORD)pKey->abyKey, byLocalID);
+
+            if ((dwKeyIndex & USE_KEYRSC) == 0) {
+                // RSC set by NIC
+                ZERO_MEMORY(&(pKey->KeyRSC), sizeof(QWORD));
+            }
+            else {
+                MEMvCopy(&(pKey->KeyRSC), pKeyRSC,  sizeof(QWORD));
+            }
+            pKey->dwTSC47_16 = 0;
+            pKey->wTSC15_0 = 0;
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"KeybSetKey(R): \n");
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->bKeyValid: %d\n ", pKey->bKeyValid);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->uKeyLength: %d\n ", (int)pKey->uKeyLength);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pKey->abyKey: ");
+            for (ii = 0; ii < pKey->uKeyLength; ii++) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%02x ", pKey->abyKey[ii]);
+            }
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n");
+
+            //DBG_PRN_GRP12(("pKey->dwTSC47_16: %lX\n ", pKey->dwTSC47_16));
+            //DBG_PRN_GRP12(("pKey->wTSC15_0: %X\n ", pKey->wTSC15_0));
+            //DBG_PRN_GRP12(("pKey->dwKeyIndex: %lX\n ", pKey->dwKeyIndex));
+
+        } // (pTable->KeyTable[i].bInUse == TRUE)
+    }
+    return (TRUE);
+}
diff --git a/drivers/staging/vt6655/key.h b/drivers/staging/vt6655/key.h
new file mode 100644
index 0000000..9c7d335
--- /dev/null
+++ b/drivers/staging/vt6655/key.h
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: key.h
+ *
+ * Purpose: Implement functions for 802.11i Key management
+ *
+ * Author: Jerry Chen
+ *
+ * Date: May 29, 2003
+ *
+ */
+
+
+#ifndef __KEY_H__
+#define __KEY_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+
+#if !defined(__80211MGR_H__)
+#include "80211mgr.h"
+#endif
+
+/*---------------------  Export Definitions -------------------------*/
+#define MAX_GROUP_KEY       4
+#define MAX_KEY_TABLE       11
+#define MAX_KEY_LEN         32
+#define AES_KEY_LEN         16
+
+
+#define AUTHENTICATOR_KEY   0x10000000
+#define USE_KEYRSC          0x20000000
+#define PAIRWISE_KEY        0x40000000
+#define TRANSMIT_KEY        0x80000000
+
+#define GROUP_KEY           0x00000000
+
+#define KEY_CTL_WEP         0x00
+#define KEY_CTL_NONE        0x01
+#define KEY_CTL_TKIP        0x02
+#define KEY_CTL_CCMP        0x03
+#define KEY_CTL_INVALID     0xFF
+
+
+typedef struct tagSKeyItem
+{
+    BOOL        bKeyValid;
+    ULONG       uKeyLength;
+    BYTE        abyKey[MAX_KEY_LEN];
+    QWORD       KeyRSC;
+    DWORD       dwTSC47_16;
+    WORD        wTSC15_0;
+    BYTE        byCipherSuite;
+    BYTE        byReserved0;
+    DWORD       dwKeyIndex;
+    PVOID       pvKeyTable;
+} SKeyItem, DEF* PSKeyItem; //64
+
+typedef struct tagSKeyTable
+{
+    BYTE        abyBSSID[U_ETHER_ADDR_LEN];  //6
+    BYTE        byReserved0[2];              //8
+    SKeyItem    PairwiseKey;
+    SKeyItem    GroupKey[MAX_GROUP_KEY]; //64*5 = 320, 320+8=328
+    DWORD       dwGTKeyIndex;            // GroupTransmitKey Index
+    BOOL        bInUse;
+    //2006-1116-01,<Modify> by NomadZhao
+    //WORD      wKeyCtl;
+    //BOOL      bSoftWEP;
+    BOOL        bSoftWEP;
+    WORD        wKeyCtl;      // for address of wKeyCtl at align 4
+
+    BYTE        byReserved1[6];
+} SKeyTable, DEF* PSKeyTable; //348
+
+typedef struct tagSKeyManagement
+{
+    SKeyTable   KeyTable[MAX_KEY_TABLE];
+} SKeyManagement, DEF* PSKeyManagement;
+
+/*---------------------  Export Types  ------------------------------*/
+
+/*---------------------  Export Macros ------------------------------*/
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+VOID KeyvInitTable(PSKeyManagement pTable, DWORD_PTR dwIoBase);
+
+BOOL KeybGetKey(
+    IN  PSKeyManagement pTable,
+    IN  PBYTE           pbyBSSID,
+    IN  DWORD           dwKeyIndex,
+    OUT PSKeyItem       *pKey
+    );
+
+BOOL KeybSetKey(
+    PSKeyManagement pTable,
+    PBYTE           pbyBSSID,
+    DWORD           dwKeyIndex,
+    ULONG           uKeyLength,
+    PQWORD          pKeyRSC,
+    PBYTE           pbyKey,
+    BYTE            byKeyDecMode,
+    DWORD_PTR       dwIoBase,
+    BYTE            byLocalID
+    );
+
+BOOL KeybSetDefaultKey(
+    PSKeyManagement pTable,
+    DWORD           dwKeyIndex,
+    ULONG           uKeyLength,
+    PQWORD          pKeyRSC,
+    PBYTE           pbyKey,
+    BYTE            byKeyDecMode,
+    DWORD_PTR       dwIoBase,
+    BYTE            byLocalID
+    );
+
+BOOL KeybRemoveKey(
+    PSKeyManagement pTable,
+    PBYTE           pbyBSSID,
+    DWORD           dwKeyIndex,
+    DWORD_PTR       dwIoBase
+    );
+
+BOOL KeybGetTransmitKey(
+    IN  PSKeyManagement pTable,
+    IN  PBYTE           pbyBSSID,
+    IN  DWORD           dwKeyType,
+    OUT PSKeyItem       *pKey
+    );
+
+BOOL KeybCheckPairewiseKey(
+    IN  PSKeyManagement pTable,
+    OUT PSKeyItem       *pKey
+    );
+
+BOOL KeybRemoveAllKey(
+    PSKeyManagement pTable,
+    PBYTE           pbyBSSID,
+    DWORD_PTR       dwIoBase
+    );
+
+VOID KeyvRemoveWEPKey(
+    PSKeyManagement pTable,
+    DWORD           dwKeyIndex,
+    DWORD_PTR       dwIoBase
+    );
+
+VOID KeyvRemoveAllWEPKey(
+    PSKeyManagement pTable,
+    DWORD_PTR       dwIoBase
+    );
+
+BOOL KeybSetAllGroupKey (
+    PSKeyManagement pTable,
+    DWORD           dwKeyIndex,
+    ULONG           uKeyLength,
+    PQWORD          pKeyRSC,
+    PBYTE           pbyKey,
+    BYTE            byKeyDecMode,
+    DWORD_PTR       dwIoBase,
+    BYTE            byLocalID
+    );
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+
+#endif /* __cplusplus */
+
+
+#endif // __KEY_H__
+
diff --git a/drivers/staging/vt6655/mac.c b/drivers/staging/vt6655/mac.c
new file mode 100644
index 0000000..0283ed3
--- /dev/null
+++ b/drivers/staging/vt6655/mac.c
@@ -0,0 +1,1752 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: mac.c
+ *
+ * Purpose:  MAC routines
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ *
+ * Functions:
+ *      MACvReadAllRegs - Read All MAC Registers to buffer
+ *      MACbIsRegBitsOn - Test if All test Bits On
+ *      MACbIsRegBitsOff - Test if All test Bits Off
+ *      MACbIsIntDisable - Test if MAC interrupt disable
+ *      MACbyReadMultiAddr - Read Multicast Address Mask Pattern
+ *      MACvWriteMultiAddr - Write Multicast Address Mask Pattern
+ *      MACvSetMultiAddrByHash - Set Multicast Address Mask by Hash value
+ *      MACvResetMultiAddrByHash - Clear Multicast Address Mask by Hash value
+ *      MACvSetRxThreshold - Set Rx Threshold value
+ *      MACvGetRxThreshold - Get Rx Threshold value
+ *      MACvSetTxThreshold - Set Tx Threshold value
+ *      MACvGetTxThreshold - Get Tx Threshold value
+ *      MACvSetDmaLength - Set Dma Length value
+ *      MACvGetDmaLength - Get Dma Length value
+ *      MACvSetShortRetryLimit - Set 802.11 Short Retry limit
+ *      MACvGetShortRetryLimit - Get 802.11 Short Retry limit
+ *      MACvSetLongRetryLimit - Set 802.11 Long Retry limit
+ *      MACvGetLongRetryLimit - Get 802.11 Long Retry limit
+ *      MACvSetLoopbackMode - Set MAC Loopback Mode
+ *      MACbIsInLoopbackMode - Test if MAC in Loopback mode
+ *      MACvSetPacketFilter - Set MAC Address Filter
+ *      MACvSaveContext - Save Context of MAC Registers
+ *      MACvRestoreContext - Restore Context of MAC Registers
+ *      MACbCompareContext - Compare if values of MAC Registers same as Context
+ *      MACbSoftwareReset - Software Reset MAC
+ *      MACbSafeRxOff - Turn Off MAC Rx
+ *      MACbSafeTxOff - Turn Off MAC Tx
+ *      MACbSafeStop - Stop MAC function
+ *      MACbShutdown - Shut down MAC
+ *      MACvInitialize - Initialize MAC
+ *      MACvSetCurrRxDescAddr - Set Rx Descriptos Address
+ *      MACvSetCurrTx0DescAddr - Set Tx0 Descriptos Address
+ *      MACvSetCurrTx1DescAddr - Set Tx1 Descriptos Address
+ *      MACvTimer0MicroSDelay - Micro Second Delay Loop by MAC
+ *
+ * Revision History:
+ *      08-22-2003 Kyle Hsu     :  Porting MAC functions from sim53
+ *      09-03-2003 Bryan YC Fan :  Add MACvClearBusSusInd()& MACvEnableBusSusEn()
+ *      09-18-2003 Jerry Chen   :  Add MACvSetKeyEntry & MACvDisableKeyEntry
+ *
+ */
+
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+
+
+WORD TxRate_iwconfig;//2008-5-8 <add> by chester
+/*---------------------  Static Definitions -------------------------*/
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+static int          msglevel                =MSG_LEVEL_INFO;
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+/*
+ * Description:
+ *      Read All MAC Registers to buffer
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      pbyMacRegs  - buffer to read
+ *
+ * Return Value: none
+ *
+ */
+VOID MACvReadAllRegs (DWORD_PTR dwIoBase, PBYTE pbyMacRegs)
+{
+    int ii;
+
+    // read page0 register
+    for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE0; ii++) {
+        VNSvInPortB(dwIoBase + ii, pbyMacRegs);
+        pbyMacRegs++;
+    }
+
+    MACvSelectPage1(dwIoBase);
+
+    // read page1 register
+    for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE1; ii++) {
+        VNSvInPortB(dwIoBase + ii, pbyMacRegs);
+        pbyMacRegs++;
+    }
+
+    MACvSelectPage0(dwIoBase);
+
+}
+
+/*
+ * Description:
+ *      Test if all test bits on
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      byRegOfs    - Offset of MAC Register
+ *      byTestBits  - Test bits
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if all test bits On; otherwise FALSE
+ *
+ */
+BOOL MACbIsRegBitsOn (DWORD_PTR dwIoBase, BYTE byRegOfs, BYTE byTestBits)
+{
+    BYTE byData;
+
+    VNSvInPortB(dwIoBase + byRegOfs, &byData);
+    return BITbIsAllBitsOn(byData, byTestBits);
+}
+
+/*
+ * Description:
+ *      Test if all test bits off
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      byRegOfs    - Offset of MAC Register
+ *      byTestBits  - Test bits
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if all test bits Off; otherwise FALSE
+ *
+ */
+BOOL MACbIsRegBitsOff (DWORD_PTR dwIoBase, BYTE byRegOfs, BYTE byTestBits)
+{
+    BYTE byData;
+
+    VNSvInPortB(dwIoBase + byRegOfs, &byData);
+    return BITbIsAllBitsOff(byData, byTestBits);
+}
+
+/*
+ * Description:
+ *      Test if MAC interrupt disable
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if interrupt is disable; otherwise FALSE
+ *
+ */
+BOOL MACbIsIntDisable (DWORD_PTR dwIoBase)
+{
+    DWORD dwData;
+
+    VNSvInPortD(dwIoBase + MAC_REG_IMR, &dwData);
+    if (dwData != 0)
+        return FALSE;
+
+    return TRUE;
+}
+
+/*
+ * Description:
+ *      Read MAC Multicast Address Mask
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      uByteidx    - Index of Mask
+ *  Out:
+ *      none
+ *
+ * Return Value: Mask Value read
+ *
+ */
+BYTE MACbyReadMultiAddr (DWORD_PTR dwIoBase, UINT uByteIdx)
+{
+    BYTE byData;
+
+    MACvSelectPage1(dwIoBase);
+    VNSvInPortB(dwIoBase + MAC_REG_MAR0 + uByteIdx, &byData);
+    MACvSelectPage0(dwIoBase);
+    return byData;
+}
+
+/*
+ * Description:
+ *      Write MAC Multicast Address Mask
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      uByteidx    - Index of Mask
+ *      byData      - Mask Value to write
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+VOID MACvWriteMultiAddr (DWORD_PTR dwIoBase, UINT uByteIdx, BYTE byData)
+{
+    MACvSelectPage1(dwIoBase);
+    VNSvOutPortB(dwIoBase + MAC_REG_MAR0 + uByteIdx, byData);
+    MACvSelectPage0(dwIoBase);
+}
+
+/*
+ * Description:
+ *      Set this hash index into multicast address register bit
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      byHashIdx   - Hash index to set
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetMultiAddrByHash (DWORD_PTR dwIoBase, BYTE byHashIdx)
+{
+    UINT uByteIdx;
+    BYTE byBitMask;
+    BYTE byOrgValue;
+
+    // calculate byte position
+    uByteIdx = byHashIdx / 8;
+    ASSERT(uByteIdx < 8);
+    // calculate bit position
+    byBitMask = 1;
+    byBitMask <<= (byHashIdx % 8);
+    // turn on the bit
+    byOrgValue = MACbyReadMultiAddr(dwIoBase, uByteIdx);
+    MACvWriteMultiAddr(dwIoBase, uByteIdx, (BYTE)(byOrgValue | byBitMask));
+}
+
+/*
+ * Description:
+ *      Reset this hash index into multicast address register bit
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      byHashIdx   - Hash index to clear
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvResetMultiAddrByHash (DWORD_PTR dwIoBase, BYTE byHashIdx)
+{
+    UINT uByteIdx;
+    BYTE byBitMask;
+    BYTE byOrgValue;
+
+    // calculate byte position
+    uByteIdx = byHashIdx / 8;
+    ASSERT(uByteIdx < 8);
+    // calculate bit position
+    byBitMask = 1;
+    byBitMask <<= (byHashIdx % 8);
+    // turn off the bit
+    byOrgValue = MACbyReadMultiAddr(dwIoBase, uByteIdx);
+    MACvWriteMultiAddr(dwIoBase, uByteIdx, (BYTE)(byOrgValue & (~byBitMask)));
+}
+
+/*
+ * Description:
+ *      Set Rx Threshold
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      byThreshold - Threshold Value
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetRxThreshold (DWORD_PTR dwIoBase, BYTE byThreshold)
+{
+    BYTE byOrgValue;
+
+    ASSERT(byThreshold < 4);
+
+    // set FCR0
+    VNSvInPortB(dwIoBase + MAC_REG_FCR0, &byOrgValue);
+    byOrgValue = (byOrgValue & 0xCF) | (byThreshold << 4);
+    VNSvOutPortB(dwIoBase + MAC_REG_FCR0, byOrgValue);
+}
+
+/*
+ * Description:
+ *      Get Rx Threshold
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      pbyThreshold- Threshold Value Get
+ *
+ * Return Value: none
+ *
+ */
+void MACvGetRxThreshold (DWORD_PTR dwIoBase, PBYTE pbyThreshold)
+{
+    // get FCR0
+    VNSvInPortB(dwIoBase + MAC_REG_FCR0, pbyThreshold);
+    *pbyThreshold = (*pbyThreshold >> 4) & 0x03;
+}
+
+/*
+ * Description:
+ *      Set Tx Threshold
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      byThreshold - Threshold Value
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetTxThreshold (DWORD_PTR dwIoBase, BYTE byThreshold)
+{
+    BYTE byOrgValue;
+
+    ASSERT(byThreshold < 4);
+
+    // set FCR0
+    VNSvInPortB(dwIoBase + MAC_REG_FCR0, &byOrgValue);
+    byOrgValue = (byOrgValue & 0xF3) | (byThreshold << 2);
+    VNSvOutPortB(dwIoBase + MAC_REG_FCR0, byOrgValue);
+}
+
+/*
+ * Description:
+ *      Get Tx Threshold
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      pbyThreshold- Threshold Value Get
+ *
+ * Return Value: none
+ *
+ */
+void MACvGetTxThreshold (DWORD_PTR dwIoBase, PBYTE pbyThreshold)
+{
+    // get FCR0
+    VNSvInPortB(dwIoBase + MAC_REG_FCR0, pbyThreshold);
+    *pbyThreshold = (*pbyThreshold >> 2) & 0x03;
+}
+
+/*
+ * Description:
+ *      Set Dma Length
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      byDmaLength - Dma Length Value
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetDmaLength (DWORD_PTR dwIoBase, BYTE byDmaLength)
+{
+    BYTE byOrgValue;
+
+    ASSERT(byDmaLength < 4);
+
+    // set FCR0
+    VNSvInPortB(dwIoBase + MAC_REG_FCR0, &byOrgValue);
+    byOrgValue = (byOrgValue & 0xFC) | byDmaLength;
+    VNSvOutPortB(dwIoBase + MAC_REG_FCR0, byOrgValue);
+}
+
+/*
+ * Description:
+ *      Get Dma Length
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      pbyDmaLength- Dma Length Value Get
+ *
+ * Return Value: none
+ *
+ */
+void MACvGetDmaLength (DWORD_PTR dwIoBase, PBYTE pbyDmaLength)
+{
+    // get FCR0
+    VNSvInPortB(dwIoBase + MAC_REG_FCR0, pbyDmaLength);
+    *pbyDmaLength &= 0x03;
+}
+
+/*
+ * Description:
+ *      Set 802.11 Short Retry Limit
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      byRetryLimit- Retry Limit
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetShortRetryLimit (DWORD_PTR dwIoBase, BYTE byRetryLimit)
+{
+    // set SRT
+    VNSvOutPortB(dwIoBase + MAC_REG_SRT, byRetryLimit);
+}
+
+/*
+ * Description:
+ *      Get 802.11 Short Retry Limit
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *  Out:
+ *      pbyRetryLimit   - Retry Limit Get
+ *
+ * Return Value: none
+ *
+ */
+void MACvGetShortRetryLimit (DWORD_PTR dwIoBase, PBYTE pbyRetryLimit)
+{
+    // get SRT
+    VNSvInPortB(dwIoBase + MAC_REG_SRT, pbyRetryLimit);
+}
+
+/*
+ * Description:
+ *      Set 802.11 Long Retry Limit
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      byRetryLimit- Retry Limit
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetLongRetryLimit (DWORD_PTR dwIoBase, BYTE byRetryLimit)
+{
+    // set LRT
+    VNSvOutPortB(dwIoBase + MAC_REG_LRT, byRetryLimit);
+}
+
+/*
+ * Description:
+ *      Get 802.11 Long Retry Limit
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *  Out:
+ *      pbyRetryLimit   - Retry Limit Get
+ *
+ * Return Value: none
+ *
+ */
+void MACvGetLongRetryLimit (DWORD_PTR dwIoBase, PBYTE pbyRetryLimit)
+{
+    // get LRT
+    VNSvInPortB(dwIoBase + MAC_REG_LRT, pbyRetryLimit);
+}
+
+/*
+ * Description:
+ *      Set MAC Loopback mode
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *      byLoopbackMode  - Loopback Mode
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetLoopbackMode (DWORD_PTR dwIoBase, BYTE byLoopbackMode)
+{
+    BYTE byOrgValue;
+
+    ASSERT(byLoopbackMode < 3);
+    byLoopbackMode <<= 6;
+    // set TCR
+    VNSvInPortB(dwIoBase + MAC_REG_TEST, &byOrgValue);
+    byOrgValue = byOrgValue & 0x3F;
+    byOrgValue = byOrgValue | byLoopbackMode;
+    VNSvOutPortB(dwIoBase + MAC_REG_TEST, byOrgValue);
+}
+
+/*
+ * Description:
+ *      Test if MAC in Loopback mode
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if in Loopback mode; otherwise FALSE
+ *
+ */
+BOOL MACbIsInLoopbackMode (DWORD_PTR dwIoBase)
+{
+    BYTE byOrgValue;
+
+    VNSvInPortB(dwIoBase + MAC_REG_TEST, &byOrgValue);
+    if (BITbIsAnyBitsOn(byOrgValue, (TEST_LBINT | TEST_LBEXT)))
+        return TRUE;
+    return FALSE;
+}
+
+/*
+ * Description:
+ *      Set MAC Address filter
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *      wFilterType     - Filter Type
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetPacketFilter (DWORD_PTR dwIoBase, WORD wFilterType)
+{
+    BYTE    byOldRCR;
+    BYTE    byNewRCR = 0;
+
+    // if only in DIRECTED mode, multicast-address will set to zero,
+    // but if other mode exist (e.g. PROMISCUOUS), multicast-address
+    // will be open
+    if (BITbIsBitOn(wFilterType, PKT_TYPE_DIRECTED)) {
+        // set multicast address to accept none
+        MACvSelectPage1(dwIoBase);
+        VNSvOutPortD(dwIoBase + MAC_REG_MAR0, 0L);
+        VNSvOutPortD(dwIoBase + MAC_REG_MAR0 + sizeof(DWORD), 0L);
+        MACvSelectPage0(dwIoBase);
+    }
+
+    if (BITbIsAnyBitsOn(wFilterType, PKT_TYPE_PROMISCUOUS | PKT_TYPE_ALL_MULTICAST)) {
+        // set multicast address to accept all
+        MACvSelectPage1(dwIoBase);
+        VNSvOutPortD(dwIoBase + MAC_REG_MAR0, 0xFFFFFFFFL);
+        VNSvOutPortD(dwIoBase + MAC_REG_MAR0 + sizeof(DWORD), 0xFFFFFFFFL);
+        MACvSelectPage0(dwIoBase);
+    }
+
+    if (BITbIsBitOn(wFilterType, PKT_TYPE_PROMISCUOUS)) {
+
+        byNewRCR |= (RCR_RXALLTYPE | RCR_UNICAST | RCR_MULTICAST | RCR_BROADCAST);
+
+        byNewRCR &= ~RCR_BSSID;
+    }
+
+    if (BITbIsAnyBitsOn(wFilterType, (PKT_TYPE_ALL_MULTICAST | PKT_TYPE_MULTICAST)))
+        byNewRCR |= RCR_MULTICAST;
+
+    if (BITbIsBitOn(wFilterType, PKT_TYPE_BROADCAST))
+        byNewRCR |= RCR_BROADCAST;
+
+    if (BITbIsBitOn(wFilterType, PKT_TYPE_ERROR_CRC))
+        byNewRCR |= RCR_ERRCRC;
+
+    VNSvInPortB(dwIoBase + MAC_REG_RCR,  &byOldRCR);
+    if (byNewRCR != byOldRCR) {
+        // Modify the Receive Command Register
+        VNSvOutPortB(dwIoBase + MAC_REG_RCR, byNewRCR);
+    }
+}
+
+/*
+ * Description:
+ *      Save MAC registers to context buffer
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      pbyCxtBuf   - Context buffer
+ *
+ * Return Value: none
+ *
+ */
+void MACvSaveContext (DWORD_PTR dwIoBase, PBYTE pbyCxtBuf)
+{
+    int         ii;
+
+    // read page0 register
+    for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE0; ii++) {
+        VNSvInPortB((dwIoBase + ii), (pbyCxtBuf + ii));
+    }
+
+    MACvSelectPage1(dwIoBase);
+
+    // read page1 register
+    for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE1; ii++) {
+        VNSvInPortB((dwIoBase + ii), (pbyCxtBuf + MAC_MAX_CONTEXT_SIZE_PAGE0 + ii));
+    }
+
+    MACvSelectPage0(dwIoBase);
+}
+
+/*
+ * Description:
+ *      Restore MAC registers from context buffer
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      pbyCxtBuf   - Context buffer
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+VOID MACvRestoreContext (DWORD_PTR dwIoBase, PBYTE pbyCxtBuf)
+{
+    int         ii;
+
+    MACvSelectPage1(dwIoBase);
+    // restore page1
+    for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE1; ii++) {
+        VNSvOutPortB((dwIoBase + ii), *(pbyCxtBuf + MAC_MAX_CONTEXT_SIZE_PAGE0 + ii));
+    }
+    MACvSelectPage0(dwIoBase);
+
+    // restore RCR,TCR,IMR...
+    for (ii = MAC_REG_RCR; ii < MAC_REG_ISR; ii++) {
+        VNSvOutPortB(dwIoBase + ii, *(pbyCxtBuf + ii));
+    }
+    // restore MAC Config.
+    for (ii = MAC_REG_LRT; ii < MAC_REG_PAGE1SEL; ii++) {
+        VNSvOutPortB(dwIoBase + ii, *(pbyCxtBuf + ii));
+    }
+    VNSvOutPortB(dwIoBase + MAC_REG_CFG, *(pbyCxtBuf + MAC_REG_CFG));
+
+    // restore PS Config.
+    for (ii = MAC_REG_PSCFG; ii < MAC_REG_BBREGCTL; ii++) {
+        VNSvOutPortB(dwIoBase + ii, *(pbyCxtBuf + ii));
+    }
+
+    // restore CURR_RX_DESC_ADDR, CURR_TX_DESC_ADDR
+    VNSvOutPortD(dwIoBase + MAC_REG_TXDMAPTR0, *(PDWORD)(pbyCxtBuf + MAC_REG_TXDMAPTR0));
+    VNSvOutPortD(dwIoBase + MAC_REG_AC0DMAPTR, *(PDWORD)(pbyCxtBuf + MAC_REG_AC0DMAPTR));
+    VNSvOutPortD(dwIoBase + MAC_REG_BCNDMAPTR, *(PDWORD)(pbyCxtBuf + MAC_REG_BCNDMAPTR));
+
+
+    VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR0, *(PDWORD)(pbyCxtBuf + MAC_REG_RXDMAPTR0));
+
+    VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR1, *(PDWORD)(pbyCxtBuf + MAC_REG_RXDMAPTR1));
+
+}
+
+/*
+ * Description:
+ *      Compare if MAC registers same as context buffer
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      pbyCxtBuf   - Context buffer
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if all values are the same; otherwise FALSE
+ *
+ */
+BOOL MACbCompareContext (DWORD_PTR dwIoBase, PBYTE pbyCxtBuf)
+{
+    DWORD       dwData;
+
+    // compare MAC context to determine if this is a power lost init,
+    // return TRUE for power remaining init, return FALSE for power lost init
+
+    // compare CURR_RX_DESC_ADDR, CURR_TX_DESC_ADDR
+    VNSvInPortD(dwIoBase + MAC_REG_TXDMAPTR0, &dwData);
+    if (dwData != *(PDWORD)(pbyCxtBuf + MAC_REG_TXDMAPTR0)) {
+        return FALSE;
+    }
+
+    VNSvInPortD(dwIoBase + MAC_REG_AC0DMAPTR, &dwData);
+    if (dwData != *(PDWORD)(pbyCxtBuf + MAC_REG_AC0DMAPTR)) {
+        return FALSE;
+    }
+
+    VNSvInPortD(dwIoBase + MAC_REG_RXDMAPTR0, &dwData);
+    if (dwData != *(PDWORD)(pbyCxtBuf + MAC_REG_RXDMAPTR0)) {
+        return FALSE;
+    }
+
+    VNSvInPortD(dwIoBase + MAC_REG_RXDMAPTR1, &dwData);
+    if (dwData != *(PDWORD)(pbyCxtBuf + MAC_REG_RXDMAPTR1)) {
+        return FALSE;
+    }
+
+
+    return TRUE;
+}
+
+/*
+ * Description:
+ *      Software Reset MAC
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if Reset Success; otherwise FALSE
+ *
+ */
+BOOL MACbSoftwareReset (DWORD_PTR dwIoBase)
+{
+    BYTE    byData;
+    WORD    ww;
+
+    // turn on HOSTCR_SOFTRST, just write 0x01 to reset
+    //MACvRegBitsOn(dwIoBase, MAC_REG_HOSTCR, HOSTCR_SOFTRST);
+    VNSvOutPortB(dwIoBase+ MAC_REG_HOSTCR, 0x01);
+
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_HOSTCR, &byData);
+        if (BITbIsBitOff(byData, HOSTCR_SOFTRST))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT)
+        return FALSE;
+    return TRUE;
+
+}
+
+/*
+ * Description:
+ *      save some important register's value, then do reset, then restore register's value
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; otherwise FALSE
+ *
+ */
+BOOL MACbSafeSoftwareReset (DWORD_PTR dwIoBase)
+{
+    BYTE    abyTmpRegData[MAC_MAX_CONTEXT_SIZE_PAGE0+MAC_MAX_CONTEXT_SIZE_PAGE1];
+    BOOL    bRetVal;
+
+    // PATCH....
+    // save some important register's value, then do
+    // reset, then restore register's value
+
+    // save MAC context
+    MACvSaveContext(dwIoBase, abyTmpRegData);
+    // do reset
+    bRetVal = MACbSoftwareReset(dwIoBase);
+    //BBvSoftwareReset(pDevice->PortOffset);
+    // restore MAC context, except CR0
+    MACvRestoreContext(dwIoBase, abyTmpRegData);
+
+    return bRetVal;
+}
+
+/*
+ * Description:
+ *      Trun Off MAC Rx
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; otherwise FALSE
+ *
+ */
+BOOL MACbSafeRxOff (DWORD_PTR dwIoBase)
+{
+    WORD    ww;
+    DWORD   dwData;
+    BYTE    byData;
+
+    // turn off wow temp for turn off Rx safely
+
+    // Clear RX DMA0,1
+    VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL0, DMACTL_CLRRUN);
+    VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL1, DMACTL_CLRRUN);
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortD(dwIoBase + MAC_REG_RXDMACTL0, &dwData);
+        if (BITbIsAllBitsOff(dwData, DMACTL_RUN))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x10);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x10)\n");
+        return(FALSE);
+    }
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortD(dwIoBase + MAC_REG_RXDMACTL1, &dwData);
+        if (BITbIsAllBitsOff(dwData, DMACTL_RUN))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x11);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x11)\n");
+        return(FALSE);
+    }
+
+    // try to safe shutdown RX
+    MACvRegBitsOff(dwIoBase, MAC_REG_HOSTCR, HOSTCR_RXON);
+    // W_MAX_TIMEOUT is the timeout period
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_HOSTCR, &byData);
+        if (BITbIsAllBitsOff(byData, HOSTCR_RXONST))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x12);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x12)\n");
+        return(FALSE);
+    }
+    return TRUE;
+}
+
+/*
+ * Description:
+ *      Trun Off MAC Tx
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; otherwise FALSE
+ *
+ */
+BOOL MACbSafeTxOff (DWORD_PTR dwIoBase)
+{
+    WORD    ww;
+    DWORD   dwData;
+    BYTE    byData;
+
+    // Clear TX DMA
+    //Tx0
+    VNSvOutPortD(dwIoBase + MAC_REG_TXDMACTL0, DMACTL_CLRRUN);
+    //AC0
+    VNSvOutPortD(dwIoBase + MAC_REG_AC0DMACTL, DMACTL_CLRRUN);
+
+
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortD(dwIoBase + MAC_REG_TXDMACTL0, &dwData);
+        if (BITbIsAllBitsOff(dwData, DMACTL_RUN))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x20);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x20)\n");
+        return(FALSE);
+    }
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortD(dwIoBase + MAC_REG_AC0DMACTL, &dwData);
+        if (BITbIsAllBitsOff(dwData, DMACTL_RUN))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x21);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x21)\n");
+        return(FALSE);
+    }
+
+    // try to safe shutdown TX
+    MACvRegBitsOff(dwIoBase, MAC_REG_HOSTCR, HOSTCR_TXON);
+
+    // W_MAX_TIMEOUT is the timeout period
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_HOSTCR, &byData);
+        if (BITbIsAllBitsOff(byData, HOSTCR_TXONST))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x24);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x24)\n");
+        return(FALSE);
+    }
+    return TRUE;
+}
+
+/*
+ * Description:
+ *      Stop MAC function
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; otherwise FALSE
+ *
+ */
+BOOL MACbSafeStop (DWORD_PTR dwIoBase)
+{
+    MACvRegBitsOff(dwIoBase, MAC_REG_TCR, TCR_AUTOBCNTX);
+
+    if (MACbSafeRxOff(dwIoBase) == FALSE) {
+        DBG_PORT80(0xA1);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" MACbSafeRxOff == FALSE)\n");
+        MACbSafeSoftwareReset(dwIoBase);
+        return FALSE;
+    }
+    if (MACbSafeTxOff(dwIoBase) == FALSE) {
+        DBG_PORT80(0xA2);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" MACbSafeTxOff == FALSE)\n");
+        MACbSafeSoftwareReset(dwIoBase);
+        return FALSE;
+    }
+
+    MACvRegBitsOff(dwIoBase, MAC_REG_HOSTCR, HOSTCR_MACEN);
+
+    return TRUE;
+}
+
+/*
+ * Description:
+ *      Shut Down MAC
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; otherwise FALSE
+ *
+ */
+BOOL MACbShutdown (DWORD_PTR dwIoBase)
+{
+    // disable MAC IMR
+    MACvIntDisable(dwIoBase);
+    MACvSetLoopbackMode(dwIoBase, MAC_LB_INTERNAL);
+    // stop the adapter
+    if (!MACbSafeStop(dwIoBase)) {
+        MACvSetLoopbackMode(dwIoBase, MAC_LB_NONE);
+        return FALSE;
+    }
+    MACvSetLoopbackMode(dwIoBase, MAC_LB_NONE);
+    return TRUE;
+}
+
+/*
+ * Description:
+ *      Initialize MAC
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvInitialize (DWORD_PTR dwIoBase)
+{
+    // clear sticky bits
+    MACvClearStckDS(dwIoBase);
+    // disable force PME-enable
+    VNSvOutPortB(dwIoBase + MAC_REG_PMC1, PME_OVR);
+    // only 3253 A
+    /*
+    MACvPwrEvntDisable(dwIoBase);
+    // clear power status
+    VNSvOutPortW(dwIoBase + MAC_REG_WAKEUPSR0, 0x0F0F);
+    */
+
+    // do reset
+    MACbSoftwareReset(dwIoBase);
+
+    // issue AUTOLD in EECSR to reload eeprom
+    //MACvRegBitsOn(dwIoBase, MAC_REG_I2MCSR, I2MCSR_AUTOLD);
+    // wait until EEPROM loading complete
+    //while (TRUE) {
+    //    U8 u8Data;
+    //    VNSvInPortB(dwIoBase + MAC_REG_I2MCSR, &u8Data);
+    //    if (BITbIsBitOff(u8Data, I2MCSR_AUTOLD))
+    //        break;
+    //}
+
+    // reset TSF counter
+    VNSvOutPortB(dwIoBase + MAC_REG_TFTCTL, TFTCTL_TSFCNTRST);
+    // enable TSF counter
+    VNSvOutPortB(dwIoBase + MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
+
+
+    // set packet filter
+    // receive directed and broadcast address
+
+    MACvSetPacketFilter(dwIoBase, PKT_TYPE_DIRECTED | PKT_TYPE_BROADCAST);
+
+}
+
+/*
+ * Description:
+ *      Set the chip with current rx descriptor address
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *      dwCurrDescAddr  - Descriptor Address
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetCurrRx0DescAddr (DWORD_PTR dwIoBase, DWORD dwCurrDescAddr)
+{
+WORD    ww;
+BYTE    byData;
+BYTE    byOrgDMACtl;
+
+    VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL0, &byOrgDMACtl);
+    if (BITbIsAllBitsOn(byOrgDMACtl, DMACTL_RUN)) {
+        VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL0+2, DMACTL_RUN);
+    }
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL0, &byData);
+        if (BITbIsAllBitsOff(byData, DMACTL_RUN))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x13);
+    }
+    VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR0, dwCurrDescAddr);
+    if (BITbIsAllBitsOn(byOrgDMACtl, DMACTL_RUN)) {
+        VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL0, DMACTL_RUN);
+    }
+}
+
+/*
+ * Description:
+ *      Set the chip with current rx descriptor address
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *      dwCurrDescAddr  - Descriptor Address
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetCurrRx1DescAddr (DWORD_PTR dwIoBase, DWORD dwCurrDescAddr)
+{
+WORD    ww;
+BYTE    byData;
+BYTE    byOrgDMACtl;
+
+    VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL1, &byOrgDMACtl);
+    if (BITbIsAllBitsOn(byOrgDMACtl, DMACTL_RUN)) {
+        VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL1+2, DMACTL_RUN);
+    }
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL1, &byData);
+        if (BITbIsAllBitsOff(byData, DMACTL_RUN))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x14);
+    }
+    VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR1, dwCurrDescAddr);
+    if (BITbIsAllBitsOn(byOrgDMACtl, DMACTL_RUN)) {
+        VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL1, DMACTL_RUN);
+    }
+}
+
+/*
+ * Description:
+ *      Set the chip with current tx0 descriptor address
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *      dwCurrDescAddr  - Descriptor Address
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetCurrTx0DescAddrEx (DWORD_PTR dwIoBase, DWORD dwCurrDescAddr)
+{
+WORD    ww;
+BYTE    byData;
+BYTE    byOrgDMACtl;
+
+    VNSvInPortB(dwIoBase + MAC_REG_TXDMACTL0, &byOrgDMACtl);
+    if (BITbIsAllBitsOn(byOrgDMACtl, DMACTL_RUN)) {
+        VNSvOutPortB(dwIoBase + MAC_REG_TXDMACTL0+2, DMACTL_RUN);
+    }
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_TXDMACTL0, &byData);
+        if (BITbIsAllBitsOff(byData, DMACTL_RUN))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x25);
+    }
+    VNSvOutPortD(dwIoBase + MAC_REG_TXDMAPTR0, dwCurrDescAddr);
+    if (BITbIsAllBitsOn(byOrgDMACtl, DMACTL_RUN)) {
+        VNSvOutPortB(dwIoBase + MAC_REG_TXDMACTL0, DMACTL_RUN);
+    }
+}
+
+/*
+ * Description:
+ *      Set the chip with current AC0 descriptor address
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *      dwCurrDescAddr  - Descriptor Address
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+ //TxDMA1 = AC0DMA
+void MACvSetCurrAC0DescAddrEx (DWORD_PTR dwIoBase, DWORD dwCurrDescAddr)
+{
+WORD    ww;
+BYTE    byData;
+BYTE    byOrgDMACtl;
+
+    VNSvInPortB(dwIoBase + MAC_REG_AC0DMACTL, &byOrgDMACtl);
+    if (BITbIsAllBitsOn(byOrgDMACtl, DMACTL_RUN)) {
+        VNSvOutPortB(dwIoBase + MAC_REG_AC0DMACTL+2, DMACTL_RUN);
+    }
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_AC0DMACTL, &byData);
+        if (BITbIsAllBitsOff(byData, DMACTL_RUN))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x26);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x26)\n");
+    }
+    VNSvOutPortD(dwIoBase + MAC_REG_AC0DMAPTR, dwCurrDescAddr);
+    if (BITbIsAllBitsOn(byOrgDMACtl, DMACTL_RUN)) {
+        VNSvOutPortB(dwIoBase + MAC_REG_AC0DMACTL, DMACTL_RUN);
+    }
+}
+
+
+
+void MACvSetCurrTXDescAddr (int iTxType, DWORD_PTR dwIoBase, DWORD dwCurrDescAddr)
+{
+    if(iTxType == TYPE_AC0DMA){
+        MACvSetCurrAC0DescAddrEx(dwIoBase, dwCurrDescAddr);
+    }else if(iTxType == TYPE_TXDMA0){
+        MACvSetCurrTx0DescAddrEx(dwIoBase, dwCurrDescAddr);
+    }
+}
+
+/*
+ * Description:
+ *      Micro Second Delay via MAC
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      uDelay      - Delay time (timer resolution is 4 us)
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+VOID MACvTimer0MicroSDelay (DWORD_PTR dwIoBase, UINT uDelay)
+{
+BYTE byValue;
+UINT uu,ii;
+
+    VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
+    VNSvOutPortD(dwIoBase + MAC_REG_TMDATA0, uDelay);
+    VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, (TMCTL_TMD | TMCTL_TE));
+    for(ii=0;ii<66;ii++) {  // assume max PCI clock is 66Mhz
+        for (uu = 0; uu < uDelay; uu++) {
+            VNSvInPortB(dwIoBase + MAC_REG_TMCTL0, &byValue);
+            if ((byValue == 0) ||
+                (BITbIsAllBitsOn(byValue, TMCTL_TSUSP))) {
+                VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
+                return;
+            }
+        }
+    }
+    VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
+
+}
+
+/*
+ * Description:
+ *      Micro Second One shot timer via MAC
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      uDelay      - Delay time
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvOneShotTimer0MicroSec (DWORD_PTR dwIoBase, UINT uDelayTime)
+{
+    VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
+    VNSvOutPortD(dwIoBase + MAC_REG_TMDATA0, uDelayTime);
+    VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, (TMCTL_TMD | TMCTL_TE));
+}
+
+/*
+ * Description:
+ *      Micro Second One shot timer via MAC
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - Base Address for MAC
+ *      uDelay      - Delay time
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvOneShotTimer1MicroSec (DWORD_PTR dwIoBase, UINT uDelayTime)
+{
+    VNSvOutPortB(dwIoBase + MAC_REG_TMCTL1, 0);
+    VNSvOutPortD(dwIoBase + MAC_REG_TMDATA1, uDelayTime);
+    VNSvOutPortB(dwIoBase + MAC_REG_TMCTL1, (TMCTL_TMD | TMCTL_TE));
+}
+
+
+void MACvSetMISCFifo (DWORD_PTR dwIoBase, WORD wOffset, DWORD dwData)
+{
+    if (wOffset > 273)
+        return;
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
+    VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+}
+
+
+BOOL MACbTxDMAOff (DWORD_PTR dwIoBase, UINT idx)
+{
+BYTE byData;
+UINT ww = 0;
+
+    if (idx == TYPE_TXDMA0) {
+        VNSvOutPortB(dwIoBase + MAC_REG_TXDMACTL0+2, DMACTL_RUN);
+        for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+            VNSvInPortB(dwIoBase + MAC_REG_TXDMACTL0, &byData);
+            if (BITbIsAllBitsOff(byData, DMACTL_RUN))
+                break;
+        }
+    } else if (idx == TYPE_AC0DMA) {
+        VNSvOutPortB(dwIoBase + MAC_REG_AC0DMACTL+2, DMACTL_RUN);
+        for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+            VNSvInPortB(dwIoBase + MAC_REG_AC0DMACTL, &byData);
+            if (BITbIsAllBitsOff(byData, DMACTL_RUN))
+                break;
+        }
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x29);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x29)\n");
+        return FALSE;
+    }
+    return TRUE;
+}
+
+void MACvClearBusSusInd (DWORD_PTR dwIoBase)
+{
+    DWORD dwOrgValue;
+    UINT ww;
+    // check if BcnSusInd enabled
+    VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue);
+    if(BITbIsBitOff(dwOrgValue, EnCFG_BcnSusInd))
+        return;
+    //Set BcnSusClr
+    dwOrgValue = dwOrgValue | EnCFG_BcnSusClr;
+    VNSvOutPortD(dwIoBase + MAC_REG_ENCFG, dwOrgValue);
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue);
+        if(BITbIsBitOff(dwOrgValue, EnCFG_BcnSusInd))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x33);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x33)\n");
+    }
+}
+
+void MACvEnableBusSusEn (DWORD_PTR dwIoBase)
+{
+    BYTE  byOrgValue;
+    DWORD dwOrgValue;
+    UINT ww;
+    // check if BcnSusInd enabled
+    VNSvInPortB(dwIoBase + MAC_REG_CFG , &byOrgValue);
+
+    //Set BcnSusEn
+    byOrgValue = byOrgValue | CFG_BCNSUSEN;
+    VNSvOutPortB(dwIoBase + MAC_REG_ENCFG, byOrgValue);
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue);
+        if(BITbIsBitOn(dwOrgValue, EnCFG_BcnSusInd))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x34);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x34)\n");
+    }
+}
+
+BOOL MACbFlushSYNCFifo (DWORD_PTR dwIoBase)
+{
+    BYTE  byOrgValue;
+    UINT ww;
+    // Read MACCR
+    VNSvInPortB(dwIoBase + MAC_REG_MACCR , &byOrgValue);
+
+    // Set SYNCFLUSH
+    byOrgValue = byOrgValue | MACCR_SYNCFLUSH;
+    VNSvOutPortB(dwIoBase + MAC_REG_MACCR, byOrgValue);
+
+    // Check if SyncFlushOK
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_MACCR , &byOrgValue);
+        if(BITbIsBitOn(byOrgValue, MACCR_SYNCFLUSHOK))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x35);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x33)\n");
+    }
+    return TRUE;
+}
+
+BOOL MACbPSWakeup (DWORD_PTR dwIoBase)
+{
+    BYTE  byOrgValue;
+    UINT ww;
+    // Read PSCTL
+    if (MACbIsRegBitsOff(dwIoBase, MAC_REG_PSCTL, PSCTL_PS)) {
+        return TRUE;
+    }
+    // Disable PS
+    MACvRegBitsOff(dwIoBase, MAC_REG_PSCTL, PSCTL_PSEN);
+
+    // Check if SyncFlushOK
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortB(dwIoBase + MAC_REG_PSCTL , &byOrgValue);
+        if(BITbIsBitOn(byOrgValue, PSCTL_WAKEDONE))
+            break;
+    }
+    if (ww == W_MAX_TIMEOUT) {
+        DBG_PORT80(0x36);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x33)\n");
+        return FALSE;
+    }
+    return TRUE;
+}
+
+/*
+ * Description:
+ *      Set the Key by MISCFIFO
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+
+void MACvSetKeyEntry (DWORD_PTR dwIoBase, WORD wKeyCtl, UINT uEntryIdx, UINT uKeyIdx, PBYTE pbyAddr, PDWORD pdwKey, BYTE byLocalID)
+{
+WORD    wOffset;
+DWORD   dwData;
+int     ii;
+
+    if (byLocalID <= 1)
+        return;
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetKeyEntry\n");
+    wOffset = MISCFIFO_KEYETRY0;
+    wOffset += (uEntryIdx * MISCFIFO_KEYENTRYSIZE);
+
+    dwData = 0;
+    dwData |= wKeyCtl;
+    dwData <<= 16;
+    dwData |= MAKEWORD(*(pbyAddr+4), *(pbyAddr+5));
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"1. wOffset: %d, Data: %lX, KeyCtl:%X\n", wOffset, dwData, wKeyCtl);
+
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
+    VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+    wOffset++;
+
+    dwData = 0;
+    dwData |= *(pbyAddr+3);
+    dwData <<= 8;
+    dwData |= *(pbyAddr+2);
+    dwData <<= 8;
+    dwData |= *(pbyAddr+1);
+    dwData <<= 8;
+    dwData |= *(pbyAddr+0);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"2. wOffset: %d, Data: %lX\n", wOffset, dwData);
+
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
+    VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+    wOffset++;
+
+    wOffset += (uKeyIdx * 4);
+    for (ii=0;ii<4;ii++) {
+        // alway push 128 bits
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"3.(%d) wOffset: %d, Data: %lX\n", ii, wOffset+ii, *pdwKey);
+        VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+ii);
+        VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, *pdwKey++);
+        VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+    }
+}
+
+
+
+/*
+ * Description:
+ *      Disable the Key Entry by MISCFIFO
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvDisableKeyEntry (DWORD_PTR dwIoBase, UINT uEntryIdx)
+{
+WORD    wOffset;
+
+    wOffset = MISCFIFO_KEYETRY0;
+    wOffset += (uEntryIdx * MISCFIFO_KEYENTRYSIZE);
+
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
+    VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, 0);
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+}
+
+
+/*
+ * Description:
+ *      Set the default Key (KeyEntry[10]) by MISCFIFO
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+
+void MACvSetDefaultKeyEntry (DWORD_PTR dwIoBase, UINT uKeyLen, UINT uKeyIdx, PDWORD pdwKey, BYTE byLocalID)
+{
+WORD    wOffset;
+DWORD   dwData;
+int     ii;
+
+    if (byLocalID <= 1)
+        return;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetDefaultKeyEntry\n");
+    wOffset = MISCFIFO_KEYETRY0;
+    wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
+
+    wOffset++;
+    wOffset++;
+    wOffset += (uKeyIdx * 4);
+    // alway push 128 bits
+    for (ii=0; ii<3; ii++) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"(%d) wOffset: %d, Data: %lX\n", ii, wOffset+ii, *pdwKey);
+        VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+ii);
+        VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, *pdwKey++);
+        VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+    }
+    dwData = *pdwKey;
+    if (uKeyLen == WLAN_WEP104_KEYLEN) {
+        dwData |= 0x80000000;
+    }
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+3);
+    VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"End. wOffset: %d, Data: %lX\n", wOffset+3, dwData);
+
+}
+
+
+/*
+ * Description:
+ *      Enable default Key (KeyEntry[10]) by MISCFIFO
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+/*
+void MACvEnableDefaultKey (DWORD_PTR dwIoBase, BYTE byLocalID)
+{
+WORD    wOffset;
+DWORD   dwData;
+
+
+    if (byLocalID <= 1)
+        return;
+
+    wOffset = MISCFIFO_KEYETRY0;
+    wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
+
+    dwData = 0xC0440000;
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
+    VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvEnableDefaultKey: wOffset: %d, Data: %lX\n", wOffset, dwData);
+
+}
+*/
+
+/*
+ * Description:
+ *      Disable default Key (KeyEntry[10]) by MISCFIFO
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvDisableDefaultKey (DWORD_PTR dwIoBase)
+{
+WORD    wOffset;
+DWORD   dwData;
+
+
+    wOffset = MISCFIFO_KEYETRY0;
+    wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
+
+    dwData = 0x0;
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
+    VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvDisableDefaultKey: wOffset: %d, Data: %lX\n", wOffset, dwData);
+}
+
+/*
+ * Description:
+ *      Set the default TKIP Group Key (KeyEntry[10]) by MISCFIFO
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void MACvSetDefaultTKIPKeyEntry (DWORD_PTR dwIoBase, UINT uKeyLen, UINT uKeyIdx, PDWORD pdwKey, BYTE byLocalID)
+{
+WORD    wOffset;
+DWORD   dwData;
+int     ii;
+
+    if (byLocalID <= 1)
+        return;
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetDefaultTKIPKeyEntry\n");
+    wOffset = MISCFIFO_KEYETRY0;
+    // Kyle test : change offset from 10 -> 0
+    wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
+
+    dwData = 0xC0660000;
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
+    VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+    wOffset++;
+
+    dwData = 0;
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
+    VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+    wOffset++;
+
+    wOffset += (uKeyIdx * 4);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"1. wOffset: %d, Data: %lX, idx:%d\n", wOffset, *pdwKey, uKeyIdx);
+    // alway push 128 bits
+    for (ii=0; ii<4; ii++) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"2.(%d) wOffset: %d, Data: %lX\n", ii, wOffset+ii, *pdwKey);
+        VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+ii);
+        VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, *pdwKey++);
+        VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+    }
+
+}
+
+
+
+/*
+ * Description:
+ *      Set the Key Control by MISCFIFO
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - Base Address for MAC
+ *
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+
+void MACvSetDefaultKeyCtl (DWORD_PTR dwIoBase, WORD wKeyCtl, UINT uEntryIdx, BYTE byLocalID)
+{
+WORD    wOffset;
+DWORD   dwData;
+
+    if (byLocalID <= 1)
+        return;
+
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetKeyEntry\n");
+    wOffset = MISCFIFO_KEYETRY0;
+    wOffset += (uEntryIdx * MISCFIFO_KEYENTRYSIZE);
+
+    dwData = 0;
+    dwData |= wKeyCtl;
+    dwData <<= 16;
+    dwData |= 0xffff;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"1. wOffset: %d, Data: %lX, KeyCtl:%X\n", wOffset, dwData, wKeyCtl);
+
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
+    VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
+
+}
+
diff --git a/drivers/staging/vt6655/mac.h b/drivers/staging/vt6655/mac.h
new file mode 100644
index 0000000..edb7096
--- /dev/null
+++ b/drivers/staging/vt6655/mac.h
@@ -0,0 +1,1166 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: mac.h
+ *
+ * Purpose: MAC routines
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ * Revision History:
+ *      07-01-2003 Bryan YC Fan:  Re-write codes to support VT3253 spec.
+ *      08-25-2003 Kyle Hsu:      Porting MAC functions from sim53.
+ *      09-03-2003 Bryan YC Fan:  Add MACvDisableProtectMD & MACvEnableProtectMD
+ *
+ */
+
+#ifndef __MAC_H__
+#define __MAC_H__
+
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__UPC_H__)
+#include "upc.h"
+#endif
+
+/*---------------------  Export Definitions -------------------------*/
+//
+// Registers in the MAC
+//
+#define MAC_MAX_CONTEXT_SIZE_PAGE0  256
+#define MAC_MAX_CONTEXT_SIZE_PAGE1  128
+#define MAC_MAX_CONTEXT_SIZE        MAC_MAX_CONTEXT_SIZE_PAGE0 + MAC_MAX_CONTEXT_SIZE_PAGE1
+
+// Registers not related to 802.11b
+#define MAC_REG_BCFG0       0x00
+#define MAC_REG_BCFG1       0x01
+#define MAC_REG_FCR0        0x02
+#define MAC_REG_FCR1        0x03
+#define MAC_REG_BISTCMD     0x04
+#define MAC_REG_BISTSR0     0x05
+#define MAC_REG_BISTSR1     0x06
+#define MAC_REG_BISTSR2     0x07
+#define MAC_REG_I2MCSR      0x08
+#define MAC_REG_I2MTGID     0x09
+#define MAC_REG_I2MTGAD     0x0A
+#define MAC_REG_I2MCFG      0x0B
+#define MAC_REG_I2MDIPT     0x0C
+#define MAC_REG_I2MDOPT     0x0E
+#define MAC_REG_PMC0        0x10
+#define MAC_REG_PMC1        0x11
+#define MAC_REG_STICKHW     0x12
+#define MAC_REG_LOCALID     0x14
+#define MAC_REG_TESTCFG     0x15
+#define MAC_REG_JUMPER0     0x16
+#define MAC_REG_JUMPER1     0x17
+#define MAC_REG_TMCTL0      0x18
+#define MAC_REG_TMCTL1      0x19
+#define MAC_REG_TMDATA0     0x1C
+// MAC Parameter related
+#define MAC_REG_LRT         0x20        //
+#define MAC_REG_SRT         0x21        //
+#define MAC_REG_SIFS        0x22        //
+#define MAC_REG_DIFS        0x23        //
+#define MAC_REG_EIFS        0x24        //
+#define MAC_REG_SLOT        0x25        //
+#define MAC_REG_BI          0x26        //
+#define MAC_REG_CWMAXMIN0   0x28        //
+#define MAC_REG_LINKOFFTOTM 0x2A
+#define MAC_REG_SWTMOT      0x2B
+#define MAC_REG_MIBCNTR     0x2C
+#define MAC_REG_RTSOKCNT    0x2C
+#define MAC_REG_RTSFAILCNT  0x2D
+#define MAC_REG_ACKFAILCNT  0x2E
+#define MAC_REG_FCSERRCNT   0x2F
+// TSF Related
+#define MAC_REG_TSFCNTR     0x30        //
+#define MAC_REG_NEXTTBTT    0x38        //
+#define MAC_REG_TSFOFST     0x40        //
+#define MAC_REG_TFTCTL      0x48        //
+// WMAC Control/Status Related
+#define MAC_REG_ENCFG       0x4C        //
+#define MAC_REG_PAGE1SEL    0x4F        //
+#define MAC_REG_CFG         0x50        //
+#define MAC_REG_TEST        0x52        //
+#define MAC_REG_HOSTCR      0x54        //
+#define MAC_REG_MACCR       0x55        //
+#define MAC_REG_RCR         0x56        //
+#define MAC_REG_TCR         0x57        //
+#define MAC_REG_IMR         0x58        //
+#define MAC_REG_ISR         0x5C
+// Power Saving Related
+#define MAC_REG_PSCFG       0x60        //
+#define MAC_REG_PSCTL       0x61        //
+#define MAC_REG_PSPWRSIG    0x62        //
+#define MAC_REG_BBCR13      0x63
+#define MAC_REG_AIDATIM     0x64
+#define MAC_REG_PWBT        0x66
+#define MAC_REG_WAKEOKTMR   0x68
+#define MAC_REG_CALTMR      0x69
+#define MAC_REG_SYNSPACCNT  0x6A
+#define MAC_REG_WAKSYNOPT   0x6B
+// Baseband/IF Control Group
+#define MAC_REG_BBREGCTL    0x6C        //
+#define MAC_REG_CHANNEL     0x6D
+#define MAC_REG_BBREGADR    0x6E
+#define MAC_REG_BBREGDATA   0x6F
+#define MAC_REG_IFREGCTL    0x70        //
+#define MAC_REG_IFDATA      0x71        //
+#define MAC_REG_ITRTMSET    0x74        //
+#define MAC_REG_PAPEDELAY   0x77        //
+#define MAC_REG_SOFTPWRCTL  0x78        //
+#define MAC_REG_GPIOCTL0    0x7A        //
+#define MAC_REG_GPIOCTL1    0x7B        //
+
+// MAC DMA Related Group
+#define MAC_REG_TXDMACTL0   0x7C        //
+#define MAC_REG_TXDMAPTR0   0x80        //
+#define MAC_REG_AC0DMACTL   0x84        //
+#define MAC_REG_AC0DMAPTR   0x88        //
+#define MAC_REG_BCNDMACTL   0x8C        //
+#define MAC_REG_BCNDMAPTR   0x90        //
+#define MAC_REG_RXDMACTL0   0x94        //
+#define MAC_REG_RXDMAPTR0   0x98        //
+#define MAC_REG_RXDMACTL1   0x9C        //
+#define MAC_REG_RXDMAPTR1   0xA0        //
+#define MAC_REG_SYNCDMACTL  0xA4        //
+#define MAC_REG_SYNCDMAPTR  0xA8
+#define MAC_REG_ATIMDMACTL  0xAC
+#define MAC_REG_ATIMDMAPTR  0xB0
+// MiscFF PIO related
+#define MAC_REG_MISCFFNDEX  0xB4
+#define MAC_REG_MISCFFCTL   0xB6
+#define MAC_REG_MISCFFDATA  0xB8
+// Extend SW Timer
+#define MAC_REG_TMDATA1     0xBC
+// WOW Related Group
+#define MAC_REG_WAKEUPEN0   0xC0
+#define MAC_REG_WAKEUPEN1   0xC1
+#define MAC_REG_WAKEUPSR0   0xC2
+#define MAC_REG_WAKEUPSR1   0xC3
+#define MAC_REG_WAKE128_0   0xC4
+#define MAC_REG_WAKE128_1   0xD4
+#define MAC_REG_WAKE128_2   0xE4
+#define MAC_REG_WAKE128_3   0xF4
+
+/////////////// Page 1 ///////////////////
+#define MAC_REG_CRC_128_0   0x04
+#define MAC_REG_CRC_128_1   0x06
+#define MAC_REG_CRC_128_2   0x08
+#define MAC_REG_CRC_128_3   0x0A
+// MAC Configuration Group
+#define MAC_REG_PAR0        0x0C
+#define MAC_REG_PAR4        0x10
+#define MAC_REG_BSSID0      0x14
+#define MAC_REG_BSSID4      0x18
+#define MAC_REG_MAR0        0x1C
+#define MAC_REG_MAR4        0x20
+// MAC RSPPKT INFO Group
+#define MAC_REG_RSPINF_B_1  0x24
+#define MAC_REG_RSPINF_B_2  0x28
+#define MAC_REG_RSPINF_B_5  0x2C
+#define MAC_REG_RSPINF_B_11 0x30
+#define MAC_REG_RSPINF_A_6  0x34
+#define MAC_REG_RSPINF_A_9  0x36
+#define MAC_REG_RSPINF_A_12 0x38
+#define MAC_REG_RSPINF_A_18 0x3A
+#define MAC_REG_RSPINF_A_24 0x3C
+#define MAC_REG_RSPINF_A_36 0x3E
+#define MAC_REG_RSPINF_A_48 0x40
+#define MAC_REG_RSPINF_A_54 0x42
+#define MAC_REG_RSPINF_A_72 0x44
+
+// 802.11h relative
+#define MAC_REG_QUIETINIT   0x60
+#define MAC_REG_QUIETGAP    0x62
+#define MAC_REG_QUIETDUR    0x64
+#define MAC_REG_MSRCTL      0x66
+#define MAC_REG_MSRBBSTS    0x67
+#define MAC_REG_MSRSTART    0x68
+#define MAC_REG_MSRDURATION 0x70
+#define MAC_REG_CCAFRACTION 0x72
+#define MAC_REG_PWRCCK      0x73
+#define MAC_REG_PWROFDM     0x7C
+
+
+//
+// Bits in the BCFG0 register
+//
+#define BCFG0_PERROFF       0x40
+#define BCFG0_MRDMDIS       0x20
+#define BCFG0_MRDLDIS       0x10
+#define BCFG0_MWMEN         0x08
+#define BCFG0_VSERREN       0x02
+#define BCFG0_LATMEN        0x01
+
+//
+// Bits in the BCFG1 register
+//
+#define BCFG1_CFUNOPT       0x80
+#define BCFG1_CREQOPT       0x40
+#define BCFG1_DMA8          0x10
+#define BCFG1_ARBITOPT      0x08
+#define BCFG1_PCIMEN        0x04
+#define BCFG1_MIOEN         0x02
+#define BCFG1_CISDLYEN      0x01
+
+// Bits in RAMBIST registers
+#define BISTCMD_TSTPAT5     0x00        //
+#define BISTCMD_TSTPATA     0x80        //
+#define BISTCMD_TSTERR      0x20        //
+#define BISTCMD_TSTPATF     0x18        //
+#define BISTCMD_TSTPAT0     0x10        //
+#define BISTCMD_TSTMODE     0x04        //
+#define BISTCMD_TSTITTX     0x03        //
+#define BISTCMD_TSTATRX     0x02        //
+#define BISTCMD_TSTATTX     0x01        //
+#define BISTCMD_TSTRX       0x00        //
+#define BISTSR0_BISTGO      0x01        //
+#define BISTSR1_TSTSR       0x01        //
+#define BISTSR2_CMDPRTEN    0x02        //
+#define BISTSR2_RAMTSTEN    0x01        //
+
+//
+// Bits in the I2MCFG EEPROM register
+//
+#define I2MCFG_BOUNDCTL     0x80
+#define I2MCFG_WAITCTL      0x20
+#define I2MCFG_SCLOECTL     0x10
+#define I2MCFG_WBUSYCTL     0x08
+#define I2MCFG_NORETRY      0x04
+#define I2MCFG_I2MLDSEQ     0x02
+#define I2MCFG_I2CMFAST     0x01
+
+//
+// Bits in the I2MCSR EEPROM register
+//
+#define I2MCSR_EEMW         0x80
+#define I2MCSR_EEMR         0x40
+#define I2MCSR_AUTOLD       0x08
+#define I2MCSR_NACK         0x02
+#define I2MCSR_DONE         0x01
+
+//
+// Bits in the PMC1 register
+//
+#define SPS_RST             0x80
+#define PCISTIKY            0x40
+#define PME_OVR             0x02
+
+//
+// Bits in the STICKYHW register
+//
+#define STICKHW_DS1_SHADOW  0x02
+#define STICKHW_DS0_SHADOW  0x01
+
+//
+// Bits in the TMCTL register
+//
+#define TMCTL_TSUSP         0x04
+#define TMCTL_TMD           0x02
+#define TMCTL_TE            0x01
+
+//
+// Bits in the TFTCTL register
+//
+#define TFTCTL_HWUTSF       0x80        //
+#define TFTCTL_TBTTSYNC     0x40
+#define TFTCTL_HWUTSFEN     0x20
+#define TFTCTL_TSFCNTRRD    0x10        //
+#define TFTCTL_TBTTSYNCEN   0x08        //
+#define TFTCTL_TSFSYNCEN    0x04        //
+#define TFTCTL_TSFCNTRST    0x02        //
+#define TFTCTL_TSFCNTREN    0x01        //
+
+//
+// Bits in the EnhanceCFG register
+//
+#define EnCFG_BarkerPream   0x00020000
+#define EnCFG_NXTBTTCFPSTR  0x00010000
+//#define EnCFG_TXLMT3UPDATE  0x00008000
+//#define EnCFG_TXLMT2UPDATE  0x00004000
+//#define EnCFG_TXLMT1UPDATE  0x00002000
+//#define EnCFG_TXLMT3EN      0x00001000
+//#define EnCFG_TXLMT2EN      0x00000800
+//#define EnCFG_TXLMT1EN      0x00000400
+#define EnCFG_BcnSusClr     0x00000200
+#define EnCFG_BcnSusInd     0x00000100
+//#define EnCFG_CWOFF1        0x00000080
+#define EnCFG_CFP_ProtectEn 0x00000040
+#define EnCFG_ProtectMd     0x00000020
+#define EnCFG_HwParCFP      0x00000010
+//#define EnCFG_QOS           0x00000008
+#define EnCFG_CFNULRSP      0x00000004
+#define EnCFG_BBType_MASK   0x00000003
+#define EnCFG_BBType_g      0x00000002
+#define EnCFG_BBType_b      0x00000001
+#define EnCFG_BBType_a      0x00000000
+
+//
+// Bits in the Page1Sel register
+//
+#define PAGE1_SEL           0x01
+
+//
+// Bits in the CFG register
+//
+#define CFG_TKIPOPT         0x80
+#define CFG_RXDMAOPT        0x40
+#define CFG_TMOT_SW         0x20
+#define CFG_TMOT_HWLONG     0x10
+#define CFG_TMOT_HW         0x00
+#define CFG_CFPENDOPT       0x08
+#define CFG_BCNSUSEN        0x04
+#define CFG_NOTXTIMEOUT     0x02
+#define CFG_NOBUFOPT        0x01
+
+//
+// Bits in the TEST register
+//
+#define TEST_LBEXT          0x80        //
+#define TEST_LBINT          0x40        //
+#define TEST_LBNONE         0x00        //
+#define TEST_SOFTINT        0x20        //
+#define TEST_CONTTX         0x10        //
+#define TEST_TXPE           0x08        //
+#define TEST_NAVDIS         0x04        //
+#define TEST_NOCTS          0x02        //
+#define TEST_NOACK          0x01        //
+
+//
+// Bits in the HOSTCR register
+//
+#define HOSTCR_TXONST       0x80        //
+#define HOSTCR_RXONST       0x40        //
+#define HOSTCR_ADHOC        0x20        // Network Type 1 = Ad-hoc
+#define HOSTCR_AP           0x10        // Port Type 1 = AP
+#define HOSTCR_TXON         0x08        //0000 1000
+#define HOSTCR_RXON         0x04        //0000 0100
+#define HOSTCR_MACEN        0x02        //0000 0010
+#define HOSTCR_SOFTRST      0x01        //0000 0001
+
+//
+// Bits in the MACCR register
+//
+#define MACCR_SYNCFLUSHOK   0x04        //
+#define MACCR_SYNCFLUSH     0x02        //
+#define MACCR_CLRNAV        0x01        //
+
+// Bits in the MAC_REG_GPIOCTL0 register
+//
+#define LED_ACTSET           0x01        //
+#define LED_RFOFF            0x02        //
+#define LED_NOCONNECT        0x04        //
+//
+// Bits in the RCR register
+//
+#define RCR_SSID            0x80
+#define RCR_RXALLTYPE       0x40        //
+#define RCR_UNICAST         0x20        //
+#define RCR_BROADCAST       0x10        //
+#define RCR_MULTICAST       0x08        //
+#define RCR_WPAERR          0x04        //
+#define RCR_ERRCRC          0x02        //
+#define RCR_BSSID           0x01        //
+
+//
+// Bits in the TCR register
+//
+#define TCR_SYNCDCFOPT      0x02        //
+#define TCR_AUTOBCNTX       0x01        // Beacon automatically transmit enable
+
+//
+// Bits in the IMR register
+//
+#define IMR_MEASURESTART    0x80000000      //
+#define IMR_QUIETSTART      0x20000000      //
+#define IMR_RADARDETECT     0x10000000      //
+#define IMR_MEASUREEND      0x08000000      //
+#define IMR_SOFTTIMER1      0x00200000      //
+//#define IMR_SYNCFLUSHOK     0x00100000      //
+//#define IMR_ATIMEND         0x00080000      //0000 1000 0000 0000 0000 0000
+//#define IMR_CFPEND          0x00040000      //0000 0100 0000 0000 0000 0000
+//#define IMR_AC3DMA          0x00020000      //0000 0010 0000 0000 0000 0000
+//#define IMR_AC2DMA          0x00010000      //0000 0001 0000 0000 0000 0000
+//#define IMR_AC1DMA          0x00008000      //0000 0000 1000 0000 0000 0000
+//#define IMR_SYNCTX          0x00004000      //0000 0000 0100 0000 0000 0000
+//#define IMR_ATIMTX          0x00002000      //0000 0000 0010 0000 0000 0000
+#define IMR_RXDMA1          0x00001000      //0000 0000 0001 0000 0000 0000
+#define IMR_RXNOBUF         0x00000800      //
+#define IMR_MIBNEARFULL     0x00000400      //
+#define IMR_SOFTINT         0x00000200      //
+#define IMR_FETALERR        0x00000100      //
+#define IMR_WATCHDOG        0x00000080      //
+#define IMR_SOFTTIMER       0x00000040      //
+#define IMR_GPIO            0x00000020      //
+#define IMR_TBTT            0x00000010      //
+#define IMR_RXDMA0          0x00000008      //
+#define IMR_BNTX            0x00000004      //
+#define IMR_AC0DMA          0x00000002      //
+#define IMR_TXDMA0          0x00000001      //
+
+
+//
+// Bits in the ISR register
+//
+
+#define ISR_MEASURESTART    0x80000000      //
+#define ISR_QUIETSTART      0x20000000      //
+#define ISR_RADARDETECT     0x10000000      //
+#define ISR_MEASUREEND      0x08000000      //
+#define ISR_SOFTTIMER1      0x00200000      //
+//#define ISR_SYNCFLUSHOK     0x00100000      //0001 0000 0000 0000 0000 0000
+//#define ISR_ATIMEND         0x00080000      //0000 1000 0000 0000 0000 0000
+//#define ISR_CFPEND          0x00040000      //0000 0100 0000 0000 0000 0000
+//#define ISR_AC3DMA          0x00020000      //0000 0010 0000 0000 0000 0000
+//#define ISR_AC2DMA          0x00010000      //0000 0001 0000 0000 0000 0000
+//#define ISR_AC1DMA          0x00008000      //0000 0000 1000 0000 0000 0000
+//#define ISR_SYNCTX          0x00004000      //0000 0000 0100 0000 0000 0000
+//#define ISR_ATIMTX          0x00002000      //0000 0000 0010 0000 0000 0000
+#define ISR_RXDMA1          0x00001000      //0000 0000 0001 0000 0000 0000
+#define ISR_RXNOBUF         0x00000800      //0000 0000 0000 1000 0000 0000
+#define ISR_MIBNEARFULL     0x00000400      //0000 0000 0000 0100 0000 0000
+#define ISR_SOFTINT         0x00000200      //
+#define ISR_FETALERR        0x00000100      //
+#define ISR_WATCHDOG        0x00000080      //
+#define ISR_SOFTTIMER       0x00000040      //
+#define ISR_GPIO            0x00000020      //
+#define ISR_TBTT            0x00000010      //
+#define ISR_RXDMA0          0x00000008      //
+#define ISR_BNTX            0x00000004      //
+#define ISR_AC0DMA          0x00000002      //
+#define ISR_TXDMA0          0x00000001      //
+
+
+//
+// Bits in the PSCFG register
+//
+#define PSCFG_PHILIPMD      0x40        //
+#define PSCFG_WAKECALEN     0x20        //
+#define PSCFG_WAKETMREN     0x10        //
+#define PSCFG_BBPSPROG      0x08        //
+#define PSCFG_WAKESYN       0x04        //
+#define PSCFG_SLEEPSYN      0x02        //
+#define PSCFG_AUTOSLEEP     0x01        //
+
+//
+// Bits in the PSCTL register
+//
+#define PSCTL_WAKEDONE      0x20        //
+#define PSCTL_PS            0x10        //
+#define PSCTL_GO2DOZE       0x08        //
+#define PSCTL_LNBCN         0x04        //
+#define PSCTL_ALBCN         0x02        //
+#define PSCTL_PSEN          0x01        //
+
+//
+// Bits in the PSPWSIG register
+//
+#define PSSIG_WPE3          0x80        //
+#define PSSIG_WPE2          0x40        //
+#define PSSIG_WPE1          0x20        //
+#define PSSIG_WRADIOPE      0x10        //
+#define PSSIG_SPE3          0x08        //
+#define PSSIG_SPE2          0x04        //
+#define PSSIG_SPE1          0x02        //
+#define PSSIG_SRADIOPE      0x01        //
+
+//
+// Bits in the BBREGCTL register
+//
+#define BBREGCTL_DONE       0x04        //
+#define BBREGCTL_REGR       0x02        //
+#define BBREGCTL_REGW       0x01        //
+
+//
+// Bits in the IFREGCTL register
+//
+#define IFREGCTL_DONE       0x04        //
+#define IFREGCTL_IFRF       0x02        //
+#define IFREGCTL_REGW       0x01        //
+
+//
+// Bits in the SOFTPWRCTL register
+//
+#define SOFTPWRCTL_RFLEOPT      0x0800  //
+#define SOFTPWRCTL_TXPEINV      0x0200  //
+#define SOFTPWRCTL_SWPECTI      0x0100  //
+#define SOFTPWRCTL_SWPAPE       0x0020  //
+#define SOFTPWRCTL_SWCALEN      0x0010  //
+#define SOFTPWRCTL_SWRADIO_PE   0x0008  //
+#define SOFTPWRCTL_SWPE2        0x0004  //
+#define SOFTPWRCTL_SWPE1        0x0002  //
+#define SOFTPWRCTL_SWPE3        0x0001  //
+
+//
+// Bits in the GPIOCTL1 register
+//
+#define GPIO1_DATA1             0x20    //
+#define GPIO1_MD1               0x10    //
+#define GPIO1_DATA0             0x02    //
+#define GPIO1_MD0               0x01    //
+
+//
+// Bits in the DMACTL register
+//
+#define DMACTL_CLRRUN       0x00080000  //
+#define DMACTL_RUN          0x00000008  //
+#define DMACTL_WAKE         0x00000004  //
+#define DMACTL_DEAD         0x00000002  //
+#define DMACTL_ACTIVE       0x00000001  //
+//
+// Bits in the RXDMACTL0 register
+//
+#define RX_PERPKT           0x00000100  //
+#define RX_PERPKTCLR        0x01000000  //
+//
+// Bits in the BCNDMACTL register
+//
+#define BEACON_READY        0x01        //
+//
+// Bits in the MISCFFCTL register
+//
+#define MISCFFCTL_WRITE     0x0001      //
+
+
+//
+// Bits in WAKEUPEN0
+//
+#define WAKEUPEN0_DIRPKT    0x10
+#define WAKEUPEN0_LINKOFF   0x08
+#define WAKEUPEN0_ATIMEN    0x04
+#define WAKEUPEN0_TIMEN     0x02
+#define WAKEUPEN0_MAGICEN   0x01
+
+//
+// Bits in WAKEUPEN1
+//
+#define WAKEUPEN1_128_3     0x08
+#define WAKEUPEN1_128_2     0x04
+#define WAKEUPEN1_128_1     0x02
+#define WAKEUPEN1_128_0     0x01
+
+//
+// Bits in WAKEUPSR0
+//
+#define WAKEUPSR0_DIRPKT    0x10
+#define WAKEUPSR0_LINKOFF   0x08
+#define WAKEUPSR0_ATIMEN    0x04
+#define WAKEUPSR0_TIMEN     0x02
+#define WAKEUPSR0_MAGICEN   0x01
+
+//
+// Bits in WAKEUPSR1
+//
+#define WAKEUPSR1_128_3     0x08
+#define WAKEUPSR1_128_2     0x04
+#define WAKEUPSR1_128_1     0x02
+#define WAKEUPSR1_128_0     0x01
+
+//
+// Bits in the MAC_REG_GPIOCTL register
+//
+#define GPIO0_MD            0x01        //
+#define GPIO0_DATA          0x02        //
+#define GPIO0_INTMD         0x04        //
+#define GPIO1_MD            0x10        //
+#define GPIO1_DATA          0x20        //
+
+
+//
+// Bits in the MSRCTL register
+//
+#define MSRCTL_FINISH       0x80
+#define MSRCTL_READY        0x40
+#define MSRCTL_RADARDETECT  0x20
+#define MSRCTL_EN           0x10
+#define MSRCTL_QUIETTXCHK   0x08
+#define MSRCTL_QUIETRPT     0x04
+#define MSRCTL_QUIETINT     0x02
+#define MSRCTL_QUIETEN      0x01
+//
+// Bits in the MSRCTL1 register
+//
+#define MSRCTL1_TXPWR       0x08
+#define MSRCTL1_CSAPAREN    0x04
+#define MSRCTL1_TXPAUSE     0x01
+
+
+// Loopback mode
+#define MAC_LB_EXT          0x02        //
+#define MAC_LB_INTERNAL     0x01        //
+#define MAC_LB_NONE         0x00        //
+
+// Ethernet address filter type
+#define PKT_TYPE_NONE           0x00    // turn off receiver
+#define PKT_TYPE_ALL_MULTICAST  0x80
+#define PKT_TYPE_PROMISCUOUS    0x40
+#define PKT_TYPE_DIRECTED       0x20    // obselete, directed address is always accepted
+#define PKT_TYPE_BROADCAST      0x10
+#define PKT_TYPE_MULTICAST      0x08
+#define PKT_TYPE_ERROR_WPA      0x04
+#define PKT_TYPE_ERROR_CRC      0x02
+#define PKT_TYPE_BSSID          0x01
+
+#define Default_BI              0x200
+
+
+// MiscFIFO Offset
+#define MISCFIFO_KEYETRY0       32
+#define MISCFIFO_KEYENTRYSIZE   22
+#define MISCFIFO_SYNINFO_IDX    10
+#define MISCFIFO_SYNDATA_IDX    11
+#define MISCFIFO_SYNDATASIZE    21
+
+// enabled mask value of irq
+#define IMR_MASK_VALUE     (IMR_SOFTTIMER1 | \
+                            IMR_RXDMA1 | \
+                            IMR_RXNOBUF | \
+                            IMR_MIBNEARFULL | \
+                            IMR_SOFTINT | \
+                            IMR_FETALERR | \
+                            IMR_WATCHDOG | \
+                            IMR_SOFTTIMER | \
+                            IMR_GPIO | \
+                            IMR_TBTT | \
+                            IMR_RXDMA0 | \
+                            IMR_BNTX | \
+                            IMR_AC0DMA | \
+                            IMR_TXDMA0)
+
+// max time out delay time
+#define W_MAX_TIMEOUT       0xFFF0U     //
+
+// wait time within loop
+#define CB_DELAY_LOOP_WAIT  10          // 10ms
+
+//
+// revision id
+//
+#define REV_ID_VT3253_A0    0x00
+#define REV_ID_VT3253_A1    0x01
+#define REV_ID_VT3253_B0    0x08
+#define REV_ID_VT3253_B1    0x09
+
+/*---------------------  Export Types  ------------------------------*/
+
+/*---------------------  Export Macros ------------------------------*/
+
+#define MACvRegBitsOn(dwIoBase, byRegOfs, byBits)           \
+{                                                           \
+    BYTE byData;                                            \
+    VNSvInPortB(dwIoBase + byRegOfs, &byData);              \
+    VNSvOutPortB(dwIoBase + byRegOfs, byData | (byBits));   \
+}
+
+#define MACvWordRegBitsOn(dwIoBase, byRegOfs, wBits)        \
+{                                                           \
+    WORD wData;                                             \
+    VNSvInPortW(dwIoBase + byRegOfs, &wData);               \
+    VNSvOutPortW(dwIoBase + byRegOfs, wData | (wBits));     \
+}
+
+#define MACvDWordRegBitsOn(dwIoBase, byRegOfs, dwBits)      \
+{                                                           \
+    DWORD dwData;                                           \
+    VNSvInPortD(dwIoBase + byRegOfs, &dwData);              \
+    VNSvOutPortD(dwIoBase + byRegOfs, dwData | (dwBits));   \
+}
+
+#define MACvRegBitsOnEx(dwIoBase, byRegOfs, byMask, byBits) \
+{                                                           \
+    BYTE byData;                                            \
+    VNSvInPortB(dwIoBase + byRegOfs, &byData);              \
+    byData &= byMask;                                       \
+    VNSvOutPortB(dwIoBase + byRegOfs, byData | (byBits));   \
+}
+
+#define MACvRegBitsOff(dwIoBase, byRegOfs, byBits)          \
+{                                                           \
+    BYTE byData;                                            \
+    VNSvInPortB(dwIoBase + byRegOfs, &byData);              \
+    VNSvOutPortB(dwIoBase + byRegOfs, byData & ~(byBits));  \
+}
+
+#define MACvWordRegBitsOff(dwIoBase, byRegOfs, wBits)       \
+{                                                           \
+    WORD wData;                                             \
+    VNSvInPortW(dwIoBase + byRegOfs, &wData);               \
+    VNSvOutPortW(dwIoBase + byRegOfs, wData & ~(wBits));    \
+}
+
+#define MACvDWordRegBitsOff(dwIoBase, byRegOfs, dwBits)     \
+{                                                           \
+    DWORD dwData;                                           \
+    VNSvInPortD(dwIoBase + byRegOfs, &dwData);              \
+    VNSvOutPortD(dwIoBase + byRegOfs, dwData & ~(dwBits));  \
+}
+
+#define MACvGetCurrRx0DescAddr(dwIoBase, pdwCurrDescAddr)    \
+{                                                           \
+    VNSvInPortD(dwIoBase + MAC_REG_RXDMAPTR0,               \
+                (PDWORD)pdwCurrDescAddr);                   \
+}
+
+#define MACvGetCurrRx1DescAddr(dwIoBase, pdwCurrDescAddr)   \
+{                                                           \
+    VNSvInPortD(dwIoBase + MAC_REG_RXDMAPTR1,               \
+                (PDWORD)pdwCurrDescAddr);                   \
+}
+
+#define MACvGetCurrTx0DescAddr(dwIoBase, pdwCurrDescAddr)   \
+{                                                           \
+    VNSvInPortD(dwIoBase + MAC_REG_TXDMAPTR0,               \
+                (PDWORD)pdwCurrDescAddr);                   \
+}
+
+#define MACvGetCurrAC0DescAddr(dwIoBase, pdwCurrDescAddr)   \
+{                                                           \
+    VNSvInPortD(dwIoBase + MAC_REG_AC0DMAPTR,               \
+                (PDWORD)pdwCurrDescAddr);                   \
+}
+
+#define MACvGetCurrSyncDescAddr(dwIoBase, pdwCurrDescAddr)  \
+{                                                           \
+    VNSvInPortD(dwIoBase + MAC_REG_SYNCDMAPTR,              \
+                (PDWORD)pdwCurrDescAddr);                   \
+}
+
+#define MACvGetCurrATIMDescAddr(dwIoBase, pdwCurrDescAddr)  \
+{                                                           \
+    VNSvInPortD(dwIoBase + MAC_REG_ATIMDMAPTR,              \
+                (PDWORD)pdwCurrDescAddr);                   \
+}                                                           \
+
+// set the chip with current BCN tx descriptor address
+#define MACvSetCurrBCNTxDescAddr(dwIoBase, dwCurrDescAddr)  \
+{                                                           \
+    VNSvOutPortD(dwIoBase + MAC_REG_BCNDMAPTR,              \
+                 dwCurrDescAddr);                           \
+}
+
+// set the chip with current BCN length
+#define MACvSetCurrBCNLength(dwIoBase, wCurrBCNLength)     \
+{                                                          \
+    VNSvOutPortW(dwIoBase + MAC_REG_BCNDMACTL+2,           \
+                 wCurrBCNLength);                          \
+}
+
+#define MACvReadBSSIDAddress(dwIoBase, pbyEtherAddr)        \
+{                                                           \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 1);           \
+    VNSvInPortB(dwIoBase + MAC_REG_BSSID0,                  \
+                (PBYTE)pbyEtherAddr);                       \
+    VNSvInPortB(dwIoBase + MAC_REG_BSSID0 + 1,              \
+                pbyEtherAddr + 1);                          \
+    VNSvInPortB(dwIoBase + MAC_REG_BSSID0 + 2,              \
+                pbyEtherAddr + 2);                          \
+    VNSvInPortB(dwIoBase + MAC_REG_BSSID0 + 3,              \
+                pbyEtherAddr + 3);                          \
+    VNSvInPortB(dwIoBase + MAC_REG_BSSID0 + 4,              \
+                pbyEtherAddr + 4);                          \
+    VNSvInPortB(dwIoBase + MAC_REG_BSSID0 + 5,              \
+                pbyEtherAddr + 5);                          \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 0);           \
+}
+
+#define MACvWriteBSSIDAddress(dwIoBase, pbyEtherAddr)       \
+{                                                           \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 1);           \
+    VNSvOutPortB(dwIoBase + MAC_REG_BSSID0,                 \
+                *(pbyEtherAddr));                           \
+    VNSvOutPortB(dwIoBase + MAC_REG_BSSID0 + 1,             \
+                *(pbyEtherAddr + 1));                       \
+    VNSvOutPortB(dwIoBase + MAC_REG_BSSID0 + 2,             \
+                *(pbyEtherAddr + 2));                       \
+    VNSvOutPortB(dwIoBase + MAC_REG_BSSID0 + 3,             \
+                *(pbyEtherAddr + 3));                       \
+    VNSvOutPortB(dwIoBase + MAC_REG_BSSID0 + 4,             \
+                *(pbyEtherAddr + 4));                       \
+    VNSvOutPortB(dwIoBase + MAC_REG_BSSID0 + 5,             \
+                *(pbyEtherAddr + 5));                       \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 0);           \
+}
+
+#define MACvReadEtherAddress(dwIoBase, pbyEtherAddr)        \
+{                                                           \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 1);           \
+    VNSvInPortB(dwIoBase + MAC_REG_PAR0,                    \
+                (PBYTE)pbyEtherAddr);                       \
+    VNSvInPortB(dwIoBase + MAC_REG_PAR0 + 1,                \
+                pbyEtherAddr + 1);                          \
+    VNSvInPortB(dwIoBase + MAC_REG_PAR0 + 2,                \
+                pbyEtherAddr + 2);                          \
+    VNSvInPortB(dwIoBase + MAC_REG_PAR0 + 3,                \
+                pbyEtherAddr + 3);                          \
+    VNSvInPortB(dwIoBase + MAC_REG_PAR0 + 4,                \
+                pbyEtherAddr + 4);                          \
+    VNSvInPortB(dwIoBase + MAC_REG_PAR0 + 5,                \
+                pbyEtherAddr + 5);                          \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 0);           \
+}
+
+
+#define MACvWriteEtherAddress(dwIoBase, pbyEtherAddr)       \
+{                                                           \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 1);           \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAR0,                   \
+                *pbyEtherAddr);                             \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAR0 + 1,               \
+                *(pbyEtherAddr + 1));                       \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAR0 + 2,               \
+                *(pbyEtherAddr + 2));                       \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAR0 + 3,               \
+                *(pbyEtherAddr + 3));                       \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAR0 + 4,               \
+                *(pbyEtherAddr + 4));                       \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAR0 + 5,               \
+                *(pbyEtherAddr + 5));                       \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 0);           \
+}
+
+
+#define MACvClearISR(dwIoBase)                              \
+{                                                           \
+    VNSvOutPortD(dwIoBase + MAC_REG_ISR, IMR_MASK_VALUE);   \
+}
+
+#define MACvStart(dwIoBase)                                      \
+{                                                                \
+    VNSvOutPortB(dwIoBase + MAC_REG_HOSTCR,                      \
+                    (HOSTCR_MACEN | HOSTCR_RXON | HOSTCR_TXON)); \
+}
+
+#define MACvRx0PerPktMode(dwIoBase)                         \
+{                                                           \
+    VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL0, RX_PERPKT);  \
+}
+
+#define MACvRx0BufferFillMode(dwIoBase)                         \
+{                                                               \
+    VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL0, RX_PERPKTCLR);   \
+}
+
+#define MACvRx1PerPktMode(dwIoBase)                         \
+{                                                           \
+    VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL1, RX_PERPKT);  \
+}
+
+#define MACvRx1BufferFillMode(dwIoBase)                         \
+{                                                               \
+    VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL1, RX_PERPKTCLR);   \
+}
+
+#define MACvRxOn(dwIoBase)                                      \
+{                                                               \
+    MACvRegBitsOn(dwIoBase, MAC_REG_HOSTCR, HOSTCR_RXON);       \
+}
+
+#define MACvReceive0(dwIoBase)                                  \
+{                                                               \
+    DWORD dwData;                                               \
+    VNSvInPortD(dwIoBase + MAC_REG_RXDMACTL0, &dwData);         \
+    if (dwData & DMACTL_RUN) {                                  \
+        VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL0, DMACTL_WAKE);\
+    }                                                           \
+    else {                                                      \
+        VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL0, DMACTL_RUN); \
+    }                                                           \
+}
+
+#define MACvReceive1(dwIoBase)                                  \
+{                                                               \
+    DWORD dwData;                                                \
+    VNSvInPortD(dwIoBase + MAC_REG_RXDMACTL1, &dwData);         \
+    if (dwData & DMACTL_RUN) {                                  \
+        VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL1, DMACTL_WAKE);\
+    }                                                           \
+    else {                                                      \
+        VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL1, DMACTL_RUN); \
+    }                                                           \
+}
+
+#define MACvTxOn(dwIoBase)                                      \
+{                                                               \
+    MACvRegBitsOn(dwIoBase, MAC_REG_HOSTCR, HOSTCR_TXON);       \
+}
+
+#define MACvTransmit0(dwIoBase)                                 \
+{                                                               \
+    DWORD dwData;                                                \
+    VNSvInPortD(dwIoBase + MAC_REG_TXDMACTL0, &dwData);         \
+    if (dwData & DMACTL_RUN) {                                  \
+        VNSvOutPortD(dwIoBase + MAC_REG_TXDMACTL0, DMACTL_WAKE);\
+    }                                                           \
+    else {                                                      \
+        VNSvOutPortD(dwIoBase + MAC_REG_TXDMACTL0, DMACTL_RUN); \
+    }                                                           \
+}
+
+#define MACvTransmitAC0(dwIoBase)                               \
+{                                                               \
+    DWORD dwData;                                                \
+    VNSvInPortD(dwIoBase + MAC_REG_AC0DMACTL, &dwData);         \
+    if (dwData & DMACTL_RUN) {                                  \
+        VNSvOutPortD(dwIoBase + MAC_REG_AC0DMACTL, DMACTL_WAKE);\
+    }                                                           \
+    else {                                                      \
+        VNSvOutPortD(dwIoBase + MAC_REG_AC0DMACTL, DMACTL_RUN); \
+    }                                                           \
+}
+
+#define MACvTransmitSYNC(dwIoBase)                               \
+{                                                                \
+    DWORD dwData;                                                 \
+    VNSvInPortD(dwIoBase + MAC_REG_SYNCDMACTL, &dwData);         \
+    if (dwData & DMACTL_RUN) {                                   \
+        VNSvOutPortD(dwIoBase + MAC_REG_SYNCDMACTL, DMACTL_WAKE);\
+    }                                                            \
+    else {                                                       \
+        VNSvOutPortD(dwIoBase + MAC_REG_SYNCDMACTL, DMACTL_RUN); \
+    }                                                            \
+}
+
+#define MACvTransmitATIM(dwIoBase)                               \
+{                                                                \
+    DWORD dwData;                                                 \
+    VNSvInPortD(dwIoBase + MAC_REG_ATIMDMACTL, &dwData);         \
+    if (dwData & DMACTL_RUN) {                                   \
+        VNSvOutPortD(dwIoBase + MAC_REG_ATIMDMACTL, DMACTL_WAKE);\
+    }                                                            \
+    else {                                                       \
+        VNSvOutPortD(dwIoBase + MAC_REG_ATIMDMACTL, DMACTL_RUN); \
+    }                                                            \
+}
+
+#define MACvTransmitBCN(dwIoBase)                               \
+{                                                               \
+    VNSvOutPortB(dwIoBase + MAC_REG_BCNDMACTL, BEACON_READY);   \
+}
+
+#define MACvClearStckDS(dwIoBase)                           \
+{                                                           \
+    BYTE byOrgValue;                                        \
+    VNSvInPortB(dwIoBase + MAC_REG_STICKHW, &byOrgValue);   \
+    byOrgValue = byOrgValue & 0xFC;                         \
+    VNSvOutPortB(dwIoBase + MAC_REG_STICKHW, byOrgValue);   \
+}
+
+#define MACvReadISR(dwIoBase, pdwValue)             \
+{                                                   \
+    VNSvInPortD(dwIoBase + MAC_REG_ISR, pdwValue);  \
+}
+
+#define MACvWriteISR(dwIoBase, dwValue)             \
+{                                                   \
+    VNSvOutPortD(dwIoBase + MAC_REG_ISR, dwValue);  \
+}
+
+#define MACvIntEnable(dwIoBase, dwMask)             \
+{                                                   \
+    VNSvOutPortD(dwIoBase + MAC_REG_IMR, dwMask);   \
+}
+
+#define MACvIntDisable(dwIoBase)                    \
+{                                                   \
+    VNSvOutPortD(dwIoBase + MAC_REG_IMR, 0);        \
+}
+
+#define MACvSelectPage0(dwIoBase)                   \
+{                                                   \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 0);   \
+}
+#define MACvSelectPage1(dwIoBase)                   \
+{                                                   \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 1);   \
+}
+
+#define MACvReadMIBCounter(dwIoBase, pdwCounter)            \
+{                                                           \
+    VNSvInPortD(dwIoBase + MAC_REG_MIBCNTR , pdwCounter);   \
+}
+
+#define MACvPwrEvntDisable(dwIoBase)                    \
+{                                                       \
+    VNSvOutPortW(dwIoBase + MAC_REG_WAKEUPEN0, 0x0000); \
+}
+
+#define MACvEnableProtectMD(dwIoBase)                    \
+{                                                        \
+    DWORD dwOrgValue;                                    \
+    VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue); \
+    dwOrgValue = dwOrgValue | EnCFG_ProtectMd;           \
+    VNSvOutPortD(dwIoBase + MAC_REG_ENCFG, dwOrgValue);  \
+}
+
+#define MACvDisableProtectMD(dwIoBase)                   \
+{                                                        \
+    DWORD dwOrgValue;                                     \
+    VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue); \
+    dwOrgValue = dwOrgValue & ~EnCFG_ProtectMd;          \
+    VNSvOutPortD(dwIoBase + MAC_REG_ENCFG, dwOrgValue);  \
+}
+
+#define MACvEnableBarkerPreambleMd(dwIoBase)             \
+{                                                        \
+    DWORD dwOrgValue;                                    \
+    VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue); \
+    dwOrgValue = dwOrgValue | EnCFG_BarkerPream;         \
+    VNSvOutPortD(dwIoBase + MAC_REG_ENCFG, dwOrgValue);  \
+}
+
+#define MACvDisableBarkerPreambleMd(dwIoBase)            \
+{                                                        \
+    DWORD dwOrgValue;                                    \
+    VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue); \
+    dwOrgValue = dwOrgValue & ~EnCFG_BarkerPream;        \
+    VNSvOutPortD(dwIoBase + MAC_REG_ENCFG, dwOrgValue);  \
+}
+
+#define MACvSetBBType(dwIoBase, byTyp)                   \
+{                                                        \
+    DWORD dwOrgValue;                                    \
+    VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue); \
+    dwOrgValue = dwOrgValue & ~EnCFG_BBType_MASK;        \
+    dwOrgValue = dwOrgValue | (DWORD) byTyp;             \
+    VNSvOutPortD(dwIoBase + MAC_REG_ENCFG, dwOrgValue);  \
+}
+
+#define MACvReadATIMW(dwIoBase, pwCounter)                 \
+{                                                          \
+    VNSvInPortW(dwIoBase + MAC_REG_AIDATIM , pwCounter);   \
+}
+
+#define MACvWriteATIMW(dwIoBase, wCounter)                 \
+{                                                          \
+    VNSvOutPortW(dwIoBase + MAC_REG_AIDATIM , wCounter);   \
+}
+
+#define MACvWriteCRC16_128(dwIoBase, byRegOfs, wCRC)       \
+{                                                          \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 1);          \
+    VNSvOutPortW(dwIoBase + byRegOfs, wCRC);               \
+    VNSvOutPortB(dwIoBase + MAC_REG_PAGE1SEL, 0);          \
+}
+
+#define MACvGPIOIn(dwIoBase, pbyValue)                      \
+{                                                           \
+    VNSvInPortB(dwIoBase + MAC_REG_GPIOCTL1, pbyValue);     \
+}
+
+#define MACvSetRFLE_LatchBase(dwIoBase)                                 \
+{                                                                        \
+    MACvWordRegBitsOn(dwIoBase, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_RFLEOPT); \
+}
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+extern WORD TxRate_iwconfig;//2008-5-8 <add> by chester
+VOID MACvReadAllRegs(DWORD_PTR dwIoBase, PBYTE pbyMacRegs);
+
+BOOL MACbIsRegBitsOn(DWORD_PTR dwIoBase, BYTE byRegOfs, BYTE byTestBits);
+BOOL MACbIsRegBitsOff(DWORD_PTR dwIoBase, BYTE byRegOfs, BYTE byTestBits);
+
+BOOL MACbIsIntDisable(DWORD_PTR dwIoBase);
+
+BYTE MACbyReadMultiAddr(DWORD_PTR dwIoBase, UINT uByteIdx);
+VOID MACvWriteMultiAddr(DWORD_PTR dwIoBase, UINT uByteIdx, BYTE byData);
+VOID MACvSetMultiAddrByHash(DWORD_PTR dwIoBase, BYTE byHashIdx);
+VOID MACvResetMultiAddrByHash(DWORD_PTR dwIoBase, BYTE byHashIdx);
+
+VOID MACvSetRxThreshold(DWORD_PTR dwIoBase, BYTE byThreshold);
+VOID MACvGetRxThreshold(DWORD_PTR dwIoBase, PBYTE pbyThreshold);
+
+VOID MACvSetTxThreshold(DWORD_PTR dwIoBase, BYTE byThreshold);
+VOID MACvGetTxThreshold(DWORD_PTR dwIoBase, PBYTE pbyThreshold);
+
+VOID MACvSetDmaLength(DWORD_PTR dwIoBase, BYTE byDmaLength);
+VOID MACvGetDmaLength(DWORD_PTR dwIoBase, PBYTE pbyDmaLength);
+
+VOID MACvSetShortRetryLimit(DWORD_PTR dwIoBase, BYTE byRetryLimit);
+VOID MACvGetShortRetryLimit(DWORD_PTR dwIoBase, PBYTE pbyRetryLimit);
+
+VOID MACvSetLongRetryLimit(DWORD_PTR dwIoBase, BYTE byRetryLimit);
+VOID MACvGetLongRetryLimit(DWORD_PTR dwIoBase, PBYTE pbyRetryLimit);
+
+VOID MACvSetLoopbackMode(DWORD_PTR dwIoBase, BYTE byLoopbackMode);
+BOOL MACbIsInLoopbackMode(DWORD_PTR dwIoBase);
+
+VOID MACvSetPacketFilter(DWORD_PTR dwIoBase, WORD wFilterType);
+
+VOID MACvSaveContext(DWORD_PTR dwIoBase, PBYTE pbyCxtBuf);
+VOID MACvRestoreContext(DWORD_PTR dwIoBase, PBYTE pbyCxtBuf);
+BOOL MACbCompareContext(DWORD_PTR dwIoBase, PBYTE pbyCxtBuf);
+
+BOOL MACbSoftwareReset(DWORD_PTR dwIoBase);
+BOOL MACbSafeSoftwareReset(DWORD_PTR dwIoBase);
+BOOL MACbSafeRxOff(DWORD_PTR dwIoBase);
+BOOL MACbSafeTxOff(DWORD_PTR dwIoBase);
+BOOL MACbSafeStop(DWORD_PTR dwIoBase);
+BOOL MACbShutdown(DWORD_PTR dwIoBase);
+VOID MACvInitialize(DWORD_PTR dwIoBase);
+VOID MACvSetCurrRx0DescAddr(DWORD_PTR dwIoBase, DWORD dwCurrDescAddr);
+VOID MACvSetCurrRx1DescAddr(DWORD_PTR dwIoBase, DWORD dwCurrDescAddr);
+VOID MACvSetCurrTXDescAddr(int iTxType, DWORD_PTR dwIoBase, DWORD dwCurrDescAddr);
+VOID MACvSetCurrTx0DescAddrEx(DWORD_PTR dwIoBase, DWORD dwCurrDescAddr);
+VOID MACvSetCurrAC0DescAddrEx(DWORD_PTR dwIoBase, DWORD dwCurrDescAddr);
+VOID MACvSetCurrSyncDescAddrEx(DWORD_PTR dwIoBase, DWORD dwCurrDescAddr);
+VOID MACvSetCurrATIMDescAddrEx(DWORD_PTR dwIoBase, DWORD dwCurrDescAddr);
+void MACvTimer0MicroSDelay(DWORD_PTR dwIoBase, UINT uDelay);
+void MACvOneShotTimer0MicroSec(DWORD_PTR dwIoBase, UINT uDelayTime);
+void MACvOneShotTimer1MicroSec(DWORD_PTR dwIoBase, UINT uDelayTime);
+
+void MACvSetMISCFifo(DWORD_PTR dwIoBase, WORD wOffset, DWORD dwData);
+
+BOOL MACbTxDMAOff (DWORD_PTR dwIoBase, UINT idx);
+
+void MACvClearBusSusInd(DWORD_PTR dwIoBase);
+void MACvEnableBusSusEn(DWORD_PTR dwIoBase);
+
+BOOL MACbFlushSYNCFifo(DWORD_PTR dwIoBase);
+BOOL MACbPSWakeup(DWORD_PTR dwIoBase);
+
+void MACvSetKeyEntry(DWORD_PTR dwIoBase, WORD wKeyCtl, UINT uEntryIdx, UINT uKeyIdx, PBYTE pbyAddr, PDWORD pdwKey, BYTE byLocalID);
+void MACvDisableKeyEntry(DWORD_PTR dwIoBase, UINT uEntryIdx);
+void MACvSetDefaultKeyEntry(DWORD_PTR dwIoBase, UINT uKeyLen, UINT uKeyIdx, PDWORD pdwKey, BYTE byLocalID);
+//void MACvEnableDefaultKey(DWORD_PTR dwIoBase, BYTE byLocalID);
+void MACvDisableDefaultKey(DWORD_PTR dwIoBase);
+void MACvSetDefaultTKIPKeyEntry(DWORD_PTR dwIoBase, UINT uKeyLen, UINT uKeyIdx, PDWORD pdwKey, BYTE byLocalID);
+void MACvSetDefaultKeyCtl(DWORD_PTR dwIoBase, WORD wKeyCtl, UINT uEntryIdx, BYTE byLocalID);
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+#endif // __MAC_H__
+
diff --git a/drivers/staging/vt6655/mib.c b/drivers/staging/vt6655/mib.c
new file mode 100644
index 0000000..3f06de1
--- /dev/null
+++ b/drivers/staging/vt6655/mib.c
@@ -0,0 +1,616 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: mib.c
+ *
+ * Purpose: Implement MIB Data Structure
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ *
+ * Functions:
+ *      STAvClearAllCounter - Clear All MIB Counter
+ *      STAvUpdateIstStatCounter - Update ISR statistic counter
+ *      STAvUpdateRDStatCounter - Update Rx statistic counter
+ *      STAvUpdateRDStatCounterEx - Update Rx statistic counter and copy rcv data
+ *      STAvUpdateTDStatCounter - Update Tx statistic counter
+ *      STAvUpdateTDStatCounterEx - Update Tx statistic counter and copy tx data
+ *      STAvUpdate802_11Counter - Update 802.11 mib counter
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__UPC_H__)
+#include "upc.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__MIB_H__)
+#include "mib.h"
+#endif
+#if !defined(__WCTL_H__)
+#include "wctl.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+
+/*---------------------  Static Definitions -------------------------*/
+static int          msglevel                =MSG_LEVEL_INFO;
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+/*
+ * Description: Clear All Statistic Counter
+ *
+ * Parameters:
+ *  In:
+ *      pStatistic  - Pointer to Statistic Counter Data Structure
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void STAvClearAllCounter (PSStatCounter pStatistic)
+{
+    // set memory to zero
+    ZERO_MEMORY(pStatistic, sizeof(SStatCounter));
+}
+
+
+/*
+ * Description: Update Isr Statistic Counter
+ *
+ * Parameters:
+ *  In:
+ *      pStatistic  - Pointer to Statistic Counter Data Structure
+ *      wisr        - Interrupt status
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void STAvUpdateIsrStatCounter (PSStatCounter pStatistic, DWORD dwIsr)
+{
+    /**********************/
+    /* ABNORMAL interrupt */
+    /**********************/
+    // not any IMR bit invoke irq
+
+    if (dwIsr == 0) {
+        pStatistic->ISRStat.dwIsrUnknown++;
+        return;
+    }
+
+//Added by Kyle
+    if (BITbIsBitOn(dwIsr, ISR_TXDMA0))               // ISR, bit0
+        pStatistic->ISRStat.dwIsrTx0OK++;             // TXDMA0 successful
+
+    if (BITbIsBitOn(dwIsr, ISR_AC0DMA))               // ISR, bit1
+        pStatistic->ISRStat.dwIsrAC0TxOK++;           // AC0DMA successful
+
+    if (BITbIsBitOn(dwIsr, ISR_BNTX))                 // ISR, bit2
+        pStatistic->ISRStat.dwIsrBeaconTxOK++;        // BeaconTx successful
+
+    if (BITbIsBitOn(dwIsr, ISR_RXDMA0))               // ISR, bit3
+        pStatistic->ISRStat.dwIsrRx0OK++;             // Rx0 successful
+
+    if (BITbIsBitOn(dwIsr, ISR_TBTT))                 // ISR, bit4
+        pStatistic->ISRStat.dwIsrTBTTInt++;           // TBTT successful
+
+    if (BITbIsBitOn(dwIsr, ISR_SOFTTIMER))            // ISR, bit6
+        pStatistic->ISRStat.dwIsrSTIMERInt++;
+
+    if (BITbIsBitOn(dwIsr, ISR_WATCHDOG))             // ISR, bit7
+        pStatistic->ISRStat.dwIsrWatchDog++;
+
+    if (BITbIsBitOn(dwIsr, ISR_FETALERR))             // ISR, bit8
+        pStatistic->ISRStat.dwIsrUnrecoverableError++;
+
+    if (BITbIsBitOn(dwIsr, ISR_SOFTINT))              // ISR, bit9
+        pStatistic->ISRStat.dwIsrSoftInterrupt++;     // software interrupt
+
+    if (BITbIsBitOn(dwIsr, ISR_MIBNEARFULL))          // ISR, bit10
+        pStatistic->ISRStat.dwIsrMIBNearfull++;
+
+    if (BITbIsBitOn(dwIsr, ISR_RXNOBUF))              // ISR, bit11
+        pStatistic->ISRStat.dwIsrRxNoBuf++;           // Rx No Buff
+
+    if (BITbIsBitOn(dwIsr, ISR_RXDMA1))               // ISR, bit12
+        pStatistic->ISRStat.dwIsrRx1OK++;             // Rx1 successful
+
+//    if (BITbIsBitOn(dwIsr, ISR_ATIMTX))               // ISR, bit13
+//        pStatistic->ISRStat.dwIsrATIMTxOK++;          // ATIMTX successful
+
+//    if (BITbIsBitOn(dwIsr, ISR_SYNCTX))               // ISR, bit14
+//        pStatistic->ISRStat.dwIsrSYNCTxOK++;          // SYNCTX successful
+
+//    if (BITbIsBitOn(dwIsr, ISR_CFPEND))               // ISR, bit18
+//        pStatistic->ISRStat.dwIsrCFPEnd++;
+
+//    if (BITbIsBitOn(dwIsr, ISR_ATIMEND))              // ISR, bit19
+//        pStatistic->ISRStat.dwIsrATIMEnd++;
+
+//    if (BITbIsBitOn(dwIsr, ISR_SYNCFLUSHOK))          // ISR, bit20
+//        pStatistic->ISRStat.dwIsrSYNCFlushOK++;
+
+    if (BITbIsBitOn(dwIsr, ISR_SOFTTIMER1))           // ISR, bit21
+        pStatistic->ISRStat.dwIsrSTIMER1Int++;
+
+}
+
+
+/*
+ * Description: Update Rx Statistic Counter
+ *
+ * Parameters:
+ *  In:
+ *      pStatistic      - Pointer to Statistic Counter Data Structure
+ *      byRSR           - Rx Status
+ *      byNewRSR        - Rx Status
+ *      pbyBuffer       - Rx Buffer
+ *      cbFrameLength   - Rx Length
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void STAvUpdateRDStatCounter (PSStatCounter pStatistic,
+                              BYTE byRSR, BYTE byNewRSR, BYTE byRxRate,
+                              PBYTE pbyBuffer, UINT cbFrameLength)
+{
+    //need change
+    PS802_11Header pHeader = (PS802_11Header)pbyBuffer;
+
+    if (BITbIsBitOn(byRSR, RSR_ADDROK))
+        pStatistic->dwRsrADDROk++;
+    if (BITbIsBitOn(byRSR, RSR_CRCOK)) {
+        pStatistic->dwRsrCRCOk++;
+
+        pStatistic->ullRsrOK++;
+
+        if (cbFrameLength >= U_ETHER_ADDR_LEN) {
+            // update counters in case that successful transmit
+            if (BITbIsBitOn(byRSR, RSR_ADDRBROAD)) {
+                pStatistic->ullRxBroadcastFrames++;
+                pStatistic->ullRxBroadcastBytes += (ULONGLONG)cbFrameLength;
+            }
+            else if (BITbIsBitOn(byRSR, RSR_ADDRMULTI)) {
+                pStatistic->ullRxMulticastFrames++;
+                pStatistic->ullRxMulticastBytes += (ULONGLONG)cbFrameLength;
+            }
+            else {
+                pStatistic->ullRxDirectedFrames++;
+                pStatistic->ullRxDirectedBytes += (ULONGLONG)cbFrameLength;
+            }
+        }
+    }
+
+    if(byRxRate==22) {
+        pStatistic->CustomStat.ullRsr11M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr11MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"11M: ALL[%d], OK[%d]:[%02x]\n", (INT)pStatistic->CustomStat.ullRsr11M, (INT)pStatistic->CustomStat.ullRsr11MCRCOk, byRSR);
+    }
+    else if(byRxRate==11) {
+        pStatistic->CustomStat.ullRsr5M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr5MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" 5M: ALL[%d], OK[%d]:[%02x]\n", (INT)pStatistic->CustomStat.ullRsr5M, (INT)pStatistic->CustomStat.ullRsr5MCRCOk, byRSR);
+    }
+    else if(byRxRate==4) {
+        pStatistic->CustomStat.ullRsr2M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr2MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" 2M: ALL[%d], OK[%d]:[%02x]\n", (INT)pStatistic->CustomStat.ullRsr2M, (INT)pStatistic->CustomStat.ullRsr2MCRCOk, byRSR);
+    }
+    else if(byRxRate==2){
+        pStatistic->CustomStat.ullRsr1M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr1MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" 1M: ALL[%d], OK[%d]:[%02x]\n", (INT)pStatistic->CustomStat.ullRsr1M, (INT)pStatistic->CustomStat.ullRsr1MCRCOk, byRSR);
+    }
+    else if(byRxRate==12){
+        pStatistic->CustomStat.ullRsr6M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr6MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" 6M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr6M, (INT)pStatistic->CustomStat.ullRsr6MCRCOk);
+    }
+    else if(byRxRate==18){
+        pStatistic->CustomStat.ullRsr9M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr9MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" 9M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr9M, (INT)pStatistic->CustomStat.ullRsr9MCRCOk);
+    }
+    else if(byRxRate==24){
+        pStatistic->CustomStat.ullRsr12M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr12MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"12M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr12M, (INT)pStatistic->CustomStat.ullRsr12MCRCOk);
+    }
+    else if(byRxRate==36){
+        pStatistic->CustomStat.ullRsr18M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr18MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"18M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr18M, (INT)pStatistic->CustomStat.ullRsr18MCRCOk);
+    }
+    else if(byRxRate==48){
+        pStatistic->CustomStat.ullRsr24M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr24MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"24M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr24M, (INT)pStatistic->CustomStat.ullRsr24MCRCOk);
+    }
+    else if(byRxRate==72){
+        pStatistic->CustomStat.ullRsr36M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr36MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"36M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr36M, (INT)pStatistic->CustomStat.ullRsr36MCRCOk);
+    }
+    else if(byRxRate==96){
+        pStatistic->CustomStat.ullRsr48M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr48MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"48M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr48M, (INT)pStatistic->CustomStat.ullRsr48MCRCOk);
+    }
+    else if(byRxRate==108){
+        pStatistic->CustomStat.ullRsr54M++;
+        if(BITbIsBitOn(byRSR, RSR_CRCOK)) {
+            pStatistic->CustomStat.ullRsr54MCRCOk++;
+        }
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"54M: ALL[%d], OK[%d]\n", (INT)pStatistic->CustomStat.ullRsr54M, (INT)pStatistic->CustomStat.ullRsr54MCRCOk);
+    }
+    else {
+    	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Unknown: Total[%d], CRCOK[%d]\n", (INT)pStatistic->dwRsrRxPacket+1, (INT)pStatistic->dwRsrCRCOk);
+    }
+
+    if (BITbIsBitOn(byRSR, RSR_BSSIDOK))
+        pStatistic->dwRsrBSSIDOk++;
+
+    if (BITbIsBitOn(byRSR, RSR_BCNSSIDOK))
+        pStatistic->dwRsrBCNSSIDOk++;
+    if (BITbIsBitOn(byRSR, RSR_IVLDLEN))  //invalid len (> 2312 byte)
+        pStatistic->dwRsrLENErr++;
+    if (BITbIsBitOn(byRSR, RSR_IVLDTYP))  //invalid packet type
+        pStatistic->dwRsrTYPErr++;
+    if (BITbIsBitOn(byRSR, (RSR_IVLDTYP | RSR_IVLDLEN)))
+        pStatistic->dwRsrErr++;
+
+    if (BITbIsBitOn(byNewRSR, NEWRSR_DECRYPTOK))
+        pStatistic->dwNewRsrDECRYPTOK++;
+    if (BITbIsBitOn(byNewRSR, NEWRSR_CFPIND))
+        pStatistic->dwNewRsrCFP++;
+    if (BITbIsBitOn(byNewRSR, NEWRSR_HWUTSF))
+        pStatistic->dwNewRsrUTSF++;
+    if (BITbIsBitOn(byNewRSR, NEWRSR_BCNHITAID))
+        pStatistic->dwNewRsrHITAID++;
+    if (BITbIsBitOn(byNewRSR, NEWRSR_BCNHITAID0))
+        pStatistic->dwNewRsrHITAID0++;
+
+    // increase rx packet count
+    pStatistic->dwRsrRxPacket++;
+    pStatistic->dwRsrRxOctet += cbFrameLength;
+
+
+    if (IS_TYPE_DATA(pbyBuffer)) {
+        pStatistic->dwRsrRxData++;
+    } else if (IS_TYPE_MGMT(pbyBuffer)){
+        pStatistic->dwRsrRxManage++;
+    } else if (IS_TYPE_CONTROL(pbyBuffer)){
+        pStatistic->dwRsrRxControl++;
+    }
+
+    if (BITbIsBitOn(byRSR, RSR_ADDRBROAD))
+        pStatistic->dwRsrBroadcast++;
+    else if (BITbIsBitOn(byRSR, RSR_ADDRMULTI))
+        pStatistic->dwRsrMulticast++;
+    else
+        pStatistic->dwRsrDirected++;
+
+    if (WLAN_GET_FC_MOREFRAG(pHeader->wFrameCtl))
+        pStatistic->dwRsrRxFragment++;
+
+    if (cbFrameLength < MIN_PACKET_LEN + 4) {
+        pStatistic->dwRsrRunt++;
+    }
+    else if (cbFrameLength == MIN_PACKET_LEN + 4) {
+        pStatistic->dwRsrRxFrmLen64++;
+    }
+    else if ((65 <= cbFrameLength) && (cbFrameLength <= 127)) {
+        pStatistic->dwRsrRxFrmLen65_127++;
+    }
+    else if ((128 <= cbFrameLength) && (cbFrameLength <= 255)) {
+        pStatistic->dwRsrRxFrmLen128_255++;
+    }
+    else if ((256 <= cbFrameLength) && (cbFrameLength <= 511)) {
+        pStatistic->dwRsrRxFrmLen256_511++;
+    }
+    else if ((512 <= cbFrameLength) && (cbFrameLength <= 1023)) {
+        pStatistic->dwRsrRxFrmLen512_1023++;
+    }
+    else if ((1024 <= cbFrameLength) && (cbFrameLength <= MAX_PACKET_LEN + 4)) {
+        pStatistic->dwRsrRxFrmLen1024_1518++;
+    } else if (cbFrameLength > MAX_PACKET_LEN + 4) {
+        pStatistic->dwRsrLong++;
+    }
+
+}
+
+
+
+/*
+ * Description: Update Rx Statistic Counter and copy Rx buffer
+ *
+ * Parameters:
+ *  In:
+ *      pStatistic      - Pointer to Statistic Counter Data Structure
+ *      byRSR           - Rx Status
+ *      byNewRSR        - Rx Status
+ *      pbyBuffer       - Rx Buffer
+ *      cbFrameLength   - Rx Length
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+
+void
+STAvUpdateRDStatCounterEx (
+    PSStatCounter   pStatistic,
+    BYTE            byRSR,
+    BYTE            byNewRSR,
+    BYTE            byRxRate,
+    PBYTE           pbyBuffer,
+    UINT            cbFrameLength
+    )
+{
+    STAvUpdateRDStatCounter(
+                    pStatistic,
+                    byRSR,
+                    byNewRSR,
+                    byRxRate,
+                    pbyBuffer,
+                    cbFrameLength
+                    );
+
+    // rx length
+    pStatistic->dwCntRxFrmLength = cbFrameLength;
+    // rx pattern, we just see 10 bytes for sample
+    MEMvCopy(pStatistic->abyCntRxPattern, (PBYTE)pbyBuffer, 10);
+}
+
+
+/*
+ * Description: Update Tx Statistic Counter
+ *
+ * Parameters:
+ *  In:
+ *      pStatistic      - Pointer to Statistic Counter Data Structure
+ *      byTSR0          - Tx Status
+ *      byTSR1          - Tx Status
+ *      pbyBuffer       - Tx Buffer
+ *      cbFrameLength   - Tx Length
+ *      uIdx            - Index of Tx DMA
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void
+STAvUpdateTDStatCounter (
+    PSStatCounter   pStatistic,
+    BYTE            byTSR0,
+    BYTE            byTSR1,
+    PBYTE           pbyBuffer,
+    UINT            cbFrameLength,
+    UINT            uIdx
+    )
+{
+    PWLAN_80211HDR_A4   pHeader;
+    PBYTE               pbyDestAddr;
+    BYTE                byTSR0_NCR = byTSR0 & TSR0_NCR;
+
+
+
+    pHeader = (PWLAN_80211HDR_A4) pbyBuffer;
+    if (WLAN_GET_FC_TODS(pHeader->wFrameCtl) == 0) {
+        pbyDestAddr = &(pHeader->abyAddr1[0]);
+    }
+    else {
+        pbyDestAddr = &(pHeader->abyAddr3[0]);
+    }
+    // increase tx packet count
+    pStatistic->dwTsrTxPacket[uIdx]++;
+    pStatistic->dwTsrTxOctet[uIdx] += cbFrameLength;
+
+    if (byTSR0_NCR != 0) {
+        pStatistic->dwTsrRetry[uIdx]++;
+        pStatistic->dwTsrTotalRetry[uIdx] += byTSR0_NCR;
+
+        if (byTSR0_NCR == 1)
+            pStatistic->dwTsrOnceRetry[uIdx]++;
+        else
+            pStatistic->dwTsrMoreThanOnceRetry[uIdx]++;
+    }
+
+    if ((byTSR1&(TSR1_TERR|TSR1_RETRYTMO|TSR1_TMO|ACK_DATA)) == 0) {
+        pStatistic->ullTsrOK[uIdx]++;
+        pStatistic->CustomStat.ullTsrAllOK =
+            (pStatistic->ullTsrOK[TYPE_AC0DMA] + pStatistic->ullTsrOK[TYPE_TXDMA0]);
+        // update counters in case that successful transmit
+        if (IS_BROADCAST_ADDRESS(pbyDestAddr)) {
+            pStatistic->ullTxBroadcastFrames[uIdx]++;
+            pStatistic->ullTxBroadcastBytes[uIdx] += (ULONGLONG)cbFrameLength;
+        }
+        else if (IS_MULTICAST_ADDRESS(pbyDestAddr)) {
+            pStatistic->ullTxMulticastFrames[uIdx]++;
+            pStatistic->ullTxMulticastBytes[uIdx] += (ULONGLONG)cbFrameLength;
+        }
+        else {
+            pStatistic->ullTxDirectedFrames[uIdx]++;
+            pStatistic->ullTxDirectedBytes[uIdx] += (ULONGLONG)cbFrameLength;
+        }
+    }
+    else {
+        if (BITbIsBitOn(byTSR1, TSR1_TERR))
+            pStatistic->dwTsrErr[uIdx]++;
+        if (BITbIsBitOn(byTSR1, TSR1_RETRYTMO))
+            pStatistic->dwTsrRetryTimeout[uIdx]++;
+        if (BITbIsBitOn(byTSR1, TSR1_TMO))
+            pStatistic->dwTsrTransmitTimeout[uIdx]++;
+        if (BITbIsBitOn(byTSR1, ACK_DATA))
+            pStatistic->dwTsrACKData[uIdx]++;
+    }
+
+    if (IS_BROADCAST_ADDRESS(pbyDestAddr))
+        pStatistic->dwTsrBroadcast[uIdx]++;
+    else if (IS_MULTICAST_ADDRESS(pbyDestAddr))
+        pStatistic->dwTsrMulticast[uIdx]++;
+    else
+        pStatistic->dwTsrDirected[uIdx]++;
+
+}
+
+
+/*
+ * Description: Update Tx Statistic Counter and copy Tx buffer
+ *
+ * Parameters:
+ *  In:
+ *      pStatistic      - Pointer to Statistic Counter Data Structure
+ *      pbyBuffer       - Tx Buffer
+ *      cbFrameLength   - Tx Length
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void
+STAvUpdateTDStatCounterEx (
+    PSStatCounter   pStatistic,
+    PBYTE           pbyBuffer,
+    DWORD           cbFrameLength
+    )
+{
+    UINT    uPktLength;
+
+    uPktLength = (UINT)cbFrameLength;
+
+    // tx length
+    pStatistic->dwCntTxBufLength = uPktLength;
+    // tx pattern, we just see 16 bytes for sample
+    MEMvCopy(pStatistic->abyCntTxPattern, pbyBuffer, 16);
+}
+
+
+/*
+ * Description: Update 802.11 mib counter
+ *
+ * Parameters:
+ *  In:
+ *      p802_11Counter  - Pointer to 802.11 mib counter
+ *      pStatistic      - Pointer to Statistic Counter Data Structure
+ *      dwCounter       - hardware counter for 802.11 mib
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void
+STAvUpdate802_11Counter(
+    PSDot11Counters         p802_11Counter,
+    PSStatCounter           pStatistic,
+    DWORD                   dwCounter
+    )
+{
+    //p802_11Counter->TransmittedFragmentCount
+    p802_11Counter->MulticastTransmittedFrameCount = (ULONGLONG) (pStatistic->dwTsrBroadcast[TYPE_AC0DMA] +
+                                                                  pStatistic->dwTsrBroadcast[TYPE_TXDMA0] +
+                                                                  pStatistic->dwTsrMulticast[TYPE_AC0DMA] +
+                                                                  pStatistic->dwTsrMulticast[TYPE_TXDMA0]);
+    p802_11Counter->FailedCount = (ULONGLONG) (pStatistic->dwTsrErr[TYPE_AC0DMA] + pStatistic->dwTsrErr[TYPE_TXDMA0]);
+    p802_11Counter->RetryCount = (ULONGLONG) (pStatistic->dwTsrRetry[TYPE_AC0DMA] + pStatistic->dwTsrRetry[TYPE_TXDMA0]);
+    p802_11Counter->MultipleRetryCount = (ULONGLONG) (pStatistic->dwTsrMoreThanOnceRetry[TYPE_AC0DMA] +
+                                                          pStatistic->dwTsrMoreThanOnceRetry[TYPE_TXDMA0]);
+    //p802_11Counter->FrameDuplicateCount
+    p802_11Counter->RTSSuccessCount += (ULONGLONG)  (dwCounter & 0x000000ff);
+    p802_11Counter->RTSFailureCount += (ULONGLONG) ((dwCounter & 0x0000ff00) >> 8);
+    p802_11Counter->ACKFailureCount += (ULONGLONG) ((dwCounter & 0x00ff0000) >> 16);
+    p802_11Counter->FCSErrorCount +=   (ULONGLONG) ((dwCounter & 0xff000000) >> 24);
+    //p802_11Counter->ReceivedFragmentCount
+    p802_11Counter->MulticastReceivedFrameCount = (ULONGLONG) (pStatistic->dwRsrBroadcast +
+                                                               pStatistic->dwRsrMulticast);
+}
+
+/*
+ * Description: Clear 802.11 mib counter
+ *
+ * Parameters:
+ *  In:
+ *      p802_11Counter  - Pointer to 802.11 mib counter
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void
+STAvClear802_11Counter(PSDot11Counters p802_11Counter)
+{
+    // set memory to zero
+    ZERO_MEMORY(p802_11Counter, sizeof(SDot11Counters));
+}
diff --git a/drivers/staging/vt6655/mib.h b/drivers/staging/vt6655/mib.h
new file mode 100644
index 0000000..b4e1c4a
--- /dev/null
+++ b/drivers/staging/vt6655/mib.h
@@ -0,0 +1,399 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: mib.h
+ *
+ * Purpose: Implement MIB Data Structure
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ *
+ */
+
+#ifndef __MIB_H__
+#define __MIB_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__DESC_H__)
+#include "desc.h"
+#endif
+
+
+
+//#define ULONGLONG   ULONG
+
+/*---------------------  Export Definitions -------------------------*/
+//
+// 802.11 counter
+//
+
+typedef struct tagSDot11Counters {
+    ULONG       Length;             // Length of structure
+    ULONGLONG   TransmittedFragmentCount;
+    ULONGLONG   MulticastTransmittedFrameCount;
+    ULONGLONG   FailedCount;
+    ULONGLONG   RetryCount;
+    ULONGLONG   MultipleRetryCount;
+    ULONGLONG   RTSSuccessCount;
+    ULONGLONG   RTSFailureCount;
+    ULONGLONG   ACKFailureCount;
+    ULONGLONG   FrameDuplicateCount;
+    ULONGLONG   ReceivedFragmentCount;
+    ULONGLONG   MulticastReceivedFrameCount;
+    ULONGLONG   FCSErrorCount;
+    ULONGLONG   TKIPLocalMICFailures;
+    ULONGLONG   TKIPRemoteMICFailures;
+    ULONGLONG   TKIPICVErrors;
+    ULONGLONG   TKIPCounterMeasuresInvoked;
+    ULONGLONG   TKIPReplays;
+    ULONGLONG   CCMPFormatErrors;
+    ULONGLONG   CCMPReplays;
+    ULONGLONG   CCMPDecryptErrors;
+    ULONGLONG   FourWayHandshakeFailures;
+//    ULONGLONG   WEPUndecryptableCount;
+//    ULONGLONG   WEPICVErrorCount;
+//    ULONGLONG   DecryptSuccessCount;
+//    ULONGLONG   DecryptFailureCount;
+} SDot11Counters, DEF* PSDot11Counters;
+
+
+//
+// MIB2 counter
+//
+typedef struct tagSMib2Counter {
+    LONG    ifIndex;
+    TCHAR   ifDescr[256];               // max size 255 plus zero ending
+                                        // e.g. "interface 1"
+    LONG    ifType;
+    LONG    ifMtu;
+    DWORD   ifSpeed;
+    BYTE    ifPhysAddress[U_ETHER_ADDR_LEN];
+    LONG    ifAdminStatus;
+    LONG    ifOperStatus;
+    DWORD   ifLastChange;
+    DWORD   ifInOctets;
+    DWORD   ifInUcastPkts;
+    DWORD   ifInNUcastPkts;
+    DWORD   ifInDiscards;
+    DWORD   ifInErrors;
+    DWORD   ifInUnknownProtos;
+    DWORD   ifOutOctets;
+    DWORD   ifOutUcastPkts;
+    DWORD   ifOutNUcastPkts;
+    DWORD   ifOutDiscards;
+    DWORD   ifOutErrors;
+    DWORD   ifOutQLen;
+    DWORD   ifSpecific;
+} SMib2Counter, DEF* PSMib2Counter;
+
+// Value in the ifType entry
+//#define ETHERNETCSMACD      6           //
+#define WIRELESSLANIEEE80211b      6           //
+
+// Value in the ifAdminStatus/ifOperStatus entry
+#define UP                  1           //
+#define DOWN                2           //
+#define TESTING             3           //
+
+
+//
+// RMON counter
+//
+typedef struct tagSRmonCounter {
+    LONG    etherStatsIndex;
+    DWORD   etherStatsDataSource;
+    DWORD   etherStatsDropEvents;
+    DWORD   etherStatsOctets;
+    DWORD   etherStatsPkts;
+    DWORD   etherStatsBroadcastPkts;
+    DWORD   etherStatsMulticastPkts;
+    DWORD   etherStatsCRCAlignErrors;
+    DWORD   etherStatsUndersizePkts;
+    DWORD   etherStatsOversizePkts;
+    DWORD   etherStatsFragments;
+    DWORD   etherStatsJabbers;
+    DWORD   etherStatsCollisions;
+    DWORD   etherStatsPkt64Octets;
+    DWORD   etherStatsPkt65to127Octets;
+    DWORD   etherStatsPkt128to255Octets;
+    DWORD   etherStatsPkt256to511Octets;
+    DWORD   etherStatsPkt512to1023Octets;
+    DWORD   etherStatsPkt1024to1518Octets;
+    DWORD   etherStatsOwners;
+    DWORD   etherStatsStatus;
+} SRmonCounter, DEF* PSRmonCounter;
+
+//
+// Custom counter
+//
+typedef struct tagSCustomCounters {
+    ULONG       Length;
+
+    ULONGLONG   ullTsrAllOK;
+
+    ULONGLONG   ullRsr11M;
+    ULONGLONG   ullRsr5M;
+    ULONGLONG   ullRsr2M;
+    ULONGLONG   ullRsr1M;
+
+    ULONGLONG   ullRsr11MCRCOk;
+    ULONGLONG   ullRsr5MCRCOk;
+    ULONGLONG   ullRsr2MCRCOk;
+    ULONGLONG   ullRsr1MCRCOk;
+
+    ULONGLONG   ullRsr54M;
+    ULONGLONG   ullRsr48M;
+    ULONGLONG   ullRsr36M;
+    ULONGLONG   ullRsr24M;
+    ULONGLONG   ullRsr18M;
+    ULONGLONG   ullRsr12M;
+    ULONGLONG   ullRsr9M;
+    ULONGLONG   ullRsr6M;
+
+    ULONGLONG   ullRsr54MCRCOk;
+    ULONGLONG   ullRsr48MCRCOk;
+    ULONGLONG   ullRsr36MCRCOk;
+    ULONGLONG   ullRsr24MCRCOk;
+    ULONGLONG   ullRsr18MCRCOk;
+    ULONGLONG   ullRsr12MCRCOk;
+    ULONGLONG   ullRsr9MCRCOk;
+    ULONGLONG   ullRsr6MCRCOk;
+
+} SCustomCounters, DEF* PSCustomCounters;
+
+
+//
+// Custom counter
+//
+typedef struct tagSISRCounters {
+    ULONG   Length;
+
+    DWORD   dwIsrTx0OK;
+    DWORD   dwIsrAC0TxOK;
+    DWORD   dwIsrBeaconTxOK;
+    DWORD   dwIsrRx0OK;
+    DWORD   dwIsrTBTTInt;
+    DWORD   dwIsrSTIMERInt;
+    DWORD   dwIsrWatchDog;
+    DWORD   dwIsrUnrecoverableError;
+    DWORD   dwIsrSoftInterrupt;
+    DWORD   dwIsrMIBNearfull;
+    DWORD   dwIsrRxNoBuf;
+
+    DWORD   dwIsrUnknown;               // unknown interrupt count
+
+    DWORD   dwIsrRx1OK;
+    DWORD   dwIsrATIMTxOK;
+    DWORD   dwIsrSYNCTxOK;
+    DWORD   dwIsrCFPEnd;
+    DWORD   dwIsrATIMEnd;
+    DWORD   dwIsrSYNCFlushOK;
+    DWORD   dwIsrSTIMER1Int;
+    /////////////////////////////////////
+} SISRCounters, DEF* PSISRCounters;
+
+
+// Value in the etherStatsStatus entry
+#define VALID               1           //
+#define CREATE_REQUEST      2           //
+#define UNDER_CREATION      3           //
+#define INVALID             4           //
+
+//#define MAX_RATE            12
+//
+// statistic counter
+//
+typedef struct tagSStatCounter {
+    //
+    // ISR status count
+    //
+
+
+    // RSR status count
+    //
+    DWORD   dwRsrFrmAlgnErr;
+    DWORD   dwRsrErr;
+    DWORD   dwRsrCRCErr;
+    DWORD   dwRsrCRCOk;
+    DWORD   dwRsrBSSIDOk;
+    DWORD   dwRsrADDROk;
+    DWORD   dwRsrBCNSSIDOk;
+    DWORD   dwRsrLENErr;
+    DWORD   dwRsrTYPErr;
+
+    DWORD   dwNewRsrDECRYPTOK;
+    DWORD   dwNewRsrCFP;
+    DWORD   dwNewRsrUTSF;
+    DWORD   dwNewRsrHITAID;
+    DWORD   dwNewRsrHITAID0;
+
+    DWORD   dwRsrLong;
+    DWORD   dwRsrRunt;
+
+    DWORD   dwRsrRxControl;
+    DWORD   dwRsrRxData;
+    DWORD   dwRsrRxManage;
+
+    DWORD   dwRsrRxPacket;
+    DWORD   dwRsrRxOctet;
+    DWORD   dwRsrBroadcast;
+    DWORD   dwRsrMulticast;
+    DWORD   dwRsrDirected;
+    // 64-bit OID
+    ULONGLONG   ullRsrOK;
+
+    // for some optional OIDs (64 bits) and DMI support
+    ULONGLONG   ullRxBroadcastBytes;
+    ULONGLONG   ullRxMulticastBytes;
+    ULONGLONG   ullRxDirectedBytes;
+    ULONGLONG   ullRxBroadcastFrames;
+    ULONGLONG   ullRxMulticastFrames;
+    ULONGLONG   ullRxDirectedFrames;
+
+    DWORD   dwRsrRxFragment;
+    DWORD   dwRsrRxFrmLen64;
+    DWORD   dwRsrRxFrmLen65_127;
+    DWORD   dwRsrRxFrmLen128_255;
+    DWORD   dwRsrRxFrmLen256_511;
+    DWORD   dwRsrRxFrmLen512_1023;
+    DWORD   dwRsrRxFrmLen1024_1518;
+
+    // TSR status count
+    //
+    DWORD   dwTsrTotalRetry[TYPE_MAXTD];        // total collision retry count
+    DWORD   dwTsrOnceRetry[TYPE_MAXTD];         // this packet only occur one collision
+    DWORD   dwTsrMoreThanOnceRetry[TYPE_MAXTD]; // this packet occur more than one collision
+    DWORD   dwTsrRetry[TYPE_MAXTD];             // this packet has ever occur collision,
+                                         // that is (dwTsrOnceCollision0 + dwTsrMoreThanOnceCollision0)
+    DWORD   dwTsrACKData[TYPE_MAXTD];
+    DWORD   dwTsrErr[TYPE_MAXTD];
+    DWORD   dwAllTsrOK[TYPE_MAXTD];
+    DWORD   dwTsrRetryTimeout[TYPE_MAXTD];
+    DWORD   dwTsrTransmitTimeout[TYPE_MAXTD];
+
+    DWORD   dwTsrTxPacket[TYPE_MAXTD];
+    DWORD   dwTsrTxOctet[TYPE_MAXTD];
+    DWORD   dwTsrBroadcast[TYPE_MAXTD];
+    DWORD   dwTsrMulticast[TYPE_MAXTD];
+    DWORD   dwTsrDirected[TYPE_MAXTD];
+
+    // RD/TD count
+    DWORD   dwCntRxFrmLength;
+    DWORD   dwCntTxBufLength;
+
+    BYTE    abyCntRxPattern[16];
+    BYTE    abyCntTxPattern[16];
+
+
+
+    // Software check....
+    DWORD   dwCntRxDataErr;             // rx buffer data software compare CRC err count
+    DWORD   dwCntDecryptErr;            // rx buffer data software compare CRC err count
+    DWORD   dwCntRxICVErr;              // rx buffer data software compare CRC err count
+    UINT    idxRxErrorDesc[TYPE_MAXRD]; // index for rx data error RD
+
+    // 64-bit OID
+    ULONGLONG   ullTsrOK[TYPE_MAXTD];
+
+    // for some optional OIDs (64 bits) and DMI support
+    ULONGLONG   ullTxBroadcastFrames[TYPE_MAXTD];
+    ULONGLONG   ullTxMulticastFrames[TYPE_MAXTD];
+    ULONGLONG   ullTxDirectedFrames[TYPE_MAXTD];
+    ULONGLONG   ullTxBroadcastBytes[TYPE_MAXTD];
+    ULONGLONG   ullTxMulticastBytes[TYPE_MAXTD];
+    ULONGLONG   ullTxDirectedBytes[TYPE_MAXTD];
+
+//    DWORD   dwTxRetryCount[8];
+    //
+    // ISR status count
+    //
+    SISRCounters ISRStat;
+
+    SCustomCounters CustomStat;
+
+   #ifdef Calcu_LinkQual
+       //Tx count:
+    ULONG TxNoRetryOkCount;         //success tx no retry !
+    ULONG TxRetryOkCount;              //sucess tx but retry !
+    ULONG TxFailCount;                      //fail tx ?
+      //Rx count:
+    ULONG RxOkCnt;                          //sucess rx !
+    ULONG RxFcsErrCnt;                    //fail rx ?
+      //statistic
+    ULONG SignalStren;
+    ULONG LinkQuality;
+   #endif
+} SStatCounter, DEF* PSStatCounter;
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+
+void STAvClearAllCounter(PSStatCounter pStatistic);
+
+void STAvUpdateIsrStatCounter(PSStatCounter pStatistic, DWORD dwIsr);
+
+void STAvUpdateRDStatCounter(PSStatCounter pStatistic,
+                              BYTE byRSR, BYTE byNewRSR, BYTE byRxRate,
+                              PBYTE pbyBuffer, UINT cbFrameLength);
+
+void STAvUpdateRDStatCounterEx(PSStatCounter pStatistic,
+                              BYTE byRSR, BYTE byNewRsr, BYTE byRxRate,
+                              PBYTE pbyBuffer, UINT cbFrameLength);
+
+void STAvUpdateTDStatCounter(PSStatCounter pStatistic,
+                             BYTE byTSR0, BYTE byTSR1,
+                             PBYTE pbyBuffer, UINT cbFrameLength, UINT uIdx );
+
+void STAvUpdateTDStatCounterEx(
+    PSStatCounter   pStatistic,
+    PBYTE           pbyBuffer,
+    DWORD           cbFrameLength
+    );
+
+void STAvUpdate802_11Counter(
+    PSDot11Counters p802_11Counter,
+    PSStatCounter   pStatistic,
+    DWORD           dwCounter
+    );
+
+void STAvClear802_11Counter(PSDot11Counters p802_11Counter);
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+
+#endif // __MIB_H__
+
+
+
diff --git a/drivers/staging/vt6655/michael.c b/drivers/staging/vt6655/michael.c
new file mode 100644
index 0000000..7bda4c1
--- /dev/null
+++ b/drivers/staging/vt6655/michael.c
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: michael.cpp
+ *
+ * Purpose: The implementation of LIST data structure.
+ *
+ * Author: Kyle Hsu
+ *
+ * Date: Sep 4, 2002
+ *
+ * Functions:
+ *      s_dwGetUINT32 - Convert from BYTE[] to DWORD in a portable way
+ *      s_vPutUINT32 - Convert from DWORD to BYTE[] in a portable way
+ *      s_vClear - Reset the state to the empty message.
+ *      s_vSetKey - Set the key.
+ *      MIC_vInit - Set the key.
+ *      s_vAppendByte - Append the byte to our word-sized buffer.
+ *      MIC_vAppend - call s_vAppendByte.
+ *      MIC_vGetMIC - Append the minimum padding and call s_vAppendByte.
+ *
+ * Revision History:
+ *
+ */
+
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__MICHAEL_H__)
+#include "michael.h"
+#endif
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+/*---------------------  Static Functions  --------------------------*/
+/*
+static DWORD s_dwGetUINT32(BYTE * p);         // Get DWORD from 4 bytes LSByte first
+static VOID s_vPutUINT32(BYTE* p, DWORD val); // Put DWORD into 4 bytes LSByte first
+*/
+static VOID s_vClear(void);                       // Clear the internal message,
+                                              // resets the object to the state just after construction.
+static VOID s_vSetKey(DWORD dwK0, DWORD dwK1);
+static VOID s_vAppendByte(BYTE b);            // Add a single byte to the internal message
+
+/*---------------------  Export Variables  --------------------------*/
+static DWORD  L, R;           // Current state
+
+static DWORD  K0, K1;         // Key
+static DWORD  M;              // Message accumulator (single word)
+static UINT   nBytesInM;      // # bytes in M
+
+/*---------------------  Export Functions  --------------------------*/
+
+/*
+static DWORD s_dwGetUINT32 (BYTE * p)
+// Convert from BYTE[] to DWORD in a portable way
+{
+    DWORD res = 0;
+    UINT i;
+    for(i=0; i<4; i++ )
+    {
+        res |= (*p++) << (8*i);
+    }
+    return res;
+}
+
+static VOID s_vPutUINT32 (BYTE* p, DWORD val)
+// Convert from DWORD to BYTE[] in a portable way
+{
+    UINT i;
+    for(i=0; i<4; i++ )
+    {
+        *p++ = (BYTE) (val & 0xff);
+        val >>= 8;
+    }
+}
+*/
+
+static VOID s_vClear (void)
+{
+    // Reset the state to the empty message.
+    L = K0;
+    R = K1;
+    nBytesInM = 0;
+    M = 0;
+}
+
+static VOID s_vSetKey (DWORD dwK0, DWORD dwK1)
+{
+    // Set the key
+    K0 = dwK0;
+    K1 = dwK1;
+    // and reset the message
+    s_vClear();
+}
+
+static VOID s_vAppendByte (BYTE b)
+{
+    // Append the byte to our word-sized buffer
+    M |= b << (8*nBytesInM);
+    nBytesInM++;
+    // Process the word if it is full.
+    if( nBytesInM >= 4 )
+    {
+        L ^= M;
+        R ^= ROL32( L, 17 );
+        L += R;
+        R ^= ((L & 0xff00ff00) >> 8) | ((L & 0x00ff00ff) << 8);
+        L += R;
+        R ^= ROL32( L, 3 );
+        L += R;
+        R ^= ROR32( L, 2 );
+        L += R;
+        // Clear the buffer
+        M = 0;
+        nBytesInM = 0;
+    }
+}
+
+VOID MIC_vInit (DWORD dwK0, DWORD dwK1)
+{
+    // Set the key
+    s_vSetKey(dwK0, dwK1);
+}
+
+
+VOID MIC_vUnInit (void)
+{
+    // Wipe the key material
+    K0 = 0;
+    K1 = 0;
+
+    // And the other fields as well.
+    //Note that this sets (L,R) to (K0,K1) which is just fine.
+    s_vClear();
+}
+
+VOID MIC_vAppend (PBYTE src, UINT nBytes)
+{
+    // This is simple
+    while (nBytes > 0)
+    {
+        s_vAppendByte(*src++);
+        nBytes--;
+    }
+}
+
+VOID MIC_vGetMIC (PDWORD pdwL, PDWORD pdwR)
+{
+    // Append the minimum padding
+    s_vAppendByte(0x5a);
+    s_vAppendByte(0);
+    s_vAppendByte(0);
+    s_vAppendByte(0);
+    s_vAppendByte(0);
+    // and then zeroes until the length is a multiple of 4
+    while( nBytesInM != 0 )
+    {
+        s_vAppendByte(0);
+    }
+    // The s_vAppendByte function has already computed the result.
+    *pdwL = L;
+    *pdwR = R;
+    // Reset to the empty message.
+    s_vClear();
+}
+
diff --git a/drivers/staging/vt6655/michael.h b/drivers/staging/vt6655/michael.h
new file mode 100644
index 0000000..62a24a6
--- /dev/null
+++ b/drivers/staging/vt6655/michael.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: Michael.h
+ *
+ * Purpose: Reference implementation for Michael
+ *          written by Niels Ferguson
+ *
+ * Author: Kyle Hsu
+ *
+ * Date: Jan 2, 2003
+ *
+ */
+
+
+#ifndef __MICHAEL_H__
+#define __MICHAEL_H__
+
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+/*---------------------  Export Definitions -------------------------*/
+
+/*---------------------  Export Types  ------------------------------*/
+
+VOID MIC_vInit(DWORD dwK0, DWORD dwK1);
+
+VOID MIC_vUnInit(void);
+
+// Append bytes to the message to be MICed
+VOID MIC_vAppend(PBYTE src, UINT nBytes);
+
+// Get the MIC result. Destination should accept 8 bytes of result.
+// This also resets the message to empty.
+VOID MIC_vGetMIC(PDWORD pdwL, PDWORD pdwR);
+
+/*---------------------  Export Macros ------------------------------*/
+
+// Rotation functions on 32 bit values
+#define ROL32( A, n ) \
+ ( ((A) << (n)) | ( ((A)>>(32-(n)))  & ( (1UL << (n)) - 1 ) ) )
+#define ROR32( A, n ) ROL32( (A), 32-(n) )
+
+#endif //__MICHAEL_H__
+
+
diff --git a/drivers/staging/vt6655/power.c b/drivers/staging/vt6655/power.c
new file mode 100644
index 0000000..edd8336
--- /dev/null
+++ b/drivers/staging/vt6655/power.c
@@ -0,0 +1,441 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: power.c
+ *
+ * Purpose: Handles 802.11 power managment  functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: July 17, 2002
+ *
+ * Functions:
+ *      PSvEnablePowerSaving - Enable Power Saving Mode
+ *      PSvDiasblePowerSaving - Disable Power Saving Mode
+ *      PSbConsiderPowerDown - Decide if we can Power Down
+ *      PSvSendPSPOLL - Send PS-POLL packet
+ *      PSbSendNullPacket - Send Null packet
+ *      PSbIsNextTBTTWakeUp - Decide if we need to wake up at next Beacon
+ *
+ * Revision History:
+ *
+ */
+
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__WMGR_H__)
+#include "wmgr.h"
+#endif
+#if !defined(__POWER_H__)
+#include "power.h"
+#endif
+#if !defined(__WCMD_H__)
+#include "wcmd.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__RXTX_H__)
+#include "rxtx.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+
+
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+
+
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+static int          msglevel                =MSG_LEVEL_INFO;
+/*---------------------  Static Functions  --------------------------*/
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+/*+
+ *
+ * Routine Description:
+ * Enable hw power saving functions
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+VOID
+PSvEnablePowerSaving(
+    IN HANDLE hDeviceContext,
+    IN WORD wListenInterval
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    WORD            wAID = pMgmt->wCurrAID | BIT14 | BIT15;
+
+    // set period of power up before TBTT
+    VNSvOutPortW(pDevice->PortOffset + MAC_REG_PWBT, C_PWBT);
+    if (pDevice->eOPMode != OP_MODE_ADHOC) {
+        // set AID
+        VNSvOutPortW(pDevice->PortOffset + MAC_REG_AIDATIM, wAID);
+    } else {
+    	// set ATIM Window
+        MACvWriteATIMW(pDevice->PortOffset, pMgmt->wCurrATIMWindow);
+    }
+    // Set AutoSleep
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_PSCFG, PSCFG_AUTOSLEEP);
+    // Set HWUTSF
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_TFTCTL, TFTCTL_HWUTSF);
+
+    if (wListenInterval >= 2) {
+        // clear always listen beacon
+        MACvRegBitsOff(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_ALBCN);
+        //pDevice->wCFG &= ~CFG_ALB;
+        // first time set listen next beacon
+        MACvRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_LNBCN);
+        pMgmt->wCountToWakeUp = wListenInterval;
+    }
+    else {
+        // always listen beacon
+        MACvRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_ALBCN);
+        //pDevice->wCFG |= CFG_ALB;
+        pMgmt->wCountToWakeUp = 0;
+    }
+
+    // enable power saving hw function
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PSEN);
+    pDevice->bEnablePSMode = TRUE;
+
+    if (pDevice->eOPMode == OP_MODE_ADHOC) {
+//        bMgrPrepareBeaconToSend((HANDLE)pDevice, pMgmt);
+    }
+    // We don't send null pkt in ad hoc mode since beacon will handle this.
+    else if (pDevice->eOPMode == OP_MODE_INFRASTRUCTURE) {
+        PSbSendNullPacket(pDevice);
+    }
+    pDevice->bPWBitOn = TRUE;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "PS:Power Saving Mode Enable... \n");
+    return;
+}
+
+
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ * Disable hw power saving functions
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+PSvDisablePowerSaving(
+    IN HANDLE hDeviceContext
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+//    PSMgmtObject    pMgmt = pDevice->pMgmt;
+
+    // disable power saving hw function
+    MACbPSWakeup(pDevice->PortOffset);
+    //clear AutoSleep
+    MACvRegBitsOff(pDevice->PortOffset, MAC_REG_PSCFG, PSCFG_AUTOSLEEP);
+    //clear HWUTSF
+    MACvRegBitsOff(pDevice->PortOffset, MAC_REG_TFTCTL, TFTCTL_HWUTSF);
+    // set always listen beacon
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_ALBCN);
+
+    pDevice->bEnablePSMode = FALSE;
+
+    if (pDevice->eOPMode == OP_MODE_INFRASTRUCTURE) {
+        PSbSendNullPacket(pDevice);
+    }
+    pDevice->bPWBitOn = FALSE;
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ * Consider to power down when no more packets to tx or rx.
+ *
+ * Return Value:
+ *    TRUE, if power down success
+ *    FALSE, if fail
+-*/
+
+
+BOOL
+PSbConsiderPowerDown(
+    IN HANDLE hDeviceContext,
+    IN BOOL bCheckRxDMA,
+    IN BOOL bCheckCountToWakeUp
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    UINT            uIdx;
+
+    // check if already in Doze mode
+    if (MACbIsRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PS))
+        return TRUE;
+
+    if (pMgmt->eCurrMode != WMAC_MODE_IBSS_STA) {
+        // check if in TIM wake period
+        if (pMgmt->bInTIMWake)
+            return FALSE;
+    }
+
+    // check scan state
+    if (pDevice->bCmdRunning)
+        return FALSE;
+
+    // Froce PSEN on
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PSEN);
+
+    // check if all TD are empty,
+    for (uIdx = 0; uIdx < TYPE_MAXTD; uIdx ++) {
+        if (pDevice->iTDUsed[uIdx] != 0)
+            return FALSE;
+    }
+
+    // check if rx isr is clear
+    if (bCheckRxDMA &&
+        ((pDevice->dwIsr& ISR_RXDMA0) != 0) &&
+        ((pDevice->dwIsr & ISR_RXDMA1) != 0)){
+        return FALSE;
+    };
+
+    if (pMgmt->eCurrMode != WMAC_MODE_IBSS_STA) {
+        if (bCheckCountToWakeUp &&
+           (pMgmt->wCountToWakeUp == 0 || pMgmt->wCountToWakeUp == 1)) {
+             return FALSE;
+        }
+    }
+
+    // no Tx, no Rx isr, now go to Doze
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_GO2DOZE);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Go to Doze ZZZZZZZZZZZZZZZ\n");
+    return TRUE;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ * Send PS-POLL packet
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+
+VOID
+PSvSendPSPOLL(
+    IN HANDLE hDeviceContext
+    )
+{
+    PSDevice            pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject        pMgmt = pDevice->pMgmt;
+    PSTxMgmtPacket      pTxPacket = NULL;
+
+
+    memset(pMgmt->pbyPSPacketPool, 0, sizeof(STxMgmtPacket) + WLAN_HDR_ADDR2_LEN);
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyPSPacketPool;
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    pTxPacket->p80211Header->sA2.wFrameCtl = cpu_to_le16(
+         (
+         WLAN_SET_FC_FTYPE(WLAN_TYPE_CTL) |
+         WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_PSPOLL) |
+         WLAN_SET_FC_PWRMGT(0)
+         ));
+    pTxPacket->p80211Header->sA2.wDurationID = pMgmt->wCurrAID | BIT14 | BIT15;
+    memcpy(pTxPacket->p80211Header->sA2.abyAddr1, pMgmt->abyCurrBSSID, WLAN_ADDR_LEN);
+    memcpy(pTxPacket->p80211Header->sA2.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    pTxPacket->cbMPDULen = WLAN_HDR_ADDR2_LEN;
+    pTxPacket->cbPayloadLen = 0;
+    // send the frame
+    if (csMgmt_xmit(pDevice, pTxPacket) != CMD_STATUS_PENDING) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Send PS-Poll packet failed..\n");
+    }
+    else {
+//        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Send PS-Poll packet success..\n");
+    };
+
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ * Send NULL packet to AP for notification power state of STA
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+BOOL
+PSbSendNullPacket(
+    IN HANDLE hDeviceContext
+    )
+{
+    PSDevice            pDevice = (PSDevice)hDeviceContext;
+    PSTxMgmtPacket      pTxPacket = NULL;
+    PSMgmtObject        pMgmt = pDevice->pMgmt;
+    UINT                uIdx;
+
+
+    if (pDevice->bLinkPass == FALSE) {
+        return FALSE;
+    }
+    #ifdef TxInSleep
+     if ((pDevice->bEnablePSMode == FALSE) &&
+	  (pDevice->fTxDataInSleep == FALSE)){
+        return FALSE;
+    }
+#else
+    if (pDevice->bEnablePSMode == FALSE) {
+        return FALSE;
+    }
+#endif
+    if (pDevice->bEnablePSMode) {
+        for (uIdx = 0; uIdx < TYPE_MAXTD; uIdx ++) {
+            if (pDevice->iTDUsed[uIdx] != 0)
+                return FALSE;
+        }
+    }
+
+    memset(pMgmt->pbyPSPacketPool, 0, sizeof(STxMgmtPacket) + WLAN_NULLDATA_FR_MAXLEN);
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyPSPacketPool;
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+
+    if (pDevice->bEnablePSMode) {
+
+        pTxPacket->p80211Header->sA3.wFrameCtl = cpu_to_le16(
+             (
+            WLAN_SET_FC_FTYPE(WLAN_TYPE_DATA) |
+            WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_NULL) |
+            WLAN_SET_FC_PWRMGT(1)
+            ));
+    }
+    else {
+        pTxPacket->p80211Header->sA3.wFrameCtl = cpu_to_le16(
+             (
+            WLAN_SET_FC_FTYPE(WLAN_TYPE_DATA) |
+            WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_NULL) |
+            WLAN_SET_FC_PWRMGT(0)
+            ));
+    }
+
+    if(pMgmt->eCurrMode != WMAC_MODE_IBSS_STA) {
+        pTxPacket->p80211Header->sA3.wFrameCtl |= cpu_to_le16((WORD)WLAN_SET_FC_TODS(1));
+    }
+
+    memcpy(pTxPacket->p80211Header->sA3.abyAddr1, pMgmt->abyCurrBSSID, WLAN_ADDR_LEN);
+    memcpy(pTxPacket->p80211Header->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy(pTxPacket->p80211Header->sA3.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+    pTxPacket->cbMPDULen = WLAN_HDR_ADDR3_LEN;
+    pTxPacket->cbPayloadLen = 0;
+    // send the frame
+    if (csMgmt_xmit(pDevice, pTxPacket) != CMD_STATUS_PENDING) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Send Null Packet failed !\n");
+        return FALSE;
+    }
+    else {
+
+//            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Send Null Packet success....\n");
+    }
+
+
+    return TRUE ;
+}
+
+/*+
+ *
+ * Routine Description:
+ * Check if Next TBTT must wake up
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+BOOL
+PSbIsNextTBTTWakeUp(
+    IN HANDLE hDeviceContext
+    )
+{
+
+    PSDevice         pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject        pMgmt = pDevice->pMgmt;
+    BOOL                bWakeUp = FALSE;
+
+    if (pMgmt->wListenInterval >= 2) {
+        if (pMgmt->wCountToWakeUp == 0) {
+            pMgmt->wCountToWakeUp = pMgmt->wListenInterval;
+        }
+
+        pMgmt->wCountToWakeUp --;
+
+        if (pMgmt->wCountToWakeUp == 1) {
+            // Turn on wake up to listen next beacon
+            MACvRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_LNBCN);
+            bWakeUp = TRUE;
+        }
+
+    }
+
+    return bWakeUp;
+}
+
diff --git a/drivers/staging/vt6655/power.h b/drivers/staging/vt6655/power.h
new file mode 100644
index 0000000..a01e7e9
--- /dev/null
+++ b/drivers/staging/vt6655/power.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: power.h
+ *
+ * Purpose: Handles 802.11 power managment  functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: July 17, 2002
+ *
+ */
+
+#ifndef __POWER_H__
+#define __POWER_H__
+
+
+/*---------------------  Export Definitions -------------------------*/
+#define     C_PWBT                   1000      // micro sec. power up before TBTT
+#define     PS_FAST_INTERVAL         1         // Fast power saving listen interval
+#define     PS_MAX_INTERVAL          4         // MAX power saving listen interval
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Types  ------------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+// IN PSDevice pDevice
+// IN PSDevice hDeviceContext
+
+BOOL
+PSbConsiderPowerDown(
+    IN HANDLE hDeviceContext,
+    IN BOOL bCheckRxDMA,
+    IN BOOL bCheckCountToWakeUp
+    );
+
+VOID
+PSvDisablePowerSaving(
+    IN HANDLE hDeviceContext
+    );
+
+VOID
+PSvEnablePowerSaving(
+    IN HANDLE hDeviceContext,
+    IN WORD wListenInterval
+    );
+
+VOID
+PSvSendPSPOLL(
+    IN HANDLE hDeviceContext
+    );
+
+BOOL
+PSbSendNullPacket(
+    IN HANDLE hDeviceContext
+    );
+
+BOOL
+PSbIsNextTBTTWakeUp(
+    IN HANDLE hDeviceContext
+    );
+
+#endif //__POWER_H__
diff --git a/drivers/staging/vt6655/rc4.c b/drivers/staging/vt6655/rc4.c
new file mode 100644
index 0000000..0345e32
--- /dev/null
+++ b/drivers/staging/vt6655/rc4.c
@@ -0,0 +1,86 @@
+/*
+ * File: rc4.c
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Purpose:
+ *
+ * Functions:
+ *
+ * Revision History:
+ *
+ * Author: Kyle Hsu
+ *
+ * Date: Sep 4, 2002
+ *
+ */
+
+#if !defined(__RC4_H__)
+#include "rc4.h"
+#endif
+
+VOID rc4_init(PRC4Ext pRC4, PBYTE pbyKey, UINT cbKey_len)
+{
+    UINT  ust1, ust2;
+    UINT  keyindex;
+    UINT  stateindex;
+    PBYTE pbyst;
+    UINT  idx;
+
+    pbyst = pRC4->abystate;
+    pRC4->ux = 0;
+    pRC4->uy = 0;
+    for (idx = 0; idx < 256; idx++)
+        pbyst[idx] = (BYTE)idx;
+    keyindex = 0;
+    stateindex = 0;
+    for (idx = 0; idx < 256; idx++) {
+        ust1 = pbyst[idx];
+        stateindex = (stateindex + pbyKey[keyindex] + ust1) & 0xff;
+        ust2 = pbyst[stateindex];
+        pbyst[stateindex] = (BYTE)ust1;
+        pbyst[idx] = (BYTE)ust2;
+        if (++keyindex >= cbKey_len)
+            keyindex = 0;
+    }
+}
+
+UINT rc4_byte(PRC4Ext pRC4)
+{
+    UINT ux;
+    UINT uy;
+    UINT ustx, usty;
+    PBYTE pbyst;
+
+    pbyst = pRC4->abystate;
+    ux = (pRC4->ux + 1) & 0xff;
+    ustx = pbyst[ux];
+    uy = (ustx + pRC4->uy) & 0xff;
+    usty = pbyst[uy];
+    pRC4->ux = ux;
+    pRC4->uy = uy;
+    pbyst[uy] = (BYTE)ustx;
+    pbyst[ux] = (BYTE)usty;
+
+    return pbyst[(ustx + usty) & 0xff];
+}
+
+VOID rc4_encrypt(PRC4Ext pRC4, PBYTE pbyDest,
+                     PBYTE pbySrc, UINT cbData_len)
+{
+    UINT ii;
+    for (ii = 0; ii < cbData_len; ii++)
+        pbyDest[ii] = (BYTE)(pbySrc[ii] ^ rc4_byte(pRC4));
+}
diff --git a/drivers/staging/vt6655/rc4.h b/drivers/staging/vt6655/rc4.h
new file mode 100644
index 0000000..4e3ccc5
--- /dev/null
+++ b/drivers/staging/vt6655/rc4.h
@@ -0,0 +1,51 @@
+/*
+ * File: rc4.h
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Purpose:
+ *
+ * Functions:
+ *
+ * Revision History:
+ *
+ * Author: Kyle Hsu
+ *
+ * Date: Sep 4, 2002
+ *
+ */
+
+#ifndef __RC4_H__
+#define __RC4_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+/*---------------------  Export Types  ------------------------------*/
+typedef struct {
+    UINT ux;
+    UINT uy;
+    BYTE abystate[256];
+} RC4Ext, DEF* PRC4Ext;
+
+VOID rc4_init(PRC4Ext pRC4, PBYTE pbyKey, UINT cbKey_len);
+UINT rc4_byte(PRC4Ext pRC4);
+void rc4_encrypt(PRC4Ext pRC4, PBYTE pbyDest, PBYTE pbySrc, UINT cbData_len);
+
+#endif //__RC4_H__
diff --git a/drivers/staging/vt6655/rf.c b/drivers/staging/vt6655/rf.c
new file mode 100644
index 0000000..9d4e3eb
--- /dev/null
+++ b/drivers/staging/vt6655/rf.c
@@ -0,0 +1,1283 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: rf.c
+ *
+ * Purpose: rf function code
+ *
+ * Author: Jerry Chen
+ *
+ * Date: Feb. 19, 2004
+ *
+ * Functions:
+ *      IFRFbWriteEmbeded      - Embeded write RF register via MAC
+ *
+ * Revision History:
+ *
+ */
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__SROM_H__)
+#include "srom.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+
+/*---------------------  Static Definitions -------------------------*/
+
+//static int          msglevel                =MSG_LEVEL_INFO;
+
+#define BY_RF2959_REG_LEN     23 //24bits
+#define CB_RF2959_INIT_SEQ    15
+#define SWITCH_CHANNEL_DELAY_RF2959 200 //us
+#define RF2959_PWR_IDX_LEN    32
+
+#define BY_MA2825_REG_LEN     23 //24bit
+#define CB_MA2825_INIT_SEQ    13
+#define SWITCH_CHANNEL_DELAY_MA2825 200 //us
+#define MA2825_PWR_IDX_LEN    31
+
+#define BY_AL2230_REG_LEN     23 //24bit
+#define CB_AL2230_INIT_SEQ    15
+#define SWITCH_CHANNEL_DELAY_AL2230 200 //us
+#define AL2230_PWR_IDX_LEN    64
+
+
+#define BY_UW2451_REG_LEN     23
+#define CB_UW2451_INIT_SEQ    6
+#define SWITCH_CHANNEL_DELAY_UW2451 200 //us
+#define UW2451_PWR_IDX_LEN    25
+
+//{{ RobertYu: 20041118
+#define BY_MA2829_REG_LEN     23 //24bit
+#define CB_MA2829_INIT_SEQ    13
+#define SWITCH_CHANNEL_DELAY_MA2829 200 //us
+#define MA2829_PWR_IDX_LEN    64
+//}} RobertYu
+
+//{{ RobertYu:20050103
+#define BY_AL7230_REG_LEN     23 //24bit
+#define CB_AL7230_INIT_SEQ    16
+#define SWITCH_CHANNEL_DELAY_AL7230 200 //us
+#define AL7230_PWR_IDX_LEN    64
+//}} RobertYu
+
+//{{ RobertYu: 20041210
+#define BY_UW2452_REG_LEN     23
+#define CB_UW2452_INIT_SEQ    5 //RoberYu:20050113, Rev0.2 Programming Guide(remove R3, so 6-->5)
+#define SWITCH_CHANNEL_DELAY_UW2452 100 //us
+#define UW2452_PWR_IDX_LEN    64
+//}} RobertYu
+
+#define BY_VT3226_REG_LEN     23
+#define CB_VT3226_INIT_SEQ    12
+#define SWITCH_CHANNEL_DELAY_VT3226 200 //us
+#define VT3226_PWR_IDX_LEN    16
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+
+
+const DWORD dwAL2230InitTable[CB_AL2230_INIT_SEQ] = {
+    0x03F79000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x03333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x01A00200+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x00FFF300+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x0005A400+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x0F4DC500+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x0805B600+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x0146C700+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x00068800+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x0403B900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x00DBBA00+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x00099B00+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, //
+    0x0BDFFC00+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x00000D00+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x00580F00+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW
+    };
+
+const DWORD dwAL2230ChannelTable0[CB_MAX_CHANNEL] = {
+    0x03F79000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 1, Tf = 2412MHz
+    0x03F79000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 2, Tf = 2417MHz
+    0x03E79000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 3, Tf = 2422MHz
+    0x03E79000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 4, Tf = 2427MHz
+    0x03F7A000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 5, Tf = 2432MHz
+    0x03F7A000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 6, Tf = 2437MHz
+    0x03E7A000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 7, Tf = 2442MHz
+    0x03E7A000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 8, Tf = 2447MHz
+    0x03F7B000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 9, Tf = 2452MHz
+    0x03F7B000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 10, Tf = 2457MHz
+    0x03E7B000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 11, Tf = 2462MHz
+    0x03E7B000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 12, Tf = 2467MHz
+    0x03F7C000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 13, Tf = 2472MHz
+    0x03E7C000+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW  // channel = 14, Tf = 2412M
+    };
+
+const DWORD dwAL2230ChannelTable1[CB_MAX_CHANNEL] = {
+    0x03333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 1, Tf = 2412MHz
+    0x0B333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 2, Tf = 2417MHz
+    0x03333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 3, Tf = 2422MHz
+    0x0B333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 4, Tf = 2427MHz
+    0x03333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 5, Tf = 2432MHz
+    0x0B333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 6, Tf = 2437MHz
+    0x03333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 7, Tf = 2442MHz
+    0x0B333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 8, Tf = 2447MHz
+    0x03333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 9, Tf = 2452MHz
+    0x0B333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 10, Tf = 2457MHz
+    0x03333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 11, Tf = 2462MHz
+    0x0B333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 12, Tf = 2467MHz
+    0x03333100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 13, Tf = 2472MHz
+    0x06666100+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW  // channel = 14, Tf = 2412M
+    };
+
+DWORD dwAL2230PowerTable[AL2230_PWR_IDX_LEN] = {
+    0x04040900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04041900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04042900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04043900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04044900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04045900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04046900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04047900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04048900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04049900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0404A900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0404B900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0404C900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0404D900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0404E900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0404F900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04050900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04051900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04052900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04053900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04054900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04055900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04056900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04057900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04058900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04059900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0405A900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0405B900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0405C900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0405D900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0405E900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0405F900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04060900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04061900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04062900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04063900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04064900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04065900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04066900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04067900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04068900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04069900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0406A900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0406B900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0406C900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0406D900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0406E900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0406F900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04070900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04071900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04072900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04073900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04074900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04075900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04076900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04077900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04078900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x04079900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0407A900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0407B900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0407C900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0407D900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0407E900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x0407F900+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW
+    };
+
+//{{ RobertYu:20050104
+// 40MHz reference frequency
+// Need to Pull PLLON(PE3) low when writing channel registers through 3-wire.
+const DWORD dwAL7230InitTable[CB_AL7230_INIT_SEQ] = {
+    0x00379000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Channel1 // Need modify for 11a
+    0x13333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Channel1 // Need modify for 11a
+    0x841FF200+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11a: 451FE2
+    0x3FDFA300+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11a: 5FDFA3
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // 11b/g    // Need modify for 11a
+    //0x802B4500+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11a: 8D1B45
+    // RoberYu:20050113, Rev0.47 Regsiter Setting Guide
+    0x802B5500+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11a: 8D1B55
+    0x56AF3600+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW,
+    0xCE020700+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11a: 860207
+    0x6EBC0800+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x221BB900+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW,
+    0xE0000A00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11a: E0600A
+    0x08031B00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // init 0x080B1B00 => 0x080F1B00 for 3 wire control TxGain(D10)
+    //0x00093C00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11a: 00143C
+    // RoberYu:20050113, Rev0.47 Regsiter Setting Guide
+    0x000A3C00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11a: 00143C
+    0xFFFFFD00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x00000E00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x1ABA8F00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW  // Need modify for 11a: 12BACF
+    };
+
+const DWORD dwAL7230InitTableAMode[CB_AL7230_INIT_SEQ] = {
+    0x0FF52000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Channel184 // Need modify for 11b/g
+    0x00000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Channel184 // Need modify for 11b/g
+    0x451FE200+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11b/g
+    0x5FDFA300+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11b/g
+    0x67F78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // 11a    // Need modify for 11b/g
+    0x853F5500+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11b/g, RoberYu:20050113
+    0x56AF3600+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW,
+    0xCE020700+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11b/g
+    0x6EBC0800+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x221BB900+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW,
+    0xE0600A00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11b/g
+    0x08031B00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // init 0x080B1B00 => 0x080F1B00 for 3 wire control TxGain(D10)
+    0x00147C00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // Need modify for 11b/g
+    0xFFFFFD00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x00000E00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW,
+    0x12BACF00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW  // Need modify for 11b/g
+    };
+
+
+const DWORD dwAL7230ChannelTable0[CB_MAX_CHANNEL] = {
+    0x00379000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  1, Tf = 2412MHz
+    0x00379000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  2, Tf = 2417MHz
+    0x00379000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  3, Tf = 2422MHz
+    0x00379000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  4, Tf = 2427MHz
+    0x0037A000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  5, Tf = 2432MHz
+    0x0037A000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  6, Tf = 2437MHz
+    0x0037A000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  7, Tf = 2442MHz
+    0x0037A000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  8, Tf = 2447MHz //RobertYu: 20050218, update for APNode 0.49
+    0x0037B000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  9, Tf = 2452MHz //RobertYu: 20050218, update for APNode 0.49
+    0x0037B000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 10, Tf = 2457MHz //RobertYu: 20050218, update for APNode 0.49
+    0x0037B000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 11, Tf = 2462MHz //RobertYu: 20050218, update for APNode 0.49
+    0x0037B000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 12, Tf = 2467MHz //RobertYu: 20050218, update for APNode 0.49
+    0x0037C000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 13, Tf = 2472MHz //RobertYu: 20050218, update for APNode 0.49
+    0x0037C000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 14, Tf = 2484MHz
+
+    // 4.9G => Ch 183, 184, 185, 187, 188, 189, 192, 196  (Value:15 ~ 22)
+    0x0FF52000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 183, Tf = 4915MHz (15)
+    0x0FF52000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 184, Tf = 4920MHz (16)
+    0x0FF52000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 185, Tf = 4925MHz (17)
+    0x0FF52000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 187, Tf = 4935MHz (18)
+    0x0FF52000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 188, Tf = 4940MHz (19)
+    0x0FF52000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 189, Tf = 4945MHz (20)
+    0x0FF53000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 192, Tf = 4960MHz (21)
+    0x0FF53000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 196, Tf = 4980MHz (22)
+
+    // 5G => Ch 7, 8, 9, 11, 12, 16, 34, 36, 38, 40, 42, 44, 46, 48, 52, 56, 60, 64,
+    // 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 149, 153, 157, 161, 165  (Value 23 ~ 56)
+
+    0x0FF54000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =   7, Tf = 5035MHz (23)
+    0x0FF54000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =   8, Tf = 5040MHz (24)
+    0x0FF54000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =   9, Tf = 5045MHz (25)
+    0x0FF54000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  11, Tf = 5055MHz (26)
+    0x0FF54000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  12, Tf = 5060MHz (27)
+    0x0FF55000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  16, Tf = 5080MHz (28)
+    0x0FF56000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  34, Tf = 5170MHz (29)
+    0x0FF56000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  36, Tf = 5180MHz (30)
+    0x0FF57000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  38, Tf = 5190MHz (31) //RobertYu: 20050218, update for APNode 0.49
+    0x0FF57000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  40, Tf = 5200MHz (32)
+    0x0FF57000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  42, Tf = 5210MHz (33)
+    0x0FF57000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  44, Tf = 5220MHz (34)
+    0x0FF57000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  46, Tf = 5230MHz (35)
+    0x0FF57000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  48, Tf = 5240MHz (36)
+    0x0FF58000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  52, Tf = 5260MHz (37)
+    0x0FF58000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  56, Tf = 5280MHz (38)
+    0x0FF58000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  60, Tf = 5300MHz (39)
+    0x0FF59000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  64, Tf = 5320MHz (40)
+
+    0x0FF5C000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 100, Tf = 5500MHz (41)
+    0x0FF5C000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 104, Tf = 5520MHz (42)
+    0x0FF5C000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 108, Tf = 5540MHz (43)
+    0x0FF5D000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 112, Tf = 5560MHz (44)
+    0x0FF5D000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 116, Tf = 5580MHz (45)
+    0x0FF5D000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 120, Tf = 5600MHz (46)
+    0x0FF5E000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 124, Tf = 5620MHz (47)
+    0x0FF5E000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 128, Tf = 5640MHz (48)
+    0x0FF5E000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 132, Tf = 5660MHz (49)
+    0x0FF5F000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 136, Tf = 5680MHz (50)
+    0x0FF5F000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 140, Tf = 5700MHz (51)
+    0x0FF60000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 149, Tf = 5745MHz (52)
+    0x0FF60000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 153, Tf = 5765MHz (53)
+    0x0FF60000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 157, Tf = 5785MHz (54)
+    0x0FF61000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 161, Tf = 5805MHz (55)
+    0x0FF61000+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW  // channel = 165, Tf = 5825MHz (56)
+    };
+
+const DWORD dwAL7230ChannelTable1[CB_MAX_CHANNEL] = {
+    0x13333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  1, Tf = 2412MHz
+    0x1B333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  2, Tf = 2417MHz
+    0x03333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  3, Tf = 2422MHz
+    0x0B333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  4, Tf = 2427MHz
+    0x13333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  5, Tf = 2432MHz
+    0x1B333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  6, Tf = 2437MHz
+    0x03333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  7, Tf = 2442MHz
+    0x0B333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  8, Tf = 2447MHz
+    0x13333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  9, Tf = 2452MHz
+    0x1B333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 10, Tf = 2457MHz
+    0x03333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 11, Tf = 2462MHz
+    0x0B333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 12, Tf = 2467MHz
+    0x13333100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 13, Tf = 2472MHz
+    0x06666100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 14, Tf = 2484MHz
+
+    // 4.9G => Ch 183, 184, 185, 187, 188, 189, 192, 196  (Value:15 ~ 22)
+    0x1D555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 183, Tf = 4915MHz (15)
+    0x00000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 184, Tf = 4920MHz (16)
+    0x02AAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 185, Tf = 4925MHz (17)
+    0x08000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 187, Tf = 4935MHz (18)
+    0x0AAAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 188, Tf = 4940MHz (19)
+    0x0D555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 189, Tf = 4945MHz (20)
+    0x15555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 192, Tf = 4960MHz (21)
+    0x00000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 196, Tf = 4980MHz (22)
+
+    // 5G => Ch 7, 8, 9, 11, 12, 16, 34, 36, 38, 40, 42, 44, 46, 48, 52, 56, 60, 64,
+    // 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 149, 153, 157, 161, 165  (Value 23 ~ 56)
+    0x1D555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =   7, Tf = 5035MHz (23)
+    0x00000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =   8, Tf = 5040MHz (24)
+    0x02AAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =   9, Tf = 5045MHz (25)
+    0x08000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  11, Tf = 5055MHz (26)
+    0x0AAAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  12, Tf = 5060MHz (27)
+    0x15555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  16, Tf = 5080MHz (28)
+    0x05555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  34, Tf = 5170MHz (29)
+    0x0AAAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  36, Tf = 5180MHz (30)
+    0x10000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  38, Tf = 5190MHz (31)
+    0x15555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  40, Tf = 5200MHz (32)
+    0x1AAAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  42, Tf = 5210MHz (33)
+    0x00000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  44, Tf = 5220MHz (34)
+    0x05555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  46, Tf = 5230MHz (35)
+    0x0AAAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  48, Tf = 5240MHz (36)
+    0x15555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  52, Tf = 5260MHz (37)
+    0x00000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  56, Tf = 5280MHz (38)
+    0x0AAAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  60, Tf = 5300MHz (39)
+    0x15555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  64, Tf = 5320MHz (40)
+    0x15555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 100, Tf = 5500MHz (41)
+    0x00000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 104, Tf = 5520MHz (42)
+    0x0AAAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 108, Tf = 5540MHz (43)
+    0x15555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 112, Tf = 5560MHz (44)
+    0x00000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 116, Tf = 5580MHz (45)
+    0x0AAAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 120, Tf = 5600MHz (46)
+    0x15555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 124, Tf = 5620MHz (47)
+    0x00000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 128, Tf = 5640MHz (48)
+    0x0AAAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 132, Tf = 5660MHz (49)
+    0x15555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 136, Tf = 5680MHz (50)
+    0x00000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 140, Tf = 5700MHz (51)
+    0x18000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 149, Tf = 5745MHz (52)
+    0x02AAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 153, Tf = 5765MHz (53)
+    0x0D555100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 157, Tf = 5785MHz (54)
+    0x18000100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 161, Tf = 5805MHz (55)
+    0x02AAA100+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW  // channel = 165, Tf = 5825MHz (56)
+    };
+
+const DWORD dwAL7230ChannelTable2[CB_MAX_CHANNEL] = {
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  1, Tf = 2412MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  2, Tf = 2417MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  3, Tf = 2422MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  4, Tf = 2427MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  5, Tf = 2432MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  6, Tf = 2437MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  7, Tf = 2442MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  8, Tf = 2447MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  9, Tf = 2452MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 10, Tf = 2457MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 11, Tf = 2462MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 12, Tf = 2467MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 13, Tf = 2472MHz
+    0x7FD78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 14, Tf = 2484MHz
+
+    // 4.9G => Ch 183, 184, 185, 187, 188, 189, 192, 196  (Value:15 ~ 22)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 183, Tf = 4915MHz (15)
+    0x67D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 184, Tf = 4920MHz (16)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 185, Tf = 4925MHz (17)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 187, Tf = 4935MHz (18)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 188, Tf = 4940MHz (19)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 189, Tf = 4945MHz (20)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 192, Tf = 4960MHz (21)
+    0x67D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 196, Tf = 4980MHz (22)
+
+    // 5G => Ch 7, 8, 9, 11, 12, 16, 34, 36, 38, 40, 42, 44, 46, 48, 52, 56, 60, 64,
+    // 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 149, 153, 157, 161, 165  (Value 23 ~ 56)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =   7, Tf = 5035MHz (23)
+    0x67D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =   8, Tf = 5040MHz (24)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =   9, Tf = 5045MHz (25)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  11, Tf = 5055MHz (26)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  12, Tf = 5060MHz (27)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  16, Tf = 5080MHz (28)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  34, Tf = 5170MHz (29)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  36, Tf = 5180MHz (30)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  38, Tf = 5190MHz (31)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  40, Tf = 5200MHz (32)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  42, Tf = 5210MHz (33)
+    0x67D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  44, Tf = 5220MHz (34)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  46, Tf = 5230MHz (35)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  48, Tf = 5240MHz (36)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  52, Tf = 5260MHz (37)
+    0x67D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  56, Tf = 5280MHz (38)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  60, Tf = 5300MHz (39)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel =  64, Tf = 5320MHz (40)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 100, Tf = 5500MHz (41)
+    0x67D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 104, Tf = 5520MHz (42)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 108, Tf = 5540MHz (43)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 112, Tf = 5560MHz (44)
+    0x67D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 116, Tf = 5580MHz (45)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 120, Tf = 5600MHz (46)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 124, Tf = 5620MHz (47)
+    0x67D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 128, Tf = 5640MHz (48)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 132, Tf = 5660MHz (49)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 136, Tf = 5680MHz (50)
+    0x67D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 140, Tf = 5700MHz (51)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 149, Tf = 5745MHz (52)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 153, Tf = 5765MHz (53)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 157, Tf = 5785MHz (54)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW, // channel = 161, Tf = 5805MHz (55)
+    0x77D78400+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW  // channel = 165, Tf = 5825MHz (56)
+    };
+//}} RobertYu
+
+
+
+
+/*---------------------  Static Functions  --------------------------*/
+
+
+
+
+/*
+ * Description: AIROHA IFRF chip init function
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL s_bAL7230Init (DWORD_PTR dwIoBase)
+{
+    int     ii;
+    BOOL    bResult;
+
+    bResult = TRUE;
+
+    //3-wire control for normal mode
+    VNSvOutPortB(dwIoBase + MAC_REG_SOFTPWRCTL, 0);
+
+    MACvWordRegBitsOn(dwIoBase, MAC_REG_SOFTPWRCTL, (SOFTPWRCTL_SWPECTI  |
+                                                     SOFTPWRCTL_TXPEINV));
+    BBvPowerSaveModeOFF(dwIoBase); //RobertYu:20050106, have DC value for Calibration
+
+    for (ii = 0; ii < CB_AL7230_INIT_SEQ; ii++)
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTable[ii]);
+
+    // PLL On
+    MACvWordRegBitsOn(dwIoBase, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_SWPE3);
+
+    //Calibration
+    MACvTimer0MicroSDelay(dwIoBase, 150);//150us
+    bResult &= IFRFbWriteEmbeded(dwIoBase, (0x9ABA8F00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW)); //TXDCOC:active, RCK:diable
+    MACvTimer0MicroSDelay(dwIoBase, 30);//30us
+    bResult &= IFRFbWriteEmbeded(dwIoBase, (0x3ABA8F00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW)); //TXDCOC:diable, RCK:active
+    MACvTimer0MicroSDelay(dwIoBase, 30);//30us
+    bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTable[CB_AL7230_INIT_SEQ-1]); //TXDCOC:diable, RCK:diable
+
+    MACvWordRegBitsOn(dwIoBase, MAC_REG_SOFTPWRCTL, (SOFTPWRCTL_SWPE3    |
+                                                     SOFTPWRCTL_SWPE2    |
+                                                     SOFTPWRCTL_SWPECTI  |
+                                                     SOFTPWRCTL_TXPEINV));
+
+    BBvPowerSaveModeON(dwIoBase); // RobertYu:20050106
+
+    // PE1: TX_ON, PE2: RX_ON, PE3: PLLON
+    //3-wire control for power saving mode
+    VNSvOutPortB(dwIoBase + MAC_REG_PSPWRSIG, (PSSIG_WPE3 | PSSIG_WPE2)); //1100 0000
+
+    return bResult;
+}
+
+// Need to Pull PLLON low when writing channel registers through 3-wire interface
+BOOL s_bAL7230SelectChannel (DWORD_PTR dwIoBase, BYTE byChannel)
+{
+    BOOL    bResult;
+
+    bResult = TRUE;
+
+    // PLLON Off
+    MACvWordRegBitsOff(dwIoBase, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_SWPE3);
+
+    bResult &= IFRFbWriteEmbeded (dwIoBase, dwAL7230ChannelTable0[byChannel-1]); //Reg0
+    bResult &= IFRFbWriteEmbeded (dwIoBase, dwAL7230ChannelTable1[byChannel-1]); //Reg1
+    bResult &= IFRFbWriteEmbeded (dwIoBase, dwAL7230ChannelTable2[byChannel-1]); //Reg4
+
+    // PLLOn On
+    MACvWordRegBitsOn(dwIoBase, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_SWPE3);
+
+    // Set Channel[7] = 0 to tell H/W channel is changing now.
+    VNSvOutPortB(dwIoBase + MAC_REG_CHANNEL, (byChannel & 0x7F));
+    MACvTimer0MicroSDelay(dwIoBase, SWITCH_CHANNEL_DELAY_AL7230);
+    // Set Channel[7] = 1 to tell H/W channel change is done.
+    VNSvOutPortB(dwIoBase + MAC_REG_CHANNEL, (byChannel | 0x80));
+
+    return bResult;
+}
+
+/*
+ * Description: Select channel with UW2452 chip
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      uChannel    - Channel number
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+
+
+//{{ RobertYu: 20041210
+/*
+ * Description: UW2452 IFRF chip init function
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+
+
+
+//}} RobertYu
+////////////////////////////////////////////////////////////////////////////////
+
+/*
+ * Description: VT3226 IFRF chip init function
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+
+/*
+ * Description: Select channel with VT3226 chip
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      uChannel    - Channel number
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+/*
+ * Description: Write to IF/RF, by embeded programming
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      dwData      - data to write
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL IFRFbWriteEmbeded (DWORD_PTR dwIoBase, DWORD dwData)
+{
+    WORD    ww;
+    DWORD   dwValue;
+
+    VNSvOutPortD(dwIoBase + MAC_REG_IFREGCTL, dwData);
+
+    // W_MAX_TIMEOUT is the timeout period
+    for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
+        VNSvInPortD(dwIoBase + MAC_REG_IFREGCTL, &dwValue);
+        if (BITbIsBitOn(dwValue, IFREGCTL_DONE))
+            break;
+    }
+
+    if (ww == W_MAX_TIMEOUT) {
+//        DBG_PORT80_ALWAYS(0x32);
+        return FALSE;
+    }
+    return TRUE;
+}
+
+
+
+/*
+ * Description: RFMD RF2959 IFRF chip init function
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+
+/*
+ * Description: Select channel with RFMD 2959 chip
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      uChannel    - Channel number
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+
+/*
+ * Description: AIROHA IFRF chip init function
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL RFbAL2230Init (DWORD_PTR dwIoBase)
+{
+    int     ii;
+    BOOL    bResult;
+
+    bResult = TRUE;
+
+    //3-wire control for normal mode
+    VNSvOutPortB(dwIoBase + MAC_REG_SOFTPWRCTL, 0);
+
+    MACvWordRegBitsOn(dwIoBase, MAC_REG_SOFTPWRCTL, (SOFTPWRCTL_SWPECTI  |
+                                                     SOFTPWRCTL_TXPEINV));
+//2008-8-21 chester <add>
+    // PLL  Off
+
+    MACvWordRegBitsOff(dwIoBase, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_SWPE3);
+
+
+
+    //patch abnormal AL2230 frequency output
+//2008-8-21 chester <add>
+    IFRFbWriteEmbeded(dwIoBase, (0x07168700+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW));
+
+
+    for (ii = 0; ii < CB_AL2230_INIT_SEQ; ii++)
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL2230InitTable[ii]);
+//2008-8-21 chester <add>
+MACvTimer0MicroSDelay(dwIoBase, 30); //delay 30 us
+
+    // PLL On
+    MACvWordRegBitsOn(dwIoBase, MAC_REG_SOFTPWRCTL, SOFTPWRCTL_SWPE3);
+
+    MACvTimer0MicroSDelay(dwIoBase, 150);//150us
+    bResult &= IFRFbWriteEmbeded(dwIoBase, (0x00d80f00+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW));
+    MACvTimer0MicroSDelay(dwIoBase, 30);//30us
+    bResult &= IFRFbWriteEmbeded(dwIoBase, (0x00780f00+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW));
+    MACvTimer0MicroSDelay(dwIoBase, 30);//30us
+    bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL2230InitTable[CB_AL2230_INIT_SEQ-1]);
+
+    MACvWordRegBitsOn(dwIoBase, MAC_REG_SOFTPWRCTL, (SOFTPWRCTL_SWPE3    |
+                                                     SOFTPWRCTL_SWPE2    |
+                                                     SOFTPWRCTL_SWPECTI  |
+                                                     SOFTPWRCTL_TXPEINV));
+
+    //3-wire control for power saving mode
+    VNSvOutPortB(dwIoBase + MAC_REG_PSPWRSIG, (PSSIG_WPE3 | PSSIG_WPE2)); //1100 0000
+
+    return bResult;
+}
+
+BOOL RFbAL2230SelectChannel (DWORD_PTR dwIoBase, BYTE byChannel)
+{
+    BOOL    bResult;
+
+    bResult = TRUE;
+
+    bResult &= IFRFbWriteEmbeded (dwIoBase, dwAL2230ChannelTable0[byChannel-1]);
+    bResult &= IFRFbWriteEmbeded (dwIoBase, dwAL2230ChannelTable1[byChannel-1]);
+
+    // Set Channel[7] = 0 to tell H/W channel is changing now.
+    VNSvOutPortB(dwIoBase + MAC_REG_CHANNEL, (byChannel & 0x7F));
+    MACvTimer0MicroSDelay(dwIoBase, SWITCH_CHANNEL_DELAY_AL2230);
+    // Set Channel[7] = 1 to tell H/W channel change is done.
+    VNSvOutPortB(dwIoBase + MAC_REG_CHANNEL, (byChannel | 0x80));
+
+    return bResult;
+}
+
+/*
+ * Description: UW2451 IFRF chip init function
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+
+
+/*
+ * Description: Select channel with UW2451 chip
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      uChannel    - Channel number
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+
+/*
+ * Description: Set sleep mode to UW2451 chip
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      uChannel    - Channel number
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+
+/*
+ * Description: RF init function
+ *
+ * Parameters:
+ *  In:
+ *      byBBType
+ *      byRFType
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL RFbInit (
+    IN  PSDevice  pDevice
+    )
+{
+BOOL    bResult = TRUE;
+    switch (pDevice->byRFType) {
+        case RF_AIROHA :
+        case RF_AL2230S:
+            pDevice->byMaxPwrLevel = AL2230_PWR_IDX_LEN;
+            bResult = RFbAL2230Init(pDevice->PortOffset);
+            break;
+        case RF_AIROHA7230 :
+            pDevice->byMaxPwrLevel = AL7230_PWR_IDX_LEN;
+            bResult = s_bAL7230Init(pDevice->PortOffset);
+            break;
+        case RF_NOTHING :
+            bResult = TRUE;
+            break;
+        default :
+            bResult = FALSE;
+            break;
+    }
+    return bResult;
+}
+
+/*
+ * Description: RF ShutDown function
+ *
+ * Parameters:
+ *  In:
+ *      byBBType
+ *      byRFType
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL RFbShutDown (
+    IN  PSDevice  pDevice
+    )
+{
+BOOL    bResult = TRUE;
+
+    switch (pDevice->byRFType) {
+        case RF_AIROHA7230 :
+            bResult = IFRFbWriteEmbeded (pDevice->PortOffset, 0x1ABAEF00+(BY_AL7230_REG_LEN<<3)+IFREGCTL_REGW);
+            break;
+        default :
+            bResult = TRUE;
+            break;
+    }
+    return bResult;
+}
+
+/*
+ * Description: Select channel
+ *
+ * Parameters:
+ *  In:
+ *      byRFType
+ *      byChannel    - Channel number
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL RFbSelectChannel (DWORD_PTR dwIoBase, BYTE byRFType, BYTE byChannel)
+{
+BOOL    bResult = TRUE;
+    switch (byRFType) {
+
+        case RF_AIROHA :
+        case RF_AL2230S:
+            bResult = RFbAL2230SelectChannel(dwIoBase, byChannel);
+            break;
+        //{{ RobertYu: 20050104
+        case RF_AIROHA7230 :
+            bResult = s_bAL7230SelectChannel(dwIoBase, byChannel);
+            break;
+        //}} RobertYu
+        case RF_NOTHING :
+            bResult = TRUE;
+            break;
+        default:
+            bResult = FALSE;
+            break;
+    }
+    return bResult;
+}
+
+/*
+ * Description: Write WakeProgSyn
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase    - I/O base address
+ *      uChannel    - channel number
+ *      bySleepCnt  - SleepProgSyn count
+ *
+ * Return Value: None.
+ *
+ */
+BOOL RFvWriteWakeProgSyn (DWORD_PTR dwIoBase, BYTE byRFType, UINT uChannel)
+{
+    int   ii;
+    BYTE  byInitCount = 0;
+    BYTE  bySleepCount = 0;
+
+    VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, 0);
+    switch (byRFType) {
+        case RF_AIROHA:
+        case RF_AL2230S:
+
+            if (uChannel > CB_MAX_CHANNEL_24G)
+                return FALSE;
+
+            byInitCount = CB_AL2230_INIT_SEQ + 2; // Init Reg + Channel Reg (2)
+            bySleepCount = 0;
+            if (byInitCount > (MISCFIFO_SYNDATASIZE - bySleepCount)) {
+                return FALSE;
+            }
+
+            for (ii = 0; ii < CB_AL2230_INIT_SEQ; ii++ ) {
+                MACvSetMISCFifo(dwIoBase, (WORD)(MISCFIFO_SYNDATA_IDX + ii), dwAL2230InitTable[ii]);
+            }
+            MACvSetMISCFifo(dwIoBase, (WORD)(MISCFIFO_SYNDATA_IDX + ii), dwAL2230ChannelTable0[uChannel-1]);
+            ii ++;
+            MACvSetMISCFifo(dwIoBase, (WORD)(MISCFIFO_SYNDATA_IDX + ii), dwAL2230ChannelTable1[uChannel-1]);
+            break;
+
+        //{{ RobertYu: 20050104
+        // Need to check, PLLON need to be low for channel setting
+        case RF_AIROHA7230:
+            byInitCount = CB_AL7230_INIT_SEQ + 3; // Init Reg + Channel Reg (3)
+            bySleepCount = 0;
+            if (byInitCount > (MISCFIFO_SYNDATASIZE - bySleepCount)) {
+                return FALSE;
+            }
+
+            if (uChannel <= CB_MAX_CHANNEL_24G)
+            {
+                for (ii = 0; ii < CB_AL7230_INIT_SEQ; ii++ ) {
+                    MACvSetMISCFifo(dwIoBase, (WORD)(MISCFIFO_SYNDATA_IDX + ii), dwAL7230InitTable[ii]);
+                }
+            }
+            else
+            {
+                for (ii = 0; ii < CB_AL7230_INIT_SEQ; ii++ ) {
+                    MACvSetMISCFifo(dwIoBase, (WORD)(MISCFIFO_SYNDATA_IDX + ii), dwAL7230InitTableAMode[ii]);
+                }
+            }
+
+            MACvSetMISCFifo(dwIoBase, (WORD)(MISCFIFO_SYNDATA_IDX + ii), dwAL7230ChannelTable0[uChannel-1]);
+            ii ++;
+            MACvSetMISCFifo(dwIoBase, (WORD)(MISCFIFO_SYNDATA_IDX + ii), dwAL7230ChannelTable1[uChannel-1]);
+            ii ++;
+            MACvSetMISCFifo(dwIoBase, (WORD)(MISCFIFO_SYNDATA_IDX + ii), dwAL7230ChannelTable2[uChannel-1]);
+            break;
+        //}} RobertYu
+
+        case RF_NOTHING :
+            return TRUE;
+            break;
+
+        default:
+            return FALSE;
+            break;
+    }
+
+    MACvSetMISCFifo(dwIoBase, MISCFIFO_SYNINFO_IDX, (DWORD)MAKEWORD(bySleepCount, byInitCount));
+
+    return TRUE;
+}
+
+/*
+ * Description: Set Tx power
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase       - I/O base address
+ *      dwRFPowerTable - RF Tx Power Setting
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL RFbSetPower (
+    IN  PSDevice  pDevice,
+    IN  UINT      uRATE,
+    IN  UINT      uCH
+    )
+{
+BOOL    bResult = TRUE;
+BYTE    byPwr = 0;
+BYTE    byDec = 0;
+BYTE    byPwrdBm = 0;
+
+    if (pDevice->dwDiagRefCount != 0) {
+        return TRUE;
+    }
+    if ((uCH < 1) || (uCH > CB_MAX_CHANNEL)) {
+        return FALSE;
+    }
+
+    switch (uRATE) {
+    case RATE_1M:
+    case RATE_2M:
+    case RATE_5M:
+    case RATE_11M:
+        byPwr = pDevice->abyCCKPwrTbl[uCH];
+        byPwrdBm = pDevice->abyCCKDefaultPwr[uCH];
+//PLICE_DEBUG->
+	//byPwr+=5;
+//PLICE_DEBUG <-
+
+//printk("Rate <11:byPwr is %d\n",byPwr);
+		break;
+    case RATE_6M:
+    case RATE_9M:
+    case RATE_18M:
+        byPwr = pDevice->abyOFDMPwrTbl[uCH];
+        if (pDevice->byRFType == RF_UW2452) {
+            byDec = byPwr + 14;
+        } else {
+            byDec = byPwr + 10;
+        }
+        if (byDec >= pDevice->byMaxPwrLevel) {
+            byDec = pDevice->byMaxPwrLevel-1;
+        }
+        if (pDevice->byRFType == RF_UW2452) {
+            byPwrdBm = byDec - byPwr;
+            byPwrdBm /= 3;
+        } else {
+            byPwrdBm = byDec - byPwr;
+            byPwrdBm >>= 1;
+        }
+        byPwrdBm += pDevice->abyOFDMDefaultPwr[uCH];
+        byPwr = byDec;
+//PLICE_DEBUG->
+	//byPwr+=5;
+//PLICE_DEBUG<-
+
+//printk("Rate <24:byPwr is %d\n",byPwr);
+		break;
+    case RATE_24M:
+    case RATE_36M:
+    case RATE_48M:
+    case RATE_54M:
+        byPwr = pDevice->abyOFDMPwrTbl[uCH];
+        byPwrdBm = pDevice->abyOFDMDefaultPwr[uCH];
+//PLICE_DEBUG->
+	//byPwr+=5;
+//PLICE_DEBUG<-
+//printk("Rate < 54:byPwr is %d\n",byPwr);
+		break;
+    }
+
+#if 0
+
+    // 802.11h TPC
+    if (pDevice->bLinkPass == TRUE) {
+        // do not over local constraint
+        if (byPwrdBm > pDevice->abyLocalPwr[uCH]) {
+            pDevice->byCurPwrdBm = pDevice->abyLocalPwr[uCH];
+            byDec = byPwrdBm - pDevice->abyLocalPwr[uCH];
+            if (pDevice->byRFType == RF_UW2452) {
+                byDec *= 3;
+            } else {
+                byDec <<= 1;
+            }
+            if (byPwr > byDec) {
+                byPwr -= byDec;
+            } else {
+                byPwr = 0;
+            }
+        } else {
+            pDevice->byCurPwrdBm = byPwrdBm;
+        }
+    } else {
+        // do not over regulatory constraint
+        if (byPwrdBm > pDevice->abyRegPwr[uCH]) {
+            pDevice->byCurPwrdBm = pDevice->abyRegPwr[uCH];
+            byDec = byPwrdBm - pDevice->abyRegPwr[uCH];
+            if (pDevice->byRFType == RF_UW2452) {
+                byDec *= 3;
+            } else {
+                byDec <<= 1;
+            }
+            if (byPwr > byDec) {
+                byPwr -= byDec;
+            } else {
+                byPwr = 0;
+            }
+        } else {
+            pDevice->byCurPwrdBm = byPwrdBm;
+        }
+    }
+#endif
+
+//    if (pDevice->byLocalID <= REV_ID_VT3253_B1) {
+    if (pDevice->byCurPwr == byPwr) {
+        return TRUE;
+    }
+    bResult = RFbRawSetPower(pDevice, byPwr, uRATE);
+//    }
+    if (bResult == TRUE) {
+       pDevice->byCurPwr = byPwr;
+    }
+    return bResult;
+}
+
+/*
+ * Description: Set Tx power
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase       - I/O base address
+ *      dwRFPowerTable - RF Tx Power Setting
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+
+BOOL RFbRawSetPower (
+    IN  PSDevice  pDevice,
+    IN  BYTE      byPwr,
+    IN  UINT      uRATE
+    )
+{
+BOOL    bResult = TRUE;
+DWORD   dwMax7230Pwr = 0;
+
+    if (byPwr >=  pDevice->byMaxPwrLevel) {
+        return (FALSE);
+    }
+    switch (pDevice->byRFType) {
+
+        case RF_AIROHA :
+            bResult &= IFRFbWriteEmbeded(pDevice->PortOffset, dwAL2230PowerTable[byPwr]);
+            if (uRATE <= RATE_11M) {
+                bResult &= IFRFbWriteEmbeded(pDevice->PortOffset, 0x0001B400+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW);
+            } else {
+                bResult &= IFRFbWriteEmbeded(pDevice->PortOffset, 0x0005A400+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW);
+            }
+            break;
+
+
+        case RF_AL2230S :
+            bResult &= IFRFbWriteEmbeded(pDevice->PortOffset, dwAL2230PowerTable[byPwr]);
+            if (uRATE <= RATE_11M) {
+                bResult &= IFRFbWriteEmbeded(pDevice->PortOffset, 0x040C1400+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW);
+                bResult &= IFRFbWriteEmbeded(pDevice->PortOffset, 0x00299B00+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW);
+            }else {
+                bResult &= IFRFbWriteEmbeded(pDevice->PortOffset, 0x0005A400+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW);
+                bResult &= IFRFbWriteEmbeded(pDevice->PortOffset, 0x00099B00+(BY_AL2230_REG_LEN<<3)+IFREGCTL_REGW);
+            }
+
+            break;
+
+        case RF_AIROHA7230:
+            //  0x080F1B00 for 3 wire control TxGain(D10) and 0x31 as TX Gain value
+            dwMax7230Pwr = 0x080C0B00 | ( (byPwr) << 12 ) |
+                           (BY_AL7230_REG_LEN << 3 )  | IFREGCTL_REGW;
+
+            bResult &= IFRFbWriteEmbeded(pDevice->PortOffset, dwMax7230Pwr);
+            break;
+
+
+        default :
+            break;
+    }
+    return bResult;
+}
+
+/*+
+ *
+ * Routine Description:
+ *     Translate RSSI to dBm
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - The adapter to be translated
+ *      byCurrRSSI      - RSSI to be translated
+ *  Out:
+ *      pdwdbm          - Translated dbm number
+ *
+ * Return Value: none
+ *
+-*/
+VOID
+RFvRSSITodBm (
+    IN  PSDevice pDevice,
+    IN  BYTE     byCurrRSSI,
+    OUT PLONG    pldBm
+    )
+{
+    BYTE byIdx = (((byCurrRSSI & 0xC0) >> 6) & 0x03);
+    LONG b = (byCurrRSSI & 0x3F);
+    LONG a = 0;
+    BYTE abyAIROHARF[4] = {0, 18, 0, 40};
+
+    switch (pDevice->byRFType) {
+        case RF_AIROHA:
+        case RF_AL2230S:
+        case RF_AIROHA7230: //RobertYu: 20040104
+            a = abyAIROHARF[byIdx];
+            break;
+        default:
+            break;
+    }
+
+    *pldBm = -1 * (a + b * 2);
+}
+
+////////////////////////////////////////////////////////////////////////////////
+//{{ RobertYu: 20050104
+
+
+// Post processing for the 11b/g and 11a.
+// for save time on changing Reg2,3,5,7,10,12,15
+BOOL RFbAL7230SelectChannelPostProcess (DWORD_PTR dwIoBase, BYTE byOldChannel, BYTE byNewChannel)
+{
+    BOOL    bResult;
+
+    bResult = TRUE;
+
+    // if change between 11 b/g and 11a need to update the following register
+    // Channel Index 1~14
+
+    if( (byOldChannel <= CB_MAX_CHANNEL_24G) && (byNewChannel > CB_MAX_CHANNEL_24G) )
+    {
+        // Change from 2.4G to 5G
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTableAMode[2]); //Reg2
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTableAMode[3]); //Reg3
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTableAMode[5]); //Reg5
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTableAMode[7]); //Reg7
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTableAMode[10]);//Reg10
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTableAMode[12]);//Reg12
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTableAMode[15]);//Reg15
+    }
+    else if( (byOldChannel > CB_MAX_CHANNEL_24G) && (byNewChannel <= CB_MAX_CHANNEL_24G) )
+    {
+        // change from 5G to 2.4G
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTable[2]); //Reg2
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTable[3]); //Reg3
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTable[5]); //Reg5
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTable[7]); //Reg7
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTable[10]);//Reg10
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTable[12]);//Reg12
+        bResult &= IFRFbWriteEmbeded(dwIoBase, dwAL7230InitTable[15]);//Reg15
+    }
+
+    return bResult;
+}
+
+
+//}} RobertYu
+////////////////////////////////////////////////////////////////////////////////
+
diff --git a/drivers/staging/vt6655/rf.h b/drivers/staging/vt6655/rf.h
new file mode 100644
index 0000000..05fe17b
--- /dev/null
+++ b/drivers/staging/vt6655/rf.h
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: rf.h
+ *
+ * Purpose:
+ *
+ * Author: Jerry Chen
+ *
+ * Date: Feb. 19, 2004
+ *
+ */
+
+
+#ifndef __RF_H__
+#define __RF_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+/*---------------------  Export Definitions -------------------------*/
+//
+// Baseband RF pair definition in eeprom (Bits 6..0)
+//
+#define RF_RFMD2959             0x01
+#define RF_MAXIMAG              0x02
+#define RF_AIROHA               0x03
+
+//#define RF_GCT5103              0x04
+#define RF_UW2451               0x05
+#define RF_MAXIMG               0x06
+#define RF_MAXIM2829            0x07 // RobertYu: 20041118
+#define RF_UW2452               0x08 // RobertYu: 20041210
+#define RF_AIROHA7230           0x0a // RobertYu: 20050104
+#define RF_UW2453               0x0b
+
+#define RF_VT3226               0x09
+#define RF_AL2230S              0x0e
+
+#define RF_NOTHING              0x7E
+#define RF_EMU                  0x80
+#define RF_MASK                 0x7F
+
+#define ZONE_FCC                0
+#define ZONE_MKK1               1
+#define ZONE_ETSI               2
+#define ZONE_IC                 3
+#define ZONE_SPAIN              4
+#define ZONE_FRANCE             5
+#define ZONE_MKK                6
+#define ZONE_ISRAEL             7
+
+//[20050104] CB_MAXIM2829_CHANNEL_5G_HIGH, CB_UW2452_CHANNEL_5G_HIGH: 40==>41
+#define CB_MAXIM2829_CHANNEL_5G_HIGH    41 //Index41: channel = 100, Tf = 5500MHz, set the (A3:A0=0101) D6=1
+#define CB_UW2452_CHANNEL_5G_HIGH       41 //[20041210] Index41: channel = 100, Tf = 5500MHz, change VCO2->VCO3
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+BOOL IFRFbWriteEmbeded(DWORD_PTR dwIoBase, DWORD dwData);
+BOOL RFbSelectChannel(DWORD_PTR dwIoBase, BYTE byRFType, BYTE byChannel);
+BOOL RFbInit (
+    IN  PSDevice  pDevice
+    );
+BOOL RFvWriteWakeProgSyn(DWORD_PTR dwIoBase, BYTE byRFType, UINT uChannel);
+BOOL RFbSetPower(PSDevice pDevice, UINT uRATE, UINT uCH);
+BOOL RFbRawSetPower(
+    IN  PSDevice  pDevice,
+    IN  BYTE      byPwr,
+    IN  UINT      uRATE
+    );
+
+VOID
+RFvRSSITodBm(
+    IN  PSDevice pDevice,
+    IN  BYTE     byCurrRSSI,
+    OUT PLONG    pldBm
+    );
+
+//{{ RobertYu: 20050104
+BOOL RFbAL7230SelectChannelPostProcess(DWORD_PTR dwIoBase, BYTE byOldChannel, BYTE byNewChannel);
+//}} RobertYu
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+#endif // __RF_H__
+
+
+
diff --git a/drivers/staging/vt6655/rxtx.c b/drivers/staging/vt6655/rxtx.c
new file mode 100644
index 0000000..c8a4a55
--- /dev/null
+++ b/drivers/staging/vt6655/rxtx.c
@@ -0,0 +1,3269 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: rxtx.c
+ *
+ * Purpose: handle WMAC/802.3/802.11 rx & tx functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 20, 2003
+ *
+ * Functions:
+ *      s_vGenerateTxParameter - Generate tx dma requried parameter.
+ *      vGenerateMACHeader - Translate 802.3 to 802.11 header
+ *      cbGetFragCount - Caculate fragement number count
+ *      csBeacon_xmit - beacon tx function
+ *      csMgmt_xmit - management tx function
+ *      s_cbFillTxBufHead - fulfill tx dma buffer header
+ *      s_uGetDataDuration - get tx data required duration
+ *      s_uFillDataHead- fulfill tx data duration header
+ *      s_uGetRTSCTSDuration- get rtx/cts requried duration
+ *      s_uGetRTSCTSRsvTime- get rts/cts reserved time
+ *      s_uGetTxRsvTime- get frame reserved time
+ *      s_vFillCTSHead- fulfill CTS ctl header
+ *      s_vFillFragParameter- Set fragement ctl parameter.
+ *      s_vFillRTSHead- fulfill RTS ctl header
+ *      s_vFillTxKey- fulfill tx encrypt key
+ *      s_vSWencryption- Software encrypt header
+ *      vDMA0_tx_80211- tx 802.11 frame via dma0
+ *      vGenerateFIFOHeader- Generate tx FIFO ctl header
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__RXTX_H__)
+#include "rxtx.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__BSSDB_H__)
+#include "bssdb.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__MICHAEL_H__)
+#include "michael.h"
+#endif
+#if !defined(__TKIP_H__)
+#include "tkip.h"
+#endif
+#if !defined(__TCRC_H__)
+#include "tcrc.h"
+#endif
+#if !defined(__WCTL_H__)
+#include "wctl.h"
+#endif
+#if !defined(__WROUTE_H__)
+#include "wroute.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__HOSTAP_H__)
+#include "hostap.h"
+#endif
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+static int          msglevel                =MSG_LEVEL_INFO;
+
+#define	PLICE_DEBUG
+
+
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Static Definitions -------------------------*/
+#define CRITICAL_PACKET_LEN      256    // if packet size < 256 -> in-direct send
+                                        //    packet size >= 256 -> direct send
+
+const WORD wTimeStampOff[2][MAX_RATE] = {
+        {384, 288, 226, 209, 54, 43, 37, 31, 28, 25, 24, 23}, // Long Preamble
+        {384, 192, 130, 113, 54, 43, 37, 31, 28, 25, 24, 23}, // Short Preamble
+    };
+
+const WORD wFB_Opt0[2][5] = {
+        {RATE_12M, RATE_18M, RATE_24M, RATE_36M, RATE_48M}, // fallback_rate0
+        {RATE_12M, RATE_12M, RATE_18M, RATE_24M, RATE_36M}, // fallback_rate1
+    };
+const WORD wFB_Opt1[2][5] = {
+        {RATE_12M, RATE_18M, RATE_24M, RATE_24M, RATE_36M}, // fallback_rate0
+        {RATE_6M , RATE_6M,  RATE_12M, RATE_12M, RATE_18M}, // fallback_rate1
+    };
+
+
+#define RTSDUR_BB       0
+#define RTSDUR_BA       1
+#define RTSDUR_AA       2
+#define CTSDUR_BA       3
+#define RTSDUR_BA_F0    4
+#define RTSDUR_AA_F0    5
+#define RTSDUR_BA_F1    6
+#define RTSDUR_AA_F1    7
+#define CTSDUR_BA_F0    8
+#define CTSDUR_BA_F1    9
+#define DATADUR_B       10
+#define DATADUR_A       11
+#define DATADUR_A_F0    12
+#define DATADUR_A_F1    13
+
+/*---------------------  Static Functions  --------------------------*/
+
+
+
+static
+VOID
+s_vFillTxKey(
+    IN  PSDevice   pDevice,
+    IN  PBYTE      pbyBuf,
+    IN  PBYTE      pbyIVHead,
+    IN  PSKeyItem  pTransmitKey,
+    IN  PBYTE      pbyHdrBuf,
+    IN  WORD       wPayloadLen,
+    OUT PBYTE      pMICHDR
+    );
+
+
+
+static
+VOID
+s_vFillRTSHead(
+    IN PSDevice         pDevice,
+    IN BYTE             byPktTyp,
+    IN PVOID            pvRTS,
+    IN UINT             cbFrameLength,
+    IN BOOL             bNeedAck,
+    IN BOOL             bDisCRC,
+    IN PSEthernetHeader psEthHeader,
+    IN WORD             wCurrentRate,
+    IN BYTE             byFBOption
+    );
+
+static
+VOID
+s_vGenerateTxParameter(
+    IN PSDevice         pDevice,
+    IN  BYTE            byPktTyp,
+    IN PVOID            pTxBufHead,
+    IN PVOID            pvRrvTime,
+    IN PVOID            pvRTS,
+    IN PVOID            pvCTS,
+    IN UINT             cbFrameSize,
+    IN BOOL             bNeedACK,
+    IN UINT             uDMAIdx,
+    IN PSEthernetHeader psEthHeader,
+    IN WORD             wCurrentRate
+    );
+
+
+
+static void s_vFillFragParameter(
+    IN PSDevice pDevice,
+    IN PBYTE    pbyBuffer,
+    IN UINT     uTxType,
+    IN PVOID    pvtdCurr,
+    IN WORD     wFragType,
+    IN UINT     cbReqCount
+    );
+
+
+static
+UINT
+s_cbFillTxBufHead (
+    IN  PSDevice         pDevice,
+    IN  BYTE             byPktTyp,
+    IN  PBYTE            pbyTxBufferAddr,
+    IN  UINT             cbFrameBodySize,
+    IN  UINT             uDMAIdx,
+    IN  PSTxDesc         pHeadTD,
+    IN  PSEthernetHeader psEthHeader,
+    IN  PBYTE            pPacket,
+    IN  BOOL             bNeedEncrypt,
+    IN  PSKeyItem        pTransmitKey,
+    IN  UINT             uNodeIndex,
+    OUT PUINT            puMACfragNum
+    );
+
+
+static
+UINT
+s_uFillDataHead (
+    IN PSDevice pDevice,
+    IN BYTE     byPktTyp,
+    IN PVOID    pTxDataHead,
+    IN UINT     cbFrameLength,
+    IN UINT     uDMAIdx,
+    IN BOOL     bNeedAck,
+    IN UINT     uFragIdx,
+    IN UINT     cbLastFragmentSize,
+    IN UINT     uMACfragNum,
+    IN BYTE     byFBOption,
+    IN WORD     wCurrentRate
+    );
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+
+static
+VOID
+s_vFillTxKey (
+    IN  PSDevice   pDevice,
+    IN  PBYTE      pbyBuf,
+    IN  PBYTE      pbyIVHead,
+    IN  PSKeyItem  pTransmitKey,
+    IN  PBYTE      pbyHdrBuf,
+    IN  WORD       wPayloadLen,
+    OUT PBYTE      pMICHDR
+    )
+{
+    PDWORD          pdwIV = (PDWORD) pbyIVHead;
+    PDWORD          pdwExtIV = (PDWORD) ((PBYTE)pbyIVHead+4);
+    WORD            wValue;
+    PS802_11Header  pMACHeader = (PS802_11Header)pbyHdrBuf;
+    DWORD           dwRevIVCounter;
+    BYTE            byKeyIndex = 0;
+
+
+
+    //Fill TXKEY
+    if (pTransmitKey == NULL)
+        return;
+
+    dwRevIVCounter = cpu_to_le32(pDevice->dwIVCounter);
+    *pdwIV = pDevice->dwIVCounter;
+    byKeyIndex = pTransmitKey->dwKeyIndex & 0xf;
+
+    if (pTransmitKey->byCipherSuite == KEY_CTL_WEP) {
+        if (pTransmitKey->uKeyLength == WLAN_WEP232_KEYLEN ){
+            MEMvCopy(pDevice->abyPRNG, (PBYTE)&(dwRevIVCounter), 3);
+            MEMvCopy(pDevice->abyPRNG+3, pTransmitKey->abyKey, pTransmitKey->uKeyLength);
+        } else {
+            MEMvCopy(pbyBuf, (PBYTE)&(dwRevIVCounter), 3);
+            MEMvCopy(pbyBuf+3, pTransmitKey->abyKey, pTransmitKey->uKeyLength);
+            if(pTransmitKey->uKeyLength == WLAN_WEP40_KEYLEN) {
+                MEMvCopy(pbyBuf+8, (PBYTE)&(dwRevIVCounter), 3);
+                MEMvCopy(pbyBuf+11, pTransmitKey->abyKey, pTransmitKey->uKeyLength);
+            }
+            MEMvCopy(pDevice->abyPRNG, pbyBuf, 16);
+        }
+        // Append IV after Mac Header
+        *pdwIV &= WEP_IV_MASK;//00000000 11111111 11111111 11111111
+        *pdwIV |= (byKeyIndex << 30);
+        *pdwIV = cpu_to_le32(*pdwIV);
+        pDevice->dwIVCounter++;
+        if (pDevice->dwIVCounter > WEP_IV_MASK) {
+            pDevice->dwIVCounter = 0;
+        }
+    } else if (pTransmitKey->byCipherSuite == KEY_CTL_TKIP) {
+        pTransmitKey->wTSC15_0++;
+        if (pTransmitKey->wTSC15_0 == 0) {
+            pTransmitKey->dwTSC47_16++;
+        }
+        TKIPvMixKey(pTransmitKey->abyKey, pDevice->abyCurrentNetAddr,
+                    pTransmitKey->wTSC15_0, pTransmitKey->dwTSC47_16, pDevice->abyPRNG);
+        MEMvCopy(pbyBuf, pDevice->abyPRNG, 16);
+        // Make IV
+        MEMvCopy(pdwIV, pDevice->abyPRNG, 3);
+
+        *(pbyIVHead+3) = (BYTE)(((byKeyIndex << 6) & 0xc0) | 0x20); // 0x20 is ExtIV
+        // Append IV&ExtIV after Mac Header
+        *pdwExtIV = cpu_to_le32(pTransmitKey->dwTSC47_16);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"vFillTxKey()---- pdwExtIV: %lx\n", *pdwExtIV);
+
+    } else if (pTransmitKey->byCipherSuite == KEY_CTL_CCMP) {
+        pTransmitKey->wTSC15_0++;
+        if (pTransmitKey->wTSC15_0 == 0) {
+            pTransmitKey->dwTSC47_16++;
+        }
+        MEMvCopy(pbyBuf, pTransmitKey->abyKey, 16);
+
+        // Make IV
+        *pdwIV = 0;
+        *(pbyIVHead+3) = (BYTE)(((byKeyIndex << 6) & 0xc0) | 0x20); // 0x20 is ExtIV
+        *pdwIV |= cpu_to_le16((WORD)(pTransmitKey->wTSC15_0));
+        //Append IV&ExtIV after Mac Header
+        *pdwExtIV = cpu_to_le32(pTransmitKey->dwTSC47_16);
+
+        //Fill MICHDR0
+        *pMICHDR = 0x59;
+        *((PBYTE)(pMICHDR+1)) = 0; // TxPriority
+        MEMvCopy(pMICHDR+2, &(pMACHeader->abyAddr2[0]), 6);
+        *((PBYTE)(pMICHDR+8)) = HIBYTE(HIWORD(pTransmitKey->dwTSC47_16));
+        *((PBYTE)(pMICHDR+9)) = LOBYTE(HIWORD(pTransmitKey->dwTSC47_16));
+        *((PBYTE)(pMICHDR+10)) = HIBYTE(LOWORD(pTransmitKey->dwTSC47_16));
+        *((PBYTE)(pMICHDR+11)) = LOBYTE(LOWORD(pTransmitKey->dwTSC47_16));
+        *((PBYTE)(pMICHDR+12)) = HIBYTE(pTransmitKey->wTSC15_0);
+        *((PBYTE)(pMICHDR+13)) = LOBYTE(pTransmitKey->wTSC15_0);
+        *((PBYTE)(pMICHDR+14)) = HIBYTE(wPayloadLen);
+        *((PBYTE)(pMICHDR+15)) = LOBYTE(wPayloadLen);
+
+        //Fill MICHDR1
+        *((PBYTE)(pMICHDR+16)) = 0; // HLEN[15:8]
+        if (pDevice->bLongHeader) {
+            *((PBYTE)(pMICHDR+17)) = 28; // HLEN[7:0]
+        } else {
+            *((PBYTE)(pMICHDR+17)) = 22; // HLEN[7:0]
+        }
+        wValue = cpu_to_le16(pMACHeader->wFrameCtl & 0xC78F);
+        MEMvCopy(pMICHDR+18, (PBYTE)&wValue, 2); // MSKFRACTL
+        MEMvCopy(pMICHDR+20, &(pMACHeader->abyAddr1[0]), 6);
+        MEMvCopy(pMICHDR+26, &(pMACHeader->abyAddr2[0]), 6);
+
+        //Fill MICHDR2
+        MEMvCopy(pMICHDR+32, &(pMACHeader->abyAddr3[0]), 6);
+        wValue = pMACHeader->wSeqCtl;
+        wValue &= 0x000F;
+        wValue = cpu_to_le16(wValue);
+        MEMvCopy(pMICHDR+38, (PBYTE)&wValue, 2); // MSKSEQCTL
+        if (pDevice->bLongHeader) {
+            MEMvCopy(pMICHDR+40, &(pMACHeader->abyAddr4[0]), 6);
+        }
+    }
+}
+
+
+static
+VOID
+s_vSWencryption (
+    IN  PSDevice            pDevice,
+    IN  PSKeyItem           pTransmitKey,
+    IN  PBYTE               pbyPayloadHead,
+    IN  WORD                wPayloadSize
+    )
+{
+    UINT   cbICVlen = 4;
+    DWORD  dwICV = 0xFFFFFFFFL;
+    PDWORD pdwICV;
+
+    if (pTransmitKey == NULL)
+        return;
+
+    if (pTransmitKey->byCipherSuite == KEY_CTL_WEP) {
+        //=======================================================================
+        // Append ICV after payload
+        dwICV = CRCdwGetCrc32Ex(pbyPayloadHead, wPayloadSize, dwICV);//ICV(Payload)
+        pdwICV = (PDWORD)(pbyPayloadHead + wPayloadSize);
+        // finally, we must invert dwCRC to get the correct answer
+        *pdwICV = cpu_to_le32(~dwICV);
+        // RC4 encryption
+        rc4_init(&pDevice->SBox, pDevice->abyPRNG, pTransmitKey->uKeyLength + 3);
+        rc4_encrypt(&pDevice->SBox, pbyPayloadHead, pbyPayloadHead, wPayloadSize+cbICVlen);
+        //=======================================================================
+    } else if (pTransmitKey->byCipherSuite == KEY_CTL_TKIP) {
+        //=======================================================================
+        //Append ICV after payload
+        dwICV = CRCdwGetCrc32Ex(pbyPayloadHead, wPayloadSize, dwICV);//ICV(Payload)
+        pdwICV = (PDWORD)(pbyPayloadHead + wPayloadSize);
+        // finally, we must invert dwCRC to get the correct answer
+        *pdwICV = cpu_to_le32(~dwICV);
+        // RC4 encryption
+        rc4_init(&pDevice->SBox, pDevice->abyPRNG, TKIP_KEY_LEN);
+        rc4_encrypt(&pDevice->SBox, pbyPayloadHead, pbyPayloadHead, wPayloadSize+cbICVlen);
+        //=======================================================================
+    }
+}
+
+
+
+
+/*byPktTyp : PK_TYPE_11A     0
+             PK_TYPE_11B     1
+             PK_TYPE_11GB    2
+             PK_TYPE_11GA    3
+*/
+static
+UINT
+s_uGetTxRsvTime (
+    IN PSDevice pDevice,
+    IN BYTE     byPktTyp,
+    IN UINT     cbFrameLength,
+    IN WORD     wRate,
+    IN BOOL     bNeedAck
+    )
+{
+    UINT uDataTime, uAckTime;
+
+    uDataTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, cbFrameLength, wRate);
+#ifdef	PLICE_DEBUG
+	//printk("s_uGetTxRsvTime is %d\n",uDataTime);
+#endif
+    if (byPktTyp == PK_TYPE_11B) {//llb,CCK mode
+        uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, 14, (WORD)pDevice->byTopCCKBasicRate);
+    } else {//11g 2.4G OFDM mode & 11a 5G OFDM mode
+        uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, 14, (WORD)pDevice->byTopOFDMBasicRate);
+    }
+
+    if (bNeedAck) {
+        return (uDataTime + pDevice->uSIFS + uAckTime);
+    }
+    else {
+        return uDataTime;
+    }
+}
+
+//byFreqType: 0=>5GHZ 1=>2.4GHZ
+static
+UINT
+s_uGetRTSCTSRsvTime (
+    IN PSDevice pDevice,
+    IN BYTE byRTSRsvType,
+    IN BYTE byPktTyp,
+    IN UINT cbFrameLength,
+    IN WORD wCurrentRate
+    )
+{
+    UINT uRrvTime  , uRTSTime, uCTSTime, uAckTime, uDataTime;
+
+    uRrvTime = uRTSTime = uCTSTime = uAckTime = uDataTime = 0;
+
+
+    uDataTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, cbFrameLength, wCurrentRate);
+    if (byRTSRsvType == 0) { //RTSTxRrvTime_bb
+        uRTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, 20, pDevice->byTopCCKBasicRate);
+        uCTSTime = uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, 14, pDevice->byTopCCKBasicRate);
+    }
+    else if (byRTSRsvType == 1){ //RTSTxRrvTime_ba, only in 2.4GHZ
+        uRTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, 20, pDevice->byTopCCKBasicRate);
+        uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, 14, pDevice->byTopCCKBasicRate);
+        uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, 14, pDevice->byTopOFDMBasicRate);
+    }
+    else if (byRTSRsvType == 2) { //RTSTxRrvTime_aa
+        uRTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, 20, pDevice->byTopOFDMBasicRate);
+        uCTSTime = uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, 14, pDevice->byTopOFDMBasicRate);
+    }
+    else if (byRTSRsvType == 3) { //CTSTxRrvTime_ba, only in 2.4GHZ
+        uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, 14, pDevice->byTopCCKBasicRate);
+        uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktTyp, 14, pDevice->byTopOFDMBasicRate);
+        uRrvTime = uCTSTime + uAckTime + uDataTime + 2*pDevice->uSIFS;
+        return uRrvTime;
+    }
+
+    //RTSRrvTime
+    uRrvTime = uRTSTime + uCTSTime + uAckTime + uDataTime + 3*pDevice->uSIFS;
+    return uRrvTime;
+}
+
+//byFreqType 0: 5GHz, 1:2.4Ghz
+static
+UINT
+s_uGetDataDuration (
+    IN PSDevice pDevice,
+    IN BYTE     byDurType,
+    IN UINT     cbFrameLength,
+    IN BYTE     byPktType,
+    IN WORD     wRate,
+    IN BOOL     bNeedAck,
+    IN UINT     uFragIdx,
+    IN UINT     cbLastFragmentSize,
+    IN UINT     uMACfragNum,
+    IN BYTE     byFBOption
+    )
+{
+    BOOL bLastFrag = 0;
+    UINT uAckTime =0, uNextPktTime = 0;
+
+
+
+    if (uFragIdx == (uMACfragNum-1)) {
+        bLastFrag = 1;
+    }
+
+
+    switch (byDurType) {
+
+    case DATADUR_B:    //DATADUR_B
+        if (((uMACfragNum == 1)) || (bLastFrag == 1)) {//Non Frag or Last Frag
+            if (bNeedAck) {
+            	uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
+                return (pDevice->uSIFS + uAckTime);
+            } else {
+                return 0;
+            }
+        }
+        else {//First Frag or Mid Frag
+            if (uFragIdx == (uMACfragNum-2)) {
+            	uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wRate, bNeedAck);
+            } else {
+                uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
+            }
+            if (bNeedAck) {
+            	uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
+                return (pDevice->uSIFS + uAckTime + uNextPktTime);
+            } else {
+                return (pDevice->uSIFS + uNextPktTime);
+            }
+        }
+        break;
+
+    case DATADUR_A:    //DATADUR_A
+        if (((uMACfragNum==1)) || (bLastFrag==1)) {//Non Frag or Last Frag
+            if(bNeedAck){
+            	uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
+                return (pDevice->uSIFS + uAckTime);
+            } else {
+                return 0;
+            }
+        }
+        else {//First Frag or Mid Frag
+            if(uFragIdx == (uMACfragNum-2)){
+            	uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wRate, bNeedAck);
+            } else {
+                uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
+            }
+            if(bNeedAck){
+            	uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
+                return (pDevice->uSIFS + uAckTime + uNextPktTime);
+            } else {
+                return (pDevice->uSIFS + uNextPktTime);
+            }
+        }
+        break;
+
+    case DATADUR_A_F0:    //DATADUR_A_F0
+	    if (((uMACfragNum==1)) || (bLastFrag==1)) {//Non Frag or Last Frag
+            if(bNeedAck){
+            	uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
+                return (pDevice->uSIFS + uAckTime);
+            } else {
+                return 0;
+            }
+        }
+	    else { //First Frag or Mid Frag
+	        if (byFBOption == AUTO_FB_0) {
+                if (wRate < RATE_18M)
+                    wRate = RATE_18M;
+                else if (wRate > RATE_54M)
+                    wRate = RATE_54M;
+
+	            if(uFragIdx == (uMACfragNum-2)){
+            	    uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wFB_Opt0[FB_RATE0][wRate-RATE_18M], bNeedAck);
+                } else {
+                    uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE0][wRate-RATE_18M], bNeedAck);
+                }
+	        } else { // (byFBOption == AUTO_FB_1)
+                if (wRate < RATE_18M)
+                    wRate = RATE_18M;
+                else if (wRate > RATE_54M)
+                    wRate = RATE_54M;
+
+	            if(uFragIdx == (uMACfragNum-2)){
+            	    uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wFB_Opt1[FB_RATE0][wRate-RATE_18M], bNeedAck);
+                } else {
+                    uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE0][wRate-RATE_18M], bNeedAck);
+                }
+	        }
+
+	        if(bNeedAck){
+            	uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
+                return (pDevice->uSIFS + uAckTime + uNextPktTime);
+            } else {
+                return (pDevice->uSIFS + uNextPktTime);
+            }
+	    }
+        break;
+
+    case DATADUR_A_F1:    //DATADUR_A_F1
+        if (((uMACfragNum==1)) || (bLastFrag==1)) {//Non Frag or Last Frag
+            if(bNeedAck){
+            	uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
+                return (pDevice->uSIFS + uAckTime);
+            } else {
+                return 0;
+            }
+        }
+	    else { //First Frag or Mid Frag
+	        if (byFBOption == AUTO_FB_0) {
+                if (wRate < RATE_18M)
+                    wRate = RATE_18M;
+                else if (wRate > RATE_54M)
+                    wRate = RATE_54M;
+
+	            if(uFragIdx == (uMACfragNum-2)){
+            	    uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wFB_Opt0[FB_RATE1][wRate-RATE_18M], bNeedAck);
+                } else {
+                    uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE1][wRate-RATE_18M], bNeedAck);
+                }
+
+	        } else { // (byFBOption == AUTO_FB_1)
+                if (wRate < RATE_18M)
+                    wRate = RATE_18M;
+                else if (wRate > RATE_54M)
+                    wRate = RATE_54M;
+
+	            if(uFragIdx == (uMACfragNum-2)){
+            	    uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbLastFragmentSize, wFB_Opt1[FB_RATE1][wRate-RATE_18M], bNeedAck);
+                } else {
+                    uNextPktTime = s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE1][wRate-RATE_18M], bNeedAck);
+                }
+	        }
+	        if(bNeedAck){
+            	uAckTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
+                return (pDevice->uSIFS + uAckTime + uNextPktTime);
+            } else {
+                return (pDevice->uSIFS + uNextPktTime);
+            }
+	    }
+        break;
+
+    default:
+        break;
+    }
+
+	ASSERT(FALSE);
+	return 0;
+}
+
+
+//byFreqType: 0=>5GHZ 1=>2.4GHZ
+static
+UINT
+s_uGetRTSCTSDuration (
+    IN PSDevice pDevice,
+    IN BYTE byDurType,
+    IN UINT cbFrameLength,
+    IN BYTE byPktType,
+    IN WORD wRate,
+    IN BOOL bNeedAck,
+    IN BYTE byFBOption
+    )
+{
+    UINT uCTSTime = 0, uDurTime = 0;
+
+
+    switch (byDurType) {
+
+    case RTSDUR_BB:    //RTSDuration_bb
+        uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
+        uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
+        break;
+
+    case RTSDUR_BA:    //RTSDuration_ba
+        uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
+        uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
+        break;
+
+    case RTSDUR_AA:    //RTSDuration_aa
+        uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
+        uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
+        break;
+
+    case CTSDUR_BA:    //CTSDuration_ba
+        uDurTime = pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wRate, bNeedAck);
+        break;
+
+    case RTSDUR_BA_F0: //RTSDuration_ba_f0
+        uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
+        if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE0][wRate-RATE_18M], bNeedAck);
+        } else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE0][wRate-RATE_18M], bNeedAck);
+        }
+        break;
+
+    case RTSDUR_AA_F0: //RTSDuration_aa_f0
+        uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
+        if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE0][wRate-RATE_18M], bNeedAck);
+        } else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE0][wRate-RATE_18M], bNeedAck);
+        }
+        break;
+
+    case RTSDUR_BA_F1: //RTSDuration_ba_f1
+        uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopCCKBasicRate);
+        if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE1][wRate-RATE_18M], bNeedAck);
+        } else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE1][wRate-RATE_18M], bNeedAck);
+        }
+        break;
+
+    case RTSDUR_AA_F1: //RTSDuration_aa_f1
+        uCTSTime = BBuGetFrameTime(pDevice->byPreambleType, byPktType, 14, pDevice->byTopOFDMBasicRate);
+        if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE1][wRate-RATE_18M], bNeedAck);
+        } else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = uCTSTime + 2*pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE1][wRate-RATE_18M], bNeedAck);
+        }
+        break;
+
+    case CTSDUR_BA_F0: //CTSDuration_ba_f0
+        if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE0][wRate-RATE_18M], bNeedAck);
+        } else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE0][wRate-RATE_18M], bNeedAck);
+        }
+        break;
+
+    case CTSDUR_BA_F1: //CTSDuration_ba_f1
+        if ((byFBOption == AUTO_FB_0) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt0[FB_RATE1][wRate-RATE_18M], bNeedAck);
+        } else if ((byFBOption == AUTO_FB_1) && (wRate >= RATE_18M) && (wRate <=RATE_54M)) {
+            uDurTime = pDevice->uSIFS + s_uGetTxRsvTime(pDevice, byPktType, cbFrameLength, wFB_Opt1[FB_RATE1][wRate-RATE_18M], bNeedAck);
+        }
+        break;
+
+    default:
+        break;
+    }
+
+    return uDurTime;
+
+}
+
+
+
+static
+UINT
+s_uFillDataHead (
+    IN PSDevice pDevice,
+    IN BYTE     byPktTyp,
+    IN PVOID    pTxDataHead,
+    IN UINT     cbFrameLength,
+    IN UINT     uDMAIdx,
+    IN BOOL     bNeedAck,
+    IN UINT     uFragIdx,
+    IN UINT     cbLastFragmentSize,
+    IN UINT     uMACfragNum,
+    IN BYTE     byFBOption,
+    IN WORD     wCurrentRate
+    )
+{
+    WORD  wLen = 0x0000;
+
+    if (pTxDataHead == NULL) {
+        return 0;
+    }
+
+    if (byPktTyp == PK_TYPE_11GB || byPktTyp == PK_TYPE_11GA) {
+        if (byFBOption == AUTO_FB_NONE) {
+            PSTxDataHead_g pBuf = (PSTxDataHead_g)pTxDataHead;
+            //Get SignalField,ServiceField,Length
+            BBvCaculateParameter(pDevice, cbFrameLength, wCurrentRate, byPktTyp,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_a), (PBYTE)&(pBuf->bySignalField_a)
+            );
+            pBuf->wTransmitLength_a = cpu_to_le16(wLen);
+            BBvCaculateParameter(pDevice, cbFrameLength, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
+            );
+            pBuf->wTransmitLength_b = cpu_to_le16(wLen);
+            //Get Duration and TimeStamp
+            pBuf->wDuration_a = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_A, cbFrameLength,
+                                                         byPktTyp, wCurrentRate, bNeedAck, uFragIdx,
+                                                         cbLastFragmentSize, uMACfragNum,
+                                                         byFBOption)); //1: 2.4GHz
+            pBuf->wDuration_b = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_B, cbFrameLength,
+                                                         PK_TYPE_11B, pDevice->byTopCCKBasicRate,
+                                                         bNeedAck, uFragIdx, cbLastFragmentSize,
+                                                         uMACfragNum, byFBOption)); //1: 2.4
+
+            pBuf->wTimeStampOff_a = cpu_to_le16(wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE]);
+            pBuf->wTimeStampOff_b = cpu_to_le16(wTimeStampOff[pDevice->byPreambleType%2][pDevice->byTopCCKBasicRate%MAX_RATE]);
+
+            return (pBuf->wDuration_a);
+         } else {
+            // Auto Fallback
+            PSTxDataHead_g_FB pBuf = (PSTxDataHead_g_FB)pTxDataHead;
+            //Get SignalField,ServiceField,Length
+            BBvCaculateParameter(pDevice, cbFrameLength, wCurrentRate, byPktTyp,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_a), (PBYTE)&(pBuf->bySignalField_a)
+            );
+            pBuf->wTransmitLength_a = cpu_to_le16(wLen);
+            BBvCaculateParameter(pDevice, cbFrameLength, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
+            );
+            pBuf->wTransmitLength_b = cpu_to_le16(wLen);
+            //Get Duration and TimeStamp
+            pBuf->wDuration_a = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_A, cbFrameLength, byPktTyp,
+                                         wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption)); //1: 2.4GHz
+            pBuf->wDuration_b = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_B, cbFrameLength, PK_TYPE_11B,
+                                         pDevice->byTopCCKBasicRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption)); //1: 2.4GHz
+            pBuf->wDuration_a_f0 = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_A_F0, cbFrameLength, byPktTyp,
+                                         wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption)); //1: 2.4GHz
+            pBuf->wDuration_a_f1 = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_A_F1, cbFrameLength, byPktTyp,
+                                         wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption)); //1: 2.4GHz
+
+            pBuf->wTimeStampOff_a = cpu_to_le16(wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE]);
+            pBuf->wTimeStampOff_b = cpu_to_le16(wTimeStampOff[pDevice->byPreambleType%2][pDevice->byTopCCKBasicRate%MAX_RATE]);
+
+            return (pBuf->wDuration_a);
+        } //if (byFBOption == AUTO_FB_NONE)
+    }
+    else if (byPktTyp == PK_TYPE_11A) {
+        if ((byFBOption != AUTO_FB_NONE)) {
+            // Auto Fallback
+            PSTxDataHead_a_FB pBuf = (PSTxDataHead_a_FB)pTxDataHead;
+            //Get SignalField,ServiceField,Length
+            BBvCaculateParameter(pDevice, cbFrameLength, wCurrentRate, byPktTyp,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
+            );
+            pBuf->wTransmitLength = cpu_to_le16(wLen);
+            //Get Duration and TimeStampOff
+
+            pBuf->wDuration = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_A, cbFrameLength, byPktTyp,
+                                        wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption)); //0: 5GHz
+            pBuf->wDuration_f0 = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_A_F0, cbFrameLength, byPktTyp,
+                                        wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption)); //0: 5GHz
+            pBuf->wDuration_f1 = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_A_F1, cbFrameLength, byPktTyp,
+                                        wCurrentRate, bNeedAck, uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption)); //0: 5GHz
+            pBuf->wTimeStampOff = cpu_to_le16(wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE]);
+            return (pBuf->wDuration);
+        } else {
+            PSTxDataHead_ab pBuf = (PSTxDataHead_ab)pTxDataHead;
+            //Get SignalField,ServiceField,Length
+            BBvCaculateParameter(pDevice, cbFrameLength, wCurrentRate, byPktTyp,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
+            );
+            pBuf->wTransmitLength = cpu_to_le16(wLen);
+            //Get Duration and TimeStampOff
+
+            pBuf->wDuration = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_A, cbFrameLength, byPktTyp,
+                                                       wCurrentRate, bNeedAck, uFragIdx,
+                                                       cbLastFragmentSize, uMACfragNum,
+                                                       byFBOption));
+
+            pBuf->wTimeStampOff = cpu_to_le16(wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE]);
+            return (pBuf->wDuration);
+        }
+    }
+    else {
+            PSTxDataHead_ab pBuf = (PSTxDataHead_ab)pTxDataHead;
+            //Get SignalField,ServiceField,Length
+            BBvCaculateParameter(pDevice, cbFrameLength, wCurrentRate, byPktTyp,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
+            );
+            pBuf->wTransmitLength = cpu_to_le16(wLen);
+            //Get Duration and TimeStampOff
+            pBuf->wDuration = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_B, cbFrameLength, byPktTyp,
+                                                       wCurrentRate, bNeedAck, uFragIdx,
+                                                       cbLastFragmentSize, uMACfragNum,
+                                                       byFBOption));
+            pBuf->wTimeStampOff = cpu_to_le16(wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE]);
+            return (pBuf->wDuration);
+    }
+    return 0;
+}
+
+
+static
+VOID
+s_vFillRTSHead (
+    IN PSDevice         pDevice,
+    IN BYTE             byPktTyp,
+    IN PVOID            pvRTS,
+    IN UINT             cbFrameLength,
+    IN BOOL             bNeedAck,
+    IN BOOL             bDisCRC,
+    IN PSEthernetHeader psEthHeader,
+    IN WORD             wCurrentRate,
+    IN BYTE             byFBOption
+    )
+{
+    UINT uRTSFrameLen = 20;
+    WORD  wLen = 0x0000;
+
+    // dummy code, only to avoid compiler warning message
+    UNREFERENCED_PARAMETER(bNeedAck);
+
+    if (pvRTS == NULL)
+    	return;
+
+    if (bDisCRC) {
+        // When CRCDIS bit is on, H/W forgot to generate FCS for RTS frame,
+        // in this case we need to decrease its length by 4.
+        uRTSFrameLen -= 4;
+    }
+
+    // Note: So far RTSHead dosen't appear in ATIM & Beacom DMA, so we don't need to take them into account.
+    //       Otherwise, we need to modified codes for them.
+    if (byPktTyp == PK_TYPE_11GB || byPktTyp == PK_TYPE_11GA) {
+        if (byFBOption == AUTO_FB_NONE) {
+            PSRTS_g pBuf = (PSRTS_g)pvRTS;
+            //Get SignalField,ServiceField,Length
+            BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
+            );
+            pBuf->wTransmitLength_b = cpu_to_le16(wLen);
+            BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopOFDMBasicRate, byPktTyp,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_a), (PBYTE)&(pBuf->bySignalField_a)
+            );
+            pBuf->wTransmitLength_a = cpu_to_le16(wLen);
+            //Get Duration
+            pBuf->wDuration_bb = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BB, cbFrameLength, PK_TYPE_11B, pDevice->byTopCCKBasicRate, bNeedAck, byFBOption));    //0:RTSDuration_bb, 1:2.4G, 1:CCKData
+            pBuf->wDuration_aa = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption)); //2:RTSDuration_aa, 1:2.4G, 2,3: 2.4G OFDMData
+            pBuf->wDuration_ba = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BA, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption)); //1:RTSDuration_ba, 1:2.4G, 2,3:2.4G OFDM Data
+
+            pBuf->Data.wDurationID = pBuf->wDuration_aa;
+            //Get RTS Frame body
+            pBuf->Data.wFrameControl = TYPE_CTL_RTS;//0x00B4
+            if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
+                (pDevice->eOPMode == OP_MODE_AP)) {
+                MEMvCopy(&(pBuf->Data.abyRA[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
+            }
+            else {
+                MEMvCopy(&(pBuf->Data.abyRA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+            }
+            if (pDevice->eOPMode == OP_MODE_AP) {
+                MEMvCopy(&(pBuf->Data.abyTA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+            }
+            else {
+                MEMvCopy(&(pBuf->Data.abyTA[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
+            }
+        }
+        else {
+           PSRTS_g_FB pBuf = (PSRTS_g_FB)pvRTS;
+            //Get SignalField,ServiceField,Length
+            BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
+            );
+            pBuf->wTransmitLength_b = cpu_to_le16(wLen);
+            BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopOFDMBasicRate, byPktTyp,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_a), (PBYTE)&(pBuf->bySignalField_a)
+            );
+            pBuf->wTransmitLength_a = cpu_to_le16(wLen);
+
+            //Get Duration
+            pBuf->wDuration_bb = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BB, cbFrameLength, PK_TYPE_11B, pDevice->byTopCCKBasicRate, bNeedAck, byFBOption));    //0:RTSDuration_bb, 1:2.4G, 1:CCKData
+            pBuf->wDuration_aa = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption)); //2:RTSDuration_aa, 1:2.4G, 2,3:2.4G OFDMData
+            pBuf->wDuration_ba = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BA, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption)); //1:RTSDuration_ba, 1:2.4G, 2,3:2.4G OFDMData
+            pBuf->wRTSDuration_ba_f0 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BA_F0, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption));    //4:wRTSDuration_ba_f0, 1:2.4G, 1:CCKData
+            pBuf->wRTSDuration_aa_f0 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA_F0, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption));    //5:wRTSDuration_aa_f0, 1:2.4G, 1:CCKData
+            pBuf->wRTSDuration_ba_f1 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BA_F1, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption));    //6:wRTSDuration_ba_f1, 1:2.4G, 1:CCKData
+            pBuf->wRTSDuration_aa_f1 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA_F1, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption));    //7:wRTSDuration_aa_f1, 1:2.4G, 1:CCKData
+            pBuf->Data.wDurationID = pBuf->wDuration_aa;
+            //Get RTS Frame body
+            pBuf->Data.wFrameControl = TYPE_CTL_RTS;//0x00B4
+
+            if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
+                (pDevice->eOPMode == OP_MODE_AP)) {
+                MEMvCopy(&(pBuf->Data.abyRA[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
+            }
+            else {
+                MEMvCopy(&(pBuf->Data.abyRA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+            }
+
+            if (pDevice->eOPMode == OP_MODE_AP) {
+                MEMvCopy(&(pBuf->Data.abyTA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+            }
+            else {
+                MEMvCopy(&(pBuf->Data.abyTA[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
+            }
+
+        } // if (byFBOption == AUTO_FB_NONE)
+    }
+    else if (byPktTyp == PK_TYPE_11A) {
+        if (byFBOption == AUTO_FB_NONE) {
+            PSRTS_ab pBuf = (PSRTS_ab)pvRTS;
+            //Get SignalField,ServiceField,Length
+            BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopOFDMBasicRate, byPktTyp,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
+            );
+            pBuf->wTransmitLength = cpu_to_le16(wLen);
+            //Get Duration
+            pBuf->wDuration = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption)); //0:RTSDuration_aa, 0:5G, 0: 5G OFDMData
+    	    pBuf->Data.wDurationID = pBuf->wDuration;
+            //Get RTS Frame body
+            pBuf->Data.wFrameControl = TYPE_CTL_RTS;//0x00B4
+
+            if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
+                (pDevice->eOPMode == OP_MODE_AP)) {
+                MEMvCopy(&(pBuf->Data.abyRA[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
+            }
+            else {
+                MEMvCopy(&(pBuf->Data.abyRA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+            }
+
+            if (pDevice->eOPMode == OP_MODE_AP) {
+                MEMvCopy(&(pBuf->Data.abyTA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+            }
+            else {
+                MEMvCopy(&(pBuf->Data.abyTA[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
+            }
+
+        }
+        else {
+            PSRTS_a_FB pBuf = (PSRTS_a_FB)pvRTS;
+            //Get SignalField,ServiceField,Length
+            BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopOFDMBasicRate, byPktTyp,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
+            );
+            pBuf->wTransmitLength = cpu_to_le16(wLen);
+            //Get Duration
+            pBuf->wDuration = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption)); //0:RTSDuration_aa, 0:5G, 0: 5G OFDMData
+    	    pBuf->wRTSDuration_f0 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA_F0, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption)); //5:RTSDuration_aa_f0, 0:5G, 0: 5G OFDMData
+    	    pBuf->wRTSDuration_f1 = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_AA_F1, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption)); //7:RTSDuration_aa_f1, 0:5G, 0:
+    	    pBuf->Data.wDurationID = pBuf->wDuration;
+    	    //Get RTS Frame body
+            pBuf->Data.wFrameControl = TYPE_CTL_RTS;//0x00B4
+
+            if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
+                (pDevice->eOPMode == OP_MODE_AP)) {
+                MEMvCopy(&(pBuf->Data.abyRA[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
+            }
+            else {
+                MEMvCopy(&(pBuf->Data.abyRA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+            }
+            if (pDevice->eOPMode == OP_MODE_AP) {
+                MEMvCopy(&(pBuf->Data.abyTA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+            }
+            else {
+                MEMvCopy(&(pBuf->Data.abyTA[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
+            }
+        }
+    }
+    else if (byPktTyp == PK_TYPE_11B) {
+        PSRTS_ab pBuf = (PSRTS_ab)pvRTS;
+        //Get SignalField,ServiceField,Length
+        BBvCaculateParameter(pDevice, uRTSFrameLen, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
+            (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField), (PBYTE)&(pBuf->bySignalField)
+        );
+        pBuf->wTransmitLength = cpu_to_le16(wLen);
+        //Get Duration
+        pBuf->wDuration = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, RTSDUR_BB, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption)); //0:RTSDuration_bb, 1:2.4G, 1:CCKData
+        pBuf->Data.wDurationID = pBuf->wDuration;
+        //Get RTS Frame body
+        pBuf->Data.wFrameControl = TYPE_CTL_RTS;//0x00B4
+
+
+        if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
+            (pDevice->eOPMode == OP_MODE_AP)) {
+            MEMvCopy(&(pBuf->Data.abyRA[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
+        }
+        else {
+            MEMvCopy(&(pBuf->Data.abyRA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+        }
+
+        if (pDevice->eOPMode == OP_MODE_AP) {
+            MEMvCopy(&(pBuf->Data.abyTA[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+        }
+        else {
+            MEMvCopy(&(pBuf->Data.abyTA[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
+        }
+    }
+}
+
+static
+VOID
+s_vFillCTSHead (
+    IN PSDevice pDevice,
+    IN UINT     uDMAIdx,
+    IN BYTE     byPktTyp,
+    IN PVOID    pvCTS,
+    IN UINT     cbFrameLength,
+    IN BOOL     bNeedAck,
+    IN BOOL     bDisCRC,
+    IN WORD     wCurrentRate,
+    IN BYTE     byFBOption
+    )
+{
+    UINT uCTSFrameLen = 14;
+    WORD  wLen = 0x0000;
+
+    if (pvCTS == NULL) {
+        return;
+    }
+
+    if (bDisCRC) {
+        // When CRCDIS bit is on, H/W forgot to generate FCS for CTS frame,
+        // in this case we need to decrease its length by 4.
+        uCTSFrameLen -= 4;
+    }
+
+    if (byPktTyp == PK_TYPE_11GB || byPktTyp == PK_TYPE_11GA) {
+        if (byFBOption != AUTO_FB_NONE && uDMAIdx != TYPE_ATIMDMA && uDMAIdx != TYPE_BEACONDMA) {
+            // Auto Fall back
+            PSCTS_FB pBuf = (PSCTS_FB)pvCTS;
+            //Get SignalField,ServiceField,Length
+            BBvCaculateParameter(pDevice, uCTSFrameLen, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
+            );
+
+
+            pBuf->wTransmitLength_b = cpu_to_le16(wLen);
+
+            pBuf->wDuration_ba = (WORD)s_uGetRTSCTSDuration(pDevice, CTSDUR_BA, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption); //3:CTSDuration_ba, 1:2.4G, 2,3:2.4G OFDM Data
+            pBuf->wDuration_ba += pDevice->wCTSDuration;
+            pBuf->wDuration_ba = cpu_to_le16(pBuf->wDuration_ba);
+            //Get CTSDuration_ba_f0
+            pBuf->wCTSDuration_ba_f0 = (WORD)s_uGetRTSCTSDuration(pDevice, CTSDUR_BA_F0, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption); //8:CTSDuration_ba_f0, 1:2.4G, 2,3:2.4G OFDM Data
+            pBuf->wCTSDuration_ba_f0 += pDevice->wCTSDuration;
+            pBuf->wCTSDuration_ba_f0 = cpu_to_le16(pBuf->wCTSDuration_ba_f0);
+            //Get CTSDuration_ba_f1
+            pBuf->wCTSDuration_ba_f1 = (WORD)s_uGetRTSCTSDuration(pDevice, CTSDUR_BA_F1, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption); //9:CTSDuration_ba_f1, 1:2.4G, 2,3:2.4G OFDM Data
+            pBuf->wCTSDuration_ba_f1 += pDevice->wCTSDuration;
+            pBuf->wCTSDuration_ba_f1 = cpu_to_le16(pBuf->wCTSDuration_ba_f1);
+            //Get CTS Frame body
+            pBuf->Data.wDurationID = pBuf->wDuration_ba;
+            pBuf->Data.wFrameControl = TYPE_CTL_CTS;//0x00C4
+            pBuf->Data.wReserved = 0x0000;
+            MEMvCopy(&(pBuf->Data.abyRA[0]), &(pDevice->abyCurrentNetAddr[0]), U_ETHER_ADDR_LEN);
+
+        } else { //if (byFBOption != AUTO_FB_NONE && uDMAIdx != TYPE_ATIMDMA && uDMAIdx != TYPE_BEACONDMA)
+            PSCTS pBuf = (PSCTS)pvCTS;
+            //Get SignalField,ServiceField,Length
+            BBvCaculateParameter(pDevice, uCTSFrameLen, pDevice->byTopCCKBasicRate, PK_TYPE_11B,
+                (PWORD)&(wLen), (PBYTE)&(pBuf->byServiceField_b), (PBYTE)&(pBuf->bySignalField_b)
+            );
+            pBuf->wTransmitLength_b = cpu_to_le16(wLen);
+            //Get CTSDuration_ba
+            pBuf->wDuration_ba = cpu_to_le16((WORD)s_uGetRTSCTSDuration(pDevice, CTSDUR_BA, cbFrameLength, byPktTyp, wCurrentRate, bNeedAck, byFBOption)); //3:CTSDuration_ba, 1:2.4G, 2,3:2.4G OFDM Data
+            pBuf->wDuration_ba += pDevice->wCTSDuration;
+            pBuf->wDuration_ba = cpu_to_le16(pBuf->wDuration_ba);
+
+            //Get CTS Frame body
+            pBuf->Data.wDurationID = pBuf->wDuration_ba;
+            pBuf->Data.wFrameControl = TYPE_CTL_CTS;//0x00C4
+            pBuf->Data.wReserved = 0x0000;
+            MEMvCopy(&(pBuf->Data.abyRA[0]), &(pDevice->abyCurrentNetAddr[0]), U_ETHER_ADDR_LEN);
+        }
+    }
+}
+
+
+
+
+
+
+/*+
+ *
+ * Description:
+ *      Generate FIFO control for MAC & Baseband controller
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - Pointer to adpater
+ *      pTxDataHead     - Transmit Data Buffer
+ *      pTxBufHead      - pTxBufHead
+ *      pvRrvTime        - pvRrvTime
+ *      pvRTS            - RTS Buffer
+ *      pCTS            - CTS Buffer
+ *      cbFrameSize     - Transmit Data Length (Hdr+Payload+FCS)
+ *      bNeedACK        - If need ACK
+ *      uDescIdx        - Desc Index
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+-*/
+// UINT            cbFrameSize,//Hdr+Payload+FCS
+static
+VOID
+s_vGenerateTxParameter (
+    IN PSDevice         pDevice,
+    IN BYTE             byPktTyp,
+    IN PVOID            pTxBufHead,
+    IN PVOID            pvRrvTime,
+    IN PVOID            pvRTS,
+    IN PVOID            pvCTS,
+    IN UINT             cbFrameSize,
+    IN BOOL             bNeedACK,
+    IN UINT             uDMAIdx,
+    IN PSEthernetHeader psEthHeader,
+    IN WORD             wCurrentRate
+    )
+{
+    UINT cbMACHdLen = WLAN_HDR_ADDR3_LEN; //24
+    WORD wFifoCtl;
+    BOOL bDisCRC = FALSE;
+    BYTE byFBOption = AUTO_FB_NONE;
+//    WORD wCurrentRate = pDevice->wCurrentRate;
+
+    //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"s_vGenerateTxParameter...\n");
+    PSTxBufHead pFifoHead = (PSTxBufHead)pTxBufHead;
+    pFifoHead->wReserved = wCurrentRate;
+    wFifoCtl = pFifoHead->wFIFOCtl;
+
+    if (wFifoCtl & FIFOCTL_CRCDIS) {
+        bDisCRC = TRUE;
+    }
+
+    if (wFifoCtl & FIFOCTL_AUTO_FB_0) {
+        byFBOption = AUTO_FB_0;
+    }
+    else if (wFifoCtl & FIFOCTL_AUTO_FB_1) {
+        byFBOption = AUTO_FB_1;
+    }
+
+    if (pDevice->bLongHeader)
+        cbMACHdLen = WLAN_HDR_ADDR3_LEN + 6;
+
+    if (byPktTyp == PK_TYPE_11GB || byPktTyp == PK_TYPE_11GA) {
+
+        if (pvRTS != NULL) { //RTS_need
+            //Fill RsvTime
+            if (pvRrvTime) {
+                PSRrvTime_gRTS pBuf = (PSRrvTime_gRTS)pvRrvTime;
+                pBuf->wRTSTxRrvTime_aa = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 2, byPktTyp, cbFrameSize, wCurrentRate));//2:RTSTxRrvTime_aa, 1:2.4GHz
+                pBuf->wRTSTxRrvTime_ba = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 1, byPktTyp, cbFrameSize, wCurrentRate));//1:RTSTxRrvTime_ba, 1:2.4GHz
+                pBuf->wRTSTxRrvTime_bb = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 0, byPktTyp, cbFrameSize, wCurrentRate));//0:RTSTxRrvTime_bb, 1:2.4GHz
+                pBuf->wTxRrvTime_a = cpu_to_le16((WORD) s_uGetTxRsvTime(pDevice, byPktTyp, cbFrameSize, wCurrentRate, bNeedACK));//2.4G OFDM
+                pBuf->wTxRrvTime_b = cpu_to_le16((WORD) s_uGetTxRsvTime(pDevice, PK_TYPE_11B, cbFrameSize, pDevice->byTopCCKBasicRate, bNeedACK));//1:CCK
+            }
+            //Fill RTS
+            s_vFillRTSHead(pDevice, byPktTyp, pvRTS, cbFrameSize, bNeedACK, bDisCRC, psEthHeader, wCurrentRate, byFBOption);
+        }
+        else {//RTS_needless, PCF mode
+
+            //Fill RsvTime
+            if (pvRrvTime) {
+                PSRrvTime_gCTS pBuf = (PSRrvTime_gCTS)pvRrvTime;
+                pBuf->wTxRrvTime_a = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, byPktTyp, cbFrameSize, wCurrentRate, bNeedACK));//2.4G OFDM
+                pBuf->wTxRrvTime_b = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, PK_TYPE_11B, cbFrameSize, pDevice->byTopCCKBasicRate, bNeedACK));//1:CCK
+                pBuf->wCTSTxRrvTime_ba = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 3, byPktTyp, cbFrameSize, wCurrentRate));//3:CTSTxRrvTime_Ba, 1:2.4GHz
+            }
+
+
+            //Fill CTS
+            s_vFillCTSHead(pDevice, uDMAIdx, byPktTyp, pvCTS, cbFrameSize, bNeedACK, bDisCRC, wCurrentRate, byFBOption);
+        }
+    }
+    else if (byPktTyp == PK_TYPE_11A) {
+
+        if (pvRTS != NULL) {//RTS_need, non PCF mode
+            //Fill RsvTime
+            if (pvRrvTime) {
+                PSRrvTime_ab pBuf = (PSRrvTime_ab)pvRrvTime;
+                pBuf->wRTSTxRrvTime = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 2, byPktTyp, cbFrameSize, wCurrentRate));//2:RTSTxRrvTime_aa, 0:5GHz
+                pBuf->wTxRrvTime = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, byPktTyp, cbFrameSize, wCurrentRate, bNeedACK));//0:OFDM
+            }
+            //Fill RTS
+            s_vFillRTSHead(pDevice, byPktTyp, pvRTS, cbFrameSize, bNeedACK, bDisCRC, psEthHeader, wCurrentRate, byFBOption);
+        }
+        else if (pvRTS == NULL) {//RTS_needless, non PCF mode
+            //Fill RsvTime
+            if (pvRrvTime) {
+                PSRrvTime_ab pBuf = (PSRrvTime_ab)pvRrvTime;
+                pBuf->wTxRrvTime = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, PK_TYPE_11A, cbFrameSize, wCurrentRate, bNeedACK)); //0:OFDM
+            }
+        }
+    }
+    else if (byPktTyp == PK_TYPE_11B) {
+
+        if ((pvRTS != NULL)) {//RTS_need, non PCF mode
+            //Fill RsvTime
+            if (pvRrvTime) {
+                PSRrvTime_ab pBuf = (PSRrvTime_ab)pvRrvTime;
+                pBuf->wRTSTxRrvTime = cpu_to_le16((WORD)s_uGetRTSCTSRsvTime(pDevice, 0, byPktTyp, cbFrameSize, wCurrentRate));//0:RTSTxRrvTime_bb, 1:2.4GHz
+                pBuf->wTxRrvTime = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, PK_TYPE_11B, cbFrameSize, wCurrentRate, bNeedACK));//1:CCK
+            }
+            //Fill RTS
+            s_vFillRTSHead(pDevice, byPktTyp, pvRTS, cbFrameSize, bNeedACK, bDisCRC, psEthHeader, wCurrentRate, byFBOption);
+        }
+        else { //RTS_needless, non PCF mode
+            //Fill RsvTime
+            if (pvRrvTime) {
+                PSRrvTime_ab pBuf = (PSRrvTime_ab)pvRrvTime;
+                pBuf->wTxRrvTime = cpu_to_le16((WORD)s_uGetTxRsvTime(pDevice, PK_TYPE_11B, cbFrameSize, wCurrentRate, bNeedACK)); //1:CCK
+            }
+        }
+    }
+    //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"s_vGenerateTxParameter END.\n");
+}
+/*
+    PBYTE pbyBuffer,//point to pTxBufHead
+    WORD  wFragType,//00:Non-Frag, 01:Start, 02:Mid, 03:Last
+    UINT  cbFragmentSize,//Hdr+payoad+FCS
+*/
+static
+VOID
+s_vFillFragParameter(
+    IN PSDevice pDevice,
+    IN PBYTE    pbyBuffer,
+    IN UINT     uTxType,
+    IN PVOID    pvtdCurr,
+    IN WORD     wFragType,
+    IN UINT     cbReqCount
+    )
+{
+    PSTxBufHead pTxBufHead = (PSTxBufHead) pbyBuffer;
+    //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"s_vFillFragParameter...\n");
+
+    if (uTxType == TYPE_SYNCDMA) {
+        //PSTxSyncDesc ptdCurr = (PSTxSyncDesc)s_pvGetTxDescHead(pDevice, uTxType, uCurIdx);
+        PSTxSyncDesc ptdCurr = (PSTxSyncDesc)pvtdCurr;
+
+         //Set FIFOCtl & TimeStamp in TxSyncDesc
+        ptdCurr->m_wFIFOCtl = pTxBufHead->wFIFOCtl;
+        ptdCurr->m_wTimeStamp = pTxBufHead->wTimeStamp;
+        //Set TSR1 & ReqCount in TxDescHead
+        ptdCurr->m_td1TD1.wReqCount = cpu_to_le16((WORD)(cbReqCount));
+        if (wFragType == FRAGCTL_ENDFRAG) { //Last Fragmentation
+            ptdCurr->m_td1TD1.byTCR |= (TCR_STP | TCR_EDP | EDMSDU);
+        }
+        else {
+            ptdCurr->m_td1TD1.byTCR |= (TCR_STP | TCR_EDP);
+        }
+    }
+    else {
+        //PSTxDesc ptdCurr = (PSTxDesc)s_pvGetTxDescHead(pDevice, uTxType, uCurIdx);
+        PSTxDesc ptdCurr = (PSTxDesc)pvtdCurr;
+        //Set TSR1 & ReqCount in TxDescHead
+        ptdCurr->m_td1TD1.wReqCount = cpu_to_le16((WORD)(cbReqCount));
+        if (wFragType == FRAGCTL_ENDFRAG) { //Last Fragmentation
+            ptdCurr->m_td1TD1.byTCR |= (TCR_STP | TCR_EDP | EDMSDU);
+        }
+        else {
+            ptdCurr->m_td1TD1.byTCR |= (TCR_STP | TCR_EDP);
+        }
+    }
+
+    pTxBufHead->wFragCtl |= (WORD)wFragType;//0x0001; //0000 0000 0000 0001
+
+    //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"s_vFillFragParameter END\n");
+}
+
+static
+UINT
+s_cbFillTxBufHead (
+    IN  PSDevice         pDevice,
+    IN  BYTE             byPktTyp,
+    IN  PBYTE            pbyTxBufferAddr,
+    IN  UINT             cbFrameBodySize,
+    IN  UINT             uDMAIdx,
+    IN  PSTxDesc         pHeadTD,
+    IN  PSEthernetHeader psEthHeader,
+    IN  PBYTE            pPacket,
+    IN  BOOL             bNeedEncrypt,
+    IN  PSKeyItem        pTransmitKey,
+    IN  UINT             uNodeIndex,
+    OUT PUINT            puMACfragNum
+    )
+{
+    UINT           cbMACHdLen;
+    UINT           cbFrameSize;
+    UINT           cbFragmentSize; //Hdr+(IV)+payoad+(MIC)+(ICV)+FCS
+    UINT           cbFragPayloadSize;
+    UINT           cbLastFragmentSize; //Hdr+(IV)+payoad+(MIC)+(ICV)+FCS
+    UINT           cbLastFragPayloadSize;
+    UINT           uFragIdx;
+    PBYTE          pbyPayloadHead;
+    PBYTE          pbyIVHead;
+    PBYTE          pbyMacHdr;
+    WORD           wFragType; //00:Non-Frag, 01:Start, 10:Mid, 11:Last
+    UINT           uDuration;
+    PBYTE          pbyBuffer;
+//    UINT           uKeyEntryIdx = NUM_KEY_ENTRY+1;
+//    BYTE           byKeySel = 0xFF;
+    UINT           cbIVlen = 0;
+    UINT           cbICVlen = 0;
+    UINT           cbMIClen = 0;
+    UINT           cbFCSlen = 4;
+    UINT           cb802_1_H_len = 0;
+    UINT           uLength = 0;
+    UINT           uTmpLen = 0;
+//    BYTE           abyTmp[8];
+//    DWORD          dwCRC;
+    UINT           cbMICHDR = 0;
+    DWORD          dwMICKey0, dwMICKey1;
+    DWORD          dwMIC_Priority;
+    PDWORD         pdwMIC_L;
+    PDWORD         pdwMIC_R;
+    DWORD          dwSafeMIC_L, dwSafeMIC_R; //Fix "Last Frag Size" < "MIC length".
+    BOOL           bMIC2Frag = FALSE;
+    UINT           uMICFragLen = 0;
+    UINT           uMACfragNum = 1;
+    UINT           uPadding = 0;
+    UINT           cbReqCount = 0;
+
+    BOOL           bNeedACK;
+    BOOL           bRTS;
+    BOOL           bIsAdhoc;
+    PBYTE          pbyType;
+    PSTxDesc       ptdCurr;
+    PSTxBufHead    psTxBufHd = (PSTxBufHead) pbyTxBufferAddr;
+//    UINT           tmpDescIdx;
+    UINT           cbHeaderLength = 0;
+    PVOID          pvRrvTime;
+    PSMICHDRHead   pMICHDR;
+    PVOID          pvRTS;
+    PVOID          pvCTS;
+    PVOID          pvTxDataHd;
+    WORD           wTxBufSize;   // FFinfo size
+    UINT           uTotalCopyLength = 0;
+    BYTE           byFBOption = AUTO_FB_NONE;
+    BOOL           bIsWEP256 = FALSE;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+
+
+    pvRrvTime = pMICHDR = pvRTS = pvCTS = pvTxDataHd = NULL;
+
+    //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"s_cbFillTxBufHead...\n");
+    if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
+        (pDevice->eOPMode == OP_MODE_AP)) {
+
+        if (IS_MULTICAST_ADDRESS(&(psEthHeader->abyDstAddr[0])) ||
+            IS_BROADCAST_ADDRESS(&(psEthHeader->abyDstAddr[0]))) {
+            bNeedACK = FALSE;
+        }
+        else {
+            bNeedACK = TRUE;
+        }
+        bIsAdhoc = TRUE;
+    }
+    else {
+        // MSDUs in Infra mode always need ACK
+        bNeedACK = TRUE;
+        bIsAdhoc = FALSE;
+    }
+
+    if (pDevice->bLongHeader)
+        cbMACHdLen = WLAN_HDR_ADDR3_LEN + 6;
+    else
+        cbMACHdLen = WLAN_HDR_ADDR3_LEN;
+
+
+    if ((bNeedEncrypt == TRUE) && (pTransmitKey != NULL)) {
+        if (pTransmitKey->byCipherSuite == KEY_CTL_WEP) {
+            cbIVlen = 4;
+            cbICVlen = 4;
+            if (pTransmitKey->uKeyLength == WLAN_WEP232_KEYLEN) {
+                bIsWEP256 = TRUE;
+            }
+        }
+        if (pTransmitKey->byCipherSuite == KEY_CTL_TKIP) {
+            cbIVlen = 8;//IV+ExtIV
+            cbMIClen = 8;
+            cbICVlen = 4;
+        }
+        if (pTransmitKey->byCipherSuite == KEY_CTL_CCMP) {
+            cbIVlen = 8;//RSN Header
+            cbICVlen = 8;//MIC
+            cbMICHDR = sizeof(SMICHDRHead);
+        }
+        if (pDevice->byLocalID > REV_ID_VT3253_A1) {
+            //MAC Header should be padding 0 to DW alignment.
+            uPadding = 4 - (cbMACHdLen%4);
+            uPadding %= 4;
+        }
+    }
+
+
+    cbFrameSize = cbMACHdLen + cbIVlen + (cbFrameBodySize + cbMIClen) + cbICVlen + cbFCSlen;
+
+    if ((bNeedACK == FALSE) ||
+        (cbFrameSize < pDevice->wRTSThreshold) ||
+        ((cbFrameSize >= pDevice->wFragmentationThreshold) && (pDevice->wFragmentationThreshold <= pDevice->wRTSThreshold))
+        ) {
+        bRTS = FALSE;
+    }
+    else {
+        bRTS = TRUE;
+        psTxBufHd->wFIFOCtl |= (FIFOCTL_RTS | FIFOCTL_LRETRY);
+    }
+    //
+    // Use for AUTO FALL BACK
+    //
+    if (psTxBufHd->wFIFOCtl & FIFOCTL_AUTO_FB_0) {
+        byFBOption = AUTO_FB_0;
+    }
+    else if (psTxBufHd->wFIFOCtl & FIFOCTL_AUTO_FB_1) {
+        byFBOption = AUTO_FB_1;
+    }
+
+    //////////////////////////////////////////////////////
+    //Set RrvTime/RTS/CTS Buffer
+    wTxBufSize = sizeof(STxBufHead);
+    if (byPktTyp == PK_TYPE_11GB || byPktTyp == PK_TYPE_11GA) {//802.11g packet
+
+        if (byFBOption == AUTO_FB_NONE) {
+            if (bRTS == TRUE) {//RTS_need
+                pvRrvTime = (PSRrvTime_gRTS) (pbyTxBufferAddr + wTxBufSize);
+                pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS));
+                pvRTS = (PSRTS_g) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR);
+                pvCTS = NULL;
+                pvTxDataHd = (PSTxDataHead_g) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR + sizeof(SRTS_g));
+                cbHeaderLength = wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR + sizeof(SRTS_g) + sizeof(STxDataHead_g);
+            }
+            else { //RTS_needless
+                pvRrvTime = (PSRrvTime_gCTS) (pbyTxBufferAddr + wTxBufSize);
+                pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS));
+                pvRTS = NULL;
+                pvCTS = (PSCTS) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR);
+                pvTxDataHd = (PSTxDataHead_g) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS));
+                cbHeaderLength = wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS) + sizeof(STxDataHead_g);
+            }
+        } else {
+            // Auto Fall Back
+            if (bRTS == TRUE) {//RTS_need
+                pvRrvTime = (PSRrvTime_gRTS) (pbyTxBufferAddr + wTxBufSize);
+                pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS));
+                pvRTS = (PSRTS_g_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR);
+                pvCTS = NULL;
+                pvTxDataHd = (PSTxDataHead_g_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR + sizeof(SRTS_g_FB));
+                cbHeaderLength = wTxBufSize + sizeof(SRrvTime_gRTS) + cbMICHDR + sizeof(SRTS_g_FB) + sizeof(STxDataHead_g_FB);
+            }
+            else { //RTS_needless
+                pvRrvTime = (PSRrvTime_gCTS) (pbyTxBufferAddr + wTxBufSize);
+                pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS));
+                pvRTS = NULL;
+                pvCTS = (PSCTS_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR);
+                pvTxDataHd = (PSTxDataHead_g_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS_FB));
+                cbHeaderLength = wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS_FB) + sizeof(STxDataHead_g_FB);
+            }
+        } // Auto Fall Back
+    }
+    else {//802.11a/b packet
+
+        if (byFBOption == AUTO_FB_NONE) {
+            if (bRTS == TRUE) {
+                pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
+                pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
+                pvRTS = (PSRTS_ab) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR);
+                pvCTS = NULL;
+                pvTxDataHd = (PSTxDataHead_ab) (pbyTxBufferAddr + wTxBufSize + sizeof(PSRrvTime_ab) + cbMICHDR + sizeof(SRTS_ab));
+                cbHeaderLength = wTxBufSize + sizeof(PSRrvTime_ab) + cbMICHDR + sizeof(SRTS_ab) + sizeof(STxDataHead_ab);
+            }
+            else { //RTS_needless, need MICHDR
+                pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
+                pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
+                pvRTS = NULL;
+                pvCTS = NULL;
+                pvTxDataHd = (PSTxDataHead_ab) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR);
+                cbHeaderLength = wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR + sizeof(STxDataHead_ab);
+            }
+        } else {
+            // Auto Fall Back
+            if (bRTS == TRUE) {//RTS_need
+                pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
+                pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
+                pvRTS = (PSRTS_a_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR);
+                pvCTS = NULL;
+                pvTxDataHd = (PSTxDataHead_a_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(PSRrvTime_ab) + cbMICHDR + sizeof(SRTS_a_FB));
+                cbHeaderLength = wTxBufSize + sizeof(PSRrvTime_ab) + cbMICHDR + sizeof(SRTS_a_FB) + sizeof(STxDataHead_a_FB);
+            }
+            else { //RTS_needless
+                pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
+                pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
+                pvRTS = NULL;
+                pvCTS = NULL;
+                pvTxDataHd = (PSTxDataHead_a_FB) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR);
+                cbHeaderLength = wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR + sizeof(STxDataHead_a_FB);
+            }
+        } // Auto Fall Back
+    }
+    ZERO_MEMORY((PVOID)(pbyTxBufferAddr + wTxBufSize), (cbHeaderLength - wTxBufSize));
+
+//////////////////////////////////////////////////////////////////
+    if ((bNeedEncrypt == TRUE) && (pTransmitKey != NULL) && (pTransmitKey->byCipherSuite == KEY_CTL_TKIP)) {
+        if (pDevice->pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) {
+            dwMICKey0 = *(PDWORD)(&pTransmitKey->abyKey[16]);
+            dwMICKey1 = *(PDWORD)(&pTransmitKey->abyKey[20]);
+        }
+        else if ((pTransmitKey->dwKeyIndex & AUTHENTICATOR_KEY) != 0) {
+            dwMICKey0 = *(PDWORD)(&pTransmitKey->abyKey[16]);
+            dwMICKey1 = *(PDWORD)(&pTransmitKey->abyKey[20]);
+        }
+        else {
+            dwMICKey0 = *(PDWORD)(&pTransmitKey->abyKey[24]);
+            dwMICKey1 = *(PDWORD)(&pTransmitKey->abyKey[28]);
+        }
+        // DO Software Michael
+        MIC_vInit(dwMICKey0, dwMICKey1);
+        MIC_vAppend((PBYTE)&(psEthHeader->abyDstAddr[0]), 12);
+        dwMIC_Priority = 0;
+        MIC_vAppend((PBYTE)&dwMIC_Priority, 4);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MIC KEY: %lX, %lX\n", dwMICKey0, dwMICKey1);
+    }
+
+///////////////////////////////////////////////////////////////////
+
+    pbyMacHdr = (PBYTE)(pbyTxBufferAddr + cbHeaderLength);
+    pbyPayloadHead = (PBYTE)(pbyMacHdr + cbMACHdLen + uPadding + cbIVlen);
+    pbyIVHead = (PBYTE)(pbyMacHdr + cbMACHdLen + uPadding);
+
+    if ((cbFrameSize > pDevice->wFragmentationThreshold) && (bNeedACK == TRUE) && (bIsWEP256 == FALSE)) {
+        // Fragmentation
+        // FragThreshold = Fragment size(Hdr+(IV)+fragment payload+(MIC)+(ICV)+FCS)
+        cbFragmentSize = pDevice->wFragmentationThreshold;
+        cbFragPayloadSize = cbFragmentSize - cbMACHdLen - cbIVlen - cbICVlen - cbFCSlen;
+        //FragNum = (FrameSize-(Hdr+FCS))/(Fragment Size -(Hrd+FCS)))
+        uMACfragNum = (WORD) ((cbFrameBodySize + cbMIClen) / cbFragPayloadSize);
+        cbLastFragPayloadSize = (cbFrameBodySize + cbMIClen) % cbFragPayloadSize;
+        if (cbLastFragPayloadSize == 0) {
+            cbLastFragPayloadSize = cbFragPayloadSize;
+        } else {
+            uMACfragNum++;
+        }
+        //[Hdr+(IV)+last fragment payload+(MIC)+(ICV)+FCS]
+        cbLastFragmentSize = cbMACHdLen + cbLastFragPayloadSize + cbIVlen + cbICVlen + cbFCSlen;
+
+        for (uFragIdx = 0; uFragIdx < uMACfragNum; uFragIdx ++) {
+            if (uFragIdx == 0) {
+                //=========================
+                //    Start Fragmentation
+                //=========================
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Start Fragmentation...\n");
+                wFragType = FRAGCTL_STAFRAG;
+
+
+                //Fill FIFO,RrvTime,RTS,and CTS
+                s_vGenerateTxParameter(pDevice, byPktTyp, (PVOID)psTxBufHd, pvRrvTime, pvRTS, pvCTS,
+                                       cbFragmentSize, bNeedACK, uDMAIdx, psEthHeader, pDevice->wCurrentRate);
+                //Fill DataHead
+                uDuration = s_uFillDataHead(pDevice, byPktTyp, pvTxDataHd, cbFragmentSize, uDMAIdx, bNeedACK,
+                                            uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption, pDevice->wCurrentRate);
+                // Generate TX MAC Header
+                vGenerateMACHeader(pDevice, pbyMacHdr, (WORD)uDuration, psEthHeader, bNeedEncrypt,
+                                   wFragType, uDMAIdx, uFragIdx);
+
+                if (bNeedEncrypt == TRUE) {
+                    //Fill TXKEY
+                    s_vFillTxKey(pDevice, (PBYTE)(psTxBufHd->adwTxKey), pbyIVHead, pTransmitKey,
+                                 pbyMacHdr, (WORD)cbFragPayloadSize, (PBYTE)pMICHDR);
+                    //Fill IV(ExtIV,RSNHDR)
+                    if (pDevice->bEnableHostWEP) {
+                        pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16 = pTransmitKey->dwTSC47_16;
+                        pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0 = pTransmitKey->wTSC15_0;
+                    }
+                }
+
+
+                // 802.1H
+                if (ntohs(psEthHeader->wType) > MAX_DATA_LEN) {
+                    if ((psEthHeader->wType == TYPE_PKT_IPX) ||
+                        (psEthHeader->wType == cpu_to_le16(0xF380))) {
+                        MEMvCopy((PBYTE) (pbyPayloadHead), &pDevice->abySNAP_Bridgetunnel[0], 6);
+                    }
+                    else {
+                        MEMvCopy((PBYTE) (pbyPayloadHead), &pDevice->abySNAP_RFC1042[0], 6);
+                    }
+                    pbyType = (PBYTE) (pbyPayloadHead + 6);
+                    MEMvCopy(pbyType, &(psEthHeader->wType), sizeof(WORD));
+                    cb802_1_H_len = 8;
+                }
+
+                cbReqCount = cbHeaderLength + cbMACHdLen + uPadding + cbIVlen + cbFragPayloadSize;
+                //---------------------------
+                // S/W or H/W Encryption
+                //---------------------------
+                //Fill MICHDR
+                //if (pDevice->bAES) {
+                //    s_vFillMICHDR(pDevice, (PBYTE)pMICHDR, pbyMacHdr, (WORD)cbFragPayloadSize);
+                //}
+                //cbReqCount += s_uDoEncryption(pDevice, psEthHeader, (PVOID)psTxBufHd, byKeySel,
+                //                                pbyPayloadHead, (WORD)cbFragPayloadSize, uDMAIdx);
+
+
+
+                //pbyBuffer = (PBYTE)pDevice->aamTxBuf[uDMAIdx][uDescIdx].pbyVAddr;
+                pbyBuffer = (PBYTE)pHeadTD->pTDInfo->buf;
+
+                uLength = cbHeaderLength + cbMACHdLen + uPadding + cbIVlen + cb802_1_H_len;
+                //copy TxBufferHeader + MacHeader to desc
+                MEMvCopy(pbyBuffer, (PVOID)psTxBufHd, uLength);
+
+                // Copy the Packet into a tx Buffer
+                MEMvCopy((pbyBuffer + uLength), (pPacket + 14), (cbFragPayloadSize - cb802_1_H_len));
+
+
+                uTotalCopyLength += cbFragPayloadSize - cb802_1_H_len;
+
+                if ((bNeedEncrypt == TRUE) && (pTransmitKey != NULL) && (pTransmitKey->byCipherSuite == KEY_CTL_TKIP)) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Start MIC: %d\n", cbFragPayloadSize);
+                    MIC_vAppend((pbyBuffer + uLength - cb802_1_H_len), cbFragPayloadSize);
+
+                }
+
+                //---------------------------
+                // S/W Encryption
+                //---------------------------
+                if ((pDevice->byLocalID <= REV_ID_VT3253_A1)) {
+                    if (bNeedEncrypt) {
+                        s_vSWencryption(pDevice, pTransmitKey, (pbyBuffer + uLength - cb802_1_H_len), (WORD)cbFragPayloadSize);
+                        cbReqCount += cbICVlen;
+                    }
+                }
+
+                ptdCurr = (PSTxDesc)pHeadTD;
+                //--------------------
+                //1.Set TSR1 & ReqCount in TxDescHead
+                //2.Set FragCtl in TxBufferHead
+                //3.Set Frame Control
+                //4.Set Sequence Control
+                //5.Get S/W generate FCS
+                //--------------------
+                s_vFillFragParameter(pDevice, pbyBuffer, uDMAIdx, (PVOID)ptdCurr, wFragType, cbReqCount);
+
+                ptdCurr->pTDInfo->dwReqCount = cbReqCount - uPadding;
+                ptdCurr->pTDInfo->dwHeaderLength = cbHeaderLength;
+                ptdCurr->pTDInfo->skb_dma = ptdCurr->pTDInfo->buf_dma;
+                ptdCurr->buff_addr = cpu_to_le32(ptdCurr->pTDInfo->skb_dma);
+                pDevice->iTDUsed[uDMAIdx]++;
+                pHeadTD = ptdCurr->next;
+            }
+            else if (uFragIdx == (uMACfragNum-1)) {
+                //=========================
+                //    Last Fragmentation
+                //=========================
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Last Fragmentation...\n");
+                //tmpDescIdx = (uDescIdx + uFragIdx) % pDevice->cbTD[uDMAIdx];
+
+                wFragType = FRAGCTL_ENDFRAG;
+
+                //Fill FIFO,RrvTime,RTS,and CTS
+                s_vGenerateTxParameter(pDevice, byPktTyp, (PVOID)psTxBufHd, pvRrvTime, pvRTS, pvCTS,
+                                       cbLastFragmentSize, bNeedACK, uDMAIdx, psEthHeader, pDevice->wCurrentRate);
+                //Fill DataHead
+                uDuration = s_uFillDataHead(pDevice, byPktTyp, pvTxDataHd, cbLastFragmentSize, uDMAIdx, bNeedACK,
+                                            uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption, pDevice->wCurrentRate);
+
+                // Generate TX MAC Header
+                vGenerateMACHeader(pDevice, pbyMacHdr, (WORD)uDuration, psEthHeader, bNeedEncrypt,
+                                   wFragType, uDMAIdx, uFragIdx);
+
+                if (bNeedEncrypt == TRUE) {
+                    //Fill TXKEY
+                    s_vFillTxKey(pDevice, (PBYTE)(psTxBufHd->adwTxKey), pbyIVHead, pTransmitKey,
+                                 pbyMacHdr, (WORD)cbLastFragPayloadSize, (PBYTE)pMICHDR);
+
+                    if (pDevice->bEnableHostWEP) {
+                        pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16 = pTransmitKey->dwTSC47_16;
+                        pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0 = pTransmitKey->wTSC15_0;
+                    }
+
+                }
+
+
+                cbReqCount = cbHeaderLength + cbMACHdLen + uPadding + cbIVlen + cbLastFragPayloadSize;
+                //---------------------------
+                // S/W or H/W Encryption
+                //---------------------------
+
+
+
+                pbyBuffer = (PBYTE)pHeadTD->pTDInfo->buf;
+                //pbyBuffer = (PBYTE)pDevice->aamTxBuf[uDMAIdx][tmpDescIdx].pbyVAddr;
+
+                uLength = cbHeaderLength + cbMACHdLen + uPadding + cbIVlen;
+
+                //copy TxBufferHeader + MacHeader to desc
+                MEMvCopy(pbyBuffer, (PVOID)psTxBufHd, uLength);
+
+                // Copy the Packet into a tx Buffer
+                if (bMIC2Frag == FALSE) {
+
+                    MEMvCopy((pbyBuffer + uLength),
+                             (pPacket + 14 + uTotalCopyLength),
+                             (cbLastFragPayloadSize - cbMIClen)
+                             );
+                    //TODO check uTmpLen !
+                    uTmpLen = cbLastFragPayloadSize - cbMIClen;
+
+                }
+                if ((bNeedEncrypt == TRUE) && (pTransmitKey != NULL) && (pTransmitKey->byCipherSuite == KEY_CTL_TKIP)) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"LAST: uMICFragLen:%d, cbLastFragPayloadSize:%d, uTmpLen:%d\n",
+                                   uMICFragLen, cbLastFragPayloadSize, uTmpLen);
+
+                    if (bMIC2Frag == FALSE) {
+                        if (uTmpLen != 0)
+                            MIC_vAppend((pbyBuffer + uLength), uTmpLen);
+                        pdwMIC_L = (PDWORD)(pbyBuffer + uLength + uTmpLen);
+                        pdwMIC_R = (PDWORD)(pbyBuffer + uLength + uTmpLen + 4);
+                        MIC_vGetMIC(pdwMIC_L, pdwMIC_R);
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Last MIC:%lX, %lX\n", *pdwMIC_L, *pdwMIC_R);
+                    } else {
+                        if (uMICFragLen >= 4) {
+                            MEMvCopy((pbyBuffer + uLength), ((PBYTE)&dwSafeMIC_R + (uMICFragLen - 4)),
+                                     (cbMIClen - uMICFragLen));
+                            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"LAST: uMICFragLen >= 4: %X, %d\n",
+                                           *(PBYTE)((PBYTE)&dwSafeMIC_R + (uMICFragLen - 4)),
+                                           (cbMIClen - uMICFragLen));
+
+                        } else {
+                            MEMvCopy((pbyBuffer + uLength), ((PBYTE)&dwSafeMIC_L + uMICFragLen),
+                                     (4 - uMICFragLen));
+                            MEMvCopy((pbyBuffer + uLength + (4 - uMICFragLen)), &dwSafeMIC_R, 4);
+                            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"LAST: uMICFragLen < 4: %X, %d\n",
+                                           *(PBYTE)((PBYTE)&dwSafeMIC_R + uMICFragLen - 4),
+                                           (cbMIClen - uMICFragLen));
+                        }
+                        /*
+                        for (ii = 0; ii < cbLastFragPayloadSize + 8 + 24; ii++) {
+                            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%02x ", *((PBYTE)((pbyBuffer + uLength) + ii - 8 - 24)));
+                        }
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n\n");
+                        */
+                    }
+                    MIC_vUnInit();
+                } else {
+                    ASSERT(uTmpLen == (cbLastFragPayloadSize - cbMIClen));
+                }
+
+
+                //---------------------------
+                // S/W Encryption
+                //---------------------------
+                if ((pDevice->byLocalID <= REV_ID_VT3253_A1)) {
+                    if (bNeedEncrypt) {
+                        s_vSWencryption(pDevice, pTransmitKey, (pbyBuffer + uLength), (WORD)cbLastFragPayloadSize);
+                        cbReqCount += cbICVlen;
+                    }
+                }
+
+                ptdCurr = (PSTxDesc)pHeadTD;
+
+                //--------------------
+                //1.Set TSR1 & ReqCount in TxDescHead
+                //2.Set FragCtl in TxBufferHead
+                //3.Set Frame Control
+                //4.Set Sequence Control
+                //5.Get S/W generate FCS
+                //--------------------
+
+
+                s_vFillFragParameter(pDevice, pbyBuffer, uDMAIdx, (PVOID)ptdCurr, wFragType, cbReqCount);
+
+                ptdCurr->pTDInfo->dwReqCount = cbReqCount - uPadding;
+                ptdCurr->pTDInfo->dwHeaderLength = cbHeaderLength;
+                ptdCurr->pTDInfo->skb_dma = ptdCurr->pTDInfo->buf_dma;
+                ptdCurr->buff_addr = cpu_to_le32(ptdCurr->pTDInfo->skb_dma);
+                pDevice->iTDUsed[uDMAIdx]++;
+                pHeadTD = ptdCurr->next;
+
+            }
+            else {
+                //=========================
+                //    Middle Fragmentation
+                //=========================
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Middle Fragmentation...\n");
+                //tmpDescIdx = (uDescIdx + uFragIdx) % pDevice->cbTD[uDMAIdx];
+
+                wFragType = FRAGCTL_MIDFRAG;
+
+                //Fill FIFO,RrvTime,RTS,and CTS
+                s_vGenerateTxParameter(pDevice, byPktTyp, (PVOID)psTxBufHd, pvRrvTime, pvRTS, pvCTS,
+                                       cbFragmentSize, bNeedACK, uDMAIdx, psEthHeader, pDevice->wCurrentRate);
+                //Fill DataHead
+                uDuration = s_uFillDataHead(pDevice, byPktTyp, pvTxDataHd, cbFragmentSize, uDMAIdx, bNeedACK,
+                                            uFragIdx, cbLastFragmentSize, uMACfragNum, byFBOption, pDevice->wCurrentRate);
+
+                // Generate TX MAC Header
+                vGenerateMACHeader(pDevice, pbyMacHdr, (WORD)uDuration, psEthHeader, bNeedEncrypt,
+                                   wFragType, uDMAIdx, uFragIdx);
+
+
+                if (bNeedEncrypt == TRUE) {
+                    //Fill TXKEY
+                    s_vFillTxKey(pDevice, (PBYTE)(psTxBufHd->adwTxKey), pbyIVHead, pTransmitKey,
+                                 pbyMacHdr, (WORD)cbFragPayloadSize, (PBYTE)pMICHDR);
+
+                    if (pDevice->bEnableHostWEP) {
+                        pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16 = pTransmitKey->dwTSC47_16;
+                        pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0 = pTransmitKey->wTSC15_0;
+                    }
+                }
+
+                cbReqCount = cbHeaderLength + cbMACHdLen + uPadding + cbIVlen + cbFragPayloadSize;
+                //---------------------------
+                // S/W or H/W Encryption
+                //---------------------------
+                //Fill MICHDR
+                //if (pDevice->bAES) {
+                //    s_vFillMICHDR(pDevice, (PBYTE)pMICHDR, pbyMacHdr, (WORD)cbFragPayloadSize);
+                //}
+                //cbReqCount += s_uDoEncryption(pDevice, psEthHeader, (PVOID)psTxBufHd, byKeySel,
+                //                              pbyPayloadHead, (WORD)cbFragPayloadSize, uDMAIdx);
+
+
+                pbyBuffer = (PBYTE)pHeadTD->pTDInfo->buf;
+                //pbyBuffer = (PBYTE)pDevice->aamTxBuf[uDMAIdx][tmpDescIdx].pbyVAddr;
+
+
+                uLength = cbHeaderLength + cbMACHdLen + uPadding + cbIVlen;
+
+                //copy TxBufferHeader + MacHeader to desc
+                MEMvCopy(pbyBuffer, (PVOID)psTxBufHd, uLength);
+
+                // Copy the Packet into a tx Buffer
+                MEMvCopy((pbyBuffer + uLength),
+                         (pPacket + 14 + uTotalCopyLength),
+                         cbFragPayloadSize
+                        );
+                uTmpLen = cbFragPayloadSize;
+
+                uTotalCopyLength += uTmpLen;
+
+                if ((bNeedEncrypt == TRUE) && (pTransmitKey != NULL) && (pTransmitKey->byCipherSuite == KEY_CTL_TKIP)) {
+
+                    MIC_vAppend((pbyBuffer + uLength), uTmpLen);
+
+                    if (uTmpLen < cbFragPayloadSize) {
+                        bMIC2Frag = TRUE;
+                        uMICFragLen = cbFragPayloadSize - uTmpLen;
+                        ASSERT(uMICFragLen < cbMIClen);
+
+                        pdwMIC_L = (PDWORD)(pbyBuffer + uLength + uTmpLen);
+                        pdwMIC_R = (PDWORD)(pbyBuffer + uLength + uTmpLen + 4);
+                        MIC_vGetMIC(pdwMIC_L, pdwMIC_R);
+                        dwSafeMIC_L = *pdwMIC_L;
+                        dwSafeMIC_R = *pdwMIC_R;
+
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MIDDLE: uMICFragLen:%d, cbFragPayloadSize:%d, uTmpLen:%d\n",
+                                       uMICFragLen, cbFragPayloadSize, uTmpLen);
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Fill MIC in Middle frag [%d]\n", uMICFragLen);
+                        /*
+                        for (ii = 0; ii < uMICFragLen; ii++) {
+                            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%02x ", *((PBYTE)((pbyBuffer + uLength + uTmpLen) + ii)));
+                        }
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n");
+                        */
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Get MIC:%lX, %lX\n", *pdwMIC_L, *pdwMIC_R);
+                    }
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Middle frag len: %d\n", uTmpLen);
+                    /*
+                    for (ii = 0; ii < uTmpLen; ii++) {
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%02x ", *((PBYTE)((pbyBuffer + uLength) + ii)));
+                    }
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n\n");
+                    */
+
+                } else {
+                    ASSERT(uTmpLen == (cbFragPayloadSize));
+                }
+
+                if ((pDevice->byLocalID <= REV_ID_VT3253_A1)) {
+                    if (bNeedEncrypt) {
+                        s_vSWencryption(pDevice, pTransmitKey, (pbyBuffer + uLength), (WORD)cbFragPayloadSize);
+                        cbReqCount += cbICVlen;
+                    }
+                }
+
+                ptdCurr = (PSTxDesc)pHeadTD;
+
+                //--------------------
+                //1.Set TSR1 & ReqCount in TxDescHead
+                //2.Set FragCtl in TxBufferHead
+                //3.Set Frame Control
+                //4.Set Sequence Control
+                //5.Get S/W generate FCS
+                //--------------------
+
+                s_vFillFragParameter(pDevice, pbyBuffer, uDMAIdx, (PVOID)ptdCurr, wFragType, cbReqCount);
+
+                ptdCurr->pTDInfo->dwReqCount = cbReqCount - uPadding;
+                ptdCurr->pTDInfo->dwHeaderLength = cbHeaderLength;
+                ptdCurr->pTDInfo->skb_dma = ptdCurr->pTDInfo->buf_dma;
+                ptdCurr->buff_addr = cpu_to_le32(ptdCurr->pTDInfo->skb_dma);
+                pDevice->iTDUsed[uDMAIdx]++;
+                pHeadTD = ptdCurr->next;
+            }
+        }  // for (uMACfragNum)
+    }
+    else {
+        //=========================
+        //    No Fragmentation
+        //=========================
+        //DEVICE_PRTGRP03(("No Fragmentation...\n"));
+        //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"No Fragmentation...\n");
+        wFragType = FRAGCTL_NONFRAG;
+
+        //Set FragCtl in TxBufferHead
+        psTxBufHd->wFragCtl |= (WORD)wFragType;
+
+        //Fill FIFO,RrvTime,RTS,and CTS
+        s_vGenerateTxParameter(pDevice, byPktTyp, (PVOID)psTxBufHd, pvRrvTime, pvRTS, pvCTS,
+                               cbFrameSize, bNeedACK, uDMAIdx, psEthHeader, pDevice->wCurrentRate);
+        //Fill DataHead
+        uDuration = s_uFillDataHead(pDevice, byPktTyp, pvTxDataHd, cbFrameSize, uDMAIdx, bNeedACK,
+                                    0, 0, uMACfragNum, byFBOption, pDevice->wCurrentRate);
+
+        // Generate TX MAC Header
+        vGenerateMACHeader(pDevice, pbyMacHdr, (WORD)uDuration, psEthHeader, bNeedEncrypt,
+                           wFragType, uDMAIdx, 0);
+
+        if (bNeedEncrypt == TRUE) {
+            //Fill TXKEY
+            s_vFillTxKey(pDevice, (PBYTE)(psTxBufHd->adwTxKey), pbyIVHead, pTransmitKey,
+                         pbyMacHdr, (WORD)cbFrameBodySize, (PBYTE)pMICHDR);
+
+            if (pDevice->bEnableHostWEP) {
+                pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16 = pTransmitKey->dwTSC47_16;
+                pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0 = pTransmitKey->wTSC15_0;
+            }
+        }
+
+        // 802.1H
+        if (ntohs(psEthHeader->wType) > MAX_DATA_LEN) {
+            if ((psEthHeader->wType == TYPE_PKT_IPX) ||
+                (psEthHeader->wType == cpu_to_le16(0xF380))) {
+                MEMvCopy((PBYTE) (pbyPayloadHead), &pDevice->abySNAP_Bridgetunnel[0], 6);
+            }
+            else {
+                MEMvCopy((PBYTE) (pbyPayloadHead), &pDevice->abySNAP_RFC1042[0], 6);
+            }
+            pbyType = (PBYTE) (pbyPayloadHead + 6);
+            MEMvCopy(pbyType, &(psEthHeader->wType), sizeof(WORD));
+            cb802_1_H_len = 8;
+        }
+
+        cbReqCount = cbHeaderLength + cbMACHdLen + uPadding + cbIVlen + (cbFrameBodySize + cbMIClen);
+        //---------------------------
+        // S/W or H/W Encryption
+        //---------------------------
+        //Fill MICHDR
+        //if (pDevice->bAES) {
+        //    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Fill MICHDR...\n");
+        //    s_vFillMICHDR(pDevice, (PBYTE)pMICHDR, pbyMacHdr, (WORD)cbFrameBodySize);
+        //}
+
+        pbyBuffer = (PBYTE)pHeadTD->pTDInfo->buf;
+        //pbyBuffer = (PBYTE)pDevice->aamTxBuf[uDMAIdx][uDescIdx].pbyVAddr;
+
+        uLength = cbHeaderLength + cbMACHdLen + uPadding + cbIVlen + cb802_1_H_len;
+
+        //copy TxBufferHeader + MacHeader to desc
+        MEMvCopy(pbyBuffer, (PVOID)psTxBufHd, uLength);
+
+        // Copy the Packet into a tx Buffer
+        MEMvCopy((pbyBuffer + uLength),
+                 (pPacket + 14),
+                 cbFrameBodySize - cb802_1_H_len
+                 );
+
+        if ((bNeedEncrypt == TRUE) && (pTransmitKey != NULL) && (pTransmitKey->byCipherSuite == KEY_CTL_TKIP)){
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Length:%d, %d\n", cbFrameBodySize - cb802_1_H_len, uLength);
+            /*
+            for (ii = 0; ii < (cbFrameBodySize - cb802_1_H_len); ii++) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%02x ", *((PBYTE)((pbyBuffer + uLength) + ii)));
+            }
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n");
+            */
+
+            MIC_vAppend((pbyBuffer + uLength - cb802_1_H_len), cbFrameBodySize);
+
+            pdwMIC_L = (PDWORD)(pbyBuffer + uLength - cb802_1_H_len + cbFrameBodySize);
+            pdwMIC_R = (PDWORD)(pbyBuffer + uLength - cb802_1_H_len + cbFrameBodySize + 4);
+
+            MIC_vGetMIC(pdwMIC_L, pdwMIC_R);
+            MIC_vUnInit();
+
+
+            if (pDevice->bTxMICFail == TRUE) {
+                *pdwMIC_L = 0;
+                *pdwMIC_R = 0;
+                pDevice->bTxMICFail = FALSE;
+            }
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"uLength: %d, %d\n", uLength, cbFrameBodySize);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"cbReqCount:%d, %d, %d, %d\n", cbReqCount, cbHeaderLength, uPadding, cbIVlen);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MIC:%lx, %lx\n", *pdwMIC_L, *pdwMIC_R);
+/*
+            for (ii = 0; ii < 8; ii++) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%02x ", *(((PBYTE)(pdwMIC_L) + ii)));
+            }
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"\n");
+*/
+
+        }
+
+
+        if ((pDevice->byLocalID <= REV_ID_VT3253_A1)){
+            if (bNeedEncrypt) {
+                s_vSWencryption(pDevice, pTransmitKey, (pbyBuffer + uLength - cb802_1_H_len),
+                                (WORD)(cbFrameBodySize + cbMIClen));
+                cbReqCount += cbICVlen;
+            }
+        }
+
+
+        ptdCurr = (PSTxDesc)pHeadTD;
+
+        ptdCurr->pTDInfo->dwReqCount = cbReqCount - uPadding;
+        ptdCurr->pTDInfo->dwHeaderLength = cbHeaderLength;
+        ptdCurr->pTDInfo->skb_dma = ptdCurr->pTDInfo->buf_dma;
+        ptdCurr->buff_addr = cpu_to_le32(ptdCurr->pTDInfo->skb_dma);
+  	    //Set TSR1 & ReqCount in TxDescHead
+        ptdCurr->m_td1TD1.byTCR |= (TCR_STP | TCR_EDP | EDMSDU);
+        ptdCurr->m_td1TD1.wReqCount = cpu_to_le16((WORD)(cbReqCount));
+
+        pDevice->iTDUsed[uDMAIdx]++;
+
+
+//   DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" ptdCurr->m_dwReserved0[%d] ptdCurr->m_dwReserved1[%d].\n", ptdCurr->pTDInfo->dwReqCount, ptdCurr->pTDInfo->dwHeaderLength);
+//   DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" cbHeaderLength[%d]\n", cbHeaderLength);
+
+    }
+    *puMACfragNum = uMACfragNum;
+    //DEVICE_PRTGRP03(("s_cbFillTxBufHead END\n"));
+    return cbHeaderLength;
+}
+
+
+VOID
+vGenerateFIFOHeader (
+    IN  PSDevice         pDevice,
+    IN  BYTE             byPktTyp,
+    IN  PBYTE            pbyTxBufferAddr,
+    IN  BOOL             bNeedEncrypt,
+    IN  UINT             cbPayloadSize,
+    IN  UINT             uDMAIdx,
+    IN  PSTxDesc         pHeadTD,
+    IN  PSEthernetHeader psEthHeader,
+    IN  PBYTE            pPacket,
+    IN  PSKeyItem        pTransmitKey,
+    IN  UINT             uNodeIndex,
+    OUT PUINT            puMACfragNum,
+    OUT PUINT            pcbHeaderSize
+    )
+{
+    UINT            wTxBufSize;       // FFinfo size
+    BOOL            bNeedACK;
+    BOOL            bIsAdhoc;
+    WORD            cbMacHdLen;
+    PSTxBufHead     pTxBufHead = (PSTxBufHead) pbyTxBufferAddr;
+
+    wTxBufSize = sizeof(STxBufHead);
+
+    ZERO_MEMORY(pTxBufHead, wTxBufSize);
+    //Set FIFOCTL_NEEDACK
+
+    if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
+        (pDevice->eOPMode == OP_MODE_AP)) {
+        if (IS_MULTICAST_ADDRESS(&(psEthHeader->abyDstAddr[0])) ||
+            IS_BROADCAST_ADDRESS(&(psEthHeader->abyDstAddr[0]))) {
+            bNeedACK = FALSE;
+            pTxBufHead->wFIFOCtl = pTxBufHead->wFIFOCtl & (~FIFOCTL_NEEDACK);
+        }
+        else {
+            bNeedACK = TRUE;
+            pTxBufHead->wFIFOCtl |= FIFOCTL_NEEDACK;
+        }
+        bIsAdhoc = TRUE;
+    }
+    else {
+        // MSDUs in Infra mode always need ACK
+        bNeedACK = TRUE;
+        pTxBufHead->wFIFOCtl |= FIFOCTL_NEEDACK;
+        bIsAdhoc = FALSE;
+    }
+
+
+    pTxBufHead->wFIFOCtl |= FIFOCTL_TMOEN;
+    pTxBufHead->wTimeStamp = cpu_to_le16(DEFAULT_MSDU_LIFETIME_RES_64us);
+
+    //Set FIFOCTL_LHEAD
+    if (pDevice->bLongHeader)
+        pTxBufHead->wFIFOCtl |= FIFOCTL_LHEAD;
+
+    //Set FIFOCTL_GENINT
+
+    pTxBufHead->wFIFOCtl |= FIFOCTL_GENINT;
+
+
+    //Set FIFOCTL_ISDMA0
+    if (TYPE_TXDMA0 == uDMAIdx) {
+        pTxBufHead->wFIFOCtl |= FIFOCTL_ISDMA0;
+    }
+
+    //Set FRAGCTL_MACHDCNT
+    if (pDevice->bLongHeader) {
+        cbMacHdLen = WLAN_HDR_ADDR3_LEN + 6;
+    } else {
+        cbMacHdLen = WLAN_HDR_ADDR3_LEN;
+    }
+    pTxBufHead->wFragCtl |= cpu_to_le16((WORD)(cbMacHdLen << 10));
+
+    //Set packet type
+    if (byPktTyp == PK_TYPE_11A) {//0000 0000 0000 0000
+        ;
+    }
+    else if (byPktTyp == PK_TYPE_11B) {//0000 0001 0000 0000
+        pTxBufHead->wFIFOCtl |= FIFOCTL_11B;
+    }
+    else if (byPktTyp == PK_TYPE_11GB) {//0000 0010 0000 0000
+        pTxBufHead->wFIFOCtl |= FIFOCTL_11GB;
+    }
+    else if (byPktTyp == PK_TYPE_11GA) {//0000 0011 0000 0000
+        pTxBufHead->wFIFOCtl |= FIFOCTL_11GA;
+    }
+    //Set FIFOCTL_GrpAckPolicy
+    if (pDevice->bGrpAckPolicy == TRUE) {//0000 0100 0000 0000
+        pTxBufHead->wFIFOCtl |=	FIFOCTL_GRPACK;
+    }
+
+    //Set Auto Fallback Ctl
+    if (pDevice->wCurrentRate >= RATE_18M) {
+        if (pDevice->byAutoFBCtrl == AUTO_FB_0) {
+            pTxBufHead->wFIFOCtl |= FIFOCTL_AUTO_FB_0;
+        } else if (pDevice->byAutoFBCtrl == AUTO_FB_1) {
+            pTxBufHead->wFIFOCtl |= FIFOCTL_AUTO_FB_1;
+        }
+    }
+
+    //Set FRAGCTL_WEPTYP
+    pDevice->bAES = FALSE;
+
+    //Set FRAGCTL_WEPTYP
+    if (pDevice->byLocalID > REV_ID_VT3253_A1) {
+        if ((bNeedEncrypt) && (pTransmitKey != NULL))  { //WEP enabled
+            if (pTransmitKey->byCipherSuite == KEY_CTL_TKIP) {
+                pTxBufHead->wFragCtl |= FRAGCTL_TKIP;
+            }
+            else if (pTransmitKey->byCipherSuite == KEY_CTL_WEP) { //WEP40 or WEP104
+                if (pTransmitKey->uKeyLength != WLAN_WEP232_KEYLEN)
+                    pTxBufHead->wFragCtl |= FRAGCTL_LEGACY;
+            }
+            else if (pTransmitKey->byCipherSuite == KEY_CTL_CCMP) { //CCMP
+                pTxBufHead->wFragCtl |= FRAGCTL_AES;
+            }
+        }
+    }
+
+#ifdef	PLICE_DEBUG
+	//printk("Func:vGenerateFIFOHeader:TxDataRate is %d,TxPower is %d\n",pDevice->wCurrentRate,pDevice->byCurPwr);
+
+	//if (pDevice->wCurrentRate <= 3)
+	//{
+	//	RFbRawSetPower(pDevice,36,pDevice->wCurrentRate);
+	//}
+	//else
+
+	RFbSetPower(pDevice, pDevice->wCurrentRate, pDevice->byCurrentCh);
+#endif
+		//if (pDevice->wCurrentRate == 3)
+		//pDevice->byCurPwr = 46;
+		pTxBufHead->byTxPower = pDevice->byCurPwr;
+
+
+
+
+/*
+    if(pDevice->bEnableHostWEP)
+        pTxBufHead->wFragCtl &=  ~(FRAGCTL_TKIP | FRAGCTL_LEGACY |FRAGCTL_AES);
+*/
+    *pcbHeaderSize = s_cbFillTxBufHead(pDevice, byPktTyp, pbyTxBufferAddr, cbPayloadSize,
+                                   uDMAIdx, pHeadTD, psEthHeader, pPacket, bNeedEncrypt,
+                                   pTransmitKey, uNodeIndex, puMACfragNum);
+
+    return;
+}
+
+
+
+
+/*+
+ *
+ * Description:
+ *      Translate 802.3 to 802.11 header
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - Pointer to adpater
+ *      dwTxBufferAddr  - Transmit Buffer
+ *      pPacket         - Packet from upper layer
+ *      cbPacketSize    - Transmit Data Length
+ *  Out:
+ *      pcbHeadSize         - Header size of MAC&Baseband control and 802.11 Header
+ *      pcbAppendPayload    - size of append payload for 802.1H translation
+ *
+ * Return Value: none
+ *
+-*/
+
+VOID
+vGenerateMACHeader (
+    IN PSDevice         pDevice,
+    IN PBYTE            pbyBufferAddr,
+    IN WORD             wDuration,
+    IN PSEthernetHeader psEthHeader,
+    IN BOOL             bNeedEncrypt,
+    IN WORD             wFragType,
+    IN UINT             uDMAIdx,
+    IN UINT             uFragIdx
+    )
+{
+    PS802_11Header  pMACHeader = (PS802_11Header)pbyBufferAddr;
+
+    ZERO_MEMORY(pMACHeader, (sizeof(S802_11Header)));  //- sizeof(pMACHeader->dwIV)));
+
+    if (uDMAIdx == TYPE_ATIMDMA) {
+    	pMACHeader->wFrameCtl = TYPE_802_11_ATIM;
+    } else {
+        pMACHeader->wFrameCtl = TYPE_802_11_DATA;
+    }
+
+    if (pDevice->eOPMode == OP_MODE_AP) {
+        MEMvCopy(&(pMACHeader->abyAddr1[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
+        MEMvCopy(&(pMACHeader->abyAddr2[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+        MEMvCopy(&(pMACHeader->abyAddr3[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
+        pMACHeader->wFrameCtl |= FC_FROMDS;
+    }
+    else {
+        if (pDevice->eOPMode == OP_MODE_ADHOC) {
+            MEMvCopy(&(pMACHeader->abyAddr1[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
+            MEMvCopy(&(pMACHeader->abyAddr2[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
+            MEMvCopy(&(pMACHeader->abyAddr3[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+        }
+        else {
+            MEMvCopy(&(pMACHeader->abyAddr3[0]), &(psEthHeader->abyDstAddr[0]), U_ETHER_ADDR_LEN);
+            MEMvCopy(&(pMACHeader->abyAddr2[0]), &(psEthHeader->abySrcAddr[0]), U_ETHER_ADDR_LEN);
+            MEMvCopy(&(pMACHeader->abyAddr1[0]), &(pDevice->abyBSSID[0]), U_ETHER_ADDR_LEN);
+            pMACHeader->wFrameCtl |= FC_TODS;
+        }
+    }
+
+    if (bNeedEncrypt)
+        pMACHeader->wFrameCtl |= cpu_to_le16((WORD)WLAN_SET_FC_ISWEP(1));
+
+    pMACHeader->wDurationID = cpu_to_le16(wDuration);
+
+    if (pDevice->bLongHeader) {
+        PWLAN_80211HDR_A4 pMACA4Header  = (PWLAN_80211HDR_A4) pbyBufferAddr;
+        pMACHeader->wFrameCtl |= (FC_TODS | FC_FROMDS);
+        MEMvCopy(pMACA4Header->abyAddr4, pDevice->abyBSSID, WLAN_ADDR_LEN);
+    }
+    pMACHeader->wSeqCtl = cpu_to_le16(pDevice->wSeqCounter << 4);
+
+    //Set FragNumber in Sequence Control
+    pMACHeader->wSeqCtl |= cpu_to_le16((WORD)uFragIdx);
+
+    if ((wFragType == FRAGCTL_ENDFRAG) || (wFragType == FRAGCTL_NONFRAG)) {
+        pDevice->wSeqCounter++;
+        if (pDevice->wSeqCounter > 0x0fff)
+            pDevice->wSeqCounter = 0;
+    }
+
+    if ((wFragType == FRAGCTL_STAFRAG) || (wFragType == FRAGCTL_MIDFRAG)) { //StartFrag or MidFrag
+        pMACHeader->wFrameCtl |= FC_MOREFRAG;
+    }
+}
+
+
+
+
+
+
+CMD_STATUS csMgmt_xmit(PSDevice pDevice, PSTxMgmtPacket pPacket) {
+
+    PSTxDesc        pFrstTD;
+    BYTE            byPktTyp;
+    PBYTE           pbyTxBufferAddr;
+    PVOID           pvRTS;
+    PSCTS           pCTS;
+    PVOID           pvTxDataHd;
+    UINT            uDuration;
+    UINT            cbReqCount;
+    PS802_11Header  pMACHeader;
+    UINT            cbHeaderSize;
+    UINT            cbFrameBodySize;
+    BOOL            bNeedACK;
+    BOOL            bIsPSPOLL = FALSE;
+    PSTxBufHead     pTxBufHead;
+    UINT            cbFrameSize;
+    UINT            cbIVlen = 0;
+    UINT            cbICVlen = 0;
+    UINT            cbMIClen = 0;
+    UINT            cbFCSlen = 4;
+    UINT            uPadding = 0;
+    WORD            wTxBufSize;
+    UINT            cbMacHdLen;
+    SEthernetHeader sEthHeader;
+    PVOID           pvRrvTime;
+    PVOID           pMICHDR;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    WORD            wCurrentRate = RATE_1M;
+
+
+    if (AVAIL_TD(pDevice, TYPE_TXDMA0) <= 0) {
+        return CMD_STATUS_RESOURCES;
+    }
+
+    pFrstTD = pDevice->apCurrTD[TYPE_TXDMA0];
+    pbyTxBufferAddr = (PBYTE)pFrstTD->pTDInfo->buf;
+    cbFrameBodySize = pPacket->cbPayloadLen;
+    pTxBufHead = (PSTxBufHead) pbyTxBufferAddr;
+    wTxBufSize = sizeof(STxBufHead);
+    memset(pTxBufHead, 0, wTxBufSize);
+
+    if (pDevice->eCurrentPHYType == PHY_TYPE_11A) {
+        wCurrentRate = RATE_6M;
+        byPktTyp = PK_TYPE_11A;
+    } else {
+        wCurrentRate = RATE_1M;
+        byPktTyp = PK_TYPE_11B;
+    }
+
+    // SetPower will cause error power TX state for OFDM Date packet in TX buffer.
+    // 2004.11.11 Kyle -- Using OFDM power to tx MngPkt will decrease the connection capability.
+    //                    And cmd timer will wait data pkt TX finish before scanning so it's OK
+    //                    to set power here.
+    if (pDevice->pMgmt->eScanState != WMAC_NO_SCANNING) {
+
+		RFbSetPower(pDevice, wCurrentRate, pDevice->byCurrentCh);
+    } else {
+        RFbSetPower(pDevice, wCurrentRate, pMgmt->uCurrChannel);
+    }
+    pTxBufHead->byTxPower = pDevice->byCurPwr;
+    //+++++++++++++++++++++ Patch VT3253 A1 performance +++++++++++++++++++++++++++
+    if (pDevice->byFOETuning) {
+        if ((pPacket->p80211Header->sA3.wFrameCtl & TYPE_DATE_NULL) == TYPE_DATE_NULL) {
+            wCurrentRate = RATE_24M;
+            byPktTyp = PK_TYPE_11GA;
+        }
+    }
+
+    //Set packet type
+    if (byPktTyp == PK_TYPE_11A) {//0000 0000 0000 0000
+        pTxBufHead->wFIFOCtl = 0;
+    }
+    else if (byPktTyp == PK_TYPE_11B) {//0000 0001 0000 0000
+        pTxBufHead->wFIFOCtl |= FIFOCTL_11B;
+    }
+    else if (byPktTyp == PK_TYPE_11GB) {//0000 0010 0000 0000
+        pTxBufHead->wFIFOCtl |= FIFOCTL_11GB;
+    }
+    else if (byPktTyp == PK_TYPE_11GA) {//0000 0011 0000 0000
+        pTxBufHead->wFIFOCtl |= FIFOCTL_11GA;
+    }
+
+    pTxBufHead->wFIFOCtl |= FIFOCTL_TMOEN;
+    pTxBufHead->wTimeStamp = cpu_to_le16(DEFAULT_MGN_LIFETIME_RES_64us);
+
+
+    if (IS_MULTICAST_ADDRESS(&(pPacket->p80211Header->sA3.abyAddr1[0])) ||
+        IS_BROADCAST_ADDRESS(&(pPacket->p80211Header->sA3.abyAddr1[0]))) {
+        bNeedACK = FALSE;
+    }
+    else {
+        bNeedACK = TRUE;
+        pTxBufHead->wFIFOCtl |= FIFOCTL_NEEDACK;
+    };
+
+    if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) ||
+        (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) ) {
+
+        pTxBufHead->wFIFOCtl |= FIFOCTL_LRETRY;
+        //Set Preamble type always long
+        //pDevice->byPreambleType = PREAMBLE_LONG;
+        // probe-response don't retry
+        //if ((pPacket->p80211Header->sA4.wFrameCtl & TYPE_SUBTYPE_MASK) == TYPE_MGMT_PROBE_RSP) {
+        //     bNeedACK = FALSE;
+        //     pTxBufHead->wFIFOCtl  &= (~FIFOCTL_NEEDACK);
+        //}
+    }
+
+    pTxBufHead->wFIFOCtl |= (FIFOCTL_GENINT | FIFOCTL_ISDMA0);
+
+    if ((pPacket->p80211Header->sA4.wFrameCtl & TYPE_SUBTYPE_MASK) == TYPE_CTL_PSPOLL) {
+        bIsPSPOLL = TRUE;
+        cbMacHdLen = WLAN_HDR_ADDR2_LEN;
+    } else {
+        cbMacHdLen = WLAN_HDR_ADDR3_LEN;
+    }
+
+    //Set FRAGCTL_MACHDCNT
+    pTxBufHead->wFragCtl |= cpu_to_le16((WORD)(cbMacHdLen << 10));
+
+    // Notes:
+    // Although spec says MMPDU can be fragmented; In most case,
+    // no one will send a MMPDU under fragmentation. With RTS may occur.
+    pDevice->bAES = FALSE;  //Set FRAGCTL_WEPTYP
+
+    if (WLAN_GET_FC_ISWEP(pPacket->p80211Header->sA4.wFrameCtl) != 0) {
+        if (pDevice->eEncryptionStatus == Ndis802_11Encryption1Enabled) {
+            cbIVlen = 4;
+            cbICVlen = 4;
+    	    pTxBufHead->wFragCtl |= FRAGCTL_LEGACY;
+        }
+        else if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled) {
+            cbIVlen = 8;//IV+ExtIV
+            cbMIClen = 8;
+            cbICVlen = 4;
+    	    pTxBufHead->wFragCtl |= FRAGCTL_TKIP;
+    	    //We need to get seed here for filling TxKey entry.
+            //TKIPvMixKey(pTransmitKey->abyKey, pDevice->abyCurrentNetAddr,
+            //            pTransmitKey->wTSC15_0, pTransmitKey->dwTSC47_16, pDevice->abyPRNG);
+        }
+        else if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled) {
+            cbIVlen = 8;//RSN Header
+            cbICVlen = 8;//MIC
+            pTxBufHead->wFragCtl |= FRAGCTL_AES;
+            pDevice->bAES = TRUE;
+        }
+        //MAC Header should be padding 0 to DW alignment.
+        uPadding = 4 - (cbMacHdLen%4);
+        uPadding %= 4;
+    }
+
+    cbFrameSize = cbMacHdLen + cbFrameBodySize + cbIVlen + cbMIClen + cbICVlen + cbFCSlen;
+
+    //Set FIFOCTL_GrpAckPolicy
+    if (pDevice->bGrpAckPolicy == TRUE) {//0000 0100 0000 0000
+        pTxBufHead->wFIFOCtl |=	FIFOCTL_GRPACK;
+    }
+    //the rest of pTxBufHead->wFragCtl:FragTyp will be set later in s_vFillFragParameter()
+
+    //Set RrvTime/RTS/CTS Buffer
+    if (byPktTyp == PK_TYPE_11GB || byPktTyp == PK_TYPE_11GA) {//802.11g packet
+
+        pvRrvTime = (PSRrvTime_gCTS) (pbyTxBufferAddr + wTxBufSize);
+        pMICHDR = NULL;
+        pvRTS = NULL;
+        pCTS = (PSCTS) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS));
+        pvTxDataHd = (PSTxDataHead_g) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + sizeof(SCTS));
+        cbHeaderSize = wTxBufSize + sizeof(SRrvTime_gCTS) + sizeof(SCTS) + sizeof(STxDataHead_g);
+    }
+    else { // 802.11a/b packet
+        pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
+        pMICHDR = NULL;
+        pvRTS = NULL;
+        pCTS = NULL;
+        pvTxDataHd = (PSTxDataHead_ab) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
+        cbHeaderSize = wTxBufSize + sizeof(SRrvTime_ab) + sizeof(STxDataHead_ab);
+    }
+
+    ZERO_MEMORY((PVOID)(pbyTxBufferAddr + wTxBufSize), (cbHeaderSize - wTxBufSize));
+
+    MEMvCopy(&(sEthHeader.abyDstAddr[0]), &(pPacket->p80211Header->sA3.abyAddr1[0]), U_ETHER_ADDR_LEN);
+    MEMvCopy(&(sEthHeader.abySrcAddr[0]), &(pPacket->p80211Header->sA3.abyAddr2[0]), U_ETHER_ADDR_LEN);
+    //=========================
+    //    No Fragmentation
+    //=========================
+    pTxBufHead->wFragCtl |= (WORD)FRAGCTL_NONFRAG;
+
+
+    //Fill FIFO,RrvTime,RTS,and CTS
+    s_vGenerateTxParameter(pDevice, byPktTyp, pbyTxBufferAddr, pvRrvTime, pvRTS, pCTS,
+                           cbFrameSize, bNeedACK, TYPE_TXDMA0, &sEthHeader, wCurrentRate);
+
+    //Fill DataHead
+    uDuration = s_uFillDataHead(pDevice, byPktTyp, pvTxDataHd, cbFrameSize, TYPE_TXDMA0, bNeedACK,
+                                0, 0, 1, AUTO_FB_NONE, wCurrentRate);
+
+    pMACHeader = (PS802_11Header) (pbyTxBufferAddr + cbHeaderSize);
+
+    cbReqCount = cbHeaderSize + cbMacHdLen + uPadding + cbIVlen + cbFrameBodySize;
+
+    if (WLAN_GET_FC_ISWEP(pPacket->p80211Header->sA4.wFrameCtl) != 0) {
+        PBYTE           pbyIVHead;
+        PBYTE           pbyPayloadHead;
+        PBYTE           pbyBSSID;
+        PSKeyItem       pTransmitKey = NULL;
+
+        pbyIVHead = (PBYTE)(pbyTxBufferAddr + cbHeaderSize + cbMacHdLen + uPadding);
+        pbyPayloadHead = (PBYTE)(pbyTxBufferAddr + cbHeaderSize + cbMacHdLen + uPadding + cbIVlen);
+
+        //Fill TXKEY
+        //Kyle: Need fix: TKIP and AES did't encryt Mnt Packet.
+        //s_vFillTxKey(pDevice, (PBYTE)pTxBufHead->adwTxKey, NULL);
+
+        //Fill IV(ExtIV,RSNHDR)
+        //s_vFillPrePayload(pDevice, pbyIVHead, NULL);
+        //---------------------------
+        // S/W or H/W Encryption
+        //---------------------------
+        //Fill MICHDR
+        //if (pDevice->bAES) {
+        //    s_vFillMICHDR(pDevice, (PBYTE)pMICHDR, (PBYTE)pMACHeader, (WORD)cbFrameBodySize);
+        //}
+        do {
+            if ((pDevice->eOPMode == OP_MODE_INFRASTRUCTURE) &&
+                (pDevice->bLinkPass == TRUE)) {
+                pbyBSSID = pDevice->abyBSSID;
+                // get pairwise key
+                if (KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, PAIRWISE_KEY, &pTransmitKey) == FALSE) {
+                    // get group key
+                    if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == TRUE) {
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Get GTK.\n");
+                        break;
+                    }
+                } else {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Get PTK.\n");
+                    break;
+                }
+            }
+            // get group key
+            pbyBSSID = pDevice->abyBroadcastAddr;
+            if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == FALSE) {
+                pTransmitKey = NULL;
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"KEY is NULL. OP Mode[%d]\n", pDevice->eOPMode);
+            } else {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Get GTK.\n");
+            }
+        } while(FALSE);
+        //Fill TXKEY
+        s_vFillTxKey(pDevice, (PBYTE)(pTxBufHead->adwTxKey), pbyIVHead, pTransmitKey,
+                     (PBYTE)pMACHeader, (WORD)cbFrameBodySize, NULL);
+
+        MEMvCopy(pMACHeader, pPacket->p80211Header, cbMacHdLen);
+        MEMvCopy(pbyPayloadHead, ((PBYTE)(pPacket->p80211Header) + cbMacHdLen),
+                 cbFrameBodySize);
+    }
+    else {
+        // Copy the Packet into a tx Buffer
+        MEMvCopy(pMACHeader, pPacket->p80211Header, pPacket->cbMPDULen);
+    }
+
+    pMACHeader->wSeqCtl = cpu_to_le16(pDevice->wSeqCounter << 4);
+    pDevice->wSeqCounter++ ;
+    if (pDevice->wSeqCounter > 0x0fff)
+        pDevice->wSeqCounter = 0;
+
+    if (bIsPSPOLL) {
+        // The MAC will automatically replace the Duration-field of MAC header by Duration-field
+        // of  FIFO control header.
+        // This will cause AID-field of PS-POLL packet be incorrect (Because PS-POLL's AID field is
+        // in the same place of other packet's Duration-field).
+        // And it will cause Cisco-AP to issue Disassociation-packet
+        if (byPktTyp == PK_TYPE_11GB || byPktTyp == PK_TYPE_11GA) {
+            ((PSTxDataHead_g)pvTxDataHd)->wDuration_a = cpu_to_le16(pPacket->p80211Header->sA2.wDurationID);
+            ((PSTxDataHead_g)pvTxDataHd)->wDuration_b = cpu_to_le16(pPacket->p80211Header->sA2.wDurationID);
+        } else {
+            ((PSTxDataHead_ab)pvTxDataHd)->wDuration = cpu_to_le16(pPacket->p80211Header->sA2.wDurationID);
+        }
+    }
+
+
+    // first TD is the only TD
+    //Set TSR1 & ReqCount in TxDescHead
+    pFrstTD->m_td1TD1.byTCR = (TCR_STP | TCR_EDP | EDMSDU);
+    pFrstTD->pTDInfo->skb_dma = pFrstTD->pTDInfo->buf_dma;
+    pFrstTD->m_td1TD1.wReqCount = cpu_to_le16((WORD)(cbReqCount));
+    pFrstTD->buff_addr = cpu_to_le32(pFrstTD->pTDInfo->skb_dma);
+    pFrstTD->pTDInfo->byFlags = 0;
+
+    if (MACbIsRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PS)) {
+        // Disable PS
+        MACbPSWakeup(pDevice->PortOffset);
+    }
+    pDevice->bPWBitOn = FALSE;
+
+    wmb();
+    pFrstTD->m_td0TD0.f1Owner = OWNED_BY_NIC;
+    wmb();
+
+    pDevice->iTDUsed[TYPE_TXDMA0]++;
+
+    if (AVAIL_TD(pDevice, TYPE_TXDMA0) <= 1) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " available td0 <= 1\n");
+    }
+
+    pDevice->apCurrTD[TYPE_TXDMA0] = pFrstTD->next;
+#ifdef	PLICE_DEBUG
+		//printk("SCAN:CurrentRate is  %d,TxPower is %d\n",wCurrentRate,pTxBufHead->byTxPower);
+#endif
+
+#ifdef TxInSleep
+  pDevice->nTxDataTimeCout=0; //2008-8-21 chester <add> for send null packet
+  #endif
+
+    // Poll Transmit the adapter
+    MACvTransmit0(pDevice->PortOffset);
+
+    return CMD_STATUS_PENDING;
+
+}
+
+
+CMD_STATUS csBeacon_xmit(PSDevice pDevice, PSTxMgmtPacket pPacket) {
+
+    BYTE             byPktTyp;
+    PBYTE            pbyBuffer = (PBYTE)pDevice->tx_beacon_bufs;
+    UINT             cbFrameSize = pPacket->cbMPDULen + WLAN_FCS_LEN;
+    UINT             cbHeaderSize = 0;
+    WORD             wTxBufSize = sizeof(STxShortBufHead);
+    PSTxShortBufHead pTxBufHead = (PSTxShortBufHead) pbyBuffer;
+    PSTxDataHead_ab  pTxDataHead = (PSTxDataHead_ab) (pbyBuffer + wTxBufSize);
+    PS802_11Header   pMACHeader;
+    WORD             wCurrentRate;
+    WORD             wLen = 0x0000;
+
+
+    memset(pTxBufHead, 0, wTxBufSize);
+
+    if (pDevice->eCurrentPHYType == PHY_TYPE_11A) {
+        wCurrentRate = RATE_6M;
+        byPktTyp = PK_TYPE_11A;
+    } else {
+        wCurrentRate = RATE_2M;
+        byPktTyp = PK_TYPE_11B;
+    }
+
+    //Set Preamble type always long
+    pDevice->byPreambleType = PREAMBLE_LONG;
+
+    //Set FIFOCTL_GENINT
+
+    pTxBufHead->wFIFOCtl |= FIFOCTL_GENINT;
+
+
+    //Set packet type & Get Duration
+    if (byPktTyp == PK_TYPE_11A) {//0000 0000 0000 0000
+        pTxDataHead->wDuration = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_A, cbFrameSize, byPktTyp,
+                                                          wCurrentRate, FALSE, 0, 0, 1, AUTO_FB_NONE));
+    }
+    else if (byPktTyp == PK_TYPE_11B) {//0000 0001 0000 0000
+        pTxBufHead->wFIFOCtl |= FIFOCTL_11B;
+        pTxDataHead->wDuration = cpu_to_le16((WORD)s_uGetDataDuration(pDevice, DATADUR_B, cbFrameSize, byPktTyp,
+                                                          wCurrentRate, FALSE, 0, 0, 1, AUTO_FB_NONE));
+    }
+
+    BBvCaculateParameter(pDevice, cbFrameSize, wCurrentRate, byPktTyp,
+        (PWORD)&(wLen), (PBYTE)&(pTxDataHead->byServiceField), (PBYTE)&(pTxDataHead->bySignalField)
+    );
+    pTxDataHead->wTransmitLength = cpu_to_le16(wLen);
+    //Get TimeStampOff
+    pTxDataHead->wTimeStampOff = cpu_to_le16(wTimeStampOff[pDevice->byPreambleType%2][wCurrentRate%MAX_RATE]);
+    cbHeaderSize = wTxBufSize + sizeof(STxDataHead_ab);
+
+   //Generate Beacon Header
+    pMACHeader = (PS802_11Header)(pbyBuffer + cbHeaderSize);
+    MEMvCopy(pMACHeader, pPacket->p80211Header, pPacket->cbMPDULen);
+
+    pMACHeader->wDurationID = 0;
+    pMACHeader->wSeqCtl = cpu_to_le16(pDevice->wSeqCounter << 4);
+    pDevice->wSeqCounter++ ;
+    if (pDevice->wSeqCounter > 0x0fff)
+        pDevice->wSeqCounter = 0;
+
+    // Set Beacon buffer length
+    pDevice->wBCNBufLen = pPacket->cbMPDULen + cbHeaderSize;
+
+    MACvSetCurrBCNTxDescAddr(pDevice->PortOffset, (pDevice->tx_beacon_dma));
+
+    MACvSetCurrBCNLength(pDevice->PortOffset, pDevice->wBCNBufLen);
+    // Set auto Transmit on
+    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_TCR, TCR_AUTOBCNTX);
+    // Poll Transmit the adapter
+    MACvTransmitBCN(pDevice->PortOffset);
+
+    return CMD_STATUS_PENDING;
+}
+
+
+
+UINT
+cbGetFragCount (
+    IN  PSDevice         pDevice,
+    IN  PSKeyItem        pTransmitKey,
+    IN  UINT             cbFrameBodySize,
+    IN  PSEthernetHeader psEthHeader
+    )
+{
+    UINT           cbMACHdLen;
+    UINT           cbFrameSize;
+    UINT           cbFragmentSize; //Hdr+(IV)+payoad+(MIC)+(ICV)+FCS
+    UINT           cbFragPayloadSize;
+    UINT           cbLastFragPayloadSize;
+    UINT           cbIVlen = 0;
+    UINT           cbICVlen = 0;
+    UINT           cbMIClen = 0;
+    UINT           cbFCSlen = 4;
+    UINT           uMACfragNum = 1;
+    BOOL           bNeedACK;
+
+
+
+    if ((pDevice->eOPMode == OP_MODE_ADHOC) ||
+        (pDevice->eOPMode == OP_MODE_AP)) {
+        if (IS_MULTICAST_ADDRESS(&(psEthHeader->abyDstAddr[0])) ||
+            IS_BROADCAST_ADDRESS(&(psEthHeader->abyDstAddr[0]))) {
+            bNeedACK = FALSE;
+        }
+        else {
+            bNeedACK = TRUE;
+        }
+    }
+    else {
+        // MSDUs in Infra mode always need ACK
+        bNeedACK = TRUE;
+    }
+
+    if (pDevice->bLongHeader)
+        cbMACHdLen = WLAN_HDR_ADDR3_LEN + 6;
+    else
+        cbMACHdLen = WLAN_HDR_ADDR3_LEN;
+
+
+    if (pDevice->bEncryptionEnable == TRUE) {
+
+        if (pTransmitKey == NULL) {
+            if ((pDevice->eEncryptionStatus == Ndis802_11Encryption1Enabled) ||
+                (pDevice->pMgmt->eAuthenMode < WMAC_AUTH_WPA)) {
+                cbIVlen = 4;
+                cbICVlen = 4;
+            } else if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled) {
+                cbIVlen = 8;//IV+ExtIV
+                cbMIClen = 8;
+                cbICVlen = 4;
+            } else if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled) {
+                cbIVlen = 8;//RSN Header
+                cbICVlen = 8;//MIC
+            }
+        } else if (pTransmitKey->byCipherSuite == KEY_CTL_WEP) {
+            cbIVlen = 4;
+            cbICVlen = 4;
+        } else if (pTransmitKey->byCipherSuite == KEY_CTL_TKIP) {
+            cbIVlen = 8;//IV+ExtIV
+            cbMIClen = 8;
+            cbICVlen = 4;
+        } else if (pTransmitKey->byCipherSuite == KEY_CTL_CCMP) {
+            cbIVlen = 8;//RSN Header
+            cbICVlen = 8;//MIC
+        }
+    }
+
+    cbFrameSize = cbMACHdLen + cbIVlen + (cbFrameBodySize + cbMIClen) + cbICVlen + cbFCSlen;
+
+    if ((cbFrameSize > pDevice->wFragmentationThreshold) && (bNeedACK == TRUE)) {
+        // Fragmentation
+        cbFragmentSize = pDevice->wFragmentationThreshold;
+        cbFragPayloadSize = cbFragmentSize - cbMACHdLen - cbIVlen - cbICVlen - cbFCSlen;
+        uMACfragNum = (WORD) ((cbFrameBodySize + cbMIClen) / cbFragPayloadSize);
+        cbLastFragPayloadSize = (cbFrameBodySize + cbMIClen) % cbFragPayloadSize;
+        if (cbLastFragPayloadSize == 0) {
+            cbLastFragPayloadSize = cbFragPayloadSize;
+        } else {
+            uMACfragNum++;
+        }
+    }
+    return uMACfragNum;
+}
+
+
+VOID
+vDMA0_tx_80211(PSDevice  pDevice, struct sk_buff *skb, PBYTE pbMPDU, UINT cbMPDULen) {
+
+    PSTxDesc        pFrstTD;
+    BYTE            byPktTyp;
+    PBYTE           pbyTxBufferAddr;
+    PVOID           pvRTS;
+    PVOID           pvCTS;
+    PVOID           pvTxDataHd;
+    UINT            uDuration;
+    UINT            cbReqCount;
+    PS802_11Header  pMACHeader;
+    UINT            cbHeaderSize;
+    UINT            cbFrameBodySize;
+    BOOL            bNeedACK;
+    BOOL            bIsPSPOLL = FALSE;
+    PSTxBufHead     pTxBufHead;
+    UINT            cbFrameSize;
+    UINT            cbIVlen = 0;
+    UINT            cbICVlen = 0;
+    UINT            cbMIClen = 0;
+    UINT            cbFCSlen = 4;
+    UINT            uPadding = 0;
+    UINT            cbMICHDR = 0;
+    UINT            uLength = 0;
+    DWORD           dwMICKey0, dwMICKey1;
+    DWORD           dwMIC_Priority;
+    PDWORD          pdwMIC_L;
+    PDWORD          pdwMIC_R;
+    WORD            wTxBufSize;
+    UINT            cbMacHdLen;
+    SEthernetHeader sEthHeader;
+    PVOID           pvRrvTime;
+    PVOID           pMICHDR;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    WORD            wCurrentRate = RATE_1M;
+    PUWLAN_80211HDR  p80211Header;
+    UINT             uNodeIndex = 0;
+    BOOL            bNodeExist = FALSE;
+    SKeyItem        STempKey;
+    PSKeyItem       pTransmitKey = NULL;
+    PBYTE           pbyIVHead;
+    PBYTE           pbyPayloadHead;
+    PBYTE           pbyMacHdr;
+
+    UINT            cbExtSuppRate = 0;
+//    PWLAN_IE        pItem;
+
+
+    pvRrvTime = pMICHDR = pvRTS = pvCTS = pvTxDataHd = NULL;
+
+    if(cbMPDULen <= WLAN_HDR_ADDR3_LEN) {
+       cbFrameBodySize = 0;
+    }
+    else {
+       cbFrameBodySize = cbMPDULen - WLAN_HDR_ADDR3_LEN;
+    }
+    p80211Header = (PUWLAN_80211HDR)pbMPDU;
+
+
+    pFrstTD = pDevice->apCurrTD[TYPE_TXDMA0];
+    pbyTxBufferAddr = (PBYTE)pFrstTD->pTDInfo->buf;
+    pTxBufHead = (PSTxBufHead) pbyTxBufferAddr;
+    wTxBufSize = sizeof(STxBufHead);
+    memset(pTxBufHead, 0, wTxBufSize);
+
+    if (pDevice->eCurrentPHYType == PHY_TYPE_11A) {
+        wCurrentRate = RATE_6M;
+        byPktTyp = PK_TYPE_11A;
+    } else {
+        wCurrentRate = RATE_1M;
+        byPktTyp = PK_TYPE_11B;
+    }
+
+    // SetPower will cause error power TX state for OFDM Date packet in TX buffer.
+    // 2004.11.11 Kyle -- Using OFDM power to tx MngPkt will decrease the connection capability.
+    //                    And cmd timer will wait data pkt TX finish before scanning so it's OK
+    //                    to set power here.
+    if (pDevice->pMgmt->eScanState != WMAC_NO_SCANNING) {
+        RFbSetPower(pDevice, wCurrentRate, pDevice->byCurrentCh);
+    } else {
+        RFbSetPower(pDevice, wCurrentRate, pMgmt->uCurrChannel);
+    }
+    pTxBufHead->byTxPower = pDevice->byCurPwr;
+
+    //+++++++++++++++++++++ Patch VT3253 A1 performance +++++++++++++++++++++++++++
+    if (pDevice->byFOETuning) {
+        if ((p80211Header->sA3.wFrameCtl & TYPE_DATE_NULL) == TYPE_DATE_NULL) {
+            wCurrentRate = RATE_24M;
+            byPktTyp = PK_TYPE_11GA;
+        }
+    }
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"vDMA0_tx_80211: p80211Header->sA3.wFrameCtl = %x \n", p80211Header->sA3.wFrameCtl);
+
+    //Set packet type
+    if (byPktTyp == PK_TYPE_11A) {//0000 0000 0000 0000
+        pTxBufHead->wFIFOCtl = 0;
+    }
+    else if (byPktTyp == PK_TYPE_11B) {//0000 0001 0000 0000
+        pTxBufHead->wFIFOCtl |= FIFOCTL_11B;
+    }
+    else if (byPktTyp == PK_TYPE_11GB) {//0000 0010 0000 0000
+        pTxBufHead->wFIFOCtl |= FIFOCTL_11GB;
+    }
+    else if (byPktTyp == PK_TYPE_11GA) {//0000 0011 0000 0000
+        pTxBufHead->wFIFOCtl |= FIFOCTL_11GA;
+    }
+
+    pTxBufHead->wFIFOCtl |= FIFOCTL_TMOEN;
+    pTxBufHead->wTimeStamp = cpu_to_le16(DEFAULT_MGN_LIFETIME_RES_64us);
+
+
+    if (IS_MULTICAST_ADDRESS(&(p80211Header->sA3.abyAddr1[0])) ||
+        IS_BROADCAST_ADDRESS(&(p80211Header->sA3.abyAddr1[0]))) {
+        bNeedACK = FALSE;
+        if (pDevice->bEnableHostWEP) {
+            uNodeIndex = 0;
+            bNodeExist = TRUE;
+        };
+    }
+    else {
+        if (pDevice->bEnableHostWEP) {
+            if (BSSDBbIsSTAInNodeDB(pDevice->pMgmt, (PBYTE)(p80211Header->sA3.abyAddr1), &uNodeIndex))
+                bNodeExist = TRUE;
+        };
+        bNeedACK = TRUE;
+        pTxBufHead->wFIFOCtl |= FIFOCTL_NEEDACK;
+    };
+
+    if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) ||
+        (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) ) {
+
+        pTxBufHead->wFIFOCtl |= FIFOCTL_LRETRY;
+        //Set Preamble type always long
+        //pDevice->byPreambleType = PREAMBLE_LONG;
+
+        // probe-response don't retry
+        //if ((p80211Header->sA4.wFrameCtl & TYPE_SUBTYPE_MASK) == TYPE_MGMT_PROBE_RSP) {
+        //     bNeedACK = FALSE;
+        //     pTxBufHead->wFIFOCtl  &= (~FIFOCTL_NEEDACK);
+        //}
+    }
+
+    pTxBufHead->wFIFOCtl |= (FIFOCTL_GENINT | FIFOCTL_ISDMA0);
+
+    if ((p80211Header->sA4.wFrameCtl & TYPE_SUBTYPE_MASK) == TYPE_CTL_PSPOLL) {
+        bIsPSPOLL = TRUE;
+        cbMacHdLen = WLAN_HDR_ADDR2_LEN;
+    } else {
+        cbMacHdLen = WLAN_HDR_ADDR3_LEN;
+    }
+
+    // hostapd deamon ext support rate patch
+    if (WLAN_GET_FC_FSTYPE(p80211Header->sA4.wFrameCtl) == WLAN_FSTYPE_ASSOCRESP) {
+
+        if (((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates)->len != 0) {
+            cbExtSuppRate += ((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates)->len + WLAN_IEHDR_LEN;
+         }
+
+        if (((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates)->len != 0) {
+            cbExtSuppRate += ((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates)->len + WLAN_IEHDR_LEN;
+         }
+
+         if (cbExtSuppRate >0) {
+            cbFrameBodySize = WLAN_ASSOCRESP_OFF_SUPP_RATES;
+         }
+    }
+
+
+    //Set FRAGCTL_MACHDCNT
+    pTxBufHead->wFragCtl |= cpu_to_le16((WORD)cbMacHdLen << 10);
+
+    // Notes:
+    // Although spec says MMPDU can be fragmented; In most case,
+    // no one will send a MMPDU under fragmentation. With RTS may occur.
+    pDevice->bAES = FALSE;  //Set FRAGCTL_WEPTYP
+
+
+    if (WLAN_GET_FC_ISWEP(p80211Header->sA4.wFrameCtl) != 0) {
+        if (pDevice->eEncryptionStatus == Ndis802_11Encryption1Enabled) {
+            cbIVlen = 4;
+            cbICVlen = 4;
+    	    pTxBufHead->wFragCtl |= FRAGCTL_LEGACY;
+        }
+        else if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled) {
+            cbIVlen = 8;//IV+ExtIV
+            cbMIClen = 8;
+            cbICVlen = 4;
+    	    pTxBufHead->wFragCtl |= FRAGCTL_TKIP;
+    	    //We need to get seed here for filling TxKey entry.
+            //TKIPvMixKey(pTransmitKey->abyKey, pDevice->abyCurrentNetAddr,
+            //            pTransmitKey->wTSC15_0, pTransmitKey->dwTSC47_16, pDevice->abyPRNG);
+        }
+        else if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled) {
+            cbIVlen = 8;//RSN Header
+            cbICVlen = 8;//MIC
+            cbMICHDR = sizeof(SMICHDRHead);
+            pTxBufHead->wFragCtl |= FRAGCTL_AES;
+            pDevice->bAES = TRUE;
+        }
+        //MAC Header should be padding 0 to DW alignment.
+        uPadding = 4 - (cbMacHdLen%4);
+        uPadding %= 4;
+    }
+
+    cbFrameSize = cbMacHdLen + cbFrameBodySize + cbIVlen + cbMIClen + cbICVlen + cbFCSlen + cbExtSuppRate;
+
+    //Set FIFOCTL_GrpAckPolicy
+    if (pDevice->bGrpAckPolicy == TRUE) {//0000 0100 0000 0000
+        pTxBufHead->wFIFOCtl |=	FIFOCTL_GRPACK;
+    }
+    //the rest of pTxBufHead->wFragCtl:FragTyp will be set later in s_vFillFragParameter()
+
+
+    if (byPktTyp == PK_TYPE_11GB || byPktTyp == PK_TYPE_11GA) {//802.11g packet
+
+        pvRrvTime = (PSRrvTime_gCTS) (pbyTxBufferAddr + wTxBufSize);
+        pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS));
+        pvRTS = NULL;
+        pvCTS = (PSCTS) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR);
+        pvTxDataHd = (PSTxDataHead_g) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS));
+        cbHeaderSize = wTxBufSize + sizeof(SRrvTime_gCTS) + cbMICHDR + sizeof(SCTS) + sizeof(STxDataHead_g);
+
+    }
+    else {//802.11a/b packet
+
+        pvRrvTime = (PSRrvTime_ab) (pbyTxBufferAddr + wTxBufSize);
+        pMICHDR = (PSMICHDRHead) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab));
+        pvRTS = NULL;
+        pvCTS = NULL;
+        pvTxDataHd = (PSTxDataHead_ab) (pbyTxBufferAddr + wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR);
+        cbHeaderSize = wTxBufSize + sizeof(SRrvTime_ab) + cbMICHDR + sizeof(STxDataHead_ab);
+
+    }
+
+    ZERO_MEMORY((PVOID)(pbyTxBufferAddr + wTxBufSize), (cbHeaderSize - wTxBufSize));
+    MEMvCopy(&(sEthHeader.abyDstAddr[0]), &(p80211Header->sA3.abyAddr1[0]), U_ETHER_ADDR_LEN);
+    MEMvCopy(&(sEthHeader.abySrcAddr[0]), &(p80211Header->sA3.abyAddr2[0]), U_ETHER_ADDR_LEN);
+    //=========================
+    //    No Fragmentation
+    //=========================
+    pTxBufHead->wFragCtl |= (WORD)FRAGCTL_NONFRAG;
+
+
+    //Fill FIFO,RrvTime,RTS,and CTS
+    s_vGenerateTxParameter(pDevice, byPktTyp, pbyTxBufferAddr, pvRrvTime, pvRTS, pvCTS,
+                           cbFrameSize, bNeedACK, TYPE_TXDMA0, &sEthHeader, wCurrentRate);
+
+    //Fill DataHead
+    uDuration = s_uFillDataHead(pDevice, byPktTyp, pvTxDataHd, cbFrameSize, TYPE_TXDMA0, bNeedACK,
+                                0, 0, 1, AUTO_FB_NONE, wCurrentRate);
+
+    pMACHeader = (PS802_11Header) (pbyTxBufferAddr + cbHeaderSize);
+
+    cbReqCount = cbHeaderSize + cbMacHdLen + uPadding + cbIVlen + (cbFrameBodySize + cbMIClen) + cbExtSuppRate;
+
+    pbyMacHdr = (PBYTE)(pbyTxBufferAddr + cbHeaderSize);
+    pbyPayloadHead = (PBYTE)(pbyMacHdr + cbMacHdLen + uPadding + cbIVlen);
+    pbyIVHead = (PBYTE)(pbyMacHdr + cbMacHdLen + uPadding);
+
+    // Copy the Packet into a tx Buffer
+    memcpy(pbyMacHdr, pbMPDU, cbMacHdLen);
+
+    // version set to 0, patch for hostapd deamon
+    pMACHeader->wFrameCtl &= cpu_to_le16(0xfffc);
+    memcpy(pbyPayloadHead, (pbMPDU + cbMacHdLen), cbFrameBodySize);
+
+    // replace support rate, patch for hostapd deamon( only support 11M)
+    if (WLAN_GET_FC_FSTYPE(p80211Header->sA4.wFrameCtl) == WLAN_FSTYPE_ASSOCRESP) {
+        if (cbExtSuppRate != 0) {
+            if (((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates)->len != 0)
+                memcpy((pbyPayloadHead + cbFrameBodySize),
+                        pMgmt->abyCurrSuppRates,
+                        ((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates)->len + WLAN_IEHDR_LEN
+                       );
+             if (((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates)->len != 0)
+                memcpy((pbyPayloadHead + cbFrameBodySize) + ((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates)->len + WLAN_IEHDR_LEN,
+                        pMgmt->abyCurrExtSuppRates,
+                        ((PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates)->len + WLAN_IEHDR_LEN
+                       );
+         }
+    }
+
+    // Set wep
+    if (WLAN_GET_FC_ISWEP(p80211Header->sA4.wFrameCtl) != 0) {
+
+        if (pDevice->bEnableHostWEP) {
+            pTransmitKey = &STempKey;
+            pTransmitKey->byCipherSuite = pMgmt->sNodeDBTable[uNodeIndex].byCipherSuite;
+            pTransmitKey->dwKeyIndex = pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex;
+            pTransmitKey->uKeyLength = pMgmt->sNodeDBTable[uNodeIndex].uWepKeyLength;
+            pTransmitKey->dwTSC47_16 = pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16;
+            pTransmitKey->wTSC15_0 = pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0;
+            memcpy(pTransmitKey->abyKey,
+                &pMgmt->sNodeDBTable[uNodeIndex].abyWepKey[0],
+                pTransmitKey->uKeyLength
+                );
+        }
+
+        if ((pTransmitKey != NULL) && (pTransmitKey->byCipherSuite == KEY_CTL_TKIP)) {
+
+            dwMICKey0 = *(PDWORD)(&pTransmitKey->abyKey[16]);
+            dwMICKey1 = *(PDWORD)(&pTransmitKey->abyKey[20]);
+
+            // DO Software Michael
+            MIC_vInit(dwMICKey0, dwMICKey1);
+            MIC_vAppend((PBYTE)&(sEthHeader.abyDstAddr[0]), 12);
+            dwMIC_Priority = 0;
+            MIC_vAppend((PBYTE)&dwMIC_Priority, 4);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"DMA0_tx_8021:MIC KEY: %lX, %lX\n", dwMICKey0, dwMICKey1);
+
+            uLength = cbHeaderSize + cbMacHdLen + uPadding + cbIVlen;
+
+            MIC_vAppend((pbyTxBufferAddr + uLength), cbFrameBodySize);
+
+            pdwMIC_L = (PDWORD)(pbyTxBufferAddr + uLength + cbFrameBodySize);
+            pdwMIC_R = (PDWORD)(pbyTxBufferAddr + uLength + cbFrameBodySize + 4);
+
+            MIC_vGetMIC(pdwMIC_L, pdwMIC_R);
+            MIC_vUnInit();
+
+            if (pDevice->bTxMICFail == TRUE) {
+                *pdwMIC_L = 0;
+                *pdwMIC_R = 0;
+                pDevice->bTxMICFail = FALSE;
+            }
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"uLength: %d, %d\n", uLength, cbFrameBodySize);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"cbReqCount:%d, %d, %d, %d\n", cbReqCount, cbHeaderSize, uPadding, cbIVlen);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MIC:%lx, %lx\n", *pdwMIC_L, *pdwMIC_R);
+
+        }
+
+
+        s_vFillTxKey(pDevice, (PBYTE)(pTxBufHead->adwTxKey), pbyIVHead, pTransmitKey,
+                     pbyMacHdr, (WORD)cbFrameBodySize, (PBYTE)pMICHDR);
+
+        if (pDevice->bEnableHostWEP) {
+            pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16 = pTransmitKey->dwTSC47_16;
+            pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0 = pTransmitKey->wTSC15_0;
+        }
+
+        if ((pDevice->byLocalID <= REV_ID_VT3253_A1)) {
+            s_vSWencryption(pDevice, pTransmitKey, pbyPayloadHead, (WORD)(cbFrameBodySize + cbMIClen));
+        }
+    }
+
+    pMACHeader->wSeqCtl = cpu_to_le16(pDevice->wSeqCounter << 4);
+    pDevice->wSeqCounter++ ;
+    if (pDevice->wSeqCounter > 0x0fff)
+        pDevice->wSeqCounter = 0;
+
+
+    if (bIsPSPOLL) {
+        // The MAC will automatically replace the Duration-field of MAC header by Duration-field
+        // of  FIFO control header.
+        // This will cause AID-field of PS-POLL packet be incorrect (Because PS-POLL's AID field is
+        // in the same place of other packet's Duration-field).
+        // And it will cause Cisco-AP to issue Disassociation-packet
+        if (byPktTyp == PK_TYPE_11GB || byPktTyp == PK_TYPE_11GA) {
+            ((PSTxDataHead_g)pvTxDataHd)->wDuration_a = cpu_to_le16(p80211Header->sA2.wDurationID);
+            ((PSTxDataHead_g)pvTxDataHd)->wDuration_b = cpu_to_le16(p80211Header->sA2.wDurationID);
+        } else {
+            ((PSTxDataHead_ab)pvTxDataHd)->wDuration = cpu_to_le16(p80211Header->sA2.wDurationID);
+        }
+    }
+
+
+    // first TD is the only TD
+    //Set TSR1 & ReqCount in TxDescHead
+    pFrstTD->pTDInfo->skb = skb;
+    pFrstTD->m_td1TD1.byTCR = (TCR_STP | TCR_EDP | EDMSDU);
+    pFrstTD->pTDInfo->skb_dma = pFrstTD->pTDInfo->buf_dma;
+    pFrstTD->m_td1TD1.wReqCount = cpu_to_le16(cbReqCount);
+    pFrstTD->buff_addr = cpu_to_le32(pFrstTD->pTDInfo->skb_dma);
+    pFrstTD->pTDInfo->byFlags = 0;
+    pFrstTD->pTDInfo->byFlags |= TD_FLAGS_PRIV_SKB;
+
+    if (MACbIsRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PS)) {
+        // Disable PS
+        MACbPSWakeup(pDevice->PortOffset);
+    }
+    pDevice->bPWBitOn = FALSE;
+
+    wmb();
+    pFrstTD->m_td0TD0.f1Owner = OWNED_BY_NIC;
+    wmb();
+
+    pDevice->iTDUsed[TYPE_TXDMA0]++;
+
+    if (AVAIL_TD(pDevice, TYPE_TXDMA0) <= 1) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " available td0 <= 1\n");
+    }
+
+    pDevice->apCurrTD[TYPE_TXDMA0] = pFrstTD->next;
+
+    // Poll Transmit the adapter
+    MACvTransmit0(pDevice->PortOffset);
+
+    return;
+}
+
+
diff --git a/drivers/staging/vt6655/rxtx.h b/drivers/staging/vt6655/rxtx.h
new file mode 100644
index 0000000..3e85264
--- /dev/null
+++ b/drivers/staging/vt6655/rxtx.h
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: whdr.h
+ *
+ * Purpose:
+ *
+ * Author: Jerry Chen
+ *
+ * Date: Jun. 27, 2002
+ *
+ */
+
+
+#ifndef __RXTX_H__
+#define __RXTX_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__WCMD_H__)
+#include "wcmd.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+/*
+VOID vGenerateMACHeader(
+    IN PSDevice pDevice,
+    IN DWORD dwTxBufferAddr,
+    IN PBYTE pbySkbData,
+    IN UINT cbPacketSize,
+    IN BOOL bDMA0Used,
+    OUT PUINT pcbHeadSize,
+    OUT PUINT pcbAppendPayload
+     );
+
+VOID vProcessRxMACHeader (
+    IN  PSDevice pDevice,
+    IN  DWORD dwRxBufferAddr,
+    IN  UINT cbPacketSize,
+    IN  BOOL bIsWEP,
+    OUT PUINT pcbHeadSize
+    );
+*/
+
+
+VOID
+vGenerateMACHeader (
+    IN PSDevice         pDevice,
+    IN PBYTE            pbyBufferAddr,
+    IN WORD             wDuration,
+    IN PSEthernetHeader psEthHeader,
+    IN BOOL             bNeedEncrypt,
+    IN WORD             wFragType,
+    IN UINT             uDMAIdx,
+    IN UINT             uFragIdx
+    );
+
+
+UINT
+cbGetFragCount(
+    IN  PSDevice         pDevice,
+    IN  PSKeyItem        pTransmitKey,
+    IN  UINT             cbFrameBodySize,
+    IN  PSEthernetHeader psEthHeader
+    );
+
+
+VOID
+vGenerateFIFOHeader (
+    IN  PSDevice         pDevice,
+    IN  BYTE             byPktTyp,
+    IN  PBYTE            pbyTxBufferAddr,
+    IN  BOOL             bNeedEncrypt,
+    IN  UINT             cbPayloadSize,
+    IN  UINT             uDMAIdx,
+    IN  PSTxDesc         pHeadTD,
+    IN  PSEthernetHeader psEthHeader,
+    IN  PBYTE            pPacket,
+    IN  PSKeyItem        pTransmitKey,
+    IN  UINT             uNodeIndex,
+    OUT PUINT            puMACfragNum,
+    OUT PUINT            pcbHeaderSize
+    );
+
+
+VOID vDMA0_tx_80211(PSDevice  pDevice, struct sk_buff *skb, PBYTE pbMPDU, UINT cbMPDULen);
+CMD_STATUS csMgmt_xmit(PSDevice pDevice, PSTxMgmtPacket pPacket);
+CMD_STATUS csBeacon_xmit(PSDevice pDevice, PSTxMgmtPacket pPacket);
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+
+#endif // __RXTX_H__
+
+
+
diff --git a/drivers/staging/vt6655/srom.c b/drivers/staging/vt6655/srom.c
new file mode 100644
index 0000000..655d6859
--- /dev/null
+++ b/drivers/staging/vt6655/srom.c
@@ -0,0 +1,437 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: srom.c
+ *
+ * Purpose:Implement functions to access eeprom
+ *
+ * Author: Jerry Chen
+ *
+ * Date: Jan 29, 2003
+ *
+ * Functions:
+ *      SROMbyReadEmbedded - Embedded read eeprom via MAC
+ *      SROMbWriteEmbedded - Embedded write eeprom via MAC
+ *      SROMvRegBitsOn - Set Bits On in eeprom
+ *      SROMvRegBitsOff - Clear Bits Off in eeprom
+ *      SROMbIsRegBitsOn - Test if Bits On in eeprom
+ *      SROMbIsRegBitsOff - Test if Bits Off in eeprom
+ *      SROMvReadAllContents - Read all contents in eeprom
+ *      SROMvWriteAllContents - Write all contents in eeprom
+ *      SROMvReadEtherAddress - Read Ethernet Address in eeprom
+ *      SROMvWriteEtherAddress - Write Ethernet Address in eeprom
+ *      SROMvReadSubSysVenId - Read Sub_VID and Sub_SysId in eeprom
+ *      SROMbAutoLoad - Auto Load eeprom to MAC register
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__UPC_H__)
+#include "upc.h"
+#endif
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__SROM_H__)
+#include "srom.h"
+#endif
+
+
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+
+/*
+ * Description: Read a byte from EEPROM, by MAC I2C
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *      byContntOffset  - address of EEPROM
+ *  Out:
+ *      none
+ *
+ * Return Value: data read
+ *
+ */
+BYTE SROMbyReadEmbedded(DWORD_PTR dwIoBase, BYTE byContntOffset)
+{
+    WORD    wDelay, wNoACK;
+    BYTE    byWait;
+    BYTE    byData;
+    BYTE    byOrg;
+
+    byData = 0xFF;
+    VNSvInPortB(dwIoBase + MAC_REG_I2MCFG, &byOrg);
+    // turn off hardware retry for getting NACK
+    VNSvOutPortB(dwIoBase + MAC_REG_I2MCFG, (byOrg & (~I2MCFG_NORETRY)));
+    for (wNoACK = 0; wNoACK < W_MAX_I2CRETRY; wNoACK++) {
+        VNSvOutPortB(dwIoBase + MAC_REG_I2MTGID, EEP_I2C_DEV_ID);
+        VNSvOutPortB(dwIoBase + MAC_REG_I2MTGAD, byContntOffset);
+
+        // issue read command
+        VNSvOutPortB(dwIoBase + MAC_REG_I2MCSR, I2MCSR_EEMR);
+        // wait DONE be set
+        for (wDelay = 0; wDelay < W_MAX_TIMEOUT; wDelay++) {
+            VNSvInPortB(dwIoBase + MAC_REG_I2MCSR, &byWait);
+            if (BITbIsAnyBitsOn(byWait, (I2MCSR_DONE | I2MCSR_NACK)))
+                break;
+            PCAvDelayByIO(CB_DELAY_LOOP_WAIT);
+        }
+        if ((wDelay < W_MAX_TIMEOUT) &&
+             (BITbIsBitOff(byWait, I2MCSR_NACK))) {
+            break;
+        }
+    }
+    VNSvInPortB(dwIoBase + MAC_REG_I2MDIPT, &byData);
+    VNSvOutPortB(dwIoBase + MAC_REG_I2MCFG, byOrg);
+    return byData;
+}
+
+
+/*
+ * Description: Write a byte to EEPROM, by MAC I2C
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *      byContntOffset  - address of EEPROM
+ *      wData           - data to write
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if succeeded; FALSE if failed.
+ *
+ */
+BOOL SROMbWriteEmbedded (DWORD_PTR dwIoBase, BYTE byContntOffset, BYTE byData)
+{
+    WORD    wDelay, wNoACK;
+    BYTE    byWait;
+
+    BYTE    byOrg;
+
+    VNSvInPortB(dwIoBase + MAC_REG_I2MCFG, &byOrg);
+    // turn off hardware retry for getting NACK
+    VNSvOutPortB(dwIoBase + MAC_REG_I2MCFG, (byOrg & (~I2MCFG_NORETRY)));
+    for (wNoACK = 0; wNoACK < W_MAX_I2CRETRY; wNoACK++) {
+        VNSvOutPortB(dwIoBase + MAC_REG_I2MTGID, EEP_I2C_DEV_ID);
+        VNSvOutPortB(dwIoBase + MAC_REG_I2MTGAD, byContntOffset);
+        VNSvOutPortB(dwIoBase + MAC_REG_I2MDOPT, byData);
+
+        // issue write command
+        VNSvOutPortB(dwIoBase + MAC_REG_I2MCSR, I2MCSR_EEMW);
+        // wait DONE be set
+        for (wDelay = 0; wDelay < W_MAX_TIMEOUT; wDelay++) {
+            VNSvInPortB(dwIoBase + MAC_REG_I2MCSR, &byWait);
+            if (BITbIsAnyBitsOn(byWait, (I2MCSR_DONE | I2MCSR_NACK)))
+                break;
+            PCAvDelayByIO(CB_DELAY_LOOP_WAIT);
+        }
+
+        if ((wDelay < W_MAX_TIMEOUT) &&
+             (BITbIsBitOff(byWait, I2MCSR_NACK))) {
+            break;
+        }
+    }
+    if (wNoACK == W_MAX_I2CRETRY) {
+        VNSvOutPortB(dwIoBase + MAC_REG_I2MCFG, byOrg);
+        return FALSE;
+    }
+    VNSvOutPortB(dwIoBase + MAC_REG_I2MCFG, byOrg);
+    return TRUE;
+}
+
+
+/*
+ * Description: Turn bits on in eeprom
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *      byContntOffset  - address of EEPROM
+ *      byBits          - bits to turn on
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void SROMvRegBitsOn (DWORD_PTR dwIoBase, BYTE byContntOffset, BYTE byBits)
+{
+    BYTE    byOrgData;
+
+    byOrgData = SROMbyReadEmbedded(dwIoBase, byContntOffset);
+    SROMbWriteEmbedded(dwIoBase, byContntOffset,(BYTE)(byOrgData | byBits));
+}
+
+
+/*
+ * Description: Turn bits off in eeprom
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *      byContntOffset  - address of EEPROM
+ *      byBits          - bits to turn off
+ *  Out:
+ *      none
+ *
+ */
+void SROMvRegBitsOff (DWORD_PTR dwIoBase, BYTE byContntOffset, BYTE byBits)
+{
+    BYTE    byOrgData;
+
+    byOrgData = SROMbyReadEmbedded(dwIoBase, byContntOffset);
+    SROMbWriteEmbedded(dwIoBase, byContntOffset,(BYTE)(byOrgData & (~byBits)));
+}
+
+
+/*
+ * Description: Test if bits on in eeprom
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *      byContntOffset  - address of EEPROM
+ *      byTestBits      - bits to test
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if all test bits on; otherwise FALSE
+ *
+ */
+BOOL SROMbIsRegBitsOn (DWORD_PTR dwIoBase, BYTE byContntOffset, BYTE byTestBits)
+{
+    BYTE    byOrgData;
+
+    byOrgData = SROMbyReadEmbedded(dwIoBase, byContntOffset);
+    return BITbIsAllBitsOn(byOrgData, byTestBits);
+}
+
+
+/*
+ * Description: Test if bits off in eeprom
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *      byContntOffset  - address of EEPROM
+ *      byTestBits      - bits to test
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if all test bits off; otherwise FALSE
+ *
+ */
+BOOL SROMbIsRegBitsOff (DWORD_PTR dwIoBase, BYTE byContntOffset, BYTE byTestBits)
+{
+    BYTE    byOrgData;
+
+    byOrgData = SROMbyReadEmbedded(dwIoBase, byContntOffset);
+    return BITbIsAllBitsOff(byOrgData, byTestBits);
+}
+
+
+/*
+ * Description: Read all contents of eeprom to buffer
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *  Out:
+ *      pbyEepromRegs   - EEPROM content Buffer
+ *
+ * Return Value: none
+ *
+ */
+void SROMvReadAllContents (DWORD_PTR dwIoBase, PBYTE pbyEepromRegs)
+{
+    int     ii;
+
+    // ii = Rom Address
+    for (ii = 0; ii < EEP_MAX_CONTEXT_SIZE; ii++) {
+        *pbyEepromRegs = SROMbyReadEmbedded(dwIoBase,(BYTE) ii);
+        pbyEepromRegs++;
+    }
+}
+
+
+/*
+ * Description: Write all contents of buffer to eeprom
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *      pbyEepromRegs   - EEPROM content Buffer
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void SROMvWriteAllContents (DWORD_PTR dwIoBase, PBYTE pbyEepromRegs)
+{
+    int     ii;
+
+    // ii = Rom Address
+    for (ii = 0; ii < EEP_MAX_CONTEXT_SIZE; ii++) {
+        SROMbWriteEmbedded(dwIoBase,(BYTE) ii, *pbyEepromRegs);
+        pbyEepromRegs++;
+    }
+}
+
+
+/*
+ * Description: Read Ethernet Address from eeprom to buffer
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *  Out:
+ *      pbyEtherAddress - Ethernet Address buffer
+ *
+ * Return Value: none
+ *
+ */
+void SROMvReadEtherAddress (DWORD_PTR dwIoBase, PBYTE pbyEtherAddress)
+{
+    BYTE     ii;
+
+    // ii = Rom Address
+    for (ii = 0; ii < U_ETHER_ADDR_LEN; ii++) {
+        *pbyEtherAddress = SROMbyReadEmbedded(dwIoBase, ii);
+        pbyEtherAddress++;
+    }
+}
+
+
+/*
+ * Description: Write Ethernet Address from buffer to eeprom
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *      pbyEtherAddress - Ethernet Address buffer
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+void SROMvWriteEtherAddress (DWORD_PTR dwIoBase, PBYTE pbyEtherAddress)
+{
+    BYTE     ii;
+
+    // ii = Rom Address
+    for (ii = 0; ii < U_ETHER_ADDR_LEN; ii++) {
+        SROMbWriteEmbedded(dwIoBase, ii, *pbyEtherAddress);
+        pbyEtherAddress++;
+    }
+}
+
+
+/*
+ * Description: Read Sub_VID and Sub_SysId from eeprom to buffer
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *  Out:
+ *      pdwSubSysVenId  - Sub_VID and Sub_SysId read
+ *
+ * Return Value: none
+ *
+ */
+void SROMvReadSubSysVenId (DWORD_PTR dwIoBase, PDWORD pdwSubSysVenId)
+{
+    PBYTE   pbyData;
+
+    pbyData = (PBYTE)pdwSubSysVenId;
+    // sub vendor
+    *pbyData = SROMbyReadEmbedded(dwIoBase, 6);
+    *(pbyData+1) = SROMbyReadEmbedded(dwIoBase, 7);
+    // sub system
+    *(pbyData+2) = SROMbyReadEmbedded(dwIoBase, 8);
+    *(pbyData+3) = SROMbyReadEmbedded(dwIoBase, 9);
+}
+
+/*
+ * Description: Auto Load EEPROM to MAC register
+ *
+ * Parameters:
+ *  In:
+ *      dwIoBase        - I/O base address
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; otherwise FALSE
+ *
+ */
+BOOL SROMbAutoLoad (DWORD_PTR dwIoBase)
+{
+    BYTE    byWait;
+    int     ii;
+
+    BYTE    byOrg;
+
+    VNSvInPortB(dwIoBase + MAC_REG_I2MCFG, &byOrg);
+    // turn on hardware retry
+    VNSvOutPortB(dwIoBase + MAC_REG_I2MCFG, (byOrg | I2MCFG_NORETRY));
+
+    MACvRegBitsOn(dwIoBase, MAC_REG_I2MCSR, I2MCSR_AUTOLD);
+
+    // ii = Rom Address
+    for (ii = 0; ii < EEP_MAX_CONTEXT_SIZE; ii++) {
+        MACvTimer0MicroSDelay(dwIoBase, CB_EEPROM_READBYTE_WAIT);
+        VNSvInPortB(dwIoBase + MAC_REG_I2MCSR, &byWait);
+        if (BITbIsBitOff(byWait, I2MCSR_AUTOLD))
+            break;
+    }
+
+    VNSvOutPortB(dwIoBase + MAC_REG_I2MCFG, byOrg);
+
+    if (ii == EEP_MAX_CONTEXT_SIZE)
+        return FALSE;
+    return TRUE;
+}
+
+
diff --git a/drivers/staging/vt6655/srom.h b/drivers/staging/vt6655/srom.h
new file mode 100644
index 0000000..a4ca5f0
--- /dev/null
+++ b/drivers/staging/vt6655/srom.h
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: srom.h
+ *
+ * Purpose: Implement functions to access eeprom
+ *
+ * Author: Jerry Chen
+ *
+ * Date: Jan 29, 2003
+ *
+ */
+
+
+#ifndef __SROM_H__
+#define __SROM_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+
+#define EEP_MAX_CONTEXT_SIZE    256
+
+#define CB_EEPROM_READBYTE_WAIT 900     //us
+
+#define W_MAX_I2CRETRY          0x0fff
+
+//
+// Contents in the EEPROM
+//
+
+#define EEP_OFS_PAR         0x00        // physical address
+#define EEP_OFS_ANTENNA     0x16
+#define EEP_OFS_RADIOCTL    0x17
+#define EEP_OFS_RFTYPE      0x1B        // for select RF
+#define EEP_OFS_MINCHANNEL  0x1C        // Min Channel #
+#define EEP_OFS_MAXCHANNEL  0x1D        // Max Channel #
+#define EEP_OFS_SIGNATURE   0x1E        //
+#define EEP_OFS_ZONETYPE    0x1F        //
+#define EEP_OFS_RFTABLE     0x20        // RF POWER TABLE
+#define EEP_OFS_PWR_CCK     0x20
+#define EEP_OFS_SETPT_CCK   0x21
+#define EEP_OFS_PWR_OFDMG   0x23
+#define EEP_OFS_SETPT_OFDMG 0x24
+#define EEP_OFS_PWR_FORMULA_OST  0x26   //
+#define EEP_OFS_MAJOR_VER 0x2E
+#define EEP_OFS_MINOR_VER 0x2F
+#define EEP_OFS_CCK_PWR_TBL     0x30
+#define EEP_OFS_CCK_PWR_dBm     0x3F
+#define EEP_OFS_OFDM_PWR_TBL    0x40
+#define EEP_OFS_OFDM_PWR_dBm    0x4F
+//{{ RobertYu: 20041124
+#define EEP_OFS_SETPT_OFDMA         0x4E
+#define EEP_OFS_OFDMA_PWR_TBL       0x50
+//}}
+#define EEP_OFS_OFDMA_PWR_dBm       0xD2
+
+
+//----------need to remove --------------------
+#define EEP_OFS_BBTAB_LEN   0x70        // BB Table Length
+#define EEP_OFS_BBTAB_ADR   0x71        // BB Table Offset
+#define EEP_OFS_CHECKSUM    0xFF        // reserved area for baseband 28h ~ 78h
+
+#define EEP_I2C_DEV_ID      0x50        // EEPROM device address on the I2C bus
+
+
+//
+// Bits in EEP_OFS_ANTENNA
+//
+#define EEP_ANTENNA_MAIN    0x01
+#define EEP_ANTENNA_AUX     0x02
+#define EEP_ANTINV          0x04
+
+//
+// Bits in EEP_OFS_RADIOCTL
+//
+#define EEP_RADIOCTL_ENABLE 0x80
+#define EEP_RADIOCTL_INV    0x01
+
+
+
+/*---------------------  Export Types  ------------------------------*/
+
+// AT24C02 eeprom contents
+//      2048 bits = 256 bytes = 128 words
+//
+typedef struct tagSSromReg {
+    BYTE    abyPAR[6];                  // 0x00 (WORD)
+
+    WORD    wSUB_VID;                   // 0x03 (WORD)
+    WORD    wSUB_SID;
+
+    BYTE    byBCFG0;                    // 0x05 (WORD)
+    BYTE    byBCFG1;
+
+    BYTE    byFCR0;                     // 0x06 (WORD)
+    BYTE    byFCR1;
+    BYTE    byPMC0;                     // 0x07 (WORD)
+    BYTE    byPMC1;
+    BYTE    byMAXLAT;                   // 0x08 (WORD)
+    BYTE    byMINGNT;
+    BYTE    byCFG0;                     // 0x09 (WORD)
+    BYTE    byCFG1;
+    WORD    wCISPTR;                    // 0x0A (WORD)
+    WORD    wRsv0;                      // 0x0B (WORD)
+    WORD    wRsv1;                      // 0x0C (WORD)
+    BYTE    byBBPAIR;                   // 0x0D (WORD)
+    BYTE    byRFTYPE;
+    BYTE    byMinChannel;               // 0x0E (WORD)
+    BYTE    byMaxChannel;
+    BYTE    bySignature;                // 0x0F (WORD)
+    BYTE    byCheckSum;
+
+    BYTE    abyReserved0[96];           // 0x10 (WORD)
+    BYTE    abyCIS[128];                // 0x80 (WORD)
+} SSromReg, DEF* PSSromReg;
+
+/*---------------------  Export Macros ------------------------------*/
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+
+BYTE SROMbyReadEmbedded(DWORD_PTR dwIoBase, BYTE byContntOffset);
+BOOL SROMbWriteEmbedded(DWORD_PTR dwIoBase, BYTE byContntOffset, BYTE byData);
+
+void SROMvRegBitsOn(DWORD_PTR dwIoBase, BYTE byContntOffset, BYTE byBits);
+void SROMvRegBitsOff(DWORD_PTR dwIoBase, BYTE byContntOffset, BYTE byBits);
+
+BOOL SROMbIsRegBitsOn(DWORD_PTR dwIoBase, BYTE byContntOffset, BYTE byTestBits);
+BOOL SROMbIsRegBitsOff(DWORD_PTR dwIoBase, BYTE byContntOffset, BYTE byTestBits);
+
+void SROMvReadAllContents(DWORD_PTR dwIoBase, PBYTE pbyEepromRegs);
+void SROMvWriteAllContents(DWORD_PTR dwIoBase, PBYTE pbyEepromRegs);
+
+void SROMvReadEtherAddress(DWORD_PTR dwIoBase, PBYTE pbyEtherAddress);
+void SROMvWriteEtherAddress(DWORD_PTR dwIoBase, PBYTE pbyEtherAddress);
+
+VOID SROMvReadSubSysVenId(DWORD_PTR dwIoBase, PDWORD pdwSubSysVenId);
+
+BOOL SROMbAutoLoad (DWORD_PTR dwIoBase);
+
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+
+#endif // __EEPROM_H__
+
+
diff --git a/drivers/staging/vt6655/tbit.h b/drivers/staging/vt6655/tbit.h
new file mode 100644
index 0000000..7c3a82e
--- /dev/null
+++ b/drivers/staging/vt6655/tbit.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: tbit.h
+ *
+ * Purpose: Bit routines
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ *
+ */
+
+
+#ifndef __TBIT_H__
+#define __TBIT_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+/*---------------------  Export Types  ------------------------------*/
+
+/*---------------------  Export Macros ------------------------------*/
+
+// test single bit on
+#define BITbIsBitOn(tData, tTestBit)                \
+    (((tData) & (tTestBit)) != 0)
+
+// test single bit off
+#define BITbIsBitOff(tData, tTestBit)               \
+    (((tData) & (tTestBit)) == 0)
+
+
+#define BITbIsAllBitsOn(tData, tTestBit)            \
+    (((tData) & (tTestBit)) == (tTestBit))
+
+#define BITbIsAllBitsOff(tData, tTestBit)           \
+    (((tData) & (tTestBit)) == 0)
+
+#define BITbIsAnyBitsOn(tData, tTestBit)            \
+    (((tData) & (tTestBit)) != 0)
+
+#define BITbIsAnyBitsOff(tData, tTestBit)           \
+    (((tData) & (tTestBit)) != (tTestBit))
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+#endif // __TBIT_H__
+
+
+
diff --git a/drivers/staging/vt6655/tcrc.c b/drivers/staging/vt6655/tcrc.c
new file mode 100644
index 0000000..b70080c
--- /dev/null
+++ b/drivers/staging/vt6655/tcrc.c
@@ -0,0 +1,207 @@
+/*
+ * Copyright (c) 2003 VIA Networking, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: tcrc.c
+ *
+ * Purpose: Implement functions to caculate CRC
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ *
+ * Functions:
+ *      CRCdwCrc32 -
+ *      CRCdwGetCrc32 -
+ *      CRCdwGetCrc32Ex -
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__TCRC_H__)
+#include "tcrc.h"
+#endif
+
+
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+// 32-bit CRC table
+static const DWORD s_adwCrc32Table[256] = {
+    0x00000000L, 0x77073096L, 0xEE0E612CL, 0x990951BAL,
+    0x076DC419L, 0x706AF48FL, 0xE963A535L, 0x9E6495A3L,
+    0x0EDB8832L, 0x79DCB8A4L, 0xE0D5E91EL, 0x97D2D988L,
+    0x09B64C2BL, 0x7EB17CBDL, 0xE7B82D07L, 0x90BF1D91L,
+    0x1DB71064L, 0x6AB020F2L, 0xF3B97148L, 0x84BE41DEL,
+    0x1ADAD47DL, 0x6DDDE4EBL, 0xF4D4B551L, 0x83D385C7L,
+    0x136C9856L, 0x646BA8C0L, 0xFD62F97AL, 0x8A65C9ECL,
+    0x14015C4FL, 0x63066CD9L, 0xFA0F3D63L, 0x8D080DF5L,
+    0x3B6E20C8L, 0x4C69105EL, 0xD56041E4L, 0xA2677172L,
+    0x3C03E4D1L, 0x4B04D447L, 0xD20D85FDL, 0xA50AB56BL,
+    0x35B5A8FAL, 0x42B2986CL, 0xDBBBC9D6L, 0xACBCF940L,
+    0x32D86CE3L, 0x45DF5C75L, 0xDCD60DCFL, 0xABD13D59L,
+    0x26D930ACL, 0x51DE003AL, 0xC8D75180L, 0xBFD06116L,
+    0x21B4F4B5L, 0x56B3C423L, 0xCFBA9599L, 0xB8BDA50FL,
+    0x2802B89EL, 0x5F058808L, 0xC60CD9B2L, 0xB10BE924L,
+    0x2F6F7C87L, 0x58684C11L, 0xC1611DABL, 0xB6662D3DL,
+    0x76DC4190L, 0x01DB7106L, 0x98D220BCL, 0xEFD5102AL,
+    0x71B18589L, 0x06B6B51FL, 0x9FBFE4A5L, 0xE8B8D433L,
+    0x7807C9A2L, 0x0F00F934L, 0x9609A88EL, 0xE10E9818L,
+    0x7F6A0DBBL, 0x086D3D2DL, 0x91646C97L, 0xE6635C01L,
+    0x6B6B51F4L, 0x1C6C6162L, 0x856530D8L, 0xF262004EL,
+    0x6C0695EDL, 0x1B01A57BL, 0x8208F4C1L, 0xF50FC457L,
+    0x65B0D9C6L, 0x12B7E950L, 0x8BBEB8EAL, 0xFCB9887CL,
+    0x62DD1DDFL, 0x15DA2D49L, 0x8CD37CF3L, 0xFBD44C65L,
+    0x4DB26158L, 0x3AB551CEL, 0xA3BC0074L, 0xD4BB30E2L,
+    0x4ADFA541L, 0x3DD895D7L, 0xA4D1C46DL, 0xD3D6F4FBL,
+    0x4369E96AL, 0x346ED9FCL, 0xAD678846L, 0xDA60B8D0L,
+    0x44042D73L, 0x33031DE5L, 0xAA0A4C5FL, 0xDD0D7CC9L,
+    0x5005713CL, 0x270241AAL, 0xBE0B1010L, 0xC90C2086L,
+    0x5768B525L, 0x206F85B3L, 0xB966D409L, 0xCE61E49FL,
+    0x5EDEF90EL, 0x29D9C998L, 0xB0D09822L, 0xC7D7A8B4L,
+    0x59B33D17L, 0x2EB40D81L, 0xB7BD5C3BL, 0xC0BA6CADL,
+    0xEDB88320L, 0x9ABFB3B6L, 0x03B6E20CL, 0x74B1D29AL,
+    0xEAD54739L, 0x9DD277AFL, 0x04DB2615L, 0x73DC1683L,
+    0xE3630B12L, 0x94643B84L, 0x0D6D6A3EL, 0x7A6A5AA8L,
+    0xE40ECF0BL, 0x9309FF9DL, 0x0A00AE27L, 0x7D079EB1L,
+    0xF00F9344L, 0x8708A3D2L, 0x1E01F268L, 0x6906C2FEL,
+    0xF762575DL, 0x806567CBL, 0x196C3671L, 0x6E6B06E7L,
+    0xFED41B76L, 0x89D32BE0L, 0x10DA7A5AL, 0x67DD4ACCL,
+    0xF9B9DF6FL, 0x8EBEEFF9L, 0x17B7BE43L, 0x60B08ED5L,
+    0xD6D6A3E8L, 0xA1D1937EL, 0x38D8C2C4L, 0x4FDFF252L,
+    0xD1BB67F1L, 0xA6BC5767L, 0x3FB506DDL, 0x48B2364BL,
+    0xD80D2BDAL, 0xAF0A1B4CL, 0x36034AF6L, 0x41047A60L,
+    0xDF60EFC3L, 0xA867DF55L, 0x316E8EEFL, 0x4669BE79L,
+    0xCB61B38CL, 0xBC66831AL, 0x256FD2A0L, 0x5268E236L,
+    0xCC0C7795L, 0xBB0B4703L, 0x220216B9L, 0x5505262FL,
+    0xC5BA3BBEL, 0xB2BD0B28L, 0x2BB45A92L, 0x5CB36A04L,
+    0xC2D7FFA7L, 0xB5D0CF31L, 0x2CD99E8BL, 0x5BDEAE1DL,
+    0x9B64C2B0L, 0xEC63F226L, 0x756AA39CL, 0x026D930AL,
+    0x9C0906A9L, 0xEB0E363FL, 0x72076785L, 0x05005713L,
+    0x95BF4A82L, 0xE2B87A14L, 0x7BB12BAEL, 0x0CB61B38L,
+    0x92D28E9BL, 0xE5D5BE0DL, 0x7CDCEFB7L, 0x0BDBDF21L,
+    0x86D3D2D4L, 0xF1D4E242L, 0x68DDB3F8L, 0x1FDA836EL,
+    0x81BE16CDL, 0xF6B9265BL, 0x6FB077E1L, 0x18B74777L,
+    0x88085AE6L, 0xFF0F6A70L, 0x66063BCAL, 0x11010B5CL,
+    0x8F659EFFL, 0xF862AE69L, 0x616BFFD3L, 0x166CCF45L,
+    0xA00AE278L, 0xD70DD2EEL, 0x4E048354L, 0x3903B3C2L,
+    0xA7672661L, 0xD06016F7L, 0x4969474DL, 0x3E6E77DBL,
+    0xAED16A4AL, 0xD9D65ADCL, 0x40DF0B66L, 0x37D83BF0L,
+    0xA9BCAE53L, 0xDEBB9EC5L, 0x47B2CF7FL, 0x30B5FFE9L,
+    0xBDBDF21CL, 0xCABAC28AL, 0x53B39330L, 0x24B4A3A6L,
+    0xBAD03605L, 0xCDD70693L, 0x54DE5729L, 0x23D967BFL,
+    0xB3667A2EL, 0xC4614AB8L, 0x5D681B02L, 0x2A6F2B94L,
+    0xB40BBE37L, 0xC30C8EA1L, 0x5A05DF1BL, 0x2D02EF8DL
+};
+
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+
+
+/*+
+ *
+ * Description:
+ *    Generate a CRC-32 from the data stream
+ *
+ * Parameters:
+ *  In:
+ *      pbyData     - the data stream
+ *      cbByte      - the length of the stream
+ *      dwCrcSeed   - Seed for CRC32
+ *  Out:
+ *      none
+ *
+ * Return Value: CRC-32
+ *
+-*/
+DWORD CRCdwCrc32 (PBYTE pbyData, UINT cbByte, DWORD dwCrcSeed)
+{
+    DWORD dwCrc;
+
+    dwCrc = dwCrcSeed;
+    while (cbByte--) {
+        dwCrc = s_adwCrc32Table[(BYTE)((dwCrc ^ (*pbyData)) & 0xFF)] ^ (dwCrc >> 8);
+        pbyData++;
+    }
+
+    return dwCrc;
+}
+
+
+/*+
+ *
+ * Description:
+ * To test CRC generator, input 8 bytes packet
+ *      -- 0xff 0xff 0xff 0xff 0x00 0x00 0x00 0x00
+ * the generated CRC should be
+ *      -- 0xff 0xff 0xff 0xff
+ *
+ * Parameters:
+ *  In:
+ *      pbyData     - the data stream
+ *      cbByte      - the length of the stream
+ *  Out:
+ *      none
+ *
+ * Return Value: CRC-32
+ *
+-*/
+DWORD CRCdwGetCrc32 (PBYTE pbyData, UINT cbByte)
+{
+    return ~CRCdwCrc32(pbyData, cbByte, 0xFFFFFFFFL);
+}
+
+
+/*+
+ *
+ * Description:
+ *
+ * NOTE.... Because CRCdwGetCrc32Ex() is an iteration function,
+ *          this means we will use the output of CRCdwGetCrc32Ex()
+ *          to be a new argument to do next CRCdwGetCrc32Ex() calculation.
+ *          Thus, the final result must be inverted to be the
+ *          correct answer.
+ *
+ * Parameters:
+ *  In:
+ *      pbyData     - the data stream
+ *      cbByte      - the length of the stream
+ *  Out:
+ *      none
+ *
+ * Return Value: CRC-32
+ *
+-*/
+DWORD CRCdwGetCrc32Ex(PBYTE pbyData, UINT cbByte, DWORD dwPreCRC)
+{
+    return CRCdwCrc32(pbyData, cbByte, dwPreCRC);
+}
+
+
diff --git a/drivers/staging/vt6655/tcrc.h b/drivers/staging/vt6655/tcrc.h
new file mode 100644
index 0000000..ebea22e
--- /dev/null
+++ b/drivers/staging/vt6655/tcrc.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2003 VIA Networking, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: tcrc.h
+ *
+ * Purpose: Implement functions to caculate CRC
+ *
+ * Author: Tevin Chen
+ *
+ * Date: Jan. 28, 1997
+ *
+ */
+
+
+#ifndef __TCRC_H__
+#define __TCRC_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+/*---------------------  Export Types  ------------------------------*/
+
+/*---------------------  Export Macros ------------------------------*/
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+
+DWORD CRCdwCrc32(PBYTE pbyData, UINT cbByte, DWORD dwCrcSeed);
+DWORD CRCdwGetCrc32(PBYTE pbyData, UINT cbByte);
+DWORD CRCdwGetCrc32Ex(PBYTE pbyData, UINT cbByte, DWORD dwPreCRC);
+
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+
+#endif // __TCRC_H__
+
+
+
diff --git a/drivers/staging/vt6655/test b/drivers/staging/vt6655/test
new file mode 100644
index 0000000..039f7d7
--- /dev/null
+++ b/drivers/staging/vt6655/test
@@ -0,0 +1,9 @@
+KSP :=  /lib/modules/$(shell uname -r)/build \
+	/usr/src/linux-$(shell uname -r) \
+	/usr/src/linux-$(shell uname -r | sed 's/-.*//') \
+#	/usr/src/kernel-headers-$(shell uname -r) \
+#	/usr/src/kernel-source-$(shell uname -r) \
+#	/usr/src/linux-$(shell uname -r | sed 's/\([0-9]*\.[0-9]*\)\..*/\1/') \
+#	/usr/src/linux   /home/plice
+test_dir = $(shell [ -e $(dir)/include/linux ] && echo $(dir))
+KSP := $(foreach dir, $(KSP), $(test_dir))
\ No newline at end of file
diff --git a/drivers/staging/vt6655/tether.c b/drivers/staging/vt6655/tether.c
new file mode 100644
index 0000000..fd69423
--- /dev/null
+++ b/drivers/staging/vt6655/tether.c
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2003 VIA Networking, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: tether.c
+ *
+ * Purpose:
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ *
+ * Functions:
+ *      ETHbyGetHashIndexByCrc32 - Caculate multicast hash value by CRC32
+ *      ETHbIsBufferCrc32Ok - Check CRC value of the buffer if Ok or not
+ *
+ * Revision History:
+ *
+ */
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__TCRC_H__)
+#include "tcrc.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+
+
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+
+/*
+ * Description: Caculate multicast hash value by CRC32
+ *
+ * Parameters:
+ *  In:
+ *		pbyMultiAddr    - Multicast Address
+ *  Out:
+ *      none
+ *
+ * Return Value: Hash value
+ *
+ */
+BYTE ETHbyGetHashIndexByCrc32 (PBYTE pbyMultiAddr)
+{
+    int     ii;
+    BYTE    byTmpHash;
+    BYTE    byHash = 0;
+
+    // get the least 6-bits from CRC generator
+    byTmpHash = (BYTE)(CRCdwCrc32(pbyMultiAddr, U_ETHER_ADDR_LEN,
+            0xFFFFFFFFL) & 0x3F);
+    // reverse most bit to least bit
+    for (ii = 0; ii < (sizeof(byTmpHash) * 8); ii++) {
+        byHash <<= 1;
+        if (BITbIsBitOn(byTmpHash, 0x01))
+            byHash |= 1;
+        byTmpHash >>= 1;
+    }
+
+    // adjust 6-bits to the right most
+    return (byHash >> 2);
+}
+
+
+/*
+ * Description: Check CRC value of the buffer if Ok or not
+ *
+ * Parameters:
+ *  In:
+ *		pbyBuffer	    - pointer of buffer (normally is rx buffer)
+ *		cbFrameLength	- length of buffer, including CRC portion
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if ok; FALSE if error.
+ *
+ */
+BOOL ETHbIsBufferCrc32Ok (PBYTE pbyBuffer, UINT cbFrameLength)
+{
+    DWORD dwCRC;
+
+    dwCRC = CRCdwGetCrc32(pbyBuffer, cbFrameLength - 4);
+    if (cpu_to_le32(*((PDWORD)(pbyBuffer + cbFrameLength - 4))) != dwCRC) {
+        return FALSE;
+    }
+    return TRUE;
+}
+
diff --git a/drivers/staging/vt6655/tether.h b/drivers/staging/vt6655/tether.h
new file mode 100644
index 0000000..920a8bb
--- /dev/null
+++ b/drivers/staging/vt6655/tether.h
@@ -0,0 +1,256 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: tether.h
+ *
+ * Purpose:
+ *
+ * Author: Tevin Chen
+ *
+ * Date: Jan. 28, 1997
+ *
+ */
+
+
+
+#ifndef __TETHER_H__
+#define __TETHER_H__
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+//
+// constants
+//
+#define U_ETHER_ADDR_LEN    6           // Ethernet address length
+#define U_TYPE_LEN          2           //
+#define U_CRC_LEN           4           //
+#define U_HEADER_LEN        (U_ETHER_ADDR_LEN * 2 + U_TYPE_LEN)
+#define U_ETHER_ADDR_STR_LEN (U_ETHER_ADDR_LEN * 2 + 1)
+                                        // Ethernet address string length
+
+#define MIN_DATA_LEN        46          // min data length
+#define MAX_DATA_LEN        1500        // max data length
+
+#define MIN_PACKET_LEN      (MIN_DATA_LEN + U_HEADER_LEN)
+                                        // 60
+                                        // min total packet length (tx)
+#define MAX_PACKET_LEN      (MAX_DATA_LEN + U_HEADER_LEN)
+                                        // 1514
+                                        // max total packet length (tx)
+
+#define MAX_LOOKAHEAD_SIZE  MAX_PACKET_LEN
+
+#define U_MULTI_ADDR_LEN    8           // multicast address length
+
+
+#ifdef __BIG_ENDIAN
+
+#define TYPE_PKT_IP         0x0800      //
+#define TYPE_PKT_ARP        0x0806      //
+#define TYPE_PKT_RARP       0x8035      //
+#define TYPE_PKT_IPX	    0x8137	    //
+#define TYPE_PKT_802_1x     0x888e
+#define TYPE_PKT_PreAuth    0x88C7
+
+#define TYPE_PKT_PING_M_REQ 0x8011      // master reguest
+#define TYPE_PKT_PING_S_GNT 0x8022      // slave grant
+#define TYPE_PKT_PING_M     0x8077      // pingpong master packet
+#define TYPE_PKT_PING_S     0x8088      // pingpong slave packet
+#define TYPE_PKT_WOL_M_REQ  0x8033      // WOL waker request
+#define TYPE_PKT_WOL_S_GNT  0x8044      // WOL sleeper grant
+#define TYPE_MGMT_PROBE_RSP 0x5000
+#define TYPE_PKT_VNT_DIAG   0x8011      // Diag Pkt
+#define TYPE_PKT_VNT_PER    0x8888      // Diag PER Pkt
+//
+// wFrameCtl field in the S802_11Header
+//
+// NOTE....
+//   in network byte order, high byte is going first
+#define FC_TODS             0x0001
+#define FC_FROMDS           0x0002
+#define FC_MOREFRAG         0x0004
+#define FC_RETRY            0x0008
+#define FC_POWERMGT         0x0010
+#define FC_MOREDATA         0x0020
+#define FC_WEP              0x0040
+#define TYPE_802_11_ATIM    0x9000
+
+#define TYPE_802_11_DATA    0x0800
+#define TYPE_802_11_CTL     0x0400
+#define TYPE_802_11_MGMT    0x0000
+#define TYPE_802_11_MASK    0x0C00
+#define TYPE_SUBTYPE_MASK   0xFC00
+#define TYPE_802_11_NODATA  0x4000
+#define TYPE_DATE_NULL      0x4800
+
+#define TYPE_CTL_PSPOLL     0xa400
+#define TYPE_CTL_RTS        0xb400
+#define TYPE_CTL_CTS        0xc400
+#define TYPE_CTL_ACK        0xd400
+
+
+//#define WEP_IV_MASK         0xFFFFFF00
+
+#else //if LITTLE_ENDIAN
+//
+// wType field in the SEthernetHeader
+//
+// NOTE....
+//   in network byte order, high byte is going first
+#define TYPE_PKT_IP         0x0008      //
+#define TYPE_PKT_ARP        0x0608      //
+#define TYPE_PKT_RARP       0x3580      //
+#define TYPE_PKT_IPX	    0x3781	    //
+
+#define TYPE_PKT_802_1x     0x8e88
+#define TYPE_PKT_PreAuth    0xC788
+
+#define TYPE_PKT_PING_M_REQ 0x1180      // master reguest
+#define TYPE_PKT_PING_S_GNT 0x2280      // slave grant
+#define TYPE_PKT_PING_M     0x7780      // pingpong master packet
+#define TYPE_PKT_PING_S     0x8880      // pingpong slave packet
+#define TYPE_PKT_WOL_M_REQ  0x3380      // WOL waker request
+#define TYPE_PKT_WOL_S_GNT  0x4480      // WOL sleeper grant
+#define TYPE_MGMT_PROBE_RSP 0x0050
+#define TYPE_PKT_VNT_DIAG   0x1180      // Diag Pkt
+#define TYPE_PKT_VNT_PER    0x8888      // Diag PER Pkt
+//
+// wFrameCtl field in the S802_11Header
+//
+// NOTE....
+//   in network byte order, high byte is going first
+#define FC_TODS             0x0100
+#define FC_FROMDS           0x0200
+#define FC_MOREFRAG         0x0400
+#define FC_RETRY            0x0800
+#define FC_POWERMGT         0x1000
+#define FC_MOREDATA         0x2000
+#define FC_WEP              0x4000
+#define TYPE_802_11_ATIM    0x0090
+
+#define TYPE_802_11_DATA    0x0008
+#define TYPE_802_11_CTL     0x0004
+#define TYPE_802_11_MGMT    0x0000
+#define TYPE_802_11_MASK    0x000C
+#define TYPE_SUBTYPE_MASK   0x00FC
+#define TYPE_802_11_NODATA  0x0040
+#define TYPE_DATE_NULL      0x0048
+
+#define TYPE_CTL_PSPOLL     0x00a4
+#define TYPE_CTL_RTS        0x00b4
+#define TYPE_CTL_CTS        0x00c4
+#define TYPE_CTL_ACK        0x00d4
+
+
+//#define WEP_IV_MASK         0x00FFFFFF
+
+#endif //#ifdef __BIG_ENDIAN
+
+#define WEP_IV_MASK         0x00FFFFFF
+
+/*---------------------  Export Types  ------------------------------*/
+//
+// Ethernet packet
+//
+typedef struct tagSEthernetHeader {
+    BYTE    abyDstAddr[U_ETHER_ADDR_LEN];
+    BYTE    abySrcAddr[U_ETHER_ADDR_LEN];
+    WORD    wType;
+}__attribute__ ((__packed__))
+SEthernetHeader, DEF* PSEthernetHeader;
+
+
+//
+// 802_3 packet
+//
+typedef struct tagS802_3Header {
+    BYTE    abyDstAddr[U_ETHER_ADDR_LEN];
+    BYTE    abySrcAddr[U_ETHER_ADDR_LEN];
+    WORD    wLen;
+}__attribute__ ((__packed__))
+S802_3Header, DEF* PS802_3Header;
+
+//
+// 802_11 packet
+//
+typedef struct tagS802_11Header {
+    WORD    wFrameCtl;
+    WORD    wDurationID;
+    BYTE    abyAddr1[U_ETHER_ADDR_LEN];
+    BYTE    abyAddr2[U_ETHER_ADDR_LEN];
+    BYTE    abyAddr3[U_ETHER_ADDR_LEN];
+    WORD    wSeqCtl;
+    BYTE    abyAddr4[U_ETHER_ADDR_LEN];
+}__attribute__ ((__packed__))
+S802_11Header, DEF* PS802_11Header;
+
+/*---------------------  Export Macros ------------------------------*/
+// Frame type macro
+
+#define IS_MULTICAST_ADDRESS(pbyEtherAddr)          \
+    ((*(PBYTE)(pbyEtherAddr) & 0x01) == 1)
+
+#define IS_BROADCAST_ADDRESS(pbyEtherAddr) (        \
+    (*(PDWORD)(pbyEtherAddr) == 0xFFFFFFFFL) &&     \
+    (*(PWORD)((PBYTE)(pbyEtherAddr) + 4) == 0xFFFF) \
+)
+
+#define IS_NULL_ADDRESS(pbyEtherAddr) (             \
+    (*(PDWORD)(pbyEtherAddr) == 0L) &&              \
+    (*(PWORD)((PBYTE)(pbyEtherAddr) + 4) == 0)      \
+)
+
+#define IS_ETH_ADDRESS_EQUAL(pbyAddr1, pbyAddr2) (  \
+    (*(PDWORD)(pbyAddr1) == *(PDWORD)(pbyAddr2)) && \
+    (*(PWORD)((PBYTE)(pbyAddr1) + 4) ==             \
+    *(PWORD)((PBYTE)(pbyAddr2) + 4))                \
+)
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+
+BYTE ETHbyGetHashIndexByCrc32(PBYTE pbyMultiAddr);
+//BYTE ETHbyGetHashIndexByCrc(PBYTE pbyMultiAddr);
+BOOL ETHbIsBufferCrc32Ok(PBYTE pbyBuffer, UINT cbFrameLength);
+
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+
+#endif // __TETHER_H__
+
+
+
diff --git a/drivers/staging/vt6655/tkip.c b/drivers/staging/vt6655/tkip.c
new file mode 100644
index 0000000..2ded842
--- /dev/null
+++ b/drivers/staging/vt6655/tkip.c
@@ -0,0 +1,284 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: tkip.c
+ *
+ * Purpose: Implement functions for 802.11i TKIP
+ *
+ * Author: Jerry Chen
+ *
+ * Date: Mar. 11, 2003
+ *
+ * Functions:
+ *      TKIPvMixKey - Get TKIP RC4 Key from TK,TA, and TSC
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__TKIP_H__)
+#include "tkip.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+/* The Sbox is reduced to 2 16-bit wide tables, each with 256 entries. */
+/* The 2nd table is the same as the 1st but with the upper and lower   */
+/* bytes swapped. To allow an endian tolerant implementation, the byte */
+/* halves have been expressed independently here.                      */
+const BYTE TKIP_Sbox_Lower[256] = {
+    0xA5,0x84,0x99,0x8D,0x0D,0xBD,0xB1,0x54,
+    0x50,0x03,0xA9,0x7D,0x19,0x62,0xE6,0x9A,
+    0x45,0x9D,0x40,0x87,0x15,0xEB,0xC9,0x0B,
+    0xEC,0x67,0xFD,0xEA,0xBF,0xF7,0x96,0x5B,
+    0xC2,0x1C,0xAE,0x6A,0x5A,0x41,0x02,0x4F,
+    0x5C,0xF4,0x34,0x08,0x93,0x73,0x53,0x3F,
+    0x0C,0x52,0x65,0x5E,0x28,0xA1,0x0F,0xB5,
+    0x09,0x36,0x9B,0x3D,0x26,0x69,0xCD,0x9F,
+    0x1B,0x9E,0x74,0x2E,0x2D,0xB2,0xEE,0xFB,
+    0xF6,0x4D,0x61,0xCE,0x7B,0x3E,0x71,0x97,
+    0xF5,0x68,0x00,0x2C,0x60,0x1F,0xC8,0xED,
+    0xBE,0x46,0xD9,0x4B,0xDE,0xD4,0xE8,0x4A,
+    0x6B,0x2A,0xE5,0x16,0xC5,0xD7,0x55,0x94,
+    0xCF,0x10,0x06,0x81,0xF0,0x44,0xBA,0xE3,
+    0xF3,0xFE,0xC0,0x8A,0xAD,0xBC,0x48,0x04,
+    0xDF,0xC1,0x75,0x63,0x30,0x1A,0x0E,0x6D,
+    0x4C,0x14,0x35,0x2F,0xE1,0xA2,0xCC,0x39,
+    0x57,0xF2,0x82,0x47,0xAC,0xE7,0x2B,0x95,
+    0xA0,0x98,0xD1,0x7F,0x66,0x7E,0xAB,0x83,
+    0xCA,0x29,0xD3,0x3C,0x79,0xE2,0x1D,0x76,
+    0x3B,0x56,0x4E,0x1E,0xDB,0x0A,0x6C,0xE4,
+    0x5D,0x6E,0xEF,0xA6,0xA8,0xA4,0x37,0x8B,
+    0x32,0x43,0x59,0xB7,0x8C,0x64,0xD2,0xE0,
+    0xB4,0xFA,0x07,0x25,0xAF,0x8E,0xE9,0x18,
+    0xD5,0x88,0x6F,0x72,0x24,0xF1,0xC7,0x51,
+    0x23,0x7C,0x9C,0x21,0xDD,0xDC,0x86,0x85,
+    0x90,0x42,0xC4,0xAA,0xD8,0x05,0x01,0x12,
+    0xA3,0x5F,0xF9,0xD0,0x91,0x58,0x27,0xB9,
+    0x38,0x13,0xB3,0x33,0xBB,0x70,0x89,0xA7,
+    0xB6,0x22,0x92,0x20,0x49,0xFF,0x78,0x7A,
+    0x8F,0xF8,0x80,0x17,0xDA,0x31,0xC6,0xB8,
+    0xC3,0xB0,0x77,0x11,0xCB,0xFC,0xD6,0x3A
+};
+
+const BYTE TKIP_Sbox_Upper[256] = {
+    0xC6,0xF8,0xEE,0xF6,0xFF,0xD6,0xDE,0x91,
+    0x60,0x02,0xCE,0x56,0xE7,0xB5,0x4D,0xEC,
+    0x8F,0x1F,0x89,0xFA,0xEF,0xB2,0x8E,0xFB,
+    0x41,0xB3,0x5F,0x45,0x23,0x53,0xE4,0x9B,
+    0x75,0xE1,0x3D,0x4C,0x6C,0x7E,0xF5,0x83,
+    0x68,0x51,0xD1,0xF9,0xE2,0xAB,0x62,0x2A,
+    0x08,0x95,0x46,0x9D,0x30,0x37,0x0A,0x2F,
+    0x0E,0x24,0x1B,0xDF,0xCD,0x4E,0x7F,0xEA,
+    0x12,0x1D,0x58,0x34,0x36,0xDC,0xB4,0x5B,
+    0xA4,0x76,0xB7,0x7D,0x52,0xDD,0x5E,0x13,
+    0xA6,0xB9,0x00,0xC1,0x40,0xE3,0x79,0xB6,
+    0xD4,0x8D,0x67,0x72,0x94,0x98,0xB0,0x85,
+    0xBB,0xC5,0x4F,0xED,0x86,0x9A,0x66,0x11,
+    0x8A,0xE9,0x04,0xFE,0xA0,0x78,0x25,0x4B,
+    0xA2,0x5D,0x80,0x05,0x3F,0x21,0x70,0xF1,
+    0x63,0x77,0xAF,0x42,0x20,0xE5,0xFD,0xBF,
+    0x81,0x18,0x26,0xC3,0xBE,0x35,0x88,0x2E,
+    0x93,0x55,0xFC,0x7A,0xC8,0xBA,0x32,0xE6,
+    0xC0,0x19,0x9E,0xA3,0x44,0x54,0x3B,0x0B,
+    0x8C,0xC7,0x6B,0x28,0xA7,0xBC,0x16,0xAD,
+    0xDB,0x64,0x74,0x14,0x92,0x0C,0x48,0xB8,
+    0x9F,0xBD,0x43,0xC4,0x39,0x31,0xD3,0xF2,
+    0xD5,0x8B,0x6E,0xDA,0x01,0xB1,0x9C,0x49,
+    0xD8,0xAC,0xF3,0xCF,0xCA,0xF4,0x47,0x10,
+    0x6F,0xF0,0x4A,0x5C,0x38,0x57,0x73,0x97,
+    0xCB,0xA1,0xE8,0x3E,0x96,0x61,0x0D,0x0F,
+    0xE0,0x7C,0x71,0xCC,0x90,0x06,0xF7,0x1C,
+    0xC2,0x6A,0xAE,0x69,0x17,0x99,0x3A,0x27,
+    0xD9,0xEB,0x2B,0x22,0xD2,0xA9,0x07,0x33,
+    0x2D,0x3C,0x15,0xC9,0x87,0xAA,0x50,0xA5,
+    0x03,0x59,0x09,0x1A,0x65,0xD7,0x84,0xD0,
+    0x82,0x29,0x5A,0x1E,0x7B,0xA8,0x6D,0x2C
+};
+
+
+//STKIPKeyManagement  sTKIPKeyTable[MAX_TKIP_KEY];
+
+/*---------------------  Static Functions  --------------------------*/
+unsigned int tkip_sbox(unsigned int index);
+unsigned int rotr1(unsigned int a);
+
+/*---------------------  Export Variables  --------------------------*/
+
+/************************************************************/
+/* tkip_sbox()                                              */
+/* Returns a 16 bit value from a 64K entry table. The Table */
+/* is synthesized from two 256 entry byte wide tables.      */
+/************************************************************/
+unsigned int tkip_sbox(unsigned int index)
+{
+    unsigned int index_low;
+    unsigned int index_high;
+    unsigned int left, right;
+
+    index_low = (index % 256);
+    index_high = ((index >> 8) % 256);
+
+    left = TKIP_Sbox_Lower[index_low] + (TKIP_Sbox_Upper[index_low] * 256);
+    right = TKIP_Sbox_Upper[index_high] + (TKIP_Sbox_Lower[index_high] * 256);
+
+    return (left ^ right);
+};
+
+
+unsigned int rotr1(unsigned int a)
+{
+    unsigned int b;
+
+    if ((a & 0x01) == 0x01) {
+        b = (a >> 1) | 0x8000;
+    } else {
+        b = (a >> 1) & 0x7fff;
+    }
+    b = b % 65536;
+    return b;
+}
+
+
+/*
+ * Description: Caculate RC4Key fom TK, TA, and TSC
+ *
+ * Parameters:
+ *  In:
+ *      pbyTKey         - TKey
+ *      pbyTA           - TA
+ *      dwTSC           - TSC
+ *  Out:
+ *      pbyRC4Key       - RC4Key
+ *
+ * Return Value: none
+ *
+ */
+VOID TKIPvMixKey(
+    PBYTE   pbyTKey,
+    PBYTE   pbyTA,
+    WORD    wTSC15_0,
+    DWORD   dwTSC47_16,
+    PBYTE   pbyRC4Key
+    )
+{
+    unsigned int p1k[5];
+//    unsigned int ttak0, ttak1, ttak2, ttak3, ttak4;
+    unsigned int tsc0, tsc1, tsc2;
+    unsigned int ppk0, ppk1, ppk2, ppk3, ppk4, ppk5;
+    unsigned long int pnl,pnh;
+
+    int i, j;
+
+    pnl = wTSC15_0;
+    pnh = dwTSC47_16;
+
+    tsc0 = (unsigned int)((pnh >> 16) % 65536); /* msb */
+    tsc1 = (unsigned int)(pnh % 65536);
+    tsc2 = (unsigned int)(pnl % 65536); /* lsb */
+
+    /* Phase 1, step 1 */
+    p1k[0] = tsc1;
+    p1k[1] = tsc0;
+    p1k[2] = (unsigned int)(pbyTA[0] + (pbyTA[1]*256));
+    p1k[3] = (unsigned int)(pbyTA[2] + (pbyTA[3]*256));
+    p1k[4] = (unsigned int)(pbyTA[4] + (pbyTA[5]*256));
+
+    /* Phase 1, step 2 */
+    for (i=0; i<8; i++) {
+        j = 2*(i & 1);
+        p1k[0] = (p1k[0] + tkip_sbox( (p1k[4] ^ ((256*pbyTKey[1+j]) + pbyTKey[j])) % 65536 )) % 65536;
+        p1k[1] = (p1k[1] + tkip_sbox( (p1k[0] ^ ((256*pbyTKey[5+j]) + pbyTKey[4+j])) % 65536 )) % 65536;
+        p1k[2] = (p1k[2] + tkip_sbox( (p1k[1] ^ ((256*pbyTKey[9+j]) + pbyTKey[8+j])) % 65536 )) % 65536;
+        p1k[3] = (p1k[3] + tkip_sbox( (p1k[2] ^ ((256*pbyTKey[13+j]) + pbyTKey[12+j])) % 65536 )) % 65536;
+        p1k[4] = (p1k[4] + tkip_sbox( (p1k[3] ^ (((256*pbyTKey[1+j]) + pbyTKey[j]))) % 65536 )) % 65536;
+        p1k[4] = (p1k[4] + i) % 65536;
+    }
+    /* Phase 2, Step 1 */
+    ppk0 = p1k[0];
+    ppk1 = p1k[1];
+    ppk2 = p1k[2];
+    ppk3 = p1k[3];
+    ppk4 = p1k[4];
+    ppk5 = (p1k[4] + tsc2) % 65536;
+
+    /* Phase2, Step 2 */
+    ppk0 = ppk0 + tkip_sbox( (ppk5 ^ ((256*pbyTKey[1]) + pbyTKey[0])) % 65536);
+    ppk1 = ppk1 + tkip_sbox( (ppk0 ^ ((256*pbyTKey[3]) + pbyTKey[2])) % 65536);
+    ppk2 = ppk2 + tkip_sbox( (ppk1 ^ ((256*pbyTKey[5]) + pbyTKey[4])) % 65536);
+    ppk3 = ppk3 + tkip_sbox( (ppk2 ^ ((256*pbyTKey[7]) + pbyTKey[6])) % 65536);
+    ppk4 = ppk4 + tkip_sbox( (ppk3 ^ ((256*pbyTKey[9]) + pbyTKey[8])) % 65536);
+    ppk5 = ppk5 + tkip_sbox( (ppk4 ^ ((256*pbyTKey[11]) + pbyTKey[10])) % 65536);
+
+    ppk0 = ppk0 + rotr1(ppk5 ^ ((256*pbyTKey[13]) + pbyTKey[12]));
+    ppk1 = ppk1 + rotr1(ppk0 ^ ((256*pbyTKey[15]) + pbyTKey[14]));
+    ppk2 = ppk2 + rotr1(ppk1);
+    ppk3 = ppk3 + rotr1(ppk2);
+    ppk4 = ppk4 + rotr1(ppk3);
+    ppk5 = ppk5 + rotr1(ppk4);
+
+    /* Phase 2, Step 3 */
+    pbyRC4Key[0] = (tsc2 >> 8) % 256;
+    pbyRC4Key[1] = (((tsc2 >> 8) % 256) | 0x20) & 0x7f;
+    pbyRC4Key[2] = tsc2 % 256;
+    pbyRC4Key[3] = ((ppk5 ^ ((256*pbyTKey[1]) + pbyTKey[0])) >> 1) % 256;
+
+    pbyRC4Key[4] = ppk0 % 256;
+    pbyRC4Key[5] = (ppk0 >> 8) % 256;
+
+    pbyRC4Key[6] = ppk1 % 256;
+    pbyRC4Key[7] = (ppk1 >> 8) % 256;
+
+    pbyRC4Key[8] = ppk2 % 256;
+    pbyRC4Key[9] = (ppk2 >> 8) % 256;
+
+    pbyRC4Key[10] = ppk3 % 256;
+    pbyRC4Key[11] = (ppk3 >> 8) % 256;
+
+    pbyRC4Key[12] = ppk4 % 256;
+    pbyRC4Key[13] = (ppk4 >> 8) % 256;
+
+    pbyRC4Key[14] = ppk5 % 256;
+    pbyRC4Key[15] = (ppk5 >> 8) % 256;
+}
diff --git a/drivers/staging/vt6655/tkip.h b/drivers/staging/vt6655/tkip.h
new file mode 100644
index 0000000..dc8382b
--- /dev/null
+++ b/drivers/staging/vt6655/tkip.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: tkip.h
+ *
+ * Purpose: Implement functions for 802.11i TKIP
+ *
+ * Author: Jerry Chen
+ *
+ * Date: Mar. 11, 2003
+ *
+ */
+
+
+#ifndef __TKIP_H__
+#define __TKIP_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+#define TKIP_KEY_LEN        16
+
+/*---------------------  Export Types  ------------------------------*/
+
+/*---------------------  Export Macros ------------------------------*/
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+VOID TKIPvMixKey(
+    PBYTE   pbyTKey,
+    PBYTE   pbyTA,
+    WORD    wTSC15_0,
+    DWORD   dwTSC47_16,
+    PBYTE   pbyRC4Key
+    );
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+#endif // __TKIP_H__
+
+
+
diff --git a/drivers/staging/vt6655/tmacro.h b/drivers/staging/vt6655/tmacro.h
new file mode 100644
index 0000000..3d932a2
--- /dev/null
+++ b/drivers/staging/vt6655/tmacro.h
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: tmacro.h
+ *
+ * Purpose: define basic common types and macros
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ *
+ */
+
+
+#ifndef __TMACRO_H__
+#define __TMACRO_H__
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+
+
+/****** Common helper macros ***********************************************/
+
+#if !defined(LONIBBLE)
+#define LONIBBLE(b)         ((BYTE)(b) & 0x0F)
+#endif
+#if !defined(HINIBBLE)
+#define HINIBBLE(b)         ((BYTE)(((WORD)(b) >> 4) & 0x0F))
+#endif
+
+#if !defined(LOBYTE)
+#define LOBYTE(w)           ((BYTE)(w))
+#endif
+#if !defined(HIBYTE)
+#define HIBYTE(w)           ((BYTE)(((WORD)(w) >> 8) & 0xFF))
+#endif
+
+#if !defined(LOWORD)
+#define LOWORD(d)           ((WORD)(d))
+#endif
+#if !defined(HIWORD)
+#define HIWORD(d)           ((WORD)((((DWORD)(d)) >> 16) & 0xFFFF))
+#endif
+
+#define LODWORD(q)          ((q).u.dwLowDword)
+#define HIDWORD(q)          ((q).u.dwHighDword)
+
+
+
+#if !defined(MAKEBYTE)
+#define MAKEBYTE(ln, hn)    ((BYTE)(((BYTE)(ln) & 0x0F) | ((BYTE)(hn) << 4)))
+#endif
+#if !defined(MAKEWORD)
+#define MAKEWORD(lb, hb)    ((WORD)(((BYTE)(lb)) | (((WORD)((BYTE)(hb))) << 8)))
+#endif
+#if !defined(MAKEDWORD)
+#define MAKEDWORD(lw, hw)   ((DWORD)(((WORD)(lw)) | (((DWORD)((WORD)(hw))) << 16)))
+#endif
+#if !defined(MAKEQWORD)
+#define MAKEQWORD(ld, hd, pq) {pq->u.dwLowDword = ld; pq->u.dwHighDword = hd;}
+#endif
+
+#if !defined(MAKELONG)
+#define MAKELONG(low, high) ((LONG)(((WORD)(low)) | (((DWORD)((WORD)(high))) << 16)))
+#endif
+
+
+
+// Bytes Reverse: big endian to little endian convert
+#if !defined(REVWORD)
+#define REVWORD(w) ((WORD)( ((WORD)(w) >> 8) | ((WORD)(w) << 8) ))
+#endif
+#if !defined(REVDWORD)
+#define REVDWORD(d) (MAKEDWORD(MAKEWORD(HIBYTE(HIWORD(d)),LOBYTE(HIWORD(d))),MAKEWORD(HIBYTE(LOWORD(d)),LOBYTE(LOWORD(d)))))
+#endif
+
+/* map to known network names */
+/*
+#define ntohs(x)        REVWORD(x)
+#define ntohl(x)        REVDWORD(x)
+#define htons(x)        REVWORD(x)
+#define htonl(x)        REVDWORD(x)
+*/
+
+
+/*
+#ifndef NOMINMAX
+#ifndef max
+#define max(a,b)            (((a) > (b)) ? (a) : (b))
+#endif
+#ifndef min
+#define min(a,b)            (((a) < (b)) ? (a) : (b))
+#endif
+#endif // NOMINMAX
+*/
+
+
+
+/****** Misc macros ********************************************************/
+
+// get the field offset in the type(struct, class, ...)
+#define OFFSET(type, field) ((int)(&((type NEAR*)1)->field)-1)
+
+
+/* string equality shorthand */
+#define STR_EQ(x, y)        (strcmp(x, y) == 0)
+#define STR_NE(x, y)        (strcmp(x, y) != 0)
+
+
+// calculate element # of array
+#define ELEMENT_NUM(array)  (sizeof(array) / sizeof(array[0]))
+//#define ARRAY_SIZE(a)       (sizeof(a) / sizeof(a[0]))
+
+
+// null statement
+#define NULL_FUNC()
+
+
+/* Since not all compilers support structure assignment, the ASSIGN()
+ * macro is used. This controls how it's actually implemented.
+ */
+#ifdef	NOSTRUCTASSIGN	/* Version for old compilers that don't support it */
+#define	ASSIGN(a,b)	memcpy((char *)&(a),(char *)&(b),sizeof(b);
+#else			/* Version for compilers that do */
+#define	ASSIGN(a,b)	((a) = (b))
+#endif
+
+
+
+
+#endif // __TMACRO_H__
+
+
diff --git a/drivers/staging/vt6655/tpci.h b/drivers/staging/vt6655/tpci.h
new file mode 100644
index 0000000..4a1c8ed
--- /dev/null
+++ b/drivers/staging/vt6655/tpci.h
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: tpci.h
+ *
+ * Purpose: PCI routines
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ *
+ */
+
+
+#ifndef __TPCI_H__
+#define __TPCI_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+#define MAX_PCI_BUS             4       // max. # of PCI bus that we support
+#define MAX_PCI_DEVICE          32      // max. # of PCI devices
+
+
+//
+// Registers in the PCI configuration space
+//
+#define PCI_REG_VENDOR_ID       0x00    //
+#define PCI_REG_DEVICE_ID       0x02    //
+#define PCI_REG_COMMAND         0x04    //
+#define PCI_REG_STATUS          0x06    //
+#define PCI_REG_REV_ID          0x08    //
+#define PCI_REG_CLASS_CODE      0x09    //
+#define PCI_REG_CACHELINE_SIZE  0x0C    //
+#define PCI_REG_LAT_TIMER       0x0D    //
+#define PCI_REG_HDR_TYPE        0x0E    //
+#define PCI_REG_BIST            0x0F    //
+
+#define PCI_REG_BAR0            0x10    //
+#define PCI_REG_BAR1            0x14    //
+#define PCI_REG_BAR2            0x18    //
+#define PCI_REG_CARDBUS_CIS_PTR 0x28    //
+
+#define PCI_REG_SUB_VEN_ID      0x2C    //
+#define PCI_REG_SUB_SYS_ID      0x2E    //
+#define PCI_REG_EXP_ROM_BAR     0x30    //
+#define PCI_REG_CAP             0x34    //
+
+#define PCI_REG_INT_LINE        0x3C    //
+#define PCI_REG_INT_PIN         0x3D    //
+#define PCI_REG_MIN_GNT         0x3E    //
+#define PCI_REG_MAX_LAT         0x3F    //
+
+#define PCI_REG_MAX_SIZE        0x100   // maximun total PCI registers
+
+
+//
+// Bits in the COMMAND register
+//
+#define COMMAND_BUSM        0x04        //
+#define COMMAND_WAIT        0x80        //
+
+/*---------------------  Export Types  ------------------------------*/
+
+/*---------------------  Export Macros ------------------------------*/
+
+// macro MAKE Bus Dev Fun ID into WORD
+#define MAKE_BDF_TO_WORD(byBusId, byDevId, byFunId) \
+    MAKEWORD(                                       \
+        ((((BYTE)(byDevId)) & 0x1F) << 3) +         \
+            (((BYTE)(byFunId)) & 0x07),             \
+        (byBusId)                                   \
+        )
+
+#define GET_BUSID(wBusDevFunId) \
+    HIBYTE(wBusDevFunId)
+
+#define GET_DEVID(wBusDevFunId) \
+    (LOBYTE(wBusDevFunId) >> 3)
+
+#define GET_FUNID(wBusDevFunId) \
+    (LOBYTE(wBusDevFunId) & 0x07)
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+
+#endif // __TPCI_H__
+
+
diff --git a/drivers/staging/vt6655/ttype.h b/drivers/staging/vt6655/ttype.h
new file mode 100644
index 0000000..1f26702
--- /dev/null
+++ b/drivers/staging/vt6655/ttype.h
@@ -0,0 +1,386 @@
+/*
+ * File: ttype.h
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Purpose: define basic common types and macros
+ *
+ * Author: Tevin Chen
+ *
+ * Date: May 21, 1996
+ *
+ */
+
+
+#ifndef __TTYPE_H__
+#define __TTYPE_H__
+
+
+/******* Common definitions and typedefs ***********************************/
+
+#ifndef VOID
+#define VOID            void
+#endif
+
+#ifndef CONST
+#define CONST           const
+#endif
+
+#ifndef STATIC
+#define STATIC          static
+#endif
+
+#ifndef IN
+#define IN
+#endif
+
+#ifndef OUT
+#define OUT
+#endif
+
+#ifndef TxInSleep
+#define TxInSleep
+#endif
+#if! defined(__CPU8051)
+typedef int             BOOL;
+#else   // __CPU8051
+#define BOOL            int
+#endif  // __CPU8051
+
+#if !defined(TRUE)
+#define TRUE            1
+#endif
+#if !defined(FALSE)
+#define FALSE           0
+#endif
+
+
+#if !defined(SUCCESS)
+#define SUCCESS         0
+#endif
+#if !defined(FAILED)
+#define FAILED          -1
+#endif
+
+//2007-0809-01<Add>by MikeLiu
+#ifndef  update_BssList
+#define update_BssList
+#endif
+
+
+
+#ifndef WPA_SM_Transtatus
+#define WPA_SM_Transtatus
+#endif
+
+#ifndef Calcu_LinkQual
+#define Calcu_LinkQual
+#endif
+
+#ifndef Calcu_LinkQual
+#define Calcu_LinkQual
+#endif
+
+/****** Simple typedefs  ***************************************************/
+
+#if! defined(__CPU8051)
+
+/* These lines assume that your compiler's longs are 32 bits and
+ * shorts are 16 bits. It is already assumed that chars are 8 bits,
+ * but it doesn't matter if they're signed or unsigned.
+ */
+
+typedef signed char             I8;     /* 8-bit signed integer */
+typedef signed short            I16;    /* 16-bit signed integer */
+typedef signed long             I32;    /* 32-bit signed integer */
+
+typedef unsigned char           U8;     /* 8-bit unsigned integer */
+typedef unsigned short          U16;    /* 16-bit unsigned integer */
+typedef unsigned long           U32;    /* 32-bit unsigned integer */
+
+
+#if defined(__WIN32)
+typedef signed __int64          I64;    /* 64-bit signed integer */
+typedef unsigned __int64        U64;    /* 64-bit unsigned integer */
+#endif // __WIN32
+
+
+typedef char            CHAR;
+typedef signed short    SHORT;
+typedef signed int      INT;
+typedef signed long     LONG;
+
+typedef unsigned char   UCHAR;
+typedef unsigned short  USHORT;
+typedef unsigned int    UINT;
+typedef unsigned long   ULONG;
+typedef unsigned long long	ULONGLONG; //64 bit
+typedef unsigned long long	ULONGULONG;
+
+
+
+typedef unsigned char   BYTE;           //  8-bit
+typedef unsigned short  WORD;           // 16-bit
+typedef unsigned long   DWORD;          // 32-bit
+
+// QWORD is for those situation that we want
+// an 8-byte-aligned 8 byte long structure
+// which is NOT really a floating point number.
+typedef union tagUQuadWord {
+    struct {
+        DWORD   dwLowDword;
+        DWORD   dwHighDword;
+    } u;
+    double      DoNotUseThisField;
+} UQuadWord;
+typedef UQuadWord       QWORD;          // 64-bit
+
+
+
+#ifndef _TCHAR_DEFINED
+typedef char            TCHAR;
+typedef char*           PTCHAR;
+typedef unsigned char   TBYTE;
+typedef unsigned char*  PTBYTE;
+#define _TCHAR_DEFINED
+#endif
+
+#else   // __CPU8051
+
+#define U8              unsigned char
+#define U16             unsigned short
+#define U32             unsigned long
+
+#define USHORT          unsigned short
+#define UINT            unsigned int
+
+#define BYTE            unsigned char
+#define WORD            unsigned short
+#define DWORD           unsigned long
+
+
+#endif  // __CPU8051
+
+
+// maybe this should be defined in <limits.h>
+#define U8_MAX          0xFFU
+#define U16_MAX         0xFFFFU
+#define U32_MAX         0xFFFFFFFFUL
+
+#define BYTE_MAX        0xFFU
+#define WORD_MAX        0xFFFFU
+#define DWORD_MAX       0xFFFFFFFFUL
+
+
+
+
+/******* 32-bit vs. 16-bit definitions and typedefs ************************/
+
+#if !defined(NULL)
+#ifdef __cplusplus
+#define NULL            0
+#else
+#define NULL            ((void *)0)
+#endif // __cplusplus
+#endif // !NULL
+
+
+
+
+#if defined(__WIN32) || defined(__CPU8051)
+
+#if !defined(FAR)
+#define FAR
+#endif
+#if !defined(NEAR)
+#define NEAR
+#endif
+#if !defined(DEF)
+#define DEF
+#endif
+#if !defined(CALLBACK)
+#define CALLBACK
+#endif
+
+#else  // !__WIN32__
+
+#if !defined(FAR)
+#define FAR
+#endif
+#if !defined(NEAR)
+#define NEAR
+#endif
+#if !defined(DEF)
+// default pointer type is FAR, if you want near pointer just redefine it to NEAR
+#define DEF
+#endif
+#if !defined(CALLBACK)
+#define CALLBACK
+#endif
+
+#endif // !__WIN32__
+
+
+
+
+/****** Common pointer types ***********************************************/
+
+#if! defined(__CPU8051)
+
+typedef signed char DEF*        PI8;
+typedef signed short DEF*       PI16;
+typedef signed long DEF*        PI32;
+
+typedef unsigned char DEF*      PU8;
+typedef unsigned short DEF*     PU16;
+typedef unsigned long DEF*      PU32;
+
+#if defined(__WIN32)
+typedef signed __int64 DEF*     PI64;
+typedef unsigned __int64 DEF*   PU64;
+#endif // __WIN32
+
+#if !defined(_WIN64)
+typedef unsigned long   ULONG_PTR;      // 32-bit
+typedef unsigned long   DWORD_PTR;      // 32-bit
+#endif // _WIN64
+
+
+// boolean pointer
+typedef int DEF*            PBOOL;
+typedef int NEAR*           NPBOOL;
+typedef int FAR*            LPBOOL;
+
+typedef int DEF*            PINT;
+typedef int NEAR*           NPINT;
+typedef int FAR*            LPINT;
+typedef const int DEF*      PCINT;
+typedef const int NEAR*     NPCINT;
+typedef const int FAR*      LPCINT;
+
+typedef unsigned int DEF*           PUINT;
+typedef const unsigned int DEF*     PCUINT;
+
+typedef long DEF*           PLONG;
+typedef long NEAR*          NPLONG;
+typedef long FAR*           LPLONG;
+//typedef const long DEF*     PCLONG;
+typedef const long NEAR*    NPCLONG;
+typedef const long FAR*     LPCLONG;
+
+typedef BYTE DEF*           PBYTE;
+typedef BYTE NEAR*          NPBYTE;
+typedef BYTE FAR*           LPBYTE;
+typedef const BYTE DEF*     PCBYTE;
+typedef const BYTE NEAR*    NPCBYTE;
+typedef const BYTE FAR*     LPCBYTE;
+
+typedef WORD DEF*           PWORD;
+typedef WORD NEAR*          NPWORD;
+typedef WORD FAR*           LPWORD;
+typedef const WORD DEF*     PCWORD;
+typedef const WORD NEAR*    NPCWORD;
+typedef const WORD FAR*     LPCWORD;
+
+typedef DWORD DEF*          PDWORD;
+typedef DWORD NEAR*         NPDWORD;
+typedef DWORD FAR*          LPDWORD;
+typedef const DWORD DEF*    PCDWORD;
+typedef const DWORD NEAR*   NPCDWORD;
+typedef const DWORD FAR*    LPCDWORD;
+
+typedef QWORD DEF*          PQWORD;
+typedef QWORD NEAR*         NPQWORD;
+typedef QWORD FAR*          LPQWORD;
+typedef const QWORD DEF*    PCQWORD;
+typedef const QWORD NEAR*   NPCQWORD;
+typedef const QWORD FAR*    LPCQWORD;
+
+typedef void DEF*           PVOID;
+typedef void NEAR*          NPVOID;
+typedef void FAR*           LPVOID;
+
+// handle declaration
+#ifdef STRICT
+typedef void *HANDLE;
+#else
+typedef PVOID HANDLE;
+#endif
+
+//
+// ANSI (Single-byte Character) types
+//
+typedef char DEF*           PCH;
+typedef char NEAR*          NPCH;
+typedef char FAR*           LPCH;
+typedef const char DEF*     PCCH;
+typedef const char NEAR*    NPCCH;
+typedef const char FAR*     LPCCH;
+
+typedef char DEF*           PSTR;
+typedef char NEAR*          NPSTR;
+typedef char FAR*           LPSTR;
+typedef const char DEF*     PCSTR;
+typedef const char NEAR*    NPCSTR;
+typedef const char FAR*     LPCSTR;
+
+#endif  // !__CPU8051
+
+
+
+
+/****** Misc definitions, types ********************************************/
+
+// parameter prefix
+#ifndef IN
+#define IN
+#endif
+
+#ifndef OUT
+#define OUT
+#endif
+
+
+// unreferenced parameter macro to avoid warning message in MS C
+#if defined(__TURBOC__)
+
+//you should use "#pragma argsused" to avoid warning message in Borland C
+#ifndef UNREFERENCED_PARAMETER
+#define UNREFERENCED_PARAMETER(x)
+#endif
+
+#else
+
+#ifndef UNREFERENCED_PARAMETER
+//#define UNREFERENCED_PARAMETER(x) x
+#define UNREFERENCED_PARAMETER(x)
+#endif
+
+#endif
+
+
+// in-line assembly prefix
+#if defined(__TURBOC__)
+#define ASM             asm
+#else  // !__TURBOC__
+#define ASM             _asm
+#endif // !__TURBOC__
+
+
+
+
+#endif // __TTYPE_H__
+
+
diff --git a/drivers/staging/vt6655/umem.h b/drivers/staging/vt6655/umem.h
new file mode 100644
index 0000000..2c3eafa
--- /dev/null
+++ b/drivers/staging/vt6655/umem.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: umem.h
+ *
+ * Purpose: Define Memory macros
+ *
+ * Author: Tevin Chen
+ *
+ * Date: Mar 17, 1997
+ *
+ */
+
+
+#ifndef __UMEM_H__
+#define __UMEM_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+// 4-byte memory tag
+#define MEM_TAG 'mTEW'
+
+// Macros used for memory allocation and deallocation.
+
+
+
+#define ZERO_MEMORY(Destination,Length) {       \
+            memset((PVOID)(Destination),        \
+            0,                                  \
+            (ULONG)(Length)                     \
+            );                                  \
+}
+
+#define MEMvCopy(pvDest, pvSource, uCount) {    \
+            memcpy((PVOID)(pvDest),             \
+            (PVOID)(pvSource),                  \
+            (ULONG)(uCount)                     \
+            );                                  \
+}
+
+
+#define MEMEqualMemory(Destination,Source,Length)   (!memcmp((Destination),(Source),(Length)))
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+
+#endif // __UMEM_H__
+
+
diff --git a/drivers/staging/vt6655/upc.h b/drivers/staging/vt6655/upc.h
new file mode 100644
index 0000000..113fc2c
--- /dev/null
+++ b/drivers/staging/vt6655/upc.h
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: upc.h
+ *
+ * Purpose: Macros to access device
+ *
+ * Author: Tevin Chen
+ *
+ * Date: Mar 17, 1997
+ *
+ */
+
+
+#ifndef __UPC_H__
+#define __UPC_H__
+
+#if !defined(DEVICE_H)
+#include "device.h"
+#endif
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+
+/*---------------------  Export Definitions -------------------------*/
+
+
+//
+//  For IO mapped
+//
+
+#ifdef IO_MAP
+
+#define VNSvInPortB(dwIOAddress, pbyData) {                     \
+	*(pbyData) = inb(dwIOAddress);                              \
+}
+
+
+#define VNSvInPortW(dwIOAddress, pwData) {                      \
+	    *(pwData) = inw(dwIOAddress);                           \
+}
+
+#define VNSvInPortD(dwIOAddress, pdwData) {                     \
+	    *(pdwData) = inl(dwIOAddress);                          \
+}
+
+
+#define VNSvOutPortB(dwIOAddress, byData) {                     \
+        outb(byData, dwIOAddress);                              \
+}
+
+
+#define VNSvOutPortW(dwIOAddress, wData) {                      \
+        outw(wData, dwIOAddress);                               \
+}
+
+#define VNSvOutPortD(dwIOAddress, dwData) {                     \
+        outl(dwData, dwIOAddress);                              \
+}
+
+#else
+
+//
+//  For memory mapped IO
+//
+
+
+#define VNSvInPortB(dwIOAddress, pbyData) {                     \
+	volatile BYTE* pbyAddr = ((PBYTE)(dwIOAddress));            \
+	*(pbyData) = readb(pbyAddr);                           \
+}
+
+
+#define VNSvInPortW(dwIOAddress, pwData) {                      \
+	volatile WORD* pwAddr = ((PWORD)(dwIOAddress));             \
+	*(pwData) = readw(pwAddr);                             \
+}
+
+#define VNSvInPortD(dwIOAddress, pdwData) {                     \
+	volatile DWORD* pdwAddr = ((PDWORD)(dwIOAddress));          \
+	*(pdwData) = readl(pdwAddr);                           \
+}
+
+
+#define VNSvOutPortB(dwIOAddress, byData) {                     \
+    volatile BYTE* pbyAddr = ((PBYTE)(dwIOAddress));            \
+    writeb((BYTE)byData, pbyAddr);							\
+}
+
+
+#define VNSvOutPortW(dwIOAddress, wData) {                      \
+    volatile WORD* pwAddr = ((PWORD)(dwIOAddress));             \
+    writew((WORD)wData, pwAddr);							\
+}
+
+#define VNSvOutPortD(dwIOAddress, dwData) {                     \
+    volatile DWORD* pdwAddr = ((PDWORD)(dwIOAddress));          \
+    writel((DWORD)dwData, pdwAddr);					    \
+}
+
+#endif
+
+
+//
+// ALWAYS IO-Mapped IO when in 16-bit/32-bit environment
+//
+#define PCBvInPortB(dwIOAddress, pbyData) {     \
+	    *(pbyData) = inb(dwIOAddress);          \
+}
+
+#define PCBvInPortW(dwIOAddress, pwData) {      \
+	    *(pwData) = inw(dwIOAddress);           \
+}
+
+#define PCBvInPortD(dwIOAddress, pdwData) {     \
+	    *(pdwData) = inl(dwIOAddress);          \
+}
+
+#define PCBvOutPortB(dwIOAddress, byData) {     \
+        outb(byData, dwIOAddress);              \
+}
+
+#define PCBvOutPortW(dwIOAddress, wData) {      \
+        outw(wData, dwIOAddress);               \
+}
+
+#define PCBvOutPortD(dwIOAddress, dwData) {     \
+        outl(dwData, dwIOAddress);              \
+}
+
+
+#define PCAvDelayByIO(uDelayUnit) {             \
+    BYTE    byData;                             \
+    ULONG   ii;                                 \
+                                                \
+    if (uDelayUnit <= 50) {                     \
+        udelay(uDelayUnit);                     \
+    }                                           \
+    else {                                      \
+        for (ii = 0; ii < (uDelayUnit); ii++)   \
+		     byData = inb(0x61);				\
+    }                                           \
+}
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+
+
+#endif // __UPC_H__
+
diff --git a/drivers/staging/vt6655/vntconfiguration.dat b/drivers/staging/vt6655/vntconfiguration.dat
new file mode 100644
index 0000000..0064ddc
--- /dev/null
+++ b/drivers/staging/vt6655/vntconfiguration.dat
@@ -0,0 +1 @@
+ZONETYPE=EUROPE
\ No newline at end of file
diff --git a/drivers/staging/vt6655/vntwifi.c b/drivers/staging/vt6655/vntwifi.c
new file mode 100644
index 0000000..58a1ba0e
--- /dev/null
+++ b/drivers/staging/vt6655/vntwifi.c
@@ -0,0 +1,832 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: vntwifi.c
+ *
+ * Purpose: export functions for vntwifi lib
+ *
+ * Functions:
+ *
+ * Revision History:
+ *
+ * Author: Yiching Chen
+ *
+ * Date: feb. 2, 2005
+ *
+ */
+
+#if !defined(__VNTWIFI_H__)
+#include "vntwifi.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+
+
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__IEEE11h_H__)
+#include "IEEE11h.h"
+#endif
+#if !defined(__COUNTRY_H__)
+#include "country.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__WMGR_H__)
+#include "wmgr.h"
+#endif
+#if !defined(__DATARATE_H__)
+#include "datarate.h"
+#endif
+//#define	PLICE_DEBUG
+
+/*---------------------  Static Definitions -------------------------*/
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+//static int          msglevel                =MSG_LEVEL_INFO;
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+/*+
+ *
+ * Description:
+ *    Set Operation Mode
+ *
+ * Parameters:
+ *  In:
+ *      pMgmtHandle - pointer to management object
+ *      eOPMode     - Opreation Mode
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+-*/
+VOID
+VNTWIFIvSetOPMode (
+    IN PVOID pMgmtHandle,
+    IN WMAC_CONFIG_MODE eOPMode
+    )
+{
+    PSMgmtObject        pMgmt = (PSMgmtObject)pMgmtHandle;
+
+    pMgmt->eConfigMode = eOPMode;
+}
+
+
+/*+
+ *
+ * Description:
+ *    Set Operation Mode
+ *
+ * Parameters:
+ *  In:
+ *      pMgmtHandle - pointer to management object
+ *      wBeaconPeriod - Beacon Period
+ *      wATIMWindow - ATIM window
+ *      uChannel - channel number
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+-*/
+VOID
+VNTWIFIvSetIBSSParameter (
+    IN PVOID pMgmtHandle,
+    IN WORD  wBeaconPeriod,
+    IN WORD  wATIMWindow,
+    IN UINT  uChannel
+    )
+{
+    PSMgmtObject        pMgmt = (PSMgmtObject)pMgmtHandle;
+
+    pMgmt->wIBSSBeaconPeriod = wBeaconPeriod;
+    pMgmt->wIBSSATIMWindow = wATIMWindow;
+    pMgmt->uIBSSChannel = uChannel;
+}
+
+/*+
+ *
+ * Description:
+ *    Get current SSID
+ *
+ * Parameters:
+ *  In:
+ *      pMgmtHandle - pointer to management object
+ *  Out:
+ *      none
+ *
+ * Return Value: current SSID pointer.
+ *
+-*/
+PWLAN_IE_SSID
+VNTWIFIpGetCurrentSSID (
+    IN PVOID pMgmtHandle
+    )
+{
+    PSMgmtObject        pMgmt = (PSMgmtObject)pMgmtHandle;
+    return((PWLAN_IE_SSID) pMgmt->abyCurrSSID);
+}
+
+/*+
+ *
+ * Description:
+ *    Get current link channel
+ *
+ * Parameters:
+ *  In:
+ *      pMgmtHandle - pointer to management object
+ *  Out:
+ *      none
+ *
+ * Return Value: current Channel.
+ *
+-*/
+UINT
+VNTWIFIpGetCurrentChannel (
+    IN PVOID pMgmtHandle
+    )
+{
+    PSMgmtObject        pMgmt = (PSMgmtObject)pMgmtHandle;
+    if (pMgmtHandle != NULL) {
+        return (pMgmt->uCurrChannel);
+    }
+    return 0;
+}
+
+/*+
+ *
+ * Description:
+ *    Get current Assoc ID
+ *
+ * Parameters:
+ *  In:
+ *      pMgmtHandle - pointer to management object
+ *  Out:
+ *      none
+ *
+ * Return Value: current Assoc ID
+ *
+-*/
+WORD
+VNTWIFIwGetAssocID (
+    IN PVOID pMgmtHandle
+    )
+{
+    PSMgmtObject        pMgmt = (PSMgmtObject)pMgmtHandle;
+    return(pMgmt->wCurrAID);
+}
+
+
+
+/*+
+ *
+ * Description:
+ *    This routine return max support rate of IES
+ *
+ * Parameters:
+ *  In:
+ *      pSupportRateIEs
+ *      pExtSupportRateIEs
+ *
+ *  Out:
+ *
+ * Return Value: max support rate
+ *
+-*/
+BYTE
+VNTWIFIbyGetMaxSupportRate (
+    IN PWLAN_IE_SUPP_RATES pSupportRateIEs,
+    IN PWLAN_IE_SUPP_RATES pExtSupportRateIEs
+    )
+{
+    BYTE    byMaxSupportRate = RATE_1M;
+    BYTE    bySupportRate = RATE_1M;
+    UINT    ii = 0;
+
+    if (pSupportRateIEs) {
+        for (ii = 0; ii < pSupportRateIEs->len; ii++) {
+            bySupportRate = DATARATEbyGetRateIdx(pSupportRateIEs->abyRates[ii]);
+            if (bySupportRate > byMaxSupportRate) {
+                byMaxSupportRate = bySupportRate;
+            }
+        }
+    }
+    if (pExtSupportRateIEs) {
+        for (ii = 0; ii < pExtSupportRateIEs->len; ii++) {
+            bySupportRate = DATARATEbyGetRateIdx(pExtSupportRateIEs->abyRates[ii]);
+            if (bySupportRate > byMaxSupportRate) {
+                byMaxSupportRate = bySupportRate;
+            }
+        }
+    }
+
+    return byMaxSupportRate;
+}
+
+/*+
+ *
+ * Description:
+ *    This routine return data rate of ACK packtet
+ *
+ * Parameters:
+ *  In:
+ *      byRxDataRate
+ *      pSupportRateIEs
+ *      pExtSupportRateIEs
+ *
+ *  Out:
+ *
+ * Return Value: max support rate
+ *
+-*/
+BYTE
+VNTWIFIbyGetACKTxRate (
+    IN BYTE byRxDataRate,
+    IN PWLAN_IE_SUPP_RATES pSupportRateIEs,
+    IN PWLAN_IE_SUPP_RATES pExtSupportRateIEs
+    )
+{
+    BYTE    byMaxAckRate;
+    BYTE    byBasicRate;
+    UINT    ii;
+
+    if (byRxDataRate <= RATE_11M) {
+        byMaxAckRate = RATE_1M;
+    } else  {
+        // 24M is mandatory for 802.11a and 802.11g
+        byMaxAckRate = RATE_24M;
+    }
+    if (pSupportRateIEs) {
+        for (ii = 0; ii < pSupportRateIEs->len; ii++) {
+            if (pSupportRateIEs->abyRates[ii] & 0x80) {
+                byBasicRate = DATARATEbyGetRateIdx(pSupportRateIEs->abyRates[ii]);
+                if ((byBasicRate <= byRxDataRate) &&
+                    (byBasicRate > byMaxAckRate))  {
+                    byMaxAckRate = byBasicRate;
+                }
+            }
+        }
+    }
+    if (pExtSupportRateIEs) {
+        for (ii = 0; ii < pExtSupportRateIEs->len; ii++) {
+            if (pExtSupportRateIEs->abyRates[ii] & 0x80) {
+                byBasicRate = DATARATEbyGetRateIdx(pExtSupportRateIEs->abyRates[ii]);
+                if ((byBasicRate <= byRxDataRate) &&
+                    (byBasicRate > byMaxAckRate))  {
+                    byMaxAckRate = byBasicRate;
+                }
+            }
+        }
+    }
+
+    return byMaxAckRate;
+}
+
+/*+
+ *
+ * Description:
+ *    Set Authentication Mode
+ *
+ * Parameters:
+ *  In:
+ *      pMgmtHandle - pointer to management object
+ *      eAuthMode   - Authentication mode
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+-*/
+VOID
+VNTWIFIvSetAuthenticationMode (
+    IN PVOID pMgmtHandle,
+    IN WMAC_AUTHENTICATION_MODE eAuthMode
+    )
+{
+    PSMgmtObject        pMgmt = (PSMgmtObject)pMgmtHandle;
+
+    pMgmt->eAuthenMode = eAuthMode;
+    if ((eAuthMode == WMAC_AUTH_SHAREKEY) ||
+        (eAuthMode == WMAC_AUTH_AUTO)) {
+        pMgmt->bShareKeyAlgorithm = TRUE;
+    } else {
+        pMgmt->bShareKeyAlgorithm = FALSE;
+    }
+}
+
+/*+
+ *
+ * Description:
+ *    Set Encryption Mode
+ *
+ * Parameters:
+ *  In:
+ *      pMgmtHandle - pointer to management object
+ *      eAuthMode   - Authentication mode
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+-*/
+VOID
+VNTWIFIvSetEncryptionMode (
+    IN PVOID pMgmtHandle,
+    IN WMAC_ENCRYPTION_MODE eEncryptionMode
+    )
+{
+    PSMgmtObject        pMgmt = (PSMgmtObject)pMgmtHandle;
+
+    pMgmt->eEncryptionMode = eEncryptionMode;
+    if ((eEncryptionMode == WMAC_ENCRYPTION_WEPEnabled) ||
+        (eEncryptionMode == WMAC_ENCRYPTION_TKIPEnabled) ||
+        (eEncryptionMode == WMAC_ENCRYPTION_AESEnabled) ) {
+        pMgmt->bPrivacyInvoked = TRUE;
+    } else {
+        pMgmt->bPrivacyInvoked = FALSE;
+    }
+}
+
+
+
+BOOL
+VNTWIFIbConfigPhyMode (
+    IN PVOID pMgmtHandle,
+    IN CARD_PHY_TYPE ePhyType
+    )
+{
+    PSMgmtObject        pMgmt = (PSMgmtObject)pMgmtHandle;
+
+    if ((ePhyType != PHY_TYPE_AUTO) &&
+        (ePhyType != pMgmt->eCurrentPHYMode)) {
+        if (CARDbSetPhyParameter(pMgmt->pAdapter, ePhyType, 0, 0, NULL, NULL)==TRUE) {
+            pMgmt->eCurrentPHYMode = ePhyType;
+        } else {
+            return(FALSE);
+        }
+    }
+    pMgmt->eConfigPHYMode = ePhyType;
+    return(TRUE);
+}
+
+
+VOID
+VNTWIFIbGetConfigPhyMode (
+    IN  PVOID pMgmtHandle,
+    OUT PVOID pePhyType
+    )
+{
+    PSMgmtObject        pMgmt = (PSMgmtObject)pMgmtHandle;
+
+    if ((pMgmt != NULL) && (pePhyType != NULL)) {
+        *(PCARD_PHY_TYPE)pePhyType = pMgmt->eConfigPHYMode;
+    }
+}
+
+/*+
+ *
+ * Description:
+ *      Clear BSS List Database except current assoc BSS
+ *
+ * Parameters:
+ *  In:
+ *      pMgmtHandle     - Management Object structure
+ *      bLinkPass       - Current Link status
+ *  Out:
+ *
+ * Return Value: None.
+ *
+-*/
+
+
+/*+
+ *
+ * Description:
+ *      Query BSS List in management database
+ *
+ * Parameters:
+ *  In:
+ *      pMgmtHandle     - Management Object structure
+ *  Out:
+ *      puBSSCount      - BSS count
+ *      pvFirstBSS      - pointer to first BSS
+ *
+ * Return Value: None.
+ *
+-*/
+
+VOID
+VNTWIFIvQueryBSSList (
+    IN PVOID    pMgmtHandle,
+    OUT PUINT   puBSSCount,
+    OUT PVOID   *pvFirstBSS
+    )
+{
+    UINT            ii = 0;
+    PSMgmtObject    pMgmt = (PSMgmtObject)pMgmtHandle;
+    PKnownBSS       pBSS = NULL;
+    UINT            uCount = 0;
+
+    *pvFirstBSS = NULL;
+
+    for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+        pBSS = &(pMgmt->sBSSList[ii]);
+        if (!pBSS->bActive) {
+            continue;
+        }
+        if (*pvFirstBSS == NULL) {
+            *pvFirstBSS = &(pMgmt->sBSSList[ii]);
+        }
+        uCount++;
+    }
+    *puBSSCount = uCount;
+}
+
+
+
+
+VOID
+VNTWIFIvGetNextBSS (
+    IN PVOID            pMgmtHandle,
+    IN PVOID            pvCurrentBSS,
+    OUT PVOID           *pvNextBSS
+    )
+{
+    PKnownBSS       pBSS = (PKnownBSS) pvCurrentBSS;
+    PSMgmtObject    pMgmt = (PSMgmtObject)pMgmtHandle;
+
+    *pvNextBSS = NULL;
+
+    while (*pvNextBSS == NULL) {
+        pBSS++;
+        if (pBSS > &(pMgmt->sBSSList[MAX_BSS_NUM])) {
+            return;
+        }
+        if (pBSS->bActive == TRUE) {
+            *pvNextBSS = pBSS;
+            return;
+        }
+    }
+}
+
+
+
+
+
+/*+
+ *
+ * Description:
+ *      Update Tx attemps, Tx failure counter in Node DB
+ *
+ *  In:
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+-*/
+VOID
+VNTWIFIvUpdateNodeTxCounter(
+    IN PVOID    pMgmtHandle,
+    IN PBYTE    pbyDestAddress,
+    IN BOOL     bTxOk,
+    IN WORD     wRate,
+    IN PBYTE    pbyTxFailCount
+    )
+{
+    PSMgmtObject    pMgmt = (PSMgmtObject)pMgmtHandle;
+    UINT            uNodeIndex = 0;
+    UINT            ii;
+
+    if ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) ||
+        (pMgmt->eCurrMode == WMAC_MODE_ESS_AP)) {
+        if (BSSDBbIsSTAInNodeDB(pMgmt, pbyDestAddress, &uNodeIndex) == FALSE) {
+            return;
+        }
+    }
+    pMgmt->sNodeDBTable[uNodeIndex].uTxAttempts++;
+    if (bTxOk == TRUE) {
+        // transmit success, TxAttempts at least plus one
+        pMgmt->sNodeDBTable[uNodeIndex].uTxOk[MAX_RATE]++;
+        pMgmt->sNodeDBTable[uNodeIndex].uTxOk[wRate]++;
+    } else {
+        pMgmt->sNodeDBTable[uNodeIndex].uTxFailures++;
+    }
+    pMgmt->sNodeDBTable[uNodeIndex].uTxRetry += pbyTxFailCount[MAX_RATE];
+    for(ii=0;ii<MAX_RATE;ii++) {
+        pMgmt->sNodeDBTable[uNodeIndex].uTxFail[ii] += pbyTxFailCount[ii];
+    }
+    return;
+}
+
+
+VOID
+VNTWIFIvGetTxRate(
+    IN PVOID    pMgmtHandle,
+    IN PBYTE    pbyDestAddress,
+    OUT PWORD   pwTxDataRate,
+    OUT PBYTE   pbyACKRate,
+    OUT PBYTE   pbyCCKBasicRate,
+    OUT PBYTE   pbyOFDMBasicRate
+    )
+{
+    PSMgmtObject        pMgmt = (PSMgmtObject)pMgmtHandle;
+    UINT                uNodeIndex = 0;
+    WORD                wTxDataRate = RATE_1M;
+    BYTE                byACKRate = RATE_1M;
+    BYTE                byCCKBasicRate = RATE_1M;
+    BYTE                byOFDMBasicRate = RATE_24M;
+    PWLAN_IE_SUPP_RATES pSupportRateIEs = NULL;
+    PWLAN_IE_SUPP_RATES pExtSupportRateIEs = NULL;
+
+
+    if ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) ||
+        (pMgmt->eCurrMode == WMAC_MODE_ESS_AP)) {
+        // Adhoc Tx rate decided from node DB
+        if(BSSDBbIsSTAInNodeDB(pMgmt, pbyDestAddress, &uNodeIndex)) {
+            wTxDataRate = (pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate);
+            pSupportRateIEs = (PWLAN_IE_SUPP_RATES) (pMgmt->sNodeDBTable[uNodeIndex].abyCurrSuppRates);
+            pExtSupportRateIEs = (PWLAN_IE_SUPP_RATES) (pMgmt->sNodeDBTable[uNodeIndex].abyCurrExtSuppRates);
+        } else {
+            if (pMgmt->eCurrentPHYMode != PHY_TYPE_11A) {
+                wTxDataRate = RATE_2M;
+            } else {
+                wTxDataRate = RATE_24M;
+            }
+            pSupportRateIEs = (PWLAN_IE_SUPP_RATES) pMgmt->abyCurrSuppRates;
+            pExtSupportRateIEs = (PWLAN_IE_SUPP_RATES) pMgmt->abyCurrExtSuppRates;
+        }
+    } else { // Infrastructure: rate decided from AP Node, index = 0
+
+		wTxDataRate = (pMgmt->sNodeDBTable[0].wTxDataRate);
+#ifdef	PLICE_DEBUG
+		printk("GetTxRate:AP MAC is %02x:%02x:%02x:%02x:%02x:%02x,TxRate is %d\n",
+				pMgmt->sNodeDBTable[0].abyMACAddr[0],pMgmt->sNodeDBTable[0].abyMACAddr[1],
+				pMgmt->sNodeDBTable[0].abyMACAddr[2],pMgmt->sNodeDBTable[0].abyMACAddr[3],
+				pMgmt->sNodeDBTable[0].abyMACAddr[4],pMgmt->sNodeDBTable[0].abyMACAddr[5],wTxDataRate);
+#endif
+
+
+        pSupportRateIEs = (PWLAN_IE_SUPP_RATES) pMgmt->abyCurrSuppRates;
+        pExtSupportRateIEs = (PWLAN_IE_SUPP_RATES) pMgmt->abyCurrExtSuppRates;
+    }
+    byACKRate = VNTWIFIbyGetACKTxRate(  (BYTE) wTxDataRate,
+                                        pSupportRateIEs,
+                                        pExtSupportRateIEs
+                                        );
+    if (byACKRate > (BYTE) wTxDataRate) {
+        byACKRate = (BYTE) wTxDataRate;
+    }
+    byCCKBasicRate = VNTWIFIbyGetACKTxRate( RATE_11M,
+                                            pSupportRateIEs,
+                                            pExtSupportRateIEs
+                                            );
+    byOFDMBasicRate = VNTWIFIbyGetACKTxRate(RATE_54M,
+                                            pSupportRateIEs,
+                                            pExtSupportRateIEs
+                                            );
+    *pwTxDataRate = wTxDataRate;
+    *pbyACKRate = byACKRate;
+    *pbyCCKBasicRate = byCCKBasicRate;
+    *pbyOFDMBasicRate = byOFDMBasicRate;
+    return;
+}
+
+BYTE
+VNTWIFIbyGetKeyCypher(
+    IN PVOID    pMgmtHandle,
+    IN BOOL     bGroupKey
+    )
+{
+    PSMgmtObject    pMgmt = (PSMgmtObject)pMgmtHandle;
+
+    if (bGroupKey == TRUE) {
+        return (pMgmt->byCSSGK);
+    } else {
+        return (pMgmt->byCSSPK);
+    }
+}
+
+
+/*
+BOOL
+VNTWIFIbInit(
+    IN PVOID    pAdapterHandler,
+    OUT PVOID   *pMgmtHandler
+    )
+{
+
+    PSMgmtObject        pMgmt = NULL;
+    UINT                ii;
+
+
+    pMgmt = (PSMgmtObject)kmalloc(sizeof(SMgmtObject), (int)GFP_ATOMIC);
+    if (pMgmt == NULL) {
+        *pMgmtHandler = NULL;
+        return FALSE;
+    }
+
+    memset(pMgmt, 0, sizeof(SMgmtObject));
+    pMgmt->pAdapter = (PVOID) pAdapterHandler;
+
+    // should initial MAC address abyMACAddr
+    for(ii=0;ii<WLAN_BSSID_LEN;ii++) {
+        pMgmt->abyDesireBSSID[ii] = 0xFF;
+    }
+    pMgmt->pbyPSPacketPool = &pMgmt->byPSPacketPool[0];
+    pMgmt->pbyMgmtPacketPool = &pMgmt->byMgmtPacketPool[0];
+    pMgmt->byCSSPK = KEY_CTL_NONE;
+    pMgmt->byCSSGK = KEY_CTL_NONE;
+    pMgmt->wIBSSBeaconPeriod = DEFAULT_IBSS_BI;
+
+    pMgmt->cbFreeCmdQueue = CMD_Q_SIZE;
+    pMgmt->uCmdDequeueIdx = 0;
+    pMgmt->uCmdEnqueueIdx = 0;
+    pMgmt->eCommandState = WLAN_CMD_STATE_IDLE;
+    pMgmt->bCmdStop = FALSE;
+    pMgmt->bCmdRunning = FALSE;
+
+    *pMgmtHandler = pMgmt;
+    return TRUE;
+}
+*/
+
+
+
+BOOL
+VNTWIFIbSetPMKIDCache (
+    IN PVOID pMgmtObject,
+    IN ULONG ulCount,
+    IN PVOID pPMKIDInfo
+    )
+{
+    PSMgmtObject    pMgmt = (PSMgmtObject) pMgmtObject;
+
+    if (ulCount > MAX_PMKID_CACHE) {
+        return (FALSE);
+    }
+    pMgmt->gsPMKIDCache.BSSIDInfoCount = ulCount;
+    MEMvCopy(pMgmt->gsPMKIDCache.BSSIDInfo, pPMKIDInfo, (ulCount*sizeof(PMKIDInfo)));
+    return (TRUE);
+}
+
+
+
+WORD
+VNTWIFIwGetMaxSupportRate(
+    IN PVOID pMgmtObject
+    )
+{
+    WORD wRate = RATE_54M;
+    PSMgmtObject    pMgmt = (PSMgmtObject) pMgmtObject;
+
+    for(wRate = RATE_54M; wRate > RATE_1M; wRate--) {
+        if (BITbIsBitOn(pMgmt->sNodeDBTable[0].wSuppRate, (1<<wRate))) {
+            return (wRate);
+        }
+    }
+    if (pMgmt->eCurrentPHYMode == PHY_TYPE_11A) {
+        return (RATE_6M);
+    } else {
+        return (RATE_1M);
+    }
+}
+
+
+VOID
+VNTWIFIvSet11h (
+    IN PVOID pMgmtObject,
+    IN BOOL  b11hEnable
+    )
+{
+    PSMgmtObject    pMgmt = (PSMgmtObject) pMgmtObject;
+
+    pMgmt->b11hEnable = b11hEnable;
+}
+
+BOOL
+VNTWIFIbMeasureReport(
+    IN PVOID pMgmtObject,
+    IN BOOL  bEndOfReport,
+    IN PVOID pvMeasureEID,
+    IN BYTE  byReportMode,
+    IN BYTE  byBasicMap,
+    IN BYTE  byCCAFraction,
+    IN PBYTE pbyRPIs
+    )
+{
+    PSMgmtObject    pMgmt = (PSMgmtObject) pMgmtObject;
+    PBYTE           pbyCurrentEID = (PBYTE) (pMgmt->pCurrMeasureEIDRep);
+
+    //spin_lock_irq(&pDevice->lock);
+    if ((pvMeasureEID != NULL) &&
+        (pMgmt->uLengthOfRepEIDs < (WLAN_A3FR_MAXLEN - sizeof(MEASEURE_REP) - sizeof(WLAN_80211HDR_A3) - 3))
+        ) {
+        pMgmt->pCurrMeasureEIDRep->byElementID = WLAN_EID_MEASURE_REP;
+        pMgmt->pCurrMeasureEIDRep->len = 3;
+        pMgmt->pCurrMeasureEIDRep->byToken = ((PWLAN_IE_MEASURE_REQ) pvMeasureEID)->byToken;
+        pMgmt->pCurrMeasureEIDRep->byMode = byReportMode;
+        pMgmt->pCurrMeasureEIDRep->byType = ((PWLAN_IE_MEASURE_REQ) pvMeasureEID)->byType;
+        switch (pMgmt->pCurrMeasureEIDRep->byType) {
+            case MEASURE_TYPE_BASIC :
+                pMgmt->pCurrMeasureEIDRep->len += sizeof(MEASEURE_REP_BASIC);
+                MEMvCopy(   &(pMgmt->pCurrMeasureEIDRep->sRep.sBasic),
+                            &(((PWLAN_IE_MEASURE_REQ) pvMeasureEID)->sReq),
+                            sizeof(MEASEURE_REQ));
+                pMgmt->pCurrMeasureEIDRep->sRep.sBasic.byMap = byBasicMap;
+                break;
+            case MEASURE_TYPE_CCA :
+                pMgmt->pCurrMeasureEIDRep->len += sizeof(MEASEURE_REP_CCA);
+                MEMvCopy(   &(pMgmt->pCurrMeasureEIDRep->sRep.sCCA),
+                            &(((PWLAN_IE_MEASURE_REQ) pvMeasureEID)->sReq),
+                            sizeof(MEASEURE_REQ));
+                pMgmt->pCurrMeasureEIDRep->sRep.sCCA.byCCABusyFraction = byCCAFraction;
+                break;
+            case MEASURE_TYPE_RPI :
+                pMgmt->pCurrMeasureEIDRep->len += sizeof(MEASEURE_REP_RPI);
+                MEMvCopy(   &(pMgmt->pCurrMeasureEIDRep->sRep.sRPI),
+                            &(((PWLAN_IE_MEASURE_REQ) pvMeasureEID)->sReq),
+                            sizeof(MEASEURE_REQ));
+                MEMvCopy(pMgmt->pCurrMeasureEIDRep->sRep.sRPI.abyRPIdensity, pbyRPIs, 8);
+                break;
+            default :
+                break;
+        }
+        pbyCurrentEID += (2 + pMgmt->pCurrMeasureEIDRep->len);
+        pMgmt->uLengthOfRepEIDs += (2 + pMgmt->pCurrMeasureEIDRep->len);
+        pMgmt->pCurrMeasureEIDRep = (PWLAN_IE_MEASURE_REP) pbyCurrentEID;
+    }
+    if (bEndOfReport == TRUE) {
+        IEEE11hbMSRRepTx(pMgmt);
+    }
+    //spin_unlock_irq(&pDevice->lock);
+    return (TRUE);
+}
+
+
+BOOL
+VNTWIFIbChannelSwitch(
+    IN PVOID pMgmtObject,
+    IN BYTE  byNewChannel
+    )
+{
+    PSMgmtObject    pMgmt = (PSMgmtObject) pMgmtObject;
+
+    //spin_lock_irq(&pDevice->lock);
+    pMgmt->uCurrChannel = byNewChannel;
+    pMgmt->bSwitchChannel = FALSE;
+    //spin_unlock_irq(&pDevice->lock);
+    return TRUE;
+}
+
+/*
+BOOL
+VNTWIFIbRadarPresent(
+    IN PVOID pMgmtObject,
+    IN BYTE  byChannel
+    )
+{
+    PSMgmtObject    pMgmt = (PSMgmtObject) pMgmtObject;
+    if ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) &&
+        (byChannel == (BYTE) pMgmt->uCurrChannel) &&
+        (pMgmt->bSwitchChannel != TRUE) &&
+        (pMgmt->b11hEnable == TRUE)) {
+        if (IS_ETH_ADDRESS_EQUAL(pMgmt->abyIBSSDFSOwner, CARDpGetCurrentAddress(pMgmt->pAdapter))) {
+            pMgmt->byNewChannel = CARDbyAutoChannelSelect(pMgmt->pAdapter,(BYTE) pMgmt->uCurrChannel);
+            pMgmt->bSwitchChannel = TRUE;
+        }
+        BEACONbSendBeacon(pMgmt);
+        CARDbChannelSwitch(pMgmt->pAdapter, 0, pMgmt->byNewChannel, 10);
+    }
+    return TRUE;
+}
+*/
+
diff --git a/drivers/staging/vt6655/vntwifi.h b/drivers/staging/vt6655/vntwifi.h
new file mode 100644
index 0000000..3e620a7
--- /dev/null
+++ b/drivers/staging/vt6655/vntwifi.h
@@ -0,0 +1,330 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: vntwifi.h
+ *
+ * Purpose: export VNT Host WiFi library function
+ *
+ * Author: Yiching Chen
+ *
+ * Date: Jan 7, 2004
+ *
+ */
+
+#ifndef __VNTWIFI_H__
+#define __VNTWIFI_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__80211MGR_H__)
+#include "80211mgr.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+
+/*---------------------  Export Definitions -------------------------*/
+#define RATE_1M         0
+#define RATE_2M         1
+#define RATE_5M         2
+#define RATE_11M        3
+#define RATE_6M         4
+#define RATE_9M         5
+#define RATE_12M        6
+#define RATE_18M        7
+#define RATE_24M        8
+#define RATE_36M        9
+#define RATE_48M       10
+#define RATE_54M       11
+#define RATE_AUTO      12
+#define MAX_RATE       12
+
+// key CipherSuite
+#define KEY_CTL_WEP         0x00
+#define KEY_CTL_NONE        0x01
+#define KEY_CTL_TKIP        0x02
+#define KEY_CTL_CCMP        0x03
+#define KEY_CTL_INVALID     0xFF
+
+#define CHANNEL_MAX_24G         14
+
+#define MAX_BSS_NUM             42
+
+#define MAX_PMKID_CACHE         16
+
+// Pre-configured Authenticaiton Mode (from XP)
+typedef enum tagWMAC_AUTHENTICATION_MODE {
+
+    WMAC_AUTH_OPEN,
+    WMAC_AUTH_SHAREKEY,
+    WMAC_AUTH_AUTO,
+    WMAC_AUTH_WPA,
+    WMAC_AUTH_WPAPSK,
+    WMAC_AUTH_WPANONE,
+    WMAC_AUTH_WPA2,
+    WMAC_AUTH_WPA2PSK,
+    WMAC_AUTH_MAX       // Not a real mode, defined as upper bound
+
+} WMAC_AUTHENTICATION_MODE, *PWMAC_AUTHENTICATION_MODE;
+
+typedef enum tagWMAC_ENCRYPTION_MODE {
+
+    WMAC_ENCRYPTION_WEPEnabled,
+    WMAC_ENCRYPTION_WEPDisabled,
+    WMAC_ENCRYPTION_WEPKeyAbsent,
+    WMAC_ENCRYPTION_WEPNotSupported,
+    WMAC_ENCRYPTION_TKIPEnabled,
+    WMAC_ENCRYPTION_TKIPKeyAbsent,
+    WMAC_ENCRYPTION_AESEnabled,
+    WMAC_ENCRYPTION_AESKeyAbsent
+
+} WMAC_ENCRYPTION_MODE, *PWMAC_ENCRYPTION_MODE;
+
+// Pre-configured Mode (from XP)
+
+typedef enum tagWMAC_CONFIG_MODE {
+
+    WMAC_CONFIG_ESS_STA = 0,
+    WMAC_CONFIG_IBSS_STA,
+    WMAC_CONFIG_AUTO,
+    WMAC_CONFIG_AP
+
+} WMAC_CONFIG_MODE, *PWMAC_CONFIG_MODE;
+
+
+
+typedef enum tagWMAC_POWER_MODE {
+
+    WMAC_POWER_CAM,
+    WMAC_POWER_FAST,
+    WMAC_POWER_MAX
+
+} WMAC_POWER_MODE, *PWMAC_POWER_MODE;
+
+#define VNTWIFIbIsShortSlotTime(wCapInfo)               \
+        WLAN_GET_CAP_INFO_SHORTSLOTTIME(wCapInfo)       \
+
+#define VNTWIFIbIsProtectMode(byERP)                    \
+        ((byERP & WLAN_EID_ERP_USE_PROTECTION) != 0)    \
+
+#define VNTWIFIbIsBarkerMode(byERP)                     \
+        ((byERP & WLAN_EID_ERP_BARKER_MODE) != 0)       \
+
+#define VNTWIFIbIsShortPreamble(wCapInfo)               \
+        WLAN_GET_CAP_INFO_SHORTPREAMBLE(wCapInfo)       \
+
+#define VNTWIFIbIsEncryption(wCapInfo)                  \
+        WLAN_GET_CAP_INFO_PRIVACY(wCapInfo)             \
+
+#define VNTWIFIbIsESS(wCapInfo)                         \
+        WLAN_GET_CAP_INFO_ESS(wCapInfo)                 \
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Types  ------------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+
+VOID
+VNTWIFIvSetIBSSParameter (
+    IN PVOID pMgmtHandle,
+    IN WORD  wBeaconPeriod,
+    IN WORD  wATIMWindow,
+    IN UINT  uChannel
+    );
+
+VOID
+VNTWIFIvSetOPMode (
+    IN PVOID pMgmtHandle,
+    IN WMAC_CONFIG_MODE eOPMode
+    );
+
+PWLAN_IE_SSID
+VNTWIFIpGetCurrentSSID(
+    IN PVOID pMgmtHandle
+    );
+
+UINT
+VNTWIFIpGetCurrentChannel(
+    IN PVOID pMgmtHandle
+    );
+
+WORD
+VNTWIFIwGetAssocID (
+    IN PVOID pMgmtHandle
+    );
+
+BYTE
+VNTWIFIbyGetMaxSupportRate (
+    IN PWLAN_IE_SUPP_RATES pSupportRateIEs,
+    IN PWLAN_IE_SUPP_RATES pExtSupportRateIEs
+    );
+
+BYTE
+VNTWIFIbyGetACKTxRate (
+    IN BYTE byRxDataRate,
+    IN PWLAN_IE_SUPP_RATES pSupportRateIEs,
+    IN PWLAN_IE_SUPP_RATES pExtSupportRateIEs
+    );
+
+VOID
+VNTWIFIvSetAuthenticationMode (
+    IN PVOID pMgmtHandle,
+    IN WMAC_AUTHENTICATION_MODE eAuthMode
+    );
+
+VOID
+VNTWIFIvSetEncryptionMode (
+    IN PVOID pMgmtHandle,
+    IN WMAC_ENCRYPTION_MODE eEncryptionMode
+    );
+
+
+BOOL
+VNTWIFIbConfigPhyMode(
+    IN PVOID pMgmtHandle,
+    IN CARD_PHY_TYPE ePhyType
+    );
+
+VOID
+VNTWIFIbGetConfigPhyMode(
+    IN  PVOID pMgmtHandle,
+    OUT PVOID pePhyType
+    );
+
+VOID
+VNTWIFIvQueryBSSList(
+    IN PVOID    pMgmtHandle,
+    OUT PUINT   puBSSCount,
+    OUT PVOID   *pvFirstBSS
+    );
+
+
+
+
+VOID
+VNTWIFIvGetNextBSS (
+    IN PVOID            pMgmtHandle,
+    IN PVOID            pvCurrentBSS,
+    OUT PVOID           *pvNextBSS
+    );
+
+
+
+VOID
+VNTWIFIvUpdateNodeTxCounter(
+    IN PVOID    pMgmtHandle,
+    IN PBYTE    pbyDestAddress,
+    IN BOOL     bTxOk,
+    IN WORD     wRate,
+    IN PBYTE    pbyTxFailCount
+    );
+
+
+VOID
+VNTWIFIvGetTxRate(
+    IN PVOID    pMgmtHandle,
+    IN PBYTE    pbyDestAddress,
+    OUT PWORD   pwTxDataRate,
+    OUT PBYTE   pbyACKRate,
+    OUT PBYTE   pbyCCKBasicRate,
+    OUT PBYTE   pbyOFDMBasicRate
+    );
+/*
+BOOL
+VNTWIFIbInit(
+    IN PVOID    pAdapterHandler,
+    OUT PVOID   *pMgmtHandler
+    );
+*/
+
+BYTE
+VNTWIFIbyGetKeyCypher(
+    IN PVOID    pMgmtHandle,
+    IN BOOL     bGroupKey
+    );
+
+
+
+
+BOOL
+VNTWIFIbSetPMKIDCache (
+    IN PVOID pMgmtObject,
+    IN ULONG ulCount,
+    IN PVOID pPMKIDInfo
+    );
+
+BOOL
+VNTWIFIbCommandRunning (
+    IN PVOID pMgmtObject
+    );
+
+WORD
+VNTWIFIwGetMaxSupportRate(
+    IN PVOID pMgmtObject
+    );
+
+// for 802.11h
+VOID
+VNTWIFIvSet11h (
+    IN PVOID pMgmtObject,
+    IN BOOL  b11hEnable
+    );
+
+BOOL
+VNTWIFIbMeasureReport(
+    IN PVOID pMgmtObject,
+    IN BOOL  bEndOfReport,
+    IN PVOID pvMeasureEID,
+    IN BYTE  byReportMode,
+    IN BYTE  byBasicMap,
+    IN BYTE  byCCAFraction,
+    IN PBYTE pbyRPIs
+    );
+
+BOOL
+VNTWIFIbChannelSwitch(
+    IN PVOID pMgmtObject,
+    IN BYTE  byNewChannel
+    );
+/*
+BOOL
+VNTWIFIbRadarPresent(
+    IN PVOID pMgmtObject,
+    IN BYTE  byChannel
+    );
+*/
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+#endif //__VNTWIFI_H__
diff --git a/drivers/staging/vt6655/wcmd.c b/drivers/staging/vt6655/wcmd.c
new file mode 100644
index 0000000..92563bd
--- /dev/null
+++ b/drivers/staging/vt6655/wcmd.c
@@ -0,0 +1,1178 @@
+ /*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: wcmd.c
+ *
+ * Purpose: Handles the management command interface functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 8, 2003
+ *
+ * Functions:
+ *      s_vProbeChannel - Active scan channel
+ *      s_MgrMakeProbeRequest - Make ProbeRequest packet
+ *      CommandTimer - Timer function to handle command
+ *      s_bCommandComplete - Command Complete function
+ *      bScheduleCommand - Push Command and wait Command Scheduler to do
+ *      vCommandTimer- Command call back functions
+ *      vCommandTimerWait- Call back timer
+ *      bClearBSSID_SCAN- Clear BSSID_SCAN cmd in CMD Queue
+ *
+ * Revision History:
+ *
+ */
+
+
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+#if !defined(__WCMD_H__)
+#include "wcmd.h"
+#endif
+#if !defined(__WMGR_H__)
+#include "wmgr.h"
+#endif
+#if !defined(__POWER_H__)
+#include "power.h"
+#endif
+#if !defined(__WCTL_H__)
+#include "wctl.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__RXTX_H__)
+#include "rxtx.h"
+#endif
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+//DavidWang
+#if !defined(__IOWPA_H__)
+#include "iowpa.h"
+#endif
+
+/*---------------------  Static Definitions -------------------------*/
+
+
+
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+static int          msglevel                =MSG_LEVEL_INFO;
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+/*---------------------  Static Functions  --------------------------*/
+
+static
+VOID
+s_vProbeChannel(
+    IN PSDevice pDevice
+    );
+
+
+static
+PSTxMgmtPacket
+s_MgrMakeProbeRequest(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PBYTE pScanBSSID,
+    IN PWLAN_IE_SSID pSSID,
+    IN PWLAN_IE_SUPP_RATES pCurrRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+    );
+
+static
+BOOL
+s_bCommandComplete (
+    PSDevice pDevice
+    );
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+/*
+ * Description:
+ *      Stop AdHoc beacon during scan process
+ *
+ * Parameters:
+ *  In:
+ *      pDevice     - Pointer to the adapter
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+static
+void
+vAdHocBeaconStop(PSDevice  pDevice)
+{
+
+    PSMgmtObject    pMgmt = &(pDevice->sMgmtObj);
+    BOOL            bStop;
+
+    /*
+     * temporarily stop Beacon packet for AdHoc Server
+     * if all of the following coditions are met:
+     *  (1) STA is in AdHoc mode
+     *  (2) VT3253 is programmed as automatic Beacon Transmitting
+     *  (3) One of the following conditions is met
+     *      (3.1) AdHoc channel is in B/G band and the
+     *      current scan channel is in A band
+     *      or
+     *      (3.2) AdHoc channel is in A mode
+     */
+    bStop = FALSE;
+    if ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) &&
+    (pMgmt->eCurrState >= WMAC_STATE_STARTED))
+    {
+        if ((pMgmt->uIBSSChannel <=  CB_MAX_CHANNEL_24G) &&
+             (pMgmt->uScanChannel > CB_MAX_CHANNEL_24G))
+        {
+            bStop = TRUE;
+        }
+        if (pMgmt->uIBSSChannel >  CB_MAX_CHANNEL_24G)
+        {
+            bStop = TRUE;
+        }
+    }
+
+    if (bStop)
+    {
+        MACvRegBitsOff(pDevice->PortOffset, MAC_REG_TCR, TCR_AUTOBCNTX);
+    }
+
+}
+
+/*
+ * Description:
+ *      Restart AdHoc beacon after scan process complete
+ *
+ * Parameters:
+ *  In:
+ *      pDevice     - Pointer to the adapter
+ *  Out:
+ *      none
+ *
+ * Return Value: none
+ *
+ */
+static
+void
+vAdHocBeaconRestart(PSDevice pDevice)
+{
+    PSMgmtObject    pMgmt = &(pDevice->sMgmtObj);
+
+    /*
+     * Restart Beacon packet for AdHoc Server
+     * if all of the following coditions are met:
+     *  (1) STA is in AdHoc mode
+     *  (2) VT3253 is programmed as automatic Beacon Transmitting
+     */
+    if ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) &&
+    (pMgmt->eCurrState >= WMAC_STATE_STARTED))
+    {
+         MACvRegBitsOn(pDevice->PortOffset, MAC_REG_TCR, TCR_AUTOBCNTX);
+    }
+
+}
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *   Prepare and send probe request management frames.
+ *
+ *
+ * Return Value:
+ *    none.
+ *
+-*/
+
+static
+VOID
+s_vProbeChannel(
+    IN PSDevice pDevice
+    )
+{
+                                                     //1M,   2M,   5M,   11M,  18M,  24M,  36M,  54M
+    BYTE abyCurrSuppRatesG[] = {WLAN_EID_SUPP_RATES, 8, 0x02, 0x04, 0x0B, 0x16, 0x24, 0x30, 0x48, 0x6C};
+    BYTE abyCurrExtSuppRatesG[] = {WLAN_EID_EXTSUPP_RATES, 4, 0x0C, 0x12, 0x18, 0x60};
+                                                           //6M,   9M,   12M,  48M
+    BYTE abyCurrSuppRatesA[] = {WLAN_EID_SUPP_RATES, 8, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x48, 0x60, 0x6C};
+    BYTE abyCurrSuppRatesB[] = {WLAN_EID_SUPP_RATES, 4, 0x02, 0x04, 0x0B, 0x16};
+    PBYTE           pbyRate;
+    PSTxMgmtPacket  pTxPacket;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    UINT            ii;
+
+
+    if (pDevice->eCurrentPHYType == PHY_TYPE_11A) {
+        pbyRate = &abyCurrSuppRatesA[0];
+    } else if (pDevice->eCurrentPHYType == PHY_TYPE_11B) {
+        pbyRate = &abyCurrSuppRatesB[0];
+    } else {
+        pbyRate = &abyCurrSuppRatesG[0];
+    }
+    // build an assocreq frame and send it
+    pTxPacket = s_MgrMakeProbeRequest
+                (
+                  pDevice,
+                  pMgmt,
+                  pMgmt->abyScanBSSID,
+                  (PWLAN_IE_SSID)pMgmt->abyScanSSID,
+                  (PWLAN_IE_SUPP_RATES)pbyRate,
+                  (PWLAN_IE_SUPP_RATES)abyCurrExtSuppRatesG
+                );
+
+    if (pTxPacket != NULL ){
+        for (ii = 0; ii < 2 ; ii++) {
+            if (csMgmt_xmit(pDevice, pTxPacket) != CMD_STATUS_PENDING) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Probe request sending fail.. \n");
+            }
+            else {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Probe request is sending.. \n");
+            }
+        }
+    }
+
+}
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *  Constructs an probe request frame
+ *
+ *
+ * Return Value:
+ *    A ptr to Tx frame or NULL on allocation failue
+ *
+-*/
+
+
+PSTxMgmtPacket
+s_MgrMakeProbeRequest(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PBYTE pScanBSSID,
+    IN PWLAN_IE_SSID pSSID,
+    IN PWLAN_IE_SUPP_RATES pCurrRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+
+    )
+{
+    PSTxMgmtPacket      pTxPacket = NULL;
+    WLAN_FR_PROBEREQ    sFrame;
+
+
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_PROBEREQ_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_PROBEREQ_FR_MAXLEN;
+    vMgrEncodeProbeRequest(&sFrame);
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+        (
+        WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+        WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_PROBEREQ)
+        ));
+    memcpy( sFrame.pHdr->sA3.abyAddr1, pScanBSSID, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pScanBSSID, WLAN_BSSID_LEN);
+    // Copy the SSID, pSSID->len=0 indicate broadcast SSID
+    sFrame.pSSID = (PWLAN_IE_SSID)(sFrame.pBuf + sFrame.len);
+    sFrame.len += pSSID->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSSID, pSSID, pSSID->len + WLAN_IEHDR_LEN);
+    sFrame.pSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+    sFrame.len += pCurrRates->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSuppRates, pCurrRates, pCurrRates->len + WLAN_IEHDR_LEN);
+    // Copy the extension rate set
+    if (pDevice->eCurrentPHYType == PHY_TYPE_11G) {
+        sFrame.pExtSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+        sFrame.len += pCurrExtSuppRates->len + WLAN_IEHDR_LEN;
+        memcpy(sFrame.pExtSuppRates, pCurrExtSuppRates, pCurrExtSuppRates->len + WLAN_IEHDR_LEN);
+    }
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+
+    return pTxPacket;
+}
+
+
+
+
+VOID
+vCommandTimerWait(
+    IN HANDLE    hDeviceContext,
+    IN UINT MSecond
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+
+    init_timer(&pDevice->sTimerCommand);
+    pDevice->sTimerCommand.data = (ULONG)pDevice;
+    pDevice->sTimerCommand.function = (TimerFunction)vCommandTimer;
+    // RUN_AT :1 msec ~= (HZ/1024)
+    pDevice->sTimerCommand.expires = (UINT)RUN_AT((MSecond * HZ) >> 10);
+    add_timer(&pDevice->sTimerCommand);
+    return;
+}
+
+
+
+VOID
+vCommandTimer (
+    IN  HANDLE      hDeviceContext
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PWLAN_IE_SSID   pItemSSID;
+    PWLAN_IE_SSID   pItemSSIDCurr;
+    CMD_STATUS      Status;
+    UINT            ii;
+    BYTE            byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80};
+    struct sk_buff  *skb;
+
+
+    if (pDevice->dwDiagRefCount != 0)
+        return;
+    if (pDevice->bCmdRunning != TRUE)
+        return;
+
+    spin_lock_irq(&pDevice->lock);
+
+    switch ( pDevice->eCommandState ) {
+
+        case WLAN_CMD_SCAN_START:
+
+	pDevice->byReAssocCount = 0;
+            if (pDevice->bRadioOff == TRUE) {
+                s_bCommandComplete(pDevice);
+                spin_unlock_irq(&pDevice->lock);
+                return;
+            }
+
+            if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+                s_bCommandComplete(pDevice);
+                CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_AP);
+                spin_unlock_irq(&pDevice->lock);
+                return;
+            }
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState= WLAN_CMD_SCAN_START\n");
+            pItemSSID = (PWLAN_IE_SSID)pMgmt->abyScanSSID;
+            // wait all Data TD complete
+            if (pDevice->iTDUsed[TYPE_AC0DMA] != 0){
+                spin_unlock_irq(&pDevice->lock);
+                vCommandTimerWait((HANDLE)pDevice, 10);
+                return;
+            };
+
+            if (pMgmt->uScanChannel == 0 ) {
+                pMgmt->uScanChannel = pDevice->byMinChannel;
+                // Set Baseband to be more sensitive.
+
+            }
+            if (pMgmt->uScanChannel > pDevice->byMaxChannel) {
+                pMgmt->eScanState = WMAC_NO_SCANNING;
+
+                // Set Baseband's sensitivity back.
+                // Set channel back
+                CARDbSetChannel(pMgmt->pAdapter, pMgmt->uCurrChannel);
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Scanning, set back to channel: [%d]\n", pMgmt->uCurrChannel);
+                if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+                    CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_ADHOC);
+                } else {
+                    CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_INFRASTRUCTURE);
+                }
+                vAdHocBeaconRestart(pDevice);
+                s_bCommandComplete(pDevice);
+
+            } else {
+//2008-8-4 <add> by chester
+                 if (!ChannelValid(pDevice->byZoneType, pMgmt->uScanChannel)) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Invalid channel pMgmt->uScanChannel = %d \n",pMgmt->uScanChannel);
+                    s_bCommandComplete(pDevice);
+                    return;
+                }
+//printk("chester-pMgmt->uScanChannel=%d,pDevice->byMaxChannel=%d\n",pMgmt->uScanChannel,pDevice->byMaxChannel);
+                if (pMgmt->uScanChannel == pDevice->byMinChannel) {
+                    //pMgmt->eScanType = WMAC_SCAN_ACTIVE;
+                    pMgmt->abyScanBSSID[0] = 0xFF;
+                    pMgmt->abyScanBSSID[1] = 0xFF;
+                    pMgmt->abyScanBSSID[2] = 0xFF;
+                    pMgmt->abyScanBSSID[3] = 0xFF;
+                    pMgmt->abyScanBSSID[4] = 0xFF;
+                    pMgmt->abyScanBSSID[5] = 0xFF;
+                    pItemSSID->byElementID = WLAN_EID_SSID;
+                    // clear bssid list
+                    // BSSvClearBSSList((HANDLE)pDevice, pDevice->bLinkPass);
+                    pMgmt->eScanState = WMAC_IS_SCANNING;
+
+                }
+
+                vAdHocBeaconStop(pDevice);
+
+                if (CARDbSetChannel(pMgmt->pAdapter, pMgmt->uScanChannel) == TRUE) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"SCAN Channel: %d\n", pMgmt->uScanChannel);
+                } else {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"SET SCAN Channel Fail: %d\n", pMgmt->uScanChannel);
+                }
+                CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_UNKNOWN);
+//	printk("chester-mxch=%d\n",pDevice->byMaxChannel);
+      //          printk("chester-ch=%d\n",pMgmt->uScanChannel);
+	pMgmt->uScanChannel++;
+//2008-8-4 <modify> by chester
+	 if (!ChannelValid(pDevice->byZoneType, pMgmt->uScanChannel) &&
+                        pMgmt->uScanChannel <= pDevice->byMaxChannel ){
+                    pMgmt->uScanChannel=pDevice->byMaxChannel+1;
+		 pMgmt->eCommandState = WLAN_CMD_SCAN_END;
+
+                }
+
+
+                if ((pMgmt->b11hEnable == FALSE) ||
+                    (pMgmt->uScanChannel < CB_MAX_CHANNEL_24G)) {
+                    s_vProbeChannel(pDevice);
+                    spin_unlock_irq(&pDevice->lock);
+                    vCommandTimerWait((HANDLE)pDevice, WCMD_ACTIVE_SCAN_TIME);
+                    return;
+                } else {
+                    spin_unlock_irq(&pDevice->lock);
+                    vCommandTimerWait((HANDLE)pDevice, WCMD_PASSIVE_SCAN_TIME);
+                    return;
+                }
+
+            }
+
+            break;
+
+        case WLAN_CMD_SCAN_END:
+
+            // Set Baseband's sensitivity back.
+            // Set channel back
+            CARDbSetChannel(pMgmt->pAdapter, pMgmt->uCurrChannel);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Scanning, set back to channel: [%d]\n", pMgmt->uCurrChannel);
+            if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+                CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_ADHOC);
+            } else {
+                CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_INFRASTRUCTURE);
+            }
+
+            pMgmt->eScanState = WMAC_NO_SCANNING;
+            vAdHocBeaconRestart(pDevice);
+//2008-0409-07, <Add> by Einsn Liu
+#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+	if(pMgmt->eScanType == WMAC_SCAN_PASSIVE)
+			{//send scan event to wpa_Supplicant
+				union iwreq_data wrqu;
+				memset(&wrqu, 0, sizeof(wrqu));
+				wireless_send_event(pDevice->dev, SIOCGIWSCAN, &wrqu, NULL);
+			}
+#endif
+            s_bCommandComplete(pDevice);
+            break;
+
+        case WLAN_CMD_DISASSOCIATE_START :
+	pDevice->byReAssocCount = 0;
+            if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
+                (pMgmt->eCurrState != WMAC_STATE_ASSOC)) {
+                s_bCommandComplete(pDevice);
+                spin_unlock_irq(&pDevice->lock);
+                return;
+            } else {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Send Disassociation Packet..\n");
+                // reason = 8 : disassoc because sta has left
+                vMgrDisassocBeginSta((HANDLE)pDevice, pMgmt, pMgmt->abyCurrBSSID, (8), &Status);
+                pDevice->bLinkPass = FALSE;
+                // unlock command busy
+                pItemSSID = (PWLAN_IE_SSID)pMgmt->abyCurrSSID;
+                pItemSSID->len = 0;
+                memset(pItemSSID->abySSID, 0, WLAN_SSID_MAXLEN);
+                pMgmt->eCurrState = WMAC_STATE_IDLE;
+                pMgmt->sNodeDBTable[0].bActive = FALSE;
+//                pDevice->bBeaconBufReady = FALSE;
+            }
+            netif_stop_queue(pDevice->dev);
+            pDevice->eCommandState = WLAN_DISASSOCIATE_WAIT;
+            // wait all Control TD complete
+            if (pDevice->iTDUsed[TYPE_TXDMA0] != 0){
+                vCommandTimerWait((HANDLE)pDevice, 10);
+                spin_unlock_irq(&pDevice->lock);
+                return;
+            };
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" CARDbRadioPowerOff\n");
+	//2008-09-02  <mark>	by chester
+           // CARDbRadioPowerOff(pDevice);
+            s_bCommandComplete(pDevice);
+            break;
+
+        case WLAN_DISASSOCIATE_WAIT :
+            // wait all Control TD complete
+            if (pDevice->iTDUsed[TYPE_TXDMA0] != 0){
+                vCommandTimerWait((HANDLE)pDevice, 10);
+                spin_unlock_irq(&pDevice->lock);
+                return;
+            };
+//2008-09-02  <mark> by chester
+           // CARDbRadioPowerOff(pDevice);
+            s_bCommandComplete(pDevice);
+            break;
+
+        case WLAN_CMD_SSID_START:
+        	pDevice->byReAssocCount = 0;
+            if (pDevice->bRadioOff == TRUE) {
+                s_bCommandComplete(pDevice);
+                spin_unlock_irq(&pDevice->lock);
+                return;
+            }
+//printk("chester-currmode=%d\n",pMgmt->eCurrMode);
+printk("chester-abyDesireSSID=%s\n",((PWLAN_IE_SSID)pMgmt->abyDesireSSID)->abySSID);
+                     //memcpy(pMgmt->abyAdHocSSID,pMgmt->abyDesireSSID,
+                              //((PWLAN_IE_SSID)pMgmt->abyDesireSSID)->len + WLAN_IEHDR_LEN);
+            pItemSSID = (PWLAN_IE_SSID)pMgmt->abyDesireSSID;
+            pItemSSIDCurr = (PWLAN_IE_SSID)pMgmt->abyCurrSSID;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" cmd: desire ssid = %s\n", pItemSSID->abySSID);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" cmd: curr ssid = %s\n", pItemSSIDCurr->abySSID);
+
+            if (pMgmt->eCurrState == WMAC_STATE_ASSOC) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Cmd pMgmt->eCurrState == WMAC_STATE_ASSOC\n");
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pItemSSID->len =%d\n",pItemSSID->len);
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pItemSSIDCurr->len = %d\n",pItemSSIDCurr->len);
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" desire ssid = %s\n", pItemSSID->abySSID);
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" curr ssid = %s\n", pItemSSIDCurr->abySSID);
+            }
+
+            if ((pMgmt->eCurrState == WMAC_STATE_ASSOC) ||
+                ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA)&& (pMgmt->eCurrState == WMAC_STATE_JOINTED))) {
+
+                if (pItemSSID->len == pItemSSIDCurr->len) {
+                    if (memcmp(pItemSSID->abySSID, pItemSSIDCurr->abySSID, pItemSSID->len) == 0) {
+                        s_bCommandComplete(pDevice);
+                        spin_unlock_irq(&pDevice->lock);
+                        return;
+                    }
+                }
+
+                netif_stop_queue(pDevice->dev);
+                pDevice->bLinkPass = FALSE;
+            }
+            // set initial state
+            pMgmt->eCurrState = WMAC_STATE_IDLE;
+            pMgmt->eCurrMode = WMAC_MODE_STANDBY;
+            PSvDisablePowerSaving((HANDLE)pDevice);
+            BSSvClearNodeDBTable(pDevice, 0);
+
+            vMgrJoinBSSBegin((HANDLE)pDevice, &Status);
+            // if Infra mode
+            if ((pMgmt->eCurrMode == WMAC_MODE_ESS_STA) && (pMgmt->eCurrState == WMAC_STATE_JOINTED)) {
+
+		// Call mgr to begin the deauthentication
+                // reason = (3) beacuse sta has left ESS
+                if (pMgmt->eCurrState>= WMAC_STATE_AUTH) {
+                    vMgrDeAuthenBeginSta((HANDLE)pDevice, pMgmt, pMgmt->abyCurrBSSID, (3), &Status);
+                }
+                // Call mgr to begin the authentication
+                vMgrAuthenBeginSta((HANDLE)pDevice, pMgmt, &Status);
+                if (Status == CMD_STATUS_SUCCESS) {
+		pDevice->byLinkWaitCount = 0;
+                    pDevice->eCommandState = WLAN_AUTHENTICATE_WAIT;
+                    vCommandTimerWait((HANDLE)pDevice, AUTHENTICATE_TIMEOUT);
+                    spin_unlock_irq(&pDevice->lock);
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Set eCommandState = WLAN_AUTHENTICATE_WAIT\n");
+                    return;
+                }
+            }
+            // if Adhoc mode
+            else if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+                if (pMgmt->eCurrState == WMAC_STATE_JOINTED) {
+                    if (netif_queue_stopped(pDevice->dev)){
+                        netif_wake_queue(pDevice->dev);
+                    }
+                    pDevice->bLinkPass = TRUE;
+
+                    pMgmt->sNodeDBTable[0].bActive = TRUE;
+                    pMgmt->sNodeDBTable[0].uInActiveCount = 0;
+                    bClearBSSID_SCAN(pDevice);
+                }
+                else {
+                    // start own IBSS
+                    vMgrCreateOwnIBSS((HANDLE)pDevice, &Status);
+                    if (Status != CMD_STATUS_SUCCESS){
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " WLAN_CMD_IBSS_CREATE fail ! \n");
+                    };
+                    BSSvAddMulticastNode(pDevice);
+                }
+            }
+            // if SSID not found
+            else if (pMgmt->eCurrMode == WMAC_MODE_STANDBY) {
+                if (pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA ||
+                    pMgmt->eConfigMode == WMAC_CONFIG_AUTO) {
+                    // start own IBSS
+                    vMgrCreateOwnIBSS((HANDLE)pDevice, &Status);
+                    if (Status != CMD_STATUS_SUCCESS){
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO" WLAN_CMD_IBSS_CREATE fail ! \n");
+                    };
+                    BSSvAddMulticastNode(pDevice);
+                    if (netif_queue_stopped(pDevice->dev)){
+                        netif_wake_queue(pDevice->dev);
+                    }
+                    pDevice->bLinkPass = TRUE;
+                }
+                else {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Disconnect SSID none\n");
+		  #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+                    // if(pDevice->bWPASuppWextEnabled == TRUE)
+                        {
+                  	union iwreq_data  wrqu;
+                  	memset(&wrqu, 0, sizeof (wrqu));
+                          wrqu.ap_addr.sa_family = ARPHRD_ETHER;
+                  	printk("wireless_send_event--->SIOCGIWAP(disassociated:vMgrJoinBSSBegin Fail !!)\n");
+                  	wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL);
+                       }
+                    #endif
+
+                }
+            }
+            s_bCommandComplete(pDevice);
+            break;
+
+        case WLAN_AUTHENTICATE_WAIT :
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState == WLAN_AUTHENTICATE_WAIT\n");
+            if (pMgmt->eCurrState == WMAC_STATE_AUTH) {
+                // Call mgr to begin the association
+                	pDevice->byLinkWaitCount = 0;
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCurrState == WMAC_STATE_AUTH\n");
+                vMgrAssocBeginSta((HANDLE)pDevice, pMgmt, &Status);
+                if (Status == CMD_STATUS_SUCCESS) {
+		pDevice->byLinkWaitCount = 0;
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState = WLAN_ASSOCIATE_WAIT\n");
+                    pDevice->eCommandState = WLAN_ASSOCIATE_WAIT;
+                    vCommandTimerWait((HANDLE)pDevice, ASSOCIATE_TIMEOUT);
+                    spin_unlock_irq(&pDevice->lock);
+                    return;
+                }
+            }
+
+	else if(pMgmt->eCurrState < WMAC_STATE_AUTHPENDING) {
+               printk("WLAN_AUTHENTICATE_WAIT:Authen Fail???\n");
+	   }
+	   else  if(pDevice->byLinkWaitCount <= 4){    //mike add:wait another 2 sec if authenticated_frame delay!
+                pDevice->byLinkWaitCount ++;
+	       printk("WLAN_AUTHENTICATE_WAIT:wait %d times!!\n",pDevice->byLinkWaitCount);
+	       spin_unlock_irq(&pDevice->lock);
+	       vCommandTimerWait((HANDLE)pDevice, AUTHENTICATE_TIMEOUT/2);
+	       return;
+	   }
+	          pDevice->byLinkWaitCount = 0;
+		 #if 0
+                     #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+                    // if(pDevice->bWPASuppWextEnabled == TRUE)
+                        {
+                  	union iwreq_data  wrqu;
+                  	memset(&wrqu, 0, sizeof (wrqu));
+                          wrqu.ap_addr.sa_family = ARPHRD_ETHER;
+                  	printk("wireless_send_event--->SIOCGIWAP(disassociated:AUTHENTICATE_WAIT_timeout)\n");
+                  	wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL);
+                       }
+                    #endif
+	         #endif
+            s_bCommandComplete(pDevice);
+            break;
+
+        case WLAN_ASSOCIATE_WAIT :
+            if (pMgmt->eCurrState == WMAC_STATE_ASSOC) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCurrState == WMAC_STATE_ASSOC\n");
+                if (pDevice->ePSMode != WMAC_POWER_CAM) {
+                    PSvEnablePowerSaving((HANDLE)pDevice, pMgmt->wListenInterval);
+                }
+                if (pMgmt->eAuthenMode >= WMAC_AUTH_WPA) {
+                    KeybRemoveAllKey(&(pDevice->sKey), pDevice->abyBSSID, pDevice->PortOffset);
+                }
+                pDevice->bLinkPass = TRUE;
+                pDevice->byLinkWaitCount = 0;
+                pDevice->byReAssocCount = 0;
+                bClearBSSID_SCAN(pDevice);
+                if (pDevice->byFOETuning) {
+                    BBvSetFOE(pDevice->PortOffset);
+                    PSbSendNullPacket(pDevice);
+                }
+                if (netif_queue_stopped(pDevice->dev)){
+                    netif_wake_queue(pDevice->dev);
+                }
+	     #ifdef TxInSleep
+		 if(pDevice->IsTxDataTrigger != FALSE)   {    //TxDataTimer is not triggered at the first time
+                     // printk("Re-initial TxDataTimer****\n");
+		    del_timer(&pDevice->sTimerTxData);
+                      init_timer(&pDevice->sTimerTxData);
+                      pDevice->sTimerTxData.data = (ULONG)pDevice;
+                      pDevice->sTimerTxData.function = (TimerFunction)BSSvSecondTxData;
+                      pDevice->sTimerTxData.expires = RUN_AT(10*HZ);      //10s callback
+                      pDevice->fTxDataInSleep = FALSE;
+                      pDevice->nTxDataTimeCout = 0;
+		 }
+		 else {
+		   // printk("mike:-->First time triger TimerTxData InSleep\n");
+		 }
+		pDevice->IsTxDataTrigger = TRUE;
+                add_timer(&pDevice->sTimerTxData);
+             #endif
+            }
+		   else if(pMgmt->eCurrState < WMAC_STATE_ASSOCPENDING) {
+               printk("WLAN_ASSOCIATE_WAIT:Association Fail???\n");
+	   }
+	   else  if(pDevice->byLinkWaitCount <= 4){    //mike add:wait another 2 sec if associated_frame delay!
+                pDevice->byLinkWaitCount ++;
+	       printk("WLAN_ASSOCIATE_WAIT:wait %d times!!\n",pDevice->byLinkWaitCount);
+	       spin_unlock_irq(&pDevice->lock);
+	       vCommandTimerWait((HANDLE)pDevice, ASSOCIATE_TIMEOUT/2);
+	       return;
+	   }
+	          pDevice->byLinkWaitCount = 0;
+		#if 0
+                     #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+                    // if(pDevice->bWPASuppWextEnabled == TRUE)
+                        {
+                  	union iwreq_data  wrqu;
+                  	memset(&wrqu, 0, sizeof (wrqu));
+                          wrqu.ap_addr.sa_family = ARPHRD_ETHER;
+                  	printk("wireless_send_event--->SIOCGIWAP(disassociated:ASSOCIATE_WAIT_timeout)\n");
+                  	wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL);
+                       }
+                    #endif
+		#endif
+
+            s_bCommandComplete(pDevice);
+            break;
+
+        case WLAN_CMD_AP_MODE_START :
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState == WLAN_CMD_AP_MODE_START\n");
+
+            if (pMgmt->eConfigMode == WMAC_CONFIG_AP) {
+                del_timer(&pMgmt->sTimerSecondCallback);
+                pMgmt->eCurrState = WMAC_STATE_IDLE;
+                pMgmt->eCurrMode = WMAC_MODE_STANDBY;
+                pDevice->bLinkPass = FALSE;
+                if (pDevice->bEnableHostWEP == TRUE)
+                    BSSvClearNodeDBTable(pDevice, 1);
+                else
+                    BSSvClearNodeDBTable(pDevice, 0);
+                pDevice->uAssocCount = 0;
+                pMgmt->eCurrState = WMAC_STATE_IDLE;
+                pDevice->bFixRate = FALSE;
+
+                vMgrCreateOwnIBSS((HANDLE)pDevice, &Status);
+                if (Status != CMD_STATUS_SUCCESS){
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " vMgrCreateOwnIBSS fail ! \n");
+                };
+                // alway turn off unicast bit
+                MACvRegBitsOff(pDevice->PortOffset, MAC_REG_RCR, RCR_UNICAST);
+                pDevice->byRxMode &= ~RCR_UNICAST;
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wcmd: rx_mode = %x\n", pDevice->byRxMode );
+                BSSvAddMulticastNode(pDevice);
+                if (netif_queue_stopped(pDevice->dev)){
+                    netif_wake_queue(pDevice->dev);
+                }
+                pDevice->bLinkPass = TRUE;
+                add_timer(&pMgmt->sTimerSecondCallback);
+            }
+            s_bCommandComplete(pDevice);
+            break;
+
+        case WLAN_CMD_TX_PSPACKET_START :
+            // DTIM Multicast tx
+            if (pMgmt->sNodeDBTable[0].bRxPSPoll) {
+                while ((skb = skb_dequeue(&pMgmt->sNodeDBTable[0].sTxPSQueue)) != NULL) {
+                    if (skb_queue_empty(&pMgmt->sNodeDBTable[0].sTxPSQueue)) {
+                        pMgmt->abyPSTxMap[0] &= ~byMask[0];
+                        pDevice->bMoreData = FALSE;
+                    }
+                    else {
+                        pDevice->bMoreData = TRUE;
+                    }
+                    if (!device_dma0_xmit(pDevice, skb, 0)) {
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Multicast ps tx fail \n");
+                    }
+                    pMgmt->sNodeDBTable[0].wEnQueueCnt--;
+                }
+            };
+
+            // PS nodes tx
+            for (ii = 1; ii < (MAX_NODE_NUM + 1); ii++) {
+                if (pMgmt->sNodeDBTable[ii].bActive &&
+                    pMgmt->sNodeDBTable[ii].bRxPSPoll) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Index=%d Enqueu Cnt= %d\n",
+                               ii, pMgmt->sNodeDBTable[ii].wEnQueueCnt);
+                    while ((skb = skb_dequeue(&pMgmt->sNodeDBTable[ii].sTxPSQueue)) != NULL) {
+                        if (skb_queue_empty(&pMgmt->sNodeDBTable[ii].sTxPSQueue)) {
+                            // clear tx map
+                            pMgmt->abyPSTxMap[pMgmt->sNodeDBTable[ii].wAID >> 3] &=
+                                    ~byMask[pMgmt->sNodeDBTable[ii].wAID & 7];
+                            pDevice->bMoreData = FALSE;
+                        }
+                        else {
+                            pDevice->bMoreData = TRUE;
+                        }
+                        if (!device_dma0_xmit(pDevice, skb, ii)) {
+                            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "sta ps tx fail \n");
+                        }
+                        pMgmt->sNodeDBTable[ii].wEnQueueCnt--;
+                        // check if sta ps enable, wait next pspoll
+                        // if sta ps disable, send all pending buffers.
+                        if (pMgmt->sNodeDBTable[ii].bPSEnable)
+                            break;
+                    }
+                    if (skb_queue_empty(&pMgmt->sNodeDBTable[ii].sTxPSQueue)) {
+                        // clear tx map
+                        pMgmt->abyPSTxMap[pMgmt->sNodeDBTable[ii].wAID >> 3] &=
+                                    ~byMask[pMgmt->sNodeDBTable[ii].wAID & 7];
+                        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Index=%d PS queue clear \n", ii);
+                    }
+                    pMgmt->sNodeDBTable[ii].bRxPSPoll = FALSE;
+                }
+            }
+
+            s_bCommandComplete(pDevice);
+            break;
+
+
+        case WLAN_CMD_RADIO_START :
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState == WLAN_CMD_RADIO_START\n");
+            if (pDevice->bRadioCmd == TRUE)
+                CARDbRadioPowerOn(pDevice);
+            else
+                CARDbRadioPowerOff(pDevice);
+
+            s_bCommandComplete(pDevice);
+            break;
+
+
+        case WLAN_CMD_CHECK_BBSENSITIVITY_CHANGE :
+            //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState == WLAN_CMD_CHECK_BBSENSITIVITY_START\n");
+            // wait all TD complete
+            if (pDevice->iTDUsed[TYPE_AC0DMA] != 0){
+                vCommandTimerWait((HANDLE)pDevice, 10);
+                spin_unlock_irq(&pDevice->lock);
+                return;
+            }
+            if (pDevice->iTDUsed[TYPE_TXDMA0] != 0){
+                vCommandTimerWait((HANDLE)pDevice, 10);
+                spin_unlock_irq(&pDevice->lock);
+                return;
+            }
+            pDevice->byBBVGACurrent = pDevice->byBBVGANew;
+            BBvSetVGAGainOffset(pDevice, pDevice->byBBVGACurrent);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"SetVGAGainOffset %02X\n", pDevice->byBBVGACurrent);
+            s_bCommandComplete(pDevice);
+            break;
+
+        default :
+            s_bCommandComplete(pDevice);
+            break;
+
+    } //switch
+    spin_unlock_irq(&pDevice->lock);
+    return;
+
+}
+
+
+static
+BOOL
+s_bCommandComplete (
+    PSDevice pDevice
+    )
+{
+    PWLAN_IE_SSID pSSID;
+    BOOL          bRadioCmd = FALSE;
+    //WORD          wDeAuthenReason = 0;
+    BOOL          bForceSCAN = TRUE;
+    PSMgmtObject  pMgmt = pDevice->pMgmt;
+
+
+    pDevice->eCommandState = WLAN_CMD_IDLE;
+    if (pDevice->cbFreeCmdQueue == CMD_Q_SIZE) {
+        //Command Queue Empty
+        pDevice->bCmdRunning = FALSE;
+        return TRUE;
+    }
+    else {
+        pDevice->eCommand = pDevice->eCmdQueue[pDevice->uCmdDequeueIdx].eCmd;
+        pSSID = (PWLAN_IE_SSID)pDevice->eCmdQueue[pDevice->uCmdDequeueIdx].abyCmdDesireSSID;
+        bRadioCmd = pDevice->eCmdQueue[pDevice->uCmdDequeueIdx].bRadioCmd;
+        bForceSCAN = pDevice->eCmdQueue[pDevice->uCmdDequeueIdx].bForceSCAN;
+        ADD_ONE_WITH_WRAP_AROUND(pDevice->uCmdDequeueIdx, CMD_Q_SIZE);
+        pDevice->cbFreeCmdQueue++;
+        pDevice->bCmdRunning = TRUE;
+        switch ( pDevice->eCommand ) {
+            case WLAN_CMD_BSSID_SCAN:
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState= WLAN_CMD_BSSID_SCAN\n");
+                pDevice->eCommandState = WLAN_CMD_SCAN_START;
+                pMgmt->uScanChannel = 0;
+                if (pSSID->len != 0) {
+                    MEMvCopy(pMgmt->abyScanSSID, pSSID, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+                } else {
+                    memset(pMgmt->abyScanSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+                }
+/*
+                if ((bForceSCAN == FALSE) && (pDevice->bLinkPass == TRUE)) {
+                    if ((pSSID->len == ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->len) &&
+                        (MEMEqualMemory(pSSID->abySSID, ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->abySSID, pSSID->len))) {
+                        pDevice->eCommandState = WLAN_CMD_IDLE;
+                    }
+                }
+*/
+                break;
+            case WLAN_CMD_SSID:
+                pDevice->eCommandState = WLAN_CMD_SSID_START;
+                if (pSSID->len > WLAN_SSID_MAXLEN)
+                    pSSID->len = WLAN_SSID_MAXLEN;
+                if (pSSID->len != 0)
+                    MEMvCopy(pDevice->pMgmt->abyDesireSSID, pSSID, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"eCommandState= WLAN_CMD_SSID_START\n");
+                break;
+            case WLAN_CMD_DISASSOCIATE:
+                pDevice->eCommandState = WLAN_CMD_DISASSOCIATE_START;
+                break;
+            case WLAN_CMD_RX_PSPOLL:
+                pDevice->eCommandState = WLAN_CMD_TX_PSPACKET_START;
+                break;
+            case WLAN_CMD_RUN_AP:
+                pDevice->eCommandState = WLAN_CMD_AP_MODE_START;
+                break;
+            case WLAN_CMD_RADIO:
+                pDevice->eCommandState = WLAN_CMD_RADIO_START;
+                pDevice->bRadioCmd = bRadioCmd;
+                break;
+            case WLAN_CMD_CHANGE_BBSENSITIVITY:
+                pDevice->eCommandState = WLAN_CMD_CHECK_BBSENSITIVITY_CHANGE;
+                break;
+
+            default:
+                break;
+
+        }
+
+        vCommandTimerWait((HANDLE)pDevice, 0);
+    }
+
+    return TRUE;
+}
+
+
+
+BOOL bScheduleCommand (
+    IN HANDLE hDeviceContext,
+    IN CMD_CODE    eCommand,
+    IN PBYTE       pbyItem0
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+
+
+    if (pDevice->cbFreeCmdQueue == 0) {
+        return (FALSE);
+    }
+    pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].eCmd = eCommand;
+    pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].bForceSCAN = TRUE;
+    memset(pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].abyCmdDesireSSID, 0 , WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+
+    if (pbyItem0 != NULL) {
+        switch (eCommand) {
+
+            case WLAN_CMD_BSSID_SCAN:
+                MEMvCopy(pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].abyCmdDesireSSID,
+                         pbyItem0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+                pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].bForceSCAN = FALSE;
+                break;
+
+            case WLAN_CMD_SSID:
+                MEMvCopy(pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].abyCmdDesireSSID,
+                         pbyItem0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+                break;
+
+            case WLAN_CMD_DISASSOCIATE:
+                pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].bNeedRadioOFF = *((PBOOL)pbyItem0);
+                break;
+/*
+            case WLAN_CMD_DEAUTH:
+                pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].wDeAuthenReason = *((PWORD)pbyItem0);
+                break;
+*/
+
+            case WLAN_CMD_RX_PSPOLL:
+                break;
+
+            case WLAN_CMD_RADIO:
+                pDevice->eCmdQueue[pDevice->uCmdEnqueueIdx].bRadioCmd = *((PBOOL)pbyItem0);
+                break;
+
+            case WLAN_CMD_CHANGE_BBSENSITIVITY:
+                pDevice->eCommandState = WLAN_CMD_CHECK_BBSENSITIVITY_CHANGE;
+                break;
+
+            default:
+                break;
+        }
+    }
+
+    ADD_ONE_WITH_WRAP_AROUND(pDevice->uCmdEnqueueIdx, CMD_Q_SIZE);
+    pDevice->cbFreeCmdQueue--;
+
+    if (pDevice->bCmdRunning == FALSE) {
+        s_bCommandComplete(pDevice);
+    }
+    else {
+    }
+    return (TRUE);
+
+}
+
+/*
+ * Description:
+ *      Clear BSSID_SCAN cmd in CMD Queue
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext  - Pointer to the adapter
+ *      eCommand        - Command
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if success; otherwise FALSE
+ *
+ */
+BOOL bClearBSSID_SCAN (
+    IN HANDLE hDeviceContext
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+    UINT            uCmdDequeueIdx = pDevice->uCmdDequeueIdx;
+    UINT            ii;
+
+    if ((pDevice->cbFreeCmdQueue < CMD_Q_SIZE) && (uCmdDequeueIdx != pDevice->uCmdEnqueueIdx)) {
+        for (ii = 0; ii < (CMD_Q_SIZE - pDevice->cbFreeCmdQueue); ii ++) {
+            if (pDevice->eCmdQueue[uCmdDequeueIdx].eCmd == WLAN_CMD_BSSID_SCAN)
+                pDevice->eCmdQueue[uCmdDequeueIdx].eCmd = WLAN_CMD_IDLE;
+            ADD_ONE_WITH_WRAP_AROUND(uCmdDequeueIdx, CMD_Q_SIZE);
+            if (uCmdDequeueIdx == pDevice->uCmdEnqueueIdx)
+                break;
+        }
+    }
+    return TRUE;
+}
+
+//mike add:reset command timer
+VOID
+vResetCommandTimer(
+    IN HANDLE      hDeviceContext
+    )
+{
+  PSDevice        pDevice = (PSDevice)hDeviceContext;
+
+  //delete timer
+      del_timer(&pDevice->sTimerCommand);
+  //init timer
+      init_timer(&pDevice->sTimerCommand);
+    pDevice->sTimerCommand.data = (ULONG)pDevice;
+    pDevice->sTimerCommand.function = (TimerFunction)vCommandTimer;
+    pDevice->sTimerCommand.expires = RUN_AT(HZ);
+    pDevice->cbFreeCmdQueue = CMD_Q_SIZE;
+    pDevice->uCmdDequeueIdx = 0;
+    pDevice->uCmdEnqueueIdx = 0;
+    pDevice->eCommandState = WLAN_CMD_IDLE;
+    pDevice->bCmdRunning = FALSE;
+    pDevice->bCmdClear = FALSE;
+}
+
+
+#ifdef TxInSleep
+VOID
+BSSvSecondTxData(
+    IN  HANDLE      hDeviceContext
+    )
+{
+  PSDevice        pDevice = (PSDevice)hDeviceContext;
+  PSMgmtObject  pMgmt = &(pDevice->sMgmtObj);
+  pDevice->nTxDataTimeCout++;
+
+  if(pDevice->nTxDataTimeCout<4)     //don't tx data if timer less than 40s
+    {
+     // printk("mike:%s-->no data Tx not exceed the desired Time as %d\n",__FUNCTION__,
+	//  	(int)pDevice->nTxDataTimeCout);
+     pDevice->sTimerTxData.expires = RUN_AT(10*HZ);      //10s callback
+     add_timer(&pDevice->sTimerTxData);
+      return;
+    }
+
+  spin_lock_irq(&pDevice->lock);
+  #if 1
+  if(((pDevice->bLinkPass ==TRUE)&&(pMgmt->eAuthenMode < WMAC_AUTH_WPA)) ||  //open && sharekey linking
+      (pDevice->fWPA_Authened == TRUE)) {   //wpa linking
+ #else
+  if(pDevice->bLinkPass ==TRUE) {
+ #endif
+
+        //   printk("mike:%s-->InSleep Tx Data Procedure\n",__FUNCTION__);
+	  pDevice->fTxDataInSleep = TRUE;
+	  PSbSendNullPacket(pDevice);      //send null packet
+	  pDevice->fTxDataInSleep = FALSE;
+  	}
+  spin_unlock_irq(&pDevice->lock);
+
+  pDevice->sTimerTxData.expires = RUN_AT(10*HZ);      //10s callback
+  add_timer(&pDevice->sTimerTxData);
+  return;
+}
+#endif
+
diff --git a/drivers/staging/vt6655/wcmd.h b/drivers/staging/vt6655/wcmd.h
new file mode 100644
index 0000000..8c6bbc4
--- /dev/null
+++ b/drivers/staging/vt6655/wcmd.h
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: wcmd.h
+ *
+ * Purpose: Handles the management command interface functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 8, 2002
+ *
+ */
+
+#ifndef __WCMD_H__
+#define __WCMD_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+#if !defined(__80211MGR_H__)
+#include "80211mgr.h"
+#endif
+
+/*---------------------  Export Definitions -------------------------*/
+
+
+
+#define AUTHENTICATE_TIMEOUT   1000 //ms
+#define ASSOCIATE_TIMEOUT      1000 //ms
+
+// Command code
+typedef enum tagCMD_CODE {
+    WLAN_CMD_BSSID_SCAN,
+    WLAN_CMD_SSID,
+    WLAN_CMD_DISASSOCIATE,
+    WLAN_CMD_DEAUTH,
+    WLAN_CMD_RX_PSPOLL,
+    WLAN_CMD_RADIO,
+    WLAN_CMD_CHANGE_BBSENSITIVITY,
+    WLAN_CMD_SETPOWER,
+    WLAN_CMD_TBTT_WAKEUP,
+    WLAN_CMD_BECON_SEND,
+    WLAN_CMD_CHANGE_ANTENNA,
+    WLAN_CMD_REMOVE_ALLKEY,
+    WLAN_CMD_MAC_DISPOWERSAVING,
+    WLAN_CMD_11H_CHSW,
+    WLAN_CMD_RUN_AP
+} CMD_CODE, DEF* PCMD_CODE;
+
+#define CMD_Q_SIZE              32
+
+
+// Command code
+typedef enum tagCMD_STATUS {
+
+    CMD_STATUS_SUCCESS,
+    CMD_STATUS_FAILURE,
+    CMD_STATUS_RESOURCES,
+    CMD_STATUS_TIMEOUT,
+    CMD_STATUS_PENDING
+
+} CMD_STATUS, DEF* PCMD_STATUS;
+
+
+typedef struct tagCMD_ITEM {
+    CMD_CODE eCmd;
+    BYTE     abyCmdDesireSSID[WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1];
+    BOOL     bNeedRadioOFF;
+    WORD     wDeAuthenReason;
+    BOOL     bRadioCmd;
+    BOOL     bForceSCAN;
+} CMD_ITEM, DEF* PCMD_ITEM;
+
+// Command state
+typedef enum tagCMD_STATE {
+    WLAN_CMD_SCAN_START,
+    WLAN_CMD_SCAN_END,
+    WLAN_CMD_DISASSOCIATE_START,
+    WLAN_CMD_SSID_START,
+    WLAN_AUTHENTICATE_WAIT,
+    WLAN_ASSOCIATE_WAIT,
+    WLAN_DISASSOCIATE_WAIT,
+    WLAN_CMD_TX_PSPACKET_START,
+    WLAN_CMD_AP_MODE_START,
+    WLAN_CMD_RADIO_START,
+    WLAN_CMD_CHECK_BBSENSITIVITY_CHANGE,
+    WLAN_CMD_IDLE
+} CMD_STATE, DEF* PCMD_STATE;
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Types  ------------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+VOID
+vResetCommandTimer(
+    IN HANDLE      hDeviceContext
+    );
+
+VOID
+vCommandTimer (
+    IN  HANDLE hDeviceContext
+    );
+
+BOOL bClearBSSID_SCAN(
+    IN HANDLE hDeviceContext
+    );
+
+BOOL
+bScheduleCommand(
+    IN HANDLE      hDeviceContext,
+    IN CMD_CODE    eCommand,
+    IN PBYTE       pbyItem0
+    );
+
+VOID
+vCommandTimerWait(
+    IN HANDLE      hDeviceContext,
+    IN UINT MSecond
+    );
+#ifdef TxInSleep
+VOID
+BSSvSecondTxData(
+    IN  HANDLE      hDeviceContext
+    );
+#endif
+#endif //__WCMD_H__
diff --git a/drivers/staging/vt6655/wctl.c b/drivers/staging/vt6655/wctl.c
new file mode 100644
index 0000000..b4fecc2
--- /dev/null
+++ b/drivers/staging/vt6655/wctl.c
@@ -0,0 +1,261 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: wctl.c
+ *
+ * Purpose: handle WMAC duplicate filter & defragment
+ *
+ * Author: Jerry Chen
+ *
+ * Date: Jun. 27, 2002
+ *
+ * Functions:
+ *      WCTLbIsDuplicate - Test if duplicate packet
+ *      WCTLuSearchDFCB - Search DeFragment Control Database
+ *      WCTLuInsertDFCB - Insert DeFragment Control Database
+ *      WCTLbHandleFragment - Handle received fragment packet
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__WCTL_H__)
+#include "wctl.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+// static int          msglevel                =MSG_LEVEL_INFO;
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+
+/*
+ * Description:
+ *      Scan Rx cache.  Return TRUE if packet is duplicate, else
+ *      inserts in receive cache and returns FALSE.
+ *
+ * Parameters:
+ *  In:
+ *      pCache      - Receive packets history
+ *      pMACHeader  - 802.11 MAC Header of received packet
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if packet duplicate; otherwise FALSE
+ *
+ */
+
+BOOL WCTLbIsDuplicate (PSCache pCache, PS802_11Header pMACHeader)
+{
+    UINT            uIndex;
+    UINT            ii;
+    PSCacheEntry    pCacheEntry;
+
+    if (IS_FC_RETRY(pMACHeader)) {
+
+        uIndex = pCache->uInPtr;
+        for (ii = 0; ii < DUPLICATE_RX_CACHE_LENGTH; ii++) {
+            pCacheEntry = &(pCache->asCacheEntry[uIndex]);
+            if ((pCacheEntry->wFmSequence == pMACHeader->wSeqCtl) &&
+                (IS_ETH_ADDRESS_EQUAL (&(pCacheEntry->abyAddr2[0]), &(pMACHeader->abyAddr2[0])))
+                ) {
+                /* Duplicate match */
+                return TRUE;
+            }
+            ADD_ONE_WITH_WRAP_AROUND(uIndex, DUPLICATE_RX_CACHE_LENGTH);
+        }
+    }
+    /* Not fount in cache - insert */
+    pCacheEntry = &pCache->asCacheEntry[pCache->uInPtr];
+    pCacheEntry->wFmSequence = pMACHeader->wSeqCtl;
+    memcpy(&(pCacheEntry->abyAddr2[0]), &(pMACHeader->abyAddr2[0]), U_ETHER_ADDR_LEN);
+    ADD_ONE_WITH_WRAP_AROUND(pCache->uInPtr, DUPLICATE_RX_CACHE_LENGTH);
+    return FALSE;
+}
+
+/*
+ * Description:
+ *      Found if sequence number of received fragment packet in Defragment Database
+ *
+ * Parameters:
+ *  In:
+ *      pDevice     - Pointer to adapter
+ *      pMACHeader  - 802.11 MAC Header of received packet
+ *  Out:
+ *      none
+ *
+ * Return Value: index number in Defragment Database
+ *
+ */
+UINT WCTLuSearchDFCB (PSDevice pDevice, PS802_11Header pMACHeader)
+{
+UINT ii;
+
+    for(ii=0;ii<pDevice->cbDFCB;ii++) {
+        if ((pDevice->sRxDFCB[ii].bInUse == TRUE) &&
+            (IS_ETH_ADDRESS_EQUAL (&(pDevice->sRxDFCB[ii].abyAddr2[0]), &(pMACHeader->abyAddr2[0])))
+            ) {
+            //
+            return(ii);
+        }
+    }
+    return(pDevice->cbDFCB);
+}
+
+
+/*
+ * Description:
+ *      Insert received fragment packet in Defragment Database
+ *
+ * Parameters:
+ *  In:
+ *      pDevice     - Pointer to adapter
+ *      pMACHeader  - 802.11 MAC Header of received packet
+ *  Out:
+ *      none
+ *
+ * Return Value: index number in Defragment Database
+ *
+ */
+UINT WCTLuInsertDFCB (PSDevice pDevice, PS802_11Header pMACHeader)
+{
+UINT ii;
+
+    if (pDevice->cbFreeDFCB == 0)
+        return(pDevice->cbDFCB);
+    for(ii=0;ii<pDevice->cbDFCB;ii++) {
+        if (pDevice->sRxDFCB[ii].bInUse == FALSE) {
+            pDevice->cbFreeDFCB--;
+            pDevice->sRxDFCB[ii].uLifetime = pDevice->dwMaxReceiveLifetime;
+            pDevice->sRxDFCB[ii].bInUse = TRUE;
+            pDevice->sRxDFCB[ii].wSequence = (pMACHeader->wSeqCtl >> 4);
+            pDevice->sRxDFCB[ii].wFragNum = (pMACHeader->wSeqCtl & 0x000F);
+            memcpy(&(pDevice->sRxDFCB[ii].abyAddr2[0]), &(pMACHeader->abyAddr2[0]), U_ETHER_ADDR_LEN);
+            return(ii);
+        }
+    }
+    return(pDevice->cbDFCB);
+}
+
+
+/*
+ * Description:
+ *      Handle received fragment packet
+ *
+ * Parameters:
+ *  In:
+ *      pDevice         - Pointer to adapter
+ *      pMACHeader      - 802.11 MAC Header of received packet
+ *      cbFrameLength   - Frame length
+ *      bWEP            - is WEP packet
+ *  Out:
+ *      none
+ *
+ * Return Value: TRUE if it is valid fragment packet and we have resource to defragment; otherwise FALSE
+ *
+ */
+BOOL WCTLbHandleFragment (PSDevice pDevice, PS802_11Header pMACHeader, UINT cbFrameLength, BOOL bWEP, BOOL bExtIV)
+{
+UINT            uHeaderSize;
+
+
+    if (bWEP == TRUE) {
+        uHeaderSize = 28;
+        if (bExtIV)
+        // ExtIV
+            uHeaderSize +=4;
+    }
+    else {
+        uHeaderSize = 24;
+    }
+
+    if (IS_FIRST_FRAGMENT_PKT(pMACHeader)) {
+        pDevice->uCurrentDFCBIdx = WCTLuSearchDFCB(pDevice, pMACHeader);
+        if (pDevice->uCurrentDFCBIdx < pDevice->cbDFCB) {
+            // duplicate, we must flush previous DCB
+            pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].uLifetime = pDevice->dwMaxReceiveLifetime;
+            pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].wSequence = (pMACHeader->wSeqCtl >> 4);
+            pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].wFragNum = (pMACHeader->wSeqCtl & 0x000F);
+        }
+        else {
+            pDevice->uCurrentDFCBIdx = WCTLuInsertDFCB(pDevice, pMACHeader);
+            if (pDevice->uCurrentDFCBIdx == pDevice->cbDFCB) {
+                return(FALSE);
+            }
+        }
+        // reserve 4 byte to match MAC RX Buffer
+#ifdef PRIVATE_OBJ
+        pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].pbyRxBuffer = (PBYTE) (pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].ref_skb.data + 4);
+#else
+        pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].pbyRxBuffer = (PBYTE) (pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].skb->data + 4);
+#endif
+        memcpy(pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].pbyRxBuffer, pMACHeader, cbFrameLength);
+        pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].cbFrameLength = cbFrameLength;
+        pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].pbyRxBuffer += cbFrameLength;
+        pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].wFragNum++;
+        //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "First pDevice->uCurrentDFCBIdx= %d\n", pDevice->uCurrentDFCBIdx);
+        return(FALSE);
+    }
+    else {
+        pDevice->uCurrentDFCBIdx = WCTLuSearchDFCB(pDevice, pMACHeader);
+        if (pDevice->uCurrentDFCBIdx != pDevice->cbDFCB) {
+            if ((pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].wSequence == (pMACHeader->wSeqCtl >> 4)) &&
+                (pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].wFragNum == (pMACHeader->wSeqCtl & 0x000F)) &&
+                ((pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].cbFrameLength + cbFrameLength - uHeaderSize) < 2346)) {
+
+                memcpy(pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].pbyRxBuffer, ((PBYTE) (pMACHeader) + uHeaderSize), (cbFrameLength - uHeaderSize));
+                pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].cbFrameLength += (cbFrameLength - uHeaderSize);
+                pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].pbyRxBuffer += (cbFrameLength - uHeaderSize);
+                pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].wFragNum++;
+                //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Second pDevice->uCurrentDFCBIdx= %d\n", pDevice->uCurrentDFCBIdx);
+            }
+            else {
+                // seq error or frag # error flush DFCB
+                pDevice->cbFreeDFCB++;
+                pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].bInUse = FALSE;
+                return(FALSE);
+            }
+        }
+        else {
+            return(FALSE);
+        }
+        if (IS_LAST_FRAGMENT_PKT(pMACHeader)) {
+            //enq defragcontrolblock
+            pDevice->cbFreeDFCB++;
+            pDevice->sRxDFCB[pDevice->uCurrentDFCBIdx].bInUse = FALSE;
+            //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Last pDevice->uCurrentDFCBIdx= %d\n", pDevice->uCurrentDFCBIdx);
+            return(TRUE);
+        }
+        return(FALSE);
+    }
+}
+
+
diff --git a/drivers/staging/vt6655/wctl.h b/drivers/staging/vt6655/wctl.h
new file mode 100644
index 0000000..f75ca59
--- /dev/null
+++ b/drivers/staging/vt6655/wctl.h
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: wctl.h
+ *
+ * Purpose:
+ *
+ * Author: Jerry Chen
+ *
+ * Date: Jun. 27, 2002
+ *
+ */
+
+
+#ifndef __WCTL_H__
+#define __WCTL_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+#define IS_TYPE_DATA(pMACHeader)                                                        \
+    ((((PS802_11Header) pMACHeader)->wFrameCtl & TYPE_802_11_MASK) == TYPE_802_11_DATA)
+
+#define IS_TYPE_MGMT(pMACHeader)                                                        \
+    ((((PS802_11Header) pMACHeader)->wFrameCtl & TYPE_802_11_MASK) == TYPE_802_11_MGMT)
+
+#define IS_TYPE_CONTROL(pMACHeader)                                                     \
+    ((((PS802_11Header) pMACHeader)->wFrameCtl & TYPE_802_11_MASK) == TYPE_802_11_CTL)
+
+#define IS_FC_MOREDATA(pMACHeader)                                                      \
+    ((((PS802_11Header) pMACHeader)->wFrameCtl & FC_MOREDATA) == FC_MOREDATA)
+
+#define IS_FC_POWERMGT(pMACHeader)                                                      \
+    ((((PS802_11Header) pMACHeader)->wFrameCtl & FC_POWERMGT) == FC_POWERMGT)
+
+#define IS_FC_RETRY(pMACHeader)                                                         \
+    ((((PS802_11Header) pMACHeader)->wFrameCtl & FC_RETRY) == FC_RETRY)
+
+#define IS_FC_WEP(pMACHeader)                                                           \
+    ((((PS802_11Header) pMACHeader)->wFrameCtl & FC_WEP) == FC_WEP)
+
+#ifdef __BIG_ENDIAN
+
+#define IS_FRAGMENT_PKT(pMACHeader)                                                     \
+    (((((PS802_11Header) pMACHeader)->wFrameCtl & FC_MOREFRAG) != 0) |                  \
+     ((((PS802_11Header) pMACHeader)->wSeqCtl & 0x0F00) != 0))
+
+#define IS_FIRST_FRAGMENT_PKT(pMACHeader)                                               \
+    ((((PS802_11Header) pMACHeader)->wSeqCtl & 0x0F00) == 0)
+
+#else
+
+#define IS_FRAGMENT_PKT(pMACHeader)                                                     \
+    (((((PS802_11Header) pMACHeader)->wFrameCtl & FC_MOREFRAG) != 0) |                  \
+     ((((PS802_11Header) pMACHeader)->wSeqCtl & 0x000F) != 0))
+
+#define IS_FIRST_FRAGMENT_PKT(pMACHeader)                                               \
+    ((((PS802_11Header) pMACHeader)->wSeqCtl & 0x000F) == 0)
+
+#endif//#ifdef __BIG_ENDIAN
+
+#define IS_LAST_FRAGMENT_PKT(pMACHeader)                                                \
+    ((((PS802_11Header) pMACHeader)->wFrameCtl & FC_MOREFRAG) == 0)
+
+#define IS_CTL_PSPOLL(pMACHeader)                                                       \
+    ((((PS802_11Header) pMACHeader)->wFrameCtl & TYPE_SUBTYPE_MASK) == TYPE_CTL_PSPOLL)
+
+
+#define ADD_ONE_WITH_WRAP_AROUND(uVar, uModulo) {   \
+    if ((uVar) >= ((uModulo) - 1))                  \
+        (uVar) = 0;                                 \
+    else                                            \
+        (uVar)++;                                   \
+}
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+BOOL WCTLbIsDuplicate(PSCache pCache, PS802_11Header pMACHeader);
+BOOL WCTLbHandleFragment(PSDevice pDevice, PS802_11Header pMACHeader, UINT cbFrameLength, BOOL bWEP, BOOL bExtIV);
+UINT WCTLuSearchDFCB(PSDevice pDevice, PS802_11Header pMACHeader);
+UINT WCTLuInsertDFCB(PSDevice pDevice, PS802_11Header pMACHeader);
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+
+#endif // __WCTL_H__
+
+
+
diff --git a/drivers/staging/vt6655/wmgr.c b/drivers/staging/vt6655/wmgr.c
new file mode 100644
index 0000000..c0886ed
--- /dev/null
+++ b/drivers/staging/vt6655/wmgr.c
@@ -0,0 +1,5088 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: wmgr.c
+ *
+ * Purpose: Handles the 802.11 management functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 8, 2002
+ *
+ * Functions:
+ *      nsMgrObjectInitial - Initialize Management Objet data structure
+ *      vMgrObjectReset - Reset Management Objet data structure
+ *      vMgrAssocBeginSta - Start associate function
+ *      vMgrReAssocBeginSta - Start reassociate function
+ *      vMgrDisassocBeginSta - Start disassociate function
+ *      s_vMgrRxAssocRequest - Handle Rcv associate_request
+ *      s_vMgrRxAssocResponse - Handle Rcv associate_response
+ *      vMrgAuthenBeginSta - Start authentication function
+ *      vMgrDeAuthenDeginSta - Start deauthentication function
+ *      s_vMgrRxAuthentication - Handle Rcv authentication
+ *      s_vMgrRxAuthenSequence_1 - Handle Rcv authentication sequence 1
+ *      s_vMgrRxAuthenSequence_2 - Handle Rcv authentication sequence 2
+ *      s_vMgrRxAuthenSequence_3 - Handle Rcv authentication sequence 3
+ *      s_vMgrRxAuthenSequence_4 - Handle Rcv authentication sequence 4
+ *      s_vMgrRxDisassociation - Handle Rcv disassociation
+ *      s_vMgrRxBeacon - Handle Rcv Beacon
+ *      vMgrCreateOwnIBSS - Create ad_hoc IBSS or AP BSS
+ *      vMgrJoinBSSBegin - Join BSS function
+ *      s_vMgrSynchBSS - Synch & adopt BSS parameters
+ *      s_MgrMakeBeacon - Create Baecon frame
+ *      s_MgrMakeProbeResponse - Create Probe Response frame
+ *      s_MgrMakeAssocRequest - Create Associate Request frame
+ *      s_MgrMakeReAssocRequest - Create ReAssociate Request frame
+ *      s_vMgrRxProbeResponse - Handle Rcv probe_response
+ *      s_vMrgRxProbeRequest - Handle Rcv probe_request
+ *      bMgrPrepareBeaconToSend - Prepare Beacon frame
+ *      s_vMgrLogStatus - Log 802.11 Status
+ *      vMgrRxManagePacket - Rcv management frame dispatch function
+ *      s_vMgrFormatTIM- Assember TIM field of beacon
+ *      vMgrTimerInit- Initial 1-sec and command call back funtions
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TBIT_H__)
+#include "tbit.h"
+#endif
+#if !defined(__DESC_H__)
+#include "desc.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+#if !defined(__80211MGR_H__)
+#include "80211mgr.h"
+#endif
+#if !defined(__WMGR_H__)
+#include "wmgr.h"
+#endif
+#if !defined(__WCMD_H__)
+#include "wcmd.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__BSSDB_H__)
+#include "bssdb.h"
+#endif
+#if !defined(__POWER_H__)
+#include "power.h"
+#endif
+#if !defined(__DATARATE_H__)
+#include "datarate.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+#if !defined(__RXTX_H__)
+#include "rxtx.h"
+#endif
+#if !defined(__WPA_H__)
+#include "wpa.h"
+#endif
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__IOWPA_H__)
+#include "iowpa.h"
+#endif
+
+#define	PLICE_DEBUG
+
+/*---------------------  Static Definitions -------------------------*/
+
+
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+static int          msglevel                =MSG_LEVEL_INFO;
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+
+/*---------------------  Static Functions  --------------------------*/
+//2008-8-4 <add> by chester
+static BOOL ChannelExceedZoneType(
+    IN PSDevice pDevice,
+    IN BYTE byCurrChannel
+    );
+// Association/diassociation functions
+static
+PSTxMgmtPacket
+s_MgrMakeAssocRequest(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PBYTE pDAddr,
+    IN WORD wCurrCapInfo,
+    IN WORD wListenInterval,
+    IN PWLAN_IE_SSID pCurrSSID,
+    IN PWLAN_IE_SUPP_RATES pCurrRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+    );
+
+static
+VOID
+s_vMgrRxAssocRequest(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket,
+    IN UINT  uNodeIndex
+    );
+
+static
+PSTxMgmtPacket
+s_MgrMakeReAssocRequest(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PBYTE pDAddr,
+    IN WORD wCurrCapInfo,
+    IN WORD wListenInterval,
+    IN PWLAN_IE_SSID pCurrSSID,
+    IN PWLAN_IE_SUPP_RATES pCurrRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+    );
+
+static
+VOID
+s_vMgrRxAssocResponse(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket,
+    IN BOOL bReAssocType
+    );
+
+static
+VOID
+s_vMgrRxDisassociation(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket
+    );
+
+// Authentication/deauthen functions
+static
+VOID
+s_vMgrRxAuthenSequence_1(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PWLAN_FR_AUTHEN pFrame
+    );
+
+static
+VOID
+s_vMgrRxAuthenSequence_2(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PWLAN_FR_AUTHEN pFrame
+    );
+
+static
+VOID
+s_vMgrRxAuthenSequence_3(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PWLAN_FR_AUTHEN pFrame
+    );
+
+static
+VOID
+s_vMgrRxAuthenSequence_4(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PWLAN_FR_AUTHEN pFrame
+    );
+
+static
+VOID
+s_vMgrRxAuthentication(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket
+    );
+
+static
+VOID
+s_vMgrRxDeauthentication(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket
+    );
+
+// Scan functions
+// probe request/response functions
+static
+VOID
+s_vMgrRxProbeRequest(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket
+    );
+
+static
+VOID
+s_vMgrRxProbeResponse(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket
+    );
+
+// beacon functions
+static
+VOID
+s_vMgrRxBeacon(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket,
+    IN BOOL bInScan
+    );
+
+static
+VOID
+s_vMgrFormatTIM(
+    IN PSMgmtObject pMgmt,
+    IN PWLAN_IE_TIM pTIM
+    );
+
+static
+PSTxMgmtPacket
+s_MgrMakeBeacon(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN WORD wCurrCapInfo,
+    IN WORD wCurrBeaconPeriod,
+    IN UINT uCurrChannel,
+    IN WORD wCurrATIMWinodw,
+    IN PWLAN_IE_SSID pCurrSSID,
+    IN PBYTE pCurrBSSID,
+    IN PWLAN_IE_SUPP_RATES pCurrSuppRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+    );
+
+
+// Association response
+static
+PSTxMgmtPacket
+s_MgrMakeAssocResponse(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN WORD wCurrCapInfo,
+    IN WORD wAssocStatus,
+    IN WORD wAssocAID,
+    IN PBYTE pDstAddr,
+    IN PWLAN_IE_SUPP_RATES pCurrSuppRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+    );
+
+// ReAssociation response
+static
+PSTxMgmtPacket
+s_MgrMakeReAssocResponse(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN WORD wCurrCapInfo,
+    IN WORD wAssocStatus,
+    IN WORD wAssocAID,
+    IN PBYTE pDstAddr,
+    IN PWLAN_IE_SUPP_RATES pCurrSuppRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+    );
+
+// Probe response
+static
+PSTxMgmtPacket
+s_MgrMakeProbeResponse(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN WORD wCurrCapInfo,
+    IN WORD wCurrBeaconPeriod,
+    IN UINT uCurrChannel,
+    IN WORD wCurrATIMWinodw,
+    IN PBYTE pDstAddr,
+    IN PWLAN_IE_SSID pCurrSSID,
+    IN PBYTE pCurrBSSID,
+    IN PWLAN_IE_SUPP_RATES pCurrSuppRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates,
+    IN BYTE byPHYType
+    );
+
+// received status
+static
+VOID
+s_vMgrLogStatus(
+    IN PSMgmtObject pMgmt,
+    IN WORD wStatus
+    );
+
+
+static
+VOID
+s_vMgrSynchBSS (
+    IN PSDevice      pDevice,
+    IN UINT          uBSSMode,
+    IN PKnownBSS     pCurr,
+    OUT PCMD_STATUS  pStatus
+    );
+
+
+static BOOL
+s_bCipherMatch (
+    IN PKnownBSS                        pBSSNode,
+    IN NDIS_802_11_ENCRYPTION_STATUS    EncStatus,
+    OUT PBYTE                           pbyCCSPK,
+    OUT PBYTE                           pbyCCSGK
+    );
+
+
+ static VOID  Encyption_Rebuild(
+    IN PSDevice pDevice,
+    IN PKnownBSS pCurr
+ );
+/*
+static
+VOID
+s_vProbeChannel(
+    IN PSDevice pDevice
+    );
+
+static
+VOID
+s_vListenChannel(
+    IN PSDevice pDevice
+    );
+
+static
+PSTxMgmtPacket
+s_MgrMakeProbeRequest(
+    IN PSMgmtObject pMgmt,
+    IN PBYTE pScanBSSID,
+    IN PWLAN_IE_SSID pSSID,
+    IN PWLAN_IE_SUPP_RATES pCurrRates
+    );
+*/
+
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+/*+
+ *
+ * Routine Description:
+ *    Allocates and initializes the Management object.
+ *
+ * Return Value:
+ *    Ndis_staus.
+ *
+-*/
+
+VOID
+vMgrObjectInit(
+    IN  HANDLE hDeviceContext
+    )
+{
+    PSDevice     pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    int ii;
+
+
+    pMgmt->pbyPSPacketPool = &pMgmt->byPSPacketPool[0];
+    pMgmt->pbyMgmtPacketPool = &pMgmt->byMgmtPacketPool[0];
+    pMgmt->uCurrChannel = pDevice->uChannel;
+    for(ii=0;ii<WLAN_BSSID_LEN;ii++) {
+        pMgmt->abyDesireBSSID[ii] = 0xFF;
+    }
+    pMgmt->sAssocInfo.AssocInfo.Length = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION);
+    //memset(pMgmt->abyDesireSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN +1);
+    pMgmt->byCSSPK = KEY_CTL_NONE;
+    pMgmt->byCSSGK = KEY_CTL_NONE;
+    pMgmt->wIBSSBeaconPeriod = DEFAULT_IBSS_BI;
+    BSSvClearBSSList((HANDLE)pDevice, FALSE);
+
+    return;
+}
+
+/*+
+ *
+ * Routine Description:
+ *    Initializes timer object
+ *
+ * Return Value:
+ *    Ndis_staus.
+ *
+-*/
+
+void
+vMgrTimerInit(
+    IN  HANDLE hDeviceContext
+    )
+{
+    PSDevice     pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+
+
+    init_timer(&pMgmt->sTimerSecondCallback);
+    pMgmt->sTimerSecondCallback.data = (ULONG)pDevice;
+    pMgmt->sTimerSecondCallback.function = (TimerFunction)BSSvSecondCallBack;
+    pMgmt->sTimerSecondCallback.expires = RUN_AT(HZ);
+
+    init_timer(&pDevice->sTimerCommand);
+    pDevice->sTimerCommand.data = (ULONG)pDevice;
+    pDevice->sTimerCommand.function = (TimerFunction)vCommandTimer;
+    pDevice->sTimerCommand.expires = RUN_AT(HZ);
+
+   #ifdef TxInSleep
+    init_timer(&pDevice->sTimerTxData);
+    pDevice->sTimerTxData.data = (ULONG)pDevice;
+    pDevice->sTimerTxData.function = (TimerFunction)BSSvSecondTxData;
+    pDevice->sTimerTxData.expires = RUN_AT(10*HZ);      //10s callback
+    pDevice->fTxDataInSleep = FALSE;
+    pDevice->IsTxDataTrigger = FALSE;
+    pDevice->nTxDataTimeCout = 0;
+   #endif
+
+    pDevice->cbFreeCmdQueue = CMD_Q_SIZE;
+    pDevice->uCmdDequeueIdx = 0;
+    pDevice->uCmdEnqueueIdx = 0;
+
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *    Reset the management object  structure.
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrObjectReset(
+    IN  HANDLE hDeviceContext
+    )
+{
+    PSDevice         pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject        pMgmt = pDevice->pMgmt;
+
+    pMgmt->eCurrMode = WMAC_MODE_STANDBY;
+    pMgmt->eCurrState = WMAC_STATE_IDLE;
+    pDevice->bEnablePSMode = FALSE;
+    // TODO: timer
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *    Start the station association procedure.  Namely, send an
+ *    association request frame to the AP.
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+VOID
+vMgrAssocBeginSta(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject pMgmt,
+    OUT PCMD_STATUS pStatus
+    )
+{
+    PSDevice             pDevice = (PSDevice)hDeviceContext;
+    PSTxMgmtPacket          pTxPacket;
+
+
+    pMgmt->wCurrCapInfo = 0;
+    pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_ESS(1);
+    if (pDevice->bEncryptionEnable) {
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_PRIVACY(1);
+    }
+    // always allow receive short preamble
+    //if (pDevice->byPreambleType == 1) {
+    //    pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTPREAMBLE(1);
+    //}
+    pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTPREAMBLE(1);
+    if (pMgmt->wListenInterval == 0)
+        pMgmt->wListenInterval = 1;    // at least one.
+
+    // ERP Phy (802.11g) should support short preamble.
+    if (pMgmt->eCurrentPHYMode == PHY_TYPE_11G) {
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTPREAMBLE(1);
+        if (CARDbIsShorSlotTime(pMgmt->pAdapter) == TRUE) {
+            pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTSLOTTIME(1);
+        }
+    } else if (pMgmt->eCurrentPHYMode == PHY_TYPE_11B) {
+        if (CARDbIsShortPreamble(pMgmt->pAdapter) == TRUE) {
+            pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTPREAMBLE(1);
+        }
+    }
+    if (pMgmt->b11hEnable == TRUE)
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SPECTRUMMNG(1);
+
+    /* build an assocreq frame and send it */
+    pTxPacket = s_MgrMakeAssocRequest
+                (
+                  pDevice,
+                  pMgmt,
+                  pMgmt->abyCurrBSSID,
+                  pMgmt->wCurrCapInfo,
+                  pMgmt->wListenInterval,
+                  (PWLAN_IE_SSID)pMgmt->abyCurrSSID,
+                  (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                  (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates
+                );
+
+    if (pTxPacket != NULL ){
+        /* send the frame */
+        *pStatus = csMgmt_xmit(pDevice, pTxPacket);
+        if (*pStatus == CMD_STATUS_PENDING) {
+            pMgmt->eCurrState = WMAC_STATE_ASSOCPENDING;
+            *pStatus = CMD_STATUS_SUCCESS;
+        }
+    }
+    else
+        *pStatus = CMD_STATUS_RESOURCES;
+
+    return ;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *    Start the station re-association procedure.
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrReAssocBeginSta(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject pMgmt,
+    OUT PCMD_STATUS pStatus
+    )
+{
+    PSDevice             pDevice = (PSDevice)hDeviceContext;
+    PSTxMgmtPacket          pTxPacket;
+
+
+
+    pMgmt->wCurrCapInfo = 0;
+    pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_ESS(1);
+    if (pDevice->bEncryptionEnable) {
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_PRIVACY(1);
+    }
+
+    //if (pDevice->byPreambleType == 1) {
+    //    pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTPREAMBLE(1);
+    //}
+    pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTPREAMBLE(1);
+
+    if (pMgmt->wListenInterval == 0)
+        pMgmt->wListenInterval = 1;    // at least one.
+
+
+    // ERP Phy (802.11g) should support short preamble.
+    if (pMgmt->eCurrentPHYMode == PHY_TYPE_11G) {
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTPREAMBLE(1);
+        if (CARDbIsShorSlotTime(pMgmt->pAdapter) == TRUE) {
+            pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTSLOTTIME(1);
+        }
+    } else if (pMgmt->eCurrentPHYMode == PHY_TYPE_11B) {
+        if (CARDbIsShortPreamble(pMgmt->pAdapter) == TRUE) {
+            pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTPREAMBLE(1);
+        }
+    }
+    if (pMgmt->b11hEnable == TRUE)
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SPECTRUMMNG(1);
+
+
+    pTxPacket = s_MgrMakeReAssocRequest
+                (
+                  pDevice,
+                  pMgmt,
+                  pMgmt->abyCurrBSSID,
+                  pMgmt->wCurrCapInfo,
+                  pMgmt->wListenInterval,
+                  (PWLAN_IE_SSID)pMgmt->abyCurrSSID,
+                  (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                  (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates
+                );
+
+    if (pTxPacket != NULL ){
+        /* send the frame */
+        *pStatus = csMgmt_xmit(pDevice, pTxPacket);
+        if (*pStatus != CMD_STATUS_PENDING) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:Reassociation tx failed.\n");
+        }
+        else {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:Reassociation tx sending.\n");
+        }
+    }
+
+
+    return ;
+}
+
+/*+
+ *
+ * Routine Description:
+ *    Send an dis-association request frame to the AP.
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrDisassocBeginSta(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject pMgmt,
+    IN  PBYTE  abyDestAddress,
+    IN  WORD    wReason,
+    OUT PCMD_STATUS pStatus
+    )
+{
+    PSDevice            pDevice = (PSDevice)hDeviceContext;
+    PSTxMgmtPacket      pTxPacket = NULL;
+    WLAN_FR_DISASSOC    sFrame;
+
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_DISASSOC_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+
+    // Setup the sFrame structure
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_DISASSOC_FR_MAXLEN;
+
+    // format fixed field frame structure
+    vMgrEncodeDisassociation(&sFrame);
+
+    // Setup the header
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+        (
+        WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+        WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_DISASSOC)
+        ));
+
+    memcpy( sFrame.pHdr->sA3.abyAddr1, abyDestAddress, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+
+    // Set reason code
+    *(sFrame.pwReason) = cpu_to_le16(wReason);
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+
+    // send the frame
+    *pStatus = csMgmt_xmit(pDevice, pTxPacket);
+    if (*pStatus == CMD_STATUS_PENDING) {
+        pMgmt->eCurrState = WMAC_STATE_IDLE;
+        *pStatus = CMD_STATUS_SUCCESS;
+    };
+
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:(AP function)
+ *    Handle incoming station association request frames.
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+static
+VOID
+s_vMgrRxAssocRequest(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket,
+    IN UINT uNodeIndex
+    )
+{
+    WLAN_FR_ASSOCREQ    sFrame;
+    CMD_STATUS          Status;
+    PSTxMgmtPacket      pTxPacket;
+    WORD                wAssocStatus = 0;
+    WORD                wAssocAID = 0;
+    UINT                uRateLen = WLAN_RATES_MAXLEN;
+    BYTE                abyCurrSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1];
+    BYTE                abyCurrExtSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1];
+
+
+    if (pMgmt->eCurrMode != WMAC_MODE_ESS_AP)
+        return;
+    //  node index not found
+    if (!uNodeIndex)
+        return;
+
+    //check if node is authenticated
+    //decode the frame
+    memset(&sFrame, 0, sizeof(WLAN_FR_ASSOCREQ));
+    memset(abyCurrSuppRates, 0, WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1);
+    memset(abyCurrExtSuppRates, 0, WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1);
+    sFrame.len = pRxPacket->cbMPDULen;
+    sFrame.pBuf = (PBYTE)pRxPacket->p80211Header;
+
+    vMgrDecodeAssocRequest(&sFrame);
+
+    if (pMgmt->sNodeDBTable[uNodeIndex].eNodeState >= NODE_AUTH) {
+        pMgmt->sNodeDBTable[uNodeIndex].eNodeState = NODE_ASSOC;
+        pMgmt->sNodeDBTable[uNodeIndex].wCapInfo = cpu_to_le16(*sFrame.pwCapInfo);
+        pMgmt->sNodeDBTable[uNodeIndex].wListenInterval = cpu_to_le16(*sFrame.pwListenInterval);
+        pMgmt->sNodeDBTable[uNodeIndex].bPSEnable =
+                WLAN_GET_FC_PWRMGT(sFrame.pHdr->sA3.wFrameCtl) ? TRUE : FALSE;
+        // Todo: check sta basic rate, if ap can't support, set status code
+        if (pDevice->eCurrentPHYType == PHY_TYPE_11B) {
+            uRateLen = WLAN_RATES_MAXLEN_11B;
+        }
+        abyCurrSuppRates[0] = WLAN_EID_SUPP_RATES;
+        abyCurrSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)sFrame.pSuppRates,
+                                         (PWLAN_IE_SUPP_RATES)abyCurrSuppRates,
+                                         uRateLen);
+        abyCurrExtSuppRates[0] = WLAN_EID_EXTSUPP_RATES;
+        if (pDevice->eCurrentPHYType == PHY_TYPE_11G) {
+            abyCurrExtSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)sFrame.pExtSuppRates,
+                                                (PWLAN_IE_SUPP_RATES)abyCurrExtSuppRates,
+                                                uRateLen);
+        } else {
+            abyCurrExtSuppRates[1] = 0;
+        }
+
+
+        RATEvParseMaxRate((PVOID)pDevice,
+                           (PWLAN_IE_SUPP_RATES)abyCurrSuppRates,
+                           (PWLAN_IE_SUPP_RATES)abyCurrExtSuppRates,
+                           FALSE, // do not change our basic rate
+                           &(pMgmt->sNodeDBTable[uNodeIndex].wMaxBasicRate),
+                           &(pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate),
+                           &(pMgmt->sNodeDBTable[uNodeIndex].wSuppRate),
+                           &(pMgmt->sNodeDBTable[uNodeIndex].byTopCCKBasicRate),
+                           &(pMgmt->sNodeDBTable[uNodeIndex].byTopOFDMBasicRate)
+                          );
+
+        // set max tx rate
+        pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate =
+                pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate;
+#ifdef	PLICE_DEBUG
+	printk("RxAssocRequest:wTxDataRate is %d\n",pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate);
+#endif
+		// Todo: check sta preamble, if ap can't support, set status code
+        pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble =
+                WLAN_GET_CAP_INFO_SHORTPREAMBLE(*sFrame.pwCapInfo);
+        pMgmt->sNodeDBTable[uNodeIndex].bShortSlotTime =
+                WLAN_GET_CAP_INFO_SHORTSLOTTIME(*sFrame.pwCapInfo);
+        pMgmt->sNodeDBTable[uNodeIndex].wAID = (WORD)uNodeIndex;
+        wAssocStatus = WLAN_MGMT_STATUS_SUCCESS;
+        wAssocAID = (WORD)uNodeIndex;
+        // check if ERP support
+        if(pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate > RATE_11M)
+           pMgmt->sNodeDBTable[uNodeIndex].bERPExist = TRUE;
+
+        if (pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate <= RATE_11M) {
+            // B only STA join
+            pDevice->bProtectMode = TRUE;
+            pDevice->bNonERPPresent = TRUE;
+        }
+        if (pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble == FALSE) {
+            pDevice->bBarkerPreambleMd = TRUE;
+        }
+
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "Associate AID= %d \n", wAssocAID);
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "MAC=%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X \n",
+                   sFrame.pHdr->sA3.abyAddr2[0],
+                   sFrame.pHdr->sA3.abyAddr2[1],
+                   sFrame.pHdr->sA3.abyAddr2[2],
+                   sFrame.pHdr->sA3.abyAddr2[3],
+                   sFrame.pHdr->sA3.abyAddr2[4],
+                   sFrame.pHdr->sA3.abyAddr2[5]
+                  ) ;
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "Max Support rate = %d \n",
+                   pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate);
+    }//else { TODO: received STA under state1 handle }
+    else {
+        return;
+    }
+
+
+    // assoc response reply..
+    pTxPacket = s_MgrMakeAssocResponse
+                (
+                  pDevice,
+                  pMgmt,
+                  pMgmt->wCurrCapInfo,
+                  wAssocStatus,
+                  wAssocAID,
+                  sFrame.pHdr->sA3.abyAddr2,
+                  (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                  (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates
+                );
+    if (pTxPacket != NULL ){
+
+        if (pDevice->bEnableHostapd) {
+            return;
+        }
+        /* send the frame */
+        Status = csMgmt_xmit(pDevice, pTxPacket);
+        if (Status != CMD_STATUS_PENDING) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:Assoc response tx failed\n");
+        }
+        else {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:Assoc response tx sending..\n");
+        }
+
+    }
+
+    return;
+}
+
+
+/*+
+ *
+ * Description:(AP function)
+ *      Handle incoming station re-association request frames.
+ *
+ * Parameters:
+ *  In:
+ *      pMgmt           - Management Object structure
+ *      pRxPacket       - Received Packet
+ *  Out:
+ *      none
+ *
+ * Return Value: None.
+ *
+-*/
+
+static
+VOID
+s_vMgrRxReAssocRequest(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket,
+    IN UINT uNodeIndex
+    )
+{
+    WLAN_FR_REASSOCREQ    sFrame;
+    CMD_STATUS          Status;
+    PSTxMgmtPacket      pTxPacket;
+    WORD                wAssocStatus = 0;
+    WORD                wAssocAID = 0;
+    UINT                uRateLen = WLAN_RATES_MAXLEN;
+    BYTE                abyCurrSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1];
+    BYTE                abyCurrExtSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1];
+
+    if (pMgmt->eCurrMode != WMAC_MODE_ESS_AP)
+        return;
+    //  node index not found
+    if (!uNodeIndex)
+        return;
+    //check if node is authenticated
+    //decode the frame
+    memset(&sFrame, 0, sizeof(WLAN_FR_REASSOCREQ));
+    sFrame.len = pRxPacket->cbMPDULen;
+    sFrame.pBuf = (PBYTE)pRxPacket->p80211Header;
+    vMgrDecodeReassocRequest(&sFrame);
+
+    if (pMgmt->sNodeDBTable[uNodeIndex].eNodeState >= NODE_AUTH) {
+        pMgmt->sNodeDBTable[uNodeIndex].eNodeState = NODE_ASSOC;
+        pMgmt->sNodeDBTable[uNodeIndex].wCapInfo = cpu_to_le16(*sFrame.pwCapInfo);
+        pMgmt->sNodeDBTable[uNodeIndex].wListenInterval = cpu_to_le16(*sFrame.pwListenInterval);
+        pMgmt->sNodeDBTable[uNodeIndex].bPSEnable =
+                WLAN_GET_FC_PWRMGT(sFrame.pHdr->sA3.wFrameCtl) ? TRUE : FALSE;
+        // Todo: check sta basic rate, if ap can't support, set status code
+
+        if (pDevice->eCurrentPHYType == PHY_TYPE_11B) {
+            uRateLen = WLAN_RATES_MAXLEN_11B;
+        }
+
+        abyCurrSuppRates[0] = WLAN_EID_SUPP_RATES;
+        abyCurrSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)sFrame.pSuppRates,
+                                         (PWLAN_IE_SUPP_RATES)abyCurrSuppRates,
+                                         uRateLen);
+        abyCurrExtSuppRates[0] = WLAN_EID_EXTSUPP_RATES;
+        if (pDevice->eCurrentPHYType == PHY_TYPE_11G) {
+            abyCurrExtSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)sFrame.pExtSuppRates,
+                                                (PWLAN_IE_SUPP_RATES)abyCurrExtSuppRates,
+                                                uRateLen);
+        } else {
+            abyCurrExtSuppRates[1] = 0;
+        }
+
+
+        RATEvParseMaxRate((PVOID)pDevice,
+                          (PWLAN_IE_SUPP_RATES)abyCurrSuppRates,
+                          (PWLAN_IE_SUPP_RATES)abyCurrExtSuppRates,
+                           FALSE, // do not change our basic rate
+                           &(pMgmt->sNodeDBTable[uNodeIndex].wMaxBasicRate),
+                           &(pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate),
+                           &(pMgmt->sNodeDBTable[uNodeIndex].wSuppRate),
+                           &(pMgmt->sNodeDBTable[uNodeIndex].byTopCCKBasicRate),
+                           &(pMgmt->sNodeDBTable[uNodeIndex].byTopOFDMBasicRate)
+                          );
+
+        // set max tx rate
+        pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate =
+                pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate;
+#ifdef	PLICE_DEBUG
+	printk("RxReAssocRequest:TxDataRate is %d\n",pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate);
+#endif
+		// Todo: check sta preamble, if ap can't support, set status code
+        pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble =
+                WLAN_GET_CAP_INFO_SHORTPREAMBLE(*sFrame.pwCapInfo);
+        pMgmt->sNodeDBTable[uNodeIndex].bShortSlotTime =
+                WLAN_GET_CAP_INFO_SHORTSLOTTIME(*sFrame.pwCapInfo);
+        pMgmt->sNodeDBTable[uNodeIndex].wAID = (WORD)uNodeIndex;
+        wAssocStatus = WLAN_MGMT_STATUS_SUCCESS;
+        wAssocAID = (WORD)uNodeIndex;
+
+        // if suppurt ERP
+        if(pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate > RATE_11M)
+           pMgmt->sNodeDBTable[uNodeIndex].bERPExist = TRUE;
+
+        if (pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate <= RATE_11M) {
+            // B only STA join
+            pDevice->bProtectMode = TRUE;
+            pDevice->bNonERPPresent = TRUE;
+        }
+        if (pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble == FALSE) {
+            pDevice->bBarkerPreambleMd = TRUE;
+        }
+
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "Rx ReAssociate AID= %d \n", wAssocAID);
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "MAC=%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X \n",
+                   sFrame.pHdr->sA3.abyAddr2[0],
+                   sFrame.pHdr->sA3.abyAddr2[1],
+                   sFrame.pHdr->sA3.abyAddr2[2],
+                   sFrame.pHdr->sA3.abyAddr2[3],
+                   sFrame.pHdr->sA3.abyAddr2[4],
+                   sFrame.pHdr->sA3.abyAddr2[5]
+                  ) ;
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "Max Support rate = %d \n",
+                   pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate);
+
+    }
+
+
+    // assoc response reply..
+    pTxPacket = s_MgrMakeReAssocResponse
+                (
+                  pDevice,
+                  pMgmt,
+                  pMgmt->wCurrCapInfo,
+                  wAssocStatus,
+                  wAssocAID,
+                  sFrame.pHdr->sA3.abyAddr2,
+                  (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                  (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates
+                );
+
+    if (pTxPacket != NULL ){
+        /* send the frame */
+        if (pDevice->bEnableHostapd) {
+            return;
+        }
+        Status = csMgmt_xmit(pDevice, pTxPacket);
+        if (Status != CMD_STATUS_PENDING) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:ReAssoc response tx failed\n");
+        }
+        else {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:ReAssoc response tx sending..\n");
+        }
+    }
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *    Handle incoming association response frames.
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+static
+VOID
+s_vMgrRxAssocResponse(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket,
+    IN BOOL bReAssocType
+    )
+{
+    WLAN_FR_ASSOCRESP   sFrame;
+    PWLAN_IE_SSID   pItemSSID;
+    PBYTE   pbyIEs;
+    viawget_wpa_header *wpahdr;
+
+
+
+    if (pMgmt->eCurrState == WMAC_STATE_ASSOCPENDING ||
+         pMgmt->eCurrState == WMAC_STATE_ASSOC) {
+
+        sFrame.len = pRxPacket->cbMPDULen;
+        sFrame.pBuf = (PBYTE)pRxPacket->p80211Header;
+        // decode the frame
+        vMgrDecodeAssocResponse(&sFrame);
+        if ((sFrame.pwCapInfo == 0) ||
+            (sFrame.pwStatus == 0) ||
+            (sFrame.pwAid == 0) ||
+            (sFrame.pSuppRates == 0)){
+            DBG_PORT80(0xCC);
+            return;
+        };
+
+        pMgmt->sAssocInfo.AssocInfo.ResponseFixedIEs.Capabilities = *(sFrame.pwCapInfo);
+        pMgmt->sAssocInfo.AssocInfo.ResponseFixedIEs.StatusCode = *(sFrame.pwStatus);
+        pMgmt->sAssocInfo.AssocInfo.ResponseFixedIEs.AssociationId = *(sFrame.pwAid);
+        pMgmt->sAssocInfo.AssocInfo.AvailableResponseFixedIEs |= 0x07;
+
+        pMgmt->sAssocInfo.AssocInfo.ResponseIELength = sFrame.len - 24 - 6;
+        pMgmt->sAssocInfo.AssocInfo.OffsetResponseIEs = pMgmt->sAssocInfo.AssocInfo.OffsetRequestIEs + pMgmt->sAssocInfo.AssocInfo.RequestIELength;
+        pbyIEs = pMgmt->sAssocInfo.abyIEs;
+        pbyIEs += pMgmt->sAssocInfo.AssocInfo.RequestIELength;
+        memcpy(pbyIEs, (sFrame.pBuf + 24 +6), pMgmt->sAssocInfo.AssocInfo.ResponseIELength);
+
+        // save values and set current BSS state
+        if (cpu_to_le16((*(sFrame.pwStatus))) == WLAN_MGMT_STATUS_SUCCESS ){
+            // set AID
+            pMgmt->wCurrAID = cpu_to_le16((*(sFrame.pwAid)));
+            if ( (pMgmt->wCurrAID >> 14) != (BIT0 | BIT1) )
+            {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "AID from AP, has two msb clear.\n");
+            };
+            DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "Association Successful, AID=%d.\n", pMgmt->wCurrAID & ~(BIT14|BIT15));
+            pMgmt->eCurrState = WMAC_STATE_ASSOC;
+            BSSvUpdateAPNode((HANDLE)pDevice, sFrame.pwCapInfo, sFrame.pSuppRates, sFrame.pExtSuppRates);
+            pItemSSID = (PWLAN_IE_SSID)pMgmt->abyCurrSSID;
+            DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "Link with AP(SSID): %s\n", pItemSSID->abySSID);
+            pDevice->bLinkPass = TRUE;
+            pDevice->uBBVGADiffCount = 0;
+            if ((pDevice->bWPADEVUp) && (pDevice->skb != NULL)) {
+	  if(skb_tailroom(pDevice->skb) <(sizeof(viawget_wpa_header)+pMgmt->sAssocInfo.AssocInfo.ResponseIELength+
+		   	                                                 pMgmt->sAssocInfo.AssocInfo.RequestIELength)) {    //data room not enough
+                     dev_kfree_skb(pDevice->skb);
+		   pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
+	       	}
+                wpahdr = (viawget_wpa_header *)pDevice->skb->data;
+                wpahdr->type = VIAWGET_ASSOC_MSG;
+                wpahdr->resp_ie_len = pMgmt->sAssocInfo.AssocInfo.ResponseIELength;
+                wpahdr->req_ie_len = pMgmt->sAssocInfo.AssocInfo.RequestIELength;
+                memcpy(pDevice->skb->data + sizeof(viawget_wpa_header), pMgmt->sAssocInfo.abyIEs, wpahdr->req_ie_len);
+                memcpy(pDevice->skb->data + sizeof(viawget_wpa_header) + wpahdr->req_ie_len,
+                       pbyIEs,
+                       wpahdr->resp_ie_len
+                       );
+                skb_put(pDevice->skb, sizeof(viawget_wpa_header) + wpahdr->resp_ie_len + wpahdr->req_ie_len);
+                pDevice->skb->dev = pDevice->wpadev;
+                pDevice->skb->mac_header = pDevice->skb->data;
+                pDevice->skb->pkt_type = PACKET_HOST;
+                pDevice->skb->protocol = htons(ETH_P_802_2);
+                memset(pDevice->skb->cb, 0, sizeof(pDevice->skb->cb));
+                netif_rx(pDevice->skb);
+                pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
+            }
+
+//2008-0409-07, <Add> by Einsn Liu
+#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+	//if(pDevice->bWPADevEnable == TRUE)
+		{
+		BYTE buf[512];
+		size_t len;
+		union iwreq_data  wrqu;
+		int we_event;
+
+		memset(buf, 0, 512);
+
+		len = pMgmt->sAssocInfo.AssocInfo.RequestIELength;
+		if(len)	{
+			memcpy(buf, pMgmt->sAssocInfo.abyIEs, len);
+			memset(&wrqu, 0, sizeof (wrqu));
+			wrqu.data.length = len;
+			we_event = IWEVASSOCREQIE;
+			wireless_send_event(pDevice->dev, we_event, &wrqu, buf);
+		}
+
+		memset(buf, 0, 512);
+		len = pMgmt->sAssocInfo.AssocInfo.ResponseIELength;
+
+		if(len)	{
+			memcpy(buf, pbyIEs, len);
+			memset(&wrqu, 0, sizeof (wrqu));
+			wrqu.data.length = len;
+			we_event = IWEVASSOCRESPIE;
+			wireless_send_event(pDevice->dev, we_event, &wrqu, buf);
+		}
+
+
+  memset(&wrqu, 0, sizeof (wrqu));
+	memcpy(wrqu.ap_addr.sa_data, &pMgmt->abyCurrBSSID[0], ETH_ALEN);
+        wrqu.ap_addr.sa_family = ARPHRD_ETHER;
+	wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL);
+	}
+#endif //#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+//End Add -- //2008-0409-07, <Add> by Einsn Liu
+		}
+        else {
+            if (bReAssocType) {
+                pMgmt->eCurrState = WMAC_STATE_IDLE;
+            }
+            else {
+                // jump back to the auth state and indicate the error
+                pMgmt->eCurrState = WMAC_STATE_AUTH;
+            }
+            s_vMgrLogStatus(pMgmt,cpu_to_le16((*(sFrame.pwStatus))));
+        }
+
+    }
+
+#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+//need clear flags related to Networkmanager
+
+              pDevice->bwextcount = 0;
+              pDevice->bWPASuppWextEnabled = FALSE;
+#endif
+
+
+if(pMgmt->eCurrState == WMAC_STATE_ASSOC)
+      timer_expire(pDevice->sTimerCommand, 0);
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *    Start the station authentication procedure.  Namely, send an
+ *    authentication frame to the AP.
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrAuthenBeginSta(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject  pMgmt,
+    OUT PCMD_STATUS pStatus
+    )
+{
+    PSDevice     pDevice = (PSDevice)hDeviceContext;
+    WLAN_FR_AUTHEN  sFrame;
+    PSTxMgmtPacket  pTxPacket = NULL;
+
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_AUTHEN_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_AUTHEN_FR_MAXLEN;
+    vMgrEncodeAuthen(&sFrame);
+    /* insert values */
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+        (
+        WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+        WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_AUTHEN)
+        ));
+    memcpy( sFrame.pHdr->sA3.abyAddr1, pMgmt->abyCurrBSSID, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+    if (pMgmt->bShareKeyAlgorithm)
+        *(sFrame.pwAuthAlgorithm) = cpu_to_le16(WLAN_AUTH_ALG_SHAREDKEY);
+    else
+        *(sFrame.pwAuthAlgorithm) = cpu_to_le16(WLAN_AUTH_ALG_OPENSYSTEM);
+
+    *(sFrame.pwAuthSequence) = cpu_to_le16(1);
+    /* Adjust the length fields */
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+
+    *pStatus = csMgmt_xmit(pDevice, pTxPacket);
+    if (*pStatus == CMD_STATUS_PENDING){
+        pMgmt->eCurrState = WMAC_STATE_AUTHPENDING;
+        *pStatus = CMD_STATUS_SUCCESS;
+    }
+
+    return ;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *    Start the station(AP) deauthentication procedure.  Namely, send an
+ *    deauthentication frame to the AP or Sta.
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrDeAuthenBeginSta(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject  pMgmt,
+    IN  PBYTE  abyDestAddress,
+    IN  WORD    wReason,
+    OUT PCMD_STATUS pStatus
+    )
+{
+    PSDevice            pDevice = (PSDevice)hDeviceContext;
+    WLAN_FR_DEAUTHEN    sFrame;
+    PSTxMgmtPacket      pTxPacket = NULL;
+
+
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_DEAUTHEN_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_DEAUTHEN_FR_MAXLEN;
+    vMgrEncodeDeauthen(&sFrame);
+    /* insert values */
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+        (
+        WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+        WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_DEAUTHEN)
+        ));
+
+    memcpy( sFrame.pHdr->sA3.abyAddr1, abyDestAddress, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+
+    *(sFrame.pwReason) = cpu_to_le16(wReason);       // deauthen. bcs left BSS
+    /* Adjust the length fields */
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+
+    *pStatus = csMgmt_xmit(pDevice, pTxPacket);
+    if (*pStatus == CMD_STATUS_PENDING){
+        *pStatus = CMD_STATUS_SUCCESS;
+    }
+
+
+    return ;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *    Handle incoming authentication frames.
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+static
+VOID
+s_vMgrRxAuthentication(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket
+    )
+{
+    WLAN_FR_AUTHEN  sFrame;
+
+    // we better be an AP or a STA in AUTHPENDING otherwise ignore
+    if (!(pMgmt->eCurrMode == WMAC_MODE_ESS_AP ||
+          pMgmt->eCurrState == WMAC_STATE_AUTHPENDING)) {
+        return;
+    }
+
+    // decode the frame
+    sFrame.len = pRxPacket->cbMPDULen;
+    sFrame.pBuf = (PBYTE)pRxPacket->p80211Header;
+    vMgrDecodeAuthen(&sFrame);
+    switch (cpu_to_le16((*(sFrame.pwAuthSequence )))){
+        case 1:
+            //AP funciton
+            s_vMgrRxAuthenSequence_1(pDevice,pMgmt, &sFrame);
+            break;
+        case 2:
+            s_vMgrRxAuthenSequence_2(pDevice, pMgmt, &sFrame);
+            break;
+        case 3:
+            //AP funciton
+            s_vMgrRxAuthenSequence_3(pDevice, pMgmt, &sFrame);
+            break;
+        case 4:
+            s_vMgrRxAuthenSequence_4(pDevice, pMgmt, &sFrame);
+            break;
+        default:
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Auth Sequence error, seq = %d\n",
+                        cpu_to_le16((*(sFrame.pwAuthSequence))));
+            break;
+    }
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *   Handles incoming authen frames with sequence 1.  Currently
+ *   assumes we're an AP.  So far, no one appears to use authentication
+ *   in Ad-Hoc mode.
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+
+static
+VOID
+s_vMgrRxAuthenSequence_1(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PWLAN_FR_AUTHEN pFrame
+     )
+{
+    PSTxMgmtPacket      pTxPacket = NULL;
+    UINT                uNodeIndex;
+    WLAN_FR_AUTHEN      sFrame;
+    PSKeyItem           pTransmitKey;
+
+    // Insert a Node entry
+    if (!BSSDBbIsSTAInNodeDB(pMgmt, pFrame->pHdr->sA3.abyAddr2, &uNodeIndex)) {
+        BSSvCreateOneNode((PSDevice)pDevice, &uNodeIndex);
+        memcpy(pMgmt->sNodeDBTable[uNodeIndex].abyMACAddr, pFrame->pHdr->sA3.abyAddr2,
+               WLAN_ADDR_LEN);
+    }
+
+    if (pMgmt->bShareKeyAlgorithm) {
+        pMgmt->sNodeDBTable[uNodeIndex].eNodeState = NODE_KNOWN;
+        pMgmt->sNodeDBTable[uNodeIndex].byAuthSequence = 1;
+    }
+    else {
+        pMgmt->sNodeDBTable[uNodeIndex].eNodeState = NODE_AUTH;
+    }
+
+    // send auth reply
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_AUTHEN_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_AUTHEN_FR_MAXLEN;
+    // format buffer structure
+    vMgrEncodeAuthen(&sFrame);
+    // insert values
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+         (
+         WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+         WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_AUTHEN)|
+         WLAN_SET_FC_ISWEP(0)
+         ));
+    memcpy( sFrame.pHdr->sA3.abyAddr1, pFrame->pHdr->sA3.abyAddr2, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+    *(sFrame.pwAuthAlgorithm) = *(pFrame->pwAuthAlgorithm);
+    *(sFrame.pwAuthSequence) = cpu_to_le16(2);
+
+    if (cpu_to_le16(*(pFrame->pwAuthAlgorithm)) == WLAN_AUTH_ALG_SHAREDKEY) {
+        if (pMgmt->bShareKeyAlgorithm)
+            *(sFrame.pwStatus) = cpu_to_le16(WLAN_MGMT_STATUS_SUCCESS);
+        else
+            *(sFrame.pwStatus) = cpu_to_le16(WLAN_MGMT_STATUS_UNSUPPORTED_AUTHALG);
+    }
+    else {
+        if (pMgmt->bShareKeyAlgorithm)
+            *(sFrame.pwStatus) = cpu_to_le16(WLAN_MGMT_STATUS_UNSUPPORTED_AUTHALG);
+        else
+            *(sFrame.pwStatus) = cpu_to_le16(WLAN_MGMT_STATUS_SUCCESS);
+    }
+
+    if (pMgmt->bShareKeyAlgorithm &&
+        (cpu_to_le16(*(sFrame.pwStatus)) == WLAN_MGMT_STATUS_SUCCESS)) {
+
+        sFrame.pChallenge = (PWLAN_IE_CHALLENGE)(sFrame.pBuf + sFrame.len);
+        sFrame.len += WLAN_CHALLENGE_IE_LEN;
+        sFrame.pChallenge->byElementID = WLAN_EID_CHALLENGE;
+        sFrame.pChallenge->len = WLAN_CHALLENGE_LEN;
+        memset(pMgmt->abyChallenge, 0, WLAN_CHALLENGE_LEN);
+        // get group key
+        if(KeybGetTransmitKey(&(pDevice->sKey), pDevice->abyBroadcastAddr, GROUP_KEY, &pTransmitKey) == TRUE) {
+            rc4_init(&pDevice->SBox, pDevice->abyPRNG, pTransmitKey->uKeyLength+3);
+            rc4_encrypt(&pDevice->SBox, pMgmt->abyChallenge, pMgmt->abyChallenge, WLAN_CHALLENGE_LEN);
+        }
+        memcpy(sFrame.pChallenge->abyChallenge, pMgmt->abyChallenge , WLAN_CHALLENGE_LEN);
+    }
+
+    /* Adjust the length fields */
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+    // send the frame
+    if (pDevice->bEnableHostapd) {
+        return;
+    }
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:Authreq_reply sequence_1 tx.. \n");
+    if (csMgmt_xmit(pDevice, pTxPacket) != CMD_STATUS_PENDING) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:Authreq_reply sequence_1 tx failed.\n");
+    }
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *   Handles incoming auth frames with sequence number 2.  Currently
+ *   assumes we're a station.
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+static
+VOID
+s_vMgrRxAuthenSequence_2(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PWLAN_FR_AUTHEN pFrame
+    )
+{
+    WLAN_FR_AUTHEN      sFrame;
+    PSTxMgmtPacket      pTxPacket = NULL;
+
+
+    switch (cpu_to_le16((*(pFrame->pwAuthAlgorithm))))
+    {
+        case WLAN_AUTH_ALG_OPENSYSTEM:
+            if ( cpu_to_le16((*(pFrame->pwStatus))) == WLAN_MGMT_STATUS_SUCCESS ){
+                DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "802.11 Authen (OPEN) Successful.\n");
+                pMgmt->eCurrState = WMAC_STATE_AUTH;
+	 timer_expire(pDevice->sTimerCommand, 0);
+            }
+            else {
+                DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "802.11 Authen (OPEN) Failed.\n");
+                s_vMgrLogStatus(pMgmt, cpu_to_le16((*(pFrame->pwStatus))));
+                pMgmt->eCurrState = WMAC_STATE_IDLE;
+            }
+            if (pDevice->eCommandState == WLAN_AUTHENTICATE_WAIT ) {
+//                spin_unlock_irq(&pDevice->lock);
+//                vCommandTimerWait((HANDLE)pDevice, 0);
+//                spin_lock_irq(&pDevice->lock);
+            }
+
+            break;
+
+        case WLAN_AUTH_ALG_SHAREDKEY:
+
+            if (cpu_to_le16((*(pFrame->pwStatus))) == WLAN_MGMT_STATUS_SUCCESS) {
+                pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+                memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_AUTHEN_FR_MAXLEN);
+                pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+                sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+                sFrame.len = WLAN_AUTHEN_FR_MAXLEN;
+                // format buffer structure
+                vMgrEncodeAuthen(&sFrame);
+                // insert values
+                sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+                     (
+                     WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+                     WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_AUTHEN)|
+                     WLAN_SET_FC_ISWEP(1)
+                     ));
+                memcpy( sFrame.pHdr->sA3.abyAddr1, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+                memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+                memcpy( sFrame.pHdr->sA3.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+                *(sFrame.pwAuthAlgorithm) = *(pFrame->pwAuthAlgorithm);
+                *(sFrame.pwAuthSequence) = cpu_to_le16(3);
+                *(sFrame.pwStatus) = cpu_to_le16(WLAN_MGMT_STATUS_SUCCESS);
+                sFrame.pChallenge = (PWLAN_IE_CHALLENGE)(sFrame.pBuf + sFrame.len);
+                sFrame.len += WLAN_CHALLENGE_IE_LEN;
+                sFrame.pChallenge->byElementID = WLAN_EID_CHALLENGE;
+                sFrame.pChallenge->len = WLAN_CHALLENGE_LEN;
+                memcpy( sFrame.pChallenge->abyChallenge, pFrame->pChallenge->abyChallenge, WLAN_CHALLENGE_LEN);
+                // Adjust the length fields
+                pTxPacket->cbMPDULen = sFrame.len;
+                pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+                // send the frame
+                if (csMgmt_xmit(pDevice, pTxPacket) != CMD_STATUS_PENDING) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:Auth_reply sequence_2 tx failed.\n");
+                }
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:Auth_reply sequence_2 tx ...\n");
+            }
+            else {
+            	DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:rx Auth_reply sequence_2 status error ...\n");
+                if ( pDevice->eCommandState == WLAN_AUTHENTICATE_WAIT ) {
+//                    spin_unlock_irq(&pDevice->lock);
+//                    vCommandTimerWait((HANDLE)pDevice, 0);
+//                    spin_lock_irq(&pDevice->lock);
+                }
+                s_vMgrLogStatus(pMgmt, cpu_to_le16((*(pFrame->pwStatus))));
+            }
+            break;
+        default:
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt: rx auth.seq = 2 unknown AuthAlgorithm=%d\n", cpu_to_le16((*(pFrame->pwAuthAlgorithm))));
+            break;
+    }
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *   Handles incoming authen frames with sequence 3.  Currently
+ *   assumes we're an AP.  This function assumes the frame has
+ *   already been successfully decrypted.
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+static
+VOID
+s_vMgrRxAuthenSequence_3(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PWLAN_FR_AUTHEN pFrame
+    )
+{
+    PSTxMgmtPacket      pTxPacket = NULL;
+    UINT                uStatusCode = 0 ;
+    UINT                uNodeIndex = 0;
+    WLAN_FR_AUTHEN      sFrame;
+
+    if (!WLAN_GET_FC_ISWEP(pFrame->pHdr->sA3.wFrameCtl)) {
+        uStatusCode = WLAN_MGMT_STATUS_CHALLENGE_FAIL;
+        goto reply;
+    }
+    if (BSSDBbIsSTAInNodeDB(pMgmt, pFrame->pHdr->sA3.abyAddr2, &uNodeIndex)) {
+         if (pMgmt->sNodeDBTable[uNodeIndex].byAuthSequence != 1) {
+            uStatusCode = WLAN_MGMT_STATUS_RX_AUTH_NOSEQ;
+            goto reply;
+         }
+         if (memcmp(pMgmt->abyChallenge, pFrame->pChallenge->abyChallenge, WLAN_CHALLENGE_LEN) != 0) {
+            uStatusCode = WLAN_MGMT_STATUS_CHALLENGE_FAIL;
+            goto reply;
+         }
+    }
+    else {
+        uStatusCode = WLAN_MGMT_STATUS_UNSPEC_FAILURE;
+        goto reply;
+    }
+
+    if (uNodeIndex) {
+        pMgmt->sNodeDBTable[uNodeIndex].eNodeState = NODE_AUTH;
+        pMgmt->sNodeDBTable[uNodeIndex].byAuthSequence = 0;
+    }
+    uStatusCode = WLAN_MGMT_STATUS_SUCCESS;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Challenge text check ok..\n");
+
+reply:
+    // send auth reply
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_AUTHEN_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_AUTHEN_FR_MAXLEN;
+    // format buffer structure
+    vMgrEncodeAuthen(&sFrame);
+    /* insert values */
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+         (
+         WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+         WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_AUTHEN)|
+         WLAN_SET_FC_ISWEP(0)
+         ));
+    memcpy( sFrame.pHdr->sA3.abyAddr1, pFrame->pHdr->sA3.abyAddr2, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+    *(sFrame.pwAuthAlgorithm) = *(pFrame->pwAuthAlgorithm);
+    *(sFrame.pwAuthSequence) = cpu_to_le16(4);
+    *(sFrame.pwStatus) = cpu_to_le16(uStatusCode);
+
+    /* Adjust the length fields */
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+    // send the frame
+    if (pDevice->bEnableHostapd) {
+        return;
+    }
+    if (csMgmt_xmit(pDevice, pTxPacket) != CMD_STATUS_PENDING) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:Authreq_reply sequence_4 tx failed.\n");
+    }
+    return;
+
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *   Handles incoming authen frames with sequence 4
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+static
+VOID
+s_vMgrRxAuthenSequence_4(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PWLAN_FR_AUTHEN pFrame
+    )
+{
+
+    if ( cpu_to_le16((*(pFrame->pwStatus))) == WLAN_MGMT_STATUS_SUCCESS ){
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "802.11 Authen (SHAREDKEY) Successful.\n");
+        pMgmt->eCurrState = WMAC_STATE_AUTH;
+	  timer_expire(pDevice->sTimerCommand, 0);
+    }
+    else{
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO "802.11 Authen (SHAREDKEY) Failed.\n");
+        s_vMgrLogStatus(pMgmt, cpu_to_le16((*(pFrame->pwStatus))) );
+        pMgmt->eCurrState = WMAC_STATE_IDLE;
+    }
+
+    if ( pDevice->eCommandState == WLAN_AUTHENTICATE_WAIT ) {
+//        spin_unlock_irq(&pDevice->lock);
+//        vCommandTimerWait((HANDLE)pDevice, 0);
+//        spin_lock_irq(&pDevice->lock);
+    }
+
+}
+
+/*+
+ *
+ * Routine Description:
+ *   Handles incoming disassociation frames
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+static
+VOID
+s_vMgrRxDisassociation(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket
+    )
+{
+    WLAN_FR_DISASSOC    sFrame;
+    UINT        uNodeIndex = 0;
+//    CMD_STATUS          CmdStatus;
+    viawget_wpa_header *wpahdr;
+
+    if ( pMgmt->eCurrMode == WMAC_MODE_ESS_AP ){
+        // if is acting an AP..
+        // a STA is leaving this BSS..
+        sFrame.len = pRxPacket->cbMPDULen;
+        sFrame.pBuf = (PBYTE)pRxPacket->p80211Header;
+        if (BSSDBbIsSTAInNodeDB(pMgmt, pRxPacket->p80211Header->sA3.abyAddr2, &uNodeIndex)) {
+            BSSvRemoveOneNode(pDevice, uNodeIndex);
+        }
+        else {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Rx disassoc, sta not found\n");
+        }
+    }
+    else if (pMgmt->eCurrMode == WMAC_MODE_ESS_STA ){
+        sFrame.len = pRxPacket->cbMPDULen;
+        sFrame.pBuf = (PBYTE)pRxPacket->p80211Header;
+        vMgrDecodeDisassociation(&sFrame);
+        DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "AP disassociated me, reason=%d.\n", cpu_to_le16(*(sFrame.pwReason)));
+        //TODO: do something let upper layer know or
+        //try to send associate packet again because of inactivity timeout
+      //  if (pMgmt->eCurrState == WMAC_STATE_ASSOC) {
+       //     vMgrReAssocBeginSta((PSDevice)pDevice, pMgmt, &CmdStatus);
+      //  };
+        if ((pDevice->bWPADEVUp) && (pDevice->skb != NULL)) {
+             wpahdr = (viawget_wpa_header *)pDevice->skb->data;
+             wpahdr->type = VIAWGET_DISASSOC_MSG;
+             wpahdr->resp_ie_len = 0;
+             wpahdr->req_ie_len = 0;
+             skb_put(pDevice->skb, sizeof(viawget_wpa_header));
+             pDevice->skb->dev = pDevice->wpadev;
+	         pDevice->skb->mac_header = pDevice->skb->data;
+
+             pDevice->skb->pkt_type = PACKET_HOST;
+             pDevice->skb->protocol = htons(ETH_P_802_2);
+             memset(pDevice->skb->cb, 0, sizeof(pDevice->skb->cb));
+             netif_rx(pDevice->skb);
+             pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
+         };
+
+ #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+  // if(pDevice->bWPASuppWextEnabled == TRUE)
+      {
+	union iwreq_data  wrqu;
+	memset(&wrqu, 0, sizeof (wrqu));
+        wrqu.ap_addr.sa_family = ARPHRD_ETHER;
+	printk("wireless_send_event--->SIOCGIWAP(disassociated)\n");
+	wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL);
+     }
+  #endif
+
+    }
+    /* else, ignore it */
+
+    return;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *   Handles incoming deauthentication frames
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+static
+VOID
+s_vMgrRxDeauthentication(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket
+    )
+{
+    WLAN_FR_DEAUTHEN    sFrame;
+    UINT        uNodeIndex = 0;
+    viawget_wpa_header *wpahdr;
+
+
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP ){
+        //Todo:
+        // if is acting an AP..
+        // a STA is leaving this BSS..
+        sFrame.len = pRxPacket->cbMPDULen;
+        sFrame.pBuf = (PBYTE)pRxPacket->p80211Header;
+        if (BSSDBbIsSTAInNodeDB(pMgmt, pRxPacket->p80211Header->sA3.abyAddr2, &uNodeIndex)) {
+            BSSvRemoveOneNode(pDevice, uNodeIndex);
+        }
+        else {
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Rx deauth, sta not found\n");
+        }
+    }
+    else {
+        if (pMgmt->eCurrMode == WMAC_MODE_ESS_STA ) {
+            sFrame.len = pRxPacket->cbMPDULen;
+            sFrame.pBuf = (PBYTE)pRxPacket->p80211Header;
+            vMgrDecodeDeauthen(&sFrame);
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO  "AP deauthed me, reason=%d.\n", cpu_to_le16((*(sFrame.pwReason))));
+            // TODO: update BSS list for specific BSSID if pre-authentication case
+            if (IS_ETH_ADDRESS_EQUAL(sFrame.pHdr->sA3.abyAddr3, pMgmt->abyCurrBSSID)) {
+                if (pMgmt->eCurrState >= WMAC_STATE_AUTHPENDING) {
+                    pMgmt->sNodeDBTable[0].bActive = FALSE;
+                    pMgmt->eCurrMode = WMAC_MODE_STANDBY;
+                    pMgmt->eCurrState = WMAC_STATE_IDLE;
+                    netif_stop_queue(pDevice->dev);
+                    pDevice->bLinkPass = FALSE;
+                }
+            };
+
+            if ((pDevice->bWPADEVUp) && (pDevice->skb != NULL)) {
+                 wpahdr = (viawget_wpa_header *)pDevice->skb->data;
+                 wpahdr->type = VIAWGET_DISASSOC_MSG;
+                 wpahdr->resp_ie_len = 0;
+                 wpahdr->req_ie_len = 0;
+                 skb_put(pDevice->skb, sizeof(viawget_wpa_header));
+                 pDevice->skb->dev = pDevice->wpadev;
+                 pDevice->skb->mac_header = pDevice->skb->data;
+                 pDevice->skb->pkt_type = PACKET_HOST;
+                 pDevice->skb->protocol = htons(ETH_P_802_2);
+                 memset(pDevice->skb->cb, 0, sizeof(pDevice->skb->cb));
+                 netif_rx(pDevice->skb);
+                 pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
+           };
+
+	   #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+  // if(pDevice->bWPASuppWextEnabled == TRUE)
+      {
+	union iwreq_data  wrqu;
+	memset(&wrqu, 0, sizeof (wrqu));
+        wrqu.ap_addr.sa_family = ARPHRD_ETHER;
+	printk("wireless_send_event--->SIOCGIWAP(disauthen)\n");
+	wireless_send_event(pDevice->dev, SIOCGIWAP, &wrqu, NULL);
+     }
+  #endif
+
+        }
+        /* else, ignore it.  TODO: IBSS authentication service
+            would be implemented here */
+    };
+    return;
+}
+
+
+//2008-8-4 <add> by chester
+/*+
+ *
+ * Routine Description:
+ * check if current channel is match ZoneType.
+ *for USA:1~11;
+ *      Japan:1~13;
+ *      Europe:1~13
+ * Return Value:
+ *               True:exceed;
+ *                False:normal case
+-*/
+static BOOL
+ChannelExceedZoneType(
+    IN PSDevice pDevice,
+    IN BYTE byCurrChannel
+    )
+{
+  BOOL exceed=FALSE;
+
+  switch(pDevice->byZoneType) {
+  	case 0x00:                  //USA:1~11
+                     if((byCurrChannel<1) ||(byCurrChannel>11))
+	                exceed = TRUE;
+	         break;
+	case 0x01:                  //Japan:1~13
+	case 0x02:                  //Europe:1~13
+                     if((byCurrChannel<1) ||(byCurrChannel>13))
+	                exceed = TRUE;
+	         break;
+	default:                    //reserve for other zonetype
+		break;
+  }
+
+  return exceed;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *   Handles and analysis incoming beacon frames.
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+static
+VOID
+s_vMgrRxBeacon(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket,
+    IN BOOL bInScan
+    )
+{
+
+    PKnownBSS           pBSSList;
+    WLAN_FR_BEACON      sFrame;
+    QWORD               qwTSFOffset;
+    BOOL                bIsBSSIDEqual = FALSE;
+    BOOL                bIsSSIDEqual = FALSE;
+    BOOL                bTSFLargeDiff = FALSE;
+    BOOL                bTSFOffsetPostive = FALSE;
+    BOOL                bUpdateTSF = FALSE;
+    BOOL                bIsAPBeacon = FALSE;
+    BOOL                bIsChannelEqual = FALSE;
+    UINT                uLocateByteIndex;
+    BYTE                byTIMBitOn = 0;
+    WORD                wAIDNumber = 0;
+    UINT                uNodeIndex;
+    QWORD               qwTimestamp, qwLocalTSF;
+    QWORD               qwCurrTSF;
+    WORD                wStartIndex = 0;
+    WORD                wAIDIndex = 0;
+    BYTE                byCurrChannel = pRxPacket->byRxChannel;
+    ERPObject           sERP;
+    UINT                uRateLen = WLAN_RATES_MAXLEN;
+    BOOL                bChannelHit = FALSE;
+    BOOL                bUpdatePhyParameter = FALSE;
+    BYTE                byIEChannel = 0;
+
+
+    memset(&sFrame, 0, sizeof(WLAN_FR_BEACON));
+    sFrame.len = pRxPacket->cbMPDULen;
+    sFrame.pBuf = (PBYTE)pRxPacket->p80211Header;
+
+    // decode the beacon frame
+    vMgrDecodeBeacon(&sFrame);
+
+    if ((sFrame.pwBeaconInterval == 0) ||
+        (sFrame.pwCapInfo == 0) ||
+        (sFrame.pSSID == 0) ||
+        (sFrame.pSuppRates == 0) ) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Rx beacon frame error\n");
+        return;
+    };
+
+
+    if (sFrame.pDSParms != NULL) {
+        if (byCurrChannel > CB_MAX_CHANNEL_24G) {
+            // channel remapping to
+            byIEChannel = CARDbyGetChannelMapping(pDevice, sFrame.pDSParms->byCurrChannel, PHY_TYPE_11A);
+        } else {
+            byIEChannel = sFrame.pDSParms->byCurrChannel;
+        }
+        if (byCurrChannel != byIEChannel) {
+            // adjust channel info. bcs we rcv adjcent channel pakckets
+            bChannelHit = FALSE;
+            byCurrChannel = byIEChannel;
+        }
+    } else {
+        // no DS channel info
+        bChannelHit = TRUE;
+    }
+//2008-0730-01<Add>by MikeLiu
+if(ChannelExceedZoneType(pDevice,byCurrChannel)==TRUE)
+      return;
+
+    if (sFrame.pERP != NULL) {
+        sERP.byERP = sFrame.pERP->byContext;
+        sERP.bERPExist = TRUE;
+
+    } else {
+        sERP.bERPExist = FALSE;
+        sERP.byERP = 0;
+    }
+
+    pBSSList = BSSpAddrIsInBSSList((HANDLE)pDevice, sFrame.pHdr->sA3.abyAddr3, sFrame.pSSID);
+    if (pBSSList == NULL) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Beacon/insert: RxChannel = : %d\n", byCurrChannel);
+        BSSbInsertToBSSList((HANDLE)pDevice,
+                            sFrame.pHdr->sA3.abyAddr3,
+                            *sFrame.pqwTimestamp,
+                            *sFrame.pwBeaconInterval,
+                            *sFrame.pwCapInfo,
+                            byCurrChannel,
+                            sFrame.pSSID,
+                            sFrame.pSuppRates,
+                            sFrame.pExtSuppRates,
+                            &sERP,
+                            sFrame.pRSN,
+                            sFrame.pRSNWPA,
+                            sFrame.pIE_Country,
+                            sFrame.pIE_Quiet,
+                            sFrame.len - WLAN_HDR_ADDR3_LEN,
+                            sFrame.pHdr->sA4.abyAddr4,   // payload of beacon
+                            (HANDLE)pRxPacket
+                           );
+    }
+    else {
+//        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"update bcn: RxChannel = : %d\n", byCurrChannel);
+        BSSbUpdateToBSSList((HANDLE)pDevice,
+                            *sFrame.pqwTimestamp,
+                            *sFrame.pwBeaconInterval,
+                            *sFrame.pwCapInfo,
+                            byCurrChannel,
+                            bChannelHit,
+                            sFrame.pSSID,
+                            sFrame.pSuppRates,
+                            sFrame.pExtSuppRates,
+                            &sERP,
+                            sFrame.pRSN,
+                            sFrame.pRSNWPA,
+                            sFrame.pIE_Country,
+                            sFrame.pIE_Quiet,
+                            pBSSList,
+                            sFrame.len - WLAN_HDR_ADDR3_LEN,
+                            sFrame.pHdr->sA4.abyAddr4,   // payload of probresponse
+                            (HANDLE)pRxPacket
+                           );
+
+    }
+
+    if (bInScan) {
+        return;
+    }
+
+    if(byCurrChannel == (BYTE)pMgmt->uCurrChannel)
+       bIsChannelEqual = TRUE;
+
+    if (bIsChannelEqual && (pMgmt->eCurrMode == WMAC_MODE_ESS_AP)) {
+
+        // if rx beacon without ERP field
+        if (sERP.bERPExist) {
+            if (WLAN_GET_ERP_USE_PROTECTION(sERP.byERP)){
+                pDevice->byERPFlag |= WLAN_SET_ERP_USE_PROTECTION(1);
+                pDevice->wUseProtectCntDown = USE_PROTECT_PERIOD;
+            }
+        }
+        else {
+            pDevice->byERPFlag |= WLAN_SET_ERP_USE_PROTECTION(1);
+            pDevice->wUseProtectCntDown = USE_PROTECT_PERIOD;
+        }
+
+        if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+            if(!WLAN_GET_CAP_INFO_SHORTPREAMBLE(*sFrame.pwCapInfo))
+                pDevice->byERPFlag |= WLAN_SET_ERP_BARKER_MODE(1);
+            if(!sERP.bERPExist)
+                pDevice->byERPFlag |= WLAN_SET_ERP_NONERP_PRESENT(1);
+        }
+
+        // set to MAC&BBP
+        if (WLAN_GET_ERP_USE_PROTECTION(pDevice->byERPFlag)){
+            if (!pDevice->bProtectMode) {
+                 MACvEnableProtectMD(pDevice->PortOffset);
+                 pDevice->bProtectMode = TRUE;
+            }
+        }
+    }
+
+
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP)
+        return;
+
+    // check if BSSID the same
+    if (memcmp(sFrame.pHdr->sA3.abyAddr3,
+               pMgmt->abyCurrBSSID,
+               WLAN_BSSID_LEN) == 0) {
+
+        bIsBSSIDEqual = TRUE;
+
+// 2008-05-21 <add> by Richardtai
+        pDevice->uCurrRSSI = pRxPacket->uRSSI;
+        pDevice->byCurrSQ = pRxPacket->bySQ;
+
+        if (pMgmt->sNodeDBTable[0].uInActiveCount != 0) {
+            pMgmt->sNodeDBTable[0].uInActiveCount = 0;
+            //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"BCN:Wake Count= [%d]\n", pMgmt->wCountToWakeUp);
+        }
+    }
+    // check if SSID the same
+    if (sFrame.pSSID->len == ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->len) {
+        if (memcmp(sFrame.pSSID->abySSID,
+                   ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->abySSID,
+                   sFrame.pSSID->len
+                   ) == 0) {
+            bIsSSIDEqual = TRUE;
+        };
+    }
+
+    if ((WLAN_GET_CAP_INFO_ESS(*sFrame.pwCapInfo)== TRUE) &&
+        (bIsBSSIDEqual == TRUE) &&
+        (bIsSSIDEqual == TRUE) &&
+        (pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
+        (pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
+        // add state check to prevent reconnect fail since we'll receive Beacon
+
+        bIsAPBeacon = TRUE;
+
+        if (pBSSList != NULL) {
+
+            // Compare PHY paramater setting
+            if (pMgmt->wCurrCapInfo != pBSSList->wCapInfo) {
+                bUpdatePhyParameter = TRUE;
+                pMgmt->wCurrCapInfo = pBSSList->wCapInfo;
+            }
+            if (sFrame.pERP != NULL) {
+                if ((sFrame.pERP->byElementID == WLAN_EID_ERP) &&
+                    (pMgmt->byERPContext != sFrame.pERP->byContext)) {
+                    bUpdatePhyParameter = TRUE;
+                    pMgmt->byERPContext = sFrame.pERP->byContext;
+                }
+            }
+            //
+            // Basic Rate Set may change dynamiclly
+            //
+            if (pBSSList->eNetworkTypeInUse == PHY_TYPE_11B) {
+                uRateLen = WLAN_RATES_MAXLEN_11B;
+            }
+            pMgmt->abyCurrSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)pBSSList->abySuppRates,
+                                                    (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                                                    uRateLen);
+            pMgmt->abyCurrExtSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)pBSSList->abyExtSuppRates,
+                                                    (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates,
+                                                    uRateLen);
+            RATEvParseMaxRate( (PVOID)pDevice,
+                               (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                               (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates,
+                               TRUE,
+                               &(pMgmt->sNodeDBTable[0].wMaxBasicRate),
+                               &(pMgmt->sNodeDBTable[0].wMaxSuppRate),
+                               &(pMgmt->sNodeDBTable[0].wSuppRate),
+                               &(pMgmt->sNodeDBTable[0].byTopCCKBasicRate),
+                               &(pMgmt->sNodeDBTable[0].byTopOFDMBasicRate)
+                              );
+#ifdef	PLICE_DEBUG
+		//printk("RxBeacon:MaxSuppRate is %d\n",pMgmt->sNodeDBTable[0].wMaxSuppRate);
+#endif
+			if (bUpdatePhyParameter == TRUE) {
+                CARDbSetPhyParameter( pMgmt->pAdapter,
+                                      pMgmt->eCurrentPHYMode,
+                                      pMgmt->wCurrCapInfo,
+                                      pMgmt->byERPContext,
+                                      pMgmt->abyCurrSuppRates,
+                                      pMgmt->abyCurrExtSuppRates
+                                      );
+            }
+            if (sFrame.pIE_PowerConstraint != NULL) {
+                CARDvSetPowerConstraint(pMgmt->pAdapter,
+                                        (BYTE) pBSSList->uChannel,
+                                        sFrame.pIE_PowerConstraint->byPower
+                                        );
+            }
+            if (sFrame.pIE_CHSW != NULL) {
+                CARDbChannelSwitch( pMgmt->pAdapter,
+                                    sFrame.pIE_CHSW->byMode,
+                                    CARDbyGetChannelMapping(pMgmt->pAdapter, sFrame.pIE_CHSW->byMode, pMgmt->eCurrentPHYMode),
+                                    sFrame.pIE_CHSW->byCount
+                                    );
+
+            } else if (bIsChannelEqual == FALSE) {
+                CARDbSetChannel(pMgmt->pAdapter, pBSSList->uChannel);
+            }
+        }
+    }
+
+//    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Beacon 2 \n");
+    // check if CF field exisit
+    if (WLAN_GET_CAP_INFO_ESS(*sFrame.pwCapInfo)) {
+        if (sFrame.pCFParms->wCFPDurRemaining > 0) {
+            // TODO: deal with CFP period to set NAV
+        };
+    };
+
+    HIDWORD(qwTimestamp) = cpu_to_le32(HIDWORD(*sFrame.pqwTimestamp));
+    LODWORD(qwTimestamp) = cpu_to_le32(LODWORD(*sFrame.pqwTimestamp));
+    HIDWORD(qwLocalTSF) = HIDWORD(pRxPacket->qwLocalTSF);
+    LODWORD(qwLocalTSF) = LODWORD(pRxPacket->qwLocalTSF);
+
+    // check if beacon TSF larger or small than our local TSF
+    if (HIDWORD(qwTimestamp) == HIDWORD(qwLocalTSF)) {
+        if (LODWORD(qwTimestamp) >= LODWORD(qwLocalTSF)) {
+            bTSFOffsetPostive = TRUE;
+        }
+        else {
+            bTSFOffsetPostive = FALSE;
+        }
+    }
+    else if (HIDWORD(qwTimestamp) > HIDWORD(qwLocalTSF)) {
+        bTSFOffsetPostive = TRUE;
+    }
+    else if (HIDWORD(qwTimestamp) < HIDWORD(qwLocalTSF)) {
+        bTSFOffsetPostive = FALSE;
+    };
+
+    if (bTSFOffsetPostive) {
+        qwTSFOffset = CARDqGetTSFOffset(pRxPacket->byRxRate, (qwTimestamp), (qwLocalTSF));
+    }
+    else {
+        qwTSFOffset = CARDqGetTSFOffset(pRxPacket->byRxRate, (qwLocalTSF), (qwTimestamp));
+    }
+
+    if (HIDWORD(qwTSFOffset) != 0 ||
+        (LODWORD(qwTSFOffset) > TRIVIAL_SYNC_DIFFERENCE )) {
+         bTSFLargeDiff = TRUE;
+    }
+
+
+    // if infra mode
+    if (bIsAPBeacon == TRUE) {
+
+        // Infra mode: Local TSF always follow AP's TSF if Difference huge.
+        if (bTSFLargeDiff)
+            bUpdateTSF = TRUE;
+
+        if ((pDevice->bEnablePSMode == TRUE) &&(sFrame.pTIM != 0)) {
+
+            // deal with DTIM, analysis TIM
+            pMgmt->bMulticastTIM = WLAN_MGMT_IS_MULTICAST_TIM(sFrame.pTIM->byBitMapCtl) ? TRUE : FALSE ;
+            pMgmt->byDTIMCount = sFrame.pTIM->byDTIMCount;
+            pMgmt->byDTIMPeriod = sFrame.pTIM->byDTIMPeriod;
+            wAIDNumber = pMgmt->wCurrAID & ~(BIT14|BIT15);
+
+            // check if AID in TIM field bit on
+            // wStartIndex = N1
+            wStartIndex = WLAN_MGMT_GET_TIM_OFFSET(sFrame.pTIM->byBitMapCtl) << 1;
+            // AIDIndex = N2
+            wAIDIndex = (wAIDNumber >> 3);
+            if ((wAIDNumber > 0) && (wAIDIndex >= wStartIndex)) {
+                uLocateByteIndex = wAIDIndex - wStartIndex;
+                // len = byDTIMCount + byDTIMPeriod + byDTIMPeriod + byVirtBitMap[0~250]
+                if (sFrame.pTIM->len >= (uLocateByteIndex + 4)) {
+                    byTIMBitOn  = (0x01) << ((wAIDNumber) % 8);
+                    pMgmt->bInTIM = sFrame.pTIM->byVirtBitMap[uLocateByteIndex] & byTIMBitOn ? TRUE : FALSE;
+                }
+                else {
+                    pMgmt->bInTIM = FALSE;
+                };
+            }
+            else {
+                pMgmt->bInTIM = FALSE;
+            };
+
+            if (pMgmt->bInTIM ||
+                (pMgmt->bMulticastTIM && (pMgmt->byDTIMCount == 0))) {
+                pMgmt->bInTIMWake = TRUE;
+                // send out ps-poll packet
+//                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "BCN:In TIM\n");
+                if (pMgmt->bInTIM) {
+                    PSvSendPSPOLL((PSDevice)pDevice);
+//                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "BCN:PS-POLL sent..\n");
+                };
+
+            }
+            else {
+                pMgmt->bInTIMWake = FALSE;
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "BCN: Not In TIM..\n");
+                if (pDevice->bPWBitOn == FALSE) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "BCN: Send Null Packet\n");
+                    if (PSbSendNullPacket(pDevice))
+                        pDevice->bPWBitOn = TRUE;
+                }
+                if(PSbConsiderPowerDown(pDevice, FALSE, FALSE)) {
+                   DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "BCN: Power down now...\n");
+                };
+            }
+
+        }
+
+    }
+    // if adhoc mode
+    if ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) && !bIsAPBeacon && bIsChannelEqual) {
+        if (bIsBSSIDEqual) {
+            // Use sNodeDBTable[0].uInActiveCount as IBSS beacons received count.
+		    if (pMgmt->sNodeDBTable[0].uInActiveCount != 0)
+		 	    pMgmt->sNodeDBTable[0].uInActiveCount = 0;
+
+            // adhoc mode:TSF updated only when beacon larger then local TSF
+            if (bTSFLargeDiff && bTSFOffsetPostive &&
+                (pMgmt->eCurrState == WMAC_STATE_JOINTED))
+                bUpdateTSF = TRUE;
+
+            // During dpc, already in spinlocked.
+            if (BSSDBbIsSTAInNodeDB(pMgmt, sFrame.pHdr->sA3.abyAddr2, &uNodeIndex)) {
+
+                // Update the STA, (Techically the Beacons of all the IBSS nodes
+		        // should be identical, but that's not happening in practice.
+                pMgmt->abyCurrSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)sFrame.pSuppRates,
+                                                        (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                                                        WLAN_RATES_MAXLEN_11B);
+                RATEvParseMaxRate( (PVOID)pDevice,
+                                   (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                                   NULL,
+                                   TRUE,
+                                   &(pMgmt->sNodeDBTable[uNodeIndex].wMaxBasicRate),
+                                   &(pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate),
+                                   &(pMgmt->sNodeDBTable[uNodeIndex].wSuppRate),
+                                   &(pMgmt->sNodeDBTable[uNodeIndex].byTopCCKBasicRate),
+                                   &(pMgmt->sNodeDBTable[uNodeIndex].byTopOFDMBasicRate)
+                                  );
+                pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble = WLAN_GET_CAP_INFO_SHORTPREAMBLE(*sFrame.pwCapInfo);
+                pMgmt->sNodeDBTable[uNodeIndex].bShortSlotTime = WLAN_GET_CAP_INFO_SHORTSLOTTIME(*sFrame.pwCapInfo);
+                pMgmt->sNodeDBTable[uNodeIndex].uInActiveCount = 0;
+            }
+            else {
+                // Todo, initial Node content
+                BSSvCreateOneNode((PSDevice)pDevice, &uNodeIndex);
+
+                pMgmt->abyCurrSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)sFrame.pSuppRates,
+                                                        (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                                                        WLAN_RATES_MAXLEN_11B);
+                RATEvParseMaxRate( (PVOID)pDevice,
+                                   (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                                   NULL,
+                                   TRUE,
+                                   &(pMgmt->sNodeDBTable[uNodeIndex].wMaxBasicRate),
+                                   &(pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate),
+                                   &(pMgmt->sNodeDBTable[uNodeIndex].wSuppRate),
+                                   &(pMgmt->sNodeDBTable[uNodeIndex].byTopCCKBasicRate),
+                                   &(pMgmt->sNodeDBTable[uNodeIndex].byTopOFDMBasicRate)
+                                 );
+
+                memcpy(pMgmt->sNodeDBTable[uNodeIndex].abyMACAddr, sFrame.pHdr->sA3.abyAddr2, WLAN_ADDR_LEN);
+                pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble = WLAN_GET_CAP_INFO_SHORTPREAMBLE(*sFrame.pwCapInfo);
+                pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate = pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate;
+#ifdef	PLICE_DEBUG
+		//if (uNodeIndex == 0)
+		{
+			printk("s_vMgrRxBeacon:TxDataRate is %d,Index is %d\n",pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate,uNodeIndex);
+		}
+#endif
+/*
+                pMgmt->sNodeDBTable[uNodeIndex].bShortSlotTime = WLAN_GET_CAP_INFO_SHORTSLOTTIME(*sFrame.pwCapInfo);
+                if(pMgmt->sNodeDBTable[uNodeIndex].wMaxSuppRate > RATE_11M)
+                       pMgmt->sNodeDBTable[uNodeIndex].bERPExist = TRUE;
+*/
+            }
+
+            // if other stations jointed, indicate connect to upper layer..
+            if (pMgmt->eCurrState == WMAC_STATE_STARTED) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Current IBSS State: [Started]........to: [Jointed] \n");
+                pMgmt->eCurrState = WMAC_STATE_JOINTED;
+                pDevice->bLinkPass = TRUE;
+                if (netif_queue_stopped(pDevice->dev)){
+                    netif_wake_queue(pDevice->dev);
+                }
+                pMgmt->sNodeDBTable[0].bActive = TRUE;
+                pMgmt->sNodeDBTable[0].uInActiveCount = 0;
+
+            };
+        }
+        else if (bIsSSIDEqual) {
+
+            // See other adhoc sta with the same SSID but BSSID is different.
+            // adpot this vars only when TSF larger then us.
+            if (bTSFLargeDiff && bTSFOffsetPostive) {
+                 // we don't support ATIM under adhoc mode
+               // if ( sFrame.pIBSSParms->wATIMWindow == 0) {
+                     // adpot this vars
+                     // TODO: check sFrame cap if privacy on, and support rate syn
+                     memcpy(pMgmt->abyCurrBSSID, sFrame.pHdr->sA3.abyAddr3, WLAN_BSSID_LEN);
+                     memcpy(pDevice->abyBSSID, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+                     pMgmt->wCurrATIMWindow = cpu_to_le16(sFrame.pIBSSParms->wATIMWindow);
+                     pMgmt->wCurrBeaconPeriod = cpu_to_le16(*sFrame.pwBeaconInterval);
+                     pMgmt->abyCurrSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)sFrame.pSuppRates,
+                                                      (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                                                      WLAN_RATES_MAXLEN_11B);
+                     // set HW beacon interval and re-synchronizing....
+                     DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Rejoining to Other Adhoc group with same SSID........\n");
+                     VNSvOutPortW(pDevice->PortOffset + MAC_REG_BI, pMgmt->wCurrBeaconPeriod);
+                     CARDbUpdateTSF(pDevice, pRxPacket->byRxRate, qwTimestamp, qwLocalTSF);
+                     CARDvUpdateNextTBTT(pDevice->PortOffset, qwTimestamp, pMgmt->wCurrBeaconPeriod);
+                     // Turn off bssid filter to avoid filter others adhoc station which bssid is different.
+                     MACvWriteBSSIDAddress(pDevice->PortOffset, pMgmt->abyCurrBSSID);
+
+                     CARDbSetPhyParameter (  pMgmt->pAdapter,
+                                            pMgmt->eCurrentPHYMode,
+                                            pMgmt->wCurrCapInfo,
+                                            pMgmt->byERPContext,
+                                            pMgmt->abyCurrSuppRates,
+                                            pMgmt->abyCurrExtSuppRates);
+
+
+                     // MACvRegBitsOff(pDevice->PortOffset, MAC_REG_RCR, RCR_BSSID);
+                     // set highest basic rate
+                     // s_vSetHighestBasicRate(pDevice, (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates);
+                     // Prepare beacon frame
+                     bMgrPrepareBeaconToSend((HANDLE)pDevice, pMgmt);
+              //  }
+            };
+        }
+    };
+    // endian issue ???
+    // Update TSF
+    if (bUpdateTSF) {
+        CARDbGetCurrentTSF(pDevice->PortOffset, &qwCurrTSF);
+        CARDbUpdateTSF(pDevice, pRxPacket->byRxRate, qwTimestamp, pRxPacket->qwLocalTSF);
+        CARDbGetCurrentTSF(pDevice->PortOffset, &qwCurrTSF);
+        CARDvUpdateNextTBTT(pDevice->PortOffset, qwTimestamp, pMgmt->wCurrBeaconPeriod);
+    }
+
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *   Instructs the hw to create a bss using the supplied
+ *   attributes. Note that this implementation only supports Ad-Hoc
+ *   BSS creation.
+ *
+ *
+ * Return Value:
+ *    CMD_STATUS
+ *
+-*/
+VOID
+vMgrCreateOwnIBSS(
+    IN  HANDLE hDeviceContext,
+    OUT PCMD_STATUS pStatus
+    )
+{
+    PSDevice            pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject        pMgmt = pDevice->pMgmt;
+    WORD                wMaxBasicRate;
+    WORD                wMaxSuppRate;
+    BYTE                byTopCCKBasicRate;
+    BYTE                byTopOFDMBasicRate;
+    QWORD               qwCurrTSF;
+    UINT                ii;
+    BYTE    abyRATE[] = {0x82, 0x84, 0x8B, 0x96, 0x24, 0x30, 0x48, 0x6C, 0x0C, 0x12, 0x18, 0x60};
+    BYTE    abyCCK_RATE[] = {0x82, 0x84, 0x8B, 0x96};
+    BYTE    abyOFDM_RATE[] = {0x0C, 0x12, 0x18, 0x24, 0x30, 0x48, 0x60, 0x6C};
+    WORD                wSuppRate;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Create Basic Service Set .......\n");
+
+    if (pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA) {
+        if ((pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) &&
+            (pDevice->eEncryptionStatus != Ndis802_11Encryption2Enabled) &&
+            (pDevice->eEncryptionStatus != Ndis802_11Encryption3Enabled)) {
+            // encryption mode error
+            *pStatus = CMD_STATUS_FAILURE;
+            return;
+        }
+    }
+
+    pMgmt->abyCurrSuppRates[0] = WLAN_EID_SUPP_RATES;
+    pMgmt->abyCurrExtSuppRates[0] = WLAN_EID_EXTSUPP_RATES;
+
+    if (pMgmt->eConfigMode == WMAC_CONFIG_AP) {
+        pMgmt->eCurrentPHYMode = pMgmt->byAPBBType;
+    } else {
+        if (pDevice->byBBType == BB_TYPE_11G)
+            pMgmt->eCurrentPHYMode = PHY_TYPE_11G;
+        if (pDevice->byBBType == BB_TYPE_11B)
+            pMgmt->eCurrentPHYMode = PHY_TYPE_11B;
+        if (pDevice->byBBType == BB_TYPE_11A)
+            pMgmt->eCurrentPHYMode = PHY_TYPE_11A;
+    }
+
+    if (pMgmt->eCurrentPHYMode != PHY_TYPE_11A) {
+        pMgmt->abyCurrSuppRates[1] = WLAN_RATES_MAXLEN_11B;
+        pMgmt->abyCurrExtSuppRates[1] = 0;
+        for (ii = 0; ii < 4; ii++)
+            pMgmt->abyCurrSuppRates[2+ii] = abyRATE[ii];
+    } else {
+        pMgmt->abyCurrSuppRates[1] = 8;
+        pMgmt->abyCurrExtSuppRates[1] = 0;
+        for (ii = 0; ii < 8; ii++)
+            pMgmt->abyCurrSuppRates[2+ii] = abyRATE[ii];
+    }
+
+
+    if (pMgmt->eCurrentPHYMode == PHY_TYPE_11G) {
+        pMgmt->abyCurrSuppRates[1] = 8;
+        pMgmt->abyCurrExtSuppRates[1] = 4;
+        for (ii = 0; ii < 4; ii++)
+            pMgmt->abyCurrSuppRates[2+ii] =  abyCCK_RATE[ii];
+        for (ii = 4; ii < 8; ii++)
+            pMgmt->abyCurrSuppRates[2+ii] =  abyOFDM_RATE[ii-4];
+        for (ii = 0; ii < 4; ii++)
+            pMgmt->abyCurrExtSuppRates[2+ii] =  abyOFDM_RATE[ii+4];
+    }
+
+
+    // Disable Protect Mode
+    pDevice->bProtectMode = 0;
+    MACvDisableProtectMD(pDevice->PortOffset);
+
+    pDevice->bBarkerPreambleMd = 0;
+    MACvDisableBarkerPreambleMd(pDevice->PortOffset);
+
+    // Kyle Test 2003.11.04
+
+    // set HW beacon interval
+    if (pMgmt->wIBSSBeaconPeriod == 0)
+        pMgmt->wIBSSBeaconPeriod = DEFAULT_IBSS_BI;
+
+
+    CARDbGetCurrentTSF(pDevice->PortOffset, &qwCurrTSF);
+    // clear TSF counter
+    VNSvOutPortB(pDevice->PortOffset + MAC_REG_TFTCTL, TFTCTL_TSFCNTRST);
+    // enable TSF counter
+    VNSvOutPortB(pDevice->PortOffset + MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
+
+    // set Next TBTT
+    CARDvSetFirstNextTBTT(pDevice->PortOffset, pMgmt->wIBSSBeaconPeriod);
+
+    pMgmt->uIBSSChannel = pDevice->uChannel;
+
+    if (pMgmt->uIBSSChannel == 0)
+        pMgmt->uIBSSChannel = DEFAULT_IBSS_CHANNEL;
+
+
+    // set basic rate
+
+    RATEvParseMaxRate((PVOID)pDevice, (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                      (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates, TRUE,
+                      &wMaxBasicRate, &wMaxSuppRate, &wSuppRate,
+                      &byTopCCKBasicRate, &byTopOFDMBasicRate);
+
+
+    if (pMgmt->eConfigMode == WMAC_CONFIG_AP) {
+        pMgmt->eCurrMode = WMAC_MODE_ESS_AP;
+    }
+
+    if (pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA) {
+        MEMvCopy(pMgmt->abyIBSSDFSOwner, pDevice->abyCurrentNetAddr, 6);
+        pMgmt->byIBSSDFSRecovery = 10;
+        pMgmt->eCurrMode = WMAC_MODE_IBSS_STA;
+    }
+
+    // Adopt pre-configured IBSS vars to current vars
+    pMgmt->eCurrState = WMAC_STATE_STARTED;
+    pMgmt->wCurrBeaconPeriod = pMgmt->wIBSSBeaconPeriod;
+    pMgmt->uCurrChannel = pMgmt->uIBSSChannel;
+    pMgmt->wCurrATIMWindow = pMgmt->wIBSSATIMWindow;
+    MACvWriteATIMW(pDevice->PortOffset, pMgmt->wCurrATIMWindow);
+    pDevice->uCurrRSSI = 0;
+    pDevice->byCurrSQ = 0;
+    //memcpy(pMgmt->abyDesireSSID,pMgmt->abyAdHocSSID,
+                     // ((PWLAN_IE_SSID)pMgmt->abyAdHocSSID)->len + WLAN_IEHDR_LEN);
+    memset(pMgmt->abyCurrSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+    memcpy(pMgmt->abyCurrSSID,
+           pMgmt->abyDesireSSID,
+           ((PWLAN_IE_SSID)pMgmt->abyDesireSSID)->len + WLAN_IEHDR_LEN
+          );
+
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+        // AP mode BSSID = MAC addr
+        memcpy(pMgmt->abyCurrBSSID, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO"AP beacon created BSSID:%02x-%02x-%02x-%02x-%02x-%02x \n",
+                      pMgmt->abyCurrBSSID[0],
+                      pMgmt->abyCurrBSSID[1],
+                      pMgmt->abyCurrBSSID[2],
+                      pMgmt->abyCurrBSSID[3],
+                      pMgmt->abyCurrBSSID[4],
+                      pMgmt->abyCurrBSSID[5]
+                    );
+    }
+
+    if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+
+        // BSSID selected must be randomized as spec 11.1.3
+        pMgmt->abyCurrBSSID[5] = (BYTE) (LODWORD(qwCurrTSF)& 0x000000ff);
+        pMgmt->abyCurrBSSID[4] = (BYTE)((LODWORD(qwCurrTSF)& 0x0000ff00) >> 8);
+        pMgmt->abyCurrBSSID[3] = (BYTE)((LODWORD(qwCurrTSF)& 0x00ff0000) >> 16);
+        pMgmt->abyCurrBSSID[2] = (BYTE)((LODWORD(qwCurrTSF)& 0x00000ff0) >> 4);
+        pMgmt->abyCurrBSSID[1] = (BYTE)((LODWORD(qwCurrTSF)& 0x000ff000) >> 12);
+        pMgmt->abyCurrBSSID[0] = (BYTE)((LODWORD(qwCurrTSF)& 0x0ff00000) >> 20);
+        pMgmt->abyCurrBSSID[5] ^= pMgmt->abyMACAddr[0];
+        pMgmt->abyCurrBSSID[4] ^= pMgmt->abyMACAddr[1];
+        pMgmt->abyCurrBSSID[3] ^= pMgmt->abyMACAddr[2];
+        pMgmt->abyCurrBSSID[2] ^= pMgmt->abyMACAddr[3];
+        pMgmt->abyCurrBSSID[1] ^= pMgmt->abyMACAddr[4];
+        pMgmt->abyCurrBSSID[0] ^= pMgmt->abyMACAddr[5];
+        pMgmt->abyCurrBSSID[0] &= ~IEEE_ADDR_GROUP;
+        pMgmt->abyCurrBSSID[0] |= IEEE_ADDR_UNIVERSAL;
+
+
+        DEVICE_PRT(MSG_LEVEL_INFO, KERN_INFO"Adhoc beacon created bssid:%02x-%02x-%02x-%02x-%02x-%02x \n",
+                      pMgmt->abyCurrBSSID[0],
+                      pMgmt->abyCurrBSSID[1],
+                      pMgmt->abyCurrBSSID[2],
+                      pMgmt->abyCurrBSSID[3],
+                      pMgmt->abyCurrBSSID[4],
+                      pMgmt->abyCurrBSSID[5]
+                    );
+    }
+
+    // Set Capability Info
+    pMgmt->wCurrCapInfo = 0;
+
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_ESS(1);
+        pMgmt->byDTIMPeriod = DEFAULT_DTIM_PERIOD;
+        pMgmt->byDTIMCount = pMgmt->byDTIMPeriod - 1;
+    }
+
+    if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_IBSS(1);
+    }
+
+    if (pDevice->bEncryptionEnable) {
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_PRIVACY(1);
+        if (pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) {
+            if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled) {
+                pMgmt->byCSSPK = KEY_CTL_CCMP;
+                pMgmt->byCSSGK = KEY_CTL_CCMP;
+            } else if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled) {
+                pMgmt->byCSSPK = KEY_CTL_TKIP;
+                pMgmt->byCSSGK = KEY_CTL_TKIP;
+            } else {
+                pMgmt->byCSSPK = KEY_CTL_NONE;
+                pMgmt->byCSSGK = KEY_CTL_WEP;
+            }
+        } else {
+            pMgmt->byCSSPK = KEY_CTL_WEP;
+            pMgmt->byCSSGK = KEY_CTL_WEP;
+        }
+    };
+
+    pMgmt->byERPContext = 0;
+
+//    memcpy(pDevice->abyBSSID, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+
+    if (pMgmt->eConfigMode == WMAC_CONFIG_AP) {
+        CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_AP);
+    } else {
+        CARDbSetBSSID(pMgmt->pAdapter, pMgmt->abyCurrBSSID, OP_MODE_ADHOC);
+    }
+
+    CARDbSetPhyParameter(   pMgmt->pAdapter,
+                            pMgmt->eCurrentPHYMode,
+                            pMgmt->wCurrCapInfo,
+                            pMgmt->byERPContext,
+                            pMgmt->abyCurrSuppRates,
+                            pMgmt->abyCurrExtSuppRates
+                            );
+
+    CARDbSetBeaconPeriod(pMgmt->pAdapter, pMgmt->wIBSSBeaconPeriod);
+    // set channel and clear NAV
+    CARDbSetChannel(pMgmt->pAdapter, pMgmt->uIBSSChannel);
+    pMgmt->uCurrChannel = pMgmt->uIBSSChannel;
+
+    if (CARDbIsShortPreamble(pMgmt->pAdapter)) {
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTPREAMBLE(1);
+    } else {
+        pMgmt->wCurrCapInfo &= (~WLAN_SET_CAP_INFO_SHORTPREAMBLE(1));
+    }
+
+    if ((pMgmt->b11hEnable == TRUE) &&
+        (pMgmt->eCurrentPHYMode == PHY_TYPE_11A)) {
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SPECTRUMMNG(1);
+    } else {
+        pMgmt->wCurrCapInfo &= (~WLAN_SET_CAP_INFO_SPECTRUMMNG(1));
+    }
+
+    pMgmt->eCurrState = WMAC_STATE_STARTED;
+    // Prepare beacon to send
+    if (bMgrPrepareBeaconToSend((HANDLE)pDevice, pMgmt)) {
+        *pStatus = CMD_STATUS_SUCCESS;
+    }
+
+    return ;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *   Instructs wmac to join a bss using the supplied attributes.
+ *   The arguments may the BSSID or SSID and the rest of the
+ *   attributes are obtained from the scan result of known bss list.
+ *
+ *
+ * Return Value:
+ *    None.
+ *
+-*/
+
+VOID
+vMgrJoinBSSBegin(
+    IN  HANDLE hDeviceContext,
+    OUT PCMD_STATUS pStatus
+    )
+{
+
+    PSDevice     pDevice = (PSDevice)hDeviceContext;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PKnownBSS       pCurr = NULL;
+    UINT            ii, uu;
+    PWLAN_IE_SUPP_RATES pItemRates = NULL;
+    PWLAN_IE_SUPP_RATES pItemExtRates = NULL;
+    PWLAN_IE_SSID   pItemSSID;
+    UINT            uRateLen = WLAN_RATES_MAXLEN;
+    WORD            wMaxBasicRate = RATE_1M;
+    WORD            wMaxSuppRate = RATE_1M;
+    WORD            wSuppRate;
+    BYTE            byTopCCKBasicRate = RATE_1M;
+    BYTE            byTopOFDMBasicRate = RATE_1M;
+
+
+    for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+        if (pMgmt->sBSSList[ii].bActive == TRUE)
+            break;
+    }
+
+    if (ii == MAX_BSS_NUM) {
+       *pStatus = CMD_STATUS_RESOURCES;
+        DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "BSS finding:BSS list is empty.\n");
+       return;
+    };
+
+    // memset(pMgmt->abyDesireBSSID, 0,  WLAN_BSSID_LEN);
+    // Search known BSS list for prefer BSSID or SSID
+
+    pCurr = BSSpSearchBSSList(pDevice,
+                              pMgmt->abyDesireBSSID,
+                              pMgmt->abyDesireSSID,
+                              pMgmt->eConfigPHYMode
+                              );
+
+    if (pCurr == NULL){
+       *pStatus = CMD_STATUS_RESOURCES;
+       pItemSSID = (PWLAN_IE_SSID)pMgmt->abyDesireSSID;
+       DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Scanning [%s] not found, disconnected !\n", pItemSSID->abySSID);
+       return;
+    };
+
+    DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "AP(BSS) finding:Found a AP(BSS)..\n");
+    if (WLAN_GET_CAP_INFO_ESS(cpu_to_le16(pCurr->wCapInfo))){
+
+        if ((pMgmt->eAuthenMode == WMAC_AUTH_WPA)||(pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK)) {
+
+    // patch for CISCO migration mode
+/*
+            if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled) {
+                if (WPA_SearchRSN(0, WPA_TKIP, pCurr) == FALSE) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"No match RSN info. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
+                    // encryption mode error
+                    pMgmt->eCurrState = WMAC_STATE_IDLE;
+                    return;
+                }
+            } else if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled) {
+                if (WPA_SearchRSN(0, WPA_AESCCMP, pCurr) == FALSE) {
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"No match RSN info. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
+                    // encryption mode error
+                    pMgmt->eCurrState = WMAC_STATE_IDLE;
+                    return;
+                }
+            }
+*/
+        }
+
+#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+	//if(pDevice->bWPASuppWextEnabled == TRUE)
+            Encyption_Rebuild(pDevice, pCurr);
+#endif
+        // Infrastructure BSS
+        s_vMgrSynchBSS(pDevice,
+                       WMAC_MODE_ESS_STA,
+                       pCurr,
+                       pStatus
+                       );
+
+        if (*pStatus == CMD_STATUS_SUCCESS){
+
+            // Adopt this BSS state vars in Mgmt Object
+            pMgmt->uCurrChannel = pCurr->uChannel;
+
+            memset(pMgmt->abyCurrSuppRates, 0 , WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1);
+            memset(pMgmt->abyCurrExtSuppRates, 0 , WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1);
+
+            if (pCurr->eNetworkTypeInUse == PHY_TYPE_11B) {
+                uRateLen = WLAN_RATES_MAXLEN_11B;
+            }
+
+            pItemRates = (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates;
+            pItemExtRates = (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates;
+
+            // Parse Support Rate IE
+            pItemRates->byElementID = WLAN_EID_SUPP_RATES;
+            pItemRates->len = RATEuSetIE((PWLAN_IE_SUPP_RATES)pCurr->abySuppRates,
+                                         pItemRates,
+                                         uRateLen);
+
+            // Parse Extension Support Rate IE
+            pItemExtRates->byElementID = WLAN_EID_EXTSUPP_RATES;
+            pItemExtRates->len = RATEuSetIE((PWLAN_IE_SUPP_RATES)pCurr->abyExtSuppRates,
+                                            pItemExtRates,
+                                            uRateLen);
+            // Stuffing Rate IE
+            if ((pItemExtRates->len > 0) && (pItemRates->len < 8)) {
+                for (ii = 0; ii < (UINT)(8 - pItemRates->len); ) {
+                    pItemRates->abyRates[pItemRates->len + ii] = pItemExtRates->abyRates[ii];
+                    ii ++;
+                    if (pItemExtRates->len <= ii)
+                        break;
+                }
+                pItemRates->len += (BYTE)ii;
+                if (pItemExtRates->len - ii > 0) {
+                    pItemExtRates->len -= (BYTE)ii;
+                    for (uu = 0; uu < pItemExtRates->len; uu ++) {
+                        pItemExtRates->abyRates[uu] = pItemExtRates->abyRates[uu + ii];
+                    }
+                } else {
+                    pItemExtRates->len = 0;
+                }
+            }
+
+            RATEvParseMaxRate((PVOID)pDevice, pItemRates, pItemExtRates, TRUE,
+                              &wMaxBasicRate, &wMaxSuppRate, &wSuppRate,
+                              &byTopCCKBasicRate, &byTopOFDMBasicRate);
+
+            // TODO: deal with if wCapInfo the privacy is on, but station WEP is off
+            // TODO: deal with if wCapInfo the PS-Pollable is on.
+            pMgmt->wCurrBeaconPeriod = pCurr->wBeaconInterval;
+            memset(pMgmt->abyCurrSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+            memcpy(pMgmt->abyCurrBSSID, pCurr->abyBSSID, WLAN_BSSID_LEN);
+            memcpy(pMgmt->abyCurrSSID, pCurr->abySSID, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+
+            pMgmt->eCurrMode = WMAC_MODE_ESS_STA;
+
+            pMgmt->eCurrState = WMAC_STATE_JOINTED;
+            // Adopt BSS state in Adapter Device Object
+            //pDevice->byOpMode = OP_MODE_INFRASTRUCTURE;
+//            memcpy(pDevice->abyBSSID, pCurr->abyBSSID, WLAN_BSSID_LEN);
+
+            // Add current BSS to Candidate list
+            // This should only works for WPA2 BSS, and WPA2 BSS check must be done before.
+            if (pMgmt->eAuthenMode == WMAC_AUTH_WPA2) {
+                BOOL bResult = bAdd_PMKID_Candidate((HANDLE)pDevice, pMgmt->abyCurrBSSID, &pCurr->sRSNCapObj);
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"bAdd_PMKID_Candidate: 1(%d)\n", bResult);
+                if (bResult == FALSE) {
+                    vFlush_PMKID_Candidate((HANDLE)pDevice);
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"vFlush_PMKID_Candidate: 4\n");
+                    bAdd_PMKID_Candidate((HANDLE)pDevice, pMgmt->abyCurrBSSID, &pCurr->sRSNCapObj);
+                }
+            }
+
+            // Preamble type auto-switch: if AP can receive short-preamble cap,
+            // we can turn on too.
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Join ESS\n");
+
+
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"End of Join AP -- A/B/G Action\n");
+        }
+        else {
+            pMgmt->eCurrState = WMAC_STATE_IDLE;
+        };
+
+
+     }
+     else {
+        // ad-hoc mode BSS
+        if (pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) {
+
+            if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled) {
+                if (WPA_SearchRSN(0, WPA_TKIP, pCurr) == FALSE) {
+                    // encryption mode error
+                    pMgmt->eCurrState = WMAC_STATE_IDLE;
+                    return;
+                }
+            } else if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled) {
+                if (WPA_SearchRSN(0, WPA_AESCCMP, pCurr) == FALSE) {
+                    // encryption mode error
+                    pMgmt->eCurrState = WMAC_STATE_IDLE;
+                    return;
+                }
+            } else {
+                // encryption mode error
+                pMgmt->eCurrState = WMAC_STATE_IDLE;
+                return;
+            }
+        }
+
+        s_vMgrSynchBSS(pDevice,
+                       WMAC_MODE_IBSS_STA,
+                       pCurr,
+                       pStatus
+                       );
+
+        if (*pStatus == CMD_STATUS_SUCCESS){
+            // Adopt this BSS state vars in Mgmt Object
+            // TODO: check if CapInfo privacy on, but we don't..
+            pMgmt->uCurrChannel = pCurr->uChannel;
+
+
+            // Parse Support Rate IE
+            pMgmt->abyCurrSuppRates[0] = WLAN_EID_SUPP_RATES;
+            pMgmt->abyCurrSuppRates[1] = RATEuSetIE((PWLAN_IE_SUPP_RATES)pCurr->abySuppRates,
+                                                    (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                                                    WLAN_RATES_MAXLEN_11B);
+            // set basic rate
+            RATEvParseMaxRate((PVOID)pDevice, (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                              NULL, TRUE, &wMaxBasicRate, &wMaxSuppRate, &wSuppRate,
+                              &byTopCCKBasicRate, &byTopOFDMBasicRate);
+
+            pMgmt->wCurrCapInfo = pCurr->wCapInfo;
+            pMgmt->wCurrBeaconPeriod = pCurr->wBeaconInterval;
+            memset(pMgmt->abyCurrSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN);
+            memcpy(pMgmt->abyCurrBSSID, pCurr->abyBSSID, WLAN_BSSID_LEN);
+            memcpy(pMgmt->abyCurrSSID, pCurr->abySSID, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN);
+//          pMgmt->wCurrATIMWindow = pCurr->wATIMWindow;
+            MACvWriteATIMW(pDevice->PortOffset, pMgmt->wCurrATIMWindow);
+            pMgmt->eCurrMode = WMAC_MODE_IBSS_STA;
+
+            pMgmt->eCurrState = WMAC_STATE_STARTED;
+            // Adopt BSS state in Adapter Device Object
+            //pDevice->byOpMode = OP_MODE_ADHOC;
+//            pDevice->bLinkPass = TRUE;
+//            memcpy(pDevice->abyBSSID, pCurr->abyBSSID, WLAN_BSSID_LEN);
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Join IBSS ok:%02x-%02x-%02x-%02x-%02x-%02x \n",
+                  pMgmt->abyCurrBSSID[0],
+                  pMgmt->abyCurrBSSID[1],
+                  pMgmt->abyCurrBSSID[2],
+                  pMgmt->abyCurrBSSID[3],
+                  pMgmt->abyCurrBSSID[4],
+                  pMgmt->abyCurrBSSID[5]
+                );
+            // Preamble type auto-switch: if AP can receive short-preamble cap,
+            // and if registry setting is short preamble we can turn on too.
+
+            // Prepare beacon
+            bMgrPrepareBeaconToSend((HANDLE)pDevice, pMgmt);
+        }
+        else {
+            pMgmt->eCurrState = WMAC_STATE_IDLE;
+        };
+     };
+    return;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ * Set HW to synchronize a specific BSS from known BSS list.
+ *
+ *
+ * Return Value:
+ *    PCM_STATUS
+ *
+-*/
+static
+VOID
+s_vMgrSynchBSS (
+    IN PSDevice      pDevice,
+    IN UINT          uBSSMode,
+    IN PKnownBSS     pCurr,
+    OUT PCMD_STATUS  pStatus
+    )
+{
+    CARD_PHY_TYPE   ePhyType = PHY_TYPE_11B;
+    PSMgmtObject  pMgmt = pDevice->pMgmt;
+//    int     ii;
+                                                     //1M,   2M,   5M,   11M,  18M,  24M,  36M,  54M
+    BYTE abyCurrSuppRatesG[] = {WLAN_EID_SUPP_RATES, 8, 0x02, 0x04, 0x0B, 0x16, 0x24, 0x30, 0x48, 0x6C};
+    BYTE abyCurrExtSuppRatesG[] = {WLAN_EID_EXTSUPP_RATES, 4, 0x0C, 0x12, 0x18, 0x60};
+                                                           //6M,   9M,   12M,  48M
+    BYTE abyCurrSuppRatesA[] = {WLAN_EID_SUPP_RATES, 8, 0x0C, 0x12, 0x18, 0x24, 0x30, 0x48, 0x60, 0x6C};
+    BYTE abyCurrSuppRatesB[] = {WLAN_EID_SUPP_RATES, 4, 0x02, 0x04, 0x0B, 0x16};
+
+
+    *pStatus = CMD_STATUS_FAILURE;
+
+    if (s_bCipherMatch(pCurr,
+                       pDevice->eEncryptionStatus,
+                       &(pMgmt->byCSSPK),
+                       &(pMgmt->byCSSGK)) == FALSE) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "s_bCipherMatch Fail .......\n");
+        return;
+    }
+
+    pMgmt->pCurrBSS = pCurr;
+
+    // if previous mode is IBSS.
+    if(pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+        MACvRegBitsOff(pDevice->PortOffset, MAC_REG_BCNDMACTL, BEACON_READY);
+        MACvRegBitsOff(pDevice->PortOffset, MAC_REG_TCR, TCR_AUTOBCNTX);
+    }
+
+    // Init the BSS informations
+    pDevice->bCCK = TRUE;
+    pDevice->bProtectMode = FALSE;
+    MACvDisableProtectMD(pDevice->PortOffset);
+    pDevice->bBarkerPreambleMd = FALSE;
+    MACvDisableBarkerPreambleMd(pDevice->PortOffset);
+    pDevice->bNonERPPresent = FALSE;
+    pDevice->byPreambleType = 0;
+    pDevice->wBasicRate = 0;
+    // Set Basic Rate
+    CARDbAddBasicRate((PVOID)pDevice, RATE_1M);
+    // calculate TSF offset
+    // TSF Offset = Received Timestamp TSF - Marked Local's TSF
+    CARDbUpdateTSF(pDevice, pCurr->byRxRate, pCurr->qwBSSTimestamp, pCurr->qwLocalTSF);
+
+    CARDbSetBeaconPeriod(pDevice, pCurr->wBeaconInterval);
+
+    // set Next TBTT
+    // Next TBTT = ((local_current_TSF / beacon_interval) + 1 ) * beacon_interval
+    CARDvSetFirstNextTBTT(pDevice->PortOffset, pCurr->wBeaconInterval);
+
+    // set BSSID
+    MACvWriteBSSIDAddress(pDevice->PortOffset, pCurr->abyBSSID);
+
+    MACvReadBSSIDAddress(pDevice->PortOffset, pMgmt->abyCurrBSSID);
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Sync:set CurrBSSID address = %02x-%02x-%02x=%02x-%02x-%02x\n",
+        pMgmt->abyCurrBSSID[0],
+        pMgmt->abyCurrBSSID[1],
+        pMgmt->abyCurrBSSID[2],
+        pMgmt->abyCurrBSSID[3],
+        pMgmt->abyCurrBSSID[4],
+        pMgmt->abyCurrBSSID[5]);
+
+    if (pCurr->eNetworkTypeInUse == PHY_TYPE_11A) {
+        if ((pMgmt->eConfigPHYMode == PHY_TYPE_11A) ||
+            (pMgmt->eConfigPHYMode == PHY_TYPE_AUTO)) {
+            ePhyType = PHY_TYPE_11A;
+        } else {
+            return;
+        }
+    } else if (pCurr->eNetworkTypeInUse == PHY_TYPE_11B) {
+        if ((pMgmt->eConfigPHYMode == PHY_TYPE_11B) ||
+            (pMgmt->eConfigPHYMode == PHY_TYPE_11G) ||
+            (pMgmt->eConfigPHYMode == PHY_TYPE_AUTO)) {
+            ePhyType = PHY_TYPE_11B;
+        } else {
+            return;
+        }
+    } else {
+        if ((pMgmt->eConfigPHYMode == PHY_TYPE_11G) ||
+            (pMgmt->eConfigPHYMode == PHY_TYPE_AUTO)) {
+            ePhyType = PHY_TYPE_11G;
+        } else if (pMgmt->eConfigPHYMode == PHY_TYPE_11B) {
+            ePhyType = PHY_TYPE_11B;
+        } else {
+            return;
+        }
+    }
+
+    if (ePhyType == PHY_TYPE_11A) {
+        MEMvCopy(pMgmt->abyCurrSuppRates, &abyCurrSuppRatesA[0], sizeof(abyCurrSuppRatesA));
+        pMgmt->abyCurrExtSuppRates[1] = 0;
+    } else if (ePhyType == PHY_TYPE_11B) {
+        MEMvCopy(pMgmt->abyCurrSuppRates, &abyCurrSuppRatesB[0], sizeof(abyCurrSuppRatesB));
+        pMgmt->abyCurrExtSuppRates[1] = 0;
+    } else {
+        MEMvCopy(pMgmt->abyCurrSuppRates, &abyCurrSuppRatesG[0], sizeof(abyCurrSuppRatesG));
+        MEMvCopy(pMgmt->abyCurrExtSuppRates, &abyCurrExtSuppRatesG[0], sizeof(abyCurrExtSuppRatesG));
+    }
+
+
+    if (WLAN_GET_CAP_INFO_ESS(pCurr->wCapInfo)) {
+        CARDbSetBSSID(pMgmt->pAdapter, pCurr->abyBSSID, OP_MODE_INFRASTRUCTURE);
+        // Add current BSS to Candidate list
+        // This should only works for WPA2 BSS, and WPA2 BSS check must be done before.
+        if (pMgmt->eAuthenMode == WMAC_AUTH_WPA2) {
+            CARDbAdd_PMKID_Candidate(pMgmt->pAdapter, pMgmt->abyCurrBSSID, pCurr->sRSNCapObj.bRSNCapExist, pCurr->sRSNCapObj.wRSNCap);
+        }
+    } else {
+        CARDbSetBSSID(pMgmt->pAdapter, pCurr->abyBSSID, OP_MODE_ADHOC);
+    }
+
+    if (CARDbSetPhyParameter(   pMgmt->pAdapter,
+                                ePhyType,
+                                pCurr->wCapInfo,
+                                pCurr->sERP.byERP,
+                                pMgmt->abyCurrSuppRates,
+                                pMgmt->abyCurrExtSuppRates
+                            ) != TRUE) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "<----s_bSynchBSS Set Phy Mode Fail [%d]\n", ePhyType);
+        return;
+    }
+    // set channel and clear NAV
+    if (CARDbSetChannel(pMgmt->pAdapter, pCurr->uChannel) == FALSE) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "<----s_bSynchBSS Set Channel [%d]\n", pCurr->uChannel);
+        return;
+    }
+
+/*
+    for (ii=0;ii<BB_VGA_LEVEL;ii++) {
+        if (pCurr->ldBmMAX< pDevice->ldBmThreshold[ii]) {
+            pDevice->byBBVGANew = pDevice->abyBBVGA[ii];
+            break;
+        }
+    }
+
+    if (pDevice->byBBVGANew != pDevice->byBBVGACurrent) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"RSSI[%d] NewGain[%d] OldGain[%d] \n",
+                        (int)pCurr->ldBmMAX, pDevice->byBBVGANew, pDevice->byBBVGACurrent);
+        printk("RSSI[%d] NewGain[%d] OldGain[%d] \n",
+                        (int)pCurr->ldBmMAX, pDevice->byBBVGANew, pDevice->byBBVGACurrent);
+        BBvSetVGAGainOffset(pDevice, pDevice->byBBVGANew);
+    }
+    printk("ldBmMAX[%d] NewGain[%d] OldGain[%d] \n",
+           (int)pCurr->ldBmMAX, pDevice->byBBVGANew, pDevice->byBBVGACurrent);
+*/
+    pMgmt->uCurrChannel = pCurr->uChannel;
+    pMgmt->eCurrentPHYMode = ePhyType;
+    pMgmt->byERPContext = pCurr->sERP.byERP;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Sync:Set to channel = [%d]\n", (INT)pCurr->uChannel);
+
+
+    *pStatus = CMD_STATUS_SUCCESS;
+
+
+    return;
+};
+
+//mike add: fix NetworkManager 0.7.0 hidden ssid mode in WPA encryption
+//                   ,need reset eAuthenMode and eEncryptionStatus
+ static VOID  Encyption_Rebuild(
+    IN PSDevice pDevice,
+    IN PKnownBSS pCurr
+ )
+ {
+  PSMgmtObject  pMgmt = &(pDevice->sMgmtObj);
+ // UINT            ii , uSameBssidNum=0;
+
+        //  for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+          //   if (pMgmt->sBSSList[ii].bActive &&
+            //      IS_ETH_ADDRESS_EQUAL(pMgmt->sBSSList[ii].abyBSSID, pCurr->abyBSSID)) {
+             //       uSameBssidNum++;
+               //   }
+           // }
+  //   if( uSameBssidNum>=2) {	 //we only check AP in hidden sssid  mode
+        if ((pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK) ||           //networkmanager 0.7.0 does not give the pairwise-key selsection,
+             (pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK)) {         // so we need re-selsect it according to real pairwise-key info.
+               if(pCurr->bWPAValid == TRUE)  {   //WPA-PSK
+                          pMgmt->eAuthenMode = WMAC_AUTH_WPAPSK;
+		    if(pCurr->abyPKType[0] == WPA_TKIP) {
+     		        pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;    //TKIP
+     		        printk("Encyption_Rebuild--->ssid reset config to [WPAPSK-TKIP]\n");
+		      }
+     		   else if(pCurr->abyPKType[0] == WPA_AESCCMP) {
+		        pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;    //AES
+                          printk("Encyption_Rebuild--->ssid reset config to [WPAPSK-AES]\n");
+     		     }
+               	}
+               else if(pCurr->bWPA2Valid == TRUE) {  //WPA2-PSK
+                         pMgmt->eAuthenMode = WMAC_AUTH_WPA2PSK;
+		       if(pCurr->abyCSSPK[0] == WLAN_11i_CSS_TKIP) {
+      		           pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;     //TKIP
+                             printk("Encyption_Rebuild--->ssid reset config to [WPA2PSK-TKIP]\n");
+		       	}
+      		       else if(pCurr->abyCSSPK[0] == WLAN_11i_CSS_CCMP) {
+		           pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;    //AES
+                            printk("Encyption_Rebuild--->ssid reset config to [WPA2PSK-AES]\n");
+      		       	}
+               	}
+              }
+        //  }
+      return;
+ }
+
+
+/*+
+ *
+ * Routine Description:
+ *  Format TIM field
+ *
+ *
+ * Return Value:
+ *    VOID
+ *
+-*/
+
+static
+VOID
+s_vMgrFormatTIM(
+    IN PSMgmtObject pMgmt,
+    IN PWLAN_IE_TIM pTIM
+    )
+{
+    BYTE        byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80};
+    BYTE        byMap;
+    UINT        ii, jj;
+    BOOL        bStartFound = FALSE;
+    BOOL        bMulticast = FALSE;
+    WORD        wStartIndex = 0;
+    WORD        wEndIndex = 0;
+
+
+    // Find size of partial virtual bitmap
+    for (ii = 0; ii < (MAX_NODE_NUM + 1); ii++) {
+        byMap = pMgmt->abyPSTxMap[ii];
+        if (!ii) {
+            // Mask out the broadcast bit which is indicated separately.
+            bMulticast = (byMap & byMask[0]) != 0;
+            if(bMulticast) {
+               pMgmt->sNodeDBTable[0].bRxPSPoll = TRUE;
+            }
+            byMap = 0;
+        }
+        if (byMap) {
+            if (!bStartFound) {
+                bStartFound = TRUE;
+                wStartIndex = ii;
+            }
+            wEndIndex = ii;
+        }
+    };
+
+
+    // Round start index down to nearest even number
+    wStartIndex &=  ~BIT0;
+
+    // Round end index up to nearest even number
+    wEndIndex = ((wEndIndex + 1) & ~BIT0);
+
+    // Size of element payload
+
+    pTIM->len =  3 + (wEndIndex - wStartIndex) + 1;
+
+    // Fill in the Fixed parts of the TIM
+    pTIM->byDTIMCount = pMgmt->byDTIMCount;
+    pTIM->byDTIMPeriod = pMgmt->byDTIMPeriod;
+    pTIM->byBitMapCtl = (bMulticast ? TIM_MULTICAST_MASK : 0) |
+        (((wStartIndex >> 1) << 1) & TIM_BITMAPOFFSET_MASK);
+
+    // Append variable part of TIM
+
+    for (ii = wStartIndex, jj =0 ; ii <= wEndIndex; ii++, jj++) {
+         pTIM->byVirtBitMap[jj] = pMgmt->abyPSTxMap[ii];
+    }
+
+    // Aid = 0 don't used.
+    pTIM->byVirtBitMap[0]  &= ~BIT0;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *  Constructs an Beacon frame( Ad-hoc mode)
+ *
+ *
+ * Return Value:
+ *    PTR to frame; or NULL on allocation failue
+ *
+-*/
+
+static
+PSTxMgmtPacket
+s_MgrMakeBeacon(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN WORD wCurrCapInfo,
+    IN WORD wCurrBeaconPeriod,
+    IN UINT uCurrChannel,
+    IN WORD wCurrATIMWinodw,
+    IN PWLAN_IE_SSID pCurrSSID,
+    IN PBYTE pCurrBSSID,
+    IN PWLAN_IE_SUPP_RATES pCurrSuppRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+    )
+{
+    PSTxMgmtPacket      pTxPacket = NULL;
+    WLAN_FR_BEACON      sFrame;
+    BYTE                abyBroadcastAddr[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
+    PBYTE               pbyBuffer;
+    UINT                uLength = 0;
+    PWLAN_IE_IBSS_DFS   pIBSSDFS = NULL;
+    UINT                ii;
+
+    // prepare beacon frame
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_BEACON_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    // Setup the sFrame structure.
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_BEACON_FR_MAXLEN;
+    vMgrEncodeBeacon(&sFrame);
+    // Setup the header
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+        (
+        WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+        WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_BEACON)
+        ));
+
+    if (pDevice->bEnablePSMode) {
+        sFrame.pHdr->sA3.wFrameCtl |= cpu_to_le16((WORD)WLAN_SET_FC_PWRMGT(1));
+    }
+
+    memcpy( sFrame.pHdr->sA3.abyAddr1, abyBroadcastAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pCurrBSSID, WLAN_BSSID_LEN);
+    *sFrame.pwBeaconInterval = cpu_to_le16(wCurrBeaconPeriod);
+    *sFrame.pwCapInfo = cpu_to_le16(wCurrCapInfo);
+    // Copy SSID
+    sFrame.pSSID = (PWLAN_IE_SSID)(sFrame.pBuf + sFrame.len);
+    sFrame.len += ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSSID,
+             pCurrSSID,
+             ((PWLAN_IE_SSID)pCurrSSID)->len + WLAN_IEHDR_LEN
+            );
+    // Copy the rate set
+    sFrame.pSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+    sFrame.len += ((PWLAN_IE_SUPP_RATES)pCurrSuppRates)->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSuppRates,
+           pCurrSuppRates,
+           ((PWLAN_IE_SUPP_RATES)pCurrSuppRates)->len + WLAN_IEHDR_LEN
+          );
+    // DS parameter
+    if (pDevice->eCurrentPHYType != PHY_TYPE_11A) {
+        sFrame.pDSParms = (PWLAN_IE_DS_PARMS)(sFrame.pBuf + sFrame.len);
+        sFrame.len += (1) + WLAN_IEHDR_LEN;
+        sFrame.pDSParms->byElementID = WLAN_EID_DS_PARMS;
+        sFrame.pDSParms->len = 1;
+        sFrame.pDSParms->byCurrChannel = (BYTE)uCurrChannel;
+    }
+    // TIM field
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+        sFrame.pTIM = (PWLAN_IE_TIM)(sFrame.pBuf + sFrame.len);
+        sFrame.pTIM->byElementID = WLAN_EID_TIM;
+        s_vMgrFormatTIM(pMgmt, sFrame.pTIM);
+        sFrame.len += (WLAN_IEHDR_LEN + sFrame.pTIM->len);
+    }
+
+    if (pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
+
+        // IBSS parameter
+        sFrame.pIBSSParms = (PWLAN_IE_IBSS_PARMS)(sFrame.pBuf + sFrame.len);
+        sFrame.len += (2) + WLAN_IEHDR_LEN;
+        sFrame.pIBSSParms->byElementID = WLAN_EID_IBSS_PARMS;
+        sFrame.pIBSSParms->len = 2;
+        sFrame.pIBSSParms->wATIMWindow = wCurrATIMWinodw;
+        if (pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) {
+            /* RSN parameter */
+            sFrame.pRSNWPA = (PWLAN_IE_RSN_EXT)(sFrame.pBuf + sFrame.len);
+            sFrame.pRSNWPA->byElementID = WLAN_EID_RSN_WPA;
+            sFrame.pRSNWPA->len = 12;
+            sFrame.pRSNWPA->abyOUI[0] = 0x00;
+            sFrame.pRSNWPA->abyOUI[1] = 0x50;
+            sFrame.pRSNWPA->abyOUI[2] = 0xf2;
+            sFrame.pRSNWPA->abyOUI[3] = 0x01;
+            sFrame.pRSNWPA->wVersion = 1;
+            sFrame.pRSNWPA->abyMulticast[0] = 0x00;
+            sFrame.pRSNWPA->abyMulticast[1] = 0x50;
+            sFrame.pRSNWPA->abyMulticast[2] = 0xf2;
+            if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled)
+                sFrame.pRSNWPA->abyMulticast[3] = 0x04;//AES
+            else if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled)
+                sFrame.pRSNWPA->abyMulticast[3] = 0x02;//TKIP
+            else if (pDevice->eEncryptionStatus == Ndis802_11Encryption1Enabled)
+                sFrame.pRSNWPA->abyMulticast[3] = 0x01;//WEP40
+            else
+                sFrame.pRSNWPA->abyMulticast[3] = 0x00;//NONE
+
+            // Pairwise Key Cipher Suite
+            sFrame.pRSNWPA->wPKCount = 0;
+            // Auth Key Management Suite
+            *((PWORD)(sFrame.pBuf + sFrame.len + sFrame.pRSNWPA->len))=0;
+            sFrame.pRSNWPA->len +=2;
+
+            // RSN Capabilites
+            *((PWORD)(sFrame.pBuf + sFrame.len + sFrame.pRSNWPA->len))=0;
+            sFrame.pRSNWPA->len +=2;
+            sFrame.len += sFrame.pRSNWPA->len + WLAN_IEHDR_LEN;
+        }
+    }
+
+    if ((pMgmt->b11hEnable == TRUE) &&
+        (pMgmt->eCurrentPHYMode == PHY_TYPE_11A)) {
+        // Country IE
+        pbyBuffer = (PBYTE)(sFrame.pBuf + sFrame.len);
+        CARDvSetCountryIE(pMgmt->pAdapter, pbyBuffer);
+        CARDvSetCountryInfo(pMgmt->pAdapter, PHY_TYPE_11A, pbyBuffer);
+        uLength += ((PWLAN_IE_COUNTRY) pbyBuffer)->len + WLAN_IEHDR_LEN;
+        pbyBuffer += (((PWLAN_IE_COUNTRY) pbyBuffer)->len + WLAN_IEHDR_LEN);
+        // Power Constrain IE
+        ((PWLAN_IE_PW_CONST) pbyBuffer)->byElementID = WLAN_EID_PWR_CONSTRAINT;
+        ((PWLAN_IE_PW_CONST) pbyBuffer)->len = 1;
+        ((PWLAN_IE_PW_CONST) pbyBuffer)->byPower = 0;
+        pbyBuffer += (1) + WLAN_IEHDR_LEN;
+        uLength += (1) + WLAN_IEHDR_LEN;
+        if (pMgmt->bSwitchChannel == TRUE) {
+            // Channel Switch IE
+            ((PWLAN_IE_CH_SW) pbyBuffer)->byElementID = WLAN_EID_CH_SWITCH;
+            ((PWLAN_IE_CH_SW) pbyBuffer)->len = 3;
+            ((PWLAN_IE_CH_SW) pbyBuffer)->byMode = 1;
+            ((PWLAN_IE_CH_SW) pbyBuffer)->byChannel = CARDbyGetChannelNumber(pMgmt->pAdapter, pMgmt->byNewChannel);
+            ((PWLAN_IE_CH_SW) pbyBuffer)->byCount = 0;
+            pbyBuffer += (3) + WLAN_IEHDR_LEN;
+            uLength += (3) + WLAN_IEHDR_LEN;
+        }
+        // TPC report
+        ((PWLAN_IE_TPC_REP) pbyBuffer)->byElementID = WLAN_EID_TPC_REP;
+        ((PWLAN_IE_TPC_REP) pbyBuffer)->len = 2;
+        ((PWLAN_IE_TPC_REP) pbyBuffer)->byTxPower = CARDbyGetTransmitPower(pMgmt->pAdapter);
+        ((PWLAN_IE_TPC_REP) pbyBuffer)->byLinkMargin = 0;
+        pbyBuffer += (2) + WLAN_IEHDR_LEN;
+        uLength += (2) + WLAN_IEHDR_LEN;
+        // IBSS DFS
+        if (pMgmt->eCurrMode != WMAC_MODE_ESS_AP) {
+            pIBSSDFS = (PWLAN_IE_IBSS_DFS) pbyBuffer;
+            pIBSSDFS->byElementID = WLAN_EID_IBSS_DFS;
+            pIBSSDFS->len = 7;
+            MEMvCopy(   pIBSSDFS->abyDFSOwner,
+                        pMgmt->abyIBSSDFSOwner,
+                        6);
+            pIBSSDFS->byDFSRecovery = pMgmt->byIBSSDFSRecovery;
+            pbyBuffer += (7) + WLAN_IEHDR_LEN;
+            uLength += (7) + WLAN_IEHDR_LEN;
+            for(ii=CB_MAX_CHANNEL_24G+1; ii<=CB_MAX_CHANNEL; ii++ ) {
+                if (CARDbGetChannelMapInfo(pMgmt->pAdapter, ii, pbyBuffer, pbyBuffer+1) == TRUE) {
+                    pbyBuffer += 2;
+                    uLength += 2;
+                    pIBSSDFS->len += 2;
+                }
+            }
+        }
+        sFrame.len += uLength;
+    }
+
+    if (pMgmt->eCurrentPHYMode == PHY_TYPE_11G) {
+        sFrame.pERP = (PWLAN_IE_ERP)(sFrame.pBuf + sFrame.len);
+        sFrame.len += 1 + WLAN_IEHDR_LEN;
+        sFrame.pERP->byElementID = WLAN_EID_ERP;
+        sFrame.pERP->len = 1;
+        sFrame.pERP->byContext = 0;
+        if (pDevice->bProtectMode == TRUE)
+            sFrame.pERP->byContext |= WLAN_EID_ERP_USE_PROTECTION;
+        if (pDevice->bNonERPPresent == TRUE)
+            sFrame.pERP->byContext |= WLAN_EID_ERP_NONERP_PRESENT;
+        if (pDevice->bBarkerPreambleMd == TRUE)
+            sFrame.pERP->byContext |= WLAN_EID_ERP_BARKER_MODE;
+    }
+    if (((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len != 0) {
+        sFrame.pExtSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+        sFrame.len += ((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len + WLAN_IEHDR_LEN;
+        MEMvCopy(sFrame.pExtSuppRates,
+             pCurrExtSuppRates,
+             ((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len + WLAN_IEHDR_LEN
+             );
+    }
+    // hostapd wpa/wpa2 IE
+    if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) && (pDevice->bEnableHostapd == TRUE)) {
+         if (pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) {
+             if (pMgmt->wWPAIELen != 0) {
+                 sFrame.pRSN = (PWLAN_IE_RSN)(sFrame.pBuf + sFrame.len);
+                 memcpy(sFrame.pRSN, pMgmt->abyWPAIE, pMgmt->wWPAIELen);
+                 sFrame.len += pMgmt->wWPAIELen;
+             }
+         }
+    }
+
+    /* Adjust the length fields */
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+
+    return pTxPacket;
+}
+
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *  Constructs an Prob-response frame
+ *
+ *
+ * Return Value:
+ *    PTR to frame; or NULL on allocation failue
+ *
+-*/
+
+
+
+
+PSTxMgmtPacket
+s_MgrMakeProbeResponse(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN WORD wCurrCapInfo,
+    IN WORD wCurrBeaconPeriod,
+    IN UINT uCurrChannel,
+    IN WORD wCurrATIMWinodw,
+    IN PBYTE pDstAddr,
+    IN PWLAN_IE_SSID pCurrSSID,
+    IN PBYTE pCurrBSSID,
+    IN PWLAN_IE_SUPP_RATES pCurrSuppRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates,
+    IN BYTE byPHYType
+    )
+{
+    PSTxMgmtPacket      pTxPacket = NULL;
+    WLAN_FR_PROBERESP   sFrame;
+    PBYTE               pbyBuffer;
+    UINT                uLength = 0;
+    PWLAN_IE_IBSS_DFS   pIBSSDFS = NULL;
+    UINT                ii;
+
+
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_PROBERESP_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    // Setup the sFrame structure.
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_PROBERESP_FR_MAXLEN;
+    vMgrEncodeProbeResponse(&sFrame);
+    // Setup the header
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+        (
+        WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+        WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_PROBERESP)
+        ));
+    memcpy( sFrame.pHdr->sA3.abyAddr1, pDstAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pCurrBSSID, WLAN_BSSID_LEN);
+    *sFrame.pwBeaconInterval = cpu_to_le16(wCurrBeaconPeriod);
+    *sFrame.pwCapInfo = cpu_to_le16(wCurrCapInfo);
+
+    if (byPHYType == BB_TYPE_11B) {
+        *sFrame.pwCapInfo &= cpu_to_le16((WORD)~(WLAN_SET_CAP_INFO_SHORTSLOTTIME(1)));
+    }
+
+    // Copy SSID
+    sFrame.pSSID = (PWLAN_IE_SSID)(sFrame.pBuf + sFrame.len);
+    sFrame.len += ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSSID,
+           pCurrSSID,
+           ((PWLAN_IE_SSID)pCurrSSID)->len + WLAN_IEHDR_LEN
+           );
+    // Copy the rate set
+    sFrame.pSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+
+    sFrame.len += ((PWLAN_IE_SUPP_RATES)pCurrSuppRates)->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSuppRates,
+           pCurrSuppRates,
+           ((PWLAN_IE_SUPP_RATES)pCurrSuppRates)->len + WLAN_IEHDR_LEN
+          );
+
+    // DS parameter
+    if (pDevice->eCurrentPHYType != PHY_TYPE_11A) {
+        sFrame.pDSParms = (PWLAN_IE_DS_PARMS)(sFrame.pBuf + sFrame.len);
+        sFrame.len += (1) + WLAN_IEHDR_LEN;
+        sFrame.pDSParms->byElementID = WLAN_EID_DS_PARMS;
+        sFrame.pDSParms->len = 1;
+        sFrame.pDSParms->byCurrChannel = (BYTE)uCurrChannel;
+    }
+
+    if (pMgmt->eCurrMode != WMAC_MODE_ESS_AP) {
+        // IBSS parameter
+        sFrame.pIBSSParms = (PWLAN_IE_IBSS_PARMS)(sFrame.pBuf + sFrame.len);
+        sFrame.len += (2) + WLAN_IEHDR_LEN;
+        sFrame.pIBSSParms->byElementID = WLAN_EID_IBSS_PARMS;
+        sFrame.pIBSSParms->len = 2;
+        sFrame.pIBSSParms->wATIMWindow = 0;
+    }
+    if (pDevice->eCurrentPHYType == PHY_TYPE_11G) {
+        sFrame.pERP = (PWLAN_IE_ERP)(sFrame.pBuf + sFrame.len);
+        sFrame.len += 1 + WLAN_IEHDR_LEN;
+        sFrame.pERP->byElementID = WLAN_EID_ERP;
+        sFrame.pERP->len = 1;
+        sFrame.pERP->byContext = 0;
+        if (pDevice->bProtectMode == TRUE)
+            sFrame.pERP->byContext |= WLAN_EID_ERP_USE_PROTECTION;
+        if (pDevice->bNonERPPresent == TRUE)
+            sFrame.pERP->byContext |= WLAN_EID_ERP_NONERP_PRESENT;
+        if (pDevice->bBarkerPreambleMd == TRUE)
+            sFrame.pERP->byContext |= WLAN_EID_ERP_BARKER_MODE;
+    }
+
+    if ((pMgmt->b11hEnable == TRUE) &&
+        (pMgmt->eCurrentPHYMode == PHY_TYPE_11A)) {
+        // Country IE
+        pbyBuffer = (PBYTE)(sFrame.pBuf + sFrame.len);
+        CARDvSetCountryIE(pMgmt->pAdapter, pbyBuffer);
+        CARDvSetCountryInfo(pMgmt->pAdapter, PHY_TYPE_11A, pbyBuffer);
+        uLength += ((PWLAN_IE_COUNTRY) pbyBuffer)->len + WLAN_IEHDR_LEN;
+        pbyBuffer += (((PWLAN_IE_COUNTRY) pbyBuffer)->len + WLAN_IEHDR_LEN);
+        // Power Constrain IE
+        ((PWLAN_IE_PW_CONST) pbyBuffer)->byElementID = WLAN_EID_PWR_CONSTRAINT;
+        ((PWLAN_IE_PW_CONST) pbyBuffer)->len = 1;
+        ((PWLAN_IE_PW_CONST) pbyBuffer)->byPower = 0;
+        pbyBuffer += (1) + WLAN_IEHDR_LEN;
+        uLength += (1) + WLAN_IEHDR_LEN;
+        if (pMgmt->bSwitchChannel == TRUE) {
+            // Channel Switch IE
+            ((PWLAN_IE_CH_SW) pbyBuffer)->byElementID = WLAN_EID_CH_SWITCH;
+            ((PWLAN_IE_CH_SW) pbyBuffer)->len = 3;
+            ((PWLAN_IE_CH_SW) pbyBuffer)->byMode = 1;
+            ((PWLAN_IE_CH_SW) pbyBuffer)->byChannel = CARDbyGetChannelNumber(pMgmt->pAdapter, pMgmt->byNewChannel);
+            ((PWLAN_IE_CH_SW) pbyBuffer)->byCount = 0;
+            pbyBuffer += (3) + WLAN_IEHDR_LEN;
+            uLength += (3) + WLAN_IEHDR_LEN;
+        }
+        // TPC report
+        ((PWLAN_IE_TPC_REP) pbyBuffer)->byElementID = WLAN_EID_TPC_REP;
+        ((PWLAN_IE_TPC_REP) pbyBuffer)->len = 2;
+        ((PWLAN_IE_TPC_REP) pbyBuffer)->byTxPower = CARDbyGetTransmitPower(pMgmt->pAdapter);
+        ((PWLAN_IE_TPC_REP) pbyBuffer)->byLinkMargin = 0;
+        pbyBuffer += (2) + WLAN_IEHDR_LEN;
+        uLength += (2) + WLAN_IEHDR_LEN;
+        // IBSS DFS
+        if (pMgmt->eCurrMode != WMAC_MODE_ESS_AP) {
+            pIBSSDFS = (PWLAN_IE_IBSS_DFS) pbyBuffer;
+            pIBSSDFS->byElementID = WLAN_EID_IBSS_DFS;
+            pIBSSDFS->len = 7;
+            MEMvCopy(   pIBSSDFS->abyDFSOwner,
+                        pMgmt->abyIBSSDFSOwner,
+                        6);
+            pIBSSDFS->byDFSRecovery = pMgmt->byIBSSDFSRecovery;
+            pbyBuffer += (7) + WLAN_IEHDR_LEN;
+            uLength += (7) + WLAN_IEHDR_LEN;
+            for(ii=CB_MAX_CHANNEL_24G+1; ii<=CB_MAX_CHANNEL; ii++ ) {
+                if (CARDbGetChannelMapInfo(pMgmt->pAdapter, ii, pbyBuffer, pbyBuffer+1) == TRUE) {
+                    pbyBuffer += 2;
+                    uLength += 2;
+                    pIBSSDFS->len += 2;
+                }
+            }
+        }
+        sFrame.len += uLength;
+    }
+
+
+    if (((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len != 0) {
+        sFrame.pExtSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+        sFrame.len += ((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len + WLAN_IEHDR_LEN;
+        MEMvCopy(sFrame.pExtSuppRates,
+             pCurrExtSuppRates,
+             ((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len + WLAN_IEHDR_LEN
+             );
+    }
+
+    // hostapd wpa/wpa2 IE
+    if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) && (pDevice->bEnableHostapd == TRUE)) {
+         if (pMgmt->eAuthenMode == WMAC_AUTH_WPANONE) {
+             if (pMgmt->wWPAIELen != 0) {
+                 sFrame.pRSN = (PWLAN_IE_RSN)(sFrame.pBuf + sFrame.len);
+                 memcpy(sFrame.pRSN, pMgmt->abyWPAIE, pMgmt->wWPAIELen);
+                 sFrame.len += pMgmt->wWPAIELen;
+             }
+         }
+    }
+
+    // Adjust the length fields
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+
+    return pTxPacket;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *  Constructs an association request frame
+ *
+ *
+ * Return Value:
+ *    A ptr to frame or NULL on allocation failue
+ *
+-*/
+
+
+PSTxMgmtPacket
+s_MgrMakeAssocRequest(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PBYTE pDAddr,
+    IN WORD wCurrCapInfo,
+    IN WORD wListenInterval,
+    IN PWLAN_IE_SSID pCurrSSID,
+    IN PWLAN_IE_SUPP_RATES pCurrRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+    )
+{
+    PSTxMgmtPacket      pTxPacket = NULL;
+    WLAN_FR_ASSOCREQ    sFrame;
+    PBYTE               pbyIEs;
+    PBYTE               pbyRSN;
+
+
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_ASSOCREQ_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    // Setup the sFrame structure.
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_ASSOCREQ_FR_MAXLEN;
+    // format fixed field frame structure
+    vMgrEncodeAssocRequest(&sFrame);
+    // Setup the header
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+        (
+        WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+        WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_ASSOCREQ)
+        ));
+    memcpy( sFrame.pHdr->sA3.abyAddr1, pDAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+
+    // Set the capibility and listen interval
+    *(sFrame.pwCapInfo) = cpu_to_le16(wCurrCapInfo);
+    *(sFrame.pwListenInterval) = cpu_to_le16(wListenInterval);
+
+    // sFrame.len point to end of fixed field
+    sFrame.pSSID = (PWLAN_IE_SSID)(sFrame.pBuf + sFrame.len);
+    sFrame.len += pCurrSSID->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSSID, pCurrSSID, pCurrSSID->len + WLAN_IEHDR_LEN);
+
+    pMgmt->sAssocInfo.AssocInfo.RequestIELength = pCurrSSID->len + WLAN_IEHDR_LEN;
+    pMgmt->sAssocInfo.AssocInfo.OffsetRequestIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION);
+    pbyIEs = pMgmt->sAssocInfo.abyIEs;
+    MEMvCopy(pbyIEs, pCurrSSID, pCurrSSID->len + WLAN_IEHDR_LEN);
+    pbyIEs += pCurrSSID->len + WLAN_IEHDR_LEN;
+
+    // Copy the rate set
+    sFrame.pSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+    if ((pDevice->eCurrentPHYType == PHY_TYPE_11B) && (pCurrRates->len > 4))
+        sFrame.len += 4 + WLAN_IEHDR_LEN;
+    else
+        sFrame.len += pCurrRates->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSuppRates, pCurrRates, pCurrRates->len + WLAN_IEHDR_LEN);
+
+    // Copy the extension rate set
+    if ((pDevice->eCurrentPHYType == PHY_TYPE_11G) && (pCurrExtSuppRates->len > 0)) {
+        sFrame.pExtSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+        sFrame.len += pCurrExtSuppRates->len + WLAN_IEHDR_LEN;
+        memcpy(sFrame.pExtSuppRates, pCurrExtSuppRates, pCurrExtSuppRates->len + WLAN_IEHDR_LEN);
+    }
+
+    pMgmt->sAssocInfo.AssocInfo.RequestIELength += pCurrRates->len + WLAN_IEHDR_LEN;
+    MEMvCopy(pbyIEs, pCurrRates, pCurrRates->len + WLAN_IEHDR_LEN);
+    pbyIEs += pCurrRates->len + WLAN_IEHDR_LEN;
+
+    // for 802.11h
+    if (pMgmt->b11hEnable == TRUE) {
+        if (sFrame.pCurrPowerCap == NULL) {
+            sFrame.pCurrPowerCap = (PWLAN_IE_PW_CAP)(sFrame.pBuf + sFrame.len);
+            sFrame.len += (2 + WLAN_IEHDR_LEN);
+            sFrame.pCurrPowerCap->byElementID = WLAN_EID_PWR_CAPABILITY;
+            sFrame.pCurrPowerCap->len = 2;
+            CARDvGetPowerCapability(pMgmt->pAdapter,
+                                    &(sFrame.pCurrPowerCap->byMinPower),
+                                    &(sFrame.pCurrPowerCap->byMaxPower)
+                                    );
+        }
+        if (sFrame.pCurrSuppCh == NULL) {
+            sFrame.pCurrSuppCh = (PWLAN_IE_SUPP_CH)(sFrame.pBuf + sFrame.len);
+            sFrame.len += CARDbySetSupportChannels(pMgmt->pAdapter,(PBYTE)sFrame.pCurrSuppCh);
+        }
+    }
+
+    if (((pMgmt->eAuthenMode == WMAC_AUTH_WPA) ||
+         (pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK) ||
+         (pMgmt->eAuthenMode == WMAC_AUTH_WPANONE)) &&
+        (pMgmt->pCurrBSS != NULL)) {
+        /* WPA IE */
+        sFrame.pRSNWPA = (PWLAN_IE_RSN_EXT)(sFrame.pBuf + sFrame.len);
+        sFrame.pRSNWPA->byElementID = WLAN_EID_RSN_WPA;
+        sFrame.pRSNWPA->len = 16;
+        sFrame.pRSNWPA->abyOUI[0] = 0x00;
+        sFrame.pRSNWPA->abyOUI[1] = 0x50;
+        sFrame.pRSNWPA->abyOUI[2] = 0xf2;
+        sFrame.pRSNWPA->abyOUI[3] = 0x01;
+        sFrame.pRSNWPA->wVersion = 1;
+        //Group Key Cipher Suite
+        sFrame.pRSNWPA->abyMulticast[0] = 0x00;
+        sFrame.pRSNWPA->abyMulticast[1] = 0x50;
+        sFrame.pRSNWPA->abyMulticast[2] = 0xf2;
+        if (pMgmt->byCSSGK == KEY_CTL_WEP) {
+            sFrame.pRSNWPA->abyMulticast[3] = pMgmt->pCurrBSS->byGKType;
+        } else if (pMgmt->byCSSGK == KEY_CTL_TKIP) {
+            sFrame.pRSNWPA->abyMulticast[3] = WPA_TKIP;
+        } else if (pMgmt->byCSSGK == KEY_CTL_CCMP) {
+            sFrame.pRSNWPA->abyMulticast[3] = WPA_AESCCMP;
+        } else {
+            sFrame.pRSNWPA->abyMulticast[3] = WPA_NONE;
+        }
+        // Pairwise Key Cipher Suite
+        sFrame.pRSNWPA->wPKCount = 1;
+        sFrame.pRSNWPA->PKSList[0].abyOUI[0] = 0x00;
+        sFrame.pRSNWPA->PKSList[0].abyOUI[1] = 0x50;
+        sFrame.pRSNWPA->PKSList[0].abyOUI[2] = 0xf2;
+        if (pMgmt->byCSSPK == KEY_CTL_TKIP) {
+            sFrame.pRSNWPA->PKSList[0].abyOUI[3] = WPA_TKIP;
+        } else if (pMgmt->byCSSPK == KEY_CTL_CCMP) {
+            sFrame.pRSNWPA->PKSList[0].abyOUI[3] = WPA_AESCCMP;
+        } else {
+            sFrame.pRSNWPA->PKSList[0].abyOUI[3] = WPA_NONE;
+        }
+        // Auth Key Management Suite
+        pbyRSN = (PBYTE)(sFrame.pBuf + sFrame.len + 2 + sFrame.pRSNWPA->len);
+        *pbyRSN++=0x01;
+        *pbyRSN++=0x00;
+        *pbyRSN++=0x00;
+        *pbyRSN++=0x50;
+        *pbyRSN++=0xf2;
+        if (pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK) {
+            *pbyRSN++=WPA_AUTH_PSK;
+        }
+        else if (pMgmt->eAuthenMode == WMAC_AUTH_WPA) {
+            *pbyRSN++=WPA_AUTH_IEEE802_1X;
+        }
+        else {
+            *pbyRSN++=WPA_NONE;
+        }
+        sFrame.pRSNWPA->len +=6;
+
+        // RSN Capabilites
+        *pbyRSN++=0x00;
+        *pbyRSN++=0x00;
+        sFrame.pRSNWPA->len +=2;
+        sFrame.len += sFrame.pRSNWPA->len + WLAN_IEHDR_LEN;
+        // copy to AssocInfo. for OID_802_11_ASSOCIATION_INFORMATION
+        pMgmt->sAssocInfo.AssocInfo.RequestIELength += sFrame.pRSNWPA->len + WLAN_IEHDR_LEN;
+        MEMvCopy(pbyIEs, sFrame.pRSNWPA, sFrame.pRSNWPA->len + WLAN_IEHDR_LEN);
+        pbyIEs += sFrame.pRSNWPA->len + WLAN_IEHDR_LEN;
+
+    } else if (((pMgmt->eAuthenMode == WMAC_AUTH_WPA2) ||
+                (pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK)) &&
+               (pMgmt->pCurrBSS != NULL)) {
+        UINT                ii;
+        PWORD               pwPMKID;
+
+        // WPA IE
+        sFrame.pRSN = (PWLAN_IE_RSN)(sFrame.pBuf + sFrame.len);
+        sFrame.pRSN->byElementID = WLAN_EID_RSN;
+        sFrame.pRSN->len = 6; //Version(2)+GK(4)
+        sFrame.pRSN->wVersion = 1;
+        //Group Key Cipher Suite
+        sFrame.pRSN->abyRSN[0] = 0x00;
+        sFrame.pRSN->abyRSN[1] = 0x0F;
+        sFrame.pRSN->abyRSN[2] = 0xAC;
+        if (pMgmt->byCSSGK == KEY_CTL_WEP) {
+            sFrame.pRSN->abyRSN[3] = pMgmt->pCurrBSS->byCSSGK;
+        } else if (pMgmt->byCSSGK == KEY_CTL_TKIP) {
+            sFrame.pRSN->abyRSN[3] = WLAN_11i_CSS_TKIP;
+        } else if (pMgmt->byCSSGK == KEY_CTL_CCMP) {
+            sFrame.pRSN->abyRSN[3] = WLAN_11i_CSS_CCMP;
+        } else {
+            sFrame.pRSN->abyRSN[3] = WLAN_11i_CSS_UNKNOWN;
+        }
+
+        // Pairwise Key Cipher Suite
+        sFrame.pRSN->abyRSN[4] = 1;
+        sFrame.pRSN->abyRSN[5] = 0;
+        sFrame.pRSN->abyRSN[6] = 0x00;
+        sFrame.pRSN->abyRSN[7] = 0x0F;
+        sFrame.pRSN->abyRSN[8] = 0xAC;
+        if (pMgmt->byCSSPK == KEY_CTL_TKIP) {
+            sFrame.pRSN->abyRSN[9] = WLAN_11i_CSS_TKIP;
+        } else if (pMgmt->byCSSPK == KEY_CTL_CCMP) {
+            sFrame.pRSN->abyRSN[9] = WLAN_11i_CSS_CCMP;
+        } else if (pMgmt->byCSSPK == KEY_CTL_NONE) {
+            sFrame.pRSN->abyRSN[9] = WLAN_11i_CSS_USE_GROUP;
+        } else {
+            sFrame.pRSN->abyRSN[9] = WLAN_11i_CSS_UNKNOWN;
+        }
+        sFrame.pRSN->len += 6;
+
+        // Auth Key Management Suite
+        sFrame.pRSN->abyRSN[10] = 1;
+        sFrame.pRSN->abyRSN[11] = 0;
+        sFrame.pRSN->abyRSN[12] = 0x00;
+        sFrame.pRSN->abyRSN[13] = 0x0F;
+        sFrame.pRSN->abyRSN[14] = 0xAC;
+        if (pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK) {
+            sFrame.pRSN->abyRSN[15] = WLAN_11i_AKMSS_PSK;
+        } else if (pMgmt->eAuthenMode == WMAC_AUTH_WPA2) {
+            sFrame.pRSN->abyRSN[15] = WLAN_11i_AKMSS_802_1X;
+        } else {
+            sFrame.pRSN->abyRSN[15] = WLAN_11i_AKMSS_UNKNOWN;
+        }
+        sFrame.pRSN->len +=6;
+
+        // RSN Capabilites
+        if (pMgmt->pCurrBSS->sRSNCapObj.bRSNCapExist == TRUE) {
+            MEMvCopy(&sFrame.pRSN->abyRSN[16], &pMgmt->pCurrBSS->sRSNCapObj.wRSNCap, 2);
+        } else {
+            sFrame.pRSN->abyRSN[16] = 0;
+            sFrame.pRSN->abyRSN[17] = 0;
+        }
+        sFrame.pRSN->len +=2;
+
+        if ((pDevice->gsPMKID.BSSIDInfoCount > 0) && (pDevice->bRoaming == TRUE) && (pMgmt->eAuthenMode == WMAC_AUTH_WPA2)) {
+            // RSN PMKID
+            pbyRSN = &sFrame.pRSN->abyRSN[18];
+            pwPMKID = (PWORD)pbyRSN; // Point to PMKID count
+            *pwPMKID = 0;            // Initialize PMKID count
+            pbyRSN += 2;             // Point to PMKID list
+            for (ii = 0; ii < pDevice->gsPMKID.BSSIDInfoCount; ii++) {
+                if (MEMEqualMemory(&pDevice->gsPMKID.BSSIDInfo[ii].BSSID[0], pMgmt->abyCurrBSSID, U_ETHER_ADDR_LEN)) {
+                    (*pwPMKID) ++;
+                    MEMvCopy(pbyRSN, pDevice->gsPMKID.BSSIDInfo[ii].PMKID, 16);
+                    pbyRSN += 16;
+                }
+            }
+            if (*pwPMKID != 0) {
+                sFrame.pRSN->len += (2 + (*pwPMKID)*16);
+            }
+        }
+
+        sFrame.len += sFrame.pRSN->len + WLAN_IEHDR_LEN;
+        // copy to AssocInfo. for OID_802_11_ASSOCIATION_INFORMATION
+        pMgmt->sAssocInfo.AssocInfo.RequestIELength += sFrame.pRSN->len + WLAN_IEHDR_LEN;
+        MEMvCopy(pbyIEs, sFrame.pRSN, sFrame.pRSN->len + WLAN_IEHDR_LEN);
+        pbyIEs += sFrame.pRSN->len + WLAN_IEHDR_LEN;
+    }
+
+
+    // Adjust the length fields
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+    return pTxPacket;
+}
+
+
+
+
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *  Constructs an re-association request frame
+ *
+ *
+ * Return Value:
+ *    A ptr to frame or NULL on allocation failue
+ *
+-*/
+
+
+PSTxMgmtPacket
+s_MgrMakeReAssocRequest(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PBYTE pDAddr,
+    IN WORD wCurrCapInfo,
+    IN WORD wListenInterval,
+    IN PWLAN_IE_SSID pCurrSSID,
+    IN PWLAN_IE_SUPP_RATES pCurrRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+    )
+{
+    PSTxMgmtPacket      pTxPacket = NULL;
+    WLAN_FR_REASSOCREQ  sFrame;
+    PBYTE               pbyIEs;
+    PBYTE               pbyRSN;
+
+
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset( pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_REASSOCREQ_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    /* Setup the sFrame structure. */
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_REASSOCREQ_FR_MAXLEN;
+
+    // format fixed field frame structure
+    vMgrEncodeReassocRequest(&sFrame);
+
+    /* Setup the header */
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+        (
+        WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+        WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_REASSOCREQ)
+        ));
+    memcpy( sFrame.pHdr->sA3.abyAddr1, pDAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+
+    /* Set the capibility and listen interval */
+    *(sFrame.pwCapInfo) = cpu_to_le16(wCurrCapInfo);
+    *(sFrame.pwListenInterval) = cpu_to_le16(wListenInterval);
+
+    memcpy(sFrame.pAddrCurrAP, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+    /* Copy the SSID */
+    /* sFrame.len point to end of fixed field */
+    sFrame.pSSID = (PWLAN_IE_SSID)(sFrame.pBuf + sFrame.len);
+    sFrame.len += pCurrSSID->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSSID, pCurrSSID, pCurrSSID->len + WLAN_IEHDR_LEN);
+
+    pMgmt->sAssocInfo.AssocInfo.RequestIELength = pCurrSSID->len + WLAN_IEHDR_LEN;
+    pMgmt->sAssocInfo.AssocInfo.OffsetRequestIEs = sizeof(NDIS_802_11_ASSOCIATION_INFORMATION);
+    pbyIEs = pMgmt->sAssocInfo.abyIEs;
+    MEMvCopy(pbyIEs, pCurrSSID, pCurrSSID->len + WLAN_IEHDR_LEN);
+    pbyIEs += pCurrSSID->len + WLAN_IEHDR_LEN;
+
+    /* Copy the rate set */
+    /* sFrame.len point to end of SSID */
+    sFrame.pSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+    sFrame.len += pCurrRates->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSuppRates, pCurrRates, pCurrRates->len + WLAN_IEHDR_LEN);
+
+    // Copy the extension rate set
+    if ((pMgmt->eCurrentPHYMode == PHY_TYPE_11G) && (pCurrExtSuppRates->len > 0)) {
+        sFrame.pExtSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+        sFrame.len += pCurrExtSuppRates->len + WLAN_IEHDR_LEN;
+        memcpy(sFrame.pExtSuppRates, pCurrExtSuppRates, pCurrExtSuppRates->len + WLAN_IEHDR_LEN);
+    }
+
+    pMgmt->sAssocInfo.AssocInfo.RequestIELength += pCurrRates->len + WLAN_IEHDR_LEN;
+    MEMvCopy(pbyIEs, pCurrRates, pCurrRates->len + WLAN_IEHDR_LEN);
+    pbyIEs += pCurrRates->len + WLAN_IEHDR_LEN;
+
+    if (((pMgmt->eAuthenMode == WMAC_AUTH_WPA) ||
+         (pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK) ||
+         (pMgmt->eAuthenMode == WMAC_AUTH_WPANONE)) &&
+        (pMgmt->pCurrBSS != NULL)) {
+        /* WPA IE */
+        sFrame.pRSNWPA = (PWLAN_IE_RSN_EXT)(sFrame.pBuf + sFrame.len);
+        sFrame.pRSNWPA->byElementID = WLAN_EID_RSN_WPA;
+        sFrame.pRSNWPA->len = 16;
+        sFrame.pRSNWPA->abyOUI[0] = 0x00;
+        sFrame.pRSNWPA->abyOUI[1] = 0x50;
+        sFrame.pRSNWPA->abyOUI[2] = 0xf2;
+        sFrame.pRSNWPA->abyOUI[3] = 0x01;
+        sFrame.pRSNWPA->wVersion = 1;
+        //Group Key Cipher Suite
+        sFrame.pRSNWPA->abyMulticast[0] = 0x00;
+        sFrame.pRSNWPA->abyMulticast[1] = 0x50;
+        sFrame.pRSNWPA->abyMulticast[2] = 0xf2;
+        if (pMgmt->byCSSGK == KEY_CTL_WEP) {
+            sFrame.pRSNWPA->abyMulticast[3] = pMgmt->pCurrBSS->byGKType;
+        } else if (pMgmt->byCSSGK == KEY_CTL_TKIP) {
+            sFrame.pRSNWPA->abyMulticast[3] = WPA_TKIP;
+        } else if (pMgmt->byCSSGK == KEY_CTL_CCMP) {
+            sFrame.pRSNWPA->abyMulticast[3] = WPA_AESCCMP;
+        } else {
+            sFrame.pRSNWPA->abyMulticast[3] = WPA_NONE;
+        }
+        // Pairwise Key Cipher Suite
+        sFrame.pRSNWPA->wPKCount = 1;
+        sFrame.pRSNWPA->PKSList[0].abyOUI[0] = 0x00;
+        sFrame.pRSNWPA->PKSList[0].abyOUI[1] = 0x50;
+        sFrame.pRSNWPA->PKSList[0].abyOUI[2] = 0xf2;
+        if (pMgmt->byCSSPK == KEY_CTL_TKIP) {
+            sFrame.pRSNWPA->PKSList[0].abyOUI[3] = WPA_TKIP;
+        } else if (pMgmt->byCSSPK == KEY_CTL_CCMP) {
+            sFrame.pRSNWPA->PKSList[0].abyOUI[3] = WPA_AESCCMP;
+        } else {
+            sFrame.pRSNWPA->PKSList[0].abyOUI[3] = WPA_NONE;
+        }
+        // Auth Key Management Suite
+        pbyRSN = (PBYTE)(sFrame.pBuf + sFrame.len + 2 + sFrame.pRSNWPA->len);
+        *pbyRSN++=0x01;
+        *pbyRSN++=0x00;
+        *pbyRSN++=0x00;
+        *pbyRSN++=0x50;
+        *pbyRSN++=0xf2;
+        if (pMgmt->eAuthenMode == WMAC_AUTH_WPAPSK) {
+            *pbyRSN++=WPA_AUTH_PSK;
+        } else if (pMgmt->eAuthenMode == WMAC_AUTH_WPA) {
+            *pbyRSN++=WPA_AUTH_IEEE802_1X;
+        } else {
+            *pbyRSN++=WPA_NONE;
+        }
+        sFrame.pRSNWPA->len +=6;
+
+        // RSN Capabilites
+        *pbyRSN++=0x00;
+        *pbyRSN++=0x00;
+        sFrame.pRSNWPA->len +=2;
+        sFrame.len += sFrame.pRSNWPA->len + WLAN_IEHDR_LEN;
+        // copy to AssocInfo. for OID_802_11_ASSOCIATION_INFORMATION
+        pMgmt->sAssocInfo.AssocInfo.RequestIELength += sFrame.pRSNWPA->len + WLAN_IEHDR_LEN;
+        MEMvCopy(pbyIEs, sFrame.pRSNWPA, sFrame.pRSNWPA->len + WLAN_IEHDR_LEN);
+        pbyIEs += sFrame.pRSNWPA->len + WLAN_IEHDR_LEN;
+
+    } else if (((pMgmt->eAuthenMode == WMAC_AUTH_WPA2) ||
+                (pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK)) &&
+               (pMgmt->pCurrBSS != NULL)) {
+        UINT                ii;
+        PWORD               pwPMKID;
+
+        /* WPA IE */
+        sFrame.pRSN = (PWLAN_IE_RSN)(sFrame.pBuf + sFrame.len);
+        sFrame.pRSN->byElementID = WLAN_EID_RSN;
+        sFrame.pRSN->len = 6; //Version(2)+GK(4)
+        sFrame.pRSN->wVersion = 1;
+        //Group Key Cipher Suite
+        sFrame.pRSN->abyRSN[0] = 0x00;
+        sFrame.pRSN->abyRSN[1] = 0x0F;
+        sFrame.pRSN->abyRSN[2] = 0xAC;
+        if (pMgmt->byCSSGK == KEY_CTL_WEP) {
+            sFrame.pRSN->abyRSN[3] = pMgmt->pCurrBSS->byCSSGK;
+        } else if (pMgmt->byCSSGK == KEY_CTL_TKIP) {
+            sFrame.pRSN->abyRSN[3] = WLAN_11i_CSS_TKIP;
+        } else if (pMgmt->byCSSGK == KEY_CTL_CCMP) {
+            sFrame.pRSN->abyRSN[3] = WLAN_11i_CSS_CCMP;
+        } else {
+            sFrame.pRSN->abyRSN[3] = WLAN_11i_CSS_UNKNOWN;
+        }
+
+        // Pairwise Key Cipher Suite
+        sFrame.pRSN->abyRSN[4] = 1;
+        sFrame.pRSN->abyRSN[5] = 0;
+        sFrame.pRSN->abyRSN[6] = 0x00;
+        sFrame.pRSN->abyRSN[7] = 0x0F;
+        sFrame.pRSN->abyRSN[8] = 0xAC;
+        if (pMgmt->byCSSPK == KEY_CTL_TKIP) {
+            sFrame.pRSN->abyRSN[9] = WLAN_11i_CSS_TKIP;
+        } else if (pMgmt->byCSSPK == KEY_CTL_CCMP) {
+            sFrame.pRSN->abyRSN[9] = WLAN_11i_CSS_CCMP;
+        } else if (pMgmt->byCSSPK == KEY_CTL_NONE) {
+            sFrame.pRSN->abyRSN[9] = WLAN_11i_CSS_USE_GROUP;
+        } else {
+            sFrame.pRSN->abyRSN[9] = WLAN_11i_CSS_UNKNOWN;
+        }
+        sFrame.pRSN->len += 6;
+
+        // Auth Key Management Suite
+        sFrame.pRSN->abyRSN[10] = 1;
+        sFrame.pRSN->abyRSN[11] = 0;
+        sFrame.pRSN->abyRSN[12] = 0x00;
+        sFrame.pRSN->abyRSN[13] = 0x0F;
+        sFrame.pRSN->abyRSN[14] = 0xAC;
+        if (pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK) {
+            sFrame.pRSN->abyRSN[15] = WLAN_11i_AKMSS_PSK;
+        } else if (pMgmt->eAuthenMode == WMAC_AUTH_WPA2) {
+            sFrame.pRSN->abyRSN[15] = WLAN_11i_AKMSS_802_1X;
+        } else {
+            sFrame.pRSN->abyRSN[15] = WLAN_11i_AKMSS_UNKNOWN;
+        }
+        sFrame.pRSN->len +=6;
+
+        // RSN Capabilites
+        if (pMgmt->pCurrBSS->sRSNCapObj.bRSNCapExist == TRUE) {
+            MEMvCopy(&sFrame.pRSN->abyRSN[16], &pMgmt->pCurrBSS->sRSNCapObj.wRSNCap, 2);
+        } else {
+            sFrame.pRSN->abyRSN[16] = 0;
+            sFrame.pRSN->abyRSN[17] = 0;
+        }
+        sFrame.pRSN->len +=2;
+
+        if ((pDevice->gsPMKID.BSSIDInfoCount > 0) && (pDevice->bRoaming == TRUE) && (pMgmt->eAuthenMode == WMAC_AUTH_WPA2)) {
+            // RSN PMKID
+            pbyRSN = &sFrame.pRSN->abyRSN[18];
+            pwPMKID = (PWORD)pbyRSN; // Point to PMKID count
+            *pwPMKID = 0;            // Initialize PMKID count
+            pbyRSN += 2;             // Point to PMKID list
+            for (ii = 0; ii < pDevice->gsPMKID.BSSIDInfoCount; ii++) {
+                if (MEMEqualMemory(&pDevice->gsPMKID.BSSIDInfo[ii].BSSID[0], pMgmt->abyCurrBSSID, U_ETHER_ADDR_LEN)) {
+                    (*pwPMKID) ++;
+                    MEMvCopy(pbyRSN, pDevice->gsPMKID.BSSIDInfo[ii].PMKID, 16);
+                    pbyRSN += 16;
+                }
+            }
+            if (*pwPMKID != 0) {
+                sFrame.pRSN->len += (2 + (*pwPMKID)*16);
+            }
+        }
+
+        sFrame.len += sFrame.pRSN->len + WLAN_IEHDR_LEN;
+        // copy to AssocInfo. for OID_802_11_ASSOCIATION_INFORMATION
+        pMgmt->sAssocInfo.AssocInfo.RequestIELength += sFrame.pRSN->len + WLAN_IEHDR_LEN;
+        MEMvCopy(pbyIEs, sFrame.pRSN, sFrame.pRSN->len + WLAN_IEHDR_LEN);
+        pbyIEs += sFrame.pRSN->len + WLAN_IEHDR_LEN;
+    }
+
+
+    /* Adjust the length fields */
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+
+    return pTxPacket;
+}
+
+
+
+/*+
+ *
+ * Routine Description:
+ *  Constructs an assoc-response frame
+ *
+ *
+ * Return Value:
+ *    PTR to frame; or NULL on allocation failue
+ *
+-*/
+
+
+PSTxMgmtPacket
+s_MgrMakeAssocResponse(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN WORD wCurrCapInfo,
+    IN WORD wAssocStatus,
+    IN WORD wAssocAID,
+    IN PBYTE pDstAddr,
+    IN PWLAN_IE_SUPP_RATES pCurrSuppRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+    )
+{
+    PSTxMgmtPacket      pTxPacket = NULL;
+    WLAN_FR_ASSOCRESP   sFrame;
+
+
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_ASSOCREQ_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    // Setup the sFrame structure
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_REASSOCRESP_FR_MAXLEN;
+    vMgrEncodeAssocResponse(&sFrame);
+    // Setup the header
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+        (
+        WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+        WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_ASSOCRESP)
+        ));
+    memcpy( sFrame.pHdr->sA3.abyAddr1, pDstAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+
+    *sFrame.pwCapInfo = cpu_to_le16(wCurrCapInfo);
+    *sFrame.pwStatus = cpu_to_le16(wAssocStatus);
+    *sFrame.pwAid = cpu_to_le16((WORD)(wAssocAID | BIT14 | BIT15));
+
+    // Copy the rate set
+    sFrame.pSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+    sFrame.len += ((PWLAN_IE_SUPP_RATES)pCurrSuppRates)->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSuppRates,
+           pCurrSuppRates,
+           ((PWLAN_IE_SUPP_RATES)pCurrSuppRates)->len + WLAN_IEHDR_LEN
+          );
+
+    if (((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len != 0) {
+        sFrame.pExtSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+        sFrame.len += ((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len + WLAN_IEHDR_LEN;
+        MEMvCopy(sFrame.pExtSuppRates,
+             pCurrExtSuppRates,
+             ((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len + WLAN_IEHDR_LEN
+             );
+    }
+
+    // Adjust the length fields
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+
+    return pTxPacket;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *  Constructs an reassoc-response frame
+ *
+ *
+ * Return Value:
+ *    PTR to frame; or NULL on allocation failue
+ *
+-*/
+
+
+PSTxMgmtPacket
+s_MgrMakeReAssocResponse(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN WORD wCurrCapInfo,
+    IN WORD wAssocStatus,
+    IN WORD wAssocAID,
+    IN PBYTE pDstAddr,
+    IN PWLAN_IE_SUPP_RATES pCurrSuppRates,
+    IN PWLAN_IE_SUPP_RATES pCurrExtSuppRates
+    )
+{
+    PSTxMgmtPacket      pTxPacket = NULL;
+    WLAN_FR_REASSOCRESP   sFrame;
+
+
+    pTxPacket = (PSTxMgmtPacket)pMgmt->pbyMgmtPacketPool;
+    memset(pTxPacket, 0, sizeof(STxMgmtPacket) + WLAN_ASSOCREQ_FR_MAXLEN);
+    pTxPacket->p80211Header = (PUWLAN_80211HDR)((PBYTE)pTxPacket + sizeof(STxMgmtPacket));
+    // Setup the sFrame structure
+    sFrame.pBuf = (PBYTE)pTxPacket->p80211Header;
+    sFrame.len = WLAN_REASSOCRESP_FR_MAXLEN;
+    vMgrEncodeReassocResponse(&sFrame);
+    // Setup the header
+    sFrame.pHdr->sA3.wFrameCtl = cpu_to_le16(
+        (
+        WLAN_SET_FC_FTYPE(WLAN_TYPE_MGR) |
+        WLAN_SET_FC_FSTYPE(WLAN_FSTYPE_REASSOCRESP)
+        ));
+    memcpy( sFrame.pHdr->sA3.abyAddr1, pDstAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr2, pMgmt->abyMACAddr, WLAN_ADDR_LEN);
+    memcpy( sFrame.pHdr->sA3.abyAddr3, pMgmt->abyCurrBSSID, WLAN_BSSID_LEN);
+
+    *sFrame.pwCapInfo = cpu_to_le16(wCurrCapInfo);
+    *sFrame.pwStatus = cpu_to_le16(wAssocStatus);
+    *sFrame.pwAid = cpu_to_le16((WORD)(wAssocAID | BIT14 | BIT15));
+
+    // Copy the rate set
+    sFrame.pSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+    sFrame.len += ((PWLAN_IE_SUPP_RATES)pCurrSuppRates)->len + WLAN_IEHDR_LEN;
+    memcpy(sFrame.pSuppRates,
+             pCurrSuppRates,
+             ((PWLAN_IE_SUPP_RATES)pCurrSuppRates)->len + WLAN_IEHDR_LEN
+             );
+
+    if (((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len != 0) {
+        sFrame.pExtSuppRates = (PWLAN_IE_SUPP_RATES)(sFrame.pBuf + sFrame.len);
+        sFrame.len += ((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len + WLAN_IEHDR_LEN;
+        MEMvCopy(sFrame.pExtSuppRates,
+             pCurrExtSuppRates,
+             ((PWLAN_IE_SUPP_RATES)pCurrExtSuppRates)->len + WLAN_IEHDR_LEN
+             );
+    }
+
+    // Adjust the length fields
+    pTxPacket->cbMPDULen = sFrame.len;
+    pTxPacket->cbPayloadLen = sFrame.len - WLAN_HDR_ADDR3_LEN;
+
+    return pTxPacket;
+}
+
+
+/*+
+ *
+ * Routine Description:
+ *  Handles probe response management frames.
+ *
+ *
+ * Return Value:
+ *    none.
+ *
+-*/
+
+static
+VOID
+s_vMgrRxProbeResponse(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket
+    )
+{
+    PKnownBSS           pBSSList = NULL;
+    WLAN_FR_PROBERESP   sFrame;
+    BYTE                byCurrChannel = pRxPacket->byRxChannel;
+    ERPObject           sERP;
+    BYTE                byIEChannel = 0;
+    BOOL                bChannelHit = TRUE;
+
+
+    memset(&sFrame, 0, sizeof(WLAN_FR_PROBERESP));
+    // decode the frame
+    sFrame.len = pRxPacket->cbMPDULen;
+    sFrame.pBuf = (PBYTE)pRxPacket->p80211Header;
+    vMgrDecodeProbeResponse(&sFrame);
+
+    if ((sFrame.pqwTimestamp == 0) ||
+        (sFrame.pwBeaconInterval == 0) ||
+        (sFrame.pwCapInfo == 0) ||
+        (sFrame.pSSID == 0) ||
+        (sFrame.pSuppRates == 0)) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Probe resp:Fail addr:[%p] \n", pRxPacket->p80211Header);
+        DBG_PORT80(0xCC);
+        return;
+    };
+
+    if(sFrame.pSSID->len == 0)
+       DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Rx Probe resp: SSID len = 0 \n");
+
+    if (sFrame.pDSParms != 0) {
+        if (byCurrChannel > CB_MAX_CHANNEL_24G) {
+            // channel remapping to
+            byIEChannel = CARDbyGetChannelMapping(pMgmt->pAdapter, sFrame.pDSParms->byCurrChannel, PHY_TYPE_11A);
+        } else {
+            byIEChannel = sFrame.pDSParms->byCurrChannel;
+        }
+        if (byCurrChannel != byIEChannel) {
+            // adjust channel info. bcs we rcv adjcent channel pakckets
+            bChannelHit = FALSE;
+            byCurrChannel = byIEChannel;
+        }
+    } else {
+        // no DS channel info
+        bChannelHit = TRUE;
+    }
+
+//2008-0730-01<Add>by MikeLiu
+if(ChannelExceedZoneType(pDevice,byCurrChannel)==TRUE)
+      return;
+
+    if (sFrame.pERP != NULL) {
+        sERP.byERP = sFrame.pERP->byContext;
+        sERP.bERPExist = TRUE;
+    } else {
+        sERP.bERPExist = FALSE;
+        sERP.byERP = 0;
+    }
+
+
+    // update or insert the bss
+    pBSSList = BSSpAddrIsInBSSList((HANDLE)pDevice, sFrame.pHdr->sA3.abyAddr3, sFrame.pSSID);
+    if (pBSSList) {
+        BSSbUpdateToBSSList((HANDLE)pDevice,
+                            *sFrame.pqwTimestamp,
+                            *sFrame.pwBeaconInterval,
+                            *sFrame.pwCapInfo,
+                            byCurrChannel,
+                            bChannelHit,
+                            sFrame.pSSID,
+                            sFrame.pSuppRates,
+                            sFrame.pExtSuppRates,
+                            &sERP,
+                            sFrame.pRSN,
+                            sFrame.pRSNWPA,
+                            sFrame.pIE_Country,
+                            sFrame.pIE_Quiet,
+                            pBSSList,
+                            sFrame.len - WLAN_HDR_ADDR3_LEN,
+                            sFrame.pHdr->sA4.abyAddr4,   // payload of probresponse
+                            (HANDLE)pRxPacket
+                           );
+    }
+    else {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Probe resp/insert: RxChannel = : %d\n", byCurrChannel);
+        BSSbInsertToBSSList((HANDLE)pDevice,
+                            sFrame.pHdr->sA3.abyAddr3,
+                            *sFrame.pqwTimestamp,
+                            *sFrame.pwBeaconInterval,
+                            *sFrame.pwCapInfo,
+                            byCurrChannel,
+                            sFrame.pSSID,
+                            sFrame.pSuppRates,
+                            sFrame.pExtSuppRates,
+                            &sERP,
+                            sFrame.pRSN,
+                            sFrame.pRSNWPA,
+                            sFrame.pIE_Country,
+                            sFrame.pIE_Quiet,
+                            sFrame.len - WLAN_HDR_ADDR3_LEN,
+                            sFrame.pHdr->sA4.abyAddr4,   // payload of beacon
+                            (HANDLE)pRxPacket
+                           );
+    }
+    return;
+
+}
+
+/*+
+ *
+ * Routine Description:(AP)or(Ad-hoc STA)
+ *  Handles probe request management frames.
+ *
+ *
+ * Return Value:
+ *    none.
+ *
+-*/
+
+
+static
+VOID
+s_vMgrRxProbeRequest(
+    IN PSDevice pDevice,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket
+    )
+{
+    WLAN_FR_PROBEREQ    sFrame;
+    CMD_STATUS          Status;
+    PSTxMgmtPacket      pTxPacket;
+    BYTE                byPHYType = BB_TYPE_11B;
+
+    // STA in Ad-hoc mode: when latest TBTT beacon transmit success,
+    // STA have to response this request.
+    if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) ||
+        ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) && pDevice->bBeaconSent)) {
+
+        memset(&sFrame, 0, sizeof(WLAN_FR_PROBEREQ));
+        // decode the frame
+        sFrame.len = pRxPacket->cbMPDULen;
+        sFrame.pBuf = (PBYTE)pRxPacket->p80211Header;
+        vMgrDecodeProbeRequest(&sFrame);
+/*
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Probe request rx:MAC addr:%02x-%02x-%02x=%02x-%02x-%02x \n",
+                  sFrame.pHdr->sA3.abyAddr2[0],
+                  sFrame.pHdr->sA3.abyAddr2[1],
+                  sFrame.pHdr->sA3.abyAddr2[2],
+                  sFrame.pHdr->sA3.abyAddr2[3],
+                  sFrame.pHdr->sA3.abyAddr2[4],
+                  sFrame.pHdr->sA3.abyAddr2[5]
+                );
+*/
+        if (sFrame.pSSID->len != 0) {
+            if (sFrame.pSSID->len != ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->len)
+                return;
+            if (memcmp(sFrame.pSSID->abySSID,
+                       ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->abySSID,
+                       ((PWLAN_IE_SSID)pMgmt->abyCurrSSID)->len) != 0) {
+                       return;
+            }
+        }
+
+        if ((sFrame.pSuppRates->len > 4) || (sFrame.pExtSuppRates != NULL)) {
+            byPHYType = BB_TYPE_11G;
+        }
+
+        // Probe response reply..
+        pTxPacket = s_MgrMakeProbeResponse
+                    (
+                      pDevice,
+                      pMgmt,
+                      pMgmt->wCurrCapInfo,
+                      pMgmt->wCurrBeaconPeriod,
+                      pMgmt->uCurrChannel,
+                      0,
+                      sFrame.pHdr->sA3.abyAddr2,
+                      (PWLAN_IE_SSID)pMgmt->abyCurrSSID,
+                      (PBYTE)pMgmt->abyCurrBSSID,
+                      (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                      (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates,
+                       byPHYType
+                    );
+        if (pTxPacket != NULL ){
+            /* send the frame */
+            Status = csMgmt_xmit(pDevice, pTxPacket);
+            if (Status != CMD_STATUS_PENDING) {
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:Probe response tx failed\n");
+            }
+            else {
+//                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Mgt:Probe response tx sending..\n");
+            }
+        }
+    }
+
+    return;
+}
+
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *
+ *  Entry point for the reception and handling of 802.11 management
+ *  frames. Makes a determination of the frame type and then calls
+ *  the appropriate function.
+ *
+ *
+ * Return Value:
+ *    none.
+ *
+-*/
+
+
+VOID
+vMgrRxManagePacket(
+    IN  HANDLE hDeviceContext,
+    IN PSMgmtObject pMgmt,
+    IN PSRxMgmtPacket pRxPacket
+     )
+{
+    PSDevice    pDevice = (PSDevice)hDeviceContext;
+    BOOL        bInScan = FALSE;
+    UINT        uNodeIndex = 0;
+    NODE_STATE  eNodeState = 0;
+    CMD_STATUS  Status;
+
+
+    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
+        if (BSSDBbIsSTAInNodeDB(pMgmt, pRxPacket->p80211Header->sA3.abyAddr2, &uNodeIndex))
+            eNodeState = pMgmt->sNodeDBTable[uNodeIndex].eNodeState;
+    }
+
+    switch( WLAN_GET_FC_FSTYPE((pRxPacket->p80211Header->sA3.wFrameCtl)) ){
+
+        case WLAN_FSTYPE_ASSOCREQ:
+            // Frame Clase = 2
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx assocreq\n");
+            if (eNodeState < NODE_AUTH) {
+                // send deauth notification
+                // reason = (6) class 2 received from nonauth sta
+                vMgrDeAuthenBeginSta(pDevice,
+                                     pMgmt,
+                                     pRxPacket->p80211Header->sA3.abyAddr2,
+                                     (6),
+                                     &Status
+                                     );
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wmgr: send vMgrDeAuthenBeginSta 1\n");
+            }
+            else {
+                s_vMgrRxAssocRequest(pDevice, pMgmt, pRxPacket, uNodeIndex);
+            }
+            break;
+
+        case WLAN_FSTYPE_ASSOCRESP:
+            // Frame Clase = 2
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx assocresp1\n");
+            s_vMgrRxAssocResponse(pDevice, pMgmt, pRxPacket, FALSE);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx assocresp2\n");
+            break;
+
+        case WLAN_FSTYPE_REASSOCREQ:
+            // Frame Clase = 2
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx reassocreq\n");
+            // Todo: reassoc
+            if (eNodeState < NODE_AUTH) {
+                // send deauth notification
+                // reason = (6) class 2 received from nonauth sta
+                vMgrDeAuthenBeginSta(pDevice,
+                                     pMgmt,
+                                     pRxPacket->p80211Header->sA3.abyAddr2,
+                                     (6),
+                                     &Status
+                                     );
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wmgr: send vMgrDeAuthenBeginSta 2\n");
+
+            }
+            s_vMgrRxReAssocRequest(pDevice, pMgmt, pRxPacket, uNodeIndex);
+            break;
+
+        case WLAN_FSTYPE_REASSOCRESP:
+            // Frame Clase = 2
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx reassocresp\n");
+            s_vMgrRxAssocResponse(pDevice, pMgmt, pRxPacket, TRUE);
+            break;
+
+        case WLAN_FSTYPE_PROBEREQ:
+            // Frame Clase = 0
+            //DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx probereq\n");
+            s_vMgrRxProbeRequest(pDevice, pMgmt, pRxPacket);
+            break;
+
+        case WLAN_FSTYPE_PROBERESP:
+            // Frame Clase = 0
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx proberesp\n");
+
+            s_vMgrRxProbeResponse(pDevice, pMgmt, pRxPacket);
+            break;
+
+        case WLAN_FSTYPE_BEACON:
+            // Frame Clase = 0
+            // DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx beacon\n");
+            if (pMgmt->eScanState != WMAC_NO_SCANNING) {
+                bInScan = TRUE;
+            };
+            s_vMgrRxBeacon(pDevice, pMgmt, pRxPacket, bInScan);
+            break;
+
+        case WLAN_FSTYPE_ATIM:
+            // Frame Clase = 1
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx atim\n");
+            break;
+
+        case WLAN_FSTYPE_DISASSOC:
+            // Frame Clase = 2
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx disassoc\n");
+            if (eNodeState < NODE_AUTH) {
+                // send deauth notification
+                // reason = (6) class 2 received from nonauth sta
+                vMgrDeAuthenBeginSta(pDevice,
+                                     pMgmt,
+                                     pRxPacket->p80211Header->sA3.abyAddr2,
+                                     (6),
+                                     &Status
+                                     );
+                DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wmgr: send vMgrDeAuthenBeginSta 3\n");
+            }
+            s_vMgrRxDisassociation(pDevice, pMgmt, pRxPacket);
+            break;
+
+        case WLAN_FSTYPE_AUTHEN:
+            // Frame Clase = 1
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO  "rx authen\n");
+            s_vMgrRxAuthentication(pDevice, pMgmt, pRxPacket);
+            break;
+
+        case WLAN_FSTYPE_DEAUTHEN:
+            // Frame Clase = 1
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx deauthen\n");
+            s_vMgrRxDeauthentication(pDevice, pMgmt, pRxPacket);
+            break;
+
+        default:
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "rx unknown mgmt\n");
+    }
+
+    return;
+}
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *
+ *
+ *  Prepare beacon to send
+ *
+ * Return Value:
+ *    TRUE if success; FALSE if failed.
+ *
+-*/
+BOOL
+bMgrPrepareBeaconToSend(
+    IN HANDLE hDeviceContext,
+    IN PSMgmtObject pMgmt
+    )
+{
+    PSDevice            pDevice = (PSDevice)hDeviceContext;
+    PSTxMgmtPacket      pTxPacket;
+
+//    pDevice->bBeaconBufReady = FALSE;
+    if (pDevice->bEncryptionEnable || pDevice->bEnable8021x){
+        pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_PRIVACY(1);
+    }
+    else {
+        pMgmt->wCurrCapInfo &= ~WLAN_SET_CAP_INFO_PRIVACY(1);
+    }
+    pTxPacket = s_MgrMakeBeacon
+                (
+                  pDevice,
+                  pMgmt,
+                  pMgmt->wCurrCapInfo,
+                  pMgmt->wCurrBeaconPeriod,
+                  pMgmt->uCurrChannel,
+                  pMgmt->wCurrATIMWindow, //0,
+                  (PWLAN_IE_SSID)pMgmt->abyCurrSSID,
+                  (PBYTE)pMgmt->abyCurrBSSID,
+                  (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrSuppRates,
+                  (PWLAN_IE_SUPP_RATES)pMgmt->abyCurrExtSuppRates
+                );
+
+    if ((pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) &&
+        (pMgmt->abyCurrBSSID[0] == 0))
+        return FALSE;
+
+    csBeacon_xmit(pDevice, pTxPacket);
+
+    return TRUE;
+}
+
+
+
+
+/*+
+ *
+ * Routine Description:
+ *
+ *  Log a warning message based on the contents of the Status
+ *  Code field of an 802.11 management frame.  Defines are
+ *  derived from 802.11-1997 SPEC.
+ *
+ * Return Value:
+ *    none.
+ *
+-*/
+static
+VOID
+s_vMgrLogStatus(
+    IN PSMgmtObject pMgmt,
+    IN WORD  wStatus
+    )
+{
+    switch( wStatus ){
+        case WLAN_MGMT_STATUS_UNSPEC_FAILURE:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Unspecified error.\n");
+            break;
+        case WLAN_MGMT_STATUS_CAPS_UNSUPPORTED:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Can't support all requested capabilities.\n");
+            break;
+        case WLAN_MGMT_STATUS_REASSOC_NO_ASSOC:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Reassoc denied, can't confirm original Association.\n");
+            break;
+        case WLAN_MGMT_STATUS_ASSOC_DENIED_UNSPEC:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Assoc denied, undefine in spec\n");
+            break;
+        case WLAN_MGMT_STATUS_UNSUPPORTED_AUTHALG:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Peer doesn't support authen algorithm.\n");
+            break;
+        case WLAN_MGMT_STATUS_RX_AUTH_NOSEQ:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Authen frame received out of sequence.\n");
+            break;
+        case WLAN_MGMT_STATUS_CHALLENGE_FAIL:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Authen rejected, challenge  failure.\n");
+            break;
+        case WLAN_MGMT_STATUS_AUTH_TIMEOUT:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Authen rejected, timeout waiting for next frame.\n");
+            break;
+        case WLAN_MGMT_STATUS_ASSOC_DENIED_BUSY:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Assoc denied, AP too busy.\n");
+            break;
+        case WLAN_MGMT_STATUS_ASSOC_DENIED_RATES:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Assoc denied, we haven't enough basic rates.\n");
+            break;
+        case WLAN_MGMT_STATUS_ASSOC_DENIED_SHORTPREAMBLE:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Assoc denied, we do not support short preamble.\n");
+            break;
+        case WLAN_MGMT_STATUS_ASSOC_DENIED_PBCC:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Assoc denied, we do not support PBCC.\n");
+            break;
+        case WLAN_MGMT_STATUS_ASSOC_DENIED_AGILITY:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Status code == Assoc denied, we do not support channel agility.\n");
+            break;
+        default:
+            DEVICE_PRT(MSG_LEVEL_NOTICE, KERN_INFO "Unknown status code %d.\n", wStatus);
+            break;
+    }
+}
+
+
+/*
+ *
+ * Description:
+ *    Add BSSID in PMKID Candidate list.
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *      pbyBSSID - BSSID address for adding
+ *      wRSNCap - BSS's RSN capability
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+BOOL
+bAdd_PMKID_Candidate (
+    IN HANDLE    hDeviceContext,
+    IN PBYTE          pbyBSSID,
+    IN PSRSNCapObject psRSNCapObj
+    )
+{
+    PSDevice         pDevice = (PSDevice)hDeviceContext;
+    PPMKID_CANDIDATE pCandidateList;
+    UINT             ii = 0;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"bAdd_PMKID_Candidate START: (%d)\n", (int)pDevice->gsPMKIDCandidate.NumCandidates);
+
+    if ((pDevice == NULL) || (pbyBSSID == NULL) || (psRSNCapObj == NULL))
+        return FALSE;
+
+    if (pDevice->gsPMKIDCandidate.NumCandidates >= MAX_PMKIDLIST)
+        return FALSE;
+
+
+
+    // Update Old Candidate
+    for (ii = 0; ii < pDevice->gsPMKIDCandidate.NumCandidates; ii++) {
+        pCandidateList = &pDevice->gsPMKIDCandidate.CandidateList[ii];
+        if (MEMEqualMemory(pCandidateList->BSSID, pbyBSSID, U_ETHER_ADDR_LEN)) {
+            if ((psRSNCapObj->bRSNCapExist == TRUE) && (psRSNCapObj->wRSNCap & BIT0)) {
+                pCandidateList->Flags |= NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED;
+            } else {
+                pCandidateList->Flags &= ~(NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED);
+            }
+            return TRUE;
+        }
+    }
+
+    // New Candidate
+    pCandidateList = &pDevice->gsPMKIDCandidate.CandidateList[pDevice->gsPMKIDCandidate.NumCandidates];
+    if ((psRSNCapObj->bRSNCapExist == TRUE) && (psRSNCapObj->wRSNCap & BIT0)) {
+        pCandidateList->Flags |= NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED;
+    } else {
+        pCandidateList->Flags &= ~(NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED);
+    }
+    MEMvCopy(pCandidateList->BSSID, pbyBSSID, U_ETHER_ADDR_LEN);
+    pDevice->gsPMKIDCandidate.NumCandidates++;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"NumCandidates:%d\n", (int)pDevice->gsPMKIDCandidate.NumCandidates);
+    return TRUE;
+}
+
+/*
+ *
+ * Description:
+ *    Flush PMKID Candidate list.
+ *
+ * Parameters:
+ *  In:
+ *      hDeviceContext - device structure point
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+VOID
+vFlush_PMKID_Candidate (
+    IN HANDLE hDeviceContext
+    )
+{
+    PSDevice        pDevice = (PSDevice)hDeviceContext;
+
+    if (pDevice == NULL)
+        return;
+
+    ZERO_MEMORY(&pDevice->gsPMKIDCandidate, sizeof(SPMKIDCandidateEvent));
+}
+
+static BOOL
+s_bCipherMatch (
+    IN PKnownBSS                        pBSSNode,
+    IN NDIS_802_11_ENCRYPTION_STATUS    EncStatus,
+    OUT PBYTE                           pbyCCSPK,
+    OUT PBYTE                           pbyCCSGK
+    )
+{
+    BYTE byMulticastCipher = KEY_CTL_INVALID;
+    BYTE byCipherMask = 0x00;
+    int i;
+
+    if (pBSSNode == NULL)
+        return FALSE;
+
+    // check cap. of BSS
+
+    if ((WLAN_GET_CAP_INFO_PRIVACY(pBSSNode->wCapInfo) != 0) &&
+         (EncStatus == Ndis802_11Encryption1Enabled)) {
+        // default is WEP only
+        byMulticastCipher = KEY_CTL_WEP;
+    }
+
+    if ((WLAN_GET_CAP_INFO_PRIVACY(pBSSNode->wCapInfo) != 0) &&
+        (pBSSNode->bWPA2Valid == TRUE) &&
+        ((EncStatus == Ndis802_11Encryption3Enabled)||(EncStatus == Ndis802_11Encryption2Enabled))) {
+
+        //WPA2
+        // check Group Key Cipher
+        if ((pBSSNode->byCSSGK == WLAN_11i_CSS_WEP40) ||
+            (pBSSNode->byCSSGK == WLAN_11i_CSS_WEP104)) {
+            byMulticastCipher = KEY_CTL_WEP;
+        } else if (pBSSNode->byCSSGK == WLAN_11i_CSS_TKIP) {
+            byMulticastCipher = KEY_CTL_TKIP;
+        } else if (pBSSNode->byCSSGK == WLAN_11i_CSS_CCMP) {
+            byMulticastCipher = KEY_CTL_CCMP;
+        } else {
+            byMulticastCipher = KEY_CTL_INVALID;
+        }
+
+        // check Pairwise Key Cipher
+        for(i=0;i<pBSSNode->wCSSPKCount;i++) {
+            if ((pBSSNode->abyCSSPK[i] == WLAN_11i_CSS_WEP40) ||
+                (pBSSNode->abyCSSPK[i] == WLAN_11i_CSS_WEP104)) {
+                // this should not happen as defined 802.11i
+                byCipherMask |= 0x01;
+            } else if (pBSSNode->abyCSSPK[i] == WLAN_11i_CSS_TKIP) {
+                byCipherMask |= 0x02;
+            } else if (pBSSNode->abyCSSPK[i] == WLAN_11i_CSS_CCMP) {
+                byCipherMask |= 0x04;
+            } else if (pBSSNode->abyCSSPK[i] == WLAN_11i_CSS_USE_GROUP) {
+                // use group key only ignore all others
+                byCipherMask = 0;
+                i = pBSSNode->wCSSPKCount;
+            }
+        }
+    } else if ((WLAN_GET_CAP_INFO_PRIVACY(pBSSNode->wCapInfo) != 0) &&
+                (pBSSNode->bWPAValid == TRUE) &&
+                ((EncStatus == Ndis802_11Encryption3Enabled)||(EncStatus == Ndis802_11Encryption2Enabled))) {
+
+        //WPA
+        // check Group Key Cipher
+        if ((pBSSNode->byGKType == WPA_WEP40) ||
+            (pBSSNode->byGKType == WPA_WEP104)) {
+            byMulticastCipher = KEY_CTL_WEP;
+        } else if (pBSSNode->byGKType == WPA_TKIP) {
+            byMulticastCipher = KEY_CTL_TKIP;
+        } else if (pBSSNode->byGKType == WPA_AESCCMP) {
+            byMulticastCipher = KEY_CTL_CCMP;
+        } else {
+            byMulticastCipher = KEY_CTL_INVALID;
+        }
+
+        // check Pairwise Key Cipher
+        for(i=0;i<pBSSNode->wPKCount;i++) {
+            if (pBSSNode->abyPKType[i] == WPA_TKIP) {
+                byCipherMask |= 0x02;
+            } else if (pBSSNode->abyPKType[i] == WPA_AESCCMP) {
+                byCipherMask |= 0x04;
+            } else if (pBSSNode->abyPKType[i] == WPA_NONE) {
+                // use group key only ignore all others
+                byCipherMask = 0;
+                i = pBSSNode->wPKCount;
+            }
+        }
+    }
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"%d, %d, %d, %d, EncStatus:%d\n",
+        byMulticastCipher, byCipherMask, pBSSNode->bWPAValid, pBSSNode->bWPA2Valid, EncStatus);
+
+    // mask our cap. with BSS
+    if (EncStatus == Ndis802_11Encryption1Enabled) {
+        // For supporting Cisco migration mode, don't care pairwise key cipher
+        if ((byMulticastCipher == KEY_CTL_WEP) &&
+            (byCipherMask == 0)) {
+            *pbyCCSGK = KEY_CTL_WEP;
+            *pbyCCSPK = KEY_CTL_NONE;
+            return TRUE;
+        } else {
+            return FALSE;
+        }
+
+    } else if (EncStatus == Ndis802_11Encryption2Enabled) {
+        if ((byMulticastCipher == KEY_CTL_TKIP) &&
+            (byCipherMask == 0)) {
+            *pbyCCSGK = KEY_CTL_TKIP;
+            *pbyCCSPK = KEY_CTL_NONE;
+            return TRUE;
+        } else if ((byMulticastCipher == KEY_CTL_WEP) &&
+                   ((byCipherMask & 0x02) != 0)) {
+            *pbyCCSGK = KEY_CTL_WEP;
+            *pbyCCSPK = KEY_CTL_TKIP;
+            return TRUE;
+        } else if ((byMulticastCipher == KEY_CTL_TKIP) &&
+                   ((byCipherMask & 0x02) != 0)) {
+            *pbyCCSGK = KEY_CTL_TKIP;
+            *pbyCCSPK = KEY_CTL_TKIP;
+            return TRUE;
+        } else {
+            return FALSE;
+        }
+    } else if (EncStatus == Ndis802_11Encryption3Enabled) {
+        if ((byMulticastCipher == KEY_CTL_CCMP) &&
+            (byCipherMask == 0)) {
+            // When CCMP is enable, "Use group cipher suite" shall not be a valid option.
+            return FALSE;
+        } else if ((byMulticastCipher == KEY_CTL_WEP) &&
+                   ((byCipherMask & 0x04) != 0)) {
+            *pbyCCSGK = KEY_CTL_WEP;
+            *pbyCCSPK = KEY_CTL_CCMP;
+            return TRUE;
+        } else if ((byMulticastCipher == KEY_CTL_TKIP) &&
+                   ((byCipherMask & 0x04) != 0)) {
+            *pbyCCSGK = KEY_CTL_TKIP;
+            *pbyCCSPK = KEY_CTL_CCMP;
+            return TRUE;
+        } else if ((byMulticastCipher == KEY_CTL_CCMP) &&
+                   ((byCipherMask & 0x04) != 0)) {
+            *pbyCCSGK = KEY_CTL_CCMP;
+            *pbyCCSPK = KEY_CTL_CCMP;
+            return TRUE;
+        } else {
+            return FALSE;
+        }
+    }
+    return TRUE;
+}
+
+
diff --git a/drivers/staging/vt6655/wmgr.h b/drivers/staging/vt6655/wmgr.h
new file mode 100644
index 0000000..5b526ab
--- /dev/null
+++ b/drivers/staging/vt6655/wmgr.h
@@ -0,0 +1,521 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: wmgr.h
+ *
+ * Purpose:
+ *
+ * Author: lyndon chen
+ *
+ * Date: Jan 2, 2003
+ *
+ * Functions:
+ *
+ * Revision History:
+ *
+ */
+
+
+#ifndef __WMGR_H__
+#define __WMGR_H__
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__80211MGR_H__)
+#include "80211mgr.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+#if !defined(__WCMD_H__)
+#include "wcmd.h"
+#endif
+#if !defined(__BSSDB_H__)
+#include "bssdb.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__WPA2_H__)
+#include "wpa2.h"
+#endif
+#if !defined(__VNTWIFI_H__)
+#include "vntwifi.h"
+#endif
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+
+
+// Scan time
+#define PROBE_DELAY                  100  // (us)
+#define SWITCH_CHANNEL_DELAY         200 // (us)
+#define WLAN_SCAN_MINITIME           25   // (ms)
+#define WLAN_SCAN_MAXTIME            100  // (ms)
+#define TRIVIAL_SYNC_DIFFERENCE      0    // (us)
+#define DEFAULT_IBSS_BI              100  // (ms)
+
+#define WCMD_ACTIVE_SCAN_TIME   50 //(ms)
+#define WCMD_PASSIVE_SCAN_TIME  100 //(ms)
+
+
+#define DEFAULT_MSDU_LIFETIME           512  // ms
+#define DEFAULT_MSDU_LIFETIME_RES_64us  8000 // 64us
+
+#define DEFAULT_MGN_LIFETIME            8    // ms
+#define DEFAULT_MGN_LIFETIME_RES_64us   125  // 64us
+
+#define MAKE_BEACON_RESERVED            10  //(us)
+
+
+#define TIM_MULTICAST_MASK           0x01
+#define TIM_BITMAPOFFSET_MASK        0xFE
+#define DEFAULT_DTIM_PERIOD             1
+
+#define AP_LONG_RETRY_LIMIT             4
+
+#define DEFAULT_IBSS_CHANNEL            6  //2.4G
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Types  ------------------------------*/
+#define timer_expire(timer,next_tick)   mod_timer(&timer, RUN_AT(next_tick))
+typedef void (*TimerFunction)(ULONG);
+
+
+//+++ NDIS related
+
+typedef UCHAR   NDIS_802_11_MAC_ADDRESS[6];
+typedef struct _NDIS_802_11_AI_REQFI
+{
+    USHORT Capabilities;
+    USHORT ListenInterval;
+    NDIS_802_11_MAC_ADDRESS  CurrentAPAddress;
+} NDIS_802_11_AI_REQFI, *PNDIS_802_11_AI_REQFI;
+
+typedef struct _NDIS_802_11_AI_RESFI
+{
+    USHORT Capabilities;
+    USHORT StatusCode;
+    USHORT AssociationId;
+} NDIS_802_11_AI_RESFI, *PNDIS_802_11_AI_RESFI;
+
+typedef struct _NDIS_802_11_ASSOCIATION_INFORMATION
+{
+    ULONG                   Length;
+    USHORT                  AvailableRequestFixedIEs;
+    NDIS_802_11_AI_REQFI    RequestFixedIEs;
+    ULONG                   RequestIELength;
+    ULONG                   OffsetRequestIEs;
+    USHORT                  AvailableResponseFixedIEs;
+    NDIS_802_11_AI_RESFI    ResponseFixedIEs;
+    ULONG                   ResponseIELength;
+    ULONG                   OffsetResponseIEs;
+} NDIS_802_11_ASSOCIATION_INFORMATION, *PNDIS_802_11_ASSOCIATION_INFORMATION;
+
+
+
+typedef struct tagSAssocInfo {
+    NDIS_802_11_ASSOCIATION_INFORMATION     AssocInfo;
+    BYTE                                    abyIEs[WLAN_BEACON_FR_MAXLEN+WLAN_BEACON_FR_MAXLEN];
+    // store ReqIEs set by OID_802_11_ASSOCIATION_INFORMATION
+    ULONG                                   RequestIELength;
+    BYTE                                    abyReqIEs[WLAN_BEACON_FR_MAXLEN];
+} SAssocInfo, DEF* PSAssocInfo;
+//---
+
+
+/*
+typedef enum tagWMAC_AUTHENTICATION_MODE {
+
+
+    WMAC_AUTH_OPEN,
+    WMAC_AUTH_SHAREKEY,
+    WMAC_AUTH_AUTO,
+    WMAC_AUTH_WPA,
+    WMAC_AUTH_WPAPSK,
+    WMAC_AUTH_WPANONE,
+    WMAC_AUTH_WPA2,
+    WMAC_AUTH_WPA2PSK,
+    WMAC_AUTH_MAX       // Not a real mode, defined as upper bound
+
+
+} WMAC_AUTHENTICATION_MODE, *PWMAC_AUTHENTICATION_MODE;
+*/
+
+
+// Pre-configured Mode (from XP)
+/*
+typedef enum tagWMAC_CONFIG_MODE {
+    WMAC_CONFIG_ESS_STA,
+    WMAC_CONFIG_IBSS_STA,
+    WMAC_CONFIG_AUTO,
+    WMAC_CONFIG_AP
+
+} WMAC_CONFIG_MODE, *PWMAC_CONFIG_MODE;
+*/
+
+typedef enum tagWMAC_SCAN_TYPE {
+
+    WMAC_SCAN_ACTIVE,
+    WMAC_SCAN_PASSIVE,
+    WMAC_SCAN_HYBRID
+
+} WMAC_SCAN_TYPE, *PWMAC_SCAN_TYPE;
+
+
+typedef enum tagWMAC_SCAN_STATE {
+
+    WMAC_NO_SCANNING,
+    WMAC_IS_SCANNING,
+    WMAC_IS_PROBEPENDING
+
+} WMAC_SCAN_STATE, *PWMAC_SCAN_STATE;
+
+
+
+// Notes:
+// Basic Service Set state explained as following:
+// WMAC_STATE_IDLE          : no BSS is selected (Adhoc or Infra)
+// WMAC_STATE_STARTED       : no BSS is selected, start own IBSS (Adhoc only)
+// WMAC_STATE_JOINTED       : BSS is selected and synchronized (Adhoc or Infra)
+// WMAC_STATE_AUTHPENDING   : Authentication pending (Infra)
+// WMAC_STATE_AUTH          : Authenticated (Infra)
+// WMAC_STATE_ASSOCPENDING  : Association pending (Infra)
+// WMAC_STATE_ASSOC         : Associated (Infra)
+
+typedef enum tagWMAC_BSS_STATE {
+
+    WMAC_STATE_IDLE,
+    WMAC_STATE_STARTED,
+    WMAC_STATE_JOINTED,
+    WMAC_STATE_AUTHPENDING,
+    WMAC_STATE_AUTH,
+    WMAC_STATE_ASSOCPENDING,
+    WMAC_STATE_ASSOC
+
+} WMAC_BSS_STATE, *PWMAC_BSS_STATE;
+
+// WMAC selected running mode
+typedef enum tagWMAC_CURRENT_MODE {
+
+    WMAC_MODE_STANDBY,
+    WMAC_MODE_ESS_STA,
+    WMAC_MODE_IBSS_STA,
+    WMAC_MODE_ESS_AP
+
+} WMAC_CURRENT_MODE, *PWMAC_CURRENT_MODE;
+
+/*
+typedef enum tagWMAC_POWER_MODE {
+
+    WMAC_POWER_CAM,
+    WMAC_POWER_FAST,
+    WMAC_POWER_MAX
+
+} WMAC_POWER_MODE, *PWMAC_POWER_MODE;
+*/
+
+
+// Tx Managment Packet descriptor
+typedef struct tagSTxMgmtPacket {
+
+    PUWLAN_80211HDR     p80211Header;
+    UINT                cbMPDULen;
+    UINT                cbPayloadLen;
+
+} STxMgmtPacket, DEF* PSTxMgmtPacket;
+
+
+// Rx Managment Packet descriptor
+typedef struct tagSRxMgmtPacket {
+
+    PUWLAN_80211HDR     p80211Header;
+    QWORD               qwLocalTSF;
+    UINT                cbMPDULen;
+    UINT                cbPayloadLen;
+    UINT                uRSSI;
+    BYTE                bySQ;
+    BYTE                byRxRate;
+    BYTE                byRxChannel;
+
+} SRxMgmtPacket, DEF* PSRxMgmtPacket;
+
+
+
+typedef struct tagSMgmtObject
+{
+
+    PVOID                   pAdapter;
+    // MAC address
+    BYTE                    abyMACAddr[WLAN_ADDR_LEN];
+
+    // Configuration Mode
+    WMAC_CONFIG_MODE        eConfigMode; // MAC pre-configed mode
+    CARD_PHY_TYPE           eCurrentPHYMode;
+    CARD_PHY_TYPE           eConfigPHYMode;
+
+
+    // Operation state variables
+    WMAC_CURRENT_MODE       eCurrMode;   // MAC current connection mode
+    WMAC_BSS_STATE          eCurrState;  // MAC current BSS state
+
+    PKnownBSS               pCurrBSS;
+    BYTE                    byCSSGK;
+    BYTE                    byCSSPK;
+
+//    BYTE                    abyNewSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN];
+//    BYTE                    abyNewExtSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN];
+
+    // Current state vars
+    UINT                    uCurrChannel;
+    BYTE                    abyCurrSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1];
+    BYTE                    abyCurrExtSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1];
+    BYTE                    abyCurrSSID[WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1];
+    BYTE                    abyCurrBSSID[WLAN_BSSID_LEN];
+    WORD                    wCurrCapInfo;
+    WORD                    wCurrAID;
+    WORD                    wCurrATIMWindow;
+    WORD                    wCurrBeaconPeriod;
+    BOOL                    bIsDS;
+    BYTE                    byERPContext;
+
+    CMD_STATE               eCommandState;
+    UINT                    uScanChannel;
+
+    // Desire joinning BSS vars
+    BYTE                    abyDesireSSID[WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1];
+    BYTE                    abyDesireBSSID[WLAN_BSSID_LEN];
+
+    // Adhoc or AP configuration vars
+  //BYTE                    abyAdHocSSID[WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1];
+    WORD                    wIBSSBeaconPeriod;
+    WORD                    wIBSSATIMWindow;
+    UINT                    uIBSSChannel;
+    BYTE                    abyIBSSSuppRates[WLAN_IEHDR_LEN + WLAN_RATES_MAXLEN + 1];
+    BYTE                    byAPBBType;
+    BYTE                    abyWPAIE[MAX_WPA_IE_LEN];
+    WORD                    wWPAIELen;
+
+    UINT                    uAssocCount;
+    BOOL                    bMoreData;
+
+    // Scan state vars
+    WMAC_SCAN_STATE         eScanState;
+    WMAC_SCAN_TYPE          eScanType;
+    UINT                    uScanStartCh;
+    UINT                    uScanEndCh;
+    WORD                    wScanSteps;
+    UINT                    uScanBSSType;
+    // Desire scannig vars
+    BYTE                    abyScanSSID[WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1];
+    BYTE                    abyScanBSSID[WLAN_BSSID_LEN];
+
+    // Privacy
+    WMAC_AUTHENTICATION_MODE eAuthenMode;
+    WMAC_ENCRYPTION_MODE    eEncryptionMode;
+    BOOL                    bShareKeyAlgorithm;
+    BYTE                    abyChallenge[WLAN_CHALLENGE_LEN];
+    BOOL                    bPrivacyInvoked;
+
+    // Received beacon state vars
+    BOOL                    bInTIM;
+    BOOL                    bMulticastTIM;
+    BYTE                    byDTIMCount;
+    BYTE                    byDTIMPeriod;
+
+    // Power saving state vars
+    WMAC_POWER_MODE         ePSMode;
+    WORD                    wListenInterval;
+    WORD                    wCountToWakeUp;
+    BOOL                    bInTIMWake;
+    PBYTE                   pbyPSPacketPool;
+    BYTE                    byPSPacketPool[sizeof(STxMgmtPacket) + WLAN_NULLDATA_FR_MAXLEN];
+    BOOL                    bRxBeaconInTBTTWake;
+    BYTE                    abyPSTxMap[MAX_NODE_NUM + 1];
+
+    // managment command related
+    UINT                    uCmdBusy;
+    UINT                    uCmdHostAPBusy;
+
+    // managment packet pool
+    PBYTE                   pbyMgmtPacketPool;
+    BYTE                    byMgmtPacketPool[sizeof(STxMgmtPacket) + WLAN_A3FR_MAXLEN];
+
+
+    // One second callback timer
+    struct timer_list	    sTimerSecondCallback;
+
+    // Temporarily Rx Mgmt Packet Descriptor
+    SRxMgmtPacket           sRxPacket;
+
+    // link list of known bss's (scan results)
+    KnownBSS                sBSSList[MAX_BSS_NUM];
+
+
+
+    // table list of known node
+    // sNodeDBList[0] is reserved for AP under Infra mode
+    // sNodeDBList[0] is reserved for Multicast under adhoc/AP mode
+    KnownNodeDB             sNodeDBTable[MAX_NODE_NUM + 1];
+
+
+
+    // WPA2 PMKID Cache
+    SPMKIDCache             gsPMKIDCache;
+    BOOL                    bRoaming;
+
+    // rate fall back vars
+
+
+
+    // associate info
+    SAssocInfo              sAssocInfo;
+
+
+    // for 802.11h
+    BOOL                    b11hEnable;
+    BOOL                    bSwitchChannel;
+    BYTE                    byNewChannel;
+    PWLAN_IE_MEASURE_REP    pCurrMeasureEIDRep;
+    UINT                    uLengthOfRepEIDs;
+    BYTE                    abyCurrentMSRReq[sizeof(STxMgmtPacket) + WLAN_A3FR_MAXLEN];
+    BYTE                    abyCurrentMSRRep[sizeof(STxMgmtPacket) + WLAN_A3FR_MAXLEN];
+    BYTE                    abyIECountry[WLAN_A3FR_MAXLEN];
+    BYTE                    abyIBSSDFSOwner[6];
+    BYTE                    byIBSSDFSRecovery;
+
+    struct sk_buff  skb;
+
+} SMgmtObject, DEF *PSMgmtObject;
+
+
+/*---------------------  Export Macros ------------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+void
+vMgrObjectInit(
+    IN  HANDLE hDeviceContext
+    );
+
+void
+vMgrTimerInit(
+    IN  HANDLE hDeviceContext
+    );
+
+VOID
+vMgrObjectReset(
+    IN  HANDLE hDeviceContext
+    );
+
+void
+vMgrAssocBeginSta(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject pMgmt,
+    OUT PCMD_STATUS pStatus
+    );
+
+VOID
+vMgrReAssocBeginSta(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject pMgmt,
+    OUT PCMD_STATUS pStatus
+    );
+
+VOID
+vMgrDisassocBeginSta(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject pMgmt,
+    IN  PBYTE  abyDestAddress,
+    IN  WORD    wReason,
+    OUT PCMD_STATUS pStatus
+    );
+
+VOID
+vMgrAuthenBeginSta(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject pMgmt,
+    OUT PCMD_STATUS pStatus
+    );
+
+VOID
+vMgrCreateOwnIBSS(
+    IN  HANDLE hDeviceContext,
+    OUT PCMD_STATUS pStatus
+    );
+
+VOID
+vMgrJoinBSSBegin(
+    IN  HANDLE hDeviceContext,
+    OUT PCMD_STATUS pStatus
+    );
+
+VOID
+vMgrRxManagePacket(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject pMgmt,
+    IN  PSRxMgmtPacket pRxPacket
+    );
+
+/*
+VOID
+vMgrScanBegin(
+    IN  HANDLE hDeviceContext,
+    OUT PCMD_STATUS pStatus
+    );
+*/
+
+VOID
+vMgrDeAuthenBeginSta(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject  pMgmt,
+    IN  PBYTE   abyDestAddress,
+    IN  WORD    wReason,
+    OUT PCMD_STATUS pStatus
+    );
+
+BOOL
+bMgrPrepareBeaconToSend(
+    IN  HANDLE hDeviceContext,
+    IN  PSMgmtObject pMgmt
+    );
+
+
+BOOL
+bAdd_PMKID_Candidate (
+    IN HANDLE    hDeviceContext,
+    IN PBYTE          pbyBSSID,
+    IN PSRSNCapObject psRSNCapObj
+    );
+
+VOID
+vFlush_PMKID_Candidate (
+    IN HANDLE hDeviceContext
+    );
+
+#endif // __WMGR_H__
diff --git a/drivers/staging/vt6655/wpa.c b/drivers/staging/vt6655/wpa.c
new file mode 100644
index 0000000..8b4e7fc
--- /dev/null
+++ b/drivers/staging/vt6655/wpa.c
@@ -0,0 +1,339 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: wpa.c
+ *
+ * Purpose: Handles the Basic Service Set & Node Database functions
+ *
+ * Functions:
+ *      WPA_ParseRSN - Parse RSN IE.
+ *
+ * Revision History:
+ *
+ * Author: Kyle Hsu
+ *
+ * Date: July 14, 2003
+ *
+ */
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__TMACRO_H__)
+#include "tmacro.h"
+#endif
+#if !defined(__TETHER_H__)
+#include "tether.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+#if !defined(__BSSDB_H__)
+#include "bssdb.h"
+#endif
+#if !defined(__WMGR_H__)
+#include "wmgr.h"
+#endif
+#if !defined(__WPA_H__)
+#include "wpa.h"
+#endif
+#if !defined(__80211MGR_H__)
+#include "80211mgr.h"
+#endif
+
+
+/*---------------------  Static Variables  --------------------------*/
+static int          msglevel                =MSG_LEVEL_INFO;
+
+const BYTE abyOUI00[4] = { 0x00, 0x50, 0xf2, 0x00 };
+const BYTE abyOUI01[4] = { 0x00, 0x50, 0xf2, 0x01 };
+const BYTE abyOUI02[4] = { 0x00, 0x50, 0xf2, 0x02 };
+const BYTE abyOUI03[4] = { 0x00, 0x50, 0xf2, 0x03 };
+const BYTE abyOUI04[4] = { 0x00, 0x50, 0xf2, 0x04 };
+const BYTE abyOUI05[4] = { 0x00, 0x50, 0xf2, 0x05 };
+
+
+/*+
+ *
+ * Description:
+ *    Clear RSN information in BSSList.
+ *
+ * Parameters:
+ *  In:
+ *      pBSSList - BSS list.
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+
+VOID
+WPA_ClearRSN (
+    IN PKnownBSS        pBSSList
+    )
+{
+    int ii;
+    pBSSList->byGKType = WPA_TKIP;
+    for (ii=0; ii < 4; ii ++)
+        pBSSList->abyPKType[ii] = WPA_TKIP;
+    pBSSList->wPKCount = 0;
+    for (ii=0; ii < 4; ii ++)
+        pBSSList->abyAuthType[ii] = WPA_AUTH_IEEE802_1X;
+    pBSSList->wAuthCount = 0;
+    pBSSList->byDefaultK_as_PK = 0;
+    pBSSList->byReplayIdx = 0;
+    pBSSList->sRSNCapObj.bRSNCapExist = FALSE;
+    pBSSList->sRSNCapObj.wRSNCap = 0;
+    pBSSList->bWPAValid = FALSE;
+}
+
+
+/*+
+ *
+ * Description:
+ *    Parse RSN IE.
+ *
+ * Parameters:
+ *  In:
+ *      pBSSList - BSS list.
+ *      pRSN - Pointer to the RSN IE.
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+VOID
+WPA_ParseRSN (
+    IN PKnownBSS        pBSSList,
+    IN PWLAN_IE_RSN_EXT pRSN
+    )
+{
+    PWLAN_IE_RSN_AUTH  pIE_RSN_Auth = NULL;
+    int                i, j, m, n = 0;
+    PBYTE              pbyCaps;
+
+    WPA_ClearRSN(pBSSList);
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"WPA_ParseRSN: [%d]\n", pRSN->len);
+
+    // information element header makes sense
+    if ((pRSN->len >= 6) // oui1(4)+ver(2)
+         && (pRSN->byElementID == WLAN_EID_RSN_WPA) && MEMEqualMemory(pRSN->abyOUI, abyOUI01, 4)
+         && (pRSN->wVersion == 1)) {
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Legal RSN\n");
+        // update each variable if pRSN is long enough to contain the variable
+        if (pRSN->len >= 10) //oui1(4)+ver(2)+GKSuite(4)
+        {
+            if (MEMEqualMemory(pRSN->abyMulticast, abyOUI01, 4))
+                pBSSList->byGKType = WPA_WEP40;
+            else if (MEMEqualMemory(pRSN->abyMulticast, abyOUI02, 4))
+                pBSSList->byGKType = WPA_TKIP;
+            else if (MEMEqualMemory(pRSN->abyMulticast, abyOUI03, 4))
+                pBSSList->byGKType = WPA_AESWRAP;
+            else if (MEMEqualMemory(pRSN->abyMulticast, abyOUI04, 4))
+                pBSSList->byGKType = WPA_AESCCMP;
+            else if (MEMEqualMemory(pRSN->abyMulticast, abyOUI05, 4))
+                pBSSList->byGKType = WPA_WEP104;
+            else
+                // any vendor checks here
+                pBSSList->byGKType = WPA_NONE;
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"byGKType: %x\n", pBSSList->byGKType);
+        }
+
+        if (pRSN->len >= 12) //oui1(4)+ver(2)+GKS(4)+PKSCnt(2)
+        {
+            j = 0;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wPKCount: %d, sizeof(pBSSList->abyPKType): %d\n", pRSN->wPKCount, sizeof(pBSSList->abyPKType));
+            for(i = 0; (i < pRSN->wPKCount) && (j < sizeof(pBSSList->abyPKType)/sizeof(BYTE)); i++) {
+                if(pRSN->len >= 12+i*4+4) { //oui1(4)+ver(2)+GKS(4)+PKSCnt(2)+PKS(4*i)
+                    if (MEMEqualMemory(pRSN->PKSList[i].abyOUI, abyOUI00, 4))
+                        pBSSList->abyPKType[j++] = WPA_NONE;
+                    else if (MEMEqualMemory(pRSN->PKSList[i].abyOUI, abyOUI02, 4))
+                        pBSSList->abyPKType[j++] = WPA_TKIP;
+                    else if (MEMEqualMemory(pRSN->PKSList[i].abyOUI, abyOUI03, 4))
+                        pBSSList->abyPKType[j++] = WPA_AESWRAP;
+                    else if (MEMEqualMemory(pRSN->PKSList[i].abyOUI, abyOUI04, 4))
+                        pBSSList->abyPKType[j++] = WPA_AESCCMP;
+                    else
+                        // any vendor checks here
+                        ;
+                }
+                else
+                    break;
+                //DBG_PRN_GRP14(("abyPKType[%d]: %X\n", j-1, pBSSList->abyPKType[j-1]));
+            } //for
+            pBSSList->wPKCount = (WORD)j;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wPKCount: %d\n", pBSSList->wPKCount);
+        }
+
+        m = pRSN->wPKCount;
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"m: %d\n", m);
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"14+m*4: %d\n", 14+m*4);
+
+        if (pRSN->len >= 14+m*4) { //oui1(4)+ver(2)+GKS(4)+PKSCnt(2)+PKS(4*m)+AKC(2)
+            // overlay IE_RSN_Auth structure into correct place
+            pIE_RSN_Auth = (PWLAN_IE_RSN_AUTH) pRSN->PKSList[m].abyOUI;
+            j = 0;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wAuthCount: %d, sizeof(pBSSList->abyAuthType): %d\n",
+                          pIE_RSN_Auth->wAuthCount, sizeof(pBSSList->abyAuthType));
+            for(i = 0; (i < pIE_RSN_Auth->wAuthCount) && (j < sizeof(pBSSList->abyAuthType)/sizeof(BYTE)); i++) {
+                if(pRSN->len >= 14+4+(m+i)*4) { //oui1(4)+ver(2)+GKS(4)+PKSCnt(2)+PKS(4*m)+AKC(2)+AKS(4*i)
+                    if (MEMEqualMemory(pIE_RSN_Auth->AuthKSList[i].abyOUI, abyOUI01, 4))
+                        pBSSList->abyAuthType[j++] = WPA_AUTH_IEEE802_1X;
+                    else if (MEMEqualMemory(pIE_RSN_Auth->AuthKSList[i].abyOUI, abyOUI02, 4))
+                        pBSSList->abyAuthType[j++] = WPA_AUTH_PSK;
+                    else
+                    // any vendor checks here
+                    ;
+                }
+                else
+                    break;
+                //DBG_PRN_GRP14(("abyAuthType[%d]: %X\n", j-1, pBSSList->abyAuthType[j-1]));
+            }
+            if(j > 0)
+                pBSSList->wAuthCount = (WORD)j;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wAuthCount: %d\n", pBSSList->wAuthCount);
+        }
+
+        if (pIE_RSN_Auth != NULL) {
+
+            n = pIE_RSN_Auth->wAuthCount;
+
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"n: %d\n", n);
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"14+4+(m+n)*4: %d\n", 14+4+(m+n)*4);
+
+            if(pRSN->len+2 >= 14+4+(m+n)*4) { //oui1(4)+ver(2)+GKS(4)+PKSCnt(2)+PKS(4*m)+AKC(2)+AKS(4*n)+Cap(2)
+                pbyCaps = (PBYTE)pIE_RSN_Auth->AuthKSList[n].abyOUI;
+                pBSSList->byDefaultK_as_PK = (*pbyCaps) & WPA_GROUPFLAG;
+                pBSSList->byReplayIdx = 2 << ((*pbyCaps >> WPA_REPLAYBITSSHIFT) & WPA_REPLAYBITS);
+                pBSSList->sRSNCapObj.bRSNCapExist = TRUE;
+                pBSSList->sRSNCapObj.wRSNCap = *(PWORD)pbyCaps;
+                //DBG_PRN_GRP14(("pbyCaps: %X\n", *pbyCaps));
+                //DBG_PRN_GRP14(("byDefaultK_as_PK: %X\n", pBSSList->byDefaultK_as_PK));
+                //DBG_PRN_GRP14(("byReplayIdx: %X\n", pBSSList->byReplayIdx));
+            }
+        }
+        pBSSList->bWPAValid = TRUE;
+    }
+}
+
+/*+
+ *
+ * Description:
+ *    Search RSN information in BSSList.
+ *
+ * Parameters:
+ *  In:
+ *      byCmd    - Search type
+ *      byEncrypt- Encrcypt Type
+ *      pBSSList - BSS list
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+BOOL
+WPA_SearchRSN (
+    BYTE                byCmd,
+    BYTE                byEncrypt,
+    IN PKnownBSS        pBSSList
+    )
+{
+    int ii;
+    BYTE byPKType = WPA_NONE;
+
+    if (pBSSList->bWPAValid == FALSE)
+        return FALSE;
+
+    switch(byCmd) {
+    case 0:
+
+        if (byEncrypt != pBSSList->byGKType)
+            return FALSE;
+
+        if (pBSSList->wPKCount > 0) {
+            for (ii = 0; ii < pBSSList->wPKCount; ii ++) {
+                if (pBSSList->abyPKType[ii] == WPA_AESCCMP)
+                    byPKType = WPA_AESCCMP;
+                else if ((pBSSList->abyPKType[ii] == WPA_TKIP) && (byPKType != WPA_AESCCMP))
+                     byPKType = WPA_TKIP;
+                else if ((pBSSList->abyPKType[ii] == WPA_WEP40) && (byPKType != WPA_AESCCMP) && (byPKType != WPA_TKIP))
+                     byPKType = WPA_WEP40;
+                else if ((pBSSList->abyPKType[ii] == WPA_WEP104) && (byPKType != WPA_AESCCMP) && (byPKType != WPA_TKIP))
+                     byPKType = WPA_WEP104;
+            }
+            if (byEncrypt != byPKType)
+                return FALSE;
+        }
+        return TRUE;
+//        if (pBSSList->wAuthCount > 0)
+//            for (ii=0; ii < pBSSList->wAuthCount; ii ++)
+//                if (byAuth == pBSSList->abyAuthType[ii])
+//                    break;
+        break;
+
+    default:
+        break;
+    }
+    return FALSE;
+}
+
+/*+
+ *
+ * Description:
+ *    Check if RSN IE makes sense.
+ *
+ * Parameters:
+ *  In:
+ *      pRSN - Pointer to the RSN IE.
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+BOOL
+WPAb_Is_RSN (
+    IN PWLAN_IE_RSN_EXT pRSN
+    )
+{
+    if (pRSN == NULL)
+        return FALSE;
+
+    if ((pRSN->len >= 6) && // oui1(4)+ver(2)
+        (pRSN->byElementID == WLAN_EID_RSN_WPA) && MEMEqualMemory(pRSN->abyOUI, abyOUI01, 4) &&
+        (pRSN->wVersion == 1)) {
+        return TRUE;
+    }
+    else
+        return FALSE;
+}
+
diff --git a/drivers/staging/vt6655/wpa.h b/drivers/staging/vt6655/wpa.h
new file mode 100644
index 0000000..8000a37
--- /dev/null
+++ b/drivers/staging/vt6655/wpa.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: wpa.h
+ *
+ * Purpose: Defines the macros, types, and functions for dealing
+ *          with WPA informations.
+ *
+ * Author: Kyle Hsu
+ *
+ * Date: Jul 14, 2003
+ *
+ */
+
+#ifndef __WPA_H__
+#define __WPA_H__
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+#define WPA_NONE            0
+#define WPA_WEP40           1
+#define WPA_TKIP            2
+#define WPA_AESWRAP         3
+#define WPA_AESCCMP         4
+#define WPA_WEP104          5
+#define WPA_AUTH_IEEE802_1X 1
+#define WPA_AUTH_PSK        2
+
+#define WPA_GROUPFLAG       0x02
+#define WPA_REPLAYBITSSHIFT 2
+#define WPA_REPLAYBITS      0x03
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Types  ------------------------------*/
+
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+VOID
+WPA_ClearRSN(
+    IN PKnownBSS        pBSSList
+    );
+
+VOID
+WPA_ParseRSN(
+    IN PKnownBSS        pBSSList,
+    IN PWLAN_IE_RSN_EXT pRSN
+    );
+
+BOOL
+WPA_SearchRSN(
+    BYTE                byCmd,
+    BYTE                byEncrypt,
+    IN PKnownBSS        pBSSList
+    );
+
+BOOL
+WPAb_Is_RSN(
+    IN PWLAN_IE_RSN_EXT pRSN
+    );
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+#endif // __WPA_H__
diff --git a/drivers/staging/vt6655/wpa2.c b/drivers/staging/vt6655/wpa2.c
new file mode 100644
index 0000000..e2fdb33
--- /dev/null
+++ b/drivers/staging/vt6655/wpa2.c
@@ -0,0 +1,373 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: wpa2.c
+ *
+ * Purpose: Handles the Basic Service Set & Node Database functions
+ *
+ * Functions:
+ *
+ * Revision History:
+ *
+ * Author: Yiching Chen
+ *
+ * Date: Oct. 4, 2004
+ *
+ */
+#if !defined(__WPA2_H__)
+#include "wpa2.h"
+#endif
+#if !defined(__UMEM_H__)
+#include "umem.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__WMGR_H__)
+#include "wmgr.h"
+#endif
+
+
+/*---------------------  Static Definitions -------------------------*/
+static int          msglevel                =MSG_LEVEL_INFO;
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+
+const BYTE abyOUIGK[4]      = { 0x00, 0x0F, 0xAC, 0x00 };
+const BYTE abyOUIWEP40[4]   = { 0x00, 0x0F, 0xAC, 0x01 };
+const BYTE abyOUIWEP104[4]  = { 0x00, 0x0F, 0xAC, 0x05 };
+const BYTE abyOUITKIP[4]    = { 0x00, 0x0F, 0xAC, 0x02 };
+const BYTE abyOUICCMP[4]    = { 0x00, 0x0F, 0xAC, 0x04 };
+
+const BYTE abyOUI8021X[4]   = { 0x00, 0x0F, 0xAC, 0x01 };
+const BYTE abyOUIPSK[4]     = { 0x00, 0x0F, 0xAC, 0x02 };
+
+
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+/*+
+ *
+ * Description:
+ *    Clear RSN information in BSSList.
+ *
+ * Parameters:
+ *  In:
+ *      pBSSNode - BSS list.
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+VOID
+WPA2_ClearRSN (
+    IN PKnownBSS        pBSSNode
+    )
+{
+    int ii;
+
+    pBSSNode->bWPA2Valid = FALSE;
+
+    pBSSNode->byCSSGK = WLAN_11i_CSS_CCMP;
+    for (ii=0; ii < 4; ii ++)
+        pBSSNode->abyCSSPK[ii] = WLAN_11i_CSS_CCMP;
+    pBSSNode->wCSSPKCount = 1;
+    for (ii=0; ii < 4; ii ++)
+        pBSSNode->abyAKMSSAuthType[ii] = WLAN_11i_AKMSS_802_1X;
+    pBSSNode->wAKMSSAuthCount = 1;
+    pBSSNode->sRSNCapObj.bRSNCapExist = FALSE;
+    pBSSNode->sRSNCapObj.wRSNCap = 0;
+}
+
+/*+
+ *
+ * Description:
+ *    Parse RSN IE.
+ *
+ * Parameters:
+ *  In:
+ *      pBSSNode - BSS list.
+ *      pRSN - Pointer to the RSN IE.
+ *  Out:
+ *      none
+ *
+ * Return Value: none.
+ *
+-*/
+VOID
+WPA2vParseRSN (
+    IN PKnownBSS        pBSSNode,
+    IN PWLAN_IE_RSN     pRSN
+    )
+{
+    int                 i, j;
+    WORD                m = 0, n = 0;
+    PBYTE               pbyOUI;
+    BOOL                bUseGK = FALSE;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"WPA2_ParseRSN: [%d]\n", pRSN->len);
+
+    WPA2_ClearRSN(pBSSNode);
+
+    if (pRSN->len == 2) { // ver(2)
+        if ((pRSN->byElementID == WLAN_EID_RSN) && (pRSN->wVersion == 1)) {
+            pBSSNode->bWPA2Valid = TRUE;
+        }
+        return;
+    }
+
+    if (pRSN->len < 6) { // ver(2) + GK(4)
+        // invalid CSS, P802.11i/D10.0, p31
+        return;
+    }
+
+    // information element header makes sense
+    if ((pRSN->byElementID == WLAN_EID_RSN) &&
+        (pRSN->wVersion == 1)) {
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Legal 802.11i RSN\n");
+
+        pbyOUI = &(pRSN->abyRSN[0]);
+        if (MEMEqualMemory(pbyOUI, abyOUIWEP40, 4))
+            pBSSNode->byCSSGK = WLAN_11i_CSS_WEP40;
+        else if (MEMEqualMemory(pbyOUI, abyOUITKIP, 4))
+            pBSSNode->byCSSGK = WLAN_11i_CSS_TKIP;
+        else if (MEMEqualMemory(pbyOUI, abyOUICCMP, 4))
+            pBSSNode->byCSSGK = WLAN_11i_CSS_CCMP;
+        else if (MEMEqualMemory(pbyOUI, abyOUIWEP104, 4))
+            pBSSNode->byCSSGK = WLAN_11i_CSS_WEP104;
+        else if (MEMEqualMemory(pbyOUI, abyOUIGK, 4)) {
+            // invalid CSS, P802.11i/D10.0, p32
+            return;
+        } else
+            // any vendor checks here
+            pBSSNode->byCSSGK = WLAN_11i_CSS_UNKNOWN;
+
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"802.11i CSS: %X\n", pBSSNode->byCSSGK);
+
+        if (pRSN->len == 6) {
+            pBSSNode->bWPA2Valid = TRUE;
+            return;
+        }
+
+        if (pRSN->len >= 8) { // ver(2) + GK(4) + PK count(2)
+            pBSSNode->wCSSPKCount = *((PWORD) &(pRSN->abyRSN[4]));
+            j = 0;
+            pbyOUI = &(pRSN->abyRSN[6]);
+
+            for (i = 0; (i < pBSSNode->wCSSPKCount) && (j < sizeof(pBSSNode->abyCSSPK)/sizeof(BYTE)); i++) {
+
+                if (pRSN->len >= 8+i*4+4) { // ver(2)+GK(4)+PKCnt(2)+PKS(4*i)
+                    if (MEMEqualMemory(pbyOUI, abyOUIGK, 4)) {
+                        pBSSNode->abyCSSPK[j++] = WLAN_11i_CSS_USE_GROUP;
+                        bUseGK = TRUE;
+                    } else if (MEMEqualMemory(pbyOUI, abyOUIWEP40, 4)) {
+                        // Invialid CSS, continue to parsing
+                    } else if (MEMEqualMemory(pbyOUI, abyOUITKIP, 4)) {
+                        if (pBSSNode->byCSSGK != WLAN_11i_CSS_CCMP)
+                            pBSSNode->abyCSSPK[j++] = WLAN_11i_CSS_TKIP;
+                        else
+                            ; // Invialid CSS, continue to parsing
+                    } else if (MEMEqualMemory(pbyOUI, abyOUICCMP, 4)) {
+                        pBSSNode->abyCSSPK[j++] = WLAN_11i_CSS_CCMP;
+                    } else if (MEMEqualMemory(pbyOUI, abyOUIWEP104, 4)) {
+                        // Invialid CSS, continue to parsing
+                    } else {
+                        // any vendor checks here
+                        pBSSNode->abyCSSPK[j++] = WLAN_11i_CSS_UNKNOWN;
+                    }
+                    pbyOUI += 4;
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"abyCSSPK[%d]: %X\n", j-1, pBSSNode->abyCSSPK[j-1]);
+                } else
+                    break;
+            } //for
+
+            if (bUseGK == TRUE) {
+                if (j != 1) {
+                    // invalid CSS, This should be only PK CSS.
+                    return;
+                }
+                if (pBSSNode->byCSSGK == WLAN_11i_CSS_CCMP) {
+                    // invalid CSS, If CCMP is enable , PK can't be CSSGK.
+                    return;
+                }
+            }
+            if ((pBSSNode->wCSSPKCount != 0) && (j == 0)) {
+                // invalid CSS, No valid PK.
+                return;
+            }
+            pBSSNode->wCSSPKCount = (WORD)j;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wCSSPKCount: %d\n", pBSSNode->wCSSPKCount);
+        }
+
+        m = *((PWORD) &(pRSN->abyRSN[4]));
+
+        if (pRSN->len >= 10+m*4) { // ver(2) + GK(4) + PK count(2) + PKS(4*m) + AKMSS count(2)
+            pBSSNode->wAKMSSAuthCount = *((PWORD) &(pRSN->abyRSN[6+4*m]));;
+            j = 0;
+            pbyOUI = &(pRSN->abyRSN[8+4*m]);
+            for (i = 0; (i < pBSSNode->wAKMSSAuthCount) && (j < sizeof(pBSSNode->abyAKMSSAuthType)/sizeof(BYTE)); i++) {
+                if (pRSN->len >= 10+(m+i)*4+4) { // ver(2)+GK(4)+PKCnt(2)+PKS(4*m)+AKMSS(2)+AKS(4*i)
+                    if (MEMEqualMemory(pbyOUI, abyOUI8021X, 4))
+                        pBSSNode->abyAKMSSAuthType[j++] = WLAN_11i_AKMSS_802_1X;
+                    else if (MEMEqualMemory(pbyOUI, abyOUIPSK, 4))
+                        pBSSNode->abyAKMSSAuthType[j++] = WLAN_11i_AKMSS_PSK;
+                    else
+                        // any vendor checks here
+                        pBSSNode->abyAKMSSAuthType[j++] = WLAN_11i_AKMSS_UNKNOWN;
+                    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"abyAKMSSAuthType[%d]: %X\n", j-1, pBSSNode->abyAKMSSAuthType[j-1]);
+                } else
+                    break;
+            }
+            pBSSNode->wAKMSSAuthCount = (WORD)j;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO"wAKMSSAuthCount: %d\n", pBSSNode->wAKMSSAuthCount);
+
+            n = *((PWORD) &(pRSN->abyRSN[6+4*m]));;
+            if (pRSN->len >= 12+4*m+4*n) { // ver(2)+GK(4)+PKCnt(2)+PKS(4*m)+AKMSSCnt(2)+AKMSS(4*n)+Cap(2)
+                pBSSNode->sRSNCapObj.bRSNCapExist = TRUE;
+                pBSSNode->sRSNCapObj.wRSNCap = *((PWORD) &(pRSN->abyRSN[8+4*m+4*n]));
+            }
+        }
+        //ignore PMKID lists bcs only (Re)Assocrequest has this field
+        pBSSNode->bWPA2Valid = TRUE;
+    }
+}
+
+
+/*+
+ *
+ * Description:
+ *    Set WPA IEs
+ *
+ * Parameters:
+ *  In:
+ *      pMgmtHandle - Pointer to management object
+ *  Out:
+ *      pRSNIEs     - Pointer to the RSN IE to set.
+ *
+ * Return Value: length of IEs.
+ *
+-*/
+UINT
+WPA2uSetIEs(
+    IN PVOID pMgmtHandle,
+    OUT PWLAN_IE_RSN pRSNIEs
+    )
+{
+    PSMgmtObject    pMgmt = (PSMgmtObject) pMgmtHandle;
+    PBYTE           pbyBuffer = NULL;
+    UINT            ii = 0;
+    PWORD           pwPMKID = NULL;
+
+    if (pRSNIEs == NULL) {
+        return(0);
+    }
+    if (((pMgmt->eAuthenMode == WMAC_AUTH_WPA2) ||
+         (pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK)) &&
+        (pMgmt->pCurrBSS != NULL)) {
+        /* WPA2 IE */
+        pbyBuffer = (PBYTE) pRSNIEs;
+        pRSNIEs->byElementID = WLAN_EID_RSN;
+        pRSNIEs->len = 6; //Version(2)+GK(4)
+        pRSNIEs->wVersion = 1;
+        //Group Key Cipher Suite
+        pRSNIEs->abyRSN[0] = 0x00;
+        pRSNIEs->abyRSN[1] = 0x0F;
+        pRSNIEs->abyRSN[2] = 0xAC;
+        if (pMgmt->byCSSGK == KEY_CTL_WEP) {
+            pRSNIEs->abyRSN[3] = pMgmt->pCurrBSS->byCSSGK;
+        } else if (pMgmt->byCSSGK == KEY_CTL_TKIP) {
+            pRSNIEs->abyRSN[3] = WLAN_11i_CSS_TKIP;
+        } else if (pMgmt->byCSSGK == KEY_CTL_CCMP) {
+            pRSNIEs->abyRSN[3] = WLAN_11i_CSS_CCMP;
+        } else {
+            pRSNIEs->abyRSN[3] = WLAN_11i_CSS_UNKNOWN;
+        }
+
+        // Pairwise Key Cipher Suite
+        pRSNIEs->abyRSN[4] = 1;
+        pRSNIEs->abyRSN[5] = 0;
+        pRSNIEs->abyRSN[6] = 0x00;
+        pRSNIEs->abyRSN[7] = 0x0F;
+        pRSNIEs->abyRSN[8] = 0xAC;
+        if (pMgmt->byCSSPK == KEY_CTL_TKIP) {
+            pRSNIEs->abyRSN[9] = WLAN_11i_CSS_TKIP;
+        } else if (pMgmt->byCSSPK == KEY_CTL_CCMP) {
+            pRSNIEs->abyRSN[9] = WLAN_11i_CSS_CCMP;
+        } else if (pMgmt->byCSSPK == KEY_CTL_NONE) {
+            pRSNIEs->abyRSN[9] = WLAN_11i_CSS_USE_GROUP;
+        } else {
+            pRSNIEs->abyRSN[9] = WLAN_11i_CSS_UNKNOWN;
+        }
+        pRSNIEs->len += 6;
+
+        // Auth Key Management Suite
+        pRSNIEs->abyRSN[10] = 1;
+        pRSNIEs->abyRSN[11] = 0;
+        pRSNIEs->abyRSN[12] = 0x00;
+        pRSNIEs->abyRSN[13] = 0x0F;
+        pRSNIEs->abyRSN[14] = 0xAC;
+        if (pMgmt->eAuthenMode == WMAC_AUTH_WPA2PSK) {
+            pRSNIEs->abyRSN[15] = WLAN_11i_AKMSS_PSK;
+        } else if (pMgmt->eAuthenMode == WMAC_AUTH_WPA2) {
+            pRSNIEs->abyRSN[15] = WLAN_11i_AKMSS_802_1X;
+        } else {
+            pRSNIEs->abyRSN[15] = WLAN_11i_AKMSS_UNKNOWN;
+        }
+        pRSNIEs->len +=6;
+
+        // RSN Capabilites
+        if (pMgmt->pCurrBSS->sRSNCapObj.bRSNCapExist == TRUE) {
+            MEMvCopy(&pRSNIEs->abyRSN[16], &pMgmt->pCurrBSS->sRSNCapObj.wRSNCap, 2);
+        } else {
+            pRSNIEs->abyRSN[16] = 0;
+            pRSNIEs->abyRSN[17] = 0;
+        }
+        pRSNIEs->len +=2;
+
+        if ((pMgmt->gsPMKIDCache.BSSIDInfoCount > 0) &&
+            (pMgmt->bRoaming == TRUE) &&
+            (pMgmt->eAuthenMode == WMAC_AUTH_WPA2)) {
+            // RSN PMKID
+            pwPMKID = (PWORD)(&pRSNIEs->abyRSN[18]);  // Point to PMKID count
+            *pwPMKID = 0;                               // Initialize PMKID count
+            pbyBuffer = &pRSNIEs->abyRSN[20];           // Point to PMKID list
+            for (ii = 0; ii < pMgmt->gsPMKIDCache.BSSIDInfoCount; ii++) {
+                if (MEMEqualMemory(&pMgmt->gsPMKIDCache.BSSIDInfo[ii].abyBSSID[0], pMgmt->abyCurrBSSID, U_ETHER_ADDR_LEN)) {
+                    (*pwPMKID) ++;
+                    MEMvCopy(pbyBuffer, pMgmt->gsPMKIDCache.BSSIDInfo[ii].abyPMKID, 16);
+                    pbyBuffer += 16;
+                }
+            }
+            if (*pwPMKID != 0) {
+                pRSNIEs->len += (2 + (*pwPMKID)*16);
+            } else {
+                pbyBuffer = &pRSNIEs->abyRSN[18];
+            }
+        }
+        return(pRSNIEs->len + WLAN_IEHDR_LEN);
+    }
+    return(0);
+}
diff --git a/drivers/staging/vt6655/wpa2.h b/drivers/staging/vt6655/wpa2.h
new file mode 100644
index 0000000..bda045b
--- /dev/null
+++ b/drivers/staging/vt6655/wpa2.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
+ * File: wpa2.h
+ *
+ * Purpose: Defines the macros, types, and functions for dealing
+ *          with WPA2 informations.
+ *
+ * Author: Yiching Chen
+ *
+ * Date: Oct. 4, 2004
+ *
+ */
+
+#ifndef __WPA2_H__
+#define __WPA2_H__
+
+
+#if !defined(__TTYPE_H__)
+#include "ttype.h"
+#endif
+#if !defined(__80211MGR_H__)
+#include "80211mgr.h"
+#endif
+#if !defined(__80211HDR_H__)
+#include "80211hdr.h"
+#endif
+#if !defined(__BSSDB_H__)
+#include "bssdb.h"
+#endif
+#if !defined(__VNTWIFI_H__)
+#include "vntwifi.h"
+#endif
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+typedef struct tagsPMKIDInfo {
+    BYTE    abyBSSID[6];
+    BYTE    abyPMKID[16];
+} PMKIDInfo, *PPMKIDInfo;
+
+typedef struct tagSPMKIDCache {
+    ULONG       BSSIDInfoCount;
+    PMKIDInfo   BSSIDInfo[MAX_PMKID_CACHE];
+} SPMKIDCache, *PSPMKIDCache;
+
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Types  ------------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+VOID
+WPA2_ClearRSN (
+    IN PKnownBSS        pBSSNode
+    );
+
+VOID
+WPA2vParseRSN (
+    IN PKnownBSS        pBSSNode,
+    IN PWLAN_IE_RSN     pRSN
+    );
+
+UINT
+WPA2uSetIEs(
+    IN PVOID pMgmtHandle,
+    OUT PWLAN_IE_RSN pRSNIEs
+    );
+
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+#endif // __WPA2_H__
diff --git a/drivers/staging/vt6655/wpactl.c b/drivers/staging/vt6655/wpactl.c
new file mode 100644
index 0000000..cc4f0ad
--- /dev/null
+++ b/drivers/staging/vt6655/wpactl.c
@@ -0,0 +1,1017 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: wpactl.c
+ *
+ * Purpose: handle wpa supplicant ioctl input/out functions
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: Oct. 20, 2003
+ *
+ * Functions:
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__WPACTL_H__)
+#include "wpactl.h"
+#endif
+#if !defined(__KEY_H__)
+#include "key.h"
+#endif
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#if !defined(__WMGR_H__)
+#include "wmgr.h"
+#endif
+#if !defined(__IOCMD_H__)
+#include "iocmd.h"
+#endif
+#if !defined(__IOWPA_H__)
+#include "iowpa.h"
+#endif
+//2008-0717-05, <Add> by James
+#if !defined(__RF_H__)
+#include "rf.h"
+#endif
+
+/*---------------------  Static Definitions -------------------------*/
+
+#define VIAWGET_WPA_MAX_BUF_SIZE 1024
+
+
+
+static const int frequency_list[] = {
+	2412, 2417, 2422, 2427, 2432, 2437, 2442,
+	2447, 2452, 2457, 2462, 2467, 2472, 2484
+};
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+static int          msglevel                =MSG_LEVEL_INFO;
+
+/*---------------------  Static Functions  --------------------------*/
+
+
+
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+static void wpadev_setup(struct net_device *dev)
+{
+	dev->type               = ARPHRD_IEEE80211;
+	dev->hard_header_len    = ETH_HLEN;
+	dev->mtu                = 2048;
+	dev->addr_len           = ETH_ALEN;
+	dev->tx_queue_len       = 1000;
+
+	memset(dev->broadcast,0xFF, ETH_ALEN);
+
+	dev->flags              = IFF_BROADCAST|IFF_MULTICAST;
+}
+
+
+
+/*
+ * Description:
+ *      register netdev for wpa supplicant deamon
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             -
+ *      enable              -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int wpa_init_wpadev(PSDevice pDevice)
+{
+    PSDevice wpadev_priv;
+	struct net_device *dev = pDevice->dev;
+         int ret=0;
+
+	pDevice->wpadev = alloc_netdev(sizeof(PSDevice), "vntwpa", wpadev_setup);
+	if (pDevice->wpadev == NULL)
+		return -ENOMEM;
+
+    wpadev_priv = netdev_priv(pDevice->wpadev);
+    *wpadev_priv = *pDevice;
+
+	memcpy(pDevice->wpadev->dev_addr, dev->dev_addr, U_ETHER_ADDR_LEN);
+         pDevice->wpadev->base_addr = dev->base_addr;
+	pDevice->wpadev->irq = dev->irq;
+	pDevice->wpadev->mem_start = dev->mem_start;
+	pDevice->wpadev->mem_end = dev->mem_end;
+	ret = register_netdev(pDevice->wpadev);
+	if (ret) {
+		DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: register_netdev(WPA) failed!\n",
+		       dev->name);
+		free_netdev(pDevice->wpadev);
+		return -1;
+	}
+
+	if (pDevice->skb == NULL) {
+        pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
+        if (pDevice->skb == NULL)
+		    return -ENOMEM;
+    }
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: Registered netdev %s for WPA management\n",
+	       dev->name, pDevice->wpadev->name);
+
+	return 0;
+}
+
+
+/*
+ * Description:
+ *      unregister net_device (wpadev)
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int wpa_release_wpadev(PSDevice pDevice)
+{
+
+    if (pDevice->skb) {
+        dev_kfree_skb(pDevice->skb);
+        pDevice->skb = NULL;
+    }
+
+    if (pDevice->wpadev) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "%s: Netdevice %s unregistered\n",
+	       pDevice->dev->name, pDevice->wpadev->name);
+	unregister_netdev(pDevice->wpadev);
+	free_netdev(pDevice->wpadev);
+         pDevice->wpadev = NULL;
+    }
+
+	return 0;
+}
+
+
+
+
+
+/*
+ * Description:
+ *      Set enable/disable dev for wpa supplicant deamon
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             -
+ *      val                 -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+int wpa_set_wpadev(PSDevice pDevice, int val)
+{
+
+
+	if (val)
+		return wpa_init_wpadev(pDevice);
+	else
+		return wpa_release_wpadev(pDevice);
+}
+
+
+/*
+ * Description:
+ *      Set WPA algorithm & keys
+ *
+ * Parameters:
+ *  In:
+ *      pDevice -
+ *      param -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+int wpa_set_keys(PSDevice pDevice, void *ctx, BOOL  fcpfkernel)
+{
+ struct viawget_wpa_param *param=ctx;
+    PSMgmtObject pMgmt = pDevice->pMgmt;
+    DWORD   dwKeyIndex = 0;
+    BYTE    abyKey[MAX_KEY_LEN];
+    BYTE    abySeq[MAX_KEY_LEN];
+    QWORD   KeyRSC;
+//    NDIS_802_11_KEY_RSC KeyRSC;
+    BYTE    byKeyDecMode = KEY_CTL_WEP;
+	int ret = 0;
+	int uu, ii;
+
+
+	if (param->u.wpa_key.alg_name > WPA_ALG_CCMP)
+		return -EINVAL;
+
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "param->u.wpa_key.alg_name = %d \n", param->u.wpa_key.alg_name);
+	if (param->u.wpa_key.alg_name == WPA_ALG_NONE) {
+        pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
+        pDevice->bEncryptionEnable = FALSE;
+        pDevice->byKeyIndex = 0;
+        pDevice->bTransmitKey = FALSE;
+        KeyvRemoveAllWEPKey(&(pDevice->sKey), pDevice->PortOffset);
+        for (uu=0; uu<MAX_KEY_TABLE; uu++) {
+            MACvDisableKeyEntry(pDevice->PortOffset, uu);
+        }
+        return ret;
+    }
+
+    //spin_unlock_irq(&pDevice->lock);
+    if(param->u.wpa_key.key && fcpfkernel) {
+       memcpy(&abyKey[0], param->u.wpa_key.key, param->u.wpa_key.key_len);
+     }
+    else {
+	spin_unlock_irq(&pDevice->lock);
+	if (param->u.wpa_key.key &&
+	    copy_from_user(&abyKey[0], param->u.wpa_key.key, param->u.wpa_key.key_len)){
+	        spin_lock_irq(&pDevice->lock);
+	    return -EINVAL;
+    	}
+spin_lock_irq(&pDevice->lock);
+    	}
+
+    dwKeyIndex = (DWORD)(param->u.wpa_key.key_index);
+
+	if (param->u.wpa_key.alg_name == WPA_ALG_WEP) {
+        if (dwKeyIndex > 3) {
+            return -EINVAL;
+        }
+        else {
+            if (param->u.wpa_key.set_tx) {
+                pDevice->byKeyIndex = (BYTE)dwKeyIndex;
+                pDevice->bTransmitKey = TRUE;
+		        dwKeyIndex |= (1 << 31);
+            }
+            KeybSetDefaultKey(&(pDevice->sKey),
+                                dwKeyIndex & ~(BIT30 | USE_KEYRSC),
+                                param->u.wpa_key.key_len,
+                                NULL,
+                                abyKey,
+                                KEY_CTL_WEP,
+                                pDevice->PortOffset,
+                                pDevice->byLocalID);
+
+        }
+        pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
+        pDevice->bEncryptionEnable = TRUE;
+        return ret;
+	}
+
+	    //spin_unlock_irq(&pDevice->lock);
+        if(param->u.wpa_key.seq && fcpfkernel) {
+           memcpy(&abySeq[0], param->u.wpa_key.seq, param->u.wpa_key.seq_len);
+        	}
+       else {
+	   	spin_unlock_irq(&pDevice->lock);
+	if (param->u.wpa_key.seq &&
+	    copy_from_user(&abySeq[0], param->u.wpa_key.seq, param->u.wpa_key.seq_len)){
+
+	 spin_lock_irq(&pDevice->lock);
+	    return -EINVAL;
+       	}
+spin_lock_irq(&pDevice->lock);
+}
+
+	if (param->u.wpa_key.seq_len > 0) {
+		for (ii = 0 ; ii < param->u.wpa_key.seq_len ; ii++) {
+		     if (ii < 4)
+			    LODWORD(KeyRSC) |= (abySeq[ii] << (ii * 8));
+			 else
+			    HIDWORD(KeyRSC) |= (abySeq[ii] << ((ii-4) * 8));
+	         //KeyRSC |= (abySeq[ii] << (ii * 8));
+		}
+		dwKeyIndex |= 1 << 29;
+	}
+
+    if (param->u.wpa_key.key_index >= MAX_GROUP_KEY) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "return  dwKeyIndex > 3\n");
+        return -EINVAL;
+    }
+
+	if (param->u.wpa_key.alg_name == WPA_ALG_TKIP) {
+        pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;
+    }
+
+	if (param->u.wpa_key.alg_name == WPA_ALG_CCMP) {
+        pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;
+    }
+
+	if (param->u.wpa_key.set_tx)
+		dwKeyIndex |= (1 << 31);
+
+    if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled)
+        byKeyDecMode = KEY_CTL_CCMP;
+    else if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled)
+        byKeyDecMode = KEY_CTL_TKIP;
+    else
+        byKeyDecMode = KEY_CTL_WEP;
+
+    // Fix HCT test that set 256 bits KEY and Ndis802_11Encryption3Enabled
+    if (pDevice->eEncryptionStatus == Ndis802_11Encryption3Enabled) {
+        if (param->u.wpa_key.key_len == MAX_KEY_LEN)
+            byKeyDecMode = KEY_CTL_TKIP;
+        else if (param->u.wpa_key.key_len == WLAN_WEP40_KEYLEN)
+            byKeyDecMode = KEY_CTL_WEP;
+        else if (param->u.wpa_key.key_len == WLAN_WEP104_KEYLEN)
+            byKeyDecMode = KEY_CTL_WEP;
+    } else if (pDevice->eEncryptionStatus == Ndis802_11Encryption2Enabled) {
+        if (param->u.wpa_key.key_len == WLAN_WEP40_KEYLEN)
+            byKeyDecMode = KEY_CTL_WEP;
+        else if (param->u.wpa_key.key_len == WLAN_WEP104_KEYLEN)
+            byKeyDecMode = KEY_CTL_WEP;
+    }
+
+
+    // Check TKIP key length
+    if ((byKeyDecMode == KEY_CTL_TKIP) &&
+        (param->u.wpa_key.key_len != MAX_KEY_LEN)) {
+        // TKIP Key must be 256 bits
+        //DBG_PRN_WLAN03(("return NDIS_STATUS_INVALID_DATA - TKIP Key must be 256 bits\n"));
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "return- TKIP Key must be 256 bits!\n");
+        return -EINVAL;
+    }
+    // Check AES key length
+    if ((byKeyDecMode == KEY_CTL_CCMP) &&
+        (param->u.wpa_key.key_len != AES_KEY_LEN)) {
+        // AES Key must be 128 bits
+        //DBG_PRN_WLAN03(("return NDIS_STATUS_INVALID_DATA - AES Key must be 128 bits\n"));
+        return -EINVAL;
+    }
+
+   // spin_lock_irq(&pDevice->lock);
+    if (IS_BROADCAST_ADDRESS(&param->addr[0]) || (param->addr == NULL)) {
+        // If IS_BROADCAST_ADDRESS, set the key as every key entry's group key.
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Groupe Key Assign.\n");
+
+        if ((KeybSetAllGroupKey(&(pDevice->sKey),
+                            dwKeyIndex,
+                            param->u.wpa_key.key_len,
+                            (PQWORD) &(KeyRSC),
+                            (PBYTE)abyKey,
+                            byKeyDecMode,
+                            pDevice->PortOffset,
+                            pDevice->byLocalID) == TRUE) &&
+            (KeybSetDefaultKey(&(pDevice->sKey),
+                            dwKeyIndex,
+                            param->u.wpa_key.key_len,
+                            (PQWORD) &(KeyRSC),
+                            (PBYTE)abyKey,
+                            byKeyDecMode,
+                            pDevice->PortOffset,
+                            pDevice->byLocalID) == TRUE) ) {
+             DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "GROUP Key Assign.\n");
+
+        } else {
+            //DBG_PRN_WLAN03(("return NDIS_STATUS_INVALID_DATA -KeybSetDefaultKey Fail.0\n"));
+           // spin_unlock_irq(&pDevice->lock);
+            return -EINVAL;
+        }
+
+    } else {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Pairwise Key Assign.\n");
+        // BSSID not 0xffffffffffff
+        // Pairwise Key can't be WEP
+        if (byKeyDecMode == KEY_CTL_WEP) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Pairwise Key can't be WEP\n");
+            //spin_unlock_irq(&pDevice->lock);
+            return -EINVAL;
+        }
+
+        dwKeyIndex |= (1 << 30); // set pairwise key
+        if (pMgmt->eConfigMode == WMAC_CONFIG_IBSS_STA) {
+            //DBG_PRN_WLAN03(("return NDIS_STATUS_INVALID_DATA - WMAC_CONFIG_IBSS_STA\n"));
+            //spin_unlock_irq(&pDevice->lock);
+            return -EINVAL;
+        }
+        if (KeybSetKey(&(pDevice->sKey),
+                       &param->addr[0],
+                       dwKeyIndex,
+                       param->u.wpa_key.key_len,
+                       (PQWORD) &(KeyRSC),
+                       (PBYTE)abyKey,
+                        byKeyDecMode,
+                        pDevice->PortOffset,
+                        pDevice->byLocalID) == TRUE) {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Pairwise Key Set\n");
+
+        } else {
+            // Key Table Full
+            if (IS_ETH_ADDRESS_EQUAL(&param->addr[0], pDevice->abyBSSID)) {
+                //DBG_PRN_WLAN03(("return NDIS_STATUS_INVALID_DATA -Key Table Full.2\n"));
+                //spin_unlock_irq(&pDevice->lock);
+                return -EINVAL;
+
+            } else {
+                // Save Key and configure just before associate/reassociate to BSSID
+                // we do not implement now
+                //spin_unlock_irq(&pDevice->lock);
+                return -EINVAL;
+            }
+        }
+    } // BSSID not 0xffffffffffff
+    if ((ret == 0) && ((param->u.wpa_key.set_tx) != 0)) {
+        pDevice->byKeyIndex = (BYTE)param->u.wpa_key.key_index;
+        pDevice->bTransmitKey = TRUE;
+    }
+    pDevice->bEncryptionEnable = TRUE;
+    //spin_unlock_irq(&pDevice->lock);
+
+/*
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " key=%x-%x-%x-%x-%x-xxxxx \n",
+               pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[byKeyIndex][0],
+               pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[byKeyIndex][1],
+               pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[byKeyIndex][2],
+               pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[byKeyIndex][3],
+               pMgmt->sNodeDBTable[iNodeIndex].abyWepKey[byKeyIndex][4]
+              );
+*/
+
+	return ret;
+
+}
+
+
+/*
+ * Description:
+ *      enable wpa auth & mode
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int wpa_set_wpa(PSDevice pDevice,
+				     struct viawget_wpa_param *param)
+{
+
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+	int ret = 0;
+
+    pMgmt->eAuthenMode = WMAC_AUTH_OPEN;
+    pMgmt->bShareKeyAlgorithm = FALSE;
+
+    return ret;
+}
+
+
+
+
+ /*
+ * Description:
+ *      set disassociate
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int wpa_set_disassociate(PSDevice pDevice,
+				     struct viawget_wpa_param *param)
+{
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+	int ret = 0;
+
+    spin_lock_irq(&pDevice->lock);
+    if (pDevice->bLinkPass) {
+        if (!memcmp(param->addr, pMgmt->abyCurrBSSID, 6))
+            bScheduleCommand((HANDLE)pDevice, WLAN_CMD_DISASSOCIATE, NULL);
+    }
+    spin_unlock_irq(&pDevice->lock);
+
+    return ret;
+}
+
+
+
+/*
+ * Description:
+ *      enable scan process
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int wpa_set_scan(PSDevice pDevice,
+				     struct viawget_wpa_param *param)
+{
+	int ret = 0;
+
+    spin_lock_irq(&pDevice->lock);
+    BSSvClearBSSList((HANDLE)pDevice, pDevice->bLinkPass);
+    bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, NULL);
+    spin_unlock_irq(&pDevice->lock);
+
+    return ret;
+}
+
+
+
+/*
+ * Description:
+ *      get bssid
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int wpa_get_bssid(PSDevice pDevice,
+				     struct viawget_wpa_param *param)
+{
+    PSMgmtObject        pMgmt = pDevice->pMgmt;
+	int ret = 0;
+
+	memcpy(param->u.wpa_associate.bssid, pMgmt->abyCurrBSSID , 6);
+
+    return ret;
+
+}
+
+
+/*
+ * Description:
+ *      get bssid
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int wpa_get_ssid(PSDevice pDevice,
+				     struct viawget_wpa_param *param)
+{
+    PSMgmtObject        pMgmt = pDevice->pMgmt;
+	PWLAN_IE_SSID       pItemSSID;
+	int ret = 0;
+
+    pItemSSID = (PWLAN_IE_SSID)pMgmt->abyCurrSSID;
+
+	memcpy(param->u.wpa_associate.ssid, pItemSSID->abySSID , pItemSSID->len);
+	param->u.wpa_associate.ssid_len = pItemSSID->len;
+
+    return ret;
+}
+
+
+
+/*
+ * Description:
+ *      get scan results
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int wpa_get_scan(PSDevice pDevice,
+				     struct viawget_wpa_param *param)
+{
+	struct viawget_scan_result *scan_buf;
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PWLAN_IE_SSID   pItemSSID;
+    PKnownBSS pBSS;
+	PBYTE  pBuf;
+	int ret = 0;
+	u16 count = 0;
+	u16 ii, jj;
+#if 1
+
+    PBYTE ptempBSS;
+
+
+
+    ptempBSS = kmalloc(sizeof(KnownBSS), (int)GFP_ATOMIC);
+
+    if (ptempBSS == NULL) {
+
+       printk("bubble sort kmalloc memory fail@@@\n");
+
+        ret = -ENOMEM;
+
+        return ret;
+
+    }
+
+    for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+
+         for(jj=0;jj<MAX_BSS_NUM-ii-1;jj++) {
+
+           if((pMgmt->sBSSList[jj].bActive!=TRUE) ||
+
+                ((pMgmt->sBSSList[jj].uRSSI>pMgmt->sBSSList[jj+1].uRSSI) &&(pMgmt->sBSSList[jj+1].bActive!=FALSE))) {
+
+                 memcpy(ptempBSS,&pMgmt->sBSSList[jj],sizeof(KnownBSS));
+
+                 memcpy(&pMgmt->sBSSList[jj],&pMgmt->sBSSList[jj+1],sizeof(KnownBSS));
+
+                 memcpy(&pMgmt->sBSSList[jj+1],ptempBSS,sizeof(KnownBSS));
+
+              }
+
+         }
+
+    };
+
+  kfree(ptempBSS);
+
+ // printk("bubble sort result:\n");
+
+  //for (ii = 0; ii < MAX_BSS_NUM; ii++)
+
+  //    printk("%d [%s]:RSSI=%d\n",ii,((PWLAN_IE_SSID)(pMgmt->sBSSList[ii].abySSID))->abySSID,
+
+  //                                                                 pMgmt->sBSSList[ii].uRSSI);
+
+ #endif
+
+//******mike:bubble sort by stronger RSSI*****//
+
+
+
+
+	count = 0;
+	pBSS = &(pMgmt->sBSSList[0]);
+    for (ii = 0; ii < MAX_BSS_NUM; ii++) {
+        pBSS = &(pMgmt->sBSSList[ii]);
+        if (!pBSS->bActive)
+            continue;
+        count++;
+    };
+
+    pBuf = kmalloc(sizeof(struct viawget_scan_result) * count, (int)GFP_ATOMIC);
+
+    if (pBuf == NULL) {
+        ret = -ENOMEM;
+        return ret;
+    }
+   	memset(pBuf, 0, sizeof(struct viawget_scan_result) * count);
+    scan_buf = (struct viawget_scan_result *)pBuf;
+	pBSS = &(pMgmt->sBSSList[0]);
+    for (ii = 0, jj = 0; ii < MAX_BSS_NUM ; ii++) {
+        pBSS = &(pMgmt->sBSSList[ii]);
+        if (pBSS->bActive) {
+            if (jj >= count)
+                break;
+            memcpy(scan_buf->bssid, pBSS->abyBSSID, WLAN_BSSID_LEN);
+            pItemSSID = (PWLAN_IE_SSID)pBSS->abySSID;
+   		    memcpy(scan_buf->ssid, pItemSSID->abySSID, pItemSSID->len);
+   		    scan_buf->ssid_len = pItemSSID->len;
+            scan_buf->freq = frequency_list[pBSS->uChannel-1];
+	  scan_buf->caps = pBSS->wCapInfo;
+            //scan_buf->caps = pBSS->wCapInfo;
+            //scan_buf->qual =
+            //scan_buf->noise =
+            //scan_buf->level =
+            //scan_buf->maxrate =
+            if (pBSS->wWPALen != 0) {
+                scan_buf->wpa_ie_len = pBSS->wWPALen;
+                memcpy(scan_buf->wpa_ie, pBSS->byWPAIE, pBSS->wWPALen);
+            }
+            if (pBSS->wRSNLen != 0) {
+                scan_buf->rsn_ie_len = pBSS->wRSNLen;
+                memcpy(scan_buf->rsn_ie, pBSS->byRSNIE, pBSS->wRSNLen);
+            }
+            scan_buf = (struct viawget_scan_result *)((PBYTE)scan_buf + sizeof(struct viawget_scan_result));
+            jj ++;
+        }
+    }
+
+    if (jj < count)
+        count = jj;
+
+    if (copy_to_user(param->u.scan_results.buf, pBuf, sizeof(struct viawget_scan_result) * count)) {
+		ret = -EFAULT;
+	};
+	param->u.scan_results.scan_count = count;
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO " param->u.scan_results.scan_count = %d\n", count)
+
+    kfree(pBuf);
+    return ret;
+}
+
+
+
+/*
+ * Description:
+ *      set associate with AP
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      param     -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+static int wpa_set_associate(PSDevice pDevice,
+				     struct viawget_wpa_param *param)
+{
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PWLAN_IE_SSID   pItemSSID;
+    BYTE    abyNullAddr[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+    BYTE    abyWPAIE[64];
+    int ret = 0;
+    BOOL bWepEnabled=FALSE;
+
+	// set key type & algorithm
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pairwise_suite = %d\n", param->u.wpa_associate.pairwise_suite);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "group_suite = %d\n", param->u.wpa_associate.group_suite);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "key_mgmt_suite = %d\n", param->u.wpa_associate.key_mgmt_suite);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "auth_alg = %d\n", param->u.wpa_associate.auth_alg);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "mode = %d\n", param->u.wpa_associate.mode);
+    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wpa_ie_len = %d\n", param->u.wpa_associate.wpa_ie_len);
+
+
+	if (param->u.wpa_associate.wpa_ie &&
+	    copy_from_user(&abyWPAIE[0], param->u.wpa_associate.wpa_ie, param->u.wpa_associate.wpa_ie_len))
+	    return -EINVAL;
+
+	if (param->u.wpa_associate.mode == 1)
+	    pMgmt->eConfigMode = WMAC_CONFIG_IBSS_STA;
+	else
+	    pMgmt->eConfigMode = WMAC_CONFIG_ESS_STA;
+    // set ssid
+	memset(pMgmt->abyDesireSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
+    pItemSSID = (PWLAN_IE_SSID)pMgmt->abyDesireSSID;
+    pItemSSID->byElementID = WLAN_EID_SSID;
+	pItemSSID->len = param->u.wpa_associate.ssid_len;
+	memcpy(pItemSSID->abySSID, param->u.wpa_associate.ssid, pItemSSID->len);
+	// set bssid
+    if (memcmp(param->u.wpa_associate.bssid, &abyNullAddr[0], 6) != 0)
+        memcpy(pMgmt->abyDesireBSSID, param->u.wpa_associate.bssid, 6);
+else
+{
+   bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, pItemSSID->abySSID);
+}
+
+    if (param->u.wpa_associate.wpa_ie_len == 0) {
+	    if (param->u.wpa_associate.auth_alg & AUTH_ALG_SHARED_KEY)
+            pMgmt->eAuthenMode = WMAC_AUTH_SHAREKEY;
+	    else
+            pMgmt->eAuthenMode = WMAC_AUTH_OPEN;
+	} else if (abyWPAIE[0] == RSN_INFO_ELEM) {
+		if (param->u.wpa_associate.key_mgmt_suite == KEY_MGMT_PSK)
+			pMgmt->eAuthenMode = WMAC_AUTH_WPA2PSK;
+		else
+			pMgmt->eAuthenMode = WMAC_AUTH_WPA2;
+	} else {
+		if (param->u.wpa_associate.key_mgmt_suite == KEY_MGMT_WPA_NONE)
+			pMgmt->eAuthenMode = WMAC_AUTH_WPANONE;
+		else if (param->u.wpa_associate.key_mgmt_suite == KEY_MGMT_PSK)
+		    pMgmt->eAuthenMode = WMAC_AUTH_WPAPSK;
+		else
+		    pMgmt->eAuthenMode = WMAC_AUTH_WPA;
+	}
+
+	switch (param->u.wpa_associate.pairwise_suite) {
+	case CIPHER_CCMP:
+		pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;
+		break;
+	case CIPHER_TKIP:
+		pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;
+		break;
+	case CIPHER_WEP40:
+	case CIPHER_WEP104:
+		pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
+		bWepEnabled=TRUE;
+		break;
+	case CIPHER_NONE:
+		if (param->u.wpa_associate.group_suite == CIPHER_CCMP)
+			pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;
+		else
+			pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;
+		break;
+	default:
+		pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
+	};
+
+//DavidWang add for WPA_supplicant support open/share mode
+
+      if (pMgmt->eAuthenMode == WMAC_AUTH_SHAREKEY) {
+            pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
+            //pMgmt->eAuthenMode = WMAC_AUTH_SHAREKEY;
+            pMgmt->bShareKeyAlgorithm = TRUE;
+             }
+     else if (pMgmt->eAuthenMode == WMAC_AUTH_OPEN) {
+          if(!bWepEnabled)  pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
+	else pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
+            //pMgmt->eAuthenMode = WMAC_AUTH_OPEN;
+            //pMgmt->bShareKeyAlgorithm = FALSE; //20080717-06,<Modify> by chester//Fix Open mode, WEP encrytion
+           }
+//mike save old encryption status
+	pDevice->eOldEncryptionStatus = pDevice->eEncryptionStatus;
+
+    if (pDevice->eEncryptionStatus !=  Ndis802_11EncryptionDisabled)
+        pDevice->bEncryptionEnable = TRUE;
+    else
+        pDevice->bEncryptionEnable = FALSE;
+if (!((pMgmt->eAuthenMode == WMAC_AUTH_SHAREKEY) ||
+      ((pMgmt->eAuthenMode == WMAC_AUTH_OPEN) && (bWepEnabled==TRUE))) )  //DavidWang  //20080717-06,<Modify> by chester//Not to initial WEP
+    KeyvInitTable(&pDevice->sKey, pDevice->PortOffset);
+    spin_lock_irq(&pDevice->lock);
+    pDevice->bLinkPass = FALSE;
+    memset(pMgmt->abyCurrBSSID, 0, 6);
+    pMgmt->eCurrState = WMAC_STATE_IDLE;
+    netif_stop_queue(pDevice->dev);
+	//20080701-02,<Add> by Mike Liu
+/*******search if ap_scan=2 ,which is associating request in hidden ssid mode ****/
+{
+   PKnownBSS       pCurr = NULL;
+    pCurr = BSSpSearchBSSList(pDevice,
+                              pMgmt->abyDesireBSSID,
+                              pMgmt->abyDesireSSID,
+                              pMgmt->eConfigPHYMode
+                              );
+
+    if (pCurr == NULL){
+    printk("wpa_set_associate---->hidden mode site survey before associate.......\n");
+    bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, pMgmt->abyDesireSSID);
+  };
+}
+/****************************************************************/
+    bScheduleCommand((HANDLE) pDevice, WLAN_CMD_SSID, NULL);
+    spin_unlock_irq(&pDevice->lock);
+
+    return ret;
+}
+
+
+/*
+ * Description:
+ *      wpa_ioctl main function supported for wpa supplicant
+ *
+ * Parameters:
+ *  In:
+ *      pDevice   -
+ *      iw_point  -
+ *  Out:
+ *
+ * Return Value:
+ *
+ */
+
+int wpa_ioctl(PSDevice pDevice, struct iw_point *p)
+{
+	struct viawget_wpa_param *param;
+	int ret = 0;
+	int wpa_ioctl = 0;
+
+	if (p->length < sizeof(struct viawget_wpa_param) ||
+	    p->length > VIAWGET_WPA_MAX_BUF_SIZE || !p->pointer)
+		return -EINVAL;
+
+	param = (struct viawget_wpa_param *) kmalloc((int)p->length, (int)GFP_KERNEL);
+	if (param == NULL)
+		return -ENOMEM;
+
+	if (copy_from_user(param, p->pointer, p->length)) {
+		ret = -EFAULT;
+		goto out;
+	}
+
+	switch (param->cmd) {
+	case VIAWGET_SET_WPA:
+        ret = wpa_set_wpa(pDevice, param);
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_WPA \n");
+		break;
+
+	case VIAWGET_SET_KEY:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_KEY \n");
+	    spin_lock_irq(&pDevice->lock);
+        ret = wpa_set_keys(pDevice, param, FALSE);
+        spin_unlock_irq(&pDevice->lock);
+		break;
+
+	case VIAWGET_SET_SCAN:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_SCAN \n");
+        ret = wpa_set_scan(pDevice, param);
+		break;
+
+	case VIAWGET_GET_SCAN:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_GET_SCAN\n");
+        ret = wpa_get_scan(pDevice, param);
+		wpa_ioctl = 1;
+		break;
+
+	case VIAWGET_GET_SSID:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_GET_SSID \n");
+        ret = wpa_get_ssid(pDevice, param);
+		wpa_ioctl = 1;
+		break;
+
+	case VIAWGET_GET_BSSID:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_GET_BSSID \n");
+        ret = wpa_get_bssid(pDevice, param);
+		wpa_ioctl = 1;
+		break;
+
+	case VIAWGET_SET_ASSOCIATE:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_ASSOCIATE \n");
+        ret = wpa_set_associate(pDevice, param);
+		break;
+
+	case VIAWGET_SET_DISASSOCIATE:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_DISASSOCIATE \n");
+        ret = wpa_set_disassociate(pDevice, param);
+		break;
+
+	case VIAWGET_SET_DROP_UNENCRYPT:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_DROP_UNENCRYPT \n");
+		break;
+
+    case VIAWGET_SET_DEAUTHENTICATE:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "VIAWGET_SET_DEAUTHENTICATE \n");
+		break;
+
+	default:
+	    DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wpa_ioctl: unknown cmd=%d\n",
+		       param->cmd);
+		return -EOPNOTSUPP;
+		break;
+	}
+
+	if ((ret == 0) && wpa_ioctl) {
+		if (copy_to_user(p->pointer, param, p->length)) {
+			ret = -EFAULT;
+			goto out;
+		}
+	}
+
+out:
+	if (param != NULL)
+		kfree(param);
+
+	return ret;
+}
+
diff --git a/drivers/staging/vt6655/wpactl.h b/drivers/staging/vt6655/wpactl.h
new file mode 100644
index 0000000..9e78897
--- /dev/null
+++ b/drivers/staging/vt6655/wpactl.h
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: wpactl.h
+ *
+ * Purpose:
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: March 1, 2005
+ *
+ */
+
+
+#ifndef __WPACTL_H__
+#define __WPACTL_H__
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
+#if !defined(__IOWPA_H__)
+#include "iowpa.h"
+#endif
+#endif
+
+/*---------------------  Export Definitions -------------------------*/
+
+
+//WPA related
+
+typedef enum { WPA_ALG_NONE, WPA_ALG_WEP, WPA_ALG_TKIP, WPA_ALG_CCMP } wpa_alg;
+typedef enum { CIPHER_NONE, CIPHER_WEP40, CIPHER_TKIP, CIPHER_CCMP,
+	       CIPHER_WEP104 } wpa_cipher;
+typedef enum { KEY_MGMT_802_1X, KEY_MGMT_CCKM,KEY_MGMT_PSK, KEY_MGMT_NONE,
+	       KEY_MGMT_802_1X_NO_WPA, KEY_MGMT_WPA_NONE } wpa_key_mgmt;
+
+#define AUTH_ALG_OPEN_SYSTEM	0x01
+#define AUTH_ALG_SHARED_KEY	0x02
+#define AUTH_ALG_LEAP		0x04
+
+#define GENERIC_INFO_ELEM 0xdd
+#define RSN_INFO_ELEM 0x30
+
+
+
+typedef ULONGLONG   NDIS_802_11_KEY_RSC;
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+int wpa_set_wpadev(PSDevice pDevice, int val);
+int wpa_ioctl(PSDevice pDevice, struct iw_point *p);
+int wpa_set_keys(PSDevice pDevice, void *ctx, BOOL  fcpfkernel);
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+
+#endif // __WPACL_H__
+
+
+
diff --git a/drivers/staging/vt6655/wroute.c b/drivers/staging/vt6655/wroute.c
new file mode 100644
index 0000000..219ae21
--- /dev/null
+++ b/drivers/staging/vt6655/wroute.c
@@ -0,0 +1,211 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: wroute.c
+ *
+ * Purpose: handle WMAC frame relay & filterring
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 20, 2003
+ *
+ * Functions:
+ *      ROUTEbRelay - Relay packet
+ *
+ * Revision History:
+ *
+ */
+
+
+#if !defined(__MAC_H__)
+#include "mac.h"
+#endif
+#if !defined(__TCRC_H__)
+#include "tcrc.h"
+#endif
+#if !defined(__RXTX_H__)
+#include "rxtx.h"
+#endif
+#if !defined(__WROUTE_H__)
+#include "wroute.h"
+#endif
+#if !defined(__CARD_H__)
+#include "card.h"
+#endif
+#if !defined(__BASEBAND_H__)
+#include "baseband.h"
+#endif
+/*---------------------  Static Definitions -------------------------*/
+
+/*---------------------  Static Classes  ----------------------------*/
+
+/*---------------------  Static Variables  --------------------------*/
+static int          msglevel                =MSG_LEVEL_INFO;
+//static int          msglevel                =MSG_LEVEL_DEBUG;
+/*---------------------  Static Functions  --------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+
+
+/*
+ * Description:
+ *      Relay packet.  Return TRUE if packet is copy to DMA1
+ *
+ * Parameters:
+ *  In:
+ *      pDevice             -
+ *      pbySkbData          - rx packet skb data
+ *  Out:
+ *      TURE, FALSE
+ *
+ * Return Value: TRUE if packet duplicate; otherwise FALSE
+ *
+ */
+BOOL ROUTEbRelay (PSDevice pDevice, PBYTE pbySkbData, UINT uDataLen, UINT uNodeIndex)
+{
+    PSMgmtObject    pMgmt = pDevice->pMgmt;
+    PSTxDesc        pHeadTD, pLastTD;
+    UINT            cbFrameBodySize;
+    UINT            uMACfragNum;
+    BYTE            byPktTyp;
+    BOOL            bNeedEncryption = FALSE;
+    SKeyItem        STempKey;
+    PSKeyItem       pTransmitKey = NULL;
+    UINT            cbHeaderSize;
+    UINT            ii;
+    PBYTE           pbyBSSID;
+
+
+
+
+    if (AVAIL_TD(pDevice, TYPE_AC0DMA)<=0) {
+        DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Relay can't allocate TD1..\n");
+        return FALSE;
+    }
+
+    pHeadTD = pDevice->apCurrTD[TYPE_AC0DMA];
+
+    pHeadTD->m_td1TD1.byTCR = (TCR_EDP|TCR_STP);
+
+    memcpy(pDevice->sTxEthHeader.abyDstAddr, (PBYTE)pbySkbData, U_HEADER_LEN);
+
+    cbFrameBodySize = uDataLen - U_HEADER_LEN;
+
+    if (ntohs(pDevice->sTxEthHeader.wType) > MAX_DATA_LEN) {
+        cbFrameBodySize += 8;
+    }
+
+    if (pDevice->bEncryptionEnable == TRUE) {
+        bNeedEncryption = TRUE;
+
+        // get group key
+        pbyBSSID = pDevice->abyBroadcastAddr;
+        if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == FALSE) {
+            pTransmitKey = NULL;
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"KEY is NULL. [%d]\n", pDevice->pMgmt->eCurrMode);
+        } else {
+            DEVICE_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Get GTK.\n");
+        }
+    }
+
+    if (pDevice->bEnableHostWEP) {
+        if (uNodeIndex >= 0) {
+            pTransmitKey = &STempKey;
+            pTransmitKey->byCipherSuite = pMgmt->sNodeDBTable[uNodeIndex].byCipherSuite;
+            pTransmitKey->dwKeyIndex = pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex;
+            pTransmitKey->uKeyLength = pMgmt->sNodeDBTable[uNodeIndex].uWepKeyLength;
+            pTransmitKey->dwTSC47_16 = pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16;
+            pTransmitKey->wTSC15_0 = pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0;
+            memcpy(pTransmitKey->abyKey,
+                &pMgmt->sNodeDBTable[uNodeIndex].abyWepKey[0],
+                pTransmitKey->uKeyLength
+                );
+        }
+    }
+
+    uMACfragNum = cbGetFragCount(pDevice, pTransmitKey, cbFrameBodySize, &pDevice->sTxEthHeader);
+
+    if (uMACfragNum > AVAIL_TD(pDevice,TYPE_AC0DMA)) {
+        return FALSE;
+    }
+    byPktTyp = (BYTE)pDevice->byPacketType;
+
+    if (pDevice->bFixRate) {
+        if (pDevice->eCurrentPHYType == PHY_TYPE_11B) {
+            if (pDevice->uConnectionRate >= RATE_11M) {
+                pDevice->wCurrentRate = RATE_11M;
+            } else {
+                pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
+            }
+        } else {
+            if ((pDevice->eCurrentPHYType == PHY_TYPE_11A) &&
+                (pDevice->uConnectionRate <= RATE_6M)) {
+                pDevice->wCurrentRate = RATE_6M;
+            } else {
+                if (pDevice->uConnectionRate >= RATE_54M)
+                    pDevice->wCurrentRate = RATE_54M;
+                else
+                    pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
+            }
+        }
+    }
+    else {
+        pDevice->wCurrentRate = pDevice->pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate;
+    }
+
+    if (pDevice->wCurrentRate <= RATE_11M)
+        byPktTyp = PK_TYPE_11B;
+
+    vGenerateFIFOHeader(pDevice, byPktTyp, pDevice->pbyTmpBuff, bNeedEncryption,
+                        cbFrameBodySize, TYPE_AC0DMA, pHeadTD,
+                        &pDevice->sTxEthHeader, pbySkbData, pTransmitKey, uNodeIndex,
+                        &uMACfragNum,
+                        &cbHeaderSize
+                        );
+
+    if (MACbIsRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PS)) {
+        // Disable PS
+        MACbPSWakeup(pDevice->PortOffset);
+    }
+
+    pDevice->bPWBitOn = FALSE;
+
+    pLastTD = pHeadTD;
+    for (ii = 0; ii < uMACfragNum; ii++) {
+        // Poll Transmit the adapter
+        wmb();
+        pHeadTD->m_td0TD0.f1Owner=OWNED_BY_NIC;
+        wmb();
+        if (ii == (uMACfragNum - 1))
+            pLastTD = pHeadTD;
+        pHeadTD = pHeadTD->next;
+    }
+
+    pLastTD->pTDInfo->skb = 0;
+    pLastTD->pTDInfo->byFlags = 0;
+
+    pDevice->apCurrTD[TYPE_AC0DMA] = pHeadTD;
+
+    MACvTransmitAC0(pDevice->PortOffset);
+
+    return TRUE;
+}
+
+
+
diff --git a/drivers/staging/vt6655/wroute.h b/drivers/staging/vt6655/wroute.h
new file mode 100644
index 0000000..ea5f589
--- /dev/null
+++ b/drivers/staging/vt6655/wroute.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * File: wroute.h
+ *
+ * Purpose:
+ *
+ * Author: Lyndon Chen
+ *
+ * Date: May 21, 2003
+ *
+ */
+
+
+#ifndef __WROUTE_H__
+#define __WROUTE_H__
+
+
+#if !defined(__DEVICE_H__)
+#include "device.h"
+#endif
+
+
+
+/*---------------------  Export Definitions -------------------------*/
+
+/*---------------------  Export Classes  ----------------------------*/
+
+/*---------------------  Export Variables  --------------------------*/
+
+/*---------------------  Export Functions  --------------------------*/
+
+
+#ifdef __cplusplus
+extern "C" {                            /* Assume C declarations for C++ */
+#endif /* __cplusplus */
+
+BOOL ROUTEbRelay (PSDevice pDevice, PBYTE pbySkbData, UINT uDataLen, UINT uNodeIndex);
+
+#ifdef __cplusplus
+}                                       /* End of extern "C" { */
+#endif /* __cplusplus */
+
+
+
+
+#endif // __WROUTE_H__
+
+
+
diff --git a/drivers/staging/winbond/Makefile b/drivers/staging/winbond/Makefile
index b49c973..fb2b7d4 100644
--- a/drivers/staging/winbond/Makefile
+++ b/drivers/staging/winbond/Makefile
@@ -7,7 +7,6 @@
 	wb35reg.o		\
 	wb35rx.o		\
 	wb35tx.o		\
-	wbhal.o			\
 	wbusb.o			\
 
 
diff --git a/drivers/staging/winbond/mds.c b/drivers/staging/winbond/mds.c
index c7af092..59d6d67 100644
--- a/drivers/staging/winbond/mds.c
+++ b/drivers/staging/winbond/mds.c
@@ -432,7 +432,7 @@
 		return;
 
 	//Only one thread can be run here
-	if (!atomic_inc_return(&pMds->TxThreadCount) == 1)
+	if (atomic_inc_return(&pMds->TxThreadCount) != 1)
 		goto cleanup;
 
 	// Start to fill the data
diff --git a/drivers/staging/winbond/mto.c b/drivers/staging/winbond/mto.c
index 94a060b..7deb5c7 100644
--- a/drivers/staging/winbond/mto.c
+++ b/drivers/staging/winbond/mto.c
@@ -175,7 +175,7 @@
 	}
 	else	//follow the setting from EEPROM
 		MTOPARA_TXPOWER_INDEX() = MTO_TXPOWER_FROM_EEPROM;
-	hal_set_rf_power(MTO_HAL(), (u8)MTOPARA_TXPOWER_INDEX());
+	RFSynthesizer_SetPowerIndex(MTO_HAL(), (u8)MTOPARA_TXPOWER_INDEX());
 	//------------------------------------------------
 
 	// For RSSI turning 20060808.4 Cancel load from EEPROM
diff --git a/drivers/staging/winbond/phy_calibration.c b/drivers/staging/winbond/phy_calibration.c
index af8c01e..8c56962 100644
--- a/drivers/staging/winbond/phy_calibration.c
+++ b/drivers/staging/winbond/phy_calibration.c
@@ -340,6 +340,25 @@
     }
 }
 
+static unsigned char hal_get_dxx_reg(struct hw_data *pHwData, u16 number, u32 * pValue)
+{
+	if (number < 0x1000)
+		number += 0x1000;
+	return Wb35Reg_ReadSync(pHwData, number, pValue);
+}
+#define hw_get_dxx_reg( _A, _B, _C ) hal_get_dxx_reg( _A, _B, (u32 *)_C )
+
+static unsigned char hal_set_dxx_reg(struct hw_data *pHwData, u16 number, u32 value)
+{
+	unsigned char ret;
+
+	if (number < 0x1000)
+		number += 0x1000;
+	ret = Wb35Reg_WriteSync(pHwData, number, value);
+	return ret;
+}
+#define hw_set_dxx_reg( _A, _B, _C ) hal_set_dxx_reg( _A, _B, (u32)_C )
+
 
 void _reset_rx_cal(struct hw_data *phw_data)
 {
diff --git a/drivers/staging/winbond/wbhal.c b/drivers/staging/winbond/wbhal.c
deleted file mode 100644
index c985ad0..0000000
--- a/drivers/staging/winbond/wbhal.c
+++ /dev/null
@@ -1,568 +0,0 @@
-#include "sysdef.h"
-#include "wbhal_f.h"
-#include "wblinux_f.h"
-
-void hal_set_ethernet_address( struct hw_data * pHwData, u8 *current_address )
-{
-	u32 ltmp[2];
-
-	if( pHwData->SurpriseRemove ) return;
-
-	memcpy( pHwData->CurrentMacAddress, current_address, ETH_ALEN );
-
-	ltmp[0]= cpu_to_le32( *(u32 *)pHwData->CurrentMacAddress );
-	ltmp[1]= cpu_to_le32( *(u32 *)(pHwData->CurrentMacAddress + 4) ) & 0xffff;
-
-	Wb35Reg_BurstWrite( pHwData, 0x03e8, ltmp, 2, AUTO_INCREMENT );
-}
-
-void hal_get_permanent_address( struct hw_data * pHwData, u8 *pethernet_address )
-{
-	if( pHwData->SurpriseRemove ) return;
-
-	memcpy( pethernet_address, pHwData->PermanentMacAddress, 6 );
-}
-
-static void hal_led_control(unsigned long data)
-{
-	struct wbsoft_priv *adapter = (struct wbsoft_priv *) data;
-	struct hw_data * pHwData = &adapter->sHwData;
-	struct wb35_reg *reg = &pHwData->reg;
-	u32	LEDSet = (pHwData->SoftwareSet & HAL_LED_SET_MASK) >> HAL_LED_SET_SHIFT;
-	u8	LEDgray[20] = { 0,3,4,6,8,10,11,12,13,14,15,14,13,12,11,10,8,6,4,2 };
-	u8	LEDgray2[30] = { 7,8,9,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,0,0,0,0,15,14,13,12,11,10,9,8 };
-	u32	TimeInterval = 500, ltmp, ltmp2;
-        ltmp=0;
-
-	if( pHwData->SurpriseRemove ) return;
-
-	if( pHwData->LED_control ) {
-		ltmp2 = pHwData->LED_control & 0xff;
-		if( ltmp2 == 5 ) // 5 is WPS mode
-		{
-			TimeInterval = 100;
-			ltmp2 = (pHwData->LED_control>>8) & 0xff;
-			switch( ltmp2 )
-			{
-				case 1: // [0.2 On][0.1 Off]...
-					pHwData->LED_Blinking %= 3;
-					ltmp = 0x1010; // Led 1 & 0 Green and Red
-					if( pHwData->LED_Blinking == 2 ) // Turn off
-						ltmp = 0;
-					break;
-				case 2: // [0.1 On][0.1 Off]...
-					pHwData->LED_Blinking %= 2;
-					ltmp = 0x0010; // Led 0 red color
-					if( pHwData->LED_Blinking ) // Turn off
-						ltmp = 0;
-					break;
-				case 3: // [0.1 On][0.1 Off][0.1 On][0.1 Off][0.1 On][0.1 Off][0.1 On][0.1 Off][0.1 On][0.1 Off][0.5 Off]...
-					pHwData->LED_Blinking %= 15;
-					ltmp = 0x0010; // Led 0 red color
-					if( (pHwData->LED_Blinking >= 9) || (pHwData->LED_Blinking%2) ) // Turn off 0.6 sec
-						ltmp = 0;
-					break;
-				case 4: // [300 On][ off ]
-					ltmp = 0x1000; // Led 1 Green color
-					if( pHwData->LED_Blinking >= 3000 )
-						ltmp = 0; // led maybe on after 300sec * 32bit counter overlap.
-					break;
-			}
-			pHwData->LED_Blinking++;
-
-			reg->U1BC_LEDConfigure = ltmp;
-			if( LEDSet != 7 ) // Only 111 mode has 2 LEDs on PCB.
-			{
-				reg->U1BC_LEDConfigure |= (ltmp &0xff)<<8; // Copy LED result to each LED control register
-				reg->U1BC_LEDConfigure |= (ltmp &0xff00)>>8;
-			}
-			Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure );
-		}
-	}
-	else if( pHwData->CurrentRadioSw || pHwData->CurrentRadioHw ) // If radio off
-	{
-		if( reg->U1BC_LEDConfigure & 0x1010 )
-		{
-			reg->U1BC_LEDConfigure &= ~0x1010;
-			Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure );
-		}
-	}
-	else
-	{
-		switch( LEDSet )
-		{
-			case 4: // [100] Only 1 Led be placed on PCB and use pin 21 of IC. Use LED_0 for showing
-				if( !pHwData->LED_LinkOn ) // Blink only if not Link On
-				{
-					// Blinking if scanning is on progress
-					if( pHwData->LED_Scanning )
-					{
-						if( pHwData->LED_Blinking == 0 )
-						{
-							reg->U1BC_LEDConfigure |= 0x10;
-							Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_0 On
-							pHwData->LED_Blinking = 1;
-							TimeInterval = 300;
-						}
-						else
-						{
-							reg->U1BC_LEDConfigure &= ~0x10;
-							Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_0 Off
-							pHwData->LED_Blinking = 0;
-							TimeInterval = 300;
-						}
-					}
-					else
-					{
-						//Turn Off LED_0
-						if( reg->U1BC_LEDConfigure & 0x10 )
-						{
-							reg->U1BC_LEDConfigure &= ~0x10;
-							Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_0 Off
-						}
-					}
-				}
-				else
-				{
-					// Turn On LED_0
-					if( (reg->U1BC_LEDConfigure & 0x10) == 0 )
-					{
-						reg->U1BC_LEDConfigure |= 0x10;
-						Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_0 Off
-					}
-				}
-				break;
-
-			case 6: // [110] Only 1 Led be placed on PCB and use pin 21 of IC. Use LED_0 for showing
-				if( !pHwData->LED_LinkOn ) // Blink only if not Link On
-				{
-					// Blinking if scanning is on progress
-					if( pHwData->LED_Scanning )
-					{
-						if( pHwData->LED_Blinking == 0 )
-						{
-							reg->U1BC_LEDConfigure &= ~0xf;
-							reg->U1BC_LEDConfigure |= 0x10;
-							Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_0 On
-							pHwData->LED_Blinking = 1;
-							TimeInterval = 300;
-						}
-						else
-						{
-							reg->U1BC_LEDConfigure &= ~0x1f;
-							Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_0 Off
-							pHwData->LED_Blinking = 0;
-							TimeInterval = 300;
-						}
-					}
-					else
-					{
-						// 20060901 Gray blinking if in disconnect state and not scanning
-						ltmp = reg->U1BC_LEDConfigure;
-						reg->U1BC_LEDConfigure &= ~0x1f;
-						if( LEDgray2[(pHwData->LED_Blinking%30)] )
-						{
-							reg->U1BC_LEDConfigure |= 0x10;
-							reg->U1BC_LEDConfigure |= LEDgray2[ (pHwData->LED_Blinking%30) ];
-						}
-						pHwData->LED_Blinking++;
-						if( reg->U1BC_LEDConfigure != ltmp )
-							Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_0 Off
-						TimeInterval = 100;
-					}
-				}
-				else
-				{
-					// Turn On LED_0
-					if( (reg->U1BC_LEDConfigure & 0x10) == 0 )
-					{
-						reg->U1BC_LEDConfigure |= 0x10;
-						Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_0 Off
-					}
-				}
-				break;
-
-			case 5: // [101] Only 1 Led be placed on PCB and use LED_1 for showing
-				if( !pHwData->LED_LinkOn ) // Blink only if not Link On
-				{
-					// Blinking if scanning is on progress
-					if( pHwData->LED_Scanning )
-					{
-						if( pHwData->LED_Blinking == 0 )
-						{
-							reg->U1BC_LEDConfigure |= 0x1000;
-							Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_1 On
-							pHwData->LED_Blinking = 1;
-							TimeInterval = 300;
-						}
-						else
-						{
-							reg->U1BC_LEDConfigure &= ~0x1000;
-							Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_1 Off
-							pHwData->LED_Blinking = 0;
-							TimeInterval = 300;
-						}
-					}
-					else
-					{
-						//Turn Off LED_1
-						if( reg->U1BC_LEDConfigure & 0x1000 )
-						{
-							reg->U1BC_LEDConfigure &= ~0x1000;
-							Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_1 Off
-						}
-					}
-				}
-				else
-				{
-					// Is transmitting/receiving ??
-					if( (adapter->RxByteCount != pHwData->RxByteCountLast ) ||
-						(adapter->TxByteCount != pHwData->TxByteCountLast ) )
-					{
-						if( (reg->U1BC_LEDConfigure & 0x3000) != 0x3000 )
-						{
-							reg->U1BC_LEDConfigure |= 0x3000;
-							Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_1 On
-						}
-
-						// Update variable
-						pHwData->RxByteCountLast = adapter->RxByteCount;
-						pHwData->TxByteCountLast = adapter->TxByteCount;
-						TimeInterval = 200;
-					}
-					else
-					{
-						// Turn On LED_1 and blinking if transmitting/receiving
-						 if( (reg->U1BC_LEDConfigure & 0x3000) != 0x1000 )
-						 {
-							 reg->U1BC_LEDConfigure &= ~0x3000;
-							 reg->U1BC_LEDConfigure |= 0x1000;
-							 Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure ); // LED_1 On
-						 }
-					}
-				}
-				break;
-
-			default: // Default setting. 2 LED be placed on PCB. LED_0: Link On LED_1 Active
-				if( (reg->U1BC_LEDConfigure & 0x3000) != 0x3000 )
-				{
-					reg->U1BC_LEDConfigure |= 0x3000;// LED_1 is always on and event enable
-					Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure );
-				}
-
-				if( pHwData->LED_Blinking )
-				{
-					// Gray blinking
-					reg->U1BC_LEDConfigure &= ~0x0f;
-					reg->U1BC_LEDConfigure |= 0x10;
-					reg->U1BC_LEDConfigure |= LEDgray[ (pHwData->LED_Blinking-1)%20 ];
-					Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure );
-
-					pHwData->LED_Blinking += 2;
-					if( pHwData->LED_Blinking < 40 )
-						TimeInterval = 100;
-					else
-					{
-						pHwData->LED_Blinking = 0; // Stop blinking
-						reg->U1BC_LEDConfigure &= ~0x0f;
-						Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure );
-					}
-					break;
-				}
-
-				if( pHwData->LED_LinkOn )
-				{
-					if( !(reg->U1BC_LEDConfigure & 0x10) ) // Check the LED_0
-					{
-						//Try to turn ON LED_0 after gray blinking
-						reg->U1BC_LEDConfigure |= 0x10;
-						pHwData->LED_Blinking = 1; //Start blinking
-						TimeInterval = 50;
-					}
-				}
-				else
-				{
-					if( reg->U1BC_LEDConfigure & 0x10 ) // Check the LED_0
-					{
-						reg->U1BC_LEDConfigure &= ~0x10;
-						Wb35Reg_Write( pHwData, 0x03bc, reg->U1BC_LEDConfigure );
-					}
-				}
-				break;
-		}
-
-		//20060828.1 Active send null packet to avoid AP disconnect
-		if( pHwData->LED_LinkOn )
-		{
-			pHwData->NullPacketCount += TimeInterval;
-			if( pHwData->NullPacketCount >= DEFAULT_NULL_PACKET_COUNT )
-			{
-				pHwData->NullPacketCount = 0;
-			}
-		}
-	}
-
-	pHwData->time_count += TimeInterval;
-	Wb35Tx_CurrentTime(adapter, pHwData->time_count); // 20060928 add
-	pHwData->LEDTimer.expires = jiffies + msecs_to_jiffies(TimeInterval);
-	add_timer(&pHwData->LEDTimer);
-}
-
-u8 hal_init_hardware(struct ieee80211_hw *hw)
-{
-	struct wbsoft_priv *priv = hw->priv;
-	struct hw_data * pHwData = &priv->sHwData;
-	u16 SoftwareSet;
-
-	// Initial the variable
-	pHwData->MaxReceiveLifeTime = DEFAULT_MSDU_LIFE_TIME; // Setting Rx maximum MSDU life time
-	pHwData->FragmentThreshold = DEFAULT_FRAGMENT_THRESHOLD; // Setting default fragment threshold
-
-	pHwData->InitialResource = 1;
-	if( Wb35Reg_initial(pHwData)) {
-		pHwData->InitialResource = 2;
-		if (Wb35Tx_initial(pHwData)) {
-			pHwData->InitialResource = 3;
-			if (Wb35Rx_initial(pHwData)) {
-				pHwData->InitialResource = 4;
-				init_timer(&pHwData->LEDTimer);
-				pHwData->LEDTimer.function = hal_led_control;
-				pHwData->LEDTimer.data = (unsigned long) priv;
-				pHwData->LEDTimer.expires = jiffies + msecs_to_jiffies(1000);
-				add_timer(&pHwData->LEDTimer);
-
-				//
-				// For restrict to vendor's hardware
-				//
-				SoftwareSet = hal_software_set( pHwData );
-
-				#ifdef Vendor2
-				// Try to make sure the EEPROM contain
-				SoftwareSet >>= 8;
-				if( SoftwareSet != 0x82 )
-					return false;
-				#endif
-
-				Wb35Rx_start(hw);
-				Wb35Tx_EP2VM_start(priv);
-
-				return true;
-			}
-		}
-	}
-
-	pHwData->SurpriseRemove = 1;
-	return false;
-}
-
-
-void hal_halt(struct hw_data * pHwData, void *ppa_data)
-{
-	switch( pHwData->InitialResource )
-	{
-		case 4:
-		case 3: del_timer_sync(&pHwData->LEDTimer);
-			msleep(100); // Wait for Timer DPC exit 940623.2
-			Wb35Rx_destroy( pHwData ); // Release the Rx
-		case 2: Wb35Tx_destroy( pHwData ); // Release the Tx
-		case 1: Wb35Reg_destroy( pHwData ); // Release the Wb35 Regisster resources
-	}
-}
-
-//---------------------------------------------------------------------------------------------------
-void hal_set_beacon_period(  struct hw_data * pHwData,  u16 beacon_period )
-{
-	u32	tmp;
-
-	if( pHwData->SurpriseRemove ) return;
-
-	pHwData->BeaconPeriod = beacon_period;
-	tmp = pHwData->BeaconPeriod << 16;
-	tmp |= pHwData->ProbeDelay;
-	Wb35Reg_Write( pHwData, 0x0848, tmp );
-}
-
-
-static void hal_set_current_channel_ex(  struct hw_data * pHwData,  ChanInfo channel )
-{
-	struct wb35_reg *reg = &pHwData->reg;
-
-	if( pHwData->SurpriseRemove )
-		return;
-
-	printk("Going to channel: %d/%d\n", channel.band, channel.ChanNo);
-
-	RFSynthesizer_SwitchingChannel( pHwData, channel );// Switch channel
-	pHwData->Channel = channel.ChanNo;
-	pHwData->band = channel.band;
-	#ifdef _PE_STATE_DUMP_
-	printk("Set channel is %d, band =%d\n", pHwData->Channel, pHwData->band);
-	#endif
-	reg->M28_MacControl &= ~0xff; // Clean channel information field
-	reg->M28_MacControl |= channel.ChanNo;
-	Wb35Reg_WriteWithCallbackValue( pHwData, 0x0828, reg->M28_MacControl,
-					(s8 *)&channel, sizeof(ChanInfo));
-}
-//---------------------------------------------------------------------------------------------------
-void hal_set_current_channel(  struct hw_data * pHwData,  ChanInfo channel )
-{
-	hal_set_current_channel_ex( pHwData, channel );
-}
-//---------------------------------------------------------------------------------------------------
-void hal_set_accept_broadcast(  struct hw_data * pHwData,  u8 enable )
-{
-	struct wb35_reg *reg = &pHwData->reg;
-
-	if( pHwData->SurpriseRemove ) return;
-
-	reg->M00_MacControl &= ~0x02000000;//The HW value
-
-	if (enable)
-		reg->M00_MacControl |= 0x02000000;//The HW value
-
-	Wb35Reg_Write( pHwData, 0x0800, reg->M00_MacControl );
-}
-
-//for wep key error detection, we need to accept broadcast packets to be received temporary.
-void hal_set_accept_promiscuous( struct hw_data * pHwData,  u8 enable)
-{
-	struct wb35_reg *reg = &pHwData->reg;
-
-	if (pHwData->SurpriseRemove) return;
-	if (enable) {
-		reg->M00_MacControl |= 0x00400000;
-		Wb35Reg_Write( pHwData, 0x0800, reg->M00_MacControl );
-	} else {
-		reg->M00_MacControl&=~0x00400000;
-		Wb35Reg_Write( pHwData, 0x0800, reg->M00_MacControl );
-	}
-}
-
-void hal_set_accept_multicast(  struct hw_data * pHwData,  u8 enable )
-{
-	struct wb35_reg *reg = &pHwData->reg;
-
-	if( pHwData->SurpriseRemove ) return;
-
-	reg->M00_MacControl &= ~0x01000000;//The HW value
-	if (enable)  reg->M00_MacControl |= 0x01000000;//The HW value
-	Wb35Reg_Write( pHwData, 0x0800, reg->M00_MacControl );
-}
-
-void hal_set_accept_beacon(  struct hw_data * pHwData,  u8 enable )
-{
-	struct wb35_reg *reg = &pHwData->reg;
-
-	if( pHwData->SurpriseRemove ) return;
-
-	// 20040108 debug
-	if( !enable )//Due to SME and MLME are not suitable for 35
-		return;
-
-	reg->M00_MacControl &= ~0x04000000;//The HW value
-	if( enable )
-		reg->M00_MacControl |= 0x04000000;//The HW value
-
-	Wb35Reg_Write( pHwData, 0x0800, reg->M00_MacControl );
-}
-//---------------------------------------------------------------------------------------------------
-
-void hal_stop(  struct hw_data * pHwData )
-{
-	struct wb35_reg *reg = &pHwData->reg;
-
-	pHwData->Wb35Rx.rx_halt = 1;
-	Wb35Rx_stop( pHwData );
-
-	pHwData->Wb35Tx.tx_halt = 1;
-	Wb35Tx_stop( pHwData );
-
-	reg->D00_DmaControl &= ~0xc0000000;//Tx Off, Rx Off
-	Wb35Reg_Write( pHwData, 0x0400, reg->D00_DmaControl );
-}
-
-unsigned char hal_idle(struct hw_data * pHwData)
-{
-	struct wb35_reg *reg = &pHwData->reg;
-	struct wb_usb *pWbUsb = &pHwData->WbUsb;
-
-	if( !pHwData->SurpriseRemove && ( pWbUsb->DetectCount || reg->EP0vm_state!=VM_STOP ) )
-		return false;
-
-	return true;
-}
-//---------------------------------------------------------------------------------------------------
-void hal_set_phy_type(  struct hw_data * pHwData,  u8 PhyType )
-{
-	pHwData->phy_type = PhyType;
-}
-
-void hal_set_radio_mode( struct hw_data * pHwData,  unsigned char radio_off)
-{
-	struct wb35_reg *reg = &pHwData->reg;
-
-	if( pHwData->SurpriseRemove ) return;
-
-	if (radio_off)	//disable Baseband receive off
-	{
-		pHwData->CurrentRadioSw = 1; // off
-		reg->M24_MacControl &= 0xffffffbf;
-	}
-	else
-	{
-		pHwData->CurrentRadioSw = 0; // on
-		reg->M24_MacControl |= 0x00000040;
-	}
-	Wb35Reg_Write( pHwData, 0x0824, reg->M24_MacControl );
-}
-
-u8 hal_get_antenna_number(  struct hw_data * pHwData )
-{
-	struct wb35_reg *reg = &pHwData->reg;
-
-	if ((reg->BB2C & BIT(11)) == 0)
-		return 0;
-	else
-		return 1;
-}
-
-//----------------------------------------------------------------------------------------------------
-//0 : radio on; 1: radio off
-u8 hal_get_hw_radio_off(  struct hw_data * pHwData )
-{
-	struct wb35_reg *reg = &pHwData->reg;
-
-	if( pHwData->SurpriseRemove ) return 1;
-
-	//read the bit16 of register U1B0
-	Wb35Reg_Read( pHwData, 0x3b0, &reg->U1B0 );
-	if ((reg->U1B0 & 0x00010000)) {
-		pHwData->CurrentRadioHw = 1;
-		return 1;
-	} else {
-		pHwData->CurrentRadioHw = 0;
-		return 0;
-	}
-}
-
-unsigned char hal_get_dxx_reg(  struct hw_data * pHwData,  u16 number,  u32 * pValue )
-{
-	if( number < 0x1000 )
-		number += 0x1000;
-	return Wb35Reg_ReadSync( pHwData, number, pValue );
-}
-
-unsigned char hal_set_dxx_reg(  struct hw_data * pHwData,  u16 number,  u32 value )
-{
-	unsigned char	ret;
-
-	if( number < 0x1000 )
-		number += 0x1000;
-	ret = Wb35Reg_WriteSync( pHwData, number, value );
-	return ret;
-}
-
-void hal_set_rf_power(struct hw_data * pHwData, u8 PowerIndex)
-{
-	RFSynthesizer_SetPowerIndex( pHwData, PowerIndex );
-}
diff --git a/drivers/staging/winbond/wbhal_f.h b/drivers/staging/winbond/wbhal_f.h
index efcaefb..bfdf05d 100644
--- a/drivers/staging/winbond/wbhal_f.h
+++ b/drivers/staging/winbond/wbhal_f.h
@@ -18,10 +18,6 @@
 void hal_clear_all_group_key(  struct hw_data * pHwData );
 void hal_clear_all_mapping_key(  struct hw_data * pHwData );
 void hal_clear_all_key(  struct hw_data * pHwData );
-void hal_get_ethernet_address(  struct hw_data * pHwData,  u8 *current_address );
-void hal_set_ethernet_address(  struct hw_data * pHwData,  u8 *current_address );
-void hal_get_permanent_address(  struct hw_data * pHwData,  u8 *pethernet_address );
-u8 hal_init_hardware(struct ieee80211_hw *hw);
 void hal_set_power_save_mode(  struct hw_data * pHwData,  unsigned char power_save,  unsigned char wakeup,  unsigned char dtim );
 void hal_get_power_save_mode(  struct hw_data * pHwData,   u8 *pin_pwr_save );
 void hal_set_slot_time(  struct hw_data * pHwData,  u8 type );
@@ -33,33 +29,21 @@
 void hal_set_aid(  struct hw_data * pHwData,  u16 aid );
 void hal_set_bssid(  struct hw_data * pHwData,  u8 *pbssid );
 void hal_get_bssid(  struct hw_data * pHwData,  u8 *pbssid );
-void hal_set_beacon_period(  struct hw_data * pHwData,  u16 beacon_period );
 void hal_set_listen_interval(  struct hw_data * pHwData,  u16 listen_interval );
 void hal_set_cap_info(  struct hw_data * pHwData,  u16 capability_info );
 void hal_set_ssid(  struct hw_data * pHwData,  u8 *pssid,  u8 ssid_len );
-void hal_set_current_channel(  struct hw_data * pHwData,  ChanInfo channel );
-void hal_set_accept_broadcast(  struct hw_data * pHwData,  u8 enable );
-void hal_set_accept_multicast(  struct hw_data * pHwData,  u8 enable );
-void hal_set_accept_beacon(  struct hw_data * pHwData,  u8 enable );
-void hal_stop(  struct hw_data * pHwData );
-void hal_halt(  struct hw_data * pHwData, void *ppa_data );
 void hal_start_tx0(  struct hw_data * pHwData );
-void hal_set_phy_type(  struct hw_data * pHwData,  u8 PhyType );
 #define hal_get_cwmin( _A ) ( (_A)->cwmin )
 void hal_set_cwmax(  struct hw_data * pHwData,  u16 cwin_max );
 #define hal_get_cwmax( _A ) ( (_A)->cwmax )
 void hal_set_rsn_wpa(  struct hw_data * pHwData,  u32 * RSN_IE_Bitmap , u32 * RSN_OUI_type , unsigned char bDesiredAuthMode);
 void hal_set_connect_info(  struct hw_data * pHwData,  unsigned char boConnect );
 u8 hal_get_est_sq3(  struct hw_data * pHwData,  u8 Count );
-void hal_set_rf_power(  struct hw_data * pHwData,  u8 PowerIndex ); // 20060621 Modify
-void hal_set_radio_mode(  struct hw_data * pHwData,  unsigned char boValue);
 void hal_descriptor_indicate(  struct hw_data * pHwData,  PDESCRIPTOR pDes );
 u8 hal_get_antenna_number(  struct hw_data * pHwData );
 u32 hal_get_bss_pk_cnt(  struct hw_data * pHwData );
 #define hal_get_region_from_EEPROM( _A ) ( (_A)->reg.EEPROMRegion )
-void hal_set_accept_promiscuous		(  struct hw_data * pHwData,  u8 enable);
 #define hal_get_tx_buffer( _A, _B ) Wb35Tx_get_tx_buffer( _A, _B )
-u8 hal_get_hw_radio_off			(  struct hw_data * pHwData );
 #define hal_software_set( _A )		(_A->SoftwareSet)
 #define hal_driver_init_OK( _A )	(_A->IsInitOK)
 #define hal_rssi_boundary_high( _A ) (_A->RSSI_high)
@@ -68,8 +52,6 @@
 
 #define PHY_DEBUG( msg, args... )
 
-unsigned char hal_get_dxx_reg(  struct hw_data * pHwData,  u16 number,  u32 * pValue );
-unsigned char hal_set_dxx_reg(  struct hw_data * pHwData,  u16 number,  u32 value );
 #define hal_get_time_count( _P )	(_P->time_count/10)	// return 100ms count
 #define hal_detect_error( _P )		(_P->WbUsb.DetectCount)
 
@@ -82,10 +64,7 @@
 #define hal_get_clear_interrupt(_A)
 #define hal_ibss_disconnect(_A) hal_stop_sync_bss(_A)
 #define hal_join_request_stop(_A)
-unsigned char	hal_idle(  struct hw_data * pHwData );
 #define hw_get_cxx_reg( _A, _B, _C )
 #define hw_set_cxx_reg( _A, _B, _C )
-#define hw_get_dxx_reg( _A, _B, _C )	hal_get_dxx_reg( _A, _B, (u32 *)_C )
-#define hw_set_dxx_reg( _A, _B, _C )	hal_set_dxx_reg( _A, _B, (u32)_C )
 
 
diff --git a/drivers/staging/winbond/wbhal_s.h b/drivers/staging/winbond/wbhal_s.h
index acfebf0..16d0e6f 100644
--- a/drivers/staging/winbond/wbhal_s.h
+++ b/drivers/staging/winbond/wbhal_s.h
@@ -401,7 +401,6 @@
 
 	// For surprise remove
 	u32	SurpriseRemove; // 0: Normal 1: Surprise remove
-	u8	InitialResource;
 	u8	IsKeyPreSet;
 	u8	CalOneTime; // 20060630.1
 
diff --git a/drivers/staging/winbond/wbusb.c b/drivers/staging/winbond/wbusb.c
index 3b2d528..745279c 100644
--- a/drivers/staging/winbond/wbusb.c
+++ b/drivers/staging/winbond/wbusb.c
@@ -2,6 +2,12 @@
  * Copyright 2008 Pavel Machek <pavel@suse.cz>
  *
  * Distribute under GPLv2.
+ *
+ * The original driver was written by:
+ *     Jeff Lee <YY_Lee@issc.com.tw>
+ *
+ * and was adapted to the 2.6 kernel by:
+ *     Costantino Leandro (Rxart Desktop) <le_costantino@pixartargentina.com.ar>
  */
 #include <net/mac80211.h>
 #include <linux/usb.h>
@@ -13,19 +19,18 @@
 #include "wbhal_f.h"
 #include "wblinux_f.h"
 
-MODULE_AUTHOR("Original by: Jeff Lee<YY_Lee@issc.com.tw> Adapted to 2.6.x by Costantino Leandro (Rxart Desktop) <le_costantino@pixartargentina.com.ar>");
 MODULE_DESCRIPTION("IS89C35 802.11bg WLAN USB Driver");
 MODULE_LICENSE("GPL");
 MODULE_VERSION("0.1");
 
 static struct usb_device_id wb35_table[] __devinitdata = {
-	{USB_DEVICE(0x0416, 0x0035)},
-	{USB_DEVICE(0x18E8, 0x6201)},
-	{USB_DEVICE(0x18E8, 0x6206)},
-	{USB_DEVICE(0x18E8, 0x6217)},
-	{USB_DEVICE(0x18E8, 0x6230)},
-	{USB_DEVICE(0x18E8, 0x6233)},
-	{USB_DEVICE(0x1131, 0x2035)},
+	{ USB_DEVICE(0x0416, 0x0035) },
+	{ USB_DEVICE(0x18E8, 0x6201) },
+	{ USB_DEVICE(0x18E8, 0x6206) },
+	{ USB_DEVICE(0x18E8, 0x6217) },
+	{ USB_DEVICE(0x18E8, 0x6230) },
+	{ USB_DEVICE(0x18E8, 0x6233) },
+	{ USB_DEVICE(0x1131, 0x2035) },
 	{ 0, }
 };
 
@@ -36,7 +41,7 @@
 };
 
 static struct ieee80211_channel wbsoft_channels[] = {
-	{ .center_freq = 2412},
+	{ .center_freq = 2412 },
 };
 
 static struct ieee80211_supported_band wbsoft_band_2GHz = {
@@ -47,14 +52,14 @@
 };
 
 static int wbsoft_add_interface(struct ieee80211_hw *dev,
-				 struct ieee80211_if_init_conf *conf)
+				struct ieee80211_if_init_conf *conf)
 {
 	printk("wbsoft_add interface called\n");
 	return 0;
 }
 
 static void wbsoft_remove_interface(struct ieee80211_hw *dev,
-				     struct ieee80211_if_init_conf *conf)
+				    struct ieee80211_if_init_conf *conf)
 {
 	printk("wbsoft_remove interface called\n");
 }
@@ -79,36 +84,18 @@
 }
 
 static void wbsoft_configure_filter(struct ieee80211_hw *dev,
-				     unsigned int changed_flags,
-				     unsigned int *total_flags,
-				     int mc_count, struct dev_mc_list *mclist)
+				    unsigned int changed_flags,
+				    unsigned int *total_flags,
+				    int mc_count, struct dev_mc_list *mclist)
 {
-	unsigned int bit_nr, new_flags;
-	u32 mc_filter[2];
-	int i;
+	unsigned int new_flags;
 
 	new_flags = 0;
 
-	if (*total_flags & FIF_PROMISC_IN_BSS) {
+	if (*total_flags & FIF_PROMISC_IN_BSS)
 		new_flags |= FIF_PROMISC_IN_BSS;
-		mc_filter[1] = mc_filter[0] = ~0;
-	} else if ((*total_flags & FIF_ALLMULTI) || (mc_count > 32)) {
+	else if ((*total_flags & FIF_ALLMULTI) || (mc_count > 32))
 		new_flags |= FIF_ALLMULTI;
-		mc_filter[1] = mc_filter[0] = ~0;
-	} else {
-		mc_filter[1] = mc_filter[0] = 0;
-		for (i = 0; i < mc_count; i++) {
-			if (!mclist)
-				break;
-			printk("Should call ether_crc here\n");
-			//bit_nr = ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26;
-			bit_nr = 0;
-
-			bit_nr &= 0x3F;
-			mc_filter[bit_nr >> 5] |= 1 << (bit_nr & 31);
-			mclist = mclist->next;
-		}
-	}
 
 	dev->flags &= ~IEEE80211_HW_RX_INCLUDES_FCS;
 
@@ -124,7 +111,6 @@
 	return NETDEV_TX_OK;
 }
 
-
 static int wbsoft_start(struct ieee80211_hw *dev)
 {
 	struct wbsoft_priv *priv = dev->priv;
@@ -134,6 +120,127 @@
 	return 0;
 }
 
+static void hal_set_radio_mode(struct hw_data *pHwData, unsigned char radio_off)
+{
+	struct wb35_reg *reg = &pHwData->reg;
+
+	if (pHwData->SurpriseRemove)
+		return;
+
+	if (radio_off)		//disable Baseband receive off
+	{
+		pHwData->CurrentRadioSw = 1;	// off
+		reg->M24_MacControl &= 0xffffffbf;
+	} else {
+		pHwData->CurrentRadioSw = 0;	// on
+		reg->M24_MacControl |= 0x00000040;
+	}
+	Wb35Reg_Write(pHwData, 0x0824, reg->M24_MacControl);
+}
+
+static void hal_set_beacon_period(struct hw_data *pHwData, u16 beacon_period)
+{
+	u32 tmp;
+
+	if (pHwData->SurpriseRemove)
+		return;
+
+	pHwData->BeaconPeriod = beacon_period;
+	tmp = pHwData->BeaconPeriod << 16;
+	tmp |= pHwData->ProbeDelay;
+	Wb35Reg_Write(pHwData, 0x0848, tmp);
+}
+
+static void
+hal_set_current_channel_ex(struct hw_data *pHwData, ChanInfo channel)
+{
+	struct wb35_reg *reg = &pHwData->reg;
+
+	if (pHwData->SurpriseRemove)
+		return;
+
+	printk("Going to channel: %d/%d\n", channel.band, channel.ChanNo);
+
+	RFSynthesizer_SwitchingChannel(pHwData, channel);	// Switch channel
+	pHwData->Channel = channel.ChanNo;
+	pHwData->band = channel.band;
+#ifdef _PE_STATE_DUMP_
+	printk("Set channel is %d, band =%d\n", pHwData->Channel,
+	       pHwData->band);
+#endif
+	reg->M28_MacControl &= ~0xff;	// Clean channel information field
+	reg->M28_MacControl |= channel.ChanNo;
+	Wb35Reg_WriteWithCallbackValue(pHwData, 0x0828, reg->M28_MacControl,
+				       (s8 *) & channel, sizeof(ChanInfo));
+}
+
+static void hal_set_current_channel(struct hw_data *pHwData, ChanInfo channel)
+{
+	hal_set_current_channel_ex(pHwData, channel);
+}
+
+static void hal_set_accept_broadcast(struct hw_data *pHwData, u8 enable)
+{
+	struct wb35_reg *reg = &pHwData->reg;
+
+	if (pHwData->SurpriseRemove)
+		return;
+
+	reg->M00_MacControl &= ~0x02000000;	//The HW value
+
+	if (enable)
+		reg->M00_MacControl |= 0x02000000;	//The HW value
+
+	Wb35Reg_Write(pHwData, 0x0800, reg->M00_MacControl);
+}
+
+//for wep key error detection, we need to accept broadcast packets to be received temporary.
+static void hal_set_accept_promiscuous(struct hw_data *pHwData, u8 enable)
+{
+	struct wb35_reg *reg = &pHwData->reg;
+
+	if (pHwData->SurpriseRemove)
+		return;
+	if (enable) {
+		reg->M00_MacControl |= 0x00400000;
+		Wb35Reg_Write(pHwData, 0x0800, reg->M00_MacControl);
+	} else {
+		reg->M00_MacControl &= ~0x00400000;
+		Wb35Reg_Write(pHwData, 0x0800, reg->M00_MacControl);
+	}
+}
+
+static void hal_set_accept_multicast(struct hw_data *pHwData, u8 enable)
+{
+	struct wb35_reg *reg = &pHwData->reg;
+
+	if (pHwData->SurpriseRemove)
+		return;
+
+	reg->M00_MacControl &= ~0x01000000;	//The HW value
+	if (enable)
+		reg->M00_MacControl |= 0x01000000;	//The HW value
+	Wb35Reg_Write(pHwData, 0x0800, reg->M00_MacControl);
+}
+
+static void hal_set_accept_beacon(struct hw_data *pHwData, u8 enable)
+{
+	struct wb35_reg *reg = &pHwData->reg;
+
+	if (pHwData->SurpriseRemove)
+		return;
+
+	// 20040108 debug
+	if (!enable)		//Due to SME and MLME are not suitable for 35
+		return;
+
+	reg->M00_MacControl &= ~0x04000000;	//The HW value
+	if (enable)
+		reg->M00_MacControl |= 0x04000000;	//The HW value
+
+	Wb35Reg_Write(pHwData, 0x0800, reg->M00_MacControl);
+}
+
 static int wbsoft_config(struct ieee80211_hw *dev, u32 changed)
 {
 	struct wbsoft_priv *priv = dev->priv;
@@ -142,36 +249,18 @@
 
 	printk("wbsoft_config called\n");
 
+	/* Should use channel_num, or something, as that is already pre-translated */
 	ch.band = 1;
-	ch.ChanNo = 1;	/* Should use channel_num, or something, as that is already pre-translated */
-
+	ch.ChanNo = 1;
 
 	hal_set_current_channel(&priv->sHwData, ch);
 	hal_set_beacon_period(&priv->sHwData, conf->beacon_int);
-//	hal_set_cap_info(&priv->sHwData, ?? );
-// hal_set_ssid(struct hw_data * pHwData,  u8 * pssid,  u8 ssid_len); ??
 	hal_set_accept_broadcast(&priv->sHwData, 1);
-	hal_set_accept_promiscuous(&priv->sHwData,  1);
-	hal_set_accept_multicast(&priv->sHwData,  1);
-	hal_set_accept_beacon(&priv->sHwData,  1);
-	hal_set_radio_mode(&priv->sHwData,  0);
-	//hal_set_antenna_number(  struct hw_data * pHwData, u8 number )
-	//hal_set_rf_power(struct hw_data * pHwData, u8 PowerIndex)
+	hal_set_accept_promiscuous(&priv->sHwData, 1);
+	hal_set_accept_multicast(&priv->sHwData, 1);
+	hal_set_accept_beacon(&priv->sHwData, 1);
+	hal_set_radio_mode(&priv->sHwData, 0);
 
-
-//	hal_start_bss(&priv->sHwData, WLAN_BSSTYPE_INFRASTRUCTURE);	??
-
-//void hal_set_rates(struct hw_data * pHwData, u8 * pbss_rates,
-//		   u8 length, unsigned char basic_rate_set)
-
-	return 0;
-}
-
-static int wbsoft_config_interface(struct ieee80211_hw *dev,
-				    struct ieee80211_vif *vif,
-				    struct ieee80211_if_conf *conf)
-{
-	printk("wbsoft_config_interface called\n");
 	return 0;
 }
 
@@ -183,63 +272,448 @@
 
 static const struct ieee80211_ops wbsoft_ops = {
 	.tx			= wbsoft_tx,
-	.start			= wbsoft_start,		/* Start can be pretty much empty as we do wb35_hw_init() during probe? */
+	.start			= wbsoft_start,
 	.stop			= wbsoft_stop,
 	.add_interface		= wbsoft_add_interface,
 	.remove_interface	= wbsoft_remove_interface,
 	.config			= wbsoft_config,
-	.config_interface	= wbsoft_config_interface,
 	.configure_filter	= wbsoft_configure_filter,
 	.get_stats		= wbsoft_get_stats,
 	.get_tx_stats		= wbsoft_get_tx_stats,
 	.get_tsf		= wbsoft_get_tsf,
-// conf_tx: hal_set_cwmin()/hal_set_cwmax;
 };
 
-static unsigned char wb35_hw_init(struct ieee80211_hw *hw)
+static void
+hal_set_ethernet_address(struct hw_data *pHwData, u8 * current_address)
+{
+	u32 ltmp[2];
+
+	if (pHwData->SurpriseRemove)
+		return;
+
+	memcpy(pHwData->CurrentMacAddress, current_address, ETH_ALEN);
+
+	ltmp[0] = cpu_to_le32(*(u32 *) pHwData->CurrentMacAddress);
+	ltmp[1] =
+	    cpu_to_le32(*(u32 *) (pHwData->CurrentMacAddress + 4)) & 0xffff;
+
+	Wb35Reg_BurstWrite(pHwData, 0x03e8, ltmp, 2, AUTO_INCREMENT);
+}
+
+static void
+hal_get_permanent_address(struct hw_data *pHwData, u8 * pethernet_address)
+{
+	if (pHwData->SurpriseRemove)
+		return;
+
+	memcpy(pethernet_address, pHwData->PermanentMacAddress, 6);
+}
+
+static void hal_stop(struct hw_data *pHwData)
+{
+	struct wb35_reg *reg = &pHwData->reg;
+
+	pHwData->Wb35Rx.rx_halt = 1;
+	Wb35Rx_stop(pHwData);
+
+	pHwData->Wb35Tx.tx_halt = 1;
+	Wb35Tx_stop(pHwData);
+
+	reg->D00_DmaControl &= ~0xc0000000;	//Tx Off, Rx Off
+	Wb35Reg_Write(pHwData, 0x0400, reg->D00_DmaControl);
+}
+
+static unsigned char hal_idle(struct hw_data *pHwData)
+{
+	struct wb35_reg *reg = &pHwData->reg;
+	struct wb_usb *pWbUsb = &pHwData->WbUsb;
+
+	if (!pHwData->SurpriseRemove
+	    && (pWbUsb->DetectCount || reg->EP0vm_state != VM_STOP))
+		return false;
+
+	return true;
+}
+
+u8 hal_get_antenna_number(struct hw_data *pHwData)
+{
+	struct wb35_reg *reg = &pHwData->reg;
+
+	if ((reg->BB2C & BIT(11)) == 0)
+		return 0;
+	else
+		return 1;
+}
+
+/* 0 : radio on; 1: radio off */
+static u8 hal_get_hw_radio_off(struct hw_data * pHwData)
+{
+	struct wb35_reg *reg = &pHwData->reg;
+
+	if (pHwData->SurpriseRemove)
+		return 1;
+
+	//read the bit16 of register U1B0
+	Wb35Reg_Read(pHwData, 0x3b0, &reg->U1B0);
+	if ((reg->U1B0 & 0x00010000)) {
+		pHwData->CurrentRadioHw = 1;
+		return 1;
+	} else {
+		pHwData->CurrentRadioHw = 0;
+		return 0;
+	}
+}
+
+static u8 LED_GRAY[20] = {
+	0, 3, 4, 6, 8, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 8, 6, 4, 2
+};
+
+static u8 LED_GRAY2[30] = {
+	7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+	0, 15, 14, 13, 12, 11, 10, 9, 8
+};
+
+static void hal_led_control(unsigned long data)
+{
+	struct wbsoft_priv *adapter = (struct wbsoft_priv *)data;
+	struct hw_data *pHwData = &adapter->sHwData;
+	struct wb35_reg *reg = &pHwData->reg;
+	u32 LEDSet = (pHwData->SoftwareSet & HAL_LED_SET_MASK) >> HAL_LED_SET_SHIFT;
+	u32 TimeInterval = 500, ltmp, ltmp2;
+	ltmp = 0;
+
+	if (pHwData->SurpriseRemove)
+		return;
+
+	if (pHwData->LED_control) {
+		ltmp2 = pHwData->LED_control & 0xff;
+		if (ltmp2 == 5)	// 5 is WPS mode
+		{
+			TimeInterval = 100;
+			ltmp2 = (pHwData->LED_control >> 8) & 0xff;
+			switch (ltmp2) {
+			case 1:	// [0.2 On][0.1 Off]...
+				pHwData->LED_Blinking %= 3;
+				ltmp = 0x1010;	// Led 1 & 0 Green and Red
+				if (pHwData->LED_Blinking == 2)	// Turn off
+					ltmp = 0;
+				break;
+			case 2:	// [0.1 On][0.1 Off]...
+				pHwData->LED_Blinking %= 2;
+				ltmp = 0x0010;	// Led 0 red color
+				if (pHwData->LED_Blinking)	// Turn off
+					ltmp = 0;
+				break;
+			case 3:	// [0.1 On][0.1 Off][0.1 On][0.1 Off][0.1 On][0.1 Off][0.1 On][0.1 Off][0.1 On][0.1 Off][0.5 Off]...
+				pHwData->LED_Blinking %= 15;
+				ltmp = 0x0010;	// Led 0 red color
+				if ((pHwData->LED_Blinking >= 9) || (pHwData->LED_Blinking % 2))	// Turn off 0.6 sec
+					ltmp = 0;
+				break;
+			case 4:	// [300 On][ off ]
+				ltmp = 0x1000;	// Led 1 Green color
+				if (pHwData->LED_Blinking >= 3000)
+					ltmp = 0;	// led maybe on after 300sec * 32bit counter overlap.
+				break;
+			}
+			pHwData->LED_Blinking++;
+
+			reg->U1BC_LEDConfigure = ltmp;
+			if (LEDSet != 7)	// Only 111 mode has 2 LEDs on PCB.
+			{
+				reg->U1BC_LEDConfigure |= (ltmp & 0xff) << 8;	// Copy LED result to each LED control register
+				reg->U1BC_LEDConfigure |= (ltmp & 0xff00) >> 8;
+			}
+			Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);
+		}
+	} else if (pHwData->CurrentRadioSw || pHwData->CurrentRadioHw)	// If radio off
+	{
+		if (reg->U1BC_LEDConfigure & 0x1010) {
+			reg->U1BC_LEDConfigure &= ~0x1010;
+			Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);
+		}
+	} else {
+		switch (LEDSet) {
+		case 4:	// [100] Only 1 Led be placed on PCB and use pin 21 of IC. Use LED_0 for showing
+			if (!pHwData->LED_LinkOn)	// Blink only if not Link On
+			{
+				// Blinking if scanning is on progress
+				if (pHwData->LED_Scanning) {
+					if (pHwData->LED_Blinking == 0) {
+						reg->U1BC_LEDConfigure |= 0x10;
+						Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_0 On
+						pHwData->LED_Blinking = 1;
+						TimeInterval = 300;
+					} else {
+						reg->U1BC_LEDConfigure &= ~0x10;
+						Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_0 Off
+						pHwData->LED_Blinking = 0;
+						TimeInterval = 300;
+					}
+				} else {
+					//Turn Off LED_0
+					if (reg->U1BC_LEDConfigure & 0x10) {
+						reg->U1BC_LEDConfigure &= ~0x10;
+						Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_0 Off
+					}
+				}
+			} else {
+				// Turn On LED_0
+				if ((reg->U1BC_LEDConfigure & 0x10) == 0) {
+					reg->U1BC_LEDConfigure |= 0x10;
+					Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_0 Off
+				}
+			}
+			break;
+
+		case 6:	// [110] Only 1 Led be placed on PCB and use pin 21 of IC. Use LED_0 for showing
+			if (!pHwData->LED_LinkOn)	// Blink only if not Link On
+			{
+				// Blinking if scanning is on progress
+				if (pHwData->LED_Scanning) {
+					if (pHwData->LED_Blinking == 0) {
+						reg->U1BC_LEDConfigure &= ~0xf;
+						reg->U1BC_LEDConfigure |= 0x10;
+						Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_0 On
+						pHwData->LED_Blinking = 1;
+						TimeInterval = 300;
+					} else {
+						reg->U1BC_LEDConfigure &= ~0x1f;
+						Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_0 Off
+						pHwData->LED_Blinking = 0;
+						TimeInterval = 300;
+					}
+				} else {
+					// 20060901 Gray blinking if in disconnect state and not scanning
+					ltmp = reg->U1BC_LEDConfigure;
+					reg->U1BC_LEDConfigure &= ~0x1f;
+					if (LED_GRAY2[(pHwData->LED_Blinking % 30)]) {
+						reg->U1BC_LEDConfigure |= 0x10;
+						reg->U1BC_LEDConfigure |=
+						    LED_GRAY2[(pHwData->LED_Blinking % 30)];
+					}
+					pHwData->LED_Blinking++;
+					if (reg->U1BC_LEDConfigure != ltmp)
+						Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_0 Off
+					TimeInterval = 100;
+				}
+			} else {
+				// Turn On LED_0
+				if ((reg->U1BC_LEDConfigure & 0x10) == 0) {
+					reg->U1BC_LEDConfigure |= 0x10;
+					Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_0 Off
+				}
+			}
+			break;
+
+		case 5:	// [101] Only 1 Led be placed on PCB and use LED_1 for showing
+			if (!pHwData->LED_LinkOn)	// Blink only if not Link On
+			{
+				// Blinking if scanning is on progress
+				if (pHwData->LED_Scanning) {
+					if (pHwData->LED_Blinking == 0) {
+						reg->U1BC_LEDConfigure |=
+						    0x1000;
+						Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_1 On
+						pHwData->LED_Blinking = 1;
+						TimeInterval = 300;
+					} else {
+						reg->U1BC_LEDConfigure &=
+						    ~0x1000;
+						Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_1 Off
+						pHwData->LED_Blinking = 0;
+						TimeInterval = 300;
+					}
+				} else {
+					//Turn Off LED_1
+					if (reg->U1BC_LEDConfigure & 0x1000) {
+						reg->U1BC_LEDConfigure &=
+						    ~0x1000;
+						Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_1 Off
+					}
+				}
+			} else {
+				// Is transmitting/receiving ??
+				if ((adapter->RxByteCount !=
+				     pHwData->RxByteCountLast)
+				    || (adapter->TxByteCount !=
+					pHwData->TxByteCountLast)) {
+					if ((reg->U1BC_LEDConfigure & 0x3000) !=
+					    0x3000) {
+						reg->U1BC_LEDConfigure |=
+						    0x3000;
+						Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_1 On
+					}
+					// Update variable
+					pHwData->RxByteCountLast =
+					    adapter->RxByteCount;
+					pHwData->TxByteCountLast =
+					    adapter->TxByteCount;
+					TimeInterval = 200;
+				} else {
+					// Turn On LED_1 and blinking if transmitting/receiving
+					if ((reg->U1BC_LEDConfigure & 0x3000) !=
+					    0x1000) {
+						reg->U1BC_LEDConfigure &=
+						    ~0x3000;
+						reg->U1BC_LEDConfigure |=
+						    0x1000;
+						Wb35Reg_Write(pHwData, 0x03bc, reg->U1BC_LEDConfigure);	// LED_1 On
+					}
+				}
+			}
+			break;
+
+		default:	// Default setting. 2 LED be placed on PCB. LED_0: Link On LED_1 Active
+			if ((reg->U1BC_LEDConfigure & 0x3000) != 0x3000) {
+				reg->U1BC_LEDConfigure |= 0x3000;	// LED_1 is always on and event enable
+				Wb35Reg_Write(pHwData, 0x03bc,
+					      reg->U1BC_LEDConfigure);
+			}
+
+			if (pHwData->LED_Blinking) {
+				// Gray blinking
+				reg->U1BC_LEDConfigure &= ~0x0f;
+				reg->U1BC_LEDConfigure |= 0x10;
+				reg->U1BC_LEDConfigure |=
+				    LED_GRAY[(pHwData->LED_Blinking - 1) % 20];
+				Wb35Reg_Write(pHwData, 0x03bc,
+					      reg->U1BC_LEDConfigure);
+
+				pHwData->LED_Blinking += 2;
+				if (pHwData->LED_Blinking < 40)
+					TimeInterval = 100;
+				else {
+					pHwData->LED_Blinking = 0;	// Stop blinking
+					reg->U1BC_LEDConfigure &= ~0x0f;
+					Wb35Reg_Write(pHwData, 0x03bc,
+						      reg->U1BC_LEDConfigure);
+				}
+				break;
+			}
+
+			if (pHwData->LED_LinkOn) {
+				if (!(reg->U1BC_LEDConfigure & 0x10))	// Check the LED_0
+				{
+					//Try to turn ON LED_0 after gray blinking
+					reg->U1BC_LEDConfigure |= 0x10;
+					pHwData->LED_Blinking = 1;	//Start blinking
+					TimeInterval = 50;
+				}
+			} else {
+				if (reg->U1BC_LEDConfigure & 0x10)	// Check the LED_0
+				{
+					reg->U1BC_LEDConfigure &= ~0x10;
+					Wb35Reg_Write(pHwData, 0x03bc,
+						      reg->U1BC_LEDConfigure);
+				}
+			}
+			break;
+		}
+
+		//20060828.1 Active send null packet to avoid AP disconnect
+		if (pHwData->LED_LinkOn) {
+			pHwData->NullPacketCount += TimeInterval;
+			if (pHwData->NullPacketCount >=
+			    DEFAULT_NULL_PACKET_COUNT) {
+				pHwData->NullPacketCount = 0;
+			}
+		}
+	}
+
+	pHwData->time_count += TimeInterval;
+	Wb35Tx_CurrentTime(adapter, pHwData->time_count);	// 20060928 add
+	pHwData->LEDTimer.expires = jiffies + msecs_to_jiffies(TimeInterval);
+	add_timer(&pHwData->LEDTimer);
+}
+
+static int hal_init_hardware(struct ieee80211_hw *hw)
 {
 	struct wbsoft_priv *priv = hw->priv;
-	struct hw_data *	pHwData;
-	u8		*pMacAddr;
-	u8		*pMacAddr2;
-	u32		InitStep = 0;
-	u8		EEPROM_region;
-	u8		HwRadioOff;
+	struct hw_data *pHwData = &priv->sHwData;
+	u16 SoftwareSet;
 
-	//
-	// Setting default value for Linux
-	//
-	priv->sLocalPara.region_INF = REGION_AUTO;
-	priv->sLocalPara.TxRateMode = RATE_AUTO;
-	priv->sLocalPara.bMacOperationMode = MODE_802_11_BG;	// B/G mode
-	priv->Mds.TxRTSThreshold = DEFAULT_RTSThreshold;
-	priv->Mds.TxFragmentThreshold = DEFAULT_FRAGMENT_THRESHOLD;
-	hal_set_phy_type( &priv->sHwData, RF_WB_242_1 );
-	priv->sLocalPara.MTUsize = MAX_ETHERNET_PACKET_SIZE;
-	priv->sLocalPara.bPreambleMode = AUTO_MODE;
+	pHwData->MaxReceiveLifeTime = DEFAULT_MSDU_LIFE_TIME;
+	pHwData->FragmentThreshold = DEFAULT_FRAGMENT_THRESHOLD;
+
+	if (!Wb35Reg_initial(pHwData))
+		goto error_reg_destroy;
+
+	if (!Wb35Tx_initial(pHwData))
+		goto error_tx_destroy;
+
+	if (!Wb35Rx_initial(pHwData))
+		goto error_rx_destroy;
+
+	init_timer(&pHwData->LEDTimer);
+	pHwData->LEDTimer.function = hal_led_control;
+	pHwData->LEDTimer.data = (unsigned long)priv;
+	pHwData->LEDTimer.expires = jiffies + msecs_to_jiffies(1000);
+	add_timer(&pHwData->LEDTimer);
+
+	SoftwareSet = hal_software_set(pHwData);
+
+#ifdef Vendor2
+	// Try to make sure the EEPROM contain
+	SoftwareSet >>= 8;
+	if (SoftwareSet != 0x82)
+		return false;
+#endif
+
+	Wb35Rx_start(hw);
+	Wb35Tx_EP2VM_start(priv);
+
+	return 0;
+
+error_rx_destroy:
+	Wb35Rx_destroy(pHwData);
+error_tx_destroy:
+	Wb35Tx_destroy(pHwData);
+error_reg_destroy:
+	Wb35Reg_destroy(pHwData);
+
+	pHwData->SurpriseRemove = 1;
+	return -EINVAL;
+}
+
+static int wb35_hw_init(struct ieee80211_hw *hw)
+{
+	struct wbsoft_priv *priv = hw->priv;
+	struct hw_data *pHwData = &priv->sHwData;
+	u8 EEPROM_region;
+	u8 HwRadioOff;
+	u8 *pMacAddr2;
+	u8 *pMacAddr;
+	int err;
+
+	pHwData->phy_type = RF_DECIDE_BY_INF;
+
+	priv->Mds.TxRTSThreshold		= DEFAULT_RTSThreshold;
+	priv->Mds.TxFragmentThreshold		= DEFAULT_FRAGMENT_THRESHOLD;
+
+	priv->sLocalPara.region_INF		= REGION_AUTO;
+	priv->sLocalPara.TxRateMode		= RATE_AUTO;
+	priv->sLocalPara.bMacOperationMode	= MODE_802_11_BG;
+	priv->sLocalPara.MTUsize		= MAX_ETHERNET_PACKET_SIZE;
+	priv->sLocalPara.bPreambleMode		= AUTO_MODE;
+	priv->sLocalPara.bWepKeyError		= false;
+	priv->sLocalPara.bToSelfPacketReceived	= false;
+	priv->sLocalPara.WepKeyDetectTimerCount	= 2 * 100; /* 2 seconds */
+
 	priv->sLocalPara.RadioOffStatus.boSwRadioOff = false;
-	pHwData = &priv->sHwData;
-	hal_set_phy_type( pHwData, RF_DECIDE_BY_INF );
 
-	//added by ws for wep key error detection
-	priv->sLocalPara.bWepKeyError= false;
-	priv->sLocalPara.bToSelfPacketReceived = false;
-	priv->sLocalPara.WepKeyDetectTimerCount= 2 * 100; /// 2 seconds
-
-	// Initial USB hal
-	InitStep = 1;
-	pHwData = &priv->sHwData;
-	if (!hal_init_hardware(hw))
+	err = hal_init_hardware(hw);
+	if (err)
 		goto error;
 
-	EEPROM_region = hal_get_region_from_EEPROM( pHwData );
+	EEPROM_region = hal_get_region_from_EEPROM(pHwData);
 	if (EEPROM_region != REGION_AUTO)
 		priv->sLocalPara.region = EEPROM_region;
 	else {
 		if (priv->sLocalPara.region_INF != REGION_AUTO)
 			priv->sLocalPara.region = priv->sLocalPara.region_INF;
 		else
-			priv->sLocalPara.region = REGION_USA;	//default setting
+			priv->sLocalPara.region = REGION_USA;	/* default setting */
 	}
 
 	// Get Software setting flag from hal
@@ -247,93 +721,80 @@
 	if (hal_software_set(pHwData) & 0x00000001)
 		priv->sLocalPara.boAntennaDiversity = true;
 
-	//
-	// For TS module
-	//
-	InitStep = 2;
-
-	// For MDS module
-	InitStep = 3;
 	Mds_initial(priv);
 
-	//=======================================
-	// Initialize the SME, SCAN, MLME, ROAM
-	//=======================================
-	InitStep = 4;
-	InitStep = 5;
-	InitStep = 6;
-
-	// If no user-defined address in the registry, use the addresss "burned" on the NIC instead.
+	/*
+	 * If no user-defined address in the registry, use the addresss
+	 * "burned" on the NIC instead.
+	 */
 	pMacAddr = priv->sLocalPara.ThisMacAddress;
 	pMacAddr2 = priv->sLocalPara.PermanentAddress;
-	hal_get_permanent_address( pHwData, priv->sLocalPara.PermanentAddress );// Reading ethernet address from EEPROM
+
+	/* Reading ethernet address from EEPROM */
+	hal_get_permanent_address(pHwData, priv->sLocalPara.PermanentAddress);
 	if (memcmp(pMacAddr, "\x00\x00\x00\x00\x00\x00", MAC_ADDR_LENGTH) == 0)
 		memcpy(pMacAddr, pMacAddr2, MAC_ADDR_LENGTH);
 	else {
-		// Set the user define MAC address
-		hal_set_ethernet_address(pHwData, priv->sLocalPara.ThisMacAddress);
+		/* Set the user define MAC address */
+		hal_set_ethernet_address(pHwData,
+					 priv->sLocalPara.ThisMacAddress);
 	}
 
-	//get current antenna
 	priv->sLocalPara.bAntennaNo = hal_get_antenna_number(pHwData);
 #ifdef _PE_STATE_DUMP_
 	printk("Driver init, antenna no = %d\n", psLOCAL->bAntennaNo);
 #endif
-	hal_get_hw_radio_off( pHwData );
+	hal_get_hw_radio_off(pHwData);
 
-	// Waiting for HAL setting OK
+	/* Waiting for HAL setting OK */
 	while (!hal_idle(pHwData))
 		msleep(10);
 
 	MTO_Init(priv);
 
-	HwRadioOff = hal_get_hw_radio_off( pHwData );
+	HwRadioOff = hal_get_hw_radio_off(pHwData);
 	priv->sLocalPara.RadioOffStatus.boHwRadioOff = !!HwRadioOff;
 
-	hal_set_radio_mode( pHwData, (unsigned char)(priv->sLocalPara.RadioOffStatus.boSwRadioOff || priv->sLocalPara.RadioOffStatus.boHwRadioOff) );
+	hal_set_radio_mode(pHwData,
+			   (unsigned char)(priv->sLocalPara.RadioOffStatus.
+					   boSwRadioOff
+					   || priv->sLocalPara.RadioOffStatus.
+					   boHwRadioOff));
 
-	hal_driver_init_OK(pHwData) = 1; // Notify hal that the driver is ready now.
-	//set a tx power for reference.....
-//	sme_set_tx_power_level(priv, 12);	FIXME?
-	return true;
+	/* Notify hal that the driver is ready now. */
+	hal_driver_init_OK(pHwData) = 1;
 
 error:
-	switch (InitStep) {
-	case 5:
-	case 4:
-	case 3: Mds_Destroy( priv );
-	case 2:
-	case 1: hal_halt( pHwData, NULL );
-	case 0: break;
-	}
-
-	return false;
+	return err;
 }
 
-static int wb35_probe(struct usb_interface *intf, const struct usb_device_id *id_table)
+static int wb35_probe(struct usb_interface *intf,
+		      const struct usb_device_id *id_table)
 {
-	struct wb_usb *pWbUsb;
-        struct usb_host_interface *interface;
-	struct usb_endpoint_descriptor *endpoint;
-	u32	ltmp;
 	struct usb_device *udev = interface_to_usbdev(intf);
-	struct wbsoft_priv *priv;
+	struct usb_endpoint_descriptor *endpoint;
+	struct usb_host_interface *interface;
 	struct ieee80211_hw *dev;
+	struct wbsoft_priv *priv;
+	struct wb_usb *pWbUsb;
 	int nr, err;
+	u32 ltmp;
 
 	usb_get_dev(udev);
 
-	// 20060630.2 Check the device if it already be opened
-	nr = usb_control_msg(udev, usb_rcvctrlpipe( udev, 0 ),
-			     0x01, USB_TYPE_VENDOR|USB_RECIP_DEVICE|USB_DIR_IN,
-			     0x0, 0x400, &ltmp, 4, HZ*100 );
+	/* Check the device if it already be opened */
+	nr = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
+			     0x01,
+			     USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
+			     0x0, 0x400, &ltmp, 4, HZ * 100);
 	if (nr < 0) {
 		err = nr;
 		goto error;
 	}
 
+	/* Is already initialized? */
 	ltmp = cpu_to_le32(ltmp);
-	if (ltmp) {  // Is already initialized?
+	if (ltmp) {
 		err = -EBUSY;
 		goto error;
 	}
@@ -351,23 +812,22 @@
 	pWbUsb = &priv->sHwData.WbUsb;
 	pWbUsb->udev = udev;
 
-        interface = intf->cur_altsetting;
-        endpoint = &interface->endpoint[0].desc;
+	interface = intf->cur_altsetting;
+	endpoint = &interface->endpoint[0].desc;
 
 	if (endpoint[2].wMaxPacketSize == 512) {
 		printk("[w35und] Working on USB 2.0\n");
 		pWbUsb->IsUsb20 = 1;
 	}
 
-	if (!wb35_hw_init(dev)) {
-		err = -EINVAL;
+	err = wb35_hw_init(dev);
+	if (err)
 		goto error_free_hw;
-	}
 
 	SET_IEEE80211_DEV(dev, &udev->dev);
 	{
-		struct hw_data * pHwData = &priv->sHwData;
-		unsigned char		dev_addr[MAX_ADDR_LEN];
+		struct hw_data *pHwData = &priv->sHwData;
+		unsigned char dev_addr[MAX_ADDR_LEN];
 		hal_get_permanent_address(pHwData, dev_addr);
 		SET_IEEE80211_PERM_ADDR(dev, dev_addr);
 	}
@@ -397,22 +857,31 @@
 	return err;
 }
 
+static void hal_halt(struct hw_data *pHwData)
+{
+	del_timer_sync(&pHwData->LEDTimer);
+	/* XXX: Wait for Timer DPC exit. */
+	msleep(100);
+	Wb35Rx_destroy(pHwData);
+	Wb35Tx_destroy(pHwData);
+	Wb35Reg_destroy(pHwData);
+}
+
 static void wb35_hw_halt(struct wbsoft_priv *adapter)
 {
-	Mds_Destroy( adapter );
+	Mds_Destroy(adapter);
 
-	// Turn off Rx and Tx hardware ability
-	hal_stop( &adapter->sHwData );
+	/* Turn off Rx and Tx hardware ability */
+	hal_stop(&adapter->sHwData);
 #ifdef _PE_USB_INI_DUMP_
 	printk("[w35und] Hal_stop O.K.\n");
 #endif
-	msleep(100);// Waiting Irp completed
+	/* Waiting Irp completed */
+	msleep(100);
 
-	// Halt the HAL
-	hal_halt(&adapter->sHwData, NULL);
+	hal_halt(&adapter->sHwData);
 }
 
-
 static void wb35_disconnect(struct usb_interface *intf)
 {
 	struct ieee80211_hw *hw = usb_get_intfdata(intf);
diff --git a/drivers/staging/wlan-ng/README b/drivers/staging/wlan-ng/README
index 028c299..d0621f8 100644
--- a/drivers/staging/wlan-ng/README
+++ b/drivers/staging/wlan-ng/README
@@ -1,7 +1,6 @@
 TODO:
 	- checkpatch.pl cleanups
 	- sparse warnings
-	- Lindent cleanups
 	- move to use the in-kernel wireless stack
 
 Please send any patches or complaints about this driver to Greg
diff --git a/drivers/staging/wlan-ng/hfa384x.h b/drivers/staging/wlan-ng/hfa384x.h
index f3e8717..46cce81 100644
--- a/drivers/staging/wlan-ng/hfa384x.h
+++ b/drivers/staging/wlan-ng/hfa384x.h
@@ -63,8 +63,9 @@
 /*--- Mins & Maxs -----------------------------------*/
 #define		HFA384x_PORTID_MAX		((u16)7)
 #define		HFA384x_NUMPORTS_MAX		((u16)(HFA384x_PORTID_MAX+1))
-#define		HFA384x_PDR_LEN_MAX		((u16)512) /* in bytes, from EK */
-#define		HFA384x_PDA_LEN_MAX		((u16)1024) /* in bytes, from EK */
+#define		HFA384x_PDR_LEN_MAX		((u16)512)	/* in bytes, from EK */
+#define		HFA384x_PDA_RECS_MAX		((u16)200)	/* a guess */
+#define		HFA384x_PDA_LEN_MAX		((u16)1024)	/* in bytes, from EK */
 #define		HFA384x_SCANRESULT_MAX		((u16)31)
 #define		HFA384x_HSCANRESULT_MAX		((u16)31)
 #define		HFA384x_CHINFORESULT_MAX	((u16)16)
@@ -629,7 +630,7 @@
 typedef struct hfa384x_ScanResult {
 	u16 rsvd;
 	u16 scanreason;
-	 hfa384x_ScanResultSub_t result[HFA384x_SCANRESULT_MAX];
+	hfa384x_ScanResultSub_t result[HFA384x_SCANRESULT_MAX];
 } __attribute__ ((packed)) hfa384x_ScanResult_t;
 
 /*--  Inquiry Frame, Diagnose: ChInfo Results & Subfields--*/
@@ -645,7 +646,7 @@
 
 typedef struct hfa384x_ChInfoResult {
 	u16 scanchannels;
-	 hfa384x_ChInfoResultSub_t result[HFA384x_CHINFORESULT_MAX];
+	hfa384x_ChInfoResultSub_t result[HFA384x_CHINFORESULT_MAX];
 } __attribute__ ((packed)) hfa384x_ChInfoResult_t;
 
 /*--  Inquiry Frame, Diagnose: Host Scan Results & Subfields--*/
@@ -665,7 +666,7 @@
 typedef struct hfa384x_HScanResult {
 	u16 nresult;
 	u16 rsvd;
-	 hfa384x_HScanResultSub_t result[HFA384x_HSCANRESULT_MAX];
+	hfa384x_HScanResultSub_t result[HFA384x_HSCANRESULT_MAX];
 } __attribute__ ((packed)) hfa384x_HScanResult_t;
 
 /*--  Unsolicited Frame, MAC Mgmt: LinkStatus --*/
@@ -882,6 +883,213 @@
 	u8 boguspad[3000];
 } __attribute__ ((packed)) hfa384x_usbin_t;
 
+/*--------------------------------------------------------------------
+PD record structures.
+--------------------------------------------------------------------*/
+
+typedef struct hfa384x_pdr_pcb_partnum {
+	u8 num[8];
+} __attribute__ ((packed)) hfa384x_pdr_pcb_partnum_t;
+
+typedef struct hfa384x_pdr_pcb_tracenum {
+	u8 num[8];
+} __attribute__ ((packed)) hfa384x_pdr_pcb_tracenum_t;
+
+typedef struct hfa384x_pdr_nic_serial {
+	u8 num[12];
+} __attribute__ ((packed)) hfa384x_pdr_nic_serial_t;
+
+typedef struct hfa384x_pdr_mkk_measurements {
+	double carrier_freq;
+	double occupied_band;
+	double power_density;
+	double tx_spur_f1;
+	double tx_spur_f2;
+	double tx_spur_f3;
+	double tx_spur_f4;
+	double tx_spur_l1;
+	double tx_spur_l2;
+	double tx_spur_l3;
+	double tx_spur_l4;
+	double rx_spur_f1;
+	double rx_spur_f2;
+	double rx_spur_l1;
+	double rx_spur_l2;
+} __attribute__ ((packed)) hfa384x_pdr_mkk_measurements_t;
+
+typedef struct hfa384x_pdr_nic_ramsize {
+	u8 size[12];		/* units of KB */
+} __attribute__ ((packed)) hfa384x_pdr_nic_ramsize_t;
+
+typedef struct hfa384x_pdr_mfisuprange {
+	u16 id;
+	u16 variant;
+	u16 bottom;
+	u16 top;
+} __attribute__ ((packed)) hfa384x_pdr_mfisuprange_t;
+
+typedef struct hfa384x_pdr_cfisuprange {
+	u16 id;
+	u16 variant;
+	u16 bottom;
+	u16 top;
+} __attribute__ ((packed)) hfa384x_pdr_cfisuprange_t;
+
+typedef struct hfa384x_pdr_nicid {
+	u16 id;
+	u16 variant;
+	u16 major;
+	u16 minor;
+} __attribute__ ((packed)) hfa384x_pdr_nicid_t;
+
+typedef struct hfa384x_pdr_refdac_measurements {
+	u16 value[0];
+} __attribute__ ((packed)) hfa384x_pdr_refdac_measurements_t;
+
+typedef struct hfa384x_pdr_vgdac_measurements {
+	u16 value[0];
+} __attribute__ ((packed)) hfa384x_pdr_vgdac_measurements_t;
+
+typedef struct hfa384x_pdr_level_comp_measurements {
+	u16 value[0];
+} __attribute__ ((packed)) hfa384x_pdr_level_compc_measurements_t;
+
+typedef struct hfa384x_pdr_mac_address {
+	u8 addr[6];
+} __attribute__ ((packed)) hfa384x_pdr_mac_address_t;
+
+typedef struct hfa384x_pdr_mkk_callname {
+	u8 callname[8];
+} __attribute__ ((packed)) hfa384x_pdr_mkk_callname_t;
+
+typedef struct hfa384x_pdr_regdomain {
+	u16 numdomains;
+	u16 domain[5];
+} __attribute__ ((packed)) hfa384x_pdr_regdomain_t;
+
+typedef struct hfa384x_pdr_allowed_channel {
+	u16 ch_bitmap;
+} __attribute__ ((packed)) hfa384x_pdr_allowed_channel_t;
+
+typedef struct hfa384x_pdr_default_channel {
+	u16 channel;
+} __attribute__ ((packed)) hfa384x_pdr_default_channel_t;
+
+typedef struct hfa384x_pdr_privacy_option {
+	u16 available;
+} __attribute__ ((packed)) hfa384x_pdr_privacy_option_t;
+
+typedef struct hfa384x_pdr_temptype {
+	u16 type;
+} __attribute__ ((packed)) hfa384x_pdr_temptype_t;
+
+typedef struct hfa384x_pdr_refdac_setup {
+	u16 ch_value[14];
+} __attribute__ ((packed)) hfa384x_pdr_refdac_setup_t;
+
+typedef struct hfa384x_pdr_vgdac_setup {
+	u16 ch_value[14];
+} __attribute__ ((packed)) hfa384x_pdr_vgdac_setup_t;
+
+typedef struct hfa384x_pdr_level_comp_setup {
+	u16 ch_value[14];
+} __attribute__ ((packed)) hfa384x_pdr_level_comp_setup_t;
+
+typedef struct hfa384x_pdr_trimdac_setup {
+	u16 trimidac;
+	u16 trimqdac;
+} __attribute__ ((packed)) hfa384x_pdr_trimdac_setup_t;
+
+typedef struct hfa384x_pdr_ifr_setting {
+	u16 value[3];
+} __attribute__ ((packed)) hfa384x_pdr_ifr_setting_t;
+
+typedef struct hfa384x_pdr_rfr_setting {
+	u16 value[3];
+} __attribute__ ((packed)) hfa384x_pdr_rfr_setting_t;
+
+typedef struct hfa384x_pdr_hfa3861_baseline {
+	u16 value[50];
+} __attribute__ ((packed)) hfa384x_pdr_hfa3861_baseline_t;
+
+typedef struct hfa384x_pdr_hfa3861_shadow {
+	u32 value[32];
+} __attribute__ ((packed)) hfa384x_pdr_hfa3861_shadow_t;
+
+typedef struct hfa384x_pdr_hfa3861_ifrf {
+	u32 value[20];
+} __attribute__ ((packed)) hfa384x_pdr_hfa3861_ifrf_t;
+
+typedef struct hfa384x_pdr_hfa3861_chcalsp {
+	u16 value[14];
+} __attribute__ ((packed)) hfa384x_pdr_hfa3861_chcalsp_t;
+
+typedef struct hfa384x_pdr_hfa3861_chcali {
+	u16 value[17];
+} __attribute__ ((packed)) hfa384x_pdr_hfa3861_chcali_t;
+
+typedef struct hfa384x_pdr_hfa3861_nic_config {
+	u16 config_bitmap;
+} __attribute__ ((packed)) hfa384x_pdr_nic_config_t;
+
+typedef struct hfa384x_pdr_hfo_delay {
+	u8 hfo_delay;
+} __attribute__ ((packed)) hfa384x_hfo_delay_t;
+
+typedef struct hfa384x_pdr_hfa3861_manf_testsp {
+	u16 value[30];
+} __attribute__ ((packed)) hfa384x_pdr_hfa3861_manf_testsp_t;
+
+typedef struct hfa384x_pdr_hfa3861_manf_testi {
+	u16 value[30];
+} __attribute__ ((packed)) hfa384x_pdr_hfa3861_manf_testi_t;
+
+typedef struct hfa384x_end_of_pda {
+	u16 crc;
+} __attribute__ ((packed)) hfa384x_pdr_end_of_pda_t;
+
+typedef struct hfa384x_pdrec {
+	u16 len;		/* in words */
+	u16 code;
+	union pdr {
+		hfa384x_pdr_pcb_partnum_t pcb_partnum;
+		hfa384x_pdr_pcb_tracenum_t pcb_tracenum;
+		hfa384x_pdr_nic_serial_t nic_serial;
+		hfa384x_pdr_mkk_measurements_t mkk_measurements;
+		hfa384x_pdr_nic_ramsize_t nic_ramsize;
+		hfa384x_pdr_mfisuprange_t mfisuprange;
+		hfa384x_pdr_cfisuprange_t cfisuprange;
+		hfa384x_pdr_nicid_t nicid;
+		hfa384x_pdr_refdac_measurements_t refdac_measurements;
+		hfa384x_pdr_vgdac_measurements_t vgdac_measurements;
+		hfa384x_pdr_level_compc_measurements_t level_compc_measurements;
+		hfa384x_pdr_mac_address_t mac_address;
+		hfa384x_pdr_mkk_callname_t mkk_callname;
+		hfa384x_pdr_regdomain_t regdomain;
+		hfa384x_pdr_allowed_channel_t allowed_channel;
+		hfa384x_pdr_default_channel_t default_channel;
+		hfa384x_pdr_privacy_option_t privacy_option;
+		hfa384x_pdr_temptype_t temptype;
+		hfa384x_pdr_refdac_setup_t refdac_setup;
+		hfa384x_pdr_vgdac_setup_t vgdac_setup;
+		hfa384x_pdr_level_comp_setup_t level_comp_setup;
+		hfa384x_pdr_trimdac_setup_t trimdac_setup;
+		hfa384x_pdr_ifr_setting_t ifr_setting;
+		hfa384x_pdr_rfr_setting_t rfr_setting;
+		hfa384x_pdr_hfa3861_baseline_t hfa3861_baseline;
+		hfa384x_pdr_hfa3861_shadow_t hfa3861_shadow;
+		hfa384x_pdr_hfa3861_ifrf_t hfa3861_ifrf;
+		hfa384x_pdr_hfa3861_chcalsp_t hfa3861_chcalsp;
+		hfa384x_pdr_hfa3861_chcali_t hfa3861_chcali;
+		hfa384x_pdr_nic_config_t nic_config;
+		hfa384x_hfo_delay_t hfo_delay;
+		hfa384x_pdr_hfa3861_manf_testsp_t hfa3861_manf_testsp;
+		hfa384x_pdr_hfa3861_manf_testi_t hfa3861_manf_testi;
+		hfa384x_pdr_end_of_pda_t end_of_pda;
+
+	} data;
+} __attribute__ ((packed)) hfa384x_pdrec_t;
+
 #ifdef __KERNEL__
 /*--------------------------------------------------------------------
 ---  MAC state structure, argument to all functions --
@@ -925,7 +1133,7 @@
 
 typedef void (*ctlx_cmdcb_t) (struct hfa384x *, const struct hfa384x_usbctlx *);
 
-typedef void (*ctlx_usercb_t) (struct hfa384x *hw,
+typedef void (*ctlx_usercb_t) (struct hfa384x * hw,
 			       void *ctlxresult, void *usercb_data);
 
 typedef struct hfa384x_usbctlx {
@@ -1112,25 +1320,25 @@
 
 } hfa384x_t;
 
-void hfa384x_create(hfa384x_t *hw, struct usb_device *usb);
-void hfa384x_destroy(hfa384x_t *hw);
+void hfa384x_create(hfa384x_t * hw, struct usb_device *usb);
+void hfa384x_destroy(hfa384x_t * hw);
 
 int
-hfa384x_corereset(hfa384x_t *hw, int holdtime, int settletime, int genesis);
-int hfa384x_drvr_commtallies(hfa384x_t *hw);
-int hfa384x_drvr_disable(hfa384x_t *hw, u16 macport);
-int hfa384x_drvr_enable(hfa384x_t *hw, u16 macport);
-int hfa384x_drvr_flashdl_enable(hfa384x_t *hw);
-int hfa384x_drvr_flashdl_disable(hfa384x_t *hw);
-int hfa384x_drvr_flashdl_write(hfa384x_t *hw, u32 daddr, void *buf, u32 len);
-int hfa384x_drvr_getconfig(hfa384x_t *hw, u16 rid, void *buf, u16 len);
-int hfa384x_drvr_ramdl_enable(hfa384x_t *hw, u32 exeaddr);
-int hfa384x_drvr_ramdl_disable(hfa384x_t *hw);
-int hfa384x_drvr_ramdl_write(hfa384x_t *hw, u32 daddr, void *buf, u32 len);
-int hfa384x_drvr_readpda(hfa384x_t *hw, void *buf, unsigned int len);
-int hfa384x_drvr_setconfig(hfa384x_t *hw, u16 rid, void *buf, u16 len);
+hfa384x_corereset(hfa384x_t * hw, int holdtime, int settletime, int genesis);
+int hfa384x_drvr_commtallies(hfa384x_t * hw);
+int hfa384x_drvr_disable(hfa384x_t * hw, u16 macport);
+int hfa384x_drvr_enable(hfa384x_t * hw, u16 macport);
+int hfa384x_drvr_flashdl_enable(hfa384x_t * hw);
+int hfa384x_drvr_flashdl_disable(hfa384x_t * hw);
+int hfa384x_drvr_flashdl_write(hfa384x_t * hw, u32 daddr, void *buf, u32 len);
+int hfa384x_drvr_getconfig(hfa384x_t * hw, u16 rid, void *buf, u16 len);
+int hfa384x_drvr_ramdl_enable(hfa384x_t * hw, u32 exeaddr);
+int hfa384x_drvr_ramdl_disable(hfa384x_t * hw);
+int hfa384x_drvr_ramdl_write(hfa384x_t * hw, u32 daddr, void *buf, u32 len);
+int hfa384x_drvr_readpda(hfa384x_t * hw, void *buf, unsigned int len);
+int hfa384x_drvr_setconfig(hfa384x_t * hw, u16 rid, void *buf, u16 len);
 
-static inline int hfa384x_drvr_getconfig16(hfa384x_t *hw, u16 rid, void *val)
+static inline int hfa384x_drvr_getconfig16(hfa384x_t * hw, u16 rid, void *val)
 {
 	int result = 0;
 	result = hfa384x_drvr_getconfig(hw, rid, val, sizeof(u16));
@@ -1139,44 +1347,44 @@
 	return result;
 }
 
-static inline int hfa384x_drvr_setconfig16(hfa384x_t *hw, u16 rid, u16 val)
+static inline int hfa384x_drvr_setconfig16(hfa384x_t * hw, u16 rid, u16 val)
 {
 	u16 value = cpu_to_le16(val);
 	return hfa384x_drvr_setconfig(hw, rid, &value, sizeof(value));
 }
 
 int
-hfa384x_drvr_getconfig_async(hfa384x_t *hw,
+hfa384x_drvr_getconfig_async(hfa384x_t * hw,
 			     u16 rid, ctlx_usercb_t usercb, void *usercb_data);
 
 int
-hfa384x_drvr_setconfig_async(hfa384x_t *hw,
+hfa384x_drvr_setconfig_async(hfa384x_t * hw,
 			     u16 rid,
 			     void *buf,
 			     u16 len, ctlx_usercb_t usercb, void *usercb_data);
 
 static inline int
-hfa384x_drvr_setconfig16_async(hfa384x_t *hw, u16 rid, u16 val)
+hfa384x_drvr_setconfig16_async(hfa384x_t * hw, u16 rid, u16 val)
 {
 	u16 value = cpu_to_le16(val);
 	return hfa384x_drvr_setconfig_async(hw, rid, &value, sizeof(value),
 					    NULL, NULL);
 }
 
-int hfa384x_drvr_start(hfa384x_t *hw);
-int hfa384x_drvr_stop(hfa384x_t *hw);
+int hfa384x_drvr_start(hfa384x_t * hw);
+int hfa384x_drvr_stop(hfa384x_t * hw);
 int
-hfa384x_drvr_txframe(hfa384x_t *hw, struct sk_buff *skb,
-		     p80211_hdr_t *p80211_hdr, p80211_metawep_t *p80211_wep);
-void hfa384x_tx_timeout(wlandevice_t *wlandev);
+hfa384x_drvr_txframe(hfa384x_t * hw, struct sk_buff *skb,
+		     p80211_hdr_t * p80211_hdr, p80211_metawep_t * p80211_wep);
+void hfa384x_tx_timeout(wlandevice_t * wlandev);
 
-int hfa384x_cmd_initialize(hfa384x_t *hw);
-int hfa384x_cmd_enable(hfa384x_t *hw, u16 macport);
-int hfa384x_cmd_disable(hfa384x_t *hw, u16 macport);
-int hfa384x_cmd_allocate(hfa384x_t *hw, u16 len);
-int hfa384x_cmd_monitor(hfa384x_t *hw, u16 enable);
+int hfa384x_cmd_initialize(hfa384x_t * hw);
+int hfa384x_cmd_enable(hfa384x_t * hw, u16 macport);
+int hfa384x_cmd_disable(hfa384x_t * hw, u16 macport);
+int hfa384x_cmd_allocate(hfa384x_t * hw, u16 len);
+int hfa384x_cmd_monitor(hfa384x_t * hw, u16 enable);
 int
-hfa384x_cmd_download(hfa384x_t *hw,
+hfa384x_cmd_download(hfa384x_t * hw,
 		     u16 mode, u16 lowaddr, u16 highaddr, u16 codelen);
 
 #endif /* __KERNEL__ */
diff --git a/drivers/staging/wlan-ng/hfa384x_usb.c b/drivers/staging/wlan-ng/hfa384x_usb.c
index 824e65b..51d9e52 100644
--- a/drivers/staging/wlan-ng/hfa384x_usb.c
+++ b/drivers/staging/wlan-ng/hfa384x_usb.c
@@ -110,8 +110,6 @@
 * --------------------------------------------------------------------
 */
 
-#include <linux/version.h>
-
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/sched.h>
@@ -162,13 +160,13 @@
 #endif
 
 static void
-hfa384x_int_rxmonitor(wlandevice_t *wlandev, hfa384x_usb_rxfrm_t *rxfrm);
+hfa384x_int_rxmonitor(wlandevice_t * wlandev, hfa384x_usb_rxfrm_t * rxfrm);
 
 static void hfa384x_usb_defer(struct work_struct *data);
 
-static int submit_rx_urb(hfa384x_t *hw, gfp_t flags);
+static int submit_rx_urb(hfa384x_t * hw, gfp_t flags);
 
-static int submit_tx_urb(hfa384x_t *hw, struct urb *tx_urb, gfp_t flags);
+static int submit_tx_urb(hfa384x_t * hw, struct urb *tx_urb, gfp_t flags);
 
 /*---------------------------------------------------*/
 /* Callbacks */
@@ -177,22 +175,22 @@
 static void hfa384x_usbin_callback(struct urb *urb);
 
 static void
-hfa384x_usbin_txcompl(wlandevice_t *wlandev, hfa384x_usbin_t *usbin);
+hfa384x_usbin_txcompl(wlandevice_t * wlandev, hfa384x_usbin_t * usbin);
 
-static void hfa384x_usbin_rx(wlandevice_t *wlandev, struct sk_buff *skb);
+static void hfa384x_usbin_rx(wlandevice_t * wlandev, struct sk_buff *skb);
 
-static void hfa384x_usbin_info(wlandevice_t *wlandev, hfa384x_usbin_t *usbin);
+static void hfa384x_usbin_info(wlandevice_t * wlandev, hfa384x_usbin_t * usbin);
 
 static void
-hfa384x_usbout_tx(wlandevice_t *wlandev, hfa384x_usbout_t *usbout);
+hfa384x_usbout_tx(wlandevice_t * wlandev, hfa384x_usbout_t * usbout);
 
-static void hfa384x_usbin_ctlx(hfa384x_t *hw, hfa384x_usbin_t *usbin,
+static void hfa384x_usbin_ctlx(hfa384x_t * hw, hfa384x_usbin_t * usbin,
 			       int urb_status);
 
 /*---------------------------------------------------*/
 /* Functions to support the prism2 usb command queue */
 
-static void hfa384x_usbctlxq_run(hfa384x_t *hw);
+static void hfa384x_usbctlxq_run(hfa384x_t * hw);
 
 static void hfa384x_usbctlx_reqtimerfn(unsigned long data);
 
@@ -204,9 +202,9 @@
 
 static void hfa384x_usbctlx_reaper_task(unsigned long data);
 
-static int hfa384x_usbctlx_submit(hfa384x_t *hw, hfa384x_usbctlx_t *ctlx);
+static int hfa384x_usbctlx_submit(hfa384x_t * hw, hfa384x_usbctlx_t * ctlx);
 
-static void unlocked_usbctlx_complete(hfa384x_t *hw, hfa384x_usbctlx_t *ctlx);
+static void unlocked_usbctlx_complete(hfa384x_t * hw, hfa384x_usbctlx_t * ctlx);
 
 struct usbctlx_completor {
 	int (*complete) (struct usbctlx_completor *);
@@ -214,35 +212,35 @@
 typedef struct usbctlx_completor usbctlx_completor_t;
 
 static int
-hfa384x_usbctlx_complete_sync(hfa384x_t *hw,
-			      hfa384x_usbctlx_t *ctlx,
-			      usbctlx_completor_t *completor);
+hfa384x_usbctlx_complete_sync(hfa384x_t * hw,
+			      hfa384x_usbctlx_t * ctlx,
+			      usbctlx_completor_t * completor);
 
 static int
-unlocked_usbctlx_cancel_async(hfa384x_t *hw, hfa384x_usbctlx_t *ctlx);
+unlocked_usbctlx_cancel_async(hfa384x_t * hw, hfa384x_usbctlx_t * ctlx);
 
-static void hfa384x_cb_status(hfa384x_t *hw, const hfa384x_usbctlx_t *ctlx);
+static void hfa384x_cb_status(hfa384x_t * hw, const hfa384x_usbctlx_t * ctlx);
 
-static void hfa384x_cb_rrid(hfa384x_t *hw, const hfa384x_usbctlx_t *ctlx);
+static void hfa384x_cb_rrid(hfa384x_t * hw, const hfa384x_usbctlx_t * ctlx);
 
 static int
-usbctlx_get_status(const hfa384x_usb_cmdresp_t *cmdresp,
-		   hfa384x_cmdresult_t *result);
+usbctlx_get_status(const hfa384x_usb_cmdresp_t * cmdresp,
+		   hfa384x_cmdresult_t * result);
 
 static void
-usbctlx_get_rridresult(const hfa384x_usb_rridresp_t *rridresp,
-		       hfa384x_rridresult_t *result);
+usbctlx_get_rridresult(const hfa384x_usb_rridresp_t * rridresp,
+		       hfa384x_rridresult_t * result);
 
 /*---------------------------------------------------*/
 /* Low level req/resp CTLX formatters and submitters */
 static int
-hfa384x_docmd(hfa384x_t *hw,
+hfa384x_docmd(hfa384x_t * hw,
 	      CMD_MODE mode,
-	      hfa384x_metacmd_t *cmd,
+	      hfa384x_metacmd_t * cmd,
 	      ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data);
 
 static int
-hfa384x_dorrid(hfa384x_t *hw,
+hfa384x_dorrid(hfa384x_t * hw,
 	       CMD_MODE mode,
 	       u16 rid,
 	       void *riddata,
@@ -250,7 +248,7 @@
 	       ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data);
 
 static int
-hfa384x_dowrid(hfa384x_t *hw,
+hfa384x_dowrid(hfa384x_t * hw,
 	       CMD_MODE mode,
 	       u16 rid,
 	       void *riddata,
@@ -258,7 +256,7 @@
 	       ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data);
 
 static int
-hfa384x_dormem(hfa384x_t *hw,
+hfa384x_dormem(hfa384x_t * hw,
 	       CMD_MODE mode,
 	       u16 page,
 	       u16 offset,
@@ -267,7 +265,7 @@
 	       ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data);
 
 static int
-hfa384x_dowmem(hfa384x_t *hw,
+hfa384x_dowmem(hfa384x_t * hw,
 	       CMD_MODE mode,
 	       u16 page,
 	       u16 offset,
@@ -292,7 +290,7 @@
 	return ctlx_str[s];
 };
 
-static inline hfa384x_usbctlx_t *get_active_ctlx(hfa384x_t *hw)
+static inline hfa384x_usbctlx_t *get_active_ctlx(hfa384x_t * hw)
 {
 	return list_entry(hw->ctlxq.active.next, hfa384x_usbctlx_t, list);
 }
@@ -304,21 +302,19 @@
 	pr_debug("urb->status=0x%08x\n", urb->status);
 	pr_debug("urb->transfer_flags=0x%08x\n", urb->transfer_flags);
 	pr_debug("urb->transfer_buffer=0x%08x\n",
-	       (unsigned int)urb->transfer_buffer);
+		 (unsigned int)urb->transfer_buffer);
 	pr_debug("urb->transfer_buffer_length=0x%08x\n",
-	       urb->transfer_buffer_length);
+		 urb->transfer_buffer_length);
 	pr_debug("urb->actual_length=0x%08x\n", urb->actual_length);
 	pr_debug("urb->bandwidth=0x%08x\n", urb->bandwidth);
 	pr_debug("urb->setup_packet(ctl)=0x%08x\n",
-	       (unsigned int)urb->setup_packet);
-	pr_debug("urb->start_frame(iso/irq)=0x%08x\n",
-	       urb->start_frame);
+		 (unsigned int)urb->setup_packet);
+	pr_debug("urb->start_frame(iso/irq)=0x%08x\n", urb->start_frame);
 	pr_debug("urb->interval(irq)=0x%08x\n", urb->interval);
 	pr_debug("urb->error_count(iso)=0x%08x\n", urb->error_count);
 	pr_debug("urb->timeout=0x%08x\n", urb->timeout);
 	pr_debug("urb->context=0x%08x\n", (unsigned int)urb->context);
-	pr_debug("urb->complete=0x%08x\n",
-	       (unsigned int)urb->complete);
+	pr_debug("urb->complete=0x%08x\n", (unsigned int)urb->complete);
 }
 #endif
 
@@ -338,7 +334,7 @@
 * Call context:
 *	Any
 ----------------------------------------------------------------*/
-static int submit_rx_urb(hfa384x_t *hw, gfp_t memflags)
+static int submit_rx_urb(hfa384x_t * hw, gfp_t memflags)
 {
 	struct sk_buff *skb;
 	int result;
@@ -399,7 +395,7 @@
 * Call context:
 *	Any
 ----------------------------------------------------------------*/
-static int submit_tx_urb(hfa384x_t *hw, struct urb *tx_urb, gfp_t memflags)
+static int submit_tx_urb(hfa384x_t * hw, struct urb *tx_urb, gfp_t memflags)
 {
 	struct net_device *netdev = hw->wlandev->netdev;
 	int result;
@@ -536,7 +532,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-void hfa384x_create(hfa384x_t *hw, struct usb_device *usb)
+void hfa384x_create(hfa384x_t * hw, struct usb_device *usb)
 {
 	memset(hw, 0, sizeof(hfa384x_t));
 	hw->usb = usb;
@@ -612,7 +608,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-void hfa384x_destroy(hfa384x_t *hw)
+void hfa384x_destroy(hfa384x_t * hw)
 {
 	struct sk_buff *skb;
 
@@ -634,7 +630,7 @@
 {
 	hfa384x_usbctlx_t *ctlx;
 
-	ctlx = kmalloc(sizeof(*ctlx), in_interrupt() ? GFP_ATOMIC : GFP_KERNEL);
+	ctlx = kmalloc(sizeof(*ctlx), in_interrupt()? GFP_ATOMIC : GFP_KERNEL);
 	if (ctlx != NULL) {
 		memset(ctlx, 0, sizeof(*ctlx));
 		init_completion(&ctlx->done);
@@ -644,8 +640,8 @@
 }
 
 static int
-usbctlx_get_status(const hfa384x_usb_cmdresp_t *cmdresp,
-		   hfa384x_cmdresult_t *result)
+usbctlx_get_status(const hfa384x_usb_cmdresp_t * cmdresp,
+		   hfa384x_cmdresult_t * result)
 {
 	result->status = le16_to_cpu(cmdresp->status);
 	result->resp0 = le16_to_cpu(cmdresp->resp0);
@@ -653,15 +649,15 @@
 	result->resp2 = le16_to_cpu(cmdresp->resp2);
 
 	pr_debug("cmdresult:status=0x%04x "
-	       "resp0=0x%04x resp1=0x%04x resp2=0x%04x\n",
-	       result->status, result->resp0, result->resp1, result->resp2);
+		 "resp0=0x%04x resp1=0x%04x resp2=0x%04x\n",
+		 result->status, result->resp0, result->resp1, result->resp2);
 
 	return result->status & HFA384x_STATUS_RESULT;
 }
 
 static void
-usbctlx_get_rridresult(const hfa384x_usb_rridresp_t *rridresp,
-		       hfa384x_rridresult_t *result)
+usbctlx_get_rridresult(const hfa384x_usb_rridresp_t * rridresp,
+		       hfa384x_rridresult_t * result)
 {
 	result->rid = le16_to_cpu(rridresp->rid);
 	result->riddata = rridresp->data;
@@ -682,7 +678,7 @@
 };
 typedef struct usbctlx_cmd_completor usbctlx_cmd_completor_t;
 
-static int usbctlx_cmd_completor_fn(usbctlx_completor_t *head)
+static int usbctlx_cmd_completor_fn(usbctlx_completor_t * head)
 {
 	usbctlx_cmd_completor_t *complete = (usbctlx_cmd_completor_t *) head;
 	return usbctlx_get_status(complete->cmdresp, complete->result);
@@ -716,7 +712,7 @@
 };
 typedef struct usbctlx_rrid_completor usbctlx_rrid_completor_t;
 
-static int usbctlx_rrid_completor_fn(usbctlx_completor_t *head)
+static int usbctlx_rrid_completor_fn(usbctlx_completor_t * head)
 {
 	usbctlx_rrid_completor_t *complete = (usbctlx_rrid_completor_t *) head;
 	hfa384x_rridresult_t rridresult;
@@ -737,7 +733,7 @@
 }
 
 static inline usbctlx_completor_t *init_rrid_completor(usbctlx_rrid_completor_t
-						       *completor,
+						       * completor,
 						       const
 						       hfa384x_usb_rridresp_t *
 						       rridresp, void *riddata,
@@ -777,7 +773,7 @@
 };
 typedef struct usbctlx_rmem_completor usbctlx_rmem_completor_t;
 
-static int usbctlx_rmem_completor_fn(usbctlx_completor_t *head)
+static int usbctlx_rmem_completor_fn(usbctlx_completor_t * head)
 {
 	usbctlx_rmem_completor_t *complete = (usbctlx_rmem_completor_t *) head;
 
@@ -787,9 +783,9 @@
 }
 
 static inline usbctlx_completor_t *init_rmem_completor(usbctlx_rmem_completor_t
-						       *completor,
+						       * completor,
 						       hfa384x_usb_rmemresp_t
-                                                       *rmemresp, void *data,
+						       * rmemresp, void *data,
 						       unsigned int len)
 {
 	completor->head.complete = usbctlx_rmem_completor_fn;
@@ -820,7 +816,7 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void hfa384x_cb_status(hfa384x_t *hw, const hfa384x_usbctlx_t *ctlx)
+static void hfa384x_cb_status(hfa384x_t * hw, const hfa384x_usbctlx_t * ctlx)
 {
 	if (ctlx->usercb != NULL) {
 		hfa384x_cmdresult_t cmdresult;
@@ -857,15 +853,14 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void hfa384x_cb_rrid(hfa384x_t *hw, const hfa384x_usbctlx_t *ctlx)
+static void hfa384x_cb_rrid(hfa384x_t * hw, const hfa384x_usbctlx_t * ctlx)
 {
 	if (ctlx->usercb != NULL) {
 		hfa384x_rridresult_t rridresult;
 
 		if (ctlx->state != CTLX_COMPLETE) {
 			memset(&rridresult, 0, sizeof(rridresult));
-			rridresult.rid =
-			    le16_to_cpu(ctlx->outbuf.rridreq.rid);
+			rridresult.rid = le16_to_cpu(ctlx->outbuf.rridreq.rid);
 		} else {
 			usbctlx_get_rridresult(&ctlx->inbuf.rridresp,
 					       &rridresult);
@@ -875,21 +870,21 @@
 	}
 }
 
-static inline int hfa384x_docmd_wait(hfa384x_t *hw, hfa384x_metacmd_t *cmd)
+static inline int hfa384x_docmd_wait(hfa384x_t * hw, hfa384x_metacmd_t * cmd)
 {
 	return hfa384x_docmd(hw, DOWAIT, cmd, NULL, NULL, NULL);
 }
 
 static inline int
-hfa384x_docmd_async(hfa384x_t *hw,
-		    hfa384x_metacmd_t *cmd,
+hfa384x_docmd_async(hfa384x_t * hw,
+		    hfa384x_metacmd_t * cmd,
 		    ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data)
 {
 	return hfa384x_docmd(hw, DOASYNC, cmd, cmdcb, usercb, usercb_data);
 }
 
 static inline int
-hfa384x_dorrid_wait(hfa384x_t *hw, u16 rid, void *riddata,
+hfa384x_dorrid_wait(hfa384x_t * hw, u16 rid, void *riddata,
 		    unsigned int riddatalen)
 {
 	return hfa384x_dorrid(hw, DOWAIT,
@@ -897,7 +892,7 @@
 }
 
 static inline int
-hfa384x_dorrid_async(hfa384x_t *hw,
+hfa384x_dorrid_async(hfa384x_t * hw,
 		     u16 rid, void *riddata, unsigned int riddatalen,
 		     ctlx_cmdcb_t cmdcb,
 		     ctlx_usercb_t usercb, void *usercb_data)
@@ -908,7 +903,7 @@
 }
 
 static inline int
-hfa384x_dowrid_wait(hfa384x_t *hw, u16 rid, void *riddata,
+hfa384x_dowrid_wait(hfa384x_t * hw, u16 rid, void *riddata,
 		    unsigned int riddatalen)
 {
 	return hfa384x_dowrid(hw, DOWAIT,
@@ -916,7 +911,7 @@
 }
 
 static inline int
-hfa384x_dowrid_async(hfa384x_t *hw,
+hfa384x_dowrid_async(hfa384x_t * hw,
 		     u16 rid, void *riddata, unsigned int riddatalen,
 		     ctlx_cmdcb_t cmdcb,
 		     ctlx_usercb_t usercb, void *usercb_data)
@@ -927,7 +922,7 @@
 }
 
 static inline int
-hfa384x_dormem_wait(hfa384x_t *hw,
+hfa384x_dormem_wait(hfa384x_t * hw,
 		    u16 page, u16 offset, void *data, unsigned int len)
 {
 	return hfa384x_dormem(hw, DOWAIT,
@@ -935,7 +930,7 @@
 }
 
 static inline int
-hfa384x_dormem_async(hfa384x_t *hw,
+hfa384x_dormem_async(hfa384x_t * hw,
 		     u16 page, u16 offset, void *data, unsigned int len,
 		     ctlx_cmdcb_t cmdcb,
 		     ctlx_usercb_t usercb, void *usercb_data)
@@ -946,7 +941,7 @@
 }
 
 static inline int
-hfa384x_dowmem_wait(hfa384x_t *hw,
+hfa384x_dowmem_wait(hfa384x_t * hw,
 		    u16 page, u16 offset, void *data, unsigned int len)
 {
 	return hfa384x_dowmem(hw, DOWAIT,
@@ -954,7 +949,7 @@
 }
 
 static inline int
-hfa384x_dowmem_async(hfa384x_t *hw,
+hfa384x_dowmem_async(hfa384x_t * hw,
 		     u16 page,
 		     u16 offset,
 		     void *data,
@@ -986,7 +981,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_cmd_initialize(hfa384x_t *hw)
+int hfa384x_cmd_initialize(hfa384x_t * hw)
 {
 	int result = 0;
 	int i;
@@ -1000,10 +995,10 @@
 	result = hfa384x_docmd_wait(hw, &cmd);
 
 	pr_debug("cmdresp.init: "
-	       "status=0x%04x, resp0=0x%04x, "
-	       "resp1=0x%04x, resp2=0x%04x\n",
-	       cmd.result.status,
-	       cmd.result.resp0, cmd.result.resp1, cmd.result.resp2);
+		 "status=0x%04x, resp0=0x%04x, "
+		 "resp1=0x%04x, resp2=0x%04x\n",
+		 cmd.result.status,
+		 cmd.result.resp0, cmd.result.resp1, cmd.result.resp2);
 	if (result == 0) {
 		for (i = 0; i < HFA384x_NUMPORTS_MAX; i++)
 			hw->port_enabled[i] = 0;
@@ -1034,7 +1029,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_cmd_disable(hfa384x_t *hw, u16 macport)
+int hfa384x_cmd_disable(hfa384x_t * hw, u16 macport)
 {
 	int result = 0;
 	hfa384x_metacmd_t cmd;
@@ -1070,7 +1065,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_cmd_enable(hfa384x_t *hw, u16 macport)
+int hfa384x_cmd_enable(hfa384x_t * hw, u16 macport)
 {
 	int result = 0;
 	hfa384x_metacmd_t cmd;
@@ -1115,7 +1110,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_cmd_monitor(hfa384x_t *hw, u16 enable)
+int hfa384x_cmd_monitor(hfa384x_t * hw, u16 enable)
 {
 	int result = 0;
 	hfa384x_metacmd_t cmd;
@@ -1169,15 +1164,14 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_cmd_download(hfa384x_t *hw, u16 mode, u16 lowaddr,
+int hfa384x_cmd_download(hfa384x_t * hw, u16 mode, u16 lowaddr,
 			 u16 highaddr, u16 codelen)
 {
 	int result = 0;
 	hfa384x_metacmd_t cmd;
 
-	printk(KERN_DEBUG
-	       "mode=%d, lowaddr=0x%04x, highaddr=0x%04x, codelen=%d\n",
-	       mode, lowaddr, highaddr, codelen);
+	pr_debug("mode=%d, lowaddr=0x%04x, highaddr=0x%04x, codelen=%d\n",
+		 mode, lowaddr, highaddr, codelen);
 
 	cmd.cmd = (HFA384x_CMD_CMDCODE_SET(HFA384x_CMDCODE_DOWNLD) |
 		   HFA384x_CMD_PROGMODE_SET(mode));
@@ -1214,7 +1208,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_corereset(hfa384x_t *hw, int holdtime, int settletime, int genesis)
+int hfa384x_corereset(hfa384x_t * hw, int holdtime, int settletime, int genesis)
 {
 	int result = 0;
 
@@ -1251,9 +1245,9 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-static int hfa384x_usbctlx_complete_sync(hfa384x_t *hw,
-					 hfa384x_usbctlx_t *ctlx,
-					 usbctlx_completor_t *completor)
+static int hfa384x_usbctlx_complete_sync(hfa384x_t * hw,
+					 hfa384x_usbctlx_t * ctlx,
+					 usbctlx_completor_t * completor)
 {
 	unsigned long flags;
 	int result;
@@ -1367,9 +1361,9 @@
 *	process
 ----------------------------------------------------------------*/
 static int
-hfa384x_docmd(hfa384x_t *hw,
+hfa384x_docmd(hfa384x_t * hw,
 	      CMD_MODE mode,
-	      hfa384x_metacmd_t *cmd,
+	      hfa384x_metacmd_t * cmd,
 	      ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data)
 {
 	int result;
@@ -1391,8 +1385,8 @@
 	ctlx->outbufsize = sizeof(ctlx->outbuf.cmdreq);
 
 	pr_debug("cmdreq: cmd=0x%04x "
-	       "parm0=0x%04x parm1=0x%04x parm2=0x%04x\n",
-	       cmd->cmd, cmd->parm0, cmd->parm1, cmd->parm2);
+		 "parm0=0x%04x parm1=0x%04x parm2=0x%04x\n",
+		 cmd->cmd, cmd->parm0, cmd->parm1, cmd->parm2);
 
 	ctlx->reapable = mode;
 	ctlx->cmdcb = cmdcb;
@@ -1456,7 +1450,7 @@
 *	process (DOWAIT or DOASYNC)
 ----------------------------------------------------------------*/
 static int
-hfa384x_dorrid(hfa384x_t *hw,
+hfa384x_dorrid(hfa384x_t * hw,
 	       CMD_MODE mode,
 	       u16 rid,
 	       void *riddata,
@@ -1537,7 +1531,7 @@
 *	process (DOWAIT or DOASYNC)
 ----------------------------------------------------------------*/
 static int
-hfa384x_dowrid(hfa384x_t *hw,
+hfa384x_dowrid(hfa384x_t * hw,
 	       CMD_MODE mode,
 	       u16 rid,
 	       void *riddata,
@@ -1556,9 +1550,8 @@
 	/* Initialize the command */
 	ctlx->outbuf.wridreq.type = cpu_to_le16(HFA384x_USB_WRIDREQ);
 	ctlx->outbuf.wridreq.frmlen = cpu_to_le16((sizeof
-						       (ctlx->outbuf.wridreq.
-							rid) + riddatalen +
-						       1) / 2);
+						   (ctlx->outbuf.wridreq.rid) +
+						   riddatalen + 1) / 2);
 	ctlx->outbuf.wridreq.rid = cpu_to_le16(rid);
 	memcpy(ctlx->outbuf.wridreq.data, riddata, riddatalen);
 
@@ -1625,7 +1618,7 @@
 *	process (DOWAIT or DOASYNC)
 ----------------------------------------------------------------*/
 static int
-hfa384x_dormem(hfa384x_t *hw,
+hfa384x_dormem(hfa384x_t * hw,
 	       CMD_MODE mode,
 	       u16 page,
 	       u16 offset,
@@ -1646,20 +1639,18 @@
 	ctlx->outbuf.rmemreq.type = cpu_to_le16(HFA384x_USB_RMEMREQ);
 	ctlx->outbuf.rmemreq.frmlen =
 	    cpu_to_le16(sizeof(ctlx->outbuf.rmemreq.offset) +
-			    sizeof(ctlx->outbuf.rmemreq.page) + len);
+			sizeof(ctlx->outbuf.rmemreq.page) + len);
 	ctlx->outbuf.rmemreq.offset = cpu_to_le16(offset);
 	ctlx->outbuf.rmemreq.page = cpu_to_le16(page);
 
 	ctlx->outbufsize = sizeof(ctlx->outbuf.rmemreq);
 
-	printk(KERN_DEBUG
-	       "type=0x%04x frmlen=%d offset=0x%04x page=0x%04x\n",
-	       ctlx->outbuf.rmemreq.type,
-	       ctlx->outbuf.rmemreq.frmlen,
-	       ctlx->outbuf.rmemreq.offset, ctlx->outbuf.rmemreq.page);
+	pr_debug("type=0x%04x frmlen=%d offset=0x%04x page=0x%04x\n",
+		 ctlx->outbuf.rmemreq.type,
+		 ctlx->outbuf.rmemreq.frmlen,
+		 ctlx->outbuf.rmemreq.offset, ctlx->outbuf.rmemreq.page);
 
-	pr_debug("pktsize=%zd\n",
-	       ROUNDUP64(sizeof(ctlx->outbuf.rmemreq)));
+	pr_debug("pktsize=%zd\n", ROUNDUP64(sizeof(ctlx->outbuf.rmemreq)));
 
 	ctlx->reapable = mode;
 	ctlx->cmdcb = cmdcb;
@@ -1718,7 +1709,7 @@
 *	process (DOWAIT or DOASYNC)
 ----------------------------------------------------------------*/
 static int
-hfa384x_dowmem(hfa384x_t *hw,
+hfa384x_dowmem(hfa384x_t * hw,
 	       CMD_MODE mode,
 	       u16 page,
 	       u16 offset,
@@ -1729,8 +1720,7 @@
 	int result;
 	hfa384x_usbctlx_t *ctlx;
 
-	pr_debug("page=0x%04x offset=0x%04x len=%d\n",
-	       page, offset, len);
+	pr_debug("page=0x%04x offset=0x%04x len=%d\n", page, offset, len);
 
 	ctlx = usbctlx_alloc();
 	if (ctlx == NULL) {
@@ -1742,7 +1732,7 @@
 	ctlx->outbuf.wmemreq.type = cpu_to_le16(HFA384x_USB_WMEMREQ);
 	ctlx->outbuf.wmemreq.frmlen =
 	    cpu_to_le16(sizeof(ctlx->outbuf.wmemreq.offset) +
-			    sizeof(ctlx->outbuf.wmemreq.page) + len);
+			sizeof(ctlx->outbuf.wmemreq.page) + len);
 	ctlx->outbuf.wmemreq.offset = cpu_to_le16(offset);
 	ctlx->outbuf.wmemreq.page = cpu_to_le16(page);
 	memcpy(ctlx->outbuf.wmemreq.data, data, len);
@@ -1793,7 +1783,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_commtallies(hfa384x_t *hw)
+int hfa384x_drvr_commtallies(hfa384x_t * hw)
 {
 	hfa384x_metacmd_t cmd;
 
@@ -1829,7 +1819,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_disable(hfa384x_t *hw, u16 macport)
+int hfa384x_drvr_disable(hfa384x_t * hw, u16 macport)
 {
 	int result = 0;
 
@@ -1867,7 +1857,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_enable(hfa384x_t *hw, u16 macport)
+int hfa384x_drvr_enable(hfa384x_t * hw, u16 macport)
 {
 	int result = 0;
 
@@ -1904,7 +1894,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_flashdl_enable(hfa384x_t *hw)
+int hfa384x_drvr_flashdl_enable(hfa384x_t * hw)
 {
 	int result = 0;
 	int i;
@@ -1962,7 +1952,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_flashdl_disable(hfa384x_t *hw)
+int hfa384x_drvr_flashdl_disable(hfa384x_t * hw)
 {
 	/* Check that we're already in the download state */
 	if (hw->dlstate != HFA384x_DLSTATE_FLASHENABLED)
@@ -2007,7 +1997,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_flashdl_write(hfa384x_t *hw, u32 daddr, void *buf, u32 len)
+int hfa384x_drvr_flashdl_write(hfa384x_t * hw, u32 daddr, void *buf, u32 len)
 {
 	int result = 0;
 	u32 dlbufaddr;
@@ -2036,9 +2026,8 @@
 	/* NOTE: dlbuffer RID stores the address in AUX format */
 	dlbufaddr =
 	    HFA384x_ADDR_AUX_MKFLAT(hw->bufinfo.page, hw->bufinfo.offset);
-	printk(KERN_DEBUG
-	       "dlbuf.page=0x%04x dlbuf.offset=0x%04x dlbufaddr=0x%08x\n",
-	       hw->bufinfo.page, hw->bufinfo.offset, dlbufaddr);
+	pr_debug("dlbuf.page=0x%04x dlbuf.offset=0x%04x dlbufaddr=0x%08x\n",
+		 hw->bufinfo.page, hw->bufinfo.offset, dlbufaddr);
 
 #if 0
 	printk(KERN_WARNING "dlbuf@0x%06lx len=%d to=%d\n", dlbufaddr,
@@ -2154,7 +2143,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_getconfig(hfa384x_t *hw, u16 rid, void *buf, u16 len)
+int hfa384x_drvr_getconfig(hfa384x_t * hw, u16 rid, void *buf, u16 len)
 {
 	int result;
 
@@ -2191,7 +2180,7 @@
  *       Any
  ----------------------------------------------------------------*/
 int
-hfa384x_drvr_getconfig_async(hfa384x_t *hw,
+hfa384x_drvr_getconfig_async(hfa384x_t * hw,
 			     u16 rid, ctlx_usercb_t usercb, void *usercb_data)
 {
 	return hfa384x_dorrid_async(hw, rid, NULL, 0,
@@ -2222,7 +2211,7 @@
  *       process
  ----------------------------------------------------------------*/
 int
-hfa384x_drvr_setconfig_async(hfa384x_t *hw,
+hfa384x_drvr_setconfig_async(hfa384x_t * hw,
 			     u16 rid,
 			     void *buf,
 			     u16 len, ctlx_usercb_t usercb, void *usercb_data)
@@ -2249,7 +2238,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_ramdl_disable(hfa384x_t *hw)
+int hfa384x_drvr_ramdl_disable(hfa384x_t * hw)
 {
 	/* Check that we're already in the download state */
 	if (hw->dlstate != HFA384x_DLSTATE_RAMENABLED)
@@ -2289,7 +2278,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_ramdl_enable(hfa384x_t *hw, u32 exeaddr)
+int hfa384x_drvr_ramdl_enable(hfa384x_t * hw, u32 exeaddr)
 {
 	int result = 0;
 	u16 lowaddr;
@@ -2324,9 +2313,8 @@
 		/* Set the download state */
 		hw->dlstate = HFA384x_DLSTATE_RAMENABLED;
 	} else {
-		printk(KERN_DEBUG
-		       "cmd_download(0x%04x, 0x%04x) failed, result=%d.\n",
-		       lowaddr, hiaddr, result);
+		pr_debug("cmd_download(0x%04x, 0x%04x) failed, result=%d.\n",
+			 lowaddr, hiaddr, result);
 	}
 
 	return result;
@@ -2358,7 +2346,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_ramdl_write(hfa384x_t *hw, u32 daddr, void *buf, u32 len)
+int hfa384x_drvr_ramdl_write(hfa384x_t * hw, u32 daddr, void *buf, u32 len)
 {
 	int result = 0;
 	int nwrites;
@@ -2437,7 +2425,7 @@
 * Call context:
 *	process or non-card interrupt.
 ----------------------------------------------------------------*/
-int hfa384x_drvr_readpda(hfa384x_t *hw, void *buf, unsigned int len)
+int hfa384x_drvr_readpda(hfa384x_t * hw, void *buf, unsigned int len)
 {
 	int result = 0;
 	u16 *pda = buf;
@@ -2543,7 +2531,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_setconfig(hfa384x_t *hw, u16 rid, void *buf, u16 len)
+int hfa384x_drvr_setconfig(hfa384x_t * hw, u16 rid, void *buf, u16 len)
 {
 	return hfa384x_dowrid_wait(hw, rid, buf, len);
 }
@@ -2568,7 +2556,7 @@
 *	process
 ----------------------------------------------------------------*/
 
-int hfa384x_drvr_start(hfa384x_t *hw)
+int hfa384x_drvr_start(hfa384x_t * hw)
 {
 	int result, result1, result2;
 	u16 status;
@@ -2630,11 +2618,10 @@
 			usb_kill_urb(&hw->rx_urb);
 			goto done;
 		} else {
-			printk(KERN_DEBUG
-			       "First cmd_initialize() failed (result %d),\n",
-			       result1);
-			printk(KERN_DEBUG
-			       "but second attempt succeeded. All should be ok\n");
+			pr_debug("First cmd_initialize() failed (result %d),\n",
+				 result1);
+			pr_debug
+			    ("but second attempt succeeded. All should be ok\n");
 		}
 	} else if (result2 != 0) {
 		printk(KERN_WARNING
@@ -2670,7 +2657,7 @@
 * Call context:
 *	process
 ----------------------------------------------------------------*/
-int hfa384x_drvr_stop(hfa384x_t *hw)
+int hfa384x_drvr_stop(hfa384x_t * hw)
 {
 	int result = 0;
 	int i;
@@ -2721,9 +2708,9 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-int hfa384x_drvr_txframe(hfa384x_t *hw, struct sk_buff *skb,
-			 p80211_hdr_t *p80211_hdr,
-			 p80211_metawep_t *p80211_wep)
+int hfa384x_drvr_txframe(hfa384x_t * hw, struct sk_buff *skb,
+			 p80211_hdr_t * p80211_hdr,
+			 p80211_metawep_t * p80211_wep)
 {
 	int usbpktlen = sizeof(hfa384x_tx_frame_t);
 	int result;
@@ -2814,7 +2801,7 @@
 	return result;
 }
 
-void hfa384x_tx_timeout(wlandevice_t *wlandev)
+void hfa384x_tx_timeout(wlandevice_t * wlandev)
 {
 	hfa384x_t *hw = wlandev->priv;
 	unsigned long flags;
@@ -2963,8 +2950,8 @@
 * Call context:
 *	Either process or interrupt, but presumably interrupt
 ----------------------------------------------------------------*/
-static int unlocked_usbctlx_cancel_async(hfa384x_t *hw,
-					 hfa384x_usbctlx_t *ctlx)
+static int unlocked_usbctlx_cancel_async(hfa384x_t * hw,
+					 hfa384x_usbctlx_t * ctlx)
 {
 	int ret;
 
@@ -3013,7 +3000,7 @@
 * Call context:
 *	Either, assume interrupt
 ----------------------------------------------------------------*/
-static void unlocked_usbctlx_complete(hfa384x_t *hw, hfa384x_usbctlx_t *ctlx)
+static void unlocked_usbctlx_complete(hfa384x_t * hw, hfa384x_usbctlx_t * ctlx)
 {
 	/* Timers have been stopped, and ctlx should be in
 	 * a terminal state. Retire it from the "active"
@@ -3030,8 +3017,7 @@
 
 	default:
 		printk(KERN_ERR "CTLX[%d] not in a terminating state(%s)\n",
-		       le16_to_cpu(ctlx->outbuf.type),
-		       ctlxstr(ctlx->state));
+		       le16_to_cpu(ctlx->outbuf.type), ctlxstr(ctlx->state));
 		break;
 	}			/* switch */
 }
@@ -3052,7 +3038,7 @@
 * Call context:
 *	any
 ----------------------------------------------------------------*/
-static void hfa384x_usbctlxq_run(hfa384x_t *hw)
+static void hfa384x_usbctlxq_run(hfa384x_t * hw)
 {
 	unsigned long flags;
 
@@ -3226,14 +3212,13 @@
 
 	case -ENOENT:
 	case -ECONNRESET:
-		pr_debug("status=%d, urb explicitly unlinked.\n",
-		       urb->status);
+		pr_debug("status=%d, urb explicitly unlinked.\n", urb->status);
 		action = ABORT;
 		break;
 
 	default:
 		pr_debug("urb status=%d, transfer flags=0x%x\n",
-		       urb->status, urb->transfer_flags);
+			 urb->status, urb->transfer_flags);
 		++(wlandev->linux_stats.rx_errors);
 		action = RESUBMIT;
 		break;
@@ -3293,18 +3278,17 @@
 
 	case HFA384x_USB_BUFAVAIL:
 		pr_debug("Received BUFAVAIL packet, frmlen=%d\n",
-		       usbin->bufavail.frmlen);
+			 usbin->bufavail.frmlen);
 		break;
 
 	case HFA384x_USB_ERROR:
 		pr_debug("Received USB_ERROR packet, errortype=%d\n",
-		       usbin->usberror.errortype);
+			 usbin->usberror.errortype);
 		break;
 
 	default:
-		printk(KERN_DEBUG
-		       "Unrecognized USBIN packet, type=%x, status=%d\n",
-		       usbin->type, urb_status);
+		pr_debug("Unrecognized USBIN packet, type=%x, status=%d\n",
+			 usbin->type, urb_status);
 		break;
 	}			/* switch */
 
@@ -3334,7 +3318,7 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void hfa384x_usbin_ctlx(hfa384x_t *hw, hfa384x_usbin_t *usbin,
+static void hfa384x_usbin_ctlx(hfa384x_t * hw, hfa384x_usbin_t * usbin,
 			       int urb_status)
 {
 	hfa384x_usbctlx_t *ctlx;
@@ -3400,8 +3384,8 @@
 			 * our request has been acknowledged. Odd,
 			 * but our OUT URB is still alive...
 			 */
-			printk(KERN_DEBUG
-			       "Causality violation: please reboot Universe, or email linux-wlan-devel@lists.linux-wlan.com\n");
+			pr_debug
+			    ("Causality violation: please reboot Universe, or email linux-wlan-devel@lists.linux-wlan.com\n");
 			ctlx->state = CTLX_RESP_COMPLETE;
 			break;
 
@@ -3455,8 +3439,8 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void hfa384x_usbin_txcompl(wlandevice_t *wlandev,
-				  hfa384x_usbin_t *usbin)
+static void hfa384x_usbin_txcompl(wlandevice_t * wlandev,
+				  hfa384x_usbin_t * usbin)
 {
 	u16 status;
 
@@ -3486,7 +3470,7 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void hfa384x_usbin_rx(wlandevice_t *wlandev, struct sk_buff *skb)
+static void hfa384x_usbin_rx(wlandevice_t * wlandev, struct sk_buff *skb)
 {
 	hfa384x_usbin_t *usbin = (hfa384x_usbin_t *) skb->data;
 	hfa384x_t *hw = wlandev->priv;
@@ -3553,8 +3537,7 @@
 			hfa384x_int_rxmonitor(wlandev, &usbin->rxfrm);
 			dev_kfree_skb(skb);
 		} else {
-			printk(KERN_DEBUG
-			       "Received monitor frame: FCSerr set\n");
+			pr_debug("Received monitor frame: FCSerr set\n");
 		}
 		break;
 
@@ -3590,8 +3573,8 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void hfa384x_int_rxmonitor(wlandevice_t *wlandev,
-				  hfa384x_usb_rxfrm_t *rxfrm)
+static void hfa384x_int_rxmonitor(wlandevice_t * wlandev,
+				  hfa384x_usb_rxfrm_t * rxfrm)
 {
 	hfa384x_rx_frame_t *rxdesc = &(rxfrm->desc);
 	unsigned int hdrlen = 0;
@@ -3616,7 +3599,7 @@
 	    (sizeof(p80211_caphdr_t) +
 	     WLAN_HDR_A4_LEN + WLAN_DATA_MAXLEN + WLAN_CRC_LEN)) {
 		pr_debug("overlen frm: len=%zd\n",
-		       skblen - sizeof(p80211_caphdr_t));
+			 skblen - sizeof(p80211_caphdr_t));
 	}
 
 	if ((skb = dev_alloc_skb(skblen)) == NULL) {
@@ -4072,7 +4055,7 @@
 * Call context:
 *	process or interrupt
 ----------------------------------------------------------------*/
-static int hfa384x_usbctlx_submit(hfa384x_t *hw, hfa384x_usbctlx_t *ctlx)
+static int hfa384x_usbctlx_submit(hfa384x_t * hw, hfa384x_usbctlx_t * ctlx)
 {
 	unsigned long flags;
 	int ret;
@@ -4113,7 +4096,7 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void hfa384x_usbout_tx(wlandevice_t *wlandev, hfa384x_usbout_t *usbout)
+static void hfa384x_usbout_tx(wlandevice_t * wlandev, hfa384x_usbout_t * usbout)
 {
 	prism2sta_ev_alloc(wlandev);
 }
@@ -4172,15 +4155,13 @@
 	default:
 		if (pdrcode < 0x1000) {
 			/* code is OK, but we don't know exactly what it is */
-			printk(KERN_DEBUG
-			       "Encountered unknown PDR#=0x%04x, "
-			       "assuming it's ok.\n", pdrcode);
+			pr_debug("Encountered unknown PDR#=0x%04x, "
+				 "assuming it's ok.\n", pdrcode);
 			return 1;
 		} else {
 			/* bad code */
-			printk(KERN_DEBUG
-			       "Encountered unknown PDR#=0x%04x, "
-			       "(>=0x1000), assuming it's bad.\n", pdrcode);
+			pr_debug("Encountered unknown PDR#=0x%04x, "
+				 "(>=0x1000), assuming it's bad.\n", pdrcode);
 			return 0;
 		}
 		break;
diff --git a/drivers/staging/wlan-ng/p80211conv.c b/drivers/staging/wlan-ng/p80211conv.c
index 2abce0c..8b4f396 100644
--- a/drivers/staging/wlan-ng/p80211conv.c
+++ b/drivers/staging/wlan-ng/p80211conv.c
@@ -102,9 +102,9 @@
 * Call context:
 *	May be called in interrupt or non-interrupt context
 ----------------------------------------------------------------*/
-int skb_ether_to_p80211(wlandevice_t *wlandev, u32 ethconv,
-			struct sk_buff *skb, p80211_hdr_t *p80211_hdr,
-			p80211_metawep_t *p80211_wep)
+int skb_ether_to_p80211(wlandevice_t * wlandev, u32 ethconv,
+			struct sk_buff *skb, p80211_hdr_t * p80211_hdr,
+			p80211_metawep_t * p80211_wep)
 {
 
 	u16 fc;
@@ -209,8 +209,8 @@
 
 		if ((foo = wep_encrypt(wlandev, skb->data, p80211_wep->data,
 				       skb->len,
-				       (wlandev->
-					hostwep & HOSTWEP_DEFAULTKEY_MASK),
+				       (wlandev->hostwep &
+					HOSTWEP_DEFAULTKEY_MASK),
 				       p80211_wep->iv, p80211_wep->icv))) {
 			printk(KERN_WARNING
 			       "Host en-WEP failed, dropping frame (%d).\n",
@@ -230,8 +230,8 @@
 }
 
 /* jkriegl: from orinoco, modified */
-static void orinoco_spy_gather(wlandevice_t *wlandev, char *mac,
-			       p80211_rxmeta_t *rxmeta)
+static void orinoco_spy_gather(wlandevice_t * wlandev, char *mac,
+			       p80211_rxmeta_t * rxmeta)
 {
 	int i;
 
@@ -272,7 +272,7 @@
 * Call context:
 *	May be called in interrupt or non-interrupt context
 ----------------------------------------------------------------*/
-int skb_p80211_to_ether(wlandevice_t *wlandev, u32 ethconv,
+int skb_p80211_to_ether(wlandevice_t * wlandev, u32 ethconv,
 			struct sk_buff *skb)
 {
 	netdevice_t *netdev = wlandev->netdev;
@@ -329,9 +329,8 @@
 				       skb->data + payload_offset +
 				       payload_length - 4))) {
 			/* de-wep failed, drop skb. */
-			printk(KERN_DEBUG
-			       "Host de-WEP failed, dropping frame (%d).\n",
-			       foo);
+			pr_debug("Host de-WEP failed, dropping frame (%d).\n",
+				 foo);
 			wlandev->rx.decrypt_err++;
 			return 2;
 		}
diff --git a/drivers/staging/wlan-ng/p80211conv.h b/drivers/staging/wlan-ng/p80211conv.h
index 6fe163b..0c62df1 100644
--- a/drivers/staging/wlan-ng/p80211conv.h
+++ b/drivers/staging/wlan-ng/p80211conv.h
@@ -153,8 +153,8 @@
 int skb_p80211_to_ether(struct wlandevice *wlandev, u32 ethconv,
 			struct sk_buff *skb);
 int skb_ether_to_p80211(struct wlandevice *wlandev, u32 ethconv,
-			struct sk_buff *skb, p80211_hdr_t *p80211_hdr,
-			p80211_metawep_t *p80211_wep);
+			struct sk_buff *skb, p80211_hdr_t * p80211_hdr,
+			p80211_metawep_t * p80211_wep);
 
 int p80211_stt_findproto(u16 proto);
 
diff --git a/drivers/staging/wlan-ng/p80211hdr.h b/drivers/staging/wlan-ng/p80211hdr.h
index ded4775..1703c92 100644
--- a/drivers/staging/wlan-ng/p80211hdr.h
+++ b/drivers/staging/wlan-ng/p80211hdr.h
@@ -68,8 +68,6 @@
 /*================================================================*/
 /* Project Includes */
 
-
-
 /*================================================================*/
 /* Constants */
 
@@ -188,7 +186,6 @@
 	p80211_hdr_a4_t a4;
 } __attribute__ ((packed)) p80211_hdr_t;
 
-
 /* Frame and header length macros */
 
 #define WLAN_CTL_FRAMELEN(fstype) (\
diff --git a/drivers/staging/wlan-ng/p80211meta.h b/drivers/staging/wlan-ng/p80211meta.h
index 2f3c9fc..c1a677b 100644
--- a/drivers/staging/wlan-ng/p80211meta.h
+++ b/drivers/staging/wlan-ng/p80211meta.h
@@ -60,7 +60,6 @@
 /*================================================================*/
 /* Project Includes */
 
-
 /*================================================================*/
 /* Types */
 
diff --git a/drivers/staging/wlan-ng/p80211metadef.h b/drivers/staging/wlan-ng/p80211metadef.h
index a29d6ae..da8b6f5 100644
--- a/drivers/staging/wlan-ng/p80211metadef.h
+++ b/drivers/staging/wlan-ng/p80211metadef.h
@@ -50,6 +50,14 @@
 #define DIDmsg_dot11req_mibget \
 			(P80211DID_MKSECTION(1) | \
 			P80211DID_MKGROUP(1))
+#define DIDmsg_dot11req_mibget_mibattribute \
+			(P80211DID_MKSECTION(1) | \
+			P80211DID_MKGROUP(1) | \
+			P80211DID_MKITEM(1) | 0x00000000)
+#define DIDmsg_dot11req_mibget_resultcode \
+			(P80211DID_MKSECTION(1) | \
+			P80211DID_MKGROUP(1) | \
+			P80211DID_MKITEM(2) | 0x00000000)
 #define DIDmsg_dot11req_mibset \
 			(P80211DID_MKSECTION(1) | \
 			P80211DID_MKGROUP(2))
@@ -94,12 +102,48 @@
 #define DIDmsg_p2req_readpda \
 			(P80211DID_MKSECTION(5) | \
 			P80211DID_MKGROUP(2))
+#define DIDmsg_p2req_readpda_pda \
+			(P80211DID_MKSECTION(5) | \
+			P80211DID_MKGROUP(2) | \
+			P80211DID_MKITEM(1) | 0x00000000)
+#define DIDmsg_p2req_readpda_resultcode \
+			(P80211DID_MKSECTION(5) | \
+			P80211DID_MKGROUP(2) | \
+			P80211DID_MKITEM(2) | 0x00000000)
 #define DIDmsg_p2req_ramdl_state \
 			(P80211DID_MKSECTION(5) | \
 			P80211DID_MKGROUP(11))
+#define DIDmsg_p2req_ramdl_state_enable \
+			(P80211DID_MKSECTION(5) | \
+			P80211DID_MKGROUP(11) | \
+			P80211DID_MKITEM(1) | 0x00000000)
+#define DIDmsg_p2req_ramdl_state_exeaddr \
+			(P80211DID_MKSECTION(5) | \
+			P80211DID_MKGROUP(11) | \
+			P80211DID_MKITEM(2) | 0x00000000)
+#define DIDmsg_p2req_ramdl_state_resultcode \
+			(P80211DID_MKSECTION(5) | \
+			P80211DID_MKGROUP(11) | \
+			P80211DID_MKITEM(3) | 0x00000000)
 #define DIDmsg_p2req_ramdl_write \
 			(P80211DID_MKSECTION(5) | \
 			P80211DID_MKGROUP(12))
+#define DIDmsg_p2req_ramdl_write_addr \
+			(P80211DID_MKSECTION(5) | \
+			P80211DID_MKGROUP(12) | \
+			P80211DID_MKITEM(1) | 0x00000000)
+#define DIDmsg_p2req_ramdl_write_len \
+			(P80211DID_MKSECTION(5) | \
+			P80211DID_MKGROUP(12) | \
+			P80211DID_MKITEM(2) | 0x00000000)
+#define DIDmsg_p2req_ramdl_write_data \
+			(P80211DID_MKSECTION(5) | \
+			P80211DID_MKGROUP(12) | \
+			P80211DID_MKITEM(3) | 0x00000000)
+#define DIDmsg_p2req_ramdl_write_resultcode \
+			(P80211DID_MKSECTION(5) | \
+			P80211DID_MKGROUP(12) | \
+			P80211DID_MKITEM(4) | 0x00000000)
 #define DIDmsg_p2req_flashdl_state \
 			(P80211DID_MKSECTION(5) | \
 			P80211DID_MKGROUP(13))
@@ -203,6 +247,10 @@
 			(P80211DID_MKSECTION(5) | \
 			P80211DID_MKGROUP(2) | \
 			P80211DID_MKITEM(1) | 0x18000000)
+#define DIDmib_p2_p2NIC_p2PRISupRange \
+			(P80211DID_MKSECTION(5) | \
+			P80211DID_MKGROUP(5) | \
+			P80211DID_MKITEM(6) | 0x10000000)
 #define DIDmib_p2_p2MAC \
 			(P80211DID_MKSECTION(5) | \
 			P80211DID_MKGROUP(6))
diff --git a/drivers/staging/wlan-ng/p80211mgmt.h b/drivers/staging/wlan-ng/p80211mgmt.h
index 6235fe7..c925a45 100644
--- a/drivers/staging/wlan-ng/p80211mgmt.h
+++ b/drivers/staging/wlan-ng/p80211mgmt.h
@@ -103,12 +103,10 @@
 /*================================================================*/
 /* Project Includes */
 
-
 #ifndef  _P80211HDR_H
 #include "p80211hdr.h"
 #endif
 
-
 /*================================================================*/
 /* Constants */
 
@@ -504,25 +502,25 @@
 
 } wlan_fr_deauthen_t;
 
-void wlan_mgmt_encode_beacon(wlan_fr_beacon_t *f);
-void wlan_mgmt_decode_beacon(wlan_fr_beacon_t *f);
-void wlan_mgmt_encode_disassoc(wlan_fr_disassoc_t *f);
-void wlan_mgmt_decode_disassoc(wlan_fr_disassoc_t *f);
-void wlan_mgmt_encode_assocreq(wlan_fr_assocreq_t *f);
-void wlan_mgmt_decode_assocreq(wlan_fr_assocreq_t *f);
-void wlan_mgmt_encode_assocresp(wlan_fr_assocresp_t *f);
-void wlan_mgmt_decode_assocresp(wlan_fr_assocresp_t *f);
-void wlan_mgmt_encode_reassocreq(wlan_fr_reassocreq_t *f);
-void wlan_mgmt_decode_reassocreq(wlan_fr_reassocreq_t *f);
-void wlan_mgmt_encode_reassocresp(wlan_fr_reassocresp_t *f);
-void wlan_mgmt_decode_reassocresp(wlan_fr_reassocresp_t *f);
-void wlan_mgmt_encode_probereq(wlan_fr_probereq_t *f);
-void wlan_mgmt_decode_probereq(wlan_fr_probereq_t *f);
-void wlan_mgmt_encode_proberesp(wlan_fr_proberesp_t *f);
-void wlan_mgmt_decode_proberesp(wlan_fr_proberesp_t *f);
-void wlan_mgmt_encode_authen(wlan_fr_authen_t *f);
-void wlan_mgmt_decode_authen(wlan_fr_authen_t *f);
-void wlan_mgmt_encode_deauthen(wlan_fr_deauthen_t *f);
-void wlan_mgmt_decode_deauthen(wlan_fr_deauthen_t *f);
+void wlan_mgmt_encode_beacon(wlan_fr_beacon_t * f);
+void wlan_mgmt_decode_beacon(wlan_fr_beacon_t * f);
+void wlan_mgmt_encode_disassoc(wlan_fr_disassoc_t * f);
+void wlan_mgmt_decode_disassoc(wlan_fr_disassoc_t * f);
+void wlan_mgmt_encode_assocreq(wlan_fr_assocreq_t * f);
+void wlan_mgmt_decode_assocreq(wlan_fr_assocreq_t * f);
+void wlan_mgmt_encode_assocresp(wlan_fr_assocresp_t * f);
+void wlan_mgmt_decode_assocresp(wlan_fr_assocresp_t * f);
+void wlan_mgmt_encode_reassocreq(wlan_fr_reassocreq_t * f);
+void wlan_mgmt_decode_reassocreq(wlan_fr_reassocreq_t * f);
+void wlan_mgmt_encode_reassocresp(wlan_fr_reassocresp_t * f);
+void wlan_mgmt_decode_reassocresp(wlan_fr_reassocresp_t * f);
+void wlan_mgmt_encode_probereq(wlan_fr_probereq_t * f);
+void wlan_mgmt_decode_probereq(wlan_fr_probereq_t * f);
+void wlan_mgmt_encode_proberesp(wlan_fr_proberesp_t * f);
+void wlan_mgmt_decode_proberesp(wlan_fr_proberesp_t * f);
+void wlan_mgmt_encode_authen(wlan_fr_authen_t * f);
+void wlan_mgmt_decode_authen(wlan_fr_authen_t * f);
+void wlan_mgmt_encode_deauthen(wlan_fr_deauthen_t * f);
+void wlan_mgmt_decode_deauthen(wlan_fr_deauthen_t * f);
 
 #endif /* _P80211MGMT_H */
diff --git a/drivers/staging/wlan-ng/p80211msg.h b/drivers/staging/wlan-ng/p80211msg.h
index f15a5d9..4ac7727 100644
--- a/drivers/staging/wlan-ng/p80211msg.h
+++ b/drivers/staging/wlan-ng/p80211msg.h
@@ -51,7 +51,6 @@
 /*================================================================*/
 /* Project Includes */
 
-
 #define WLAN_DEVNAMELEN_MAX	16
 
 /*--------------------------------------------------------------------*/
diff --git a/drivers/staging/wlan-ng/p80211netdev.c b/drivers/staging/wlan-ng/p80211netdev.c
index bc0d764..90f499e 100644
--- a/drivers/staging/wlan-ng/p80211netdev.c
+++ b/drivers/staging/wlan-ng/p80211netdev.c
@@ -49,7 +49,6 @@
 * --------------------------------------------------------------------
 */
 
-#include <linux/version.h>
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/sched.h>
@@ -95,18 +94,18 @@
 static void p80211netdev_rx_bh(unsigned long arg);
 
 /* netdevice method functions */
-static int p80211knetdev_init(netdevice_t *netdev);
-static struct net_device_stats *p80211knetdev_get_stats(netdevice_t *netdev);
-static int p80211knetdev_open(netdevice_t *netdev);
-static int p80211knetdev_stop(netdevice_t *netdev);
+static int p80211knetdev_init(netdevice_t * netdev);
+static struct net_device_stats *p80211knetdev_get_stats(netdevice_t * netdev);
+static int p80211knetdev_open(netdevice_t * netdev);
+static int p80211knetdev_stop(netdevice_t * netdev);
 static int p80211knetdev_hard_start_xmit(struct sk_buff *skb,
-					 netdevice_t *netdev);
-static void p80211knetdev_set_multicast_list(netdevice_t *dev);
-static int p80211knetdev_do_ioctl(netdevice_t *dev, struct ifreq *ifr,
+					 netdevice_t * netdev);
+static void p80211knetdev_set_multicast_list(netdevice_t * dev);
+static int p80211knetdev_do_ioctl(netdevice_t * dev, struct ifreq *ifr,
 				  int cmd);
-static int p80211knetdev_set_mac_address(netdevice_t *dev, void *addr);
-static void p80211knetdev_tx_timeout(netdevice_t *netdev);
-static int p80211_rx_typedrop(wlandevice_t *wlandev, u16 fc);
+static int p80211knetdev_set_mac_address(netdevice_t * dev, void *addr);
+static void p80211knetdev_tx_timeout(netdevice_t * netdev);
+static int p80211_rx_typedrop(wlandevice_t * wlandev, u16 fc);
 
 int wlan_watchdog = 5000;
 module_param(wlan_watchdog, int, 0644);
@@ -128,7 +127,7 @@
 * Returns:
 *	nothing
 ----------------------------------------------------------------*/
-static int p80211knetdev_init(netdevice_t *netdev)
+static int p80211knetdev_init(netdevice_t * netdev)
 {
 	/* Called in response to register_netdev */
 	/* This is usually the probe function, but the probe has */
@@ -151,7 +150,7 @@
 * Returns:
 *	the address of the statistics structure
 ----------------------------------------------------------------*/
-static struct net_device_stats *p80211knetdev_get_stats(netdevice_t *netdev)
+static struct net_device_stats *p80211knetdev_get_stats(netdevice_t * netdev)
 {
 	wlandevice_t *wlandev = netdev->ml_priv;
 
@@ -175,7 +174,7 @@
 * Returns:
 *	zero on success, non-zero otherwise
 ----------------------------------------------------------------*/
-static int p80211knetdev_open(netdevice_t *netdev)
+static int p80211knetdev_open(netdevice_t * netdev)
 {
 	int result = 0;		/* success */
 	wlandevice_t *wlandev = netdev->ml_priv;
@@ -210,7 +209,7 @@
 * Returns:
 *	zero on success, non-zero otherwise
 ----------------------------------------------------------------*/
-static int p80211knetdev_stop(netdevice_t *netdev)
+static int p80211knetdev_stop(netdevice_t * netdev)
 {
 	int result = 0;
 	wlandevice_t *wlandev = netdev->ml_priv;
@@ -237,7 +236,7 @@
 * Side effects:
 *
 ----------------------------------------------------------------*/
-void p80211netdev_rx(wlandevice_t *wlandev, struct sk_buff *skb)
+void p80211netdev_rx(wlandevice_t * wlandev, struct sk_buff *skb)
 {
 	/* Enqueue for post-irq processing */
 	skb_queue_tail(&wlandev->nsd_rxq, skb);
@@ -346,7 +345,7 @@
 *	zero on success, non-zero on failure.
 ----------------------------------------------------------------*/
 static int p80211knetdev_hard_start_xmit(struct sk_buff *skb,
-					 netdevice_t *netdev)
+					 netdevice_t * netdev)
 {
 	int result = 0;
 	int txresult = -1;
@@ -410,7 +409,7 @@
 		     &p80211_wep) != 0) {
 			/* convert failed */
 			pr_debug("ether_to_80211(%d) failed.\n",
-			       wlandev->ethconv);
+				 wlandev->ethconv);
 			result = 1;
 			goto failed;
 		}
@@ -473,7 +472,7 @@
 * Returns:
 *	nothing
 ----------------------------------------------------------------*/
-static void p80211knetdev_set_multicast_list(netdevice_t *dev)
+static void p80211knetdev_set_multicast_list(netdevice_t * dev)
 {
 	wlandevice_t *wlandev = dev->ml_priv;
 
@@ -486,7 +485,7 @@
 
 #ifdef SIOCETHTOOL
 
-static int p80211netdev_ethtool(wlandevice_t *wlandev, void __user *useraddr)
+static int p80211netdev_ethtool(wlandevice_t * wlandev, void __user * useraddr)
 {
 	u32 ethcmd;
 	struct ethtool_drvinfo info;
@@ -558,7 +557,7 @@
 *	Process thread (ioctl caller).  TODO: SMP support may require
 *	locks.
 ----------------------------------------------------------------*/
-static int p80211knetdev_do_ioctl(netdevice_t *dev, struct ifreq *ifr, int cmd)
+static int p80211knetdev_do_ioctl(netdevice_t * dev, struct ifreq *ifr, int cmd)
 {
 	int result = 0;
 	p80211ioctl_req_t *req = (p80211ioctl_req_t *) ifr;
@@ -567,8 +566,6 @@
 
 	pr_debug("rx'd ioctl, cmd=%d, len=%d\n", cmd, req->len);
 
-	mutex_lock(&wlandev->ioctl_lock);
-
 #ifdef SIOCETHTOOL
 	if (cmd == SIOCETHTOOL) {
 		result =
@@ -609,8 +606,6 @@
 		result = -ENOMEM;
 	}
 bail:
-	mutex_unlock(&wlandev->ioctl_lock);
-
 	return result;		/* If allocate,copyfrom or copyto fails, return errno */
 }
 
@@ -639,7 +634,7 @@
 *
 * by: Collin R. Mulliner <collin@mulliner.org>
 ----------------------------------------------------------------*/
-static int p80211knetdev_set_mac_address(netdevice_t *dev, void *addr)
+static int p80211knetdev_set_mac_address(netdevice_t * dev, void *addr)
 {
 	struct sockaddr *new_addr = addr;
 	p80211msg_dot11req_mibset_t dot11req;
@@ -654,7 +649,7 @@
 
 	/* Set up some convenience pointers. */
 	mibattr = &dot11req.mibattribute;
-	macaddr = (p80211item_pstr6_t *)&mibattr->data;
+	macaddr = (p80211item_pstr6_t *) & mibattr->data;
 	resultcode = &dot11req.resultcode;
 
 	/* Set up a dot11req_mibset */
@@ -682,7 +677,7 @@
 	resultcode->data = 0;
 
 	/* now fire the request */
-	result = p80211req_dorequest(dev->ml_priv, (u8 *)&dot11req);
+	result = p80211req_dorequest(dev->ml_priv, (u8 *) & dot11req);
 
 	/* If the request wasn't successful, report an error and don't
 	 * change the netdev address
@@ -699,7 +694,7 @@
 	return result;
 }
 
-static int wlan_change_mtu(netdevice_t *dev, int new_mtu)
+static int wlan_change_mtu(netdevice_t * dev, int new_mtu)
 {
 	/* 2312 is max 802.11 payload, 20 is overhead, (ether + llc +snap)
 	   and another 8 for wep. */
@@ -712,17 +707,17 @@
 }
 
 static const struct net_device_ops p80211_netdev_ops = {
-	.ndo_init		= p80211knetdev_init,
-	.ndo_open		= p80211knetdev_open,
-	.ndo_stop		= p80211knetdev_stop,
-	.ndo_get_stats		= p80211knetdev_get_stats,
-	.ndo_start_xmit		= p80211knetdev_hard_start_xmit,
-	.ndo_set_multicast_list	= p80211knetdev_set_multicast_list,
-	.ndo_do_ioctl		= p80211knetdev_do_ioctl,
-	.ndo_set_mac_address	= p80211knetdev_set_mac_address,
-	.ndo_tx_timeout		= p80211knetdev_tx_timeout,
-	.ndo_change_mtu		= wlan_change_mtu,
-	.ndo_validate_addr	= eth_validate_addr,
+	.ndo_init = p80211knetdev_init,
+	.ndo_open = p80211knetdev_open,
+	.ndo_stop = p80211knetdev_stop,
+	.ndo_get_stats = p80211knetdev_get_stats,
+	.ndo_start_xmit = p80211knetdev_hard_start_xmit,
+	.ndo_set_multicast_list = p80211knetdev_set_multicast_list,
+	.ndo_do_ioctl = p80211knetdev_do_ioctl,
+	.ndo_set_mac_address = p80211knetdev_set_mac_address,
+	.ndo_tx_timeout = p80211knetdev_tx_timeout,
+	.ndo_change_mtu = wlan_change_mtu,
+	.ndo_validate_addr = eth_validate_addr,
 };
 
 /*----------------------------------------------------------------
@@ -747,7 +742,7 @@
 *	compiled drivers, this function will be called in the
 *	context of the kernel startup code.
 ----------------------------------------------------------------*/
-int wlan_setup(wlandevice_t *wlandev)
+int wlan_setup(wlandevice_t * wlandev)
 {
 	int result = 0;
 	netdevice_t *dev;
@@ -772,11 +767,6 @@
 		dev->ml_priv = wlandev;
 		dev->netdev_ops = &p80211_netdev_ops;
 
-		mutex_init(&wlandev->ioctl_lock);
-		/* block ioctls until fully initialised. Don't forget to call
-		   allow_ioctls at some point!*/
-		mutex_lock(&wlandev->ioctl_lock);
-
 #if (WIRELESS_EXT < 21)
 		dev->get_wireless_stats = p80211wext_get_wireless_stats;
 #endif
@@ -810,7 +800,7 @@
 *	compiled drivers, this function will be called in the
 *	context of the kernel startup code.
 ----------------------------------------------------------------*/
-int wlan_unsetup(wlandevice_t *wlandev)
+int wlan_unsetup(wlandevice_t * wlandev)
 {
 	int result = 0;
 
@@ -846,7 +836,7 @@
 * Call Context:
 *	Can be either interrupt or not.
 ----------------------------------------------------------------*/
-int register_wlandev(wlandevice_t *wlandev)
+int register_wlandev(wlandevice_t * wlandev)
 {
 	int i = 0;
 
@@ -874,7 +864,7 @@
 * Call Context:
 *	Can be either interrupt or not.
 ----------------------------------------------------------------*/
-int unregister_wlandev(wlandevice_t *wlandev)
+int unregister_wlandev(wlandevice_t * wlandev)
 {
 	struct sk_buff *skb;
 
@@ -917,7 +907,7 @@
 * Call context:
 *	Usually interrupt.
 ----------------------------------------------------------------*/
-void p80211netdev_hwremoved(wlandevice_t *wlandev)
+void p80211netdev_hwremoved(wlandevice_t * wlandev)
 {
 	wlandev->hwremoved = 1;
 	if (wlandev->state == WLAN_DEVICE_OPEN)
@@ -947,7 +937,7 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static int p80211_rx_typedrop(wlandevice_t *wlandev, u16 fc)
+static int p80211_rx_typedrop(wlandevice_t * wlandev, u16 fc)
 {
 	u16 ftype;
 	u16 fstype;
@@ -1105,7 +1095,7 @@
 	return drop;
 }
 
-static void p80211knetdev_tx_timeout(netdevice_t *netdev)
+static void p80211knetdev_tx_timeout(netdevice_t * netdev)
 {
 	wlandevice_t *wlandev = netdev->ml_priv;
 
@@ -1117,8 +1107,3 @@
 		netif_wake_queue(wlandev->netdev);
 	}
 }
-
-void p80211_allow_ioctls(wlandevice_t *wlandev)
-{
-	mutex_unlock(&wlandev->ioctl_lock);
-}
diff --git a/drivers/staging/wlan-ng/p80211netdev.h b/drivers/staging/wlan-ng/p80211netdev.h
index b96090d..f4fcd2b 100644
--- a/drivers/staging/wlan-ng/p80211netdev.h
+++ b/drivers/staging/wlan-ng/p80211netdev.h
@@ -182,16 +182,16 @@
 	unsigned int ethconv;
 
 	/* device methods (init by MSD, used by p80211 */
-	int (*open) (struct wlandevice *wlandev);
-	int (*close) (struct wlandevice *wlandev);
-	void (*reset) (struct wlandevice *wlandev);
-	int (*txframe) (struct wlandevice *wlandev, struct sk_buff *skb,
-			p80211_hdr_t *p80211_hdr,
-			p80211_metawep_t *p80211_wep);
-	int (*mlmerequest) (struct wlandevice *wlandev, p80211msg_t *msg);
-	int (*set_multicast_list) (struct wlandevice *wlandev,
-				   netdevice_t *dev);
-	void (*tx_timeout) (struct wlandevice *wlandev);
+	int (*open) (struct wlandevice * wlandev);
+	int (*close) (struct wlandevice * wlandev);
+	void (*reset) (struct wlandevice * wlandev);
+	int (*txframe) (struct wlandevice * wlandev, struct sk_buff * skb,
+			p80211_hdr_t * p80211_hdr,
+			p80211_metawep_t * p80211_wep);
+	int (*mlmerequest) (struct wlandevice * wlandev, p80211msg_t * msg);
+	int (*set_multicast_list) (struct wlandevice * wlandev,
+				   netdevice_t * dev);
+	void (*tx_timeout) (struct wlandevice * wlandev);
 
 	/* 802.11 State */
 	u8 bssid[WLAN_BSSID_LEN];
@@ -227,22 +227,19 @@
 	u8 spy_number;
 	char spy_address[IW_MAX_SPY][ETH_ALEN];
 	struct iw_quality spy_stat[IW_MAX_SPY];
-
-	struct mutex ioctl_lock;
 } wlandevice_t;
 
 /* WEP stuff */
-int wep_change_key(wlandevice_t *wlandev, int keynum, u8 *key, int keylen);
-int wep_decrypt(wlandevice_t *wlandev, u8 *buf, u32 len, int key_override,
-		u8 *iv, u8 *icv);
-int wep_encrypt(wlandevice_t *wlandev, u8 *buf, u8 *dst, u32 len, int keynum,
-		u8 *iv, u8 *icv);
+int wep_change_key(wlandevice_t * wlandev, int keynum, u8 * key, int keylen);
+int wep_decrypt(wlandevice_t * wlandev, u8 * buf, u32 len, int key_override,
+		u8 * iv, u8 * icv);
+int wep_encrypt(wlandevice_t * wlandev, u8 * buf, u8 * dst, u32 len, int keynum,
+		u8 * iv, u8 * icv);
 
-int wlan_setup(wlandevice_t *wlandev);
-int wlan_unsetup(wlandevice_t *wlandev);
-int register_wlandev(wlandevice_t *wlandev);
-int unregister_wlandev(wlandevice_t *wlandev);
-void p80211netdev_rx(wlandevice_t *wlandev, struct sk_buff *skb);
-void p80211netdev_hwremoved(wlandevice_t *wlandev);
-void p80211_allow_ioctls(wlandevice_t *wlandev);
+int wlan_setup(wlandevice_t * wlandev);
+int wlan_unsetup(wlandevice_t * wlandev);
+int register_wlandev(wlandevice_t * wlandev);
+int unregister_wlandev(wlandevice_t * wlandev);
+void p80211netdev_rx(wlandevice_t * wlandev, struct sk_buff *skb);
+void p80211netdev_hwremoved(wlandevice_t * wlandev);
 #endif
diff --git a/drivers/staging/wlan-ng/p80211req.c b/drivers/staging/wlan-ng/p80211req.c
index 15ecba6..584c419 100644
--- a/drivers/staging/wlan-ng/p80211req.c
+++ b/drivers/staging/wlan-ng/p80211req.c
@@ -73,9 +73,9 @@
 #include "p80211metastruct.h"
 #include "p80211req.h"
 
-static void p80211req_handlemsg(wlandevice_t *wlandev, p80211msg_t *msg);
-static int p80211req_mibset_mibget(wlandevice_t *wlandev,
-				   p80211msg_dot11req_mibget_t *mib_msg,
+static void p80211req_handlemsg(wlandevice_t * wlandev, p80211msg_t * msg);
+static int p80211req_mibset_mibget(wlandevice_t * wlandev,
+				   p80211msg_dot11req_mibget_t * mib_msg,
 				   int isget);
 
 /*----------------------------------------------------------------
@@ -94,7 +94,7 @@
 *	Potentially blocks the caller, so it's a good idea to
 *	not call this function from an interrupt context.
 ----------------------------------------------------------------*/
-int p80211req_dorequest(wlandevice_t *wlandev, u8 *msgbuf)
+int p80211req_dorequest(wlandevice_t * wlandev, u8 * msgbuf)
 {
 	int result = 0;
 	p80211msg_t *msg = (p80211msg_t *) msgbuf;
@@ -129,7 +129,7 @@
 		wlandev->mlmerequest(wlandev, msg);
 
 	clear_bit(1, &(wlandev->request_pending));
-	return result; /* if result==0, msg->status still may contain an err */
+	return result;		/* if result==0, msg->status still may contain an err */
 }
 
 /*----------------------------------------------------------------
@@ -150,7 +150,7 @@
 * Call context:
 *	Process thread
 ----------------------------------------------------------------*/
-static void p80211req_handlemsg(wlandevice_t *wlandev, p80211msg_t *msg)
+static void p80211req_handlemsg(wlandevice_t * wlandev, p80211msg_t * msg)
 {
 	switch (msg->msgcode) {
 
@@ -180,8 +180,8 @@
 	return;
 }
 
-static int p80211req_mibset_mibget(wlandevice_t *wlandev,
-				   p80211msg_dot11req_mibget_t *mib_msg,
+static int p80211req_mibset_mibget(wlandevice_t * wlandev,
+				   p80211msg_dot11req_mibget_t * mib_msg,
 				   int isget)
 {
 	p80211itemd_t *mibitem = (p80211itemd_t *) mib_msg->mibattribute.data;
@@ -243,8 +243,8 @@
 			u32 *data = (u32 *) mibitem->data;
 
 			if (isget) {
-				if (wlandev->
-				    hostwep & HOSTWEP_EXCLUDEUNENCRYPTED)
+				if (wlandev->hostwep &
+				    HOSTWEP_EXCLUDEUNENCRYPTED)
 					*data = P80211ENUM_truth_true;
 				else
 					*data = P80211ENUM_truth_false;
diff --git a/drivers/staging/wlan-ng/p80211req.h b/drivers/staging/wlan-ng/p80211req.h
index a95a45a..5d91767 100644
--- a/drivers/staging/wlan-ng/p80211req.h
+++ b/drivers/staging/wlan-ng/p80211req.h
@@ -48,6 +48,6 @@
 #ifndef _LINUX_P80211REQ_H
 #define _LINUX_P80211REQ_H
 
-int p80211req_dorequest(wlandevice_t *wlandev, u8 *msgbuf);
+int p80211req_dorequest(wlandevice_t * wlandev, u8 * msgbuf);
 
 #endif
diff --git a/drivers/staging/wlan-ng/p80211types.h b/drivers/staging/wlan-ng/p80211types.h
index a22437c..043da1e 100644
--- a/drivers/staging/wlan-ng/p80211types.h
+++ b/drivers/staging/wlan-ng/p80211types.h
@@ -61,7 +61,6 @@
 /* Project Includes */
 /*================================================================*/
 
-
 /*----------------------------------------------------------------*/
 /* The following constants are indexes into the Mib Category List */
 /* and the Message Category List */
@@ -345,11 +344,11 @@
 /*  metadata items.  Some components may choose to use more, */
 /*  less or different metadata items. */
 
-typedef void (*p80211_totext_t) (struct catlistitem *, u32 did, u8 *itembuf,
+typedef void (*p80211_totext_t) (struct catlistitem *, u32 did, u8 * itembuf,
 				 char *textbuf);
-typedef void (*p80211_fromtext_t) (struct catlistitem *, u32 did, u8 *itembuf,
+typedef void (*p80211_fromtext_t) (struct catlistitem *, u32 did, u8 * itembuf,
 				   char *textbuf);
-typedef u32(*p80211_valid_t) (struct catlistitem *, u32 did, u8 *itembuf);
+typedef u32(*p80211_valid_t) (struct catlistitem *, u32 did, u8 * itembuf);
 
 /*----------------------------------------------------------------*/
 /* Enumeration Lists */
diff --git a/drivers/staging/wlan-ng/p80211wep.c b/drivers/staging/wlan-ng/p80211wep.c
index 405ce89..f0b4275 100644
--- a/drivers/staging/wlan-ng/p80211wep.c
+++ b/drivers/staging/wlan-ng/p80211wep.c
@@ -48,9 +48,6 @@
 /*================================================================*/
 /* System Includes */
 
-
-#include <linux/version.h>
-
 #include <linux/netdevice.h>
 #include <linux/wireless.h>
 #include <linux/slab.h>
@@ -77,58 +74,58 @@
 /* Local Static Definitions */
 
 static const u32 wep_crc32_table[256] = {
-        0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
-        0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
-        0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
-        0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
-        0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
-        0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
-        0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
-        0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
-        0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
-        0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
-        0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
-        0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
-        0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
-        0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
-        0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
-        0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
-        0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
-        0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
-        0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
-        0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
-        0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
-        0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
-        0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
-        0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
-        0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
-        0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
-        0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
-        0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
-        0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
-        0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
-        0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
-        0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
-        0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
-        0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
-        0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
-        0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
-        0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
-        0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
-        0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
-        0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
-        0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
-        0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
-        0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
-        0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
-        0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
-        0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
-        0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
-        0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
-        0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
-        0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
-        0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
-        0x2d02ef8dL
+	0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
+	0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
+	0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
+	0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
+	0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
+	0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
+	0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
+	0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
+	0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
+	0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
+	0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
+	0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
+	0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
+	0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
+	0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
+	0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
+	0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
+	0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
+	0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
+	0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
+	0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
+	0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
+	0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
+	0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
+	0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
+	0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
+	0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
+	0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
+	0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
+	0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
+	0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
+	0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
+	0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
+	0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
+	0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
+	0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
+	0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
+	0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
+	0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
+	0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
+	0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
+	0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
+	0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
+	0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
+	0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
+	0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
+	0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
+	0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
+	0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
+	0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
+	0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
+	0x2d02ef8dL
 };
 
 /*================================================================*/
@@ -139,17 +136,24 @@
 
 /* keylen in bytes! */
 
-int wep_change_key(wlandevice_t *wlandev, int keynum, u8* key, int keylen)
+int wep_change_key(wlandevice_t * wlandev, int keynum, u8 * key, int keylen)
 {
-	if (keylen < 0)  return -1;
-	if (keylen >= MAX_KEYLEN) return -1;
-	if (key == NULL) return -1;
-	if (keynum < 0)  return -1;
-	if (keynum >= NUM_WEPKEYS) return -1;
-
+	if (keylen < 0)
+		return -1;
+	if (keylen >= MAX_KEYLEN)
+		return -1;
+	if (key == NULL)
+		return -1;
+	if (keynum < 0)
+		return -1;
+	if (keynum >= NUM_WEPKEYS)
+		return -1;
 
 #ifdef WEP_DEBUG
-	printk(KERN_DEBUG "WEP key %d len %d = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", keynum, keylen, key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7]);
+	printk(KERN_DEBUG
+	       "WEP key %d len %d = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
+	       keynum, keylen, key[0], key[1], key[2], key[3], key[4], key[5],
+	       key[6], key[7]);
 #endif
 
 	wlandev->wep_keylens[keynum] = keylen;
@@ -162,14 +166,16 @@
   4-byte IV at start of buffer, 4-byte ICV at end of buffer.
   if successful, buf start is payload begin, length -= 8;
  */
-int wep_decrypt(wlandevice_t *wlandev, u8 *buf, u32 len, int key_override, u8 *iv, u8 *icv)
+int wep_decrypt(wlandevice_t * wlandev, u8 * buf, u32 len, int key_override,
+		u8 * iv, u8 * icv)
 {
 	u32 i, j, k, crc, keylen;
 	u8 s[256], key[64], c_crc[4];
 	u8 keyidx;
 
 	/* Needs to be at least 8 bytes of payload */
-	if (len <= 0) return -1;
+	if (len <= 0)
+		return -1;
 
 	/* initialize the first bytes of the key from the IV */
 	key[0] = iv[0];
@@ -180,19 +186,24 @@
 	if (key_override >= 0)
 		keyidx = key_override;
 
-	if (keyidx >= NUM_WEPKEYS) return -2;
+	if (keyidx >= NUM_WEPKEYS)
+		return -2;
 
 	keylen = wlandev->wep_keylens[keyidx];
 
-	if (keylen == 0) return -3;
+	if (keylen == 0)
+		return -3;
 
 	/* copy the rest of the key over from the designated key */
-	memcpy(key+3, wlandev->wep_keys[keyidx], keylen);
+	memcpy(key + 3, wlandev->wep_keys[keyidx], keylen);
 
-	keylen+=3;  /* add in IV bytes */
+	keylen += 3;		/* add in IV bytes */
 
 #ifdef WEP_DEBUG
-	printk(KERN_DEBUG "D %d: %02x %02x %02x (%d %d) %02x:%02x:%02x:%02x:%02x\n", len, key[0], key[1], key[2], keyidx, keylen, key[3], key[4], key[5], key[6], key[7]);
+	printk(KERN_DEBUG
+	       "D %d: %02x %02x %02x (%d %d) %02x:%02x:%02x:%02x:%02x\n", len,
+	       key[0], key[1], key[2], keyidx, keylen, key[3], key[4], key[5],
+	       key[6], key[7]);
 #endif
 
 	/* set up the RC4 state */
@@ -201,16 +212,16 @@
 	j = 0;
 	for (i = 0; i < 256; i++) {
 		j = (j + s[i] + key[i % keylen]) & 0xff;
-		swap(i,j);
+		swap(i, j);
 	}
 
 	/* Apply the RC4 to the data, update the CRC32 */
 	crc = ~0;
 	i = j = 0;
 	for (k = 0; k < len; k++) {
-		i = (i+1) & 0xff;
-		j = (j+s[i]) & 0xff;
-		swap(i,j);
+		i = (i + 1) & 0xff;
+		j = (j + s[i]) & 0xff;
+		swap(i, j);
 		buf[k] ^= s[(s[i] + s[j]) & 0xff];
 		crc = wep_crc32_table[(crc ^ buf[k]) & 0xff] ^ (crc >> 8);
 	}
@@ -224,28 +235,32 @@
 
 	for (k = 0; k < 4; k++) {
 		i = (i + 1) & 0xff;
-		j = (j+s[i]) & 0xff;
-		swap(i,j);
+		j = (j + s[i]) & 0xff;
+		swap(i, j);
 		if ((c_crc[k] ^ s[(s[i] + s[j]) & 0xff]) != icv[k])
-			return -(4 | (k << 4)) ; /* ICV mismatch */
+			return -(4 | (k << 4));	/* ICV mismatch */
 	}
 
 	return 0;
 }
 
 /* encrypts in-place. */
-int wep_encrypt(wlandevice_t *wlandev, u8 *buf, u8 *dst, u32 len, int keynum, u8 *iv, u8 *icv)
+int wep_encrypt(wlandevice_t * wlandev, u8 * buf, u8 * dst, u32 len, int keynum,
+		u8 * iv, u8 * icv)
 {
 	u32 i, j, k, crc, keylen;
 	u8 s[256], key[64];
 
 	/* no point in WEPping an empty frame */
-	if (len <= 0) return -1;
+	if (len <= 0)
+		return -1;
 
 	/* we need to have a real key.. */
-	if (keynum >= NUM_WEPKEYS) return -2;
+	if (keynum >= NUM_WEPKEYS)
+		return -2;
 	keylen = wlandev->wep_keylens[keynum];
-	if (keylen <= 0) return -3;
+	if (keylen <= 0)
+		return -3;
 
 	/* use a random IV.  And skip known weak ones. */
 	get_random_bytes(iv, 3);
@@ -259,12 +274,15 @@
 	key[2] = iv[2];
 
 	/* copy the rest of the key over from the designated key */
-	memcpy(key+3, wlandev->wep_keys[keynum], keylen);
+	memcpy(key + 3, wlandev->wep_keys[keynum], keylen);
 
-	keylen+=3;  /* add in IV bytes */
+	keylen += 3;		/* add in IV bytes */
 
 #ifdef WEP_DEBUG
-	printk(KERN_DEBUG "E %d (%d/%d %d) %02x %02x %02x %02x:%02x:%02x:%02x:%02x\n", len,  iv[3], keynum, keylen, key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7]);
+	printk(KERN_DEBUG
+	       "E %d (%d/%d %d) %02x %02x %02x %02x:%02x:%02x:%02x:%02x\n", len,
+	       iv[3], keynum, keylen, key[0], key[1], key[2], key[3], key[4],
+	       key[5], key[6], key[7]);
 #endif
 
 	/* set up the RC4 state */
@@ -273,7 +291,7 @@
 	j = 0;
 	for (i = 0; i < 256; i++) {
 		j = (j + s[i] + key[i % keylen]) & 0xff;
-		swap(i,j);
+		swap(i, j);
 	}
 
 	/* Update CRC32 then apply RC4 to the data */
@@ -281,9 +299,9 @@
 	i = j = 0;
 	for (k = 0; k < len; k++) {
 		crc = wep_crc32_table[(crc ^ buf[k]) & 0xff] ^ (crc >> 8);
-		i = (i+1) & 0xff;
-		j = (j+s[i]) & 0xff;
-		swap(i,j);
+		i = (i + 1) & 0xff;
+		j = (j + s[i]) & 0xff;
+		swap(i, j);
 		dst[k] = buf[k] ^ s[(s[i] + s[j]) & 0xff];
 	}
 	crc = ~crc;
@@ -296,8 +314,8 @@
 
 	for (k = 0; k < 4; k++) {
 		i = (i + 1) & 0xff;
-		j = (j+s[i]) & 0xff;
-		swap(i,j);
+		j = (j + s[i]) & 0xff;
+		swap(i, j);
 		icv[k] ^= s[(s[i] + s[j]) & 0xff];
 	}
 
diff --git a/drivers/staging/wlan-ng/p80211wext.c b/drivers/staging/wlan-ng/p80211wext.c
index 96078b0..984e45d 100644
--- a/drivers/staging/wlan-ng/p80211wext.c
+++ b/drivers/staging/wlan-ng/p80211wext.c
@@ -37,8 +37,6 @@
 /*================================================================*/
 /* System Includes */
 
-
-
 #include <linux/kernel.h>
 #include <linux/sched.h>
 #include <linux/types.h>
@@ -68,10 +66,10 @@
 #include "p80211ioctl.h"
 #include "p80211req.h"
 
-static int p80211wext_giwrate(netdevice_t *dev,
+static int p80211wext_giwrate(netdevice_t * dev,
 			      struct iw_request_info *info,
 			      struct iw_param *rrq, char *extra);
-static int p80211wext_giwessid(netdevice_t *dev,
+static int p80211wext_giwessid(netdevice_t * dev,
 			       struct iw_request_info *info,
 			       struct iw_point *data, char *essid);
 
@@ -132,7 +130,7 @@
 	return 100;
 }
 
-static int p80211wext_dorequest(wlandevice_t *wlandev, u32 did, u32 data)
+static int p80211wext_dorequest(wlandevice_t * wlandev, u32 did, u32 data)
 {
 	p80211msg_dot11req_mibset_t msg;
 	p80211item_uint32_t mibitem;
@@ -142,12 +140,12 @@
 	mibitem.did = did;
 	mibitem.data = data;
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	return result;
 }
 
-static int p80211wext_autojoin(wlandevice_t *wlandev)
+static int p80211wext_autojoin(wlandevice_t * wlandev)
 {
 	p80211msg_lnxreq_autojoin_t msg;
 	struct iw_point data;
@@ -179,7 +177,7 @@
 	memcpy(msg.ssid.data.data, ssid, data.length);
 	msg.ssid.data.len = data.length;
 
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -216,7 +214,7 @@
 	if (wlandev->mlmerequest == NULL)
 		return NULL;
 
-	retval = wlandev->mlmerequest(wlandev, (p80211msg_t *)&quality);
+	retval = wlandev->mlmerequest(wlandev, (p80211msg_t *) & quality);
 
 	wstats->qual.qual = qual_as_percent(quality.link.data);	/* overall link quality */
 	wstats->qual.level = quality.level.data;	/* instant signal level */
@@ -234,7 +232,7 @@
 	return wstats;
 }
 
-static int p80211wext_giwname(netdevice_t *dev,
+static int p80211wext_giwname(netdevice_t * dev,
 			      struct iw_request_info *info,
 			      char *name, char *extra)
 {
@@ -263,7 +261,7 @@
 	return err;
 }
 
-static int p80211wext_giwfreq(netdevice_t *dev,
+static int p80211wext_giwfreq(netdevice_t * dev,
 			      struct iw_request_info *info,
 			      struct iw_freq *freq, char *extra)
 {
@@ -276,7 +274,7 @@
 	msg.msgcode = DIDmsg_dot11req_mibget;
 	mibitem.did = DIDmib_dot11phy_dot11PhyDSSSTable_dot11CurrentChannel;
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -298,7 +296,7 @@
 	return err;
 }
 
-static int p80211wext_siwfreq(netdevice_t *dev,
+static int p80211wext_siwfreq(netdevice_t * dev,
 			      struct iw_request_info *info,
 			      struct iw_freq *freq, char *extra)
 {
@@ -323,7 +321,7 @@
 		mibitem.data = p80211_mhz_to_channel(freq->m);
 
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -334,9 +332,9 @@
 	return err;
 }
 
-static int p80211wext_giwmode(netdevice_t *dev,
+static int p80211wext_giwmode(netdevice_t * dev,
 			      struct iw_request_info *info,
-			      __u32 *mode, char *extra)
+			      __u32 * mode, char *extra)
 {
 	wlandevice_t *wlandev = dev->ml_priv;
 
@@ -358,9 +356,9 @@
 	return 0;
 }
 
-static int p80211wext_siwmode(netdevice_t *dev,
+static int p80211wext_siwmode(netdevice_t * dev,
 			      struct iw_request_info *info,
-			      __u32 *mode, char *extra)
+			      __u32 * mode, char *extra)
 {
 	wlandevice_t *wlandev = dev->ml_priv;
 	p80211item_uint32_t mibitem;
@@ -404,7 +402,7 @@
 	mibitem.did = DIDmib_p2_p2Static_p2CnfPortType;
 	mibitem.data = (*mode == IW_MODE_ADHOC) ? 0 : 1;
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result)
 		err = -EFAULT;
@@ -413,7 +411,7 @@
 	return err;
 }
 
-static int p80211wext_giwrange(netdevice_t *dev,
+static int p80211wext_giwrange(netdevice_t * dev,
 			       struct iw_request_info *info,
 			       struct iw_point *data, char *extra)
 {
@@ -482,7 +480,7 @@
 	return 0;
 }
 
-static int p80211wext_giwap(netdevice_t *dev,
+static int p80211wext_giwap(netdevice_t * dev,
 			    struct iw_request_info *info,
 			    struct sockaddr *ap_addr, char *extra)
 {
@@ -495,7 +493,7 @@
 	return 0;
 }
 
-static int p80211wext_giwencode(netdevice_t *dev,
+static int p80211wext_giwencode(netdevice_t * dev,
 				struct iw_request_info *info,
 				struct iw_point *erq, char *key)
 {
@@ -536,7 +534,7 @@
 	return err;
 }
 
-static int p80211wext_siwencode(netdevice_t *dev,
+static int p80211wext_siwencode(netdevice_t * dev,
 				struct iw_request_info *info,
 				struct iw_point *erq, char *key)
 {
@@ -626,7 +624,7 @@
 
 			msg.msgcode = DIDmsg_dot11req_mibset;
 			memcpy(&msg.mibattribute.data, &pstr, sizeof(pstr));
-			result = p80211req_dorequest(wlandev, (u8 *)&msg);
+			result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 			if (result) {
 				err = -EFAULT;
@@ -683,7 +681,7 @@
 	return err;
 }
 
-static int p80211wext_giwessid(netdevice_t *dev,
+static int p80211wext_giwessid(netdevice_t * dev,
 			       struct iw_request_info *info,
 			       struct iw_point *data, char *essid)
 {
@@ -706,7 +704,7 @@
 	return 0;
 }
 
-static int p80211wext_siwessid(netdevice_t *dev,
+static int p80211wext_siwessid(netdevice_t * dev,
 			       struct iw_request_info *info,
 			       struct iw_point *data, char *essid)
 {
@@ -742,7 +740,7 @@
 	msg.ssid.data.len = length;
 
 	pr_debug("autojoin_ssid for %s \n", essid);
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 	pr_debug("autojoin_ssid %d\n", result);
 
 	if (result) {
@@ -754,7 +752,7 @@
 	return err;
 }
 
-static int p80211wext_siwcommit(netdevice_t *dev,
+static int p80211wext_siwcommit(netdevice_t * dev,
 				struct iw_request_info *info,
 				struct iw_point *data, char *essid)
 {
@@ -773,7 +771,7 @@
 	return err;
 }
 
-static int p80211wext_giwrate(netdevice_t *dev,
+static int p80211wext_giwrate(netdevice_t * dev,
 			      struct iw_request_info *info,
 			      struct iw_param *rrq, char *extra)
 {
@@ -786,7 +784,7 @@
 	msg.msgcode = DIDmsg_dot11req_mibget;
 	mibitem.did = DIDmib_p2_p2MAC_p2CurrentTxRate;
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -824,7 +822,7 @@
 	return err;
 }
 
-static int p80211wext_giwrts(netdevice_t *dev,
+static int p80211wext_giwrts(netdevice_t * dev,
 			     struct iw_request_info *info,
 			     struct iw_param *rts, char *extra)
 {
@@ -837,7 +835,7 @@
 	msg.msgcode = DIDmsg_dot11req_mibget;
 	mibitem.did = DIDmib_dot11mac_dot11OperationTable_dot11RTSThreshold;
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -854,7 +852,7 @@
 	return err;
 }
 
-static int p80211wext_siwrts(netdevice_t *dev,
+static int p80211wext_siwrts(netdevice_t * dev,
 			     struct iw_request_info *info,
 			     struct iw_param *rts, char *extra)
 {
@@ -877,7 +875,7 @@
 		mibitem.data = rts->value;
 
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -888,7 +886,7 @@
 	return err;
 }
 
-static int p80211wext_giwfrag(netdevice_t *dev,
+static int p80211wext_giwfrag(netdevice_t * dev,
 			      struct iw_request_info *info,
 			      struct iw_param *frag, char *extra)
 {
@@ -902,7 +900,7 @@
 	mibitem.did =
 	    DIDmib_dot11mac_dot11OperationTable_dot11FragmentationThreshold;
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -919,7 +917,7 @@
 	return err;
 }
 
-static int p80211wext_siwfrag(netdevice_t *dev,
+static int p80211wext_siwfrag(netdevice_t * dev,
 			      struct iw_request_info *info,
 			      struct iw_param *frag, char *extra)
 {
@@ -944,7 +942,7 @@
 		mibitem.data = frag->value;
 
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -963,7 +961,7 @@
 #define IW_RETRY_SHORT IW_RETRY_MIN
 #endif
 
-static int p80211wext_giwretry(netdevice_t *dev,
+static int p80211wext_giwretry(netdevice_t * dev,
 			       struct iw_request_info *info,
 			       struct iw_param *rrq, char *extra)
 {
@@ -978,7 +976,7 @@
 	mibitem.did = DIDmib_dot11mac_dot11OperationTable_dot11ShortRetryLimit;
 
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -992,7 +990,7 @@
 	mibitem.did = DIDmib_dot11mac_dot11OperationTable_dot11LongRetryLimit;
 
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -1007,7 +1005,7 @@
 	    DIDmib_dot11mac_dot11OperationTable_dot11MaxTransmitMSDULifetime;
 
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -1040,7 +1038,7 @@
 
 }
 
-static int p80211wext_siwretry(netdevice_t *dev,
+static int p80211wext_siwretry(netdevice_t * dev,
 			       struct iw_request_info *info,
 			       struct iw_param *rrq, char *extra)
 {
@@ -1068,7 +1066,7 @@
 		mibitem.data = rrq->value /= 1024;
 
 		memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-		result = p80211req_dorequest(wlandev, (u8 *)&msg);
+		result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 		if (result) {
 			err = -EFAULT;
@@ -1082,7 +1080,7 @@
 
 			memcpy(&msg.mibattribute.data, &mibitem,
 			       sizeof(mibitem));
-			result = p80211req_dorequest(wlandev, (u8 *)&msg);
+			result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 			if (result) {
 				err = -EFAULT;
@@ -1097,7 +1095,7 @@
 
 			memcpy(&msg.mibattribute.data, &mibitem,
 			       sizeof(mibitem));
-			result = p80211req_dorequest(wlandev, (u8 *)&msg);
+			result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 			if (result) {
 				err = -EFAULT;
@@ -1111,7 +1109,7 @@
 
 }
 
-static int p80211wext_siwtxpow(netdevice_t *dev,
+static int p80211wext_siwtxpow(netdevice_t * dev,
 			       struct iw_request_info *info,
 			       struct iw_param *rrq, char *extra)
 {
@@ -1134,7 +1132,7 @@
 	else
 		mibitem.data = rrq->value;
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -1145,7 +1143,7 @@
 	return err;
 }
 
-static int p80211wext_giwtxpow(netdevice_t *dev,
+static int p80211wext_giwtxpow(netdevice_t * dev,
 			       struct iw_request_info *info,
 			       struct iw_param *rrq, char *extra)
 {
@@ -1160,7 +1158,7 @@
 	    DIDmib_dot11phy_dot11PhyTxPowerTable_dot11CurrentTxPowerLevel;
 
 	memcpy(&msg.mibattribute.data, &mibitem, sizeof(mibitem));
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 
 	if (result) {
 		err = -EFAULT;
@@ -1180,7 +1178,7 @@
 	return err;
 }
 
-static int p80211wext_siwspy(netdevice_t *dev,
+static int p80211wext_siwspy(netdevice_t * dev,
 			     struct iw_request_info *info,
 			     struct iw_point *srq, char *extra)
 {
@@ -1215,7 +1213,7 @@
 }
 
 /* jkriegl: from orinoco, modified */
-static int p80211wext_giwspy(netdevice_t *dev,
+static int p80211wext_giwspy(netdevice_t * dev,
 			     struct iw_request_info *info,
 			     struct iw_point *srq, char *extra)
 {
@@ -1275,7 +1273,7 @@
 	return err;
 }
 
-static int p80211wext_siwscan(netdevice_t *dev,
+static int p80211wext_siwscan(netdevice_t * dev,
 			      struct iw_request_info *info,
 			      struct iw_point *srq, char *extra)
 {
@@ -1308,7 +1306,7 @@
 	msg.maxchanneltime.data = 250;
 	msg.minchanneltime.data = 200;
 
-	result = p80211req_dorequest(wlandev, (u8 *)&msg);
+	result = p80211req_dorequest(wlandev, (u8 *) & msg);
 	if (result)
 		err = prism2_result2err(msg.resultcode.data);
 
@@ -1322,7 +1320,7 @@
  */
 static char *wext_translate_bss(struct iw_request_info *info, char *current_ev,
 				char *end_buf,
-				p80211msg_dot11req_scan_results_t *bss)
+				p80211msg_dot11req_scan_results_t * bss)
 {
 	struct iw_event iwe;	/* Temporary buffer */
 
@@ -1406,7 +1404,7 @@
 	return current_ev;
 }
 
-static int p80211wext_giwscan(netdevice_t *dev,
+static int p80211wext_giwscan(netdevice_t * dev,
 			      struct iw_request_info *info,
 			      struct iw_point *srq, char *extra)
 {
@@ -1427,7 +1425,7 @@
 		msg.msgcode = DIDmsg_dot11req_scan_results;
 		msg.bssindex.data = i;
 
-		result = p80211req_dorequest(wlandev, (u8 *)&msg);
+		result = p80211req_dorequest(wlandev, (u8 *) & msg);
 		if ((result != 0) ||
 		    (msg.resultcode.data != P80211ENUM_resultcode_success)) {
 			break;
@@ -1466,7 +1464,7 @@
 	int idx = encoding->flags & IW_ENCODE_INDEX;
 
 	pr_debug("set_encode_ext flags[%d] alg[%d] keylen[%d]\n",
-	       ext->ext_flags, (int)ext->alg, (int)ext->key_len);
+		 ext->ext_flags, (int)ext->alg, (int)ext->key_len);
 
 	if (ext->ext_flags & IW_ENCODE_EXT_GROUP_KEY) {
 		/* set default key ? I'm not sure if this the the correct thing to do here */
@@ -1487,8 +1485,8 @@
 	}
 
 	if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY) {
-		if (!(ext->alg & IW_ENCODE_ALG_WEP)) {
-			pr_debug("asked to set a non wep key :(");
+		if (ext->alg != IW_ENCODE_ALG_WEP) {
+			pr_debug("asked to set a non wep key :(\n");
 			return -EINVAL;
 		}
 		if (idx) {
@@ -1502,7 +1500,7 @@
 		memcpy(wlandev->wep_keys[idx], ext->key, ext->key_len);
 
 		memset(&msg, 0, sizeof(msg));
-		pstr = (p80211item_pstr32_t *)&msg.mibattribute.data;
+		pstr = (p80211item_pstr32_t *) & msg.mibattribute.data;
 		memcpy(pstr->data.data, ext->key, ext->key_len);
 		pstr->data.len = ext->key_len;
 		switch (idx) {
@@ -1526,7 +1524,7 @@
 			break;
 		}
 		msg.msgcode = DIDmsg_dot11req_mibset;
-		result = p80211req_dorequest(wlandev, (u8 *)&msg);
+		result = p80211req_dorequest(wlandev, (u8 *) & msg);
 		pr_debug("result (%d)\n", result);
 	}
 	return result;
@@ -1546,12 +1544,11 @@
 	int idx;
 
 	pr_debug("get_encode_ext flags[%d] alg[%d] keylen[%d]\n",
-	       ext->ext_flags, (int)ext->alg, (int)ext->key_len);
+		 ext->ext_flags, (int)ext->alg, (int)ext->key_len);
 
 	max_len = encoding->length - sizeof(*ext);
 	if (max_len <= 0) {
-		pr_debug("get_encodeext max_len [%d] invalid\n",
-		       max_len);
+		pr_debug("get_encodeext max_len [%d] invalid\n", max_len);
 		result = -EINVAL;
 		goto exit;
 	}
@@ -1561,8 +1558,8 @@
 
 	if (idx) {
 		if (idx < 1 || idx > NUM_WEPKEYS) {
-			printk(KERN_DEBUG
-			       "get_encode_ext invalid key index [%d]\n", idx);
+			pr_debug("get_encode_ext invalid key index [%d]\n",
+				 idx);
 			result = -EINVAL;
 			goto exit;
 		}
@@ -1593,8 +1590,7 @@
 	struct iw_param *param = &wrqu->param;
 	int result = 0;
 
-	pr_debug("set_iwauth flags[%d]\n",
-	       (int)param->flags & IW_AUTH_INDEX);
+	pr_debug("set_iwauth flags[%d]\n", (int)param->flags & IW_AUTH_INDEX);
 
 	switch (param->flags & IW_AUTH_INDEX) {
 	case IW_AUTH_DROP_UNENCRYPTED:
@@ -1635,8 +1631,7 @@
 			wlandev->hostwep |= HOSTWEP_SHAREDKEY;
 		} else {
 			/* don't know what to do know  */
-			pr_debug("unknown AUTH_ALG (%d)\n",
-			       param->value);
+			pr_debug("unknown AUTH_ALG (%d)\n", param->value);
 			result = -EINVAL;
 		}
 		break;
@@ -1657,8 +1652,7 @@
 	struct iw_param *param = &wrqu->param;
 	int result = 0;
 
-	pr_debug("get_iwauth flags[%d]\n",
-	       (int)param->flags & IW_AUTH_INDEX);
+	pr_debug("get_iwauth flags[%d]\n", (int)param->flags & IW_AUTH_INDEX);
 
 	switch (param->flags & IW_AUTH_INDEX) {
 	case IW_AUTH_DROP_UNENCRYPTED:
@@ -1673,9 +1667,8 @@
 
 	case IW_AUTH_80211_AUTH_ALG:
 		param->value =
-		    wlandev->
-		    hostwep & HOSTWEP_SHAREDKEY ? IW_AUTH_ALG_SHARED_KEY :
-		    IW_AUTH_ALG_OPEN_SYSTEM;
+		    wlandev->hostwep & HOSTWEP_SHAREDKEY ?
+		    IW_AUTH_ALG_SHARED_KEY : IW_AUTH_ALG_OPEN_SYSTEM;
 		break;
 
 	default:
@@ -1755,7 +1748,7 @@
 	.get_wireless_stats = p80211wext_get_wireless_stats
 };
 
-int p80211wext_event_associated(wlandevice_t *wlandev, int assoc)
+int p80211wext_event_associated(wlandevice_t * wlandev, int assoc)
 {
 	union iwreq_data data;
 
diff --git a/drivers/staging/wlan-ng/prism2fw.c b/drivers/staging/wlan-ng/prism2fw.c
new file mode 100644
index 0000000..608b234
--- /dev/null
+++ b/drivers/staging/wlan-ng/prism2fw.c
@@ -0,0 +1,1406 @@
+/* from src/prism2/download/prism2dl.c
+*
+* utility for downloading prism2 images moved into kernelspace
+*
+* Copyright (C) 1999 AbsoluteValue Systems, Inc.  All Rights Reserved.
+* --------------------------------------------------------------------
+*
+* linux-wlan
+*
+*   The contents of this file are subject to the Mozilla Public
+*   License Version 1.1 (the "License"); you may not use this file
+*   except in compliance with the License. You may obtain a copy of
+*   the License at http://www.mozilla.org/MPL/
+*
+*   Software distributed under the License is distributed on an "AS
+*   IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
+*   implied. See the License for the specific language governing
+*   rights and limitations under the License.
+*
+*   Alternatively, the contents of this file may be used under the
+*   terms of the GNU Public License version 2 (the "GPL"), in which
+*   case the provisions of the GPL are applicable instead of the
+*   above.  If you wish to allow the use of your version of this file
+*   only under the terms of the GPL and not to allow others to use
+*   your version of this file under the MPL, indicate your decision
+*   by deleting the provisions above and replace them with the notice
+*   and other provisions required by the GPL.  If you do not delete
+*   the provisions above, a recipient may use your version of this
+*   file under either the MPL or the GPL.
+*
+* --------------------------------------------------------------------
+*
+* Inquiries regarding the linux-wlan Open Source project can be
+* made directly to:
+*
+* AbsoluteValue Systems Inc.
+* info@linux-wlan.com
+* http://www.linux-wlan.com
+*
+* --------------------------------------------------------------------
+*
+* Portions of the development of this software were funded by
+* Intersil Corporation as part of PRISM(R) chipset product development.
+*
+* --------------------------------------------------------------------
+*/
+
+/*================================================================*/
+/* System Includes */
+#include <linux/sort.h>
+#include <linux/firmware.h>
+
+/*================================================================*/
+/* Local Constants */
+
+#define PRISM2_USB_FWFILE	"prism2_ru.hex"
+
+#define S3DATA_MAX		5000
+#define S3PLUG_MAX		200
+#define S3CRC_MAX		200
+#define S3INFO_MAX		50
+#define SREC_LINE_MAX		264
+#define S3LEN_TXTOFFSET		2
+#define S3LEN_TXTLEN		2
+#define S3ADDR_TXTOFFSET	4
+#define S3ADDR_TXTLEN		8
+#define S3DATA_TXTOFFSET	12
+/*S3DATA_TXTLEN			variable, depends on len field */
+/*S3CKSUM_TXTOFFSET		variable, depends on len field */
+#define S3CKSUM_TXTLEN		2
+#define SERNUM_LEN_MAX		12
+
+#define S3PLUG_ITEMCODE_TXTOFFSET	(S3DATA_TXTOFFSET)
+#define S3PLUG_ITEMCODE_TXTLEN		8
+#define S3PLUG_ADDR_TXTOFFSET		(S3DATA_TXTOFFSET+8)
+#define S3PLUG_ADDR_TXTLEN		8
+#define S3PLUG_LEN_TXTOFFSET		(S3DATA_TXTOFFSET+16)
+#define S3PLUG_LEN_TXTLEN		8
+
+#define S3CRC_ADDR_TXTOFFSET		(S3DATA_TXTOFFSET)
+#define S3CRC_ADDR_TXTLEN		8
+#define S3CRC_LEN_TXTOFFSET		(S3DATA_TXTOFFSET+8)
+#define S3CRC_LEN_TXTLEN		8
+#define S3CRC_DOWRITE_TXTOFFSET		(S3DATA_TXTOFFSET+16)
+#define S3CRC_DOWRITE_TXTLEN		8
+
+#define S3INFO_LEN_TXTOFFSET		(S3DATA_TXTOFFSET)
+#define S3INFO_LEN_TXTLEN		4
+#define S3INFO_TYPE_TXTOFFSET		(S3DATA_TXTOFFSET+4)
+#define S3INFO_TYPE_TXTLEN		4
+#define S3INFO_DATA_TXTOFFSET		(S3DATA_TXTOFFSET+8)
+/* S3INFO_DATA_TXTLEN			variable, depends on INFO_LEN field */
+
+#define S3ADDR_PLUG		(0xff000000UL)
+#define S3ADDR_CRC		(0xff100000UL)
+#define S3ADDR_INFO		(0xff200000UL)
+
+#define PDAFILE_LINE_MAX	1024
+
+#define CHUNKS_MAX		100
+
+#define WRITESIZE_MAX		4096
+
+/*================================================================*/
+/* Local Macros */
+
+#define bswap_16(x) \
+     (__extension__							      \
+      ({ register unsigned short int __v, __x = (x);			      \
+	   __asm__ ("rorw $8, %w0"					      \
+		    : "=r" (__v)					      \
+		    : "0" (__x)						      \
+		    : "cc");						      \
+	 __v; }))
+
+#define bswap_32(x) \
+     (__extension__							      \
+      ({ register unsigned int __v, __x = (x);				      \
+	   __asm__ ("rorw $8, %w0;"					      \
+		    "rorl $16, %0;"					      \
+		    "rorw $8, %w0"					      \
+		    : "=r" (__v)					      \
+		    : "0" (__x)						      \
+		    : "cc");						      \
+	 __v; }))
+
+/*================================================================*/
+/* Local Types */
+
+typedef struct s3datarec {
+	u32 len;
+	u32 addr;
+	u8 checksum;
+	u8 *data;
+} s3datarec_t;
+
+typedef struct s3plugrec {
+	u32 itemcode;
+	u32 addr;
+	u32 len;
+} s3plugrec_t;
+
+typedef struct s3crcrec {
+	u32 addr;
+	u32 len;
+	unsigned int dowrite;
+} s3crcrec_t;
+
+typedef struct s3inforec {
+	u16 len;
+	u16 type;
+	union {
+		hfa384x_compident_t version;
+		hfa384x_caplevel_t compat;
+		u16 buildseq;
+		hfa384x_compident_t platform;
+	} info;
+} s3inforec_t;
+
+typedef struct pda {
+	u8 buf[HFA384x_PDA_LEN_MAX];
+	hfa384x_pdrec_t *rec[HFA384x_PDA_RECS_MAX];
+	unsigned int nrec;
+} pda_t;
+
+typedef struct imgchunk {
+	u32 addr;		/* start address */
+	u32 len;		/* in bytes */
+	u16 crc;		/* CRC value (if it falls at a chunk boundary) */
+	u8 *data;
+} imgchunk_t;
+
+/*================================================================*/
+/* Local Static Definitions */
+
+/*----------------------------------------------------------------*/
+/* s-record image processing */
+
+/* Data records */
+unsigned int ns3data = 0;
+s3datarec_t s3data[S3DATA_MAX];
+
+/* Plug records */
+unsigned int ns3plug = 0;
+s3plugrec_t s3plug[S3PLUG_MAX];
+
+/* CRC records */
+unsigned int ns3crc = 0;
+s3crcrec_t s3crc[S3CRC_MAX];
+
+/* Info records */
+unsigned int ns3info = 0;
+s3inforec_t s3info[S3INFO_MAX];
+
+/* S7 record (there _better_ be only one) */
+u32 startaddr;
+
+/* Load image chunks */
+unsigned int nfchunks;
+imgchunk_t fchunk[CHUNKS_MAX];
+
+/* Note that for the following pdrec_t arrays, the len and code */
+/*   fields are stored in HOST byte order. The mkpdrlist() function */
+/*   does the conversion.  */
+/*----------------------------------------------------------------*/
+/* PDA, built from [card|newfile]+[addfile1+addfile2...] */
+
+pda_t pda;
+hfa384x_compident_t nicid;
+hfa384x_caplevel_t rfid;
+hfa384x_caplevel_t macid;
+hfa384x_caplevel_t priid;
+
+/*================================================================*/
+/* Local Function Declarations */
+
+int prism2_fwapply(char *rfptr, int rfsize, wlandevice_t * wlandev);
+int read_srecfile(char *rfptr, int rfsize);
+int mkimage(imgchunk_t * clist, unsigned int *ccnt);
+int read_cardpda(pda_t * pda, wlandevice_t * wlandev);
+int mkpdrlist(pda_t * pda);
+int s3datarec_compare(const void *p1, const void *p2);
+int plugimage(imgchunk_t * fchunk, unsigned int nfchunks,
+	      s3plugrec_t * s3plug, unsigned int ns3plug, pda_t * pda);
+int crcimage(imgchunk_t * fchunk, unsigned int nfchunks,
+	     s3crcrec_t * s3crc, unsigned int ns3crc);
+int writeimage(wlandevice_t * wlandev, imgchunk_t * fchunk,
+	       unsigned int nfchunks);
+void free_chunks(imgchunk_t * fchunk, unsigned int *nfchunks);
+void free_srecs(void);
+
+int validate_identity(void);
+
+/*================================================================*/
+/* Function Definitions */
+
+/*----------------------------------------------------------------
+* prism2_fwtry
+*
+* Try and get firmware into memory
+*
+* Arguments:
+*	udev	usb device structure
+*	wlandev wlan device structure
+*
+* Returns:
+*	0	- success
+*	~0	- failure
+----------------------------------------------------------------*/
+int prism2_fwtry(struct usb_device *udev, wlandevice_t * wlandev)
+{
+	const struct firmware *fw_entry = NULL;
+
+	printk(KERN_INFO "prism2_usb: Checking for firmware %s\n",
+	       PRISM2_USB_FWFILE);
+	if (request_firmware(&fw_entry, PRISM2_USB_FWFILE, &udev->dev) != 0) {
+		printk(KERN_INFO
+		       "prism2_usb: Firmware not available, but not essential\n");
+		printk(KERN_INFO
+		       "prism2_usb: can continue to use card anyway.\n");
+		return 1;
+	}
+
+	printk(KERN_INFO "prism2_usb: %s will be processed, size %d\n",
+	       PRISM2_USB_FWFILE, fw_entry->size);
+	prism2_fwapply((char *)fw_entry->data, fw_entry->size, wlandev);
+
+	release_firmware(fw_entry);
+	return 0;
+}
+
+/*----------------------------------------------------------------
+* prism2_fwapply
+*
+* Apply the firmware loaded into memory
+*
+* Arguments:
+*	rfptr	firmware image in kernel memory
+*	rfsize	firmware size in kernel memory
+*	wlandev device
+*
+* Returns:
+*	0	- success
+*	~0	- failure
+----------------------------------------------------------------*/
+int prism2_fwapply(char *rfptr, int rfsize, wlandevice_t * wlandev)
+{
+	signed int result = 0;
+	p80211msg_dot11req_mibget_t getmsg;
+	p80211itemd_t *item;
+	u32 *data;
+
+	/* Initialize the data structures */
+	ns3data = 0;
+	memset(s3data, 0, sizeof(s3data));
+	ns3plug = 0;
+	memset(s3plug, 0, sizeof(s3plug));
+	ns3crc = 0;
+	memset(s3crc, 0, sizeof(s3crc));
+	ns3info = 0;
+	memset(s3info, 0, sizeof(s3info));
+	startaddr = 0;
+
+	nfchunks = 0;
+	memset(fchunk, 0, sizeof(fchunk));
+	memset(&nicid, 0, sizeof(nicid));
+	memset(&rfid, 0, sizeof(rfid));
+	memset(&macid, 0, sizeof(macid));
+	memset(&priid, 0, sizeof(priid));
+
+	/* clear the pda and add an initial END record */
+	memset(&pda, 0, sizeof(pda));
+	pda.rec[0] = (hfa384x_pdrec_t *) pda.buf;
+	pda.rec[0]->len = cpu_to_le16(2);	/* len in words *//* len in words */
+	pda.rec[0]->code = cpu_to_le16(HFA384x_PDR_END_OF_PDA);
+	pda.nrec = 1;
+
+	/*-----------------------------------------------------*/
+	/* Put card into fwload state */
+	prism2sta_ifstate(wlandev, P80211ENUM_ifstate_fwload);
+
+	/* Build the PDA we're going to use. */
+	if (read_cardpda(&pda, wlandev)) {
+		printk(KERN_ERR "load_cardpda failed, exiting.\n");
+		return (1);
+	}
+
+	/* read the card's PRI-SUP */
+	memset(&getmsg, 0, sizeof(getmsg));
+	getmsg.msgcode = DIDmsg_dot11req_mibget;
+	getmsg.msglen = sizeof(getmsg);
+	strcpy(getmsg.devname, wlandev->name);
+
+	getmsg.mibattribute.did = DIDmsg_dot11req_mibget_mibattribute;
+	getmsg.mibattribute.status = P80211ENUM_msgitem_status_data_ok;
+	getmsg.resultcode.did = DIDmsg_dot11req_mibget_resultcode;
+	getmsg.resultcode.status = P80211ENUM_msgitem_status_no_value;
+
+	item = (p80211itemd_t *) getmsg.mibattribute.data;
+	item->did = DIDmib_p2_p2NIC_p2PRISupRange;
+	item->status = P80211ENUM_msgitem_status_no_value;
+
+	data = (u32 *) item->data;
+
+	/* DIDmsg_dot11req_mibget */
+	prism2mgmt_mibset_mibget(wlandev, &getmsg);
+	if (getmsg.resultcode.data != P80211ENUM_resultcode_success) {
+		printk(KERN_ERR "Couldn't fetch PRI-SUP info\n");
+	}
+
+	/* Already in host order */
+	priid.role = *data++;
+	priid.id = *data++;
+	priid.variant = *data++;
+	priid.bottom = *data++;
+	priid.top = *data++;
+
+	/* Read the S3 file */
+	result = read_srecfile(rfptr, rfsize);
+	if (result) {
+		printk(KERN_ERR "Failed to read the data exiting.\n");
+		return (1);
+	}
+	/* Sort the S3 data records */
+	sort(s3data, ns3data, sizeof(s3datarec_t), s3datarec_compare, NULL);
+
+	result = validate_identity();
+
+	if (result) {
+		printk(KERN_ERR "Incompatible firmware image.\n");
+		return (1);
+	}
+
+	if (startaddr == 0x00000000) {
+		printk(KERN_ERR "Can't RAM download a Flash image!\n");
+		return (1);
+	}
+
+	/* Make the image chunks */
+	result = mkimage(fchunk, &nfchunks);
+
+	/* Do any plugging */
+	result = plugimage(fchunk, nfchunks, s3plug, ns3plug, &pda);
+	if (result) {
+		printk(KERN_ERR "Failed to plug data.\n");
+		return (1);
+	}
+
+	/* Insert any CRCs */
+	if (crcimage(fchunk, nfchunks, s3crc, ns3crc)) {
+		printk(KERN_ERR "Failed to insert all CRCs\n");
+		return (1);
+	}
+
+	/* Write the image */
+	result = writeimage(wlandev, fchunk, nfchunks);
+	if (result) {
+		printk(KERN_ERR "Failed to ramwrite image data.\n");
+		return (1);
+	}
+
+	/* clear any allocated memory */
+	free_chunks(fchunk, &nfchunks);
+	free_srecs();
+
+	printk(KERN_INFO "prism2_usb: firmware loading finished.\n");
+
+	return result;
+}
+
+/*----------------------------------------------------------------
+* crcimage
+*
+* Adds a CRC16 in the two bytes prior to each block identified by
+* an S3 CRC record.  Currently, we don't actually do a CRC we just
+* insert the value 0xC0DE in hfa384x order.
+*
+* Arguments:
+*	fchunk		Array of image chunks
+*	nfchunks	Number of image chunks
+*	s3crc		Array of crc records
+*	ns3crc		Number of crc records
+*
+* Returns:
+*	0	success
+*	~0	failure
+----------------------------------------------------------------*/
+int crcimage(imgchunk_t * fchunk, unsigned int nfchunks, s3crcrec_t * s3crc,
+	     unsigned int ns3crc)
+{
+	int result = 0;
+	int i;
+	int c;
+	u32 crcstart;
+	u32 crcend;
+	u32 cstart = 0;
+	u32 cend;
+	u8 *dest;
+	u32 chunkoff;
+
+	for (i = 0; i < ns3crc; i++) {
+		if (!s3crc[i].dowrite)
+			continue;
+		crcstart = s3crc[i].addr;
+		crcend = s3crc[i].addr + s3crc[i].len;
+		/* Find chunk */
+		for (c = 0; c < nfchunks; c++) {
+			cstart = fchunk[c].addr;
+			cend = fchunk[c].addr + fchunk[c].len;
+			/*  the line below does an address & len match search */
+			/*  unfortunately, I've found that the len fields of */
+			/*  some crc records don't match with the length of */
+			/*  the actual data, so we're not checking right */
+			/*  now */
+			/* if ( crcstart-2 >= cstart && crcend <= cend ) break; */
+
+			/* note the -2 below, it's to make sure the chunk has */
+			/*   space for the CRC value */
+			if (crcstart - 2 >= cstart && crcstart < cend)
+				break;
+		}
+		if (c >= nfchunks) {
+			printk(KERN_ERR
+			       "Failed to find chunk for "
+			       "crcrec[%d], addr=0x%06x len=%d , "
+			       "aborting crc.\n",
+			       i, s3crc[i].addr, s3crc[i].len);
+			return 1;
+		}
+
+		/* Insert crc */
+		pr_debug("Adding crc @ 0x%06x\n", s3crc[i].addr - 2);
+		chunkoff = crcstart - cstart - 2;
+		dest = fchunk[c].data + chunkoff;
+		*dest = 0xde;
+		*(dest + 1) = 0xc0;
+
+	}
+	return result;
+}
+
+/*----------------------------------------------------------------
+* free_chunks
+*
+* Clears the chunklist data structures in preparation for a new file.
+*
+* Arguments:
+*	none
+*
+* Returns:
+*	nothing
+----------------------------------------------------------------*/
+void free_chunks(imgchunk_t * fchunk, unsigned int *nfchunks)
+{
+	int i;
+	for (i = 0; i < *nfchunks; i++) {
+		if (fchunk[i].data != NULL) {
+			kfree(fchunk[i].data);
+		}
+	}
+	*nfchunks = 0;
+	memset(fchunk, 0, sizeof(fchunk));
+
+}
+
+/*----------------------------------------------------------------
+* free_srecs
+*
+* Clears the srec data structures in preparation for a new file.
+*
+* Arguments:
+*	none
+*
+* Returns:
+*	nothing
+----------------------------------------------------------------*/
+void free_srecs(void)
+{
+	int i;
+	for (i = 0; i < ns3data; i++) {
+		kfree(s3data[i].data);
+	}
+	ns3data = 0;
+	memset(s3data, 0, sizeof(s3data));
+	ns3plug = 0;
+	memset(s3plug, 0, sizeof(s3plug));
+	ns3crc = 0;
+	memset(s3crc, 0, sizeof(s3crc));
+	ns3info = 0;
+	memset(s3info, 0, sizeof(s3info));
+	startaddr = 0;
+}
+
+/*----------------------------------------------------------------
+* mkimage
+*
+* Scans the currently loaded set of S records for data residing
+* in contiguous memory regions.  Each contiguous region is then
+* made into a 'chunk'.  This function assumes that we're building
+* a new chunk list.  Assumes the s3data items are in sorted order.
+*
+* Arguments:	none
+*
+* Returns:
+*	0	- success
+*	~0	- failure (probably an errno)
+----------------------------------------------------------------*/
+int mkimage(imgchunk_t * clist, unsigned int *ccnt)
+{
+	int result = 0;
+	int i;
+	int j;
+	int currchunk = 0;
+	u32 nextaddr = 0;
+	u32 s3start;
+	u32 s3end;
+	u32 cstart = 0;
+	u32 cend;
+	u32 coffset;
+
+	/* There may already be data in the chunklist */
+	*ccnt = 0;
+
+	/* Establish the location and size of each chunk */
+	for (i = 0; i < ns3data; i++) {
+		if (s3data[i].addr == nextaddr) {
+			/* existing chunk, grow it */
+			clist[currchunk].len += s3data[i].len;
+			nextaddr += s3data[i].len;
+		} else {
+			/* New chunk */
+			(*ccnt)++;
+			currchunk = *ccnt - 1;
+			clist[currchunk].addr = s3data[i].addr;
+			clist[currchunk].len = s3data[i].len;
+			nextaddr = s3data[i].addr + s3data[i].len;
+			/* Expand the chunk if there is a CRC record at */
+			/* their beginning bound */
+			for (j = 0; j < ns3crc; j++) {
+				if (s3crc[j].dowrite &&
+				    s3crc[j].addr == clist[currchunk].addr) {
+					clist[currchunk].addr -= 2;
+					clist[currchunk].len += 2;
+				}
+			}
+		}
+	}
+
+	/* We're currently assuming there aren't any overlapping chunks */
+	/*  if this proves false, we'll need to add code to coalesce. */
+
+	/* Allocate buffer space for chunks */
+	for (i = 0; i < *ccnt; i++) {
+		clist[i].data = kmalloc(clist[i].len, GFP_KERNEL);
+		if (clist[i].data == NULL) {
+			printk(KERN_ERR
+			       "failed to allocate image space, exitting.\n");
+			return (1);
+		}
+		memset(clist[i].data, 0, clist[i].len);
+	}
+
+	/* Display chunks */
+	for (i = 0; i < *ccnt; i++) {
+		pr_debug("chunk[%d]: addr=0x%06x len=%d\n",
+			 i, clist[i].addr, clist[i].len);
+	}
+
+	/* Copy srec data to chunks */
+	for (i = 0; i < ns3data; i++) {
+		s3start = s3data[i].addr;
+		s3end = s3start + s3data[i].len - 1;
+		for (j = 0; j < *ccnt; j++) {
+			cstart = clist[j].addr;
+			cend = cstart + clist[j].len - 1;
+			if (s3start >= cstart && s3end <= cend) {
+				break;
+			}
+		}
+		if (((unsigned int)j) >= (*ccnt)) {
+			printk(KERN_ERR
+			       "s3rec(a=0x%06x,l=%d), no chunk match, exiting.\n",
+			       s3start, s3data[i].len);
+			return (1);
+		}
+		coffset = s3start - cstart;
+		memcpy(clist[j].data + coffset, s3data[i].data, s3data[i].len);
+	}
+
+	return result;
+}
+
+/*----------------------------------------------------------------
+* mkpdrlist
+*
+* Reads a raw PDA and builds an array of pdrec_t structures.
+*
+* Arguments:
+*	pda	buffer containing raw PDA bytes
+*	pdrec	ptr to an array of pdrec_t's.  Will be filled on exit.
+*	nrec	ptr to a variable that will contain the count of PDRs
+*
+* Returns:
+*	0	- success
+*	~0	- failure (probably an errno)
+----------------------------------------------------------------*/
+int mkpdrlist(pda_t * pda)
+{
+	int result = 0;
+	u16 *pda16 = (u16 *) pda->buf;
+	int curroff;		/* in 'words' */
+
+	pda->nrec = 0;
+	curroff = 0;
+	while (curroff < (HFA384x_PDA_LEN_MAX / 2) &&
+	       le16_to_cpu(pda16[curroff + 1]) != HFA384x_PDR_END_OF_PDA) {
+		pda->rec[pda->nrec] = (hfa384x_pdrec_t *) & (pda16[curroff]);
+
+		if (le16_to_cpu(pda->rec[pda->nrec]->code) == HFA384x_PDR_NICID) {
+			memcpy(&nicid, &pda->rec[pda->nrec]->data.nicid,
+			       sizeof(nicid));
+			nicid.id = le16_to_cpu(nicid.id);
+			nicid.variant = le16_to_cpu(nicid.variant);
+			nicid.major = le16_to_cpu(nicid.major);
+			nicid.minor = le16_to_cpu(nicid.minor);
+		}
+		if (le16_to_cpu(pda->rec[pda->nrec]->code) ==
+		    HFA384x_PDR_MFISUPRANGE) {
+			memcpy(&rfid, &pda->rec[pda->nrec]->data.mfisuprange,
+			       sizeof(rfid));
+			rfid.id = le16_to_cpu(rfid.id);
+			rfid.variant = le16_to_cpu(rfid.variant);
+			rfid.bottom = le16_to_cpu(rfid.bottom);
+			rfid.top = le16_to_cpu(rfid.top);
+		}
+		if (le16_to_cpu(pda->rec[pda->nrec]->code) ==
+		    HFA384x_PDR_CFISUPRANGE) {
+			memcpy(&macid, &pda->rec[pda->nrec]->data.cfisuprange,
+			       sizeof(macid));
+			macid.id = le16_to_cpu(macid.id);
+			macid.variant = le16_to_cpu(macid.variant);
+			macid.bottom = le16_to_cpu(macid.bottom);
+			macid.top = le16_to_cpu(macid.top);
+		}
+
+		(pda->nrec)++;
+		curroff += le16_to_cpu(pda16[curroff]) + 1;
+
+	}
+	if (curroff >= (HFA384x_PDA_LEN_MAX / 2)) {
+		printk(KERN_ERR
+		       "no end record found or invalid lengths in "
+		       "PDR data, exiting. %x %d\n", curroff, pda->nrec);
+		return (1);
+	}
+	if (le16_to_cpu(pda16[curroff + 1]) == HFA384x_PDR_END_OF_PDA) {
+		pda->rec[pda->nrec] = (hfa384x_pdrec_t *) & (pda16[curroff]);
+		(pda->nrec)++;
+	}
+	return result;
+}
+
+/*----------------------------------------------------------------
+* plugimage
+*
+* Plugs the given image using the given plug records from the given
+* PDA and filename.
+*
+* Arguments:
+*	fchunk		Array of image chunks
+*	nfchunks	Number of image chunks
+*	s3plug		Array of plug records
+*	ns3plug		Number of plug records
+*	pda		Current pda data
+*
+* Returns:
+*	0	success
+*	~0	failure
+----------------------------------------------------------------*/
+int plugimage(imgchunk_t * fchunk, unsigned int nfchunks,
+	      s3plugrec_t * s3plug, unsigned int ns3plug, pda_t * pda)
+{
+	int result = 0;
+	int i;			/* plug index */
+	int j;			/* index of PDR or -1 if fname plug */
+	int c;			/* chunk index */
+	u32 pstart;
+	u32 pend;
+	u32 cstart = 0;
+	u32 cend;
+	u32 chunkoff;
+	u8 *dest;
+
+	/* for each plug record */
+	for (i = 0; i < ns3plug; i++) {
+		pstart = s3plug[i].addr;
+		pend = s3plug[i].addr + s3plug[i].len;
+		/* find the matching PDR (or filename) */
+		if (s3plug[i].itemcode != 0xffffffffUL) {	/* not filename */
+			for (j = 0; j < pda->nrec; j++) {
+				if (s3plug[i].itemcode ==
+				    le16_to_cpu(pda->rec[j]->code))
+					break;
+			}
+		} else {
+			j = -1;
+		}
+		if (j >= pda->nrec && j != -1) {	/*  if no matching PDR, fail */
+			printk(KERN_WARNING
+			       "warning: Failed to find PDR for "
+			       "plugrec 0x%04x.\n", s3plug[i].itemcode);
+			continue;	/* and move on to the next PDR */
+#if 0
+			/* MSM: They swear that unless it's the MAC address,
+			 * the serial number, or the TX calibration records,
+			 * then there's reasonable defaults in the f/w
+			 * image.  Therefore, missing PDRs in the card
+			 * should only be a warning, not fatal.
+			 * TODO: add fatals for the PDRs mentioned above.
+			 */
+			result = 1;
+			continue;
+#endif
+		}
+
+		/* Validate plug len against PDR len */
+		if (j != -1 && s3plug[i].len < le16_to_cpu(pda->rec[j]->len)) {
+			printk(KERN_ERR
+			       "error: Plug vs. PDR len mismatch for "
+			       "plugrec 0x%04x, abort plugging.\n",
+			       s3plug[i].itemcode);
+			result = 1;
+			continue;
+		}
+
+		/* Validate plug address against chunk data and identify chunk */
+		for (c = 0; c < nfchunks; c++) {
+			cstart = fchunk[c].addr;
+			cend = fchunk[c].addr + fchunk[c].len;
+			if (pstart >= cstart && pend <= cend)
+				break;
+		}
+		if (c >= nfchunks) {
+			printk(KERN_ERR
+			       "error: Failed to find image chunk for "
+			       "plugrec 0x%04x.\n", s3plug[i].itemcode);
+			result = 1;
+			continue;
+		}
+
+		/* Plug data */
+		chunkoff = pstart - cstart;
+		dest = fchunk[c].data + chunkoff;
+		pr_debug("Plugging item 0x%04x @ 0x%06x, len=%d, "
+			 "cnum=%d coff=0x%06x\n",
+			 s3plug[i].itemcode, pstart, s3plug[i].len,
+			 c, chunkoff);
+
+		if (j == -1) {	/* plug the filename */
+			memset(dest, 0, s3plug[i].len);
+			strncpy(dest, PRISM2_USB_FWFILE, s3plug[i].len - 1);
+		} else {	/* plug a PDR */
+			memcpy(dest, &(pda->rec[j]->data), s3plug[i].len);
+		}
+	}
+	return result;
+
+}
+
+/*----------------------------------------------------------------
+* read_cardpda
+*
+* Sends the command for the driver to read the pda from the card
+* named in the device variable.  Upon success, the card pda is
+* stored in the "cardpda" variables.  Note that the pda structure
+* is considered 'well formed' after this function.  That means
+* that the nrecs is valid, the rec array has been set up, and there's
+* a valid PDAEND record in the raw PDA data.
+*
+* Arguments:
+*	pda		pda structure
+*	wlandev		device
+*
+* Returns:
+*	0	- success
+*	~0	- failure (probably an errno)
+----------------------------------------------------------------*/
+int read_cardpda(pda_t * pda, wlandevice_t * wlandev)
+{
+	int result = 0;
+	p80211msg_p2req_readpda_t msg;
+
+	/* set up the msg */
+	msg.msgcode = DIDmsg_p2req_readpda;
+	msg.msglen = sizeof(msg);
+	strcpy(msg.devname, wlandev->name);
+	msg.pda.did = DIDmsg_p2req_readpda_pda;
+	msg.pda.len = HFA384x_PDA_LEN_MAX;
+	msg.pda.status = P80211ENUM_msgitem_status_no_value;
+	msg.resultcode.did = DIDmsg_p2req_readpda_resultcode;
+	msg.resultcode.len = sizeof(u32);
+	msg.resultcode.status = P80211ENUM_msgitem_status_no_value;
+
+	if (prism2mgmt_readpda(wlandev, &msg) != 0) {
+		/* prism2mgmt_readpda prints an errno if appropriate */
+		result = -1;
+	} else if (msg.resultcode.data == P80211ENUM_resultcode_success) {
+		memcpy(pda->buf, msg.pda.data, HFA384x_PDA_LEN_MAX);
+		result = mkpdrlist(pda);
+	} else {
+		/* resultcode must've been something other than success */
+		result = -1;
+	}
+
+	return result;
+}
+
+/*----------------------------------------------------------------
+* copy_line
+*
+* Copies a line of text, up to \n, \0, or SREC_LINE_MAX, or limit of
+* From array
+*
+* Arguments:
+*	from	From addr
+*	to	To addr
+*	limit	Addr of last character in From array that can be copied
+*
+* Returns:
+*	Num characters copied
+----------------------------------------------------------------*/
+int copyline(char *from, char *to, char *limit)
+{
+	int c = 0;
+
+	while ((c < SREC_LINE_MAX - 1) && (from + c <= limit) &&
+	       (from[c] != '\n') && (from[c] != '\0')) {
+		to[c] = from[c];
+		c++;
+	}
+
+	to[c] = '\0';
+	return (c < SREC_LINE_MAX - 1) ? c + 1 : c;
+}
+
+/*----------------------------------------------------------------
+* read_srecfile
+*
+* Reads the given srecord file and loads the records into the
+* s3xxx arrays.  This function can be called repeatedly (once for
+* each of a set of files), if necessary.  This function performs
+* no validation of the data except for the grossest of S-record
+* line format checks.  Don't forget that these will be DOS files...
+* CR/LF at the end of each line.
+*
+* Here's the SREC format we're dealing with:
+* S[37]nnaaaaaaaaddd...dddcc
+*
+*       nn - number of bytes starting with the address field
+* aaaaaaaa - address in readable (or big endian) format
+* dd....dd - 0-245 data bytes (two chars per byte)
+*       cc - checksum
+*
+* The S7 record's (there should be only one) address value gets
+* saved in startaddr.  It's the start execution address used
+* for RAM downloads.
+*
+* The S3 records have a collection of subformats indicated by the
+* value of aaaaaaaa:
+*   0xff000000 - Plug record, data field format:
+*                xxxxxxxxaaaaaaaassssssss
+*                x - PDR code number (little endian)
+*                a - Address in load image to plug (little endian)
+*                s - Length of plug data area (little endian)
+*
+*   0xff100000 - CRC16 generation record, data field format:
+*                aaaaaaaassssssssbbbbbbbb
+*                a - Start address for CRC calculation (little endian)
+*                s - Length of data to  calculate over (little endian)
+*                b - Boolean, true=write crc, false=don't write
+*
+*   0xff200000 - Info record, data field format:
+*                ssssttttdd..dd
+*                s - Size in words (little endian)
+*                t - Info type (little endian), see #defines and
+*                    s3inforec_t for details about types.
+*                d - (s - 1) little endian words giving the contents of
+*                    the given info type.
+*
+* Arguments:
+*	rfptr	firmware image (s-record structure) in kernel memory
+*	rfsize	firmware size in kernel memory
+*
+* Returns:
+*	0	- success
+*	~0	- failure (probably an errno)
+----------------------------------------------------------------*/
+int read_srecfile(char *rfptr, int rfsize)
+{
+	int result = 0;
+	char buf[SREC_LINE_MAX];
+	char tmpbuf[30];
+	s3datarec_t tmprec;
+	int i, c;
+	int line = 0;
+	u16 *tmpinfo;
+	char *endptr = rfptr + rfsize;
+
+	pr_debug("Reading S-record file ...\n");
+
+	while ((c = copyline(rfptr, buf, endptr)) >= 12) {
+		rfptr = rfptr + c;
+		line++;
+		if (buf[0] != 'S') {
+			printk(KERN_ERR "%d warning: No initial \'S\'\n", line);
+			return 1;
+		}
+		if (buf[1] == '7') {	/* S7 record, start address */
+			buf[12] = '\0';
+			startaddr = simple_strtoul(buf + 4, NULL, 16);
+			pr_debug("  S7 start addr, line=%d "
+				 " addr=0x%08x\n", line, startaddr);
+			continue;
+		} else if (buf[1] == '3') {
+			/* Ok, it's an S3, parse and put it in the right array */
+			/* Record Length field (we only want datalen) */
+			memcpy(tmpbuf, buf + S3LEN_TXTOFFSET, S3LEN_TXTLEN);
+			tmpbuf[S3LEN_TXTLEN] = '\0';
+			tmprec.len = simple_strtoul(tmpbuf, NULL, 16) - 4 - 1;	/* 4=addr, 1=cksum */
+			/* Address field */
+			memcpy(tmpbuf, buf + S3ADDR_TXTOFFSET, S3ADDR_TXTLEN);
+			tmpbuf[S3ADDR_TXTLEN] = '\0';
+			tmprec.addr = simple_strtoul(tmpbuf, NULL, 16);
+			/* Checksum field */
+			tmprec.checksum =
+			    simple_strtoul(buf + strlen(buf) - 2, NULL, 16);
+
+			switch (tmprec.addr) {
+			case S3ADDR_PLUG:
+				memcpy(tmpbuf, buf + S3PLUG_ITEMCODE_TXTOFFSET,
+				       S3PLUG_ITEMCODE_TXTLEN);
+				tmpbuf[S3PLUG_ITEMCODE_TXTLEN] = '\0';
+				s3plug[ns3plug].itemcode =
+				    simple_strtoul(tmpbuf, NULL, 16);
+				s3plug[ns3plug].itemcode =
+				    bswap_32(s3plug[ns3plug].itemcode);
+
+				memcpy(tmpbuf, buf + S3PLUG_ADDR_TXTOFFSET,
+				       S3PLUG_ADDR_TXTLEN);
+				tmpbuf[S3PLUG_ADDR_TXTLEN] = '\0';
+				s3plug[ns3plug].addr =
+				    simple_strtoul(tmpbuf, NULL, 16);
+				s3plug[ns3plug].addr =
+				    bswap_32(s3plug[ns3plug].addr);
+
+				memcpy(tmpbuf, buf + S3PLUG_LEN_TXTOFFSET,
+				       S3PLUG_LEN_TXTLEN);
+				tmpbuf[S3PLUG_LEN_TXTLEN] = '\0';
+				s3plug[ns3plug].len =
+				    simple_strtoul(tmpbuf, NULL, 16);
+				s3plug[ns3plug].len =
+				    bswap_32(s3plug[ns3plug].len);
+
+				pr_debug("  S3 plugrec, line=%d "
+					 "itemcode=0x%04x addr=0x%08x len=%d\n",
+					 line,
+					 s3plug[ns3plug].itemcode,
+					 s3plug[ns3plug].addr,
+					 s3plug[ns3plug].len);
+
+				ns3plug++;
+				if (ns3plug == S3PLUG_MAX) {
+					printk(KERN_ERR
+					       "S3 plugrec limit reached - aborting\n");
+					return 1;
+				}
+				break;
+			case S3ADDR_CRC:
+				memcpy(tmpbuf, buf + S3CRC_ADDR_TXTOFFSET,
+				       S3CRC_ADDR_TXTLEN);
+				tmpbuf[S3CRC_ADDR_TXTLEN] = '\0';
+				s3crc[ns3crc].addr =
+				    simple_strtoul(tmpbuf, NULL, 16);
+				s3crc[ns3crc].addr =
+				    bswap_32(s3crc[ns3crc].addr);
+
+				memcpy(tmpbuf, buf + S3CRC_LEN_TXTOFFSET,
+				       S3CRC_LEN_TXTLEN);
+				tmpbuf[S3CRC_LEN_TXTLEN] = '\0';
+				s3crc[ns3crc].len =
+				    simple_strtoul(tmpbuf, NULL, 16);
+				s3crc[ns3crc].len = bswap_32(s3crc[ns3crc].len);
+
+				memcpy(tmpbuf, buf + S3CRC_DOWRITE_TXTOFFSET,
+				       S3CRC_DOWRITE_TXTLEN);
+				tmpbuf[S3CRC_DOWRITE_TXTLEN] = '\0';
+				s3crc[ns3crc].dowrite =
+				    simple_strtoul(tmpbuf, NULL, 16);
+				s3crc[ns3crc].dowrite =
+				    bswap_32(s3crc[ns3crc].dowrite);
+
+				pr_debug("  S3 crcrec, line=%d "
+					 "addr=0x%08x len=%d write=0x%08x\n",
+					 line,
+					 s3crc[ns3crc].addr,
+					 s3crc[ns3crc].len,
+					 s3crc[ns3crc].dowrite);
+				ns3crc++;
+				if (ns3crc == S3CRC_MAX) {
+					printk(KERN_ERR
+					       "S3 crcrec limit reached - aborting\n");
+					return 1;
+				}
+				break;
+			case S3ADDR_INFO:
+				memcpy(tmpbuf, buf + S3INFO_LEN_TXTOFFSET,
+				       S3INFO_LEN_TXTLEN);
+				tmpbuf[S3INFO_LEN_TXTLEN] = '\0';
+				s3info[ns3info].len =
+				    simple_strtoul(tmpbuf, NULL, 16);
+				s3info[ns3info].len =
+				    bswap_16(s3info[ns3info].len);
+
+				memcpy(tmpbuf, buf + S3INFO_TYPE_TXTOFFSET,
+				       S3INFO_TYPE_TXTLEN);
+				tmpbuf[S3INFO_TYPE_TXTLEN] = '\0';
+				s3info[ns3info].type =
+				    simple_strtoul(tmpbuf, NULL, 16);
+				s3info[ns3info].type =
+				    bswap_16(s3info[ns3info].type);
+
+				pr_debug("  S3 inforec, line=%d "
+					 "len=0x%04x type=0x%04x\n",
+					 line,
+					 s3info[ns3info].len,
+					 s3info[ns3info].type);
+				if (((s3info[ns3info].len - 1) * sizeof(u16)) >
+				    sizeof(s3info[ns3info].info)) {
+					printk(KERN_ERR
+					       " S3 inforec length too long - aborting\n");
+					return 1;
+				}
+
+				tmpinfo =
+				    (u16 *) & (s3info[ns3info].info.version);
+				for (i = 0; i < s3info[ns3info].len - 1; i++) {
+					memcpy(tmpbuf,
+					       buf + S3INFO_DATA_TXTOFFSET +
+					       (i * 4), 4);
+					tmpbuf[4] = '\0';
+					tmpinfo[i] =
+					    simple_strtoul(tmpbuf, NULL, 16);
+					tmpinfo[i] = bswap_16(tmpinfo[i]);
+				}
+				pr_debug("            info=");
+				for (i = 0; i < s3info[ns3info].len - 1; i++) {
+					pr_debug("%04x ", tmpinfo[i]);
+				}
+				pr_debug("\n");
+
+				ns3info++;
+				if (ns3info == S3INFO_MAX) {
+					printk(KERN_ERR
+					       "S3 inforec limit reached - aborting\n");
+					return 1;
+				}
+				break;
+			default:	/* Data record */
+				s3data[ns3data].addr = tmprec.addr;
+				s3data[ns3data].len = tmprec.len;
+				s3data[ns3data].checksum = tmprec.checksum;
+				s3data[ns3data].data =
+				    kmalloc(tmprec.len, GFP_KERNEL);
+				for (i = 0; i < tmprec.len; i++) {
+					memcpy(tmpbuf,
+					       buf + S3DATA_TXTOFFSET + (i * 2),
+					       2);
+					tmpbuf[2] = '\0';
+					s3data[ns3data].data[i] =
+					    simple_strtoul(tmpbuf, NULL, 16);
+				}
+				ns3data++;
+				if (ns3data == S3DATA_MAX) {
+					printk(KERN_ERR
+					       "S3 datarec limit reached - aborting\n");
+					return 1;
+				}
+				break;
+			}
+		} else {
+			printk(KERN_WARNING
+			       "%d warning: Unknown S-record detected.\n",
+			       line);
+		}
+	}
+	return result;
+}
+
+/*----------------------------------------------------------------
+* s3datarec_compare
+*
+* Comparison function for sort().
+*
+* Arguments:
+*	p1	ptr to the first item
+*	p2	ptr to the second item
+* Returns:
+*	0	items are equal
+*	<0	p1 < p2
+*	>0	p1 > p2
+----------------------------------------------------------------*/
+int s3datarec_compare(const void *p1, const void *p2)
+{
+	const s3datarec_t *s1 = p1;
+	const s3datarec_t *s2 = p2;
+	if (s1->addr == s2->addr)
+		return 0;
+	if (s1->addr < s2->addr)
+		return -1;
+	return 1;
+}
+
+/*----------------------------------------------------------------
+* writeimage
+*
+* Takes the chunks, builds p80211 messages and sends them down
+* to the driver for writing to the card.
+*
+* Arguments:
+*	wlandev		device
+*	fchunk		Array of image chunks
+*	nfchunks	Number of image chunks
+*
+* Returns:
+*	0	success
+*	~0	failure
+----------------------------------------------------------------*/
+int writeimage(wlandevice_t * wlandev, imgchunk_t * fchunk,
+	       unsigned int nfchunks)
+{
+	int result = 0;
+	p80211msg_p2req_ramdl_state_t rstatemsg;
+	p80211msg_p2req_ramdl_write_t rwritemsg;
+	p80211msg_t *msgp;
+	u32 resultcode;
+	int i;
+	int j;
+	unsigned int nwrites;
+	u32 curroff;
+	u32 currlen;
+	u32 currdaddr;
+
+	/* Initialize the messages */
+	memset(&rstatemsg, 0, sizeof(rstatemsg));
+	strcpy(rstatemsg.devname, wlandev->name);
+	rstatemsg.msgcode = DIDmsg_p2req_ramdl_state;
+	rstatemsg.msglen = sizeof(rstatemsg);
+	rstatemsg.enable.did = DIDmsg_p2req_ramdl_state_enable;
+	rstatemsg.exeaddr.did = DIDmsg_p2req_ramdl_state_exeaddr;
+	rstatemsg.resultcode.did = DIDmsg_p2req_ramdl_state_resultcode;
+	rstatemsg.enable.status = P80211ENUM_msgitem_status_data_ok;
+	rstatemsg.exeaddr.status = P80211ENUM_msgitem_status_data_ok;
+	rstatemsg.resultcode.status = P80211ENUM_msgitem_status_no_value;
+	rstatemsg.enable.len = sizeof(u32);
+	rstatemsg.exeaddr.len = sizeof(u32);
+	rstatemsg.resultcode.len = sizeof(u32);
+
+	memset(&rwritemsg, 0, sizeof(rwritemsg));
+	strcpy(rwritemsg.devname, wlandev->name);
+	rwritemsg.msgcode = DIDmsg_p2req_ramdl_write;
+	rwritemsg.msglen = sizeof(rwritemsg);
+	rwritemsg.addr.did = DIDmsg_p2req_ramdl_write_addr;
+	rwritemsg.len.did = DIDmsg_p2req_ramdl_write_len;
+	rwritemsg.data.did = DIDmsg_p2req_ramdl_write_data;
+	rwritemsg.resultcode.did = DIDmsg_p2req_ramdl_write_resultcode;
+	rwritemsg.addr.status = P80211ENUM_msgitem_status_data_ok;
+	rwritemsg.len.status = P80211ENUM_msgitem_status_data_ok;
+	rwritemsg.data.status = P80211ENUM_msgitem_status_data_ok;
+	rwritemsg.resultcode.status = P80211ENUM_msgitem_status_no_value;
+	rwritemsg.addr.len = sizeof(u32);
+	rwritemsg.len.len = sizeof(u32);
+	rwritemsg.data.len = WRITESIZE_MAX;
+	rwritemsg.resultcode.len = sizeof(u32);
+
+	/* Send xxx_state(enable) */
+	pr_debug("Sending dl_state(enable) message.\n");
+	rstatemsg.enable.data = P80211ENUM_truth_true;
+	rstatemsg.exeaddr.data = startaddr;
+
+	msgp = (p80211msg_t *) & rstatemsg;
+	result = prism2mgmt_ramdl_state(wlandev, msgp);
+	if (result) {
+		printk(KERN_ERR
+		       "writeimage state enable failed w/ result=%d, "
+		       "aborting download\n", result);
+		return result;
+	}
+	resultcode = rstatemsg.resultcode.data;
+	if (resultcode != P80211ENUM_resultcode_success) {
+		printk(KERN_ERR
+		       "writeimage()->xxxdl_state msg indicates failure, "
+		       "w/ resultcode=%d, aborting download.\n", resultcode);
+		return 1;
+	}
+
+	/* Now, loop through the data chunks and send WRITESIZE_MAX data */
+	for (i = 0; i < nfchunks; i++) {
+		nwrites = fchunk[i].len / WRITESIZE_MAX;
+		nwrites += (fchunk[i].len % WRITESIZE_MAX) ? 1 : 0;
+		curroff = 0;
+		for (j = 0; j < nwrites; j++) {
+			currlen =
+			    (fchunk[i].len - (WRITESIZE_MAX * j)) >
+			    WRITESIZE_MAX ? WRITESIZE_MAX : (fchunk[i].len -
+							     (WRITESIZE_MAX *
+							      j));
+			curroff = j * WRITESIZE_MAX;
+			currdaddr = fchunk[i].addr + curroff;
+			/* Setup the message */
+			rwritemsg.addr.data = currdaddr;
+			rwritemsg.len.data = currlen;
+			memcpy(rwritemsg.data.data,
+			       fchunk[i].data + curroff, currlen);
+
+			/* Send flashdl_write(pda) */
+			pr_debug
+			    ("Sending xxxdl_write message addr=%06x len=%d.\n",
+			     currdaddr, currlen);
+
+			msgp = (p80211msg_t *) & rwritemsg;
+			result = prism2mgmt_ramdl_write(wlandev, msgp);
+
+			/* Check the results */
+			if (result) {
+				printk(KERN_ERR
+				       "writeimage chunk write failed w/ result=%d, "
+				       "aborting download\n", result);
+				return result;
+			}
+			resultcode = rstatemsg.resultcode.data;
+			if (resultcode != P80211ENUM_resultcode_success) {
+				printk(KERN_ERR
+				       "writeimage()->xxxdl_write msg indicates failure, "
+				       "w/ resultcode=%d, aborting download.\n",
+				       resultcode);
+				return 1;
+			}
+
+		}
+	}
+
+	/* Send xxx_state(disable) */
+	pr_debug("Sending dl_state(disable) message.\n");
+	rstatemsg.enable.data = P80211ENUM_truth_false;
+	rstatemsg.exeaddr.data = 0;
+
+	msgp = (p80211msg_t *) & rstatemsg;
+	result = prism2mgmt_ramdl_state(wlandev, msgp);
+	if (result) {
+		printk(KERN_ERR
+		       "writeimage state disable failed w/ result=%d, "
+		       "aborting download\n", result);
+		return result;
+	}
+	resultcode = rstatemsg.resultcode.data;
+	if (resultcode != P80211ENUM_resultcode_success) {
+		printk(KERN_ERR
+		       "writeimage()->xxxdl_state msg indicates failure, "
+		       "w/ resultcode=%d, aborting download.\n", resultcode);
+		return 1;
+	}
+	return result;
+}
+
+int validate_identity(void)
+{
+	int i;
+	int result = 1;
+
+	pr_debug("NIC ID: %#x v%d.%d.%d\n",
+		 nicid.id, nicid.major, nicid.minor, nicid.variant);
+	pr_debug("MFI ID: %#x v%d %d->%d\n",
+		 rfid.id, rfid.variant, rfid.bottom, rfid.top);
+	pr_debug("CFI ID: %#x v%d %d->%d\n",
+		 macid.id, macid.variant, macid.bottom, macid.top);
+	pr_debug("PRI ID: %#x v%d %d->%d\n",
+		 priid.id, priid.variant, priid.bottom, priid.top);
+
+	for (i = 0; i < ns3info; i++) {
+		switch (s3info[i].type) {
+		case 1:
+			pr_debug("Version:  ID %#x %d.%d.%d\n",
+				 s3info[i].info.version.id,
+				 s3info[i].info.version.major,
+				 s3info[i].info.version.minor,
+				 s3info[i].info.version.variant);
+			break;
+		case 2:
+			pr_debug("Compat: Role %#x Id %#x v%d %d->%d\n",
+				 s3info[i].info.compat.role,
+				 s3info[i].info.compat.id,
+				 s3info[i].info.compat.variant,
+				 s3info[i].info.compat.bottom,
+				 s3info[i].info.compat.top);
+
+			/* MAC compat range */
+			if ((s3info[i].info.compat.role == 1) &&
+			    (s3info[i].info.compat.id == 2)) {
+				if (s3info[i].info.compat.variant !=
+				    macid.variant) {
+					result = 2;
+				}
+			}
+
+			/* PRI compat range */
+			if ((s3info[i].info.compat.role == 1) &&
+			    (s3info[i].info.compat.id == 3)) {
+				if ((s3info[i].info.compat.bottom > priid.top)
+				    || (s3info[i].info.compat.top <
+					priid.bottom)) {
+					result = 3;
+				}
+			}
+			/* SEC compat range */
+			if ((s3info[i].info.compat.role == 1) &&
+			    (s3info[i].info.compat.id == 4)) {
+
+			}
+
+			break;
+		case 3:
+			pr_debug("Seq: %#x\n", s3info[i].info.buildseq);
+
+			break;
+		case 4:
+			pr_debug("Platform:  ID %#x %d.%d.%d\n",
+				 s3info[i].info.version.id,
+				 s3info[i].info.version.major,
+				 s3info[i].info.version.minor,
+				 s3info[i].info.version.variant);
+
+			if (nicid.id != s3info[i].info.version.id)
+				continue;
+			if (nicid.major != s3info[i].info.version.major)
+				continue;
+			if (nicid.minor != s3info[i].info.version.minor)
+				continue;
+			if ((nicid.variant != s3info[i].info.version.variant) &&
+			    (nicid.id != 0x8008))
+				continue;
+
+			if (result != 2)
+				result = 0;
+			break;
+		case 0x8001:
+			pr_debug("name inforec len %d\n", s3info[i].len);
+
+			break;
+		default:
+			pr_debug("Unknown inforec type %d\n", s3info[i].type);
+		}
+	}
+	// walk through
+
+	return result;
+}
diff --git a/drivers/staging/wlan-ng/prism2mgmt.c b/drivers/staging/wlan-ng/prism2mgmt.c
index e7a7939..46545765 100644
--- a/drivers/staging/wlan-ng/prism2mgmt.c
+++ b/drivers/staging/wlan-ng/prism2mgmt.c
@@ -117,7 +117,7 @@
 *	process thread  (usually)
 *	interrupt
 ----------------------------------------------------------------*/
-int prism2mgmt_scan(wlandevice_t *wlandev, void *msgp)
+int prism2mgmt_scan(wlandevice_t * wlandev, void *msgp)
 {
 	int result = 0;
 	hfa384x_t *hw = wlandev->priv;
@@ -362,7 +362,7 @@
 *	process thread  (usually)
 *	interrupt
 ----------------------------------------------------------------*/
-int prism2mgmt_scan_results(wlandevice_t *wlandev, void *msgp)
+int prism2mgmt_scan_results(wlandevice_t * wlandev, void *msgp)
 {
 	int result = 0;
 	p80211msg_dot11req_scan_results_t *req;
@@ -389,7 +389,7 @@
 
 	if (req->bssindex.data >= count) {
 		pr_debug("requested index (%d) out of range (%d)\n",
-		       req->bssindex.data, count);
+			 req->bssindex.data, count);
 		result = 2;
 		req->resultcode.data = P80211ENUM_resultcode_invalid_parameters;
 		goto exit;
@@ -511,7 +511,7 @@
 *	process thread  (usually)
 *	interrupt
 ----------------------------------------------------------------*/
-int prism2mgmt_start(wlandevice_t *wlandev, void *msgp)
+int prism2mgmt_start(wlandevice_t * wlandev, void *msgp)
 {
 	int result = 0;
 	hfa384x_t *hw = wlandev->priv;
@@ -544,7 +544,7 @@
 	/*** STATION ***/
 	/* Set the REQUIRED config items */
 	/* SSID */
-	pstr = (p80211pstrd_t *)&(msg->ssid.data);
+	pstr = (p80211pstrd_t *) & (msg->ssid.data);
 	prism2mgmt_pstr2bytestr(p2bytestr, pstr);
 	result = hfa384x_drvr_setconfig(hw, HFA384x_RID_CNFOWNSSID,
 					bytebuf, HFA384x_RID_CNFOWNSSID_LEN);
@@ -688,7 +688,7 @@
 * Call context:
 *	process thread  (usually)
 ----------------------------------------------------------------*/
-int prism2mgmt_readpda(wlandevice_t *wlandev, void *msgp)
+int prism2mgmt_readpda(wlandevice_t * wlandev, void *msgp)
 {
 	hfa384x_t *hw = wlandev->priv;
 	p80211msg_p2req_readpda_t *msg = msgp;
@@ -754,7 +754,7 @@
 * Call context:
 *	process thread  (usually)
 ----------------------------------------------------------------*/
-int prism2mgmt_ramdl_state(wlandevice_t *wlandev, void *msgp)
+int prism2mgmt_ramdl_state(wlandevice_t * wlandev, void *msgp)
 {
 	hfa384x_t *hw = wlandev->priv;
 	p80211msg_p2req_ramdl_state_t *msg = msgp;
@@ -810,7 +810,7 @@
 * Call context:
 *	process thread  (usually)
 ----------------------------------------------------------------*/
-int prism2mgmt_ramdl_write(wlandevice_t *wlandev, void *msgp)
+int prism2mgmt_ramdl_write(wlandevice_t * wlandev, void *msgp)
 {
 	hfa384x_t *hw = wlandev->priv;
 	p80211msg_p2req_ramdl_write_t *msg = msgp;
@@ -872,7 +872,7 @@
 * Call context:
 *	process thread  (usually)
 ----------------------------------------------------------------*/
-int prism2mgmt_flashdl_state(wlandevice_t *wlandev, void *msgp)
+int prism2mgmt_flashdl_state(wlandevice_t * wlandev, void *msgp)
 {
 	int result = 0;
 	hfa384x_t *hw = wlandev->priv;
@@ -943,7 +943,7 @@
 * Call context:
 *	process thread  (usually)
 ----------------------------------------------------------------*/
-int prism2mgmt_flashdl_write(wlandevice_t *wlandev, void *msgp)
+int prism2mgmt_flashdl_write(wlandevice_t * wlandev, void *msgp)
 {
 	hfa384x_t *hw = wlandev->priv;
 	p80211msg_p2req_flashdl_write_t *msg = msgp;
@@ -1004,7 +1004,7 @@
 *	process thread  (usually)
 *	interrupt
 ----------------------------------------------------------------*/
-int prism2mgmt_autojoin(wlandevice_t *wlandev, void *msgp)
+int prism2mgmt_autojoin(wlandevice_t * wlandev, void *msgp)
 {
 	hfa384x_t *hw = wlandev->priv;
 	int result = 0;
@@ -1037,7 +1037,7 @@
 
 	/* Set the ssid */
 	memset(bytebuf, 0, 256);
-	pstr = (p80211pstrd_t *)&(msg->ssid.data);
+	pstr = (p80211pstrd_t *) & (msg->ssid.data);
 	prism2mgmt_pstr2bytestr(p2bytestr, pstr);
 	result = hfa384x_drvr_setconfig(hw, HFA384x_RID_CNFDESIREDSSID,
 					bytebuf,
@@ -1075,7 +1075,7 @@
 *	process thread  (usually)
 *	interrupt
 ----------------------------------------------------------------*/
-int prism2mgmt_wlansniff(wlandevice_t *wlandev, void *msgp)
+int prism2mgmt_wlansniff(wlandevice_t * wlandev, void *msgp)
 {
 	int result = 0;
 	p80211msg_lnxreq_wlansniff_t *msg = msgp;
@@ -1096,17 +1096,16 @@
 		/* Disable monitor mode */
 		result = hfa384x_cmd_monitor(hw, HFA384x_MONITOR_DISABLE);
 		if (result) {
-			printk(KERN_DEBUG
-			       "failed to disable monitor mode, result=%d\n",
-			       result);
+			pr_debug("failed to disable monitor mode, result=%d\n",
+				 result);
 			goto failed;
 		}
 		/* Disable port 0 */
 		result = hfa384x_drvr_disable(hw, 0);
 		if (result) {
-			printk(KERN_DEBUG
-			       "failed to disable port 0 after sniffing, result=%d\n",
-			       result);
+			pr_debug
+			    ("failed to disable port 0 after sniffing, result=%d\n",
+			     result);
 			goto failed;
 		}
 		/* Clear the driver state */
@@ -1117,9 +1116,9 @@
 						  HFA384x_RID_CNFWEPFLAGS,
 						  hw->presniff_wepflags);
 		if (result) {
-			printk(KERN_DEBUG
-			       "failed to restore wepflags=0x%04x, result=%d\n",
-			       hw->presniff_wepflags, result);
+			pr_debug
+			    ("failed to restore wepflags=0x%04x, result=%d\n",
+			     hw->presniff_wepflags, result);
 			goto failed;
 		}
 
@@ -1130,18 +1129,18 @@
 							  HFA384x_RID_CNFPORTTYPE,
 							  word);
 			if (result) {
-				printk(KERN_DEBUG
-				       "failed to restore porttype, result=%d\n",
-				       result);
+				pr_debug
+				    ("failed to restore porttype, result=%d\n",
+				     result);
 				goto failed;
 			}
 
 			/* Enable the port */
 			result = hfa384x_drvr_enable(hw, 0);
 			if (result) {
-				printk(KERN_DEBUG
-				       "failed to enable port to presniff setting, result=%d\n",
-				       result);
+				pr_debug
+				    ("failed to enable port to presniff setting, result=%d\n",
+				     result);
 				goto failed;
 			}
 		} else {
@@ -1161,40 +1160,42 @@
 				/* Save macport 0 state */
 				result = hfa384x_drvr_getconfig16(hw,
 								  HFA384x_RID_CNFPORTTYPE,
-								  &(hw->
-								    presniff_port_type));
+								  &
+								  (hw->
+								   presniff_port_type));
 				if (result) {
-					printk(KERN_DEBUG
-					       "failed to read porttype, result=%d\n",
-					       result);
+					pr_debug
+					    ("failed to read porttype, result=%d\n",
+					     result);
 					goto failed;
 				}
 				/* Save the wepflags state */
 				result = hfa384x_drvr_getconfig16(hw,
 								  HFA384x_RID_CNFWEPFLAGS,
-								  &(hw->
-								    presniff_wepflags));
+								  &
+								  (hw->
+								   presniff_wepflags));
 				if (result) {
-					printk(KERN_DEBUG
-					       "failed to read wepflags, result=%d\n",
-					       result);
+					pr_debug
+					    ("failed to read wepflags, result=%d\n",
+					     result);
 					goto failed;
 				}
 				hfa384x_drvr_stop(hw);
 				result = hfa384x_drvr_start(hw);
 				if (result) {
-					printk(KERN_DEBUG
-					       "failed to restart the card for sniffing, result=%d\n",
-					       result);
+					pr_debug
+					    ("failed to restart the card for sniffing, result=%d\n",
+					     result);
 					goto failed;
 				}
 			} else {
 				/* Disable the port */
 				result = hfa384x_drvr_disable(hw, 0);
 				if (result) {
-					printk(KERN_DEBUG
-					       "failed to enable port for sniffing, result=%d\n",
-					       result);
+					pr_debug
+					    ("failed to enable port for sniffing, result=%d\n",
+					     result);
 					goto failed;
 				}
 			}
@@ -1210,9 +1211,8 @@
 		hw->sniff_channel = word;
 
 		if (result) {
-			printk(KERN_DEBUG
-			       "failed to set channel %d, result=%d\n",
-			       word, result);
+			pr_debug("failed to set channel %d, result=%d\n",
+				 word, result);
 			goto failed;
 		}
 
@@ -1224,9 +1224,9 @@
 							  HFA384x_RID_CNFPORTTYPE,
 							  word);
 			if (result) {
-				printk(KERN_DEBUG
-				       "failed to set porttype %d, result=%d\n",
-				       word, result);
+				pr_debug
+				    ("failed to set porttype %d, result=%d\n",
+				     word, result);
 				goto failed;
 			}
 			if ((msg->keepwepflags.status ==
@@ -1243,9 +1243,9 @@
 			}
 
 			if (result) {
-				printk(KERN_DEBUG
-				       "failed to set wepflags=0x%04x, result=%d\n",
-				       word, result);
+				pr_debug
+				    ("failed to set wepflags=0x%04x, result=%d\n",
+				     word, result);
 				goto failed;
 			}
 		}
@@ -1269,17 +1269,16 @@
 		/* Enable the port */
 		result = hfa384x_drvr_enable(hw, 0);
 		if (result) {
-			printk(KERN_DEBUG
-			       "failed to enable port for sniffing, result=%d\n",
-			       result);
+			pr_debug
+			    ("failed to enable port for sniffing, result=%d\n",
+			     result);
 			goto failed;
 		}
 		/* Enable monitor mode */
 		result = hfa384x_cmd_monitor(hw, HFA384x_MONITOR_ENABLE);
 		if (result) {
-			printk(KERN_DEBUG
-			       "failed to enable monitor mode, result=%d\n",
-			       result);
+			pr_debug("failed to enable monitor mode, result=%d\n",
+				 result);
 			goto failed;
 		}
 
diff --git a/drivers/staging/wlan-ng/prism2mgmt.h b/drivers/staging/wlan-ng/prism2mgmt.h
index 07eeceb..bdf2b3e 100644
--- a/drivers/staging/wlan-ng/prism2mgmt.h
+++ b/drivers/staging/wlan-ng/prism2mgmt.h
@@ -63,43 +63,43 @@
 extern int prism2_reset_holdtime;
 extern int prism2_reset_settletime;
 
-u32 prism2sta_ifstate(wlandevice_t *wlandev, u32 ifstate);
+u32 prism2sta_ifstate(wlandevice_t * wlandev, u32 ifstate);
 
-void prism2sta_ev_info(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf);
-void prism2sta_ev_txexc(wlandevice_t *wlandev, u16 status);
-void prism2sta_ev_tx(wlandevice_t *wlandev, u16 status);
-void prism2sta_ev_rx(wlandevice_t *wlandev, struct sk_buff *skb);
-void prism2sta_ev_alloc(wlandevice_t *wlandev);
+void prism2sta_ev_info(wlandevice_t * wlandev, hfa384x_InfFrame_t * inf);
+void prism2sta_ev_txexc(wlandevice_t * wlandev, u16 status);
+void prism2sta_ev_tx(wlandevice_t * wlandev, u16 status);
+void prism2sta_ev_rx(wlandevice_t * wlandev, struct sk_buff *skb);
+void prism2sta_ev_alloc(wlandevice_t * wlandev);
 
-int prism2mgmt_mibset_mibget(wlandevice_t *wlandev, void *msgp);
-int prism2mgmt_scan(wlandevice_t *wlandev, void *msgp);
-int prism2mgmt_scan_results(wlandevice_t *wlandev, void *msgp);
-int prism2mgmt_start(wlandevice_t *wlandev, void *msgp);
-int prism2mgmt_wlansniff(wlandevice_t *wlandev, void *msgp);
-int prism2mgmt_readpda(wlandevice_t *wlandev, void *msgp);
-int prism2mgmt_ramdl_state(wlandevice_t *wlandev, void *msgp);
-int prism2mgmt_ramdl_write(wlandevice_t *wlandev, void *msgp);
-int prism2mgmt_flashdl_state(wlandevice_t *wlandev, void *msgp);
-int prism2mgmt_flashdl_write(wlandevice_t *wlandev, void *msgp);
-int prism2mgmt_autojoin(wlandevice_t *wlandev, void *msgp);
+int prism2mgmt_mibset_mibget(wlandevice_t * wlandev, void *msgp);
+int prism2mgmt_scan(wlandevice_t * wlandev, void *msgp);
+int prism2mgmt_scan_results(wlandevice_t * wlandev, void *msgp);
+int prism2mgmt_start(wlandevice_t * wlandev, void *msgp);
+int prism2mgmt_wlansniff(wlandevice_t * wlandev, void *msgp);
+int prism2mgmt_readpda(wlandevice_t * wlandev, void *msgp);
+int prism2mgmt_ramdl_state(wlandevice_t * wlandev, void *msgp);
+int prism2mgmt_ramdl_write(wlandevice_t * wlandev, void *msgp);
+int prism2mgmt_flashdl_state(wlandevice_t * wlandev, void *msgp);
+int prism2mgmt_flashdl_write(wlandevice_t * wlandev, void *msgp);
+int prism2mgmt_autojoin(wlandevice_t * wlandev, void *msgp);
 
 /*---------------------------------------------------------------
 * conversion functions going between wlan message data types and
 * Prism2 data types
 ---------------------------------------------------------------*/
 /* byte area conversion functions*/
-void prism2mgmt_pstr2bytearea(u8 *bytearea, p80211pstrd_t *pstr);
-void prism2mgmt_bytearea2pstr(u8 *bytearea, p80211pstrd_t *pstr, int len);
+void prism2mgmt_pstr2bytearea(u8 * bytearea, p80211pstrd_t * pstr);
+void prism2mgmt_bytearea2pstr(u8 * bytearea, p80211pstrd_t * pstr, int len);
 
 /* byte string conversion functions*/
-void prism2mgmt_pstr2bytestr(hfa384x_bytestr_t *bytestr, p80211pstrd_t *pstr);
-void prism2mgmt_bytestr2pstr(hfa384x_bytestr_t *bytestr, p80211pstrd_t *pstr);
+void prism2mgmt_pstr2bytestr(hfa384x_bytestr_t * bytestr, p80211pstrd_t * pstr);
+void prism2mgmt_bytestr2pstr(hfa384x_bytestr_t * bytestr, p80211pstrd_t * pstr);
 
 /* functions to convert Group Addresses */
-void prism2mgmt_get_grpaddr(u32 did, p80211pstrd_t *pstr, hfa384x_t *priv);
+void prism2mgmt_get_grpaddr(u32 did, p80211pstrd_t * pstr, hfa384x_t * priv);
 int prism2mgmt_set_grpaddr(u32 did,
-			   u8 *prism2buf, p80211pstrd_t *pstr,
-			   hfa384x_t *priv);
+			   u8 * prism2buf, p80211pstrd_t * pstr,
+			   hfa384x_t * priv);
 int prism2mgmt_get_grpaddr_index(u32 did);
 
 void prism2sta_processing_defer(struct work_struct *data);
diff --git a/drivers/staging/wlan-ng/prism2mib.c b/drivers/staging/wlan-ng/prism2mib.c
index 5a6ba86..f930254 100644
--- a/drivers/staging/wlan-ng/prism2mib.c
+++ b/drivers/staging/wlan-ng/prism2mib.c
@@ -50,7 +50,6 @@
 * --------------------------------------------------------------------
 */
 
-#include <linux/version.h>
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/sched.h>
@@ -87,65 +86,65 @@
 	u16 parm1;
 	u16 parm2;
 	u16 parm3;
-	int (*func) (struct mibrec *mib,
+	int (*func) (struct mibrec * mib,
 		     int isget,
-		     wlandevice_t *wlandev,
-		     hfa384x_t *hw,
-		     p80211msg_dot11req_mibset_t *msg, void *data);
+		     wlandevice_t * wlandev,
+		     hfa384x_t * hw,
+		     p80211msg_dot11req_mibset_t * msg, void *data);
 } mibrec_t;
 
-static int prism2mib_bytearea2pstr(mibrec_t *mib,
+static int prism2mib_bytearea2pstr(mibrec_t * mib,
 				   int isget,
-				   wlandevice_t *wlandev,
-				   hfa384x_t *hw,
-				   p80211msg_dot11req_mibset_t *msg,
+				   wlandevice_t * wlandev,
+				   hfa384x_t * hw,
+				   p80211msg_dot11req_mibset_t * msg,
 				   void *data);
 
-static int prism2mib_uint32(mibrec_t *mib,
+static int prism2mib_uint32(mibrec_t * mib,
 			    int isget,
-			    wlandevice_t *wlandev,
-			    hfa384x_t *hw,
-			    p80211msg_dot11req_mibset_t *msg, void *data);
+			    wlandevice_t * wlandev,
+			    hfa384x_t * hw,
+			    p80211msg_dot11req_mibset_t * msg, void *data);
 
-static int prism2mib_flag(mibrec_t *mib,
+static int prism2mib_flag(mibrec_t * mib,
 			  int isget,
-			  wlandevice_t *wlandev,
-			  hfa384x_t *hw,
-			  p80211msg_dot11req_mibset_t *msg, void *data);
+			  wlandevice_t * wlandev,
+			  hfa384x_t * hw,
+			  p80211msg_dot11req_mibset_t * msg, void *data);
 
-static int prism2mib_wepdefaultkey(mibrec_t *mib,
+static int prism2mib_wepdefaultkey(mibrec_t * mib,
 				   int isget,
-				   wlandevice_t *wlandev,
-				   hfa384x_t *hw,
-				   p80211msg_dot11req_mibset_t *msg,
+				   wlandevice_t * wlandev,
+				   hfa384x_t * hw,
+				   p80211msg_dot11req_mibset_t * msg,
 				   void *data);
 
-static int prism2mib_privacyinvoked(mibrec_t *mib,
+static int prism2mib_privacyinvoked(mibrec_t * mib,
 				    int isget,
-				    wlandevice_t *wlandev,
-				    hfa384x_t *hw,
-				    p80211msg_dot11req_mibset_t *msg,
+				    wlandevice_t * wlandev,
+				    hfa384x_t * hw,
+				    p80211msg_dot11req_mibset_t * msg,
 				    void *data);
 
-static int prism2mib_excludeunencrypted(mibrec_t *mib,
+static int prism2mib_excludeunencrypted(mibrec_t * mib,
 					int isget,
-					wlandevice_t *wlandev,
-					hfa384x_t *hw,
-					p80211msg_dot11req_mibset_t *msg,
+					wlandevice_t * wlandev,
+					hfa384x_t * hw,
+					p80211msg_dot11req_mibset_t * msg,
 					void *data);
 
-static int prism2mib_fragmentationthreshold(mibrec_t *mib,
+static int prism2mib_fragmentationthreshold(mibrec_t * mib,
 					    int isget,
-					    wlandevice_t *wlandev,
-					    hfa384x_t *hw,
-					    p80211msg_dot11req_mibset_t *msg,
+					    wlandevice_t * wlandev,
+					    hfa384x_t * hw,
+					    p80211msg_dot11req_mibset_t * msg,
 					    void *data);
 
-static int prism2mib_priv(mibrec_t *mib,
+static int prism2mib_priv(mibrec_t * mib,
 			  int isget,
-			  wlandevice_t *wlandev,
-			  hfa384x_t *hw,
-			  p80211msg_dot11req_mibset_t *msg, void *data);
+			  wlandevice_t * wlandev,
+			  hfa384x_t * hw,
+			  p80211msg_dot11req_mibset_t * msg, void *data);
 
 static mibrec_t mibtab[] = {
 
@@ -259,7 +258,7 @@
 *	interrupt
 ----------------------------------------------------------------*/
 
-int prism2mgmt_mibset_mibget(wlandevice_t *wlandev, void *msgp)
+int prism2mgmt_mibset_mibget(wlandevice_t * wlandev, void *msgp)
 {
 	hfa384x_t *hw = wlandev->priv;
 	int result, isget;
@@ -331,8 +330,7 @@
 
 	if (msg->resultcode.data == P80211ENUM_resultcode_success) {
 		if (result != 0) {
-			pr_debug("get/set failure, result=%d\n",
-			       result);
+			pr_debug("get/set failure, result=%d\n", result);
 			msg->resultcode.data =
 			    P80211ENUM_resultcode_implementation_failure;
 		} else {
@@ -374,11 +372,11 @@
 *
 ----------------------------------------------------------------*/
 
-static int prism2mib_bytearea2pstr(mibrec_t *mib,
+static int prism2mib_bytearea2pstr(mibrec_t * mib,
 				   int isget,
-				   wlandevice_t *wlandev,
-				   hfa384x_t *hw,
-				   p80211msg_dot11req_mibset_t *msg,
+				   wlandevice_t * wlandev,
+				   hfa384x_t * hw,
+				   p80211msg_dot11req_mibset_t * msg,
 				   void *data)
 {
 	int result;
@@ -424,11 +422,11 @@
 *
 ----------------------------------------------------------------*/
 
-static int prism2mib_uint32(mibrec_t *mib,
+static int prism2mib_uint32(mibrec_t * mib,
 			    int isget,
-			    wlandevice_t *wlandev,
-			    hfa384x_t *hw,
-			    p80211msg_dot11req_mibset_t *msg, void *data)
+			    wlandevice_t * wlandev,
+			    hfa384x_t * hw,
+			    p80211msg_dot11req_mibset_t * msg, void *data)
 {
 	int result;
 	u32 *uint32 = (u32 *) data;
@@ -471,11 +469,11 @@
 *
 ----------------------------------------------------------------*/
 
-static int prism2mib_flag(mibrec_t *mib,
+static int prism2mib_flag(mibrec_t * mib,
 			  int isget,
-			  wlandevice_t *wlandev,
-			  hfa384x_t *hw,
-			  p80211msg_dot11req_mibset_t *msg, void *data)
+			  wlandevice_t * wlandev,
+			  hfa384x_t * hw,
+			  p80211msg_dot11req_mibset_t * msg, void *data)
 {
 	int result;
 	u32 *uint32 = (u32 *) data;
@@ -528,11 +526,11 @@
 *
 ----------------------------------------------------------------*/
 
-static int prism2mib_wepdefaultkey(mibrec_t *mib,
+static int prism2mib_wepdefaultkey(mibrec_t * mib,
 				   int isget,
-				   wlandevice_t *wlandev,
-				   hfa384x_t *hw,
-				   p80211msg_dot11req_mibset_t *msg,
+				   wlandevice_t * wlandev,
+				   hfa384x_t * hw,
+				   p80211msg_dot11req_mibset_t * msg,
 				   void *data)
 {
 	int result;
@@ -578,11 +576,11 @@
 *
 ----------------------------------------------------------------*/
 
-static int prism2mib_privacyinvoked(mibrec_t *mib,
+static int prism2mib_privacyinvoked(mibrec_t * mib,
 				    int isget,
-				    wlandevice_t *wlandev,
-				    hfa384x_t *hw,
-				    p80211msg_dot11req_mibset_t *msg,
+				    wlandevice_t * wlandev,
+				    hfa384x_t * hw,
+				    p80211msg_dot11req_mibset_t * msg,
 				    void *data)
 {
 	int result;
@@ -624,11 +622,11 @@
 *
 ----------------------------------------------------------------*/
 
-static int prism2mib_excludeunencrypted(mibrec_t *mib,
+static int prism2mib_excludeunencrypted(mibrec_t * mib,
 					int isget,
-					wlandevice_t *wlandev,
-					hfa384x_t *hw,
-					p80211msg_dot11req_mibset_t *msg,
+					wlandevice_t * wlandev,
+					hfa384x_t * hw,
+					p80211msg_dot11req_mibset_t * msg,
 					void *data)
 {
 	int result;
@@ -663,11 +661,11 @@
 *
 ----------------------------------------------------------------*/
 
-static int prism2mib_fragmentationthreshold(mibrec_t *mib,
+static int prism2mib_fragmentationthreshold(mibrec_t * mib,
 					    int isget,
-					    wlandevice_t *wlandev,
-					    hfa384x_t *hw,
-					    p80211msg_dot11req_mibset_t *msg,
+					    wlandevice_t * wlandev,
+					    hfa384x_t * hw,
+					    p80211msg_dot11req_mibset_t * msg,
 					    void *data)
 {
 	int result;
@@ -712,11 +710,11 @@
 *
 ----------------------------------------------------------------*/
 
-static int prism2mib_priv(mibrec_t *mib,
+static int prism2mib_priv(mibrec_t * mib,
 			  int isget,
-			  wlandevice_t *wlandev,
-			  hfa384x_t *hw,
-			  p80211msg_dot11req_mibset_t *msg, void *data)
+			  wlandevice_t * wlandev,
+			  hfa384x_t * hw,
+			  p80211msg_dot11req_mibset_t * msg, void *data)
 {
 	p80211pstrd_t *pstr = (p80211pstrd_t *) data;
 
@@ -728,7 +726,7 @@
 			if (isget) {
 				hfa384x_drvr_getconfig(hw,
 						       HFA384x_RID_CNFWPADATA,
-						       (u8 *)&wpa,
+						       (u8 *) & wpa,
 						       sizeof(wpa));
 				pstr->len = le16_to_cpu(wpa.datalen);
 				memcpy(pstr->data, wpa.data, pstr->len);
@@ -739,7 +737,7 @@
 				result =
 				    hfa384x_drvr_setconfig(hw,
 							   HFA384x_RID_CNFWPADATA,
-							   (u8 *)&wpa,
+							   (u8 *) & wpa,
 							   sizeof(wpa));
 			}
 			break;
@@ -766,7 +764,7 @@
 *
 ----------------------------------------------------------------*/
 
-void prism2mgmt_pstr2bytestr(hfa384x_bytestr_t *bytestr, p80211pstrd_t *pstr)
+void prism2mgmt_pstr2bytestr(hfa384x_bytestr_t * bytestr, p80211pstrd_t * pstr)
 {
 	bytestr->len = cpu_to_le16((u16) (pstr->len));
 	memcpy(bytestr->data, pstr->data, pstr->len);
@@ -787,7 +785,7 @@
 *
 ----------------------------------------------------------------*/
 
-void prism2mgmt_pstr2bytearea(u8 *bytearea, p80211pstrd_t *pstr)
+void prism2mgmt_pstr2bytearea(u8 * bytearea, p80211pstrd_t * pstr)
 {
 	memcpy(bytearea, pstr->data, pstr->len);
 }
@@ -807,7 +805,7 @@
 *
 ----------------------------------------------------------------*/
 
-void prism2mgmt_bytestr2pstr(hfa384x_bytestr_t *bytestr, p80211pstrd_t *pstr)
+void prism2mgmt_bytestr2pstr(hfa384x_bytestr_t * bytestr, p80211pstrd_t * pstr)
 {
 	pstr->len = (u8) (le16_to_cpu((u16) (bytestr->len)));
 	memcpy(pstr->data, bytestr->data, pstr->len);
@@ -828,13 +826,8 @@
 *
 ----------------------------------------------------------------*/
 
-void prism2mgmt_bytearea2pstr(u8 *bytearea, p80211pstrd_t *pstr, int len)
+void prism2mgmt_bytearea2pstr(u8 * bytearea, p80211pstrd_t * pstr, int len)
 {
 	pstr->len = (u8) len;
 	memcpy(pstr->data, bytearea, len);
 }
-
-
-
-
-
diff --git a/drivers/staging/wlan-ng/prism2sta.c b/drivers/staging/wlan-ng/prism2sta.c
index 9d57f82..f493cf4 100644
--- a/drivers/staging/wlan-ng/prism2sta.c
+++ b/drivers/staging/wlan-ng/prism2sta.c
@@ -127,37 +127,37 @@
 
 MODULE_LICENSE("Dual MPL/GPL");
 
-static int prism2sta_open(wlandevice_t *wlandev);
-static int prism2sta_close(wlandevice_t *wlandev);
-static void prism2sta_reset(wlandevice_t *wlandev);
-static int prism2sta_txframe(wlandevice_t *wlandev, struct sk_buff *skb,
-			     p80211_hdr_t *p80211_hdr,
-			     p80211_metawep_t *p80211_wep);
-static int prism2sta_mlmerequest(wlandevice_t *wlandev, p80211msg_t *msg);
-static int prism2sta_getcardinfo(wlandevice_t *wlandev);
-static int prism2sta_globalsetup(wlandevice_t *wlandev);
-static int prism2sta_setmulticast(wlandevice_t *wlandev, netdevice_t *dev);
+static int prism2sta_open(wlandevice_t * wlandev);
+static int prism2sta_close(wlandevice_t * wlandev);
+static void prism2sta_reset(wlandevice_t * wlandev);
+static int prism2sta_txframe(wlandevice_t * wlandev, struct sk_buff *skb,
+			     p80211_hdr_t * p80211_hdr,
+			     p80211_metawep_t * p80211_wep);
+static int prism2sta_mlmerequest(wlandevice_t * wlandev, p80211msg_t * msg);
+static int prism2sta_getcardinfo(wlandevice_t * wlandev);
+static int prism2sta_globalsetup(wlandevice_t * wlandev);
+static int prism2sta_setmulticast(wlandevice_t * wlandev, netdevice_t * dev);
 
-static void prism2sta_inf_handover(wlandevice_t *wlandev,
-				   hfa384x_InfFrame_t *inf);
-static void prism2sta_inf_tallies(wlandevice_t *wlandev,
-				  hfa384x_InfFrame_t *inf);
-static void prism2sta_inf_hostscanresults(wlandevice_t *wlandev,
-					  hfa384x_InfFrame_t *inf);
-static void prism2sta_inf_scanresults(wlandevice_t *wlandev,
-				      hfa384x_InfFrame_t *inf);
-static void prism2sta_inf_chinforesults(wlandevice_t *wlandev,
-					hfa384x_InfFrame_t *inf);
-static void prism2sta_inf_linkstatus(wlandevice_t *wlandev,
-				     hfa384x_InfFrame_t *inf);
-static void prism2sta_inf_assocstatus(wlandevice_t *wlandev,
-				      hfa384x_InfFrame_t *inf);
-static void prism2sta_inf_authreq(wlandevice_t *wlandev,
-				  hfa384x_InfFrame_t *inf);
-static void prism2sta_inf_authreq_defer(wlandevice_t *wlandev,
-					hfa384x_InfFrame_t *inf);
-static void prism2sta_inf_psusercnt(wlandevice_t *wlandev,
-				    hfa384x_InfFrame_t *inf);
+static void prism2sta_inf_handover(wlandevice_t * wlandev,
+				   hfa384x_InfFrame_t * inf);
+static void prism2sta_inf_tallies(wlandevice_t * wlandev,
+				  hfa384x_InfFrame_t * inf);
+static void prism2sta_inf_hostscanresults(wlandevice_t * wlandev,
+					  hfa384x_InfFrame_t * inf);
+static void prism2sta_inf_scanresults(wlandevice_t * wlandev,
+				      hfa384x_InfFrame_t * inf);
+static void prism2sta_inf_chinforesults(wlandevice_t * wlandev,
+					hfa384x_InfFrame_t * inf);
+static void prism2sta_inf_linkstatus(wlandevice_t * wlandev,
+				     hfa384x_InfFrame_t * inf);
+static void prism2sta_inf_assocstatus(wlandevice_t * wlandev,
+				      hfa384x_InfFrame_t * inf);
+static void prism2sta_inf_authreq(wlandevice_t * wlandev,
+				  hfa384x_InfFrame_t * inf);
+static void prism2sta_inf_authreq_defer(wlandevice_t * wlandev,
+					hfa384x_InfFrame_t * inf);
+static void prism2sta_inf_psusercnt(wlandevice_t * wlandev,
+				    hfa384x_InfFrame_t * inf);
 
 /*----------------------------------------------------------------
 * prism2sta_open
@@ -180,7 +180,7 @@
 * Call context:
 *	process thread
 ----------------------------------------------------------------*/
-static int prism2sta_open(wlandevice_t *wlandev)
+static int prism2sta_open(wlandevice_t * wlandev)
 {
 	/* We don't currently have to do anything else.
 	 * The setup of the MAC should be subsequently completed via
@@ -214,7 +214,7 @@
 * Call context:
 *	process thread
 ----------------------------------------------------------------*/
-static int prism2sta_close(wlandevice_t *wlandev)
+static int prism2sta_close(wlandevice_t * wlandev)
 {
 	/* We don't currently have to do anything else.
 	 * Higher layers know we're not ready from dev->start==0 and
@@ -242,7 +242,7 @@
 * Call context:
 *	process thread
 ----------------------------------------------------------------*/
-static void prism2sta_reset(wlandevice_t *wlandev)
+static void prism2sta_reset(wlandevice_t * wlandev)
 {
 	return;
 }
@@ -268,9 +268,9 @@
 * Call context:
 *	process thread
 ----------------------------------------------------------------*/
-static int prism2sta_txframe(wlandevice_t *wlandev, struct sk_buff *skb,
-			     p80211_hdr_t *p80211_hdr,
-			     p80211_metawep_t *p80211_wep)
+static int prism2sta_txframe(wlandevice_t * wlandev, struct sk_buff *skb,
+			     p80211_hdr_t * p80211_hdr,
+			     p80211_metawep_t * p80211_wep)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 	int result;
@@ -310,7 +310,7 @@
 * Call context:
 *	process thread
 ----------------------------------------------------------------*/
-static int prism2sta_mlmerequest(wlandevice_t *wlandev, p80211msg_t *msg)
+static int prism2sta_mlmerequest(wlandevice_t * wlandev, p80211msg_t * msg)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 
@@ -401,12 +401,9 @@
 			qualmsg->noise.status =
 			    P80211ENUM_msgitem_status_data_ok;
 
-			qualmsg->link.data =
-			    le16_to_cpu(hw->qual.CQ_currBSS);
-			qualmsg->level.data =
-			    le16_to_cpu(hw->qual.ASL_currBSS);
-			qualmsg->noise.data =
-			    le16_to_cpu(hw->qual.ANL_currFC);
+			qualmsg->link.data = le16_to_cpu(hw->qual.CQ_currBSS);
+			qualmsg->level.data = le16_to_cpu(hw->qual.ASL_currBSS);
+			qualmsg->noise.data = le16_to_cpu(hw->qual.ANL_currFC);
 
 			break;
 		}
@@ -440,7 +437,7 @@
 *	process thread  (usually)
 *	interrupt
 ----------------------------------------------------------------*/
-u32 prism2sta_ifstate(wlandevice_t *wlandev, u32 ifstate)
+u32 prism2sta_ifstate(wlandevice_t * wlandev, u32 ifstate)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 	u32 result;
@@ -448,7 +445,7 @@
 	result = P80211ENUM_resultcode_implementation_failure;
 
 	pr_debug("Current MSD state(%d), requesting(%d)\n",
-	       wlandev->msdstate, ifstate);
+		 wlandev->msdstate, ifstate);
 	switch (ifstate) {
 	case P80211ENUM_ifstate_fwload:
 		switch (wlandev->msdstate) {
@@ -610,7 +607,7 @@
 * Call context:
 *	Either.
 ----------------------------------------------------------------*/
-static int prism2sta_getcardinfo(wlandevice_t *wlandev)
+static int prism2sta_getcardinfo(wlandevice_t * wlandev)
 {
 	int result = 0;
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
@@ -811,10 +808,8 @@
 	   fields in byte order */
 	hw->cap_act_pri_cfi.role = le16_to_cpu(hw->cap_act_pri_cfi.role);
 	hw->cap_act_pri_cfi.id = le16_to_cpu(hw->cap_act_pri_cfi.id);
-	hw->cap_act_pri_cfi.variant =
-	    le16_to_cpu(hw->cap_act_pri_cfi.variant);
-	hw->cap_act_pri_cfi.bottom =
-	    le16_to_cpu(hw->cap_act_pri_cfi.bottom);
+	hw->cap_act_pri_cfi.variant = le16_to_cpu(hw->cap_act_pri_cfi.variant);
+	hw->cap_act_pri_cfi.bottom = le16_to_cpu(hw->cap_act_pri_cfi.bottom);
 	hw->cap_act_pri_cfi.top = le16_to_cpu(hw->cap_act_pri_cfi.top);
 
 	printk(KERN_INFO
@@ -836,10 +831,8 @@
 	   fields in byte order */
 	hw->cap_act_sta_cfi.role = le16_to_cpu(hw->cap_act_sta_cfi.role);
 	hw->cap_act_sta_cfi.id = le16_to_cpu(hw->cap_act_sta_cfi.id);
-	hw->cap_act_sta_cfi.variant =
-	    le16_to_cpu(hw->cap_act_sta_cfi.variant);
-	hw->cap_act_sta_cfi.bottom =
-	    le16_to_cpu(hw->cap_act_sta_cfi.bottom);
+	hw->cap_act_sta_cfi.variant = le16_to_cpu(hw->cap_act_sta_cfi.variant);
+	hw->cap_act_sta_cfi.bottom = le16_to_cpu(hw->cap_act_sta_cfi.bottom);
 	hw->cap_act_sta_cfi.top = le16_to_cpu(hw->cap_act_sta_cfi.top);
 
 	printk(KERN_INFO
@@ -861,10 +854,8 @@
 	   fields in byte order */
 	hw->cap_act_sta_mfi.role = le16_to_cpu(hw->cap_act_sta_mfi.role);
 	hw->cap_act_sta_mfi.id = le16_to_cpu(hw->cap_act_sta_mfi.id);
-	hw->cap_act_sta_mfi.variant =
-	    le16_to_cpu(hw->cap_act_sta_mfi.variant);
-	hw->cap_act_sta_mfi.bottom =
-	    le16_to_cpu(hw->cap_act_sta_mfi.bottom);
+	hw->cap_act_sta_mfi.variant = le16_to_cpu(hw->cap_act_sta_mfi.variant);
+	hw->cap_act_sta_mfi.bottom = le16_to_cpu(hw->cap_act_sta_mfi.bottom);
 	hw->cap_act_sta_mfi.top = le16_to_cpu(hw->cap_act_sta_mfi.top);
 
 	printk(KERN_INFO
@@ -940,7 +931,7 @@
 * Call context:
 *	process thread
 ----------------------------------------------------------------*/
-static int prism2sta_globalsetup(wlandevice_t *wlandev)
+static int prism2sta_globalsetup(wlandevice_t * wlandev)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 
@@ -949,7 +940,7 @@
 					WLAN_DATA_MAXLEN);
 }
 
-static int prism2sta_setmulticast(wlandevice_t *wlandev, netdevice_t *dev)
+static int prism2sta_setmulticast(wlandevice_t * wlandev, netdevice_t * dev)
 {
 	int result = 0;
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
@@ -990,8 +981,8 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void prism2sta_inf_handover(wlandevice_t *wlandev,
-				   hfa384x_InfFrame_t *inf)
+static void prism2sta_inf_handover(wlandevice_t * wlandev,
+				   hfa384x_InfFrame_t * inf)
 {
 	pr_debug("received infoframe:HANDOVER (unhandled)\n");
 	return;
@@ -1014,8 +1005,8 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void prism2sta_inf_tallies(wlandevice_t *wlandev,
-				  hfa384x_InfFrame_t *inf)
+static void prism2sta_inf_tallies(wlandevice_t * wlandev,
+				  hfa384x_InfFrame_t * inf)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 	u16 *src16;
@@ -1031,13 +1022,13 @@
 
 	cnt = sizeof(hfa384x_CommTallies32_t) / sizeof(u32);
 	if (inf->framelen > 22) {
-		dst = (u32 *)&hw->tallies;
-		src32 = (u32 *)&inf->info.commtallies32;
+		dst = (u32 *) & hw->tallies;
+		src32 = (u32 *) & inf->info.commtallies32;
 		for (i = 0; i < cnt; i++, dst++, src32++)
 			*dst += le32_to_cpu(*src32);
 	} else {
-		dst = (u32 *)&hw->tallies;
-		src16 = (u16 *)&inf->info.commtallies16;
+		dst = (u32 *) & hw->tallies;
+		src16 = (u16 *) & inf->info.commtallies16;
 		for (i = 0; i < cnt; i++, dst++, src16++)
 			*dst += le16_to_cpu(*src16);
 	}
@@ -1062,8 +1053,8 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void prism2sta_inf_scanresults(wlandevice_t *wlandev,
-				      hfa384x_InfFrame_t *inf)
+static void prism2sta_inf_scanresults(wlandevice_t * wlandev,
+				      hfa384x_InfFrame_t * inf)
 {
 
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
@@ -1080,14 +1071,14 @@
 
 	/* Print em */
 	pr_debug("rx scanresults, reason=%d, nbss=%d:\n",
-	       inf->info.scanresult.scanreason, nbss);
+		 inf->info.scanresult.scanreason, nbss);
 	for (i = 0; i < nbss; i++) {
 		pr_debug("chid=%d anl=%d sl=%d bcnint=%d\n",
-		       sr->result[i].chid,
-		       sr->result[i].anl,
-		       sr->result[i].sl, sr->result[i].bcnint);
+			 sr->result[i].chid,
+			 sr->result[i].anl,
+			 sr->result[i].sl, sr->result[i].bcnint);
 		pr_debug("  capinfo=0x%04x proberesp_rate=%d\n",
-		       sr->result[i].capinfo, sr->result[i].proberesp_rate);
+			 sr->result[i].capinfo, sr->result[i].proberesp_rate);
 	}
 	/* issue a join request */
 	joinreq.channel = sr->result[0].chid;
@@ -1120,8 +1111,8 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void prism2sta_inf_hostscanresults(wlandevice_t *wlandev,
-					  hfa384x_InfFrame_t *inf)
+static void prism2sta_inf_hostscanresults(wlandevice_t * wlandev,
+					  hfa384x_InfFrame_t * inf)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 	int nbss;
@@ -1162,8 +1153,8 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void prism2sta_inf_chinforesults(wlandevice_t *wlandev,
-					hfa384x_InfFrame_t *inf)
+static void prism2sta_inf_chinforesults(wlandevice_t * wlandev,
+					hfa384x_InfFrame_t * inf)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 	unsigned int i, n;
@@ -1174,29 +1165,26 @@
 	for (i = 0, n = 0; i < HFA384x_CHINFORESULT_MAX; i++) {
 		if (hw->channel_info.results.scanchannels & (1 << i)) {
 			int channel =
-			    le16_to_cpu(inf->info.chinforesult.result[n].
-					    chid) - 1;
+			    le16_to_cpu(inf->info.chinforesult.result[n].chid) -
+			    1;
 			hfa384x_ChInfoResultSub_t *chinforesult =
 			    &hw->channel_info.results.result[channel];
 			chinforesult->chid = channel;
 			chinforesult->anl =
-			    le16_to_cpu(inf->info.chinforesult.result[n].
-					    anl);
+			    le16_to_cpu(inf->info.chinforesult.result[n].anl);
 			chinforesult->pnl =
-			    le16_to_cpu(inf->info.chinforesult.result[n].
-					    pnl);
+			    le16_to_cpu(inf->info.chinforesult.result[n].pnl);
 			chinforesult->active =
 			    le16_to_cpu(inf->info.chinforesult.result[n].
-					    active);
-			printk(KERN_DEBUG
-			       "chinfo: channel %d, %s level (avg/peak)=%d/%d dB, pcf %d\n",
-			       channel + 1,
-			       chinforesult->
-			       active & HFA384x_CHINFORESULT_BSSACTIVE ?
-			       "signal" : "noise", chinforesult->anl,
-			       chinforesult->pnl,
-			       chinforesult->
-			       active & HFA384x_CHINFORESULT_PCFACTIVE ? 1 : 0);
+					active);
+			pr_debug
+			    ("chinfo: channel %d, %s level (avg/peak)=%d/%d dB, pcf %d\n",
+			     channel + 1,
+			     chinforesult->
+			     active & HFA384x_CHINFORESULT_BSSACTIVE ? "signal"
+			     : "noise", chinforesult->anl, chinforesult->pnl,
+			     chinforesult->
+			     active & HFA384x_CHINFORESULT_PCFACTIVE ? 1 : 0);
 			n++;
 		}
 	}
@@ -1276,9 +1264,9 @@
 							wlandev->bssid,
 							WLAN_BSSID_LEN);
 			if (result) {
-				printk(KERN_DEBUG
-				       "getconfig(0x%02x) failed, result = %d\n",
-				       HFA384x_RID_CURRENTBSSID, result);
+				pr_debug
+				    ("getconfig(0x%02x) failed, result = %d\n",
+				     HFA384x_RID_CURRENTBSSID, result);
 				goto failed;
 			}
 
@@ -1286,23 +1274,23 @@
 							HFA384x_RID_CURRENTSSID,
 							&ssid, sizeof(ssid));
 			if (result) {
-				printk(KERN_DEBUG
-				       "getconfig(0x%02x) failed, result = %d\n",
-				       HFA384x_RID_CURRENTSSID, result);
+				pr_debug
+				    ("getconfig(0x%02x) failed, result = %d\n",
+				     HFA384x_RID_CURRENTSSID, result);
 				goto failed;
 			}
-			prism2mgmt_bytestr2pstr((hfa384x_bytestr_t *)&ssid,
-						(p80211pstrd_t *)&wlandev->
-						ssid);
+			prism2mgmt_bytestr2pstr((hfa384x_bytestr_t *) & ssid,
+						(p80211pstrd_t *) &
+						wlandev->ssid);
 
 			/* Collect the port status */
 			result = hfa384x_drvr_getconfig16(hw,
 							  HFA384x_RID_PORTSTATUS,
 							  &portstatus);
 			if (result) {
-				printk(KERN_DEBUG
-				       "getconfig(0x%02x) failed, result = %d\n",
-				       HFA384x_RID_PORTSTATUS, result);
+				pr_debug
+				    ("getconfig(0x%02x) failed, result = %d\n",
+				     HFA384x_RID_PORTSTATUS, result);
 				goto failed;
 			}
 			wlandev->macmode =
@@ -1366,9 +1354,8 @@
 						HFA384x_RID_CURRENTBSSID,
 						wlandev->bssid, WLAN_BSSID_LEN);
 		if (result) {
-			printk(KERN_DEBUG
-			       "getconfig(0x%02x) failed, result = %d\n",
-			       HFA384x_RID_CURRENTBSSID, result);
+			pr_debug("getconfig(0x%02x) failed, result = %d\n",
+				 HFA384x_RID_CURRENTBSSID, result);
 			goto failed;
 		}
 
@@ -1376,13 +1363,12 @@
 						HFA384x_RID_CURRENTSSID,
 						&ssid, sizeof(ssid));
 		if (result) {
-			printk(KERN_DEBUG
-			       "getconfig(0x%02x) failed, result = %d\n",
-			       HFA384x_RID_CURRENTSSID, result);
+			pr_debug("getconfig(0x%02x) failed, result = %d\n",
+				 HFA384x_RID_CURRENTSSID, result);
 			goto failed;
 		}
-		prism2mgmt_bytestr2pstr((hfa384x_bytestr_t *)&ssid,
-					(p80211pstrd_t *)&wlandev->ssid);
+		prism2mgmt_bytestr2pstr((hfa384x_bytestr_t *) & ssid,
+					(p80211pstrd_t *) & wlandev->ssid);
 
 		hw->link_status = HFA384x_LINK_CONNECTED;
 		netif_carrier_on(wlandev->netdev);
@@ -1482,8 +1468,8 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void prism2sta_inf_linkstatus(wlandevice_t *wlandev,
-				     hfa384x_InfFrame_t *inf)
+static void prism2sta_inf_linkstatus(wlandevice_t * wlandev,
+				     hfa384x_InfFrame_t * inf)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 
@@ -1512,8 +1498,8 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void prism2sta_inf_assocstatus(wlandevice_t *wlandev,
-				      hfa384x_InfFrame_t *inf)
+static void prism2sta_inf_assocstatus(wlandevice_t * wlandev,
+				      hfa384x_InfFrame_t * inf)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 	hfa384x_AssocStatus_t rec;
@@ -1574,8 +1560,8 @@
 *	interrupt
 *
 ----------------------------------------------------------------*/
-static void prism2sta_inf_authreq(wlandevice_t *wlandev,
-				  hfa384x_InfFrame_t *inf)
+static void prism2sta_inf_authreq(wlandevice_t * wlandev,
+				  hfa384x_InfFrame_t * inf)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 	struct sk_buff *skb;
@@ -1589,8 +1575,8 @@
 	}
 }
 
-static void prism2sta_inf_authreq_defer(wlandevice_t *wlandev,
-					hfa384x_InfFrame_t *inf)
+static void prism2sta_inf_authreq_defer(wlandevice_t * wlandev,
+					hfa384x_InfFrame_t * inf)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 	hfa384x_authenticateStation_data_t rec;
@@ -1763,8 +1749,8 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-static void prism2sta_inf_psusercnt(wlandevice_t *wlandev,
-				    hfa384x_InfFrame_t *inf)
+static void prism2sta_inf_psusercnt(wlandevice_t * wlandev,
+				    hfa384x_InfFrame_t * inf)
 {
 	hfa384x_t *hw = (hfa384x_t *) wlandev->priv;
 
@@ -1790,7 +1776,7 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-void prism2sta_ev_info(wlandevice_t *wlandev, hfa384x_InfFrame_t *inf)
+void prism2sta_ev_info(wlandevice_t * wlandev, hfa384x_InfFrame_t * inf)
 {
 	inf->infotype = le16_to_cpu(inf->infotype);
 	/* Dispatch */
@@ -1858,7 +1844,7 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-void prism2sta_ev_txexc(wlandevice_t *wlandev, u16 status)
+void prism2sta_ev_txexc(wlandevice_t * wlandev, u16 status)
 {
 	pr_debug("TxExc status=0x%x.\n", status);
 
@@ -1881,7 +1867,7 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-void prism2sta_ev_tx(wlandevice_t *wlandev, u16 status)
+void prism2sta_ev_tx(wlandevice_t * wlandev, u16 status)
 {
 	pr_debug("Tx Complete, status=0x%04x\n", status);
 	/* update linux network stats */
@@ -1905,7 +1891,7 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-void prism2sta_ev_rx(wlandevice_t *wlandev, struct sk_buff *skb)
+void prism2sta_ev_rx(wlandevice_t * wlandev, struct sk_buff *skb)
 {
 	p80211netdev_rx(wlandev, skb);
 	return;
@@ -1927,7 +1913,7 @@
 * Call context:
 *	interrupt
 ----------------------------------------------------------------*/
-void prism2sta_ev_alloc(wlandevice_t *wlandev)
+void prism2sta_ev_alloc(wlandevice_t * wlandev)
 {
 	netif_wake_queue(wlandev->netdev);
 	return;
@@ -2020,9 +2006,9 @@
 		}
 
 		pr_debug("commsqual %d %d %d\n",
-		       le16_to_cpu(hw->qual.CQ_currBSS),
-		       le16_to_cpu(hw->qual.ASL_currBSS),
-		       le16_to_cpu(hw->qual.ANL_currFC));
+			 le16_to_cpu(hw->qual.CQ_currBSS),
+			 le16_to_cpu(hw->qual.ASL_currBSS),
+			 le16_to_cpu(hw->qual.ANL_currFC));
 	}
 
 	/* Lastly, we need to make sure the BSSID didn't change on us */
@@ -2030,9 +2016,8 @@
 					HFA384x_RID_CURRENTBSSID,
 					wlandev->bssid, WLAN_BSSID_LEN);
 	if (result) {
-		printk(KERN_DEBUG
-		       "getconfig(0x%02x) failed, result = %d\n",
-		       HFA384x_RID_CURRENTBSSID, result);
+		pr_debug("getconfig(0x%02x) failed, result = %d\n",
+			 HFA384x_RID_CURRENTBSSID, result);
 		goto done;
 	}
 
@@ -2040,13 +2025,12 @@
 					HFA384x_RID_CURRENTSSID,
 					&ssid, sizeof(ssid));
 	if (result) {
-		printk(KERN_DEBUG
-		       "getconfig(0x%02x) failed, result = %d\n",
-		       HFA384x_RID_CURRENTSSID, result);
+		pr_debug("getconfig(0x%02x) failed, result = %d\n",
+			 HFA384x_RID_CURRENTSSID, result);
 		goto done;
 	}
-	prism2mgmt_bytestr2pstr((hfa384x_bytestr_t *)&ssid,
-				(p80211pstrd_t *)&wlandev->ssid);
+	prism2mgmt_bytestr2pstr((hfa384x_bytestr_t *) & ssid,
+				(p80211pstrd_t *) & wlandev->ssid);
 
 	/* Reschedule timer */
 	mod_timer(&hw->commsqual_timer, jiffies + HZ);
diff --git a/drivers/staging/wlan-ng/prism2usb.c b/drivers/staging/wlan-ng/prism2usb.c
index d8a1298..7aa703c 100644
--- a/drivers/staging/wlan-ng/prism2usb.c
+++ b/drivers/staging/wlan-ng/prism2usb.c
@@ -2,6 +2,7 @@
 #include "prism2mgmt.c"
 #include "prism2mib.c"
 #include "prism2sta.c"
+#include "prism2fw.c"
 
 #define PRISM_USB_DEVICE(vid, pid, name) \
            USB_DEVICE(vid, pid),  \
@@ -23,9 +24,8 @@
 	 (0x066b, 0x2213, "Linksys WUSB12v1.1 11Mbps WLAN USB Adapter")},
 	{PRISM_USB_DEVICE
 	 (0x067c, 0x1022, "Siemens SpeedStream 1022 11Mbps WLAN USB Adapter")},
-	{PRISM_USB_DEVICE
-	 (0x049f, 0x0033,
-	  "Compaq/Intel W100 PRO/Wireless 11Mbps multiport WLAN Adapter")},
+	{PRISM_USB_DEVICE(0x049f, 0x0033,
+			  "Compaq/Intel W100 PRO/Wireless 11Mbps multiport WLAN Adapter")},
 	{PRISM_USB_DEVICE
 	 (0x0411, 0x0016, "Melco WLI-USB-S11 11Mbps WLAN Adapter")},
 	{PRISM_USB_DEVICE
@@ -153,15 +153,16 @@
 
 	wlandev->msdstate = WLAN_MSD_HWPRESENT;
 
+	/* Try and load firmware, then enable card before we register */
+	prism2_fwtry(dev, wlandev);
+	prism2sta_ifstate(wlandev, P80211ENUM_ifstate_enable);
+
 	if (register_wlandev(wlandev) != 0) {
 		printk(KERN_ERR "%s: register_wlandev() failed.\n", dev_info);
 		result = -EIO;
 		goto failed;
 	}
 
-/* enable the card */
-	prism2sta_ifstate(wlandev, P80211ENUM_ifstate_enable);
-
 	goto done;
 
 failed:
@@ -170,7 +171,6 @@
 	wlandev = NULL;
 
 done:
-	p80211_allow_ioctls(wlandev);
 	usb_set_intfdata(interface, wlandev);
 	return result;
 }
diff --git a/drivers/usb/host/ehci-ps3.c b/drivers/usb/host/ehci-ps3.c
index eecd2a0..93f7035 100644
--- a/drivers/usb/host/ehci-ps3.c
+++ b/drivers/usb/host/ehci-ps3.c
@@ -77,7 +77,7 @@
 	.port_handed_over	= ehci_port_handed_over,
 };
 
-static int ps3_ehci_probe(struct ps3_system_bus_device *dev)
+static int __devinit ps3_ehci_probe(struct ps3_system_bus_device *dev)
 {
 	int result;
 	struct usb_hcd *hcd;
@@ -225,7 +225,7 @@
 	return 0;
 }
 
-static int ps3_ehci_driver_register(struct ps3_system_bus_driver *drv)
+static int __init ps3_ehci_driver_register(struct ps3_system_bus_driver *drv)
 {
 	return firmware_has_feature(FW_FEATURE_PS3_LV1)
 		? ps3_system_bus_driver_register(drv)
diff --git a/drivers/usb/host/ohci-ps3.c b/drivers/usb/host/ohci-ps3.c
index 1d56259..7009504 100644
--- a/drivers/usb/host/ohci-ps3.c
+++ b/drivers/usb/host/ohci-ps3.c
@@ -75,7 +75,7 @@
 #endif
 };
 
-static int ps3_ohci_probe(struct ps3_system_bus_device *dev)
+static int __devinit ps3_ohci_probe(struct ps3_system_bus_device *dev)
 {
 	int result;
 	struct usb_hcd *hcd;
@@ -224,7 +224,7 @@
 	return 0;
 }
 
-static int ps3_ohci_driver_register(struct ps3_system_bus_driver *drv)
+static int __init ps3_ohci_driver_register(struct ps3_system_bus_driver *drv)
 {
 	return firmware_has_feature(FW_FEATURE_PS3_LV1)
 		? ps3_system_bus_driver_register(drv)
diff --git a/drivers/video/Kconfig b/drivers/video/Kconfig
index 932ffdb..d6d65ef 100644
--- a/drivers/video/Kconfig
+++ b/drivers/video/Kconfig
@@ -1122,12 +1122,14 @@
 	select FB_CFB_FILLRECT
 	select FB_CFB_COPYAREA
 	select FB_CFB_IMAGEBLIT
-	select FB_BOOT_VESA_SUPPORT
+	select FB_BOOT_VESA_SUPPORT if FB_INTEL = y
 	help
 	  This driver supports the on-board graphics built in to the Intel
           830M/845G/852GM/855GM/865G/915G/915GM/945G/945GM/965G/965GM chipsets.
           Say Y if you have and plan to use such a board.
 
+	  To make FB_INTELFB=Y work you need to say AGP_INTEL=y too.
+
 	  To compile this driver as a module, choose M here: the
 	  module will be called intelfb.
 
@@ -1460,7 +1462,7 @@
 	select FB_CFB_FILLRECT
 	select FB_CFB_COPYAREA
 	select FB_CFB_IMAGEBLIT
-	select FB_BOOT_VESA_SUPPORT
+	select FB_BOOT_VESA_SUPPORT if FB_SIS = y
 	help
 	  This is the frame buffer device driver for the SiS 300, 315, 330
 	  and 340 series as well as XGI V3XT, V5, V8, Z7 graphics chipsets.
diff --git a/drivers/video/xilinxfb.c b/drivers/video/xilinxfb.c
index 7a868bd..ed7c8d0 100644
--- a/drivers/video/xilinxfb.c
+++ b/drivers/video/xilinxfb.c
@@ -124,7 +124,6 @@
 						registers */
 
 	dcr_host_t      dcr_host;
-	unsigned int    dcr_start;
 	unsigned int    dcr_len;
 
 	void		*fb_virt;	/* virt. address of the frame buffer */
@@ -325,8 +324,8 @@
 					drvdata->regs);
 	}
 	/* Put a banner in the log (for DEBUG) */
-	dev_dbg(dev, "fb: phys=%p, virt=%p, size=%x\n",
-		(void *)drvdata->fb_phys, drvdata->fb_virt, fbsize);
+	dev_dbg(dev, "fb: phys=%llx, virt=%p, size=%x\n",
+		(unsigned long long)drvdata->fb_phys, drvdata->fb_virt, fbsize);
 
 	return 0;	/* success */
 
@@ -404,9 +403,7 @@
 	u32 tft_access;
 	struct xilinxfb_platform_data pdata;
 	struct resource res;
-	int size, rc;
-	int start = 0, len = 0;
-	dcr_host_t dcr_host;
+	int size, rc, start;
 	struct xilinxfb_drvdata *drvdata;
 
 	/* Copy with the default pdata (not a ptr reference!) */
@@ -414,35 +411,39 @@
 
 	dev_dbg(&op->dev, "xilinxfb_of_probe(%p, %p)\n", op, match);
 
+	/* Allocate the driver data region */
+	drvdata = kzalloc(sizeof(*drvdata), GFP_KERNEL);
+	if (!drvdata) {
+		dev_err(&op->dev, "Couldn't allocate device private record\n");
+		return -ENOMEM;
+	}
+
 	/*
 	 * To check whether the core is connected directly to DCR or PLB
 	 * interface and initialize the tft_access accordingly.
 	 */
 	p = (u32 *)of_get_property(op->node, "xlnx,dcr-splb-slave-if", NULL);
-
-	if (p)
-		tft_access = *p;
-	else
-		tft_access = 0;		/* For backward compatibility */
+	tft_access = p ? *p : 0;
 
 	/*
 	 * Fill the resource structure if its direct PLB interface
 	 * otherwise fill the dcr_host structure.
 	 */
 	if (tft_access) {
+		drvdata->flags |= PLB_ACCESS_FLAG;
 		rc = of_address_to_resource(op->node, 0, &res);
 		if (rc) {
 			dev_err(&op->dev, "invalid address\n");
-			return -ENODEV;
+			goto err;
 		}
-
 	} else {
+		res.start = 0;
 		start = dcr_resource_start(op->node, 0);
-		len = dcr_resource_len(op->node, 0);
-		dcr_host = dcr_map(op->node, start, len);
-		if (!DCR_MAP_OK(dcr_host)) {
-			dev_err(&op->dev, "invalid address\n");
-			return -ENODEV;
+		drvdata->dcr_len = dcr_resource_len(op->node, 0);
+		drvdata->dcr_host = dcr_map(op->node, start, drvdata->dcr_len);
+		if (!DCR_MAP_OK(drvdata->dcr_host)) {
+			dev_err(&op->dev, "invalid DCR address\n");
+			goto err;
 		}
 	}
 
@@ -467,26 +468,12 @@
 	if (of_find_property(op->node, "rotate-display", NULL))
 		pdata.rotate_screen = 1;
 
-	/* Allocate the driver data region */
-	drvdata = kzalloc(sizeof(*drvdata), GFP_KERNEL);
-	if (!drvdata) {
-		dev_err(&op->dev, "Couldn't allocate device private record\n");
-		return -ENOMEM;
-	}
 	dev_set_drvdata(&op->dev, drvdata);
+	return xilinxfb_assign(&op->dev, drvdata, res.start, &pdata);
 
-	if (tft_access)
-		drvdata->flags |= PLB_ACCESS_FLAG;
-
-	/* Arguments are passed based on the interface */
-	if (drvdata->flags & PLB_ACCESS_FLAG) {
-		return xilinxfb_assign(&op->dev, drvdata, res.start, &pdata);
-	} else {
-		drvdata->dcr_start = start;
-		drvdata->dcr_len = len;
-		drvdata->dcr_host = dcr_host;
-		return xilinxfb_assign(&op->dev, drvdata, 0, &pdata);
-	}
+ err:
+	kfree(drvdata);
+	return -ENODEV;
 }
 
 static int __devexit xilinxfb_of_remove(struct of_device *op)
diff --git a/drivers/w1/masters/w1-gpio.c b/drivers/w1/masters/w1-gpio.c
index a411702..6f8866d 100644
--- a/drivers/w1/masters/w1-gpio.c
+++ b/drivers/w1/masters/w1-gpio.c
@@ -74,6 +74,9 @@
 	if (err)
 		goto free_gpio;
 
+	if (pdata->enable_external_pullup)
+		pdata->enable_external_pullup(1);
+
 	platform_set_drvdata(pdev, master);
 
 	return 0;
@@ -91,6 +94,9 @@
 	struct w1_bus_master *master = platform_get_drvdata(pdev);
 	struct w1_gpio_platform_data *pdata = pdev->dev.platform_data;
 
+	if (pdata->enable_external_pullup)
+		pdata->enable_external_pullup(0);
+
 	w1_remove_master_device(master);
 	gpio_free(pdata->pin);
 	kfree(master);
@@ -98,12 +104,41 @@
 	return 0;
 }
 
+#ifdef CONFIG_PM
+
+static int w1_gpio_suspend(struct platform_device *pdev, pm_message_t state)
+{
+	struct w1_gpio_platform_data *pdata = pdev->dev.platform_data;
+
+	if (pdata->enable_external_pullup)
+		pdata->enable_external_pullup(0);
+
+	return 0;
+}
+
+static int w1_gpio_resume(struct platform_device *pdev)
+{
+	struct w1_gpio_platform_data *pdata = pdev->dev.platform_data;
+
+	if (pdata->enable_external_pullup)
+		pdata->enable_external_pullup(1);
+
+	return 0;
+}
+
+#else
+#define w1_gpio_suspend	NULL
+#define w1_gpio_resume	NULL
+#endif
+
 static struct platform_driver w1_gpio_driver = {
 	.driver = {
 		.name	= "w1-gpio",
 		.owner	= THIS_MODULE,
 	},
 	.remove	= __exit_p(w1_gpio_remove),
+	.suspend = w1_gpio_suspend,
+	.resume = w1_gpio_resume,
 };
 
 static int __init w1_gpio_init(void)
diff --git a/drivers/watchdog/alim7101_wdt.c b/drivers/watchdog/alim7101_wdt.c
index 90f98df..f90afdb 100644
--- a/drivers/watchdog/alim7101_wdt.c
+++ b/drivers/watchdog/alim7101_wdt.c
@@ -322,7 +322,8 @@
 		 * watchdog on reboot with no heartbeat
 		 */
 		wdt_change(WDT_ENABLE);
-		printk(KERN_INFO PFX "Watchdog timer is now enabled with no heartbeat - should reboot in ~1 second.\n");
+		printk(KERN_INFO PFX "Watchdog timer is now enabled "
+			"with no heartbeat - should reboot in ~1 second.\n");
 	}
 	return NOTIFY_DONE;
 }
@@ -374,12 +375,17 @@
 	pci_dev_put(ali1543_south);
 	if ((tmp & 0x1e) == 0x00) {
 		if (!use_gpio) {
-			printk(KERN_INFO PFX "Detected old alim7101 revision 'a1d'.  If this is a cobalt board, set the 'use_gpio' module parameter.\n");
+			printk(KERN_INFO PFX
+				"Detected old alim7101 revision 'a1d'.  "
+				"If this is a cobalt board, set the 'use_gpio' "
+				"module parameter.\n");
 			goto err_out;
 		}
 		nowayout = 1;
 	} else if ((tmp & 0x1e) != 0x12 && (tmp & 0x1e) != 0x00) {
-		printk(KERN_INFO PFX "ALi 1543 South-Bridge does not have the correct revision number (???1001?) - WDT not set\n");
+		printk(KERN_INFO PFX
+			"ALi 1543 South-Bridge does not have the correct "
+			"revision number (???1001?) - WDT not set\n");
 		goto err_out;
 	}
 
@@ -409,7 +415,8 @@
 	if (nowayout)
 		__module_get(THIS_MODULE);
 
-	printk(KERN_INFO PFX "WDT driver for ALi M7101 initialised. timeout=%d sec (nowayout=%d)\n",
+	printk(KERN_INFO PFX "WDT driver for ALi M7101 initialised. "
+					"timeout=%d sec (nowayout=%d)\n",
 		timeout, nowayout);
 	return 0;
 
diff --git a/drivers/watchdog/ar7_wdt.c b/drivers/watchdog/ar7_wdt.c
index 55dcbfe..3fe9742 100644
--- a/drivers/watchdog/ar7_wdt.c
+++ b/drivers/watchdog/ar7_wdt.c
@@ -246,7 +246,8 @@
 	static struct watchdog_info ident = {
 		.identity = LONGNAME,
 		.firmware_version = 1,
-		.options = (WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING),
+		.options = (WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING |
+						WDIOF_MAGICCLOSE),
 	};
 	int new_margin;
 
diff --git a/drivers/watchdog/at91rm9200_wdt.c b/drivers/watchdog/at91rm9200_wdt.c
index 29e52c2..b185daf 100644
--- a/drivers/watchdog/at91rm9200_wdt.c
+++ b/drivers/watchdog/at91rm9200_wdt.c
@@ -268,7 +268,8 @@
 	   if not reset to the default */
 	if (at91_wdt_settimeout(wdt_time)) {
 		at91_wdt_settimeout(WDT_DEFAULT_TIME);
-		pr_info("at91_wdt: wdt_time value must be 1 <= wdt_time <= 256, using %d\n", wdt_time);
+		pr_info("at91_wdt: wdt_time value must be 1 <= wdt_time <= 256"
+						", using %d\n", wdt_time);
 	}
 
 	return platform_driver_register(&at91wdt_driver);
diff --git a/drivers/watchdog/at91sam9_wdt.c b/drivers/watchdog/at91sam9_wdt.c
index 435b057..eac2602 100644
--- a/drivers/watchdog/at91sam9_wdt.c
+++ b/drivers/watchdog/at91sam9_wdt.c
@@ -156,7 +156,8 @@
 
 static const struct watchdog_info at91_wdt_info = {
 	.identity	= DRV_NAME,
-	.options	= WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING,
+	.options	= WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING |
+						WDIOF_MAGICCLOSE,
 };
 
 /*
diff --git a/drivers/watchdog/bfin_wdt.c b/drivers/watchdog/bfin_wdt.c
index 067a57c..c7b3f9d 100644
--- a/drivers/watchdog/bfin_wdt.c
+++ b/drivers/watchdog/bfin_wdt.c
@@ -27,10 +27,15 @@
 #include <linux/uaccess.h>
 #include <asm/blackfin.h>
 
-#define stamp(fmt, args...) pr_debug("%s:%i: " fmt "\n", __func__, __LINE__, ## args)
+#define stamp(fmt, args...) \
+	pr_debug("%s:%i: " fmt "\n", __func__, __LINE__, ## args)
 #define stampit() stamp("here i am")
-#define pr_devinit(fmt, args...) ({ static const __devinitconst char __fmt[] = fmt; printk(__fmt, ## args); })
-#define pr_init(fmt, args...) ({ static const __initconst char __fmt[] = fmt; printk(__fmt, ## args); })
+#define pr_devinit(fmt, args...) \
+	({ static const __devinitconst char __fmt[] = fmt; \
+	printk(__fmt, ## args); })
+#define pr_init(fmt, args...) \
+	({ static const __initconst char __fmt[] = fmt; \
+	printk(__fmt, ## args); })
 
 #define WATCHDOG_NAME "bfin-wdt"
 #define PFX WATCHDOG_NAME ": "
@@ -476,7 +481,8 @@
 		return ret;
 	}
 
-	bfin_wdt_device = platform_device_register_simple(WATCHDOG_NAME, -1, NULL, 0);
+	bfin_wdt_device = platform_device_register_simple(WATCHDOG_NAME,
+								-1, NULL, 0);
 	if (IS_ERR(bfin_wdt_device)) {
 		pr_init(KERN_ERR PFX "unable to register device\n");
 		platform_driver_unregister(&bfin_wdt_driver);
diff --git a/drivers/watchdog/cpwd.c b/drivers/watchdog/cpwd.c
index 41070e4..081f295 100644
--- a/drivers/watchdog/cpwd.c
+++ b/drivers/watchdog/cpwd.c
@@ -154,9 +154,9 @@
 
 static struct timer_list cpwd_timer;
 
-static int wd0_timeout = 0;
-static int wd1_timeout = 0;
-static int wd2_timeout = 0;
+static int wd0_timeout;
+static int wd1_timeout;
+static int wd2_timeout;
 
 module_param(wd0_timeout, int, 0);
 MODULE_PARM_DESC(wd0_timeout, "Default watchdog0 timeout in 1/10secs");
diff --git a/drivers/watchdog/davinci_wdt.c b/drivers/watchdog/davinci_wdt.c
index c51d0b0..83e22e7 100644
--- a/drivers/watchdog/davinci_wdt.c
+++ b/drivers/watchdog/davinci_wdt.c
@@ -193,7 +193,7 @@
 	.fops = &davinci_wdt_fops,
 };
 
-static int davinci_wdt_probe(struct platform_device *pdev)
+static int __devinit davinci_wdt_probe(struct platform_device *pdev)
 {
 	int ret = 0, size;
 	struct resource *res;
@@ -237,7 +237,7 @@
 	return ret;
 }
 
-static int davinci_wdt_remove(struct platform_device *pdev)
+static int __devexit davinci_wdt_remove(struct platform_device *pdev)
 {
 	misc_deregister(&davinci_wdt_miscdev);
 	if (wdt_mem) {
@@ -254,7 +254,7 @@
 		.owner	= THIS_MODULE,
 	},
 	.probe = davinci_wdt_probe,
-	.remove = davinci_wdt_remove,
+	.remove = __devexit_p(davinci_wdt_remove),
 };
 
 static int __init davinci_wdt_init(void)
diff --git a/drivers/watchdog/hpwdt.c b/drivers/watchdog/hpwdt.c
index 3137361..c0b9169 100644
--- a/drivers/watchdog/hpwdt.c
+++ b/drivers/watchdog/hpwdt.c
@@ -19,6 +19,7 @@
 #include <linux/interrupt.h>
 #include <linux/io.h>
 #include <linux/irq.h>
+#include <linux/nmi.h>
 #include <linux/kernel.h>
 #include <linux/miscdevice.h>
 #include <linux/mm.h>
@@ -47,7 +48,7 @@
 #define PCI_BIOS32_PARAGRAPH_LEN	16
 #define PCI_ROM_BASE1			0x000F0000
 #define ROM_SIZE			0x10000
-#define HPWDT_VERSION			"1.01"
+#define HPWDT_VERSION			"1.1.1"
 
 struct bios32_service_dir {
 	u32 signature;
@@ -119,6 +120,7 @@
 static char expect_release;
 static unsigned long hpwdt_is_open;
 static unsigned int allow_kdump;
+static int hpwdt_nmi_sourcing;
 
 static void __iomem *pci_mem_addr;		/* the PCI-memory address */
 static unsigned long __iomem *hpwdt_timer_reg;
@@ -468,21 +470,22 @@
 	if (ulReason != DIE_NMI && ulReason != DIE_NMI_IPI)
 		return NOTIFY_OK;
 
-	spin_lock_irqsave(&rom_lock, rom_pl);
-	if (!die_nmi_called)
-		asminline_call(&cmn_regs, cru_rom_addr);
-	die_nmi_called = 1;
-	spin_unlock_irqrestore(&rom_lock, rom_pl);
-	if (cmn_regs.u1.ral == 0) {
-		printk(KERN_WARNING "hpwdt: An NMI occurred, "
-			"but unable to determine source.\n");
-	} else {
-		if (allow_kdump)
-			hpwdt_stop();
-		panic("An NMI occurred, please see the Integrated "
-			"Management Log for details.\n");
+	if (hpwdt_nmi_sourcing) {
+		spin_lock_irqsave(&rom_lock, rom_pl);
+		if (!die_nmi_called)
+			asminline_call(&cmn_regs, cru_rom_addr);
+		die_nmi_called = 1;
+		spin_unlock_irqrestore(&rom_lock, rom_pl);
+		if (cmn_regs.u1.ral == 0) {
+			printk(KERN_WARNING "hpwdt: An NMI occurred, "
+				"but unable to determine source.\n");
+		} else {
+			if (allow_kdump)
+				hpwdt_stop();
+			panic("An NMI occurred, please see the Integrated "
+				"Management Log for details.\n");
+		}
 	}
-
 	return NOTIFY_OK;
 }
 
@@ -627,12 +630,38 @@
  *	Init & Exit
  */
 
+#ifdef ARCH_HAS_NMI_WATCHDOG
+static void __devinit hpwdt_check_nmi_sourcing(struct pci_dev *dev)
+{
+	/*
+	 * If nmi_watchdog is turned off then we can turn on
+	 * our nmi sourcing capability.
+	 */
+	if (!nmi_watchdog_active())
+		hpwdt_nmi_sourcing = 1;
+	else
+		dev_warn(&dev->dev, "NMI sourcing is disabled. To enable this "
+			"functionality you must reboot with nmi_watchdog=0.\n");
+}
+#else
+static void __devinit hpwdt_check_nmi_sourcing(struct pci_dev *dev)
+{
+	dev_warn(&dev->dev, "NMI sourcing is disabled. "
+		"Your kernel does not support a NMI Watchdog.\n");
+}
+#endif
+
 static int __devinit hpwdt_init_one(struct pci_dev *dev,
 					const struct pci_device_id *ent)
 {
 	int retval;
 
 	/*
+	 * Check if we can do NMI sourcing or not
+	 */
+	hpwdt_check_nmi_sourcing(dev);
+
+	/*
 	 * First let's find out if we are on an iLO2 server. We will
 	 * not run on a legacy ASM box.
 	 * So we only support the G5 ProLiant servers and higher.
diff --git a/drivers/watchdog/iTCO_vendor_support.c b/drivers/watchdog/iTCO_vendor_support.c
index d3c0f6d..5133bca 100644
--- a/drivers/watchdog/iTCO_vendor_support.c
+++ b/drivers/watchdog/iTCO_vendor_support.c
@@ -19,7 +19,7 @@
 
 /* Module and version information */
 #define DRV_NAME	"iTCO_vendor_support"
-#define DRV_VERSION	"1.03"
+#define DRV_VERSION	"1.04"
 #define PFX		DRV_NAME ": "
 
 /* Includes */
@@ -35,20 +35,23 @@
 #include "iTCO_vendor.h"
 
 /* iTCO defines */
-#define	SMI_EN		acpibase + 0x30	/* SMI Control and Enable Register */
-#define	TCOBASE		acpibase + 0x60	/* TCO base address */
-#define	TCO1_STS	TCOBASE + 0x04	/* TCO1 Status Register */
+#define	SMI_EN		(acpibase + 0x30) /* SMI Control and Enable Register */
+#define	TCOBASE		(acpibase + 0x60) /* TCO base address */
+#define	TCO1_STS	(TCOBASE + 0x04)  /* TCO1 Status Register */
 
 /* List of vendor support modes */
 /* SuperMicro Pentium 3 Era 370SSE+-OEM1/P3TSSE */
 #define SUPERMICRO_OLD_BOARD	1
 /* SuperMicro Pentium 4 / Xeon 4 / EMT64T Era Systems */
 #define SUPERMICRO_NEW_BOARD	2
+/* Broken BIOS */
+#define BROKEN_BIOS		911
 
 static int vendorsupport;
 module_param(vendorsupport, int, 0);
 MODULE_PARM_DESC(vendorsupport, "iTCO vendor specific support mode, default="
-			"0 (none), 1=SuperMicro Pent3, 2=SuperMicro Pent4+");
+			"0 (none), 1=SuperMicro Pent3, 2=SuperMicro Pent4+, "
+							"911=Broken SMI BIOS");
 
 /*
  *	Vendor Specific Support
@@ -243,25 +246,92 @@
 }
 
 /*
+ *	Vendor Support: 911
+ *	Board: Some Intel ICHx based motherboards
+ *	iTCO chipset: ICH7+
+ *
+ *	Some Intel motherboards have a broken BIOS implementation: i.e.
+ *	the SMI handler clear's the TIMEOUT bit in the TC01_STS register
+ *	and does not reload the time. Thus the TCO watchdog does not reboot
+ *	the system.
+ *
+ *	These are the conclusions of Andriy Gapon <avg@icyb.net.ua> after
+ *	debugging: the SMI handler is quite simple - it tests value in
+ *	TCO1_CNT against 0x800, i.e. checks TCO_TMR_HLT. If the bit is set
+ *	the handler goes into an infinite loop, apparently to allow the
+ *	second timeout and reboot. Otherwise it simply clears TIMEOUT bit
+ *	in TCO1_STS and that's it.
+ *	So the logic seems to be reversed, because it is hard to see how
+ *	TIMEOUT can get set to 1 and SMI generated when TCO_TMR_HLT is set
+ *	(other than a transitional effect).
+ *
+ *	The only fix found to get the motherboard(s) to reboot is to put
+ *	the glb_smi_en bit to 0. This is a dirty hack that bypasses the
+ *	broken code by disabling Global SMI.
+ *
+ *	WARNING: globally disabling SMI could possibly lead to dramatic
+ *	problems, especially on laptops! I.e. various ACPI things where
+ *	SMI is used for communication between OS and firmware.
+ *
+ *	Don't use this fix if you don't need to!!!
+ */
+
+static void broken_bios_start(unsigned long acpibase)
+{
+	unsigned long val32;
+
+	val32 = inl(SMI_EN);
+	/* Bit 13: TCO_EN     -> 0 = Disables TCO logic generating an SMI#
+	   Bit  0: GBL_SMI_EN -> 0 = No SMI# will be generated by ICH. */
+	val32 &= 0xffffdffe;
+	outl(val32, SMI_EN);
+}
+
+static void broken_bios_stop(unsigned long acpibase)
+{
+	unsigned long val32;
+
+	val32 = inl(SMI_EN);
+	/* Bit 13: TCO_EN     -> 1 = Enables TCO logic generating an SMI#
+	   Bit  0: GBL_SMI_EN -> 1 = Turn global SMI on again. */
+	val32 |= 0x00002001;
+	outl(val32, SMI_EN);
+}
+
+/*
  *	Generic Support Functions
  */
 
 void iTCO_vendor_pre_start(unsigned long acpibase,
 			   unsigned int heartbeat)
 {
-	if (vendorsupport == SUPERMICRO_OLD_BOARD)
+	switch (vendorsupport) {
+	case SUPERMICRO_OLD_BOARD:
 		supermicro_old_pre_start(acpibase);
-	else if (vendorsupport == SUPERMICRO_NEW_BOARD)
+		break;
+	case SUPERMICRO_NEW_BOARD:
 		supermicro_new_pre_start(heartbeat);
+		break;
+	case BROKEN_BIOS:
+		broken_bios_start(acpibase);
+		break;
+	}
 }
 EXPORT_SYMBOL(iTCO_vendor_pre_start);
 
 void iTCO_vendor_pre_stop(unsigned long acpibase)
 {
-	if (vendorsupport == SUPERMICRO_OLD_BOARD)
+	switch (vendorsupport) {
+	case SUPERMICRO_OLD_BOARD:
 		supermicro_old_pre_stop(acpibase);
-	else if (vendorsupport == SUPERMICRO_NEW_BOARD)
+		break;
+	case SUPERMICRO_NEW_BOARD:
 		supermicro_new_pre_stop();
+		break;
+	case BROKEN_BIOS:
+		broken_bios_stop(acpibase);
+		break;
+	}
 }
 EXPORT_SYMBOL(iTCO_vendor_pre_stop);
 
diff --git a/drivers/watchdog/iTCO_wdt.c b/drivers/watchdog/iTCO_wdt.c
index 648250b..6a51edd 100644
--- a/drivers/watchdog/iTCO_wdt.c
+++ b/drivers/watchdog/iTCO_wdt.c
@@ -236,19 +236,19 @@
 
 /* Address definitions for the TCO */
 /* TCO base address */
-#define TCOBASE		iTCO_wdt_private.ACPIBASE + 0x60
+#define TCOBASE		(iTCO_wdt_private.ACPIBASE + 0x60)
 /* SMI Control and Enable Register */
-#define SMI_EN		iTCO_wdt_private.ACPIBASE + 0x30
+#define SMI_EN		(iTCO_wdt_private.ACPIBASE + 0x30)
 
-#define TCO_RLD		TCOBASE + 0x00	/* TCO Timer Reload and Curr. Value */
-#define TCOv1_TMR	TCOBASE + 0x01	/* TCOv1 Timer Initial Value	*/
-#define TCO_DAT_IN	TCOBASE + 0x02	/* TCO Data In Register		*/
-#define TCO_DAT_OUT	TCOBASE + 0x03	/* TCO Data Out Register	*/
-#define TCO1_STS	TCOBASE + 0x04	/* TCO1 Status Register		*/
-#define TCO2_STS	TCOBASE + 0x06	/* TCO2 Status Register		*/
-#define TCO1_CNT	TCOBASE + 0x08	/* TCO1 Control Register	*/
-#define TCO2_CNT	TCOBASE + 0x0a	/* TCO2 Control Register	*/
-#define TCOv2_TMR	TCOBASE + 0x12	/* TCOv2 Timer Initial Value	*/
+#define TCO_RLD		(TCOBASE + 0x00) /* TCO Timer Reload and Curr. Value */
+#define TCOv1_TMR	(TCOBASE + 0x01) /* TCOv1 Timer Initial Value	*/
+#define TCO_DAT_IN	(TCOBASE + 0x02) /* TCO Data In Register	*/
+#define TCO_DAT_OUT	(TCOBASE + 0x03) /* TCO Data Out Register	*/
+#define TCO1_STS	(TCOBASE + 0x04) /* TCO1 Status Register	*/
+#define TCO2_STS	(TCOBASE + 0x06) /* TCO2 Status Register	*/
+#define TCO1_CNT	(TCOBASE + 0x08) /* TCO1 Control Register	*/
+#define TCO2_CNT	(TCOBASE + 0x0a) /* TCO2 Control Register	*/
+#define TCOv2_TMR	(TCOBASE + 0x12) /* TCOv2 Timer Initial Value	*/
 
 /* internal variables */
 static unsigned long is_active;
@@ -666,6 +666,11 @@
 	   GCS = RCBA + ICH6_GCS(0x3410). */
 	if (iTCO_wdt_private.iTCO_version == 2) {
 		pci_read_config_dword(pdev, 0xf0, &base_address);
+		if ((base_address & 1) == 0) {
+			printk(KERN_ERR PFX "RCBA is disabled by harddware\n");
+			ret = -ENODEV;
+			goto out;
+		}
 		RCBA = base_address & 0xffffc000;
 		iTCO_wdt_private.gcs = ioremap((RCBA + 0x3410), 4);
 	}
@@ -675,7 +680,7 @@
 		printk(KERN_ERR PFX "failed to reset NO_REBOOT flag, "
 					"reboot disabled by hardware\n");
 		ret = -ENODEV;	/* Cannot reset NO_REBOOT bit */
-		goto out;
+		goto out_unmap;
 	}
 
 	/* Set the NO_REBOOT bit to prevent later reboots, just for sure */
@@ -686,7 +691,7 @@
 		printk(KERN_ERR PFX
 			"I/O address 0x%04lx already in use\n", SMI_EN);
 		ret = -EIO;
-		goto out;
+		goto out_unmap;
 	}
 	/* Bit 13: TCO_EN -> 0 = Disables TCO logic generating an SMI# */
 	val32 = inl(SMI_EN);
@@ -742,9 +747,10 @@
 	release_region(TCOBASE, 0x20);
 unreg_smi_en:
 	release_region(SMI_EN, 4);
-out:
+out_unmap:
 	if (iTCO_wdt_private.iTCO_version == 2)
 		iounmap(iTCO_wdt_private.gcs);
+out:
 	pci_dev_put(iTCO_wdt_private.pdev);
 	iTCO_wdt_private.ACPIBASE = 0;
 	return ret;
diff --git a/drivers/watchdog/indydog.c b/drivers/watchdog/indydog.c
index 0f761db..bea8a12 100644
--- a/drivers/watchdog/indydog.c
+++ b/drivers/watchdog/indydog.c
@@ -83,7 +83,6 @@
 	indydog_start();
 	indydog_ping();
 
-	indydog_alive = 1;
 	printk(KERN_INFO "Started watchdog timer.\n");
 
 	return nonseekable_open(inode, file);
@@ -113,8 +112,7 @@
 {
 	int options, retval = -EINVAL;
 	static struct watchdog_info ident = {
-		.options		= WDIOF_KEEPALIVEPING |
-					  WDIOF_MAGICCLOSE,
+		.options		= WDIOF_KEEPALIVEPING,
 		.firmware_version	= 0,
 		.identity		= "Hardware Watchdog for SGI IP22",
 	};
diff --git a/drivers/watchdog/it8712f_wdt.c b/drivers/watchdog/it8712f_wdt.c
index 2270ee0..daed48d 100644
--- a/drivers/watchdog/it8712f_wdt.c
+++ b/drivers/watchdog/it8712f_wdt.c
@@ -239,7 +239,8 @@
 	static struct watchdog_info ident = {
 		.identity = "IT8712F Watchdog",
 		.firmware_version = 1,
-		.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING,
+		.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING |
+						WDIOF_MAGICCLOSE,
 	};
 	int value;
 
diff --git a/drivers/watchdog/ks8695_wdt.c b/drivers/watchdog/ks8695_wdt.c
index ae38321..00b03eb 100644
--- a/drivers/watchdog/ks8695_wdt.c
+++ b/drivers/watchdog/ks8695_wdt.c
@@ -293,8 +293,8 @@
 	   if not reset to the default */
 	if (ks8695_wdt_settimeout(wdt_time)) {
 		ks8695_wdt_settimeout(WDT_DEFAULT_TIME);
-		pr_info("ks8695_wdt: wdt_time value must be 1 <= wdt_time <= %i, using %d\n",
-							wdt_time, WDT_MAX_TIME);
+		pr_info("ks8695_wdt: wdt_time value must be 1 <= wdt_time <= %i"
+					", using %d\n", wdt_time, WDT_MAX_TIME);
 	}
 	return platform_driver_register(&ks8695wdt_driver);
 }
diff --git a/drivers/watchdog/machzwd.c b/drivers/watchdog/machzwd.c
index 2dfc275..b6b3f59 100644
--- a/drivers/watchdog/machzwd.c
+++ b/drivers/watchdog/machzwd.c
@@ -118,7 +118,8 @@
  */
 static int action;
 module_param(action, int, 0);
-MODULE_PARM_DESC(action, "after watchdog resets, generate: 0 = RESET(*)  1 = SMI  2 = NMI  3 = SCI");
+MODULE_PARM_DESC(action, "after watchdog resets, generate: "
+				"0 = RESET(*)  1 = SMI  2 = NMI  3 = SCI");
 
 static void zf_ping(unsigned long data);
 
@@ -142,7 +143,8 @@
 #ifndef ZF_DEBUG
 #	define dprintk(format, args...)
 #else
-#	define dprintk(format, args...) printk(KERN_DEBUG PFX ":%s:%d: " format, __func__, __LINE__ , ## args)
+#	define dprintk(format, args...) printk(KERN_DEBUG PFX
+				":%s:%d: " format, __func__, __LINE__ , ## args)
 #endif
 
 
@@ -340,7 +342,8 @@
 		zf_timer_off();
 	else {
 		del_timer(&zf_timer);
-		printk(KERN_ERR PFX ": device file closed unexpectedly. Will not stop the WDT!\n");
+		printk(KERN_ERR PFX ": device file closed unexpectedly. "
+						"Will not stop the WDT!\n");
 	}
 	clear_bit(0, &zf_is_open);
 	zf_expect_close = 0;
diff --git a/drivers/watchdog/mpc5200_wdt.c b/drivers/watchdog/mpc5200_wdt.c
index 465fe36..fa9c47c 100644
--- a/drivers/watchdog/mpc5200_wdt.c
+++ b/drivers/watchdog/mpc5200_wdt.c
@@ -188,7 +188,7 @@
 	if (!wdt)
 		return -ENOMEM;
 
-	wdt->ipb_freq = mpc52xx_find_ipb_freq(op->node);
+	wdt->ipb_freq = mpc5xxx_get_bus_frequency(op->node);
 
 	err = of_address_to_resource(op->node, 0, &wdt->mem);
 	if (err)
diff --git a/drivers/watchdog/mpcore_wdt.c b/drivers/watchdog/mpcore_wdt.c
index 1512ab8..83fa34b 100644
--- a/drivers/watchdog/mpcore_wdt.c
+++ b/drivers/watchdog/mpcore_wdt.c
@@ -61,7 +61,9 @@
 #define ONLY_TESTING	0
 static int mpcore_noboot = ONLY_TESTING;
 module_param(mpcore_noboot, int, 0);
-MODULE_PARM_DESC(mpcore_noboot, "MPcore watchdog action, set to 1 to ignore reboots, 0 to reboot (default=" __MODULE_STRING(ONLY_TESTING) ")");
+MODULE_PARM_DESC(mpcore_noboot, "MPcore watchdog action, "
+	"set to 1 to ignore reboots, 0 to reboot (default="
+					__MODULE_STRING(ONLY_TESTING) ")");
 
 /*
  *	This is the interrupt handler.  Note that we only use this
@@ -416,7 +418,8 @@
 	},
 };
 
-static char banner[] __initdata = KERN_INFO "MPcore Watchdog Timer: 0.1. mpcore_noboot=%d mpcore_margin=%d sec (nowayout= %d)\n";
+static char banner[] __initdata = KERN_INFO "MPcore Watchdog Timer: 0.1. "
+		"mpcore_noboot=%d mpcore_margin=%d sec (nowayout= %d)\n";
 
 static int __init mpcore_wdt_init(void)
 {
diff --git a/drivers/watchdog/mtx-1_wdt.c b/drivers/watchdog/mtx-1_wdt.c
index 539b6f6..08e8a6a 100644
--- a/drivers/watchdog/mtx-1_wdt.c
+++ b/drivers/watchdog/mtx-1_wdt.c
@@ -206,7 +206,7 @@
 };
 
 
-static int mtx1_wdt_probe(struct platform_device *pdev)
+static int __devinit mtx1_wdt_probe(struct platform_device *pdev)
 {
 	int ret;
 
@@ -229,7 +229,7 @@
 	return 0;
 }
 
-static int mtx1_wdt_remove(struct platform_device *pdev)
+static int __devexit mtx1_wdt_remove(struct platform_device *pdev)
 {
 	/* FIXME: do we need to lock this test ? */
 	if (mtx1_wdt_device.queue) {
@@ -242,7 +242,7 @@
 
 static struct platform_driver mtx1_wdt = {
 	.probe = mtx1_wdt_probe,
-	.remove = mtx1_wdt_remove,
+	.remove = __devexit_p(mtx1_wdt_remove),
 	.driver.name = "mtx1-wdt",
 	.driver.owner = THIS_MODULE,
 };
diff --git a/drivers/watchdog/pnx4008_wdt.c b/drivers/watchdog/pnx4008_wdt.c
index 6413519..f24d041 100644
--- a/drivers/watchdog/pnx4008_wdt.c
+++ b/drivers/watchdog/pnx4008_wdt.c
@@ -246,7 +246,7 @@
 	.fops = &pnx4008_wdt_fops,
 };
 
-static int pnx4008_wdt_probe(struct platform_device *pdev)
+static int __devinit pnx4008_wdt_probe(struct platform_device *pdev)
 {
 	int ret = 0, size;
 	struct resource *res;
@@ -299,7 +299,7 @@
 	return ret;
 }
 
-static int pnx4008_wdt_remove(struct platform_device *pdev)
+static int __devexit pnx4008_wdt_remove(struct platform_device *pdev)
 {
 	misc_deregister(&pnx4008_wdt_miscdev);
 	if (wdt_clk) {
@@ -321,7 +321,7 @@
 		.owner	= THIS_MODULE,
 	},
 	.probe = pnx4008_wdt_probe,
-	.remove = pnx4008_wdt_remove,
+	.remove = __devexit_p(pnx4008_wdt_remove),
 };
 
 static int __init pnx4008_wdt_init(void)
diff --git a/drivers/watchdog/rdc321x_wdt.c b/drivers/watchdog/rdc321x_wdt.c
index 36e221b..4976bfd 100644
--- a/drivers/watchdog/rdc321x_wdt.c
+++ b/drivers/watchdog/rdc321x_wdt.c
@@ -245,7 +245,7 @@
 	return 0;
 }
 
-static int rdc321x_wdt_remove(struct platform_device *pdev)
+static int __devexit rdc321x_wdt_remove(struct platform_device *pdev)
 {
 	if (rdc321x_wdt_device.queue) {
 		rdc321x_wdt_device.queue = 0;
@@ -259,7 +259,7 @@
 
 static struct platform_driver rdc321x_wdt_driver = {
 	.probe = rdc321x_wdt_probe,
-	.remove = rdc321x_wdt_remove,
+	.remove = __devexit_p(rdc321x_wdt_remove),
 	.driver = {
 		.owner = THIS_MODULE,
 		.name = "rdc321x-wdt",
diff --git a/drivers/watchdog/rm9k_wdt.c b/drivers/watchdog/rm9k_wdt.c
index cce1982..2e44426 100644
--- a/drivers/watchdog/rm9k_wdt.c
+++ b/drivers/watchdog/rm9k_wdt.c
@@ -345,8 +345,8 @@
 	return platform_get_resource_byname(pdv, type, buf);
 }
 
-/* No hotplugging on the platform bus - use __init */
-static int __init wdt_gpi_probe(struct platform_device *pdv)
+/* No hotplugging on the platform bus - use __devinit */
+static int __devinit wdt_gpi_probe(struct platform_device *pdv)
 {
 	int res;
 	const struct resource
@@ -373,7 +373,7 @@
 	return res;
 }
 
-static int __exit wdt_gpi_remove(struct platform_device *dev)
+static int __devexit wdt_gpi_remove(struct platform_device *dev)
 {
 	int res;
 
diff --git a/drivers/watchdog/s3c2410_wdt.c b/drivers/watchdog/s3c2410_wdt.c
index e31925e..b57ac6b 100644
--- a/drivers/watchdog/s3c2410_wdt.c
+++ b/drivers/watchdog/s3c2410_wdt.c
@@ -68,15 +68,10 @@
 			__MODULE_STRING(CONFIG_S3C2410_WATCHDOG_ATBOOT));
 MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default="
 			__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
-MODULE_PARM_DESC(soft_noboot, "Watchdog action, set to 1 to ignore reboots, 0 to reboot (default depends on ONLY_TESTING)");
+MODULE_PARM_DESC(soft_noboot, "Watchdog action, set to 1 to ignore reboots, "
+			"0 to reboot (default depends on ONLY_TESTING)");
 MODULE_PARM_DESC(debug, "Watchdog debug, set to >1 for debug, (default 0)");
 
-
-typedef enum close_state {
-	CLOSE_STATE_NOT,
-	CLOSE_STATE_ALLOW = 0x4021
-} close_state_t;
-
 static unsigned long open_lock;
 static struct device    *wdt_dev;	/* platform device attached to */
 static struct resource	*wdt_mem;
@@ -84,7 +79,7 @@
 static struct clk	*wdt_clock;
 static void __iomem	*wdt_base;
 static unsigned int	 wdt_count;
-static close_state_t	 allow_close;
+static char		 expect_close;
 static DEFINE_SPINLOCK(wdt_lock);
 
 /* watchdog control routines */
@@ -211,7 +206,7 @@
 	if (nowayout)
 		__module_get(THIS_MODULE);
 
-	allow_close = CLOSE_STATE_NOT;
+	expect_close = 0;
 
 	/* start the timer */
 	s3c2410wdt_start();
@@ -225,13 +220,13 @@
 	 * 	Lock it in if it's a module and we set nowayout
 	 */
 
-	if (allow_close == CLOSE_STATE_ALLOW)
+	if (expect_close == 42)
 		s3c2410wdt_stop();
 	else {
 		dev_err(wdt_dev, "Unexpected close, not stopping watchdog\n");
 		s3c2410wdt_keepalive();
 	}
-	allow_close = CLOSE_STATE_NOT;
+	expect_close = 0;
 	clear_bit(0, &open_lock);
 	return 0;
 }
@@ -247,7 +242,7 @@
 			size_t i;
 
 			/* In case it was set long ago */
-			allow_close = CLOSE_STATE_NOT;
+			expect_close = 0;
 
 			for (i = 0; i != len; i++) {
 				char c;
@@ -255,7 +250,7 @@
 				if (get_user(c, data + i))
 					return -EFAULT;
 				if (c == 'V')
-					allow_close = CLOSE_STATE_ALLOW;
+					expect_close = 42;
 			}
 		}
 		s3c2410wdt_keepalive();
@@ -263,7 +258,7 @@
 	return len;
 }
 
-#define OPTIONS WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE
+#define OPTIONS (WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE)
 
 static const struct watchdog_info s3c2410_wdt_ident = {
 	.options          =     OPTIONS,
@@ -331,7 +326,7 @@
 }
 /* device interface */
 
-static int s3c2410wdt_probe(struct platform_device *pdev)
+static int __devinit s3c2410wdt_probe(struct platform_device *pdev)
 {
 	struct resource *res;
 	struct device *dev;
@@ -404,7 +399,8 @@
 			   "tmr_margin value out of range, default %d used\n",
 			       CONFIG_S3C2410_WATCHDOG_DEFAULT_TIME);
 		else
-			dev_info(dev, "default timer value is out of range, cannot start\n");
+			dev_info(dev, "default timer value is out of range, "
+							"cannot start\n");
 	}
 
 	ret = misc_register(&s3c2410wdt_miscdev);
@@ -453,7 +449,7 @@
 	return ret;
 }
 
-static int s3c2410wdt_remove(struct platform_device *dev)
+static int __devexit s3c2410wdt_remove(struct platform_device *dev)
 {
 	release_resource(wdt_mem);
 	kfree(wdt_mem);
@@ -515,7 +511,7 @@
 
 static struct platform_driver s3c2410wdt_driver = {
 	.probe		= s3c2410wdt_probe,
-	.remove		= s3c2410wdt_remove,
+	.remove		= __devexit_p(s3c2410wdt_remove),
 	.shutdown	= s3c2410wdt_shutdown,
 	.suspend	= s3c2410wdt_suspend,
 	.resume		= s3c2410wdt_resume,
diff --git a/drivers/watchdog/sb_wdog.c b/drivers/watchdog/sb_wdog.c
index 38f5831..9748eed 100644
--- a/drivers/watchdog/sb_wdog.c
+++ b/drivers/watchdog/sb_wdog.c
@@ -93,7 +93,7 @@
 
 static const struct watchdog_info ident = {
 	.options	= WDIOF_CARDRESET | WDIOF_SETTIMEOUT |
-						WDIOF_KEEPALIVEPING,
+					WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE,
 	.identity	= "SiByte Watchdog",
 };
 
@@ -269,9 +269,10 @@
 	 * if it's the second watchdog timer, it's for those users
 	 */
 	if (wd_cfg_reg == user_dog)
-		printk(KERN_CRIT
-			"%s in danger of initiating system reset in %ld.%01ld seconds\n",
-			ident.identity, wd_init / 1000000, (wd_init / 100000) % 10);
+		printk(KERN_CRIT "%s in danger of initiating system reset "
+			"in %ld.%01ld seconds\n",
+			ident.identity,
+			wd_init / 1000000, (wd_init / 100000) % 10);
 	else
 		cfg |= 1;
 
diff --git a/drivers/watchdog/sbc60xxwdt.c b/drivers/watchdog/sbc60xxwdt.c
index d1c390c..626d0e8 100644
--- a/drivers/watchdog/sbc60xxwdt.c
+++ b/drivers/watchdog/sbc60xxwdt.c
@@ -372,8 +372,9 @@
 						wdt_miscdev.minor, rc);
 		goto err_out_reboot;
 	}
-	printk(KERN_INFO PFX "WDT driver for 60XX single board computer initialised. timeout=%d sec (nowayout=%d)\n",
-		timeout, nowayout);
+	printk(KERN_INFO PFX
+		"WDT driver for 60XX single board computer initialised. "
+		"timeout=%d sec (nowayout=%d)\n", timeout, nowayout);
 
 	return 0;
 
diff --git a/drivers/watchdog/sbc8360.c b/drivers/watchdog/sbc8360.c
index b6e6799..68e2e2d 100644
--- a/drivers/watchdog/sbc8360.c
+++ b/drivers/watchdog/sbc8360.c
@@ -280,8 +280,8 @@
 	if (expect_close == 42)
 		sbc8360_stop();
 	else
-		printk(KERN_CRIT PFX
-			"SBC8360 device closed unexpectedly.  SBC8360 will not stop!\n");
+		printk(KERN_CRIT PFX "SBC8360 device closed unexpectedly.  "
+						"SBC8360 will not stop!\n");
 
 	clear_bit(0, &sbc8360_is_open);
 	expect_close = 0;
diff --git a/drivers/watchdog/sbc_epx_c3.c b/drivers/watchdog/sbc_epx_c3.c
index e467ddc..28f1214 100644
--- a/drivers/watchdog/sbc_epx_c3.c
+++ b/drivers/watchdog/sbc_epx_c3.c
@@ -107,8 +107,7 @@
 	int options, retval = -EINVAL;
 	int __user *argp = (void __user *)arg;
 	static const struct watchdog_info ident = {
-		.options		= WDIOF_KEEPALIVEPING |
-					  WDIOF_MAGICCLOSE,
+		.options		= WDIOF_KEEPALIVEPING,
 		.firmware_version	= 0,
 		.identity		= "Winsystems EPX-C3 H/W Watchdog",
 	};
@@ -174,8 +173,8 @@
 	.notifier_call = epx_c3_notify_sys,
 };
 
-static const char banner[] __initdata =
-    KERN_INFO PFX "Hardware Watchdog Timer for Winsystems EPX-C3 SBC: 0.1\n";
+static const char banner[] __initdata = KERN_INFO PFX
+	"Hardware Watchdog Timer for Winsystems EPX-C3 SBC: 0.1\n";
 
 static int __init watchdog_init(void)
 {
@@ -219,6 +218,9 @@
 module_exit(watchdog_exit);
 
 MODULE_AUTHOR("Calin A. Culianu <calin@ajvar.org>");
-MODULE_DESCRIPTION("Hardware Watchdog Device for Winsystems EPX-C3 SBC.  Note that there is no way to probe for this device -- so only use it if you are *sure* you are runnning on this specific SBC system from Winsystems!  It writes to IO ports 0x1ee and 0x1ef!");
+MODULE_DESCRIPTION("Hardware Watchdog Device for Winsystems EPX-C3 SBC.  "
+	"Note that there is no way to probe for this device -- "
+	"so only use it if you are *sure* you are runnning on this specific "
+	"SBC system from Winsystems!  It writes to IO ports 0x1ee and 0x1ef!");
 MODULE_LICENSE("GPL");
 MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
diff --git a/drivers/watchdog/scx200_wdt.c b/drivers/watchdog/scx200_wdt.c
index 9e19a10..e67b76c 100644
--- a/drivers/watchdog/scx200_wdt.c
+++ b/drivers/watchdog/scx200_wdt.c
@@ -108,7 +108,9 @@
 static int scx200_wdt_release(struct inode *inode, struct file *file)
 {
 	if (expect_close != 42)
-		printk(KERN_WARNING NAME ": watchdog device closed unexpectedly, will not disable the watchdog timer\n");
+		printk(KERN_WARNING NAME
+			": watchdog device closed unexpectedly, "
+			"will not disable the watchdog timer\n");
 	else if (!nowayout)
 		scx200_wdt_disable();
 	expect_close = 0;
@@ -163,7 +165,8 @@
 	static const struct watchdog_info ident = {
 		.identity = "NatSemi SCx200 Watchdog",
 		.firmware_version = 1,
-		.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING,
+		.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING |
+						WDIOF_MAGICCLOSE,
 	};
 	int new_margin;
 
diff --git a/drivers/watchdog/shwdt.c b/drivers/watchdog/shwdt.c
index cdc7138..a03f84e 100644
--- a/drivers/watchdog/shwdt.c
+++ b/drivers/watchdog/shwdt.c
@@ -494,7 +494,9 @@
 MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
 
 module_param(clock_division_ratio, int, 0);
-MODULE_PARM_DESC(clock_division_ratio, "Clock division ratio. Valid ranges are from 0x5 (1.31ms) to 0x7 (5.25ms). (default=" __MODULE_STRING(clock_division_ratio) ")");
+MODULE_PARM_DESC(clock_division_ratio,
+	"Clock division ratio. Valid ranges are from 0x5 (1.31ms) "
+	"to 0x7 (5.25ms). (default=" __MODULE_STRING(clock_division_ratio) ")");
 
 module_param(heartbeat, int, 0);
 MODULE_PARM_DESC(heartbeat,
diff --git a/drivers/watchdog/softdog.c b/drivers/watchdog/softdog.c
index ebcc9ce..833f49f 100644
--- a/drivers/watchdog/softdog.c
+++ b/drivers/watchdog/softdog.c
@@ -71,7 +71,9 @@
 #endif  /* ONLY_TESTING */
 
 module_param(soft_noboot, int, 0);
-MODULE_PARM_DESC(soft_noboot, "Softdog action, set to 1 to ignore reboots, 0 to reboot (default depends on ONLY_TESTING)");
+MODULE_PARM_DESC(soft_noboot,
+	"Softdog action, set to 1 to ignore reboots, 0 to reboot "
+					"(default depends on ONLY_TESTING)");
 
 /*
  *	Our timer
@@ -264,7 +266,8 @@
 	.notifier_call	= softdog_notify_sys,
 };
 
-static char banner[] __initdata = KERN_INFO "Software Watchdog Timer: 0.07 initialized. soft_noboot=%d soft_margin=%d sec (nowayout= %d)\n";
+static char banner[] __initdata = KERN_INFO "Software Watchdog Timer: 0.07 "
+	"initialized. soft_noboot=%d soft_margin=%d sec (nowayout= %d)\n";
 
 static int __init watchdog_init(void)
 {
diff --git a/drivers/watchdog/w83697hf_wdt.c b/drivers/watchdog/w83697hf_wdt.c
index a9c7f35..af08972 100644
--- a/drivers/watchdog/w83697hf_wdt.c
+++ b/drivers/watchdog/w83697hf_wdt.c
@@ -413,7 +413,8 @@
 	w83697hf_init();
 	if (early_disable) {
 		if (wdt_running())
-			printk(KERN_WARNING PFX "Stopping previously enabled watchdog until userland kicks in\n");
+			printk(KERN_WARNING PFX "Stopping previously enabled "
+					"watchdog until userland kicks in\n");
 		wdt_disable();
 	}
 
diff --git a/drivers/watchdog/wdrtas.c b/drivers/watchdog/wdrtas.c
index a38fa49..a4fe7a3 100644
--- a/drivers/watchdog/wdrtas.c
+++ b/drivers/watchdog/wdrtas.c
@@ -49,12 +49,7 @@
 MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
 MODULE_ALIAS_MISCDEV(TEMP_MINOR);
 
-#ifdef CONFIG_WATCHDOG_NOWAYOUT
-static int wdrtas_nowayout = 1;
-#else
-static int wdrtas_nowayout = 0;
-#endif
-
+static int wdrtas_nowayout = WATCHDOG_NOWAYOUT;
 static atomic_t wdrtas_miscdev_open = ATOMIC_INIT(0);
 static char wdrtas_expect_close;
 
diff --git a/fs/9p/vfs_super.c b/fs/9p/vfs_super.c
index ab5547f..38d695d 100644
--- a/fs/9p/vfs_super.c
+++ b/fs/9p/vfs_super.c
@@ -37,7 +37,6 @@
 #include <linux/mount.h>
 #include <linux/idr.h>
 #include <linux/sched.h>
-#include <linux/smp_lock.h>
 #include <net/9p/9p.h>
 #include <net/9p/client.h>
 
@@ -231,10 +230,8 @@
 {
 	struct v9fs_session_info *v9ses;
 
-	lock_kernel();
 	v9ses = sb->s_fs_info;
 	v9fs_session_cancel(v9ses);
-	unlock_kernel();
 }
 
 static const struct super_operations v9fs_super_ops = {
diff --git a/fs/Kconfig b/fs/Kconfig
index 4044f16..d78e950 100644
--- a/fs/Kconfig
+++ b/fs/Kconfig
@@ -134,7 +134,7 @@
 config HUGETLBFS
 	bool "HugeTLB file system support"
 	depends on X86 || IA64 || PPC64 || SPARC64 || (SUPERH && MMU) || \
-		   (S390 && 64BIT) || BROKEN
+		   (S390 && 64BIT) || SYS_SUPPORTS_HUGETLBFS || BROKEN
 	help
 	  hugetlbfs is a filesystem backing for HugeTLB pages, based on
 	  ramfs. For architectures that support it, say Y here and read
diff --git a/fs/adfs/adfs.h b/fs/adfs/adfs.h
index a6665f3..9cc1877 100644
--- a/fs/adfs/adfs.h
+++ b/fs/adfs/adfs.h
@@ -1,3 +1,6 @@
+#include <linux/fs.h>
+#include <linux/adfs_fs.h>
+
 /* Internal data structures for ADFS */
 
 #define ADFS_FREE_FRAG		 0
@@ -17,6 +20,58 @@
 struct buffer_head;
 
 /*
+ * adfs file system inode data in memory
+ */
+struct adfs_inode_info {
+	loff_t		mmu_private;
+	unsigned long	parent_id;	/* object id of parent		*/
+	__u32		loadaddr;	/* RISC OS load address		*/
+	__u32		execaddr;	/* RISC OS exec address		*/
+	unsigned int	filetype;	/* RISC OS file type		*/
+	unsigned int	attr;		/* RISC OS permissions		*/
+	unsigned int	stamped:1;	/* RISC OS file has date/time	*/
+	struct inode vfs_inode;
+};
+
+/*
+ * Forward-declare this
+ */
+struct adfs_discmap;
+struct adfs_dir_ops;
+
+/*
+ * ADFS file system superblock data in memory
+ */
+struct adfs_sb_info {
+	struct adfs_discmap *s_map;	/* bh list containing map		 */
+	struct adfs_dir_ops *s_dir;	/* directory operations			 */
+
+	uid_t		s_uid;		/* owner uid				 */
+	gid_t		s_gid;		/* owner gid				 */
+	umode_t		s_owner_mask;	/* ADFS owner perm -> unix perm		 */
+	umode_t		s_other_mask;	/* ADFS other perm -> unix perm		 */
+
+	__u32		s_ids_per_zone;	/* max. no ids in one zone		 */
+	__u32		s_idlen;	/* length of ID in map			 */
+	__u32		s_map_size;	/* sector size of a map			 */
+	unsigned long	s_size;		/* total size (in blocks) of this fs	 */
+	signed int	s_map2blk;	/* shift left by this for map->sector	 */
+	unsigned int	s_log2sharesize;/* log2 share size			 */
+	__le32		s_version;	/* disc format version			 */
+	unsigned int	s_namelen;	/* maximum number of characters in name	 */
+};
+
+static inline struct adfs_sb_info *ADFS_SB(struct super_block *sb)
+{
+	return sb->s_fs_info;
+}
+
+static inline struct adfs_inode_info *ADFS_I(struct inode *inode)
+{
+	return container_of(inode, struct adfs_inode_info, vfs_inode);
+}
+
+/*
  * Directory handling
  */
 struct adfs_dir {
diff --git a/fs/adfs/dir.c b/fs/adfs/dir.c
index 4d40734..23aa52f 100644
--- a/fs/adfs/dir.c
+++ b/fs/adfs/dir.c
@@ -9,15 +9,7 @@
  *
  *  Common directory handling for ADFS
  */
-#include <linux/errno.h>
-#include <linux/fs.h>
-#include <linux/adfs_fs.h>
-#include <linux/time.h>
-#include <linux/stat.h>
-#include <linux/spinlock.h>
 #include <linux/smp_lock.h>
-#include <linux/buffer_head.h>		/* for file_fsync() */
-
 #include "adfs.h"
 
 /*
diff --git a/fs/adfs/dir_f.c b/fs/adfs/dir_f.c
index 31df6ad..bafc712 100644
--- a/fs/adfs/dir_f.c
+++ b/fs/adfs/dir_f.c
@@ -9,15 +9,7 @@
  *
  *  E and F format directory handling
  */
-#include <linux/errno.h>
-#include <linux/fs.h>
-#include <linux/adfs_fs.h>
-#include <linux/time.h>
-#include <linux/stat.h>
-#include <linux/spinlock.h>
 #include <linux/buffer_head.h>
-#include <linux/string.h>
-
 #include "adfs.h"
 #include "dir_f.h"
 
diff --git a/fs/adfs/dir_fplus.c b/fs/adfs/dir_fplus.c
index 139e0f3..1796bb35 100644
--- a/fs/adfs/dir_fplus.c
+++ b/fs/adfs/dir_fplus.c
@@ -7,15 +7,7 @@
  * it under the terms of the GNU General Public License version 2 as
  * published by the Free Software Foundation.
  */
-#include <linux/errno.h>
-#include <linux/fs.h>
-#include <linux/adfs_fs.h>
-#include <linux/time.h>
-#include <linux/stat.h>
-#include <linux/spinlock.h>
 #include <linux/buffer_head.h>
-#include <linux/string.h>
-
 #include "adfs.h"
 #include "dir_fplus.h"
 
diff --git a/fs/adfs/file.c b/fs/adfs/file.c
index 8224d54..005ea34 100644
--- a/fs/adfs/file.c
+++ b/fs/adfs/file.c
@@ -19,10 +19,6 @@
  *
  *  adfs regular file handling primitives           
  */
-#include <linux/fs.h>
-#include <linux/buffer_head.h>			/* for file_fsync() */
-#include <linux/adfs_fs.h>
-
 #include "adfs.h"
 
 const struct file_operations adfs_file_operations = {
diff --git a/fs/adfs/inode.c b/fs/adfs/inode.c
index 05b3a67..798cb07 100644
--- a/fs/adfs/inode.c
+++ b/fs/adfs/inode.c
@@ -7,17 +7,8 @@
  * it under the terms of the GNU General Public License version 2 as
  * published by the Free Software Foundation.
  */
-#include <linux/errno.h>
-#include <linux/fs.h>
-#include <linux/adfs_fs.h>
-#include <linux/time.h>
-#include <linux/stat.h>
-#include <linux/string.h>
-#include <linux/mm.h>
 #include <linux/smp_lock.h>
-#include <linux/module.h>
 #include <linux/buffer_head.h>
-
 #include "adfs.h"
 
 /*
@@ -395,4 +386,3 @@
 	unlock_kernel();
 	return ret;
 }
-MODULE_LICENSE("GPL");
diff --git a/fs/adfs/map.c b/fs/adfs/map.c
index 568081b..d1a5932 100644
--- a/fs/adfs/map.c
+++ b/fs/adfs/map.c
@@ -7,14 +7,8 @@
  * it under the terms of the GNU General Public License version 2 as
  * published by the Free Software Foundation.
  */
-#include <linux/errno.h>
-#include <linux/fs.h>
-#include <linux/adfs_fs.h>
-#include <linux/spinlock.h>
 #include <linux/buffer_head.h>
-
 #include <asm/unaligned.h>
-
 #include "adfs.h"
 
 /*
diff --git a/fs/adfs/super.c b/fs/adfs/super.c
index 0ec5aaf..aad92f0 100644
--- a/fs/adfs/super.c
+++ b/fs/adfs/super.c
@@ -8,26 +8,12 @@
  * published by the Free Software Foundation.
  */
 #include <linux/module.h>
-#include <linux/errno.h>
-#include <linux/fs.h>
-#include <linux/adfs_fs.h>
-#include <linux/slab.h>
-#include <linux/time.h>
-#include <linux/stat.h>
-#include <linux/string.h>
 #include <linux/init.h>
 #include <linux/buffer_head.h>
-#include <linux/vfs.h>
 #include <linux/parser.h>
-#include <linux/bitops.h>
 #include <linux/mount.h>
 #include <linux/seq_file.h>
-
-#include <asm/uaccess.h>
-#include <asm/system.h>
-
-#include <stdarg.h>
-
+#include <linux/statfs.h>
 #include "adfs.h"
 #include "dir_f.h"
 #include "dir_fplus.h"
@@ -534,3 +520,4 @@
 
 module_init(init_adfs_fs)
 module_exit(exit_adfs_fs)
+MODULE_LICENSE("GPL");
diff --git a/fs/befs/linuxvfs.c b/fs/befs/linuxvfs.c
index 89cd2de..615d549 100644
--- a/fs/befs/linuxvfs.c
+++ b/fs/befs/linuxvfs.c
@@ -735,8 +735,6 @@
 static void
 befs_put_super(struct super_block *sb)
 {
-	lock_kernel();
-
 	kfree(BEFS_SB(sb)->mount_opts.iocharset);
 	BEFS_SB(sb)->mount_opts.iocharset = NULL;
 
@@ -747,8 +745,6 @@
 
 	kfree(sb->s_fs_info);
 	sb->s_fs_info = NULL;
-
-	unlock_kernel();
 }
 
 /* Allocate private field of the superblock, fill it.
diff --git a/fs/binfmt_elf.c b/fs/binfmt_elf.c
index 40381df..9fa212b0 100644
--- a/fs/binfmt_elf.c
+++ b/fs/binfmt_elf.c
@@ -1340,8 +1340,10 @@
 	prstatus->pr_info.si_signo = prstatus->pr_cursig = signr;
 	prstatus->pr_sigpend = p->pending.signal.sig[0];
 	prstatus->pr_sighold = p->blocked.sig[0];
+	rcu_read_lock();
+	prstatus->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
+	rcu_read_unlock();
 	prstatus->pr_pid = task_pid_vnr(p);
-	prstatus->pr_ppid = task_pid_vnr(p->real_parent);
 	prstatus->pr_pgrp = task_pgrp_vnr(p);
 	prstatus->pr_sid = task_session_vnr(p);
 	if (thread_group_leader(p)) {
@@ -1382,8 +1384,10 @@
 			psinfo->pr_psargs[i] = ' ';
 	psinfo->pr_psargs[len] = 0;
 
+	rcu_read_lock();
+	psinfo->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
+	rcu_read_unlock();
 	psinfo->pr_pid = task_pid_vnr(p);
-	psinfo->pr_ppid = task_pid_vnr(p->real_parent);
 	psinfo->pr_pgrp = task_pgrp_vnr(p);
 	psinfo->pr_sid = task_session_vnr(p);
 
diff --git a/fs/binfmt_elf_fdpic.c b/fs/binfmt_elf_fdpic.c
index fdb66fa..20fbece 100644
--- a/fs/binfmt_elf_fdpic.c
+++ b/fs/binfmt_elf_fdpic.c
@@ -1387,8 +1387,10 @@
 	prstatus->pr_info.si_signo = prstatus->pr_cursig = signr;
 	prstatus->pr_sigpend = p->pending.signal.sig[0];
 	prstatus->pr_sighold = p->blocked.sig[0];
+	rcu_read_lock();
+	prstatus->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
+	rcu_read_unlock();
 	prstatus->pr_pid = task_pid_vnr(p);
-	prstatus->pr_ppid = task_pid_vnr(p->real_parent);
 	prstatus->pr_pgrp = task_pgrp_vnr(p);
 	prstatus->pr_sid = task_session_vnr(p);
 	if (thread_group_leader(p)) {
@@ -1432,8 +1434,10 @@
 			psinfo->pr_psargs[i] = ' ';
 	psinfo->pr_psargs[len] = 0;
 
+	rcu_read_lock();
+	psinfo->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent));
+	rcu_read_unlock();
 	psinfo->pr_pid = task_pid_vnr(p);
-	psinfo->pr_ppid = task_pid_vnr(p->real_parent);
 	psinfo->pr_pgrp = task_pgrp_vnr(p);
 	psinfo->pr_sid = task_session_vnr(p);
 
diff --git a/fs/compat_ioctl.c b/fs/compat_ioctl.c
index 0aac371..c5ded5f 100644
--- a/fs/compat_ioctl.c
+++ b/fs/compat_ioctl.c
@@ -788,12 +788,6 @@
 	if (put_user(compat_ptr(data), &sgio->usr_ptr))
 		return -EFAULT;
 
-	if (copy_in_user(&sgio->status, &sgio32->status,
-			 (4 * sizeof(unsigned char)) +
-			 (2 * sizeof(unsigned short)) +
-			 (3 * sizeof(int))))
-		return -EFAULT;
-
 	err = sys_ioctl(fd, cmd, (unsigned long) sgio);
 
 	if (err >= 0) {
diff --git a/fs/efs/dir.c b/fs/efs/dir.c
index 49308a2..7ee6f7e3 100644
--- a/fs/efs/dir.c
+++ b/fs/efs/dir.c
@@ -5,12 +5,12 @@
  */
 
 #include <linux/buffer_head.h>
-#include <linux/smp_lock.h>
 #include "efs.h"
 
 static int efs_readdir(struct file *, void *, filldir_t);
 
 const struct file_operations efs_dir_operations = {
+	.llseek		= generic_file_llseek,
 	.read		= generic_read_dir,
 	.readdir	= efs_readdir,
 };
@@ -33,8 +33,6 @@
 	if (inode->i_size & (EFS_DIRBSIZE-1))
 		printk(KERN_WARNING "EFS: WARNING: readdir(): directory size not a multiple of EFS_DIRBSIZE\n");
 
-	lock_kernel();
-
 	/* work out where this entry can be found */
 	block = filp->f_pos >> EFS_DIRBSIZE_BITS;
 
@@ -107,7 +105,6 @@
 
 	filp->f_pos = (block << EFS_DIRBSIZE_BITS) | slot;
 out:
-	unlock_kernel();
 	return 0;
 }
 
diff --git a/fs/efs/namei.c b/fs/efs/namei.c
index c3fb5f9..1511bf9 100644
--- a/fs/efs/namei.c
+++ b/fs/efs/namei.c
@@ -8,7 +8,6 @@
 
 #include <linux/buffer_head.h>
 #include <linux/string.h>
-#include <linux/smp_lock.h>
 #include <linux/exportfs.h>
 #include "efs.h"
 
@@ -63,16 +62,12 @@
 	efs_ino_t inodenum;
 	struct inode * inode = NULL;
 
-	lock_kernel();
 	inodenum = efs_find_entry(dir, dentry->d_name.name, dentry->d_name.len);
 	if (inodenum) {
 		inode = efs_iget(dir->i_sb, inodenum);
-		if (IS_ERR(inode)) {
-			unlock_kernel();
+		if (IS_ERR(inode))
 			return ERR_CAST(inode);
-		}
 	}
-	unlock_kernel();
 
 	return d_splice_alias(inode, dentry);
 }
@@ -115,11 +110,9 @@
 	struct dentry *parent = ERR_PTR(-ENOENT);
 	efs_ino_t ino;
 
-	lock_kernel();
 	ino = efs_find_entry(child->d_inode, "..", 2);
 	if (ino)
 		parent = d_obtain_alias(efs_iget(child->d_inode->i_sb, ino));
-	unlock_kernel();
 
 	return parent;
 }
diff --git a/fs/efs/symlink.c b/fs/efs/symlink.c
index 41911ec..75117d0 100644
--- a/fs/efs/symlink.c
+++ b/fs/efs/symlink.c
@@ -9,7 +9,6 @@
 #include <linux/string.h>
 #include <linux/pagemap.h>
 #include <linux/buffer_head.h>
-#include <linux/smp_lock.h>
 #include "efs.h"
 
 static int efs_symlink_readpage(struct file *file, struct page *page)
@@ -22,9 +21,8 @@
   
 	err = -ENAMETOOLONG;
 	if (size > 2 * EFS_BLOCKSIZE)
-		goto fail_notlocked;
+		goto fail;
   
-	lock_kernel();
 	/* read first 512 bytes of link target */
 	err = -EIO;
 	bh = sb_bread(inode->i_sb, efs_bmap(inode, 0));
@@ -40,14 +38,11 @@
 		brelse(bh);
 	}
 	link[size] = '\0';
-	unlock_kernel();
 	SetPageUptodate(page);
 	kunmap(page);
 	unlock_page(page);
 	return 0;
 fail:
-	unlock_kernel();
-fail_notlocked:
 	SetPageError(page);
 	kunmap(page);
 	unlock_page(page);
diff --git a/fs/eventpoll.c b/fs/eventpoll.c
index 5458e80..085c5c0 100644
--- a/fs/eventpoll.c
+++ b/fs/eventpoll.c
@@ -98,7 +98,7 @@
 struct nested_call_node {
 	struct list_head llink;
 	void *cookie;
-	int cpu;
+	void *ctx;
 };
 
 /*
@@ -317,17 +317,17 @@
  * @nproc: Nested call core function pointer.
  * @priv: Opaque data to be passed to the @nproc callback.
  * @cookie: Cookie to be used to identify this nested call.
+ * @ctx: This instance context.
  *
  * Returns: Returns the code returned by the @nproc callback, or -1 if
  *          the maximum recursion limit has been exceeded.
  */
 static int ep_call_nested(struct nested_calls *ncalls, int max_nests,
 			  int (*nproc)(void *, void *, int), void *priv,
-			  void *cookie)
+			  void *cookie, void *ctx)
 {
 	int error, call_nests = 0;
 	unsigned long flags;
-	int this_cpu = get_cpu();
 	struct list_head *lsthead = &ncalls->tasks_call_list;
 	struct nested_call_node *tncur;
 	struct nested_call_node tnode;
@@ -340,7 +340,7 @@
 	 * very much limited.
 	 */
 	list_for_each_entry(tncur, lsthead, llink) {
-		if (tncur->cpu == this_cpu &&
+		if (tncur->ctx == ctx &&
 		    (tncur->cookie == cookie || ++call_nests > max_nests)) {
 			/*
 			 * Ops ... loop detected or maximum nest level reached.
@@ -352,7 +352,7 @@
 	}
 
 	/* Add the current task and cookie to the list */
-	tnode.cpu = this_cpu;
+	tnode.ctx = ctx;
 	tnode.cookie = cookie;
 	list_add(&tnode.llink, lsthead);
 
@@ -364,10 +364,9 @@
 	/* Remove the current task from the list */
 	spin_lock_irqsave(&ncalls->lock, flags);
 	list_del(&tnode.llink);
- out_unlock:
+out_unlock:
 	spin_unlock_irqrestore(&ncalls->lock, flags);
 
-	put_cpu();
 	return error;
 }
 
@@ -408,8 +407,12 @@
  */
 static void ep_poll_safewake(wait_queue_head_t *wq)
 {
+	int this_cpu = get_cpu();
+
 	ep_call_nested(&poll_safewake_ncalls, EP_MAX_NESTS,
-		       ep_poll_wakeup_proc, NULL, wq);
+		       ep_poll_wakeup_proc, NULL, wq, (void *) (long) this_cpu);
+
+	put_cpu();
 }
 
 /*
@@ -663,7 +666,7 @@
 	 * could re-enter here.
 	 */
 	pollflags = ep_call_nested(&poll_readywalk_ncalls, EP_MAX_NESTS,
-				   ep_poll_readyevents_proc, ep, ep);
+				   ep_poll_readyevents_proc, ep, ep, current);
 
 	return pollflags != -1 ? pollflags : 0;
 }
diff --git a/fs/ext2/dir.c b/fs/ext2/dir.c
index 0035004..6cde970 100644
--- a/fs/ext2/dir.c
+++ b/fs/ext2/dir.c
@@ -450,7 +450,7 @@
 
 /* Releases the page */
 void ext2_set_link(struct inode *dir, struct ext2_dir_entry_2 *de,
-			struct page *page, struct inode *inode)
+		   struct page *page, struct inode *inode, int update_times)
 {
 	loff_t pos = page_offset(page) +
 			(char *) de - (char *) page_address(page);
@@ -465,7 +465,8 @@
 	ext2_set_de_type(de, inode);
 	err = ext2_commit_chunk(page, pos, len);
 	ext2_put_page(page);
-	dir->i_mtime = dir->i_ctime = CURRENT_TIME_SEC;
+	if (update_times)
+		dir->i_mtime = dir->i_ctime = CURRENT_TIME_SEC;
 	EXT2_I(dir)->i_flags &= ~EXT2_BTREE_FL;
 	mark_inode_dirty(dir);
 }
diff --git a/fs/ext2/ext2.h b/fs/ext2/ext2.h
index f2e5811..d988a71 100644
--- a/fs/ext2/ext2.h
+++ b/fs/ext2/ext2.h
@@ -111,7 +111,7 @@
 extern int ext2_delete_entry (struct ext2_dir_entry_2 *, struct page *);
 extern int ext2_empty_dir (struct inode *);
 extern struct ext2_dir_entry_2 * ext2_dotdot (struct inode *, struct page **);
-extern void ext2_set_link(struct inode *, struct ext2_dir_entry_2 *, struct page *, struct inode *);
+extern void ext2_set_link(struct inode *, struct ext2_dir_entry_2 *, struct page *, struct inode *, int);
 
 /* ialloc.c */
 extern struct inode * ext2_new_inode (struct inode *, int);
diff --git a/fs/ext2/namei.c b/fs/ext2/namei.c
index 90ea179..6524eca 100644
--- a/fs/ext2/namei.c
+++ b/fs/ext2/namei.c
@@ -320,7 +320,7 @@
 		if (!new_de)
 			goto out_dir;
 		inode_inc_link_count(old_inode);
-		ext2_set_link(new_dir, new_de, new_page, old_inode);
+		ext2_set_link(new_dir, new_de, new_page, old_inode, 1);
 		new_inode->i_ctime = CURRENT_TIME_SEC;
 		if (dir_de)
 			drop_nlink(new_inode);
@@ -352,7 +352,8 @@
 	inode_dec_link_count(old_inode);
 
 	if (dir_de) {
-		ext2_set_link(old_inode, dir_de, dir_page, new_dir);
+		if (old_dir != new_dir)
+			ext2_set_link(old_inode, dir_de, dir_page, new_dir, 0);
 		inode_dec_link_count(old_dir);
 	}
 	return 0;
diff --git a/fs/ext3/acl.c b/fs/ext3/acl.c
index d81ef2f..e0c7454 100644
--- a/fs/ext3/acl.c
+++ b/fs/ext3/acl.c
@@ -129,12 +129,15 @@
 static inline struct posix_acl *
 ext3_iget_acl(struct inode *inode, struct posix_acl **i_acl)
 {
-	struct posix_acl *acl = EXT3_ACL_NOT_CACHED;
+	struct posix_acl *acl = ACCESS_ONCE(*i_acl);
 
-	spin_lock(&inode->i_lock);
-	if (*i_acl != EXT3_ACL_NOT_CACHED)
-		acl = posix_acl_dup(*i_acl);
-	spin_unlock(&inode->i_lock);
+	if (acl) {
+		spin_lock(&inode->i_lock);
+		acl = *i_acl;
+		if (acl != EXT3_ACL_NOT_CACHED)
+			acl = posix_acl_dup(acl);
+		spin_unlock(&inode->i_lock);
+	}
 
 	return acl;
 }
diff --git a/fs/ext3/inode.c b/fs/ext3/inode.c
index b0248c6..05dea81 100644
--- a/fs/ext3/inode.c
+++ b/fs/ext3/inode.c
@@ -820,7 +820,7 @@
 		while (count < maxblocks && count <= blocks_to_boundary) {
 			ext3_fsblk_t blk;
 
-			if (!verify_chain(chain, partial)) {
+			if (!verify_chain(chain, chain + depth - 1)) {
 				/*
 				 * Indirect block might be removed by
 				 * truncate while we were reading it.
@@ -2374,7 +2374,7 @@
 	struct page *page;
 
 	if (!ext3_can_truncate(inode))
-		return;
+		goto out_notrans;
 
 	if (inode->i_size == 0 && ext3_should_writeback_data(inode))
 		ei->i_state |= EXT3_STATE_FLUSH_ON_CLOSE;
@@ -2390,7 +2390,7 @@
 		page = grab_cache_page(mapping,
 				inode->i_size >> PAGE_CACHE_SHIFT);
 		if (!page)
-			return;
+			goto out_notrans;
 	}
 
 	handle = start_transaction(inode);
@@ -2401,7 +2401,7 @@
 			unlock_page(page);
 			page_cache_release(page);
 		}
-		return;		/* AKPM: return what? */
+		goto out_notrans;
 	}
 
 	last_block = (inode->i_size + blocksize-1)
@@ -2525,6 +2525,14 @@
 		ext3_orphan_del(handle, inode);
 
 	ext3_journal_stop(handle);
+	return;
+out_notrans:
+	/*
+	 * Delete the inode from orphan list so that it doesn't stay there
+	 * forever and trigger assertion on umount.
+	 */
+	if (inode->i_nlink)
+		ext3_orphan_del(NULL, inode);
 }
 
 static ext3_fsblk_t ext3_get_inode_block(struct super_block *sb,
@@ -3122,12 +3130,6 @@
 
 	rc = inode_setattr(inode, attr);
 
-	/* If inode_setattr's call to ext3_truncate failed to get a
-	 * transaction handle at all, we need to clean up the in-core
-	 * orphan list manually. */
-	if (inode->i_nlink)
-		ext3_orphan_del(NULL, inode);
-
 	if (!rc && (ia_valid & ATTR_MODE))
 		rc = ext3_acl_chmod(inode);
 
diff --git a/fs/ext3/resize.c b/fs/ext3/resize.c
index 8a0b263..8359e7b 100644
--- a/fs/ext3/resize.c
+++ b/fs/ext3/resize.c
@@ -990,7 +990,7 @@
 			sb->s_id, n_blocks_count);
 		if (sizeof(sector_t) < 8)
 			ext3_warning(sb, __func__,
-			"CONFIG_LBD not enabled\n");
+			"CONFIG_LBDAF not enabled\n");
 		return -EINVAL;
 	}
 
diff --git a/fs/ext3/super.c b/fs/ext3/super.c
index 26aa64d..601e881 100644
--- a/fs/ext3/super.c
+++ b/fs/ext3/super.c
@@ -1812,7 +1812,7 @@
 		printk(KERN_ERR "EXT3-fs: filesystem on %s:"
 			" too large to mount safely\n", sb->s_id);
 		if (sizeof(sector_t) < 8)
-			printk(KERN_WARNING "EXT3-fs: CONFIG_LBD not "
+			printk(KERN_WARNING "EXT3-fs: CONFIG_LBDAF not "
 					"enabled\n");
 		goto failed_mount;
 	}
diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile
index 8a34710..8867b2a 100644
--- a/fs/ext4/Makefile
+++ b/fs/ext4/Makefile
@@ -6,7 +6,7 @@
 
 ext4-y	:= balloc.o bitmap.o dir.o file.o fsync.o ialloc.o inode.o \
 		ioctl.o namei.o super.o symlink.o hash.o resize.o extents.o \
-		ext4_jbd2.o migrate.o mballoc.o block_validity.o
+		ext4_jbd2.o migrate.o mballoc.o block_validity.o move_extent.o
 
 ext4-$(CONFIG_EXT4_FS_XATTR)		+= xattr.o xattr_user.o xattr_trusted.o
 ext4-$(CONFIG_EXT4_FS_POSIX_ACL)	+= acl.o
diff --git a/fs/ext4/acl.c b/fs/ext4/acl.c
index 647e0d6..605aeed 100644
--- a/fs/ext4/acl.c
+++ b/fs/ext4/acl.c
@@ -129,12 +129,15 @@
 static inline struct posix_acl *
 ext4_iget_acl(struct inode *inode, struct posix_acl **i_acl)
 {
-	struct posix_acl *acl = EXT4_ACL_NOT_CACHED;
+	struct posix_acl *acl = ACCESS_ONCE(*i_acl);
 
-	spin_lock(&inode->i_lock);
-	if (*i_acl != EXT4_ACL_NOT_CACHED)
-		acl = posix_acl_dup(*i_acl);
-	spin_unlock(&inode->i_lock);
+	if (acl) {
+		spin_lock(&inode->i_lock);
+		acl = *i_acl;
+		if (acl != EXT4_ACL_NOT_CACHED)
+			acl = posix_acl_dup(acl);
+		spin_unlock(&inode->i_lock);
+	}
 
 	return acl;
 }
diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h
index cc7d5ed..17b9998 100644
--- a/fs/ext4/ext4.h
+++ b/fs/ext4/ext4.h
@@ -352,6 +352,7 @@
  /* note ioctl 10 reserved for an early version of the FIEMAP ioctl */
  /* note ioctl 11 reserved for filesystem-independent FIEMAP ioctl */
 #define EXT4_IOC_ALLOC_DA_BLKS		_IO('f', 12)
+#define EXT4_IOC_MOVE_EXT		_IOWR('f', 15, struct move_extent)
 
 /*
  * ioctl commands in 32 bit emulation
@@ -447,6 +448,15 @@
 	__le32  i_version_hi;	/* high 32 bits for 64-bit version */
 };
 
+struct move_extent {
+	__u32 reserved;		/* should be zero */
+	__u32 donor_fd;		/* donor file descriptor */
+	__u64 orig_start;	/* logical start offset in block for orig */
+	__u64 donor_start;	/* logical start offset in block for donor */
+	__u64 len;		/* block length to be moved */
+	__u64 moved_len;	/* moved block length */
+};
+#define MAX_DEFRAG_SIZE         ((1UL<<31) - 1)
 
 #define EXT4_EPOCH_BITS 2
 #define EXT4_EPOCH_MASK ((1 << EXT4_EPOCH_BITS) - 1)
@@ -674,7 +684,6 @@
 #define EXT4_MOUNT_ERRORS_PANIC		0x00040	/* Panic on errors */
 #define EXT4_MOUNT_MINIX_DF		0x00080	/* Mimics the Minix statfs */
 #define EXT4_MOUNT_NOLOAD		0x00100	/* Don't use existing journal*/
-#define EXT4_MOUNT_ABORT		0x00200	/* Fatal error detected */
 #define EXT4_MOUNT_DATA_FLAGS		0x00C00	/* Mode for data writes: */
 #define EXT4_MOUNT_JOURNAL_DATA		0x00400	/* Write data to journal */
 #define EXT4_MOUNT_ORDERED_DATA		0x00800	/* Flush data before commit */
@@ -696,17 +705,10 @@
 #define EXT4_MOUNT_DATA_ERR_ABORT	0x10000000 /* Abort on file data write */
 #define EXT4_MOUNT_BLOCK_VALIDITY	0x20000000 /* Block validity checking */
 
-/* Compatibility, for having both ext2_fs.h and ext4_fs.h included at once */
-#ifndef _LINUX_EXT2_FS_H
 #define clear_opt(o, opt)		o &= ~EXT4_MOUNT_##opt
 #define set_opt(o, opt)			o |= EXT4_MOUNT_##opt
 #define test_opt(sb, opt)		(EXT4_SB(sb)->s_mount_opt & \
 					 EXT4_MOUNT_##opt)
-#else
-#define EXT2_MOUNT_NOLOAD		EXT4_MOUNT_NOLOAD
-#define EXT2_MOUNT_ABORT		EXT4_MOUNT_ABORT
-#define EXT2_MOUNT_DATA_FLAGS		EXT4_MOUNT_DATA_FLAGS
-#endif
 
 #define ext4_set_bit			ext2_set_bit
 #define ext4_set_bit_atomic		ext2_set_bit_atomic
@@ -824,6 +826,13 @@
 };
 
 #ifdef __KERNEL__
+
+/*
+ * run-time mount flags
+ */
+#define EXT4_MF_MNTDIR_SAMPLED	0x0001
+#define EXT4_MF_FS_ABORTED	0x0002	/* Fatal error detected */
+
 /*
  * fourth extended-fs super-block data in memory
  */
@@ -842,7 +851,8 @@
 	struct buffer_head * s_sbh;	/* Buffer containing the super block */
 	struct ext4_super_block *s_es;	/* Pointer to the super block in the buffer */
 	struct buffer_head **s_group_desc;
-	unsigned long  s_mount_opt;
+	unsigned int s_mount_opt;
+	unsigned int s_mount_flags;
 	ext4_fsblk_t s_sb_block;
 	uid_t s_resuid;
 	gid_t s_resgid;
@@ -853,6 +863,7 @@
 	int s_inode_size;
 	int s_first_ino;
 	unsigned int s_inode_readahead_blks;
+	unsigned int s_inode_goal;
 	spinlock_t s_next_gen_lock;
 	u32 s_next_generation;
 	u32 s_hash_seed[4];
@@ -1305,7 +1316,8 @@
 			  dx_hash_info *hinfo);
 
 /* ialloc.c */
-extern struct inode * ext4_new_inode(handle_t *, struct inode *, int);
+extern struct inode *ext4_new_inode(handle_t *, struct inode *, int,
+				    const struct qstr *qstr, __u32 goal);
 extern void ext4_free_inode(handle_t *, struct inode *);
 extern struct inode * ext4_orphan_get(struct super_block *, unsigned long);
 extern unsigned long ext4_count_free_inodes(struct super_block *);
@@ -1329,7 +1341,7 @@
 extern int __init init_ext4_mballoc(void);
 extern void exit_ext4_mballoc(void);
 extern void ext4_mb_free_blocks(handle_t *, struct inode *,
-		unsigned long, unsigned long, int, unsigned long *);
+		ext4_fsblk_t, unsigned long, int, unsigned long *);
 extern int ext4_mb_add_groupinfo(struct super_block *sb,
 		ext4_group_t i, struct ext4_group_desc *desc);
 extern void ext4_mb_update_group_info(struct ext4_group_info *grp,
@@ -1647,6 +1659,11 @@
 			   struct buffer_head *bh, int flags);
 extern int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
 			__u64 start, __u64 len);
+/* move_extent.c */
+extern int ext4_move_extents(struct file *o_filp, struct file *d_filp,
+			     __u64 start_orig, __u64 start_donor,
+			     __u64 len, __u64 *moved_len);
+
 
 /*
  * Add new method to test wether block and inode bitmaps are properly
diff --git a/fs/ext4/ext4_extents.h b/fs/ext4/ext4_extents.h
index f0c3ec85..20a8410 100644
--- a/fs/ext4/ext4_extents.h
+++ b/fs/ext4/ext4_extents.h
@@ -221,12 +221,16 @@
 }
 
 extern int ext4_ext_calc_metadata_amount(struct inode *inode, int blocks);
+extern ext4_fsblk_t ext_pblock(struct ext4_extent *ex);
 extern ext4_fsblk_t idx_pblock(struct ext4_extent_idx *);
 extern void ext4_ext_store_pblock(struct ext4_extent *, ext4_fsblk_t);
 extern int ext4_extent_tree_init(handle_t *, struct inode *);
 extern int ext4_ext_calc_credits_for_single_extent(struct inode *inode,
 						   int num,
 						   struct ext4_ext_path *path);
+extern int ext4_can_extents_be_merged(struct inode *inode,
+				      struct ext4_extent *ex1,
+				      struct ext4_extent *ex2);
 extern int ext4_ext_try_to_merge(struct inode *inode,
 				 struct ext4_ext_path *path,
 				 struct ext4_extent *);
diff --git a/fs/ext4/extents.c b/fs/ext4/extents.c
index 2593f74..50322a0 100644
--- a/fs/ext4/extents.c
+++ b/fs/ext4/extents.c
@@ -49,7 +49,7 @@
  * ext_pblock:
  * combine low and high parts of physical block number into ext4_fsblk_t
  */
-static ext4_fsblk_t ext_pblock(struct ext4_extent *ex)
+ext4_fsblk_t ext_pblock(struct ext4_extent *ex)
 {
 	ext4_fsblk_t block;
 
@@ -1417,7 +1417,7 @@
 	return err;
 }
 
-static int
+int
 ext4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,
 				struct ext4_extent *ex2)
 {
diff --git a/fs/ext4/file.c b/fs/ext4/file.c
index 588af8c..3f1873f 100644
--- a/fs/ext4/file.c
+++ b/fs/ext4/file.c
@@ -21,6 +21,8 @@
 #include <linux/time.h>
 #include <linux/fs.h>
 #include <linux/jbd2.h>
+#include <linux/mount.h>
+#include <linux/path.h>
 #include "ext4.h"
 #include "ext4_jbd2.h"
 #include "xattr.h"
@@ -145,6 +147,38 @@
 	return 0;
 }
 
+static int ext4_file_open(struct inode * inode, struct file * filp)
+{
+	struct super_block *sb = inode->i_sb;
+	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
+	struct vfsmount *mnt = filp->f_path.mnt;
+	struct path path;
+	char buf[64], *cp;
+
+	if (unlikely(!(sbi->s_mount_flags & EXT4_MF_MNTDIR_SAMPLED) &&
+		     !(sb->s_flags & MS_RDONLY))) {
+		sbi->s_mount_flags |= EXT4_MF_MNTDIR_SAMPLED;
+		/*
+		 * Sample where the filesystem has been mounted and
+		 * store it in the superblock for sysadmin convenience
+		 * when trying to sort through large numbers of block
+		 * devices or filesystem images.
+		 */
+		memset(buf, 0, sizeof(buf));
+		path.mnt = mnt->mnt_parent;
+		path.dentry = mnt->mnt_mountpoint;
+		path_get(&path);
+		cp = d_path(&path, buf, sizeof(buf));
+		path_put(&path);
+		if (!IS_ERR(cp)) {
+			memcpy(sbi->s_es->s_last_mounted, cp,
+			       sizeof(sbi->s_es->s_last_mounted));
+			sb->s_dirt = 1;
+		}
+	}
+	return generic_file_open(inode, filp);
+}
+
 const struct file_operations ext4_file_operations = {
 	.llseek		= generic_file_llseek,
 	.read		= do_sync_read,
@@ -156,7 +190,7 @@
 	.compat_ioctl	= ext4_compat_ioctl,
 #endif
 	.mmap		= ext4_file_mmap,
-	.open		= generic_file_open,
+	.open		= ext4_file_open,
 	.release	= ext4_release_file,
 	.fsync		= ext4_sync_file,
 	.splice_read	= generic_file_splice_read,
diff --git a/fs/ext4/fsync.c b/fs/ext4/fsync.c
index 5afe437..83cf641 100644
--- a/fs/ext4/fsync.c
+++ b/fs/ext4/fsync.c
@@ -28,10 +28,12 @@
 #include <linux/writeback.h>
 #include <linux/jbd2.h>
 #include <linux/blkdev.h>
-#include <linux/marker.h>
+
 #include "ext4.h"
 #include "ext4_jbd2.h"
 
+#include <trace/events/ext4.h>
+
 /*
  * akpm: A new design for ext4_sync_file().
  *
@@ -52,9 +54,7 @@
 
 	J_ASSERT(ext4_journal_current_handle() == NULL);
 
-	trace_mark(ext4_sync_file, "dev %s datasync %d ino %ld parent %ld",
-		   inode->i_sb->s_id, datasync, inode->i_ino,
-		   dentry->d_parent->d_inode->i_ino);
+	trace_ext4_sync_file(file, dentry, datasync);
 
 	/*
 	 * data=writeback:
diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c
index 3743bd8..2f64573 100644
--- a/fs/ext4/ialloc.c
+++ b/fs/ext4/ialloc.c
@@ -23,11 +23,14 @@
 #include <linux/bitops.h>
 #include <linux/blkdev.h>
 #include <asm/byteorder.h>
+
 #include "ext4.h"
 #include "ext4_jbd2.h"
 #include "xattr.h"
 #include "acl.h"
 
+#include <trace/events/ext4.h>
+
 /*
  * ialloc.c contains the inodes allocation and deallocation routines
  */
@@ -208,11 +211,7 @@
 
 	ino = inode->i_ino;
 	ext4_debug("freeing inode %lu\n", ino);
-	trace_mark(ext4_free_inode,
-		   "dev %s ino %lu mode %d uid %lu gid %lu bocks %llu",
-		   sb->s_id, inode->i_ino, inode->i_mode,
-		   (unsigned long) inode->i_uid, (unsigned long) inode->i_gid,
-		   (unsigned long long) inode->i_blocks);
+	trace_ext4_free_inode(inode);
 
 	/*
 	 * Note: we must free any quota before locking the superblock,
@@ -471,7 +470,8 @@
  */
 
 static int find_group_orlov(struct super_block *sb, struct inode *parent,
-			    ext4_group_t *group, int mode)
+			    ext4_group_t *group, int mode,
+			    const struct qstr *qstr)
 {
 	ext4_group_t parent_group = EXT4_I(parent)->i_block_group;
 	struct ext4_sb_info *sbi = EXT4_SB(sb);
@@ -486,6 +486,7 @@
 	struct ext4_group_desc *desc;
 	struct orlov_stats stats;
 	int flex_size = ext4_flex_bg_size(sbi);
+	struct dx_hash_info hinfo;
 
 	ngroups = real_ngroups;
 	if (flex_size > 1) {
@@ -507,7 +508,13 @@
 		int best_ndir = inodes_per_group;
 		int ret = -1;
 
-		get_random_bytes(&grp, sizeof(grp));
+		if (qstr) {
+			hinfo.hash_version = DX_HASH_HALF_MD4;
+			hinfo.seed = sbi->s_hash_seed;
+			ext4fs_dirhash(qstr->name, qstr->len, &hinfo);
+			grp = hinfo.hash;
+		} else
+			get_random_bytes(&grp, sizeof(grp));
 		parent_group = (unsigned)grp % ngroups;
 		for (i = 0; i < ngroups; i++) {
 			g = (parent_group + i) % ngroups;
@@ -650,7 +657,7 @@
 		*group = parent_group + flex_size;
 		if (*group > ngroups)
 			*group = 0;
-		return find_group_orlov(sb, parent, group, mode);
+		return find_group_orlov(sb, parent, group, mode, 0);
 	}
 
 	/*
@@ -791,7 +798,8 @@
  * For other inodes, search forward from the parent directory's block
  * group to find a free inode.
  */
-struct inode *ext4_new_inode(handle_t *handle, struct inode *dir, int mode)
+struct inode *ext4_new_inode(handle_t *handle, struct inode *dir, int mode,
+			     const struct qstr *qstr, __u32 goal)
 {
 	struct super_block *sb;
 	struct buffer_head *inode_bitmap_bh = NULL;
@@ -815,14 +823,23 @@
 
 	sb = dir->i_sb;
 	ngroups = ext4_get_groups_count(sb);
-	trace_mark(ext4_request_inode, "dev %s dir %lu mode %d", sb->s_id,
-		   dir->i_ino, mode);
+	trace_ext4_request_inode(dir, mode);
 	inode = new_inode(sb);
 	if (!inode)
 		return ERR_PTR(-ENOMEM);
 	ei = EXT4_I(inode);
 	sbi = EXT4_SB(sb);
 
+	if (!goal)
+		goal = sbi->s_inode_goal;
+
+	if (goal && goal < le32_to_cpu(sbi->s_es->s_inodes_count)) {
+		group = (goal - 1) / EXT4_INODES_PER_GROUP(sb);
+		ino = (goal - 1) % EXT4_INODES_PER_GROUP(sb);
+		ret2 = 0;
+		goto got_group;
+	}
+
 	if (sbi->s_log_groups_per_flex && test_opt(sb, OLDALLOC)) {
 		ret2 = find_group_flex(sb, dir, &group);
 		if (ret2 == -1) {
@@ -841,7 +858,7 @@
 		if (test_opt(sb, OLDALLOC))
 			ret2 = find_group_dir(sb, dir, &group);
 		else
-			ret2 = find_group_orlov(sb, dir, &group, mode);
+			ret2 = find_group_orlov(sb, dir, &group, mode, qstr);
 	} else
 		ret2 = find_group_other(sb, dir, &group, mode);
 
@@ -851,7 +868,7 @@
 	if (ret2 == -1)
 		goto out;
 
-	for (i = 0; i < ngroups; i++) {
+	for (i = 0; i < ngroups; i++, ino = 0) {
 		err = -EIO;
 
 		gdp = ext4_get_group_desc(sb, group, &group_desc_bh);
@@ -863,8 +880,6 @@
 		if (!inode_bitmap_bh)
 			goto fail;
 
-		ino = 0;
-
 repeat_in_this_group:
 		ino = ext4_find_next_zero_bit((unsigned long *)
 					      inode_bitmap_bh->b_data,
@@ -1047,8 +1062,7 @@
 	}
 
 	ext4_debug("allocating inode %lu\n", inode->i_ino);
-	trace_mark(ext4_allocate_inode, "dev %s ino %lu dir %lu mode %d",
-		   sb->s_id, inode->i_ino, dir->i_ino, mode);
+	trace_ext4_allocate_inode(inode, dir, mode);
 	goto really_out;
 fail:
 	ext4_std_error(sb, err);
diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c
index 875db94..7c17ae2 100644
--- a/fs/ext4/inode.c
+++ b/fs/ext4/inode.c
@@ -37,11 +37,14 @@
 #include <linux/namei.h>
 #include <linux/uio.h>
 #include <linux/bio.h>
+
 #include "ext4_jbd2.h"
 #include "xattr.h"
 #include "acl.h"
 #include "ext4_extents.h"
 
+#include <trace/events/ext4.h>
+
 #define MPAGE_DA_EXTENT_TAIL 0x01
 
 static inline int ext4_begin_ordered_truncate(struct inode *inode,
@@ -78,7 +81,7 @@
  * If the handle isn't valid we're not journaling so there's nothing to do.
  */
 int ext4_forget(handle_t *handle, int is_metadata, struct inode *inode,
-			struct buffer_head *bh, ext4_fsblk_t blocknr)
+		struct buffer_head *bh, ext4_fsblk_t blocknr)
 {
 	int err;
 
@@ -90,7 +93,7 @@
 	BUFFER_TRACE(bh, "enter");
 
 	jbd_debug(4, "forgetting bh %p: is_metadata = %d, mode %o, "
-		  "data mode %lx\n",
+		  "data mode %x\n",
 		  bh, is_metadata, inode->i_mode,
 		  test_opt(inode->i_sb, DATA_FLAGS));
 
@@ -329,8 +332,8 @@
  */
 
 static int ext4_block_to_path(struct inode *inode,
-			ext4_lblk_t i_block,
-			ext4_lblk_t offsets[4], int *boundary)
+			      ext4_lblk_t i_block,
+			      ext4_lblk_t offsets[4], int *boundary)
 {
 	int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
 	int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
@@ -362,9 +365,9 @@
 		final = ptrs;
 	} else {
 		ext4_warning(inode->i_sb, "ext4_block_to_path",
-				"block %lu > max in inode %lu",
-				i_block + direct_blocks +
-				indirect_blocks + double_blocks, inode->i_ino);
+			     "block %lu > max in inode %lu",
+			     i_block + direct_blocks +
+			     indirect_blocks + double_blocks, inode->i_ino);
 	}
 	if (boundary)
 		*boundary = final - 1 - (i_block & (ptrs - 1));
@@ -379,25 +382,25 @@
 
 	while (bref < p+max) {
 		blk = le32_to_cpu(*bref++);
-		if (blk && 
-		    unlikely(!ext4_data_block_valid(EXT4_SB(inode->i_sb), 
+		if (blk &&
+		    unlikely(!ext4_data_block_valid(EXT4_SB(inode->i_sb),
 						    blk, 1))) {
 			ext4_error(inode->i_sb, function,
 				   "invalid block reference %u "
 				   "in inode #%lu", blk, inode->i_ino);
- 			return -EIO;
- 		}
- 	}
- 	return 0;
+			return -EIO;
+		}
+	}
+	return 0;
 }
 
 
 #define ext4_check_indirect_blockref(inode, bh)                         \
-        __ext4_check_blockref(__func__, inode, (__le32 *)(bh)->b_data,  \
+	__ext4_check_blockref(__func__, inode, (__le32 *)(bh)->b_data,  \
 			      EXT4_ADDR_PER_BLOCK((inode)->i_sb))
 
 #define ext4_check_inode_blockref(inode)                                \
-        __ext4_check_blockref(__func__, inode, EXT4_I(inode)->i_data,   \
+	__ext4_check_blockref(__func__, inode, EXT4_I(inode)->i_data,   \
 			      EXT4_NDIR_BLOCKS)
 
 /**
@@ -447,7 +450,7 @@
 		bh = sb_getblk(sb, le32_to_cpu(p->key));
 		if (unlikely(!bh))
 			goto failure;
-                  
+
 		if (!bh_uptodate_or_lock(bh)) {
 			if (bh_submit_read(bh) < 0) {
 				put_bh(bh);
@@ -459,7 +462,7 @@
 				goto failure;
 			}
 		}
-		
+
 		add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
 		/* Reader: end */
 		if (!p->key)
@@ -552,7 +555,7 @@
  *	returns it.
  */
 static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
-		Indirect *partial)
+				   Indirect *partial)
 {
 	/*
 	 * XXX need to get goal block from mballoc's data structures
@@ -574,7 +577,7 @@
  *	direct and indirect blocks.
  */
 static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
-		int blocks_to_boundary)
+				 int blocks_to_boundary)
 {
 	unsigned int count = 0;
 
@@ -610,9 +613,9 @@
  *		direct blocks
  */
 static int ext4_alloc_blocks(handle_t *handle, struct inode *inode,
-				ext4_lblk_t iblock, ext4_fsblk_t goal,
-				int indirect_blks, int blks,
-				ext4_fsblk_t new_blocks[4], int *err)
+			     ext4_lblk_t iblock, ext4_fsblk_t goal,
+			     int indirect_blks, int blks,
+			     ext4_fsblk_t new_blocks[4], int *err)
 {
 	struct ext4_allocation_request ar;
 	int target, i;
@@ -683,10 +686,10 @@
 	}
 	if (!*err) {
 		if (target == blks) {
-		/*
-		 * save the new block number
-		 * for the first direct block
-		 */
+			/*
+			 * save the new block number
+			 * for the first direct block
+			 */
 			new_blocks[index] = current_block;
 		}
 		blk_allocated += ar.len;
@@ -728,9 +731,9 @@
  *	as described above and return 0.
  */
 static int ext4_alloc_branch(handle_t *handle, struct inode *inode,
-				ext4_lblk_t iblock, int indirect_blks,
-				int *blks, ext4_fsblk_t goal,
-				ext4_lblk_t *offsets, Indirect *branch)
+			     ext4_lblk_t iblock, int indirect_blks,
+			     int *blks, ext4_fsblk_t goal,
+			     ext4_lblk_t *offsets, Indirect *branch)
 {
 	int blocksize = inode->i_sb->s_blocksize;
 	int i, n = 0;
@@ -777,7 +780,7 @@
 			 * the chain to point to the new allocated
 			 * data blocks numbers
 			 */
-			for (i=1; i < num; i++)
+			for (i = 1; i < num; i++)
 				*(branch[n].p + i) = cpu_to_le32(++current_block);
 		}
 		BUFFER_TRACE(bh, "marking uptodate");
@@ -820,7 +823,8 @@
  * chain to new block and return 0.
  */
 static int ext4_splice_branch(handle_t *handle, struct inode *inode,
-			ext4_lblk_t block, Indirect *where, int num, int blks)
+			      ext4_lblk_t block, Indirect *where, int num,
+			      int blks)
 {
 	int i;
 	int err = 0;
@@ -852,10 +856,6 @@
 	}
 
 	/* We are done with atomic stuff, now do the rest of housekeeping */
-
-	inode->i_ctime = ext4_current_time(inode);
-	ext4_mark_inode_dirty(handle, inode);
-
 	/* had we spliced it onto indirect block? */
 	if (where->bh) {
 		/*
@@ -874,8 +874,8 @@
 	} else {
 		/*
 		 * OK, we spliced it into the inode itself on a direct block.
-		 * Inode was dirtied above.
 		 */
+		ext4_mark_inode_dirty(handle, inode);
 		jbd_debug(5, "splicing direct\n");
 	}
 	return err;
@@ -921,9 +921,9 @@
  * blocks.
  */
 static int ext4_ind_get_blocks(handle_t *handle, struct inode *inode,
-				  ext4_lblk_t iblock, unsigned int maxblocks,
-				  struct buffer_head *bh_result,
-				  int flags)
+			       ext4_lblk_t iblock, unsigned int maxblocks,
+			       struct buffer_head *bh_result,
+			       int flags)
 {
 	int err = -EIO;
 	ext4_lblk_t offsets[4];
@@ -939,7 +939,7 @@
 	J_ASSERT(!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL));
 	J_ASSERT(handle != NULL || (flags & EXT4_GET_BLOCKS_CREATE) == 0);
 	depth = ext4_block_to_path(inode, iblock, offsets,
-					&blocks_to_boundary);
+				   &blocks_to_boundary);
 
 	if (depth == 0)
 		goto out;
@@ -987,8 +987,8 @@
 	 * Block out ext4_truncate while we alter the tree
 	 */
 	err = ext4_alloc_branch(handle, inode, iblock, indirect_blks,
-					&count, goal,
-					offsets + (partial - chain), partial);
+				&count, goal,
+				offsets + (partial - chain), partial);
 
 	/*
 	 * The ext4_splice_branch call will free and forget any buffers
@@ -999,8 +999,8 @@
 	 */
 	if (!err)
 		err = ext4_splice_branch(handle, inode, iblock,
-					partial, indirect_blks, count);
-	else 
+					 partial, indirect_blks, count);
+	else
 		goto cleanup;
 
 	set_buffer_new(bh_result);
@@ -1172,7 +1172,7 @@
 	up_read((&EXT4_I(inode)->i_data_sem));
 
 	if (retval > 0 && buffer_mapped(bh)) {
-		int ret = check_block_validity(inode, block, 
+		int ret = check_block_validity(inode, block,
 					       bh->b_blocknr, retval);
 		if (ret != 0)
 			return ret;
@@ -1254,7 +1254,7 @@
 
 	up_write((&EXT4_I(inode)->i_data_sem));
 	if (retval > 0 && buffer_mapped(bh)) {
-		int ret = check_block_validity(inode, block, 
+		int ret = check_block_validity(inode, block,
 					       bh->b_blocknr, retval);
 		if (ret != 0)
 			return ret;
@@ -1405,8 +1405,7 @@
 
 	for (bh = head, block_start = 0;
 	     ret == 0 && (bh != head || !block_start);
-	     block_start = block_end, bh = next)
-	{
+	     block_start = block_end, bh = next) {
 		next = bh->b_this_page;
 		block_end = block_start + blocksize;
 		if (block_end <= from || block_start >= to) {
@@ -1447,7 +1446,7 @@
  * write.
  */
 static int do_journal_get_write_access(handle_t *handle,
-					struct buffer_head *bh)
+				       struct buffer_head *bh)
 {
 	if (!buffer_mapped(bh) || buffer_freed(bh))
 		return 0;
@@ -1455,27 +1454,24 @@
 }
 
 static int ext4_write_begin(struct file *file, struct address_space *mapping,
-				loff_t pos, unsigned len, unsigned flags,
-				struct page **pagep, void **fsdata)
+			    loff_t pos, unsigned len, unsigned flags,
+			    struct page **pagep, void **fsdata)
 {
 	struct inode *inode = mapping->host;
 	int ret, needed_blocks;
 	handle_t *handle;
 	int retries = 0;
 	struct page *page;
- 	pgoff_t index;
+	pgoff_t index;
 	unsigned from, to;
 
-	trace_mark(ext4_write_begin,
-		   "dev %s ino %lu pos %llu len %u flags %u",
-		   inode->i_sb->s_id, inode->i_ino,
-		   (unsigned long long) pos, len, flags);
+	trace_ext4_write_begin(inode, pos, len, flags);
 	/*
 	 * Reserve one block more for addition to orphan list in case
 	 * we allocate blocks but write fails for some reason
 	 */
 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
- 	index = pos >> PAGE_CACHE_SHIFT;
+	index = pos >> PAGE_CACHE_SHIFT;
 	from = pos & (PAGE_CACHE_SIZE - 1);
 	to = from + len;
 
@@ -1523,7 +1519,7 @@
 		ext4_journal_stop(handle);
 		if (pos + len > inode->i_size) {
 			vmtruncate(inode, inode->i_size);
-			/* 
+			/*
 			 * If vmtruncate failed early the inode might
 			 * still be on the orphan list; we need to
 			 * make sure the inode is removed from the
@@ -1550,9 +1546,9 @@
 }
 
 static int ext4_generic_write_end(struct file *file,
-				struct address_space *mapping,
-				loff_t pos, unsigned len, unsigned copied,
-				struct page *page, void *fsdata)
+				  struct address_space *mapping,
+				  loff_t pos, unsigned len, unsigned copied,
+				  struct page *page, void *fsdata)
 {
 	int i_size_changed = 0;
 	struct inode *inode = mapping->host;
@@ -1603,18 +1599,15 @@
  * buffers are managed internally.
  */
 static int ext4_ordered_write_end(struct file *file,
-				struct address_space *mapping,
-				loff_t pos, unsigned len, unsigned copied,
-				struct page *page, void *fsdata)
+				  struct address_space *mapping,
+				  loff_t pos, unsigned len, unsigned copied,
+				  struct page *page, void *fsdata)
 {
 	handle_t *handle = ext4_journal_current_handle();
 	struct inode *inode = mapping->host;
 	int ret = 0, ret2;
 
-	trace_mark(ext4_ordered_write_end,
-		   "dev %s ino %lu pos %llu len %u copied %u",
-		   inode->i_sb->s_id, inode->i_ino,
-		   (unsigned long long) pos, len, copied);
+	trace_ext4_ordered_write_end(inode, pos, len, copied);
 	ret = ext4_jbd2_file_inode(handle, inode);
 
 	if (ret == 0) {
@@ -1636,7 +1629,7 @@
 
 	if (pos + len > inode->i_size) {
 		vmtruncate(inode, inode->i_size);
-		/* 
+		/*
 		 * If vmtruncate failed early the inode might still be
 		 * on the orphan list; we need to make sure the inode
 		 * is removed from the orphan list in that case.
@@ -1650,18 +1643,15 @@
 }
 
 static int ext4_writeback_write_end(struct file *file,
-				struct address_space *mapping,
-				loff_t pos, unsigned len, unsigned copied,
-				struct page *page, void *fsdata)
+				    struct address_space *mapping,
+				    loff_t pos, unsigned len, unsigned copied,
+				    struct page *page, void *fsdata)
 {
 	handle_t *handle = ext4_journal_current_handle();
 	struct inode *inode = mapping->host;
 	int ret = 0, ret2;
 
-	trace_mark(ext4_writeback_write_end,
-		   "dev %s ino %lu pos %llu len %u copied %u",
-		   inode->i_sb->s_id, inode->i_ino,
-		   (unsigned long long) pos, len, copied);
+	trace_ext4_writeback_write_end(inode, pos, len, copied);
 	ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
 							page, fsdata);
 	copied = ret2;
@@ -1681,7 +1671,7 @@
 
 	if (pos + len > inode->i_size) {
 		vmtruncate(inode, inode->i_size);
-		/* 
+		/*
 		 * If vmtruncate failed early the inode might still be
 		 * on the orphan list; we need to make sure the inode
 		 * is removed from the orphan list in that case.
@@ -1694,9 +1684,9 @@
 }
 
 static int ext4_journalled_write_end(struct file *file,
-				struct address_space *mapping,
-				loff_t pos, unsigned len, unsigned copied,
-				struct page *page, void *fsdata)
+				     struct address_space *mapping,
+				     loff_t pos, unsigned len, unsigned copied,
+				     struct page *page, void *fsdata)
 {
 	handle_t *handle = ext4_journal_current_handle();
 	struct inode *inode = mapping->host;
@@ -1705,10 +1695,7 @@
 	unsigned from, to;
 	loff_t new_i_size;
 
-	trace_mark(ext4_journalled_write_end,
-		   "dev %s ino %lu pos %llu len %u copied %u",
-		   inode->i_sb->s_id, inode->i_ino,
-		   (unsigned long long) pos, len, copied);
+	trace_ext4_journalled_write_end(inode, pos, len, copied);
 	from = pos & (PAGE_CACHE_SIZE - 1);
 	to = from + len;
 
@@ -1747,7 +1734,7 @@
 		ret = ret2;
 	if (pos + len > inode->i_size) {
 		vmtruncate(inode, inode->i_size);
-		/* 
+		/*
 		 * If vmtruncate failed early the inode might still be
 		 * on the orphan list; we need to make sure the inode
 		 * is removed from the orphan list in that case.
@@ -1854,7 +1841,7 @@
 }
 
 static void ext4_da_page_release_reservation(struct page *page,
-						unsigned long offset)
+					     unsigned long offset)
 {
 	int to_release = 0;
 	struct buffer_head *head, *bh;
@@ -2554,9 +2541,7 @@
 	struct buffer_head *page_bufs;
 	struct inode *inode = page->mapping->host;
 
-	trace_mark(ext4_da_writepage,
-		   "dev %s ino %lu page_index %lu",
-		   inode->i_sb->s_id, inode->i_ino, page->index);
+	trace_ext4_da_writepage(inode, page);
 	size = i_size_read(inode);
 	if (page->index == size >> PAGE_CACHE_SHIFT)
 		len = size & ~PAGE_CACHE_MASK;
@@ -2667,19 +2652,7 @@
 	int needed_blocks, ret = 0, nr_to_writebump = 0;
 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
 
-	trace_mark(ext4_da_writepages,
-		   "dev %s ino %lu nr_t_write %ld "
-		   "pages_skipped %ld range_start %llu "
-		   "range_end %llu nonblocking %d "
-		   "for_kupdate %d for_reclaim %d "
-		   "for_writepages %d range_cyclic %d",
-		   inode->i_sb->s_id, inode->i_ino,
-		   wbc->nr_to_write, wbc->pages_skipped,
-		   (unsigned long long) wbc->range_start,
-		   (unsigned long long) wbc->range_end,
-		   wbc->nonblocking, wbc->for_kupdate,
-		   wbc->for_reclaim, wbc->for_writepages,
-		   wbc->range_cyclic);
+	trace_ext4_da_writepages(inode, wbc);
 
 	/*
 	 * No pages to write? This is mainly a kludge to avoid starting
@@ -2693,13 +2666,13 @@
 	 * If the filesystem has aborted, it is read-only, so return
 	 * right away instead of dumping stack traces later on that
 	 * will obscure the real source of the problem.  We test
-	 * EXT4_MOUNT_ABORT instead of sb->s_flag's MS_RDONLY because
+	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
 	 * the latter could be true if the filesystem is mounted
 	 * read-only, and in that case, ext4_da_writepages should
 	 * *never* be called, so if that ever happens, we would want
 	 * the stack trace.
 	 */
-	if (unlikely(sbi->s_mount_opt & EXT4_MOUNT_ABORT))
+	if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
 		return -EROFS;
 
 	/*
@@ -2845,14 +2818,7 @@
 	if (!no_nrwrite_index_update)
 		wbc->no_nrwrite_index_update = 0;
 	wbc->nr_to_write -= nr_to_writebump;
-	trace_mark(ext4_da_writepage_result,
-		   "dev %s ino %lu ret %d pages_written %d "
-		   "pages_skipped %ld congestion %d "
-		   "more_io %d no_nrwrite_index_update %d",
-		   inode->i_sb->s_id, inode->i_ino, ret,
-		   pages_written, wbc->pages_skipped,
-		   wbc->encountered_congestion, wbc->more_io,
-		   wbc->no_nrwrite_index_update);
+	trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
 	return ret;
 }
 
@@ -2884,8 +2850,8 @@
 }
 
 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
-				loff_t pos, unsigned len, unsigned flags,
-				struct page **pagep, void **fsdata)
+			       loff_t pos, unsigned len, unsigned flags,
+			       struct page **pagep, void **fsdata)
 {
 	int ret, retries = 0;
 	struct page *page;
@@ -2904,11 +2870,7 @@
 					len, flags, pagep, fsdata);
 	}
 	*fsdata = (void *)0;
-
-	trace_mark(ext4_da_write_begin,
-		   "dev %s ino %lu pos %llu len %u flags %u",
-		   inode->i_sb->s_id, inode->i_ino,
-		   (unsigned long long) pos, len, flags);
+	trace_ext4_da_write_begin(inode, pos, len, flags);
 retry:
 	/*
 	 * With delayed allocation, we don't log the i_disksize update
@@ -2959,7 +2921,7 @@
  * when write to the end of file but not require block allocation
  */
 static int ext4_da_should_update_i_disksize(struct page *page,
-					 unsigned long offset)
+					    unsigned long offset)
 {
 	struct buffer_head *bh;
 	struct inode *inode = page->mapping->host;
@@ -2978,9 +2940,9 @@
 }
 
 static int ext4_da_write_end(struct file *file,
-				struct address_space *mapping,
-				loff_t pos, unsigned len, unsigned copied,
-				struct page *page, void *fsdata)
+			     struct address_space *mapping,
+			     loff_t pos, unsigned len, unsigned copied,
+			     struct page *page, void *fsdata)
 {
 	struct inode *inode = mapping->host;
 	int ret = 0, ret2;
@@ -3001,10 +2963,7 @@
 		}
 	}
 
-	trace_mark(ext4_da_write_end,
-		   "dev %s ino %lu pos %llu len %u copied %u",
-		   inode->i_sb->s_id, inode->i_ino,
-		   (unsigned long long) pos, len, copied);
+	trace_ext4_da_write_end(inode, pos, len, copied);
 	start = pos & (PAGE_CACHE_SIZE - 1);
 	end = start + copied - 1;
 
@@ -3081,7 +3040,7 @@
 	 * not strictly speaking necessary (and for users of
 	 * laptop_mode, not even desirable).  However, to do otherwise
 	 * would require replicating code paths in:
-	 * 
+	 *
 	 * ext4_da_writepages() ->
 	 *    write_cache_pages() ---> (via passed in callback function)
 	 *        __mpage_da_writepage() -->
@@ -3101,7 +3060,7 @@
 	 * write out the pages, but rather only collect contiguous
 	 * logical block extents, call the multi-block allocator, and
 	 * then update the buffer heads with the block allocations.
-	 * 
+	 *
 	 * For now, though, we'll cheat by calling filemap_flush(),
 	 * which will map the blocks, and start the I/O, but not
 	 * actually wait for the I/O to complete.
@@ -3237,7 +3196,7 @@
  *
  */
 static int __ext4_normal_writepage(struct page *page,
-				struct writeback_control *wbc)
+				   struct writeback_control *wbc)
 {
 	struct inode *inode = page->mapping->host;
 
@@ -3249,15 +3208,13 @@
 }
 
 static int ext4_normal_writepage(struct page *page,
-				struct writeback_control *wbc)
+				 struct writeback_control *wbc)
 {
 	struct inode *inode = page->mapping->host;
 	loff_t size = i_size_read(inode);
 	loff_t len;
 
-	trace_mark(ext4_normal_writepage,
-		   "dev %s ino %lu page_index %lu",
-		   inode->i_sb->s_id, inode->i_ino, page->index);
+	trace_ext4_normal_writepage(inode, page);
 	J_ASSERT(PageLocked(page));
 	if (page->index == size >> PAGE_CACHE_SHIFT)
 		len = size & ~PAGE_CACHE_MASK;
@@ -3287,7 +3244,7 @@
 }
 
 static int __ext4_journalled_writepage(struct page *page,
-				struct writeback_control *wbc)
+				       struct writeback_control *wbc)
 {
 	struct address_space *mapping = page->mapping;
 	struct inode *inode = mapping->host;
@@ -3337,15 +3294,13 @@
 }
 
 static int ext4_journalled_writepage(struct page *page,
-				struct writeback_control *wbc)
+				     struct writeback_control *wbc)
 {
 	struct inode *inode = page->mapping->host;
 	loff_t size = i_size_read(inode);
 	loff_t len;
 
-	trace_mark(ext4_journalled_writepage,
-		   "dev %s ino %lu page_index %lu",
-		   inode->i_sb->s_id, inode->i_ino, page->index);
+	trace_ext4_journalled_writepage(inode, page);
 	J_ASSERT(PageLocked(page));
 	if (page->index == size >> PAGE_CACHE_SHIFT)
 		len = size & ~PAGE_CACHE_MASK;
@@ -3442,8 +3397,8 @@
  * VFS code falls back into buffered path in that case so we are safe.
  */
 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
-			const struct iovec *iov, loff_t offset,
-			unsigned long nr_segs)
+			      const struct iovec *iov, loff_t offset,
+			      unsigned long nr_segs)
 {
 	struct file *file = iocb->ki_filp;
 	struct inode *inode = file->f_mapping->host;
@@ -3763,7 +3718,8 @@
  *			(no partially truncated stuff there).  */
 
 static Indirect *ext4_find_shared(struct inode *inode, int depth,
-			ext4_lblk_t offsets[4], Indirect chain[4], __le32 *top)
+				  ext4_lblk_t offsets[4], Indirect chain[4],
+				  __le32 *top)
 {
 	Indirect *partial, *p;
 	int k, err;
@@ -3819,8 +3775,10 @@
  * than `count' because there can be holes in there.
  */
 static void ext4_clear_blocks(handle_t *handle, struct inode *inode,
-		struct buffer_head *bh, ext4_fsblk_t block_to_free,
-		unsigned long count, __le32 *first, __le32 *last)
+			      struct buffer_head *bh,
+			      ext4_fsblk_t block_to_free,
+			      unsigned long count, __le32 *first,
+			      __le32 *last)
 {
 	__le32 *p;
 	if (try_to_extend_transaction(handle, inode)) {
@@ -3837,10 +3795,11 @@
 	}
 
 	/*
-	 * Any buffers which are on the journal will be in memory. We find
-	 * them on the hash table so jbd2_journal_revoke() will run jbd2_journal_forget()
-	 * on them.  We've already detached each block from the file, so
-	 * bforget() in jbd2_journal_forget() should be safe.
+	 * Any buffers which are on the journal will be in memory. We
+	 * find them on the hash table so jbd2_journal_revoke() will
+	 * run jbd2_journal_forget() on them.  We've already detached
+	 * each block from the file, so bforget() in
+	 * jbd2_journal_forget() should be safe.
 	 *
 	 * AKPM: turn on bforget in jbd2_journal_forget()!!!
 	 */
@@ -4212,7 +4171,7 @@
 				   (__le32*)partial->bh->b_data+addr_per_block,
 				   (chain+n-1) - partial);
 		BUFFER_TRACE(partial->bh, "call brelse");
-		brelse (partial->bh);
+		brelse(partial->bh);
 		partial--;
 	}
 do_indirects:
@@ -4453,8 +4412,9 @@
 	if (flags & S_DIRSYNC)
 		ei->i_flags |= EXT4_DIRSYNC_FL;
 }
+
 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
-					struct ext4_inode_info *ei)
+				  struct ext4_inode_info *ei)
 {
 	blkcnt_t i_blocks ;
 	struct inode *inode = &(ei->vfs_inode);
@@ -4569,7 +4529,7 @@
 					EXT4_GOOD_OLD_INODE_SIZE +
 					ei->i_extra_isize;
 			if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
-				 ei->i_state |= EXT4_STATE_XATTR;
+				ei->i_state |= EXT4_STATE_XATTR;
 		}
 	} else
 		ei->i_extra_isize = 0;
@@ -4588,7 +4548,7 @@
 
 	ret = 0;
 	if (ei->i_file_acl &&
-	    ((ei->i_file_acl < 
+	    ((ei->i_file_acl <
 	      (le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block) +
 	       EXT4_SB(sb)->s_gdb_count)) ||
 	     (ei->i_file_acl >= ext4_blocks_count(EXT4_SB(sb)->s_es)))) {
@@ -4603,15 +4563,15 @@
 		     !ext4_inode_is_fast_symlink(inode)))
 			/* Validate extent which is part of inode */
 			ret = ext4_ext_check_inode(inode);
- 	} else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
+	} else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
 		   (S_ISLNK(inode->i_mode) &&
 		    !ext4_inode_is_fast_symlink(inode))) {
-	 	/* Validate block references which are part of inode */
+		/* Validate block references which are part of inode */
 		ret = ext4_check_inode_blockref(inode);
 	}
 	if (ret) {
- 		brelse(bh);
- 		goto bad_inode;
+		brelse(bh);
+		goto bad_inode;
 	}
 
 	if (S_ISREG(inode->i_mode)) {
@@ -4642,7 +4602,7 @@
 	} else {
 		brelse(bh);
 		ret = -EIO;
-		ext4_error(inode->i_sb, __func__, 
+		ext4_error(inode->i_sb, __func__,
 			   "bogus i_mode (%o) for inode=%lu",
 			   inode->i_mode, inode->i_ino);
 		goto bad_inode;
@@ -4795,8 +4755,9 @@
 				cpu_to_le32(new_encode_dev(inode->i_rdev));
 			raw_inode->i_block[2] = 0;
 		}
-	} else for (block = 0; block < EXT4_N_BLOCKS; block++)
-		raw_inode->i_block[block] = ei->i_data[block];
+	} else
+		for (block = 0; block < EXT4_N_BLOCKS; block++)
+			raw_inode->i_block[block] = ei->i_data[block];
 
 	raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
 	if (ei->i_extra_isize) {
@@ -5150,7 +5111,7 @@
  * Give this, we know that the caller already has write access to iloc->bh.
  */
 int ext4_mark_iloc_dirty(handle_t *handle,
-		struct inode *inode, struct ext4_iloc *iloc)
+			 struct inode *inode, struct ext4_iloc *iloc)
 {
 	int err = 0;
 
diff --git a/fs/ext4/ioctl.c b/fs/ext4/ioctl.c
index 91e75f7..bb415408 100644
--- a/fs/ext4/ioctl.c
+++ b/fs/ext4/ioctl.c
@@ -14,6 +14,7 @@
 #include <linux/compat.h>
 #include <linux/smp_lock.h>
 #include <linux/mount.h>
+#include <linux/file.h>
 #include <asm/uaccess.h>
 #include "ext4_jbd2.h"
 #include "ext4.h"
@@ -213,6 +214,41 @@
 
 		return err;
 	}
+
+	case EXT4_IOC_MOVE_EXT: {
+		struct move_extent me;
+		struct file *donor_filp;
+		int err;
+
+		if (copy_from_user(&me,
+			(struct move_extent __user *)arg, sizeof(me)))
+			return -EFAULT;
+
+		donor_filp = fget(me.donor_fd);
+		if (!donor_filp)
+			return -EBADF;
+
+		if (!capable(CAP_DAC_OVERRIDE)) {
+			if ((current->real_cred->fsuid != inode->i_uid) ||
+				!(inode->i_mode & S_IRUSR) ||
+				!(donor_filp->f_dentry->d_inode->i_mode &
+				S_IRUSR)) {
+				fput(donor_filp);
+				return -EACCES;
+			}
+		}
+
+		err = ext4_move_extents(filp, donor_filp, me.orig_start,
+					me.donor_start, me.len, &me.moved_len);
+		fput(donor_filp);
+
+		if (!err)
+			if (copy_to_user((struct move_extent *)arg,
+				&me, sizeof(me)))
+				return -EFAULT;
+		return err;
+	}
+
 	case EXT4_IOC_GROUP_ADD: {
 		struct ext4_new_group_data input;
 		struct super_block *sb = inode->i_sb;
diff --git a/fs/ext4/mballoc.c b/fs/ext4/mballoc.c
index ed8482e..519a0a6 100644
--- a/fs/ext4/mballoc.c
+++ b/fs/ext4/mballoc.c
@@ -22,6 +22,8 @@
  */
 
 #include "mballoc.h"
+#include <trace/events/ext4.h>
+
 /*
  * MUSTDO:
  *   - test ext4_ext_search_left() and ext4_ext_search_right()
@@ -340,8 +342,6 @@
 						ext4_group_t group);
 static void release_blocks_on_commit(journal_t *journal, transaction_t *txn);
 
-
-
 static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
 {
 #if BITS_PER_LONG == 64
@@ -2859,9 +2859,8 @@
 		discard_block = (ext4_fsblk_t) entry->group * EXT4_BLOCKS_PER_GROUP(sb)
 			+ entry->start_blk
 			+ le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
-		trace_mark(ext4_discard_blocks, "dev %s blk %llu count %u",
-			   sb->s_id, (unsigned long long) discard_block,
-			   entry->count);
+		trace_ext4_discard_blocks(sb, (unsigned long long)discard_block,
+					  entry->count);
 		sb_issue_discard(sb, discard_block, entry->count);
 
 		kmem_cache_free(ext4_free_ext_cachep, entry);
@@ -3629,10 +3628,7 @@
 
 	mb_debug("new inode pa %p: %llu/%u for %u\n", pa,
 			pa->pa_pstart, pa->pa_len, pa->pa_lstart);
-	trace_mark(ext4_mb_new_inode_pa,
-		   "dev %s ino %lu pstart %llu len %u lstart %u",
-		   sb->s_id, ac->ac_inode->i_ino,
-		   pa->pa_pstart, pa->pa_len, pa->pa_lstart);
+	trace_ext4_mb_new_inode_pa(ac, pa);
 
 	ext4_mb_use_inode_pa(ac, pa);
 	atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
@@ -3691,9 +3687,8 @@
 	pa->pa_type = MB_GROUP_PA;
 
 	mb_debug("new group pa %p: %llu/%u for %u\n", pa,
-		 pa->pa_pstart, pa->pa_len, pa->pa_lstart);
-	trace_mark(ext4_mb_new_group_pa, "dev %s pstart %llu len %u lstart %u",
-		   sb->s_id, pa->pa_pstart, pa->pa_len, pa->pa_lstart);
+			pa->pa_pstart, pa->pa_len, pa->pa_lstart);
+	trace_ext4_mb_new_group_pa(ac, pa);
 
 	ext4_mb_use_group_pa(ac, pa);
 	atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
@@ -3783,10 +3778,8 @@
 			ext4_mb_store_history(ac);
 		}
 
-		trace_mark(ext4_mb_release_inode_pa,
-			   "dev %s ino %lu block %llu count %u",
-			   sb->s_id, pa->pa_inode->i_ino, grp_blk_start + bit,
-			   next - bit);
+		trace_ext4_mb_release_inode_pa(ac, pa, grp_blk_start + bit,
+					       next - bit);
 		mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
 		bit = next + 1;
 	}
@@ -3820,8 +3813,7 @@
 	if (ac)
 		ac->ac_op = EXT4_MB_HISTORY_DISCARD;
 
-	trace_mark(ext4_mb_release_group_pa, "dev %s pstart %llu len %d",
-		   sb->s_id, pa->pa_pstart, pa->pa_len);
+	trace_ext4_mb_release_group_pa(ac, pa);
 	BUG_ON(pa->pa_deleted == 0);
 	ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
 	BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
@@ -3889,6 +3881,8 @@
 
 	INIT_LIST_HEAD(&list);
 	ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
+	if (ac)
+		ac->ac_sb = sb;
 repeat:
 	ext4_lock_group(sb, group);
 	list_for_each_entry_safe(pa, tmp,
@@ -3987,12 +3981,15 @@
 	}
 
 	mb_debug("discard preallocation for inode %lu\n", inode->i_ino);
-	trace_mark(ext4_discard_preallocations, "dev %s ino %lu", sb->s_id,
-		   inode->i_ino);
+	trace_ext4_discard_preallocations(inode);
 
 	INIT_LIST_HEAD(&list);
 
 	ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
+	if (ac) {
+		ac->ac_sb = sb;
+		ac->ac_inode = inode;
+	}
 repeat:
 	/* first, collect all pa's in the inode */
 	spin_lock(&ei->i_prealloc_lock);
@@ -4276,6 +4273,8 @@
 
 	INIT_LIST_HEAD(&discard_list);
 	ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
+	if (ac)
+		ac->ac_sb = sb;
 
 	spin_lock(&lg->lg_prealloc_lock);
 	list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
@@ -4445,8 +4444,7 @@
 	int ret;
 	int freed = 0;
 
-	trace_mark(ext4_mb_discard_preallocations, "dev %s needed %d",
-		   sb->s_id, needed);
+	trace_ext4_mb_discard_preallocations(sb, needed);
 	for (i = 0; i < ngroups && needed > 0; i++) {
 		ret = ext4_mb_discard_group_preallocations(sb, i, needed);
 		freed += ret;
@@ -4475,17 +4473,7 @@
 	sb = ar->inode->i_sb;
 	sbi = EXT4_SB(sb);
 
-	trace_mark(ext4_request_blocks, "dev %s flags %u len %u ino %lu "
-		   "lblk %llu goal %llu lleft %llu lright %llu "
-		   "pleft %llu pright %llu ",
-		   sb->s_id, ar->flags, ar->len,
-		   ar->inode ? ar->inode->i_ino : 0,
-		   (unsigned long long) ar->logical,
-		   (unsigned long long) ar->goal,
-		   (unsigned long long) ar->lleft,
-		   (unsigned long long) ar->lright,
-		   (unsigned long long) ar->pleft,
-		   (unsigned long long) ar->pright);
+	trace_ext4_request_blocks(ar);
 
 	/*
 	 * For delayed allocation, we could skip the ENOSPC and
@@ -4521,7 +4509,10 @@
 	}
 
 	ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
-	if (!ac) {
+	if (ac) {
+		ac->ac_sb = sb;
+		ac->ac_inode = ar->inode;
+	} else {
 		ar->len = 0;
 		*errp = -ENOMEM;
 		goto out1;
@@ -4594,18 +4585,7 @@
 						reserv_blks);
 	}
 
-	trace_mark(ext4_allocate_blocks,
-		   "dev %s block %llu flags %u len %u ino %lu "
-		   "logical %llu goal %llu lleft %llu lright %llu "
-		   "pleft %llu pright %llu ",
-		   sb->s_id, (unsigned long long) block,
-		   ar->flags, ar->len, ar->inode ? ar->inode->i_ino : 0,
-		   (unsigned long long) ar->logical,
-		   (unsigned long long) ar->goal,
-		   (unsigned long long) ar->lleft,
-		   (unsigned long long) ar->lright,
-		   (unsigned long long) ar->pleft,
-		   (unsigned long long) ar->pright);
+	trace_ext4_allocate_blocks(ar, (unsigned long long)block);
 
 	return block;
 }
@@ -4709,7 +4689,7 @@
  * Main entry point into mballoc to free blocks
  */
 void ext4_mb_free_blocks(handle_t *handle, struct inode *inode,
-			unsigned long block, unsigned long count,
+			ext4_fsblk_t block, unsigned long count,
 			int metadata, unsigned long *freed)
 {
 	struct buffer_head *bitmap_bh = NULL;
@@ -4735,15 +4715,12 @@
 	    block + count > ext4_blocks_count(es)) {
 		ext4_error(sb, __func__,
 			    "Freeing blocks not in datazone - "
-			    "block = %lu, count = %lu", block, count);
+			    "block = %llu, count = %lu", block, count);
 		goto error_return;
 	}
 
-	ext4_debug("freeing block %lu\n", block);
-	trace_mark(ext4_free_blocks,
-		   "dev %s block %llu count %lu metadata %d ino %lu",
-		   sb->s_id, (unsigned long long) block, count, metadata,
-		   inode ? inode->i_ino : 0);
+	ext4_debug("freeing block %llu\n", block);
+	trace_ext4_free_blocks(inode, block, count, metadata);
 
 	ac = kmem_cache_alloc(ext4_ac_cachep, GFP_NOFS);
 	if (ac) {
@@ -4784,7 +4761,7 @@
 
 		ext4_error(sb, __func__,
 			   "Freeing blocks in system zone - "
-			   "Block = %lu, count = %lu", block, count);
+			   "Block = %llu, count = %lu", block, count);
 		/* err = 0. ext4_std_error should be a no op */
 		goto error_return;
 	}
diff --git a/fs/ext4/mballoc.h b/fs/ext4/mballoc.h
index 75e34f6..c96bb19 100644
--- a/fs/ext4/mballoc.h
+++ b/fs/ext4/mballoc.h
@@ -19,7 +19,6 @@
 #include <linux/seq_file.h>
 #include <linux/version.h>
 #include <linux/blkdev.h>
-#include <linux/marker.h>
 #include <linux/mutex.h>
 #include "ext4_jbd2.h"
 #include "ext4.h"
diff --git a/fs/ext4/migrate.c b/fs/ext4/migrate.c
index fe64d9f..313a50b 100644
--- a/fs/ext4/migrate.c
+++ b/fs/ext4/migrate.c
@@ -458,6 +458,7 @@
 	struct inode *tmp_inode = NULL;
 	struct list_blocks_struct lb;
 	unsigned long max_entries;
+	__u32 goal;
 
 	/*
 	 * If the filesystem does not support extents, or the inode
@@ -483,9 +484,10 @@
 		retval = PTR_ERR(handle);
 		return retval;
 	}
-	tmp_inode = ext4_new_inode(handle,
-				inode->i_sb->s_root->d_inode,
-				S_IFREG);
+	goal = (((inode->i_ino - 1) / EXT4_INODES_PER_GROUP(inode->i_sb)) *
+		EXT4_INODES_PER_GROUP(inode->i_sb)) + 1;
+	tmp_inode = ext4_new_inode(handle, inode->i_sb->s_root->d_inode,
+				   S_IFREG, 0, goal);
 	if (IS_ERR(tmp_inode)) {
 		retval = -ENOMEM;
 		ext4_journal_stop(handle);
diff --git a/fs/ext4/move_extent.c b/fs/ext4/move_extent.c
new file mode 100644
index 0000000..bbf2dd9
--- /dev/null
+++ b/fs/ext4/move_extent.c
@@ -0,0 +1,1320 @@
+/*
+ * Copyright (c) 2008,2009 NEC Software Tohoku, Ltd.
+ * Written by Takashi Sato <t-sato@yk.jp.nec.com>
+ *            Akira Fujita <a-fujita@rs.jp.nec.com>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2.1 of the GNU Lesser General Public License
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ */
+
+#include <linux/fs.h>
+#include <linux/quotaops.h>
+#include "ext4_jbd2.h"
+#include "ext4_extents.h"
+#include "ext4.h"
+
+#define get_ext_path(path, inode, block, ret)		\
+	do {								\
+		path = ext4_ext_find_extent(inode, block, path);	\
+		if (IS_ERR(path)) {					\
+			ret = PTR_ERR(path);				\
+			path = NULL;					\
+		}							\
+	} while (0)
+
+/**
+ * copy_extent_status - Copy the extent's initialization status
+ *
+ * @src:	an extent for getting initialize status
+ * @dest:	an extent to be set the status
+ */
+static void
+copy_extent_status(struct ext4_extent *src, struct ext4_extent *dest)
+{
+	if (ext4_ext_is_uninitialized(src))
+		ext4_ext_mark_uninitialized(dest);
+	else
+		dest->ee_len = cpu_to_le16(ext4_ext_get_actual_len(dest));
+}
+
+/**
+ * mext_next_extent - Search for the next extent and set it to "extent"
+ *
+ * @inode:	inode which is searched
+ * @path:	this will obtain data for the next extent
+ * @extent:	pointer to the next extent we have just gotten
+ *
+ * Search the next extent in the array of ext4_ext_path structure (@path)
+ * and set it to ext4_extent structure (@extent). In addition, the member of
+ * @path (->p_ext) also points the next extent. Return 0 on success, 1 if
+ * ext4_ext_path structure refers to the last extent, or a negative error
+ * value on failure.
+ */
+static int
+mext_next_extent(struct inode *inode, struct ext4_ext_path *path,
+		      struct ext4_extent **extent)
+{
+	int ppos, leaf_ppos = path->p_depth;
+
+	ppos = leaf_ppos;
+	if (EXT_LAST_EXTENT(path[ppos].p_hdr) > path[ppos].p_ext) {
+		/* leaf block */
+		*extent = ++path[ppos].p_ext;
+		return 0;
+	}
+
+	while (--ppos >= 0) {
+		if (EXT_LAST_INDEX(path[ppos].p_hdr) >
+		    path[ppos].p_idx) {
+			int cur_ppos = ppos;
+
+			/* index block */
+			path[ppos].p_idx++;
+			path[ppos].p_block = idx_pblock(path[ppos].p_idx);
+			if (path[ppos+1].p_bh)
+				brelse(path[ppos+1].p_bh);
+			path[ppos+1].p_bh =
+				sb_bread(inode->i_sb, path[ppos].p_block);
+			if (!path[ppos+1].p_bh)
+				return -EIO;
+			path[ppos+1].p_hdr =
+				ext_block_hdr(path[ppos+1].p_bh);
+
+			/* Halfway index block */
+			while (++cur_ppos < leaf_ppos) {
+				path[cur_ppos].p_idx =
+					EXT_FIRST_INDEX(path[cur_ppos].p_hdr);
+				path[cur_ppos].p_block =
+					idx_pblock(path[cur_ppos].p_idx);
+				if (path[cur_ppos+1].p_bh)
+					brelse(path[cur_ppos+1].p_bh);
+				path[cur_ppos+1].p_bh = sb_bread(inode->i_sb,
+					path[cur_ppos].p_block);
+				if (!path[cur_ppos+1].p_bh)
+					return -EIO;
+				path[cur_ppos+1].p_hdr =
+					ext_block_hdr(path[cur_ppos+1].p_bh);
+			}
+
+			/* leaf block */
+			path[leaf_ppos].p_ext = *extent =
+				EXT_FIRST_EXTENT(path[leaf_ppos].p_hdr);
+			return 0;
+		}
+	}
+	/* We found the last extent */
+	return 1;
+}
+
+/**
+ * mext_double_down_read - Acquire two inodes' read semaphore
+ *
+ * @orig_inode:		original inode structure
+ * @donor_inode:	donor inode structure
+ * Acquire read semaphore of the two inodes (orig and donor) by i_ino order.
+ */
+static void
+mext_double_down_read(struct inode *orig_inode, struct inode *donor_inode)
+{
+	struct inode *first = orig_inode, *second = donor_inode;
+
+	BUG_ON(orig_inode == NULL || donor_inode == NULL);
+
+	/*
+	 * Use the inode number to provide the stable locking order instead
+	 * of its address, because the C language doesn't guarantee you can
+	 * compare pointers that don't come from the same array.
+	 */
+	if (donor_inode->i_ino < orig_inode->i_ino) {
+		first = donor_inode;
+		second = orig_inode;
+	}
+
+	down_read(&EXT4_I(first)->i_data_sem);
+	down_read(&EXT4_I(second)->i_data_sem);
+}
+
+/**
+ * mext_double_down_write - Acquire two inodes' write semaphore
+ *
+ * @orig_inode:		original inode structure
+ * @donor_inode:	donor inode structure
+ * Acquire write semaphore of the two inodes (orig and donor) by i_ino order.
+ */
+static void
+mext_double_down_write(struct inode *orig_inode, struct inode *donor_inode)
+{
+	struct inode *first = orig_inode, *second = donor_inode;
+
+	BUG_ON(orig_inode == NULL || donor_inode == NULL);
+
+	/*
+	 * Use the inode number to provide the stable locking order instead
+	 * of its address, because the C language doesn't guarantee you can
+	 * compare pointers that don't come from the same array.
+	 */
+	if (donor_inode->i_ino < orig_inode->i_ino) {
+		first = donor_inode;
+		second = orig_inode;
+	}
+
+	down_write(&EXT4_I(first)->i_data_sem);
+	down_write(&EXT4_I(second)->i_data_sem);
+}
+
+/**
+ * mext_double_up_read - Release two inodes' read semaphore
+ *
+ * @orig_inode:		original inode structure to be released its lock first
+ * @donor_inode:	donor inode structure to be released its lock second
+ * Release read semaphore of two inodes (orig and donor).
+ */
+static void
+mext_double_up_read(struct inode *orig_inode, struct inode *donor_inode)
+{
+	BUG_ON(orig_inode == NULL || donor_inode == NULL);
+
+	up_read(&EXT4_I(orig_inode)->i_data_sem);
+	up_read(&EXT4_I(donor_inode)->i_data_sem);
+}
+
+/**
+ * mext_double_up_write - Release two inodes' write semaphore
+ *
+ * @orig_inode:		original inode structure to be released its lock first
+ * @donor_inode:	donor inode structure to be released its lock second
+ * Release write semaphore of two inodes (orig and donor).
+ */
+static void
+mext_double_up_write(struct inode *orig_inode, struct inode *donor_inode)
+{
+	BUG_ON(orig_inode == NULL || donor_inode == NULL);
+
+	up_write(&EXT4_I(orig_inode)->i_data_sem);
+	up_write(&EXT4_I(donor_inode)->i_data_sem);
+}
+
+/**
+ * mext_insert_across_blocks - Insert extents across leaf block
+ *
+ * @handle:		journal handle
+ * @orig_inode:		original inode
+ * @o_start:		first original extent to be changed
+ * @o_end:		last original extent to be changed
+ * @start_ext:		first new extent to be inserted
+ * @new_ext:		middle of new extent to be inserted
+ * @end_ext:		last new extent to be inserted
+ *
+ * Allocate a new leaf block and insert extents into it. Return 0 on success,
+ * or a negative error value on failure.
+ */
+static int
+mext_insert_across_blocks(handle_t *handle, struct inode *orig_inode,
+		struct ext4_extent *o_start, struct ext4_extent *o_end,
+		struct ext4_extent *start_ext, struct ext4_extent *new_ext,
+		struct ext4_extent *end_ext)
+{
+	struct ext4_ext_path *orig_path = NULL;
+	ext4_lblk_t eblock = 0;
+	int new_flag = 0;
+	int end_flag = 0;
+	int err = 0;
+
+	if (start_ext->ee_len && new_ext->ee_len && end_ext->ee_len) {
+		if (o_start == o_end) {
+
+			/*       start_ext   new_ext    end_ext
+			 * donor |---------|-----------|--------|
+			 * orig  |------------------------------|
+			 */
+			end_flag = 1;
+		} else {
+
+			/*       start_ext   new_ext   end_ext
+			 * donor |---------|----------|---------|
+			 * orig  |---------------|--------------|
+			 */
+			o_end->ee_block = end_ext->ee_block;
+			o_end->ee_len = end_ext->ee_len;
+			ext4_ext_store_pblock(o_end, ext_pblock(end_ext));
+		}
+
+		o_start->ee_len = start_ext->ee_len;
+		new_flag = 1;
+
+	} else if (start_ext->ee_len && new_ext->ee_len &&
+		   !end_ext->ee_len && o_start == o_end) {
+
+		/*	 start_ext	new_ext
+		 * donor |--------------|---------------|
+		 * orig  |------------------------------|
+		 */
+		o_start->ee_len = start_ext->ee_len;
+		new_flag = 1;
+
+	} else if (!start_ext->ee_len && new_ext->ee_len &&
+		   end_ext->ee_len && o_start == o_end) {
+
+		/*	  new_ext	end_ext
+		 * donor |--------------|---------------|
+		 * orig  |------------------------------|
+		 */
+		o_end->ee_block = end_ext->ee_block;
+		o_end->ee_len = end_ext->ee_len;
+		ext4_ext_store_pblock(o_end, ext_pblock(end_ext));
+
+		/*
+		 * Set 0 to the extent block if new_ext was
+		 * the first block.
+		 */
+		if (new_ext->ee_block)
+			eblock = le32_to_cpu(new_ext->ee_block);
+
+		new_flag = 1;
+	} else {
+		ext4_debug("ext4 move extent: Unexpected insert case\n");
+		return -EIO;
+	}
+
+	if (new_flag) {
+		get_ext_path(orig_path, orig_inode, eblock, err);
+		if (orig_path == NULL)
+			goto out;
+
+		if (ext4_ext_insert_extent(handle, orig_inode,
+					orig_path, new_ext))
+			goto out;
+	}
+
+	if (end_flag) {
+		get_ext_path(orig_path, orig_inode,
+				      le32_to_cpu(end_ext->ee_block) - 1, err);
+		if (orig_path == NULL)
+			goto out;
+
+		if (ext4_ext_insert_extent(handle, orig_inode,
+					   orig_path, end_ext))
+			goto out;
+	}
+out:
+	if (orig_path) {
+		ext4_ext_drop_refs(orig_path);
+		kfree(orig_path);
+	}
+
+	return err;
+
+}
+
+/**
+ * mext_insert_inside_block - Insert new extent to the extent block
+ *
+ * @o_start:		first original extent to be moved
+ * @o_end:		last original extent to be moved
+ * @start_ext:		first new extent to be inserted
+ * @new_ext:		middle of new extent to be inserted
+ * @end_ext:		last new extent to be inserted
+ * @eh:			extent header of target leaf block
+ * @range_to_move:	used to decide how to insert extent
+ *
+ * Insert extents into the leaf block. The extent (@o_start) is overwritten
+ * by inserted extents.
+ */
+static void
+mext_insert_inside_block(struct ext4_extent *o_start,
+			      struct ext4_extent *o_end,
+			      struct ext4_extent *start_ext,
+			      struct ext4_extent *new_ext,
+			      struct ext4_extent *end_ext,
+			      struct ext4_extent_header *eh,
+			      int range_to_move)
+{
+	int i = 0;
+	unsigned long len;
+
+	/* Move the existing extents */
+	if (range_to_move && o_end < EXT_LAST_EXTENT(eh)) {
+		len = (unsigned long)(EXT_LAST_EXTENT(eh) + 1) -
+			(unsigned long)(o_end + 1);
+		memmove(o_end + 1 + range_to_move, o_end + 1, len);
+	}
+
+	/* Insert start entry */
+	if (start_ext->ee_len)
+		o_start[i++].ee_len = start_ext->ee_len;
+
+	/* Insert new entry */
+	if (new_ext->ee_len) {
+		o_start[i] = *new_ext;
+		ext4_ext_store_pblock(&o_start[i++], ext_pblock(new_ext));
+	}
+
+	/* Insert end entry */
+	if (end_ext->ee_len)
+		o_start[i] = *end_ext;
+
+	/* Increment the total entries counter on the extent block */
+	le16_add_cpu(&eh->eh_entries, range_to_move);
+}
+
+/**
+ * mext_insert_extents - Insert new extent
+ *
+ * @handle:	journal handle
+ * @orig_inode:	original inode
+ * @orig_path:	path indicates first extent to be changed
+ * @o_start:	first original extent to be changed
+ * @o_end:	last original extent to be changed
+ * @start_ext:	first new extent to be inserted
+ * @new_ext:	middle of new extent to be inserted
+ * @end_ext:	last new extent to be inserted
+ *
+ * Call the function to insert extents. If we cannot add more extents into
+ * the leaf block, we call mext_insert_across_blocks() to create a
+ * new leaf block. Otherwise call mext_insert_inside_block(). Return 0
+ * on success, or a negative error value on failure.
+ */
+static int
+mext_insert_extents(handle_t *handle, struct inode *orig_inode,
+			 struct ext4_ext_path *orig_path,
+			 struct ext4_extent *o_start,
+			 struct ext4_extent *o_end,
+			 struct ext4_extent *start_ext,
+			 struct ext4_extent *new_ext,
+			 struct ext4_extent *end_ext)
+{
+	struct  ext4_extent_header *eh;
+	unsigned long need_slots, slots_range;
+	int	range_to_move, depth, ret;
+
+	/*
+	 * The extents need to be inserted
+	 * start_extent + new_extent + end_extent.
+	 */
+	need_slots = (start_ext->ee_len ? 1 : 0) + (end_ext->ee_len ? 1 : 0) +
+		(new_ext->ee_len ? 1 : 0);
+
+	/* The number of slots between start and end */
+	slots_range = ((unsigned long)(o_end + 1) - (unsigned long)o_start + 1)
+		/ sizeof(struct ext4_extent);
+
+	/* Range to move the end of extent */
+	range_to_move = need_slots - slots_range;
+	depth = orig_path->p_depth;
+	orig_path += depth;
+	eh = orig_path->p_hdr;
+
+	if (depth) {
+		/* Register to journal */
+		ret = ext4_journal_get_write_access(handle, orig_path->p_bh);
+		if (ret)
+			return ret;
+	}
+
+	/* Expansion */
+	if (range_to_move > 0 &&
+		(range_to_move > le16_to_cpu(eh->eh_max)
+			- le16_to_cpu(eh->eh_entries))) {
+
+		ret = mext_insert_across_blocks(handle, orig_inode, o_start,
+					o_end, start_ext, new_ext, end_ext);
+		if (ret < 0)
+			return ret;
+	} else
+		mext_insert_inside_block(o_start, o_end, start_ext, new_ext,
+						end_ext, eh, range_to_move);
+
+	if (depth) {
+		ret = ext4_handle_dirty_metadata(handle, orig_inode,
+						 orig_path->p_bh);
+		if (ret)
+			return ret;
+	} else {
+		ret = ext4_mark_inode_dirty(handle, orig_inode);
+		if (ret < 0)
+			return ret;
+	}
+
+	return 0;
+}
+
+/**
+ * mext_leaf_block - Move one leaf extent block into the inode.
+ *
+ * @handle:		journal handle
+ * @orig_inode:		original inode
+ * @orig_path:		path indicates first extent to be changed
+ * @dext:		donor extent
+ * @from:		start offset on the target file
+ *
+ * In order to insert extents into the leaf block, we must divide the extent
+ * in the leaf block into three extents. The one is located to be inserted
+ * extents, and the others are located around it.
+ *
+ * Therefore, this function creates structures to save extents of the leaf
+ * block, and inserts extents by calling mext_insert_extents() with
+ * created extents. Return 0 on success, or a negative error value on failure.
+ */
+static int
+mext_leaf_block(handle_t *handle, struct inode *orig_inode,
+		     struct ext4_ext_path *orig_path, struct ext4_extent *dext,
+		     ext4_lblk_t *from)
+{
+	struct ext4_extent *oext, *o_start, *o_end, *prev_ext;
+	struct ext4_extent new_ext, start_ext, end_ext;
+	ext4_lblk_t new_ext_end;
+	ext4_fsblk_t new_phys_end;
+	int oext_alen, new_ext_alen, end_ext_alen;
+	int depth = ext_depth(orig_inode);
+	int ret;
+
+	o_start = o_end = oext = orig_path[depth].p_ext;
+	oext_alen = ext4_ext_get_actual_len(oext);
+	start_ext.ee_len = end_ext.ee_len = 0;
+
+	new_ext.ee_block = cpu_to_le32(*from);
+	ext4_ext_store_pblock(&new_ext, ext_pblock(dext));
+	new_ext.ee_len = dext->ee_len;
+	new_ext_alen = ext4_ext_get_actual_len(&new_ext);
+	new_ext_end = le32_to_cpu(new_ext.ee_block) + new_ext_alen - 1;
+	new_phys_end = ext_pblock(&new_ext) + new_ext_alen - 1;
+
+	/*
+	 * Case: original extent is first
+	 * oext      |--------|
+	 * new_ext      |--|
+	 * start_ext |--|
+	 */
+	if (le32_to_cpu(oext->ee_block) < le32_to_cpu(new_ext.ee_block) &&
+		le32_to_cpu(new_ext.ee_block) <
+		le32_to_cpu(oext->ee_block) + oext_alen) {
+		start_ext.ee_len = cpu_to_le16(le32_to_cpu(new_ext.ee_block) -
+					       le32_to_cpu(oext->ee_block));
+		copy_extent_status(oext, &start_ext);
+	} else if (oext > EXT_FIRST_EXTENT(orig_path[depth].p_hdr)) {
+		prev_ext = oext - 1;
+		/*
+		 * We can merge new_ext into previous extent,
+		 * if these are contiguous and same extent type.
+		 */
+		if (ext4_can_extents_be_merged(orig_inode, prev_ext,
+					       &new_ext)) {
+			o_start = prev_ext;
+			start_ext.ee_len = cpu_to_le16(
+				ext4_ext_get_actual_len(prev_ext) +
+				new_ext_alen);
+			copy_extent_status(prev_ext, &start_ext);
+			new_ext.ee_len = 0;
+		}
+	}
+
+	/*
+	 * Case: new_ext_end must be less than oext
+	 * oext      |-----------|
+	 * new_ext       |-------|
+	 */
+	BUG_ON(le32_to_cpu(oext->ee_block) + oext_alen - 1 < new_ext_end);
+
+	/*
+	 * Case: new_ext is smaller than original extent
+	 * oext    |---------------|
+	 * new_ext |-----------|
+	 * end_ext             |---|
+	 */
+	if (le32_to_cpu(oext->ee_block) <= new_ext_end &&
+		new_ext_end < le32_to_cpu(oext->ee_block) + oext_alen - 1) {
+		end_ext.ee_len =
+			cpu_to_le16(le32_to_cpu(oext->ee_block) +
+			oext_alen - 1 - new_ext_end);
+		copy_extent_status(oext, &end_ext);
+		end_ext_alen = ext4_ext_get_actual_len(&end_ext);
+		ext4_ext_store_pblock(&end_ext,
+			(ext_pblock(o_end) + oext_alen - end_ext_alen));
+		end_ext.ee_block =
+			cpu_to_le32(le32_to_cpu(o_end->ee_block) +
+			oext_alen - end_ext_alen);
+	}
+
+	ret = mext_insert_extents(handle, orig_inode, orig_path, o_start,
+				o_end, &start_ext, &new_ext, &end_ext);
+	return ret;
+}
+
+/**
+ * mext_calc_swap_extents - Calculate extents for extent swapping.
+ *
+ * @tmp_dext:		the extent that will belong to the original inode
+ * @tmp_oext:		the extent that will belong to the donor inode
+ * @orig_off:		block offset of original inode
+ * @donor_off:		block offset of donor inode
+ * @max_count:		the maximun length of extents
+ */
+static void
+mext_calc_swap_extents(struct ext4_extent *tmp_dext,
+			      struct ext4_extent *tmp_oext,
+			      ext4_lblk_t orig_off, ext4_lblk_t donor_off,
+			      ext4_lblk_t max_count)
+{
+	ext4_lblk_t diff, orig_diff;
+	struct ext4_extent dext_old, oext_old;
+
+	dext_old = *tmp_dext;
+	oext_old = *tmp_oext;
+
+	/* When tmp_dext is too large, pick up the target range. */
+	diff = donor_off - le32_to_cpu(tmp_dext->ee_block);
+
+	ext4_ext_store_pblock(tmp_dext, ext_pblock(tmp_dext) + diff);
+	tmp_dext->ee_block =
+			cpu_to_le32(le32_to_cpu(tmp_dext->ee_block) + diff);
+	tmp_dext->ee_len = cpu_to_le16(le16_to_cpu(tmp_dext->ee_len) - diff);
+
+	if (max_count < ext4_ext_get_actual_len(tmp_dext))
+		tmp_dext->ee_len = cpu_to_le16(max_count);
+
+	orig_diff = orig_off - le32_to_cpu(tmp_oext->ee_block);
+	ext4_ext_store_pblock(tmp_oext, ext_pblock(tmp_oext) + orig_diff);
+
+	/* Adjust extent length if donor extent is larger than orig */
+	if (ext4_ext_get_actual_len(tmp_dext) >
+	    ext4_ext_get_actual_len(tmp_oext) - orig_diff)
+		tmp_dext->ee_len = cpu_to_le16(le16_to_cpu(tmp_oext->ee_len) -
+						orig_diff);
+
+	tmp_oext->ee_len = cpu_to_le16(ext4_ext_get_actual_len(tmp_dext));
+
+	copy_extent_status(&oext_old, tmp_dext);
+	copy_extent_status(&dext_old, tmp_oext);
+}
+
+/**
+ * mext_replace_branches - Replace original extents with new extents
+ *
+ * @handle:		journal handle
+ * @orig_inode:		original inode
+ * @donor_inode:	donor inode
+ * @from:		block offset of orig_inode
+ * @count:		block count to be replaced
+ *
+ * Replace original inode extents and donor inode extents page by page.
+ * We implement this replacement in the following three steps:
+ * 1. Save the block information of original and donor inodes into
+ *    dummy extents.
+ * 2. Change the block information of original inode to point at the
+ *    donor inode blocks.
+ * 3. Change the block information of donor inode to point at the saved
+ *    original inode blocks in the dummy extents.
+ *
+ * Return 0 on success, or a negative error value on failure.
+ */
+static int
+mext_replace_branches(handle_t *handle, struct inode *orig_inode,
+			   struct inode *donor_inode, ext4_lblk_t from,
+			   ext4_lblk_t count)
+{
+	struct ext4_ext_path *orig_path = NULL;
+	struct ext4_ext_path *donor_path = NULL;
+	struct ext4_extent *oext, *dext;
+	struct ext4_extent tmp_dext, tmp_oext;
+	ext4_lblk_t orig_off = from, donor_off = from;
+	int err = 0;
+	int depth;
+	int replaced_count = 0;
+	int dext_alen;
+
+	mext_double_down_write(orig_inode, donor_inode);
+
+	/* Get the original extent for the block "orig_off" */
+	get_ext_path(orig_path, orig_inode, orig_off, err);
+	if (orig_path == NULL)
+		goto out;
+
+	/* Get the donor extent for the head */
+	get_ext_path(donor_path, donor_inode, donor_off, err);
+	if (donor_path == NULL)
+		goto out;
+	depth = ext_depth(orig_inode);
+	oext = orig_path[depth].p_ext;
+	tmp_oext = *oext;
+
+	depth = ext_depth(donor_inode);
+	dext = donor_path[depth].p_ext;
+	tmp_dext = *dext;
+
+	mext_calc_swap_extents(&tmp_dext, &tmp_oext, orig_off,
+				      donor_off, count);
+
+	/* Loop for the donor extents */
+	while (1) {
+		/* The extent for donor must be found. */
+		BUG_ON(!dext || donor_off != le32_to_cpu(tmp_dext.ee_block));
+
+		/* Set donor extent to orig extent */
+		err = mext_leaf_block(handle, orig_inode,
+					   orig_path, &tmp_dext, &orig_off);
+		if (err < 0)
+			goto out;
+
+		/* Set orig extent to donor extent */
+		err = mext_leaf_block(handle, donor_inode,
+					   donor_path, &tmp_oext, &donor_off);
+		if (err < 0)
+			goto out;
+
+		dext_alen = ext4_ext_get_actual_len(&tmp_dext);
+		replaced_count += dext_alen;
+		donor_off += dext_alen;
+		orig_off += dext_alen;
+
+		/* Already moved the expected blocks */
+		if (replaced_count >= count)
+			break;
+
+		if (orig_path)
+			ext4_ext_drop_refs(orig_path);
+		get_ext_path(orig_path, orig_inode, orig_off, err);
+		if (orig_path == NULL)
+			goto out;
+		depth = ext_depth(orig_inode);
+		oext = orig_path[depth].p_ext;
+		if (le32_to_cpu(oext->ee_block) +
+				ext4_ext_get_actual_len(oext) <= orig_off) {
+			err = 0;
+			goto out;
+		}
+		tmp_oext = *oext;
+
+		if (donor_path)
+			ext4_ext_drop_refs(donor_path);
+		get_ext_path(donor_path, donor_inode,
+				      donor_off, err);
+		if (donor_path == NULL)
+			goto out;
+		depth = ext_depth(donor_inode);
+		dext = donor_path[depth].p_ext;
+		if (le32_to_cpu(dext->ee_block) +
+				ext4_ext_get_actual_len(dext) <= donor_off) {
+			err = 0;
+			goto out;
+		}
+		tmp_dext = *dext;
+
+		mext_calc_swap_extents(&tmp_dext, &tmp_oext, orig_off,
+					      donor_off,
+					      count - replaced_count);
+	}
+
+out:
+	if (orig_path) {
+		ext4_ext_drop_refs(orig_path);
+		kfree(orig_path);
+	}
+	if (donor_path) {
+		ext4_ext_drop_refs(donor_path);
+		kfree(donor_path);
+	}
+
+	mext_double_up_write(orig_inode, donor_inode);
+	return err;
+}
+
+/**
+ * move_extent_per_page - Move extent data per page
+ *
+ * @o_filp:			file structure of original file
+ * @donor_inode:		donor inode
+ * @orig_page_offset:		page index on original file
+ * @data_offset_in_page:	block index where data swapping starts
+ * @block_len_in_page:		the number of blocks to be swapped
+ * @uninit:			orig extent is uninitialized or not
+ *
+ * Save the data in original inode blocks and replace original inode extents
+ * with donor inode extents by calling mext_replace_branches().
+ * Finally, write out the saved data in new original inode blocks. Return 0
+ * on success, or a negative error value on failure.
+ */
+static int
+move_extent_par_page(struct file *o_filp, struct inode *donor_inode,
+		  pgoff_t orig_page_offset, int data_offset_in_page,
+		  int block_len_in_page, int uninit)
+{
+	struct inode *orig_inode = o_filp->f_dentry->d_inode;
+	struct address_space *mapping = orig_inode->i_mapping;
+	struct buffer_head *bh;
+	struct page *page = NULL;
+	const struct address_space_operations *a_ops = mapping->a_ops;
+	handle_t *handle;
+	ext4_lblk_t orig_blk_offset;
+	long long offs = orig_page_offset << PAGE_CACHE_SHIFT;
+	unsigned long blocksize = orig_inode->i_sb->s_blocksize;
+	unsigned int w_flags = 0;
+	unsigned int tmp_data_len, data_len;
+	void *fsdata;
+	int ret, i, jblocks;
+	int blocks_per_page = PAGE_CACHE_SIZE >> orig_inode->i_blkbits;
+
+	/*
+	 * It needs twice the amount of ordinary journal buffers because
+	 * inode and donor_inode may change each different metadata blocks.
+	 */
+	jblocks = ext4_writepage_trans_blocks(orig_inode) * 2;
+	handle = ext4_journal_start(orig_inode, jblocks);
+	if (IS_ERR(handle)) {
+		ret = PTR_ERR(handle);
+		return ret;
+	}
+
+	if (segment_eq(get_fs(), KERNEL_DS))
+		w_flags |= AOP_FLAG_UNINTERRUPTIBLE;
+
+	orig_blk_offset = orig_page_offset * blocks_per_page +
+		data_offset_in_page;
+
+	/*
+	 * If orig extent is uninitialized one,
+	 * it's not necessary force the page into memory
+	 * and then force it to be written out again.
+	 * Just swap data blocks between orig and donor.
+	 */
+	if (uninit) {
+		ret = mext_replace_branches(handle, orig_inode,
+						 donor_inode, orig_blk_offset,
+						 block_len_in_page);
+
+		/* Clear the inode cache not to refer to the old data */
+		ext4_ext_invalidate_cache(orig_inode);
+		ext4_ext_invalidate_cache(donor_inode);
+		goto out2;
+	}
+
+	offs = (long long)orig_blk_offset << orig_inode->i_blkbits;
+
+	/* Calculate data_len */
+	if ((orig_blk_offset + block_len_in_page - 1) ==
+	    ((orig_inode->i_size - 1) >> orig_inode->i_blkbits)) {
+		/* Replace the last block */
+		tmp_data_len = orig_inode->i_size & (blocksize - 1);
+		/*
+		 * If data_len equal zero, it shows data_len is multiples of
+		 * blocksize. So we set appropriate value.
+		 */
+		if (tmp_data_len == 0)
+			tmp_data_len = blocksize;
+
+		data_len = tmp_data_len +
+			((block_len_in_page - 1) << orig_inode->i_blkbits);
+	} else {
+		data_len = block_len_in_page << orig_inode->i_blkbits;
+	}
+
+	ret = a_ops->write_begin(o_filp, mapping, offs, data_len, w_flags,
+				 &page, &fsdata);
+	if (unlikely(ret < 0))
+		goto out;
+
+	if (!PageUptodate(page)) {
+		mapping->a_ops->readpage(o_filp, page);
+		lock_page(page);
+	}
+
+	/*
+	 * try_to_release_page() doesn't call releasepage in writeback mode.
+	 * We should care about the order of writing to the same file
+	 * by multiple move extent processes.
+	 * It needs to call wait_on_page_writeback() to wait for the
+	 * writeback of the page.
+	 */
+	if (PageWriteback(page))
+		wait_on_page_writeback(page);
+
+	/* Release old bh and drop refs */
+	try_to_release_page(page, 0);
+
+	ret = mext_replace_branches(handle, orig_inode, donor_inode,
+					 orig_blk_offset, block_len_in_page);
+	if (ret < 0)
+		goto out;
+
+	/* Clear the inode cache not to refer to the old data */
+	ext4_ext_invalidate_cache(orig_inode);
+	ext4_ext_invalidate_cache(donor_inode);
+
+	if (!page_has_buffers(page))
+		create_empty_buffers(page, 1 << orig_inode->i_blkbits, 0);
+
+	bh = page_buffers(page);
+	for (i = 0; i < data_offset_in_page; i++)
+		bh = bh->b_this_page;
+
+	for (i = 0; i < block_len_in_page; i++) {
+		ret = ext4_get_block(orig_inode,
+				(sector_t)(orig_blk_offset + i), bh, 0);
+		if (ret < 0)
+			goto out;
+
+		if (bh->b_this_page != NULL)
+			bh = bh->b_this_page;
+	}
+
+	ret = a_ops->write_end(o_filp, mapping, offs, data_len, data_len,
+			       page, fsdata);
+	page = NULL;
+
+out:
+	if (unlikely(page)) {
+		if (PageLocked(page))
+			unlock_page(page);
+		page_cache_release(page);
+	}
+out2:
+	ext4_journal_stop(handle);
+
+	return ret < 0 ? ret : 0;
+}
+
+/**
+ * mext_check_argumants - Check whether move extent can be done
+ *
+ * @orig_inode:		original inode
+ * @donor_inode:	donor inode
+ * @orig_start:		logical start offset in block for orig
+ * @donor_start:	logical start offset in block for donor
+ * @len:		the number of blocks to be moved
+ * @moved_len:		moved block length
+ *
+ * Check the arguments of ext4_move_extents() whether the files can be
+ * exchanged with each other.
+ * Return 0 on success, or a negative error value on failure.
+ */
+static int
+mext_check_arguments(struct inode *orig_inode,
+			  struct inode *donor_inode, __u64 orig_start,
+			  __u64 donor_start, __u64 *len, __u64 moved_len)
+{
+	/* Regular file check */
+	if (!S_ISREG(orig_inode->i_mode) || !S_ISREG(donor_inode->i_mode)) {
+		ext4_debug("ext4 move extent: The argument files should be "
+			"regular file [ino:orig %lu, donor %lu]\n",
+			orig_inode->i_ino, donor_inode->i_ino);
+		return -EINVAL;
+	}
+
+	/* Ext4 move extent does not support swapfile */
+	if (IS_SWAPFILE(orig_inode) || IS_SWAPFILE(donor_inode)) {
+		ext4_debug("ext4 move extent: The argument files should "
+			"not be swapfile [ino:orig %lu, donor %lu]\n",
+			orig_inode->i_ino, donor_inode->i_ino);
+		return -EINVAL;
+	}
+
+	/* Files should be in the same ext4 FS */
+	if (orig_inode->i_sb != donor_inode->i_sb) {
+		ext4_debug("ext4 move extent: The argument files "
+			"should be in same FS [ino:orig %lu, donor %lu]\n",
+			orig_inode->i_ino, donor_inode->i_ino);
+		return -EINVAL;
+	}
+
+	/* orig and donor should be different file */
+	if (orig_inode->i_ino == donor_inode->i_ino) {
+		ext4_debug("ext4 move extent: The argument files should not "
+			"be same file [ino:orig %lu, donor %lu]\n",
+			orig_inode->i_ino, donor_inode->i_ino);
+		return -EINVAL;
+	}
+
+	/* Ext4 move extent supports only extent based file */
+	if (!(EXT4_I(orig_inode)->i_flags & EXT4_EXTENTS_FL)) {
+		ext4_debug("ext4 move extent: orig file is not extents "
+			"based file [ino:orig %lu]\n", orig_inode->i_ino);
+		return -EOPNOTSUPP;
+	} else if (!(EXT4_I(donor_inode)->i_flags & EXT4_EXTENTS_FL)) {
+		ext4_debug("ext4 move extent: donor file is not extents "
+			"based file [ino:donor %lu]\n", donor_inode->i_ino);
+		return -EOPNOTSUPP;
+	}
+
+	if ((!orig_inode->i_size) || (!donor_inode->i_size)) {
+		ext4_debug("ext4 move extent: File size is 0 byte\n");
+		return -EINVAL;
+	}
+
+	/* Start offset should be same */
+	if (orig_start != donor_start) {
+		ext4_debug("ext4 move extent: orig and donor's start "
+			"offset are not same [ino:orig %lu, donor %lu]\n",
+			orig_inode->i_ino, donor_inode->i_ino);
+		return -EINVAL;
+	}
+
+	if (moved_len) {
+		ext4_debug("ext4 move extent: moved_len should be 0 "
+			"[ino:orig %lu, donor %lu]\n", orig_inode->i_ino,
+			donor_inode->i_ino);
+		return -EINVAL;
+	}
+
+	if ((orig_start > MAX_DEFRAG_SIZE) ||
+	    (donor_start > MAX_DEFRAG_SIZE) ||
+	    (*len > MAX_DEFRAG_SIZE) ||
+	    (orig_start + *len > MAX_DEFRAG_SIZE))  {
+		ext4_debug("ext4 move extent: Can't handle over [%lu] blocks "
+			"[ino:orig %lu, donor %lu]\n", MAX_DEFRAG_SIZE,
+			orig_inode->i_ino, donor_inode->i_ino);
+		return -EINVAL;
+	}
+
+	if (orig_inode->i_size > donor_inode->i_size) {
+		if (orig_start >= donor_inode->i_size) {
+			ext4_debug("ext4 move extent: orig start offset "
+			"[%llu] should be less than donor file size "
+			"[%lld] [ino:orig %lu, donor_inode %lu]\n",
+			orig_start, donor_inode->i_size,
+			orig_inode->i_ino, donor_inode->i_ino);
+			return -EINVAL;
+		}
+
+		if (orig_start + *len > donor_inode->i_size) {
+			ext4_debug("ext4 move extent: End offset [%llu] should "
+				"be less than donor file size [%lld]."
+				"So adjust length from %llu to %lld "
+				"[ino:orig %lu, donor %lu]\n",
+				orig_start + *len, donor_inode->i_size,
+				*len, donor_inode->i_size - orig_start,
+				orig_inode->i_ino, donor_inode->i_ino);
+			*len = donor_inode->i_size - orig_start;
+		}
+	} else {
+		if (orig_start >= orig_inode->i_size) {
+			ext4_debug("ext4 move extent: start offset [%llu] "
+				"should be less than original file size "
+				"[%lld] [inode:orig %lu, donor %lu]\n",
+				 orig_start, orig_inode->i_size,
+				orig_inode->i_ino, donor_inode->i_ino);
+			return -EINVAL;
+		}
+
+		if (orig_start + *len > orig_inode->i_size) {
+			ext4_debug("ext4 move extent: Adjust length "
+				"from %llu to %lld. Because it should be "
+				"less than original file size "
+				"[ino:orig %lu, donor %lu]\n",
+				*len, orig_inode->i_size - orig_start,
+				orig_inode->i_ino, donor_inode->i_ino);
+			*len = orig_inode->i_size - orig_start;
+		}
+	}
+
+	if (!*len) {
+		ext4_debug("ext4 move extent: len shoudld not be 0 "
+			"[ino:orig %lu, donor %lu]\n", orig_inode->i_ino,
+			donor_inode->i_ino);
+		return -EINVAL;
+	}
+
+	return 0;
+}
+
+/**
+ * mext_inode_double_lock - Lock i_mutex on both @inode1 and @inode2
+ *
+ * @inode1:	the inode structure
+ * @inode2:	the inode structure
+ *
+ * Lock two inodes' i_mutex by i_ino order. This function is moved from
+ * fs/inode.c.
+ */
+static void
+mext_inode_double_lock(struct inode *inode1, struct inode *inode2)
+{
+	if (inode1 == NULL || inode2 == NULL || inode1 == inode2) {
+		if (inode1)
+			mutex_lock(&inode1->i_mutex);
+		else if (inode2)
+			mutex_lock(&inode2->i_mutex);
+		return;
+	}
+
+	if (inode1->i_ino < inode2->i_ino) {
+		mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
+		mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
+	} else {
+		mutex_lock_nested(&inode2->i_mutex, I_MUTEX_PARENT);
+		mutex_lock_nested(&inode1->i_mutex, I_MUTEX_CHILD);
+	}
+}
+
+/**
+ * mext_inode_double_unlock - Release i_mutex on both @inode1 and @inode2
+ *
+ * @inode1:     the inode that is released first
+ * @inode2:     the inode that is released second
+ *
+ * This function is moved from fs/inode.c.
+ */
+
+static void
+mext_inode_double_unlock(struct inode *inode1, struct inode *inode2)
+{
+	if (inode1)
+		mutex_unlock(&inode1->i_mutex);
+
+	if (inode2 && inode2 != inode1)
+		mutex_unlock(&inode2->i_mutex);
+}
+
+/**
+ * ext4_move_extents - Exchange the specified range of a file
+ *
+ * @o_filp:		file structure of the original file
+ * @d_filp:		file structure of the donor file
+ * @orig_start:		start offset in block for orig
+ * @donor_start:	start offset in block for donor
+ * @len:		the number of blocks to be moved
+ * @moved_len:		moved block length
+ *
+ * This function returns 0 and moved block length is set in moved_len
+ * if succeed, otherwise returns error value.
+ *
+ * Note: ext4_move_extents() proceeds the following order.
+ * 1:ext4_move_extents() calculates the last block number of moving extent
+ *   function by the start block number (orig_start) and the number of blocks
+ *   to be moved (len) specified as arguments.
+ *   If the {orig, donor}_start points a hole, the extent's start offset
+ *   pointed by ext_cur (current extent), holecheck_path, orig_path are set
+ *   after hole behind.
+ * 2:Continue step 3 to step 5, until the holecheck_path points to last_extent
+ *   or the ext_cur exceeds the block_end which is last logical block number.
+ * 3:To get the length of continues area, call mext_next_extent()
+ *   specified with the ext_cur (initial value is holecheck_path) re-cursive,
+ *   until find un-continuous extent, the start logical block number exceeds
+ *   the block_end or the extent points to the last extent.
+ * 4:Exchange the original inode data with donor inode data
+ *   from orig_page_offset to seq_end_page.
+ *   The start indexes of data are specified as arguments.
+ *   That of the original inode is orig_page_offset,
+ *   and the donor inode is also orig_page_offset
+ *   (To easily handle blocksize != pagesize case, the offset for the
+ *   donor inode is block unit).
+ * 5:Update holecheck_path and orig_path to points a next proceeding extent,
+ *   then returns to step 2.
+ * 6:Release holecheck_path, orig_path and set the len to moved_len
+ *   which shows the number of moved blocks.
+ *   The moved_len is useful for the command to calculate the file offset
+ *   for starting next move extent ioctl.
+ * 7:Return 0 on success, or a negative error value on failure.
+ */
+int
+ext4_move_extents(struct file *o_filp, struct file *d_filp,
+		 __u64 orig_start, __u64 donor_start, __u64 len,
+		 __u64 *moved_len)
+{
+	struct inode *orig_inode = o_filp->f_dentry->d_inode;
+	struct inode *donor_inode = d_filp->f_dentry->d_inode;
+	struct ext4_ext_path *orig_path = NULL, *holecheck_path = NULL;
+	struct ext4_extent *ext_prev, *ext_cur, *ext_dummy;
+	ext4_lblk_t block_start = orig_start;
+	ext4_lblk_t block_end, seq_start, add_blocks, file_end, seq_blocks = 0;
+	ext4_lblk_t rest_blocks;
+	pgoff_t orig_page_offset = 0, seq_end_page;
+	int ret, depth, last_extent = 0;
+	int blocks_per_page = PAGE_CACHE_SIZE >> orig_inode->i_blkbits;
+	int data_offset_in_page;
+	int block_len_in_page;
+	int uninit;
+
+	/* protect orig and donor against a truncate */
+	mext_inode_double_lock(orig_inode, donor_inode);
+
+	mext_double_down_read(orig_inode, donor_inode);
+	/* Check the filesystem environment whether move_extent can be done */
+	ret = mext_check_arguments(orig_inode, donor_inode, orig_start,
+					donor_start, &len, *moved_len);
+	mext_double_up_read(orig_inode, donor_inode);
+	if (ret)
+		goto out2;
+
+	file_end = (i_size_read(orig_inode) - 1) >> orig_inode->i_blkbits;
+	block_end = block_start + len - 1;
+	if (file_end < block_end)
+		len -= block_end - file_end;
+
+	get_ext_path(orig_path, orig_inode, block_start, ret);
+	if (orig_path == NULL)
+		goto out2;
+
+	/* Get path structure to check the hole */
+	get_ext_path(holecheck_path, orig_inode, block_start, ret);
+	if (holecheck_path == NULL)
+		goto out;
+
+	depth = ext_depth(orig_inode);
+	ext_cur = holecheck_path[depth].p_ext;
+	if (ext_cur == NULL) {
+		ret = -EINVAL;
+		goto out;
+	}
+
+	/*
+	 * Get proper extent whose ee_block is beyond block_start
+	 * if block_start was within the hole.
+	 */
+	if (le32_to_cpu(ext_cur->ee_block) +
+		ext4_ext_get_actual_len(ext_cur) - 1 < block_start) {
+		last_extent = mext_next_extent(orig_inode,
+					holecheck_path, &ext_cur);
+		if (last_extent < 0) {
+			ret = last_extent;
+			goto out;
+		}
+		last_extent = mext_next_extent(orig_inode, orig_path,
+							&ext_dummy);
+		if (last_extent < 0) {
+			ret = last_extent;
+			goto out;
+		}
+	}
+	seq_start = block_start;
+
+	/* No blocks within the specified range. */
+	if (le32_to_cpu(ext_cur->ee_block) > block_end) {
+		ext4_debug("ext4 move extent: The specified range of file "
+							"may be the hole\n");
+		ret = -EINVAL;
+		goto out;
+	}
+
+	/* Adjust start blocks */
+	add_blocks = min(le32_to_cpu(ext_cur->ee_block) +
+			 ext4_ext_get_actual_len(ext_cur), block_end + 1) -
+		     max(le32_to_cpu(ext_cur->ee_block), block_start);
+
+	while (!last_extent && le32_to_cpu(ext_cur->ee_block) <= block_end) {
+		seq_blocks += add_blocks;
+
+		/* Adjust tail blocks */
+		if (seq_start + seq_blocks - 1 > block_end)
+			seq_blocks = block_end - seq_start + 1;
+
+		ext_prev = ext_cur;
+		last_extent = mext_next_extent(orig_inode, holecheck_path,
+						&ext_cur);
+		if (last_extent < 0) {
+			ret = last_extent;
+			break;
+		}
+		add_blocks = ext4_ext_get_actual_len(ext_cur);
+
+		/*
+		 * Extend the length of contiguous block (seq_blocks)
+		 * if extents are contiguous.
+		 */
+		if (ext4_can_extents_be_merged(orig_inode,
+					       ext_prev, ext_cur) &&
+		    block_end >= le32_to_cpu(ext_cur->ee_block) &&
+		    !last_extent)
+			continue;
+
+		/* Is original extent is uninitialized */
+		uninit = ext4_ext_is_uninitialized(ext_prev);
+
+		data_offset_in_page = seq_start % blocks_per_page;
+
+		/*
+		 * Calculate data blocks count that should be swapped
+		 * at the first page.
+		 */
+		if (data_offset_in_page + seq_blocks > blocks_per_page) {
+			/* Swapped blocks are across pages */
+			block_len_in_page =
+					blocks_per_page - data_offset_in_page;
+		} else {
+			/* Swapped blocks are in a page */
+			block_len_in_page = seq_blocks;
+		}
+
+		orig_page_offset = seq_start >>
+				(PAGE_CACHE_SHIFT - orig_inode->i_blkbits);
+		seq_end_page = (seq_start + seq_blocks - 1) >>
+				(PAGE_CACHE_SHIFT - orig_inode->i_blkbits);
+		seq_start = le32_to_cpu(ext_cur->ee_block);
+		rest_blocks = seq_blocks;
+
+		/* Discard preallocations of two inodes */
+		down_write(&EXT4_I(orig_inode)->i_data_sem);
+		ext4_discard_preallocations(orig_inode);
+		up_write(&EXT4_I(orig_inode)->i_data_sem);
+
+		down_write(&EXT4_I(donor_inode)->i_data_sem);
+		ext4_discard_preallocations(donor_inode);
+		up_write(&EXT4_I(donor_inode)->i_data_sem);
+
+		while (orig_page_offset <= seq_end_page) {
+
+			/* Swap original branches with new branches */
+			ret = move_extent_par_page(o_filp, donor_inode,
+						orig_page_offset,
+						data_offset_in_page,
+						block_len_in_page, uninit);
+			if (ret < 0)
+				goto out;
+			orig_page_offset++;
+			/* Count how many blocks we have exchanged */
+			*moved_len += block_len_in_page;
+			BUG_ON(*moved_len > len);
+
+			data_offset_in_page = 0;
+			rest_blocks -= block_len_in_page;
+			if (rest_blocks > blocks_per_page)
+				block_len_in_page = blocks_per_page;
+			else
+				block_len_in_page = rest_blocks;
+		}
+
+		/* Decrease buffer counter */
+		if (holecheck_path)
+			ext4_ext_drop_refs(holecheck_path);
+		get_ext_path(holecheck_path, orig_inode,
+				      seq_start, ret);
+		if (holecheck_path == NULL)
+			break;
+		depth = holecheck_path->p_depth;
+
+		/* Decrease buffer counter */
+		if (orig_path)
+			ext4_ext_drop_refs(orig_path);
+		get_ext_path(orig_path, orig_inode, seq_start, ret);
+		if (orig_path == NULL)
+			break;
+
+		ext_cur = holecheck_path[depth].p_ext;
+		add_blocks = ext4_ext_get_actual_len(ext_cur);
+		seq_blocks = 0;
+
+	}
+out:
+	if (orig_path) {
+		ext4_ext_drop_refs(orig_path);
+		kfree(orig_path);
+	}
+	if (holecheck_path) {
+		ext4_ext_drop_refs(holecheck_path);
+		kfree(holecheck_path);
+	}
+out2:
+	mext_inode_double_unlock(orig_inode, donor_inode);
+
+	if (ret)
+		return ret;
+
+	/* All of the specified blocks must be exchanged in succeed */
+	BUG_ON(*moved_len != len);
+
+	return 0;
+}
diff --git a/fs/ext4/namei.c b/fs/ext4/namei.c
index 07eb664..de04013 100644
--- a/fs/ext4/namei.c
+++ b/fs/ext4/namei.c
@@ -1782,7 +1782,7 @@
 	if (IS_DIRSYNC(dir))
 		ext4_handle_sync(handle);
 
-	inode = ext4_new_inode (handle, dir, mode);
+	inode = ext4_new_inode(handle, dir, mode, &dentry->d_name, 0);
 	err = PTR_ERR(inode);
 	if (!IS_ERR(inode)) {
 		inode->i_op = &ext4_file_inode_operations;
@@ -1816,7 +1816,7 @@
 	if (IS_DIRSYNC(dir))
 		ext4_handle_sync(handle);
 
-	inode = ext4_new_inode(handle, dir, mode);
+	inode = ext4_new_inode(handle, dir, mode, &dentry->d_name, 0);
 	err = PTR_ERR(inode);
 	if (!IS_ERR(inode)) {
 		init_special_inode(inode, inode->i_mode, rdev);
@@ -1853,7 +1853,8 @@
 	if (IS_DIRSYNC(dir))
 		ext4_handle_sync(handle);
 
-	inode = ext4_new_inode(handle, dir, S_IFDIR | mode);
+	inode = ext4_new_inode(handle, dir, S_IFDIR | mode,
+			       &dentry->d_name, 0);
 	err = PTR_ERR(inode);
 	if (IS_ERR(inode))
 		goto out_stop;
@@ -2264,7 +2265,8 @@
 	if (IS_DIRSYNC(dir))
 		ext4_handle_sync(handle);
 
-	inode = ext4_new_inode(handle, dir, S_IFLNK|S_IRWXUGO);
+	inode = ext4_new_inode(handle, dir, S_IFLNK|S_IRWXUGO,
+			       &dentry->d_name, 0);
 	err = PTR_ERR(inode);
 	if (IS_ERR(inode))
 		goto out_stop;
diff --git a/fs/ext4/resize.c b/fs/ext4/resize.c
index 27eb289..68b0351 100644
--- a/fs/ext4/resize.c
+++ b/fs/ext4/resize.c
@@ -1002,7 +1002,7 @@
 			" too large to resize to %llu blocks safely\n",
 			sb->s_id, n_blocks_count);
 		if (sizeof(sector_t) < 8)
-			ext4_warning(sb, __func__, "CONFIG_LBD not enabled");
+			ext4_warning(sb, __func__, "CONFIG_LBDAF not enabled");
 		return -EINVAL;
 	}
 
diff --git a/fs/ext4/super.c b/fs/ext4/super.c
index 012c425..8bb9e2d 100644
--- a/fs/ext4/super.c
+++ b/fs/ext4/super.c
@@ -37,7 +37,6 @@
 #include <linux/seq_file.h>
 #include <linux/proc_fs.h>
 #include <linux/ctype.h>
-#include <linux/marker.h>
 #include <linux/log2.h>
 #include <linux/crc16.h>
 #include <asm/uaccess.h>
@@ -47,6 +46,9 @@
 #include "xattr.h"
 #include "acl.h"
 
+#define CREATE_TRACE_POINTS
+#include <trace/events/ext4.h>
+
 static int default_mb_history_length = 1000;
 
 module_param_named(default_mb_history_length, default_mb_history_length,
@@ -301,7 +303,7 @@
 	if (!test_opt(sb, ERRORS_CONT)) {
 		journal_t *journal = EXT4_SB(sb)->s_journal;
 
-		EXT4_SB(sb)->s_mount_opt |= EXT4_MOUNT_ABORT;
+		EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
 		if (journal)
 			jbd2_journal_abort(journal, -EIO);
 	}
@@ -414,7 +416,7 @@
 	ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
 	EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
 	sb->s_flags |= MS_RDONLY;
-	EXT4_SB(sb)->s_mount_opt |= EXT4_MOUNT_ABORT;
+	EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
 	if (EXT4_SB(sb)->s_journal)
 		jbd2_journal_abort(EXT4_SB(sb)->s_journal, -EIO);
 }
@@ -1474,7 +1476,7 @@
 			break;
 #endif
 		case Opt_abort:
-			set_opt(sbi->s_mount_opt, ABORT);
+			sbi->s_mount_flags |= EXT4_MF_FS_ABORTED;
 			break;
 		case Opt_nobarrier:
 			clear_opt(sbi->s_mount_opt, BARRIER);
@@ -1653,7 +1655,7 @@
 	ext4_commit_super(sb, 1);
 	if (test_opt(sb, DEBUG))
 		printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
-				"bpg=%lu, ipg=%lu, mo=%04lx]\n",
+				"bpg=%lu, ipg=%lu, mo=%04x]\n",
 			sb->s_blocksize,
 			sbi->s_groups_count,
 			EXT4_BLOCKS_PER_GROUP(sb),
@@ -1957,7 +1959,7 @@
 	/* small i_blocks in vfs inode? */
 	if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
 		/*
-		 * CONFIG_LBD is not enabled implies the inode
+		 * CONFIG_LBDAF is not enabled implies the inode
 		 * i_block represent total blocks in 512 bytes
 		 * 32 == size of vfs inode i_blocks * 8
 		 */
@@ -2000,7 +2002,7 @@
 
 	if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
 		/*
-		 * !has_huge_files or CONFIG_LBD not enabled implies that
+		 * !has_huge_files or CONFIG_LBDAF not enabled implies that
 		 * the inode i_block field represents total file blocks in
 		 * 2^32 512-byte sectors == size of vfs inode i_blocks * 8
 		 */
@@ -2204,6 +2206,7 @@
 EXT4_RO_ATTR(lifetime_write_kbytes);
 EXT4_ATTR_OFFSET(inode_readahead_blks, 0644, sbi_ui_show,
 		 inode_readahead_blks_store, s_inode_readahead_blks);
+EXT4_RW_ATTR_SBI_UI(inode_goal, s_inode_goal);
 EXT4_RW_ATTR_SBI_UI(mb_stats, s_mb_stats);
 EXT4_RW_ATTR_SBI_UI(mb_max_to_scan, s_mb_max_to_scan);
 EXT4_RW_ATTR_SBI_UI(mb_min_to_scan, s_mb_min_to_scan);
@@ -2216,6 +2219,7 @@
 	ATTR_LIST(session_write_kbytes),
 	ATTR_LIST(lifetime_write_kbytes),
 	ATTR_LIST(inode_readahead_blks),
+	ATTR_LIST(inode_goal),
 	ATTR_LIST(mb_stats),
 	ATTR_LIST(mb_max_to_scan),
 	ATTR_LIST(mb_min_to_scan),
@@ -2436,13 +2440,13 @@
 	if (has_huge_files) {
 		/*
 		 * Large file size enabled file system can only be
-		 * mount if kernel is build with CONFIG_LBD
+		 * mount if kernel is build with CONFIG_LBDAF
 		 */
 		if (sizeof(root->i_blocks) < sizeof(u64) &&
 				!(sb->s_flags & MS_RDONLY)) {
 			ext4_msg(sb, KERN_ERR, "Filesystem with huge "
 					"files cannot be mounted read-write "
-					"without CONFIG_LBD");
+					"without CONFIG_LBDAF");
 			goto failed_mount;
 		}
 	}
@@ -2566,7 +2570,7 @@
 		ext4_msg(sb, KERN_ERR, "filesystem"
 			" too large to mount safely");
 		if (sizeof(sector_t) < 8)
-			ext4_msg(sb, KERN_WARNING, "CONFIG_LBD not enabled");
+			ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled");
 		goto failed_mount;
 	}
 
@@ -3346,7 +3350,7 @@
 	int ret = 0;
 	tid_t target;
 
-	trace_mark(ext4_sync_fs, "dev %s wait %d", sb->s_id, wait);
+	trace_ext4_sync_fs(sb, wait);
 	if (jbd2_journal_start_commit(EXT4_SB(sb)->s_journal, &target)) {
 		if (wait)
 			jbd2_log_wait_commit(EXT4_SB(sb)->s_journal, target);
@@ -3450,7 +3454,7 @@
 		goto restore_opts;
 	}
 
-	if (sbi->s_mount_opt & EXT4_MOUNT_ABORT)
+	if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED)
 		ext4_abort(sb, __func__, "Abort forced by user");
 
 	sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
@@ -3465,7 +3469,7 @@
 
 	if ((*flags & MS_RDONLY) != (sb->s_flags & MS_RDONLY) ||
 		n_blocks_count > ext4_blocks_count(es)) {
-		if (sbi->s_mount_opt & EXT4_MOUNT_ABORT) {
+		if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED) {
 			err = -EROFS;
 			goto restore_opts;
 		}
diff --git a/fs/fat/inode.c b/fs/fat/inode.c
index 304b411..8970d8c 100644
--- a/fs/fat/inode.c
+++ b/fs/fat/inode.c
@@ -966,7 +966,7 @@
 
 	opts->fs_uid = current_uid();
 	opts->fs_gid = current_gid();
-	opts->fs_fmask = current_umask();
+	opts->fs_fmask = opts->fs_dmask = current_umask();
 	opts->allow_utime = -1;
 	opts->codepage = fat_default_codepage;
 	opts->iocharset = fat_default_iocharset;
diff --git a/fs/fuse/inode.c b/fs/fuse/inode.c
index f0df55a..d8673cc 100644
--- a/fs/fuse/inode.c
+++ b/fs/fuse/inode.c
@@ -19,7 +19,6 @@
 #include <linux/random.h>
 #include <linux/sched.h>
 #include <linux/exportfs.h>
-#include <linux/smp_lock.h>
 
 MODULE_AUTHOR("Miklos Szeredi <miklos@szeredi.hu>");
 MODULE_DESCRIPTION("Filesystem in Userspace");
@@ -260,9 +259,7 @@
 
 static void fuse_umount_begin(struct super_block *sb)
 {
-	lock_kernel();
 	fuse_abort_conn(get_fuse_conn_super(sb));
-	unlock_kernel();
 }
 
 static void fuse_send_destroy(struct fuse_conn *fc)
diff --git a/fs/gfs2/Kconfig b/fs/gfs2/Kconfig
index cad957c..5971359 100644
--- a/fs/gfs2/Kconfig
+++ b/fs/gfs2/Kconfig
@@ -1,6 +1,6 @@
 config GFS2_FS
 	tristate "GFS2 file system support"
-	depends on EXPERIMENTAL && (64BIT || LBD)
+	depends on EXPERIMENTAL && (64BIT || LBDAF)
 	select DLM if GFS2_FS_LOCKING_DLM
 	select CONFIGFS_FS if GFS2_FS_LOCKING_DLM
 	select SYSFS if GFS2_FS_LOCKING_DLM
diff --git a/fs/ioctl.c b/fs/ioctl.c
index 286f38d..001f8d3 100644
--- a/fs/ioctl.c
+++ b/fs/ioctl.c
@@ -70,9 +70,7 @@
 	res = get_user(block, p);
 	if (res)
 		return res;
-	lock_kernel();
 	res = mapping->a_ops->bmap(mapping, block);
-	unlock_kernel();
 	return put_user(res, p);
 }
 
diff --git a/fs/isofs/dir.c b/fs/isofs/dir.c
index 2f0dc5a..8ba5441 100644
--- a/fs/isofs/dir.c
+++ b/fs/isofs/dir.c
@@ -195,9 +195,8 @@
 		 * Do not report hidden files if so instructed, or associated
 		 * files unless instructed to do so
 		 */
-		if ((sbi->s_hide == 'y' &&
-				(de->flags[-sbi->s_high_sierra] & 1)) ||
-				(sbi->s_showassoc =='n' &&
+		if ((sbi->s_hide && (de->flags[-sbi->s_high_sierra] & 1)) ||
+		    (!sbi->s_showassoc &&
 				(de->flags[-sbi->s_high_sierra] & 4))) {
 			filp->f_pos += de_len;
 			continue;
diff --git a/fs/isofs/inode.c b/fs/isofs/inode.c
index 068b34b..58a7963 100644
--- a/fs/isofs/inode.c
+++ b/fs/isofs/inode.c
@@ -141,13 +141,17 @@
 };
 
 struct iso9660_options{
-	char map;
-	char rock;
+	unsigned int rock:1;
+	unsigned int cruft:1;
+	unsigned int hide:1;
+	unsigned int showassoc:1;
+	unsigned int nocompress:1;
+	unsigned int overriderockperm:1;
+	unsigned int uid_set:1;
+	unsigned int gid_set:1;
+	unsigned int utf8:1;
+	unsigned char map;
 	char joliet;
-	char cruft;
-	char hide;
-	char showassoc;
-	char nocompress;
 	unsigned char check;
 	unsigned int blocksize;
 	mode_t fmode;
@@ -155,7 +159,6 @@
 	gid_t gid;
 	uid_t uid;
 	char *iocharset;
-	unsigned char utf8;
 	/* LVE */
 	s32 session;
 	s32 sbsector;
@@ -312,7 +315,7 @@
 	Opt_block, Opt_check_r, Opt_check_s, Opt_cruft, Opt_gid, Opt_ignore,
 	Opt_iocharset, Opt_map_a, Opt_map_n, Opt_map_o, Opt_mode, Opt_nojoliet,
 	Opt_norock, Opt_sb, Opt_session, Opt_uid, Opt_unhide, Opt_utf8, Opt_err,
-	Opt_nocompress, Opt_hide, Opt_showassoc, Opt_dmode,
+	Opt_nocompress, Opt_hide, Opt_showassoc, Opt_dmode, Opt_overriderockperm,
 };
 
 static const match_table_t tokens = {
@@ -340,6 +343,7 @@
 	{Opt_gid, "gid=%u"},
 	{Opt_mode, "mode=%u"},
 	{Opt_dmode, "dmode=%u"},
+	{Opt_overriderockperm, "overriderockperm"},
 	{Opt_block, "block=%u"},
 	{Opt_ignore, "conv=binary"},
 	{Opt_ignore, "conv=b"},
@@ -359,24 +363,22 @@
 	int option;
 
 	popt->map = 'n';
-	popt->rock = 'y';
-	popt->joliet = 'y';
-	popt->cruft = 'n';
-	popt->hide = 'n';
-	popt->showassoc = 'n';
+	popt->rock = 1;
+	popt->joliet = 1;
+	popt->cruft = 0;
+	popt->hide = 0;
+	popt->showassoc = 0;
 	popt->check = 'u';		/* unset */
 	popt->nocompress = 0;
 	popt->blocksize = 1024;
-	popt->fmode = popt->dmode = S_IRUGO | S_IXUGO; /*
-					 * r-x for all.  The disc could
-					 * be shared with DOS machines so
-					 * virtually anything could be
-					 * a valid executable.
-					 */
+	popt->fmode = popt->dmode = ISOFS_INVALID_MODE;
+	popt->uid_set = 0;
+	popt->gid_set = 0;
 	popt->gid = 0;
 	popt->uid = 0;
 	popt->iocharset = NULL;
 	popt->utf8 = 0;
+	popt->overriderockperm = 0;
 	popt->session=-1;
 	popt->sbsector=-1;
 	if (!options)
@@ -393,20 +395,20 @@
 		token = match_token(p, tokens, args);
 		switch (token) {
 		case Opt_norock:
-			popt->rock = 'n';
+			popt->rock = 0;
 			break;
 		case Opt_nojoliet:
-			popt->joliet = 'n';
+			popt->joliet = 0;
 			break;
 		case Opt_hide:
-			popt->hide = 'y';
+			popt->hide = 1;
 			break;
 		case Opt_unhide:
 		case Opt_showassoc:
-			popt->showassoc = 'y';
+			popt->showassoc = 1;
 			break;
 		case Opt_cruft:
-			popt->cruft = 'y';
+			popt->cruft = 1;
 			break;
 		case Opt_utf8:
 			popt->utf8 = 1;
@@ -450,11 +452,13 @@
 			if (match_int(&args[0], &option))
 				return 0;
 			popt->uid = option;
+			popt->uid_set = 1;
 			break;
 		case Opt_gid:
 			if (match_int(&args[0], &option))
 				return 0;
 			popt->gid = option;
+			popt->gid_set = 1;
 			break;
 		case Opt_mode:
 			if (match_int(&args[0], &option))
@@ -466,6 +470,9 @@
 				return 0;
 			popt->dmode = option;
 			break;
+		case Opt_overriderockperm:
+			popt->overriderockperm = 1;
+			break;
 		case Opt_block:
 			if (match_int(&args[0], &option))
 				return 0;
@@ -650,7 +657,7 @@
 					goto out_freebh;
 
 				sbi->s_high_sierra = 1;
-				opt.rock = 'n';
+				opt.rock = 0;
 				h_pri = (struct hs_primary_descriptor *)vdp;
 				goto root_found;
 			}
@@ -673,7 +680,7 @@
 
 root_found:
 
-	if (joliet_level && (pri == NULL || opt.rock == 'n')) {
+	if (joliet_level && (pri == NULL || !opt.rock)) {
 		/* This is the case of Joliet with the norock mount flag.
 		 * A disc with both Joliet and Rock Ridge is handled later
 		 */
@@ -802,22 +809,31 @@
 	s->s_op = &isofs_sops;
 	s->s_export_op = &isofs_export_ops;
 	sbi->s_mapping = opt.map;
-	sbi->s_rock = (opt.rock == 'y' ? 2 : 0);
+	sbi->s_rock = (opt.rock ? 2 : 0);
 	sbi->s_rock_offset = -1; /* initial offset, will guess until SP is found*/
 	sbi->s_cruft = opt.cruft;
 	sbi->s_hide = opt.hide;
 	sbi->s_showassoc = opt.showassoc;
 	sbi->s_uid = opt.uid;
 	sbi->s_gid = opt.gid;
+	sbi->s_uid_set = opt.uid_set;
+	sbi->s_gid_set = opt.gid_set;
 	sbi->s_utf8 = opt.utf8;
 	sbi->s_nocompress = opt.nocompress;
+	sbi->s_overriderockperm = opt.overriderockperm;
 	/*
 	 * It would be incredibly stupid to allow people to mark every file
 	 * on the disk as suid, so we merely allow them to set the default
 	 * permissions.
 	 */
-	sbi->s_fmode = opt.fmode & 0777;
-	sbi->s_dmode = opt.dmode & 0777;
+	if (opt.fmode != ISOFS_INVALID_MODE)
+		sbi->s_fmode = opt.fmode & 0777;
+	else
+		sbi->s_fmode = ISOFS_INVALID_MODE;
+	if (opt.dmode != ISOFS_INVALID_MODE)
+		sbi->s_dmode = opt.dmode & 0777;
+	else
+		sbi->s_dmode = ISOFS_INVALID_MODE;
 
 	/*
 	 * Read the root inode, which _may_ result in changing
@@ -1095,18 +1111,6 @@
 	.bmap = _isofs_bmap
 };
 
-static inline void test_and_set_uid(uid_t *p, uid_t value)
-{
-	if (value)
-		*p = value;
-}
-
-static inline void test_and_set_gid(gid_t *p, gid_t value)
-{
-        if (value)
-                *p = value;
-}
-
 static int isofs_read_level3_size(struct inode *inode)
 {
 	unsigned long bufsize = ISOFS_BUFFER_SIZE(inode);
@@ -1261,7 +1265,10 @@
 	ei->i_file_format = isofs_file_normal;
 
 	if (de->flags[-high_sierra] & 2) {
-		inode->i_mode = sbi->s_dmode | S_IFDIR;
+		if (sbi->s_dmode != ISOFS_INVALID_MODE)
+			inode->i_mode = S_IFDIR | sbi->s_dmode;
+		else
+			inode->i_mode = S_IFDIR | S_IRUGO | S_IXUGO;
 		inode->i_nlink = 1;	/*
 					 * Set to 1.  We know there are 2, but
 					 * the find utility tries to optimize
@@ -1270,8 +1277,16 @@
 					 * do it the hard way.
 					 */
 	} else {
-		/* Everybody gets to read the file. */
-		inode->i_mode = sbi->s_fmode | S_IFREG;
+		if (sbi->s_fmode != ISOFS_INVALID_MODE) {
+			inode->i_mode = S_IFREG | sbi->s_fmode;
+		} else {
+			/*
+			 * Set default permissions: r-x for all.  The disc
+			 * could be shared with DOS machines so virtually
+			 * anything could be a valid executable.
+			 */
+			inode->i_mode = S_IFREG | S_IRUGO | S_IXUGO;
+		}
 		inode->i_nlink = 1;
 	}
 	inode->i_uid = sbi->s_uid;
@@ -1300,7 +1315,7 @@
 	 * this CDROM was mounted with the cruft option.
 	 */
 
-	if (sbi->s_cruft == 'y')
+	if (sbi->s_cruft)
 		inode->i_size &= 0x00ffffff;
 
 	if (de->interleave[0]) {
@@ -1346,9 +1361,18 @@
 	if (!high_sierra) {
 		parse_rock_ridge_inode(de, inode);
 		/* if we want uid/gid set, override the rock ridge setting */
-		test_and_set_uid(&inode->i_uid, sbi->s_uid);
-		test_and_set_gid(&inode->i_gid, sbi->s_gid);
+		if (sbi->s_uid_set)
+			inode->i_uid = sbi->s_uid;
+		if (sbi->s_gid_set)
+			inode->i_gid = sbi->s_gid;
 	}
+	/* Now set final access rights if overriding rock ridge setting */
+	if (S_ISDIR(inode->i_mode) && sbi->s_overriderockperm &&
+	    sbi->s_dmode != ISOFS_INVALID_MODE)
+		inode->i_mode = S_IFDIR | sbi->s_dmode;
+	if (S_ISREG(inode->i_mode) && sbi->s_overriderockperm &&
+	    sbi->s_fmode != ISOFS_INVALID_MODE)
+		inode->i_mode = S_IFREG | sbi->s_fmode;
 
 	/* Install the inode operations vector */
 	if (S_ISREG(inode->i_mode)) {
diff --git a/fs/isofs/isofs.h b/fs/isofs/isofs.h
index ccbf72f..7d33de8 100644
--- a/fs/isofs/isofs.h
+++ b/fs/isofs/isofs.h
@@ -35,21 +35,20 @@
 	unsigned long s_log_zone_size;
 	unsigned long s_max_size;
 	
-	unsigned char s_high_sierra; /* A simple flag */
-	unsigned char s_mapping;
 	int           s_rock_offset; /* offset of SUSP fields within SU area */
-	unsigned char s_rock;
 	unsigned char s_joliet_level;
-	unsigned char s_utf8;
-	unsigned char s_cruft; /* Broken disks with high
-				  byte of length containing
-				  junk */
-	unsigned char s_unhide;
-	unsigned char s_nosuid;
-	unsigned char s_nodev;
-	unsigned char s_nocompress;
-	unsigned char s_hide;
-	unsigned char s_showassoc;
+	unsigned char s_mapping;
+	unsigned int  s_high_sierra:1;
+	unsigned int  s_rock:2;
+	unsigned int  s_utf8:1;
+	unsigned int  s_cruft:1; /* Broken disks with high byte of length
+				  * containing junk */
+	unsigned int  s_nocompress:1;
+	unsigned int  s_hide:1;
+	unsigned int  s_showassoc:1;
+	unsigned int  s_overriderockperm:1;
+	unsigned int  s_uid_set:1;
+	unsigned int  s_gid_set:1;
 
 	mode_t s_fmode;
 	mode_t s_dmode;
@@ -58,6 +57,8 @@
 	struct nls_table *s_nls_iocharset; /* Native language support table */
 };
 
+#define ISOFS_INVALID_MODE ((mode_t) -1)
+
 static inline struct isofs_sb_info *ISOFS_SB(struct super_block *sb)
 {
 	return sb->s_fs_info;
diff --git a/fs/isofs/namei.c b/fs/isofs/namei.c
index 8299889..eaa8313 100644
--- a/fs/isofs/namei.c
+++ b/fs/isofs/namei.c
@@ -142,9 +142,9 @@
 		 */
 		match = 0;
 		if (dlen > 0 &&
-			(sbi->s_hide =='n' ||
+			(!sbi->s_hide ||
 				(!(de->flags[-sbi->s_high_sierra] & 1))) &&
-			(sbi->s_showassoc =='y' ||
+			(sbi->s_showassoc ||
 				(!(de->flags[-sbi->s_high_sierra] & 4)))) {
 			match = (isofs_cmp(dentry, dpnt, dlen) == 0);
 		}
diff --git a/fs/jbd/transaction.c b/fs/jbd/transaction.c
index ed886e6..73242ba 100644
--- a/fs/jbd/transaction.c
+++ b/fs/jbd/transaction.c
@@ -1686,35 +1686,6 @@
 	return;
 }
 
-/*
- * journal_try_to_free_buffers() could race with journal_commit_transaction()
- * The latter might still hold the a count on buffers when inspecting
- * them on t_syncdata_list or t_locked_list.
- *
- * journal_try_to_free_buffers() will call this function to
- * wait for the current transaction to finish syncing data buffers, before
- * tryinf to free that buffer.
- *
- * Called with journal->j_state_lock held.
- */
-static void journal_wait_for_transaction_sync_data(journal_t *journal)
-{
-	transaction_t *transaction = NULL;
-	tid_t tid;
-
-	spin_lock(&journal->j_state_lock);
-	transaction = journal->j_committing_transaction;
-
-	if (!transaction) {
-		spin_unlock(&journal->j_state_lock);
-		return;
-	}
-
-	tid = transaction->t_tid;
-	spin_unlock(&journal->j_state_lock);
-	log_wait_commit(journal, tid);
-}
-
 /**
  * int journal_try_to_free_buffers() - try to free page buffers.
  * @journal: journal for operation
@@ -1786,25 +1757,6 @@
 
 	ret = try_to_free_buffers(page);
 
-	/*
-	 * There are a number of places where journal_try_to_free_buffers()
-	 * could race with journal_commit_transaction(), the later still
-	 * holds the reference to the buffers to free while processing them.
-	 * try_to_free_buffers() failed to free those buffers. Some of the
-	 * caller of releasepage() request page buffers to be dropped, otherwise
-	 * treat the fail-to-free as errors (such as generic_file_direct_IO())
-	 *
-	 * So, if the caller of try_to_release_page() wants the synchronous
-	 * behaviour(i.e make sure buffers are dropped upon return),
-	 * let's wait for the current transaction to finish flush of
-	 * dirty data buffers, then try to free those buffers again,
-	 * with the journal locked.
-	 */
-	if (ret == 0 && (gfp_mask & __GFP_WAIT) && (gfp_mask & __GFP_FS)) {
-		journal_wait_for_transaction_sync_data(journal);
-		ret = try_to_free_buffers(page);
-	}
-
 busy:
 	return ret;
 }
diff --git a/fs/jbd2/checkpoint.c b/fs/jbd2/checkpoint.c
index 17159ca..5d70b3e 100644
--- a/fs/jbd2/checkpoint.c
+++ b/fs/jbd2/checkpoint.c
@@ -20,9 +20,9 @@
 #include <linux/time.h>
 #include <linux/fs.h>
 #include <linux/jbd2.h>
-#include <linux/marker.h>
 #include <linux/errno.h>
 #include <linux/slab.h>
+#include <trace/events/jbd2.h>
 
 /*
  * Unlink a buffer from a transaction checkpoint list.
@@ -358,8 +358,7 @@
 	 * journal straight away.
 	 */
 	result = jbd2_cleanup_journal_tail(journal);
-	trace_mark(jbd2_checkpoint, "dev %s need_checkpoint %d",
-		   journal->j_devname, result);
+	trace_jbd2_checkpoint(journal, result);
 	jbd_debug(1, "cleanup_journal_tail returned %d\n", result);
 	if (result <= 0)
 		return result;
diff --git a/fs/jbd2/commit.c b/fs/jbd2/commit.c
index 0b7d3b8..7b4088b 100644
--- a/fs/jbd2/commit.c
+++ b/fs/jbd2/commit.c
@@ -16,7 +16,6 @@
 #include <linux/time.h>
 #include <linux/fs.h>
 #include <linux/jbd2.h>
-#include <linux/marker.h>
 #include <linux/errno.h>
 #include <linux/slab.h>
 #include <linux/mm.h>
@@ -26,6 +25,7 @@
 #include <linux/writeback.h>
 #include <linux/backing-dev.h>
 #include <linux/bio.h>
+#include <trace/events/jbd2.h>
 
 /*
  * Default IO end handler for temporary BJ_IO buffer_heads.
@@ -253,6 +253,7 @@
 		 * block allocation  with delalloc. We need to write
 		 * only allocated blocks here.
 		 */
+		trace_jbd2_submit_inode_data(jinode->i_vfs_inode);
 		err = journal_submit_inode_data_buffers(mapping);
 		if (!ret)
 			ret = err;
@@ -394,8 +395,7 @@
 	commit_transaction = journal->j_running_transaction;
 	J_ASSERT(commit_transaction->t_state == T_RUNNING);
 
-	trace_mark(jbd2_start_commit, "dev %s transaction %d",
-		   journal->j_devname, commit_transaction->t_tid);
+	trace_jbd2_start_commit(journal, commit_transaction);
 	jbd_debug(1, "JBD: starting commit of transaction %d\n",
 			commit_transaction->t_tid);
 
@@ -409,6 +409,7 @@
 	 */
 	if (commit_transaction->t_synchronous_commit)
 		write_op = WRITE_SYNC_PLUG;
+	trace_jbd2_commit_locking(journal, commit_transaction);
 	stats.u.run.rs_wait = commit_transaction->t_max_wait;
 	stats.u.run.rs_locked = jiffies;
 	stats.u.run.rs_running = jbd2_time_diff(commit_transaction->t_start,
@@ -484,6 +485,7 @@
 	 */
 	jbd2_journal_switch_revoke_table(journal);
 
+	trace_jbd2_commit_flushing(journal, commit_transaction);
 	stats.u.run.rs_flushing = jiffies;
 	stats.u.run.rs_locked = jbd2_time_diff(stats.u.run.rs_locked,
 					       stats.u.run.rs_flushing);
@@ -520,6 +522,7 @@
 	commit_transaction->t_state = T_COMMIT;
 	spin_unlock(&journal->j_state_lock);
 
+	trace_jbd2_commit_logging(journal, commit_transaction);
 	stats.u.run.rs_logging = jiffies;
 	stats.u.run.rs_flushing = jbd2_time_diff(stats.u.run.rs_flushing,
 						 stats.u.run.rs_logging);
@@ -1054,9 +1057,7 @@
 	if (journal->j_commit_callback)
 		journal->j_commit_callback(journal, commit_transaction);
 
-	trace_mark(jbd2_end_commit, "dev %s transaction %d head %d",
-		   journal->j_devname, commit_transaction->t_tid,
-		   journal->j_tail_sequence);
+	trace_jbd2_end_commit(journal, commit_transaction);
 	jbd_debug(1, "JBD: commit %d complete, head %d\n",
 		  journal->j_commit_sequence, journal->j_tail_sequence);
 	if (to_free)
diff --git a/fs/jbd2/journal.c b/fs/jbd2/journal.c
index 62be7d2..18bfd5d 100644
--- a/fs/jbd2/journal.c
+++ b/fs/jbd2/journal.c
@@ -38,6 +38,10 @@
 #include <linux/debugfs.h>
 #include <linux/seq_file.h>
 #include <linux/math64.h>
+#include <linux/hash.h>
+
+#define CREATE_TRACE_POINTS
+#include <trace/events/jbd2.h>
 
 #include <asm/uaccess.h>
 #include <asm/page.h>
@@ -2377,6 +2381,71 @@
 	jbd2_journal_destroy_caches();
 }
 
+/* 
+ * jbd2_dev_to_name is a utility function used by the jbd2 and ext4 
+ * tracing infrastructure to map a dev_t to a device name.
+ *
+ * The caller should use rcu_read_lock() in order to make sure the
+ * device name stays valid until its done with it.  We use
+ * rcu_read_lock() as well to make sure we're safe in case the caller
+ * gets sloppy, and because rcu_read_lock() is cheap and can be safely
+ * nested.
+ */
+struct devname_cache {
+	struct rcu_head	rcu;
+	dev_t		device;
+	char		devname[BDEVNAME_SIZE];
+};
+#define CACHE_SIZE_BITS 6
+static struct devname_cache *devcache[1 << CACHE_SIZE_BITS];
+static DEFINE_SPINLOCK(devname_cache_lock);
+
+static void free_devcache(struct rcu_head *rcu)
+{
+	kfree(rcu);
+}
+
+const char *jbd2_dev_to_name(dev_t device)
+{
+	int	i = hash_32(device, CACHE_SIZE_BITS);
+	char	*ret;
+	struct block_device *bd;
+
+	rcu_read_lock();
+	if (devcache[i] && devcache[i]->device == device) {
+		ret = devcache[i]->devname;
+		rcu_read_unlock();
+		return ret;
+	}
+	rcu_read_unlock();
+
+	spin_lock(&devname_cache_lock);
+	if (devcache[i]) {
+		if (devcache[i]->device == device) {
+			ret = devcache[i]->devname;
+			spin_unlock(&devname_cache_lock);
+			return ret;
+		}
+		call_rcu(&devcache[i]->rcu, free_devcache);
+	}
+	devcache[i] = kmalloc(sizeof(struct devname_cache), GFP_KERNEL);
+	if (!devcache[i]) {
+		spin_unlock(&devname_cache_lock);
+		return "NODEV-ALLOCFAILURE"; /* Something non-NULL */
+	}
+	devcache[i]->device = device;
+	bd = bdget(device);
+	if (bd) {
+		bdevname(bd, devcache[i]->devname);
+		bdput(bd);
+	} else
+		__bdevname(device, devcache[i]->devname);
+	ret = devcache[i]->devname;
+	spin_unlock(&devname_cache_lock);
+	return ret;
+}
+EXPORT_SYMBOL(jbd2_dev_to_name);
+
 MODULE_LICENSE("GPL");
 module_init(journal_init);
 module_exit(journal_exit);
diff --git a/fs/jbd2/transaction.c b/fs/jbd2/transaction.c
index 996ffda..494501e 100644
--- a/fs/jbd2/transaction.c
+++ b/fs/jbd2/transaction.c
@@ -1547,36 +1547,6 @@
 	return;
 }
 
-/*
- * jbd2_journal_try_to_free_buffers() could race with
- * jbd2_journal_commit_transaction(). The later might still hold the
- * reference count to the buffers when inspecting them on
- * t_syncdata_list or t_locked_list.
- *
- * jbd2_journal_try_to_free_buffers() will call this function to
- * wait for the current transaction to finish syncing data buffers, before
- * try to free that buffer.
- *
- * Called with journal->j_state_lock hold.
- */
-static void jbd2_journal_wait_for_transaction_sync_data(journal_t *journal)
-{
-	transaction_t *transaction;
-	tid_t tid;
-
-	spin_lock(&journal->j_state_lock);
-	transaction = journal->j_committing_transaction;
-
-	if (!transaction) {
-		spin_unlock(&journal->j_state_lock);
-		return;
-	}
-
-	tid = transaction->t_tid;
-	spin_unlock(&journal->j_state_lock);
-	jbd2_log_wait_commit(journal, tid);
-}
-
 /**
  * int jbd2_journal_try_to_free_buffers() - try to free page buffers.
  * @journal: journal for operation
@@ -1649,25 +1619,6 @@
 
 	ret = try_to_free_buffers(page);
 
-	/*
-	 * There are a number of places where jbd2_journal_try_to_free_buffers()
-	 * could race with jbd2_journal_commit_transaction(), the later still
-	 * holds the reference to the buffers to free while processing them.
-	 * try_to_free_buffers() failed to free those buffers. Some of the
-	 * caller of releasepage() request page buffers to be dropped, otherwise
-	 * treat the fail-to-free as errors (such as generic_file_direct_IO())
-	 *
-	 * So, if the caller of try_to_release_page() wants the synchronous
-	 * behaviour(i.e make sure buffers are dropped upon return),
-	 * let's wait for the current transaction to finish flush of
-	 * dirty data buffers, then try to free those buffers again,
-	 * with the journal locked.
-	 */
-	if (ret == 0 && (gfp_mask & __GFP_WAIT) && (gfp_mask & __GFP_FS)) {
-		jbd2_journal_wait_for_transaction_sync_data(journal);
-		ret = try_to_free_buffers(page);
-	}
-
 busy:
 	return ret;
 }
diff --git a/fs/minix/bitmap.c b/fs/minix/bitmap.c
index 3aebe32..6ac693f 100644
--- a/fs/minix/bitmap.c
+++ b/fs/minix/bitmap.c
@@ -12,13 +12,14 @@
 /* bitmap.c contains the code that handles the inode and block bitmaps */
 
 #include "minix.h"
-#include <linux/smp_lock.h>
 #include <linux/buffer_head.h>
 #include <linux/bitops.h>
 #include <linux/sched.h>
 
 static const int nibblemap[] = { 4,3,3,2,3,2,2,1,3,2,2,1,2,1,1,0 };
 
+static DEFINE_SPINLOCK(bitmap_lock);
+
 static unsigned long count_free(struct buffer_head *map[], unsigned numblocks, __u32 numbits)
 {
 	unsigned i, j, sum = 0;
@@ -69,11 +70,11 @@
 		return;
 	}
 	bh = sbi->s_zmap[zone];
-	lock_kernel();
+	spin_lock(&bitmap_lock);
 	if (!minix_test_and_clear_bit(bit, bh->b_data))
 		printk("minix_free_block (%s:%lu): bit already cleared\n",
 		       sb->s_id, block);
-	unlock_kernel();
+	spin_unlock(&bitmap_lock);
 	mark_buffer_dirty(bh);
 	return;
 }
@@ -88,18 +89,18 @@
 		struct buffer_head *bh = sbi->s_zmap[i];
 		int j;
 
-		lock_kernel();
+		spin_lock(&bitmap_lock);
 		j = minix_find_first_zero_bit(bh->b_data, bits_per_zone);
 		if (j < bits_per_zone) {
 			minix_set_bit(j, bh->b_data);
-			unlock_kernel();
+			spin_unlock(&bitmap_lock);
 			mark_buffer_dirty(bh);
 			j += i * bits_per_zone + sbi->s_firstdatazone-1;
 			if (j < sbi->s_firstdatazone || j >= sbi->s_nzones)
 				break;
 			return j;
 		}
-		unlock_kernel();
+		spin_unlock(&bitmap_lock);
 	}
 	return 0;
 }
@@ -211,10 +212,10 @@
 	minix_clear_inode(inode);	/* clear on-disk copy */
 
 	bh = sbi->s_imap[ino];
-	lock_kernel();
+	spin_lock(&bitmap_lock);
 	if (!minix_test_and_clear_bit(bit, bh->b_data))
 		printk("minix_free_inode: bit %lu already cleared\n", bit);
-	unlock_kernel();
+	spin_unlock(&bitmap_lock);
 	mark_buffer_dirty(bh);
  out:
 	clear_inode(inode);		/* clear in-memory copy */
@@ -237,7 +238,7 @@
 	j = bits_per_zone;
 	bh = NULL;
 	*error = -ENOSPC;
-	lock_kernel();
+	spin_lock(&bitmap_lock);
 	for (i = 0; i < sbi->s_imap_blocks; i++) {
 		bh = sbi->s_imap[i];
 		j = minix_find_first_zero_bit(bh->b_data, bits_per_zone);
@@ -245,17 +246,17 @@
 			break;
 	}
 	if (!bh || j >= bits_per_zone) {
-		unlock_kernel();
+		spin_unlock(&bitmap_lock);
 		iput(inode);
 		return NULL;
 	}
 	if (minix_test_and_set_bit(j, bh->b_data)) {	/* shouldn't happen */
-		unlock_kernel();
+		spin_unlock(&bitmap_lock);
 		printk("minix_new_inode: bit already set\n");
 		iput(inode);
 		return NULL;
 	}
-	unlock_kernel();
+	spin_unlock(&bitmap_lock);
 	mark_buffer_dirty(bh);
 	j += i * bits_per_zone;
 	if (!j || j > sbi->s_ninodes) {
diff --git a/fs/minix/dir.c b/fs/minix/dir.c
index e5f2064..d407e7a 100644
--- a/fs/minix/dir.c
+++ b/fs/minix/dir.c
@@ -11,7 +11,6 @@
 #include "minix.h"
 #include <linux/buffer_head.h>
 #include <linux/highmem.h>
-#include <linux/smp_lock.h>
 #include <linux/swap.h>
 
 typedef struct minix_dir_entry minix_dirent;
@@ -20,6 +19,7 @@
 static int minix_readdir(struct file *, void *, filldir_t);
 
 const struct file_operations minix_dir_operations = {
+	.llseek		= generic_file_llseek,
 	.read		= generic_read_dir,
 	.readdir	= minix_readdir,
 	.fsync		= simple_fsync,
@@ -102,8 +102,6 @@
 	char *name;
 	__u32 inumber;
 
-	lock_kernel();
-
 	pos = (pos + chunk_size-1) & ~(chunk_size-1);
 	if (pos >= inode->i_size)
 		goto done;
@@ -146,7 +144,6 @@
 
 done:
 	filp->f_pos = (n << PAGE_CACHE_SHIFT) | offset;
-	unlock_kernel();
 	return 0;
 }
 
diff --git a/fs/minix/inode.c b/fs/minix/inode.c
index f91a236..74ea82d 100644
--- a/fs/minix/inode.c
+++ b/fs/minix/inode.c
@@ -35,8 +35,6 @@
 	int i;
 	struct minix_sb_info *sbi = minix_sb(sb);
 
-	lock_kernel();
-
 	if (!(sb->s_flags & MS_RDONLY)) {
 		if (sbi->s_version != MINIX_V3)	 /* s_state is now out from V3 sb */
 			sbi->s_ms->s_state = sbi->s_mount_state;
@@ -50,8 +48,6 @@
 	kfree(sbi->s_imap);
 	sb->s_fs_info = NULL;
 	kfree(sbi);
-
-	unlock_kernel();
 }
 
 static struct kmem_cache * minix_inode_cachep;
diff --git a/fs/notify/inotify/inotify.h b/fs/notify/inotify/inotify.h
index ea2605a..f234f3a 100644
--- a/fs/notify/inotify/inotify.h
+++ b/fs/notify/inotify/inotify.h
@@ -15,7 +15,8 @@
 	int wd;
 };
 
-extern void inotify_destroy_mark_entry(struct fsnotify_mark_entry *entry, struct fsnotify_group *group);
+extern void inotify_ignored_and_remove_idr(struct fsnotify_mark_entry *entry,
+					   struct fsnotify_group *group);
 extern void inotify_free_event_priv(struct fsnotify_event_private_data *event_priv);
 
 extern const struct fsnotify_ops inotify_fsnotify_ops;
diff --git a/fs/notify/inotify/inotify_fsnotify.c b/fs/notify/inotify/inotify_fsnotify.c
index 7ef75b8..47cd258 100644
--- a/fs/notify/inotify/inotify_fsnotify.c
+++ b/fs/notify/inotify/inotify_fsnotify.c
@@ -81,7 +81,7 @@
 
 static void inotify_freeing_mark(struct fsnotify_mark_entry *entry, struct fsnotify_group *group)
 {
-	inotify_destroy_mark_entry(entry, group);
+	inotify_ignored_and_remove_idr(entry, group);
 }
 
 static bool inotify_should_send_event(struct fsnotify_group *group, struct inode *inode, __u32 mask)
diff --git a/fs/notify/inotify/inotify_user.c b/fs/notify/inotify/inotify_user.c
index 982a412..ff231ad 100644
--- a/fs/notify/inotify/inotify_user.c
+++ b/fs/notify/inotify/inotify_user.c
@@ -363,39 +363,17 @@
 }
 
 /*
- * When, for whatever reason, inotify is done with a mark (or what used to be a
- * watch) we need to remove that watch from the idr and we need to send IN_IGNORED
- * for the given wd.
- *
- * There is a bit of recursion here.  The loop looks like:
- * 	inotify_destroy_mark_entry -> fsnotify_destroy_mark_by_entry ->
- *	inotify_freeing_mark -> inotify_destory_mark_entry -> restart
- * But the loop is broken in 2 places.  fsnotify_destroy_mark_by_entry sets
- * entry->group = NULL before the call to inotify_freeing_mark, so the if (egroup)
- * test below will not call back to fsnotify again.  But even if that test wasn't
- * there this would still be safe since fsnotify_destroy_mark_by_entry() is
- * safe from recursion.
+ * Send IN_IGNORED for this wd, remove this wd from the idr, and drop the
+ * internal reference help on the mark because it is in the idr.
  */
-void inotify_destroy_mark_entry(struct fsnotify_mark_entry *entry, struct fsnotify_group *group)
+void inotify_ignored_and_remove_idr(struct fsnotify_mark_entry *entry,
+				    struct fsnotify_group *group)
 {
 	struct inotify_inode_mark_entry *ientry;
 	struct inotify_event_private_data *event_priv;
 	struct fsnotify_event_private_data *fsn_event_priv;
-	struct fsnotify_group *egroup;
 	struct idr *idr;
 
-	spin_lock(&entry->lock);
-	egroup = entry->group;
-
-	/* if egroup we aren't really done and something might still send events
-	 * for this inode, on the callback we'll send the IN_IGNORED */
-	if (egroup) {
-		spin_unlock(&entry->lock);
-		fsnotify_destroy_mark_by_entry(entry);
-		return;
-	}
-	spin_unlock(&entry->lock);
-
 	ientry = container_of(entry, struct inotify_inode_mark_entry, fsn_entry);
 
 	event_priv = kmem_cache_alloc(event_priv_cachep, GFP_KERNEL);
@@ -699,7 +677,7 @@
 	fsnotify_get_mark(entry);
 	spin_unlock(&group->inotify_data.idr_lock);
 
-	inotify_destroy_mark_entry(entry, group);
+	fsnotify_destroy_mark_by_entry(entry);
 	fsnotify_put_mark(entry);
 
 out:
diff --git a/fs/ocfs2/super.c b/fs/ocfs2/super.c
index d33767f..0d3ed74 100644
--- a/fs/ocfs2/super.c
+++ b/fs/ocfs2/super.c
@@ -552,7 +552,7 @@
 	 */
 
 #if BITS_PER_LONG == 32
-# if defined(CONFIG_LBD)
+# if defined(CONFIG_LBDAF)
 	BUILD_BUG_ON(sizeof(sector_t) != 8);
 	/*
 	 * We might be limited by page cache size.
diff --git a/fs/proc/Makefile b/fs/proc/Makefile
index 63d9651..11a7b5c 100644
--- a/fs/proc/Makefile
+++ b/fs/proc/Makefile
@@ -18,6 +18,7 @@
 proc-y	+= stat.o
 proc-y	+= uptime.o
 proc-y	+= version.o
+proc-y	+= softirqs.o
 proc-$(CONFIG_PROC_SYSCTL)	+= proc_sysctl.o
 proc-$(CONFIG_NET)		+= proc_net.o
 proc-$(CONFIG_PROC_KCORE)	+= kcore.o
diff --git a/fs/proc/proc_devtree.c b/fs/proc/proc_devtree.c
index fc6c302..7ba79a5 100644
--- a/fs/proc/proc_devtree.c
+++ b/fs/proc/proc_devtree.c
@@ -195,20 +195,20 @@
 			p = fixup_name(np, de, p);
 
 		ent = proc_mkdir(p, de);
-		if (ent == 0)
+		if (ent == NULL)
 			break;
 		proc_device_tree_add_node(child, ent);
 	}
 	of_node_put(child);
 
-	for (pp = np->properties; pp != 0; pp = pp->next) {
+	for (pp = np->properties; pp != NULL; pp = pp->next) {
 		p = pp->name;
 
 		if (duplicate_name(de, p))
 			p = fixup_name(np, de, p);
 
 		ent = __proc_device_tree_add_prop(de, pp, p);
-		if (ent == 0)
+		if (ent == NULL)
 			break;
 	}
 }
@@ -221,10 +221,10 @@
 	struct device_node *root;
 
 	proc_device_tree = proc_mkdir("device-tree", NULL);
-	if (proc_device_tree == 0)
+	if (proc_device_tree == NULL)
 		return;
 	root = of_find_node_by_path("/");
-	if (root == 0) {
+	if (root == NULL) {
 		printk(KERN_ERR "/proc/device-tree: can't find root\n");
 		return;
 	}
diff --git a/fs/proc/softirqs.c b/fs/proc/softirqs.c
new file mode 100644
index 0000000..1807c24
--- /dev/null
+++ b/fs/proc/softirqs.c
@@ -0,0 +1,44 @@
+#include <linux/init.h>
+#include <linux/kernel_stat.h>
+#include <linux/proc_fs.h>
+#include <linux/seq_file.h>
+
+/*
+ * /proc/softirqs  ... display the number of softirqs
+ */
+static int show_softirqs(struct seq_file *p, void *v)
+{
+	int i, j;
+
+	seq_printf(p, "                ");
+	for_each_possible_cpu(i)
+		seq_printf(p, "CPU%-8d", i);
+	seq_printf(p, "\n");
+
+	for (i = 0; i < NR_SOFTIRQS; i++) {
+		seq_printf(p, "%8s:", softirq_to_name[i]);
+		for_each_possible_cpu(j)
+			seq_printf(p, " %10u", kstat_softirqs_cpu(i, j));
+		seq_printf(p, "\n");
+	}
+	return 0;
+}
+
+static int softirqs_open(struct inode *inode, struct file *file)
+{
+	return single_open(file, show_softirqs, NULL);
+}
+
+static const struct file_operations proc_softirqs_operations = {
+	.open		= softirqs_open,
+	.read		= seq_read,
+	.llseek		= seq_lseek,
+	.release	= single_release,
+};
+
+static int __init proc_softirqs_init(void)
+{
+	proc_create("softirqs", 0, NULL, &proc_softirqs_operations);
+	return 0;
+}
+module_init(proc_softirqs_init);
diff --git a/fs/proc/stat.c b/fs/proc/stat.c
index 81e4eb6..7cc726c 100644
--- a/fs/proc/stat.c
+++ b/fs/proc/stat.c
@@ -29,6 +29,8 @@
 	cputime64_t user, nice, system, idle, iowait, irq, softirq, steal;
 	cputime64_t guest;
 	u64 sum = 0;
+	u64 sum_softirq = 0;
+	unsigned int per_softirq_sums[NR_SOFTIRQS] = {0};
 	struct timespec boottime;
 	unsigned int per_irq_sum;
 
@@ -53,6 +55,13 @@
 			sum += kstat_irqs_cpu(j, i);
 		}
 		sum += arch_irq_stat_cpu(i);
+
+		for (j = 0; j < NR_SOFTIRQS; j++) {
+			unsigned int softirq_stat = kstat_softirqs_cpu(j, i);
+
+			per_softirq_sums[j] += softirq_stat;
+			sum_softirq += softirq_stat;
+		}
 	}
 	sum += arch_irq_stat();
 
@@ -115,6 +124,12 @@
 		nr_running(),
 		nr_iowait());
 
+	seq_printf(p, "softirq %llu", (unsigned long long)sum_softirq);
+
+	for (i = 0; i < NR_SOFTIRQS; i++)
+		seq_printf(p, " %u", per_softirq_sums[i]);
+	seq_printf(p, "\n");
+
 	return 0;
 }
 
diff --git a/fs/proc/vmcore.c b/fs/proc/vmcore.c
index 5edcc3f..0872afa 100644
--- a/fs/proc/vmcore.c
+++ b/fs/proc/vmcore.c
@@ -166,12 +166,7 @@
 
 static struct vmcore* __init get_new_element(void)
 {
-	struct vmcore *p;
-
-	p = kmalloc(sizeof(*p), GFP_KERNEL);
-	if (p)
-		memset(p, 0, sizeof(*p));
-	return p;
+	return kzalloc(sizeof(struct vmcore), GFP_KERNEL);
 }
 
 static u64 __init get_vmcore_size_elf64(char *elfptr)
diff --git a/fs/reiserfs/do_balan.c b/fs/reiserfs/do_balan.c
index 4beb964..128d3f7 100644
--- a/fs/reiserfs/do_balan.c
+++ b/fs/reiserfs/do_balan.c
@@ -1270,9 +1270,8 @@
 
 					RFALSE(ih, "PAP-12210: ih must be 0");
 
-					if (is_direntry_le_ih
-					    (aux_ih =
-					     B_N_PITEM_HEAD(tbS0, item_pos))) {
+					aux_ih = B_N_PITEM_HEAD(tbS0, item_pos);
+					if (is_direntry_le_ih(aux_ih)) {
 						/* we append to directory item */
 
 						int entry_count;
diff --git a/fs/reiserfs/lbalance.c b/fs/reiserfs/lbalance.c
index 381750a..03d85cb 100644
--- a/fs/reiserfs/lbalance.c
+++ b/fs/reiserfs/lbalance.c
@@ -390,7 +390,8 @@
 
 	if (last_first == FIRST_TO_LAST) {
 		/* if ( if item in position item_num in buffer SOURCE is directory item ) */
-		if (is_direntry_le_ih(ih = B_N_PITEM_HEAD(src, item_num)))
+		ih = B_N_PITEM_HEAD(src, item_num);
+		if (is_direntry_le_ih(ih))
 			leaf_copy_dir_entries(dest_bi, src, FIRST_TO_LAST,
 					      item_num, 0, cpy_bytes);
 		else {
@@ -418,7 +419,8 @@
 		}
 	} else {
 		/*  if ( if item in position item_num in buffer SOURCE is directory item ) */
-		if (is_direntry_le_ih(ih = B_N_PITEM_HEAD(src, item_num)))
+		ih = B_N_PITEM_HEAD(src, item_num);
+		if (is_direntry_le_ih(ih))
 			leaf_copy_dir_entries(dest_bi, src, LAST_TO_FIRST,
 					      item_num,
 					      I_ENTRY_COUNT(ih) - cpy_bytes,
@@ -774,8 +776,8 @@
 			leaf_delete_items_entirely(cur_bi, first + 1,
 						   del_num - 1);
 
-			if (is_direntry_le_ih
-			    (ih = B_N_PITEM_HEAD(bh, B_NR_ITEMS(bh) - 1)))
+			ih = B_N_PITEM_HEAD(bh, B_NR_ITEMS(bh) - 1);
+			if (is_direntry_le_ih(ih))
 				/* the last item is directory  */
 				/* len = numbers of directory entries in this item */
 				len = ih_entry_count(ih);
diff --git a/fs/seq_file.c b/fs/seq_file.c
index 7f40f30c..6c95927 100644
--- a/fs/seq_file.c
+++ b/fs/seq_file.c
@@ -640,6 +640,26 @@
 }
 EXPORT_SYMBOL(seq_puts);
 
+/**
+ * seq_write - write arbitrary data to buffer
+ * @seq: seq_file identifying the buffer to which data should be written
+ * @data: data address
+ * @len: number of bytes
+ *
+ * Return 0 on success, non-zero otherwise.
+ */
+int seq_write(struct seq_file *seq, const void *data, size_t len)
+{
+	if (seq->count + len < seq->size) {
+		memcpy(seq->buf + seq->count, data, len);
+		seq->count += len;
+		return 0;
+	}
+	seq->count = seq->size;
+	return -1;
+}
+EXPORT_SYMBOL(seq_write);
+
 struct list_head *seq_list_start(struct list_head *head, loff_t pos)
 {
 	struct list_head *lh;
diff --git a/fs/super.c b/fs/super.c
index 83b47416..d40d53a 100644
--- a/fs/super.c
+++ b/fs/super.c
@@ -545,24 +545,18 @@
 	if ((flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY)) {
 		if (force)
 			mark_files_ro(sb);
-		else if (!fs_may_remount_ro(sb)) {
-			unlock_kernel();
+		else if (!fs_may_remount_ro(sb))
 			return -EBUSY;
-		}
 		retval = vfs_dq_off(sb, 1);
-		if (retval < 0 && retval != -ENOSYS) {
-			unlock_kernel();
+		if (retval < 0 && retval != -ENOSYS)
 			return -EBUSY;
-		}
 	}
 	remount_rw = !(flags & MS_RDONLY) && (sb->s_flags & MS_RDONLY);
 
 	if (sb->s_op->remount_fs) {
 		retval = sb->s_op->remount_fs(sb, &flags, data);
-		if (retval) {
-			unlock_kernel();
+		if (retval)
 			return retval;
-		}
 	}
 	sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK);
 	if (remount_rw)
diff --git a/fs/sysv/dir.c b/fs/sysv/dir.c
index c779807..4e50286 100644
--- a/fs/sysv/dir.c
+++ b/fs/sysv/dir.c
@@ -15,13 +15,13 @@
 
 #include <linux/pagemap.h>
 #include <linux/highmem.h>
-#include <linux/smp_lock.h>
 #include <linux/swap.h>
 #include "sysv.h"
 
 static int sysv_readdir(struct file *, void *, filldir_t);
 
 const struct file_operations sysv_dir_operations = {
+	.llseek		= generic_file_llseek,
 	.read		= generic_read_dir,
 	.readdir	= sysv_readdir,
 	.fsync		= simple_fsync,
@@ -74,8 +74,6 @@
 	unsigned long n = pos >> PAGE_CACHE_SHIFT;
 	unsigned long npages = dir_pages(inode);
 
-	lock_kernel();
-
 	pos = (pos + SYSV_DIRSIZE-1) & ~(SYSV_DIRSIZE-1);
 	if (pos >= inode->i_size)
 		goto done;
@@ -113,7 +111,6 @@
 
 done:
 	filp->f_pos = ((loff_t)n << PAGE_CACHE_SHIFT) | offset;
-	unlock_kernel();
 	return 0;
 }
 
diff --git a/fs/sysv/inode.c b/fs/sysv/inode.c
index 4799234..9824743 100644
--- a/fs/sysv/inode.c
+++ b/fs/sysv/inode.c
@@ -21,7 +21,6 @@
  *  the superblock.
  */
 
-#include <linux/smp_lock.h>
 #include <linux/highuid.h>
 #include <linux/slab.h>
 #include <linux/init.h>
@@ -37,7 +36,6 @@
 	unsigned long time = get_seconds(), old_time;
 
 	lock_super(sb);
-	lock_kernel();
 
 	/*
 	 * If we are going to write out the super block,
@@ -52,7 +50,6 @@
 		mark_buffer_dirty(sbi->s_bh2);
 	}
 
-	unlock_kernel();
 	unlock_super(sb);
 
 	return 0;
@@ -82,8 +79,6 @@
 {
 	struct sysv_sb_info *sbi = SYSV_SB(sb);
 
-	lock_kernel();
-
 	if (sb->s_dirt)
 		sysv_write_super(sb);
 
@@ -99,8 +94,6 @@
 		brelse(sbi->s_bh2);
 
 	kfree(sbi);
-
-	unlock_kernel();
 }
 
 static int sysv_statfs(struct dentry *dentry, struct kstatfs *buf)
@@ -275,7 +268,6 @@
 		return -EIO;
 	}
 
-	lock_kernel();
 	raw_inode->i_mode = cpu_to_fs16(sbi, inode->i_mode);
 	raw_inode->i_uid = cpu_to_fs16(sbi, fs_high2lowuid(inode->i_uid));
 	raw_inode->i_gid = cpu_to_fs16(sbi, fs_high2lowgid(inode->i_gid));
@@ -291,7 +283,6 @@
 	for (block = 0; block < 10+1+1+1; block++)
 		write3byte(sbi, (u8 *)&si->i_data[block],
 			&raw_inode->i_data[3*block]);
-	unlock_kernel();
 	mark_buffer_dirty(bh);
 	if (wait) {
                 sync_dirty_buffer(bh);
@@ -315,9 +306,7 @@
 	truncate_inode_pages(&inode->i_data, 0);
 	inode->i_size = 0;
 	sysv_truncate(inode);
-	lock_kernel();
 	sysv_free_inode(inode);
-	unlock_kernel();
 }
 
 static struct kmem_cache *sysv_inode_cachep;
diff --git a/fs/ubifs/budget.c b/fs/ubifs/budget.c
index af19144..eaf6d89 100644
--- a/fs/ubifs/budget.c
+++ b/fs/ubifs/budget.c
@@ -91,7 +91,6 @@
 	return nr_written;
 }
 
-
 /**
  * run_gc - run garbage collector.
  * @c: UBIFS file-system description object
@@ -628,7 +627,7 @@
  *
  * This function releases budget corresponding to a dirty inode. It is usually
  * called when after the inode has been written to the media and marked as
- * clean.
+ * clean. It also causes the "no space" flags to be cleared.
  */
 void ubifs_release_dirty_inode_budget(struct ubifs_info *c,
 				      struct ubifs_inode *ui)
@@ -636,6 +635,7 @@
 	struct ubifs_budget_req req;
 
 	memset(&req, 0, sizeof(struct ubifs_budget_req));
+	/* The "no space" flags will be cleared because dd_growth is > 0 */
 	req.dd_growth = c->inode_budget + ALIGN(ui->data_len, 8);
 	ubifs_release_budget(c, &req);
 }
diff --git a/fs/ubifs/dir.c b/fs/ubifs/dir.c
index f55d523..552fb01 100644
--- a/fs/ubifs/dir.c
+++ b/fs/ubifs/dir.c
@@ -528,6 +528,25 @@
 		inode->i_nlink, dir->i_ino);
 	ubifs_assert(mutex_is_locked(&dir->i_mutex));
 	ubifs_assert(mutex_is_locked(&inode->i_mutex));
+
+	/*
+	 * Return -ENOENT if we've raced with unlink and i_nlink is 0.  Doing
+	 * otherwise has the potential to corrupt the orphan inode list.
+	 *
+	 * Indeed, consider a scenario when 'vfs_link(dirA/fileA)' and
+	 * 'vfs_unlink(dirA/fileA, dirB/fileB)' race. 'vfs_link()' does not
+	 * lock 'dirA->i_mutex', so this is possible. Both of the functions
+	 * lock 'fileA->i_mutex' though. Suppose 'vfs_unlink()' wins, and takes
+	 * 'fileA->i_mutex' mutex first. Suppose 'fileA->i_nlink' is 1. In this
+	 * case 'ubifs_unlink()' will drop the last reference, and put 'inodeA'
+	 * to the list of orphans. After this, 'vfs_link()' will link
+	 * 'dirB/fileB' to 'inodeA'. This is a problem because, for example,
+	 * the subsequent 'vfs_unlink(dirB/fileB)' will add the same inode
+	 * to the list of orphans.
+	 */
+	 if (inode->i_nlink == 0)
+		 return -ENOENT;
+
 	err = dbg_check_synced_i_size(inode);
 	if (err)
 		return err;
diff --git a/fs/ubifs/io.c b/fs/ubifs/io.c
index e8e632a..bc58571 100644
--- a/fs/ubifs/io.c
+++ b/fs/ubifs/io.c
@@ -293,13 +293,14 @@
  *
  * This function is called when the write-buffer timer expires.
  */
-static void wbuf_timer_callback_nolock(unsigned long data)
+static enum hrtimer_restart wbuf_timer_callback_nolock(struct hrtimer *timer)
 {
-	struct ubifs_wbuf *wbuf = (struct ubifs_wbuf *)data;
+	struct ubifs_wbuf *wbuf = container_of(timer, struct ubifs_wbuf, timer);
 
 	wbuf->need_sync = 1;
 	wbuf->c->need_wbuf_sync = 1;
 	ubifs_wake_up_bgt(wbuf->c);
+	return HRTIMER_NORESTART;
 }
 
 /**
@@ -308,13 +309,12 @@
  */
 static void new_wbuf_timer_nolock(struct ubifs_wbuf *wbuf)
 {
-	ubifs_assert(!timer_pending(&wbuf->timer));
+	ubifs_assert(!hrtimer_active(&wbuf->timer));
 
-	if (!wbuf->timeout)
+	if (!ktime_to_ns(wbuf->softlimit))
 		return;
-
-	wbuf->timer.expires = jiffies + wbuf->timeout;
-	add_timer(&wbuf->timer);
+	hrtimer_start_range_ns(&wbuf->timer, wbuf->softlimit, wbuf->delta,
+			       HRTIMER_MODE_REL);
 }
 
 /**
@@ -329,7 +329,7 @@
 	 * should be canceled.
 	 */
 	wbuf->need_sync = 0;
-	del_timer(&wbuf->timer);
+	hrtimer_cancel(&wbuf->timer);
 }
 
 /**
@@ -825,6 +825,7 @@
 int ubifs_wbuf_init(struct ubifs_info *c, struct ubifs_wbuf *wbuf)
 {
 	size_t size;
+	ktime_t hardlimit;
 
 	wbuf->buf = kmalloc(c->min_io_size, GFP_KERNEL);
 	if (!wbuf->buf)
@@ -845,14 +846,21 @@
 	wbuf->sync_callback = NULL;
 	mutex_init(&wbuf->io_mutex);
 	spin_lock_init(&wbuf->lock);
-
 	wbuf->c = c;
-	init_timer(&wbuf->timer);
-	wbuf->timer.function = wbuf_timer_callback_nolock;
-	wbuf->timer.data = (unsigned long)wbuf;
-	wbuf->timeout = DEFAULT_WBUF_TIMEOUT;
 	wbuf->next_ino = 0;
 
+	hrtimer_init(&wbuf->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
+	wbuf->timer.function = wbuf_timer_callback_nolock;
+	/*
+	 * Make write-buffer soft limit to be 20% of the hard limit. The
+	 * write-buffer timer is allowed to expire any time between the soft
+	 * and hard limits.
+	 */
+	hardlimit = ktime_set(DEFAULT_WBUF_TIMEOUT_SECS, 0);
+	wbuf->delta = (DEFAULT_WBUF_TIMEOUT_SECS * NSEC_PER_SEC) * 2 / 10;
+	wbuf->softlimit = ktime_sub_ns(hardlimit, wbuf->delta);
+	hrtimer_set_expires_range_ns(&wbuf->timer,  wbuf->softlimit,
+				     wbuf->delta);
 	return 0;
 }
 
diff --git a/fs/ubifs/recovery.c b/fs/ubifs/recovery.c
index 1066297..8056052 100644
--- a/fs/ubifs/recovery.c
+++ b/fs/ubifs/recovery.c
@@ -343,33 +343,15 @@
  *
  * This function returns %1 if @offs was in the last write to the LEB whose data
  * is in @buf, otherwise %0 is returned.  The determination is made by checking
- * for subsequent empty space starting from the next min_io_size boundary (or a
- * bit less than the common header size if min_io_size is one).
+ * for subsequent empty space starting from the next @c->min_io_size boundary.
  */
 static int is_last_write(const struct ubifs_info *c, void *buf, int offs)
 {
-	int empty_offs;
-	int check_len;
+	int empty_offs, check_len;
 	uint8_t *p;
 
-	if (c->min_io_size == 1) {
-		check_len = c->leb_size - offs;
-		p = buf + check_len;
-		for (; check_len > 0; check_len--)
-			if (*--p != 0xff)
-				break;
-		/*
-		 * 'check_len' is the size of the corruption which cannot be
-		 * more than the size of 1 node if it was caused by an unclean
-		 * unmount.
-		 */
-		if (check_len > UBIFS_MAX_NODE_SZ)
-			return 0;
-		return 1;
-	}
-
 	/*
-	 * Round up to the next c->min_io_size boundary i.e. 'offs' is in the
+	 * Round up to the next @c->min_io_size boundary i.e. @offs is in the
 	 * last wbuf written. After that should be empty space.
 	 */
 	empty_offs = ALIGN(offs + 1, c->min_io_size);
@@ -392,7 +374,7 @@
  *
  * This function pads up to the next min_io_size boundary (if there is one) and
  * sets empty space to all 0xff. @buf, @offs and @len are updated to the next
- * min_io_size boundary (if there is one).
+ * @c->min_io_size boundary.
  */
 static void clean_buf(const struct ubifs_info *c, void **buf, int lnum,
 		      int *offs, int *len)
@@ -402,11 +384,6 @@
 	lnum = lnum;
 	dbg_rcvry("cleaning corruption at %d:%d", lnum, *offs);
 
-	if (c->min_io_size == 1) {
-		memset(*buf, 0xff, c->leb_size - *offs);
-		return;
-	}
-
 	ubifs_assert(!(*offs & 7));
 	empty_offs = ALIGN(*offs, c->min_io_size);
 	pad_len = empty_offs - *offs;
diff --git a/fs/ubifs/super.c b/fs/ubifs/super.c
index 3260b73..79fad43 100644
--- a/fs/ubifs/super.c
+++ b/fs/ubifs/super.c
@@ -361,6 +361,11 @@
 out:
 	if (ui->dirty)
 		ubifs_release_dirty_inode_budget(c, ui);
+	else {
+		/* We've deleted something - clean the "no space" flags */
+		c->nospace = c->nospace_rp = 0;
+		smp_wmb();
+	}
 	clear_inode(inode);
 }
 
@@ -792,7 +797,7 @@
 	 * does not need to be synchronized by timer.
 	 */
 	c->jheads[GCHD].wbuf.dtype = UBI_LONGTERM;
-	c->jheads[GCHD].wbuf.timeout = 0;
+	c->jheads[GCHD].wbuf.softlimit = ktime_set(0, 0);
 
 	return 0;
 }
@@ -933,6 +938,27 @@
 };
 
 /**
+ * parse_standard_option - parse a standard mount option.
+ * @option: the option to parse
+ *
+ * Normally, standard mount options like "sync" are passed to file-systems as
+ * flags. However, when a "rootflags=" kernel boot parameter is used, they may
+ * be present in the options string. This function tries to deal with this
+ * situation and parse standard options. Returns 0 if the option was not
+ * recognized, and the corresponding integer flag if it was.
+ *
+ * UBIFS is only interested in the "sync" option, so do not check for anything
+ * else.
+ */
+static int parse_standard_option(const char *option)
+{
+	ubifs_msg("parse %s", option);
+	if (!strcmp(option, "sync"))
+		return MS_SYNCHRONOUS;
+	return 0;
+}
+
+/**
  * ubifs_parse_options - parse mount parameters.
  * @c: UBIFS file-system description object
  * @options: parameters to parse
@@ -1008,9 +1034,19 @@
 			break;
 		}
 		default:
-			ubifs_err("unrecognized mount option \"%s\" "
-				  "or missing value", p);
-			return -EINVAL;
+		{
+			unsigned long flag;
+			struct super_block *sb = c->vfs_sb;
+
+			flag = parse_standard_option(p);
+			if (!flag) {
+				ubifs_err("unrecognized mount option \"%s\" "
+					  "or missing value", p);
+				return -EINVAL;
+			}
+			sb->s_flags |= flag;
+			break;
+		}
 		}
 	}
 
@@ -1180,6 +1216,7 @@
 	if (!ubifs_compr_present(c->default_compr)) {
 		ubifs_err("'compressor \"%s\" is not compiled in",
 			  ubifs_compr_name(c->default_compr));
+		err = -ENOTSUPP;
 		goto out_free;
 	}
 
@@ -1656,7 +1693,7 @@
 
 	for (i = 0; i < c->jhead_cnt; i++) {
 		ubifs_wbuf_sync(&c->jheads[i].wbuf);
-		del_timer_sync(&c->jheads[i].wbuf.timer);
+		hrtimer_cancel(&c->jheads[i].wbuf.timer);
 	}
 
 	c->mst_node->flags &= ~cpu_to_le32(UBIFS_MST_DIRTY);
@@ -1719,7 +1756,7 @@
 		if (c->jheads)
 			for (i = 0; i < c->jhead_cnt; i++) {
 				ubifs_wbuf_sync(&c->jheads[i].wbuf);
-				del_timer_sync(&c->jheads[i].wbuf.timer);
+				hrtimer_cancel(&c->jheads[i].wbuf.timer);
 			}
 
 		/*
@@ -1911,6 +1948,7 @@
 	INIT_LIST_HEAD(&c->orph_list);
 	INIT_LIST_HEAD(&c->orph_new);
 
+	c->vfs_sb = sb;
 	c->highest_inum = UBIFS_FIRST_INO;
 	c->lhead_lnum = c->ltail_lnum = UBIFS_LOG_LNUM;
 
@@ -1945,13 +1983,10 @@
 	if (err)
 		goto out_bdi;
 
-	c->vfs_sb = sb;
-
 	sb->s_fs_info = c;
 	sb->s_magic = UBIFS_SUPER_MAGIC;
 	sb->s_blocksize = UBIFS_BLOCK_SIZE;
 	sb->s_blocksize_bits = UBIFS_BLOCK_SHIFT;
-	sb->s_dev = c->vi.cdev;
 	sb->s_maxbytes = c->max_inode_sz = key_max_inode_size(c);
 	if (c->max_inode_sz > MAX_LFS_FILESIZE)
 		sb->s_maxbytes = c->max_inode_sz = MAX_LFS_FILESIZE;
@@ -1996,16 +2031,9 @@
 static int sb_test(struct super_block *sb, void *data)
 {
 	dev_t *dev = data;
+	struct ubifs_info *c = sb->s_fs_info;
 
-	return sb->s_dev == *dev;
-}
-
-static int sb_set(struct super_block *sb, void *data)
-{
-	dev_t *dev = data;
-
-	sb->s_dev = *dev;
-	return 0;
+	return c->vi.cdev == *dev;
 }
 
 static int ubifs_get_sb(struct file_system_type *fs_type, int flags,
@@ -2033,7 +2061,7 @@
 
 	dbg_gen("opened ubi%d_%d", vi.ubi_num, vi.vol_id);
 
-	sb = sget(fs_type, &sb_test, &sb_set, &vi.cdev);
+	sb = sget(fs_type, &sb_test, &set_anon_super, &vi.cdev);
 	if (IS_ERR(sb)) {
 		err = PTR_ERR(sb);
 		goto out_close;
@@ -2073,16 +2101,11 @@
 	return err;
 }
 
-static void ubifs_kill_sb(struct super_block *sb)
-{
-	generic_shutdown_super(sb);
-}
-
 static struct file_system_type ubifs_fs_type = {
 	.name    = "ubifs",
 	.owner   = THIS_MODULE,
 	.get_sb  = ubifs_get_sb,
-	.kill_sb = ubifs_kill_sb
+	.kill_sb = kill_anon_super,
 };
 
 /*
diff --git a/fs/ubifs/ubifs.h b/fs/ubifs/ubifs.h
index 0a8341e..1bf01d8 100644
--- a/fs/ubifs/ubifs.h
+++ b/fs/ubifs/ubifs.h
@@ -95,8 +95,8 @@
  */
 #define BGT_NAME_PATTERN "ubifs_bgt%d_%d"
 
-/* Default write-buffer synchronization timeout (5 secs) */
-#define DEFAULT_WBUF_TIMEOUT (5 * HZ)
+/* Default write-buffer synchronization timeout in seconds */
+#define DEFAULT_WBUF_TIMEOUT_SECS 5
 
 /* Maximum possible inode number (only 32-bit inodes are supported now) */
 #define MAX_INUM 0xFFFFFFFF
@@ -650,8 +650,10 @@
  * @io_mutex: serializes write-buffer I/O
  * @lock: serializes @buf, @lnum, @offs, @avail, @used, @next_ino and @inodes
  *        fields
+ * @softlimit: soft write-buffer timeout interval
+ * @delta: hard and soft timeouts delta (the timer expire inteval is @softlimit
+ *         and @softlimit + @delta)
  * @timer: write-buffer timer
- * @timeout: timer expire interval in jiffies
  * @need_sync: it is set if its timer expired and needs sync
  * @next_ino: points to the next position of the following inode number
  * @inodes: stores the inode numbers of the nodes which are in wbuf
@@ -678,8 +680,9 @@
 	int (*sync_callback)(struct ubifs_info *c, int lnum, int free, int pad);
 	struct mutex io_mutex;
 	spinlock_t lock;
-	struct timer_list timer;
-	int timeout;
+	ktime_t softlimit;
+	unsigned long long delta;
+	struct hrtimer timer;
 	int need_sync;
 	int next_ino;
 	ino_t *inodes;
diff --git a/fs/ufs/inode.c b/fs/ufs/inode.c
index 3d2512c..7cf3337 100644
--- a/fs/ufs/inode.c
+++ b/fs/ufs/inode.c
@@ -56,9 +56,7 @@
 
 
 	UFSD("ptrs=uspi->s_apb = %d,double_blocks=%ld \n",ptrs,double_blocks);
-	if (i_block < 0) {
-		ufs_warning(inode->i_sb, "ufs_block_to_path", "block < 0");
-	} else if (i_block < direct_blocks) {
+	if (i_block < direct_blocks) {
 		offsets[n++] = i_block;
 	} else if ((i_block -= direct_blocks) < indirect_blocks) {
 		offsets[n++] = UFS_IND_BLOCK;
@@ -440,8 +438,6 @@
 	lock_kernel();
 
 	UFSD("ENTER, ino %lu, fragment %llu\n", inode->i_ino, (unsigned long long)fragment);
-	if (fragment < 0)
-		goto abort_negative;
 	if (fragment >
 	    ((UFS_NDADDR + uspi->s_apb + uspi->s_2apb + uspi->s_3apb)
 	     << uspi->s_fpbshift))
@@ -504,10 +500,6 @@
 	unlock_kernel();
 	return err;
 
-abort_negative:
-	ufs_warning(sb, "ufs_get_block", "block < 0");
-	goto abort;
-
 abort_too_big:
 	ufs_warning(sb, "ufs_get_block", "block > big");
 	goto abort;
diff --git a/fs/xfs/linux-2.6/xfs_linux.h b/fs/xfs/linux-2.6/xfs_linux.h
index f65a53f..6127e24 100644
--- a/fs/xfs/linux-2.6/xfs_linux.h
+++ b/fs/xfs/linux-2.6/xfs_linux.h
@@ -24,7 +24,7 @@
  * XFS_BIG_BLKNOS needs block layer disk addresses to be 64 bits.
  * XFS_BIG_INUMS requires XFS_BIG_BLKNOS to be set.
  */
-#if defined(CONFIG_LBD) || (BITS_PER_LONG == 64)
+#if defined(CONFIG_LBDAF) || (BITS_PER_LONG == 64)
 # define XFS_BIG_BLKNOS	1
 # define XFS_BIG_INUMS	1
 #else
diff --git a/fs/xfs/linux-2.6/xfs_super.c b/fs/xfs/linux-2.6/xfs_super.c
index 2e09efb..a220d36 100644
--- a/fs/xfs/linux-2.6/xfs_super.c
+++ b/fs/xfs/linux-2.6/xfs_super.c
@@ -616,7 +616,7 @@
 	 */
 
 #if BITS_PER_LONG == 32
-# if defined(CONFIG_LBD)
+# if defined(CONFIG_LBDAF)
 	ASSERT(sizeof(sector_t) == 8);
 	pagefactor = PAGE_CACHE_SIZE;
 	bitshift = BITS_PER_LONG;
diff --git a/include/Kbuild b/include/Kbuild
index fe36acc..8d226bf 100644
--- a/include/Kbuild
+++ b/include/Kbuild
@@ -9,3 +9,4 @@
 header-y += video/
 header-y += drm/
 header-y += xen/
+header-y += scsi/
diff --git a/include/asm-generic/dma-mapping-common.h b/include/asm-generic/dma-mapping-common.h
new file mode 100644
index 0000000..5406a60
--- /dev/null
+++ b/include/asm-generic/dma-mapping-common.h
@@ -0,0 +1,190 @@
+#ifndef _ASM_GENERIC_DMA_MAPPING_H
+#define _ASM_GENERIC_DMA_MAPPING_H
+
+#include <linux/kmemcheck.h>
+#include <linux/scatterlist.h>
+#include <linux/dma-debug.h>
+#include <linux/dma-attrs.h>
+
+static inline dma_addr_t dma_map_single_attrs(struct device *dev, void *ptr,
+					      size_t size,
+					      enum dma_data_direction dir,
+					      struct dma_attrs *attrs)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+	dma_addr_t addr;
+
+	kmemcheck_mark_initialized(ptr, size);
+	BUG_ON(!valid_dma_direction(dir));
+	addr = ops->map_page(dev, virt_to_page(ptr),
+			     (unsigned long)ptr & ~PAGE_MASK, size,
+			     dir, attrs);
+	debug_dma_map_page(dev, virt_to_page(ptr),
+			   (unsigned long)ptr & ~PAGE_MASK, size,
+			   dir, addr, true);
+	return addr;
+}
+
+static inline void dma_unmap_single_attrs(struct device *dev, dma_addr_t addr,
+					  size_t size,
+					  enum dma_data_direction dir,
+					  struct dma_attrs *attrs)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+
+	BUG_ON(!valid_dma_direction(dir));
+	if (ops->unmap_page)
+		ops->unmap_page(dev, addr, size, dir, attrs);
+	debug_dma_unmap_page(dev, addr, size, dir, true);
+}
+
+static inline int dma_map_sg_attrs(struct device *dev, struct scatterlist *sg,
+				   int nents, enum dma_data_direction dir,
+				   struct dma_attrs *attrs)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+	int i, ents;
+	struct scatterlist *s;
+
+	for_each_sg(sg, s, nents, i)
+		kmemcheck_mark_initialized(sg_virt(s), s->length);
+	BUG_ON(!valid_dma_direction(dir));
+	ents = ops->map_sg(dev, sg, nents, dir, attrs);
+	debug_dma_map_sg(dev, sg, nents, ents, dir);
+
+	return ents;
+}
+
+static inline void dma_unmap_sg_attrs(struct device *dev, struct scatterlist *sg,
+				      int nents, enum dma_data_direction dir,
+				      struct dma_attrs *attrs)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+
+	BUG_ON(!valid_dma_direction(dir));
+	debug_dma_unmap_sg(dev, sg, nents, dir);
+	if (ops->unmap_sg)
+		ops->unmap_sg(dev, sg, nents, dir, attrs);
+}
+
+static inline dma_addr_t dma_map_page(struct device *dev, struct page *page,
+				      size_t offset, size_t size,
+				      enum dma_data_direction dir)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+	dma_addr_t addr;
+
+	kmemcheck_mark_initialized(page_address(page) + offset, size);
+	BUG_ON(!valid_dma_direction(dir));
+	addr = ops->map_page(dev, page, offset, size, dir, NULL);
+	debug_dma_map_page(dev, page, offset, size, dir, addr, false);
+
+	return addr;
+}
+
+static inline void dma_unmap_page(struct device *dev, dma_addr_t addr,
+				  size_t size, enum dma_data_direction dir)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+
+	BUG_ON(!valid_dma_direction(dir));
+	if (ops->unmap_page)
+		ops->unmap_page(dev, addr, size, dir, NULL);
+	debug_dma_unmap_page(dev, addr, size, dir, false);
+}
+
+static inline void dma_sync_single_for_cpu(struct device *dev, dma_addr_t addr,
+					   size_t size,
+					   enum dma_data_direction dir)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+
+	BUG_ON(!valid_dma_direction(dir));
+	if (ops->sync_single_for_cpu)
+		ops->sync_single_for_cpu(dev, addr, size, dir);
+	debug_dma_sync_single_for_cpu(dev, addr, size, dir);
+	flush_write_buffers();
+}
+
+static inline void dma_sync_single_for_device(struct device *dev,
+					      dma_addr_t addr, size_t size,
+					      enum dma_data_direction dir)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+
+	BUG_ON(!valid_dma_direction(dir));
+	if (ops->sync_single_for_device)
+		ops->sync_single_for_device(dev, addr, size, dir);
+	debug_dma_sync_single_for_device(dev, addr, size, dir);
+	flush_write_buffers();
+}
+
+static inline void dma_sync_single_range_for_cpu(struct device *dev,
+						 dma_addr_t addr,
+						 unsigned long offset,
+						 size_t size,
+						 enum dma_data_direction dir)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+
+	BUG_ON(!valid_dma_direction(dir));
+	if (ops->sync_single_range_for_cpu) {
+		ops->sync_single_range_for_cpu(dev, addr, offset, size, dir);
+		debug_dma_sync_single_range_for_cpu(dev, addr, offset, size, dir);
+
+		flush_write_buffers();
+	} else
+		dma_sync_single_for_cpu(dev, addr, size, dir);
+}
+
+static inline void dma_sync_single_range_for_device(struct device *dev,
+						    dma_addr_t addr,
+						    unsigned long offset,
+						    size_t size,
+						    enum dma_data_direction dir)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+
+	BUG_ON(!valid_dma_direction(dir));
+	if (ops->sync_single_range_for_device) {
+		ops->sync_single_range_for_device(dev, addr, offset, size, dir);
+		debug_dma_sync_single_range_for_device(dev, addr, offset, size, dir);
+
+		flush_write_buffers();
+	} else
+		dma_sync_single_for_device(dev, addr, size, dir);
+}
+
+static inline void
+dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
+		    int nelems, enum dma_data_direction dir)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+
+	BUG_ON(!valid_dma_direction(dir));
+	if (ops->sync_sg_for_cpu)
+		ops->sync_sg_for_cpu(dev, sg, nelems, dir);
+	debug_dma_sync_sg_for_cpu(dev, sg, nelems, dir);
+	flush_write_buffers();
+}
+
+static inline void
+dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
+		       int nelems, enum dma_data_direction dir)
+{
+	struct dma_map_ops *ops = get_dma_ops(dev);
+
+	BUG_ON(!valid_dma_direction(dir));
+	if (ops->sync_sg_for_device)
+		ops->sync_sg_for_device(dev, sg, nelems, dir);
+	debug_dma_sync_sg_for_device(dev, sg, nelems, dir);
+
+	flush_write_buffers();
+}
+
+#define dma_map_single(d, a, s, r) dma_map_single_attrs(d, a, s, r, NULL)
+#define dma_unmap_single(d, a, s, r) dma_unmap_single_attrs(d, a, s, r, NULL)
+#define dma_map_sg(d, s, n, r) dma_map_sg_attrs(d, s, n, r, NULL)
+#define dma_unmap_sg(d, s, n, r) dma_unmap_sg_attrs(d, s, n, r, NULL)
+
+#endif
diff --git a/include/asm-generic/pci.h b/include/asm-generic/pci.h
index 515c6e2..b4326b5 100644
--- a/include/asm-generic/pci.h
+++ b/include/asm-generic/pci.h
@@ -30,19 +30,6 @@
 	res->end = region->end;
 }
 
-static inline struct resource *
-pcibios_select_root(struct pci_dev *pdev, struct resource *res)
-{
-	struct resource *root = NULL;
-
-	if (res->flags & IORESOURCE_IO)
-		root = &ioport_resource;
-	if (res->flags & IORESOURCE_MEM)
-		root = &iomem_resource;
-
-	return root;
-}
-
 #define pcibios_scan_all_fns(a, b)	0
 
 #ifndef HAVE_ARCH_PCI_GET_LEGACY_IDE_IRQ
diff --git a/include/asm-generic/sections.h b/include/asm-generic/sections.h
index 4ce48e8..d083561 100644
--- a/include/asm-generic/sections.h
+++ b/include/asm-generic/sections.h
@@ -14,6 +14,9 @@
 extern char __initdata_begin[], __initdata_end[];
 extern char __start_rodata[], __end_rodata[];
 
+/* Start and end of .ctors section - used for constructor calls. */
+extern char __ctors_start[], __ctors_end[];
+
 /* function descriptor handling (if any).  Override
  * in asm/sections.h */
 #ifndef dereference_function_descriptor
diff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h
index 6bdba10..55413e5 100644
--- a/include/asm-generic/vmlinux.lds.h
+++ b/include/asm-generic/vmlinux.lds.h
@@ -440,12 +440,21 @@
 		INIT_TASK						\
 	}
 
+#ifdef CONFIG_CONSTRUCTORS
+#define KERNEL_CTORS()	VMLINUX_SYMBOL(__ctors_start) = .; \
+			*(.ctors)			   \
+			VMLINUX_SYMBOL(__ctors_end) = .;
+#else
+#define KERNEL_CTORS()
+#endif
+
 /* init and exit section handling */
 #define INIT_DATA							\
 	*(.init.data)							\
 	DEV_DISCARD(init.data)						\
 	CPU_DISCARD(init.data)						\
 	MEM_DISCARD(init.data)						\
+	KERNEL_CTORS()							\
 	*(.init.rodata)							\
 	DEV_DISCARD(init.rodata)					\
 	CPU_DISCARD(init.rodata)					\
diff --git a/include/drm/drmP.h b/include/drm/drmP.h
index d4ddc22..45b67d9 100644
--- a/include/drm/drmP.h
+++ b/include/drm/drmP.h
@@ -34,9 +34,6 @@
 #ifndef _DRM_P_H_
 #define _DRM_P_H_
 
-/* If you want the memory alloc debug functionality, change define below */
-/* #define DEBUG_MEMORY */
-
 #ifdef __KERNEL__
 #ifdef __alpha__
 /* add include of current.h so that "current" is defined
@@ -133,31 +130,6 @@
 
 #define DRM_FLAG_DEBUG	  0x01
 
-#define DRM_MEM_DMA	   0
-#define DRM_MEM_SAREA	   1
-#define DRM_MEM_DRIVER	   2
-#define DRM_MEM_MAGIC	   3
-#define DRM_MEM_IOCTLS	   4
-#define DRM_MEM_MAPS	   5
-#define DRM_MEM_VMAS	   6
-#define DRM_MEM_BUFS	   7
-#define DRM_MEM_SEGS	   8
-#define DRM_MEM_PAGES	   9
-#define DRM_MEM_FILES	  10
-#define DRM_MEM_QUEUES	  11
-#define DRM_MEM_CMDS	  12
-#define DRM_MEM_MAPPINGS  13
-#define DRM_MEM_BUFLISTS  14
-#define DRM_MEM_AGPLISTS  15
-#define DRM_MEM_TOTALAGP  16
-#define DRM_MEM_BOUNDAGP  17
-#define DRM_MEM_CTXBITMAP 18
-#define DRM_MEM_STUB      19
-#define DRM_MEM_SGLISTS   20
-#define DRM_MEM_CTXLIST   21
-#define DRM_MEM_MM        22
-#define DRM_MEM_HASHTAB   23
-
 #define DRM_MAX_CTXBITMAP (PAGE_SIZE * 8)
 #define DRM_MAP_HASH_OFFSET 0x10000000
 
@@ -1517,24 +1489,6 @@
 {
 }
 
-#ifndef DEBUG_MEMORY
-/** Wrapper around kmalloc() */
-static __inline__ void *drm_alloc(size_t size, int area)
-{
-	return kmalloc(size, GFP_KERNEL);
-}
-
-/** Wrapper around kfree() */
-static __inline__ void drm_free(void *pt, size_t size, int area)
-{
-	kfree(pt);
-}
-
-/** Wrapper around kcalloc() */
-static __inline__ void *drm_calloc(size_t nmemb, size_t size, int area)
-{
-	return kcalloc(nmemb, size, GFP_KERNEL);
-}
 
 static __inline__ void *drm_calloc_large(size_t nmemb, size_t size)
 {
@@ -1555,12 +1509,6 @@
 
 	vfree(ptr);
 }
-#else
-extern void *drm_alloc(size_t size, int area);
-extern void drm_free(void *pt, size_t size, int area);
-extern void *drm_calloc(size_t nmemb, size_t size, int area);
-#endif
-
 /*@}*/
 
 #endif				/* __KERNEL__ */
diff --git a/include/drm/drm_edid.h b/include/drm/drm_edid.h
index a11cc9d..c263e4d 100644
--- a/include/drm/drm_edid.h
+++ b/include/drm/drm_edid.h
@@ -28,53 +28,49 @@
 #define EDID_LENGTH 128
 #define DDC_ADDR 0x50
 
-#ifdef BIG_ENDIAN
-#error "EDID structure is little endian, need big endian versions"
-#else
-
 struct est_timings {
 	u8 t1;
 	u8 t2;
 	u8 mfg_rsvd;
 } __attribute__((packed));
 
+/* 00=16:10, 01=4:3, 10=5:4, 11=16:9 */
+#define EDID_TIMING_ASPECT_SHIFT 0
+#define EDID_TIMING_ASPECT_MASK  (0x3 << EDID_TIMING_ASPECT_SHIFT)
+
+/* need to add 60 */
+#define EDID_TIMING_VFREQ_SHIFT  2
+#define EDID_TIMING_VFREQ_MASK   (0x3f << EDID_TIMING_VFREQ_SHIFT)
+
 struct std_timing {
 	u8 hsize; /* need to multiply by 8 then add 248 */
-	u8 vfreq:6; /* need to add 60 */
-	u8 aspect_ratio:2; /* 00=16:10, 01=4:3, 10=5:4, 11=16:9 */
+	u8 vfreq_aspect;
 } __attribute__((packed));
 
+#define DRM_EDID_PT_HSYNC_POSITIVE (1 << 6)
+#define DRM_EDID_PT_VSYNC_POSITIVE (1 << 5)
+#define DRM_EDID_PT_SEPARATE_SYNC  (3 << 3)
+#define DRM_EDID_PT_STEREO         (1 << 2)
+#define DRM_EDID_PT_INTERLACED     (1 << 1)
+
 /* If detailed data is pixel timing */
 struct detailed_pixel_timing {
 	u8 hactive_lo;
 	u8 hblank_lo;
-	u8 hblank_hi:4;
-	u8 hactive_hi:4;
+	u8 hactive_hblank_hi;
 	u8 vactive_lo;
 	u8 vblank_lo;
-	u8 vblank_hi:4;
-	u8 vactive_hi:4;
+	u8 vactive_vblank_hi;
 	u8 hsync_offset_lo;
 	u8 hsync_pulse_width_lo;
-	u8 vsync_pulse_width_lo:4;
-	u8 vsync_offset_lo:4;
-	u8 vsync_pulse_width_hi:2;
-	u8 vsync_offset_hi:2;
-	u8 hsync_pulse_width_hi:2;
-	u8 hsync_offset_hi:2;
+	u8 vsync_offset_pulse_width_lo;
+	u8 hsync_vsync_offset_pulse_width_hi;
 	u8 width_mm_lo;
 	u8 height_mm_lo;
-	u8 height_mm_hi:4;
-	u8 width_mm_hi:4;
+	u8 width_height_mm_hi;
 	u8 hborder;
 	u8 vborder;
-	u8 unknown0:1;
-	u8 hsync_positive:1;
-	u8 vsync_positive:1;
-	u8 separate_sync:2;
-	u8 stereo:1;
-	u8 unknown6:1;
-	u8 interlaced:1;
+	u8 misc;
 } __attribute__((packed));
 
 /* If it's not pixel timing, it'll be one of the below */
@@ -88,18 +84,16 @@
 	u8 min_hfreq_khz;
 	u8 max_hfreq_khz;
 	u8 pixel_clock_mhz; /* need to multiply by 10 */
-	u16 sec_gtf_toggle; /* A000=use above, 20=use below */ /* FIXME: byte order */
+	__le16 sec_gtf_toggle; /* A000=use above, 20=use below */
 	u8 hfreq_start_khz; /* need to multiply by 2 */
 	u8 c; /* need to divide by 2 */
-	u16 m; /* FIXME: byte order */
+	__le16 m;
 	u8 k;
 	u8 j; /* need to divide by 2 */
 } __attribute__((packed));
 
 struct detailed_data_wpindex {
-	u8 white_y_lo:2;
-	u8 white_x_lo:2;
-	u8 pad:4;
+	u8 white_xy_lo; /* Upper 2 bits each */
 	u8 white_x_hi;
 	u8 white_y_hi;
 	u8 gamma; /* need to divide by 100 then add 1 */
@@ -134,13 +128,29 @@
 #define EDID_DETAIL_MONITOR_SERIAL 0xff
 
 struct detailed_timing {
-	u16 pixel_clock; /* need to multiply by 10 KHz */ /* FIXME: byte order */
+	__le16 pixel_clock; /* need to multiply by 10 KHz */
 	union {
 		struct detailed_pixel_timing pixel_data;
 		struct detailed_non_pixel other_data;
 	} data;
 } __attribute__((packed));
 
+#define DRM_EDID_INPUT_SERRATION_VSYNC (1 << 7)
+#define DRM_EDID_INPUT_SYNC_ON_GREEN   (1 << 5)
+#define DRM_EDID_INPUT_COMPOSITE_SYNC  (1 << 4)
+#define DRM_EDID_INPUT_SEPARATE_SYNCS  (1 << 3)
+#define DRM_EDID_INPUT_BLANK_TO_BLACK  (1 << 2)
+#define DRM_EDID_INPUT_VIDEO_LEVEL     (3 << 1)
+#define DRM_EDID_INPUT_DIGITAL         (1 << 0) /* bits above must be zero if set */
+
+#define DRM_EDID_FEATURE_DEFAULT_GTF      (1 << 7)
+#define DRM_EDID_FEATURE_PREFERRED_TIMING (1 << 6)
+#define DRM_EDID_FEATURE_STANDARD_COLOR   (1 << 5)
+#define DRM_EDID_FEATURE_DISPLAY_TYPE     (3 << 3) /* 00=mono, 01=rgb, 10=non-rgb, 11=unknown */
+#define DRM_EDID_FEATURE_PM_ACTIVE_OFF    (1 << 2)
+#define DRM_EDID_FEATURE_PM_SUSPEND       (1 << 1)
+#define DRM_EDID_FEATURE_PM_STANDBY       (1 << 0)
+
 struct edid {
 	u8 header[8];
 	/* Vendor & product info */
@@ -153,25 +163,11 @@
 	u8 version;
 	u8 revision;
 	/* Display info: */
-	/*   input definition */
-	u8 serration_vsync:1;
-	u8 sync_on_green:1;
-	u8 composite_sync:1;
-	u8 separate_syncs:1;
-	u8 blank_to_black:1;
-	u8 video_level:2;
-	u8 digital:1; /* bits below must be zero if set */
+	u8 input;
 	u8 width_cm;
 	u8 height_cm;
 	u8 gamma;
-	/*   feature support */
-	u8 default_gtf:1;
-	u8 preferred_timing:1;
-	u8 standard_color:1;
-	u8 display_type:2; /* 00=mono, 01=rgb, 10=non-rgb, 11=unknown */
-	u8 pm_active_off:1;
-	u8 pm_suspend:1;
-	u8 pm_standby:1;
+	u8 features;
 	/* Color characteristics */
 	u8 red_green_lo;
 	u8 black_white_lo;
@@ -195,8 +191,6 @@
 	u8 checksum;
 } __attribute__((packed));
 
-#endif /* little endian structs */
-
 #define EDID_PRODUCT_ID(e) ((e)->prod_code[0] | ((e)->prod_code[1] << 8))
 
 #endif /* __DRM_EDID_H__ */
diff --git a/include/drm/drm_memory_debug.h b/include/drm/drm_memory_debug.h
deleted file mode 100644
index 6463271..0000000
--- a/include/drm/drm_memory_debug.h
+++ /dev/null
@@ -1,309 +0,0 @@
-/**
- * \file drm_memory_debug.h
- * Memory management wrappers for DRM.
- *
- * \author Rickard E. (Rik) Faith <faith@valinux.com>
- * \author Gareth Hughes <gareth@valinux.com>
- */
-
-/*
- * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
- * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
- * All Rights Reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice (including the next
- * paragraph) shall be included in all copies or substantial portions of the
- * Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
- * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- * OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#include "drmP.h"
-
-typedef struct drm_mem_stats {
-	const char *name;
-	int succeed_count;
-	int free_count;
-	int fail_count;
-	unsigned long bytes_allocated;
-	unsigned long bytes_freed;
-} drm_mem_stats_t;
-
-static DEFINE_SPINLOCK(drm_mem_lock);
-static unsigned long drm_ram_available = 0;	/* In pages */
-static unsigned long drm_ram_used = 0;
-static drm_mem_stats_t drm_mem_stats[] =
-{
-	[DRM_MEM_DMA] = {"dmabufs"},
-	[DRM_MEM_SAREA] = {"sareas"},
-	[DRM_MEM_DRIVER] = {"driver"},
-	[DRM_MEM_MAGIC] = {"magic"},
-	[DRM_MEM_IOCTLS] = {"ioctltab"},
-	[DRM_MEM_MAPS] = {"maplist"},
-	[DRM_MEM_VMAS] = {"vmalist"},
-	[DRM_MEM_BUFS] = {"buflist"},
-	[DRM_MEM_SEGS] = {"seglist"},
-	[DRM_MEM_PAGES] = {"pagelist"},
-	[DRM_MEM_FILES] = {"files"},
-	[DRM_MEM_QUEUES] = {"queues"},
-	[DRM_MEM_CMDS] = {"commands"},
-	[DRM_MEM_MAPPINGS] = {"mappings"},
-	[DRM_MEM_BUFLISTS] = {"buflists"},
-	[DRM_MEM_AGPLISTS] = {"agplist"},
-	[DRM_MEM_SGLISTS] = {"sglist"},
-	[DRM_MEM_TOTALAGP] = {"totalagp"},
-	[DRM_MEM_BOUNDAGP] = {"boundagp"},
-	[DRM_MEM_CTXBITMAP] = {"ctxbitmap"},
-	[DRM_MEM_CTXLIST] = {"ctxlist"},
-	[DRM_MEM_STUB] = {"stub"},
-	{NULL, 0,}		/* Last entry must be null */
-};
-
-void drm_mem_init (void) {
-	drm_mem_stats_t *mem;
-	struct sysinfo si;
-
-	for (mem = drm_mem_stats; mem->name; ++mem) {
-		mem->succeed_count = 0;
-		mem->free_count = 0;
-		mem->fail_count = 0;
-		mem->bytes_allocated = 0;
-		mem->bytes_freed = 0;
-	}
-
-	si_meminfo(&si);
-	drm_ram_available = si.totalram;
-	drm_ram_used = 0;
-}
-
-/* drm_mem_info is called whenever a process reads /dev/drm/mem. */
-
-static int drm__mem_info (char *buf, char **start, off_t offset,
-			   int request, int *eof, void *data) {
-	drm_mem_stats_t *pt;
-	int len = 0;
-
-	if (offset > DRM_PROC_LIMIT) {
-		*eof = 1;
-		return 0;
-	}
-
-	*eof = 0;
-	*start = &buf[offset];
-
-	DRM_PROC_PRINT("		  total counts			"
-		       " |    outstanding  \n");
-	DRM_PROC_PRINT("type	   alloc freed fail	bytes	   freed"
-		       " | allocs      bytes\n\n");
-	DRM_PROC_PRINT("%-9.9s %5d %5d %4d %10lu kB         |\n",
-		       "system", 0, 0, 0,
-		       drm_ram_available << (PAGE_SHIFT - 10));
-	DRM_PROC_PRINT("%-9.9s %5d %5d %4d %10lu kB         |\n",
-		       "locked", 0, 0, 0, drm_ram_used >> 10);
-	DRM_PROC_PRINT("\n");
-	for (pt = drm_mem_stats; pt->name; pt++) {
-		DRM_PROC_PRINT("%-9.9s %5d %5d %4d %10lu %10lu | %6d %10ld\n",
-			       pt->name,
-			       pt->succeed_count,
-			       pt->free_count,
-			       pt->fail_count,
-			       pt->bytes_allocated,
-			       pt->bytes_freed,
-			       pt->succeed_count - pt->free_count,
-			       (long)pt->bytes_allocated
-			       - (long)pt->bytes_freed);
-	}
-
-	if (len > request + offset)
-		return request;
-	*eof = 1;
-	return len - offset;
-}
-
-int drm_mem_info (char *buf, char **start, off_t offset,
-		   int len, int *eof, void *data) {
-	int ret;
-
-	spin_lock(&drm_mem_lock);
-	ret = drm__mem_info (buf, start, offset, len, eof, data);
-	spin_unlock(&drm_mem_lock);
-	return ret;
-}
-
-void *drm_alloc (size_t size, int area) {
-	void *pt;
-
-	if (!size) {
-		DRM_MEM_ERROR(area, "Allocating 0 bytes\n");
-		return NULL;
-	}
-
-	if (!(pt = kmalloc(size, GFP_KERNEL))) {
-		spin_lock(&drm_mem_lock);
-		++drm_mem_stats[area].fail_count;
-		spin_unlock(&drm_mem_lock);
-		return NULL;
-	}
-	spin_lock(&drm_mem_lock);
-	++drm_mem_stats[area].succeed_count;
-	drm_mem_stats[area].bytes_allocated += size;
-	spin_unlock(&drm_mem_lock);
-	return pt;
-}
-
-void *drm_calloc (size_t nmemb, size_t size, int area) {
-	void *addr;
-
-	addr = drm_alloc (nmemb * size, area);
-	if (addr != NULL)
-		memset((void *)addr, 0, size * nmemb);
-
-	return addr;
-}
-
-void *drm_realloc (void *oldpt, size_t oldsize, size_t size, int area) {
-	void *pt;
-
-	if (!(pt = drm_alloc (size, area)))
-		return NULL;
-	if (oldpt && oldsize) {
-		memcpy(pt, oldpt, oldsize);
-		drm_free (oldpt, oldsize, area);
-	}
-	return pt;
-}
-
-void drm_free (void *pt, size_t size, int area) {
-	int alloc_count;
-	int free_count;
-
-	if (!pt)
-		DRM_MEM_ERROR(area, "Attempt to free NULL pointer\n");
-	else
-		kfree(pt);
-	spin_lock(&drm_mem_lock);
-	drm_mem_stats[area].bytes_freed += size;
-	free_count = ++drm_mem_stats[area].free_count;
-	alloc_count = drm_mem_stats[area].succeed_count;
-	spin_unlock(&drm_mem_lock);
-	if (free_count > alloc_count) {
-		DRM_MEM_ERROR(area, "Excess frees: %d frees, %d allocs\n",
-			      free_count, alloc_count);
-	}
-}
-
-#if __OS_HAS_AGP
-
-DRM_AGP_MEM *drm_alloc_agp (drm_device_t *dev, int pages, u32 type) {
-	DRM_AGP_MEM *handle;
-
-	if (!pages) {
-		DRM_MEM_ERROR(DRM_MEM_TOTALAGP, "Allocating 0 pages\n");
-		return NULL;
-	}
-
-	if ((handle = drm_agp_allocate_memory (pages, type))) {
-		spin_lock(&drm_mem_lock);
-		++drm_mem_stats[DRM_MEM_TOTALAGP].succeed_count;
-		drm_mem_stats[DRM_MEM_TOTALAGP].bytes_allocated
-		    += pages << PAGE_SHIFT;
-		spin_unlock(&drm_mem_lock);
-		return handle;
-	}
-	spin_lock(&drm_mem_lock);
-	++drm_mem_stats[DRM_MEM_TOTALAGP].fail_count;
-	spin_unlock(&drm_mem_lock);
-	return NULL;
-}
-
-int drm_free_agp (DRM_AGP_MEM * handle, int pages) {
-	int alloc_count;
-	int free_count;
-	int retval = -EINVAL;
-
-	if (!handle) {
-		DRM_MEM_ERROR(DRM_MEM_TOTALAGP,
-			      "Attempt to free NULL AGP handle\n");
-		return retval;
-	}
-
-	if (drm_agp_free_memory (handle)) {
-		spin_lock(&drm_mem_lock);
-		free_count = ++drm_mem_stats[DRM_MEM_TOTALAGP].free_count;
-		alloc_count = drm_mem_stats[DRM_MEM_TOTALAGP].succeed_count;
-		drm_mem_stats[DRM_MEM_TOTALAGP].bytes_freed
-		    += pages << PAGE_SHIFT;
-		spin_unlock(&drm_mem_lock);
-		if (free_count > alloc_count) {
-			DRM_MEM_ERROR(DRM_MEM_TOTALAGP,
-				      "Excess frees: %d frees, %d allocs\n",
-				      free_count, alloc_count);
-		}
-		return 0;
-	}
-	return retval;
-}
-
-int drm_bind_agp (DRM_AGP_MEM * handle, unsigned int start) {
-	int retcode = -EINVAL;
-
-	if (!handle) {
-		DRM_MEM_ERROR(DRM_MEM_BOUNDAGP,
-			      "Attempt to bind NULL AGP handle\n");
-		return retcode;
-	}
-
-	if (!(retcode = drm_agp_bind_memory (handle, start))) {
-		spin_lock(&drm_mem_lock);
-		++drm_mem_stats[DRM_MEM_BOUNDAGP].succeed_count;
-		drm_mem_stats[DRM_MEM_BOUNDAGP].bytes_allocated
-		    += handle->page_count << PAGE_SHIFT;
-		spin_unlock(&drm_mem_lock);
-		return retcode;
-	}
-	spin_lock(&drm_mem_lock);
-	++drm_mem_stats[DRM_MEM_BOUNDAGP].fail_count;
-	spin_unlock(&drm_mem_lock);
-	return retcode;
-}
-
-int drm_unbind_agp (DRM_AGP_MEM * handle) {
-	int alloc_count;
-	int free_count;
-	int retcode = -EINVAL;
-
-	if (!handle) {
-		DRM_MEM_ERROR(DRM_MEM_BOUNDAGP,
-			      "Attempt to unbind NULL AGP handle\n");
-		return retcode;
-	}
-
-	if ((retcode = drm_agp_unbind_memory (handle)))
-		return retcode;
-	spin_lock(&drm_mem_lock);
-	free_count = ++drm_mem_stats[DRM_MEM_BOUNDAGP].free_count;
-	alloc_count = drm_mem_stats[DRM_MEM_BOUNDAGP].succeed_count;
-	drm_mem_stats[DRM_MEM_BOUNDAGP].bytes_freed
-	    += handle->page_count << PAGE_SHIFT;
-	spin_unlock(&drm_mem_lock);
-	if (free_count > alloc_count) {
-		DRM_MEM_ERROR(DRM_MEM_BOUNDAGP,
-			      "Excess frees: %d frees, %d allocs\n",
-			      free_count, alloc_count);
-	}
-	return retcode;
-}
-#endif
diff --git a/include/drm/drm_mm.h b/include/drm/drm_mm.h
index 5662f42..f833207 100644
--- a/include/drm/drm_mm.h
+++ b/include/drm/drm_mm.h
@@ -59,13 +59,22 @@
 /*
  * Basic range manager support (drm_mm.c)
  */
-
-extern struct drm_mm_node *drm_mm_get_block(struct drm_mm_node *parent,
-					    unsigned long size,
-					    unsigned alignment);
-extern struct drm_mm_node *drm_mm_get_block_atomic(struct drm_mm_node *parent,
+extern struct drm_mm_node *drm_mm_get_block_generic(struct drm_mm_node *node,
+						    unsigned long size,
+						    unsigned alignment,
+						    int atomic);
+static inline struct drm_mm_node *drm_mm_get_block(struct drm_mm_node *parent,
 						   unsigned long size,
-						   unsigned alignment);
+						   unsigned alignment)
+{
+	return drm_mm_get_block_generic(parent, size, alignment, 0);
+}
+static inline struct drm_mm_node *drm_mm_get_block_atomic(struct drm_mm_node *parent,
+							  unsigned long size,
+							  unsigned alignment)
+{
+	return drm_mm_get_block_generic(parent, size, alignment, 1);
+}
 extern void drm_mm_put_block(struct drm_mm_node *cur);
 extern struct drm_mm_node *drm_mm_search_free(const struct drm_mm *mm,
 					      unsigned long size,
diff --git a/include/linux/Kbuild b/include/linux/Kbuild
index a2df703..03f2207 100644
--- a/include/linux/Kbuild
+++ b/include/linux/Kbuild
@@ -308,6 +308,7 @@
 unifdef-y += poll.h
 unifdef-y += ppp_defs.h
 unifdef-y += ppp-comp.h
+unifdef-y += pps.h
 unifdef-y += ptrace.h
 unifdef-y += quota.h
 unifdef-y += random.h
diff --git a/include/linux/adfs_fs.h b/include/linux/adfs_fs.h
index ef788c2..b19801f 100644
--- a/include/linux/adfs_fs.h
+++ b/include/linux/adfs_fs.h
@@ -41,8 +41,6 @@
 #define ADFS_DR_SIZE_BITS	(ADFS_DR_SIZE << 3)
 
 #ifdef __KERNEL__
-#include <linux/adfs_fs_i.h>
-#include <linux/adfs_fs_sb.h>
 /*
  * Calculate the boot block checksum on an ADFS drive.  Note that this will
  * appear to be correct if the sector contains all zeros, so also check that
@@ -60,17 +58,6 @@
 
 	return (result & 0xff) != ptr[511];
 }
-
-static inline struct adfs_sb_info *ADFS_SB(struct super_block *sb)
-{
-	return sb->s_fs_info;
-}
-
-static inline struct adfs_inode_info *ADFS_I(struct inode *inode)
-{
-	return container_of(inode, struct adfs_inode_info, vfs_inode);
-}
-
 #endif
 
 #endif
diff --git a/include/linux/adfs_fs_i.h b/include/linux/adfs_fs_i.h
deleted file mode 100644
index cb54303..0000000
--- a/include/linux/adfs_fs_i.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- *  linux/include/linux/adfs_fs_i.h
- *
- * Copyright (C) 1997 Russell King
- */
-
-#ifndef _ADFS_FS_I
-#define _ADFS_FS_I
-
-/*
- * adfs file system inode data in memory
- */
-struct adfs_inode_info {
-	loff_t		mmu_private;
-	unsigned long	parent_id;	/* object id of parent		*/
-	__u32		loadaddr;	/* RISC OS load address		*/
-	__u32		execaddr;	/* RISC OS exec address		*/
-	unsigned int	filetype;	/* RISC OS file type		*/
-	unsigned int	attr;		/* RISC OS permissions		*/
-	unsigned int	stamped:1;	/* RISC OS file has date/time	*/
-	struct inode vfs_inode;
-};
-
-#endif
diff --git a/include/linux/adfs_fs_sb.h b/include/linux/adfs_fs_sb.h
deleted file mode 100644
index d9bf05c..0000000
--- a/include/linux/adfs_fs_sb.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- *  linux/include/linux/adfs_fs_sb.h
- *
- * Copyright (C) 1997-1999 Russell King
- */
-
-#ifndef _ADFS_FS_SB
-#define _ADFS_FS_SB
-
-/*
- * Forward-declare this
- */
-struct adfs_discmap;
-struct adfs_dir_ops;
-
-/*
- * ADFS file system superblock data in memory
- */
-struct adfs_sb_info {
-	struct adfs_discmap *s_map;	/* bh list containing map		 */
-	struct adfs_dir_ops *s_dir;	/* directory operations			 */
-
-	uid_t		s_uid;		/* owner uid				 */
-	gid_t		s_gid;		/* owner gid				 */
-	umode_t		s_owner_mask;	/* ADFS owner perm -> unix perm		 */
-	umode_t		s_other_mask;	/* ADFS other perm -> unix perm		 */
-
-	__u32		s_ids_per_zone;	/* max. no ids in one zone		 */
-	__u32		s_idlen;	/* length of ID in map			 */
-	__u32		s_map_size;	/* sector size of a map			 */
-	unsigned long	s_size;		/* total size (in blocks) of this fs	 */
-	signed int	s_map2blk;	/* shift left by this for map->sector	 */
-	unsigned int	s_log2sharesize;/* log2 share size			 */
-	__le32		s_version;	/* disc format version			 */
-	unsigned int	s_namelen;	/* maximum number of characters in name	 */
-};
-
-#endif
diff --git a/include/linux/agp_backend.h b/include/linux/agp_backend.h
index 2b8df8b..76fa794 100644
--- a/include/linux/agp_backend.h
+++ b/include/linux/agp_backend.h
@@ -70,7 +70,7 @@
 	struct agp_memory *next;
 	struct agp_memory *prev;
 	struct agp_bridge_data *bridge;
-	unsigned long *memory;
+	struct page **pages;
 	size_t page_count;
 	int key;
 	int num_scratch_pages;
diff --git a/include/linux/amba/pl061.h b/include/linux/amba/pl061.h
new file mode 100644
index 0000000..b4fbd98
--- /dev/null
+++ b/include/linux/amba/pl061.h
@@ -0,0 +1,15 @@
+/* platform data for the PL061 GPIO driver */
+
+struct pl061_platform_data {
+	/* number of the first GPIO */
+	unsigned	gpio_base;
+
+	/* number of the first IRQ.
+	 * If the IRQ functionality in not desired this must be set to
+	 * (unsigned) -1.
+	 */
+	unsigned	irq_base;
+
+	u8		directions;	/* startup directions, 1: out, 0: in */
+	u8		values;		/* startup values */
+};
diff --git a/include/linux/ata.h b/include/linux/ata.h
index 915da43..9c75921 100644
--- a/include/linux/ata.h
+++ b/include/linux/ata.h
@@ -800,6 +800,20 @@
 	return id[ATA_ID_ROT_SPEED] == 0x01;
 }
 
+static inline int ata_id_pio_need_iordy(const u16 *id, const u8 pio)
+{
+	/* CF spec. r4.1 Table 22 says no IORDY on PIO5 and PIO6. */
+	if (pio > 4 && ata_id_is_cfa(id))
+		return 0;
+	/* For PIO3 and higher it is mandatory. */
+	if (pio > 2)
+		return 1;
+	/* Turn it on when possible. */
+	if (ata_id_has_iordy(id))
+		return 1;
+	return 0;
+}
+
 static inline int ata_drive_40wire(const u16 *dev_id)
 {
 	if (ata_id_is_sata(dev_id))
diff --git a/include/linux/compiler-gcc3.h b/include/linux/compiler-gcc3.h
index 8005eff..b721129 100644
--- a/include/linux/compiler-gcc3.h
+++ b/include/linux/compiler-gcc3.h
@@ -16,6 +16,12 @@
 #define __must_check		__attribute__((warn_unused_result))
 #endif
 
+#ifdef CONFIG_GCOV_KERNEL
+# if __GNUC_MINOR__ < 4
+#   error "GCOV profiling support for gcc versions below 3.4 not included"
+# endif /* __GNUC_MINOR__ */
+#endif /* CONFIG_GCOV_KERNEL */
+
 /*
  * A trick to suppress uninitialized variable warning without generating any
  * code
diff --git a/include/linux/dma-mapping.h b/include/linux/dma-mapping.h
index 8083b6a..07dfd46 100644
--- a/include/linux/dma-mapping.h
+++ b/include/linux/dma-mapping.h
@@ -63,24 +63,26 @@
 
 #define DMA_BIT_MASK(n)	(((n) == 64) ? ~0ULL : ((1ULL<<(n))-1))
 
+typedef u64 DMA_nnBIT_MASK __deprecated;
+
 /*
  * NOTE: do not use the below macros in new code and do not add new definitions
  * here.
  *
  * Instead, just open-code DMA_BIT_MASK(n) within your driver
  */
-#define DMA_64BIT_MASK	DMA_BIT_MASK(64)
-#define DMA_48BIT_MASK	DMA_BIT_MASK(48)
-#define DMA_47BIT_MASK	DMA_BIT_MASK(47)
-#define DMA_40BIT_MASK	DMA_BIT_MASK(40)
-#define DMA_39BIT_MASK	DMA_BIT_MASK(39)
-#define DMA_35BIT_MASK	DMA_BIT_MASK(35)
-#define DMA_32BIT_MASK	DMA_BIT_MASK(32)
-#define DMA_31BIT_MASK	DMA_BIT_MASK(31)
-#define DMA_30BIT_MASK	DMA_BIT_MASK(30)
-#define DMA_29BIT_MASK	DMA_BIT_MASK(29)
-#define DMA_28BIT_MASK	DMA_BIT_MASK(28)
-#define DMA_24BIT_MASK	DMA_BIT_MASK(24)
+#define DMA_64BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(64)
+#define DMA_48BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(48)
+#define DMA_47BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(47)
+#define DMA_40BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(40)
+#define DMA_39BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(39)
+#define DMA_35BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(35)
+#define DMA_32BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(32)
+#define DMA_31BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(31)
+#define DMA_30BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(30)
+#define DMA_29BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(29)
+#define DMA_28BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(28)
+#define DMA_24BIT_MASK	(DMA_nnBIT_MASK)DMA_BIT_MASK(24)
 
 #define DMA_MASK_NONE	0x0ULL
 
@@ -107,9 +109,20 @@
 #include <asm-generic/dma-mapping-broken.h>
 #endif
 
-/* Backwards compat, remove in 2.7.x */
-#define dma_sync_single		dma_sync_single_for_cpu
-#define dma_sync_sg		dma_sync_sg_for_cpu
+/* for backwards compatibility, removed soon */
+static inline void __deprecated dma_sync_single(struct device *dev,
+						dma_addr_t addr, size_t size,
+						enum dma_data_direction dir)
+{
+	dma_sync_single_for_cpu(dev, addr, size, dir);
+}
+
+static inline void __deprecated dma_sync_sg(struct device *dev,
+					    struct scatterlist *sg, int nelems,
+					    enum dma_data_direction dir)
+{
+	dma_sync_sg_for_cpu(dev, sg, nelems, dir);
+}
 
 static inline u64 dma_get_mask(struct device *dev)
 {
diff --git a/include/linux/efi.h b/include/linux/efi.h
index bb66feb..ce4581f 100644
--- a/include/linux/efi.h
+++ b/include/linux/efi.h
@@ -101,7 +101,7 @@
 	u64 attribute;
 } efi_memory_desc_t;
 
-typedef int (*efi_freemem_callback_t) (unsigned long start, unsigned long end, void *arg);
+typedef int (*efi_freemem_callback_t) (u64 start, u64 end, void *arg);
 
 /*
  * Types and defines for Time Services
diff --git a/include/linux/fsl_devices.h b/include/linux/fsl_devices.h
index 244677c..43fc95d 100644
--- a/include/linux/fsl_devices.h
+++ b/include/linux/fsl_devices.h
@@ -79,10 +79,6 @@
 	u16	max_chipselect;
 	void	(*cs_control)(struct spi_device *spi, bool on);
 	u32	sysclk;
-
-	/* Legacy hooks, used by mpc52xx_psc_spi driver. */
-	void	(*activate_cs)(u8 cs, u8 polarity);
-	void	(*deactivate_cs)(u8 cs, u8 polarity);
 };
 
 struct mpc8xx_pcmcia_ops {
diff --git a/include/linux/ftrace.h b/include/linux/ftrace.h
index 39b95c5..dc3b132 100644
--- a/include/linux/ftrace.h
+++ b/include/linux/ftrace.h
@@ -362,6 +362,7 @@
 	unsigned long func;
 	unsigned long long calltime;
 	unsigned long long subtime;
+	unsigned long fp;
 };
 
 /*
@@ -372,7 +373,8 @@
 extern void return_to_handler(void);
 
 extern int
-ftrace_push_return_trace(unsigned long ret, unsigned long func, int *depth);
+ftrace_push_return_trace(unsigned long ret, unsigned long func, int *depth,
+			 unsigned long frame_pointer);
 
 /*
  * Sometimes we don't want to trace a function with the function
diff --git a/include/linux/gameport.h b/include/linux/gameport.h
index 0cd825f..1bc0854 100644
--- a/include/linux/gameport.h
+++ b/include/linux/gameport.h
@@ -11,6 +11,7 @@
 
 #ifdef __KERNEL__
 #include <asm/io.h>
+#include <linux/types.h>
 #include <linux/list.h>
 #include <linux/mutex.h>
 #include <linux/device.h>
@@ -62,7 +63,7 @@
 
 	struct device_driver driver;
 
-	unsigned int ignore;
+	bool ignore;
 };
 #define to_gameport_driver(d)	container_of(d, struct gameport_driver, driver)
 
diff --git a/include/linux/gcd.h b/include/linux/gcd.h
new file mode 100644
index 0000000..69f5e8a
--- /dev/null
+++ b/include/linux/gcd.h
@@ -0,0 +1,8 @@
+#ifndef _GCD_H
+#define _GCD_H
+
+#include <linux/compiler.h>
+
+unsigned long gcd(unsigned long a, unsigned long b) __attribute_const__;
+
+#endif /* _GCD_H */
diff --git a/include/linux/gfp.h b/include/linux/gfp.h
index cfdb35d..7c777a0 100644
--- a/include/linux/gfp.h
+++ b/include/linux/gfp.h
@@ -99,7 +99,7 @@
 			__GFP_NORETRY|__GFP_NOMEMALLOC)
 
 /* Control slab gfp mask during early boot */
-#define SLAB_GFP_BOOT_MASK __GFP_BITS_MASK & ~(__GFP_WAIT|__GFP_IO|__GFP_FS)
+#define GFP_BOOT_MASK __GFP_BITS_MASK & ~(__GFP_WAIT|__GFP_IO|__GFP_FS)
 
 /* Control allocation constraints */
 #define GFP_CONSTRAINT_MASK (__GFP_HARDWALL|__GFP_THISNODE)
@@ -348,4 +348,11 @@
 	oom_killer_disabled = false;
 }
 
+extern gfp_t gfp_allowed_mask;
+
+static inline void set_gfp_allowed_mask(gfp_t mask)
+{
+	gfp_allowed_mask = mask;
+}
+
 #endif /* __LINUX_GFP_H */
diff --git a/include/linux/i2c.h b/include/linux/i2c.h
index ad25805..f4784c0 100644
--- a/include/linux/i2c.h
+++ b/include/linux/i2c.h
@@ -47,6 +47,7 @@
 union i2c_smbus_data;
 struct i2c_board_info;
 
+#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
 /*
  * The master routines are the ones normally used to transmit data to devices
  * on a bus (or read from them). Apart from two basic transfer functions to
@@ -93,6 +94,7 @@
 extern s32 i2c_smbus_write_i2c_block_data(struct i2c_client *client,
 					  u8 command, u8 length,
 					  const u8 *values);
+#endif /* I2C */
 
 /**
  * struct i2c_driver - represent an I2C device driver
@@ -100,9 +102,8 @@
  * @class: What kind of i2c device we instantiate (for detect)
  * @attach_adapter: Callback for bus addition (for legacy drivers)
  * @detach_adapter: Callback for bus removal (for legacy drivers)
- * @detach_client: Callback for device removal (for legacy drivers)
- * @probe: Callback for device binding (new-style drivers)
- * @remove: Callback for device unbinding (new-style drivers)
+ * @probe: Callback for device binding
+ * @remove: Callback for device unbinding
  * @shutdown: Callback for device shutdown
  * @suspend: Callback for device suspend
  * @resume: Callback for device resume
@@ -137,26 +138,14 @@
 	int id;
 	unsigned int class;
 
-	/* Notifies the driver that a new bus has appeared. This routine
-	 * can be used by the driver to test if the bus meets its conditions
-	 * & seek for the presence of the chip(s) it supports. If found, it
-	 * registers the client(s) that are on the bus to the i2c admin. via
-	 * i2c_attach_client.  (LEGACY I2C DRIVERS ONLY)
+	/* Notifies the driver that a new bus has appeared or is about to be
+	 * removed. You should avoid using this if you can, it will probably
+	 * be removed in a near future.
 	 */
 	int (*attach_adapter)(struct i2c_adapter *);
 	int (*detach_adapter)(struct i2c_adapter *);
 
-	/* tells the driver that a client is about to be deleted & gives it
-	 * the chance to remove its private data. Also, if the client struct
-	 * has been dynamically allocated by the driver in the function above,
-	 * it must be freed here.  (LEGACY I2C DRIVERS ONLY)
-	 */
-	int (*detach_client)(struct i2c_client *) __deprecated;
-
-	/* Standard driver model interfaces, for "new style" i2c drivers.
-	 * With the driver model, device enumeration is NEVER done by drivers;
-	 * it's done by infrastructure.  (NEW STYLE DRIVERS ONLY)
-	 */
+	/* Standard driver model interfaces */
 	int (*probe)(struct i2c_client *, const struct i2c_device_id *);
 	int (*remove)(struct i2c_client *);
 
@@ -191,9 +180,8 @@
  * @driver: device's driver, hence pointer to access routines
  * @dev: Driver model device node for the slave.
  * @irq: indicates the IRQ generated by this device (if any)
- * @list: list of active/busy clients (DEPRECATED)
- * @detected: member of an i2c_driver.clients list
- * @released: used to synchronize client releases & detaches and references
+ * @detected: member of an i2c_driver.clients list or i2c-core's
+ *	userspace_devices list
  *
  * An i2c_client identifies a single device (i.e. chip) connected to an
  * i2c bus. The behaviour exposed to Linux is defined by the driver
@@ -209,9 +197,7 @@
 	struct i2c_driver *driver;	/* and our access routines	*/
 	struct device dev;		/* the device structure		*/
 	int irq;			/* irq issued by device		*/
-	struct list_head list;		/* DEPRECATED */
 	struct list_head detected;
-	struct completion released;
 };
 #define to_i2c_client(d) container_of(d, struct i2c_client, dev)
 
@@ -248,11 +234,10 @@
  * that, such as chip type, configuration, associated IRQ, and so on.
  *
  * i2c_board_info is used to build tables of information listing I2C devices
- * that are present.  This information is used to grow the driver model tree
- * for "new style" I2C drivers.  For mainboards this is done statically using
- * i2c_register_board_info(); bus numbers identify adapters that aren't
- * yet available.  For add-on boards, i2c_new_device() does this dynamically
- * with the adapter already known.
+ * that are present.  This information is used to grow the driver model tree.
+ * For mainboards this is done statically using i2c_register_board_info();
+ * bus numbers identify adapters that aren't yet available.  For add-on boards,
+ * i2c_new_device() does this dynamically with the adapter already known.
  */
 struct i2c_board_info {
 	char		type[I2C_NAME_SIZE];
@@ -277,6 +262,7 @@
 	.type = dev_type, .addr = (dev_addr)
 
 
+#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
 /* Add-on boards should register/unregister their devices; e.g. a board
  * with integrated I2C, a config eeprom, sensors, and a codec that's
  * used in conjunction with the primary hardware.
@@ -300,6 +286,7 @@
 i2c_new_dummy(struct i2c_adapter *adap, u16 address);
 
 extern void i2c_unregister_device(struct i2c_client *);
+#endif /* I2C */
 
 /* Mainboard arch_initcall() code should register all its I2C devices.
  * This is done at arch_initcall time, before declaring any i2c adapters.
@@ -316,7 +303,7 @@
 {
 	return 0;
 }
-#endif
+#endif /* I2C_BOARDINFO */
 
 /*
  * The following structs are for those who like to implement new bus drivers:
@@ -352,21 +339,15 @@
 	const struct i2c_algorithm *algo; /* the algorithm to access the bus */
 	void *algo_data;
 
-	/* --- administration stuff. */
-	int (*client_register)(struct i2c_client *) __deprecated;
-	int (*client_unregister)(struct i2c_client *) __deprecated;
-
 	/* data fields that are valid for all devices	*/
 	u8 level; 			/* nesting level for lockdep */
 	struct mutex bus_lock;
-	struct mutex clist_lock;
 
 	int timeout;			/* in jiffies */
 	int retries;
 	struct device dev;		/* the adapter device */
 
 	int nr;
-	struct list_head clients;	/* DEPRECATED */
 	char name[48];
 	struct completion dev_released;
 };
@@ -412,11 +393,16 @@
 /* The numbers to use to set I2C bus address */
 #define ANY_I2C_BUS		0xffff
 
+/* Construct an I2C_CLIENT_END-terminated array of i2c addresses */
+#define I2C_ADDRS(addr, addrs...) \
+	((const unsigned short []){ addr, ## addrs, I2C_CLIENT_END })
+
 
 /* ----- functions exported by i2c.o */
 
 /* administration...
  */
+#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
 extern int i2c_add_adapter(struct i2c_adapter *);
 extern int i2c_del_adapter(struct i2c_adapter *);
 extern int i2c_add_numbered_adapter(struct i2c_adapter *);
@@ -429,11 +415,6 @@
 	return i2c_register_driver(THIS_MODULE, driver);
 }
 
-/* These are deprecated, your driver should use the standard .probe()
- * and .remove() methods instead. */
-extern int __deprecated i2c_attach_client(struct i2c_client *);
-extern int __deprecated i2c_detach_client(struct i2c_client *);
-
 extern struct i2c_client *i2c_use_client(struct i2c_client *client);
 extern void i2c_release_client(struct i2c_client *client);
 
@@ -442,14 +423,6 @@
 extern void i2c_clients_command(struct i2c_adapter *adap,
 				unsigned int cmd, void *arg);
 
-/* Detect function. It iterates over all possible addresses itself.
- * It will only call found_proc if some client is connected at the
- * specific address (unless a 'force' matched);
- */
-extern int i2c_probe(struct i2c_adapter *adapter,
-		const struct i2c_client_address_data *address_data,
-		int (*found_proc) (struct i2c_adapter *, int, int));
-
 extern struct i2c_adapter *i2c_get_adapter(int id);
 extern void i2c_put_adapter(struct i2c_adapter *adap);
 
@@ -471,6 +444,7 @@
 {
 	return adap->nr;
 }
+#endif /* I2C */
 #endif /* __KERNEL__ */
 
 /**
diff --git a/include/linux/i2c/lm8323.h b/include/linux/i2c/lm8323.h
new file mode 100644
index 0000000..478d668b
--- /dev/null
+++ b/include/linux/i2c/lm8323.h
@@ -0,0 +1,46 @@
+/*
+ * lm8323.h - Configuration for LM8323 keypad driver.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation (version 2 of the License only).
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef __LINUX_LM8323_H
+#define __LINUX_LM8323_H
+
+#include <linux/types.h>
+
+/*
+ * Largest keycode that the chip can send, plus one,
+ * so keys can be mapped directly at the index of the
+ * LM8323 keycode instead of subtracting one.
+ */
+#define LM8323_KEYMAP_SIZE	(0x7f + 1)
+
+#define LM8323_NUM_PWMS		3
+
+struct lm8323_platform_data {
+	int debounce_time; /* Time to watch for key bouncing, in ms. */
+	int active_time; /* Idle time until sleep, in ms. */
+
+	int size_x;
+	int size_y;
+	bool repeat;
+	const unsigned short *keymap;
+
+	const char *pwm_names[LM8323_NUM_PWMS];
+
+	const char *name; /* Device name. */
+};
+
+#endif /* __LINUX_LM8323_H */
diff --git a/include/linux/i2c/pca953x.h b/include/linux/i2c/pca953x.h
index 3c73612..81736d6 100644
--- a/include/linux/i2c/pca953x.h
+++ b/include/linux/i2c/pca953x.h
@@ -15,4 +15,5 @@
 	int		(*teardown)(struct i2c_client *client,
 				unsigned gpio, unsigned ngpio,
 				void *context);
+	char		**names;
 };
diff --git a/include/linux/ide.h b/include/linux/ide.h
index a6c6a2f..95c6e00 100644
--- a/include/linux/ide.h
+++ b/include/linux/ide.h
@@ -157,12 +157,6 @@
 #define REQ_UNPARK_HEADS	0x23
 
 /*
- * Check for an interrupt and acknowledge the interrupt status
- */
-struct hwif_s;
-typedef int (ide_ack_intr_t)(struct hwif_s *);
-
-/*
  * hwif_chipset_t is used to keep track of the specific hardware
  * chipset used by each IDE interface, if known.
  */
@@ -185,7 +179,6 @@
 	};
 
 	int		irq;			/* our irq number */
-	ide_ack_intr_t	*ack_intr;		/* acknowledge interrupt */
 	struct device	*dev, *parent;
 	unsigned long	config;
 };
@@ -331,11 +324,6 @@
 	PC_FLAG_WRITING			= (1 << 6),
 };
 
-/*
- * With each packet command, we allocate a buffer of IDE_PC_BUFFER_SIZE bytes.
- * This is used for several packet commands (not for READ/WRITE commands).
- */
-#define IDE_PC_BUFFER_SIZE	64
 #define ATAPI_WAIT_PC		(60 * HZ)
 
 struct ide_atapi_pc {
@@ -347,12 +335,6 @@
 
 	/* bytes to transfer */
 	int req_xfer;
-	/* bytes actually transferred */
-	int xferred;
-
-	/* data buffer */
-	u8 *buf;
-	int buf_size;
 
 	/* the corresponding request */
 	struct request *rq;
@@ -363,8 +345,6 @@
 	 * those are more or less driver-specific and some of them are subject
 	 * to change/removal later.
 	 */
-	u8 pc_buf[IDE_PC_BUFFER_SIZE];
-
 	unsigned long timeout;
 };
 
@@ -552,7 +532,7 @@
 
 	unsigned int	bios_cyl;	/* BIOS/fdisk/LILO number of cyls */
 	unsigned int	cyl;		/* "real" number of cyls */
-	unsigned int	drive_data;	/* used by set_pio_mode/dev_select() */
+	void		*drive_data;	/* used by set_pio_mode/dev_select() */
 	unsigned int	failures;	/* current failure count */
 	unsigned int	max_failures;	/* maximum allowed failure count */
 	u64		probed_capacity;/* initial/native media capacity */
@@ -649,6 +629,7 @@
 	void	(*maskproc)(ide_drive_t *, int);
 	void	(*quirkproc)(ide_drive_t *);
 	void	(*clear_irq)(ide_drive_t *);
+	int	(*test_irq)(struct hwif_s *);
 
 	u8	(*mdma_filter)(ide_drive_t *);
 	u8	(*udma_filter)(ide_drive_t *);
@@ -674,6 +655,10 @@
 	u8	(*dma_sff_read_status)(struct hwif_s *);
 };
 
+enum {
+	IDE_PFLAG_PROBING		= (1 << 0),
+};
+
 struct ide_host;
 
 typedef struct hwif_s {
@@ -690,6 +675,8 @@
 
 	ide_drive_t	*devices[MAX_DRIVES + 1];
 
+	unsigned long	port_flags;
+
 	u8 major;	/* our major number */
 	u8 index;	/* 0 for ide0; 1 for ide1; ... */
 	u8 channel;	/* for dual-port chips: 0=primary, 1=secondary */
@@ -708,8 +695,6 @@
 
 	struct device *dev;
 
-	ide_ack_intr_t *ack_intr;
-
 	void (*rw_disk)(ide_drive_t *, struct request *);
 
 	const struct ide_tp_ops		*tp_ops;
@@ -1130,6 +1115,8 @@
 u8 ide_read_error(ide_drive_t *);
 void ide_read_bcount_and_ireason(ide_drive_t *, u16 *, u8 *);
 
+int ide_check_ireason(ide_drive_t *, struct request *, int, int, int);
+
 int ide_check_atapi_device(ide_drive_t *, const char *);
 
 void ide_init_pc(struct ide_atapi_pc *);
@@ -1154,7 +1141,8 @@
 	REQ_IDETAPE_WRITE	= (1 << 3),
 };
 
-int ide_queue_pc_tail(ide_drive_t *, struct gendisk *, struct ide_atapi_pc *);
+int ide_queue_pc_tail(ide_drive_t *, struct gendisk *, struct ide_atapi_pc *,
+		      void *, unsigned int);
 
 int ide_do_test_unit_ready(ide_drive_t *, struct gendisk *);
 int ide_do_start_stop(ide_drive_t *, struct gendisk *, int);
@@ -1524,6 +1512,7 @@
 int ide_scan_pio_blacklist(char *);
 const char *ide_xfer_verbose(u8);
 u8 ide_get_best_pio_mode(ide_drive_t *, u8, u8);
+int ide_pio_need_iordy(ide_drive_t *, const u8);
 int ide_set_pio_mode(ide_drive_t *, u8);
 int ide_set_dma_mode(ide_drive_t *, u8);
 void ide_set_pio(ide_drive_t *, u8);
@@ -1561,6 +1550,16 @@
 	return (peer->dev_flags & IDE_DFLAG_PRESENT) ? peer : NULL;
 }
 
+static inline void *ide_get_drivedata(ide_drive_t *drive)
+{
+	return drive->drive_data;
+}
+
+static inline void ide_set_drivedata(ide_drive_t *drive, void *data)
+{
+	drive->drive_data = data;
+}
+
 #define ide_port_for_each_dev(i, dev, port) \
 	for ((i) = 0; ((dev) = (port)->devices[i]) || (i) < MAX_DRIVES; (i)++)
 
diff --git a/include/linux/init.h b/include/linux/init.h
index 8c2c998..13b633e 100644
--- a/include/linux/init.h
+++ b/include/linux/init.h
@@ -134,6 +134,9 @@
 extern initcall_t __con_initcall_start[], __con_initcall_end[];
 extern initcall_t __security_initcall_start[], __security_initcall_end[];
 
+/* Used for contructor calls. */
+typedef void (*ctor_fn_t)(void);
+
 /* Defined in init/main.c */
 extern int do_one_initcall(initcall_t fn);
 extern char __initdata boot_command_line[];
diff --git a/include/linux/input.h b/include/linux/input.h
index 6fed4f6..8b3bc3e0 100644
--- a/include/linux/input.h
+++ b/include/linux/input.h
@@ -53,6 +53,7 @@
 	__s32 maximum;
 	__s32 fuzz;
 	__s32 flat;
+	__s32 resolution;
 };
 
 #define EVIOCGVERSION		_IOR('E', 0x01, int)			/* get driver version */
@@ -1109,6 +1110,7 @@
 	int absmin[ABS_MAX + 1];
 	int absfuzz[ABS_MAX + 1];
 	int absflat[ABS_MAX + 1];
+	int absres[ABS_MAX + 1];
 
 	int (*open)(struct input_dev *dev);
 	void (*close)(struct input_dev *dev);
diff --git a/include/linux/ipc_namespace.h b/include/linux/ipc_namespace.h
index 3bf40e2..e408722 100644
--- a/include/linux/ipc_namespace.h
+++ b/include/linux/ipc_namespace.h
@@ -94,13 +94,8 @@
 #endif
 
 #if defined(CONFIG_IPC_NS)
-extern void free_ipc_ns(struct ipc_namespace *ns);
 extern struct ipc_namespace *copy_ipcs(unsigned long flags,
 				       struct ipc_namespace *ns);
-extern void free_ipcs(struct ipc_namespace *ns, struct ipc_ids *ids,
-		      void (*free)(struct ipc_namespace *,
-				   struct kern_ipc_perm *));
-
 static inline struct ipc_namespace *get_ipc_ns(struct ipc_namespace *ns)
 {
 	if (ns)
diff --git a/include/linux/jbd2.h b/include/linux/jbd2.h
index cc02393..d97eb65 100644
--- a/include/linux/jbd2.h
+++ b/include/linux/jbd2.h
@@ -1315,6 +1315,12 @@
 #define BUFFER_TRACE2(bh, bh2, info)	do {} while (0)
 #define JBUFFER_TRACE(jh, info)	do {} while (0)
 
+/* 
+ * jbd2_dev_to_name is a utility function used by the jbd2 and ext4 
+ * tracing infrastructure to map a dev_t to a device name.
+ */
+extern const char *jbd2_dev_to_name(dev_t device);
+
 #endif	/* __KERNEL__ */
 
 #endif	/* _LINUX_JBD2_H */
diff --git a/include/linux/kernel.h b/include/linux/kernel.h
index c5a71c3..fac104e 100644
--- a/include/linux/kernel.h
+++ b/include/linux/kernel.h
@@ -58,7 +58,7 @@
 #define _RET_IP_		(unsigned long)__builtin_return_address(0)
 #define _THIS_IP_  ({ __label__ __here; __here: (unsigned long)&&__here; })
 
-#ifdef CONFIG_LBD
+#ifdef CONFIG_LBDAF
 # include <asm/div64.h>
 # define sector_div(a, b) do_div(a, b)
 #else
diff --git a/include/linux/kernel_stat.h b/include/linux/kernel_stat.h
index a77c600..348fa88 100644
--- a/include/linux/kernel_stat.h
+++ b/include/linux/kernel_stat.h
@@ -5,6 +5,7 @@
 #include <linux/threads.h>
 #include <linux/percpu.h>
 #include <linux/cpumask.h>
+#include <linux/interrupt.h>
 #include <asm/irq.h>
 #include <asm/cputime.h>
 
@@ -31,6 +32,7 @@
 #ifndef CONFIG_GENERIC_HARDIRQS
        unsigned int irqs[NR_IRQS];
 #endif
+	unsigned int softirqs[NR_SOFTIRQS];
 };
 
 DECLARE_PER_CPU(struct kernel_stat, kstat);
@@ -67,6 +69,16 @@
 
 #endif
 
+static inline void kstat_incr_softirqs_this_cpu(unsigned int irq)
+{
+	kstat_this_cpu.softirqs[irq]++;
+}
+
+static inline unsigned int kstat_softirqs_cpu(unsigned int irq, int cpu)
+{
+       return kstat_cpu(cpu).softirqs[irq];
+}
+
 /*
  * Number of interrupts per specific IRQ source, since bootup
  */
diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h
index 45add35..e46a073 100644
--- a/include/linux/memcontrol.h
+++ b/include/linux/memcontrol.h
@@ -117,7 +117,7 @@
 }
 
 extern bool mem_cgroup_oom_called(struct task_struct *task);
-
+void mem_cgroup_update_mapped_file_stat(struct page *page, int val);
 #else /* CONFIG_CGROUP_MEM_RES_CTLR */
 struct mem_cgroup;
 
@@ -271,6 +271,11 @@
 {
 }
 
+static inline void mem_cgroup_update_mapped_file_stat(struct page *page,
+							int val)
+{
+}
+
 #endif /* CONFIG_CGROUP_MEM_CONT */
 
 #endif /* _LINUX_MEMCONTROL_H */
diff --git a/include/linux/mfd/ab3100.h b/include/linux/mfd/ab3100.h
new file mode 100644
index 0000000..7a3f316
--- /dev/null
+++ b/include/linux/mfd/ab3100.h
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2007-2009 ST-Ericsson AB
+ * License terms: GNU General Public License (GPL) version 2
+ * AB3100 core access functions
+ * Author: Linus Walleij <linus.walleij@stericsson.com>
+ */
+
+#include <linux/device.h>
+
+#ifndef MFD_AB3100_H
+#define MFD_AB3100_H
+
+#define ABUNKNOWN	0
+#define	AB3000		1
+#define	AB3100		2
+
+/*
+ * AB3100, EVENTA1, A2 and A3 event register flags
+ * these are catenated into a single 32-bit flag in the code
+ * for event notification broadcasts.
+ */
+#define AB3100_EVENTA1_ONSWA				(0x01<<16)
+#define AB3100_EVENTA1_ONSWB				(0x02<<16)
+#define AB3100_EVENTA1_ONSWC				(0x04<<16)
+#define AB3100_EVENTA1_DCIO				(0x08<<16)
+#define AB3100_EVENTA1_OVER_TEMP			(0x10<<16)
+#define AB3100_EVENTA1_SIM_OFF				(0x20<<16)
+#define AB3100_EVENTA1_VBUS				(0x40<<16)
+#define AB3100_EVENTA1_VSET_USB				(0x80<<16)
+
+#define AB3100_EVENTA2_READY_TX				(0x01<<8)
+#define AB3100_EVENTA2_READY_RX				(0x02<<8)
+#define AB3100_EVENTA2_OVERRUN_ERROR			(0x04<<8)
+#define AB3100_EVENTA2_FRAMING_ERROR			(0x08<<8)
+#define AB3100_EVENTA2_CHARG_OVERCURRENT		(0x10<<8)
+#define AB3100_EVENTA2_MIDR				(0x20<<8)
+#define AB3100_EVENTA2_BATTERY_REM			(0x40<<8)
+#define AB3100_EVENTA2_ALARM				(0x80<<8)
+
+#define AB3100_EVENTA3_ADC_TRIG5			(0x01)
+#define AB3100_EVENTA3_ADC_TRIG4			(0x02)
+#define AB3100_EVENTA3_ADC_TRIG3			(0x04)
+#define AB3100_EVENTA3_ADC_TRIG2			(0x08)
+#define AB3100_EVENTA3_ADC_TRIGVBAT			(0x10)
+#define AB3100_EVENTA3_ADC_TRIGVTX			(0x20)
+#define AB3100_EVENTA3_ADC_TRIG1			(0x40)
+#define AB3100_EVENTA3_ADC_TRIG0			(0x80)
+
+/* AB3100, STR register flags */
+#define AB3100_STR_ONSWA				(0x01)
+#define AB3100_STR_ONSWB				(0x02)
+#define AB3100_STR_ONSWC				(0x04)
+#define AB3100_STR_DCIO					(0x08)
+#define AB3100_STR_BOOT_MODE				(0x10)
+#define AB3100_STR_SIM_OFF				(0x20)
+#define AB3100_STR_BATT_REMOVAL				(0x40)
+#define AB3100_STR_VBUS					(0x80)
+
+/**
+ * struct ab3100
+ * @access_mutex: lock out concurrent accesses to the AB3100 registers
+ * @dev: pointer to the containing device
+ * @i2c_client: I2C client for this chip
+ * @testreg_client: secondary client for test registers
+ * @chip_name: name of this chip variant
+ * @chip_id: 8 bit chip ID for this chip variant
+ * @work: an event handling worker
+ * @event_subscribers: event subscribers are listed here
+ * @startup_events: a copy of the first reading of the event registers
+ * @startup_events_read: whether the first events have been read
+ *
+ * This struct is PRIVATE and devices using it should NOT
+ * access ANY fields. It is used as a token for calling the
+ * AB3100 functions.
+ */
+struct ab3100 {
+	struct mutex access_mutex;
+	struct device *dev;
+	struct i2c_client *i2c_client;
+	struct i2c_client *testreg_client;
+	char chip_name[32];
+	u8 chip_id;
+	struct work_struct work;
+	struct blocking_notifier_head event_subscribers;
+	u32 startup_events;
+	bool startup_events_read;
+};
+
+int ab3100_set_register(struct ab3100 *ab3100, u8 reg, u8 regval);
+int ab3100_get_register(struct ab3100 *ab3100, u8 reg, u8 *regval);
+int ab3100_get_register_page(struct ab3100 *ab3100,
+			     u8 first_reg, u8 *regvals, u8 numregs);
+int ab3100_mask_and_set_register(struct ab3100 *ab3100,
+				 u8 reg, u8 andmask, u8 ormask);
+u8 ab3100_get_chip_type(struct ab3100 *ab3100);
+int ab3100_event_register(struct ab3100 *ab3100,
+			  struct notifier_block *nb);
+int ab3100_event_unregister(struct ab3100 *ab3100,
+			    struct notifier_block *nb);
+int ab3100_event_registers_startup_state_get(struct ab3100 *ab3100,
+					     u32 *fatevent);
+
+#endif
diff --git a/include/linux/mfd/asic3.h b/include/linux/mfd/asic3.h
index 322cd6d..de3c4ad 100644
--- a/include/linux/mfd/asic3.h
+++ b/include/linux/mfd/asic3.h
@@ -30,6 +30,13 @@
 #define ASIC3_NUM_GPIOS		64
 #define ASIC3_NR_IRQS		ASIC3_NUM_GPIOS + 6
 
+#define ASIC3_IRQ_LED0		64
+#define ASIC3_IRQ_LED1		65
+#define ASIC3_IRQ_LED2		66
+#define ASIC3_IRQ_SPI		67
+#define ASIC3_IRQ_SMBUS		68
+#define ASIC3_IRQ_OWM		69
+
 #define ASIC3_TO_GPIO(gpio) (NR_BUILTIN_GPIO + (gpio))
 
 #define ASIC3_GPIO_BANK_A	0
@@ -227,8 +234,8 @@
 
 
 /* Basic control of the SD ASIC */
-#define ASIC3_SDHWCTRL_Base	0x0E00
-#define ASIC3_SDHWCTRL_SDConf    0x00
+#define ASIC3_SDHWCTRL_BASE     0x0E00
+#define ASIC3_SDHWCTRL_SDCONF     0x00
 
 #define ASIC3_SDHWCTRL_SUSPEND    (1 << 0)  /* 1=suspend all SD operations */
 #define ASIC3_SDHWCTRL_CLKSEL     (1 << 1)  /* 1=SDICK, 0=HCLK */
@@ -242,10 +249,10 @@
 /* SD card power supply ctrl 1=enable */
 #define ASIC3_SDHWCTRL_SDPWR      (1 << 6)
 
-#define ASIC3_EXTCF_Base		0x1100
+#define ASIC3_EXTCF_BASE        0x1100
 
-#define ASIC3_EXTCF_Select         0x00
-#define ASIC3_EXTCF_Reset          0x04
+#define ASIC3_EXTCF_SELECT        0x00
+#define ASIC3_EXTCF_RESET         0x04
 
 #define ASIC3_EXTCF_SMOD0	         (1 << 0)  /* slot number of mode 0 */
 #define ASIC3_EXTCF_SMOD1	         (1 << 1)  /* slot number of mode 1 */
@@ -279,222 +286,9 @@
  *  SDIO_CTRL         Control registers for SDIO operations
  *
  *****************************************************************************/
-#define ASIC3_SD_CONFIG_Base            0x0400 /* Assumes 32 bit addressing */
-
-#define ASIC3_SD_CONFIG_Command           0x08   /* R/W: Command */
-
-/* [0:8] SD Control Register Base Address */
-#define ASIC3_SD_CONFIG_Addr0             0x20
-
-/* [9:31] SD Control Register Base Address */
-#define ASIC3_SD_CONFIG_Addr1             0x24
-
-/* R/O: interrupt assigned to pin */
-#define ASIC3_SD_CONFIG_IntPin            0x78
-
-/*
- * Set to 0x1f to clock SD controller, 0 otherwise.
- * At 0x82 - Gated Clock Ctrl
- */
-#define ASIC3_SD_CONFIG_ClkStop           0x80
-
-/* Control clock of SD controller */
-#define ASIC3_SD_CONFIG_ClockMode         0x84
-#define ASIC3_SD_CONFIG_SDHC_PinStatus    0x88   /* R/0: SD pins status */
-#define ASIC3_SD_CONFIG_SDHC_Power1       0x90   /* Power1 - manual pwr ctrl */
-
-/* auto power up after card inserted */
-#define ASIC3_SD_CONFIG_SDHC_Power2       0x92
-
-/* auto power down when card removed */
-#define ASIC3_SD_CONFIG_SDHC_Power3       0x94
-#define ASIC3_SD_CONFIG_SDHC_CardDetect   0x98
-#define ASIC3_SD_CONFIG_SDHC_Slot         0xA0   /* R/O: support slot number */
-#define ASIC3_SD_CONFIG_SDHC_ExtGateClk1  0x1E0  /* Not used */
-#define ASIC3_SD_CONFIG_SDHC_ExtGateClk2  0x1E2  /* Not used*/
-
-/* GPIO Output Reg. , at 0x1EA - GPIO Output Enable Reg. */
-#define ASIC3_SD_CONFIG_SDHC_GPIO_OutAndEnable  0x1E8
-#define ASIC3_SD_CONFIG_SDHC_GPIO_Status  0x1EC  /* GPIO Status Reg. */
-
-/* Bit 1: double buffer/single buffer */
-#define ASIC3_SD_CONFIG_SDHC_ExtGateClk3  0x1F0
-
-/* Memory access enable (set to 1 to access SD Controller) */
-#define SD_CONFIG_COMMAND_MAE                (1<<1)
-
-#define SD_CONFIG_CLK_ENABLE_ALL             0x1f
-
-#define SD_CONFIG_POWER1_PC_33V              0x0200    /* Set for 3.3 volts */
-#define SD_CONFIG_POWER1_PC_OFF              0x0000    /* Turn off power */
-
- /* two bits - number of cycles for card detection */
-#define SD_CONFIG_CARDDETECTMODE_CLK           ((x) & 0x3)
-
-
-#define ASIC3_SD_CTRL_Base            0x1000
-
-#define ASIC3_SD_CTRL_Cmd                  0x00
-#define ASIC3_SD_CTRL_Arg0                 0x08
-#define ASIC3_SD_CTRL_Arg1                 0x0C
-#define ASIC3_SD_CTRL_StopInternal         0x10
-#define ASIC3_SD_CTRL_TransferSectorCount  0x14
-#define ASIC3_SD_CTRL_Response0            0x18
-#define ASIC3_SD_CTRL_Response1            0x1C
-#define ASIC3_SD_CTRL_Response2            0x20
-#define ASIC3_SD_CTRL_Response3            0x24
-#define ASIC3_SD_CTRL_Response4            0x28
-#define ASIC3_SD_CTRL_Response5            0x2C
-#define ASIC3_SD_CTRL_Response6            0x30
-#define ASIC3_SD_CTRL_Response7            0x34
-#define ASIC3_SD_CTRL_CardStatus           0x38
-#define ASIC3_SD_CTRL_BufferCtrl           0x3C
-#define ASIC3_SD_CTRL_IntMaskCard          0x40
-#define ASIC3_SD_CTRL_IntMaskBuffer        0x44
-#define ASIC3_SD_CTRL_CardClockCtrl        0x48
-#define ASIC3_SD_CTRL_MemCardXferDataLen   0x4C
-#define ASIC3_SD_CTRL_MemCardOptionSetup   0x50
-#define ASIC3_SD_CTRL_ErrorStatus0         0x58
-#define ASIC3_SD_CTRL_ErrorStatus1         0x5C
-#define ASIC3_SD_CTRL_DataPort             0x60
-#define ASIC3_SD_CTRL_TransactionCtrl      0x68
-#define ASIC3_SD_CTRL_SoftwareReset        0x1C0
-
-#define SD_CTRL_SOFTWARE_RESET_CLEAR            (1<<0)
-
-#define SD_CTRL_TRANSACTIONCONTROL_SET          (1<<8)
-
-#define SD_CTRL_CARDCLOCKCONTROL_FOR_SD_CARD    (1<<15)
-#define SD_CTRL_CARDCLOCKCONTROL_ENABLE_CLOCK   (1<<8)
-#define SD_CTRL_CARDCLOCKCONTROL_CLK_DIV_512    (1<<7)
-#define SD_CTRL_CARDCLOCKCONTROL_CLK_DIV_256    (1<<6)
-#define SD_CTRL_CARDCLOCKCONTROL_CLK_DIV_128    (1<<5)
-#define SD_CTRL_CARDCLOCKCONTROL_CLK_DIV_64     (1<<4)
-#define SD_CTRL_CARDCLOCKCONTROL_CLK_DIV_32     (1<<3)
-#define SD_CTRL_CARDCLOCKCONTROL_CLK_DIV_16     (1<<2)
-#define SD_CTRL_CARDCLOCKCONTROL_CLK_DIV_8      (1<<1)
-#define SD_CTRL_CARDCLOCKCONTROL_CLK_DIV_4      (1<<0)
-#define SD_CTRL_CARDCLOCKCONTROL_CLK_DIV_2      (0<<0)
-
-#define MEM_CARD_OPTION_REQUIRED                   0x000e
-#define MEM_CARD_OPTION_DATA_RESPONSE_TIMEOUT(x)   (((x) & 0x0f) << 4)
-#define MEM_CARD_OPTION_C2_MODULE_NOT_PRESENT      (1<<14)
-#define MEM_CARD_OPTION_DATA_XFR_WIDTH_1           (1<<15)
-#define MEM_CARD_OPTION_DATA_XFR_WIDTH_4           0
-
-#define SD_CTRL_COMMAND_INDEX(x)                   ((x) & 0x3f)
-#define SD_CTRL_COMMAND_TYPE_CMD                   (0 << 6)
-#define SD_CTRL_COMMAND_TYPE_ACMD                  (1 << 6)
-#define SD_CTRL_COMMAND_TYPE_AUTHENTICATION        (2 << 6)
-#define SD_CTRL_COMMAND_RESPONSE_TYPE_NORMAL       (0 << 8)
-#define SD_CTRL_COMMAND_RESPONSE_TYPE_EXT_R1       (4 << 8)
-#define SD_CTRL_COMMAND_RESPONSE_TYPE_EXT_R1B      (5 << 8)
-#define SD_CTRL_COMMAND_RESPONSE_TYPE_EXT_R2       (6 << 8)
-#define SD_CTRL_COMMAND_RESPONSE_TYPE_EXT_R3       (7 << 8)
-#define SD_CTRL_COMMAND_DATA_PRESENT               (1 << 11)
-#define SD_CTRL_COMMAND_TRANSFER_READ              (1 << 12)
-#define SD_CTRL_COMMAND_TRANSFER_WRITE             (0 << 12)
-#define SD_CTRL_COMMAND_MULTI_BLOCK                (1 << 13)
-#define SD_CTRL_COMMAND_SECURITY_CMD               (1 << 14)
-
-#define SD_CTRL_STOP_INTERNAL_ISSSUE_CMD12         (1 << 0)
-#define SD_CTRL_STOP_INTERNAL_AUTO_ISSUE_CMD12     (1 << 8)
-
-#define SD_CTRL_CARDSTATUS_RESPONSE_END            (1 << 0)
-#define SD_CTRL_CARDSTATUS_RW_END                  (1 << 2)
-#define SD_CTRL_CARDSTATUS_CARD_REMOVED_0          (1 << 3)
-#define SD_CTRL_CARDSTATUS_CARD_INSERTED_0         (1 << 4)
-#define SD_CTRL_CARDSTATUS_SIGNAL_STATE_PRESENT_0  (1 << 5)
-#define SD_CTRL_CARDSTATUS_WRITE_PROTECT           (1 << 7)
-#define SD_CTRL_CARDSTATUS_CARD_REMOVED_3          (1 << 8)
-#define SD_CTRL_CARDSTATUS_CARD_INSERTED_3         (1 << 9)
-#define SD_CTRL_CARDSTATUS_SIGNAL_STATE_PRESENT_3  (1 << 10)
-
-#define SD_CTRL_BUFFERSTATUS_CMD_INDEX_ERROR       (1 << 0)
-#define SD_CTRL_BUFFERSTATUS_CRC_ERROR             (1 << 1)
-#define SD_CTRL_BUFFERSTATUS_STOP_BIT_END_ERROR    (1 << 2)
-#define SD_CTRL_BUFFERSTATUS_DATA_TIMEOUT          (1 << 3)
-#define SD_CTRL_BUFFERSTATUS_BUFFER_OVERFLOW       (1 << 4)
-#define SD_CTRL_BUFFERSTATUS_BUFFER_UNDERFLOW      (1 << 5)
-#define SD_CTRL_BUFFERSTATUS_CMD_TIMEOUT           (1 << 6)
-#define SD_CTRL_BUFFERSTATUS_UNK7                  (1 << 7)
-#define SD_CTRL_BUFFERSTATUS_BUFFER_READ_ENABLE    (1 << 8)
-#define SD_CTRL_BUFFERSTATUS_BUFFER_WRITE_ENABLE   (1 << 9)
-#define SD_CTRL_BUFFERSTATUS_ILLEGAL_FUNCTION      (1 << 13)
-#define SD_CTRL_BUFFERSTATUS_CMD_BUSY              (1 << 14)
-#define SD_CTRL_BUFFERSTATUS_ILLEGAL_ACCESS        (1 << 15)
-
-#define SD_CTRL_INTMASKCARD_RESPONSE_END           (1 << 0)
-#define SD_CTRL_INTMASKCARD_RW_END                 (1 << 2)
-#define SD_CTRL_INTMASKCARD_CARD_REMOVED_0         (1 << 3)
-#define SD_CTRL_INTMASKCARD_CARD_INSERTED_0        (1 << 4)
-#define SD_CTRL_INTMASKCARD_SIGNAL_STATE_PRESENT_0 (1 << 5)
-#define SD_CTRL_INTMASKCARD_UNK6                   (1 << 6)
-#define SD_CTRL_INTMASKCARD_WRITE_PROTECT          (1 << 7)
-#define SD_CTRL_INTMASKCARD_CARD_REMOVED_3         (1 << 8)
-#define SD_CTRL_INTMASKCARD_CARD_INSERTED_3        (1 << 9)
-#define SD_CTRL_INTMASKCARD_SIGNAL_STATE_PRESENT_3 (1 << 10)
-
-#define SD_CTRL_INTMASKBUFFER_CMD_INDEX_ERROR      (1 << 0)
-#define SD_CTRL_INTMASKBUFFER_CRC_ERROR            (1 << 1)
-#define SD_CTRL_INTMASKBUFFER_STOP_BIT_END_ERROR   (1 << 2)
-#define SD_CTRL_INTMASKBUFFER_DATA_TIMEOUT         (1 << 3)
-#define SD_CTRL_INTMASKBUFFER_BUFFER_OVERFLOW      (1 << 4)
-#define SD_CTRL_INTMASKBUFFER_BUFFER_UNDERFLOW     (1 << 5)
-#define SD_CTRL_INTMASKBUFFER_CMD_TIMEOUT          (1 << 6)
-#define SD_CTRL_INTMASKBUFFER_UNK7                 (1 << 7)
-#define SD_CTRL_INTMASKBUFFER_BUFFER_READ_ENABLE   (1 << 8)
-#define SD_CTRL_INTMASKBUFFER_BUFFER_WRITE_ENABLE  (1 << 9)
-#define SD_CTRL_INTMASKBUFFER_ILLEGAL_FUNCTION     (1 << 13)
-#define SD_CTRL_INTMASKBUFFER_CMD_BUSY             (1 << 14)
-#define SD_CTRL_INTMASKBUFFER_ILLEGAL_ACCESS       (1 << 15)
-
-#define SD_CTRL_DETAIL0_RESPONSE_CMD_ERROR                   (1 << 0)
-#define SD_CTRL_DETAIL0_END_BIT_ERROR_FOR_RESPONSE_NON_CMD12 (1 << 2)
-#define SD_CTRL_DETAIL0_END_BIT_ERROR_FOR_RESPONSE_CMD12     (1 << 3)
-#define SD_CTRL_DETAIL0_END_BIT_ERROR_FOR_READ_DATA          (1 << 4)
-#define SD_CTRL_DETAIL0_END_BIT_ERROR_FOR_WRITE_CRC_STATUS   (1 << 5)
-#define SD_CTRL_DETAIL0_CRC_ERROR_FOR_RESPONSE_NON_CMD12     (1 << 8)
-#define SD_CTRL_DETAIL0_CRC_ERROR_FOR_RESPONSE_CMD12         (1 << 9)
-#define SD_CTRL_DETAIL0_CRC_ERROR_FOR_READ_DATA              (1 << 10)
-#define SD_CTRL_DETAIL0_CRC_ERROR_FOR_WRITE_CMD              (1 << 11)
-
-#define SD_CTRL_DETAIL1_NO_CMD_RESPONSE                      (1 << 0)
-#define SD_CTRL_DETAIL1_TIMEOUT_READ_DATA                    (1 << 4)
-#define SD_CTRL_DETAIL1_TIMEOUT_CRS_STATUS                   (1 << 5)
-#define SD_CTRL_DETAIL1_TIMEOUT_CRC_BUSY                     (1 << 6)
-
-#define ASIC3_SDIO_CTRL_Base          0x1200
-
-#define ASIC3_SDIO_CTRL_Cmd                  0x00
-#define ASIC3_SDIO_CTRL_CardPortSel          0x04
-#define ASIC3_SDIO_CTRL_Arg0                 0x08
-#define ASIC3_SDIO_CTRL_Arg1                 0x0C
-#define ASIC3_SDIO_CTRL_TransferBlockCount   0x14
-#define ASIC3_SDIO_CTRL_Response0            0x18
-#define ASIC3_SDIO_CTRL_Response1            0x1C
-#define ASIC3_SDIO_CTRL_Response2            0x20
-#define ASIC3_SDIO_CTRL_Response3            0x24
-#define ASIC3_SDIO_CTRL_Response4            0x28
-#define ASIC3_SDIO_CTRL_Response5            0x2C
-#define ASIC3_SDIO_CTRL_Response6            0x30
-#define ASIC3_SDIO_CTRL_Response7            0x34
-#define ASIC3_SDIO_CTRL_CardStatus           0x38
-#define ASIC3_SDIO_CTRL_BufferCtrl           0x3C
-#define ASIC3_SDIO_CTRL_IntMaskCard          0x40
-#define ASIC3_SDIO_CTRL_IntMaskBuffer        0x44
-#define ASIC3_SDIO_CTRL_CardXferDataLen      0x4C
-#define ASIC3_SDIO_CTRL_CardOptionSetup      0x50
-#define ASIC3_SDIO_CTRL_ErrorStatus0         0x54
-#define ASIC3_SDIO_CTRL_ErrorStatus1         0x58
-#define ASIC3_SDIO_CTRL_DataPort             0x60
-#define ASIC3_SDIO_CTRL_TransactionCtrl      0x68
-#define ASIC3_SDIO_CTRL_CardIntCtrl          0x6C
-#define ASIC3_SDIO_CTRL_ClocknWaitCtrl       0x70
-#define ASIC3_SDIO_CTRL_HostInformation      0x74
-#define ASIC3_SDIO_CTRL_ErrorCtrl            0x78
-#define ASIC3_SDIO_CTRL_LEDCtrl              0x7C
-#define ASIC3_SDIO_CTRL_SoftwareReset        0x1C0
+#define ASIC3_SD_CONFIG_BASE	0x0400 /* Assumes 32 bit addressing */
+#define ASIC3_SD_CTRL_BASE	0x1000
+#define ASIC3_SDIO_CTRL_BASE	0x1200
 
 #define ASIC3_MAP_SIZE_32BIT	0x2000
 #define ASIC3_MAP_SIZE_16BIT	0x1000
diff --git a/include/linux/mfd/ezx-pcap.h b/include/linux/mfd/ezx-pcap.h
new file mode 100644
index 0000000..c12c3c0
--- /dev/null
+++ b/include/linux/mfd/ezx-pcap.h
@@ -0,0 +1,256 @@
+/*
+ * Copyright 2009 Daniel Ribeiro <drwyrm@gmail.com>
+ *
+ * For further information, please see http://wiki.openezx.org/PCAP2
+ */
+
+#ifndef EZX_PCAP_H
+#define EZX_PCAP_H
+
+struct pcap_subdev {
+	int id;
+	const char *name;
+	void *platform_data;
+};
+
+struct pcap_platform_data {
+	unsigned int irq_base;
+	unsigned int config;
+	void (*init) (void *);	/* board specific init */
+	int num_subdevs;
+	struct pcap_subdev *subdevs;
+};
+
+struct pcap_chip;
+
+int ezx_pcap_write(struct pcap_chip *, u8, u32);
+int ezx_pcap_read(struct pcap_chip *, u8, u32 *);
+int pcap_to_irq(struct pcap_chip *, int);
+int pcap_adc_async(struct pcap_chip *, u8, u32, u8[], void *, void *);
+int pcap_adc_sync(struct pcap_chip *, u8, u32, u8[], u16[]);
+
+#define PCAP_SECOND_PORT	1
+#define PCAP_CS_AH		2
+
+#define PCAP_REGISTER_WRITE_OP_BIT	0x80000000
+#define PCAP_REGISTER_READ_OP_BIT	0x00000000
+
+#define PCAP_REGISTER_VALUE_MASK	0x01ffffff
+#define PCAP_REGISTER_ADDRESS_MASK	0x7c000000
+#define PCAP_REGISTER_ADDRESS_SHIFT	26
+#define PCAP_REGISTER_NUMBER		32
+#define PCAP_CLEAR_INTERRUPT_REGISTER	0x01ffffff
+#define PCAP_MASK_ALL_INTERRUPT		0x01ffffff
+
+/* registers acessible by both pcap ports */
+#define PCAP_REG_ISR		0x0	/* Interrupt Status */
+#define PCAP_REG_MSR		0x1	/* Interrupt Mask */
+#define PCAP_REG_PSTAT		0x2	/* Processor Status */
+#define PCAP_REG_VREG2		0x6	/* Regulator Bank 2 Control */
+#define PCAP_REG_AUXVREG	0x7	/* Auxiliary Regulator Control */
+#define PCAP_REG_BATT		0x8	/* Battery Control */
+#define PCAP_REG_ADC		0x9	/* AD Control */
+#define PCAP_REG_ADR		0xa	/* AD Result */
+#define PCAP_REG_CODEC		0xb	/* Audio Codec Control */
+#define PCAP_REG_RX_AMPS	0xc	/* RX Audio Amplifiers Control */
+#define PCAP_REG_ST_DAC		0xd	/* Stereo DAC Control */
+#define PCAP_REG_BUSCTRL	0x14	/* Connectivity Control */
+#define PCAP_REG_PERIPH		0x15	/* Peripheral Control */
+#define PCAP_REG_LOWPWR		0x18	/* Regulator Low Power Control */
+#define PCAP_REG_TX_AMPS	0x1a	/* TX Audio Amplifiers Control */
+#define PCAP_REG_GP		0x1b	/* General Purpose */
+#define PCAP_REG_TEST1		0x1c
+#define PCAP_REG_TEST2		0x1d
+#define PCAP_REG_VENDOR_TEST1	0x1e
+#define PCAP_REG_VENDOR_TEST2	0x1f
+
+/* registers acessible by pcap port 1 only (a1200, e2 & e6) */
+#define PCAP_REG_INT_SEL	0x3	/* Interrupt Select */
+#define PCAP_REG_SWCTRL		0x4	/* Switching Regulator Control */
+#define PCAP_REG_VREG1		0x5	/* Regulator Bank 1 Control */
+#define PCAP_REG_RTC_TOD	0xe	/* RTC Time of Day */
+#define PCAP_REG_RTC_TODA	0xf	/* RTC Time of Day Alarm */
+#define PCAP_REG_RTC_DAY	0x10	/* RTC Day */
+#define PCAP_REG_RTC_DAYA	0x11	/* RTC Day Alarm */
+#define PCAP_REG_MTRTMR		0x12	/* AD Monitor Timer */
+#define PCAP_REG_PWR		0x13	/* Power Control */
+#define PCAP_REG_AUXVREG_MASK	0x16	/* Auxiliary Regulator Mask */
+#define PCAP_REG_VENDOR_REV	0x17
+#define PCAP_REG_PERIPH_MASK	0x19	/* Peripheral Mask */
+
+/* PCAP2 Interrupts */
+#define PCAP_NIRQS		23
+#define PCAP_IRQ_ADCDONE	0	/* ADC done port 1 */
+#define PCAP_IRQ_TS		1	/* Touch Screen */
+#define PCAP_IRQ_1HZ		2	/* 1HZ timer */
+#define PCAP_IRQ_WH		3	/* ADC above high limit */
+#define PCAP_IRQ_WL		4	/* ADC below low limit */
+#define PCAP_IRQ_TODA		5	/* Time of day alarm */
+#define PCAP_IRQ_USB4V		6	/* USB above 4V */
+#define PCAP_IRQ_ONOFF		7	/* On/Off button */
+#define PCAP_IRQ_ONOFF2		8	/* On/Off button 2 */
+#define PCAP_IRQ_USB1V		9	/* USB above 1V */
+#define PCAP_IRQ_MOBPORT	10
+#define PCAP_IRQ_MIC		11	/* Mic attach/HS button */
+#define PCAP_IRQ_HS		12	/* Headset attach */
+#define PCAP_IRQ_ST		13
+#define PCAP_IRQ_PC		14	/* Power Cut */
+#define PCAP_IRQ_WARM		15
+#define PCAP_IRQ_EOL		16	/* Battery End Of Life */
+#define PCAP_IRQ_CLK		17
+#define PCAP_IRQ_SYSRST		18	/* System Reset */
+#define PCAP_IRQ_DUMMY		19
+#define PCAP_IRQ_ADCDONE2	20	/* ADC done port 2 */
+#define PCAP_IRQ_SOFTRESET	21
+#define PCAP_IRQ_MNEXB		22
+
+/* voltage regulators */
+#define V1		0
+#define V2		1
+#define V3		2
+#define V4		3
+#define V5		4
+#define V6		5
+#define V7		6
+#define V8		7
+#define V9		8
+#define V10		9
+#define VAUX1		10
+#define VAUX2		11
+#define VAUX3		12
+#define VAUX4		13
+#define VSIM		14
+#define VSIM2		15
+#define VVIB		16
+#define SW1		17
+#define SW2		18
+#define SW3		19
+#define SW1S		20
+#define SW2S		21
+
+#define PCAP_BATT_DAC_MASK		0x000000ff
+#define PCAP_BATT_DAC_SHIFT		0
+#define PCAP_BATT_B_FDBK		(1 << 8)
+#define PCAP_BATT_EXT_ISENSE		(1 << 9)
+#define PCAP_BATT_V_COIN_MASK		0x00003c00
+#define PCAP_BATT_V_COIN_SHIFT		10
+#define PCAP_BATT_I_COIN		(1 << 14)
+#define PCAP_BATT_COIN_CH_EN		(1 << 15)
+#define PCAP_BATT_EOL_SEL_MASK		0x000e0000
+#define PCAP_BATT_EOL_SEL_SHIFT		17
+#define PCAP_BATT_EOL_CMP_EN		(1 << 20)
+#define PCAP_BATT_BATT_DET_EN		(1 << 21)
+#define PCAP_BATT_THERMBIAS_CTRL	(1 << 22)
+
+#define PCAP_ADC_ADEN			(1 << 0)
+#define PCAP_ADC_RAND			(1 << 1)
+#define PCAP_ADC_AD_SEL1		(1 << 2)
+#define PCAP_ADC_AD_SEL2		(1 << 3)
+#define PCAP_ADC_ADA1_MASK		0x00000070
+#define PCAP_ADC_ADA1_SHIFT		4
+#define PCAP_ADC_ADA2_MASK		0x00000380
+#define PCAP_ADC_ADA2_SHIFT		7
+#define PCAP_ADC_ATO_MASK		0x00003c00
+#define PCAP_ADC_ATO_SHIFT		10
+#define PCAP_ADC_ATOX			(1 << 14)
+#define PCAP_ADC_MTR1			(1 << 15)
+#define PCAP_ADC_MTR2			(1 << 16)
+#define PCAP_ADC_TS_M_MASK		0x000e0000
+#define PCAP_ADC_TS_M_SHIFT		17
+#define PCAP_ADC_TS_REF_LOWPWR		(1 << 20)
+#define PCAP_ADC_TS_REFENB		(1 << 21)
+#define PCAP_ADC_BATT_I_POLARITY	(1 << 22)
+#define PCAP_ADC_BATT_I_ADC		(1 << 23)
+
+#define PCAP_ADC_BANK_0			0
+#define PCAP_ADC_BANK_1			1
+/* ADC bank 0 */
+#define PCAP_ADC_CH_COIN		0
+#define PCAP_ADC_CH_BATT		1
+#define PCAP_ADC_CH_BPLUS		2
+#define PCAP_ADC_CH_MOBPORTB		3
+#define PCAP_ADC_CH_TEMPERATURE		4
+#define PCAP_ADC_CH_CHARGER_ID		5
+#define PCAP_ADC_CH_AD6			6
+/* ADC bank 1 */
+#define PCAP_ADC_CH_AD7			0
+#define PCAP_ADC_CH_AD8			1
+#define PCAP_ADC_CH_AD9			2
+#define PCAP_ADC_CH_TS_X1		3
+#define PCAP_ADC_CH_TS_X2		4
+#define PCAP_ADC_CH_TS_Y1		5
+#define PCAP_ADC_CH_TS_Y2		6
+
+#define PCAP_ADC_T_NOW			0
+#define PCAP_ADC_T_IN_BURST		1
+#define PCAP_ADC_T_OUT_BURST		2
+
+#define PCAP_ADC_ATO_IN_BURST		6
+#define PCAP_ADC_ATO_OUT_BURST		0
+
+#define PCAP_ADC_TS_M_XY		1
+#define PCAP_ADC_TS_M_PRESSURE		2
+#define PCAP_ADC_TS_M_PLATE_X		3
+#define PCAP_ADC_TS_M_PLATE_Y		4
+#define PCAP_ADC_TS_M_STANDBY		5
+#define PCAP_ADC_TS_M_NONTS		6
+
+#define PCAP_ADR_ADD1_MASK		0x000003ff
+#define PCAP_ADR_ADD1_SHIFT		0
+#define PCAP_ADR_ADD2_MASK		0x000ffc00
+#define PCAP_ADR_ADD2_SHIFT		10
+#define PCAP_ADR_ADINC1			(1 << 20)
+#define PCAP_ADR_ADINC2			(1 << 21)
+#define PCAP_ADR_ASC			(1 << 22)
+#define PCAP_ADR_ONESHOT		(1 << 23)
+
+#define PCAP_BUSCTRL_FSENB		(1 << 0)
+#define PCAP_BUSCTRL_USB_SUSPEND	(1 << 1)
+#define PCAP_BUSCTRL_USB_PU		(1 << 2)
+#define PCAP_BUSCTRL_USB_PD		(1 << 3)
+#define PCAP_BUSCTRL_VUSB_EN		(1 << 4)
+#define PCAP_BUSCTRL_USB_PS		(1 << 5)
+#define PCAP_BUSCTRL_VUSB_MSTR_EN	(1 << 6)
+#define PCAP_BUSCTRL_VBUS_PD_ENB	(1 << 7)
+#define PCAP_BUSCTRL_CURRLIM		(1 << 8)
+#define PCAP_BUSCTRL_RS232ENB		(1 << 9)
+#define PCAP_BUSCTRL_RS232_DIR		(1 << 10)
+#define PCAP_BUSCTRL_SE0_CONN		(1 << 11)
+#define PCAP_BUSCTRL_USB_PDM		(1 << 12)
+#define PCAP_BUSCTRL_BUS_PRI_ADJ	(1 << 24)
+
+/* leds */
+#define PCAP_LED0		0
+#define PCAP_LED1		1
+#define PCAP_BL0		2
+#define PCAP_BL1		3
+#define PCAP_VIB		4
+#define PCAP_LED_3MA		0
+#define PCAP_LED_4MA		1
+#define PCAP_LED_5MA		2
+#define PCAP_LED_9MA		3
+#define PCAP_LED_GPIO_VAL_MASK	0x00ffffff
+#define PCAP_LED_GPIO_EN	0x01000000
+#define PCAP_LED_GPIO_INVERT	0x02000000
+#define PCAP_LED_T_MASK		0xf
+#define PCAP_LED_C_MASK		0x3
+#define PCAP_BL_MASK		0x1f
+#define PCAP_BL0_SHIFT		0
+#define PCAP_LED0_EN		(1 << 5)
+#define PCAP_LED1_EN		(1 << 6)
+#define PCAP_LED0_T_SHIFT	7
+#define PCAP_LED1_T_SHIFT	11
+#define PCAP_LED0_C_SHIFT	15
+#define PCAP_LED1_C_SHIFT	17
+#define PCAP_BL1_SHIFT		20
+#define PCAP_VIB_MASK		0x3
+#define PCAP_VIB_SHIFT		20
+#define PCAP_VIB_EN		(1 << 19)
+
+/* RTC */
+#define PCAP_RTC_DAY_MASK	0x3fff
+#define PCAP_RTC_TOD_MASK	0xffff
+#define PCAP_RTC_PC_MASK	0x7
+#define SEC_PER_DAY		86400
+
+#endif
diff --git a/include/linux/mfd/tmio.h b/include/linux/mfd/tmio.h
index c377118..6b9c5d0 100644
--- a/include/linux/mfd/tmio.h
+++ b/include/linux/mfd/tmio.h
@@ -22,7 +22,7 @@
  * data for the MMC controller
  */
 struct tmio_mmc_data {
-	unsigned int		hclk;
+	const unsigned int		hclk;
 };
 
 /*
diff --git a/include/linux/module.h b/include/linux/module.h
index 505f20d..098bdb7 100644
--- a/include/linux/module.h
+++ b/include/linux/module.h
@@ -363,6 +363,12 @@
 	local_t ref;
 #endif
 #endif
+
+#ifdef CONFIG_CONSTRUCTORS
+	/* Constructor functions. */
+	ctor_fn_t *ctors;
+	unsigned int num_ctors;
+#endif
 };
 #ifndef MODULE_ARCH_INIT
 #define MODULE_ARCH_INIT {}
diff --git a/include/linux/mtd/ubi.h b/include/linux/mtd/ubi.h
index 6316faf..6913b71 100644
--- a/include/linux/mtd/ubi.h
+++ b/include/linux/mtd/ubi.h
@@ -132,6 +132,39 @@
 	dev_t cdev;
 };
 
+/*
+ * enum - volume notification types.
+ * @UBI_VOLUME_ADDED: volume has been added
+ * @UBI_VOLUME_REMOVED: start volume volume
+ * @UBI_VOLUME_RESIZED: volume size has been re-sized
+ * @UBI_VOLUME_RENAMED: volume name has been re-named
+ * @UBI_VOLUME_UPDATED: volume name has been updated
+ *
+ * These constants define which type of event has happened when a volume
+ * notification function is invoked.
+ */
+enum {
+	UBI_VOLUME_ADDED,
+	UBI_VOLUME_REMOVED,
+	UBI_VOLUME_RESIZED,
+	UBI_VOLUME_RENAMED,
+	UBI_VOLUME_UPDATED,
+};
+
+/*
+ * struct ubi_notification - UBI notification description structure.
+ * @di: UBI device description object
+ * @vi: UBI volume description object
+ *
+ * UBI notifiers are called with a pointer to an object of this type. The
+ * object describes the notification. Namely, it provides a description of the
+ * UBI device and UBI volume the notification informs about.
+ */
+struct ubi_notification {
+	struct ubi_device_info di;
+	struct ubi_volume_info vi;
+};
+
 /* UBI descriptor given to users when they open UBI volumes */
 struct ubi_volume_desc;
 
@@ -141,6 +174,10 @@
 struct ubi_volume_desc *ubi_open_volume(int ubi_num, int vol_id, int mode);
 struct ubi_volume_desc *ubi_open_volume_nm(int ubi_num, const char *name,
 					   int mode);
+int ubi_register_volume_notifier(struct notifier_block *nb,
+				 int ignore_existing);
+int ubi_unregister_volume_notifier(struct notifier_block *nb);
+
 void ubi_close_volume(struct ubi_volume_desc *desc);
 int ubi_leb_read(struct ubi_volume_desc *desc, int lnum, char *buf, int offset,
 		 int len, int check);
diff --git a/include/linux/netdevice.h b/include/linux/netdevice.h
index 9ea8d6d..d4a4d98 100644
--- a/include/linux/netdevice.h
+++ b/include/linux/netdevice.h
@@ -224,6 +224,11 @@
 	struct rcu_head		rcu_head;
 };
 
+struct netdev_hw_addr_list {
+	struct list_head	list;
+	int			count;
+};
+
 struct hh_cache
 {
 	struct hh_cache *hh_next;	/* Next entry			     */
@@ -776,9 +781,8 @@
 	unsigned char		addr_len;	/* hardware address length	*/
 	unsigned short          dev_id;		/* for shared network cards */
 
-	struct list_head	uc_list;	/* Secondary unicast mac
-						   addresses */
-	int			uc_count;	/* Number of installed ucasts	*/
+	struct netdev_hw_addr_list	uc;	/* Secondary unicast
+						   mac addresses */
 	int			uc_promisc;
 	spinlock_t		addr_list_lock;
 	struct dev_addr_list	*mc_list;	/* Multicast mac addresses	*/
@@ -810,7 +814,8 @@
 						   because most packets are
 						   unicast) */
 
-	struct list_head	dev_addr_list; /* list of device hw addresses */
+	struct netdev_hw_addr_list	dev_addrs; /* list of device
+						      hw addresses */
 
 	unsigned char		broadcast[MAX_ADDR_LEN];	/* hw bcast add	*/
 
@@ -1806,11 +1811,11 @@
 }
 
 /*
- * dev_addr_list walker. Should be used only for read access. Call with
+ * dev_addrs walker. Should be used only for read access. Call with
  * rcu_read_lock held.
  */
 #define for_each_dev_addr(dev, ha) \
-		list_for_each_entry_rcu(ha, &dev->dev_addr_list, list)
+		list_for_each_entry_rcu(ha, &dev->dev_addrs.list, list)
 
 /* These functions live elsewhere (drivers/net/net_init.c, but related) */
 
diff --git a/include/linux/page-flags.h b/include/linux/page-flags.h
index d6792f8..e2e5ce5 100644
--- a/include/linux/page-flags.h
+++ b/include/linux/page-flags.h
@@ -118,7 +118,6 @@
 	PG_savepinned = PG_dirty,
 
 	/* SLOB */
-	PG_slob_page = PG_active,
 	PG_slob_free = PG_private,
 
 	/* SLUB */
@@ -201,7 +200,6 @@
 PAGEFLAG(Reserved, reserved) __CLEARPAGEFLAG(Reserved, reserved)
 PAGEFLAG(SwapBacked, swapbacked) __CLEARPAGEFLAG(SwapBacked, swapbacked)
 
-__PAGEFLAG(SlobPage, slob_page)
 __PAGEFLAG(SlobFree, slob_free)
 
 __PAGEFLAG(SlubFrozen, slub_frozen)
diff --git a/include/linux/pps.h b/include/linux/pps.h
new file mode 100644
index 0000000..cfe5c72
--- /dev/null
+++ b/include/linux/pps.h
@@ -0,0 +1,122 @@
+/*
+ * PPS API header
+ *
+ * Copyright (C) 2005-2009   Rodolfo Giometti <giometti@linux.it>
+ *
+ *   This program is free software; you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+
+#ifndef _PPS_H_
+#define _PPS_H_
+
+#define PPS_VERSION		"5.3.6"
+#define PPS_MAX_SOURCES		16		/* should be enough... */
+
+/* Implementation note: the logical states ``assert'' and ``clear''
+ * are implemented in terms of the chip register, i.e. ``assert''
+ * means the bit is set.  */
+
+/*
+ * 3.2 New data structures
+ */
+
+#define PPS_API_VERS_1		1
+#define PPS_API_VERS		PPS_API_VERS_1	/* we use API version 1 */
+#define PPS_MAX_NAME_LEN	32
+
+/* 32-bit vs. 64-bit compatibility.
+ *
+ * 0n i386, the alignment of a uint64_t is only 4 bytes, while on most other
+ * architectures it's 8 bytes. On i386, there will be no padding between the
+ * two consecutive 'struct pps_ktime' members of struct pps_kinfo and struct
+ * pps_kparams. But on most platforms there will be padding to ensure correct
+ * alignment.
+ *
+ * The simple fix is probably to add an explicit padding.
+ *					 		[David Woodhouse]
+ */
+struct pps_ktime {
+	__s64 sec;
+	__s32 nsec;
+	__u32 flags;
+};
+#define PPS_TIME_INVALID	(1<<0)	/* used to specify timeout==NULL */
+
+struct pps_kinfo {
+	__u32 assert_sequence;		/* seq. num. of assert event */
+	__u32 clear_sequence; 		/* seq. num. of clear event */
+	struct pps_ktime assert_tu;	/* time of assert event */
+	struct pps_ktime clear_tu;	/* time of clear event */
+	int current_mode;		/* current mode bits */
+};
+
+struct pps_kparams {
+	int api_version;		/* API version # */
+	int mode;			/* mode bits */
+	struct pps_ktime assert_off_tu;	/* offset compensation for assert */
+	struct pps_ktime clear_off_tu;	/* offset compensation for clear */
+};
+
+/*
+ * 3.3 Mode bit definitions
+ */
+
+/* Device/implementation parameters */
+#define PPS_CAPTUREASSERT	0x01	/* capture assert events */
+#define PPS_CAPTURECLEAR	0x02	/* capture clear events */
+#define PPS_CAPTUREBOTH		0x03	/* capture assert and clear events */
+
+#define PPS_OFFSETASSERT	0x10	/* apply compensation for assert ev. */
+#define PPS_OFFSETCLEAR		0x20	/* apply compensation for clear ev. */
+
+#define PPS_CANWAIT		0x100	/* can we wait for an event? */
+#define PPS_CANPOLL		0x200	/* bit reserved for future use */
+
+/* Kernel actions */
+#define PPS_ECHOASSERT		0x40	/* feed back assert event to output */
+#define PPS_ECHOCLEAR		0x80	/* feed back clear event to output */
+
+/* Timestamp formats */
+#define PPS_TSFMT_TSPEC		0x1000	/* select timespec format */
+#define PPS_TSFMT_NTPFP		0x2000	/* select NTP format */
+
+/*
+ * 3.4.4 New functions: disciplining the kernel timebase
+ */
+
+/* Kernel consumers */
+#define PPS_KC_HARDPPS		0	/* hardpps() (or equivalent) */
+#define PPS_KC_HARDPPS_PLL	1	/* hardpps() constrained to
+					   use a phase-locked loop */
+#define PPS_KC_HARDPPS_FLL	2	/* hardpps() constrained to
+					   use a frequency-locked loop */
+/*
+ * Here begins the implementation-specific part!
+ */
+
+struct pps_fdata {
+	struct pps_kinfo info;
+	struct pps_ktime timeout;
+};
+
+#include <linux/ioctl.h>
+
+#define PPS_GETPARAMS		_IOR('p', 0xa1, struct pps_kparams *)
+#define PPS_SETPARAMS		_IOW('p', 0xa2, struct pps_kparams *)
+#define PPS_GETCAP		_IOR('p', 0xa3, int *)
+#define PPS_FETCH		_IOWR('p', 0xa4, struct pps_fdata *)
+
+#endif /* _PPS_H_ */
diff --git a/include/linux/pps_kernel.h b/include/linux/pps_kernel.h
new file mode 100644
index 0000000..e0a193f
--- /dev/null
+++ b/include/linux/pps_kernel.h
@@ -0,0 +1,89 @@
+/*
+ * PPS API kernel header
+ *
+ * Copyright (C) 2009   Rodolfo Giometti <giometti@linux.it>
+ *
+ *   This program is free software; you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or
+ *   (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#include <linux/pps.h>
+
+#include <linux/cdev.h>
+#include <linux/device.h>
+#include <linux/time.h>
+
+/*
+ * Global defines
+ */
+
+/* The specific PPS source info */
+struct pps_source_info {
+	char name[PPS_MAX_NAME_LEN];		/* simbolic name */
+	char path[PPS_MAX_NAME_LEN];		/* path of connected device */
+	int mode;				/* PPS's allowed mode */
+
+	void (*echo)(int source, int event, void *data); /* PPS echo function */
+
+	struct module *owner;
+	struct device *dev;
+};
+
+/* The main struct */
+struct pps_device {
+	struct pps_source_info info;		/* PSS source info */
+
+	struct pps_kparams params;		/* PPS's current params */
+
+	__u32 assert_sequence;			/* PPS' assert event seq # */
+	__u32 clear_sequence;			/* PPS' clear event seq # */
+	struct pps_ktime assert_tu;
+	struct pps_ktime clear_tu;
+	int current_mode;			/* PPS mode at event time */
+
+	int go;					/* PPS event is arrived? */
+	wait_queue_head_t queue;		/* PPS event queue */
+
+	unsigned int id;			/* PPS source unique ID */
+	struct cdev cdev;
+	struct device *dev;
+	int devno;
+	struct fasync_struct *async_queue;	/* fasync method */
+	spinlock_t lock;
+
+	atomic_t usage;				/* usage count */
+};
+
+/*
+ * Global variables
+ */
+
+extern spinlock_t pps_idr_lock;
+extern struct idr pps_idr;
+extern struct timespec pps_irq_ts[];
+
+extern struct device_attribute pps_attrs[];
+
+/*
+ * Exported functions
+ */
+
+struct pps_device *pps_get_source(int source);
+extern void pps_put_source(struct pps_device *pps);
+extern int pps_register_source(struct pps_source_info *info,
+				int default_params);
+extern void pps_unregister_source(int source);
+extern int pps_register_cdev(struct pps_device *pps);
+extern void pps_unregister_cdev(struct pps_device *pps);
+extern void pps_event(int source, struct pps_ktime *ts, int event, void *data);
diff --git a/include/linux/ptrace.h b/include/linux/ptrace.h
index 59e133d..7456d7d 100644
--- a/include/linux/ptrace.h
+++ b/include/linux/ptrace.h
@@ -81,7 +81,6 @@
 
 
 extern long arch_ptrace(struct task_struct *child, long request, long addr, long data);
-extern struct task_struct *ptrace_get_task_struct(pid_t pid);
 extern int ptrace_traceme(void);
 extern int ptrace_readdata(struct task_struct *tsk, unsigned long src, char __user *dst, int len);
 extern int ptrace_writedata(struct task_struct *tsk, char __user *src, unsigned long dst, int len);
diff --git a/include/linux/raid/md_p.h b/include/linux/raid/md_p.h
index 6ba830f..ffa2efb 100644
--- a/include/linux/raid/md_p.h
+++ b/include/linux/raid/md_p.h
@@ -232,7 +232,7 @@
 	__le64	reshape_position;	/* next address in array-space for reshape */
 	__le32	delta_disks;	/* change in number of raid_disks		*/
 	__le32	new_layout;	/* new layout					*/
-	__le32	new_chunk;	/* new chunk size (bytes)			*/
+	__le32	new_chunk;	/* new chunk size (512byte sectors)		*/
 	__u8	pad1[128-124];	/* set to 0 when written */
 
 	/* constant this-device information - 64 bytes */
diff --git a/include/linux/reiserfs_fs.h b/include/linux/reiserfs_fs.h
index 2245c78..dd31e7b 100644
--- a/include/linux/reiserfs_fs.h
+++ b/include/linux/reiserfs_fs.h
@@ -660,23 +660,54 @@
 		   cpu_to_le32(type2uniqueness(type)))
 	    : (void)(set_offset_v2_k_type(&(key->u.k_offset_v2), type));
 }
+
 static inline void set_le_ih_k_type(struct item_head *ih, int type)
 {
 	set_le_key_k_type(ih_version(ih), &(ih->ih_key), type);
 }
 
-#define is_direntry_le_key(version,key) (le_key_k_type (version, key) == TYPE_DIRENTRY)
-#define is_direct_le_key(version,key) (le_key_k_type (version, key) == TYPE_DIRECT)
-#define is_indirect_le_key(version,key) (le_key_k_type (version, key) == TYPE_INDIRECT)
-#define is_statdata_le_key(version,key) (le_key_k_type (version, key) == TYPE_STAT_DATA)
+static inline int is_direntry_le_key(int version, struct reiserfs_key *key)
+{
+	return le_key_k_type(version, key) == TYPE_DIRENTRY;
+}
+
+static inline int is_direct_le_key(int version, struct reiserfs_key *key)
+{
+	return le_key_k_type(version, key) == TYPE_DIRECT;
+}
+
+static inline int is_indirect_le_key(int version, struct reiserfs_key *key)
+{
+	return le_key_k_type(version, key) == TYPE_INDIRECT;
+}
+
+static inline int is_statdata_le_key(int version, struct reiserfs_key *key)
+{
+	return le_key_k_type(version, key) == TYPE_STAT_DATA;
+}
 
 //
 // item header has version.
 //
-#define is_direntry_le_ih(ih) is_direntry_le_key (ih_version (ih), &((ih)->ih_key))
-#define is_direct_le_ih(ih) is_direct_le_key (ih_version (ih), &((ih)->ih_key))
-#define is_indirect_le_ih(ih) is_indirect_le_key (ih_version(ih), &((ih)->ih_key))
-#define is_statdata_le_ih(ih) is_statdata_le_key (ih_version (ih), &((ih)->ih_key))
+static inline int is_direntry_le_ih(struct item_head *ih)
+{
+	return is_direntry_le_key(ih_version(ih), &ih->ih_key);
+}
+
+static inline int is_direct_le_ih(struct item_head *ih)
+{
+	return is_direct_le_key(ih_version(ih), &ih->ih_key);
+}
+
+static inline int is_indirect_le_ih(struct item_head *ih)
+{
+	return is_indirect_le_key(ih_version(ih), &ih->ih_key);
+}
+
+static inline int is_statdata_le_ih(struct item_head *ih)
+{
+	return is_statdata_le_key(ih_version(ih), &ih->ih_key);
+}
 
 //
 // key is pointer to cpu key, result is cpu
diff --git a/include/linux/res_counter.h b/include/linux/res_counter.h
index 4c5bcf6..511f42f 100644
--- a/include/linux/res_counter.h
+++ b/include/linux/res_counter.h
@@ -49,6 +49,8 @@
 	struct res_counter *parent;
 };
 
+#define RESOURCE_MAX (unsigned long long)LLONG_MAX
+
 /**
  * Helpers to interact with userspace
  * res_counter_read_u64() - returns the value of the specified member.
diff --git a/include/linux/rotary_encoder.h b/include/linux/rotary_encoder.h
index 12d63a3..215278b 100644
--- a/include/linux/rotary_encoder.h
+++ b/include/linux/rotary_encoder.h
@@ -8,6 +8,8 @@
 	unsigned int gpio_b;
 	unsigned int inverted_a;
 	unsigned int inverted_b;
+	bool relative_axis;
+	bool rollover;
 };
 
 #endif /* __ROTARY_ENCODER_H__ */
diff --git a/include/linux/sched.h b/include/linux/sched.h
index 02042e7..4d07542 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -92,7 +92,6 @@
 
 #include <asm/processor.h>
 
-struct mem_cgroup;
 struct exec_domain;
 struct futex_pi_state;
 struct robust_list_head;
@@ -1879,9 +1878,6 @@
 /*
  * find a task by one of its numerical ids
  *
- * find_task_by_pid_type_ns():
- *      it is the most generic call - it finds a task by all id,
- *      type and namespace specified
  * find_task_by_pid_ns():
  *      finds a task by its pid in the specified namespace
  * find_task_by_vpid():
@@ -1890,9 +1886,6 @@
  * see also find_vpid() etc in include/linux/pid.h
  */
 
-extern struct task_struct *find_task_by_pid_type_ns(int type, int pid,
-		struct pid_namespace *ns);
-
 extern struct task_struct *find_task_by_vpid(pid_t nr);
 extern struct task_struct *find_task_by_pid_ns(pid_t nr,
 		struct pid_namespace *ns);
diff --git a/include/linux/seq_file.h b/include/linux/seq_file.h
index 004f3b3..0c6a86b 100644
--- a/include/linux/seq_file.h
+++ b/include/linux/seq_file.h
@@ -43,6 +43,7 @@
 int seq_escape(struct seq_file *, const char *, const char *);
 int seq_putc(struct seq_file *m, char c);
 int seq_puts(struct seq_file *m, const char *s);
+int seq_write(struct seq_file *seq, const void *data, size_t len);
 
 int seq_printf(struct seq_file *, const char *, ...)
 	__attribute__ ((format (printf,2,3)));
diff --git a/include/linux/serio.h b/include/linux/serio.h
index e0417e4..126d24c 100644
--- a/include/linux/serio.h
+++ b/include/linux/serio.h
@@ -15,6 +15,7 @@
 
 #ifdef __KERNEL__
 
+#include <linux/types.h>
 #include <linux/interrupt.h>
 #include <linux/list.h>
 #include <linux/spinlock.h>
@@ -28,7 +29,10 @@
 	char name[32];
 	char phys[32];
 
-	unsigned int manual_bind;
+	bool manual_bind;
+	bool registered;	/* port has been fully registered with driver core */
+	bool suspended;		/* port is suspended */
+
 
 	struct serio_device_id id;
 
@@ -47,7 +51,6 @@
 	struct mutex drv_mutex;		/* protects serio->drv so attributes can pin driver */
 
 	struct device dev;
-	unsigned int registered;	/* port has been fully registered with driver core */
 
 	struct list_head node;
 };
@@ -58,7 +61,7 @@
 	char *description;
 
 	struct serio_device_id *id_table;
-	unsigned int manual_bind;
+	bool manual_bind;
 
 	void (*write_wakeup)(struct serio *);
 	irqreturn_t (*interrupt)(struct serio *, unsigned char, unsigned int);
diff --git a/include/linux/skbuff.h b/include/linux/skbuff.h
index 63ef24b..b47b3f0 100644
--- a/include/linux/skbuff.h
+++ b/include/linux/skbuff.h
@@ -265,7 +265,7 @@
  *	@transport_header: Transport layer header
  *	@network_header: Network layer header
  *	@mac_header: Link layer header
- *	@dst: destination entry
+ *	@_skb_dst: destination entry
  *	@sp: the security path, used for xfrm
  *	@cb: Control buffer. Free for use by every layer. Put private vars here
  *	@len: Length of actual data
diff --git a/include/linux/spi/ads7846.h b/include/linux/spi/ads7846.h
index 2ea2032..51948eb 100644
--- a/include/linux/spi/ads7846.h
+++ b/include/linux/spi/ads7846.h
@@ -17,6 +17,7 @@
 	u16	vref_mv;		/* external vref value, milliVolts */
 	bool	keep_vref_on;		/* set to keep vref on for differential
 					 * measurements as well */
+	bool	swap_xy;		/* swap x and y axes */
 
 	/* Settling time of the analog signals; a function of Vcc and the
 	 * capacitance on the X/Y drivers.  If set to non-zero, two samples
diff --git a/include/linux/spi/spi.h b/include/linux/spi/spi.h
index a0faa18..9c4cd27 100644
--- a/include/linux/spi/spi.h
+++ b/include/linux/spi/spi.h
@@ -245,6 +245,9 @@
 	 */
 	u16			dma_alignment;
 
+	/* spi_device.mode flags understood by this controller driver */
+	u16			mode_bits;
+
 	/* Setup mode and clock, etc (spi driver may call many times).
 	 *
 	 * IMPORTANT:  this may be called when transfers to another
@@ -523,30 +526,7 @@
 	kfree(m);
 }
 
-/**
- * spi_setup - setup SPI mode and clock rate
- * @spi: the device whose settings are being modified
- * Context: can sleep, and no requests are queued to the device
- *
- * SPI protocol drivers may need to update the transfer mode if the
- * device doesn't work with its default.  They may likewise need
- * to update clock rates or word sizes from initial values.  This function
- * changes those settings, and must be called from a context that can sleep.
- * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
- * effect the next time the device is selected and data is transferred to
- * or from it.  When this function returns, the spi device is deselected.
- *
- * Note that this call will fail if the protocol driver specifies an option
- * that the underlying controller or its driver does not support.  For
- * example, not all hardware supports wire transfers using nine bit words,
- * LSB-first wire encoding, or active-high chipselects.
- */
-static inline int
-spi_setup(struct spi_device *spi)
-{
-	return spi->master->setup(spi);
-}
-
+extern int spi_setup(struct spi_device *spi);
 
 /**
  * spi_async - asynchronous SPI transfer
diff --git a/include/linux/swap.h b/include/linux/swap.h
index 0cedf31..c88b366 100644
--- a/include/linux/swap.h
+++ b/include/linux/swap.h
@@ -319,10 +319,11 @@
 }
 
 #ifdef CONFIG_CGROUP_MEM_RES_CTLR
-extern void mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent);
+extern void
+mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout);
 #else
 static inline void
-mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent)
+mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
 {
 }
 #endif
@@ -423,12 +424,6 @@
 #define has_swap_token(x) 0
 #define disable_swap_token() do { } while(0)
 
-static inline int mem_cgroup_cache_charge_swapin(struct page *page,
-			struct mm_struct *mm, gfp_t mask, bool locked)
-{
-	return 0;
-}
-
 static inline void
 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent)
 {
diff --git a/include/linux/trace_seq.h b/include/linux/trace_seq.h
index c68bccb..c134dd1 100644
--- a/include/linux/trace_seq.h
+++ b/include/linux/trace_seq.h
@@ -3,6 +3,8 @@
 
 #include <linux/fs.h>
 
+#include <asm/page.h>
+
 /*
  * Trace sequences are used to allow a function to call several other functions
  * to create a string of data to use (up to a max of PAGE_SIZE.
diff --git a/include/linux/tracehook.h b/include/linux/tracehook.h
index eb96603..17ba82ef 100644
--- a/include/linux/tracehook.h
+++ b/include/linux/tracehook.h
@@ -143,7 +143,7 @@
  *
  * Return %LSM_UNSAFE_* bits applied to an exec because of tracing.
  *
- * Called with task_lock() held on @task.
+ * @task->cred_guard_mutex is held by the caller through the do_execve().
  */
 static inline int tracehook_unsafe_exec(struct task_struct *task)
 {
diff --git a/include/linux/types.h b/include/linux/types.h
index 5abe354..c42724f 100644
--- a/include/linux/types.h
+++ b/include/linux/types.h
@@ -131,7 +131,7 @@
  *
  * blkcnt_t is the type of the inode's block count.
  */
-#ifdef CONFIG_LBD
+#ifdef CONFIG_LBDAF
 typedef u64 sector_t;
 typedef u64 blkcnt_t;
 #else
diff --git a/include/linux/ucb1400.h b/include/linux/ucb1400.h
index 970473b..ed889f4 100644
--- a/include/linux/ucb1400.h
+++ b/include/linux/ucb1400.h
@@ -134,28 +134,13 @@
 	ucb1400_reg_write(ac97, UCB_ADC_CR, UCB_ADC_ENA);
 }
 
-static unsigned int ucb1400_adc_read(struct snd_ac97 *ac97, u16 adc_channel,
-					int adcsync)
-{
-	unsigned int val;
-
-	if (adcsync)
-		adc_channel |= UCB_ADC_SYNC_ENA;
-
-	ucb1400_reg_write(ac97, UCB_ADC_CR, UCB_ADC_ENA | adc_channel);
-	ucb1400_reg_write(ac97, UCB_ADC_CR, UCB_ADC_ENA | adc_channel |
-				UCB_ADC_START);
-
-	while (!((val = ucb1400_reg_read(ac97, UCB_ADC_DATA))
-			& UCB_ADC_DAT_VALID))
-		schedule_timeout_uninterruptible(1);
-
-	return val & UCB_ADC_DAT_MASK;
-}
-
 static inline void ucb1400_adc_disable(struct snd_ac97 *ac97)
 {
 	ucb1400_reg_write(ac97, UCB_ADC_CR, 0);
 }
 
+
+unsigned int ucb1400_adc_read(struct snd_ac97 *ac97, u16 adc_channel,
+			      int adcsync);
+
 #endif
diff --git a/include/linux/w1-gpio.h b/include/linux/w1-gpio.h
index 9797fec..3adeff8 100644
--- a/include/linux/w1-gpio.h
+++ b/include/linux/w1-gpio.h
@@ -18,6 +18,7 @@
 struct w1_gpio_platform_data {
 	unsigned int pin;
 	unsigned int is_open_drain:1;
+	void (*enable_external_pullup)(int enable);
 };
 
 #endif /* _LINUX_W1_GPIO_H */
diff --git a/include/net/sock.h b/include/net/sock.h
index 95bd3fd..07133c5e 100644
--- a/include/net/sock.h
+++ b/include/net/sock.h
@@ -1208,6 +1208,39 @@
 	return 0;
 }
 
+/**
+ * sk_wmem_alloc_get - returns write allocations
+ * @sk: socket
+ *
+ * Returns sk_wmem_alloc minus initial offset of one
+ */
+static inline int sk_wmem_alloc_get(const struct sock *sk)
+{
+	return atomic_read(&sk->sk_wmem_alloc) - 1;
+}
+
+/**
+ * sk_rmem_alloc_get - returns read allocations
+ * @sk: socket
+ *
+ * Returns sk_rmem_alloc
+ */
+static inline int sk_rmem_alloc_get(const struct sock *sk)
+{
+	return atomic_read(&sk->sk_rmem_alloc);
+}
+
+/**
+ * sk_has_allocations - check if allocations are outstanding
+ * @sk: socket
+ *
+ * Returns true if socket has write or read allocations
+ */
+static inline int sk_has_allocations(const struct sock *sk)
+{
+	return sk_wmem_alloc_get(sk) || sk_rmem_alloc_get(sk);
+}
+
 /*
  * 	Queue a received datagram if it will fit. Stream and sequenced
  *	protocols can't normally use this as they need to fit buffers in
diff --git a/include/net/x25.h b/include/net/x25.h
index fc3f03d..2cda040 100644
--- a/include/net/x25.h
+++ b/include/net/x25.h
@@ -187,7 +187,7 @@
 extern int  x25_addr_aton(unsigned char *, struct x25_address *,
 			  struct x25_address *);
 extern struct sock *x25_find_socket(unsigned int, struct x25_neigh *);
-extern void x25_destroy_socket(struct sock *);
+extern void x25_destroy_socket_from_timer(struct sock *);
 extern int  x25_rx_call_request(struct sk_buff *, struct x25_neigh *, unsigned int);
 extern void x25_kill_by_neigh(struct x25_neigh *);
 
diff --git a/include/scsi/Kbuild b/include/scsi/Kbuild
new file mode 100644
index 0000000..33b2750
--- /dev/null
+++ b/include/scsi/Kbuild
@@ -0,0 +1,4 @@
+header-y += scsi.h
+header-y += scsi_netlink.h
+header-y += scsi_netlink_fc.h
+header-y += scsi_bsg_fc.h
diff --git a/include/scsi/scsi_bsg_fc.h b/include/scsi/scsi_bsg_fc.h
new file mode 100644
index 0000000..a4b2333
--- /dev/null
+++ b/include/scsi/scsi_bsg_fc.h
@@ -0,0 +1,322 @@
+/*
+ *  FC Transport BSG Interface
+ *
+ *  Copyright (C) 2008   James Smart, Emulex Corporation
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ */
+
+#ifndef SCSI_BSG_FC_H
+#define SCSI_BSG_FC_H
+
+/*
+ * This file intended to be included by both kernel and user space
+ */
+
+#include <scsi/scsi.h>
+
+/*
+ * FC Transport SGIO v4 BSG Message Support
+ */
+
+/* Default BSG request timeout (in seconds) */
+#define FC_DEFAULT_BSG_TIMEOUT		(10 * HZ)
+
+
+/*
+ * Request Message Codes supported by the FC Transport
+ */
+
+/* define the class masks for the message codes */
+#define FC_BSG_CLS_MASK		0xF0000000	/* find object class */
+#define FC_BSG_HST_MASK		0x80000000	/* fc host class */
+#define FC_BSG_RPT_MASK		0x40000000	/* fc rport class */
+
+	/* fc_host Message Codes */
+#define FC_BSG_HST_ADD_RPORT		(FC_BSG_HST_MASK | 0x00000001)
+#define FC_BSG_HST_DEL_RPORT		(FC_BSG_HST_MASK | 0x00000002)
+#define FC_BSG_HST_ELS_NOLOGIN		(FC_BSG_HST_MASK | 0x00000003)
+#define FC_BSG_HST_CT			(FC_BSG_HST_MASK | 0x00000004)
+#define FC_BSG_HST_VENDOR		(FC_BSG_HST_MASK | 0x000000FF)
+
+	/* fc_rport Message Codes */
+#define FC_BSG_RPT_ELS			(FC_BSG_RPT_MASK | 0x00000001)
+#define FC_BSG_RPT_CT			(FC_BSG_RPT_MASK | 0x00000002)
+
+
+
+/*
+ * FC Address Identifiers in Message Structures :
+ *
+ *   Whenever a command payload contains a FC Address Identifier
+ *   (aka port_id), the value is effectively in big-endian
+ *   order, thus the array elements are decoded as follows:
+ *     element [0] is bits 23:16 of the FC Address Identifier
+ *     element [1] is bits 15:8 of the FC Address Identifier
+ *     element [2] is bits 7:0 of the FC Address Identifier
+ */
+
+
+/*
+ * FC Host Messages
+ */
+
+/* FC_BSG_HST_ADDR_PORT : */
+
+/* Request:
+ * This message requests the FC host to login to the remote port
+ * at the specified N_Port_Id.  The remote port is to be enumerated
+ * with the transport upon completion of the login.
+ */
+struct fc_bsg_host_add_rport {
+	uint8_t		reserved;
+
+	/* FC Address Identier of the remote port to login to */
+	uint8_t		port_id[3];
+};
+
+/* Response:
+ * There is no additional response data - fc_bsg_reply->result is sufficient
+ */
+
+
+/* FC_BSG_HST_DEL_RPORT : */
+
+/* Request:
+ * This message requests the FC host to remove an enumerated
+ * remote port and to terminate the login to it.
+ *
+ * Note: The driver is free to reject this request if it desires to
+ * remain logged in with the remote port.
+ */
+struct fc_bsg_host_del_rport {
+	uint8_t		reserved;
+
+	/* FC Address Identier of the remote port to logout of */
+	uint8_t		port_id[3];
+};
+
+/* Response:
+ * There is no additional response data - fc_bsg_reply->result is sufficient
+ */
+
+
+/* FC_BSG_HST_ELS_NOLOGIN : */
+
+/* Request:
+ * This message requests the FC_Host to send an ELS to a specific
+ * N_Port_ID. The host does not need to log into the remote port,
+ * nor does it need to enumerate the rport for further traffic
+ * (although, the FC host is free to do so if it desires).
+ */
+struct fc_bsg_host_els {
+	/*
+	 * ELS Command Code being sent (must be the same as byte 0
+	 * of the payload)
+	 */
+	uint8_t 	command_code;
+
+	/* FC Address Identier of the remote port to send the ELS to */
+	uint8_t		port_id[3];
+};
+
+/* Response:
+ */
+/* fc_bsg_ctels_reply->status values */
+#define FC_CTELS_STATUS_OK	0x00000000
+#define FC_CTELS_STATUS_REJECT	0x00000001
+#define FC_CTELS_STATUS_P_RJT	0x00000002
+#define FC_CTELS_STATUS_F_RJT	0x00000003
+#define FC_CTELS_STATUS_P_BSY	0x00000004
+#define FC_CTELS_STATUS_F_BSY	0x00000006
+struct fc_bsg_ctels_reply {
+	/*
+	 * Note: An ELS LS_RJT may be reported in 2 ways:
+	 *  a) A status of FC_CTELS_STATUS_OK is returned. The caller
+	 *     is to look into the ELS receive payload to determine
+	 *     LS_ACC or LS_RJT (by contents of word 0). The reject
+	 *     data will be in word 1.
+	 *  b) A status of FC_CTELS_STATUS_REJECT is returned, The
+	 *     rjt_data field will contain valid data.
+	 *
+	 * Note: ELS LS_ACC is determined by an FC_CTELS_STATUS_OK, and
+	 *   the receive payload word 0 indicates LS_ACC
+	 *   (e.g. value is 0x02xxxxxx).
+	 *
+	 * Note: Similarly, a CT Reject may be reported in 2 ways:
+	 *  a) A status of FC_CTELS_STATUS_OK is returned. The caller
+	 *     is to look into the CT receive payload to determine
+	 *     Accept or Reject (by contents of word 2). The reject
+	 *     data will be in word 3.
+	 *  b) A status of FC_CTELS_STATUS_REJECT is returned, The
+	 *     rjt_data field will contain valid data.
+	 *
+	 * Note: x_RJT/BSY status will indicae that the rjt_data field
+	 *   is valid and contains the reason/explanation values.
+	 */
+	uint32_t	status;		/* See FC_CTELS_STATUS_xxx */
+
+	/* valid if status is not FC_CTELS_STATUS_OK */
+	struct	{
+		uint8_t	action;		/* fragment_id for CT REJECT */
+		uint8_t	reason_code;
+		uint8_t	reason_explanation;
+		uint8_t	vendor_unique;
+	} rjt_data;
+};
+
+
+/* FC_BSG_HST_CT : */
+
+/* Request:
+ * This message requests that a CT Request be performed with the
+ * indicated N_Port_ID. The driver is responsible for logging in with
+ * the fabric and/or N_Port_ID, etc as per FC rules. This request does
+ * not mandate that the driver must enumerate the destination in the
+ * transport. The driver is allowed to decide whether to enumerate it,
+ * and whether to tear it down after the request.
+ */
+struct fc_bsg_host_ct {
+	uint8_t		reserved;
+
+	/* FC Address Identier of the remote port to send the ELS to */
+	uint8_t		port_id[3];
+
+	/*
+	 * We need words 0-2 of the generic preamble for the LLD's
+	 */
+	uint32_t	preamble_word0;	/* revision & IN_ID */
+	uint32_t	preamble_word1;	/* GS_Type, GS_SubType, Options, Rsvd */
+	uint32_t	preamble_word2;	/* Cmd Code, Max Size */
+
+};
+/* Response:
+ *
+ * The reply structure is an fc_bsg_ctels_reply structure
+ */
+
+
+/* FC_BSG_HST_VENDOR : */
+
+/* Request:
+ * Note: When specifying vendor_id, be sure to read the Vendor Type and ID
+ *   formatting requirements specified in scsi_netlink.h
+ */
+struct fc_bsg_host_vendor {
+	/*
+	 * Identifies the vendor that the message is formatted for. This
+	 * should be the recipient of the message.
+	 */
+	uint64_t vendor_id;
+
+	/* start of vendor command area */
+	uint32_t vendor_cmd[0];
+};
+
+/* Response:
+ */
+struct fc_bsg_host_vendor_reply {
+	/* start of vendor response area */
+	uint32_t vendor_rsp[0];
+};
+
+
+
+/*
+ * FC Remote Port Messages
+ */
+
+/* FC_BSG_RPT_ELS : */
+
+/* Request:
+ * This message requests that an ELS be performed with the rport.
+ */
+struct fc_bsg_rport_els {
+	/*
+	 * ELS Command Code being sent (must be the same as
+	 * byte 0 of the payload)
+	 */
+	uint8_t els_code;
+};
+
+/* Response:
+ *
+ * The reply structure is an fc_bsg_ctels_reply structure
+ */
+
+
+/* FC_BSG_RPT_CT : */
+
+/* Request:
+ * This message requests that a CT Request be performed with the rport.
+ */
+struct fc_bsg_rport_ct {
+	/*
+	 * We need words 0-2 of the generic preamble for the LLD's
+	 */
+	uint32_t	preamble_word0;	/* revision & IN_ID */
+	uint32_t	preamble_word1;	/* GS_Type, GS_SubType, Options, Rsvd */
+	uint32_t	preamble_word2;	/* Cmd Code, Max Size */
+};
+/* Response:
+ *
+ * The reply structure is an fc_bsg_ctels_reply structure
+ */
+
+
+
+
+/* request (CDB) structure of the sg_io_v4 */
+struct fc_bsg_request {
+	uint32_t msgcode;
+	union {
+		struct fc_bsg_host_add_rport	h_addrport;
+		struct fc_bsg_host_del_rport	h_delrport;
+		struct fc_bsg_host_els		h_els;
+		struct fc_bsg_host_ct		h_ct;
+		struct fc_bsg_host_vendor	h_vendor;
+
+		struct fc_bsg_rport_els		r_els;
+		struct fc_bsg_rport_ct		r_ct;
+	} rqst_data;
+};
+
+
+/* response (request sense data) structure of the sg_io_v4 */
+struct fc_bsg_reply {
+	/*
+	 * The completion result. Result exists in two forms:
+	 *  if negative, it is an -Exxx system errno value. There will
+	 *    be no further reply information supplied.
+	 *  else, it's the 4-byte scsi error result, with driver, host,
+	 *    msg and status fields. The per-msgcode reply structure
+	 *    will contain valid data.
+	 */
+	uint32_t result;
+
+	/* If there was reply_payload, how much was recevied ? */
+	uint32_t reply_payload_rcv_len;
+
+	union {
+		struct fc_bsg_host_vendor_reply		vendor_reply;
+
+		struct fc_bsg_ctels_reply		ctels_reply;
+	} reply_data;
+};
+
+
+#endif /* SCSI_BSG_FC_H */
+
diff --git a/include/scsi/scsi_host.h b/include/scsi/scsi_host.h
index d123ca8..b62a097 100644
--- a/include/scsi/scsi_host.h
+++ b/include/scsi/scsi_host.h
@@ -478,6 +478,15 @@
 	 * module_init/module_exit.
 	 */
 	struct list_head legacy_hosts;
+
+	/*
+	 * Vendor Identifier associated with the host
+	 *
+	 * Note: When specifying vendor_id, be sure to read the
+	 *   Vendor Type and ID formatting requirements specified in
+	 *   scsi_netlink.h
+	 */
+	u64 vendor_id;
 };
 
 /*
diff --git a/include/scsi/scsi_transport_fc.h b/include/scsi/scsi_transport_fc.h
index 68a8d87..fc50bd6 100644
--- a/include/scsi/scsi_transport_fc.h
+++ b/include/scsi/scsi_transport_fc.h
@@ -33,7 +33,6 @@
 
 struct scsi_transport_template;
 
-
 /*
  * FC Port definitions - Following FC HBAAPI guidelines
  *
@@ -352,6 +351,7 @@
  	struct delayed_work fail_io_work;
  	struct work_struct stgt_delete_work;
 	struct work_struct rport_delete_work;
+	struct request_queue *rqst_q;	/* bsg support */
 } __attribute__((aligned(sizeof(unsigned long))));
 
 /* bit field values for struct fc_rport "flags" field: */
@@ -514,6 +514,9 @@
 	struct workqueue_struct *work_q;
 	char devloss_work_q_name[20];
 	struct workqueue_struct *devloss_work_q;
+
+	/* bsg support */
+	struct request_queue *rqst_q;
 };
 
 #define shost_to_fc_host(x) \
@@ -579,6 +582,47 @@
 	(((struct fc_host_attrs *)(x)->shost_data)->devloss_work_q)
 
 
+struct fc_bsg_buffer {
+	unsigned int payload_len;
+	int sg_cnt;
+	struct scatterlist *sg_list;
+};
+
+/* Values for fc_bsg_job->state_flags (bitflags) */
+#define FC_RQST_STATE_INPROGRESS	0
+#define FC_RQST_STATE_DONE		1
+
+struct fc_bsg_job {
+	struct Scsi_Host *shost;
+	struct fc_rport *rport;
+	struct device *dev;
+	struct request *req;
+	spinlock_t job_lock;
+	unsigned int state_flags;
+	unsigned int ref_cnt;
+	void (*job_done)(struct fc_bsg_job *);
+
+	struct fc_bsg_request *request;
+	struct fc_bsg_reply *reply;
+	unsigned int request_len;
+	unsigned int reply_len;
+	/*
+	 * On entry : reply_len indicates the buffer size allocated for
+	 * the reply.
+	 *
+	 * Upon completion : the message handler must set reply_len
+	 *  to indicates the size of the reply to be returned to the
+	 *  caller.
+	 */
+
+	/* DMA payloads for the request/response */
+	struct fc_bsg_buffer request_payload;
+	struct fc_bsg_buffer reply_payload;
+
+	void *dd_data;			/* Used for driver-specific storage */
+};
+
+
 /* The functions by which the transport class and the driver communicate */
 struct fc_function_template {
 	void    (*get_rport_dev_loss_tmo)(struct fc_rport *);
@@ -614,9 +658,14 @@
 	int     (* tsk_mgmt_response)(struct Scsi_Host *, u64, u64, int);
 	int     (* it_nexus_response)(struct Scsi_Host *, u64, int);
 
+	/* bsg support */
+	int	(*bsg_request)(struct fc_bsg_job *);
+	int	(*bsg_timeout)(struct fc_bsg_job *);
+
 	/* allocation lengths for host-specific data */
 	u32	 			dd_fcrport_size;
 	u32	 			dd_fcvport_size;
+	u32				dd_bsg_size;
 
 	/*
 	 * The driver sets these to tell the transport class it
@@ -737,7 +786,6 @@
 	vport->vport_state = new_state;
 }
 
-
 struct scsi_transport_template *fc_attach_transport(
 			struct fc_function_template *);
 void fc_release_transport(struct scsi_transport_template *);
diff --git a/include/scsi/scsi_transport_spi.h b/include/scsi/scsi_transport_spi.h
index 286e962..7497a38 100644
--- a/include/scsi/scsi_transport_spi.h
+++ b/include/scsi/scsi_transport_spi.h
@@ -36,8 +36,10 @@
 	unsigned int width:1;	/* 0 - narrow, 1 - wide */
 	unsigned int max_width:1;
 	unsigned int iu:1;	/* Information Units enabled */
+	unsigned int max_iu:1;
 	unsigned int dt:1;	/* DT clocking enabled */
 	unsigned int qas:1;	/* Quick Arbitration and Selection enabled */
+	unsigned int max_qas:1;
 	unsigned int wr_flow:1;	/* Write Flow control enabled */
 	unsigned int rd_strm:1;	/* Read streaming enabled */
 	unsigned int rti:1;	/* Retain Training Information */
@@ -77,8 +79,10 @@
 #define spi_width(x)	(((struct spi_transport_attrs *)&(x)->starget_data)->width)
 #define spi_max_width(x) (((struct spi_transport_attrs *)&(x)->starget_data)->max_width)
 #define spi_iu(x)	(((struct spi_transport_attrs *)&(x)->starget_data)->iu)
+#define spi_max_iu(x)	(((struct spi_transport_attrs *)&(x)->starget_data)->max_iu)
 #define spi_dt(x)	(((struct spi_transport_attrs *)&(x)->starget_data)->dt)
 #define spi_qas(x)	(((struct spi_transport_attrs *)&(x)->starget_data)->qas)
+#define spi_max_qas(x)	(((struct spi_transport_attrs *)&(x)->starget_data)->max_qas)
 #define spi_wr_flow(x)	(((struct spi_transport_attrs *)&(x)->starget_data)->wr_flow)
 #define spi_rd_strm(x)	(((struct spi_transport_attrs *)&(x)->starget_data)->rd_strm)
 #define spi_rti(x)	(((struct spi_transport_attrs *)&(x)->starget_data)->rti)
diff --git a/include/trace/events/ext4.h b/include/trace/events/ext4.h
new file mode 100644
index 0000000..acf4cc9
--- /dev/null
+++ b/include/trace/events/ext4.h
@@ -0,0 +1,719 @@
+#if !defined(_TRACE_EXT4_H) || defined(TRACE_HEADER_MULTI_READ)
+#define _TRACE_EXT4_H
+
+#undef TRACE_SYSTEM
+#define TRACE_SYSTEM ext4
+
+#include <linux/writeback.h>
+#include "../../../fs/ext4/ext4.h"
+#include "../../../fs/ext4/mballoc.h"
+#include <linux/tracepoint.h>
+
+TRACE_EVENT(ext4_free_inode,
+	TP_PROTO(struct inode *inode),
+
+	TP_ARGS(inode),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	umode_t, mode			)
+		__field(	uid_t,	uid			)
+		__field(	gid_t,	gid			)
+		__field(	blkcnt_t, blocks		)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+		__entry->mode	= inode->i_mode;
+		__entry->uid	= inode->i_uid;
+		__entry->gid	= inode->i_gid;
+		__entry->blocks	= inode->i_blocks;
+	),
+
+	TP_printk("dev %s ino %lu mode %d uid %u gid %u blocks %llu",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->mode,
+		  __entry->uid, __entry->gid, __entry->blocks)
+);
+
+TRACE_EVENT(ext4_request_inode,
+	TP_PROTO(struct inode *dir, int mode),
+
+	TP_ARGS(dir, mode),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	dir			)
+		__field(	umode_t, mode			)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= dir->i_sb->s_dev;
+		__entry->dir	= dir->i_ino;
+		__entry->mode	= mode;
+	),
+
+	TP_printk("dev %s dir %lu mode %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->dir, __entry->mode)
+);
+
+TRACE_EVENT(ext4_allocate_inode,
+	TP_PROTO(struct inode *inode, struct inode *dir, int mode),
+
+	TP_ARGS(inode, dir, mode),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	ino_t,	dir			)
+		__field(	umode_t, mode			)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+		__entry->dir	= dir->i_ino;
+		__entry->mode	= mode;
+	),
+
+	TP_printk("dev %s ino %lu dir %lu mode %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->dir, __entry->mode)
+);
+
+TRACE_EVENT(ext4_write_begin,
+
+	TP_PROTO(struct inode *inode, loff_t pos, unsigned int len,
+		 unsigned int flags),
+
+	TP_ARGS(inode, pos, len, flags),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	loff_t,	pos			)
+		__field(	unsigned int, len		)
+		__field(	unsigned int, flags		)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+		__entry->pos	= pos;
+		__entry->len	= len;
+		__entry->flags	= flags;
+	),
+
+	TP_printk("dev %s ino %lu pos %llu len %u flags %u",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->pos, __entry->len,
+		  __entry->flags)
+);
+
+TRACE_EVENT(ext4_ordered_write_end,
+	TP_PROTO(struct inode *inode, loff_t pos, unsigned int len,
+			unsigned int copied),
+
+	TP_ARGS(inode, pos, len, copied),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	loff_t,	pos			)
+		__field(	unsigned int, len		)
+		__field(	unsigned int, copied		)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+		__entry->pos	= pos;
+		__entry->len	= len;
+		__entry->copied	= copied;
+	),
+
+	TP_printk("dev %s ino %lu pos %llu len %u copied %u",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->pos, __entry->len,
+		  __entry->copied)
+);
+
+TRACE_EVENT(ext4_writeback_write_end,
+	TP_PROTO(struct inode *inode, loff_t pos, unsigned int len,
+		 unsigned int copied),
+
+	TP_ARGS(inode, pos, len, copied),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	loff_t,	pos			)
+		__field(	unsigned int, len		)
+		__field(	unsigned int, copied		)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+		__entry->pos	= pos;
+		__entry->len	= len;
+		__entry->copied	= copied;
+	),
+
+	TP_printk("dev %s ino %lu pos %llu len %u copied %u",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->pos, __entry->len,
+		  __entry->copied)
+);
+
+TRACE_EVENT(ext4_journalled_write_end,
+	TP_PROTO(struct inode *inode, loff_t pos, unsigned int len,
+		 unsigned int copied),
+	TP_ARGS(inode, pos, len, copied),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	loff_t,	pos			)
+		__field(	unsigned int, len		)
+		__field(	unsigned int, copied		)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+		__entry->pos	= pos;
+		__entry->len	= len;
+		__entry->copied	= copied;
+	),
+
+	TP_printk("dev %s ino %lu pos %llu len %u copied %u",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->pos, __entry->len,
+		  __entry->copied)
+);
+
+TRACE_EVENT(ext4_da_writepage,
+	TP_PROTO(struct inode *inode, struct page *page),
+
+	TP_ARGS(inode, page),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	pgoff_t, index			)
+
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+		__entry->index	= page->index;
+	),
+
+	TP_printk("dev %s ino %lu page_index %lu",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->index)
+);
+
+TRACE_EVENT(ext4_da_writepages,
+	TP_PROTO(struct inode *inode, struct writeback_control *wbc),
+
+	TP_ARGS(inode, wbc),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	long,	nr_to_write		)
+		__field(	long,	pages_skipped		)
+		__field(	loff_t,	range_start		)
+		__field(	loff_t,	range_end		)
+		__field(	char,	nonblocking		)
+		__field(	char,	for_kupdate		)
+		__field(	char,	for_reclaim		)
+		__field(	char,	for_writepages		)
+		__field(	char,	range_cyclic		)
+	),
+
+	TP_fast_assign(
+		__entry->dev		= inode->i_sb->s_dev;
+		__entry->ino		= inode->i_ino;
+		__entry->nr_to_write	= wbc->nr_to_write;
+		__entry->pages_skipped	= wbc->pages_skipped;
+		__entry->range_start	= wbc->range_start;
+		__entry->range_end	= wbc->range_end;
+		__entry->nonblocking	= wbc->nonblocking;
+		__entry->for_kupdate	= wbc->for_kupdate;
+		__entry->for_reclaim	= wbc->for_reclaim;
+		__entry->for_writepages	= wbc->for_writepages;
+		__entry->range_cyclic	= wbc->range_cyclic;
+	),
+
+	TP_printk("dev %s ino %lu nr_t_write %ld pages_skipped %ld range_start %llu range_end %llu nonblocking %d for_kupdate %d for_reclaim %d for_writepages %d range_cyclic %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->nr_to_write,
+		  __entry->pages_skipped, __entry->range_start,
+		  __entry->range_end, __entry->nonblocking,
+		  __entry->for_kupdate, __entry->for_reclaim,
+		  __entry->for_writepages, __entry->range_cyclic)
+);
+
+TRACE_EVENT(ext4_da_writepages_result,
+	TP_PROTO(struct inode *inode, struct writeback_control *wbc,
+			int ret, int pages_written),
+
+	TP_ARGS(inode, wbc, ret, pages_written),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	int,	ret			)
+		__field(	int,	pages_written		)
+		__field(	long,	pages_skipped		)
+		__field(	char,	encountered_congestion	)
+		__field(	char,	more_io			)	
+		__field(	char,	no_nrwrite_index_update )
+	),
+
+	TP_fast_assign(
+		__entry->dev		= inode->i_sb->s_dev;
+		__entry->ino		= inode->i_ino;
+		__entry->ret		= ret;
+		__entry->pages_written	= pages_written;
+		__entry->pages_skipped	= wbc->pages_skipped;
+		__entry->encountered_congestion	= wbc->encountered_congestion;
+		__entry->more_io	= wbc->more_io;
+		__entry->no_nrwrite_index_update = wbc->no_nrwrite_index_update;
+	),
+
+	TP_printk("dev %s ino %lu ret %d pages_written %d pages_skipped %ld congestion %d more_io %d no_nrwrite_index_update %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->ret,
+		  __entry->pages_written, __entry->pages_skipped,
+		  __entry->encountered_congestion, __entry->more_io,
+		  __entry->no_nrwrite_index_update)
+);
+
+TRACE_EVENT(ext4_da_write_begin,
+	TP_PROTO(struct inode *inode, loff_t pos, unsigned int len,
+			unsigned int flags),
+
+	TP_ARGS(inode, pos, len, flags),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	loff_t,	pos			)
+		__field(	unsigned int, len		)
+		__field(	unsigned int, flags		)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+		__entry->pos	= pos;
+		__entry->len	= len;
+		__entry->flags	= flags;
+	),
+
+	TP_printk("dev %s ino %lu pos %llu len %u flags %u",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->pos, __entry->len,
+		  __entry->flags)
+);
+
+TRACE_EVENT(ext4_da_write_end,
+	TP_PROTO(struct inode *inode, loff_t pos, unsigned int len,
+			unsigned int copied),
+
+	TP_ARGS(inode, pos, len, copied),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	loff_t,	pos			)
+		__field(	unsigned int, len		)
+		__field(	unsigned int, copied		)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+		__entry->pos	= pos;
+		__entry->len	= len;
+		__entry->copied	= copied;
+	),
+
+	TP_printk("dev %s ino %lu pos %llu len %u copied %u",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->pos, __entry->len,
+		  __entry->copied)
+);
+
+TRACE_EVENT(ext4_normal_writepage,
+	TP_PROTO(struct inode *inode, struct page *page),
+
+	TP_ARGS(inode, page),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	pgoff_t, index			)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+		__entry->index	= page->index;
+	),
+
+	TP_printk("dev %s ino %lu page_index %lu",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->index)
+);
+
+TRACE_EVENT(ext4_journalled_writepage,
+	TP_PROTO(struct inode *inode, struct page *page),
+
+	TP_ARGS(inode, page),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	pgoff_t, index			)
+
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+		__entry->index	= page->index;
+	),
+
+	TP_printk("dev %s ino %lu page_index %lu",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->index)
+);
+
+TRACE_EVENT(ext4_discard_blocks,
+	TP_PROTO(struct super_block *sb, unsigned long long blk,
+			unsigned long long count),
+
+	TP_ARGS(sb, blk, count),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	__u64,	blk			)
+		__field(	__u64,	count			)
+
+	),
+
+	TP_fast_assign(
+		__entry->dev	= sb->s_dev;
+		__entry->blk	= blk;
+		__entry->count	= count;
+	),
+
+	TP_printk("dev %s blk %llu count %llu",
+		  jbd2_dev_to_name(__entry->dev), __entry->blk, __entry->count)
+);
+
+TRACE_EVENT(ext4_mb_new_inode_pa,
+	TP_PROTO(struct ext4_allocation_context *ac,
+		 struct ext4_prealloc_space *pa),
+
+	TP_ARGS(ac, pa),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	__u64,	pa_pstart		)
+		__field(	__u32,	pa_len			)
+		__field(	__u64,	pa_lstart		)
+
+	),
+
+	TP_fast_assign(
+		__entry->dev		= ac->ac_sb->s_dev;
+		__entry->ino		= ac->ac_inode->i_ino;
+		__entry->pa_pstart	= pa->pa_pstart;
+		__entry->pa_len		= pa->pa_len;
+		__entry->pa_lstart	= pa->pa_lstart;
+	),
+
+	TP_printk("dev %s ino %lu pstart %llu len %u lstart %llu",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->pa_pstart,
+		  __entry->pa_len, __entry->pa_lstart)
+);
+
+TRACE_EVENT(ext4_mb_new_group_pa,
+	TP_PROTO(struct ext4_allocation_context *ac,
+		 struct ext4_prealloc_space *pa),
+
+	TP_ARGS(ac, pa),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	__u64,	pa_pstart		)
+		__field(	__u32,	pa_len			)
+		__field(	__u64,	pa_lstart		)
+
+	),
+
+	TP_fast_assign(
+		__entry->dev		= ac->ac_sb->s_dev;
+		__entry->ino		= ac->ac_inode->i_ino;
+		__entry->pa_pstart	= pa->pa_pstart;
+		__entry->pa_len		= pa->pa_len;
+		__entry->pa_lstart	= pa->pa_lstart;
+	),
+
+	TP_printk("dev %s ino %lu pstart %llu len %u lstart %llu",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->pa_pstart,
+		  __entry->pa_len, __entry->pa_lstart)
+);
+
+TRACE_EVENT(ext4_mb_release_inode_pa,
+	TP_PROTO(struct ext4_allocation_context *ac,
+		 struct ext4_prealloc_space *pa,
+		 unsigned long long block, unsigned int count),
+
+	TP_ARGS(ac, pa, block, count),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	__u64,	block			)
+		__field(	__u32,	count			)
+
+	),
+
+	TP_fast_assign(
+		__entry->dev		= ac->ac_sb->s_dev;
+		__entry->ino		= ac->ac_inode->i_ino;
+		__entry->block		= block;
+		__entry->count		= count;
+	),
+
+	TP_printk("dev %s ino %lu block %llu count %u",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->block,
+		  __entry->count)
+);
+
+TRACE_EVENT(ext4_mb_release_group_pa,
+	TP_PROTO(struct ext4_allocation_context *ac,
+		 struct ext4_prealloc_space *pa),
+
+	TP_ARGS(ac, pa),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	__u64,	pa_pstart		)
+		__field(	__u32,	pa_len			)
+
+	),
+
+	TP_fast_assign(
+		__entry->dev		= ac->ac_sb->s_dev;
+		__entry->ino		= ac->ac_inode->i_ino;
+		__entry->pa_pstart	= pa->pa_pstart;
+		__entry->pa_len		= pa->pa_len;
+	),
+
+	TP_printk("dev %s pstart %llu len %u",
+		  jbd2_dev_to_name(__entry->dev), __entry->pa_pstart, __entry->pa_len)
+);
+
+TRACE_EVENT(ext4_discard_preallocations,
+	TP_PROTO(struct inode *inode),
+
+	TP_ARGS(inode),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+	),
+
+	TP_printk("dev %s ino %lu",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino)
+);
+
+TRACE_EVENT(ext4_mb_discard_preallocations,
+	TP_PROTO(struct super_block *sb, int needed),
+
+	TP_ARGS(sb, needed),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	int,	needed			)
+
+	),
+
+	TP_fast_assign(
+		__entry->dev	= sb->s_dev;
+		__entry->needed	= needed;
+	),
+
+	TP_printk("dev %s needed %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->needed)
+);
+
+TRACE_EVENT(ext4_request_blocks,
+	TP_PROTO(struct ext4_allocation_request *ar),
+
+	TP_ARGS(ar),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	unsigned int, flags		)
+		__field(	unsigned int, len		)
+		__field(	__u64,  logical			)
+		__field(	__u64,	goal			)
+		__field(	__u64,	lleft			)
+		__field(	__u64,	lright			)
+		__field(	__u64,	pleft			)
+		__field(	__u64,	pright			)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= ar->inode->i_sb->s_dev;
+		__entry->ino	= ar->inode->i_ino;
+		__entry->flags	= ar->flags;
+		__entry->len	= ar->len;
+		__entry->logical = ar->logical;
+		__entry->goal	= ar->goal;
+		__entry->lleft	= ar->lleft;
+		__entry->lright	= ar->lright;
+		__entry->pleft	= ar->pleft;
+		__entry->pright	= ar->pright;
+	),
+
+	TP_printk("dev %s ino %lu flags %u len %u lblk %llu goal %llu lleft %llu lright %llu pleft %llu pright %llu ",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->flags,
+		  __entry->len,
+		  (unsigned long long) __entry->logical,
+		  (unsigned long long) __entry->goal,
+		  (unsigned long long) __entry->lleft,
+		  (unsigned long long) __entry->lright,
+		  (unsigned long long) __entry->pleft,
+		  (unsigned long long) __entry->pright)
+);
+
+TRACE_EVENT(ext4_allocate_blocks,
+	TP_PROTO(struct ext4_allocation_request *ar, unsigned long long block),
+
+	TP_ARGS(ar, block),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	__u64,	block			)
+		__field(	unsigned int, flags		)
+		__field(	unsigned int, len		)
+		__field(	__u64,  logical			)
+		__field(	__u64,	goal			)
+		__field(	__u64,	lleft			)
+		__field(	__u64,	lright			)
+		__field(	__u64,	pleft			)
+		__field(	__u64,	pright			)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= ar->inode->i_sb->s_dev;
+		__entry->ino	= ar->inode->i_ino;
+		__entry->block	= block;
+		__entry->flags	= ar->flags;
+		__entry->len	= ar->len;
+		__entry->logical = ar->logical;
+		__entry->goal	= ar->goal;
+		__entry->lleft	= ar->lleft;
+		__entry->lright	= ar->lright;
+		__entry->pleft	= ar->pleft;
+		__entry->pright	= ar->pright;
+	),
+
+	TP_printk("dev %s ino %lu flags %u len %u block %llu lblk %llu goal %llu lleft %llu lright %llu pleft %llu pright %llu ",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->flags,
+		  __entry->len, __entry->block,
+		  (unsigned long long) __entry->logical,
+		  (unsigned long long) __entry->goal,
+		  (unsigned long long) __entry->lleft,
+		  (unsigned long long) __entry->lright,
+		  (unsigned long long) __entry->pleft,
+		  (unsigned long long) __entry->pright)
+);
+
+TRACE_EVENT(ext4_free_blocks,
+	TP_PROTO(struct inode *inode, __u64 block, unsigned long count,
+			int metadata),
+
+	TP_ARGS(inode, block, count, metadata),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	__u64,	block			)
+		__field(	unsigned long,	count		)
+		__field(	int,	metadata		)
+
+	),
+
+	TP_fast_assign(
+		__entry->dev		= inode->i_sb->s_dev;
+		__entry->ino		= inode->i_ino;
+		__entry->block		= block;
+		__entry->count		= count;
+		__entry->metadata	= metadata;
+	),
+
+	TP_printk("dev %s ino %lu block %llu count %lu metadata %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->block,
+		  __entry->count, __entry->metadata)
+);
+
+TRACE_EVENT(ext4_sync_file,
+	TP_PROTO(struct file *file, struct dentry *dentry, int datasync),
+
+	TP_ARGS(file, dentry, datasync),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+		__field(	ino_t,	parent			)
+		__field(	int,	datasync		)
+	),
+
+	TP_fast_assign(
+		__entry->dev		= dentry->d_inode->i_sb->s_dev;
+		__entry->ino		= dentry->d_inode->i_ino;
+		__entry->datasync	= datasync;
+		__entry->parent		= dentry->d_parent->d_inode->i_ino;
+	),
+
+	TP_printk("dev %s ino %ld parent %ld datasync %d ",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino, __entry->parent,
+		  __entry->datasync)
+);
+
+TRACE_EVENT(ext4_sync_fs,
+	TP_PROTO(struct super_block *sb, int wait),
+
+	TP_ARGS(sb, wait),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	int,	wait			)
+
+	),
+
+	TP_fast_assign(
+		__entry->dev	= sb->s_dev;
+		__entry->wait	= wait;
+	),
+
+	TP_printk("dev %s wait %d", jbd2_dev_to_name(__entry->dev),
+		  __entry->wait)
+);
+
+#endif /* _TRACE_EXT4_H */
+
+/* This part must be outside protection */
+#include <trace/define_trace.h>
diff --git a/include/trace/events/jbd2.h b/include/trace/events/jbd2.h
new file mode 100644
index 0000000..845b0b4
--- /dev/null
+++ b/include/trace/events/jbd2.h
@@ -0,0 +1,168 @@
+#if !defined(_TRACE_JBD2_H) || defined(TRACE_HEADER_MULTI_READ)
+#define _TRACE_JBD2_H
+
+#include <linux/jbd2.h>
+#include <linux/tracepoint.h>
+
+#undef TRACE_SYSTEM
+#define TRACE_SYSTEM jbd2
+
+TRACE_EVENT(jbd2_checkpoint,
+
+	TP_PROTO(journal_t *journal, int result),
+
+	TP_ARGS(journal, result),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	int,	result			)
+	),
+
+	TP_fast_assign(
+		__entry->dev		= journal->j_fs_dev->bd_dev;
+		__entry->result		= result;
+	),
+
+	TP_printk("dev %s result %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->result)
+);
+
+TRACE_EVENT(jbd2_start_commit,
+
+	TP_PROTO(journal_t *journal, transaction_t *commit_transaction),
+
+	TP_ARGS(journal, commit_transaction),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	char,	sync_commit		  )
+		__field(	int,	transaction		  )
+	),
+
+	TP_fast_assign(
+		__entry->dev		= journal->j_fs_dev->bd_dev;
+		__entry->sync_commit = commit_transaction->t_synchronous_commit;
+		__entry->transaction	= commit_transaction->t_tid;
+	),
+
+	TP_printk("dev %s transaction %d sync %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->transaction,
+		  __entry->sync_commit)
+);
+
+TRACE_EVENT(jbd2_commit_locking,
+
+	TP_PROTO(journal_t *journal, transaction_t *commit_transaction),
+
+	TP_ARGS(journal, commit_transaction),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	char,	sync_commit		  )
+		__field(	int,	transaction		  )
+	),
+
+	TP_fast_assign(
+		__entry->dev		= journal->j_fs_dev->bd_dev;
+		__entry->sync_commit = commit_transaction->t_synchronous_commit;
+		__entry->transaction	= commit_transaction->t_tid;
+	),
+
+	TP_printk("dev %s transaction %d sync %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->transaction,
+		  __entry->sync_commit)
+);
+
+TRACE_EVENT(jbd2_commit_flushing,
+
+	TP_PROTO(journal_t *journal, transaction_t *commit_transaction),
+
+	TP_ARGS(journal, commit_transaction),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	char,	sync_commit		  )
+		__field(	int,	transaction		  )
+	),
+
+	TP_fast_assign(
+		__entry->dev		= journal->j_fs_dev->bd_dev;
+		__entry->sync_commit = commit_transaction->t_synchronous_commit;
+		__entry->transaction	= commit_transaction->t_tid;
+	),
+
+	TP_printk("dev %s transaction %d sync %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->transaction,
+		  __entry->sync_commit)
+);
+
+TRACE_EVENT(jbd2_commit_logging,
+
+	TP_PROTO(journal_t *journal, transaction_t *commit_transaction),
+
+	TP_ARGS(journal, commit_transaction),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	char,	sync_commit		  )
+		__field(	int,	transaction		  )
+	),
+
+	TP_fast_assign(
+		__entry->dev		= journal->j_fs_dev->bd_dev;
+		__entry->sync_commit = commit_transaction->t_synchronous_commit;
+		__entry->transaction	= commit_transaction->t_tid;
+	),
+
+	TP_printk("dev %s transaction %d sync %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->transaction,
+		  __entry->sync_commit)
+);
+
+TRACE_EVENT(jbd2_end_commit,
+	TP_PROTO(journal_t *journal, transaction_t *commit_transaction),
+
+	TP_ARGS(journal, commit_transaction),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	char,	sync_commit		  )
+		__field(	int,	transaction		  )
+		__field(	int,	head		  	  )
+	),
+
+	TP_fast_assign(
+		__entry->dev		= journal->j_fs_dev->bd_dev;
+		__entry->sync_commit = commit_transaction->t_synchronous_commit;
+		__entry->transaction	= commit_transaction->t_tid;
+		__entry->head		= journal->j_tail_sequence;
+	),
+
+	TP_printk("dev %s transaction %d sync %d head %d",
+		  jbd2_dev_to_name(__entry->dev), __entry->transaction,
+		  __entry->sync_commit, __entry->head)
+);
+
+TRACE_EVENT(jbd2_submit_inode_data,
+	TP_PROTO(struct inode *inode),
+
+	TP_ARGS(inode),
+
+	TP_STRUCT__entry(
+		__field(	dev_t,	dev			)
+		__field(	ino_t,	ino			)
+	),
+
+	TP_fast_assign(
+		__entry->dev	= inode->i_sb->s_dev;
+		__entry->ino	= inode->i_ino;
+	),
+
+	TP_printk("dev %s ino %lu",
+		  jbd2_dev_to_name(__entry->dev), __entry->ino)
+);
+
+#endif /* _TRACE_JBD2_H */
+
+/* This part must be outside protection */
+#include <trace/define_trace.h>
diff --git a/init/Kconfig b/init/Kconfig
index c4b3c6d..1ce05a4 100644
--- a/init/Kconfig
+++ b/init/Kconfig
@@ -16,6 +16,11 @@
 	default "$ARCH_DEFCONFIG"
 	default "arch/$ARCH/defconfig"
 
+config CONSTRUCTORS
+	bool
+	depends on !UML
+	default y
+
 menu "General setup"
 
 config EXPERIMENTAL
diff --git a/init/main.c b/init/main.c
index 0e7aede..09131ec 100644
--- a/init/main.c
+++ b/init/main.c
@@ -642,6 +642,10 @@
 				 "enabled early\n");
 	early_boot_irqs_on();
 	local_irq_enable();
+
+	/* Interrupts are enabled now so all GFP allocations are safe. */
+	set_gfp_allowed_mask(__GFP_BITS_MASK);
+
 	kmem_cache_init_late();
 
 	/*
@@ -720,6 +724,17 @@
 	rest_init();
 }
 
+/* Call all constructor functions linked into the kernel. */
+static void __init do_ctors(void)
+{
+#ifdef CONFIG_CONSTRUCTORS
+	ctor_fn_t *call = (ctor_fn_t *) __ctors_start;
+
+	for (; call < (ctor_fn_t *) __ctors_end; call++)
+		(*call)();
+#endif
+}
+
 int initcall_debug;
 core_param(initcall_debug, initcall_debug, bool, 0644);
 
@@ -800,6 +815,7 @@
 	usermodehelper_init();
 	driver_init();
 	init_irq_proc();
+	do_ctors();
 	do_initcalls();
 }
 
diff --git a/ipc/namespace.c b/ipc/namespace.c
index 4a5e752..a1094ff 100644
--- a/ipc/namespace.c
+++ b/ipc/namespace.c
@@ -14,7 +14,7 @@
 
 #include "util.h"
 
-static struct ipc_namespace *clone_ipc_ns(struct ipc_namespace *old_ns)
+static struct ipc_namespace *create_ipc_ns(void)
 {
 	struct ipc_namespace *ns;
 	int err;
@@ -48,18 +48,9 @@
 
 struct ipc_namespace *copy_ipcs(unsigned long flags, struct ipc_namespace *ns)
 {
-	struct ipc_namespace *new_ns;
-
-	BUG_ON(!ns);
-	get_ipc_ns(ns);
-
 	if (!(flags & CLONE_NEWIPC))
-		return ns;
-
-	new_ns = clone_ipc_ns(ns);
-
-	put_ipc_ns(ns);
-	return new_ns;
+		return get_ipc_ns(ns);
+	return create_ipc_ns();
 }
 
 /*
@@ -92,6 +83,30 @@
 	up_write(&ids->rw_mutex);
 }
 
+static void free_ipc_ns(struct ipc_namespace *ns)
+{
+	/*
+	 * Unregistering the hotplug notifier at the beginning guarantees
+	 * that the ipc namespace won't be freed while we are inside the
+	 * callback routine. Since the blocking_notifier_chain_XXX routines
+	 * hold a rw lock on the notifier list, unregister_ipcns_notifier()
+	 * won't take the rw lock before blocking_notifier_call_chain() has
+	 * released the rd lock.
+	 */
+	unregister_ipcns_notifier(ns);
+	sem_exit_ns(ns);
+	msg_exit_ns(ns);
+	shm_exit_ns(ns);
+	kfree(ns);
+	atomic_dec(&nr_ipc_ns);
+
+	/*
+	 * Do the ipcns removal notification after decrementing nr_ipc_ns in
+	 * order to have a correct value when recomputing msgmni.
+	 */
+	ipcns_notify(IPCNS_REMOVED);
+}
+
 /*
  * put_ipc_ns - drop a reference to an ipc namespace.
  * @ns: the namespace to put
@@ -117,27 +132,3 @@
 		free_ipc_ns(ns);
 	}
 }
-
-void free_ipc_ns(struct ipc_namespace *ns)
-{
-	/*
-	 * Unregistering the hotplug notifier at the beginning guarantees
-	 * that the ipc namespace won't be freed while we are inside the
-	 * callback routine. Since the blocking_notifier_chain_XXX routines
-	 * hold a rw lock on the notifier list, unregister_ipcns_notifier()
-	 * won't take the rw lock before blocking_notifier_call_chain() has
-	 * released the rd lock.
-	 */
-	unregister_ipcns_notifier(ns);
-	sem_exit_ns(ns);
-	msg_exit_ns(ns);
-	shm_exit_ns(ns);
-	kfree(ns);
-	atomic_dec(&nr_ipc_ns);
-
-	/*
-	 * Do the ipcns removal notification after decrementing nr_ipc_ns in
-	 * order to have a correct value when recomputing msgmni.
-	 */
-	ipcns_notify(IPCNS_REMOVED);
-}
diff --git a/ipc/util.h b/ipc/util.h
index 1187332..ab3ebf2 100644
--- a/ipc/util.h
+++ b/ipc/util.h
@@ -128,7 +128,7 @@
 struct kern_ipc_perm *ipcctl_pre_down(struct ipc_ids *ids, int id, int cmd,
 				      struct ipc64_perm *perm, int extra_perm);
 
-#if defined(__ia64__) || defined(__x86_64__) || defined(__hppa__) || defined(__XTENSA__)
+#ifndef __ARCH_WANT_IPC_PARSE_VERSION
   /* On IA-64, we always use the "64-bit version" of the IPC structures.  */ 
 # define ipc_parse_version(cmd)	IPC_64
 #else
@@ -171,5 +171,6 @@
 struct kern_ipc_perm *ipc_lock_check(struct ipc_ids *ids, int id);
 int ipcget(struct ipc_namespace *ns, struct ipc_ids *ids,
 			struct ipc_ops *ops, struct ipc_params *params);
-
+void free_ipcs(struct ipc_namespace *ns, struct ipc_ids *ids,
+		void (*free)(struct ipc_namespace *, struct kern_ipc_perm *));
 #endif
diff --git a/kernel/Makefile b/kernel/Makefile
index 9df4501..0a32cb2 100644
--- a/kernel/Makefile
+++ b/kernel/Makefile
@@ -71,6 +71,7 @@
 obj-$(CONFIG_KPROBES_SANITY_TEST) += test_kprobes.o
 obj-$(CONFIG_AUDIT) += audit.o auditfilter.o
 obj-$(CONFIG_AUDITSYSCALL) += auditsc.o
+obj-$(CONFIG_GCOV_KERNEL) += gcov/
 obj-$(CONFIG_AUDIT_TREE) += audit_tree.o
 obj-$(CONFIG_KPROBES) += kprobes.o
 obj-$(CONFIG_KGDB) += kgdb.o
diff --git a/kernel/cgroup.c b/kernel/cgroup.c
index 3fb789f..3737a68 100644
--- a/kernel/cgroup.c
+++ b/kernel/cgroup.c
@@ -843,6 +843,11 @@
 				     struct cgroup_sb_opts *opts)
 {
 	char *token, *o = data ?: "all";
+	unsigned long mask = (unsigned long)-1;
+
+#ifdef CONFIG_CPUSETS
+	mask = ~(1UL << cpuset_subsys_id);
+#endif
 
 	opts->subsys_bits = 0;
 	opts->flags = 0;
@@ -887,6 +892,15 @@
 		}
 	}
 
+	/*
+	 * Option noprefix was introduced just for backward compatibility
+	 * with the old cpuset, so we allow noprefix only if mounting just
+	 * the cpuset subsystem.
+	 */
+	if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
+	    (opts->subsys_bits & mask))
+		return -EINVAL;
+
 	/* We can't have an empty hierarchy */
 	if (!opts->subsys_bits)
 		return -EINVAL;
diff --git a/kernel/exit.c b/kernel/exit.c
index b6c90b5..628d41f 100644
--- a/kernel/exit.c
+++ b/kernel/exit.c
@@ -375,9 +375,8 @@
 }
 
 /*
- * Let kernel threads use this to say that they
- * allow a certain signal (since daemonize() will
- * have disabled all of them by default).
+ * Let kernel threads use this to say that they allow a certain signal.
+ * Must not be used if kthread was cloned with CLONE_SIGHAND.
  */
 int allow_signal(int sig)
 {
@@ -385,14 +384,14 @@
 		return -EINVAL;
 
 	spin_lock_irq(&current->sighand->siglock);
+	/* This is only needed for daemonize()'ed kthreads */
 	sigdelset(&current->blocked, sig);
-	if (!current->mm) {
-		/* Kernel threads handle their own signals.
-		   Let the signal code know it'll be handled, so
-		   that they don't get converted to SIGKILL or
-		   just silently dropped */
-		current->sighand->action[(sig)-1].sa.sa_handler = (void __user *)2;
-	}
+	/*
+	 * Kernel threads handle their own signals. Let the signal code
+	 * know it'll be handled, so that they don't get converted to
+	 * SIGKILL or just silently dropped.
+	 */
+	current->sighand->action[(sig)-1].sa.sa_handler = (void __user *)2;
 	recalc_sigpending();
 	spin_unlock_irq(&current->sighand->siglock);
 	return 0;
@@ -591,7 +590,7 @@
 	/*
 	 * Search in the siblings
 	 */
-	list_for_each_entry(c, &p->parent->children, sibling) {
+	list_for_each_entry(c, &p->real_parent->children, sibling) {
 		if (c->mm == mm)
 			goto assign_new_owner;
 	}
@@ -758,7 +757,7 @@
 	p->exit_signal = SIGCHLD;
 
 	/* If it has exited notify the new parent about this child's death. */
-	if (!p->ptrace &&
+	if (!task_ptrace(p) &&
 	    p->exit_state == EXIT_ZOMBIE && thread_group_empty(p)) {
 		do_notify_parent(p, p->exit_signal);
 		if (task_detached(p)) {
@@ -783,7 +782,7 @@
 	list_for_each_entry_safe(p, n, &father->children, sibling) {
 		p->real_parent = reaper;
 		if (p->parent == father) {
-			BUG_ON(p->ptrace);
+			BUG_ON(task_ptrace(p));
 			p->parent = p->real_parent;
 		}
 		reparent_thread(father, p, &dead_children);
@@ -1081,6 +1080,18 @@
 	return 0;
 }
 
+struct wait_opts {
+	enum pid_type		wo_type;
+	int			wo_flags;
+	struct pid		*wo_pid;
+
+	struct siginfo __user	*wo_info;
+	int __user		*wo_stat;
+	struct rusage __user	*wo_rusage;
+
+	int			notask_error;
+};
+
 static struct pid *task_pid_type(struct task_struct *task, enum pid_type type)
 {
 	struct pid *pid = NULL;
@@ -1091,13 +1102,12 @@
 	return pid;
 }
 
-static int eligible_child(enum pid_type type, struct pid *pid, int options,
-			  struct task_struct *p)
+static int eligible_child(struct wait_opts *wo, struct task_struct *p)
 {
 	int err;
 
-	if (type < PIDTYPE_MAX) {
-		if (task_pid_type(p, type) != pid)
+	if (wo->wo_type < PIDTYPE_MAX) {
+		if (task_pid_type(p, wo->wo_type) != wo->wo_pid)
 			return 0;
 	}
 
@@ -1106,8 +1116,8 @@
 	 * set; otherwise, wait for non-clone children *only*.  (Note:
 	 * A "clone" child here is one that reports to its parent
 	 * using a signal other than SIGCHLD.) */
-	if (((p->exit_signal != SIGCHLD) ^ ((options & __WCLONE) != 0))
-	    && !(options & __WALL))
+	if (((p->exit_signal != SIGCHLD) ^ !!(wo->wo_flags & __WCLONE))
+	    && !(wo->wo_flags & __WALL))
 		return 0;
 
 	err = security_task_wait(p);
@@ -1117,14 +1127,15 @@
 	return 1;
 }
 
-static int wait_noreap_copyout(struct task_struct *p, pid_t pid, uid_t uid,
-			       int why, int status,
-			       struct siginfo __user *infop,
-			       struct rusage __user *rusagep)
+static int wait_noreap_copyout(struct wait_opts *wo, struct task_struct *p,
+				pid_t pid, uid_t uid, int why, int status)
 {
-	int retval = rusagep ? getrusage(p, RUSAGE_BOTH, rusagep) : 0;
+	struct siginfo __user *infop;
+	int retval = wo->wo_rusage
+		? getrusage(p, RUSAGE_BOTH, wo->wo_rusage) : 0;
 
 	put_task_struct(p);
+	infop = wo->wo_info;
 	if (!retval)
 		retval = put_user(SIGCHLD, &infop->si_signo);
 	if (!retval)
@@ -1148,19 +1159,18 @@
  * the lock and this task is uninteresting.  If we return nonzero, we have
  * released the lock and the system call should return.
  */
-static int wait_task_zombie(struct task_struct *p, int options,
-			    struct siginfo __user *infop,
-			    int __user *stat_addr, struct rusage __user *ru)
+static int wait_task_zombie(struct wait_opts *wo, struct task_struct *p)
 {
 	unsigned long state;
 	int retval, status, traced;
 	pid_t pid = task_pid_vnr(p);
 	uid_t uid = __task_cred(p)->uid;
+	struct siginfo __user *infop;
 
-	if (!likely(options & WEXITED))
+	if (!likely(wo->wo_flags & WEXITED))
 		return 0;
 
-	if (unlikely(options & WNOWAIT)) {
+	if (unlikely(wo->wo_flags & WNOWAIT)) {
 		int exit_code = p->exit_code;
 		int why, status;
 
@@ -1173,8 +1183,7 @@
 			why = (exit_code & 0x80) ? CLD_DUMPED : CLD_KILLED;
 			status = exit_code & 0x7f;
 		}
-		return wait_noreap_copyout(p, pid, uid, why,
-					   status, infop, ru);
+		return wait_noreap_copyout(wo, p, pid, uid, why, status);
 	}
 
 	/*
@@ -1188,11 +1197,13 @@
 	}
 
 	traced = ptrace_reparented(p);
-
-	if (likely(!traced)) {
+	/*
+	 * It can be ptraced but not reparented, check
+	 * !task_detached() to filter out sub-threads.
+	 */
+	if (likely(!traced) && likely(!task_detached(p))) {
 		struct signal_struct *psig;
 		struct signal_struct *sig;
-		struct task_cputime cputime;
 
 		/*
 		 * The resource counters for the group leader are in its
@@ -1205,26 +1216,23 @@
 		 * p->signal fields, because they are only touched by
 		 * __exit_signal, which runs with tasklist_lock
 		 * write-locked anyway, and so is excluded here.  We do
-		 * need to protect the access to p->parent->signal fields,
+		 * need to protect the access to parent->signal fields,
 		 * as other threads in the parent group can be right
 		 * here reaping other children at the same time.
-		 *
-		 * We use thread_group_cputime() to get times for the thread
-		 * group, which consolidates times for all threads in the
-		 * group including the group leader.
 		 */
-		thread_group_cputime(p, &cputime);
-		spin_lock_irq(&p->parent->sighand->siglock);
-		psig = p->parent->signal;
+		spin_lock_irq(&p->real_parent->sighand->siglock);
+		psig = p->real_parent->signal;
 		sig = p->signal;
 		psig->cutime =
 			cputime_add(psig->cutime,
-			cputime_add(cputime.utime,
-				    sig->cutime));
+			cputime_add(p->utime,
+			cputime_add(sig->utime,
+				    sig->cutime)));
 		psig->cstime =
 			cputime_add(psig->cstime,
-			cputime_add(cputime.stime,
-				    sig->cstime));
+			cputime_add(p->stime,
+			cputime_add(sig->stime,
+				    sig->cstime)));
 		psig->cgtime =
 			cputime_add(psig->cgtime,
 			cputime_add(p->gtime,
@@ -1246,7 +1254,7 @@
 			sig->oublock + sig->coublock;
 		task_io_accounting_add(&psig->ioac, &p->ioac);
 		task_io_accounting_add(&psig->ioac, &sig->ioac);
-		spin_unlock_irq(&p->parent->sighand->siglock);
+		spin_unlock_irq(&p->real_parent->sighand->siglock);
 	}
 
 	/*
@@ -1255,11 +1263,14 @@
 	 */
 	read_unlock(&tasklist_lock);
 
-	retval = ru ? getrusage(p, RUSAGE_BOTH, ru) : 0;
+	retval = wo->wo_rusage
+		? getrusage(p, RUSAGE_BOTH, wo->wo_rusage) : 0;
 	status = (p->signal->flags & SIGNAL_GROUP_EXIT)
 		? p->signal->group_exit_code : p->exit_code;
-	if (!retval && stat_addr)
-		retval = put_user(status, stat_addr);
+	if (!retval && wo->wo_stat)
+		retval = put_user(status, wo->wo_stat);
+
+	infop = wo->wo_info;
 	if (!retval && infop)
 		retval = put_user(SIGCHLD, &infop->si_signo);
 	if (!retval && infop)
@@ -1327,15 +1338,18 @@
  * the lock and this task is uninteresting.  If we return nonzero, we have
  * released the lock and the system call should return.
  */
-static int wait_task_stopped(int ptrace, struct task_struct *p,
-			     int options, struct siginfo __user *infop,
-			     int __user *stat_addr, struct rusage __user *ru)
+static int wait_task_stopped(struct wait_opts *wo,
+				int ptrace, struct task_struct *p)
 {
+	struct siginfo __user *infop;
 	int retval, exit_code, *p_code, why;
 	uid_t uid = 0; /* unneeded, required by compiler */
 	pid_t pid;
 
-	if (!(options & WUNTRACED))
+	/*
+	 * Traditionally we see ptrace'd stopped tasks regardless of options.
+	 */
+	if (!ptrace && !(wo->wo_flags & WUNTRACED))
 		return 0;
 
 	exit_code = 0;
@@ -1349,7 +1363,7 @@
 	if (!exit_code)
 		goto unlock_sig;
 
-	if (!unlikely(options & WNOWAIT))
+	if (!unlikely(wo->wo_flags & WNOWAIT))
 		*p_code = 0;
 
 	/* don't need the RCU readlock here as we're holding a spinlock */
@@ -1371,14 +1385,15 @@
 	why = ptrace ? CLD_TRAPPED : CLD_STOPPED;
 	read_unlock(&tasklist_lock);
 
-	if (unlikely(options & WNOWAIT))
-		return wait_noreap_copyout(p, pid, uid,
-					   why, exit_code,
-					   infop, ru);
+	if (unlikely(wo->wo_flags & WNOWAIT))
+		return wait_noreap_copyout(wo, p, pid, uid, why, exit_code);
 
-	retval = ru ? getrusage(p, RUSAGE_BOTH, ru) : 0;
-	if (!retval && stat_addr)
-		retval = put_user((exit_code << 8) | 0x7f, stat_addr);
+	retval = wo->wo_rusage
+		? getrusage(p, RUSAGE_BOTH, wo->wo_rusage) : 0;
+	if (!retval && wo->wo_stat)
+		retval = put_user((exit_code << 8) | 0x7f, wo->wo_stat);
+
+	infop = wo->wo_info;
 	if (!retval && infop)
 		retval = put_user(SIGCHLD, &infop->si_signo);
 	if (!retval && infop)
@@ -1405,15 +1420,13 @@
  * the lock and this task is uninteresting.  If we return nonzero, we have
  * released the lock and the system call should return.
  */
-static int wait_task_continued(struct task_struct *p, int options,
-			       struct siginfo __user *infop,
-			       int __user *stat_addr, struct rusage __user *ru)
+static int wait_task_continued(struct wait_opts *wo, struct task_struct *p)
 {
 	int retval;
 	pid_t pid;
 	uid_t uid;
 
-	if (!unlikely(options & WCONTINUED))
+	if (!unlikely(wo->wo_flags & WCONTINUED))
 		return 0;
 
 	if (!(p->signal->flags & SIGNAL_STOP_CONTINUED))
@@ -1425,7 +1438,7 @@
 		spin_unlock_irq(&p->sighand->siglock);
 		return 0;
 	}
-	if (!unlikely(options & WNOWAIT))
+	if (!unlikely(wo->wo_flags & WNOWAIT))
 		p->signal->flags &= ~SIGNAL_STOP_CONTINUED;
 	uid = __task_cred(p)->uid;
 	spin_unlock_irq(&p->sighand->siglock);
@@ -1434,17 +1447,17 @@
 	get_task_struct(p);
 	read_unlock(&tasklist_lock);
 
-	if (!infop) {
-		retval = ru ? getrusage(p, RUSAGE_BOTH, ru) : 0;
+	if (!wo->wo_info) {
+		retval = wo->wo_rusage
+			? getrusage(p, RUSAGE_BOTH, wo->wo_rusage) : 0;
 		put_task_struct(p);
-		if (!retval && stat_addr)
-			retval = put_user(0xffff, stat_addr);
+		if (!retval && wo->wo_stat)
+			retval = put_user(0xffff, wo->wo_stat);
 		if (!retval)
 			retval = pid;
 	} else {
-		retval = wait_noreap_copyout(p, pid, uid,
-					     CLD_CONTINUED, SIGCONT,
-					     infop, ru);
+		retval = wait_noreap_copyout(wo, p, pid, uid,
+					     CLD_CONTINUED, SIGCONT);
 		BUG_ON(retval == 0);
 	}
 
@@ -1454,19 +1467,16 @@
 /*
  * Consider @p for a wait by @parent.
  *
- * -ECHILD should be in *@notask_error before the first call.
+ * -ECHILD should be in ->notask_error before the first call.
  * Returns nonzero for a final return, when we have unlocked tasklist_lock.
  * Returns zero if the search for a child should continue;
- * then *@notask_error is 0 if @p is an eligible child,
+ * then ->notask_error is 0 if @p is an eligible child,
  * or another error from security_task_wait(), or still -ECHILD.
  */
-static int wait_consider_task(struct task_struct *parent, int ptrace,
-			      struct task_struct *p, int *notask_error,
-			      enum pid_type type, struct pid *pid, int options,
-			      struct siginfo __user *infop,
-			      int __user *stat_addr, struct rusage __user *ru)
+static int wait_consider_task(struct wait_opts *wo, struct task_struct *parent,
+				int ptrace, struct task_struct *p)
 {
-	int ret = eligible_child(type, pid, options, p);
+	int ret = eligible_child(wo, p);
 	if (!ret)
 		return ret;
 
@@ -1478,17 +1488,17 @@
 		 * to look for security policy problems, rather
 		 * than for mysterious wait bugs.
 		 */
-		if (*notask_error)
-			*notask_error = ret;
+		if (wo->notask_error)
+			wo->notask_error = ret;
 		return 0;
 	}
 
-	if (likely(!ptrace) && unlikely(p->ptrace)) {
+	if (likely(!ptrace) && unlikely(task_ptrace(p))) {
 		/*
 		 * This child is hidden by ptrace.
 		 * We aren't allowed to see it now, but eventually we will.
 		 */
-		*notask_error = 0;
+		wo->notask_error = 0;
 		return 0;
 	}
 
@@ -1499,34 +1509,30 @@
 	 * We don't reap group leaders with subthreads.
 	 */
 	if (p->exit_state == EXIT_ZOMBIE && !delay_group_leader(p))
-		return wait_task_zombie(p, options, infop, stat_addr, ru);
+		return wait_task_zombie(wo, p);
 
 	/*
 	 * It's stopped or running now, so it might
 	 * later continue, exit, or stop again.
 	 */
-	*notask_error = 0;
+	wo->notask_error = 0;
 
 	if (task_stopped_code(p, ptrace))
-		return wait_task_stopped(ptrace, p, options,
-					 infop, stat_addr, ru);
+		return wait_task_stopped(wo, ptrace, p);
 
-	return wait_task_continued(p, options, infop, stat_addr, ru);
+	return wait_task_continued(wo, p);
 }
 
 /*
  * Do the work of do_wait() for one thread in the group, @tsk.
  *
- * -ECHILD should be in *@notask_error before the first call.
+ * -ECHILD should be in ->notask_error before the first call.
  * Returns nonzero for a final return, when we have unlocked tasklist_lock.
  * Returns zero if the search for a child should continue; then
- * *@notask_error is 0 if there were any eligible children,
+ * ->notask_error is 0 if there were any eligible children,
  * or another error from security_task_wait(), or still -ECHILD.
  */
-static int do_wait_thread(struct task_struct *tsk, int *notask_error,
-			  enum pid_type type, struct pid *pid, int options,
-			  struct siginfo __user *infop, int __user *stat_addr,
-			  struct rusage __user *ru)
+static int do_wait_thread(struct wait_opts *wo, struct task_struct *tsk)
 {
 	struct task_struct *p;
 
@@ -1535,9 +1541,7 @@
 		 * Do not consider detached threads.
 		 */
 		if (!task_detached(p)) {
-			int ret = wait_consider_task(tsk, 0, p, notask_error,
-						     type, pid, options,
-						     infop, stat_addr, ru);
+			int ret = wait_consider_task(wo, tsk, 0, p);
 			if (ret)
 				return ret;
 		}
@@ -1546,22 +1550,12 @@
 	return 0;
 }
 
-static int ptrace_do_wait(struct task_struct *tsk, int *notask_error,
-			  enum pid_type type, struct pid *pid, int options,
-			  struct siginfo __user *infop, int __user *stat_addr,
-			  struct rusage __user *ru)
+static int ptrace_do_wait(struct wait_opts *wo, struct task_struct *tsk)
 {
 	struct task_struct *p;
 
-	/*
-	 * Traditionally we see ptrace'd stopped tasks regardless of options.
-	 */
-	options |= WUNTRACED;
-
 	list_for_each_entry(p, &tsk->ptraced, ptrace_entry) {
-		int ret = wait_consider_task(tsk, 1, p, notask_error,
-					     type, pid, options,
-					     infop, stat_addr, ru);
+		int ret = wait_consider_task(wo, tsk, 1, p);
 		if (ret)
 			return ret;
 	}
@@ -1569,65 +1563,59 @@
 	return 0;
 }
 
-static long do_wait(enum pid_type type, struct pid *pid, int options,
-		    struct siginfo __user *infop, int __user *stat_addr,
-		    struct rusage __user *ru)
+static long do_wait(struct wait_opts *wo)
 {
 	DECLARE_WAITQUEUE(wait, current);
 	struct task_struct *tsk;
 	int retval;
 
-	trace_sched_process_wait(pid);
+	trace_sched_process_wait(wo->wo_pid);
 
 	add_wait_queue(&current->signal->wait_chldexit,&wait);
 repeat:
 	/*
 	 * If there is nothing that can match our critiera just get out.
-	 * We will clear @retval to zero if we see any child that might later
-	 * match our criteria, even if we are not able to reap it yet.
+	 * We will clear ->notask_error to zero if we see any child that
+	 * might later match our criteria, even if we are not able to reap
+	 * it yet.
 	 */
-	retval = -ECHILD;
-	if ((type < PIDTYPE_MAX) && (!pid || hlist_empty(&pid->tasks[type])))
-		goto end;
+	wo->notask_error = -ECHILD;
+	if ((wo->wo_type < PIDTYPE_MAX) &&
+	   (!wo->wo_pid || hlist_empty(&wo->wo_pid->tasks[wo->wo_type])))
+		goto notask;
 
-	current->state = TASK_INTERRUPTIBLE;
+	set_current_state(TASK_INTERRUPTIBLE);
 	read_lock(&tasklist_lock);
 	tsk = current;
 	do {
-		int tsk_result = do_wait_thread(tsk, &retval,
-						type, pid, options,
-						infop, stat_addr, ru);
-		if (!tsk_result)
-			tsk_result = ptrace_do_wait(tsk, &retval,
-						    type, pid, options,
-						    infop, stat_addr, ru);
-		if (tsk_result) {
-			/*
-			 * tasklist_lock is unlocked and we have a final result.
-			 */
-			retval = tsk_result;
+		retval = do_wait_thread(wo, tsk);
+		if (retval)
 			goto end;
-		}
 
-		if (options & __WNOTHREAD)
+		retval = ptrace_do_wait(wo, tsk);
+		if (retval)
+			goto end;
+
+		if (wo->wo_flags & __WNOTHREAD)
 			break;
-		tsk = next_thread(tsk);
-		BUG_ON(tsk->signal != current->signal);
-	} while (tsk != current);
+	} while_each_thread(current, tsk);
 	read_unlock(&tasklist_lock);
 
-	if (!retval && !(options & WNOHANG)) {
+notask:
+	retval = wo->notask_error;
+	if (!retval && !(wo->wo_flags & WNOHANG)) {
 		retval = -ERESTARTSYS;
 		if (!signal_pending(current)) {
 			schedule();
 			goto repeat;
 		}
 	}
-
 end:
-	current->state = TASK_RUNNING;
+	__set_current_state(TASK_RUNNING);
 	remove_wait_queue(&current->signal->wait_chldexit,&wait);
-	if (infop) {
+	if (wo->wo_info) {
+		struct siginfo __user *infop = wo->wo_info;
+
 		if (retval > 0)
 			retval = 0;
 		else {
@@ -1656,6 +1644,7 @@
 SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *,
 		infop, int, options, struct rusage __user *, ru)
 {
+	struct wait_opts wo;
 	struct pid *pid = NULL;
 	enum pid_type type;
 	long ret;
@@ -1685,7 +1674,14 @@
 
 	if (type < PIDTYPE_MAX)
 		pid = find_get_pid(upid);
-	ret = do_wait(type, pid, options, infop, NULL, ru);
+
+	wo.wo_type	= type;
+	wo.wo_pid	= pid;
+	wo.wo_flags	= options;
+	wo.wo_info	= infop;
+	wo.wo_stat	= NULL;
+	wo.wo_rusage	= ru;
+	ret = do_wait(&wo);
 	put_pid(pid);
 
 	/* avoid REGPARM breakage on x86: */
@@ -1696,6 +1692,7 @@
 SYSCALL_DEFINE4(wait4, pid_t, upid, int __user *, stat_addr,
 		int, options, struct rusage __user *, ru)
 {
+	struct wait_opts wo;
 	struct pid *pid = NULL;
 	enum pid_type type;
 	long ret;
@@ -1717,7 +1714,13 @@
 		pid = find_get_pid(upid);
 	}
 
-	ret = do_wait(type, pid, options | WEXITED, NULL, stat_addr, ru);
+	wo.wo_type	= type;
+	wo.wo_pid	= pid;
+	wo.wo_flags	= options | WEXITED;
+	wo.wo_info	= NULL;
+	wo.wo_stat	= stat_addr;
+	wo.wo_rusage	= ru;
+	ret = do_wait(&wo);
 	put_pid(pid);
 
 	/* avoid REGPARM breakage on x86: */
diff --git a/kernel/fork.c b/kernel/fork.c
index be022c2..467746b 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -1029,7 +1029,6 @@
 	p->vfork_done = NULL;
 	spin_lock_init(&p->alloc_lock);
 
-	clear_tsk_thread_flag(p, TIF_SIGPENDING);
 	init_sigpending(&p->pending);
 
 	p->utime = cputime_zero;
diff --git a/kernel/gcov/Kconfig b/kernel/gcov/Kconfig
new file mode 100644
index 0000000..22e9dcf
--- /dev/null
+++ b/kernel/gcov/Kconfig
@@ -0,0 +1,48 @@
+menu "GCOV-based kernel profiling"
+
+config GCOV_KERNEL
+	bool "Enable gcov-based kernel profiling"
+	depends on DEBUG_FS && CONSTRUCTORS
+	default n
+	---help---
+	This option enables gcov-based code profiling (e.g. for code coverage
+	measurements).
+
+	If unsure, say N.
+
+	Additionally specify CONFIG_GCOV_PROFILE_ALL=y to get profiling data
+	for the entire kernel. To enable profiling for specific files or
+	directories, add a line similar to the following to the respective
+	Makefile:
+
+	For a single file (e.g. main.o):
+	        GCOV_PROFILE_main.o := y
+
+	For all files in one directory:
+	        GCOV_PROFILE := y
+
+	To exclude files from being profiled even when CONFIG_GCOV_PROFILE_ALL
+	is specified, use:
+
+	        GCOV_PROFILE_main.o := n
+	and:
+	        GCOV_PROFILE := n
+
+	Note that the debugfs filesystem has to be mounted to access
+	profiling data.
+
+config GCOV_PROFILE_ALL
+	bool "Profile entire Kernel"
+	depends on GCOV_KERNEL
+	depends on S390 || X86
+	default n
+	---help---
+	This options activates profiling for the entire kernel.
+
+	If unsure, say N.
+
+	Note that a kernel compiled with profiling flags will be significantly
+	larger and run slower. Also be sure to exclude files from profiling
+	which are not linked to the kernel image to prevent linker errors.
+
+endmenu
diff --git a/kernel/gcov/Makefile b/kernel/gcov/Makefile
new file mode 100644
index 0000000..3f76100
--- /dev/null
+++ b/kernel/gcov/Makefile
@@ -0,0 +1,3 @@
+EXTRA_CFLAGS := -DSRCTREE='"$(srctree)"' -DOBJTREE='"$(objtree)"'
+
+obj-$(CONFIG_GCOV_KERNEL) := base.o fs.o gcc_3_4.o
diff --git a/kernel/gcov/base.c b/kernel/gcov/base.c
new file mode 100644
index 0000000..9b22d03
--- /dev/null
+++ b/kernel/gcov/base.c
@@ -0,0 +1,148 @@
+/*
+ *  This code maintains a list of active profiling data structures.
+ *
+ *    Copyright IBM Corp. 2009
+ *    Author(s): Peter Oberparleiter <oberpar@linux.vnet.ibm.com>
+ *
+ *    Uses gcc-internal data definitions.
+ *    Based on the gcov-kernel patch by:
+ *		 Hubertus Franke <frankeh@us.ibm.com>
+ *		 Nigel Hinds <nhinds@us.ibm.com>
+ *		 Rajan Ravindran <rajancr@us.ibm.com>
+ *		 Peter Oberparleiter <oberpar@linux.vnet.ibm.com>
+ *		 Paul Larson
+ */
+
+#define pr_fmt(fmt)	"gcov: " fmt
+
+#include <linux/init.h>
+#include <linux/module.h>
+#include <linux/mutex.h>
+#include "gcov.h"
+
+static struct gcov_info *gcov_info_head;
+static int gcov_events_enabled;
+static DEFINE_MUTEX(gcov_lock);
+
+/*
+ * __gcov_init is called by gcc-generated constructor code for each object
+ * file compiled with -fprofile-arcs.
+ */
+void __gcov_init(struct gcov_info *info)
+{
+	static unsigned int gcov_version;
+
+	mutex_lock(&gcov_lock);
+	if (gcov_version == 0) {
+		gcov_version = info->version;
+		/*
+		 * Printing gcc's version magic may prove useful for debugging
+		 * incompatibility reports.
+		 */
+		pr_info("version magic: 0x%x\n", gcov_version);
+	}
+	/*
+	 * Add new profiling data structure to list and inform event
+	 * listener.
+	 */
+	info->next = gcov_info_head;
+	gcov_info_head = info;
+	if (gcov_events_enabled)
+		gcov_event(GCOV_ADD, info);
+	mutex_unlock(&gcov_lock);
+}
+EXPORT_SYMBOL(__gcov_init);
+
+/*
+ * These functions may be referenced by gcc-generated profiling code but serve
+ * no function for kernel profiling.
+ */
+void __gcov_flush(void)
+{
+	/* Unused. */
+}
+EXPORT_SYMBOL(__gcov_flush);
+
+void __gcov_merge_add(gcov_type *counters, unsigned int n_counters)
+{
+	/* Unused. */
+}
+EXPORT_SYMBOL(__gcov_merge_add);
+
+void __gcov_merge_single(gcov_type *counters, unsigned int n_counters)
+{
+	/* Unused. */
+}
+EXPORT_SYMBOL(__gcov_merge_single);
+
+void __gcov_merge_delta(gcov_type *counters, unsigned int n_counters)
+{
+	/* Unused. */
+}
+EXPORT_SYMBOL(__gcov_merge_delta);
+
+/**
+ * gcov_enable_events - enable event reporting through gcov_event()
+ *
+ * Turn on reporting of profiling data load/unload-events through the
+ * gcov_event() callback. Also replay all previous events once. This function
+ * is needed because some events are potentially generated too early for the
+ * callback implementation to handle them initially.
+ */
+void gcov_enable_events(void)
+{
+	struct gcov_info *info;
+
+	mutex_lock(&gcov_lock);
+	gcov_events_enabled = 1;
+	/* Perform event callback for previously registered entries. */
+	for (info = gcov_info_head; info; info = info->next)
+		gcov_event(GCOV_ADD, info);
+	mutex_unlock(&gcov_lock);
+}
+
+#ifdef CONFIG_MODULES
+static inline int within(void *addr, void *start, unsigned long size)
+{
+	return ((addr >= start) && (addr < start + size));
+}
+
+/* Update list and generate events when modules are unloaded. */
+static int gcov_module_notifier(struct notifier_block *nb, unsigned long event,
+				void *data)
+{
+	struct module *mod = data;
+	struct gcov_info *info;
+	struct gcov_info *prev;
+
+	if (event != MODULE_STATE_GOING)
+		return NOTIFY_OK;
+	mutex_lock(&gcov_lock);
+	prev = NULL;
+	/* Remove entries located in module from linked list. */
+	for (info = gcov_info_head; info; info = info->next) {
+		if (within(info, mod->module_core, mod->core_size)) {
+			if (prev)
+				prev->next = info->next;
+			else
+				gcov_info_head = info->next;
+			if (gcov_events_enabled)
+				gcov_event(GCOV_REMOVE, info);
+		} else
+			prev = info;
+	}
+	mutex_unlock(&gcov_lock);
+
+	return NOTIFY_OK;
+}
+
+static struct notifier_block gcov_nb = {
+	.notifier_call	= gcov_module_notifier,
+};
+
+static int __init gcov_init(void)
+{
+	return register_module_notifier(&gcov_nb);
+}
+device_initcall(gcov_init);
+#endif /* CONFIG_MODULES */
diff --git a/kernel/gcov/fs.c b/kernel/gcov/fs.c
new file mode 100644
index 0000000..ef3c3f8
--- /dev/null
+++ b/kernel/gcov/fs.c
@@ -0,0 +1,673 @@
+/*
+ *  This code exports profiling data as debugfs files to userspace.
+ *
+ *    Copyright IBM Corp. 2009
+ *    Author(s): Peter Oberparleiter <oberpar@linux.vnet.ibm.com>
+ *
+ *    Uses gcc-internal data definitions.
+ *    Based on the gcov-kernel patch by:
+ *		 Hubertus Franke <frankeh@us.ibm.com>
+ *		 Nigel Hinds <nhinds@us.ibm.com>
+ *		 Rajan Ravindran <rajancr@us.ibm.com>
+ *		 Peter Oberparleiter <oberpar@linux.vnet.ibm.com>
+ *		 Paul Larson
+ *		 Yi CDL Yang
+ */
+
+#define pr_fmt(fmt)	"gcov: " fmt
+
+#include <linux/init.h>
+#include <linux/module.h>
+#include <linux/debugfs.h>
+#include <linux/fs.h>
+#include <linux/list.h>
+#include <linux/string.h>
+#include <linux/slab.h>
+#include <linux/mutex.h>
+#include <linux/seq_file.h>
+#include "gcov.h"
+
+/**
+ * struct gcov_node - represents a debugfs entry
+ * @list: list head for child node list
+ * @children: child nodes
+ * @all: list head for list of all nodes
+ * @parent: parent node
+ * @info: associated profiling data structure if not a directory
+ * @ghost: when an object file containing profiling data is unloaded we keep a
+ *         copy of the profiling data here to allow collecting coverage data
+ *         for cleanup code. Such a node is called a "ghost".
+ * @dentry: main debugfs entry, either a directory or data file
+ * @links: associated symbolic links
+ * @name: data file basename
+ *
+ * struct gcov_node represents an entity within the gcov/ subdirectory
+ * of debugfs. There are directory and data file nodes. The latter represent
+ * the actual synthesized data file plus any associated symbolic links which
+ * are needed by the gcov tool to work correctly.
+ */
+struct gcov_node {
+	struct list_head list;
+	struct list_head children;
+	struct list_head all;
+	struct gcov_node *parent;
+	struct gcov_info *info;
+	struct gcov_info *ghost;
+	struct dentry *dentry;
+	struct dentry **links;
+	char name[0];
+};
+
+static const char objtree[] = OBJTREE;
+static const char srctree[] = SRCTREE;
+static struct gcov_node root_node;
+static struct dentry *reset_dentry;
+static LIST_HEAD(all_head);
+static DEFINE_MUTEX(node_lock);
+
+/* If non-zero, keep copies of profiling data for unloaded modules. */
+static int gcov_persist = 1;
+
+static int __init gcov_persist_setup(char *str)
+{
+	unsigned long val;
+
+	if (strict_strtoul(str, 0, &val)) {
+		pr_warning("invalid gcov_persist parameter '%s'\n", str);
+		return 0;
+	}
+	gcov_persist = val;
+	pr_info("setting gcov_persist to %d\n", gcov_persist);
+
+	return 1;
+}
+__setup("gcov_persist=", gcov_persist_setup);
+
+/*
+ * seq_file.start() implementation for gcov data files. Note that the
+ * gcov_iterator interface is designed to be more restrictive than seq_file
+ * (no start from arbitrary position, etc.), to simplify the iterator
+ * implementation.
+ */
+static void *gcov_seq_start(struct seq_file *seq, loff_t *pos)
+{
+	loff_t i;
+
+	gcov_iter_start(seq->private);
+	for (i = 0; i < *pos; i++) {
+		if (gcov_iter_next(seq->private))
+			return NULL;
+	}
+	return seq->private;
+}
+
+/* seq_file.next() implementation for gcov data files. */
+static void *gcov_seq_next(struct seq_file *seq, void *data, loff_t *pos)
+{
+	struct gcov_iterator *iter = data;
+
+	if (gcov_iter_next(iter))
+		return NULL;
+	(*pos)++;
+
+	return iter;
+}
+
+/* seq_file.show() implementation for gcov data files. */
+static int gcov_seq_show(struct seq_file *seq, void *data)
+{
+	struct gcov_iterator *iter = data;
+
+	if (gcov_iter_write(iter, seq))
+		return -EINVAL;
+	return 0;
+}
+
+static void gcov_seq_stop(struct seq_file *seq, void *data)
+{
+	/* Unused. */
+}
+
+static const struct seq_operations gcov_seq_ops = {
+	.start	= gcov_seq_start,
+	.next	= gcov_seq_next,
+	.show	= gcov_seq_show,
+	.stop	= gcov_seq_stop,
+};
+
+/*
+ * Return the profiling data set for a given node. This can either be the
+ * original profiling data structure or a duplicate (also called "ghost")
+ * in case the associated object file has been unloaded.
+ */
+static struct gcov_info *get_node_info(struct gcov_node *node)
+{
+	if (node->info)
+		return node->info;
+
+	return node->ghost;
+}
+
+/*
+ * open() implementation for gcov data files. Create a copy of the profiling
+ * data set and initialize the iterator and seq_file interface.
+ */
+static int gcov_seq_open(struct inode *inode, struct file *file)
+{
+	struct gcov_node *node = inode->i_private;
+	struct gcov_iterator *iter;
+	struct seq_file *seq;
+	struct gcov_info *info;
+	int rc = -ENOMEM;
+
+	mutex_lock(&node_lock);
+	/*
+	 * Read from a profiling data copy to minimize reference tracking
+	 * complexity and concurrent access.
+	 */
+	info = gcov_info_dup(get_node_info(node));
+	if (!info)
+		goto out_unlock;
+	iter = gcov_iter_new(info);
+	if (!iter)
+		goto err_free_info;
+	rc = seq_open(file, &gcov_seq_ops);
+	if (rc)
+		goto err_free_iter_info;
+	seq = file->private_data;
+	seq->private = iter;
+out_unlock:
+	mutex_unlock(&node_lock);
+	return rc;
+
+err_free_iter_info:
+	gcov_iter_free(iter);
+err_free_info:
+	gcov_info_free(info);
+	goto out_unlock;
+}
+
+/*
+ * release() implementation for gcov data files. Release resources allocated
+ * by open().
+ */
+static int gcov_seq_release(struct inode *inode, struct file *file)
+{
+	struct gcov_iterator *iter;
+	struct gcov_info *info;
+	struct seq_file *seq;
+
+	seq = file->private_data;
+	iter = seq->private;
+	info = gcov_iter_get_info(iter);
+	gcov_iter_free(iter);
+	gcov_info_free(info);
+	seq_release(inode, file);
+
+	return 0;
+}
+
+/*
+ * Find a node by the associated data file name. Needs to be called with
+ * node_lock held.
+ */
+static struct gcov_node *get_node_by_name(const char *name)
+{
+	struct gcov_node *node;
+	struct gcov_info *info;
+
+	list_for_each_entry(node, &all_head, all) {
+		info = get_node_info(node);
+		if (info && (strcmp(info->filename, name) == 0))
+			return node;
+	}
+
+	return NULL;
+}
+
+static void remove_node(struct gcov_node *node);
+
+/*
+ * write() implementation for gcov data files. Reset profiling data for the
+ * associated file. If the object file has been unloaded (i.e. this is
+ * a "ghost" node), remove the debug fs node as well.
+ */
+static ssize_t gcov_seq_write(struct file *file, const char __user *addr,
+			      size_t len, loff_t *pos)
+{
+	struct seq_file *seq;
+	struct gcov_info *info;
+	struct gcov_node *node;
+
+	seq = file->private_data;
+	info = gcov_iter_get_info(seq->private);
+	mutex_lock(&node_lock);
+	node = get_node_by_name(info->filename);
+	if (node) {
+		/* Reset counts or remove node for unloaded modules. */
+		if (node->ghost)
+			remove_node(node);
+		else
+			gcov_info_reset(node->info);
+	}
+	/* Reset counts for open file. */
+	gcov_info_reset(info);
+	mutex_unlock(&node_lock);
+
+	return len;
+}
+
+/*
+ * Given a string <path> representing a file path of format:
+ *   path/to/file.gcda
+ * construct and return a new string:
+ *   <dir/>path/to/file.<ext>
+ */
+static char *link_target(const char *dir, const char *path, const char *ext)
+{
+	char *target;
+	char *old_ext;
+	char *copy;
+
+	copy = kstrdup(path, GFP_KERNEL);
+	if (!copy)
+		return NULL;
+	old_ext = strrchr(copy, '.');
+	if (old_ext)
+		*old_ext = '\0';
+	if (dir)
+		target = kasprintf(GFP_KERNEL, "%s/%s.%s", dir, copy, ext);
+	else
+		target = kasprintf(GFP_KERNEL, "%s.%s", copy, ext);
+	kfree(copy);
+
+	return target;
+}
+
+/*
+ * Construct a string representing the symbolic link target for the given
+ * gcov data file name and link type. Depending on the link type and the
+ * location of the data file, the link target can either point to a
+ * subdirectory of srctree, objtree or in an external location.
+ */
+static char *get_link_target(const char *filename, const struct gcov_link *ext)
+{
+	const char *rel;
+	char *result;
+
+	if (strncmp(filename, objtree, strlen(objtree)) == 0) {
+		rel = filename + strlen(objtree) + 1;
+		if (ext->dir == SRC_TREE)
+			result = link_target(srctree, rel, ext->ext);
+		else
+			result = link_target(objtree, rel, ext->ext);
+	} else {
+		/* External compilation. */
+		result = link_target(NULL, filename, ext->ext);
+	}
+
+	return result;
+}
+
+#define SKEW_PREFIX	".tmp_"
+
+/*
+ * For a filename .tmp_filename.ext return filename.ext. Needed to compensate
+ * for filename skewing caused by the mod-versioning mechanism.
+ */
+static const char *deskew(const char *basename)
+{
+	if (strncmp(basename, SKEW_PREFIX, sizeof(SKEW_PREFIX) - 1) == 0)
+		return basename + sizeof(SKEW_PREFIX) - 1;
+	return basename;
+}
+
+/*
+ * Create links to additional files (usually .c and .gcno files) which the
+ * gcov tool expects to find in the same directory as the gcov data file.
+ */
+static void add_links(struct gcov_node *node, struct dentry *parent)
+{
+	char *basename;
+	char *target;
+	int num;
+	int i;
+
+	for (num = 0; gcov_link[num].ext; num++)
+		/* Nothing. */;
+	node->links = kcalloc(num, sizeof(struct dentry *), GFP_KERNEL);
+	if (!node->links)
+		return;
+	for (i = 0; i < num; i++) {
+		target = get_link_target(get_node_info(node)->filename,
+					 &gcov_link[i]);
+		if (!target)
+			goto out_err;
+		basename = strrchr(target, '/');
+		if (!basename)
+			goto out_err;
+		basename++;
+		node->links[i] = debugfs_create_symlink(deskew(basename),
+							parent,	target);
+		if (!node->links[i])
+			goto out_err;
+		kfree(target);
+	}
+
+	return;
+out_err:
+	kfree(target);
+	while (i-- > 0)
+		debugfs_remove(node->links[i]);
+	kfree(node->links);
+	node->links = NULL;
+}
+
+static const struct file_operations gcov_data_fops = {
+	.open		= gcov_seq_open,
+	.release	= gcov_seq_release,
+	.read		= seq_read,
+	.llseek		= seq_lseek,
+	.write		= gcov_seq_write,
+};
+
+/* Basic initialization of a new node. */
+static void init_node(struct gcov_node *node, struct gcov_info *info,
+		      const char *name, struct gcov_node *parent)
+{
+	INIT_LIST_HEAD(&node->list);
+	INIT_LIST_HEAD(&node->children);
+	INIT_LIST_HEAD(&node->all);
+	node->info = info;
+	node->parent = parent;
+	if (name)
+		strcpy(node->name, name);
+}
+
+/*
+ * Create a new node and associated debugfs entry. Needs to be called with
+ * node_lock held.
+ */
+static struct gcov_node *new_node(struct gcov_node *parent,
+				  struct gcov_info *info, const char *name)
+{
+	struct gcov_node *node;
+
+	node = kzalloc(sizeof(struct gcov_node) + strlen(name) + 1, GFP_KERNEL);
+	if (!node) {
+		pr_warning("out of memory\n");
+		return NULL;
+	}
+	init_node(node, info, name, parent);
+	/* Differentiate between gcov data file nodes and directory nodes. */
+	if (info) {
+		node->dentry = debugfs_create_file(deskew(node->name), 0600,
+					parent->dentry, node, &gcov_data_fops);
+	} else
+		node->dentry = debugfs_create_dir(node->name, parent->dentry);
+	if (!node->dentry) {
+		pr_warning("could not create file\n");
+		kfree(node);
+		return NULL;
+	}
+	if (info)
+		add_links(node, parent->dentry);
+	list_add(&node->list, &parent->children);
+	list_add(&node->all, &all_head);
+
+	return node;
+}
+
+/* Remove symbolic links associated with node. */
+static void remove_links(struct gcov_node *node)
+{
+	int i;
+
+	if (!node->links)
+		return;
+	for (i = 0; gcov_link[i].ext; i++)
+		debugfs_remove(node->links[i]);
+	kfree(node->links);
+	node->links = NULL;
+}
+
+/*
+ * Remove node from all lists and debugfs and release associated resources.
+ * Needs to be called with node_lock held.
+ */
+static void release_node(struct gcov_node *node)
+{
+	list_del(&node->list);
+	list_del(&node->all);
+	debugfs_remove(node->dentry);
+	remove_links(node);
+	if (node->ghost)
+		gcov_info_free(node->ghost);
+	kfree(node);
+}
+
+/* Release node and empty parents. Needs to be called with node_lock held. */
+static void remove_node(struct gcov_node *node)
+{
+	struct gcov_node *parent;
+
+	while ((node != &root_node) && list_empty(&node->children)) {
+		parent = node->parent;
+		release_node(node);
+		node = parent;
+	}
+}
+
+/*
+ * Find child node with given basename. Needs to be called with node_lock
+ * held.
+ */
+static struct gcov_node *get_child_by_name(struct gcov_node *parent,
+					   const char *name)
+{
+	struct gcov_node *node;
+
+	list_for_each_entry(node, &parent->children, list) {
+		if (strcmp(node->name, name) == 0)
+			return node;
+	}
+
+	return NULL;
+}
+
+/*
+ * write() implementation for reset file. Reset all profiling data to zero
+ * and remove ghost nodes.
+ */
+static ssize_t reset_write(struct file *file, const char __user *addr,
+			   size_t len, loff_t *pos)
+{
+	struct gcov_node *node;
+
+	mutex_lock(&node_lock);
+restart:
+	list_for_each_entry(node, &all_head, all) {
+		if (node->info)
+			gcov_info_reset(node->info);
+		else if (list_empty(&node->children)) {
+			remove_node(node);
+			/* Several nodes may have gone - restart loop. */
+			goto restart;
+		}
+	}
+	mutex_unlock(&node_lock);
+
+	return len;
+}
+
+/* read() implementation for reset file. Unused. */
+static ssize_t reset_read(struct file *file, char __user *addr, size_t len,
+			  loff_t *pos)
+{
+	/* Allow read operation so that a recursive copy won't fail. */
+	return 0;
+}
+
+static const struct file_operations gcov_reset_fops = {
+	.write	= reset_write,
+	.read	= reset_read,
+};
+
+/*
+ * Create a node for a given profiling data set and add it to all lists and
+ * debugfs. Needs to be called with node_lock held.
+ */
+static void add_node(struct gcov_info *info)
+{
+	char *filename;
+	char *curr;
+	char *next;
+	struct gcov_node *parent;
+	struct gcov_node *node;
+
+	filename = kstrdup(info->filename, GFP_KERNEL);
+	if (!filename)
+		return;
+	parent = &root_node;
+	/* Create directory nodes along the path. */
+	for (curr = filename; (next = strchr(curr, '/')); curr = next + 1) {
+		if (curr == next)
+			continue;
+		*next = 0;
+		if (strcmp(curr, ".") == 0)
+			continue;
+		if (strcmp(curr, "..") == 0) {
+			if (!parent->parent)
+				goto err_remove;
+			parent = parent->parent;
+			continue;
+		}
+		node = get_child_by_name(parent, curr);
+		if (!node) {
+			node = new_node(parent, NULL, curr);
+			if (!node)
+				goto err_remove;
+		}
+		parent = node;
+	}
+	/* Create file node. */
+	node = new_node(parent, info, curr);
+	if (!node)
+		goto err_remove;
+out:
+	kfree(filename);
+	return;
+
+err_remove:
+	remove_node(parent);
+	goto out;
+}
+
+/*
+ * The profiling data set associated with this node is being unloaded. Store a
+ * copy of the profiling data and turn this node into a "ghost".
+ */
+static int ghost_node(struct gcov_node *node)
+{
+	node->ghost = gcov_info_dup(node->info);
+	if (!node->ghost) {
+		pr_warning("could not save data for '%s' (out of memory)\n",
+			   node->info->filename);
+		return -ENOMEM;
+	}
+	node->info = NULL;
+
+	return 0;
+}
+
+/*
+ * Profiling data for this node has been loaded again. Add profiling data
+ * from previous instantiation and turn this node into a regular node.
+ */
+static void revive_node(struct gcov_node *node, struct gcov_info *info)
+{
+	if (gcov_info_is_compatible(node->ghost, info))
+		gcov_info_add(info, node->ghost);
+	else {
+		pr_warning("discarding saved data for '%s' (version changed)\n",
+			   info->filename);
+	}
+	gcov_info_free(node->ghost);
+	node->ghost = NULL;
+	node->info = info;
+}
+
+/*
+ * Callback to create/remove profiling files when code compiled with
+ * -fprofile-arcs is loaded/unloaded.
+ */
+void gcov_event(enum gcov_action action, struct gcov_info *info)
+{
+	struct gcov_node *node;
+
+	mutex_lock(&node_lock);
+	node = get_node_by_name(info->filename);
+	switch (action) {
+	case GCOV_ADD:
+		/* Add new node or revive ghost. */
+		if (!node) {
+			add_node(info);
+			break;
+		}
+		if (gcov_persist)
+			revive_node(node, info);
+		else {
+			pr_warning("could not add '%s' (already exists)\n",
+				   info->filename);
+		}
+		break;
+	case GCOV_REMOVE:
+		/* Remove node or turn into ghost. */
+		if (!node) {
+			pr_warning("could not remove '%s' (not found)\n",
+				   info->filename);
+			break;
+		}
+		if (gcov_persist) {
+			if (!ghost_node(node))
+				break;
+		}
+		remove_node(node);
+		break;
+	}
+	mutex_unlock(&node_lock);
+}
+
+/* Create debugfs entries. */
+static __init int gcov_fs_init(void)
+{
+	int rc = -EIO;
+
+	init_node(&root_node, NULL, NULL, NULL);
+	/*
+	 * /sys/kernel/debug/gcov will be parent for the reset control file
+	 * and all profiling files.
+	 */
+	root_node.dentry = debugfs_create_dir("gcov", NULL);
+	if (!root_node.dentry)
+		goto err_remove;
+	/*
+	 * Create reset file which resets all profiling counts when written
+	 * to.
+	 */
+	reset_dentry = debugfs_create_file("reset", 0600, root_node.dentry,
+					   NULL, &gcov_reset_fops);
+	if (!reset_dentry)
+		goto err_remove;
+	/* Replay previous events to get our fs hierarchy up-to-date. */
+	gcov_enable_events();
+	return 0;
+
+err_remove:
+	pr_err("init failed\n");
+	if (root_node.dentry)
+		debugfs_remove(root_node.dentry);
+
+	return rc;
+}
+device_initcall(gcov_fs_init);
diff --git a/kernel/gcov/gcc_3_4.c b/kernel/gcov/gcc_3_4.c
new file mode 100644
index 0000000..ae5bb42
--- /dev/null
+++ b/kernel/gcov/gcc_3_4.c
@@ -0,0 +1,447 @@
+/*
+ *  This code provides functions to handle gcc's profiling data format
+ *  introduced with gcc 3.4. Future versions of gcc may change the gcov
+ *  format (as happened before), so all format-specific information needs
+ *  to be kept modular and easily exchangeable.
+ *
+ *  This file is based on gcc-internal definitions. Functions and data
+ *  structures are defined to be compatible with gcc counterparts.
+ *  For a better understanding, refer to gcc source: gcc/gcov-io.h.
+ *
+ *    Copyright IBM Corp. 2009
+ *    Author(s): Peter Oberparleiter <oberpar@linux.vnet.ibm.com>
+ *
+ *    Uses gcc-internal data definitions.
+ */
+
+#include <linux/errno.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+#include <linux/seq_file.h>
+#include <linux/vmalloc.h>
+#include "gcov.h"
+
+/* Symbolic links to be created for each profiling data file. */
+const struct gcov_link gcov_link[] = {
+	{ OBJ_TREE, "gcno" },	/* Link to .gcno file in $(objtree). */
+	{ 0, NULL},
+};
+
+/*
+ * Determine whether a counter is active. Based on gcc magic. Doesn't change
+ * at run-time.
+ */
+static int counter_active(struct gcov_info *info, unsigned int type)
+{
+	return (1 << type) & info->ctr_mask;
+}
+
+/* Determine number of active counters. Based on gcc magic. */
+static unsigned int num_counter_active(struct gcov_info *info)
+{
+	unsigned int i;
+	unsigned int result = 0;
+
+	for (i = 0; i < GCOV_COUNTERS; i++) {
+		if (counter_active(info, i))
+			result++;
+	}
+	return result;
+}
+
+/**
+ * gcov_info_reset - reset profiling data to zero
+ * @info: profiling data set
+ */
+void gcov_info_reset(struct gcov_info *info)
+{
+	unsigned int active = num_counter_active(info);
+	unsigned int i;
+
+	for (i = 0; i < active; i++) {
+		memset(info->counts[i].values, 0,
+		       info->counts[i].num * sizeof(gcov_type));
+	}
+}
+
+/**
+ * gcov_info_is_compatible - check if profiling data can be added
+ * @info1: first profiling data set
+ * @info2: second profiling data set
+ *
+ * Returns non-zero if profiling data can be added, zero otherwise.
+ */
+int gcov_info_is_compatible(struct gcov_info *info1, struct gcov_info *info2)
+{
+	return (info1->stamp == info2->stamp);
+}
+
+/**
+ * gcov_info_add - add up profiling data
+ * @dest: profiling data set to which data is added
+ * @source: profiling data set which is added
+ *
+ * Adds profiling counts of @source to @dest.
+ */
+void gcov_info_add(struct gcov_info *dest, struct gcov_info *source)
+{
+	unsigned int i;
+	unsigned int j;
+
+	for (i = 0; i < num_counter_active(dest); i++) {
+		for (j = 0; j < dest->counts[i].num; j++) {
+			dest->counts[i].values[j] +=
+				source->counts[i].values[j];
+		}
+	}
+}
+
+/* Get size of function info entry. Based on gcc magic. */
+static size_t get_fn_size(struct gcov_info *info)
+{
+	size_t size;
+
+	size = sizeof(struct gcov_fn_info) + num_counter_active(info) *
+	       sizeof(unsigned int);
+	if (__alignof__(struct gcov_fn_info) > sizeof(unsigned int))
+		size = ALIGN(size, __alignof__(struct gcov_fn_info));
+	return size;
+}
+
+/* Get address of function info entry. Based on gcc magic. */
+static struct gcov_fn_info *get_fn_info(struct gcov_info *info, unsigned int fn)
+{
+	return (struct gcov_fn_info *)
+		((char *) info->functions + fn * get_fn_size(info));
+}
+
+/**
+ * gcov_info_dup - duplicate profiling data set
+ * @info: profiling data set to duplicate
+ *
+ * Return newly allocated duplicate on success, %NULL on error.
+ */
+struct gcov_info *gcov_info_dup(struct gcov_info *info)
+{
+	struct gcov_info *dup;
+	unsigned int i;
+	unsigned int active;
+
+	/* Duplicate gcov_info. */
+	active = num_counter_active(info);
+	dup = kzalloc(sizeof(struct gcov_info) +
+		      sizeof(struct gcov_ctr_info) * active, GFP_KERNEL);
+	if (!dup)
+		return NULL;
+	dup->version		= info->version;
+	dup->stamp		= info->stamp;
+	dup->n_functions	= info->n_functions;
+	dup->ctr_mask		= info->ctr_mask;
+	/* Duplicate filename. */
+	dup->filename		= kstrdup(info->filename, GFP_KERNEL);
+	if (!dup->filename)
+		goto err_free;
+	/* Duplicate table of functions. */
+	dup->functions = kmemdup(info->functions, info->n_functions *
+				 get_fn_size(info), GFP_KERNEL);
+	if (!dup->functions)
+		goto err_free;
+	/* Duplicate counter arrays. */
+	for (i = 0; i < active ; i++) {
+		struct gcov_ctr_info *ctr = &info->counts[i];
+		size_t size = ctr->num * sizeof(gcov_type);
+
+		dup->counts[i].num = ctr->num;
+		dup->counts[i].merge = ctr->merge;
+		dup->counts[i].values = vmalloc(size);
+		if (!dup->counts[i].values)
+			goto err_free;
+		memcpy(dup->counts[i].values, ctr->values, size);
+	}
+	return dup;
+
+err_free:
+	gcov_info_free(dup);
+	return NULL;
+}
+
+/**
+ * gcov_info_free - release memory for profiling data set duplicate
+ * @info: profiling data set duplicate to free
+ */
+void gcov_info_free(struct gcov_info *info)
+{
+	unsigned int active = num_counter_active(info);
+	unsigned int i;
+
+	for (i = 0; i < active ; i++)
+		vfree(info->counts[i].values);
+	kfree(info->functions);
+	kfree(info->filename);
+	kfree(info);
+}
+
+/**
+ * struct type_info - iterator helper array
+ * @ctr_type: counter type
+ * @offset: index of the first value of the current function for this type
+ *
+ * This array is needed to convert the in-memory data format into the in-file
+ * data format:
+ *
+ * In-memory:
+ *   for each counter type
+ *     for each function
+ *       values
+ *
+ * In-file:
+ *   for each function
+ *     for each counter type
+ *       values
+ *
+ * See gcc source gcc/gcov-io.h for more information on data organization.
+ */
+struct type_info {
+	int ctr_type;
+	unsigned int offset;
+};
+
+/**
+ * struct gcov_iterator - specifies current file position in logical records
+ * @info: associated profiling data
+ * @record: record type
+ * @function: function number
+ * @type: counter type
+ * @count: index into values array
+ * @num_types: number of counter types
+ * @type_info: helper array to get values-array offset for current function
+ */
+struct gcov_iterator {
+	struct gcov_info *info;
+
+	int record;
+	unsigned int function;
+	unsigned int type;
+	unsigned int count;
+
+	int num_types;
+	struct type_info type_info[0];
+};
+
+static struct gcov_fn_info *get_func(struct gcov_iterator *iter)
+{
+	return get_fn_info(iter->info, iter->function);
+}
+
+static struct type_info *get_type(struct gcov_iterator *iter)
+{
+	return &iter->type_info[iter->type];
+}
+
+/**
+ * gcov_iter_new - allocate and initialize profiling data iterator
+ * @info: profiling data set to be iterated
+ *
+ * Return file iterator on success, %NULL otherwise.
+ */
+struct gcov_iterator *gcov_iter_new(struct gcov_info *info)
+{
+	struct gcov_iterator *iter;
+
+	iter = kzalloc(sizeof(struct gcov_iterator) +
+		       num_counter_active(info) * sizeof(struct type_info),
+		       GFP_KERNEL);
+	if (iter)
+		iter->info = info;
+
+	return iter;
+}
+
+/**
+ * gcov_iter_free - release memory for iterator
+ * @iter: file iterator to free
+ */
+void gcov_iter_free(struct gcov_iterator *iter)
+{
+	kfree(iter);
+}
+
+/**
+ * gcov_iter_get_info - return profiling data set for given file iterator
+ * @iter: file iterator
+ */
+struct gcov_info *gcov_iter_get_info(struct gcov_iterator *iter)
+{
+	return iter->info;
+}
+
+/**
+ * gcov_iter_start - reset file iterator to starting position
+ * @iter: file iterator
+ */
+void gcov_iter_start(struct gcov_iterator *iter)
+{
+	int i;
+
+	iter->record = 0;
+	iter->function = 0;
+	iter->type = 0;
+	iter->count = 0;
+	iter->num_types = 0;
+	for (i = 0; i < GCOV_COUNTERS; i++) {
+		if (counter_active(iter->info, i)) {
+			iter->type_info[iter->num_types].ctr_type = i;
+			iter->type_info[iter->num_types++].offset = 0;
+		}
+	}
+}
+
+/* Mapping of logical record number to actual file content. */
+#define RECORD_FILE_MAGIC	0
+#define RECORD_GCOV_VERSION	1
+#define RECORD_TIME_STAMP	2
+#define RECORD_FUNCTION_TAG	3
+#define RECORD_FUNCTON_TAG_LEN	4
+#define RECORD_FUNCTION_IDENT	5
+#define RECORD_FUNCTION_CHECK	6
+#define RECORD_COUNT_TAG	7
+#define RECORD_COUNT_LEN	8
+#define RECORD_COUNT		9
+
+/**
+ * gcov_iter_next - advance file iterator to next logical record
+ * @iter: file iterator
+ *
+ * Return zero if new position is valid, non-zero if iterator has reached end.
+ */
+int gcov_iter_next(struct gcov_iterator *iter)
+{
+	switch (iter->record) {
+	case RECORD_FILE_MAGIC:
+	case RECORD_GCOV_VERSION:
+	case RECORD_FUNCTION_TAG:
+	case RECORD_FUNCTON_TAG_LEN:
+	case RECORD_FUNCTION_IDENT:
+	case RECORD_COUNT_TAG:
+		/* Advance to next record */
+		iter->record++;
+		break;
+	case RECORD_COUNT:
+		/* Advance to next count */
+		iter->count++;
+		/* fall through */
+	case RECORD_COUNT_LEN:
+		if (iter->count < get_func(iter)->n_ctrs[iter->type]) {
+			iter->record = 9;
+			break;
+		}
+		/* Advance to next counter type */
+		get_type(iter)->offset += iter->count;
+		iter->count = 0;
+		iter->type++;
+		/* fall through */
+	case RECORD_FUNCTION_CHECK:
+		if (iter->type < iter->num_types) {
+			iter->record = 7;
+			break;
+		}
+		/* Advance to next function */
+		iter->type = 0;
+		iter->function++;
+		/* fall through */
+	case RECORD_TIME_STAMP:
+		if (iter->function < iter->info->n_functions)
+			iter->record = 3;
+		else
+			iter->record = -1;
+		break;
+	}
+	/* Check for EOF. */
+	if (iter->record == -1)
+		return -EINVAL;
+	else
+		return 0;
+}
+
+/**
+ * seq_write_gcov_u32 - write 32 bit number in gcov format to seq_file
+ * @seq: seq_file handle
+ * @v: value to be stored
+ *
+ * Number format defined by gcc: numbers are recorded in the 32 bit
+ * unsigned binary form of the endianness of the machine generating the
+ * file.
+ */
+static int seq_write_gcov_u32(struct seq_file *seq, u32 v)
+{
+	return seq_write(seq, &v, sizeof(v));
+}
+
+/**
+ * seq_write_gcov_u64 - write 64 bit number in gcov format to seq_file
+ * @seq: seq_file handle
+ * @v: value to be stored
+ *
+ * Number format defined by gcc: numbers are recorded in the 32 bit
+ * unsigned binary form of the endianness of the machine generating the
+ * file. 64 bit numbers are stored as two 32 bit numbers, the low part
+ * first.
+ */
+static int seq_write_gcov_u64(struct seq_file *seq, u64 v)
+{
+	u32 data[2];
+
+	data[0] = (v & 0xffffffffUL);
+	data[1] = (v >> 32);
+	return seq_write(seq, data, sizeof(data));
+}
+
+/**
+ * gcov_iter_write - write data for current pos to seq_file
+ * @iter: file iterator
+ * @seq: seq_file handle
+ *
+ * Return zero on success, non-zero otherwise.
+ */
+int gcov_iter_write(struct gcov_iterator *iter, struct seq_file *seq)
+{
+	int rc = -EINVAL;
+
+	switch (iter->record) {
+	case RECORD_FILE_MAGIC:
+		rc = seq_write_gcov_u32(seq, GCOV_DATA_MAGIC);
+		break;
+	case RECORD_GCOV_VERSION:
+		rc = seq_write_gcov_u32(seq, iter->info->version);
+		break;
+	case RECORD_TIME_STAMP:
+		rc = seq_write_gcov_u32(seq, iter->info->stamp);
+		break;
+	case RECORD_FUNCTION_TAG:
+		rc = seq_write_gcov_u32(seq, GCOV_TAG_FUNCTION);
+		break;
+	case RECORD_FUNCTON_TAG_LEN:
+		rc = seq_write_gcov_u32(seq, 2);
+		break;
+	case RECORD_FUNCTION_IDENT:
+		rc = seq_write_gcov_u32(seq, get_func(iter)->ident);
+		break;
+	case RECORD_FUNCTION_CHECK:
+		rc = seq_write_gcov_u32(seq, get_func(iter)->checksum);
+		break;
+	case RECORD_COUNT_TAG:
+		rc = seq_write_gcov_u32(seq,
+			GCOV_TAG_FOR_COUNTER(get_type(iter)->ctr_type));
+		break;
+	case RECORD_COUNT_LEN:
+		rc = seq_write_gcov_u32(seq,
+				get_func(iter)->n_ctrs[iter->type] * 2);
+		break;
+	case RECORD_COUNT:
+		rc = seq_write_gcov_u64(seq,
+			iter->info->counts[iter->type].
+				values[iter->count + get_type(iter)->offset]);
+		break;
+	}
+	return rc;
+}
diff --git a/kernel/gcov/gcov.h b/kernel/gcov/gcov.h
new file mode 100644
index 0000000..060073e
--- /dev/null
+++ b/kernel/gcov/gcov.h
@@ -0,0 +1,128 @@
+/*
+ *  Profiling infrastructure declarations.
+ *
+ *  This file is based on gcc-internal definitions. Data structures are
+ *  defined to be compatible with gcc counterparts. For a better
+ *  understanding, refer to gcc source: gcc/gcov-io.h.
+ *
+ *    Copyright IBM Corp. 2009
+ *    Author(s): Peter Oberparleiter <oberpar@linux.vnet.ibm.com>
+ *
+ *    Uses gcc-internal data definitions.
+ */
+
+#ifndef GCOV_H
+#define GCOV_H GCOV_H
+
+#include <linux/types.h>
+
+/*
+ * Profiling data types used for gcc 3.4 and above - these are defined by
+ * gcc and need to be kept as close to the original definition as possible to
+ * remain compatible.
+ */
+#define GCOV_COUNTERS		5
+#define GCOV_DATA_MAGIC		((unsigned int) 0x67636461)
+#define GCOV_TAG_FUNCTION	((unsigned int) 0x01000000)
+#define GCOV_TAG_COUNTER_BASE	((unsigned int) 0x01a10000)
+#define GCOV_TAG_FOR_COUNTER(count)					\
+	(GCOV_TAG_COUNTER_BASE + ((unsigned int) (count) << 17))
+
+#if BITS_PER_LONG >= 64
+typedef long gcov_type;
+#else
+typedef long long gcov_type;
+#endif
+
+/**
+ * struct gcov_fn_info - profiling meta data per function
+ * @ident: object file-unique function identifier
+ * @checksum: function checksum
+ * @n_ctrs: number of values per counter type belonging to this function
+ *
+ * This data is generated by gcc during compilation and doesn't change
+ * at run-time.
+ */
+struct gcov_fn_info {
+	unsigned int ident;
+	unsigned int checksum;
+	unsigned int n_ctrs[0];
+};
+
+/**
+ * struct gcov_ctr_info - profiling data per counter type
+ * @num: number of counter values for this type
+ * @values: array of counter values for this type
+ * @merge: merge function for counter values of this type (unused)
+ *
+ * This data is generated by gcc during compilation and doesn't change
+ * at run-time with the exception of the values array.
+ */
+struct gcov_ctr_info {
+	unsigned int	num;
+	gcov_type	*values;
+	void		(*merge)(gcov_type *, unsigned int);
+};
+
+/**
+ * struct gcov_info - profiling data per object file
+ * @version: gcov version magic indicating the gcc version used for compilation
+ * @next: list head for a singly-linked list
+ * @stamp: time stamp
+ * @filename: name of the associated gcov data file
+ * @n_functions: number of instrumented functions
+ * @functions: function data
+ * @ctr_mask: mask specifying which counter types are active
+ * @counts: counter data per counter type
+ *
+ * This data is generated by gcc during compilation and doesn't change
+ * at run-time with the exception of the next pointer.
+ */
+struct gcov_info {
+	unsigned int			version;
+	struct gcov_info		*next;
+	unsigned int			stamp;
+	const char			*filename;
+	unsigned int			n_functions;
+	const struct gcov_fn_info	*functions;
+	unsigned int			ctr_mask;
+	struct gcov_ctr_info		counts[0];
+};
+
+/* Base interface. */
+enum gcov_action {
+	GCOV_ADD,
+	GCOV_REMOVE,
+};
+
+void gcov_event(enum gcov_action action, struct gcov_info *info);
+void gcov_enable_events(void);
+
+/* Iterator control. */
+struct seq_file;
+struct gcov_iterator;
+
+struct gcov_iterator *gcov_iter_new(struct gcov_info *info);
+void gcov_iter_free(struct gcov_iterator *iter);
+void gcov_iter_start(struct gcov_iterator *iter);
+int gcov_iter_next(struct gcov_iterator *iter);
+int gcov_iter_write(struct gcov_iterator *iter, struct seq_file *seq);
+struct gcov_info *gcov_iter_get_info(struct gcov_iterator *iter);
+
+/* gcov_info control. */
+void gcov_info_reset(struct gcov_info *info);
+int gcov_info_is_compatible(struct gcov_info *info1, struct gcov_info *info2);
+void gcov_info_add(struct gcov_info *dest, struct gcov_info *source);
+struct gcov_info *gcov_info_dup(struct gcov_info *info);
+void gcov_info_free(struct gcov_info *info);
+
+struct gcov_link {
+	enum {
+		OBJ_TREE,
+		SRC_TREE,
+	} dir;
+	const char *ext;
+};
+extern const struct gcov_link gcov_link[];
+
+#endif /* GCOV_H */
diff --git a/kernel/hrtimer.c b/kernel/hrtimer.c
index b675a67..9002958 100644
--- a/kernel/hrtimer.c
+++ b/kernel/hrtimer.c
@@ -380,6 +380,8 @@
 	return res;
 }
 
+EXPORT_SYMBOL_GPL(ktime_add_safe);
+
 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
 
 static struct debug_obj_descr hrtimer_debug_descr;
diff --git a/kernel/kthread.c b/kernel/kthread.c
index 7fa4413..9b1a7de 100644
--- a/kernel/kthread.c
+++ b/kernel/kthread.c
@@ -27,7 +27,6 @@
 	/* Information passed to kthread() from kthreadd. */
 	int (*threadfn)(void *data);
 	void *data;
-	struct completion started;
 
 	/* Result passed back to kthread_create() from kthreadd. */
 	struct task_struct *result;
@@ -36,17 +35,13 @@
 	struct list_head list;
 };
 
-struct kthread_stop_info
-{
-	struct task_struct *k;
-	int err;
-	struct completion done;
+struct kthread {
+	int should_stop;
+	struct completion exited;
 };
 
-/* Thread stopping is done by setthing this var: lock serializes
- * multiple kthread_stop calls. */
-static DEFINE_MUTEX(kthread_stop_lock);
-static struct kthread_stop_info kthread_stop_info;
+#define to_kthread(tsk)	\
+	container_of((tsk)->vfork_done, struct kthread, exited)
 
 /**
  * kthread_should_stop - should this kthread return now?
@@ -57,36 +52,35 @@
  */
 int kthread_should_stop(void)
 {
-	return (kthread_stop_info.k == current);
+	return to_kthread(current)->should_stop;
 }
 EXPORT_SYMBOL(kthread_should_stop);
 
 static int kthread(void *_create)
 {
-	struct kthread_create_info *create = _create;
-	int (*threadfn)(void *data);
-	void *data;
-	int ret = -EINTR;
-
 	/* Copy data: it's on kthread's stack */
-	threadfn = create->threadfn;
-	data = create->data;
+	struct kthread_create_info *create = _create;
+	int (*threadfn)(void *data) = create->threadfn;
+	void *data = create->data;
+	struct kthread self;
+	int ret;
+
+	self.should_stop = 0;
+	init_completion(&self.exited);
+	current->vfork_done = &self.exited;
 
 	/* OK, tell user we're spawned, wait for stop or wakeup */
 	__set_current_state(TASK_UNINTERRUPTIBLE);
 	create->result = current;
-	complete(&create->started);
+	complete(&create->done);
 	schedule();
 
-	if (!kthread_should_stop())
+	ret = -EINTR;
+	if (!self.should_stop)
 		ret = threadfn(data);
 
-	/* It might have exited on its own, w/o kthread_stop.  Check. */
-	if (kthread_should_stop()) {
-		kthread_stop_info.err = ret;
-		complete(&kthread_stop_info.done);
-	}
-	return 0;
+	/* we can't just return, we must preserve "self" on stack */
+	do_exit(ret);
 }
 
 static void create_kthread(struct kthread_create_info *create)
@@ -95,11 +89,10 @@
 
 	/* We want our own signal handler (we take no signals by default). */
 	pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
-	if (pid < 0)
+	if (pid < 0) {
 		create->result = ERR_PTR(pid);
-	else
-		wait_for_completion(&create->started);
-	complete(&create->done);
+		complete(&create->done);
+	}
 }
 
 /**
@@ -130,7 +123,6 @@
 
 	create.threadfn = threadfn;
 	create.data = data;
-	init_completion(&create.started);
 	init_completion(&create.done);
 
 	spin_lock(&kthread_create_lock);
@@ -198,30 +190,22 @@
  */
 int kthread_stop(struct task_struct *k)
 {
+	struct kthread *kthread;
 	int ret;
 
-	mutex_lock(&kthread_stop_lock);
-
-	/* It could exit after stop_info.k set, but before wake_up_process. */
+	trace_sched_kthread_stop(k);
 	get_task_struct(k);
 
-	trace_sched_kthread_stop(k);
+	kthread = to_kthread(k);
+	barrier(); /* it might have exited */
+	if (k->vfork_done != NULL) {
+		kthread->should_stop = 1;
+		wake_up_process(k);
+		wait_for_completion(&kthread->exited);
+	}
+	ret = k->exit_code;
 
-	/* Must init completion *before* thread sees kthread_stop_info.k */
-	init_completion(&kthread_stop_info.done);
-	smp_wmb();
-
-	/* Now set kthread_should_stop() to true, and wake it up. */
-	kthread_stop_info.k = k;
-	wake_up_process(k);
 	put_task_struct(k);
-
-	/* Once it dies, reset stop ptr, gather result and we're done. */
-	wait_for_completion(&kthread_stop_info.done);
-	kthread_stop_info.k = NULL;
-	ret = kthread_stop_info.err;
-	mutex_unlock(&kthread_stop_lock);
-
 	trace_sched_kthread_stop_ret(ret);
 
 	return ret;
diff --git a/kernel/module.c b/kernel/module.c
index 215aaab..38928fc 100644
--- a/kernel/module.c
+++ b/kernel/module.c
@@ -2216,6 +2216,10 @@
 	mod->unused_gpl_crcs = section_addr(hdr, sechdrs, secstrings,
 					    "__kcrctab_unused_gpl");
 #endif
+#ifdef CONFIG_CONSTRUCTORS
+	mod->ctors = section_objs(hdr, sechdrs, secstrings, ".ctors",
+				  sizeof(*mod->ctors), &mod->num_ctors);
+#endif
 
 #ifdef CONFIG_MARKERS
 	mod->markers = section_objs(hdr, sechdrs, secstrings, "__markers",
@@ -2389,6 +2393,17 @@
 	goto free_hdr;
 }
 
+/* Call module constructors. */
+static void do_mod_ctors(struct module *mod)
+{
+#ifdef CONFIG_CONSTRUCTORS
+	unsigned long i;
+
+	for (i = 0; i < mod->num_ctors; i++)
+		mod->ctors[i]();
+#endif
+}
+
 /* This is where the real work happens */
 SYSCALL_DEFINE3(init_module, void __user *, umod,
 		unsigned long, len, const char __user *, uargs)
@@ -2417,6 +2432,7 @@
 	blocking_notifier_call_chain(&module_notify_list,
 			MODULE_STATE_COMING, mod);
 
+	do_mod_ctors(mod);
 	/* Start the module */
 	if (mod->init != NULL)
 		ret = do_one_initcall(mod->init);
diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c
index 63598dc..09b4ff9 100644
--- a/kernel/nsproxy.c
+++ b/kernel/nsproxy.c
@@ -26,19 +26,14 @@
 
 struct nsproxy init_nsproxy = INIT_NSPROXY(init_nsproxy);
 
-/*
- * creates a copy of "orig" with refcount 1.
- */
-static inline struct nsproxy *clone_nsproxy(struct nsproxy *orig)
+static inline struct nsproxy *create_nsproxy(void)
 {
-	struct nsproxy *ns;
+	struct nsproxy *nsproxy;
 
-	ns = kmem_cache_alloc(nsproxy_cachep, GFP_KERNEL);
-	if (ns) {
-		memcpy(ns, orig, sizeof(struct nsproxy));
-		atomic_set(&ns->count, 1);
-	}
-	return ns;
+	nsproxy = kmem_cache_alloc(nsproxy_cachep, GFP_KERNEL);
+	if (nsproxy)
+		atomic_set(&nsproxy->count, 1);
+	return nsproxy;
 }
 
 /*
@@ -52,7 +47,7 @@
 	struct nsproxy *new_nsp;
 	int err;
 
-	new_nsp = clone_nsproxy(tsk->nsproxy);
+	new_nsp = create_nsproxy();
 	if (!new_nsp)
 		return ERR_PTR(-ENOMEM);
 
diff --git a/kernel/pid.c b/kernel/pid.c
index b2e5f78..31310b5 100644
--- a/kernel/pid.c
+++ b/kernel/pid.c
@@ -378,26 +378,15 @@
 /*
  * Must be called under rcu_read_lock() or with tasklist_lock read-held.
  */
-struct task_struct *find_task_by_pid_type_ns(int type, int nr,
-		struct pid_namespace *ns)
+struct task_struct *find_task_by_pid_ns(pid_t nr, struct pid_namespace *ns)
 {
-	return pid_task(find_pid_ns(nr, ns), type);
+	return pid_task(find_pid_ns(nr, ns), PIDTYPE_PID);
 }
 
-EXPORT_SYMBOL(find_task_by_pid_type_ns);
-
 struct task_struct *find_task_by_vpid(pid_t vnr)
 {
-	return find_task_by_pid_type_ns(PIDTYPE_PID, vnr,
-			current->nsproxy->pid_ns);
+	return find_task_by_pid_ns(vnr, current->nsproxy->pid_ns);
 }
-EXPORT_SYMBOL(find_task_by_vpid);
-
-struct task_struct *find_task_by_pid_ns(pid_t nr, struct pid_namespace *ns)
-{
-	return find_task_by_pid_type_ns(PIDTYPE_PID, nr, ns);
-}
-EXPORT_SYMBOL(find_task_by_pid_ns);
 
 struct pid *get_task_pid(struct task_struct *task, enum pid_type type)
 {
diff --git a/kernel/pid_namespace.c b/kernel/pid_namespace.c
index 2d1001b..821722a 100644
--- a/kernel/pid_namespace.c
+++ b/kernel/pid_namespace.c
@@ -67,9 +67,10 @@
 	return NULL;
 }
 
-static struct pid_namespace *create_pid_namespace(unsigned int level)
+static struct pid_namespace *create_pid_namespace(struct pid_namespace *parent_pid_ns)
 {
 	struct pid_namespace *ns;
+	unsigned int level = parent_pid_ns->level + 1;
 	int i;
 
 	ns = kmem_cache_zalloc(pid_ns_cachep, GFP_KERNEL);
@@ -86,6 +87,7 @@
 
 	kref_init(&ns->kref);
 	ns->level = level;
+	ns->parent = get_pid_ns(parent_pid_ns);
 
 	set_bit(0, ns->pidmap[0].page);
 	atomic_set(&ns->pidmap[0].nr_free, BITS_PER_PAGE - 1);
@@ -114,25 +116,11 @@
 
 struct pid_namespace *copy_pid_ns(unsigned long flags, struct pid_namespace *old_ns)
 {
-	struct pid_namespace *new_ns;
-
-	BUG_ON(!old_ns);
-	new_ns = get_pid_ns(old_ns);
 	if (!(flags & CLONE_NEWPID))
-		goto out;
-
-	new_ns = ERR_PTR(-EINVAL);
+		return get_pid_ns(old_ns);
 	if (flags & CLONE_THREAD)
-		goto out_put;
-
-	new_ns = create_pid_namespace(old_ns->level + 1);
-	if (!IS_ERR(new_ns))
-		new_ns->parent = get_pid_ns(old_ns);
-
-out_put:
-	put_pid_ns(old_ns);
-out:
-	return new_ns;
+		return ERR_PTR(-EINVAL);
+	return create_pid_namespace(old_ns);
 }
 
 void free_pid_ns(struct kref *kref)
diff --git a/kernel/ptrace.c b/kernel/ptrace.c
index f6d8b8c..61c78b2 100644
--- a/kernel/ptrace.c
+++ b/kernel/ptrace.c
@@ -167,67 +167,82 @@
 int ptrace_attach(struct task_struct *task)
 {
 	int retval;
-	unsigned long flags;
 
 	audit_ptrace(task);
 
 	retval = -EPERM;
+	if (unlikely(task->flags & PF_KTHREAD))
+		goto out;
 	if (same_thread_group(task, current))
 		goto out;
 
-	/* Protect the target's credential calculations against our
+	/*
+	 * Protect exec's credential calculations against our interference;
 	 * interference; SUID, SGID and LSM creds get determined differently
 	 * under ptrace.
 	 */
 	retval = mutex_lock_interruptible(&task->cred_guard_mutex);
-	if (retval  < 0)
+	if (retval < 0)
 		goto out;
 
-	retval = -EPERM;
-repeat:
-	/*
-	 * Nasty, nasty.
-	 *
-	 * We want to hold both the task-lock and the
-	 * tasklist_lock for writing at the same time.
-	 * But that's against the rules (tasklist_lock
-	 * is taken for reading by interrupts on other
-	 * cpu's that may have task_lock).
-	 */
 	task_lock(task);
-	if (!write_trylock_irqsave(&tasklist_lock, flags)) {
-		task_unlock(task);
-		do {
-			cpu_relax();
-		} while (!write_can_lock(&tasklist_lock));
-		goto repeat;
-	}
-
-	if (!task->mm)
-		goto bad;
-	/* the same process cannot be attached many times */
-	if (task->ptrace & PT_PTRACED)
-		goto bad;
 	retval = __ptrace_may_access(task, PTRACE_MODE_ATTACH);
+	task_unlock(task);
 	if (retval)
-		goto bad;
+		goto unlock_creds;
 
-	/* Go */
-	task->ptrace |= PT_PTRACED;
+	write_lock_irq(&tasklist_lock);
+	retval = -EPERM;
+	if (unlikely(task->exit_state))
+		goto unlock_tasklist;
+	if (task->ptrace)
+		goto unlock_tasklist;
+
+	task->ptrace = PT_PTRACED;
 	if (capable(CAP_SYS_PTRACE))
 		task->ptrace |= PT_PTRACE_CAP;
 
 	__ptrace_link(task, current);
-
 	send_sig_info(SIGSTOP, SEND_SIG_FORCED, task);
-bad:
-	write_unlock_irqrestore(&tasklist_lock, flags);
-	task_unlock(task);
+
+	retval = 0;
+unlock_tasklist:
+	write_unlock_irq(&tasklist_lock);
+unlock_creds:
 	mutex_unlock(&task->cred_guard_mutex);
 out:
 	return retval;
 }
 
+/**
+ * ptrace_traceme  --  helper for PTRACE_TRACEME
+ *
+ * Performs checks and sets PT_PTRACED.
+ * Should be used by all ptrace implementations for PTRACE_TRACEME.
+ */
+int ptrace_traceme(void)
+{
+	int ret = -EPERM;
+
+	write_lock_irq(&tasklist_lock);
+	/* Are we already being traced? */
+	if (!current->ptrace) {
+		ret = security_ptrace_traceme(current->parent);
+		/*
+		 * Check PF_EXITING to ensure ->real_parent has not passed
+		 * exit_ptrace(). Otherwise we don't report the error but
+		 * pretend ->real_parent untraces us right after return.
+		 */
+		if (!ret && !(current->real_parent->flags & PF_EXITING)) {
+			current->ptrace = PT_PTRACED;
+			__ptrace_link(current, current->real_parent);
+		}
+	}
+	write_unlock_irq(&tasklist_lock);
+
+	return ret;
+}
+
 /*
  * Called with irqs disabled, returns true if childs should reap themselves.
  */
@@ -409,37 +424,33 @@
 
 static int ptrace_getsiginfo(struct task_struct *child, siginfo_t *info)
 {
+	unsigned long flags;
 	int error = -ESRCH;
 
-	read_lock(&tasklist_lock);
-	if (likely(child->sighand != NULL)) {
+	if (lock_task_sighand(child, &flags)) {
 		error = -EINVAL;
-		spin_lock_irq(&child->sighand->siglock);
 		if (likely(child->last_siginfo != NULL)) {
 			*info = *child->last_siginfo;
 			error = 0;
 		}
-		spin_unlock_irq(&child->sighand->siglock);
+		unlock_task_sighand(child, &flags);
 	}
-	read_unlock(&tasklist_lock);
 	return error;
 }
 
 static int ptrace_setsiginfo(struct task_struct *child, const siginfo_t *info)
 {
+	unsigned long flags;
 	int error = -ESRCH;
 
-	read_lock(&tasklist_lock);
-	if (likely(child->sighand != NULL)) {
+	if (lock_task_sighand(child, &flags)) {
 		error = -EINVAL;
-		spin_lock_irq(&child->sighand->siglock);
 		if (likely(child->last_siginfo != NULL)) {
 			*child->last_siginfo = *info;
 			error = 0;
 		}
-		spin_unlock_irq(&child->sighand->siglock);
+		unlock_task_sighand(child, &flags);
 	}
-	read_unlock(&tasklist_lock);
 	return error;
 }
 
@@ -566,72 +577,16 @@
 	return ret;
 }
 
-/**
- * ptrace_traceme  --  helper for PTRACE_TRACEME
- *
- * Performs checks and sets PT_PTRACED.
- * Should be used by all ptrace implementations for PTRACE_TRACEME.
- */
-int ptrace_traceme(void)
-{
-	int ret = -EPERM;
-
-	/*
-	 * Are we already being traced?
-	 */
-repeat:
-	task_lock(current);
-	if (!(current->ptrace & PT_PTRACED)) {
-		/*
-		 * See ptrace_attach() comments about the locking here.
-		 */
-		unsigned long flags;
-		if (!write_trylock_irqsave(&tasklist_lock, flags)) {
-			task_unlock(current);
-			do {
-				cpu_relax();
-			} while (!write_can_lock(&tasklist_lock));
-			goto repeat;
-		}
-
-		ret = security_ptrace_traceme(current->parent);
-
-		/*
-		 * Check PF_EXITING to ensure ->real_parent has not passed
-		 * exit_ptrace(). Otherwise we don't report the error but
-		 * pretend ->real_parent untraces us right after return.
-		 */
-		if (!ret && !(current->real_parent->flags & PF_EXITING)) {
-			current->ptrace |= PT_PTRACED;
-			__ptrace_link(current, current->real_parent);
-		}
-
-		write_unlock_irqrestore(&tasklist_lock, flags);
-	}
-	task_unlock(current);
-	return ret;
-}
-
-/**
- * ptrace_get_task_struct  --  grab a task struct reference for ptrace
- * @pid:       process id to grab a task_struct reference of
- *
- * This function is a helper for ptrace implementations.  It checks
- * permissions and then grabs a task struct for use of the actual
- * ptrace implementation.
- *
- * Returns the task_struct for @pid or an ERR_PTR() on failure.
- */
-struct task_struct *ptrace_get_task_struct(pid_t pid)
+static struct task_struct *ptrace_get_task_struct(pid_t pid)
 {
 	struct task_struct *child;
 
-	read_lock(&tasklist_lock);
+	rcu_read_lock();
 	child = find_task_by_vpid(pid);
 	if (child)
 		get_task_struct(child);
+	rcu_read_unlock();
 
-	read_unlock(&tasklist_lock);
 	if (!child)
 		return ERR_PTR(-ESRCH);
 	return child;
diff --git a/kernel/res_counter.c b/kernel/res_counter.c
index bf8e753..e1338f0 100644
--- a/kernel/res_counter.c
+++ b/kernel/res_counter.c
@@ -18,7 +18,7 @@
 void res_counter_init(struct res_counter *counter, struct res_counter *parent)
 {
 	spin_lock_init(&counter->lock);
-	counter->limit = (unsigned long long)LLONG_MAX;
+	counter->limit = RESOURCE_MAX;
 	counter->parent = parent;
 }
 
@@ -133,6 +133,16 @@
 					unsigned long long *res)
 {
 	char *end;
+
+	/* return RESOURCE_MAX(unlimited) if "-1" is specified */
+	if (*buf == '-') {
+		*res = simple_strtoull(buf + 1, &end, 10);
+		if (*res != 1 || *end != '\0')
+			return -EINVAL;
+		*res = RESOURCE_MAX;
+		return 0;
+	}
+
 	/* FIXME - make memparse() take const char* args */
 	*res = memparse((char *)buf, &end);
 	if (*end != '\0')
diff --git a/kernel/sched.c b/kernel/sched.c
index f46540b..7c9098d 100644
--- a/kernel/sched.c
+++ b/kernel/sched.c
@@ -7046,7 +7046,7 @@
 
 		if (cpu_is_offline(cpu)) {
 			spin_unlock_irq(&rq->lock);
-			goto wait_to_die;
+			break;
 		}
 
 		if (rq->active_balance) {
@@ -7072,16 +7072,7 @@
 		complete(&req->done);
 	}
 	__set_current_state(TASK_RUNNING);
-	return 0;
 
-wait_to_die:
-	/* Wait for kthread_stop */
-	set_current_state(TASK_INTERRUPTIBLE);
-	while (!kthread_should_stop()) {
-		schedule();
-		set_current_state(TASK_INTERRUPTIBLE);
-	}
-	__set_current_state(TASK_RUNNING);
 	return 0;
 }
 
@@ -7495,6 +7486,7 @@
 		rq = task_rq_lock(p, &flags);
 		__setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
 		task_rq_unlock(rq, &flags);
+		get_task_struct(p);
 		cpu_rq(cpu)->migration_thread = p;
 		break;
 
@@ -7525,6 +7517,7 @@
 		kthread_bind(cpu_rq(cpu)->migration_thread,
 			     cpumask_any(cpu_online_mask));
 		kthread_stop(cpu_rq(cpu)->migration_thread);
+		put_task_struct(cpu_rq(cpu)->migration_thread);
 		cpu_rq(cpu)->migration_thread = NULL;
 		break;
 
@@ -7534,6 +7527,7 @@
 		migrate_live_tasks(cpu);
 		rq = cpu_rq(cpu);
 		kthread_stop(rq->migration_thread);
+		put_task_struct(rq->migration_thread);
 		rq->migration_thread = NULL;
 		/* Idle task back to normal (off runqueue, low prio) */
 		spin_lock_irq(&rq->lock);
@@ -7829,7 +7823,7 @@
 		free_rootdomain(old_rd);
 }
 
-static int __init_refok init_rootdomain(struct root_domain *rd, bool bootmem)
+static int init_rootdomain(struct root_domain *rd, bool bootmem)
 {
 	gfp_t gfp = GFP_KERNEL;
 
diff --git a/kernel/sched_cpupri.c b/kernel/sched_cpupri.c
index 7deffc9..e6c2517 100644
--- a/kernel/sched_cpupri.c
+++ b/kernel/sched_cpupri.c
@@ -152,7 +152,7 @@
  *
  * Returns: -ENOMEM if memory fails.
  */
-int __init_refok cpupri_init(struct cpupri *cp, bool bootmem)
+int cpupri_init(struct cpupri *cp, bool bootmem)
 {
 	gfp_t gfp = GFP_KERNEL;
 	int i;
diff --git a/kernel/sched_debug.c b/kernel/sched_debug.c
index 467ca72..70c7e0b 100644
--- a/kernel/sched_debug.c
+++ b/kernel/sched_debug.c
@@ -162,7 +162,7 @@
 {
 	s64 MIN_vruntime = -1, min_vruntime, max_vruntime = -1,
 		spread, rq0_min_vruntime, spread0;
-	struct rq *rq = &per_cpu(runqueues, cpu);
+	struct rq *rq = cpu_rq(cpu);
 	struct sched_entity *last;
 	unsigned long flags;
 
@@ -191,7 +191,7 @@
 	if (last)
 		max_vruntime = last->vruntime;
 	min_vruntime = cfs_rq->min_vruntime;
-	rq0_min_vruntime = per_cpu(runqueues, 0).cfs.min_vruntime;
+	rq0_min_vruntime = cpu_rq(0)->cfs.min_vruntime;
 	spin_unlock_irqrestore(&rq->lock, flags);
 	SEQ_printf(m, "  .%-30s: %Ld.%06ld\n", "MIN_vruntime",
 			SPLIT_NS(MIN_vruntime));
@@ -248,7 +248,7 @@
 
 static void print_cpu(struct seq_file *m, int cpu)
 {
-	struct rq *rq = &per_cpu(runqueues, cpu);
+	struct rq *rq = cpu_rq(cpu);
 
 #ifdef CONFIG_X86
 	{
diff --git a/kernel/sched_fair.c b/kernel/sched_fair.c
index 5f9650e..ba7fd6e 100644
--- a/kernel/sched_fair.c
+++ b/kernel/sched_fair.c
@@ -430,12 +430,13 @@
 
 	for_each_sched_entity(se) {
 		struct load_weight *load;
+		struct load_weight lw;
 
 		cfs_rq = cfs_rq_of(se);
 		load = &cfs_rq->load;
 
 		if (unlikely(!se->on_rq)) {
-			struct load_weight lw = cfs_rq->load;
+			lw = cfs_rq->load;
 
 			update_load_add(&lw, se->load.weight);
 			load = &lw;
diff --git a/kernel/signal.c b/kernel/signal.c
index d81f495..ccf1cee 100644
--- a/kernel/signal.c
+++ b/kernel/signal.c
@@ -1410,7 +1410,7 @@
  	/* do_notify_parent_cldstop should have been called instead.  */
  	BUG_ON(task_is_stopped_or_traced(tsk));
 
-	BUG_ON(!tsk->ptrace &&
+	BUG_ON(!task_ptrace(tsk) &&
 	       (tsk->group_leader != tsk || !thread_group_empty(tsk)));
 
 	info.si_signo = sig;
@@ -1449,7 +1449,7 @@
 
 	psig = tsk->parent->sighand;
 	spin_lock_irqsave(&psig->siglock, flags);
-	if (!tsk->ptrace && sig == SIGCHLD &&
+	if (!task_ptrace(tsk) && sig == SIGCHLD &&
 	    (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN ||
 	     (psig->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDWAIT))) {
 		/*
@@ -1486,7 +1486,7 @@
 	struct task_struct *parent;
 	struct sighand_struct *sighand;
 
-	if (tsk->ptrace & PT_PTRACED)
+	if (task_ptrace(tsk))
 		parent = tsk->parent;
 	else {
 		tsk = tsk->group_leader;
@@ -1499,7 +1499,7 @@
 	 * see comment in do_notify_parent() abot the following 3 lines
 	 */
 	rcu_read_lock();
-	info.si_pid = task_pid_nr_ns(tsk, tsk->parent->nsproxy->pid_ns);
+	info.si_pid = task_pid_nr_ns(tsk, parent->nsproxy->pid_ns);
 	info.si_uid = __task_cred(tsk)->uid;
 	rcu_read_unlock();
 
@@ -1535,7 +1535,7 @@
 
 static inline int may_ptrace_stop(void)
 {
-	if (!likely(current->ptrace & PT_PTRACED))
+	if (!likely(task_ptrace(current)))
 		return 0;
 	/*
 	 * Are we in the middle of do_coredump?
@@ -1753,7 +1753,7 @@
 static int ptrace_signal(int signr, siginfo_t *info,
 			 struct pt_regs *regs, void *cookie)
 {
-	if (!(current->ptrace & PT_PTRACED))
+	if (!task_ptrace(current))
 		return signr;
 
 	ptrace_signal_deliver(regs, cookie);
diff --git a/kernel/softirq.c b/kernel/softirq.c
index b41fb71..3a94905 100644
--- a/kernel/softirq.c
+++ b/kernel/softirq.c
@@ -213,6 +213,7 @@
 	do {
 		if (pending & 1) {
 			int prev_count = preempt_count();
+			kstat_incr_softirqs_this_cpu(h - softirq_vec);
 
 			trace_softirq_entry(h, softirq_vec);
 			h->action(h);
diff --git a/kernel/sysctl.c b/kernel/sysctl.c
index ab462b9..62e4ff9 100644
--- a/kernel/sysctl.c
+++ b/kernel/sysctl.c
@@ -2283,7 +2283,7 @@
 		  void *data)
 {
 #define TMPBUFLEN 21
-	int *i, vleft, first=1, neg, val;
+	int *i, vleft, first = 1, neg;
 	unsigned long lval;
 	size_t left, len;
 	
@@ -2336,8 +2336,6 @@
 			len = p-buf;
 			if ((len < left) && *p && !isspace(*p))
 				break;
-			if (neg)
-				val = -val;
 			s += len;
 			left -= len;
 
diff --git a/kernel/time/tick-sched.c b/kernel/time/tick-sched.c
index 2aff39c..e0f59a2 100644
--- a/kernel/time/tick-sched.c
+++ b/kernel/time/tick-sched.c
@@ -222,6 +222,15 @@
 
 	cpu = smp_processor_id();
 	ts = &per_cpu(tick_cpu_sched, cpu);
+
+	/*
+	 * Call to tick_nohz_start_idle stops the last_update_time from being
+	 * updated. Thus, it must not be called in the event we are called from
+	 * irq_exit() with the prior state different than idle.
+	 */
+	if (!inidle && !ts->inidle)
+		goto end;
+
 	now = tick_nohz_start_idle(ts);
 
 	/*
@@ -239,9 +248,6 @@
 	if (unlikely(ts->nohz_mode == NOHZ_MODE_INACTIVE))
 		goto end;
 
-	if (!inidle && !ts->inidle)
-		goto end;
-
 	ts->inidle = 1;
 
 	if (need_resched())
diff --git a/kernel/trace/Kconfig b/kernel/trace/Kconfig
index 61071fe..1551f47 100644
--- a/kernel/trace/Kconfig
+++ b/kernel/trace/Kconfig
@@ -18,6 +18,13 @@
 config HAVE_FUNCTION_GRAPH_TRACER
 	bool
 
+config HAVE_FUNCTION_GRAPH_FP_TEST
+	bool
+	help
+	 An arch may pass in a unique value (frame pointer) to both the
+	 entering and exiting of a function. On exit, the value is compared
+	 and if it does not match, then it will panic the kernel.
+
 config HAVE_FUNCTION_TRACE_MCOUNT_TEST
 	bool
 	help
@@ -121,6 +128,7 @@
 	bool "Kernel Function Graph Tracer"
 	depends on HAVE_FUNCTION_GRAPH_TRACER
 	depends on FUNCTION_TRACER
+	depends on !X86_32 || !CC_OPTIMIZE_FOR_SIZE
 	default y
 	help
 	  Enable the kernel to trace a function at both its return
diff --git a/kernel/trace/ftrace.c b/kernel/trace/ftrace.c
index bb60732..3718d55 100644
--- a/kernel/trace/ftrace.c
+++ b/kernel/trace/ftrace.c
@@ -1224,6 +1224,13 @@
 		return;
 
 	ftrace_start_up--;
+	/*
+	 * Just warn in case of unbalance, no need to kill ftrace, it's not
+	 * critical but the ftrace_call callers may be never nopped again after
+	 * further ftrace uses.
+	 */
+	WARN_ON_ONCE(ftrace_start_up < 0);
+
 	if (!ftrace_start_up)
 		command |= FTRACE_DISABLE_CALLS;
 
diff --git a/kernel/trace/kmemtrace.c b/kernel/trace/kmemtrace.c
index 86cdf67..1edaa95 100644
--- a/kernel/trace/kmemtrace.c
+++ b/kernel/trace/kmemtrace.c
@@ -186,7 +186,7 @@
 	int cpu;
 	kmemtrace_array = tr;
 
-	for_each_cpu_mask(cpu, cpu_possible_map)
+	for_each_cpu(cpu, cpu_possible_mask)
 		tracing_reset(tr, cpu);
 
 	kmemtrace_start_probes();
diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c
index dc4dc70..04dac26 100644
--- a/kernel/trace/ring_buffer.c
+++ b/kernel/trace/ring_buffer.c
@@ -206,6 +206,7 @@
 #define RB_EVNT_HDR_SIZE (offsetof(struct ring_buffer_event, array))
 #define RB_ALIGNMENT		4U
 #define RB_MAX_SMALL_DATA	(RB_ALIGNMENT * RINGBUF_TYPE_DATA_TYPE_LEN_MAX)
+#define RB_EVNT_MIN_SIZE	8U	/* two 32bit words */
 
 /* define RINGBUF_TYPE_DATA for 'case RINGBUF_TYPE_DATA:' */
 #define RINGBUF_TYPE_DATA 0 ... RINGBUF_TYPE_DATA_TYPE_LEN_MAX
@@ -415,6 +416,8 @@
 	unsigned long			overrun;
 	unsigned long			read;
 	local_t				entries;
+	local_t				committing;
+	local_t				commits;
 	u64				write_stamp;
 	u64				read_stamp;
 	atomic_t			record_disabled;
@@ -618,12 +621,6 @@
 	kfree(cpu_buffer);
 }
 
-/*
- * Causes compile errors if the struct buffer_page gets bigger
- * than the struct page.
- */
-extern int ring_buffer_page_too_big(void);
-
 #ifdef CONFIG_HOTPLUG_CPU
 static int rb_cpu_notify(struct notifier_block *self,
 			 unsigned long action, void *hcpu);
@@ -646,11 +643,6 @@
 	int bsize;
 	int cpu;
 
-	/* Paranoid! Optimizes out when all is well */
-	if (sizeof(struct buffer_page) > sizeof(struct page))
-		ring_buffer_page_too_big();
-
-
 	/* keep it in its own cache line */
 	buffer = kzalloc(ALIGN(sizeof(*buffer), cache_line_size()),
 			 GFP_KERNEL);
@@ -666,8 +658,8 @@
 	buffer->reader_lock_key = key;
 
 	/* need at least two pages */
-	if (buffer->pages == 1)
-		buffer->pages++;
+	if (buffer->pages < 2)
+		buffer->pages = 2;
 
 	/*
 	 * In case of non-hotplug cpu, if the ring-buffer is allocated
@@ -1011,12 +1003,12 @@
 {
 	unsigned long addr = (unsigned long)event;
 
-	return (addr & ~PAGE_MASK) - (PAGE_SIZE - BUF_PAGE_SIZE);
+	return (addr & ~PAGE_MASK) - BUF_PAGE_HDR_SIZE;
 }
 
 static inline int
-rb_is_commit(struct ring_buffer_per_cpu *cpu_buffer,
-	     struct ring_buffer_event *event)
+rb_event_is_commit(struct ring_buffer_per_cpu *cpu_buffer,
+		   struct ring_buffer_event *event)
 {
 	unsigned long addr = (unsigned long)event;
 	unsigned long index;
@@ -1029,31 +1021,6 @@
 }
 
 static void
-rb_set_commit_event(struct ring_buffer_per_cpu *cpu_buffer,
-		    struct ring_buffer_event *event)
-{
-	unsigned long addr = (unsigned long)event;
-	unsigned long index;
-
-	index = rb_event_index(event);
-	addr &= PAGE_MASK;
-
-	while (cpu_buffer->commit_page->page != (void *)addr) {
-		if (RB_WARN_ON(cpu_buffer,
-			  cpu_buffer->commit_page == cpu_buffer->tail_page))
-			return;
-		cpu_buffer->commit_page->page->commit =
-			cpu_buffer->commit_page->write;
-		rb_inc_page(cpu_buffer, &cpu_buffer->commit_page);
-		cpu_buffer->write_stamp =
-			cpu_buffer->commit_page->page->time_stamp;
-	}
-
-	/* Now set the commit to the event's index */
-	local_set(&cpu_buffer->commit_page->page->commit, index);
-}
-
-static void
 rb_set_commit_to_write(struct ring_buffer_per_cpu *cpu_buffer)
 {
 	/*
@@ -1171,6 +1138,60 @@
 	return length;
 }
 
+static inline void
+rb_reset_tail(struct ring_buffer_per_cpu *cpu_buffer,
+	      struct buffer_page *tail_page,
+	      unsigned long tail, unsigned long length)
+{
+	struct ring_buffer_event *event;
+
+	/*
+	 * Only the event that crossed the page boundary
+	 * must fill the old tail_page with padding.
+	 */
+	if (tail >= BUF_PAGE_SIZE) {
+		local_sub(length, &tail_page->write);
+		return;
+	}
+
+	event = __rb_page_index(tail_page, tail);
+	kmemcheck_annotate_bitfield(event, bitfield);
+
+	/*
+	 * If this event is bigger than the minimum size, then
+	 * we need to be careful that we don't subtract the
+	 * write counter enough to allow another writer to slip
+	 * in on this page.
+	 * We put in a discarded commit instead, to make sure
+	 * that this space is not used again.
+	 *
+	 * If we are less than the minimum size, we don't need to
+	 * worry about it.
+	 */
+	if (tail > (BUF_PAGE_SIZE - RB_EVNT_MIN_SIZE)) {
+		/* No room for any events */
+
+		/* Mark the rest of the page with padding */
+		rb_event_set_padding(event);
+
+		/* Set the write back to the previous setting */
+		local_sub(length, &tail_page->write);
+		return;
+	}
+
+	/* Put in a discarded event */
+	event->array[0] = (BUF_PAGE_SIZE - tail) - RB_EVNT_HDR_SIZE;
+	event->type_len = RINGBUF_TYPE_PADDING;
+	/* time delta must be non zero */
+	event->time_delta = 1;
+	/* Account for this as an entry */
+	local_inc(&tail_page->entries);
+	local_inc(&cpu_buffer->entries);
+
+	/* Set write to end of buffer */
+	length = (tail + length) - BUF_PAGE_SIZE;
+	local_sub(length, &tail_page->write);
+}
 
 static struct ring_buffer_event *
 rb_move_tail(struct ring_buffer_per_cpu *cpu_buffer,
@@ -1180,7 +1201,6 @@
 {
 	struct buffer_page *next_page, *head_page, *reader_page;
 	struct ring_buffer *buffer = cpu_buffer->buffer;
-	struct ring_buffer_event *event;
 	bool lock_taken = false;
 	unsigned long flags;
 
@@ -1265,27 +1285,7 @@
 		cpu_buffer->tail_page->page->time_stamp = *ts;
 	}
 
-	/*
-	 * The actual tail page has moved forward.
-	 */
-	if (tail < BUF_PAGE_SIZE) {
-		/* Mark the rest of the page with padding */
-		event = __rb_page_index(tail_page, tail);
-		kmemcheck_annotate_bitfield(event, bitfield);
-		rb_event_set_padding(event);
-	}
-
-	/* Set the write back to the previous setting */
-	local_sub(length, &tail_page->write);
-
-	/*
-	 * If this was a commit entry that failed,
-	 * increment that too
-	 */
-	if (tail_page == cpu_buffer->commit_page &&
-	    tail == rb_commit_index(cpu_buffer)) {
-		rb_set_commit_to_write(cpu_buffer);
-	}
+	rb_reset_tail(cpu_buffer, tail_page, tail, length);
 
 	__raw_spin_unlock(&cpu_buffer->lock);
 	local_irq_restore(flags);
@@ -1295,7 +1295,7 @@
 
  out_reset:
 	/* reset write */
-	local_sub(length, &tail_page->write);
+	rb_reset_tail(cpu_buffer, tail_page, tail, length);
 
 	if (likely(lock_taken))
 		__raw_spin_unlock(&cpu_buffer->lock);
@@ -1325,9 +1325,6 @@
 
 	/* We reserved something on the buffer */
 
-	if (RB_WARN_ON(cpu_buffer, write > BUF_PAGE_SIZE))
-		return NULL;
-
 	event = __rb_page_index(tail_page, tail);
 	kmemcheck_annotate_bitfield(event, bitfield);
 	rb_update_event(event, type, length);
@@ -1337,11 +1334,11 @@
 		local_inc(&tail_page->entries);
 
 	/*
-	 * If this is a commit and the tail is zero, then update
-	 * this page's time stamp.
+	 * If this is the first commit on the page, then update
+	 * its timestamp.
 	 */
-	if (!tail && rb_is_commit(cpu_buffer, event))
-		cpu_buffer->commit_page->page->time_stamp = *ts;
+	if (!tail)
+		tail_page->page->time_stamp = *ts;
 
 	return event;
 }
@@ -1410,16 +1407,16 @@
 		return -EAGAIN;
 
 	/* Only a commited time event can update the write stamp */
-	if (rb_is_commit(cpu_buffer, event)) {
+	if (rb_event_is_commit(cpu_buffer, event)) {
 		/*
-		 * If this is the first on the page, then we need to
-		 * update the page itself, and just put in a zero.
+		 * If this is the first on the page, then it was
+		 * updated with the page itself. Try to discard it
+		 * and if we can't just make it zero.
 		 */
 		if (rb_event_index(event)) {
 			event->time_delta = *delta & TS_MASK;
 			event->array[0] = *delta >> TS_SHIFT;
 		} else {
-			cpu_buffer->commit_page->page->time_stamp = *ts;
 			/* try to discard, since we do not need this */
 			if (!rb_try_to_discard(cpu_buffer, event)) {
 				/* nope, just zero it */
@@ -1445,6 +1442,44 @@
 	return ret;
 }
 
+static void rb_start_commit(struct ring_buffer_per_cpu *cpu_buffer)
+{
+	local_inc(&cpu_buffer->committing);
+	local_inc(&cpu_buffer->commits);
+}
+
+static void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer)
+{
+	unsigned long commits;
+
+	if (RB_WARN_ON(cpu_buffer,
+		       !local_read(&cpu_buffer->committing)))
+		return;
+
+ again:
+	commits = local_read(&cpu_buffer->commits);
+	/* synchronize with interrupts */
+	barrier();
+	if (local_read(&cpu_buffer->committing) == 1)
+		rb_set_commit_to_write(cpu_buffer);
+
+	local_dec(&cpu_buffer->committing);
+
+	/* synchronize with interrupts */
+	barrier();
+
+	/*
+	 * Need to account for interrupts coming in between the
+	 * updating of the commit page and the clearing of the
+	 * committing counter.
+	 */
+	if (unlikely(local_read(&cpu_buffer->commits) != commits) &&
+	    !local_read(&cpu_buffer->committing)) {
+		local_inc(&cpu_buffer->committing);
+		goto again;
+	}
+}
+
 static struct ring_buffer_event *
 rb_reserve_next_event(struct ring_buffer_per_cpu *cpu_buffer,
 		      unsigned long length)
@@ -1454,6 +1489,8 @@
 	int commit = 0;
 	int nr_loops = 0;
 
+	rb_start_commit(cpu_buffer);
+
 	length = rb_calculate_event_length(length);
  again:
 	/*
@@ -1466,7 +1503,7 @@
 	 * Bail!
 	 */
 	if (RB_WARN_ON(cpu_buffer, ++nr_loops > 1000))
-		return NULL;
+		goto out_fail;
 
 	ts = rb_time_stamp(cpu_buffer->buffer, cpu_buffer->cpu);
 
@@ -1497,7 +1534,7 @@
 
 			commit = rb_add_time_stamp(cpu_buffer, &ts, &delta);
 			if (commit == -EBUSY)
-				return NULL;
+				goto out_fail;
 
 			if (commit == -EAGAIN)
 				goto again;
@@ -1511,28 +1548,19 @@
 	if (unlikely(PTR_ERR(event) == -EAGAIN))
 		goto again;
 
-	if (!event) {
-		if (unlikely(commit))
-			/*
-			 * Ouch! We needed a timestamp and it was commited. But
-			 * we didn't get our event reserved.
-			 */
-			rb_set_commit_to_write(cpu_buffer);
-		return NULL;
-	}
+	if (!event)
+		goto out_fail;
 
-	/*
-	 * If the timestamp was commited, make the commit our entry
-	 * now so that we will update it when needed.
-	 */
-	if (unlikely(commit))
-		rb_set_commit_event(cpu_buffer, event);
-	else if (!rb_is_commit(cpu_buffer, event))
+	if (!rb_event_is_commit(cpu_buffer, event))
 		delta = 0;
 
 	event->time_delta = delta;
 
 	return event;
+
+ out_fail:
+	rb_end_commit(cpu_buffer);
+	return NULL;
 }
 
 #define TRACE_RECURSIVE_DEPTH 16
@@ -1642,13 +1670,14 @@
 {
 	local_inc(&cpu_buffer->entries);
 
-	/* Only process further if we own the commit */
-	if (!rb_is_commit(cpu_buffer, event))
-		return;
+	/*
+	 * The event first in the commit queue updates the
+	 * time stamp.
+	 */
+	if (rb_event_is_commit(cpu_buffer, event))
+		cpu_buffer->write_stamp += event->time_delta;
 
-	cpu_buffer->write_stamp += event->time_delta;
-
-	rb_set_commit_to_write(cpu_buffer);
+	rb_end_commit(cpu_buffer);
 }
 
 /**
@@ -1737,15 +1766,15 @@
 	/* The event is discarded regardless */
 	rb_event_discard(event);
 
+	cpu = smp_processor_id();
+	cpu_buffer = buffer->buffers[cpu];
+
 	/*
 	 * This must only be called if the event has not been
 	 * committed yet. Thus we can assume that preemption
 	 * is still disabled.
 	 */
-	RB_WARN_ON(buffer, preemptible());
-
-	cpu = smp_processor_id();
-	cpu_buffer = buffer->buffers[cpu];
+	RB_WARN_ON(buffer, !local_read(&cpu_buffer->committing));
 
 	if (!rb_try_to_discard(cpu_buffer, event))
 		goto out;
@@ -1756,13 +1785,7 @@
 	 */
 	local_inc(&cpu_buffer->entries);
  out:
-	/*
-	 * If a write came in and pushed the tail page
-	 * we still need to update the commit pointer
-	 * if we were the commit.
-	 */
-	if (rb_is_commit(cpu_buffer, event))
-		rb_set_commit_to_write(cpu_buffer);
+	rb_end_commit(cpu_buffer);
 
 	trace_recursive_unlock();
 
@@ -2446,6 +2469,21 @@
 }
 EXPORT_SYMBOL_GPL(ring_buffer_iter_peek);
 
+static inline int rb_ok_to_lock(void)
+{
+	/*
+	 * If an NMI die dumps out the content of the ring buffer
+	 * do not grab locks. We also permanently disable the ring
+	 * buffer too. A one time deal is all you get from reading
+	 * the ring buffer from an NMI.
+	 */
+	if (likely(!in_nmi() && !oops_in_progress))
+		return 1;
+
+	tracing_off_permanent();
+	return 0;
+}
+
 /**
  * ring_buffer_peek - peek at the next event to be read
  * @buffer: The ring buffer to read
@@ -2461,14 +2499,20 @@
 	struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu];
 	struct ring_buffer_event *event;
 	unsigned long flags;
+	int dolock;
 
 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
 		return NULL;
 
+	dolock = rb_ok_to_lock();
  again:
-	spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
+	local_irq_save(flags);
+	if (dolock)
+		spin_lock(&cpu_buffer->reader_lock);
 	event = rb_buffer_peek(buffer, cpu, ts);
-	spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
+	if (dolock)
+		spin_unlock(&cpu_buffer->reader_lock);
+	local_irq_restore(flags);
 
 	if (event && event->type_len == RINGBUF_TYPE_PADDING) {
 		cpu_relax();
@@ -2520,6 +2564,9 @@
 	struct ring_buffer_per_cpu *cpu_buffer;
 	struct ring_buffer_event *event = NULL;
 	unsigned long flags;
+	int dolock;
+
+	dolock = rb_ok_to_lock();
 
  again:
 	/* might be called in atomic */
@@ -2529,7 +2576,9 @@
 		goto out;
 
 	cpu_buffer = buffer->buffers[cpu];
-	spin_lock_irqsave(&cpu_buffer->reader_lock, flags);
+	local_irq_save(flags);
+	if (dolock)
+		spin_lock(&cpu_buffer->reader_lock);
 
 	event = rb_buffer_peek(buffer, cpu, ts);
 	if (!event)
@@ -2538,7 +2587,9 @@
 	rb_advance_reader(cpu_buffer);
 
  out_unlock:
-	spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags);
+	if (dolock)
+		spin_unlock(&cpu_buffer->reader_lock);
+	local_irq_restore(flags);
 
  out:
 	preempt_enable();
@@ -2680,6 +2731,8 @@
 	cpu_buffer->overrun = 0;
 	cpu_buffer->read = 0;
 	local_set(&cpu_buffer->entries, 0);
+	local_set(&cpu_buffer->committing, 0);
+	local_set(&cpu_buffer->commits, 0);
 
 	cpu_buffer->write_stamp = 0;
 	cpu_buffer->read_stamp = 0;
@@ -2734,12 +2787,25 @@
 int ring_buffer_empty(struct ring_buffer *buffer)
 {
 	struct ring_buffer_per_cpu *cpu_buffer;
+	unsigned long flags;
+	int dolock;
 	int cpu;
+	int ret;
+
+	dolock = rb_ok_to_lock();
 
 	/* yes this is racy, but if you don't like the race, lock the buffer */
 	for_each_buffer_cpu(buffer, cpu) {
 		cpu_buffer = buffer->buffers[cpu];
-		if (!rb_per_cpu_empty(cpu_buffer))
+		local_irq_save(flags);
+		if (dolock)
+			spin_lock(&cpu_buffer->reader_lock);
+		ret = rb_per_cpu_empty(cpu_buffer);
+		if (dolock)
+			spin_unlock(&cpu_buffer->reader_lock);
+		local_irq_restore(flags);
+
+		if (!ret)
 			return 0;
 	}
 
@@ -2755,14 +2821,23 @@
 int ring_buffer_empty_cpu(struct ring_buffer *buffer, int cpu)
 {
 	struct ring_buffer_per_cpu *cpu_buffer;
+	unsigned long flags;
+	int dolock;
 	int ret;
 
 	if (!cpumask_test_cpu(cpu, buffer->cpumask))
 		return 1;
 
-	cpu_buffer = buffer->buffers[cpu];
-	ret = rb_per_cpu_empty(cpu_buffer);
+	dolock = rb_ok_to_lock();
 
+	cpu_buffer = buffer->buffers[cpu];
+	local_irq_save(flags);
+	if (dolock)
+		spin_lock(&cpu_buffer->reader_lock);
+	ret = rb_per_cpu_empty(cpu_buffer);
+	if (dolock)
+		spin_unlock(&cpu_buffer->reader_lock);
+	local_irq_restore(flags);
 
 	return ret;
 }
@@ -3108,7 +3183,7 @@
 	switch (action) {
 	case CPU_UP_PREPARE:
 	case CPU_UP_PREPARE_FROZEN:
-		if (cpu_isset(cpu, *buffer->cpumask))
+		if (cpumask_test_cpu(cpu, buffer->cpumask))
 			return NOTIFY_OK;
 
 		buffer->buffers[cpu] =
@@ -3119,7 +3194,7 @@
 			return NOTIFY_OK;
 		}
 		smp_wmb();
-		cpu_set(cpu, *buffer->cpumask);
+		cpumask_set_cpu(cpu, buffer->cpumask);
 		break;
 	case CPU_DOWN_PREPARE:
 	case CPU_DOWN_PREPARE_FROZEN:
diff --git a/kernel/trace/ring_buffer_benchmark.c b/kernel/trace/ring_buffer_benchmark.c
index 8d68e14..573d3cc 100644
--- a/kernel/trace/ring_buffer_benchmark.c
+++ b/kernel/trace/ring_buffer_benchmark.c
@@ -102,8 +102,10 @@
 			event = (void *)&rpage->data[i];
 			switch (event->type_len) {
 			case RINGBUF_TYPE_PADDING:
-				/* We don't expect any padding */
-				KILL_TEST();
+				/* failed writes may be discarded events */
+				if (!event->time_delta)
+					KILL_TEST();
+				inc = event->array[0] + 4;
 				break;
 			case RINGBUF_TYPE_TIME_EXTEND:
 				inc = 8;
@@ -119,7 +121,7 @@
 					KILL_TEST();
 					break;
 				}
-				inc = event->array[0];
+				inc = event->array[0] + 4;
 				break;
 			default:
 				entry = ring_buffer_event_data(event);
@@ -201,7 +203,7 @@
 	 * Hammer the buffer for 10 secs (this may
 	 * make the system stall)
 	 */
-	pr_info("Starting ring buffer hammer\n");
+	trace_printk("Starting ring buffer hammer\n");
 	do_gettimeofday(&start_tv);
 	do {
 		struct ring_buffer_event *event;
@@ -237,7 +239,7 @@
 #endif
 
 	} while (end_tv.tv_sec < (start_tv.tv_sec + RUN_TIME) && !kill_test);
-	pr_info("End ring buffer hammer\n");
+	trace_printk("End ring buffer hammer\n");
 
 	if (consumer) {
 		/* Init both completions here to avoid races */
@@ -260,49 +262,50 @@
 	overruns = ring_buffer_overruns(buffer);
 
 	if (kill_test)
-		pr_info("ERROR!\n");
-	pr_info("Time:     %lld (usecs)\n", time);
-	pr_info("Overruns: %lld\n", overruns);
+		trace_printk("ERROR!\n");
+	trace_printk("Time:     %lld (usecs)\n", time);
+	trace_printk("Overruns: %lld\n", overruns);
 	if (disable_reader)
-		pr_info("Read:     (reader disabled)\n");
+		trace_printk("Read:     (reader disabled)\n");
 	else
-		pr_info("Read:     %ld  (by %s)\n", read,
+		trace_printk("Read:     %ld  (by %s)\n", read,
 			read_events ? "events" : "pages");
-	pr_info("Entries:  %lld\n", entries);
-	pr_info("Total:    %lld\n", entries + overruns + read);
-	pr_info("Missed:   %ld\n", missed);
-	pr_info("Hit:      %ld\n", hit);
+	trace_printk("Entries:  %lld\n", entries);
+	trace_printk("Total:    %lld\n", entries + overruns + read);
+	trace_printk("Missed:   %ld\n", missed);
+	trace_printk("Hit:      %ld\n", hit);
 
 	/* Convert time from usecs to millisecs */
 	do_div(time, USEC_PER_MSEC);
 	if (time)
 		hit /= (long)time;
 	else
-		pr_info("TIME IS ZERO??\n");
+		trace_printk("TIME IS ZERO??\n");
 
-	pr_info("Entries per millisec: %ld\n", hit);
+	trace_printk("Entries per millisec: %ld\n", hit);
 
 	if (hit) {
 		/* Calculate the average time in nanosecs */
 		avg = NSEC_PER_MSEC / hit;
-		pr_info("%ld ns per entry\n", avg);
+		trace_printk("%ld ns per entry\n", avg);
 	}
 
 	if (missed) {
 		if (time)
 			missed /= (long)time;
 
-		pr_info("Total iterations per millisec: %ld\n", hit + missed);
+		trace_printk("Total iterations per millisec: %ld\n",
+			     hit + missed);
 
 		/* it is possible that hit + missed will overflow and be zero */
 		if (!(hit + missed)) {
-			pr_info("hit + missed overflowed and totalled zero!\n");
+			trace_printk("hit + missed overflowed and totalled zero!\n");
 			hit--; /* make it non zero */
 		}
 
 		/* Caculate the average time in nanosecs */
 		avg = NSEC_PER_MSEC / (hit + missed);
-		pr_info("%ld ns per entry\n", avg);
+		trace_printk("%ld ns per entry\n", avg);
 	}
 }
 
@@ -353,7 +356,7 @@
 
 		ring_buffer_producer();
 
-		pr_info("Sleeping for 10 secs\n");
+		trace_printk("Sleeping for 10 secs\n");
 		set_current_state(TASK_INTERRUPTIBLE);
 		schedule_timeout(HZ * SLEEP_TIME);
 		__set_current_state(TASK_RUNNING);
diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c
index c1878bf..076fa6f 100644
--- a/kernel/trace/trace.c
+++ b/kernel/trace/trace.c
@@ -2191,11 +2191,12 @@
 	if (!alloc_cpumask_var(&tracing_cpumask_new, GFP_KERNEL))
 		return -ENOMEM;
 
-	mutex_lock(&tracing_cpumask_update_lock);
 	err = cpumask_parse_user(ubuf, count, tracing_cpumask_new);
 	if (err)
 		goto err_unlock;
 
+	mutex_lock(&tracing_cpumask_update_lock);
+
 	local_irq_disable();
 	__raw_spin_lock(&ftrace_max_lock);
 	for_each_tracing_cpu(cpu) {
@@ -2223,8 +2224,7 @@
 	return count;
 
 err_unlock:
-	mutex_unlock(&tracing_cpumask_update_lock);
-	free_cpumask_var(tracing_cpumask);
+	free_cpumask_var(tracing_cpumask_new);
 
 	return err;
 }
@@ -3626,7 +3626,7 @@
 	struct trace_seq *s;
 	unsigned long cnt;
 
-	s = kmalloc(sizeof(*s), GFP_ATOMIC);
+	s = kmalloc(sizeof(*s), GFP_KERNEL);
 	if (!s)
 		return ENOMEM;
 
diff --git a/kernel/trace/trace_events_filter.c b/kernel/trace/trace_events_filter.c
index db6e54b..936c621 100644
--- a/kernel/trace/trace_events_filter.c
+++ b/kernel/trace/trace_events_filter.c
@@ -27,8 +27,6 @@
 #include "trace.h"
 #include "trace_output.h"
 
-static DEFINE_MUTEX(filter_mutex);
-
 enum filter_op_ids
 {
 	OP_OR,
@@ -178,7 +176,7 @@
 static int filter_pred_strloc(struct filter_pred *pred, void *event,
 			      int val1, int val2)
 {
-	int str_loc = *(int *)(event + pred->offset);
+	unsigned short str_loc = *(unsigned short *)(event + pred->offset);
 	char *addr = (char *)(event + str_loc);
 	int cmp, match;
 
@@ -294,12 +292,12 @@
 {
 	struct event_filter *filter = call->filter;
 
-	mutex_lock(&filter_mutex);
+	mutex_lock(&event_mutex);
 	if (filter->filter_string)
 		trace_seq_printf(s, "%s\n", filter->filter_string);
 	else
 		trace_seq_printf(s, "none\n");
-	mutex_unlock(&filter_mutex);
+	mutex_unlock(&event_mutex);
 }
 
 void print_subsystem_event_filter(struct event_subsystem *system,
@@ -307,12 +305,12 @@
 {
 	struct event_filter *filter = system->filter;
 
-	mutex_lock(&filter_mutex);
+	mutex_lock(&event_mutex);
 	if (filter->filter_string)
 		trace_seq_printf(s, "%s\n", filter->filter_string);
 	else
 		trace_seq_printf(s, "none\n");
-	mutex_unlock(&filter_mutex);
+	mutex_unlock(&event_mutex);
 }
 
 static struct ftrace_event_field *
@@ -381,6 +379,7 @@
 			filter_free_pred(filter->preds[i]);
 	}
 	kfree(filter->preds);
+	kfree(filter->filter_string);
 	kfree(filter);
 	call->filter = NULL;
 }
@@ -433,7 +432,6 @@
 		filter->n_preds = 0;
 	}
 
-	mutex_lock(&event_mutex);
 	list_for_each_entry(call, &ftrace_events, list) {
 		if (!call->define_fields)
 			continue;
@@ -443,7 +441,6 @@
 			remove_filter_string(call->filter);
 		}
 	}
-	mutex_unlock(&event_mutex);
 }
 
 static int filter_add_pred_fn(struct filter_parse_state *ps,
@@ -546,6 +543,7 @@
 	filter_pred_fn_t fn;
 	unsigned long long val;
 	int string_type;
+	int ret;
 
 	pred->fn = filter_pred_none;
 
@@ -581,7 +579,11 @@
 			pred->not = 1;
 		return filter_add_pred_fn(ps, call, pred, fn);
 	} else {
-		if (strict_strtoull(pred->str_val, 0, &val)) {
+		if (field->is_signed)
+			ret = strict_strtoll(pred->str_val, 0, &val);
+		else
+			ret = strict_strtoull(pred->str_val, 0, &val);
+		if (ret) {
 			parse_error(ps, FILT_ERR_ILLEGAL_INTVAL, 0);
 			return -EINVAL;
 		}
@@ -625,7 +627,6 @@
 	filter->preds[filter->n_preds] = pred;
 	filter->n_preds++;
 
-	mutex_lock(&event_mutex);
 	list_for_each_entry(call, &ftrace_events, list) {
 
 		if (!call->define_fields)
@@ -636,14 +637,12 @@
 
 		err = filter_add_pred(ps, call, pred);
 		if (err) {
-			mutex_unlock(&event_mutex);
 			filter_free_subsystem_preds(system);
 			parse_error(ps, FILT_ERR_BAD_SUBSYS_FILTER, 0);
 			goto out;
 		}
 		replace_filter_string(call->filter, filter_string);
 	}
-	mutex_unlock(&event_mutex);
 out:
 	return err;
 }
@@ -1070,12 +1069,12 @@
 
 	struct filter_parse_state *ps;
 
-	mutex_lock(&filter_mutex);
+	mutex_lock(&event_mutex);
 
 	if (!strcmp(strstrip(filter_string), "0")) {
 		filter_disable_preds(call);
 		remove_filter_string(call->filter);
-		mutex_unlock(&filter_mutex);
+		mutex_unlock(&event_mutex);
 		return 0;
 	}
 
@@ -1103,7 +1102,7 @@
 	postfix_clear(ps);
 	kfree(ps);
 out_unlock:
-	mutex_unlock(&filter_mutex);
+	mutex_unlock(&event_mutex);
 
 	return err;
 }
@@ -1115,12 +1114,12 @@
 
 	struct filter_parse_state *ps;
 
-	mutex_lock(&filter_mutex);
+	mutex_lock(&event_mutex);
 
 	if (!strcmp(strstrip(filter_string), "0")) {
 		filter_free_subsystem_preds(system);
 		remove_filter_string(system->filter);
-		mutex_unlock(&filter_mutex);
+		mutex_unlock(&event_mutex);
 		return 0;
 	}
 
@@ -1148,7 +1147,7 @@
 	postfix_clear(ps);
 	kfree(ps);
 out_unlock:
-	mutex_unlock(&filter_mutex);
+	mutex_unlock(&event_mutex);
 
 	return err;
 }
diff --git a/kernel/trace/trace_functions.c b/kernel/trace/trace_functions.c
index c9a0b7d..90f1347 100644
--- a/kernel/trace/trace_functions.c
+++ b/kernel/trace/trace_functions.c
@@ -193,9 +193,11 @@
 static void tracing_stop_function_trace(void)
 {
 	ftrace_function_enabled = 0;
-	/* OK if they are not registered */
-	unregister_ftrace_function(&trace_stack_ops);
-	unregister_ftrace_function(&trace_ops);
+
+	if (func_flags.val & TRACE_FUNC_OPT_STACK)
+		unregister_ftrace_function(&trace_stack_ops);
+	else
+		unregister_ftrace_function(&trace_ops);
 }
 
 static int func_set_flag(u32 old_flags, u32 bit, int set)
diff --git a/kernel/trace/trace_functions_graph.c b/kernel/trace/trace_functions_graph.c
index 8b59241..d2249ab 100644
--- a/kernel/trace/trace_functions_graph.c
+++ b/kernel/trace/trace_functions_graph.c
@@ -57,7 +57,8 @@
 
 /* Add a function return address to the trace stack on thread info.*/
 int
-ftrace_push_return_trace(unsigned long ret, unsigned long func, int *depth)
+ftrace_push_return_trace(unsigned long ret, unsigned long func, int *depth,
+			 unsigned long frame_pointer)
 {
 	unsigned long long calltime;
 	int index;
@@ -85,6 +86,7 @@
 	current->ret_stack[index].func = func;
 	current->ret_stack[index].calltime = calltime;
 	current->ret_stack[index].subtime = 0;
+	current->ret_stack[index].fp = frame_pointer;
 	*depth = index;
 
 	return 0;
@@ -92,7 +94,8 @@
 
 /* Retrieve a function return address to the trace stack on thread info.*/
 static void
-ftrace_pop_return_trace(struct ftrace_graph_ret *trace, unsigned long *ret)
+ftrace_pop_return_trace(struct ftrace_graph_ret *trace, unsigned long *ret,
+			unsigned long frame_pointer)
 {
 	int index;
 
@@ -106,6 +109,31 @@
 		return;
 	}
 
+#ifdef CONFIG_HAVE_FUNCTION_GRAPH_FP_TEST
+	/*
+	 * The arch may choose to record the frame pointer used
+	 * and check it here to make sure that it is what we expect it
+	 * to be. If gcc does not set the place holder of the return
+	 * address in the frame pointer, and does a copy instead, then
+	 * the function graph trace will fail. This test detects this
+	 * case.
+	 *
+	 * Currently, x86_32 with optimize for size (-Os) makes the latest
+	 * gcc do the above.
+	 */
+	if (unlikely(current->ret_stack[index].fp != frame_pointer)) {
+		ftrace_graph_stop();
+		WARN(1, "Bad frame pointer: expected %lx, received %lx\n"
+		     "  from func %pF return to %lx\n",
+		     current->ret_stack[index].fp,
+		     frame_pointer,
+		     (void *)current->ret_stack[index].func,
+		     current->ret_stack[index].ret);
+		*ret = (unsigned long)panic;
+		return;
+	}
+#endif
+
 	*ret = current->ret_stack[index].ret;
 	trace->func = current->ret_stack[index].func;
 	trace->calltime = current->ret_stack[index].calltime;
@@ -117,12 +145,12 @@
  * Send the trace to the ring-buffer.
  * @return the original return address.
  */
-unsigned long ftrace_return_to_handler(void)
+unsigned long ftrace_return_to_handler(unsigned long frame_pointer)
 {
 	struct ftrace_graph_ret trace;
 	unsigned long ret;
 
-	ftrace_pop_return_trace(&trace, &ret);
+	ftrace_pop_return_trace(&trace, &ret, frame_pointer);
 	trace.rettime = trace_clock_local();
 	ftrace_graph_return(&trace);
 	barrier();
diff --git a/kernel/utsname.c b/kernel/utsname.c
index 815237a..8a82b4b 100644
--- a/kernel/utsname.c
+++ b/kernel/utsname.c
@@ -15,6 +15,16 @@
 #include <linux/err.h>
 #include <linux/slab.h>
 
+static struct uts_namespace *create_uts_ns(void)
+{
+	struct uts_namespace *uts_ns;
+
+	uts_ns = kmalloc(sizeof(struct uts_namespace), GFP_KERNEL);
+	if (uts_ns)
+		kref_init(&uts_ns->kref);
+	return uts_ns;
+}
+
 /*
  * Clone a new ns copying an original utsname, setting refcount to 1
  * @old_ns: namespace to clone
@@ -24,14 +34,13 @@
 {
 	struct uts_namespace *ns;
 
-	ns = kmalloc(sizeof(struct uts_namespace), GFP_KERNEL);
+	ns = create_uts_ns();
 	if (!ns)
 		return ERR_PTR(-ENOMEM);
 
 	down_read(&uts_sem);
 	memcpy(&ns->name, &old_ns->name, sizeof(ns->name));
 	up_read(&uts_sem);
-	kref_init(&ns->kref);
 	return ns;
 }
 
diff --git a/lib/Makefile b/lib/Makefile
index 8e9bcf9..b6d1857 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -21,7 +21,7 @@
 
 obj-y += bcd.o div64.o sort.o parser.o halfmd4.o debug_locks.o random32.o \
 	 bust_spinlocks.o hexdump.o kasprintf.o bitmap.o scatterlist.o \
-	 string_helpers.o
+	 string_helpers.o gcd.o
 
 ifeq ($(CONFIG_DEBUG_KOBJECT),y)
 CFLAGS_kobject.o += -DDEBUG
diff --git a/lib/gcd.c b/lib/gcd.c
new file mode 100644
index 0000000..f879033
--- /dev/null
+++ b/lib/gcd.c
@@ -0,0 +1,18 @@
+#include <linux/kernel.h>
+#include <linux/gcd.h>
+#include <linux/module.h>
+
+/* Greatest common divisor */
+unsigned long gcd(unsigned long a, unsigned long b)
+{
+	unsigned long r;
+
+	if (a < b)
+		swap(a, b);
+	while ((r = a % b) != 0) {
+		a = b;
+		b = r;
+	}
+	return b;
+}
+EXPORT_SYMBOL_GPL(gcd);
diff --git a/mm/bootmem.c b/mm/bootmem.c
index 282df0a..d2a9ce9 100644
--- a/mm/bootmem.c
+++ b/mm/bootmem.c
@@ -536,11 +536,15 @@
 		return kzalloc(size, GFP_NOWAIT);
 
 #ifdef CONFIG_HAVE_ARCH_BOOTMEM
-	bootmem_data_t *p_bdata;
+	{
+		bootmem_data_t *p_bdata;
 
-	p_bdata = bootmem_arch_preferred_node(bdata, size, align, goal, limit);
-	if (p_bdata)
-		return alloc_bootmem_core(p_bdata, size, align, goal, limit);
+		p_bdata = bootmem_arch_preferred_node(bdata, size, align,
+							goal, limit);
+		if (p_bdata)
+			return alloc_bootmem_core(p_bdata, size, align,
+							goal, limit);
+	}
 #endif
 	return NULL;
 }
diff --git a/mm/kmemleak.c b/mm/kmemleak.c
index 58ec86c..ec759b6 100644
--- a/mm/kmemleak.c
+++ b/mm/kmemleak.c
@@ -109,6 +109,9 @@
 
 #define BYTES_PER_POINTER	sizeof(void *)
 
+/* GFP bitmask for kmemleak internal allocations */
+#define GFP_KMEMLEAK_MASK	(GFP_KERNEL | GFP_ATOMIC)
+
 /* scanning area inside a memory block */
 struct kmemleak_scan_area {
 	struct hlist_node node;
@@ -199,9 +202,9 @@
 static int reported_leaks;
 
 /*
- * Early object allocation/freeing logging. Kkmemleak is initialized after the
+ * Early object allocation/freeing logging. Kmemleak is initialized after the
  * kernel allocator. However, both the kernel allocator and kmemleak may
- * allocate memory blocks which need to be tracked. Kkmemleak defines an
+ * allocate memory blocks which need to be tracked. Kmemleak defines an
  * arbitrary buffer to hold the allocation/freeing information before it is
  * fully initialized.
  */
@@ -245,10 +248,10 @@
 
 /*
  * Macro invoked when a serious kmemleak condition occured and cannot be
- * recovered from. Kkmemleak will be disabled and further allocation/freeing
+ * recovered from. Kmemleak will be disabled and further allocation/freeing
  * tracing no longer available.
  */
-#define kmemleak_panic(x...)	do {	\
+#define kmemleak_stop(x...)	do {	\
 	kmemleak_warn(x);		\
 	kmemleak_disable();		\
 } while (0)
@@ -462,10 +465,10 @@
 	struct prio_tree_node *node;
 	struct stack_trace trace;
 
-	object = kmem_cache_alloc(object_cache, gfp & ~GFP_SLAB_BUG_MASK);
+	object = kmem_cache_alloc(object_cache, gfp & GFP_KMEMLEAK_MASK);
 	if (!object) {
-		kmemleak_panic("kmemleak: Cannot allocate a kmemleak_object "
-			       "structure\n");
+		kmemleak_stop("kmemleak: Cannot allocate a kmemleak_object "
+			      "structure\n");
 		return;
 	}
 
@@ -524,8 +527,8 @@
 	if (node != &object->tree_node) {
 		unsigned long flags;
 
-		kmemleak_panic("kmemleak: Cannot insert 0x%lx into the object "
-			       "search tree (already existing)\n", ptr);
+		kmemleak_stop("kmemleak: Cannot insert 0x%lx into the object "
+			      "search tree (already existing)\n", ptr);
 		object = lookup_object(ptr, 1);
 		spin_lock_irqsave(&object->lock, flags);
 		dump_object_info(object);
@@ -636,7 +639,7 @@
 		return;
 	}
 
-	area = kmem_cache_alloc(scan_area_cache, gfp & ~GFP_SLAB_BUG_MASK);
+	area = kmem_cache_alloc(scan_area_cache, gfp & GFP_KMEMLEAK_MASK);
 	if (!area) {
 		kmemleak_warn("kmemleak: Cannot allocate a scan area\n");
 		goto out;
@@ -696,7 +699,7 @@
 	struct early_log *log;
 
 	if (crt_early_log >= ARRAY_SIZE(early_log)) {
-		kmemleak_panic("kmemleak: Early log buffer exceeded\n");
+		kmemleak_stop("kmemleak: Early log buffer exceeded\n");
 		return;
 	}
 
@@ -1404,7 +1407,7 @@
 early_param("kmemleak", kmemleak_boot_config);
 
 /*
- * Kkmemleak initialization.
+ * Kmemleak initialization.
  */
 void __init kmemleak_init(void)
 {
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index 70db6e0..e2fa20d 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -45,7 +45,7 @@
 #define MEM_CGROUP_RECLAIM_RETRIES	5
 
 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
-/* Turned on only when memory cgroup is enabled && really_do_swap_account = 0 */
+/* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
 int do_swap_account __read_mostly;
 static int really_do_swap_account __initdata = 1; /* for remember boot option*/
 #else
@@ -62,7 +62,8 @@
 	 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
 	 */
 	MEM_CGROUP_STAT_CACHE, 	   /* # of pages charged as cache */
-	MEM_CGROUP_STAT_RSS,	   /* # of pages charged as rss */
+	MEM_CGROUP_STAT_RSS,	   /* # of pages charged as anon rss */
+	MEM_CGROUP_STAT_MAPPED_FILE,  /* # of pages charged as file rss */
 	MEM_CGROUP_STAT_PGPGIN_COUNT,	/* # of pages paged in */
 	MEM_CGROUP_STAT_PGPGOUT_COUNT,	/* # of pages paged out */
 
@@ -176,6 +177,9 @@
 
 	unsigned int	swappiness;
 
+	/* set when res.limit == memsw.limit */
+	bool		memsw_is_minimum;
+
 	/*
 	 * statistics. This must be placed at the end of memcg.
 	 */
@@ -188,6 +192,7 @@
 	MEM_CGROUP_CHARGE_TYPE_SHMEM,	/* used by page migration of shmem */
 	MEM_CGROUP_CHARGE_TYPE_FORCE,	/* used by force_empty */
 	MEM_CGROUP_CHARGE_TYPE_SWAPOUT,	/* for accounting swapcache */
+	MEM_CGROUP_CHARGE_TYPE_DROP,	/* a page was unused swap cache */
 	NR_CHARGE_TYPE,
 };
 
@@ -644,6 +649,7 @@
 	int zid = zone_idx(z);
 	struct mem_cgroup_per_zone *mz;
 	int lru = LRU_FILE * !!file + !!active;
+	int ret;
 
 	BUG_ON(!mem_cont);
 	mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
@@ -661,9 +667,19 @@
 			continue;
 
 		scan++;
-		if (__isolate_lru_page(page, mode, file) == 0) {
+		ret = __isolate_lru_page(page, mode, file);
+		switch (ret) {
+		case 0:
 			list_move(&page->lru, dst);
+			mem_cgroup_del_lru(page);
 			nr_taken++;
+			break;
+		case -EBUSY:
+			/* we don't affect global LRU but rotate in our LRU */
+			mem_cgroup_rotate_lru_list(page, page_lru(page));
+			break;
+		default:
+			break;
 		}
 	}
 
@@ -845,6 +861,10 @@
 	int ret, total = 0;
 	int loop = 0;
 
+	/* If memsw_is_minimum==1, swap-out is of-no-use. */
+	if (root_mem->memsw_is_minimum)
+		noswap = true;
+
 	while (loop < 2) {
 		victim = mem_cgroup_select_victim(root_mem);
 		if (victim == root_mem)
@@ -900,6 +920,44 @@
 	mem_cgroup_walk_tree(mem, NULL, record_last_oom_cb);
 }
 
+/*
+ * Currently used to update mapped file statistics, but the routine can be
+ * generalized to update other statistics as well.
+ */
+void mem_cgroup_update_mapped_file_stat(struct page *page, int val)
+{
+	struct mem_cgroup *mem;
+	struct mem_cgroup_stat *stat;
+	struct mem_cgroup_stat_cpu *cpustat;
+	int cpu;
+	struct page_cgroup *pc;
+
+	if (!page_is_file_cache(page))
+		return;
+
+	pc = lookup_page_cgroup(page);
+	if (unlikely(!pc))
+		return;
+
+	lock_page_cgroup(pc);
+	mem = pc->mem_cgroup;
+	if (!mem)
+		goto done;
+
+	if (!PageCgroupUsed(pc))
+		goto done;
+
+	/*
+	 * Preemption is already disabled, we don't need get_cpu()
+	 */
+	cpu = smp_processor_id();
+	stat = &mem->stat;
+	cpustat = &stat->cpustat[cpu];
+
+	__mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_MAPPED_FILE, val);
+done:
+	unlock_page_cgroup(pc);
+}
 
 /*
  * Unlike exported interface, "oom" parameter is added. if oom==true,
@@ -1098,6 +1156,10 @@
 	struct mem_cgroup_per_zone *from_mz, *to_mz;
 	int nid, zid;
 	int ret = -EBUSY;
+	struct page *page;
+	int cpu;
+	struct mem_cgroup_stat *stat;
+	struct mem_cgroup_stat_cpu *cpustat;
 
 	VM_BUG_ON(from == to);
 	VM_BUG_ON(PageLRU(pc->page));
@@ -1118,6 +1180,23 @@
 
 	res_counter_uncharge(&from->res, PAGE_SIZE);
 	mem_cgroup_charge_statistics(from, pc, false);
+
+	page = pc->page;
+	if (page_is_file_cache(page) && page_mapped(page)) {
+		cpu = smp_processor_id();
+		/* Update mapped_file data for mem_cgroup "from" */
+		stat = &from->stat;
+		cpustat = &stat->cpustat[cpu];
+		__mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_MAPPED_FILE,
+						-1);
+
+		/* Update mapped_file data for mem_cgroup "to" */
+		stat = &to->stat;
+		cpustat = &stat->cpustat[cpu];
+		__mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_MAPPED_FILE,
+						1);
+	}
+
 	if (do_swap_account)
 		res_counter_uncharge(&from->memsw, PAGE_SIZE);
 	css_put(&from->css);
@@ -1433,6 +1512,7 @@
 
 	switch (ctype) {
 	case MEM_CGROUP_CHARGE_TYPE_MAPPED:
+	case MEM_CGROUP_CHARGE_TYPE_DROP:
 		if (page_mapped(page))
 			goto unlock_out;
 		break;
@@ -1496,18 +1576,23 @@
  * called after __delete_from_swap_cache() and drop "page" account.
  * memcg information is recorded to swap_cgroup of "ent"
  */
-void mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent)
+void
+mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
 {
 	struct mem_cgroup *memcg;
+	int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
 
-	memcg = __mem_cgroup_uncharge_common(page,
-					MEM_CGROUP_CHARGE_TYPE_SWAPOUT);
+	if (!swapout) /* this was a swap cache but the swap is unused ! */
+		ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
+
+	memcg = __mem_cgroup_uncharge_common(page, ctype);
+
 	/* record memcg information */
-	if (do_swap_account && memcg) {
+	if (do_swap_account && swapout && memcg) {
 		swap_cgroup_record(ent, css_id(&memcg->css));
 		mem_cgroup_get(memcg);
 	}
-	if (memcg)
+	if (swapout && memcg)
 		css_put(&memcg->css);
 }
 #endif
@@ -1685,6 +1770,12 @@
 			break;
 		}
 		ret = res_counter_set_limit(&memcg->res, val);
+		if (!ret) {
+			if (memswlimit == val)
+				memcg->memsw_is_minimum = true;
+			else
+				memcg->memsw_is_minimum = false;
+		}
 		mutex_unlock(&set_limit_mutex);
 
 		if (!ret)
@@ -1703,16 +1794,14 @@
 	return ret;
 }
 
-int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
-				unsigned long long val)
+static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
+					unsigned long long val)
 {
 	int retry_count;
 	u64 memlimit, oldusage, curusage;
 	int children = mem_cgroup_count_children(memcg);
 	int ret = -EBUSY;
 
-	if (!do_swap_account)
-		return -EINVAL;
 	/* see mem_cgroup_resize_res_limit */
  	retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
 	oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
@@ -1734,6 +1823,12 @@
 			break;
 		}
 		ret = res_counter_set_limit(&memcg->memsw, val);
+		if (!ret) {
+			if (memlimit == val)
+				memcg->memsw_is_minimum = true;
+			else
+				memcg->memsw_is_minimum = false;
+		}
 		mutex_unlock(&set_limit_mutex);
 
 		if (!ret)
@@ -1947,8 +2042,7 @@
 		val = res_counter_read_u64(&mem->res, name);
 		break;
 	case _MEMSWAP:
-		if (do_swap_account)
-			val = res_counter_read_u64(&mem->memsw, name);
+		val = res_counter_read_u64(&mem->memsw, name);
 		break;
 	default:
 		BUG();
@@ -2046,6 +2140,7 @@
 enum {
 	MCS_CACHE,
 	MCS_RSS,
+	MCS_MAPPED_FILE,
 	MCS_PGPGIN,
 	MCS_PGPGOUT,
 	MCS_INACTIVE_ANON,
@@ -2066,6 +2161,7 @@
 } memcg_stat_strings[NR_MCS_STAT] = {
 	{"cache", "total_cache"},
 	{"rss", "total_rss"},
+	{"mapped_file", "total_mapped_file"},
 	{"pgpgin", "total_pgpgin"},
 	{"pgpgout", "total_pgpgout"},
 	{"inactive_anon", "total_inactive_anon"},
@@ -2086,6 +2182,8 @@
 	s->stat[MCS_CACHE] += val * PAGE_SIZE;
 	val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
 	s->stat[MCS_RSS] += val * PAGE_SIZE;
+	val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_MAPPED_FILE);
+	s->stat[MCS_MAPPED_FILE] += val * PAGE_SIZE;
 	val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGIN_COUNT);
 	s->stat[MCS_PGPGIN] += val;
 	val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGOUT_COUNT);
diff --git a/mm/page_alloc.c b/mm/page_alloc.c
index a5f3c27..6f0753f 100644
--- a/mm/page_alloc.c
+++ b/mm/page_alloc.c
@@ -73,6 +73,7 @@
 unsigned long totalreserve_pages __read_mostly;
 unsigned long highest_memmap_pfn __read_mostly;
 int percpu_pagelist_fraction;
+gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
 
 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
 int pageblock_order __read_mostly;
@@ -1863,6 +1864,8 @@
 	struct page *page;
 	int migratetype = allocflags_to_migratetype(gfp_mask);
 
+	gfp_mask &= gfp_allowed_mask;
+
 	lockdep_trace_alloc(gfp_mask);
 
 	might_sleep_if(gfp_mask & __GFP_WAIT);
diff --git a/mm/page_cgroup.c b/mm/page_cgroup.c
index 11a8a10..f22b4eb 100644
--- a/mm/page_cgroup.c
+++ b/mm/page_cgroup.c
@@ -83,12 +83,12 @@
 			goto fail;
 	}
 	printk(KERN_INFO "allocated %ld bytes of page_cgroup\n", total_usage);
-	printk(KERN_INFO "please try cgroup_disable=memory option if you"
-	" don't want\n");
+	printk(KERN_INFO "please try 'cgroup_disable=memory' option if you"
+	" don't want memory cgroups\n");
 	return;
 fail:
-	printk(KERN_CRIT "allocation of page_cgroup was failed.\n");
-	printk(KERN_CRIT "please try cgroup_disable=memory boot option\n");
+	printk(KERN_CRIT "allocation of page_cgroup failed.\n");
+	printk(KERN_CRIT "please try 'cgroup_disable=memory' boot option\n");
 	panic("Out of memory");
 }
 
@@ -99,6 +99,8 @@
 	unsigned long pfn = page_to_pfn(page);
 	struct mem_section *section = __pfn_to_section(pfn);
 
+	if (!section->page_cgroup)
+		return NULL;
 	return section->page_cgroup + pfn;
 }
 
@@ -252,14 +254,14 @@
 		fail = init_section_page_cgroup(pfn);
 	}
 	if (fail) {
-		printk(KERN_CRIT "try cgroup_disable=memory boot option\n");
+		printk(KERN_CRIT "try 'cgroup_disable=memory' boot option\n");
 		panic("Out of memory");
 	} else {
 		hotplug_memory_notifier(page_cgroup_callback, 0);
 	}
 	printk(KERN_INFO "allocated %ld bytes of page_cgroup\n", total_usage);
-	printk(KERN_INFO "please try cgroup_disable=memory option if you don't"
-	" want\n");
+	printk(KERN_INFO "please try 'cgroup_disable=memory' option if you don't"
+	" want memory cgroups\n");
 }
 
 void __meminit pgdat_page_cgroup_init(struct pglist_data *pgdat)
@@ -309,8 +311,6 @@
 	struct swap_cgroup_ctrl *ctrl;
 	unsigned long idx, max;
 
-	if (!do_swap_account)
-		return 0;
 	ctrl = &swap_cgroup_ctrl[type];
 
 	for (idx = 0; idx < ctrl->length; idx++) {
@@ -347,9 +347,6 @@
 	struct swap_cgroup *sc;
 	unsigned short old;
 
-	if (!do_swap_account)
-		return 0;
-
 	ctrl = &swap_cgroup_ctrl[type];
 
 	mappage = ctrl->map[idx];
@@ -378,9 +375,6 @@
 	struct swap_cgroup *sc;
 	unsigned short ret;
 
-	if (!do_swap_account)
-		return 0;
-
 	ctrl = &swap_cgroup_ctrl[type];
 	mappage = ctrl->map[idx];
 	sc = page_address(mappage);
diff --git a/mm/rmap.c b/mm/rmap.c
index c9ccc1a..836c6c6 100644
--- a/mm/rmap.c
+++ b/mm/rmap.c
@@ -703,8 +703,10 @@
  */
 void page_add_file_rmap(struct page *page)
 {
-	if (atomic_inc_and_test(&page->_mapcount))
+	if (atomic_inc_and_test(&page->_mapcount)) {
 		__inc_zone_page_state(page, NR_FILE_MAPPED);
+		mem_cgroup_update_mapped_file_stat(page, 1);
+	}
 }
 
 #ifdef CONFIG_DEBUG_VM
@@ -753,6 +755,7 @@
 			mem_cgroup_uncharge_page(page);
 		__dec_zone_page_state(page,
 			PageAnon(page) ? NR_ANON_PAGES : NR_FILE_MAPPED);
+		mem_cgroup_update_mapped_file_stat(page, -1);
 		/*
 		 * It would be tidy to reset the PageAnon mapping here,
 		 * but that might overwrite a racing page_add_anon_rmap
diff --git a/mm/slab.c b/mm/slab.c
index f257d4d..e74a16e 100644
--- a/mm/slab.c
+++ b/mm/slab.c
@@ -305,12 +305,6 @@
 };
 
 /*
- * The slab allocator is initialized with interrupts disabled. Therefore, make
- * sure early boot allocations don't accidentally enable interrupts.
- */
-static gfp_t slab_gfp_mask __read_mostly = SLAB_GFP_BOOT_MASK;
-
-/*
  * Need this for bootstrapping a per node allocator.
  */
 #define NUM_INIT_LISTS (3 * MAX_NUMNODES)
@@ -1559,11 +1553,6 @@
 {
 	struct kmem_cache *cachep;
 
-	/*
-	 * Interrupts are enabled now so all GFP allocations are safe.
-	 */
-	slab_gfp_mask = __GFP_BITS_MASK;
-
 	/* 6) resize the head arrays to their final sizes */
 	mutex_lock(&cache_chain_mutex);
 	list_for_each_entry(cachep, &cache_chain, next)
@@ -2308,6 +2297,15 @@
 		/* really off slab. No need for manual alignment */
 		slab_size =
 		    cachep->num * sizeof(kmem_bufctl_t) + sizeof(struct slab);
+
+#ifdef CONFIG_PAGE_POISONING
+		/* If we're going to use the generic kernel_map_pages()
+		 * poisoning, then it's going to smash the contents of
+		 * the redzone and userword anyhow, so switch them off.
+		 */
+		if (size % PAGE_SIZE == 0 && flags & SLAB_POISON)
+			flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
+#endif
 	}
 
 	cachep->colour_off = cache_line_size();
@@ -3298,7 +3296,7 @@
 	unsigned long save_flags;
 	void *ptr;
 
-	flags &= slab_gfp_mask;
+	flags &= gfp_allowed_mask;
 
 	lockdep_trace_alloc(flags);
 
@@ -3383,7 +3381,7 @@
 	unsigned long save_flags;
 	void *objp;
 
-	flags &= slab_gfp_mask;
+	flags &= gfp_allowed_mask;
 
 	lockdep_trace_alloc(flags);
 
diff --git a/mm/slob.c b/mm/slob.c
index 64f6db1..c78742d 100644
--- a/mm/slob.c
+++ b/mm/slob.c
@@ -133,17 +133,17 @@
  */
 static inline int is_slob_page(struct slob_page *sp)
 {
-	return PageSlobPage((struct page *)sp);
+	return PageSlab((struct page *)sp);
 }
 
 static inline void set_slob_page(struct slob_page *sp)
 {
-	__SetPageSlobPage((struct page *)sp);
+	__SetPageSlab((struct page *)sp);
 }
 
 static inline void clear_slob_page(struct slob_page *sp)
 {
-	__ClearPageSlobPage((struct page *)sp);
+	__ClearPageSlab((struct page *)sp);
 }
 
 static inline struct slob_page *slob_page(const void *addr)
diff --git a/mm/slub.c b/mm/slub.c
index 2701419..ce62b77 100644
--- a/mm/slub.c
+++ b/mm/slub.c
@@ -179,12 +179,6 @@
 	SYSFS		/* Sysfs up */
 } slab_state = DOWN;
 
-/*
- * The slab allocator is initialized with interrupts disabled. Therefore, make
- * sure early boot allocations don't accidentally enable interrupts.
- */
-static gfp_t slab_gfp_mask __read_mostly = SLAB_GFP_BOOT_MASK;
-
 /* A list of all slab caches on the system */
 static DECLARE_RWSEM(slub_lock);
 static LIST_HEAD(slab_caches);
@@ -840,6 +834,11 @@
 	return atomic_long_read(&n->nr_slabs);
 }
 
+static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
+{
+	return atomic_long_read(&n->nr_slabs);
+}
+
 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
 {
 	struct kmem_cache_node *n = get_node(s, node);
@@ -1058,6 +1057,8 @@
 
 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
 							{ return 0; }
+static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
+							{ return 0; }
 static inline void inc_slabs_node(struct kmem_cache *s, int node,
 							int objects) {}
 static inline void dec_slabs_node(struct kmem_cache *s, int node,
@@ -1514,6 +1515,65 @@
 	return 1;
 }
 
+static int count_free(struct page *page)
+{
+	return page->objects - page->inuse;
+}
+
+static unsigned long count_partial(struct kmem_cache_node *n,
+					int (*get_count)(struct page *))
+{
+	unsigned long flags;
+	unsigned long x = 0;
+	struct page *page;
+
+	spin_lock_irqsave(&n->list_lock, flags);
+	list_for_each_entry(page, &n->partial, lru)
+		x += get_count(page);
+	spin_unlock_irqrestore(&n->list_lock, flags);
+	return x;
+}
+
+static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
+{
+#ifdef CONFIG_SLUB_DEBUG
+	return atomic_long_read(&n->total_objects);
+#else
+	return 0;
+#endif
+}
+
+static noinline void
+slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
+{
+	int node;
+
+	printk(KERN_WARNING
+		"SLUB: Unable to allocate memory on node %d (gfp=0x%x)\n",
+		nid, gfpflags);
+	printk(KERN_WARNING "  cache: %s, object size: %d, buffer size: %d, "
+		"default order: %d, min order: %d\n", s->name, s->objsize,
+		s->size, oo_order(s->oo), oo_order(s->min));
+
+	for_each_online_node(node) {
+		struct kmem_cache_node *n = get_node(s, node);
+		unsigned long nr_slabs;
+		unsigned long nr_objs;
+		unsigned long nr_free;
+
+		if (!n)
+			continue;
+
+		nr_free  = count_partial(n, count_free);
+		nr_slabs = node_nr_slabs(n);
+		nr_objs  = node_nr_objs(n);
+
+		printk(KERN_WARNING
+			"  node %d: slabs: %ld, objs: %ld, free: %ld\n",
+			node, nr_slabs, nr_objs, nr_free);
+	}
+}
+
 /*
  * Slow path. The lockless freelist is empty or we need to perform
  * debugging duties.
@@ -1595,6 +1655,8 @@
 		c->page = new;
 		goto load_freelist;
 	}
+	if (!(gfpflags & __GFP_NOWARN) && printk_ratelimit())
+		slab_out_of_memory(s, gfpflags, node);
 	return NULL;
 debug:
 	if (!alloc_debug_processing(s, c->page, object, addr))
@@ -1624,7 +1686,7 @@
 	unsigned long flags;
 	unsigned int objsize;
 
-	gfpflags &= slab_gfp_mask;
+	gfpflags &= gfp_allowed_mask;
 
 	lockdep_trace_alloc(gfpflags);
 	might_sleep_if(gfpflags & __GFP_WAIT);
@@ -2636,6 +2698,7 @@
 	struct kmem_cache *s;
 	char *text;
 	size_t realsize;
+	unsigned long slabflags;
 
 	s = kmalloc_caches_dma[index];
 	if (s)
@@ -2657,10 +2720,18 @@
 			 (unsigned int)realsize);
 	s = kmalloc(kmem_size, flags & ~SLUB_DMA);
 
+	/*
+	 * Must defer sysfs creation to a workqueue because we don't know
+	 * what context we are called from. Before sysfs comes up, we don't
+	 * need to do anything because our sysfs initcall will start by
+	 * adding all existing slabs to sysfs.
+	 */
+	slabflags = SLAB_CACHE_DMA|SLAB_NOTRACK;
+	if (slab_state >= SYSFS)
+		slabflags |= __SYSFS_ADD_DEFERRED;
+
 	if (!s || !text || !kmem_cache_open(s, flags, text,
-			realsize, ARCH_KMALLOC_MINALIGN,
-			SLAB_CACHE_DMA|SLAB_NOTRACK|__SYSFS_ADD_DEFERRED,
-			NULL)) {
+			realsize, ARCH_KMALLOC_MINALIGN, slabflags, NULL)) {
 		kfree(s);
 		kfree(text);
 		goto unlock_out;
@@ -2669,7 +2740,8 @@
 	list_add(&s->list, &slab_caches);
 	kmalloc_caches_dma[index] = s;
 
-	schedule_work(&sysfs_add_work);
+	if (slab_state >= SYSFS)
+		schedule_work(&sysfs_add_work);
 
 unlock_out:
 	up_write(&slub_lock);
@@ -3142,10 +3214,6 @@
 
 void __init kmem_cache_init_late(void)
 {
-	/*
-	 * Interrupts are enabled now so all GFP allocations are safe.
-	 */
-	slab_gfp_mask = __GFP_BITS_MASK;
 }
 
 /*
@@ -3368,20 +3436,6 @@
 }
 
 #ifdef CONFIG_SLUB_DEBUG
-static unsigned long count_partial(struct kmem_cache_node *n,
-					int (*get_count)(struct page *))
-{
-	unsigned long flags;
-	unsigned long x = 0;
-	struct page *page;
-
-	spin_lock_irqsave(&n->list_lock, flags);
-	list_for_each_entry(page, &n->partial, lru)
-		x += get_count(page);
-	spin_unlock_irqrestore(&n->list_lock, flags);
-	return x;
-}
-
 static int count_inuse(struct page *page)
 {
 	return page->inuse;
@@ -3392,11 +3446,6 @@
 	return page->objects;
 }
 
-static int count_free(struct page *page)
-{
-	return page->objects - page->inuse;
-}
-
 static int validate_slab(struct kmem_cache *s, struct page *page,
 						unsigned long *map)
 {
diff --git a/mm/swapfile.c b/mm/swapfile.c
index 28faa01..d1ade1a 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -583,8 +583,9 @@
 			swap_list.next = p - swap_info;
 		nr_swap_pages++;
 		p->inuse_pages--;
-		mem_cgroup_uncharge_swap(ent);
 	}
+	if (!swap_count(count))
+		mem_cgroup_uncharge_swap(ent);
 	return count;
 }
 
@@ -609,12 +610,19 @@
 void swapcache_free(swp_entry_t entry, struct page *page)
 {
 	struct swap_info_struct *p;
+	int ret;
 
-	if (page)
-		mem_cgroup_uncharge_swapcache(page, entry);
 	p = swap_info_get(entry);
 	if (p) {
-		swap_entry_free(p, entry, SWAP_CACHE);
+		ret = swap_entry_free(p, entry, SWAP_CACHE);
+		if (page) {
+			bool swapout;
+			if (ret)
+				swapout = true; /* the end of swap out */
+			else
+				swapout = false; /* no more swap users! */
+			mem_cgroup_uncharge_swapcache(page, entry, swapout);
+		}
 		spin_unlock(&swap_lock);
 	}
 	return;
diff --git a/mm/util.c b/mm/util.c
index d5d2213..7c35ad9 100644
--- a/mm/util.c
+++ b/mm/util.c
@@ -168,6 +168,10 @@
  *
  * The memory of the object @p points to is zeroed before freed.
  * If @p is %NULL, kzfree() does nothing.
+ *
+ * Note: this function zeroes the whole allocated buffer which can be a good
+ * deal bigger than the requested buffer size passed to kmalloc(). So be
+ * careful when using this function in performance sensitive code.
  */
 void kzfree(const void *p)
 {
diff --git a/mm/vmscan.c b/mm/vmscan.c
index 4139aa5..e8fa2d9 100644
--- a/mm/vmscan.c
+++ b/mm/vmscan.c
@@ -837,7 +837,6 @@
 		 */
 		ClearPageLRU(page);
 		ret = 0;
-		mem_cgroup_del_lru(page);
 	}
 
 	return ret;
@@ -885,12 +884,14 @@
 		switch (__isolate_lru_page(page, mode, file)) {
 		case 0:
 			list_move(&page->lru, dst);
+			mem_cgroup_del_lru(page);
 			nr_taken++;
 			break;
 
 		case -EBUSY:
 			/* else it is being freed elsewhere */
 			list_move(&page->lru, src);
+			mem_cgroup_rotate_lru_list(page, page_lru(page));
 			continue;
 
 		default:
@@ -931,6 +932,7 @@
 				continue;
 			if (__isolate_lru_page(cursor_page, mode, file) == 0) {
 				list_move(&cursor_page->lru, dst);
+				mem_cgroup_del_lru(page);
 				nr_taken++;
 				scan++;
 			}
diff --git a/net/appletalk/atalk_proc.c b/net/appletalk/atalk_proc.c
index fd8e084..80caad1 100644
--- a/net/appletalk/atalk_proc.c
+++ b/net/appletalk/atalk_proc.c
@@ -204,8 +204,8 @@
 			"%02X %d\n",
 		   s->sk_type, ntohs(at->src_net), at->src_node, at->src_port,
 		   ntohs(at->dest_net), at->dest_node, at->dest_port,
-		   atomic_read(&s->sk_wmem_alloc),
-		   atomic_read(&s->sk_rmem_alloc),
+		   sk_wmem_alloc_get(s),
+		   sk_rmem_alloc_get(s),
 		   s->sk_state, SOCK_INODE(s->sk_socket)->i_uid);
 out:
 	return 0;
diff --git a/net/appletalk/ddp.c b/net/appletalk/ddp.c
index b603cba..590b839 100644
--- a/net/appletalk/ddp.c
+++ b/net/appletalk/ddp.c
@@ -162,8 +162,7 @@
 {
 	struct sock *sk = (struct sock *)data;
 
-	if (atomic_read(&sk->sk_wmem_alloc) ||
-	    atomic_read(&sk->sk_rmem_alloc)) {
+	if (sk_has_allocations(sk)) {
 		sk->sk_timer.expires = jiffies + SOCK_DESTROY_TIME;
 		add_timer(&sk->sk_timer);
 	} else
@@ -175,8 +174,7 @@
 	atalk_remove_socket(sk);
 	skb_queue_purge(&sk->sk_receive_queue);
 
-	if (atomic_read(&sk->sk_wmem_alloc) ||
-	    atomic_read(&sk->sk_rmem_alloc)) {
+	if (sk_has_allocations(sk)) {
 		setup_timer(&sk->sk_timer, atalk_destroy_timer,
 				(unsigned long)sk);
 		sk->sk_timer.expires	= jiffies + SOCK_DESTROY_TIME;
@@ -1750,8 +1748,7 @@
 	switch (cmd) {
 		/* Protocol layer */
 		case TIOCOUTQ: {
-			long amount = sk->sk_sndbuf -
-				      atomic_read(&sk->sk_wmem_alloc);
+			long amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
 
 			if (amount < 0)
 				amount = 0;
diff --git a/net/atm/common.c b/net/atm/common.c
index d34edbe..c1c9793 100644
--- a/net/atm/common.c
+++ b/net/atm/common.c
@@ -62,15 +62,15 @@
 	struct sk_buff *skb;
 	struct sock *sk = sk_atm(vcc);
 
-	if (atomic_read(&sk->sk_wmem_alloc) && !atm_may_send(vcc, size)) {
+	if (sk_wmem_alloc_get(sk) && !atm_may_send(vcc, size)) {
 		pr_debug("Sorry: wmem_alloc = %d, size = %d, sndbuf = %d\n",
-			atomic_read(&sk->sk_wmem_alloc), size,
+			sk_wmem_alloc_get(sk), size,
 			sk->sk_sndbuf);
 		return NULL;
 	}
-	while (!(skb = alloc_skb(size,GFP_KERNEL))) schedule();
-	pr_debug("AlTx %d += %d\n", atomic_read(&sk->sk_wmem_alloc),
-		skb->truesize);
+	while (!(skb = alloc_skb(size, GFP_KERNEL)))
+		schedule();
+	pr_debug("AlTx %d += %d\n", sk_wmem_alloc_get(sk), skb->truesize);
 	atomic_add(skb->truesize, &sk->sk_wmem_alloc);
 	return skb;
 }
@@ -145,7 +145,7 @@
 	memset(&vcc->local,0,sizeof(struct sockaddr_atmsvc));
 	memset(&vcc->remote,0,sizeof(struct sockaddr_atmsvc));
 	vcc->qos.txtp.max_sdu = 1 << 16; /* for meta VCs */
-	atomic_set(&sk->sk_wmem_alloc, 0);
+	atomic_set(&sk->sk_wmem_alloc, 1);
 	atomic_set(&sk->sk_rmem_alloc, 0);
 	vcc->push = NULL;
 	vcc->pop = NULL;
diff --git a/net/atm/ioctl.c b/net/atm/ioctl.c
index 76ed3c8..4da8892 100644
--- a/net/atm/ioctl.c
+++ b/net/atm/ioctl.c
@@ -63,8 +63,7 @@
 				error =  -EINVAL;
 				goto done;
 			}
-			error = put_user(sk->sk_sndbuf -
-					 atomic_read(&sk->sk_wmem_alloc),
+			error = put_user(sk->sk_sndbuf - sk_wmem_alloc_get(sk),
 					 (int __user *) argp) ? -EFAULT : 0;
 			goto done;
 		case SIOCINQ:
diff --git a/net/atm/proc.c b/net/atm/proc.c
index e7b3b273..38de5ff 100644
--- a/net/atm/proc.c
+++ b/net/atm/proc.c
@@ -204,8 +204,8 @@
 			seq_printf(seq, "%3d", sk->sk_family);
 	}
 	seq_printf(seq, " %04lx  %5d %7d/%7d %7d/%7d [%d]\n", vcc->flags, sk->sk_err,
-		  atomic_read(&sk->sk_wmem_alloc), sk->sk_sndbuf,
-		  atomic_read(&sk->sk_rmem_alloc), sk->sk_rcvbuf,
+		  sk_wmem_alloc_get(sk), sk->sk_sndbuf,
+		  sk_rmem_alloc_get(sk), sk->sk_rcvbuf,
 		  atomic_read(&sk->sk_refcnt));
 }
 
diff --git a/net/atm/raw.c b/net/atm/raw.c
index b0a2d8c..cbfcc71 100644
--- a/net/atm/raw.c
+++ b/net/atm/raw.c
@@ -33,7 +33,7 @@
 	struct sock *sk = sk_atm(vcc);
 
 	pr_debug("APopR (%d) %d -= %d\n", vcc->vci,
-		atomic_read(&sk->sk_wmem_alloc), skb->truesize);
+		sk_wmem_alloc_get(sk), skb->truesize);
 	atomic_sub(skb->truesize, &sk->sk_wmem_alloc);
 	dev_kfree_skb_any(skb);
 	sk->sk_write_space(sk);
diff --git a/net/ax25/af_ax25.c b/net/ax25/af_ax25.c
index fd9d06f..da0f64f 100644
--- a/net/ax25/af_ax25.c
+++ b/net/ax25/af_ax25.c
@@ -330,8 +330,7 @@
 	}
 
 	if (ax25->sk != NULL) {
-		if (atomic_read(&ax25->sk->sk_wmem_alloc) ||
-		    atomic_read(&ax25->sk->sk_rmem_alloc)) {
+		if (sk_has_allocations(ax25->sk)) {
 			/* Defer: outstanding buffers */
 			setup_timer(&ax25->dtimer, ax25_destroy_timer,
 					(unsigned long)ax25);
@@ -1691,7 +1690,8 @@
 	switch (cmd) {
 	case TIOCOUTQ: {
 		long amount;
-		amount = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc);
+
+		amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
 		if (amount < 0)
 			amount = 0;
 		res = put_user(amount, (int __user *)argp);
@@ -1781,8 +1781,8 @@
 		ax25_info.idletimer = ax25_display_timer(&ax25->idletimer) / (60 * HZ);
 		ax25_info.n2count   = ax25->n2count;
 		ax25_info.state     = ax25->state;
-		ax25_info.rcv_q     = atomic_read(&sk->sk_rmem_alloc);
-		ax25_info.snd_q     = atomic_read(&sk->sk_wmem_alloc);
+		ax25_info.rcv_q     = sk_wmem_alloc_get(sk);
+		ax25_info.snd_q     = sk_rmem_alloc_get(sk);
 		ax25_info.vs        = ax25->vs;
 		ax25_info.vr        = ax25->vr;
 		ax25_info.va        = ax25->va;
@@ -1922,8 +1922,8 @@
 
 	if (ax25->sk != NULL) {
 		seq_printf(seq, " %d %d %lu\n",
-			   atomic_read(&ax25->sk->sk_wmem_alloc),
-			   atomic_read(&ax25->sk->sk_rmem_alloc),
+			   sk_wmem_alloc_get(ax25->sk),
+			   sk_rmem_alloc_get(ax25->sk),
 			   sock_i_ino(ax25->sk));
 	} else {
 		seq_puts(seq, " * * *\n");
diff --git a/net/bluetooth/af_bluetooth.c b/net/bluetooth/af_bluetooth.c
index 02b9baa..0250e06 100644
--- a/net/bluetooth/af_bluetooth.c
+++ b/net/bluetooth/af_bluetooth.c
@@ -337,7 +337,7 @@
 		if (sk->sk_state == BT_LISTEN)
 			return -EINVAL;
 
-		amount = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc);
+		amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
 		if (amount < 0)
 			amount = 0;
 		err = put_user(amount, (int __user *) arg);
diff --git a/net/core/dev.c b/net/core/dev.c
index 576a615..baf2dc1 100644
--- a/net/core/dev.c
+++ b/net/core/dev.c
@@ -3461,10 +3461,10 @@
 		/* Unicast addresses changes may only happen under the rtnl,
 		 * therefore calling __dev_set_promiscuity here is safe.
 		 */
-		if (dev->uc_count > 0 && !dev->uc_promisc) {
+		if (dev->uc.count > 0 && !dev->uc_promisc) {
 			__dev_set_promiscuity(dev, 1);
 			dev->uc_promisc = 1;
-		} else if (dev->uc_count == 0 && dev->uc_promisc) {
+		} else if (dev->uc.count == 0 && dev->uc_promisc) {
 			__dev_set_promiscuity(dev, -1);
 			dev->uc_promisc = 0;
 		}
@@ -3483,9 +3483,8 @@
 
 /* hw addresses list handling functions */
 
-static int __hw_addr_add(struct list_head *list, int *delta,
-			 unsigned char *addr, int addr_len,
-			 unsigned char addr_type)
+static int __hw_addr_add(struct netdev_hw_addr_list *list, unsigned char *addr,
+			 int addr_len, unsigned char addr_type)
 {
 	struct netdev_hw_addr *ha;
 	int alloc_size;
@@ -3493,7 +3492,7 @@
 	if (addr_len > MAX_ADDR_LEN)
 		return -EINVAL;
 
-	list_for_each_entry(ha, list, list) {
+	list_for_each_entry(ha, &list->list, list) {
 		if (!memcmp(ha->addr, addr, addr_len) &&
 		    ha->type == addr_type) {
 			ha->refcount++;
@@ -3512,9 +3511,8 @@
 	ha->type = addr_type;
 	ha->refcount = 1;
 	ha->synced = false;
-	list_add_tail_rcu(&ha->list, list);
-	if (delta)
-		(*delta)++;
+	list_add_tail_rcu(&ha->list, &list->list);
+	list->count++;
 	return 0;
 }
 
@@ -3526,120 +3524,121 @@
 	kfree(ha);
 }
 
-static int __hw_addr_del(struct list_head *list, int *delta,
-			 unsigned char *addr, int addr_len,
-			 unsigned char addr_type)
+static int __hw_addr_del(struct netdev_hw_addr_list *list, unsigned char *addr,
+			 int addr_len, unsigned char addr_type)
 {
 	struct netdev_hw_addr *ha;
 
-	list_for_each_entry(ha, list, list) {
+	list_for_each_entry(ha, &list->list, list) {
 		if (!memcmp(ha->addr, addr, addr_len) &&
 		    (ha->type == addr_type || !addr_type)) {
 			if (--ha->refcount)
 				return 0;
 			list_del_rcu(&ha->list);
 			call_rcu(&ha->rcu_head, ha_rcu_free);
-			if (delta)
-				(*delta)--;
+			list->count--;
 			return 0;
 		}
 	}
 	return -ENOENT;
 }
 
-static int __hw_addr_add_multiple(struct list_head *to_list, int *to_delta,
-				  struct list_head *from_list, int addr_len,
+static int __hw_addr_add_multiple(struct netdev_hw_addr_list *to_list,
+				  struct netdev_hw_addr_list *from_list,
+				  int addr_len,
 				  unsigned char addr_type)
 {
 	int err;
 	struct netdev_hw_addr *ha, *ha2;
 	unsigned char type;
 
-	list_for_each_entry(ha, from_list, list) {
+	list_for_each_entry(ha, &from_list->list, list) {
 		type = addr_type ? addr_type : ha->type;
-		err = __hw_addr_add(to_list, to_delta, ha->addr,
-				    addr_len, type);
+		err = __hw_addr_add(to_list, ha->addr, addr_len, type);
 		if (err)
 			goto unroll;
 	}
 	return 0;
 
 unroll:
-	list_for_each_entry(ha2, from_list, list) {
+	list_for_each_entry(ha2, &from_list->list, list) {
 		if (ha2 == ha)
 			break;
 		type = addr_type ? addr_type : ha2->type;
-		__hw_addr_del(to_list, to_delta, ha2->addr,
-			      addr_len, type);
+		__hw_addr_del(to_list, ha2->addr, addr_len, type);
 	}
 	return err;
 }
 
-static void __hw_addr_del_multiple(struct list_head *to_list, int *to_delta,
-				   struct list_head *from_list, int addr_len,
+static void __hw_addr_del_multiple(struct netdev_hw_addr_list *to_list,
+				   struct netdev_hw_addr_list *from_list,
+				   int addr_len,
 				   unsigned char addr_type)
 {
 	struct netdev_hw_addr *ha;
 	unsigned char type;
 
-	list_for_each_entry(ha, from_list, list) {
+	list_for_each_entry(ha, &from_list->list, list) {
 		type = addr_type ? addr_type : ha->type;
-		__hw_addr_del(to_list, to_delta, ha->addr,
-			      addr_len, addr_type);
+		__hw_addr_del(to_list, ha->addr, addr_len, addr_type);
 	}
 }
 
-static int __hw_addr_sync(struct list_head *to_list, int *to_delta,
-			  struct list_head *from_list, int *from_delta,
+static int __hw_addr_sync(struct netdev_hw_addr_list *to_list,
+			  struct netdev_hw_addr_list *from_list,
 			  int addr_len)
 {
 	int err = 0;
 	struct netdev_hw_addr *ha, *tmp;
 
-	list_for_each_entry_safe(ha, tmp, from_list, list) {
+	list_for_each_entry_safe(ha, tmp, &from_list->list, list) {
 		if (!ha->synced) {
-			err = __hw_addr_add(to_list, to_delta, ha->addr,
+			err = __hw_addr_add(to_list, ha->addr,
 					    addr_len, ha->type);
 			if (err)
 				break;
 			ha->synced = true;
 			ha->refcount++;
 		} else if (ha->refcount == 1) {
-			__hw_addr_del(to_list, to_delta, ha->addr,
-				      addr_len, ha->type);
-			__hw_addr_del(from_list, from_delta, ha->addr,
-				      addr_len, ha->type);
+			__hw_addr_del(to_list, ha->addr, addr_len, ha->type);
+			__hw_addr_del(from_list, ha->addr, addr_len, ha->type);
 		}
 	}
 	return err;
 }
 
-static void __hw_addr_unsync(struct list_head *to_list, int *to_delta,
-			     struct list_head *from_list, int *from_delta,
+static void __hw_addr_unsync(struct netdev_hw_addr_list *to_list,
+			     struct netdev_hw_addr_list *from_list,
 			     int addr_len)
 {
 	struct netdev_hw_addr *ha, *tmp;
 
-	list_for_each_entry_safe(ha, tmp, from_list, list) {
+	list_for_each_entry_safe(ha, tmp, &from_list->list, list) {
 		if (ha->synced) {
-			__hw_addr_del(to_list, to_delta, ha->addr,
+			__hw_addr_del(to_list, ha->addr,
 				      addr_len, ha->type);
 			ha->synced = false;
-			__hw_addr_del(from_list, from_delta, ha->addr,
+			__hw_addr_del(from_list, ha->addr,
 				      addr_len, ha->type);
 		}
 	}
 }
 
-
-static void __hw_addr_flush(struct list_head *list)
+static void __hw_addr_flush(struct netdev_hw_addr_list *list)
 {
 	struct netdev_hw_addr *ha, *tmp;
 
-	list_for_each_entry_safe(ha, tmp, list, list) {
+	list_for_each_entry_safe(ha, tmp, &list->list, list) {
 		list_del_rcu(&ha->list);
 		call_rcu(&ha->rcu_head, ha_rcu_free);
 	}
+	list->count = 0;
+}
+
+static void __hw_addr_init(struct netdev_hw_addr_list *list)
+{
+	INIT_LIST_HEAD(&list->list);
+	list->count = 0;
 }
 
 /* Device addresses handling functions */
@@ -3648,7 +3647,7 @@
 {
 	/* rtnl_mutex must be held here */
 
-	__hw_addr_flush(&dev->dev_addr_list);
+	__hw_addr_flush(&dev->dev_addrs);
 	dev->dev_addr = NULL;
 }
 
@@ -3660,16 +3659,16 @@
 
 	/* rtnl_mutex must be held here */
 
-	INIT_LIST_HEAD(&dev->dev_addr_list);
+	__hw_addr_init(&dev->dev_addrs);
 	memset(addr, 0, sizeof(addr));
-	err = __hw_addr_add(&dev->dev_addr_list, NULL, addr, sizeof(addr),
+	err = __hw_addr_add(&dev->dev_addrs, addr, sizeof(addr),
 			    NETDEV_HW_ADDR_T_LAN);
 	if (!err) {
 		/*
 		 * Get the first (previously created) address from the list
 		 * and set dev_addr pointer to this location.
 		 */
-		ha = list_first_entry(&dev->dev_addr_list,
+		ha = list_first_entry(&dev->dev_addrs.list,
 				      struct netdev_hw_addr, list);
 		dev->dev_addr = ha->addr;
 	}
@@ -3694,8 +3693,7 @@
 
 	ASSERT_RTNL();
 
-	err = __hw_addr_add(&dev->dev_addr_list, NULL, addr, dev->addr_len,
-			    addr_type);
+	err = __hw_addr_add(&dev->dev_addrs, addr, dev->addr_len, addr_type);
 	if (!err)
 		call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
 	return err;
@@ -3725,11 +3723,12 @@
 	 * We can not remove the first address from the list because
 	 * dev->dev_addr points to that.
 	 */
-	ha = list_first_entry(&dev->dev_addr_list, struct netdev_hw_addr, list);
+	ha = list_first_entry(&dev->dev_addrs.list,
+			      struct netdev_hw_addr, list);
 	if (ha->addr == dev->dev_addr && ha->refcount == 1)
 		return -ENOENT;
 
-	err = __hw_addr_del(&dev->dev_addr_list, NULL, addr, dev->addr_len,
+	err = __hw_addr_del(&dev->dev_addrs, addr, dev->addr_len,
 			    addr_type);
 	if (!err)
 		call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
@@ -3757,8 +3756,7 @@
 
 	if (from_dev->addr_len != to_dev->addr_len)
 		return -EINVAL;
-	err = __hw_addr_add_multiple(&to_dev->dev_addr_list, NULL,
-				     &from_dev->dev_addr_list,
+	err = __hw_addr_add_multiple(&to_dev->dev_addrs, &from_dev->dev_addrs,
 				     to_dev->addr_len, addr_type);
 	if (!err)
 		call_netdevice_notifiers(NETDEV_CHANGEADDR, to_dev);
@@ -3784,15 +3782,14 @@
 
 	if (from_dev->addr_len != to_dev->addr_len)
 		return -EINVAL;
-	__hw_addr_del_multiple(&to_dev->dev_addr_list, NULL,
-			       &from_dev->dev_addr_list,
+	__hw_addr_del_multiple(&to_dev->dev_addrs, &from_dev->dev_addrs,
 			       to_dev->addr_len, addr_type);
 	call_netdevice_notifiers(NETDEV_CHANGEADDR, to_dev);
 	return 0;
 }
 EXPORT_SYMBOL(dev_addr_del_multiple);
 
-/* unicast and multicast addresses handling functions */
+/* multicast addresses handling functions */
 
 int __dev_addr_delete(struct dev_addr_list **list, int *count,
 		      void *addr, int alen, int glbl)
@@ -3868,8 +3865,8 @@
 
 	ASSERT_RTNL();
 
-	err = __hw_addr_del(&dev->uc_list, &dev->uc_count, addr,
-			    dev->addr_len, NETDEV_HW_ADDR_T_UNICAST);
+	err = __hw_addr_del(&dev->uc, addr, dev->addr_len,
+			    NETDEV_HW_ADDR_T_UNICAST);
 	if (!err)
 		__dev_set_rx_mode(dev);
 	return err;
@@ -3892,8 +3889,8 @@
 
 	ASSERT_RTNL();
 
-	err = __hw_addr_add(&dev->uc_list, &dev->uc_count, addr,
-			    dev->addr_len, NETDEV_HW_ADDR_T_UNICAST);
+	err = __hw_addr_add(&dev->uc, addr, dev->addr_len,
+			    NETDEV_HW_ADDR_T_UNICAST);
 	if (!err)
 		__dev_set_rx_mode(dev);
 	return err;
@@ -3966,8 +3963,7 @@
 	if (to->addr_len != from->addr_len)
 		return -EINVAL;
 
-	err = __hw_addr_sync(&to->uc_list, &to->uc_count,
-			     &from->uc_list, &from->uc_count, to->addr_len);
+	err = __hw_addr_sync(&to->uc, &from->uc, to->addr_len);
 	if (!err)
 		__dev_set_rx_mode(to);
 	return err;
@@ -3990,8 +3986,7 @@
 	if (to->addr_len != from->addr_len)
 		return;
 
-	__hw_addr_unsync(&to->uc_list, &to->uc_count,
-			 &from->uc_list, &from->uc_count, to->addr_len);
+	__hw_addr_unsync(&to->uc, &from->uc, to->addr_len);
 	__dev_set_rx_mode(to);
 }
 EXPORT_SYMBOL(dev_unicast_unsync);
@@ -4000,15 +3995,14 @@
 {
 	/* rtnl_mutex must be held here */
 
-	__hw_addr_flush(&dev->uc_list);
-	dev->uc_count = 0;
+	__hw_addr_flush(&dev->uc);
 }
 
 static void dev_unicast_init(struct net_device *dev)
 {
 	/* rtnl_mutex must be held here */
 
-	INIT_LIST_HEAD(&dev->uc_list);
+	__hw_addr_init(&dev->uc);
 }
 
 
diff --git a/net/core/skbuff.c b/net/core/skbuff.c
index 5c93435..9e0597d 100644
--- a/net/core/skbuff.c
+++ b/net/core/skbuff.c
@@ -204,6 +204,10 @@
 	skb->end = skb->tail + size;
 	kmemcheck_annotate_bitfield(skb, flags1);
 	kmemcheck_annotate_bitfield(skb, flags2);
+#ifdef NET_SKBUFF_DATA_USES_OFFSET
+	skb->mac_header = ~0U;
+#endif
+
 	/* make sure we initialize shinfo sequentially */
 	shinfo = skb_shinfo(skb);
 	atomic_set(&shinfo->dataref, 1);
@@ -665,7 +669,8 @@
 	/* {transport,network,mac}_header are relative to skb->head */
 	new->transport_header += offset;
 	new->network_header   += offset;
-	new->mac_header	      += offset;
+	if (skb_mac_header_was_set(new))
+		new->mac_header	      += offset;
 #endif
 	skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
 	skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
@@ -847,7 +852,8 @@
 	skb->tail	      += off;
 	skb->transport_header += off;
 	skb->network_header   += off;
-	skb->mac_header	      += off;
+	if (skb_mac_header_was_set(skb))
+		skb->mac_header += off;
 	skb->csum_start       += nhead;
 	skb->cloned   = 0;
 	skb->hdr_len  = 0;
@@ -939,7 +945,8 @@
 #ifdef NET_SKBUFF_DATA_USES_OFFSET
 	n->transport_header += off;
 	n->network_header   += off;
-	n->mac_header	    += off;
+	if (skb_mac_header_was_set(skb))
+		n->mac_header += off;
 #endif
 
 	return n;
diff --git a/net/decnet/af_decnet.c b/net/decnet/af_decnet.c
index a5e3a59..d351b8d 100644
--- a/net/decnet/af_decnet.c
+++ b/net/decnet/af_decnet.c
@@ -1240,7 +1240,7 @@
 		return val;
 
 	case TIOCOUTQ:
-		amount = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc);
+		amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
 		if (amount < 0)
 			amount = 0;
 		err = put_user(amount, (int __user *)arg);
diff --git a/net/econet/af_econet.c b/net/econet/af_econet.c
index 8121bf0..2e1f836 100644
--- a/net/econet/af_econet.c
+++ b/net/econet/af_econet.c
@@ -540,8 +540,7 @@
 {
 	struct sock *sk=(struct sock *)data;
 
-	if (!atomic_read(&sk->sk_wmem_alloc) &&
-	    !atomic_read(&sk->sk_rmem_alloc)) {
+	if (!sk_has_allocations(sk)) {
 		sk_free(sk);
 		return;
 	}
@@ -579,8 +578,7 @@
 
 	skb_queue_purge(&sk->sk_receive_queue);
 
-	if (atomic_read(&sk->sk_rmem_alloc) ||
-	    atomic_read(&sk->sk_wmem_alloc)) {
+	if (sk_has_allocations(sk)) {
 		sk->sk_timer.data     = (unsigned long)sk;
 		sk->sk_timer.expires  = jiffies + HZ;
 		sk->sk_timer.function = econet_destroy_timer;
diff --git a/net/ieee802154/dgram.c b/net/ieee802154/dgram.c
index 1779677..14d3984 100644
--- a/net/ieee802154/dgram.c
+++ b/net/ieee802154/dgram.c
@@ -126,7 +126,8 @@
 	switch (cmd) {
 	case SIOCOUTQ:
 	{
-		int amount = atomic_read(&sk->sk_wmem_alloc);
+		int amount = sk_wmem_alloc_get(sk);
+
 		return put_user(amount, (int __user *)arg);
 	}
 
diff --git a/net/ipv4/fib_trie.c b/net/ipv4/fib_trie.c
index d1a39b1..012cf5a 100644
--- a/net/ipv4/fib_trie.c
+++ b/net/ipv4/fib_trie.c
@@ -391,13 +391,8 @@
 static void tnode_free_safe(struct tnode *tn)
 {
 	BUG_ON(IS_LEAF(tn));
-
-	if (node_parent((struct node *) tn)) {
-		tn->tnode_free = tnode_free_head;
-		tnode_free_head = tn;
-	} else {
-		tnode_free(tn);
-	}
+	tn->tnode_free = tnode_free_head;
+	tnode_free_head = tn;
 }
 
 static void tnode_free_flush(void)
@@ -1009,7 +1004,7 @@
 	return NULL;
 }
 
-static struct node *trie_rebalance(struct trie *t, struct tnode *tn)
+static void trie_rebalance(struct trie *t, struct tnode *tn)
 {
 	int wasfull;
 	t_key cindex, key;
@@ -1033,12 +1028,13 @@
 	}
 
 	/* Handle last (top) tnode */
-	if (IS_TNODE(tn)) {
+	if (IS_TNODE(tn))
 		tn = (struct tnode *)resize(t, (struct tnode *)tn);
-		tnode_free_flush();
-	}
 
-	return (struct node *)tn;
+	rcu_assign_pointer(t->trie, (struct node *)tn);
+	tnode_free_flush();
+
+	return;
 }
 
 /* only used from updater-side */
@@ -1186,7 +1182,7 @@
 
 	/* Rebalance the trie */
 
-	rcu_assign_pointer(t->trie, trie_rebalance(t, tp));
+	trie_rebalance(t, tp);
 done:
 	return fa_head;
 }
@@ -1605,7 +1601,7 @@
 	if (tp) {
 		t_key cindex = tkey_extract_bits(l->key, tp->pos, tp->bits);
 		put_child(t, (struct tnode *)tp, cindex, NULL);
-		rcu_assign_pointer(t->trie, trie_rebalance(t, tp));
+		trie_rebalance(t, tp);
 	} else
 		rcu_assign_pointer(t->trie, NULL);
 
diff --git a/net/ipv4/inet_diag.c b/net/ipv4/inet_diag.c
index b0b2735..a706a47 100644
--- a/net/ipv4/inet_diag.c
+++ b/net/ipv4/inet_diag.c
@@ -156,10 +156,10 @@
 	r->idiag_inode = sock_i_ino(sk);
 
 	if (minfo) {
-		minfo->idiag_rmem = atomic_read(&sk->sk_rmem_alloc);
+		minfo->idiag_rmem = sk_rmem_alloc_get(sk);
 		minfo->idiag_wmem = sk->sk_wmem_queued;
 		minfo->idiag_fmem = sk->sk_forward_alloc;
-		minfo->idiag_tmem = atomic_read(&sk->sk_wmem_alloc);
+		minfo->idiag_tmem = sk_wmem_alloc_get(sk);
 	}
 
 	handler->idiag_get_info(sk, r, info);
diff --git a/net/ipv4/raw.c b/net/ipv4/raw.c
index 3dc9171..2979f14 100644
--- a/net/ipv4/raw.c
+++ b/net/ipv4/raw.c
@@ -799,7 +799,8 @@
 {
 	switch (cmd) {
 		case SIOCOUTQ: {
-			int amount = atomic_read(&sk->sk_wmem_alloc);
+			int amount = sk_wmem_alloc_get(sk);
+
 			return put_user(amount, (int __user *)arg);
 		}
 		case SIOCINQ: {
@@ -935,8 +936,8 @@
 	seq_printf(seq, "%4d: %08X:%04X %08X:%04X"
 		" %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %p %d\n",
 		i, src, srcp, dest, destp, sp->sk_state,
-		atomic_read(&sp->sk_wmem_alloc),
-		atomic_read(&sp->sk_rmem_alloc),
+		sk_wmem_alloc_get(sp),
+		sk_rmem_alloc_get(sp),
 		0, 0L, 0, sock_i_uid(sp), 0, sock_i_ino(sp),
 		atomic_read(&sp->sk_refcnt), sp, atomic_read(&sp->sk_drops));
 }
diff --git a/net/ipv4/udp.c b/net/ipv4/udp.c
index 8f4158d..80e3812 100644
--- a/net/ipv4/udp.c
+++ b/net/ipv4/udp.c
@@ -840,7 +840,8 @@
 	switch (cmd) {
 	case SIOCOUTQ:
 	{
-		int amount = atomic_read(&sk->sk_wmem_alloc);
+		int amount = sk_wmem_alloc_get(sk);
+
 		return put_user(amount, (int __user *)arg);
 	}
 
@@ -1721,8 +1722,8 @@
 	seq_printf(f, "%4d: %08X:%04X %08X:%04X"
 		" %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %p %d%n",
 		bucket, src, srcp, dest, destp, sp->sk_state,
-		atomic_read(&sp->sk_wmem_alloc),
-		atomic_read(&sp->sk_rmem_alloc),
+		sk_wmem_alloc_get(sp),
+		sk_rmem_alloc_get(sp),
 		0, 0L, 0, sock_i_uid(sp), 0, sock_i_ino(sp),
 		atomic_read(&sp->sk_refcnt), sp,
 		atomic_read(&sp->sk_drops), len);
diff --git a/net/ipv6/raw.c b/net/ipv6/raw.c
index 36a090d..8b0b6f9 100644
--- a/net/ipv6/raw.c
+++ b/net/ipv6/raw.c
@@ -1130,7 +1130,8 @@
 	switch(cmd) {
 		case SIOCOUTQ:
 		{
-			int amount = atomic_read(&sk->sk_wmem_alloc);
+			int amount = sk_wmem_alloc_get(sk);
+
 			return put_user(amount, (int __user *)arg);
 		}
 		case SIOCINQ:
@@ -1236,8 +1237,8 @@
 		   dest->s6_addr32[0], dest->s6_addr32[1],
 		   dest->s6_addr32[2], dest->s6_addr32[3], destp,
 		   sp->sk_state,
-		   atomic_read(&sp->sk_wmem_alloc),
-		   atomic_read(&sp->sk_rmem_alloc),
+		   sk_wmem_alloc_get(sp),
+		   sk_rmem_alloc_get(sp),
 		   0, 0L, 0,
 		   sock_i_uid(sp), 0,
 		   sock_i_ino(sp),
diff --git a/net/ipv6/udp.c b/net/ipv6/udp.c
index fc333d8..023beda 100644
--- a/net/ipv6/udp.c
+++ b/net/ipv6/udp.c
@@ -1061,8 +1061,8 @@
 		   dest->s6_addr32[0], dest->s6_addr32[1],
 		   dest->s6_addr32[2], dest->s6_addr32[3], destp,
 		   sp->sk_state,
-		   atomic_read(&sp->sk_wmem_alloc),
-		   atomic_read(&sp->sk_rmem_alloc),
+		   sk_wmem_alloc_get(sp),
+		   sk_rmem_alloc_get(sp),
 		   0, 0L, 0,
 		   sock_i_uid(sp), 0,
 		   sock_i_ino(sp),
diff --git a/net/ipx/af_ipx.c b/net/ipx/af_ipx.c
index 1627050..417b0e3 100644
--- a/net/ipx/af_ipx.c
+++ b/net/ipx/af_ipx.c
@@ -1835,7 +1835,7 @@
 
 	switch (cmd) {
 	case TIOCOUTQ:
-		amount = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc);
+		amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
 		if (amount < 0)
 			amount = 0;
 		rc = put_user(amount, (int __user *)argp);
diff --git a/net/ipx/ipx_proc.c b/net/ipx/ipx_proc.c
index 5ed97ad..5761784 100644
--- a/net/ipx/ipx_proc.c
+++ b/net/ipx/ipx_proc.c
@@ -280,8 +280,8 @@
 	}
 
 	seq_printf(seq, "%08X  %08X  %02X     %03d\n",
-		   atomic_read(&s->sk_wmem_alloc),
-		   atomic_read(&s->sk_rmem_alloc),
+		   sk_wmem_alloc_get(s),
+		   sk_rmem_alloc_get(s),
 		   s->sk_state, SOCK_INODE(s->sk_socket)->i_uid);
 out:
 	return 0;
diff --git a/net/irda/af_irda.c b/net/irda/af_irda.c
index 3eb5bcc..5922feb 100644
--- a/net/irda/af_irda.c
+++ b/net/irda/af_irda.c
@@ -1762,7 +1762,8 @@
 	switch (cmd) {
 	case TIOCOUTQ: {
 		long amount;
-		amount = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc);
+
+		amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
 		if (amount < 0)
 			amount = 0;
 		if (put_user(amount, (unsigned int __user *)arg))
diff --git a/net/key/af_key.c b/net/key/af_key.c
index 643c1be..dba9abd 100644
--- a/net/key/af_key.c
+++ b/net/key/af_key.c
@@ -3662,8 +3662,8 @@
 		seq_printf(f ,"%p %-6d %-6u %-6u %-6u %-6lu\n",
 			       s,
 			       atomic_read(&s->sk_refcnt),
-			       atomic_read(&s->sk_rmem_alloc),
-			       atomic_read(&s->sk_wmem_alloc),
+			       sk_rmem_alloc_get(s),
+			       sk_wmem_alloc_get(s),
 			       sock_i_uid(s),
 			       sock_i_ino(s)
 			       );
diff --git a/net/llc/llc_proc.c b/net/llc/llc_proc.c
index d208b33..f97be47 100644
--- a/net/llc/llc_proc.c
+++ b/net/llc/llc_proc.c
@@ -134,8 +134,8 @@
 	seq_printf(seq, "@%02X ", llc->sap->laddr.lsap);
 	llc_ui_format_mac(seq, llc->daddr.mac);
 	seq_printf(seq, "@%02X %8d %8d %2d %3d %4d\n", llc->daddr.lsap,
-		   atomic_read(&sk->sk_wmem_alloc),
-		   atomic_read(&sk->sk_rmem_alloc) - llc->copied_seq,
+		   sk_wmem_alloc_get(sk),
+		   sk_rmem_alloc_get(sk) - llc->copied_seq,
 		   sk->sk_state,
 		   sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : -1,
 		   llc->link);
diff --git a/net/mac80211/debugfs.c b/net/mac80211/debugfs.c
index 11c7231..6c439cd 100644
--- a/net/mac80211/debugfs.c
+++ b/net/mac80211/debugfs.c
@@ -163,6 +163,29 @@
 	.open = mac80211_open_file_generic
 };
 
+static ssize_t queues_read(struct file *file, char __user *user_buf,
+			   size_t count, loff_t *ppos)
+{
+	struct ieee80211_local *local = file->private_data;
+	unsigned long flags;
+	char buf[IEEE80211_MAX_QUEUES * 20];
+	int q, res = 0;
+
+	spin_lock_irqsave(&local->queue_stop_reason_lock, flags);
+	for (q = 0; q < local->hw.queues; q++)
+		res += sprintf(buf + res, "%02d: %#.8lx/%d\n", q,
+				local->queue_stop_reasons[q],
+				__netif_subqueue_stopped(local->mdev, q));
+	spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags);
+
+	return simple_read_from_buffer(user_buf, count, ppos, buf, res);
+}
+
+static const struct file_operations queues_ops = {
+	.read = queues_read,
+	.open = mac80211_open_file_generic
+};
+
 /* statistics stuff */
 
 #define DEBUGFS_STATS_FILE(name, buflen, fmt, value...)			\
@@ -298,6 +321,7 @@
 	DEBUGFS_ADD(total_ps_buffered);
 	DEBUGFS_ADD(wep_iv);
 	DEBUGFS_ADD(tsf);
+	DEBUGFS_ADD(queues);
 	DEBUGFS_ADD_MODE(reset, 0200);
 	DEBUGFS_ADD(noack);
 
@@ -350,6 +374,7 @@
 	DEBUGFS_DEL(total_ps_buffered);
 	DEBUGFS_DEL(wep_iv);
 	DEBUGFS_DEL(tsf);
+	DEBUGFS_DEL(queues);
 	DEBUGFS_DEL(reset);
 	DEBUGFS_DEL(noack);
 
diff --git a/net/mac80211/ieee80211_i.h b/net/mac80211/ieee80211_i.h
index 4dbc289..68eb505 100644
--- a/net/mac80211/ieee80211_i.h
+++ b/net/mac80211/ieee80211_i.h
@@ -783,6 +783,7 @@
 		struct dentry *total_ps_buffered;
 		struct dentry *wep_iv;
 		struct dentry *tsf;
+		struct dentry *queues;
 		struct dentry *reset;
 		struct dentry *noack;
 		struct dentry *statistics;
@@ -1100,7 +1101,6 @@
 u32 ieee802_11_parse_elems_crc(u8 *start, size_t len,
 			       struct ieee802_11_elems *elems,
 			       u64 filter, u32 crc);
-int ieee80211_set_freq(struct ieee80211_sub_if_data *sdata, int freq);
 u32 ieee80211_mandatory_rates(struct ieee80211_local *local,
 			      enum ieee80211_band band);
 
diff --git a/net/mac80211/mlme.c b/net/mac80211/mlme.c
index d779c57..aca22b0 100644
--- a/net/mac80211/mlme.c
+++ b/net/mac80211/mlme.c
@@ -1102,14 +1102,6 @@
 	struct sta_info *sta;
 	u32 changed = 0, config_changed = 0;
 
-	rcu_read_lock();
-
-	sta = sta_info_get(local, ifmgd->bssid);
-	if (!sta) {
-		rcu_read_unlock();
-		return;
-	}
-
 	if (deauth) {
 		ifmgd->direct_probe_tries = 0;
 		ifmgd->auth_tries = 0;
@@ -1120,7 +1112,11 @@
 	netif_tx_stop_all_queues(sdata->dev);
 	netif_carrier_off(sdata->dev);
 
-	ieee80211_sta_tear_down_BA_sessions(sta);
+	rcu_read_lock();
+	sta = sta_info_get(local, ifmgd->bssid);
+	if (sta)
+		ieee80211_sta_tear_down_BA_sessions(sta);
+	rcu_read_unlock();
 
 	bss = ieee80211_rx_bss_get(local, ifmgd->bssid,
 				   conf->channel->center_freq,
@@ -1156,8 +1152,6 @@
 				ifmgd->ssid, ifmgd->ssid_len);
 	}
 
-	rcu_read_unlock();
-
 	ieee80211_set_wmm_default(sdata);
 
 	ieee80211_recalc_idle(local);
@@ -2223,7 +2217,10 @@
 				       capa_mask, capa_val);
 
 	if (bss) {
-		ieee80211_set_freq(sdata, bss->cbss.channel->center_freq);
+		local->oper_channel = bss->cbss.channel;
+		local->oper_channel_type = NL80211_CHAN_NO_HT;
+		ieee80211_hw_config(local, 0);
+
 		if (!(ifmgd->flags & IEEE80211_STA_SSID_SET))
 			ieee80211_sta_set_ssid(sdata, bss->ssid,
 					       bss->ssid_len);
@@ -2445,6 +2442,14 @@
 			ieee80211_set_disassoc(sdata, true, true,
 					       WLAN_REASON_DEAUTH_LEAVING);
 
+		if (ifmgd->ssid_len == 0) {
+			/*
+			 * Only allow association to be started if a valid SSID
+			 * is configured.
+			 */
+			return;
+		}
+
 		if (!(ifmgd->flags & IEEE80211_STA_EXT_SME) ||
 		    ifmgd->state != IEEE80211_STA_MLME_ASSOCIATE)
 			set_bit(IEEE80211_STA_REQ_AUTH, &ifmgd->request);
@@ -2476,6 +2481,10 @@
 	ifmgd = &sdata->u.mgd;
 
 	if (ifmgd->ssid_len != len || memcmp(ifmgd->ssid, ssid, len) != 0) {
+		if (ifmgd->state == IEEE80211_STA_MLME_ASSOCIATED)
+			ieee80211_set_disassoc(sdata, true, true,
+					       WLAN_REASON_DEAUTH_LEAVING);
+
 		/*
 		 * Do not use reassociation if SSID is changed (different ESS).
 		 */
@@ -2500,6 +2509,11 @@
 {
 	struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
 
+	if (compare_ether_addr(bssid, ifmgd->bssid) != 0 &&
+	    ifmgd->state == IEEE80211_STA_MLME_ASSOCIATED)
+		ieee80211_set_disassoc(sdata, true, true,
+				       WLAN_REASON_DEAUTH_LEAVING);
+
 	if (is_valid_ether_addr(bssid)) {
 		memcpy(ifmgd->bssid, bssid, ETH_ALEN);
 		ifmgd->flags |= IEEE80211_STA_BSSID_SET;
diff --git a/net/mac80211/util.c b/net/mac80211/util.c
index 66ce96a..915e777 100644
--- a/net/mac80211/util.c
+++ b/net/mac80211/util.c
@@ -774,31 +774,6 @@
 	dev_queue_xmit(skb);
 }
 
-int ieee80211_set_freq(struct ieee80211_sub_if_data *sdata, int freqMHz)
-{
-	int ret = -EINVAL;
-	struct ieee80211_channel *chan;
-	struct ieee80211_local *local = sdata->local;
-
-	chan = ieee80211_get_channel(local->hw.wiphy, freqMHz);
-
-	if (chan && !(chan->flags & IEEE80211_CHAN_DISABLED)) {
-		if (sdata->vif.type == NL80211_IFTYPE_ADHOC &&
-		    chan->flags & IEEE80211_CHAN_NO_IBSS)
-			return ret;
-		local->oper_channel = chan;
-		local->oper_channel_type = NL80211_CHAN_NO_HT;
-
-		if (local->sw_scanning || local->hw_scanning)
-			ret = 0;
-		else
-			ret = ieee80211_hw_config(
-				local, IEEE80211_CONF_CHANGE_CHANNEL);
-	}
-
-	return ret;
-}
-
 u32 ieee80211_mandatory_rates(struct ieee80211_local *local,
 			      enum ieee80211_band band)
 {
diff --git a/net/mac80211/wext.c b/net/mac80211/wext.c
index d2d81b1..1da81f4 100644
--- a/net/mac80211/wext.c
+++ b/net/mac80211/wext.c
@@ -55,6 +55,8 @@
 				   struct iw_freq *freq, char *extra)
 {
 	struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev);
+	struct ieee80211_local *local = sdata->local;
+	struct ieee80211_channel *chan;
 
 	if (sdata->vif.type == NL80211_IFTYPE_ADHOC)
 		return cfg80211_ibss_wext_siwfreq(dev, info, freq, extra);
@@ -69,17 +71,38 @@
 					IEEE80211_STA_AUTO_CHANNEL_SEL;
 			return 0;
 		} else
-			return ieee80211_set_freq(sdata,
+			chan = ieee80211_get_channel(local->hw.wiphy,
 				ieee80211_channel_to_frequency(freq->m));
 	} else {
 		int i, div = 1000000;
 		for (i = 0; i < freq->e; i++)
 			div /= 10;
-		if (div > 0)
-			return ieee80211_set_freq(sdata, freq->m / div);
-		else
+		if (div <= 0)
 			return -EINVAL;
+		chan = ieee80211_get_channel(local->hw.wiphy, freq->m / div);
 	}
+
+	if (!chan)
+		return -EINVAL;
+
+	if (chan->flags & IEEE80211_CHAN_DISABLED)
+		return -EINVAL;
+
+	/*
+	 * no change except maybe auto -> fixed, ignore the HT
+	 * setting so you can fix a channel you're on already
+	 */
+	if (local->oper_channel == chan)
+		return 0;
+
+	if (sdata->vif.type == NL80211_IFTYPE_STATION)
+		ieee80211_sta_req_auth(sdata);
+
+	local->oper_channel = chan;
+	local->oper_channel_type = NL80211_CHAN_NO_HT;
+	ieee80211_hw_config(local, 0);
+
+	return 0;
 }
 
 
diff --git a/net/netlink/af_netlink.c b/net/netlink/af_netlink.c
index 8b6bbb3..2936fa3 100644
--- a/net/netlink/af_netlink.c
+++ b/net/netlink/af_netlink.c
@@ -1914,8 +1914,8 @@
 			   s->sk_protocol,
 			   nlk->pid,
 			   nlk->groups ? (u32)nlk->groups[0] : 0,
-			   atomic_read(&s->sk_rmem_alloc),
-			   atomic_read(&s->sk_wmem_alloc),
+			   sk_rmem_alloc_get(s),
+			   sk_wmem_alloc_get(s),
 			   nlk->cb,
 			   atomic_read(&s->sk_refcnt),
 			   atomic_read(&s->sk_drops)
diff --git a/net/netrom/af_netrom.c b/net/netrom/af_netrom.c
index 3be0e01..ce51ce0 100644
--- a/net/netrom/af_netrom.c
+++ b/net/netrom/af_netrom.c
@@ -286,8 +286,7 @@
 		kfree_skb(skb);
 	}
 
-	if (atomic_read(&sk->sk_wmem_alloc) ||
-	    atomic_read(&sk->sk_rmem_alloc)) {
+	if (sk_has_allocations(sk)) {
 		/* Defer: outstanding buffers */
 		sk->sk_timer.function = nr_destroy_timer;
 		sk->sk_timer.expires  = jiffies + 2 * HZ;
@@ -1206,7 +1205,7 @@
 		long amount;
 
 		lock_sock(sk);
-		amount = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc);
+		amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
 		if (amount < 0)
 			amount = 0;
 		release_sock(sk);
@@ -1342,8 +1341,8 @@
 			nr->n2count,
 			nr->n2,
 			nr->window,
-			atomic_read(&s->sk_wmem_alloc),
-			atomic_read(&s->sk_rmem_alloc),
+			sk_wmem_alloc_get(s),
+			sk_rmem_alloc_get(s),
 			s->sk_socket ? SOCK_INODE(s->sk_socket)->i_ino : 0L);
 
 		bh_unlock_sock(s);
diff --git a/net/packet/af_packet.c b/net/packet/af_packet.c
index 4f76e55..ebe5718 100644
--- a/net/packet/af_packet.c
+++ b/net/packet/af_packet.c
@@ -1987,7 +1987,8 @@
 	switch (cmd) {
 		case SIOCOUTQ:
 		{
-			int amount = atomic_read(&sk->sk_wmem_alloc);
+			int amount = sk_wmem_alloc_get(sk);
+
 			return put_user(amount, (int __user *)arg);
 		}
 		case SIOCINQ:
diff --git a/net/rose/af_rose.c b/net/rose/af_rose.c
index 877a7f6..6bd8e938 100644
--- a/net/rose/af_rose.c
+++ b/net/rose/af_rose.c
@@ -356,8 +356,7 @@
 		kfree_skb(skb);
 	}
 
-	if (atomic_read(&sk->sk_wmem_alloc) ||
-	    atomic_read(&sk->sk_rmem_alloc)) {
+	if (sk_has_allocations(sk)) {
 		/* Defer: outstanding buffers */
 		setup_timer(&sk->sk_timer, rose_destroy_timer,
 				(unsigned long)sk);
@@ -1310,7 +1309,8 @@
 	switch (cmd) {
 	case TIOCOUTQ: {
 		long amount;
-		amount = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc);
+
+		amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
 		if (amount < 0)
 			amount = 0;
 		return put_user(amount, (unsigned int __user *) argp);
@@ -1481,8 +1481,8 @@
 			rose->hb / HZ,
 			ax25_display_timer(&rose->idletimer) / (60 * HZ),
 			rose->idle / (60 * HZ),
-			atomic_read(&s->sk_wmem_alloc),
-			atomic_read(&s->sk_rmem_alloc),
+			sk_wmem_alloc_get(s),
+			sk_rmem_alloc_get(s),
 			s->sk_socket ? SOCK_INODE(s->sk_socket)->i_ino : 0L);
 	}
 
diff --git a/net/sched/act_police.c b/net/sched/act_police.c
index f8f047b6..723964c 100644
--- a/net/sched/act_police.c
+++ b/net/sched/act_police.c
@@ -294,6 +294,8 @@
 	if (police->tcfp_ewma_rate &&
 	    police->tcf_rate_est.bps >= police->tcfp_ewma_rate) {
 		police->tcf_qstats.overlimits++;
+		if (police->tcf_action == TC_ACT_SHOT)
+			police->tcf_qstats.drops++;
 		spin_unlock(&police->tcf_lock);
 		return police->tcf_action;
 	}
@@ -327,6 +329,8 @@
 	}
 
 	police->tcf_qstats.overlimits++;
+	if (police->tcf_action == TC_ACT_SHOT)
+		police->tcf_qstats.drops++;
 	spin_unlock(&police->tcf_lock);
 	return police->tcf_action;
 }
diff --git a/net/sched/em_meta.c b/net/sched/em_meta.c
index 266151a..18d85d2 100644
--- a/net/sched/em_meta.c
+++ b/net/sched/em_meta.c
@@ -349,13 +349,13 @@
 META_COLLECTOR(int_sk_rmem_alloc)
 {
 	SKIP_NONLOCAL(skb);
-	dst->value = atomic_read(&skb->sk->sk_rmem_alloc);
+	dst->value = sk_rmem_alloc_get(skb->sk);
 }
 
 META_COLLECTOR(int_sk_wmem_alloc)
 {
 	SKIP_NONLOCAL(skb);
-	dst->value = atomic_read(&skb->sk->sk_wmem_alloc);
+	dst->value = sk_wmem_alloc_get(skb->sk);
 }
 
 META_COLLECTOR(int_sk_omem_alloc)
diff --git a/net/sctp/socket.c b/net/sctp/socket.c
index 0f01e5d..35ba035 100644
--- a/net/sctp/socket.c
+++ b/net/sctp/socket.c
@@ -130,7 +130,7 @@
 	if (asoc->ep->sndbuf_policy)
 		amt = asoc->sndbuf_used;
 	else
-		amt = atomic_read(&asoc->base.sk->sk_wmem_alloc);
+		amt = sk_wmem_alloc_get(asoc->base.sk);
 
 	if (amt >= asoc->base.sk->sk_sndbuf) {
 		if (asoc->base.sk->sk_userlocks & SOCK_SNDBUF_LOCK)
@@ -6523,7 +6523,7 @@
 {
 	int amt = 0;
 
-	amt = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc);
+	amt = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
 	if (amt < 0)
 		amt = 0;
 	return amt;
diff --git a/net/unix/af_unix.c b/net/unix/af_unix.c
index 9dcc6e7..36d4e44 100644
--- a/net/unix/af_unix.c
+++ b/net/unix/af_unix.c
@@ -1946,7 +1946,7 @@
 
 	switch (cmd) {
 	case SIOCOUTQ:
-		amount = atomic_read(&sk->sk_wmem_alloc);
+		amount = sk_wmem_alloc_get(sk);
 		err = put_user(amount, (int __user *)arg);
 		break;
 	case SIOCINQ:
diff --git a/net/x25/af_x25.c b/net/x25/af_x25.c
index ed80af8..21cdc87 100644
--- a/net/x25/af_x25.c
+++ b/net/x25/af_x25.c
@@ -332,14 +332,14 @@
 /*
  *	Deferred destroy.
  */
-void x25_destroy_socket(struct sock *);
+static void __x25_destroy_socket(struct sock *);
 
 /*
  *	handler for deferred kills.
  */
 static void x25_destroy_timer(unsigned long data)
 {
-	x25_destroy_socket((struct sock *)data);
+	x25_destroy_socket_from_timer((struct sock *)data);
 }
 
 /*
@@ -349,12 +349,10 @@
  *	will touch it and we are (fairly 8-) ) safe.
  *	Not static as it's used by the timer
  */
-void x25_destroy_socket(struct sock *sk)
+static void __x25_destroy_socket(struct sock *sk)
 {
 	struct sk_buff *skb;
 
-	sock_hold(sk);
-	lock_sock(sk);
 	x25_stop_heartbeat(sk);
 	x25_stop_timer(sk);
 
@@ -374,8 +372,7 @@
 		kfree_skb(skb);
 	}
 
-	if (atomic_read(&sk->sk_wmem_alloc) ||
-	    atomic_read(&sk->sk_rmem_alloc)) {
+	if (sk_has_allocations(sk)) {
 		/* Defer: outstanding buffers */
 		sk->sk_timer.expires  = jiffies + 10 * HZ;
 		sk->sk_timer.function = x25_destroy_timer;
@@ -385,7 +382,22 @@
 		/* drop last reference so sock_put will free */
 		__sock_put(sk);
 	}
+}
 
+void x25_destroy_socket_from_timer(struct sock *sk)
+{
+	sock_hold(sk);
+	bh_lock_sock(sk);
+	__x25_destroy_socket(sk);
+	bh_unlock_sock(sk);
+	sock_put(sk);
+}
+
+static void x25_destroy_socket(struct sock *sk)
+{
+	sock_hold(sk);
+	lock_sock(sk);
+	__x25_destroy_socket(sk);
 	release_sock(sk);
 	sock_put(sk);
 }
@@ -1259,8 +1271,8 @@
 
 	switch (cmd) {
 		case TIOCOUTQ: {
-			int amount = sk->sk_sndbuf -
-				     atomic_read(&sk->sk_wmem_alloc);
+			int amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
+
 			if (amount < 0)
 				amount = 0;
 			rc = put_user(amount, (unsigned int __user *)argp);
diff --git a/net/x25/x25_proc.c b/net/x25/x25_proc.c
index 1afa44d..0a04e62 100644
--- a/net/x25/x25_proc.c
+++ b/net/x25/x25_proc.c
@@ -163,8 +163,8 @@
 		   devname, x25->lci & 0x0FFF, x25->state, x25->vs, x25->vr,
 		   x25->va, x25_display_timer(s) / HZ, x25->t2  / HZ,
 		   x25->t21 / HZ, x25->t22 / HZ, x25->t23 / HZ,
-		   atomic_read(&s->sk_wmem_alloc),
-		   atomic_read(&s->sk_rmem_alloc),
+		   sk_wmem_alloc_get(s),
+		   sk_rmem_alloc_get(s),
 		   s->sk_socket ? SOCK_INODE(s->sk_socket)->i_ino : 0L);
 out:
 	return 0;
diff --git a/net/x25/x25_timer.c b/net/x25/x25_timer.c
index d3e3e54..5c5db1a 100644
--- a/net/x25/x25_timer.c
+++ b/net/x25/x25_timer.c
@@ -113,7 +113,7 @@
 			    (sk->sk_state == TCP_LISTEN &&
 			     sock_flag(sk, SOCK_DEAD))) {
 				bh_unlock_sock(sk);
-				x25_destroy_socket(sk);
+				x25_destroy_socket_from_timer(sk);
 				return;
 			}
 			break;
diff --git a/samples/trace_events/Makefile b/samples/trace_events/Makefile
index 0d428dc..0f8d921 100644
--- a/samples/trace_events/Makefile
+++ b/samples/trace_events/Makefile
@@ -1,6 +1,14 @@
 # builds the trace events example kernel modules;
 # then to use one (as root):  insmod <module_name.ko>
 
+# If you include a trace header outside of include/trace/events
+# then the file that does the #define CREATE_TRACE_POINTS must
+# have that tracer file in its main search path. This is because
+# define_trace.h will include it, and must be able to find it from
+# the include/trace directory.
+#
+# Here trace-events-sample.c does the CREATE_TRACE_POINTS.
+#
 CFLAGS_trace-events-sample.o := -I$(src)
 
 obj-$(CONFIG_SAMPLE_TRACE_EVENTS) += trace-events-sample.o
diff --git a/samples/trace_events/trace-events-sample.h b/samples/trace_events/trace-events-sample.h
index 128a897..9977a75 100644
--- a/samples/trace_events/trace-events-sample.h
+++ b/samples/trace_events/trace-events-sample.h
@@ -19,16 +19,21 @@
  * If TRACE_SYSTEM is defined, that will be the directory created
  * in the ftrace directory under /debugfs/tracing/events/<system>
  *
- * The define_trace.h belowe will also look for a file name of
+ * The define_trace.h below will also look for a file name of
  * TRACE_SYSTEM.h where TRACE_SYSTEM is what is defined here.
+ * In this case, it would look for sample.h
  *
- * If you want a different system than file name, you can override
- * the header name by defining TRACE_INCLUDE_FILE
+ * If the header name will be different than the system name
+ * (as in this case), then you can override the header name that
+ * define_trace.h will look up by defining TRACE_INCLUDE_FILE
  *
- * If this file was called, goofy.h, then we would define:
+ * This file is called trace-events-sample.h but we want the system
+ * to be called "sample". Therefore we must define the name of this
+ * file:
  *
- * #define TRACE_INCLUDE_FILE goofy
+ * #define TRACE_INCLUDE_FILE trace-events-sample
  *
+ * As we do an the bottom of this file.
  */
 #undef TRACE_SYSTEM
 #define TRACE_SYSTEM sample
@@ -99,13 +104,13 @@
  *
  * #define TRACE_INCLUDE_PATH ../../samples/trace_events
  *
- * But I chose to simply make it use the current directory and then in
- * the Makefile I added:
+ * But the safest and easiest way to simply make it use the directory
+ * that the file is in is to add in the Makefile:
  *
- * CFLAGS_trace-events-sample.o := -I$(PWD)/samples/trace_events/
+ * CFLAGS_trace-events-sample.o := -I$(src)
  *
  * This will make sure the current path is part of the include
- * structure for our file so that we can find it.
+ * structure for our file so that define_trace.h can find it.
  *
  * I could have made only the top level directory the include:
  *
@@ -115,8 +120,8 @@
  *
  * #define TRACE_INCLUDE_PATH samples/trace_events
  *
- * But then if something defines "samples" or "trace_events" then we
- * could risk that being converted too, and give us an unexpected
+ * But then if something defines "samples" or "trace_events" as a macro
+ * then we could risk that being converted too, and give us an unexpected
  * result.
  */
 #undef TRACE_INCLUDE_PATH
diff --git a/scripts/Makefile.lib b/scripts/Makefile.lib
index 2b70661..7a77787 100644
--- a/scripts/Makefile.lib
+++ b/scripts/Makefile.lib
@@ -116,6 +116,17 @@
                  $(asflags-y) $(AFLAGS_$(basetarget).o)
 _cpp_flags     = $(KBUILD_CPPFLAGS) $(cppflags-y) $(CPPFLAGS_$(@F))
 
+#
+# Enable gcov profiling flags for a file, directory or for all files depending
+# on variables GCOV_PROFILE_obj.o, GCOV_PROFILE and CONFIG_GCOV_PROFILE_ALL
+# (in this order)
+#
+ifeq ($(CONFIG_GCOV_KERNEL),y)
+_c_flags += $(if $(patsubst n%,, \
+		$(GCOV_PROFILE_$(basetarget).o)$(GCOV_PROFILE)$(CONFIG_GCOV_PROFILE_ALL)), \
+		$(CFLAGS_GCOV))
+endif
+
 # If building the kernel in a separate objtree expand all occurrences
 # of -Idir to -I$(srctree)/dir except for absolute paths (starting with '/').
 
diff --git a/scripts/basic/docproc.c b/scripts/basic/docproc.c
index 4c9523e..99ca7a6 100644
--- a/scripts/basic/docproc.c
+++ b/scripts/basic/docproc.c
@@ -385,7 +385,7 @@
 	if (!srctree)
 		srctree = getcwd(NULL, 0);
 	kernsrctree = getenv("KBUILD_SRC");
-	if (!kernsrctree)
+	if (!kernsrctree || !*kernsrctree)
 		kernsrctree = srctree;
 	if (argc != 3) {
 		usage();
diff --git a/scripts/kallsyms.c b/scripts/kallsyms.c
index 3cb5789..64343cc 100644
--- a/scripts/kallsyms.c
+++ b/scripts/kallsyms.c
@@ -167,11 +167,11 @@
 	for (i = 0; i < ARRAY_SIZE(text_ranges); ++i) {
 		tr = &text_ranges[i];
 
-		if (s->addr >= tr->start && s->addr < tr->end)
-			return 0;
+		if (s->addr >= tr->start && s->addr <= tr->end)
+			return 1;
 	}
 
-	return 1;
+	return 0;
 }
 
 static int symbol_valid(struct sym_entry *s)
diff --git a/scripts/kernel-doc b/scripts/kernel-doc
index a193fa3..ed591e9 100755
--- a/scripts/kernel-doc
+++ b/scripts/kernel-doc
@@ -1468,6 +1468,8 @@
 	    }
 
 	}
+	# strip kmemcheck_bitfield_{begin,end}.*;
+	$members =~ s/kmemcheck_bitfield_.*?;//gos;
 
 	output_declaration($declaration_name,
 			   'enum',
@@ -1651,6 +1653,15 @@
 	}
 	}
 
+	# strip spaces from $param so that it is one continous string
+	# on @parameterlist;
+	# this fixes a problem where check_sections() cannot find
+	# a parameter like "addr[6 + 2]" because it actually appears
+	# as "addr[6", "+", "2]" on the parameter list;
+	# but it's better to maintain the param string unchanged for output,
+	# so just weaken the string compare in check_sections() to ignore
+	# "[blah" in a parameter string;
+	###$param =~ s/\s*//g;
 	push @parameterlist, $param;
 	$parametertypes{$param} = $type;
 }
@@ -1669,6 +1680,14 @@
 			$prm_clean = $prms[$px];
 			$prm_clean =~ s/\[.*\]//;
 			$prm_clean =~ s/__attribute__\s*\(\([a-z,_\*\s\(\)]*\)\)//;
+			# ignore array size in a parameter string;
+			# however, the original param string may contain
+			# spaces, e.g.:  addr[6 + 2]
+			# and this appears in @prms as "addr[6" since the
+			# parameter list is split at spaces;
+			# hence just ignore "[..." for the sections check;
+			$prm_clean =~ s/\[.*//;
+
 			##$prm_clean =~ s/^\**//;
 			if ($prm_clean eq $sects[$sx]) {
 				$err = 0;
diff --git a/security/device_cgroup.c b/security/device_cgroup.c
index 5fda7df..b8186ba 100644
--- a/security/device_cgroup.c
+++ b/security/device_cgroup.c
@@ -490,7 +490,7 @@
 
 	list_for_each_entry_rcu(wh, &dev_cgroup->whitelist, list) {
 		if (wh->type & DEV_ALL)
-			goto acc_check;
+			goto found;
 		if ((wh->type & DEV_BLOCK) && !S_ISBLK(inode->i_mode))
 			continue;
 		if ((wh->type & DEV_CHAR) && !S_ISCHR(inode->i_mode))
@@ -499,11 +499,12 @@
 			continue;
 		if (wh->minor != ~0 && wh->minor != iminor(inode))
 			continue;
-acc_check:
+
 		if ((mask & MAY_WRITE) && !(wh->access & ACC_WRITE))
 			continue;
 		if ((mask & MAY_READ) && !(wh->access & ACC_READ))
 			continue;
+found:
 		rcu_read_unlock();
 		return 0;
 	}
@@ -527,7 +528,7 @@
 
 	list_for_each_entry_rcu(wh, &dev_cgroup->whitelist, list) {
 		if (wh->type & DEV_ALL)
-			goto acc_check;
+			goto found;
 		if ((wh->type & DEV_BLOCK) && !S_ISBLK(mode))
 			continue;
 		if ((wh->type & DEV_CHAR) && !S_ISCHR(mode))
@@ -536,9 +537,10 @@
 			continue;
 		if (wh->minor != ~0 && wh->minor != MINOR(dev))
 			continue;
-acc_check:
+
 		if (!(wh->access & ACC_MKNOD))
 			continue;
+found:
 		rcu_read_unlock();
 		return 0;
 	}
diff --git a/sound/pci/lx6464es/lx6464es.c b/sound/pci/lx6464es/lx6464es.c
index ccf1b38..18da2ef 100644
--- a/sound/pci/lx6464es/lx6464es.c
+++ b/sound/pci/lx6464es/lx6464es.c
@@ -988,7 +988,7 @@
 	pci_set_master(pci);
 
 	/* check if we can restrict PCI DMA transfers to 32 bits */
-	err = pci_set_dma_mask(pci, DMA_32BIT_MASK);
+	err = pci_set_dma_mask(pci, DMA_BIT_MASK(32));
 	if (err < 0) {
 		snd_printk(KERN_ERR "architecture does not support "
 			   "32bit PCI busmaster DMA\n");